From 04555e4230ae76447a426e62ba7800ef53df2584 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:19:58 +1300 Subject: [PATCH 001/129] Preserve near-front Account Game Design and World owner foundations --- .github/workflows/ci.yml | 52 +- dev-tools/README.md | 2 +- .../tests/gradle-proof-tooling-contract.sh | 152 + dev-tools/validation/inspect-test-results.sh | 207 +- .../v1/account_gameplay_admission_lease.proto | 160 + .../v1/account_issuer_authority_source.proto | 37 + .../v1/draft_terminal_service.proto | 38 + .../v1/draft_visibility_service.proto | 52 + .../game-design/v1/game_design_service.proto | 157 + .../v1/tenant_identity_service.proto | 27 + .../v1/game_session_service.proto | 112 + .../v1/draft_terminal_service.proto | 38 + ...rld_canonical_initial_admission_hold.proto | 45 + ...ical_initial_admission_hold_terminal.proto | 32 + .../world_canonical_instance_activation.proto | 31 + ...ld_canonical_instance_lifecycle_read.proto | 22 + ...orld_canonical_player_admission_hold.proto | 45 + .../v1/world_canonical_player_location.proto | 69 + .../v1/world_management_service.proto | 111 + .../world_published_spawn_requirements.proto | 67 + .../world_published_start_location_read.proto | 60 + services/account-service/build.gradle.kts | 6 + ...untDraftTerminalReconciliationService.java | 199 + .../DraftAuthorizationFenceRepository.java | 765 ++ .../config/AccountJwtJwksApiBinding.java | 1260 ++++ .../AccountJwtReadinessTrustBinding.java | 480 ++ ...ountJwtSignerMaterializerTrustBinding.java | 404 + .../AccountJwtValidatorInventoryBinding.java | 678 ++ .../dto/AccountAuthEvidenceBundle.java | 808 ++ ...ntGameplayAdmissionCommitConfirmation.java | 116 + ...ccountGameplayAdmissionLeaseOperation.java | 47 + ...ntGameplayAdmissionOriginalAckReceipt.java | 97 + ...tGameplayAdmissionProvisionalDecision.java | 27 + ...GameplayPublicAdmissionSourceSnapshot.java | 25 + .../AccountGameplayTokenIdentityFence.java | 80 + .../dto/AccountLogoutRequestDigest.java | 116 + .../AccountMembershipRoleSourceSnapshot.java | 68 + ...AccountPlatformRestrictionBirthSource.java | 197 + .../AccountSecurityStateMutationRequest.java | 173 + .../AccountSecurityStateRequestDigest.java | 51 + .../DemoTenantEntitlementEventV1Codec.java | 435 ++ .../dto/DemoTenantEntitlementRequest.java | 121 + .../dto/DemoTenantEntitlementSnapshot.java | 92 + .../dto/TenantAuthorityEventV1Codec.java | 427 ++ .../AccountAuthEvidenceBundleRepository.java | 684 ++ ...ountAuthoritySourceEvidenceRepository.java | 561 +- ...ccountDemoTenantEntitlementRepository.java | 546 ++ .../AccountGameplayAdmissionAbortOwner.java | 119 + ...eplayAdmissionCommitConfirmationOwner.java | 127 + ...AdmissionCommitConfirmationRepository.java | 136 + ...countGameplayAdmissionLeaseRepository.java | 320 + ...ssionOriginalAckReceiptCommitExecutor.java | 187 + ...AdmissionOriginalAckReceiptRepository.java | 172 + ...meplayAdmissionOriginalCommitExecutor.java | 255 + .../AccountGameplayAdmissionReadOwner.java | 99 + ...ameplayAdmissionReceiptCommitExecutor.java | 155 + ...countGameplayCredentialRequestBinding.java | 29 + ...tGameplayDelegationIssuanceRepository.java | 2538 +++++++ ...ountGameplayDelegationPendingIdentity.java | 38 + ...yDelegationResponseEnvelopeRepository.java | 1384 ++++ ...tGameplayTokenIdentityFenceRepository.java | 247 + .../AccountIssuerSourceSnapshotReadOwner.java | 159 + .../AccountJwtJwksPublicationRepository.java | 1315 ++++ .../AccountJwtReadinessProbeRepository.java | 2701 +++++++ ...ccountJwtSignerDesiredStateRepository.java | 4075 ++++++++++ ...ccountJwtValidatorInventoryRepository.java | 279 + .../AccountLifecyclePendingDenialReader.java | 155 + .../AccountLogoutAllOperationRepository.java | 321 + ...countPasswordResetOperationRepository.java | 316 + ...untPlatformRestrictionBirthRepository.java | 325 + .../repository/AccountRepository.java | 10 + ...countSecurityStateOperationRepository.java | 693 ++ ...AccountTenantAuthorityEventRepository.java | 580 ++ ...ountTenantEntitlementOutboxRepository.java | 211 + .../AccountAuthoritySourceEventReadback.java | 714 ++ .../service/AccountAuthoritySourceReader.java | 237 + ...ntGameplayPublicAdmissionSourceReader.java | 258 + .../service/AccountGenerationProjection.java | 355 + ...ountGenerationProjectionRedisContract.java | 99 + ...tionProjectionRedisScriptContribution.java | 36 + .../AccountMembershipRoleSourceReader.java | 288 + .../AccountRedisScriptDescriptorLoader.java | 107 + .../DemoTenantEntitlementException.java | 31 + .../service/IssuerGenerationProjection.java | 272 + ...ountGameplayAdmissionLeaseGrpcService.java | 144 + ...countIssuerAuthoritySourceGrpcService.java | 86 + ...layAdmissionInitialTokenAuthenticator.java | 269 + ...ameplayAuthenticatedPublicSourceOwner.java | 185 + ...GameplayDelegationAuthorityProjection.java | 772 ++ ...eplayDelegationCommittedIssuanceOwner.java | 455 ++ ...meplayDelegationIssuanceCommitService.java | 436 ++ .../AccountGameplayDelegationRedisClient.java | 1434 ++++ ...playDelegationRedisScriptContribution.java | 60 + ...playDelegationResponseEnvelopeService.java | 50 + .../AccountGameplayDelegationSigner.java | 1556 ++++ ...ccountGameplayDelegationTokenRegistry.java | 236 + .../AccountJwtJwksConfigMapClient.java | 704 ++ .../session/AccountJwtJwksTrustedSource.java | 761 ++ .../AccountJwtValidatorInventorySource.java | 1117 +++ .../AccountMountedJwtSignerBundle.java | 1269 ++++ .../AccountResponseEnvelopeCryptography.java | 403 + .../AccountResponseEnvelopeKeyring.java | 291 + ...ntSelectedGameplayAuthorityProjection.java | 226 + ...on.redis.contracts.RedisScriptContribution | 2 + .../V41__account_jwt_signer_desired_state.sql | 404 + ...nt_jwt_signer_materialization_readback.sql | 326 + .../V43__account_jwt_jwks_prepublication.sql | 599 ++ ...__account_gameplay_delegation_issuance.sql | 273 + .../V45__account_jwt_readiness_probes.sql | 466 ++ .../V46__account_auth_evidence_bundles.sql | 374 + ...gameplay_delegation_encrypted_response.sql | 124 + ...account_jwt_signer_promotion_lifecycle.sql | 569 ++ ...t_jwt_readiness_single_delivery_claims.sql | 125 + ...gameplay_delegation_committed_issuance.sql | 352 + ...ount_jwt_validator_inventory_snapshots.sql | 67 + ...3__account_protected_demo_entitlements.sql | 427 ++ ...account_tenant_authority_source_bridge.sql | 482 ++ .../V74.1__account_global_role_source.sql | 158 + ...account_gameplay_token_identity_fences.sql | 85 + ...ount_password_reset_operation_receipts.sql | 91 + ...V76__draft_commit_authorization_fences.sql | 188 + ..._account_logout_all_operation_receipts.sql | 90 + ...V78__account_security_state_operations.sql | 401 + ...eplay_login_credential_request_binding.sql | 87 + ...3__account_security_event_source_guard.sql | 398 + ...unt_auth_evidence_checkpoint_key_count.sql | 231 + ...ount_auth_evidence_shared_issuer_guard.sql | 232 + ...nt_gameplay_commit_bundle_source_fence.sql | 309 + ...gameplay_authority_shared_issuer_guard.sql | 135 + ...lay_delegation_decimal_source_versions.sql | 133 + ...__account_lifecycle_serving_operations.sql | 191 + ...nt_gameplay_admission_lease_operations.sql | 113 + ...unt_platform_restriction_birth_sources.sql | 261 + ...count_admission_unknown_decision_abort.sql | 31 + ..._admission_durable_commit_confirmation.sql | 404 + ...ccount_global_pending_admission_fences.sql | 89 + ...account_admission_original_ack_receipt.sql | 259 + ...93__account_draft_required_owner_fence.sql | 371 + .../account_generation_projection_cas.lua | 54 + ...-session-delegation-activate-committed.lua | 62 + ...e-session-delegation-authority-project.lua | 127 + ...me-session-delegation-pending-register.lua | 39 + ...session-delegation-activate-committed.json | 75 + ...n-delegation-authority-project-issuer.json | 69 + ...e-session-delegation-pending-register.json | 67 + .../account-generation-projection-cas.json | 65 + ...cted-membership-generation-projection.json | 65 + ...selected-tenant-generation-projection.json | 65 + ...orizationFencePostgresIntegrationTest.java | 1932 +++++ ...issionLeasePersistenceIntegrationTest.java | 2638 +++++++ ...ceSnapshotReadPostgresIntegrationTest.java | 484 ++ .../AccountPostgresIntegrationFixture.java | 65 +- .../PreRestrictionBirthAccountFixture.java | 182 + ...raftTerminalReconciliationServiceTest.java | 817 ++ ...ccountGameplayAdmissionAbortOwnerTest.java | 304 + ...yAdmissionCommitConfirmationOwnerTest.java | 239 + ...ssionCommitConfirmationRepositoryTest.java | 290 + ...tGameplayAdmissionLeaseRepositoryTest.java | 312 + ...nOriginalAckReceiptCommitExecutorTest.java | 489 ++ ...ssionOriginalAckReceiptRepositoryTest.java | 521 ++ ...ayAdmissionOriginalCommitExecutorTest.java | 412 + ...AccountGameplayAdmissionReadOwnerTest.java | 203 + ...layAdmissionReceiptCommitExecutorTest.java | 384 + ...ountIssuerSourceSnapshotReadOwnerTest.java | 342 + ...meplayPublicAdmissionSourceReaderTest.java | 666 ++ ...ccountRedisScriptDescriptorLoaderTest.java | 78 + ...GameplayAdmissionLeaseGrpcServiceTest.java | 396 + ...tIssuerAuthoritySourceGrpcServiceTest.java | 111 + ...dmissionInitialTokenAuthenticatorTest.java | 509 ++ ...layAuthenticatedPublicSourceOwnerTest.java | 343 + ...lectedGameplayAuthorityProjectionTest.java | 217 + ...meplayCredentialRequestBindingFixture.java | 11 + .../common-platform-core/build.gradle.kts | 1 + .../AccountIssuerAuthoritySourceClient.java | 224 + .../AccountIssuerSourceSnapshotEvidence.java | 166 + .../AccountIssuerSourceSnapshotGrpcCodec.java | 250 + ...AccountLogoutAllAuthorityEventV1Codec.java | 355 + ...untSecurityStateAuthorityEventV1Codec.java | 391 + .../PasswordResetAuthorityEventV1Codec.java | 372 + .../DraftAuthorizationFenceBinding.java | 662 ++ .../common/authoring/DraftCommitBinding.java | 454 ++ .../GameDesignDraftTerminalReadClient.java | 151 + .../GameDesignDraftTerminalReadEvidence.java | 105 + .../GameDesignDraftTerminalReadGrpcCodec.java | 169 + .../WorldDraftTerminalReadClient.java | 150 + .../WorldDraftTerminalReadEvidence.java | 99 + .../WorldDraftTerminalReadGrpcCodec.java | 736 ++ .../AuthoredWorldLaunchDescriptorClient.java | 201 + ...AuthoredWorldLaunchDescriptorEvidence.java | 568 ++ ...uthoredWorldLaunchDescriptorGrpcCodec.java | 444 ++ ...thoredWorldReleaseAttestationEvidence.java | 732 ++ .../AuthoredWorldVersionStateClient.java | 157 + .../AuthoredWorldVersionStateEvidence.java | 218 + .../AuthoredWorldVersionStateGrpcCodec.java | 191 + .../CompleteLaunchBindingEvidence.java | 14 + .../DraftSynchronizedVisibilityClient.java | 150 + .../DraftSynchronizedVisibilityEvidence.java | 359 + .../DraftSynchronizedVisibilityGrpcCodec.java | 182 + ...GameDesignPublicationTerminalEvidence.java | 517 ++ ...alGameInstanceLaunchAssociationClient.java | 155 + ...InstanceLaunchAssociationReadEvidence.java | 120 + ...nstanceLaunchAssociationReadGrpcCodec.java | 188 + ...GrpcServerPeerIdentityCallCredentials.java | 41 + ...ccountPublicationAuthorizationBinding.java | 150 + .../AuthoredDraftPublishSelectionBinding.java | 359 + ...GameDesignPublicationOperationBinding.java | 67 + .../common/publication/RealmEntryPolicy.java | 176 + .../tenant/AuthoredWorldSourceClient.java | 158 + .../tenant/AuthoredWorldSourceDigest.java | 147 + .../tenant/AuthoredWorldSourceEvidence.java | 63 + .../tenant/AuthoredWorldSourceGrpcCodec.java | 115 + .../WorldAuthoredSourceIntakeClient.java | 178 + .../WorldAuthoredSourceIntakeGrpcCodec.java | 307 + ...nonicalWorldInstancePreparationClient.java | 185 + ...icalWorldInstancePreparationGrpcCodec.java | 167 + ...onCanonicalInitialAdmissionOwnerProof.java | 66 + ...onicalInitialAdmissionOwnerProofCodec.java | 114 + .../firemud/common/world/RoomTemplateRef.java | 22 + .../WorldCanonicalInitialAdmissionHold.java | 391 + .../WorldCanonicalInitialPlayerLocation.java | 550 ++ .../WorldCanonicalInstanceActivation.java | 251 + ...WorldCanonicalInstanceLifecycleClient.java | 156 + ...rldCanonicalInstanceLifecycleEvidence.java | 555 ++ ...ldCanonicalInstanceLifecycleGrpcCodec.java | 69 + .../WorldDraftStartLocationEvidence.java | 286 + ...WorldPublishedSpawnRequirementsClient.java | 182 + ...rldPublishedSpawnRequirementsEvidence.java | 341 + ...ldPublishedSpawnRequirementsGrpcCodec.java | 322 + .../WorldPublishedStartLocationClient.java | 151 + .../WorldPublishedStartLocationEvidence.java | 556 ++ .../WorldPublishedStartLocationGrpcCodec.java | 216 + ...ntIssuerAuthoritySourceClientMtlsTest.java | 489 ++ ...ccountIssuerAuthoritySourceClientTest.java | 204 + ...countIssuerSourceSnapshotEvidenceTest.java | 211 + ...ountIssuerSourceSnapshotGrpcCodecTest.java | 273 + ...aftAuthorizationFenceBindingCodecTest.java | 699 ++ ...GameDesignDraftTerminalReadClientTest.java | 181 + .../WorldDraftTerminalReadClientTest.java | 227 + .../WorldDraftTerminalReadGrpcCodecTest.java | 891 +++ ...thoredWorldLaunchDescriptorClientTest.java | 195 + ...edWorldReleaseAttestationSelectorTest.java | 290 + .../AuthoredWorldVersionStateClientTest.java | 138 + ...DraftSynchronizedVisibilityClientTest.java | 106 + ...aftSynchronizedVisibilityEvidenceTest.java | 168 + ...ftSynchronizedVisibilityGrpcCodecTest.java | 247 + ...onicalInstanceLifecycleClientMtlsTest.java | 587 ++ .../WorldAuthoredSourceIntakeClientTest.java | 296 + ...orldInstancePreparationClientMtlsTest.java | 706 ++ ...WorldInstancePreparationGrpcCodecTest.java | 362 + ...rldCanonicalInitialPlayerLocationTest.java | 485 ++ ...anonicalInstanceLifecycleEvidenceTest.java | 859 +++ ...lishedSpawnRequirementsClientMtlsTest.java | 493 ++ ...dPublishedSpawnRequirementsClientTest.java | 38 + ...ublishedSpawnRequirementsEvidenceTest.java | 90 + ...blishedSpawnRequirementsGrpcCodecTest.java | 443 ++ ...WorldPublishedStartLocationClientTest.java | 155 + ...ldPublishedStartLocationGrpcCodecTest.java | 179 + .../common-redis-contracts/build.gradle.kts | 9 + .../redis/contracts/RedisScriptCatalog.java | 80 + .../contracts/RedisScriptContribution.java | 11 + .../contracts/RedisScriptDescriptor.java | 264 + ...ccountGameplayAdmissionLeaseWireCodec.java | 119 + .../ControlUiJwtProfileValidator.java | 101 + ...essionAccountDelegationRegistryRecord.java | 890 +++ .../firemud/common/security/JwtClaims.java | 27 + .../PlayerBootstrapJwtProfileValidator.java | 38 + .../common/security/SessionContext.java | 13 + ...dCanonicalPlayerAdmissionHoldEvidence.java | 312 + ...onicalPlayerAdmissionHoldEvidenceTest.java | 808 ++ services/game-design-service/build.gradle.kts | 15 + .../draft/AuthoredDraftPublishSelection.java | 146 + ...thoredDraftPublishSelectionRepository.java | 272 + .../DraftCommitCoordinatorRepository.java | 1679 +++++ .../GameDesignDraftTerminalOperation.java | 86 + .../draft/GameDesignDraftTerminalOutcome.java | 177 + ...eDesignDraftTerminalOutcomeRepository.java | 637 ++ ...ameDesignDraftTerminalReadGrpcService.java | 126 + .../dto/CompleteLaunchBindingDto.java | 15 + .../dto/PublishParticipantDigestDto.java | 23 + .../dto/PublishedReleaseBundleDto.java | 152 +- .../dto/ResolvedLaunchDescriptorDto.java | 34 +- .../gamedesign/entity/LaunchDescriptor.java | 16 + .../entity/PublishedReleaseBundle.java | 7 + .../firemud/gamedesign/entity/Version.java | 6 + .../entity/VersionAssetArtifact.java | 4 + .../publication/CommandApplication.java | 97 + .../publication/CommandSnapshot.java | 134 + .../gamedesign/publication/CommandSource.java | 645 ++ .../publication/CommandSourceRepository.java | 809 ++ .../GameDesignPublicationOperation.java | 42 + ...eDesignPublicationOperationRepository.java | 254 + .../GameDesignSourceRepository.java | 301 + .../PublicationReleaseContent.java | 65 + .../publication/RealmPolicyApplication.java | 92 + .../publication/RealmPolicyGenesis.java | 48 + .../RealmPolicyPublicationRepository.java | 537 ++ .../RealmPolicyPublishedEvidence.java | 281 + .../publication/RealmPolicySnapshot.java | 81 + .../publication/RealmPolicySource.java | 192 + .../RealmPolicySourceRepository.java | 607 ++ ...AuthoredWorldSourceDeliveryRepository.java | 604 ++ .../GameAuthoredWorldSourceRepository.java | 627 ++ .../LaunchDescriptorRepository.java | 173 +- .../repository/PublishAttemptRepository.java | 56 + .../PublishedReleaseBundleRepository.java | 332 +- .../VersionAssetArtifactRepository.java | 20 + .../VersionAssetPublicationRepository.java | 570 ++ .../repository/VersionRepository.java | 221 +- .../service/CompleteLaunchBindingService.java | 14 + .../service/ExportedAssetManifest.java | 60 +- .../service/LaunchDescriptorService.java | 29 +- .../service/PublishedArtifactDigest.java | 62 + .../PublishedReleaseBundleService.java | 11 + .../AuthoredWorldVersionStateGrpcService.java | 110 + .../AuthoredWorldVersionStateService.java | 74 + .../CompleteLaunchBindingServiceImpl.java | 489 ++ ...FrozenLaunchDescriptorDenialException.java | 23 + .../service/impl/GameDesignGrpcService.java | 2 +- .../impl/LaunchDescriptorServiceImpl.java | 754 +- .../impl/PublishedReleaseBundleContract.java | 122 + .../PublishedReleaseBundleServiceImpl.java | 179 +- .../V33__authored_world_source_operations.sql | 224 + .../V35.1__canonical_version_identity.sql | 116 + ....2__canonical_release_version_identity.sql | 86 + ...hored_source_launch_descriptor_binding.sql | 147 + ...que_published_release_bundle_reference.sql | 56 + .../V37__version_asset_export_snapshot.sql | 348 + .../V38__published_asset_digest_evidence.sql | 75 + ...V39__publication_evidence_text_storage.sql | 11 + ..._publish_attempt_ability_schema_digest.sql | 2 + .../V41__world_authored_source_delivery.sql | 249 + ...V42__durable_draft_commit_coordination.sql | 865 +++ .../V43__authored_draft_publish_selection.sql | 265 + ...uthored_draft_publish_request_identity.sql | 5 + ...lected_publish_attempt_digest_capacity.sql | 5 + ...8__game_design_draft_terminal_outcomes.sql | 405 + ...ublished_world_start_location_evidence.sql | 238 + ...0__publication_operation_terminal_seal.sql | 180 + ...publication_terminal_content_and_epoch.sql | 141 + .../V52__immutable_realm_policy_source.sql | 311 + ...aled_realm_policy_publication_evidence.sql | 278 + .../V54__immutable_command_source.sql | 480 ++ .../draft/IsolatedPublicationOwnerSetup.java | 200 + .../IsolatedPublicationOperationFixtures.java | 162 + .../impl/PublishedWorldSelectorFixtures.java | 406 + ...tCoordinatorRepositoryIntegrationTest.java | 1017 +++ ...erminalOutcomePostgresIntegrationTest.java | 772 ++ ...dWorldSourceRepositoryIntegrationTest.java | 617 ++ ...leaseCanonicalIdentityIntegrationTest.java | 1075 +++ ...rsionCanonicalIdentityIntegrationTest.java | 508 ++ ...teLaunchBindingServiceIntegrationTest.java | 582 ++ ...aunchDescriptorServiceIntegrationTest.java | 1348 +++- ...esignDraftTerminalReadGrpcServiceTest.java | 296 + .../VersionAssetArtifactRepositoryTest.java | 12 + .../repository/VersionRepositoryTest.java | 5 + .../service/ExportedAssetManifestTest.java | 23 + ...horedWorldVersionStateGrpcServiceTest.java | 211 + .../AuthoredWorldVersionStateServiceTest.java | 227 + .../CompleteLaunchBindingServiceImplTest.java | 1011 +++ .../impl/GameDesignGrpcServiceAuthTest.java | 14 +- .../impl/GameDesignGrpcServiceTest.java | 5 +- .../impl/LaunchDescriptorServiceImplTest.java | 1040 ++- ...PublishedReleaseBundleServiceImplTest.java | 348 +- .../world-management-service/build.gradle.kts | 3 + .../entity/RegionInstance.java | 2 + .../entity/WorldEntitySpawnBinding.java | 4 + .../repository/RegionInstanceRepository.java | 28 +- .../WorldEntitySpawnBindingRepository.java | 18 + .../WorldDraftDesignDigestServiceImpl.java | 67 +- ...nCanonicalInitialAdmissionOwnerClient.java | 237 + ...nonicalInitialAdmissionOwnerGrpcCodec.java | 223 + .../tenant/WorldAuthoredGraph.java | 471 ++ .../tenant/WorldAuthoredGraphReader.java | 325 + .../tenant/WorldAuthoredGraphSnapshot.java | 208 + .../WorldAuthoredGraphSnapshotCapture.java | 329 + .../WorldAuthoredGraphSnapshotRepository.java | 599 ++ .../WorldAuthoredSourceIntakeDigest.java | 112 + .../WorldAuthoredSourceIntakeGrpcService.java | 258 + .../WorldAuthoredSourceIntakeReceipt.java | 61 + .../WorldAuthoredSourceIntakeRepository.java | 687 ++ .../WorldAuthoredSourceIntakeService.java | 336 + .../WorldAuthoredVersionIdentityReceipt.java | 94 + ...orldAuthoredVersionIdentityRepository.java | 453 ++ .../WorldAuthoredVersionIdentityService.java | 340 + .../tenant/WorldCanonicalAuthoredGraph.java | 98 + .../WorldCanonicalAuthoredGraphReader.java | 176 + ...onicalCurrentPlayerLocationRepository.java | 347 + ...CanonicalCurrentPlayerLocationService.java | 55 + .../tenant/WorldCanonicalFrozenTopology.java | 124 + ...orldCanonicalFrozenTopologyRepository.java | 288 + .../WorldCanonicalFrozenTopologyService.java | 43 + ...alAdmissionHoldFinalizationRepository.java | 587 ++ ...itialAdmissionHoldFinalizationService.java | 134 + ...onicalInitialAdmissionHoldGrpcService.java | 322 + ...nonicalInitialAdmissionHoldRepository.java | 397 + ...itialAdmissionHoldTerminalGrpcService.java | 200 + ...onicalInitialPlayerLocationRepository.java | 462 ++ ...CanonicalInitialPlayerLocationService.java | 76 + ...anonicalInstanceActivationGrpcService.java | 186 + ...CanonicalInstanceActivationRepository.java | 296 + ...rldCanonicalInstanceActivationService.java | 85 + .../WorldCanonicalInstanceAssociation.java | 455 ++ ...anonicalInstanceAssociationRepository.java | 938 +++ ...nicalInstanceLifecycleReadGrpcService.java | 129 + ...onicalInstanceLifecycleReadRepository.java | 899 +++ .../WorldCanonicalInstancePreparation.java | 278 + ...calInstancePreparationAssemblyService.java | 324 + ...nonicalInstancePreparationGrpcService.java | 346 + ...anonicalInstancePreparationRepository.java | 824 ++ ...ldCanonicalInstancePreparationService.java | 88 + .../WorldCanonicalInstanceTopologyPlan.java | 575 ++ ...nonicalPlayerAdmissionHoldGrpcService.java | 210 + ...anonicalPlayerAdmissionHoldRepository.java | 208 + ...ldCanonicalPlayerAdmissionHoldService.java | 83 + ...rldCanonicalPlayerLocationGrpcService.java | 430 ++ .../WorldCompleteLaunchBindingReceipt.java | 74 + .../WorldCompleteLaunchBindingRepository.java | 491 ++ .../WorldCompleteLaunchBindingService.java | 677 ++ .../WorldDesignPublicationFenceEvidence.java | 183 + ...WorldDesignPublicationFenceRepository.java | 527 ++ .../tenant/WorldDraftGraphApplication.java | 41 + .../WorldDraftGraphApplicationRepository.java | 373 + .../WorldDraftGraphApplicationService.java | 100 + .../tenant/WorldDraftGraphAppliedResult.java | 158 + .../WorldDraftRegionCommitEvidence.java | 51 + .../tenant/WorldDraftRegionCommitPlan.java | 234 + .../WorldDraftRegionCommitRepository.java | 249 + .../tenant/WorldDraftRegionCommitService.java | 78 + .../tenant/WorldDraftRegionGraphStager.java | 153 + .../WorldDraftRegionStagingService.java | 65 + .../WorldDraftStartLocationReceipt.java | 88 + ...ldDraftStartLocationReceiptRepository.java | 95 + .../tenant/WorldDraftTerminalOperation.java | 208 + .../tenant/WorldDraftTerminalOutcome.java | 262 + .../WorldDraftTerminalOutcomeRepository.java | 464 ++ .../WorldDraftTerminalOutcomeService.java | 43 + .../WorldDraftTerminalReadGrpcService.java | 150 + .../WorldDraftTopologyCommitEvidence.java | 51 + .../tenant/WorldDraftTopologyCommitPlan.java | 446 ++ .../WorldDraftTopologyCommitRepository.java | 617 ++ .../WorldDraftTopologyCommitService.java | 79 + .../tenant/WorldDraftTopologyInputGraph.java | 117 + .../tenant/WorldPublicationTerminal.java | 110 + .../WorldPublicationTerminalRepository.java | 443 ++ .../WorldPublicationTerminalService.java | 90 + ...ishedSpawnRequirementsReadGrpcService.java | 61 + ...ldPublishedSpawnRequirementsReadOwner.java | 334 + ...PublishedStartLocationReadGrpcService.java | 167 + ...WorldPublishedStartLocationRepository.java | 109 + .../WorldPublishedStartLocationSource.java | 18 + ...dSynchronizedDraftTopologyReadService.java | 43 + .../V23.1__world_authored_source_intake.sql | 250 + ..._world_canonical_tenant_mutation_guard.sql | 219 + .../V25__world_design_publication_fence.sql | 220 + .../V26__world_complete_launch_binding.sql | 72 + .../V27__world_authored_version_identity.sql | 80 + .../V28__world_authored_graph_snapshot.sql | 329 + ...29__world_guarded_region_draft_commits.sql | 392 + ...0__world_guarded_uuid_topology_commits.sql | 490 ++ .../V31__world_canonical_frozen_topology.sql | 96 + .../V32__world_digest_schema3_capture.sql | 39 + ...__world_canonical_instance_association.sql | 506 ++ ...guarded_canonical_instance_preparation.sql | 858 +++ .../V36__world_draft_terminal_outcomes.sql | 237 + ...__world_draft_terminal_guard_namespace.sql | 43 + ..._world_account_bound_graph_application.sql | 216 + ..._world_preparation_exact_release_graph.sql | 67 + ...ld_explicit_fresh_graph_start_location.sql | 292 + ...release_start_location_materialization.sql | 227 + ...anonical_instance_activation_operation.sql | 565 ++ ...44__world_publication_terminal_handoff.sql | 354 + ...5__world_operational_region_assignment.sql | 93 + ...orld_canonical_initial_player_location.sql | 458 ++ ...nonical_initial_admission_hold_binding.sql | 255 + ...onical_initial_admission_hold_terminal.sql | 334 + ...cal_initial_player_location_typed_hold.sql | 146 + ...cal_initial_location_operation_origins.sql | 148 + ..._world_canonical_player_admission_hold.sql | 241 + ...al_activation_complete_region_evidence.sql | 108 + ...dGraphSnapshotPostgresIntegrationTest.java | 1401 ++++ ...ldAuthoredSourceIntakeIntegrationTest.java | 1329 ++++ ...thoredSourceIntakeMtlsIntegrationTest.java | 775 ++ ...uthoredVersionIdentityIntegrationTest.java | 957 +++ ...dCompleteLaunchBindingIntegrationTest.java | 1148 +++ ...DesignPublicationFenceIntegrationTest.java | 975 +++ ...FrozenTopologyPostgresIntegrationTest.java | 1230 +++ ...nHoldMigrationPostgresIntegrationTest.java | 354 + ...nceAssociationPostgresIntegrationTest.java | 2429 ++++++ ...ncePreparationPostgresIntegrationTest.java | 251 + ...rAdmissionHoldPostgresIntegrationTest.java | 564 ++ ...aphApplicationPostgresIntegrationTest.java | 6683 +++++++++++++++++ ...ftRegionCommitPostgresIntegrationTest.java | 1094 +++ ...erminalOutcomePostgresIntegrationTest.java | 1167 +++ ...TopologyCommitPostgresIntegrationTest.java | 1368 ++++ ...gionAssignmentPostgresIntegrationTest.java | 383 + .../WorldPreparationTestWorkloadPki.java | 292 + ...ftTopologyReadPostgresIntegrationTest.java | 443 ++ ...dCanonicalPlayerLocationHoldProofTest.java | 193 + ...WorldDraftDesignDigestServiceImplTest.java | 136 +- ...alInitialAdmissionOwnerClientMtlsTest.java | 502 ++ ...onicalInitialAdmissionOwnerClientTest.java | 175 + ...calInitialAdmissionOwnerGrpcCodecTest.java | 352 + .../WorldAuthoredGraphSnapshotTest.java | 162 + .../tenant/WorldAuthoredGraphTest.java | 327 + .../WorldAuthoredSourceIntakeDigestTest.java | 131 + ...ldAuthoredSourceIntakeGrpcServiceTest.java | 438 ++ .../WorldAuthoredSourceIntakeMtlsTest.java | 695 ++ .../WorldAuthoredSourceIntakeServiceTest.java | 638 ++ ...rldAuthoredVersionIdentityServiceTest.java | 489 ++ ...WorldCanonicalAuthoredGraphReaderTest.java | 153 + ...nicalCurrentPlayerLocationServiceTest.java | 107 + ...rldCanonicalFrozenTopologyServiceTest.java | 96 + .../WorldCanonicalFrozenTopologyTest.java | 64 + ...missionHoldFinalizationRepositoryTest.java | 481 ++ ...lAdmissionHoldFinalizationServiceTest.java | 216 + ...alInitialAdmissionHoldGrpcServiceTest.java | 505 ++ ...calInitialAdmissionHoldRepositoryTest.java | 482 ++ ...lAdmissionHoldTerminalGrpcServiceTest.java | 368 + ...orldCanonicalInitialAdmissionMtlsTest.java | 514 ++ ...nicalInitialPlayerLocationServiceTest.java | 142 + ...icalInstanceActivationGrpcServiceTest.java | 420 ++ ...nicalInstanceActivationRepositoryTest.java | 80 + ...anonicalInstanceActivationServiceTest.java | 102 + ...WorldCanonicalInstanceAssociationTest.java | 94 + ...lInstanceLifecycleReadGrpcServiceTest.java | 187 + ...alInstanceLifecycleReadRepositoryTest.java | 54 + ...nstancePreparationAssemblyServiceTest.java | 389 + ...calInstancePreparationGrpcServiceTest.java | 566 ++ ...WorldCanonicalInstancePreparationTest.java | 670 ++ ...orldCanonicalInstanceTopologyPlanTest.java | 650 ++ ...calPlayerAdmissionHoldGrpcServiceTest.java | 308 + ...icalPlayerAdmissionHoldRepositoryTest.java | 110 + ...nonicalPlayerAdmissionHoldServiceTest.java | 122 + ...WorldCanonicalPlayerAdmissionHoldTest.java | 223 + ...anonicalPlayerLocationGrpcServiceTest.java | 1301 ++++ ...WorldCompleteLaunchBindingServiceTest.java | 1351 ++++ ...rldDesignPublicationFenceEvidenceTest.java | 232 + ...WorldDraftGraphApplicationServiceTest.java | 110 + .../WorldDraftRegionCommitEvidenceTest.java | 42 + .../WorldDraftRegionCommitPlanTest.java | 540 ++ .../WorldDraftRegionCommitRepositoryTest.java | 102 + .../WorldDraftRegionCommitServiceTest.java | 121 + .../WorldDraftRegionGraphStagerTest.java | 366 + .../WorldDraftRegionStagingServiceTest.java | 142 + .../WorldDraftStartLocationReceiptTest.java | 47 + .../tenant/WorldDraftTerminalOutcomeTest.java | 240 + ...WorldDraftTerminalReadGrpcServiceTest.java | 273 + .../WorldDraftTopologyCommitEvidenceTest.java | 42 + .../WorldDraftTopologyCommitPlanTest.java | 870 +++ ...orldDraftTopologyCommitRepositoryTest.java | 161 + .../WorldDraftTopologyCommitServiceTest.java | 123 + .../WorldPublicationTerminalServiceTest.java | 22 + .../WorldPublishedSourceSnapshotReadTest.java | 88 + ...dSpawnRequirementsReadGrpcServiceTest.java | 74 + ...blishedSpawnRequirementsReadOwnerTest.java | 476 ++ ...ishedStartLocationReadGrpcServiceTest.java | 159 + ...chronizedDraftTopologyReadServiceTest.java | 149 + settings.gradle.kts | 3 + 558 files changed, 184167 insertions(+), 593 deletions(-) create mode 100644 protos/account/v1/account_gameplay_admission_lease.proto create mode 100644 protos/account/v1/account_issuer_authority_source.proto create mode 100644 protos/game-design/v1/draft_terminal_service.proto create mode 100644 protos/game-design/v1/draft_visibility_service.proto create mode 100644 protos/world-management/v1/draft_terminal_service.proto create mode 100644 protos/world-management/v1/world_canonical_initial_admission_hold.proto create mode 100644 protos/world-management/v1/world_canonical_initial_admission_hold_terminal.proto create mode 100644 protos/world-management/v1/world_canonical_instance_activation.proto create mode 100644 protos/world-management/v1/world_canonical_instance_lifecycle_read.proto create mode 100644 protos/world-management/v1/world_canonical_player_admission_hold.proto create mode 100644 protos/world-management/v1/world_canonical_player_location.proto create mode 100644 protos/world-management/v1/world_published_spawn_requirements.proto create mode 100644 protos/world-management/v1/world_published_start_location_read.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundle.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionCommitConfirmation.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionOriginalAckReceipt.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionProvisionalDecision.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipRoleSourceSnapshot.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutor.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisScriptContribution.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountRedisScriptDescriptorLoader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticator.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java create mode 100644 services/account-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution create mode 100644 services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql create mode 100644 services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql create mode 100644 services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql create mode 100644 services/account-service/src/main/resources/db/migration/V44__account_gameplay_delegation_issuance.sql create mode 100644 services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql create mode 100644 services/account-service/src/main/resources/db/migration/V46__account_auth_evidence_bundles.sql create mode 100644 services/account-service/src/main/resources/db/migration/V47__account_gameplay_delegation_encrypted_response.sql create mode 100644 services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql create mode 100644 services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql create mode 100644 services/account-service/src/main/resources/db/migration/V51__account_gameplay_delegation_committed_issuance.sql create mode 100644 services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql create mode 100644 services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql create mode 100644 services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql create mode 100644 services/account-service/src/main/resources/db/migration/V74.1__account_global_role_source.sql create mode 100644 services/account-service/src/main/resources/db/migration/V74__account_gameplay_token_identity_fences.sql create mode 100644 services/account-service/src/main/resources/db/migration/V75__account_password_reset_operation_receipts.sql create mode 100644 services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql create mode 100644 services/account-service/src/main/resources/db/migration/V77__account_logout_all_operation_receipts.sql create mode 100644 services/account-service/src/main/resources/db/migration/V78__account_security_state_operations.sql create mode 100644 services/account-service/src/main/resources/db/migration/V81__account_gameplay_login_credential_request_binding.sql create mode 100644 services/account-service/src/main/resources/db/migration/V83__account_security_event_source_guard.sql create mode 100644 services/account-service/src/main/resources/db/migration/V84.1__account_auth_evidence_checkpoint_key_count.sql create mode 100644 services/account-service/src/main/resources/db/migration/V84.2__account_auth_evidence_shared_issuer_guard.sql create mode 100644 services/account-service/src/main/resources/db/migration/V84.3__account_gameplay_commit_bundle_source_fence.sql create mode 100644 services/account-service/src/main/resources/db/migration/V84.4__account_gameplay_authority_shared_issuer_guard.sql create mode 100644 services/account-service/src/main/resources/db/migration/V84__account_gameplay_delegation_decimal_source_versions.sql create mode 100644 services/account-service/src/main/resources/db/migration/V86__account_lifecycle_serving_operations.sql create mode 100644 services/account-service/src/main/resources/db/migration/V87__account_gameplay_admission_lease_operations.sql create mode 100644 services/account-service/src/main/resources/db/migration/V88__account_platform_restriction_birth_sources.sql create mode 100644 services/account-service/src/main/resources/db/migration/V89__account_admission_unknown_decision_abort.sql create mode 100644 services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql create mode 100644 services/account-service/src/main/resources/db/migration/V91__account_global_pending_admission_fences.sql create mode 100644 services/account-service/src/main/resources/db/migration/V92__account_admission_original_ack_receipt.sql create mode 100644 services/account-service/src/main/resources/db/migration/V93__account_draft_required_owner_fence.sql create mode 100644 services/account-service/src/main/resources/redis/account_generation_projection_cas.lua create mode 100644 services/account-service/src/main/resources/redis/lua/account-game-session-delegation-activate-committed.lua create mode 100644 services/account-service/src/main/resources/redis/lua/account-game-session-delegation-authority-project.lua create mode 100644 services/account-service/src/main/resources/redis/lua/account-game-session-delegation-pending-register.lua create mode 100644 services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-activate-committed.json create mode 100644 services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer.json create mode 100644 services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-pending-register.json create mode 100644 services/account-service/src/main/resources/redis/scripts/account-generation-projection-cas.json create mode 100644 services/account-service/src/main/resources/redis/scripts/account-selected-membership-generation-projection.json create mode 100644 services/account-service/src/main/resources/redis/scripts/account-selected-tenant-generation-projection.json create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutorTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountRedisScriptDescriptorLoaderTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticatorTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBindingFixture.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.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/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProof.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocation.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceActivation.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.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/world/CanonicalWorldInstancePreparationClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java create mode 100644 services/common-redis-contracts/build.gradle.kts create mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalog.java create mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptContribution.java create mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodec.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOperation.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcome.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalReadGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.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/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V33__authored_world_source_operations.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V40__publish_attempt_ability_schema_digest.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V42__durable_draft_commit_coordination.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V48__game_design_draft_terminal_outcomes.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V52__immutable_realm_policy_source.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V53__sealed_realm_policy_publication_evidence.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql create mode 100644 services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java create mode 100644 services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java create mode 100644 services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.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/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalReadGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/ExportedAssetManifestTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClient.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.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/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityReceipt.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldTerminalGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlan.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingReceipt.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplication.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphAppliedResult.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidence.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlan.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStager.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOperation.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcome.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidence.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationSource.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadService.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/main/resources/db/migration/V25__world_design_publication_fence.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V28__world_authored_graph_snapshot.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V29__world_guarded_region_draft_commits.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V30__world_guarded_uuid_topology_commits.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V31__world_canonical_frozen_topology.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V32__world_digest_schema3_capture.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V34__world_canonical_instance_association.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V35__world_guarded_canonical_instance_preparation.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V36__world_draft_terminal_outcomes.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V37__world_draft_terminal_guard_namespace.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V39__world_account_bound_graph_application.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V40__world_preparation_exact_release_graph.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V41__world_explicit_fresh_graph_start_location.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V45__world_operational_region_assignment.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V46__world_canonical_initial_player_location.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V47__canonical_initial_admission_hold_binding.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V48__canonical_initial_admission_hold_terminal.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V49__canonical_initial_player_location_typed_hold.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V50__canonical_initial_location_operation_origins.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V51__world_canonical_player_admission_hold.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V52__canonical_activation_complete_region_evidence.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java 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/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldMigrationPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomePostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPreparationTestWorkloadPki.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationHoldProofTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodecTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.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 create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReaderTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldTerminalGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlanTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidenceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlanTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStagerTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidenceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSourceSnapshotReadTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f24d2dfb29..1b8aa7a151 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -948,8 +948,8 @@ jobs: permissions: contents: read id-token: write - # The World PostgreSQL proof can run close to 20 minutes before Gradle post-job cleanup. - timeout-minutes: ${{ matrix.module == 'world-management-service' && 30 || 20 }} + # Account and World PostgreSQL proofs can run close to 20 minutes before Gradle post-job cleanup. + timeout-minutes: ${{ (matrix.module == 'account-service' || matrix.module == 'world-management-service') && 30 || 20 }} strategy: fail-fast: false matrix: @@ -995,6 +995,54 @@ jobs: ./gradlew :${{ matrix.module }}:check -PfullCheck echo "::endgroup::" + - name: 📤 Capture Account Draft authorization fence PostgreSQL XML + if: ${{ always() && matrix.module == 'account-service' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: account-draft-authorization-fence-postgresql-proof-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: services/account-service/build/test-results/integrationTest/TEST-*DraftAuthorizationFencePostgresIntegrationTest.xml + if-no-files-found: error + retention-days: 7 + + - name: 🔎 Verify Account Draft authorization fence PostgreSQL proof + if: ${{ !cancelled() && matrix.module == 'account-service' }} + run: | + bash dev-tools/validation/inspect-test-results.sh \ + --strict \ + --require-suite integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#accountAndGlobalRolePendingScopesVersionOnlyTheirExistingAccountTuple()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#producerLocksDeduplicatedAccountsInUuidOrderBeforeAnySourceLocks()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#scopeInsertVersionsAccountBeforeTheExistingParentLockingTrigger()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#applicableMissingOrMalformedAccountScopesDenyWithoutCreatingAccountOrIntent()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#twoOwnerConsumerPersistsWorldOnceAndRecoversMissingGameDesignOnRetry()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#mixedCommitOrderPreservesOriginalWorldCommitAndHoldsSourceFence()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#concurrentExactConsumerRetriesReturnTheSameOriginalSettlement()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#concurrentConflictingOwnerEvidenceRejectsRetryAndPreservesWinningBytes()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#revokeBeforeCommitDeniesDelayedRequestsUntilBothDefinitiveAborts()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBothReadbacks()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReopening()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#bothMixedDirectionsRemainPendingAndPreserveOriginalReadbacks()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#revokeOrderWithEitherMixedDirectionCannotAuthorizeSourceMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#changedCompleteBindingsConflictWithoutRewritingOriginal()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#inconsistentOrMalformedCompleteBindingsFailBeforeReservationStorage()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflict()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#distinctPendingChangesCannotRetainTwoOldCapturesForTheSameSource()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#concurrentDistinctSourceClaimsAdmitOnlyOnePendingCaptureWithoutBlockingDisjointSources()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#concurrentCommitOrderAndRevocationChooseExactlyOneDurableOrdering()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#originalBindingSurvivesRestartAndAbsenceRemainsUnknownUnderOwnerTransaction()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#discoveryPagesOriginalPendingOperationsAndExcludesEverySettledVector()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#originalRecoveryRejectsMalformedBytesAndEveryConflictingIdentityColumn()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#ownerRecoveryRejectsReadbackThatContradictsItsOutcomeColumn()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#v2WorldEntityAndCoordinatorRequireAllThreeExactOriginalResults()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#v2FreshDraftEpochZeroAcceptsExactRequiredOwnerReadback()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#rawSqlCannotRecordOwnerProofWithMissingChangedOrExtraSourceParticipation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#v2RequiredOwnerDecoderRejectsMissingExtraDuplicateAndReorderedOwners()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#v2AllRequiredAbortsSettleBothCommitAndRevokeOrdering()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#v2MixedResultsHoldBothSourceTransitionsAndPreserveAppliedBytes()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#forwardMigrationRetainsV1BindingReadbackAndFlywayChecksumsExactly()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest#issuerSourceKeysPreserveLegacyAndUnicodeIdentityThroughExactByteBound()' \ + account-service + - name: 📦 Build Runtime JAR if: ${{ contains(fromJSON(needs.changes.outputs.bootable_modules), matrix.module) }} run: ./gradlew :${{ matrix.module }}:bootJar -PfullCheck diff --git a/dev-tools/README.md b/dev-tools/README.md index 9292190bc2..1a4b91e74f 100644 --- a/dev-tools/README.md +++ b/dev-tools/README.md @@ -15,7 +15,7 @@ Keep the root of `dev-tools/` small. Only canonical human-facing entrypoints and - `build-local-smoke-images.sh` – builds the pinned local base and service images for a 40-character commit tag after rebuilding the service boot jars. - `verify-compose-health.sh` – shared health gate used by the smoke entrypoints. - `validation/run-locked-gradle.sh` – canonical local Gradle wrapper that serializes heavy builds across worktrees, protects shared output trees, and bounds lock acquisition and cancellation start. Use it for local proof and service boot-jar builds; [Local Gradle execution](../design/developer-workflows/validation-and-runtime-proof.md#local-gradle-execution) owns configuration and cancellation limits. For example: `bash dev-tools/validation/run-locked-gradle.sh :account-service:test`. -- `validation/inspect-test-results.sh` – read-only JUnit XML summary helper for diagnosing quiet post-suite Gradle tails without guessing at process state. For example: `bash dev-tools/validation/inspect-test-results.sh account-service`. This is diagnostic evidence only and does not prove that the Gradle invocation completed cleanly. +- `validation/inspect-test-results.sh` – read-only JUnit XML helper for diagnosing quiet post-suite Gradle tails without guessing at process state. For example: `bash dev-tools/validation/inspect-test-results.sh account-service`. Default mode is diagnostic only and does not prove that Gradle completed cleanly. CI may use `--strict` with repeated `--require-suite ` and `--require-case ` arguments to fail closed on missing, duplicate, malformed, empty, skipped, or failing JUnit proof; strict output contains only counts, requested names, and outcomes. - `pr-review` – the sole review controller. Use `dev-tools/pr-review stack set ...` and `stack show` for the repository review stack, `status [--pr ]` for fail-closed live state, `run hosted|cli [--expect-pr ] [--force [--reason ]]` for a complete checkpoint, `evidence []` for anchored evidence, and `decide ...` for explicit judgments. `--force` records acknowledgment of a known candidate-quality warning with the attempt; it does not bypass PR/candidate identity or admission-time rechecks, provider ceilings or quota, active-request exclusion, channel caps, stopped/completed channels, or accepted-finding obligations. A completed result counts normally for its PR and channel. The complete review, status, checkpoint, and disposition policy is owned by [PR lifecycle: Review and Status](../design/developer-workflows/pr-lifecycle.md#review-and-status). Until an explicitly validated JSON-to-SQLite cutover, controller decisions remain in the locked private common-directory JSON state file; do not assume cutover has occurred. Live shared cutover waits until the controller change is merged and its version-matched tooling is installed. Select the trusted promoted `dev-tools/pr-review` entrypoint and inspect `dev-tools/pr-review --version` before migration or shared writes. Follow [PR-review SQLite operations](pr_review/README.md) for the atomic JSON migration and old-writer fence, separate records bootstrap, provider-checkpoint imports, curated manual/subagent batch imports, and read-only history/route queries. Existing controller-era routes remain available through `routes` and `status`; full provider captures remain separate audit evidence outside SQLite. Provider imports and independent records do not affect CodeRabbit taper. Live PR, CI, checkpoint, and review evidence is derived when requested. For hands-on acceptance, pass the paired global options `--acceptance-fixture ` and `--state-path `; these use synthetic fixture adapters in a dedicated private directory and never contact GitHub or consume review quota. The implementation and focused contracts live in `pr_review/` and `tests/pr-review-controller-contract.sh`. An acceptance fixture is a JSON object containing `repository`, `default_base_ref`, `default_base_tip`, `branch_heads`, `pull_requests`, `ancestors`, `merge_bases`, `test_merge_trees`, `patch_ids`, and optional `ordered_prs` and `evidence`. `test_merge_trees` maps each exact `base...head` pair to its synthetic full tree SHA; every direct default-base PR needs a matching fact. Pull requests provide exact `base_ref`, `base_tip`, `head`, and `head_repository` identities; `head_repository` must explicitly match the fixture's `repository`. They may also provide `head_ref`, state, mergeability, and merge flags; Git relationships, merge trees, and patch identities are explicit so missing or stale facts fail closed. Create a dedicated private directory with `review_acceptance_dir=$(mktemp -d)`, place the fixture there, then run `dev-tools/pr-review --acceptance-fixture "$review_acceptance_dir/fixture.json" --state-path "$review_acceptance_dir/state.json" status --json`. The state directory must already exist, be owned by the caller, and have mode `0700`; the canonical state directory is forbidden. diff --git a/dev-tools/tests/gradle-proof-tooling-contract.sh b/dev-tools/tests/gradle-proof-tooling-contract.sh index 7341840bd8..0ab5047560 100644 --- a/dev-tools/tests/gradle-proof-tooling-contract.sh +++ b/dev-tools/tests/gradle-proof-tooling-contract.sh @@ -89,6 +89,158 @@ grep -q "Most recent XML on disk:" <<<"$inspection_output" grep -q "Failing XML files:" <<<"$inspection_output" grep -q "Diagnostic only:" <<<"$inspection_output" +DRAFT_SUITE="integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest" +DRAFT_CASE="${DRAFT_SUITE}#accountAndGlobalRolePendingScopesVersionOnlyTheirExistingAccountTuple()" +STRICT_ROOT="$TMP_DIR/strict" +STRICT_REPORTS="$STRICT_ROOT/services/account-service/build/test-results/integrationTest" +mkdir -p "$STRICT_REPORTS" + +inspect_strict() { + bash "$INSPECTOR" --root "$STRICT_ROOT" --strict \ + --require-suite "$DRAFT_SUITE" \ + --require-case "$DRAFT_CASE" \ + account-service +} + +cat >"$STRICT_REPORTS/TEST-draft.xml" < + + +XML +strict_green_output="$(inspect_strict)" +grep -q '^Strict JUnit proof: passed$' <<<"$strict_green_output" +grep -Fq "Case $DRAFT_CASE: executions=1 outcome=passed" <<<"$strict_green_output" + +rm "$STRICT_REPORTS/TEST-draft.xml" +if strict_no_reports_output="$(inspect_strict 2>&1)"; then + echo "Strict inspection unexpectedly accepted missing JUnit XML reports." >&2 + exit 1 +fi +grep -Fq "No JUnit XML reports were found." <<<"$strict_no_reports_output" + +cat >"$STRICT_REPORTS/TEST-draft.xml" < + + +XML +if strict_missing_suite_output="$(inspect_strict 2>&1)"; then + echo "Strict inspection unexpectedly accepted a missing required suite." >&2 + exit 1 +fi +grep -Fq "Missing required suite: $DRAFT_SUITE" <<<"$strict_missing_suite_output" + +cat >"$STRICT_REPORTS/TEST-draft.xml" < +XML +if strict_zero_tests_output="$(inspect_strict 2>&1)"; then + echo "Strict inspection unexpectedly accepted an empty required suite." >&2 + exit 1 +fi +grep -Fq "Required suite has zero tests: $DRAFT_SUITE" <<<"$strict_zero_tests_output" + +cat >"$STRICT_REPORTS/TEST-draft.xml" < + + +XML +if strict_failure_output="$(inspect_strict 2>&1)"; then + echo "Strict inspection unexpectedly accepted a failing required case." >&2 + exit 1 +fi +grep -Fq "Required suite is failing, errored, or skipped: $DRAFT_SUITE" <<<"$strict_failure_output" + +cat >"$STRICT_REPORTS/TEST-draft.xml" < + + +XML +cp "$STRICT_REPORTS/TEST-draft.xml" "$STRICT_REPORTS/TEST-draft-copy.xml" +if strict_duplicate_output="$(inspect_strict 2>&1)"; then + echo "Strict inspection unexpectedly accepted a duplicate required suite." >&2 + exit 1 +fi +grep -Fq "Duplicate required suite: $DRAFT_SUITE" <<<"$strict_duplicate_output" +rm "$STRICT_REPORTS/TEST-draft-copy.xml" + +cat >"$STRICT_REPORTS/TEST-draft.xml" < + + + +XML +if strict_duplicate_case_output="$(inspect_strict 2>&1)"; then + echo "Strict inspection unexpectedly accepted duplicate execution of a required case." >&2 + exit 1 +fi +grep -Fq "Duplicate required case: $DRAFT_CASE" <<<"$strict_duplicate_case_output" + +cat >"$STRICT_REPORTS/TEST-draft.xml" < + + +XML +if strict_skipped_output="$(inspect_strict 2>&1)"; then + echo "Strict inspection unexpectedly accepted a skipped required case." >&2 + exit 1 +fi +grep -Fq "Required suite is failing, errored, or skipped: $DRAFT_SUITE" <<<"$strict_skipped_output" +grep -Fq "outcome=skipped" <<<"$strict_skipped_output" + +printf '"$STRICT_REPORTS/TEST-malformed.xml" +if strict_malformed_output="$(inspect_strict 2>&1)"; then + echo "Strict inspection unexpectedly accepted malformed XML." >&2 + exit 1 +fi +grep -Fq "Malformed report(s): 1" <<<"$strict_malformed_output" + +python3 - "$ROOT_DIR" <<'PY' +from __future__ import annotations + +import re +import sys +from pathlib import Path + +root = Path(sys.argv[1]) +workflow = (root / ".github/workflows/ci.yml").read_text() +suite = "integration.net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFencePostgresIntegrationTest" +test_source = (root / "services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java").read_text() +methods = re.findall(r"(?m)^ void ([A-Za-z0-9_]+)\(", test_source) +if len(methods) != 31: + raise SystemExit(f"Expected 31 Account Draft fence cases, found {len(methods)}") +if methods[:4] != [ + "accountAndGlobalRolePendingScopesVersionOnlyTheirExistingAccountTuple", + "producerLocksDeduplicatedAccountsInUuidOrderBeforeAnySourceLocks", + "scopeInsertVersionsAccountBeforeTheExistingParentLockingTrigger", + "applicableMissingOrMalformedAccountScopesDenyWithoutCreatingAccountOrIntent", +]: + raise SystemExit("The first four Account Draft fence source lock/version cases changed") +if methods[-1] != "issuerSourceKeysPreserveLegacyAndUnicodeIdentityThroughExactByteBound": + raise SystemExit("The final Account Draft fence byte-bound case changed") + +for method in methods: + required = f"--require-case '{suite}#{method}()'" + if workflow.count(required) != 1: + raise SystemExit(f"CI must require exactly one execution of {suite}#{method}()") + +if workflow.count(f"--require-suite {suite}") != 1: + raise SystemExit("CI must require the Draft Authorization Fence suite exactly once") +if "if: ${{ !cancelled() && matrix.module == 'account-service' }}" not in workflow: + raise SystemExit("Strict Account Draft fence verification must run unless cancelled") +if "if: ${{ always() && matrix.module == 'account-service' }}" not in workflow: + raise SystemExit("Account Draft fence raw XML capture must always run") +if "TEST-*DraftAuthorizationFencePostgresIntegrationTest.xml" not in workflow: + raise SystemExit("CI must capture the Account Draft fence raw XML report") +if "actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9" not in workflow: + raise SystemExit("Account Draft fence XML capture must use the pinned workflow artifact action") +check_step = workflow.index("- name: 🧪 Run Gradle Checks") +capture_step = workflow.index("- name: 📤 Capture Account Draft authorization fence PostgreSQL XML") +verify_step = workflow.index("- name: 🔎 Verify Account Draft authorization fence PostgreSQL proof") +if not check_step < capture_step < verify_step: + raise SystemExit("Account Draft fence XML capture and strict verification must follow Gradle checks in order") +if "bash dev-tools/validation/inspect-test-results.sh \\\n --strict" not in workflow[verify_step:]: + raise SystemExit("Account Draft fence verification must invoke the strict JUnit inspector") +PY + bootstrap_validation_output="$( FIREMUD_SMOKE_COMPOSE_SERVICES=$'gateway\ngame-session-service\n' \ FIREMUD_SMOKE_NO_CACHE_SERVICES='gateway game-session-service' \ diff --git a/dev-tools/validation/inspect-test-results.sh b/dev-tools/validation/inspect-test-results.sh index 4cd95c4cce..22d56ab732 100644 --- a/dev-tools/validation/inspect-test-results.sh +++ b/dev-tools/validation/inspect-test-results.sh @@ -6,14 +6,25 @@ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" usage() { cat <<'EOF' >&2 Usage: inspect-test-results.sh [--root ] + inspect-test-results.sh --strict [--root ] \ + --require-suite ... \ + --require-case ... Summarize parsed JUnit XML currently on disk under services//build/test-results. This is diagnostic only; it helps explain quiet Gradle tails but does not prove the original Gradle invocation completed cleanly. + +Strict mode fails closed unless every named suite has exactly one non-empty, +green report and every named test case executed exactly once without a skip, +failure, or error. EOF exit 1 } +STRICT_MODE=0 +REQUIRED_SUITES=() +REQUIRED_CASES=() + while (($# > 0)); do case "$1" in --root) @@ -21,6 +32,20 @@ while (($# > 0)); do ROOT_DIR="$2" shift 2 ;; + --strict) + STRICT_MODE=1 + shift + ;; + --require-suite) + [[ $# -ge 2 ]] || usage + REQUIRED_SUITES+=("$2") + shift 2 + ;; + --require-case) + [[ $# -ge 2 ]] || usage + REQUIRED_CASES+=("$2") + shift 2 + ;; --help|-h) usage ;; @@ -32,6 +57,33 @@ done [[ $# -eq 1 ]] || usage +if [[ "$STRICT_MODE" == "1" ]]; then + ((${#REQUIRED_SUITES[@]} > 0 && ${#REQUIRED_CASES[@]} > 0)) || usage + for ((i = 0; i < ${#REQUIRED_SUITES[@]}; i++)); do + suite_name="${REQUIRED_SUITES[$i]}" + [[ -n "$suite_name" && ! "$suite_name" =~ [[:cntrl:]] && "$suite_name" != *'#'* ]] || usage + for ((j = 0; j < i; j++)); do + [[ "$suite_name" != "${REQUIRED_SUITES[$j]}" ]] || usage + done + done + for ((i = 0; i < ${#REQUIRED_CASES[@]}; i++)); do + case_name="${REQUIRED_CASES[$i]}" + [[ "$case_name" == *'#'* && "${case_name#*#}" != *'#'* && ! "$case_name" =~ [[:cntrl:]] ]] || usage + case_suite="${case_name%%#*}" + [[ -n "${case_name#*#}" ]] || usage + suite_is_required=0 + for required_suite in "${REQUIRED_SUITES[@]}"; do + [[ "$case_suite" != "$required_suite" ]] || suite_is_required=1 + done + [[ "$suite_is_required" == "1" ]] || usage + for ((j = 0; j < i; j++)); do + [[ "$case_name" != "${REQUIRED_CASES[$j]}" ]] || usage + done + done +elif ((${#REQUIRED_SUITES[@]} > 0 || ${#REQUIRED_CASES[@]} > 0)); then + usage +fi + SERVICE_NAME="$1" SERVICE_DIR="$ROOT_DIR/services/$SERVICE_NAME" @@ -40,7 +92,7 @@ if [[ ! -d "$SERVICE_DIR" ]]; then exit 1 fi -python3 - "$SERVICE_DIR" <<'PY' +python3 - "$SERVICE_DIR" "$STRICT_MODE" "${REQUIRED_SUITES[@]}" --required-cases "${REQUIRED_CASES[@]}" <<'PY' from __future__ import annotations import datetime as dt @@ -50,9 +102,162 @@ from collections import defaultdict from pathlib import Path service_dir = Path(sys.argv[1]) +strict_mode = sys.argv[2] == "1" +case_separator = sys.argv.index("--required-cases", 3) +required_suites = sys.argv[3:case_separator] +required_cases = sys.argv[case_separator + 1 :] service_name = service_dir.name result_root = service_dir / "build" / "test-results" + +def strict_inspection() -> None: + xml_files = sorted(result_root.glob("**/TEST-*.xml")) if result_root.exists() else [] + malformed_reports = 0 + parsed_suite_count = 0 + parsed_test_count = 0 + suites: dict[str, list[dict[str, object]]] = defaultdict(list) + required_suite_set = set(required_suites) + + def count(value: str | None) -> int | None: + if value is None or not value.isascii() or not value.isdecimal(): + return None + try: + return int(value) + except ValueError: + return None + + for xml_file in xml_files: + try: + root = ET.parse(xml_file).getroot() + except (ET.ParseError, OSError, ValueError): + malformed_reports += 1 + continue + if root.tag == "testsuite": + report_suites = [root] + elif root.tag == "testsuites": + report_suites = list(root.findall(".//testsuite")) + else: + malformed_reports += 1 + continue + if not report_suites: + malformed_reports += 1 + continue + + report_valid = True + parsed_suites: list[dict[str, object]] = [] + for suite in report_suites: + name = suite.attrib.get("name") + tests = count(suite.attrib.get("tests")) + failures = count(suite.attrib.get("failures")) + errors = count(suite.attrib.get("errors")) + skipped = count(suite.attrib.get("skipped")) + disabled = count(suite.attrib.get("disabled", "0")) + testcases = list(suite.findall("./testcase")) + if not name or None in (tests, failures, errors, skipped, disabled) or tests != len(testcases): + report_valid = False + cases: list[dict[str, object]] = [] + for testcase in testcases: + classname = testcase.attrib.get("classname") + case_name = testcase.attrib.get("name") + if not classname or not case_name: + report_valid = False + continue + cases.append({ + "identity": f"{classname}#{case_name}", + "failed": bool(testcase.findall("./failure")), + "errored": bool(testcase.findall("./error")), + "skipped": bool(testcase.findall("./skipped")), + }) + parsed_suites.append({ + "name": name, "tests": tests, "failures": failures, "errors": errors, + "skipped": skipped, "disabled": disabled, "cases": cases, + }) + if not report_valid: + malformed_reports += 1 + continue + parsed_suite_count += len(parsed_suites) + parsed_test_count += sum(int(suite["tests"]) for suite in parsed_suites) + for suite in parsed_suites: + if suite["name"] in required_suite_set: + suites[str(suite["name"])].append(suite) + + problems: list[str] = [] + suite_status: dict[str, tuple[str, dict[str, object] | None]] = {} + for name in required_suites: + matches = suites.get(name, []) + if not matches: + suite_status[name] = ("missing", None) + problems.append(f"Missing required suite: {name}") + continue + if len(matches) != 1: + suite_status[name] = ("duplicate", None) + problems.append(f"Duplicate required suite: {name} ({len(matches)} report(s))") + continue + suite = matches[0] + status = "passed" + if int(suite["tests"]) == 0: + status = "zero tests" + problems.append(f"Required suite has zero tests: {name}") + elif (int(suite["failures"]) or int(suite["errors"]) or int(suite["skipped"]) + or int(suite["disabled"]) or any( + case["failed"] or case["errored"] or case["skipped"] for case in suite["cases"] + )): + status = "failed or skipped" + problems.append(f"Required suite is failing, errored, or skipped: {name}") + suite_status[name] = (status, suite) + + for case_spec in required_cases: + case_suite, _ = case_spec.split("#", 1) + suite = suite_status[case_suite][1] + matches = [case for case in suite["cases"] if case["identity"] == case_spec] if suite else [] + if not matches: + problems.append(f"Missing required case: {case_spec}") + elif len(matches) != 1: + problems.append(f"Duplicate required case: {case_spec} ({len(matches)} execution(s))") + elif matches[0]["failed"] or matches[0]["errored"] or matches[0]["skipped"]: + problems.append(f"Required case did not pass: {case_spec}") + + if malformed_reports: + problems.append(f"Malformed report(s): {malformed_reports}") + print("Strict JUnit proof: passed" if not problems else "Strict JUnit proof: failed") + print(f"Reports: {len(xml_files)}; suites: {parsed_suite_count}; tests: {parsed_test_count}; " + f"malformed reports: {malformed_reports}") + for name in required_suites: + status, suite = suite_status[name] + if suite is None: + print(f"Suite {name}: outcome={status}") + else: + print(f"Suite {name}: tests={suite['tests']} skipped={int(suite['skipped']) + int(suite['disabled'])} " + f"failures={suite['failures']} errors={suite['errors']} outcome={status}") + for case_spec in required_cases: + case_suite, _ = case_spec.split("#", 1) + suite = suite_status[case_suite][1] + matches = [case for case in suite["cases"] if case["identity"] == case_spec] if suite else [] + if not matches: + outcome = "missing" + elif len(matches) != 1: + outcome = "duplicate" + elif matches[0]["failed"]: + outcome = "failure" + elif matches[0]["errored"]: + outcome = "error" + elif matches[0]["skipped"]: + outcome = "skipped" + else: + outcome = "passed" + print(f"Case {case_spec}: executions={len(matches)} outcome={outcome}") + for problem in problems: + print(f"- {problem}") + if not xml_files: + print("No JUnit XML reports were found.") + if problems: + raise SystemExit(1) + + +if strict_mode: + strict_inspection() + raise SystemExit(0) + if not result_root.exists(): print(f"Service: {service_name}") print("No build/test-results directory exists yet.") diff --git a/protos/account/v1/account_gameplay_admission_lease.proto b/protos/account/v1/account_gameplay_admission_lease.proto new file mode 100644 index 0000000000..e94e7e7a7a --- /dev/null +++ b/protos/account/v1/account_gameplay_admission_lease.proto @@ -0,0 +1,160 @@ +syntax = "proto3"; + +package account.v1; + +import "shared/v1/errors.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Planned owner transport only; this schema registers no runtime admission surface. +// Exact same-namespace Game Session mTLS is required. Produced domain denials use typed +// outcomes; validation/authentication, dependency outages and other pre-domain failures use +// canonical non-OK gRPC status with bounded details, never an OK availability result. +service AccountGameplayAdmissionLeaseService { + rpc AcquirePublicGameplayAdmissionLease(AcquirePublicGameplayAdmissionLeaseRequest) + returns (AcquirePublicGameplayAdmissionLeaseResponse); + rpc FinalizeGameplayAdmissionLease(FinalizeGameplayAdmissionLeaseRequest) + returns (FinalizeGameplayAdmissionLeaseResponse); + rpc ReadGameplayAdmissionLease(ReadGameplayAdmissionLeaseRequest) + returns (ReadGameplayAdmissionLeaseResponse); + rpc AbortGameplayAdmissionLease(AbortGameplayAdmissionLeaseRequest) + returns (AbortGameplayAdmissionLeaseResponse); + rpc ReconcileGameplayAdmissionLease(ReconcileGameplayAdmissionLeaseRequest) + returns (ReconcileGameplayAdmissionLeaseResponse); +} + +message AcquirePublicGameplayAdmissionLeaseRequest { + string request_id = 1; + // Initial unscoped LOGIN delegation token, never an admitted PlayerExecutionContext. + // Account verifies the concrete peer and token before any owner SQL source transaction. + string initial_auth_token = 2; + PublicGameplayAdmissionCandidate candidate = 3; + GameplayAdmissionLeaseKind lease_kind = 4; + // Decimal counters retain exact precision; absence is distinct from a default value. + optional string expected_old_binding_generation = 5; + // Required with expected_old_binding_generation for RESUME; absent for NEW_BINDING. + // Presence of RESUME in this schema does not establish implemented resume authority. + optional string resume_episode_id = 6; +} + +enum GameplayAdmissionLeaseKind { + GAMEPLAY_ADMISSION_LEASE_KIND_UNSPECIFIED = 0; + GAMEPLAY_ADMISSION_LEASE_KIND_NEW_BINDING = 1; + GAMEPLAY_ADMISSION_LEASE_KIND_RESUME = 2; +} + +// Selectors and expected correlation only. Account must obtain protected actual target-owner +// evidence; caller values are never World, route, character, coordination or admission proof. +// Account derives the subject, peer, lease ID/fence/deadline and current Account predicates. +message PublicGameplayAdmissionCandidate { + string tenant_id = 1; + string world_slug = 2; + string realm_slug = 3; + string realm_id = 4; + string playable_state_namespace_id = 5; + string playable_state_scope = 6; + string game_instance_id = 7; + string character_id = 8; + string session_id = 9; + string binding_generation = 10; + string catalog_revision = 11; + string pointer_version = 12; + string region_id = 13; + string region_epoch = 14; +} + +// One unchanged closed AccountGameplayAdmissionLeaseEvidence carrier, not a second tuple schema. +// Bytes must be canonical UTF-8 JSON, nonempty and <=64 KiB. Digest is lowercase hexadecimal +// SHA-256 of those exact bytes. request_id must equal the carrier's original requestId. +// Shape/digest validation alone establishes no authenticated receipt or authorization. +message GameplayAdmissionLeaseReference { + string request_id = 1; + bytes evidence_canonical_json = 2; + string evidence_sha256 = 3; +} + +message FinalizeGameplayAdmissionLeaseRequest { + GameplayAdmissionLeaseReference lease = 1; + // Lookup selector only. Account obtains the exact lease-bound PROVISIONAL decision through + // Gameplay's protected CanonicalGameplayAdmissionDecisionOwner transport before finalizing. + string binding_decision_id = 2; +} + +message ReadGameplayAdmissionLeaseRequest { + string request_id = 1; + optional GameplayAdmissionLeaseReference expected_lease = 2; +} + +message AbortGameplayAdmissionLeaseRequest { + GameplayAdmissionLeaseReference lease = 1; + // Absent means no supplied observation/unknown, never proved absence. Never fabricate an ID. + optional string binding_decision_id = 2; +} + +message ReconcileGameplayAdmissionLeaseRequest { + string request_id = 1; + optional GameplayAdmissionLeaseReference expected_lease = 2; + optional string binding_decision_id = 3; +} + +enum GameplayAdmissionLeaseState { + GAMEPLAY_ADMISSION_LEASE_STATE_UNSPECIFIED = 0; + GAMEPLAY_ADMISSION_LEASE_STATE_PENDING = 1; + GAMEPLAY_ADMISSION_LEASE_STATE_COMMITTED = 2; + GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED = 3; +} + +// Reject unspecified/unknown states. COMMITTED requires the exact decision ID. ABORTED requires +// a retained cleanup ID but may have an unknown decision. PENDING has neither ID; COMMITTED has +// no cleanup ID. pending_orphan_cleanup is true exactly for ABORTED, not completed cleanup. +// Storage shape is not authenticated finalization; only the protected real owner supplies that. +message GameplayAdmissionLeaseOperationReadback { + GameplayAdmissionLeaseReference lease = 1; + GameplayAdmissionLeaseState state = 2; + optional string binding_decision_id = 3; + optional string orphan_cleanup_id = 4; + bool pending_orphan_cleanup = 5; +} + +// Storage observation only: never authoritative absence, token retirement, completed cleanup, +// or permission to start a replacement mutation after an uncertain original outcome. +message GameplayAdmissionLeaseNotObserved { + string request_id = 1; +} + +message AcquirePublicGameplayAdmissionLeaseResponse { + oneof outcome { + GameplayAdmissionLeaseOperationReadback operation = 1; + shared.v1.ErrorDetail denied = 2; + } +} + +message FinalizeGameplayAdmissionLeaseResponse { + oneof outcome { + GameplayAdmissionLeaseOperationReadback operation = 1; + shared.v1.ErrorDetail denied = 2; + } +} + +message ReadGameplayAdmissionLeaseResponse { + oneof outcome { + GameplayAdmissionLeaseOperationReadback operation = 1; + GameplayAdmissionLeaseNotObserved not_observed = 2; + } +} + +message AbortGameplayAdmissionLeaseResponse { + oneof outcome { + GameplayAdmissionLeaseOperationReadback operation = 1; + shared.v1.ErrorDetail denied = 2; + } +} + +message ReconcileGameplayAdmissionLeaseResponse { + oneof outcome { + GameplayAdmissionLeaseOperationReadback operation = 1; + GameplayAdmissionLeaseNotObserved not_observed = 2; + shared.v1.ErrorDetail denied = 3; + } +} diff --git a/protos/account/v1/account_issuer_authority_source.proto b/protos/account/v1/account_issuer_authority_source.proto new file mode 100644 index 0000000000..056f26a94a --- /dev/null +++ b/protos/account/v1/account_issuer_authority_source.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Source-only, unregistered owner read. The receiving Account service authenticates the exact +// same-namespace Game Session mTLS peer before opening its issuer-source snapshot. +service AccountIssuerAuthoritySourceService { + rpc ReadCurrentIssuerAuthoritySource(ReadCurrentIssuerAuthoritySourceRequest) + returns (AccountIssuerAuthoritySourceSnapshot); +} + +message ReadCurrentIssuerAuthoritySourceRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string reconciliation_operation_id = 3; + string issuer_id = 4; + optional AccountIssuerAuthoritySourceSnapshot expected_source = 5; +} + +// Closed issuer source carrier. Decimal counters remain strings to preserve exact precision. +// Sequence zero is the original enrollment checkpoint and has no source_event. Positive +// sequences carry the unchanged canonical issuer variant of the Account authority source event. +message AccountIssuerAuthoritySourceSnapshot { + uint32 schema_version = 1; + string target_namespace = 2; + string caller_workload = 3; + string reconciliation_operation_id = 4; + string issuer_id = 5; + string issuer_auth_generation = 6; + string source_version = 7; + string outbox_stream_key = 8; + string last_committed_outbox_sequence = 9; + optional bytes source_event = 10; +} diff --git a/protos/game-design/v1/draft_terminal_service.proto b/protos/game-design/v1/draft_terminal_service.proto new file mode 100644 index 0000000000..499b22a733 --- /dev/null +++ b/protos/game-design/v1/draft_terminal_service.proto @@ -0,0 +1,38 @@ +syntax = "proto3"; + +package game_design.v1; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Opt-in authenticated readback of immutable Game Design Draft terminal evidence. +service GameDesignDraftTerminalReadService { + rpc ReadGameDesignDraftTerminalOutcome(ReadGameDesignDraftTerminalOutcomeRequest) + returns (ReadGameDesignDraftTerminalOutcomeResponse); +} + +enum GameDesignDraftTerminalReadStatus { + GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_UNSPECIFIED = 0; + GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_UNKNOWN = 1; + GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_COMMITTED = 2; + GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED = 3; +} + +message ReadGameDesignDraftTerminalOutcomeRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical Account fence bytes; this is read identity, not permission. + bytes original_account_binding = 4; +} + +message ReadGameDesignDraftTerminalOutcomeResponse { + // The complete request tuple is echoed byte-for-byte, including the original Account binding. + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_account_binding = 4; + GameDesignDraftTerminalReadStatus status = 5; + // Canonical account-draft-owner-readback/v1 bytes. Empty only for UNKNOWN. + bytes owner_readback_bytes = 6; +} diff --git a/protos/game-design/v1/draft_visibility_service.proto b/protos/game-design/v1/draft_visibility_service.proto new file mode 100644 index 0000000000..37d241dd53 --- /dev/null +++ b/protos/game-design/v1/draft_visibility_service.proto @@ -0,0 +1,52 @@ +syntax = "proto3"; + +package gamedesign.v1; + +import "google/protobuf/timestamp.proto"; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Opt-in owner-to-owner read of the durable synchronized Draft visibility fence. +service DraftSynchronizedVisibilityService { + rpc ReadDraftSynchronizedVisibility(ReadDraftSynchronizedVisibilityRequest) + returns (ReadDraftSynchronizedVisibilityResponse); +} + +message DraftVisibilityTarget { + string canonical_tenant_id = 1; + string canonical_version_id = 2; + int64 game_design_version_row_id = 3; + string game_design_version_tenant_key = 4; + int64 source_game_row_id = 5; + string source_game_tenant_key = 6; + string source_provenance_kind = 7; +} + +message ReadDraftSynchronizedVisibilityRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + DraftVisibilityTarget target = 4; +} + +message DraftSynchronizedVisibilityFence { + string request_id = 1; + string commit_id = 2; + string input_digest = 3; + // Exact immutable owner-result vector stored with the durable visibility fence. + string result_vector_json = 4; + google.protobuf.Timestamp created_at = 5; +} + +message ReadDraftSynchronizedVisibilityResponse { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + DraftVisibilityTarget target = 4; + // Exact canonical DraftCommitBinding JSON and its full digest. + string binding_json = 5; + string binding_digest = 6; + string workflow_state = 7; + DraftSynchronizedVisibilityFence fence = 8; +} diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index b7739f7145..fbcb0debfa 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -31,10 +31,16 @@ service GameDesignService { rpc GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse); rpc GetVersionState(GetVersionStateRequest) returns (GetVersionStateResponse); + // Exact current version state for one already-registered authored-world source. + rpc GetAuthoredWorldVersionState(GetAuthoredWorldVersionStateRequest) + returns (GetAuthoredWorldVersionStateResponse); rpc CompareAndSetVersionState(CompareAndSetVersionStateRequest) returns (CompareAndSetVersionStateResponse); rpc ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse); + rpc GetLaunchDescriptor(GetLaunchDescriptorRequest) returns (GetLaunchDescriptorResponse); + rpc GetCompleteLaunchBinding(GetLaunchDescriptorRequest) + returns (GetCompleteLaunchBindingResponse); rpc CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse); rpc ApproveTemplateRemapSet(ApproveTemplateRemapSetRequest) @@ -93,6 +99,7 @@ message WorldDesignMutationRevision { string scope_id = 8; int64 expected_draft_scope_revision_epoch = 9; world_management.v1.WorldDesignScopeMutationPolicy scope_mutation_policy = 10; + world_management.v1.WorldFreshGraphDeclaration fresh_graph_declaration = 11; oneof payload { world_management.v1.RegionDesignMutation region = 20; world_management.v1.ZoneDesignMutation zone = 21; @@ -115,6 +122,11 @@ message PublishVersionRequest { string tenant_id = 1; string notes = 2; string publish_request_id = 3; + + + + + } message PublishVersionResponse { @@ -322,6 +334,54 @@ message GetVersionStateResponse { shared.v1.ErrorDetail error = 2; } +message GetAuthoredWorldVersionStateRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; + int64 version_id = 8; +} + +message GetAuthoredWorldVersionStateResponse { + AuthoredWorldVersionStateEvidence evidence = 1; +} + +message AuthoredWorldVersionStateEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string source_operation_id = 6; + string expected_source_evidence_digest = 7; + int64 version_id = 8; + AuthoredWorldSourceReceipt source_evidence = 9; + VersionLifecycleState version_state = 10; + int64 version_state_epoch = 11; + string evidence_digest = 12; + string canonical_version_id = 13; +} + +// Complete immutable registration receipt, without another RPC's transient read request ID. +message AuthoredWorldSourceReceipt { + int32 schema_version = 1; + string target_namespace = 2; + string registration_request_id = 3; + string operation_id = 4; + string request_digest = 5; + string canonical_tenant_id = 6; + string tenant_slug = 7; + string world_slug = 8; + string world_display_name = 9; + int64 source_game_row_id = 10; + string source_game_tenant_key = 11; + string provenance_kind = 12; + string evidence_digest = 13; +} + message CompareAndSetVersionStateRequest { string tenant_id = 1; int64 version_id = 2; @@ -344,6 +404,11 @@ message ResolveLaunchDescriptorRequest { optional int64 source_version_id = 5; optional int64 target_version_id = 6; optional string requested_runtime_flags_json = 7; + string world_slug = 8; + string authored_world_source_operation_id = 9; + string expected_authored_world_source_evidence_digest = 10; + // Canonical source identity is distinct from the retained legacy tenant selector. + string canonical_tenant_id = 11; } message ResolveLaunchDescriptorResponse { @@ -351,6 +416,28 @@ message ResolveLaunchDescriptorResponse { shared.v1.ErrorDetail error = 2; } +message GetLaunchDescriptorRequest { + string request_id = 1; + string canonical_tenant_id = 2; + string world_slug = 3; + string control_plane_request_id = 4; + string expected_request_digest = 5; + string expected_result_digest = 6; +} + +message GetLaunchDescriptorResponse { + string request_id = 1; + LaunchDescriptor launch_descriptor = 2; + shared.v1.ErrorDetail error = 3; +} + +message GetCompleteLaunchBindingResponse { + string request_id = 1; + LaunchDescriptor launch_descriptor = 2; + AuthoredWorldReleaseAttestationEvidence release_attestation = 3; + shared.v1.ErrorDetail error = 4; +} + message CreateTemplateRemapSetRequest { string tenant_id = 1; int64 source_version_id = 2; @@ -491,6 +578,20 @@ message PublishedReleaseBundle { string workflow_status = 14; string workflow_family = 15; repeated string command_definitions = 16; + string published_release_bundle_ref = 17; + string canonical_tenant_id = 18; + string canonical_version_id = 19; + optional int32 manifest_schema_version = 20; + repeated PublishedArtifactDigest artifact_digests = 21; +} + +message PublishedArtifactDigest { + string usage_key = 1; + string artifact_kind = 2; + string immutable_object_key = 3; + string content_digest = 4; + string content_type = 5; + int32 artifact_schema_version = 6; } message LaunchDescriptor { @@ -506,6 +607,61 @@ message LaunchDescriptor { int64 release_bundle_id = 10; string published_release_bundle_ref = 11; string remap_set_id = 12; + AuthoredWorldLaunchDescriptorEvidence authored_world_binding = 13; + string canonical_tenant_id = 14; +} + +message AuthoredWorldLaunchDescriptorEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string control_plane_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string authored_world_source_operation_id = 6; + string authored_world_source_evidence_digest = 7; + int64 game_template_id = 8; + optional string requested_script_patch_version = 9; + optional int64 source_version_id = 10; + optional int64 target_version_id = 11; + optional string requested_runtime_flags_json = 12; + string request_digest = 13; + string launch_descriptor_id = 14; + int64 version_id = 15; + optional string script_patch_version = 16; + string runtime_flags_json = 17; + string generation_config_revision = 18; + int64 version_state_epoch = 19; + int64 release_bundle_id = 20; + string published_release_bundle_ref = 21; + optional string remap_set_id = 22; + string result_digest = 23; +} + +// Separate closed evidence: never extends or reinterprets descriptor/v1. +message AuthoredWorldReleaseAttestationEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string descriptor_result_digest = 3; + string canonical_tenant_id = 4; + string canonical_version_id = 5; + string world_slug = 6; + string authored_world_source_operation_id = 7; + string authored_world_source_evidence_digest = 8; + string launch_descriptor_id = 9; + string published_release_bundle_ref = 10; + int64 version_state_epoch = 11; + string publish_workflow_id = 12; + string commit_id = 13; + repeated ParticipantDigest participant_digests = 14; + string manifest_hash = 15; + int32 manifest_schema_version = 16; + repeated string required_manifest_asset_keys = 17; + repeated PublishedArtifactDigest artifact_digests = 18; + repeated string command_definitions = 19; + string generation_config_revision = 20; + string evidence_digest = 21; + // Closed original World Account/APPLIED/receipt evidence. Absent in schema 1, required in 2. + optional bytes world_start_location_evidence = 22; } message TemplateRemapSet { @@ -556,6 +712,7 @@ message ParticipantDigest { string applied_commit_id = 3; string content_digest = 4; int32 digest_schema_version = 5; + optional string ability_schema_digest = 6; } enum VersionLifecycleState { diff --git a/protos/game-design/v1/tenant_identity_service.proto b/protos/game-design/v1/tenant_identity_service.proto index 1aedc3deb7..5bfcb367e4 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; // Read-only exact Account/Game Session workload handoff for owner-created tenant evidence. service TenantIdentityService { + // Unregistered authored-world source read; no creation or admission permission. + rpc ResolveAuthoredWorldSource(ResolveAuthoredWorldSourceRequest) + returns (ResolveAuthoredWorldSourceResponse); rpc ResolveFreshTenantCreation(ResolveFreshTenantCreationRequest) returns (ResolveFreshTenantCreationResponse); } @@ -28,3 +31,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/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index adf1810f08..ce60023730 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -4,6 +4,7 @@ package game_session.v1; import "entity-management/v1/entity_management_service.proto"; import "game-design/v1/game_design_service.proto"; +import "google/protobuf/timestamp.proto"; import "shared/v1/errors.proto"; option java_package = "net.firedevops.firemud.gamesession.v1"; @@ -41,6 +42,14 @@ service GameSessionControlPlaneService { // Read exact durable owner proof for a World-owned initial-admission hold. rpc GetInitialAdmissionBindProof(GetInitialAdmissionBindProofRequest) returns (GetInitialAdmissionBindProofResponse); + // Read the exact canonical Game Session-owned initial-admission terminal outcome for World. + rpc GetCanonicalInitialAdmissionOwnerProof( + GetCanonicalInitialAdmissionOwnerProofRequest) + returns (GetCanonicalInitialAdmissionOwnerProofResponse); + // Read the exact Game Session-owned STARTING launch association for World composition. + rpc GetCanonicalGameInstanceLaunchAssociation( + GetCanonicalGameInstanceLaunchAssociationRequest) + returns (GetCanonicalGameInstanceLaunchAssociationResponse); rpc ValidateBuiltInCommandAlias(ValidateBuiltInCommandAliasRequest) returns (ValidateBuiltInCommandAliasResponse); rpc ListAdmissionPointers(ListAdmissionPointersRequest) @@ -500,6 +509,109 @@ message GetInitialAdmissionBindProofResponse { shared.v1.ErrorDetail error = 20; } +enum CanonicalInitialAdmissionOrigin { + CANONICAL_INITIAL_ADMISSION_ORIGIN_UNSPECIFIED = 0; + CANONICAL_INITIAL_ADMISSION_ORIGIN_NO_PRIOR_POINTER = 1; + CANONICAL_INITIAL_ADMISSION_ORIGIN_EXPECT_CLOSED = 2; +} + +enum CanonicalInitialAdmissionOwnerProofOutcome { + CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_UNSPECIFIED = 0; + CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING = 1; + CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED = 2; + CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED = 3; +} + +// World supplies the complete immutable request it acquired the hold for. No numeric runtime +// identifier is substituted for a canonical UUID, and World's hold digest remains distinct from +// the bare Game Session request digest. +message GetCanonicalInitialAdmissionOwnerProofRequest { + string target_namespace = 1; + string initial_admission_request_id = 2; + string initial_admission_request_digest = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string realm_id = 6; + string playable_state_namespace_id = 7; + string playable_state_scope = 8; + string canonical_game_instance_id = 9; + string canonical_version_id = 10; + int64 active_lifecycle_epoch = 11; + int64 expected_catalog_revision = 12; + CanonicalInitialAdmissionOrigin origin = 13; + optional int64 expected_prior_pointer_version = 14; + string hold_id = 15; + string hold_fence = 16; + string hold_binding_digest = 17; +} + +// Every successful domain result echoes the complete expected operation tuple. Only a COMMITTED +// pointer/audit result or a positively fenced durable ABORTED result is terminal proof. Missing +// owner attempts and reads that cannot establish an exact result use non-OK gRPC status, never a +// NOT_FOUND/UNAVAILABLE outcome or an inferred abort. +message GetCanonicalInitialAdmissionOwnerProofResponse { + string target_namespace = 1; + string initial_admission_request_id = 2; + string initial_admission_request_digest = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string realm_id = 6; + string playable_state_namespace_id = 7; + string playable_state_scope = 8; + string canonical_game_instance_id = 9; + string canonical_version_id = 10; + int64 active_lifecycle_epoch = 11; + int64 expected_catalog_revision = 12; + CanonicalInitialAdmissionOrigin origin = 13; + optional int64 expected_prior_pointer_version = 14; + string hold_id = 15; + string hold_fence = 16; + string hold_binding_digest = 17; + CanonicalInitialAdmissionOwnerProofOutcome outcome = 18; + optional int64 committed_pointer_version = 19; + optional int64 audit_event_id = 20; + // Terminal Game Session proof digest; sha256:-prefixed and distinct from the bare request digest. + string proof_digest = 21; + bool positive_durable_abort = 22; + google.protobuf.Timestamp terminal_at = 23; +} + +// A transport retry has a separate read identity and cannot create a new launch operation. +message GetCanonicalGameInstanceLaunchAssociationRequest { + string read_request_id = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string world_slug = 4; + string game_instance_uuid = 5; + string control_plane_request_id = 6; + string launch_descriptor_id = 7; + string expected_descriptor_request_digest = 8; + string expected_descriptor_result_digest = 9; + string expected_release_attestation_evidence_digest = 10; +} + +message GetCanonicalGameInstanceLaunchAssociationResponse { + string read_request_id = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string world_slug = 4; + string game_instance_uuid = 5; + string control_plane_request_id = 6; + string launch_descriptor_id = 7; + string descriptor_request_digest = 8; + string descriptor_result_digest = 9; + string release_attestation_evidence_digest = 10; + string playable_state_namespace_id = 11; + string playable_state_scope = 12; + // Current Game Session row projection only; World lifecycle authority remains separate. + string current_game_instance_status = 13; + int64 current_row_version = 14; + gamedesign.v1.LaunchDescriptor launch_descriptor = 15; + gamedesign.v1.AuthoredWorldReleaseAttestationEvidence release_attestation = 16; + shared.v1.ErrorDetail error = 17; + bool public_production = 18; +} + message GetGameplayCommandStatusRequest { string command_id = 1; string tenant_id = 2; diff --git a/protos/world-management/v1/draft_terminal_service.proto b/protos/world-management/v1/draft_terminal_service.proto new file mode 100644 index 0000000000..b839e55728 --- /dev/null +++ b/protos/world-management/v1/draft_terminal_service.proto @@ -0,0 +1,38 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Opt-in authenticated readback of immutable World Draft terminal evidence. +service WorldDraftTerminalReadService { + rpc ReadWorldDraftTerminalOutcome(ReadWorldDraftTerminalOutcomeRequest) + returns (ReadWorldDraftTerminalOutcomeResponse); +} + +enum WorldDraftTerminalReadStatus { + WORLD_DRAFT_TERMINAL_READ_STATUS_UNSPECIFIED = 0; + WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN = 1; + WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED = 2; + WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED = 3; +} + +message ReadWorldDraftTerminalOutcomeRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical Account fence bytes; this is read identity, not permission. + bytes original_account_binding = 4; +} + +message ReadWorldDraftTerminalOutcomeResponse { + // The complete request tuple is echoed byte-for-byte, including the original Account binding. + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_account_binding = 4; + WorldDraftTerminalReadStatus status = 5; + // Canonical account-draft-owner-readback/v1 bytes. Empty only for UNKNOWN. + bytes owner_readback_bytes = 6; +} diff --git a/protos/world-management/v1/world_canonical_initial_admission_hold.proto b/protos/world-management/v1/world_canonical_initial_admission_hold.proto new file mode 100644 index 0000000000..f33c447ac0 --- /dev/null +++ b/protos/world-management/v1/world_canonical_initial_admission_hold.proto @@ -0,0 +1,45 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Canonical World initial-admission hold owner operations. Runtime composition is explicitly +// opt-in and default-disabled; each operation authenticates the exact Game Session workload. +service WorldCanonicalInitialAdmissionHoldService { + rpc AcquireCanonicalInitialAdmissionHold(AcquireCanonicalInitialAdmissionHoldRequest) + returns (AcquireCanonicalInitialAdmissionHoldResponse); + rpc ReadCanonicalInitialAdmissionHoldIdentity(ReadCanonicalInitialAdmissionHoldIdentityRequest) + returns (ReadCanonicalInitialAdmissionHoldIdentityResponse); +} + +message AcquireCanonicalInitialAdmissionHoldRequest { + // Complete closed canonical World initial-admission hold request bytes. + bytes canonical_hold_request_bytes = 1; + + // Complete closed canonical World lifecycle read request bytes for the exact target. + bytes canonical_lifecycle_read_request_bytes = 2; +} + +message AcquireCanonicalInitialAdmissionHoldResponse { + // Immutable World-issued hold identity, including the exact request bytes and binding digest. + bytes hold_identity_bytes = 1; +} + +message ReadCanonicalInitialAdmissionHoldIdentityRequest { + // Fresh non-nil UUID correlation for this read, in canonical lowercase form. + string read_request_id = 1; + + // Complete closed canonical World initial-admission hold request bytes. + bytes canonical_hold_request_bytes = 2; +} + +message ReadCanonicalInitialAdmissionHoldIdentityResponse { + // Exact correlation echoed from this read request. + string read_request_id = 1; + + // Historical immutable acquisition identity only; this is not terminal state, current + // admission, or an absence checkpoint. + bytes hold_identity_bytes = 2; +} diff --git a/protos/world-management/v1/world_canonical_initial_admission_hold_terminal.proto b/protos/world-management/v1/world_canonical_initial_admission_hold_terminal.proto new file mode 100644 index 0000000000..eed3acd44e --- /dev/null +++ b/protos/world-management/v1/world_canonical_initial_admission_hold_terminal.proto @@ -0,0 +1,32 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Standalone World terminalization surface for one canonical initial-admission hold. +service WorldCanonicalInitialAdmissionHoldTerminalService { + rpc FinalizeCanonicalInitialAdmissionHold( + FinalizeCanonicalInitialAdmissionHoldRequest) + returns (FinalizeCanonicalInitialAdmissionHoldResponse); +} + +message FinalizeCanonicalInitialAdmissionHoldRequest { + // Complete immutable World-issued initial-admission hold identity bytes. + bytes hold_identity_bytes = 1; + + // Requested terminal Game Session owner outcome. PENDING is deliberately not selectable. + ExpectedOutcome expected_outcome = 2; + + enum ExpectedOutcome { + EXPECTED_OUTCOME_UNSPECIFIED = 0; + COMMITTED = 1; + ABORTED = 2; + } +} + +message FinalizeCanonicalInitialAdmissionHoldResponse { + // Complete immutable authenticated Game Session owner proof returned after World finalization. + bytes owner_proof_bytes = 1; +} diff --git a/protos/world-management/v1/world_canonical_instance_activation.proto b/protos/world-management/v1/world_canonical_instance_activation.proto new file mode 100644 index 0000000000..db7fa3ebb7 --- /dev/null +++ b/protos/world-management/v1/world_canonical_instance_activation.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Standalone canonical World owner activation. This is separate from the legacy numeric +// WorldManagementService.ActivatePreparedWorldInstance operation. +service WorldCanonicalInstanceActivationService { + rpc ActivateCanonicalWorldInstance(ActivateCanonicalWorldInstanceRequest) + returns (ActivateCanonicalWorldInstanceResponse); +} + +message ActivateCanonicalWorldInstanceRequest { + // Stable non-nil UUID for the canonical activation operation. + string activation_request_id = 1; + + // Complete original canonical PREPARING lifecycle evidence, including its read correlation. + // These bytes are caller-supplied evidence and do not authenticate a producer or authorize the + // owner operation; World verifies current authority independently. + bytes preparing_lifecycle_evidence_bytes = 2; +} + +message ActivateCanonicalWorldInstanceResponse { + // Stable correlation for this activation operation; it is not an authority claim. + string activation_request_id = 1; + + // Complete immutable canonical World activation result, including its original request proof. + bytes canonical_result_bytes = 2; +} diff --git a/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto b/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto new file mode 100644 index 0000000000..2fe0c25a6b --- /dev/null +++ b/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Read-only complete canonical World lifecycle owner evidence for authenticated Game Session. +service WorldCanonicalInstanceLifecycleReadService { + rpc ReadWorldCanonicalInstanceLifecycle(ReadWorldCanonicalInstanceLifecycleRequest) + returns (ReadWorldCanonicalInstanceLifecycleResponse); +} + +message ReadWorldCanonicalInstanceLifecycleRequest { + // Complete closed versioned WorldCanonicalInstanceLifecycleEvidence.Request bytes. + bytes canonical_request_bytes = 1; +} + +message ReadWorldCanonicalInstanceLifecycleResponse { + // Complete closed evidence bytes, including the exact request echo and full launch binding. + bytes canonical_response_bytes = 1; +} diff --git a/protos/world-management/v1/world_canonical_player_admission_hold.proto b/protos/world-management/v1/world_canonical_player_admission_hold.proto new file mode 100644 index 0000000000..94b82b5b7b --- /dev/null +++ b/protos/world-management/v1/world_canonical_player_admission_hold.proto @@ -0,0 +1,45 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Distinct Account-to-World player-admission hold; neither binding admission nor hold release. +service WorldCanonicalPlayerAdmissionHoldService { + rpc AcquireCanonicalPlayerAdmissionHold(AcquireCanonicalPlayerAdmissionHoldRequest) + returns (AcquireCanonicalPlayerAdmissionHoldResponse); + rpc ReadCanonicalPlayerAdmissionHold(ReadCanonicalPlayerAdmissionHoldRequest) + returns (ReadCanonicalPlayerAdmissionHoldResponse); +} + +message AcquireCanonicalPlayerAdmissionHoldRequest { + // Fresh read correlation, echoed only; never the durable Account lease/attempt identity. + string request_id = 1; + bytes original_lease_json = 2; + string original_lease_sha256 = 3; + string expected_lifecycle_epoch = 4; + string expected_row_version = 5; +} + +message AcquireCanonicalPlayerAdmissionHoldResponse { + string request_id = 1; + string original_lease_sha256 = 2; + bytes hold_evidence_json = 3; + string hold_evidence_sha256 = 4; +} + +message ReadCanonicalPlayerAdmissionHoldRequest { + string request_id = 1; + bytes original_lease_json = 2; + string original_lease_sha256 = 3; + string expected_lifecycle_epoch = 4; + string expected_row_version = 5; +} + +message ReadCanonicalPlayerAdmissionHoldResponse { + string request_id = 1; + string original_lease_sha256 = 2; + bytes hold_evidence_json = 3; + string hold_evidence_sha256 = 4; +} diff --git a/protos/world-management/v1/world_canonical_player_location.proto b/protos/world-management/v1/world_canonical_player_location.proto new file mode 100644 index 0000000000..87558c8ca2 --- /dev/null +++ b/protos/world-management/v1/world_canonical_player_location.proto @@ -0,0 +1,69 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Standalone canonical World initial placement and current-location transport. This is distinct +// from the legacy numeric WorldManagementService surface and is intentionally unregistered. +service WorldCanonicalPlayerLocationService { + rpc PlaceCanonicalInitialPlayerLocation(PlaceCanonicalInitialPlayerLocationRequest) + returns (PlaceCanonicalInitialPlayerLocationResponse); + rpc ReadCanonicalCurrentPlayerLocation(ReadCanonicalCurrentPlayerLocationRequest) + returns (ReadCanonicalCurrentPlayerLocationResponse); +} + +message PlaceCanonicalInitialPlayerLocationRequest { + // Complete closed canonical World initial-placement request bytes. + bytes canonical_request_bytes = 1; + + // Complete original ACTIVE lifecycle evidence bytes, including its read correlation UUID. + bytes original_lifecycle_evidence_bytes = 2; +} + +message PlaceCanonicalInitialPlayerLocationResponse { + // Stable operation UUID from the immutable placement request. + string operation_id = 1; + + // Exact immutable canonical World placement result bytes, including its original request proof. + bytes canonical_result_bytes = 2; +} + +message ReadCanonicalCurrentPlayerLocationRequest { + // Fresh canonical non-nil UUID for this read correlation; it grants no gameplay authority. + string read_request_id = 1; + + // Complete closed canonical placement request bytes, without the lifecycle read correlation. + bytes canonical_placement_request_bytes = 2; + + // Complete current ACTIVE lifecycle evidence for this read correlation. In this RPC these are + // fresh current bytes, distinct from the original lifecycle evidence retained with placement. + bytes original_lifecycle_evidence_bytes = 3; +} + +message ReadCanonicalCurrentPlayerLocationResponse { + // Echo of the fresh read correlation UUID. + string read_request_id = 1; + + // Stable operation UUID of the immutable initial placement. + string placement_operation_id = 2; + + // Exact canonical digest of the immutable placement request. + string placement_request_digest = 3; + + // Complete current ACTIVE lifecycle evidence, including this read's correlation UUID. + bytes current_lifecycle_evidence_bytes = 4; + + // Exact immutable APPLIED placement result bytes retained by World. + bytes immutable_placement_result_bytes = 5; + + // Complete original lifecycle evidence retained with the immutable placement operation. + bytes original_placement_lifecycle_evidence_bytes = 6; + + // Persisted V35 canonicalRegionInstanceId UUID for the current scoped room. + string region_instance_id = 7; + + // Distinct persisted V45 operationalRegionId UUID for the current scoped room. + string operational_region_id = 8; +} diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index d9c7fd624c..f7190a53ca 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -5,6 +5,7 @@ package world_management.v1; import "entity-management/v1/entity_management_service.proto"; import "shared/v1/errors.proto"; import "shared/v1/instance_refs.proto"; +import "world-management/v1/world_canonical_instance_lifecycle_read.proto"; option java_package = "net.firedevops.firemud.worldmanagement.v1"; option java_multiple_files = true; @@ -34,6 +35,94 @@ 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); +} + +// Explicitly unwired Game Session-to-World canonical launch preparation transport. +service WorldCanonicalInstancePreparationService { + rpc PrepareCanonicalWorldInstance(PrepareCanonicalWorldInstanceRequest) + returns (PrepareCanonicalWorldInstanceResponse); +} + +// The exact ten-field committed Game Session launch-association selector. +message PrepareCanonicalWorldInstanceRequest { + string read_request_id = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string world_slug = 4; + string game_instance_uuid = 5; + string control_plane_request_id = 6; + string launch_descriptor_id = 7; + string expected_descriptor_request_digest = 8; + string expected_descriptor_result_digest = 9; + string expected_release_attestation_evidence_digest = 10; +} + +message PrepareCanonicalWorldInstanceResponse { + PrepareCanonicalWorldInstanceRequest request = 1; + ReadWorldCanonicalInstanceLifecycleResponse lifecycle = 2; + shared.v1.ErrorDetail error = 3; +} + +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; @@ -349,6 +438,28 @@ enum WorldDesignAggregateType { WORLD_DESIGN_AGGREGATE_TYPE_WORLD_GENERATION_SUBTREE = 7; } +// Canonical authored room identity for a selected World start location. This is not a runtime +// room instance or a private database key. +message RoomTemplateRef { + string tenant_id = 1; + string version_id = 2; + string room_template_id = 3; +} + +message WorldFreshGraphFamilyCount { + WorldDesignAggregateType family = 1; + // Presence is carried by this repeated entry; zero is an explicit empty-family declaration. + optional int32 count = 2; +} + +// Complete fresh graph declaration bound into the original Game Design revision payload. +message WorldFreshGraphDeclaration { + string tenant_id = 1; + string version_id = 2; + RoomTemplateRef start_location = 3; + repeated WorldFreshGraphFamilyCount family_counts = 4; +} + enum WorldDesignMutationResult { WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED = 0; WORLD_DESIGN_MUTATION_RESULT_APPLIED = 1; diff --git a/protos/world-management/v1/world_published_spawn_requirements.proto b/protos/world-management/v1/world_published_spawn_requirements.proto new file mode 100644 index 0000000000..382f8c06bc --- /dev/null +++ b/protos/world-management/v1/world_published_spawn_requirements.proto @@ -0,0 +1,67 @@ +syntax = "proto3"; + +package world_management.v1; + +import "game-design/v1/game_design_service.proto"; +import "shared/v1/errors.proto"; +import "world-management/v1/world_management_service.proto"; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Exact immutable source read for the verified same-namespace Entity workload. +service WorldPublishedSpawnRequirementsReadService { + rpc ReadWorldPublishedSpawnRequirements(ReadWorldPublishedSpawnRequirementsRequest) + returns (ReadWorldPublishedSpawnRequirementsResponse); +} + +message ReadWorldPublishedSpawnRequirementsRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + gamedesign.v1.GetLaunchDescriptorRequest launch_binding_request = 4; + string expected_release_attestation_digest = 5; +} + +message WorldPublishedSpawnRequirementsFamilyCount { + WorldDesignAggregateType family = 1; + optional int32 count = 2; +} + +message WorldPublishedSpawnRequirementsEntityTemplateReference { + EntityTemplateReferenceType kind = 1; + string tenant_id = 2; + string version_id = 3; + string template_id = 4; +} + +message WorldPublishedSpawnRequirement { + string revision_order = 1; + string revision_id = 2; + string spawn_binding_id = 3; + RoomTemplateRef room_template = 4; + WorldPublishedSpawnRequirementsEntityTemplateReference entity_template = 5; + int32 spawn_count = 6; + int32 respawn_delay_seconds = 7; +} + +message WorldPublishedGenerationRequirement { + string revision_order = 1; + string revision_id = 2; + string rule_template_id = 3; + WorldDesignAggregateType scope_family = 4; + string scope_id = 5; + string name = 6; + string value = 7; +} + +message ReadWorldPublishedSpawnRequirementsResponse { + ReadWorldPublishedSpawnRequirementsRequest request = 1; + gamedesign.v1.GetCompleteLaunchBindingResponse complete_launch_binding = 2; + string capture_id = 3; + string graph_digest = 4; + repeated WorldPublishedSpawnRequirementsFamilyCount family_counts = 5; + repeated WorldPublishedSpawnRequirement spawn_requirements = 6; + repeated WorldPublishedGenerationRequirement generation_requirements = 7; + shared.v1.ErrorDetail error = 8; +} diff --git a/protos/world-management/v1/world_published_start_location_read.proto b/protos/world-management/v1/world_published_start_location_read.proto new file mode 100644 index 0000000000..571992c5f2 --- /dev/null +++ b/protos/world-management/v1/world_published_start_location_read.proto @@ -0,0 +1,60 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Opt-in authenticated readback of the selector in an exact frozen World publication capture. +service WorldPublishedStartLocationReadService { + rpc ReadWorldPublishedStartLocation(ReadWorldPublishedStartLocationRequest) + returns (ReadWorldPublishedStartLocationResponse); +} + +message WorldPublishedStartLocationAffectedTuple { + string owner = 1; + string aggregate_type = 2; + string aggregate_id = 3; + string scope_type = 4; + string scope_id = 5; + string expected_epoch = 6; +} + +message ReadWorldPublishedStartLocationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string canonical_version_id = 4; + string intake_request_id = 5; + string publication_fence = 6; + string publication_request_id = 7; + string request_digest = 8; + int64 version_state_epoch = 9; + string publish_workflow_id = 10; + string applied_commit_id = 11; + string content_digest = 12; + int32 digest_schema_version = 13; + repeated WorldPublishedStartLocationAffectedTuple world_affected_tuples = 14; +} + +message ReadWorldPublishedStartLocationResponse { + // Exact echo of the complete immutable frozen selection request. + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string canonical_version_id = 4; + string intake_request_id = 5; + string publication_fence = 6; + string publication_request_id = 7; + string request_digest = 8; + int64 version_state_epoch = 9; + string publish_workflow_id = 10; + string applied_commit_id = 11; + string content_digest = 12; + int32 digest_schema_version = 13; + repeated WorldPublishedStartLocationAffectedTuple world_affected_tuples = 14; + // Exact original World receipt, Account binding, and APPLIED result bytes. + bytes selector_receipt_bytes = 15; + bytes original_account_binding_bytes = 16; + bytes applied_result_bytes = 17; +} diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 1a362013eb..d1f200b19c 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -2,6 +2,7 @@ apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { + `java-test-fixtures` id("net.firedevops.firemud.secured-stateful-service-conventions") id("net.firedevops.firemud.aop-conventions") id("net.firedevops.firemud.jooq-conventions") @@ -12,7 +13,12 @@ firemudJooq { } dependencies { + testCompileOnly(libs.spotbugs.annotations) + implementation(project(":common-redis-contracts")) + implementation("com.fasterxml.jackson.core:jackson-databind") implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) + testImplementation(testFixtures(project(":account-service"))) + integrationTestImplementation(testFixtures(project(":account-service"))) } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java new file mode 100644 index 0000000000..a2ed5db9ac --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java @@ -0,0 +1,199 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Game Design/World subset recovery consumer. It reads only required owners supported + * by these clients; other missing v2 owners remain pending under the repository's complete-set + * settlement predicate. This component creates no authorization, source mutation or activation. + */ +public final class AccountDraftTerminalReconciliationService { + private final DraftAuthorizationFenceRepository repository; + private final GameDesignDraftTerminalReadClient gameDesignClient; + private final WorldDraftTerminalReadClient worldClient; + private final String namespace; + private final TransactionTemplate ownerTransaction; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected owner repository is intentionally shared, not a value object.") + public AccountDraftTerminalReconciliationService( + DraftAuthorizationFenceRepository repository, + PlatformTransactionManager transactionManager, + GameDesignDraftTerminalReadClient gameDesignClient, + WorldDraftTerminalReadClient worldClient, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient); + this.worldClient = Objects.requireNonNull(worldClient); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical owner workload namespace required"); + } + this.namespace = namespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Recovers only missing exact participant readbacks. A missing or timed-out owner stays unknown; + * the remote reads run between two short Account owner transactions. + */ + public Optional reconcile(UUID operationId) { + DraftAuthorizationFenceBinding.requireUuid(operationId); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Draft terminal recovery cannot join an ambient transaction"); + } + + Optional original = + Objects.requireNonNull( + ownerTransaction.execute( + status -> repository.readOriginalBinding(operationId).map(this::snapshot))); + if (original.isEmpty()) return Optional.empty(); + Snapshot before = original.orElseThrow(); + if (before.ordering() == Ordering.RESERVED || before.settlement() != Settlement.PENDING) { + return Optional.of(before.settlement()); + } + + Optional gameDesignReadback = + before.binding().requiredOwners().contains(Owner.GAME_DESIGN) + && before.gameDesignReadback().isEmpty() + ? readGameDesign(before.binding()) + : Optional.empty(); + Optional worldReadback = + before.binding().requiredOwners().contains(Owner.WORLD) && before.worldReadback().isEmpty() + ? readWorld(before.binding()) + : Optional.empty(); + + Settlement settled = + ownerTransaction.execute( + status -> { + DraftAuthorizationFenceBinding current = + repository + .readOriginalBinding(operationId) + .orElseThrow( + () -> new IllegalStateException("Original Draft operation disappeared")); + if (!Arrays.equals(current.canonicalBytes(), before.binding().canonicalBytes())) { + throw new IllegalStateException("Original Draft binding changed during recovery"); + } + Snapshot after = snapshot(current); + if (after.ordering() != before.ordering()) { + throw new IllegalStateException("Original Draft ordering changed during recovery"); + } + retainExactMissing(current, Owner.GAME_DESIGN, gameDesignReadback, after); + retainExactMissing(current, Owner.WORLD, worldReadback, after); + return repository.readSettlement(current); + }); + return Optional.of(Objects.requireNonNull(settled)); + } + + private Optional readGameDesign(DraftAuthorizationFenceBinding binding) { + GameDesignDraftTerminalReadEvidence.Request request = + GameDesignDraftTerminalReadEvidence.Request.create(namespace, binding.canonicalBytes()); + GameDesignDraftTerminalReadEvidence response = + Objects.requireNonNull(gameDesignClient.read(request)); + if (!request.equals(Objects.requireNonNull(response.request()))) { + throw new IllegalArgumentException( + "Game Design terminal response changed the exact read request"); + } + return Objects.requireNonNull(response.ownerReadback()) + .map(readback -> verifyOwnerReadback(binding, Owner.GAME_DESIGN, readback)); + } + + private Optional readWorld(DraftAuthorizationFenceBinding binding) { + WorldDraftTerminalReadEvidence.Request request = + WorldDraftTerminalReadEvidence.Request.create(namespace, binding.canonicalBytes()); + WorldDraftTerminalReadEvidence response = Objects.requireNonNull(worldClient.read(request)); + if (!request.equals(Objects.requireNonNull(response.request()))) { + throw new IllegalArgumentException("World terminal response changed the exact read request"); + } + return Objects.requireNonNull(response.ownerReadback()) + .map(readback -> verifyOwnerReadback(binding, Owner.WORLD, readback)); + } + + private Snapshot snapshot(DraftAuthorizationFenceBinding binding) { + Ordering ordering = repository.read(binding).ordering(); + Optional gameDesign = readStoredOwnerResult(binding, Owner.GAME_DESIGN); + Optional world = readStoredOwnerResult(binding, Owner.WORLD); + return new Snapshot(binding, ordering, repository.readSettlement(binding), gameDesign, world); + } + + private Optional readStoredOwnerResult( + DraftAuthorizationFenceBinding binding, Owner owner) { + if (!binding.requiredOwners().contains(owner)) return Optional.empty(); + return repository + .readOwnerResult(binding, owner) + .map( + stored -> { + OwnerReadback readback = OwnerReadback.fromStored(stored.readback()); + if (stored.outcome() != readback.outcome()) { + throw new IllegalStateException("Stored Draft outcome differs from its readback"); + } + return verifyOwnerReadback(binding, owner, readback); + }); + } + + private static OwnerReadback verifyOwnerReadback( + DraftAuthorizationFenceBinding binding, Owner expectedOwner, OwnerReadback readback) { + Objects.requireNonNull(readback); + if (readback.owner() != expectedOwner || readback.result().length == 0) { + throw new IllegalArgumentException( + "Owner terminal result is absent or belongs to another owner"); + } + readback.requireBinding(binding); + OwnerReadback decoded = OwnerReadback.fromStored(readback.canonicalBytes()); + decoded.requireBinding(binding); + if (decoded.owner() != expectedOwner + || decoded.outcome() != readback.outcome() + || !Arrays.equals(decoded.result(), readback.result())) { + throw new IllegalArgumentException( + "Owner terminal result differs from its canonical readback"); + } + return decoded; + } + + private void retainExactMissing( + DraftAuthorizationFenceBinding binding, + Owner owner, + Optional candidate, + Snapshot after) { + if (!binding.requiredOwners().contains(owner) || candidate.isEmpty()) return; + OwnerReadback verified = verifyOwnerReadback(binding, owner, candidate.orElseThrow()); + Optional existing = + owner == Owner.GAME_DESIGN ? after.gameDesignReadback() : after.worldReadback(); + if (existing.isPresent()) { + if (!Arrays.equals(existing.orElseThrow().canonicalBytes(), verified.canonicalBytes())) { + throw new IllegalArgumentException("Concurrent owner recovery changed immutable evidence"); + } + return; + } + repository.recordOwnerReadback(binding, verified); + } + + private record Snapshot( + DraftAuthorizationFenceBinding binding, + Ordering ordering, + Settlement settlement, + Optional gameDesignReadback, + Optional worldReadback) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java new file mode 100644 index 0000000000..18d376eecd --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -0,0 +1,765 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.sql.Connection; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired durable ordering component. Every method requires a writable caller READ_COMMITTED + * Account transaction. Callers lock/revalidate actual authority sources first, then this component + * locks sorted source participation rows and sorted operations. Never hold these locks across RPC. + * Reservation and returned source evidence alone grant no owner commit permission. + * + *

Future authenticated capture/source-change and owner-readback producers are mandatory. This + * class does not authenticate supplied evidence or manufacture missing role/terms source state. + */ +public final class DraftAuthorizationFenceRepository { + private static final String FENCES = "account_draft_authorization_fences"; + private static final String SOURCES = "account_draft_authorization_sources"; + private static final String READBACKS = "account_draft_authorization_owner_readbacks"; + private static final String CHANGES = "account_draft_authorization_source_changes"; + private static final String CHANGED = "account_draft_authorization_changed_scopes"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected DSLContext is an internal owner-transaction persistence collaborator.") + public DraftAuthorizationFenceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public enum Ordering { + RESERVED, + COMMIT_ORDER, + REVOKE_ORDER + } + + public enum Settlement { + PENDING, + COMMITTED, + FAILED_NONPUBLICATION + } + + /** Terminal reason for an Account source change that made no source mutation. */ + public enum SourceChangeAbortReason { + EXPIRED, + DEFINITIVE_ABORT + } + + public record FenceSnapshot( + Ordering ordering, byte[] binding, OffsetDateTime reservedAt, OffsetDateTime orderedAt) { + public FenceSnapshot { + binding = binding.clone(); + } + + @Override + public byte[] binding() { + return binding.clone(); + } + } + + public record OwnerResultSnapshot(Outcome outcome, byte[] readback, OffsetDateTime recordedAt) { + public OwnerResultSnapshot { + readback = readback.clone(); + } + + @Override + public byte[] readback() { + return readback.clone(); + } + } + + public record SourceChangeSnapshot( + UUID changeId, + byte[] binding, + String status, + OffsetDateTime requestedAt, + OffsetDateTime committedAt, + OffsetDateTime abortedAt, + SourceChangeAbortReason abortReason) { + public SourceChangeSnapshot { + binding = binding.clone(); + } + + @Override + public byte[] binding() { + return binding.clone(); + } + } + + /** Full exact mutation intent and independently captured affected source vector. */ + public record SourceChange(UUID changeId, List sources, byte[] mutation) { + public SourceChange { + DraftAuthorizationFenceBinding.requireUuid(changeId); + sources = + List.copyOf(Objects.requireNonNull(sources)).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Distinct affected sources required"); + } + mutation = DraftAuthorizationFenceBinding.bytes(mutation); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + @Override + public byte[] mutation() { + return mutation.clone(); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-draft-source-change/v1"); + DraftAuthorizationFenceBinding.frame(out, changeId.toString()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes()); + } + DraftAuthorizationFenceBinding.frame(out, mutation); + return out.toByteArray(); + } + + /** + * Exact recovery of the original vector; callers must never replace it with a fresh capture. + */ + public static SourceChange fromStored(byte[] stored) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect("account-draft-source-change/v1"); + String id = reader.text(); + DraftAuthorizationFenceBinding.canonicalUuid(id); + String count = reader.text(); + DraftAuthorizationFenceBinding.decimal(count, false); + final int size; + try { + size = Integer.parseInt(count); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Stored source count is out of range", invalid); + } + if (size > reader.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Incomplete stored source vector"); + } + java.util.ArrayList sources = new java.util.ArrayList<>(); + for (int i = 0; i < size; i++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + SourceChange change = new SourceChange(UUID.fromString(id), sources, reader.bytes()); + reader.requireEnd(); + if (!Arrays.equals(stored, change.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored source change"); + } + return change; + } + } + + /** + * Already-existing source capture only. Future producer must establish completeness/currentness. + */ + public FenceSnapshot reserve(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + lockSources(binding.sources()); + Record existing = readOperation(binding.operationId()); + if (existing != null) { + return snapshot(requireExact(existing, binding)); + } + if (hasWaitingChange(binding.sources())) { + throw new IllegalStateException("Applicable authority source change is waiting"); + } + dsl.execute( + "INSERT INTO " + + FENCES + + " (operation_id, request_id, commit_id, fence_id, binding, ordering) VALUES (?, ?, ?, ?, ?, 'RESERVED')", + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.canonicalBytes()); + for (SourceEvidence source : binding.sources()) { + dsl.execute( + "INSERT INTO " + + SOURCES + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + source.key(), + source.canonicalBytes()); + } + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** + * Irrevocable exact operation order; revalidate actual source state under its locks before + * calling. + */ + public FenceSnapshot claimCommitOrder(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + lockSources(binding.sources()); + Record row = requireExact(readOperation(binding.operationId()), binding); + Ordering ordering = Ordering.valueOf(row.get("ordering", String.class)); + if (ordering == Ordering.COMMIT_ORDER) { + return snapshot(row); + } + if (ordering == Ordering.REVOKE_ORDER || hasWaitingChange(binding.sources())) { + throw new IllegalStateException("Revocation precedes this owner commit"); + } + dsl.execute( + "UPDATE " + + FENCES + + " SET ordering = 'COMMIT_ORDER', ordered_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND ordering = 'RESERVED'", + binding.operationId()); + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** + * Commit this WAITING result even when false: rolling back would lose revocation intent. True + * means settled or an exact SOURCE_COMMITTED replay; call sourceMutationPermitted before writing. + * A distinct request overlapping an already pending source change is not admitted: it must not + * retain a second old-state capture that becomes stale when the first source change commits. + */ + public boolean requestSourceChange(SourceChange change) { + requireTransaction(); + lockChangedAccounts(change.sources()); + lockSources(change.sources()); + Record prior = readChange(change.changeId()); + if (prior != null) { + requireChange(prior, change); + String priorStatus = prior.get("status", String.class); + if ("SOURCE_COMMITTED".equals(priorStatus)) { + return true; + } + if ("SOURCE_ABORTED".equals(priorStatus)) { + throw new IllegalStateException("Aborted source change cannot be requested again"); + } + if (!"WAITING".equals(priorStatus)) { + throw new IllegalStateException("Source change has an unsupported terminal state"); + } + } else { + if (hasWaitingChange(change.sources())) { + throw new IllegalStateException("Another authority source change is already pending"); + } + dsl.execute( + "INSERT INTO " + CHANGES + " (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change.changeId(), + change.canonicalBytes()); + for (SourceEvidence source : change.sources()) { + dsl.execute( + "INSERT INTO " + CHANGED + " (change_id, source_key) VALUES (?, ?)", + change.changeId(), + source.key()); + } + } + for (UUID operation : affectedOperations(change.sources())) { + Record row = readOperation(operation); + if ("RESERVED".equals(row.get("ordering", String.class))) { + dsl.execute( + "UPDATE " + + FENCES + + " SET ordering = 'REVOKE_ORDER', ordered_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND ordering = 'RESERVED'", + operation); + } + } + return allAffectedSettled(change.sources()); + } + + /** Verify before the first source mutation and retain the transaction through source commit. */ + public boolean sourceMutationPermitted(SourceChange change) { + requireTransaction(); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + return "WAITING".equals(row.get("status", String.class)) + && allAffectedSettled(change.sources()); + } + + /** A no-mutation cancellation is safe only after every affected owner operation is settled. */ + public boolean sourceAbortPermitted(SourceChange change) { + requireTransaction(); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + return "WAITING".equals(row.get("status", String.class)) + && allAffectedSettled(change.sources()); + } + + /** + * Same transaction as actual source mutation/event/readback. No RPC or fake source write here. + */ + public void markSourceCommitted(SourceChange change) { + requireTransaction(); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + String status = row.get("status", String.class); + if ("SOURCE_COMMITTED".equals(status)) { + return; + } + if ("SOURCE_ABORTED".equals(status)) { + throw new IllegalStateException("Aborted source change cannot be committed"); + } + if (!"WAITING".equals(status)) { + throw new IllegalStateException("Source change is not waiting"); + } + if (!allAffectedSettled(change.sources())) { + throw new IllegalStateException("Owner outcomes unresolved"); + } + int updated = + dsl.execute( + "UPDATE " + + CHANGES + + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP" + + " WHERE change_id = ? AND status = 'WAITING'", + change.changeId()); + if (updated != 1) { + throw new IllegalStateException("Draft source change did not commit exactly once"); + } + } + + /** + * Records a terminal no-mutation result. The same ordering-aware settlement predicate used for + * source commit applies: revoke order requires two definitive aborts; commit order requires two + * exact terminal owner readbacks, including a mixed vector. + */ + public void markSourceAborted(SourceChange change, SourceChangeAbortReason reason) { + requireTransaction(); + Objects.requireNonNull(reason, "source-change abort reason"); + lockSources(change.sources()); + Record row = readChange(change.changeId()); + requireChange(row, change); + String status = row.get("status", String.class); + if ("SOURCE_ABORTED".equals(status)) { + if (!reason.name().equals(row.get("abort_reason", String.class))) { + throw new IllegalArgumentException("Source change abort reason differs from readback"); + } + return; + } + if ("SOURCE_COMMITTED".equals(status)) { + throw new IllegalStateException("Committed source change cannot be aborted"); + } + if (!"WAITING".equals(status)) { + throw new IllegalStateException("Source change is not waiting"); + } + if (!allAffectedSettled(change.sources())) { + throw new IllegalStateException("Owner outcomes unresolved"); + } + int updated = + dsl.execute( + "UPDATE " + + CHANGES + + " SET status = 'SOURCE_ABORTED', aborted_at = CURRENT_TIMESTAMP, abort_reason = ?" + + " WHERE change_id = ? AND status = 'WAITING'", + reason.name(), + change.changeId()); + if (updated != 1) { + throw new IllegalStateException("Draft source change did not abort exactly once"); + } + } + + /** Exact durable owner readback, supplied only by the future authenticated owner verifier. */ + public void recordOwnerReadback(DraftAuthorizationFenceBinding binding, OwnerReadback readback) { + requireTransaction(); + readback.requireBinding(binding); + if (!binding.requiredOwners().contains(readback.owner())) { + throw new IllegalArgumentException("Owner is not required by the original Draft operation"); + } + lockSources(binding.sources()); + Record row = requireExact(readOperation(binding.operationId()), binding); + if ("RESERVED".equals(row.get("ordering", String.class))) { + throw new IllegalStateException("Reservation alone cannot produce terminal owner evidence"); + } + Record prior = + dsl.fetchOne( + "SELECT readback FROM " + READBACKS + " WHERE operation_id = ? AND owner = ?", + binding.operationId(), + readback.owner().name()); + if (prior != null) { + if (!Arrays.equals(prior.get("readback", byte[].class), readback.canonicalBytes())) { + throw new IllegalArgumentException("Changed owner terminal evidence"); + } + return; + } + dsl.execute( + "INSERT INTO " + + READBACKS + + " (operation_id, owner, outcome, readback) VALUES (?, ?, ?, ?)", + binding.operationId(), + readback.owner().name(), + readback.outcome().name(), + readback.canonicalBytes()); + } + + public FenceSnapshot read(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + return snapshot(requireExact(readOperation(binding.operationId()), binding)); + } + + /** Derived exact settlement only; original ordering and owner readbacks remain immutable. */ + public Settlement readSettlement(DraftAuthorizationFenceBinding binding) { + requireTransaction(); + Record row = requireExact(readOperation(binding.operationId()), binding); + return settlement(originalBinding(row), Ordering.valueOf(row.get("ordering", String.class))); + } + + /** Original immutable capture only. An absent operation is UNKNOWN, never abort proof. */ + public Optional readOriginalBinding(UUID operationId) { + requireTransaction(); + DraftAuthorizationFenceBinding.requireUuid(operationId); + Record row = readOperation(operationId); + return row == null ? Optional.empty() : Optional.of(originalBinding(row)); + } + + /** Stable keyset position, independent of mutable ordering or participant outcomes. */ + public record RecoveryCursor(OffsetDateTime reservedAt, UUID operationId) { + public RecoveryCursor { + Objects.requireNonNull(reservedAt); + DraftAuthorizationFenceBinding.requireUuid(operationId); + } + } + + public record UnresolvedOperation( + DraftAuthorizationFenceBinding binding, Ordering ordering, RecoveryCursor cursor) {} + + /** + * Bounded discovery of original unsettled operations. Resume after the last returned cursor; an + * empty page ends this pass. Later passes start again to revisit still-pending operations. + * Discovery grants no owner permission and never captures new sources or infers expiry. + * Participant outcomes can advance concurrently: consumers re-read settlement before acting. + */ + public List readUnresolvedOperations(RecoveryCursor after, int limit) { + requireTransaction(); + if (limit < 1 || limit > 100) { + throw new IllegalArgumentException("Recovery page limit must be between 1 and 100"); + } + String pending = " NOT account_draft_authorization_is_settled(f.operation_id)"; + String sql = "SELECT f.* FROM " + FENCES + " f WHERE" + pending; + Object[] parameters; + if (after == null) { + parameters = new Object[] {limit}; + } else { + sql += " AND (f.reserved_at, f.operation_id) > (?::timestamptz, ?::uuid)"; + parameters = new Object[] {after.reservedAt(), after.operationId(), limit}; + } + sql += " ORDER BY f.reserved_at, f.operation_id LIMIT ? FOR UPDATE OF f"; + return dsl.fetch(sql, parameters).stream() + .map( + row -> + new UnresolvedOperation( + originalBinding(row), + Ordering.valueOf(row.get("ordering", String.class)), + new RecoveryCursor( + row.get("reserved_at", OffsetDateTime.class), + row.get("operation_id", UUID.class)))) + .toList(); + } + + private DraftAuthorizationFenceBinding originalBinding(Record row) { + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(row.get("binding", byte[].class)); + requireExact(row, binding); + return binding; + } + + /** Absence means UNKNOWN, never no-commit proof. */ + public Optional readOwnerResult( + DraftAuthorizationFenceBinding binding, Owner owner) { + requireTransaction(); + requireExact(readOperation(binding.operationId()), binding); + Record row = + dsl.fetchOne( + "SELECT owner, outcome, readback, recorded_at FROM " + + READBACKS + + " WHERE operation_id = ? AND owner = ?", + binding.operationId(), + owner.name()); + if (row != null) { + OwnerReadback readback = OwnerReadback.fromStored(row.get("readback", byte[].class)); + readback.requireBinding(binding); + if (!binding.requiredOwners().contains(owner) + || readback.owner() != owner + || !readback.outcome().name().equals(row.get("outcome", String.class)) + || !owner.name().equals(row.get("owner", String.class))) { + throw new IllegalStateException("Owner readback differs from persisted columns"); + } + } + return row == null + ? Optional.empty() + : Optional.of( + new OwnerResultSnapshot( + Outcome.valueOf(row.get("outcome", String.class)), + row.get("readback", byte[].class), + row.get("recorded_at", OffsetDateTime.class))); + } + + /** Durable recovery discovery only; no auto-running worker or authority decision. */ + public List waitingSourceChanges() { + requireTransaction(); + return dsl + .fetch("SELECT * FROM " + CHANGES + " WHERE status = 'WAITING' ORDER BY change_id") + .stream() + .map( + row -> + new SourceChangeSnapshot( + row.get("change_id", UUID.class), + row.get("binding", byte[].class), + row.get("status", String.class), + row.get("requested_at", OffsetDateTime.class), + row.get("committed_at", OffsetDateTime.class), + row.get("aborted_at", OffsetDateTime.class), + abortReason(row.get("abort_reason", String.class)))) + .toList(); + } + + public SourceChangeSnapshot readSourceChange(SourceChange change) { + requireTransaction(); + Record row = readChange(change.changeId()); + requireChange(row, change); + return sourceChangeSnapshot(row); + } + + /** + * Non-locking exact inspection for callers that must preserve Account/envelope/V57 lock order. + */ + public SourceChangeSnapshot inspectSourceChange(SourceChange change) { + requireTransaction(); + Record row = + dsl.fetchOne("SELECT * FROM " + CHANGES + " WHERE change_id = ?", change.changeId()); + if (row == null) { + throw new IllegalArgumentException("Absent or changed immutable source mutation intent"); + } + requireChange(row, change); + return sourceChangeSnapshot(row); + } + + private SourceChangeSnapshot sourceChangeSnapshot(Record row) { + return new SourceChangeSnapshot( + row.get("change_id", UUID.class), + row.get("binding", byte[].class), + row.get("status", String.class), + row.get("requested_at", OffsetDateTime.class), + row.get("committed_at", OffsetDateTime.class), + row.get("aborted_at", OffsetDateTime.class), + abortReason(row.get("abort_reason", String.class))); + } + + private SourceChangeAbortReason abortReason(String value) { + return value == null ? null : SourceChangeAbortReason.valueOf(value); + } + + private void lockSources(List sources) { + for (SourceEvidence source : sources) { + dsl.execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT DO NOTHING", + source.key()); + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + source.key()); + } + } + + /** Account-wide negative intent uses Account-before-source/operation lock order. */ + private void lockChangedAccounts(List sources) { + for (UUID account : + sources.stream() + .filter(s -> s.kind() == SourceKind.ACCOUNT || s.kind() == SourceKind.GLOBAL_ROLES) + .map(s -> UUID.fromString(s.scopeId())) + .distinct() + .sorted(Comparator.comparing(UUID::toString)) + .toList()) { + Record row = + dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ?" + + " AND id > 0 AND account_uuid_source_numeric_id = id" + + " AND account_uuid_provenance IN ('ACCOUNT_V29_MIGRATION'," + + " 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT') FOR UPDATE", + account); + if (row == null) { + throw new IllegalStateException("Source change requires the exact persisted Account row"); + } + } + } + + private boolean hasWaitingChange(List sources) { + for (SourceEvidence source : sources) { + if (!dsl.fetch( + "SELECT c.change_id FROM " + + CHANGES + + " c JOIN " + + CHANGED + + " s ON s.change_id = c.change_id WHERE s.source_key = ? AND c.status = 'WAITING'", + source.key()) + .isEmpty()) { + return true; + } + } + return false; + } + + private List affectedOperations(List sources) { + return sources.stream() + .flatMap( + source -> + dsl + .fetch( + "SELECT operation_id FROM " + SOURCES + " WHERE source_key = ?", + source.key()) + .getValues("operation_id", UUID.class) + .stream()) + .distinct() + .sorted(Comparator.comparing(UUID::toString)) + .toList(); + } + + /** + * Every original required owner must report one uniform exact terminal outcome. Missing or mixed + * evidence always remains pending. + */ + private boolean allAffectedSettled(List sources) { + for (UUID operation : affectedOperations(sources)) { + Record row = readOperation(operation); + if (settlement(originalBinding(row), Ordering.valueOf(row.get("ordering", String.class))) + == Settlement.PENDING) { + return false; + } + } + return true; + } + + private Settlement settlement(DraftAuthorizationFenceBinding binding, Ordering ordering) { + if (ordering == Ordering.RESERVED) { + return Settlement.PENDING; + } + var rows = + dsl.fetch( + "SELECT owner, outcome, readback FROM " + READBACKS + " WHERE operation_id = ?", + binding.operationId()); + if (rows.size() != binding.requiredOwners().size()) { + return Settlement.PENDING; + } + List outcomes = new java.util.ArrayList<>(); + var owners = java.util.EnumSet.noneOf(Owner.class); + for (Record row : rows) { + try { + OwnerReadback readback = OwnerReadback.fromStored(row.get("readback", byte[].class)); + readback.requireBinding(binding); + if (!binding.requiredOwners().contains(readback.owner()) + || !owners.add(readback.owner()) + || !readback.owner().name().equals(row.get("owner", String.class)) + || !readback.outcome().name().equals(row.get("outcome", String.class))) { + return Settlement.PENDING; + } + outcomes.add(readback.outcome()); + } catch (IllegalArgumentException invalidEvidence) { + return Settlement.PENDING; + } + } + boolean bothAborted = outcomes.stream().allMatch(o -> o == Outcome.DEFINITIVELY_ABORTED); + if (ordering == Ordering.REVOKE_ORDER) { + return bothAborted ? Settlement.FAILED_NONPUBLICATION : Settlement.PENDING; + } + if (outcomes.stream().allMatch(o -> o == Outcome.COMMITTED)) { + return Settlement.COMMITTED; + } + return bothAborted ? Settlement.FAILED_NONPUBLICATION : Settlement.PENDING; + } + + private Record readOperation(UUID operation) { + return dsl.fetchOne( + "SELECT * FROM " + FENCES + " WHERE operation_id = ? FOR UPDATE", operation); + } + + private Record readChange(UUID change) { + return dsl.fetchOne("SELECT * FROM " + CHANGES + " WHERE change_id = ? FOR UPDATE", change); + } + + private Record requireExact(Record row, DraftAuthorizationFenceBinding binding) { + if (row == null + || !binding.operationId().equals(row.get("operation_id", UUID.class)) + || !Arrays.equals(row.get("binding", byte[].class), binding.canonicalBytes()) + || !binding.requestId().equals(row.get("request_id", UUID.class)) + || !binding.commitId().equals(row.get("commit_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class))) { + throw new IllegalArgumentException("Absent or changed immutable Draft operation"); + } + List sourceRows = + dsl + .fetch( + "SELECT source_key, source_evidence FROM " + SOURCES + " WHERE operation_id = ?", + binding.operationId()) + .stream() + .sorted(Comparator.comparing(record -> record.get("source_key", String.class))) + .toList(); + if (sourceRows.size() != binding.sources().size()) { + throw new IllegalStateException("Incomplete source participation"); + } + for (int i = 0; i < sourceRows.size(); i++) { + SourceEvidence source = binding.sources().get(i); + if (!source.key().equals(sourceRows.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), sourceRows.get(i).get("source_evidence", byte[].class))) { + throw new IllegalStateException("Source participation differs from exact binding"); + } + } + return row; + } + + private void requireChange(Record row, SourceChange change) { + if (row == null || !Arrays.equals(row.get("binding", byte[].class), change.canonicalBytes())) { + throw new IllegalArgumentException("Absent or changed immutable source mutation intent"); + } + List stored = + dsl + .fetch("SELECT source_key FROM " + CHANGED + " WHERE change_id = ?", change.changeId()) + .getValues("source_key", String.class) + .stream() + .sorted() + .toList(); + if (!stored.equals(change.sources().stream().map(SourceEvidence::key).toList())) { + throw new IllegalStateException("Incomplete source change participation"); + } + } + + private FenceSnapshot snapshot(Record row) { + return new FenceSnapshot( + Ordering.valueOf(row.get("ordering", String.class)), + row.get("binding", byte[].class), + row.get("reserved_at", OffsetDateTime.class), + row.get("ordered_at", OffsetDateTime.class)); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable caller Account transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Transaction-bound writable READ_COMMITTED connection required"); + } + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java new file mode 100644 index 0000000000..f92fc8418f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java @@ -0,0 +1,1260 @@ +package net.firedevops.firemud.accountservice.config; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.IDN; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Independently protected, default-inactive trust for Account's fixed public-JWKS Kubernetes + * ConfigMap calls. This is deliberately not a Spring component: lifecycle wiring must opt in. + */ +public final class AccountJwtJwksApiBinding { + public static final int MAX_BINDING_BYTES = 16 * 1024; + private static final int MAX_CA_BYTES = 128 * 1024; + private static final int MAX_BEARER_BYTES = 16 * 1024; + private static final int MAX_RESPONSE_BYTES = 1024 * 1024; + private static final int MAX_REQUEST_BYTES = 1024 * 1024; + private static final String BINDING_VERSION = "account-jwt-jwks-api-binding/v1"; + private static final String ACCOUNT_SERVICE_ACCOUNT = "account-service"; + private static final Path TRUST_ROOT = Path.of("/etc/firemud/account-jwt-api"); + private static final Path TRUST_BINDING_PATH = TRUST_ROOT.resolve("binding.json"); + private static final Path TRUST_CA_PATH = TRUST_ROOT.resolve("serving-ca.pem"); + + private static final Path TOKEN_ROOT = protectedTokenRoot(); + + private static final Path TOKEN_PATH = TOKEN_ROOT.resolve("token"); + + private static final Path CANONICAL_TOKEN_ROOT = canonicalProjectedTokenRoot(); + + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern NAMESPACE = ENVIRONMENT; + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern BEARER = Pattern.compile("[!-~]{1,16384}"); + private static final Set CONFIG_FIELDS = + Set.of( + "version", + "enabled", + "configRevision", + "environmentId", + "clusterId", + "apiServerUrl", + "tlsServerName", + "servingCaPath", + "servingCaSha256", + "bearerTokenPath", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedApiUsername", + "bindingDigest"); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "Account's bearer credential is read only from this fixed protected projected-token root.") + private static Path protectedTokenRoot() { + return Path.of("/var/run/secrets/firemud/account-jwt-api-token"); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "This exact canonical root remains the only alternate projected-token mount accepted by the protected Account API boundary.") + private static Path canonicalProjectedTokenRoot() { + return Path.of("/run/secrets/firemud/account-jwt-api-token"); + } + + private final boolean enabled; + private final String protectedBindingPath; + private final Duration requestTimeout; + private final ProtectedState testProtectedState; + private final ProtectedPaths protectedPaths; + private final AtomicReference acceptedIdentity = new AtomicReference<>(); + + /** Creates an inert binding. No Spring activation or ambient Kubernetes configuration exists. */ + public AccountJwtJwksApiBinding() { + this(false, ""); + } + + /** + * Creates an explicitly selected binding. The selected file still has to authorize the exact + * Account endpoint, trust anchor, cluster/namespace incarnation, and authenticated principal. + */ + public AccountJwtJwksApiBinding(boolean enabled, String protectedBindingPath) { + this.enabled = enabled; + String configuredPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.protectedBindingPath = + TRUST_BINDING_PATH.toString().equals(configuredPath) ? configuredPath : ""; + this.requestTimeout = Duration.ofSeconds(8); + this.testProtectedState = null; + this.protectedPaths = + new ProtectedPaths( + TRUST_ROOT, TRUST_BINDING_PATH, TRUST_CA_PATH, TOKEN_ROOT, TOKEN_PATH, false); + } + + private AccountJwtJwksApiBinding(Duration requestTimeout, ProtectedState testProtectedState) { + this.enabled = true; + this.protectedBindingPath = ""; + this.requestTimeout = requestTimeout; + this.testProtectedState = testProtectedState; + this.protectedPaths = null; + } + + private AccountJwtJwksApiBinding(String bindingPath, ProtectedPaths protectedPaths) { + this.enabled = true; + this.protectedBindingPath = bindingPath; + this.requestTimeout = Duration.ofSeconds(8); + this.testProtectedState = null; + this.protectedPaths = protectedPaths; + } + + static AccountJwtJwksApiBinding forProtectedFilesTest( + Path bindingPath, Path trustRoot, Path caPath, Path tokenRoot, Path tokenPath) { + Objects.requireNonNull(bindingPath, "test binding path is required"); + Objects.requireNonNull(trustRoot, "test trust root is required"); + Objects.requireNonNull(caPath, "test CA path is required"); + Objects.requireNonNull(tokenRoot, "test token root is required"); + Objects.requireNonNull(tokenPath, "test token path is required"); + Path normalizedBinding = bindingPath.toAbsolutePath().normalize(); + Path normalizedTrustRoot = trustRoot.toAbsolutePath().normalize(); + Path normalizedCa = caPath.toAbsolutePath().normalize(); + Path normalizedTokenRoot = tokenRoot.toAbsolutePath().normalize(); + Path normalizedToken = tokenPath.toAbsolutePath().normalize(); + if (!normalizedBinding.equals(normalizedTrustRoot.resolve("binding.json")) + || !normalizedCa.equals(normalizedTrustRoot.resolve("serving-ca.pem")) + || !normalizedToken.equals(normalizedTokenRoot.resolve("token"))) { + throw new IllegalArgumentException("Protected Account JWT test paths are invalid"); + } + ProtectedPaths paths = + new ProtectedPaths( + normalizedTrustRoot, + normalizedBinding, + normalizedCa, + normalizedTokenRoot, + normalizedToken, + true); + return new AccountJwtJwksApiBinding(normalizedBinding.toString(), paths); + } + + /** + * Supplies trusted in-memory binding material only to package-local transport tests. It still + * exercises the production pinned-CA HTTPS sender and cannot install a custom HTTP client. + */ + static AccountJwtJwksApiBinding forTransportTest( + ParsedBinding binding, byte[] caBytes, String bearerToken, Duration requestTimeout) { + Objects.requireNonNull(binding, "transport test binding is required"); + Objects.requireNonNull(caBytes, "transport test CA is required"); + Objects.requireNonNull(requestTimeout, "transport test timeout is required"); + if (caBytes.length == 0 + || caBytes.length > MAX_CA_BYTES + || !sha256(caBytes).equals(binding.servingCaSha256()) + || !"https".equalsIgnoreCase(binding.apiServer().getScheme()) + || binding.apiServer().getHost() == null + || !binding.apiServer().getHost().equalsIgnoreCase(binding.tlsServerName()) + || !binding + .expectedApiUsername() + .equals("system:serviceaccount:" + binding.namespace() + ":" + ACCOUNT_SERVICE_ACCOUNT) + || bearerToken == null + || !BEARER.matcher(bearerToken).matches() + || requestTimeout.isZero() + || requestTimeout.isNegative() + || requestTimeout.compareTo(Duration.ofSeconds(8)) > 0) { + throw new IllegalArgumentException("Account JWT JWKS transport test binding is invalid"); + } + byte[] caSnapshot = caBytes.clone(); + Set readOnly = Set.of(PosixFilePermission.OWNER_READ); + FileIdentity bindingIdentity = testFileIdentity("test-binding", new byte[] {1}, readOnly); + FileIdentity caIdentity = testFileIdentity("test-ca", caSnapshot, readOnly); + FileIdentity bearerIdentity = + testFileIdentity( + binding.bearerTokenPath().toString(), + bearerToken.getBytes(StandardCharsets.UTF_8), + readOnly); + TrustIdentity identity = + new TrustIdentity( + bindingIdentity, + caIdentity, + credentialPolicy(bearerIdentity), + binding.bindingDigest(), + ""); + return new AccountJwtJwksApiBinding( + requestTimeout, + new ProtectedState(binding, caSnapshot, bearerToken, identity, bearerIdentity)); + } + + /** Returns non-secret pinned endpoint and identity fields after rechecking protected files. */ + public ParsedBinding current() { + if (!enabled || protectedBindingPath.isBlank()) { + throw new BindingRejectedException(); + } + try { + return acceptCurrentProtectedState().config(); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + /** Opens one fixed-endpoint operation with a single bounded bearer snapshot. */ + public ApiOperation beginOperation() { + if (!enabled || protectedBindingPath.isBlank()) { + throw new BindingRejectedException(); + } + try { + return new ApiOperation(acceptCurrentProtectedState()); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + private ApiResponse send(ProtectedState credentialSnapshot, ApiCall call, byte[] requestBody) { + return send(credentialSnapshot, call, requestBody, null); + } + + private ApiResponse send( + ProtectedState credentialSnapshot, + ApiCall call, + byte[] requestBody, + String protectedInventoryPath) { + Objects.requireNonNull(call, "Kubernetes API call is required"); + if (!enabled || protectedBindingPath.isBlank() || credentialSnapshot == null) { + throw new BindingRejectedException(); + } + if (requestBody != null && requestBody.length > MAX_REQUEST_BYTES) { + throw new BindingRejectedException(); + } + validateCallBody(call, requestBody); + ProtectedState state = recheckProtectedState(); + TrustIdentity baseline = acceptedIdentity.get(); + if (!baseline.equals(credentialSnapshot.identity()) + || !credentialSnapshot.bearerIdentity().equals(state.bearerIdentity())) { + throw new BindingRejectedException(); + } + + HttpClient client; + try { + client = createHttpClient(credentialSnapshot.caBytes()); + } catch (Exception ex) { + throw new BindingRejectedException(); + } + if ((call == ApiCall.READ_VALIDATOR_DEPLOYMENT + || call == ApiCall.LIST_VALIDATOR_PODS + || call == ApiCall.READ_VALIDATOR_REPLICA_SET) + != (protectedInventoryPath != null)) { + throw new BindingRejectedException(); + } + URI uri = + credentialSnapshot + .config() + .apiServer() + .resolve( + protectedInventoryPath == null + ? call.path(credentialSnapshot.config().namespace()) + : protectedInventoryPath); + HttpRequest.Builder request = + HttpRequest.newBuilder(uri) + .timeout(requestTimeout) + .header("Accept", "application/json") + .header("Authorization", "Bearer " + credentialSnapshot.bearerToken()); + if (call == ApiCall.PATCH_JWKS_CONFIG_MAP) { + request.header("Content-Type", "application/merge-patch+json"); + } else if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL) { + request.header("Content-Type", "application/json"); + } + if (requestBody == null) { + request.method(call.method(), HttpRequest.BodyPublishers.noBody()); + } else { + request.method(call.method(), HttpRequest.BodyPublishers.ofByteArray(requestBody)); + } + + // Catch changed or withdrawn trust after client construction and immediately before send. + ProtectedState beforeSend = recheckProtectedState(); + if (!baseline.equals(beforeSend.identity()) + || !credentialSnapshot.bearerIdentity().equals(beforeSend.bearerIdentity())) { + throw new BindingRejectedException(); + } + long responseDeadlineNanos = System.nanoTime() + requestTimeout.toNanos(); + try { + HttpResponse response = + client.send(request.build(), HttpResponse.BodyHandlers.ofInputStream()); + try (java.io.InputStream body = response.body()) { + ExecutorService bodyReader = + Executors.newSingleThreadExecutor( + task -> { + Thread thread = new Thread(task, "account-jwks-api-response-reader"); + thread.setDaemon(true); + return thread; + }); + Future bodyFuture = bodyReader.submit(() -> readBounded(body, MAX_RESPONSE_BYTES)); + try { + long remainingNanos = responseDeadlineNanos - System.nanoTime(); + if (remainingNanos <= 0L) { + throw new TimeoutException(); + } + return new ApiResponse( + response.statusCode(), bodyFuture.get(remainingNanos, TimeUnit.NANOSECONDS)); + } catch (TimeoutException ex) { + bodyFuture.cancel(true); + throw new IOException("Kubernetes API response exceeded its deadline"); + } finally { + bodyReader.shutdownNow(); + } + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new ApiTransportException(); + } catch (Exception ex) { + throw new ApiTransportException(); + } + } + + private ProtectedState recheckProtectedState() { + try { + return acceptCurrentProtectedState(); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + /** Strict parser is exposed for deterministic format tests, not as an activation path. */ + public static ParsedBinding parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BINDING_BYTES) { + throw new IllegalArgumentException("Account JWT JWKS API binding is unavailable"); + } + try { + String text = decodeUtf8(bytes); + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || !root.isObject() || root.size() != CONFIG_FIELDS.size()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + Map supplied = new LinkedHashMap<>(); + for (Map.Entry field : root.properties()) { + if (!CONFIG_FIELDS.contains(field.getKey()) + || supplied.putIfAbsent(field.getKey(), field.getValue()) != null) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + } + if (!supplied.keySet().equals(CONFIG_FIELDS) + || !"true".equals(requiredText(root, "enabled", 5)) + || !BINDING_VERSION.equals(requiredText(root, "version", 80))) { + throw new IllegalArgumentException("Account JWT JWKS API binding is disabled"); + } + + String revision = requiredText(root, "configRevision", 128); + String environmentId = requiredText(root, "environmentId", 63); + String clusterId = requiredText(root, "clusterId", 128); + String namespace = requiredText(root, "namespace", 63); + String clusterUid = canonicalUid(requiredText(root, "expectedClusterIncarnationUid", 36)); + String namespaceUid = canonicalUid(requiredText(root, "expectedNamespaceUid", 36)); + String apiUsername = requiredText(root, "expectedApiUsername", 256); + if (!REVISION.matcher(revision).matches() + || !ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !NAMESPACE.matcher(namespace).matches() + || !apiUsername.equals( + "system:serviceaccount:" + namespace + ":" + ACCOUNT_SERVICE_ACCOUNT)) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + + URI apiServer = parseApiServer(requiredText(root, "apiServerUrl", 512)); + String tlsServerName = requiredText(root, "tlsServerName", 253); + String asciiTlsName = canonicalDnsName(tlsServerName); + if (!asciiTlsName.equalsIgnoreCase(apiServer.getHost())) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is not pinned"); + } + String caPath = requiredText(root, "servingCaPath", 1024); + String caSha256 = requiredText(root, "servingCaSha256", 64); + String tokenPath = requiredText(root, "bearerTokenPath", 1024); + if (!SHA256.matcher(caSha256).matches()) { + throw new IllegalArgumentException("Account JWT JWKS API CA pin is malformed"); + } + Path servingCaPath = absoluteProtectedPath(caPath); + Path bearerTokenPath = absoluteProtectedPath(tokenPath); + String suppliedDigest = requiredText(root, "bindingDigest", 64); + if (!SHA256.matcher(suppliedDigest).matches() + || !suppliedDigest.equals(computeBindingDigest(root))) { + throw new IllegalArgumentException("Account JWT JWKS API binding digest is invalid"); + } + return new ParsedBinding( + revision, + environmentId, + clusterId, + apiServer, + asciiTlsName, + servingCaPath, + caSha256, + bearerTokenPath, + namespace, + clusterUid, + namespaceUid, + apiUsername, + suppliedDigest); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + } + + public static String computeBindingDigest(JsonNode protectedBinding) { + if (protectedBinding == null || !protectedBinding.isObject()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + try { + Map content = new LinkedHashMap<>(); + for (String field : CONFIG_FIELDS) { + if (!"bindingDigest".equals(field)) { + JsonNode value = protectedBinding.get(field); + if (value == null || !value.isValueNode()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + content.put(field, value.asText()); + } + } + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8(STRICT_JSON.writeValueAsString(content)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (IOException | NoSuchAlgorithmException | RuntimeException ex) { + throw new IllegalArgumentException("Account JWT JWKS API binding digest is unavailable"); + } + } + + private ProtectedState readCurrentProtectedState() throws Exception { + if (testProtectedState != null) { + return testProtectedState; + } + Path bindingPath = absoluteProtectedPath(protectedBindingPath); + if (protectedPaths == null + || !bindingPath.equals(protectedPaths.bindingPath()) + || (!protectedPaths.testOnly() + && (!bindingPath.equals(TRUST_BINDING_PATH) + || !protectedPaths.trustRoot().equals(TRUST_ROOT) + || !protectedPaths.caPath().equals(TRUST_CA_PATH) + || !protectedPaths.tokenRoot().equals(TOKEN_ROOT) + || !protectedPaths.tokenPath().equals(TOKEN_PATH)))) { + throw new BindingRejectedException(); + } + Path canonicalTokenRoot = resolveTrustedTokenRoot(protectedPaths); + if (!protectedPaths.testOnly()) { + verifyProtectedDirectoryChain(TRUST_ROOT); + verifyProtectedDirectoryChain(canonicalTokenRoot); + } + ProtectedFile bindingFile = readProtectedFile(bindingPath, MAX_BINDING_BYTES); + ParsedBinding config = parseProtectedBytes(bindingFile.bytes()); + if (!config.servingCaPath().equals(protectedPaths.caPath()) + || !config.bearerTokenPath().equals(protectedPaths.tokenPath())) { + throw new BindingRejectedException(); + } + ProtectedFile caFile = readProtectedFile(config.servingCaPath(), MAX_CA_BYTES); + ProtectedFile tokenFile = + readBearerProtectedFile(config.bearerTokenPath(), protectedPaths.tokenRoot()); + String caDigest = sha256(caFile.bytes()); + if (!caDigest.equals(config.servingCaSha256())) { + throw new BindingRejectedException(); + } + String token = decodeUtf8(tokenFile.bytes()); + if (!BEARER.matcher(token).matches()) { + throw new BindingRejectedException(); + } + TrustIdentity identity = + new TrustIdentity( + bindingFile.identity(), + caFile.identity(), + credentialPolicy(tokenFile.identity()), + config.bindingDigest(), + canonicalTokenRoot.toString()); + return new ProtectedState(config, caFile.bytes(), token, identity, tokenFile.identity()); + } + + private static CredentialPolicyIdentity credentialPolicy(FileIdentity identity) { + return new CredentialPolicyIdentity( + identity.path(), identity.ownerUid(), identity.groupId(), identity.permissions()); + } + + private ProtectedState acceptCurrentProtectedState() throws Exception { + ProtectedState state = readCurrentProtectedState(); + TrustIdentity baseline = acceptedIdentity.get(); + if (baseline == null) { + acceptedIdentity.compareAndSet(null, state.identity()); + baseline = acceptedIdentity.get(); + } + if (baseline == null || !baseline.equals(state.identity())) { + throw new BindingRejectedException(); + } + return state; + } + + private static HttpClient createHttpClient(byte[] caBytes) throws Exception { + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + List certificates = + List.copyOf(certificateFactory.generateCertificates(new ByteArrayInputStream(caBytes))); + if (certificates.isEmpty() || certificates.size() > 16) { + throw new BindingRejectedException(); + } + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + int index = 0; + for (Certificate certificate : certificates) { + if (!(certificate instanceof X509Certificate x509)) { + throw new BindingRejectedException(); + } + x509.checkValidity(); + if (x509.getBasicConstraints() < 0) { + throw new BindingRejectedException(); + } + trustStore.setCertificateEntry("account-jwks-ca-" + index++, x509); + } + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustManagers.getTrustManagers(), null); + SSLParameters sslParameters = new SSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + return HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(3)) + .followRedirects(HttpClient.Redirect.NEVER) + .version(HttpClient.Version.HTTP_1_1) + .sslContext(sslContext) + .sslParameters(sslParameters) + .proxy(DIRECT_ONLY_PROXY) + .build(); + } + + private static final ProxySelector DIRECT_ONLY_PROXY = + new ProxySelector() { + @Override + public List select(URI uri) { + return List.of(Proxy.NO_PROXY); + } + + @Override + public void connectFailed(URI uri, SocketAddress address, IOException failure) { + // No proxy exists; connection failures are handled by the bounded API call. + } + }; + + private static byte[] readBounded(java.io.InputStream input, int maximumBytes) + throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(Math.min(maximumBytes, 8192)); + byte[] buffer = new byte[8192]; + int total = 0; + while (true) { + int count = input.read(buffer); + if (count < 0) { + return output.toByteArray(); + } + total += count; + if (total > maximumBytes) { + throw new IOException("Kubernetes API response exceeded its bound"); + } + output.write(buffer, 0, count); + } + } + + private static void validateCallBody(ApiCall call, byte[] body) { + if (call == ApiCall.PATCH_JWKS_CONFIG_MAP) { + if (body == null || body.length == 0) { + throw new BindingRejectedException(); + } + try { + JsonNode patch = STRICT_JSON.readTree(decodeUtf8(body)); + JsonNode metadata = patch == null ? null : patch.get("metadata"); + JsonNode data = patch == null ? null : patch.get("data"); + if (patch == null + || !patch.isObject() + || patch.size() != 2 + || metadata == null + || !metadata.isObject() + || metadata.size() != 2 + || !validUid(text(metadata.get("uid"))) + || !validResourceVersion(text(metadata.get("resourceVersion"))) + || data == null + || !data.isObject() + || data.size() != 2 + || !data.has("jwks.json") + || !data.has("jwt-generation.json") + || !data.get("jwks.json").isTextual() + || !data.get("jwt-generation.json").isTextual() + || data.get("jwks.json").asText().isBlank() + || data.get("jwt-generation.json").asText().isBlank()) { + throw new BindingRejectedException(); + } + JsonNode jwks = STRICT_JSON.readTree(data.get("jwks.json").asText()); + JsonNode keys = jwks == null ? null : jwks.get("keys"); + if (jwks == null + || !jwks.isObject() + || jwks.size() != 1 + || keys == null + || !keys.isArray() + || keys.isEmpty()) { + throw new BindingRejectedException(); + } + for (JsonNode key : keys) { + if (!key.isObject() + || key.has("d") + || key.has("p") + || key.has("q") + || key.has("dp") + || key.has("dq") + || key.has("qi") + || key.has("oth") + || key.has("k")) { + throw new BindingRejectedException(); + } + } + } catch (BindingRejectedException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new BindingRejectedException(); + } + return; + } + if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL) { + String expected = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}"; + if (body == null || !expected.equals(decodeUtf8(body))) { + throw new BindingRejectedException(); + } + return; + } + if (body != null) { + throw new BindingRejectedException(); + } + } + + private static ProtectedFile readProtectedFile(Path path, int maximumBytes) throws IOException { + return readProtectedFile(path, maximumBytes, false); + } + + private static ProtectedFile readBearerProtectedFile(Path configuredPath, Path trustedTokenRoot) + throws IOException { + Path absolute = configuredPath.toAbsolutePath().normalize(); + Path tokenRoot = trustedTokenRoot.toAbsolutePath().normalize(); + if (absolute.getParent() == null + || !absolute.equals(configuredPath) + || !absolute.equals(tokenRoot.resolve("token"))) { + throw new IOException("Protected Account JWT bearer file is unavailable"); + } + Path canonicalTokenRoot = tokenRoot.toRealPath(); + if (!canonicalTokenRoot.equals(tokenRoot) && !canonicalTokenRoot.equals(CANONICAL_TOKEN_ROOT)) { + throw new IOException("Protected Account JWT bearer projection root is invalid"); + } + verifyProtectedDirectory(canonicalTokenRoot); + + BasicFileAttributes linkBefore = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!linkBefore.isSymbolicLink()) { + throw new IOException("Protected Account JWT bearer file is unavailable"); + } + Object linkOwner = Files.getAttribute(absolute, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (!(linkOwner instanceof Number linkUid) || linkUid.longValue() != 0L) { + throw new IOException("Protected Account JWT bearer file ownership is invalid"); + } + + Path target = absolute.toRealPath(); + Path versionDirectory = target.getParent(); + Path targetFileName = target.getFileName(); + Path versionDirectoryFileName = + versionDirectory == null ? null : versionDirectory.getFileName(); + if (!target.startsWith(canonicalTokenRoot) + || versionDirectory == null + || !canonicalTokenRoot.equals(versionDirectory.getParent()) + || targetFileName == null + || !"token".equals(targetFileName.toString()) + || versionDirectoryFileName == null + || !versionDirectoryFileName.toString().matches("\\.\\.[A-Za-z0-9._-]{1,128}")) { + throw new IOException("Protected Account JWT bearer projection is invalid"); + } + ProtectedFile targetFile = readProtectedFile(target, MAX_BEARER_BYTES, true); + Path targetAfter = absolute.toRealPath(); + BasicFileAttributes linkAfter = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Object linkOwnerAfter = Files.getAttribute(absolute, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (!target.equals(targetAfter) + || !sameLinkAttributes(linkBefore, linkAfter) + || !(linkOwnerAfter instanceof Number linkUidAfter) + || linkUidAfter.longValue() != 0L) { + throw new IOException("Protected Account JWT bearer file changed while reading"); + } + + FileIdentity targetIdentity = targetFile.identity(); + return new ProtectedFile( + targetFile.bytes(), + new FileIdentity( + absolute.toString(), + target + "|link=" + String.valueOf(linkBefore.fileKey()), + targetIdentity.size(), + targetIdentity.modifiedMillis(), + targetIdentity.ownerUid(), + targetIdentity.groupId(), + targetIdentity.permissions(), + targetIdentity.contentSha256())); + } + + private static ProtectedFile readProtectedFile( + Path path, int maximumBytes, boolean bearerCredential) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute) || !absolute.equals(absolute.toRealPath())) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0 || before.size() > maximumBytes) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + FileSecurity beforeSecurity = fileSecurity(absolute); + verifyRootOwnedAndNonWritable(absolute); + if (bearerCredential) { + verifyBearerPermissions(absolute, beforeSecurity.permissions()); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + int count = channel.read(buffer); + if (count < 0) { + throw new IOException("Protected Account JWT JWKS file changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected Account JWT JWKS file changed while reading"); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + FileSecurity afterSecurity = fileSecurity(absolute); + if (!sameAttributes(before, after) || !beforeSecurity.equals(afterSecurity)) { + throw new IOException("Protected Account JWT JWKS file changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + if (bearerCredential) { + verifyBearerPermissions(absolute, afterSecurity.permissions()); + } + return new ProtectedFile( + bytes, + new FileIdentity( + absolute.toString(), + String.valueOf(before.fileKey()), + before.size(), + before.lastModifiedTime().toMillis(), + afterSecurity.ownerUid(), + afterSecurity.groupId(), + afterSecurity.permissions(), + sha256(bytes))); + } + + private static FileSecurity fileSecurity(Path file) throws IOException { + Object owner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object group = Files.getAttribute(file, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!(owner instanceof Number ownerUid) || !(group instanceof Number groupId)) { + throw new IOException("Protected Account JWT JWKS file ownership is unavailable"); + } + return new FileSecurity( + ownerUid.longValue(), + groupId.longValue(), + Set.copyOf(Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS))); + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + verifyProtectedDirectory(parent); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + if (!(fileOwner instanceof Number fileUid) || fileUid.longValue() != 0L || writable(fileMode)) { + throw new IOException("Protected Account JWT JWKS file ownership is invalid"); + } + } + + private static void verifyProtectedDirectory(Path directory) throws IOException { + Path normalizedDirectory = directory.toAbsolutePath().normalize(); + Path realDirectory = normalizedDirectory.toRealPath(); + Object directoryOwner = + Files.getAttribute(realDirectory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set directoryMode = + Files.getPosixFilePermissions(realDirectory, LinkOption.NOFOLLOW_LINKS); + if (!realDirectory.equals(normalizedDirectory) + || !Files.isDirectory(realDirectory, LinkOption.NOFOLLOW_LINKS) + || !(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writableByUntrusted(directoryMode)) { + throw new IOException("Protected Account JWT JWKS directory ownership is invalid"); + } + } + + private static Path resolveTrustedTokenRoot(ProtectedPaths paths) throws IOException { + Path lexicalRoot = paths.tokenRoot().toAbsolutePath().normalize(); + Path canonicalRoot = lexicalRoot.toRealPath(); + if (paths.testOnly()) { + if (!canonicalRoot.equals(lexicalRoot)) { + throw new IOException("Protected Account JWT bearer root is unavailable"); + } + } else if (!lexicalRoot.equals(TOKEN_ROOT) + || (!canonicalRoot.equals(TOKEN_ROOT) && !canonicalRoot.equals(CANONICAL_TOKEN_ROOT))) { + throw new IOException("Protected Account JWT bearer root is unavailable"); + } + return canonicalRoot; + } + + private static void verifyProtectedDirectoryChain(Path directory) throws IOException { + Path normalized = directory.toAbsolutePath().normalize(); + Path canonical = normalized.toRealPath(); + if (!normalized.equals(canonical)) { + throw new IOException("Protected Account JWT JWKS directory ownership is invalid"); + } + for (Path current = canonical; current != null; current = current.getParent()) { + verifyProtectedDirectory(current); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static boolean writableByUntrusted(Set permissions) { + return permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static void verifyBearerPermissions(Path file, Set permissions) + throws IOException { + if (!permissions.contains(PosixFilePermission.OWNER_READ) + || !Files.isReadable(file) + || permissions.contains(PosixFilePermission.OTHERS_READ) + || permissions.contains(PosixFilePermission.OWNER_EXECUTE) + || permissions.contains(PosixFilePermission.GROUP_EXECUTE) + || permissions.contains(PosixFilePermission.OTHERS_EXECUTE)) { + throw new IOException("Protected Account JWT bearer file permissions are invalid"); + } + } + + private static boolean validUid(String value) { + return value != null && UID.matcher(value).matches(); + } + + private static boolean validResourceVersion(String value) { + return value != null && value.matches("[!-~]{1,256}"); + } + + private static boolean sameAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static boolean sameLinkAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return before.isSymbolicLink() == after.isSymbolicLink() + && before.isRegularFile() == after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static String requiredText(JsonNode object, String field, int maximumLength) { + JsonNode value = object.get(field); + if (value == null + || !value.isTextual() + || value.asText().isEmpty() + || value.asText().length() > maximumLength) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + return value.asText(); + } + + private static String text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + private static URI parseApiServer(String value) { + try { + URI uri = URI.create(value); + if (!"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getPort() < 1 + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || (uri.getRawPath() != null + && !uri.getRawPath().isEmpty() + && !"/".equals(uri.getRawPath()))) { + throw new IllegalArgumentException("Account JWT JWKS API endpoint is malformed"); + } + return URI.create("https://" + uri.getRawAuthority() + "/"); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Account JWT JWKS API endpoint is malformed"); + } + } + + private static String canonicalDnsName(String value) { + if (value == null || value.isBlank() || value.endsWith(".")) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + try { + String ascii = + IDN.toASCII(value, IDN.USE_STD3_ASCII_RULES).toLowerCase(java.util.Locale.ROOT); + if (ascii.length() > 253 || ascii.startsWith("[") || isIpLiteral(ascii)) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + return ascii; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + } + + private static boolean isIpLiteral(String value) { + return value.matches("[0-9.]+") || value.indexOf(':') >= 0; + } + + private static Path absoluteProtectedPath(String value) { + Path path = Path.of(value); + if (!path.isAbsolute() || !path.normalize().equals(path)) { + throw new IllegalArgumentException("Account JWT JWKS protected path is malformed"); + } + return path; + } + + private static String canonicalUid(String value) { + if (!UID.matcher(value).matches() || "00000000-0000-0000-0000-000000000000".equals(value)) { + throw new IllegalArgumentException("Account JWT JWKS API UID is malformed"); + } + return value; + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException("Account JWT JWKS protected file is not UTF-8"); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception ex) { + throw new IllegalStateException("Account JWT JWKS digest is unavailable"); + } + } + + private static FileIdentity testFileIdentity( + String path, byte[] bytes, Set permissions) { + return new FileIdentity( + path, "test-file-identity:" + path, bytes.length, 1L, 0L, 0L, permissions, sha256(bytes)); + } + + private record ProtectedFile(byte[] bytes, FileIdentity identity) {} + + private record FileSecurity(long ownerUid, long groupId, Set permissions) {} + + private record ProtectedState( + ParsedBinding config, + byte[] caBytes, + String bearerToken, + TrustIdentity identity, + FileIdentity bearerIdentity) {} + + private record TrustIdentity( + FileIdentity binding, + FileIdentity ca, + CredentialPolicyIdentity bearer, + String bindingDigest, + String bearerRootRealPath) {} + + private record CredentialPolicyIdentity( + String path, long ownerUid, long groupId, Set permissions) {} + + private record ProtectedPaths( + Path trustRoot, + Path bindingPath, + Path caPath, + Path tokenRoot, + Path tokenPath, + boolean testOnly) {} + + private record FileIdentity( + String path, + String fileKey, + long size, + long modifiedMillis, + long ownerUid, + long groupId, + Set permissions, + String contentSha256) {} + + public record ParsedBinding( + String configRevision, + String environmentId, + String clusterId, + URI apiServer, + String tlsServerName, + Path servingCaPath, + String servingCaSha256, + Path bearerTokenPath, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedApiUsername, + String bindingDigest) {} + + /** One operation-scoped credential lease; all its API calls use the same bearer snapshot. */ + public final class ApiOperation implements AutoCloseable { + private ProtectedState credentialSnapshot; + + private ApiOperation(ProtectedState credentialSnapshot) { + this.credentialSnapshot = credentialSnapshot; + } + + public ParsedBinding binding() { + if (credentialSnapshot == null) { + throw new BindingRejectedException(); + } + return credentialSnapshot.config(); + } + + public ApiResponse send(ApiCall call, byte[] requestBody) { + return AccountJwtJwksApiBinding.this.send(credentialSnapshot, call, requestBody); + } + + /** Reads one Deployment named by the independently protected validator inventory only. */ + public ApiResponse readValidatorDeployment( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, ApiCall.READ_VALIDATOR_DEPLOYMENT, inventory, validator, null); + } + + /** Lists Pods only by the protected validator selector in the pinned namespace. */ + public ApiResponse listValidatorPods( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, ApiCall.LIST_VALIDATOR_PODS, inventory, validator, continuationToken); + } + + /** Reads one ReplicaSet named by an observed Pod owner reference in the pinned namespace. */ + public ApiResponse readValidatorReplicaSet( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String replicaSetName) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, + ApiCall.READ_VALIDATOR_REPLICA_SET, + inventory, + validator, + null, + replicaSetName); + } + + @Override + public void close() { + credentialSnapshot = null; + } + } + + private ApiResponse sendInventoryRead( + ProtectedState credentialSnapshot, + ApiCall call, + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken) { + return sendInventoryRead( + credentialSnapshot, call, inventory, validator, continuationToken, null); + } + + private ApiResponse sendInventoryRead( + ProtectedState credentialSnapshot, + ApiCall call, + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken, + String replicaSetName) { + if (credentialSnapshot == null + || inventory == null + || validator == null + || !inventory.matchesApiBinding(credentialSnapshot.config()) + || inventory.validators().stream().noneMatch(expected -> expected == validator)) { + throw new BindingRejectedException(); + } + String path; + if (call == ApiCall.READ_VALIDATOR_DEPLOYMENT) { + if (continuationToken != null) { + throw new BindingRejectedException(); + } + path = + "/apis/apps/v1/namespaces/" + + inventory.namespace() + + "/deployments/" + + validator.deploymentName(); + } else if (call == ApiCall.LIST_VALIDATOR_PODS) { + String selector = + validator.selector().entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(entry -> entry.getKey() + "=" + entry.getValue()) + .collect(java.util.stream.Collectors.joining(",")); + path = + "/api/v1/namespaces/" + + inventory.namespace() + + "/pods?labelSelector=" + + queryEncode(selector) + + "&limit=250"; + if (continuationToken != null && !continuationToken.isEmpty()) { + if (continuationToken.length() > 2048 + || !continuationToken.matches("[A-Za-z0-9_./+=-]{1,2048}")) { + throw new BindingRejectedException(); + } + path += "&continue=" + queryEncode(continuationToken); + } + } else if (call == ApiCall.READ_VALIDATOR_REPLICA_SET) { + if (continuationToken != null + || replicaSetName == null + || !replicaSetName.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new BindingRejectedException(); + } + path = "/apis/apps/v1/namespaces/" + inventory.namespace() + "/replicasets/" + replicaSetName; + } else { + throw new BindingRejectedException(); + } + return send(credentialSnapshot, call, null, path); + } + + private static String queryEncode(String value) { + return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20"); + } + + public enum ApiCall { + REVIEW_AUTHENTICATED_PRINCIPAL("POST", "/apis/authentication.k8s.io/v1/selfsubjectreviews"), + READ_KUBE_SYSTEM_NAMESPACE("GET", "/api/v1/namespaces/kube-system"), + READ_TARGET_NAMESPACE("GET", null), + READ_JWKS_CONFIG_MAP("GET", null), + PATCH_JWKS_CONFIG_MAP("PATCH", null), + READ_VALIDATOR_DEPLOYMENT("GET", null), + LIST_VALIDATOR_PODS("GET", null), + READ_VALIDATOR_REPLICA_SET("GET", null); + + private final String method; + private final String fixedPath; + + ApiCall(String method, String fixedPath) { + this.method = method; + this.fixedPath = fixedPath; + } + + public String method() { + return method; + } + + private String path(String namespace) { + return switch (this) { + case REVIEW_AUTHENTICATED_PRINCIPAL, READ_KUBE_SYSTEM_NAMESPACE -> fixedPath; + case READ_TARGET_NAMESPACE -> "/api/v1/namespaces/" + namespace; + case READ_JWKS_CONFIG_MAP, PATCH_JWKS_CONFIG_MAP -> + "/api/v1/namespaces/" + namespace + "/configmaps/jwt-jwks"; + case READ_VALIDATOR_DEPLOYMENT, LIST_VALIDATOR_PODS, READ_VALIDATOR_REPLICA_SET -> + throw new BindingRejectedException(); + }; + } + } + + public record ApiResponse(int statusCode, byte[] body) { + public ApiResponse { + body = body == null ? new byte[0] : body.clone(); + } + + @Override + public byte[] body() { + return body.clone(); + } + } + + public static final class BindingRejectedException extends RuntimeException { + public BindingRejectedException() { + super("Account JWT JWKS API binding is unavailable or changed"); + } + } + + public static final class ApiTransportException extends RuntimeException { + public ApiTransportException() { + super("Account JWT JWKS Kubernetes API request failed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java new file mode 100644 index 0000000000..ecd37c379a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java @@ -0,0 +1,480 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import tools.jackson.databind.json.JsonMapper; + +/** Independently protected, expiring trust for the non-authorizing readiness RPC only. */ +@Component +public final class AccountJwtReadinessTrustBinding { + public static final int MAX_FILE_BYTES = 8 * 1024; + private static final String VERSION = "account-jwt-readiness-trust-binding/v1"; + private static final String VALIDATOR_ID = "account-service"; + private static final String HARNESS_SERVICE_ACCOUNT = "account-jwt-readiness-harness"; + private static final Set REQUIRED_FIELDS = + Set.of( + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedPeerUri", + "peerSpkiSha256Pins", + "validatorId", + "validatorInstanceId", + "validUntilEpochSecond", + "bindingDigest"); + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern INSTANCE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final boolean enabled; + private final String protectedBindingPath; + private final Clock clock; + + @Autowired + public AccountJwtReadinessTrustBinding( + @Value("${firemud.account.jwt-readiness.validation.enabled:false}") boolean enabled, + @Value("${firemud.account.jwt-readiness.validation.protected-binding-path:}") + String protectedBindingPath) { + this(enabled, protectedBindingPath, Clock.systemUTC()); + } + + AccountJwtReadinessTrustBinding(boolean enabled, String protectedBindingPath, Clock clock) { + this.enabled = enabled; + this.protectedBindingPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.clock = Objects.requireNonNull(clock); + } + + /** Missing, disabled, malformed, expired, or mutable trust configuration denies access. */ + public Optional current() { + if (!enabled || protectedBindingPath.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(readProtectedFile(Path.of(protectedBindingPath), clock.instant())); + } catch (Exception ex) { + return Optional.empty(); + } + } + + static Binding parseProtectedBytes(byte[] bytes, long nowEpochSecond) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_FILE_BYTES) { + throw unavailable(); + } + Map fields = parseFields(decodeUtf8(bytes)); + if (!fields.keySet().equals(REQUIRED_FIELDS) || !"true".equals(fields.get("enabled"))) { + throw unavailable(); + } + + String environmentId = fields.get("environmentId"); + String clusterId = fields.get("clusterId"); + String namespace = fields.get("namespace"); + String clusterUid = canonicalUuid(fields.get("expectedClusterIncarnationUid")); + String namespaceUid = canonicalUuid(fields.get("expectedNamespaceUid")); + String revision = fields.get("configRevision"); + String instanceId = fields.get("validatorInstanceId"); + long validUntil = parsePositiveLong(fields.get("validUntilEpochSecond")); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(revision).matches() + || !INSTANCE.matcher(instanceId).matches() + || !VALIDATOR_ID.equals(fields.get("validatorId")) + || nowEpochSecond <= 0L + || nowEpochSecond >= validUntil) { + throw unavailable(); + } + + String expectedUri = fields.get("expectedPeerUri"); + if (!expectedHarnessUri(namespace, expectedUri)) { + throw unavailable(); + } + List pins = parsePins(fields.get("peerSpkiSha256Pins")); + String digest = + computeBindingDigest( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + instanceId, + validUntil); + if (!digest.equals(fields.get("bindingDigest"))) { + throw unavailable(); + } + return new Binding( + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + revision, + VALIDATOR_ID, + instanceId, + validUntil, + digest); + } + + private static Binding readProtectedFile(Path path, java.time.Instant now) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute)) { + throw new IOException("Protected readiness binding is unavailable"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0 || before.size() > MAX_FILE_BYTES) { + throw new IOException("Protected readiness binding is unavailable"); + } + verifyRootOwnedAndNonWritable(absolute); + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw new IOException("Protected readiness binding changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected readiness binding changed while reading"); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime())) { + throw new IOException("Protected readiness binding changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + return parseProtectedBytes(bytes, now.getEpochSecond()); + } + + private static Map parseFields(String text) { + String[] lines = text.split("\n", -1); + int count = lines.length; + if (count > 0 && lines[count - 1].isEmpty()) { + count--; + } + Map fields = new LinkedHashMap<>(); + for (int index = 0; index < count; index++) { + String line = lines[index]; + int separator = line.indexOf('='); + if (line.isEmpty() || separator <= 0 || separator == line.length() - 1) { + throw unavailable(); + } + String key = line.substring(0, separator); + String value = line.substring(separator + 1); + if (!REQUIRED_FIELDS.contains(key) || fields.putIfAbsent(key, value) != null) { + throw unavailable(); + } + } + return fields; + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected readiness binding is unavailable"); + } + Path realParent = parent.toRealPath(); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object directoryOwner = Files.getAttribute(realParent, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + Set directoryMode = Files.getPosixFilePermissions(realParent); + if (!(fileOwner instanceof Number fileUid) + || fileUid.longValue() != 0L + || !(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writable(fileMode) + || writable(directoryMode)) { + throw new IOException("Protected readiness binding ownership is invalid"); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw unavailable(); + } + } + + private static List parsePins(String value) { + String[] parts = value.split(",", -1); + if (parts.length == 0 || parts.length > 8) { + throw unavailable(); + } + List pins = new ArrayList<>(parts.length); + for (String pin : parts) { + if (!SHA256.matcher(pin).matches() || pins.contains(pin)) { + throw unavailable(); + } + pins.add(pin); + } + return List.copyOf(pins); + } + + private static boolean expectedHarnessUri(String namespace, String uri) { + return ("spiffe://firemud/ns/" + namespace + "/sa/" + HARNESS_SERVICE_ACCOUNT).equals(uri); + } + + private static String canonicalUuid(String value) { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value) || new UUID(0L, 0L).equals(uuid)) { + throw unavailable(); + } + return uuid.toString(); + } + + private static long parsePositiveLong(String value) { + try { + long result = Long.parseLong(value); + if (result <= 0L || !Long.toString(result).equals(value)) { + throw unavailable(); + } + return result; + } catch (NumberFormatException ex) { + throw unavailable(); + } + } + + public static String computeBindingDigest( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List pins, + String validatorInstanceId, + long validUntilEpochSecond) { + try { + Map binding = new LinkedHashMap<>(); + binding.put("digestVersion", VERSION); + binding.put("configRevision", configRevision); + binding.put("environmentId", environmentId); + binding.put("clusterId", clusterId); + binding.put("namespace", namespace); + binding.put("expectedClusterIncarnationUid", expectedClusterIncarnationUid); + binding.put("expectedNamespaceUid", expectedNamespaceUid); + binding.put("expectedPeerUri", expectedPeerUri); + binding.put("peerSpkiSha256Pins", List.copyOf(pins)); + binding.put("validatorId", VALIDATOR_ID); + binding.put("validatorInstanceId", validatorInstanceId); + binding.put("validUntilEpochSecond", validUntilEpochSecond); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(binding)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException ex) { + throw new IllegalStateException("Readiness binding digest is unavailable"); + } + } + + public static PeerIdentity identifyPeer(java.security.cert.Certificate[] certificates) { + if (certificates == null || certificates.length == 0) { + throw new PeerIdentityRejectedException(); + } + if (!(certificates[0] instanceof X509Certificate certificate)) { + throw new PeerIdentityRejectedException(); + } + try { + certificate.checkValidity(); + Collection> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); + if (subjectAlternativeNames == null) { + throw new PeerIdentityRejectedException(); + } + String foundUri = null; + int uriCount = 0; + for (List entry : subjectAlternativeNames) { + if (entry.size() < 2 || !(entry.get(0) instanceof Integer type) || type != 6) { + continue; + } + uriCount++; + if (!(entry.get(1) instanceof String uri)) { + throw new PeerIdentityRejectedException(); + } + foundUri = uri; + } + if (uriCount != 1 || foundUri == null) { + throw new PeerIdentityRejectedException(); + } + String spki = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(certificate.getPublicKey().getEncoded())); + return new PeerIdentity(foundUri, spki); + } catch (CertificateException | NoSuchAlgorithmException ex) { + throw new PeerIdentityRejectedException(); + } + } + + private static IllegalArgumentException unavailable() { + return new IllegalArgumentException("Readiness trust binding is unavailable"); + } + + public static boolean matchesPeer( + java.security.cert.Certificate[] certificates, Binding binding) { + if (binding == null) { + return false; + } + try { + PeerIdentity peer = identifyPeer(certificates); + return binding.matches(peer); + } catch (RuntimeException rejected) { + return false; + } + } + + public record PeerIdentity(String uri, String spkiSha256) {} + + /** + * Configured per-validator-instance identity; this is not proof of pod UID or fleet inventory. + */ + public record Binding( + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List peerSpkiSha256Pins, + String configRevision, + String validatorId, + String validatorInstanceId, + long validUntilEpochSecond, + String bindingDigest) { + public Binding { + Objects.requireNonNull(environmentId); + Objects.requireNonNull(clusterId); + Objects.requireNonNull(namespace); + Objects.requireNonNull(expectedClusterIncarnationUid); + Objects.requireNonNull(expectedNamespaceUid); + Objects.requireNonNull(expectedPeerUri); + peerSpkiSha256Pins = List.copyOf(peerSpkiSha256Pins); + Objects.requireNonNull(configRevision); + Objects.requireNonNull(validatorInstanceId); + Objects.requireNonNull(bindingDigest); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(configRevision).matches() + || !INSTANCE.matcher(validatorInstanceId).matches() + || !VALIDATOR_ID.equals(validatorId) + || peerSpkiSha256Pins.isEmpty() + || peerSpkiSha256Pins.size() > 8 + || validUntilEpochSecond <= 0L + || !SHA256.matcher(bindingDigest).matches() + || !expectedHarnessUri(namespace, expectedPeerUri) + || !peerSpkiSha256Pins.stream().allMatch(pin -> SHA256.matcher(pin).matches()) + || peerSpkiSha256Pins.stream().distinct().count() != peerSpkiSha256Pins.size()) { + throw unavailable(); + } + UUID clusterUid = UUID.fromString(expectedClusterIncarnationUid); + UUID namespaceUid = UUID.fromString(expectedNamespaceUid); + if (!clusterUid.toString().equals(expectedClusterIncarnationUid) + || !namespaceUid.toString().equals(expectedNamespaceUid) + || clusterUid.equals(new UUID(0L, 0L)) + || namespaceUid.equals(new UUID(0L, 0L))) { + throw unavailable(); + } + String expectedDigest = + computeBindingDigest( + configRevision, + environmentId, + clusterId, + namespace, + expectedClusterIncarnationUid, + expectedNamespaceUid, + expectedPeerUri, + peerSpkiSha256Pins, + validatorInstanceId, + validUntilEpochSecond); + if (!expectedDigest.equals(bindingDigest)) { + throw unavailable(); + } + } + + public boolean isCurrentAt(long nowEpochSecond) { + return nowEpochSecond > 0L && nowEpochSecond < validUntilEpochSecond; + } + + public boolean matches(PeerIdentity peer) { + if (peer == null || !expectedPeerUri.equals(peer.uri())) { + return false; + } + try { + byte[] actual = HexFormat.of().parseHex(peer.spkiSha256()); + boolean matched = false; + for (String pin : peerSpkiSha256Pins) { + matched |= MessageDigest.isEqual(actual, HexFormat.of().parseHex(pin)); + } + return matched; + } catch (IllegalArgumentException malformedPeer) { + return false; + } + } + } + + public static final class PeerIdentityRejectedException extends RuntimeException { + public PeerIdentityRejectedException() { + super("Readiness caller identity is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java new file mode 100644 index 0000000000..71ba3c2455 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java @@ -0,0 +1,404 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import tools.jackson.databind.json.JsonMapper; + +/** + * Reads the independently protected trust binding for Account's narrow JWT materializer RPCs. The + * file must be root-owned and non-writable by the Account/materializer workload. It is read again + * for every RPC so pin rotation or trust withdrawal takes effect without process restart. + */ +@Component +public final class AccountJwtSignerMaterializerTrustBinding { + public static final int MAX_FILE_BYTES = 8 * 1024; + private static final String VERSION = "account-jwt-signer-materializer-binding/v1"; + private static final Set REQUIRED_FIELDS = + Set.of( + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedPeerUri", + "peerSpkiSha256Pins", + "bindingDigest"); + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final boolean enabled; + private final String protectedBindingPath; + + public AccountJwtSignerMaterializerTrustBinding( + @Value("${firemud.account.jwt-signer.materialization.enabled:false}") boolean enabled, + @Value("${firemud.account.jwt-signer.materialization.protected-binding-path:}") + String protectedBindingPath) { + this.enabled = enabled; + this.protectedBindingPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + } + + /** Missing, disabled, malformed, or mutable trust configuration always means no access. */ + public Optional current() { + if (!enabled || protectedBindingPath.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(readProtectedFile(Path.of(protectedBindingPath))); + } catch (Exception ex) { + // Never expose config contents, file paths, or certificate details through RPC errors. + return Optional.empty(); + } + } + + /** Testable parser boundary; production calls still require the protected-file checks above. */ + static AccountJwtSignerMaterializerTrustBinding.Binding parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_FILE_BYTES) { + throw new IllegalArgumentException("JWT materializer trust binding is unavailable"); + } + String text = decodeUtf8(bytes); + String[] lines = text.split("\n", -1); + int count = lines.length; + if (count > 0 && lines[count - 1].isEmpty()) { + count--; + } + Map fields = new LinkedHashMap<>(); + for (int index = 0; index < count; index++) { + String line = lines[index]; + int separator = line.indexOf('='); + if (line.isEmpty() || separator <= 0 || separator == line.length() - 1) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + String key = line.substring(0, separator); + String value = line.substring(separator + 1); + if (!REQUIRED_FIELDS.contains(key) || fields.putIfAbsent(key, value) != null) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + } + if (!fields.keySet().equals(REQUIRED_FIELDS) || !"true".equals(fields.get("enabled"))) { + throw new IllegalArgumentException("JWT materializer trust binding is disabled"); + } + + String environmentId = fields.get("environmentId"); + String clusterId = fields.get("clusterId"); + String namespace = fields.get("namespace"); + String clusterUid = canonicalUuid(fields.get("expectedClusterIncarnationUid")); + String namespaceUid = canonicalUuid(fields.get("expectedNamespaceUid")); + String revision = fields.get("configRevision"); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(revision).matches()) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + String expectedUri = fields.get("expectedPeerUri"); + if (!validExpectedPeerUri(namespace, expectedUri)) { + throw new IllegalArgumentException("JWT materializer workload identity is not canonical"); + } + List pins = parsePins(fields.get("peerSpkiSha256Pins")); + String digest = + computeBindingDigest( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins); + if (!digest.equals(fields.get("bindingDigest"))) { + throw new IllegalArgumentException("JWT materializer trust binding digest is invalid"); + } + return new AccountJwtSignerMaterializerTrustBinding.Binding( + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + revision, + digest); + } + + private static Binding readProtectedFile(Path path) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute)) { + throw new IOException("Protected Account JWT materializer binding is not a regular file"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile()) { + throw new IOException("Protected Account JWT materializer binding is not a regular file"); + } + verifyRootOwnedAndNonWritable(absolute); + if (before.size() <= 0 || before.size() > MAX_FILE_BYTES) { + throw new IOException("Protected Account JWT materializer binding size is invalid"); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + int count = channel.read(buffer); + if (count < 0) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime())) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + return parseProtectedBytes(bytes); + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected Account JWT materializer binding is unavailable"); + } + Path realParent = parent.toRealPath(); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object directoryOwner = Files.getAttribute(realParent, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + Set directoryMode = Files.getPosixFilePermissions(realParent); + if (!(fileOwner instanceof Number fileUid) + || fileUid.longValue() != 0L + || !(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writable(fileMode) + || writable(directoryMode)) { + throw new IOException("Protected Account JWT materializer binding ownership is invalid"); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException("JWT materializer trust binding is not UTF-8", ex); + } + } + + private static List parsePins(String value) { + String[] parts = value.split(",", -1); + if (parts.length == 0 || parts.length > 8) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + List pins = new ArrayList<>(parts.length); + for (String pin : parts) { + if (!SHA256.matcher(pin).matches() || pins.contains(pin)) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + pins.add(pin); + } + return List.copyOf(pins); + } + + private static boolean validExpectedPeerUri(String namespace, String uri) { + String prefix = "spiffe://firemud/ns/" + namespace + "/sa/"; + return uri != null + && uri.startsWith(prefix) + && ENVIRONMENT.matcher(uri.substring(prefix.length())).matches(); + } + + private static String canonicalUuid(String value) { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value) || new UUID(0L, 0L).equals(uuid)) { + throw new IllegalArgumentException("JWT materializer trust UID is malformed"); + } + return uuid.toString(); + } + + public static String computeBindingDigest( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List pins) { + try { + Map binding = new LinkedHashMap<>(); + binding.put("digestVersion", VERSION); + binding.put("configRevision", configRevision); + binding.put("environmentId", environmentId); + binding.put("clusterId", clusterId); + binding.put("namespace", namespace); + binding.put("expectedClusterIncarnationUid", expectedClusterIncarnationUid); + binding.put("expectedNamespaceUid", expectedNamespaceUid); + binding.put("expectedPeerUri", expectedPeerUri); + binding.put("peerSpkiSha256Pins", List.copyOf(pins)); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(binding)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (Exception ex) { + throw new IllegalStateException("JWT materializer trust binding digest is unavailable", ex); + } + } + + public static boolean matchesPeer( + java.security.cert.Certificate[] peerCertificates, Binding binding) { + if (peerCertificates == null || peerCertificates.length == 0 || binding == null) { + return false; + } + if (!(peerCertificates[0] instanceof X509Certificate certificate)) { + return false; + } + try { + certificate.checkValidity(); + Collection> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); + if (subjectAlternativeNames == null) { + return false; + } + String foundUri = null; + int uriCount = 0; + for (List entry : subjectAlternativeNames) { + if (entry.size() < 2 || !(entry.get(0) instanceof Integer type) || type != 6) { + continue; + } + uriCount++; + if (!(entry.get(1) instanceof String uri)) { + return false; + } + foundUri = uri; + } + if (uriCount != 1 || !binding.expectedPeerUri().equals(foundUri)) { + return false; + } + byte[] spkiDigest = + MessageDigest.getInstance("SHA-256").digest(certificate.getPublicKey().getEncoded()); + byte[] configuredPin = HexFormat.of().parseHex(binding.peerSpkiSha256Pins().get(0)); + boolean matched = MessageDigest.isEqual(spkiDigest, configuredPin); + for (int index = 1; index < binding.peerSpkiSha256Pins().size(); index++) { + byte[] pin = HexFormat.of().parseHex(binding.peerSpkiSha256Pins().get(index)); + matched |= MessageDigest.isEqual(spkiDigest, pin); + } + return matched; + } catch (CertificateException | NoSuchAlgorithmException | RuntimeException ex) { + return false; + } + } + + public record Binding( + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List peerSpkiSha256Pins, + String configRevision, + String bindingDigest) { + public Binding { + Objects.requireNonNull(environmentId, "Environment identity is required"); + Objects.requireNonNull(clusterId, "Cluster identity is required"); + Objects.requireNonNull(namespace, "Namespace identity is required"); + canonicalUuid(expectedClusterIncarnationUid); + canonicalUuid(expectedNamespaceUid); + Objects.requireNonNull(expectedPeerUri, "Materializer URI identity is required"); + peerSpkiSha256Pins = List.copyOf(peerSpkiSha256Pins); + if (peerSpkiSha256Pins.isEmpty() || peerSpkiSha256Pins.size() > 8) { + throw new IllegalArgumentException("JWT materializer certificate pins are unavailable"); + } + for (String pin : peerSpkiSha256Pins) { + if (!SHA256.matcher(pin).matches()) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + } + Objects.requireNonNull(configRevision, "Materializer trust revision is required"); + if (!REVISION.matcher(configRevision).matches() || !SHA256.matcher(bindingDigest).matches()) { + throw new IllegalArgumentException("JWT materializer trust binding digest is malformed"); + } + if (peerSpkiSha256Pins.stream().distinct().count() != peerSpkiSha256Pins.size()) { + throw new IllegalArgumentException("JWT materializer certificate pins are duplicated"); + } + AccountJwtSignerDesiredStateRepository.Binding stateBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + environmentId, + clusterId, + namespace, + AccountJwtSignerDesiredStateRepository.CustodyMode + .INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + if (!validExpectedPeerUri(stateBinding.namespace(), expectedPeerUri)) { + throw new IllegalArgumentException("JWT materializer workload identity is not canonical"); + } + String expectedDigest = + computeBindingDigest( + configRevision, + environmentId, + clusterId, + namespace, + expectedClusterIncarnationUid, + expectedNamespaceUid, + expectedPeerUri, + peerSpkiSha256Pins); + if (!expectedDigest.equals(bindingDigest)) { + throw new IllegalArgumentException("JWT materializer trust binding digest is invalid"); + } + } + + public AccountJwtSignerDesiredStateRepository.Binding accountBinding() { + return new AccountJwtSignerDesiredStateRepository.Binding( + environmentId, + clusterId, + namespace, + AccountJwtSignerDesiredStateRepository.CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java new file mode 100644 index 0000000000..1afe45ef49 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java @@ -0,0 +1,678 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Default-inactive, independently protected expected validator applicability and runtime pins. + * + *

This binding is an operator-installed input, never learned from Kubernetes labels, caller + * claims, a first read, or the readiness plan's partial applicability matrix. It provides no + * readiness, promotion, or per-validator acceptance authority. + */ +public final class AccountJwtValidatorInventoryBinding { + public static final int MAX_BINDING_BYTES = 32 * 1024; + public static final int MAX_RUNTIME_CONFIG_BYTES = 8 * 1024; + public static final Path PROTECTED_BINDING_PATH = + Path.of("/etc/firemud/account-jwt-api/validator-inventory.json"); + private static final Path PROTECTED_ROOT = Path.of("/etc/firemud/account-jwt-api"); + private static final String VERSION = "account-jwt-validator-inventory-binding/v1"; + private static final String RUNTIME_CONFIG_ENV = "FIREMUD_JWT_VERIFIER_CONFIG"; + private static final Set ROOT_FIELDS = + Set.of( + "version", + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "apiBindingRevision", + "apiBindingDigest", + "validators", + "bindingDigest"); + private static final Set VALIDATOR_FIELDS = + Set.of( + "validatorId", + "deploymentName", + "deploymentUid", + "selector", + "replicas", + "containerName", + "image", + "jwksUri", + "maxCacheAgeSeconds", + "profiles"); + private static final Set PROFILE_FIELDS = Set.of("tokenProfile", "audience"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Pattern DNS_LABEL = Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern ENVIRONMENT = DNS_LABEL; + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = CLUSTER; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern LABEL_KEY = + Pattern.compile( + "[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?(?:/[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?"); + private static final Pattern LABEL_VALUE = + Pattern.compile("(?:[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?"); + private static final Pattern PROFILE = Pattern.compile("[a-z][a-z0-9-]{0,63}"); + private static final Pattern AUDIENCE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}"); + + private final boolean enabled; + private final String configuredPath; + private final AtomicReference acceptedFile = new AtomicReference<>(); + + /** Creates a disabled binding; production composition must opt in with the one fixed path. */ + public AccountJwtValidatorInventoryBinding() { + this(false, ""); + } + + public AccountJwtValidatorInventoryBinding(boolean enabled, String protectedBindingPath) { + this.enabled = enabled; + String path = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.configuredPath = PROTECTED_BINDING_PATH.toString().equals(path) ? path : ""; + } + + /** Returns the exact immutable protected expectations, or empty when disabled/unavailable. */ + public java.util.Optional current() { + if (!enabled || configuredPath.isBlank()) { + return java.util.Optional.empty(); + } + try { + ProtectedFile file = readProtectedFile(PROTECTED_BINDING_PATH); + ProtectedInventory parsed = parseProtectedBytes(file.bytes()); + FileIdentity existing = acceptedFile.get(); + if (existing == null) { + acceptedFile.compareAndSet(null, file.identity()); + existing = acceptedFile.get(); + } + if (!file.identity().equals(existing)) { + throw unavailable(); + } + return java.util.Optional.of(parsed); + } catch (RuntimeException | IOException failure) { + return java.util.Optional.empty(); + } + } + + static ProtectedInventory parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BINDING_BYTES) { + throw unavailable(); + } + try { + JsonNode root = JSON.readTree(decodeUtf8(bytes)); + requireObjectFields(root, ROOT_FIELDS); + if (!VERSION.equals(requiredText(root, "version", 96)) + || !"true".equals(requiredText(root, "enabled", 5))) { + throw unavailable(); + } + String revision = requiredText(root, "configRevision", 128); + String environmentId = requiredText(root, "environmentId", 63); + String clusterId = requiredText(root, "clusterId", 128); + String namespace = requiredText(root, "namespace", 63); + String clusterUid = canonicalUid(requiredText(root, "expectedClusterIncarnationUid", 36)); + String namespaceUid = canonicalUid(requiredText(root, "expectedNamespaceUid", 36)); + String apiRevision = requiredText(root, "apiBindingRevision", 128); + String apiDigest = requiredText(root, "apiBindingDigest", 64); + String digest = requiredText(root, "bindingDigest", 64); + if (!REVISION.matcher(revision).matches() + || !ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !DNS_LABEL.matcher(namespace).matches() + || !REVISION.matcher(apiRevision).matches() + || !SHA256.matcher(apiDigest).matches() + || !SHA256.matcher(digest).matches() + || !digest.equals(computeBindingDigest(root))) { + throw unavailable(); + } + List validators = parseValidators(root.get("validators")); + if (validators.isEmpty() || validators.size() > 32) { + throw unavailable(); + } + return new ProtectedInventory( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + apiRevision, + apiDigest, + digest, + validators); + } catch (IllegalArgumentException failure) { + throw unavailable(); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + public static String computeBindingDigest(JsonNode root) { + try { + requireObjectFields(root, ROOT_FIELDS); + Map value = new LinkedHashMap<>(); + for (String field : ROOT_FIELDS) { + if (!"bindingDigest".equals(field)) { + JsonNode node = root.get(field); + value.put(field, JSON.readValue(JSON.writeValueAsString(node), Object.class)); + } + } + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException failure) { + throw unavailable(); + } + } + + private static List parseValidators(JsonNode node) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > 32) { + throw unavailable(); + } + List result = new ArrayList<>(); + Set ids = new LinkedHashSet<>(); + Set deployments = new LinkedHashSet<>(); + for (JsonNode validator : node) { + requireObjectFields(validator, VALIDATOR_FIELDS); + String id = requiredText(validator, "validatorId", 63); + String deployment = requiredText(validator, "deploymentName", 63); + String deploymentUid = canonicalUid(requiredText(validator, "deploymentUid", 36)); + String container = requiredText(validator, "containerName", 63); + String image = requiredText(validator, "image", 512); + String jwksUri = canonicalJwksUri(requiredText(validator, "jwksUri", 512)); + int replicas = exactInt(validator.get("replicas"), 1, 128); + int maximumCacheAge = exactInt(validator.get("maxCacheAgeSeconds"), 1, 300); + if (!DNS_LABEL.matcher(id).matches() + || !DNS_LABEL.matcher(deployment).matches() + || !DNS_LABEL.matcher(container).matches() + || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}") + || !ids.add(id) + || !deployments.add(deployment)) { + throw unavailable(); + } + Map selector = parseSelector(validator.get("selector")); + List profiles = parseProfiles(validator.get("profiles")); + if (profiles.isEmpty()) { + throw unavailable(); + } + String runtimeConfig = canonicalRuntimeConfig(jwksUri, maximumCacheAge, profiles); + if (runtimeConfig.getBytes(StandardCharsets.UTF_8).length > MAX_RUNTIME_CONFIG_BYTES) { + throw unavailable(); + } + result.add( + new ValidatorExpectation( + id, + deployment, + deploymentUid, + selector, + replicas, + container, + image, + jwksUri, + maximumCacheAge, + profiles, + runtimeConfig)); + } + return List.copyOf(result); + } + + private static Map parseSelector(JsonNode node) { + if (node == null || !node.isObject() || node.isEmpty() || node.size() > 16) { + throw unavailable(); + } + Map selector = new LinkedHashMap<>(); + for (Map.Entry entry : node.properties()) { + if (!LABEL_KEY.matcher(entry.getKey()).matches() + || !entry.getValue().isTextual() + || !LABEL_VALUE.matcher(entry.getValue().asText()).matches()) { + throw unavailable(); + } + selector.put(entry.getKey(), entry.getValue().asText()); + } + return Map.copyOf(selector); + } + + private static List parseProfiles(JsonNode node) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > 32) { + throw unavailable(); + } + List profiles = new ArrayList<>(); + Set unique = new LinkedHashSet<>(); + for (JsonNode profile : node) { + requireObjectFields(profile, PROFILE_FIELDS); + String name = requiredText(profile, "tokenProfile", 64); + String audience = requiredText(profile, "audience", 256); + if (!PROFILE.matcher(name).matches() + || !AUDIENCE.matcher(audience).matches() + || !unique.add(name + "\u0000" + audience)) { + throw unavailable(); + } + profiles.add(new ProfileExpectation(name, audience)); + } + profiles.sort( + Comparator.comparing(ProfileExpectation::tokenProfile) + .thenComparing(ProfileExpectation::audience)); + return List.copyOf(profiles); + } + + private static String canonicalRuntimeConfig( + String jwksUri, int maxCacheAgeSeconds, List profiles) { + try { + List> profileValues = + profiles.stream() + .map( + profile -> + Map.of( + "tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .toList(); + Map runtime = + Map.of( + "algorithm", + "RS256", + "jwksUri", + jwksUri, + "maxCacheAgeSeconds", + maxCacheAgeSeconds, + "profiles", + profileValues); + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(runtime)), + StandardCharsets.UTF_8); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static String canonicalJwksUri(String value) { + try { + java.net.URI uri = java.net.URI.create(value); + if (!"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || !"/.well-known/jwks.json".equals(uri.getRawPath())) { + throw unavailable(); + } + return uri.toASCIIString(); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static ProtectedFile readProtectedFile(Path path) throws IOException { + if (!path.equals(PROTECTED_BINDING_PATH) + || Files.isSymbolicLink(path) + || !path.equals(path.toRealPath())) { + throw unavailable(); + } + verifyProtectedDirectory(PROTECTED_ROOT); + BasicFileAttributes before = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Set mode = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + Object owner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object group = Files.getAttribute(path, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() + || before.size() <= 0 + || before.size() > MAX_BINDING_BYTES + || !(owner instanceof Number uid) + || uid.longValue() != 0L + || !(group instanceof Number gid) + || writable(mode) + || !mode.contains(PosixFilePermission.OWNER_READ) + || mode.contains(PosixFilePermission.OTHERS_READ)) { + throw unavailable(); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw unavailable(); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw unavailable(); + } + } + BasicFileAttributes after = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Set afterMode = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + Object afterOwner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object afterGroup = Files.getAttribute(path, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!sameAttributes(before, after) + || !mode.equals(afterMode) + || !Objects.equals(owner, afterOwner) + || !Objects.equals(group, afterGroup)) { + throw unavailable(); + } + FileIdentity identity = + new FileIdentity( + String.valueOf(before.fileKey()), + before.size(), + before.lastModifiedTime().toMillis(), + uid.longValue(), + gid.longValue(), + Set.copyOf(mode), + sha256(bytes)); + return new ProtectedFile(bytes, identity); + } + + private static void verifyProtectedDirectory(Path directory) throws IOException { + if (!directory.equals(directory.toRealPath()) + || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) { + throw unavailable(); + } + Object owner = Files.getAttribute(directory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set mode = + Files.getPosixFilePermissions(directory, LinkOption.NOFOLLOW_LINKS); + if (!(owner instanceof Number uid) + || uid.longValue() != 0L + || mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE)) { + throw unavailable(); + } + } + + private static void requireObjectFields(JsonNode node, Set expected) { + if (node == null || !node.isObject() || node.size() != expected.size()) { + throw unavailable(); + } + for (Map.Entry field : node.properties()) { + if (!expected.contains(field.getKey()) + || field.getValue() == null + || field.getValue().isNull()) { + throw unavailable(); + } + } + } + + private static String requiredText(JsonNode node, String field, int maximumLength) { + JsonNode value = node.get(field); + if (value == null + || !value.isTextual() + || value.asText().isBlank() + || value.asText().length() > maximumLength) { + throw unavailable(); + } + return value.asText(); + } + + private static int exactInt(JsonNode node, int minimum, int maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToInt()) { + throw unavailable(); + } + int value = node.intValue(); + if (value < minimum || value > maximum) { + throw unavailable(); + } + return value; + } + + private static String canonicalUid(String uid) { + if (!UID.matcher(uid).matches() || uid.startsWith("00000000-")) { + throw unavailable(); + } + return uid; + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException failure) { + throw unavailable(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw unavailable(); + } + } + + private static boolean sameAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static boolean writable(Set mode) { + return mode.contains(PosixFilePermission.OWNER_WRITE) + || mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Protected Account validator inventory binding is unavailable"); + } + + private record FileIdentity( + String fileKey, + long size, + long modifiedMillis, + long ownerUid, + long groupId, + Set permissions, + String contentSha256) {} + + private record ProtectedFile(byte[] bytes, FileIdentity identity) {} + + /** An immutable, file-backed expected inventory; no public constructor or mutation exists. */ + public static final class ProtectedInventory { + private final String configRevision; + private final String environmentId; + private final String clusterId; + private final String namespace; + private final String expectedClusterIncarnationUid; + private final String expectedNamespaceUid; + private final String apiBindingRevision; + private final String apiBindingDigest; + private final String bindingDigest; + private final List validators; + + private ProtectedInventory( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String bindingDigest, + List validators) { + this.configRevision = configRevision; + this.environmentId = environmentId; + this.clusterId = clusterId; + this.namespace = namespace; + this.expectedClusterIncarnationUid = expectedClusterIncarnationUid; + this.expectedNamespaceUid = expectedNamespaceUid; + this.apiBindingRevision = apiBindingRevision; + this.apiBindingDigest = apiBindingDigest; + this.bindingDigest = bindingDigest; + this.validators = List.copyOf(validators); + } + + public boolean matchesApiBinding(AccountJwtJwksApiBinding.ParsedBinding binding) { + return binding != null + && configRevision != null + && environmentId.equals(binding.environmentId()) + && clusterId.equals(binding.clusterId()) + && namespace.equals(binding.namespace()) + && expectedClusterIncarnationUid.equals(binding.expectedClusterIncarnationUid()) + && expectedNamespaceUid.equals(binding.expectedNamespaceUid()) + && apiBindingRevision.equals(binding.configRevision()) + && apiBindingDigest.equals(binding.bindingDigest()); + } + + public String configRevision() { + return configRevision; + } + + public String environmentId() { + return environmentId; + } + + public String clusterId() { + return clusterId; + } + + public String namespace() { + return namespace; + } + + public String expectedClusterIncarnationUid() { + return expectedClusterIncarnationUid; + } + + public String expectedNamespaceUid() { + return expectedNamespaceUid; + } + + public String apiBindingRevision() { + return apiBindingRevision; + } + + public String apiBindingDigest() { + return apiBindingDigest; + } + + public String bindingDigest() { + return bindingDigest; + } + + public List validators() { + return validators; + } + } + + public static final class ValidatorExpectation { + private final String validatorId; + private final String deploymentName; + private final String deploymentUid; + private final Map selector; + private final int replicas; + private final String containerName; + private final String image; + private final String jwksUri; + private final int maxCacheAgeSeconds; + private final List profiles; + private final String canonicalRuntimeConfig; + + private ValidatorExpectation( + String validatorId, + String deploymentName, + String deploymentUid, + Map selector, + int replicas, + String containerName, + String image, + String jwksUri, + int maxCacheAgeSeconds, + List profiles, + String canonicalRuntimeConfig) { + this.validatorId = validatorId; + this.deploymentName = deploymentName; + this.deploymentUid = deploymentUid; + this.selector = Map.copyOf(selector); + this.replicas = replicas; + this.containerName = containerName; + this.image = image; + this.jwksUri = jwksUri; + this.maxCacheAgeSeconds = maxCacheAgeSeconds; + this.profiles = List.copyOf(profiles); + this.canonicalRuntimeConfig = canonicalRuntimeConfig; + } + + public String validatorId() { + return validatorId; + } + + public String deploymentName() { + return deploymentName; + } + + public String deploymentUid() { + return deploymentUid; + } + + public Map selector() { + return selector; + } + + public int replicas() { + return replicas; + } + + public String containerName() { + return containerName; + } + + public String image() { + return image; + } + + public String jwksUri() { + return jwksUri; + } + + public int maxCacheAgeSeconds() { + return maxCacheAgeSeconds; + } + + public List profiles() { + return profiles; + } + + public String canonicalRuntimeConfig() { + return canonicalRuntimeConfig; + } + } + + public record ProfileExpectation(String tokenProfile, String audience) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundle.java new file mode 100644 index 0000000000..54188382cf --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundle.java @@ -0,0 +1,808 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed canonical Account-owned {@code account-auth-evidence-bundle/v1} value for the explicitly + * non-tenant Game Session-to-Account delegation. + * + *

This codec validates shape and canonical bytes only. It does not establish that owner source + * rows, event history, cutoff applicability, or the caller are authentic/current. The DTO itself is + * never proof; the Account repository must derive and persist it only from locked owner readback. + */ +public final class AccountAuthEvidenceBundle { + public static final String SCHEMA = "account-auth-evidence-bundle/v1"; + // The existing Account response-envelope AEAD binding accepts at most 8 KiB for this value. + public static final int MAX_CANONICAL_BYTES = 8 * 1024; + + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern EVENT_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern UUID_TEXT = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern V4_UUID_TEXT = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("0|[1-9][0-9]{0,18}"); + private static final Pattern POSITIVE_XID8 = Pattern.compile("[1-9][0-9]{0,19}"); + private static final Pattern WORKLOAD = + Pattern.compile( + "^spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$"); + + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "bundleRef", + "snapshotIdentity", + "evaluationIdentity", + "issuer", + "profile", + "audience", + "scope", + "operation", + "tokenIdentity", + "authorityTuple", + "issuanceFence", + "membershipVersion", + "authoritySourceVersions", + "accountIdentitySource", + "outboxCheckpoints"); + private static final Set BUNDLE_REF_FIELDS = + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization"); + private static final Set SCOPE_FIELDS = Set.of("kind", "accountId", "tenantIds"); + private static final Set OPERATION_FIELDS = + Set.of( + "operationId", + "requestId", + "requestDigest", + "callerWorkload", + "callerContextId", + "accountId"); + private static final Set TOKEN_IDENTITY_FIELDS = + Set.of("jti", "tokenGeneration", "iat", "nbf", "exp"); + private static final Set AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set OPTIONAL_AUTHORITY_TUPLE_FIELDS = + Set.of("accountSecurityCutoff"); + private static final Set AUTHORITY_SOURCE_VERSION_FIELDS = + Set.of("issuerSourceVersion", "accountSourceVersion", "issuanceFenceSourceVersion"); + private static final Set ACCOUNT_IDENTITY_FIELDS = + Set.of("sourceRowId", "provenance", "sourceNumericId"); + private static final Set OUTBOX_CHECKPOINT_FIELDS = + Set.of("outboxStreamKey", "outboxSequence", "sourceEventId", "sourceEventDigest"); + private static final Set ZERO_OUTBOX_CHECKPOINT_FIELDS = + Set.of("outboxStreamKey", "outboxSequence"); + private static final Set ACCOUNT_SECURITY_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String PROFILE = GameSessionAccountDelegationProfile.PROFILE; + private static final String AUDIENCE = GameSessionAccountDelegationProfile.AUDIENCE; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final Map fields; + private final byte[] canonicalBytes; + + private AccountAuthEvidenceBundle(Map fields, byte[] canonicalBytes) { + this.fields = immutableMap(fields); + this.canonicalBytes = canonicalBytes.clone(); + } + + /** + * Encodes the supplied closed value. This factory is not an authenticity boundary; production + * persistence must derive the values from locked owner readback and independently compare all + * source rows and event payloads. + */ + public static AccountAuthEvidenceBundle fromOwnerEvaluation(OwnerEvaluation evaluation) { + Objects.requireNonNull(evaluation, "Account owner evaluation is required"); + Map fields = fields(evaluation); + validateFields(fields); + return canonicalValue(fields); + } + + /** Strictly parses the exact closed canonical bundle encoding. */ + public static AccountAuthEvidenceBundle parseCanonical(byte[] value) { + if (value == null || value.length == 0 || value.length > MAX_CANONICAL_BYTES) { + throw invalid("Account auth-evidence bundle is absent or exceeds its byte bound"); + } + String text = strictUtf8(value); + final Map parsed; + try { + parsed = JSON.readValue(text, new TypeReference<>() {}); + } catch (RuntimeException ex) { + throw invalid("Account auth-evidence bundle JSON is malformed"); + } + validateFields(parsed); + byte[] canonical = canonicalize(text); + if (!Arrays.equals(value, canonical)) { + throw invalid("Account auth-evidence bundle bytes are not canonical"); + } + return new AccountAuthEvidenceBundle(parsed, canonical); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** Lowercase SHA-256 digest of these exact canonical bytes. */ + public String canonicalSha256() { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(canonicalBytes)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable"); + } + } + + public Map fields() { + return immutableMap(fields); + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof AccountAuthEvidenceBundle bundle + && Arrays.equals(canonicalBytes, bundle.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + @Override + public String toString() { + return "AccountAuthEvidenceBundle[redacted]"; + } + + private static Map fields(OwnerEvaluation evaluation) { + Map root = new LinkedHashMap<>(); + root.put("schema", SCHEMA); + Map ref = new LinkedHashMap<>(); + ref.put("bundleVersion", evaluation.bundleReference().bundleVersion()); + ref.put("sourceVersion", evaluation.bundleReference().sourceVersion()); + ref.put("sourceFence", evaluation.bundleReference().sourceFence()); + ref.put("linearization", evaluation.bundleReference().linearization()); + root.put("bundleRef", ref); + root.put("snapshotIdentity", evaluation.snapshotIdentity()); + root.put("evaluationIdentity", evaluation.evaluationIdentity()); + root.put("issuer", ISSUER); + root.put("profile", PROFILE); + root.put("audience", AUDIENCE); + + Map scope = new LinkedHashMap<>(); + scope.put("kind", "account"); + scope.put("accountId", evaluation.accountId().toString()); + scope.put("tenantIds", List.of()); + root.put("scope", scope); + + OperationIdentity operation = evaluation.operation(); + Map operationFields = new LinkedHashMap<>(); + operationFields.put("operationId", operation.operationId().toString()); + operationFields.put("requestId", operation.requestId().toString()); + operationFields.put("requestDigest", operation.requestDigest()); + operationFields.put("callerWorkload", operation.callerWorkload()); + operationFields.put("callerContextId", operation.callerContextId().toString()); + operationFields.put("accountId", operation.accountId().toString()); + root.put("operation", operationFields); + + TokenIdentity token = evaluation.token(); + Map tokenFields = new LinkedHashMap<>(); + tokenFields.put("jti", token.jti().toString()); + tokenFields.put("tokenGeneration", Long.toString(token.tokenGeneration())); + tokenFields.put("iat", token.issuedAtEpochSecond()); + tokenFields.put("nbf", token.notBeforeEpochSecond()); + tokenFields.put("exp", token.expiresAtEpochSecond()); + root.put("tokenIdentity", tokenFields); + + root.put("authorityTuple", deepCopyMap(evaluation.authorityTuple())); + root.put("issuanceFence", decimal(evaluation.issuanceFence())); + root.put("membershipVersion", Map.of()); + + AuthoritySourceVersions sourceVersions = evaluation.authoritySourceVersions(); + Map versions = new LinkedHashMap<>(); + versions.put("issuerSourceVersion", decimal(sourceVersions.issuerSourceVersion())); + versions.put("accountSourceVersion", decimal(sourceVersions.accountSourceVersion())); + versions.put( + "issuanceFenceSourceVersion", decimal(sourceVersions.issuanceFenceSourceVersion())); + root.put("authoritySourceVersions", versions); + + AccountIdentitySource accountSource = evaluation.accountIdentitySource(); + Map accountIdentity = new LinkedHashMap<>(); + accountIdentity.put("sourceRowId", decimal(accountSource.sourceRowId())); + accountIdentity.put("provenance", accountSource.provenance().name()); + accountIdentity.put("sourceNumericId", decimal(accountSource.sourceNumericId())); + root.put("accountIdentitySource", accountIdentity); + + List> checkpoints = new ArrayList<>(); + for (OutboxCheckpoint checkpoint : evaluation.outboxCheckpoints()) { + Map checkpointFields = new LinkedHashMap<>(); + checkpointFields.put("outboxStreamKey", checkpoint.outboxStreamKey()); + checkpointFields.put("outboxSequence", nonnegativeDecimal(checkpoint.outboxSequence())); + if (checkpoint.outboxSequence() > 0L) { + checkpointFields.put("sourceEventId", checkpoint.sourceEventId()); + checkpointFields.put("sourceEventDigest", checkpoint.sourceEventDigest()); + } + checkpoints.add(checkpointFields); + } + root.put("outboxCheckpoints", checkpoints); + return root; + } + + private static void validateFields(Map root) { + requireExactFields(root, ROOT_FIELDS, "bundle"); + requireText(root.get("schema"), SCHEMA, "schema"); + requireText(root.get("issuer"), ISSUER, "issuer"); + requireText(root.get("profile"), PROFILE, "profile"); + requireText(root.get("audience"), AUDIENCE, "audience"); + requireHash(root.get("snapshotIdentity"), "snapshotIdentity"); + requireHash(root.get("evaluationIdentity"), "evaluationIdentity"); + + Map ref = requireObject(root.get("bundleRef"), "bundleRef"); + requireExactFields(ref, BUNDLE_REF_FIELDS, "bundleRef"); + requirePositiveDecimal(ref.get("bundleVersion"), "bundleVersion"); + requirePositiveXid8(ref.get("sourceVersion"), "sourceVersion"); + requirePositiveDecimal(ref.get("sourceFence"), "sourceFence"); + requirePositiveXid8(ref.get("linearization"), "linearization"); + + Map scope = requireObject(root.get("scope"), "scope"); + requireExactFields(scope, SCOPE_FIELDS, "scope"); + requireText(scope.get("kind"), "account", "scope.kind"); + String accountId = requireUuid(scope.get("accountId"), "scope.accountId"); + requireEmptyList(scope.get("tenantIds"), "scope.tenantIds"); + + Map operation = requireObject(root.get("operation"), "operation"); + requireExactFields(operation, OPERATION_FIELDS, "operation"); + requireV4Uuid(operation.get("operationId"), "operation.operationId"); + requireV4Uuid(operation.get("requestId"), "operation.requestId"); + requireHash(operation.get("requestDigest"), "operation.requestDigest"); + String caller = + requireBoundedText(operation.get("callerWorkload"), "operation.callerWorkload", 256); + if (!WORKLOAD.matcher(caller).matches()) { + throw invalid( + "Account auth-evidence bundle caller workload is not the exact Game Session peer"); + } + requireV4Uuid(operation.get("callerContextId"), "operation.callerContextId"); + if (!accountId.equals(requireUuid(operation.get("accountId"), "operation.accountId"))) { + throw invalid("Account auth-evidence bundle operation is scoped to another Account"); + } + + Map token = requireObject(root.get("tokenIdentity"), "tokenIdentity"); + requireExactFields(token, TOKEN_IDENTITY_FIELDS, "tokenIdentity"); + requireV4Uuid(token.get("jti"), "tokenIdentity.jti"); + long tokenGeneration = parsePositiveDecimal(token.get("tokenGeneration"), "tokenGeneration"); + long issuedAt = requirePositiveInteger(token.get("iat"), "iat"); + long notBefore = requirePositiveInteger(token.get("nbf"), "nbf"); + long expiresAt = requirePositiveInteger(token.get("exp"), "exp"); + if (tokenGeneration != 1L + || notBefore > issuedAt + || expiresAt <= issuedAt + || expiresAt - issuedAt > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw invalid("Account auth-evidence bundle token identity bounds are invalid"); + } + + Map tuple = requireObject(root.get("authorityTuple"), "authorityTuple"); + requireRequiredAndOptionalFields( + tuple, AUTHORITY_TUPLE_FIELDS, OPTIONAL_AUTHORITY_TUPLE_FIELDS, "authorityTuple"); + parsePositiveDecimal(tuple.get("issuerAuthGeneration"), "issuerAuthGeneration"); + parsePositiveDecimal(tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + requireEmptyObject(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + requireEmptyObject(tuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + requireEmptyList(tuple.get("privateRealmGrantVersions"), "privateRealmGrantVersions"); + requirePositiveDecimal(root.get("issuanceFence"), "issuanceFence"); + requireEmptyObject(root.get("membershipVersion"), "membershipVersion"); + + Map versions = + requireObject(root.get("authoritySourceVersions"), "authoritySourceVersions"); + requireExactFields(versions, AUTHORITY_SOURCE_VERSION_FIELDS, "authoritySourceVersions"); + for (String field : AUTHORITY_SOURCE_VERSION_FIELDS) { + requirePositiveDecimal(versions.get(field), field); + } + + Map identitySource = + requireObject(root.get("accountIdentitySource"), "accountIdentitySource"); + requireExactFields(identitySource, ACCOUNT_IDENTITY_FIELDS, "accountIdentitySource"); + long sourceRowId = parsePositiveDecimal(identitySource.get("sourceRowId"), "sourceRowId"); + long sourceNumericId = + parsePositiveDecimal(identitySource.get("sourceNumericId"), "sourceNumericId"); + if (sourceRowId != sourceNumericId) { + throw invalid("Account auth-evidence bundle Account source identity is contradictory"); + } + AccountIdentityProvenance provenance = + AccountIdentityProvenance.fromStorageValue( + requireBoundedText(identitySource.get("provenance"), "provenance", 40)); + if (!AccountIdentityProvenance.isAccepted(provenance)) { + throw invalid("Account auth-evidence bundle Account provenance is not accepted"); + } + + List checkpoints = requireList(root.get("outboxCheckpoints"), "outboxCheckpoints"); + if (checkpoints.size() != 2) { + throw invalid("Account auth-evidence bundle requires exact issuer and Account checkpoints"); + } + String issuerStream = "account:auth-authority:v1:issuer/" + ISSUER; + String accountStream = "account:auth-authority:v1:account/" + accountId; + Map> byStream = new LinkedHashMap<>(); + for (Object item : checkpoints) { + Map checkpoint = requireObject(item, "outbox checkpoint"); + String stream = + requireBoundedText(checkpoint.get("outboxStreamKey"), "outboxStreamKey", 2048); + if (byStream.put(stream, checkpoint) != null) { + throw invalid("Account auth-evidence bundle has a duplicate outbox stream"); + } + long sequence = parseNonnegativeDecimal(checkpoint.get("outboxSequence"), "outboxSequence"); + if (sequence == 0L) { + requireExactFields(checkpoint, ZERO_OUTBOX_CHECKPOINT_FIELDS, "zero outbox baseline"); + } else { + requireExactFields(checkpoint, OUTBOX_CHECKPOINT_FIELDS, "positive outbox checkpoint"); + requireBoundedText(checkpoint.get("sourceEventId"), "sourceEventId", 512); + requireEventDigest(checkpoint.get("sourceEventDigest"), "sourceEventDigest"); + } + } + if (!byStream.keySet().equals(Set.of(issuerStream, accountStream))) { + throw invalid("Account auth-evidence bundle outbox checkpoint scope is not exact"); + } + List canonicalOrder = new ArrayList<>(byStream.keySet()); + canonicalOrder.sort(Comparator.naturalOrder()); + List suppliedOrder = new ArrayList<>(); + for (Object item : checkpoints) { + Map checkpoint = requireObject(item, "outbox checkpoint"); + suppliedOrder.add( + requireBoundedText(checkpoint.get("outboxStreamKey"), "outboxStreamKey", 2048)); + } + if (!canonicalOrder.equals(suppliedOrder)) { + throw invalid("Account auth-evidence bundle checkpoints are not in canonical stream order"); + } + if (tuple.containsKey("accountSecurityCutoff")) { + Map cutoff = + requireObject(tuple.get("accountSecurityCutoff"), "authorityTuple.accountSecurityCutoff"); + requireExactFields(cutoff, ACCOUNT_SECURITY_CUTOFF_FIELDS, "accountSecurityCutoff"); + long cutoffGeneration = + parsePositiveDecimal( + cutoff.get("accountAuthorityGeneration"), + "authorityTuple.accountSecurityCutoff.accountAuthorityGeneration"); + requirePositiveDecimal( + cutoff.get("outboxSequence"), "authorityTuple.accountSecurityCutoff.outboxSequence"); + String cutoffStream = + requireBoundedText( + cutoff.get("outboxStreamKey"), + "authorityTuple.accountSecurityCutoff.outboxStreamKey", + 2048); + if (!accountStream.equals(cutoffStream) + || cutoffGeneration + != parsePositiveDecimal( + tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration")) { + throw invalid("Account auth-evidence security cutoff is outside the exact Account scope"); + } + Map accountCheckpoint = byStream.get(accountStream); + if (parseNonnegativeDecimal( + accountCheckpoint.get("outboxSequence"), "account outbox sequence") + < parsePositiveDecimal(cutoff.get("outboxSequence"), "cutoff outbox sequence")) { + throw invalid("Account auth-evidence checkpoint does not cover the security cutoff"); + } + } + if (!accountId.equals(requireUuid(scope.get("accountId"), "scope.accountId"))) { + throw invalid("Account auth-evidence bundle Account scope is inconsistent"); + } + } + + private static AccountAuthEvidenceBundle canonicalValue(Map fields) { + try { + String json = JSON.writeValueAsString(fields); + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (bytes.length == 0 || bytes.length > MAX_CANONICAL_BYTES) { + throw invalid("Account auth-evidence bundle exceeds its canonical byte bound"); + } + return new AccountAuthEvidenceBundle(fields, bytes); + } catch (IOException | RuntimeException ex) { + if (ex instanceof InvalidBundleException invalid) throw invalid; + throw invalid("Account auth-evidence bundle canonicalization failed"); + } + } + + private static Map immutableMap(Map input) { + return Collections.unmodifiableMap(deepCopyMap(input)); + } + + private static Map deepCopyMap(Map input) { + Map copy = new LinkedHashMap<>(); + for (Map.Entry entry : input.entrySet()) { + Object value = entry.getValue(); + if (value == null) throw invalid("Account auth-evidence bundle contains null"); + if (value instanceof Map map) { + Map child = new LinkedHashMap<>(); + for (Map.Entry item : map.entrySet()) { + if (!(item.getKey() instanceof String key)) { + throw invalid("Account auth-evidence bundle object key is not text"); + } + child.put(key, item.getValue()); + } + copy.put(entry.getKey(), immutableMap(child)); + } else if (value instanceof List list) { + List child = new ArrayList<>(list.size()); + for (Object item : list) { + if (item == null) throw invalid("Account auth-evidence bundle contains null"); + if (item instanceof Map map) { + Map nested = new LinkedHashMap<>(); + for (Map.Entry nestedItem : map.entrySet()) { + if (!(nestedItem.getKey() instanceof String key)) { + throw invalid("Account auth-evidence bundle object key is not text"); + } + nested.put(key, nestedItem.getValue()); + } + child.add(immutableMap(nested)); + } else { + child.add(item); + } + } + copy.put(entry.getKey(), List.copyOf(child)); + } else { + copy.put(entry.getKey(), value); + } + } + return copy; + } + + private static Map requireObject(Object value, String field) { + if (!(value instanceof Map input)) throw invalid(field + " must be an object"); + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : input.entrySet()) { + if (!(entry.getKey() instanceof String key) || entry.getValue() == null) { + throw invalid(field + " has a non-text key or null value"); + } + result.put(key, entry.getValue()); + } + return result; + } + + private static List requireList(Object value, String field) { + if (!(value instanceof List list)) throw invalid(field + " must be an array"); + return list; + } + + private static void requireExactFields( + Map value, Set expected, String field) { + if (!value.keySet().equals(expected) || value.values().stream().anyMatch(Objects::isNull)) { + throw invalid(field + " has missing, unknown, or null fields"); + } + } + + private static void requireRequiredAndOptionalFields( + Map value, Set required, Set optional, String field) { + if (!value.keySet().containsAll(required) + || !union(required, optional).containsAll(value.keySet()) + || value.values().stream().anyMatch(Objects::isNull)) { + throw invalid(field + " has missing, unknown, or null fields"); + } + } + + private static Set union(Set required, Set optional) { + java.util.HashSet values = new java.util.HashSet<>(required); + values.addAll(optional); + return Set.copyOf(values); + } + + private static void requireText(Object value, String expected, String field) { + if (!(value instanceof String text) || !text.equals(expected)) { + throw invalid(field + " is not the exact Account delegation value"); + } + } + + private static String requireBoundedText(Object value, String field, int maxLength) { + if (!(value instanceof String text) + || text.isEmpty() + || text.length() > maxLength + || !text.equals(text.strip()) + || text.chars().anyMatch(Character::isISOControl)) { + throw invalid(field + " is absent, unbounded, or malformed"); + } + return text; + } + + private static String requireUuid(Object value, String field) { + String text = requireBoundedText(value, field, 36); + if (!UUID_TEXT.matcher(text).matches()) throw invalid(field + " is not a canonical UUID"); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw invalid(field + " is not a nonzero canonical UUID"); + } + } catch (IllegalArgumentException ex) { + throw invalid(field + " is not a canonical UUID"); + } + return text; + } + + private static void requireHash(Object value, String field) { + if (!(value instanceof String text) || !SHA256.matcher(text).matches()) { + throw invalid(field + " must be lowercase SHA-256 hex"); + } + } + + private static void requireEventDigest(Object value, String field) { + if (!(value instanceof String text) || !EVENT_DIGEST.matcher(text).matches()) { + throw invalid(field + " must be a canonical Account event digest"); + } + } + + private static String requireV4Uuid(Object value, String field) { + String text = requireBoundedText(value, field, 36); + if (!V4_UUID_TEXT.matcher(text).matches()) { + throw invalid(field + " is not a canonical high-entropy UUID"); + } + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw invalid(field + " is not a nonzero canonical UUID"); + } + } catch (IllegalArgumentException ex) { + throw invalid(field + " is not a canonical UUID"); + } + return text; + } + + private static long requirePositiveInteger(Object value, String field) { + if (!(value instanceof Number number)) throw invalid(field + " must be a JSON integer"); + String text = number.toString(); + if (!POSITIVE_DECIMAL.matcher(text).matches()) + throw invalid(field + " is not a canonical integer"); + try { + return Long.parseLong(text); + } catch (NumberFormatException ex) { + throw invalid(field + " is outside the supported bound"); + } + } + + private static void requirePositiveDecimal(Object value, String field) { + parsePositiveDecimal(value, field); + } + + private static long parsePositiveDecimal(Object value, String field) { + if (!(value instanceof String text) || !POSITIVE_DECIMAL.matcher(text).matches()) { + throw invalid(field + " must be a canonical positive decimal string"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException ex) { + throw invalid(field + " is outside the supported bound"); + } + } + + private static long parseNonnegativeDecimal(Object value, String field) { + if (!(value instanceof String text) || !NONNEGATIVE_DECIMAL.matcher(text).matches()) { + throw invalid(field + " must be a canonical non-negative decimal string"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException ex) { + throw invalid(field + " is outside the supported bound"); + } + } + + private static void requirePositiveXid8(Object value, String field) { + if (!(value instanceof String text) || !POSITIVE_XID8.matcher(text).matches()) { + throw invalid(field + " must be a positive canonical xid8 decimal string"); + } + BigInteger xact = new BigInteger(text); + if (xact.signum() <= 0 || xact.bitLength() > 64) { + throw invalid(field + " is outside the PostgreSQL xid8 bound"); + } + } + + private static String decimal(long value) { + if (value <= 0L) throw invalid("Account auth-evidence bundle counter must be positive"); + return Long.toString(value); + } + + private static String nonnegativeDecimal(long value) { + if (value < 0L) throw invalid("Account auth-evidence checkpoint cannot be negative"); + return Long.toString(value); + } + + private static void requireEmptyObject(Object value, String field) { + Map object = requireObject(value, field); + if (!object.isEmpty()) throw invalid(field + " must be an empty object for this profile"); + } + + private static void requireEmptyList(Object value, String field) { + if (!(value instanceof List list) || !list.isEmpty()) { + throw invalid(field + " must be an empty array for this profile"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw invalid("Account auth-evidence bundle is not valid UTF-8"); + } + } + + private static byte[] canonicalize(String value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(value); + } catch (IOException | RuntimeException ex) { + throw invalid("Account auth-evidence bundle canonicalization failed"); + } + } + + private static InvalidBundleException invalid(String message) { + return new InvalidBundleException(message); + } + + /** Values captured from locked Account source rows; this record itself is not authority. */ + public record OwnerEvaluation( + BundleReference bundleReference, + String snapshotIdentity, + String evaluationIdentity, + UUID accountId, + OperationIdentity operation, + TokenIdentity token, + Map authorityTuple, + long issuanceFence, + AuthoritySourceVersions authoritySourceVersions, + AccountIdentitySource accountIdentitySource, + List outboxCheckpoints) { + public OwnerEvaluation { + Objects.requireNonNull(bundleReference, "Bundle reference is required"); + requireHash(snapshotIdentity, "snapshotIdentity"); + requireHash(evaluationIdentity, "evaluationIdentity"); + Objects.requireNonNull(accountId, "Account ID is required"); + if (issuanceFence <= 0L) { + throw invalid("Account issuance fence must be positive"); + } + Objects.requireNonNull(operation, "Operation identity is required"); + Objects.requireNonNull(token, "Token identity is required"); + authorityTuple = immutableMap(authorityTuple); + Objects.requireNonNull(authoritySourceVersions, "Authority source versions are required"); + Objects.requireNonNull(accountIdentitySource, "Account identity source is required"); + outboxCheckpoints = List.copyOf(outboxCheckpoints); + if (outboxCheckpoints.stream().anyMatch(Objects::isNull)) { + throw invalid("Account auth-evidence bundle has a null outbox checkpoint"); + } + if (!accountId.equals(operation.accountId())) { + throw invalid("Account auth-evidence bundle operation scope is contradictory"); + } + } + + @Override + public Map authorityTuple() { + return immutableMap(authorityTuple); + } + } + + public record BundleReference( + String bundleVersion, String sourceVersion, String sourceFence, String linearization) { + public BundleReference { + requirePositiveDecimal(bundleVersion, "bundleVersion"); + requirePositiveXid8(sourceVersion, "sourceVersion"); + requirePositiveDecimal(sourceFence, "sourceFence"); + requirePositiveXid8(linearization, "linearization"); + } + } + + public record OperationIdentity( + UUID operationId, + UUID requestId, + String requestDigest, + String callerWorkload, + UUID callerContextId, + UUID accountId) { + public OperationIdentity { + requireV4Uuid(operationId == null ? null : operationId.toString(), "operationId"); + requireV4Uuid(requestId == null ? null : requestId.toString(), "requestId"); + requireHash(requestDigest, "requestDigest"); + if (callerWorkload == null || !WORKLOAD.matcher(callerWorkload).matches()) { + throw invalid("Account auth-evidence caller is not the exact Game Session workload"); + } + requireV4Uuid(callerContextId == null ? null : callerContextId.toString(), "callerContextId"); + requireUuid(accountId == null ? null : accountId.toString(), "accountId"); + } + } + + public record TokenIdentity( + UUID jti, + long tokenGeneration, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond) { + public TokenIdentity { + requireV4Uuid(jti == null ? null : jti.toString(), "jti"); + if (tokenGeneration != 1L + || issuedAtEpochSecond <= 0L + || notBeforeEpochSecond <= 0L + || notBeforeEpochSecond > issuedAtEpochSecond + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw invalid("Account auth-evidence token identity is invalid"); + } + } + } + + public record AuthoritySourceVersions( + long issuerSourceVersion, long accountSourceVersion, long issuanceFenceSourceVersion) { + public AuthoritySourceVersions { + if (issuerSourceVersion <= 0L + || accountSourceVersion <= 0L + || issuanceFenceSourceVersion <= 0L) { + throw invalid("Account authority source versions must be positive"); + } + } + } + + public record AccountIdentitySource( + long sourceRowId, AccountIdentityProvenance provenance, long sourceNumericId) { + public AccountIdentitySource { + if (sourceRowId <= 0L || sourceNumericId != sourceRowId) { + throw invalid("Account UUID source row identity is contradictory"); + } + Objects.requireNonNull(provenance, "Account UUID provenance is required"); + if (!AccountIdentityProvenance.isAccepted(provenance)) { + throw invalid("Account UUID provenance is not accepted"); + } + } + } + + public record OutboxCheckpoint( + String outboxStreamKey, long outboxSequence, String sourceEventId, String sourceEventDigest) { + public OutboxCheckpoint { + if (outboxStreamKey == null || outboxStreamKey.isBlank() || outboxStreamKey.length() > 2048) { + throw invalid("Account authority outbox stream key is invalid"); + } + if (outboxSequence < 0L) { + throw invalid("Account outbox checkpoint sequence cannot be negative"); + } + if (outboxSequence == 0L) { + if (sourceEventId != null || sourceEventDigest != null) { + throw invalid("An explicit zero baseline cannot claim an event identity"); + } + } else { + if (sourceEventId == null || sourceEventId.isBlank() || sourceEventId.length() > 512) { + throw invalid("Account outbox checkpoint event ID is invalid"); + } + requireEventDigest(sourceEventDigest, "sourceEventDigest"); + } + } + } + + public static final class InvalidBundleException extends IllegalArgumentException { + public InvalidBundleException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionCommitConfirmation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionCommitConfirmation.java new file mode 100644 index 0000000000..672872bbf5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionCommitConfirmation.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.math.BigInteger; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; + +/** + * Non-authorizing readback of PostgreSQL's durable confirmation for one original COMMITTED lease. + * + *

This immutable value preserves the exact lease operation and database-stamped proof fields. It + * does not prove current Account authority, cleanup, or permission to admit gameplay. + */ +public record AccountGameplayAdmissionCommitConfirmation( + AccountGameplayAdmissionLeaseOperation operation, + short confirmationVersion, + UUID requestId, + UUID accountId, + UUID leaseId, + long leaseFence, + String evidenceSha256, + UUID bindingDecisionId, + long expiresAtMs, + String finalizationXid, + String walInsertLsn, + String walFlushLsn, + long committedBeforeMs, + String confirmationXid) { + private static final BigInteger UINT32_MAX = + BigInteger.ONE.shiftLeft(32).subtract(BigInteger.ONE); + private static final BigInteger UINT64_MAX = + BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); + + public AccountGameplayAdmissionCommitConfirmation { + Objects.requireNonNull(operation, "original committed lease operation is required"); + Objects.requireNonNull(requestId, "request ID is required"); + Objects.requireNonNull(accountId, "Account ID is required"); + Objects.requireNonNull(leaseId, "lease ID is required"); + Objects.requireNonNull(evidenceSha256, "evidence digest is required"); + Objects.requireNonNull(bindingDecisionId, "binding decision ID is required"); + Objects.requireNonNull(finalizationXid, "finalization transaction ID is required"); + Objects.requireNonNull(walInsertLsn, "WAL insert LSN is required"); + Objects.requireNonNull(walFlushLsn, "WAL flush LSN is required"); + Objects.requireNonNull(confirmationXid, "confirmation transaction ID is required"); + + var evidence = operation.evidence(); + var carrier = evidence.carrier(); + var scope = (java.util.Map) carrier.get("bindingScope"); + UUID expectedRequest = UUID.fromString((String) carrier.get("requestId")); + UUID expectedLease = UUID.fromString((String) carrier.get("leaseId")); + UUID expectedAccount = UUID.fromString((String) scope.get("accountId")); + long expectedFence = evidence.leaseFence().longValueExact(); + long expectedExpiry = Long.parseLong((String) carrier.get("expiresAt")); + + if (operation.state() != State.COMMITTED + || operation.bindingDecisionId() == null + || confirmationVersion != 1 + || !requestId.equals(expectedRequest) + || !accountId.equals(expectedAccount) + || !leaseId.equals(expectedLease) + || leaseFence <= 0L + || leaseFence != expectedFence + || !evidenceSha256.matches("[0-9a-f]{64}") + || !evidenceSha256.equals(evidence.sha256()) + || !bindingDecisionId.equals(operation.bindingDecisionId()) + || expiresAtMs <= 0L + || expiresAtMs != expectedExpiry + || committedBeforeMs <= 0L + || committedBeforeMs >= expiresAtMs) { + throw invalid(); + } + + requireCanonicalFullXid(finalizationXid); + requireCanonicalFullXid(confirmationXid); + if (finalizationXid.equals(confirmationXid)) throw invalid(); + BigInteger insert = parseLsn(walInsertLsn); + BigInteger flush = parseLsn(walFlushLsn); + if (insert.signum() <= 0 || flush.compareTo(insert) < 0) throw invalid(); + } + + private static void requireCanonicalFullXid(String value) { + if (value.isEmpty() || !value.matches("[1-9][0-9]*")) throw invalid(); + try { + BigInteger xid = new BigInteger(value); + if (xid.signum() <= 0 || xid.compareTo(UINT64_MAX) > 0) throw invalid(); + } catch (NumberFormatException failure) { + throw invalid(); + } + } + + private static BigInteger parseLsn(String value) { + if (!value.matches("(0|[1-9A-F][0-9A-F]{0,7})/(0|[1-9A-F][0-9A-F]{0,7})")) throw invalid(); + try { + int separator = value.indexOf('/'); + BigInteger high = new BigInteger(value.substring(0, separator), 16); + BigInteger low = new BigInteger(value.substring(separator + 1), 16); + if (high.compareTo(UINT32_MAX) > 0 || low.compareTo(UINT32_MAX) > 0) throw invalid(); + return high.shiftLeft(32).add(low); + } catch (NumberFormatException failure) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid durable Account admission commit confirmation"); + } + + @Override + public String toString() { + return "AccountGameplayAdmissionCommitConfirmation[requestId=" + + requestId + + ", confirmationVersion=" + + confirmationVersion + + "]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java new file mode 100644 index 0000000000..11805e3eef --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionLeaseOperation.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; + +/** Durable Account storage readback only; even COMMITTED is not authenticated admission proof. */ +public record AccountGameplayAdmissionLeaseOperation( + AccountGameplayAdmissionLeaseEvidence evidence, + State state, + UUID bindingDecisionId, + UUID orphanCleanupId) { + public AccountGameplayAdmissionLeaseOperation { + Objects.requireNonNull(evidence); + Objects.requireNonNull(state); + if ((bindingDecisionId != null + && (bindingDecisionId.version() != 4 || bindingDecisionId.variant() != 2)) + || (orphanCleanupId != null + && (orphanCleanupId.version() != 4 || orphanCleanupId.variant() != 2))) { + throw new IllegalArgumentException("Canonical non-nil UUIDv4 terminal identity required"); + } + if ((state == State.PENDING && (bindingDecisionId != null || orphanCleanupId != null)) + || (state == State.COMMITTED && (bindingDecisionId == null || orphanCleanupId != null)) + || (state == State.ABORTED && orphanCleanupId == null)) { + throw new IllegalArgumentException("Incomplete admission operation storage state"); + } + } + + public enum State { + PENDING, + COMMITTED, + ABORTED + } + + /** + * ABORTED retains exact binding/token evidence as pending work, never completed cleanup. A null + * decision is unknown or unobserved, never authoritative proof that no decision exists. + */ + public boolean hasPendingOrphanCleanup() { + return state == State.ABORTED; + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseOperation[state=" + state + "]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionOriginalAckReceipt.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionOriginalAckReceipt.java new file mode 100644 index 0000000000..70dc704b18 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionOriginalAckReceipt.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.math.BigInteger; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; + +/** + * Immutable storage readback of a trusted-JVM original COMMIT acknowledgement. + * + *

{@code committedBeforeMs} is opaque in-process capability evidence produced after the original + * physical COMMIT. SQL checks its shape and exact operation binding; SQL does not derive, + * authenticate, or independently prove that clock value. This receipt grants no current authority, + * Game Session installation, cleanup, or gameplay admission. + */ +public record AccountGameplayAdmissionOriginalAckReceipt( + AccountGameplayAdmissionLeaseOperation operation, + short schemaVersion, + UUID requestId, + UUID accountId, + UUID leaseId, + long leaseFence, + String evidenceSha256, + UUID bindingDecisionId, + long expiresAtMs, + String finalizationXid, + long committedBeforeMs, + String receiptXid) { + private static final BigInteger UINT64_MAX = + BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); + + public AccountGameplayAdmissionOriginalAckReceipt { + Objects.requireNonNull(operation, "original committed lease operation is required"); + Objects.requireNonNull(requestId, "request ID is required"); + Objects.requireNonNull(accountId, "Account ID is required"); + Objects.requireNonNull(leaseId, "lease ID is required"); + Objects.requireNonNull(evidenceSha256, "evidence digest is required"); + Objects.requireNonNull(bindingDecisionId, "binding decision ID is required"); + Objects.requireNonNull(finalizationXid, "finalization transaction ID is required"); + Objects.requireNonNull(receiptXid, "receipt transaction ID is required"); + + var evidence = operation.evidence(); + var carrier = evidence.carrier(); + var scope = (java.util.Map) carrier.get("bindingScope"); + UUID expectedRequest = UUID.fromString((String) carrier.get("requestId")); + UUID expectedLease = UUID.fromString((String) carrier.get("leaseId")); + UUID expectedAccount = UUID.fromString((String) scope.get("accountId")); + long expectedFence = evidence.leaseFence().longValueExact(); + long expectedExpiry = Long.parseLong((String) carrier.get("expiresAt")); + + if (operation.state() != State.COMMITTED + || operation.bindingDecisionId() == null + || schemaVersion != 1 + || !requestId.equals(expectedRequest) + || !accountId.equals(expectedAccount) + || !leaseId.equals(expectedLease) + || leaseFence <= 0L + || leaseFence != expectedFence + || !evidenceSha256.matches("[0-9a-f]{64}") + || !evidenceSha256.equals(evidence.sha256()) + || !bindingDecisionId.equals(operation.bindingDecisionId()) + || expiresAtMs <= 0L + || expiresAtMs != expectedExpiry + || committedBeforeMs <= 0L + || committedBeforeMs >= expiresAtMs) { + throw invalid(); + } + + requireCanonicalFullXid(finalizationXid); + requireCanonicalFullXid(receiptXid); + if (finalizationXid.equals(receiptXid)) throw invalid(); + } + + private static void requireCanonicalFullXid(String value) { + if (value.isEmpty() || !value.matches("[1-9][0-9]*")) throw invalid(); + try { + BigInteger xid = new BigInteger(value); + if (xid.signum() <= 0 || xid.compareTo(UINT64_MAX) > 0) throw invalid(); + } catch (NumberFormatException failure) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Invalid original Account admission acknowledgement receipt"); + } + + @Override + public String toString() { + return "AccountGameplayAdmissionOriginalAckReceipt[requestId=" + + requestId + + ", schemaVersion=" + + schemaVersion + + "]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionProvisionalDecision.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionProvisionalDecision.java new file mode 100644 index 0000000000..52429b66f2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayAdmissionProvisionalDecision.java @@ -0,0 +1,27 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; + +/** + * Exact non-authorizing PROVISIONAL observation returned by the Game Session owner. It proves + * neither durable Account state nor current Account/World authority. + */ +public record AccountGameplayAdmissionProvisionalDecision( + UUID bindingDecisionId, AccountGameplayAdmissionLeaseEvidence evidence) { + public AccountGameplayAdmissionProvisionalDecision { + if (bindingDecisionId == null + || bindingDecisionId.version() != 4 + || bindingDecisionId.variant() != 2 + || new UUID(0L, 0L).equals(bindingDecisionId)) { + throw new IllegalArgumentException("Canonical nonnil UUIDv4 decision ID is required"); + } + Objects.requireNonNull(evidence, "Original Account lease evidence is required"); + } + + @Override + public String toString() { + return "AccountGameplayAdmissionProvisionalDecision[status=PROVISIONAL]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java new file mode 100644 index 0000000000..f8a48195ba --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayPublicAdmissionSourceSnapshot.java @@ -0,0 +1,25 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; + +/** + * Immutable Account SQL sources captured for public fresh-admission owner work. + * + *

The values are valid only within the transaction that captured them. The token fence is + * persisted SQL state and the lifecycle enum is copied from the exact Account row. Neither carries + * caller authentication, token cryptographic validity, the separate safety-restriction projections, + * registry state, or gameplay admission by itself. + */ +public record AccountGameplayPublicAdmissionSourceSnapshot( + AccountMembershipRoleSourceSnapshot membershipSource, + AccountLifecycleState accountLifecycleState, + DemoTenantEntitlementSnapshot entitlementSource, + AccountGameplayTokenIdentityFence tokenIdentityFence) { + public AccountGameplayPublicAdmissionSourceSnapshot { + Objects.requireNonNull(membershipSource, "Current membership source is required"); + Objects.requireNonNull(accountLifecycleState, "Current Account lifecycle source is required"); + Objects.requireNonNull(entitlementSource, "Current demo entitlement source is required"); + Objects.requireNonNull(tokenIdentityFence, "Current SQL token fence is required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java new file mode 100644 index 0000000000..4f228b4732 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountGameplayTokenIdentityFence.java @@ -0,0 +1,80 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; + +/** Account SQL token identity and monotonic fence; contains no credential or registry assertion. */ +public record AccountGameplayTokenIdentityFence( + TokenIdentity identity, + long tokenIdentityFence, + State state, + UUID revocationRequestId, + String revocationDigest) { + public AccountGameplayTokenIdentityFence { + Objects.requireNonNull(identity); + Objects.requireNonNull(state); + if (tokenIdentityFence <= 0L) + throw new IllegalArgumentException("Positive token fence required"); + if (state == State.ACTIVE) { + if (tokenIdentityFence != 1L || revocationRequestId != null || revocationDigest != null) { + throw new IllegalArgumentException("Initial active fence is malformed"); + } + } else { + requireUuid(revocationRequestId); + requireDigest(revocationDigest); + if (tokenIdentityFence != (state == State.PENDING ? 2L : 3L)) { + throw new IllegalArgumentException("Revocation fence is malformed"); + } + } + } + + public enum State { + ACTIVE, + PENDING, + COMMITTED + } + + /** Exact immutable Account COMMITTED issuance identity, never reconstructed from Redis. */ + public record TokenIdentity( + UUID accountId, + UUID operationId, + UUID issuanceRequestId, + String tokenSha256, + UUID tokenJti, + long notBeforeEpochSecond, + long tokenGeneration, + long issuanceFence) { + public TokenIdentity { + requireUuid(accountId); + requireUuid(operationId); + requireUuid(issuanceRequestId); + requireUuid(tokenJti); + requireDigest(tokenSha256); + if (notBeforeEpochSecond <= 0L || tokenGeneration <= 0L || issuanceFence <= 0L) { + throw new IllegalArgumentException("Positive exact token identity metadata required"); + } + } + + @Override + public String toString() { + return "TokenIdentity[redacted]"; + } + } + + private static void requireUuid(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Canonical UUIDv4 required"); + } + } + + private static void requireDigest(String value) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical SHA-256 required"); + } + } + + @Override + public String toString() { + return "AccountGameplayTokenIdentityFence[redacted]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java new file mode 100644 index 0000000000..029c6bf10f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigest.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.ByteArrayOutputStream; +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; + +/** Canonical, bounded request digests for the two Account token-logout operations. */ +public final class AccountLogoutRequestDigest { + private static final String DOMAIN = "requestDigest/v1"; + private static final HexFormat HEX = HexFormat.of(); + + private AccountLogoutRequestDigest() {} + + public static String tokenLogout(UUID subjectAccountId, String tokenProfile, String tokenHash) { + return digest(OperationKind.TOKEN_LOGOUT, subjectAccountId, tokenProfile, tokenHash); + } + + public static String accountLogoutAll( + UUID subjectAccountId, String tokenProfile, String presentedTokenHash) { + return digest( + OperationKind.ACCOUNT_LOGOUT_ALL, subjectAccountId, tokenProfile, presentedTokenHash); + } + + /** Validates the exact closed token-profile vocabulary accepted by logout request bindings. */ + public static void validateTokenProfile(String tokenProfile) { + if (!"control-ui".equals(tokenProfile) && !"player-bootstrap".equals(tokenProfile)) { + throw new IllegalArgumentException( + "Logout request token profile must be control-ui or player-bootstrap"); + } + } + + /** Validates a SHA-256 token identity rendered as lowercase hexadecimal without a prefix. */ + public static void validateTokenHash(String tokenHash) { + if (tokenHash == null || !tokenHash.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Logout request token hash must be lowercase SHA-256 hex"); + } + } + + public static String tokenLogoutPreimageHex( + UUID subjectAccountId, String tokenProfile, String tokenHash) { + validateBindings(subjectAccountId, tokenProfile, tokenHash); + return HEX.formatHex( + preimage(OperationKind.TOKEN_LOGOUT, subjectAccountId, tokenProfile, tokenHash)); + } + + public static String accountLogoutAllPreimageHex( + UUID subjectAccountId, String tokenProfile, String presentedTokenHash) { + validateBindings(subjectAccountId, tokenProfile, presentedTokenHash); + return HEX.formatHex( + preimage( + OperationKind.ACCOUNT_LOGOUT_ALL, subjectAccountId, tokenProfile, presentedTokenHash)); + } + + private static String digest( + OperationKind operationKind, UUID subjectAccountId, String tokenProfile, String tokenHash) { + validateBindings(subjectAccountId, tokenProfile, tokenHash); + Objects.requireNonNull(operationKind, "A closed logout operation kind is required"); + byte[] preimage = preimage(operationKind, subjectAccountId, tokenProfile, tokenHash); + try { + return HEX.formatHex(MessageDigest.getInstance("SHA-256").digest(preimage)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void validateBindings( + UUID subjectAccountId, String tokenProfile, String tokenHash) { + if (subjectAccountId == null || new UUID(0L, 0L).equals(subjectAccountId)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + validateTokenProfile(tokenProfile); + validateTokenHash(tokenHash); + } + + private static byte[] preimage( + OperationKind operationKind, UUID subjectAccountId, String tokenProfile, String tokenHash) { + String tokenIdentityField = + operationKind == OperationKind.ACCOUNT_LOGOUT_ALL ? "presentedTokenHash" : "tokenHash"; + ByteArrayOutputStream output = new ByteArrayOutputStream(256); + appendSegment(output, DOMAIN); + appendStringField(output, "operationKind", operationKind.wireValue); + appendStringField(output, "subjectAccountId", subjectAccountId.toString()); + appendStringField(output, "tokenProfile", tokenProfile); + appendStringField(output, tokenIdentityField, tokenHash); + return output.toByteArray(); + } + + private static void appendStringField(ByteArrayOutputStream output, String name, String value) { + appendSegment(output, name); + appendSegment(output, "string"); + output.write('1'); + appendSegment(output, value); + } + + private static void appendSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private enum OperationKind { + TOKEN_LOGOUT("TOKEN_LOGOUT"), + ACCOUNT_LOGOUT_ALL("ACCOUNT_LOGOUT_ALL"); + + private final String wireValue; + + OperationKind(String wireValue) { + this.wireValue = wireValue; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipRoleSourceSnapshot.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipRoleSourceSnapshot.java new file mode 100644 index 0000000000..9c5e49256e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountMembershipRoleSourceSnapshot.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; + +/** + * Immutable Account SQL source capture, including historical membership event and current owners. + * + *

This is not authentication, authorization, signed recipient evidence, an ACTIVE proof, a + * mutation, or positive no-applicable-deadline evidence. In particular, INACTIVE and invalidated + * history may be captured without authorizing admission. Its validity is limited to the enclosing + * owner transaction; later mutation must revalidate the exact sources under its own owner locks. + */ +public record AccountMembershipRoleSourceSnapshot( + IssuerAccountSourceSnapshot issuerAccountSources, + CompositeSnapshot currentAuthority, + TenantAuthorityEventV1Codec.Event tenantSource, + PairAuthority pair, + MembershipSource membership, + RoleSnapshot roles, + Checkpoint membershipCheckpoint, + Event storedMembershipEvent, + MembershipEvent membershipEvent) { + public AccountMembershipRoleSourceSnapshot { + Objects.requireNonNull(issuerAccountSources); + Objects.requireNonNull(currentAuthority); + Objects.requireNonNull(tenantSource); + Objects.requireNonNull(pair); + Objects.requireNonNull(membership); + Objects.requireNonNull(roles); + Objects.requireNonNull(membershipCheckpoint); + Objects.requireNonNull(storedMembershipEvent); + Objects.requireNonNull(membershipEvent); + } + + /** Copies every membership identity/state field instead of retaining a mutable storage entity. */ + public record MembershipSource( + long membershipId, + long accountRowId, + UUID accountId, + AccountIdentityProvenance accountIdentityProvenance, + long accountSourceNumericId, + UUID tenantId, + VerifiedTenantProvenance tenantProvenance, + String lifecycleState, + boolean gameplayAdmissionAllowed, + long membershipVersion, + long membershipAuthorityGeneration, + String authorityProvenance) { + public MembershipSource { + Objects.requireNonNull(accountId); + Objects.requireNonNull(accountIdentityProvenance); + Objects.requireNonNull(tenantId); + Objects.requireNonNull(tenantProvenance); + Objects.requireNonNull(lifecycleState); + Objects.requireNonNull(authorityProvenance); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.java new file mode 100644 index 0000000000..e5f1b42d60 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionBirthSource.java @@ -0,0 +1,197 @@ +package net.firedevops.firemud.accountservice.dto; + +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 net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; + +/** Exact owner-local fresh-birth evidence; this value grants no admission or activation. */ +public record AccountPlatformRestrictionBirthSource( + UUID accountId, + long accountSourceNumericId, + long accountInsertTransactionId, + ScopeState birthAuthority, + ScopeState currentAuthority, + CategorySource accountSecurityLock, + CategorySource platformAccessBan) { + public AccountPlatformRestrictionBirthSource { + Objects.requireNonNull(accountId, "Account UUID is required"); + if (accountId.version() != 4 + || accountId.variant() != 2 + || accountSourceNumericId <= 0 + || accountInsertTransactionId <= 0) { + throw new IllegalArgumentException("Exact fresh Account identity is required"); + } + requireAccountAuthority(accountId, birthAuthority); + requireAccountAuthority(accountId, currentAuthority); + if (birthAuthority.generation() != 1 + || birthAuthority.sourceVersion() != 1 + || birthAuthority.issuanceFence().value() != 1 + || birthAuthority.issuanceFence().sourceVersion() != 1) { + throw new IllegalArgumentException("Fresh birth requires the initial Account authority"); + } + requireCategory(accountId, accountSecurityLock, Category.ACCOUNT_SECURITY_LOCK); + requireCategory(accountId, platformAccessBan, Category.PLATFORM_ACCESS_BAN); + for (CategorySource source : new CategorySource[] {accountSecurityLock, platformAccessBan}) { + if (!source + .payloadDigest() + .equals( + birthDigest( + accountId, + accountSourceNumericId, + accountInsertTransactionId, + birthAuthority, + source.category(), + source.operationId(), + source.resultId(), + source.eventId()))) { + throw new IllegalArgumentException("Restriction birth payload digest differs"); + } + } + if (accountSecurityLock.operationId().equals(platformAccessBan.operationId()) + || accountSecurityLock.resultId().equals(platformAccessBan.resultId()) + || accountSecurityLock.eventId().equals(platformAccessBan.eventId())) { + throw new IllegalArgumentException("Category birth identities must be independent"); + } + } + + private static void requireAccountAuthority(UUID accountId, ScopeState authority) { + Objects.requireNonNull(authority, "Account authority is required"); + if (!AuthorityScope.account(accountId).equals(authority.scope()) + || authority.issuanceFence() == null + || !accountId.equals(authority.issuanceFence().accountId())) { + throw new IllegalArgumentException("Account authority identity differs"); + } + } + + private static void requireCategory(UUID accountId, CategorySource source, Category expected) { + Objects.requireNonNull(source, "Explicit category source is required"); + if (source.category() != expected + || !source.outboxStreamKey().equals(streamKey(accountId, expected))) { + throw new IllegalArgumentException("Exact category scope is required"); + } + } + + public static String streamKey(UUID accountId, Category category) { + return "account:restriction-birth:v1:" + accountId + "/" + category.storageValue(); + } + + /** + * Closed UTF-8 newline-separated birth preimage, with one final newline. Exact order: schema, + * account UUID, private numeric source ID, provenance, insert txid, category, source kind, + * restriction state, revision, enforcement epoch, birth generation, generation source version, + * fence, fence source version, operation ID, result ID, event ID, stream key, outbox sequence. + * Every variable field is a canonical UUID, positive decimal, or fixed closed vocabulary. + */ + public static String birthDigest( + UUID accountId, + long numericId, + long transactionId, + ScopeState birth, + Category category, + UUID operationId, + UUID resultId, + UUID eventId) { + String preimage = + String.join( + "\n", + "account-restriction-birth/v1", + accountId.toString(), + Long.toString(numericId), + "ACCOUNT_REPOSITORY_INSERT", + Long.toString(transactionId), + category.storageValue(), + "CATEGORY", + "NONRESTRICTED", + "1", + "1", + Long.toString(birth.generation()), + Long.toString(birth.sourceVersion()), + Long.toString(birth.issuanceFence().value()), + Long.toString(birth.issuanceFence().sourceVersion()), + operationId.toString(), + resultId.toString(), + eventId.toString(), + streamKey(accountId, category), + "1") + + "\n"; + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("Required SHA-256 digest is unavailable", unavailable); + } + } + + public enum Category { + ACCOUNT_SECURITY_LOCK("account_security_lock"), + PLATFORM_ACCESS_BAN("platform_access_ban"); + + private final String storageValue; + + Category(String storageValue) { + this.storageValue = storageValue; + } + + public String storageValue() { + return storageValue; + } + } + + public enum SourceKind { + CATEGORY + } + + public enum RestrictionState { + NONRESTRICTED + } + + /** A positive, explicit category revision/result, never inferred from absent rows. */ + public record CategorySource( + Category category, + SourceKind sourceKind, + RestrictionState restrictionState, + long revision, + long enforcementEpoch, + UUID operationId, + UUID resultId, + UUID eventId, + String payloadDigest, + String outboxStreamKey, + long outboxSequence) { + public CategorySource { + Objects.requireNonNull(category, "Category is required"); + Objects.requireNonNull(sourceKind, "Explicit source kind is required"); + Objects.requireNonNull(restrictionState, "Explicit restriction state is required"); + requireUuid(operationId); + requireUuid(resultId); + requireUuid(eventId); + if (payloadDigest == null || !payloadDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical restriction birth digest is required"); + } + Objects.requireNonNull(outboxStreamKey, "Restriction outbox stream is required"); + if (revision != 1 + || enforcementEpoch != 1 + || outboxSequence != 1 + || operationId.equals(resultId) + || operationId.equals(eventId) + || resultId.equals(eventId)) { + throw new IllegalArgumentException( + "Exact independent birth result and outbox are required"); + } + } + + private static void requireUuid(UUID value) { + Objects.requireNonNull(value, "Server-generated birth identity is required"); + if (value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Canonical version-four birth identity is required"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java new file mode 100644 index 0000000000..bb5f164754 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.accountservice.dto; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Immutable operation correlation only; this request does not establish caller authorization. */ +public record AccountSecurityStateMutationRequest( + UUID requestId, + UUID accountUuid, + byte[] callerProofBinding, + long expectedGeneration, + long expectedSourceVersion, + List mutationKinds, + AccountState desiredState) { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Set CALLER_FIELDS = + Set.of("schemaVersion", "actorAccountUuid", "ownerOperationId", "ownerEvidenceDigest"); + + public AccountSecurityStateMutationRequest { + requireUuid(requestId); + requireUuid(accountUuid); + if (expectedGeneration <= 0 || expectedSourceVersion <= 0) { + throw new IllegalArgumentException("Original positive source counters are required"); + } + callerProofBinding = canonicalCallerBinding(callerProofBinding); + mutationKinds = List.copyOf(Objects.requireNonNull(mutationKinds)); + Objects.requireNonNull(desiredState); + // The shared source codec owns the complete state and family vocabulary. + var validated = + AccountSecurityStateAuthorityEventV1Codec.seal( + eventPreimage(requestId, accountUuid, "1", "1", "1", mutationKinds, desiredState)); + desiredState = validated.accountState(); + mutationKinds = validated.mutationKinds(); + } + + @Override + public byte[] callerProofBinding() { + return callerProofBinding.clone(); + } + + @Override + public List mutationKinds() { + return List.copyOf(mutationKinds); + } + + public byte[] canonicalDesiredState() { + return canonicalState(desiredState); + } + + public static byte[] canonicalState(AccountState state) { + Objects.requireNonNull(state); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(state)); + } catch (IOException exception) { + throw new IllegalArgumentException("Account state cannot be canonicalized", exception); + } + } + + public static AccountState parseCanonicalState(byte[] bytes) { + try { + String text = new String(Objects.requireNonNull(bytes), StandardCharsets.UTF_8); + JsonNode node = JSON.readTree(text); + var validated = + AccountSecurityStateAuthorityEventV1Codec.seal( + eventPreimage( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "1", + "1", + "1", + List.of("EMAIL_LOGIN_ELIGIBILITY_CHANGED"), + JSON.convertValue(node, new TypeReference>() {}))); + if (!Arrays.equals(bytes, canonicalState(validated.accountState()))) { + throw new IllegalArgumentException("Stored Account state is not canonical"); + } + return validated.accountState(); + } catch (IOException exception) { + throw new IllegalArgumentException("Stored Account state is malformed", exception); + } + } + + public static Map eventPreimage( + UUID requestId, + UUID accountUuid, + String generation, + String sourceVersion, + String sequence, + List mutationKinds, + Object state) { + String stream = "account:auth-authority:v1:account/" + accountUuid; + return Map.ofEntries( + Map.entry("schemaVersion", AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", AccountSecurityStateAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", AccountSecurityStateAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId), + Map.entry("requestId", requestId.toString()), + Map.entry("accountId", accountUuid.toString()), + Map.entry("sourceScope", "account/" + accountUuid), + Map.entry("outboxStreamKey", stream), + Map.entry("outboxSequence", sequence), + Map.entry("accountAuthorityGeneration", generation), + Map.entry("sourceVersion", sourceVersion), + Map.entry( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + generation, + "outboxStreamKey", + stream, + "outboxSequence", + sequence)), + Map.entry("mutationKinds", mutationKinds), + Map.entry("accountState", state)); + } + + private static byte[] canonicalCallerBinding(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > 16_384) { + throw new IllegalArgumentException("Bounded original caller/proof correlation is required"); + } + try { + String text = new String(bytes, StandardCharsets.UTF_8); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(text))) { + throw new IllegalArgumentException("Caller/proof correlation must be canonical JSON"); + } + JsonNode node = JSON.readTree(text); + Set fields = new java.util.HashSet<>(); + node.fieldNames().forEachRemaining(fields::add); + if (!node.isObject() || !fields.equals(CALLER_FIELDS)) { + throw new IllegalArgumentException( + "Caller correlation must contain exactly its identity fields"); + } + if (!"account-security-state-caller-correlation/v1" + .equals(node.path("schemaVersion").textValue())) { + throw new IllegalArgumentException("Unsupported caller correlation version"); + } + for (String field : List.of("actorAccountUuid", "ownerOperationId")) { + JsonNode id = node.get(field); + if (!id.isTextual() + || !id.textValue() + .matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + throw new IllegalArgumentException("Canonical correlation UUIDs are required"); + } + requireUuid(UUID.fromString(id.textValue())); + } + if (!node.get("ownerEvidenceDigest").isTextual() + || !node.get("ownerEvidenceDigest").textValue().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "Original owner evidence digest correlation is required"); + } + return bytes.clone(); + } catch (IOException exception) { + throw new IllegalArgumentException("Caller/proof correlation is malformed", exception); + } + } + + private static void requireUuid(UUID uuid) { + if (uuid == null || uuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException( + "Canonical non-nil operation and Account UUIDs are required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java new file mode 100644 index 0000000000..e779dddd2a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountSecurityStateRequestDigest.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; + +/** Exact versioned request/capture bytes; neither digest establishes caller authorization. */ +public final class AccountSecurityStateRequestDigest { + public static final String REQUEST_DOMAIN = "firemud/account/security-state/request/v1"; + + private AccountSecurityStateRequestDigest() {} + + public static byte[] requestBytes(AccountSecurityStateMutationRequest request) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + frame(bytes, REQUEST_DOMAIN); + frame(bytes, request.requestId().toString()); + frame(bytes, request.accountUuid().toString()); + frame(bytes, request.callerProofBinding()); + frame(bytes, Long.toString(request.expectedGeneration())); + frame(bytes, Long.toString(request.expectedSourceVersion())); + // Each kind has its own frame; cardinality is also an explicit frame. + frame(bytes, Integer.toString(request.mutationKinds().size())); + request.mutationKinds().forEach(kind -> frame(bytes, kind)); + frame(bytes, request.canonicalDesiredState()); + return bytes.toByteArray(); + } + + public static String digest(AccountSecurityStateMutationRequest request) { + return sha256(requestBytes(request)); + } + + public static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + public static void frame(ByteArrayOutputStream output, String text) { + frame(output, text.getBytes(StandardCharsets.UTF_8)); + } + + public static void frame(ByteArrayOutputStream output, byte[] value) { + output.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); + output.writeBytes(value); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java new file mode 100644 index 0000000000..e5a77be1b4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementEventV1Codec.java @@ -0,0 +1,435 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Closed canonical Account event encoding for explicit non-paid demo entitlements. */ +public final class DemoTenantEntitlementEventV1Codec { + public static final String SCHEMA_VERSION = "account-tenant-entitlement-event/v1"; + public static final String EVENT_TYPE = "TENANT_ENTITLEMENT_CHANGED"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Set EVENT_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "requestDigest", + "outboxStreamKey", + "tenantId", + "tenantBillingSequence", + "tenantAuthorityGeneration", + "tenantAuthoritySourceVersion", + "entitlementVersion", + "entitlementKind", + "status", + "subscriptionStatus", + "paid", + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts", + "quotas", + "sourceEvidence", + "eventDigest"); + private static final Set QUOTA_FIELDS = + Set.of("maxActiveSessions", "maxConcurrentGameInstances", "maxStorageBytes"); + private static final java.util.regex.Pattern DIGEST = + java.util.regex.Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]{0,18})"); + private static final Set SOURCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private DemoTenantEntitlementEventV1Codec() {} + + public static Event seal( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence) { + if (request == null || source == null) { + throw new IllegalArgumentException( + "Demo entitlement request and source evidence are required"); + } + if (!request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest())) { + throw new IllegalArgumentException( + "Demo entitlement event source differs from exact request"); + } + UUID eventId = eventId(request.requestId()); + String streamKey = + AccountTenantEntitlementOutboxRepository.streamKey(request.canonicalTenantId()); + Map preimage = + eventFields( + request, + source, + entitlementVersion, + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + tenantBillingSequence, + eventId, + streamKey); + String digest = digest(canonical(preimage)); + Map wire = new LinkedHashMap<>(preimage); + wire.put("eventDigest", digest); + byte[] payload = canonical(wire); + return new Event( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + source, + entitlementVersion, + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + tenantBillingSequence, + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas(), + eventId, + streamKey, + digest, + payload); + } + + /** Parses and verifies the exact canonical event payload stored in Account's outbox. */ + public static Event verify(byte[] payload) { + if (payload == null || payload.length == 0 || payload.length > 32 * 1024) { + throw new IllegalArgumentException("Demo entitlement event payload is absent or oversized"); + } + final Map wire; + try { + wire = JSON.readValue(payload, new TypeReference<>() {}); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Demo entitlement event payload is malformed", exception); + } + if (!wire.keySet().equals(EVENT_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement event fields are incomplete or unknown"); + } + String claimedDigest = text(wire.get("eventDigest"), "eventDigest"); + Map preimage = new LinkedHashMap<>(wire); + preimage.remove("eventDigest"); + byte[] canonicalPreimage = canonical(preimage); + if (!claimedDigest.equals(digest(canonicalPreimage))) { + throw new IllegalArgumentException( + "Demo entitlement event digest does not match its payload"); + } + if (!java.util.Arrays.equals(payload, canonical(wire))) { + throw new IllegalArgumentException("Demo entitlement event payload is not canonical JSON"); + } + + UUID tenantId = uuid(wire.get("tenantId"), "tenantId"); + UUID requestId = uuid(wire.get("requestId"), "requestId"); + UUID actualEventId = uuid(wire.get("eventId"), "eventId"); + String streamKey = text(wire.get("outboxStreamKey"), "outboxStreamKey"); + if (!SCHEMA_VERSION.equals(wire.get("schemaVersion")) + || !EVENT_TYPE.equals(wire.get("eventType")) + || !"NON_PAID_DEMO".equals(wire.get("entitlementKind")) + || !"ACTIVE".equals(wire.get("status")) + || wire.get("subscriptionStatus") != null + || !Boolean.FALSE.equals(wire.get("paid")) + || !DIGEST.matcher(text(wire.get("requestDigest"), "requestDigest")).matches() + || !eventId(requestId).equals(actualEventId) + || !AccountTenantEntitlementOutboxRepository.streamKey(tenantId).equals(streamKey)) { + throw new IllegalArgumentException( + "Demo entitlement event identity or non-paid state is invalid"); + } + + Map sourceMap = object(wire.get("sourceEvidence"), "sourceEvidence"); + if (!sourceMap.keySet().equals(SOURCE_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement source evidence fields are incomplete"); + } + FreshTenantCreationEvidence source = + new FreshTenantCreationEvidence( + integer(sourceMap.get("schemaVersion"), "source schemaVersion"), + text(sourceMap.get("targetNamespace"), "source targetNamespace"), + uuid(sourceMap.get("creationRequestId"), "source creationRequestId"), + uuid(sourceMap.get("operationId"), "source operationId"), + text(sourceMap.get("requestDigest"), "source requestDigest"), + uuid(sourceMap.get("canonicalTenantId"), "source canonicalTenantId"), + positiveDecimal(sourceMap.get("sourceGameRowId"), "source sourceGameRowId"), + text(sourceMap.get("sourceGameTenantKey"), "source sourceGameTenantKey"), + text(sourceMap.get("provenanceKind"), "source provenanceKind"), + text(sourceMap.get("evidenceDigest"), "source evidenceDigest")); + if (!tenantId.equals(source.canonicalTenantId())) { + throw new IllegalArgumentException("Demo entitlement event source targets another tenant"); + } + + Map quotaMap = object(wire.get("quotas"), "quotas"); + if (!quotaMap.keySet().equals(QUOTA_FIELDS)) { + throw new IllegalArgumentException("Demo entitlement event quota fields are incomplete"); + } + DemoTenantEntitlementRequest.Quotas quotas = + new DemoTenantEntitlementRequest.Quotas( + nonnegativeDecimal(quotaMap.get("maxActiveSessions"), "maxActiveSessions"), + nonnegativeDecimal( + quotaMap.get("maxConcurrentGameInstances"), "maxConcurrentGameInstances"), + nonnegativeDecimal(quotaMap.get("maxStorageBytes"), "maxStorageBytes")); + + return new Event( + requestId, + text(wire.get("requestDigest"), "requestDigest"), + tenantId, + source, + positiveDecimal(wire.get("entitlementVersion"), "entitlementVersion"), + positiveDecimal(wire.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"), + positiveDecimal(wire.get("tenantAuthoritySourceVersion"), "tenantAuthoritySourceVersion"), + positiveDecimal(wire.get("tenantBillingSequence"), "tenantBillingSequence"), + bool(wire.get("gameplayAvailable"), "gameplayAvailable"), + bool(wire.get("allowPublicJoin"), "allowPublicJoin"), + bool(wire.get("allowNewGameplayBindings"), "allowNewGameplayBindings"), + bool(wire.get("allowNewInstanceStarts"), "allowNewInstanceStarts"), + quotas, + actualEventId, + streamKey, + claimedDigest, + payload); + } + + public static UUID eventId(UUID requestId) { + if (requestId == null || NIL_UUID.equals(requestId)) { + throw new IllegalArgumentException("Demo entitlement request ID is required"); + } + return UUID.nameUUIDFromBytes( + (SCHEMA_VERSION + ":" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static Map eventFields( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence, + UUID eventId, + String streamKey) { + if (entitlementVersion <= 0 + || tenantAuthorityGeneration <= 0 + || tenantAuthoritySourceVersion <= 0 + || tenantBillingSequence <= 0) { + throw new IllegalArgumentException("Demo entitlement event versions must be positive"); + } + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", SCHEMA_VERSION); + fields.put("eventType", EVENT_TYPE); + fields.put("eventId", eventId.toString()); + fields.put("requestId", request.requestId().toString()); + fields.put("requestDigest", request.requestDigest()); + fields.put("outboxStreamKey", streamKey); + fields.put("tenantId", request.canonicalTenantId().toString()); + fields.put("tenantBillingSequence", Long.toString(tenantBillingSequence)); + fields.put("tenantAuthorityGeneration", Long.toString(tenantAuthorityGeneration)); + fields.put("tenantAuthoritySourceVersion", Long.toString(tenantAuthoritySourceVersion)); + fields.put("entitlementVersion", Long.toString(entitlementVersion)); + fields.put("entitlementKind", "NON_PAID_DEMO"); + fields.put("status", "ACTIVE"); + fields.put("subscriptionStatus", null); + fields.put("paid", false); + fields.put("gameplayAvailable", request.gameplayAvailable()); + fields.put("allowPublicJoin", request.allowPublicJoin()); + fields.put("allowNewGameplayBindings", request.allowNewGameplayBindings()); + fields.put("allowNewInstanceStarts", request.allowNewInstanceStarts()); + fields.put("quotas", quotaFields(request.quotas())); + fields.put("sourceEvidence", sourceFields(source)); + return fields; + } + + private static Map sourceFields(FreshTenantCreationEvidence source) { + Map fields = new LinkedHashMap<>(); + fields.put("schemaVersion", source.schemaVersion()); + fields.put("targetNamespace", source.targetNamespace()); + fields.put("creationRequestId", source.creationRequestId().toString()); + fields.put("operationId", source.operationId().toString()); + fields.put("requestDigest", source.requestDigest()); + fields.put("canonicalTenantId", source.canonicalTenantId().toString()); + fields.put("sourceGameRowId", Long.toString(source.sourceGameRowId())); + fields.put("sourceGameTenantKey", source.sourceGameTenantKey()); + fields.put("provenanceKind", source.provenanceKind()); + fields.put("evidenceDigest", source.evidenceDigest()); + return fields; + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException exception) { + throw new IllegalStateException( + "Demo entitlement event could not be canonicalized", exception); + } + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + @SuppressWarnings("unchecked") + private static Map object(Object value, String field) { + if (!(value instanceof Map raw)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " must be an object"); + } + for (Object key : raw.keySet()) { + if (!(key instanceof String)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " has invalid keys"); + } + } + return (Map) raw; + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isBlank()) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is invalid"); + } + return text; + } + + private static UUID uuid(Object value, String field) { + String text = text(value, field); + UUID uuid; + try { + uuid = UUID.fromString(text); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is not a UUID", exception); + } + if (NIL_UUID.equals(uuid) || !uuid.toString().equals(text)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is not canonical"); + } + return uuid; + } + + private static int integer(Object value, String field) { + if (!(value instanceof Number number)) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " must be a JSON integer"); + } + String encoded = number.toString(); + if (!POSITIVE_DECIMAL.matcher(encoded).matches()) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " must be a positive JSON integer"); + } + try { + return Integer.parseInt(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is too large", exception); + } + } + + private static long positiveDecimal(Object value, String field) { + String encoded = decimalText(value, field, POSITIVE_DECIMAL, "positive"); + try { + return Long.parseLong(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is outside the supported owner range", exception); + } + } + + private static long nonnegativeDecimal(Object value, String field) { + String encoded = decimalText(value, field, NONNEGATIVE_DECIMAL, "non-negative"); + try { + return Long.parseLong(encoded); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Demo entitlement event " + field + " is outside the supported owner range", exception); + } + } + + private static String decimalText( + Object value, String field, Pattern grammar, String description) { + if (!(value instanceof String encoded) || !grammar.matcher(encoded).matches()) { + throw new IllegalArgumentException( + "Demo entitlement event " + + field + + " must be a canonical " + + description + + " decimal string"); + } + return encoded; + } + + private static Map quotaFields(DemoTenantEntitlementRequest.Quotas quotas) { + Map fields = new LinkedHashMap<>(); + fields.put("maxActiveSessions", Long.toString(quotas.maxActiveSessions())); + fields.put("maxConcurrentGameInstances", Long.toString(quotas.maxConcurrentGameInstances())); + fields.put("maxStorageBytes", Long.toString(quotas.maxStorageBytes())); + return fields; + } + + private static boolean bool(Object value, String field) { + if (!(value instanceof Boolean result)) { + throw new IllegalArgumentException("Demo entitlement event " + field + " is not boolean"); + } + return result; + } + + /** Exact closed event evidence stored in the Account entitlement outbox. */ + public record Event( + UUID requestId, + String requestDigest, + UUID canonicalTenantId, + FreshTenantCreationEvidence sourceEvidence, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long tenantBillingSequence, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + DemoTenantEntitlementRequest.Quotas quotas, + UUID eventId, + String outboxStreamKey, + String eventDigest, + byte[] payload) { + public Event { + payload = payload.clone(); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java new file mode 100644 index 0000000000..e6f8a3b16a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementRequest.java @@ -0,0 +1,121 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Explicit Account-owned non-paid demo entitlement mutation from a protected local fixture. */ +public record DemoTenantEntitlementRequest( + UUID requestId, + UUID canonicalTenantId, + UUID tenantCreationRequestId, + String tenantCreationRequestDigest, + Long expectedEntitlementVersion, + Long expectedTenantAuthorityGeneration, + Long expectedTenantAuthoritySourceVersion, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + Quotas quotas) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + public DemoTenantEntitlementRequest { + requireNonNil(requestId, "Demo entitlement request ID"); + requireNonNil(canonicalTenantId, "Canonical tenant UUID"); + requireNonNil(tenantCreationRequestId, "Fresh tenant creation request ID"); + if (tenantCreationRequestDigest == null + || !DIGEST.matcher(tenantCreationRequestDigest).matches()) { + throw new IllegalArgumentException("Fresh tenant creation request digest is invalid"); + } + boolean creating = expectedEntitlementVersion == null; + if (creating != (expectedTenantAuthorityGeneration == null) + || creating != (expectedTenantAuthoritySourceVersion == null)) { + throw new IllegalArgumentException( + "Demo entitlement create or update fence fields must be supplied together"); + } + if (!creating + && (expectedEntitlementVersion <= 0 + || expectedTenantAuthorityGeneration <= 0 + || expectedTenantAuthoritySourceVersion <= 0)) { + throw new IllegalArgumentException("Expected demo entitlement fences must be positive"); + } + Objects.requireNonNull(quotas, "Explicit demo entitlement quotas are required"); + } + + /** Stable normalized request digest; the request ID remains the operation identity. */ + public String requestDigest() { + Map normalized = new LinkedHashMap<>(); + normalized.put("schemaVersion", "account-demo-entitlement-request/v1"); + normalized.put("canonicalTenantId", canonicalTenantId.toString()); + normalized.put("tenantCreationRequestId", tenantCreationRequestId.toString()); + normalized.put("tenantCreationRequestDigest", tenantCreationRequestDigest); + normalized.put("expectedEntitlementVersion", decimal(expectedEntitlementVersion)); + normalized.put("expectedTenantAuthorityGeneration", decimal(expectedTenantAuthorityGeneration)); + normalized.put( + "expectedTenantAuthoritySourceVersion", decimal(expectedTenantAuthoritySourceVersion)); + normalized.put("entitlementKind", "NON_PAID_DEMO"); + normalized.put("subscriptionStatus", null); + normalized.put("paid", false); + normalized.put("status", "ACTIVE"); + normalized.put("gameplayAvailable", gameplayAvailable); + normalized.put("allowPublicJoin", allowPublicJoin); + normalized.put("allowNewGameplayBindings", allowNewGameplayBindings); + normalized.put("allowNewInstanceStarts", allowNewInstanceStarts); + normalized.put("quotas", quotaFields(quotas)); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(normalized)); + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException exception) { + throw new IllegalStateException( + "Demo entitlement request digest could not be computed", exception); + } + } + + private static void requireNonNil(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + } + + private static String decimal(Long value) { + return value == null ? null : Long.toString(value); + } + + private static Map quotaFields(Quotas quotas) { + Map fields = new LinkedHashMap<>(); + fields.put("maxActiveSessions", Long.toString(quotas.maxActiveSessions())); + fields.put("maxConcurrentGameInstances", Long.toString(quotas.maxConcurrentGameInstances())); + fields.put("maxStorageBytes", Long.toString(quotas.maxStorageBytes())); + return fields; + } + + /** Quotas are explicit demo values and never copied from a paid plan or subscription. */ + public record Quotas( + long maxActiveSessions, long maxConcurrentGameInstances, long maxStorageBytes) { + public Quotas { + if (maxActiveSessions < 0 || maxConcurrentGameInstances < 0 || maxStorageBytes < 0) { + throw new IllegalArgumentException("Demo entitlement quotas cannot be negative"); + } + } + + public Map asMap() { + Map values = new LinkedHashMap<>(); + values.put("maxActiveSessions", maxActiveSessions); + values.put("maxConcurrentGameInstances", maxConcurrentGameInstances); + values.put("maxStorageBytes", maxStorageBytes); + return values; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java new file mode 100644 index 0000000000..d5de209ab2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementSnapshot.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.accountservice.dto; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; + +/** Exact committed demo entitlement and its current Account tenant-generation/outbox evidence. */ +public record DemoTenantEntitlementSnapshot( + UUID canonicalTenantId, + FreshTenantCreationEvidence sourceEvidence, + String entitlementKind, + String status, + String subscriptionStatus, + boolean paid, + boolean gameplayAvailable, + boolean allowPublicJoin, + boolean allowNewGameplayBindings, + boolean allowNewInstanceStarts, + DemoTenantEntitlementRequest.Quotas quotas, + long entitlementVersion, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + String outboxStreamKey, + long tenantBillingSequence, + UUID eventId, + String eventDigest, + String snapshotIdentity, + String tenantAuthorityOutboxStreamKey, + long tenantAuthorityOutboxSequence, + UUID tenantAuthorityEventId, + String tenantAuthorityEventDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern EVENT_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "NON_PAID_DEMO requires null subscriptionStatus; the compact record constructor implicitly stores that validated null.") + public DemoTenantEntitlementSnapshot { + if (canonicalTenantId == null || NIL_UUID.equals(canonicalTenantId)) { + throw new IllegalArgumentException("Canonical tenant UUID is required"); + } + Objects.requireNonNull( + sourceEvidence, "Authenticated fresh tenant source evidence is required"); + if (!canonicalTenantId.equals(sourceEvidence.canonicalTenantId())) { + throw new IllegalArgumentException("Demo entitlement source evidence targets another tenant"); + } + if (!"NON_PAID_DEMO".equals(entitlementKind) + || !"ACTIVE".equals(status) + || subscriptionStatus != null + || paid) { + throw new IllegalArgumentException("Demo entitlement must remain explicitly non-paid"); + } + Objects.requireNonNull(quotas, "Demo entitlement quotas are required"); + if (entitlementVersion <= 0 + || tenantAuthorityGeneration <= 0 + || tenantAuthoritySourceVersion <= 0 + || tenantBillingSequence <= 0) { + throw new IllegalArgumentException("Demo entitlement currentness values must be positive"); + } + String expectedStream = AccountTenantEntitlementOutboxRepository.streamKey(canonicalTenantId); + if (!expectedStream.equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Demo entitlement outbox scope differs from its tenant UUID"); + } + if (eventId == null || NIL_UUID.equals(eventId)) { + throw new IllegalArgumentException("Demo entitlement event ID is required"); + } + if (eventDigest == null || !EVENT_DIGEST.matcher(eventDigest).matches()) { + throw new IllegalArgumentException("Demo entitlement event digest is invalid"); + } + if (!eventDigest.equals(snapshotIdentity)) { + throw new IllegalArgumentException( + "Demo entitlement snapshot identity differs from its event"); + } + if (!TenantAuthorityEventV1Codec.streamKey(canonicalTenantId) + .equals(tenantAuthorityOutboxStreamKey)) { + throw new IllegalArgumentException( + "Demo entitlement authority stream differs from its tenant UUID"); + } + if (tenantAuthorityOutboxSequence <= 0L + || tenantAuthorityEventId == null + || NIL_UUID.equals(tenantAuthorityEventId) + || tenantAuthorityEventDigest == null + || !EVENT_DIGEST.matcher(tenantAuthorityEventDigest).matches()) { + throw new IllegalArgumentException("Demo entitlement authority event evidence is invalid"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java new file mode 100644 index 0000000000..2ec896e75a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/TenantAuthorityEventV1Codec.java @@ -0,0 +1,427 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed canonical event encoding for Account's independently sequenced tenant authority stream. + */ +public final class TenantAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-tenant-authority-event/v1"; + public static final String EVENT_TYPE = "TENANT_AUTHORITY_CHANGED"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String STREAM_PREFIX = "account:auth-authority:v1:tenant/"; + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set EVENT_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "requestDigest", + "tenantId", + "tenantAuthorityGeneration", + "tenantAuthoritySourceVersion", + "outboxStreamKey", + "outboxSequence", + "tenantBillingReceipt", + "sourceEvidence", + "eventDigest"); + private static final Set BILLING_FIELDS = + Set.of("outboxStreamKey", "tenantBillingSequence", "eventId", "eventDigest"); + private static final Set SOURCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private TenantAuthorityEventV1Codec() {} + + public static String streamKey(UUID tenantId) { + requireUuid(tenantId, "tenant UUID"); + return STREAM_PREFIX + tenantId; + } + + public static Event seal( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + long outboxSequence, + DemoTenantEntitlementEventV1Codec.Event billingEvent) { + if (request == null || source == null || billingEvent == null) { + throw new IllegalArgumentException( + "Tenant authority request, source, and committed billing event are required"); + } + if (!request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest()) + || !"NEW_GAME_ROW".equals(source.provenanceKind()) + || !request.requestId().equals(billingEvent.requestId()) + || !request.requestDigest().equals(billingEvent.requestDigest()) + || !request.canonicalTenantId().equals(billingEvent.canonicalTenantId())) { + throw new IllegalArgumentException( + "Tenant authority event differs from its exact source or billing request"); + } + requirePositive(tenantAuthorityGeneration, "tenant authority generation"); + requirePositive(tenantAuthoritySourceVersion, "tenant authority source version"); + requirePositive(outboxSequence, "authority outbox sequence"); + UUID eventId = eventId(request.requestId()); + String streamKey = streamKey(request.canonicalTenantId()); + Map preimage = + fields( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + streamKey, + outboxSequence, + eventId, + billingEvent, + source); + String digest = digest(canonical(preimage)); + Map wire = new LinkedHashMap<>(preimage); + wire.put("eventDigest", digest); + byte[] payload = canonical(wire); + return new Event( + request.requestId(), + request.requestDigest(), + request.canonicalTenantId(), + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + streamKey, + outboxSequence, + eventId, + billingEvent.outboxStreamKey(), + billingEvent.tenantBillingSequence(), + billingEvent.eventId(), + billingEvent.eventDigest(), + source, + digest, + payload); + } + + /** Parses and verifies the exact canonical Account authority event bytes. */ + public static Event verify(byte[] payload) { + if (payload == null || payload.length == 0 || payload.length > 32 * 1024) { + throw new IllegalArgumentException("Tenant authority event payload is absent or oversized"); + } + final Map wire; + try { + wire = JSON.readValue(payload, new TypeReference<>() {}); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Tenant authority event payload is malformed", exception); + } + if (!wire.keySet().equals(EVENT_FIELDS)) { + throw new IllegalArgumentException("Tenant authority event fields are incomplete or unknown"); + } + String claimedDigest = text(wire.get("eventDigest"), "eventDigest"); + Map preimage = new LinkedHashMap<>(wire); + preimage.remove("eventDigest"); + if (!claimedDigest.equals(digest(canonical(preimage))) + || !Arrays.equals(payload, canonical(wire))) { + throw new IllegalArgumentException("Tenant authority event digest or canonical bytes differ"); + } + String schemaVersion = text(wire.get("schemaVersion"), "schemaVersion"); + String eventType = text(wire.get("eventType"), "eventType"); + UUID tenantId = uuid(wire.get("tenantId"), "tenantId"); + UUID requestId = uuid(wire.get("requestId"), "requestId"); + UUID eventId = uuid(wire.get("eventId"), "eventId"); + String requestDigest = digestText(wire.get("requestDigest"), "requestDigest"); + String streamKey = text(wire.get("outboxStreamKey"), "outboxStreamKey"); + long authorityGeneration = + positiveDecimal(wire.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + long sourceVersion = + positiveDecimal(wire.get("tenantAuthoritySourceVersion"), "tenantAuthoritySourceVersion"); + long sequence = positiveDecimal(wire.get("outboxSequence"), "outboxSequence"); + if (!SCHEMA_VERSION.equals(schemaVersion) + || !EVENT_TYPE.equals(eventType) + || !streamKey(tenantId).equals(streamKey) + || !eventId(requestId).equals(eventId)) { + throw new IllegalArgumentException("Tenant authority event scope or identity is invalid"); + } + + Map billing = object(wire.get("tenantBillingReceipt"), "tenantBillingReceipt"); + if (!billing.keySet().equals(BILLING_FIELDS)) { + throw new IllegalArgumentException("Tenant billing receipt fields are incomplete"); + } + String billingStream = text(billing.get("outboxStreamKey"), "billing outboxStreamKey"); + long billingSequence = + positiveDecimal(billing.get("tenantBillingSequence"), "tenantBillingSequence"); + UUID billingEventId = uuid(billing.get("eventId"), "billing eventId"); + String billingDigest = digestText(billing.get("eventDigest"), "billing eventDigest"); + if (!AccountTenantEntitlementOutboxRepository.streamKey(tenantId).equals(billingStream)) { + throw new IllegalArgumentException("Tenant billing receipt has another tenant scope"); + } + if (!DemoTenantEntitlementEventV1Codec.eventId(requestId).equals(billingEventId)) { + throw new IllegalArgumentException("Tenant billing receipt has another request identity"); + } + + Map sourceMap = object(wire.get("sourceEvidence"), "sourceEvidence"); + if (!sourceMap.keySet().equals(SOURCE_FIELDS)) { + throw new IllegalArgumentException("Tenant source evidence fields are incomplete"); + } + FreshTenantCreationEvidence source = + new FreshTenantCreationEvidence( + integer(sourceMap.get("schemaVersion"), "source schemaVersion"), + text(sourceMap.get("targetNamespace"), "source targetNamespace"), + uuid(sourceMap.get("creationRequestId"), "source creationRequestId"), + uuid(sourceMap.get("operationId"), "source operationId"), + digestText(sourceMap.get("requestDigest"), "source requestDigest"), + uuid(sourceMap.get("canonicalTenantId"), "source canonicalTenantId"), + positiveDecimal(sourceMap.get("sourceGameRowId"), "source sourceGameRowId"), + text(sourceMap.get("sourceGameTenantKey"), "source sourceGameTenantKey"), + text(sourceMap.get("provenanceKind"), "source provenanceKind"), + digestText(sourceMap.get("evidenceDigest"), "source evidenceDigest")); + if (!tenantId.equals(source.canonicalTenantId()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new IllegalArgumentException("Tenant authority source evidence targets another tenant"); + } + return new Event( + requestId, + requestDigest, + tenantId, + authorityGeneration, + sourceVersion, + streamKey, + sequence, + eventId, + billingStream, + billingSequence, + billingEventId, + billingDigest, + source, + claimedDigest, + payload); + } + + public static UUID eventId(UUID requestId) { + requireUuid(requestId, "request ID"); + return UUID.nameUUIDFromBytes( + (SCHEMA_VERSION + ":" + requestId).getBytes(StandardCharsets.UTF_8)); + } + + private static Map fields( + UUID requestId, + String requestDigest, + UUID tenantId, + long authorityGeneration, + long sourceVersion, + String streamKey, + long sequence, + UUID eventId, + DemoTenantEntitlementEventV1Codec.Event billingEvent, + FreshTenantCreationEvidence source) { + Map values = new LinkedHashMap<>(); + values.put("schemaVersion", SCHEMA_VERSION); + values.put("eventType", EVENT_TYPE); + values.put("eventId", eventId.toString()); + values.put("requestId", requestId.toString()); + values.put("requestDigest", requestDigest); + values.put("tenantId", tenantId.toString()); + values.put("tenantAuthorityGeneration", Long.toString(authorityGeneration)); + values.put("tenantAuthoritySourceVersion", Long.toString(sourceVersion)); + values.put("outboxStreamKey", streamKey); + values.put("outboxSequence", Long.toString(sequence)); + Map billing = new LinkedHashMap<>(); + billing.put("outboxStreamKey", billingEvent.outboxStreamKey()); + billing.put("tenantBillingSequence", Long.toString(billingEvent.tenantBillingSequence())); + billing.put("eventId", billingEvent.eventId().toString()); + billing.put("eventDigest", billingEvent.eventDigest()); + values.put("tenantBillingReceipt", billing); + values.put("sourceEvidence", sourceFields(source)); + return values; + } + + private static Map sourceFields(FreshTenantCreationEvidence source) { + Map values = new LinkedHashMap<>(); + values.put("schemaVersion", source.schemaVersion()); + values.put("targetNamespace", source.targetNamespace()); + values.put("creationRequestId", source.creationRequestId().toString()); + values.put("operationId", source.operationId().toString()); + values.put("requestDigest", source.requestDigest()); + values.put("canonicalTenantId", source.canonicalTenantId().toString()); + values.put("sourceGameRowId", Long.toString(source.sourceGameRowId())); + values.put("sourceGameTenantKey", source.sourceGameTenantKey()); + values.put("provenanceKind", source.provenanceKind()); + values.put("evidenceDigest", source.evidenceDigest()); + return values; + } + + private static byte[] canonical(Map value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException exception) { + throw new IllegalStateException( + "Tenant authority event could not be canonicalized", exception); + } + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map raw)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is not an object"); + } + Map result = new LinkedHashMap<>(); + raw.forEach( + (key, fieldValue) -> { + if (!(key instanceof String textKey)) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " has a bad key"); + } + result.put(textKey, fieldValue); + }); + return result; + } + + private static String text(Object value, String field) { + if (!(value instanceof String text) || text.isBlank() || !text.equals(text.strip())) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return text; + } + + private static String digestText(Object value, String field) { + String text = text(value, field); + if (!DIGEST.matcher(text).matches()) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return text; + } + + private static UUID uuid(Object value, String field) { + try { + String text = text(value, field); + UUID uuid = UUID.fromString(text); + requireUuid(uuid, field); + if (!uuid.toString().equals(text)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is not canonical"); + } + return uuid; + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " is invalid", exception); + } + } + + private static int integer(Object value, String field) { + if (!(value instanceof Integer) || ((Integer) value) <= 0) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + return (Integer) value; + } + + private static long positiveDecimal(Object value, String field) { + String text = text(value, field); + if (!POSITIVE_DECIMAL.matcher(text).matches()) { + throw new IllegalArgumentException("Tenant authority event " + field + " is invalid"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Tenant authority event " + field + " is out of range", exception); + } + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) { + throw new IllegalArgumentException("Tenant authority event " + field + " must be positive"); + } + } + + private static void requireUuid(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException("Tenant authority event " + field + " is required"); + } + } + + /** Exact authority event plus its independent tenant-billing and fresh-source linkage. */ + public record Event( + UUID requestId, + String requestDigest, + UUID tenantId, + long tenantAuthorityGeneration, + long tenantAuthoritySourceVersion, + String outboxStreamKey, + long outboxSequence, + UUID eventId, + String tenantBillingStreamKey, + long tenantBillingSequence, + UUID tenantBillingEventId, + String tenantBillingEventDigest, + FreshTenantCreationEvidence sourceEvidence, + String eventDigest, + byte[] payload) { + public Event { + payload = payload == null ? null : payload.clone(); + requireUuid(requestId, "request ID"); + requireUuid(tenantId, "tenant UUID"); + requireUuid(eventId, "event ID"); + requireUuid(tenantBillingEventId, "billing event ID"); + if (requestDigest == null + || !DIGEST.matcher(requestDigest).matches() + || eventDigest == null + || !DIGEST.matcher(eventDigest).matches() + || tenantBillingEventDigest == null + || !DIGEST.matcher(tenantBillingEventDigest).matches() + || !streamKey(tenantId).equals(outboxStreamKey) + || !AccountTenantEntitlementOutboxRepository.streamKey(tenantId) + .equals(tenantBillingStreamKey) + || tenantAuthorityGeneration <= 0L + || tenantAuthoritySourceVersion <= 0L + || outboxSequence <= 0L + || tenantBillingSequence <= 0L + || sourceEvidence == null + || !tenantId.equals(sourceEvidence.canonicalTenantId()) + || payload == null + || payload.length == 0) { + throw new IllegalArgumentException("Tenant authority event evidence is incomplete"); + } + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java new file mode 100644 index 0000000000..a3840af241 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java @@ -0,0 +1,684 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-local persistence boundary for immutable, non-authorizing delegation evidence bundles. + * + *

Capture consumes the Account-owned, codec-verified issuer/account source snapshot in the same + * transaction as the locked PENDING operation. It never accepts caller-supplied bundle bytes or + * synthesizes an empty checkpoint. The source repository proves a zero checkpoint only from its + * exact fresh-initialization provenance and exhaustive empty history; retained or ambiguous history + * fails closed. + */ +@Repository +public class AccountAuthEvidenceBundleRepository { + private static final String ISSUER_STREAM = + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER; + private static final String OPERATION_TABLE = "account_gameplay_delegation_issuance_operations"; + private static final String BUNDLE_TABLE = "account_gameplay_delegation_auth_evidence_bundles"; + private static final Pattern V4_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern GAME_SESSION_WORKLOAD = + Pattern.compile( + "^spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final AccountAuthorityGenerationRepository authorityGenerations; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator preconditions fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountAuthEvidenceBundleRepository( + DSLContext dsl, + AccountAuthorityGenerationRepository authorityGenerations, + AccountAuthorityOutboxRepository authorityOutbox) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.authorityGenerations = + Objects.requireNonNull(authorityGenerations, "Account authority repository is required"); + Objects.requireNonNull(authorityOutbox, "Account authority outbox is required"); + this.sourceEvidence = + new AccountAuthoritySourceEvidenceRepository(dsl, authorityGenerations, authorityOutbox); + } + + /** + * Captures and immutably persists source evidence for the exact Account-owned PENDING row. Caller + * data supplies only the lookup identity; every value in the bundle is read from locked Account + * operation, identity, authority, source, and retained-event rows. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountAuthEvidenceBundle captureAndPersist(UUID requestId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(requestId, "Request ID is required"); + // This first read only discovers immutable row identity. It does not authorize capture or lock + // the operation before the Account and composite authority rows. + Record preliminary = + dsl.fetchOne( + "SELECT operation_id, request_id, account_uuid FROM " + + OPERATION_TABLE + + " WHERE request_id = ?", + requestId); + if (preliminary == null) throw new OperationNotFoundException(); + UUID preliminaryRequestId = preliminary.get("request_id", UUID.class); + UUID preliminaryOperationId = preliminary.get("operation_id", UUID.class); + UUID preliminaryAccountId = preliminary.get("account_uuid", UUID.class); + if (!requestId.equals(preliminaryRequestId) + || !canonicalV4(preliminaryOperationId) + || preliminaryAccountId == null) { + throw new OwnerEvidenceUnavailableException(); + } + + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id " + + "FROM accounts WHERE account_uuid = ? FOR SHARE", + preliminaryAccountId); + if (account == null) throw new OwnerEvidenceUnavailableException(); + long rowId = positive(account.get("id", Long.class)); + long sourceId = positive(account.get("account_uuid_source_numeric_id", Long.class)); + AccountIdentityProvenance provenance; + try { + provenance = + AccountIdentityProvenance.fromStorageValue( + account.get("account_uuid_provenance", String.class)); + } catch (RuntimeException ex) { + throw new OwnerEvidenceUnavailableException(); + } + if (!preliminaryAccountId.equals(account.get("account_uuid", UUID.class)) + || rowId != sourceId + || !AccountIdentityProvenance.isAccepted(provenance)) { + throw new OwnerEvidenceUnavailableException(); + } + + CompositeSnapshot current = + authorityGenerations.readCompositeSnapshot( + GameSessionAccountDelegationProfile.ISSUER, preliminaryAccountId, List.of(), List.of()); + + // Re-read and lock the operation only after the Account and authority snapshot are locked. + // Every identity/status/authority field is checked again; the preliminary lookup is never + // evidence for capture. + Record operation = + dsl.fetchOne( + "SELECT * FROM " + OPERATION_TABLE + " WHERE request_id = ? FOR UPDATE", requestId); + if (operation == null) throw new OwnerEvidenceUnavailableException(); + UUID storedRequestId = operation.get("request_id", UUID.class); + UUID operationId = operation.get("operation_id", UUID.class); + UUID accountId = operation.get("account_uuid", UUID.class); + UUID callerContextId = operation.get("caller_context_id", UUID.class); + UUID tokenJti = operation.get("token_jti", UUID.class); + String requestDigest = operation.get("request_digest", String.class); + String callerWorkload = operation.get("caller_workload", String.class); + if (!requestId.equals(storedRequestId) + || !requestId.equals(preliminaryRequestId) + || !preliminaryOperationId.equals(operationId) + || !preliminaryAccountId.equals(accountId) + || !canonicalV4(operationId) + || !canonicalV4(callerContextId) + || !canonicalV4(tokenJti) + || requestDigest == null + || !SHA256.matcher(requestDigest).matches() + || !"PENDING".equals(operation.get("status", String.class)) + || callerWorkload == null + || !GAME_SESSION_WORKLOAD.matcher(callerWorkload).matches()) { + throw new OwnerEvidenceUnavailableException(); + } + requireExactPendingAuthority(operation, current, accountId); + final IssuerAccountSourceSnapshot sources; + try { + sources = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId); + } catch (RuntimeException ex) { + throw new OwnerEvidenceUnavailableException(); + } + requireExactSourceSnapshot(sources, current, operation, account, accountId); + + Record prior = + dsl.fetchOne( + "SELECT operation_id FROM " + BUNDLE_TABLE + " WHERE operation_id = ?", operationId); + if (prior != null) { + AccountAuthEvidenceBundle stored = readStoredNonAuthorizingValue(operationId); + AccountAuthEvidenceBundle expected = + makeBundle(operation, account, sources, storedBundleReference(stored)); + if (!MessageDigest.isEqual(expected.canonicalBytes(), stored.canonicalBytes())) { + throw new OwnerEvidenceUnavailableException(); + } + return stored; + } + + String transactionId = currentTransactionId(); + String sourceFence = allocateSourceFence(operationId, transactionId); + AccountAuthEvidenceBundle.BundleReference bundleReference = + new AccountAuthEvidenceBundle.BundleReference( + "1", transactionId, sourceFence, transactionId); + AccountAuthEvidenceBundle candidate = makeBundle(operation, account, sources, bundleReference); + int inserted = + dsl.execute( + "INSERT INTO " + + BUNDLE_TABLE + + " (operation_id, request_id, account_uuid, bundle_schema, bundle_version, " + + "source_version, source_fence, issuance_fence, linearization, canonical_sha256, " + + "canonical_bundle_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT DO NOTHING", + operationId, + requestId, + accountId, + AccountAuthEvidenceBundle.SCHEMA, + bundleReference.bundleVersion(), + bundleReference.sourceVersion(), + bundleReference.sourceFence(), + Long.toString(sources.issuanceFence().value()), + bundleReference.linearization(), + candidate.canonicalSha256(), + candidate.canonicalBytes()); + AccountAuthEvidenceBundle readback = readStoredNonAuthorizingValue(operationId); + if (inserted != 1 + || !MessageDigest.isEqual(candidate.canonicalBytes(), readback.canonicalBytes())) { + throw new OwnerEvidenceUnavailableException(); + } + return readback; + } + + /** + * Returns a strictly parsed immutable value for diagnostics/reconciliation only; this method does + * not revalidate or grant source freshness, promotion, activation, or caller authority. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountAuthEvidenceBundle readStoredNonAuthorizingValue(UUID operationId) { + Objects.requireNonNull(operationId, "Operation ID is required"); + Record row = + dsl.fetchOne( + "SELECT operation_id, request_id, account_uuid, bundle_schema, canonical_sha256, " + + "bundle_version, source_version, source_fence, issuance_fence, linearization, " + + "canonical_bundle_bytes FROM " + + BUNDLE_TABLE + + " WHERE operation_id = ?", + operationId); + if (row == null) throw new StoredBundleUnavailableException(); + try { + if (!operationId.equals(row.get("operation_id", UUID.class))) { + throw new StoredBundleUnavailableException(); + } + AccountAuthEvidenceBundle bundle = + AccountAuthEvidenceBundle.parseCanonical(row.get("canonical_bundle_bytes", byte[].class)); + String digest = row.get("canonical_sha256", String.class); + if (!MessageDigest.isEqual( + bundle.canonicalSha256().getBytes(StandardCharsets.US_ASCII), + Objects.toString(digest, "").getBytes(StandardCharsets.US_ASCII)) + || !AccountAuthEvidenceBundle.SCHEMA.equals(row.get("bundle_schema", String.class)) + || !Objects.equals( + operationId.toString(), nestedText(bundle.fields(), "operation", "operationId")) + || !Objects.equals( + row.get("request_id", UUID.class).toString(), + nestedText(bundle.fields(), "operation", "requestId")) + || !Objects.equals( + row.get("account_uuid", UUID.class).toString(), + nestedText(bundle.fields(), "scope", "accountId")) + || !Objects.equals( + row.get("bundle_version", String.class), + nestedText(bundle.fields(), "bundleRef", "bundleVersion")) + || !Objects.equals( + row.get("source_version", String.class), + nestedText(bundle.fields(), "bundleRef", "sourceVersion")) + || !Objects.equals( + row.get("source_fence", String.class), + nestedText(bundle.fields(), "bundleRef", "sourceFence")) + || !Objects.equals( + row.get("issuance_fence", String.class), + Objects.toString(bundle.fields().get("issuanceFence"), null)) + || !Objects.equals( + row.get("linearization", String.class), + nestedText(bundle.fields(), "bundleRef", "linearization"))) { + throw new StoredBundleUnavailableException(); + } + return bundle; + } catch (RuntimeException ex) { + if (ex instanceof StoredBundleUnavailableException unavailable) throw unavailable; + throw new StoredBundleUnavailableException(); + } + } + + private static void requireExactPendingAuthority( + Record operation, CompositeSnapshot snapshot, UUID accountId) { + if (snapshot.account().scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ACCOUNT + || !accountId.equals(snapshot.account().scope().accountId()) + || snapshot.account().scope().issuerId() != null + || snapshot.account().scope().tenantId() != null + || snapshot.issuer().scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ISSUER + || !GameSessionAccountDelegationProfile.ISSUER.equals(snapshot.issuer().scope().issuerId()) + || snapshot.issuer().scope().accountId() != null + || snapshot.issuer().scope().tenantId() != null + || !snapshot.tenants().isEmpty() + || !snapshot.memberships().isEmpty() + || !Objects.equals( + operation.get("authority_issuer_generation", Long.class), + snapshot.issuer().generation()) + || !Objects.equals( + operation.get("authority_issuer_source_version", Long.class), + snapshot.issuer().sourceVersion()) + || !Objects.equals( + operation.get("authority_account_generation", Long.class), + snapshot.account().generation()) + || !Objects.equals( + operation.get("authority_account_source_version", Long.class), + snapshot.account().sourceVersion()) + || !Objects.equals( + operation.get("issuance_fence", Long.class), snapshot.issuanceFence().value()) + || !Objects.equals( + operation.get("issuance_fence_source_version", Long.class), + snapshot.issuanceFence().sourceVersion()) + || !accountId.equals(snapshot.issuanceFence().accountId())) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static void requireExactSourceSnapshot( + IssuerAccountSourceSnapshot sources, + CompositeSnapshot current, + Record operation, + Record account, + UUID accountId) { + CurrentSourceEvidence issuer = sources.issuer(); + CurrentSourceEvidence accountSource = sources.account(); + String accountStream = "account:auth-authority:v1:account/" + accountId; + if (issuer.scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ISSUER + || !GameSessionAccountDelegationProfile.ISSUER.equals(issuer.scope().issuerId()) + || issuer.scope().accountId() != null + || issuer.scope().tenantId() != null + || accountSource.scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ACCOUNT + || !accountId.equals(accountSource.scope().accountId()) + || accountSource.scope().issuerId() != null + || accountSource.scope().tenantId() != null + || !ISSUER_STREAM.equals(issuer.checkpoint().outboxStreamKey()) + || !accountStream.equals(accountSource.checkpoint().outboxStreamKey()) + || issuer.generation() != current.issuer().generation() + || issuer.sourceVersion() != current.issuer().sourceVersion() + || accountSource.generation() != current.account().generation() + || accountSource.sourceVersion() != current.account().sourceVersion() + || !Objects.equals(accountSource.issuanceFence(), sources.issuanceFence()) + || !Objects.equals(sources.issuanceFence(), current.issuanceFence()) + || !Objects.equals( + operation.get("authority_issuer_generation", Long.class), issuer.generation()) + || !Objects.equals( + operation.get("authority_issuer_source_version", Long.class), issuer.sourceVersion()) + || !Objects.equals( + operation.get("authority_account_generation", Long.class), accountSource.generation()) + || !Objects.equals( + operation.get("authority_account_source_version", Long.class), + accountSource.sourceVersion()) + || !Objects.equals( + operation.get("issuance_fence", Long.class), sources.issuanceFence().value()) + || !Objects.equals( + operation.get("issuance_fence_source_version", Long.class), + sources.issuanceFence().sourceVersion()) + || !"ISSUER_SCOPE_INSERT".equals(issuer.initializationProvenance()) + || !"ACCOUNT_REPOSITORY_INSERT".equals(accountSource.initializationProvenance()) + || !Objects.equals( + positive(account.get("id", Long.class)), accountSource.accountSourceNumericId()) + || !Objects.equals( + account.get("account_uuid_provenance", String.class), + accountSource.accountUuidProvenance())) { + throw new OwnerEvidenceUnavailableException(); + } + Map tuple = authorityTuple(sources); + if (!MessageDigest.isEqual( + canonicalJson(tuple), requiredBytes(operation, "authority_tuple_canonical_bytes")) + || !MessageDigest.isEqual( + requiredBytes(operation, "membership_version_canonical_bytes"), + "{}".getBytes(StandardCharsets.US_ASCII))) { + // The exact current tuple, including an applicable Account security cutoff, must match the + // immutable PENDING operation. A baseline-only or synthesized-empty tuple is not accepted. + throw new OwnerEvidenceUnavailableException(); + } + } + + private AccountAuthEvidenceBundle makeBundle( + Record operation, + Record account, + IssuerAccountSourceSnapshot sources, + AccountAuthEvidenceBundle.BundleReference bundleReference) { + UUID accountId = requiredUuid(operation, "account_uuid"); + UUID operationId = requiredUuid(operation, "operation_id"); + UUID requestId = requiredUuid(operation, "request_id"); + UUID callerContextId = requiredUuid(operation, "caller_context_id"); + UUID tokenJti = requiredUuid(operation, "token_jti"); + String requestDigest = requiredText(operation, "request_digest"); + String callerWorkload = requiredText(operation, "caller_workload"); + long issuedAt = positive(operation.get("issued_at_epoch_second", Long.class)); + long notBefore = positive(operation.get("not_before_epoch_second", Long.class)); + long expiresAt = positive(operation.get("expires_at_epoch_second", Long.class)); + long tokenGeneration = positive(operation.get("token_generation", Long.class)); + Map tuple = authorityTuple(sources); + Map sourceVersions = sourceVersions(sources); + List checkpoints = + List.of( + checkpoint(sources.account().checkpoint()), checkpoint(sources.issuer().checkpoint())); + long sourceRowId = positive(account.get("id", Long.class)); + AccountIdentityProvenance provenance = + AccountIdentityProvenance.fromStorageValue( + requiredText(account, "account_uuid_provenance")); + long sourceNumericId = positive(account.get("account_uuid_source_numeric_id", Long.class)); + AccountAuthEvidenceBundle.AccountIdentitySource identitySource = + new AccountAuthEvidenceBundle.AccountIdentitySource( + sourceRowId, provenance, sourceNumericId); + String snapshotIdentity = + sha256( + canonicalJson( + snapshotIdentityPreimage( + sources, accountId, identitySource, tuple, sourceVersions))); + String evaluationIdentity = + sha256( + canonicalJson( + evaluationIdentityPreimage( + snapshotIdentity, + bundleReference, + operationId, + requestId, + requestDigest, + callerWorkload, + callerContextId, + accountId, + tokenJti, + tokenGeneration, + issuedAt, + notBefore, + expiresAt))); + return AccountAuthEvidenceBundle.fromOwnerEvaluation( + new AccountAuthEvidenceBundle.OwnerEvaluation( + new AccountAuthEvidenceBundle.BundleReference( + bundleReference.bundleVersion(), + bundleReference.sourceVersion(), + bundleReference.sourceFence(), + bundleReference.linearization()), + snapshotIdentity, + evaluationIdentity, + accountId, + new AccountAuthEvidenceBundle.OperationIdentity( + operationId, requestId, requestDigest, callerWorkload, callerContextId, accountId), + new AccountAuthEvidenceBundle.TokenIdentity( + tokenJti, tokenGeneration, issuedAt, notBefore, expiresAt), + tuple, + sources.issuanceFence().value(), + new AccountAuthEvidenceBundle.AuthoritySourceVersions( + sources.issuer().sourceVersion(), + sources.account().sourceVersion(), + sources.issuanceFence().sourceVersion()), + identitySource, + checkpoints)); + } + + private static Map authorityTuple(IssuerAccountSourceSnapshot sources) { + return GameSessionAccountDelegationProfile.authorityTuple( + sources.issuer().generation(), + sources.account().generation(), + sources + .account() + .accountSecurityCutoff() + .map( + cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))); + } + + private static Map sourceVersions(IssuerAccountSourceSnapshot sources) { + Map versions = new LinkedHashMap<>(); + versions.put("issuerSourceVersion", Long.toString(sources.issuer().sourceVersion())); + versions.put("accountSourceVersion", Long.toString(sources.account().sourceVersion())); + versions.put( + "issuanceFenceSourceVersion", Long.toString(sources.issuanceFence().sourceVersion())); + return versions; + } + + private static AccountAuthEvidenceBundle.OutboxCheckpoint checkpoint(SourceCheckpoint source) { + return new AccountAuthEvidenceBundle.OutboxCheckpoint( + source.outboxStreamKey(), + source.sequence(), + source.sourceEventId().orElse(null), + source.sourceEventDigest().orElse(null)); + } + + private static Map snapshotIdentityPreimage( + IssuerAccountSourceSnapshot sources, + UUID accountId, + AccountAuthEvidenceBundle.AccountIdentitySource identitySource, + Map tuple, + Map sourceVersions) { + Map snapshot = new LinkedHashMap<>(); + snapshot.put("domain", "firemud/account-auth-evidence/snapshot/v1"); + snapshot.put("schema", AccountAuthEvidenceBundle.SCHEMA); + snapshot.put("issuer", GameSessionAccountDelegationProfile.ISSUER); + snapshot.put("profile", GameSessionAccountDelegationProfile.PROFILE); + snapshot.put("accountId", accountId.toString()); + snapshot.put("authorityTuple", tuple); + snapshot.put("issuanceFence", Long.toString(sources.issuanceFence().value())); + snapshot.put("authoritySourceVersions", sourceVersions); + snapshot.put("issuerCheckpoint", checkpointFields(sources.issuer().checkpoint())); + snapshot.put("accountCheckpoint", checkpointFields(sources.account().checkpoint())); + snapshot.put("issuerInitializationProvenance", sources.issuer().initializationProvenance()); + snapshot.put("accountInitializationProvenance", sources.account().initializationProvenance()); + snapshot.put("accountIdentitySource", identitySourceFields(identitySource)); + return snapshot; + } + + private static Map evaluationIdentityPreimage( + String snapshotIdentity, + AccountAuthEvidenceBundle.BundleReference bundleReference, + UUID operationId, + UUID requestId, + String requestDigest, + String callerWorkload, + UUID callerContextId, + UUID accountId, + UUID tokenJti, + long tokenGeneration, + long issuedAt, + long notBefore, + long expiresAt) { + Map operation = new LinkedHashMap<>(); + operation.put("operationId", operationId.toString()); + operation.put("requestId", requestId.toString()); + operation.put("requestDigest", requestDigest); + operation.put("callerWorkload", callerWorkload); + operation.put("callerContextId", callerContextId.toString()); + operation.put("accountId", accountId.toString()); + Map token = new LinkedHashMap<>(); + token.put("jti", tokenJti.toString()); + token.put("tokenGeneration", Long.toString(tokenGeneration)); + token.put("iat", issuedAt); + token.put("nbf", notBefore); + token.put("exp", expiresAt); + Map evaluation = new LinkedHashMap<>(); + evaluation.put("domain", "firemud/account-auth-evidence/evaluation/v1"); + evaluation.put("schema", AccountAuthEvidenceBundle.SCHEMA); + evaluation.put("snapshotIdentity", snapshotIdentity); + evaluation.put( + "bundleRef", + Map.of( + "bundleVersion", bundleReference.bundleVersion(), + "sourceVersion", bundleReference.sourceVersion(), + "sourceFence", bundleReference.sourceFence(), + "linearization", bundleReference.linearization())); + evaluation.put("operation", operation); + evaluation.put("tokenIdentity", token); + evaluation.put("membershipVersion", Map.of()); + return evaluation; + } + + private static Map checkpointFields(SourceCheckpoint checkpoint) { + Map fields = new LinkedHashMap<>(); + fields.put("outboxStreamKey", checkpoint.outboxStreamKey()); + fields.put("outboxSequence", Long.toString(checkpoint.sequence())); + checkpoint.sourceEventId().ifPresent(value -> fields.put("sourceEventId", value)); + checkpoint.sourceEventDigest().ifPresent(value -> fields.put("sourceEventDigest", value)); + return fields; + } + + private static Map identitySourceFields( + AccountAuthEvidenceBundle.AccountIdentitySource identitySource) { + Map fields = new LinkedHashMap<>(); + fields.put("sourceRowId", Long.toString(identitySource.sourceRowId())); + fields.put("provenance", identitySource.provenance().name()); + fields.put("sourceNumericId", Long.toString(identitySource.sourceNumericId())); + return fields; + } + + private String currentTransactionId() { + Record transaction = dsl.fetchOne("SELECT pg_current_xact_id()::text AS transaction_id"); + String value = transaction == null ? null : transaction.get("transaction_id", String.class); + if (value == null || !value.matches("[1-9][0-9]{0,19}")) { + throw new OwnerEvidenceUnavailableException(); + } + try { + if (new java.math.BigInteger(value).bitLength() > 64) { + throw new OwnerEvidenceUnavailableException(); + } + } catch (NumberFormatException ex) { + throw new OwnerEvidenceUnavailableException(); + } + return value; + } + + private static AccountAuthEvidenceBundle.BundleReference storedBundleReference( + AccountAuthEvidenceBundle stored) { + Object reference = stored.fields().get("bundleRef"); + if (!(reference instanceof Map fields) + || !(fields.get("bundleVersion") instanceof String bundleVersion) + || !(fields.get("sourceVersion") instanceof String sourceVersion) + || !(fields.get("sourceFence") instanceof String sourceFence) + || !(fields.get("linearization") instanceof String linearization)) { + throw new StoredBundleUnavailableException(); + } + try { + return new AccountAuthEvidenceBundle.BundleReference( + bundleVersion, sourceVersion, sourceFence, linearization); + } catch (RuntimeException ex) { + throw new StoredBundleUnavailableException(); + } + } + + private String allocateSourceFence(UUID operationId, String transactionId) { + Record allocation = + dsl.fetchOne( + "UPDATE account_gameplay_auth_evidence_source_fence " + + "SET last_source_fence = last_source_fence + 1, last_operation_id = ?, " + + "last_transaction_id = ? " + + "WHERE allocator_id = TRUE AND last_source_fence < 9223372036854775807 " + + "RETURNING last_source_fence", + operationId, + transactionId); + if (allocation == null) throw new OwnerEvidenceUnavailableException(); + Long sourceFence = allocation.get("last_source_fence", Long.class); + if (sourceFence == null || sourceFence <= 0L) { + throw new OwnerEvidenceUnavailableException(); + } + return Long.toString(sourceFence); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException ex) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null) throw new OwnerEvidenceUnavailableException(); + return value; + } + + private static String requiredText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw new OwnerEvidenceUnavailableException(); + return value; + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) throw new OwnerEvidenceUnavailableException(); + return value.clone(); + } + + private static long positive(Long value) { + if (value == null || value <= 0L) throw new OwnerEvidenceUnavailableException(); + return value; + } + + private static boolean canonicalV4(UUID value) { + return value != null && value.version() == 4 && V4_UUID.matcher(value.toString()).matches(); + } + + private static String nestedText(Map root, String parent, String child) { + Object value = root.get(parent); + if (!(value instanceof Map object)) throw new StoredBundleUnavailableException(); + Object nested = object.get(child); + if (!(nested instanceof String text)) throw new StoredBundleUnavailableException(); + return text; + } + + private static void requireWritableAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account auth-evidence capture requires a writable Account transaction"); + } + } + + public static final class OwnerEvidenceUnavailableException extends IllegalStateException { + public OwnerEvidenceUnavailableException() { + super("Account owner source and retained-history evidence is unavailable or ambiguous"); + } + } + + public static final class OperationNotFoundException extends IllegalStateException { + public OperationNotFoundException() { + super("Account gameplay delegation operation is absent"); + } + } + + public static final class StoredBundleUnavailableException extends IllegalStateException { + public StoredBundleUnavailableException() { + super("Stored Account auth-evidence bundle is unavailable or malformed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java index 1d7d6dec6c..34f9e93da8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java @@ -7,6 +7,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; @@ -14,8 +15,14 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback.RetainedEventEvidence; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountEvent; import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountPreimage; @@ -29,6 +36,7 @@ import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Owns explicit fresh source baselines and exact Account/issuer authority event append/readback. @@ -79,14 +87,20 @@ public CurrentSourceEvidence initializeIssuerIfAbsent(String exactIssuerId) { @Transactional(propagation = Propagation.MANDATORY) public void initializeFreshAccount(AccountRepository.FreshAccountInsert proof) { Objects.requireNonNull(proof, "fresh Account repository insert proof is required"); - initializeIssuerIfAbsent(ACCOUNT_ISSUER); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new SourceEvidenceUnavailableException(); + } long accountInsertTransactionId = requireFreshAccountReadback(proof); + initializeIssuerIfAbsent(ACCOUNT_ISSUER); ScopeState accountState = generations.initializeAccountForFreshRepositoryInsert(proof); insertFreshBaseline( AuthorityScope.account(proof.accountUuid()), accountState, new AccountIdentitySource(proof.accountId(), accountInsertTransactionId)); readCurrentSource(AuthorityScope.account(proof.accountUuid()), accountState); + new AccountPlatformRestrictionBirthRepository(dsl) + .initializeFreshAccount(proof, accountInsertTransactionId, accountState); } /** @@ -195,7 +209,203 @@ public IssuerAccountSourceSnapshot readCurrentIssuerAccountSources( || !account.issuanceFence().equals(snapshot.account().issuanceFence())) { throw new SourceEvidenceUnavailableException(); } - return new IssuerAccountSourceSnapshot(issuer, account, snapshot.issuanceFence()); + AccountAuthoritySourceEventReadback.LatestSourceSnapshot closedSource = + closedEventReadback() + .requireCurrentLatest( + readAccountIdentityForClosedReadback(accountUuid), snapshot.account()); + if (closedSource.outboxSequence() != account.checkpoint().sequence()) { + throw new SourceEvidenceUnavailableException(); + } + if (closedSource.outboxSequence() == 0L) { + if (closedSource.latestEvent().isPresent() + || account.checkpoint().sourceEventId().isPresent() + || account.checkpoint().sourceEventDigest().isPresent()) { + throw new SourceEvidenceUnavailableException(); + } + } else { + Event closedEvent = closedSource.latestEvent().orElseThrow(); + if (closedEvent.outboxSequence() != account.checkpoint().sequence() + || !closedEvent.eventId().equals(account.checkpoint().sourceEventId().orElseThrow()) + || !closedEvent + .eventDigest() + .equals(account.checkpoint().sourceEventDigest().orElseThrow())) { + throw new SourceEvidenceUnavailableException(); + } + } + AccountGenerationProjection accountProjection = + AccountGenerationProjection.fromSource( + new AccountSourceSnapshot( + accountUuid, + snapshot.account(), + account.checkpoint().outboxStreamKey(), + account.checkpoint().sequence(), + closedSource.latestEvent())); + return new IssuerAccountSourceSnapshot( + issuer, + account, + snapshot.issuanceFence(), + accountProjection, + IssuerGenerationProjection.fromSource( + new CanonicalIssuerSourceSnapshot( + issuer, + issuer.checkpoint().sequence() == 0L + ? Optional.empty() + : Optional.of( + outbox + .findEvent( + issuer.checkpoint().outboxStreamKey(), + issuer.checkpoint().sequence()) + .orElseThrow(SourceEvidenceUnavailableException::new))))); + } + + /** + * Prepares exactly one Account-local advance against the complete current source readback. This + * is not authorization or a committed receipt. The closed event, immutable operation receipt and + * source head must all complete in this same owner transaction; deferred SQL consistency guards + * reject an incomplete transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ScopeState prepareClosedAccountAdvance(UUID accountUuid, CurrentSourceEvidence expected) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || accountUuid == null + || accountUuid.equals(new UUID(0L, 0L)) + || expected == null + || !AuthorityScope.account(accountUuid).equals(expected.scope()) + || expected.issuanceFence() == null) { + throw new SourceEvidenceUnavailableException(); + } + AuthorityScope scope = AuthorityScope.account(accountUuid); + ScopeState current = generations.read(scope); + CurrentSourceEvidence actual = readCurrentSource(scope, current); + if (!expected.equals(actual) || !expected.issuanceFence().equals(current.issuanceFence())) { + throw new SourceEvidenceUnavailableException(); + } + long nextGeneration = Math.addExact(current.generation(), 1L); + long nextSourceVersion = Math.addExact(current.sourceVersion(), 1L); + long nextFence = Math.addExact(current.issuanceFence().value(), 1L); + long nextFenceVersion = Math.addExact(current.issuanceFence().sourceVersion(), 1L); + ScopeState advanced = generations.advanceForSourceEvidence(current, current.issuanceFence()); + if (!scope.equals(advanced.scope()) + || advanced.generation() != nextGeneration + || advanced.sourceVersion() != nextSourceVersion + || advanced.issuanceFence() == null + || !accountUuid.equals(advanced.issuanceFence().accountId()) + || advanced.issuanceFence().value() != nextFence + || advanced.issuanceFence().sourceVersion() != nextFenceVersion) { + throw new SourceEvidenceUnavailableException(); + } + return advanced; + } + + /** + * Advances the canonical Account source head only after a closed operation's immutable owner + * receipt and exact outbox event have been stored in this same owner transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CurrentSourceEvidence advanceClosedAccountHead( + UUID accountUuid, ScopeState expected, ScopeState advanced, Event event) { + Objects.requireNonNull(accountUuid, "Account UUID is required"); + Objects.requireNonNull(expected, "expected Account source state is required"); + Objects.requireNonNull(advanced, "advanced Account source state is required"); + Objects.requireNonNull(event, "closed Account source event is required"); + AuthorityScope scope = AuthorityScope.account(accountUuid); + if (!scope.equals(expected.scope()) + || !scope.equals(advanced.scope()) + || expected.issuanceFence() == null + || advanced.issuanceFence() == null + || advanced.generation() != Math.addExact(expected.generation(), 1L) + || advanced.sourceVersion() != Math.addExact(expected.sourceVersion(), 1L) + || advanced.issuanceFence().value() != Math.addExact(expected.issuanceFence().value(), 1L) + || advanced.issuanceFence().sourceVersion() + != Math.addExact(expected.issuanceFence().sourceVersion(), 1L)) { + throw new SourceEvidenceUnavailableException(); + } + + // The typed producer has already appended the event, but source_records must still contain + // the exact old head. Read and authenticate that previous head while allowing only this one + // pending outbox append; a normal current-source read would correctly reject the transaction's + // temporarily advanced stream checkpoint. + CurrentSourceEvidence before = readPreviousSourceForClosedAppend(scope, expected, event); + long expectedSequence = Math.addExact(before.checkpoint().sequence(), 1L); + RetainedEventEvidence receiptEvidence = + closedEventReadback() + .requireRetainedEvent( + readAccountIdentityForClosedReadback(accountUuid), event, advanced); + if (!streamKey(scope).equals(event.outboxStreamKey()) + || event.outboxSequence() != expectedSequence + || advanced.generation() != receiptEvidence.accountAuthorityGeneration() + || advanced.sourceVersion() != receiptEvidence.sourceVersion() + || receiptEvidence.issuanceFence() != advanced.issuanceFence().value() + || receiptEvidence.issuanceFenceSourceVersion() + != advanced.issuanceFence().sourceVersion()) { + throw new SourceEvidenceUnavailableException(); + } + Event bySequence = + outbox + .findEvent(event.outboxStreamKey(), event.outboxSequence()) + .orElseThrow(SourceEvidenceUnavailableException::new); + Event byRequest = + outbox + .findEvent(event.outboxStreamKey(), event.requestId()) + .orElseThrow(SourceEvidenceUnavailableException::new); + if (!event.equals(bySequence) || !event.equals(byRequest)) { + throw new SourceEvidenceUnavailableException(); + } + Checkpoint checkpoint = + outbox + .readCheckpoint(event.outboxStreamKey()) + .orElseThrow(SourceEvidenceUnavailableException::new); + if (checkpoint.outboxSequence() != expectedSequence + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new SourceEvidenceUnavailableException(); + } + var typedCutoff = receiptEvidence.accountSecurityCutoff(); + updateSourceHead( + before, + event, + new AccountSecurityCutoff( + typedCutoff.accountAuthorityGeneration(), + typedCutoff.outboxStreamKey(), + typedCutoff.outboxSequence()), + advanced, + advanced.issuanceFence()); + CurrentSourceEvidence current = readCurrentSource(scope, advanced); + if (current.checkpoint().sequence() != event.outboxSequence() + || !current.checkpoint().sourceEventId().orElseThrow().equals(event.eventId()) + || !current.checkpoint().sourceEventDigest().orElseThrow().equals(event.eventDigest())) { + throw new SourceEvidenceUnavailableException(); + } + Account latestAccount = readAccountIdentityForClosedReadback(accountUuid); + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest = + closedEventReadback().requireCurrentLatest(latestAccount, advanced); + if (latest.outboxSequence() != event.outboxSequence() + || latest.latestEvent().isEmpty() + || !event.equals(latest.latestEvent().orElseThrow())) { + throw new SourceEvidenceUnavailableException(); + } + return current; + } + + /** Returns the actual current issuer source and its retained terminal event without mutation. */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalIssuerSourceSnapshot readCurrentCanonicalIssuerSource(String exactIssuerId) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new SourceEvidenceUnavailableException(); + } + AuthorityScope scope = AuthorityScope.issuer(exactIssuerId); + CurrentSourceEvidence current = readCurrentSource(scope, generations.read(scope)); + Optional latest = + current.checkpoint().sequence() == 0L + ? Optional.empty() + : Optional.of( + outbox + .findEvent( + current.checkpoint().outboxStreamKey(), current.checkpoint().sequence()) + .orElseThrow(SourceEvidenceUnavailableException::new)); + return new CanonicalIssuerSourceSnapshot(current, latest); } /** Records an explicit issuer-wide mutation with exact event readback and no Account cutoff. */ @@ -287,13 +497,42 @@ private void insertFreshBaseline( } private CurrentSourceEvidence readCurrentSource(AuthorityScope scope, ScopeState authority) { - return readCurrentSource(scope, authority, Optional.empty()); + return readCurrentSource(scope, authority, Optional.empty(), false); } private CurrentSourceEvidence readCurrentSource( AuthorityScope scope, ScopeState authority, Optional expectedPreUpdateAccountState) { + return readCurrentSource(scope, authority, expectedPreUpdateAccountState, false); + } + + private CurrentSourceEvidence readPreviousSourceForClosedAppend( + AuthorityScope scope, ScopeState authority, Event pendingEvent) { + CurrentSourceEvidence before = readCurrentSource(scope, authority, Optional.empty(), true); + if (!streamKey(scope).equals(pendingEvent.outboxStreamKey()) + || pendingEvent.outboxSequence() != Math.addExact(before.checkpoint().sequence(), 1L)) { + throw new SourceEvidenceUnavailableException(); + } + Event exactPending = + outbox + .findEvent(pendingEvent.outboxStreamKey(), pendingEvent.outboxSequence()) + .orElseThrow(SourceEvidenceUnavailableException::new); + Event requestMatch = + outbox + .findEvent(pendingEvent.outboxStreamKey(), pendingEvent.requestId()) + .orElseThrow(SourceEvidenceUnavailableException::new); + if (!pendingEvent.equals(exactPending) || !pendingEvent.equals(requestMatch)) { + throw new SourceEvidenceUnavailableException(); + } + return before; + } + + private CurrentSourceEvidence readCurrentSource( + AuthorityScope scope, + ScopeState authority, + Optional expectedPreUpdateAccountState, + boolean allowOnePendingAppend) { String key = streamKey(scope); Record source = dsl.fetchOne( @@ -337,12 +576,25 @@ private CurrentSourceEvidence readCurrentSource( "SELECT last_sequence FROM account_authority_outbox_streams " + "WHERE outbox_stream_key = ? FOR SHARE", key); - if (stream == null || nonnegative(stream, "last_sequence") != sequence) { + long expectedStreamSequence = allowOnePendingAppend ? Math.addExact(sequence, 1L) : sequence; + if (stream == null || nonnegative(stream, "last_sequence") != expectedStreamSequence) { throw new SourceEvidenceUnavailableException(); } + if (scope.kind() == ScopeKind.ACCOUNT) { + Record eventCountRow = + dsl.fetchOne( + "SELECT count(*) AS event_count FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + key); + Long eventCount = eventCountRow == null ? null : eventCountRow.get("event_count", Long.class); + if (eventCount == null || eventCount != expectedStreamSequence) { + throw new SourceEvidenceUnavailableException(); + } + } + SourceCheckpoint checkpoint; - Optional cutoff = Optional.empty(); - SourceEvent latest = null; + Optional cutoff = Optional.empty(); + VerifiedSourceHistory history = null; if (sequence == 0L) { if (source.get("last_event_id", String.class) != null || source.get("last_event_digest", String.class) != null @@ -355,17 +607,27 @@ private CurrentSourceEvidence readCurrentSource( } checkpoint = new SourceCheckpoint(key, 0L, Optional.empty(), Optional.empty()); } else { - latest = verifyLatestEvent(scope, key, sequence, authority, fence); - if (!latest.eventId().equals(source.get("last_event_id", String.class)) - || !latest.eventDigest().equals(source.get("last_event_digest", String.class))) { + if (scope.kind() == ScopeKind.ISSUER) { + history = verifyLatestEvent(scope, key, sequence, authority, fence); + } else { + history = verifyEventHistory(scope, key, sequence, authority, fence); + } + Event latestEvent = history.latestEvent(); + if (!latestEvent.eventId().equals(source.get("last_event_id", String.class)) + || !latestEvent.eventDigest().equals(source.get("last_event_digest", String.class))) { throw new SourceEvidenceUnavailableException(); } checkpoint = new SourceCheckpoint( - key, sequence, Optional.of(latest.eventId()), Optional.of(latest.eventDigest())); + key, + sequence, + Optional.of(latestEvent.eventId()), + Optional.of(latestEvent.eventDigest())); if (scope.kind() == ScopeKind.ACCOUNT) { - AccountEvent accountEvent = (AccountEvent) latest; - AccountSecurityCutoff exactCutoff = accountEvent.accountSecurityCutoff(); + AccountSecurityCutoff exactCutoff = + history + .accountSecurityCutoff() + .orElseThrow(() -> new SourceEvidenceUnavailableException()); if (positive(source, "cutoff_generation") != currentGeneration || !key.equals(source.get("cutoff_stream_key", String.class)) || positive(source, "cutoff_sequence") != sequence @@ -383,7 +645,8 @@ private CurrentSourceEvidence readCurrentSource( } if (scope.kind() == ScopeKind.ACCOUNT) { requireAccountSourceIdentity(source, scope); - if (latest instanceof AccountEvent accountEvent) { + if (history != null && history.latestLegacyAccountEvent().isPresent()) { + AccountEvent accountEvent = history.latestLegacyAccountEvent().orElseThrow(); AccountState expectedAccountState = expectedPreUpdateAccountState.orElseGet(() -> readAccountState(scope.accountId())); if (!accountEvent.accountState().equals(expectedAccountState)) { @@ -405,7 +668,7 @@ private CurrentSourceEvidence readCurrentSource( source.get("account_repository_insert_transaction_id", Long.class)); } - private SourceEvent verifyLatestEvent( + private VerifiedSourceHistory verifyLatestEvent( AuthorityScope scope, String streamKey, long sequence, @@ -459,7 +722,103 @@ private SourceEvent verifyLatestEvent( || fence.sourceVersion() != sequence + 1L))) { throw new SourceEvidenceUnavailableException(); } - return latest; + return new VerifiedSourceHistory(stored, Optional.empty(), Optional.empty()); + } + + private VerifiedSourceHistory verifyEventHistory( + AuthorityScope scope, + String streamKey, + long sequence, + ScopeState authority, + IssuanceFence fence) { + Event latest = null; + AccountEvent latestLegacyAccountEvent = null; + AccountSecurityCutoff latestCutoff = null; + Account sourceAccount = + scope.kind() == ScopeKind.ACCOUNT + ? readAccountIdentityForClosedReadback(scope.accountId()) + : null; + for (long current = 1L; current <= sequence; current++) { + Event stored = + outbox + .findEvent(streamKey, current) + .orElseThrow(() -> new SourceEvidenceUnavailableException()); + SourceEvent event = null; + try { + event = + AccountAuthoritySourceEventV1Codec.verify( + new String(stored.payload(), StandardCharsets.UTF_8)); + } catch (RuntimeException notLegacyEvent) { + // Closed RESET/LOGOUT/security events are verified by their operation-specific receipts + // below. Generic source history remains readable but is not accepted as current authority. + } + if (event != null) { + if (!stored.eventId().equals(event.eventId()) + || !stored.requestId().equals(event.requestId()) + || !stored.outboxStreamKey().equals(event.outboxStreamKey()) + || stored.outboxSequence() != Long.parseLong(event.outboxSequence()) + || !stored.eventDigest().equals(event.eventDigest()) + || (scope.kind() == ScopeKind.ISSUER && !(event instanceof IssuerEvent)) + || (scope.kind() == ScopeKind.ACCOUNT && !(event instanceof AccountEvent))) { + throw new SourceEvidenceUnavailableException(); + } + if (event instanceof IssuerEvent issuer + && (!issuer.issuerId().equals(scope.issuerId()) + || Long.parseLong(issuer.issuerAuthGeneration()) != current + 1L + || Long.parseLong(issuer.sourceVersion()) != current + 1L)) { + throw new SourceEvidenceUnavailableException(); + } + if (event instanceof AccountEvent account + && (!account.accountId().equals(scope.accountId().toString()) + || Long.parseLong(account.accountAuthorityGeneration()) != current + 1L + || Long.parseLong(account.sourceVersion()) != current + 1L + || Long.parseLong(account.issuanceFence()) != current + 1L + || Long.parseLong(account.issuanceFenceSourceVersion()) != current + 1L)) { + throw new SourceEvidenceUnavailableException(); + } + latestLegacyAccountEvent = event instanceof AccountEvent account ? account : null; + latestCutoff = + event instanceof AccountEvent account ? account.accountSecurityCutoff() : null; + } else if (scope.kind() == ScopeKind.ACCOUNT) { + final RetainedEventEvidence receiptEvidence; + try { + receiptEvidence = + closedEventReadback().requireRetainedEvent(sourceAccount, stored, authority); + } catch (RuntimeException missingOrInvalidReceipt) { + throw new SourceEvidenceUnavailableException(); + } + if (!streamKey.equals(receiptEvidence.outboxStreamKey()) + || receiptEvidence.outboxSequence() != current + || receiptEvidence.accountAuthorityGeneration() != current + 1L + || receiptEvidence.sourceVersion() != current + 1L + || receiptEvidence.issuanceFence() != current + 1L + || receiptEvidence.issuanceFenceSourceVersion() != current + 1L) { + throw new SourceEvidenceUnavailableException(); + } + var typedCutoff = receiptEvidence.accountSecurityCutoff(); + latestCutoff = + new AccountSecurityCutoff( + typedCutoff.accountAuthorityGeneration(), + typedCutoff.outboxStreamKey(), + typedCutoff.outboxSequence()); + latestLegacyAccountEvent = null; + } else { + throw new SourceEvidenceUnavailableException(); + } + latest = stored; + } + if (latest == null + || latest.outboxSequence() != sequence + || authority.generation() != sequence + 1L + || authority.sourceVersion() != sequence + 1L + || (scope.kind() == ScopeKind.ACCOUNT + && (fence == null + || fence.value() != sequence + 1L + || fence.sourceVersion() != sequence + 1L))) { + throw new SourceEvidenceUnavailableException(); + } + return new VerifiedSourceHistory( + latest, Optional.ofNullable(latestLegacyAccountEvent), Optional.ofNullable(latestCutoff)); } private void updateSourceHead( @@ -469,6 +828,40 @@ private void updateSourceHead( IssuanceFence advancedFence) { AccountSecurityCutoff cutoff = event instanceof AccountEvent account ? account.accountSecurityCutoff() : null; + updateSourceHead( + before, + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + cutoff, + advanced, + advancedFence); + } + + private void updateSourceHead( + CurrentSourceEvidence before, + Event event, + AccountSecurityCutoff cutoff, + ScopeState advanced, + IssuanceFence advancedFence) { + updateSourceHead( + before, + Long.toString(event.outboxSequence()), + event.eventId(), + event.eventDigest(), + cutoff, + advanced, + advancedFence); + } + + private void updateSourceHead( + CurrentSourceEvidence before, + String sequenceText, + String eventId, + String eventDigest, + AccountSecurityCutoff cutoff, + ScopeState advanced, + IssuanceFence advancedFence) { Record changed = dsl.fetchOne( "UPDATE " @@ -486,9 +879,9 @@ private void updateSourceHead( advanced.sourceVersion(), advancedFence == null ? null : advancedFence.value(), advancedFence == null ? null : advancedFence.sourceVersion(), - Long.parseLong(event.outboxSequence()), - event.eventId(), - event.eventDigest(), + Long.parseLong(sequenceText), + eventId, + eventDigest, cutoff == null ? null : Long.parseLong(cutoff.accountAuthorityGeneration()), cutoff == null ? null : cutoff.outboxStreamKey(), cutoff == null ? null : Long.parseLong(cutoff.outboxSequence()), @@ -628,6 +1021,34 @@ private AccountState readAccountState(UUID accountUuid) { return accountState(account); } + private Account readAccountIdentityForClosedReadback(UUID accountUuid) { + Record row = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id, " + + "password_hash FROM accounts WHERE account_uuid = ? FOR SHARE", + accountUuid); + if (row == null) throw new SourceEvidenceUnavailableException(); + Account account = new Account(); + account.setId(positive(row, "id")); + account.setAccountUuid(row.get("account_uuid", UUID.class)); + account.setAccountUuidProvenance( + AccountIdentityProvenance.fromStorageValue( + row.get("account_uuid_provenance", String.class))); + account.setAccountUuidSourceNumericId(positive(row, "account_uuid_source_numeric_id")); + account.setPasswordHash(row.get("password_hash", String.class)); + return account; + } + + private AccountAuthoritySourceEventReadback closedEventReadback() { + // Construct at use, not in the repository constructor: the security-state storage owner + // itself depends on this source owner. Every invocation still requires every exact receipt. + return new AccountAuthoritySourceEventReadback( + outbox, + new AccountPasswordResetOperationRepository(dsl), + new AccountLogoutAllOperationRepository(dsl), + new AccountSecurityStateOperationRepository(dsl)); + } + private void requireAccountReadback( UUID accountUuid, long accountId, AccountRepository.AccountAuthorityState expected) { Record account = @@ -800,6 +1221,17 @@ public record SourceCheckpoint( } } + private record VerifiedSourceHistory( + Event latestEvent, + Optional latestLegacyAccountEvent, + Optional accountSecurityCutoff) { + private VerifiedSourceHistory { + Objects.requireNonNull(latestEvent); + Objects.requireNonNull(latestLegacyAccountEvent); + Objects.requireNonNull(accountSecurityCutoff); + } + } + public record CurrentSourceEvidence( AuthorityScope scope, long generation, @@ -872,8 +1304,61 @@ public record CurrentSourceEvidence( } } + public record CanonicalIssuerSourceSnapshot( + CurrentSourceEvidence source, Optional latestEvent) { + public CanonicalIssuerSourceSnapshot { + Objects.requireNonNull(source); + Objects.requireNonNull(latestEvent); + if (source.scope().kind() != ScopeKind.ISSUER + || (source.checkpoint().sequence() == 0L) != latestEvent.isEmpty()) { + throw new SourceEvidenceUnavailableException(); + } + } + } + public record IssuerAccountSourceSnapshot( - CurrentSourceEvidence issuer, CurrentSourceEvidence account, IssuanceFence issuanceFence) { + CurrentSourceEvidence issuer, + CurrentSourceEvidence account, + IssuanceFence issuanceFence, + AccountGenerationProjection canonicalAccountProjection, + IssuerGenerationProjection canonicalIssuerProjection) { + public IssuerAccountSourceSnapshot( + CurrentSourceEvidence issuer, + CurrentSourceEvidence account, + IssuanceFence issuanceFence, + AccountGenerationProjection canonicalAccountProjection) { + this( + issuer, + account, + issuanceFence, + canonicalAccountProjection, + issuer != null && issuer.checkpoint().sequence() == 0L + ? IssuerGenerationProjection.fromSource(issuer) + : null); + } + + /** + * Preserves lightweight source-state fixtures while refusing to invent advanced event bytes. + * Production snapshots are created by {@link #readCurrentIssuerAccountSources} with the exact + * receipt-verified latest event from that same composite owner read. + */ + public IssuerAccountSourceSnapshot( + CurrentSourceEvidence issuer, CurrentSourceEvidence account, IssuanceFence issuanceFence) { + this( + issuer, + account, + issuanceFence, + account != null && account.checkpoint().sequence() == 0L + ? new AccountGenerationProjection( + account.scope().accountId().toString(), + Long.toString(account.generation()), + Long.toString(account.sourceVersion()), + account.checkpoint().outboxStreamKey(), + "0", + Optional.empty()) + : null); + } + public IssuerAccountSourceSnapshot { Objects.requireNonNull(issuer); Objects.requireNonNull(account); @@ -884,6 +1369,44 @@ public record IssuerAccountSourceSnapshot( || !account.issuanceFence().equals(issuanceFence)) { throw new IllegalArgumentException("Issuer/Account source snapshot scope is invalid"); } + if (canonicalAccountProjection != null + && (!account.scope().accountId().toString().equals(canonicalAccountProjection.accountId()) + || !Long.toString(account.generation()) + .equals(canonicalAccountProjection.accountAuthorityGeneration()) + || !Long.toString(account.sourceVersion()) + .equals(canonicalAccountProjection.sourceVersion()) + || !account + .checkpoint() + .outboxStreamKey() + .equals(canonicalAccountProjection.outboxStreamKey()) + || !Long.toString(account.checkpoint().sequence()) + .equals(canonicalAccountProjection.outboxSequence()))) { + throw new IllegalArgumentException( + "Canonical Account source projection differs from its snapshot"); + } + if (canonicalIssuerProjection != null + && (!issuer.scope().issuerId().equals(canonicalIssuerProjection.issuerId()) + || !Long.toString(issuer.generation()) + .equals(canonicalIssuerProjection.issuerAuthGeneration()) + || !Long.toString(issuer.sourceVersion()) + .equals(canonicalIssuerProjection.sourceVersion()) + || !issuer + .checkpoint() + .outboxStreamKey() + .equals(canonicalIssuerProjection.outboxStreamKey()) + || !Long.toString(issuer.checkpoint().sequence()) + .equals(canonicalIssuerProjection.lastAppliedSourceOutboxSequence()) + || !issuer + .checkpoint() + .sourceEventId() + .equals(canonicalIssuerProjection.lastAppliedSourceEventId()) + || !issuer + .checkpoint() + .sourceEventDigest() + .equals(canonicalIssuerProjection.lastAppliedSourceEventDigest()))) { + throw new IllegalArgumentException( + "Canonical issuer source projection differs from its snapshot"); + } } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java new file mode 100644 index 0000000000..77d1cabbaf --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java @@ -0,0 +1,546 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException.Code; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account's exact-UUID demo entitlement source, commit, lookup, and currentness fence. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories and DSLContext are private transaction collaborators.") +public class AccountDemoTenantEntitlementRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final FreshTenantIdentityAssociationRepository tenantIdentityRepository; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; + private final AccountTenantEntitlementOutboxRepository outboxRepository; + private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve injected collaborator preconditions; Spring must proxy this non-final repository.") + public AccountDemoTenantEntitlementRepository( + DSLContext dsl, + FreshTenantIdentityAssociationRepository tenantIdentityRepository, + AccountAuthorityGenerationRepository authorityGenerationRepository, + AccountTenantEntitlementOutboxRepository outboxRepository, + AccountTenantAuthorityEventRepository tenantAuthorityEvents) { + this.dsl = Objects.requireNonNull(dsl); + this.tenantIdentityRepository = Objects.requireNonNull(tenantIdentityRepository); + this.authorityGenerationRepository = Objects.requireNonNull(authorityGenerationRepository); + this.outboxRepository = Objects.requireNonNull(outboxRepository); + this.tenantAuthorityEvents = Objects.requireNonNull(tenantAuthorityEvents); + } + + /** Commits one protected-fixture mutation with source readback, shared generation, and outbox. */ + @Transactional(propagation = Propagation.MANDATORY) + public DemoTenantEntitlementSnapshot provision( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence authenticatedSource) { + requireTransaction(); + Objects.requireNonNull(request, "Demo entitlement request is required"); + requireExactSource(request, authenticatedSource); + FreshTenantCreationEvidence currentSource = + tenantIdentityRepository + .read(request.canonicalTenantId()) + .orElseThrow( + () -> + new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Exact fresh Game Design source evidence is absent at Account commit")); + if (!authenticatedSource.equals(currentSource)) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Authenticated source evidence differs from exact Account UUID readback at commit"); + } + + int reserved = + dsl.execute( + "INSERT INTO account_demo_tenant_entitlement_operations (request_id, tenant_uuid, " + + "request_digest, source_creation_request_id, source_request_digest, " + + "source_operation_id, source_evidence_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 'PENDING') ON CONFLICT (request_id) DO NOTHING", + request.requestId(), + request.canonicalTenantId(), + request.requestDigest(), + authenticatedSource.creationRequestId(), + authenticatedSource.requestDigest(), + authenticatedSource.operationId(), + authenticatedSource.evidenceDigest()); + if (reserved == 0) { + return replay(request, authenticatedSource); + } + if (reserved != 1) { + throw new IllegalStateException("Demo entitlement request reservation was ambiguous"); + } + + ScopeState oldAuthority = + authorityGenerationRepository.read(AuthorityScope.tenant(request.canonicalTenantId())); + Record oldEntitlement = readCurrentRow(request.canonicalTenantId(), true); + if (oldEntitlement == null) { + tenantAuthorityEvents.establishFirstEventSource( + request.canonicalTenantId(), request.requestId(), authenticatedSource, oldAuthority); + } + long nextEntitlementVersion; + if (oldEntitlement == null) { + if (request.expectedEntitlementVersion() != null) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_VERSION_CONFLICT, + "Demo entitlement create request supplied an update fence"); + } + nextEntitlementVersion = 1L; + } else { + if (request.expectedEntitlementVersion() == null + || request.expectedEntitlementVersion() != value(oldEntitlement, "entitlement_version") + || request.expectedTenantAuthorityGeneration() != oldAuthority.generation() + || request.expectedTenantAuthoritySourceVersion() != oldAuthority.sourceVersion()) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Demo entitlement update does not match the exact current entitlement and tenant authority"); + } + nextEntitlementVersion = increment(value(oldEntitlement, "entitlement_version")); + } + ScopeState nextAuthority = authorityGenerationRepository.advance(oldAuthority, null); + final long committedEntitlementVersion = nextEntitlementVersion; + Event committedEvent = + outboxRepository.append( + request.canonicalTenantId(), + request.requestId(), + sequence -> + DemoTenantEntitlementEventV1Codec.seal( + request, + authenticatedSource, + committedEntitlementVersion, + nextAuthority.generation(), + nextAuthority.sourceVersion(), + sequence)); + + TenantAuthorityEventV1Codec.Event authorityEvent = + tenantAuthorityEvents.append(request, authenticatedSource, nextAuthority, committedEvent); + + writeCurrent( + request, authenticatedSource, committedEvent, authorityEvent, oldEntitlement == null); + int committed = + dsl.execute( + "UPDATE account_demo_tenant_entitlement_operations SET status = 'COMMITTED', " + + "tenant_billing_sequence = ?, event_id = ?, event_digest = ?, " + + "entitlement_version = ?, tenant_authority_generation = ?, " + + "tenant_authority_source_version = ?, tenant_authority_outbox_stream_key = ?, " + + "tenant_authority_outbox_sequence = ?, tenant_authority_event_id = ?, " + + "tenant_authority_event_digest = ?, committed_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND status = 'PENDING'", + committedEvent.tenantBillingSequence(), + committedEvent.eventId(), + committedEvent.eventDigest(), + committedEvent.entitlementVersion(), + committedEvent.tenantAuthorityGeneration(), + committedEvent.tenantAuthoritySourceVersion(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest(), + request.requestId()); + if (committed != 1) { + throw new IllegalStateException("Demo entitlement operation receipt was not committed"); + } + return snapshot(committedEvent, authorityEvent); + } + + /** Reads one exact current snapshot and denies stale or incomplete Account/source state. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public DemoTenantEntitlementSnapshot readCurrent(UUID canonicalTenantId) { + requireTenantUuid(canonicalTenantId); + Optional evidence = + tenantIdentityRepository.read(canonicalTenantId); + FreshTenantCreationEvidence source = + evidence.orElseThrow( + () -> + new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "No exact fresh Game Design source evidence exists for this tenant UUID")); + ScopeState authority = + authorityGenerationRepository.read(AuthorityScope.tenant(canonicalTenantId)); + Record row = readCurrentRow(canonicalTenantId, false); + if (row == null) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_UNAVAILABLE, "No Account demo entitlement exists for this tenant UUID"); + } + CurrentEvents current = currentEvents(row, source, authority); + return snapshot(current.billingEvent(), current.authorityEvent()); + } + + /** Re-reads all source, generation, version, and outbox evidence at the final admission fence. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public DemoTenantEntitlementSnapshot revalidate(DemoTenantEntitlementSnapshot evaluated) { + Objects.requireNonNull(evaluated, "Complete evaluated entitlement evidence is required"); + DemoTenantEntitlementSnapshot current = readCurrent(evaluated.canonicalTenantId()); + if (!current.equals(evaluated)) { + throw new DemoTenantEntitlementException( + Code.STALE_ADMISSION_EVIDENCE, + "Account demo entitlement changed after its complete evaluation snapshot"); + } + return current; + } + + private DemoTenantEntitlementSnapshot replay( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence authenticatedSource) { + Record operation = + dsl.fetchOne( + "SELECT tenant_uuid, request_digest, source_creation_request_id, " + + "source_request_digest, source_operation_id, source_evidence_digest, status, " + + "tenant_billing_sequence, event_id, event_digest, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest " + + "FROM account_demo_tenant_entitlement_operations WHERE request_id = ? FOR UPDATE", + request.requestId()); + if (operation == null + || !request.canonicalTenantId().equals(get(operation, "tenant_uuid", UUID.class)) + || !request.requestDigest().equals(get(operation, "request_digest", String.class)) + || !authenticatedSource + .creationRequestId() + .equals(get(operation, "source_creation_request_id", UUID.class)) + || !authenticatedSource + .requestDigest() + .equals(get(operation, "source_request_digest", String.class)) + || !authenticatedSource + .operationId() + .equals(get(operation, "source_operation_id", UUID.class)) + || !authenticatedSource + .evidenceDigest() + .equals(get(operation, "source_evidence_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.IDEMPOTENCY_CONFLICT, + "Demo entitlement request ID was reused for a different tenant or payload"); + } + if (!"COMMITTED".equals(get(operation, "status", String.class))) { + throw new IllegalStateException("Committed Account contains an unfinished demo operation"); + } + long sequence = value(operation, "tenant_billing_sequence"); + Event event = + outboxRepository + .readEvent(request.canonicalTenantId(), sequence) + .orElseThrow( + () -> + new IllegalStateException("Committed demo entitlement operation has no event")); + if (!request.requestId().equals(event.requestId()) + || !request.requestDigest().equals(event.requestDigest()) + || !event.eventId().equals(get(operation, "event_id", UUID.class)) + || !event.eventDigest().equals(get(operation, "event_digest", String.class)) + || !authenticatedSource.equals(event.sourceEvidence())) { + throw new IllegalStateException("Committed demo entitlement receipt differs from its event"); + } + var authorityEvent = + tenantAuthorityEvents.readCommittedReceipt( + request.canonicalTenantId(), + request.requestId(), + request.requestDigest(), + authenticatedSource, + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + value(operation, "tenant_authority_outbox_sequence"), + get(operation, "tenant_authority_event_id", String.class), + get(operation, "tenant_authority_event_digest", String.class)); + if (!authorityEvent + .outboxStreamKey() + .equals(get(operation, "tenant_authority_outbox_stream_key", String.class)) + || authorityEvent.tenantAuthorityGeneration() != event.tenantAuthorityGeneration() + || authorityEvent.tenantAuthoritySourceVersion() != event.tenantAuthoritySourceVersion()) { + throw new IllegalStateException( + "Committed demo entitlement receipt differs from its tenant authority event"); + } + return snapshot(event, authorityEvent); + } + + private CurrentEvents currentEvents( + Record row, FreshTenantCreationEvidence source, ScopeState authority) { + long storedGeneration = value(row, "tenant_authority_generation"); + long storedSourceVersion = value(row, "tenant_authority_source_version"); + if (storedGeneration != authority.generation() + || storedSourceVersion != authority.sourceVersion()) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Stored demo entitlement is stale against Account's shared tenant authority generation"); + } + if (source.schemaVersion() != get(row, "source_schema_version", Integer.class) + || !source.targetNamespace().equals(get(row, "source_target_namespace", String.class)) + || !source.creationRequestId().equals(get(row, "source_creation_request_id", UUID.class)) + || !source.operationId().equals(get(row, "source_operation_id", UUID.class)) + || !source.requestDigest().equals(get(row, "source_request_digest", String.class)) + || source.sourceGameRowId() != value(row, "source_game_row_id") + || !source.sourceGameTenantKey().equals(get(row, "source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(get(row, "source_provenance_kind", String.class)) + || !source.evidenceDigest().equals(get(row, "source_evidence_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Stored demo entitlement source tuple differs from current authenticated Account source evidence"); + } + long sequence = value(row, "tenant_billing_sequence"); + var checkpoint = + outboxRepository + .readCheckpoint(source.canonicalTenantId()) + .orElseThrow( + () -> + new IllegalStateException("Current demo entitlement has no outbox checkpoint")); + if (checkpoint.sequence() != sequence + || !checkpoint.eventId().equals(get(row, "event_id", UUID.class)) + || !checkpoint.eventDigest().equals(get(row, "event_digest", String.class))) { + throw new DemoTenantEntitlementException( + Code.TENANT_AUTHORITY_STALE, + "Current demo entitlement does not match the exact tenant entitlement outbox head"); + } + Event event = + outboxRepository + .readEvent(source.canonicalTenantId(), sequence) + .orElseThrow( + () -> new IllegalStateException("Current demo entitlement event is absent")); + if (!source.equals(event.sourceEvidence()) + || event.entitlementVersion() != value(row, "entitlement_version") + || event.tenantAuthorityGeneration() != storedGeneration + || event.tenantAuthoritySourceVersion() != storedSourceVersion + || !event.requestId().equals(get(row, "last_request_id", UUID.class)) + || !event.requestDigest().equals(get(row, "last_request_digest", String.class)) + || !event.eventId().equals(get(row, "event_id", UUID.class)) + || !event.eventDigest().equals(get(row, "event_digest", String.class)) + || event.gameplayAvailable() != get(row, "gameplay_available", Boolean.class) + || event.allowPublicJoin() != get(row, "allow_public_join", Boolean.class) + || event.allowNewGameplayBindings() + != get(row, "allow_new_gameplay_bindings", Boolean.class) + || event.allowNewInstanceStarts() != get(row, "allow_new_instance_starts", Boolean.class) + || !event + .quotas() + .equals( + new DemoTenantEntitlementRequest.Quotas( + value(row, "max_active_sessions"), + value(row, "max_concurrent_game_instances"), + value(row, "max_storage_bytes")))) { + throw new IllegalStateException("Current demo entitlement projection differs from its event"); + } + TenantAuthorityEventV1Codec.Event authorityEvent = + tenantAuthorityEvents.readCurrentCheckpoint( + source.canonicalTenantId(), + source, + authority, + event.requestId(), + event.requestDigest(), + sequence, + event.eventId(), + event.eventDigest()); + if (authorityEvent.tenantAuthorityGeneration() != storedGeneration + || authorityEvent.tenantAuthoritySourceVersion() != storedSourceVersion) { + throw new IllegalStateException( + "Current tenant authority event differs from Account's actual generation"); + } + return new CurrentEvents(event, authorityEvent); + } + + private void writeCurrent( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + Event event, + TenantAuthorityEventV1Codec.Event authorityEvent, + boolean insert) { + String sql = + insert + ? "INSERT INTO account_demo_tenant_entitlements (tenant_uuid, source_schema_version, " + + "source_target_namespace, source_creation_request_id, source_operation_id, " + + "source_request_digest, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest, entitlement_kind, status, " + + "subscription_status, paid, gameplay_available, allow_public_join, " + + "allow_new_gameplay_bindings, allow_new_instance_starts, max_active_sessions, " + + "max_concurrent_game_instances, max_storage_bytes, entitlement_version, " + + "tenant_authority_generation, tenant_authority_source_version, " + + "tenant_billing_sequence, event_id, event_digest, last_request_id, last_request_digest, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'NON_PAID_DEMO', 'ACTIVE', NULL, FALSE, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + : "UPDATE account_demo_tenant_entitlements SET gameplay_available = ?, " + + "allow_public_join = ?, allow_new_gameplay_bindings = ?, allow_new_instance_starts = ?, " + + "max_active_sessions = ?, max_concurrent_game_instances = ?, max_storage_bytes = ?, " + + "entitlement_version = ?, tenant_authority_generation = ?, " + + "tenant_authority_source_version = ?, tenant_billing_sequence = ?, event_id = ?, " + + "event_digest = ?, last_request_id = ?, last_request_digest = ?, " + + "tenant_authority_outbox_stream_key = ?, tenant_authority_outbox_sequence = ?, " + + "tenant_authority_event_id = ?, tenant_authority_event_digest = ? " + + "WHERE tenant_uuid = ?"; + Object[] values = + insert + ? new Object[] { + request.canonicalTenantId(), + source.schemaVersion(), + source.targetNamespace(), + source.creationRequestId(), + source.operationId(), + source.requestDigest(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas().maxActiveSessions(), + request.quotas().maxConcurrentGameInstances(), + request.quotas().maxStorageBytes(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + request.requestId(), + request.requestDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest() + } + : new Object[] { + request.gameplayAvailable(), + request.allowPublicJoin(), + request.allowNewGameplayBindings(), + request.allowNewInstanceStarts(), + request.quotas().maxActiveSessions(), + request.quotas().maxConcurrentGameInstances(), + request.quotas().maxStorageBytes(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + request.requestId(), + request.requestDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId().toString(), + authorityEvent.eventDigest(), + request.canonicalTenantId() + }; + int changed = dsl.execute(sql, values); + if (changed != 1) { + throw new IllegalStateException( + "Demo entitlement current state was not committed exactly once"); + } + } + + private Record readCurrentRow(UUID tenantId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT source_schema_version, source_target_namespace, source_creation_request_id, " + + "source_operation_id, source_request_digest, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " + + "entitlement_version, gameplay_available, allow_public_join, " + + "allow_new_gameplay_bindings, allow_new_instance_starts, max_active_sessions, " + + "max_concurrent_game_instances, max_storage_bytes, tenant_authority_generation, " + + "tenant_authority_source_version, tenant_billing_sequence, event_id, event_digest, " + + "last_request_id, last_request_digest, tenant_authority_outbox_stream_key, " + + "tenant_authority_outbox_sequence, tenant_authority_event_id, " + + "tenant_authority_event_digest FROM account_demo_tenant_entitlements " + + "WHERE tenant_uuid = ?" + + (forUpdate ? " FOR UPDATE" : " FOR SHARE"), + tenantId); + } + + private static DemoTenantEntitlementSnapshot snapshot( + Event event, TenantAuthorityEventV1Codec.Event authorityEvent) { + return new DemoTenantEntitlementSnapshot( + event.canonicalTenantId(), + event.sourceEvidence(), + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + event.gameplayAvailable(), + event.allowPublicJoin(), + event.allowNewGameplayBindings(), + event.allowNewInstanceStarts(), + event.quotas(), + event.entitlementVersion(), + event.tenantAuthorityGeneration(), + event.tenantAuthoritySourceVersion(), + event.outboxStreamKey(), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest(), + event.eventDigest(), + authorityEvent.outboxStreamKey(), + authorityEvent.outboxSequence(), + authorityEvent.eventId(), + authorityEvent.eventDigest()); + } + + private record CurrentEvents( + Event billingEvent, TenantAuthorityEventV1Codec.Event authorityEvent) {} + + private static void requireExactSource( + DemoTenantEntitlementRequest request, FreshTenantCreationEvidence source) { + if (source == null + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.tenantCreationRequestId().equals(source.creationRequestId()) + || !request.tenantCreationRequestDigest().equals(source.requestDigest()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Only exact authenticated fresh Game Design tenant creation evidence can receive a demo entitlement"); + } + } + + private static void requireTenantUuid(UUID tenantId) { + if (tenantId == null || NIL_UUID.equals(tenantId)) { + throw new DemoTenantEntitlementException( + Code.ENTITLEMENT_UNAVAILABLE, "Exact non-nil canonical tenant UUID is required"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account demo entitlement operation requires one owner transaction"); + } + } + + private static long value(Record row, String column) { + Long value = row.get(column, Long.class); + if (value == null || value < 0) { + throw new IllegalStateException("Account demo entitlement " + column + " is malformed"); + } + return value; + } + + private static long increment(long current) { + try { + return Math.addExact(current, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account demo entitlement version is exhausted", overflow); + } + } + + private static T get(Record row, String column, Class type) { + T result = row.get(column, type); + if (result == null) { + throw new IllegalStateException("Account demo entitlement " + column + " is absent"); + } + return result; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwner.java new file mode 100644 index 0000000000..1ff62dd884 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwner.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.accountservice.repository; + +import io.grpc.Status; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered cancellation owner. Authenticates the original Game Session workload and retains + * pending orphan cleanup atomically; grants no admission, current authority or token retirement. A + * supplied decision is correlation only, never a verified Gameplay decision. + */ +public final class AccountGameplayAdmissionAbortOwner { + private final AccountGameplayAdmissionLeaseRepository repository; + private final TransactionTemplate transaction; + private final String namespace; + + public AccountGameplayAdmissionAbortOwner( + AccountGameplayAdmissionLeaseRepository repository, + PlatformTransactionManager transactionManager, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + } + + public AccountGameplayAdmissionLeaseOperation abort(AbortGameplayAdmissionLeaseRequest request) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + if (!GrpcPeerIdentity.isValidNamespace(namespace) + || !peer.uri().equals("spiffe://firemud/ns/" + namespace + "/sa/game-session-service")) + throw Status.PERMISSION_DENIED + .withDescription("Game Session workload required") + .asRuntimeException(); + if (request == null || !request.hasLease() || !request.getUnknownFields().asMap().isEmpty()) + throw new IllegalArgumentException("Malformed Account admission abort request"); + var evidence = AccountGameplayAdmissionLeaseWireCodec.parseReference(request.getLease()); + UUID decision = + request.hasBindingDecisionId() ? decision(request.getBindingDecisionId()) : null; + if (!namespace.equals(evidence.carrier().get("targetNamespace")) + || !peer.uri().equals(evidence.carrier().get("callerWorkload"))) + throw Status.PERMISSION_DENIED + .withDescription("Admission lease caller mismatch") + .asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION + .withDescription("Owned Account transaction required") + .asRuntimeException(); + return Objects.requireNonNull( + transaction.execute( + ignored -> { + AccountGameplayAdmissionLeaseOperation prior; + try { + prior = + repository + .readExact(evidence) + .orElseThrow(() -> new AbortDeniedException("ADMISSION_LEASE_UNRESOLVED")); + } catch (AccountGameplayAdmissionLeaseRepository.IdentityConflictException failure) { + throw conflict(); + } + if (prior.state() == State.COMMITTED) + throw new AbortDeniedException("ADMISSION_LEASE_NOT_ABORTABLE"); + if (prior.state() == State.ABORTED) { + if (!Objects.equals(prior.bindingDecisionId(), decision)) throw conflict(); + return prior; + } + try { + return repository.recordAborted(evidence, decision, UUID.randomUUID()); + } catch (AccountGameplayAdmissionLeaseRepository.IdentityConflictException failure) { + throw conflict(); + } + })); + } + + private static UUID decision(String text) { + try { + UUID value = UUID.fromString(text); + if (!value.toString().equals(text) || value.version() != 4 || value.variant() != 2) + throw new IllegalArgumentException(); + return value; + } catch (IllegalArgumentException ignored) { + throw new IllegalArgumentException("Malformed Account admission abort request"); + } + } + + private static AbortDeniedException conflict() { + return new AbortDeniedException("IDEMPOTENCY_CONFLICT"); + } + + /** Produced domain denial; no evidence or storage failure details are exposed. */ + public static final class AbortDeniedException extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final String code; + + private AbortDeniedException(String code) { + super("Account admission abort denied"); + this.code = code; + } + + public String code() { + return code; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java new file mode 100644 index 0000000000..a6e844ffce --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java @@ -0,0 +1,127 @@ +package net.firedevops.firemud.accountservice.repository; + +import io.grpc.Status; +import java.util.Objects; +import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionCommitConfirmation; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, non-admitting owner for database proof that an original lease COMMIT preceded its + * unchanged expiry. It evaluates no current source authority and does not finalize or admit. + */ +public final class AccountGameplayAdmissionCommitConfirmationOwner { + private final DataSource dataSource; + private final AccountGameplayAdmissionReceiptCommitExecutor executor; + private final String namespace; + + public AccountGameplayAdmissionCommitConfirmationOwner(DataSource dataSource, String namespace) { + this(dataSource, new AccountGameplayAdmissionReceiptCommitExecutor(dataSource), namespace); + } + + AccountGameplayAdmissionCommitConfirmationOwner( + DataSource dataSource, + AccountGameplayAdmissionReceiptCommitExecutor executor, + String namespace) { + this.dataSource = Objects.requireNonNull(dataSource); + this.executor = Objects.requireNonNull(executor); + this.namespace = namespace; + } + + /** + * Creates/replays the temporal receipt, waits for that transaction to commit, then independently + * reads the durable receipt in a fresh transaction before returning it. + */ + public AccountGameplayAdmissionCommitConfirmation confirm( + FinalizeGameplayAdmissionLeaseRequest request) { + RequestIdentity identity = authenticateAndParse(request); + rejectAmbientTransaction(); + try { + return Objects.requireNonNull(executor.confirm(identity.evidence(), identity.decisionId())); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + /** Reads an existing proof only; it never creates or repairs a receipt. */ + public AccountGameplayAdmissionCommitConfirmation read( + FinalizeGameplayAdmissionLeaseRequest request) { + RequestIdentity identity = authenticateAndParse(request); + rejectAmbientTransaction(); + try { + return Objects.requireNonNull(executor.read(identity.evidence(), identity.decisionId())); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private RequestIdentity authenticateAndParse(FinalizeGameplayAdmissionLeaseRequest request) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + if (!GrpcPeerIdentity.isValidNamespace(namespace) + || !peer.uri().equals("spiffe://firemud/ns/" + namespace + "/sa/game-session-service")) + throw Status.PERMISSION_DENIED + .withDescription("Game Session workload required") + .asRuntimeException(); + if (request == null || !request.hasLease() || !request.getUnknownFields().asMap().isEmpty()) + throw invalidRequest(); + + AccountGameplayAdmissionLeaseEvidence evidence; + try { + evidence = AccountGameplayAdmissionLeaseWireCodec.parseReference(request.getLease()); + } catch (IllegalArgumentException failure) { + throw invalidRequest(); + } + var decision = canonicalDecision(request.getBindingDecisionId()); + if (!namespace.equals(evidence.carrier().get("targetNamespace")) + || !peer.uri().equals(evidence.carrier().get("callerWorkload"))) + throw Status.PERMISSION_DENIED + .withDescription("Admission lease caller mismatch") + .asRuntimeException(); + return new RequestIdentity(evidence, decision); + } + + private void rejectAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.hasResource(dataSource)) + throw Status.FAILED_PRECONDITION + .withDescription("Owned Account transaction required") + .asRuntimeException(); + } + + private static java.util.UUID canonicalDecision(String text) { + try { + java.util.UUID value = java.util.UUID.fromString(text); + if (!value.toString().equals(text) || value.version() != 4 || value.variant() != 2) + throw new IllegalArgumentException(); + return value; + } catch (RuntimeException failure) { + throw invalidRequest(); + } + } + + private static io.grpc.StatusRuntimeException invalidRequest() { + return Status.INVALID_ARGUMENT + .withDescription("Malformed Account admission confirmation request") + .asRuntimeException(); + } + + private static io.grpc.StatusRuntimeException unavailable() { + return Status.UNAVAILABLE + .withDescription("Durable Account admission commit confirmation unavailable") + .asRuntimeException(); + } + + private record RequestIdentity( + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + evidence, + java.util.UUID decisionId) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java new file mode 100644 index 0000000000..4887402f54 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java @@ -0,0 +1,136 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionCommitConfirmation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, non-admitting storage confirmation for an already retained COMMITTED lease. + * + *

The database functions alone create or independently read a durability receipt. A raw + * operation state, timestamp, visible receipt row, or returned Java clock value is insufficient. + */ +public final class AccountGameplayAdmissionCommitConfirmationRepository { + private final DSLContext dsl; + private final AccountGameplayAdmissionLeaseRepository leaseRepository; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private injected persistence context; the repository never exposes it") + public AccountGameplayAdmissionCommitConfirmationRepository( + DSLContext dsl, AccountGameplayAdmissionLeaseRepository leaseRepository) { + this.dsl = Objects.requireNonNull(dsl); + this.leaseRepository = Objects.requireNonNull(leaseRepository); + } + + /** Creates or exactly replays a database-stamped receipt for the original proven COMMIT. */ + AccountGameplayAdmissionCommitConfirmation confirmCommitted( + AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { + UUID requestId = validateRequest(evidence, bindingDecisionId); + Record row = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + requestId, + evidence.sha256(), + bindingDecisionId); + if (row == null) throw unavailable(); + AccountGameplayAdmissionLeaseOperation operation = exactCommitted(evidence, bindingDecisionId); + return confirmation(row, operation); + } + + /** Reads only a committed, independently durable receipt; this path never creates one. */ + AccountGameplayAdmissionCommitConfirmation readCommitConfirmation( + AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { + UUID requestId = validateRequest(evidence, bindingDecisionId); + Record row = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_read_commit_confirmation(?, ?, ?)", + requestId, + evidence.sha256(), + bindingDecisionId); + if (row == null) throw unavailable(); + AccountGameplayAdmissionLeaseOperation operation = exactCommitted(evidence, bindingDecisionId); + return confirmation(row, operation); + } + + private static UUID validateRequest( + AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { + requireWritableSerializableTransaction(); + Objects.requireNonNull(evidence); + UUID requestId = requestId(evidence); + requireUuidV4(requestId); + requireUuidV4(bindingDecisionId); + return requestId; + } + + private AccountGameplayAdmissionLeaseOperation exactCommitted( + AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { + AccountGameplayAdmissionLeaseOperation operation = + leaseRepository + .readExact(evidence) + .orElseThrow(AccountGameplayAdmissionCommitConfirmationRepository::unavailable); + if (operation.state() != State.COMMITTED + || !bindingDecisionId.equals(operation.bindingDecisionId())) throw unavailable(); + return operation; + } + + private static AccountGameplayAdmissionCommitConfirmation confirmation( + Record row, AccountGameplayAdmissionLeaseOperation operation) { + if (row == null) throw unavailable(); + try { + return new AccountGameplayAdmissionCommitConfirmation( + operation, + required(row, "confirmation_version", Short.class), + required(row, "request_id", UUID.class), + required(row, "account_uuid", UUID.class), + required(row, "lease_id", UUID.class), + required(row, "lease_fence", Long.class), + required(row, "evidence_sha256", String.class), + required(row, "binding_decision_id", UUID.class), + required(row, "expires_at_ms", Long.class), + required(row, "finalization_xid", String.class), + required(row, "wal_insert_lsn", String.class), + required(row, "wal_flush_lsn", String.class), + required(row, "committed_before_ms", Long.class), + required(row, "confirmation_xid", String.class)); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) throw unavailable(); + return value; + } + + private static UUID requestId(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString((String) evidence.carrier().get("requestId")); + } + + private static void requireWritableSerializableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException("Writable SERIALIZABLE Account transaction required"); + } + } + + private static void requireUuidV4(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) + throw new IllegalArgumentException("Canonical non-nil UUIDv4 identity required"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Durable Account admission commit confirmation unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java new file mode 100644 index 0000000000..72d774ff1c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java @@ -0,0 +1,320 @@ +package net.firedevops.firemud.accountservice.repository; + +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.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, non-admitting Account-owned storage foundation. No production caller exists. + * + *

Owner-internal seams require a writable SERIALIZABLE Account transaction and lock Account + * before allocation or operation rows. They compare storage identity, not current lifecycle, + * billing, security, source checkpoints or authenticated workload. An eventual authenticated owner + * must compose every current predicate before using these seams. COMMITTED here records a decision + * identity only; it is never source authorization or a public finalization result. + * + *

SQL statement time guards expiry; this does not prove expiry at physical transaction COMMIT. + * ABORTED atomically retains the original full lease and exact orphan decision as pending cleanup; + * Account neither deletes Game Session state nor claims token retirement or cleanup delivery. + */ +public final class AccountGameplayAdmissionLeaseRepository { + private static final String OPERATIONS = "account_gameplay_admission_lease_operations"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private injected persistence context; the repository never exposes it") + public AccountGameplayAdmissionLeaseRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Fence domain is independent of issuance/token fences; retries retain the first allocation. */ + Allocation allocate(UUID accountId, UUID requestId, UUID leaseId) { + lockAccount(accountId); + requireUuidV4(requestId); + requireUuidV4(leaseId); + Record existing = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + requestId); + if (existing != null) { + Allocation prior = allocation(existing); + if (!prior.accountId().equals(accountId) + || !prior.requestId().equals(requestId) + || !prior.leaseId().equals(leaseId)) throw conflict(); + return prior; + } + dsl.execute( + "INSERT INTO account_gameplay_admission_lease_fences(account_uuid, last_fence) VALUES (?, 1) " + + "ON CONFLICT (account_uuid) DO UPDATE SET last_fence = " + + "account_gameplay_admission_lease_fences.last_fence + 1", + accountId); + Record counter = + dsl.fetchOne( + "SELECT last_fence FROM account_gameplay_admission_lease_fences WHERE account_uuid = ?", + accountId); + if (counter == null) { + throw new IllegalStateException("Account admission lease counter readback unavailable"); + } + Long fence = counter.get("last_fence", Long.class); + if (fence == null || fence <= 0L) { + throw new IllegalStateException("Account admission lease counter readback invalid"); + } + int inserted = + dsl.execute( + "INSERT INTO account_gameplay_admission_lease_allocations " + + "(account_uuid, request_id, lease_id, lease_fence) VALUES (?, ?, ?, ?)", + accountId, + requestId, + leaseId, + fence); + if (inserted != 1) { + throw new IllegalStateException("Account admission lease allocation insert unavailable"); + } + Allocation expected = new Allocation(accountId, requestId, leaseId, fence); + Record readback = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + requestId); + if (readback == null) { + throw new IllegalStateException("Account admission lease allocation readback unavailable"); + } + Allocation stored = allocation(readback); + if (!expected.equals(stored)) throw conflict(); + return stored; + } + + /** + * Recovers the original allocation after a lost response using only the original request. An + * empty result is storage absence only, never authoritative absence or no-token proof. + */ + Optional findAllocation(UUID accountId, UUID requestId) { + lockAccount(accountId); + requireUuidV4(requestId); + Record row = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + requestId); + if (row == null) return Optional.empty(); + Allocation stored = allocation(row); + if (!accountId.equals(stored.accountId()) || !requestId.equals(stored.requestId())) + throw conflict(); + return Optional.of(stored); + } + + /** + * Recovers validated original operation storage after a lost response. Workload equality is + * storage correlation only. An eventual facade must supply its concretely verified peer and + * compare current authorization and immutable client inputs before any externally usable retry. + * Empty storage is never admission, authoritative absence or no-token evidence. + */ + Optional findByRequest( + UUID accountId, UUID requestId, String expectedCallerWorkload) { + lockAccount(accountId); + requireUuidV4(requestId); + if (expectedCallerWorkload == null || expectedCallerWorkload.isBlank()) { + throw new IllegalArgumentException("Exact stored caller workload correlation required"); + } + Record row = select(requestId); + if (row == null) return Optional.empty(); + AccountGameplayAdmissionLeaseEvidence evidence = + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + row.get("evidence_json", String.class)); + AccountGameplayAdmissionLeaseOperation stored = exact(row, evidence); + if (!accountId.equals(accountId(stored.evidence())) + || !requestId.equals(id(stored.evidence(), "requestId")) + || !expectedCallerWorkload.equals(stored.evidence().carrier().get("callerWorkload"))) { + throw conflict(); + } + return Optional.of(stored); + } + + /** Stores only the exact carrier for an already retained Account-owned allocation. */ + AccountGameplayAdmissionLeaseOperation beginPending( + AccountGameplayAdmissionLeaseEvidence evidence) { + Objects.requireNonNull(evidence); + UUID accountId = accountId(evidence); + lockAccount(accountId); + Allocation expected = + new Allocation( + accountId, + id(evidence, "requestId"), + id(evidence, "leaseId"), + evidence.leaseFence().longValueExact()); + Record allocated = + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + expected.requestId()); + if (allocated == null || !expected.equals(allocation(allocated))) throw conflict(); + Record prior = select(expected.requestId()); + if (prior != null) return exact(prior, evidence); + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATIONS + + " (account_uuid, request_id, lease_id, lease_fence, caller_workload, evidence_json, " + + "evidence_sha256, evaluated_at_ms, expires_at_ms, status) " + + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING' " + + "WHERE ? <= floor(extract(epoch FROM clock_timestamp()) * 1000) " + + "AND ? > floor(extract(epoch FROM clock_timestamp()) * 1000)", + accountId, + expected.requestId(), + expected.leaseId(), + expected.leaseFence(), + evidence.carrier().get("callerWorkload"), + evidence.canonicalJson(), + evidence.sha256(), + time(evidence, "evaluatedAt"), + time(evidence, "expiresAt"), + time(evidence, "evaluatedAt"), + time(evidence, "expiresAt")); + if (inserted != 1) throw new IllegalStateException("Admission lease storage deadline expired"); + return exact(select(expected.requestId()), evidence); + } + + /** Exact retry/readback retains the original state and deadline, including expired evidence. */ + Optional readExact( + AccountGameplayAdmissionLeaseEvidence evidence) { + Objects.requireNonNull(evidence); + lockAccount(accountId(evidence)); + Record stored = select(id(evidence, "requestId")); + return stored == null ? Optional.empty() : Optional.of(exact(stored, evidence)); + } + + AccountGameplayAdmissionLeaseOperation recordCommitted( + AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { + return terminal(evidence, State.COMMITTED, bindingDecisionId, null); + } + + /** A missing decision remains unknown; the original cleanup identity is always required. */ + AccountGameplayAdmissionLeaseOperation recordAborted( + AccountGameplayAdmissionLeaseEvidence evidence, + UUID bindingDecisionId, + UUID orphanCleanupId) { + requireUuidV4(orphanCleanupId); + return terminal(evidence, State.ABORTED, bindingDecisionId, orphanCleanupId); + } + + private AccountGameplayAdmissionLeaseOperation terminal( + AccountGameplayAdmissionLeaseEvidence evidence, State state, UUID decision, UUID cleanup) { + if (state == State.COMMITTED || decision != null) requireUuidV4(decision); + AccountGameplayAdmissionLeaseOperation prior = + readExact(evidence) + .orElseThrow( + () -> new IllegalStateException("Exact admission lease operation missing")); + if (prior.state() != State.PENDING) { + if (prior.state() != state + || !Objects.equals(prior.bindingDecisionId(), decision) + || !Objects.equals(prior.orphanCleanupId(), cleanup)) throw conflict(); + return prior; + } + int updated = + dsl.execute( + "UPDATE " + + OPERATIONS + + " SET status = ?, binding_decision_id = ?, orphan_cleanup_id = ? " + + "WHERE request_id = ? AND status = 'PENDING' " + + "AND (? = 'ABORTED' OR expires_at_ms > floor(extract(epoch FROM clock_timestamp()) * 1000))", + state.name(), + decision, + cleanup, + id(evidence, "requestId"), + state.name()); + if (updated != 1) throw new IllegalStateException("Admission lease storage deadline expired"); + return exact(select(id(evidence, "requestId")), evidence); + } + + private void lockAccount(UUID accountId) { + requireUuidV4(accountId); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException("Writable SERIALIZABLE Account transaction required"); + } + if (dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", accountId) + == null) throw new IllegalStateException("Account admission storage owner missing"); + } + + private Record select(UUID requestId) { + return dsl.fetchOne( + "SELECT * FROM " + OPERATIONS + " WHERE request_id = ? FOR UPDATE", requestId); + } + + private static AccountGameplayAdmissionLeaseOperation exact( + Record row, AccountGameplayAdmissionLeaseEvidence expected) { + if (row == null) throw new IllegalStateException("Admission lease storage readback missing"); + AccountGameplayAdmissionLeaseEvidence stored = + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + row.get("evidence_json", String.class)); + if (!stored.sha256().equals(row.get("evidence_sha256", String.class)) + || !stored.hasSameIdentity(expected) + || !accountId(stored).equals(row.get("account_uuid", UUID.class)) + || !id(stored, "requestId").equals(row.get("request_id", UUID.class)) + || !id(stored, "leaseId").equals(row.get("lease_id", UUID.class)) + || !Long.valueOf(stored.leaseFence().longValueExact()) + .equals(row.get("lease_fence", Long.class)) + || !stored.carrier().get("callerWorkload").equals(row.get("caller_workload", String.class)) + || !Long.valueOf(time(stored, "evaluatedAt")).equals(row.get("evaluated_at_ms", Long.class)) + || !Long.valueOf(time(stored, "expiresAt")).equals(row.get("expires_at_ms", Long.class))) + throw conflict(); + return new AccountGameplayAdmissionLeaseOperation( + stored, + State.valueOf(row.get("status", String.class)), + row.get("binding_decision_id", UUID.class), + row.get("orphan_cleanup_id", UUID.class)); + } + + private static Allocation allocation(Record row) { + UUID account = row.get("account_uuid", UUID.class); + UUID request = row.get("request_id", UUID.class); + UUID lease = row.get("lease_id", UUID.class); + Long fence = row.get("lease_fence", Long.class); + requireUuidV4(account); + requireUuidV4(request); + requireUuidV4(lease); + if (fence == null || fence <= 0L) throw conflict(); + return new Allocation(account, request, lease, fence); + } + + private static UUID accountId(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString( + (String) ((java.util.Map) evidence.carrier().get("bindingScope")).get("accountId")); + } + + private static UUID id(AccountGameplayAdmissionLeaseEvidence evidence, String key) { + return UUID.fromString((String) evidence.carrier().get(key)); + } + + private static long time(AccountGameplayAdmissionLeaseEvidence evidence, String key) { + return Long.parseLong((String) evidence.carrier().get(key)); + } + + private static void requireUuidV4(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) + throw new IllegalArgumentException("Canonical non-nil UUIDv4 identity required"); + } + + private static IdentityConflictException conflict() { + return new IdentityConflictException(); + } + + static final class IdentityConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + IdentityConflictException() { + super("Exact admission operation identity conflict"); + } + } + + record Allocation(UUID accountId, UUID requestId, UUID leaseId, long leaseFence) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java new file mode 100644 index 0000000000..7d068328d6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java @@ -0,0 +1,187 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Objects; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered opaque original-ACK receipt executor; supplies no authentication or admission. */ +final class AccountGameplayAdmissionOriginalAckReceiptCommitExecutor { + private final DataSource dataSource; + + AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(DataSource dataSource) { + this.dataSource = Objects.requireNonNull(dataSource); + } + + AccountGameplayAdmissionOriginalAckReceipt confirm( + OriginalCommitAcknowledgement acknowledgement) { + Objects.requireNonNull(acknowledgement); + if (!acknowledgement.belongsTo(dataSource)) throw denied(); + rejectAmbient(); + var creation = + execute( + new ReceiptTransactionManager(dataSource), + repository -> { + var result = Objects.requireNonNull(repository.create(acknowledgement)); + var receipt = Objects.requireNonNull(result.receipt()); + validate(receipt, acknowledgement.evidence(), acknowledgement.decisionId()); + if (!receipt.finalizationXid().equals(acknowledgement.finalizationXid()) + || receipt.committedBeforeMs() != acknowledgement.committedBeforeMs()) + throw denied(); + return result; + }); + var created = Objects.requireNonNull(creation.receipt()); + // A fresh insert is proved by its actual receipt COMMIT; a retry COMMIT cannot prove an old + // row. + rejectAmbient(); + var read = + execute( + new ReceiptTransactionManager(dataSource), + repository -> + creation.inserted() + ? repository.readExact(acknowledgement.evidence(), acknowledgement.decisionId()) + : repository.readDurably( + acknowledgement.evidence(), acknowledgement.decisionId())); + validate(read, acknowledgement.evidence(), acknowledgement.decisionId()); + if (!created.equals(read)) throw denied(); + return read; + } + + AccountGameplayAdmissionOriginalAckReceipt read( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + Objects.requireNonNull(evidence); + Objects.requireNonNull(decisionId); + rejectAmbient(); + var receipt = + execute( + new ReceiptTransactionManager(dataSource), + repository -> repository.readDurably(evidence, decisionId)); + validate(receipt, evidence, decisionId); + return receipt; + } + + private static void validate( + AccountGameplayAdmissionOriginalAckReceipt receipt, + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decisionId) { + if (!receipt.operation().evidence().canonicalJson().equals(evidence.canonicalJson()) + || !receipt.operation().evidence().sha256().equals(evidence.sha256()) + || !receipt.bindingDecisionId().equals(decisionId)) throw denied(); + } + + private static T execute( + ReceiptTransactionManager manager, + java.util.function.Function + operation) { + var transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + var result = + transaction.execute( + status -> { + if (!status.isNewTransaction()) throw denied(); + Connection connection = manager.bindConnection(); + var dsl = DSL.using(connection, SQLDialect.POSTGRES); + var repository = + new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + return Objects.requireNonNull(operation.apply(repository)); + }); + if (!manager.committed) throw denied(); + return Objects.requireNonNull(result); + } + + private void rejectAmbient() { + // Spring unwraps a TransactionAwareDataSourceProxy; reject a binding on either identity. + DataSource enlistedSource = + Objects.requireNonNull(new ReceiptTransactionManager(dataSource).getDataSource()); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.hasResource(dataSource) + || TransactionSynchronizationManager.hasResource(enlistedSource)) throw denied(); + } + + private static final class ReceiptTransactionManager extends DataSourceTransactionManager { + private static final long serialVersionUID = 1L; + private transient Connection connection; + private transient boolean committed; + + private ReceiptTransactionManager(DataSource dataSource) { + super(dataSource); + // A failed guard or uncertain COMMIT must roll back before restoring auto-commit. + setRollbackOnCommitFailure(true); + } + + private Connection enlistedConnection() { + Object resource = + TransactionSynchronizationManager.getResource(Objects.requireNonNull(getDataSource())); + if (!(resource instanceof ConnectionHolder holder)) throw denied(); + return holder.getConnection(); + } + + private Connection bindConnection() { + if (connection != null) throw denied(); + connection = enlistedConnection(); + return connection; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + if (!status.isNewTransaction() + || connection == null + || connection != enlistedConnection() + || committed) throw denied(); + try { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE + || !"PostgreSQL".equals(connection.getMetaData().getDatabaseProductName())) + throw denied(); + try (Statement statement = connection.createStatement()) { + statement.execute("SET LOCAL synchronous_commit = on"); + try (ResultSet settings = + statement.executeQuery( + "SELECT current_setting('server_version_num')::integer, pg_is_in_recovery(), " + + "current_setting('fsync'), current_setting('synchronous_commit'), " + + "current_setting('transaction_isolation'), current_setting('transaction_read_only')")) { + if (!settings.next()) throw denied(); + int version = settings.getInt(1); + if (version < 160000 + || version >= 170000 + || settings.getBoolean(2) + || !"on".equals(settings.getString(3)) + || !"on".equals(settings.getString(4)) + || !"serializable".equals(settings.getString(5)) + || !"off".equals(settings.getString(6)) + || settings.next()) throw denied(); + } + } + connection.commit(); + committed = true; + } catch (SQLException failure) { + throw new TransactionSystemException( + "Account receipt physical COMMIT unavailable", failure); + } + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Fresh owned Account receipt COMMIT required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java new file mode 100644 index 0000000000..ea0df8aeb8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java @@ -0,0 +1,172 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.sql.Connection; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered storage for an opaque trusted-JVM acknowledgement of an original Account COMMIT. + * + *

The receipt preserves the exact original operation and post-COMMIT clock bound. SQL checks + * shape and binding but does not authenticate the acknowledgement or derive its clock value. A + * receipt is not current authority, installation, cleanup, or gameplay admission. + */ +final class AccountGameplayAdmissionOriginalAckReceiptRepository { + private static final String RECEIPTS = "account_gameplay_admission_original_commit_ack_receipts"; + private static final String READ_DURABLY_SQL = + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)"; + + private final DSLContext dsl; + private final AccountGameplayAdmissionLeaseRepository leaseRepository; + + AccountGameplayAdmissionOriginalAckReceiptRepository( + DSLContext dsl, AccountGameplayAdmissionLeaseRepository leaseRepository) { + this.dsl = Objects.requireNonNull(dsl); + this.leaseRepository = Objects.requireNonNull(leaseRepository); + } + + /** Stores an exact typed ACK or returns its unchanged retained receipt. */ + Creation create(OriginalCommitAcknowledgement acknowledgement) { + requireWritableSerializableTransaction(); + Objects.requireNonNull(acknowledgement); + AccountGameplayAdmissionLeaseEvidence evidence = + Objects.requireNonNull(acknowledgement.evidence()); + UUID decisionId = Objects.requireNonNull(acknowledgement.decisionId()); + UUID requestId = validateRequest(evidence, decisionId); + + Record inserted = + dsl.fetchOne( + "INSERT INTO " + + RECEIPTS + + " (request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) " + + "VALUES (?, ?, ?, ?, ?) ON CONFLICT (request_id) DO NOTHING RETURNING *", + requestId, + evidence.sha256(), + decisionId, + acknowledgement.finalizationXid(), + acknowledgement.committedBeforeMs()); + AccountGameplayAdmissionLeaseOperation operation = exactCommitted(evidence, decisionId); + AccountGameplayAdmissionOriginalAckReceipt receipt; + boolean wasInserted; + if (inserted != null) { + receipt = decode(inserted, operation); + wasInserted = true; + } else { + Record retained = selectReceipt(requestId); + if (retained == null) throw unavailable(); + receipt = decode(retained, operation); + wasInserted = false; + } + if (!receipt.finalizationXid().equals(acknowledgement.finalizationXid()) + || receipt.committedBeforeMs() != acknowledgement.committedBeforeMs()) { + throw unavailable(); + } + return new Creation(receipt, wasInserted); + } + + /** Exact storage-only read for the sibling owner after it observed successful receipt COMMIT. */ + AccountGameplayAdmissionOriginalAckReceipt readExact( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + requireWritableSerializableTransaction(); + UUID requestId = validateRequest(evidence, decisionId); + Record row = selectReceipt(requestId); + if (row == null) throw unavailable(); + return decode(row, exactCommitted(evidence, decisionId)); + } + + /** Proves historical independent receipt durability without changing its original evidence. */ + AccountGameplayAdmissionOriginalAckReceipt readDurably( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + requireWritableSerializableTransaction(); + UUID requestId = validateRequest(evidence, decisionId); + Record row = dsl.fetchOne(READ_DURABLY_SQL, requestId, evidence.sha256(), decisionId); + if (row == null) throw unavailable(); + return decode(row, exactCommitted(evidence, decisionId)); + } + + private Record selectReceipt(UUID requestId) { + return dsl.fetchOne("SELECT * FROM " + RECEIPTS + " WHERE request_id = ?", requestId); + } + + private AccountGameplayAdmissionLeaseOperation exactCommitted( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + AccountGameplayAdmissionLeaseOperation operation = + leaseRepository + .readExact(evidence) + .orElseThrow(AccountGameplayAdmissionOriginalAckReceiptRepository::unavailable); + if (operation.state() != State.COMMITTED || !decisionId.equals(operation.bindingDecisionId())) + throw unavailable(); + return operation; + } + + private static AccountGameplayAdmissionOriginalAckReceipt decode( + Record row, AccountGameplayAdmissionLeaseOperation operation) { + try { + return new AccountGameplayAdmissionOriginalAckReceipt( + operation, + required(row, "schema_version", Short.class), + required(row, "request_id", UUID.class), + required(row, "account_uuid", UUID.class), + required(row, "lease_id", UUID.class), + required(row, "lease_fence", Long.class), + required(row, "evidence_sha256", String.class), + required(row, "binding_decision_id", UUID.class), + required(row, "expires_at_ms", Long.class), + required(row, "finalization_xid", String.class), + required(row, "committed_before_ms", Long.class), + required(row, "receipt_xid", String.class)); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static T required(Record row, String field, Class type) { + if (row == null) throw unavailable(); + T value = row.get(field, type); + if (value == null) throw unavailable(); + return value; + } + + private static UUID validateRequest( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + Objects.requireNonNull(evidence); + UUID requestId = UUID.fromString((String) evidence.carrier().get("requestId")); + requireUuidV4(requestId); + requireUuidV4(decisionId); + return requestId; + } + + private static void requireWritableSerializableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException("Writable SERIALIZABLE Account transaction required"); + } + } + + private static void requireUuidV4(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Canonical non-nil UUIDv4 identity required"); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Original Account admission acknowledgement receipt unavailable"); + } + + record Creation(AccountGameplayAdmissionOriginalAckReceipt receipt, boolean inserted) { + Creation { + Objects.requireNonNull(receipt); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java new file mode 100644 index 0000000000..09470f9d90 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java @@ -0,0 +1,255 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Objects; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered original storage-COMMIT executor; supplies no authentication or admission authority. + * + *

The opaque acknowledgement binds successful synchronous COMMIT of this fresh transition to a + * subsequent database-clock upper bound strictly before unchanged expiry, on the same connection. + * It is not a persisted temporal confirmation or durable receipt. The protected owner must + * separately persist its exact confirmation and prove the receipt's own durability. Lost + * acknowledgement or unavailable/late clock evidence cannot be reconstructed by retrying this + * executor: a retained COMMITTED operation is rejected. + */ +final class AccountGameplayAdmissionOriginalCommitExecutor { + private final DataSource dataSource; + + AccountGameplayAdmissionOriginalCommitExecutor(DataSource dataSource) { + this.dataSource = Objects.requireNonNull(dataSource); + } + + OriginalCommitAcknowledgement execute( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + Objects.requireNonNull(evidence); + Objects.requireNonNull(decisionId); + var manager = new OriginalCommitTransactionManager(dataSource); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.hasResource( + Objects.requireNonNull(manager.getDataSource()))) { + throw denied(); + } + // Each invocation owns its manager, enlisted connection and acknowledgement slot. + var transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + transaction.executeWithoutResult( + ignored -> { + if (!ignored.isNewTransaction()) throw denied(); + Connection connection = manager.enlistedConnection(); + // The repository cannot acquire another connection: its DSL uses this connection itself. + var repository = + new AccountGameplayAdmissionLeaseRepository( + DSL.using(connection, SQLDialect.POSTGRES)); + var prior = + repository + .readExact(evidence) + .orElseThrow(AccountGameplayAdmissionOriginalCommitExecutor::denied); + if (prior.state() != State.PENDING) throw denied(); + var committed = repository.recordCommitted(evidence, decisionId); + if (committed.state() != State.COMMITTED + || !decisionId.equals(committed.bindingDecisionId()) + || !evidence.canonicalJson().equals(committed.evidence().canonicalJson()) + || !evidence.sha256().equals(committed.evidence().sha256())) throw denied(); + manager.bindOriginal(connection, evidence, decisionId); + }); + return Objects.requireNonNull(manager.acknowledgement); + } + + /** + * Non-serializable, immutable in-process capability; only the physical COMMIT path constructs it. + */ + static final class OriginalCommitAcknowledgement { + private final DataSource originatingSource; + private final AccountGameplayAdmissionLeaseEvidence evidence; + private final UUID decisionId; + private final String finalizationXid; + private final long committedBeforeMs; + + private OriginalCommitAcknowledgement( + DataSource originatingSource, OriginalBinding binding, long committedBeforeMs) { + this.originatingSource = originatingSource; + evidence = binding.evidence(); + decisionId = binding.decisionId(); + finalizationXid = binding.finalizationXid(); + this.committedBeforeMs = committedBeforeMs; + } + + boolean belongsTo(DataSource source) { + return originatingSource == source; + } + + AccountGameplayAdmissionLeaseEvidence evidence() { + return evidence; + } + + UUID decisionId() { + return decisionId; + } + + String finalizationXid() { + return finalizationXid; + } + + long committedBeforeMs() { + return committedBeforeMs; + } + + @Override + public String toString() { + return "OriginalCommitAcknowledgement[not a temporal confirmation]"; + } + } + + private record OriginalBinding( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId, String finalizationXid) {} + + private static final class OriginalCommitTransactionManager extends DataSourceTransactionManager { + private static final long serialVersionUID = 1L; + private final transient DataSource originatingSource; + private transient Connection originalConnection; + private transient OriginalBinding binding; + private transient OriginalCommitAcknowledgement acknowledgement; + + private OriginalCommitTransactionManager(DataSource dataSource) { + super(dataSource); + originatingSource = dataSource; + // A rejected pre-COMMIT durability check must roll back before cleanup restores auto-commit. + // A failed/ambiguous physical COMMIT still never produces an acknowledgement. + setRollbackOnCommitFailure(true); + } + + private Connection enlistedConnection() { + DataSource source = Objects.requireNonNull(getDataSource()); + Object resource = TransactionSynchronizationManager.getResource(source); + if (!(resource instanceof ConnectionHolder holder)) throw denied(); + return holder.getConnection(); + } + + private void bindOriginal( + Connection connection, AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + if (originalConnection != null || binding != null || connection != enlistedConnection()) + throw denied(); + String sql = + "SELECT finalization_xid, pg_current_xact_id_if_assigned()::text " + + "FROM account_gameplay_admission_lease_operations " + + "WHERE request_id = ? AND lease_id = ? AND evidence_sha256 = ? " + + "AND binding_decision_id = ? AND status = 'COMMITTED' FOR UPDATE"; + try (PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setObject(1, UUID.fromString((String) evidence.carrier().get("requestId"))); + statement.setObject(2, UUID.fromString((String) evidence.carrier().get("leaseId"))); + statement.setString(3, evidence.sha256()); + statement.setObject(4, decisionId); + try (ResultSet row = statement.executeQuery()) { + if (!row.next()) throw denied(); + String finalizationXid = row.getString(1); + if (finalizationXid == null + || !finalizationXid.matches("[1-9][0-9]{0,19}") + || !finalizationXid.equals(row.getString(2)) + || row.next()) throw denied(); + originalConnection = connection; + binding = new OriginalBinding(evidence, decisionId, finalizationXid); + } + } catch (SQLException failure) { + throw new TransactionSystemException( + "Original Account finalization identity unavailable", failure); + } + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + if (!status.isNewTransaction() + || binding == null + || originalConnection == null + || originalConnection != enlistedConnection() + || acknowledgement != null) throw denied(); + try { + Connection connection = originalConnection; + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE + || !"PostgreSQL".equals(connection.getMetaData().getDatabaseProductName())) + throw denied(); + try (Statement statement = connection.createStatement()) { + statement.execute("SET LOCAL synchronous_commit = on"); + try (ResultSet settings = + statement.executeQuery( + "SELECT current_setting('server_version_num')::integer, pg_is_in_recovery(), " + + "current_setting('fsync'), current_setting('synchronous_commit'), " + + "current_setting('transaction_isolation'), current_setting('transaction_read_only')")) { + if (!settings.next()) throw denied(); + int version = settings.getInt(1); + if (version < 160000 + || version >= 170000 + || settings.getBoolean(2) + || !"on".equals(settings.getString(3)) + || !"on".equals(settings.getString(4)) + || !"serializable".equals(settings.getString(5)) + || !"off".equals(settings.getString(6)) + || settings.next()) throw denied(); + } + } + // No callback or caller flag can mint this capability. An ambiguous JDBC outcome throws. + connection.commit(); + long committedBeforeMs = observeCommitBound(connection, binding.evidence()); + acknowledgement = + new OriginalCommitAcknowledgement(originatingSource, binding, committedBeforeMs); + } catch (SQLException failure) { + throw new TransactionSystemException( + "Original Account physical COMMIT unavailable", failure); + } + } + + private static long observeCommitBound( + Connection connection, AccountGameplayAdmissionLeaseEvidence evidence) { + // This statement follows the actual successful COMMIT, before cleanup or any reconnect. + // A failure here cannot undo that original COMMIT, and must never mint a capability. + try (Statement statement = connection.createStatement(); + ResultSet row = + statement.executeQuery( + "SELECT ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint")) { + if (!row.next()) throw unavailableClock(); + BigDecimal value = row.getBigDecimal(1); + if (value == null) throw unavailableClock(); + long observed = value.longValueExact(); + long expiry = Long.parseLong((String) evidence.carrier().get("expiresAt")); + if (observed <= 0 || observed >= expiry || row.next()) throw unavailableClock(); + return observed; + } catch (SQLException failure) { + throw new TransactionSystemException( + "Original Account post-COMMIT clock unavailable", failure); + } catch (ArithmeticException failure) { + throw unavailableClock(); + } + } + } + + private static IllegalStateException unavailableClock() { + return new IllegalStateException("Original Account post-COMMIT clock bound unavailable"); + } + + private static IllegalStateException denied() { + return new IllegalStateException("Fresh owned Account original COMMIT required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwner.java new file mode 100644 index 0000000000..3eab991cbe --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwner.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.accountservice.repository; + +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered, non-authorizing exact readback for retained negative admission state. + * + *

The owner accepts only the original same-namespace Game Session workload and a complete + * expected lease carrier. It returns exact PENDING or ABORTED storage evidence; missing operations, + * identity mismatches, and raw storage COMMITTED are unresolved and never become admission results. + */ +public final class AccountGameplayAdmissionReadOwner { + private final AccountGameplayAdmissionLeaseRepository repository; + private final TransactionTemplate transaction; + private final String namespace; + + public AccountGameplayAdmissionReadOwner( + AccountGameplayAdmissionLeaseRepository repository, + PlatformTransactionManager transactionManager, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + } + + public AccountGameplayAdmissionLeaseOperation read(ReadGameplayAdmissionLeaseRequest request) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + if (!GrpcPeerIdentity.isValidNamespace(namespace) + || !peer.uri().equals("spiffe://firemud/ns/" + namespace + "/sa/game-session-service")) + throw Status.PERMISSION_DENIED + .withDescription("Game Session workload required") + .asRuntimeException(); + if (request == null + || !request.hasExpectedLease() + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Malformed Account admission lease read request"); + } + + var evidence = + AccountGameplayAdmissionLeaseWireCodec.parseReference(request.getExpectedLease()); + if (!request.getRequestId().equals(evidence.carrier().get("requestId"))) { + throw new IllegalArgumentException("Malformed Account admission lease read request"); + } + if (!namespace.equals(evidence.carrier().get("targetNamespace")) + || !peer.uri().equals(evidence.carrier().get("callerWorkload"))) { + throw Status.PERMISSION_DENIED + .withDescription("Admission lease caller mismatch") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Owned Account transaction required") + .asRuntimeException(); + } + + return Objects.requireNonNull( + transaction.execute( + ignored -> { + AccountGameplayAdmissionLeaseOperation stored; + try { + stored = + repository + .readExact(evidence) + .orElseThrow(AccountGameplayAdmissionReadOwner::unresolved); + } catch (AccountGameplayAdmissionLeaseRepository.IdentityConflictException failure) { + throw unresolved(); + } catch (IllegalArgumentException failure) { + // The request was already parsed; a parser failure here is corrupt stored evidence. + throw unresolved(); + } + if (stored.state() == State.COMMITTED) throw unresolved(); + return stored; + })); + } + + private static RuntimeException unresolved() { + return Status.FAILED_PRECONDITION + .withDescription("Exact Account admission lease readback unavailable") + .asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutor.java new file mode 100644 index 0000000000..75d05e4406 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutor.java @@ -0,0 +1,155 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Objects; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionCommitConfirmation; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered receipt persistence executor; supplies no admission or original clock authority. */ +final class AccountGameplayAdmissionReceiptCommitExecutor { + private final DataSource dataSource; + + AccountGameplayAdmissionReceiptCommitExecutor(DataSource dataSource) { + this.dataSource = Objects.requireNonNull(dataSource); + } + + AccountGameplayAdmissionCommitConfirmation confirm( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + rejectAmbient(); + var creation = new ReceiptTransactionManager(dataSource); + var created = execute(creation, evidence, decisionId, true); + // execute returns only after this manager observed the concrete JDBC COMMIT successfully. + rejectAmbient(); + var read = execute(new ReceiptTransactionManager(dataSource), evidence, decisionId, false); + if (!created.equals(read)) throw denied(); + return read; + } + + AccountGameplayAdmissionCommitConfirmation read( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + rejectAmbient(); + return execute(new ReceiptTransactionManager(dataSource), evidence, decisionId, false); + } + + private static AccountGameplayAdmissionCommitConfirmation execute( + ReceiptTransactionManager manager, + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decisionId, + boolean create) { + Objects.requireNonNull(evidence); + Objects.requireNonNull(decisionId); + var transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + var result = + transaction.execute( + status -> { + if (!status.isNewTransaction()) throw denied(); + Connection connection = manager.bindConnection(); + var dsl = DSL.using(connection, SQLDialect.POSTGRES); + var repository = + new AccountGameplayAdmissionCommitConfirmationRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + var receipt = + Objects.requireNonNull( + create + ? repository.confirmCommitted(evidence, decisionId) + : repository.readCommitConfirmation(evidence, decisionId)); + if (!receipt.operation().evidence().canonicalJson().equals(evidence.canonicalJson()) + || !receipt.operation().evidence().sha256().equals(evidence.sha256()) + || !receipt.bindingDecisionId().equals(decisionId)) throw denied(); + return receipt; + }); + if (!manager.committed) throw denied(); + return Objects.requireNonNull(result); + } + + private void rejectAmbient() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.hasResource(dataSource)) throw denied(); + } + + private static final class ReceiptTransactionManager extends DataSourceTransactionManager { + private static final long serialVersionUID = 1L; + private transient Connection connection; + private transient boolean committed; + + private ReceiptTransactionManager(DataSource dataSource) { + super(dataSource); + // A failed guard or uncertain COMMIT must roll back before restoring auto-commit. + setRollbackOnCommitFailure(true); + } + + private Connection enlistedConnection() { + Object resource = + TransactionSynchronizationManager.getResource(Objects.requireNonNull(getDataSource())); + if (!(resource instanceof ConnectionHolder holder)) throw denied(); + return holder.getConnection(); + } + + private Connection bindConnection() { + if (connection != null) throw denied(); + connection = enlistedConnection(); + return connection; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + if (!status.isNewTransaction() + || connection == null + || connection != enlistedConnection() + || committed) throw denied(); + try { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE + || !"PostgreSQL".equals(connection.getMetaData().getDatabaseProductName())) + throw denied(); + try (Statement statement = connection.createStatement()) { + statement.execute("SET LOCAL synchronous_commit = on"); + try (ResultSet settings = + statement.executeQuery( + "SELECT current_setting('server_version_num')::integer, pg_is_in_recovery(), " + + "current_setting('fsync'), current_setting('synchronous_commit'), " + + "current_setting('transaction_isolation'), current_setting('transaction_read_only')")) { + if (!settings.next()) throw denied(); + int version = settings.getInt(1); + if (version < 160000 + || version >= 170000 + || settings.getBoolean(2) + || !"on".equals(settings.getString(3)) + || !"on".equals(settings.getString(4)) + || !"serializable".equals(settings.getString(5)) + || !"off".equals(settings.getString(6)) + || settings.next()) throw denied(); + } + } + connection.commit(); + committed = true; + } catch (SQLException failure) { + throw new TransactionSystemException( + "Account receipt physical COMMIT unavailable", failure); + } + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Fresh owned Account receipt COMMIT required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBinding.java new file mode 100644 index 0000000000..83ad16d083 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBinding.java @@ -0,0 +1,29 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.regex.Pattern; + +/** Keyed, versioned credential-request identity persisted with one gameplay LOGIN operation. */ +public record AccountGameplayCredentialRequestBinding( + int digestSchemaVersion, String digestKeyId, String credentialRequestDigest) { + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,32}"); + private static final Pattern HMAC_SHA256 = Pattern.compile("[0-9a-f]{64}"); + + public AccountGameplayCredentialRequestBinding { + if (digestSchemaVersion != 1) { + throw new IllegalArgumentException("Unsupported credential digest schema version"); + } + if (digestKeyId == null || !KEY_ID.matcher(digestKeyId).matches()) { + throw new IllegalArgumentException("Credential digest key identifier is malformed"); + } + Objects.requireNonNull(credentialRequestDigest, "Credential request digest is required"); + if (!HMAC_SHA256.matcher(credentialRequestDigest).matches()) { + throw new IllegalArgumentException("Credential request digest is malformed"); + } + } + + @Override + public String toString() { + return "AccountGameplayCredentialRequestBinding[redacted]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java new file mode 100644 index 0000000000..5a5f6ea6a6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java @@ -0,0 +1,2538 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection.ProjectionObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.PendingRegistrationOutcome; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +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; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned immutable issuance intent, candidate binding, and non-authorizing commit evidence. + * + *

This is deliberately not an Authenticate issuer, signer-promotion authority, response recovery + * store, active-token validator, or registry activation path. It records a bounded pre-sign intent, + * separately binds the candidate hash and canonical pending projection, and can persist COMMITTED + * only with signer-owned verification, pinned Redis, current projection, full bundle, and sealed + * envelope evidence. Every mutation locks the existing Account authority rows in the caller's + * Account transaction; no remote operation is performed while those locks are held. + */ +@Repository +public class AccountGameplayDelegationIssuanceRepository { + private static final String TABLE = "account_gameplay_delegation_issuance_operations"; + private static final int REQUEST_DIGEST_VERSION = 2; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final int MAX_INTENT_BYTES = 16 * 1024; + private static final int MAX_COMMIT_PROOF_BYTES = + AccountGameplayDelegationIssuanceCommitService.MAX_COMMIT_PROOF_BYTES; + private static final byte[] EMPTY_OBJECT = "{}".getBytes(StandardCharsets.US_ASCII); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final DSLContext dsl; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountAuthEvidenceBundleRepository evidenceBundles; + private final Clock clock; + private final AccountGameplayTokenIdentityFenceRepository tokenIdentityFences; + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator preconditions fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountGameplayDelegationIssuanceRepository( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository evidenceBundles) { + this(dsl, sourceEvidence, evidenceBundles, Clock.systemUTC()); + } + + /** Compatibility for non-signing repositories/fixtures that only use the pending boundary. */ + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator preconditions fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountGameplayDelegationIssuanceRepository( + DSLContext dsl, AccountAuthoritySourceEvidenceRepository sourceEvidence) { + this(dsl, sourceEvidence, defaultEvidenceBundles(dsl), Clock.systemUTC()); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator preconditions fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountGameplayDelegationIssuanceRepository( + DSLContext dsl, AccountAuthoritySourceEvidenceRepository sourceEvidence, Clock clock) { + this(dsl, sourceEvidence, defaultEvidenceBundles(dsl), clock); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator preconditions fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountGameplayDelegationIssuanceRepository( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository evidenceBundles, + Clock clock) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.sourceEvidence = + Objects.requireNonNull(sourceEvidence, "Account authority source evidence is required"); + this.evidenceBundles = evidenceBundles; + this.clock = Objects.requireNonNull(clock, "Clock is required"); + this.tokenIdentityFences = new AccountGameplayTokenIdentityFenceRepository(dsl); + } + + /** Persists an immutable pre-sign intent or returns its exact still-current replay. */ + @Transactional(propagation = Propagation.MANDATORY) + public PendingOperation beginPending(PendingIntent intent) { + requireWritableAccountTransaction(); + Objects.requireNonNull(intent, "Account gameplay delegation intent is required"); + tokenIdentityFences.lockAccountForUpdate(intent.authoritySnapshot().accountId()); + lockRequestId(intent.requestId()); + long now = Math.floorDiv(clock.millis(), 1000L); + long latestIssueTime; + try { + latestIssueTime = Math.addExact(now, 5L); + } catch (ArithmeticException ex) { + latestIssueTime = Long.MAX_VALUE; + } + if (now <= 0L + || intent.expiresAtEpochSecond() <= now + || intent.issuedAtEpochSecond() > latestIssueTime) { + throw new IllegalArgumentException("Delegation issuance intent is expired"); + } + IssuerAccountSourceSnapshot current = readAndCompareAuthority(intent); + String digest = requestDigest(intent); + Record prior = selectByRequestId(intent.requestId(), false); + if (prior != null) { + requireExactIntent(prior, intent, digest, current); + Record locked = selectByRequestId(intent.requestId(), true); + if (locked == null) throw new StorageUnavailableException(); + requireExactIntent(locked, intent, digest, current); + return decodeOperation(locked); + } + + insertIntent(intent, digest, current); + Record readback = selectByRequestId(intent.requestId(), true); + if (readback == null) throw new StorageUnavailableException(); + requireExactIntent(readback, intent, digest, current); + return decodeOperation(readback); + } + + /** + * Reads the exact current PENDING or COMMITTED gameplay-login request under its request-id + * serialization lock. A COMMITTED replay additionally requires the canonical persisted commit + * proof. This metadata-only owner boundary rechecks current source authority and original expiry; + * it never reconstructs the request identity or returns a credential. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional readCurrentGameplayLoginReplay( + UUID requestId) { + requireWritableAccountTransaction(); + requireRequestId(requestId); + + Record preliminary = selectByRequestId(requestId, false); + if (preliminary == null) return java.util.Optional.empty(); + String preliminaryStatus = preliminary.get("status", String.class); + if (!isReplayableGameplayLoginStatus(preliminaryStatus)) { + throw new IdempotencyConflictException(); + } + UUID accountId = preliminary.get("account_uuid", UUID.class); + UUID operationId = preliminary.get("operation_id", UUID.class); + if (accountId == null || operationId == null) throw new StorageUnavailableException(); + + tokenIdentityFences.lockAccountForUpdate(accountId); + lockRequestId(requestId); + IssuerAccountSourceSnapshot current = readCurrentAuthority(accountId); + Record locked = selectByRequestId(requestId, true); + String lockedStatus = locked == null ? null : locked.get("status", String.class); + if (locked == null + || !accountId.equals(locked.get("account_uuid", UUID.class)) + || !operationId.equals(locked.get("operation_id", UUID.class)) + || !isReplayableGameplayLoginStatus(lockedStatus) + || ("COMMITTED".equals(preliminaryStatus) && !"COMMITTED".equals(lockedStatus))) { + throw new IdempotencyConflictException(); + } + AccountGameplayDelegationPendingIdentity identity = identity(locked); + requireStoredAuthority(locked, current); + AccountAuthoritySnapshot currentAuthority = authoritySnapshot(current); + PendingIntent exactIntent = + new PendingIntent( + identity.operationId(), + identity.requestId(), + identity.callerWorkload(), + identity.callerContextId(), + identity.tokenJti(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + currentAuthority, + identity.credentialRequestBinding()); + if (!requestId.equals(identity.requestId()) + || !identity.requestDigest().equals(requestDigest(exactIntent))) { + throw new IdempotencyConflictException(); + } + if (identity.expiresAtEpochSecond() <= Math.floorDiv(clock.millis(), 1000L)) { + throw new PendingCandidateUnavailableException(); + } + PendingOperation operation = decodeOperation(locked); + CommittedIssuanceReadback committedProof = null; + GameplayLoginReplayState replayState = GameplayLoginReplayState.PENDING; + if ("COMMITTED".equals(lockedStatus)) { + if (!operation.candidateBound()) throw new StorageUnavailableException(); + committedProof = + decodeCommittedReadback( + locked, + locked.get("commit_proof_sha256", String.class), + locked.get("commit_proof_canonical_bytes", byte[].class)); + replayState = GameplayLoginReplayState.COMMITTED; + } + return java.util.Optional.of( + new GameplayLoginReplayReadback(identity, operation, replayState, committedProof, false)); + } + + /** Creates a single Account-owned request identity from the current locked authority snapshot. */ + @Transactional(propagation = Propagation.MANDATORY) + public GameplayLoginReplayReadback beginPendingForAccount( + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + AccountGameplayCredentialRequestBinding credentialRequestBinding) { + requireWritableAccountTransaction(); + requireRequestId(requestId); + Objects.requireNonNull(accountId, "Account UUID is required"); + if (accountId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("A non-nil Account UUID is required"); + } + requireRequestId(callerContextId); + Objects.requireNonNull(callerWorkload, "Caller workload is required"); + Objects.requireNonNull( + credentialRequestBinding, "Keyed credential request binding is required"); + tokenIdentityFences.lockAccountForUpdate(accountId); + lockRequestId(requestId); + + java.util.Optional existing = + readCurrentGameplayLoginReplay(requestId); + if (existing.isPresent()) { + GameplayLoginReplayReadback replay = existing.orElseThrow(); + AccountGameplayDelegationPendingIdentity identity = replay.identity(); + if (!accountId.equals(identity.accountId()) + || !callerWorkload.equals(identity.callerWorkload()) + || !callerContextId.equals(identity.callerContextId()) + || !credentialRequestBinding.equals(identity.credentialRequestBinding())) { + throw new IdempotencyConflictException(); + } + return replay; + } + + IssuerAccountSourceSnapshot current = readCurrentAuthority(accountId); + long issuedAt = Math.floorDiv(clock.millis(), 1000L); + long expiresAt; + try { + expiresAt = + Math.addExact(issuedAt, GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS); + } catch (ArithmeticException ex) { + throw new StorageUnavailableException(); + } + PendingIntent intent = + new PendingIntent( + UUID.randomUUID(), + requestId, + callerWorkload, + callerContextId, + UUID.randomUUID(), + issuedAt, + issuedAt, + expiresAt, + authoritySnapshot(current), + credentialRequestBinding); + PendingOperation operation = beginPending(intent); + Record readback = selectByRequestId(requestId, true); + if (readback == null) throw new StorageUnavailableException(); + AccountGameplayDelegationPendingIdentity identity = identity(readback); + requireExactIntent(readback, intent, requestDigest(intent), current); + if (!operation.equals(decodeOperation(readback))) throw new StorageUnavailableException(); + return new GameplayLoginReplayReadback( + identity, operation, GameplayLoginReplayState.PENDING, null, true); + } + + /** + * Reads the exact current owner identity and persisted full evidence bundle before signing or + * resuming a previously signed candidate. Account and authority rows are locked before the + * immutable operation row; the canonical bundle owner re-evaluates and returns its persisted + * bytes in this same Account transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PendingSigningIdentity readPendingSigningIdentity(UUID requestId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(requestId, "Request ID is required"); + if (evidenceBundles == null) throw new PendingCandidateUnavailableException(); + + Record preliminary = selectByRequestId(requestId, false); + if (preliminary == null) throw new PendingCandidateUnavailableException(); + UUID preliminaryAccountId = preliminary.get("account_uuid", UUID.class); + UUID preliminaryOperationId = preliminary.get("operation_id", UUID.class); + if (preliminaryAccountId == null || preliminaryOperationId == null) { + throw new PendingCandidateUnavailableException(); + } + + IssuerAccountSourceSnapshot current = readCurrentAuthority(preliminaryAccountId); + Record operation = selectByRequestId(requestId, true); + if (operation == null + || !preliminaryAccountId.equals(operation.get("account_uuid", UUID.class)) + || !preliminaryOperationId.equals(operation.get("operation_id", UUID.class)) + || !"PENDING".equals(operation.get("status", String.class)) + || !Objects.equals(operation.get("token_generation", Long.class), 1L) + || !hasConsistentCandidateBinding(operation)) { + throw new PendingCandidateUnavailableException(); + } + + AccountGameplayDelegationPendingIdentity identity = identity(operation); + AccountAuthoritySnapshot authority = authoritySnapshot(current); + if (!requestId.equals(identity.requestId()) + || !preliminaryAccountId.equals(identity.accountId())) { + throw new PendingCandidateUnavailableException(); + } + requireStoredAuthority(operation, current); + PendingIntent exactIntent = + new PendingIntent( + identity.operationId(), + identity.requestId(), + identity.callerWorkload(), + identity.callerContextId(), + identity.tokenJti(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + authority, + identity.credentialRequestBinding()); + if (!identity.requestDigest().equals(requestDigest(exactIntent))) { + throw new IdempotencyConflictException(); + } + long now = Math.floorDiv(clock.millis(), 1000L); + if (now <= 0L || identity.expiresAtEpochSecond() <= now) { + throw new PendingCandidateUnavailableException(); + } + + AccountAuthEvidenceBundle captured = evidenceBundles.captureAndPersist(requestId); + AccountAuthEvidenceBundle stored = + evidenceBundles.readStoredNonAuthorizingValue(identity.operationId()); + if (!MessageDigest.isEqual(captured.canonicalBytes(), stored.canonicalBytes())) { + throw new PendingCandidateUnavailableException(); + } + requireExactSigningBundle(stored, identity, authority, current); + Optional persistedCandidate = + operation.get("token_hash", String.class) == null + ? Optional.empty() + : Optional.of(decodePendingRegistryCandidate(operation, current, stored)); + return new PendingSigningIdentity(identity, authority, stored, persistedCandidate); + } + + private static boolean hasConsistentCandidateBinding(Record operation) { + String tokenHash = operation.get("token_hash", String.class); + String kid = operation.get("signer_kid", String.class); + String generation = operation.get("signer_generation", String.class); + byte[] candidateBytes = operation.get("pending_registry_candidate_bytes", byte[].class); + boolean any = tokenHash != null || kid != null || generation != null || candidateBytes != null; + boolean all = tokenHash != null && kid != null && generation != null && candidateBytes != null; + return !any || all; + } + + /** + * Binds the signed compact-token identity once. The raw JWT is transient and never stored; this + * method cannot assert signature validity, promotion, or active-token authority. + */ + @Transactional(propagation = Propagation.MANDATORY) + public BoundTokenCandidate bindSignedCandidate( + UUID requestId, String compactJwt, String signerGeneration) { + requireWritableAccountTransaction(); + Objects.requireNonNull(requestId, "Request ID is required"); + Objects.requireNonNull(compactJwt, "Compact JWT is required"); + requirePositiveDecimal(signerGeneration, "signerGeneration"); + Record prior = selectByRequestId(requestId, false); + if (prior == null) throw new StorageUnavailableException(); + UUID accountId = prior.get("account_uuid", UUID.class); + IssuerAccountSourceSnapshot current = readCurrentAuthority(accountId); + Record operation = selectByRequestId(requestId, true); + if (operation == null || !accountId.equals(operation.get("account_uuid", UUID.class))) { + throw new StorageUnavailableException(); + } + requireStoredAuthority(operation, current); + + AccountGameplayDelegationPendingIdentity identity = identity(operation); + AccountAuthoritySnapshot accountSnapshot = authoritySnapshot(current); + AccountAuthEvidenceBundle evidenceBundle = + requireCurrentEvidenceBundle(requestId, identity, accountSnapshot, current); + GameSessionAccountDelegationRegistryRecord candidate = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compactJwt, + signerGeneration, + new IssuanceBinding( + identity.operationId().toString(), + identity.requestId().toString(), + identity.requestDigest(), + identity.accountId().toString()), + accountSnapshot, + evidenceBundleReference(evidenceBundle), + Math.floorDiv(clock.millis(), 1000L), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + Map candidateFields = candidate.fields(); + if (!identity.operationId().toString().equals(candidate.operationId()) + || !identity.requestId().toString().equals(candidate.requestId()) + || !identity.requestDigest().equals(candidate.requestDigest()) + || !identity.accountId().toString().equals(candidate.accountId()) + || !identity.tokenJti().toString().equals(candidate.jti()) + || identity.issuedAtEpochSecond() != candidate.issuedAtEpochSecond() + || identity.notBeforeEpochSecond() != candidate.notBeforeEpochSecond() + || identity.expiresAtEpochSecond() != candidate.expiresAtEpochSecond() + || candidate.issuanceFence() != authoritySnapshot(current).issuanceFence() + || !Arrays.equals( + canonicalJson(candidateFields.get("authorityTuple")), + canonicalJson(authorityTuple(authoritySnapshot(current)))) + || !Arrays.equals(canonicalJson(candidateFields.get("membershipVersion")), EMPTY_OBJECT) + || !Arrays.equals( + canonicalJson(candidateFields.get("authoritySourceVersions")), + canonicalJson(sourceVersionsMap(current)))) { + throw new IdempotencyConflictException(); + } + byte[] candidateBytes = + candidate.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + String hash = candidate.tokenHash(); + String kid = candidate.kid(); + String existingHash = operation.get("token_hash", String.class); + byte[] existingBytes = operation.get("pending_registry_candidate_bytes", byte[].class); + String existingSigner = operation.get("signer_generation", String.class); + String existingKid = operation.get("signer_kid", String.class); + if (existingHash != null + || existingBytes != null + || existingSigner != null + || existingKid != null) { + if (!hash.equals(existingHash) + || !Arrays.equals(candidateBytes, existingBytes) + || !signerGeneration.equals(existingSigner) + || !kid.equals(existingKid)) { + throw new IdempotencyConflictException(); + } + return new BoundTokenCandidate(identity.requestId(), hash, kid, signerGeneration); + } + + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET token_hash = ?, signer_kid = ?, signer_generation = ?, " + + "pending_registry_candidate_bytes = ? WHERE request_id = ? " + + "AND status = 'PENDING' AND token_hash IS NULL AND signer_kid IS NULL " + + "AND signer_generation IS NULL AND pending_registry_candidate_bytes IS NULL", + hash, + kid, + signerGeneration, + candidateBytes, + requestId); + if (changed != 1) throw new StorageUnavailableException(); + Record readback = selectByRequestId(requestId, true); + if (readback == null + || !hash.equals(readback.get("token_hash", String.class)) + || !kid.equals(readback.get("signer_kid", String.class)) + || !signerGeneration.equals(readback.get("signer_generation", String.class)) + || !Arrays.equals( + candidateBytes, readback.get("pending_registry_candidate_bytes", byte[].class))) { + throw new StorageUnavailableException(); + } + requireStoredAuthority(readback, current); + return new BoundTokenCandidate(identity.requestId(), hash, kid, signerGeneration); + } + + /** Reads a canonical pending projection only after an exact current-authority SQL recheck. */ + @Transactional(propagation = Propagation.REQUIRED) + public PendingRegistryCandidate readPendingRegistryCandidate(UUID requestId) { + Objects.requireNonNull(requestId, "Request ID is required"); + Record prior = selectByRequestId(requestId, false); + if (prior == null) throw new StorageUnavailableException(); + UUID accountId = prior.get("account_uuid", UUID.class); + IssuerAccountSourceSnapshot current = readCurrentAuthority(accountId); + Record row = selectByRequestId(requestId, true); + if (row == null + || !accountId.equals(row.get("account_uuid", UUID.class)) + || !"PENDING".equals(row.get("status", String.class))) { + throw new StorageUnavailableException(); + } + requireStoredAuthority(row, current); + AccountAuthEvidenceBundle evidenceBundle = + requireCurrentEvidenceBundle(requestId, identity(row), authoritySnapshot(current), current); + return decodePendingRegistryCandidate(row, current, evidenceBundle); + } + + private PendingRegistryCandidate decodePendingRegistryCandidate( + Record row, IssuerAccountSourceSnapshot current, AccountAuthEvidenceBundle evidenceBundle) { + byte[] bytes = row.get("pending_registry_candidate_bytes", byte[].class); + String hash = row.get("token_hash", String.class); + String kid = row.get("signer_kid", String.class); + String signer = row.get("signer_generation", String.class); + if (bytes == null || hash == null || kid == null || signer == null) { + throw new PendingCandidateUnavailableException(); + } + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.decode( + bytes, GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + AccountGameplayDelegationPendingIdentity identity = identity(row); + if (!record.tokenHash().equals(hash) + || !record.kid().equals(kid) + || !record.signerGeneration().equals(signer) + || !"pending".equals(record.state()) + || !record.operationId().equals(identity.operationId().toString()) + || !record.requestId().equals(identity.requestId().toString()) + || !record.requestDigest().equals(identity.requestDigest()) + || !record.accountId().equals(identity.accountId().toString()) + || !record.jti().equals(identity.tokenJti().toString()) + || record.issuanceFence() != authoritySnapshot(current).issuanceFence() + || !Arrays.equals( + canonicalJson(record.fields().get("authorityTuple")), + canonicalJson(authorityTuple(authoritySnapshot(current)))) + || !Arrays.equals(canonicalJson(record.fields().get("membershipVersion")), EMPTY_OBJECT) + || !Arrays.equals( + canonicalJson(record.fields().get("authoritySourceVersions")), + canonicalJson(sourceVersionsMap(current))) + || !record.evidenceBundleReference().equals(evidenceBundleReference(evidenceBundle)) + || !Long.valueOf(identity.issuedAtEpochSecond()) + .equals(requireJsonInteger(record.fields().get("iat"))) + || !Long.valueOf(identity.notBeforeEpochSecond()) + .equals(requireJsonInteger(record.fields().get("nbf"))) + || !Long.valueOf(identity.expiresAtEpochSecond()) + .equals(requireJsonInteger(record.fields().get("exp")))) { + throw new StorageUnavailableException(); + } + return new PendingRegistryCandidate( + identity, + hash, + kid, + signer, + record.expiresAtEpochSecond(), + bytes, + authoritySnapshot(current), + evidenceBundleReference(evidenceBundle)); + } + + /** + * Reads and validates the complete immutable COMMITTED owner evidence under the same Account, + * authority, and operation lock order used by issuance. The result is non-authorizing metadata; + * it deliberately contains neither the JWT, registry bytes, response ciphertext, nor proof bytes. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CommittedCandidateVerificationData readCurrentCommittedCandidate(UUID requestId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(requestId, "Request ID is required"); + if (evidenceBundles == null) throw new StorageUnavailableException(); + + Record preliminary = selectByRequestId(requestId, false); + if (preliminary == null) throw new StorageUnavailableException(); + UUID accountId = preliminary.get("account_uuid", UUID.class); + UUID operationId = preliminary.get("operation_id", UUID.class); + if (accountId == null || operationId == null) throw new StorageUnavailableException(); + + IssuerAccountSourceSnapshot current = readCurrentAuthority(accountId); + Record row = selectByRequestId(requestId, true); + if (row == null + || !accountId.equals(row.get("account_uuid", UUID.class)) + || !operationId.equals(row.get("operation_id", UUID.class)) + || !requestId.equals(row.get("request_id", UUID.class)) + || !"COMMITTED".equals(row.get("status", String.class)) + || !Objects.equals(row.get("token_generation", Long.class), 1L) + || row.get("token_hash", String.class) == null + || row.get("signer_kid", String.class) == null + || row.get("signer_generation", String.class) == null + || row.get("pending_registry_candidate_bytes", byte[].class) == null) { + throw new StorageUnavailableException(); + } + AccountGameplayDelegationPendingIdentity identity = identity(row); + AccountAuthoritySnapshot authority = authoritySnapshot(current); + requireStoredAuthority(row, current); + PendingIntent exactIntent = + new PendingIntent( + identity.operationId(), + identity.requestId(), + identity.callerWorkload(), + identity.callerContextId(), + identity.tokenJti(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + authority, + identity.credentialRequestBinding()); + if (!requestDigest(exactIntent).equals(identity.requestDigest())) { + throw new IdempotencyConflictException(); + } + requireUnexpired(identity); + + AccountAuthEvidenceBundle bundle; + try { + bundle = evidenceBundles.readStoredNonAuthorizingValue(operationId); + } catch (RuntimeException failure) { + throw new StorageUnavailableException(); + } + requireExactSigningBundle(bundle, identity, authority, current); + PendingRegistryCandidate candidate = decodePendingRegistryCandidate(row, current, bundle); + + CommittedIssuanceReadback readback = decodeCommittedReadback(row, null, null); + String proofSha256 = row.get("commit_proof_sha256", String.class); + byte[] proofBytes = row.get("commit_proof_canonical_bytes", byte[].class); + Map proof = parseCommitProof(proofBytes); + requireCommittedProofIdentity(proof, identity, readback, candidate, bundle, current); + tokenIdentityFences.requireActiveForUpdate(tokenIdentity(row)); + AuthenticatedSignerCorrespondence correspondence = + requireCommittedSignerProof(proof, candidate); + EnvelopeIdentity envelope = + requireCommittedEnvelopeProof(proof, identity, candidate, authority, bundle); + Map persistedRegistry = requireMap(proof.get("registry")); + long registryExpiryMillis = + positiveCanonicalLong(persistedRegistry.get("absoluteExpiryMillis")); + long registrationLocalAofCount = positiveCanonicalLong(persistedRegistry.get("localAofCount")); + long registrationReplicaAofCount = + positiveCanonicalLong(persistedRegistry.get("replicaAofCount")); + PendingRegistrationOutcome registrationOutcome = + switch (Objects.toString(persistedRegistry.get("outcome"), "")) { + case "CREATED" -> PendingRegistrationOutcome.CREATED; + case "EXACT_RETRY" -> PendingRegistrationOutcome.EXACT_RETRY; + default -> throw new StorageUnavailableException(); + }; + + return new CommittedCandidateVerificationData( + identity, + authority, + evidenceBundleReference(bundle), + candidate.tokenHash(), + candidate.kid(), + candidate.signerGeneration(), + sha256(candidate.canonicalRecordBytes()), + proofSha256, + correspondence, + envelope.keyId(), + envelope.sha256(), + envelope.length(), + envelope.expiryMillis(), + registryExpiryMillis, + registrationLocalAofCount, + registrationReplicaAofCount, + registrationOutcome); + } + + /** + * Resolves an untrusted signed-token JTI only to the request key of a committed operation, then + * runs the same full current-authority/commit-proof read used by the issuance owner. The JTI is a + * lookup hint, never authentication or permission by itself. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional readCurrentCommittedCandidateByJti( + UUID tokenJti) { + requireWritableAccountTransaction(); + if (tokenJti == null || tokenJti.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil token JTI is required"); + } + Record requestRow; + try { + requestRow = + dsl.fetchOne( + "SELECT request_id FROM account_gameplay_delegation_issuance_operations " + + "WHERE token_jti = ? AND status = 'COMMITTED' AND token_generation = 1", + tokenJti); + } catch (org.jooq.exception.TooManyRowsException ambiguous) { + throw new StorageUnavailableException(); + } + if (requestRow == null) return java.util.Optional.empty(); + UUID requestId = requestRow.get("request_id", UUID.class); + if (requestId == null || requestId.equals(new UUID(0L, 0L))) { + throw new StorageUnavailableException(); + } + CommittedCandidateVerificationData current = readCurrentCommittedCandidate(requestId); + if (current == null + || !requestId.equals(current.identity().requestId()) + || !tokenJti.equals(current.identity().tokenJti())) { + throw new StorageUnavailableException(); + } + return java.util.Optional.of(current); + } + + private void requireUnexpired(AccountGameplayDelegationPendingIdentity identity) { + long now = Math.floorDiv(clock.millis(), 1_000L); + long latestIssuedAt = now > Long.MAX_VALUE - 5L ? Long.MAX_VALUE : now + 5L; + if (now <= 0L + || identity.notBeforeEpochSecond() > now + || identity.issuedAtEpochSecond() > latestIssuedAt + || identity.expiresAtEpochSecond() <= now) { + throw new StorageUnavailableException(); + } + } + + private static void requireCommittedProofIdentity( + Map proof, + AccountGameplayDelegationPendingIdentity identity, + CommittedIssuanceReadback readback, + PendingRegistryCandidate candidate, + AccountAuthEvidenceBundle bundle, + IssuerAccountSourceSnapshot current) { + Map proofIdentity = requireMap(proof.get("identity")); + requireExactFields( + proofIdentity, + Set.of( + "operationId", + "requestId", + "accountId", + "requestDigest", + "callerWorkload", + "callerContextId", + "tokenJti", + "tokenGeneration", + "issuedAtEpochSecond", + "notBeforeEpochSecond", + "expiresAtEpochSecond", + "tokenSha256")); + if (!AccountGameplayDelegationIssuanceCommitService.COMMIT_PROOF_SCHEMA.equals( + proof.get("schema")) + || !identity.operationId().toString().equals(proofIdentity.get("operationId")) + || !identity.requestId().toString().equals(proofIdentity.get("requestId")) + || !identity.accountId().toString().equals(proofIdentity.get("accountId")) + || !identity.requestDigest().equals(proofIdentity.get("requestDigest")) + || !identity.callerWorkload().equals(proofIdentity.get("callerWorkload")) + || !identity.callerContextId().toString().equals(proofIdentity.get("callerContextId")) + || !identity.tokenJti().toString().equals(proofIdentity.get("tokenJti")) + || !"1".equals(proofIdentity.get("tokenGeneration")) + || !Long.toString(identity.issuedAtEpochSecond()) + .equals(proofIdentity.get("issuedAtEpochSecond")) + || !Long.toString(identity.notBeforeEpochSecond()) + .equals(proofIdentity.get("notBeforeEpochSecond")) + || !Long.toString(identity.expiresAtEpochSecond()) + .equals(proofIdentity.get("expiresAtEpochSecond")) + || !candidate.tokenHash().equals(proofIdentity.get("tokenSha256")) + || !candidate.tokenHash().equals(proof.get("tokenSha256")) + || !sha256(candidate.canonicalRecordBytes()).equals(proof.get("registryRecordSha256")) + || !readback.operationId().equals(identity.operationId()) + || !readback.requestId().equals(identity.requestId()) + || !readback.accountId().equals(identity.accountId()) + || !readback.requestDigest().equals(identity.requestDigest()) + || !readback.tokenHash().equals(candidate.tokenHash()) + || !readback.signerKid().equals(candidate.kid()) + || !readback.signerGeneration().equals(candidate.signerGeneration())) { + throw new StorageUnavailableException(); + } + + Map registry = requireMap(proof.get("registry")); + requireExactFields( + registry, + Set.of( + "state", + "registryVersion", + "tokenKey", + "tokenHash", + "kid", + "signerGeneration", + "operationId", + "requestId", + "requestDigest", + "absoluteExpiryMillis", + "localAofCount", + "replicaAofCount", + "outcome", + "canonicalRecordSha256", + "evidenceBundleSha256", + "aclIdentity")); + long tokenExpiryMillis; + long registryExpiryMillis; + try { + tokenExpiryMillis = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + registryExpiryMillis = positiveCanonicalLong(registry.get("absoluteExpiryMillis")); + } catch (RuntimeException invalidExpiry) { + throw new StorageUnavailableException(); + } + long expiryMargin; + try { + expiryMargin = Math.subtractExact(registryExpiryMillis, tokenExpiryMillis); + } catch (ArithmeticException invalidMargin) { + throw new StorageUnavailableException(); + } + Object outcome = registry.get("outcome"); + if (!"pending".equals(registry.get("state")) + || positiveCanonicalLong(registry.get("registryVersion")) != 1L + || !AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + .concat(candidate.tokenHash()) + .equals(registry.get("tokenKey")) + || !candidate.tokenHash().equals(registry.get("tokenHash")) + || !candidate.kid().equals(registry.get("kid")) + || !candidate.signerGeneration().equals(registry.get("signerGeneration")) + || !identity.operationId().toString().equals(registry.get("operationId")) + || !identity.requestId().toString().equals(registry.get("requestId")) + || !identity.requestDigest().equals(registry.get("requestDigest")) + || expiryMargin < 0L + || expiryMargin > 300_000L + || positiveCanonicalLong(registry.get("localAofCount")) < 1L + || positiveCanonicalLong(registry.get("replicaAofCount")) < 1L + || !("CREATED".equals(outcome) || "EXACT_RETRY".equals(outcome)) + || !sha256(candidate.canonicalRecordBytes()).equals(registry.get("canonicalRecordSha256")) + || !bundle.canonicalSha256().equals(registry.get("evidenceBundleSha256")) + || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals( + registry.get("aclIdentity"))) { + throw new StorageUnavailableException(); + } + + Map bundleReference = requireMap(proof.get("bundle")); + if (!sameCanonicalMap(bundleReference, evidenceBundleReference(bundle).toMap())) { + throw new StorageUnavailableException(); + } + + Map authority = requireMap(proof.get("authority")); + requireExactFields( + authority, + Set.of( + "issuerGeneration", + "issuerSourceVersion", + "accountGeneration", + "accountSourceVersion", + "issuanceFence", + "issuanceFenceSourceVersion", + "authorityTuple", + "authoritySourceVersions", + "issuerProjectionGeneration", + "accountProjectionGeneration", + "issuerProjectionSha256", + "accountProjectionSha256")); + byte[][] projectionPair = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(current); + AccountAuthoritySnapshot snapshot = authoritySnapshot(current); + if (!Long.toString(snapshot.issuerGeneration()).equals(authority.get("issuerGeneration")) + || !Long.toString(snapshot.issuerSourceVersion()) + .equals(authority.get("issuerSourceVersion")) + || !Long.toString(snapshot.accountGeneration()).equals(authority.get("accountGeneration")) + || !Long.toString(snapshot.accountSourceVersion()) + .equals(authority.get("accountSourceVersion")) + || !Long.toString(snapshot.issuanceFence()).equals(authority.get("issuanceFence")) + || !Long.toString(snapshot.issuanceFenceSourceVersion()) + .equals(authority.get("issuanceFenceSourceVersion")) + || !sameCanonicalMap(authority.get("authorityTuple"), authorityTuple(snapshot)) + || !sameCanonicalMap(authority.get("authoritySourceVersions"), snapshot.sourceVersions()) + || !Long.toString(snapshot.issuerGeneration()) + .equals(authority.get("issuerProjectionGeneration")) + || !Long.toString(snapshot.accountGeneration()) + .equals(authority.get("accountProjectionGeneration")) + || !sha256(projectionPair[0]).equals(authority.get("issuerProjectionSha256")) + || !sha256(projectionPair[1]).equals(authority.get("accountProjectionSha256"))) { + throw new StaleAuthorityException(); + } + } + + private static AuthenticatedSignerCorrespondence requireCommittedSignerProof( + Map proof, PendingRegistryCandidate candidate) { + Map signer = requireMap(proof.get("signer")); + requireExactFields( + signer, + Set.of( + "promotionStatus", + "promotionOperationId", + "generationOperationId", + "targetKid", + "targetGeneration", + "correspondenceSha256", + "correspondence")); + Map correspondenceMap = requireMap(signer.get("correspondence")); + Set correspondenceFields = + Arrays.stream(AuthenticatedSignerCorrespondence.class.getRecordComponents()) + .map(java.lang.reflect.RecordComponent::getName) + .collect(java.util.stream.Collectors.toUnmodifiableSet()); + requireExactFields(correspondenceMap, correspondenceFields); + if (!"COMMITTED".equals(signer.get("promotionStatus")) + || !candidate.kid().equals(signer.get("targetKid")) + || !candidate.signerGeneration().equals(signer.get("targetGeneration")) + || !sha256(canonicalProofJson(correspondenceMap)) + .equals(signer.get("correspondenceSha256"))) { + throw new StorageUnavailableException(); + } + try { + byte[] bytes = JSON.writeValueAsBytes(correspondenceMap); + AuthenticatedSignerCorrespondence correspondence = + JSON.readValue(bytes, AuthenticatedSignerCorrespondence.class); + if (!correspondence + .promotionOperationId() + .toString() + .equals(signer.get("promotionOperationId")) + || !correspondence + .generationOperationId() + .toString() + .equals(signer.get("generationOperationId")) + || !"COMMITTED".equals(correspondence.promotionStatus()) + || !correspondence.privatePromotionDispatched() + || !correspondence + .promotionOperationId() + .equals(correspondence.privatePromotionOperationId()) + || !correspondence + .promotionOperationId() + .equals(correspondence.publicPromotionOperationId()) + || !correspondence + .generationOperationId() + .equals(correspondence.privatePromotionGenerationOperationId()) + || correspondence + .durableActive() + .filter( + active -> + active.generation().equals(candidate.signerGeneration()) + && active.kid().equals(candidate.kid())) + .isEmpty() + || correspondence + .publishedActive() + .filter( + active -> + active.generation().equals(candidate.signerGeneration()) + && active.kid().equals(candidate.kid())) + .isEmpty() + || correspondence + .promotionPrivateObservedResourceVersion() + .filter(correspondence.privatePromotionObservedResourceVersion()::equals) + .isEmpty() + || correspondence + .promotionPrivateReceiptDigest() + .filter(correspondence.privatePromotionReceiptDigest()::equals) + .isEmpty() + || correspondence + .activeJwksObservedResourceVersion() + .filter(correspondence.observedPublicResourceVersion()::equals) + .isEmpty() + || correspondence + .activeJwksPublicDataDigest() + .filter(correspondence.publicDataDigest()::equals) + .isEmpty() + || correspondence + .activeJwksReceiptDigest() + .filter(correspondence.publicReceiptDigest()::equals) + .isEmpty() + || !correspondence + .publicConfigMapUid() + .equals(correspondence.publicJwksSourceIdentity().configMapUid())) { + throw new StorageUnavailableException(); + } + return correspondence; + } catch (RuntimeException failure) { + throw new StorageUnavailableException(); + } + } + + private EnvelopeIdentity requireCommittedEnvelopeProof( + Map proof, + AccountGameplayDelegationPendingIdentity identity, + PendingRegistryCandidate candidate, + AccountAuthoritySnapshot authority, + AccountAuthEvidenceBundle bundle) { + Map envelopeProof = requireMap(proof.get("envelope")); + requireExactFields( + envelopeProof, + Set.of( + "operationId", + "requestId", + "tokenHash", + "kid", + "signerGeneration", + "authorityEvidenceBundleSha256", + "issuanceFence", + "responseRecoveryExpiryEpochMillis", + "envelopeSha256", + "envelopeBytesLength")); + long expectedExpiryMillis; + try { + expectedExpiryMillis = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException failure) { + throw new StorageUnavailableException(); + } + Record envelope = + dsl.fetchOne( + "SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, " + + "authority_evidence_bundle_sha256, issuance_fence, " + + "response_recovery_expiry_epoch_ms, envelope_sha256, envelope_bytes " + + "FROM account_gameplay_delegation_response_envelopes " + + "WHERE operation_id = ? FOR SHARE", + identity.operationId()); + if (envelope == null) throw new StorageUnavailableException(); + byte[] bytes = envelope.get("envelope_bytes", byte[].class); + String digest = envelope.get("envelope_sha256", String.class); + String tokenHash = envelope.get("token_hash", String.class); + String keyId = envelope.get("signer_kid", String.class); + String signerGeneration = envelope.get("signer_generation", String.class); + long expiry = positive(envelope.get("response_recovery_expiry_epoch_ms", Long.class), "expiry"); + if (bytes == null + || bytes.length == 0 + || bytes.length > 65_610 + || !SHA256.matcher(Objects.toString(digest, "")).matches() + || !digest.equals(sha256(bytes)) + || !identity.operationId().equals(envelope.get("operation_id", UUID.class)) + || !identity.requestId().equals(envelope.get("request_id", UUID.class)) + || !candidate.tokenHash().equals(tokenHash) + || !candidate.kid().equals(keyId) + || !candidate.signerGeneration().equals(signerGeneration) + || !bundle + .canonicalSha256() + .equals(envelope.get("authority_evidence_bundle_sha256", String.class)) + || authority.issuanceFence() + != positive(envelope.get("issuance_fence", Long.class), "issuance fence") + || expiry != expectedExpiryMillis + || !identity.operationId().toString().equals(envelopeProof.get("operationId")) + || !identity.requestId().toString().equals(envelopeProof.get("requestId")) + || !candidate.tokenHash().equals(envelopeProof.get("tokenHash")) + || !candidate.kid().equals(envelopeProof.get("kid")) + || !candidate.signerGeneration().equals(envelopeProof.get("signerGeneration")) + || !bundle.canonicalSha256().equals(envelopeProof.get("authorityEvidenceBundleSha256")) + || !Long.toString(authority.issuanceFence()).equals(envelopeProof.get("issuanceFence")) + || !Long.toString(expiry).equals(envelopeProof.get("responseRecoveryExpiryEpochMillis")) + || !digest.equals(envelopeProof.get("envelopeSha256")) + || !Integer.toString(bytes.length).equals(envelopeProof.get("envelopeBytesLength"))) { + throw new StorageUnavailableException(); + } + EnvelopeHeader header = parseEnvelopeHeader(bytes, expiry); + return new EnvelopeIdentity(digest, bytes.length, expiry, header.keyId()); + } + + private static long positiveCanonicalLong(Object value) { + if (!(value instanceof String text) || !POSITIVE_DECIMAL.matcher(text).matches()) { + throw new StorageUnavailableException(); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException invalid) { + throw new StorageUnavailableException(); + } + } + + private static EnvelopeHeader parseEnvelopeHeader(byte[] bytes, long expectedExpiryMillis) { + final byte[] magic = {'F', 'R', 'E', 'A'}; + final int minimumLength = 4 + 1 + 1 + 1 + Long.BYTES + 12 + 16 + 1; + if (bytes.length < minimumLength + || bytes.length > 65_610 + || bytes[0] != magic[0] + || bytes[1] != magic[1] + || bytes[2] != magic[2] + || bytes[3] != magic[3] + || bytes[4] != 1) { + throw new StorageUnavailableException(); + } + int keyLength = Byte.toUnsignedInt(bytes[5]); + if (keyLength < 1 + || keyLength > 32 + || bytes.length < 6 + keyLength + Long.BYTES + 12 + 16 + 1) { + throw new StorageUnavailableException(); + } + String keyId = new String(bytes, 6, keyLength, StandardCharsets.US_ASCII); + if (!keyId.matches("[A-Za-z0-9_-]{1,32}")) throw new StorageUnavailableException(); + long expiry = ByteBuffer.wrap(bytes, 6 + keyLength, Long.BYTES).getLong(); + if (expiry <= 0L || expiry != expectedExpiryMillis) throw new StorageUnavailableException(); + return new EnvelopeHeader(keyId); + } + + private static boolean sameCanonicalMap(Object actual, Object expected) { + try { + return Arrays.equals(canonicalJson(actual), canonicalJson(expected)); + } catch (RuntimeException failure) { + return false; + } + } + + private static void requireExactFields(Map value, Set fields) { + if (!value.keySet().equals(fields)) throw new StorageUnavailableException(); + } + + /** + * Persists signer-verified, exact pinned-Redis registration and source-projection evidence as one + * immutable non-authorizing PENDING-to-COMMITTED transition. Network work is supplied only as + * private-constructor owner receipts and is complete before this Account transaction begins. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CommittedIssuanceReadback commitPendingCandidate( + UUID requestId, + AccountGameplayDelegationSigner.PendingCandidateVerificationProof signerProof, + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt redisReceipt, + ProjectionObservation projectionObservation, + AccountGameplayDelegationIssuanceCommitService.CommitProof commitProof) { + requireWritableAccountTransaction(); + Objects.requireNonNull(requestId, "Request ID is required"); + Objects.requireNonNull(signerProof, "Signer-owned candidate proof is required"); + Objects.requireNonNull(redisReceipt, "Pinned pending registration receipt is required"); + Objects.requireNonNull(projectionObservation, "Current Account projection is required"); + Objects.requireNonNull(commitProof, "Canonical Account commit proof is required"); + + PendingRegistryCandidate candidate = readPendingRegistryCandidate(requestId); + AccountGameplayDelegationPendingIdentity identity = candidate.identity(); + if (!identity.operationId().equals(signerProof.operationId()) + || !requestId.equals(signerProof.requestId()) + || !identity.accountId().equals(signerProof.accountId()) + || !identity.requestDigest().equals(signerProof.identity().requestDigest()) + || !identity.callerWorkload().equals(signerProof.identity().callerWorkload()) + || !identity.callerContextId().equals(signerProof.identity().callerContextId()) + || !identity.tokenJti().equals(signerProof.tokenJti()) + || identity.issuedAtEpochSecond() != signerProof.issuedAtEpochSecond() + || identity.notBeforeEpochSecond() != signerProof.notBeforeEpochSecond() + || identity.expiresAtEpochSecond() != signerProof.expiresAtEpochSecond() + || !candidate.tokenHash().equals(signerProof.tokenSha256()) + || !candidate.kid().equals(signerProof.signerKid()) + || !candidate.signerGeneration().equals(signerProof.signerGeneration()) + || candidate.authoritySnapshot().issuanceFence() != signerProof.issuanceFence() + || !candidate.authoritySnapshot().equals(signerProof.authoritySnapshot()) + || !candidate.evidenceBundleReference().equals(signerProof.evidenceBundleReference()) + || !sha256(candidate.canonicalRecordBytes()) + .equals(signerProof.canonicalRegistryRecordSha256()) + || !commitProof.operationId().equals(identity.operationId()) + || !commitProof.requestId().equals(requestId) + || !commitProof.accountId().equals(identity.accountId()) + || !commitProof.requestDigest().equals(identity.requestDigest()) + || !commitProof.tokenSha256().equals(candidate.tokenHash())) { + throw new IdempotencyConflictException(); + } + + IssuerAccountSourceSnapshot current = readCurrentAuthority(identity.accountId()); + AccountAuthoritySnapshot currentAuthority = authoritySnapshot(current); + if (!currentAuthority.equals(candidate.authoritySnapshot()) + || !currentAuthority.equals(signerProof.authoritySnapshot())) { + throw new StaleAuthorityException(); + } + requireExactProjectionObservation(projectionObservation, current); + requireExactRedisReceipt(redisReceipt, candidate); + requireExactSealedEnvelope(signerProof.sealedCandidate(), candidate); + requireCanonicalCommitProof(commitProof, signerProof, redisReceipt, projectionObservation); + + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'COMMITTED', commit_proof_version = 1, commit_proof_sha256 = ?, " + + "commit_proof_canonical_bytes = ?, committed_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND status = 'PENDING' AND token_hash = ? " + + "AND signer_kid = ? AND signer_generation = ? " + + "AND pending_registry_candidate_bytes = ?", + commitProof.sha256(), + commitProof.canonicalBytes(), + requestId, + candidate.tokenHash(), + candidate.kid(), + candidate.signerGeneration(), + candidate.canonicalRecordBytes()); + if (changed != 1) throw new StaleAuthorityException(); + + Record readback = selectByRequestId(requestId, true); + CommittedIssuanceReadback exact = + decodeCommittedReadback(readback, commitProof.sha256(), commitProof.canonicalBytes()); + requireStoredAuthority(readback, current); + tokenIdentityFences.registerCommittedIssuance(tokenIdentity(readback)); + return exact; + } + + /** + * Reads only the immutable non-authorizing COMMITTED result. A prior exact commit replay never + * invokes the signer, extends Redis TTL, or returns/decrypts the encrypted response envelope. + */ + @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true) + public java.util.Optional readCommittedProof(UUID requestId) { + Objects.requireNonNull(requestId, "Request ID is required"); + Record row = selectByRequestId(requestId, false); + if (row == null) throw new StorageUnavailableException(); + String status = row.get("status", String.class); + if ("PENDING".equals(status)) return java.util.Optional.empty(); + if (!"COMMITTED".equals(status)) throw new StorageUnavailableException(); + String proofSha = row.get("commit_proof_sha256", String.class); + byte[] proofBytes = row.get("commit_proof_canonical_bytes", byte[].class); + CommittedIssuanceReadback exact = decodeCommittedReadback(row, proofSha, proofBytes); + tokenIdentityFences.requireActiveReadback(tokenIdentity(row)); + return java.util.Optional.of(exact); + } + + private static void requireExactProjectionObservation( + ProjectionObservation observation, IssuerAccountSourceSnapshot current) { + byte[][] expected = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(current); + var issuer = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + expected[0], "issuer", GameSessionAccountDelegationProfile.ISSUER); + var account = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + expected[1], "account", current.account().scope().accountId().toString()); + if (!issuer.digest().equals(observation.issuerDigest()) + || !account.digest().equals(observation.accountDigest()) + || issuer.generation() != observation.issuerGeneration() + || !account + .generationValue() + .equals(java.math.BigInteger.valueOf(observation.accountGeneration())) + || !current.issuanceFence().equals(current.account().issuanceFence())) { + throw new StaleAuthorityException(); + } + } + + private static void requireExactRedisReceipt( + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt receipt, + PendingRegistryCandidate candidate) { + AccountGameplayDelegationPendingIdentity identity = candidate.identity(); + long tokenExpiry; + try { + tokenExpiry = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + long margin = Math.subtractExact(receipt.absoluteExpiryMillis(), tokenExpiry); + if (margin < 0L || margin > 300_000L) throw new StorageUnavailableException(); + } catch (ArithmeticException ex) { + throw new StorageUnavailableException(); + } + if (!receipt + .tokenKey() + .equals(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + candidate.tokenHash()) + || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals(receipt.aclIdentity()) + || !receipt.canonicalRecordSha256().equals(sha256(candidate.canonicalRecordBytes())) + || !receipt.operationId().equals(identity.operationId().toString()) + || !receipt.requestId().equals(identity.requestId().toString()) + || !receipt.requestDigest().equals(identity.requestDigest()) + || !receipt.accountId().equals(identity.accountId().toString()) + || !receipt.tokenJti().equals(identity.tokenJti().toString()) + || !receipt.tokenHash().equals(candidate.tokenHash()) + || !receipt.kid().equals(candidate.kid()) + || !receipt.signerGeneration().equals(candidate.signerGeneration()) + || receipt.issuedAtEpochSecond() != identity.issuedAtEpochSecond() + || receipt.notBeforeEpochSecond() != identity.notBeforeEpochSecond() + || receipt.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || receipt.issuanceFence() != candidate.authoritySnapshot().issuanceFence() + || receipt.registryVersion() != 1L + || !receipt.evidenceBundleReference().equals(candidate.evidenceBundleReference()) + || receipt.localAofCount() < 1L + || receipt.replicaAofCount() < 1L) { + throw new StorageUnavailableException(); + } + } + + private void requireExactSealedEnvelope( + AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation sealed, + PendingRegistryCandidate candidate) { + Record envelope = + dsl.fetchOne( + "SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, " + + "authority_evidence_bundle_sha256, issuance_fence, " + + "response_recovery_expiry_epoch_ms, envelope_sha256, " + + "octet_length(envelope_bytes) AS envelope_bytes_length " + + "FROM account_gameplay_delegation_response_envelopes " + + "WHERE operation_id = ? FOR SHARE", + candidate.identity().operationId()); + if (envelope == null + || !Objects.equals(envelope.get("operation_id", UUID.class), sealed.operationId()) + || !Objects.equals(envelope.get("request_id", UUID.class), sealed.requestId()) + || !Objects.equals(envelope.get("token_hash", String.class), candidate.tokenHash()) + || !Objects.equals(envelope.get("signer_kid", String.class), candidate.kid()) + || !Objects.equals( + envelope.get("signer_generation", String.class), candidate.signerGeneration()) + || !Objects.equals( + envelope.get("authority_evidence_bundle_sha256", String.class), + sealed.authorityEvidenceBundleSha256()) + || !Objects.equals(envelope.get("issuance_fence", Long.class), sealed.issuanceFence()) + || !Objects.equals( + envelope.get("response_recovery_expiry_epoch_ms", Long.class), + sealed.responseRecoveryExpiryEpochMillis()) + || !Objects.equals(envelope.get("envelope_sha256", String.class), sealed.envelopeSha256()) + || !Objects.equals( + envelope.get("envelope_bytes_length", Integer.class), sealed.envelopeBytesLength())) { + throw new StorageUnavailableException(); + } + } + + private static void requireCanonicalCommitProof( + AccountGameplayDelegationIssuanceCommitService.CommitProof commitProof, + AccountGameplayDelegationSigner.PendingCandidateVerificationProof signerProof, + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt redisReceipt, + ProjectionObservation projectionObservation) { + byte[] bytes = commitProof.canonicalBytes(); + if (bytes.length == 0 + || bytes.length > MAX_COMMIT_PROOF_BYTES + || !sha256(bytes).equals(commitProof.sha256()) + || !commitProof.operationId().equals(signerProof.operationId()) + || !commitProof.requestId().equals(signerProof.requestId()) + || !commitProof.accountId().equals(signerProof.accountId()) + || !commitProof.requestDigest().equals(signerProof.identity().requestDigest()) + || !commitProof.tokenSha256().equals(redisReceipt.tokenHash())) { + throw new StorageUnavailableException(); + } + Map proof = parseCommitProof(bytes); + Object identityValue = proof.get("identity"); + Object registryValue = proof.get("registry"); + Object bundleValue = proof.get("bundle"); + Object authorityValue = proof.get("authority"); + Object signerValue = proof.get("signer"); + Object envelopeValue = proof.get("envelope"); + var identity = requireMap(identityValue); + var registry = requireMap(registryValue); + var bundle = requireMap(bundleValue); + var authority = requireMap(authorityValue); + var signer = requireMap(signerValue); + var envelope = requireMap(envelopeValue); + var correspondence = requireMap(signer.get("correspondence")); + var pending = signerProof.identity(); + var snapshot = signerProof.authoritySnapshot(); + var bundleReference = signerProof.evidenceBundleReference(); + var sealed = signerProof.sealedCandidate(); + long expectedExpiryMillis; + try { + expectedExpiryMillis = Math.multiplyExact(pending.expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException ex) { + throw new StorageUnavailableException(); + } + if (!identity + .keySet() + .equals( + Set.of( + "operationId", + "requestId", + "accountId", + "requestDigest", + "callerWorkload", + "callerContextId", + "tokenJti", + "tokenGeneration", + "issuedAtEpochSecond", + "notBeforeEpochSecond", + "expiresAtEpochSecond", + "tokenSha256")) + || !registry + .keySet() + .equals( + Set.of( + "state", + "registryVersion", + "tokenKey", + "tokenHash", + "kid", + "signerGeneration", + "operationId", + "requestId", + "requestDigest", + "absoluteExpiryMillis", + "localAofCount", + "replicaAofCount", + "outcome", + "canonicalRecordSha256", + "evidenceBundleSha256", + "aclIdentity")) + || !bundle + .keySet() + .equals( + Set.of( + "bundleVersion", + "sourceVersion", + "sourceFence", + "linearization", + "canonicalSha256")) + || !authority + .keySet() + .equals( + Set.of( + "issuerGeneration", + "issuerSourceVersion", + "accountGeneration", + "accountSourceVersion", + "issuanceFence", + "issuanceFenceSourceVersion", + "authorityTuple", + "authoritySourceVersions", + "issuerProjectionGeneration", + "accountProjectionGeneration", + "issuerProjectionSha256", + "accountProjectionSha256")) + || !signer + .keySet() + .equals( + Set.of( + "promotionStatus", + "promotionOperationId", + "generationOperationId", + "targetKid", + "targetGeneration", + "correspondenceSha256", + "correspondence")) + || !envelope + .keySet() + .equals( + Set.of( + "operationId", + "requestId", + "tokenHash", + "kid", + "signerGeneration", + "authorityEvidenceBundleSha256", + "issuanceFence", + "responseRecoveryExpiryEpochMillis", + "envelopeSha256", + "envelopeBytesLength")) + || !AccountGameplayDelegationIssuanceCommitService.COMMIT_PROOF_SCHEMA.equals( + proof.get("schema")) + || !pending.operationId().toString().equals(identity.get("operationId")) + || !pending.requestId().toString().equals(identity.get("requestId")) + || !pending.accountId().toString().equals(identity.get("accountId")) + || !pending.requestDigest().equals(identity.get("requestDigest")) + || !pending.callerWorkload().equals(identity.get("callerWorkload")) + || !pending.callerContextId().toString().equals(identity.get("callerContextId")) + || !pending.tokenJti().toString().equals(identity.get("tokenJti")) + || !"1".equals(identity.get("tokenGeneration")) + || !Long.toString(pending.issuedAtEpochSecond()).equals(identity.get("issuedAtEpochSecond")) + || !Long.toString(pending.notBeforeEpochSecond()) + .equals(identity.get("notBeforeEpochSecond")) + || !Long.toString(pending.expiresAtEpochSecond()) + .equals(identity.get("expiresAtEpochSecond")) + || !signerProof.tokenSha256().equals(identity.get("tokenSha256")) + || !signerProof.tokenSha256().equals(proof.get("tokenSha256")) + || !redisReceipt.canonicalRecordSha256().equals(proof.get("registryRecordSha256")) + || !"pending".equals(registry.get("state")) + || !"1".equals(registry.get("registryVersion")) + || !redisReceipt.tokenKey().equals(registry.get("tokenKey")) + || !redisReceipt.tokenHash().equals(registry.get("tokenHash")) + || !redisReceipt.kid().equals(registry.get("kid")) + || !redisReceipt.signerGeneration().equals(registry.get("signerGeneration")) + || !redisReceipt.operationId().equals(registry.get("operationId")) + || !redisReceipt.requestId().equals(registry.get("requestId")) + || !redisReceipt.requestDigest().equals(registry.get("requestDigest")) + || !Long.toString(redisReceipt.absoluteExpiryMillis()) + .equals(registry.get("absoluteExpiryMillis")) + || !Long.toString(redisReceipt.localAofCount()).equals(registry.get("localAofCount")) + || !Long.toString(redisReceipt.replicaAofCount()).equals(registry.get("replicaAofCount")) + || !redisReceipt.outcome().name().equals(registry.get("outcome")) + || !redisReceipt.canonicalRecordSha256().equals(registry.get("canonicalRecordSha256")) + || !bundleReference.canonicalSha256().equals(registry.get("evidenceBundleSha256")) + || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals( + registry.get("aclIdentity")) + || !bundleReference.toMap().equals(bundle) + || !Long.toString(snapshot.issuerGeneration()).equals(authority.get("issuerGeneration")) + || !Long.toString(snapshot.issuerSourceVersion()) + .equals(authority.get("issuerSourceVersion")) + || !Long.toString(snapshot.accountGeneration()).equals(authority.get("accountGeneration")) + || !Long.toString(snapshot.accountSourceVersion()) + .equals(authority.get("accountSourceVersion")) + || !Long.toString(snapshot.issuanceFence()).equals(authority.get("issuanceFence")) + || !Long.toString(snapshot.issuanceFenceSourceVersion()) + .equals(authority.get("issuanceFenceSourceVersion")) + || !Arrays.equals( + canonicalJson(authorityTuple(snapshot)), canonicalJson(authority.get("authorityTuple"))) + || !Arrays.equals( + canonicalJson(snapshot.sourceVersions()), + canonicalJson(authority.get("authoritySourceVersions"))) + || !Long.toString(projectionObservation.issuerGeneration()) + .equals(authority.get("issuerProjectionGeneration")) + || !Long.toString(projectionObservation.accountGeneration()) + .equals(authority.get("accountProjectionGeneration")) + || !projectionObservation.issuerDigest().equals(authority.get("issuerProjectionSha256")) + || !projectionObservation.accountDigest().equals(authority.get("accountProjectionSha256")) + || !"COMMITTED".equals(signer.get("promotionStatus")) + || !signerProof + .signerCorrespondence() + .promotionOperationId() + .toString() + .equals(signer.get("promotionOperationId")) + || !signerProof + .signerCorrespondence() + .generationOperationId() + .toString() + .equals(signer.get("generationOperationId")) + || !signerProof.signerKid().equals(signer.get("targetKid")) + || !signerProof.signerGeneration().equals(signer.get("targetGeneration")) + || !SHA256.matcher(Objects.toString(signer.get("correspondenceSha256"), "")).matches() + || !sha256(canonicalJson(correspondence)).equals(signer.get("correspondenceSha256")) + || !pending.operationId().toString().equals(envelope.get("operationId")) + || !pending.requestId().toString().equals(envelope.get("requestId")) + || !signerProof.tokenSha256().equals(envelope.get("tokenHash")) + || !signerProof.signerKid().equals(envelope.get("kid")) + || !signerProof.signerGeneration().equals(envelope.get("signerGeneration")) + || !bundleReference.canonicalSha256().equals(envelope.get("authorityEvidenceBundleSha256")) + || !Long.toString(signerProof.issuanceFence()).equals(envelope.get("issuanceFence")) + || !Long.toString(sealed.responseRecoveryExpiryEpochMillis()) + .equals(envelope.get("responseRecoveryExpiryEpochMillis")) + || !sealed.envelopeSha256().equals(envelope.get("envelopeSha256")) + || !Integer.toString(sealed.envelopeBytesLength()) + .equals(envelope.get("envelopeBytesLength")) + || redisReceipt.absoluteExpiryMillis() < expectedExpiryMillis + || redisReceipt.absoluteExpiryMillis() - expectedExpiryMillis > 300_000L + || redisReceipt.localAofCount() < 1L + || redisReceipt.replicaAofCount() < 1L + || !redisReceipt.outcome().name().equals(registry.get("outcome")) + || !redisReceipt.canonicalRecordSha256().equals(registry.get("canonicalRecordSha256"))) { + throw new StorageUnavailableException(); + } + } + + private static Map requireMap(Object value) { + if (!(value instanceof Map map)) throw new StorageUnavailableException(); + return map; + } + + private CommittedIssuanceReadback decodeCommittedReadback( + Record row, String expectedSha256, byte[] expectedBytes) { + Object storedVersion = row == null ? null : row.get("commit_proof_version"); + if (row == null + || !"COMMITTED".equals(row.get("status", String.class)) + || !(storedVersion instanceof Number version) + || version.intValue() != 1 + || row.get("committed_at") == null) { + throw new StorageUnavailableException(); + } + String storedSha = row.get("commit_proof_sha256", String.class); + byte[] storedBytes = row.get("commit_proof_canonical_bytes", byte[].class); + if (storedSha == null + || !SHA256.matcher(storedSha).matches() + || storedBytes == null + || storedBytes.length == 0 + || storedBytes.length > MAX_COMMIT_PROOF_BYTES + || !storedSha.equals(sha256(storedBytes)) + || (expectedSha256 != null && !expectedSha256.equals(storedSha)) + || (expectedBytes != null && !Arrays.equals(expectedBytes, storedBytes))) { + throw new StorageUnavailableException(); + } + Map proof = parseCommitProof(storedBytes); + AccountGameplayDelegationPendingIdentity identity = identity(row); + Object proofIdentity = proof.get("identity"); + if (!(proofIdentity instanceof Map fields) + || !fields + .keySet() + .equals( + Set.of( + "operationId", + "requestId", + "accountId", + "requestDigest", + "callerWorkload", + "callerContextId", + "tokenJti", + "tokenGeneration", + "issuedAtEpochSecond", + "notBeforeEpochSecond", + "expiresAtEpochSecond", + "tokenSha256")) + || !AccountGameplayDelegationIssuanceCommitService.COMMIT_PROOF_SCHEMA.equals( + proof.get("schema")) + || !identity.operationId().toString().equals(fields.get("operationId")) + || !identity.requestId().toString().equals(fields.get("requestId")) + || !identity.accountId().toString().equals(fields.get("accountId")) + || !identity.requestDigest().equals(fields.get("requestDigest")) + || !identity.tokenJti().toString().equals(fields.get("tokenJti")) + || !"1".equals(fields.get("tokenGeneration")) + || !Long.toString(identity.issuedAtEpochSecond()).equals(fields.get("issuedAtEpochSecond")) + || !Long.toString(identity.notBeforeEpochSecond()) + .equals(fields.get("notBeforeEpochSecond")) + || !Long.toString(identity.expiresAtEpochSecond()) + .equals(fields.get("expiresAtEpochSecond")) + || !identity.callerWorkload().equals(fields.get("callerWorkload")) + || !identity.callerContextId().toString().equals(fields.get("callerContextId")) + || !Objects.equals(row.get("token_hash", String.class), fields.get("tokenSha256")) + || !identity.tokenJti().toString().equals(row.get("token_jti", UUID.class).toString()) + || !Objects.equals(row.get("token_hash", String.class), proof.get("tokenSha256"))) { + throw new StorageUnavailableException(); + } + return new CommittedIssuanceReadback( + identity.operationId(), + identity.requestId(), + identity.accountId(), + identity.requestDigest(), + row.get("token_hash", String.class), + row.get("signer_kid", String.class), + row.get("signer_generation", String.class), + storedSha); + } + + private static Map parseCommitProof(byte[] bytes) { + try { + Map parsed = JSON.readValue(bytes, new TypeReference<>() {}); + if (!parsed + .keySet() + .equals( + Set.of( + "schema", + "identity", + "tokenSha256", + "registryRecordSha256", + "registry", + "bundle", + "authority", + "signer", + "envelope")) + || !Arrays.equals(bytes, canonicalProofJson(parsed))) { + throw new StorageUnavailableException(); + } + return parsed; + } catch (RuntimeException ex) { + if (ex instanceof StorageUnavailableException unavailable) throw unavailable; + throw new StorageUnavailableException(); + } + } + + private static byte[] canonicalProofJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException ex) { + throw new StorageUnavailableException(); + } + } + + /** Versioned request digest over the immutable pre-sign operation and locked authority tuple. */ + public static String requestDigest(PendingIntent intent) { + Objects.requireNonNull(intent, "Intent is required"); + Map value = + Map.ofEntries( + Map.entry("schema", "account-game-session-delegation-issuance/v2"), + Map.entry("operationId", intent.operationId().toString()), + Map.entry("requestId", intent.requestId().toString()), + Map.entry("accountId", intent.authoritySnapshot().accountId().toString()), + Map.entry("callerWorkload", intent.callerWorkload()), + Map.entry("callerContextId", intent.callerContextId().toString()), + Map.entry( + "credentialRequestBinding", + Map.of( + "digestSchemaVersion", + intent.credentialRequestBinding().digestSchemaVersion(), + "digestKeyId", + intent.credentialRequestBinding().digestKeyId(), + "credentialRequestDigest", + intent.credentialRequestBinding().credentialRequestDigest())), + Map.entry("jti", intent.tokenJti().toString()), + Map.entry("iat", intent.issuedAtEpochSecond()), + Map.entry("nbf", intent.notBeforeEpochSecond()), + Map.entry("exp", intent.expiresAtEpochSecond()), + Map.entry("authorityTuple", authorityTuple(intent.authoritySnapshot())), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", Long.toString(intent.authoritySnapshot().issuanceFence())), + Map.entry("authoritySourceVersions", intent.authoritySnapshot().sourceVersions())); + return sha256(canonicalJson(value)); + } + + private void insertIntent( + PendingIntent intent, String digest, IssuerAccountSourceSnapshot current) { + AccountAuthoritySnapshot authority = authoritySnapshot(current); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (operation_id, request_id, account_uuid, caller_workload, caller_context_id, " + + "request_digest_version, request_digest, credential_request_digest_version, " + + "credential_digest_key_id, credential_request_digest, token_jti, token_generation, " + + "issued_at_epoch_second, not_before_epoch_second, expires_at_epoch_second, " + + "authority_issuer_generation, authority_issuer_source_version, " + + "authority_account_generation, authority_account_source_version, issuance_fence, " + + "issuance_fence_source_version, authority_tuple_canonical_bytes, " + + "membership_version_canonical_bytes, authority_source_versions_canonical_bytes) " + + "VALUES (?, ?, ?, ?, ?, 2, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (request_id) DO NOTHING", + intent.operationId(), + intent.requestId(), + authority.accountId(), + intent.callerWorkload(), + intent.callerContextId(), + digest, + intent.credentialRequestBinding().digestSchemaVersion(), + intent.credentialRequestBinding().digestKeyId(), + intent.credentialRequestBinding().credentialRequestDigest(), + intent.tokenJti(), + intent.issuedAtEpochSecond(), + intent.notBeforeEpochSecond(), + intent.expiresAtEpochSecond(), + authority.issuerGeneration(), + authority.issuerSourceVersion(), + authority.accountGeneration(), + authority.accountSourceVersion(), + authority.issuanceFence(), + authority.issuanceFenceSourceVersion(), + canonicalJson(authorityTuple(authority)), + EMPTY_OBJECT, + canonicalJson(authority.sourceVersions())); + if (inserted < 0 || inserted > 1) throw new StorageUnavailableException(); + } + + private Record selectByRequestId(UUID requestId, boolean lock) { + return dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE request_id = ?" + (lock ? " FOR UPDATE" : ""), + requestId); + } + + private void lockRequestId(UUID requestId) { + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + "account-gameplay-delegation-request/" + requestId); + } + + private static void requireRequestId(UUID value) { + Objects.requireNonNull(value, "Non-nil high-entropy UUID is required"); + if (value.equals(new UUID(0L, 0L)) || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Non-nil high-entropy UUID is required"); + } + } + + private static boolean isReplayableGameplayLoginStatus(String status) { + return "PENDING".equals(status) || "COMMITTED".equals(status); + } + + private IssuerAccountSourceSnapshot readAndCompareAuthority(PendingIntent intent) { + IssuerAccountSourceSnapshot current = + readCurrentAuthority(intent.authoritySnapshot().accountId()); + AccountAuthoritySnapshot expected = intent.authoritySnapshot(); + if (!authoritySnapshot(current).equals(expected)) throw new StaleAuthorityException(); + return current; + } + + private IssuerAccountSourceSnapshot readCurrentAuthority(UUID accountId) { + tokenIdentityFences.lockAccountForUpdate(accountId); + IssuerAccountSourceSnapshot snapshot = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId); + if (snapshot.issuer().scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ISSUER + || !GameSessionAccountDelegationProfile.ISSUER.equals(snapshot.issuer().scope().issuerId()) + || snapshot.issuer().scope().accountId() != null + || snapshot.issuer().scope().tenantId() != null + || snapshot.account().scope().kind() + != AccountAuthorityGenerationRepository.ScopeKind.ACCOUNT + || !accountId.equals(snapshot.account().scope().accountId()) + || snapshot.account().scope().issuerId() != null + || snapshot.account().scope().tenantId() != null + || !accountId.equals(snapshot.issuanceFence().accountId()) + || !Objects.equals(snapshot.account().issuanceFence(), snapshot.issuanceFence())) { + throw new IllegalStateException("Exact non-tenant Account authority snapshot is required"); + } + return snapshot; + } + + private static TokenIdentity tokenIdentity(Record row) { + return new TokenIdentity( + row.get("account_uuid", UUID.class), row.get("operation_id", UUID.class), + row.get("request_id", UUID.class), row.get("token_hash", String.class), + row.get("token_jti", UUID.class), row.get("not_before_epoch_second", Long.class), + row.get("token_generation", Long.class), row.get("issuance_fence", Long.class)); + } + + private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSnapshot snapshot) { + AccountSecurityCutoff cutoff = + snapshot + .account() + .accountSecurityCutoff() + .map( + value -> + new AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())) + .orElse(null); + return new AccountAuthoritySnapshot( + snapshot.account().scope().accountId(), + snapshot.issuer().generation(), + snapshot.issuer().sourceVersion(), + snapshot.account().generation(), + snapshot.account().sourceVersion(), + snapshot.issuanceFence().value(), + snapshot.issuanceFence().sourceVersion(), + java.util.Optional.ofNullable(cutoff)); + } + + private static Map authorityTuple(AccountAuthoritySnapshot snapshot) { + return GameSessionAccountDelegationProfile.authorityTuple( + snapshot.issuerGeneration(), + snapshot.accountGeneration(), + snapshot.accountSecurityCutoff()); + } + + private static Map sourceVersionsMap(IssuerAccountSourceSnapshot snapshot) { + return authoritySnapshot(snapshot).sourceVersions(); + } + + private static void requireExactIntent( + Record row, PendingIntent intent, String digest, IssuerAccountSourceSnapshot current) { + AccountGameplayDelegationPendingIdentity identity = identity(row); + if (!identity.operationId().equals(intent.operationId()) + || !identity.requestId().equals(intent.requestId()) + || !identity.accountId().equals(intent.authoritySnapshot().accountId()) + || !identity.callerWorkload().equals(intent.callerWorkload()) + || !identity.callerContextId().equals(intent.callerContextId()) + || !identity.credentialRequestBinding().equals(intent.credentialRequestBinding()) + || !identity.tokenJti().equals(intent.tokenJti()) + || identity.issuedAtEpochSecond() != intent.issuedAtEpochSecond() + || identity.notBeforeEpochSecond() != intent.notBeforeEpochSecond() + || identity.expiresAtEpochSecond() != intent.expiresAtEpochSecond() + || !identity.requestDigest().equals(digest)) { + throw new IdempotencyConflictException(); + } + requireStoredAuthority(row, current); + if (!"PENDING".equals(row.get("status", String.class))) { + throw new StorageUnavailableException(); + } + } + + private static void requireStoredAuthority(Record row, IssuerAccountSourceSnapshot current) { + AccountAuthoritySnapshot authority = authoritySnapshot(current); + if (!Objects.equals( + row.get("authority_issuer_generation", Long.class), authority.issuerGeneration()) + || !Objects.equals( + row.get("authority_issuer_source_version", Long.class), authority.issuerSourceVersion()) + || !Objects.equals( + row.get("authority_account_generation", Long.class), authority.accountGeneration()) + || !Objects.equals( + row.get("authority_account_source_version", Long.class), + authority.accountSourceVersion()) + || !Objects.equals(row.get("issuance_fence", Long.class), authority.issuanceFence()) + || !Objects.equals( + row.get("issuance_fence_source_version", Long.class), + authority.issuanceFenceSourceVersion()) + || !Arrays.equals( + row.get("authority_tuple_canonical_bytes", byte[].class), + canonicalJson(authorityTuple(authority))) + || !Arrays.equals(row.get("membership_version_canonical_bytes", byte[].class), EMPTY_OBJECT) + || !Arrays.equals( + row.get("authority_source_versions_canonical_bytes", byte[].class), + canonicalJson(authority.sourceVersions()))) { + throw new StaleAuthorityException(); + } + } + + private static void requireExactSigningBundle( + AccountAuthEvidenceBundle bundle, + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authority, + IssuerAccountSourceSnapshot current) { + try { + Map fields = bundle.fields(); + if (!AccountAuthEvidenceBundle.SCHEMA.equals(fields.get("schema")) + || !GameSessionAccountDelegationProfile.ISSUER.equals(fields.get("issuer")) + || !GameSessionAccountDelegationProfile.PROFILE.equals(fields.get("profile")) + || !GameSessionAccountDelegationProfile.AUDIENCE.equals(fields.get("audience"))) { + throw new PendingCandidateUnavailableException(); + } + requireCanonicalSubtree( + fields.get("scope"), + Map.of( + "kind", + "account", + "accountId", + identity.accountId().toString(), + "tenantIds", + java.util.List.of())); + requireCanonicalSubtree( + fields.get("operation"), + Map.of( + "operationId", identity.operationId().toString(), + "requestId", identity.requestId().toString(), + "requestDigest", identity.requestDigest(), + "callerWorkload", identity.callerWorkload(), + "callerContextId", identity.callerContextId().toString(), + "accountId", identity.accountId().toString())); + requireCanonicalSubtree( + fields.get("tokenIdentity"), + Map.of( + "jti", identity.tokenJti().toString(), + "tokenGeneration", "1", + "iat", identity.issuedAtEpochSecond(), + "nbf", identity.notBeforeEpochSecond(), + "exp", identity.expiresAtEpochSecond())); + requireCanonicalSubtree(fields.get("authorityTuple"), authorityTuple(authority)); + requireCanonicalSubtree(fields.get("membershipVersion"), Map.of()); + Object issuanceFence = fields.get("issuanceFence"); + if (!(issuanceFence instanceof String fence) + || !Long.toString(authority.issuanceFence()).equals(fence)) { + throw new PendingCandidateUnavailableException(); + } + requireCanonicalSubtree(fields.get("authoritySourceVersions"), sourceVersionStrings(current)); + requireCanonicalSubtree(fields.get("accountIdentitySource"), accountIdentitySource(current)); + requireCanonicalSubtree(fields.get("outboxCheckpoints"), outboxCheckpoints(current)); + } catch (RuntimeException ex) { + if (ex instanceof PendingCandidateUnavailableException unavailable) throw unavailable; + throw new PendingCandidateUnavailableException(); + } + } + + private AccountAuthEvidenceBundle requireCurrentEvidenceBundle( + UUID requestId, + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authority, + IssuerAccountSourceSnapshot current) { + if (evidenceBundles == null) throw new PendingCandidateUnavailableException(); + AccountAuthEvidenceBundle captured; + AccountAuthEvidenceBundle stored; + try { + captured = evidenceBundles.captureAndPersist(requestId); + stored = evidenceBundles.readStoredNonAuthorizingValue(identity.operationId()); + } catch (RuntimeException ex) { + throw new PendingCandidateUnavailableException(); + } + if (!MessageDigest.isEqual(captured.canonicalBytes(), stored.canonicalBytes())) { + throw new PendingCandidateUnavailableException(); + } + requireExactSigningBundle(stored, identity, authority, current); + return stored; + } + + private static EvidenceBundleReference evidenceBundleReference(AccountAuthEvidenceBundle bundle) { + Object value = bundle.fields().get("bundleRef"); + if (!(value instanceof Map reference)) { + throw new PendingCandidateUnavailableException(); + } + Object bundleVersion = reference.get("bundleVersion"); + Object sourceVersion = reference.get("sourceVersion"); + Object sourceFence = reference.get("sourceFence"); + Object linearization = reference.get("linearization"); + if (!(bundleVersion instanceof String version) + || !(sourceVersion instanceof String source) + || !(sourceFence instanceof String fence) + || !(linearization instanceof String xid)) { + throw new PendingCandidateUnavailableException(); + } + try { + return new EvidenceBundleReference(version, source, fence, xid, bundle.canonicalSha256()); + } catch (RuntimeException ex) { + throw new PendingCandidateUnavailableException(); + } + } + + private static AccountAuthEvidenceBundleRepository defaultEvidenceBundles(DSLContext dsl) { + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + return new AccountAuthEvidenceBundleRepository(dsl, generations, outbox); + } + + private static void requireCanonicalSubtree(Object actual, Object expected) { + if (!Arrays.equals(canonicalJson(actual), canonicalJson(expected))) { + throw new PendingCandidateUnavailableException(); + } + } + + private static Map sourceVersionStrings(IssuerAccountSourceSnapshot current) { + AccountAuthoritySnapshot authority = authoritySnapshot(current); + return Map.of( + "issuerSourceVersion", Long.toString(authority.issuerSourceVersion()), + "accountSourceVersion", Long.toString(authority.accountSourceVersion()), + "issuanceFenceSourceVersion", Long.toString(authority.issuanceFenceSourceVersion())); + } + + private static Map accountIdentitySource(IssuerAccountSourceSnapshot current) { + var account = current.account(); + if (account.accountSourceNumericId() == null || account.accountUuidProvenance() == null) { + throw new PendingCandidateUnavailableException(); + } + String sourceId = Long.toString(account.accountSourceNumericId()); + return Map.of( + "sourceRowId", sourceId, + "provenance", account.accountUuidProvenance(), + "sourceNumericId", sourceId); + } + + private static java.util.List> outboxCheckpoints( + IssuerAccountSourceSnapshot current) { + java.util.List> result = new java.util.ArrayList<>(2); + for (var source : java.util.List.of(current.account(), current.issuer())) { + var checkpoint = source.checkpoint(); + Map value = new java.util.LinkedHashMap<>(); + value.put("outboxStreamKey", checkpoint.outboxStreamKey()); + value.put("outboxSequence", Long.toString(checkpoint.sequence())); + if (checkpoint.sequence() > 0L) { + value.put("sourceEventId", checkpoint.sourceEventId().orElseThrow()); + value.put("sourceEventDigest", checkpoint.sourceEventDigest().orElseThrow()); + } + result.add(Map.copyOf(value)); + } + return java.util.List.copyOf(result); + } + + private static AccountGameplayDelegationPendingIdentity identity(Record row) { + try { + if (row.get("request_digest_version", Short.class) == null + || row.get("request_digest_version", Short.class).intValue() != REQUEST_DIGEST_VERSION) { + throw new StorageUnavailableException(); + } + return new AccountGameplayDelegationPendingIdentity( + row.get("operation_id", UUID.class), + row.get("request_id", UUID.class), + row.get("account_uuid", UUID.class), + row.get("caller_workload", String.class), + row.get("caller_context_id", UUID.class), + new AccountGameplayCredentialRequestBinding( + row.get("credential_request_digest_version", Short.class).intValue(), + row.get("credential_digest_key_id", String.class), + row.get("credential_request_digest", String.class)), + row.get("request_digest", String.class), + row.get("token_jti", UUID.class), + positive(row.get("issued_at_epoch_second", Long.class), "issued-at"), + positive(row.get("not_before_epoch_second", Long.class), "not-before"), + positive(row.get("expires_at_epoch_second", Long.class), "expiry")); + } catch (RuntimeException ex) { + throw new StorageUnavailableException(); + } + } + + private static PendingOperation decodeOperation(Record row) { + AccountGameplayDelegationPendingIdentity identity = identity(row); + return new PendingOperation( + identity.operationId(), + identity.requestId(), + identity.requestDigest(), + identity.tokenJti(), + row.get("token_hash", String.class) != null); + } + + private static byte[] canonicalJson(Object value) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (canonical.length == 0 || canonical.length > MAX_INTENT_BYTES) { + throw new IllegalArgumentException("Account issuance metadata exceeds its finite bound"); + } + return canonical; + } catch (IOException ex) { + throw new StorageUnavailableException(); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable"); + } + } + + private static long positive(Long value, String field) { + if (value == null || value <= 0L) + throw new IllegalArgumentException(field + " must be positive"); + return value; + } + + private static Long requireJsonInteger(Object value) { + if (!(value instanceof Number number)) throw new StorageUnavailableException(); + String encoded = number.toString(); + if (!POSITIVE_DECIMAL.matcher(encoded).matches()) throw new StorageUnavailableException(); + try { + return Long.parseLong(encoded); + } catch (NumberFormatException ex) { + throw new StorageUnavailableException(); + } + } + + private static void requirePositiveDecimal(String value, String field) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a canonical positive decimal"); + } + try { + Long.parseLong(value); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException(field + " exceeds its supported range"); + } + } + + private static void requireWritableAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account gameplay delegation issuance requires a writable Account transaction"); + } + } + + public record PendingIntent( + UUID operationId, + UUID requestId, + String callerWorkload, + UUID callerContextId, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + AccountAuthoritySnapshot authoritySnapshot, + AccountGameplayCredentialRequestBinding credentialRequestBinding) { + public PendingIntent { + requireUuid(operationId, "operationId"); + requireUuid(requestId, "requestId"); + requireUuid(callerContextId, "callerContextId"); + requireUuid(tokenJti, "token jti"); + if (callerWorkload == null + || callerWorkload.length() > 256 + || !callerWorkload.matches( + "^spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$")) { + throw new IllegalArgumentException("Exact Game Session workload identity is required"); + } + Objects.requireNonNull(authoritySnapshot, "Expected Account authority snapshot is required"); + Objects.requireNonNull( + credentialRequestBinding, "Keyed credential request binding is required"); + if (issuedAtEpochSecond <= 0L + || notBeforeEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || notBeforeEpochSecond > issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw new IllegalArgumentException("Delegation token time bounds are invalid"); + } + try { + if (Math.subtractExact(expiresAtEpochSecond, issuedAtEpochSecond) <= 0L + || Math.subtractExact(expiresAtEpochSecond, issuedAtEpochSecond) + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw new IllegalArgumentException("Delegation token time bounds are invalid"); + } + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Delegation token time bounds are invalid"); + } + } + + private static void requireUuid(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (value.equals(new UUID(0L, 0L)) || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException(field + " must be a non-zero high-entropy UUID"); + } + } + + @Override + public String toString() { + return "PendingIntent[redacted]"; + } + } + + public record PendingOperation( + UUID operationId, + UUID requestId, + String requestDigest, + UUID tokenJti, + boolean candidateBound) { + @Override + public String toString() { + return "PendingOperation[redacted]"; + } + } + + public enum GameplayLoginReplayState { + PENDING, + COMMITTED + } + + /** Exact current request replay readback; no token or envelope bytes are included. */ + public static final class GameplayLoginReplayReadback { + private final AccountGameplayDelegationPendingIdentity identity; + private final PendingOperation operation; + private final GameplayLoginReplayState state; + private final boolean created; + + private GameplayLoginReplayReadback( + AccountGameplayDelegationPendingIdentity identity, + PendingOperation operation, + GameplayLoginReplayState state, + CommittedIssuanceReadback committedProof, + boolean created) { + this.identity = Objects.requireNonNull(identity); + this.operation = Objects.requireNonNull(operation); + this.state = Objects.requireNonNull(state); + this.created = created; + if (!identity.operationId().equals(operation.operationId()) + || !identity.requestId().equals(operation.requestId()) + || !identity.tokenJti().equals(operation.tokenJti())) { + throw new StorageUnavailableException(); + } + if (state == GameplayLoginReplayState.COMMITTED) { + if (created + || !operation.candidateBound() + || committedProof == null + || !identity.operationId().equals(committedProof.operationId()) + || !identity.requestId().equals(committedProof.requestId()) + || !identity.accountId().equals(committedProof.accountId()) + || !identity.requestDigest().equals(committedProof.requestDigest())) { + throw new StorageUnavailableException(); + } + } else if (committedProof != null) { + throw new StorageUnavailableException(); + } + } + + public AccountGameplayDelegationPendingIdentity identity() { + return identity; + } + + public PendingOperation operation() { + return operation; + } + + public GameplayLoginReplayState state() { + return state; + } + + public boolean created() { + return created; + } + + @Override + public String toString() { + return "GameplayLoginReplayReadback[non-authorizing,redacted]"; + } + } + + /** Exact durable COMMITTED metadata only; this is not token validation or issuance authority. */ + public record CommittedIssuanceReadback( + UUID operationId, + UUID requestId, + UUID accountId, + String requestDigest, + String tokenHash, + String signerKid, + String signerGeneration, + String proofSha256) { + public CommittedIssuanceReadback { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(accountId); + if (requestDigest == null + || !SHA256.matcher(requestDigest).matches() + || tokenHash == null + || !SHA256.matcher(tokenHash).matches() + || signerKid == null + || !signerKid.matches("[A-Za-z0-9_-]{1,64}") + || proofSha256 == null + || !SHA256.matcher(proofSha256).matches()) { + throw new IllegalArgumentException("Account committed issuance readback is malformed"); + } + requirePositiveDecimal(signerGeneration, "signerGeneration"); + } + + @Override + public String toString() { + return "CommittedIssuanceReadback[non-authorizing]"; + } + } + + public record BoundTokenCandidate( + UUID requestId, String tokenHash, String kid, String signerGeneration) { + public BoundTokenCandidate { + Objects.requireNonNull(requestId, "Request ID is required"); + if (tokenHash == null || !SHA256.matcher(tokenHash).matches()) { + throw new IllegalArgumentException("Token hash must be lowercase SHA-256 hex"); + } + if (kid == null || !kid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Signer kid is malformed"); + } + requirePositiveDecimal(signerGeneration, "signerGeneration"); + } + + @Override + public String toString() { + return "BoundTokenCandidate[redacted]"; + } + } + + public record PendingRegistryCandidate( + AccountGameplayDelegationPendingIdentity identity, + String tokenHash, + String kid, + String signerGeneration, + long expiresAtEpochSecond, + byte[] canonicalRecordBytes, + AccountAuthoritySnapshot authoritySnapshot, + EvidenceBundleReference evidenceBundleReference) { + public PendingRegistryCandidate { + canonicalRecordBytes = canonicalRecordBytes.clone(); + Objects.requireNonNull(identity); + Objects.requireNonNull(authoritySnapshot); + Objects.requireNonNull(evidenceBundleReference); + } + + @Override + public byte[] canonicalRecordBytes() { + return canonicalRecordBytes.clone(); + } + + @Override + public String toString() { + return "PendingRegistryCandidate[redacted]"; + } + } + + /** + * Repository-issued exact pre-sign identity plus the persisted full Account evidence value. + * Construction is private so callers cannot turn a supplied DTO into a signing authorization. + */ + public static final class PendingSigningIdentity { + private final AccountGameplayDelegationPendingIdentity identity; + private final AccountAuthoritySnapshot authoritySnapshot; + private final AccountAuthEvidenceBundle evidenceBundle; + private final Optional persistedCandidate; + + private PendingSigningIdentity( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot, + AccountAuthEvidenceBundle evidenceBundle, + Optional persistedCandidate) { + this.identity = Objects.requireNonNull(identity); + this.authoritySnapshot = Objects.requireNonNull(authoritySnapshot); + this.evidenceBundle = Objects.requireNonNull(evidenceBundle); + this.persistedCandidate = Objects.requireNonNull(persistedCandidate); + if (!identity.accountId().equals(authoritySnapshot.accountId())) { + throw new PendingCandidateUnavailableException(); + } + Map fields = evidenceBundle.fields(); + requireCanonicalSubtree( + fields.get("operation"), + Map.of( + "operationId", identity.operationId().toString(), + "requestId", identity.requestId().toString(), + "requestDigest", identity.requestDigest(), + "callerWorkload", identity.callerWorkload(), + "callerContextId", identity.callerContextId().toString(), + "accountId", identity.accountId().toString())); + requireCanonicalSubtree( + fields.get("tokenIdentity"), + Map.of( + "jti", identity.tokenJti().toString(), + "tokenGeneration", "1", + "iat", identity.issuedAtEpochSecond(), + "nbf", identity.notBeforeEpochSecond(), + "exp", identity.expiresAtEpochSecond())); + requireCanonicalSubtree(fields.get("authorityTuple"), authorityTuple(authoritySnapshot)); + requireCanonicalSubtree(fields.get("membershipVersion"), Map.of()); + Object issuanceFence = fields.get("issuanceFence"); + if (!(issuanceFence instanceof String fence) + || !Long.toString(authoritySnapshot.issuanceFence()).equals(fence)) { + throw new PendingCandidateUnavailableException(); + } + requireCanonicalSubtree( + fields.get("authoritySourceVersions"), + Map.of( + "issuerSourceVersion", Long.toString(authoritySnapshot.issuerSourceVersion()), + "accountSourceVersion", Long.toString(authoritySnapshot.accountSourceVersion()), + "issuanceFenceSourceVersion", + Long.toString(authoritySnapshot.issuanceFenceSourceVersion()))); + } + + public AccountGameplayDelegationPendingIdentity identity() { + return identity; + } + + public AccountAuthoritySnapshot authoritySnapshot() { + return authoritySnapshot; + } + + public AccountAuthEvidenceBundle evidenceBundle() { + return evidenceBundle; + } + + /** Exact persisted PENDING candidate, when a prior signing attempt bound it successfully. */ + public Optional persistedCandidate() { + return persistedCandidate; + } + + @Override + public String toString() { + return "PendingSigningIdentity[redacted]"; + } + } + + /** + * Repository-issued, non-authorizing snapshot of the exact current durable COMMITTED evidence. + * The type contains no candidate/JWT bytes, commit-proof bytes, registry bytes, or ciphertext. + */ + public static final class CommittedCandidateVerificationData { + private final AccountGameplayDelegationPendingIdentity identity; + private final AccountAuthoritySnapshot authoritySnapshot; + private final EvidenceBundleReference evidenceBundleReference; + private final String tokenSha256; + private final String signerKid; + private final String signerGeneration; + private final String canonicalRegistryRecordSha256; + private final String commitProofSha256; + private final AuthenticatedSignerCorrespondence signerCorrespondence; + private final String envelopeKeyId; + private final String envelopeSha256; + private final int envelopeBytesLength; + private final long responseRecoveryExpiryEpochMillis; + private final long registryAbsoluteExpiryMillis; + private final long registrationLocalAofCount; + private final long registrationReplicaAofCount; + private final AccountGameplayDelegationRedisClient.PendingRegistrationOutcome + registrationOutcome; + + private CommittedCandidateVerificationData( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot, + EvidenceBundleReference evidenceBundleReference, + String tokenSha256, + String signerKid, + String signerGeneration, + String canonicalRegistryRecordSha256, + String commitProofSha256, + AuthenticatedSignerCorrespondence signerCorrespondence, + String envelopeKeyId, + String envelopeSha256, + int envelopeBytesLength, + long responseRecoveryExpiryEpochMillis, + long registryAbsoluteExpiryMillis, + long registrationLocalAofCount, + long registrationReplicaAofCount, + AccountGameplayDelegationRedisClient.PendingRegistrationOutcome registrationOutcome) { + this.identity = Objects.requireNonNull(identity); + this.authoritySnapshot = Objects.requireNonNull(authoritySnapshot); + this.evidenceBundleReference = Objects.requireNonNull(evidenceBundleReference); + this.tokenSha256 = requireSha256(tokenSha256); + this.signerKid = Objects.requireNonNull(signerKid); + this.signerGeneration = Objects.requireNonNull(signerGeneration); + this.canonicalRegistryRecordSha256 = requireSha256(canonicalRegistryRecordSha256); + this.commitProofSha256 = requireSha256(commitProofSha256); + this.signerCorrespondence = Objects.requireNonNull(signerCorrespondence); + this.envelopeKeyId = Objects.requireNonNull(envelopeKeyId); + this.envelopeSha256 = requireSha256(envelopeSha256); + this.envelopeBytesLength = envelopeBytesLength; + this.responseRecoveryExpiryEpochMillis = responseRecoveryExpiryEpochMillis; + this.registryAbsoluteExpiryMillis = registryAbsoluteExpiryMillis; + this.registrationLocalAofCount = registrationLocalAofCount; + this.registrationReplicaAofCount = registrationReplicaAofCount; + this.registrationOutcome = Objects.requireNonNull(registrationOutcome); + if (!identity.accountId().equals(authoritySnapshot.accountId()) + || signerKid.isBlank() + || signerKid.length() > 64 + || !signerKid.matches("[A-Za-z0-9_-]+") + || envelopeKeyId.isBlank() + || envelopeKeyId.length() > 32 + || !envelopeKeyId.matches("[A-Za-z0-9_-]+") + || envelopeBytesLength < 1 + || envelopeBytesLength > 65_610 + || responseRecoveryExpiryEpochMillis <= 0L + || registryAbsoluteExpiryMillis <= 0L + || registrationLocalAofCount < 1L + || registrationReplicaAofCount < 1L) { + throw new StorageUnavailableException(); + } + requirePositiveDecimal(signerGeneration, "signer generation"); + } + + private static String requireSha256(String value) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new StorageUnavailableException(); + } + return value; + } + + public AccountGameplayDelegationPendingIdentity identity() { + return identity; + } + + public AccountAuthoritySnapshot authoritySnapshot() { + return authoritySnapshot; + } + + public EvidenceBundleReference evidenceBundleReference() { + return evidenceBundleReference; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String signerKid() { + return signerKid; + } + + public String signerGeneration() { + return signerGeneration; + } + + public String canonicalRegistryRecordSha256() { + return canonicalRegistryRecordSha256; + } + + public String commitProofSha256() { + return commitProofSha256; + } + + public AuthenticatedSignerCorrespondence signerCorrespondence() { + return signerCorrespondence; + } + + public String envelopeKeyId() { + return envelopeKeyId; + } + + public String envelopeSha256() { + return envelopeSha256; + } + + public int envelopeBytesLength() { + return envelopeBytesLength; + } + + public long responseRecoveryExpiryEpochMillis() { + return responseRecoveryExpiryEpochMillis; + } + + /** Exact absolute deadline persisted in the immutable COMMITTED proof. */ + public long registryAbsoluteExpiryMillis() { + return registryAbsoluteExpiryMillis; + } + + /** Historical WAITAOF counts validated from the immutable COMMITTED proof. */ + public long registrationLocalAofCount() { + return registrationLocalAofCount; + } + + public long registrationReplicaAofCount() { + return registrationReplicaAofCount; + } + + public AccountGameplayDelegationRedisClient.PendingRegistrationOutcome registrationOutcome() { + return registrationOutcome; + } + + @Override + public String toString() { + return "CommittedCandidateVerificationData[redacted]"; + } + } + + private record EnvelopeHeader(String keyId) {} + + private record EnvelopeIdentity(String sha256, int length, long expiryMillis, String keyId) {} + + public static class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException() { + super("Account gameplay delegation issuance storage is unavailable or ambiguous"); + } + } + + public static final class StaleAuthorityException extends IllegalStateException { + public StaleAuthorityException() { + super("Account gameplay delegation authority changed"); + } + } + + public static final class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException() { + super("Account gameplay delegation request identity conflicts"); + } + } + + public static final class PendingCandidateUnavailableException extends IllegalStateException { + public PendingCandidateUnavailableException() { + super("Account gameplay delegation pending candidate is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java new file mode 100644 index 0000000000..d099d926e4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * Immutable pending-issuance identity data; this value is not signing or authorization evidence. + */ +public record AccountGameplayDelegationPendingIdentity( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + AccountGameplayCredentialRequestBinding credentialRequestBinding, + String requestDigest, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond) { + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + public AccountGameplayDelegationPendingIdentity { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(accountId); + Objects.requireNonNull(callerContextId); + Objects.requireNonNull(credentialRequestBinding); + Objects.requireNonNull(tokenJti); + if (requestDigest == null || !SHA256.matcher(requestDigest).matches()) { + throw new IllegalArgumentException("Request digest is malformed"); + } + if (callerWorkload == null || callerWorkload.length() > 256) { + throw new IllegalArgumentException("Caller workload is malformed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java new file mode 100644 index 0000000000..b8116c0e37 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java @@ -0,0 +1,1384 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.dto.AccountAuthEvidenceBundle; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner.ActiveCommittedIssuanceObservation; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +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; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Stores and recovers one immutable encrypted compact-token candidate for an Account operation. + * + *

Sealing is candidate custody only. Recovery compares caller values to immutable owner rows but + * does not authenticate them; the actual Game Session boundary must provide its authenticated + * workload identity and enforce that its original socket context remains open and current. Recovery + * requires current Account owner evidence and the exact result of the separate registry activation + * owner before it returns the JWT in a redacted typed result. + */ +@Repository +public class AccountGameplayDelegationResponseEnvelopeRepository { + private static final String OPERATION_TABLE = "account_gameplay_delegation_issuance_operations"; + private static final String BUNDLE_TABLE = "account_gameplay_delegation_auth_evidence_bundles"; + private static final String RESPONSE_TABLE = "account_gameplay_delegation_response_envelopes"; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern V4_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern GAME_SESSION_WORKLOAD = + Pattern.compile( + "^spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$"); + private static final byte[] EMPTY_OBJECT = "{}".getBytes(StandardCharsets.US_ASCII); + private static final JsonMapper JSON = + JsonMapper.builder().enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).build(); + + private final DSLContext dsl; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountAuthEvidenceBundleRepository evidenceBundles; + private final AccountGameplayDelegationIssuanceRepository issuanceRepository; + private final AccountResponseEnvelopeCryptography responseCryptography; + private final Clock clock; + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep fail-fast collaborator preconditions in the delegated constructor; this non-final Spring repository acquires no external resources and does not escape partially initialized.") + public AccountGameplayDelegationResponseEnvelopeRepository( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository evidenceBundles, + AccountGameplayDelegationIssuanceRepository issuanceRepository, + AccountResponseEnvelopeCryptography responseCryptography) { + this( + dsl, + sourceEvidence, + evidenceBundles, + issuanceRepository, + responseCryptography, + Clock.systemUTC()); + } + + /** Compatibility constructor for the existing candidate-sealing component fixtures. */ + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep fail-fast collaborator preconditions in the delegated constructor; constructing the lightweight owner adds no external resource acquisition or partially initialized escape.") + public AccountGameplayDelegationResponseEnvelopeRepository( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository evidenceBundles, + AccountResponseEnvelopeCryptography responseCryptography) { + this( + dsl, + sourceEvidence, + evidenceBundles, + new AccountGameplayDelegationIssuanceRepository(dsl, sourceEvidence, evidenceBundles), + responseCryptography, + Clock.systemUTC()); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep required collaborator and clock null checks fail-fast; this non-final Spring repository acquires no external resources and does not escape partially initialized.") + AccountGameplayDelegationResponseEnvelopeRepository( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthEvidenceBundleRepository evidenceBundles, + AccountGameplayDelegationIssuanceRepository issuanceRepository, + AccountResponseEnvelopeCryptography responseCryptography, + Clock clock) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.sourceEvidence = + Objects.requireNonNull(sourceEvidence, "Account authority source evidence is required"); + this.evidenceBundles = + Objects.requireNonNull(evidenceBundles, "Account auth-evidence bundle owner is required"); + this.issuanceRepository = + Objects.requireNonNull(issuanceRepository, "Account durable issuance owner is required"); + this.responseCryptography = + Objects.requireNonNull( + responseCryptography, "Account response-envelope crypto is required"); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + } + + /** + * Encrypts and durably read-backs an exact candidate once, or returns its existing sealed + * metadata for a matching retry. Caller values are comparison inputs from the upstream + * authenticated boundary; this repository does not authenticate them. + */ + @Transactional(propagation = Propagation.MANDATORY) + public SealedCandidateObservation sealPendingCandidate( + UUID requestId, CallerIdentity caller, String exactCompactJwt) { + requireWritableAccountTransaction(); + requireV4(requestId, "request ID"); + Objects.requireNonNull(caller, "Caller identity comparison is required"); + validateCompactJwt(exactCompactJwt); + + Record preliminary = selectOperation(requestId, false); + if (preliminary == null) throw new OperationUnavailableException(); + UUID accountId = uuid(preliminary, "account_uuid"); + UUID operationId = uuid(preliminary, "operation_id"); + requireV4(operationId, "operation ID"); + PendingIdentity identity = identity(preliminary); + if (!requestId.equals(identity.requestId())) throw new OperationUnavailableException(); + requireCallerMatch(identity, caller); + CandidateIdentity candidate = candidate(preliminary, identity); + String exactTokenHash = sha256(exactCompactJwt.getBytes(StandardCharsets.US_ASCII)); + if (!MessageDigest.isEqual( + exactTokenHash.getBytes(StandardCharsets.US_ASCII), + candidate.tokenHash().getBytes(StandardCharsets.US_ASCII))) { + throw new IdempotencyConflictException(); + } + long immutableExpiryMillis = expiryEpochMillis(identity.expiresAtEpochSecond()); + if (clock.millis() >= immutableExpiryMillis) throw new ResponseRecoveryExpiredException(); + + final IssuerAccountSourceSnapshot current; + try { + // Locks Account and authority before the operation row and verifies exact retained source + // checkpoints, including the applicable Account security cutoff. + current = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId); + } catch (RuntimeException ex) { + throw new AuthorityChangedException(); + } + Record operation = selectOperation(requestId, true); + if (operation == null + || !operationId.equals(uuid(operation, "operation_id")) + || !accountId.equals(uuid(operation, "account_uuid"))) { + throw new OperationUnavailableException(); + } + identity = identity(operation); + requireCallerMatch(identity, caller); + candidate = candidate(operation, identity); + if (!exactTokenHash.equals(candidate.tokenHash())) throw new IdempotencyConflictException(); + requireCurrentAuthority(operation, current, accountId); + + AccountAuthEvidenceBundle evaluatedBundle; + AccountAuthEvidenceBundle bundle; + try { + // This owner API performs the current locked source/history evaluation. A previously stored + // value alone is not enough for this new seal attempt. + evaluatedBundle = evidenceBundles.captureAndPersist(requestId); + bundle = evidenceBundles.readStoredNonAuthorizingValue(operationId); + } catch (RuntimeException ex) { + // A missing or malformed owner bundle is not replaced by operation-row fields or caller data. + throw new OwnerEvidenceUnavailableException(); + } + if (!MessageDigest.isEqual(evaluatedBundle.canonicalBytes(), bundle.canonicalBytes())) { + throw new OwnerEvidenceUnavailableException(); + } + requireExactBundle(bundle, identity, operation, current, accountId); + requireCandidateMatchesBoundRows(candidate.record(), identity, operation, current); + + Record existing = selectEnvelope(operationId); + if (existing != null) { + return exactReadback(existing, identity, candidate, bundle, immutableExpiryMillis); + } + + Binding binding = binding(identity, operation, bundle); + Instant recoveryExpiry; + try { + recoveryExpiry = Instant.ofEpochMilli(immutableExpiryMillis); + } catch (RuntimeException ex) { + throw new OwnerEvidenceUnavailableException(); + } + byte[] plaintext = exactCompactJwt.getBytes(StandardCharsets.US_ASCII); + final EncryptedResponseEnvelope sealed; + try { + sealed = responseCryptography.encrypt(binding, plaintext, recoveryExpiry); + } finally { + Arrays.fill(plaintext, (byte) 0); + } + byte[] envelopeBytes = sealed.bytes(); + try { + String envelopeHash = sha256(envelopeBytes); + String bundleHash = bundle.canonicalSha256(); + int inserted = + dsl.execute( + "INSERT INTO " + + RESPONSE_TABLE + + " (operation_id, request_id, token_hash, signer_kid, signer_generation, " + + "authority_evidence_bundle_sha256, issuance_fence, " + + "response_recovery_expiry_epoch_ms, envelope_sha256, envelope_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + identity.operationId(), + identity.requestId(), + candidate.tokenHash(), + candidate.kid(), + candidate.signerGeneration(), + bundleHash, + identity.issuanceFence(), + immutableExpiryMillis, + envelopeHash, + envelopeBytes); + if (inserted != 1) throw new StorageUnavailableException(); + Record readback = selectEnvelope(operationId); + if (readback == null) throw new StorageUnavailableException(); + SealedCandidateObservation observation = + exactReadback(readback, identity, candidate, bundle, immutableExpiryMillis); + byte[] readbackBytes = bytes(readback, "envelope_bytes"); + try { + if (!MessageDigest.isEqual(envelopeBytes, readbackBytes)) { + throw new StorageUnavailableException(); + } + } finally { + Arrays.fill(readbackBytes, (byte) 0); + } + return observation; + } finally { + Arrays.fill(envelopeBytes, (byte) 0); + } + } + + /** + * Opens one exact, still-current PENDING candidate for Account's internal signer verification + * retry. This is not caller recovery: no gameplay caller or public response boundary receives a + * credential, and the returned bytes are consumed only by the signer before commit. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PendingCandidateCredential openPendingCandidate(UUID requestId, CallerIdentity caller) { + requireWritableAccountTransaction(); + requireV4(requestId, "request ID"); + Objects.requireNonNull(caller, "Caller identity comparison is required"); + + Record preliminary = selectOperation(requestId, false); + if (preliminary == null) throw new OperationUnavailableException(); + PendingIdentity preliminaryIdentity = identity(preliminary); + requireCallerMatch(preliminaryIdentity, caller); + CandidateIdentity preliminaryCandidate = candidate(preliminary, preliminaryIdentity); + long immutableExpiryMillis = expiryEpochMillis(preliminaryIdentity.expiresAtEpochSecond()); + requirePendingCandidateUnexpired(immutableExpiryMillis); + + final IssuerAccountSourceSnapshot current; + try { + current = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, preliminaryIdentity.accountId()); + } catch (RuntimeException unavailable) { + throw new AuthorityChangedException(); + } + Record operation = selectOperation(requestId, true); + if (operation == null) throw new OperationUnavailableException(); + PendingIdentity identity = identity(operation); + requireCallerMatch(identity, caller); + CandidateIdentity persistedCandidate = candidate(operation, identity); + if (!preliminaryIdentity.equals(identity) + || !preliminaryCandidate.tokenHash().equals(persistedCandidate.tokenHash()) + || !preliminaryCandidate.kid().equals(persistedCandidate.kid()) + || !preliminaryCandidate.signerGeneration().equals(persistedCandidate.signerGeneration()) + || !Arrays.equals( + preliminaryCandidate + .record() + .toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES), + persistedCandidate + .record() + .toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES))) { + throw new IdempotencyConflictException(); + } + requireCurrentAuthority(operation, current, identity.accountId()); + requireCandidateMatchesBoundRows(persistedCandidate.record(), identity, operation, current); + + final AccountAuthEvidenceBundle bundle; + try { + bundle = evidenceBundles.readStoredNonAuthorizingValue(identity.operationId()); + } catch (RuntimeException unavailable) { + throw new OwnerEvidenceUnavailableException(); + } + requireExactBundle(bundle, identity, operation, current, identity.accountId()); + if (!bundle + .canonicalSha256() + .equals(persistedCandidate.record().evidenceBundleReference().canonicalSha256())) { + throw new OwnerEvidenceUnavailableException(); + } + + Record envelope = selectEnvelopeForRecovery(identity.operationId()); + if (envelope == null) throw new StorageUnavailableException(); + byte[] envelopeBytes = bytes(envelope, "envelope_bytes"); + byte[] plaintext = null; + try { + SealedCandidateObservation sealed = + exactReadback(envelope, identity, persistedCandidate, bundle, immutableExpiryMillis); + requirePendingCandidateUnexpired(immutableExpiryMillis); + plaintext = + responseCryptography.decrypt( + new EncryptedResponseEnvelope(envelopeBytes), + binding(identity, operation, bundle), + Instant.ofEpochMilli(immutableExpiryMillis)); + validateRecoveredCompactJwt(plaintext, persistedCandidate.tokenHash()); + return new PendingCandidateCredential(plaintext, sealed); + } catch (AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException expired) { + throw new ResponseRecoveryExpiredException(); + } catch (RuntimeException failure) { + if (failure instanceof ResponseRecoveryExpiredException expired) throw expired; + throw new StorageUnavailableException(); + } finally { + if (plaintext != null) Arrays.fill(plaintext, (byte) 0); + Arrays.fill(envelopeBytes, (byte) 0); + } + } + + private void requirePendingCandidateUnexpired(long immutableExpiryMillis) { + long nowMillis = clock.millis(); + if (nowMillis <= 0L || nowMillis >= immutableExpiryMillis) { + throw new ResponseRecoveryExpiredException(); + } + } + + /** + * Checks only immutable request/caller identity and the stored response horizon before registry + * activation. This deliberately does not authenticate the supplied identity or inspect/decrypt + * the response envelope; the actual Game Session boundary must supply its authenticated mTLS + * workload and ensure the original caller context is still open and current. + */ + @Transactional(propagation = Propagation.MANDATORY) + public RecoveryPreflight preflightCommittedRecovery( + UUID requestId, UUID expectedAccountId, CallerIdentity caller) { + requireWritableAccountTransaction(); + requireRecoveryRequest(requestId, expectedAccountId, caller); + Record operation = selectOperation(requestId, false); + if (operation == null) throw new OperationUnavailableException(); + CommittedRecoveryIdentity identity = committedRecoveryIdentity(operation); + requireRecoveryCaller(identity, requestId, expectedAccountId, caller); + long expiryMillis = expiryEpochMillis(identity.expiresAtEpochSecond()); + long nowMillis = clock.millis(); + if (nowMillis <= 0L || nowMillis >= expiryMillis) { + throw new ResponseRecoveryExpiredException(); + } + return new RecoveryPreflight( + identity.operationId(), + identity.requestId(), + identity.accountId(), + identity.callerWorkload(), + identity.callerContextId(), + identity.requestDigest(), + identity.tokenJti(), + identity.expiresAtEpochSecond(), + expiryMillis); + } + + /** + * Reads current durable COMMITTED evidence and decrypts its exact original compact JWT only after + * the caller has completed the COMMITTED-to-ACTIVE registry postcondition. The SQL owner + * transaction contains no network operation; plaintext is returned only in the redacted typed + * credential result and the local byte buffer is wiped before exit. + */ + @Transactional(propagation = Propagation.MANDATORY) + public RecoveredCredential recoverCommittedResponse( + UUID requestId, + UUID expectedAccountId, + CallerIdentity caller, + ActiveCommittedIssuanceObservation active) { + requireWritableAccountTransaction(); + requireRecoveryRequest(requestId, expectedAccountId, caller); + Objects.requireNonNull(active, "Completed Account activation evidence is required"); + + Record preliminary = selectOperation(requestId, false); + if (preliminary == null) throw new OperationUnavailableException(); + CommittedRecoveryIdentity preliminaryIdentity = committedRecoveryIdentity(preliminary); + requireRecoveryCaller(preliminaryIdentity, requestId, expectedAccountId, caller); + long immutableExpiryMillis = expiryEpochMillis(preliminaryIdentity.expiresAtEpochSecond()); + if (clock.millis() <= 0L || clock.millis() >= immutableExpiryMillis) { + throw new ResponseRecoveryExpiredException(); + } + + final CommittedCandidateVerificationData committed; + try { + committed = issuanceRepository.readCurrentCommittedCandidate(requestId); + } catch (RuntimeException failure) { + if (clock.millis() >= immutableExpiryMillis) { + throw new ResponseRecoveryExpiredException(); + } + throw new OwnerEvidenceUnavailableException(); + } + + Record operation = selectOperation(requestId, true); + if (operation == null) throw new OperationUnavailableException(); + CommittedRecoveryIdentity identity = committedRecoveryIdentity(operation); + requireRecoveryCaller(identity, requestId, expectedAccountId, caller); + if (!preliminaryIdentity.equals(identity) + || !committedMatches(committed, identity) + || !activeMatches(active, committed)) { + throw new OwnerEvidenceUnavailableException(); + } + if (clock.millis() <= 0L || clock.millis() >= immutableExpiryMillis) { + throw new ResponseRecoveryExpiredException(); + } + + final IssuerAccountSourceSnapshot current; + try { + current = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, identity.accountId()); + } catch (RuntimeException failure) { + throw new AuthorityChangedException(); + } + requireCurrentAuthority(operation, current, identity.accountId()); + CandidateIdentity candidate = candidate(operation, identity.pendingIdentity()); + requireCandidateMatchesBoundRows( + candidate.record(), identity.pendingIdentity(), operation, current); + + final AccountAuthEvidenceBundle bundle; + try { + bundle = evidenceBundles.readStoredNonAuthorizingValue(identity.operationId()); + } catch (RuntimeException failure) { + throw new OwnerEvidenceUnavailableException(); + } + if (!committed.evidenceBundleReference().canonicalSha256().equals(bundle.canonicalSha256()) + || !candidate.record().evidenceBundleReference().equals(committed.evidenceBundleReference()) + || !committed.tokenSha256().equals(candidate.tokenHash()) + || !committed.signerKid().equals(candidate.kid()) + || !committed.signerGeneration().equals(candidate.signerGeneration()) + || !committed + .canonicalRegistryRecordSha256() + .equals(sha256(bytes(operation, "pending_registry_candidate_bytes"))) + || !committed.authoritySnapshot().equals(authoritySnapshot(current))) { + throw new OwnerEvidenceUnavailableException(); + } + requireExactBundle( + bundle, identity.pendingIdentity(), operation, current, identity.accountId()); + + Record envelope = selectEnvelopeForRecovery(identity.operationId()); + if (envelope == null) throw new StorageUnavailableException(); + byte[] envelopeBytes = bytes(envelope, "envelope_bytes"); + String envelopeHash = text(envelope, "envelope_sha256"); + if (!exactCommittedEnvelope( + envelope, + envelopeBytes, + envelopeHash, + identity, + candidate, + committed, + bundle, + immutableExpiryMillis)) { + throw new StorageUnavailableException(); + } + + byte[] plaintext = null; + try { + plaintext = + responseCryptography.decrypt( + new EncryptedResponseEnvelope(envelopeBytes), + binding(identity.pendingIdentity(), operation, bundle), + Instant.ofEpochMilli(immutableExpiryMillis)); + validateRecoveredCompactJwt(plaintext, committed.tokenSha256()); + return new RecoveredCredential( + plaintext, + identity.accountId(), + identity.tokenJti(), + committed.tokenSha256(), + GameSessionAccountDelegationProfile.PROFILE, + identity.expiresAtEpochSecond(), + bundle); + } catch (AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException expired) { + throw new ResponseRecoveryExpiredException(); + } catch (RuntimeException failure) { + if (failure instanceof ResponseRecoveryExpiredException expired) throw expired; + throw new StorageUnavailableException(); + } finally { + if (plaintext != null) Arrays.fill(plaintext, (byte) 0); + Arrays.fill(envelopeBytes, (byte) 0); + } + } + + private Record selectEnvelopeForRecovery(UUID operationId) { + return dsl.fetchOne( + "SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, " + + "authority_evidence_bundle_sha256, issuance_fence, " + + "response_recovery_expiry_epoch_ms, envelope_sha256, envelope_bytes " + + "FROM " + + RESPONSE_TABLE + + " WHERE operation_id = ? FOR SHARE", + operationId); + } + + private boolean exactCommittedEnvelope( + Record envelope, + byte[] envelopeBytes, + String envelopeHash, + CommittedRecoveryIdentity identity, + CandidateIdentity candidate, + CommittedCandidateVerificationData committed, + AccountAuthEvidenceBundle bundle, + long immutableExpiryMillis) { + return identity.operationId().equals(uuid(envelope, "operation_id")) + && identity.requestId().equals(uuid(envelope, "request_id")) + && candidate.tokenHash().equals(text(envelope, "token_hash")) + && candidate.kid().equals(text(envelope, "signer_kid")) + && candidate.signerGeneration().equals(text(envelope, "signer_generation")) + && bundle.canonicalSha256().equals(text(envelope, "authority_evidence_bundle_sha256")) + && identity.issuanceFence() == positive(envelope, "issuance_fence") + && immutableExpiryMillis == positive(envelope, "response_recovery_expiry_epoch_ms") + && immutableExpiryMillis == committed.responseRecoveryExpiryEpochMillis() + && committed.envelopeSha256().equals(envelopeHash) + && committed.envelopeBytesLength() == envelopeBytes.length + && envelopeBytes.length > 0 + && envelopeBytes.length <= 65_610 + && SHA256.matcher(envelopeHash).matches() + && MessageDigest.isEqual( + sha256(envelopeBytes).getBytes(StandardCharsets.US_ASCII), + envelopeHash.getBytes(StandardCharsets.US_ASCII)); + } + + private static boolean committedMatches( + CommittedCandidateVerificationData committed, CommittedRecoveryIdentity identity) { + var committedIdentity = committed.identity(); + return committedIdentity.operationId().equals(identity.operationId()) + && committedIdentity.requestId().equals(identity.requestId()) + && committedIdentity.accountId().equals(identity.accountId()) + && committedIdentity.callerWorkload().equals(identity.callerWorkload()) + && committedIdentity.callerContextId().equals(identity.callerContextId()) + && committedIdentity.requestDigest().equals(identity.requestDigest()) + && committedIdentity.tokenJti().equals(identity.tokenJti()) + && committedIdentity.issuedAtEpochSecond() == identity.issuedAtEpochSecond() + && committedIdentity.notBeforeEpochSecond() == identity.notBeforeEpochSecond() + && committedIdentity.expiresAtEpochSecond() == identity.expiresAtEpochSecond() + && committed.tokenSha256().equals(identity.tokenHash()) + && committed.authoritySnapshot().accountId().equals(identity.accountId()) + && committed.authoritySnapshot().issuanceFence() == identity.issuanceFence() + && committed.responseRecoveryExpiryEpochMillis() + == expiryEpochMillis(identity.expiresAtEpochSecond()); + } + + private static boolean activeMatches( + ActiveCommittedIssuanceObservation active, CommittedCandidateVerificationData committed) { + return active.operationId().equals(committed.identity().operationId()) + && active.requestId().equals(committed.identity().requestId()) + && active.accountId().equals(committed.identity().accountId()) + && active.tokenSha256().equals(committed.tokenSha256()) + && active.commitProofSha256().equals(committed.commitProofSha256()) + && active.registryVersion() == 2L + && active.absoluteExpiryMillis() == committed.registryAbsoluteExpiryMillis() + && active.observedAtEpochMillis() > 0L + && active.observedAtEpochMillis() < committed.responseRecoveryExpiryEpochMillis() + && active.activeRecordSha256() != null + && SHA256.matcher(active.activeRecordSha256()).matches(); + } + + private static void requireV4ForRecovery(UUID value, String field) { + requireV4(value, field); + if (value.variant() != 2) throw new OperationUnavailableException(); + } + + private CommittedRecoveryIdentity committedRecoveryIdentity(Record operation) { + if (!"COMMITTED".equals(text(operation, "status")) + || number(operation, "request_digest_version") != 2L + || number(operation, "token_generation") != 1L) { + throw new OperationUnavailableException(); + } + String callerWorkload = text(operation, "caller_workload"); + if (!GAME_SESSION_WORKLOAD.matcher(callerWorkload).matches()) { + throw new OperationUnavailableException(); + } + String requestDigest = text(operation, "request_digest"); + if (!SHA256.matcher(requestDigest).matches()) throw new OperationUnavailableException(); + UUID operationId = uuid(operation, "operation_id"); + UUID requestId = uuid(operation, "request_id"); + UUID accountId = uuid(operation, "account_uuid"); + UUID callerContextId = uuid(operation, "caller_context_id"); + UUID tokenJti = uuid(operation, "token_jti"); + requireV4ForRecovery(operationId, "operation ID"); + requireV4ForRecovery(requestId, "request ID"); + requireV4ForRecovery(accountId, "Account ID"); + requireV4ForRecovery(callerContextId, "caller context ID"); + requireV4ForRecovery(tokenJti, "token ID"); + String tokenHash = text(operation, "token_hash"); + if (!SHA256.matcher(tokenHash).matches()) throw new CandidateUnavailableException(); + return new CommittedRecoveryIdentity( + operationId, + requestId, + accountId, + callerWorkload, + callerContextId, + credentialRequestBinding(operation), + requestDigest, + tokenJti, + positive(operation, "issued_at_epoch_second"), + positive(operation, "not_before_epoch_second"), + positive(operation, "expires_at_epoch_second"), + tokenHash, + positive(operation, "issuance_fence")); + } + + private static void requireRecoveryCaller( + CommittedRecoveryIdentity identity, + UUID requestId, + UUID expectedAccountId, + CallerIdentity caller) { + if (!identity.requestId().equals(requestId)) throw new OperationUnavailableException(); + if (!identity.accountId().equals(expectedAccountId) + || !identity.callerWorkload().equals(caller.workload()) + || !identity.callerContextId().equals(caller.contextId())) { + throw new IdempotencyConflictException(); + } + } + + private static void requireRecoveryRequest( + UUID requestId, UUID expectedAccountId, CallerIdentity caller) { + requireV4ForRecovery(requestId, "request ID"); + requireV4ForRecovery(expectedAccountId, "Account ID"); + Objects.requireNonNull(caller, "Authenticated Game Session identity comparison is required"); + } + + private static void validateRecoveredCompactJwt(byte[] bytes, String expectedSha256) { + if (bytes == null + || bytes.length == 0 + || bytes.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES) { + throw new StorageUnavailableException(); + } + for (byte value : bytes) { + int octet = Byte.toUnsignedInt(value); + if (octet < 0x21 || octet > 0x7e) throw new StorageUnavailableException(); + } + if (!MessageDigest.isEqual( + sha256(bytes).getBytes(StandardCharsets.US_ASCII), + expectedSha256.getBytes(StandardCharsets.US_ASCII))) { + throw new StorageUnavailableException(); + } + } + + private Record selectOperation(UUID requestId, boolean lock) { + return dsl.fetchOne( + "SELECT * FROM " + OPERATION_TABLE + " WHERE request_id = ?" + (lock ? " FOR UPDATE" : ""), + requestId); + } + + private Record selectEnvelope(UUID operationId) { + return dsl.fetchOne( + "SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, " + + "authority_evidence_bundle_sha256, issuance_fence, " + + "response_recovery_expiry_epoch_ms, envelope_sha256, envelope_bytes " + + "FROM " + + RESPONSE_TABLE + + " WHERE operation_id = ?", + operationId); + } + + private SealedCandidateObservation exactReadback( + Record row, + PendingIdentity identity, + CandidateIdentity candidate, + AccountAuthEvidenceBundle bundle, + long expiryMillis) { + byte[] envelope = bytes(row, "envelope_bytes"); + String storedEnvelopeHash = text(row, "envelope_sha256"); + try { + if (!identity.operationId().equals(uuid(row, "operation_id")) + || !identity.requestId().equals(uuid(row, "request_id")) + || !candidate.tokenHash().equals(text(row, "token_hash")) + || !candidate.kid().equals(text(row, "signer_kid")) + || !candidate.signerGeneration().equals(text(row, "signer_generation")) + || !bundle.canonicalSha256().equals(text(row, "authority_evidence_bundle_sha256")) + || identity.issuanceFence() != positive(row, "issuance_fence") + || expiryMillis != positive(row, "response_recovery_expiry_epoch_ms") + || envelope.length == 0 + || envelope.length > 65_610 + || !SHA256.matcher(storedEnvelopeHash).matches() + || !MessageDigest.isEqual( + sha256(envelope).getBytes(StandardCharsets.US_ASCII), + storedEnvelopeHash.getBytes(StandardCharsets.US_ASCII))) { + throw new StorageUnavailableException(); + } + return new SealedCandidateObservation( + identity.operationId(), + identity.requestId(), + bundle.canonicalSha256(), + identity.issuanceFence(), + expiryMillis, + storedEnvelopeHash, + envelope.length); + } finally { + Arrays.fill(envelope, (byte) 0); + } + } + + private static Binding binding( + PendingIdentity identity, Record operation, AccountAuthEvidenceBundle bundle) { + return new Binding( + GameSessionAccountDelegationProfile.PROFILE, + identity.requestId().toString(), + HexFormat.of().parseHex(identity.requestDigest()), + identity.callerWorkload(), + identity.operationId().toString(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + identity.issuanceFence(), + bytes(operation, "authority_tuple_canonical_bytes"), + bytes(operation, "membership_version_canonical_bytes"), + bundle.canonicalBytes()); + } + + private static PendingIdentity identity(Record operation) { + if (!"PENDING".equals(text(operation, "status")) + || number(operation, "request_digest_version") != 2L + || number(operation, "token_generation") != 1L) { + throw new OperationUnavailableException(); + } + String caller = text(operation, "caller_workload"); + if (!GAME_SESSION_WORKLOAD.matcher(caller).matches()) { + throw new OperationUnavailableException(); + } + String digest = text(operation, "request_digest"); + if (!SHA256.matcher(digest).matches()) throw new OperationUnavailableException(); + return new PendingIdentity( + uuid(operation, "operation_id"), + uuid(operation, "request_id"), + uuid(operation, "account_uuid"), + caller, + uuid(operation, "caller_context_id"), + credentialRequestBinding(operation), + digest, + uuid(operation, "token_jti"), + positive(operation, "issued_at_epoch_second"), + positive(operation, "not_before_epoch_second"), + positive(operation, "expires_at_epoch_second"), + positive(operation, "issuance_fence")); + } + + private static AccountGameplayCredentialRequestBinding credentialRequestBinding( + Record operation) { + try { + return new AccountGameplayCredentialRequestBinding( + Math.toIntExact(number(operation, "credential_request_digest_version")), + text(operation, "credential_digest_key_id"), + text(operation, "credential_request_digest")); + } catch (RuntimeException ex) { + throw new OperationUnavailableException(); + } + } + + private static CandidateIdentity candidate(Record operation, PendingIdentity identity) { + String tokenHash = text(operation, "token_hash"); + String kid = text(operation, "signer_kid"); + String signerGeneration = text(operation, "signer_generation"); + byte[] candidateBytes = bytes(operation, "pending_registry_candidate_bytes"); + if (!SHA256.matcher(tokenHash).matches() + || !kid.matches("[A-Za-z0-9_-]{1,64}") + || !signerGeneration.matches("[1-9][0-9]{0,18}") + || candidateBytes.length == 0 + || candidateBytes.length > GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES) { + throw new CandidateUnavailableException(); + } + GameSessionAccountDelegationRegistryRecord record; + try { + record = + GameSessionAccountDelegationRegistryRecord.decode( + candidateBytes, GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + } catch (RuntimeException ex) { + throw new CandidateUnavailableException(); + } + return new CandidateIdentity(tokenHash, kid, signerGeneration, record); + } + + private static void requireCallerMatch(PendingIdentity identity, CallerIdentity caller) { + if (!identity.callerWorkload().equals(caller.workload()) + || !identity.callerContextId().equals(caller.contextId())) { + throw new IdempotencyConflictException(); + } + } + + private static void requireCurrentAuthority( + Record operation, IssuerAccountSourceSnapshot snapshot, UUID accountId) { + CurrentSourceEvidence issuer = snapshot.issuer(); + CurrentSourceEvidence account = snapshot.account(); + if (issuer.scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ISSUER + || !GameSessionAccountDelegationProfile.ISSUER.equals(issuer.scope().issuerId()) + || issuer.scope().accountId() != null + || issuer.scope().tenantId() != null + || account.scope().kind() != AccountAuthorityGenerationRepository.ScopeKind.ACCOUNT + || !accountId.equals(account.scope().accountId()) + || account.scope().issuerId() != null + || account.scope().tenantId() != null + || !Objects.equals(account.issuanceFence(), snapshot.issuanceFence()) + || !accountId.equals(snapshot.issuanceFence().accountId()) + || !Objects.equals(issuer.generation(), longValue(operation, "authority_issuer_generation")) + || !Objects.equals( + issuer.sourceVersion(), longValue(operation, "authority_issuer_source_version")) + || !Objects.equals( + account.generation(), longValue(operation, "authority_account_generation")) + || !Objects.equals( + account.sourceVersion(), longValue(operation, "authority_account_source_version")) + || !Objects.equals(snapshot.issuanceFence().value(), longValue(operation, "issuance_fence")) + || !Objects.equals( + snapshot.issuanceFence().sourceVersion(), + longValue(operation, "issuance_fence_source_version"))) { + throw new AuthorityChangedException(); + } + Map currentTuple = + GameSessionAccountDelegationProfile.authorityTuple( + issuer.generation(), + account.generation(), + account + .accountSecurityCutoff() + .map( + cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))); + if (!Arrays.equals( + bytes(operation, "authority_tuple_canonical_bytes"), canonicalJson(currentTuple)) + || !Arrays.equals(bytes(operation, "membership_version_canonical_bytes"), EMPTY_OBJECT)) { + throw new AuthorityChangedException(); + } + } + + private void requireExactBundle( + AccountAuthEvidenceBundle bundle, + PendingIdentity identity, + Record operation, + IssuerAccountSourceSnapshot current, + UUID accountId) { + Map root = bundle.fields(); + Map scope = object(root, "scope"); + Map operationFields = object(root, "operation"); + Map token = object(root, "tokenIdentity"); + Map authorityTuple = object(root, "authorityTuple"); + Map sourceVersions = object(root, "authoritySourceVersions"); + if (!"account".equals(scope.get("kind")) + || !accountId.toString().equals(scope.get("accountId")) + || !List.of().equals(scope.get("tenantIds")) + || !identity.operationId().toString().equals(operationFields.get("operationId")) + || !identity.requestId().toString().equals(operationFields.get("requestId")) + || !identity.requestDigest().equals(operationFields.get("requestDigest")) + || !identity.callerWorkload().equals(operationFields.get("callerWorkload")) + || !identity.callerContextId().toString().equals(operationFields.get("callerContextId")) + || !accountId.toString().equals(operationFields.get("accountId")) + || !identity.tokenJti().toString().equals(token.get("jti")) + || !Long.valueOf(1L).equals(numberFromString(token.get("tokenGeneration"))) + || numberValue(token.get("iat")) != identity.issuedAtEpochSecond() + || numberValue(token.get("nbf")) != identity.notBeforeEpochSecond() + || numberValue(token.get("exp")) != identity.expiresAtEpochSecond() + || !Long.toString(identity.issuanceFence()).equals(root.get("issuanceFence")) + || !Map.of().equals(root.get("membershipVersion")) + || !Long.valueOf(current.issuer().generation()) + .equals(numberFromString(authorityTuple.get("issuerAuthGeneration"))) + || !Long.valueOf(current.account().generation()) + .equals(numberFromString(authorityTuple.get("accountAuthorityGeneration"))) + || !Arrays.equals( + canonicalJson(authorityTuple), bytes(operation, "authority_tuple_canonical_bytes")) + || !Arrays.equals( + canonicalJson(root.get("membershipVersion")), + bytes(operation, "membership_version_canonical_bytes")) + || !Long.toString(current.issuer().sourceVersion()) + .equals(sourceVersions.get("issuerSourceVersion")) + || !Long.toString(current.account().sourceVersion()) + .equals(sourceVersions.get("accountSourceVersion")) + || !Long.toString(current.issuanceFence().sourceVersion()) + .equals(sourceVersions.get("issuanceFenceSourceVersion")) + || positive(operation, "authority_issuer_source_version") + != current.issuer().sourceVersion() + || positive(operation, "authority_account_source_version") + != current.account().sourceVersion() + || positive(operation, "issuance_fence_source_version") + != current.issuanceFence().sourceVersion()) { + throw new OwnerEvidenceUnavailableException(); + } + Record accountRow = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id " + + "FROM accounts WHERE account_uuid = ? FOR SHARE", + accountId); + if (accountRow == null + || !accountId.equals(uuid(accountRow, "account_uuid")) + || !Long.toString(positive(accountRow, "id")) + .equals(object(root, "accountIdentitySource").get("sourceRowId")) + || !Long.toString(positive(accountRow, "account_uuid_source_numeric_id")) + .equals(object(root, "accountIdentitySource").get("sourceNumericId"))) { + throw new OwnerEvidenceUnavailableException(); + } + AccountIdentityProvenance provenance; + try { + provenance = + AccountIdentityProvenance.fromStorageValue(text(accountRow, "account_uuid_provenance")); + } catch (RuntimeException ex) { + throw new OwnerEvidenceUnavailableException(); + } + if (!AccountIdentityProvenance.isAccepted(provenance) + || !provenance.name().equals(object(root, "accountIdentitySource").get("provenance"))) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static void requireCandidateMatchesBoundRows( + GameSessionAccountDelegationRegistryRecord record, + PendingIdentity identity, + Record operation, + IssuerAccountSourceSnapshot current) { + AccountAuthoritySnapshot currentAuthority = authoritySnapshot(current); + Map fields = record.fields(); + if (!record.tokenHash().equals(text(operation, "token_hash")) + || !record.kid().equals(text(operation, "signer_kid")) + || !record.signerGeneration().equals(text(operation, "signer_generation")) + || !"pending".equals(record.state()) + || !identity.operationId().toString().equals(record.operationId()) + || !identity.requestId().toString().equals(record.requestId()) + || !identity.requestDigest().equals(record.requestDigest()) + || !identity.accountId().toString().equals(record.accountId()) + || !identity.tokenJti().toString().equals(record.jti()) + || identity.issuedAtEpochSecond() != record.issuedAtEpochSecond() + || identity.notBeforeEpochSecond() != record.notBeforeEpochSecond() + || identity.expiresAtEpochSecond() != record.expiresAtEpochSecond() + || identity.issuanceFence() != record.issuanceFence() + || !Arrays.equals( + canonicalJson(fields.get("authorityTuple")), + bytes(operation, "authority_tuple_canonical_bytes")) + || !Arrays.equals( + canonicalJson(fields.get("membershipVersion")), + bytes(operation, "membership_version_canonical_bytes")) + || !Arrays.equals( + canonicalJson(fields.get("authoritySourceVersions")), + canonicalJson(currentAuthority.sourceVersions()))) { + throw new CandidateUnavailableException(); + } + } + + private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSnapshot sources) { + Optional cutoff = + sources + .account() + .accountSecurityCutoff() + .map( + value -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); + return new AccountAuthoritySnapshot( + sources.account().scope().accountId(), + sources.issuer().generation(), + sources.issuer().sourceVersion(), + sources.account().generation(), + sources.account().sourceVersion(), + sources.issuanceFence().value(), + sources.issuanceFence().sourceVersion(), + cutoff); + } + + private static long expiryEpochMillis(long expEpochSecond) { + try { + long millis = Math.multiplyExact(expEpochSecond, 1_000L); + if (millis <= 0L) throw new ArithmeticException(); + return millis; + } catch (ArithmeticException ex) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static void validateCompactJwt(String value) { + if (value == null + || value.isEmpty() + || value.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES) { + throw new CandidateUnavailableException(); + } + for (int index = 0; index < value.length(); index++) { + if (value.charAt(index) > 0x7f) throw new CandidateUnavailableException(); + } + } + + private static byte[] canonicalJson(Object value) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (canonical.length == 0 || canonical.length > 8 * 1024) { + throw new OwnerEvidenceUnavailableException(); + } + return canonical; + } catch (IOException | RuntimeException ex) { + if (ex instanceof OwnerEvidenceUnavailableException unavailable) throw unavailable; + throw new OwnerEvidenceUnavailableException(); + } + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException ex) { + throw new StorageUnavailableException(); + } + } + + private static Map object(Map parent, String field) { + Object value = parent.get(field); + if (!(value instanceof Map map)) throw new OwnerEvidenceUnavailableException(); + @SuppressWarnings("unchecked") + Map typed = (Map) map; + return typed; + } + + private static long numberValue(Object value) { + if (!(value instanceof Number number)) throw new OwnerEvidenceUnavailableException(); + try { + return Long.parseLong(number.toString()); + } catch (NumberFormatException ex) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static Long numberFromString(Object value) { + if (!(value instanceof String text) || !text.matches("[1-9][0-9]{0,18}")) { + throw new OwnerEvidenceUnavailableException(); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException ex) { + throw new OwnerEvidenceUnavailableException(); + } + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null) throw new OperationUnavailableException(); + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw new OperationUnavailableException(); + return value; + } + + private static byte[] bytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) throw new OperationUnavailableException(); + return value.clone(); + } + + private static long number(Record row, String field) { + Object value = row.get(field); + if (!(value instanceof Number numeric)) throw new OperationUnavailableException(); + return numeric.longValue(); + } + + private static Long longValue(Record row, String field) { + Object value = row.get(field); + return value instanceof Number numeric ? numeric.longValue() : null; + } + + private static long positive(Record row, String field) { + long value = number(row, field); + if (value <= 0L) throw new OperationUnavailableException(); + return value; + } + + private static void requireV4(UUID value, String field) { + if (value == null || value.version() != 4 || !V4_UUID.matcher(value.toString()).matches()) { + throw new OperationUnavailableException(); + } + } + + private static void requireWritableAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account response-envelope storage requires a writable Account owner transaction"); + } + } + + private record PendingIdentity( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + AccountGameplayCredentialRequestBinding credentialRequestBinding, + String requestDigest, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + long issuanceFence) {} + + private record CandidateIdentity( + String tokenHash, + String kid, + String signerGeneration, + GameSessionAccountDelegationRegistryRecord record) {} + + private record CommittedRecoveryIdentity( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + AccountGameplayCredentialRequestBinding credentialRequestBinding, + String requestDigest, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + String tokenHash, + long issuanceFence) { + private PendingIdentity pendingIdentity() { + return new PendingIdentity( + operationId, + requestId, + accountId, + callerWorkload, + callerContextId, + credentialRequestBinding, + requestDigest, + tokenJti, + issuedAtEpochSecond, + notBeforeEpochSecond, + expiresAtEpochSecond, + issuanceFence); + } + } + + /** Comparison inputs only; a caller transport must establish its authenticity separately. */ + public record CallerIdentity(String workload, UUID contextId) { + public CallerIdentity { + if (workload == null + || !GAME_SESSION_WORKLOAD.matcher(workload).matches() + || contextId == null + || contextId.version() != 4 + || contextId.variant() != 2) { + throw new IllegalArgumentException("Exact Game Session caller comparison is required"); + } + } + + @Override + public String toString() { + return "CallerIdentity[redacted]"; + } + } + + /** Non-authorizing readback metadata; no envelope or credential bytes are exposed. */ + public record SealedCandidateObservation( + UUID operationId, + UUID requestId, + String authorityEvidenceBundleSha256, + long issuanceFence, + long responseRecoveryExpiryEpochMillis, + String envelopeSha256, + int envelopeBytesLength) { + @Override + public String toString() { + return "SealedCandidateObservation[redacted]"; + } + } + + /** Pre-activation immutable identity read; it does not authenticate or authorize the caller. */ + public record RecoveryPreflight( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + String requestDigest, + UUID tokenJti, + long expiresAtEpochSecond, + long responseRecoveryExpiryEpochMillis) { + @Override + public String toString() { + return "RecoveryPreflight[non-authorizing,redacted]"; + } + } + + /** + * Exact compact JWT returned only after committed issuance activation and current owner reads. + */ + public static final class RecoveredCredential { + private final byte[] compactJwtBytes; + private final UUID accountId; + private final UUID tokenJti; + private final String tokenSha256; + private final String profile; + private final long expiresAtEpochSecond; + private final AccountAuthEvidenceBundle authEvidenceBundle; + + private RecoveredCredential( + byte[] compactJwtBytes, + UUID accountId, + UUID tokenJti, + String tokenSha256, + String profile, + long expiresAtEpochSecond, + AccountAuthEvidenceBundle authEvidenceBundle) { + this.compactJwtBytes = compactJwtBytes.clone(); + this.accountId = Objects.requireNonNull(accountId); + this.tokenJti = Objects.requireNonNull(tokenJti); + this.tokenSha256 = Objects.requireNonNull(tokenSha256); + this.profile = Objects.requireNonNull(profile); + this.expiresAtEpochSecond = expiresAtEpochSecond; + this.authEvidenceBundle = + Objects.requireNonNull( + authEvidenceBundle, "Verified Account auth-evidence bundle is required"); + } + + public byte[] compactJwtBytes() { + return compactJwtBytes.clone(); + } + + public UUID accountId() { + return accountId; + } + + public UUID tokenJti() { + return tokenJti; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String profile() { + return profile; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public AccountAuthEvidenceBundle authEvidenceBundle() { + return authEvidenceBundle; + } + + @Override + public String toString() { + return "RecoveredCredential[secret,redacted]"; + } + } + + /** + * Transient exact plaintext readback for the Account signer retry path. This value is not a + * caller response or authorization proof and must be closed as soon as signature verification + * finishes. + */ + public static final class PendingCandidateCredential implements AutoCloseable { + private byte[] compactJwtBytes; + private final SealedCandidateObservation sealedCandidate; + + private PendingCandidateCredential( + byte[] compactJwtBytes, SealedCandidateObservation sealedCandidate) { + this.compactJwtBytes = Objects.requireNonNull(compactJwtBytes).clone(); + this.sealedCandidate = Objects.requireNonNull(sealedCandidate); + } + + public byte[] compactJwtBytes() { + if (compactJwtBytes == null) throw new StorageUnavailableException(); + return compactJwtBytes.clone(); + } + + public SealedCandidateObservation sealedCandidate() { + return sealedCandidate; + } + + @Override + public void close() { + if (compactJwtBytes != null) { + Arrays.fill(compactJwtBytes, (byte) 0); + compactJwtBytes = null; + } + } + + @Override + public String toString() { + return "PendingCandidateCredential[secret,redacted]"; + } + } + + public static final class OperationUnavailableException extends IllegalStateException { + public OperationUnavailableException() { + super("Account gameplay delegation operation is unavailable or ambiguous"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } + + public static final class CandidateUnavailableException extends IllegalStateException { + public CandidateUnavailableException() { + super("Account signed delegation candidate is unavailable or malformed"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } + + public static final class OwnerEvidenceUnavailableException extends IllegalStateException { + public OwnerEvidenceUnavailableException() { + super("Account owner evidence is unavailable, stale, or ambiguous"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } + + public static final class AuthorityChangedException extends IllegalStateException { + public AuthorityChangedException() { + super("Account gameplay delegation authority changed"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } + + public static final class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException() { + super("Account gameplay delegation response candidate conflicts with its PENDING operation"); + } + + public String errorCode() { + return "IDEMPOTENCY_CONFLICT"; + } + } + + public static final class ResponseRecoveryExpiredException extends IllegalStateException { + public ResponseRecoveryExpiredException() { + super("Account response recovery horizon has expired"); + } + + public String errorCode() { + return "RESPONSE_RECOVERY_EXPIRED"; + } + } + + public static final class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException() { + super("Account encrypted response-envelope storage is unavailable or ambiguous"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java new file mode 100644 index 0000000000..0e9ec66408 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepository.java @@ -0,0 +1,247 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +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 net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account-row-first serialization of admission with exact-token revocation intent. Initial rows + * come only from the real SQL COMMITTED issuance writer. This is not a logout finalizer: no public + * method accepts a claimed Gateway acknowledgement or commits revocation completion. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private injected persistence context") +public class AccountGameplayTokenIdentityFenceRepository { + private static final String TABLE = "account_gameplay_token_identity_fences"; + private static final String COLUMNS = + "account_uuid, operation_id, issuance_request_id, token_hash, token_jti, " + + "not_before_epoch_second, token_generation, issuance_fence, token_identity_fence, " + + "state, revocation_request_id, revocation_digest"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep the required DSLContext precondition fail-fast; this non-final Spring repository is proxied, no partially initialized instance escapes, and it declares no finalizer.") + public AccountGameplayTokenIdentityFenceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Must precede all authority, token, operation and admission row locks in the transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public void lockAccountForUpdate(UUID accountId) { + requireTransaction(); + Objects.requireNonNull(accountId); + if (dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", accountId) + == null) throw new TokenFenceUnavailableException(); + } + + /** Exact current fence for reserve/finalize; a durable revocation intent denies immediately. */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountGameplayTokenIdentityFence requireActiveForUpdate(TokenIdentity identity) { + requireTransaction(); + Objects.requireNonNull(identity); + lockAccountForUpdate(identity.accountId()); + AccountGameplayTokenIdentityFence fence = requireExact(identity, true); + if (fence.state() != State.ACTIVE) throw new TokenRevokedException(); + return fence; + } + + /** Package-private writer called only after the real issuance COMMITTED proof was validated. */ + AccountGameplayTokenIdentityFence registerCommittedIssuance(TokenIdentity identity) { + requireTransaction(); + lockAccountForUpdate(identity.accountId()); + dsl.execute( + "INSERT INTO " + + TABLE + + " (account_uuid, operation_id, issuance_request_id, token_hash, " + + "token_jti, not_before_epoch_second, token_generation, issuance_fence) " + + "SELECT account_uuid, operation_id, request_id, token_hash, token_jti, " + + "not_before_epoch_second, token_generation, issuance_fence " + + "FROM account_gameplay_delegation_issuance_operations " + + "WHERE operation_id = ? AND request_id = ? AND account_uuid = ? " + + "AND token_hash = ? AND token_jti = ? AND not_before_epoch_second = ? " + + "AND token_generation = ? AND issuance_fence = ? AND status = 'COMMITTED' " + + "ON CONFLICT (operation_id) DO NOTHING", + identity.operationId(), + identity.issuanceRequestId(), + identity.accountId(), + identity.tokenSha256(), + identity.tokenJti(), + identity.notBeforeEpochSecond(), + identity.tokenGeneration(), + identity.issuanceFence()); + return requireActiveForUpdate(identity); + } + + /** Independent metadata readback, including the source COMMITTED identity, never registration. */ + AccountGameplayTokenIdentityFence requireActiveReadback(TokenIdentity identity) { + AccountGameplayTokenIdentityFence fence = requireExact(identity, false); + if (fence.state() != State.ACTIVE) throw new TokenRevokedException(); + return fence; + } + + /** + * Durably starts the exact bounded revocation intent. Same request/digest replays its stored + * result, and changed requests conflict. No registry deletion or logout-success claim follows. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountGameplayTokenIdentityFence beginRevocationIntent( + TokenIdentity identity, UUID requestId, String digest) { + requireTransaction(); + Objects.requireNonNull(identity); + if (!revocationDigest(identity, requestId).equals(digest)) { + throw new IllegalArgumentException("Exact Account revocation digest required"); + } + lockAccountForUpdate(identity.accountId()); + AccountGameplayTokenIdentityFence before = requireExact(identity, true); + if (before.state() != State.ACTIVE) { + if (!requestId.equals(before.revocationRequestId()) + || !digest.equals(before.revocationDigest())) { + throw new RevocationConflictException(); + } + return before; + } + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET state = 'PENDING', token_identity_fence = 2, " + + "revocation_request_id = ?, revocation_digest = ? " + + "WHERE operation_id = ? AND state = 'ACTIVE' AND token_identity_fence = 1", + requestId, + digest, + identity.operationId()); + if (changed != 1) throw new TokenFenceUnavailableException(); + AccountGameplayTokenIdentityFence after = requireExact(identity, true); + if (after.state() != State.PENDING + || !requestId.equals(after.revocationRequestId()) + || !digest.equals(after.revocationDigest())) throw new TokenFenceUnavailableException(); + return after; + } + + public static String revocationDigest(TokenIdentity identity, UUID requestId) { + Objects.requireNonNull(identity); + if (requestId == null || requestId.version() != 4 || requestId.variant() != 2) { + throw new IllegalArgumentException("Canonical UUIDv4 revocation request required"); + } + // All fields have fixed/canonical syntax, so the domain-separated framing is unambiguous. + String input = + "account-gameplay-token-revocation-intent/v1\n" + + requestId + + "\n" + + identity.accountId() + + "\n" + + identity.operationId() + + "\n" + + identity.issuanceRequestId() + + "\n" + + identity.tokenSha256() + + "\n" + + identity.tokenJti() + + "\n" + + identity.notBeforeEpochSecond() + + "\n" + + identity.tokenGeneration() + + "\n" + + identity.issuanceFence() + + "\n"; + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(input.getBytes(StandardCharsets.US_ASCII))); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private AccountGameplayTokenIdentityFence requireExact(TokenIdentity identity, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT " + + COLUMNS + + " FROM " + + TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + identity.operationId()); + if (row == null) throw new TokenFenceUnavailableException(); + AccountGameplayTokenIdentityFence fence = decode(row); + if (!identity.equals(fence.identity())) throw new TokenFenceUnavailableException(); + Record source = + dsl.fetchOne( + "SELECT operation_id FROM account_gameplay_delegation_issuance_operations " + + "WHERE operation_id = ? AND request_id = ? AND account_uuid = ? AND token_hash = ? " + + "AND token_jti = ? AND not_before_epoch_second = ? AND token_generation = ? " + + "AND issuance_fence = ? AND status = 'COMMITTED'", + identity.operationId(), + identity.issuanceRequestId(), + identity.accountId(), + identity.tokenSha256(), + identity.tokenJti(), + identity.notBeforeEpochSecond(), + identity.tokenGeneration(), + identity.issuanceFence()); + if (source == null) throw new TokenFenceUnavailableException(); + return fence; + } + + private static AccountGameplayTokenIdentityFence decode(Record row) { + try { + return new AccountGameplayTokenIdentityFence( + new TokenIdentity( + row.get("account_uuid", UUID.class), row.get("operation_id", UUID.class), + row.get("issuance_request_id", UUID.class), row.get("token_hash", String.class), + row.get("token_jti", UUID.class), row.get("not_before_epoch_second", Long.class), + row.get("token_generation", Long.class), row.get("issuance_fence", Long.class)), + row.get("token_identity_fence", Long.class), + State.valueOf(row.get("state", String.class)), + row.get("revocation_request_id", UUID.class), + row.get("revocation_digest", String.class)); + } catch (RuntimeException malformed) { + throw new TokenFenceUnavailableException(); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account transaction required"); + } + } + + public static final class TokenFenceUnavailableException extends IllegalStateException { + public TokenFenceUnavailableException() { + super("Exact Account token fence unavailable"); + } + } + + public static final class TokenRevokedException extends IllegalStateException { + public TokenRevokedException() { + super("Account token has a durable revocation fence"); + } + } + + public static final class RevocationConflictException extends IllegalStateException { + public RevocationConflictException() { + super("Account token revocation request conflicts"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwner.java new file mode 100644 index 0000000000..2605fcc317 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwner.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotEvidence; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionException; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered, authenticated owner read for one exact current Account issuer source snapshot. */ +public final class AccountIssuerSourceSnapshotReadOwner { + private final AccountAuthoritySourceEvidenceRepository sourceRepository; + private final TransactionTemplate transaction; + private final String workloadNamespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private injected source repository collaborator; the owner never exposes it") + public AccountIssuerSourceSnapshotReadOwner( + AccountAuthoritySourceEvidenceRepository sourceRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.sourceRepository = Objects.requireNonNull(sourceRepository); + this.workloadNamespace = Objects.requireNonNull(workloadNamespace); + transaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + } + + /** + * Authenticates first, then validates the closed request before opening the owner transaction. + */ + public ReadResult read(ReadCurrentIssuerAuthoritySourceRequest request) { + GrpcPeerIdentity peer = requireGameSessionPeer(); + rejectAmbientTransaction(); + if (request == null) { + throw new IllegalArgumentException("Malformed Account issuer source request"); + } + AccountIssuerSourceSnapshotGrpcCodec.ReadRequest parsed = + AccountIssuerSourceSnapshotGrpcCodec.fromRequest(request, workloadNamespace, peer.uri()); + + final AccountIssuerSourceSnapshotEvidence current; + try { + current = + Objects.requireNonNull( + transaction.execute( + ignored -> { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw failedPrecondition( + "Owned writable Account source transaction required"); + } + return readCurrent(parsed, peer); + }), + "Account issuer source transaction returned no snapshot"); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (DataAccessException | TransactionException unavailable) { + throw unavailable(); + } catch (RuntimeException unavailable) { + throw unavailable(); + } + return new ReadResult(parsed, peer.uri(), current); + } + + private AccountIssuerSourceSnapshotEvidence readCurrent( + AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request, GrpcPeerIdentity peer) { + final AccountIssuerSourceSnapshotEvidence current; + try { + var source = sourceRepository.readCurrentCanonicalIssuerSource(request.issuerId()); + IssuerGenerationProjection projection = IssuerGenerationProjection.fromSource(source); + current = + new AccountIssuerSourceSnapshotEvidence( + request.reconciliationOperationId(), + request.targetNamespace(), + peer.uri(), + projection.issuerId(), + projection.issuerAuthGeneration(), + projection.sourceVersion(), + projection.outboxStreamKey(), + projection.lastAppliedSourceOutboxSequence(), + projection.sourceEvent()); + } catch (IllegalArgumentException | IllegalStateException invalidSource) { + throw failedPrecondition("Account issuer source snapshot is unavailable or inconsistent"); + } catch (DataAccessException unavailable) { + throw unavailable(); + } + + request + .expectedSource() + .ifPresent( + expected -> { + if (!expected.equals(current)) { + throw failedPrecondition( + "Account issuer source differs from the exact expected snapshot"); + } + }); + return current; + } + + private GrpcPeerIdentity requireGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !peer.isInNamespace(workloadNamespace) + || !peer.isService("game-session-service") + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service")) { + throw Status.PERMISSION_DENIED + .withDescription("Same-namespace Game Session workload required") + .asRuntimeException(); + } + return peer; + } + + private static void rejectAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw failedPrecondition("Account issuer source read requires its own transaction"); + } + } + + private static StatusRuntimeException failedPrecondition(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } + + private static StatusRuntimeException unavailable() { + return Status.UNAVAILABLE + .withDescription("Account issuer source is temporarily unavailable") + .asRuntimeException(); + } + + /** Context required by the unregistered gRPC adapter to encode the closed response. */ + public record ReadResult( + AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request, + String authenticatedCallerWorkload, + AccountIssuerSourceSnapshotEvidence evidence) { + public ReadResult { + Objects.requireNonNull(request); + Objects.requireNonNull(authenticatedCallerWorkload); + Objects.requireNonNull(evidence); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java new file mode 100644 index 0000000000..ea4954ad03 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java @@ -0,0 +1,1315 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +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; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable Account-owned evidence for the fixed public JWT ConfigMap projection. + * + *

Every write re-locks the current desired-state row, generation operation, and exact generation + * result through {@link AccountJwtSignerDesiredStateRepository} before touching these rows. The + * repository records intent before external CAS, and its receipts/observations never authorize + * PREPARED, activation, token issuance, or readiness. + */ +@Repository +public class AccountJwtJwksPublicationRepository { + public static final String PUBLIC_JWKS_NAME = "jwt-jwks"; + public static final String JWKS_DATA_KEY = "jwks.json"; + public static final String GENERATION_MARKER_DATA_KEY = "jwt-generation.json"; + public static final int MAX_JWKS_BYTES = 256 * 1024; + public static final int MAX_MARKER_BYTES = 16 * 1024; + + private static final String INTENT_TABLE = "account_jwt_jwks_prepublication_intents"; + private static final String RECEIPT_TABLE = "account_jwt_jwks_publication_receipts"; + private static final String MOUNT_TABLE = "account_jwt_jwks_mount_observations"; + private static final String CUSTODY_MODE = "INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK"; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtJwksPublicationRepository( + DSLContext dsl, AccountJwtSignerDesiredStateRepository desiredStateRepository) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Desired-state repository is required"); + } + + /** + * Returns the current operation's immutable intent, locking its entire owner chain first. A + * missing intent stays missing; reads never create a publication request. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentIntent(Binding binding, TrustFence trust) { + requireAccountTransaction(); + GenerationResult result = readAndLockCurrentResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(result.operationId(), true); + if (intent == null) { + return Optional.empty(); + } + verifyIntentMatches(result, request, intent); + return Optional.of(intent); + } + + /** + * Persists the exact Account-constructed public projection before remote ConfigMap CAS. Only an + * exact same-operation retry can read back the existing row; a changed prior object, public + * bytes, API trust identity, generation result, or active fence is a conflict. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PrepublicationIntent recordPrepublicationIntent( + Binding binding, + TrustFence trust, + GenerationResult expectedResult, + GenerationRequest expectedRequest, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String jwksJson, + String generationMarkerJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedResult, "Exact current generation result is required"); + Objects.requireNonNull(expectedRequest, "Exact current generation request is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireDigest(expectedSnapshotDigest, "expected ConfigMap snapshot digest"); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + + GenerationResult currentResult = readAndLockCurrentResult(binding, trust); + GenerationRequest currentRequest = + desiredStateRepository.readCurrentGenerationRequest(binding, trust); + requireExactGeneration(expectedResult, currentResult, expectedRequest, currentRequest); + PrepublicationIntent candidate = + PrepublicationIntent.create( + currentResult, + currentRequest, + apiBindingDigest, + apiConfigRevision, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + jwksJson, + generationMarkerJson); + + PrepublicationIntent existing = selectIntent(currentResult.operationId(), true); + if (existing != null) { + verifyIntentMatches(currentResult, currentRequest, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account JWT JWKS publication intent changed for the same operation"); + } + return existing; + } + + insertIntent(candidate); + PrepublicationIntent readback = selectIntent(currentResult.operationId(), true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS publication intent did not read back exactly"); + } + return readback; + } + + /** Returns the current operation's persisted intent and optional exact API readback receipt. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPublication(Binding binding, TrustFence trust) { + requireAccountTransaction(); + GenerationResult result = readAndLockCurrentResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(result.operationId(), true); + if (intent == null) { + return Optional.empty(); + } + verifyIntentMatches(result, request, intent); + PublicationReceipt receipt = selectReceipt(result.operationId(), true); + if (receipt != null) { + verifyReceiptMatches(intent, receipt); + } + MountObservation mount = selectMountObservation(result.operationId(), true); + if (mount != null) { + if (receipt == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWKS observation has no Account publication receipt"); + } + verifyMountMatches(intent, receipt, mount); + } + return Optional.of( + new PublicationEvidence(intent, Optional.ofNullable(receipt), Optional.ofNullable(mount))); + } + + /** + * Recovery-only read of the immutable publication that authorized the exact PREPARED source + * generation. Ordinary current-publication reads remain unavailable while PREPARED. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public PreparedPublicationEvidence readPreparedPublicationForRecovery( + Binding binding, TrustFence trust) { + requireAccountTransaction(); + PreparedGenerationEvidence prepared = + desiredStateRepository.readPreparedGenerationForRecovery(binding, trust); + GenerationResult result = prepared.generationResult(); + PrepublicationIntent intent = selectIntent(result.operationId(), false); + PublicationReceipt receipt = selectReceipt(result.operationId(), false); + MountObservation mount = selectMountObservation(result.operationId(), false); + if (intent == null || receipt == null || mount == null) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared generation has no exact public prepublication/readback/mount evidence"); + } + verifyPreparedIntentMatches(prepared, intent); + verifyReceiptMatches(intent, receipt); + verifyMountMatches(intent, receipt, mount); + PromotionOperationEvidence promotion = prepared.promotion(); + if (!promotion.prepublicationIntentDigest().equals(intent.intentDigest()) + || !promotion.prepublicationReceiptDigest().equals(receipt.receiptDigest()) + || !promotion.mountedObservationDigest().equals(mount.observationDigest()) + || !promotion.publicConfigMapUid().equals(intent.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(receipt.observedResourceVersion()) + || !promotion.apiBindingDigest().equals(intent.apiBindingDigest()) + || !promotion.apiConfigRevision().equals(intent.apiConfigRevision()) + || !promotion.expectedPublicJwksJson().equals(intent.jwksJson())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Prepared promotion no longer matches its immutable prepublication evidence"); + } + return new PreparedPublicationEvidence(intent, receipt, mount); + } + + /** + * Persists only an exact GET readback from the protected CAS client. No Kubernetes response body, + * bearer token, or private key is stored. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PublicationReceipt recordPublicationReceipt( + Binding binding, + TrustFence trust, + UUID operationId, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String returnedResourceVersion, + String jwksJson, + String generationMarkerJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(returnedResourceVersion, "observed ConfigMap resourceVersion"); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + + GenerationResult result = readAndLockCurrentResult(binding, trust); + if (!result.operationId().equals(operationId)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Account JWT JWKS receipt is not for the current generation operation"); + } + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(operationId, true); + if (intent == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS publication intent is missing"); + } + verifyIntentMatches(result, request, intent); + if (!intent.apiBindingDigest().equals(apiBindingDigest) + || !intent.apiConfigRevision().equals(apiConfigRevision) + || !intent.configMapUid().equals(configMapUid) + || !intent.jwksJson().equals(jwksJson) + || !intent.generationMarkerJson().equals(generationMarkerJson)) { + throw new AccountJwtSignerDesiredStateRepository.BindingMismatchException( + "Account JWT JWKS readback does not match the protected publication intent"); + } + + PublicationReceipt candidate = PublicationReceipt.create(intent, returnedResourceVersion); + PublicationReceipt existing = selectReceipt(operationId, true); + if (existing != null) { + verifyReceiptMatches(intent, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account JWT JWKS readback changed for the same operation"); + } + return existing; + } + insertReceipt(candidate); + PublicationReceipt readback = selectReceipt(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt did not read back exactly"); + } + return readback; + } + + /** + * Records a local mounted private/public correspondence result only after the exact same + * operation has a persisted API publication receipt. This observation remains non-authorizing. + */ + @Transactional(propagation = Propagation.MANDATORY) + public MountObservation recordMountedCorrespondence( + Binding binding, + TrustFence trust, + UUID operationId, + String generationMarkerDigest, + String mountedPublicDataDigest, + String localPublicKeyFingerprint) { + requireWritableAccountTransaction(); + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(generationMarkerDigest, "mounted generation marker digest"); + requireDigest(mountedPublicDataDigest, "mounted public projection digest"); + requireDigest(localPublicKeyFingerprint, "mounted public-key fingerprint"); + + GenerationResult result = readAndLockCurrentResult(binding, trust); + if (!result.operationId().equals(operationId)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Mounted JWT correspondence is not for the current generation operation"); + } + PrepublicationIntent intent = selectIntent(operationId, true); + PublicationReceipt receipt = selectReceipt(operationId, true); + if (intent == null || receipt == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence has no Account publication receipt"); + } + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + verifyIntentMatches(result, request, intent); + verifyReceiptMatches(intent, receipt); + if (!intent.generationMarkerDigest().equals(generationMarkerDigest) + || !intent.publicDataDigest().equals(mountedPublicDataDigest) + || !result.publicKeyFingerprint().equals(localPublicKeyFingerprint)) { + throw new AccountJwtSignerDesiredStateRepository.BindingMismatchException( + "Mounted JWT correspondence does not match Account's exact publication"); + } + + MountObservation candidate = MountObservation.create(intent, receipt); + MountObservation existing = selectMountObservation(operationId, true); + if (existing != null) { + verifyMountMatches(intent, receipt, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Mounted JWT correspondence changed for the same operation"); + } + return existing; + } + insertMountObservation(candidate, binding); + MountObservation readback = selectMountObservation(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence did not read back exactly"); + } + return readback; + } + + private GenerationResult readAndLockCurrentResult(Binding binding, TrustFence trust) { + GenerationResult result = desiredStateRepository.readCurrentGenerationResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED + || !request.operationId().equals(result.operationId()) + || !request.operationDigest().equals(result.operationDigest()) + || !request.generationReceiptDigest().equals(result.receiptDigest()) + || !request.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !request.publicJwkJson().equals(result.publicJwkJson()) + || !request.trustFence().equals(trust)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT publication is not bound to a complete current generation result"); + } + return result; + } + + private static void requireExactGeneration( + GenerationResult expectedResult, + GenerationResult currentResult, + GenerationRequest expectedRequest, + GenerationRequest currentRequest) { + if (!expectedResult.equals(currentResult) || !expectedRequest.equals(currentRequest)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Account JWT publication candidate is not the exact current generation result"); + } + } + + private PrepublicationIntent selectIntent(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, generation_receipt_digest, " + + "desired_state_version, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, api_binding_digest, api_config_revision, " + + "config_map_name, config_map_uid, expected_resource_version, expected_snapshot_digest, " + + "target_generation, target_kid, public_key_fingerprint, expected_durable_active_json, " + + "expected_published_active_json, jwks_json, generation_marker_json, public_data_digest, " + + "generation_marker_digest, intent_digest FROM " + + INTENT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeIntent(row); + } + + private PublicationReceipt selectReceipt(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, config_map_uid, expected_resource_version, " + + "observed_resource_version, public_data_digest, receipt_digest FROM " + + RECEIPT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeReceipt(row); + } + + private MountObservation selectMountObservation(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, intent_digest, publication_receipt_digest, " + + "generation_marker_digest, public_data_digest, public_key_fingerprint, " + + "observation_digest FROM " + + MOUNT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeMountObservation(row); + } + + private void insertIntent(PrepublicationIntent intent) { + int inserted = + dsl.execute( + "INSERT INTO " + + INTENT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, generation_receipt_digest, " + + "desired_state_version, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, api_binding_digest, api_config_revision, " + + "config_map_name, config_map_uid, expected_resource_version, expected_snapshot_digest, " + + "target_generation, target_kid, public_key_fingerprint, expected_durable_active_json, " + + "expected_published_active_json, jwks_json, generation_marker_json, public_data_digest, " + + "generation_marker_digest, intent_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'jwt-jwks', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + intent.operationId(), + intent.binding().environmentId(), + intent.binding().clusterId(), + intent.binding().namespace(), + CUSTODY_MODE, + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + UUID.fromString(intent.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(intent.trustFence().expectedNamespaceUid()), + intent.trustFence().bindingDigest(), + intent.trustFence().configRevision(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + UUID.fromString(intent.configMapUid()), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + Long.parseLong(intent.targetGeneration()), + intent.targetKid(), + intent.publicKeyFingerprint(), + activeJson(intent.expectedDurableActive()), + activeJson(intent.expectedPublishedActive()), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + intent.intentDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS intent insert was ambiguous"); + } + } + + private void insertReceipt(PublicationReceipt receipt) { + int inserted = + dsl.execute( + "INSERT INTO " + + RECEIPT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, config_map_uid, expected_resource_version, " + + "observed_resource_version, public_data_digest, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.operationId(), + receipt.binding().environmentId(), + receipt.binding().clusterId(), + receipt.binding().namespace(), + receipt.binding().mode().value(), + receipt.intentDigest(), + UUID.fromString(receipt.configMapUid()), + receipt.expectedResourceVersion(), + receipt.observedResourceVersion(), + receipt.publicDataDigest(), + receipt.receiptDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS receipt insert was ambiguous"); + } + } + + private void insertMountObservation(MountObservation observation, Binding binding) { + int inserted = + dsl.execute( + "INSERT INTO " + + MOUNT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, publication_receipt_digest, " + + "generation_marker_digest, public_data_digest, public_key_fingerprint, " + + "observation_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + observation.operationId(), + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.mode().value(), + observation.intentDigest(), + observation.publicationReceiptDigest(), + observation.generationMarkerDigest(), + observation.publicDataDigest(), + observation.publicKeyFingerprint(), + observation.observationDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account mounted JWT correspondence insert was ambiguous"); + } + } + + private PrepublicationIntent decodeIntent(Record row) { + try { + Binding binding = + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + parseCustodyMode(row.get("custody_mode", String.class))); + return new PrepublicationIntent( + row.get("operation_id", UUID.class), + binding, + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + row.get("generation_receipt_digest", String.class), + positive(row.get("desired_state_version", Long.class), "desired-state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("api_binding_digest", String.class), + row.get("api_config_revision", String.class), + row.get("config_map_name", String.class), + row.get("config_map_uid", UUID.class).toString(), + row.get("expected_resource_version", String.class), + row.get("expected_snapshot_digest", String.class), + Long.toString(positive(row.get("target_generation", Long.class), "target generation")), + row.get("target_kid", String.class), + row.get("public_key_fingerprint", String.class), + parseActive(row.get("expected_durable_active_json", String.class)), + parseActive(row.get("expected_published_active_json", String.class)), + row.get("jwks_json", String.class), + row.get("generation_marker_json", String.class), + row.get("public_data_digest", String.class), + row.get("generation_marker_digest", String.class), + row.get("intent_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS intent is malformed", ex); + } + } + + private PublicationReceipt decodeReceipt(Record row) { + try { + return new PublicationReceipt( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + parseCustodyMode(row.get("custody_mode", String.class))), + row.get("intent_digest", String.class), + row.get("config_map_uid", UUID.class).toString(), + row.get("expected_resource_version", String.class), + row.get("observed_resource_version", String.class), + row.get("public_data_digest", String.class), + row.get("receipt_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt is malformed", ex); + } + } + + private MountObservation decodeMountObservation(Record row) { + try { + return new MountObservation( + row.get("operation_id", UUID.class), + row.get("intent_digest", String.class), + row.get("publication_receipt_digest", String.class), + row.get("generation_marker_digest", String.class), + row.get("public_data_digest", String.class), + row.get("public_key_fingerprint", String.class), + row.get("observation_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account mounted JWT correspondence is malformed", ex); + } + } + + private static void verifyIntentMatches( + GenerationResult result, GenerationRequest request, PrepublicationIntent intent) { + if (!intent.operationId().equals(result.operationId()) + || !intent.binding().equals(result.binding()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.trustFence().equals(result.trustFence()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(request.expectedActive()) + || !intent.expectedPublishedActive().equals(request.expectedPublishedActive()) + || !PUBLIC_JWKS_NAME.equals(intent.configMapName()) + || !PrepublicationIntent.digest(intent).equals(intent.intentDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS intent no longer matches its current generation result"); + } + } + + private static void verifyPreparedIntentMatches( + PreparedGenerationEvidence prepared, PrepublicationIntent intent) { + GenerationResult result = prepared.generationResult(); + PromotionOperationEvidence promotion = prepared.promotion(); + if (!intent.operationId().equals(result.operationId()) + || !intent.binding().equals(result.binding()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.trustFence().equals(result.trustFence()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(promotion.expectedPreviousActive()) + || !intent.expectedPublishedActive().equals(promotion.expectedPublishedActive()) + || !PUBLIC_JWKS_NAME.equals(intent.configMapName()) + || !PrepublicationIntent.digest(intent).equals(intent.intentDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Prepared Account JWKS intent does not match the exact source generation"); + } + } + + private static void verifyReceiptMatches( + PrepublicationIntent intent, PublicationReceipt receipt) { + if (!receipt.operationId().equals(intent.operationId()) + || !receipt.binding().equals(intent.binding()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !receipt.configMapUid().equals(intent.configMapUid()) + || !receipt.expectedResourceVersion().equals(intent.expectedResourceVersion()) + || !receipt.publicDataDigest().equals(intent.publicDataDigest()) + || !PublicationReceipt.digest(receipt).equals(receipt.receiptDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt is not bound to its immutable intent"); + } + } + + private static void verifyMountMatches( + PrepublicationIntent intent, PublicationReceipt receipt, MountObservation observation) { + if (!observation.operationId().equals(intent.operationId()) + || !observation.intentDigest().equals(intent.intentDigest()) + || !observation.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !observation.generationMarkerDigest().equals(intent.generationMarkerDigest()) + || !observation.publicDataDigest().equals(intent.publicDataDigest()) + || !observation.publicKeyFingerprint().equals(intent.publicKeyFingerprint()) + || !MountObservation.digest(observation).equals(observation.observationDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence is not bound to its exact Account publication"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account JWT JWKS persistence requires the owning Account transaction"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Account JWT JWKS persistence transaction must be writable"); + } + } + + private static void requireExactCurrentIdentity( + Binding binding, + TrustFence trust, + GenerationResult result, + String apiBindingDigest, + String apiConfigRevision) { + if (!result.binding().equals(binding) + || !result.trustFence().equals(trust) + || !result.trustFence().bindingDigest().equals(trust.bindingDigest()) + || !result.trustFence().configRevision().equals(trust.configRevision())) { + throw new AccountJwtSignerDesiredStateRepository.BindingMismatchException( + "Account JWT publication trust identity changed"); + } + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException ex) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS canonicalization is unavailable"); + } + } + + private static AccountJwtSignerDesiredStateRepository.CustodyMode parseCustodyMode(String value) { + for (AccountJwtSignerDesiredStateRepository.CustodyMode candidate : + AccountJwtSignerDesiredStateRepository.CustodyMode.values()) { + if (candidate.value().equals(value)) { + return candidate; + } + } + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "JWT signer custody mode is unsupported"); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static void requireDigest(String value, String field) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireRevision(String value, String field) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(); + } + } catch (RuntimeException ex) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed", ex); + } + } + + private static void requireResourceVersion(String value, String field) { + if (value == null || !RESOURCE_VERSION.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireBounded(String value, int limit, String field) { + if (value == null || value.isBlank() || value.getBytes(StandardCharsets.UTF_8).length > limit) { + throw new IllegalArgumentException("JWT signer " + field + " is missing or oversized"); + } + } + + private static long positive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalArgumentException("JWT signer " + field + " is not positive"); + } + return value; + } + + private static String activeJson(Optional active) { + Map value = new LinkedHashMap<>(); + value.put("present", active.isPresent()); + active.ifPresent( + signer -> { + value.put("generation", signer.generation()); + value.put("kid", signer.kid()); + }); + return new String(canonicalJson(value), StandardCharsets.UTF_8); + } + + private static Optional parseActive(String json) { + try { + tools.jackson.databind.JsonNode node = JSON.readTree(json); + if (node == null || !node.isObject() || !node.has("present")) { + throw new IllegalArgumentException(); + } + if (node.size() == 1 + && node.get("present").isBoolean() + && !node.get("present").booleanValue()) { + return Optional.empty(); + } + if (node.size() == 3 + && node.get("present").isBoolean() + && node.get("present").booleanValue() + && node.get("generation").isTextual() + && node.get("kid").isTextual()) { + return Optional.of( + new ActiveSigner(node.get("generation").textValue(), node.get("kid").textValue())); + } + throw new IllegalArgumentException(); + } catch (Exception ex) { + throw new IllegalArgumentException("JWT signer active fence is malformed", ex); + } + } + + /** Fixed non-secret Account intent recorded before an external ConfigMap CAS. */ + public record PrepublicationIntent( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest, + String intentDigest) { + public PrepublicationIntent { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + Objects.requireNonNull(binding, "Account JWT signer binding is required"); + requireDigest(operationDigest, "operation digest"); + requireDigest(generationRequestDigest, "generation request digest"); + requireDigest(generationReceiptDigest, "generation receipt digest"); + if (desiredStateVersion <= 1L) { + throw new IllegalArgumentException("JWT signer desired-state version is invalid"); + } + Objects.requireNonNull(trustFence, "JWT signer trust fence is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + if (!PUBLIC_JWKS_NAME.equals(configMapName)) { + throw new IllegalArgumentException("JWT signer public ConfigMap name is not fixed"); + } + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireDigest(expectedSnapshotDigest, "expected ConfigMap snapshot digest"); + if (targetGeneration == null || !targetGeneration.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("JWT signer target generation is malformed"); + } + if (targetKid == null || !targetKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("JWT signer target kid is malformed"); + } + requireDigest(publicKeyFingerprint, "public-key fingerprint"); + expectedDurableActive = Objects.requireNonNull(expectedDurableActive); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + requireDigest(publicDataDigest, "public data digest"); + requireDigest(generationMarkerDigest, "generation marker digest"); + requireDigest(intentDigest, "prepublication intent digest"); + if (!publicDataDigest.equals( + AccountJwtJwksPublicationRepository.publicDataDigest(jwksJson, generationMarkerJson)) + || !generationMarkerDigest.equals(digestUtf8(generationMarkerJson))) { + throw new IllegalArgumentException("JWT signer public projection digest is invalid"); + } + if (!intentDigest.equals( + digest( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest))) { + throw new IllegalArgumentException("JWT signer prepublication intent digest is invalid"); + } + } + + public static PrepublicationIntent create( + GenerationResult result, + GenerationRequest request, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String jwksJson, + String generationMarkerJson) { + return create( + result.operationId(), + result.binding(), + result.operationDigest(), + result.generationRequestDigest(), + result.receiptDigest(), + result.desiredStateVersion(), + result.trustFence(), + apiBindingDigest, + apiConfigRevision, + PUBLIC_JWKS_NAME, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + result.targetGeneration(), + result.targetKid(), + result.publicKeyFingerprint(), + request.expectedActive(), + request.expectedPublishedActive(), + jwksJson, + generationMarkerJson, + AccountJwtJwksPublicationRepository.publicDataDigest(jwksJson, generationMarkerJson), + digestUtf8(generationMarkerJson)); + } + + public static PrepublicationIntent create( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest) { + String intentDigest = + digest( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest); + return new PrepublicationIntent( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest, + intentDigest); + } + + static String digest(PrepublicationIntent value) { + return digest( + value.operationId(), + value.binding(), + value.operationDigest(), + value.generationRequestDigest(), + value.generationReceiptDigest(), + value.desiredStateVersion(), + value.trustFence(), + value.apiBindingDigest(), + value.apiConfigRevision(), + value.configMapName(), + value.configMapUid(), + value.expectedResourceVersion(), + value.expectedSnapshotDigest(), + value.targetGeneration(), + value.targetKid(), + value.publicKeyFingerprint(), + value.expectedDurableActive(), + value.expectedPublishedActive(), + value.jwksJson(), + value.generationMarkerJson(), + value.publicDataDigest(), + value.generationMarkerDigest()); + } + + private static String digest( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-prepublication-intent/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("environmentId", binding.environmentId()); + preimage.put("clusterId", binding.clusterId()); + preimage.put("namespace", binding.namespace()); + preimage.put("custodyMode", CUSTODY_MODE); + preimage.put("operationDigest", operationDigest); + preimage.put("generationRequestDigest", generationRequestDigest); + preimage.put("generationReceiptDigest", generationReceiptDigest); + preimage.put("desiredStateVersion", desiredStateVersion); + preimage.put("expectedClusterIncarnationUid", trustFence.expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", trustFence.expectedNamespaceUid()); + preimage.put("trustBindingDigest", trustFence.bindingDigest()); + preimage.put("trustConfigRevision", trustFence.configRevision()); + preimage.put("apiBindingDigest", apiBindingDigest); + preimage.put("apiConfigRevision", apiConfigRevision); + preimage.put("configMapName", configMapName); + preimage.put("configMapUid", configMapUid); + preimage.put("expectedResourceVersion", expectedResourceVersion); + preimage.put("expectedSnapshotDigest", expectedSnapshotDigest); + preimage.put("targetGeneration", targetGeneration); + preimage.put("targetKid", targetKid); + preimage.put("publicKeyFingerprint", publicKeyFingerprint); + preimage.put( + "expectedDurableActive", expectedDurableActive.map(ActiveSigner::generation).orElse("")); + preimage.put( + "expectedDurableActiveKid", expectedDurableActive.map(ActiveSigner::kid).orElse("")); + preimage.put( + "expectedPublishedActive", + expectedPublishedActive.map(ActiveSigner::generation).orElse("")); + preimage.put( + "expectedPublishedActiveKid", expectedPublishedActive.map(ActiveSigner::kid).orElse("")); + preimage.put("jwksJson", jwksJson); + preimage.put("generationMarkerJson", generationMarkerJson); + preimage.put("publicDataDigest", publicDataDigest); + preimage.put("generationMarkerDigest", generationMarkerDigest); + return sha256(canonicalJson(preimage)); + } + } + + /** Exact ConfigMap readback; it proves publication only, never activation/readiness. */ + public record PublicationReceipt( + UUID operationId, + Binding binding, + String intentDigest, + String configMapUid, + String expectedResourceVersion, + String observedResourceVersion, + String publicDataDigest, + String receiptDigest) { + public PublicationReceipt { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + Objects.requireNonNull(binding, "Account JWT signer binding is required"); + requireDigest(intentDigest, "prepublication intent digest"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireResourceVersion(observedResourceVersion, "observed ConfigMap resourceVersion"); + requireDigest(publicDataDigest, "published public data digest"); + requireDigest(receiptDigest, "publication receipt digest"); + if (expectedResourceVersion.equals(observedResourceVersion)) { + throw new IllegalArgumentException("Account JWT ConfigMap resourceVersion did not advance"); + } + if (!receiptDigest.equals( + digest( + operationId, + binding, + intentDigest, + configMapUid, + expectedResourceVersion, + observedResourceVersion, + publicDataDigest))) { + throw new IllegalArgumentException("Account JWT publication receipt digest is invalid"); + } + } + + public static PublicationReceipt create( + PrepublicationIntent intent, String observedResourceVersion) { + String receiptDigest = + digest( + intent.operationId(), + intent.binding(), + intent.intentDigest(), + intent.configMapUid(), + intent.expectedResourceVersion(), + observedResourceVersion, + intent.publicDataDigest()); + return new PublicationReceipt( + intent.operationId(), + intent.binding(), + intent.intentDigest(), + intent.configMapUid(), + intent.expectedResourceVersion(), + observedResourceVersion, + intent.publicDataDigest(), + receiptDigest); + } + + static String digest(PublicationReceipt value) { + return digest( + value.operationId(), + value.binding(), + value.intentDigest(), + value.configMapUid(), + value.expectedResourceVersion(), + value.observedResourceVersion(), + value.publicDataDigest()); + } + + private static String digest( + UUID operationId, + Binding binding, + String intentDigest, + String configMapUid, + String expectedResourceVersion, + String observedResourceVersion, + String publicDataDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-publication-receipt/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("environmentId", binding.environmentId()); + preimage.put("clusterId", binding.clusterId()); + preimage.put("namespace", binding.namespace()); + preimage.put("custodyMode", CUSTODY_MODE); + preimage.put("intentDigest", intentDigest); + preimage.put("configMapUid", configMapUid); + preimage.put("expectedResourceVersion", expectedResourceVersion); + preimage.put("observedResourceVersion", observedResourceVersion); + preimage.put("publicDataDigest", publicDataDigest); + return sha256(canonicalJson(preimage)); + } + } + + /** Non-secret Account-local observation of the published private/public mounted projection. */ + public record MountObservation( + UUID operationId, + String intentDigest, + String publicationReceiptDigest, + String generationMarkerDigest, + String publicDataDigest, + String publicKeyFingerprint, + String observationDigest) { + public MountObservation { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(intentDigest, "prepublication intent digest"); + requireDigest(publicationReceiptDigest, "publication receipt digest"); + requireDigest(generationMarkerDigest, "generation marker digest"); + requireDigest(publicDataDigest, "mounted public data digest"); + requireDigest(publicKeyFingerprint, "mounted public-key fingerprint"); + requireDigest(observationDigest, "mounted observation digest"); + if (!observationDigest.equals( + digest( + operationId, + intentDigest, + publicationReceiptDigest, + generationMarkerDigest, + publicDataDigest, + publicKeyFingerprint))) { + throw new IllegalArgumentException("Mounted JWT observation digest is invalid"); + } + } + + public static MountObservation create(PrepublicationIntent intent, PublicationReceipt receipt) { + String observationDigest = + digest( + intent.operationId(), + intent.intentDigest(), + receipt.receiptDigest(), + intent.generationMarkerDigest(), + intent.publicDataDigest(), + intent.publicKeyFingerprint()); + return new MountObservation( + intent.operationId(), + intent.intentDigest(), + receipt.receiptDigest(), + intent.generationMarkerDigest(), + intent.publicDataDigest(), + intent.publicKeyFingerprint(), + observationDigest); + } + + static String digest(MountObservation value) { + return digest( + value.operationId(), + value.intentDigest(), + value.publicationReceiptDigest(), + value.generationMarkerDigest(), + value.publicDataDigest(), + value.publicKeyFingerprint()); + } + + private static String digest( + UUID operationId, + String intentDigest, + String publicationReceiptDigest, + String generationMarkerDigest, + String publicDataDigest, + String publicKeyFingerprint) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-mounted-correspondence/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("intentDigest", intentDigest); + preimage.put("publicationReceiptDigest", publicationReceiptDigest); + preimage.put("generationMarkerDigest", generationMarkerDigest); + preimage.put("publicDataDigest", publicDataDigest); + preimage.put("publicKeyFingerprint", publicKeyFingerprint); + return sha256(canonicalJson(preimage)); + } + } + + public record PublicationEvidence( + PrepublicationIntent intent, + Optional receipt, + Optional mountedCorrespondence) { + public PublicationEvidence { + Objects.requireNonNull(intent); + receipt = Objects.requireNonNull(receipt); + mountedCorrespondence = Objects.requireNonNull(mountedCorrespondence); + } + } + + public record PreparedPublicationEvidence( + PrepublicationIntent intent, + PublicationReceipt receipt, + MountObservation mountedCorrespondence) { + public PreparedPublicationEvidence { + Objects.requireNonNull(intent); + Objects.requireNonNull(receipt); + Objects.requireNonNull(mountedCorrespondence); + verifyReceiptMatches(intent, receipt); + verifyMountMatches(intent, receipt, mountedCorrespondence); + } + } + + /** Canonical digest of all observed ConfigMap data used as the pre-CAS compare fence. */ + public static String snapshotDigest(Map data) { + Objects.requireNonNull(data, "ConfigMap data is required"); + if (data.size() > 128) { + throw new IllegalArgumentException("JWT public ConfigMap data has too many entries"); + } + long totalBytes = 0L; + Map bounded = new LinkedHashMap<>(); + for (Map.Entry entry : data.entrySet()) { + if (entry.getKey() == null + || entry.getKey().isBlank() + || entry.getKey().length() > 253 + || entry.getValue() == null) { + throw new IllegalArgumentException("JWT public ConfigMap data is malformed"); + } + totalBytes += entry.getKey().getBytes(StandardCharsets.UTF_8).length; + totalBytes += entry.getValue().getBytes(StandardCharsets.UTF_8).length; + if (totalBytes > 1024L * 1024L) { + throw new IllegalArgumentException("JWT public ConfigMap data is oversized"); + } + bounded.put(entry.getKey(), entry.getValue()); + } + return sha256(canonicalJson(bounded)); + } + + public static String publicDataDigest(String jwksJson, String generationMarkerJson) { + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + Map data = new LinkedHashMap<>(); + data.put(JWKS_DATA_KEY, jwksJson); + data.put(GENERATION_MARKER_DATA_KEY, generationMarkerJson); + return sha256(canonicalJson(data)); + } + + private static String digestUtf8(String value) { + return sha256(value.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java new file mode 100644 index 0000000000..63fa47891e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java @@ -0,0 +1,2701 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.PeerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.SignedProbeDigest; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +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; +import tools.jackson.databind.json.JsonMapper; + +/** + * Durable, operation-scoped readiness-probe planning and result evidence for Account's interim + * mounted signer. + * + *

This repository never advances signer lifecycle state. It can record only a validator + * observation already authenticated and verified by the owner-internal readiness service. Every + * operation re-locks and compares the existing desired-state, generation, JWKS publication, and + * mounted-correspondence authorities; probe plans are evidence attached to that owner operation, + * not a second key authority. + */ +@Repository +public class AccountJwtReadinessProbeRepository { + public static final int MAX_VALIDATOR_CACHE_AGE_SECONDS = 300; + public static final int PROBE_LIFETIME_SECONDS = 300; + public static final int MAX_ENTRIES_PER_OPERATION = 256; + public static final String INVENTORY_STATUS = "PARTIAL_UNCONFIRMED"; + + private static final String PLAN_TABLE = "account_jwt_readiness_probe_plans"; + private static final String ENTRY_TABLE = "account_jwt_readiness_probe_entries"; + private static final String DELIVERY_CLAIM_TABLE = "account_jwt_readiness_delivery_claims"; + private static final String VALIDATOR_ID = "account-service"; + private static final String CANARY_PROFILE = "account-jwt-readiness-canary"; + private static final String CANARY_AUDIENCE = "firemud-account-jwt-readiness"; + private static final String CONTROL_UI_PROFILE = ControlUiJwtProfileValidator.PROFILE; + private static final String CONTROL_UI_AUDIENCE = ControlUiJwtProfileValidator.AUDIENCE; + private static final String PLAYER_BOOTSTRAP_PROFILE = PlayerBootstrapJwtProfileValidator.PROFILE; + private static final String PLAYER_BOOTSTRAP_AUDIENCE = + PlayerBootstrapJwtProfileValidator.AUDIENCE; + private static final String REPRESENTATIVE_PROFILE = GameSessionAccountDelegationProfile.PROFILE; + private static final String REPRESENTATIVE_AUDIENCE = + GameSessionAccountDelegationProfile.AUDIENCE; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPublicationRepository publicationRepository; + private final AccountJwtValidatorInventoryRepository inventoryRepository; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators and constructs an in-memory repository; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtReadinessProbeRepository( + DSLContext dsl, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository) { + this( + dsl, + desiredStateRepository, + publicationRepository, + new AccountJwtValidatorInventoryRepository(dsl)); + } + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtReadinessProbeRepository( + DSLContext dsl, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + AccountJwtValidatorInventoryRepository inventoryRepository) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Desired-state repository is required"); + this.publicationRepository = + Objects.requireNonNull(publicationRepository, "JWKS publication repository is required"); + this.inventoryRepository = + Objects.requireNonNull(inventoryRepository, "Inventory repository is required"); + } + + /** + * Creates one immutable plan from the exact current Account operation and publication evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan planCurrent(Binding binding, TrustFence trust, Instant plannedAt) { + return planCurrent(binding, trust, plannedAt, Optional.empty()); + } + + /** + * Creates a still-partial plan bound to the exact Account-owned immutable inventory snapshot. The + * live inventory observation does not establish per-Pod acceptance or promotion evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan planCurrent( + Binding binding, TrustFence trust, Instant plannedAt, InventorySnapshot inventorySnapshot) { + return planCurrent( + binding, trust, plannedAt, Optional.of(Objects.requireNonNull(inventorySnapshot))); + } + + private ReadinessProbePlan planCurrent( + Binding binding, + TrustFence trust, + Instant plannedAt, + Optional inventorySnapshot) { + requireWritableAccountTransaction(); + Objects.requireNonNull(plannedAt, "Probe plan time is required"); + long plannedEpoch = exactEpochSecond(plannedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + UUID operationId = current.request().operationId(); + ReadinessProbePlan existing = selectPlan(operationId, true); + if (existing != null) { + requirePlanMatchesCurrent(existing, current); + if (inventorySnapshot.isPresent()) { + String requestedDigest = inventorySnapshot.orElseThrow().digest(); + if (!existing.inventorySnapshotDigest().equals(Optional.of(requestedDigest))) { + throw new InventoryPlanConflictException(); + } + inventoryRepository.readRequired(requestedDigest, binding, trust); + } + return readbackPlan(existing, true); + } + + Optional snapshotDigest = Optional.empty(); + if (inventorySnapshot.isPresent()) { + InventorySnapshot snapshot = inventorySnapshot.orElseThrow(); + requireInventorySnapshotWithinPlanWindow(snapshot, plannedEpoch); + AccountJwtValidatorInventoryRepository.StoredSnapshot stored = + inventoryRepository.persistOrReadback(snapshot, binding, trust); + snapshotDigest = Optional.of(stored.digest()); + } + ReadinessProbePlan candidate = newPlan(current, plannedEpoch, snapshotDigest); + insertPlan(candidate); + for (ProbeEntry entry : candidate.entries()) { + insertEntry(entry); + } + ReadinessProbePlan readback = selectPlan(operationId, true); + if (readback == null) { + throw new StorageUnavailableException("Account JWT readiness probe plan did not read back"); + } + requirePlanMatchesCurrent(readback, current); + if (!candidate.equals(readback)) { + throw new QuarantinedStateException("Account JWT readiness probe plan changed on readback"); + } + return readback; + } + + private static void requireInventorySnapshotWithinPlanWindow( + InventorySnapshot snapshot, long plannedEpoch) { + long observedEpoch; + try { + observedEpoch = snapshot.observedAt().getEpochSecond(); + } catch (RuntimeException failure) { + throw new InventoryPlanConflictException(); + } + if (observedEpoch <= 0L + || observedEpoch > plannedEpoch + || plannedEpoch - observedEpoch > MAX_VALIDATOR_CACHE_AGE_SECONDS) { + throw new InventoryPlanConflictException(); + } + } + + /** + * Durably claims the one transient delivery attempt for this exact current plan before signing. A + * claim is never cleared or reused: a lost response or interrupted attempt remains quarantined. + */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim claimSingleDelivery( + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .Binding + binding, + TrustFence trust, + ReadinessProbePlan expectedPlan, + net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding + readinessBinding, + PeerIdentity peer, + Instant claimedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedPlan, "Exact persisted readiness plan is required"); + Objects.requireNonNull(readinessBinding, "Authenticated readiness binding is required"); + Objects.requireNonNull(peer, "TLS-authenticated readiness peer is required"); + long claimedEpoch = exactEpochSecond(claimedAt); + if (!readinessBinding.isCurrentAt(claimedEpoch) + || !readinessBinding.matches(peer) + || !binding.environmentId().equals(readinessBinding.environmentId()) + || !binding.clusterId().equals(readinessBinding.clusterId()) + || !binding.namespace().equals(readinessBinding.namespace()) + || !trust + .expectedClusterIncarnationUid() + .equals(readinessBinding.expectedClusterIncarnationUid()) + || !trust.expectedNamespaceUid().equals(readinessBinding.expectedNamespaceUid())) { + throw new DeliveryClaimRejectedException(); + } + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedPlan.operationId().toString()); + ReadinessProbePlan stored = requireStoredPlan(current); + ReadinessProbePlan currentPlan = readbackPlan(stored, true); + if (!currentPlan.equals(expectedPlan)) { + throw new StaleOperationException( + "Readiness delivery claim does not match the exact current plan"); + } + if (claimedEpoch < currentPlan.notBeforeEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (claimedEpoch >= currentPlan.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + if (currentPlan.entries().isEmpty() + || currentPlan.entries().size() > MAX_ENTRIES_PER_OPERATION + || currentPlan.entries().stream() + .anyMatch( + entry -> + entry.state() != ProbeState.PLANNED + || entry.signingAttemptedAtEpochSecond().isPresent() + || entry.compactTokenSha256().isPresent() + || entry.verificationReceipt().isPresent())) { + throw new DeliveryAlreadyClaimedException(); + } + if (selectDeliveryClaim(currentPlan.operationId(), true) != null) { + throw new DeliveryAlreadyClaimedException(); + } + + DeliveryClaim candidate = + DeliveryClaim.create(currentPlan, trust, readinessBinding, peer, claimedEpoch); + insertDeliveryClaim(candidate); + DeliveryClaim readback = selectDeliveryClaim(candidate.rotationOperationId(), true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account readiness single-delivery claim did not read back exactly"); + } + return readback; + } + + /** Rechecks the immutable one-shot claim immediately before any pending-key signing. */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim requireCurrentDeliveryClaim( + Binding binding, + TrustFence trust, + ReadinessProbePlan expectedPlan, + DeliveryClaim expectedClaim, + Instant checkedAt) { + requireAccountTransaction(); + Objects.requireNonNull(expectedPlan, "Exact persisted readiness plan is required"); + Objects.requireNonNull(expectedClaim, "Durable single-delivery claim is required"); + long checkedEpoch = exactEpochSecond(checkedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedPlan.operationId().toString()); + ReadinessProbePlan plan = readbackPlan(requireStoredPlan(current), true); + DeliveryClaim persisted = selectDeliveryClaim(plan.operationId(), true); + if (!plan.equals(expectedPlan) + || persisted == null + || !persisted.equals(expectedClaim) + || !persisted.planDigest().equals(plan.planDigest()) + || !persisted.materializerTrustBindingDigest().equals(trust.bindingDigest()) + || !persisted.materializerTrustConfigRevision().equals(trust.configRevision()) + || !persisted.expectedClusterUid().equals(trust.expectedClusterIncarnationUid()) + || !persisted.expectedNamespaceUid().equals(trust.expectedNamespaceUid()) + || !persisted.targetGeneration().equals(plan.targetGeneration()) + || !persisted.targetKid().equals(plan.targetKid())) { + throw new DeliveryAlreadyClaimedException(); + } + if (checkedEpoch < plan.notBeforeEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (checkedEpoch >= plan.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + return persisted; + } + + /** + * Recovery-only read for the exact generation/publication currently owned by PREPARED state. The + * static applicability matrix and immutable Deployment inventory snapshot are not per-Pod + * acceptance evidence. These PARTIAL_UNCONFIRMED plans cannot satisfy promotion. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPromotionPrerequisites( + Binding binding, TrustFence trust, UUID rotationOperationId) { + // This is a nonmutating proof read, but it joins the writable lifecycle transaction because + // the existing owner evidence readers lock their rows to fence the adjacent PREPARED CAS. + requireWritableAccountTransaction(); + requireOperationId(rotationOperationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(rotationOperationId)) { + throw new StaleOperationException( + "Readiness prerequisite proof is not for Account's current operation"); + } + ReadinessProbePlan plan = selectPlan(rotationOperationId, false); + if (plan == null) { + throw new MissingPlanException("Current signer generation has no readiness plan"); + } + ReadinessProbePlan stored = readbackPlan(plan, false); + requirePlanMatchesCurrent(stored, current); + if (readinessPlanOutOfWindow(stored)) { + return Optional.empty(); + } + if (!stored.validatorInventoryComplete()) { + return Optional.empty(); + } + // The immutable inventory snapshot is not per-Pod acceptance evidence. Never upgrade the + // static matrix or receipt set into complete inventory proof. + throw new QuarantinedStateException( + "Readiness plan claims complete inventory without protected inventory evidence"); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readPromotionProof( + Binding binding, TrustFence trust, UUID rotationOperationId) { + // Recovery evidence is likewise a locked, nonmutating read inside the writable reconciliation + // transaction; do not split these reads into an unlocked read-only snapshot. + requireWritableAccountTransaction(); + requireOperationId(rotationOperationId); + var prepared = desiredStateRepository.readPreparedGenerationForRecovery(binding, trust); + var generation = prepared.generationResult(); + var promotion = prepared.promotion(); + if (!generation.operationId().equals(rotationOperationId) + || !promotion.generationOperationId().equals(rotationOperationId) + || !promotion.binding().equals(binding) + || !promotion.trustFence().equals(trust)) { + throw new StaleOperationException( + "Readiness promotion proof does not match the exact PREPARED generation"); + } + AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication = + publicationRepository.readPreparedPublicationForRecovery(binding, trust); + ReadinessProbePlan plan = selectPlan(rotationOperationId, false); + if (plan == null) { + throw new MissingPlanException("Prepared signer generation has no readiness plan"); + } + ReadinessProbePlan stored = readbackPlan(plan, false); + requirePreparedPlanMatches(stored, generation, promotion, publication); + if (readinessPlanOutOfWindow(stored)) { + return Optional.empty(); + } + if (!stored.validatorInventoryComplete()) { + return Optional.empty(); + } + // The immutable inventory snapshot is not per-Pod acceptance evidence. Never upgrade the + // static matrix or receipt set into complete inventory proof. + throw new QuarantinedStateException( + "Readiness plan claims complete inventory without protected inventory evidence"); + } + + private boolean readinessPlanOutOfWindow(ReadinessProbePlan plan) { + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account readiness database clock readback is unavailable"); + } + return databaseNow < plan.notBeforeEpochSecond() || databaseNow >= plan.expiresAtEpochSecond(); + } + + /** Reads one plan only while its original generation and publication evidence remain current. */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan readCurrentPlan(Binding binding, TrustFence trust, UUID operationId) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(operationId)) { + throw new StaleOperationException( + "Readiness probe plan is not for Account's current operation"); + } + ReadinessProbePlan stored = selectPlan(operationId, true); + if (stored == null) { + throw new MissingPlanException("Account JWT readiness probe plan is missing"); + } + requirePlanMatchesCurrent(stored, current); + return readbackPlan(stored, true); + } + + /** Reads one exact current probe selected by the complete key and its immutable JTI. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry readCurrentEntry( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || !entry.jti().equals(jti) + || !entry.planDigest().equals(plan.planDigest())) { + throw new StaleOperationException("Readiness probe selector is not the exact current entry"); + } + return entry; + } + + /** + * Records only the exact authenticated, cryptographically verified observation for one current + * ISSUED entry. A matching VERIFIED retry reads back the original immutable receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordVerified( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + VerifiedProbeObservation observation) { + requireWritableAccountTransaction(); + requireOperationId(operationId); + Objects.requireNonNull(observation, "Authenticated verification observation is required"); + long observedAt = exactEpochSecond(Instant.ofEpochSecond(observation.observedAtEpochSecond())); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || !entry.jti().equals(jti) + || !entry.planDigest().equals(plan.planDigest()) + || !entry.targetGeneration().equals(plan.targetGeneration()) + || !entry.targetKid().equals(plan.targetKid()) + || !entry.expectedActive().equals(plan.expectedFence().durableActive()) + || !entry.expectedActive().equals(plan.expectedFence().publishedActive()) + || entry.registryVersion() != 1 + || !entry.compactTokenSha256().equals(Optional.of(observation.compactTokenSha256())) + || !entry.targetKid().equals(observation.verifiedKid())) { + throw new StaleOperationException( + "Verified readiness probe does not match the exact current operation entry"); + } + requireNotExpired(entry, observedAt); + if (observedAt < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + + if (entry.state() == ProbeState.VERIFIED) { + VerificationReceipt existing = + entry + .verificationReceipt() + .orElseThrow( + () -> + new QuarantinedStateException( + "Verified readiness entry has no immutable receipt")); + requireMatchingObservation(existing, observation); + return entry; + } + if (entry.state() != ProbeState.ISSUED || entry.verificationReceipt().isPresent()) { + throw new AmbiguousDeliveryException("Readiness probe is not the exact current ISSUED entry"); + } + + long resultEntryVersion = Math.addExact(entry.entryVersion(), 1L); + VerificationReceipt receipt = verificationReceipt(plan, entry, observation, resultEntryVersion); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'VERIFIED', entry_version = ?, verification_receipt_version = ?, " + + "verification_source_entry_version = ?, verified_at_epoch_seconds = ?, " + + "verified_kid = ?, validator_instance_id = ?, validator_binding_digest = ?, " + + "validator_config_revision = ?, validator_peer_uri = ?, " + + "validator_peer_spki_sha256 = ?, verification_receipt_sha256 = ? " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND jti = ? AND plan_digest = ? " + + "AND state = 'ISSUED' AND entry_version = ? AND target_generation = ? " + + "AND target_kid = ? AND compact_token_sha256 = ? " + + "AND verification_receipt_sha256 IS NULL " + + "AND CURRENT_TIMESTAMP >= to_timestamp(planned_issued_at_epoch_seconds) " + + "AND CURRENT_TIMESTAMP < to_timestamp(expires_at_epoch_seconds)", + receipt.resultEntryVersion(), + receipt.receiptVersion(), + receipt.sourceEntryVersion(), + receipt.observedAtEpochSecond(), + receipt.verifiedKid(), + receipt.validatorInstanceId(), + receipt.validatorBindingDigest(), + receipt.validatorConfigRevision(), + receipt.validatorPeerUri(), + receipt.validatorPeerSpkiSha256(), + receipt.receiptSha256(), + operationId, + validatorId, + tokenProfile, + audience, + probeKind.name(), + jti, + plan.planDigest(), + entry.entryVersion(), + Long.parseLong(plan.targetGeneration()), + plan.targetKid(), + observation.compactTokenSha256()); + if (changed != 1) { + throw new VersionConflictException("Readiness VERIFIED transition lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != ProbeState.VERIFIED + || readback.entryVersion() != receipt.resultEntryVersion() + || readback.verificationReceipt().filter(receipt::equals).isEmpty()) { + throw new QuarantinedStateException("Verified readiness receipt did not read back exactly"); + } + return readback; + } + + /** + * Pins the exact signed-token hash before delivery. A row with this pin but no ISSUED result is + * ambiguous after a crash and must be quarantined; it is never signed or delivered again. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordSigningAttempt( + Binding binding, TrustFence trust, SignedProbeDigest signed, Instant attemptedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(signed, "Mounted signer result is required"); + long attemptedEpoch = exactEpochSecond(attemptedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, signed.operationId()); + ReadinessProbePlan plan = requireStoredPlan(current); + ProbeEntry entry = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + requireSignedResultMatches(plan, entry, signed); + requireNotExpired(entry, attemptedEpoch); + if (attemptedEpoch < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (entry.state() != ProbeState.PLANNED + || entry.compactTokenSha256().isPresent() + || entry.signingAttemptedAtEpochSecond().isPresent()) { + throw new AmbiguousDeliveryException("Readiness probe already has a signing attempt"); + } + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET signing_attempted_at_epoch_seconds = ?, compact_token_sha256 = ?, " + + "entry_version = entry_version + 1 WHERE rotation_operation_id = ? " + + "AND validator_id = ? AND token_profile = ? AND audience = ? AND probe_kind = ? " + + "AND plan_digest = ? AND state = 'PLANNED' AND entry_version = ? " + + "AND compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL", + attemptedEpoch, + signed.compactTokenSha256(), + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind().name(), + plan.planDigest(), + entry.entryVersion()); + if (changed != 1) { + throw new VersionConflictException("Readiness probe signing attempt lost its exact CAS"); + } + ProbeEntry readback = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + if (readback == null + || readback.state() != ProbeState.PLANNED + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256())) + || !readback.signingAttemptedAtEpochSecond().equals(Optional.of(attemptedEpoch))) { + throw new QuarantinedStateException( + "Readiness probe signing attempt did not read back exactly"); + } + return readback; + } + + /** Durably records ISSUED before the exact compact probe reaches its transient consumer. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordIssued( + Binding binding, TrustFence trust, SignedProbeDigest signed, Instant issuedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(signed, "Mounted signer result is required"); + long issuedEpoch = exactEpochSecond(issuedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, signed.operationId()); + ReadinessProbePlan plan = requireStoredPlan(current); + ProbeEntry entry = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + requireSignedResultMatches(plan, entry, signed); + requireNotExpired(entry, issuedEpoch); + if (issuedEpoch < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (entry.state() == ProbeState.ISSUED) { + if (!entry.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256()))) { + throw new IdempotencyConflictException("Issued readiness probe hash changed"); + } + return entry; + } + if (entry.state() != ProbeState.PLANNED + || !entry.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256())) + || entry.signingAttemptedAtEpochSecond().isEmpty()) { + throw new AmbiguousDeliveryException("Readiness probe is not pinned for exact delivery"); + } + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'ISSUED', entry_version = entry_version + 1 " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND plan_digest = ? " + + "AND state = 'PLANNED' AND entry_version = ? AND compact_token_sha256 = ? " + + "AND signing_attempted_at_epoch_seconds IS NOT NULL", + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind().name(), + plan.planDigest(), + entry.entryVersion(), + signed.compactTokenSha256()); + if (changed != 1) { + throw new VersionConflictException("Readiness probe ISSUED transition lost its exact CAS"); + } + ProbeEntry readback = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + if (readback == null + || readback.state() != ProbeState.ISSUED + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256()))) { + throw new QuarantinedStateException("Issued readiness probe did not read back exactly"); + } + return readback; + } + + /** Quarantines a pinned PLANNED attempt after delivery or persistence became ambiguous. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry abortAmbiguousAttempt( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + Instant terminalAt) { + requireWritableAccountTransaction(); + long terminalEpoch = exactEpochSecond(terminalAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + requireStoredPlan(current); + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || entry.state() != ProbeState.PLANNED + || entry.compactTokenSha256().isEmpty()) { + throw new AmbiguousDeliveryException("No ambiguous pinned readiness attempt exists"); + } + return transitionTerminal(entry, ProbeState.ABORTED, terminalEpoch); + } + + /** Aborts only entries belonging to the exact current Account operation. */ + @Transactional(propagation = Propagation.MANDATORY) + public List abortCurrent( + Binding binding, TrustFence trust, UUID operationId, Instant terminalAt) { + requireWritableAccountTransaction(); + long terminalEpoch = exactEpochSecond(terminalAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + List result = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ProbeEntry currentEntry = selectEntry(entry, true); + if (currentEntry.state() == ProbeState.PLANNED + || currentEntry.state() == ProbeState.ISSUED + || currentEntry.state() == ProbeState.VERIFIED) { + result.add(transitionTerminal(currentEntry, ProbeState.ABORTED, terminalEpoch)); + } else { + result.add(currentEntry); + } + } + return List.copyOf(result); + } + + /** Expires only this exact current operation after its immutable entry expiry. */ + @Transactional(propagation = Propagation.MANDATORY) + public List expireCurrent( + Binding binding, TrustFence trust, UUID operationId, Instant now) { + requireWritableAccountTransaction(); + long nowEpoch = exactEpochSecond(now); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + List result = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ProbeEntry currentEntry = selectEntry(entry, true); + if ((currentEntry.state() == ProbeState.PLANNED + || currentEntry.state() == ProbeState.ISSUED + || currentEntry.state() == ProbeState.VERIFIED) + && nowEpoch >= currentEntry.expiresAtEpochSecond()) { + result.add(transitionTerminal(currentEntry, ProbeState.EXPIRED, nowEpoch)); + } else { + result.add(currentEntry); + } + } + return List.copyOf(result); + } + + /** + * Bounded cleanup of terminal entries for one explicit operation. It never queries or scans + * another operation and retains all non-secret identity/hash/terminal evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public List cleanTerminalEntries(UUID operationId, int maximumEntries) { + requireWritableAccountTransaction(); + requireOperationId(operationId); + if (maximumEntries < 1 || maximumEntries > MAX_ENTRIES_PER_OPERATION) { + throw new IllegalArgumentException("Readiness cleanup bound is outside its fixed limit"); + } + Result terminalRows = + dsl.fetch( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? AND state IN ('ABORTED', 'EXPIRED') " + + "ORDER BY validator_id, token_profile, audience, probe_kind LIMIT ? FOR UPDATE", + operationId, + maximumEntries); + if (terminalRows.size() > maximumEntries) { + throw new QuarantinedStateException("Readiness cleanup exceeded its exact operation bound"); + } + List cleaned = new ArrayList<>(); + for (Record row : terminalRows) { + ProbeEntry entry = decodeEntry(row); + cleaned.add(transitionTerminal(entry, ProbeState.CLEANED, null)); + } + return List.copyOf(cleaned); + } + + private ProbeEntry transitionTerminal(ProbeEntry entry, ProbeState target, Long transitionEpoch) { + if (target == ProbeState.EXPIRED && transitionEpoch == null) { + throw new IllegalArgumentException("Expiry time is required"); + } + String outcome = + target == ProbeState.CLEANED ? entry.terminalOutcome().orElseThrow() : target.name(); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = ?, terminal_outcome = ?, entry_version = entry_version + 1 " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND state = ? AND entry_version = ?", + target.name(), + outcome, + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name(), + entry.state().name(), + entry.entryVersion()); + if (changed != 1) { + throw new VersionConflictException("Readiness terminal transition lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != target + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.terminalOutcome().equals(Optional.of(outcome))) { + throw new QuarantinedStateException( + "Readiness terminal transition did not read back exactly"); + } + return readback; + } + + private ReadinessProbePlan newPlan( + CurrentEvidence current, + long plannedAtEpochSecond, + Optional inventorySnapshotDigest) { + long notBefore = add(plannedAtEpochSecond, MAX_VALIDATOR_CACHE_AGE_SECONDS); + long expiresAt = add(notBefore, PROBE_LIFETIME_SECONDS); + String matrixJson = applicabilityMatrixJson(); + String matrixDigest = sha256(matrixJson.getBytes(StandardCharsets.UTF_8)); + List entries = + List.of( + newEntry( + current, + ProbeKind.CANARY, + CANARY_PROFILE, + CANARY_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + ProbeKind.REPRESENTATIVE, + CONTROL_UI_PROFILE, + CONTROL_UI_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + ProbeKind.REPRESENTATIVE, + PLAYER_BOOTSTRAP_PROFILE, + PLAYER_BOOTSTRAP_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + ProbeKind.REPRESENTATIVE, + REPRESENTATIVE_PROFILE, + REPRESENTATIVE_AUDIENCE, + notBefore, + expiresAt)) + .stream() + .sorted(PROBE_ENTRY_ORDER) + .toList(); + String planDigest = + planDigest( + current, + matrixJson, + matrixDigest, + plannedAtEpochSecond, + notBefore, + expiresAt, + entries, + inventorySnapshotDigest); + List boundEntries = + entries.stream().map(entry -> entry.withPlanDigest(planDigest)).toList(); + return ReadinessProbePlan.fromCurrent( + current, + matrixJson, + matrixDigest, + false, + MAX_VALIDATOR_CACHE_AGE_SECONDS, + plannedAtEpochSecond, + notBefore, + expiresAt, + planDigest, + boundEntries, + inventorySnapshotDigest); + } + + private static ProbeEntry newEntry( + CurrentEvidence current, + ProbeKind kind, + String profile, + String audience, + long notBefore, + long expiresAt) { + return new ProbeEntry( + current.request().operationId(), + "0".repeat(64), + VALIDATOR_ID, + profile, + audience, + kind, + UUID.randomUUID(), + current.request().targetGeneration(), + current.request().targetKid(), + current.state().durableActive(), + 1, + 1, + notBefore, + expiresAt, + ProbeState.PLANNED, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); + } + + private void insertPlan(ReadinessProbePlan plan) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", plan.operationId()); + fields.put("environment_id", plan.binding().environmentId()); + fields.put("cluster_id", plan.binding().clusterId()); + fields.put("kubernetes_namespace", plan.binding().namespace()); + fields.put("custody_mode", plan.binding().mode().value()); + fields.put("operation_digest", plan.operationDigest()); + fields.put("generation_request_digest", plan.generationRequestDigest()); + fields.put("generation_receipt_digest", plan.generationReceiptDigest()); + fields.put("desired_state_version", plan.desiredStateVersion()); + fields.put( + "expected_cluster_incarnation_uid", + UUID.fromString(plan.trustFence().expectedClusterIncarnationUid())); + fields.put("expected_namespace_uid", UUID.fromString(plan.trustFence().expectedNamespaceUid())); + fields.put("trust_binding_digest", plan.trustFence().bindingDigest()); + fields.put("trust_config_revision", plan.trustFence().configRevision()); + fields.put("target_generation", Long.parseLong(plan.targetGeneration())); + fields.put("target_kid", plan.targetKid()); + fields.put("target_public_key_fingerprint", plan.targetPublicKeyFingerprint()); + fields.put( + "expected_active_generation", + plan.expectedFence() + .durableActive() + .map(value -> Long.parseLong(value.generation())) + .orElse(null)); + fields.put( + "expected_active_kid", + plan.expectedFence().durableActive().map(ActiveSigner::kid).orElse(null)); + fields.put( + "expected_published_generation", + plan.expectedFence() + .publishedActive() + .map(value -> Long.parseLong(value.generation())) + .orElse(null)); + fields.put( + "expected_published_kid", + plan.expectedFence().publishedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("publication_intent_digest", plan.publicationIntentDigest()); + fields.put("publication_receipt_digest", plan.publicationReceiptDigest()); + fields.put("mounted_observation_digest", plan.mountedObservationDigest()); + fields.put("applicability_matrix_json", plan.applicabilityMatrixJson()); + fields.put("applicability_matrix_digest", plan.applicabilityMatrixDigest()); + fields.put("validator_inventory_complete", plan.validatorInventoryComplete()); + fields.put("inventory_snapshot_digest", plan.inventorySnapshotDigest().orElse(null)); + fields.put("maximum_cache_age_seconds", plan.maximumCacheAgeSeconds()); + fields.put("planned_at_epoch_seconds", plan.plannedAtEpochSecond()); + fields.put("not_before_epoch_seconds", plan.notBeforeEpochSecond()); + fields.put("expires_at_epoch_seconds", plan.expiresAtEpochSecond()); + fields.put("plan_version", 1); + fields.put("plan_digest", plan.planDigest()); + insertOne(dsl, PLAN_TABLE, fields); + } + + private void insertDeliveryClaim(DeliveryClaim claim) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", claim.rotationOperationId()); + fields.put("plan_digest", claim.planDigest()); + fields.put("expected_cluster_incarnation_uid", UUID.fromString(claim.expectedClusterUid())); + fields.put("expected_namespace_uid", UUID.fromString(claim.expectedNamespaceUid())); + fields.put("materializer_trust_binding_digest", claim.materializerTrustBindingDigest()); + fields.put("materializer_trust_config_revision", claim.materializerTrustConfigRevision()); + fields.put("target_generation", Long.parseLong(claim.targetGeneration())); + fields.put("target_kid", claim.targetKid()); + fields.put( + "expected_active_generation", + claim.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null)); + fields.put("expected_active_kid", claim.expectedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("readiness_binding_digest", claim.readinessBindingDigest()); + fields.put("readiness_config_revision", claim.readinessConfigRevision()); + fields.put( + "readiness_binding_valid_until_epoch_seconds", + claim.readinessBindingValidUntilEpochSecond()); + fields.put("validator_id", claim.validatorId()); + fields.put("validator_instance_id", claim.validatorInstanceId()); + fields.put("validator_peer_uri", claim.validatorPeerUri()); + fields.put("validator_peer_spki_sha256", claim.validatorPeerSpkiSha256()); + fields.put("claimed_at_epoch_seconds", claim.claimedAtEpochSecond()); + fields.put("expires_at_epoch_seconds", claim.expiresAtEpochSecond()); + fields.put("claim_digest", claim.claimDigest()); + insertOne(dsl, DELIVERY_CLAIM_TABLE, fields); + } + + private DeliveryClaim selectDeliveryClaim(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + DELIVERY_CLAIM_TABLE + + " WHERE rotation_operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + if (row == null) { + return null; + } + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + DeliveryClaim result = + new DeliveryClaim( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("materializer_trust_binding_digest", String.class), + row.get("materializer_trust_config_revision", String.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + decodeActive(activeGeneration, activeKid), + row.get("readiness_binding_digest", String.class), + row.get("readiness_config_revision", String.class), + row.get("readiness_binding_valid_until_epoch_seconds", Long.class), + row.get("validator_id", String.class), + row.get("validator_instance_id", String.class), + row.get("validator_peer_uri", String.class), + row.get("validator_peer_spki_sha256", String.class), + row.get("claimed_at_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + row.get("claim_digest", String.class)); + if (!result.claimDigest().equals(deliveryClaimDigest(result))) { + throw new QuarantinedStateException("Account readiness delivery claim digest is invalid"); + } + return result; + } + + private void insertEntry(ProbeEntry entry) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", entry.rotationOperationId()); + fields.put("plan_digest", entry.planDigest()); + fields.put("validator_id", entry.validatorId()); + fields.put("token_profile", entry.tokenProfile()); + fields.put("audience", entry.audience()); + fields.put("probe_kind", entry.probeKind().name()); + fields.put("jti", entry.jti()); + fields.put("target_generation", Long.parseLong(entry.targetGeneration())); + fields.put("target_kid", entry.targetKid()); + fields.put( + "expected_active_generation", + entry.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null)); + fields.put("expected_active_kid", entry.expectedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("registry_version", entry.registryVersion()); + fields.put("entry_version", entry.entryVersion()); + fields.put("planned_issued_at_epoch_seconds", entry.plannedIssuedAtEpochSecond()); + fields.put("expires_at_epoch_seconds", entry.expiresAtEpochSecond()); + fields.put("state", entry.state().name()); + fields.put("terminal_outcome", null); + fields.put("signing_attempted_at_epoch_seconds", null); + fields.put("compact_token_sha256", null); + insertOne(dsl, ENTRY_TABLE, fields); + } + + private ReadinessProbePlan selectPlan(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + PLAN_TABLE + + " WHERE rotation_operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodePlan(row, selectEntries(operationId, lock)); + } + + private ReadinessProbePlan readbackPlan(ReadinessProbePlan plan, boolean lock) { + List entries = selectEntries(plan.operationId(), lock); + if (!entries.equals(plan.entries())) { + throw new QuarantinedStateException("Readiness probe entries changed after plan persistence"); + } + if (!plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException("Readiness probe plan digest is invalid"); + } + plan.inventorySnapshotDigest() + .ifPresent( + digest -> inventoryRepository.readRequired(digest, plan.binding(), plan.trustFence())); + return plan; + } + + private List selectEntries(UUID operationId, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? ORDER BY validator_id, CASE token_profile WHEN '" + + CANARY_PROFILE + + "' THEN 0 WHEN '" + + CONTROL_UI_PROFILE + + "' THEN 1 WHEN '" + + PLAYER_BOOTSTRAP_PROFILE + + "' THEN 2 WHEN '" + + REPRESENTATIVE_PROFILE + + "' THEN 3 ELSE 4 END, token_profile, audience, probe_kind" + + (lock ? " FOR UPDATE" : ""), + operationId); + List entries = new ArrayList<>(rows.size()); + for (Record row : rows) { + entries.add(decodeEntry(row)); + } + return List.copyOf(entries); + } + + // Keep the candidate's digest/equality order identical to the durable key order. If a future + // schema adds identity dimensions (for example Pod membership), append them to both this + // comparator and SELECT's ORDER BY; V1 plans retain their existing tuple and digest semantics. + private static final Comparator PROBE_ENTRY_ORDER = + Comparator.comparing(ProbeEntry::validatorId) + // V1 plan digests bind the established tuple order. Keep it explicit and shared with + // durable readback while appending any future identity dimensions consistently. + .thenComparingInt(entry -> profileOrder(entry.tokenProfile())) + .thenComparing(ProbeEntry::audience) + .thenComparing(entry -> entry.probeKind().name()); + + private static int profileOrder(String profile) { + if (CANARY_PROFILE.equals(profile)) return 0; + if (CONTROL_UI_PROFILE.equals(profile)) return 1; + if (PLAYER_BOOTSTRAP_PROFILE.equals(profile)) return 2; + if (REPRESENTATIVE_PROFILE.equals(profile)) return 3; + throw new QuarantinedStateException("Readiness probe profile has no canonical plan order"); + } + + private ProbeEntry selectEntry( + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ?" + + (lock ? " FOR UPDATE" : ""), + operationId, + validatorId, + tokenProfile, + audience, + probeKind.name()); + return row == null ? null : decodeEntry(row); + } + + private ProbeEntry selectEntry(ProbeEntry entry, boolean lock) { + return selectEntry( + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + lock); + } + + private ProbeEntry decodeEntry(Record row) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + Optional expectedActive = decodeActive(activeGeneration, activeKid); + Long attemptAt = row.get("signing_attempted_at_epoch_seconds", Long.class); + String hash = row.get("compact_token_sha256", String.class); + String terminalOutcome = row.get("terminal_outcome", String.class); + VerificationReceipt receipt = decodeVerificationReceipt(row); + return new ProbeEntry( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("jti", UUID.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + expectedActive, + row.get("registry_version", Short.class).intValue(), + row.get("entry_version", Long.class), + row.get("planned_issued_at_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + ProbeState.valueOf(row.get("state", String.class)), + Optional.ofNullable(terminalOutcome), + Optional.ofNullable(attemptAt), + Optional.ofNullable(hash), + Optional.ofNullable(receipt)); + } + + private VerificationReceipt decodeVerificationReceipt(Record row) { + Short version = row.get("verification_receipt_version", Short.class); + Long sourceVersion = row.get("verification_source_entry_version", Long.class); + Long verifiedAt = row.get("verified_at_epoch_seconds", Long.class); + String verifiedKid = row.get("verified_kid", String.class); + String validatorInstanceId = row.get("validator_instance_id", String.class); + String bindingDigest = row.get("validator_binding_digest", String.class); + String configRevision = row.get("validator_config_revision", String.class); + String peerUri = row.get("validator_peer_uri", String.class); + String peerSpki = row.get("validator_peer_spki_sha256", String.class); + String receiptSha256 = row.get("verification_receipt_sha256", String.class); + if (version == null + && sourceVersion == null + && verifiedAt == null + && verifiedKid == null + && validatorInstanceId == null + && bindingDigest == null + && configRevision == null + && peerUri == null + && peerSpki == null + && receiptSha256 == null) { + return null; + } + if (version == null + || sourceVersion == null + || verifiedAt == null + || verifiedKid == null + || validatorInstanceId == null + || bindingDigest == null + || configRevision == null + || peerUri == null + || peerSpki == null + || receiptSha256 == null) { + throw new QuarantinedStateException("Readiness verification receipt is partial"); + } + Long resultVersion = Math.addExact(sourceVersion, 1L); + return new VerificationReceipt( + version.intValue(), + sourceVersion, + resultVersion, + verifiedAt, + receiptSha256, + verifiedKid, + validatorInstanceId, + bindingDigest, + configRevision, + peerUri, + peerSpki); + } + + private ReadinessProbePlan decodePlan(Record row, List entries) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + Long publishedGeneration = row.get("expected_published_generation", Long.class); + String publishedKid = row.get("expected_published_kid", String.class); + SignerFence fence = + new SignerFence( + decodeActive(activeGeneration, activeKid), + decodeActive(publishedGeneration, publishedKid)); + return new ReadinessProbePlan( + row.get("rotation_operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + AccountJwtSignerDesiredStateRepository.CustodyMode + .INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + row.get("generation_receipt_digest", String.class), + row.get("desired_state_version", Long.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + row.get("target_public_key_fingerprint", String.class), + fence, + row.get("publication_intent_digest", String.class), + row.get("publication_receipt_digest", String.class), + row.get("mounted_observation_digest", String.class), + row.get("applicability_matrix_json", String.class), + row.get("applicability_matrix_digest", String.class), + row.get("validator_inventory_complete", Boolean.class), + row.get("maximum_cache_age_seconds", Short.class).intValue(), + row.get("planned_at_epoch_seconds", Long.class), + row.get("not_before_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + row.get("plan_version", Short.class).intValue(), + row.get("plan_digest", String.class), + entries, + Optional.ofNullable(row.get("inventory_snapshot_digest", String.class))); + } + + private static Optional decodeActive(Long generation, String kid) { + if (generation == null && kid == null) { + return Optional.empty(); + } + if (generation == null || kid == null) { + throw new QuarantinedStateException("Readiness signer fence has a partial active pair"); + } + return Optional.of(new ActiveSigner(generation.toString(), kid)); + } + + private void requirePlanMatchesCurrent(ReadinessProbePlan plan, CurrentEvidence current) { + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = current.publication(); + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = + publication.receipt().orElseThrow(); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication.mountedCorrespondence().orElseThrow(); + if (!plan.operationId().equals(request.operationId()) + || !plan.binding().equals(request.binding()) + || !plan.trustFence().equals(request.trustFence()) + || !plan.operationDigest().equals(request.operationDigest()) + || !plan.generationRequestDigest().equals(result.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(result.receiptDigest()) + || plan.desiredStateVersion() != result.desiredStateVersion() + || !plan.targetGeneration().equals(result.targetGeneration()) + || !plan.targetKid().equals(result.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !plan.expectedFence().durableActive().equals(request.expectedActive()) + || !plan.expectedFence().publishedActive().equals(request.expectedPublishedActive()) + || !plan.publicationIntentDigest().equals(intent.intentDigest()) + || !plan.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !plan.mountedObservationDigest().equals(mount.observationDigest()) + || !plan.applicabilityMatrixJson().equals(applicabilityMatrixJson()) + || !plan.applicabilityMatrixDigest() + .equals(sha256(plan.applicabilityMatrixJson().getBytes(StandardCharsets.UTF_8))) + || plan.validatorInventoryComplete() + || !plan.planDigest().equals(planDigest(plan))) { + throw new StaleOperationException( + "Readiness probe plan no longer matches current Account evidence"); + } + } + + private static void requirePreparedPlanMatches( + ReadinessProbePlan plan, + GenerationResult generation, + AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence promotion, + AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication) { + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = publication.receipt(); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication.mountedCorrespondence(); + if (!plan.operationId().equals(generation.operationId()) + || !plan.binding().equals(generation.binding()) + || !plan.trustFence().equals(generation.trustFence()) + || !plan.operationDigest().equals(generation.operationDigest()) + || !plan.generationRequestDigest().equals(generation.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(generation.receiptDigest()) + || plan.desiredStateVersion() != generation.desiredStateVersion() + || !plan.targetGeneration().equals(generation.targetGeneration()) + || !plan.targetKid().equals(generation.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(generation.publicKeyFingerprint()) + || !plan.expectedFence().durableActive().equals(promotion.expectedPreviousActive()) + || !plan.expectedFence().publishedActive().equals(promotion.expectedPublishedActive()) + || !plan.publicationIntentDigest().equals(intent.intentDigest()) + || !plan.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !plan.mountedObservationDigest().equals(mount.observationDigest()) + || !plan.planDigest().equals(promotion.readinessPlanDigest()) + || !intent.operationId().equals(generation.operationId()) + || !receipt.operationId().equals(generation.operationId()) + || !mount.operationId().equals(generation.operationId()) + || !promotion.prepublicationIntentDigest().equals(intent.intentDigest()) + || !promotion.prepublicationReceiptDigest().equals(receipt.receiptDigest()) + || !promotion.mountedObservationDigest().equals(mount.observationDigest()) + || !promotion.publicConfigMapUid().equals(intent.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(receipt.observedResourceVersion()) + || !promotion.expectedPublicJwksJson().equals(intent.jwksJson()) + || !promotion.apiBindingDigest().equals(intent.apiBindingDigest()) + || !promotion.apiConfigRevision().equals(intent.apiConfigRevision()) + || !plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException( + "Prepared readiness evidence differs from exact Account generation/publication owner records"); + } + } + + private CurrentEvidence lockCurrentEvidence(Binding binding, TrustFence trust) { + Objects.requireNonNull(binding, "Account signer binding is required"); + Objects.requireNonNull(trust, "Current signer trust fence is required"); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + GenerationResult result = desiredStateRepository.readCurrentGenerationResult(binding, trust); + DesiredState state = desiredStateRepository.read(binding); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = + publicationRepository + .readCurrentPublication(binding, trust) + .orElseThrow(() -> new MissingPublicationEvidenceException()); + if (request.phase() != GenerationPhase.GENERATION_RECORDED + || state.preparedOperationId().isPresent() + || !state.generationOperationId().equals(Optional.of(request.operationId())) + || !request.operationId().equals(result.operationId()) + || !request.binding().equals(binding) + || !result.binding().equals(binding) + || !request.trustFence().equals(trust) + || !result.trustFence().equals(trust) + || state.recordVersion() != result.desiredStateVersion() + || !request.targetGeneration().equals(result.targetGeneration()) + || !request.targetKid().equals(result.targetKid()) + || !request.expectedActive().equals(state.durableActive()) + || !request.expectedPublishedActive().equals(state.publishedActive()) + || !state.durableActive().equals(state.publishedActive())) { + throw new StaleOperationException( + "Current Account JWT signer evidence is incomplete or changed"); + } + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = + publication.receipt().orElseThrow(() -> new MissingPublicationEvidenceException()); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication + .mountedCorrespondence() + .orElseThrow(() -> new MissingPublicationEvidenceException()); + if (!intent.operationId().equals(result.operationId()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !receipt.operationId().equals(result.operationId()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !mount.operationId().equals(result.operationId()) + || !mount.intentDigest().equals(intent.intentDigest()) + || !mount.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !mount.publicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw new StaleOperationException( + "Account JWT publication evidence is not exact for readiness"); + } + return new CurrentEvidence(state, request, result, publication); + } + + private ReadinessProbePlan requireStoredPlan(CurrentEvidence current) { + ReadinessProbePlan plan = selectPlan(current.request().operationId(), true); + if (plan == null) { + throw new MissingPlanException("Account JWT readiness probe plan is missing"); + } + requirePlanMatchesCurrent(plan, current); + return readbackPlan(plan, true); + } + + private static void requireCurrentOperation(CurrentEvidence current, String operationId) { + if (!current.request().operationId().toString().equals(operationId)) { + throw new StaleOperationException("Readiness probe belongs to a stale Account operation"); + } + } + + private static void requireSignedResultMatches( + ReadinessProbePlan plan, ProbeEntry entry, SignedProbeDigest signed) { + if (entry == null + || !signed.operationId().equals(plan.operationId().toString()) + || !signed.validatorId().equals(entry.validatorId()) + || signed.probeKind() != entry.probeKind() + || !signed.tokenProfile().equals(entry.tokenProfile()) + || !signed.audience().equals(entry.audience()) + || !signed.jti().equals(entry.jti()) + || !signed.targetGeneration().equals(entry.targetGeneration()) + || !signed.targetKid().equals(entry.targetKid()) + || !signed.publicKeyFingerprint().equals(plan.targetPublicKeyFingerprint()) + || signed.issuedAtEpochSecond() != entry.plannedIssuedAtEpochSecond() + || signed.expiresAtEpochSecond() != entry.expiresAtEpochSecond() + || !SHA256.matcher(signed.compactTokenSha256()).matches()) { + throw new IdempotencyConflictException( + "Mounted readiness signature does not match its exact plan"); + } + } + + private static VerificationReceipt verificationReceipt( + ReadinessProbePlan plan, + ProbeEntry entry, + VerifiedProbeObservation observation, + long resultEntryVersion) { + Map fields = new LinkedHashMap<>(); + fields.put("receiptVersion", 1); + fields.put("rotationOperationId", plan.operationId().toString()); + fields.put("planDigest", plan.planDigest()); + fields.put("operationDigest", plan.operationDigest()); + fields.put("generationRequestDigest", plan.generationRequestDigest()); + fields.put("generationReceiptDigest", plan.generationReceiptDigest()); + fields.put("desiredStateVersion", plan.desiredStateVersion()); + fields.put("environmentId", plan.binding().environmentId()); + fields.put("clusterId", plan.binding().clusterId()); + fields.put("namespace", plan.binding().namespace()); + fields.put( + "trustFence", + Map.of( + "clusterIncarnationUid", plan.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", plan.trustFence().expectedNamespaceUid(), + "bindingDigest", plan.trustFence().bindingDigest(), + "configRevision", plan.trustFence().configRevision())); + fields.put("targetGeneration", entry.targetGeneration()); + fields.put("targetKid", entry.targetKid()); + fields.put("targetPublicKeyFingerprint", plan.targetPublicKeyFingerprint()); + fields.put("expectedActive", activeMap(plan.expectedFence().durableActive())); + fields.put("expectedPublishedActive", activeMap(plan.expectedFence().publishedActive())); + fields.put("validatorId", entry.validatorId()); + fields.put("tokenProfile", entry.tokenProfile()); + fields.put("audience", entry.audience()); + fields.put("probeKind", entry.probeKind().name()); + fields.put("jti", entry.jti().toString()); + fields.put("registryVersion", entry.registryVersion()); + fields.put("sourceEntryVersion", entry.entryVersion()); + fields.put("resultEntryVersion", resultEntryVersion); + fields.put("issuedAtEpochSecond", entry.plannedIssuedAtEpochSecond()); + fields.put("expiresAtEpochSecond", entry.expiresAtEpochSecond()); + fields.put("compactTokenSha256", observation.compactTokenSha256()); + fields.put("verifiedKid", observation.verifiedKid()); + fields.put("validatorInstanceId", observation.validatorInstanceId()); + fields.put("validatorBindingDigest", observation.validatorBindingDigest()); + fields.put("validatorConfigRevision", observation.validatorConfigRevision()); + fields.put("validatorPeerUri", observation.validatorPeerUri()); + fields.put("validatorPeerSpkiSha256", observation.validatorPeerSpkiSha256()); + fields.put("observedAtEpochSecond", observation.observedAtEpochSecond()); + return new VerificationReceipt( + 1, + entry.entryVersion(), + resultEntryVersion, + observation.observedAtEpochSecond(), + digest(fields), + observation.verifiedKid(), + observation.validatorInstanceId(), + observation.validatorBindingDigest(), + observation.validatorConfigRevision(), + observation.validatorPeerUri(), + observation.validatorPeerSpkiSha256()); + } + + private static void requireMatchingObservation( + VerificationReceipt receipt, VerifiedProbeObservation observation) { + if (!receipt.verifiedKid().equals(observation.verifiedKid()) + || !receipt.validatorInstanceId().equals(observation.validatorInstanceId()) + || !receipt.validatorBindingDigest().equals(observation.validatorBindingDigest()) + || !receipt.validatorConfigRevision().equals(observation.validatorConfigRevision()) + || !receipt.validatorPeerUri().equals(observation.validatorPeerUri()) + || !receipt.validatorPeerSpkiSha256().equals(observation.validatorPeerSpkiSha256())) { + throw new IdempotencyConflictException( + "Readiness verification retry differs from its immutable authenticated receipt"); + } + } + + private void requireNotExpired(ProbeEntry entry, long nowEpoch) { + if (nowEpoch >= entry.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + } + + static String applicabilityMatrixJson() { + List> applicableProfiles = + List.of( + Map.of("audience", CONTROL_UI_AUDIENCE, "tokenProfile", CONTROL_UI_PROFILE), + Map.of( + "audience", PLAYER_BOOTSTRAP_AUDIENCE, + "tokenProfile", PLAYER_BOOTSTRAP_PROFILE), + Map.of("audience", REPRESENTATIVE_AUDIENCE, "tokenProfile", REPRESENTATIVE_PROFILE)); + Map validator = new LinkedHashMap<>(); + validator.put("applicableProfiles", applicableProfiles); + validator.put("validatorId", VALIDATOR_ID); + Map matrix = new LinkedHashMap<>(); + matrix.put("inventoryStatus", INVENTORY_STATUS); + matrix.put("schemaVersion", 1); + matrix.put("validators", List.of(validator)); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(matrix)), + StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new StorageUnavailableException( + "Readiness applicability matrix cannot be canonicalized"); + } + } + + private static String planDigest( + CurrentEvidence current, + String matrixJson, + String matrixDigest, + long plannedAt, + long notBefore, + long expiresAt, + List entries, + Optional inventorySnapshotDigest) { + Map preimage = new LinkedHashMap<>(); + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = current.publication(); + preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v1"); + preimage.put("rotationOperationId", request.operationId().toString()); + preimage.put("environmentId", request.binding().environmentId()); + preimage.put("clusterId", request.binding().clusterId()); + preimage.put("namespace", request.binding().namespace()); + preimage.put("custodyMode", request.binding().mode().value()); + preimage.put("operationDigest", request.operationDigest()); + preimage.put("generationRequestDigest", result.generationRequestDigest()); + preimage.put("generationReceiptDigest", result.receiptDigest()); + preimage.put("desiredStateVersion", result.desiredStateVersion()); + preimage.put( + "trustFence", + Map.of( + "clusterIncarnationUid", request.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", request.trustFence().expectedNamespaceUid(), + "bindingDigest", request.trustFence().bindingDigest(), + "configRevision", request.trustFence().configRevision())); + preimage.put("targetGeneration", result.targetGeneration()); + preimage.put("targetKid", result.targetKid()); + preimage.put("targetPublicKeyFingerprint", result.publicKeyFingerprint()); + preimage.put("expectedActive", activeMap(request.expectedActive())); + preimage.put("expectedPublishedActive", activeMap(request.expectedPublishedActive())); + preimage.put("publicationIntentDigest", publication.intent().intentDigest()); + preimage.put("publicationReceiptDigest", publication.receipt().orElseThrow().receiptDigest()); + preimage.put( + "mountedObservationDigest", + publication.mountedCorrespondence().orElseThrow().observationDigest()); + preimage.put("applicabilityMatrixJson", matrixJson); + preimage.put("applicabilityMatrixDigest", matrixDigest); + preimage.put("validatorInventoryComplete", false); + inventorySnapshotDigest.ifPresent(digest -> preimage.put("inventorySnapshotDigest", digest)); + preimage.put("maximumCacheAgeSeconds", MAX_VALIDATOR_CACHE_AGE_SECONDS); + preimage.put("plannedAtEpochSecond", plannedAt); + preimage.put("notBeforeEpochSecond", notBefore); + preimage.put("expiresAtEpochSecond", expiresAt); + preimage.put( + "entries", + entries.stream().map(AccountJwtReadinessProbeRepository::entryDigestMap).toList()); + return digest(preimage); + } + + private static String planDigest(ReadinessProbePlan plan) { + Map preimage = planDigestMap(plan); + return digest(preimage); + } + + private static Map planDigestMap(ReadinessProbePlan plan) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v1"); + preimage.put("rotationOperationId", plan.operationId().toString()); + preimage.put("environmentId", plan.binding().environmentId()); + preimage.put("clusterId", plan.binding().clusterId()); + preimage.put("namespace", plan.binding().namespace()); + preimage.put("custodyMode", plan.binding().mode().value()); + preimage.put("operationDigest", plan.operationDigest()); + preimage.put("generationRequestDigest", plan.generationRequestDigest()); + preimage.put("generationReceiptDigest", plan.generationReceiptDigest()); + preimage.put("desiredStateVersion", plan.desiredStateVersion()); + preimage.put( + "trustFence", + Map.of( + "clusterIncarnationUid", plan.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", plan.trustFence().expectedNamespaceUid(), + "bindingDigest", plan.trustFence().bindingDigest(), + "configRevision", plan.trustFence().configRevision())); + preimage.put("targetGeneration", plan.targetGeneration()); + preimage.put("targetKid", plan.targetKid()); + preimage.put("targetPublicKeyFingerprint", plan.targetPublicKeyFingerprint()); + preimage.put("expectedActive", activeMap(plan.expectedFence().durableActive())); + preimage.put("expectedPublishedActive", activeMap(plan.expectedFence().publishedActive())); + preimage.put("publicationIntentDigest", plan.publicationIntentDigest()); + preimage.put("publicationReceiptDigest", plan.publicationReceiptDigest()); + preimage.put("mountedObservationDigest", plan.mountedObservationDigest()); + preimage.put("applicabilityMatrixJson", plan.applicabilityMatrixJson()); + preimage.put("applicabilityMatrixDigest", plan.applicabilityMatrixDigest()); + preimage.put("validatorInventoryComplete", plan.validatorInventoryComplete()); + plan.inventorySnapshotDigest() + .ifPresent(digest -> preimage.put("inventorySnapshotDigest", digest)); + preimage.put("maximumCacheAgeSeconds", plan.maximumCacheAgeSeconds()); + preimage.put("plannedAtEpochSecond", plan.plannedAtEpochSecond()); + preimage.put("notBeforeEpochSecond", plan.notBeforeEpochSecond()); + preimage.put("expiresAtEpochSecond", plan.expiresAtEpochSecond()); + preimage.put( + "entries", + plan.entries().stream().map(AccountJwtReadinessProbeRepository::entryDigestMap).toList()); + return preimage; + } + + private static Map entryDigestMap(ProbeEntry entry) { + Map item = new LinkedHashMap<>(); + item.put("validatorId", entry.validatorId()); + item.put("tokenProfile", entry.tokenProfile()); + item.put("audience", entry.audience()); + item.put("probeKind", entry.probeKind().name()); + item.put("jti", entry.jti().toString()); + item.put("targetGeneration", entry.targetGeneration()); + item.put("targetKid", entry.targetKid()); + item.put("expectedActive", activeMap(entry.expectedActive())); + item.put("registryVersion", entry.registryVersion()); + item.put("entryVersion", 1); + item.put("plannedIssuedAtEpochSecond", entry.plannedIssuedAtEpochSecond()); + item.put("expiresAtEpochSecond", entry.expiresAtEpochSecond()); + return item; + } + + private static Map activeMap(Optional active) { + if (active.isEmpty()) { + return Map.of("present", false); + } + ActiveSigner signer = active.orElseThrow(); + return Map.of("present", true, "generation", signer.generation(), "kid", signer.kid()); + } + + private static String deliveryClaimDigest(DeliveryClaim claim) { + Map value = new LinkedHashMap<>(); + value.put("rotationOperationId", claim.rotationOperationId().toString()); + value.put("planDigest", claim.planDigest()); + value.put("expectedClusterUid", claim.expectedClusterUid()); + value.put("expectedNamespaceUid", claim.expectedNamespaceUid()); + value.put("materializerTrustBindingDigest", claim.materializerTrustBindingDigest()); + value.put("materializerTrustConfigRevision", claim.materializerTrustConfigRevision()); + value.put("targetGeneration", claim.targetGeneration()); + value.put("targetKid", claim.targetKid()); + value.put("expectedActive", activeMap(claim.expectedActive())); + value.put("readinessBindingDigest", claim.readinessBindingDigest()); + value.put("readinessConfigRevision", claim.readinessConfigRevision()); + value.put( + "readinessBindingValidUntilEpochSecond", claim.readinessBindingValidUntilEpochSecond()); + value.put("validatorId", claim.validatorId()); + value.put("validatorInstanceId", claim.validatorInstanceId()); + value.put("validatorPeerUri", claim.validatorPeerUri()); + value.put("validatorPeerSpkiSha256", claim.validatorPeerSpkiSha256()); + value.put("claimedAtEpochSecond", claim.claimedAtEpochSecond()); + value.put("expiresAtEpochSecond", claim.expiresAtEpochSecond()); + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } catch (IOException failure) { + throw new StorageUnavailableException("Readiness delivery claim cannot be canonicalized"); + } + } + + private static String readinessPromotionDigest( + ReadinessProbePlan plan, + GenerationResult generation, + AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication, + String inventoryEvidenceReference, + String inventoryEvidenceDigest, + List verifiedProbes) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-readiness-promotion-proof/v1"); + preimage.put("plan", planDigestMap(plan)); + preimage.put("planDigest", plan.planDigest()); + preimage.put("generation", generationEvidenceMap(generation)); + preimage.put("publication", preparedPublicationEvidenceMap(publication)); + preimage.put("inventoryEvidenceReference", inventoryEvidenceReference); + preimage.put("inventoryEvidenceDigest", inventoryEvidenceDigest); + preimage.put( + "verifiedProbes", + verifiedProbes.stream() + .map(AccountJwtReadinessProbeRepository::verifiedProbeEvidenceMap) + .toList()); + return digest(preimage); + } + + private static Map generationEvidenceMap(GenerationResult result) { + Map value = new LinkedHashMap<>(); + value.put("operationId", result.operationId().toString()); + value.put("environmentId", result.binding().environmentId()); + value.put("clusterId", result.binding().clusterId()); + value.put("namespace", result.binding().namespace()); + value.put("custodyMode", result.binding().mode().value()); + value.put("operationDigest", result.operationDigest()); + value.put("generationRequestDigest", result.generationRequestDigest()); + value.put("desiredStateVersion", result.desiredStateVersion()); + value.put("trustFence", trustFenceMap(result.trustFence())); + value.put("privateSecretName", result.privateSecretName()); + value.put("secretUid", result.secretUid()); + value.put("expectedPriorResourceVersion", result.expectedPriorResourceVersion()); + value.put("observedResourceVersion", result.observedResourceVersion()); + value.put("targetGeneration", result.targetGeneration()); + value.put("targetKid", result.targetKid()); + value.put("targetAlgorithm", result.targetAlgorithm()); + value.put("publicKeyFingerprint", result.publicKeyFingerprint()); + value.put("publicJwkJson", result.publicJwkJson()); + value.put("receiptDigest", result.receiptDigest()); + return value; + } + + private static Map trustFenceMap(TrustFence trust) { + return Map.of( + "clusterIncarnationUid", trust.expectedClusterIncarnationUid(), + "namespaceUid", trust.expectedNamespaceUid(), + "bindingDigest", trust.bindingDigest(), + "configRevision", trust.configRevision()); + } + + private static Map preparedPublicationEvidenceMap( + AccountJwtJwksPublicationRepository.PreparedPublicationEvidence evidence) { + var intent = evidence.intent(); + var receipt = evidence.receipt(); + var mount = evidence.mountedCorrespondence(); + Map intentValue = new LinkedHashMap<>(); + intentValue.put("operationId", intent.operationId().toString()); + intentValue.put("environmentId", intent.binding().environmentId()); + intentValue.put("clusterId", intent.binding().clusterId()); + intentValue.put("namespace", intent.binding().namespace()); + intentValue.put("operationDigest", intent.operationDigest()); + intentValue.put("generationRequestDigest", intent.generationRequestDigest()); + intentValue.put("generationReceiptDigest", intent.generationReceiptDigest()); + intentValue.put("desiredStateVersion", intent.desiredStateVersion()); + intentValue.put("trustFence", trustFenceMap(intent.trustFence())); + intentValue.put("apiBindingDigest", intent.apiBindingDigest()); + intentValue.put("apiConfigRevision", intent.apiConfigRevision()); + intentValue.put("configMapName", intent.configMapName()); + intentValue.put("configMapUid", intent.configMapUid()); + intentValue.put("expectedResourceVersion", intent.expectedResourceVersion()); + intentValue.put("expectedSnapshotDigest", intent.expectedSnapshotDigest()); + intentValue.put("targetGeneration", intent.targetGeneration()); + intentValue.put("targetKid", intent.targetKid()); + intentValue.put("publicKeyFingerprint", intent.publicKeyFingerprint()); + intentValue.put("expectedDurableActive", activeMap(intent.expectedDurableActive())); + intentValue.put("expectedPublishedActive", activeMap(intent.expectedPublishedActive())); + intentValue.put("publicDataDigest", intent.publicDataDigest()); + intentValue.put("generationMarkerDigest", intent.generationMarkerDigest()); + intentValue.put("intentDigest", intent.intentDigest()); + + Map receiptValue = new LinkedHashMap<>(); + receiptValue.put("operationId", receipt.operationId().toString()); + receiptValue.put("intentDigest", receipt.intentDigest()); + receiptValue.put("configMapUid", receipt.configMapUid()); + receiptValue.put("expectedResourceVersion", receipt.expectedResourceVersion()); + receiptValue.put("observedResourceVersion", receipt.observedResourceVersion()); + receiptValue.put("publicDataDigest", receipt.publicDataDigest()); + receiptValue.put("receiptDigest", receipt.receiptDigest()); + + Map mountValue = new LinkedHashMap<>(); + mountValue.put("operationId", mount.operationId().toString()); + mountValue.put("intentDigest", mount.intentDigest()); + mountValue.put("publicationReceiptDigest", mount.publicationReceiptDigest()); + mountValue.put("generationMarkerDigest", mount.generationMarkerDigest()); + mountValue.put("publicDataDigest", mount.publicDataDigest()); + mountValue.put("publicKeyFingerprint", mount.publicKeyFingerprint()); + mountValue.put("observationDigest", mount.observationDigest()); + return Map.of("intent", intentValue, "receipt", receiptValue, "mount", mountValue); + } + + private static Map verifiedProbeEvidenceMap(VerifiedProbeEvidence probe) { + VerificationReceipt receipt = probe.receipt(); + Map value = new LinkedHashMap<>(); + value.put("rotationOperationId", probe.rotationOperationId().toString()); + value.put("planDigest", probe.planDigest()); + value.put("validatorId", probe.validatorId()); + value.put("tokenProfile", probe.tokenProfile()); + value.put("audience", probe.audience()); + value.put("probeKind", probe.probeKind().name()); + value.put("jti", probe.jti().toString()); + value.put("targetGeneration", probe.targetGeneration()); + value.put("targetKid", probe.targetKid()); + value.put("expectedActive", activeMap(probe.expectedActive())); + value.put("registryVersion", probe.registryVersion()); + value.put("entryVersion", probe.entryVersion()); + value.put("plannedIssuedAtEpochSecond", probe.plannedIssuedAtEpochSecond()); + value.put("expiresAtEpochSecond", probe.expiresAtEpochSecond()); + value.put("compactTokenSha256", probe.compactTokenSha256()); + Map receiptValue = new LinkedHashMap<>(); + receiptValue.put("receiptVersion", receipt.receiptVersion()); + receiptValue.put("sourceEntryVersion", receipt.sourceEntryVersion()); + receiptValue.put("resultEntryVersion", receipt.resultEntryVersion()); + receiptValue.put("observedAtEpochSecond", receipt.observedAtEpochSecond()); + receiptValue.put("receiptSha256", receipt.receiptSha256()); + receiptValue.put("verifiedKid", receipt.verifiedKid()); + receiptValue.put("validatorInstanceId", receipt.validatorInstanceId()); + receiptValue.put("validatorBindingDigest", receipt.validatorBindingDigest()); + receiptValue.put("validatorConfigRevision", receipt.validatorConfigRevision()); + receiptValue.put("validatorPeerUri", receipt.validatorPeerUri()); + receiptValue.put("validatorPeerSpkiSha256", receipt.validatorPeerSpkiSha256()); + value.put("verificationReceipt", receiptValue); + return value; + } + + private static String digest(Map value) { + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } catch (IOException ex) { + throw new StorageUnavailableException("Readiness evidence cannot be canonicalized"); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new StorageUnavailableException("SHA-256 is unavailable"); + } + } + + private static long exactEpochSecond(Instant instant) { + Objects.requireNonNull(instant, "Readiness timestamp is required"); + if (instant.getNano() != 0 || instant.getEpochSecond() <= 0L) { + throw new IllegalArgumentException("Readiness time must be a positive exact epoch second"); + } + return instant.getEpochSecond(); + } + + private static long add(long value, long amount) { + try { + return Math.addExact(value, amount); + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Readiness timestamp overflow", ex); + } + } + + private static void requireOperationId(UUID operationId) { + if (operationId == null || operationId.version() != 4 || operationId.variant() != 2) { + throw new IllegalArgumentException("Account JWT readiness operation ID must be UUIDv4"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("An owning Account transaction is required"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("A writable Account transaction is required"); + } + } + + private static void insertOne(DSLContext dsl, String table, Map fields) { + String columns = String.join(", ", fields.keySet()); + String placeholders = String.join(", ", java.util.Collections.nCopies(fields.size(), "?")); + dsl.execute( + "INSERT INTO " + table + " (" + columns + ") VALUES (" + placeholders + ")", + fields.values().toArray()); + } + + private record CurrentEvidence( + DesiredState state, + GenerationRequest request, + GenerationResult result, + AccountJwtJwksPublicationRepository.PublicationEvidence publication) {} + + public enum ProbeState { + PLANNED, + ISSUED, + VERIFIED, + CLEANED, + EXPIRED, + ABORTED + } + + public record SignerFence( + Optional durableActive, Optional publishedActive) { + public SignerFence { + durableActive = Objects.requireNonNull(durableActive); + publishedActive = Objects.requireNonNull(publishedActive); + if (!durableActive.equals(publishedActive)) { + throw new QuarantinedStateException("Durable and published signer fences disagree"); + } + } + } + + public record ProbeEntry( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + String targetGeneration, + String targetKid, + Optional expectedActive, + int registryVersion, + long entryVersion, + long plannedIssuedAtEpochSecond, + long expiresAtEpochSecond, + ProbeState state, + Optional terminalOutcome, + Optional signingAttemptedAtEpochSecond, + Optional compactTokenSha256, + Optional verificationReceipt) { + public ProbeEntry { + Objects.requireNonNull(rotationOperationId); + requireDigest(planDigest, "probe plan digest"); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + Objects.requireNonNull(expectedActive); + Objects.requireNonNull(state); + terminalOutcome = Objects.requireNonNull(terminalOutcome); + signingAttemptedAtEpochSecond = Objects.requireNonNull(signingAttemptedAtEpochSecond); + compactTokenSha256 = Objects.requireNonNull(compactTokenSha256); + verificationReceipt = Objects.requireNonNull(verificationReceipt); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + requireGeneration(targetGeneration); + requireKid(targetKid); + if (jti.version() != 4 + || jti.variant() != 2 + || registryVersion != 1 + || entryVersion <= 0L + || plannedIssuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= plannedIssuedAtEpochSecond + || expiresAtEpochSecond - plannedIssuedAtEpochSecond > PROBE_LIFETIME_SECONDS) { + throw new QuarantinedStateException("Readiness probe entry identity is malformed"); + } + compactTokenSha256.ifPresent(value -> requireDigest(value, "compact probe hash")); + if (compactTokenSha256.isPresent() != signingAttemptedAtEpochSecond.isPresent()) { + throw new QuarantinedStateException("Readiness signing-attempt evidence is partial"); + } + signingAttemptedAtEpochSecond.ifPresent( + attemptedAt -> { + if (attemptedAt < plannedIssuedAtEpochSecond || attemptedAt >= expiresAtEpochSecond) { + throw new QuarantinedStateException( + "Readiness signing-attempt time is outside its plan"); + } + }); + if ((state == ProbeState.ABORTED + || state == ProbeState.EXPIRED + || state == ProbeState.CLEANED) + != terminalOutcome.isPresent() + || (state == ProbeState.ABORTED && terminalOutcome.filter("ABORTED"::equals).isEmpty()) + || (state == ProbeState.EXPIRED && terminalOutcome.filter("EXPIRED"::equals).isEmpty()) + || (state == ProbeState.CLEANED + && terminalOutcome + .filter(value -> value.equals("ABORTED") || value.equals("EXPIRED")) + .isEmpty())) { + throw new QuarantinedStateException("Readiness terminal outcome does not match its state"); + } + if ((state == ProbeState.ISSUED || state == ProbeState.VERIFIED) + && compactTokenSha256.isEmpty()) { + throw new QuarantinedStateException("Issued readiness probe has no exact token hash"); + } + if ((state == ProbeState.VERIFIED && verificationReceipt.isEmpty()) + || ((state == ProbeState.PLANNED || state == ProbeState.ISSUED) + && verificationReceipt.isPresent())) { + throw new QuarantinedStateException("Readiness state and verification receipt disagree"); + } + verificationReceipt.ifPresent( + receipt -> { + if (!receipt.verifiedKid().equals(targetKid) + || receipt.resultEntryVersion() > entryVersion + || receipt.sourceEntryVersion() + 1L != receipt.resultEntryVersion() + || (state == ProbeState.VERIFIED && receipt.resultEntryVersion() != entryVersion)) { + throw new QuarantinedStateException( + "Readiness verification receipt differs from its immutable entry"); + } + }); + if (verificationReceipt.isPresent() + && verificationReceipt.orElseThrow().resultEntryVersion() > entryVersion) { + throw new QuarantinedStateException("Terminal readiness receipt version is invalid"); + } + if (state == ProbeState.CLEANED && terminalOutcome.isEmpty()) { + throw new QuarantinedStateException("Cleaned readiness probe lost its terminal evidence"); + } + } + + private ProbeEntry withPlanDigest(String value) { + return new ProbeEntry( + rotationOperationId, + value, + validatorId, + tokenProfile, + audience, + probeKind, + jti, + targetGeneration, + targetKid, + expectedActive, + registryVersion, + entryVersion, + plannedIssuedAtEpochSecond, + expiresAtEpochSecond, + state, + terminalOutcome, + signingAttemptedAtEpochSecond, + compactTokenSha256, + verificationReceipt); + } + } + + /** Exact authenticated transport and cryptographic verification evidence; contains no token. */ + public record VerifiedProbeObservation( + String compactTokenSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256, + long observedAtEpochSecond) { + public VerifiedProbeObservation { + requireDigest(compactTokenSha256, "verified compact token hash"); + requireKid(verifiedKid); + if (validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorConfigRevision == null + || !validatorConfigRevision.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness") + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Readiness verification observation is malformed"); + } + requireDigest(validatorBindingDigest, "validator trust binding digest"); + requireDigest(validatorPeerSpkiSha256, "validator peer SPKI digest"); + } + } + + /** Immutable digest and identity fields read back from the readiness entry row. */ + public record VerificationReceipt( + int receiptVersion, + long sourceEntryVersion, + long resultEntryVersion, + long observedAtEpochSecond, + String receiptSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256) { + public VerificationReceipt { + if (receiptVersion != 1 + || sourceEntryVersion <= 0L + || resultEntryVersion != sourceEntryVersion + 1L + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Readiness verification receipt version is malformed"); + } + requireDigest(receiptSha256, "readiness verification receipt digest"); + requireKid(verifiedKid); + if (validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorConfigRevision == null + || !validatorConfigRevision.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness")) { + throw new QuarantinedStateException("Readiness verification receipt identity is malformed"); + } + requireDigest(validatorBindingDigest, "validator trust binding digest"); + requireDigest(validatorPeerSpkiSha256, "validator peer SPKI digest"); + } + } + + public record ReadinessProbePlan( + UUID operationId, + Binding binding, + TrustFence trustFence, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + String targetGeneration, + String targetKid, + String targetPublicKeyFingerprint, + SignerFence expectedFence, + String publicationIntentDigest, + String publicationReceiptDigest, + String mountedObservationDigest, + String applicabilityMatrixJson, + String applicabilityMatrixDigest, + boolean validatorInventoryComplete, + int maximumCacheAgeSeconds, + long plannedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + int planVersion, + String planDigest, + List entries, + Optional inventorySnapshotDigest) { + public ReadinessProbePlan( + UUID operationId, + Binding binding, + TrustFence trustFence, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + String targetGeneration, + String targetKid, + String targetPublicKeyFingerprint, + SignerFence expectedFence, + String publicationIntentDigest, + String publicationReceiptDigest, + String mountedObservationDigest, + String applicabilityMatrixJson, + String applicabilityMatrixDigest, + boolean validatorInventoryComplete, + int maximumCacheAgeSeconds, + long plannedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + int planVersion, + String planDigest, + List entries) { + this( + operationId, + binding, + trustFence, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + targetGeneration, + targetKid, + targetPublicKeyFingerprint, + expectedFence, + publicationIntentDigest, + publicationReceiptDigest, + mountedObservationDigest, + applicabilityMatrixJson, + applicabilityMatrixDigest, + validatorInventoryComplete, + maximumCacheAgeSeconds, + plannedAtEpochSecond, + notBeforeEpochSecond, + expiresAtEpochSecond, + planVersion, + planDigest, + entries, + Optional.empty()); + } + + public ReadinessProbePlan { + requireOperationId(operationId); + Objects.requireNonNull(binding); + Objects.requireNonNull(trustFence); + Objects.requireNonNull(expectedFence); + requireDigest(operationDigest, "operation digest"); + requireDigest(generationRequestDigest, "generation request digest"); + requireDigest(generationReceiptDigest, "generation receipt digest"); + requireGeneration(targetGeneration); + requireKid(targetKid); + requireDigest(targetPublicKeyFingerprint, "target public key fingerprint"); + requireDigest(publicationIntentDigest, "publication intent digest"); + requireDigest(publicationReceiptDigest, "publication receipt digest"); + requireDigest(mountedObservationDigest, "mounted observation digest"); + Objects.requireNonNull(applicabilityMatrixJson); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + requireDigest(planDigest, "plan digest"); + Objects.requireNonNull(inventorySnapshotDigest); + inventorySnapshotDigest.ifPresent( + value -> requireDigest(value, "validator inventory snapshot digest")); + entries = List.copyOf(entries); + if (desiredStateVersion <= 1L + || maximumCacheAgeSeconds != MAX_VALIDATOR_CACHE_AGE_SECONDS + || plannedAtEpochSecond <= 0L + || notBeforeEpochSecond < plannedAtEpochSecond + maximumCacheAgeSeconds + || expiresAtEpochSecond <= notBeforeEpochSecond + || expiresAtEpochSecond - notBeforeEpochSecond > PROBE_LIFETIME_SECONDS + || planVersion != 1 + || entries.isEmpty() + || entries.size() > MAX_ENTRIES_PER_OPERATION) { + throw new QuarantinedStateException("Readiness probe plan is malformed"); + } + } + + private static ReadinessProbePlan fromCurrent( + CurrentEvidence current, + String matrixJson, + String matrixDigest, + boolean inventoryComplete, + int maxCacheAge, + long plannedAt, + long notBefore, + long expiresAt, + String planDigest, + List entries, + Optional inventorySnapshotDigest) { + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + var publication = current.publication(); + return new ReadinessProbePlan( + request.operationId(), + request.binding(), + request.trustFence(), + request.operationDigest(), + result.generationRequestDigest(), + result.receiptDigest(), + result.desiredStateVersion(), + result.targetGeneration(), + result.targetKid(), + result.publicKeyFingerprint(), + new SignerFence(request.expectedActive(), request.expectedPublishedActive()), + publication.intent().intentDigest(), + publication.receipt().orElseThrow().receiptDigest(), + publication.mountedCorrespondence().orElseThrow().observationDigest(), + matrixJson, + matrixDigest, + inventoryComplete, + maxCacheAge, + plannedAt, + notBefore, + expiresAt, + 1, + planDigest, + entries, + inventorySnapshotDigest); + } + } + + /** + * Owner-created, non-secret readiness evidence accepted by the Account promotion owner. Its + * constructor is private: callers cannot turn an applicability matrix or receipt DTO into proof. + */ + public static final class ReadinessPromotionProof { + private final ReadinessProbePlan plan; + private final GenerationResult generationResult; + private final AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication; + private final String inventoryEvidenceReference; + private final String inventoryEvidenceDigest; + private final List verifiedProbes; + private final String readinessEvidenceDigest; + + private ReadinessPromotionProof( + ReadinessProbePlan plan, + GenerationResult generationResult, + AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication, + String inventoryEvidenceReference, + String inventoryEvidenceDigest) { + this.plan = Objects.requireNonNull(plan); + this.generationResult = Objects.requireNonNull(generationResult); + this.publication = Objects.requireNonNull(publication); + if (!plan.validatorInventoryComplete()) { + throw new QuarantinedStateException( + "Partial readiness inventory cannot create promotion proof"); + } + if (inventoryEvidenceReference == null + || !inventoryEvidenceReference.matches("[A-Za-z0-9][A-Za-z0-9._:/-]{0,511}")) { + throw new QuarantinedStateException("Protected readiness inventory reference is malformed"); + } + requireDigest(inventoryEvidenceDigest, "protected readiness inventory digest"); + this.inventoryEvidenceReference = inventoryEvidenceReference; + this.inventoryEvidenceDigest = inventoryEvidenceDigest; + List verifiedProbes = + plan.entries().stream().map(VerifiedProbeEvidence::from).toList(); + if (verifiedProbes.isEmpty() + || verifiedProbes.size() > MAX_ENTRIES_PER_OPERATION + || !plan.operationId().equals(generationResult.operationId()) + || !plan.operationDigest().equals(generationResult.operationDigest()) + || !plan.generationRequestDigest().equals(generationResult.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(generationResult.receiptDigest()) + || plan.desiredStateVersion() != generationResult.desiredStateVersion() + || !plan.targetGeneration().equals(generationResult.targetGeneration()) + || !plan.targetKid().equals(generationResult.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(generationResult.publicKeyFingerprint()) + || !plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException( + "Readiness proof differs from exact generation and verified probe evidence"); + } + this.verifiedProbes = List.copyOf(verifiedProbes); + this.readinessEvidenceDigest = + readinessPromotionDigest( + plan, + generationResult, + publication, + inventoryEvidenceReference, + inventoryEvidenceDigest, + this.verifiedProbes); + } + + public ReadinessProbePlan plan() { + return plan; + } + + public GenerationResult generationResult() { + return generationResult; + } + + public AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication() { + return publication; + } + + public String inventoryEvidenceReference() { + return inventoryEvidenceReference; + } + + public String inventoryEvidenceDigest() { + return inventoryEvidenceDigest; + } + + public List verifiedProbes() { + return verifiedProbes; + } + + /** Digest computed by Account over all canonical proof fields except this digest itself. */ + public String readinessEvidenceDigest() { + return readinessEvidenceDigest; + } + } + + /** Ordered immutable row and authenticated receipt identity for one VERIFIED registry entry. */ + public record VerifiedProbeEvidence( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + String targetGeneration, + String targetKid, + Optional expectedActive, + int registryVersion, + long entryVersion, + long plannedIssuedAtEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256, + VerificationReceipt receipt) { + public VerifiedProbeEvidence { + Objects.requireNonNull(rotationOperationId); + requireDigest(planDigest, "verified probe plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + requireDigest(compactTokenSha256, "verified probe token digest"); + Objects.requireNonNull(receipt); + if (registryVersion != 1 + || entryVersion <= 0L + || plannedIssuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= plannedIssuedAtEpochSecond + || !targetKid.equals(receipt.verifiedKid()) + || receipt.resultEntryVersion() != entryVersion) { + throw new QuarantinedStateException( + "Verified probe evidence does not match its immutable receipt"); + } + } + + private static VerifiedProbeEvidence from(ProbeEntry entry) { + if (entry.state() != ProbeState.VERIFIED) { + throw new QuarantinedStateException( + "Every promotion readiness entry must be owner-recorded VERIFIED"); + } + return new VerifiedProbeEvidence( + entry.rotationOperationId(), + entry.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + entry.jti(), + entry.targetGeneration(), + entry.targetKid(), + entry.expectedActive(), + entry.registryVersion(), + entry.entryVersion(), + entry.plannedIssuedAtEpochSecond(), + entry.expiresAtEpochSecond(), + entry.compactTokenSha256().orElseThrow(), + entry.verificationReceipt().orElseThrow()); + } + } + + /** Immutable winner of the only permitted transient delivery for a readiness operation. */ + public record DeliveryClaim( + UUID rotationOperationId, + String planDigest, + String expectedClusterUid, + String expectedNamespaceUid, + String materializerTrustBindingDigest, + String materializerTrustConfigRevision, + String targetGeneration, + String targetKid, + Optional expectedActive, + String readinessBindingDigest, + String readinessConfigRevision, + long readinessBindingValidUntilEpochSecond, + String validatorId, + String validatorInstanceId, + String validatorPeerUri, + String validatorPeerSpkiSha256, + long claimedAtEpochSecond, + long expiresAtEpochSecond, + String claimDigest) { + public DeliveryClaim { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "delivery plan digest"); + requireUuid(expectedClusterUid, "delivery cluster UID"); + requireUuid(expectedNamespaceUid, "delivery namespace UID"); + requireDigest(materializerTrustBindingDigest, "materializer trust digest"); + requireRevision(materializerTrustConfigRevision, "materializer trust revision"); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + expectedActive.ifPresent( + active -> { + requireGeneration(active.generation()); + requireKid(active.kid()); + if (Long.parseLong(targetGeneration) <= Long.parseLong(active.generation()) + || targetKid.equals(active.kid())) { + throw new QuarantinedStateException("Delivery active fence is not older than target"); + } + }); + requireDigest(readinessBindingDigest, "readiness trust digest"); + requireRevision(readinessConfigRevision, "readiness trust revision"); + if (readinessBindingValidUntilEpochSecond <= claimedAtEpochSecond) { + throw new QuarantinedStateException("Readiness binding expires before delivery claim"); + } + requireValidatorId(validatorId); + if (!VALIDATOR_ID.equals(validatorId) + || validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness")) { + throw new QuarantinedStateException("Readiness delivery identity is malformed"); + } + requireDigest(validatorPeerSpkiSha256, "readiness peer SPKI digest"); + if (claimedAtEpochSecond <= 0L || expiresAtEpochSecond <= claimedAtEpochSecond) { + throw new QuarantinedStateException("Readiness delivery claim window is malformed"); + } + requireDigest(claimDigest, "readiness delivery claim digest"); + } + + private static DeliveryClaim create( + ReadinessProbePlan plan, + TrustFence trust, + net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding + readinessBinding, + PeerIdentity peer, + long claimedAt) { + DeliveryClaim unsigned = + new DeliveryClaim( + plan.operationId(), + plan.planDigest(), + trust.expectedClusterIncarnationUid(), + trust.expectedNamespaceUid(), + trust.bindingDigest(), + trust.configRevision(), + plan.targetGeneration(), + plan.targetKid(), + plan.expectedFence().durableActive(), + readinessBinding.bindingDigest(), + readinessBinding.configRevision(), + readinessBinding.validUntilEpochSecond(), + readinessBinding.validatorId(), + readinessBinding.validatorInstanceId(), + peer.uri(), + peer.spkiSha256(), + claimedAt, + plan.expiresAtEpochSecond(), + "0".repeat(64)); + return new DeliveryClaim( + unsigned.rotationOperationId(), + unsigned.planDigest(), + unsigned.expectedClusterUid(), + unsigned.expectedNamespaceUid(), + unsigned.materializerTrustBindingDigest(), + unsigned.materializerTrustConfigRevision(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.expectedActive(), + unsigned.readinessBindingDigest(), + unsigned.readinessConfigRevision(), + unsigned.readinessBindingValidUntilEpochSecond(), + unsigned.validatorId(), + unsigned.validatorInstanceId(), + unsigned.validatorPeerUri(), + unsigned.validatorPeerSpkiSha256(), + unsigned.claimedAtEpochSecond(), + unsigned.expiresAtEpochSecond(), + deliveryClaimDigest(unsigned)); + } + } + + private static String requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new QuarantinedStateException(label + " is malformed"); + } + return value; + } + + private static String requireUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) + || parsed.version() != 4 + || parsed.variant() != 2 + || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(); + } + return value; + } catch (RuntimeException invalid) { + throw new QuarantinedStateException(label + " is malformed"); + } + } + + private static String requireRevision(String value, String label) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new QuarantinedStateException(label + " is malformed"); + } + return value; + } + + private static String requireValidatorId(String value) { + if (value == null || !value.matches("[a-z0-9][a-z0-9-]{0,62}")) { + throw new QuarantinedStateException("Readiness validator ID is malformed"); + } + return value; + } + + private static String requireProfile(String value) { + if (value == null || !value.matches("[a-z0-9][a-z0-9-]{0,127}")) { + throw new QuarantinedStateException("Readiness token profile is malformed"); + } + return value; + } + + private static String requireAudience(String value) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new QuarantinedStateException("Readiness audience is malformed"); + } + return value; + } + + private static String requireGeneration(String value) { + if (value == null || !value.matches("[1-9][0-9]{0,63}")) { + throw new QuarantinedStateException("Readiness signer generation is malformed"); + } + return value; + } + + private static String requireKid(String value) { + if (value == null || !value.matches("[A-Za-z0-9_-]{1,64}")) { + throw new QuarantinedStateException("Readiness signer kid is malformed"); + } + return value; + } + + public static final class MissingPlanException extends IllegalStateException { + public MissingPlanException(String message) { + super(message); + } + } + + public static final class DeliveryAlreadyClaimedException extends IllegalStateException { + public DeliveryAlreadyClaimedException() { + super("Readiness probe delivery was already claimed"); + } + } + + public static final class DeliveryClaimRejectedException extends SecurityException { + public DeliveryClaimRejectedException() { + super("Authenticated readiness delivery caller is not bound to the current plan"); + } + } + + public static final class MissingPublicationEvidenceException extends IllegalStateException { + public MissingPublicationEvidenceException() { + super("Current JWKS publication evidence is incomplete"); + } + } + + public static final class InventoryPlanConflictException extends IllegalStateException { + public InventoryPlanConflictException() { + super("Account validator inventory snapshot does not match the immutable readiness plan"); + } + } + + public static final class StaleOperationException extends IllegalStateException { + public StaleOperationException(String message) { + super(message); + } + } + + public static final class CacheAgeNotElapsedException extends IllegalStateException { + public CacheAgeNotElapsedException() { + super("Validator maximum cache age has not elapsed"); + } + } + + public static final class ProbeExpiredException extends IllegalStateException { + public ProbeExpiredException() { + super("Readiness probe is expired"); + } + } + + public static final class AmbiguousDeliveryException extends IllegalStateException { + public AmbiguousDeliveryException(String message) { + super(message); + } + } + + public static final class VersionConflictException extends IllegalStateException { + public VersionConflictException(String message) { + super(message); + } + } + + public static final class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static final class QuarantinedStateException extends IllegalStateException { + public QuarantinedStateException(String message) { + super(message); + } + } + + public static final class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java new file mode 100644 index 0000000000..4f34b1140d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java @@ -0,0 +1,4075 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +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; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned persistence for the interim mounted JWT signer. + * + *

Account chooses and persists the operation, generation, and {@code kid}. The materializer can + * only observe the fixed Secret, then perform one pending-slot generation/CAS or an exact + * PREPARED-only slot promotion and return public-only results. Account remains the sole durable + * commit authority; public prepublication, cache convergence, validator probes, and correspondence + * evidence are separately owned prerequisites and are never inferred by this repository. + */ +@Repository +public class AccountJwtSignerDesiredStateRepository { + public static final String PRIVATE_SECRET_NAME = "jwt-signing-keys"; + public static final String PUBLIC_JWKS_CONFIG_MAP_NAME = "jwt-jwks"; + public static final String REQUEST_DIGEST_VERSION = "account-jwt-signer-generation-operation/v1"; + public static final String OBSERVATION_DIGEST_VERSION = + "account-jwt-signer-secret-observation/v1"; + public static final String GENERATION_REQUEST_DIGEST_VERSION = + "account-jwt-signer-generation-request/v1"; + public static final String RECEIPT_DIGEST_VERSION = "account-jwt-signer-generation-receipt/v1"; + private static final String PROMOTION_DIGEST_VERSION = + "account-jwt-signer-promotion-operation/v1"; + + private static final String STATE_TABLE = "account_jwt_signer_desired_states"; + private static final String OPERATION_TABLE = "account_jwt_signer_generation_operations"; + private static final String OBSERVATION_TABLE = "account_jwt_signer_secret_observations"; + private static final String RESULT_TABLE = "account_jwt_signer_generation_results"; + private static final String PROMOTION_TABLE = "account_jwt_signer_promotion_operations"; + private static final String MODE = "INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK"; + private static final String ALGORITHM = "RS256"; + private static final String ACTION = "MATERIALIZE_PENDING"; + private static final String PENDING_SLOT = "pending"; + private static final byte[] PENDING_SLOT_CANONICAL_BYTES = + "[\"pending\"]".getBytes(StandardCharsets.UTF_8); + private static final byte[] PROMOTION_SLOTS_CANONICAL_BYTES = + "[\"current\",\"pending\",\"previous\"]".getBytes(StandardCharsets.UTF_8); + private static final Pattern ENVIRONMENT_ID = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern SHA256_HEX = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set PUBLIC_JWK_FIELDS = + Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final DSLContext dsl; + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates its trusted injected DSLContext; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtSignerDesiredStateRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Enrolls the fixed Account environment only after both protected trust bindings and a live + * fixed-ConfigMap observation have been reconciled by the enrollment owner. + */ + @Transactional(propagation = Propagation.MANDATORY) + public DesiredState initialize(Binding binding, EnrollmentIdentity enrollmentIdentity) { + requireWritableAccountTransaction(); + Objects.requireNonNull(binding, "JWT signer binding is required"); + Objects.requireNonNull(enrollmentIdentity, "Pinned JWT signer enrollment is required"); + int inserted = + dsl.execute( + "INSERT INTO " + + STATE_TABLE + + " (environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "private_secret_name, public_jwks_config_map_name, record_version, " + + "durable_active_generation, durable_active_kid, published_active_generation, " + + "published_active_kid, generation_operation_id, prepared_operation_id, " + + "enrollment_cluster_incarnation_uid, enrollment_namespace_uid, " + + "enrollment_materializer_binding_digest, enrollment_materializer_config_revision, " + + "enrollment_api_binding_digest, enrollment_api_config_revision, " + + "enrollment_public_config_map_uid, enrollment_public_config_map_resource_version, " + + "enrollment_public_config_map_snapshot_digest) " + + "VALUES (?, ?, ?, ?, 'jwt-signing-keys', 'jwt-jwks', 1, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (environment_id) DO NOTHING", + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.mode().value(), + UUID.fromString(enrollmentIdentity.expectedClusterIncarnationUid()), + UUID.fromString(enrollmentIdentity.expectedNamespaceUid()), + enrollmentIdentity.materializerTrustBindingDigest(), + enrollmentIdentity.materializerTrustConfigRevision(), + enrollmentIdentity.apiBindingDigest(), + enrollmentIdentity.apiConfigRevision(), + UUID.fromString(enrollmentIdentity.publicConfigMapUid()), + enrollmentIdentity.publicConfigMapResourceVersion(), + enrollmentIdentity.publicConfigMapSnapshotDigest()); + if (inserted < 0 || inserted > 1) { + throw new StorageUnavailableException("Account JWT signer initialization was ambiguous"); + } + Record row = selectState(binding.environmentId(), true); + if (row == null) { + throw new QuarantinedStateException("Initialized Account JWT signer state did not read back"); + } + DesiredState state = decodeState(row); + requireBinding(state, binding); + if (state.enrollmentIdentity().isEmpty() + || !state.enrollmentIdentity().orElseThrow().sameStablePins(enrollmentIdentity)) { + throw new BindingMismatchException( + "Account JWT signer enrollment trust or precreated resource identity changed"); + } + if (inserted == 1 && !state.enrollmentIdentity().orElseThrow().equals(enrollmentIdentity)) { + throw new QuarantinedStateException( + "Initial Account JWT signer enrollment receipt did not read back exactly"); + } + if (inserted == 1 + && (state.recordVersion() != 1 + || state.durableActive().isPresent() + || state.publishedActive().isPresent() + || state.generationOperationId().isPresent() + || state.preparedOperationId().isPresent())) { + throw new QuarantinedStateException( + "New Account JWT signer state contains inferred or unexpected authority"); + } + return state; + } + + /** + * Returns a pinned enrollment row even while PREPARED so startup reconciliation can inspect it. + * Ordinary desired-state reads continue to quarantine PREPARED signer state. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional readEnrollmentState(Binding expectedBinding) { + requireAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Record row = selectState(expectedBinding.environmentId(), false); + if (row == null) { + return Optional.empty(); + } + DesiredState state = decodeState(row); + requireBinding(state, expectedBinding); + if (state.enrollmentIdentity().isEmpty()) { + throw new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity"); + } + return Optional.of(state); + } + + /** Reads an explicitly enrolled state; a missing row never initializes desired state. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public DesiredState read(Binding expectedBinding) { + requireAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Record row = selectState(expectedBinding.environmentId(), false); + if (row == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(row); + requireBinding(state, expectedBinding); + if (state.enrollmentIdentity().isEmpty()) { + throw new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity"); + } + verifyPreparedIsUnavailable(state); + if (state.generationOperationId().isPresent()) { + StoredGenerationOperation operation = + selectGenerationOperation(state.generationOperationId().orElseThrow(), false); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + } + return state; + } + + /** + * Account's internal operation entrypoint. It receives no caller-selected operation, key + * identity, resource name, fingerprint, or material. Account creates one immutable operation if + * absent, or returns the same operation under the same protected trust snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest ensureCurrentGenerationRequest( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + + if (state.generationOperationId().isEmpty()) { + if (state.durableActive().isPresent()) { + throw new MissingGenerationOperationException( + "Account has no durable rotation request for its committed signer"); + } + return createGenerationRequest(state, trust); + } + + StoredGenerationOperation operation = + selectGenerationOperation(state.generationOperationId().orElseThrow(), true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return readGenerationRequest(operation, state, true); + } + + /** + * Returns the same current Account-selected request and exact phase for an authenticated peer. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest readCurrentGenerationRequest(Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + UUID operationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no owner-selected JWT generation operation")); + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return readGenerationRequest(operation, state, true); + } + + /** + * Reads the exact immutable result for Account's current generation operation while locking the + * desired-state, operation, and result rows in their canonical order. A historical result is + * never returned after the Account operation or protected trust fence has moved. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationResult readCurrentGenerationResult(Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + UUID operationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no owner-selected JWT generation operation")); + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + GenerationResult result = selectGenerationResult(operationId, true); + if (result == null) { + throw new MissingGenerationObservationException( + "Account JWT generation result is not recorded for the current operation"); + } + verifyGenerationResultMatchesOperation(result, operation, state); + return result; + } + + /** + * Recovery-only read for the exact generation that owns the current PREPARED operation. It is + * intentionally distinct from ordinary serving/generation reads, which continue to fail closed + * while a promotion is unresolved. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedGenerationEvidence readPreparedGenerationForRecovery( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + UUID promotionId = + state.preparedOperationId().orElseThrow(() -> new NoPreparedPromotionException()); + if (state.generationOperationId().isPresent()) { + throw new QuarantinedStateException( + "Account PREPARED signer state also contains a generation pointer"); + } + StoredPromotion promotion = selectPromotion(promotionId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + StoredGenerationOperation operation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (operation == null || result == null) { + throw new QuarantinedStateException( + "Prepared JWT signer operation has incomplete generation evidence"); + } + verifyPreparedGenerationMatches(promotion, operation, result); + return new PreparedGenerationEvidence(state, promotion.publicEvidence(), result); + } + + /** + * Atomically records that the authenticated materializer may receive the immutable private-slot + * promotion operation. This marker is deliberately sticky: after it is committed, a lost RPC + * response is an uncertain external mutation and the operation must remain PREPARED for forward + * reconciliation. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedGenerationEvidence readAndMarkPreparedPromotionDispatched( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + PreparedGenerationEvidence evidence = readPreparedGenerationForRecovery(expectedBinding, trust); + UUID operationId = evidence.promotion().operationId(); + StoredPromotion promotion = selectPromotion(operationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + if (!promotion.privatePromotionDispatched()) { + int changed = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET private_promotion_dispatched_at = CURRENT_TIMESTAMP " + + "WHERE operation_id = ? AND status = 'PREPARED' " + + "AND private_promotion_dispatched_at IS NULL " + + "AND private_promotion_receipt_digest IS NULL " + + "AND active_jwks_receipt_digest IS NULL", + operationId); + if (changed != 1) { + throw new VersionConflictException( + "Account private promotion dispatch authorization CAS did not apply"); + } + promotion = selectPromotion(operationId, true); + } + if (promotion == null + || !promotion.privatePromotionDispatched() + || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException( + "Account private promotion dispatch authorization did not read back exactly"); + } + return evidence; + } + + /** + * Records one authenticated materializer readback of the exact fixed-Secret slot transition. Only + * public key identities, resource UID/RV, and slot names cross this boundary; private bytes and + * hashes of private bytes are neither accepted nor persisted. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PrivatePromotionReceipt recordPrivatePromotionResult( + Binding expectedBinding, TrustFence trust, PrivatePromotionObservation observation) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(observation, "Exact private promotion observation is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + if (!state.preparedOperationId().equals(Optional.of(observation.promotionOperationId())) + || state.generationOperationId().isPresent()) { + throw new StaleGenerationOperationException( + "Private promotion result does not target Account's current PREPARED operation"); + } + StoredPromotion promotion = selectPromotion(observation.promotionOperationId(), true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (!promotion.requestDigest().equals(observation.promotionRequestDigest()) + || !promotion.generationOperationId().equals(observation.generationOperationId()) + || !promotion.generationOperationDigest().equals(observation.generationOperationDigest())) { + throw new IdempotencyConflictException( + "Private promotion result does not match the exact Account operation"); + } + if (!promotion.privatePromotionDispatched()) { + throw new PromotionPrerequisitesIncompleteException( + "Private promotion result has no prior durable Account dispatch authorization"); + } + StoredGenerationOperation operation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (operation == null || result == null) { + throw new QuarantinedStateException( + "Prepared JWT signer operation has incomplete generation evidence"); + } + verifyPreparedGenerationMatches(promotion, operation, result); + requirePrivatePromotionObservation(promotion, observation); + PrivatePromotionReceipt candidate = PrivatePromotionReceipt.from(promotion, observation); + if (promotion.privatePromotionReceiptDigest() != null) { + if (!candidate.receiptDigest().equals(promotion.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.privatePromotionObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Private promotion readback changed for the same Account operation"); + } + return candidate; + } + int updated = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET private_promotion_observed_resource_version = ?, " + + "private_promotion_receipt_digest = ? WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_dispatched_at IS NOT NULL " + + "AND private_promotion_receipt_digest IS NULL", + candidate.observedResourceVersion(), + candidate.receiptDigest(), + candidate.promotionOperationId()); + if (updated != 1) { + throw new VersionConflictException("Account private promotion receipt CAS did not apply"); + } + StoredPromotion readback = selectPromotion(candidate.promotionOperationId(), true); + if (readback == null + || !candidate.receiptDigest().equals(readback.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(readback.privatePromotionObservedResourceVersion())) { + throw new QuarantinedStateException( + "Account private promotion receipt did not read back exactly"); + } + return candidate; + } + + /** + * Records Account's exact readback after its fixed public ConfigMap CAS changes only the + * generation marker from PREPUBLISHED to ACTIVE. The public receipt contains no private Secret + * bytes or digest of private material. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ActiveJwksPromotionReceipt recordActiveJwksPromotionResult( + Binding expectedBinding, TrustFence trust, ActiveJwksPromotionObservation observation) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(observation, "Exact Account ConfigMap promotion readback is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + UUID promotionId = + state + .preparedOperationId() + .orElseThrow( + () -> + new PromotionPrerequisitesIncompleteException( + "Account has no PREPARED JWT signer promotion")); + StoredPromotion promotion = selectPromotion(promotionId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionReceiptDigest() == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account cannot publish ACTIVE before the exact private-slot readback"); + } + requireActiveJwksObservation(promotion, observation); + ActiveJwksPromotionReceipt candidate = ActiveJwksPromotionReceipt.from(promotion, observation); + if (promotion.activeJwksReceiptDigest() != null) { + if (!candidate.receiptDigest().equals(promotion.activeJwksReceiptDigest()) + || !candidate.publicDataDigest().equals(promotion.activeJwksPublicDataDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.activeJwksObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Active Account JWT JWKS readback changed for the same promotion operation"); + } + return candidate; + } + int updated = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET active_jwks_observed_resource_version = ?, active_jwks_public_data_digest = ?, " + + "active_jwks_receipt_digest = ? WHERE operation_id = ? AND status = 'PREPARED' " + + "AND private_promotion_receipt_digest IS NOT NULL " + + "AND active_jwks_receipt_digest IS NULL", + candidate.observedResourceVersion(), + candidate.publicDataDigest(), + candidate.receiptDigest(), + candidate.promotionOperationId()); + if (updated != 1) { + throw new VersionConflictException("Account active JWKS promotion receipt CAS did not apply"); + } + StoredPromotion readback = selectPromotion(candidate.promotionOperationId(), true); + if (readback == null + || !candidate.receiptDigest().equals(readback.activeJwksReceiptDigest()) + || !candidate.publicDataDigest().equals(readback.activeJwksPublicDataDigest()) + || !candidate + .observedResourceVersion() + .equals(readback.activeJwksObservedResourceVersion())) { + throw new QuarantinedStateException("Account active JWKS receipt did not read back exactly"); + } + return candidate; + } + + /** + * Commits only after both exact external-resource receipts are durably read back. The promotion + * row and desired-state active fences transition in one Account transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CommittedSignerEvidence commitPreparedPromotion( + Binding expectedBinding, + TrustFence trust, + UUID promotionOperationId, + ReadinessPromotionProof readinessProof) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(promotionOperationId); + Objects.requireNonNull(readinessProof, "Current Account readiness proof is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + if (!state.preparedOperationId().equals(Optional.of(promotionOperationId))) { + throw new StaleGenerationOperationException( + "Commit does not target Account's exact PREPARED promotion"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account promotion lacks exact private and public resource receipts"); + } + if (!promotion.privatePromotionDispatched()) { + throw new QuarantinedStateException( + "Account promotion receipts have no durable private dispatch authorization"); + } + StoredGenerationOperation generation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (generation == null || result == null) { + throw new QuarantinedStateException("Committed signer generation evidence is missing"); + } + verifyPreparedGenerationMatches(promotion, generation, result); + PromotionPreparation commitPreparation = + new PromotionPreparation( + promotion.generationOperationId(), + result, + state.enrollmentIdentity().orElseThrow(), + promotion.apiBindingDigest(), + promotion.apiConfigRevision(), + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + promotion.prepublicationIntentDigest(), + promotion.prepublicationReceiptDigest(), + promotion.mountedObservationDigest(), + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + promotion.expectedPublicJwksJson()); + requireReadinessProofMatches( + result, commitPreparation, promotion, expectedBinding, trust, readinessProof); + requireUnexpiredCurrentReadinessProof(promotion, result, readinessProof); + + // State is locked first above, matching readiness expiry/cleanup's owner lock order. The + // terminal UPDATE repeats the clock and complete-entry fence atomically; the count query in + // the helper is a validation read, not an entry-row lock. + int changed = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET status = 'COMMITTED' WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_dispatched_at IS NOT NULL " + + "AND private_promotion_receipt_digest IS NOT NULL " + + "AND active_jwks_receipt_digest IS NOT NULL " + + "AND EXISTS (SELECT 1 FROM account_jwt_readiness_probe_plans plan " + + "WHERE plan.rotation_operation_id = ? AND plan.plan_digest = ? " + + "AND plan.validator_inventory_complete = TRUE " + + "AND plan.not_before_epoch_seconds <= " + + "floor(extract(epoch FROM clock_timestamp()))::BIGINT " + + "AND plan.expires_at_epoch_seconds > " + + "floor(extract(epoch FROM clock_timestamp()))::BIGINT) " + + "AND (SELECT count(*) FROM account_jwt_readiness_probe_entries entry " + + "WHERE entry.rotation_operation_id = ? AND entry.plan_digest = ?) = ? " + + "AND (SELECT count(*) FROM account_jwt_readiness_probe_entries entry " + + "WHERE entry.rotation_operation_id = ? AND entry.plan_digest = ? " + + "AND entry.state = 'VERIFIED' AND entry.verification_receipt_sha256 IS NOT NULL " + + "AND entry.verified_at_epoch_seconds < entry.expires_at_epoch_seconds " + + "AND entry.expires_at_epoch_seconds > " + + "floor(extract(epoch FROM clock_timestamp()))::BIGINT) = ?", + promotionOperationId, + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + readinessProof.verifiedProbes().size(), + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + readinessProof.verifiedProbes().size()); + if (changed != 1) { + throw new VersionConflictException("Account promotion terminal CAS did not apply"); + } + int advanced = + dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, durable_active_generation = ?, " + + "durable_active_kid = ?, published_active_generation = ?, published_active_kid = ?, " + + "prepared_operation_id = NULL, updated_at = CURRENT_TIMESTAMP " + + "WHERE environment_id = ? AND cluster_id = ? AND kubernetes_namespace = ? " + + "AND custody_mode = ? AND record_version = ? AND prepared_operation_id = ? " + + "AND generation_operation_id IS NULL " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ?", + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + promotionOperationId, + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + if (advanced != 1) { + throw new VersionConflictException("Account committed active-signer CAS did not apply"); + } + StoredPromotion committed = selectPromotion(promotionOperationId, true); + Record committedStateRow = selectState(expectedBinding.environmentId(), true); + if (committed == null || committedStateRow == null || !"COMMITTED".equals(committed.status())) { + throw new QuarantinedStateException("Account committed promotion did not read back"); + } + DesiredState committedState = decodeState(committedStateRow); + requireCommittedStateMatches(committed, committedState); + return new CommittedSignerEvidence( + committed.publicEvidence(), + result, + committedState, + PrivatePromotionReceipt.fromStored(committed), + ActiveJwksPromotionReceipt.fromStored(committed)); + } + + /** + * Aborts only before either Kubernetes mutation was recorded. Once either external write may have + * happened, the operation remains PREPARED for exact forward recovery rather than guessing + * rollback state. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AbortedPromotion abortPreparedBeforeMutation( + Binding expectedBinding, TrustFence trust, UUID promotionOperationId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(promotionOperationId); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + if (!state.preparedOperationId().equals(Optional.of(promotionOperationId))) { + throw new StaleGenerationOperationException( + "Abort does not target the exact PREPARED operation"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionDispatched() + || promotion.privatePromotionReceiptDigest() != null + || promotion.activeJwksReceiptDigest() != null) { + throw new PromotionPrerequisitesIncompleteException( + "A dispatched promotion must remain PREPARED for forward reconciliation"); + } + int changed = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET status = 'ABORTED' WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_receipt_digest IS NULL " + + "AND active_jwks_receipt_digest IS NULL " + + "AND private_promotion_dispatched_at IS NULL", + promotionOperationId); + if (changed != 1) + throw new VersionConflictException("Account promotion abort CAS did not apply"); + int advanced = + dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, prepared_operation_id = NULL, " + + "updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? AND record_version = ? " + + "AND prepared_operation_id = ? AND generation_operation_id IS NULL", + expectedBinding.environmentId(), + state.recordVersion(), + promotionOperationId); + if (advanced != 1) + throw new VersionConflictException("Account signer abort state CAS did not apply"); + StoredPromotion aborted = selectPromotion(promotionOperationId, true); + DesiredState abortedState = decodeState(selectState(expectedBinding.environmentId(), true)); + if (aborted == null + || !"ABORTED".equals(aborted.status()) + || abortedState.preparedOperationId().isPresent()) { + throw new QuarantinedStateException("Account aborted promotion did not read back exactly"); + } + return new AbortedPromotion( + promotionOperationId, + abortedState.recordVersion(), + abortedState.durableActive(), + abortedState.publishedActive()); + } + + /** Reads only the exact Account-committed generation and both durable resource receipts. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentCommittedSigner( + Binding expectedBinding, + TrustFence trust, + String currentApiBindingDigest, + String currentApiConfigRevision) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) return Optional.empty(); + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + EnrollmentIdentity enrollment = state.enrollmentIdentity().orElseThrow(); + requireMatch(SHA256_HEX, currentApiBindingDigest, "current public API binding digest"); + requireMatch(CLUSTER_ID, currentApiConfigRevision, "current public API config revision"); + if (!enrollment.apiBindingDigest().equals(currentApiBindingDigest) + || !enrollment.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException("Protected Account JWKS API binding changed"); + } + if (state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Account signer lifecycle is unresolved and cannot serve a committed signer"); + } + if (state.durableActive().isEmpty() || !state.durableActive().equals(state.publishedActive())) { + throw new QuarantinedStateException( + "Account durable and published active signer fences disagree"); + } + ActiveSigner active = state.durableActive().orElseThrow(); + if (state.generationOperationId().isPresent()) { + StoredGenerationOperation pending = + selectGenerationOperation(state.generationOperationId().orElseThrow(), false); + if (pending == null) { + throw new QuarantinedStateException("Current Account generation operation is missing"); + } + verifyOperationMatchesState(pending, state); + requireCurrentTrust(pending, trust); + } + StoredPromotion promotion = selectCommittedPromotion(state, active); + if (promotion == null) { + throw new QuarantinedStateException( + "Account active signer has no exact committed promotion receipt"); + } + requireCurrentTrust(promotion, trust); + requireCommittedActiveStillCurrent(promotion, state); + if (!promotion.apiBindingDigest().equals(currentApiBindingDigest) + || !promotion.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException( + "Committed signer uses an obsolete Account JWKS API binding"); + } + StoredGenerationOperation generation = + selectGenerationOperation(promotion.generationOperationId(), false); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), false); + if (generation == null || result == null) { + throw new QuarantinedStateException("Committed Account generation result is missing"); + } + verifyPreparedGenerationMatches(promotion, generation, result); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException( + "Committed Account signer is missing exact resource receipts"); + } + return Optional.of( + new CommittedSignerEvidence( + promotion.publicEvidence(), + result, + state, + PrivatePromotionReceipt.fromStored(promotion), + ActiveJwksPromotionReceipt.fromStored(promotion))); + } + + /** Persists the pinned materializer's read-only observation of the fixed pre-created Secret. */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest recordSecretObservation( + Binding expectedBinding, + TrustFence trust, + UUID operationId, + String operationDigest, + String secretUid, + String observedResourceVersion) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, operationDigest, "JWT generation operation digest"); + requireUuid(secretUid, "fixed Secret UID"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + + LockedCurrent current = lockCurrentOperation(expectedBinding, trust, operationId); + if (!current.operation().operationDigest().equals(operationDigest)) { + throw new IdempotencyConflictException( + "JWT signer Secret observation does not match the Account operation digest"); + } + SecretObservation candidate = + SecretObservation.from(current.operation(), secretUid, observedResourceVersion); + SecretObservation existing = selectSecretObservation(operationId, true); + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer Secret observation changed for the same Account operation"); + } + return readGenerationRequest(current.operation(), current.state(), true); + } + + insertSecretObservation(candidate); + SecretObservation readback = selectSecretObservation(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account JWT signer Secret observation did not read back exactly"); + } + return toGenerationRequest(current.operation(), current.state(), readback, null); + } + + /** + * Persists one public-only key-generation result. Account validates the canonical RSA JWK and + * derives the RFC 7638 fingerprint; private members, tokens, and caller fingerprints are not + * accepted. Exact retries return the immutable receipt; changed/stale retries fail closed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationResult recordGenerationResult( + Binding expectedBinding, + TrustFence trust, + UUID operationId, + String generationRequestDigest, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + String publicJwkJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, generationRequestDigest, "JWT generation request digest"); + requireUuid(secretUid, "fixed Secret UID"); + requireMatch(RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret resourceVersion"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + if (expectedPriorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException("JWT signer Secret resourceVersion did not advance"); + } + PublicJwk publicJwk = parsePublicJwk(publicJwkJson); + + LockedCurrent current = lockCurrentOperation(expectedBinding, trust, operationId); + StoredGenerationOperation operation = current.operation(); + SecretObservation observation = selectSecretObservation(operationId, true); + if (observation == null) { + throw new MissingGenerationObservationException( + "JWT signer generation cannot precede exact Secret observation"); + } + if (!observation.secretUid().equals(secretUid) + || !observation.observedResourceVersion().equals(expectedPriorResourceVersion) + || !observation.generationRequestDigest().equals(generationRequestDigest)) { + throw new StaleGenerationOperationException( + "JWT signer generation result does not match the observed Secret fence"); + } + if (!publicJwk.kid().equals(operation.targetKid()) + || !ALGORITHM.equals(operation.targetAlgorithm())) { + throw new QuarantinedStateException( + "JWT signer public JWK does not match the Account-selected key identity"); + } + + GenerationResult candidate = + GenerationResult.from( + operation, + current.state().recordVersion(), + observation, + observedResourceVersion, + publicJwk); + GenerationResult existing = selectGenerationResult(operationId, true); + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer generation result changed for the same Account operation"); + } + return existing; + } + + insertGenerationResult(candidate); + GenerationResult readback = selectGenerationResult(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account JWT signer generation result did not read back exactly"); + } + return readback; + } + + /** + * Persists PREPARED only for exact owner-readback generation, prepublication, and readiness + * evidence supplied by the lifecycle coordinator. The database independently locks and checks the + * generation/publication/readiness rows; caller booleans and signer/JWKS agreement alone cannot + * enter PREPARED. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedPromotion prepareCurrentGeneration( + Binding expectedBinding, + TrustFence trust, + PromotionPreparation preparation, + ReadinessPromotionProof readinessProof) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(preparation, "Owner-readback promotion preparation is required"); + Objects.requireNonNull(readinessProof, "Account-verified readiness proof is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + EnrollmentIdentity enrollment = state.enrollmentIdentity().orElseThrow(); + if (!enrollment.sameStablePins(preparation.enrollmentIdentity()) + || !enrollment.apiBindingDigest().equals(preparation.apiBindingDigest()) + || !enrollment.apiConfigRevision().equals(preparation.apiConfigRevision()) + || !enrollment.publicConfigMapUid().equals(preparation.publicConfigMapUid())) { + throw new BindingMismatchException( + "JWT signer promotion trust does not match the independently pinned enrollment"); + } + if (state.preparedOperationId().isPresent()) { + StoredPromotion replay = selectPromotion(state.preparedOperationId().orElseThrow(), true); + if (replay == null || !"PREPARED".equals(replay.status())) { + throw new QuarantinedStateException("Account PREPARED promotion is missing"); + } + requirePromotionMatchesState(replay, state); + requireCurrentTrust(replay, trust); + StoredGenerationOperation replayGeneration = + selectGenerationOperation(replay.generationOperationId(), true); + GenerationResult replayResult = selectGenerationResult(replay.generationOperationId(), true); + if (replayGeneration == null || replayResult == null) { + throw new QuarantinedStateException("Prepared promotion source generation is missing"); + } + verifyPreparedGenerationMatches(replay, replayGeneration, replayResult); + if (!replay.matchesPreparation(preparation, replayGeneration, replayResult, enrollment)) { + throw new IdempotencyConflictException( + "JWT signer promotion retry changed its immutable evidence"); + } + requireReadinessProofMatches( + replayResult, preparation, replay, expectedBinding, trust, readinessProof); + return new PreparedPromotion(replay.operationId(), replay.requestDigest(), "PREPARED"); + } + UUID generationOperationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no current generation operation to promote")); + StoredGenerationOperation generation = selectGenerationOperation(generationOperationId, true); + GenerationResult result = selectGenerationResult(generationOperationId, true); + if (generation == null || result == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account generation operation has no exact persisted result"); + } + verifyOperationMatchesState(generation, state); + requireCurrentTrust(generation, trust); + verifyGenerationResultMatchesOperation(result, generation, state); + if (!result.equals(preparation.generationResult()) + || !preparation.generationOperationId().equals(generationOperationId)) { + throw new StaleGenerationOperationException( + "Promotion preparation does not match the exact current generation result"); + } + requireReadinessProofMatches(result, preparation, null, expectedBinding, trust, readinessProof); + requireCurrentPublicationForPreparation(result, preparation); + requireCurrentReadinessForPreparation(result, preparation); + + StoredPromotion candidate = + StoredPromotion.create(preparation, state, generation, result, trust, expectedBinding); + StoredPromotion existing = selectPromotion(candidate.operationId(), true); + if (existing != null) { + requirePromotionMatchesState(existing, state); + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer promotion request changed for the same operation"); + } + return new PreparedPromotion(existing.operationId(), existing.requestDigest(), "PREPARED"); + } + insertPromotion(candidate); + int advanced = advanceToPrepared(state, candidate.operationId()); + if (advanced != 1) { + throw new VersionConflictException("Account desired state changed while entering PREPARED"); + } + StoredPromotion readback = selectPromotion(candidate.operationId(), true); + Record stateReadbackRow = selectState(expectedBinding.environmentId(), true); + if (readback == null || stateReadbackRow == null || !readback.equals(candidate)) { + throw new QuarantinedStateException("Account PREPARED promotion did not read back exactly"); + } + DesiredState stateReadback = decodeState(stateReadbackRow); + requirePromotionMatchesState(readback, stateReadback); + return new PreparedPromotion(readback.operationId(), readback.requestDigest(), "PREPARED"); + } + + private static void requireReadinessProofMatches( + GenerationResult result, + PromotionPreparation preparation, + StoredPromotion preparedReplay, + Binding expectedBinding, + TrustFence trust, + ReadinessPromotionProof proof) { + var plan = proof.plan(); + var publication = proof.publication(); + if (!proof.generationResult().equals(result) + || !preparation.generationResult().equals(result) + || !plan.operationId().equals(result.operationId()) + || !plan.binding().equals(expectedBinding) + || !plan.trustFence().equals(trust) + || !plan.planDigest().equals(preparation.readinessPlanDigest()) + || !proof.readinessEvidenceDigest().equals(preparation.readinessEvidenceDigest()) + || !plan.operationDigest().equals(result.operationDigest()) + || !plan.generationRequestDigest().equals(result.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(result.receiptDigest()) + || plan.desiredStateVersion() != result.desiredStateVersion() + || !plan.targetGeneration().equals(result.targetGeneration()) + || !plan.targetKid().equals(result.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !publication.intent().intentDigest().equals(preparation.prepublicationIntentDigest()) + || !publication.receipt().receiptDigest().equals(preparation.prepublicationReceiptDigest()) + || !publication + .mountedCorrespondence() + .observationDigest() + .equals(preparation.mountedObservationDigest()) + || !publication.intent().configMapUid().equals(preparation.publicConfigMapUid()) + || !publication + .receipt() + .observedResourceVersion() + .equals(preparation.expectedPublicResourceVersion()) + || !publication.intent().apiBindingDigest().equals(preparation.apiBindingDigest()) + || !publication.intent().apiConfigRevision().equals(preparation.apiConfigRevision()) + || !publication.intent().jwksJson().equals(preparation.expectedPublicJwksJson())) { + throw new PromotionPrerequisitesIncompleteException( + "Account readiness proof does not match the exact generation and publication"); + } + if (preparedReplay != null + && (!preparedReplay.readinessPlanDigest().equals(plan.planDigest()) + || !preparedReplay.readinessEvidenceDigest().equals(proof.readinessEvidenceDigest()))) { + throw new IdempotencyConflictException( + "Readiness recovery proof changed for the exact PREPARED promotion"); + } + if (!plan.validatorInventoryComplete() + || proof.inventoryEvidenceReference() == null + || !proof.inventoryEvidenceReference().matches("[A-Za-z0-9][A-Za-z0-9._:/-]{0,511}") + || proof.inventoryEvidenceDigest() == null + || !proof.inventoryEvidenceDigest().matches("[0-9a-f]{64}") + || proof.verifiedProbes().isEmpty() + || !proof.readinessEvidenceDigest().matches("[0-9a-f]{64}") + || !publication.intent().operationId().equals(result.operationId()) + || !publication.receipt().operationId().equals(result.operationId()) + || !publication.mountedCorrespondence().operationId().equals(result.operationId()) + || !publication.intent().intentDigest().equals(plan.publicationIntentDigest()) + || !publication.receipt().receiptDigest().equals(plan.publicationReceiptDigest()) + || !publication + .mountedCorrespondence() + .observationDigest() + .equals(plan.mountedObservationDigest())) { + throw new PromotionPrerequisitesIncompleteException( + "Account readiness proof lacks exact publication or protected inventory evidence"); + } + } + + private GenerationRequest createGenerationRequest(DesiredState state, TrustFence trust) { + if (state.recordVersion() == Long.MAX_VALUE) { + throw new VersionConflictException("Account JWT signer state version is exhausted"); + } + long previousGeneration = + Math.max( + state.durableActive().map(value -> parseGeneration(value.generation())).orElse(0L), + state.publishedActive().map(value -> parseGeneration(value.generation())).orElse(0L)); + if (previousGeneration == Long.MAX_VALUE) { + throw new VersionConflictException("Account JWT signer generation is exhausted"); + } + long targetGeneration = previousGeneration + 1; + UUID operationId = UUID.randomUUID(); + String targetKid = "jwt-" + targetGeneration + "-" + operationId.toString().substring(0, 12); + StoredGenerationOperation operation = + StoredGenerationOperation.create(state, trust, operationId, targetGeneration, targetKid); + insertGenerationOperation(operation); + int changed = advanceToGenerationRequest(state, operationId); + if (changed != 1) { + throw new VersionConflictException( + "Account JWT signer state changed during request creation"); + } + Record readbackStateRow = selectState(state.binding().environmentId(), true); + Record readbackOperationRow = selectGenerationOperationRow(operationId, true); + if (readbackStateRow == null || readbackOperationRow == null) { + throw new QuarantinedStateException("Account JWT generation request did not read back"); + } + DesiredState readbackState = decodeState(readbackStateRow); + StoredGenerationOperation readbackOperation = decodeGenerationOperation(readbackOperationRow); + requireBinding(readbackState, state.binding()); + verifyOperationMatchesState(readbackOperation, readbackState); + if (!readbackOperation.equals(operation)) { + throw new QuarantinedStateException("Account JWT generation request changed on readback"); + } + return readGenerationRequest(readbackOperation, readbackState, true); + } + + private GenerationRequest readGenerationRequest( + StoredGenerationOperation operation, DesiredState state, boolean lockEvidence) { + GenerationResult result = selectGenerationResult(operation.operationId(), lockEvidence); + if (result != null) { + verifyGenerationResultMatchesOperation(result, operation, state); + return toGenerationRequest(operation, state, null, result); + } + SecretObservation observation = selectSecretObservation(operation.operationId(), lockEvidence); + if (observation != null) { + verifySecretObservationMatchesOperation(observation, operation, state); + } + return toGenerationRequest(operation, state, observation, null); + } + + private static void verifySecretObservationMatchesOperation( + SecretObservation observation, StoredGenerationOperation operation, DesiredState state) { + if (!observation.operationId().equals(operation.operationId()) + || !observation.binding().equals(operation.binding()) + || !observation.operationDigest().equals(operation.operationDigest()) + || observation.expectedRecordVersion() != operation.expectedRecordVersion() + || !observation.trustFence().equals(operation.trustFence()) + || state.recordVersion() != operation.expectedRecordVersion() + 1) { + throw new QuarantinedStateException( + "JWT signer Secret observation is not bound to its operation"); + } + } + + private static void verifyGenerationResultMatchesOperation( + GenerationResult result, StoredGenerationOperation operation, DesiredState state) { + if (!result.operationId().equals(operation.operationId()) + || !result.binding().equals(operation.binding()) + || !result.operationDigest().equals(operation.operationDigest()) + || !result.trustFence().equals(operation.trustFence()) + || result.desiredStateVersion() != state.recordVersion() + || !result.targetGeneration().equals(operation.targetGeneration()) + || !result.targetKid().equals(operation.targetKid()) + || !result.targetAlgorithm().equals(operation.targetAlgorithm())) { + throw new QuarantinedStateException( + "JWT signer generation result is not bound to its operation"); + } + } + + private GenerationRequest toGenerationRequest( + StoredGenerationOperation operation, + DesiredState state, + SecretObservation observation, + GenerationResult result) { + GenerationPhase phase = + result != null + ? GenerationPhase.GENERATION_RECORDED + : observation != null + ? GenerationPhase.GENERATE_PENDING + : GenerationPhase.OBSERVE_PRIVATE_SECRET; + return new GenerationRequest( + phase, + operation.operationId(), + operation.operationDigest(), + result != null + ? result.generationRequestDigest() + : observation == null ? "" : observation.generationRequestDigest(), + state.recordVersion(), + operation.binding(), + operation.trustFence(), + PRIVATE_SECRET_NAME, + operation.targetGeneration(), + operation.targetKid(), + operation.targetAlgorithm(), + ACTION, + List.of(PENDING_SLOT), + operation.expectedPreviousActive(), + operation.expectedPublishedActive(), + result != null ? result.secretUid() : observation == null ? "" : observation.secretUid(), + result != null + ? result.expectedPriorResourceVersion() + : observation == null ? "" : observation.observedResourceVersion(), + result == null ? "" : result.receiptDigest(), + result == null ? "" : result.publicKeyFingerprint(), + result == null ? "" : result.publicJwkJson(), + result == null ? "" : result.observedResourceVersion()); + } + + private LockedCurrent lockCurrentOperation( + Binding expectedBinding, TrustFence trust, UUID operationId) { + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + if (!state.generationOperationId().equals(Optional.of(operationId))) { + throw new StaleGenerationOperationException( + "JWT signer request does not target Account's current generation operation"); + } + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return new LockedCurrent(state, operation); + } + + private void requireCurrentTrust(StoredGenerationOperation operation, TrustFence current) { + if (!operation.trustFence().equals(current)) { + throw new BindingMismatchException( + "JWT materializer trust or namespace incarnation changed for the generation operation"); + } + } + + private static void requireEnrollmentTrust(DesiredState state, TrustFence trust) { + EnrollmentIdentity enrolled = + state + .enrollmentIdentity() + .orElseThrow( + () -> + new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity")); + if (!enrolled.expectedClusterIncarnationUid().equals(trust.expectedClusterIncarnationUid()) + || !enrolled.expectedNamespaceUid().equals(trust.expectedNamespaceUid()) + || !enrolled.materializerTrustBindingDigest().equals(trust.bindingDigest()) + || !enrolled.materializerTrustConfigRevision().equals(trust.configRevision())) { + throw new BindingMismatchException( + "JWT materializer trust no longer matches Account's pinned enrollment"); + } + } + + private void verifyOperationMatchesState( + StoredGenerationOperation operation, DesiredState state) { + if (!state.generationOperationId().equals(Optional.of(operation.operationId())) + || !operation.binding().equals(state.binding()) + || operation.expectedRecordVersion() == Long.MAX_VALUE + || state.recordVersion() != operation.expectedRecordVersion() + 1 + || !operation.expectedPreviousActive().equals(state.durableActive()) + || !operation.expectedPublishedActive().equals(state.publishedActive()) + || !REQUEST_DIGEST_VERSION.equals(operation.digestVersion()) + || !generationOperationDigest(operation).equals(operation.operationDigest())) { + throw new QuarantinedStateException( + "Account JWT signer generation request does not match current desired state"); + } + } + + private Record selectState(String environmentId, boolean lock) { + return dsl.fetchOne( + "SELECT environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "private_secret_name, public_jwks_config_map_name, record_version, " + + "durable_active_generation, durable_active_kid, published_active_generation, " + + "published_active_kid, generation_operation_id, prepared_operation_id, " + + "enrollment_cluster_incarnation_uid, enrollment_namespace_uid, " + + "enrollment_materializer_binding_digest, enrollment_materializer_config_revision, " + + "enrollment_api_binding_digest, enrollment_api_config_revision, " + + "enrollment_public_config_map_uid, enrollment_public_config_map_resource_version, " + + "enrollment_public_config_map_snapshot_digest FROM " + + STATE_TABLE + + " WHERE environment_id = ?" + + (lock ? " FOR UPDATE" : ""), + environmentId); + } + + private StoredPromotion selectPromotion(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT p.operation_id, p.environment_id, p.cluster_id, p.kubernetes_namespace, p.custody_mode, " + + "p.request_digest_version, p.request_digest, p.expected_record_version, " + + "p.expected_previous_generation, p.expected_previous_kid, p.target_generation, p.target_kid, " + + "p.target_algorithm, p.target_public_key_fingerprint, " + + "p.expected_private_secret_resource_version, p.expected_public_jwks_resource_version, " + + "p.expected_public_active_generation, p.expected_public_active_kid, p.operation_action, " + + "p.allowed_private_slots_canonical_bytes, p.status, p.generation_operation_id, " + + "p.expected_cluster_incarnation_uid, p.expected_namespace_uid, " + + "p.materializer_trust_binding_digest, p.materializer_trust_config_revision, " + + "p.api_binding_digest, p.api_config_revision, p.expected_private_secret_uid, " + + "p.expected_public_config_map_uid, p.prepublication_intent_digest, " + + "p.prepublication_receipt_digest, p.mounted_observation_digest, p.readiness_plan_digest, " + + "p.readiness_evidence_digest, p.expected_public_jwks_json, " + + "p.expected_active_generation_marker_json, " + + "(p.private_promotion_dispatched_at IS NOT NULL) AS private_promotion_dispatched, " + + "p.private_promotion_observed_resource_version, " + + "p.private_promotion_receipt_digest, p.active_jwks_observed_resource_version, " + + "p.active_jwks_public_data_digest, p.active_jwks_receipt_digest, " + + "generation.operation_digest AS generation_operation_digest, " + + "generation_result.receipt_digest AS generation_receipt_digest " + + "FROM " + + PROMOTION_TABLE + + " AS p " + + "JOIN " + + OPERATION_TABLE + + " AS generation " + + "ON generation.operation_id = p.generation_operation_id " + + "JOIN " + + RESULT_TABLE + + " AS generation_result " + + "ON generation_result.operation_id = p.generation_operation_id " + + "WHERE p.operation_id = ?" + + (lock ? " FOR UPDATE OF p, generation, generation_result" : ""), + operationId); + return row == null ? null : decodePromotion(row); + } + + private StoredPromotion selectCommittedPromotion(DesiredState state, ActiveSigner active) { + Result rows = + dsl.fetch( + "SELECT operation_id FROM " + + PROMOTION_TABLE + + " WHERE environment_id = ? AND cluster_id = ? AND kubernetes_namespace = ? " + + "AND custody_mode = ? AND status = 'COMMITTED' AND target_generation = ? " + + "AND target_kid = ? ORDER BY created_at DESC LIMIT 2", + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + parseGeneration(active.generation()), + active.kid()); + if (rows.size() != 1) { + throw new QuarantinedStateException( + "Account active signer does not resolve to exactly one committed promotion"); + } + UUID operationId = rows.get(0).get("operation_id", UUID.class); + return selectPromotion(operationId, false); + } + + private static void requireCommittedStateMatches(StoredPromotion promotion, DesiredState state) { + ActiveSigner expected = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.binding().equals(state.binding()) + || state.preparedOperationId().isPresent() + || state.generationOperationId().isPresent() + || state.durableActive().filter(expected::equals).isEmpty() + || state.publishedActive().filter(expected::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() != promotion.expectedRecordVersion() + 2 + || promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException( + "Committed Account signer does not match its exact operation and active fences"); + } + } + + private static void requireCommittedActiveStillCurrent( + StoredPromotion promotion, DesiredState state) { + ActiveSigner expected = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.binding().equals(state.binding()) + || state.preparedOperationId().isPresent() + || state.durableActive().filter(expected::equals).isEmpty() + || state.publishedActive().filter(expected::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() < promotion.expectedRecordVersion() + 2) { + throw new QuarantinedStateException( + "Committed Account promotion is not the current active signer"); + } + } + + private static void requireActiveJwksObservation( + StoredPromotion promotion, ActiveJwksPromotionObservation observation) { + if (!promotion.publicConfigMapUid().equals(observation.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(observation.priorResourceVersion()) + || observation.priorResourceVersion().equals(observation.observedResourceVersion()) + || !promotion.expectedPublicJwksJson().equals(observation.jwksJson()) + || !promotion.expectedActiveMarkerJson().equals(observation.activeMarkerJson())) { + throw new QuarantinedStateException( + "Account ConfigMap CAS did not read back the exact authorized ACTIVE projection"); + } + requireActiveMarkerMatchesPromotion(promotion, observation.activeMarkerJson()); + } + + private static void requireActiveMarkerMatchesPromotion( + StoredPromotion promotion, String marker) { + try { + JsonNode root = STRICT_JSON.readTree(marker); + if (root == null + || !root.isObject() + || root.size() != 11 + || !root.path("schemaVersion").isIntegralNumber() + || root.path("schemaVersion").intValue() != 1 + || !"ACTIVE".equals(requiredText(root, "phase", 16)) + || !promotion + .generationOperationId() + .toString() + .equals(requiredText(root, "operationId", 36)) + || !promotion + .generationOperationDigest() + .equals(requiredText(root, "operationDigest", 64)) + || !promotion + .generationReceiptDigest() + .equals(requiredText(root, "generationReceiptDigest", 64)) + || !markerBindingMatches(promotion, root.get("binding")) + || !markerFenceMatches( + promotion, root.get("expectedDurableActive"), promotion.expectedPreviousActive()) + || !markerFenceMatches( + promotion, root.get("expectedPublishedActive"), promotion.expectedPublishedActive()) + || !markerPublicMapMatches(root.get("publicConfigMap")) + || !markerPromotionMatches(promotion, root.get("promotion"))) { + throw new IllegalArgumentException("Active marker mismatch"); + } + JsonNode active = root.get("active"); + if (active == null + || !active.isObject() + || active.size() != 4 + || !promotion.targetGeneration().equals(requiredText(active, "generation", 19)) + || !promotion.targetKid().equals(requiredText(active, "kid", 64)) + || !ALGORITHM.equals(requiredText(active, "algorithm", 16)) + || !promotion + .targetPublicKeyFingerprint() + .equals(requiredText(active, "publicKeyFingerprint", 64))) { + throw new IllegalArgumentException("Active signer mismatch"); + } + } catch (RuntimeException ex) { + throw new QuarantinedStateException("Account ACTIVE generation marker is malformed", ex); + } + } + + private static boolean markerBindingMatches(StoredPromotion promotion, JsonNode binding) { + return binding != null + && binding.isObject() + && binding.size() == 9 + && promotion.binding().environmentId().equals(requiredText(binding, "environmentId", 64)) + && promotion.binding().clusterId().equals(requiredText(binding, "clusterId", 128)) + && promotion.binding().namespace().equals(requiredText(binding, "namespace", 64)) + && promotion + .trustFence() + .expectedClusterIncarnationUid() + .equals(requiredText(binding, "expectedClusterIncarnationUid", 36)) + && promotion + .trustFence() + .expectedNamespaceUid() + .equals(requiredText(binding, "expectedNamespaceUid", 36)) + && promotion + .trustFence() + .bindingDigest() + .equals(requiredText(binding, "trustBindingDigest", 64)) + && promotion + .trustFence() + .configRevision() + .equals(requiredText(binding, "trustConfigRevision", 128)) + && promotion.apiBindingDigest().equals(requiredText(binding, "apiBindingDigest", 64)) + && promotion.apiConfigRevision().equals(requiredText(binding, "apiConfigRevision", 128)); + } + + private static boolean markerFenceMatches( + StoredPromotion promotion, JsonNode fence, Optional expected) { + return fence != null && parseMarkerActive(fence).equals(expected); + } + + private static Optional parseMarkerActive(JsonNode fence) { + if (fence == null || !fence.isObject()) { + throw new IllegalArgumentException("Active marker fence is malformed"); + } + if (fence.size() == 1 + && fence.path("present").isBoolean() + && !fence.path("present").booleanValue()) { + return Optional.empty(); + } + if (fence.size() == 3 + && fence.path("present").isBoolean() + && fence.path("present").booleanValue()) { + return Optional.of( + new ActiveSigner(requiredText(fence, "generation", 19), requiredText(fence, "kid", 64))); + } + throw new IllegalArgumentException("Active marker fence is malformed"); + } + + private static boolean markerPublicMapMatches(JsonNode publicMap) { + return publicMap != null + && publicMap.isObject() + && publicMap.size() == 1 + && PUBLIC_JWKS_CONFIG_MAP_NAME.equals(requiredText(publicMap, "name", 64)); + } + + private static boolean markerPromotionMatches(StoredPromotion promotion, JsonNode proof) { + return proof != null + && proof.isObject() + && proof.size() == 7 + && promotion.operationId().toString().equals(requiredText(proof, "operationId", 36)) + && promotion.requestDigest().equals(requiredText(proof, "requestDigest", 64)) + && promotion + .prepublicationIntentDigest() + .equals(requiredText(proof, "prepublicationIntentDigest", 64)) + && promotion + .prepublicationReceiptDigest() + .equals(requiredText(proof, "prepublicationReceiptDigest", 64)) + && promotion + .mountedObservationDigest() + .equals(requiredText(proof, "mountedObservationDigest", 64)) + && promotion.readinessPlanDigest().equals(requiredText(proof, "readinessPlanDigest", 64)) + && promotion + .readinessEvidenceDigest() + .equals(requiredText(proof, "readinessEvidenceDigest", 64)); + } + + private static String activeMarkerJson(StoredPromotion promotion) { + Map marker = new LinkedHashMap<>(); + marker.put("schemaVersion", 1); + marker.put("phase", "ACTIVE"); + marker.put("operationId", promotion.generationOperationId().toString()); + marker.put("operationDigest", promotion.generationOperationDigest()); + marker.put("generationReceiptDigest", promotion.generationReceiptDigest()); + Map binding = new LinkedHashMap<>(); + binding.put("environmentId", promotion.binding().environmentId()); + binding.put("clusterId", promotion.binding().clusterId()); + binding.put("namespace", promotion.binding().namespace()); + binding.put( + "expectedClusterIncarnationUid", promotion.trustFence().expectedClusterIncarnationUid()); + binding.put("expectedNamespaceUid", promotion.trustFence().expectedNamespaceUid()); + binding.put("trustBindingDigest", promotion.trustFence().bindingDigest()); + binding.put("trustConfigRevision", promotion.trustFence().configRevision()); + binding.put("apiBindingDigest", promotion.apiBindingDigest()); + binding.put("apiConfigRevision", promotion.apiConfigRevision()); + marker.put("binding", binding); + marker.put("publicConfigMap", Map.of("name", PUBLIC_JWKS_CONFIG_MAP_NAME)); + marker.put("expectedDurableActive", activeMarker(promotion.expectedPreviousActive())); + marker.put("expectedPublishedActive", activeMarker(promotion.expectedPublishedActive())); + marker.put( + "active", + Map.of( + "generation", promotion.targetGeneration(), + "kid", promotion.targetKid(), + "algorithm", promotion.targetAlgorithm(), + "publicKeyFingerprint", promotion.targetPublicKeyFingerprint())); + marker.put( + "promotion", + Map.of( + "operationId", promotion.operationId().toString(), + "requestDigest", promotion.requestDigest(), + "prepublicationIntentDigest", promotion.prepublicationIntentDigest(), + "prepublicationReceiptDigest", promotion.prepublicationReceiptDigest(), + "mountedObservationDigest", promotion.mountedObservationDigest(), + "readinessPlanDigest", promotion.readinessPlanDigest(), + "readinessEvidenceDigest", promotion.readinessEvidenceDigest())); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(marker)), + StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new StorageUnavailableException("Account ACTIVE JWT marker could not be canonicalized"); + } + } + + private static Map activeMarker(Optional active) { + Map marker = new LinkedHashMap<>(); + marker.put("present", active.isPresent()); + active.ifPresent( + signer -> { + marker.put("generation", signer.generation()); + marker.put("kid", signer.kid()); + }); + return marker; + } + + private static String requiredText(JsonNode object, String name, int maxLength) { + JsonNode value = object.get(name); + if (value == null + || !value.isTextual() + || value.textValue().isEmpty() + || value.textValue().length() > maxLength) { + throw new IllegalArgumentException("Account JWT signer JSON field is malformed"); + } + return value.textValue(); + } + + private static void requirePromotionMatchesState(StoredPromotion promotion, DesiredState state) { + if (!promotion.binding().equals(state.binding()) + || !state.preparedOperationId().equals(Optional.of(promotion.operationId())) + || state.generationOperationId().isPresent() + || state.recordVersion() != promotion.expectedRecordVersion() + 1 + || !promotion.expectedPreviousActive().equals(state.durableActive()) + || !promotion.expectedPublishedActive().equals(state.publishedActive()) + || !promotion.requestDigest().equals(promotionRequestDigest(promotion))) { + throw new QuarantinedStateException( + "Account PREPARED promotion does not match its exact desired-state fence"); + } + } + + private static void requireCurrentTrust(StoredPromotion promotion, TrustFence current) { + if (!promotion.trustFence().equals(current)) { + throw new BindingMismatchException( + "JWT materializer trust or namespace incarnation changed during promotion"); + } + } + + private static void verifyPreparedGenerationMatches( + StoredPromotion promotion, StoredGenerationOperation operation, GenerationResult result) { + if (!promotion.generationOperationId().equals(operation.operationId()) + || !promotion.binding().equals(operation.binding()) + || !promotion.operationDigestForGeneration().equals(operation.operationDigest()) + || !promotion.expectedPreviousActive().equals(operation.expectedPreviousActive()) + || !promotion.expectedPublishedActive().equals(operation.expectedPublishedActive()) + || !promotion.targetGeneration().equals(operation.targetGeneration()) + || !promotion.targetKid().equals(operation.targetKid()) + || !ALGORITHM.equals(operation.targetAlgorithm()) + || !promotion.trustFence().equals(operation.trustFence()) + || !promotion.generationOperationId().equals(result.operationId()) + || !promotion.generationReceiptDigest().equals(result.receiptDigest()) + || !promotion.secretUid().equals(result.secretUid()) + || !promotion.expectedPrivateResourceVersion().equals(result.observedResourceVersion()) + || !promotion.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw new QuarantinedStateException( + "Prepared promotion is not bound to the exact source generation result"); + } + } + + private static void requirePrivatePromotionObservation( + StoredPromotion promotion, PrivatePromotionObservation observation) { + Optional expectedPrevious = + promotion + .expectedPreviousActive() + .map( + active -> + new PublicKeyIdentity( + active.generation(), + active.kid(), + publicFingerprintForKid(promotion.expectedPublicJwksJson(), active.kid()))); + PublicKeyIdentity expectedCurrent = + new PublicKeyIdentity( + promotion.targetGeneration(), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint()); + List expectedSlots = + expectedPrevious.isPresent() ? List.of("current", "previous") : List.of("current"); + if (!observation.secretUid().equals(promotion.secretUid()) + || !observation + .expectedPriorResourceVersion() + .equals(promotion.expectedPrivateResourceVersion()) + || observation.expectedPriorResourceVersion().equals(observation.observedResourceVersion()) + || !expectedCurrent.equals(observation.current()) + || !expectedPrevious.equals(observation.previous()) + || !expectedSlots.equals(observation.resultingSlots())) { + throw new QuarantinedStateException( + "Materializer did not read back the exact authorized private slot transition"); + } + } + + private static String publicFingerprintForKid(String jwksJson, String kid) { + try { + JsonNode root = STRICT_JSON.readTree(jwksJson); + JsonNode keys = root == null ? null : root.get("keys"); + if (keys == null || !keys.isArray()) { + throw new IllegalArgumentException("JWKS keys are malformed"); + } + String found = null; + for (JsonNode key : keys) { + if (key != null && key.isObject() && kid.equals(requiredText(key, "kid", 64))) { + if (found != null) { + throw new IllegalArgumentException("JWKS contains a duplicate kid"); + } + found = + digest( + Map.of( + "e", + requiredText(key, "e", 16), + "kty", + "RSA", + "n", + requiredText(key, "n", 4096))); + } + } + if (found == null) { + throw new IllegalArgumentException("Expected prior public key is missing from JWKS"); + } + return found; + } catch (Exception ex) { + throw new QuarantinedStateException("Expected prior public key identity is unavailable", ex); + } + } + + private StoredPromotion decodePromotion(Record row) { + try { + byte[] slots = row.get("allowed_private_slots_canonical_bytes", byte[].class); + if (!Arrays.equals(PROMOTION_SLOTS_CANONICAL_BYTES, slots) + || !"PROMOTE_PENDING".equals(row.get("operation_action", String.class))) { + throw new QuarantinedStateException( + "Account promotion action or fixed Secret slots are malformed"); + } + StoredPromotion promotion = + new StoredPromotion( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + Math.toIntExact( + positive( + row.get("request_digest_version", Short.class).longValue(), + "promotion digest version")), + row.get("request_digest", String.class), + positive( + row.get("expected_record_version", Long.class), "expected signer state version"), + activeOptional( + row.get("expected_previous_generation", Long.class), + row.get("expected_previous_kid", String.class), + "previous signer"), + activeOptional( + row.get("expected_public_active_generation", Long.class), + row.get("expected_public_active_kid", String.class), + "published previous signer"), + canonicalGeneration( + row.get("target_generation", Long.class), "promotion target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + row.get("target_public_key_fingerprint", String.class), + row.get("expected_private_secret_resource_version", String.class), + row.get("expected_public_jwks_resource_version", String.class), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("materializer_trust_binding_digest", String.class), + row.get("materializer_trust_config_revision", String.class)), + row.get("generation_operation_id", UUID.class), + row.get("generation_operation_digest", String.class), + row.get("generation_receipt_digest", String.class), + row.get("api_binding_digest", String.class), + row.get("api_config_revision", String.class), + row.get("expected_private_secret_uid", UUID.class).toString(), + row.get("expected_public_config_map_uid", UUID.class).toString(), + row.get("prepublication_intent_digest", String.class), + row.get("prepublication_receipt_digest", String.class), + row.get("mounted_observation_digest", String.class), + row.get("readiness_plan_digest", String.class), + row.get("readiness_evidence_digest", String.class), + row.get("expected_public_jwks_json", String.class), + row.get("expected_active_generation_marker_json", String.class), + row.get("status", String.class), + Boolean.TRUE.equals(row.get("private_promotion_dispatched", Boolean.class)), + row.get("private_promotion_observed_resource_version", String.class), + row.get("private_promotion_receipt_digest", String.class), + row.get("active_jwks_observed_resource_version", String.class), + row.get("active_jwks_public_data_digest", String.class), + row.get("active_jwks_receipt_digest", String.class)); + if (promotion.requestDigestVersion() != 1 + || !promotionRequestDigest(promotion).equals(promotion.requestDigest())) { + throw new QuarantinedStateException("Account promotion operation digest is invalid"); + } + return promotion; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account promotion operation is malformed", ex); + } + } + + private static String promotionRequestDigest(StoredPromotion promotion) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", PROMOTION_DIGEST_VERSION); + preimage.put("operationId", promotion.operationId().toString()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("environmentId", promotion.binding().environmentId()); + preimage.put("clusterId", promotion.binding().clusterId()); + preimage.put("namespace", promotion.binding().namespace()); + preimage.put("custodyMode", promotion.binding().mode().value()); + preimage.put("expectedRecordVersion", Long.toString(promotion.expectedRecordVersion())); + preimage.put("expectedPreviousActive", activeDigestValue(promotion.expectedPreviousActive())); + preimage.put("expectedPublishedActive", activeDigestValue(promotion.expectedPublishedActive())); + preimage.put("targetGeneration", promotion.targetGeneration()); + preimage.put("targetKid", promotion.targetKid()); + preimage.put("targetAlgorithm", ALGORITHM); + preimage.put("targetPublicKeyFingerprint", promotion.targetPublicKeyFingerprint()); + preimage.put("expectedPrivateSecretUid", promotion.secretUid()); + preimage.put( + "expectedPrivateSecretResourceVersion", promotion.expectedPrivateResourceVersion()); + preimage.put("expectedPublicConfigMapUid", promotion.publicConfigMapUid()); + preimage.put("expectedPublicJwksResourceVersion", promotion.expectedPublicResourceVersion()); + preimage.put( + "expectedClusterIncarnationUid", promotion.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", promotion.trustFence().expectedNamespaceUid()); + preimage.put("materializerTrustBindingDigest", promotion.trustFence().bindingDigest()); + preimage.put("materializerTrustConfigRevision", promotion.trustFence().configRevision()); + preimage.put("apiBindingDigest", promotion.apiBindingDigest()); + preimage.put("apiConfigRevision", promotion.apiConfigRevision()); + preimage.put("prepublicationIntentDigest", promotion.prepublicationIntentDigest()); + preimage.put("prepublicationReceiptDigest", promotion.prepublicationReceiptDigest()); + preimage.put("mountedObservationDigest", promotion.mountedObservationDigest()); + preimage.put("readinessPlanDigest", promotion.readinessPlanDigest()); + preimage.put("readinessEvidenceDigest", promotion.readinessEvidenceDigest()); + preimage.put("publicJwksSha256", sha256(promotion.expectedPublicJwksJson())); + preimage.put("operationAction", "PROMOTE_PENDING"); + preimage.put("allowedPrivateSlots", List.of("current", "pending", "previous")); + return digest(preimage); + } + + private Record selectGenerationOperationRow(UUID operationId, boolean lock) { + return dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, " + + "expected_published_generation, expected_published_kid, target_generation, target_kid, " + + "target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, operation_action, " + + "allowed_private_slots_canonical_bytes FROM " + + OPERATION_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + } + + private StoredGenerationOperation selectGenerationOperation(UUID operationId, boolean lock) { + Record row = selectGenerationOperationRow(operationId, lock); + return row == null ? null : decodeGenerationOperation(row); + } + + private SecretObservation selectSecretObservation(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, expected_record_version, expected_cluster_incarnation_uid, " + + "expected_namespace_uid, trust_binding_digest, trust_config_revision, " + + "private_secret_name, secret_uid, observed_resource_version, observation_digest, " + + "generation_request_digest FROM " + + OBSERVATION_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeSecretObservation(row); + } + + private GenerationResult selectGenerationResult(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, desired_state_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, " + + "expected_prior_resource_version, observed_resource_version, target_generation, " + + "target_kid, target_algorithm, public_key_fingerprint, public_jwk_json, receipt_digest " + + "FROM " + + RESULT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeGenerationResult(row); + } + + private void insertGenerationOperation(StoredGenerationOperation operation) { + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, " + + "expected_published_generation, expected_published_kid, target_generation, target_kid, " + + "target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, operation_action, " + + "allowed_private_slots_canonical_bytes) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'MATERIALIZE_PENDING', ?) ", + operation.operationId(), + operation.binding().environmentId(), + operation.binding().clusterId(), + operation.binding().namespace(), + operation.binding().mode().value(), + operation.operationDigest(), + operation.expectedRecordVersion(), + generationValue(operation.expectedPreviousActive()), + kidValue(operation.expectedPreviousActive()), + generationValue(operation.expectedPublishedActive()), + kidValue(operation.expectedPublishedActive()), + parseGeneration(operation.targetGeneration()), + operation.targetKid(), + operation.targetAlgorithm(), + UUID.fromString(operation.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(operation.trustFence().expectedNamespaceUid()), + operation.trustFence().bindingDigest(), + operation.trustFence().configRevision(), + PENDING_SLOT_CANONICAL_BYTES); + if (inserted != 1) { + throw new StorageUnavailableException( + "Account JWT generation operation insert was ambiguous"); + } + } + + private void requireCurrentPublicationForPreparation( + GenerationResult result, PromotionPreparation preparation) { + Record evidence = + dsl.fetchOne( + "SELECT intent.operation_id, intent.intent_digest, intent.environment_id, intent.cluster_id, " + + "intent.kubernetes_namespace, intent.custody_mode, intent.operation_digest, " + + "intent.generation_request_digest, intent.generation_receipt_digest, " + + "intent.desired_state_version, intent.expected_cluster_incarnation_uid, " + + "intent.expected_namespace_uid, intent.trust_binding_digest, " + + "intent.trust_config_revision, intent.api_binding_digest, intent.api_config_revision, " + + "intent.config_map_name, intent.config_map_uid, intent.jwks_json, " + + "receipt.receipt_digest, receipt.observed_resource_version, " + + "mount.observation_digest FROM account_jwt_jwks_prepublication_intents AS intent " + + "JOIN account_jwt_jwks_publication_receipts AS receipt " + + "ON receipt.operation_id = intent.operation_id " + + "AND receipt.intent_digest = intent.intent_digest " + + "JOIN account_jwt_jwks_mount_observations AS mount " + + "ON mount.operation_id = intent.operation_id " + + "WHERE intent.operation_id = ? FOR UPDATE OF intent, receipt, mount", + result.operationId()); + if (evidence == null + || !preparation + .prepublicationIntentDigest() + .equals(evidence.get("intent_digest", String.class)) + || !preparation + .prepublicationReceiptDigest() + .equals(evidence.get("receipt_digest", String.class)) + || !preparation + .mountedObservationDigest() + .equals(evidence.get("observation_digest", String.class)) + || !preparation + .publicConfigMapUid() + .equals(evidence.get("config_map_uid", UUID.class).toString()) + || !preparation + .expectedPublicResourceVersion() + .equals(evidence.get("observed_resource_version", String.class)) + || !preparation.apiBindingDigest().equals(evidence.get("api_binding_digest", String.class)) + || !preparation + .apiConfigRevision() + .equals(evidence.get("api_config_revision", String.class)) + || !preparation.expectedPublicJwksJson().equals(evidence.get("jwks_json", String.class)) + || !result.operationId().equals(evidence.get("operation_id", UUID.class)) + || !result.operationDigest().equals(evidence.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(evidence.get("generation_request_digest", String.class)) + || !result.receiptDigest().equals(evidence.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != evidence.get("desired_state_version", Long.class)) { + throw new PromotionPrerequisitesIncompleteException( + "Exact Account JWKS prepublication, API readback, or mount receipt is unavailable"); + } + } + + private void requireCurrentReadinessForPreparation( + GenerationResult result, PromotionPreparation preparation) { + Record plan = + dsl.fetchOne( + "SELECT plan_digest, operation_digest, generation_request_digest, " + + "generation_receipt_digest, desired_state_version, target_generation, target_kid, " + + "target_public_key_fingerprint, publication_intent_digest, " + + "publication_receipt_digest, mounted_observation_digest, " + + "validator_inventory_complete, expires_at_epoch_seconds " + + "FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = ? " + + "AND plan_digest = ? FOR UPDATE", + result.operationId(), + preparation.readinessPlanDigest()); + if (plan == null + || !Boolean.TRUE.equals(plan.get("validator_inventory_complete", Boolean.class)) + || plan.get("expires_at_epoch_seconds", Long.class) == null + || plan.get("expires_at_epoch_seconds", Long.class) == null + || !result.operationDigest().equals(plan.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(plan.get("generation_request_digest", String.class)) + || !result.receiptDigest().equals(plan.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != plan.get("desired_state_version", Long.class) + || !result + .targetGeneration() + .equals(String.valueOf(plan.get("target_generation", Long.class))) + || !result.targetKid().equals(plan.get("target_kid", String.class)) + || !result + .publicKeyFingerprint() + .equals(plan.get("target_public_key_fingerprint", String.class)) + || !preparation + .prepublicationIntentDigest() + .equals(plan.get("publication_intent_digest", String.class)) + || !preparation + .prepublicationReceiptDigest() + .equals(plan.get("publication_receipt_digest", String.class)) + || !preparation + .mountedObservationDigest() + .equals(plan.get("mounted_observation_digest", String.class))) { + throw new PromotionPrerequisitesIncompleteException( + "Complete current Account JWT readiness proof is unavailable"); + } + Record entries = + dsl.fetchOne( + "SELECT count(*) AS total, count(*) FILTER (WHERE state = 'VERIFIED' " + + "AND verification_receipt_sha256 IS NOT NULL " + + "AND verified_at_epoch_seconds < expires_at_epoch_seconds) AS verified " + + "FROM account_jwt_readiness_probe_entries WHERE rotation_operation_id = ? " + + "AND plan_digest = ? AND EXISTS (SELECT 1 FROM account_jwt_readiness_probe_plans " + + "WHERE rotation_operation_id = ? AND plan_digest = ? " + + "AND expires_at_epoch_seconds > floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT)", + result.operationId(), + preparation.readinessPlanDigest(), + result.operationId(), + preparation.readinessPlanDigest()); + if (entries == null + || entries.get("total", Long.class) == null + || entries.get("total", Long.class) <= 0 + || !entries.get("total", Long.class).equals(entries.get("verified", Long.class))) { + throw new PromotionPrerequisitesIncompleteException( + "Every exact current Account JWT validator probe must be VERIFIED"); + } + } + + /** + * Rechecks the owner-created typed proof at the durable COMMITTED boundary. A proof read before + * this transaction is insufficient: the plan and every VERIFIED entry must still be inside their + * recorded validity window when Account commits the promotion. + */ + private void requireUnexpiredCurrentReadinessProof( + StoredPromotion promotion, GenerationResult result, ReadinessPromotionProof proof) { + var expectedPlan = proof.plan(); + Record currentPlan = + dsl.fetchOne( + "SELECT plan_digest, operation_digest, generation_request_digest, " + + "generation_receipt_digest, desired_state_version, target_generation, target_kid, " + + "target_public_key_fingerprint, publication_intent_digest, " + + "publication_receipt_digest, mounted_observation_digest, " + + "applicability_matrix_digest, validator_inventory_complete, " + + "maximum_cache_age_seconds, not_before_epoch_seconds, expires_at_epoch_seconds, " + + "floor(extract(epoch FROM clock_timestamp()))::bigint AS checked_epoch " + + "FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = ? " + + "AND plan_digest = ? FOR UPDATE", + result.operationId(), + promotion.readinessPlanDigest()); + if (currentPlan == null + || !Boolean.TRUE.equals(currentPlan.get("validator_inventory_complete", Boolean.class)) + || !promotion.readinessPlanDigest().equals(currentPlan.get("plan_digest", String.class)) + || !result.operationDigest().equals(currentPlan.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(currentPlan.get("generation_request_digest", String.class)) + || !result + .receiptDigest() + .equals(currentPlan.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != currentPlan.get("desired_state_version", Long.class) + || !result + .targetGeneration() + .equals(String.valueOf(currentPlan.get("target_generation", Long.class))) + || !result.targetKid().equals(currentPlan.get("target_kid", String.class)) + || !result + .publicKeyFingerprint() + .equals(currentPlan.get("target_public_key_fingerprint", String.class)) + || !promotion + .prepublicationIntentDigest() + .equals(currentPlan.get("publication_intent_digest", String.class)) + || !promotion + .prepublicationReceiptDigest() + .equals(currentPlan.get("publication_receipt_digest", String.class)) + || !promotion + .mountedObservationDigest() + .equals(currentPlan.get("mounted_observation_digest", String.class)) + || !expectedPlan + .applicabilityMatrixDigest() + .equals(currentPlan.get("applicability_matrix_digest", String.class)) + || expectedPlan.maximumCacheAgeSeconds() + != currentPlan.get("maximum_cache_age_seconds", Short.class) + || expectedPlan.notBeforeEpochSecond() + != currentPlan.get("not_before_epoch_seconds", Long.class) + || expectedPlan.expiresAtEpochSecond() + != currentPlan.get("expires_at_epoch_seconds", Long.class) + || currentPlan.get("checked_epoch", Long.class) == null + || currentPlan.get("checked_epoch", Long.class) < expectedPlan.notBeforeEpochSecond() + || currentPlan.get("checked_epoch", Long.class) >= expectedPlan.expiresAtEpochSecond()) { + throw new PromotionPrerequisitesIncompleteException( + "Exact Account readiness proof is missing, changed, or expired at commit"); + } + + Record currentEntries = + dsl.fetchOne( + "SELECT count(*) AS total, count(*) FILTER (WHERE state = 'VERIFIED' " + + "AND verification_receipt_sha256 IS NOT NULL " + + "AND verified_at_epoch_seconds < expires_at_epoch_seconds " + + "AND expires_at_epoch_seconds > floor(extract(epoch FROM clock_timestamp()))::bigint) " + + "AS verified FROM account_jwt_readiness_probe_entries " + + "WHERE rotation_operation_id = ? AND plan_digest = ?", + result.operationId(), + promotion.readinessPlanDigest()); + Long total = currentEntries == null ? null : currentEntries.get("total", Long.class); + Long verified = currentEntries == null ? null : currentEntries.get("verified", Long.class); + if (total == null + || verified == null + || total <= 0L + || total != proof.verifiedProbes().size() + || !total.equals(verified)) { + throw new PromotionPrerequisitesIncompleteException( + "Every exact Account validator proof must remain VERIFIED and unexpired at commit"); + } + } + + private void insertPromotion(StoredPromotion promotion) { + int inserted = + dsl.execute( + "INSERT INTO " + + PROMOTION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "request_digest_version, request_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, target_generation, target_kid, " + + "target_algorithm, target_public_key_fingerprint, " + + "expected_private_secret_resource_version, expected_public_jwks_resource_version, " + + "expected_public_active_generation, expected_public_active_kid, operation_action, " + + "allowed_private_slots_canonical_bytes, status, generation_operation_id, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, " + + "materializer_trust_binding_digest, materializer_trust_config_revision, " + + "api_binding_digest, api_config_revision, expected_private_secret_uid, " + + "expected_public_config_map_uid, prepublication_intent_digest, " + + "prepublication_receipt_digest, mounted_observation_digest, readiness_plan_digest, " + + "readiness_evidence_digest, expected_public_jwks_json, " + + "expected_active_generation_marker_json) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'RS256', ?, ?, ?, ?, ?, " + + "'PROMOTE_PENDING', ?, 'PREPARED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + promotion.operationId(), + promotion.binding().environmentId(), + promotion.binding().clusterId(), + promotion.binding().namespace(), + promotion.binding().mode().value(), + promotion.requestDigest(), + promotion.expectedRecordVersion(), + generationValue(promotion.expectedPreviousActive()), + kidValue(promotion.expectedPreviousActive()), + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint(), + promotion.expectedPrivateResourceVersion(), + promotion.expectedPublicResourceVersion(), + generationValue(promotion.expectedPublishedActive()), + kidValue(promotion.expectedPublishedActive()), + PROMOTION_SLOTS_CANONICAL_BYTES, + promotion.generationOperationId(), + UUID.fromString(promotion.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(promotion.trustFence().expectedNamespaceUid()), + promotion.trustFence().bindingDigest(), + promotion.trustFence().configRevision(), + promotion.apiBindingDigest(), + promotion.apiConfigRevision(), + UUID.fromString(promotion.secretUid()), + UUID.fromString(promotion.publicConfigMapUid()), + promotion.prepublicationIntentDigest(), + promotion.prepublicationReceiptDigest(), + promotion.mountedObservationDigest(), + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson()); + if (inserted != 1) { + throw new StorageUnavailableException("Account promotion operation insert was ambiguous"); + } + } + + private int advanceToPrepared(DesiredState state, UUID promotionOperationId) { + return dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, generation_operation_id = NULL, " + + "prepared_operation_id = ?, updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? " + + "AND cluster_id = ? AND kubernetes_namespace = ? AND custody_mode = ? " + + "AND record_version = ? AND generation_operation_id = ? AND prepared_operation_id IS NULL " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ?", + promotionOperationId, + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + state.generationOperationId().orElseThrow(), + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + } + + private int advanceToGenerationRequest(DesiredState state, UUID operationId) { + return dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, generation_operation_id = ?, " + + "updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? AND cluster_id = ? " + + "AND kubernetes_namespace = ? AND custody_mode = ? " + + "AND private_secret_name = 'jwt-signing-keys' " + + "AND public_jwks_config_map_name = 'jwt-jwks' AND record_version = ? " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ? " + + "AND generation_operation_id IS NULL AND prepared_operation_id IS NULL", + operationId, + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + } + + private void insertSecretObservation(SecretObservation observation) { + int inserted = + dsl.execute( + "INSERT INTO " + + OBSERVATION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, observed_resource_version, " + + "observation_digest_version, observation_digest, generation_request_digest) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'jwt-signing-keys', ?, ?, 1, ?, ?)", + observation.operationId(), + observation.binding().environmentId(), + observation.binding().clusterId(), + observation.binding().namespace(), + observation.binding().mode().value(), + observation.operationDigest(), + observation.expectedRecordVersion(), + UUID.fromString(observation.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(observation.trustFence().expectedNamespaceUid()), + observation.trustFence().bindingDigest(), + observation.trustFence().configRevision(), + UUID.fromString(observation.secretUid()), + observation.observedResourceVersion(), + observation.observationDigest(), + observation.generationRequestDigest()); + if (inserted != 1) { + throw new StorageUnavailableException("Account JWT Secret observation insert was ambiguous"); + } + } + + private void insertGenerationResult(GenerationResult result) { + int inserted = + dsl.execute( + "INSERT INTO " + + RESULT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, desired_state_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, " + + "expected_prior_resource_version, observed_resource_version, target_generation, " + + "target_kid, target_algorithm, public_key_fingerprint, public_jwk_json, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'jwt-signing-keys', ?, ?, ?, ?, ?, 'RS256', ?, ?, ?)", + result.operationId(), + result.binding().environmentId(), + result.binding().clusterId(), + result.binding().namespace(), + result.binding().mode().value(), + result.operationDigest(), + result.generationRequestDigest(), + result.desiredStateVersion(), + UUID.fromString(result.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(result.trustFence().expectedNamespaceUid()), + result.trustFence().bindingDigest(), + result.trustFence().configRevision(), + UUID.fromString(result.secretUid()), + result.expectedPriorResourceVersion(), + result.observedResourceVersion(), + parseGeneration(result.targetGeneration()), + result.targetKid(), + result.publicKeyFingerprint(), + result.publicJwkJson(), + result.receiptDigest()); + if (inserted != 1) { + throw new StorageUnavailableException("Account JWT generation result insert was ambiguous"); + } + } + + private DesiredState decodeState(Record row) { + try { + if (!PRIVATE_SECRET_NAME.equals(row.get("private_secret_name", String.class)) + || !PUBLIC_JWKS_CONFIG_MAP_NAME.equals( + row.get("public_jwks_config_map_name", String.class))) { + throw new QuarantinedStateException("Account JWT signer resource binding is malformed"); + } + return new DesiredState( + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + positive(row.get("record_version", Long.class), "Account JWT signer record version"), + activeOptional( + row.get("durable_active_generation", Long.class), + row.get("durable_active_kid", String.class), + "durable active signer"), + activeOptional( + row.get("published_active_generation", Long.class), + row.get("published_active_kid", String.class), + "published active signer"), + Optional.ofNullable(row.get("generation_operation_id", UUID.class)), + Optional.ofNullable(row.get("prepared_operation_id", UUID.class)), + enrollmentIdentity(row)); + } catch (RuntimeException ex) { + throw new QuarantinedStateException("Account JWT signer desired state is malformed", ex); + } + } + + private static Optional enrollmentIdentity(Record row) { + UUID clusterUid = row.get("enrollment_cluster_incarnation_uid", UUID.class); + UUID namespaceUid = row.get("enrollment_namespace_uid", UUID.class); + String materializerDigest = row.get("enrollment_materializer_binding_digest", String.class); + String materializerRevision = row.get("enrollment_materializer_config_revision", String.class); + String apiDigest = row.get("enrollment_api_binding_digest", String.class); + String apiRevision = row.get("enrollment_api_config_revision", String.class); + UUID configMapUid = row.get("enrollment_public_config_map_uid", UUID.class); + String resourceVersion = row.get("enrollment_public_config_map_resource_version", String.class); + String snapshotDigest = row.get("enrollment_public_config_map_snapshot_digest", String.class); + boolean allAbsent = + clusterUid == null + && namespaceUid == null + && materializerDigest == null + && materializerRevision == null + && apiDigest == null + && apiRevision == null + && configMapUid == null + && resourceVersion == null + && snapshotDigest == null; + if (allAbsent) { + return Optional.empty(); + } + if (clusterUid == null + || namespaceUid == null + || materializerDigest == null + || materializerRevision == null + || apiDigest == null + || apiRevision == null + || configMapUid == null + || resourceVersion == null + || snapshotDigest == null) { + throw new QuarantinedStateException("Account JWT signer enrollment pins are partial"); + } + return Optional.of( + new EnrollmentIdentity( + clusterUid.toString(), + namespaceUid.toString(), + materializerDigest, + materializerRevision, + apiDigest, + apiRevision, + configMapUid.toString(), + resourceVersion, + snapshotDigest)); + } + + private StoredGenerationOperation decodeGenerationOperation(Record row) { + try { + String slotBytes = + new String( + row.get("allowed_private_slots_canonical_bytes", byte[].class), + StandardCharsets.UTF_8); + if (!"[\"pending\"]".equals(slotBytes)) { + throw new QuarantinedStateException("JWT signer operation private slots are malformed"); + } + Integer digestVersion = row.get("operation_digest_version", Integer.class); + StoredGenerationOperation operation = + new StoredGenerationOperation( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + digestVersion != null && digestVersion == 1 ? REQUEST_DIGEST_VERSION : "unsupported", + row.get("operation_digest", String.class), + positive(row.get("expected_record_version", Long.class), "expected state version"), + activeOptional( + row.get("expected_previous_generation", Long.class), + row.get("expected_previous_kid", String.class), + "expected active signer"), + activeOptional( + row.get("expected_published_generation", Long.class), + row.get("expected_published_kid", String.class), + "expected published signer"), + canonicalGeneration(row.get("target_generation", Long.class), "target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class))); + if (!ACTION.equals(row.get("operation_action", String.class))) { + throw new QuarantinedStateException("JWT signer operation action is unsupported"); + } + if (!generationOperationDigest(operation).equals(operation.operationDigest())) { + throw new QuarantinedStateException("JWT signer operation digest is invalid"); + } + return operation; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException( + "Account JWT signer generation operation is malformed", ex); + } + } + + private SecretObservation decodeSecretObservation(Record row) { + try { + SecretObservation observation = + new SecretObservation( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + row.get("operation_digest", String.class), + positive(row.get("expected_record_version", Long.class), "expected state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("private_secret_name", String.class), + row.get("secret_uid", UUID.class).toString(), + row.get("observed_resource_version", String.class), + row.get("observation_digest", String.class), + row.get("generation_request_digest", String.class)); + if (!observationDigest( + observation.operationDigest(), + observation.trustFence(), + observation.secretUid(), + observation.observedResourceVersion()) + .equals(observation.observationDigest()) + || !generationRequestDigest(observation).equals(observation.generationRequestDigest())) { + throw new QuarantinedStateException("JWT signer Secret observation digest is invalid"); + } + return observation; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account JWT Secret observation is malformed", ex); + } + } + + private GenerationResult decodeGenerationResult(Record row) { + try { + GenerationResult result = + new GenerationResult( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + positive(row.get("desired_state_version", Long.class), "desired state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("private_secret_name", String.class), + row.get("secret_uid", UUID.class).toString(), + row.get("expected_prior_resource_version", String.class), + row.get("observed_resource_version", String.class), + canonicalGeneration(row.get("target_generation", Long.class), "target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + row.get("public_key_fingerprint", String.class), + row.get("public_jwk_json", String.class), + row.get("receipt_digest", String.class)); + PublicJwk jwk = parsePublicJwk(result.publicJwkJson()); + if (!jwk.kid().equals(result.targetKid()) + || !jwk.fingerprint().equals(result.publicKeyFingerprint()) + || !generationReceiptDigest(result).equals(result.receiptDigest())) { + throw new QuarantinedStateException("JWT signer generation receipt digest is invalid"); + } + return result; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account JWT generation result is malformed", ex); + } + } + + private static void verifyPreparedIsUnavailable(DesiredState state) { + if (state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Existing PREPARED signer state requires unavailable lifecycle evidence"); + } + } + + private static void requireBinding(DesiredState state, Binding expected) { + if (!state.binding().equals(expected)) { + throw new BindingMismatchException( + "Account JWT signer environment, cluster, namespace, or custody binding changed"); + } + } + + private static String generationOperationDigest(StoredGenerationOperation operation) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", REQUEST_DIGEST_VERSION); + preimage.put("environmentId", operation.binding().environmentId()); + preimage.put("clusterId", operation.binding().clusterId()); + preimage.put("namespace", operation.binding().namespace()); + preimage.put("custodyMode", operation.binding().mode().value()); + preimage.put("privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("operationId", operation.operationId().toString()); + preimage.put("expectedRecordVersion", Long.toString(operation.expectedRecordVersion())); + preimage.put("expectedPreviousActive", activeDigestValue(operation.expectedPreviousActive())); + preimage.put("expectedPublishedActive", activeDigestValue(operation.expectedPublishedActive())); + preimage.put("targetGeneration", operation.targetGeneration()); + preimage.put("targetKid", operation.targetKid()); + preimage.put("targetAlgorithm", operation.targetAlgorithm()); + preimage.put("operationAction", ACTION); + preimage.put("allowedPrivateSlots", List.of(PENDING_SLOT)); + preimage.put( + "expectedClusterIncarnationUid", operation.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", operation.trustFence().expectedNamespaceUid()); + preimage.put("trustBindingDigest", operation.trustFence().bindingDigest()); + preimage.put("trustConfigRevision", operation.trustFence().configRevision()); + return digest(preimage); + } + + private static String observationDigest( + String operationDigest, TrustFence trust, String secretUid, String resourceVersion) { + return digest( + Map.of( + "digestVersion", OBSERVATION_DIGEST_VERSION, + "operationDigest", operationDigest, + "privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME), + "expectedClusterIncarnationUid", trust.expectedClusterIncarnationUid(), + "expectedNamespaceUid", trust.expectedNamespaceUid(), + "trustBindingDigest", trust.bindingDigest(), + "trustConfigRevision", trust.configRevision(), + "secretUid", secretUid, + "observedResourceVersion", resourceVersion)); + } + + private static String generationRequestDigest(SecretObservation observation) { + return digest( + Map.of( + "digestVersion", GENERATION_REQUEST_DIGEST_VERSION, + "operationDigest", observation.operationDigest(), + "observationDigest", observation.observationDigest(), + "secretUid", observation.secretUid(), + "expectedPriorResourceVersion", observation.observedResourceVersion(), + "target", "pending")); + } + + private static String generationReceiptDigest(GenerationResult result) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", RECEIPT_DIGEST_VERSION); + preimage.put("operationId", result.operationId().toString()); + preimage.put("operationDigest", result.operationDigest()); + preimage.put("generationRequestDigest", result.generationRequestDigest()); + preimage.put("desiredStateVersion", Long.toString(result.desiredStateVersion())); + preimage.put("environmentId", result.binding().environmentId()); + preimage.put("clusterId", result.binding().clusterId()); + preimage.put("namespace", result.binding().namespace()); + preimage.put( + "expectedClusterIncarnationUid", result.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", result.trustFence().expectedNamespaceUid()); + preimage.put("trustBindingDigest", result.trustFence().bindingDigest()); + preimage.put("trustConfigRevision", result.trustFence().configRevision()); + preimage.put("privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("secretUid", result.secretUid()); + preimage.put("expectedPriorResourceVersion", result.expectedPriorResourceVersion()); + preimage.put("observedResourceVersion", result.observedResourceVersion()); + preimage.put("targetGeneration", result.targetGeneration()); + preimage.put("targetKid", result.targetKid()); + preimage.put("targetAlgorithm", result.targetAlgorithm()); + preimage.put("publicKeyFingerprint", result.publicKeyFingerprint()); + preimage.put("publicJwk", result.publicJwkJson()); + return digest(preimage); + } + + private static String digest(Object value) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException ex) { + throw new IllegalStateException("Account JWT signer evidence digest is unavailable", ex); + } + } + + private static String sha256(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable for JWT promotion evidence", ex); + } + } + + private static Object activeDigestValue(Optional active) { + if (active.isEmpty()) { + return Map.of("present", false); + } + ActiveSigner value = active.orElseThrow(); + return Map.of("present", true, "generation", value.generation(), "kid", value.kid()); + } + + private static PublicJwk parsePublicJwk(String json) { + if (json == null || json.isEmpty() || json.getBytes(StandardCharsets.UTF_8).length > 8_192) { + throw new IllegalArgumentException("JWT signer public JWK is missing or too large"); + } + try { + JsonNode node = STRICT_JSON.readTree(json); + if (node == null || !node.isObject() || node.size() != PUBLIC_JWK_FIELDS.size()) { + throw new IllegalArgumentException("JWT signer public JWK has an unsupported shape"); + } + for (Map.Entry property : node.properties()) { + if (!PUBLIC_JWK_FIELDS.contains(property.getKey())) { + throw new IllegalArgumentException("JWT signer public JWK has an unsupported field"); + } + } + String canonicalJson = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + if (!canonicalJson.equals(json)) { + throw new IllegalArgumentException("JWT signer public JWK must be canonical RFC 8785 JSON"); + } + String kty = requiredText(node, "kty", 8); + String use = requiredText(node, "use", 8); + String algorithm = requiredText(node, "alg", 8); + String kid = requiredText(node, "kid", 64); + String modulus = requiredText(node, "n", 4_096); + String exponent = requiredText(node, "e", 16); + JsonNode keyOps = node.get("key_ops"); + if (!"RSA".equals(kty) + || !"sig".equals(use) + || !ALGORITHM.equals(algorithm) + || !KID.matcher(kid).matches() + || keyOps == null + || !keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())) { + throw new IllegalArgumentException("JWT signer public JWK does not meet RS256 policy"); + } + byte[] modulusBytes = decodeCanonicalBase64Url(modulus, 2_048); + byte[] exponentBytes = decodeCanonicalBase64Url(exponent, 8); + try { + if (modulusBytes.length == 0 + || modulusBytes[0] == 0 + || exponentBytes.length == 0 + || exponentBytes[0] == 0) { + throw new IllegalArgumentException("JWT signer RSA public numbers are malformed"); + } + BigInteger modulusInteger = new BigInteger(1, modulusBytes); + BigInteger exponentInteger = new BigInteger(1, exponentBytes); + if (modulusInteger.bitLength() < 3_072 + || modulusInteger.bitLength() > 16_384 + || !modulusInteger.testBit(0) + || !BigInteger.valueOf(65_537).equals(exponentInteger)) { + throw new IllegalArgumentException("JWT signer RSA public key is outside policy"); + } + } finally { + java.util.Arrays.fill(modulusBytes, (byte) 0); + java.util.Arrays.fill(exponentBytes, (byte) 0); + } + String fingerprint = + digest( + Map.of( + "e", exponent, + "kty", "RSA", + "n", modulus)); + return new PublicJwk(kid, canonicalJson, fingerprint); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalArgumentException("JWT signer public JWK is malformed", ex); + } + } + + private static byte[] decodeCanonicalBase64Url(String encoded, int maxBytes) { + final byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(encoded); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("JWT signer RSA public number is malformed", ex); + } + byte[] canonical = Base64.getUrlEncoder().withoutPadding().encode(decoded); + boolean matches = canonical.length == encoded.length(); + for (int index = 0; matches && index < canonical.length; index++) { + matches = (char) Byte.toUnsignedInt(canonical[index]) == encoded.charAt(index); + } + java.util.Arrays.fill(canonical, (byte) 0); + if (decoded.length == 0 || decoded.length > maxBytes || !matches) { + java.util.Arrays.fill(decoded, (byte) 0); + throw new IllegalArgumentException("JWT signer RSA public number is not canonical"); + } + return decoded; + } + + private static ActiveSigner active(Long generation, String kid, String field) { + if (generation == null && kid == null) { + return null; + } + if (generation == null || kid == null) { + throw new QuarantinedStateException(field + " has an incomplete generation/kid pair"); + } + return new ActiveSigner(Long.toString(positive(generation, field + " generation")), kid); + } + + private static Optional activeOptional(Long generation, String kid, String field) { + return Optional.ofNullable(active(generation, kid, field)); + } + + private static Long generationValue(Optional active) { + return active.map(value -> parseGeneration(value.generation())).orElse(null); + } + + private static String kidValue(Optional active) { + return active.map(ActiveSigner::kid).orElse(null); + } + + private static String canonicalGeneration(Long value, String field) { + return Long.toString(positive(value, field)); + } + + private static long positive(Long value, String field) { + if (value == null || value <= 0) { + throw new QuarantinedStateException(field + " must be positive"); + } + return value; + } + + private static long parseGeneration(String value) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException("Signer generation must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException("Signer generation is outside its supported range", ex); + } + } + + private static void requireOperationId(UUID operationId) { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + if (operationId.version() != 4) { + throw new IllegalArgumentException("Account JWT signer operation ID must be UUIDv4"); + } + } + + private static void requireUuid(String value, String field) { + if (value == null) { + throw new IllegalArgumentException("JWT signer " + field + " is missing"); + } + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } catch (RuntimeException ex) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed", ex); + } + } + + private static void requireMatch(Pattern pattern, String value, String field) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Account transaction is required for JWT signer state"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Writable Account transaction is required for JWT signer state"); + } + } + + public enum CustodyMode { + INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK(MODE); + + private final String value; + + CustodyMode(String value) { + this.value = value; + } + + public String value() { + return value; + } + + private static CustodyMode fromValue(String value) { + for (CustodyMode candidate : values()) { + if (candidate.value.equals(value)) { + return candidate; + } + } + throw new QuarantinedStateException("JWT signer custody mode is unsupported"); + } + } + + public enum GenerationPhase { + OBSERVE_PRIVATE_SECRET, + GENERATE_PENDING, + GENERATION_RECORDED + } + + public record Binding( + String environmentId, String clusterId, String namespace, CustodyMode mode) { + public Binding { + requireMatch(ENVIRONMENT_ID, environmentId, "environment ID"); + requireMatch(CLUSTER_ID, clusterId, "cluster ID"); + requireMatch(ENVIRONMENT_ID, namespace, "Kubernetes namespace"); + Objects.requireNonNull(mode, "JWT signer custody mode is required"); + } + } + + /** Independently protected trust identity captured by every immutable operation and receipt. */ + public record TrustFence( + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String bindingDigest, + String configRevision) { + public TrustFence { + requireUuid(expectedClusterIncarnationUid, "expected cluster incarnation UID"); + requireUuid(expectedNamespaceUid, "expected namespace UID"); + requireMatch(SHA256_HEX, bindingDigest, "materializer trust binding digest"); + requireMatch(CLUSTER_ID, configRevision, "materializer trust configuration revision"); + } + } + + /** + * Immutable independently protected trust and first ConfigMap observation used for enrollment. + */ + public record EnrollmentIdentity( + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String materializerTrustBindingDigest, + String materializerTrustConfigRevision, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String publicConfigMapResourceVersion, + String publicConfigMapSnapshotDigest) { + public EnrollmentIdentity { + requireUuid(expectedClusterIncarnationUid, "enrollment cluster incarnation UID"); + requireUuid(expectedNamespaceUid, "enrollment namespace UID"); + requireMatch(SHA256_HEX, materializerTrustBindingDigest, "materializer trust digest"); + requireMatch(CLUSTER_ID, materializerTrustConfigRevision, "materializer trust revision"); + requireMatch(SHA256_HEX, apiBindingDigest, "public JWKS API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "public JWKS API configuration revision"); + requireUuid(publicConfigMapUid, "pre-created public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, publicConfigMapResourceVersion, "initial ConfigMap resourceVersion"); + requireMatch(SHA256_HEX, publicConfigMapSnapshotDigest, "initial ConfigMap snapshot digest"); + } + + /** Stable pin equality deliberately excludes the historical first ConfigMap RV/data digest. */ + public boolean sameStablePins(EnrollmentIdentity other) { + Objects.requireNonNull(other, "Enrollment identity is required"); + return expectedClusterIncarnationUid.equals(other.expectedClusterIncarnationUid) + && expectedNamespaceUid.equals(other.expectedNamespaceUid) + && materializerTrustBindingDigest.equals(other.materializerTrustBindingDigest) + && materializerTrustConfigRevision.equals(other.materializerTrustConfigRevision) + && apiBindingDigest.equals(other.apiBindingDigest) + && apiConfigRevision.equals(other.apiConfigRevision) + && publicConfigMapUid.equals(other.publicConfigMapUid); + } + } + + public record ActiveSigner(String generation, String kid) { + public ActiveSigner { + parseGeneration(generation); + requireMatch(KID, kid, "active signer kid"); + } + } + + public record DesiredState( + Binding binding, + long recordVersion, + Optional durableActive, + Optional publishedActive, + Optional generationOperationId, + Optional preparedOperationId, + Optional enrollmentIdentity) { + public DesiredState { + Objects.requireNonNull(binding, "JWT signer binding is required"); + if (recordVersion <= 0) { + throw new IllegalArgumentException("JWT signer record version must be positive"); + } + durableActive = Objects.requireNonNull(durableActive, "Durable active signer is required"); + publishedActive = + Objects.requireNonNull(publishedActive, "Published active signer is required"); + generationOperationId = + Objects.requireNonNull(generationOperationId, "Generation operation state is required"); + preparedOperationId = + Objects.requireNonNull(preparedOperationId, "Prepared operation state is required"); + enrollmentIdentity = + Objects.requireNonNull(enrollmentIdentity, "Enrollment identity state is required"); + if (generationOperationId.isPresent() && preparedOperationId.isPresent()) { + throw new IllegalArgumentException("Generation and PREPARED pointers cannot coexist"); + } + } + } + + public record GenerationRequest( + GenerationPhase phase, + UUID operationId, + String operationDigest, + String generationRequestDigest, + long desiredStateVersion, + Binding binding, + TrustFence trustFence, + String privateSecretName, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String operationAction, + List allowedPrivateSlots, + Optional expectedActive, + Optional expectedPublishedActive, + String secretUid, + String expectedSecretResourceVersion, + String generationReceiptDigest, + String publicKeyFingerprint, + String publicJwkJson, + String observedSecretResourceVersion) { + public GenerationRequest { + Objects.requireNonNull(phase, "Generation phase is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + if (phase != GenerationPhase.OBSERVE_PRIVATE_SECRET) { + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } else if (generationRequestDigest != null && !generationRequestDigest.isEmpty()) { + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } + if (desiredStateVersion <= 1) { + throw new QuarantinedStateException("JWT generation request state version is invalid"); + } + Objects.requireNonNull(binding, "Generation request binding is required"); + Objects.requireNonNull(trustFence, "Generation request trust fence is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName) + || !ALGORITHM.equals(targetAlgorithm) + || !ACTION.equals(operationAction) + || !List.of(PENDING_SLOT).equals(allowedPrivateSlots)) { + throw new QuarantinedStateException("JWT generation request fixed operation is malformed"); + } + allowedPrivateSlots = List.copyOf(allowedPrivateSlots); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + expectedActive = Objects.requireNonNull(expectedActive, "Expected active signer is required"); + expectedPublishedActive = + Objects.requireNonNull(expectedPublishedActive, "Expected published signer is required"); + secretUid = secretUid == null ? "" : secretUid; + expectedSecretResourceVersion = + expectedSecretResourceVersion == null ? "" : expectedSecretResourceVersion; + generationReceiptDigest = generationReceiptDigest == null ? "" : generationReceiptDigest; + publicKeyFingerprint = publicKeyFingerprint == null ? "" : publicKeyFingerprint; + publicJwkJson = publicJwkJson == null ? "" : publicJwkJson; + observedSecretResourceVersion = + observedSecretResourceVersion == null ? "" : observedSecretResourceVersion; + if (phase != GenerationPhase.OBSERVE_PRIVATE_SECRET) { + requireUuid(secretUid, "observed fixed Secret UID"); + requireMatch( + RESOURCE_VERSION, expectedSecretResourceVersion, "observed Secret resourceVersion"); + } + if (phase == GenerationPhase.GENERATION_RECORDED) { + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + requireMatch(SHA256_HEX, publicKeyFingerprint, "RFC 7638 public-key fingerprint"); + parsePublicJwk(publicJwkJson); + requireMatch( + RESOURCE_VERSION, observedSecretResourceVersion, "result Secret resourceVersion"); + } else if (!generationReceiptDigest.isEmpty() + || !publicKeyFingerprint.isEmpty() + || !publicJwkJson.isEmpty() + || !observedSecretResourceVersion.isEmpty()) { + throw new QuarantinedStateException( + "Incomplete JWT generation request contains result evidence"); + } + } + } + + public record GenerationResult( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + long desiredStateVersion, + TrustFence trustFence, + String privateSecretName, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String publicKeyFingerprint, + String publicJwkJson, + String receiptDigest) { + public GenerationResult { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Generation result binding is required"); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + if (desiredStateVersion <= 1) { + throw new QuarantinedStateException("JWT generation result state version is invalid"); + } + Objects.requireNonNull(trustFence, "Generation result trust fence is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName)) { + throw new IllegalArgumentException("JWT generation result must name the fixed Secret"); + } + requireUuid(secretUid, "generation result Secret UID"); + requireMatch( + RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret resourceVersion"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + if (expectedPriorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException("JWT signer Secret resourceVersion did not advance"); + } + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new IllegalArgumentException("Only RS256 JWT signer results are supported"); + } + requireMatch(SHA256_HEX, publicKeyFingerprint, "RFC 7638 public-key fingerprint"); + requireMatch(SHA256_HEX, receiptDigest, "generation receipt digest"); + PublicJwk jwk = parsePublicJwk(publicJwkJson); + if (!jwk.kid().equals(targetKid) || !jwk.fingerprint().equals(publicKeyFingerprint)) { + throw new QuarantinedStateException( + "JWT generation result public key does not match receipt"); + } + } + + private static GenerationResult from( + StoredGenerationOperation operation, + long desiredStateVersion, + SecretObservation observation, + String observedResourceVersion, + PublicJwk jwk) { + GenerationResult candidate = + new GenerationResult( + operation.operationId(), + operation.binding(), + operation.operationDigest(), + observation.generationRequestDigest(), + desiredStateVersion, + operation.trustFence(), + PRIVATE_SECRET_NAME, + observation.secretUid(), + observation.observedResourceVersion(), + observedResourceVersion, + operation.targetGeneration(), + operation.targetKid(), + operation.targetAlgorithm(), + jwk.fingerprint(), + jwk.canonicalJson(), + "0".repeat(64)); + return new GenerationResult( + candidate.operationId(), + candidate.binding(), + candidate.operationDigest(), + candidate.generationRequestDigest(), + candidate.desiredStateVersion(), + candidate.trustFence(), + candidate.privateSecretName(), + candidate.secretUid(), + candidate.expectedPriorResourceVersion(), + candidate.observedResourceVersion(), + candidate.targetGeneration(), + candidate.targetKid(), + candidate.targetAlgorithm(), + candidate.publicKeyFingerprint(), + candidate.publicJwkJson(), + generationReceiptDigest(candidate)); + } + } + + private record StoredGenerationOperation( + UUID operationId, + Binding binding, + String digestVersion, + String operationDigest, + long expectedRecordVersion, + Optional expectedPreviousActive, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + TrustFence trustFence) { + private StoredGenerationOperation { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Generation operation binding is required"); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + if (expectedRecordVersion <= 0 || expectedRecordVersion == Long.MAX_VALUE) { + throw new IllegalArgumentException("Generation operation state version is invalid"); + } + expectedPreviousActive = + Objects.requireNonNull(expectedPreviousActive, "Expected active signer is required"); + expectedPublishedActive = + Objects.requireNonNull(expectedPublishedActive, "Expected published signer is required"); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new IllegalArgumentException("Only RS256 generation operations are supported"); + } + Objects.requireNonNull(trustFence, "Generation operation trust is required"); + } + + private static StoredGenerationOperation create( + DesiredState state, + TrustFence trust, + UUID operationId, + long targetGeneration, + String targetKid) { + StoredGenerationOperation unsigned = + new StoredGenerationOperation( + operationId, + state.binding(), + REQUEST_DIGEST_VERSION, + "0".repeat(64), + state.recordVersion(), + state.durableActive(), + state.publishedActive(), + Long.toString(targetGeneration), + targetKid, + ALGORITHM, + trust); + return new StoredGenerationOperation( + unsigned.operationId(), + unsigned.binding(), + unsigned.digestVersion(), + generationOperationDigest(unsigned), + unsigned.expectedRecordVersion(), + unsigned.expectedPreviousActive(), + unsigned.expectedPublishedActive(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.targetAlgorithm(), + unsigned.trustFence()); + } + } + + private record SecretObservation( + UUID operationId, + Binding binding, + String operationDigest, + long expectedRecordVersion, + TrustFence trustFence, + String privateSecretName, + String secretUid, + String observedResourceVersion, + String observationDigest, + String generationRequestDigest) { + private SecretObservation { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Secret observation binding is required"); + if (expectedRecordVersion <= 0 || expectedRecordVersion == Long.MAX_VALUE) { + throw new IllegalArgumentException("Secret observation state version is invalid"); + } + requireMatch(SHA256_HEX, operationDigest, "operation digest"); + Objects.requireNonNull(trustFence, "Secret observation trust is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName)) { + throw new IllegalArgumentException("Secret observation must name the fixed Secret"); + } + requireUuid(secretUid, "observed Secret UID"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + requireMatch(SHA256_HEX, observationDigest, "Secret observation digest"); + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } + + private static SecretObservation from( + StoredGenerationOperation operation, String secretUid, String resourceVersion) { + String observationDigest = + AccountJwtSignerDesiredStateRepository.observationDigest( + operation.operationDigest(), operation.trustFence(), secretUid, resourceVersion); + String generationRequestDigest = + AccountJwtSignerDesiredStateRepository.generationRequestDigest( + operation.operationDigest(), observationDigest, secretUid, resourceVersion); + return new SecretObservation( + operation.operationId(), + operation.binding(), + operation.operationDigest(), + operation.expectedRecordVersion(), + operation.trustFence(), + PRIVATE_SECRET_NAME, + secretUid, + resourceVersion, + observationDigest, + generationRequestDigest); + } + } + + private record PublicJwk(String kid, String canonicalJson, String fingerprint) {} + + private record LockedCurrent(DesiredState state, StoredGenerationOperation operation) {} + + private record StoredPromotion( + UUID operationId, + Binding binding, + int requestDigestVersion, + String requestDigest, + long expectedRecordVersion, + Optional expectedPreviousActive, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String targetPublicKeyFingerprint, + String expectedPrivateResourceVersion, + String expectedPublicResourceVersion, + TrustFence trustFence, + UUID generationOperationId, + String generationOperationDigest, + String generationReceiptDigest, + String apiBindingDigest, + String apiConfigRevision, + String secretUid, + String publicConfigMapUid, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String expectedPublicJwksJson, + String expectedActiveMarkerJson, + String status, + boolean privatePromotionDispatched, + String privatePromotionObservedResourceVersion, + String privatePromotionReceiptDigest, + String activeJwksObservedResourceVersion, + String activeJwksPublicDataDigest, + String activeJwksReceiptDigest) { + private StoredPromotion { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Promotion binding is required"); + if (requestDigestVersion != 1 + || expectedRecordVersion <= 0L + || expectedRecordVersion == Long.MAX_VALUE) { + throw new QuarantinedStateException("Promotion version fence is malformed"); + } + requireMatch(SHA256_HEX, requestDigest, "promotion request digest"); + expectedPreviousActive = Objects.requireNonNull(expectedPreviousActive); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "promotion target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new QuarantinedStateException("Promotion target algorithm is unsupported"); + } + requireMatch(SHA256_HEX, targetPublicKeyFingerprint, "promotion target fingerprint"); + requireMatch( + RESOURCE_VERSION, expectedPrivateResourceVersion, "expected private Secret version"); + requireMatch( + RESOURCE_VERSION, expectedPublicResourceVersion, "expected public ConfigMap version"); + Objects.requireNonNull(trustFence, "Promotion trust fence is required"); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + requireMatch(SHA256_HEX, apiBindingDigest, "public API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "public API config revision"); + requireUuid(secretUid, "promotion Secret UID"); + requireUuid(publicConfigMapUid, "promotion ConfigMap UID"); + requireMatch(SHA256_HEX, prepublicationIntentDigest, "prepublication intent digest"); + requireMatch(SHA256_HEX, prepublicationReceiptDigest, "prepublication receipt digest"); + requireMatch(SHA256_HEX, mountedObservationDigest, "mounted observation digest"); + requireMatch(SHA256_HEX, readinessPlanDigest, "readiness plan digest"); + requireMatch(SHA256_HEX, readinessEvidenceDigest, "readiness evidence digest"); + if (expectedPublicJwksJson == null + || expectedPublicJwksJson.isBlank() + || expectedPublicJwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024 + || expectedActiveMarkerJson == null + || expectedActiveMarkerJson.isBlank() + || expectedActiveMarkerJson.getBytes(StandardCharsets.UTF_8).length > 16 * 1024) { + throw new QuarantinedStateException("Promotion public payload is missing or oversized"); + } + if (!Set.of("PREPARED", "COMMITTED", "ABORTED").contains(status)) { + throw new QuarantinedStateException("Promotion status is malformed"); + } + boolean noActiveJwksReceipt = + activeJwksObservedResourceVersion == null + && activeJwksPublicDataDigest == null + && activeJwksReceiptDigest == null; + boolean completeActiveJwksReceipt = + activeJwksObservedResourceVersion != null + && activeJwksPublicDataDigest != null + && activeJwksReceiptDigest != null; + if ((privatePromotionObservedResourceVersion == null) + != (privatePromotionReceiptDigest == null) + || !(noActiveJwksReceipt || completeActiveJwksReceipt)) { + throw new QuarantinedStateException("Promotion resource receipts are partial"); + } + if ((privatePromotionReceiptDigest != null && !privatePromotionDispatched) + || ("COMMITTED".equals(status) && !privatePromotionDispatched) + || ("ABORTED".equals(status) && privatePromotionDispatched)) { + throw new QuarantinedStateException( + "Promotion dispatch state is inconsistent with its receipts or terminal status"); + } + if (privatePromotionObservedResourceVersion != null) { + requireMatch( + RESOURCE_VERSION, + privatePromotionObservedResourceVersion, + "private promotion readback version"); + requireMatch(SHA256_HEX, privatePromotionReceiptDigest, "private promotion receipt digest"); + } + if (activeJwksObservedResourceVersion != null) { + requireMatch( + RESOURCE_VERSION, activeJwksObservedResourceVersion, "active JWKS readback version"); + requireMatch(SHA256_HEX, activeJwksPublicDataDigest, "active JWKS public data digest"); + requireMatch(SHA256_HEX, activeJwksReceiptDigest, "active JWKS receipt digest"); + } + } + + private static StoredPromotion create( + PromotionPreparation preparation, + DesiredState state, + StoredGenerationOperation generation, + GenerationResult result, + TrustFence trust, + Binding binding) { + if (!preparation.generationOperationId().equals(generation.operationId()) + || !preparation.generationResult().equals(result) + || !preparation + .enrollmentIdentity() + .sameStablePins(state.enrollmentIdentity().orElseThrow()) + || !generation.binding().equals(binding) + || !result.binding().equals(binding) + || !generation.trustFence().equals(trust) + || !result.trustFence().equals(trust) + || !state.generationOperationId().equals(Optional.of(generation.operationId())) + || state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Promotion preparation is not bound to the current Account generation and enrollment"); + } + UUID promotionId = UUID.randomUUID(); + StoredPromotion unsigned = + new StoredPromotion( + promotionId, + binding, + 1, + "0".repeat(64), + state.recordVersion(), + state.durableActive(), + state.publishedActive(), + result.targetGeneration(), + result.targetKid(), + result.targetAlgorithm(), + result.publicKeyFingerprint(), + result.observedResourceVersion(), + preparation.expectedPublicResourceVersion(), + trust, + generation.operationId(), + generation.operationDigest(), + result.receiptDigest(), + preparation.apiBindingDigest(), + preparation.apiConfigRevision(), + result.secretUid(), + preparation.publicConfigMapUid(), + preparation.prepublicationIntentDigest(), + preparation.prepublicationReceiptDigest(), + preparation.mountedObservationDigest(), + preparation.readinessPlanDigest(), + preparation.readinessEvidenceDigest(), + preparation.expectedPublicJwksJson(), + "{}", + "PREPARED", + false, + null, + null, + null, + null, + null); + StoredPromotion signed = + new StoredPromotion( + unsigned.operationId(), + unsigned.binding(), + unsigned.requestDigestVersion(), + promotionRequestDigest(unsigned), + unsigned.expectedRecordVersion(), + unsigned.expectedPreviousActive(), + unsigned.expectedPublishedActive(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.targetAlgorithm(), + unsigned.targetPublicKeyFingerprint(), + unsigned.expectedPrivateResourceVersion(), + unsigned.expectedPublicResourceVersion(), + unsigned.trustFence(), + unsigned.generationOperationId(), + unsigned.generationOperationDigest(), + unsigned.generationReceiptDigest(), + unsigned.apiBindingDigest(), + unsigned.apiConfigRevision(), + unsigned.secretUid(), + unsigned.publicConfigMapUid(), + unsigned.prepublicationIntentDigest(), + unsigned.prepublicationReceiptDigest(), + unsigned.mountedObservationDigest(), + unsigned.readinessPlanDigest(), + unsigned.readinessEvidenceDigest(), + unsigned.expectedPublicJwksJson(), + "{}", + unsigned.status(), + unsigned.privatePromotionDispatched(), + null, + null, + null, + null, + null); + return new StoredPromotion( + signed.operationId(), + signed.binding(), + signed.requestDigestVersion(), + signed.requestDigest(), + signed.expectedRecordVersion(), + signed.expectedPreviousActive(), + signed.expectedPublishedActive(), + signed.targetGeneration(), + signed.targetKid(), + signed.targetAlgorithm(), + signed.targetPublicKeyFingerprint(), + signed.expectedPrivateResourceVersion(), + signed.expectedPublicResourceVersion(), + signed.trustFence(), + signed.generationOperationId(), + signed.generationOperationDigest(), + signed.generationReceiptDigest(), + signed.apiBindingDigest(), + signed.apiConfigRevision(), + signed.secretUid(), + signed.publicConfigMapUid(), + signed.prepublicationIntentDigest(), + signed.prepublicationReceiptDigest(), + signed.mountedObservationDigest(), + signed.readinessPlanDigest(), + signed.readinessEvidenceDigest(), + signed.expectedPublicJwksJson(), + activeMarkerJson(signed), + signed.status(), + signed.privatePromotionDispatched(), + null, + null, + null, + null, + null); + } + + private String operationDigestForGeneration() { + return generationOperationDigest; + } + + private boolean matchesPreparation( + PromotionPreparation preparation, + StoredGenerationOperation generation, + GenerationResult result, + EnrollmentIdentity enrollment) { + return generation.operationId().equals(preparation.generationOperationId()) + && result.equals(preparation.generationResult()) + && preparation.enrollmentIdentity().sameStablePins(enrollment) + && apiBindingDigest.equals(preparation.apiBindingDigest()) + && apiConfigRevision.equals(preparation.apiConfigRevision()) + && publicConfigMapUid.equals(preparation.publicConfigMapUid()) + && expectedPublicResourceVersion.equals(preparation.expectedPublicResourceVersion()) + && prepublicationIntentDigest.equals(preparation.prepublicationIntentDigest()) + && prepublicationReceiptDigest.equals(preparation.prepublicationReceiptDigest()) + && mountedObservationDigest.equals(preparation.mountedObservationDigest()) + && readinessPlanDigest.equals(preparation.readinessPlanDigest()) + && readinessEvidenceDigest.equals(preparation.readinessEvidenceDigest()) + && expectedPublicJwksJson.equals(preparation.expectedPublicJwksJson()) + && generationOperationId.equals(generation.operationId()) + && generationOperationDigest.equals(generation.operationDigest()) + && generationReceiptDigest.equals(result.receiptDigest()) + && secretUid.equals(result.secretUid()) + && expectedPrivateResourceVersion.equals(result.observedResourceVersion()) + && targetGeneration.equals(result.targetGeneration()) + && targetKid.equals(result.targetKid()) + && targetPublicKeyFingerprint.equals(result.publicKeyFingerprint()); + } + + private PromotionOperationEvidence publicEvidence() { + return new PromotionOperationEvidence( + operationId, + requestDigest, + expectedRecordVersion, + binding, + expectedPreviousActive, + expectedPreviousActive.map( + active -> publicFingerprintForKid(expectedPublicJwksJson, active.kid())), + expectedPublishedActive, + targetGeneration, + targetKid, + targetAlgorithm, + targetPublicKeyFingerprint, + trustFence, + generationOperationId, + generationOperationDigest, + generationReceiptDigest, + secretUid, + expectedPrivateResourceVersion, + apiBindingDigest, + apiConfigRevision, + publicConfigMapUid, + expectedPublicResourceVersion, + prepublicationIntentDigest, + prepublicationReceiptDigest, + mountedObservationDigest, + readinessPlanDigest, + readinessEvidenceDigest, + expectedPublicJwksJson, + expectedActiveMarkerJson, + status, + privatePromotionDispatched, + Optional.ofNullable(privatePromotionObservedResourceVersion), + Optional.ofNullable(privatePromotionReceiptDigest), + Optional.ofNullable(activeJwksObservedResourceVersion), + Optional.ofNullable(activeJwksPublicDataDigest), + Optional.ofNullable(activeJwksReceiptDigest)); + } + } + + public record PreparedGenerationEvidence( + DesiredState desiredState, + PromotionOperationEvidence promotion, + GenerationResult generationResult) { + public PreparedGenerationEvidence { + Objects.requireNonNull(desiredState); + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + if (!"PREPARED".equals(promotion.status()) + || !promotion.generationOperationId().equals(generationResult.operationId())) { + throw new QuarantinedStateException("Prepared generation evidence is inconsistent"); + } + } + } + + /** Exact current owner-readback values required to freeze one PREPARED operation. */ + public record PromotionPreparation( + UUID generationOperationId, + GenerationResult generationResult, + EnrollmentIdentity enrollmentIdentity, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String expectedPublicResourceVersion, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String expectedPublicJwksJson) { + public PromotionPreparation { + requireOperationId(generationOperationId); + Objects.requireNonNull(generationResult, "Persisted generation result is required"); + Objects.requireNonNull(enrollmentIdentity, "Pinned Account enrollment is required"); + requireMatch(SHA256_HEX, apiBindingDigest, "promotion API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "promotion API config revision"); + requireUuid(publicConfigMapUid, "promotion public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, expectedPublicResourceVersion, "promotion ConfigMap resourceVersion"); + requireMatch(SHA256_HEX, prepublicationIntentDigest, "prepublication intent digest"); + requireMatch(SHA256_HEX, prepublicationReceiptDigest, "prepublication receipt digest"); + requireMatch(SHA256_HEX, mountedObservationDigest, "mounted observation digest"); + requireMatch(SHA256_HEX, readinessPlanDigest, "readiness plan digest"); + requireMatch(SHA256_HEX, readinessEvidenceDigest, "readiness evidence digest"); + if (expectedPublicJwksJson == null + || expectedPublicJwksJson.isBlank() + || expectedPublicJwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024) { + throw new PromotionPrerequisitesIncompleteException( + "Account promotion public projection is missing or oversized"); + } + } + } + + public record ActiveJwksPromotionObservation( + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String jwksJson, + String activeMarkerJson) { + public ActiveJwksPromotionObservation { + requireUuid(configMapUid, "active public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, priorResourceVersion, "active ConfigMap prior resourceVersion"); + requireMatch( + RESOURCE_VERSION, observedResourceVersion, "active ConfigMap readback resourceVersion"); + if (priorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap resourceVersion did not advance"); + } + if (jwksJson == null + || jwksJson.isBlank() + || jwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024 + || activeMarkerJson == null + || activeMarkerJson.isBlank() + || activeMarkerJson.getBytes(StandardCharsets.UTF_8).length > 16 * 1024) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap projection is missing or oversized"); + } + } + } + + public record ActiveJwksPromotionReceipt( + UUID promotionOperationId, + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String publicDataDigest, + String receiptDigest) { + public ActiveJwksPromotionReceipt { + requireOperationId(promotionOperationId); + requireUuid(configMapUid, "active public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, priorResourceVersion, "active ConfigMap prior resourceVersion"); + requireMatch( + RESOURCE_VERSION, observedResourceVersion, "active ConfigMap readback resourceVersion"); + requireMatch(SHA256_HEX, publicDataDigest, "active public ConfigMap data digest"); + requireMatch(SHA256_HEX, receiptDigest, "active public ConfigMap receipt digest"); + if (priorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap resourceVersion did not advance"); + } + } + + private static ActiveJwksPromotionReceipt from( + StoredPromotion promotion, ActiveJwksPromotionObservation observation) { + String dataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + observation.jwksJson(), observation.activeMarkerJson()); + return create( + promotion, + observation.configMapUid(), + observation.priorResourceVersion(), + observation.observedResourceVersion(), + dataDigest); + } + + private static ActiveJwksPromotionReceipt fromStored(StoredPromotion promotion) { + if (promotion.activeJwksObservedResourceVersion() == null + || promotion.activeJwksPublicDataDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException("Committed signer has no active JWKS receipt"); + } + ActiveJwksPromotionReceipt calculated = + create( + promotion, + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + promotion.activeJwksObservedResourceVersion(), + promotion.activeJwksPublicDataDigest()); + if (!calculated.receiptDigest().equals(promotion.activeJwksReceiptDigest())) { + throw new QuarantinedStateException("Committed active JWKS receipt digest is invalid"); + } + return calculated; + } + + private static ActiveJwksPromotionReceipt create( + StoredPromotion promotion, + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String dataDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("receiptVersion", "account-jwt-active-jwks-promotion-receipt/v1"); + preimage.put("promotionOperationId", promotion.operationId().toString()); + preimage.put("promotionRequestDigest", promotion.requestDigest()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("configMapName", PUBLIC_JWKS_CONFIG_MAP_NAME); + preimage.put("configMapUid", configMapUid); + preimage.put("priorResourceVersion", priorResourceVersion); + preimage.put("observedResourceVersion", observedResourceVersion); + preimage.put("action", "MARK_ACTIVE"); + preimage.put("publicDataDigest", dataDigest); + return new ActiveJwksPromotionReceipt( + promotion.operationId(), + configMapUid, + priorResourceVersion, + observedResourceVersion, + dataDigest, + digest(preimage)); + } + } + + /** Durable non-authorizing result for Account's current committed active signer. */ + public record CommittedSignerEvidence( + PromotionOperationEvidence promotion, + GenerationResult generationResult, + DesiredState desiredState, + PrivatePromotionReceipt privateReceipt, + ActiveJwksPromotionReceipt publicReceipt) { + public CommittedSignerEvidence { + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + Objects.requireNonNull(desiredState); + Objects.requireNonNull(privateReceipt); + Objects.requireNonNull(publicReceipt); + ActiveSigner target = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.operationId().equals(privateReceipt.promotionOperationId()) + || !promotion.operationId().equals(publicReceipt.promotionOperationId()) + || !promotion.generationOperationId().equals(generationResult.operationId()) + || desiredState.durableActive().filter(target::equals).isEmpty() + || desiredState.publishedActive().filter(target::equals).isEmpty() + || desiredState.preparedOperationId().isPresent()) { + throw new QuarantinedStateException("Committed signer evidence is inconsistent"); + } + } + } + + public record AbortedPromotion( + UUID operationId, + long desiredStateVersion, + Optional durableActive, + Optional publishedActive) { + public AbortedPromotion { + requireOperationId(operationId); + if (desiredStateVersion <= 0) + throw new IllegalArgumentException("Aborted state version is invalid"); + durableActive = Objects.requireNonNull(durableActive); + publishedActive = Objects.requireNonNull(publishedActive); + if (!durableActive.equals(publishedActive)) { + throw new QuarantinedStateException("Aborted signer operation changed active fences"); + } + } + } + + /** Public-only immutable promotion row needed by the materializer and Account reconciler. */ + public record PromotionOperationEvidence( + UUID operationId, + String requestDigest, + long expectedRecordVersion, + Binding binding, + Optional expectedPreviousActive, + Optional expectedPreviousPublicKeyFingerprint, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String targetPublicKeyFingerprint, + TrustFence trustFence, + UUID generationOperationId, + String generationOperationDigest, + String generationReceiptDigest, + String secretUid, + String expectedPrivateResourceVersion, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String expectedPublicResourceVersion, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String expectedPublicJwksJson, + String expectedActiveMarkerJson, + String status, + boolean privatePromotionDispatched, + Optional privatePromotionObservedResourceVersion, + Optional privatePromotionReceiptDigest, + Optional activeJwksObservedResourceVersion, + Optional activeJwksPublicDataDigest, + Optional activeJwksReceiptDigest) { + public PromotionOperationEvidence { + Objects.requireNonNull(operationId); + requireMatch(SHA256_HEX, requestDigest, "promotion request digest"); + Objects.requireNonNull(binding); + expectedPreviousActive = Objects.requireNonNull(expectedPreviousActive); + expectedPreviousPublicKeyFingerprint = + Objects.requireNonNull(expectedPreviousPublicKeyFingerprint); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + if (expectedPreviousActive.isPresent() != expectedPreviousPublicKeyFingerprint.isPresent()) { + throw new QuarantinedStateException("Promotion prior public identity is incomplete"); + } + expectedPreviousPublicKeyFingerprint.ifPresent( + value -> requireMatch(SHA256_HEX, value, "prior public-key fingerprint")); + Objects.requireNonNull(trustFence); + Objects.requireNonNull(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + privatePromotionObservedResourceVersion = + Objects.requireNonNull(privatePromotionObservedResourceVersion); + privatePromotionReceiptDigest = Objects.requireNonNull(privatePromotionReceiptDigest); + activeJwksObservedResourceVersion = Objects.requireNonNull(activeJwksObservedResourceVersion); + activeJwksPublicDataDigest = Objects.requireNonNull(activeJwksPublicDataDigest); + activeJwksReceiptDigest = Objects.requireNonNull(activeJwksReceiptDigest); + } + } + + public record PublicKeyIdentity(String generation, String kid, String publicKeyFingerprint) { + public PublicKeyIdentity { + parseGeneration(generation); + requireMatch(KID, kid, "observed public key kid"); + requireMatch(SHA256_HEX, publicKeyFingerprint, "observed public key fingerprint"); + } + } + + public record PrivatePromotionObservation( + UUID promotionOperationId, + String promotionRequestDigest, + UUID generationOperationId, + String generationOperationDigest, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + PublicKeyIdentity current, + Optional previous, + List resultingSlots) { + public PrivatePromotionObservation { + requireOperationId(promotionOperationId); + requireMatch(SHA256_HEX, promotionRequestDigest, "promotion request digest"); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireUuid(secretUid, "observed fixed Secret UID"); + requireMatch(RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret version"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret version"); + Objects.requireNonNull(current); + previous = Objects.requireNonNull(previous); + resultingSlots = List.copyOf(resultingSlots); + if (expectedPriorResourceVersion.equals(observedResourceVersion) + || !(resultingSlots.equals(List.of("current")) + || resultingSlots.equals(List.of("current", "previous")))) { + throw new QuarantinedStateException("Private promotion readback identity is malformed"); + } + } + } + + public record PrivatePromotionReceipt( + UUID promotionOperationId, + UUID generationOperationId, + String observedResourceVersion, + String receiptDigest) { + public PrivatePromotionReceipt { + requireOperationId(promotionOperationId); + requireOperationId(generationOperationId); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "private promotion readback version"); + requireMatch(SHA256_HEX, receiptDigest, "private promotion receipt digest"); + } + + private static PrivatePromotionReceipt from( + StoredPromotion promotion, PrivatePromotionObservation observation) { + Map preimage = new LinkedHashMap<>(); + preimage.put("receiptVersion", 1); + preimage.put("promotionOperationId", promotion.operationId().toString()); + preimage.put("promotionRequestDigest", promotion.requestDigest()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("secretResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("secretUid", observation.secretUid()); + preimage.put("expectedPriorResourceVersion", observation.expectedPriorResourceVersion()); + preimage.put("observedResourceVersion", observation.observedResourceVersion()); + preimage.put("action", "PROMOTE_PENDING"); + preimage.put("resultingSlots", observation.resultingSlots()); + preimage.put("current", publicKeyIdentityMap(observation.current())); + preimage.put( + "previous", + observation + .previous() + .map(AccountJwtSignerDesiredStateRepository::publicKeyIdentityMap) + .orElseGet(() -> Map.of("present", false))); + return new PrivatePromotionReceipt( + promotion.operationId(), + promotion.generationOperationId(), + observation.observedResourceVersion(), + digest(preimage)); + } + + private static PrivatePromotionReceipt fromStored(StoredPromotion promotion) { + if (promotion.privatePromotionObservedResourceVersion() == null + || promotion.privatePromotionReceiptDigest() == null) { + throw new QuarantinedStateException("Committed signer has no private promotion receipt"); + } + Optional previous = + promotion + .expectedPreviousActive() + .map( + active -> + new PublicKeyIdentity( + active.generation(), + active.kid(), + publicFingerprintForKid( + promotion.expectedPublicJwksJson(), active.kid()))); + PrivatePromotionReceipt calculated = + from( + promotion, + new PrivatePromotionObservation( + promotion.operationId(), + promotion.requestDigest(), + promotion.generationOperationId(), + promotion.generationOperationDigest(), + promotion.secretUid(), + promotion.expectedPrivateResourceVersion(), + promotion.privatePromotionObservedResourceVersion(), + new PublicKeyIdentity( + promotion.targetGeneration(), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint()), + previous, + previous.isPresent() ? List.of("current", "previous") : List.of("current"))); + if (!calculated.receiptDigest().equals(promotion.privatePromotionReceiptDigest())) { + throw new QuarantinedStateException( + "Committed private promotion receipt digest is invalid"); + } + return calculated; + } + } + + private static Map publicKeyIdentityMap(PublicKeyIdentity identity) { + return Map.of( + "generation", identity.generation(), + "kid", identity.kid(), + "publicKeyFingerprint", identity.publicKeyFingerprint()); + } + + public record PreparedPromotion(UUID operationId, String requestDigest, String status) { + public PreparedPromotion { + requireOperationId(operationId); + requireMatch(SHA256_HEX, requestDigest, "prepared promotion digest"); + if (!"PREPARED".equals(status)) { + throw new IllegalArgumentException("Only PREPARED JWT signer operations are represented"); + } + } + } + + private static String generationRequestDigest( + String operationDigest, String observationDigest, String secretUid, String resourceVersion) { + return digest( + Map.of( + "digestVersion", GENERATION_REQUEST_DIGEST_VERSION, + "operationDigest", operationDigest, + "observationDigest", observationDigest, + "secretUid", secretUid, + "expectedPriorResourceVersion", resourceVersion, + "target", "pending")); + } + + public static class MissingDesiredStateException extends IllegalStateException { + public MissingDesiredStateException(String environmentId) { + super("Account JWT signer desired state is missing for environment " + environmentId); + } + } + + public static class MissingGenerationOperationException extends IllegalStateException { + public MissingGenerationOperationException(String message) { + super(message); + } + } + + public static class MissingGenerationObservationException extends IllegalStateException { + public MissingGenerationObservationException(String message) { + super(message); + } + } + + public static class StaleGenerationOperationException extends IllegalStateException { + public StaleGenerationOperationException(String message) { + super(message); + } + } + + public static class BindingMismatchException extends IllegalStateException { + public BindingMismatchException(String message) { + super(message); + } + } + + public static class VersionConflictException extends IllegalStateException { + public VersionConflictException(String message) { + super(message); + } + } + + public static class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static class QuarantinedStateException extends IllegalStateException { + public QuarantinedStateException(String message) { + super(message); + } + + public QuarantinedStateException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class PromotionPrerequisitesIncompleteException extends IllegalStateException { + public PromotionPrerequisitesIncompleteException(String message) { + super(message); + } + } + + public static class NoPreparedPromotionException extends IllegalStateException { + public NoPreparedPromotionException() { + super("Account has no PREPARED JWT signer promotion"); + } + } + + public static class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java new file mode 100644 index 0000000000..e8b11ec12c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java @@ -0,0 +1,279 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Immutable persistence for an Account-observed, non-authorizing validator inventory snapshot. The + * table stores only the source's closed canonical public/runtime observation, never API response + * objects or credentials. + */ +@Repository +public class AccountJwtValidatorInventoryRepository { + public static final int MAX_SNAPSHOT_BYTES = 4 * 1024 * 1024; + private static final String TABLE = "account_jwt_validator_inventory_snapshots"; + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates its trusted injected DSLContext; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtValidatorInventoryRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** Inserts once or proves that a same-digest retry reads back the exact immutable bytes. */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSnapshot persistOrReadback( + InventorySnapshot snapshot, Binding binding, TrustFence trustFence) { + requireWritableAccountTransaction(); + Objects.requireNonNull(snapshot, "Owner-observed inventory snapshot is required"); + requireBinding(snapshot, binding, trustFence); + byte[] canonicalBytes = snapshot.canonicalBytes(); + requireSnapshotBytes(canonicalBytes, snapshot.digest()); + dsl.execute( + "INSERT INTO " + + TABLE + + " (snapshot_digest, environment_id, cluster_id, cluster_incarnation_uid, " + + "kubernetes_namespace, namespace_uid, api_binding_revision, api_binding_digest, " + + "inventory_binding_revision, inventory_binding_digest, observed_at, canonical_snapshot) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (snapshot_digest) DO NOTHING", + snapshot.digest(), + snapshot.environmentId(), + snapshot.clusterId(), + UUID.fromString(snapshot.clusterIncarnationUid()), + snapshot.namespace(), + UUID.fromString(snapshot.namespaceUid()), + snapshot.apiBindingRevision(), + snapshot.apiBindingDigest(), + snapshot.inventoryBindingRevision(), + snapshot.inventoryBindingDigest(), + snapshot.observedAt().toString(), + canonicalBytes); + Record row = + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE snapshot_digest = ? FOR UPDATE", snapshot.digest()); + StoredSnapshot stored = decode(row); + requireSameSnapshot(snapshot, stored); + requireBinding(stored, binding, trustFence); + return stored; + } + + /** Reads the exact previously persisted snapshot and rechecks its Account binding. */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSnapshot readRequired(String digest, Binding binding, TrustFence trustFence) { + requireAccountTransaction(); + if (digest == null || !DIGEST.matcher(digest).matches()) { + throw new InventorySnapshotUnavailableException(); + } + Record row = + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE snapshot_digest = ? FOR KEY SHARE", digest); + StoredSnapshot stored = decode(row); + requireBinding(stored, binding, trustFence); + return stored; + } + + private static StoredSnapshot decode(Record row) { + if (row == null) { + throw new InventorySnapshotUnavailableException(); + } + try { + String digest = row.get("snapshot_digest", String.class); + byte[] bytes = row.get("canonical_snapshot", byte[].class); + requireSnapshotBytes(bytes, digest); + StoredSnapshot stored = + new StoredSnapshot( + digest, + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("cluster_incarnation_uid", UUID.class).toString(), + row.get("kubernetes_namespace", String.class), + row.get("namespace_uid", UUID.class).toString(), + row.get("api_binding_revision", String.class), + row.get("api_binding_digest", String.class), + row.get("inventory_binding_revision", String.class), + row.get("inventory_binding_digest", String.class), + Instant.parse(row.get("observed_at", String.class)), + bytes); + return stored; + } catch (InventorySnapshotUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireSnapshotBytes(byte[] bytes, String digest) { + if (bytes == null + || bytes.length < 2 + || bytes.length > MAX_SNAPSHOT_BYTES + || digest == null + || !DIGEST.matcher(digest).matches() + || !digest(bytes).equals(digest)) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static String digest(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireSameSnapshot(InventorySnapshot expected, StoredSnapshot actual) { + if (!expected.digest().equals(actual.digest()) + || !expected.environmentId().equals(actual.environmentId()) + || !expected.clusterId().equals(actual.clusterId()) + || !expected.clusterIncarnationUid().equals(actual.clusterIncarnationUid()) + || !expected.namespace().equals(actual.namespace()) + || !expected.namespaceUid().equals(actual.namespaceUid()) + || !expected.apiBindingRevision().equals(actual.apiBindingRevision()) + || !expected.apiBindingDigest().equals(actual.apiBindingDigest()) + || !expected.inventoryBindingRevision().equals(actual.inventoryBindingRevision()) + || !expected.inventoryBindingDigest().equals(actual.inventoryBindingDigest()) + || !expected.observedAt().equals(actual.observedAt()) + || !MessageDigest.isEqual(expected.canonicalBytes(), actual.canonicalBytes())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireBinding( + InventorySnapshot snapshot, Binding binding, TrustFence trustFence) { + Objects.requireNonNull(binding, "Account generation binding is required"); + Objects.requireNonNull(trustFence, "Account trust fence is required"); + if (!binding.environmentId().equals(snapshot.environmentId()) + || !binding.clusterId().equals(snapshot.clusterId()) + || !binding.namespace().equals(snapshot.namespace()) + || !trustFence.expectedClusterIncarnationUid().equals(snapshot.clusterIncarnationUid()) + || !trustFence.expectedNamespaceUid().equals(snapshot.namespaceUid())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireBinding( + StoredSnapshot snapshot, Binding binding, TrustFence trustFence) { + Objects.requireNonNull(binding, "Account generation binding is required"); + Objects.requireNonNull(trustFence, "Account trust fence is required"); + if (!binding.environmentId().equals(snapshot.environmentId()) + || !binding.clusterId().equals(snapshot.clusterId()) + || !binding.namespace().equals(snapshot.namespace()) + || !trustFence.expectedClusterIncarnationUid().equals(snapshot.clusterIncarnationUid()) + || !trustFence.expectedNamespaceUid().equals(snapshot.namespaceUid())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("An owning Account transaction is required"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("A writable Account transaction is required"); + } + } + + public record StoredSnapshot( + String digest, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + Instant observedAt, + byte[] canonicalBytes) { + public StoredSnapshot { + Objects.requireNonNull(digest); + Objects.requireNonNull(environmentId); + Objects.requireNonNull(clusterId); + Objects.requireNonNull(clusterIncarnationUid); + Objects.requireNonNull(namespace); + Objects.requireNonNull(namespaceUid); + Objects.requireNonNull(apiBindingRevision); + Objects.requireNonNull(apiBindingDigest); + Objects.requireNonNull(inventoryBindingRevision); + Objects.requireNonNull(inventoryBindingDigest); + Objects.requireNonNull(observedAt); + canonicalBytes = canonicalBytes.clone(); + requireSnapshotBytes(canonicalBytes, digest); + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof StoredSnapshot that)) { + return false; + } + return digest.equals(that.digest) + && environmentId.equals(that.environmentId) + && clusterId.equals(that.clusterId) + && clusterIncarnationUid.equals(that.clusterIncarnationUid) + && namespace.equals(that.namespace) + && namespaceUid.equals(that.namespaceUid) + && apiBindingRevision.equals(that.apiBindingRevision) + && apiBindingDigest.equals(that.apiBindingDigest) + && inventoryBindingRevision.equals(that.inventoryBindingRevision) + && inventoryBindingDigest.equals(that.inventoryBindingDigest) + && observedAt.equals(that.observedAt) + && Arrays.equals(canonicalBytes, that.canonicalBytes); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + digest, + environmentId, + clusterId, + clusterIncarnationUid, + namespace, + namespaceUid, + apiBindingRevision, + apiBindingDigest, + inventoryBindingRevision, + inventoryBindingDigest, + observedAt) + + Arrays.hashCode(canonicalBytes); + } + } + + public static final class InventorySnapshotUnavailableException extends RuntimeException { + public InventorySnapshotUnavailableException() { + super("Account validator inventory snapshot is unavailable or inconsistent"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java new file mode 100644 index 0000000000..8d2443d595 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLifecyclePendingDenialReader.java @@ -0,0 +1,155 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Reads exact target-tenant lifecycle operations and Account-wide pending source operations as a + * fail-closed admission denial predicate. It proves no producer identity, World result, source + * finalization, current serving state, or admission permission. + */ +@Repository +public class AccountLifecyclePendingDenialReader { + private static final String ACCOUNT_LOCK_SQL = + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE"; + private static final String PENDING_SQL = + "SELECT EXISTS (SELECT 1 FROM account_lifecycle_serving_operations " + + "WHERE account_uuid = ? AND tenant_uuid = ? " + + "AND status IN ('PENDING', 'WORLD_TERMINAL')) " + + "OR EXISTS (SELECT 1 FROM account_security_state_operations " + + "WHERE account_uuid = ? AND status = 'WAITING') " + + "OR EXISTS (SELECT 1 FROM account_draft_authorization_source_changes c " + + "JOIN account_draft_authorization_changed_scopes s ON s.change_id = c.change_id " + + "WHERE c.status = 'WAITING' AND s.source_key IN (?, ?))"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Keep the required DSL precondition fail-fast; this non-final Spring repository is proxied and no partially initialized instance escapes.") + public AccountLifecyclePendingDenialReader(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Requires no unresolved exact target-tenant lifecycle operation or Account-wide pending source + * operation. + * + *

The existing writable owner transaction must be READ_COMMITTED, REPEATABLE_READ, or + * SERIALIZABLE. At READ_COMMITTED, the exact Account row lock makes this query observe a + * lifecycle insert committed before the lock is acquired; the lifecycle journal's and + * Account-wide pending-intent tables' row-version fences prevent an insert from crossing a later + * lock holder. When Spring uses the datasource's default isolation, the actual PostgreSQL + * transaction isolation is checked. A pending lifecycle intent, a correlated World terminal + * receipt, an Account security-state operation in WAITING, or an Account/GLOBAL_ROLES source + * change in WAITING remains denial evidence. Tenant membership and tenant source scopes are not + * promoted to Account-wide scope. + */ + public void requireNoPending(UUID accountUuid, UUID tenantUuid) { + requireWritableOwnerTransaction(dsl); + requireUuid(accountUuid, "Account UUID"); + requireUuid(tenantUuid, "tenant UUID"); + + try { + Record account = dsl.fetchOne(ACCOUNT_LOCK_SQL, accountUuid); + if (account == null || !accountUuid.equals(account.get(0, UUID.class))) { + throw new PendingStateUnavailableException( + "Account lifecycle pending state could not be read"); + } + Record pendingRecord = + dsl.fetchOne( + PENDING_SQL, + accountUuid, + tenantUuid, + accountUuid, + "ACCOUNT:" + accountUuid, + "GLOBAL_ROLES:" + accountUuid); + Boolean pending = pendingRecord == null ? null : pendingRecord.get(0, Boolean.class); + if (pending == null) { + throw new PendingStateUnavailableException( + "Account lifecycle pending state could not be read"); + } + if (pending) { + throw new PendingOperationException( + "Account-wide or target-tenant invalidation is unresolved"); + } + } catch (PendingOperationException | PendingStateUnavailableException denied) { + throw denied; + } catch (DataAccessException unavailable) { + throw new PendingStateUnavailableException( + "Account lifecycle pending state could not be read", unavailable); + } + } + + private static void requireWritableOwnerTransaction(DSLContext dsl) { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account lifecycle pending read requires an owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account lifecycle pending read requires a writable transaction"); + } + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (isolation == null) { + final String databaseIsolation; + try { + Record isolationRecord = dsl.fetchOne("SHOW transaction_isolation"); + databaseIsolation = isolationRecord == null ? null : isolationRecord.get(0, String.class); + } catch (DataAccessException unavailable) { + throw new IllegalStateException( + "Account lifecycle pending read could not determine transaction isolation", + unavailable); + } + if ("read committed".equals(databaseIsolation)) { + isolation = TransactionDefinition.ISOLATION_READ_COMMITTED; + } else if ("repeatable read".equals(databaseIsolation)) { + isolation = TransactionDefinition.ISOLATION_REPEATABLE_READ; + } else if ("serializable".equals(databaseIsolation)) { + isolation = TransactionDefinition.ISOLATION_SERIALIZABLE; + } + } + if (isolation == null + || (isolation != TransactionDefinition.ISOLATION_READ_COMMITTED + && isolation != TransactionDefinition.ISOLATION_REPEATABLE_READ + && isolation != TransactionDefinition.ISOLATION_SERIALIZABLE)) { + throw new IllegalStateException( + "Account lifecycle pending read requires READ_COMMITTED, REPEATABLE_READ, or SERIALIZABLE isolation"); + } + } + + private static void requireUuid(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + public static final class PendingOperationException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public PendingOperationException(String message) { + super(message); + } + } + + public static final class PendingStateUnavailableException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public PendingStateUnavailableException(String message) { + super(message); + } + + public PendingStateUnavailableException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java new file mode 100644 index 0000000000..0ce98e77e2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountLogoutAllOperationRepository.java @@ -0,0 +1,321 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Stores immutable source and lifecycle-result evidence for one Account logout-all operation. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountLogoutAllOperationRepository { + private static final String TABLE = "account_logout_all_operation_receipts"; + private static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + private static final String LIFECYCLE_RESULT = "LOGOUT_ALL_COMMITTED"; + private static final String SELECT_COLUMNS = + "request_id, account_id, account_uuid, operation_kind, request_digest_version, " + + "request_digest, presented_token_hash, token_profile, outbox_stream_key, outbox_sequence, " + + "event_id, event_digest, account_authority_generation, account_source_version, " + + "issuance_fence, issuance_fence_source_version, lifecycle_result"; + private static final HexFormat HEX = HexFormat.of(); + + private final DSLContext dsl; + + public AccountLogoutAllOperationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Exact request lookup; callers compare every immutable request binding before recovery. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByRequestId(UUID requestId) { + requireOwnerTransaction(); + requireRequestId(requestId); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE request_id = ?", requestId); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** + * Token identity lookup prevents an old presented token from being rebound to another request. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByPresentedTokenHash(String tokenHash) { + requireOwnerTransaction(); + byte[] hash = decodeDigest(tokenHash, "presented token hash"); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE presented_token_hash = ?", + hash); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** Inserts the one immutable lifecycle receipt for the source event. */ + @Transactional(propagation = Propagation.MANDATORY) + public LogoutAllReceipt insert(LogoutAllReceipt receipt) { + requireOwnerTransaction(); + validateReceipt(receipt); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, account_id, account_uuid, operation_kind, " + + "request_digest_version, request_digest, presented_token_hash, token_profile, " + + "outbox_stream_key, outbox_sequence, event_id, event_digest, " + + "account_authority_generation, account_source_version, issuance_fence, " + + "issuance_fence_source_version, lifecycle_result) " + + "VALUES (?, ?, ?, 'ACCOUNT_LOGOUT_ALL', 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'LOGOUT_ALL_COMMITTED')", + receipt.requestId(), + receipt.accountId(), + receipt.accountUuid(), + decodeDigest(receipt.requestDigest(), "request digest"), + decodeDigest(receipt.presentedTokenHash(), "presented token hash"), + receipt.tokenProfile(), + receipt.outboxStreamKey(), + receipt.outboxSequence(), + receipt.eventId(), + receipt.eventDigest(), + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion()); + if (inserted != 1) { + throw new IllegalStateException("Logout-all operation receipt was not inserted"); + } + return receipt; + } + + private LogoutAllReceipt toReceipt(Record row) { + return new LogoutAllReceipt( + requiredUuid(row.get("request_id", UUID.class), "request ID"), + requiredPositive(row.get("account_id", Long.class), "Account association"), + requiredUuid(row.get("account_uuid", UUID.class), "Account UUID"), + requireText(row.get("operation_kind", String.class), "operation kind"), + requiredPositive(row.get("request_digest_version", Integer.class), "digest version"), + encodeDigest(row.get("request_digest", byte[].class), "request digest"), + encodeDigest(row.get("presented_token_hash", byte[].class), "presented token hash"), + requireText(row.get("token_profile", String.class), "token profile"), + requireText(row.get("outbox_stream_key", String.class), "outbox stream key"), + requiredPositive(row.get("outbox_sequence", Long.class), "outbox sequence"), + requireText(row.get("event_id", String.class), "event ID"), + requireText(row.get("event_digest", String.class), "event digest"), + requiredPositive( + row.get("account_authority_generation", Long.class), "Account authority generation"), + requiredPositive(row.get("account_source_version", Long.class), "Account source version"), + requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"), + requiredPositive( + row.get("issuance_fence_source_version", Long.class), "issuance-fence source version"), + requireText(row.get("lifecycle_result", String.class), "lifecycle result")); + } + + private static void validateReceipt(LogoutAllReceipt receipt) { + Objects.requireNonNull(receipt, "logout-all receipt is required"); + requireRequestId(receipt.requestId()); + decodeDigest(receipt.requestDigest(), "request digest"); + decodeDigest(receipt.presentedTokenHash(), "presented token hash"); + AccountLogoutRequestDigest.validateTokenProfile(receipt.tokenProfile()); + if (receipt.accountId() <= 0L + || receipt.accountUuid() == null + || isNil(receipt.accountUuid()) + || receipt.requestDigestVersion() != 1 + || !AccountLogoutRequestDigest.accountLogoutAll( + receipt.accountUuid(), receipt.tokenProfile(), receipt.presentedTokenHash()) + .equals(receipt.requestDigest()) + || receipt.outboxSequence() <= 0L + || receipt.accountAuthorityGeneration() <= 0L + || receipt.accountSourceVersion() <= 0L + || receipt.issuanceFence() <= 0L + || receipt.issuanceFenceSourceVersion() <= 0L + || !accountStreamKey(receipt.accountUuid()).equals(receipt.outboxStreamKey()) + || !expectedEventId(receipt.requestId()).equals(receipt.eventId()) + || receipt.eventDigest() == null + || !receipt.eventDigest().matches("sha256:[0-9a-f]{64}") + || !LIFECYCLE_RESULT.equals(receipt.lifecycleResult())) { + throw new IllegalArgumentException("Logout-all operation receipt is malformed"); + } + requireBoundedText(receipt.operationKind(), "operation kind", 32); + if (!"ACCOUNT_LOGOUT_ALL".equals(receipt.operationKind())) { + throw new IllegalArgumentException("Logout-all operation kind is invalid"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Logout-all operation storage requires an active Account transaction"); + } + } + + private static UUID requiredUuid(UUID value, String field) { + if (value == null || isNil(value)) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static long requiredPositive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static int requiredPositive(Integer value, String field) { + if (value == null || value <= 0) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static String requireText(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return value; + } + + private static void requireBoundedText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + "Logout-all receipt " + field + " must contain 1 to " + maximumLength + " characters"); + } + } + + private static void requireRequestId(UUID requestId) { + if (requestId == null || isNil(requestId)) { + throw new IllegalArgumentException("A canonical non-nil logout-all request UUID is required"); + } + } + + private static byte[] decodeDigest(String value, String field) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Logout-all receipt " + field + " is malformed"); + } + return HEX.parseHex(value); + } + + private static String encodeDigest(byte[] value, String field) { + if (value == null || value.length != 32) { + throw new IllegalStateException("Logout-all receipt " + field + " is missing or invalid"); + } + return HEX.formatHex(value); + } + + private static String accountStreamKey(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + private static String expectedEventId(UUID requestId) { + return EVENT_ID_PREFIX + requestId; + } + + private static boolean isNil(UUID value) { + return new UUID(0L, 0L).equals(value); + } + + /** Immutable committed request binding, source checkpoint and lifecycle-only result. */ + public record LogoutAllReceipt( + UUID requestId, + long accountId, + UUID accountUuid, + String operationKind, + int requestDigestVersion, + String requestDigest, + String presentedTokenHash, + String tokenProfile, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + long accountAuthorityGeneration, + long accountSourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + String lifecycleResult) { + public LogoutAllReceipt { + requireRequestId(requestId); + decodeDigest(requestDigest, "request digest"); + decodeDigest(presentedTokenHash, "presented token hash"); + AccountLogoutRequestDigest.validateTokenProfile(tokenProfile); + if (accountId <= 0L + || accountUuid == null + || isNil(accountUuid) + || requestDigestVersion != 1 + || !AccountLogoutRequestDigest.accountLogoutAll( + accountUuid, tokenProfile, presentedTokenHash) + .equals(requestDigest) + || outboxSequence <= 0L + || accountAuthorityGeneration <= 0L + || accountSourceVersion <= 0L + || issuanceFence <= 0L + || issuanceFenceSourceVersion <= 0L + || !accountStreamKey(accountUuid).equals(outboxStreamKey) + || !expectedEventId(requestId).equals(eventId) + || eventDigest == null + || !eventDigest.matches("sha256:[0-9a-f]{64}") + || !LIFECYCLE_RESULT.equals(lifecycleResult)) { + throw new IllegalArgumentException("Logout-all operation receipt is malformed"); + } + requireBoundedText(operationKind, "operation kind", 32); + if (!"ACCOUNT_LOGOUT_ALL".equals(operationKind)) { + throw new IllegalArgumentException("Logout-all operation kind is invalid"); + } + } + + public static LogoutAllReceipt committed( + UUID requestId, + long accountId, + UUID accountUuid, + String requestDigest, + String presentedTokenHash, + String tokenProfile, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + ScopeState accountAuthority, + IssuanceFence issuanceFence) { + if (accountAuthority == null + || issuanceFence == null + || accountAuthority.issuanceFence() == null + || !issuanceFence.equals(accountAuthority.issuanceFence())) { + throw new IllegalArgumentException( + "Committed logout-all authority and issuance fence must match exactly"); + } + return new LogoutAllReceipt( + requestId, + accountId, + accountUuid, + "ACCOUNT_LOGOUT_ALL", + 1, + requestDigest, + presentedTokenHash, + tokenProfile, + outboxStreamKey, + outboxSequence, + eventId, + eventDigest, + accountAuthority.generation(), + accountAuthority.sourceVersion(), + issuanceFence.value(), + issuanceFence.sourceVersion(), + LIFECYCLE_RESULT); + } + + public IssuanceFence issuanceFenceEvidence() { + return new IssuanceFence(accountUuid, issuanceFence, issuanceFenceSourceVersion); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java new file mode 100644 index 0000000000..700668e747 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java @@ -0,0 +1,316 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Stores immutable proof for one Account-owned password-reset source commit. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class AccountPasswordResetOperationRepository { + private static final String TABLE = "account_password_reset_operation_receipts"; + private static final String REQUEST_ID_PREFIX = "account-password-reset-request-v1:"; + private static final String EVENT_ID_PREFIX = "account-password-reset-event-v1:"; + private static final String SELECT_COLUMNS = + "token_hash, account_id, account_uuid, operation_kind, request_id, " + + "request_digest_version, request_digest, token_expires_at, " + + "password_verifier_digest, outbox_stream_key, outbox_sequence, event_id, " + + "event_digest, account_authority_generation, account_source_version, " + + "issuance_fence, issuance_fence_source_version"; + private static final HexFormat HEX = HexFormat.of(); + + private final DSLContext dsl; + + public AccountPasswordResetOperationRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Read-only lookup by the SHA-256 identity of the token, including after token consumption. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByTokenHash(String tokenHash) { + requireOwnerTransaction(); + byte[] tokenHashBytes = decodeDigest(tokenHash, "token hash"); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE token_hash = ?", + tokenHashBytes); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** Read-only source-history lookup used to prove a progressed Account stream. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByRequestId(String requestId) { + requireOwnerTransaction(); + requireBoundedText(requestId, "request ID", 128); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE request_id = ?", requestId); + return Optional.ofNullable(row == null ? null : toReceipt(row)); + } + + /** Inserts the one immutable receipt for this token hash. */ + @Transactional(propagation = Propagation.MANDATORY) + public PasswordResetReceipt insert(PasswordResetReceipt receipt) { + requireOwnerTransaction(); + validateReceipt(receipt); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (token_hash, account_id, account_uuid, operation_kind, request_id, " + + "request_digest_version, request_digest, token_expires_at, " + + "password_verifier_digest, outbox_stream_key, outbox_sequence, event_id, " + + "event_digest, account_authority_generation, account_source_version, " + + "issuance_fence, issuance_fence_source_version) " + + "VALUES (?, ?, ?, 'PASSWORD_RESET', ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + decodeDigest(receipt.tokenHash(), "token hash"), + receipt.accountId(), + receipt.accountUuid(), + receipt.requestId(), + decodeDigest(receipt.requestDigest(), "request digest"), + receipt.tokenExpiresAt(), + decodeDigest(receipt.passwordVerifierDigest(), "password verifier digest"), + receipt.outboxStreamKey(), + receipt.outboxSequence(), + receipt.eventId(), + receipt.eventDigest(), + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion()); + if (inserted != 1) { + throw new IllegalStateException("Password-reset operation receipt was not inserted"); + } + return receipt; + } + + private PasswordResetReceipt toReceipt(Record row) { + return new PasswordResetReceipt( + requiredPositive(row.get("account_id", Long.class), "Account association"), + Objects.requireNonNull(row.get("account_uuid", UUID.class), "receipt Account UUID"), + encodeDigest(row.get("token_hash", byte[].class), "token hash"), + requireText(row.get("operation_kind", String.class), "operation kind"), + requireText(row.get("request_id", String.class), "request ID"), + requiredPositive(row.get("request_digest_version", Integer.class), "digest version"), + encodeDigest(row.get("request_digest", byte[].class), "request digest"), + Objects.requireNonNull( + row.get("token_expires_at", java.time.LocalDateTime.class), "token deadline"), + encodeDigest(row.get("password_verifier_digest", byte[].class), "password verifier digest"), + requireText(row.get("outbox_stream_key", String.class), "outbox stream key"), + requiredPositive(row.get("outbox_sequence", Long.class), "outbox sequence"), + requireText(row.get("event_id", String.class), "event ID"), + requireText(row.get("event_digest", String.class), "event digest"), + requiredPositive( + row.get("account_authority_generation", Long.class), "Account authority generation"), + requiredPositive(row.get("account_source_version", Long.class), "Account source version"), + requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"), + requiredPositive( + row.get("issuance_fence_source_version", Long.class), "issuance-fence source version")); + } + + private static void validateReceipt(PasswordResetReceipt receipt) { + Objects.requireNonNull(receipt, "password-reset receipt is required"); + decodeDigest(receipt.tokenHash(), "token hash"); + decodeDigest(receipt.requestDigest(), "request digest"); + decodeDigest(receipt.passwordVerifierDigest(), "password verifier digest"); + if (receipt.accountId() <= 0L + || receipt.accountUuid() == null + || new UUID(0L, 0L).equals(receipt.accountUuid()) + || receipt.requestDigestVersion() != 1 + || receipt.tokenExpiresAt() == null + || receipt.outboxSequence() <= 0L + || receipt.accountAuthorityGeneration() <= 0L + || receipt.accountSourceVersion() <= 0L + || receipt.issuanceFence() <= 0L + || receipt.issuanceFenceSourceVersion() <= 0L + || !accountStreamKey(receipt.accountUuid()).equals(receipt.outboxStreamKey()) + || receipt.eventDigest() == null + || !receipt.eventDigest().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Password-reset operation receipt is malformed"); + } + requireBoundedText(receipt.operationKind(), "operation kind", 32); + if (!"PASSWORD_RESET".equals(receipt.operationKind())) { + throw new IllegalArgumentException("Password-reset operation kind is invalid"); + } + requireBoundedText(receipt.requestId(), "request ID", 128); + requireBoundedText(receipt.eventId(), "event ID", 128); + if (!(REQUEST_ID_PREFIX + receipt.tokenHash()).equals(receipt.requestId()) + || !(EVENT_ID_PREFIX + receipt.tokenHash()).equals(receipt.eventId())) { + throw new IllegalArgumentException( + "Password-reset operation IDs must be derived from the token hash"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Password-reset operation storage requires an active Account transaction"); + } + } + + private static long requiredPositive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return value; + } + + private static int requiredPositive(Integer value, String field) { + if (value == null || value <= 0) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return value; + } + + private static String requireText(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return value; + } + + private static void requireBoundedText(String value, String field, int maximumLength) { + if (value == null || value.isBlank() || value.length() > maximumLength) { + throw new IllegalArgumentException( + "Password-reset receipt " + + field + + " must contain 1 to " + + maximumLength + + " characters"); + } + } + + private static byte[] decodeDigest(String value, String field) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Password-reset receipt " + field + " is malformed"); + } + return HEX.parseHex(value); + } + + private static String encodeDigest(byte[] value, String field) { + if (value == null || value.length != 32) { + throw new IllegalStateException("Password-reset receipt " + field + " is missing or invalid"); + } + return HEX.formatHex(value); + } + + private static String accountStreamKey(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + /** Immutable commit and retry evidence; digest values are lowercase SHA-256 hex strings. */ + public record PasswordResetReceipt( + long accountId, + UUID accountUuid, + String tokenHash, + String operationKind, + String requestId, + int requestDigestVersion, + String requestDigest, + java.time.LocalDateTime tokenExpiresAt, + String passwordVerifierDigest, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + long accountAuthorityGeneration, + long accountSourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion) { + public PasswordResetReceipt { + decodeDigest(tokenHash, "token hash"); + decodeDigest(requestDigest, "request digest"); + decodeDigest(passwordVerifierDigest, "password verifier digest"); + if (accountId <= 0L + || accountUuid == null + || new UUID(0L, 0L).equals(accountUuid) + || requestDigestVersion != 1 + || tokenExpiresAt == null + || outboxSequence <= 0L + || accountAuthorityGeneration <= 0L + || accountSourceVersion <= 0L + || issuanceFence <= 0L + || issuanceFenceSourceVersion <= 0L + || !accountStreamKey(accountUuid).equals(outboxStreamKey) + || eventDigest == null + || !eventDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Password-reset operation receipt is malformed"); + } + requireBoundedText(operationKind, "operation kind", 32); + if (!"PASSWORD_RESET".equals(operationKind)) { + throw new IllegalArgumentException("Password-reset operation kind is invalid"); + } + requireBoundedText(requestId, "request ID", 128); + requireBoundedText(eventId, "event ID", 128); + if (!(REQUEST_ID_PREFIX + tokenHash).equals(requestId) + || !(EVENT_ID_PREFIX + tokenHash).equals(eventId)) { + throw new IllegalArgumentException( + "Password-reset operation IDs must be derived from the token hash"); + } + } + + public static PasswordResetReceipt committed( + long accountId, + UUID accountUuid, + String tokenHash, + String requestId, + String requestDigest, + java.time.LocalDateTime tokenExpiresAt, + String passwordVerifierDigest, + String outboxStreamKey, + long outboxSequence, + String eventId, + String eventDigest, + ScopeState accountAuthority, + IssuanceFence issuanceFence) { + if (accountAuthority == null + || issuanceFence == null + || accountAuthority.issuanceFence() == null + || !issuanceFence.equals(accountAuthority.issuanceFence())) { + throw new IllegalArgumentException( + "Committed password-reset authority and issuance fence must match exactly"); + } + return new PasswordResetReceipt( + accountId, + accountUuid, + tokenHash, + "PASSWORD_RESET", + requestId, + 1, + requestDigest, + tokenExpiresAt, + passwordVerifierDigest, + outboxStreamKey, + outboxSequence, + eventId, + eventDigest, + accountAuthority.generation(), + accountAuthority.sourceVersion(), + issuanceFence.value(), + issuanceFence.sourceVersion()); + } + + public IssuanceFence issuanceFenceEvidence() { + return new IssuanceFence(accountUuid, issuanceFence, issuanceFenceSourceVersion); + } + } + + /** A token identity was already committed with a different supplied password. */ + public static final class OperationConflictException extends IllegalStateException { + public OperationConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepository.java new file mode 100644 index 0000000000..abb4585c1a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionBirthRepository.java @@ -0,0 +1,325 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.Category; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.CategorySource; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.RestrictionState; +import net.firedevops.firemud.accountservice.dto.AccountPlatformRestrictionBirthSource.SourceKind; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Fresh source prerequisite only. Retained Accounts and later moderation writes are not enrolled. + */ +@Repository +public class AccountPlatformRestrictionBirthRepository { + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = "Preserve required DSLContext; Spring must proxy this repository.") + public AccountPlatformRestrictionBirthRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** Called only after the existing fresh-insert capability and sequence-zero source readback. */ + @Transactional(propagation = Propagation.MANDATORY) + void initializeFreshAccount( + AccountRepository.FreshAccountInsert proof, long insertTransactionId, ScopeState birth) { + requireTransaction(); + Objects.requireNonNull(proof, "Fresh Account insert proof is required"); + Record account = lockAccount(proof.accountUuid()); + if (positive(account, "id") != proof.accountId() + || positive(account, "account_repository_insert_transaction_id") != insertTransactionId + || positive(account, "current_xid") != insertTransactionId + || !"active".equals(account.get("lifecycle_state", String.class))) { + throw new BirthSourceUnavailableException(); + } + ScopeState current = currentAuthority(proof.accountUuid()); + if (!current.equals(birth) + || birth.generation() != 1 + || birth.sourceVersion() != 1 + || birth.issuanceFence() == null + || birth.issuanceFence().value() != 1 + || birth.issuanceFence().sourceVersion() != 1) { + throw new BirthSourceUnavailableException(); + } + CategorySource lock = + insertCategory( + proof.accountUuid(), + proof.accountId(), + insertTransactionId, + birth, + Category.ACCOUNT_SECURITY_LOCK); + CategorySource ban = + insertCategory( + proof.accountUuid(), + proof.accountId(), + insertTransactionId, + birth, + Category.PLATFORM_ACCESS_BAN); + AccountPlatformRestrictionBirthSource expected = + new AccountPlatformRestrictionBirthSource( + proof.accountUuid(), proof.accountId(), insertTransactionId, birth, current, lock, ban); + if (!expected.equals(readCurrentBirthSource(proof.accountUuid()))) { + throw new BirthSourceUnavailableException(); + } + } + + /** + * Locks Account first and requires both explicit CATEGORY projections, exact immutable birth + * results and their distinct restriction outbox evidence. Missing or changed evidence denies. + * NONRESTRICTED is the historical birth result, not proof of current protective-lock absence. + * This source read does not authorize a player or manufacture an auth-authority event. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountPlatformRestrictionBirthSource readCurrentBirthSource(UUID accountId) { + requireTransaction(); + Record account = lockAccount(accountId); + ScopeState current = currentAuthority(accountId); + CategoryReadback lock = readCategory(accountId, Category.ACCOUNT_SECURITY_LOCK, account); + CategoryReadback ban = readCategory(accountId, Category.PLATFORM_ACCESS_BAN, account); + if (!lock.birthAuthority().equals(ban.birthAuthority())) { + throw new BirthSourceUnavailableException(); + } + try { + return new AccountPlatformRestrictionBirthSource( + accountId, + positive(account, "id"), + positive(account, "account_repository_insert_transaction_id"), + lock.birthAuthority(), + current, + lock.source(), + ban.source()); + } catch (IllegalArgumentException malformed) { + throw new BirthSourceUnavailableException(); + } + } + + private CategorySource insertCategory( + UUID accountId, long numericId, long transactionId, ScopeState birth, Category category) { + // No upsert or retry minting: this method is reachable only inside the exact new row's tx. + // Committed readback always returns the original retained identities. + UUID operationId = UUID.randomUUID(); + UUID resultId = UUID.randomUUID(); + UUID eventId = UUID.randomUUID(); + String stream = AccountPlatformRestrictionBirthSource.streamKey(accountId, category); + String digest = + AccountPlatformRestrictionBirthSource.birthDigest( + accountId, numericId, transactionId, birth, category, operationId, resultId, eventId); + int inserted = + dsl.execute( + "INSERT INTO account_platform_restriction_births (account_uuid, category, revision, " + + "enforcement_epoch, source_kind, restriction_state, operation_id, result_id, event_id, payload_digest, " + + "account_source_numeric_id, account_insert_transaction_id, account_generation, " + + "account_source_version, issuance_fence, fence_source_version) " + + "VALUES (?, ?, 1, 1, 'CATEGORY', 'NONRESTRICTED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + accountId, + category.storageValue(), + operationId, + resultId, + eventId, + digest, + numericId, + transactionId, + birth.generation(), + birth.sourceVersion(), + birth.issuanceFence().value(), + birth.issuanceFence().sourceVersion()); + int projected = + dsl.execute( + "INSERT INTO account_platform_restriction_projections " + + "(account_uuid, category, revision, enforcement_epoch, result_id) VALUES (?, ?, 1, 1, ?)", + accountId, + category.storageValue(), + resultId); + int emitted = + dsl.execute( + "INSERT INTO account_platform_restriction_birth_outbox " + + "(account_uuid, category, revision, enforcement_epoch, operation_id, result_id, " + + "event_id, payload_digest, outbox_stream_key, outbox_sequence, source_kind, restriction_state) " + + "VALUES (?, ?, 1, 1, ?, ?, ?, ?, ?, 1, 'CATEGORY', 'NONRESTRICTED')", + accountId, + category.storageValue(), + operationId, + resultId, + eventId, + digest, + stream); + if (inserted != 1 || projected != 1 || emitted != 1) { + throw new BirthSourceUnavailableException(); + } + return new CategorySource( + category, + SourceKind.CATEGORY, + RestrictionState.NONRESTRICTED, + 1, + 1, + operationId, + resultId, + eventId, + digest, + stream, + 1); + } + + private CategoryReadback readCategory(UUID accountId, Category category, Record account) { + Record birth = + dsl.fetchOne( + "SELECT * FROM account_platform_restriction_births " + + "WHERE account_uuid = ? AND category = ? FOR SHARE", + accountId, + category.storageValue()); + Record projection = + dsl.fetchOne( + "SELECT * FROM account_platform_restriction_projections " + + "WHERE account_uuid = ? AND category = ? FOR SHARE", + accountId, + category.storageValue()); + Record event = + dsl.fetchOne( + "SELECT * FROM account_platform_restriction_birth_outbox " + + "WHERE account_uuid = ? AND category = ? FOR SHARE", + accountId, + category.storageValue()); + if (birth == null + || projection == null + || event == null + || positive(birth, "account_source_numeric_id") != positive(account, "id") + || positive(birth, "account_insert_transaction_id") + != positive(account, "account_repository_insert_transaction_id")) { + throw new BirthSourceUnavailableException(); + } + for (String field : + new String[] {"account_uuid", "category", "revision", "enforcement_epoch", "result_id"}) { + if (!Objects.equals(birth.get(field), projection.get(field)) + || !Objects.equals(birth.get(field), event.get(field))) { + throw new BirthSourceUnavailableException(); + } + } + for (String field : + new String[] { + "operation_id", "event_id", "payload_digest", "source_kind", "restriction_state" + }) { + if (!Objects.equals(birth.get(field), event.get(field))) { + throw new BirthSourceUnavailableException(); + } + } + if (!accountId.equals(birth.get("account_uuid", UUID.class)) + || !category.storageValue().equals(birth.get("category", String.class)) + || !"CATEGORY".equals(birth.get("source_kind", String.class)) + || !"NONRESTRICTED".equals(birth.get("restriction_state", String.class)) + || positive(birth, "revision") != 1 + || positive(birth, "enforcement_epoch") != 1 + || positive(event, "outbox_sequence") != 1 + || !AccountPlatformRestrictionBirthSource.streamKey(accountId, category) + .equals(event.get("outbox_stream_key", String.class))) { + throw new BirthSourceUnavailableException(); + } + try { + var fence = + new AccountAuthorityGenerationRepository.IssuanceFence( + accountId, + positive(birth, "issuance_fence"), + positive(birth, "fence_source_version")); + var authority = + new ScopeState( + AuthorityScope.account(accountId), + positive(birth, "account_generation"), + positive(birth, "account_source_version"), + fence); + if (authority.generation() != 1 + || authority.sourceVersion() != 1 + || fence.value() != 1 + || fence.sourceVersion() != 1) { + throw new BirthSourceUnavailableException(); + } + UUID operationId = birth.get("operation_id", UUID.class); + UUID resultId = birth.get("result_id", UUID.class); + UUID eventId = event.get("event_id", UUID.class); + if (operationId == null || resultId == null || eventId == null) { + throw new BirthSourceUnavailableException(); + } + return new CategoryReadback( + authority, + new CategorySource( + category, + SourceKind.CATEGORY, + RestrictionState.NONRESTRICTED, + 1, + 1, + operationId, + resultId, + eventId, + birth.get("payload_digest", String.class), + event.get("outbox_stream_key", String.class), + 1)); + } catch (IllegalArgumentException malformed) { + throw new BirthSourceUnavailableException(); + } + } + + private Record lockAccount(UUID accountId) { + if (accountId == null || accountId.version() != 4 || accountId.variant() != 2) { + throw new BirthSourceUnavailableException(); + } + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id, lifecycle_state, " + + "account_repository_insert_transaction_id, txid_current() AS current_xid " + + "FROM accounts WHERE account_uuid = ? FOR UPDATE", + accountId); + if (account == null + || !accountId.equals(account.get("account_uuid", UUID.class)) + || !AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + .name() + .equals(account.get("account_uuid_provenance", String.class)) + || positive(account, "id") != positive(account, "account_uuid_source_numeric_id")) { + throw new BirthSourceUnavailableException(); + } + positive(account, "account_repository_insert_transaction_id"); + return account; + } + + private ScopeState currentAuthority(UUID accountId) { + ScopeState state = + new AccountAuthorityGenerationRepository(dsl).read(AuthorityScope.account(accountId)); + if (state.issuanceFence() == null || !accountId.equals(state.issuanceFence().accountId())) { + throw new BirthSourceUnavailableException(); + } + return state; + } + + private static long positive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0) throw new BirthSourceUnavailableException(); + return value; + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Restriction birth source requires an Account transaction"); + } + } + + private record CategoryReadback(ScopeState birthAuthority, CategorySource source) {} + + public static final class BirthSourceUnavailableException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public BirthSourceUnavailableException() { + super("Exact Account restriction birth source is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java index 532b660843..b60da32522 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java @@ -52,6 +52,16 @@ public Optional findById(Long id) { dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).fetchOne(this::toEntity)); } + /** Locks one exact persisted Account row before an owner-local authority mutation. */ + @Transactional + public Optional findByIdForUpdate(Long id) { + if (id == null || id <= 0L) { + throw new IllegalArgumentException("A positive persisted Account ID is required"); + } + return Optional.ofNullable( + dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).forUpdate().fetchOne(this::toEntity)); + } + public Optional findByAccountUuid(UUID accountUuid) { Objects.requireNonNull(accountUuid, "accountUuid must not be null"); return Optional.ofNullable( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java new file mode 100644 index 0000000000..25076a2630 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSecurityStateOperationRepository.java @@ -0,0 +1,693 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateMutationRequest; +import net.firedevops.firemud.accountservice.dto.AccountSecurityStateRequestDigest; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceEventReadback; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec.AccountState; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account-local immutable operation storage. Caller bytes are correlation only. This class neither + * authorizes a mutation nor updates Account/source/outbox or settles V57. Real owner evidence, + * exact workload/caller authentication and commit currentness must be proved separately; a digest + * cannot replace a retained owner receipt. Data access is not producer activation. + */ +@Repository +public class AccountSecurityStateOperationRepository { + private static final String TABLE = "account_security_state_operations"; + private final DSLContext dsl; + private final AccountAuthorityGenerationRepository generations; + private final AccountAuthorityOutboxRepository outbox; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + + @SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "Spring proxies require a non-final repository; constructor only validates internal DSL collaborators, acquires no resources and publishes no partial instance.") + public AccountSecurityStateOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + generations = new AccountAuthorityGenerationRepository(dsl); + outbox = new AccountAuthorityOutboxRepository(dsl); + sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + } + + /** Locks identity, then recovers the original request before comparing any new capture. */ + public Claim claim(AccountSecurityStateMutationRequest request, Capture capture) { + requireTransaction(); + Objects.requireNonNull(request); + Objects.requireNonNull(capture); + lockAssociation(capture.accountId(), request.accountUuid(), capture.provenance()); + Optional prior = readForUpdate(request.requestId()); + if (prior.isPresent()) { + Operation original = prior.orElseThrow(); + requireRequest(original, request); + if (capture.accountId() != original.capture().accountId() + || capture.provenance() != original.capture().provenance()) { + throw new OperationConflictException("Original Account association changed"); + } + if (original.receipt().isEmpty()) requireSourceChange(original.capture(), false); + return new Claim(false, original); + } + requireCapture(request, capture); + increment(request.expectedGeneration()); + increment(request.expectedSourceVersion()); + increment(capture.sourceState().issuanceFence().value()); + increment(capture.sourceState().issuanceFence().sourceVersion()); + increment(capture.checkpointSequence()); + if (request.mutationKinds().contains("GLOBAL_ROLE_CHANGED")) + increment(capture.globalRoleSourceVersion()); + ScopeState current = generations.read(AuthorityScope.account(request.accountUuid())); + if (!current.equals(capture.sourceState()) + || !readCurrentState(request.accountUuid(), capture.globalRoleSourceVersion()) + .equals(capture.beforeState())) { + throw new IllegalStateException("Original source/state capture is not current"); + } + requireCheckpoint(capture, request.accountUuid()); + requireSourceChange(capture, false); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, account_id, account_uuid, account_provenance, " + + "caller_proof_binding, request_payload, request_digest, expected_generation, " + + "expected_source_version, expected_fence, expected_fence_source_version, " + + "checkpoint_sequence, checkpoint_payload, global_role_source_version, before_state, " + + "after_state, mutation_kinds, source_change_id, source_change_binding, capture_payload, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'WAITING') " + + "ON CONFLICT (request_id) DO NOTHING", + request.requestId(), + capture.accountId(), + request.accountUuid(), + capture.provenance().name(), + request.callerProofBinding(), + AccountSecurityStateRequestDigest.requestBytes(request), + AccountSecurityStateRequestDigest.digest(request), + request.expectedGeneration(), + request.expectedSourceVersion(), + capture.sourceState().issuanceFence().value(), + capture.sourceState().issuanceFence().sourceVersion(), + capture.checkpointSequence(), + capture.checkpointPayload(), + capture.globalRoleSourceVersion(), + AccountSecurityStateMutationRequest.canonicalState(capture.beforeState()), + request.canonicalDesiredState(), + request.mutationKinds().toArray(String[]::new), + capture.sourceChange().changeId(), + capture.sourceChange().canonicalBytes(), + captureBytes(request, capture)); + Operation stored = readForUpdate(request.requestId()).orElseThrow(); + requireRequest(stored, request); + if (inserted == 1 + && !Arrays.equals( + captureBytes(request, capture), captureBytes(request, stored.capture()))) { + throw new IllegalStateException("Original operation capture readback differs"); + } + return new Claim(inserted == 1, stored); + } + + /** Returns immutable current or historical operation evidence without applying a mutation. */ + public Optional findByRequestId(UUID requestId) { + return findByRequestId(requestId, false); + } + + /** Reads only complete immutable receipts without upgrading a source reader's Account lock. */ + public Optional findCommittedByRequestIdShared(UUID requestId) { + return findByRequestId(requestId, true); + } + + private Optional findByRequestId(UUID requestId, boolean sharedCommittedRead) { + requireTransaction(); + Objects.requireNonNull(requestId); + Record identity = + dsl.fetchOne( + "SELECT account_id, account_uuid, account_provenance FROM " + + TABLE + + " WHERE request_id = ?", + requestId); + if (identity == null) return Optional.empty(); + lockAssociation( + identity.get("account_id", Long.class), + identity.get("account_uuid", UUID.class), + AccountIdentityProvenance.fromStorageValue( + identity.get("account_provenance", String.class)), + sharedCommittedRead); + Optional stored = readOperation(requestId, sharedCommittedRead); + if (sharedCommittedRead && stored.isPresent() && stored.orElseThrow().receipt().isEmpty()) { + throw new IllegalStateException("Complete committed security-state receipt is required"); + } + stored + .filter(operation -> operation.receipt().isEmpty()) + .ifPresent(operation -> requireSourceChange(operation.capture(), false)); + return stored; + } + + /** Proves actual current poststate, separately from immutable historical receipt validation. */ + public void requireCurrentPostState(Operation operation, ScopeState current) { + requireTransaction(); + Objects.requireNonNull(operation); + Receipt receipt = + operation + .receipt() + .orElseThrow( + () -> new IllegalStateException("Committed security-state receipt is required")); + var request = operation.request(); + lockAssociation( + operation.capture().accountId(), + request.accountUuid(), + operation.capture().provenance(), + true); + Operation stored = findCommittedByRequestIdShared(request.requestId()).orElseThrow(); + requireRequest(stored, request); + if (!stored.receipt().orElseThrow().event().equals(receipt.event()) + || current == null + || !receipt.sourceState().scope().equals(current.scope()) + || receipt.sourceState().generation() != current.generation() + || receipt.sourceState().sourceVersion() != current.sourceVersion() + || !generations.read(AuthorityScope.account(request.accountUuid())).equals(current) + || !readCurrentState(request.accountUuid(), receipt.globalRoleSourceVersion()) + .equals(request.desiredState())) { + throw new IllegalStateException( + "Latest security-state actual Account/role/source poststate differs"); + } + var checkpoint = outbox.readCheckpoint(streamKey(request.accountUuid())).orElseThrow(); + if (checkpoint.outboxSequence() != receipt.event().outboxSequence() + || !checkpoint.sourceEventId().equals(receipt.event().eventId()) + || !checkpoint.sourceEventDigest().equals(receipt.event().eventDigest())) { + throw new IllegalStateException("Latest security-state complete checkpoint differs"); + } + } + + /** Records only an existing producer-committed event and V57 completion in this transaction. */ + public Operation complete( + AccountSecurityStateMutationRequest request, + Event event, + ScopeState result, + long resultGlobalRoleSourceVersion) { + requireTransaction(); + Record identity = + dsl.fetchOne( + "SELECT account_id, account_provenance FROM " + TABLE + " WHERE request_id = ?", + request.requestId()); + if (identity == null) + throw new IllegalStateException("Original security-state request is missing"); + lockAssociation( + identity.get("account_id", Long.class), + request.accountUuid(), + AccountIdentityProvenance.fromStorageValue( + identity.get("account_provenance", String.class))); + Operation original = readForUpdate(request.requestId()).orElseThrow(); + requireRequest(original, request); + if (original.receipt().isPresent()) { + Receipt committed = original.receipt().orElseThrow(); + if (!committed.event().equals(event) + || !committed.sourceState().equals(result) + || committed.globalRoleSourceVersion() != resultGlobalRoleSourceVersion) { + throw new OperationConflictException("Committed receipt was supplied with changed results"); + } + return original; + } + requireResult(original, event, result, resultGlobalRoleSourceVersion); + requireSourceChange(original.capture(), true); + if (!generations.read(AuthorityScope.account(request.accountUuid())).equals(result) + || !readCurrentState(request.accountUuid(), resultGlobalRoleSourceVersion) + .equals(request.desiredState())) { + throw new IllegalStateException("Committed producer state readback differs"); + } + var checkpoint = outbox.readCheckpoint(event.outboxStreamKey()).orElseThrow(); + if (checkpoint.outboxSequence() != event.outboxSequence() + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new IllegalStateException("Committed source checkpoint readback differs"); + } + int updated = + dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'COMMITTED', event_sequence = ?, event_id = ?, " + + "event_digest = ?, event_payload = ?, result_generation = ?, result_source_version = ?, " + + "result_fence = ?, result_fence_source_version = ?, result_global_role_source_version = ? " + + "WHERE request_id = ? AND status = 'WAITING'", + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.payload(), + result.generation(), + result.sourceVersion(), + result.issuanceFence().value(), + result.issuanceFence().sourceVersion(), + resultGlobalRoleSourceVersion, + request.requestId()); + if (updated != 1) throw new IllegalStateException("Operation did not commit exactly once"); + Operation stored = readForUpdate(request.requestId()).orElseThrow(); + requireRequest(stored, request); + if (!stored.receipt().orElseThrow().event().equals(event)) { + throw new IllegalStateException("Committed operation event readback differs"); + } + sourceEvidence.advanceClosedAccountHead( + request.accountUuid(), original.capture().sourceState(), result, event); + return stored; + } + + private Optional readForUpdate(UUID requestId) { + return readOperation(requestId, false); + } + + private Optional readOperation(UUID requestId, boolean shared) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE request_id = ?" + + (shared ? " FOR SHARE" : " FOR UPDATE"), + requestId); + if (row == null) return Optional.empty(); + UUID accountUuid = row.get("account_uuid", UUID.class); + var request = + new AccountSecurityStateMutationRequest( + requestId, + accountUuid, + row.get("caller_proof_binding", byte[].class), + row.get("expected_generation", Long.class), + row.get("expected_source_version", Long.class), + List.of(row.get("mutation_kinds", String[].class)), + AccountSecurityStateMutationRequest.parseCanonicalState( + row.get("after_state", byte[].class))); + if (!Arrays.equals( + AccountSecurityStateRequestDigest.requestBytes(request), + row.get("request_payload", byte[].class)) + || !AccountSecurityStateRequestDigest.digest(request) + .equals(row.get("request_digest", String.class))) { + throw new IllegalStateException("Stored original request digest/bytes differ"); + } + ScopeState expected = + new ScopeState( + AuthorityScope.account(accountUuid), + request.expectedGeneration(), + request.expectedSourceVersion(), + new AccountAuthorityGenerationRepository.IssuanceFence( + accountUuid, + row.get("expected_fence", Long.class), + row.get("expected_fence_source_version", Long.class))); + Capture capture = + new Capture( + row.get("account_id", Long.class), + AccountIdentityProvenance.fromStorageValue(row.get("account_provenance", String.class)), + AccountSecurityStateMutationRequest.parseCanonicalState( + row.get("before_state", byte[].class)), + expected, + row.get("checkpoint_sequence", Long.class), + row.get("checkpoint_payload", byte[].class), + row.get("global_role_source_version", Long.class), + SourceChange.fromStored(row.get("source_change_binding", byte[].class))); + requireCapture(request, capture); + if (!capture.sourceChange().changeId().equals(row.get("source_change_id", UUID.class)) + || !Arrays.equals( + captureBytes(request, capture), row.get("capture_payload", byte[].class))) { + throw new IllegalStateException("Stored original source capture differs"); + } + String status = row.get("status", String.class); + Optional receipt = Optional.empty(); + if ("COMMITTED".equals(status)) { + Event event = + new Event( + streamKey(accountUuid), + requestId.toString(), + row.get("event_sequence", Long.class), + row.get("event_id", String.class), + row.get("event_digest", String.class), + row.get("event_payload", byte[].class)); + ScopeState result = + new ScopeState( + AuthorityScope.account(accountUuid), + row.get("result_generation", Long.class), + row.get("result_source_version", Long.class), + new AccountAuthorityGenerationRepository.IssuanceFence( + accountUuid, + row.get("result_fence", Long.class), + row.get("result_fence_source_version", Long.class))); + receipt = + Optional.of( + new Receipt(event, result, row.get("result_global_role_source_version", Long.class))); + } else if (!"WAITING".equals(status)) { + throw new IllegalStateException("Unsupported operation state"); + } + Operation operation = new Operation(request, capture, receipt); + if (receipt.isPresent()) { + requireResult( + operation, + receipt.orElseThrow().event(), + receipt.orElseThrow().sourceState(), + receipt.orElseThrow().globalRoleSourceVersion()); + requireSourceChange(capture, true); + requireReceiptNotAhead(operation); + } + return Optional.of(operation); + } + + private void requireResult( + Operation operation, Event event, ScopeState result, long roleSourceVersion) { + if (event == null || result == null || result.issuanceFence() == null) { + throw new IllegalStateException("Complete Account source receipt is required"); + } + var request = operation.request(); + var capture = operation.capture(); + var verified = + AccountSecurityStateAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + if (!Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + || !request.accountUuid().toString().equals(verified.accountId()) + || !request.requestId().toString().equals(verified.requestId()) + || !request.requestId().toString().equals(event.requestId()) + || !streamKey(request.accountUuid()).equals(event.outboxStreamKey()) + || !event.outboxStreamKey().equals(verified.outboxStreamKey()) + || !event.eventId().equals(verified.eventId()) + || !event.eventDigest().equals(verified.eventDigest()) + || !Long.toString(event.outboxSequence()).equals(verified.outboxSequence()) + || event.outboxSequence() != increment(capture.checkpointSequence()) + || !result.scope().equals(capture.sourceState().scope()) + || result.generation() != increment(request.expectedGeneration()) + || result.sourceVersion() != increment(request.expectedSourceVersion()) + || !Long.toString(result.generation()).equals(verified.accountAuthorityGeneration()) + || !Long.toString(result.sourceVersion()).equals(verified.sourceVersion()) + || !request.accountUuid().equals(result.issuanceFence().accountId()) + || result.issuanceFence().value() + != increment(capture.sourceState().issuanceFence().value()) + || result.issuanceFence().sourceVersion() + != increment(capture.sourceState().issuanceFence().sourceVersion()) + || roleSourceVersion + != (request.mutationKinds().contains("GLOBAL_ROLE_CHANGED") + ? increment(capture.globalRoleSourceVersion()) + : capture.globalRoleSourceVersion()) + || !verified.accountState().equals(request.desiredState()) + || !verified.mutationKinds().equals(request.mutationKinds())) { + throw new IllegalStateException("Source receipt differs from the original operation/result"); + } + Event byRequest = outbox.findEvent(event.outboxStreamKey(), event.requestId()).orElseThrow(); + Event bySequence = + outbox.findEvent(event.outboxStreamKey(), event.outboxSequence()).orElseThrow(); + if (!event.equals(byRequest) || !event.equals(bySequence)) { + throw new IllegalStateException("Canonical outbox receipt readback differs"); + } + } + + private void requireCapture(AccountSecurityStateMutationRequest request, Capture capture) { + Objects.requireNonNull(capture.sourceChange(), "Original V57 source change is required"); + if (!capture.sourceState().scope().equals(AuthorityScope.account(request.accountUuid())) + || capture.sourceState().generation() != request.expectedGeneration() + || capture.sourceState().sourceVersion() != request.expectedSourceVersion() + || !request.accountUuid().equals(capture.sourceState().issuanceFence().accountId()) + || !detectedKinds(capture.beforeState(), request.desiredState()) + .equals(request.mutationKinds())) { + throw new IllegalArgumentException( + "Original state/source/family capture differs from request"); + } + // Passwords are intentionally absent; their real owner operation is outside this journal. + boolean accountSource = false; + boolean roleSource = false; + for (var source : capture.sourceChange().sources()) { + if (!request.accountUuid().toString().equals(source.scopeId())) { + throw new IllegalArgumentException("Source participation targets another Account"); + } + if (source.kind() == SourceKind.ACCOUNT) { + accountSource = true; + if (!Long.toString(request.expectedGeneration()).equals(source.generation()) + || !Long.toString(request.expectedSourceVersion()).equals(source.sourceVersion()) + || !streamKey(request.accountUuid()).equals(source.checkpointStream()) + || !Long.toString(capture.checkpointSequence()).equals(source.checkpointSequence()) + || !Arrays.equals(captureBytes(request, capture), source.evidence())) { + throw new IllegalArgumentException("Exact Account source participation is required"); + } + } else if (source.kind() == SourceKind.GLOBAL_ROLES) { + roleSource = true; + if (!Long.toString(capture.globalRoleSourceVersion()).equals(source.sourceVersion()) + || source.generation() != null + || source.checkpointStream() != null + || !Arrays.equals(captureBytes(request, capture), source.evidence())) { + throw new IllegalArgumentException("Independent role-source version differs"); + } + } else { + throw new IllegalArgumentException("Unrelated source participation is unsupported"); + } + } + if (!accountSource + || roleSource != request.mutationKinds().contains("GLOBAL_ROLE_CHANGED") + || !Arrays.equals(captureBytes(request, capture), capture.sourceChange().mutation())) { + throw new IllegalArgumentException("Complete exact source-change binding is required"); + } + } + + public static List detectedKinds(AccountState before, AccountState after) { + List kinds = new ArrayList<>(); + if (before.emailVerified() != after.emailVerified()) + kinds.add("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); + if (!before.globalRoles().equals(after.globalRoles())) kinds.add("GLOBAL_ROLE_CHANGED"); + if (!before.lifecycleState().equals(after.lifecycleState())) + kinds.add("LIFECYCLE_STATE_CHANGED"); + if (!before.loginAuthModes().equals(after.loginAuthModes())) + kinds.add("LOGIN_AUTH_MODES_CHANGED"); + return List.copyOf(kinds); + } + + public static byte[] captureBytes(AccountSecurityStateMutationRequest request, Capture capture) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + AccountSecurityStateRequestDigest.frame(bytes, "firemud/account/security-state/capture/v1"); + AccountSecurityStateRequestDigest.frame( + bytes, AccountSecurityStateRequestDigest.requestBytes(request)); + AccountSecurityStateRequestDigest.frame(bytes, Long.toString(capture.accountId())); + AccountSecurityStateRequestDigest.frame(bytes, capture.provenance().name()); + AccountSecurityStateRequestDigest.frame( + bytes, AccountSecurityStateMutationRequest.canonicalState(capture.beforeState())); + AccountSecurityStateRequestDigest.frame( + bytes, Long.toString(capture.sourceState().issuanceFence().value())); + AccountSecurityStateRequestDigest.frame( + bytes, Long.toString(capture.sourceState().issuanceFence().sourceVersion())); + AccountSecurityStateRequestDigest.frame(bytes, Long.toString(capture.checkpointSequence())); + AccountSecurityStateRequestDigest.frame(bytes, capture.checkpointPayload()); + AccountSecurityStateRequestDigest.frame( + bytes, Long.toString(capture.globalRoleSourceVersion())); + return bytes.toByteArray(); + } + + private void requireCheckpoint(Capture capture, UUID accountUuid) { + var checkpoint = outbox.readCheckpoint(streamKey(accountUuid)); + if (capture.checkpointSequence() == 0) { + Record history = + dsl.fetchOne( + "SELECT count(*)::integer AS count FROM account_authority_outbox_events WHERE outbox_stream_key = ?", + streamKey(accountUuid)); + if (history == null) { + throw new IllegalStateException("Original Account source history count is missing"); + } + Integer count = history.get("count", Integer.class); + if (capture.sourceState().generation() != 1 + || capture.sourceState().sourceVersion() != 1 + || checkpoint.isPresent() + || count == null + || count != 0 + || capture.checkpointPayload().length != 0) { + throw new IllegalStateException("Original sequence-zero baseline is not proved"); + } + } else { + Event latest = + outbox.findEvent(streamKey(accountUuid), capture.checkpointSequence()).orElseThrow(); + if (checkpoint.orElseThrow().outboxSequence() != capture.checkpointSequence() + || !checkpoint.orElseThrow().sourceEventId().equals(latest.eventId()) + || !checkpoint.orElseThrow().sourceEventDigest().equals(latest.eventDigest()) + || !latest.equals( + outbox.findEvent(streamKey(accountUuid), latest.requestId()).orElseThrow()) + || !Arrays.equals(capture.checkpointPayload(), latest.payload())) { + throw new IllegalStateException("Original checkpoint capture differs"); + } + // Structural closed-schema verification only; this does not prove caller authorization. + new AccountSourceSnapshot( + accountUuid, + capture.sourceState(), + streamKey(accountUuid), + capture.checkpointSequence(), + Optional.of(latest)); + } + } + + private void requireReceiptNotAhead(Operation operation) { + Receipt retained = operation.receipt().orElseThrow(); + UUID accountUuid = operation.request().accountUuid(); + ScopeState current = generations.read(AuthorityScope.account(accountUuid)); + var checkpoint = outbox.readCheckpoint(streamKey(accountUuid)).orElseThrow(); + Event latest = + outbox.findEvent(streamKey(accountUuid), checkpoint.outboxSequence()).orElseThrow(); + AccountSourceSnapshot snapshot = + new AccountSourceSnapshot( + accountUuid, + current, + streamKey(accountUuid), + checkpoint.outboxSequence(), + Optional.of(latest)); + new AccountSourceEventReadback(snapshot, retained.event()); + Record role = + dsl.fetchOne( + "SELECT global_role_source_version FROM account_global_role_sources WHERE account_uuid = ? FOR SHARE", + accountUuid); + Long roleVersion = role == null ? null : role.get("global_role_source_version", Long.class); + if (retained.sourceState().issuanceFence().value() > current.issuanceFence().value() + || retained.sourceState().issuanceFence().sourceVersion() + > current.issuanceFence().sourceVersion() + || roleVersion == null + || retained.globalRoleSourceVersion() > roleVersion) { + throw new IllegalStateException("Retained receipt is ahead of present Account authority"); + } + } + + private void requireSourceChange(Capture capture, boolean committed) { + Record source = + dsl.fetchOne( + "SELECT binding, status FROM account_draft_authorization_source_changes WHERE change_id = ? FOR SHARE", + capture.sourceChange().changeId()); + if (source == null + || !Arrays.equals( + capture.sourceChange().canonicalBytes(), source.get("binding", byte[].class)) + || !(committed ? "SOURCE_COMMITTED" : "WAITING") + .equals(source.get("status", String.class))) { + throw new IllegalStateException("Original V57 source-change evidence/status differs"); + } + } + + private void lockAssociation( + long numericId, UUID accountUuid, AccountIdentityProvenance provenance) { + lockAssociation(numericId, accountUuid, provenance, false); + } + + private void lockAssociation( + long numericId, UUID accountUuid, AccountIdentityProvenance provenance, boolean shared) { + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_source_numeric_id, account_uuid_provenance FROM accounts WHERE id = ?" + + (shared ? " FOR SHARE" : " FOR UPDATE"), + numericId); + if (account == null + || !accountUuid.equals(account.get("account_uuid", UUID.class)) + || !Long.valueOf(numericId) + .equals(account.get("account_uuid_source_numeric_id", Long.class)) + || !provenance.name().equals(account.get("account_uuid_provenance", String.class))) { + throw new IllegalStateException("Persisted numeric/UUID/provenance association differs"); + } + } + + private AccountState readCurrentState(UUID accountUuid, long roleVersion) { + Record row = + dsl.fetchOne( + "SELECT a.email_verified, a.login_auth_modes, a.lifecycle_state, r.global_roles, r.global_role_source_version FROM accounts a JOIN account_global_role_sources r ON r.account_uuid = a.account_uuid WHERE a.account_uuid = ? FOR SHARE OF a, r", + accountUuid); + if (row == null + || !Long.valueOf(roleVersion).equals(row.get("global_role_source_version", Long.class))) { + throw new IllegalStateException( + "Current independently versioned global-role source is unavailable"); + } + var state = + new AccountState( + Boolean.TRUE.equals(row.get("email_verified", Boolean.class)), + AccountLoginAuthModes.read(row.get("login_auth_modes", String.class)).stream() + .map(Enum::name) + .sorted() + .toList(), + Arrays.stream(row.get("global_roles", String[].class)).sorted().toList(), + row.get("lifecycle_state", String.class).toUpperCase(java.util.Locale.ROOT)); + return AccountSecurityStateMutationRequest.parseCanonicalState( + AccountSecurityStateMutationRequest.canonicalState(state)); + } + + private static void requireRequest( + Operation original, AccountSecurityStateMutationRequest request) { + if (!Arrays.equals( + AccountSecurityStateRequestDigest.requestBytes(original.request()), + AccountSecurityStateRequestDigest.requestBytes(request))) { + throw new OperationConflictException( + "Request ID was reused with changed original caller/state binding"); + } + } + + private static long increment(long value) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account source counter overflow", overflow); + } + } + + private static String streamKey(UUID accountUuid) { + return "account:auth-authority:v1:account/" + accountUuid; + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account owner transaction is required"); + } + } + + public record Capture( + long accountId, + AccountIdentityProvenance provenance, + AccountState beforeState, + ScopeState sourceState, + long checkpointSequence, + byte[] checkpointPayload, + long globalRoleSourceVersion, + SourceChange sourceChange) { + public Capture { + if (accountId <= 0 + || checkpointSequence < 0 + || globalRoleSourceVersion <= 0 + || provenance == null + || beforeState == null + || sourceState == null + || sourceState.issuanceFence() == null + || checkpointPayload == null) + throw new IllegalArgumentException("Complete original capture is required"); + checkpointPayload = checkpointPayload.clone(); + beforeState = + AccountSecurityStateMutationRequest.parseCanonicalState( + AccountSecurityStateMutationRequest.canonicalState(beforeState)); + // A temporary null change is permitted solely while constructing its non-circular capture + // bytes. + } + + @Override + public byte[] checkpointPayload() { + return checkpointPayload.clone(); + } + } + + public record Receipt(Event event, ScopeState sourceState, long globalRoleSourceVersion) {} + + public record Operation( + AccountSecurityStateMutationRequest request, Capture capture, Optional receipt) {} + + public record Claim(boolean claimed, Operation operation) {} + + public static final class OperationConflictException extends IllegalStateException { + public OperationConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java new file mode 100644 index 0000000000..60655921ca --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java @@ -0,0 +1,580 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Typed tenant-authority source, outbox, receipt, and current-checkpoint readback. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account repositories and DSLContext are private transaction collaborators.") +public class AccountTenantAuthorityEventRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final AccountAuthorityOutboxRepository authorityOutbox; + private final AccountTenantEntitlementOutboxRepository billingOutbox; + private final FreshTenantIdentityAssociationRepository tenantIdentity; + private final AccountAuthorityGenerationRepository generations; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve injected collaborator preconditions; Spring must proxy this non-final repository.") + public AccountTenantAuthorityEventRepository( + DSLContext dsl, + AccountAuthorityOutboxRepository authorityOutbox, + AccountTenantEntitlementOutboxRepository billingOutbox, + FreshTenantIdentityAssociationRepository tenantIdentity, + AccountAuthorityGenerationRepository generations) { + this.dsl = Objects.requireNonNull(dsl); + this.authorityOutbox = Objects.requireNonNull(authorityOutbox); + this.billingOutbox = Objects.requireNonNull(billingOutbox); + this.tenantIdentity = Objects.requireNonNull(tenantIdentity); + this.generations = Objects.requireNonNull(generations); + } + + /** Establishes sequence zero only from the same Account transaction that enrolled the tenant. */ + @Transactional(propagation = Propagation.MANDATORY) + public void establishFirstEventSource( + UUID tenantId, UUID requestId, FreshTenantCreationEvidence source, ScopeState authority) { + requireTransaction(); + requireExactTenant(tenantId, source, authority); + if (authority.generation() != 1L || authority.sourceVersion() != 1L) { + throw new IllegalStateException( + "Tenant authority has advanced without canonical source-event evidence"); + } + + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + Record existingSource = + dsl.fetchOne( + "SELECT last_outbox_sequence FROM account_tenant_authority_source_records " + + "WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (existingSource != null) { + throw new IllegalStateException( + "Tenant authority source already exists without its current entitlement row"); + } + + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (stream != null) { + throw new IllegalStateException( + "Tenant authority stream exists without Account source initialization proof"); + } + + Record sourceInitialization = + dsl.fetchOne( + "SELECT fresh.authority_source_transaction_id, generation.created_transaction_id, " + + "generation.generation, generation.source_version " + + "FROM account_fresh_tenant_identity_associations fresh " + + "JOIN account_canonical_tenant_identity_claims claim " + + "ON claim.canonical_tenant_id = fresh.canonical_tenant_id " + + "AND claim.identity_kind = 'FRESH_GAME_DESIGN' " + + "AND claim.source_operation_id = fresh.operation_id " + + "AND claim.source_creation_request_id = fresh.creation_request_id " + + "AND claim.source_request_digest = fresh.request_digest " + + "AND claim.source_game_row_id = fresh.source_game_row_id " + + "AND claim.source_game_tenant_key = fresh.source_game_tenant_key " + + "AND claim.source_provenance_kind = fresh.provenance_kind " + + "AND claim.source_evidence_digest = fresh.evidence_digest " + + "JOIN account_authority_generations generation " + + "ON generation.scope_kind = 'TENANT' " + + "AND generation.tenant_uuid = fresh.canonical_tenant_id " + + "WHERE fresh.canonical_tenant_id = ?", + tenantId); + if (sourceInitialization == null + || sourceInitialization.get("authority_source_transaction_id", Long.class) == null + || !Objects.equals( + sourceInitialization.get("authority_source_transaction_id", Long.class), + sourceInitialization.get("created_transaction_id", Long.class)) + || !Long.valueOf(1L).equals(sourceInitialization.get("generation", Long.class)) + || !Long.valueOf(1L).equals(sourceInitialization.get("source_version", Long.class))) { + throw new IllegalStateException( + "Fresh tenant source and Account generation lack one owner initialization proof"); + } + + Record billingStream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR SHARE", + tenantId); + Record priorOperation = + dsl.fetchOne( + "SELECT request_id FROM account_demo_tenant_entitlement_operations " + + "WHERE tenant_uuid = ? AND request_id <> ? LIMIT 1", + tenantId, + requestId); + if (billingStream != null || priorOperation != null) { + throw new IllegalStateException( + "Tenant has retained billing history without canonical authority source evidence"); + } + + int streamInserted = + dsl.execute( + "INSERT INTO account_authority_outbox_streams (outbox_stream_key, last_sequence) " + + "VALUES (?, 0) ON CONFLICT (outbox_stream_key) DO NOTHING", + streamKey); + if (streamInserted != 1) { + throw new IllegalStateException( + "Tenant authority stream changed before Account source enrollment"); + } + long initializationTransactionId = + sourceInitialization.get("created_transaction_id", Long.class); + int sourceInserted = + dsl.execute( + "INSERT INTO account_tenant_authority_source_records (outbox_stream_key, tenant_uuid, " + + "initialization_transaction_id, baseline_generation, baseline_source_version, " + + "current_generation, current_source_version, last_outbox_sequence) " + + "VALUES (?, ?, ?, 1, 1, 1, 1, 0)", + streamKey, + tenantId, + initializationTransactionId); + if (sourceInserted != 1) { + throw new IllegalStateException("Tenant authority source baseline was not enrolled"); + } + } + + /** Appends one tenant-scoped event after the owner has advanced the exact generation row. */ + @Transactional(propagation = Propagation.MANDATORY) + public Event append( + DemoTenantEntitlementRequest request, + FreshTenantCreationEvidence source, + ScopeState nextAuthority, + DemoTenantEntitlementEventV1Codec.Event billingEvent) { + requireTransaction(); + if (request == null || billingEvent == null) { + throw new IllegalArgumentException("Tenant authority request and billing event are required"); + } + requireExactTenant(request.canonicalTenantId(), source, nextAuthority); + String streamKey = TenantAuthorityEventV1Codec.streamKey(request.canonicalTenantId()); + Record sourceHead = + dsl.fetchOne( + "SELECT current_generation, current_source_version, last_outbox_sequence " + + "FROM account_tenant_authority_source_records WHERE outbox_stream_key = ? FOR UPDATE", + streamKey); + if (sourceHead == null || nonnegative(sourceHead, "last_outbox_sequence") < 0L) { + throw new IllegalStateException( + "Tenant authority source head does not match the actual prior generation"); + } + if (increment(positive(sourceHead, "current_generation"), "generation") + != nextAuthority.generation() + || increment(positive(sourceHead, "current_source_version"), "source version") + != nextAuthority.sourceVersion()) { + throw new IllegalStateException( + "Tenant authority source head does not match the actual prior generation"); + } + AccountAuthorityOutboxRepository.Event committed = + authorityOutbox.append( + streamKey, + request.requestId().toString(), + sequence -> + evidence( + TenantAuthorityEventV1Codec.seal( + request, + source, + nextAuthority.generation(), + nextAuthority.sourceVersion(), + sequence, + billingEvent))); + TenantAuthorityEventV1Codec.Event typed = + TenantAuthorityEventV1Codec.verify(committed.payload()); + if (!committed.outboxStreamKey().equals(streamKey) + || !committed.requestId().equals(request.requestId().toString()) + || typed.outboxSequence() != committed.outboxSequence() + || !typed.eventId().toString().equals(committed.eventId()) + || !typed.eventDigest().equals(committed.eventDigest()) + || !request.requestId().equals(typed.requestId()) + || !request.requestDigest().equals(typed.requestDigest()) + || !source.equals(typed.sourceEvidence()) + || typed.tenantAuthorityGeneration() != nextAuthority.generation() + || typed.tenantAuthoritySourceVersion() != nextAuthority.sourceVersion() + || typed.tenantBillingSequence() != billingEvent.tenantBillingSequence() + || !typed.tenantBillingEventId().equals(billingEvent.eventId()) + || !typed.tenantBillingEventDigest().equals(billingEvent.eventDigest())) { + throw new IllegalStateException( + "Committed tenant authority outbox event differs from its exact Account source"); + } + int updated = + dsl.execute( + "UPDATE account_tenant_authority_source_records SET current_generation = ?, " + + "current_source_version = ?, last_outbox_sequence = ?, last_request_id = ?, " + + "last_request_digest = ?, last_event_id = ?, last_event_digest = ?, " + + "tenant_billing_sequence = ?, tenant_billing_event_id = ?, " + + "tenant_billing_event_digest = ? WHERE outbox_stream_key = ? " + + "AND current_generation = ? AND current_source_version = ? " + + "AND last_outbox_sequence = ?", + typed.tenantAuthorityGeneration(), + typed.tenantAuthoritySourceVersion(), + typed.outboxSequence(), + typed.requestId(), + typed.requestDigest(), + typed.eventId().toString(), + typed.eventDigest(), + typed.tenantBillingSequence(), + typed.tenantBillingEventId(), + typed.tenantBillingEventDigest(), + streamKey, + typed.tenantAuthorityGeneration() - 1L, + typed.tenantAuthoritySourceVersion() - 1L, + typed.outboxSequence() - 1L); + if (updated != 1) { + throw new IllegalStateException("Tenant authority source checkpoint was not advanced once"); + } + return typed; + } + + /** + * Verifies the exact event and owning committed receipt, without requiring it to remain latest. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Event readCommittedReceipt( + UUID tenantId, + UUID requestId, + String requestDigest, + FreshTenantCreationEvidence source, + long billingSequence, + UUID billingEventId, + String billingEventDigest, + long authoritySequence, + String authorityEventId, + String authorityEventDigest) { + requireTransaction(); + requireTenant(tenantId); + Record operation = + dsl.fetchOne( + "SELECT tenant_uuid, request_digest, source_creation_request_id, source_request_digest, " + + "source_operation_id, source_evidence_digest, status, tenant_billing_sequence, " + + "event_id, event_digest, tenant_authority_outbox_stream_key, " + + "tenant_authority_outbox_sequence, tenant_authority_event_id, " + + "tenant_authority_event_digest FROM account_demo_tenant_entitlement_operations " + + "WHERE request_id = ?", + requestId); + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + if (operation == null + || !tenantId.equals(operation.get("tenant_uuid", UUID.class)) + || !requestDigest.equals(operation.get("request_digest", String.class)) + || !"COMMITTED".equals(operation.get("status", String.class)) + || !source + .creationRequestId() + .equals(operation.get("source_creation_request_id", UUID.class)) + || !source.requestDigest().equals(operation.get("source_request_digest", String.class)) + || !source.operationId().equals(operation.get("source_operation_id", UUID.class)) + || !source.evidenceDigest().equals(operation.get("source_evidence_digest", String.class)) + || billingSequence != positive(operation, "tenant_billing_sequence") + || !billingEventId.equals(operation.get("event_id", UUID.class)) + || !billingEventDigest.equals(operation.get("event_digest", String.class)) + || !streamKey.equals(operation.get("tenant_authority_outbox_stream_key", String.class)) + || authoritySequence != positive(operation, "tenant_authority_outbox_sequence") + || !authorityEventId.equals(operation.get("tenant_authority_event_id", String.class)) + || !authorityEventDigest.equals( + operation.get("tenant_authority_event_digest", String.class))) { + throw new IllegalStateException( + "Tenant authority readback has no exact owning committed entitlement receipt"); + } + AccountAuthorityOutboxRepository.Event stored = + authorityOutbox + .findEvent(streamKey, authoritySequence) + .orElseThrow( + () -> new IllegalStateException("Tenant authority event is absent at its receipt")); + Event event = TenantAuthorityEventV1Codec.verify(stored.payload()); + if (!stored.eventId().equals(event.eventId().toString()) + || !stored.eventDigest().equals(event.eventDigest()) + || !stored.requestId().equals(requestId.toString()) + || !event.requestDigest().equals(requestDigest) + || !event.tenantId().equals(tenantId) + || !source.equals(event.sourceEvidence()) + || event.tenantBillingSequence() != billingSequence + || !event.tenantBillingEventId().equals(billingEventId) + || !event.tenantBillingEventDigest().equals(billingEventDigest)) { + throw new IllegalStateException( + "Tenant authority event differs from its exact entitlement receipt or source"); + } + DemoTenantEntitlementEventV1Codec.Event billing = + billingOutbox + .readEvent(tenantId, billingSequence) + .orElseThrow( + () -> new IllegalStateException("Tenant billing event is absent at its receipt")); + if (!billing.eventId().equals(billingEventId) + || !billing.eventDigest().equals(billingEventDigest) + || !requestId.equals(billing.requestId()) + || !requestDigest.equals(billing.requestDigest()) + || !source.equals(billing.sourceEvidence())) { + throw new IllegalStateException( + "Tenant authority event does not link to the exact original billing event"); + } + return event; + } + + /** Verifies that a current Account generation is represented by the exact latest source event. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Event readCurrentCheckpoint( + UUID tenantId, + FreshTenantCreationEvidence source, + ScopeState authority, + UUID requestId, + String requestDigest, + long billingSequence, + UUID billingEventId, + String billingEventDigest) { + requireTransaction(); + requireExactTenant(tenantId, source, authority); + String streamKey = TenantAuthorityEventV1Codec.streamKey(tenantId); + Record head = + dsl.fetchOne( + "SELECT current_generation, current_source_version, last_outbox_sequence, " + + "last_event_id, last_event_digest, last_request_id, last_request_digest, " + + "tenant_billing_sequence, tenant_billing_event_id, tenant_billing_event_digest " + + "FROM account_tenant_authority_source_records WHERE outbox_stream_key = ?", + streamKey); + if (head == null + || positive(head, "current_generation") != authority.generation() + || positive(head, "current_source_version") != authority.sourceVersion() + || !requestId.equals(head.get("last_request_id", UUID.class)) + || !requestDigest.equals(head.get("last_request_digest", String.class)) + || billingSequence != positive(head, "tenant_billing_sequence") + || !billingEventId.equals(head.get("tenant_billing_event_id", UUID.class)) + || !billingEventDigest.equals(head.get("tenant_billing_event_digest", String.class))) { + throw new IllegalStateException( + "Tenant authority source checkpoint is absent, stale, or differs from Account current state"); + } + long sequence = positive(head, "last_outbox_sequence"); + String eventId = requiredText(head, "last_event_id"); + String eventDigest = requiredText(head, "last_event_digest"); + AccountAuthorityOutboxRepository.Checkpoint checkpoint = + authorityOutbox + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Tenant authority outbox checkpoint is absent")); + if (checkpoint.outboxSequence() != sequence + || !checkpoint.sourceEventId().equals(eventId) + || !checkpoint.sourceEventDigest().equals(eventDigest)) { + throw new IllegalStateException( + "Tenant authority source checkpoint differs from its canonical outbox head"); + } + return readCommittedReceipt( + tenantId, + requestId, + requestDigest, + source, + billingSequence, + billingEventId, + billingEventDigest, + sequence, + eventId, + eventDigest); + } + + /** Resolves current Account owner state itself; callers cannot supply a receipt or checkpoint. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Event readCurrentByTenant(UUID tenantId) { + requireTransaction(); + requireTenant(tenantId); + Record freshIdentity = + dsl.fetchOne( + "SELECT canonical_tenant_id FROM account_fresh_tenant_identity_associations " + + "WHERE canonical_tenant_id = ? FOR SHARE", + tenantId); + if (freshIdentity == null + || !tenantId.equals(freshIdentity.get("canonical_tenant_id", UUID.class))) { + throw new IllegalStateException( + "Exact fresh Account tenant source association is unavailable"); + } + FreshTenantCreationEvidence source = + tenantIdentity + .read(tenantId) + .orElseThrow( + () -> + new IllegalStateException( + "Exact fresh Account tenant source evidence is unavailable")); + ScopeState authority = + generations.read(AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId)); + Record current = + dsl.fetchOne( + "SELECT source_schema_version, source_target_namespace, source_creation_request_id, " + + "source_operation_id, source_request_digest, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " + + "entitlement_kind, status, subscription_status, paid, gameplay_available, " + + "allow_public_join, allow_new_gameplay_bindings, allow_new_instance_starts, " + + "max_active_sessions, max_concurrent_game_instances, max_storage_bytes, " + + "entitlement_version, " + + "tenant_authority_generation, tenant_authority_source_version, " + + "tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, " + + "tenant_authority_event_id, tenant_authority_event_digest, " + + "tenant_billing_sequence, event_id, event_digest, last_request_id, last_request_digest " + + "FROM account_demo_tenant_entitlements WHERE tenant_uuid = ? FOR SHARE", + tenantId); + if (current == null + || !source.equals(sourceFromCurrent(tenantId, current)) + || positive(current, "tenant_authority_generation") != authority.generation() + || positive(current, "tenant_authority_source_version") != authority.sourceVersion() + || !TenantAuthorityEventV1Codec.streamKey(tenantId) + .equals(current.get("tenant_authority_outbox_stream_key", String.class))) { + throw new IllegalStateException( + "Account current tenant entitlement lacks matching fresh source and authority generation"); + } + long billingSequence = positive(current, "tenant_billing_sequence"); + UUID billingEventId = requiredUuid(current, "event_id"); + String billingEventDigest = requiredText(current, "event_digest"); + UUID requestId = requiredUuid(current, "last_request_id"); + String requestDigest = requiredText(current, "last_request_digest"); + long authoritySequence = positive(current, "tenant_authority_outbox_sequence"); + String authorityEventId = requiredText(current, "tenant_authority_event_id"); + String authorityEventDigest = requiredText(current, "tenant_authority_event_digest"); + Event event = + readCurrentCheckpoint( + tenantId, + source, + authority, + requestId, + requestDigest, + billingSequence, + billingEventId, + billingEventDigest); + if (event.outboxSequence() != authoritySequence + || !event.eventId().toString().equals(authorityEventId) + || !event.eventDigest().equals(authorityEventDigest) + || event.tenantAuthorityGeneration() != authority.generation() + || event.tenantAuthoritySourceVersion() != authority.sourceVersion()) { + throw new IllegalStateException( + "Account current tenant row differs from its exact typed authority event"); + } + DemoTenantEntitlementEventV1Codec.Event billingEvent = + billingOutbox + .readEvent(tenantId, billingSequence) + .orElseThrow(() -> new IllegalStateException("Current tenant billing event is absent")); + if (!billingEvent.eventId().equals(billingEventId) + || !billingEvent.eventDigest().equals(billingEventDigest) + || !billingEvent.requestId().equals(requestId) + || !billingEvent.requestDigest().equals(requestDigest) + || !source.equals(billingEvent.sourceEvidence()) + || billingEvent.tenantAuthorityGeneration() != authority.generation() + || billingEvent.tenantAuthoritySourceVersion() != authority.sourceVersion() + || !"NON_PAID_DEMO".equals(current.get("entitlement_kind", String.class)) + || !"ACTIVE".equals(current.get("status", String.class)) + || current.get("subscription_status", String.class) != null + || !Boolean.FALSE.equals(current.get("paid", Boolean.class)) + || positive(current, "entitlement_version") != billingEvent.entitlementVersion() + || !Objects.equals( + current.get("gameplay_available", Boolean.class), billingEvent.gameplayAvailable()) + || !Objects.equals( + current.get("allow_public_join", Boolean.class), billingEvent.allowPublicJoin()) + || !Objects.equals( + current.get("allow_new_gameplay_bindings", Boolean.class), + billingEvent.allowNewGameplayBindings()) + || !Objects.equals( + current.get("allow_new_instance_starts", Boolean.class), + billingEvent.allowNewInstanceStarts()) + || nonnegative(current, "max_active_sessions") != billingEvent.quotas().maxActiveSessions() + || nonnegative(current, "max_concurrent_game_instances") + != billingEvent.quotas().maxConcurrentGameInstances() + || nonnegative(current, "max_storage_bytes") != billingEvent.quotas().maxStorageBytes()) { + throw new IllegalStateException( + "Current tenant entitlement row differs from its exact committed billing event"); + } + return event; + } + + private static FreshTenantCreationEvidence sourceFromCurrent(UUID tenantId, Record current) { + return new FreshTenantCreationEvidence( + current.get("source_schema_version", Integer.class), + requiredText(current, "source_target_namespace"), + requiredUuid(current, "source_creation_request_id"), + requiredUuid(current, "source_operation_id"), + requiredText(current, "source_request_digest"), + tenantId, + positive(current, "source_game_row_id"), + requiredText(current, "source_game_tenant_key"), + requiredText(current, "source_provenance_kind"), + requiredText(current, "source_evidence_digest")); + } + + private static AccountAuthorityOutboxRepository.EventEvidence evidence(Event event) { + return new AccountAuthorityOutboxRepository.EventEvidence( + event.eventId().toString(), event.eventDigest(), event.payload()); + } + + private static void requireExactTenant( + UUID tenantId, FreshTenantCreationEvidence source, ScopeState authority) { + requireTenant(tenantId); + if (source == null + || authority == null + || !tenantId.equals(source.canonicalTenantId()) + || !AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId) + .equals(authority.scope()) + || authority.generation() <= 0L + || authority.sourceVersion() <= 0L) { + throw new IllegalArgumentException("Exact fresh tenant authority evidence is required"); + } + } + + private static void requireTenant(UUID tenantId) { + if (tenantId == null || NIL_UUID.equals(tenantId)) { + throw new IllegalArgumentException("Exact tenant UUID is required"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Tenant authority event operation requires the Account owner transaction"); + } + } + + private static long positive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static long nonnegative(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value < 0L) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static long increment(long value, String field) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Tenant authority " + field + " is exhausted", overflow); + } + } + + private static String requiredText(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isBlank()) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalStateException("Tenant authority " + field + " is absent or malformed"); + } + return value; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java new file mode 100644 index 0000000000..a5f7971da6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java @@ -0,0 +1,211 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.LongFunction; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec.Event; +import net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account-owned per-tenant billing/entitlement event stream for demo entitlement currentness. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Account transaction collaborator.") +public class AccountTenantEntitlementOutboxRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve the injected DSLContext precondition; Spring must proxy this non-final repository.") + public AccountTenantEntitlementOutboxRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public static String streamKey(UUID canonicalTenantId) { + if (canonicalTenantId == null || NIL_UUID.equals(canonicalTenantId)) { + throw new IllegalArgumentException( + "Canonical tenant UUID is required for entitlement stream"); + } + return "account:tenant-entitlement:v1:tenant/" + canonicalTenantId; + } + + /** Appends one event or returns only an exact request and payload replay. */ + @Transactional(propagation = Propagation.MANDATORY) + public Event append(UUID tenantId, UUID requestId, LongFunction eventFactory) { + requireTransaction(); + streamKey(tenantId); + if (requestId == null || NIL_UUID.equals(requestId) || eventFactory == null) { + throw new IllegalArgumentException( + "Exact entitlement request identity and event are required"); + } + String key = streamKey(tenantId); + dsl.execute( + "INSERT INTO account_tenant_entitlement_outbox_streams (tenant_uuid, last_sequence) " + + "VALUES (?, 0) ON CONFLICT (tenant_uuid) DO NOTHING", + tenantId); + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR UPDATE", + tenantId); + long currentSequence = nonnegative(stream, "last_sequence"); + Record priorRequest = + dsl.fetchOne( + "SELECT tenant_billing_sequence, event_id, event_digest, payload " + + "FROM account_tenant_entitlement_outbox_events " + + "WHERE tenant_uuid = ? AND request_id = ?", + tenantId, + requestId); + if (priorRequest != null) { + Event committed = event(tenantId, priorRequest); + Event candidate = + Objects.requireNonNull(eventFactory.apply(committed.tenantBillingSequence())); + if (!matches(committed, candidate) || currentSequence < committed.tenantBillingSequence()) { + throw new DemoTenantEntitlementException( + DemoTenantEntitlementException.Code.IDEMPOTENCY_CONFLICT, + "Tenant entitlement outbox request was reused with different event evidence"); + } + return committed; + } + + long nextSequence; + try { + nextSequence = Math.addExact(currentSequence, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Tenant entitlement event sequence is exhausted", overflow); + } + Event candidate = Objects.requireNonNull(eventFactory.apply(nextSequence)); + if (!tenantId.equals(candidate.canonicalTenantId()) + || !requestId.equals(candidate.requestId()) + || !key.equals(candidate.outboxStreamKey()) + || candidate.tenantBillingSequence() != nextSequence) { + throw new IllegalArgumentException("Tenant entitlement event differs from its exact stream"); + } + Record advanced = + dsl.fetchOne( + "UPDATE account_tenant_entitlement_outbox_streams SET last_sequence = ? " + + "WHERE tenant_uuid = ? AND last_sequence = ? RETURNING last_sequence", + nextSequence, + tenantId, + currentSequence); + if (advanced == null) { + throw new IllegalStateException("Tenant entitlement outbox stream changed concurrently"); + } + int inserted = + dsl.execute( + "INSERT INTO account_tenant_entitlement_outbox_events " + + "(tenant_uuid, tenant_billing_sequence, request_id, event_id, event_digest, payload) " + + "VALUES (?, ?, ?, ?, ?, ?)", + tenantId, + nextSequence, + requestId, + candidate.eventId(), + candidate.eventDigest(), + candidate.payload()); + if (inserted != 1) { + throw new IllegalStateException("Tenant entitlement outbox event was not appended"); + } + return candidate; + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCheckpoint(UUID tenantId) { + requireTransaction(); + Record stream = + dsl.fetchOne( + "SELECT last_sequence FROM account_tenant_entitlement_outbox_streams " + + "WHERE tenant_uuid = ? FOR SHARE", + tenantId); + if (stream == null || nonnegative(stream, "last_sequence") == 0L) { + return Optional.empty(); + } + long sequence = positive(stream, "last_sequence"); + Event event = + readEvent(tenantId, sequence) + .orElseThrow( + () -> new IllegalStateException("Tenant entitlement checkpoint has no event")); + return Optional.of( + new Checkpoint( + streamKey(tenantId), + event.tenantBillingSequence(), + event.eventId(), + event.eventDigest())); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readEvent(UUID tenantId, long sequence) { + requireTransaction(); + if (sequence <= 0L) { + throw new IllegalArgumentException("Tenant entitlement event sequence must be positive"); + } + Record row = + dsl.fetchOne( + "SELECT tenant_billing_sequence, request_id, event_id, event_digest, payload " + + "FROM account_tenant_entitlement_outbox_events " + + "WHERE tenant_uuid = ? AND tenant_billing_sequence = ?", + tenantId, + sequence); + return row == null ? Optional.empty() : Optional.of(event(tenantId, row)); + } + + private Event event(UUID tenantId, Record row) { + byte[] payload = row.get("payload", byte[].class); + Event event = DemoTenantEntitlementEventV1Codec.verify(payload); + if (!tenantId.equals(event.canonicalTenantId()) + || row.get("tenant_billing_sequence", Long.class) != event.tenantBillingSequence() + || !row.get("event_id", UUID.class).equals(event.eventId()) + || !row.get("event_digest", String.class).equals(event.eventDigest()) + || !row.get("request_id", UUID.class).equals(event.requestId())) { + throw new IllegalStateException("Stored tenant entitlement event differs from its payload"); + } + return event; + } + + private static boolean matches(Event left, Event right) { + return left.eventId().equals(right.eventId()) + && left.eventDigest().equals(right.eventDigest()) + && java.util.Arrays.equals(left.payload(), right.payload()); + } + + private static long positive(Record row, String field) { + Long value = row == null ? null : row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new IllegalStateException("Tenant entitlement outbox " + field + " is malformed"); + } + return value; + } + + private static long nonnegative(Record row, String field) { + Long value = row == null ? null : row.get(field, Long.class); + if (value == null || value < 0L) { + throw new IllegalStateException("Tenant entitlement outbox " + field + " is malformed"); + } + return value; + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Tenant entitlement outbox requires an owner transaction"); + } + } + + public record Checkpoint( + String outboxStreamKey, long sequence, UUID eventId, String eventDigest) { + public Checkpoint { + if (outboxStreamKey == null || sequence <= 0L || eventId == null || eventDigest == null) { + throw new IllegalArgumentException("Complete tenant entitlement checkpoint is required"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java new file mode 100644 index 0000000000..c6136e68ac --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java @@ -0,0 +1,714 @@ +package net.firedevops.firemud.accountservice.service; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountLogoutRequestDigest; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository.LogoutAllReceipt; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository.PasswordResetReceipt; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; + +/** + * Narrow receipt validator for the three closed Account account-scope source-event schemas. It does + * not authenticate a caller or turn source evidence into recipient authority. + */ +public final class AccountAuthoritySourceEventReadback { + private static final ObjectMapper SNAPSHOT_JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final String PASSWORD_RESET_REQUEST_ID_PREFIX = + "account-password-reset-request-v1:"; + private static final String PASSWORD_RESET_EVENT_ID_PREFIX = "account-password-reset-event-v1:"; + private static final String PASSWORD_RESET_REQUEST_DOMAIN = "account-password-reset-request/v1"; + private static final String LOGOUT_ALL_EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + private static final String PASSWORD_RESET_OPERATION_KIND = "PASSWORD_RESET"; + private static final String LOGOUT_ALL_OPERATION_KIND = "ACCOUNT_LOGOUT_ALL"; + private static final String LOGOUT_ALL_RESULT = "LOGOUT_ALL_COMMITTED"; + + private final AccountAuthorityOutboxRepository outboxRepository; + private final AccountPasswordResetOperationRepository passwordResetRepository; + private final AccountLogoutAllOperationRepository logoutAllRepository; + private final AccountSecurityStateOperationRepository securityStateRepository; + + public AccountAuthoritySourceEventReadback( + AccountAuthorityOutboxRepository outboxRepository, + AccountPasswordResetOperationRepository passwordResetRepository, + AccountLogoutAllOperationRepository logoutAllRepository, + AccountSecurityStateOperationRepository securityStateRepository) { + this.outboxRepository = + Objects.requireNonNull(outboxRepository, "Account authority outbox repository is required"); + this.passwordResetRepository = + Objects.requireNonNull( + passwordResetRepository, "Password-reset operation repository is required"); + this.logoutAllRepository = + Objects.requireNonNull(logoutAllRepository, "Logout-all operation repository is required"); + this.securityStateRepository = + Objects.requireNonNull( + securityStateRepository, "Security-state operation repository is required"); + } + + /** + * Proves the exact current Account source generation, source version and shared outbox + * checkpoint. Sequence zero is valid only for the original positive 1/1 source baseline and + * absent history. + */ + public LatestSourceSnapshot requireCurrentLatest(Account account, ScopeState current) { + requireAccountAssociation(account); + AuthorityScope expectedScope = AuthorityScope.account(account.getAccountUuid()); + if (current == null + || !expectedScope.equals(current.scope()) + || current.generation() <= 0L + || current.sourceVersion() <= 0L) { + throw new IllegalStateException("Account source authority scope or counters are invalid"); + } + requireCurrentFence(current.issuanceFence(), account.getAccountUuid()); + + String streamKey = streamKey(account.getAccountUuid()); + Optional checkpoint = outboxRepository.readCheckpoint(streamKey); + if (checkpoint.isEmpty()) { + if (current.generation() != 1L || current.sourceVersion() != 1L) { + throw new IllegalStateException( + "Account source sequence zero is not the original positive 1/1 baseline"); + } + return new LatestSourceSnapshot(0L, Optional.empty()); + } + + Checkpoint latestCheckpoint = checkpoint.orElseThrow(); + if (current.generation() == 1L && current.sourceVersion() == 1L) { + throw new IllegalStateException("Pristine Account source has contradictory event history"); + } + if (current.generation() <= 1L || current.sourceVersion() <= 1L) { + throw new IllegalStateException("Account source history is not proven"); + } + // The latest closed receipt cannot make an earlier generic Account mutation authoritative. + // Retain generic history for inspection elsewhere, but fail closed for currentness until every + // event in this stream has the closed operation-specific receipt/readback contract. + for (long sequence = 1L; sequence < latestCheckpoint.outboxSequence(); sequence++) { + Event retainedEvent = + outboxRepository + .findEvent(streamKey, sequence) + .orElseThrow( + () -> new IllegalStateException("Retained Account source event is missing")); + requireRetainedEvent(account, retainedEvent, current); + } + Event latestEvent = + outboxRepository + .findEvent(streamKey, latestCheckpoint.outboxSequence()) + .orElseThrow(() -> new IllegalStateException("Latest Account source event is missing")); + requireCheckpointMatches(latestCheckpoint, latestEvent); + VerifiedSourceEvent verified = verifyEvent(latestEvent, account.getAccountUuid()); + if (!Long.toString(current.generation()).equals(verified.accountAuthorityGeneration()) + || !Long.toString(current.sourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException( + "Latest Account source event does not match its current generation and source version"); + } + + if (verified.passwordReset().isPresent()) { + PasswordResetReceipt receipt = + passwordResetRepository + .findByRequestId(verified.requestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Latest Account password-reset event has no immutable operation receipt")); + requirePasswordResetReceipt(account, receipt, latestEvent, verified, current); + } else if (verified.securityState().isPresent()) { + requireSecurityStateReceipt(account, latestEvent, verified, current, true); + } else { + UUID requestId = parseLogoutAllRequestId(verified.requestId()); + LogoutAllReceipt receipt = + logoutAllRepository + .findByRequestId(requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Latest Account logout-all event has no immutable operation receipt")); + requireLogoutAllReceipt(account, receipt, latestEvent, verified, current); + } + return new LatestSourceSnapshot(latestEvent.outboxSequence(), Optional.of(latestEvent)); + } + + /** Validates one retained logout-all receipt after the account stream has advanced further. */ + public void requireLogoutAllReceiptRetained( + Account account, LogoutAllReceipt receipt, Event event, ScopeState current) { + requireAccountAssociation(account); + if (current == null + || !AuthorityScope.account(account.getAccountUuid()).equals(current.scope())) { + throw new IllegalStateException("Logout-all current Account source scope is invalid"); + } + requireCurrentFence(current.issuanceFence(), account.getAccountUuid()); + VerifiedSourceEvent verified = verifyEvent(event, account.getAccountUuid()); + requireLogoutAllReceipt(account, receipt, event, verified, current); + if (event.outboxSequence() > currentSourceSequence(account)) { + throw new IllegalStateException( + "Logout-all operation event is ahead of its source checkpoint"); + } + } + + /** + * Validates one selected immutable Account event and its receipt against the current local + * authority fence. Historical password-reset evidence deliberately does not prove that the old + * password verifier remains current or make that reset operation recoverable. + */ + public RetainedEventEvidence requireRetainedEvent( + Account account, Event event, ScopeState current) { + requireAccountAssociation(account); + if (current == null + || !AuthorityScope.account(account.getAccountUuid()).equals(current.scope()) + || current.generation() <= 0L + || current.sourceVersion() <= 0L) { + throw new IllegalStateException("Retained Account source authority state is invalid"); + } + requireCurrentFence(current.issuanceFence(), account.getAccountUuid()); + VerifiedSourceEvent verified = verifyEvent(event, account.getAccountUuid()); + if (event.outboxSequence() > currentSourceSequence(account)) { + throw new IllegalStateException("Selected Account source event is ahead of its checkpoint"); + } + + if (verified.passwordReset().isPresent()) { + PasswordResetReceipt receipt = + passwordResetRepository + .findByRequestId(verified.requestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account password-reset event has no immutable operation receipt")); + requirePasswordResetReceiptBinding(account, receipt, event, verified, current); + return retainedEvidence( + event, verified, receipt.issuanceFence(), receipt.issuanceFenceSourceVersion()); + } + + if (verified.securityState().isPresent()) { + var operation = + securityStateRepository + .findCommittedByRequestIdShared(UUID.fromString(verified.requestId())) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account security-state event has no immutable operation receipt")); + var receipt = + operation + .receipt() + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account security-state operation is not COMMITTED")); + requireSecurityStateReceipt(account, event, verified, current, false); + return retainedEvidence( + event, + verified, + receipt.sourceState().issuanceFence().value(), + receipt.sourceState().issuanceFence().sourceVersion()); + } + UUID requestId = parseLogoutAllRequestId(verified.requestId()); + LogoutAllReceipt receipt = + logoutAllRepository + .findByRequestId(requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account logout-all event has no immutable operation receipt")); + requireLogoutAllReceipt(account, receipt, event, verified, current); + return retainedEvidence( + event, verified, receipt.issuanceFence(), receipt.issuanceFenceSourceVersion()); + } + + private RetainedEventEvidence retainedEvidence( + Event event, VerifiedSourceEvent verified, long issuanceFence, long fenceSourceVersion) { + return new RetainedEventEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + Long.parseLong(verified.accountAuthorityGeneration()), + Long.parseLong(verified.sourceVersion()), + issuanceFence, + fenceSourceVersion, + verified.accountSecurityCutoff()); + } + + private long currentSourceSequence(Account account) { + return outboxRepository + .readCheckpoint(streamKey(account.getAccountUuid())) + .map(Checkpoint::outboxSequence) + .orElse(0L); + } + + private void requireSecurityStateReceipt( + Account account, + Event event, + VerifiedSourceEvent verified, + ScopeState current, + boolean latest) { + var operation = + securityStateRepository + .findCommittedByRequestIdShared(UUID.fromString(verified.requestId())) + .orElseThrow( + () -> + new IllegalStateException( + "Account security-state event has no immutable operation receipt")); + var receipt = + operation + .receipt() + .orElseThrow( + () -> + new IllegalStateException("Account security-state operation is not COMMITTED")); + if (!operation.request().accountUuid().equals(account.getAccountUuid()) + || operation.capture().accountId() != account.getId() + || operation.capture().provenance() != account.getAccountUuidProvenance() + || !receipt.event().equals(event)) { + throw new IllegalStateException("Account security-state operation association/event differs"); + } + requireReceiptNotAhead( + receipt.sourceState().generation(), + receipt.sourceState().sourceVersion(), + receipt.sourceState().issuanceFence().value(), + receipt.sourceState().issuanceFence().sourceVersion(), + current, + "Security-state"); + if (latest) securityStateRepository.requireCurrentPostState(operation, current); + } + + private void requirePasswordResetReceipt( + Account account, + PasswordResetReceipt receipt, + Event event, + VerifiedSourceEvent verified, + ScopeState current) { + requirePasswordResetReceiptBinding(account, receipt, event, verified, current); + requireCurrentPasswordVerifier(account, receipt); + } + + private void requirePasswordResetReceiptBinding( + Account account, + PasswordResetReceipt receipt, + Event event, + VerifiedSourceEvent verified, + ScopeState current) { + if (receipt.accountId() != account.getId() + || !account.getAccountUuid().equals(receipt.accountUuid()) + || !PASSWORD_RESET_OPERATION_KIND.equals(receipt.operationKind()) + || receipt.requestDigestVersion() != 1 + || !streamKey(account.getAccountUuid()).equals(receipt.outboxStreamKey()) + || receipt.outboxSequence() != event.outboxSequence() + || !receipt.requestId().equals(event.requestId()) + || !receipt.eventId().equals(event.eventId()) + || !receipt.eventDigest().equals(event.eventDigest()) + || !receipt.eventId().equals(PASSWORD_RESET_EVENT_ID_PREFIX + receipt.tokenHash()) + || !receipt.requestId().equals(PASSWORD_RESET_REQUEST_ID_PREFIX + receipt.tokenHash()) + || !Long.toString(receipt.accountAuthorityGeneration()) + .equals(verified.accountAuthorityGeneration()) + || !Long.toString(receipt.accountSourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException( + "Latest Account password-reset receipt does not match its source event"); + } + String expectedDigest = + passwordResetRequestDigest( + receipt.accountUuid(), + receipt.tokenHash(), + receipt.tokenExpiresAt().toString(), + receipt.passwordVerifierDigest()); + if (!constantTimeTextEquals(expectedDigest, receipt.requestDigest())) { + throw new IllegalStateException( + "Latest Account password-reset receipt request digest is inconsistent"); + } + requireReceiptNotAhead( + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion(), + current, + "Password-reset"); + } + + private void requireCurrentPasswordVerifier(Account account, PasswordResetReceipt receipt) { + String currentVerifier = account.getPasswordHash(); + if (currentVerifier == null + || currentVerifier.isBlank() + || !constantTimeTextEquals(sha256Hex(currentVerifier), receipt.passwordVerifierDigest())) { + throw new IllegalStateException( + "Latest Account password-reset event does not match the current password verifier"); + } + } + + private void requireLogoutAllReceipt( + Account account, + LogoutAllReceipt receipt, + Event event, + VerifiedSourceEvent verified, + ScopeState current) { + UUID requestId = parseLogoutAllRequestId(verified.requestId()); + if (!requestId.toString().equals(verified.requestId()) + || !requestId.equals(receipt.requestId()) + || receipt.accountId() != account.getId() + || !account.getAccountUuid().equals(receipt.accountUuid()) + || !LOGOUT_ALL_OPERATION_KIND.equals(receipt.operationKind()) + || receipt.requestDigestVersion() != 1 + || !receipt.lifecycleResult().equals(LOGOUT_ALL_RESULT) + || !streamKey(account.getAccountUuid()).equals(receipt.outboxStreamKey()) + || receipt.outboxSequence() != event.outboxSequence() + || !receipt.requestId().toString().equals(event.requestId()) + || !receipt.eventId().equals(event.eventId()) + || !receipt.eventDigest().equals(event.eventDigest()) + || !receipt.eventId().equals(LOGOUT_ALL_EVENT_ID_PREFIX + receipt.requestId()) + || !Long.toString(receipt.accountAuthorityGeneration()) + .equals(verified.accountAuthorityGeneration()) + || !Long.toString(receipt.accountSourceVersion()).equals(verified.sourceVersion())) { + throw new IllegalStateException("Latest Account logout-all receipt does not match its event"); + } + String expectedRequestDigest = + AccountLogoutRequestDigest.accountLogoutAll( + receipt.accountUuid(), receipt.tokenProfile(), receipt.presentedTokenHash()); + if (!constantTimeTextEquals(expectedRequestDigest, receipt.requestDigest())) { + throw new IllegalStateException( + "Account logout-all receipt request digest does not match its immutable caller bindings"); + } + requireReceiptNotAhead( + receipt.accountAuthorityGeneration(), + receipt.accountSourceVersion(), + receipt.issuanceFence(), + receipt.issuanceFenceSourceVersion(), + current, + "Logout-all"); + } + + private UUID parseLogoutAllRequestId(String requestIdText) { + UUID requestId; + try { + requestId = UUID.fromString(requestIdText); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Logout-all source request ID is malformed", exception); + } + if (!requestId.toString().equals(requestIdText)) { + throw new IllegalStateException("Logout-all source request ID is not canonical"); + } + return requestId; + } + + private static VerifiedSourceEvent verifyEvent(Event event, UUID accountUuid) { + if (event == null) throw new IllegalStateException("Account source event is missing"); + String payload = new String(event.payload(), StandardCharsets.UTF_8); + try { + JsonNode tree = SNAPSHOT_JSON.readTree(payload); + if (tree == null || !tree.isObject() || !tree.path("schemaVersion").isTextual()) { + throw new IllegalStateException("Account source event schema is missing"); + } + return switch (tree.path("schemaVersion").textValue()) { + case PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION -> { + var reset = PasswordResetAuthorityEventV1Codec.verify(payload); + requireEventBinding( + event, + accountUuid, + reset.accountId(), + reset.requestId(), + reset.eventId(), + reset.eventDigest(), + reset.outboxStreamKey(), + reset.outboxSequence(), + reset.canonicalJsonUtf8()); + yield VerifiedSourceEvent.passwordReset(reset); + } + case AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION -> { + var logout = AccountLogoutAllAuthorityEventV1Codec.verify(payload); + requireEventBinding( + event, + accountUuid, + logout.accountId(), + logout.requestId(), + logout.eventId(), + logout.eventDigest(), + logout.outboxStreamKey(), + logout.outboxSequence(), + logout.canonicalJsonUtf8()); + yield VerifiedSourceEvent.logoutAll(logout); + } + case AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION -> { + var security = AccountSecurityStateAuthorityEventV1Codec.verify(payload); + requireEventBinding( + event, + accountUuid, + security.accountId(), + security.requestId(), + security.eventId(), + security.eventDigest(), + security.outboxStreamKey(), + security.outboxSequence(), + security.canonicalJsonUtf8()); + yield VerifiedSourceEvent.securityState(security); + } + default -> throw new IllegalStateException("Account source event schema is unsupported"); + }; + } catch (IOException | IllegalArgumentException invalid) { + throw new IllegalStateException("Account source event is invalid", invalid); + } + } + + private static void requireEventBinding( + Event event, + UUID accountUuid, + String accountId, + String requestId, + String eventId, + String digest, + String stream, + String sequence, + byte[] canonical) { + if (!MessageDigest.isEqual(event.payload(), canonical) + || !accountUuid.toString().equals(accountId) + || !event.requestId().equals(requestId) + || !event.eventId().equals(eventId) + || !event.eventDigest().equals(digest) + || !event.outboxStreamKey().equals(stream) + || !Long.toString(event.outboxSequence()).equals(sequence)) { + throw new IllegalStateException("Account source event readback is inconsistent"); + } + } + + /** Structural binding only; owner receipt proof is checked separately. */ + static void requireEventMatchesSnapshot( + Event event, UUID accountUuid, ScopeState current, boolean mustBeCurrentLatest) { + if (accountUuid == null + || current == null + || !AuthorityScope.account(accountUuid).equals(current.scope()) + || current.generation() <= 0L + || current.sourceVersion() <= 0L) { + throw new IllegalStateException("Account source snapshot scope or counters are invalid"); + } + SnapshotCounters verified = verifySnapshotEvent(event, accountUuid); + BigInteger eventGeneration = new BigInteger(verified.accountAuthorityGeneration()); + BigInteger eventSourceVersion = new BigInteger(verified.sourceVersion()); + BigInteger currentGeneration = BigInteger.valueOf(current.generation()); + BigInteger currentSourceVersion = BigInteger.valueOf(current.sourceVersion()); + boolean countersMatch = + mustBeCurrentLatest + ? eventGeneration.equals(currentGeneration) + && eventSourceVersion.equals(currentSourceVersion) + : eventGeneration.compareTo(currentGeneration) <= 0 + && eventSourceVersion.compareTo(currentSourceVersion) <= 0; + if (!countersMatch) { + throw new IllegalStateException( + "Account source event counters contradict or lead the current snapshot"); + } + } + + private static SnapshotCounters verifySnapshotEvent(Event event, UUID accountUuid) { + VerifiedSourceEvent verified = verifyEvent(event, accountUuid); + return new SnapshotCounters(verified.accountAuthorityGeneration(), verified.sourceVersion()); + } + + private record SnapshotCounters(String accountAuthorityGeneration, String sourceVersion) {} + + private void requireReceiptNotAhead( + long generation, + long sourceVersion, + long fence, + long fenceSourceVersion, + ScopeState current, + String operation) { + IssuanceFence currentFence = current.issuanceFence(); + if (generation > current.generation() + || sourceVersion > current.sourceVersion() + || fence > currentFence.value() + || fenceSourceVersion > currentFence.sourceVersion()) { + throw new IllegalStateException(operation + " receipt is ahead of current Account authority"); + } + } + + private void requireCurrentFence(IssuanceFence fence, UUID accountUuid) { + if (fence == null + || !accountUuid.equals(fence.accountId()) + || fence.value() <= 0L + || fence.sourceVersion() <= 0L) { + throw new IllegalStateException("Account source issuance fence is missing or invalid"); + } + } + + private void requireAccountAssociation(Account account) { + AccountIdentityProvenance provenance = + account == null ? null : account.getAccountUuidProvenance(); + if (account == null + || account.getId() == null + || account.getId() <= 0L + || account.getAccountUuid() == null + || new UUID(0L, 0L).equals(account.getAccountUuid()) + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION + && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT)) { + throw new IllegalStateException("Verified persisted Account association is required"); + } + } + + private void requireCheckpointMatches(Checkpoint checkpoint, Event event) { + if (!checkpoint.outboxStreamKey().equals(event.outboxStreamKey()) + || checkpoint.outboxSequence() != event.outboxSequence() + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest())) { + throw new IllegalStateException("Account source checkpoint differs from its latest event"); + } + } + + private String streamKey(UUID accountUuid) { + return STREAM_PREFIX + accountUuid; + } + + private String passwordResetRequestDigest( + UUID accountUuid, String tokenHash, String tokenExpiresAt, String verifierDigest) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + updateLengthPrefixed(digest, PASSWORD_RESET_REQUEST_DOMAIN); + updateLengthPrefixed(digest, PASSWORD_RESET_OPERATION_KIND); + updateLengthPrefixed(digest, accountUuid.toString()); + updateLengthPrefixed(digest, tokenHash); + updateLengthPrefixed(digest, tokenExpiresAt); + updateLengthPrefixed(digest, verifierDigest); + return HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private void updateLengthPrefixed(MessageDigest digest, String value) { + if (value == null) { + throw new IllegalArgumentException("Password-reset request field is required"); + } + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } + + private String sha256Hex(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private boolean constantTimeTextEquals(String left, String right) { + return left != null + && right != null + && MessageDigest.isEqual( + left.getBytes(StandardCharsets.US_ASCII), right.getBytes(StandardCharsets.US_ASCII)); + } + + /** Current exact source checkpoint; empty event is legal only for the proven 1/1 baseline. */ + public record LatestSourceSnapshot(long outboxSequence, Optional latestEvent) { + public LatestSourceSnapshot { + latestEvent = Objects.requireNonNull(latestEvent, "latest source event optional is required"); + if (outboxSequence < 0L + || (outboxSequence == 0L && latestEvent.isPresent()) + || (outboxSequence > 0L + && (latestEvent.isEmpty() + || latestEvent.orElseThrow().outboxSequence() != outboxSequence))) { + throw new IllegalArgumentException("Account latest source snapshot is inconsistent"); + } + } + } + + /** Exact closed-schema source counters and cutoff returned only after receipt validation. */ + public record RetainedEventEvidence( + String outboxStreamKey, + long outboxSequence, + long accountAuthorityGeneration, + long sourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + AccountSecurityCutoff accountSecurityCutoff) { + public RetainedEventEvidence { + if (outboxStreamKey == null + || outboxSequence <= 0L + || accountAuthorityGeneration <= 0L + || sourceVersion <= 0L + || issuanceFence != accountAuthorityGeneration + || issuanceFenceSourceVersion != sourceVersion + || accountSecurityCutoff == null + || !outboxStreamKey.equals(accountSecurityCutoff.outboxStreamKey()) + || outboxSequence != Long.parseLong(accountSecurityCutoff.outboxSequence()) + || accountAuthorityGeneration + != Long.parseLong(accountSecurityCutoff.accountAuthorityGeneration())) { + throw new IllegalArgumentException("Retained Account source evidence is inconsistent"); + } + } + } + + private record VerifiedSourceEvent( + String requestId, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + Optional passwordReset, + Optional + securityState) { + private static VerifiedSourceEvent passwordReset(PasswordResetAuthorityEvent event) { + return new VerifiedSourceEvent( + event.requestId(), + event.accountAuthorityGeneration(), + event.sourceVersion(), + new AccountSecurityCutoff( + event.accountSecurityCutoff().accountAuthorityGeneration(), + event.accountSecurityCutoff().outboxStreamKey(), + event.accountSecurityCutoff().outboxSequence()), + Optional.of(event), + Optional.empty()); + } + + private static VerifiedSourceEvent logoutAll(AccountLogoutAllAuthorityEvent event) { + return new VerifiedSourceEvent( + event.requestId(), + event.accountAuthorityGeneration(), + event.sourceVersion(), + new AccountSecurityCutoff( + event.accountSecurityCutoff().accountAuthorityGeneration(), + event.accountSecurityCutoff().outboxStreamKey(), + event.accountSecurityCutoff().outboxSequence()), + Optional.empty(), + Optional.empty()); + } + + private static VerifiedSourceEvent securityState( + AccountSecurityStateAuthorityEventV1Codec.AccountSecurityStateAuthorityEvent event) { + return new VerifiedSourceEvent( + event.requestId(), + event.accountAuthorityGeneration(), + event.sourceVersion(), + new AccountSecurityCutoff( + event.accountSecurityCutoff().accountAuthorityGeneration(), + event.accountSecurityCutoff().outboxStreamKey(), + event.accountSecurityCutoff().outboxSequence()), + Optional.empty(), + Optional.of(event)); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java new file mode 100644 index 0000000000..104217fe25 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java @@ -0,0 +1,237 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired owner-local reader for current and selected historical Account authority source events. + * Returned source evidence is not recipient authority. + */ +public final class AccountAuthoritySourceReader { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String ACCOUNT_STREAM_PREFIX = "account:auth-authority:v1:account/"; + + private final AccountRepository accountRepository; + private final AccountAuthorityGenerationRepository generationRepository; + private final AccountAuthorityOutboxRepository outboxRepository; + private final AccountAuthoritySourceEventReadback sourceEventReadback; + private final TransactionTemplate ownerTransaction; + + public AccountAuthoritySourceReader( + AccountRepository accountRepository, + AccountAuthorityGenerationRepository generationRepository, + AccountAuthorityOutboxRepository outboxRepository, + AccountAuthoritySourceEventReadback sourceEventReadback, + PlatformTransactionManager transactionManager) { + this.accountRepository = + Objects.requireNonNull(accountRepository, "Account repository is required"); + this.generationRepository = + Objects.requireNonNull(generationRepository, "authority generation repository is required"); + this.outboxRepository = + Objects.requireNonNull(outboxRepository, "authority outbox repository is required"); + this.sourceEventReadback = + Objects.requireNonNull(sourceEventReadback, "source event readback is required"); + + this.ownerTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** Reads the current positive Account source and its exact latest event, if one exists. */ + public AccountSourceSnapshot readCurrent(UUID accountId) { + requireCanonicalAccountId(accountId); + requireNoAmbientTransaction(); + return requireTransactionResult( + ownerTransaction.execute( + status -> readCurrentSnapshot(loadLockedAccount(accountId), accountId))); + } + + /** + * Reads one positive immutable event from this Account stream together with the current source + * snapshot that fences its use. + */ + public AccountSourceEventReadback readCommittedEvent(UUID accountId, long outboxSequence) { + requireCanonicalAccountId(accountId); + if (outboxSequence <= 0L) { + throw new IllegalArgumentException("A positive Account source event sequence is required"); + } + requireNoAmbientTransaction(); + return requireTransactionResult( + ownerTransaction.execute( + status -> { + Account account = loadLockedAccount(accountId); + AccountSourceSnapshot current = readCurrentSnapshot(account, accountId); + if (outboxSequence > current.outboxSequence()) { + throw new IllegalStateException( + "Selected Account source event is ahead of its current checkpoint"); + } + Event requested = + outboxRepository + .findEvent(current.outboxStreamKey(), outboxSequence) + .orElseThrow( + () -> + new IllegalStateException( + "Selected Account source event is missing")); + if (!current.outboxStreamKey().equals(requested.outboxStreamKey()) + || requested.outboxSequence() != outboxSequence) { + throw new IllegalStateException( + "Selected Account source event identity changed during readback"); + } + sourceEventReadback.requireRetainedEvent(account, requested, current.sourceState()); + return new AccountSourceEventReadback(current, requested); + })); + } + + private AccountSourceSnapshot readCurrentSnapshot(Account account, UUID accountId) { + AuthorityScope scope = AuthorityScope.account(accountId); + ScopeState state = generationRepository.read(scope); + if (state == null || !scope.equals(state.scope())) { + throw new IllegalStateException("Current Account authority scope changed during readback"); + } + AccountAuthoritySourceEventReadback.LatestSourceSnapshot latest = + sourceEventReadback.requireCurrentLatest(account, state); + return new AccountSourceSnapshot( + accountId, + state, + accountStreamKey(accountId), + latest.outboxSequence(), + latest.latestEvent()); + } + + private Account loadLockedAccount(UUID accountId) { + Account associated = + accountRepository + .findByAccountUuid(accountId) + .orElseThrow( + () -> new IllegalStateException("Persisted Account UUID association is missing")); + requirePersistedAssociation(associated, accountId); + + Account locked = + accountRepository + .findByIdForUpdate(associated.getId()) + .orElseThrow( + () -> new IllegalStateException("Persisted Account source row is missing")); + requirePersistedAssociation(locked, accountId); + if (!Objects.equals(associated.getId(), locked.getId()) + || !Objects.equals(associated.getAccountUuid(), locked.getAccountUuid()) + || associated.getAccountUuidProvenance() != locked.getAccountUuidProvenance() + || !Objects.equals( + associated.getAccountUuidSourceNumericId(), locked.getAccountUuidSourceNumericId())) { + throw new IllegalStateException( + "Locked Account row changed its exact UUID association or provenance"); + } + return locked; + } + + private void requirePersistedAssociation(Account account, UUID accountId) { + AccountIdentityProvenance provenance = + account == null ? null : account.getAccountUuidProvenance(); + if (account == null + || account.getId() == null + || account.getId() <= 0L + || !accountId.equals(account.getAccountUuid()) + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId()) + || (provenance != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + && provenance != AccountIdentityProvenance.ACCOUNT_V29_MIGRATION + && provenance != AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT)) { + throw new IllegalStateException("Verified persisted Account association is required"); + } + } + + private static void requireCanonicalAccountId(UUID accountId) { + if (accountId == null || NIL_UUID.equals(accountId)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account authority source reader must own its transaction without an ambient transaction"); + } + } + + private static T requireTransactionResult(T result) { + if (result == null) { + throw new IllegalStateException("Account authority source readback returned no result"); + } + return result; + } + + private static String accountStreamKey(UUID accountId) { + return ACCOUNT_STREAM_PREFIX + accountId; + } + + /** Immutable current owner-local source snapshot; it carries no credential or recipient tuple. */ + public record AccountSourceSnapshot( + UUID accountId, + ScopeState sourceState, + String outboxStreamKey, + long outboxSequence, + Optional latestEvent) { + public AccountSourceSnapshot { + requireCanonicalAccountId(accountId); + Objects.requireNonNull(sourceState, "Account source state is required"); + Objects.requireNonNull(outboxStreamKey, "Account source stream key is required"); + latestEvent = Objects.requireNonNull(latestEvent, "latest source event optional is required"); + AuthorityScope expectedScope = AuthorityScope.account(accountId); + if (!expectedScope.equals(sourceState.scope()) + || sourceState.generation() <= 0L + || sourceState.sourceVersion() <= 0L + || !outboxStreamKey.equals(accountStreamKey(accountId)) + || sourceState.issuanceFence() == null + || !accountId.equals(sourceState.issuanceFence().accountId()) + || sourceState.issuanceFence().value() <= 0L + || sourceState.issuanceFence().sourceVersion() <= 0L + || outboxSequence < 0L + || (outboxSequence == 0L + && (sourceState.generation() != 1L + || sourceState.sourceVersion() != 1L + || latestEvent.isPresent())) + || (outboxSequence > 0L + && (sourceState.generation() <= 1L + || sourceState.sourceVersion() <= 1L + || latestEvent.isEmpty() + || latestEvent.orElseThrow().outboxSequence() != outboxSequence + || !outboxStreamKey.equals(latestEvent.orElseThrow().outboxStreamKey())))) { + throw new IllegalArgumentException("Account source snapshot is inconsistent"); + } + latestEvent.ifPresent( + event -> + AccountAuthoritySourceEventReadback.requireEventMatchesSnapshot( + event, accountId, sourceState, true)); + } + } + + /** Immutable selected event paired with the current Account source fence. */ + public record AccountSourceEventReadback( + AccountSourceSnapshot currentSnapshot, Event requestedEvent) { + public AccountSourceEventReadback { + Objects.requireNonNull(currentSnapshot, "current Account source snapshot is required"); + Objects.requireNonNull(requestedEvent, "selected Account source event is required"); + if (requestedEvent.outboxSequence() <= 0L + || requestedEvent.outboxSequence() > currentSnapshot.outboxSequence() + || !currentSnapshot.outboxStreamKey().equals(requestedEvent.outboxStreamKey())) { + throw new IllegalArgumentException("Selected Account source event is inconsistent"); + } + AccountAuthoritySourceEventReadback.requireEventMatchesSnapshot( + requestedEvent, currentSnapshot.accountId(), currentSnapshot.sourceState(), false); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java new file mode 100644 index 0000000000..68e9ffe342 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReader.java @@ -0,0 +1,258 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayPublicAdmissionSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountLifecyclePendingDenialReader; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, read-only-in-purpose SQL source composition for public fresh NON_PAID_DEMO work. + * + *

The caller must already own a writable Account transaction at REPEATABLE_READ or SERIALIZABLE + * isolation. The membership reader supplies the first Account lock. This reader does not create a + * transaction, write state, authenticate a caller or token, validate a signature or token registry, + * establish Account safety restrictions, World ACTIVE, routing, coordination, grant, or deadline + * evidence, decide admission, or issue or commit an admission lease. Current SQL token-fence state + * and Account lifecycle are only captured sources, not complete token authority or admission. + */ +public final class AccountGameplayPublicAdmissionSourceReader { + private final AccountMembershipRoleSourceReader membershipSources; + private final AccountRepository accounts; + private final AccountDemoTenantEntitlementRepository entitlements; + private final AccountGameplayTokenIdentityFenceRepository tokenFences; + private final AccountLifecyclePendingDenialReader lifecyclePendingDenials; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Account owner sources are private transaction collaborators.") + public AccountGameplayPublicAdmissionSourceReader( + AccountMembershipRoleSourceReader membershipSources, + AccountRepository accounts, + AccountDemoTenantEntitlementRepository entitlements, + AccountGameplayTokenIdentityFenceRepository tokenFences, + AccountLifecyclePendingDenialReader lifecyclePendingDenials) { + this.membershipSources = Objects.requireNonNull(membershipSources); + this.accounts = Objects.requireNonNull(accounts); + this.entitlements = Objects.requireNonNull(entitlements); + this.tokenFences = Objects.requireNonNull(tokenFences); + this.lifecyclePendingDenials = Objects.requireNonNull(lifecyclePendingDenials); + } + + /** Captures exact Account owner sources under the caller's existing serialized transaction. */ + public AccountGameplayPublicAdmissionSourceSnapshot readCurrent( + UUID accountId, UUID tenantId, TokenIdentity identity) { + requireUuid(accountId, "account"); + requireUuid(tenantId, "tenant"); + Objects.requireNonNull(identity, "Exact committed token identity is required"); + if (!accountId.equals(identity.accountId())) { + throw new IllegalArgumentException("Token identity account differs from the exact account"); + } + requireWritableOwnerTransaction(); + + // This owner read establishes the Account-first lock order and the membership snapshot. + AccountMembershipRoleSourceSnapshot membership = + membershipSources.readCurrent(accountId, tenantId); + requireMembership(membership, accountId, tenantId, identity); + lifecyclePendingDenials.requireNoPending(accountId, tenantId); + Account account = + accounts + .findByAccountUuid(accountId) + .orElseThrow(AccountGameplayPublicAdmissionSourceReader::accountSourceUnavailable); + AccountLifecycleState accountLifecycleState = + requireAccountIdentityAndActiveLifecycle(account, membership, accountId); + + DemoTenantEntitlementSnapshot evaluated = entitlements.readCurrent(tenantId); + require(evaluated != null, "Current demo entitlement source is unavailable"); + DemoTenantEntitlementSnapshot current = entitlements.revalidate(evaluated); + require( + current != null && current.equals(evaluated), + "Revalidated demo entitlement source is unavailable or changed"); + requireEntitlement(membership, current, tenantId); + + AccountGameplayTokenIdentityFence tokenFence = tokenFences.requireActiveForUpdate(identity); + require( + tokenFence != null + && identity.equals(tokenFence.identity()) + && tokenFence.state() == State.ACTIVE, + "Exact Account SQL token identity is not active"); + + return new AccountGameplayPublicAdmissionSourceSnapshot( + membership, accountLifecycleState, current, tokenFence); + } + + private static AccountLifecycleState requireAccountIdentityAndActiveLifecycle( + Account account, AccountMembershipRoleSourceSnapshot membership, UUID accountId) { + var member = membership.membership(); + var accountSource = membership.issuerAccountSources().account(); + require( + accountId.equals(account.getAccountUuid()) + && account.getId() != null + && account.getId() > 0L + && account.getId() == member.accountRowId() + && Objects.equals(account.getId(), accountSource.accountSourceNumericId()) + && account.getAccountUuidProvenance() + == AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + && account.getAccountUuidProvenance() == member.accountIdentityProvenance() + && AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + .name() + .equals(accountSource.accountUuidProvenance()) + && account.getAccountUuidSourceNumericId() != null + && account.getAccountUuidSourceNumericId().equals(account.getId()) + && account.getAccountUuidSourceNumericId() == member.accountSourceNumericId(), + "Current Account lifecycle source is unavailable or inconsistent"); + AccountLifecycleState lifecycleState = account.getLifecycleState(); + require( + lifecycleState == AccountLifecycleState.ACTIVE, + "Current Account lifecycle does not allow gameplay admission"); + return lifecycleState; + } + + private static IllegalStateException accountSourceUnavailable() { + return new IllegalStateException( + "Current Account lifecycle source is unavailable or inconsistent"); + } + + private static void requireMembership( + AccountMembershipRoleSourceSnapshot snapshot, + UUID accountId, + UUID tenantId, + TokenIdentity identity) { + require(snapshot != null, "Current membership source is unavailable"); + var member = snapshot.membership(); + require( + accountId.equals(member.accountId()) + && tenantId.equals(member.tenantId()) + && "ACTIVE".equals(member.lifecycleState()) + && member.gameplayAdmissionAllowed(), + "Current Account membership does not allow gameplay admission"); + require( + snapshot.roles().roles().contains("player") + && snapshot.roles().accountUuid() != null + && accountId.equals(snapshot.roles().accountUuid()) + && tenantId.equals(snapshot.roles().tenantUuid()) + && snapshot.roles().membershipId() == member.membershipId() + && snapshot.roles().snapshotVersion() == member.membershipVersion(), + "Current Account membership has no exact player role source"); + require( + accountId.equals(snapshot.issuerAccountSources().issuanceFence().accountId()) + && snapshot + .currentAuthority() + .issuanceFence() + .equals(snapshot.issuerAccountSources().issuanceFence()) + && snapshot.issuerAccountSources().issuanceFence().value() == identity.issuanceFence(), + "Current Account issuance fence differs from the exact token identity"); + require( + tenantId.equals(snapshot.tenantSource().tenantId()) + && tenantId.equals(snapshot.pair().tenantUuid()) + && accountId.equals(snapshot.pair().accountUuid()) + && snapshot.pair().provenance().equals(member.tenantProvenance()) + && snapshot.pair().provenance().equals(snapshot.roles().tenantProvenance()) + && tenantId.toString().equals(snapshot.membershipEvent().tenantId()) + && accountId.toString().equals(snapshot.membershipEvent().accountId()) + && snapshot.currentAuthority().tenants().size() == 1 + && snapshot.currentAuthority().memberships().size() == 1, + "Current Account membership source scope is inconsistent"); + var checkpoint = snapshot.membershipCheckpoint(); + var storedEvent = snapshot.storedMembershipEvent(); + var sourceEvent = snapshot.membershipEvent(); + require( + checkpoint.outboxStreamKey().equals(storedEvent.outboxStreamKey()) + && checkpoint.outboxSequence() == storedEvent.outboxSequence() + && checkpoint.sourceEventId().equals(storedEvent.eventId()) + && checkpoint.sourceEventDigest().equals(storedEvent.eventDigest()) + && snapshot.pair().eventSequence() == checkpoint.outboxSequence() + && snapshot.pair().eventId().equals(checkpoint.sourceEventId()) + && snapshot.pair().eventDigest().equals(checkpoint.sourceEventDigest()) + && sourceEvent.eventId().equals(storedEvent.eventId()) + && sourceEvent.eventDigest().equals(storedEvent.eventDigest()) + && sourceEvent.roles().equals(snapshot.roles().roles()) + && sourceEvent.membershipLifecycleState().equals(member.lifecycleState()) + && sourceEvent.gameplayAdmissionAllowed() == member.gameplayAdmissionAllowed(), + "Current Account membership event and checkpoint do not match the role snapshot"); + } + + private static void requireEntitlement( + AccountMembershipRoleSourceSnapshot membership, + DemoTenantEntitlementSnapshot entitlement, + UUID tenantId) { + var tenant = membership.tenantSource(); + var currentTenantAuthority = + membership.currentAuthority().tenants().stream() + .filter(state -> AuthorityScope.tenant(tenantId).equals(state.scope())) + .findFirst() + .orElse(null); + require( + currentTenantAuthority != null + && tenantId.equals(entitlement.canonicalTenantId()) + && "NEW_GAME_ROW".equals(entitlement.sourceEvidence().provenanceKind()) + && entitlement.sourceEvidence().equals(tenant.sourceEvidence()) + && membership.pair().provenance().kind() == TenantProvenanceKind.FRESH_GAME_DESIGN + && entitlement + .sourceEvidence() + .operationId() + .equals(membership.pair().provenance().sourceOperationId()) + && entitlement + .sourceEvidence() + .evidenceDigest() + .equals(membership.pair().provenance().digest()) + && entitlement.tenantAuthorityGeneration() == tenant.tenantAuthorityGeneration() + && entitlement.tenantAuthoritySourceVersion() == tenant.tenantAuthoritySourceVersion() + && currentTenantAuthority.generation() == tenant.tenantAuthorityGeneration() + && currentTenantAuthority.sourceVersion() == tenant.tenantAuthoritySourceVersion() + && entitlement.gameplayAvailable() + && entitlement.allowNewGameplayBindings(), + "Current public demo entitlement or fresh Game Design source is unavailable or denied"); + + require( + entitlement.tenantAuthorityOutboxStreamKey().equals(tenant.outboxStreamKey()) + && entitlement.tenantAuthorityOutboxSequence() == tenant.outboxSequence() + && entitlement.tenantAuthorityEventId().equals(tenant.eventId()) + && entitlement.tenantAuthorityEventDigest().equals(tenant.eventDigest()), + "Current demo entitlement differs from the tenant authority event checkpoint"); + require( + entitlement.outboxStreamKey().equals(tenant.tenantBillingStreamKey()) + && entitlement.tenantBillingSequence() == tenant.tenantBillingSequence() + && entitlement.eventId().equals(tenant.tenantBillingEventId()) + && entitlement.eventDigest().equals(tenant.tenantBillingEventDigest()), + "Current demo entitlement differs from the exact tenant billing receipt"); + } + + private static void requireWritableOwnerTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + require( + TransactionSynchronizationManager.isActualTransactionActive() + && !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + && (Objects.equals(isolation, TransactionDefinition.ISOLATION_REPEATABLE_READ) + || Objects.equals(isolation, TransactionDefinition.ISOLATION_SERIALIZABLE)), + "Writable Account REPEATABLE_READ or SERIALIZABLE transaction required"); + } + + private static void requireUuid(UUID value, String label) { + if (value == null + || value.equals(new UUID(0L, 0L)) + || value.version() != 4 + || value.variant() != 2) { + throw new IllegalArgumentException("Canonical non-nil v4 " + label + " UUID required"); + } + } + + private static void require(boolean valid, String message) { + if (!valid) throw new IllegalStateException(message); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java new file mode 100644 index 0000000000..3dcf25d099 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjection.java @@ -0,0 +1,355 @@ +package net.firedevops.firemud.accountservice.service; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.service.AccountAuthoritySourceReader.AccountSourceSnapshot; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountLogoutAllAuthorityEventV1Codec.AccountLogoutAllAuthorityEvent; +import net.firedevops.firemud.common.account.authority.AccountSecurityStateAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.PasswordResetAuthorityEventV1Codec.PasswordResetAuthorityEvent; + +/** Closed current-snapshot projection of one durable Account account-generation source. */ +public record AccountGenerationProjection( + String accountId, + String accountAuthorityGeneration, + String sourceVersion, + String outboxStreamKey, + String outboxSequence, + Optional sourceEvent) { + public static final String SCHEMA_VERSION = "account-auth-account-generation-projection/v1"; + public static final String KEY_PREFIX = "session:auth:generation:account:"; + private static final String STREAM_PREFIX = "account:auth-authority:v1:account/"; + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("0|[1-9][0-9]*"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final Set REQUIRED_FIELDS = + Set.of( + "schemaVersion", + "accountId", + "accountAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence"); + private static final Set ALL_FIELDS = + Set.of( + "schemaVersion", + "accountId", + "accountAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent"); + + public AccountGenerationProjection { + requireCanonicalAccountId(accountId); + requirePositiveDecimal(accountAuthorityGeneration, "accountAuthorityGeneration"); + requirePositiveDecimal(sourceVersion, "sourceVersion"); + requireNonNegativeDecimal(outboxSequence, "outboxSequence"); + if (!streamKeyForAccount(accountId).equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Account generation projection stream key is not canonical"); + } + sourceEvent = Objects.requireNonNull(sourceEvent, "sourceEvent optional is required"); + BigInteger sequence = new BigInteger(outboxSequence); + if (sequence.signum() == 0) { + if (!"1".equals(accountAuthorityGeneration) + || !"1".equals(sourceVersion) + || sourceEvent.isPresent()) { + throw new IllegalArgumentException( + "Account sequence zero requires the original 1/1 source baseline and no event"); + } + } else { + if (new BigInteger(accountAuthorityGeneration).compareTo(BigInteger.ONE) <= 0 + || new BigInteger(sourceVersion).compareTo(BigInteger.ONE) <= 0 + || sourceEvent.isEmpty()) { + throw new IllegalArgumentException( + "Positive Account source sequence requires advanced counters and its exact event"); + } + validateSourceEvent( + sourceEvent.orElseThrow(), + accountId, + accountAuthorityGeneration, + sourceVersion, + outboxStreamKey, + outboxSequence); + } + } + + /** Builds projection evidence only from Account's owner-local current durable readback. */ + public static AccountGenerationProjection fromSource(AccountSourceSnapshot source) { + Objects.requireNonNull(source, "Account source snapshot is required"); + AuthorityScope scope = source.sourceState().scope(); + if (scope.kind() != ScopeKind.ACCOUNT || !source.accountId().equals(scope.accountId())) { + throw new IllegalArgumentException("Account source snapshot has a different authority scope"); + } + Optional event = + source.latestEvent().map(AccountGenerationProjection::decodeCanonicalEvent); + return new AccountGenerationProjection( + source.accountId().toString(), + Long.toString(source.sourceState().generation()), + Long.toString(source.sourceState().sourceVersion()), + source.outboxStreamKey(), + Long.toString(source.outboxSequence()), + event); + } + + /** + * Parses the closed wire shape and rejects noncanonical JSON and all alternate representations. + */ + public static AccountGenerationProjection parse(String json) { + Objects.requireNonNull(json, "projection JSON is required"); + final JsonNode root; + try { + root = JSON.readTree(json); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Account generation projection JSON is malformed", exception); + } + if (!(root instanceof ObjectNode object)) { + throw new IllegalArgumentException("Account generation projection must be a JSON object"); + } + Set fields = new HashSet<>(); + object.fieldNames().forEachRemaining(fields::add); + if (!fields.contains("sourceEvent") && !fields.equals(REQUIRED_FIELDS)) { + throw new IllegalArgumentException( + "Account generation projection has unknown or missing fields"); + } + if (fields.contains("sourceEvent") && !fields.equals(ALL_FIELDS)) { + throw new IllegalArgumentException( + "Account generation projection has unknown or missing fields"); + } + if (!SCHEMA_VERSION.equals(requireText(object, "schemaVersion"))) { + throw new IllegalArgumentException( + "Account generation projection schemaVersion is unsupported"); + } + Optional event = + fields.contains("sourceEvent") + ? Optional.of(requireText(object, "sourceEvent")) + : Optional.empty(); + AccountGenerationProjection projection = + new AccountGenerationProjection( + requireText(object, "accountId"), + requireText(object, "accountAuthorityGeneration"), + requireText(object, "sourceVersion"), + requireText(object, "outboxStreamKey"), + requireText(object, "outboxSequence"), + event); + if (!projection.toJson().equals(json)) { + throw new IllegalArgumentException("Account generation projection JSON is not canonical"); + } + return projection; + } + + public String key() { + return KEY_PREFIX + accountId; + } + + public String toJson() { + ObjectNode object = JSON.createObjectNode(); + object.put("schemaVersion", SCHEMA_VERSION); + object.put("accountId", accountId); + object.put("accountAuthorityGeneration", accountAuthorityGeneration); + object.put("sourceVersion", sourceVersion); + object.put("outboxStreamKey", outboxStreamKey); + object.put("outboxSequence", outboxSequence); + sourceEvent.ifPresent(value -> object.put("sourceEvent", value)); + try { + return JSON.writeValueAsString(object); + } catch (IOException exception) { + throw new IllegalStateException( + "Account generation projection cannot be serialized", exception); + } + } + + public BigInteger generationValue() { + return new BigInteger(accountAuthorityGeneration); + } + + public BigInteger sourceVersionValue() { + return new BigInteger(sourceVersion); + } + + public BigInteger outboxSequenceValue() { + return new BigInteger(outboxSequence); + } + + static String keyForAccount(UUID accountId) { + Objects.requireNonNull(accountId, "Account UUID is required"); + if (new UUID(0L, 0L).equals(accountId)) { + throw new IllegalArgumentException("A canonical non-nil Account UUID is required"); + } + return KEY_PREFIX + accountId; + } + + private static String streamKeyForAccount(String accountId) { + return STREAM_PREFIX + accountId; + } + + private static String decodeCanonicalEvent(Event event) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(event.payload())) + .toString(); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Account source event is not valid UTF-8", exception); + } + } + + private static void validateSourceEvent( + String eventJson, + String accountId, + String generation, + String sourceVersion, + String streamKey, + String sequence) { + final JsonNode root; + try { + root = JSON.readTree(eventJson); + } catch (IOException exception) { + throw new IllegalArgumentException("Account source event JSON is malformed", exception); + } + if (!(root instanceof ObjectNode object)) { + throw new IllegalArgumentException("Account source event must be a JSON object"); + } + String canonicalEvent; + switch (requireText(object, "schemaVersion")) { + case PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION -> { + PasswordResetAuthorityEvent reset = PasswordResetAuthorityEventV1Codec.verify(eventJson); + canonicalEvent = new String(reset.canonicalJsonUtf8(), StandardCharsets.UTF_8); + requireEventBinding( + accountId, + generation, + sourceVersion, + streamKey, + sequence, + reset.accountId(), + reset.accountAuthorityGeneration(), + reset.sourceVersion(), + reset.outboxStreamKey(), + reset.outboxSequence()); + } + case AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION -> { + AccountLogoutAllAuthorityEvent logout = + AccountLogoutAllAuthorityEventV1Codec.verify(eventJson); + canonicalEvent = new String(logout.canonicalJsonUtf8(), StandardCharsets.UTF_8); + requireEventBinding( + accountId, + generation, + sourceVersion, + streamKey, + sequence, + logout.accountId(), + logout.accountAuthorityGeneration(), + logout.sourceVersion(), + logout.outboxStreamKey(), + logout.outboxSequence()); + } + case AccountSecurityStateAuthorityEventV1Codec.SCHEMA_VERSION -> { + var security = AccountSecurityStateAuthorityEventV1Codec.verify(eventJson); + canonicalEvent = security.canonicalJson(); + requireEventBinding( + accountId, + generation, + sourceVersion, + streamKey, + sequence, + security.accountId(), + security.accountAuthorityGeneration(), + security.sourceVersion(), + security.outboxStreamKey(), + security.outboxSequence()); + } + default -> { + throw new IllegalArgumentException( + "Account source event is not one of the declared closed schemas"); + } + } + if (!canonicalEvent.equals(eventJson)) { + throw new IllegalArgumentException("Account source event JSON is not canonical"); + } + } + + private static void requireEventBinding( + String expectedAccount, + String expectedGeneration, + String expectedSourceVersion, + String expectedStream, + String expectedSequence, + String actualAccount, + String actualGeneration, + String actualSourceVersion, + String actualStream, + String actualSequence) { + if (!expectedAccount.equals(actualAccount) + || !expectedGeneration.equals(actualGeneration) + || !expectedSourceVersion.equals(actualSourceVersion) + || !expectedStream.equals(actualStream) + || !expectedSequence.equals(actualSequence)) { + throw new IllegalArgumentException( + "Account source event does not match its current projection checkpoint"); + } + } + + private static String requireText(ObjectNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Account generation projection " + field + " must be a string"); + } + return value.textValue(); + } + + private static void requireCanonicalAccountId(String value) { + Objects.requireNonNull(value, "accountId is required"); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException( + "Account generation projection accountId is not canonical"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Account generation projection accountId must be a lowercase canonical non-nil UUID", + malformed); + } + } + + private static void requirePositiveDecimal(String value, String field) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a positive canonical decimal string"); + } + } + + private static void requireNonNegativeDecimal(String value, String field) { + if (value == null || !NON_NEGATIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException( + field + " must be a non-negative canonical decimal string"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java new file mode 100644 index 0000000000..cad950c275 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContract.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; + +/** Registered Account-owned single-key compare-and-set for the account generation projection. */ +public final class AccountGenerationProjectionRedisContract { + public static final String SCRIPT_ID = "account.account-generation-projection.v1"; + public static final String RESOURCE_PATH = "redis/account_generation_projection_cas.lua"; + public static final String DESCRIPTOR_RESOURCE = + "/redis/scripts/account-generation-projection-cas.json"; + public static final String OWNER = "account-service"; + public static final String PRINCIPAL = "account_coord_app"; + public static final RedisScriptDescriptor.RedisRole ROLE = + RedisScriptDescriptor.RedisRole.COORDINATION; + public static final RedisScriptDescriptor.ScriptCategory CATEGORY = + RedisScriptDescriptor.ScriptCategory.SESSION_CAS; + public static final String KEY_PREFIX = AccountGenerationProjection.KEY_PREFIX; + public static final String RESOURCE_SHA256 = + "b8cf7abd202786a0b45b59444d1396a6c821e65284092e21a46a995e19e72507"; + + private static final RedisScriptDescriptor EXPECTED = + AccountRedisScriptDescriptorLoader.load( + AccountGenerationProjectionRedisContract.class, DESCRIPTOR_RESOURCE); + private static final RedisScriptCatalog CATALOG = + RedisScriptCatalog.loadInstalled( + AccountGenerationProjectionRedisContract.class.getClassLoader()); + + private AccountGenerationProjectionRedisContract() {} + + /** Resolves the descriptor only from an installed owner contribution. */ + public static RedisScriptDescriptor descriptor() { + RedisScriptDescriptor descriptor = CATALOG.require(SCRIPT_ID); + requireSupportedDescriptor(descriptor); + return descriptor; + } + + /** Validates the exact Account-local invocation shape before private Redis execution. */ + static void validateInvocation( + String key, String expectedMode, String expectedBytes, String candidateBytes) { + Objects.requireNonNull(key, "Account generation key is required"); + Objects.requireNonNull(expectedMode, "Expected generation mode is required"); + Objects.requireNonNull(expectedBytes, "Expected generation bytes are required"); + Objects.requireNonNull(candidateBytes, "Candidate generation bytes are required"); + requireCanonicalAccountKey(key); + switch (expectedMode) { + case "ABSENT" -> { + if (!expectedBytes.isEmpty() || candidateBytes.isEmpty()) { + throw new IllegalArgumentException("ABSENT projection invocation is malformed"); + } + } + case "PRESENT" -> { + if (expectedBytes.isEmpty() || candidateBytes.isEmpty()) { + throw new IllegalArgumentException("PRESENT projection invocation is malformed"); + } + } + case "VERIFY" -> { + if (expectedBytes.isEmpty() || !candidateBytes.isEmpty()) { + throw new IllegalArgumentException("VERIFY projection invocation is malformed"); + } + } + default -> throw new IllegalArgumentException("Account projection mode is unsupported"); + } + } + + static void requireSupportedDescriptor(RedisScriptDescriptor descriptor) { + if (descriptor != CATALOG.require(SCRIPT_ID) + || !EXPECTED.equals(descriptor) + || !SCRIPT_ID.equals(descriptor.scriptId()) + || !OWNER.equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || !RESOURCE_PATH.equals(descriptor.resourcePath()) + || !RESOURCE_SHA256.equals(descriptor.sha256()) + || descriptor.role() != ROLE + || descriptor.category() != CATEGORY) { + throw new IllegalStateException( + "Account current-generation projection descriptor differs from its owner contract"); + } + } + + private static void requireCanonicalAccountKey(String key) { + if (!key.startsWith(KEY_PREFIX)) { + throw new IllegalArgumentException("Account generation key is outside its owner prefix"); + } + String accountId = key.substring(KEY_PREFIX.length()); + try { + UUID parsed = UUID.fromString(accountId); + if (new UUID(0L, 0L).equals(parsed) || !parsed.toString().equals(accountId)) { + throw new IllegalArgumentException( + "Account generation key must use a canonical non-nil UUID"); + } + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Account generation key must use a canonical non-nil UUID", malformed); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisScriptContribution.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisScriptContribution.java new file mode 100644 index 0000000000..a459db5889 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisScriptContribution.java @@ -0,0 +1,36 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; + +/** Account-owned descriptor contribution for the current-generation projection CAS script. */ +public final class AccountGenerationProjectionRedisScriptContribution + implements RedisScriptContribution { + private static final String DESCRIPTOR_RESOURCE = + "/redis/scripts/account-generation-projection-cas.json"; + + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + try { + RedisScriptDescriptor descriptor = + AccountRedisScriptDescriptorLoader.load( + AccountGenerationProjectionRedisScriptContribution.class, DESCRIPTOR_RESOURCE); + if (!"account-service".equals(descriptor.owner()) + || !"account.account-generation-projection.v1".equals(descriptor.scriptId())) { + throw new IllegalStateException( + "Account generation projection descriptor identity is invalid"); + } + return List.of(descriptor); + } catch (RuntimeException exception) { + if (exception instanceof IllegalStateException state) throw state; + throw new IllegalStateException("Account generation projection descriptor is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReader.java new file mode 100644 index 0000000000..4c71f255c6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipRoleSourceReader.java @@ -0,0 +1,288 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot.MembershipSource; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, read-only-in-purpose current membership/role SQL source capture. + * + *

Requires a writable Account transaction for owner locks, with REPEATABLE_READ or SERIALIZABLE + * isolation. No transaction, network call, enrollment, mutation, actor authority, deadline evidence + * or admission decision is created here. Actual owner APIs currently support FRESH_GAME_DESIGN + * tenant provenance only; approved retained tenant mappings cannot be inferred through this reader. + * Applicable later owner decisions can consume this capture; it supplies no reduction intent. + */ +public final class AccountMembershipRoleSourceReader { + private final AccountAuthoritySourceEvidenceRepository sources; + private final AccountAuthorityGenerationRepository generations; + private final AccountTenantMembershipRepository memberships; + private final AccountMembershipPairAuthorityRepository pairs; + private final AccountTenantMembershipRoleSnapshotRepository roles; + private final AccountAuthorityOutboxRepository outbox; + private final AccountTenantAuthorityEventRepository tenants; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Account owner repositories are private transaction collaborators.") + public AccountMembershipRoleSourceReader( + AccountAuthoritySourceEvidenceRepository sources, + AccountAuthorityGenerationRepository generations, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository pairs, + AccountTenantMembershipRoleSnapshotRepository roles, + AccountAuthorityOutboxRepository outbox, + AccountTenantAuthorityEventRepository tenants) { + this.sources = Objects.requireNonNull(sources); + this.generations = Objects.requireNonNull(generations); + this.memberships = Objects.requireNonNull(memberships); + this.pairs = Objects.requireNonNull(pairs); + this.roles = Objects.requireNonNull(roles); + this.outbox = Objects.requireNonNull(outbox); + this.tenants = Objects.requireNonNull(tenants); + } + + public AccountMembershipRoleSourceSnapshot readCurrent(UUID accountId, UUID tenantId) { + requireUuid(accountId); + requireUuid(tenantId); + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + require( + TransactionSynchronizationManager.isActualTransactionActive() + && !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + && (Objects.equals(isolation, TransactionDefinition.ISOLATION_REPEATABLE_READ) + || Objects.equals(isolation, TransactionDefinition.ISOLATION_SERIALIZABLE))); + + // Both owner source/composite APIs lock Account first, before authority, tenant or pair rows. + var source = + sources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId); + var authority = + generations.readCompositeSnapshot( + GameSessionAccountDelegationProfile.ISSUER, + accountId, + List.of(tenantId), + List.of(tenantId)); + require(source != null && authority != null); + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + require(authority.tenants().size() == 1 && authority.memberships().size() == 1); + var tenantState = authority.tenants().getFirst(); + var memberState = authority.memberships().getFirst(); + require( + AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER) + .equals(source.issuer().scope()) + && AuthorityScope.account(accountId).equals(source.account().scope()) + && source.issuer().scope().equals(authority.issuer().scope()) + && source.account().scope().equals(authority.account().scope()) + && AuthorityScope.tenant(tenantId).equals(tenantState.scope()) + && AuthorityScope.membership(accountId, tenantId).equals(memberState.scope()) + && source.issuer().generation() == authority.issuer().generation() + && source.issuer().sourceVersion() == authority.issuer().sourceVersion() + && source.account().generation() == authority.account().generation() + && source.account().sourceVersion() == authority.account().sourceVersion() + && source.issuanceFence().equals(authority.issuanceFence()) + && accountId.equals(authority.issuanceFence().accountId()) + && authority.issuanceFence().equals(authority.account().issuanceFence()) + && authority.issuanceFence().equals(memberState.issuanceFence()) + && authority.issuer().issuanceFence() == null + && tenantState.issuanceFence() == null); + var tenant = tenants.readCurrentByTenant(tenantId); + require(tenant != null); + require( + tenantId.equals(tenant.tenantId()) + && tenantId.equals(tenant.sourceEvidence().canonicalTenantId()) + && tenant.tenantAuthorityGeneration() == tenantState.generation() + && tenant.tenantAuthoritySourceVersion() == tenantState.sourceVersion()); + var member = + memberships + .findFreshMembershipForUpdate(accountId, tenantId) + .orElseThrow(AccountMembershipRoleSourceReader::unavailable); + var pair = + pairs + .readForUpdate(accountId, tenantId) + .orElseThrow(AccountMembershipRoleSourceReader::unavailable); + var provenance = pair.provenance(); + var account = member.getAccount(); + if (account == null) { + throw unavailable(); + } + require( + account.getId() != null + && account.getId() > 0L + && member.getId() != null + && member.getId() > 0L); + require( + accountId.equals(pair.accountUuid()) + && tenantId.equals(pair.tenantUuid()) + && pair.membershipExists() + && pair.eventSequence() > 0L + && provenance.kind() == TenantProvenanceKind.FRESH_GAME_DESIGN + && provenance.legacyTenantId() == null + && member.getTenantId() == null + && provenance.kind().name().equals(member.getTenantProvenanceKind()) + && provenance.sourceOperationId().equals(tenant.sourceEvidence().operationId()) + && provenance.digest().equals(tenant.sourceEvidence().evidenceDigest()) + && provenance.sourceOperationId().equals(member.getTenantSourceOperationId()) + && provenance.digest().equals(member.getTenantProvenanceDigest()) + && accountId.equals(account.getAccountUuid()) + && tenantId.equals(member.getTenantUuid()) + && AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.equals( + account.getAccountUuidProvenance()) + && account.getId().equals(account.getAccountUuidSourceNumericId()) + && account.getId().equals(source.account().accountSourceNumericId()) + && member.getMembershipVersion() == pair.membershipVersion() + && member.getMembershipAuthorityGeneration() == pair.membershipAuthorityGeneration() + && memberState.generation() == pair.membershipAuthorityGeneration() + && member.getAuthorityProvenance() != null + && !member.getAuthorityProvenance().isBlank()); + var role = + roles + .findForCanonicalUpdate( + accountId, tenantId, provenance, member.getId(), member.getMembershipVersion()) + .orElseThrow(AccountMembershipRoleSourceReader::unavailable); + require( + role.accountId() == account.getId() + && Objects.equals(role.tenantId(), member.getTenantId()) + && role.membershipId() == member.getId() + && role.snapshotVersion() == member.getMembershipVersion() + && accountId.equals(role.accountUuid()) + && tenantId.equals(role.tenantUuid()) + && provenance.equals(role.tenantProvenance())); + String stream = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountId + + "/" + + tenantId; + var checkpoint = + outbox.readCheckpoint(stream).orElseThrow(AccountMembershipRoleSourceReader::unavailable); + var event = + outbox + .findEvent(stream, checkpoint.outboxSequence()) + .orElseThrow(AccountMembershipRoleSourceReader::unavailable); + var verified = + MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); + require( + stream.equals(checkpoint.outboxStreamKey()) + && stream.equals(event.outboxStreamKey()) + && stream.equals(verified.outboxStreamKey()) + && ("membership/" + accountId + "/" + tenantId).equals(verified.sourceScope()) + && checkpoint.outboxSequence() == pair.eventSequence() + && event.outboxSequence() == pair.eventSequence() + && Long.toString(pair.eventSequence()).equals(verified.outboxSequence()) + && pair.eventId().equals(checkpoint.sourceEventId()) + && pair.eventId().equals(event.eventId()) + && pair.eventId().equals(verified.eventId()) + && pair.eventDigest().equals(checkpoint.sourceEventDigest()) + && pair.eventDigest().equals(event.eventDigest()) + && pair.eventDigest().equals(verified.eventDigest()) + && event.requestId().equals(verified.requestId()) + && Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + && accountId.toString().equals(verified.accountId()) + && tenantId.toString().equals(verified.tenantId()) + && Map.of(tenantId.toString(), Long.toString(pair.membershipVersion())) + .equals(verified.membershipVersion()) + && Long.toString(pair.membershipAuthorityGeneration()) + .equals(verified.membershipAuthorityGeneration()) + && Objects.equals(member.getLifecycleState(), verified.membershipLifecycleState()) + && member.isGameplayAdmissionAllowed() == verified.gameplayAdmissionAllowed() + && pair.lastTransitionInvalidated() == verified.callerBoundAuthorityInvalidated() + && role.roles().equals(verified.roles())); + // Historical event bytes remain unchanged when independent current sources advance. + var tuple = verified.authorityTuple(); + require( + tuple + .membershipAuthorityGeneration() + .equals(Map.of(tenantId.toString(), Long.toString(memberState.generation()))) + && tuple + .tenantAuthorityGeneration() + .keySet() + .equals(java.util.Set.of(tenantId.toString()))); + requireNotFuture(tuple.issuerAuthGeneration(), authority.issuer().generation()); + requireNotFuture(tuple.accountAuthorityGeneration(), authority.account().generation()); + requireNotFuture( + tuple.tenantAuthorityGeneration().get(tenantId.toString()), tenantState.generation()); + requireNotFuture(verified.issuanceFence(), authority.issuanceFence().value()); + // No private-grant source owner is included in this bounded reader. + require(tuple.privateRealmGrantVersions().isEmpty()); + tuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> { + requireNotFuture(cutoff.accountAuthorityGeneration(), source.account().generation()); + requireNotFuture(cutoff.outboxSequence(), source.account().checkpoint().sequence()); + }); + tuple + .tenantBillingCutoff() + .ifPresent( + cutoffs -> { + require(cutoffs.keySet().equals(java.util.Set.of(tenantId.toString()))); + var cutoff = cutoffs.get(tenantId.toString()); + requireNotFuture(cutoff.tenantAuthorityGeneration(), tenantState.generation()); + requireNotFuture(cutoff.tenantBillingSequence(), tenant.tenantBillingSequence()); + requireNotFuture(cutoff.outboxSequence(), tenant.outboxSequence()); + }); + return new AccountMembershipRoleSourceSnapshot( + source, + authority, + tenant, + pair, + new MembershipSource( + member.getId(), + account.getId(), + accountId, + account.getAccountUuidProvenance(), + account.getAccountUuidSourceNumericId(), + tenantId, + provenance, + member.getLifecycleState(), + member.isGameplayAdmissionAllowed(), + member.getMembershipVersion(), + member.getMembershipAuthorityGeneration(), + member.getAuthorityProvenance()), + role, + checkpoint, + event, + verified); + } + + private static void requireNotFuture(String historical, long current) { + require(new BigInteger(historical).compareTo(BigInteger.valueOf(current)) <= 0); + } + + private static void requireUuid(UUID id) { + if (id == null || id.equals(new UUID(0L, 0L)) || id.version() != 4 || id.variant() != 2) { + throw new IllegalArgumentException("Canonical non-nil v4 UUID selector is required"); + } + } + + private static void require(boolean valid) { + if (!valid) throw unavailable(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Current Account membership/role SQL source is unavailable or inconsistent"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountRedisScriptDescriptorLoader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountRedisScriptDescriptorLoader.java new file mode 100644 index 0000000000..baf621e087 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountRedisScriptDescriptorLoader.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.accountservice.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.HashSet; +import java.util.Set; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Closed, bounded reader for Account's canonical owner-local descriptor resources. */ +public final class AccountRedisScriptDescriptorLoader { + public static final int MAX_DESCRIPTOR_BYTES = 16 * 1024; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + + private AccountRedisScriptDescriptorLoader() {} + + public static RedisScriptDescriptor load(Class owner, String resource) { + try (InputStream input = owner.getResourceAsStream(resource)) { + if (input == null) throw new IllegalStateException("Account Redis descriptor is unavailable"); + return parse(input.readNBytes(MAX_DESCRIPTOR_BYTES + 1)); + } catch (IOException exception) { + throw new IllegalStateException("Account Redis descriptor is unavailable", exception); + } + } + + public static RedisScriptDescriptor parse(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_DESCRIPTOR_BYTES) { + throw new IllegalArgumentException("Account Redis descriptor size is invalid"); + } + JsonNode root = JSON.readTree(bytes); + fields( + root, + "scriptId", + "resourcePath", + "sha256", + "owner", + "principal", + "role", + "keys", + "arguments", + "category", + "outcomes", + "resetSensitivity", + "lossClass", + "tailLossBehavior", + "compatibilityLevel", + "supportedCoexistence", + "legacyPayloadShape"); + array(root, "keys", "name", "ownedPrefix", "hashTagDeclaration"); + array(root, "arguments", "name"); + array(root, "outcomes", "code", "category", "effect"); + array(root, "supportedCoexistence", "callerVersion", "payloadVersion"); + for (String field : + Set.of( + "scriptId", + "resourcePath", + "sha256", + "owner", + "principal", + "role", + "category", + "resetSensitivity", + "lossClass", + "tailLossBehavior", + "compatibilityLevel")) { + if (!root.get(field).isTextual()) { + throw new IllegalArgumentException("Descriptor text is required"); + } + } + if (!root.get("legacyPayloadShape").isNull() && !root.get("legacyPayloadShape").isTextual()) { + throw new IllegalArgumentException("Descriptor legacy shape is invalid"); + } + return JSON.treeToValue(root, RedisScriptDescriptor.class); + } + + private static void array(JsonNode root, String name, String... itemFields) { + JsonNode items = root.get(name); + if (!items.isArray()) throw new IllegalArgumentException("Descriptor array is required"); + for (JsonNode item : items) { + fields(item, itemFields); + for (String field : itemFields) { + if (!item.get(field).isTextual()) { + throw new IllegalArgumentException("Descriptor declaration text is required"); + } + } + } + } + + private static void fields(JsonNode node, String... names) { + if (node == null || !node.isObject()) { + throw new IllegalArgumentException("Descriptor object is required"); + } + Set actual = new HashSet<>(); + node.properties().forEach(entry -> actual.add(entry.getKey())); + if (!actual.equals(Set.of(names))) { + throw new IllegalArgumentException("Descriptor fields are not canonical"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java new file mode 100644 index 0000000000..f0950da2b1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/DemoTenantEntitlementException.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.accountservice.service; + +/** Typed fail-closed outcomes for Account's protected non-paid demo entitlement slice. */ +public final class DemoTenantEntitlementException extends IllegalStateException { + private final Code code; + + public DemoTenantEntitlementException(Code code, String message) { + super(message); + this.code = code; + } + + public DemoTenantEntitlementException(Code code, String message, Throwable cause) { + super(message, cause); + this.code = code; + } + + public Code code() { + return code; + } + + public enum Code { + FIXTURE_DISABLED, + ENVIRONMENT_DENIED, + SOURCE_EVIDENCE_INVALID, + IDEMPOTENCY_CONFLICT, + ENTITLEMENT_VERSION_CONFLICT, + TENANT_AUTHORITY_STALE, + ENTITLEMENT_UNAVAILABLE, + STALE_ADMISSION_EVIDENCE + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java new file mode 100644 index 0000000000..d93ca57ec9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/IssuerGenerationProjection.java @@ -0,0 +1,272 @@ +package net.firedevops.firemud.accountservice.service; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.math.BigInteger; +import java.util.HashSet; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeKind; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.IssuerEvent; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** Closed Account-owned current issuer projection; not recipient or token authorization. */ +public record IssuerGenerationProjection( + String issuerId, + String issuerAuthGeneration, + String sourceVersion, + String outboxStreamKey, + String lastAppliedSourceOutboxSequence, + Optional lastAppliedSourceEventId, + Optional lastAppliedSourceEventDigest, + Optional sourceEvent) { + public static final String SCHEMA_VERSION = "account-auth-issuer-generation-projection/v1"; + public static final String KEY_PREFIX = "session:auth:generation:issuer:"; + private static final String STREAM = + "account:auth-authority:v1:issuer/" + GameSessionAccountDelegationProfile.ISSUER; + private static final Set BASE_FIELDS = + Set.of( + "schemaVersion", + "issuerId", + "issuerAuthGeneration", + "sourceVersion", + "outboxStreamKey", + "lastAppliedSourceOutboxSequence"); + private static final Set EVENT_FIELDS = + Set.of( + "schemaVersion", + "issuerId", + "issuerAuthGeneration", + "sourceVersion", + "outboxStreamKey", + "lastAppliedSourceOutboxSequence", + "lastAppliedSourceEventId", + "lastAppliedSourceEventDigest", + "sourceEvent"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + public IssuerGenerationProjection { + keyForIssuer(issuerId); + positive(issuerAuthGeneration); + positive(sourceVersion); + if (lastAppliedSourceOutboxSequence == null + || !lastAppliedSourceOutboxSequence.matches("0|[1-9][0-9]*") + || !STREAM.equals(outboxStreamKey)) { + throw new IllegalArgumentException("Issuer projection stream/checkpoint is not canonical"); + } + lastAppliedSourceEventId = Objects.requireNonNull(lastAppliedSourceEventId); + lastAppliedSourceEventDigest = Objects.requireNonNull(lastAppliedSourceEventDigest); + sourceEvent = Objects.requireNonNull(sourceEvent); + if (new BigInteger(lastAppliedSourceOutboxSequence).signum() == 0) { + if (!"1".equals(issuerAuthGeneration) + || !"1".equals(sourceVersion) + || lastAppliedSourceEventId.isPresent() + || lastAppliedSourceEventDigest.isPresent() + || sourceEvent.isPresent()) { + throw new IllegalArgumentException( + "Issuer sequence zero requires original 1/1 and no event"); + } + } else { + if (new BigInteger(issuerAuthGeneration).compareTo(BigInteger.ONE) <= 0 + || new BigInteger(sourceVersion).compareTo(BigInteger.ONE) <= 0 + || lastAppliedSourceEventId.isEmpty() + || lastAppliedSourceEventDigest.isEmpty() + || sourceEvent.isEmpty()) { + throw new IllegalArgumentException( + "Advanced issuer projection requires complete event evidence"); + } + var verified = AccountAuthoritySourceEventV1Codec.verify(sourceEvent.orElseThrow()); + if (!(verified instanceof IssuerEvent event)) { + throw new IllegalArgumentException("Issuer projection source event is not an issuer event"); + } + if (!sourceEvent.orElseThrow().equals(event.canonicalJson()) + || !event.eventId().equals(event.requestId()) + || !issuerId.equals(event.issuerId()) + || !issuerAuthGeneration.equals(event.issuerAuthGeneration()) + || !sourceVersion.equals(event.sourceVersion()) + || !outboxStreamKey.equals(event.outboxStreamKey()) + || !lastAppliedSourceOutboxSequence.equals(event.outboxSequence()) + || !lastAppliedSourceEventId.orElseThrow().equals(event.eventId()) + || !lastAppliedSourceEventDigest.orElseThrow().equals(event.eventDigest())) { + throw new IllegalArgumentException( + "Issuer projection differs from its exact canonical event"); + } + } + } + + /** Adapts only the owner-proved original source; unsupported historical codecs deny. */ + public static IssuerGenerationProjection fromSource( + net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository + .CanonicalIssuerSourceSnapshot + snapshot) { + Objects.requireNonNull(snapshot); + CurrentSourceEvidence source = snapshot.source(); + if (source.checkpoint().sequence() == 0L) return fromSource(source); + if (source.scope().kind() != ScopeKind.ISSUER + || !"ISSUER_SCOPE_INSERT".equals(source.initializationProvenance()) + || source.initializationTransactionId() <= 0L + || source.issuanceFence() != null) { + throw new IllegalArgumentException("Issuer source enrollment is unavailable"); + } + var stored = snapshot.latestEvent().orElseThrow(); + var verified = + AccountAuthoritySourceEventV1Codec.verify( + new String(stored.payload(), java.nio.charset.StandardCharsets.UTF_8)); + if (!(verified instanceof IssuerEvent event)) { + throw new IllegalArgumentException( + "Issuer source checkpoint does not contain an issuer event"); + } + if (!java.util.Arrays.equals(stored.payload(), event.canonicalJsonUtf8()) + || !stored.outboxStreamKey().equals(source.checkpoint().outboxStreamKey()) + || stored.outboxSequence() != source.checkpoint().sequence() + || !event.outboxStreamKey().equals(source.checkpoint().outboxStreamKey()) + || !event.outboxSequence().equals(Long.toString(source.checkpoint().sequence())) + || !event.issuerId().equals(source.scope().issuerId()) + || !event.issuerAuthGeneration().equals(Long.toString(source.generation())) + || !event.sourceVersion().equals(Long.toString(source.sourceVersion())) + || !source.checkpoint().sourceEventId().equals(Optional.of(stored.eventId())) + || !source.checkpoint().sourceEventDigest().equals(Optional.of(stored.eventDigest())) + || !stored.eventId().equals(event.eventId()) + || !stored.eventDigest().equals(event.eventDigest()) + || !stored.requestId().equals(event.requestId()) + || !stored.eventId().equals(stored.requestId()) + || !event.eventId().equals(event.requestId())) { + throw new IllegalArgumentException( + "Issuer projection event differs from the owned checkpoint"); + } + return new IssuerGenerationProjection( + source.scope().issuerId(), Long.toString(source.generation()), + Long.toString(source.sourceVersion()), source.checkpoint().outboxStreamKey(), + Long.toString(source.checkpoint().sequence()), source.checkpoint().sourceEventId(), + source.checkpoint().sourceEventDigest(), Optional.of(event.canonicalJson())); + } + + /** Original enrollment only; advanced values require their unchanged canonical event bytes. */ + public static IssuerGenerationProjection fromSource(CurrentSourceEvidence source) { + Objects.requireNonNull(source); + if (source.scope().kind() != ScopeKind.ISSUER + || !"ISSUER_SCOPE_INSERT".equals(source.initializationProvenance()) + || source.initializationTransactionId() <= 0L + || source.issuanceFence() != null + || source.checkpoint().sequence() != 0L + || source.checkpoint().sourceEventId().isPresent() + || source.checkpoint().sourceEventDigest().isPresent()) { + throw new IllegalArgumentException( + "Current issuer source cannot prove the canonical issuer event contract"); + } + return new IssuerGenerationProjection( + source.scope().issuerId(), + Long.toString(source.generation()), + Long.toString(source.sourceVersion()), + source.checkpoint().outboxStreamKey(), + Long.toString(source.checkpoint().sequence()), + Optional.empty(), + Optional.empty(), + Optional.empty()); + } + + public static IssuerGenerationProjection parse(String json) { + Objects.requireNonNull(json); + final JsonNode root; + try { + root = JSON.readTree(json); + } catch (IOException failure) { + throw new IllegalArgumentException("Issuer projection JSON is malformed", failure); + } + if (!(root instanceof ObjectNode object)) { + throw new IllegalArgumentException("Issuer projection must be an object"); + } + Set fields = new HashSet<>(); + object.fieldNames().forEachRemaining(fields::add); + if (!fields.equals(BASE_FIELDS) && !fields.equals(EVENT_FIELDS)) { + throw new IllegalArgumentException("Issuer projection has missing or unknown fields"); + } + if (!SCHEMA_VERSION.equals(text(object, "schemaVersion"))) { + throw new IllegalArgumentException("Issuer projection schema is unsupported"); + } + boolean event = fields.equals(EVENT_FIELDS); + var projection = + new IssuerGenerationProjection( + text(object, "issuerId"), + text(object, "issuerAuthGeneration"), + text(object, "sourceVersion"), + text(object, "outboxStreamKey"), + text(object, "lastAppliedSourceOutboxSequence"), + event ? Optional.of(text(object, "lastAppliedSourceEventId")) : Optional.empty(), + event ? Optional.of(text(object, "lastAppliedSourceEventDigest")) : Optional.empty(), + event ? Optional.of(text(object, "sourceEvent")) : Optional.empty()); + if (!projection.toJson().equals(json)) { + throw new IllegalArgumentException("Issuer projection JSON is not canonical"); + } + return projection; + } + + public String toJson() { + ObjectNode object = JSON.createObjectNode(); + object.put("schemaVersion", SCHEMA_VERSION); + object.put("issuerId", issuerId); + object.put("issuerAuthGeneration", issuerAuthGeneration); + object.put("sourceVersion", sourceVersion); + object.put("outboxStreamKey", outboxStreamKey); + object.put("lastAppliedSourceOutboxSequence", lastAppliedSourceOutboxSequence); + lastAppliedSourceEventId.ifPresent(value -> object.put("lastAppliedSourceEventId", value)); + lastAppliedSourceEventDigest.ifPresent( + value -> object.put("lastAppliedSourceEventDigest", value)); + sourceEvent.ifPresent(value -> object.put("sourceEvent", value)); + try { + return JSON.writeValueAsString(object); + } catch (IOException failure) { + throw new IllegalStateException("Issuer projection cannot be serialized", failure); + } + } + + public String key() { + return keyForIssuer(issuerId); + } + + public BigInteger generationValue() { + return new BigInteger(issuerAuthGeneration); + } + + public BigInteger sourceVersionValue() { + return new BigInteger(sourceVersion); + } + + public BigInteger outboxSequenceValue() { + return new BigInteger(lastAppliedSourceOutboxSequence); + } + + public static String keyForIssuer(String issuerId) { + if (!GameSessionAccountDelegationProfile.ISSUER.equals(issuerId)) { + throw new IllegalArgumentException( + "Issuer projection must bind the configured Account issuer"); + } + return KEY_PREFIX + issuerId; + } + + private static String text(ObjectNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Issuer projection field must be a string: " + field); + } + return value.textValue(); + } + + private static void positive(String value) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "Issuer projection counter must be a positive canonical decimal"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java new file mode 100644 index 0000000000..a7e1ad4732 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcService.java @@ -0,0 +1,144 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseState; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwner; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwner.AbortDeniedException; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionReadOwner; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.shared.v1.ErrorDetail; + +/** Unregistered negative-state read and abort transport; positive admission methods stay absent. */ +public final class AccountGameplayAdmissionLeaseGrpcService + extends AccountGameplayAdmissionLeaseServiceGrpc.AccountGameplayAdmissionLeaseServiceImplBase { + private final AccountGameplayAdmissionAbortOwner owner; + private final AccountGameplayAdmissionReadOwner readOwner; + + public AccountGameplayAdmissionLeaseGrpcService( + AccountGameplayAdmissionAbortOwner owner, AccountGameplayAdmissionReadOwner readOwner) { + this.owner = Objects.requireNonNull(owner); + this.readOwner = Objects.requireNonNull(readOwner); + } + + @Override + public void readGameplayAdmissionLease( + ReadGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + ReadGameplayAdmissionLeaseResponse response; + try { + var read = readOwner.read(request); + if (read.state() == State.COMMITTED) + throw Status.FAILED_PRECONDITION + .withDescription("Exact Account admission lease readback unavailable") + .asRuntimeException(); + response = + ReadGameplayAdmissionLeaseResponse.newBuilder() + .setOperation( + AccountGameplayAdmissionLeaseWireCodec.encodeOperation( + read.evidence(), + read.state() == State.PENDING + ? GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_PENDING + : GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED, + read.bindingDecisionId(), + read.orphanCleanupId())) + .build(); + } catch (StatusRuntimeException failure) { + observer.onError(sanitizedReadFailure(failure)); + return; + } catch (IllegalArgumentException failure) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Malformed Account admission lease read request") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Account admission lease read unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static StatusRuntimeException sanitizedReadFailure(StatusRuntimeException failure) { + return switch (Status.fromThrowable(failure).getCode()) { + case UNAUTHENTICATED -> + Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + case PERMISSION_DENIED -> + Status.PERMISSION_DENIED + .withDescription("Game Session workload required") + .asRuntimeException(); + case INVALID_ARGUMENT -> + Status.INVALID_ARGUMENT + .withDescription("Malformed Account admission lease read request") + .asRuntimeException(); + case FAILED_PRECONDITION -> + Status.FAILED_PRECONDITION + .withDescription("Exact Account admission lease readback unavailable") + .asRuntimeException(); + default -> + Status.UNAVAILABLE + .withDescription("Account admission lease read unavailable") + .asRuntimeException(); + }; + } + + @Override + public void abortGameplayAdmissionLease( + AbortGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + AbortGameplayAdmissionLeaseResponse response; + try { + var aborted = owner.abort(request); + if (aborted.state() != State.ABORTED) + throw new IllegalStateException("Abort result required"); + response = + AbortGameplayAdmissionLeaseResponse.newBuilder() + .setOperation( + AccountGameplayAdmissionLeaseWireCodec.encodeOperation( + aborted.evidence(), + GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED, + aborted.bindingDecisionId(), + aborted.orphanCleanupId())) + .build(); + } catch (AbortDeniedException failure) { + response = + AbortGameplayAdmissionLeaseResponse.newBuilder() + .setDenied( + ErrorDetail.newBuilder() + .setCode(failure.code()) + .setMessage("Account admission abort denied")) + .build(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + return; + } catch (IllegalArgumentException failure) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Malformed Account admission abort request") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Account admission abort unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcService.java new file mode 100644 index 0000000000..289c007a6f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcService.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceServiceGrpc; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.accountservice.repository.AccountIssuerSourceSnapshotReadOwner; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec; + +/** Unregistered adapter for the protected Account issuer-source owner read. */ +public final class AccountIssuerAuthoritySourceGrpcService + extends AccountIssuerAuthoritySourceServiceGrpc.AccountIssuerAuthoritySourceServiceImplBase { + private final AccountIssuerSourceSnapshotReadOwner owner; + + public AccountIssuerAuthoritySourceGrpcService(AccountIssuerSourceSnapshotReadOwner owner) { + this.owner = Objects.requireNonNull(owner); + } + + @Override + public void readCurrentIssuerAuthoritySource( + ReadCurrentIssuerAuthoritySourceRequest request, + StreamObserver observer) { + final AccountIssuerSourceSnapshotReadOwner.ReadResult result; + try { + result = owner.read(request); + } catch (StatusRuntimeException failure) { + observer.onError(sanitize(failure)); + return; + } catch (IllegalArgumentException failure) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Malformed Account issuer source request") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Account issuer source is temporarily unavailable") + .asRuntimeException()); + return; + } + + final AccountIssuerAuthoritySourceSnapshot response; + try { + response = + AccountIssuerSourceSnapshotGrpcCodec.toResponse( + result.evidence(), result.request(), result.authenticatedCallerWorkload()); + } catch (RuntimeException invalidSource) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Account issuer source snapshot is unavailable or inconsistent") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static StatusRuntimeException sanitize(StatusRuntimeException failure) { + return switch (Status.fromThrowable(failure).getCode()) { + case UNAUTHENTICATED -> + Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + case PERMISSION_DENIED -> + Status.PERMISSION_DENIED + .withDescription("Same-namespace Game Session workload required") + .asRuntimeException(); + case INVALID_ARGUMENT -> + Status.INVALID_ARGUMENT + .withDescription("Malformed Account issuer source request") + .asRuntimeException(); + case FAILED_PRECONDITION -> + Status.FAILED_PRECONDITION + .withDescription("Account issuer source snapshot is unavailable or conflicts") + .asRuntimeException(); + default -> + Status.UNAVAILABLE + .withDescription("Account issuer source is temporarily unavailable") + .asRuntimeException(); + }; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticator.java new file mode 100644 index 0000000000..45ec68e7bb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticator.java @@ -0,0 +1,269 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, read-only authentication of an initial Game Session Account delegation token. + * + *

This checks the TLS-authenticated Game Session workload, verifies only the unscoped initial + * JWT shape, and asks the Account committed-issuance owner for current COMMITTED plus ACTIVE + * evidence. It neither admits a player nor creates a lease, and its observation is not a reusable + * credential or stand-alone acquire authorization. Callers still need the current source-specific + * acquire predicates and durable lease-bound decision readback. + */ +public final class AccountGameplayAdmissionInitialTokenAuthenticator { + private static final String ROUTE_ID = "game-session-initial-admission-acquire"; + private static final String GAME_SESSION_SERVICE = "game-session-service"; + private static final Set NO_OPTIONAL_CLAIMS = Set.of(); + private static final ExplicitRouteProfilePolicy INITIAL_POLICY = + new ExplicitRouteProfilePolicy( + ROUTE_ID, + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.TYPE, + GameSessionAccountDelegationProfile.ISSUER, + GameSessionAccountDelegationProfile.AUDIENCE, + GameSessionAccountDelegationJwtProfileValidator.REQUIRED_CLAIMS, + NO_OPTIONAL_CLAIMS, + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS, + 0, + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES, + GameSessionAccountDelegationJwtProfileValidator::validateInitialClaims); + + private final AccountAsymmetricJwtVerifier verifier; + private final AccountGameplayDelegationCommittedIssuanceOwner committedIssuanceOwner; + private final String trustedWorkloadNamespace; + private final Clock clock; + + public AccountGameplayAdmissionInitialTokenAuthenticator( + AccountAsymmetricJwtVerifier verifier, + AccountGameplayDelegationCommittedIssuanceOwner committedIssuanceOwner, + String trustedWorkloadNamespace, + Clock clock) { + this.verifier = Objects.requireNonNull(verifier, "Account JWT verifier is required"); + this.committedIssuanceOwner = + Objects.requireNonNull(committedIssuanceOwner, "Committed issuance owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(trustedWorkloadNamespace)) { + throw new IllegalArgumentException("Trusted Game Session namespace is invalid"); + } + this.trustedWorkloadNamespace = trustedWorkloadNamespace; + this.clock = Objects.requireNonNull(clock, "Clock is required"); + } + + /** + * Authenticates one compact initial token against the current committed and active owner state. + * + *

The compact token is neither retained nor included in any returned value or failure. + */ + public CurrentInitialTokenObservation authenticateInitialToken(String compactJwt) { + try { + // Refuse caller-owned SQL work before the verifier can touch JWKS or the owner can touch SQL + // and Redis. Both dependencies are deliberately called only outside ambient transactions. + requireNoAmbientTransaction(); + GrpcPeerIdentity peer = requireCurrentGameSessionPeer(); + + VerifiedClaims verified = verifier.verify(compactJwt, INITIAL_POLICY); + requireVerifiedRoute(verified); + Map claims = verified.claims(); + UUID tokenJti = canonicalUuid(claims.get("jti")); + + requireNoAmbientTransaction(); + CommittedCandidateVerificationData candidate = + committedIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(tokenJti); + long observedAt = clock.instant().getEpochSecond(); + requireCandidateAndClaims(peer, claims, verified, candidate, compactJwt, observedAt); + return new CurrentInitialTokenObservation(candidate, observedAt); + } catch (RuntimeException failure) { + if (failure instanceof InitialTokenAuthenticationException denied) { + throw denied; + } + // Do not expose token, verifier, SQL, signer, or registry details to the caller. + throw denied(); + } + } + + private GrpcPeerIdentity requireCurrentGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expectedUri = + "spiffe://firemud/ns/" + trustedWorkloadNamespace + "/sa/" + GAME_SESSION_SERVICE; + if (peer == null + || !peer.isService(GAME_SESSION_SERVICE) + || !peer.isInNamespace(trustedWorkloadNamespace) + || !expectedUri.equals(peer.uri())) { + throw denied(); + } + return peer; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw denied(); + } + } + + private static void requireVerifiedRoute(VerifiedClaims verified) { + if (verified == null + || !ROUTE_ID.equals(verified.routeId()) + || !GameSessionAccountDelegationProfile.PROFILE.equals(verified.profile()) + || !GameSessionAccountDelegationProfile.TYPE.equals(verified.tokenType()) + || !GameSessionAccountDelegationProfile.ISSUER.equals(verified.claims().get("iss")) + || !GameSessionAccountDelegationProfile.AUDIENCE.equals(verified.claims().get("aud"))) { + throw denied(); + } + } + + private void requireCandidateAndClaims( + GrpcPeerIdentity peer, + Map claims, + VerifiedClaims verified, + CommittedCandidateVerificationData candidate, + String compactJwt, + long observedAtEpochSecond) { + if (candidate == null) { + throw denied(); + } + AccountGameplayDelegationPendingIdentity identity = candidate.identity(); + AccountAuthoritySnapshot authority = candidate.authoritySnapshot(); + if (identity == null + || authority == null + || !identity.accountId().equals(authority.accountId()) + || !peer.uri().equals(identity.callerWorkload()) + || !candidate.signerKid().equals(verified.keyId()) + || !candidate.tokenSha256().equals(sha256(compactJwt)) + || !stringClaim(claims, "iss").equals(GameSessionAccountDelegationProfile.ISSUER) + || !stringClaim(claims, "aud").equals(GameSessionAccountDelegationProfile.AUDIENCE) + || !identity.accountId().toString().equals(stringClaim(claims, "sub")) + || !identity.accountId().toString().equals(stringClaim(claims, "accountId")) + || !identity.tokenJti().equals(canonicalUuid(claims.get("jti"))) + || epochSecondClaim(claims, "iat") != identity.issuedAtEpochSecond() + || epochSecondClaim(claims, "nbf") != identity.notBeforeEpochSecond() + || epochSecondClaim(claims, "exp") != identity.expiresAtEpochSecond() + // Initial LOGIN issues durable token generation one; the committed owner verifies that + // exact generation in its SQL/evidence proof before returning this candidate. + || !"1".equals(stringClaim(claims, "tokenGeneration")) + || !Long.toString(authority.issuanceFence()).equals(stringClaim(claims, "issuanceFence")) + || !GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff()) + .equals(mapClaim(claims, "authorityTuple")) + || !Map.of().equals(mapClaim(claims, "membershipVersion"))) { + throw denied(); + } + if (observedAtEpochSecond < identity.issuedAtEpochSecond() + || observedAtEpochSecond < identity.notBeforeEpochSecond() + || observedAtEpochSecond >= identity.expiresAtEpochSecond()) { + throw denied(); + } + } + + private static UUID canonicalUuid(Object value) { + if (!(value instanceof String text)) { + throw denied(); + } + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.version() != 4 || parsed.variant() != 2) { + throw denied(); + } + return parsed; + } catch (IllegalArgumentException failure) { + throw denied(); + } + } + + private static String stringClaim(Map claims, String name) { + Object value = claims.get(name); + if (!(value instanceof String text)) { + throw denied(); + } + return text; + } + + private static long epochSecondClaim(Map claims, String name) { + Object value = claims.get(name); + try { + if (!(value instanceof Number number)) { + throw denied(); + } + return new BigDecimal(number.toString()).longValueExact(); + } catch (ArithmeticException | NumberFormatException failure) { + throw denied(); + } + } + + private static Map mapClaim(Map claims, String name) { + Object value = claims.get(name); + if (!(value instanceof Map map)) { + throw denied(); + } + return map; + } + + private static String sha256(String compactJwt) { + try { + byte[] digest = + MessageDigest.getInstance("SHA-256") + .digest(compactJwt.getBytes(StandardCharsets.US_ASCII)); + return HexFormat.of().formatHex(digest); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static InitialTokenAuthenticationException denied() { + return new InitialTokenAuthenticationException(); + } + + /** Generic fail-closed error; deliberately contains no token or dependency details. */ + public static final class InitialTokenAuthenticationException extends SecurityException { + private InitialTokenAuthenticationException() { + super("Initial Account token authentication failed"); + } + } + + /** + * Read-only currentness observation. It cannot authorize admission or replace source predicates + * and durable decision readback at a later acquire boundary. + */ + public static final class CurrentInitialTokenObservation { + private final CommittedCandidateVerificationData candidate; + private final long observedAtEpochSecond; + + private CurrentInitialTokenObservation( + CommittedCandidateVerificationData candidate, long observedAtEpochSecond) { + this.candidate = Objects.requireNonNull(candidate); + this.observedAtEpochSecond = observedAtEpochSecond; + } + + public CommittedCandidateVerificationData candidate() { + return candidate; + } + + public long observedAtEpochSecond() { + return observedAtEpochSecond; + } + + @Override + public String toString() { + return "CurrentInitialTokenObservation[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwner.java new file mode 100644 index 0000000000..b799f1d78c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwner.java @@ -0,0 +1,185 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Clock; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayPublicAdmissionSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.service.AccountGameplayPublicAdmissionSourceReader; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered, non-admitting composition of initial authentication and current Account sources. + * + *

JWT/JWKS and committed SQL/Redis authentication finish before this owner opens its SQL source + * transaction. Only the real Account source reader runs inside that transaction. Its captured + * sources are valid at that transaction alone; every later commit must revalidate. This does not + * supply platform_access_ban, World, restriction, deadline, lease, or physical commit proof. The + * absent platform_access_ban source keeps gameplay admission denied. + */ +public final class AccountGameplayAuthenticatedPublicSourceOwner { + private final AccountGameplayAdmissionInitialTokenAuthenticator authenticator; + private final AccountGameplayPublicAdmissionSourceReader sources; + private final TransactionTemplate sourceTransaction; + private final Clock clock; + + /** The timeout is trusted operational SQL configuration, never an authorization deadline. */ + public AccountGameplayAuthenticatedPublicSourceOwner( + AccountGameplayAdmissionInitialTokenAuthenticator authenticator, + AccountGameplayPublicAdmissionSourceReader sources, + PlatformTransactionManager transactionManager, + Clock clock, + int sourceReadTimeoutSeconds) { + this.authenticator = Objects.requireNonNull(authenticator); + this.sources = Objects.requireNonNull(sources); + this.clock = Objects.requireNonNull(clock); + if (sourceReadTimeoutSeconds <= 0) { + throw new IllegalArgumentException("Positive Account source transaction timeout is required"); + } + sourceTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + sourceTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + sourceTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + sourceTransaction.setReadOnly(false); + sourceTransaction.setTimeout(sourceReadTimeoutSeconds); + } + + /** Target tenant is only a subject-bound owner lookup selector, never caller authority. */ + public CurrentPublicSourceObservation observeCurrent(String compactJwt, UUID tenantId) { + try { + requireNoAmbientTransaction(); + if (tenantId == null || tenantId.version() != 4 || tenantId.variant() != 2) throw denied(); + var authenticated = authenticator.authenticateInitialToken(compactJwt); + var candidate = Objects.requireNonNull(authenticated).candidate(); + var pending = Objects.requireNonNull(candidate).identity(); + var authority = candidate.authoritySnapshot(); + if (!pending.accountId().equals(authority.accountId())) throw denied(); + TokenIdentity identity = + new TokenIdentity( + pending.accountId(), + pending.operationId(), + pending.requestId(), + candidate.tokenSha256(), + pending.tokenJti(), + pending.notBeforeEpochSecond(), + 1L, + authority.issuanceFence()); + requireTokenTime(candidate); + requireNoAmbientTransaction(); + CurrentPublicSourceObservation result = + sourceTransaction.execute( + status -> { + requireSourceTransaction(); + requireTokenTime(candidate); + var snapshot = sources.readCurrent(identity.accountId(), tenantId, identity); + requireMatchingSources(candidate, tenantId, identity, snapshot); + long capturedAt = requireTokenTime(candidate); + return new CurrentPublicSourceObservation( + identity, + pending.issuedAtEpochSecond(), + pending.expiresAtEpochSecond(), + snapshot, + capturedAt); + }); + // A delayed transaction completion must not return an already-expired observation. + requireTokenTime(candidate); + return Objects.requireNonNull(result); + } catch (RuntimeException failure) { + throw denied(); + } + } + + private static void requireMatchingSources( + CommittedCandidateVerificationData candidate, + UUID tenantId, + TokenIdentity identity, + AccountGameplayPublicAdmissionSourceSnapshot snapshot) { + var membership = Objects.requireNonNull(snapshot).membershipSource(); + var member = membership.membership(); + var current = membership.currentAuthority(); + var ownerSources = membership.issuerAccountSources(); + var signed = candidate.authoritySnapshot(); + var issuerScope = AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER); + var accountScope = AuthorityScope.account(identity.accountId()); + if (!identity.accountId().equals(member.accountId()) + || !tenantId.equals(member.tenantId()) + || snapshot.accountLifecycleState() != AccountLifecycleState.ACTIVE + || !issuerScope.equals(ownerSources.issuer().scope()) + || !accountScope.equals(ownerSources.account().scope()) + || !issuerScope.equals(current.issuer().scope()) + || !accountScope.equals(current.account().scope()) + || current.issuer().generation() != signed.issuerGeneration() + || current.account().generation() != signed.accountGeneration() + || ownerSources.issuer().generation() != signed.issuerGeneration() + || ownerSources.account().generation() != signed.accountGeneration() + || !ownerSources.account().accountSecurityCutoff().equals(signed.accountSecurityCutoff()) + || !identity.accountId().equals(current.issuanceFence().accountId()) + || current.issuanceFence().value() != identity.issuanceFence() + || !current.issuanceFence().equals(ownerSources.issuanceFence()) + || !current.issuanceFence().equals(ownerSources.account().issuanceFence()) + || !identity.equals(snapshot.tokenIdentityFence().identity()) + || snapshot.tokenIdentityFence().state() != State.ACTIVE + || snapshot.tokenIdentityFence().tokenIdentityFence() != 1L) { + throw denied(); + } + // The initial JWT's empty membershipVersion is not a target membership baseline. Preserve + // the reader's current membership, tenant/billing and source-event evidence unchanged. + } + + private long requireTokenTime(CommittedCandidateVerificationData candidate) { + var identity = candidate.identity(); + long now = clock.instant().getEpochSecond(); + if (now < identity.issuedAtEpochSecond() + || now < identity.notBeforeEpochSecond() + || now >= identity.expiresAtEpochSecond()) throw denied(); + return now; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw denied(); + } + + private static void requireSourceTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_SERIALIZABLE) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw denied(); + } + } + + private static PublicSourceObservationException denied() { + return new PublicSourceObservationException(); + } + + public static final class PublicSourceObservationException extends SecurityException { + private PublicSourceObservationException() { + super("Current Account public source observation failed"); + } + } + + /** Immutable captured evidence; cannot authorize admission, minting, or a later SQL commit. */ + public record CurrentPublicSourceObservation( + TokenIdentity tokenIdentity, + long tokenIssuedAtEpochSecond, + long tokenExpiresAtEpochSecond, + AccountGameplayPublicAdmissionSourceSnapshot sourceSnapshot, + long capturedAtEpochSecond) { + public CurrentPublicSourceObservation { + Objects.requireNonNull(tokenIdentity); + Objects.requireNonNull(sourceSnapshot); + } + + @Override + public String toString() { + return "CurrentPublicSourceObservation[non-authorizing, redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java new file mode 100644 index 0000000000..7055b4b4a5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java @@ -0,0 +1,772 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Explicit, non-authorizing Account source-head projection publisher and observer. + * + *

The SQL owner snapshot is captured and its transaction ends before Coordination Redis is + * contacted. The canonical keys are in distinct Redis Cluster hash slots, so publication uses the + * Account client's same pinned physical connection for separate one-key CAS scripts, followed by + * one WAITAOF and exact byte readback of all values. This is an asynchronous projection: it is + * neither atomic with Account SQL nor by itself a token-authorization decision. No numeric + * freshness window is declared here because the canonical owner contract supplies none. + */ +public final class AccountGameplayDelegationAuthorityProjection { + public static final String ISSUER_KEY_PREFIX = "session:auth:generation:issuer:"; + public static final String ACCOUNT_KEY_PREFIX = "session:auth:generation:account:"; + public static final int MAX_PROJECTION_BYTES = 8 * 1024; + + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern EVENT_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final TransactionTemplate accountTransaction; + private final AccountGameplayDelegationRedisClient coordinationRedis; + private SelectedOwner selectedOwner; + + public AccountGameplayDelegationAuthorityProjection( + AccountAuthoritySourceEvidenceRepository sourceEvidence, + PlatformTransactionManager transactionManager, + AccountGameplayDelegationRedisClient coordinationRedis) { + this( + sourceEvidence, + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")), + coordinationRedis); + } + + AccountGameplayDelegationAuthorityProjection( + AccountAuthoritySourceEvidenceRepository sourceEvidence, + TransactionTemplate accountTransaction, + AccountGameplayDelegationRedisClient coordinationRedis) { + this.sourceEvidence = + Objects.requireNonNull(sourceEvidence, "Account source evidence is required"); + this.accountTransaction = Objects.requireNonNull(accountTransaction); + this.coordinationRedis = Objects.requireNonNull(coordinationRedis); + } + + /** Real owner dependencies; no caller-supplied snapshot/currentness callback is accepted. */ + public AccountGameplayDelegationAuthorityProjection( + AccountAuthoritySourceEvidenceRepository sourceEvidence, + PlatformTransactionManager transactionManager, + AccountGameplayDelegationRedisClient coordinationRedis, + AccountAuthorityGenerationRepository generations, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository pairs, + AccountAuthorityOutboxRepository outbox, + AccountTenantAuthorityEventRepository tenantSources) { + this(sourceEvidence, transactionManager, coordinationRedis); + this.selectedOwner = + new SelectedOwner( + Objects.requireNonNull(generations), + Objects.requireNonNull(memberships), + Objects.requireNonNull(pairs), + Objects.requireNonNull(outbox), + Objects.requireNonNull(tenantSources)); + accountTransaction.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_REPEATABLE_READ); + accountTransaction.setReadOnly(false); + } + + /** Four separate canonical keys on one pinned Redis connection; never an admission decision. */ + public SelectedProjectionObservation publishSelectedCurrent(UUID accountId, UUID tenantId) { + requireOutsideOwnerTransaction(); + SelectedSnapshot before = readSelectedSnapshot(accountId, tenantId); + var outcome = + coordinationRedis.publishSelectedAuthorityProjections(accountId, tenantId, before.values()); + SelectedSnapshot after = readSelectedSnapshot(accountId, tenantId); + requireSameSelectedSnapshot(before, after); + return new SelectedProjectionObservation(after, outcome); + } + + /** + * Actual SQL owner reads surround exact Redis observation, including independent member version. + */ + public SelectedProjectionObservation observeSelectedCurrent(UUID accountId, UUID tenantId) { + requireOutsideOwnerTransaction(); + SelectedSnapshot before = readSelectedSnapshot(accountId, tenantId); + byte[][] actual = coordinationRedis.readSelectedAuthorityProjections(accountId, tenantId); + SelectedSnapshot after = readSelectedSnapshot(accountId, tenantId); + requireSameSelectedSnapshot(before, after); + if (!Arrays.deepEquals(actual, after.values())) throw new StaleProjectionException(); + return new SelectedProjectionObservation(after, null); + } + + private SelectedSnapshot readSelectedSnapshot(UUID accountId, UUID tenantId) { + requireAccountId(accountId); + requireAccountId(tenantId); + if (selectedOwner == null) throw new ProjectionUnavailableException(); + SelectedSnapshot result = + accountTransaction.execute( + status -> { + // The source and composite owners both take Account first; the composite fixes all + // four scopes. + var source = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId); + var composite = + selectedOwner + .generations() + .readCompositeSnapshot( + GameSessionAccountDelegationProfile.ISSUER, + accountId, + List.of(tenantId), + List.of(tenantId)); + var tenant = selectedOwner.tenantSources().readCurrentByTenant(tenantId); + var member = + selectedOwner + .memberships() + .findFreshMembershipForUpdate(accountId, tenantId) + .orElseThrow(ProjectionUnavailableException::new); + var pair = + selectedOwner + .pairs() + .readForUpdate(accountId, tenantId) + .orElseThrow(ProjectionUnavailableException::new); + String memberStream = + "account:auth-authority:v1:membership/" + accountId + "/" + tenantId; + var checkpoint = + selectedOwner + .outbox() + .readCheckpoint(memberStream) + .orElseThrow(ProjectionUnavailableException::new); + var event = + selectedOwner + .outbox() + .findEvent(memberStream, checkpoint.outboxSequence()) + .orElseThrow(ProjectionUnavailableException::new); + var verified = + MembershipAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + var tenantState = composite.tenants().getFirst(); + var memberState = composite.memberships().getFirst(); + if (source.issuer().generation() != composite.issuer().generation() + || source.issuer().sourceVersion() != composite.issuer().sourceVersion() + || source.account().generation() != composite.account().generation() + || source.account().sourceVersion() != composite.account().sourceVersion() + || !source.issuanceFence().equals(composite.issuanceFence()) + || tenant.tenantAuthorityGeneration() != tenantState.generation() + || tenant.tenantAuthoritySourceVersion() != tenantState.sourceVersion() + || !tenantId.equals(tenant.tenantId()) + || !pair.provenance() + .sourceOperationId() + .equals(tenant.sourceEvidence().operationId()) + || !pair.provenance().digest().equals(tenant.sourceEvidence().evidenceDigest()) + || !pair.membershipExists() + || pair.lastTransitionInvalidated() + || !"ACTIVE".equals(member.getLifecycleState()) + || !member.isGameplayAdmissionAllowed() + || member.getMembershipVersion() != pair.membershipVersion() + || member.getMembershipAuthorityGeneration() + != pair.membershipAuthorityGeneration() + || memberState.generation() != pair.membershipAuthorityGeneration() + || checkpoint.outboxSequence() != pair.eventSequence() + || !checkpoint.sourceEventId().equals(pair.eventId()) + || !checkpoint.sourceEventDigest().equals(pair.eventDigest()) + || !event.eventId().equals(pair.eventId()) + || !event.eventDigest().equals(pair.eventDigest()) + || !Long.toString(checkpoint.outboxSequence()).equals(verified.outboxSequence()) + || !checkpoint.outboxStreamKey().equals(verified.outboxStreamKey()) + || !Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + || !accountId.toString().equals(verified.accountId()) + || !tenantId.toString().equals(verified.tenantId()) + || !Long.toString(pair.membershipVersion()) + .equals(verified.membershipVersion().get(tenantId.toString())) + || !Long.toString(pair.membershipAuthorityGeneration()) + .equals(verified.membershipAuthorityGeneration()) + || !"ACTIVE".equals(verified.membershipLifecycleState()) + || !verified.gameplayAdmissionAllowed() + || verified.callerBoundAuthorityInvalidated() + || !verified.roles().contains("player")) + throw new ProjectionUnavailableException(); + // The immutable event proves this pair, not today's independent global/tenant + // sources. + // Derive today's tuple from the same locked owner read; never rewrite the historical + // event. + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", Long.toString(composite.issuer().generation())); + tuple.put( + "accountAuthorityGeneration", Long.toString(composite.account().generation())); + tuple.put( + "tenantAuthorityGeneration", + Map.of(tenantId.toString(), Long.toString(tenantState.generation()))); + tuple.put( + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), Long.toString(memberState.generation()))); + tuple.put("privateRealmGrantVersions", List.of()); + var accountCutoff = source.account().accountSecurityCutoff(); + if (accountCutoff.isPresent()) { + var cutoff = accountCutoff.orElseThrow(); + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence())); + } + // The explicit demo owner has positive linked billing evidence; non-paid does not + // mean absent cutoff. + tuple.put( + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + Long.toString(tenant.tenantAuthorityGeneration()), + "tenantBillingSequence", Long.toString(tenant.tenantBillingSequence()), + "outboxStreamKey", tenant.tenantBillingStreamKey(), + "outboxSequence", Long.toString(tenant.tenantBillingSequence())))); + byte[][] initial = canonicalProjectionPair(source); + return new SelectedSnapshot( + source, + composite, + pair, + verified.canonicalJson(), + new String(tenant.payload(), StandardCharsets.UTF_8), + canonical(tuple), + new byte[][] { + initial[0], + initial[1], + AccountSelectedGameplayAuthorityProjection.tenant(tenant).canonicalBytes(), + AccountSelectedGameplayAuthorityProjection.membership( + verified, memberState.sourceVersion()) + .canonicalBytes() + }); + }); + if (result == null) throw new ProjectionUnavailableException(); + return result; + } + + private static void requireSameSelectedSnapshot(SelectedSnapshot before, SelectedSnapshot after) { + if (!before.source().equals(after.source()) + || !before.composite().equals(after.composite()) + || !before.pair().equals(after.pair()) + || !before.membershipEvent().equals(after.membershipEvent()) + || !before.tenantEvent().equals(after.tenantEvent()) + || !Arrays.equals(before.currentTuple(), after.currentTuple()) + || !Arrays.deepEquals(before.values(), after.values())) + throw new StaleProjectionException(); + } + + private static void requireOutsideOwnerTransaction() { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) { + throw new ProjectionUnavailableException(); + } + } + + private record SelectedOwner( + AccountAuthorityGenerationRepository generations, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository pairs, + AccountAuthorityOutboxRepository outbox, + AccountTenantAuthorityEventRepository tenantSources) {} + + private record SelectedSnapshot( + IssuerAccountSourceSnapshot source, + AccountAuthorityGenerationRepository.CompositeSnapshot composite, + AccountMembershipPairAuthorityRepository.PairAuthority pair, + String membershipEvent, + String tenantEvent, + byte[] currentTuple, + byte[][] values) {} + + /** Owner-generated informational evidence. It cannot be fabricated as a positive caller proof. */ + public static final class SelectedProjectionObservation { + private final SelectedSnapshot snapshot; + private final AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome + publicationOutcome; + + private SelectedProjectionObservation( + SelectedSnapshot snapshot, + AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome publicationOutcome) { + this.snapshot = snapshot; + this.publicationOutcome = publicationOutcome; + } + + public boolean admitting() { + return false; + } + + public long membershipVersion() { + return snapshot.pair().membershipVersion(); + } + + public long membershipAuthorityGeneration() { + return snapshot.pair().membershipAuthorityGeneration(); + } + + public byte[] canonicalCurrentAuthorityTuple() { + return snapshot.currentTuple().clone(); + } + + public Map currentAuthorityTuple() { + try { + return JSON.readValue(snapshot.currentTuple(), new TypeReference<>() {}); + } catch (RuntimeException unavailable) { + throw new ProjectionUnavailableException(); + } + } + + public long issuanceFence() { + return snapshot.composite().issuanceFence().value(); + } + + public void requireExactOwnerSnapshot( + IssuerAccountSourceSnapshot source, + AccountAuthorityGenerationRepository.CompositeSnapshot authority, + AccountMembershipPairAuthorityRepository.PairAuthority pair, + MembershipAuthorityEventV1Codec.MembershipEvent membership, + net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event tenant) { + if (!snapshot.source().equals(source) + || !snapshot.composite().equals(authority) + || !snapshot.pair().equals(pair) + || !snapshot.membershipEvent().equals(membership.canonicalJson()) + || !snapshot.tenantEvent().equals(new String(tenant.payload(), StandardCharsets.UTF_8))) + throw new StaleProjectionException(); + } + + public void requireSameSnapshot(SelectedProjectionObservation current) { + if (current == null) throw new StaleProjectionException(); + requireSameSelectedSnapshot(snapshot, current.snapshot); + } + + public Map projectionDigests() { + return Map.of( + "issuer", + sha256(snapshot.values()[0]), + "account", + sha256(snapshot.values()[1]), + "tenant", + sha256(snapshot.values()[2]), + "membership", + sha256(snapshot.values()[3])); + } + + public byte[][] canonicalProjections() { + return Arrays.stream(snapshot.values()).map(byte[]::clone).toArray(byte[][]::new); + } + + public AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome publicationOutcome() { + return publicationOutcome; + } + } + + /** + * Publishes the exact latest locked issuer/Account source heads. This method does not activate a + * token or establish freshness authority; a missing/ambiguous Redis acknowledgement fails. + */ + public PublicationObservation publishCurrent(UUID accountId) { + requireAccountId(accountId); + IssuerAccountSourceSnapshot source = readOwnerSnapshot(accountId); + byte[][] values = canonicalProjectionPair(source); + ProjectionValue issuer = + ProjectionValue.decode(values[0], "issuer", GameSessionAccountDelegationProfile.ISSUER); + ProjectionValue account = ProjectionValue.decode(values[1], "account", accountId.toString()); + AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome outcome = + coordinationRedis.publishAuthorityProjections(accountId, values[0], values[1]); + IssuerAccountSourceSnapshot after = readOwnerSnapshot(accountId); + if (!source.equals(after) || !Arrays.deepEquals(values, canonicalProjectionPair(after))) { + throw new StaleProjectionException(); + } + return new PublicationObservation( + issuer.digest(), + account.digest(), + source.issuer().generation(), + source.account().generation(), + outcome); + } + + /** + * Observes a Redis projection only when both values equal two consecutive exact Account + * owner-source reads. This is informational, remains non-authorizing, and defines no elapsed-time + * freshness policy or subsequent-use race guarantee. + */ + public ProjectionObservation observeCurrent(UUID accountId) { + requireAccountId(accountId); + IssuerAccountSourceSnapshot before = readOwnerSnapshot(accountId); + byte[][] raw = coordinationRedis.readAuthorityProjections(accountId); + IssuerAccountSourceSnapshot after = readOwnerSnapshot(accountId); + if (!before.equals(after)) throw new StaleProjectionException(); + + ProjectionValue issuer = + ProjectionValue.decode(raw[0], "issuer", GameSessionAccountDelegationProfile.ISSUER); + ProjectionValue account = ProjectionValue.decode(raw[1], "account", accountId.toString()); + byte[][] expected = canonicalProjectionPair(after); + if (!Arrays.equals(issuer.canonicalBytes(), expected[0]) + || !Arrays.equals(account.canonicalBytes(), expected[1])) { + throw new StaleProjectionException(); + } + return new ProjectionObservation( + issuer.digest(), account.digest(), issuer.generation(), account.generation()); + } + + private IssuerAccountSourceSnapshot readOwnerSnapshot(UUID accountId) { + IssuerAccountSourceSnapshot snapshot = + accountTransaction.execute( + status -> + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId)); + if (snapshot == null + || !GameSessionAccountDelegationProfile.ISSUER.equals(snapshot.issuer().scope().issuerId()) + || !accountId.equals(snapshot.account().scope().accountId())) { + throw new ProjectionUnavailableException(); + } + return snapshot; + } + + /** Encodes exact source DTOs for the two projection keys; these bytes are not authority proof. */ + public static byte[][] canonicalProjectionPair(IssuerAccountSourceSnapshot source) { + Objects.requireNonNull(source, "Account authority source snapshot is required"); + var canonicalIssuer = source.canonicalIssuerProjection(); + if (canonicalIssuer == null + || !source.issuer().scope().issuerId().equals(canonicalIssuer.issuerId()) + || !Long.toString(source.issuer().generation()) + .equals(canonicalIssuer.issuerAuthGeneration()) + || !Long.toString(source.issuer().sourceVersion()).equals(canonicalIssuer.sourceVersion()) + || !source.issuer().checkpoint().outboxStreamKey().equals(canonicalIssuer.outboxStreamKey()) + || !Long.toString(source.issuer().checkpoint().sequence()) + .equals(canonicalIssuer.lastAppliedSourceOutboxSequence()) + || !source + .issuer() + .checkpoint() + .sourceEventId() + .equals(canonicalIssuer.lastAppliedSourceEventId()) + || !source + .issuer() + .checkpoint() + .sourceEventDigest() + .equals(canonicalIssuer.lastAppliedSourceEventDigest())) { + throw new ProjectionUnavailableException(); + } + ProjectionValue issuer = + ProjectionValue.decode( + canonicalIssuer.toJson().getBytes(StandardCharsets.UTF_8), + "issuer", + canonicalIssuer.issuerId()); + AccountGenerationProjection canonicalAccount = source.canonicalAccountProjection(); + if (canonicalAccount == null + || !source.account().scope().accountId().toString().equals(canonicalAccount.accountId()) + || !Long.toString(source.account().generation()) + .equals(canonicalAccount.accountAuthorityGeneration()) + || !Long.toString(source.account().sourceVersion()).equals(canonicalAccount.sourceVersion()) + || !source + .account() + .checkpoint() + .outboxStreamKey() + .equals(canonicalAccount.outboxStreamKey()) + || !Long.toString(source.account().checkpoint().sequence()) + .equals(canonicalAccount.outboxSequence()) + || !source.issuanceFence().equals(source.account().issuanceFence())) { + throw new ProjectionUnavailableException(); + } + ProjectionValue account = + ProjectionValue.decode( + canonicalAccount.toJson().getBytes(StandardCharsets.UTF_8), + "account", + canonicalAccount.accountId()); + return new byte[][] {issuer.canonicalBytes(), account.canonicalBytes()}; + } + + private static void requireAccountId(UUID accountId) { + Objects.requireNonNull(accountId, "Canonical Account UUID is required"); + if (accountId.equals(new UUID(0L, 0L)) + || accountId.version() != 4 + || accountId.variant() != 2) { + throw new IllegalArgumentException("Canonical high-entropy Account UUID is required"); + } + } + + /** Strict canonical non-authorizing value stored at one canonical authority key. */ + public static final class ProjectionValue { + private static final String ISSUER = "issuer"; + private static final String ACCOUNT = "account"; + + private final String scope; + private final String scopeId; + private final BigInteger generation; + private final String digest; + private final byte[] canonicalBytes; + + private ProjectionValue( + String scope, String scopeId, BigInteger generation, String digest, byte[] canonicalBytes) { + this.scope = scope; + this.scopeId = scopeId; + this.generation = generation; + this.digest = digest; + this.canonicalBytes = canonicalBytes.clone(); + } + + static ProjectionValue fromSource(CurrentSourceEvidence source) { + Objects.requireNonNull(source, "Verified Account authority source is required"); + final String scope; + final String scopeId; + if (source.scope().kind() + == net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository + .ScopeKind.ISSUER) { + scope = ISSUER; + scopeId = source.scope().issuerId(); + if (!GameSessionAccountDelegationProfile.ISSUER.equals(scopeId)) { + throw new ProjectionUnavailableException(); + } + } else { + throw new ProjectionUnavailableException(); + } + try { + IssuerGenerationProjection issuer = IssuerGenerationProjection.fromSource(source); + return decode(issuer.toJson().getBytes(StandardCharsets.UTF_8), scope, scopeId); + } catch (IllegalArgumentException unsupportedSource) { + throw new ProjectionUnavailableException(); + } + } + + /** Strictly parses canonical owner projection bytes and verifies its preimage digest. */ + public static ProjectionValue decode( + byte[] bytes, String expectedScope, String expectedScopeId) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_PROJECTION_BYTES) { + throw new ProjectionUnavailableException(); + } + try { + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + if (ACCOUNT.equals(expectedScope)) { + AccountGenerationProjection account = AccountGenerationProjection.parse(text); + if (!expectedScopeId.equals(account.accountId())) + throw new ProjectionUnavailableException(); + return new ProjectionValue( + ACCOUNT, account.accountId(), account.generationValue(), sha256(bytes), bytes); + } + if (!ISSUER.equals(expectedScope)) throw new ProjectionUnavailableException(); + IssuerGenerationProjection issuer = IssuerGenerationProjection.parse(text); + if (!expectedScopeId.equals(issuer.issuerId())) throw new ProjectionUnavailableException(); + return new ProjectionValue( + ISSUER, issuer.issuerId(), issuer.generationValue(), sha256(bytes), bytes); + } catch (ProjectionUnavailableException ex) { + throw ex; + } catch (Exception ex) { + throw new ProjectionUnavailableException(); + } + } + + public String scope() { + return scope; + } + + public String scopeId() { + return scopeId; + } + + public long generation() { + return generation.longValueExact(); + } + + public BigInteger generationValue() { + return generation; + } + + public String digest() { + return digest; + } + + public String key() { + return AccountGameplayDelegationAuthorityProjection.key(scope, scopeId); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public String toString() { + return "AccountAuthorityProjection[redacted]"; + } + } + + public record PublicationObservation( + String issuerDigest, + String accountDigest, + long issuerGeneration, + long accountGeneration, + AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome redisOutcome) { + public PublicationObservation { + requireDigest(issuerDigest); + requireDigest(accountDigest); + if (issuerGeneration <= 0L || accountGeneration <= 0L) { + throw new IllegalArgumentException("Projected generations must be positive"); + } + Objects.requireNonNull(redisOutcome); + } + + @Override + public String toString() { + return "AccountAuthorityProjectionPublication[redacted]"; + } + } + + public record ProjectionObservation( + String issuerDigest, String accountDigest, long issuerGeneration, long accountGeneration) { + public ProjectionObservation { + requireDigest(issuerDigest); + requireDigest(accountDigest); + if (issuerGeneration <= 0L || accountGeneration <= 0L) { + throw new IllegalArgumentException("Observed generations must be positive"); + } + } + + @Override + public String toString() { + return "AccountAuthorityProjectionObservation[non-authorizing]"; + } + } + + public static final class ProjectionUnavailableException extends IllegalStateException { + public ProjectionUnavailableException() { + super("Account authority projection is unavailable or inconsistent"); + } + } + + public static final class StaleProjectionException extends IllegalStateException { + public StaleProjectionException() { + super("Account authority projection is stale or changed during observation"); + } + } + + private static String key(String scope, String scopeId) { + return (ProjectionValue.ISSUER.equals(scope) ? ISSUER_KEY_PREFIX : ACCOUNT_KEY_PREFIX) + + scopeId; + } + + private static UUID parseCanonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) throw new IllegalArgumentException(); + return parsed; + } catch (RuntimeException ex) { + throw new ProjectionUnavailableException(); + } + } + + private static Map object(Object value) { + if (!(value instanceof Map input)) throw new ProjectionUnavailableException(); + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : input.entrySet()) { + if (!(entry.getKey() instanceof String key) || entry.getValue() == null) { + throw new ProjectionUnavailableException(); + } + result.put(key, entry.getValue()); + } + return result; + } + + private static String text(Object value) { + if (!(value instanceof String text) || text.isEmpty() || text.length() > 2048) { + throw new ProjectionUnavailableException(); + } + return text; + } + + private static String requireBoundedText(Object value, int maxLength) { + String text = text(value); + if (text.length() > maxLength || text.isBlank() || !text.equals(text.strip())) { + throw new ProjectionUnavailableException(); + } + return text; + } + + private static long parsePositive(Object value) { + String text = text(value); + if (!POSITIVE_DECIMAL.matcher(text).matches()) throw new ProjectionUnavailableException(); + try { + return Long.parseLong(text); + } catch (NumberFormatException ex) { + throw new ProjectionUnavailableException(); + } + } + + private static long parseNonnegative(Object value) { + String text = text(value); + if (!text.matches("0|[1-9][0-9]{0,18}")) throw new ProjectionUnavailableException(); + try { + return Long.parseLong(text); + } catch (NumberFormatException ex) { + throw new ProjectionUnavailableException(); + } + } + + private static void requireDigest(String digest) { + if (digest == null || !SHA256.matcher(digest).matches()) { + throw new IllegalArgumentException("Projection digest is malformed"); + } + } + + private static byte[] canonical(Object value) { + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (bytes.length == 0 || bytes.length > MAX_PROJECTION_BYTES) { + throw new ProjectionUnavailableException(); + } + return bytes; + } catch (IOException | RuntimeException ex) { + if (ex instanceof ProjectionUnavailableException unavailable) throw unavailable; + throw new ProjectionUnavailableException(); + } + } + + private static byte[] canonicalize(String text) throws IOException { + return Rfc8785CanonicalJson.canonicalizeUtf8(text); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new ProjectionUnavailableException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java new file mode 100644 index 0000000000..a571737b3a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java @@ -0,0 +1,455 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Clock; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired Account owner for the separate COMMITTED-to-ACTIVE initial LOGIN stage. + * + *

The activation operation surrounds one pinned Redis CAS/readback with independent fresh + * Account/source/envelope and current signer-owner transactions. Its returned metadata is not a + * credential, player-admission decision, response-recovery proof, or globally atomic cross-store + * snapshot. Recovery may use an older committed signing generation only when its exact original + * public-key fingerprint remains in the current trusted JWKS; current signer/trust and the exact + * original committed issuance are reread on both sides of the Redis postcondition. + */ +public final class AccountGameplayDelegationCommittedIssuanceOwner { + private final AccountGameplayDelegationIssuanceRepository issuanceRepository; + private final AccountGameplayDelegationSigner signer; + private final AccountGameplayDelegationTokenRegistry tokenRegistry; + private final TransactionTemplate accountTransaction; + private final Clock clock; + + public AccountGameplayDelegationCommittedIssuanceOwner( + AccountGameplayDelegationIssuanceRepository issuanceRepository, + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry tokenRegistry, + PlatformTransactionManager transactionManager, + Clock clock) { + this.issuanceRepository = + Objects.requireNonNull(issuanceRepository, "Account issuance repository is required"); + this.signer = Objects.requireNonNull(signer, "Account signer is required"); + this.tokenRegistry = + Objects.requireNonNull(tokenRegistry, "Account token registry is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + } + + /** Performs one fresh informational check of an already persisted COMMITTED request. */ + public CurrentCommittedIssuanceObservation inspectCurrentCommittedIssuance(UUID requestId) { + if (requestId == null || requestId.version() != 4 || requestId.variant() != 2) { + throw unavailable(); + } + // The method owns its complete bounded transaction; it must never inherit unknown caller work. + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + try { + CheckedObservation current = readCurrentOwnerEvidence(requestId); + if (current == null) throw unavailable(); + long observedAt = clock.millis(); + if (current.checkedAtMillis() <= 0L + || Math.floorDiv(current.checkedAtMillis(), 1_000L) + >= current.evidence().identity().expiresAtEpochSecond() + || observedAt <= 0L + || Math.floorDiv(observedAt, 1_000L) + >= current.evidence().identity().expiresAtEpochSecond()) { + throw unavailable(); + } + return new CurrentCommittedIssuanceObservation(current.evidence(), current.checkedAtMillis()); + } catch (OwnerUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + // Storage, signer, parsing, and protected-owner details are deliberately not surfaced. + throw unavailable(); + } + } + + /** + * Resolves an untrusted verified-token JTI to the current committed Account issuance and then + * requires the exact ACTIVE Redis projection after releasing every SQL lock. This is a read-only + * caller-currentness check; it never activates, repairs, or extends the registry record. + */ + public CommittedCandidateVerificationData requireCurrentActiveCommittedCandidateByJti( + UUID tokenJti) { + if (tokenJti == null || tokenJti.version() != 4 || tokenJti.variant() != 2) { + throw unavailable(); + } + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + try { + CommittedCandidateVerificationData evidence = + accountTransaction.execute( + status -> { + CommittedCandidateVerificationData current = + issuanceRepository + .readCurrentCommittedCandidateByJti(tokenJti) + .orElseThrow(AccountGameplayDelegationCommittedIssuanceOwner::unavailable); + signer.requireCurrentCommittedSigner(current); + return current; + }); + if (evidence == null + || !tokenJti.equals(evidence.identity().tokenJti()) + || Math.floorDiv(clock.millis(), 1_000L) >= evidence.identity().expiresAtEpochSecond()) { + throw unavailable(); + } + tokenRegistry.requireExactActiveRecord(evidence); + if (Math.floorDiv(clock.millis(), 1_000L) >= evidence.identity().expiresAtEpochSecond()) { + throw unavailable(); + } + return evidence; + } catch (OwnerUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + /** + * Advances one exact committed issuance to ACTIVE, then independently rereads the Account owner + * evidence. This is a separate Redis/SQL transition, not a global cross-store transaction or a + * credential-return authorization; Authenticate and response recovery remain unwired. + */ + public ActiveCommittedIssuanceObservation activateCommittedIssuance(UUID requestId) { + requireRequestId(requestId); + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + try { + CheckedObservation before = readCurrentRecoveryOwnerEvidence(requestId); + if (before == null) throw unavailable(); + requireUnexpired(before, clock.millis()); + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt active = + tokenRegistry.activateCommittedCandidate(before.evidence()); + requireExactActiveReceipt(active, before.evidence()); + + CheckedObservation after = readCurrentRecoveryOwnerEvidence(requestId); + if (after == null || !sameCommittedOwnerEvidence(before.evidence(), after.evidence())) { + throw unavailable(); + } + long observedAt = clock.millis(); + requireUnexpired(before, observedAt); + requireUnexpired(after, observedAt); + if (active.absoluteExpiryMillis() != after.evidence().registryAbsoluteExpiryMillis()) { + throw unavailable(); + } + return new ActiveCommittedIssuanceObservation(active, observedAt); + } catch (OwnerUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private CheckedObservation readCurrentOwnerEvidence(UUID requestId) { + return accountTransaction.execute( + status -> { + CommittedCandidateVerificationData evidence = + issuanceRepository.readCurrentCommittedCandidate(requestId); + signer.requireCurrentCommittedSigner(evidence); + return new CheckedObservation(evidence, clock.millis()); + }); + } + + /** + * Reads current Account signer/trust and the immutable issuance inside SQL, then checks the + * historical key against the trusted live JWKS only after the SQL transaction has ended. + */ + private CheckedObservation readCurrentRecoveryOwnerEvidence(UUID requestId) { + CheckedObservation checked = + accountTransaction.execute( + status -> { + CommittedCandidateVerificationData evidence = + issuanceRepository.readCurrentCommittedCandidate(requestId); + signer.requireCurrentCommittedRecoverySigner(evidence); + return new CheckedObservation(evidence, clock.millis()); + }); + if (checked == null) return null; + signer.requireRetainedCommittedPublicKey(checked.evidence()); + return checked; + } + + private void requireUnexpired(CheckedObservation checked, long observedAtMillis) { + long expiry = checked.evidence().identity().expiresAtEpochSecond(); + if (checked.checkedAtMillis() <= 0L + || Math.floorDiv(checked.checkedAtMillis(), 1_000L) >= expiry + || observedAtMillis <= 0L + || Math.floorDiv(observedAtMillis, 1_000L) >= expiry) { + throw unavailable(); + } + } + + private static void requireRequestId(UUID requestId) { + if (requestId == null || requestId.version() != 4 || requestId.variant() != 2) { + throw unavailable(); + } + } + + private static void requireExactActiveReceipt( + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt receipt, + CommittedCandidateVerificationData evidence) { + var identity = evidence.identity(); + if (receipt == null + || !receipt + .tokenKey() + .equals(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + evidence.tokenSha256()) + || !receipt.tokenHash().equals(evidence.tokenSha256()) + || !receipt.operationId().equals(identity.operationId().toString()) + || !receipt.requestId().equals(identity.requestId().toString()) + || !receipt.accountId().equals(identity.accountId().toString()) + || !receipt.commitProofSha256().equals(evidence.commitProofSha256()) + || receipt.registryVersion() != 2L + || receipt.absoluteExpiryMillis() != evidence.registryAbsoluteExpiryMillis() + || receipt.localAofCount() < 1L + || receipt.replicaAofCount() < 1L) { + throw unavailable(); + } + } + + private static boolean sameCommittedOwnerEvidence( + CommittedCandidateVerificationData left, CommittedCandidateVerificationData right) { + return left.identity().equals(right.identity()) + && left.authoritySnapshot().equals(right.authoritySnapshot()) + && left.evidenceBundleReference().equals(right.evidenceBundleReference()) + && left.tokenSha256().equals(right.tokenSha256()) + && left.signerKid().equals(right.signerKid()) + && left.signerGeneration().equals(right.signerGeneration()) + && left.canonicalRegistryRecordSha256().equals(right.canonicalRegistryRecordSha256()) + && left.commitProofSha256().equals(right.commitProofSha256()) + && left.signerCorrespondence().equals(right.signerCorrespondence()) + && left.envelopeKeyId().equals(right.envelopeKeyId()) + && left.envelopeSha256().equals(right.envelopeSha256()) + && left.envelopeBytesLength() == right.envelopeBytesLength() + && left.responseRecoveryExpiryEpochMillis() == right.responseRecoveryExpiryEpochMillis() + && left.registryAbsoluteExpiryMillis() == right.registryAbsoluteExpiryMillis() + && left.registrationLocalAofCount() == right.registrationLocalAofCount() + && left.registrationReplicaAofCount() == right.registrationReplicaAofCount() + && left.registrationOutcome() == right.registrationOutcome(); + } + + private static OwnerUnavailableException unavailable() { + return new OwnerUnavailableException(); + } + + private record CheckedObservation( + CommittedCandidateVerificationData evidence, long checkedAtMillis) {} + + /** Exact active-store receipt plus before/after owner reread timestamps; never a credential. */ + public static final class ActiveCommittedIssuanceObservation { + private final UUID operationId; + private final UUID requestId; + private final UUID accountId; + private final String tokenSha256; + private final String activeRecordSha256; + private final String commitProofSha256; + private final long registryVersion; + private final long absoluteExpiryMillis; + private final AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome outcome; + private final long observedAtEpochMillis; + + private ActiveCommittedIssuanceObservation( + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt receipt, + long observedAtEpochMillis) { + this.operationId = UUID.fromString(receipt.operationId()); + this.requestId = UUID.fromString(receipt.requestId()); + this.accountId = UUID.fromString(receipt.accountId()); + this.tokenSha256 = receipt.tokenHash(); + this.activeRecordSha256 = receipt.canonicalActiveRecordSha256(); + this.commitProofSha256 = receipt.commitProofSha256(); + this.registryVersion = receipt.registryVersion(); + this.absoluteExpiryMillis = receipt.absoluteExpiryMillis(); + this.outcome = receipt.outcome(); + this.observedAtEpochMillis = observedAtEpochMillis; + } + + public UUID operationId() { + return operationId; + } + + public UUID requestId() { + return requestId; + } + + public UUID accountId() { + return accountId; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String activeRecordSha256() { + return activeRecordSha256; + } + + public String commitProofSha256() { + return commitProofSha256; + } + + public long registryVersion() { + return registryVersion; + } + + public long absoluteExpiryMillis() { + return absoluteExpiryMillis; + } + + public AccountGameplayDelegationRedisClient.ActiveRegistrationOutcome outcome() { + return outcome; + } + + public long observedAtEpochMillis() { + return observedAtEpochMillis; + } + + @Override + public String toString() { + return "ActiveCommittedIssuanceObservation[non-authorizing,redacted]"; + } + } + + /** Immutable informational result; no candidate, ciphertext, or proof bytes are exposed. */ + public static final class CurrentCommittedIssuanceObservation { + private final UUID operationId; + private final UUID requestId; + private final UUID accountId; + private final UUID tokenJti; + private final String requestDigest; + private final String tokenSha256; + private final String signerKid; + private final String signerGeneration; + private final String commitProofSha256; + private final AccountAuthoritySnapshot authoritySnapshot; + private final EvidenceBundleReference evidenceBundleReference; + private final String canonicalRegistryRecordSha256; + private final String envelopeKeyId; + private final String envelopeSha256; + private final int envelopeBytesLength; + private final long issuedAtEpochSecond; + private final long notBeforeEpochSecond; + private final long expiresAtEpochSecond; + private final long responseRecoveryExpiryEpochMillis; + private final long observedAtEpochMillis; + + private CurrentCommittedIssuanceObservation( + CommittedCandidateVerificationData evidence, long observedAtEpochMillis) { + var identity = evidence.identity(); + this.operationId = identity.operationId(); + this.requestId = identity.requestId(); + this.accountId = identity.accountId(); + this.tokenJti = identity.tokenJti(); + this.requestDigest = identity.requestDigest(); + this.tokenSha256 = evidence.tokenSha256(); + this.signerKid = evidence.signerKid(); + this.signerGeneration = evidence.signerGeneration(); + this.commitProofSha256 = evidence.commitProofSha256(); + this.authoritySnapshot = evidence.authoritySnapshot(); + this.evidenceBundleReference = evidence.evidenceBundleReference(); + this.canonicalRegistryRecordSha256 = evidence.canonicalRegistryRecordSha256(); + this.envelopeKeyId = evidence.envelopeKeyId(); + this.envelopeSha256 = evidence.envelopeSha256(); + this.envelopeBytesLength = evidence.envelopeBytesLength(); + this.issuedAtEpochSecond = identity.issuedAtEpochSecond(); + this.notBeforeEpochSecond = identity.notBeforeEpochSecond(); + this.expiresAtEpochSecond = identity.expiresAtEpochSecond(); + this.responseRecoveryExpiryEpochMillis = evidence.responseRecoveryExpiryEpochMillis(); + this.observedAtEpochMillis = observedAtEpochMillis; + } + + public UUID operationId() { + return operationId; + } + + public UUID requestId() { + return requestId; + } + + public UUID accountId() { + return accountId; + } + + public UUID tokenJti() { + return tokenJti; + } + + public String requestDigest() { + return requestDigest; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String signerKid() { + return signerKid; + } + + public String signerGeneration() { + return signerGeneration; + } + + public String commitProofSha256() { + return commitProofSha256; + } + + public AccountAuthoritySnapshot authoritySnapshot() { + return authoritySnapshot; + } + + public EvidenceBundleReference evidenceBundleReference() { + return evidenceBundleReference; + } + + public String canonicalRegistryRecordSha256() { + return canonicalRegistryRecordSha256; + } + + public String envelopeKeyId() { + return envelopeKeyId; + } + + public String envelopeSha256() { + return envelopeSha256; + } + + public int envelopeBytesLength() { + return envelopeBytesLength; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long notBeforeEpochSecond() { + return notBeforeEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public long responseRecoveryExpiryEpochMillis() { + return responseRecoveryExpiryEpochMillis; + } + + public long observedAtEpochMillis() { + return observedAtEpochMillis; + } + + @Override + public String toString() { + return "CurrentCommittedIssuanceObservation[non-authorizing,redacted]"; + } + } + + public static final class OwnerUnavailableException extends IllegalStateException { + public OwnerUnavailableException() { + super("Current committed Account gameplay delegation evidence is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java new file mode 100644 index 0000000000..faa57e9ec8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java @@ -0,0 +1,436 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.lang.reflect.RecordComponent; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedIssuanceReadback; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection.ProjectionObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.PendingRegistrationReceipt; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.CandidateOutcome; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.PendingCandidateVerificationProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** + * Explicitly unwired, non-authorizing Account PENDING-to-COMMITTED orchestration boundary. + * + *

All protected signer, Coordination Redis, and source projection work finishes before the final + * Account SQL transaction begins. The final transaction rechecks the signer and owner rows, + * persists only bounded canonical non-secret evidence, and is followed by an independent exact + * COMMITTED readback. No compact JWT is returned, decrypted, or persisted here. + */ +public final class AccountGameplayDelegationIssuanceCommitService { + public static final String COMMIT_PROOF_SCHEMA = + "account-game-session-delegation-commit-proof/v1"; + public static final int MAX_COMMIT_PROOF_BYTES = 32 * 1024; + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final AccountGameplayDelegationSigner signer; + private final AccountGameplayDelegationTokenRegistry tokenRegistry; + private final AccountGameplayDelegationAuthorityProjection authorityProjection; + private final AccountGameplayDelegationIssuanceRepository issuanceRepository; + private final TransactionTemplate accountTransaction; + private final Clock clock; + + public AccountGameplayDelegationIssuanceCommitService( + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry tokenRegistry, + AccountGameplayDelegationAuthorityProjection authorityProjection, + AccountGameplayDelegationIssuanceRepository issuanceRepository, + PlatformTransactionManager accountTransactionManager, + Clock clock) { + this.signer = Objects.requireNonNull(signer, "Account gameplay signer is required"); + this.tokenRegistry = + Objects.requireNonNull(tokenRegistry, "Account pending registry is required"); + this.authorityProjection = + Objects.requireNonNull(authorityProjection, "Account authority projection is required"); + this.issuanceRepository = + Objects.requireNonNull(issuanceRepository, "Account issuance repository is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull( + accountTransactionManager, "Account transaction manager is required")); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + } + + /** + * Verifies and commits one already-persisted initial LOGIN issuance operation. This method is + * intentionally not connected to Authenticate, Spring runtime wiring, or a response endpoint. + */ + public CommitResult commitPendingCandidate(UUID requestId) { + requireRequestId(requestId); + // This method performs signer, Redis and source reads before its final SQL transaction. An + // ambient caller transaction could retain Account locks across those network operations, so + // refuse it instead of silently joining or suspending unknown work. + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + try { + Optional prior = issuanceRepository.readCommittedProof(requestId); + if (prior.isPresent()) return CommitResult.exactRetry(prior.orElseThrow()); + + CandidateOutcome candidate = signer.signPendingCandidate(requestId); + if (candidate == null || candidate.verificationProof() == null) throw unavailable(); + PendingCandidateVerificationProof proof = candidate.verificationProof(); + long now = Math.floorDiv(clock.millis(), 1_000L); + if (!requestId.equals(proof.requestId()) + || now <= 0L + || proof.notBeforeEpochSecond() > now + || proof.expiresAtEpochSecond() <= now) { + throw unavailable(); + } + + PendingRegistrationReceipt registration = tokenRegistry.registerPending(requestId); + ProjectionObservation projection = authorityProjection.observeCurrent(proof.accountId()); + CommitProof commitProof = CommitProof.create(proof, registration, projection); + + CommittedIssuanceReadback transactionReadback = + accountTransaction.execute( + status -> { + signer.requireCurrentCommittedSigner(proof); + return issuanceRepository.commitPendingCandidate( + requestId, proof, registration, projection, commitProof); + }); + if (transactionReadback == null + || !transactionReadback.proofSha256().equals(commitProof.sha256())) { + throw unavailable(); + } + + Optional durable = + issuanceRepository.readCommittedProof(requestId); + if (durable.isEmpty() || !durable.orElseThrow().equals(transactionReadback)) { + throw unavailable(); + } + return CommitResult.created(durable.orElseThrow()); + } catch (RuntimeException failure) { + if (failure instanceof IssuanceCommitUnavailableException unavailable) throw unavailable; + throw unavailable(); + } + } + + private static void requireRequestId(UUID requestId) { + Objects.requireNonNull(requestId, "Account issuance request ID is required"); + if (requestId.version() != 4 || requestId.variant() != 2) throw unavailable(); + } + + private static IssuanceCommitUnavailableException unavailable() { + return new IssuanceCommitUnavailableException(); + } + + /** Private-constructor immutable proof assembled only from owner-produced typed evidence. */ + public static final class CommitProof { + private final UUID operationId; + private final UUID requestId; + private final UUID accountId; + private final String requestDigest; + private final String tokenSha256; + private final String sha256; + private final byte[] canonicalBytes; + + private CommitProof( + UUID operationId, + UUID requestId, + UUID accountId, + String requestDigest, + String tokenSha256, + byte[] canonicalBytes) { + this.operationId = Objects.requireNonNull(operationId); + this.requestId = Objects.requireNonNull(requestId); + this.accountId = Objects.requireNonNull(accountId); + this.requestDigest = Objects.requireNonNull(requestDigest); + this.tokenSha256 = Objects.requireNonNull(tokenSha256); + this.canonicalBytes = canonicalBytes.clone(); + if (this.canonicalBytes.length == 0 || this.canonicalBytes.length > MAX_COMMIT_PROOF_BYTES) { + throw unavailable(); + } + this.sha256 = AccountGameplayDelegationIssuanceCommitService.sha256(this.canonicalBytes); + } + + private static CommitProof create( + PendingCandidateVerificationProof proof, + PendingRegistrationReceipt registration, + ProjectionObservation projection) { + Objects.requireNonNull(proof, "Signer-owned pending verification proof is required"); + Objects.requireNonNull(registration, "Pinned Redis registration receipt is required"); + Objects.requireNonNull(projection, "Current Account authority projection is required"); + var identity = proof.identity(); + AccountAuthoritySnapshot snapshot = proof.authoritySnapshot(); + EvidenceBundleReference bundleReference = proof.evidenceBundleReference(); + if (!identity.operationId().toString().equals(registration.operationId()) + || !identity.requestId().toString().equals(registration.requestId()) + || !identity.accountId().toString().equals(registration.accountId()) + || !identity.requestDigest().equals(registration.requestDigest()) + || !identity.tokenJti().toString().equals(registration.tokenJti()) + || !proof.tokenSha256().equals(registration.tokenHash()) + || !proof.signerKid().equals(registration.kid()) + || !proof.signerGeneration().equals(registration.signerGeneration()) + || proof.issuanceFence() != registration.issuanceFence() + || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals( + registration.aclIdentity()) + || !bundleReference.equals(registration.evidenceBundleReference()) + || !proof.canonicalRegistryRecordSha256().equals(registration.canonicalRecordSha256()) + || projection.issuerGeneration() != snapshot.issuerGeneration() + || projection.accountGeneration() != snapshot.accountGeneration() + || registration.registryVersion() != 1L + || registration.localAofCount() < 1L + || registration.replicaAofCount() < 1L) { + throw unavailable(); + } + + Map root = new LinkedHashMap<>(); + root.put("schema", COMMIT_PROOF_SCHEMA); + root.put( + "identity", + Map.ofEntries( + Map.entry("operationId", identity.operationId().toString()), + Map.entry("requestId", identity.requestId().toString()), + Map.entry("accountId", identity.accountId().toString()), + Map.entry("requestDigest", identity.requestDigest()), + Map.entry("callerWorkload", identity.callerWorkload()), + Map.entry("callerContextId", identity.callerContextId().toString()), + Map.entry("tokenJti", identity.tokenJti().toString()), + Map.entry("tokenGeneration", "1"), + Map.entry("issuedAtEpochSecond", Long.toString(identity.issuedAtEpochSecond())), + Map.entry("notBeforeEpochSecond", Long.toString(identity.notBeforeEpochSecond())), + Map.entry("expiresAtEpochSecond", Long.toString(identity.expiresAtEpochSecond())), + Map.entry("tokenSha256", proof.tokenSha256()))); + root.put("tokenSha256", proof.tokenSha256()); + root.put("registryRecordSha256", proof.canonicalRegistryRecordSha256()); + root.put( + "registry", + Map.ofEntries( + Map.entry("state", "pending"), + Map.entry("registryVersion", Long.toString(registration.registryVersion())), + Map.entry("tokenKey", registration.tokenKey()), + Map.entry("tokenHash", registration.tokenHash()), + Map.entry("kid", registration.kid()), + Map.entry("signerGeneration", registration.signerGeneration()), + Map.entry("operationId", registration.operationId()), + Map.entry("requestId", registration.requestId()), + Map.entry("requestDigest", registration.requestDigest()), + Map.entry("absoluteExpiryMillis", Long.toString(registration.absoluteExpiryMillis())), + Map.entry("localAofCount", Long.toString(registration.localAofCount())), + Map.entry("replicaAofCount", Long.toString(registration.replicaAofCount())), + Map.entry("outcome", registration.outcome().name()), + Map.entry("canonicalRecordSha256", registration.canonicalRecordSha256()), + Map.entry( + "evidenceBundleSha256", registration.evidenceBundleReference().canonicalSha256()), + Map.entry("aclIdentity", registration.aclIdentity()))); + root.put("bundle", bundleReference.toMap()); + + root.put( + "authority", + Map.ofEntries( + Map.entry("issuerGeneration", Long.toString(snapshot.issuerGeneration())), + Map.entry("issuerSourceVersion", Long.toString(snapshot.issuerSourceVersion())), + Map.entry("accountGeneration", Long.toString(snapshot.accountGeneration())), + Map.entry("accountSourceVersion", Long.toString(snapshot.accountSourceVersion())), + Map.entry("issuanceFence", Long.toString(snapshot.issuanceFence())), + Map.entry( + "issuanceFenceSourceVersion", + Long.toString(snapshot.issuanceFenceSourceVersion())), + Map.entry( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + snapshot.issuerGeneration(), + snapshot.accountGeneration(), + snapshot.accountSecurityCutoff())), + Map.entry("authoritySourceVersions", snapshot.sourceVersions()), + Map.entry("issuerProjectionGeneration", Long.toString(projection.issuerGeneration())), + Map.entry( + "accountProjectionGeneration", Long.toString(projection.accountGeneration())), + Map.entry("issuerProjectionSha256", projection.issuerDigest()), + Map.entry("accountProjectionSha256", projection.accountDigest()))); + + AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence correspondence = + proof.signerCorrespondence(); + Object canonicalCorrespondence = canonicalValue(correspondence, 0); + byte[] correspondenceBytes = canonicalJson(canonicalCorrespondence); + root.put( + "signer", + Map.of( + "promotionStatus", + correspondence.promotionStatus(), + "promotionOperationId", + correspondence.promotionOperationId().toString(), + "generationOperationId", + correspondence.generationOperationId().toString(), + "targetKid", + proof.signerKid(), + "targetGeneration", + proof.signerGeneration(), + "correspondenceSha256", + AccountGameplayDelegationIssuanceCommitService.sha256(correspondenceBytes), + "correspondence", + canonicalCorrespondence)); + + var sealed = proof.sealedCandidate(); + root.put( + "envelope", + Map.of( + "operationId", + sealed.operationId().toString(), + "requestId", + sealed.requestId().toString(), + "tokenHash", + proof.tokenSha256(), + "kid", + proof.signerKid(), + "signerGeneration", + proof.signerGeneration(), + "authorityEvidenceBundleSha256", + sealed.authorityEvidenceBundleSha256(), + "issuanceFence", + Long.toString(sealed.issuanceFence()), + "responseRecoveryExpiryEpochMillis", + Long.toString(sealed.responseRecoveryExpiryEpochMillis()), + "envelopeSha256", + sealed.envelopeSha256(), + "envelopeBytesLength", + Integer.toString(sealed.envelopeBytesLength()))); + + byte[] canonicalBytes = canonicalJson(root); + return new CommitProof( + identity.operationId(), + identity.requestId(), + identity.accountId(), + identity.requestDigest(), + proof.tokenSha256(), + canonicalBytes); + } + + public UUID operationId() { + return operationId; + } + + public UUID requestId() { + return requestId; + } + + public UUID accountId() { + return accountId; + } + + public String requestDigest() { + return requestDigest; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String sha256() { + return sha256; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public String toString() { + return "AccountGameplayDelegationCommitProof[redacted]"; + } + } + + /** The result exposes only immutable operation identity and proof digest; never a JWT. */ + public record CommitResult( + UUID operationId, UUID requestId, UUID accountId, String proofSha256, Outcome outcome) { + public CommitResult { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(accountId); + Objects.requireNonNull(proofSha256); + Objects.requireNonNull(outcome); + } + + private static CommitResult created(CommittedIssuanceReadback readback) { + return result(readback, Outcome.COMMITTED); + } + + private static CommitResult exactRetry(CommittedIssuanceReadback readback) { + return result(readback, Outcome.EXACT_RETRY); + } + + private static CommitResult result(CommittedIssuanceReadback readback, Outcome outcome) { + return new CommitResult( + readback.operationId(), + readback.requestId(), + readback.accountId(), + readback.proofSha256(), + outcome); + } + + @Override + public String toString() { + return "AccountGameplayDelegationCommitResult[non-authorizing]"; + } + } + + public enum Outcome { + COMMITTED, + EXACT_RETRY + } + + public static final class IssuanceCommitUnavailableException extends IllegalStateException { + public IssuanceCommitUnavailableException() { + super("Account gameplay delegation commit is unavailable or ambiguous"); + } + } + + private static Object canonicalValue(Object value, int depth) { + if (depth > 8) throw unavailable(); + if (value == null) return null; + if (value instanceof Optional optional) + return canonicalValue(optional.orElse(null), depth + 1); + if (value instanceof UUID uuid) return uuid.toString(); + if (value instanceof Enum enumValue) return enumValue.name(); + if (value instanceof String || value instanceof Boolean || value instanceof Number) + return value; + if (!value.getClass().isRecord()) throw unavailable(); + RecordComponent[] components = value.getClass().getRecordComponents(); + if (components.length == 0 || components.length > 64) throw unavailable(); + Map fields = new LinkedHashMap<>(); + try { + for (RecordComponent component : components) { + fields.put( + component.getName(), canonicalValue(component.getAccessor().invoke(value), depth + 1)); + } + } catch (ReflectiveOperationException ex) { + throw unavailable(); + } + return fields; + } + + private static byte[] canonicalJson(Object value) { + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (bytes.length == 0 || bytes.length > MAX_COMMIT_PROOF_BYTES) throw unavailable(); + return bytes; + } catch (IOException ex) { + throw unavailable(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw unavailable(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java new file mode 100644 index 0000000000..b4500b20e9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java @@ -0,0 +1,1434 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingIntent; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisContract; +import net.firedevops.firemud.accountservice.service.AccountRedisScriptDescriptorLoader; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Private, pinned-connection Account Coordination client for issuance and source projections. + * + *

The caller must supply an Account-private connection provider. Every operation independently + * proves the live ACL identity with {@code ACL WHOAMI}; a caller-supplied label is not accepted. + * This class is deliberately not Spring-wired. Endpoint/TLS/ACL provisioning remains an external + * protected binding and is not established by this helper. + */ +public final class AccountGameplayDelegationRedisClient { + public static final String SCRIPT_ID = "account-game-session-delegation-pending-register.v1"; + public static final String ISSUER_PROJECTION_SCRIPT_ID = + "account-game-session-delegation-authority-project-issuer.v1"; + public static final String ACCOUNT_PROJECTION_SCRIPT_ID = + AccountGenerationProjectionRedisContract.SCRIPT_ID; + public static final String TENANT_PROJECTION_SCRIPT_ID = + "account.selected-tenant-generation-projection.v1"; + public static final String MEMBERSHIP_PROJECTION_SCRIPT_ID = + "account.selected-membership-generation-projection.v1"; + public static final String ACTIVE_TRANSITION_SCRIPT_ID = + "account-game-session-delegation-activate-committed.v1"; + private static final String AUTHORITY_PROJECTION_SCRIPT_RESOURCE = + "redis/lua/account-game-session-delegation-authority-project.lua"; + private static final String ACTIVE_TRANSITION_SCRIPT_RESOURCE = + "redis/lua/account-game-session-delegation-activate-committed.lua"; + public static final String TOKEN_KEY_PREFIX = "session:auth:token:"; + public static final String REQUIRED_ACL_IDENTITY = "account_coord_app"; + private static final int MAX_SCRIPT_SOURCE_BYTES = 32 * 1024; + private static final long MAX_CLEANUP_MARGIN_MILLIS = 300_000L; + private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern SHA1 = Pattern.compile("[0-9a-f]{40}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final tools.jackson.databind.json.JsonMapper JSON = + tools.jackson.databind.json.JsonMapper.builder().build(); + + private final AccountCoordinationPinnedConnectionProvider connectionProvider; + private final RedisScriptCatalog scriptCatalog; + private final AcknowledgementRequirements acknowledgementRequirements; + private final int maxRecordBytes; + private final ClassLoader resourceClassLoader; + + public AccountGameplayDelegationRedisClient( + AccountCoordinationPinnedConnectionProvider connectionProvider, + RedisScriptCatalog scriptCatalog, + AcknowledgementRequirements acknowledgementRequirements, + int maxRecordBytes, + ClassLoader resourceClassLoader) { + this.connectionProvider = + Objects.requireNonNull( + connectionProvider, "Private Account Coordination provider is required"); + this.scriptCatalog = Objects.requireNonNull(scriptCatalog, "Redis script catalog is required"); + this.acknowledgementRequirements = + Objects.requireNonNull(acknowledgementRequirements, "WAITAOF requirements are required"); + if (maxRecordBytes <= 0 + || maxRecordBytes > GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES) { + throw new IllegalArgumentException("Registry byte bound exceeds the finite profile ceiling"); + } + this.maxRecordBytes = maxRecordBytes; + this.resourceClassLoader = + Objects.requireNonNull(resourceClassLoader, "Resource class loader is required"); + } + + /** + * Registers or reasserts the exact pending record and acknowledges its write on one physical + * connection. The absolute deadline is fixed by the Account caller and is never extended. + */ + public PendingRegistrationReceipt registerPending( + String tokenHash, byte[] canonicalRecordBytes, long absoluteExpiryMillis) { + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw new IllegalArgumentException("Account token hash is malformed"); + } + Objects.requireNonNull(canonicalRecordBytes, "Canonical pending record is required"); + if (canonicalRecordBytes.length == 0 || canonicalRecordBytes.length > maxRecordBytes) { + throw new IllegalArgumentException("Pending registry record exceeds its finite byte bound"); + } + if (absoluteExpiryMillis <= 0L) { + throw new IllegalArgumentException("Pending registry absolute expiry is malformed"); + } + byte[] recordBytes = canonicalRecordBytes.clone(); + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.decode(recordBytes, maxRecordBytes); + if (!"pending".equals(record.state()) || !tokenHash.equals(record.tokenHash())) { + throw new IllegalArgumentException("Pending registry identity does not match its key"); + } + long tokenExpiryMillis; + try { + tokenExpiryMillis = Math.multiplyExact(record.expiresAtEpochSecond(), 1000L); + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Pending token expiry cannot be represented"); + } + long cleanupMarginMillis = absoluteExpiryMillis - tokenExpiryMillis; + if (cleanupMarginMillis < 0L || cleanupMarginMillis > MAX_CLEANUP_MARGIN_MILLIS) { + throw new IllegalArgumentException("Pending registry cleanup margin is outside its bound"); + } + + RedisScriptDescriptor descriptor = requirePendingDescriptor(); + byte[] scriptSource = readScriptSource(descriptor); + if (!descriptor.sha256().equals(sha256(scriptSource))) { + throw unavailable(); + } + byte[] key = (TOKEN_KEY_PREFIX + tokenHash).getBytes(StandardCharsets.US_ASCII); + byte[] deadline = Long.toString(absoluteExpiryMillis).getBytes(StandardCharsets.US_ASCII); + + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + + try { + if (!connection.isOpen()) throw unavailable(); + ClientOptions clientOptions = connection.getOptions(); + if (clientOptions == null || clientOptions.isAutoReconnect()) { + throw unavailable(); + } + RedisCommands commands = connection.sync(); + requireAccountAclIdentity(commands); + String loadedSha = commands.scriptLoad(scriptSource); + if (loadedSha == null || !SHA1.matcher(loadedSha).matches()) throw unavailable(); + String expectedSha = sha1(scriptSource); + if (!expectedSha.equals(loadedSha)) throw unavailable(); + + Long result = + commands.evalsha( + loadedSha, ScriptOutputType.INTEGER, new byte[][] {key}, recordBytes, deadline); + if (result == null || (result != 0L && result != 1L)) throw unavailable(); + + Acknowledgement acknowledgement = requireDurabilityAcknowledgement(commands); + + byte[] readback = commands.get(key); + Long observedExpiry = commands.pexpiretime(key); + if (!Arrays.equals(recordBytes, readback) + || observedExpiry == null + || observedExpiry.longValue() != absoluteExpiryMillis) { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord verified = + GameSessionAccountDelegationRegistryRecord.decode(readback, maxRecordBytes); + if (!"pending".equals(verified.state()) || !tokenHash.equals(verified.tokenHash())) { + throw unavailable(); + } + return new PendingRegistrationReceipt( + verified, + sha256(recordBytes), + absoluteExpiryMillis, + result == 1L + ? PendingRegistrationOutcome.CREATED + : PendingRegistrationOutcome.EXACT_RETRY, + acknowledgement.localAofCount(), + acknowledgement.replicaAofCount()); + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + /** + * Applies the exact PENDING-to-ACTIVE Redis projection transition only when supplied the + * repository's typed, current COMMITTED-candidate readback. This helper is deliberately not wired + * to Authenticate, response recovery, or a runtime token validator. Its receipt proves only the + * observed Redis transition and the immutable owner facts supplied for this call; it does not + * establish freshness through a later response or player-admission decision. + */ + public ActiveRegistrationReceipt activateCommittedPending( + PendingRegistrationReceipt pendingReceipt, + CommittedCandidateVerificationData committedCandidate) { + Objects.requireNonNull(pendingReceipt, "Pinned pending-registration receipt is required"); + Objects.requireNonNull( + committedCandidate, "Repository-produced COMMITTED candidate evidence is required"); + requireOwnerReceiptCorrespondence(pendingReceipt, committedCandidate); + + RedisScriptDescriptor descriptor = requireActiveTransitionDescriptor(); + byte[] scriptSource = readScriptSource(descriptor); + if (!descriptor.sha256().equals(sha256(scriptSource))) throw unavailable(); + + byte[] key = ascii(pendingReceipt.tokenKey()); + byte[] deadline = + Long.toString(pendingReceipt.absoluteExpiryMillis()).getBytes(StandardCharsets.US_ASCII); + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + + try { + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + String loadedSha = commands.scriptLoad(scriptSource); + if (loadedSha == null + || !SHA1.matcher(loadedSha).matches() + || !sha1(scriptSource).equals(loadedSha)) { + throw unavailable(); + } + + byte[] pendingBytes = commands.get(key); + Long observedExpiry = commands.pexpiretime(key); + if (!boundedRegistryRecord(pendingBytes) + || observedExpiry == null + || observedExpiry.longValue() != pendingReceipt.absoluteExpiryMillis()) { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord observedRecord = + GameSessionAccountDelegationRegistryRecord.decode(pendingBytes, maxRecordBytes); + final GameSessionAccountDelegationRegistryRecord pendingRecord; + final byte[] exactPendingBytes; + final byte[] activeBytes; + if ("pending".equals(observedRecord.state()) && observedRecord.registryVersion() == 1L) { + pendingRecord = observedRecord; + exactPendingBytes = pendingBytes; + requirePendingMatchesOwner( + pendingRecord, exactPendingBytes, pendingReceipt, committedCandidate); + activeBytes = activeRecordBytes(pendingRecord); + } else if ("active".equals(observedRecord.state()) + && observedRecord.registryVersion() == 2L) { + activeBytes = pendingBytes; + exactPendingBytes = pendingRecordBytes(observedRecord); + pendingRecord = + GameSessionAccountDelegationRegistryRecord.decode(exactPendingBytes, maxRecordBytes); + requirePendingMatchesOwner( + pendingRecord, exactPendingBytes, pendingReceipt, committedCandidate); + if (!Arrays.equals(activeRecordBytes(pendingRecord), activeBytes)) throw unavailable(); + } else { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord expectedActive = + GameSessionAccountDelegationRegistryRecord.decode(activeBytes, maxRecordBytes); + if (!"active".equals(expectedActive.state()) + || expectedActive.registryVersion() != 2L + || !expectedActive.tokenHash().equals(committedCandidate.tokenSha256())) { + throw unavailable(); + } + + Long result = + commands.evalsha( + loadedSha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + exactPendingBytes, + activeBytes, + deadline); + if (result == null || (result != 0L && result != 1L)) throw unavailable(); + Acknowledgement acknowledgement = requireDurabilityAcknowledgement(commands); + + byte[] activeReadback = commands.get(key); + Long activeExpiry = commands.pexpiretime(key); + if (!Arrays.equals(activeBytes, activeReadback) + || activeExpiry == null + || activeExpiry.longValue() != pendingReceipt.absoluteExpiryMillis()) { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord verifiedActive = + GameSessionAccountDelegationRegistryRecord.decode(activeReadback, maxRecordBytes); + if (!"active".equals(verifiedActive.state()) + || verifiedActive.registryVersion() != 2L + || !verifiedActive.tokenHash().equals(committedCandidate.tokenSha256())) { + throw unavailable(); + } + return new ActiveRegistrationReceipt( + verifiedActive, + sha256(activeReadback), + committedCandidate.commitProofSha256(), + pendingReceipt.absoluteExpiryMillis(), + result == 1L + ? ActiveRegistrationOutcome.ACTIVATED + : ActiveRegistrationOutcome.EXACT_RETRY, + acknowledgement.localAofCount(), + acknowledgement.replicaAofCount()); + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + /** + * Recovers the original exact registration receipt from repository-validated COMMITTED proof, + * then performs the same fenced pending-to-active CAS. The observed Redis deadline is compared to + * the immutable SQL proof; it is never used to manufacture or extend that deadline. + */ + ActiveRegistrationReceipt activateCommittedCandidate( + CommittedCandidateVerificationData committedCandidate) { + Objects.requireNonNull( + committedCandidate, "Repository-produced COMMITTED candidate evidence is required"); + PendingRegistrationReceipt registration = readCommittedRegistrationReceipt(committedCandidate); + return activateCommittedPending(registration, committedCandidate); + } + + private PendingRegistrationReceipt readCommittedRegistrationReceipt( + CommittedCandidateVerificationData committedCandidate) { + String tokenHash = committedCandidate.tokenSha256(); + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) throw unavailable(); + byte[] key = ascii(TOKEN_KEY_PREFIX + tokenHash); + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + + try { + if (!connection.isOpen()) throw unavailable(); + ClientOptions clientOptions = connection.getOptions(); + if (clientOptions == null || clientOptions.isAutoReconnect()) throw unavailable(); + RedisCommands commands = connection.sync(); + requireAccountAclIdentity(commands); + byte[] currentBytes = commands.get(key); + Long observedExpiry = commands.pexpiretime(key); + if (!boundedRegistryRecord(currentBytes) + || observedExpiry == null + || observedExpiry.longValue() != committedCandidate.registryAbsoluteExpiryMillis()) { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord currentRecord = + GameSessionAccountDelegationRegistryRecord.decode(currentBytes, maxRecordBytes); + final byte[] exactPendingBytes; + final GameSessionAccountDelegationRegistryRecord pendingRecord; + if ("pending".equals(currentRecord.state()) && currentRecord.registryVersion() == 1L) { + exactPendingBytes = currentBytes; + pendingRecord = currentRecord; + } else if ("active".equals(currentRecord.state()) && currentRecord.registryVersion() == 2L) { + exactPendingBytes = pendingRecordBytes(currentRecord); + pendingRecord = + GameSessionAccountDelegationRegistryRecord.decode(exactPendingBytes, maxRecordBytes); + } else { + throw unavailable(); + } + if (!committedCandidate.canonicalRegistryRecordSha256().equals(sha256(exactPendingBytes))) { + throw unavailable(); + } + PendingRegistrationReceipt reconstructed = + new PendingRegistrationReceipt( + pendingRecord, + committedCandidate.canonicalRegistryRecordSha256(), + committedCandidate.registryAbsoluteExpiryMillis(), + committedCandidate.registrationOutcome(), + committedCandidate.registrationLocalAofCount(), + committedCandidate.registrationReplicaAofCount()); + requireOwnerReceiptCorrespondence(reconstructed, committedCandidate); + requirePendingMatchesOwner( + pendingRecord, exactPendingBytes, reconstructed, committedCandidate); + return reconstructed; + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + /** + * Advances the two canonical Account authority projections on one private pinned connection. Each + * key uses a one-key script because issuer and Account keys intentionally have different Redis + * Cluster slots. No result is successful until one WAITAOF and exact byte readback of both + * projections completes on that same connection. + */ + public ProjectionPublicationOutcome publishAuthorityProjections( + java.util.UUID accountId, byte[] issuerProjectionBytes, byte[] accountProjectionBytes) { + return publishProjections(accountId, issuerProjectionBytes, accountProjectionBytes, null, null); + } + + public ProjectionPublicationOutcome publishSelectedAuthorityProjections( + java.util.UUID accountId, java.util.UUID tenantId, byte[][] values) { + if (TransactionSynchronizationManager.isActualTransactionActive() || tenantId == null) + throw unavailable(); + if (values == null || values.length != 4) throw unavailable(); + AccountSelectedGameplayAuthorityProjection.decode(values[2], null, tenantId); + AccountSelectedGameplayAuthorityProjection.decode(values[3], accountId, tenantId); + return publishProjections( + accountId, values[0], values[1], tenantId, new byte[][] {values[2], values[3]}); + } + + private ProjectionPublicationOutcome publishProjections( + java.util.UUID accountId, + byte[] issuerProjectionBytes, + byte[] accountProjectionBytes, + java.util.UUID tenantId, + byte[][] selected) { + Objects.requireNonNull(accountId, "Account UUID is required"); + AccountGameplayDelegationAuthorityProjection.ProjectionValue issuer = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + issuerProjectionBytes, "issuer", GameSessionAccountDelegationProfile.ISSUER); + AccountGameplayDelegationAuthorityProjection.ProjectionValue account = + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + accountProjectionBytes, "account", accountId.toString()); + if (!(AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .equals(issuer.key()) + || !(AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) + .equals(account.key())) { + throw unavailable(); + } + + RedisScriptDescriptor issuerDescriptor = requireIssuerProjectionDescriptor(); + RedisScriptDescriptor accountDescriptor = requireCanonicalAccountProjectionDescriptor(); + byte[] scriptSource = readScriptSource(issuerDescriptor); + byte[] accountScriptSource = readScriptSource(accountDescriptor); + if (!issuerDescriptor.sha256().equals(sha256(scriptSource)) + || !accountDescriptor.sha256().equals(sha256(accountScriptSource))) { + throw unavailable(); + } + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + + try { + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + String loadedSha = commands.scriptLoad(scriptSource); + if (loadedSha == null + || !SHA1.matcher(loadedSha).matches() + || !sha1(scriptSource).equals(loadedSha)) { + throw unavailable(); + } + byte[][] issuerProjectionArguments = {issuerProjectionBytes}; + Long issuerResult = + commands.evalsha( + loadedSha, + ScriptOutputType.INTEGER, + new byte[][] {ascii(issuer.key())}, + issuerProjectionArguments); + requireProjectionResult(issuerResult); + String accountSha = commands.scriptLoad(accountScriptSource); + if (accountSha == null || !sha1(accountScriptSource).equals(accountSha)) throw unavailable(); + byte[] accountKey = ascii(account.key()); + byte[] priorAccountBytes = commands.get(accountKey); + if (priorAccountBytes != null) { + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + priorAccountBytes, "account", accountId.toString()); + AccountGenerationProjection incoming = + AccountGenerationProjection.parse( + new String(accountProjectionBytes, StandardCharsets.UTF_8)); + AccountGenerationProjection stored = + AccountGenerationProjection.parse( + new String(priorAccountBytes, StandardCharsets.UTF_8)); + if (incoming.generationValue().compareTo(stored.generationValue()) < 0 + || incoming.sourceVersionValue().compareTo(stored.sourceVersionValue()) < 0 + || incoming.outboxSequenceValue().compareTo(stored.outboxSequenceValue()) < 0 + || (incoming.outboxSequenceValue().equals(stored.outboxSequenceValue()) + && !incoming.equals(stored))) throw unavailable(); + } + boolean exactAccount = Arrays.equals(priorAccountBytes, accountProjectionBytes); + Long accountResult = + commands.evalsha( + accountSha, + ScriptOutputType.INTEGER, + new byte[][] {accountKey}, + ascii(priorAccountBytes == null ? "ABSENT" : exactAccount ? "VERIFY" : "PRESENT"), + priorAccountBytes == null ? new byte[0] : priorAccountBytes, + exactAccount ? new byte[0] : accountProjectionBytes); + requireProjectionResult(accountResult); + boolean selectedReplay = true; + if (selected != null) { + if (!Long.valueOf(-1L).equals(commands.pttl(ascii(issuer.key())))) throw unavailable(); + for (int index = 0; index < 2; index++) { + var value = + AccountSelectedGameplayAuthorityProjection.decode( + selected[index], index == 0 ? null : accountId, tenantId); + var descriptor = requireSelectedProjectionDescriptor(index == 0); + byte[] selectedScript = readScriptSource(descriptor); + if (!descriptor.sha256().equals(sha256(selectedScript))) throw unavailable(); + String selectedSha = commands.scriptLoad(selectedScript); + if (!sha1(selectedScript).equals(selectedSha)) throw unavailable(); + byte[] key = ascii(value.key()); + byte[] prior = commands.get(key); + value.requireSuccessorOf( + prior == null + ? null + : AccountSelectedGameplayAuthorityProjection.decode( + prior, index == 0 ? null : accountId, tenantId)); + boolean exact = Arrays.equals(prior, selected[index]); + Long result = + commands.evalsha( + selectedSha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + ascii(prior == null ? "ABSENT" : exact ? "VERIFY" : "PRESENT"), + prior == null ? new byte[0] : prior, + exact ? new byte[0] : selected[index]); + requireProjectionResult(result); + selectedReplay &= result == 0L; + } + } + requireDurabilityAcknowledgement(commands); + byte[] issuerReadback = commands.get(ascii(issuer.key())); + byte[] accountReadback = commands.get(ascii(account.key())); + if (!Arrays.equals(issuerProjectionBytes, issuerReadback) + || !Arrays.equals(accountProjectionBytes, accountReadback) + || !Long.valueOf(-1L).equals(commands.pttl(accountKey))) { + throw unavailable(); + } + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + issuerReadback, "issuer", GameSessionAccountDelegationProfile.ISSUER); + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + accountReadback, "account", accountId.toString()); + if (selected != null) { + for (int index = 0; index < 2; index++) { + var value = + AccountSelectedGameplayAuthorityProjection.decode( + selected[index], index == 0 ? null : accountId, tenantId); + if (!Arrays.equals(selected[index], commands.get(ascii(value.key()))) + || !Long.valueOf(-1L).equals(commands.pttl(ascii(value.key())))) throw unavailable(); + } + } + return issuerResult == 0L && accountResult == 0L && selectedReplay + ? ProjectionPublicationOutcome.EXACT_RETRY + : ProjectionPublicationOutcome.PUBLISHED; + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + /** Reads both exact canonical authority keys over one role-checked pinned connection. */ + public byte[][] readAuthorityProjections(java.util.UUID accountId) { + return readProjections(accountId, null); + } + + public byte[][] readSelectedAuthorityProjections( + java.util.UUID accountId, java.util.UUID tenantId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + Objects.requireNonNull(tenantId, "Selected tenant UUID is required"); + return readProjections(accountId, tenantId); + } + + private byte[][] readProjections(java.util.UUID accountId, java.util.UUID tenantId) { + Objects.requireNonNull(accountId, "Account UUID is required"); + if (accountId.equals(new java.util.UUID(0L, 0L)) + || accountId.version() != 4 + || accountId.variant() != 2) { + throw new IllegalArgumentException("Canonical Account UUID is required"); + } + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + try { + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + byte[] issuer = + commands.get( + ascii( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER)); + byte[] account = + commands.get( + ascii(AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId)); + if (!boundedProjection(issuer) || !boundedProjection(account)) throw unavailable(); + if (!Long.valueOf(-1L) + .equals( + commands.pttl( + ascii( + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + + accountId)))) { + throw unavailable(); + } + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + issuer, "issuer", GameSessionAccountDelegationProfile.ISSUER); + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + account, "account", accountId.toString()); + if (tenantId != null) { + if (!Long.valueOf(-1L) + .equals( + commands.pttl( + ascii( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER)))) throw unavailable(); + byte[] tenantKey = + ascii(AccountSelectedGameplayAuthorityProjection.TENANT_PREFIX + tenantId); + byte[] membershipKey = + ascii( + AccountSelectedGameplayAuthorityProjection.MEMBERSHIP_PREFIX + + accountId + + ":" + + tenantId); + byte[] tenant = commands.get(tenantKey); + byte[] membership = commands.get(membershipKey); + AccountSelectedGameplayAuthorityProjection.decode(tenant, null, tenantId); + AccountSelectedGameplayAuthorityProjection.decode(membership, accountId, tenantId); + if (!Long.valueOf(-1L).equals(commands.pttl(tenantKey)) + || !Long.valueOf(-1L).equals(commands.pttl(membershipKey))) throw unavailable(); + return new byte[][] {issuer.clone(), account.clone(), tenant.clone(), membership.clone()}; + } + return new byte[][] {issuer.clone(), account.clone()}; + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + /** Pure exact PENDING observation; no script, WAITAOF, registration, activation or renewal. */ + public void requirePendingRecord(String tokenHash, byte[] expected, long expectedAbsoluteExpiry) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || tokenHash == null + || !TOKEN_HASH.matcher(tokenHash).matches() + || !boundedRegistryRecord(expected) + || expectedAbsoluteExpiry <= System.currentTimeMillis()) throw unavailable(); + try (var connection = connectionProvider.openPinnedConnection()) { + if (connection == null) throw unavailable(); + var commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + byte[] key = ascii(TOKEN_KEY_PREFIX + tokenHash); + if (!"string".equals(commands.type(key))) throw unavailable(); + byte[] actual = commands.get(key); + Long ttl = commands.pttl(key); + if (!Arrays.equals(actual, expected) + || !Long.valueOf(expectedAbsoluteExpiry).equals(commands.pexpiretime(key)) + || ttl == null + || ttl <= 0) throw unavailable(); + var record = GameSessionAccountDelegationRegistryRecord.decode(actual, maxRecordBytes); + if (!"pending".equals(record.state()) + || !tokenHash.equals(record.tokenHash()) + || record.expiresAtEpochSecond() <= Instant.now().getEpochSecond() + || !Arrays.equals(actual, commands.get(key)) + || !Long.valueOf(expectedAbsoluteExpiry).equals(commands.pexpiretime(key))) + throw unavailable(); + } catch (RuntimeException rejected) { + throw unavailable(); + } + } + + /** + * Reads one ACTIVE token record through Account's pinned, role-checked coordination connection. + * The returned value is deliberately metadata-only; callers must still compare it with the + * current committed Account issuance and verify the JWT signature/profile independently. + */ + public ActiveRegistryReadback readActiveRecord(String tokenHash) { + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw new IllegalArgumentException("Account token hash is malformed"); + } + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable(); + } + + final StatefulRedisConnection connection; + try { + connection = connectionProvider.openPinnedConnection(); + } catch (RuntimeException ex) { + throw unavailable(); + } + if (connection == null) throw unavailable(); + + byte[] activeBytes = null; + byte[] pendingBytes = null; + try { + RedisCommands commands = requirePinnedCommands(connection); + requireAccountAclIdentity(commands); + byte[] key = ascii(TOKEN_KEY_PREFIX + tokenHash); + activeBytes = commands.get(key); + Long absoluteExpiryMillis = commands.pexpiretime(key); + if (!boundedRegistryRecord(activeBytes) + || absoluteExpiryMillis == null + || absoluteExpiryMillis <= 0L) { + throw unavailable(); + } + GameSessionAccountDelegationRegistryRecord active = + GameSessionAccountDelegationRegistryRecord.decode(activeBytes, maxRecordBytes); + if (!"active".equals(active.state()) + || active.registryVersion() != 2L + || !tokenHash.equals(active.tokenHash())) { + throw unavailable(); + } + pendingBytes = pendingRecordBytes(active); + return new ActiveRegistryReadback( + active.tokenHash(), + active.accountId(), + active.jti(), + active.expiresAtEpochSecond(), + absoluteExpiryMillis, + sha256(pendingBytes)); + } catch (RuntimeException ex) { + if (ex instanceof AccountCoordinationRedisException) throw ex; + throw unavailable(); + } finally { + if (activeBytes != null) Arrays.fill(activeBytes, (byte) 0); + if (pendingBytes != null) Arrays.fill(pendingBytes, (byte) 0); + try { + connection.close(); + } catch (RuntimeException ex) { + throw unavailable(); + } + } + } + + private RedisScriptDescriptor requirePendingDescriptor() { + return requireExactDescriptor( + SCRIPT_ID, "account-game-session-delegation-pending-register.json"); + } + + private RedisScriptDescriptor requireActiveTransitionDescriptor() { + return requireExactDescriptor( + ACTIVE_TRANSITION_SCRIPT_ID, "account-game-session-delegation-activate-committed.json"); + } + + private void requireOwnerReceiptCorrespondence( + PendingRegistrationReceipt receipt, CommittedCandidateVerificationData committed) { + AccountGameplayDelegationPendingIdentity identity = committed.identity(); + var authority = committed.authoritySnapshot(); + var signer = committed.signerCorrespondence(); + if (!REQUIRED_ACL_IDENTITY.equals(receipt.aclIdentity()) + || !receipt.tokenKey().equals(TOKEN_KEY_PREFIX + receipt.tokenHash()) + || !receipt.operationId().equals(identity.operationId().toString()) + || !receipt.requestId().equals(identity.requestId().toString()) + || !receipt.requestDigest().equals(identity.requestDigest()) + || !receipt.accountId().equals(identity.accountId().toString()) + || !receipt.tokenJti().equals(identity.tokenJti().toString()) + || !receipt.tokenHash().equals(committed.tokenSha256()) + || !receipt.kid().equals(committed.signerKid()) + || !receipt.signerGeneration().equals(committed.signerGeneration()) + || !receipt.canonicalRecordSha256().equals(committed.canonicalRegistryRecordSha256()) + || !receipt.evidenceBundleReference().equals(committed.evidenceBundleReference()) + || receipt.issuedAtEpochSecond() != identity.issuedAtEpochSecond() + || receipt.notBeforeEpochSecond() != identity.notBeforeEpochSecond() + || receipt.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || receipt.issuanceFence() != authority.issuanceFence() + || receipt.registryVersion() != 1L + || receipt.localAofCount() < 1L + || receipt.replicaAofCount() < 1L + || !SHA256.matcher(committed.commitProofSha256()).matches() + || !"COMMITTED".equals(signer.promotionStatus()) + || !committed.signerKid().equals(signer.targetKid()) + || !committed.signerGeneration().equals(signer.targetGeneration())) { + throw unavailable(); + } + long expiresAtMillis; + try { + expiresAtMillis = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + long cleanupMargin = Math.subtractExact(receipt.absoluteExpiryMillis(), expiresAtMillis); + if (cleanupMargin < 0L || cleanupMargin > MAX_CLEANUP_MARGIN_MILLIS) throw unavailable(); + } catch (ArithmeticException ex) { + throw unavailable(); + } + if (identity.expiresAtEpochSecond() <= Instant.now().getEpochSecond()) throw unavailable(); + PendingIntent intent = + new PendingIntent( + identity.operationId(), + identity.requestId(), + identity.callerWorkload(), + identity.callerContextId(), + identity.tokenJti(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + authority, + identity.credentialRequestBinding()); + if (!AccountGameplayDelegationIssuanceRepository.requestDigest(intent) + .equals(identity.requestDigest())) { + throw unavailable(); + } + } + + private void requirePendingMatchesOwner( + GameSessionAccountDelegationRegistryRecord record, + byte[] canonicalBytes, + PendingRegistrationReceipt receipt, + CommittedCandidateVerificationData committed) { + AccountGameplayDelegationPendingIdentity identity = committed.identity(); + var authority = committed.authoritySnapshot(); + if (!"pending".equals(record.state()) + || record.registryVersion() != 1L + || !record.tokenHash().equals(receipt.tokenHash()) + || !record.tokenHash().equals(committed.tokenSha256()) + || !record.kid().equals(committed.signerKid()) + || !record.signerGeneration().equals(committed.signerGeneration()) + || !record.operationId().equals(identity.operationId().toString()) + || !record.requestId().equals(identity.requestId().toString()) + || !record.accountId().equals(identity.accountId().toString()) + || !record.requestDigest().equals(identity.requestDigest()) + || !record.jti().equals(identity.tokenJti().toString()) + || record.issuedAtEpochSecond() != identity.issuedAtEpochSecond() + || record.notBeforeEpochSecond() != identity.notBeforeEpochSecond() + || record.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || record.issuanceFence() != authority.issuanceFence() + || !record.evidenceBundleReference().equals(committed.evidenceBundleReference()) + || !SHA256.matcher(committed.canonicalRegistryRecordSha256()).matches() + || !committed.canonicalRegistryRecordSha256().equals(sha256(canonicalBytes)) + || !canonicalMapEquals( + record.fields().get("authorityTuple"), + GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff())) + || !canonicalMapEquals(record.fields().get("membershipVersion"), Map.of()) + || !canonicalMapEquals( + record.fields().get("authoritySourceVersions"), authority.sourceVersions()) + || !"1".equals(record.fields().get("tokenGeneration"))) { + throw unavailable(); + } + } + + private byte[] activeRecordBytes(GameSessionAccountDelegationRegistryRecord pendingRecord) { + if (!"pending".equals(pendingRecord.state()) || pendingRecord.registryVersion() != 1L) { + throw unavailable(); + } + Map activeFields = new LinkedHashMap<>(pendingRecord.fields()); + activeFields.put("registryVersion", 2); + activeFields.put("state", "active"); + try { + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(activeFields)); + if (!boundedRegistryRecord(canonical)) throw unavailable(); + return canonical; + } catch (IOException | RuntimeException ex) { + throw unavailable(); + } + } + + private byte[] pendingRecordBytes(GameSessionAccountDelegationRegistryRecord activeRecord) { + if (!"active".equals(activeRecord.state()) || activeRecord.registryVersion() != 2L) { + throw unavailable(); + } + Map pendingFields = new LinkedHashMap<>(activeRecord.fields()); + pendingFields.put("registryVersion", 1); + pendingFields.put("state", "pending"); + try { + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(pendingFields)); + if (!boundedRegistryRecord(canonical)) throw unavailable(); + return canonical; + } catch (IOException | RuntimeException ex) { + throw unavailable(); + } + } + + private static boolean canonicalMapEquals(Object value, Map expected) { + if (!(value instanceof Map actual)) return false; + try { + return Arrays.equals(canonicalJson(actual), canonicalJson(expected)); + } catch (RuntimeException ex) { + return false; + } + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException ex) { + throw unavailable(); + } + } + + private boolean boundedRegistryRecord(byte[] value) { + return value != null && value.length > 0 && value.length <= maxRecordBytes; + } + + private static Long exactInteger(Object value) { + if (!(value instanceof Number number)) return null; + String encoded = number.toString(); + if (!encoded.matches("0|[1-9][0-9]{0,18}")) return null; + try { + return Long.valueOf(encoded); + } catch (NumberFormatException ex) { + return null; + } + } + + private RedisScriptDescriptor requireIssuerProjectionDescriptor() { + return requireExactDescriptor( + ISSUER_PROJECTION_SCRIPT_ID, + "account-game-session-delegation-authority-project-issuer.json"); + } + + private RedisScriptDescriptor requireCanonicalAccountProjectionDescriptor() { + RedisScriptDescriptor expected = AccountGenerationProjectionRedisContract.descriptor(); + RedisScriptDescriptor actual = scriptCatalog.require(ACCOUNT_PROJECTION_SCRIPT_ID); + if (!expected.equals(actual)) throw unavailable(); + return actual; + } + + private RedisScriptDescriptor requireSelectedProjectionDescriptor(boolean tenant) { + return requireExactDescriptor( + tenant ? TENANT_PROJECTION_SCRIPT_ID : MEMBERSHIP_PROJECTION_SCRIPT_ID, + tenant + ? "account-selected-tenant-generation-projection.json" + : "account-selected-membership-generation-projection.json"); + } + + private RedisScriptDescriptor requireExactDescriptor(String scriptId, String resource) { + RedisScriptDescriptor descriptor = scriptCatalog.require(scriptId); + RedisScriptDescriptor expected = + AccountRedisScriptDescriptorLoader.load( + AccountGameplayDelegationRedisClient.class, "/redis/scripts/" + resource); + if (!scriptId.equals(expected.scriptId()) || !expected.equals(descriptor)) throw unavailable(); + return descriptor; + } + + private static RedisCommands requirePinnedCommands( + StatefulRedisConnection connection) { + if (!connection.isOpen()) throw unavailable(); + ClientOptions options = connection.getOptions(); + if (options == null || options.isAutoReconnect()) throw unavailable(); + return connection.sync(); + } + + private boolean boundedProjection(byte[] value) { + return value != null + && value.length > 0 + && value.length <= AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES; + } + + private static void requireProjectionResult(Long result) { + if (result == null || (result != 0L && result != 1L)) throw unavailable(); + } + + private byte[] readScriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = resourceClassLoader.getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_SOURCE_BYTES + 1); + if (bytes.length == 0 || bytes.length > MAX_SCRIPT_SOURCE_BYTES) throw unavailable(); + return bytes; + } catch (IOException ex) { + throw unavailable(); + } + } + + private static void requireAccountAclIdentity(RedisCommands commands) { + String identity = commands.aclWhoami(); + if (!REQUIRED_ACL_IDENTITY.equals(identity)) { + throw unavailable(); + } + } + + private Acknowledgement requireDurabilityAcknowledgement(RedisCommands commands) { + CommandArgs arguments = + new CommandArgs<>(ByteArrayCodec.INSTANCE) + .add(acknowledgementRequirements.requiredLocalAofCount()) + .add(acknowledgementRequirements.requiredReplicaAofCount()) + .add(acknowledgementRequirements.timeoutMillis()); + List counts = + commands.dispatch( + WaitAofCommand.INSTANCE, new ArrayOutput<>(ByteArrayCodec.INSTANCE), arguments); + if (counts == null || counts.size() != 2) throw unavailable(); + Object localCount = counts.get(0); + Object replicaCount = counts.get(1); + if (!(localCount instanceof Long local) + || !(replicaCount instanceof Long replicas) + || local < acknowledgementRequirements.requiredLocalAofCount() + || replicas < acknowledgementRequirements.requiredReplicaAofCount()) { + throw unavailable(); + } + return new Acknowledgement(local, replicas); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String sha256(byte[] bytes) { + return digest("SHA-256", bytes); + } + + private static String sha1(byte[] bytes) { + return digest("SHA-1", bytes); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw unavailable(); + } + } + + private static AccountCoordinationRedisException unavailable() { + return new AccountCoordinationRedisException(); + } + + @FunctionalInterface + public interface AccountCoordinationPinnedConnectionProvider { + /** + * Opens one private, dedicated, non-clustered Lettuce connection used for identity, script, + * acknowledgement, and readback. The provider must not return an ambient/default Spring + * connection, must disable automatic reconnect, and must preserve one pinned physical Redis + * connection for this invocation. This client checks the open and no-auto-reconnect contract + * before issuing any Redis command. + */ + StatefulRedisConnection openPinnedConnection(); + } + + public record AcknowledgementRequirements( + int requiredLocalAofCount, int requiredReplicaAofCount, int timeoutMillis) { + public AcknowledgementRequirements { + if (requiredLocalAofCount != 1 + || requiredReplicaAofCount < 1 + || requiredReplicaAofCount > 16 + || timeoutMillis < 1 + || timeoutMillis > 60_000) { + throw new IllegalArgumentException("WAITAOF requirements are outside the supported bound"); + } + } + } + + public enum PendingRegistrationOutcome { + CREATED, + EXACT_RETRY + } + + /** + * Exact non-authorizing proof that a PENDING registry value was written and read back after + * required WAITAOF acknowledgement on one role-checked pinned connection. The private constructor + * prevents callers from turning Redis presence, a DTO, or a configured role label into + * registration evidence. + */ + public static final class PendingRegistrationReceipt { + private final String tokenKey; + private final String canonicalRecordSha256; + private final String aclIdentity; + private final String operationId; + private final String requestId; + private final String requestDigest; + private final String accountId; + private final String tokenJti; + private final String tokenHash; + private final String kid; + private final String signerGeneration; + private final long issuedAtEpochSecond; + private final long notBeforeEpochSecond; + private final long expiresAtEpochSecond; + private final long issuanceFence; + private final long registryVersion; + private final GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference + evidenceBundleReference; + private final long absoluteExpiryMillis; + private final PendingRegistrationOutcome outcome; + private final long localAofCount; + private final long replicaAofCount; + + private PendingRegistrationReceipt( + GameSessionAccountDelegationRegistryRecord record, + String canonicalRecordSha256, + long absoluteExpiryMillis, + PendingRegistrationOutcome outcome, + long localAofCount, + long replicaAofCount) { + Objects.requireNonNull(record, "Verified pending registry record is required"); + if (!"pending".equals(record.state()) + || record.registryVersion() != 1L + || !TOKEN_HASH.matcher(canonicalRecordSha256).matches() + || absoluteExpiryMillis <= 0L + || localAofCount < 1L + || replicaAofCount < 1L) { + throw unavailable(); + } + long tokenExpiryMillis; + try { + tokenExpiryMillis = Math.multiplyExact(record.expiresAtEpochSecond(), 1_000L); + long cleanupMarginMillis = Math.subtractExact(absoluteExpiryMillis, tokenExpiryMillis); + if (cleanupMarginMillis < 0L || cleanupMarginMillis > MAX_CLEANUP_MARGIN_MILLIS) { + throw unavailable(); + } + } catch (ArithmeticException ex) { + throw unavailable(); + } + this.tokenKey = TOKEN_KEY_PREFIX + record.tokenHash(); + this.canonicalRecordSha256 = canonicalRecordSha256; + this.aclIdentity = REQUIRED_ACL_IDENTITY; + this.operationId = record.operationId(); + this.requestId = record.requestId(); + this.requestDigest = record.requestDigest(); + this.accountId = record.accountId(); + this.tokenJti = record.jti(); + this.tokenHash = record.tokenHash(); + this.kid = record.kid(); + this.signerGeneration = record.signerGeneration(); + this.issuedAtEpochSecond = record.issuedAtEpochSecond(); + this.notBeforeEpochSecond = record.notBeforeEpochSecond(); + this.expiresAtEpochSecond = record.expiresAtEpochSecond(); + this.issuanceFence = record.issuanceFence(); + this.registryVersion = record.registryVersion(); + this.evidenceBundleReference = record.evidenceBundleReference(); + this.absoluteExpiryMillis = absoluteExpiryMillis; + this.outcome = Objects.requireNonNull(outcome); + this.localAofCount = localAofCount; + this.replicaAofCount = replicaAofCount; + } + + public String tokenKey() { + return tokenKey; + } + + public String canonicalRecordSha256() { + return canonicalRecordSha256; + } + + public String aclIdentity() { + return aclIdentity; + } + + public String operationId() { + return operationId; + } + + public String requestId() { + return requestId; + } + + public String requestDigest() { + return requestDigest; + } + + public String accountId() { + return accountId; + } + + public String tokenJti() { + return tokenJti; + } + + public String tokenHash() { + return tokenHash; + } + + public String kid() { + return kid; + } + + public String signerGeneration() { + return signerGeneration; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long notBeforeEpochSecond() { + return notBeforeEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public long issuanceFence() { + return issuanceFence; + } + + public long registryVersion() { + return registryVersion; + } + + public GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference + evidenceBundleReference() { + return evidenceBundleReference; + } + + public long absoluteExpiryMillis() { + return absoluteExpiryMillis; + } + + public PendingRegistrationOutcome outcome() { + return outcome; + } + + public long localAofCount() { + return localAofCount; + } + + public long replicaAofCount() { + return replicaAofCount; + } + + @Override + public String toString() { + return "PendingRegistrationReceipt[redacted]"; + } + } + + public enum ActiveRegistrationOutcome { + ACTIVATED, + EXACT_RETRY + } + + /** + * Private-constructor metadata for an exact ACTIVE registry readback. This value is not a token + * credential and is not proof of player admission, response recovery, or current signer state + * beyond the committed owner data supplied to the transition. + */ + public static final class ActiveRegistrationReceipt { + private final String tokenKey; + private final String tokenHash; + private final String operationId; + private final String requestId; + private final String accountId; + private final String canonicalActiveRecordSha256; + private final String commitProofSha256; + private final long registryVersion; + private final long absoluteExpiryMillis; + private final ActiveRegistrationOutcome outcome; + private final long localAofCount; + private final long replicaAofCount; + + private ActiveRegistrationReceipt( + GameSessionAccountDelegationRegistryRecord record, + String canonicalActiveRecordSha256, + String commitProofSha256, + long absoluteExpiryMillis, + ActiveRegistrationOutcome outcome, + long localAofCount, + long replicaAofCount) { + Objects.requireNonNull(record, "Verified active registry record is required"); + if (!"active".equals(record.state()) + || record.registryVersion() != 2L + || !SHA256.matcher(canonicalActiveRecordSha256).matches() + || !SHA256.matcher(commitProofSha256).matches() + || absoluteExpiryMillis <= 0L + || localAofCount < 1L + || replicaAofCount < 1L) { + throw unavailable(); + } + this.tokenKey = TOKEN_KEY_PREFIX + record.tokenHash(); + this.tokenHash = record.tokenHash(); + this.operationId = record.operationId(); + this.requestId = record.requestId(); + this.accountId = record.accountId(); + this.canonicalActiveRecordSha256 = canonicalActiveRecordSha256; + this.commitProofSha256 = commitProofSha256; + this.registryVersion = record.registryVersion(); + this.absoluteExpiryMillis = absoluteExpiryMillis; + this.outcome = Objects.requireNonNull(outcome); + this.localAofCount = localAofCount; + this.replicaAofCount = replicaAofCount; + } + + public String tokenKey() { + return tokenKey; + } + + public String tokenHash() { + return tokenHash; + } + + public String operationId() { + return operationId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return accountId; + } + + public String canonicalActiveRecordSha256() { + return canonicalActiveRecordSha256; + } + + public String commitProofSha256() { + return commitProofSha256; + } + + public long registryVersion() { + return registryVersion; + } + + public long absoluteExpiryMillis() { + return absoluteExpiryMillis; + } + + public ActiveRegistrationOutcome outcome() { + return outcome; + } + + public long localAofCount() { + return localAofCount; + } + + public long replicaAofCount() { + return replicaAofCount; + } + + @Override + public String toString() { + return "ActiveRegistrationReceipt[redacted]"; + } + } + + private record Acknowledgement(long localAofCount, long replicaAofCount) {} + + public enum ProjectionPublicationOutcome { + PUBLISHED, + EXACT_RETRY + } + + public static final class AccountCoordinationRedisException extends IllegalStateException { + private AccountCoordinationRedisException() { + super("Account Coordination Redis operation is unavailable or ambiguous"); + } + } + + /** Metadata-only observation of a Redis ACTIVE record; it does not authenticate a caller. */ + public static final class ActiveRegistryReadback { + private final String tokenHash; + private final String accountId; + private final String jti; + private final long tokenExpiryEpochSecond; + private final long absoluteExpiryMillis; + private final String canonicalPendingRecordSha256; + + private ActiveRegistryReadback( + String tokenHash, + String accountId, + String jti, + long tokenExpiryEpochSecond, + long absoluteExpiryMillis, + String canonicalPendingRecordSha256) { + this.tokenHash = Objects.requireNonNull(tokenHash); + this.accountId = Objects.requireNonNull(accountId); + this.jti = Objects.requireNonNull(jti); + this.tokenExpiryEpochSecond = tokenExpiryEpochSecond; + this.absoluteExpiryMillis = absoluteExpiryMillis; + this.canonicalPendingRecordSha256 = Objects.requireNonNull(canonicalPendingRecordSha256); + } + + public String tokenHash() { + return tokenHash; + } + + public String accountId() { + return accountId; + } + + public String jti() { + return jti; + } + + public long tokenExpiryEpochSecond() { + return tokenExpiryEpochSecond; + } + + public long absoluteExpiryMillis() { + return absoluteExpiryMillis; + } + + public String canonicalPendingRecordSha256() { + return canonicalPendingRecordSha256; + } + + @Override + public String toString() { + return "ActiveRegistryReadback[redacted]"; + } + } + + private enum WaitAofCommand implements ProtocolKeyword { + INSTANCE; + + private static final byte[] BYTES = ascii("WAITAOF"); + + @Override + public byte[] getBytes() { + return BYTES.clone(); + } + + @Override + public String toString() { + return "WAITAOF"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java new file mode 100644 index 0000000000..6214afaa62 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisScriptContribution.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.accountservice.service.AccountRedisScriptDescriptorLoader; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; + +/** + * Account-owned descriptors for issuance registry transitions and current authority projections. + */ +public final class AccountGameplayDelegationRedisScriptContribution + implements RedisScriptContribution { + private static final String[] DESCRIPTOR_RESOURCES = { + "/redis/scripts/account-game-session-delegation-pending-register.json", + "/redis/scripts/account-game-session-delegation-activate-committed.json", + "/redis/scripts/account-game-session-delegation-authority-project-issuer.json", + "/redis/scripts/account-selected-tenant-generation-projection.json", + "/redis/scripts/account-selected-membership-generation-projection.json" + }; + + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + try { + java.util.ArrayList descriptors = + new java.util.ArrayList<>(DESCRIPTOR_RESOURCES.length); + for (String resource : DESCRIPTOR_RESOURCES) { + RedisScriptDescriptor descriptor = + AccountRedisScriptDescriptorLoader.load( + AccountGameplayDelegationRedisScriptContribution.class, resource); + if (!"account-service".equals(descriptor.owner())) { + throw new IllegalStateException("Account Redis descriptor owner is invalid"); + } + descriptors.add(descriptor); + } + if (descriptors.size() != 5 + || !descriptors.stream() + .map(RedisScriptDescriptor::scriptId) + .toList() + .equals( + List.of( + AccountGameplayDelegationRedisClient.SCRIPT_ID, + AccountGameplayDelegationRedisClient.ACTIVE_TRANSITION_SCRIPT_ID, + AccountGameplayDelegationRedisClient.ISSUER_PROJECTION_SCRIPT_ID, + AccountGameplayDelegationRedisClient.TENANT_PROJECTION_SCRIPT_ID, + AccountGameplayDelegationRedisClient.MEMBERSHIP_PROJECTION_SCRIPT_ID))) { + throw new IllegalStateException("Account Redis descriptor identities are invalid"); + } + return List.copyOf(descriptors); + } catch (RuntimeException ex) { + if (ex instanceof IllegalStateException state) throw state; + throw new IllegalStateException("Account Redis descriptor is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeService.java new file mode 100644 index 0000000000..5a3e29d053 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseEnvelopeService.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.PendingCandidateCredential; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Account-local orchestration for sealing one exact PENDING delegation candidate. + * + *

This service does not authenticate the supplied caller, invoke signing, reconcile a registry, + * transition lifecycle state, decrypt an envelope, or return a credential. Its result is only a + * non-authorizing metadata observation for the owning issuance workflow. + */ +@Service +public class AccountGameplayDelegationResponseEnvelopeService { + private final AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring transaction proxies require an extensible service; this constructor retains only" + + " a repository reference, with no sensitive or native partially initialized" + + " resources or finalizer") + public AccountGameplayDelegationResponseEnvelopeService( + AccountGameplayDelegationResponseEnvelopeRepository responseEnvelopes) { + this.responseEnvelopes = + Objects.requireNonNull( + responseEnvelopes, "Account response-envelope repository is required"); + } + + /** Persists the exact candidate only when every immutable owner identity still matches. */ + @Transactional(propagation = Propagation.MANDATORY) + public SealedCandidateObservation sealPendingCandidate( + UUID requestId, CallerIdentity caller, String exactCompactJwt) { + return responseEnvelopes.sealPendingCandidate(requestId, caller, exactCompactJwt); + } + + /** Opens exact durable PENDING bytes only for the internal signer verification retry. */ + @Transactional(propagation = Propagation.MANDATORY) + public PendingCandidateCredential openPendingCandidate(UUID requestId, CallerIdentity caller) { + return responseEnvelopes.openPendingCandidate(requestId, caller); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java new file mode 100644 index 0000000000..9cb048ccf9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java @@ -0,0 +1,1556 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.BoundTokenCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingSigningIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.PendingCandidateCredential; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.AccountJwtExactValues; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Account-internal producer for one exact pending Game Session delegation candidate. + * + *

This class is intentionally not a Spring component and declares no RPC. It re-reads the + * durable unbound issuance identity, requires Account's exact current COMMITTED signer owner + * evidence, validates the active mounted key against Account's authenticated current public + * projection, and seals that exact pending candidate for Account-owned recovery. It has no active + * registry transition or caller-facing credential response. + */ +public final class AccountGameplayDelegationSigner { + private static final Path PRIVATE_MOUNT_ROOT = privateSignerMountRoot(); + private static final Path PRIVATE_ACTIVE_BUNDLE = Path.of("current.key"); + private static final Path PUBLIC_MOUNT_ROOT = publicJwksMountRoot(); + private static final Path PUBLIC_JWKS = Path.of("jwks.json"); + private static final Duration PUBLIC_KEY_CACHE_AGE = Duration.ofSeconds(30); + private static final ExplicitRouteProfilePolicy GSA_SIGNING_POLICY = + new ExplicitRouteProfilePolicy( + "account-gameplay-delegation-signing-self-check", + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.TYPE, + GameSessionAccountDelegationProfile.ISSUER, + GameSessionAccountDelegationProfile.AUDIENCE, + GameSessionAccountDelegationJwtProfileValidator.REQUIRED_CLAIMS, + GameSessionAccountDelegationJwtProfileValidator.OPTIONAL_CLAIMS, + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS, + 5, + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES, + GameSessionAccountDelegationJwtProfileValidator::validateClaims); + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The interim Account private signing key uses this architecture-defined fixed protected mount; runtime configuration cannot redirect it or add a fallback.") + private static Path privateSignerMountRoot() { + return Path.of("/var/run/secrets/firemud/jwt"); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "Account signer correspondence reads this architecture-defined fixed public JWKS mount; runtime configuration cannot redirect it or add a fallback.") + private static Path publicJwksMountRoot() { + return Path.of("/var/run/secrets/firemud/jwks"); + } + + private final AccountGameplayDelegationIssuanceRepository issuanceRepository; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtJwksApiBinding apiBinding; + private final AccountJwtJwksTrustedSource trustedJwksSource; + private final AccountGameplayDelegationResponseEnvelopeService responseEnvelopeService; + private final TransactionTemplate accountTransaction; + private final Clock clock; + private final Path privateMountRoot; + private final Path privateBundlePath; + private final Path publicMountRoot; + private final Path publicJwksPath; + + public AccountGameplayDelegationSigner( + AccountGameplayDelegationIssuanceRepository issuanceRepository, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksApiBinding apiBinding, + AccountJwtJwksTrustedSource trustedJwksSource, + AccountGameplayDelegationResponseEnvelopeService responseEnvelopeService, + PlatformTransactionManager transactionManager, + Clock clock) { + this( + issuanceRepository, + desiredStateRepository, + materializerTrustBinding, + apiBinding, + trustedJwksSource, + responseEnvelopeService, + transactionManager, + clock, + PRIVATE_MOUNT_ROOT, + PRIVATE_ACTIVE_BUNDLE, + PUBLIC_MOUNT_ROOT, + PUBLIC_JWKS); + } + + AccountGameplayDelegationSigner( + AccountGameplayDelegationIssuanceRepository issuanceRepository, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksApiBinding apiBinding, + AccountJwtJwksTrustedSource trustedJwksSource, + AccountGameplayDelegationResponseEnvelopeService responseEnvelopeService, + PlatformTransactionManager transactionManager, + Clock clock, + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath) { + this.issuanceRepository = + Objects.requireNonNull(issuanceRepository, "Account issuance repository is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Account signer owner is required"); + this.materializerTrustBinding = + Objects.requireNonNull( + materializerTrustBinding, "Protected materializer trust is required"); + this.apiBinding = + Objects.requireNonNull(apiBinding, "Protected Account JWKS API binding is required"); + this.trustedJwksSource = + Objects.requireNonNull(trustedJwksSource, "Account authenticated JWKS source is required"); + this.responseEnvelopeService = + Objects.requireNonNull( + responseEnvelopeService, "Account response envelope owner is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + this.privateMountRoot = + Objects.requireNonNull(privateMountRoot, "Private mount root is required"); + this.privateBundlePath = + Objects.requireNonNull(privateBundlePath, "Private bundle path is required"); + this.publicMountRoot = Objects.requireNonNull(publicMountRoot, "Public mount root is required"); + this.publicJwksPath = Objects.requireNonNull(publicJwksPath, "Public JWKS path is required"); + } + + /** + * Signs and seals one Account-selected pending issuance by request ID. The result contains only + * non-authorizing candidate and encrypted-envelope metadata, never a compact JWT. + */ + CandidateOutcome signPendingCandidate(UUID requestId) { + if (requestId == null) { + throw unavailable(); + } + + byte[] transientCompactJwt = null; + byte[] firstJwksBytes = null; + byte[] finalJwksBytes = null; + AtomicReference compactTokenCapture = new AtomicReference<>(); + AtomicReference acquiredCandidate = new AtomicReference<>(); + PendingCandidateCredential openedCandidate = null; + try { + InvocationIdentity acquired = + accountTransaction.execute( + status -> { + CurrentSigner signer = currentCommittedSigner(); + PendingSigningIdentity pending = requireCurrentPendingIdentity(requestId); + requireUnexpired(pending); + PendingCandidateCredential resumed = + pending.persistedCandidate().isPresent() + ? responseEnvelopeService.openPendingCandidate( + requestId, + new CallerIdentity( + pending.identity().callerWorkload(), + pending.identity().callerContextId())) + : null; + if (resumed != null) { + PendingCandidateCredential replaced = acquiredCandidate.getAndSet(resumed); + if (replaced != null) replaced.close(); + requireOpenedCandidate(pending, resumed); + } + return new InvocationIdentity(signer, pending, resumed); + }); + openedCandidate = acquiredCandidate.getAndSet(null); + if (acquired == null) { + throw unavailable(); + } + final InvocationIdentity initial = acquired; + + SourceIdentity sourcePin = trustedJwksSource.sourceIdentity(); + PublicJwksSnapshot initialSnapshot = trustedJwksSource.load(); + firstJwksBytes = + requireExactTrustedSnapshot(initial.currentSigner(), sourcePin, initialSnapshot); + byte[] initialJwksProjection = firstJwksBytes; + AccountPublicJwksCache keyCache = + new AccountPublicJwksCache( + () -> { + PublicJwksSnapshot observed = trustedJwksSource.load(); + byte[] observedBytes = + requireExactTrustedSnapshot(initial.currentSigner(), sourcePin, observed); + try { + if (!Arrays.equals(initialJwksProjection, observedBytes)) { + throw new AccountPublicJwksCache.InvalidJwksException(); + } + return observed; + } finally { + wipe(observedBytes); + } + }, + sourcePin, + clock, + PUBLIC_KEY_CACHE_AGE); + keyCache.keyFor(initial.currentSigner().expectedIdentity().kid()); + + AccountMountedJwtSignerBundle.SignedDelegationDigest digest = null; + VerifiedCandidateIdentity candidateIdentity; + if (initial.resumedCandidate() == null) { + digest = + AccountMountedJwtSignerBundle.signCommittedGameplayDelegationDigest( + privateMountRoot, + privateBundlePath, + publicMountRoot, + publicJwksPath, + initial.currentSigner().expectedIdentity(), + new AccountMountedJwtSignerBundle.DelegationSigningSpec( + initial.pending().identity(), initial.pending().authoritySnapshot()), + (signed, exactCompactJwt) -> { + requireSignedIdentity(initial, signed); + byte[] transientCopy = exactCompactJwt.clone(); + if (!compactTokenCapture.compareAndSet(null, transientCopy)) { + wipe(transientCopy); + throw unavailable(); + } + }); + transientCompactJwt = compactTokenCapture.getAndSet(null); + if (transientCompactJwt == null + || !sha256(transientCompactJwt).equals(digest.compactTokenSha256())) { + throw unavailable(); + } + candidateIdentity = candidateIdentity(initial.pending(), digest); + } else { + PendingRegistryCandidate persisted = + initial + .pending() + .persistedCandidate() + .orElseThrow(AccountGameplayDelegationSigner::unavailable); + requirePersistedCandidateSigner(initial, persisted); + transientCompactJwt = initial.resumedCandidate().compactJwtBytes(); + candidateIdentity = candidateIdentity(initial.pending(), persisted); + if (!sha256(transientCompactJwt).equals(candidateIdentity.tokenSha256())) { + throw unavailable(); + } + } + String compactJwt = exactAscii(transientCompactJwt); + + VerifiedClaims verified = + new AccountAsymmetricJwtVerifier(keyCache, clock).verify(compactJwt, GSA_SIGNING_POLICY); + requireVerifiedClaims(initial, candidateIdentity, verified); + + PublicJwksSnapshot finalSnapshot = trustedJwksSource.load(); + finalJwksBytes = + requireExactTrustedSnapshot(initial.currentSigner(), sourcePin, finalSnapshot); + if (!Arrays.equals(firstJwksBytes, finalJwksBytes)) { + throw unavailable(); + } + + AccountMountedJwtSignerBundle.SignedDelegationDigest signedDigest = digest; + VerifiedCandidateIdentity verifiedCandidateIdentity = candidateIdentity; + CandidateOutcome outcome = + accountTransaction.execute( + status -> + initial.resumedCandidate() == null + ? bindAndSealWithinTransaction( + requestId, + compactJwt, + initial, + verifiedCandidateIdentity, + signedDigest, + sourcePin) + : resumeAndReadbackWithinTransaction( + requestId, initial, verifiedCandidateIdentity, sourcePin)); + if (outcome == null) { + throw unavailable(); + } + return outcome; + } catch (RuntimeException failure) { + // Never preserve implementation, parser, API, or JWT-bearing causes across this boundary. + throw unavailable(); + } finally { + wipe(transientCompactJwt); + wipe(compactTokenCapture.getAndSet(null)); + wipe(firstJwksBytes); + wipe(finalJwksBytes); + if (openedCandidate != null) openedCandidate.close(); + PendingCandidateCredential untransferredCandidate = acquiredCandidate.getAndSet(null); + if (untransferredCandidate != null) untransferredCandidate.close(); + } + } + + /** + * Revalidates signer-owned candidate evidence inside the caller's writable Account transaction. + * This method performs no signing, external JWKS/API request, mutation, or authorization effect. + */ + void requireCurrentCommittedSigner(PendingCandidateVerificationProof proof) { + if (proof == null + || !TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw unavailable(); + } + VerifiedPendingIdentity identity = proof.identity(); + long now = Math.floorDiv(clock.millis(), 1_000L); + long latestIssuedAt = now > Long.MAX_VALUE - 5L ? Long.MAX_VALUE : now + 5L; + if (now <= 0L + || identity.notBeforeEpochSecond() > now + || identity.issuedAtEpochSecond() > latestIssuedAt + || identity.expiresAtEpochSecond() <= now) { + throw unavailable(); + } + + CurrentSigner current = currentCommittedSigner(); + SourceIdentity originalSourceIdentity = proof.signerCorrespondence().publicJwksSourceIdentity(); + requireCurrentSourceIdentity(current, originalSourceIdentity); + if (!signerCorrespondence(current, originalSourceIdentity) + .equals(proof.signerCorrespondence())) { + throw unavailable(); + } + } + + /** + * Revalidates the exact signer correspondence captured by durable COMMITTED evidence inside a + * caller-owned writable Account transaction. It neither verifies a fabricated DTO nor signs, + * fetches public response data, mutates the operation, or authorizes token use. + */ + void requireCurrentCommittedSigner(CommittedCandidateVerificationData committed) { + if (committed == null + || !TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw unavailable(); + } + AuthenticatedSignerCorrespondence original = requireCommittedCandidateIdentity(committed); + + CurrentSigner current = currentCommittedSigner(); + SourceIdentity sourceIdentity = original.publicJwksSourceIdentity(); + requireCurrentSourceIdentity(current, sourceIdentity); + if (!signerCorrespondence(current, sourceIdentity).equals(original)) throw unavailable(); + } + + /** + * Revalidates COMMITTED signer metadata while allowing its generation to be historical for + * bounded response recovery. The current Account owner must still have one coherent COMMITTED + * ACTIVE signer under the exact original protected trust/API/source identity. The historical + * token key is checked separately against today's owner/readback-proved JWKS outside SQL. + */ + void requireCurrentCommittedRecoverySigner(CommittedCandidateVerificationData committed) { + if (committed == null + || !TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw unavailable(); + } + AuthenticatedSignerCorrespondence original = requireCommittedCandidateIdentity(committed); + + CurrentSigner current = currentCommittedSigner(); + requireCurrentSourceIdentity(current, original.publicJwksSourceIdentity()); + if (!current.binding().equals(original.binding()) + || !current.trust().equals(original.trustFence()) + || !current.api().bindingDigest().equals(original.apiBindingDigest()) + || !current.api().configRevision().equals(original.apiConfigRevision())) { + throw unavailable(); + } + } + + /** Confirms the original committed key has not been pruned or substituted in current JWKS. */ + void requireRetainedCommittedPublicKey(CommittedCandidateVerificationData committed) { + if (committed == null || TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable(); + } + AuthenticatedSignerCorrespondence original = requireCommittedCandidateIdentity(committed); + Optional currentFingerprint; + try { + if (!original.publicJwksSourceIdentity().equals(trustedJwksSource.sourceIdentity())) { + throw unavailable(); + } + PublicJwksSnapshot currentJwks = trustedJwksSource.load(); + currentFingerprint = + AccountJwtJwksTrustedSource.publicKeyFingerprint( + currentJwks, original.publicJwksSourceIdentity(), original.targetKid()); + } catch (RuntimeException unavailableSource) { + throw unavailable(); + } + if (currentFingerprint.isEmpty() + || !original.targetPublicKeyFingerprint().equals(currentFingerprint.orElseThrow())) { + throw unavailable(); + } + } + + private AuthenticatedSignerCorrespondence requireCommittedCandidateIdentity( + CommittedCandidateVerificationData committed) { + var identity = committed.identity(); + long now = Math.floorDiv(clock.millis(), 1_000L); + long latestIssuedAt = now > Long.MAX_VALUE - 5L ? Long.MAX_VALUE : now + 5L; + long expectedEnvelopeExpiry; + try { + expectedEnvelopeExpiry = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException invalidExpiry) { + throw unavailable(); + } + AuthenticatedSignerCorrespondence original = committed.signerCorrespondence(); + if (now <= 0L + || identity.notBeforeEpochSecond() > now + || identity.issuedAtEpochSecond() > latestIssuedAt + || identity.expiresAtEpochSecond() <= now + || !identity.accountId().equals(committed.authoritySnapshot().accountId()) + || !committed.evidenceBundleReference().canonicalSha256().matches("[0-9a-f]{64}") + || !committed.tokenSha256().matches("[0-9a-f]{64}") + || !committed.canonicalRegistryRecordSha256().matches("[0-9a-f]{64}") + || !committed.commitProofSha256().matches("[0-9a-f]{64}") + || !committed.envelopeSha256().matches("[0-9a-f]{64}") + || committed.envelopeBytesLength() < 1 + || committed.envelopeBytesLength() > 65_610 + || committed.envelopeKeyId() == null + || !committed.envelopeKeyId().matches("[A-Za-z0-9_-]{1,32}") + || expectedEnvelopeExpiry != committed.responseRecoveryExpiryEpochMillis() + || !committed.signerKid().equals(original.targetKid()) + || !committed.signerGeneration().equals(original.targetGeneration()) + || !"COMMITTED".equals(original.promotionStatus()) + || !original.privatePromotionDispatched() + || !original.promotionOperationId().equals(original.privatePromotionOperationId()) + || !original.promotionOperationId().equals(original.publicPromotionOperationId()) + || !original + .generationOperationId() + .equals(original.privatePromotionGenerationOperationId()) + || !"RS256".equals(original.targetAlgorithm()) + || !original.targetPublicKeyFingerprint().matches("[0-9a-f]{64}") + || original + .durableActive() + .filter( + active -> + active.generation().equals(committed.signerGeneration()) + && active.kid().equals(committed.signerKid())) + .isEmpty() + || original + .publishedActive() + .filter( + active -> + active.generation().equals(committed.signerGeneration()) + && active.kid().equals(committed.signerKid())) + .isEmpty()) { + throw unavailable(); + } + return original; + } + + private static void requireCurrentSourceIdentity( + CurrentSigner currentSigner, SourceIdentity sourceIdentity) { + if (sourceIdentity == null + || !currentSigner.binding().environmentId().equals(sourceIdentity.environmentId()) + || !currentSigner.binding().clusterId().equals(sourceIdentity.clusterId()) + || !currentSigner.binding().namespace().equals(sourceIdentity.namespace()) + || !currentSigner + .trust() + .expectedClusterIncarnationUid() + .equals(sourceIdentity.clusterIncarnationUid()) + || !currentSigner.trust().expectedNamespaceUid().equals(sourceIdentity.namespaceUid()) + || !currentSigner.api().configRevision().equals(sourceIdentity.bindingRevision()) + || !currentSigner.api().apiServer().toString().equals(sourceIdentity.apiServerOrigin()) + || !currentSigner.api().servingCaSha256().equals(sourceIdentity.servingCaSha256()) + || !currentSigner + .evidence() + .promotion() + .publicConfigMapUid() + .equals(sourceIdentity.configMapUid()) + || !currentSigner + .evidence() + .publicReceipt() + .configMapUid() + .equals(sourceIdentity.configMapUid())) { + throw unavailable(); + } + } + + private CandidateOutcome bindAndSealWithinTransaction( + UUID requestId, + String compactJwt, + InvocationIdentity initial, + VerifiedCandidateIdentity candidateIdentity, + AccountMountedJwtSignerBundle.SignedDelegationDigest digest, + SourceIdentity sourceIdentity) { + CurrentSigner currentBeforePersist = currentCommittedSigner(); + PendingSigningIdentity pendingBeforePersist = requireCurrentPendingIdentity(requestId); + requireUnexpired(pendingBeforePersist); + requireSameCommittedSigner(initial.currentSigner(), currentBeforePersist); + requireSamePendingIdentity(initial.pending(), pendingBeforePersist); + + BoundTokenCandidate bound = + issuanceRepository.bindSignedCandidate(requestId, compactJwt, digest.signerGeneration()); + requireBoundCandidate(requestId, candidateIdentity, bound); + + PendingRegistryCandidate persisted = issuanceRepository.readPendingRegistryCandidate(requestId); + requirePersistedCandidate(initial, candidateIdentity, persisted); + + SealedCandidateObservation sealed = + responseEnvelopeService.sealPendingCandidate( + requestId, + new CallerIdentity( + pendingBeforePersist.identity().callerWorkload(), + pendingBeforePersist.identity().callerContextId()), + compactJwt); + requireSealedCandidate(requestId, pendingBeforePersist, sealed); + + PendingRegistryCandidate finalReadback = + issuanceRepository.readPendingRegistryCandidate(requestId); + requirePersistedCandidate(initial, candidateIdentity, finalReadback); + CurrentSigner currentAfterPersist = currentCommittedSigner(); + requireSameCommittedSigner(initial.currentSigner(), currentAfterPersist); + + PendingCandidateVerificationProof verificationProof = + createVerificationProof( + pendingBeforePersist, + candidateIdentity, + finalReadback, + sealed, + currentAfterPersist, + sourceIdentity); + + return new CandidateOutcome( + pendingBeforePersist.identity().operationId(), + requestId, + candidateIdentity.tokenSha256(), + candidateIdentity.signerGeneration(), + candidateIdentity.kid(), + sealed, + verificationProof); + } + + private CandidateOutcome resumeAndReadbackWithinTransaction( + UUID requestId, + InvocationIdentity initial, + VerifiedCandidateIdentity candidateIdentity, + SourceIdentity sourceIdentity) { + CurrentSigner currentBeforePersist = currentCommittedSigner(); + PendingSigningIdentity pendingBeforePersist = requireCurrentPendingIdentity(requestId); + requireUnexpired(pendingBeforePersist); + requireSameCommittedSigner(initial.currentSigner(), currentBeforePersist); + requireSamePendingIdentity(initial.pending(), pendingBeforePersist); + + PendingRegistryCandidate persisted = issuanceRepository.readPendingRegistryCandidate(requestId); + requirePersistedCandidate(initial, candidateIdentity, persisted); + PendingCandidateCredential revalidatedEnvelope = + responseEnvelopeService.openPendingCandidate( + requestId, + new CallerIdentity( + pendingBeforePersist.identity().callerWorkload(), + pendingBeforePersist.identity().callerContextId())); + final SealedCandidateObservation sealed; + try { + sealed = revalidatedEnvelope.sealedCandidate(); + if (!sealed.equals(initial.resumedCandidate().sealedCandidate())) throw unavailable(); + } finally { + revalidatedEnvelope.close(); + } + + PendingRegistryCandidate finalReadback = + issuanceRepository.readPendingRegistryCandidate(requestId); + requirePersistedCandidate(initial, candidateIdentity, finalReadback); + CurrentSigner currentAfterPersist = currentCommittedSigner(); + requireSameCommittedSigner(initial.currentSigner(), currentAfterPersist); + + PendingCandidateVerificationProof verificationProof = + createVerificationProof( + pendingBeforePersist, + candidateIdentity, + finalReadback, + sealed, + currentAfterPersist, + sourceIdentity); + + return new CandidateOutcome( + pendingBeforePersist.identity().operationId(), + requestId, + candidateIdentity.tokenSha256(), + candidateIdentity.signerGeneration(), + candidateIdentity.kid(), + sealed, + verificationProof); + } + + private static PendingCandidateVerificationProof createVerificationProof( + PendingSigningIdentity pending, + VerifiedCandidateIdentity candidateIdentity, + PendingRegistryCandidate persisted, + SealedCandidateObservation sealed, + CurrentSigner currentSigner, + SourceIdentity sourceIdentity) { + byte[] canonicalRecord = persisted.canonicalRecordBytes(); + final String recordSha256; + try { + recordSha256 = sha256(canonicalRecord); + } finally { + wipe(canonicalRecord); + } + VerifiedPendingIdentity identity = + new VerifiedPendingIdentity( + persisted.identity().operationId(), + persisted.identity().requestId(), + persisted.identity().accountId(), + persisted.identity().callerWorkload(), + persisted.identity().callerContextId(), + persisted.identity().requestDigest(), + persisted.identity().tokenJti(), + persisted.identity().issuedAtEpochSecond(), + persisted.identity().notBeforeEpochSecond(), + persisted.identity().expiresAtEpochSecond()); + if (!identity.requestId().equals(candidateIdentity.requestId()) + || !identity.operationId().equals(candidateIdentity.operationId()) + || !identity.tokenJti().equals(candidateIdentity.jti()) + || candidateIdentity.issuedAtEpochSecond() != identity.issuedAtEpochSecond() + || candidateIdentity.notBeforeEpochSecond() != identity.notBeforeEpochSecond() + || candidateIdentity.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || persisted.authoritySnapshot() == null + || !persisted + .evidenceBundleReference() + .canonicalSha256() + .equals(pending.evidenceBundle().canonicalSha256()) + || !persisted.tokenHash().equals(candidateIdentity.tokenSha256()) + || !persisted.kid().equals(candidateIdentity.kid()) + || !persisted.signerGeneration().equals(candidateIdentity.signerGeneration())) { + throw unavailable(); + } + AuthenticatedSignerCorrespondence correspondence = + signerCorrespondence(currentSigner, sourceIdentity); + if (!persisted.authoritySnapshot().equals(pending.authoritySnapshot()) + || !correspondence + .generationOperationId() + .equals(UUID.fromString(currentSigner.expectedIdentity().operationId())) + || !correspondence.targetGeneration().equals(candidateIdentity.signerGeneration()) + || !correspondence.targetKid().equals(candidateIdentity.kid()) + || !correspondence + .targetPublicKeyFingerprint() + .equals(currentSigner.expectedIdentity().publicKeyFingerprint())) { + throw unavailable(); + } + return new PendingCandidateVerificationProof( + identity, + persisted.authoritySnapshot(), + persisted.evidenceBundleReference(), + persisted.tokenHash(), + recordSha256, + correspondence, + sealed); + } + + private static AuthenticatedSignerCorrespondence signerCorrespondence( + CurrentSigner currentSigner, SourceIdentity sourceIdentity) { + CommittedSignerEvidence evidence = currentSigner.evidence(); + var promotion = evidence.promotion(); + var generation = evidence.generationResult(); + var desiredState = evidence.desiredState(); + var privateReceipt = evidence.privateReceipt(); + var publicReceipt = evidence.publicReceipt(); + if (sourceIdentity == null + || !promotion.publicConfigMapUid().equals(sourceIdentity.configMapUid()) + || !promotion.apiBindingDigest().equals(currentSigner.api().bindingDigest()) + || !promotion.apiConfigRevision().equals(currentSigner.api().configRevision()) + || !publicReceipt.configMapUid().equals(sourceIdentity.configMapUid()) + || !privateReceipt.promotionOperationId().equals(promotion.operationId()) + || !privateReceipt.generationOperationId().equals(generation.operationId()) + || !publicReceipt.promotionOperationId().equals(promotion.operationId()) + || !generation.operationId().equals(promotion.generationOperationId()) + || !promotion.privatePromotionDispatched() + || promotion + .privatePromotionObservedResourceVersion() + .filter(privateReceipt.observedResourceVersion()::equals) + .isEmpty() + || promotion + .privatePromotionReceiptDigest() + .filter(privateReceipt.receiptDigest()::equals) + .isEmpty() + || promotion + .activeJwksObservedResourceVersion() + .filter(publicReceipt.observedResourceVersion()::equals) + .isEmpty() + || promotion + .activeJwksPublicDataDigest() + .filter(publicReceipt.publicDataDigest()::equals) + .isEmpty() + || promotion + .activeJwksReceiptDigest() + .filter(publicReceipt.receiptDigest()::equals) + .isEmpty()) { + throw unavailable(); + } + return new AuthenticatedSignerCorrespondence( + currentSigner.binding(), + currentSigner.trust(), + currentSigner.api().bindingDigest(), + currentSigner.api().configRevision(), + sourceIdentity, + desiredState.recordVersion(), + desiredState.durableActive(), + desiredState.publishedActive(), + promotion.operationId(), + promotion.requestDigest(), + promotion.expectedRecordVersion(), + promotion.expectedPreviousActive(), + promotion.expectedPreviousPublicKeyFingerprint(), + promotion.expectedPublishedActive(), + promotion.status(), + promotion.generationOperationId(), + promotion.generationOperationDigest(), + promotion.generationReceiptDigest(), + generation.desiredStateVersion(), + generation.privateSecretName(), + generation.secretUid(), + generation.expectedPriorResourceVersion(), + generation.observedResourceVersion(), + generation.targetGeneration(), + generation.targetKid(), + generation.targetAlgorithm(), + generation.publicKeyFingerprint(), + privateReceipt.observedResourceVersion(), + privateReceipt.receiptDigest(), + promotion.apiBindingDigest(), + promotion.apiConfigRevision(), + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + publicReceipt.priorResourceVersion(), + publicReceipt.observedResourceVersion(), + publicReceipt.publicDataDigest(), + publicReceipt.receiptDigest(), + promotion.prepublicationIntentDigest(), + promotion.prepublicationReceiptDigest(), + promotion.mountedObservationDigest(), + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + promotion.privatePromotionDispatched(), + privateReceipt.promotionOperationId(), + privateReceipt.generationOperationId(), + publicReceipt.promotionOperationId(), + promotion.privatePromotionObservedResourceVersion(), + promotion.privatePromotionReceiptDigest(), + promotion.activeJwksObservedResourceVersion(), + promotion.activeJwksPublicDataDigest(), + promotion.activeJwksReceiptDigest()); + } + + private byte[] requireExactTrustedSnapshot( + CurrentSigner currentSigner, SourceIdentity sourceIdentity, PublicJwksSnapshot snapshot) { + if (sourceIdentity == null + || snapshot == null + || !sourceIdentity.equals(snapshot.sourceIdentity()) + || !currentSigner.binding().environmentId().equals(sourceIdentity.environmentId()) + || !currentSigner.binding().clusterId().equals(sourceIdentity.clusterId()) + || !currentSigner.binding().namespace().equals(sourceIdentity.namespace()) + || !currentSigner + .trust() + .expectedClusterIncarnationUid() + .equals(sourceIdentity.clusterIncarnationUid()) + || !currentSigner.trust().expectedNamespaceUid().equals(sourceIdentity.namespaceUid()) + || !currentSigner + .evidence() + .promotion() + .publicConfigMapUid() + .equals(sourceIdentity.configMapUid()) + || !currentSigner + .evidence() + .publicReceipt() + .configMapUid() + .equals(sourceIdentity.configMapUid()) + || !currentSigner.api().configRevision().equals(sourceIdentity.bindingRevision()) + || !currentSigner.api().servingCaSha256().equals(sourceIdentity.servingCaSha256()) + || !currentSigner.api().apiServer().toString().equals(sourceIdentity.apiServerOrigin())) { + throw unavailable(); + } + byte[] jwksBytes = snapshot.jwksBytes(); + if (jwksBytes == null + || jwksBytes.length == 0 + || jwksBytes.length > AccountPublicJwksCache.MAX_JWKS_BYTES) { + wipe(jwksBytes); + throw unavailable(); + } + return jwksBytes; + } + + private PendingSigningIdentity requireCurrentPendingIdentity(UUID requestId) { + PendingSigningIdentity pending = issuanceRepository.readPendingSigningIdentity(requestId); + if (pending == null + || pending.identity() == null + || pending.authoritySnapshot() == null + || pending.evidenceBundle() == null + || !requestId.equals(pending.identity().requestId()) + || !pending.identity().accountId().equals(pending.authoritySnapshot().accountId()) + || !GameSessionAccountDelegationProfile.PROFILE.equals( + pending.evidenceBundle().fields().get("profile")) + || !GameSessionAccountDelegationProfile.AUDIENCE.equals( + pending.evidenceBundle().fields().get("audience"))) { + throw unavailable(); + } + return pending; + } + + private CurrentSigner currentCommittedSigner() { + AccountJwtSignerMaterializerTrustBinding.Binding materializer = + materializerTrustBinding + .current() + .orElseThrow(AccountGameplayDelegationSigner::unavailable); + AccountJwtJwksApiBinding.ParsedBinding api = apiBinding.current(); + if (!materializer.environmentId().equals(api.environmentId()) + || !materializer.clusterId().equals(api.clusterId()) + || !materializer.namespace().equals(api.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid())) { + throw unavailable(); + } + + AccountJwtSignerDesiredStateRepository.Binding binding = + new AccountJwtSignerDesiredStateRepository.Binding( + materializer.environmentId(), + materializer.clusterId(), + materializer.namespace(), + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + TrustFence trust = + new TrustFence( + materializer.expectedClusterIncarnationUid(), + materializer.expectedNamespaceUid(), + materializer.bindingDigest(), + materializer.configRevision()); + CommittedSignerEvidence evidence = + desiredStateRepository + .readCurrentCommittedSigner(binding, trust, api.bindingDigest(), api.configRevision()) + .orElseThrow(AccountGameplayDelegationSigner::unavailable); + return verifiedCurrentSigner(binding, trust, api, evidence); + } + + private static CurrentSigner verifiedCurrentSigner( + AccountJwtSignerDesiredStateRepository.Binding binding, + TrustFence trust, + AccountJwtJwksApiBinding.ParsedBinding api, + CommittedSignerEvidence evidence) { + var promotion = evidence.promotion(); + var generation = evidence.generationResult(); + ActiveSigner target = new ActiveSigner(generation.targetGeneration(), generation.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !binding.equals(promotion.binding()) + || !binding.equals(generation.binding()) + || !trust.equals(promotion.trustFence()) + || !trust.equals(generation.trustFence()) + || !promotion.generationOperationId().equals(generation.operationId()) + || !promotion.targetGeneration().equals(generation.targetGeneration()) + || !promotion.targetKid().equals(generation.targetKid()) + || !promotion.targetAlgorithm().equals("RS256") + || !generation.targetAlgorithm().equals("RS256") + || !promotion.targetPublicKeyFingerprint().equals(generation.publicKeyFingerprint()) + || evidence.desiredState().durableActive().filter(target::equals).isEmpty() + || evidence.desiredState().publishedActive().filter(target::equals).isEmpty() + || evidence.desiredState().preparedOperationId().isPresent() + || !evidence.privateReceipt().promotionOperationId().equals(promotion.operationId()) + || !evidence.publicReceipt().promotionOperationId().equals(promotion.operationId())) { + throw unavailable(); + } + AccountMountedJwtSignerBundle.ExpectedIdentity expected = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + generation.operationId().toString(), + generation.targetGeneration(), + generation.targetKid(), + generation.publicKeyFingerprint()); + return new CurrentSigner(binding, trust, api, evidence, expected); + } + + private static void requireSameCommittedSigner(CurrentSigner expected, CurrentSigner observed) { + if (!expected.equals(observed)) { + throw unavailable(); + } + } + + private void requireUnexpired(PendingSigningIdentity pending) { + long now = Math.floorDiv(clock.millis(), 1000L); + long latestIssuedAt = now > Long.MAX_VALUE - 5L ? Long.MAX_VALUE : now + 5L; + if (now <= 0L + || pending.identity().notBeforeEpochSecond() > now + || pending.identity().issuedAtEpochSecond() > latestIssuedAt + || pending.identity().expiresAtEpochSecond() <= now) { + throw unavailable(); + } + } + + private static void requireSignedIdentity( + InvocationIdentity initial, AccountMountedJwtSignerBundle.SignedDelegationDigest digest) { + PendingSigningIdentity pending = initial.pending(); + AccountMountedJwtSignerBundle.ExpectedIdentity signer = + initial.currentSigner().expectedIdentity(); + if (!digest.issuanceOperationId().equals(pending.identity().operationId()) + || !digest.requestId().equals(pending.identity().requestId()) + || !digest.jti().equals(pending.identity().tokenJti()) + || !digest.signerOperationId().equals(signer.operationId()) + || !digest.signerGeneration().equals(signer.generation()) + || !digest.kid().equals(signer.kid()) + || !digest.publicKeyFingerprint().equals(signer.publicKeyFingerprint()) + || digest.issuedAtEpochSecond() != pending.identity().issuedAtEpochSecond() + || digest.notBeforeEpochSecond() != pending.identity().notBeforeEpochSecond() + || digest.expiresAtEpochSecond() != pending.identity().expiresAtEpochSecond()) { + throw unavailable(); + } + } + + private static void requireVerifiedClaims( + InvocationIdentity initial, VerifiedCandidateIdentity candidate, VerifiedClaims verified) { + PendingSigningIdentity pending = initial.pending(); + AccountMountedJwtSignerBundle.ExpectedIdentity signer = + initial.currentSigner().expectedIdentity(); + Map claims = verified.claims(); + Object authorityTuple = claims.get("authorityTuple"); + Object expectedAuthorityTuple = + GameSessionAccountDelegationProfile.authorityTuple( + pending.authoritySnapshot().issuerGeneration(), + pending.authoritySnapshot().accountGeneration(), + pending.authoritySnapshot().accountSecurityCutoff()); + if (!GameSessionAccountDelegationProfile.PROFILE.equals(verified.profile()) + || !GameSessionAccountDelegationProfile.TYPE.equals(verified.tokenType()) + || !signer.kid().equals(verified.keyId()) + || !candidate.kid().equals(signer.kid()) + || !candidate.signerGeneration().equals(signer.generation()) + || !pending.identity().accountId().toString().equals(claims.get("sub")) + || !pending.identity().accountId().toString().equals(claims.get("accountId")) + || !pending.identity().tokenJti().toString().equals(claims.get("jti")) + || decimalCounterClaim(claims, "tokenGeneration") != 1L + || numberClaim(claims, "iat") != pending.identity().issuedAtEpochSecond() + || numberClaim(claims, "nbf") != pending.identity().notBeforeEpochSecond() + || numberClaim(claims, "exp") != pending.identity().expiresAtEpochSecond() + || decimalCounterClaim(claims, "issuanceFence") + != pending.authoritySnapshot().issuanceFence() + || !(claims.get("membershipVersion") instanceof Map membershipVersion) + || !membershipVersion.isEmpty() + || !(authorityTuple instanceof Map) + || !authorityTuple.equals(expectedAuthorityTuple) + || claims.containsKey("globalRoles") + || claims.containsKey("scopedRoles") + || !candidate.operationId().equals(pending.identity().operationId()) + || !candidate.requestId().equals(pending.identity().requestId()) + || !candidate.jti().equals(pending.identity().tokenJti()) + || candidate.issuedAtEpochSecond() != pending.identity().issuedAtEpochSecond() + || candidate.notBeforeEpochSecond() != pending.identity().notBeforeEpochSecond() + || candidate.expiresAtEpochSecond() != pending.identity().expiresAtEpochSecond() + || !candidate.tokenSha256().matches("[0-9a-f]{64}")) { + throw unavailable(); + } + } + + private static long numberClaim(Map claims, String field) { + Object value = claims.get(field); + if (!(value instanceof Number number)) { + throw unavailable(); + } + try { + return new java.math.BigDecimal(number.toString()).longValueExact(); + } catch (ArithmeticException | NumberFormatException malformed) { + throw unavailable(); + } + } + + private static long decimalCounterClaim(Map claims, String field) { + try { + return AccountJwtExactValues.positiveDecimalCounter(claims.get(field)).longValueExact(); + } catch (IllegalArgumentException | ArithmeticException malformed) { + throw unavailable(); + } + } + + private static void requireSamePendingIdentity( + PendingSigningIdentity expected, PendingSigningIdentity observed) { + if (!expected.identity().equals(observed.identity()) + || !expected.authoritySnapshot().equals(observed.authoritySnapshot()) + || !expected + .evidenceBundle() + .canonicalSha256() + .equals(observed.evidenceBundle().canonicalSha256()) + || !Arrays.equals( + expected.evidenceBundle().canonicalBytes(), observed.evidenceBundle().canonicalBytes()) + || !samePersistedCandidate(expected.persistedCandidate(), observed.persistedCandidate())) { + throw unavailable(); + } + } + + private static void requireBoundCandidate( + UUID requestId, VerifiedCandidateIdentity candidate, BoundTokenCandidate bound) { + if (bound == null + || !bound.requestId().equals(requestId) + || !bound.tokenHash().equals(candidate.tokenSha256()) + || !bound.signerGeneration().equals(candidate.signerGeneration()) + || !bound.kid().equals(candidate.kid())) { + throw unavailable(); + } + } + + private static void requirePersistedCandidate( + InvocationIdentity initial, + VerifiedCandidateIdentity candidateIdentity, + PendingRegistryCandidate persisted) { + if (persisted == null + || !persisted.identity().equals(initial.pending().identity()) + || !persisted.authoritySnapshot().equals(initial.pending().authoritySnapshot()) + || !persisted.tokenHash().equals(candidateIdentity.tokenSha256()) + || !persisted.kid().equals(candidateIdentity.kid()) + || !persisted.signerGeneration().equals(candidateIdentity.signerGeneration()) + || !persisted.identity().tokenJti().equals(candidateIdentity.jti()) + || persisted.identity().issuedAtEpochSecond() != candidateIdentity.issuedAtEpochSecond() + || persisted.identity().notBeforeEpochSecond() != candidateIdentity.notBeforeEpochSecond() + || persisted.expiresAtEpochSecond() != candidateIdentity.expiresAtEpochSecond() + || (initial.pending().persistedCandidate().isPresent() + && !samePersistedCandidate( + initial.pending().persistedCandidate(), Optional.of(persisted))) + || !matchesEvidenceBundleReference( + initial.pending(), persisted.evidenceBundleReference())) { + throw unavailable(); + } + } + + private static boolean samePersistedCandidate( + Optional expected, Optional observed) { + if (expected.isEmpty() || observed.isEmpty()) return expected.isEmpty() && observed.isEmpty(); + PendingRegistryCandidate left = expected.orElseThrow(); + PendingRegistryCandidate right = observed.orElseThrow(); + return left.identity().equals(right.identity()) + && left.tokenHash().equals(right.tokenHash()) + && left.kid().equals(right.kid()) + && left.signerGeneration().equals(right.signerGeneration()) + && left.expiresAtEpochSecond() == right.expiresAtEpochSecond() + && left.authoritySnapshot().equals(right.authoritySnapshot()) + && left.evidenceBundleReference().equals(right.evidenceBundleReference()) + && Arrays.equals(left.canonicalRecordBytes(), right.canonicalRecordBytes()); + } + + private static void requireOpenedCandidate( + PendingSigningIdentity pending, PendingCandidateCredential opened) { + PendingRegistryCandidate persisted = + pending.persistedCandidate().orElseThrow(AccountGameplayDelegationSigner::unavailable); + SealedCandidateObservation sealed = opened.sealedCandidate(); + long expectedExpiryMillis; + try { + expectedExpiryMillis = Math.multiplyExact(persisted.expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException invalidExpiry) { + throw unavailable(); + } + if (!persisted.identity().operationId().equals(sealed.operationId()) + || !persisted.identity().requestId().equals(sealed.requestId()) + || !persisted + .evidenceBundleReference() + .canonicalSha256() + .equals(sealed.authorityEvidenceBundleSha256()) + || persisted.authoritySnapshot().issuanceFence() != sealed.issuanceFence() + || expectedExpiryMillis != sealed.responseRecoveryExpiryEpochMillis()) { + throw unavailable(); + } + } + + private static void requirePersistedCandidateSigner( + InvocationIdentity initial, PendingRegistryCandidate persisted) { + AccountMountedJwtSignerBundle.ExpectedIdentity signer = + initial.currentSigner().expectedIdentity(); + PendingSigningIdentity pending = initial.pending(); + if (!persisted.identity().equals(pending.identity()) + || !persisted.authoritySnapshot().equals(pending.authoritySnapshot()) + || !persisted + .evidenceBundleReference() + .canonicalSha256() + .equals(pending.evidenceBundle().canonicalSha256()) + || !persisted.kid().equals(signer.kid()) + || !persisted.signerGeneration().equals(signer.generation()) + || !persisted.tokenHash().matches("[0-9a-f]{64}") + || persisted.expiresAtEpochSecond() != pending.identity().expiresAtEpochSecond()) { + throw unavailable(); + } + } + + private static VerifiedCandidateIdentity candidateIdentity( + PendingSigningIdentity pending, AccountMountedJwtSignerBundle.SignedDelegationDigest digest) { + if (!digest.issuanceOperationId().equals(pending.identity().operationId()) + || !digest.requestId().equals(pending.identity().requestId()) + || !digest.jti().equals(pending.identity().tokenJti())) { + throw unavailable(); + } + return new VerifiedCandidateIdentity( + digest.issuanceOperationId(), + digest.requestId(), + digest.jti(), + digest.kid(), + digest.signerGeneration(), + digest.issuedAtEpochSecond(), + digest.notBeforeEpochSecond(), + digest.expiresAtEpochSecond(), + digest.compactTokenSha256()); + } + + private static VerifiedCandidateIdentity candidateIdentity( + PendingSigningIdentity pending, PendingRegistryCandidate persisted) { + if (!persisted.identity().equals(pending.identity())) throw unavailable(); + return new VerifiedCandidateIdentity( + persisted.identity().operationId(), + persisted.identity().requestId(), + persisted.identity().tokenJti(), + persisted.kid(), + persisted.signerGeneration(), + persisted.identity().issuedAtEpochSecond(), + persisted.identity().notBeforeEpochSecond(), + persisted.expiresAtEpochSecond(), + persisted.tokenHash()); + } + + private static boolean matchesEvidenceBundleReference( + PendingSigningIdentity pending, EvidenceBundleReference actual) { + Object referenceValue = pending.evidenceBundle().fields().get("bundleRef"); + if (!(referenceValue instanceof Map reference)) { + return false; + } + return Objects.equals(reference.get("bundleVersion"), actual.bundleVersion()) + && Objects.equals(reference.get("sourceVersion"), actual.sourceVersion()) + && Objects.equals(reference.get("sourceFence"), actual.sourceFence()) + && Objects.equals(reference.get("linearization"), actual.linearization()) + && pending.evidenceBundle().canonicalSha256().equals(actual.canonicalSha256()); + } + + private static void requireSealedCandidate( + UUID requestId, PendingSigningIdentity pending, SealedCandidateObservation sealed) { + final long immutableExpiryMillis; + try { + immutableExpiryMillis = Math.multiplyExact(pending.identity().expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException invalidExpiry) { + throw unavailable(); + } + if (sealed == null + || !sealed.requestId().equals(requestId) + || !sealed.operationId().equals(pending.identity().operationId()) + || !sealed + .authorityEvidenceBundleSha256() + .equals(pending.evidenceBundle().canonicalSha256()) + || sealed.issuanceFence() != pending.authoritySnapshot().issuanceFence() + || sealed.responseRecoveryExpiryEpochMillis() != immutableExpiryMillis) { + throw unavailable(); + } + } + + private static String exactAscii(byte[] compactJwt) { + if (compactJwt == null + || compactJwt.length == 0 + || compactJwt.length > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES) { + throw unavailable(); + } + String value = new String(compactJwt, StandardCharsets.US_ASCII); + if (!Arrays.equals(compactJwt, value.getBytes(StandardCharsets.US_ASCII))) { + throw unavailable(); + } + return value; + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw AccountGameplayDelegationSigner.unavailable(); + } + } + + private static void wipe(byte[] bytes) { + if (bytes != null) { + Arrays.fill(bytes, (byte) 0); + } + } + + private static SigningUnavailableException unavailable() { + return new SigningUnavailableException(); + } + + private record CurrentSigner( + AccountJwtSignerDesiredStateRepository.Binding binding, + TrustFence trust, + AccountJwtJwksApiBinding.ParsedBinding api, + CommittedSignerEvidence evidence, + AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity) {} + + private record InvocationIdentity( + CurrentSigner currentSigner, + PendingSigningIdentity pending, + PendingCandidateCredential resumedCandidate) { + @Override + public String toString() { + return "InvocationIdentity[redacted]"; + } + } + + private record VerifiedCandidateIdentity( + UUID operationId, + UUID requestId, + UUID jti, + String kid, + String signerGeneration, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + String tokenSha256) { + private VerifiedCandidateIdentity { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(jti); + Objects.requireNonNull(kid); + Objects.requireNonNull(signerGeneration); + Objects.requireNonNull(tokenSha256); + if (!tokenSha256.matches("[0-9a-f]{64}")) throw unavailable(); + } + } + + /** + * Signer-produced evidence that one exact pending candidate passed local cryptographic and + * profile validation, was durably bound, sealed, and read back under unchanged owner fences. This + * is neither an issuance receipt nor authority to transition the registry to COMMITTED. + */ + public static final class PendingCandidateVerificationProof { + private final VerifiedPendingIdentity identity; + private final AccountAuthoritySnapshot authoritySnapshot; + private final EvidenceBundleReference evidenceBundleReference; + private final String tokenSha256; + private final String canonicalRegistryRecordSha256; + private final AuthenticatedSignerCorrespondence signerCorrespondence; + private final SealedCandidateObservation sealedCandidate; + + private PendingCandidateVerificationProof( + VerifiedPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot, + EvidenceBundleReference evidenceBundleReference, + String tokenSha256, + String canonicalRegistryRecordSha256, + AuthenticatedSignerCorrespondence signerCorrespondence, + SealedCandidateObservation sealedCandidate) { + this.identity = Objects.requireNonNull(identity); + this.authoritySnapshot = Objects.requireNonNull(authoritySnapshot); + this.evidenceBundleReference = Objects.requireNonNull(evidenceBundleReference); + this.tokenSha256 = Objects.requireNonNull(tokenSha256); + this.canonicalRegistryRecordSha256 = Objects.requireNonNull(canonicalRegistryRecordSha256); + this.signerCorrespondence = Objects.requireNonNull(signerCorrespondence); + this.sealedCandidate = Objects.requireNonNull(sealedCandidate); + final long immutableExpiryMillis; + try { + immutableExpiryMillis = Math.multiplyExact(identity.expiresAtEpochSecond(), 1_000L); + } catch (ArithmeticException invalidExpiry) { + throw unavailable(); + } + if (!identity.operationId().equals(sealedCandidate.operationId()) + || !identity.requestId().equals(sealedCandidate.requestId()) + || !identity.accountId().equals(authoritySnapshot.accountId()) + || !evidenceBundleReference + .canonicalSha256() + .equals(sealedCandidate.authorityEvidenceBundleSha256()) + || authoritySnapshot.issuanceFence() != sealedCandidate.issuanceFence() + || immutableExpiryMillis != sealedCandidate.responseRecoveryExpiryEpochMillis() + || !"COMMITTED".equals(signerCorrespondence.promotionStatus()) + || !signerCorrespondence.privatePromotionDispatched() + || !signerCorrespondence + .promotionOperationId() + .equals(signerCorrespondence.privatePromotionOperationId()) + || !signerCorrespondence + .promotionOperationId() + .equals(signerCorrespondence.publicPromotionOperationId()) + || !signerCorrespondence + .generationOperationId() + .equals(signerCorrespondence.privatePromotionGenerationOperationId()) + || signerCorrespondence + .durableActive() + .filter( + active -> + active.generation().equals(signerCorrespondence.targetGeneration()) + && active.kid().equals(signerCorrespondence.targetKid())) + .isEmpty() + || signerCorrespondence + .publishedActive() + .filter( + active -> + active.generation().equals(signerCorrespondence.targetGeneration()) + && active.kid().equals(signerCorrespondence.targetKid())) + .isEmpty() + || signerCorrespondence + .promotionPrivateObservedResourceVersion() + .filter(signerCorrespondence.privatePromotionObservedResourceVersion()::equals) + .isEmpty() + || signerCorrespondence + .promotionPrivateReceiptDigest() + .filter(signerCorrespondence.privatePromotionReceiptDigest()::equals) + .isEmpty() + || signerCorrespondence + .activeJwksObservedResourceVersion() + .filter(signerCorrespondence.observedPublicResourceVersion()::equals) + .isEmpty() + || signerCorrespondence + .activeJwksPublicDataDigest() + .filter(signerCorrespondence.publicDataDigest()::equals) + .isEmpty() + || signerCorrespondence + .activeJwksReceiptDigest() + .filter(signerCorrespondence.publicReceiptDigest()::equals) + .isEmpty() + || !signerCorrespondence + .publicConfigMapUid() + .equals(signerCorrespondence.publicJwksSourceIdentity().configMapUid()) + || !tokenSha256.matches("[0-9a-f]{64}") + || !canonicalRegistryRecordSha256.matches("[0-9a-f]{64}") + || !evidenceBundleReference.canonicalSha256().matches("[0-9a-f]{64}")) { + throw unavailable(); + } + } + + public VerifiedPendingIdentity identity() { + return identity; + } + + public UUID operationId() { + return identity.operationId(); + } + + public UUID requestId() { + return identity.requestId(); + } + + public UUID accountId() { + return identity.accountId(); + } + + public UUID tokenJti() { + return identity.tokenJti(); + } + + public long issuedAtEpochSecond() { + return identity.issuedAtEpochSecond(); + } + + public long notBeforeEpochSecond() { + return identity.notBeforeEpochSecond(); + } + + public long expiresAtEpochSecond() { + return identity.expiresAtEpochSecond(); + } + + public long issuanceFence() { + return authoritySnapshot.issuanceFence(); + } + + public AccountAuthoritySnapshot authoritySnapshot() { + return authoritySnapshot; + } + + public UUID signerOperationId() { + return signerCorrespondence.generationOperationId(); + } + + public String signerKid() { + return signerCorrespondence.targetKid(); + } + + public String signerGeneration() { + return signerCorrespondence.targetGeneration(); + } + + public EvidenceBundleReference evidenceBundleReference() { + return evidenceBundleReference; + } + + public String tokenSha256() { + return tokenSha256; + } + + public String canonicalRegistryRecordSha256() { + return canonicalRegistryRecordSha256; + } + + public AuthenticatedSignerCorrespondence signerCorrespondence() { + return signerCorrespondence; + } + + public SealedCandidateObservation sealedCandidate() { + return sealedCandidate; + } + + @Override + public String toString() { + return "PendingCandidateVerificationProof[redacted]"; + } + } + + /** Exact immutable pending identity read back from Account's issuance owner. */ + public record VerifiedPendingIdentity( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + String requestDigest, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond) { + public VerifiedPendingIdentity { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(accountId); + Objects.requireNonNull(callerWorkload); + Objects.requireNonNull(callerContextId); + Objects.requireNonNull(requestDigest); + Objects.requireNonNull(tokenJti); + } + + @Override + public String toString() { + return "VerifiedPendingIdentity[redacted]"; + } + } + + /** Public, byte-free projection of the exact authenticated committed signer source evidence. */ + public record AuthenticatedSignerCorrespondence( + AccountJwtSignerDesiredStateRepository.Binding binding, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + SourceIdentity publicJwksSourceIdentity, + long desiredStateRecordVersion, + java.util.Optional durableActive, + java.util.Optional publishedActive, + UUID promotionOperationId, + String promotionRequestDigest, + long promotionExpectedRecordVersion, + java.util.Optional expectedPreviousActive, + java.util.Optional expectedPreviousPublicKeyFingerprint, + java.util.Optional expectedPublishedActive, + String promotionStatus, + UUID generationOperationId, + String generationOperationDigest, + String generationReceiptDigest, + long generationDesiredStateVersion, + String privateSecretName, + String secretUid, + String expectedPriorSecretResourceVersion, + String observedSecretResourceVersion, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String targetPublicKeyFingerprint, + String privatePromotionObservedResourceVersion, + String privatePromotionReceiptDigest, + String promotionApiBindingDigest, + String promotionApiConfigRevision, + String publicConfigMapUid, + String expectedPublicResourceVersion, + String priorPublicResourceVersion, + String observedPublicResourceVersion, + String publicDataDigest, + String publicReceiptDigest, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + boolean privatePromotionDispatched, + UUID privatePromotionOperationId, + UUID privatePromotionGenerationOperationId, + UUID publicPromotionOperationId, + java.util.Optional promotionPrivateObservedResourceVersion, + java.util.Optional promotionPrivateReceiptDigest, + java.util.Optional activeJwksObservedResourceVersion, + java.util.Optional activeJwksPublicDataDigest, + java.util.Optional activeJwksReceiptDigest) { + public AuthenticatedSignerCorrespondence { + Objects.requireNonNull(binding); + Objects.requireNonNull(trustFence); + Objects.requireNonNull(apiBindingDigest); + Objects.requireNonNull(apiConfigRevision); + Objects.requireNonNull(publicJwksSourceIdentity); + Objects.requireNonNull(durableActive); + Objects.requireNonNull(publishedActive); + Objects.requireNonNull(promotionOperationId); + Objects.requireNonNull(expectedPreviousActive); + Objects.requireNonNull(expectedPreviousPublicKeyFingerprint); + Objects.requireNonNull(expectedPublishedActive); + Objects.requireNonNull(generationOperationId); + Objects.requireNonNull(privatePromotionOperationId); + Objects.requireNonNull(privatePromotionGenerationOperationId); + Objects.requireNonNull(publicPromotionOperationId); + Objects.requireNonNull(promotionPrivateObservedResourceVersion); + Objects.requireNonNull(promotionPrivateReceiptDigest); + Objects.requireNonNull(activeJwksObservedResourceVersion); + Objects.requireNonNull(activeJwksPublicDataDigest); + Objects.requireNonNull(activeJwksReceiptDigest); + } + + @Override + public String toString() { + return "AuthenticatedSignerCorrespondence[redacted]"; + } + } + + /** Non-authorizing metadata returned after the candidate and sealed envelope commit. */ + record CandidateOutcome( + UUID operationId, + UUID requestId, + String tokenSha256, + String signerGeneration, + String signerKid, + SealedCandidateObservation sealedCandidate, + PendingCandidateVerificationProof verificationProof) { + CandidateOutcome { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(tokenSha256); + Objects.requireNonNull(signerGeneration); + Objects.requireNonNull(signerKid); + Objects.requireNonNull(sealedCandidate); + Objects.requireNonNull(verificationProof); + if (!operationId.equals(verificationProof.operationId()) + || !requestId.equals(verificationProof.requestId()) + || !tokenSha256.equals(verificationProof.tokenSha256()) + || !signerGeneration.equals(verificationProof.signerGeneration()) + || !signerKid.equals(verificationProof.signerKid()) + || !sealedCandidate.equals(verificationProof.sealedCandidate())) { + throw unavailable(); + } + } + + @Override + public String toString() { + return "CandidateOutcome[redacted]"; + } + } + + static final class SigningUnavailableException extends IllegalStateException { + private SigningUnavailableException() { + super("Account gameplay delegation candidate is unavailable or ambiguous"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java new file mode 100644 index 0000000000..9bd587494e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistry.java @@ -0,0 +1,236 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Clock; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.PendingRegistryCandidate; +import net.firedevops.firemud.common.security.AccountJwtExactValues; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired Account Coordination Redis boundary for non-authorizing Game Session delegation records. + * + *

This registry writes the exact PENDING projection read from Account's durable issuance + * repository and exposes a separate package-scoped COMMITTED-to-ACTIVE transition for the committed + * owner. Both use the pinned Account Coordination client and exact readback/WAITAOF. It is not a + * token validator, Authenticate/HMAC path, signer-promotion, readiness, or response-recovery API; + * active owner metadata does not itself authorize player access or expose a credential. + */ +public final class AccountGameplayDelegationTokenRegistry { + private static final long MAX_CLEANUP_MARGIN_MILLIS = 300_000L; + + private final AccountGameplayDelegationIssuanceRepository issuanceRepository; + private final AccountGameplayDelegationRedisClient coordinationRedis; + private final Clock clock; + private final long maxEncodedBytes; + private final long cleanupMarginMillis; + + public AccountGameplayDelegationTokenRegistry( + AccountGameplayDelegationIssuanceRepository issuanceRepository, + AccountGameplayDelegationRedisClient coordinationRedis, + Clock clock, + long maxEncodedBytes, + long cleanupMarginMillis) { + this.issuanceRepository = + Objects.requireNonNull(issuanceRepository, "Account issuance repository is required"); + this.coordinationRedis = + Objects.requireNonNull(coordinationRedis, "Account Coordination Redis client is required"); + this.clock = Objects.requireNonNull(clock, "Clock is required"); + if (maxEncodedBytes <= 0L + || maxEncodedBytes > GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES) { + throw new IllegalArgumentException("Registry byte bound exceeds the finite profile ceiling"); + } + if (cleanupMarginMillis < 0L || cleanupMarginMillis > MAX_CLEANUP_MARGIN_MILLIS) { + throw new IllegalArgumentException("Registry cleanup margin is outside its finite bound"); + } + this.maxEncodedBytes = maxEncodedBytes; + this.cleanupMarginMillis = cleanupMarginMillis; + } + + /** + * CAS-writes the exact pending projection loaded from committed Account SQL state and reads it + * back byte-for-byte. The signed JWT is never accepted here, logged, returned, or stored. + */ + public AccountGameplayDelegationRedisClient.PendingRegistrationReceipt registerPending( + UUID requestId) { + Objects.requireNonNull(requestId, "Request ID is required"); + PendingRegistryCandidate candidate = issuanceRepository.readPendingRegistryCandidate(requestId); + var identity = candidate.identity(); + byte[] recordBytes = candidate.canonicalRecordBytes(); + if (recordBytes.length == 0 || recordBytes.length > maxEncodedBytes) { + throw new IllegalArgumentException("Pending registry record exceeds its finite byte bound"); + } + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.decode(recordBytes, maxEncodedBytes); + if (!"pending".equals(record.state()) + || !requestId.toString().equals(record.requestId()) + || !candidate.tokenHash().equals(record.tokenHash()) + || !candidate.kid().equals(record.kid()) + || !candidate.signerGeneration().equals(record.signerGeneration()) + || !identity.operationId().toString().equals(record.operationId()) + || !identity.requestId().toString().equals(record.requestId()) + || !identity.requestDigest().equals(record.requestDigest()) + || !identity.accountId().toString().equals(record.accountId()) + || !identity.tokenJti().toString().equals(record.jti()) + || identity.issuedAtEpochSecond() != record.issuedAtEpochSecond() + || identity.notBeforeEpochSecond() != record.notBeforeEpochSecond() + || identity.expiresAtEpochSecond() != record.expiresAtEpochSecond() + || candidate.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || !candidate.authoritySnapshot().accountId().equals(identity.accountId()) + || record.issuanceFence() != candidate.authoritySnapshot().issuanceFence() + || !candidate.evidenceBundleReference().equals(record.evidenceBundleReference()) + || !authorityTupleMatches(record.fields(), candidate) + || !authoritySourceVersionsMatch(record.fields(), candidate)) { + throw new IllegalStateException( + "Durable pending registry candidate does not match its record"); + } + + long nowMillis = clock.millis(); + if (nowMillis < 0L) throw new IllegalStateException("Clock returned a negative instant"); + long expiryMillis; + try { + expiryMillis = Math.multiplyExact(candidate.expiresAtEpochSecond(), 1000L); + expiryMillis = Math.addExact(expiryMillis, cleanupMarginMillis); + if (Math.subtractExact(expiryMillis, nowMillis) <= 0L) { + throw new IllegalArgumentException("Pending token is expired"); + } + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Pending registry TTL cannot be represented"); + } + + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt receipt = + coordinationRedis.registerPending(candidate.tokenHash(), recordBytes, expiryMillis); + requireExactReceipt(receipt, candidate, recordBytes, expiryMillis); + return receipt; + } + + /** + * Requires the exact ACTIVE Redis projection for an already-current COMMITTED Account owner read. + * This read grants no authority by itself and performs no registry activation. + */ + public AccountGameplayDelegationRedisClient.ActiveRegistryReadback requireExactActiveRecord( + CommittedCandidateVerificationData committedCandidate) { + Objects.requireNonNull(committedCandidate, "Current COMMITTED Account evidence is required"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Active registry reads must not run under Account SQL locks"); + } + AccountGameplayDelegationRedisClient.ActiveRegistryReadback active = + coordinationRedis.readActiveRecord(committedCandidate.tokenSha256()); + var identity = committedCandidate.identity(); + if (!committedCandidate.tokenSha256().equals(active.tokenHash()) + || !identity.accountId().toString().equals(active.accountId()) + || !identity.tokenJti().toString().equals(active.jti()) + || identity.expiresAtEpochSecond() != active.tokenExpiryEpochSecond() + || committedCandidate.registryAbsoluteExpiryMillis() != active.absoluteExpiryMillis() + || !committedCandidate + .canonicalRegistryRecordSha256() + .equals(active.canonicalPendingRecordSha256())) { + throw new IllegalStateException( + "ACTIVE registry state differs from the exact current COMMITTED Account issuance"); + } + return active; + } + + /** + * Performs the committed owner's exact Redis transition without holding Account SQL locks. The + * caller must obtain this repository-issued value in its own bounded transaction and revalidate + * current Account/signer ownership after this network operation. + */ + AccountGameplayDelegationRedisClient.ActiveRegistrationReceipt activateCommittedCandidate( + CommittedCandidateVerificationData committedCandidate) { + Objects.requireNonNull( + committedCandidate, "Repository-produced COMMITTED candidate evidence is required"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Account transaction must not span Coordination Redis work"); + } + var identity = committedCandidate.identity(); + long nowMillis = clock.millis(); + if (nowMillis <= 0L + || Math.floorDiv(nowMillis, 1_000L) >= identity.expiresAtEpochSecond() + || committedCandidate.registryAbsoluteExpiryMillis() <= nowMillis) { + throw new IllegalStateException("Committed Account issuance is expired or unavailable"); + } + return coordinationRedis.activateCommittedCandidate(committedCandidate); + } + + private static void requireExactReceipt( + AccountGameplayDelegationRedisClient.PendingRegistrationReceipt receipt, + PendingRegistryCandidate candidate, + byte[] canonicalRecordBytes, + long absoluteExpiryMillis) { + var identity = candidate.identity(); + if (receipt == null + || !receipt + .tokenKey() + .equals(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX + candidate.tokenHash()) + || !AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY.equals(receipt.aclIdentity()) + || !receipt.canonicalRecordSha256().equals(sha256(canonicalRecordBytes)) + || !receipt.operationId().equals(identity.operationId().toString()) + || !receipt.requestId().equals(identity.requestId().toString()) + || !receipt.requestDigest().equals(identity.requestDigest()) + || !receipt.accountId().equals(identity.accountId().toString()) + || !receipt.tokenJti().equals(identity.tokenJti().toString()) + || !receipt.tokenHash().equals(candidate.tokenHash()) + || !receipt.kid().equals(candidate.kid()) + || !receipt.signerGeneration().equals(candidate.signerGeneration()) + || receipt.issuedAtEpochSecond() != identity.issuedAtEpochSecond() + || receipt.notBeforeEpochSecond() != identity.notBeforeEpochSecond() + || receipt.expiresAtEpochSecond() != identity.expiresAtEpochSecond() + || receipt.issuanceFence() != candidate.authoritySnapshot().issuanceFence() + || receipt.registryVersion() != 1L + || !receipt.evidenceBundleReference().equals(candidate.evidenceBundleReference()) + || receipt.absoluteExpiryMillis() != absoluteExpiryMillis + || receipt.localAofCount() < 1L + || receipt.replicaAofCount() < 1L) { + throw new IllegalStateException("Account pending registration receipt is inconsistent"); + } + } + + private static boolean authorityTupleMatches( + Map fields, PendingRegistryCandidate candidate) { + Object value = fields.get("authorityTuple"); + if (!(value instanceof Map tuple)) return false; + Map expected = + GameSessionAccountDelegationProfile.authorityTuple( + candidate.authoritySnapshot().issuerGeneration(), + candidate.authoritySnapshot().accountGeneration(), + candidate.authoritySnapshot().accountSecurityCutoff()); + return expected.equals(tuple) + && fields.get("membershipVersion") instanceof Map membershipVersion + && membershipVersion.isEmpty(); + } + + private static boolean authoritySourceVersionsMatch( + Map fields, PendingRegistryCandidate candidate) { + Object value = fields.get("authoritySourceVersions"); + if (!(value instanceof Map versions)) return false; + return positive(versions.get("issuerSourceVersion")) + == candidate.authoritySnapshot().issuerSourceVersion() + && positive(versions.get("accountSourceVersion")) + == candidate.authoritySnapshot().accountSourceVersion() + && positive(versions.get("issuanceFenceSourceVersion")) + == candidate.authoritySnapshot().issuanceFenceSourceVersion(); + } + + private static long positive(Object value) { + try { + return AccountJwtExactValues.positiveDecimalCounter(value).longValueExact(); + } catch (IllegalArgumentException | ArithmeticException ex) { + return -1L; + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java new file mode 100644 index 0000000000..3f2077f190 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java @@ -0,0 +1,704 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Supplier; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * The Account-only Kubernetes adapter for the pre-created public {@code jwt-jwks} ConfigMap. Every + * write is a fixed-name, resourceVersion-guarded merge patch followed by exact readback. This class + * is intentionally not a lifecycle, readiness, or signer-promotion authority. + */ +public final class AccountJwtJwksConfigMapClient { + public static final String CONFIG_MAP_NAME = "jwt-jwks"; + public static final String JWKS_DATA_KEY = "jwks.json"; + public static final String GENERATION_DATA_KEY = "jwt-generation.json"; + public static final int MAX_DESIRED_VALUE_BYTES = 768 * 1024; + private static final int MAX_CONFIG_MAP_DATA_KEYS = 128; + private static final int MAX_CONFIG_MAP_DATA_BYTES = 1024 * 1024; + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Set ACCOUNT_DATA_KEYS = Set.of(JWKS_DATA_KEY, GENERATION_DATA_KEY); + private static final Set PRIVATE_JWK_FIELDS = + Set.of("d", "p", "q", "dp", "dq", "qi", "oth", "k"); + private static final byte[] SELF_SUBJECT_REVIEW_REQUEST = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}" + .getBytes(StandardCharsets.UTF_8); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final Supplier operationSupplier; + + /** Production constructor; API TLS and bearer handling remain inside the protected binding. */ + public AccountJwtJwksConfigMapClient(AccountJwtJwksApiBinding binding) { + AccountJwtJwksApiBinding requiredBinding = + Objects.requireNonNull(binding, "Account JWT JWKS API binding is required"); + this.operationSupplier = + () -> { + AccountJwtJwksApiBinding.ApiOperation operation = requiredBinding.beginOperation(); + return new ApiSession() { + @Override + public ParsedBinding binding() { + return operation.binding(); + } + + @Override + public ApiResponse send(ApiCall call, byte[] body) { + return operation.send(call, body); + } + + @Override + public void close() { + operation.close(); + } + }; + }; + } + + /** Deterministic bounded transport seam for focused tests. */ + AccountJwtJwksConfigMapClient(Supplier operationSupplier) { + this.operationSupplier = + Objects.requireNonNull(operationSupplier, "API operation supplier is required"); + } + + /** + * Returns only the independently protected non-secret API/destination pins. Callers can compare + * these with Account's materializer binding before creating durable publication intent. + */ + public BindingIdentity identity() { + try (ApiSession operation = beginOperation()) { + return toIdentity(operation.binding()); + } + } + + /** + * Reads only the fixed pre-created public ConfigMap after checking Account API identity and both + * namespace incarnation pins. No list, create, delete, or Secret endpoint is available. + */ + public ConfigMapSnapshot observe() { + try (ApiSession operation = beginOperation()) { + verifyEnvironment(operation); + return readConfigMap(operation); + } + } + + /** + * Applies an exact owner-authored public data map using Kubernetes resourceVersion CAS. Only + * {@code jwks.json} and {@code jwt-generation.json} are accepted; unrelated data is preserved. An + * ambiguous write is successful only after a fresh exact-content readback on the same UID. + */ + public CasObservation publish(ConfigMapSnapshot expected, Map desiredPublicData) { + Objects.requireNonNull(expected, "expected ConfigMap snapshot is required"); + Map desired = validateDesiredPublicData(desiredPublicData); + requireSnapshotIdentity(expected); + + try (ApiSession operation = beginOperation()) { + return publish(operation, expected, desired); + } + } + + /** + * Reconciles Account's exact active-marker transition from its durable prepublication RV. The + * freshly observed full snapshot preserves unrelated entries on a first write; an exact replay is + * accepted only when the live Account-owned data already matches and its RV advanced beyond the + * original prepublication fence. + */ + public CasObservation publishActiveProjection( + ConfigMapSnapshot observed, + String expectedPriorResourceVersion, + Map desiredPublicData) { + Objects.requireNonNull(observed, "fresh ConfigMap observation is required"); + Map desired = validateDesiredPublicData(desiredPublicData); + requireSnapshotIdentity(observed); + if (expectedPriorResourceVersion == null + || !RESOURCE_VERSION.matcher(expectedPriorResourceVersion).matches()) { + throw new IllegalArgumentException("Active ConfigMap prior resourceVersion is malformed"); + } + + try (ApiSession operation = beginOperation()) { + verifyEnvironment(operation); + ConfigMapSnapshot before = readConfigMap(operation); + if (!before.uid().equals(observed.uid()) + || !before.resourceVersion().equals(observed.resourceVersion()) + || !before.data().equals(observed.data())) { + throw conflict(before); + } + if (sameAccountData(before.data(), desired)) { + if (before.resourceVersion().equals(expectedPriorResourceVersion)) { + throw conflict(before); + } + return observationWithPrior( + expectedPriorResourceVersion, before, desired, Outcome.EXACT_REPLAY); + } + if (!before.resourceVersion().equals(expectedPriorResourceVersion)) { + throw conflict(before); + } + + byte[] patch = createMergePatch(before, desired); + verifyEnvironment(operation); + ApiResponse response; + try { + response = operation.send(ApiCall.PATCH_JWKS_CONFIG_MAP, patch); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + return reconcileUnknownWrite(operation, before, before, desired); + } + if (response.statusCode() == 409) { + verifyEnvironment(operation); + throw conflict(readConfigMap(operation)); + } + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (response.statusCode() >= 500 || response.statusCode() == 408) { + return reconcileUnknownWrite(operation, before, before, desired); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + ConfigMapSnapshot readback; + try { + verifyEnvironment(operation); + readback = readConfigMap(operation); + } catch (RuntimeException ex) { + throw new UncertainOutcomeException(); + } + requireExactPostcondition(before, before, readback, desired); + return observationWithPrior(expectedPriorResourceVersion, readback, desired, Outcome.APPLIED); + } + } + + private CasObservation publish( + ApiSession operation, ConfigMapSnapshot expected, Map desired) { + verifyEnvironment(operation); + ConfigMapSnapshot before = readConfigMap(operation); + if (!before.uid().equals(expected.uid())) { + throw conflict(before); + } + if (sameAccountData(before.data(), desired)) { + if (before.resourceVersion().equals(expected.resourceVersion())) { + throw conflict(before); + } + return observation(expected, before, desired, Outcome.EXACT_REPLAY); + } + if (!before.resourceVersion().equals(expected.resourceVersion())) { + throw conflict(before); + } + + byte[] patch = createMergePatch(expected, desired); + // Identity checks are repeated immediately before the only write call. + verifyEnvironment(operation); + ApiResponse response; + try { + response = operation.send(ApiCall.PATCH_JWKS_CONFIG_MAP, patch); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + return reconcileUnknownWrite(operation, expected, before, desired); + } + if (response.statusCode() == 409) { + verifyEnvironment(operation); + throw conflict(readConfigMap(operation)); + } + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (response.statusCode() >= 500 || response.statusCode() == 408) { + return reconcileUnknownWrite(operation, expected, before, desired); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + + ConfigMapSnapshot readback; + try { + verifyEnvironment(operation); + readback = readConfigMap(operation); + } catch (RuntimeException ex) { + throw new UncertainOutcomeException(); + } + requireExactPostcondition(expected, before, readback, desired); + return observation(expected, readback, desired, Outcome.APPLIED); + } + + private CasObservation reconcileUnknownWrite( + ApiSession operation, + ConfigMapSnapshot expected, + ConfigMapSnapshot before, + Map desired) { + try { + verifyEnvironment(operation); + ConfigMapSnapshot observed = readConfigMap(operation); + if (observed.uid().equals(expected.uid()) && sameAccountData(observed.data(), desired)) { + requirePreservedUnrelatedData(before, observed); + if (observed.resourceVersion().equals(expected.resourceVersion())) { + throw new UncertainOutcomeException(); + } + return observation(expected, observed, desired, Outcome.EXACT_REPLAY); + } + } catch (UncertainOutcomeException ex) { + throw ex; + } catch (RuntimeException ex) { + // The write outcome remains unknown when reconciliation itself is unavailable. + } + throw new UncertainOutcomeException(); + } + + private void requireExactPostcondition( + ConfigMapSnapshot expected, + ConfigMapSnapshot before, + ConfigMapSnapshot readback, + Map desired) { + if (!readback.uid().equals(expected.uid()) + || readback.resourceVersion().equals(expected.resourceVersion()) + || !sameAccountData(readback.data(), desired)) { + throw new UncertainOutcomeException(); + } + requirePreservedUnrelatedData(before, readback); + } + + private static void requirePreservedUnrelatedData( + ConfigMapSnapshot before, ConfigMapSnapshot after) { + Map previous = unrelatedData(before.data()); + Map current = unrelatedData(after.data()); + if (!previous.equals(current)) { + throw new UncertainOutcomeException(); + } + } + + private static Map unrelatedData(Map data) { + Map unrelated = new LinkedHashMap<>(); + data.forEach( + (key, value) -> { + if (!ACCOUNT_DATA_KEYS.contains(key)) { + unrelated.put(key, value); + } + }); + return Map.copyOf(unrelated); + } + + private ConfigMapSnapshot readConfigMap(ApiSession operation) { + ApiResponse response = send(operation, ApiCall.READ_JWKS_CONFIG_MAP, null); + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + return parseConfigMap(response.body(), operation.binding()); + } + + private void verifyEnvironment(ApiSession operation) { + ParsedBinding binding = operation.binding(); + ApiResponse selfReview = + send(operation, ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, SELF_SUBJECT_REVIEW_REQUEST); + if ((selfReview.statusCode() != 200 && selfReview.statusCode() != 201) + || !binding.expectedApiUsername().equals(parseAuthenticatedUsername(selfReview.body()))) { + throw new BindingRejectedException(); + } + verifyNamespace( + send(operation, ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null), + "kube-system", + binding.expectedClusterIncarnationUid()); + verifyNamespace( + send(operation, ApiCall.READ_TARGET_NAMESPACE, null), + binding.namespace(), + binding.expectedNamespaceUid()); + } + + private void verifyNamespace(ApiResponse response, String name, String expectedUid) { + if (!isSuccess(response.statusCode())) { + if (response.statusCode() == 404) { + throw new BindingRejectedException(); + } + throw new ApiFailureException(response.statusCode()); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode status = root.get("status"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"Namespace".equals(text(root.get("kind"))) + || metadata == null + || !name.equals(text(metadata.get("name"))) + || !expectedUid.equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || status == null + || !"Active".equals(text(status.get("phase")))) { + throw new BindingRejectedException(); + } + } + + private static String parseAuthenticatedUsername(byte[] bytes) { + JsonNode root = parseJson(bytes); + JsonNode status = root.get("status"); + JsonNode userInfo = status == null ? null : status.get("userInfo"); + String username = userInfo == null ? null : text(userInfo.get("username")); + JsonNode evaluationError = status == null ? null : status.get("evaluationError"); + if (!"authentication.k8s.io/v1".equals(text(root.get("apiVersion"))) + || !"SelfSubjectReview".equals(text(root.get("kind"))) + || username == null + || (evaluationError != null + && !evaluationError.isNull() + && (!evaluationError.isTextual() || !evaluationError.asText().isEmpty()))) { + throw new BindingRejectedException(); + } + return username; + } + + private static ConfigMapSnapshot parseConfigMap(byte[] bytes, ParsedBinding binding) { + JsonNode root = parseJson(bytes); + JsonNode metadata = root.get("metadata"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"ConfigMap".equals(text(root.get("kind"))) + || metadata == null + || !CONFIG_MAP_NAME.equals(text(metadata.get("name"))) + || !binding.namespace().equals(text(metadata.get("namespace"))) + || metadata.hasNonNull("deletionTimestamp") + || Boolean.TRUE.equals(booleanValue(root.get("immutable"))) + || (root.has("binaryData") && !root.get("binaryData").isNull())) { + throw new ApiFailureException(0); + } + String uid = canonicalUid(text(metadata.get("uid"))); + String resourceVersion = text(metadata.get("resourceVersion")); + if (resourceVersion == null || !RESOURCE_VERSION.matcher(resourceVersion).matches()) { + throw new ApiFailureException(0); + } + Map data = parseData(root.get("data")); + return new ConfigMapSnapshot(uid, resourceVersion, data); + } + + private static Map parseData(JsonNode dataNode) { + if (dataNode == null || dataNode.isNull()) { + return Map.of(); + } + if (!dataNode.isObject() || dataNode.size() > MAX_CONFIG_MAP_DATA_KEYS) { + throw new ApiFailureException(0); + } + Map data = new LinkedHashMap<>(); + int totalBytes = 0; + for (Map.Entry entry : dataNode.properties()) { + JsonNode value = entry.getValue(); + if (!value.isTextual()) { + throw new ApiFailureException(0); + } + String text = value.asText(); + totalBytes += text.getBytes(StandardCharsets.UTF_8).length; + if (totalBytes > MAX_CONFIG_MAP_DATA_BYTES) { + throw new ApiFailureException(0); + } + data.put(entry.getKey(), text); + } + return Map.copyOf(data); + } + + private ApiSession beginOperation() { + try { + return Objects.requireNonNull(operationSupplier.get(), "API operation is unavailable"); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (RuntimeException ex) { + throw new BindingRejectedException(); + } + } + + private ApiResponse send(ApiSession operation, ApiCall call, byte[] body) { + try { + return operation.send(call, body); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + throw new ApiFailureException(0); + } + } + + private static BindingIdentity toIdentity(ParsedBinding binding) { + return new BindingIdentity( + binding.bindingDigest(), + binding.configRevision(), + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.apiServer().toString(), + binding.tlsServerName(), + binding.servingCaSha256(), + binding.expectedApiUsername()); + } + + private static Map validateDesiredPublicData(Map desired) { + if (desired == null || !desired.keySet().equals(ACCOUNT_DATA_KEYS)) { + throw new IllegalArgumentException("Account public JWKS data keys are invalid"); + } + Map copy = new LinkedHashMap<>(); + int total = 0; + for (String key : ACCOUNT_DATA_KEYS) { + String value = desired.get(key); + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Account public JWKS data is incomplete"); + } + int length = value.getBytes(StandardCharsets.UTF_8).length; + if (length > MAX_DESIRED_VALUE_BYTES) { + throw new IllegalArgumentException("Account public JWKS data exceeds its bound"); + } + total += length; + copy.put(key, value); + } + if (total > MAX_CONFIG_MAP_DATA_BYTES) { + throw new IllegalArgumentException("Account public JWKS data exceeds its bound"); + } + validatePublicJwks(copy.get(JWKS_DATA_KEY)); + return Map.copyOf(copy); + } + + private static void validatePublicJwks(String jwks) { + JsonNode root = parseJson(jwks.getBytes(StandardCharsets.UTF_8)); + JsonNode keys = root.get("keys"); + if (!root.isObject() || root.size() != 1 || keys == null || !keys.isArray() || keys.isEmpty()) { + throw new IllegalArgumentException("Account public JWKS is malformed"); + } + for (JsonNode key : keys) { + if (!key.isObject()) { + throw new IllegalArgumentException("Account public JWKS is malformed"); + } + for (String privateField : PRIVATE_JWK_FIELDS) { + if (key.has(privateField)) { + throw new IllegalArgumentException("Account public JWKS contains private material"); + } + } + } + } + + private static byte[] createMergePatch(ConfigMapSnapshot expected, Map desired) { + Map metadata = new LinkedHashMap<>(); + metadata.put("uid", expected.uid()); + metadata.put("resourceVersion", expected.resourceVersion()); + Map patch = new LinkedHashMap<>(); + patch.put("metadata", metadata); + patch.put("data", desired); + try { + return STRICT_JSON.writeValueAsBytes(patch); + } catch (Exception ex) { + throw new IllegalStateException("Account public JWKS patch could not be encoded"); + } + } + + private static boolean sameAccountData(Map current, Map desired) { + return desired.get(JWKS_DATA_KEY).equals(current.get(JWKS_DATA_KEY)) + && desired.get(GENERATION_DATA_KEY).equals(current.get(GENERATION_DATA_KEY)); + } + + private static CasObservation observation( + ConfigMapSnapshot expected, + ConfigMapSnapshot observed, + Map desired, + Outcome outcome) { + Map exactOutput = new LinkedHashMap<>(); + exactOutput.put(JWKS_DATA_KEY, desired.get(JWKS_DATA_KEY)); + exactOutput.put(GENERATION_DATA_KEY, desired.get(GENERATION_DATA_KEY)); + return new CasObservation( + observed.uid(), + expected.resourceVersion(), + observed.resourceVersion(), + exactOutput, + observed.data(), + outcome); + } + + private static CasObservation observationWithPrior( + String priorResourceVersion, + ConfigMapSnapshot observed, + Map desired, + Outcome outcome) { + Map exactOutput = new LinkedHashMap<>(); + exactOutput.put(JWKS_DATA_KEY, desired.get(JWKS_DATA_KEY)); + exactOutput.put(GENERATION_DATA_KEY, desired.get(GENERATION_DATA_KEY)); + return new CasObservation( + observed.uid(), + priorResourceVersion, + observed.resourceVersion(), + exactOutput, + observed.data(), + outcome); + } + + private static CasConflictException conflict(ConfigMapSnapshot observed) { + return new CasConflictException(observed.uid(), observed.resourceVersion()); + } + + private static void requireSnapshotIdentity(ConfigMapSnapshot snapshot) { + if (!validUid(snapshot.uid()) + || snapshot.resourceVersion() == null + || !RESOURCE_VERSION.matcher(snapshot.resourceVersion()).matches()) { + throw new IllegalArgumentException("Expected ConfigMap snapshot identity is malformed"); + } + } + + private static boolean isSuccess(int statusCode) { + return statusCode >= 200 && statusCode < 300; + } + + private static JsonNode parseJson(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CONFIG_MAP_DATA_BYTES) { + throw new ApiFailureException(0); + } + try { + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || !root.isObject()) { + throw new ApiFailureException(0); + } + return root; + } catch (CharacterCodingException | RuntimeException ex) { + throw new ApiFailureException(0); + } + } + + private static String text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + @SuppressFBWarnings( + value = "NP_BOOLEAN_RETURN_NULL", + justification = + "The parser intentionally preserves absent or malformed booleans as unknown; callers require explicit true.") + private static Boolean booleanValue(JsonNode node) { + return node != null && node.isBoolean() ? node.booleanValue() : null; + } + + private static String canonicalUid(String value) { + if (!validUid(value)) { + throw new ApiFailureException(0); + } + return value; + } + + private static boolean validUid(String value) { + return value != null + && UID.matcher(value).matches() + && !"00000000-0000-0000-0000-000000000000".equals(value); + } + + interface ApiSession extends AutoCloseable { + ParsedBinding binding(); + + ApiResponse send(ApiCall call, byte[] body); + + @Override + void close(); + } + + public record BindingIdentity( + String bindingDigest, + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String apiServerUrl, + String tlsServerName, + String servingCaSha256, + String expectedApiUsername) {} + + public record ConfigMapSnapshot(String uid, String resourceVersion, Map data) { + public ConfigMapSnapshot { + data = data == null ? Map.of() : Map.copyOf(data); + } + } + + public record CasObservation( + String uid, + String priorResourceVersion, + String resourceVersion, + Map publishedData, + Map readbackData, + Outcome outcome) { + public CasObservation { + publishedData = Map.copyOf(publishedData); + readbackData = Map.copyOf(readbackData); + } + } + + public enum Outcome { + APPLIED, + EXACT_REPLAY + } + + public static class ResourceMissingException extends RuntimeException { + public ResourceMissingException() { + super("Pre-created Account public JWKS ConfigMap is unavailable"); + } + } + + public static class CasConflictException extends RuntimeException { + private final String observedUid; + private final String observedResourceVersion; + + public CasConflictException(String observedUid, String observedResourceVersion) { + super("Account public JWKS ConfigMap compare-and-set conflict"); + this.observedUid = observedUid; + this.observedResourceVersion = observedResourceVersion; + } + + public String observedUid() { + return observedUid; + } + + public String observedResourceVersion() { + return observedResourceVersion; + } + } + + public static class UncertainOutcomeException extends RuntimeException { + public UncertainOutcomeException() { + super("Account public JWKS ConfigMap write outcome is uncertain"); + } + } + + public static class ApiFailureException extends RuntimeException { + private final int statusCode; + + public ApiFailureException(int statusCode) { + super("Account public JWKS Kubernetes API request failed"); + this.statusCode = statusCode; + } + + public int statusCode() { + return statusCode; + } + } + + public static class BindingRejectedException extends RuntimeException { + public BindingRejectedException() { + super("Account public JWKS API binding or identity was rejected"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java new file mode 100644 index 0000000000..4742f95fed --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java @@ -0,0 +1,761 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.math.BigInteger; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned authenticated read adapter for the current public JWKS publication. + * + *

The cache pin is derived from Account's root-protected Kubernetes API binding and exact + * Account-owned publication evidence. The first receipt-backed PREPUBLISHED key can be served to + * readiness probes before a signer is committed, but is never represented as active authority. + * During ordinary prepublication of a next key, the prior committed key remains the only active + * signer while the exact new public set may be served for validation overlap. PREPARED and + * unexplained resource changes deny. This adapter exposes only public JWKS bytes and grants no + * signing, registry, readiness, or admission authority. + */ +public final class AccountJwtJwksTrustedSource + implements AccountPublicJwksCache.TrustedPublicJwksSource { + private static final int MAX_JWKS_BYTES = 256 * 1024; + private static final int MAX_MARKER_BYTES = 16 * 1024; + private static final String ACCOUNT_SERVICE_USERNAME_PREFIX = "system:serviceaccount:"; + private static final String ACCOUNT_SERVICE_NAME = "account-service"; + private static final int MAX_KEYS = 64; + private static final java.util.Set JWKS_FIELDS = java.util.Set.of("keys"); + private static final java.util.Set JWK_FIELDS = + java.util.Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountJwtJwksConfigMapClient configMapClient; + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPublicationRepository publicationRepository; + private final TransactionTemplate accountTransaction; + private final Object pinMonitor = new Object(); + + private volatile TrustedPin trustedPin; + + /** Constructs an inactive adapter over Account's real protected API and owner-recorded state. */ + public AccountJwtJwksTrustedSource( + AccountJwtJwksConfigMapClient configMapClient, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + PlatformTransactionManager transactionManager) { + this.configMapClient = + Objects.requireNonNull(configMapClient, "Account ConfigMap client is required"); + this.materializerTrustBinding = + Objects.requireNonNull(materializerTrustBinding, "Protected Account trust is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Account signer repository is required"); + this.publicationRepository = + Objects.requireNonNull(publicationRepository, "Account publication repository is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.accountTransaction.setReadOnly(false); + } + + /** + * Establishes the immutable cache pin from a coherent, protected Account read. A cache owner + * obtains its expected source identity here; it is not accepted as caller-supplied evidence. + */ + public SourceIdentity sourceIdentity() { + TrustedPin current = trustedPin; + if (current != null) { + return current.sourceIdentity(); + } + synchronized (pinMonitor) { + current = trustedPin; + if (current == null) { + VerifiedSource verified = readVerifiedSource(); + current = verified.pin(); + trustedPin = current; + } + } + return current.sourceIdentity(); + } + + /** + * Derives one key's RFC 7638 fingerprint from a snapshot already loaded through this trusted + * source. It compares the immutable pin and grants no signer, registry, or token authority. + */ + static Optional publicKeyFingerprint( + PublicJwksSnapshot snapshot, SourceIdentity expectedSourceIdentity, String kid) { + if (snapshot == null + || expectedSourceIdentity == null + || !expectedSourceIdentity.equals(snapshot.sourceIdentity()) + || kid == null + || !kid.matches("[A-Za-z0-9_-]{1,64}")) { + throw rejected(); + } + Map fingerprints = + publicKeyFingerprints(new String(snapshot.jwksBytes(), StandardCharsets.UTF_8)); + return Optional.ofNullable(fingerprints.get(kid)); + } + + /** + * Loads one exact public JWKS snapshot after checking Account trust and receipt readback twice. + */ + @Override + public PublicJwksSnapshot load() { + TrustedPin expected = trustedPin; + if (expected == null) { + throw rejected(); + } + VerifiedSource verified = readVerifiedSource(); + if (!expected.equals(verified.pin())) { + throw rejected(); + } + return new PublicJwksSnapshot(expected.sourceIdentity(), verified.jwksBytes()); + } + + private VerifiedSource readVerifiedSource() { + Binding materializerBefore = currentMaterializerBinding(); + BindingIdentity apiBefore = currentApiIdentity(); + requireBindingsAgree(materializerBefore, apiBefore); + TrustedPin alreadyPinned = trustedPin; + if (alreadyPinned != null + && (!alreadyPinned.materializerBinding().equals(materializerBefore) + || !alreadyPinned.apiIdentity().equals(apiBefore))) { + throw rejected(); + } + + OwnerProjection ownerBefore = currentOwnerProjection(materializerBefore, apiBefore); + SourceIdentity pinnedIdentity = + sourceIdentity(materializerBefore, apiBefore, ownerBefore.projection().configMapUid()); + if (alreadyPinned != null && !alreadyPinned.sourceIdentity().equals(pinnedIdentity)) { + throw rejected(); + } + + ConfigMapSnapshot live; + try { + live = configMapClient.observe(); + } catch (AccountJwtJwksConfigMapClient.ResourceMissingException unavailable) { + requireUnchangedProtectedTrust(materializerBefore, apiBefore); + throw unavailable(); + } catch (AccountJwtJwksConfigMapClient.ApiFailureException failure) { + requireUnchangedProtectedTrust(materializerBefore, apiBefore); + if (isTemporaryApiFailure(failure.statusCode())) { + throw unavailable(); + } + throw rejected(); + } catch (AccountJwtJwksConfigMapClient.BindingRejectedException trustRejected) { + throw rejected(); + } catch (RuntimeException unexpected) { + throw rejected(); + } + + Binding materializerAfter = currentMaterializerBinding(); + BindingIdentity apiAfter = currentApiIdentity(); + if (!materializerBefore.equals(materializerAfter) || !apiBefore.equals(apiAfter)) { + throw rejected(); + } + + OwnerProjection ownerAfter = currentOwnerProjection(materializerAfter, apiAfter); + if (!ownerBefore.equals(ownerAfter)) { + // A concurrent Account lifecycle/publication change is not a coherent source snapshot. + throw unavailable(); + } + requireExactReadback(ownerAfter.projection(), live); + + byte[] jwks = + live.data() + .get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY) + .getBytes(StandardCharsets.UTF_8); + if (jwks.length == 0 || jwks.length > MAX_JWKS_BYTES) { + throw rejected(); + } + TrustedPin pin = new TrustedPin(materializerBefore, apiBefore, pinnedIdentity); + return new VerifiedSource(pin, jwks); + } + + private Binding currentMaterializerBinding() { + return materializerTrustBinding.current().orElseThrow(AccountJwtJwksTrustedSource::rejected); + } + + private BindingIdentity currentApiIdentity() { + try { + return Objects.requireNonNull(configMapClient.identity()); + } catch (RuntimeException rejectedBinding) { + throw rejected(); + } + } + + private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity api) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw rejected(); + } + try { + OwnerProjection result = + accountTransaction.execute( + status -> { + DesiredState enrolled = + desiredStateRepository + .readEnrollmentState(binding.accountBinding()) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + if (enrolled.durableActive().isEmpty() && enrolled.publishedActive().isEmpty()) { + return initialPrepublicationProjection(enrolled, binding, api); + } + CommittedSignerEvidence committed = + desiredStateRepository + .readCurrentCommittedSigner( + binding.accountBinding(), + trustFence(binding), + api.bindingDigest(), + api.configRevision()) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + ActiveSigner currentActive = + new ActiveSigner( + committed.promotion().targetGeneration(), + committed.promotion().targetKid()); + PublishedProjection projection = committedProjection(committed); + if (committed.desiredState().generationOperationId().isEmpty()) { + return new OwnerProjection(committed, projection); + } + + var request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED) { + return new OwnerProjection(committed, projection); + } + Optional currentPublication = + publicationRepository.readCurrentPublication( + binding.accountBinding(), trustFence(binding)); + if (currentPublication.isEmpty() + || currentPublication.orElseThrow().receipt().isEmpty()) { + return new OwnerProjection(committed, projection); + } + PublicationEvidence evidence = currentPublication.orElseThrow(); + requirePublicationBinding(evidence, binding, api); + PrepublicationIntent intent = evidence.intent(); + var receipt = evidence.receipt().orElseThrow(); + if (!intent.operationId().equals(request.operationId()) + || !intent.operationDigest().equals(request.operationDigest()) + || !intent.generationRequestDigest().equals(request.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(request.generationReceiptDigest()) + || !intent.targetGeneration().equals(request.targetGeneration()) + || !intent.targetKid().equals(request.targetKid()) + || !intent.publicKeyFingerprint().equals(request.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(Optional.of(currentActive)) + || !intent.expectedPublishedActive().equals(Optional.of(currentActive)) + || !intent.configMapUid().equals(committed.promotion().publicConfigMapUid()) + || !receipt.configMapUid().equals(committed.promotion().publicConfigMapUid()) + || !intent.apiBindingDigest().equals(api.bindingDigest()) + || !intent.apiConfigRevision().equals(api.configRevision())) { + throw rejected(); + } + requireRetainedPublicKeySet(committed, intent); + return new OwnerProjection( + committed, + new PublishedProjection( + intent.configMapUid(), + receipt.observedResourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson(), + receipt.publicDataDigest())); + }); + if (result == null) { + throw unavailable(); + } + return result; + } catch (RuntimeException ownerStateUnavailable) { + if (ownerStateUnavailable instanceof SourceUnavailableException unavailable) { + throw unavailable; + } + if (ownerStateUnavailable instanceof IllegalStateException + && ownerStateUnavailable.getMessage() != null + && ownerStateUnavailable.getMessage().contains("Account trusted public JWKS source")) { + throw ownerStateUnavailable; + } + throw rejected(); + } + } + + /** + * The first exact Account-receipted PREPUBLISHED set is visible to validator probes before any + * signer is committed. It is never represented as an active signer and remains unavailable during + * PREPARED or after any active fence appears. + */ + private OwnerProjection initialPrepublicationProjection( + DesiredState enrolled, Binding binding, BindingIdentity api) { + if (!enrolled.binding().equals(binding.accountBinding()) + || enrolled.preparedOperationId().isPresent() + || enrolled.generationOperationId().isEmpty() + || enrolled.enrollmentIdentity().isEmpty()) { + throw rejected(); + } + EnrollmentIdentity enrollment = enrolled.enrollmentIdentity().orElseThrow(); + if (!enrollment.expectedClusterIncarnationUid().equals(binding.expectedClusterIncarnationUid()) + || !enrollment.expectedNamespaceUid().equals(binding.expectedNamespaceUid()) + || !enrollment.materializerTrustBindingDigest().equals(binding.bindingDigest()) + || !enrollment.materializerTrustConfigRevision().equals(binding.configRevision()) + || !enrollment.apiBindingDigest().equals(api.bindingDigest()) + || !enrollment.apiConfigRevision().equals(api.configRevision())) { + throw rejected(); + } + + GenerationRequest request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + GenerationResult result = + desiredStateRepository.readCurrentGenerationResult( + binding.accountBinding(), trustFence(binding)); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED + || !request.expectedActive().isEmpty() + || !request.expectedPublishedActive().isEmpty() + || !enrolled.generationOperationId().equals(Optional.of(request.operationId())) + || !request.binding().equals(binding.accountBinding()) + || !request.trustFence().equals(trustFence(binding)) + || !result.binding().equals(binding.accountBinding()) + || !result.trustFence().equals(trustFence(binding)) + || request.desiredStateVersion() != result.desiredStateVersion() + || !request.operationId().equals(result.operationId()) + || !request.operationDigest().equals(result.operationDigest()) + || !request.generationRequestDigest().equals(result.generationRequestDigest()) + || !request.targetGeneration().equals(result.targetGeneration()) + || !request.targetKid().equals(result.targetKid()) + || !request.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !request.publicJwkJson().equals(result.publicJwkJson()) + || !"RS256".equals(result.targetAlgorithm())) { + throw rejected(); + } + + PublicationEvidence evidence = + publicationRepository + .readCurrentPublication(binding.accountBinding(), trustFence(binding)) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + requirePublicationBinding(evidence, binding, api); + PrepublicationIntent intent = evidence.intent(); + var receipt = evidence.receipt().orElseThrow(AccountJwtJwksTrustedSource::unavailable); + if (!intent.operationId().equals(result.operationId()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.expectedDurableActive().isEmpty() + || !intent.expectedPublishedActive().isEmpty() + || !intent.configMapUid().equals(enrollment.publicConfigMapUid()) + || !receipt.configMapUid().equals(enrollment.publicConfigMapUid()) + || !intent.apiBindingDigest().equals(enrollment.apiBindingDigest()) + || !intent.apiConfigRevision().equals(enrollment.apiConfigRevision()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw rejected(); + } + Map publicKeys = publicKeyFingerprints(intent.jwksJson()); + if (publicKeys.size() != 1 + || !result.publicKeyFingerprint().equals(publicKeys.get(result.targetKid()))) { + throw rejected(); + } + requireInitialPrepublicationMarker(intent, result, binding, api); + return new OwnerProjection( + null, + new PublishedProjection( + intent.configMapUid(), + receipt.observedResourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson(), + receipt.publicDataDigest())); + } + + private static void requireInitialPrepublicationMarker( + PrepublicationIntent intent, GenerationResult result, Binding binding, BindingIdentity api) { + try { + JsonNode marker = STRICT_JSON.readTree(intent.generationMarkerJson()); + JsonNode markerBinding = marker == null ? null : marker.get("binding"); + JsonNode publicConfigMap = marker == null ? null : marker.get("publicConfigMap"); + JsonNode pending = marker == null ? null : marker.get("pending"); + JsonNode durable = marker == null ? null : marker.get("expectedDurableActive"); + JsonNode published = marker == null ? null : marker.get("expectedPublishedActive"); + if (marker == null + || !marker.isObject() + || !hasExactFields( + marker, + java.util.Set.of( + "schemaVersion", + "phase", + "operationId", + "operationDigest", + "generationRequestDigest", + "generationReceiptDigest", + "binding", + "publicConfigMap", + "expectedDurableActive", + "expectedPublishedActive", + "pending")) + || !marker.get("schemaVersion").isIntegralNumber() + || marker.get("schemaVersion").intValue() != 1 + || !"PREPUBLISHED".equals(requiredText(marker, "phase")) + || !intent.operationId().toString().equals(requiredText(marker, "operationId")) + || !intent.operationDigest().equals(requiredText(marker, "operationDigest")) + || !intent + .generationRequestDigest() + .equals(requiredText(marker, "generationRequestDigest")) + || !intent + .generationReceiptDigest() + .equals(requiredText(marker, "generationReceiptDigest")) + || !hasExactFields( + markerBinding, + java.util.Set.of( + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "trustBindingDigest", + "trustConfigRevision", + "apiBindingDigest", + "apiConfigRevision")) + || !binding.environmentId().equals(requiredText(markerBinding, "environmentId")) + || !binding.clusterId().equals(requiredText(markerBinding, "clusterId")) + || !binding.namespace().equals(requiredText(markerBinding, "namespace")) + || !binding + .expectedClusterIncarnationUid() + .equals(requiredText(markerBinding, "expectedClusterIncarnationUid")) + || !binding + .expectedNamespaceUid() + .equals(requiredText(markerBinding, "expectedNamespaceUid")) + || !binding.bindingDigest().equals(requiredText(markerBinding, "trustBindingDigest")) + || !binding.configRevision().equals(requiredText(markerBinding, "trustConfigRevision")) + || !api.bindingDigest().equals(requiredText(markerBinding, "apiBindingDigest")) + || !api.configRevision().equals(requiredText(markerBinding, "apiConfigRevision")) + || !hasExactFields(publicConfigMap, java.util.Set.of("name")) + || !AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME.equals( + requiredText(publicConfigMap, "name")) + || !hasExactFields( + pending, java.util.Set.of("generation", "kid", "algorithm", "publicKeyFingerprint")) + || !result.targetGeneration().equals(requiredText(pending, "generation")) + || !result.targetKid().equals(requiredText(pending, "kid")) + || !"RS256".equals(requiredText(pending, "algorithm")) + || !result.publicKeyFingerprint().equals(requiredText(pending, "publicKeyFingerprint")) + || !inactiveMarker(durable) + || !inactiveMarker(published)) { + throw rejected(); + } + } catch (RuntimeException malformed) { + throw rejected(); + } + } + + private static boolean inactiveMarker(JsonNode marker) { + return hasExactFields(marker, java.util.Set.of("present")) + && marker.get("present").isBoolean() + && !marker.get("present").booleanValue(); + } + + private static void requireBindingsAgree(Binding materializer, BindingIdentity api) { + if (!materializer.environmentId().equals(api.environmentId()) + || !materializer.clusterId().equals(api.clusterId()) + || !materializer.namespace().equals(api.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid()) + || api.bindingDigest() == null + || api.configRevision() == null + || api.expectedApiUsername() == null + || !api.expectedApiUsername() + .equals( + ACCOUNT_SERVICE_USERNAME_PREFIX + + materializer.namespace() + + ":" + + ACCOUNT_SERVICE_NAME)) { + throw rejected(); + } + URI endpoint; + try { + endpoint = URI.create(api.apiServerUrl()); + } catch (RuntimeException malformedEndpoint) { + throw rejected(); + } + if (!"https".equalsIgnoreCase(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() <= 0 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null + && !endpoint.getRawPath().isEmpty() + && !"/".equals(endpoint.getRawPath())) + || api.tlsServerName() == null + || !endpoint.getHost().equalsIgnoreCase(api.tlsServerName()) + || api.servingCaSha256() == null) { + throw rejected(); + } + } + + private static void requirePublicationBinding( + PublicationEvidence evidence, Binding materializer, BindingIdentity api) { + PrepublicationIntent intent = evidence.intent(); + if (!intent.binding().equals(materializer.accountBinding()) + || !intent.trustFence().equals(trustFence(materializer)) + || !AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME.equals(intent.configMapName()) + || !intent.apiBindingDigest().equals(api.bindingDigest()) + || !intent.apiConfigRevision().equals(api.configRevision()) + || !AccountJwtJwksPublicationRepository.publicDataDigest( + intent.jwksJson(), intent.generationMarkerJson()) + .equals(intent.publicDataDigest())) { + throw rejected(); + } + PublicationReceipt receipt = evidence.receipt().orElse(null); + if (receipt != null + && (!receipt.operationId().equals(intent.operationId()) + || !receipt.binding().equals(materializer.accountBinding()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !receipt.configMapUid().equals(intent.configMapUid()) + || !receipt.publicDataDigest().equals(intent.publicDataDigest()) + || !receipt.expectedResourceVersion().equals(intent.expectedResourceVersion()))) { + throw rejected(); + } + } + + private static PublishedProjection committedProjection(CommittedSignerEvidence committed) { + PromotionOperationEvidence promotion = committed.promotion(); + var receipt = committed.publicReceipt(); + String dataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson()); + if (!promotion.publicConfigMapUid().equals(receipt.configMapUid()) + || !promotion + .activeJwksObservedResourceVersion() + .orElseThrow() + .equals(receipt.observedResourceVersion()) + || !promotion.activeJwksPublicDataDigest().orElseThrow().equals(dataDigest) + || !receipt.publicDataDigest().equals(dataDigest)) { + throw rejected(); + } + return new PublishedProjection( + receipt.configMapUid(), + receipt.observedResourceVersion(), + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson(), + dataDigest); + } + + private static void requireRetainedPublicKeySet( + CommittedSignerEvidence committed, PrepublicationIntent intent) { + Map previousKeys = + publicKeyFingerprints(committed.promotion().expectedPublicJwksJson()); + Map currentKeys = publicKeyFingerprints(intent.jwksJson()); + if (previousKeys.isEmpty() || currentKeys.size() < previousKeys.size()) { + throw rejected(); + } + if (new BigInteger(intent.targetGeneration()) + .compareTo(new BigInteger(committed.promotion().targetGeneration())) + <= 0) { + throw rejected(); + } + for (Map.Entry previous : previousKeys.entrySet()) { + if (!previous.getValue().equals(currentKeys.get(previous.getKey()))) { + throw rejected(); + } + } + if (!intent.publicKeyFingerprint().equals(currentKeys.get(intent.targetKid())) + || !committed + .promotion() + .targetPublicKeyFingerprint() + .equals(currentKeys.get(committed.promotion().targetKid()))) { + throw rejected(); + } + } + + private static Map publicKeyFingerprints(String jwksJson) { + try { + if (jwksJson == null + || jwksJson.isBlank() + || jwksJson.getBytes(StandardCharsets.UTF_8).length > MAX_JWKS_BYTES) { + throw new IllegalArgumentException(); + } + JsonNode root = STRICT_JSON.readTree(jwksJson); + if (root == null || !root.isObject() || !hasExactFields(root, JWKS_FIELDS)) { + throw new IllegalArgumentException(); + } + JsonNode keys = root.get("keys"); + if (keys == null || !keys.isArray() || keys.isEmpty() || keys.size() > MAX_KEYS) { + throw new IllegalArgumentException(); + } + Map fingerprints = new LinkedHashMap<>(); + for (JsonNode key : keys) { + if (key == null || !key.isObject() || !hasExactFields(key, JWK_FIELDS)) { + throw new IllegalArgumentException(); + } + String kty = requiredText(key, "kty"); + String use = requiredText(key, "use"); + String alg = requiredText(key, "alg"); + String kid = requiredText(key, "kid"); + String modulus = requiredText(key, "n"); + String exponent = requiredText(key, "e"); + JsonNode keyOps = key.get("key_ops"); + if (!"RSA".equals(kty) + || !"sig".equals(use) + || !"RS256".equals(alg) + || !kid.matches("[A-Za-z0-9_-]{1,64}") + || keyOps == null + || !keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())) { + throw new IllegalArgumentException(); + } + String preimage = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + STRICT_JSON.writeValueAsString( + Map.of("e", exponent, "kty", kty, "n", modulus))), + StandardCharsets.UTF_8); + String fingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.getBytes(StandardCharsets.UTF_8))); + if (fingerprints.putIfAbsent(kid, fingerprint) != null) { + throw new IllegalArgumentException(); + } + } + return Map.copyOf(fingerprints); + } catch (IOException | NoSuchAlgorithmException | RuntimeException malformed) { + throw rejected(); + } + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || value.textValue().isEmpty()) { + throw new IllegalArgumentException(); + } + return value.textValue(); + } + + private static boolean hasExactFields(JsonNode object, java.util.Set expected) { + if (object == null || !object.isObject() || object.size() != expected.size()) { + return false; + } + for (Map.Entry property : object.properties()) { + if (!expected.contains(property.getKey())) { + return false; + } + } + return true; + } + + private static void requireExactReadback(PublishedProjection projection, ConfigMapSnapshot live) { + String jwks = live.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY); + String marker = live.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY); + if (!projection.configMapUid().equals(live.uid()) + || !projection.resourceVersion().equals(live.resourceVersion()) + || !projection.jwksJson().equals(jwks) + || !projection.markerJson().equals(marker) + || marker == null + || marker.getBytes(StandardCharsets.UTF_8).length > MAX_MARKER_BYTES + || !AccountJwtJwksPublicationRepository.publicDataDigest(jwks, marker) + .equals(projection.publicDataDigest())) { + throw rejected(); + } + } + + private static SourceIdentity sourceIdentity( + Binding materializer, BindingIdentity api, String configMapUid) { + try { + return new SourceIdentity( + materializer.environmentId(), + materializer.clusterId(), + materializer.expectedClusterIncarnationUid(), + materializer.namespace(), + materializer.expectedNamespaceUid(), + configMapUid, + api.configRevision(), + api.apiServerUrl(), + api.servingCaSha256()); + } catch (RuntimeException invalidIdentity) { + throw rejected(); + } + } + + private void requireUnchangedProtectedTrust(Binding expected, BindingIdentity expectedApi) { + Binding currentMaterializer = currentMaterializerBinding(); + BindingIdentity currentApi = currentApiIdentity(); + if (!expected.equals(currentMaterializer) || !expectedApi.equals(currentApi)) { + throw rejected(); + } + } + + private static boolean isTemporaryApiFailure(int statusCode) { + return statusCode == 0 || statusCode == 408 || statusCode == 429 || statusCode >= 500; + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private static SourceUnavailableException unavailable() { + return new SourceUnavailableException(); + } + + private static IllegalStateException rejected() { + return new IllegalStateException("Account trusted public JWKS source was rejected"); + } + + private record TrustedPin( + Binding materializerBinding, BindingIdentity apiIdentity, SourceIdentity sourceIdentity) {} + + private record OwnerProjection( + CommittedSignerEvidence committedSigner, PublishedProjection projection) {} + + private record PublishedProjection( + String configMapUid, + String resourceVersion, + String jwksJson, + String markerJson, + String publicDataDigest) {} + + private record VerifiedSource(TrustedPin pin, byte[] jwksBytes) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java new file mode 100644 index 0000000000..289c255116 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java @@ -0,0 +1,1117 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiOperation; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProtectedInventory; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ValidatorExpectation; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Default-inactive reader for one protected expected validator inventory and its live Kubernetes + * Deployment/Pod observations. The snapshot is non-authorizing evidence only; it does not prove + * per-Pod token acceptance, readiness completeness, promotion eligibility, or convergence. + */ +public final class AccountJwtValidatorInventorySource { + private static final int MAX_PAGES = 16; + private static final int MAX_PODS_PER_VALIDATOR = 128; + private static final int MAX_CANONICAL_SNAPSHOT_BYTES = 4 * 1024 * 1024; + private static final String INVENTORY_DOMAIN = "firemud-account-validator-inventory/v1"; + private static final String SELF_REVIEW_REQUEST = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}"; + private static final String RUNTIME_CONFIG_ENV = "FIREMUD_JWT_VERIFIER_CONFIG"; + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern IMAGE_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POD_TEMPLATE_HASH = Pattern.compile("[a-z0-9]{5,20}"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountJwtJwksApiBinding apiBinding; + private final AccountJwtValidatorInventoryBinding inventoryBinding; + private final Clock clock; + + /** No Spring stereotype or automatic activation is provided. */ + public AccountJwtValidatorInventorySource( + AccountJwtJwksApiBinding apiBinding, + AccountJwtValidatorInventoryBinding inventoryBinding, + Clock clock) { + this.apiBinding = + Objects.requireNonNull(apiBinding, "protected Kubernetes API binding is required"); + this.inventoryBinding = + Objects.requireNonNull( + inventoryBinding, "protected validator inventory binding is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + /** + * Produces a fresh immutable observation. Any unavailable, changed, partial, ambiguous, legacy, + * or unpinned state is returned as one redacted failure; no Kubernetes response body is retained. + */ + public InventorySnapshot observe() { + ProtectedInventory expected = + inventoryBinding.current().orElseThrow(InventoryUnavailableException::new); + try (ApiOperation operation = apiBinding.beginOperation()) { + ParsedBinding api = operation.binding(); + if (!expected.matchesApiBinding(api)) { + throw new InventoryUnavailableException(); + } + verifyApiIdentity(operation, expected); + List observations = new ArrayList<>(); + for (ValidatorExpectation validator : expected.validators()) { + DeploymentObservation beforeDeployment = readDeployment(operation, expected, validator); + List beforePods = + readPods(operation, expected, validator, beforeDeployment); + List beforeReplicaSets = + readReplicaSets(operation, expected, validator, beforeDeployment, beforePods); + DeploymentObservation afterDeployment = readDeployment(operation, expected, validator); + List afterPods = readPods(operation, expected, validator, afterDeployment); + List afterReplicaSets = + readReplicaSets(operation, expected, validator, afterDeployment, afterPods); + if (!beforeDeployment.equals(afterDeployment) + || !beforePods.equals(afterPods) + || !beforeReplicaSets.equals(afterReplicaSets)) { + throw new InventoryUnavailableException(); + } + observations.add( + new ValidatorObservation( + validator.validatorId(), + beforeDeployment.name(), + beforeDeployment.uid(), + beforeDeployment.generation(), + beforeDeployment.resourceVersion(), + beforeDeployment.replicas(), + beforeDeployment.image(), + beforeDeployment.verifierConfigSha256(), + validator.maxCacheAgeSeconds(), + validator.profiles(), + beforePods, + beforeReplicaSets)); + } + verifyApiIdentity(operation, expected); + ProtectedInventory afterExpected = + inventoryBinding.current().orElseThrow(InventoryUnavailableException::new); + if (!expected.bindingDigest().equals(afterExpected.bindingDigest()) + || !expected.configRevision().equals(afterExpected.configRevision())) { + throw new InventoryUnavailableException(); + } + Instant observedAt = clock.instant(); + if (observedAt == null || observedAt.isBefore(Instant.EPOCH)) { + throw new InventoryUnavailableException(); + } + return createSnapshot(expected, observations, observedAt); + } catch (InventoryUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + // Do not expose tokens, API bodies, file paths, parser details, or exception causes. + throw new InventoryUnavailableException(); + } + } + + private static void verifyApiIdentity(ApiOperation operation, ProtectedInventory expected) { + ParsedBinding binding = operation.binding(); + if (!expected.matchesApiBinding(binding)) { + throw new InventoryUnavailableException(); + } + ApiResponse selfReview = + operation.send( + AccountJwtJwksApiBinding.ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + SELF_REVIEW_REQUEST.getBytes(StandardCharsets.UTF_8)); + if (selfReview.statusCode() != 200 && selfReview.statusCode() != 201) { + throw new InventoryUnavailableException(); + } + JsonNode review = parseJson(selfReview.body()); + JsonNode status = review.get("status"); + JsonNode userInfo = status == null ? null : status.get("userInfo"); + JsonNode username = userInfo == null ? null : userInfo.get("username"); + JsonNode evaluationError = status == null ? null : status.get("evaluationError"); + if (!"authentication.k8s.io/v1".equals(text(review.get("apiVersion"))) + || !"SelfSubjectReview".equals(text(review.get("kind"))) + || !binding.expectedApiUsername().equals(text(username)) + || (evaluationError != null + && !evaluationError.isNull() + && (!evaluationError.isTextual() || !evaluationError.asText().isEmpty()))) { + throw new InventoryUnavailableException(); + } + verifyNamespace( + operation.send(AccountJwtJwksApiBinding.ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null), + "kube-system", + expected.expectedClusterIncarnationUid()); + verifyNamespace( + operation.send(AccountJwtJwksApiBinding.ApiCall.READ_TARGET_NAMESPACE, null), + expected.namespace(), + expected.expectedNamespaceUid()); + } + + private static void verifyNamespace(ApiResponse response, String name, String expectedUid) { + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode status = root.get("status"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"Namespace".equals(text(root.get("kind"))) + || metadata == null + || !name.equals(text(metadata.get("name"))) + || !expectedUid.equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || status == null + || !"Active".equals(text(status.get("phase")))) { + throw new InventoryUnavailableException(); + } + } + + private static DeploymentObservation readDeployment( + ApiOperation operation, ProtectedInventory inventory, ValidatorExpectation expected) { + ApiResponse response = operation.readValidatorDeployment(inventory, expected); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode spec = root.get("spec"); + JsonNode status = root.get("status"); + JsonNode selector = spec == null ? null : spec.get("selector"); + JsonNode template = spec == null ? null : spec.get("template"); + JsonNode templateMetadata = template == null ? null : template.get("metadata"); + JsonNode templateSpec = template == null ? null : template.get("spec"); + if (!"apps/v1".equals(text(root.get("apiVersion"))) + || !"Deployment".equals(text(root.get("kind"))) + || metadata == null + || !expected.deploymentName().equals(text(metadata.get("name"))) + || !inventory.namespace().equals(text(metadata.get("namespace"))) + || !expected.deploymentUid().equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || spec == null + || status == null + || selector == null + || !selectorMatches(selector.get("matchLabels"), expected.selector()) + || (selector.has("matchExpressions") + && selector.get("matchExpressions") != null + && !selector.get("matchExpressions").isNull() + && (!selector.get("matchExpressions").isArray() + || !selector.get("matchExpressions").isEmpty())) + || templateMetadata == null + || !labelsMatch(templateMetadata.get("labels"), expected.selector()) + || templateSpec == null) { + throw new InventoryUnavailableException(); + } + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + long generation = positiveLong(metadata.get("generation")); + int replicas = exactInt(spec.get("replicas"), 1, 128); + if (replicas != expected.replicas() + || positiveLong(status.get("observedGeneration")) != generation + || exactInt(status.get("readyReplicas"), 0, 128) != replicas + || exactInt(status.get("updatedReplicas"), 0, 128) != replicas + || exactInt(status.get("availableReplicas"), 0, 128) != replicas + || (status.has("unavailableReplicas") + && !status.get("unavailableReplicas").isNull() + && exactInt(status.get("unavailableReplicas"), 0, 128) != 0)) { + throw new InventoryUnavailableException(); + } + ContainerConfig container = + findVerifiedContainer( + templateSpec.get("containers"), expected, templateSpec.get("volumes")); + return new DeploymentObservation( + expected.deploymentName(), + expected.deploymentUid(), + resourceVersion, + generation, + replicas, + container.image(), + container.runtimeConfigSha256()); + } + + private static List readPods( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + DeploymentObservation deployment) { + String continuation = null; + String listResourceVersion = null; + int pageCount = 0; + List pods = new ArrayList<>(); + Set podUids = new LinkedHashSet<>(); + Set podNames = new LinkedHashSet<>(); + do { + if (++pageCount > MAX_PAGES) { + throw new InventoryUnavailableException(); + } + ApiResponse response = operation.listValidatorPods(inventory, expected, continuation); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode items = root.get("items"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"PodList".equals(text(root.get("kind"))) + || metadata == null + || items == null + || !items.isArray()) { + throw new InventoryUnavailableException(); + } + String pageVersion = resourceVersion(text(metadata.get("resourceVersion"))); + if (listResourceVersion == null) { + listResourceVersion = pageVersion; + } else if (!listResourceVersion.equals(pageVersion)) { + throw new InventoryUnavailableException(); + } + for (JsonNode item : items) { + if (pods.size() >= MAX_PODS_PER_VALIDATOR) { + throw new InventoryUnavailableException(); + } + PodObservation pod = parsePod(item, inventory.namespace(), expected, deployment); + if (!podUids.add(pod.uid()) || !podNames.add(pod.name())) { + throw new InventoryUnavailableException(); + } + pods.add(pod); + } + JsonNode continueNode = metadata.get("continue"); + if (continueNode == null || continueNode.isNull() || !continueNode.isTextual()) { + continuation = null; + } else { + continuation = continueNode.asText(); + if (continuation.isEmpty()) { + continuation = null; + } else if (continuation.length() > 2048) { + throw new InventoryUnavailableException(); + } + } + } while (continuation != null); + if (pods.size() != expected.replicas()) { + throw new InventoryUnavailableException(); + } + pods.sort(Comparator.comparing(PodObservation::uid)); + return List.copyOf(pods); + } + + private static PodObservation parsePod( + JsonNode pod, + String namespace, + ValidatorExpectation expected, + DeploymentObservation deployment) { + if (pod == null || pod.isNull()) { + throw new InventoryUnavailableException(); + } + JsonNode metadata = pod.get("metadata"); + JsonNode spec = pod.get("spec"); + JsonNode status = pod.get("status"); + if (!"v1".equals(text(pod.get("apiVersion"))) + || !"Pod".equals(text(pod.get("kind"))) + || metadata == null + || spec == null + || status == null + || !namespace.equals(text(metadata.get("namespace"))) + || metadata.hasNonNull("deletionTimestamp") + || !labelsMatch(metadata.get("labels"), expected.selector()) + || !"Running".equals(text(status.get("phase")))) { + throw new InventoryUnavailableException(); + } + String name = dnsLabel(text(metadata.get("name"))); + String uid = canonicalUid(text(metadata.get("uid"))); + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + String templateHash = podTemplateHash(metadata.get("labels")); + JsonNode owners = metadata.get("ownerReferences"); + if (owners == null || !owners.isArray() || owners.size() != 1) { + throw new InventoryUnavailableException(); + } + JsonNode owner = owners.get(0); + if (!"apps/v1".equals(text(owner.get("apiVersion"))) + || !"ReplicaSet".equals(text(owner.get("kind"))) + || !Boolean.TRUE.equals(booleanValue(owner.get("controller")))) { + throw new InventoryUnavailableException(); + } + String ownerName = dnsLabel(text(owner.get("name"))); + String ownerUid = canonicalUid(text(owner.get("uid"))); + ContainerConfig container = + findVerifiedContainer(spec.get("containers"), expected, spec.get("volumes")); + if (!deployment.image().equals(container.image()) + || !deployment.verifierConfigSha256().equals(container.runtimeConfigSha256())) { + throw new InventoryUnavailableException(); + } + verifyReadyCondition(status.get("conditions")); + verifyContainerReady(status.get("containerStatuses"), expected, deployment.image()); + return new PodObservation( + name, + uid, + resourceVersion, + ownerName, + ownerUid, + templateHash, + deployment.image(), + deployment.verifierConfigSha256()); + } + + private static List readReplicaSets( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + DeploymentObservation deployment, + List pods) { + Map observedOwners = new LinkedHashMap<>(); + Map templateHashes = new LinkedHashMap<>(); + for (PodObservation pod : pods) { + String prior = observedOwners.putIfAbsent(pod.ownerName(), pod.ownerUid()); + String priorHash = templateHashes.putIfAbsent(pod.ownerName(), pod.podTemplateHash()); + if ((prior != null && !prior.equals(pod.ownerUid())) + || (priorHash != null && !priorHash.equals(pod.podTemplateHash()))) { + throw new InventoryUnavailableException(); + } + } + List observations = new ArrayList<>(observedOwners.size()); + for (Map.Entry owner : observedOwners.entrySet()) { + ApiResponse response = operation.readValidatorReplicaSet(inventory, expected, owner.getKey()); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + observations.add( + parseReplicaSet( + response.body(), + inventory.namespace(), + expected, + deployment, + owner.getKey(), + owner.getValue(), + templateHashes.get(owner.getKey()))); + } + observations.sort(Comparator.comparing(ReplicaSetObservation::uid)); + return List.copyOf(observations); + } + + private static ReplicaSetObservation parseReplicaSet( + byte[] responseBody, + String namespace, + ValidatorExpectation expected, + DeploymentObservation deployment, + String expectedName, + String expectedUid, + String expectedTemplateHash) { + JsonNode root = parseJson(responseBody); + JsonNode metadata = root.get("metadata"); + JsonNode spec = root.get("spec"); + JsonNode status = root.get("status"); + JsonNode owners = metadata == null ? null : metadata.get("ownerReferences"); + JsonNode selector = spec == null ? null : spec.get("selector"); + JsonNode template = spec == null ? null : spec.get("template"); + JsonNode templateMetadata = template == null ? null : template.get("metadata"); + JsonNode templateSpec = template == null ? null : template.get("spec"); + if (!"apps/v1".equals(text(root.get("apiVersion"))) + || !"ReplicaSet".equals(text(root.get("kind"))) + || metadata == null + || !expectedName.equals(text(metadata.get("name"))) + || !namespace.equals(text(metadata.get("namespace"))) + || !expectedUid.equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || owners == null + || !owners.isArray() + || owners.size() != 1 + || spec == null + || status == null + || selector == null + || !replicaSetSelectorMatches( + selector.get("matchLabels"), expected.selector(), expectedTemplateHash) + || (selector.has("matchExpressions") + && selector.get("matchExpressions") != null + && !selector.get("matchExpressions").isNull() + && (!selector.get("matchExpressions").isArray() + || !selector.get("matchExpressions").isEmpty())) + || templateMetadata == null + || !labelsMatch(templateMetadata.get("labels"), expected.selector()) + || !expectedTemplateHash.equals( + text(templateMetadata.get("labels").get("pod-template-hash"))) + || templateSpec == null) { + throw new InventoryUnavailableException(); + } + JsonNode owner = owners.get(0); + if (!"apps/v1".equals(text(owner.get("apiVersion"))) + || !"Deployment".equals(text(owner.get("kind"))) + || !deployment.name().equals(text(owner.get("name"))) + || !deployment.uid().equals(canonicalUid(text(owner.get("uid")))) + || !Boolean.TRUE.equals(booleanValue(owner.get("controller")))) { + throw new InventoryUnavailableException(); + } + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + long generation = positiveLong(metadata.get("generation")); + int replicas = exactInt(spec.get("replicas"), 1, 128); + if (positiveLong(status.get("observedGeneration")) != generation + || exactInt(status.get("readyReplicas"), 0, 128) != replicas + || replicas != expected.replicas()) { + throw new InventoryUnavailableException(); + } + ContainerConfig container = + findVerifiedContainer( + templateSpec.get("containers"), expected, templateSpec.get("volumes")); + if (!deployment.image().equals(container.image()) + || !deployment.verifierConfigSha256().equals(container.runtimeConfigSha256())) { + throw new InventoryUnavailableException(); + } + return new ReplicaSetObservation( + expectedName, + expectedUid, + resourceVersion, + generation, + replicas, + deployment.name(), + deployment.uid(), + expectedTemplateHash, + container.image(), + container.runtimeConfigSha256()); + } + + private static boolean replicaSetSelectorMatches( + JsonNode actual, Map expected, String expectedTemplateHash) { + if (actual == null + || !actual.isObject() + || expectedTemplateHash == null + || actual.size() != expected.size() + 1 + || !expectedTemplateHash.equals(text(actual.get("pod-template-hash")))) { + return false; + } + for (Map.Entry entry : expected.entrySet()) { + if (!entry.getValue().equals(text(actual.get(entry.getKey())))) { + return false; + } + } + return true; + } + + private static String podTemplateHash(JsonNode labels) { + if (labels == null || !labels.isObject()) { + throw new InventoryUnavailableException(); + } + String value = text(labels.get("pod-template-hash")); + if (value == null || !POD_TEMPLATE_HASH.matcher(value).matches()) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static ContainerConfig findVerifiedContainer( + JsonNode containers, ValidatorExpectation expected, JsonNode volumes) { + if (containers == null + || !containers.isArray() + || containers.isEmpty() + || containers.size() > 32) { + throw new InventoryUnavailableException(); + } + JsonNode selected = null; + for (JsonNode container : containers) { + String name = text(container.get("name")); + rejectSigningMaterialEnvironment(container.get("env")); + rejectSigningSecretMounts(container.get("volumeMounts")); + if (expected.containerName().equals(name)) { + if (selected != null) { + throw new InventoryUnavailableException(); + } + selected = container; + } + } + rejectSigningSecretVolumes(volumes); + if (selected == null || !expected.image().equals(text(selected.get("image")))) { + throw new InventoryUnavailableException(); + } + JsonNode env = selected.get("env"); + JsonNode configNode = null; + Set environmentNames = new LinkedHashSet<>(); + if (env != null && !env.isNull()) { + if (!env.isArray() || env.size() > 256) { + throw new InventoryUnavailableException(); + } + for (JsonNode variable : env) { + String envName = text(variable.get("name")); + if (envName == null || !environmentNames.add(envName)) { + throw new InventoryUnavailableException(); + } + if (RUNTIME_CONFIG_ENV.equals(envName)) { + if (variable.has("valueFrom") + || !expected.canonicalRuntimeConfig().equals(text(variable.get("value")))) { + throw new InventoryUnavailableException(); + } + configNode = variable; + } + if ("SPRING_APPLICATION_JSON".equals(envName) + || "JAVA_TOOL_OPTIONS".equals(envName) + || "JDK_JAVA_OPTIONS".equals(envName)) { + throw new InventoryUnavailableException(); + } + } + } + if (configNode == null) { + throw new InventoryUnavailableException(); + } + return new ContainerConfig( + expected.image(), + sha256(expected.canonicalRuntimeConfig().getBytes(StandardCharsets.UTF_8))); + } + + private static void rejectSigningMaterialEnvironment(JsonNode env) { + if (env == null || env.isNull()) { + return; + } + if (!env.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode variable : env) { + String name = text(variable.get("name")); + if (name != null + && (name.equals("FIREMUD_AUTH_JWT_SECRET") + || name.equals("FIREMUD_AUTH_JWT_SECRET_PATH") + || name.contains("JWT_HMAC") + || name.contains("JWT_SIGNING_KEY"))) { + throw new InventoryUnavailableException(); + } + JsonNode valueFrom = variable.get("valueFrom"); + JsonNode secretKeyRef = valueFrom == null ? null : valueFrom.get("secretKeyRef"); + if (secretKeyRef != null && !secretKeyRef.isNull()) { + String secretName = text(secretKeyRef.get("name")); + if ("jwt-signing-keys".equals(secretName)) { + throw new InventoryUnavailableException(); + } + } + } + } + + private static void rejectSigningSecretMounts(JsonNode mounts) { + if (mounts == null || mounts.isNull()) { + return; + } + if (!mounts.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode mount : mounts) { + String name = text(mount.get("name")); + String path = text(mount.get("mountPath")); + if ("jwt-signing-keys".equals(name) + || (path != null && path.startsWith("/var/run/secrets/firemud/jwt"))) { + throw new InventoryUnavailableException(); + } + } + } + + private static void rejectSigningSecretVolumes(JsonNode volumes) { + if (volumes == null || volumes.isNull()) { + return; + } + if (!volumes.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode volume : volumes) { + String name = text(volume.get("name")); + JsonNode secret = volume.get("secret"); + if ("jwt-signing-keys".equals(name) + || (secret != null + && !secret.isNull() + && "jwt-signing-keys".equals(text(secret.get("secretName"))))) { + throw new InventoryUnavailableException(); + } + } + } + + private static void verifyReadyCondition(JsonNode conditions) { + if (conditions == null || !conditions.isArray() || conditions.size() > 64) { + throw new InventoryUnavailableException(); + } + boolean ready = false; + for (JsonNode condition : conditions) { + if ("Ready".equals(text(condition.get("type")))) { + if (ready || !"True".equals(text(condition.get("status")))) { + throw new InventoryUnavailableException(); + } + ready = true; + } + } + if (!ready) { + throw new InventoryUnavailableException(); + } + } + + private static void verifyContainerReady( + JsonNode statuses, ValidatorExpectation expected, String expectedImage) { + if (statuses == null || !statuses.isArray() || statuses.isEmpty() || statuses.size() > 32) { + throw new InventoryUnavailableException(); + } + JsonNode found = null; + for (JsonNode status : statuses) { + if (expected.containerName().equals(text(status.get("name")))) { + if (found != null) { + throw new InventoryUnavailableException(); + } + found = status; + } + } + String imageId = found == null ? null : text(found.get("imageID")); + String digest = imageDigest(imageId); + String expectedDigest = expected.image().substring(expected.image().lastIndexOf('@') + 1); + if (found == null + || !Boolean.TRUE.equals(booleanValue(found.get("ready"))) + || !expectedDigest.equals(digest)) { + throw new InventoryUnavailableException(); + } + } + + private static InventorySnapshot createSnapshot( + ProtectedInventory expected, List validators, Instant observedAt) { + List sorted = + validators.stream() + .sorted(Comparator.comparing(ValidatorObservation::validatorId)) + .toList(); + Map preimage = new LinkedHashMap<>(); + preimage.put("domain", INVENTORY_DOMAIN); + preimage.put("observedAt", observedAt.toString()); + preimage.put("environmentId", expected.environmentId()); + preimage.put("clusterId", expected.clusterId()); + preimage.put("clusterIncarnationUid", expected.expectedClusterIncarnationUid()); + preimage.put("namespace", expected.namespace()); + preimage.put("namespaceUid", expected.expectedNamespaceUid()); + preimage.put("apiBindingRevision", expected.apiBindingRevision()); + preimage.put("apiBindingDigest", expected.apiBindingDigest()); + preimage.put("inventoryBindingRevision", expected.configRevision()); + preimage.put("inventoryBindingDigest", expected.bindingDigest()); + preimage.put( + "validators", + sorted.stream().map(AccountJwtValidatorInventorySource::validatorMap).toList()); + byte[] canonicalSnapshot = canonicalBytes(preimage); + if (canonicalSnapshot.length > MAX_CANONICAL_SNAPSHOT_BYTES) { + throw new InventoryUnavailableException(); + } + String digest = sha256(canonicalSnapshot); + return new InventorySnapshot( + observedAt, + expected.environmentId(), + expected.clusterId(), + expected.expectedClusterIncarnationUid(), + expected.namespace(), + expected.expectedNamespaceUid(), + expected.apiBindingRevision(), + expected.apiBindingDigest(), + expected.configRevision(), + expected.bindingDigest(), + sorted, + canonicalSnapshot, + digest); + } + + private static Map validatorMap(ValidatorObservation validator) { + Map result = new LinkedHashMap<>(); + result.put("validatorId", validator.validatorId()); + result.put("deploymentName", validator.deploymentName()); + result.put("deploymentUid", validator.deploymentUid()); + result.put("deploymentGeneration", Long.toString(validator.deploymentGeneration())); + result.put("deploymentResourceVersion", validator.deploymentResourceVersion()); + result.put("replicas", Integer.toString(validator.replicas())); + result.put("image", validator.image()); + result.put("verifierConfigSha256", validator.verifierConfigSha256()); + result.put("maxCacheAgeSeconds", Integer.toString(validator.maxCacheAgeSeconds())); + result.put( + "profiles", + validator.profiles().stream() + .map( + profile -> + Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .toList()); + result.put( + "pods", validator.pods().stream().map(AccountJwtValidatorInventorySource::podMap).toList()); + result.put( + "replicaSets", + validator.replicaSets().stream() + .map(AccountJwtValidatorInventorySource::replicaSetMap) + .toList()); + return result; + } + + private static Map replicaSetMap(ReplicaSetObservation replicaSet) { + return Map.of( + "name", replicaSet.name(), + "uid", replicaSet.uid(), + "resourceVersion", replicaSet.resourceVersion(), + "generation", Long.toString(replicaSet.generation()), + "replicas", Integer.toString(replicaSet.replicas()), + "ownerDeploymentName", replicaSet.ownerDeploymentName(), + "ownerDeploymentUid", replicaSet.ownerDeploymentUid(), + "podTemplateHash", replicaSet.podTemplateHash(), + "image", replicaSet.image(), + "verifierConfigSha256", replicaSet.verifierConfigSha256()); + } + + private static Map podMap(PodObservation pod) { + return Map.of( + "name", pod.name(), + "uid", pod.uid(), + "resourceVersion", pod.resourceVersion(), + "ownerReplicaSetName", pod.ownerName(), + "ownerReplicaSetUid", pod.ownerUid(), + "podTemplateHash", pod.podTemplateHash(), + "image", pod.image(), + "verifierConfigSha256", pod.verifierConfigSha256()); + } + + private static boolean selectorMatches(JsonNode actual, Map expected) { + if (actual == null || !actual.isObject() || actual.size() != expected.size()) { + return false; + } + return labelsMatch(actual, expected); + } + + private static boolean labelsMatch(JsonNode labels, Map expected) { + if (labels == null || !labels.isObject()) { + return false; + } + for (Map.Entry entry : expected.entrySet()) { + if (!entry.getValue().equals(text(labels.get(entry.getKey())))) { + return false; + } + } + return true; + } + + private static JsonNode parseJson(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > 1024 * 1024) { + throw new InventoryUnavailableException(); + } + try { + JsonNode parsed = JSON.readTree(decodeUtf8(bytes)); + if (parsed == null || !parsed.isObject()) { + throw new InventoryUnavailableException(); + } + return parsed; + } catch (InventoryUnavailableException failure) { + throw failure; + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private static byte[] canonicalBytes(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private static String imageDigest(String imageId) { + if (imageId == null) { + throw new InventoryUnavailableException(); + } + int marker = imageId.lastIndexOf("sha256:"); + if (marker < 0) { + throw new InventoryUnavailableException(); + } + String digest = imageId.substring(marker); + if (!IMAGE_DIGEST.matcher(digest).matches()) { + throw new InventoryUnavailableException(); + } + return digest; + } + + private static String canonicalUid(String value) { + if (value == null || !UID.matcher(value).matches() || value.startsWith("00000000-")) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static String resourceVersion(String value) { + if (value == null || !RESOURCE_VERSION.matcher(value).matches()) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static String dnsLabel(String value) { + if (value == null || !value.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static long positiveLong(JsonNode node) { + long value = exactLong(node, 1L, Long.MAX_VALUE); + return value; + } + + private static int exactInt(JsonNode node, int minimum, int maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToLong()) { + throw new InventoryUnavailableException(); + } + long value = node.longValue(); + if (value < minimum || value > maximum) { + throw new InventoryUnavailableException(); + } + return (int) value; + } + + private static long exactLong(JsonNode node, long minimum, long maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToLong()) { + throw new InventoryUnavailableException(); + } + long value = node.longValue(); + if (value < minimum || value > maximum) { + throw new InventoryUnavailableException(); + } + return value; + } + + @SuppressFBWarnings( + value = "NP_BOOLEAN_RETURN_NULL", + justification = + "The parser intentionally preserves absent or malformed booleans as unknown; callers require explicit true.") + private static Boolean booleanValue(JsonNode node) { + return node != null && node.isBoolean() ? node.booleanValue() : null; + } + + private static String text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException failure) { + throw new InventoryUnavailableException(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private record ContainerConfig(String image, String runtimeConfigSha256) {} + + private record DeploymentObservation( + String name, + String uid, + String resourceVersion, + long generation, + int replicas, + String image, + String verifierConfigSha256) {} + + public record ReplicaSetObservation( + String name, + String uid, + String resourceVersion, + long generation, + int replicas, + String ownerDeploymentName, + String ownerDeploymentUid, + String podTemplateHash, + String image, + String verifierConfigSha256) {} + + /** No Pod or Kubernetes API body is retained, only closed non-secret identity fields. */ + public record PodObservation( + String name, + String uid, + String resourceVersion, + String ownerName, + String ownerUid, + String podTemplateHash, + String image, + String verifierConfigSha256) {} + + public record ValidatorObservation( + String validatorId, + String deploymentName, + String deploymentUid, + long deploymentGeneration, + String deploymentResourceVersion, + int replicas, + String image, + String verifierConfigSha256, + int maxCacheAgeSeconds, + List profiles, + List pods, + List replicaSets) { + public ValidatorObservation { + profiles = List.copyOf(profiles); + pods = List.copyOf(pods); + replicaSets = List.copyOf(replicaSets); + } + } + + public static final class InventorySnapshot { + private final Instant observedAt; + private final String environmentId; + private final String clusterId; + private final String clusterIncarnationUid; + private final String namespace; + private final String namespaceUid; + private final String apiBindingRevision; + private final String apiBindingDigest; + private final String inventoryBindingRevision; + private final String inventoryBindingDigest; + private final List validators; + private final byte[] canonicalBytes; + private final String digest; + + private InventorySnapshot( + Instant observedAt, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + List validators, + byte[] canonicalBytes, + String digest) { + this.observedAt = Objects.requireNonNull(observedAt); + this.environmentId = Objects.requireNonNull(environmentId); + this.clusterId = Objects.requireNonNull(clusterId); + this.clusterIncarnationUid = Objects.requireNonNull(clusterIncarnationUid); + this.namespace = Objects.requireNonNull(namespace); + this.namespaceUid = Objects.requireNonNull(namespaceUid); + this.apiBindingRevision = Objects.requireNonNull(apiBindingRevision); + this.apiBindingDigest = Objects.requireNonNull(apiBindingDigest); + this.inventoryBindingRevision = Objects.requireNonNull(inventoryBindingRevision); + this.inventoryBindingDigest = Objects.requireNonNull(inventoryBindingDigest); + this.validators = List.copyOf(validators); + this.canonicalBytes = Objects.requireNonNull(canonicalBytes).clone(); + this.digest = Objects.requireNonNull(digest); + if (this.canonicalBytes.length == 0 + || this.canonicalBytes.length > MAX_CANONICAL_SNAPSHOT_BYTES + || !sha256(this.canonicalBytes).equals(digest)) { + throw new InventoryUnavailableException(); + } + } + + public Instant observedAt() { + return observedAt; + } + + public String environmentId() { + return environmentId; + } + + public String clusterId() { + return clusterId; + } + + public String clusterIncarnationUid() { + return clusterIncarnationUid; + } + + public String namespace() { + return namespace; + } + + public String namespaceUid() { + return namespaceUid; + } + + public String apiBindingRevision() { + return apiBindingRevision; + } + + public String apiBindingDigest() { + return apiBindingDigest; + } + + public String inventoryBindingRevision() { + return inventoryBindingRevision; + } + + public String inventoryBindingDigest() { + return inventoryBindingDigest; + } + + public List validators() { + return validators; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof InventorySnapshot that)) return false; + return observedAt.equals(that.observedAt) + && environmentId.equals(that.environmentId) + && clusterId.equals(that.clusterId) + && clusterIncarnationUid.equals(that.clusterIncarnationUid) + && namespace.equals(that.namespace) + && namespaceUid.equals(that.namespaceUid) + && apiBindingRevision.equals(that.apiBindingRevision) + && apiBindingDigest.equals(that.apiBindingDigest) + && inventoryBindingRevision.equals(that.inventoryBindingRevision) + && inventoryBindingDigest.equals(that.inventoryBindingDigest) + && validators.equals(that.validators) + && java.util.Arrays.equals(canonicalBytes, that.canonicalBytes) + && digest.equals(that.digest); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + observedAt, + environmentId, + clusterId, + clusterIncarnationUid, + namespace, + namespaceUid, + apiBindingRevision, + apiBindingDigest, + inventoryBindingRevision, + inventoryBindingDigest, + validators, + digest) + + java.util.Arrays.hashCode(canonicalBytes); + } + } + + public static final class InventoryUnavailableException extends RuntimeException { + public InventoryUnavailableException() { + super("Account validator inventory is unavailable or inconsistent"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java new file mode 100644 index 0000000000..2e1929da82 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java @@ -0,0 +1,1269 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.Signature; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.RSAPublicKeySpec; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Bounded Account-local parser and correspondence proof for the interim mounted JWT signer. + * + *

This class exposes no general private-key operation or caller-facing token response. Its + * package-private signing operations are closed readiness probes and the exact Account-owned + * initial Game Session delegation candidate; compact bytes are delivered only to an owner callback + * and wiped after it returns. Local correspondence alone proves no lifecycle or authorization. + */ +public final class AccountMountedJwtSignerBundle { + public static final int MAX_PRIVATE_BUNDLE_BYTES = 64 * 1024; + public static final int MAX_PUBLIC_JWKS_BYTES = 256 * 1024; + private static final int MAX_READINESS_COMPACT_JWT_BYTES = 16 * 1024; + private static final int MAX_DELEGATION_COMPACT_JWT_BYTES = + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES; + private static final int MAX_RSA_BITS = 16_384; + private static final int MIN_RSA_BITS = 3_072; + private static final int MAX_JWKS_KEYS = 64; + private static final int MAX_PRIVATE_KEY_DER_BYTES = 16 * 1024; + private static final int CHALLENGE_NONCE_BYTES = 32; + private static final SecureRandom CHALLENGE_RANDOM = new SecureRandom(); + private static final String ALGORITHM = "RS256"; + static final String READINESS_CANARY_PROFILE = "account-jwt-readiness-canary"; + static final String READINESS_CANARY_TYPE = "account_jwt_readiness_canary"; + static final String READINESS_CANARY_AUDIENCE = "firemud-account-jwt-readiness"; + static final String READINESS_VALIDATOR_ID = "account-service"; + static final String REPRESENTATIVE_PROFILE = GameSessionAccountDelegationProfile.PROFILE; + static final String REPRESENTATIVE_AUDIENCE = GameSessionAccountDelegationProfile.AUDIENCE; + private static final String ISSUER = "firemud-account-service"; + private static final String RESERVED_SUBJECT = "00000000-0000-4000-8000-000000000001"; + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,63}"); + private static final Pattern FINGERPRINT = Pattern.compile("[0-9a-f]{64}"); + private static final Set PRIVATE_BUNDLE_FIELDS = + Set.of( + "version", + "environmentId", + "clusterId", + "namespace", + "operationId", + "generation", + "kid", + "algorithm", + "privateKeyPkcs8", + "publicKeyFingerprint"); + private static final Set JWKS_FIELDS = Set.of("keys"); + private static final Set JWK_FIELDS = + Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final byte[] CHALLENGE_DOMAIN = + new byte[] { + 0, 'F', 'i', 'r', 'e', 'M', 'U', 'D', '/', 'A', 'c', 'c', 'o', 'u', 'n', 't', '/', 'm', 'o', + 'u', 'n', 't', 'e', 'd', '-', 's', 'i', 'g', 'n', 'e', 'r', '-', 'c', 'o', 'r', 'r', 'e', + 's', 'p', 'o', 'n', 'd', 'e', 'n', 'c', 'e', '/', 'v', '1', 0 + }; + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private AccountMountedJwtSignerBundle() {} + + /** + * Reads the explicitly configured Account-only private projection and public JWKS projection. + * Relative file paths must remain beneath their respective configured mount roots. Kubernetes + * projected-volume symlinks are accepted only when their resolved regular files stay beneath + * those roots. + */ + public static LocalObservation observeMounted( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity) { + return readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity) + .observation(); + } + + /** + * Signs only one fixed non-authorizing canary or one fixed-shape representative profile, passes + * the exact compact bytes transiently to the Account-owned callback, then wipes them and returns + * only their digest plus immutable planned identity. This method is package-private so no route, + * ordinary issuer, or other service can request arbitrary JWT signing from the mounted pending + * key. + */ + static SignedProbeDigest signReadinessProbeDigest( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity, + ReadinessProbeSigningSpec spec, + ProbeDeliveryConsumer deliveryConsumer) { + Objects.requireNonNull(spec, "Readiness probe signing specification is required"); + Objects.requireNonNull(deliveryConsumer, "Readiness probe delivery consumer is required"); + VerifiedMountedSigner mounted = + readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); + if (!mounted.observation().expectedIdentity().equals(expectedIdentity) + || !spec.targetGeneration().equals(expectedIdentity.generation()) + || !spec.targetKid().equals(expectedIdentity.kid())) { + throw invalid(); + } + + byte[] header = null; + byte[] claims = null; + byte[] encodedHeader = null; + byte[] encodedClaims = null; + byte[] signingInput = null; + byte[] signatureBytes = null; + byte[] encodedSignature = null; + byte[] compactBytes = null; + byte[] tokenDigest = null; + byte[] deliveryBytes = null; + try { + SignedProbeDigest result; + try { + Map headerFields = new LinkedHashMap<>(); + headerFields.put("alg", ALGORITHM); + headerFields.put("kid", expectedIdentity.kid()); + headerFields.put("typ", "JWT"); + header = canonicalJsonBytes(headerFields); + claims = canonicalJsonBytes(readinessClaims(spec)); + encodedHeader = Base64.getUrlEncoder().withoutPadding().encode(header); + encodedClaims = Base64.getUrlEncoder().withoutPadding().encode(claims); + signingInput = joinCompactParts(encodedHeader, encodedClaims, null); + + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(mounted.privateKey()); + signer.update(signingInput); + signatureBytes = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(mounted.publicKey()); + verifier.update(signingInput); + if (!verifier.verify(signatureBytes)) { + throw invalid(); + } + encodedSignature = Base64.getUrlEncoder().withoutPadding().encode(signatureBytes); + compactBytes = joinCompactParts(encodedHeader, encodedClaims, encodedSignature); + if (compactBytes.length > MAX_READINESS_COMPACT_JWT_BYTES) { + throw invalid(); + } + tokenDigest = MessageDigest.getInstance("SHA-256").digest(compactBytes); + result = + new SignedProbeDigest( + expectedIdentity.operationId(), + spec.validatorId(), + spec.probeKind(), + spec.tokenProfile(), + spec.audience(), + spec.jti(), + expectedIdentity.generation(), + expectedIdentity.kid(), + expectedIdentity.publicKeyFingerprint(), + spec.issuedAtEpochSecond(), + spec.expiresAtEpochSecond(), + java.util.HexFormat.of().formatHex(tokenDigest)); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + throw invalid(); + } + deliveryBytes = compactBytes.clone(); + deliveryConsumer.persistAttemptAndDeliver(result, deliveryBytes); + if (!sha256(deliveryBytes).equals(result.compactTokenSha256())) { + throw invalid(); + } + return result; + } finally { + wipe(header); + wipe(claims); + wipe(encodedHeader); + wipe(encodedClaims); + wipe(signingInput); + wipe(signatureBytes); + wipe(encodedSignature); + wipe(compactBytes); + wipe(tokenDigest); + wipe(deliveryBytes); + } + } + + /** + * Signs only the exact Account-owned, initial Game Session delegation claim shape with the + * already committed signer identity supplied by the owner service. The compact credential is + * passed once to the Account persistence callback and wiped before this method returns. + */ + static SignedDelegationDigest signCommittedGameplayDelegationDigest( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity, + DelegationSigningSpec spec, + DelegationCandidateConsumer candidateConsumer) { + Objects.requireNonNull(spec, "Gameplay delegation signing specification is required"); + Objects.requireNonNull(candidateConsumer, "Gameplay delegation owner callback is required"); + VerifiedMountedSigner mounted = + readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); + AccountGameplayDelegationPendingIdentity identity = spec.identity(); + AccountAuthoritySnapshot authority = spec.authoritySnapshot(); + if (!mounted.observation().expectedIdentity().equals(expectedIdentity) + || !authority.accountId().equals(identity.accountId())) { + throw invalid(); + } + + byte[] header = null; + byte[] claims = null; + byte[] encodedHeader = null; + byte[] encodedClaims = null; + byte[] signingInput = null; + byte[] signatureBytes = null; + byte[] encodedSignature = null; + byte[] compactBytes = null; + byte[] tokenDigest = null; + byte[] callbackBytes = null; + try { + Map headerFields = new LinkedHashMap<>(); + headerFields.put("alg", ALGORITHM); + headerFields.put("kid", expectedIdentity.kid()); + headerFields.put("typ", "JWT"); + header = canonicalJsonBytes(headerFields); + Map delegation = delegationClaims(identity, authority); + if (spec.bound().isPresent()) { + var bound = spec.bound().orElseThrow(); + delegation.put("tenantId", bound.tenantId()); + delegation.put("authorityTuple", bound.authorityTuple()); + delegation.put("membershipVersion", bound.membershipVersion()); + } + net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator + .validateClaims(delegation); + claims = canonicalJsonBytes(delegation); + encodedHeader = Base64.getUrlEncoder().withoutPadding().encode(header); + encodedClaims = Base64.getUrlEncoder().withoutPadding().encode(claims); + signingInput = joinCompactParts(encodedHeader, encodedClaims, null); + + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(mounted.privateKey()); + signer.update(signingInput); + signatureBytes = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(mounted.publicKey()); + verifier.update(signingInput); + if (!verifier.verify(signatureBytes)) { + throw invalid(); + } + encodedSignature = Base64.getUrlEncoder().withoutPadding().encode(signatureBytes); + compactBytes = joinCompactParts(encodedHeader, encodedClaims, encodedSignature); + if (compactBytes.length > MAX_DELEGATION_COMPACT_JWT_BYTES) { + throw invalid(); + } + tokenDigest = MessageDigest.getInstance("SHA-256").digest(compactBytes); + SignedDelegationDigest digest = + new SignedDelegationDigest( + identity.operationId(), + identity.requestId(), + identity.tokenJti(), + expectedIdentity.operationId(), + expectedIdentity.generation(), + expectedIdentity.kid(), + expectedIdentity.publicKeyFingerprint(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + java.util.HexFormat.of().formatHex(tokenDigest)); + callbackBytes = compactBytes.clone(); + try { + candidateConsumer.bindExactCandidate(digest, callbackBytes); + } catch (RuntimeException failure) { + // Callback exception chains must never retain the transient compact credential. + throw invalid(); + } + if (!sha256(callbackBytes).equals(digest.compactTokenSha256())) { + throw invalid(); + } + return digest; + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + throw invalid(); + } finally { + wipe(header); + wipe(claims); + wipe(encodedHeader); + wipe(encodedClaims); + wipe(signingInput); + wipe(signatureBytes); + wipe(encodedSignature); + wipe(compactBytes); + wipe(tokenDigest); + wipe(callbackBytes); + } + } + + private static Map delegationClaims( + AccountGameplayDelegationPendingIdentity identity, AccountAuthoritySnapshot authority) { + if (!authority.accountId().equals(identity.accountId())) { + throw invalid(); + } + Map claims = new LinkedHashMap<>(); + claims.put("iss", ISSUER); + claims.put("sub", authority.accountId().toString()); + claims.put("jti", identity.tokenJti().toString()); + claims.put("accountId", authority.accountId().toString()); + claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + claims.put("iat", identity.issuedAtEpochSecond()); + claims.put("nbf", identity.notBeforeEpochSecond()); + claims.put("exp", identity.expiresAtEpochSecond()); + claims.put("tokenGeneration", "1"); + claims.put( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff())); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", Long.toString(authority.issuanceFence())); + return claims; + } + + private static VerifiedMountedSigner readAndVerifyMounted( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity) { + byte[] privateBytes = null; + try { + if (expectedIdentity == null) { + throw invalid(); + } + validateIdentity(expectedIdentity); + Path privateFile = resolveMountedFile(privateMountRoot, privateBundlePath); + Path publicFile = resolveMountedFile(publicMountRoot, publicJwksPath); + privateBytes = readBounded(privateFile, MAX_PRIVATE_BUNDLE_BYTES); + ParsedPrivateBundle privateBundle = parsePrivateBundle(privateBytes); + Arrays.fill(privateBytes, (byte) 0); + privateBytes = null; + requireExpectedIdentity(privateBundle.identity(), expectedIdentity); + + byte[] publicBytes = readBounded(publicFile, MAX_PUBLIC_JWKS_BYTES); + Map publicKeys; + try { + publicKeys = parsePublicJwks(publicBytes); + } finally { + Arrays.fill(publicBytes, (byte) 0); + } + RSAPublicKey publicKey = publicKeys.get(expectedIdentity.kid()); + if (publicKey == null + || !publicKey.getModulus().equals(privateBundle.publicModulus()) + || !publicKey.getPublicExponent().equals(privateBundle.publicExponent())) { + throw invalid(); + } + String fingerprint = fingerprint(publicKey.getModulus(), publicKey.getPublicExponent()); + if (!fingerprint.equals(expectedIdentity.publicKeyFingerprint()) + || !fingerprint.equals(privateBundle.identity().publicKeyFingerprint())) { + throw invalid(); + } + proveCorrespondence(privateBundle.privateKey(), publicKey); + return new VerifiedMountedSigner( + new LocalObservation(expectedIdentity, fingerprint), + privateBundle.privateKey(), + publicKey); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + // Do not retain path, parser, key, or mounted-file details in a caller-visible failure. + throw invalid(); + } finally { + if (privateBytes != null) { + Arrays.fill(privateBytes, (byte) 0); + } + } + } + + private static Map readinessClaims(ReadinessProbeSigningSpec spec) { + Map claims = new LinkedHashMap<>(); + claims.put("iss", ISSUER); + claims.put("sub", RESERVED_SUBJECT); + claims.put("jti", spec.jti().toString()); + claims.put("aud", spec.audience()); + claims.put("iat", spec.issuedAtEpochSecond()); + claims.put("nbf", spec.issuedAtEpochSecond()); + claims.put("exp", spec.expiresAtEpochSecond()); + if (spec.probeKind() == ProbeKind.CANARY) { + claims.put("tokenProfile", READINESS_CANARY_PROFILE); + claims.put("tokenType", READINESS_CANARY_TYPE); + return claims; + } + if (ControlUiJwtProfileValidator.PROFILE.equals(spec.tokenProfile()) + || PlayerBootstrapJwtProfileValidator.PROFILE.equals(spec.tokenProfile())) { + claims.put("scopedRoles", Map.of()); + } + boolean decimalCounters = + GameSessionAccountDelegationProfile.PROFILE.equals(spec.tokenProfile()); + Object initialCounter = decimalCounters ? "1" : 1L; + claims.put("accountId", RESERVED_SUBJECT); + claims.put("tokenGeneration", initialCounter); + Map authorityTuple = new LinkedHashMap<>(); + authorityTuple.put("issuerAuthGeneration", initialCounter); + authorityTuple.put("accountAuthorityGeneration", initialCounter); + authorityTuple.put("tenantAuthorityGeneration", Map.of()); + authorityTuple.put("membershipAuthorityGeneration", Map.of()); + authorityTuple.put("privateRealmGrantVersions", List.of()); + claims.put("authorityTuple", authorityTuple); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", initialCounter); + return claims; + } + + private static byte[] canonicalJsonBytes(Map fields) throws Exception { + String json = STRICT_JSON.writeValueAsString(fields); + return Rfc8785CanonicalJson.canonicalizeUtf8(json); + } + + private static byte[] joinCompactParts(byte[] header, byte[] claims, byte[] signature) { + int signatureLength = signature == null ? 0 : signature.length; + int separatorCount = signature == null ? 1 : 2; + byte[] compact = new byte[header.length + claims.length + signatureLength + separatorCount]; + int offset = 0; + System.arraycopy(header, 0, compact, offset, header.length); + offset += header.length; + compact[offset++] = (byte) '.'; + System.arraycopy(claims, 0, compact, offset, claims.length); + offset += claims.length; + if (signature != null) { + compact[offset++] = (byte) '.'; + System.arraycopy(signature, 0, compact, offset, signature.length); + } + return compact; + } + + private static void wipe(byte[] bytes) { + if (bytes != null) { + Arrays.fill(bytes, (byte) 0); + } + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (GeneralSecurityException ex) { + throw invalid(); + } + } + + /** + * Builds the binary, domain-separated challenge used only by the local correspondence proof. Its + * leading NUL makes it structurally distinct from an ASCII compact JWT serialization. + */ + static byte[] correspondenceChallenge(byte[] nonce) { + if (nonce == null || nonce.length != CHALLENGE_NONCE_BYTES) { + throw invalid(); + } + byte[] challenge = Arrays.copyOf(CHALLENGE_DOMAIN, CHALLENGE_DOMAIN.length + nonce.length); + System.arraycopy(nonce, 0, challenge, CHALLENGE_DOMAIN.length, nonce.length); + return challenge; + } + + static void validateStrongRsaCrtPrivateKey(PrivateKey privateKey) { + if (!(privateKey instanceof RSAPrivateCrtKey rsaPrivateKey) + || !"RSA".equalsIgnoreCase(privateKey.getAlgorithm())) { + throw invalid(); + } + BigInteger modulus = rsaPrivateKey.getModulus(); + BigInteger publicExponent = rsaPrivateKey.getPublicExponent(); + BigInteger privateExponent = rsaPrivateKey.getPrivateExponent(); + BigInteger primeP = rsaPrivateKey.getPrimeP(); + BigInteger primeQ = rsaPrivateKey.getPrimeQ(); + BigInteger primeExponentP = rsaPrivateKey.getPrimeExponentP(); + BigInteger primeExponentQ = rsaPrivateKey.getPrimeExponentQ(); + BigInteger crtCoefficient = rsaPrivateKey.getCrtCoefficient(); + if (!positive(modulus) + || modulus.bitLength() < MIN_RSA_BITS + || modulus.bitLength() > MAX_RSA_BITS + || !BigInteger.valueOf(65_537).equals(publicExponent) + || !positive(privateExponent) + || !positive(primeP) + || !positive(primeQ) + || primeP.equals(primeQ) + || !positive(primeExponentP) + || !positive(primeExponentQ) + || !positive(crtCoefficient)) { + throw invalid(); + } + BigInteger pMinusOne = primeP.subtract(BigInteger.ONE); + BigInteger qMinusOne = primeQ.subtract(BigInteger.ONE); + BigInteger lambda = pMinusOne.divide(pMinusOne.gcd(qMinusOne)).multiply(qMinusOne); + if (!primeP.multiply(primeQ).equals(modulus) + || !privateExponent.multiply(publicExponent).mod(lambda).equals(BigInteger.ONE) + || !privateExponent.mod(pMinusOne).equals(primeExponentP) + || !privateExponent.mod(qMinusOne).equals(primeExponentQ) + || !primeQ.modInverse(primeP).equals(crtCoefficient)) { + throw invalid(); + } + } + + private static void validateIdentity(ExpectedIdentity identity) { + if (!validIdentityValue(identity.environmentId()) + || !validIdentityValue(identity.clusterId()) + || !validIdentityValue(identity.namespace()) + || !validUuidV4(identity.operationId()) + || identity.generation() == null + || !GENERATION.matcher(identity.generation()).matches() + || identity.kid() == null + || !KID.matcher(identity.kid()).matches() + || identity.publicKeyFingerprint() == null + || !FINGERPRINT.matcher(identity.publicKeyFingerprint()).matches()) { + throw invalid(); + } + } + + private static boolean validIdentityValue(String value) { + if (value == null || value.isBlank() || value.length() > 128) { + return false; + } + for (int index = 0; index < value.length(); index++) { + if (Character.isISOControl(value.charAt(index))) { + return false; + } + } + return true; + } + + private static boolean validUuidV4(String value) { + if (value == null) { + return false; + } + try { + UUID uuid = UUID.fromString(value); + return uuid.toString().equals(value) && uuid.version() == 4 && uuid.variant() == 2; + } catch (IllegalArgumentException ex) { + return false; + } + } + + private static void requireExpectedIdentity(ExpectedIdentity actual, ExpectedIdentity expected) { + if (!actual.equals(expected)) { + throw invalid(); + } + } + + private static ParsedPrivateBundle parsePrivateBundle(byte[] contents) { + if (contents == null || contents.length == 0 || contents.length > MAX_PRIVATE_BUNDLE_BYTES) { + throw invalid(); + } + try { + JsonNode root = strictJson(contents); + requireOnlyFields(root, PRIVATE_BUNDLE_FIELDS); + if (root.size() != PRIVATE_BUNDLE_FIELDS.size()) { + throw invalid(); + } + JsonNode version = root.get("version"); + if (version == null + || version.isNull() + || !version.isIntegralNumber() + || !version.canConvertToInt() + || version.intValue() != 1) { + throw invalid(); + } + ExpectedIdentity identity = + new ExpectedIdentity( + requiredText(root, "environmentId", 128), + requiredText(root, "clusterId", 128), + requiredText(root, "namespace", 128), + requiredText(root, "operationId", 36), + requiredText(root, "generation", 64), + requiredText(root, "kid", 64), + requiredText(root, "publicKeyFingerprint", 64)); + validateIdentity(identity); + if (!ALGORITHM.equals(requiredText(root, "algorithm", 8))) { + throw invalid(); + } + + String encodedPrivateKey = requiredText(root, "privateKeyPkcs8", 24 * 1024); + byte[] privateDer = decodeCanonicalBase64Url(encodedPrivateKey, MAX_PRIVATE_KEY_DER_BYTES); + try { + PrivateKey privateKey = + KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateDer)); + validateStrongRsaCrtPrivateKey(privateKey); + RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; + byte[] canonicalEncoding = privateKey.getEncoded(); + try { + if (canonicalEncoding == null || !Arrays.equals(privateDer, canonicalEncoding)) { + throw invalid(); + } + } finally { + if (canonicalEncoding != null) { + Arrays.fill(canonicalEncoding, (byte) 0); + } + } + return new ParsedPrivateBundle( + privateKey, identity, rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent()); + } finally { + Arrays.fill(privateDer, (byte) 0); + } + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (CharacterCodingException | GeneralSecurityException | RuntimeException ex) { + throw invalid(); + } + } + + private static Map parsePublicJwks(byte[] contents) { + if (contents == null || contents.length == 0 || contents.length > MAX_PUBLIC_JWKS_BYTES) { + throw invalid(); + } + try { + JsonNode root = strictJson(contents); + requireOnlyFields(root, JWKS_FIELDS); + if (root.size() != 1) { + throw invalid(); + } + JsonNode keysNode = root.get("keys"); + if (keysNode == null + || !keysNode.isArray() + || keysNode.isEmpty() + || keysNode.size() > MAX_JWKS_KEYS) { + throw invalid(); + } + Map keys = new HashMap<>(); + Set seenKids = new HashSet<>(); + for (JsonNode jwk : keysNode) { + requireOnlyFields(jwk, JWK_FIELDS); + String keyType = requiredText(jwk, "kty", 8); + String use = requiredText(jwk, "use", 8); + String algorithm = requiredText(jwk, "alg", 8); + String kid = requiredText(jwk, "kid", 64); + String encodedModulus = requiredText(jwk, "n", 4_096); + String encodedExponent = requiredText(jwk, "e", 16); + if (!"RSA".equals(keyType) + || !"sig".equals(use) + || !ALGORITHM.equals(algorithm) + || !KID.matcher(kid).matches() + || !seenKids.add(kid)) { + throw invalid(); + } + JsonNode keyOps = jwk.get("key_ops"); + if (keyOps != null) { + if (!keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())) { + throw invalid(); + } + } + byte[] modulusBytes = decodeCanonicalBase64Url(encodedModulus, 2_048); + byte[] exponentBytes = decodeCanonicalBase64Url(encodedExponent, 8); + try { + if (modulusBytes.length == 0 + || modulusBytes[0] == 0 + || exponentBytes.length == 0 + || exponentBytes[0] == 0) { + throw invalid(); + } + BigInteger modulus = new BigInteger(1, modulusBytes); + BigInteger exponent = new BigInteger(1, exponentBytes); + if (modulus.bitLength() < MIN_RSA_BITS + || modulus.bitLength() > MAX_RSA_BITS + || !modulus.testBit(0) + || !BigInteger.valueOf(65_537).equals(exponent)) { + throw invalid(); + } + RSAPublicKey publicKey = + (RSAPublicKey) + KeyFactory.getInstance("RSA") + .generatePublic(new RSAPublicKeySpec(modulus, exponent)); + keys.put(kid, publicKey); + } finally { + Arrays.fill(modulusBytes, (byte) 0); + Arrays.fill(exponentBytes, (byte) 0); + } + } + return Map.copyOf(keys); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (CharacterCodingException | GeneralSecurityException | RuntimeException ex) { + throw invalid(); + } + } + + private static JsonNode strictJson(byte[] contents) throws CharacterCodingException { + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(contents)) + .toString(); + if (text.startsWith("\uFEFF")) { + throw invalid(); + } + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || root.isNull()) { + throw invalid(); + } + return root; + } + + private static void requireOnlyFields(JsonNode node, Set allowedFields) { + if (node == null || !node.isObject()) { + throw invalid(); + } + for (Map.Entry field : node.properties()) { + if (!allowedFields.contains(field.getKey())) { + throw invalid(); + } + } + } + + private static String requiredText(JsonNode object, String name, int maxLength) { + JsonNode value = object.get(name); + if (value == null || value.isNull() || !value.isTextual()) { + throw invalid(); + } + String text = value.textValue(); + if (text == null || text.isEmpty() || text.length() > maxLength) { + throw invalid(); + } + return text; + } + + private static byte[] decodeCanonicalBase64Url(String encoded, int maxBytes) { + if (encoded == null || encoded.isEmpty()) { + throw invalid(); + } + byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(encoded); + } catch (IllegalArgumentException ex) { + throw invalid(); + } + byte[] canonical = Base64.getUrlEncoder().withoutPadding().encode(decoded); + boolean canonicalEncoding = canonical.length == encoded.length(); + for (int index = 0; canonicalEncoding && index < canonical.length; index++) { + canonicalEncoding = (char) Byte.toUnsignedInt(canonical[index]) == encoded.charAt(index); + } + Arrays.fill(canonical, (byte) 0); + if (decoded.length == 0 || decoded.length > maxBytes || !canonicalEncoding) { + Arrays.fill(decoded, (byte) 0); + throw invalid(); + } + return decoded; + } + + private static Path resolveMountedFile(Path configuredRoot, Path configuredRelativeFile) + throws IOException { + if (configuredRoot == null + || configuredRelativeFile == null + || !configuredRoot.isAbsolute() + || configuredRelativeFile.isAbsolute() + || configuredRelativeFile.toString().isBlank()) { + throw invalid(); + } + for (Path segment : configuredRelativeFile) { + if (".".equals(segment.toString()) || "..".equals(segment.toString())) { + throw invalid(); + } + } + Path mountRoot = configuredRoot.toRealPath(); + if (!Files.isDirectory(mountRoot, LinkOption.NOFOLLOW_LINKS)) { + throw invalid(); + } + Path resolvedFile = mountRoot.resolve(configuredRelativeFile).toRealPath(); + if (!resolvedFile.startsWith(mountRoot) + || !Files.isRegularFile(resolvedFile, LinkOption.NOFOLLOW_LINKS)) { + throw invalid(); + } + return resolvedFile; + } + + private static byte[] readBounded(Path path, int maxBytes) throws IOException { + byte[] scratch = new byte[maxBytes + 1]; + try { + try (SeekableByteChannel channel = + Files.newByteChannel(path, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS))) { + ByteBuffer buffer = ByteBuffer.wrap(scratch); + int total = 0; + while (true) { + int count = channel.read(buffer); + if (count < 0) { + break; + } + if (count == 0) { + continue; + } + total += count; + if (total > maxBytes) { + throw invalid(); + } + } + if (channel.position() != channel.size() || total != channel.size()) { + throw invalid(); + } + return Arrays.copyOf(scratch, total); + } + } finally { + Arrays.fill(scratch, (byte) 0); + } + } + + private static void proveCorrespondence(PrivateKey privateKey, RSAPublicKey publicKey) + throws GeneralSecurityException { + byte[] nonce = new byte[CHALLENGE_NONCE_BYTES]; + byte[] challenge = null; + byte[] signatureBytes = null; + try { + CHALLENGE_RANDOM.nextBytes(nonce); + challenge = correspondenceChallenge(nonce); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(privateKey); + signer.update(challenge); + signatureBytes = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(publicKey); + verifier.update(challenge); + if (!verifier.verify(signatureBytes)) { + throw invalid(); + } + } finally { + Arrays.fill(nonce, (byte) 0); + if (challenge != null) { + Arrays.fill(challenge, (byte) 0); + } + if (signatureBytes != null) { + Arrays.fill(signatureBytes, (byte) 0); + } + } + } + + private static String fingerprint(BigInteger modulus, BigInteger exponent) { + String canonicalJwk = + "{\"e\":\"" + + base64Url(unsignedBytes(exponent)) + + "\",\"kty\":\"RSA\",\"n\":\"" + + base64Url(unsignedBytes(modulus)) + + "\"}"; + try { + byte[] digest = + MessageDigest.getInstance("SHA-256") + .digest(canonicalJwk.getBytes(StandardCharsets.US_ASCII)); + return java.util.HexFormat.of().formatHex(digest); + } catch (GeneralSecurityException ex) { + throw invalid(); + } + } + + private static byte[] unsignedBytes(BigInteger value) { + byte[] encoded = value.toByteArray(); + if (encoded.length > 1 && encoded[0] == 0) { + return Arrays.copyOfRange(encoded, 1, encoded.length); + } + return encoded; + } + + private static String base64Url(byte[] bytes) { + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } finally { + Arrays.fill(bytes, (byte) 0); + } + } + + private static boolean positive(BigInteger value) { + return value != null && value.signum() > 0; + } + + private static InvalidMountedSignerBundleException invalid() { + return new InvalidMountedSignerBundleException(); + } + + /** Caller-supplied durable request identity; it is not authorization or proof of provisioning. */ + public record ExpectedIdentity( + String environmentId, + String clusterId, + String namespace, + String operationId, + String generation, + String kid, + String publicKeyFingerprint) {} + + /** Closed signing input built only from the issuance repository's locked owner readback. */ + record DelegationSigningSpec( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot, + Optional bound) { + DelegationSigningSpec( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot) { + this(identity, authoritySnapshot, Optional.empty()); + } + + DelegationSigningSpec { + Objects.requireNonNull(bound); + Objects.requireNonNull(identity, "Persisted pending identity is required"); + Objects.requireNonNull(authoritySnapshot, "Persisted Account authority is required"); + if (!authoritySnapshot.accountId().equals(identity.accountId()) + || identity.issuedAtEpochSecond() <= 0L + || identity.notBeforeEpochSecond() <= 0L + || identity.notBeforeEpochSecond() > identity.issuedAtEpochSecond() + || identity.expiresAtEpochSecond() <= identity.issuedAtEpochSecond() + || identity.expiresAtEpochSecond() - identity.issuedAtEpochSecond() + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw invalid(); + } + } + } + + record BoundDelegationClaims( + String tenantId, Map authorityTuple, Map membershipVersion) { + BoundDelegationClaims { + net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile + .requirePublicTenantBoundAuthority(tenantId, authorityTuple, membershipVersion); + authorityTuple = Map.copyOf(authorityTuple); + membershipVersion = Map.copyOf(membershipVersion); + } + } + + @FunctionalInterface + interface DelegationCandidateConsumer { + /** The caller persists the exact candidate before any internal transient handoff. */ + void bindExactCandidate(SignedDelegationDigest digest, byte[] compactJwt); + } + + /** Non-secret operation, signer and token-hash identity; never includes compact JWT bytes. */ + static final class SignedDelegationDigest { + private final UUID issuanceOperationId; + private final UUID requestId; + private final UUID jti; + private final String signerOperationId; + private final String signerGeneration; + private final String kid; + private final String publicKeyFingerprint; + private final long issuedAtEpochSecond; + private final long notBeforeEpochSecond; + private final long expiresAtEpochSecond; + private final String compactTokenSha256; + + private SignedDelegationDigest( + UUID issuanceOperationId, + UUID requestId, + UUID jti, + String signerOperationId, + String signerGeneration, + String kid, + String publicKeyFingerprint, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256) { + this.issuanceOperationId = Objects.requireNonNull(issuanceOperationId); + this.requestId = Objects.requireNonNull(requestId); + this.jti = Objects.requireNonNull(jti); + this.signerOperationId = Objects.requireNonNull(signerOperationId); + this.signerGeneration = Objects.requireNonNull(signerGeneration); + this.kid = Objects.requireNonNull(kid); + this.publicKeyFingerprint = Objects.requireNonNull(publicKeyFingerprint); + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.notBeforeEpochSecond = notBeforeEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + if (compactTokenSha256 == null || !FINGERPRINT.matcher(compactTokenSha256).matches()) { + throw invalid(); + } + this.compactTokenSha256 = compactTokenSha256; + } + + UUID issuanceOperationId() { + return issuanceOperationId; + } + + UUID requestId() { + return requestId; + } + + UUID jti() { + return jti; + } + + String signerOperationId() { + return signerOperationId; + } + + String signerGeneration() { + return signerGeneration; + } + + String kid() { + return kid; + } + + String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + long notBeforeEpochSecond() { + return notBeforeEpochSecond; + } + + long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + String compactTokenSha256() { + return compactTokenSha256; + } + + @Override + public String toString() { + return "SignedDelegationDigest[redacted]"; + } + } + + public enum ProbeKind { + CANARY, + REPRESENTATIVE + } + + @FunctionalInterface + interface ProbeDeliveryConsumer { + /** The caller must durably pin {@code digest} before passing the transient bytes onward. */ + void persistAttemptAndDeliver(SignedProbeDigest digest, byte[] compactJwt); + } + + /** A closed claim-shape input; its constructor permits only the two declared readiness forms. */ + record ReadinessProbeSigningSpec( + String validatorId, + ProbeKind probeKind, + String tokenProfile, + String audience, + UUID jti, + String targetGeneration, + String targetKid, + long issuedAtEpochSecond, + long expiresAtEpochSecond) { + ReadinessProbeSigningSpec { + if (validatorId == null + || !READINESS_VALIDATOR_ID.equals(validatorId) + || probeKind == null + || jti == null + || jti.version() != 4 + || jti.variant() != 2 + || targetGeneration == null + || !GENERATION.matcher(targetGeneration).matches() + || targetKid == null + || !KID.matcher(targetKid).matches() + || issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond > 300L) { + throw invalid(); + } + if (probeKind == ProbeKind.CANARY) { + if (!READINESS_CANARY_PROFILE.equals(tokenProfile) + || !READINESS_CANARY_AUDIENCE.equals(audience)) { + throw invalid(); + } + } else { + boolean exactProfileAudience = + (ControlUiJwtProfileValidator.PROFILE.equals(tokenProfile) + && ControlUiJwtProfileValidator.AUDIENCE.equals(audience)) + || (PlayerBootstrapJwtProfileValidator.PROFILE.equals(tokenProfile) + && PlayerBootstrapJwtProfileValidator.AUDIENCE.equals(audience)) + || (REPRESENTATIVE_PROFILE.equals(tokenProfile) + && REPRESENTATIVE_AUDIENCE.equals(audience)); + if (!exactProfileAudience) { + throw invalid(); + } + } + } + } + + /** Non-secret output from the one constrained signing operation; it never contains JWT bytes. */ + public static final class SignedProbeDigest { + private final String operationId; + private final String validatorId; + private final ProbeKind probeKind; + private final String tokenProfile; + private final String audience; + private final UUID jti; + private final String targetGeneration; + private final String targetKid; + private final String publicKeyFingerprint; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final String compactTokenSha256; + + private SignedProbeDigest( + String operationId, + String validatorId, + ProbeKind probeKind, + String tokenProfile, + String audience, + UUID jti, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256) { + this.operationId = operationId; + this.validatorId = validatorId; + this.probeKind = probeKind; + this.tokenProfile = tokenProfile; + this.audience = audience; + this.jti = jti; + this.targetGeneration = targetGeneration; + this.targetKid = targetKid; + this.publicKeyFingerprint = publicKeyFingerprint; + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + this.compactTokenSha256 = compactTokenSha256; + } + + public String operationId() { + return operationId; + } + + public String validatorId() { + return validatorId; + } + + public ProbeKind probeKind() { + return probeKind; + } + + public String tokenProfile() { + return tokenProfile; + } + + public String audience() { + return audience; + } + + public UUID jti() { + return jti; + } + + public String targetGeneration() { + return targetGeneration; + } + + public String targetKid() { + return targetKid; + } + + public String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + @Override + public String toString() { + return "AccountMountedJwtSignerBundle.SignedProbeDigest[operation=" + + operationId + + ", probeKind=" + + probeKind + + ", tokenBytes=discarded, authorization=none, verification=unproved]"; + } + } + + /** Non-secret, process-local observation with no token-signing or private-key accessor. */ + public static final class LocalObservation { + private final ExpectedIdentity expectedIdentity; + private final String publicKeyFingerprint; + + private LocalObservation(ExpectedIdentity expectedIdentity, String publicKeyFingerprint) { + this.expectedIdentity = expectedIdentity; + this.publicKeyFingerprint = publicKeyFingerprint; + } + + public ExpectedIdentity expectedIdentity() { + return expectedIdentity; + } + + public String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + public boolean localPrivatePublicCorrespondenceObserved() { + return true; + } + + @Override + public String toString() { + return "AccountMountedJwtSignerBundle.LocalObservation[local correspondence observed; " + + "authorization=none, provisioning=unproved, readiness=unproved]"; + } + } + + /** Safe generic failure for malformed, unavailable, or mismatched mounted projections. */ + public static final class InvalidMountedSignerBundleException extends IllegalArgumentException { + private InvalidMountedSignerBundleException() { + super("Mounted signer correspondence is unavailable or invalid"); + } + } + + private record ParsedPrivateBundle( + PrivateKey privateKey, + ExpectedIdentity identity, + BigInteger publicModulus, + BigInteger publicExponent) {} + + private record VerifiedMountedSigner( + LocalObservation observation, PrivateKey privateKey, RSAPublicKey publicKey) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java new file mode 100644 index 0000000000..7122b4dc2c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java @@ -0,0 +1,403 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Pattern; +import javax.crypto.AEADBadTagException; +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** Account-owned AEAD primitive for exact, bounded response-byte recovery. */ +@Component +public final class AccountResponseEnvelopeCryptography { + static final int NONCE_BYTES = 12; + static final int TAG_BITS = 128; + static final int TAG_BYTES = TAG_BITS / Byte.SIZE; + static final int MAX_RESPONSE_BYTES = 64 * 1024; + static final int MAX_BINDING_BYTES = 16 * 1024; + private static final byte[] MAGIC = {'F', 'R', 'E', 'A'}; + private static final byte FORMAT_VERSION = 1; + private static final int FIXED_HEADER_BYTES = MAGIC.length + 1 + 1 + Long.BYTES + NONCE_BYTES; + private static final int MAX_HEADER_BYTES = FIXED_HEADER_BYTES + 32; + static final int MAX_ENVELOPE_BYTES = MAX_HEADER_BYTES + MAX_RESPONSE_BYTES + TAG_BYTES; + private static final byte[] AAD_DOMAIN = + "firemud/account-response-envelope/aad/v1".getBytes(StandardCharsets.US_ASCII); + private static final byte[] BINDING_DOMAIN = + "firemud/account-response-envelope/binding/v1".getBytes(StandardCharsets.US_ASCII); + private static final Pattern SAFE_IDENTIFIER = Pattern.compile("[A-Za-z0-9._:/@+-]{1,256}"); + + private final AccountResponseEnvelopeKeyring keyring; + private final Clock clock; + private final SecureRandom secureRandom; + + @Autowired + public AccountResponseEnvelopeCryptography(AccountResponseEnvelopeKeyring keyring) { + this(keyring, Clock.systemUTC(), new SecureRandom()); + } + + AccountResponseEnvelopeCryptography( + AccountResponseEnvelopeKeyring keyring, Clock clock, SecureRandom secureRandom) { + this.keyring = Objects.requireNonNull(keyring, "keyring"); + this.clock = Objects.requireNonNull(clock, "clock"); + this.secureRandom = Objects.requireNonNull(secureRandom, "secureRandom"); + } + + /** Encrypts exact response bytes under the current active key and immutable operation expiry. */ + public EncryptedResponseEnvelope encrypt( + Binding binding, byte[] exactResponseBytes, Instant immutableRecoveryExpiry) { + Objects.requireNonNull(binding, "binding"); + validateResponse(exactResponseBytes); + long expiryMillis = exactEpochMillis(immutableRecoveryExpiry); + if (!clock.instant().isBefore(immutableRecoveryExpiry)) { + throw new IllegalArgumentException("Recovery expiry must be in the future when sealing"); + } + + AccountResponseEnvelopeKeyring.KeyEntry active = keyring.readCurrent().activeKey(); + byte[] nonce = new byte[NONCE_BYTES]; + secureRandom.nextBytes(nonce); + byte[] header = encodeHeader(active.keyId(), expiryMillis, nonce); + byte[] bindingBytes = canonicalBinding(binding); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, active.secretKey(), new GCMParameterSpec(TAG_BITS, nonce)); + cipher.updateAAD(associatedData(header, bindingBytes)); + byte[] ciphertext = cipher.doFinal(exactResponseBytes); + if (ciphertext.length != exactResponseBytes.length + TAG_BYTES) { + throw new CryptographyUnavailableException(); + } + return new EncryptedResponseEnvelope(concatenate(header, ciphertext)); + } catch (GeneralSecurityException ex) { + throw new CryptographyUnavailableException(); + } + } + + /** + * Decrypts only for the exact immutable owner binding and expiry read from the durable operation. + * The caller must establish current authorization and postconditions before invoking this method. + */ + public byte[] decrypt( + EncryptedResponseEnvelope envelope, Binding expectedBinding, Instant expectedRecoveryExpiry) { + Objects.requireNonNull(envelope, "envelope"); + Objects.requireNonNull(expectedBinding, "expectedBinding"); + long expectedExpiryMillis = exactEpochMillis(expectedRecoveryExpiry); + byte[] encoded = envelope.bytes(); + Header header = parseHeader(encoded); + if (header.expiryMillis() != expectedExpiryMillis) { + throw new IntegrityException(); + } + Instant now = clock.instant(); + if (!now.isBefore(expectedRecoveryExpiry)) { + throw new ResponseRecoveryExpiredException(); + } + + AccountResponseEnvelopeKeyring.KeyEntry key = + keyring.readCurrent().decryptionKey(header.keyId(), now); + byte[] ciphertext = Arrays.copyOfRange(encoded, header.headerLength(), encoded.length); + byte[] bindingBytes = canonicalBinding(expectedBinding); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init( + Cipher.DECRYPT_MODE, key.secretKey(), new GCMParameterSpec(TAG_BITS, header.nonce())); + cipher.updateAAD(associatedData(Arrays.copyOf(encoded, header.headerLength()), bindingBytes)); + return cipher.doFinal(ciphertext); + } catch (AEADBadTagException ex) { + throw new IntegrityException(); + } catch (GeneralSecurityException ex) { + throw new CryptographyUnavailableException(); + } + } + + private static byte[] encodeHeader(String keyId, long expiryMillis, byte[] nonce) { + byte[] keyIdBytes = keyId.getBytes(StandardCharsets.US_ASCII); + if (keyIdBytes.length == 0 || keyIdBytes.length > 32 || nonce.length != NONCE_BYTES) { + throw new CryptographyUnavailableException(); + } + ByteBuffer header = ByteBuffer.allocate(FIXED_HEADER_BYTES + keyIdBytes.length); + header.put(MAGIC); + header.put(FORMAT_VERSION); + header.put((byte) keyIdBytes.length); + header.put(keyIdBytes); + header.putLong(expiryMillis); + header.put(nonce); + return header.array(); + } + + private static Header parseHeader(byte[] encoded) { + if (encoded == null + || encoded.length < FIXED_HEADER_BYTES + 1 + TAG_BYTES + 1 + || encoded.length > MAX_ENVELOPE_BYTES) { + throw new IntegrityException(); + } + ByteBuffer input = ByteBuffer.wrap(encoded); + byte[] magic = new byte[MAGIC.length]; + input.get(magic); + if (!Arrays.equals(magic, MAGIC) || input.get() != FORMAT_VERSION) { + throw new IntegrityException(); + } + int keyIdLength = Byte.toUnsignedInt(input.get()); + if (keyIdLength < 1 + || keyIdLength > 32 + || input.remaining() < keyIdLength + Long.BYTES + NONCE_BYTES + TAG_BYTES + 1) { + throw new IntegrityException(); + } + byte[] keyIdBytes = new byte[keyIdLength]; + input.get(keyIdBytes); + for (byte value : keyIdBytes) { + if (Byte.toUnsignedInt(value) > 0x7e || Byte.toUnsignedInt(value) < 0x21) { + throw new IntegrityException(); + } + } + String keyId = new String(keyIdBytes, StandardCharsets.US_ASCII); + if (!keyId.matches("[A-Za-z0-9_-]{1,32}")) { + throw new IntegrityException(); + } + long expiryMillis = input.getLong(); + if (expiryMillis <= 0) { + throw new IntegrityException(); + } + byte[] nonce = new byte[NONCE_BYTES]; + input.get(nonce); + int ciphertextBytes = input.remaining(); + if (ciphertextBytes < TAG_BYTES + 1 || ciphertextBytes > MAX_RESPONSE_BYTES + TAG_BYTES) { + throw new IntegrityException(); + } + return new Header(keyId, expiryMillis, nonce, input.position()); + } + + private static byte[] canonicalBinding(Binding binding) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + output.write(BINDING_DOMAIN); + writeString(output, binding.operation()); + writeString(output, binding.requestId()); + writeBytes(output, binding.requestDigest()); + writeString(output, binding.callerWorkload()); + writeString(output, binding.bindingId()); + writeOptionalString(output, binding.lineageId()); + writeOptionalString(output, binding.replacementId()); + writeOptionalString(output, binding.leaseId()); + output.writeLong(binding.issuanceFence()); + writeBytes(output, binding.authorityTupleCanonicalBytes()); + writeBytes(output, binding.membershipVersionMapCanonicalBytes()); + writeBytes(output, binding.authorityEvidenceBundleCanonicalBytes()); + } catch (IOException ex) { + throw new IntegrityException(); + } + byte[] encoded = bytes.toByteArray(); + if (encoded.length > MAX_BINDING_BYTES) { + throw new IllegalArgumentException("Response-envelope binding exceeds its size bound"); + } + return encoded; + } + + private static void writeOptionalString(DataOutputStream output, Optional value) + throws IOException { + output.writeBoolean(value.isPresent()); + if (value.isPresent()) { + writeString(output, value.orElseThrow()); + } + } + + private static void writeString(DataOutputStream output, String value) throws IOException { + byte[] encoded = value.getBytes(StandardCharsets.US_ASCII); + output.writeInt(encoded.length); + output.write(encoded); + } + + private static void writeBytes(DataOutputStream output, byte[] value) throws IOException { + output.writeInt(value.length); + output.write(value); + } + + private static byte[] associatedData(byte[] header, byte[] binding) { + ByteBuffer aad = + ByteBuffer.allocate(AAD_DOMAIN.length + Integer.BYTES * 2 + header.length + binding.length); + aad.put(AAD_DOMAIN); + aad.putInt(header.length); + aad.put(header); + aad.putInt(binding.length); + aad.put(binding); + return aad.array(); + } + + private static byte[] concatenate(byte[] header, byte[] ciphertext) { + if (header.length + ciphertext.length > MAX_ENVELOPE_BYTES) { + throw new IllegalArgumentException("Response envelope exceeds its size bound"); + } + byte[] result = Arrays.copyOf(header, header.length + ciphertext.length); + System.arraycopy(ciphertext, 0, result, header.length, ciphertext.length); + return result; + } + + private static void validateResponse(byte[] response) { + if (response == null || response.length == 0 || response.length > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Response bytes are empty or exceed their size bound"); + } + } + + private static long exactEpochMillis(Instant instant) { + Objects.requireNonNull(instant, "immutableRecoveryExpiry"); + try { + long millis = instant.toEpochMilli(); + if (!Instant.ofEpochMilli(millis).equals(instant) || millis <= 0) { + throw new IllegalArgumentException("Recovery expiry must be a positive exact millisecond"); + } + return millis; + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Recovery expiry is outside the supported range"); + } + } + + private static void validateIdentifier(String value, String fieldName) { + if (value == null || !SAFE_IDENTIFIER.matcher(value).matches()) { + throw new IllegalArgumentException(fieldName + " is not a canonical identifier"); + } + } + + private static void validateOptional(Optional value, String fieldName) { + Objects.requireNonNull(value, fieldName); + value.ifPresent(item -> validateIdentifier(item, fieldName)); + } + + private record Header(String keyId, long expiryMillis, byte[] nonce, int headerLength) {} + + /** + * Immutable, typed operation binding. The owner must derive every field from durable evidence. + */ + public record Binding( + String operation, + String requestId, + byte[] requestDigest, + String callerWorkload, + String bindingId, + Optional lineageId, + Optional replacementId, + Optional leaseId, + long issuanceFence, + byte[] authorityTupleCanonicalBytes, + byte[] membershipVersionMapCanonicalBytes, + byte[] authorityEvidenceBundleCanonicalBytes) { + public Binding { + validateIdentifier(operation, "operation"); + validateIdentifier(requestId, "requestId"); + validateIdentifier(callerWorkload, "callerWorkload"); + validateIdentifier(bindingId, "bindingId"); + validateOptional(lineageId, "lineageId"); + validateOptional(replacementId, "replacementId"); + validateOptional(leaseId, "leaseId"); + if (requestDigest == null || requestDigest.length != 32) { + throw new IllegalArgumentException("requestDigest must contain exactly 32 bytes"); + } + if (authorityTupleCanonicalBytes == null + || authorityTupleCanonicalBytes.length == 0 + || authorityTupleCanonicalBytes.length > 8 * 1024) { + throw new IllegalArgumentException("authority tuple bytes are empty or exceed their bound"); + } + if (membershipVersionMapCanonicalBytes == null + || membershipVersionMapCanonicalBytes.length == 0 + || membershipVersionMapCanonicalBytes.length > 4 * 1024) { + throw new IllegalArgumentException( + "membership version map bytes are empty or exceed their bound"); + } + if (authorityEvidenceBundleCanonicalBytes == null + || authorityEvidenceBundleCanonicalBytes.length == 0 + || authorityEvidenceBundleCanonicalBytes.length > 8 * 1024) { + throw new IllegalArgumentException( + "authority evidence bundle bytes are empty or exceed their bound"); + } + if (issuanceFence <= 0) { + throw new IllegalArgumentException("issuanceFence must be positive"); + } + requestDigest = requestDigest.clone(); + authorityTupleCanonicalBytes = authorityTupleCanonicalBytes.clone(); + membershipVersionMapCanonicalBytes = membershipVersionMapCanonicalBytes.clone(); + authorityEvidenceBundleCanonicalBytes = authorityEvidenceBundleCanonicalBytes.clone(); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] authorityTupleCanonicalBytes() { + return authorityTupleCanonicalBytes.clone(); + } + + @Override + public byte[] membershipVersionMapCanonicalBytes() { + return membershipVersionMapCanonicalBytes.clone(); + } + + @Override + public byte[] authorityEvidenceBundleCanonicalBytes() { + return authorityEvidenceBundleCanonicalBytes.clone(); + } + + @Override + public String toString() { + return "AccountResponseEnvelopeCryptography.Binding[redacted]"; + } + } + + /** Defensively copied opaque ciphertext; no response bytes are exposed through diagnostics. */ + public record EncryptedResponseEnvelope(byte[] bytes) { + public EncryptedResponseEnvelope { + if (bytes == null) { + throw new IllegalArgumentException("Envelope bytes are required"); + } + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } + + @Override + public String toString() { + return "EncryptedResponseEnvelope[redacted]"; + } + } + + /** Integrity/format failure; callers must fail closed and must not expose a token. */ + public static final class IntegrityException extends RuntimeException { + private IntegrityException() { + super("Account response envelope failed integrity validation"); + } + } + + /** Maps only the immutable owner-recorded response horizon to the canonical terminal outcome. */ + public static final class ResponseRecoveryExpiredException extends RuntimeException { + private ResponseRecoveryExpiredException() { + super("Account response recovery horizon has expired"); + } + + public String errorCode() { + return "RESPONSE_RECOVERY_EXPIRED"; + } + } + + /** Retryable provider/runtime failure, without including secret or response material. */ + public static final class CryptographyUnavailableException extends RuntimeException { + private CryptographyUnavailableException() { + super("Account response-envelope cryptography is unavailable"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java new file mode 100644 index 0000000000..ffcb7915a5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java @@ -0,0 +1,291 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.Instant; +import java.util.Base64; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * Loads Account's separate response-envelope encryption ring from its mounted read-only directory. + */ +@Component +public final class AccountResponseEnvelopeKeyring { + static final int KEY_BYTES = 32; + static final int MAX_MANIFEST_BYTES = 16 * 1024; + static final int MAX_RETIRING_KEYS = 8; + private static final String MANIFEST_HEADER = "firemud-account-response-envelope-keyring-v1"; + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,32}"); + + private final String mountPath; + + @Autowired + public AccountResponseEnvelopeKeyring( + @Value("${firemud.account.response-envelope.keyring-path:}") String mountPath) { + this.mountPath = mountPath == null ? "" : mountPath; + } + + /** Reloads on every operation so a withdrawn or unreadable mounted key is never cached. */ + Snapshot readCurrent() { + if (mountPath.isBlank()) { + throw new KeyUnavailableException(); + } + try { + Path configuredRoot = Path.of(mountPath); + if (!configuredRoot.isAbsolute()) { + throw new KeyUnavailableException(); + } + Path mountRoot = configuredRoot.toRealPath(); + if (!Files.isDirectory(mountRoot, LinkOption.NOFOLLOW_LINKS)) { + throw new KeyUnavailableException(); + } + // Kubernetes projected Secrets use key -> ..data/key and ..data -> .. symlinks. + // Resolve that projection, but do not let its target leave this configured trust root. + Path projectedKey = mountRoot.resolve("keyring").toRealPath(); + if (!projectedKey.startsWith(mountRoot) + || !Files.isRegularFile(projectedKey, LinkOption.NOFOLLOW_LINKS)) { + throw new KeyUnavailableException(); + } + return parse(readBounded(projectedKey)); + } catch (KeyUnavailableException ex) { + throw ex; + } catch (Exception ex) { + throw new KeyUnavailableException(); + } + } + + private static byte[] readBounded(Path path) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (SeekableByteChannel channel = + Files.newByteChannel(path, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS))) { + ByteBuffer buffer = ByteBuffer.allocate(1024); + int total = 0; + while (true) { + int count = channel.read(buffer); + if (count < 0) { + break; + } + if (count == 0) { + continue; + } + total += count; + if (total > MAX_MANIFEST_BYTES) { + throw new KeyUnavailableException(); + } + buffer.flip(); + output.write(buffer.array(), buffer.position(), buffer.remaining()); + buffer.clear(); + } + } + return output.toByteArray(); + } + + private static Snapshot parse(byte[] contents) { + if (contents.length == 0 || contents.length > MAX_MANIFEST_BYTES) { + throw new KeyUnavailableException(); + } + String text; + try { + text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(contents)) + .toString(); + } catch (CharacterCodingException ex) { + throw new KeyUnavailableException(); + } + if (text.indexOf('\r') >= 0 || text.indexOf('\0') >= 0 || text.startsWith("\uFEFF")) { + throw new KeyUnavailableException(); + } + for (int index = 0; index < text.length(); index++) { + char value = text.charAt(index); + if (value > 0x7e || (value < 0x20 && value != '\n')) { + throw new KeyUnavailableException(); + } + } + + String normalized = text.endsWith("\n") ? text.substring(0, text.length() - 1) : text; + if (normalized.isEmpty() || normalized.endsWith("\n")) { + throw new KeyUnavailableException(); + } + String[] lines = normalized.split("\n", -1); + if (!MANIFEST_HEADER.equals(lines[0]) || lines.length < 2) { + throw new KeyUnavailableException(); + } + + KeyEntry active = null; + Map allKeys = new HashMap<>(); + Set seenIds = new HashSet<>(); + int retiringCount = 0; + for (int index = 1; index < lines.length; index++) { + String line = lines[index]; + if (line.isEmpty()) { + throw new KeyUnavailableException(); + } + String[] fields = line.split(" ", -1); + if (fields.length == 3 && "active".equals(fields[0])) { + if (active != null) { + throw new KeyUnavailableException(); + } + if (index != 1) { + throw new KeyUnavailableException(); + } + KeyEntry entry = parseEntry(fields[1], fields[2], null); + if (!seenIds.add(entry.keyId())) { + throw new KeyUnavailableException(); + } + active = entry; + allKeys.put(entry.keyId(), entry); + } else if (fields.length == 4 && "retiring".equals(fields[0])) { + if (active == null) { + throw new KeyUnavailableException(); + } + retiringCount++; + if (retiringCount > MAX_RETIRING_KEYS) { + throw new KeyUnavailableException(); + } + long decryptUntilMillis; + try { + if (!fields[2].matches("[1-9][0-9]{0,18}")) { + throw new NumberFormatException(); + } + decryptUntilMillis = Long.parseLong(fields[2]); + if (decryptUntilMillis <= 0) { + throw new NumberFormatException(); + } + } catch (NumberFormatException ex) { + throw new KeyUnavailableException(); + } + Instant decryptUntil; + try { + decryptUntil = Instant.ofEpochMilli(decryptUntilMillis); + } catch (RuntimeException ex) { + throw new KeyUnavailableException(); + } + KeyEntry entry = parseEntry(fields[1], fields[3], decryptUntil); + if (!seenIds.add(entry.keyId())) { + throw new KeyUnavailableException(); + } + allKeys.put(entry.keyId(), entry); + } else { + throw new KeyUnavailableException(); + } + } + if (active == null) { + throw new KeyUnavailableException(); + } + return new Snapshot(active, allKeys); + } + + private static KeyEntry parseEntry(String keyId, String encodedKey, Instant decryptUntil) { + if (keyId == null || !KEY_ID.matcher(keyId).matches() || encodedKey == null) { + throw new KeyUnavailableException(); + } + byte[] keyMaterial; + try { + keyMaterial = Base64.getUrlDecoder().decode(encodedKey); + } catch (IllegalArgumentException ex) { + throw new KeyUnavailableException(); + } + if (keyMaterial.length != KEY_BYTES + || !Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(keyMaterial) + .equals(encodedKey)) { + java.util.Arrays.fill(keyMaterial, (byte) 0); + throw new KeyUnavailableException(); + } + KeyEntry entry = new KeyEntry(keyId, keyMaterial, decryptUntil); + java.util.Arrays.fill(keyMaterial, (byte) 0); + return entry; + } + + static final class Snapshot { + private final KeyEntry active; + private final Map keys; + + private Snapshot(KeyEntry active, Map keys) { + this.active = active; + this.keys = Map.copyOf(keys); + } + + String activeKeyId() { + return active.keyId(); + } + + KeyEntry activeKey() { + return active; + } + + KeyEntry decryptionKey(String keyId, Instant now) { + KeyEntry key = keys.get(keyId); + if (key == null || (key.decryptUntil() != null && !now.isBefore(key.decryptUntil()))) { + throw new KeyUnavailableException(); + } + return key; + } + + @Override + public String toString() { + return "AccountResponseEnvelopeKeyring.Snapshot[redacted]"; + } + } + + static final class KeyEntry { + private final String keyId; + private final byte[] keyMaterial; + private final Instant decryptUntil; + + private KeyEntry(String keyId, byte[] keyMaterial, Instant decryptUntil) { + this.keyId = keyId; + this.keyMaterial = keyMaterial.clone(); + this.decryptUntil = decryptUntil; + } + + String keyId() { + return keyId; + } + + Instant decryptUntil() { + return decryptUntil; + } + + javax.crypto.SecretKey secretKey() { + return new javax.crypto.spec.SecretKeySpec(keyMaterial.clone(), "AES"); + } + + @Override + public String toString() { + return "AccountResponseEnvelopeKeyring.KeyEntry[keyId=" + keyId + ", material=redacted]"; + } + } + + /** Retryable failure for absent, withdrawn, malformed, or unreadable mounted key material. */ + public static final class KeyUnavailableException extends RuntimeException { + private KeyUnavailableException() { + super("Account response-envelope encryption keyring is unavailable"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java new file mode 100644 index 0000000000..92516c0387 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjection.java @@ -0,0 +1,226 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Closed non-authorizing projections for the selected public-gameplay Account owner path. */ +public final class AccountSelectedGameplayAuthorityProjection { + public static final String TENANT_SCHEMA = "account-auth-tenant-generation-projection/v1"; + public static final String MEMBERSHIP_SCHEMA = "account-auth-membership-generation-projection/v1"; + public static final String TENANT_PREFIX = "session:auth:generation:tenant:"; + public static final String MEMBERSHIP_PREFIX = "session:auth:generation:membership:"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private final Map fields; + private final byte[] bytes; + + private AccountSelectedGameplayAuthorityProjection(Map fields) { + this.fields = Map.copyOf(fields); + this.bytes = canonical(fields); + if (bytes.length > AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES) { + throw new IllegalArgumentException("Selected Account authority projection exceeds its bound"); + } + } + + static AccountSelectedGameplayAuthorityProjection tenant( + TenantAuthorityEventV1Codec.Event event) { + Map value = + base( + TENANT_SCHEMA, + event.tenantId().toString(), + Long.toString(event.tenantAuthoritySourceVersion()), + event.outboxStreamKey(), + Long.toString(event.outboxSequence()), + new String(event.payload(), StandardCharsets.UTF_8)); + value.put("tenantAuthorityGeneration", Long.toString(event.tenantAuthorityGeneration())); + return decode(canonical(value), null, event.tenantId()); + } + + static AccountSelectedGameplayAuthorityProjection membership( + MembershipAuthorityEventV1Codec.MembershipEvent event, long sourceVersion) { + Map value = + base( + MEMBERSHIP_SCHEMA, + event.tenantId(), + Long.toString(sourceVersion), + event.outboxStreamKey(), + event.outboxSequence(), + event.canonicalJson()); + value.put("accountId", event.accountId()); + value.put("membershipAuthorityGeneration", event.membershipAuthorityGeneration()); + value.put("membershipVersion", event.membershipVersion().get(event.tenantId())); + return decode( + canonical(value), UUID.fromString(event.accountId()), UUID.fromString(event.tenantId())); + } + + /** Strict, no-alias parsing; the complete independently verified event is retained unchanged. */ + public static AccountSelectedGameplayAuthorityProjection decode( + byte[] bytes, UUID accountId, UUID tenantId) { + if (bytes == null + || bytes.length == 0 + || bytes.length > AccountGameplayDelegationAuthorityProjection.MAX_PROJECTION_BYTES) + throw invalid(); + try { + String json = + StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString(); + Map fields = JSON.readValue(json, new TypeReference<>() {}); + boolean member = accountId != null; + Set expected = + member + ? Set.of( + "schemaVersion", + "accountId", + "tenantId", + "membershipAuthorityGeneration", + "membershipVersion", + "sourceVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent") + : Set.of( + "schemaVersion", + "tenantId", + "tenantAuthorityGeneration", + "sourceVersion", + "outboxStreamKey", + "outboxSequence", + "sourceEvent"); + if (!fields.keySet().equals(expected) + || !Arrays.equals(bytes, canonical(fields)) + || !(member ? MEMBERSHIP_SCHEMA : TENANT_SCHEMA).equals(fields.get("schemaVersion")) + || !tenantId.toString().equals(fields.get("tenantId"))) throw invalid(); + positive(fields, "sourceVersion"); + positive(fields, "outboxSequence"); + if (member) { + positive(fields, "membershipAuthorityGeneration"); + positive(fields, "membershipVersion"); + var event = MembershipAuthorityEventV1Codec.verify(text(fields, "sourceEvent")); + if (!accountId.toString().equals(fields.get("accountId")) + || !event.canonicalJson().equals(fields.get("sourceEvent")) + || !event.accountId().equals(fields.get("accountId")) + || !event.tenantId().equals(fields.get("tenantId")) + || !event + .membershipAuthorityGeneration() + .equals(fields.get("membershipAuthorityGeneration")) + || !event + .membershipVersion() + .get(event.tenantId()) + .equals(fields.get("membershipVersion")) + || !event.outboxStreamKey().equals(fields.get("outboxStreamKey")) + || !event.outboxSequence().equals(fields.get("outboxSequence"))) throw invalid(); + } else { + positive(fields, "tenantAuthorityGeneration"); + var event = + TenantAuthorityEventV1Codec.verify( + text(fields, "sourceEvent").getBytes(StandardCharsets.UTF_8)); + if (!event.tenantId().equals(tenantId) + || !Long.toString(event.tenantAuthorityGeneration()) + .equals(fields.get("tenantAuthorityGeneration")) + || !Long.toString(event.tenantAuthoritySourceVersion()) + .equals(fields.get("sourceVersion")) + || !event.outboxStreamKey().equals(fields.get("outboxStreamKey")) + || !Long.toString(event.outboxSequence()).equals(fields.get("outboxSequence"))) + throw invalid(); + } + return new AccountSelectedGameplayAuthorityProjection(fields); + } catch (java.nio.charset.CharacterCodingException | RuntimeException failure) { + throw invalid(); + } + } + + public String key() { + return fields.containsKey("accountId") + ? MEMBERSHIP_PREFIX + fields.get("accountId") + ":" + fields.get("tenantId") + : TENANT_PREFIX + fields.get("tenantId"); + } + + public byte[] canonicalBytes() { + return bytes.clone(); + } + + public BigInteger sequence() { + return positive(fields, "outboxSequence"); + } + + public BigInteger sourceVersion() { + return positive(fields, "sourceVersion"); + } + + public BigInteger generation() { + return positive( + fields, + fields.containsKey("accountId") + ? "membershipAuthorityGeneration" + : "tenantAuthorityGeneration"); + } + + public BigInteger membershipVersion() { + return positive(fields, "membershipVersion"); + } + + /** A source gap is not healed by installing an arbitrary latest-head value. */ + public void requireSuccessorOf(AccountSelectedGameplayAuthorityProjection prior) { + if (prior == null) { + if (!sequence().equals(BigInteger.ONE)) throw invalid(); + return; + } + if (!key().equals(prior.key())) throw invalid(); + if (Arrays.equals(bytes, prior.bytes)) return; + if (!sequence().equals(prior.sequence().add(BigInteger.ONE)) + || generation().compareTo(prior.generation()) < 0 + || sourceVersion().compareTo(prior.sourceVersion()) < 0 + || (fields.containsKey("accountId") + && membershipVersion().compareTo(prior.membershipVersion()) <= 0)) throw invalid(); + } + + private static Map base( + String schema, String tenant, String source, String stream, String sequence, String event) { + Map value = new LinkedHashMap<>(); + value.put("schemaVersion", schema); + value.put("tenantId", tenant); + value.put("sourceVersion", source); + value.put("outboxStreamKey", stream); + value.put("outboxSequence", sequence); + value.put("sourceEvent", event); + return value; + } + + private static BigInteger positive(Map fields, String key) { + String value = text(fields, key); + if (!value.matches("[1-9][0-9]*")) throw invalid(); + return new BigInteger(value); + } + + private static String text(Map fields, String key) { + if (!(fields.get(key) instanceof String value)) throw invalid(); + return value; + } + + private static byte[] canonical(Map fields) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields)); + } catch (Exception failure) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Selected Account authority projection is unavailable or contradictory"); + } +} diff --git a/services/account-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution b/services/account-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution new file mode 100644 index 0000000000..3e5dfa2660 --- /dev/null +++ b/services/account-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution @@ -0,0 +1,2 @@ +net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisScriptContribution +net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisScriptContribution diff --git a/services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql b/services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql new file mode 100644 index 0000000000..9048e940f8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql @@ -0,0 +1,404 @@ +-- Account-owned signer desired state, Account-selected generation requests, and a dormant +-- PREPARED schema for the later lifecycle phase. Generation/materialization evidence is not a +-- PREPARED promotion record and never authorizes signing. +CREATE TABLE account_jwt_signer_desired_states ( + environment_id VARCHAR(63) PRIMARY KEY, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL DEFAULT 'jwt-signing-keys', + public_jwks_config_map_name VARCHAR(63) NOT NULL DEFAULT 'jwt-jwks', + record_version BIGINT NOT NULL DEFAULT 1, + durable_active_generation BIGINT, + durable_active_kid VARCHAR(128), + published_active_generation BIGINT, + published_active_kid VARCHAR(128), + generation_operation_id UUID, + prepared_operation_id UUID, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_state_binding_unique + UNIQUE (environment_id, cluster_id, kubernetes_namespace, custody_mode), + CONSTRAINT account_jwt_signer_state_environment_check + CHECK (environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_state_cluster_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_state_namespace_check + CHECK (kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_state_mode_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_state_resource_names_check + CHECK (private_secret_name = 'jwt-signing-keys' + AND public_jwks_config_map_name = 'jwt-jwks'), + CONSTRAINT account_jwt_signer_state_version_check CHECK (record_version > 0), + CONSTRAINT account_jwt_signer_state_durable_active_shape_check + CHECK ((durable_active_generation IS NULL AND durable_active_kid IS NULL) + OR (durable_active_generation IS NOT NULL + AND durable_active_generation > 0 + AND durable_active_kid IS NOT NULL + AND durable_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_state_published_active_shape_check + CHECK ((published_active_generation IS NULL AND published_active_kid IS NULL) + OR (published_active_generation IS NOT NULL + AND published_active_generation > 0 + AND published_active_kid IS NOT NULL + AND published_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) +); + +CREATE TABLE account_jwt_signer_promotion_operations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + request_digest_version SMALLINT NOT NULL, + request_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_previous_generation BIGINT, + expected_previous_kid VARCHAR(128), + target_generation BIGINT NOT NULL, + target_kid VARCHAR(128) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + target_public_key_fingerprint VARCHAR(64) NOT NULL, + expected_private_secret_resource_version VARCHAR(256) NOT NULL, + expected_public_jwks_resource_version VARCHAR(256) NOT NULL, + expected_public_active_generation BIGINT, + expected_public_active_kid VARCHAR(128), + operation_action VARCHAR(32) NOT NULL, + allowed_private_slots_canonical_bytes BYTEA NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'PREPARED', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_promotion_operation_state_fk + FOREIGN KEY (environment_id) + REFERENCES account_jwt_signer_desired_states(environment_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_promotion_exact_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_promotion_cluster_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_promotion_namespace_check + CHECK (kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_promotion_mode_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_promotion_id_v4_check + CHECK (operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_jwt_signer_promotion_digest_check + CHECK (request_digest_version = 1 AND request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_promotion_record_version_check + CHECK (expected_record_version > 0 + AND expected_record_version < 9223372036854775807), + CONSTRAINT account_jwt_signer_promotion_previous_shape_check + CHECK ((expected_previous_generation IS NULL AND expected_previous_kid IS NULL) + OR (expected_previous_generation IS NOT NULL + AND expected_previous_generation > 0 + AND expected_previous_kid IS NOT NULL + AND expected_previous_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_promotion_target_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_previous_generation IS NULL + OR (expected_previous_generation IS NOT NULL + AND target_generation > expected_previous_generation + AND target_kid <> expected_previous_kid))), + CONSTRAINT account_jwt_signer_promotion_algorithm_check + CHECK (target_algorithm = 'RS256'), + CONSTRAINT account_jwt_signer_promotion_fingerprint_check + CHECK (target_public_key_fingerprint ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_promotion_resource_versions_check + CHECK (expected_private_secret_resource_version ~ '^[!-~]+$' + AND char_length(expected_private_secret_resource_version) BETWEEN 1 AND 256 + AND expected_public_jwks_resource_version ~ '^[!-~]+$' + AND char_length(expected_public_jwks_resource_version) BETWEEN 1 AND 256), + CONSTRAINT account_jwt_signer_promotion_public_active_shape_check + CHECK ((expected_public_active_generation IS NULL AND expected_public_active_kid IS NULL) + OR (expected_public_active_generation IS NOT NULL + AND expected_public_active_generation > 0 + AND expected_public_active_kid IS NOT NULL + AND expected_public_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_promotion_published_generation_check + CHECK (expected_public_active_generation IS NULL + OR (target_generation > expected_public_active_generation + AND target_kid <> expected_public_active_kid)), + CONSTRAINT account_jwt_signer_promotion_action_check + CHECK (operation_action = 'MATERIALIZE_PENDING'), + CONSTRAINT account_jwt_signer_promotion_slots_check + CHECK (allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea), + CONSTRAINT account_jwt_signer_promotion_status_check CHECK (status = 'PREPARED') +); + +ALTER TABLE account_jwt_signer_desired_states + ADD CONSTRAINT account_jwt_signer_state_prepared_operation_fk + FOREIGN KEY (prepared_operation_id) + REFERENCES account_jwt_signer_promotion_operations(operation_id) + ON DELETE RESTRICT; + +CREATE TABLE account_jwt_signer_generation_operations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest_version SMALLINT NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_previous_generation BIGINT, + expected_previous_kid VARCHAR(128), + expected_published_generation BIGINT, + expected_published_kid VARCHAR(128), + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + operation_action VARCHAR(32) NOT NULL, + allowed_private_slots_canonical_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_generation_state_fk + FOREIGN KEY (environment_id) + REFERENCES account_jwt_signer_desired_states(environment_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_exact_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, target_generation, target_kid, + expected_published_generation, expected_published_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_observation_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, expected_cluster_incarnation_uid, + expected_namespace_uid, trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_receipt_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_id_v4_check + CHECK (operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_jwt_signer_generation_binding_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_generation_digest_check + CHECK (operation_digest_version = 1 AND operation_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_generation_state_version_check + CHECK (expected_record_version > 0 AND expected_record_version < 9223372036854775807), + CONSTRAINT account_jwt_signer_generation_previous_shape_check + CHECK ((expected_previous_generation IS NULL AND expected_previous_kid IS NULL) + OR (expected_previous_generation IS NOT NULL AND expected_previous_generation > 0 + AND expected_previous_kid IS NOT NULL + AND expected_previous_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_generation_target_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_previous_generation IS NULL + OR (target_generation > expected_previous_generation + AND target_kid <> expected_previous_kid))), + CONSTRAINT account_jwt_signer_generation_algorithm_check + CHECK (target_algorithm = 'RS256'), + CONSTRAINT account_jwt_signer_generation_published_shape_check + CHECK ((expected_published_generation IS NULL AND expected_published_kid IS NULL) + OR (expected_published_generation IS NOT NULL AND expected_published_generation > 0 + AND expected_published_kid IS NOT NULL + AND expected_published_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_generation_trust_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_generation_action_check + CHECK (operation_action = 'MATERIALIZE_PENDING'), + CONSTRAINT account_jwt_signer_generation_slots_check + CHECK (allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea) +); + +ALTER TABLE account_jwt_signer_desired_states + ADD CONSTRAINT account_jwt_signer_state_generation_operation_fk + FOREIGN KEY (generation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT; + +CREATE UNIQUE INDEX account_jwt_signer_generation_target_once + ON account_jwt_signer_generation_operations (environment_id, target_generation); + +CREATE UNIQUE INDEX account_jwt_signer_generation_kid_once + ON account_jwt_signer_generation_operations (environment_id, target_kid); + +CREATE UNIQUE INDEX account_jwt_signer_one_prepared_operation_per_environment + ON account_jwt_signer_promotion_operations (environment_id) + WHERE status = 'PREPARED'; + +CREATE UNIQUE INDEX account_jwt_signer_target_generation_once + ON account_jwt_signer_promotion_operations (environment_id, target_generation); + +CREATE UNIQUE INDEX account_jwt_signer_target_kid_once + ON account_jwt_signer_promotion_operations (environment_id, target_kid); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_signer_desired_state_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_environment VARCHAR(63); + operation_expected_version BIGINT; + operation_previous_generation BIGINT; + operation_previous_kid VARCHAR(128); + operation_published_generation BIGINT; + operation_published_kid VARCHAR(128); + operation_status VARCHAR(16); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_target_generation BIGINT; + operation_target_kid VARCHAR(64); + operation_algorithm VARCHAR(16); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer desired state cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + IF NEW.environment_id IS DISTINCT FROM OLD.environment_id + OR NEW.cluster_id IS DISTINCT FROM OLD.cluster_id + OR NEW.kubernetes_namespace IS DISTINCT FROM OLD.kubernetes_namespace + OR NEW.custody_mode IS DISTINCT FROM OLD.custody_mode + OR NEW.private_secret_name IS DISTINCT FROM OLD.private_secret_name + OR NEW.public_jwks_config_map_name IS DISTINCT FROM OLD.public_jwks_config_map_name + OR NEW.durable_active_generation IS DISTINCT FROM OLD.durable_active_generation + OR NEW.durable_active_kid IS DISTINCT FROM OLD.durable_active_kid + OR NEW.published_active_generation IS DISTINCT FROM OLD.published_active_generation + OR NEW.published_active_kid IS DISTINCT FROM OLD.published_active_kid + OR NEW.created_at IS DISTINCT FROM OLD.created_at + OR NEW.record_version <> OLD.record_version + 1 THEN + RAISE EXCEPTION 'Account JWT signer desired state permits only a versioned owner transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + IF NEW.prepared_operation_id IS DISTINCT FROM OLD.prepared_operation_id THEN + RAISE EXCEPTION 'JWT signer promotion prerequisites are incomplete' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + + IF OLD.generation_operation_id IS NOT NULL + OR NEW.generation_operation_id IS NULL + OR OLD.prepared_operation_id IS NOT NULL + OR NEW.prepared_operation_id IS NOT NULL THEN + RAISE EXCEPTION 'Account JWT signer generation operation is already fenced or not promotable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + + SELECT environment_id, cluster_id, kubernetes_namespace, custody_mode, + expected_record_version, expected_previous_generation, expected_previous_kid, + expected_published_generation, expected_published_kid, + target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision + INTO operation_environment, operation_cluster, operation_namespace, operation_mode, + operation_expected_version, operation_previous_generation, operation_previous_kid, + operation_published_generation, operation_published_kid, + operation_target_generation, operation_target_kid, operation_algorithm, + operation_cluster_uid, operation_namespace_uid, + operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id; + IF operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_expected_version IS DISTINCT FROM OLD.record_version + OR operation_previous_generation IS DISTINCT FROM OLD.durable_active_generation + OR operation_previous_kid IS DISTINCT FROM OLD.durable_active_kid + OR operation_published_generation IS DISTINCT FROM OLD.published_active_generation + OR operation_published_kid IS DISTINCT FROM OLD.published_active_kid + OR operation_algorithm IS DISTINCT FROM 'RS256' + OR operation_cluster_uid IS NULL OR operation_namespace_uid IS NULL + OR operation_trust_digest IS NULL OR operation_trust_revision IS NULL THEN + RAISE EXCEPTION 'Account JWT signer state must point to its exact owner-selected generation operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_desired_state_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer desired state cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer operation history is immutable and PREPARED-only' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_operation_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer operation history cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_operation_immutable() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer generation operation is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_jwt_signer_desired_state_guard + BEFORE UPDATE OR DELETE ON account_jwt_signer_desired_states + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_desired_state_guard(); + +CREATE TRIGGER account_jwt_signer_desired_state_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_desired_states + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_desired_state_no_truncate(); + +CREATE TRIGGER account_jwt_signer_operation_guard + BEFORE UPDATE OR DELETE ON account_jwt_signer_promotion_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_operation_guard(); + +CREATE TRIGGER account_jwt_signer_operation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_promotion_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_operation_no_truncate(); + +CREATE TRIGGER account_jwt_signer_generation_operation_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_generation_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_operation_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_operation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_generation_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_operation_immutable(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql b/services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql new file mode 100644 index 0000000000..acb940fa59 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql @@ -0,0 +1,326 @@ +-- Immutable Account-bound reports for the fixed private Secret. The first report observes only +-- the fixed-name pre-created Secret; the second records one pending-key generation/CAS result. +-- Neither report changes active state, PREPARED state, JWKS, token signing, or readiness. +CREATE TABLE account_jwt_signer_secret_observations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest_version SMALLINT NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL, + secret_uid UUID NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + observation_digest_version SMALLINT NOT NULL, + observation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_observation_exact_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_observation_exact_operation_fk + FOREIGN KEY (operation_id, environment_id, cluster_id, kubernetes_namespace, + custody_mode, operation_digest, expected_record_version, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + REFERENCES account_jwt_signer_generation_operations( + operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, expected_cluster_incarnation_uid, + expected_namespace_uid, trust_binding_digest, trust_config_revision) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_observation_readback_unique + UNIQUE (operation_id, operation_digest, generation_request_digest, + secret_uid, observed_resource_version), + CONSTRAINT account_jwt_signer_observation_name_check + CHECK (private_secret_name = 'jwt-signing-keys'), + CONSTRAINT account_jwt_signer_observation_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_signer_observation_trust_check + CHECK (trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_observation_version_check + CHECK (expected_record_version > 0 AND operation_digest_version = 1 + AND observation_digest_version = 1), + CONSTRAINT account_jwt_signer_observation_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND observation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_observation_resource_version_check + CHECK (observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256) +); + +CREATE TABLE account_jwt_signer_generation_results ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL, + secret_uid UUID NOT NULL, + expected_prior_resource_version VARCHAR(256) NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + public_jwk_json VARCHAR(8192) NOT NULL, + receipt_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_generation_result_exact_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_exact_operation_fk + FOREIGN KEY (operation_id, environment_id, cluster_id, kubernetes_namespace, + custody_mode, operation_digest, + target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + REFERENCES account_jwt_signer_generation_operations( + operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, target_generation, target_kid, + target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_exact_observation_fk + FOREIGN KEY (operation_id, operation_digest, generation_request_digest, + secret_uid, expected_prior_resource_version) + REFERENCES account_jwt_signer_secret_observations( + operation_id, operation_digest, generation_request_digest, + secret_uid, observed_resource_version) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_name_check + CHECK (private_secret_name = 'jwt-signing-keys'), + CONSTRAINT account_jwt_signer_generation_result_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_signer_generation_result_trust_check + CHECK (trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_generation_result_version_check + CHECK (desired_state_version > 1), + CONSTRAINT account_jwt_signer_generation_result_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND receipt_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_generation_result_resource_versions_check + CHECK (expected_prior_resource_version ~ '^[!-~]+$' + AND char_length(expected_prior_resource_version) BETWEEN 1 AND 256 + AND observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256 + AND expected_prior_resource_version <> observed_resource_version), + CONSTRAINT account_jwt_signer_generation_result_key_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND target_algorithm = 'RS256' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +ALTER TABLE account_jwt_signer_generation_results + ADD CONSTRAINT account_jwt_signer_generation_result_public_jwk_check + CHECK (octet_length(public_jwk_json) <= 8192 + AND jsonb_typeof(public_jwk_json::jsonb) = 'object' + AND (public_jwk_json::jsonb ?& ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e']) + AND NOT (public_jwk_json::jsonb ?| ARRAY['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k']) + AND public_jwk_json::jsonb - ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e'] = '{}'::jsonb); +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_signer_secret_observation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_record_version BIGINT; + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); +BEGIN + SELECT desired_state.generation_operation_id, desired_state.record_version + INTO state_operation_id, state_record_version + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = NEW.environment_id + AND desired_state.cluster_id = NEW.cluster_id + AND desired_state.kubernetes_namespace = NEW.kubernetes_namespace + AND desired_state.custody_mode = NEW.custody_mode + FOR UPDATE; + + SELECT generation_op.operation_digest, generation_op.expected_record_version, + generation_op.environment_id, generation_op.cluster_id, generation_op.kubernetes_namespace, + generation_op.custody_mode, generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision + INTO operation_digest, operation_expected_version, operation_environment, + operation_cluster, operation_namespace, operation_mode, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.operation_id + FOR UPDATE; + + IF state_operation_id IS DISTINCT FROM NEW.operation_id + OR state_record_version IS DISTINCT FROM operation_expected_version + 1 + OR operation_digest IS DISTINCT FROM NEW.operation_digest + OR operation_expected_version IS DISTINCT FROM NEW.expected_record_version + OR operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_cluster_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR operation_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR operation_trust_digest IS DISTINCT FROM NEW.trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM NEW.trust_config_revision + OR NEW.private_secret_name IS DISTINCT FROM 'jwt-signing-keys' THEN + RAISE EXCEPTION 'JWT signer Secret observation must bind the current Account operation and trust' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_secret_observation_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_result_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_record_version BIGINT; + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_generation BIGINT; + operation_kid VARCHAR(64); + operation_algorithm VARCHAR(16); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); + observation_generation_request_digest VARCHAR(64); + observation_secret_uid UUID; + observation_resource_version VARCHAR(256); +BEGIN + -- Lock order matches every Account repository write: desired state, then operation. + SELECT desired_state.generation_operation_id, desired_state.record_version + INTO state_operation_id, state_record_version + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = NEW.environment_id + AND desired_state.cluster_id = NEW.cluster_id + AND desired_state.kubernetes_namespace = NEW.kubernetes_namespace + AND desired_state.custody_mode = NEW.custody_mode + FOR UPDATE; + + SELECT generation_op.operation_digest, generation_op.expected_record_version, + generation_op.environment_id, generation_op.cluster_id, generation_op.kubernetes_namespace, + generation_op.custody_mode, generation_op.target_generation, generation_op.target_kid, + generation_op.target_algorithm, generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision + INTO operation_digest, operation_expected_version, operation_environment, + operation_cluster, operation_namespace, operation_mode, operation_generation, + operation_kid, operation_algorithm, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.operation_id + FOR UPDATE; + + SELECT observation.generation_request_digest, observation.secret_uid, + observation.observed_resource_version + INTO observation_generation_request_digest, observation_secret_uid, + observation_resource_version + FROM account_jwt_signer_secret_observations AS observation + WHERE observation.operation_id = NEW.operation_id + FOR UPDATE; + + IF state_operation_id IS DISTINCT FROM NEW.operation_id + OR state_record_version IS DISTINCT FROM operation_expected_version + 1 + OR NEW.desired_state_version IS DISTINCT FROM state_record_version + OR operation_digest IS DISTINCT FROM NEW.operation_digest + OR operation_expected_version IS NULL + OR operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_generation IS DISTINCT FROM NEW.target_generation + OR operation_kid IS DISTINCT FROM NEW.target_kid + OR operation_algorithm IS DISTINCT FROM NEW.target_algorithm + OR operation_cluster_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR operation_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR operation_trust_digest IS DISTINCT FROM NEW.trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM NEW.trust_config_revision + OR observation_generation_request_digest IS DISTINCT FROM NEW.generation_request_digest + OR observation_secret_uid IS DISTINCT FROM NEW.secret_uid + OR observation_resource_version IS DISTINCT FROM NEW.expected_prior_resource_version + OR NEW.private_secret_name IS DISTINCT FROM 'jwt-signing-keys' THEN + RAISE EXCEPTION 'JWT signer generation result must bind the exact current request and observation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_result_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_evidence_immutable() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer generation evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_evidence_immutable'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_jwt_signer_secret_observation_guard + BEFORE INSERT ON account_jwt_signer_secret_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_secret_observation_guard(); + +CREATE TRIGGER account_jwt_signer_secret_observation_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_secret_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_secret_observation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_secret_observations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_result_guard + BEFORE INSERT ON account_jwt_signer_generation_results + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_result_guard(); + +CREATE TRIGGER account_jwt_signer_generation_result_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_generation_results + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_result_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_generation_results + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql b/services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql new file mode 100644 index 0000000000..6da03d99d7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql @@ -0,0 +1,599 @@ +-- Account records its exact public-JWKS intent before the protected ConfigMap CAS, then binds +-- server readback and local mounted correspondence to the same current generation operation. +-- These observations are non-authorizing and never advance signer lifecycle state. +CREATE TABLE account_jwt_jwks_prepublication_intents ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + generation_receipt_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + api_config_revision VARCHAR(128) NOT NULL, + config_map_name VARCHAR(63) NOT NULL, + config_map_uid UUID NOT NULL, + expected_resource_version VARCHAR(256) NOT NULL, + expected_snapshot_digest VARCHAR(64) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + expected_durable_active_json VARCHAR(512) NOT NULL, + expected_published_active_json VARCHAR(512) NOT NULL, + jwks_json TEXT NOT NULL, + generation_marker_json TEXT NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + generation_marker_digest VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_intent_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_intent_generation_result_fk + FOREIGN KEY (operation_id) + REFERENCES account_jwt_signer_generation_results(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_intent_digest_unique + UNIQUE (operation_id, intent_digest), + CONSTRAINT account_jwt_jwks_intent_identity_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND config_map_name = 'jwt-jwks' + AND desired_state_version > 1 + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]+$' + AND char_length(target_kid) BETWEEN 1 AND 64), + CONSTRAINT account_jwt_jwks_intent_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_jwks_intent_resource_version_check + CHECK (expected_resource_version ~ '^[!-~]+$' + AND char_length(expected_resource_version) BETWEEN 1 AND 256), + CONSTRAINT account_jwt_jwks_intent_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND generation_receipt_digest ~ '^[0-9a-f]{64}$' + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND expected_snapshot_digest ~ '^[0-9a-f]{64}$' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND generation_marker_digest ~ '^[0-9a-f]{64}$' + AND intent_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_jwks_intent_revision_check + CHECK (trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' + AND char_length(trust_config_revision) BETWEEN 1 AND 128 + AND api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' + AND char_length(api_config_revision) BETWEEN 1 AND 128), + CONSTRAINT account_jwt_jwks_intent_content_bounds_check + CHECK (octet_length(jwks_json) BETWEEN 1 AND 262144 + AND octet_length(generation_marker_json) BETWEEN 1 AND 16384 + AND octet_length(expected_durable_active_json) BETWEEN 1 AND 512 + AND octet_length(expected_published_active_json) BETWEEN 1 AND 512) +); + +CREATE TABLE account_jwt_jwks_publication_receipts ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + config_map_uid UUID NOT NULL, + expected_resource_version VARCHAR(256) NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + receipt_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_receipt_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_receipt_intent_fk + FOREIGN KEY (operation_id, intent_digest) + REFERENCES account_jwt_jwks_prepublication_intents(operation_id, intent_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_receipt_digest_unique + UNIQUE (operation_id, intent_digest, receipt_digest), + CONSTRAINT account_jwt_jwks_receipt_identity_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_resource_version ~ '^[!-~]+$' + AND char_length(expected_resource_version) BETWEEN 1 AND 256 + AND observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256 + AND expected_resource_version <> observed_resource_version), + CONSTRAINT account_jwt_jwks_receipt_digest_check + CHECK (intent_digest ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND receipt_digest ~ '^[0-9a-f]{64}$') +); + +CREATE TABLE account_jwt_jwks_mount_observations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + publication_receipt_digest VARCHAR(64) NOT NULL, + generation_marker_digest VARCHAR(64) NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + observation_digest VARCHAR(64) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_mount_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_mount_receipt_fk + FOREIGN KEY (operation_id, intent_digest, publication_receipt_digest) + REFERENCES account_jwt_jwks_publication_receipts( + operation_id, intent_digest, receipt_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_mount_digest_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND intent_digest ~ '^[0-9a-f]{64}$' + AND publication_receipt_digest ~ '^[0-9a-f]{64}$' + AND generation_marker_digest ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$' + AND observation_digest ~ '^[0-9a-f]{64}$') +); + +-- Keep the trigger bodies out of jOOQ DDL parsing; the database still enforces these invariants. +-- [jooq ignore start] +CREATE FUNCTION account_jwt_jwks_lock_current_generation( + p_operation_id UUID, + p_environment_id VARCHAR, + p_cluster_id VARCHAR, + p_namespace VARCHAR, + p_custody_mode VARCHAR, + p_operation_digest VARCHAR, + p_generation_request_digest VARCHAR, + p_generation_receipt_digest VARCHAR, + p_desired_state_version BIGINT, + p_cluster_uid UUID, + p_namespace_uid UUID, + p_trust_binding_digest VARCHAR, + p_trust_config_revision VARCHAR, + p_target_generation BIGINT, + p_target_kid VARCHAR, + p_public_key_fingerprint VARCHAR +) +RETURNS JSONB +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_version BIGINT; + state_prepared_operation_id UUID; + durable_active JSONB; + published_active JSONB; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); + operation_target_generation BIGINT; + operation_target_kid VARCHAR(64); + operation_target_algorithm VARCHAR(16); + operation_previous_generation BIGINT; + operation_previous_kid VARCHAR(128); + operation_published_generation BIGINT; + operation_published_kid VARCHAR(128); + result_environment VARCHAR(63); + result_cluster VARCHAR(128); + result_namespace VARCHAR(63); + result_mode VARCHAR(64); + result_operation_digest VARCHAR(64); + result_generation_request_digest VARCHAR(64); + result_desired_state_version BIGINT; + result_cluster_uid UUID; + result_namespace_uid UUID; + result_trust_digest VARCHAR(64); + result_trust_revision VARCHAR(128); + result_generation BIGINT; + result_kid VARCHAR(64); + result_fingerprint VARCHAR(64); + result_receipt_digest VARCHAR(64); + result_jwk VARCHAR(8192); +BEGIN + SELECT desired_state.generation_operation_id, + desired_state.record_version, + desired_state.prepared_operation_id, + CASE WHEN desired_state.durable_active_generation IS NULL + THEN '{"present":false}'::jsonb + ELSE jsonb_build_object('present', true, + 'generation', desired_state.durable_active_generation::text, + 'kid', desired_state.durable_active_kid) + END, + CASE WHEN desired_state.published_active_generation IS NULL + THEN '{"present":false}'::jsonb + ELSE jsonb_build_object('present', true, + 'generation', desired_state.published_active_generation::text, + 'kid', desired_state.published_active_kid) + END + INTO state_operation_id, state_version, state_prepared_operation_id, + durable_active, published_active + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = p_environment_id + AND desired_state.cluster_id = p_cluster_id + AND desired_state.kubernetes_namespace = p_namespace + AND desired_state.custody_mode = p_custody_mode + FOR UPDATE; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT JWKS current desired state is missing' USING ERRCODE = '23514'; + END IF; + + SELECT generation_op.environment_id, generation_op.cluster_id, + generation_op.kubernetes_namespace, generation_op.custody_mode, + generation_op.operation_digest, generation_op.expected_record_version, + generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision, generation_op.target_generation, + generation_op.target_kid, generation_op.target_algorithm, + generation_op.expected_previous_generation, generation_op.expected_previous_kid, + generation_op.expected_published_generation, generation_op.expected_published_kid + INTO operation_environment, operation_cluster, operation_namespace, operation_mode, + operation_digest, operation_expected_version, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision, + operation_target_generation, operation_target_kid, operation_target_algorithm, + operation_previous_generation, operation_previous_kid, + operation_published_generation, operation_published_kid + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = p_operation_id + FOR UPDATE; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT JWKS generation operation is missing' USING ERRCODE = '23514'; + END IF; + + SELECT generation_result.environment_id, generation_result.cluster_id, + generation_result.kubernetes_namespace, generation_result.custody_mode, + generation_result.operation_digest, generation_result.generation_request_digest, + generation_result.desired_state_version, + generation_result.expected_cluster_incarnation_uid, + generation_result.expected_namespace_uid, generation_result.trust_binding_digest, + generation_result.trust_config_revision, generation_result.target_generation, + generation_result.target_kid, generation_result.public_key_fingerprint, + generation_result.receipt_digest, generation_result.public_jwk_json + INTO result_environment, result_cluster, result_namespace, result_mode, + result_operation_digest, result_generation_request_digest, result_desired_state_version, + result_cluster_uid, result_namespace_uid, result_trust_digest, result_trust_revision, + result_generation, result_kid, result_fingerprint, result_receipt_digest, result_jwk + FROM account_jwt_signer_generation_results AS generation_result + WHERE generation_result.operation_id = p_operation_id + FOR UPDATE; + + IF NOT FOUND + OR state_operation_id IS DISTINCT FROM p_operation_id + OR state_version IS DISTINCT FROM p_desired_state_version + OR state_prepared_operation_id IS NOT NULL + OR operation_environment IS DISTINCT FROM p_environment_id + OR operation_cluster IS DISTINCT FROM p_cluster_id + OR operation_namespace IS DISTINCT FROM p_namespace + OR operation_mode IS DISTINCT FROM p_custody_mode + OR operation_digest IS DISTINCT FROM p_operation_digest + OR operation_expected_version + 1 IS DISTINCT FROM p_desired_state_version + OR operation_cluster_uid IS DISTINCT FROM p_cluster_uid + OR operation_namespace_uid IS DISTINCT FROM p_namespace_uid + OR operation_trust_digest IS DISTINCT FROM p_trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM p_trust_config_revision + OR operation_target_generation IS DISTINCT FROM p_target_generation + OR operation_target_kid IS DISTINCT FROM p_target_kid + OR operation_target_algorithm IS DISTINCT FROM 'RS256' + OR result_environment IS DISTINCT FROM p_environment_id + OR result_cluster IS DISTINCT FROM p_cluster_id + OR result_namespace IS DISTINCT FROM p_namespace + OR result_mode IS DISTINCT FROM p_custody_mode + OR result_operation_digest IS DISTINCT FROM p_operation_digest + OR result_generation_request_digest IS DISTINCT FROM p_generation_request_digest + OR result_receipt_digest IS DISTINCT FROM p_generation_receipt_digest + OR result_desired_state_version IS DISTINCT FROM p_desired_state_version + OR result_cluster_uid IS DISTINCT FROM p_cluster_uid + OR result_namespace_uid IS DISTINCT FROM p_namespace_uid + OR result_trust_digest IS DISTINCT FROM p_trust_binding_digest + OR result_trust_revision IS DISTINCT FROM p_trust_config_revision + OR result_generation IS DISTINCT FROM p_target_generation + OR result_kid IS DISTINCT FROM p_target_kid + OR result_fingerprint IS DISTINCT FROM p_public_key_fingerprint + OR operation_previous_generation IS DISTINCT FROM + NULLIF(durable_active->>'generation', '')::BIGINT + OR operation_previous_kid IS DISTINCT FROM NULLIF(durable_active->>'kid', '') + OR operation_published_generation IS DISTINCT FROM + NULLIF(published_active->>'generation', '')::BIGINT + OR operation_published_kid IS DISTINCT FROM NULLIF(published_active->>'kid', '') THEN + RAISE EXCEPTION 'Account JWT JWKS evidence is stale or mismatched' USING ERRCODE = '23514'; + END IF; + + RETURN jsonb_build_object( + 'durableActive', durable_active, + 'publishedActive', published_active, + 'publicJwk', result_jwk::jsonb); +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_public_intent() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + current_evidence JSONB; + jwks_document JSONB; + marker_document JSONB; + key_document JSONB; + key_kid TEXT; + seen_kids TEXT[] := ARRAY[]::TEXT[]; + target_key_count INTEGER := 0; + public_jwk JSONB; +BEGIN + current_evidence := account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, NEW.operation_digest, NEW.generation_request_digest, + NEW.generation_receipt_digest, NEW.desired_state_version, + NEW.expected_cluster_incarnation_uid, NEW.expected_namespace_uid, + NEW.trust_binding_digest, NEW.trust_config_revision, + NEW.target_generation, NEW.target_kid, NEW.public_key_fingerprint); + + IF NEW.expected_durable_active_json::jsonb IS DISTINCT FROM current_evidence->'durableActive' + OR NEW.expected_published_active_json::jsonb IS DISTINCT FROM current_evidence->'publishedActive' THEN + RAISE EXCEPTION 'Account JWT JWKS active fence is stale' USING ERRCODE = '23514'; + END IF; + + jwks_document := NEW.jwks_json::jsonb; + IF jsonb_typeof(jwks_document) IS DISTINCT FROM 'object' + OR jwks_document - ARRAY['keys'] <> '{}'::jsonb + OR jsonb_typeof(jwks_document->'keys') IS DISTINCT FROM 'array' + OR jsonb_array_length(jwks_document->'keys') < 1 + OR jsonb_array_length(jwks_document->'keys') > 64 THEN + RAISE EXCEPTION 'Account public JWKS has an unsupported shape' USING ERRCODE = '23514'; + END IF; + public_jwk := current_evidence->'publicJwk'; + FOR key_document IN + SELECT jwks_key.value + FROM jsonb_array_elements(jwks_document->'keys') AS jwks_key(value) + LOOP + IF jsonb_typeof(key_document) IS DISTINCT FROM 'object' + OR key_document - ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e'] <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys(key_document)) NOT BETWEEN 6 AND 7 + OR key_document ?| ARRAY['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k'] + OR key_document->>'kty' IS DISTINCT FROM 'RSA' + OR key_document->>'use' IS DISTINCT FROM 'sig' + OR key_document->>'alg' IS DISTINCT FROM 'RS256' + OR key_document->>'kid' IS NULL + OR key_document->>'kid' !~ '^[A-Za-z0-9_-]{1,64}$' + OR jsonb_typeof(key_document->'n') IS DISTINCT FROM 'string' + OR jsonb_typeof(key_document->'e') IS DISTINCT FROM 'string' + OR key_document->>'n' !~ '^[A-Za-z0-9_-]+$' + OR key_document->>'e' !~ '^[A-Za-z0-9_-]+$' + OR (key_document ? 'key_ops' + AND (jsonb_typeof(key_document->'key_ops') IS DISTINCT FROM 'array' + OR key_document->'key_ops' <> '["verify"]'::jsonb)) THEN + RAISE EXCEPTION 'Account public JWKS contains an invalid or private key' USING ERRCODE = '23514'; + END IF; + key_kid := key_document->>'kid'; + IF key_kid = ANY(seen_kids) THEN + RAISE EXCEPTION 'Account public JWKS has duplicate kids' USING ERRCODE = '23514'; + END IF; + seen_kids := array_append(seen_kids, key_kid); + IF key_kid = NEW.target_kid THEN + target_key_count := target_key_count + 1; + IF key_document IS DISTINCT FROM public_jwk THEN + RAISE EXCEPTION 'Account public JWKS pending key differs from receipt' USING ERRCODE = '23514'; + END IF; + END IF; + END LOOP; + IF target_key_count <> 1 THEN + RAISE EXCEPTION 'Account public JWKS does not contain exactly one pending key' USING ERRCODE = '23514'; + END IF; + + marker_document := NEW.generation_marker_json::jsonb; + IF jsonb_typeof(marker_document) IS DISTINCT FROM 'object' + OR (marker_document - ARRAY['schemaVersion', 'phase', 'operationId', 'operationDigest', + 'generationRequestDigest', 'generationReceiptDigest', 'binding', 'publicConfigMap', + 'expectedDurableActive', 'expectedPublishedActive', 'pending']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys(marker_document)) <> 11 + OR jsonb_typeof((marker_document -> 'binding')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'binding') - ARRAY['environmentId', 'clusterId', 'namespace', + 'expectedClusterIncarnationUid', 'expectedNamespaceUid', 'trustBindingDigest', + 'trustConfigRevision', 'apiBindingDigest', 'apiConfigRevision']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'binding'))) <> 9 + OR jsonb_typeof((marker_document -> 'publicConfigMap')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'publicConfigMap') - ARRAY['name']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'publicConfigMap'))) <> 1 + OR jsonb_typeof((marker_document -> 'pending')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'pending') - ARRAY['generation', 'kid', 'algorithm', + 'publicKeyFingerprint']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'pending'))) <> 4 + OR (marker_document ->> 'schemaVersion') IS DISTINCT FROM '1' + OR (marker_document ->> 'phase') IS DISTINCT FROM 'PREPUBLISHED' + OR (marker_document ->> 'operationId') IS DISTINCT FROM NEW.operation_id::TEXT + OR (marker_document ->> 'operationDigest') IS DISTINCT FROM NEW.operation_digest + OR (marker_document ->> 'generationRequestDigest') IS DISTINCT FROM NEW.generation_request_digest + OR (marker_document ->> 'generationReceiptDigest') IS DISTINCT FROM NEW.generation_receipt_digest + OR ((marker_document -> 'binding') ->> 'environmentId') IS DISTINCT FROM NEW.environment_id + OR ((marker_document -> 'binding') ->> 'clusterId') IS DISTINCT FROM NEW.cluster_id + OR ((marker_document -> 'binding') ->> 'namespace') IS DISTINCT FROM NEW.kubernetes_namespace + OR ((marker_document -> 'binding') ->> 'expectedClusterIncarnationUid') IS DISTINCT FROM NEW.expected_cluster_incarnation_uid::TEXT + OR ((marker_document -> 'binding') ->> 'expectedNamespaceUid') IS DISTINCT FROM NEW.expected_namespace_uid::TEXT + OR ((marker_document -> 'binding') ->> 'trustBindingDigest') IS DISTINCT FROM NEW.trust_binding_digest + OR ((marker_document -> 'binding') ->> 'trustConfigRevision') IS DISTINCT FROM NEW.trust_config_revision + OR ((marker_document -> 'binding') ->> 'apiBindingDigest') IS DISTINCT FROM NEW.api_binding_digest + OR ((marker_document -> 'binding') ->> 'apiConfigRevision') IS DISTINCT FROM NEW.api_config_revision + OR ((marker_document -> 'publicConfigMap') ->> 'name') IS DISTINCT FROM 'jwt-jwks' + OR (marker_document -> 'expectedDurableActive') IS DISTINCT FROM (NEW.expected_durable_active_json::jsonb) + OR (marker_document -> 'expectedPublishedActive') IS DISTINCT FROM (NEW.expected_published_active_json::jsonb) + OR ((marker_document -> 'pending') ->> 'generation') IS DISTINCT FROM NEW.target_generation::TEXT + OR ((marker_document -> 'pending') ->> 'kid') IS DISTINCT FROM NEW.target_kid + OR ((marker_document -> 'pending') ->> 'algorithm') IS DISTINCT FROM 'RS256' + OR ((marker_document -> 'pending') ->> 'publicKeyFingerprint') IS DISTINCT FROM NEW.public_key_fingerprint THEN + RAISE EXCEPTION 'Account public generation marker is stale or mismatched' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_publication_receipt() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + intent_row account_jwt_jwks_prepublication_intents%ROWTYPE; +BEGIN + PERFORM account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, (SELECT intent.operation_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_request_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_receipt_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.desired_state_version FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_cluster_incarnation_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_namespace_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_binding_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_config_revision FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_generation FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_kid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.public_key_fingerprint FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id)); + SELECT intent.* INTO intent_row + FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id + FOR UPDATE; + IF NOT FOUND + OR intent_row.environment_id IS DISTINCT FROM NEW.environment_id + OR intent_row.cluster_id IS DISTINCT FROM NEW.cluster_id + OR intent_row.kubernetes_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR intent_row.custody_mode IS DISTINCT FROM NEW.custody_mode + OR intent_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR intent_row.config_map_uid IS DISTINCT FROM NEW.config_map_uid + OR intent_row.expected_resource_version IS DISTINCT FROM NEW.expected_resource_version + OR intent_row.public_data_digest IS DISTINCT FROM NEW.public_data_digest + OR NEW.expected_resource_version = NEW.observed_resource_version THEN + RAISE EXCEPTION 'Account JWT publication receipt does not match current intent' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_mount_observation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + intent_row account_jwt_jwks_prepublication_intents%ROWTYPE; + receipt_row account_jwt_jwks_publication_receipts%ROWTYPE; +BEGIN + PERFORM account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, (SELECT intent.operation_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_request_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_receipt_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.desired_state_version FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_cluster_incarnation_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_namespace_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_binding_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_config_revision FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_generation FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_kid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.public_key_fingerprint FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id)); + SELECT intent.* INTO intent_row + FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id + FOR UPDATE; + SELECT receipt.* INTO receipt_row + FROM account_jwt_jwks_publication_receipts AS receipt + WHERE receipt.operation_id = NEW.operation_id + FOR UPDATE; + IF NOT FOUND + OR intent_row.environment_id IS DISTINCT FROM NEW.environment_id + OR intent_row.cluster_id IS DISTINCT FROM NEW.cluster_id + OR intent_row.kubernetes_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR intent_row.custody_mode IS DISTINCT FROM NEW.custody_mode + OR intent_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR receipt_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR receipt_row.receipt_digest IS DISTINCT FROM NEW.publication_receipt_digest + OR intent_row.generation_marker_digest IS DISTINCT FROM NEW.generation_marker_digest + OR intent_row.public_data_digest IS DISTINCT FROM NEW.public_data_digest + OR intent_row.public_key_fingerprint IS DISTINCT FROM NEW.public_key_fingerprint THEN + RAISE EXCEPTION 'Mounted Account JWT correspondence is stale or mismatched' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_reject_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT JWKS publication evidence is immutable' USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER account_jwt_jwks_intent_current_guard + BEFORE INSERT ON account_jwt_jwks_prepublication_intents + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_public_intent(); +CREATE TRIGGER account_jwt_jwks_receipt_current_guard + BEFORE INSERT ON account_jwt_jwks_publication_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_publication_receipt(); +CREATE TRIGGER account_jwt_jwks_mount_current_guard + BEFORE INSERT ON account_jwt_jwks_mount_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_mount_observation(); + +CREATE TRIGGER account_jwt_jwks_intent_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_prepublication_intents + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_receipt_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_publication_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_mount_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_mount_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); + +CREATE TRIGGER account_jwt_jwks_intent_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_prepublication_intents + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_receipt_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_publication_receipts + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_mount_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_mount_observations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V44__account_gameplay_delegation_issuance.sql b/services/account-service/src/main/resources/db/migration/V44__account_gameplay_delegation_issuance.sql new file mode 100644 index 0000000000..058ed771b4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V44__account_gameplay_delegation_issuance.sql @@ -0,0 +1,273 @@ +-- Account-owned non-authorizing LOGIN issuance intent. This deliberately has no COMMITTED state: +-- the Account signer-promotion and current-authority projection proof required for activation do +-- not yet exist. The only mutable transition binds an exact signed-token identity once. +CREATE TABLE account_gameplay_delegation_issuance_operations ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + account_uuid UUID NOT NULL REFERENCES accounts (account_uuid) ON DELETE RESTRICT, + caller_workload VARCHAR(256) NOT NULL, + caller_context_id UUID NOT NULL, + request_digest_version SMALLINT NOT NULL, + request_digest VARCHAR(64) NOT NULL, + token_jti UUID NOT NULL UNIQUE, + token_generation BIGINT NOT NULL DEFAULT 1, + issued_at_epoch_second BIGINT NOT NULL, + not_before_epoch_second BIGINT NOT NULL, + expires_at_epoch_second BIGINT NOT NULL, + authority_issuer_generation BIGINT NOT NULL, + authority_issuer_source_version BIGINT NOT NULL, + authority_account_generation BIGINT NOT NULL, + authority_account_source_version BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + issuance_fence_source_version BIGINT NOT NULL, + authority_tuple_canonical_bytes BYTEA NOT NULL, + membership_version_canonical_bytes BYTEA NOT NULL, + authority_source_versions_canonical_bytes BYTEA NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'PENDING', + token_hash VARCHAR(64), + signer_kid VARCHAR(64), + signer_generation VARCHAR(19), + pending_registry_candidate_bytes BYTEA, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_gameplay_delegation_operation_ids_check + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND caller_context_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND caller_context_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND token_jti <> '00000000-0000-0000-0000-000000000000'::UUID + AND token_jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_gameplay_delegation_caller_check + CHECK (caller_workload ~ '^spiffe://firemud/ns/[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?/sa/game-session-service$'), + CONSTRAINT account_gameplay_delegation_digest_check + CHECK (request_digest_version = 1 AND request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_gameplay_delegation_time_check + CHECK (token_generation = 1 AND issued_at_epoch_second > 0 + AND not_before_epoch_second > 0 AND not_before_epoch_second <= issued_at_epoch_second + AND expires_at_epoch_second > issued_at_epoch_second + AND expires_at_epoch_second - issued_at_epoch_second <= 300), + CONSTRAINT account_gameplay_delegation_authority_check + CHECK (authority_issuer_generation > 0 AND authority_issuer_source_version > 0 + AND authority_account_generation > 0 AND authority_account_source_version > 0 + AND issuance_fence > 0 AND issuance_fence_source_version > 0), + CONSTRAINT account_gameplay_delegation_profile_bytes_check + CHECK (octet_length(authority_tuple_canonical_bytes) BETWEEN 1 AND 4096 + AND convert_from(membership_version_canonical_bytes, 'UTF8') = '{}' + AND octet_length(authority_source_versions_canonical_bytes) BETWEEN 1 AND 4096), + CONSTRAINT account_gameplay_delegation_status_check CHECK (status = 'PENDING'), + CONSTRAINT account_gameplay_delegation_candidate_shape_check + CHECK ((token_hash IS NULL AND signer_kid IS NULL AND signer_generation IS NULL + AND pending_registry_candidate_bytes IS NULL) + OR (token_hash IS NOT NULL AND token_hash ~ '^[0-9a-f]{64}$' + AND signer_kid IS NOT NULL AND signer_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND signer_generation IS NOT NULL AND signer_generation ~ '^[1-9][0-9]{0,18}$' + AND pending_registry_candidate_bytes IS NOT NULL + AND octet_length(pending_registry_candidate_bytes) BETWEEN 1 AND 16384)) +); + +-- Insert and post-sign bind both lock and compare the existing Account authority sources. This +-- is intentionally the same issuer/account/fence model used by AccountAuthorityGenerationRepository. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_delegation_authority_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + source_issuer_generation BIGINT; + source_issuer_source_version BIGINT; + current_issuer_sequence BIGINT; + current_issuer_stream VARCHAR(2048); + current_account_generation BIGINT; + current_account_source_version BIGINT; + source_account_generation BIGINT; + source_account_source_version BIGINT; + current_account_sequence BIGINT; + current_account_stream VARCHAR(2048); + current_account_cutoff_generation BIGINT; + current_account_cutoff_stream VARCHAR(2048); + current_account_cutoff_sequence BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + expected_authority_tuple TEXT; +BEGIN + -- Keep the owner lock order: Account row, issuer/account generations and fence, then the + -- source rows whose exact optional cutoff is carried by the immutable pending intent. + PERFORM account_uuid FROM accounts WHERE account_uuid = NEW.account_uuid FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account gameplay delegation Account source is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + SELECT outbox_stream_key, current_generation, current_source_version, last_outbox_sequence + INTO current_issuer_stream, source_issuer_generation, source_issuer_source_version, + current_issuer_sequence + FROM account_authority_source_records + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL + AND outbox_stream_key = 'account:auth-authority:v1:issuer/firemud-account-service' + FOR UPDATE; + SELECT outbox_stream_key, current_generation, current_source_version, last_outbox_sequence, + cutoff_generation, cutoff_stream_key, cutoff_sequence + INTO current_account_stream, source_account_generation, source_account_source_version, + current_account_sequence, current_account_cutoff_generation, + current_account_cutoff_stream, current_account_cutoff_sequence + FROM account_authority_source_records + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL + AND outbox_stream_key = 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + FOR UPDATE; + + IF current_account_sequence = 0 + AND current_account_cutoff_generation IS NULL + AND current_account_cutoff_stream IS NULL + AND current_account_cutoff_sequence IS NULL THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":' || source_account_generation::TEXT + || ',"issuerAuthGeneration":' || source_issuer_generation::TEXT + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + ELSIF current_account_sequence > 0 + AND current_account_cutoff_generation = source_account_generation + AND current_account_cutoff_stream = current_account_stream + AND current_account_cutoff_sequence = current_account_sequence THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":' || source_account_generation::TEXT + || ',"accountSecurityCutoff":{"accountAuthorityGeneration":"' + || current_account_cutoff_generation::TEXT || '","outboxSequence":"' + || current_account_cutoff_sequence::TEXT || '","outboxStreamKey":"' + || current_account_cutoff_stream || '"},"issuerAuthGeneration":' + || source_issuer_generation::TEXT + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + END IF; + + IF current_issuer_generation IS NULL OR current_account_generation IS NULL + OR current_issuance_fence IS NULL OR current_issuer_stream IS NULL + OR current_account_stream IS NULL OR current_issuer_sequence IS NULL + OR current_account_sequence IS NULL OR source_issuer_generation IS NULL + OR source_issuer_source_version IS NULL OR source_account_generation IS NULL + OR source_account_source_version IS NULL OR current_fence_source_version IS NULL + OR expected_authority_tuple IS NULL + OR current_issuer_stream <> 'account:auth-authority:v1:issuer/firemud-account-service' + OR current_account_stream <> 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + OR source_issuer_generation <> current_issuer_generation + OR source_issuer_source_version <> current_issuer_source_version + OR source_account_generation <> current_account_generation + OR source_account_source_version <> current_account_source_version + OR source_issuer_generation <> source_issuer_source_version + OR source_issuer_generation <> current_issuer_sequence + 1 + OR source_account_generation <> source_account_source_version + OR source_account_generation <> current_account_sequence + 1 + OR current_issuance_fence <> current_account_sequence + 1 + OR current_fence_source_version <> current_account_sequence + 1 + OR NEW.authority_issuer_generation <> current_issuer_generation + OR NEW.authority_issuer_source_version <> current_issuer_source_version + OR NEW.authority_account_generation <> current_account_generation + OR NEW.authority_account_source_version <> current_account_source_version + OR NEW.issuance_fence <> current_issuance_fence + OR NEW.issuance_fence_source_version <> current_fence_source_version + OR convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8') <> + expected_authority_tuple + OR convert_from(NEW.membership_version_canonical_bytes, 'UTF8') <> '{}' + OR convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8') <> + '{"accountSourceVersion":' || current_account_source_version::text + || ',"issuanceFenceSourceVersion":' || current_fence_source_version::text + || ',"issuerSourceVersion":' || current_issuer_source_version::text || '}' THEN + RAISE EXCEPTION 'Account gameplay delegation authority snapshot is stale or missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_gameplay_delegation_authority_guard + BEFORE INSERT OR UPDATE ON account_gameplay_delegation_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_gameplay_delegation_authority_guard(); + +CREATE FUNCTION account_gameplay_delegation_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account gameplay delegation issuance evidence cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + IF NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.caller_workload IS DISTINCT FROM OLD.caller_workload + OR NEW.caller_context_id IS DISTINCT FROM OLD.caller_context_id + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.token_jti IS DISTINCT FROM OLD.token_jti + OR NEW.token_generation IS DISTINCT FROM OLD.token_generation + OR NEW.issued_at_epoch_second IS DISTINCT FROM OLD.issued_at_epoch_second + OR NEW.not_before_epoch_second IS DISTINCT FROM OLD.not_before_epoch_second + OR NEW.expires_at_epoch_second IS DISTINCT FROM OLD.expires_at_epoch_second + OR NEW.authority_issuer_generation IS DISTINCT FROM OLD.authority_issuer_generation + OR NEW.authority_issuer_source_version IS DISTINCT FROM OLD.authority_issuer_source_version + OR NEW.authority_account_generation IS DISTINCT FROM OLD.authority_account_generation + OR NEW.authority_account_source_version IS DISTINCT FROM OLD.authority_account_source_version + OR NEW.issuance_fence IS DISTINCT FROM OLD.issuance_fence + OR NEW.issuance_fence_source_version IS DISTINCT FROM OLD.issuance_fence_source_version + OR NEW.authority_tuple_canonical_bytes IS DISTINCT FROM OLD.authority_tuple_canonical_bytes + OR NEW.membership_version_canonical_bytes IS DISTINCT FROM OLD.membership_version_canonical_bytes + OR NEW.authority_source_versions_canonical_bytes IS DISTINCT FROM OLD.authority_source_versions_canonical_bytes + OR NEW.status IS DISTINCT FROM OLD.status + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Account gameplay delegation intent is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + IF OLD.token_hash IS NOT NULL OR OLD.signer_kid IS NOT NULL + OR OLD.signer_generation IS NOT NULL OR OLD.pending_registry_candidate_bytes IS NOT NULL + OR NEW.token_hash IS NULL OR NEW.signer_kid IS NULL + OR NEW.signer_generation IS NULL OR NEW.pending_registry_candidate_bytes IS NULL THEN + RAISE EXCEPTION 'Account gameplay delegation token identity may be bound exactly once' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_candidate_one_way'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_gameplay_delegation_operation_guard + BEFORE UPDATE OR DELETE ON account_gameplay_delegation_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_gameplay_delegation_operation_guard(); + +CREATE FUNCTION account_gameplay_delegation_operation_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM account_gameplay_delegation_issuance_operations) THEN + RAISE EXCEPTION 'Account gameplay delegation issuance evidence cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_gameplay_delegation_operation_no_truncate + BEFORE TRUNCATE ON account_gameplay_delegation_issuance_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_delegation_operation_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql b/services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql new file mode 100644 index 0000000000..611ce071cf --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql @@ -0,0 +1,466 @@ +-- Durable, operation-scoped probe plans for the interim Account-mounted JWT signer. +-- Plans bind existing desired-state, generation-result, JWKS publication, and mount evidence; +-- this migration creates no second key authority, validator endpoint, or promotion transition. +CREATE TABLE account_jwt_readiness_probe_plans ( + rotation_operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + generation_receipt_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_public_key_fingerprint VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + expected_published_generation BIGINT, + expected_published_kid VARCHAR(64), + publication_intent_digest VARCHAR(64) NOT NULL, + publication_receipt_digest VARCHAR(64) NOT NULL, + mounted_observation_digest VARCHAR(64) NOT NULL, + applicability_matrix_json TEXT NOT NULL, + applicability_matrix_digest VARCHAR(64) NOT NULL, + validator_inventory_complete BOOLEAN NOT NULL DEFAULT FALSE, + maximum_cache_age_seconds SMALLINT NOT NULL, + planned_at_epoch_seconds BIGINT NOT NULL, + not_before_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + plan_version SMALLINT NOT NULL DEFAULT 1, + plan_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_readiness_plan_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_operation_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_result_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_signer_generation_results(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_publication_intent_fk + FOREIGN KEY (rotation_operation_id, publication_intent_digest) + REFERENCES account_jwt_jwks_prepublication_intents(operation_id, intent_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_publication_receipt_fk + FOREIGN KEY (rotation_operation_id, publication_intent_digest, publication_receipt_digest) + REFERENCES account_jwt_jwks_publication_receipts( + operation_id, intent_digest, receipt_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_mount_observation_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_jwks_mount_observations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_identity_check + CHECK (rotation_operation_id::text ~ + '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND desired_state_version > 1 + AND target_generation > COALESCE(expected_active_generation, 0) + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL + AND expected_published_generation IS NULL AND expected_published_kid IS NULL) + OR (expected_active_generation IS NOT NULL AND expected_active_kid IS NOT NULL + AND expected_published_generation IS NOT NULL AND expected_published_kid IS NOT NULL + AND expected_active_generation > 0 + AND expected_active_generation = expected_published_generation + AND expected_active_kid = expected_published_kid)) + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_active_kid IS NULL OR expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$') + AND target_kid <> expected_active_kid + AND target_public_key_fingerprint ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_readiness_plan_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND generation_receipt_digest ~ '^[0-9a-f]{64}$' + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND publication_intent_digest ~ '^[0-9a-f]{64}$' + AND publication_receipt_digest ~ '^[0-9a-f]{64}$' + AND mounted_observation_digest ~ '^[0-9a-f]{64}$' + AND applicability_matrix_digest ~ '^[0-9a-f]{64}$' + AND plan_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_readiness_plan_revision_check + CHECK (trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_readiness_plan_trust_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_readiness_plan_inventory_check + CHECK (octet_length(applicability_matrix_json) BETWEEN 2 AND 8192), + CONSTRAINT account_jwt_readiness_plan_window_check + CHECK (maximum_cache_age_seconds BETWEEN 1 AND 300 + AND planned_at_epoch_seconds > 0 + AND not_before_epoch_seconds >= planned_at_epoch_seconds + maximum_cache_age_seconds + AND expires_at_epoch_seconds > not_before_epoch_seconds + AND expires_at_epoch_seconds - not_before_epoch_seconds <= 300 + AND plan_version = 1), + CONSTRAINT account_jwt_readiness_plan_digest_unique + UNIQUE (rotation_operation_id, plan_digest) +); + +CREATE TABLE account_jwt_readiness_probe_entries ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + jti UUID NOT NULL UNIQUE, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + registry_version SMALLINT NOT NULL DEFAULT 1, + entry_version BIGINT NOT NULL DEFAULT 1, + planned_issued_at_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + state VARCHAR(16) NOT NULL DEFAULT 'PLANNED', + terminal_outcome VARCHAR(16), + signing_attempted_at_epoch_seconds BIGINT, + compact_token_sha256 VARCHAR(64), + verification_receipt_version SMALLINT, + verification_source_entry_version BIGINT, + verified_at_epoch_seconds BIGINT, + verified_kid VARCHAR(64), + validator_instance_id VARCHAR(128), + validator_binding_digest VARCHAR(64), + validator_config_revision VARCHAR(128), + validator_peer_uri VARCHAR(256), + validator_peer_spki_sha256 VARCHAR(64), + verification_receipt_sha256 VARCHAR(64), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind), + CONSTRAINT account_jwt_readiness_probe_plan_fk + FOREIGN KEY (rotation_operation_id, plan_digest) + REFERENCES account_jwt_readiness_probe_plans(rotation_operation_id, plan_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_probe_jti_v4_check + CHECK (jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_jwt_readiness_probe_identity_check + CHECK (validator_id ~ '^[a-z0-9][a-z0-9-]{0,62}$' + AND token_profile ~ '^[a-z0-9][a-z0-9-]{0,127}$' + AND audience ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND probe_kind IN ('CANARY', 'REPRESENTATIVE') + AND target_generation > COALESCE(expected_active_generation, 0) + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation IS NOT NULL AND expected_active_kid IS NOT NULL + AND expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid), + CONSTRAINT account_jwt_readiness_probe_state_check + CHECK (state IN ('PLANNED', 'ISSUED', 'VERIFIED', 'RETIRED', 'CLEANED', 'EXPIRED', 'ABORTED') + AND (terminal_outcome IS NULL OR terminal_outcome IN ('EXPIRED', 'ABORTED')) + AND ((state IN ('EXPIRED', 'ABORTED', 'CLEANED') AND terminal_outcome IS NOT NULL) + OR (state NOT IN ('EXPIRED', 'ABORTED', 'CLEANED') AND terminal_outcome IS NULL))), + CONSTRAINT account_jwt_readiness_probe_evidence_check + CHECK (plan_digest ~ '^[0-9a-f]{64}$' + AND registry_version = 1 + AND entry_version > 0 + AND planned_issued_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > planned_issued_at_epoch_seconds + AND (compact_token_sha256 IS NULL OR compact_token_sha256 ~ '^[0-9a-f]{64}$') + AND (signing_attempted_at_epoch_seconds IS NULL + OR (signing_attempted_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND signing_attempted_at_epoch_seconds < expires_at_epoch_seconds)) + AND ((compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL) + OR (compact_token_sha256 IS NOT NULL AND signing_attempted_at_epoch_seconds IS NOT NULL)) + AND (state NOT IN ('ISSUED', 'VERIFIED', 'RETIRED') + OR compact_token_sha256 IS NOT NULL) + AND (verification_receipt_version IS NULL OR verification_receipt_version = 1) + AND (verification_source_entry_version IS NULL OR verification_source_entry_version > 0) + AND (verified_at_epoch_seconds IS NULL + OR (verified_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND verified_at_epoch_seconds < expires_at_epoch_seconds)) + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND (validator_instance_id IS NULL + OR validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_binding_digest IS NULL OR validator_binding_digest ~ '^[0-9a-f]{64}$') + AND (validator_config_revision IS NULL + OR validator_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_peer_uri IS NULL + OR validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness$') + AND (validator_peer_spki_sha256 IS NULL + OR validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$') + AND (verification_receipt_sha256 IS NULL + OR verification_receipt_sha256 ~ '^[0-9a-f]{64}$') + AND ((verification_receipt_sha256 IS NULL + AND verification_receipt_version IS NULL + AND verification_source_entry_version IS NULL + AND verified_at_epoch_seconds IS NULL + AND verified_kid IS NULL + AND validator_instance_id IS NULL + AND validator_binding_digest IS NULL + AND validator_config_revision IS NULL + AND validator_peer_uri IS NULL + AND validator_peer_spki_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 1 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid IS NOT NULL + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL)) + AND (state NOT IN ('VERIFIED', 'RETIRED') OR verification_receipt_sha256 IS NOT NULL) + AND (state NOT IN ('PLANNED', 'ISSUED') OR verification_receipt_sha256 IS NULL)) +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_readiness_plan_inventory_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + matrix jsonb; +BEGIN + IF NEW.validator_inventory_complete THEN + RAISE EXCEPTION 'Readiness inventory is incomplete without authenticated validator evidence' + USING ERRCODE = '23514'; + END IF; + matrix := NEW.applicability_matrix_json::jsonb; + IF matrix ->> 'inventoryStatus' <> 'PARTIAL_UNCONFIRMED' + OR matrix ->> 'schemaVersion' <> '1' + OR jsonb_array_length(matrix -> 'validators') <> 1 + OR matrix #>> '{validators,0,validatorId}' <> 'account-service' + OR jsonb_array_length(matrix #> '{validators,0,applicableProfiles}') <> 3 + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Readiness applicability must bind the exact partial Account profile set' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_plan_inventory + BEFORE INSERT ON account_jwt_readiness_probe_plans + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_plan_inventory_guard(); + +CREATE FUNCTION account_jwt_readiness_plan_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT readiness probe plans are immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_plan_immutable + BEFORE UPDATE OR DELETE ON account_jwt_readiness_probe_plans + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_plan_immutable_guard(); + +CREATE FUNCTION account_jwt_readiness_entry_lifecycle_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'PLANNED' + OR NEW.entry_version <> 1 + OR NEW.terminal_outcome IS NOT NULL + OR NEW.compact_token_sha256 IS NOT NULL + OR NEW.signing_attempted_at_epoch_seconds IS NOT NULL + OR NEW.verification_receipt_sha256 IS NOT NULL THEN + RAISE EXCEPTION 'Account JWT readiness entries must begin PLANNED' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM plan_row.not_before_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Account JWT readiness entry differs from its immutable plan' + USING ERRCODE = '23514'; + END IF; + IF NEW.probe_kind = 'CANARY' THEN + IF NEW.validator_id <> 'account-service' + OR NEW.token_profile <> 'account-jwt-readiness-canary' + OR NEW.audience <> 'firemud-account-jwt-readiness' THEN + RAISE EXCEPTION 'Account JWT readiness canary shape is not fixed' + USING ERRCODE = '23514'; + END IF; + ELSIF NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') + AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'applicableProfiles') + AS applicable(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND applicable.value ->> 'tokenProfile' = NEW.token_profile + AND applicable.value ->> 'audience' = NEW.audience + ) THEN + RAISE EXCEPTION 'Account JWT readiness profile is outside its applicability matrix' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT readiness evidence is retained' USING ERRCODE = '23514'; + END IF; + + IF NEW.rotation_operation_id IS DISTINCT FROM OLD.rotation_operation_id + OR NEW.plan_digest IS DISTINCT FROM OLD.plan_digest + OR NEW.validator_id IS DISTINCT FROM OLD.validator_id + OR NEW.token_profile IS DISTINCT FROM OLD.token_profile + OR NEW.audience IS DISTINCT FROM OLD.audience + OR NEW.probe_kind IS DISTINCT FROM OLD.probe_kind + OR NEW.jti IS DISTINCT FROM OLD.jti + OR NEW.target_generation IS DISTINCT FROM OLD.target_generation + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM OLD.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM OLD.expected_active_kid + OR NEW.registry_version IS DISTINCT FROM OLD.registry_version + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM OLD.planned_issued_at_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM OLD.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Account JWT readiness probe identity is immutable' USING ERRCODE = '23514'; + END IF; + + IF NEW.entry_version <> OLD.entry_version + 1 THEN + RAISE EXCEPTION 'Account JWT readiness entry version must advance once' USING ERRCODE = '23514'; + END IF; + + IF OLD.state = 'PLANNED' + AND NEW.state = 'PLANNED' + AND OLD.compact_token_sha256 IS NULL + AND NEW.compact_token_sha256 IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds >= OLD.planned_issued_at_epoch_seconds + AND NEW.signing_attempted_at_epoch_seconds < OLD.expires_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + + IF OLD.state = 'PLANNED' + AND NEW.state = 'ISSUED' + AND OLD.compact_token_sha256 IS NOT NULL + AND NEW.compact_token_sha256 = OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds = OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + + IF OLD.state = 'ISSUED' AND NEW.state = 'VERIFIED' THEN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.compact_token_sha256 IS DISTINCT FROM OLD.compact_token_sha256 + OR NEW.signing_attempted_at_epoch_seconds + IS DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + OR NEW.verification_receipt_version IS DISTINCT FROM 1 + OR NEW.verification_source_entry_version IS DISTINCT FROM OLD.entry_version + OR NEW.entry_version IS DISTINCT FROM OLD.entry_version + 1 + OR NEW.verified_kid IS DISTINCT FROM OLD.target_kid + OR NEW.verified_at_epoch_seconds IS NULL + OR NEW.verified_at_epoch_seconds < OLD.planned_issued_at_epoch_seconds + OR NEW.verified_at_epoch_seconds >= OLD.expires_at_epoch_seconds + OR to_timestamp(NEW.verified_at_epoch_seconds) > CURRENT_TIMESTAMP + OR NEW.validator_id IS DISTINCT FROM 'account-service' + OR NEW.validator_peer_uri IS DISTINCT FROM + 'spiffe://firemud/ns/' || plan_row.kubernetes_namespace || '/sa/account-jwt-readiness-harness' + OR CURRENT_TIMESTAMP < to_timestamp(OLD.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + OR NEW.terminal_outcome IS NOT NULL THEN + RAISE EXCEPTION 'Verified readiness probe differs from its current immutable plan' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'ABORTED' + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.terminal_outcome = 'ABORTED' THEN + RETURN NEW; + END IF; + + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'EXPIRED' + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.terminal_outcome = 'EXPIRED' THEN + RETURN NEW; + END IF; + + IF OLD.state IN ('ABORTED', 'EXPIRED') + AND NEW.state = 'CLEANED' + AND NEW.terminal_outcome = OLD.terminal_outcome + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 THEN + RETURN NEW; + END IF; + + -- This table records bounded non-authorizing observations only. RETIRED and every promotion + -- transition remain unavailable until their separate Account owner contracts are implemented. + RAISE EXCEPTION 'Account JWT readiness probe lifecycle transition is unavailable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_lifecycle + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V46__account_auth_evidence_bundles.sql b/services/account-service/src/main/resources/db/migration/V46__account_auth_evidence_bundles.sql new file mode 100644 index 0000000000..8760d48546 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V46__account_auth_evidence_bundles.sql @@ -0,0 +1,374 @@ +-- Strict, immutable, non-authorizing evidence snapshots for exact Account-owned issuance rows. +-- This table does not introduce COMMITTED/ACTIVE state or provide credential response recovery. +CREATE TABLE account_gameplay_auth_evidence_source_fence ( + allocator_id BOOLEAN PRIMARY KEY DEFAULT TRUE, + last_source_fence BIGINT NOT NULL, + last_operation_id UUID, + last_transaction_id VARCHAR(20), + CONSTRAINT account_gameplay_auth_evidence_source_fence_singleton + CHECK (allocator_id), + CONSTRAINT account_gameplay_auth_evidence_source_fence_state + CHECK ((last_source_fence = 0 AND last_operation_id IS NULL AND last_transaction_id IS NULL) + OR (last_source_fence > 0 AND last_operation_id IS NOT NULL + AND last_transaction_id IS NOT NULL + AND last_transaction_id ~ '^[1-9][0-9]{0,19}$' + AND last_transaction_id::numeric <= 18446744073709551615)), + CONSTRAINT account_gameplay_auth_evidence_source_fence_operation_fk + FOREIGN KEY (last_operation_id) + REFERENCES account_gameplay_delegation_issuance_operations(operation_id) + ON DELETE RESTRICT +); +INSERT INTO account_gameplay_auth_evidence_source_fence (allocator_id, last_source_fence) +VALUES (TRUE, 0); + +CREATE TABLE account_gameplay_delegation_auth_evidence_bundles ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + account_uuid UUID NOT NULL, + bundle_schema VARCHAR(64) NOT NULL, + bundle_version VARCHAR(19) NOT NULL, + source_version VARCHAR(20) NOT NULL, + source_fence VARCHAR(19) NOT NULL, + issuance_fence VARCHAR(19) NOT NULL, + linearization VARCHAR(20) NOT NULL, + canonical_sha256 VARCHAR(64) NOT NULL, + canonical_bundle_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_gameplay_auth_evidence_schema_check + CHECK (bundle_schema = 'account-auth-evidence-bundle/v1'), + CONSTRAINT account_gameplay_auth_evidence_positive_values_check + CHECK (bundle_version ~ '^[1-9][0-9]{0,18}$' + AND bundle_version::numeric <= 9223372036854775807 + AND source_version ~ '^[1-9][0-9]{0,19}$' + AND source_version::numeric <= 18446744073709551615 + AND source_fence ~ '^[1-9][0-9]{0,18}$' + AND source_fence::numeric <= 9223372036854775807 + AND issuance_fence ~ '^[1-9][0-9]{0,18}$' + AND issuance_fence::numeric <= 9223372036854775807 + AND linearization ~ '^[1-9][0-9]{0,19}$' + AND linearization::numeric <= 18446744073709551615), + CONSTRAINT account_gameplay_auth_evidence_source_fence_unique UNIQUE (source_fence), + CONSTRAINT account_gameplay_auth_evidence_digest_check + CHECK (canonical_sha256 ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_gameplay_auth_evidence_size_check + CHECK (octet_length(canonical_bundle_bytes) BETWEEN 1 AND 8192), + CONSTRAINT account_gameplay_auth_evidence_json_check + CHECK (jsonb_typeof(convert_from(canonical_bundle_bytes, 'UTF8')::jsonb) = 'object'), + CONSTRAINT account_gameplay_auth_evidence_operation_fk + FOREIGN KEY (operation_id) + REFERENCES account_gameplay_delegation_issuance_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_gameplay_auth_evidence_request_fk + FOREIGN KEY (request_id) + REFERENCES account_gameplay_delegation_issuance_operations(request_id) + ON DELETE RESTRICT, + CONSTRAINT account_gameplay_auth_evidence_account_fk + FOREIGN KEY (account_uuid) + REFERENCES accounts(account_uuid) + ON DELETE RESTRICT +); + +-- SQL binds the snapshot to the exact immutable pending operation, current owner rows, Account +-- identity, and existing positive outbox event identities. A zero checkpoint is only a closed +-- encoding for an owner-proved initialized empty stream; this trigger can check the stored shape, +-- but cannot prove its exhaustive-history provenance. The Account repository additionally has to +-- validate event payload contracts and cutoff applicability before it can insert. A +-- sequence/high-water mark alone is never accepted as source evidence. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_auth_evidence_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; + account_row RECORD; + bundle JSONB; + checkpoint JSONB; + expected_account_stream TEXT; + expected_issuer_stream TEXT := 'account:auth-authority:v1:issuer/firemud-account-service'; + capture_transaction_id TEXT; + allocated_source_fence BIGINT; + allocated_operation_id UUID; + allocated_transaction_id TEXT; + checkpoint_count INTEGER; + matched_account_checkpoint BOOLEAN := FALSE; + matched_issuer_checkpoint BOOLEAN := FALSE; + checkpoint_sequence BIGINT; + stream_sequence BIGINT; + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + current_account_generation BIGINT; + current_account_source_version BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + event_row RECORD; +BEGIN + bundle := convert_from(NEW.canonical_bundle_bytes, 'UTF8')::jsonb; + capture_transaction_id := pg_current_xact_id()::text; + + SELECT last_source_fence, last_operation_id, last_transaction_id + INTO allocated_source_fence, allocated_operation_id, allocated_transaction_id + FROM account_gameplay_auth_evidence_source_fence + WHERE allocator_id = TRUE + FOR UPDATE; + IF allocated_source_fence IS NULL + OR allocated_source_fence <= 0 + OR NEW.source_fence IS DISTINCT FROM allocated_source_fence::text + OR allocated_operation_id IS DISTINCT FROM NEW.operation_id + OR allocated_transaction_id IS DISTINCT FROM capture_transaction_id + OR NEW.source_version IS DISTINCT FROM capture_transaction_id + OR NEW.linearization IS DISTINCT FROM capture_transaction_id THEN + RAISE EXCEPTION 'Account auth-evidence bundle reference is not the exact persisted capture allocation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_capture_reference'; + END IF; + + -- Match the Account owner lock order used by source snapshots and issuance: Account row, + -- issuer/account generations, issuance fence, then the operation row. The Account identity is + -- read-only here, so FOR SHARE also avoids upgrading the source reader's existing lock. + SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id + INTO account_row + FROM accounts + WHERE account_uuid = NEW.account_uuid + FOR SHARE; + IF account_row.id IS NULL + OR account_row.id <> account_row.account_uuid_source_numeric_id + OR account_row.account_uuid_provenance NOT IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT') + OR bundle#>>'{accountIdentitySource,sourceRowId}' IS DISTINCT FROM account_row.id::text + OR bundle#>>'{accountIdentitySource,sourceNumericId}' IS DISTINCT FROM account_row.account_uuid_source_numeric_id::text + OR bundle#>>'{accountIdentitySource,provenance}' IS DISTINCT FROM account_row.account_uuid_provenance THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the Account identity row' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_identity_match'; + END IF; + + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + + SELECT * INTO operation_row + FROM account_gameplay_delegation_issuance_operations + WHERE operation_id = NEW.operation_id + FOR UPDATE; + IF operation_row.operation_id IS NULL + OR operation_row.request_id <> NEW.request_id + OR operation_row.account_uuid <> NEW.account_uuid + OR operation_row.status <> 'PENDING' + OR bundle->>'schema' IS DISTINCT FROM NEW.bundle_schema + OR bundle->>'profile' IS DISTINCT FROM 'game-session-account-delegation' + OR bundle->>'issuer' IS DISTINCT FROM 'firemud-account-service' + OR bundle->>'audience' IS DISTINCT FROM 'account-service' + OR bundle#>>'{bundleRef,bundleVersion}' IS DISTINCT FROM NEW.bundle_version + OR bundle#>>'{bundleRef,sourceVersion}' IS DISTINCT FROM NEW.source_version + OR bundle#>>'{bundleRef,sourceFence}' IS DISTINCT FROM NEW.source_fence + OR bundle#>>'{bundleRef,linearization}' IS DISTINCT FROM NEW.linearization + OR bundle#>>'{scope,kind}' IS DISTINCT FROM 'account' + OR bundle#>>'{scope,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR jsonb_typeof(bundle#>'{scope,tenantIds}') IS DISTINCT FROM 'array' + OR COALESCE(jsonb_array_length(bundle#>'{scope,tenantIds}'), -1) <> 0 + OR bundle#>>'{operation,operationId}' IS DISTINCT FROM NEW.operation_id::text + OR bundle#>>'{operation,requestId}' IS DISTINCT FROM NEW.request_id::text + OR bundle#>>'{operation,requestDigest}' IS DISTINCT FROM operation_row.request_digest + OR bundle#>>'{operation,callerWorkload}' IS DISTINCT FROM operation_row.caller_workload + OR bundle#>>'{operation,callerContextId}' IS DISTINCT FROM operation_row.caller_context_id::text + OR bundle#>>'{operation,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR bundle#>>'{tokenIdentity,jti}' IS DISTINCT FROM operation_row.token_jti::text + OR bundle#>>'{tokenIdentity,tokenGeneration}' IS DISTINCT FROM operation_row.token_generation::text + OR bundle#>>'{tokenIdentity,iat}' IS DISTINCT FROM operation_row.issued_at_epoch_second::text + OR bundle#>>'{tokenIdentity,nbf}' IS DISTINCT FROM operation_row.not_before_epoch_second::text + OR bundle#>>'{tokenIdentity,exp}' IS DISTINCT FROM operation_row.expires_at_epoch_second::text + OR bundle->'authorityTuple' IS DISTINCT FROM + convert_from(operation_row.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR bundle->'membershipVersion' IS DISTINCT FROM + convert_from(operation_row.membership_version_canonical_bytes, 'UTF8')::jsonb + OR bundle->>'issuanceFence' IS DISTINCT FROM operation_row.issuance_fence::text + OR bundle->'authoritySourceVersions' IS DISTINCT FROM + jsonb_build_object( + 'issuerSourceVersion', operation_row.authority_issuer_source_version::text, + 'accountSourceVersion', operation_row.authority_account_source_version::text, + 'issuanceFenceSourceVersion', operation_row.issuance_fence_source_version::text) + OR NEW.issuance_fence <> operation_row.issuance_fence::text THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the exact pending operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_operation_match'; + END IF; + + IF current_issuer_generation IS NULL + OR current_account_generation IS NULL + OR current_issuance_fence IS NULL + OR operation_row.authority_issuer_generation <> current_issuer_generation + OR operation_row.authority_issuer_source_version <> current_issuer_source_version + OR operation_row.authority_account_generation <> current_account_generation + OR operation_row.authority_account_source_version <> current_account_source_version + OR operation_row.issuance_fence <> current_issuance_fence + OR operation_row.issuance_fence_source_version <> current_fence_source_version THEN + RAISE EXCEPTION 'Account auth-evidence bundle is stale against current authority' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_current_authority'; + END IF; + + expected_account_stream := 'account:auth-authority:v1:account/' || NEW.account_uuid::text; + IF jsonb_typeof(bundle->'outboxCheckpoints') <> 'array' + OR jsonb_array_length(bundle->'outboxCheckpoints') <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle requires exact issuer and Account checkpoints' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT count(*) INTO checkpoint_count FROM jsonb_array_elements(bundle->'outboxCheckpoints'); + IF checkpoint_count <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are ambiguous' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + FOR checkpoint IN SELECT value FROM jsonb_array_elements(bundle->'outboxCheckpoints') LOOP + IF checkpoint->>'outboxStreamKey' = expected_account_stream THEN + matched_account_checkpoint := TRUE; + ELSIF checkpoint->>'outboxStreamKey' = expected_issuer_stream THEN + matched_issuer_checkpoint := TRUE; + ELSE + RAISE EXCEPTION 'Account auth-evidence bundle has an out-of-scope checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF COALESCE(checkpoint->>'outboxSequence', '') !~ '^(0|[1-9][0-9]{0,18})$' THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint sequence is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + checkpoint_sequence := (checkpoint->>'outboxSequence')::BIGINT; + SELECT last_sequence INTO stream_sequence + FROM account_authority_outbox_streams + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + FOR SHARE; + IF checkpoint_sequence = 0 THEN + IF jsonb_object_length(checkpoint) <> 2 + OR checkpoint ? 'sourceEventId' + OR checkpoint ? 'sourceEventDigest' + OR stream_sequence IS DISTINCT FROM 0 + OR EXISTS ( + SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey') THEN + RAISE EXCEPTION 'Account zero checkpoint is not an exact initialized empty stream' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + ELSE + IF jsonb_object_length(checkpoint) <> 4 + OR checkpoint->>'sourceEventId' IS NULL + OR checkpoint->>'sourceEventDigest' IS NULL THEN + RAISE EXCEPTION 'Account positive checkpoint is missing exact event identity' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT event_id, event_digest INTO event_row + FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + AND outbox_sequence = checkpoint_sequence; + IF stream_sequence IS DISTINCT FROM checkpoint_sequence + OR event_row.event_id IS NULL + OR checkpoint->>'sourceEventId' <> event_row.event_id + OR checkpoint->>'sourceEventDigest' <> event_row.event_digest THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not match a current stored event' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + END IF; + END LOOP; + IF NOT matched_account_checkpoint OR NOT matched_issuer_checkpoint THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are incomplete' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF bundle#>'{authorityTuple,accountSecurityCutoff}' IS NOT NULL THEN + IF bundle#>>'{authorityTuple,accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM expected_account_stream + OR bundle#>>'{authorityTuple,accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM + operation_row.authority_account_generation::text + OR COALESCE(bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}', '') !~ '^[1-9][0-9]{0,18}$' THEN + RAISE EXCEPTION 'Account auth-evidence security cutoff is malformed or out of scope' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + IF (bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}')::BIGINT > ( + SELECT (item->>'outboxSequence')::BIGINT + FROM jsonb_array_elements(bundle->'outboxCheckpoints') AS item + WHERE item->>'outboxStreamKey' = expected_account_stream) THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not cover its cutoff' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_gameplay_auth_evidence_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account auth-evidence bundle is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_immutable'; + RETURN OLD; +END; +$$; + +CREATE FUNCTION account_gameplay_auth_evidence_source_fence_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.allocator_id IS DISTINCT FROM OLD.allocator_id + OR NEW.last_source_fence <> OLD.last_source_fence + 1 + OR NEW.last_operation_id IS NULL + OR NEW.last_transaction_id IS DISTINCT FROM pg_current_xact_id()::text THEN + RAISE EXCEPTION 'Account auth-evidence source fence must advance exactly once in its capture transaction' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_source_fence_monotonic'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_gameplay_auth_evidence_source_fence_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account auth-evidence source fence allocator cannot be inserted, deleted, or truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_source_fence_immutable'; + RETURN OLD; +END; +$$; + +CREATE FUNCTION account_gameplay_auth_evidence_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM account_gameplay_delegation_auth_evidence_bundles) THEN + RAISE EXCEPTION 'Account auth-evidence bundles cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_immutable'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_gameplay_auth_evidence_insert + BEFORE INSERT ON account_gameplay_delegation_auth_evidence_bundles + FOR EACH ROW EXECUTE FUNCTION account_gameplay_auth_evidence_insert_guard(); +CREATE TRIGGER account_gameplay_auth_evidence_update_delete + BEFORE UPDATE OR DELETE ON account_gameplay_delegation_auth_evidence_bundles + FOR EACH ROW EXECUTE FUNCTION account_gameplay_auth_evidence_immutable_guard(); +CREATE TRIGGER account_gameplay_auth_evidence_truncate + BEFORE TRUNCATE ON account_gameplay_delegation_auth_evidence_bundles + FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_auth_evidence_no_truncate(); +CREATE TRIGGER account_gameplay_auth_evidence_source_fence_update + BEFORE UPDATE ON account_gameplay_auth_evidence_source_fence + FOR EACH ROW EXECUTE FUNCTION account_gameplay_auth_evidence_source_fence_update_guard(); +CREATE TRIGGER account_gameplay_auth_evidence_source_fence_insert_delete + BEFORE INSERT OR DELETE ON account_gameplay_auth_evidence_source_fence + FOR EACH ROW EXECUTE FUNCTION account_gameplay_auth_evidence_source_fence_immutable_guard(); +CREATE TRIGGER account_gameplay_auth_evidence_source_fence_truncate + BEFORE TRUNCATE ON account_gameplay_auth_evidence_source_fence + FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_auth_evidence_source_fence_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V47__account_gameplay_delegation_encrypted_response.sql b/services/account-service/src/main/resources/db/migration/V47__account_gameplay_delegation_encrypted_response.sql new file mode 100644 index 0000000000..c0f450fcc5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V47__account_gameplay_delegation_encrypted_response.sql @@ -0,0 +1,124 @@ +-- Exact compact delegation candidates are separately Account-encrypted and remain PENDING. +-- This table stores no plaintext JWT and introduces no COMMITTED/ACTIVE state or recovery API. +CREATE TABLE account_gameplay_delegation_response_envelopes ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + token_hash VARCHAR(64) NOT NULL, + signer_kid VARCHAR(64) NOT NULL, + signer_generation VARCHAR(19) NOT NULL, + authority_evidence_bundle_sha256 VARCHAR(64) NOT NULL, + issuance_fence BIGINT NOT NULL, + response_recovery_expiry_epoch_ms BIGINT NOT NULL, + envelope_sha256 VARCHAR(64) NOT NULL, + envelope_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_gameplay_delegation_response_candidate_check + CHECK (token_hash ~ '^[0-9a-f]{64}$' + AND signer_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND signer_generation ~ '^[1-9][0-9]{0,18}$'), + CONSTRAINT account_gameplay_delegation_response_evidence_check + CHECK (authority_evidence_bundle_sha256 ~ '^[0-9a-f]{64}$' + AND issuance_fence > 0), + CONSTRAINT account_gameplay_delegation_response_expiry_check + CHECK (response_recovery_expiry_epoch_ms > 0 + AND response_recovery_expiry_epoch_ms % 1000 = 0), + CONSTRAINT account_gameplay_delegation_response_hash_check + CHECK (envelope_sha256 ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_gameplay_delegation_response_size_check + CHECK (octet_length(envelope_bytes) BETWEEN 1 AND 65610), + CONSTRAINT account_gameplay_delegation_response_operation_fk + FOREIGN KEY (operation_id) + REFERENCES account_gameplay_delegation_issuance_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_gameplay_delegation_response_request_fk + FOREIGN KEY (request_id) + REFERENCES account_gameplay_delegation_issuance_operations(request_id) + ON DELETE RESTRICT +); + +-- The trigger binds only immutable ciphertext metadata to the exact PENDING operation and the +-- already-persisted owner bundle. Java additionally checks current locked generations, canonical +-- bytes, the transient JWT hash, and exact readback. Neither layer claims signature validity, +-- completed external postconditions, or permission to recover plaintext. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_delegation_response_envelope_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; + bundle_row RECORD; + bundle JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Account gameplay delegation response envelope is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_response_immutable'; + END IF; + + SELECT * INTO operation_row + FROM account_gameplay_delegation_issuance_operations + WHERE operation_id = NEW.operation_id + FOR UPDATE; + IF operation_row.operation_id IS NULL + OR operation_row.request_id <> NEW.request_id + OR operation_row.status <> 'PENDING' + OR operation_row.token_hash IS NULL + OR operation_row.token_hash <> NEW.token_hash + OR operation_row.signer_kid <> NEW.signer_kid + OR operation_row.signer_generation <> NEW.signer_generation + OR operation_row.issuance_fence <> NEW.issuance_fence + OR NEW.response_recovery_expiry_epoch_ms / 1000 <> operation_row.expires_at_epoch_second + OR NEW.response_recovery_expiry_epoch_ms % 1000 <> 0 THEN + RAISE EXCEPTION 'Account gameplay delegation response has no exact PENDING candidate' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_response_operation_match'; + END IF; + + SELECT request_id, account_uuid, bundle_schema, issuance_fence, canonical_sha256, + canonical_bundle_bytes + INTO bundle_row + FROM account_gameplay_delegation_auth_evidence_bundles + WHERE operation_id = NEW.operation_id; + IF bundle_row.request_id IS NULL + OR bundle_row.request_id <> NEW.request_id + OR bundle_row.account_uuid <> operation_row.account_uuid + OR bundle_row.bundle_schema <> 'account-auth-evidence-bundle/v1' + OR bundle_row.issuance_fence <> operation_row.issuance_fence::text + OR bundle_row.canonical_sha256 <> NEW.authority_evidence_bundle_sha256 + OR octet_length(bundle_row.canonical_bundle_bytes) > 8192 THEN + RAISE EXCEPTION 'Account gameplay delegation response has no exact owner evidence bundle' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_response_evidence_match'; + END IF; + bundle := convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb; + IF bundle->>'schema' IS DISTINCT FROM bundle_row.bundle_schema + OR bundle#>>'{operation,operationId}' IS DISTINCT FROM NEW.operation_id::text + OR bundle#>>'{operation,requestId}' IS DISTINCT FROM NEW.request_id::text + OR bundle#>>'{tokenIdentity,jti}' IS DISTINCT FROM operation_row.token_jti::text + OR bundle#>>'{operation,requestDigest}' IS DISTINCT FROM operation_row.request_digest + OR bundle->>'issuanceFence' IS DISTINCT FROM operation_row.issuance_fence::text THEN + RAISE EXCEPTION 'Account gameplay delegation response evidence does not match its operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_response_evidence_match'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_gameplay_delegation_response_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM account_gameplay_delegation_response_envelopes) THEN + RAISE EXCEPTION 'Account gameplay delegation response envelopes cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_response_immutable'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_gameplay_delegation_response_envelope_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_gameplay_delegation_response_envelopes + FOR EACH ROW EXECUTE FUNCTION account_gameplay_delegation_response_envelope_guard(); +CREATE TRIGGER account_gameplay_delegation_response_no_truncate + BEFORE TRUNCATE ON account_gameplay_delegation_response_envelopes + FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_delegation_response_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql b/services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql new file mode 100644 index 0000000000..33a320ae11 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql @@ -0,0 +1,569 @@ +-- Forward-only lifecycle extension for the existing Account-owned signer authority. The +-- generation operation remains immutable; one separate promotion operation binds it to the +-- authenticated Secret/JWKS/probe evidence and owns the PREPARED -> COMMITTED|ABORTED CAS. + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_action_check; + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_slots_check; + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_status_check; + +ALTER TABLE account_jwt_signer_promotion_operations + ADD COLUMN generation_operation_id UUID, + ADD COLUMN expected_cluster_incarnation_uid UUID, + ADD COLUMN expected_namespace_uid UUID, + ADD COLUMN materializer_trust_binding_digest VARCHAR(64), + ADD COLUMN materializer_trust_config_revision VARCHAR(128), + ADD COLUMN api_binding_digest VARCHAR(64), + ADD COLUMN api_config_revision VARCHAR(128), + ADD COLUMN expected_private_secret_uid UUID, + ADD COLUMN expected_public_config_map_uid UUID, + ADD COLUMN prepublication_intent_digest VARCHAR(64), + ADD COLUMN prepublication_receipt_digest VARCHAR(64), + ADD COLUMN mounted_observation_digest VARCHAR(64), + ADD COLUMN readiness_plan_digest VARCHAR(64), + ADD COLUMN readiness_evidence_digest VARCHAR(64), + ADD COLUMN expected_public_jwks_json TEXT, + ADD COLUMN expected_active_generation_marker_json TEXT, + ADD COLUMN private_promotion_observed_resource_version VARCHAR(256), + ADD COLUMN private_promotion_receipt_digest VARCHAR(64), + ADD COLUMN private_promotion_dispatched_at TIMESTAMPTZ, + ADD COLUMN active_jwks_observed_resource_version VARCHAR(256), + ADD COLUMN active_jwks_public_data_digest VARCHAR(64), + ADD COLUMN active_jwks_receipt_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_signer_promotion_generation_fk + FOREIGN KEY (generation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT, + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_action_check + CHECK ((operation_action = 'MATERIALIZE_PENDING' + AND allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea) + OR (operation_action = 'PROMOTE_PENDING' + AND allowed_private_slots_canonical_bytes = + '\x5b2263757272656e74222c2270656e64696e67222c2270726576696f7573225d'::bytea)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_status_check + CHECK (status IN ('PREPARED', 'COMMITTED', 'ABORTED')), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_identity_check + CHECK (operation_action <> 'PROMOTE_PENDING' + OR (generation_operation_id IS NOT NULL + AND expected_cluster_incarnation_uid IS NOT NULL + AND expected_namespace_uid IS NOT NULL + AND materializer_trust_binding_digest IS NOT NULL + AND materializer_trust_binding_digest ~ '^[0-9a-f]{64}$' + AND materializer_trust_config_revision IS NOT NULL + AND materializer_trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest IS NOT NULL + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND api_config_revision IS NOT NULL + AND api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND expected_private_secret_uid IS NOT NULL + AND expected_public_config_map_uid IS NOT NULL + AND prepublication_intent_digest IS NOT NULL + AND prepublication_intent_digest ~ '^[0-9a-f]{64}$' + AND prepublication_receipt_digest IS NOT NULL + AND prepublication_receipt_digest ~ '^[0-9a-f]{64}$' + AND mounted_observation_digest IS NOT NULL + AND mounted_observation_digest ~ '^[0-9a-f]{64}$' + AND readiness_plan_digest IS NOT NULL + AND readiness_plan_digest ~ '^[0-9a-f]{64}$' + AND readiness_evidence_digest IS NOT NULL + AND readiness_evidence_digest ~ '^[0-9a-f]{64}$' + AND expected_public_jwks_json IS NOT NULL + AND expected_active_generation_marker_json IS NOT NULL)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_uid_check + CHECK ((expected_cluster_incarnation_uid IS NULL + OR expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_namespace_uid IS NULL + OR expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_private_secret_uid IS NULL + OR expected_private_secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_public_config_map_uid IS NULL + OR expected_public_config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_digest_check + CHECK ((materializer_trust_binding_digest IS NULL + OR materializer_trust_binding_digest ~ '^[0-9a-f]{64}$') + AND (api_binding_digest IS NULL OR api_binding_digest ~ '^[0-9a-f]{64}$') + AND (prepublication_intent_digest IS NULL + OR prepublication_intent_digest ~ '^[0-9a-f]{64}$') + AND (prepublication_receipt_digest IS NULL + OR prepublication_receipt_digest ~ '^[0-9a-f]{64}$') + AND (mounted_observation_digest IS NULL + OR mounted_observation_digest ~ '^[0-9a-f]{64}$') + AND (readiness_plan_digest IS NULL + OR readiness_plan_digest ~ '^[0-9a-f]{64}$') + AND (readiness_evidence_digest IS NULL + OR readiness_evidence_digest ~ '^[0-9a-f]{64}$') + AND (private_promotion_receipt_digest IS NULL + OR private_promotion_receipt_digest ~ '^[0-9a-f]{64}$') + AND (active_jwks_public_data_digest IS NULL + OR active_jwks_public_data_digest ~ '^[0-9a-f]{64}$') + AND (active_jwks_receipt_digest IS NULL + OR active_jwks_receipt_digest ~ '^[0-9a-f]{64}$')), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_rv_check + CHECK ((private_promotion_observed_resource_version IS NULL + OR (private_promotion_observed_resource_version ~ '^[!-~]+$' + AND char_length(private_promotion_observed_resource_version) BETWEEN 1 AND 256)) + AND (active_jwks_observed_resource_version IS NULL + OR (active_jwks_observed_resource_version ~ '^[!-~]+$' + AND char_length(active_jwks_observed_resource_version) BETWEEN 1 AND 256))), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_content_check + CHECK ((expected_public_jwks_json IS NULL OR octet_length(expected_public_jwks_json) BETWEEN 1 AND 262144) + AND (expected_active_generation_marker_json IS NULL + OR octet_length(expected_active_generation_marker_json) BETWEEN 1 AND 16384)), + ADD CONSTRAINT account_jwt_signer_promotion_dispatch_check + CHECK ((private_promotion_receipt_digest IS NULL + OR private_promotion_dispatched_at IS NOT NULL) + AND (status <> 'COMMITTED' + OR (private_promotion_dispatched_at IS NOT NULL + AND private_promotion_receipt_digest IS NOT NULL + AND active_jwks_receipt_digest IS NOT NULL)) + AND (status <> 'ABORTED' + OR (private_promotion_dispatched_at IS NULL + AND private_promotion_receipt_digest IS NULL + AND active_jwks_receipt_digest IS NULL))); + +-- Enrollment is admitted only after both independently protected bindings and a live read of the +-- fixed pre-created public ConfigMap agree on the environment/cluster/namespace incarnation. +-- Existing rows with NULL pins are intentionally not backfilled or promoted. +ALTER TABLE account_jwt_signer_desired_states + ADD COLUMN enrollment_cluster_incarnation_uid UUID, + ADD COLUMN enrollment_namespace_uid UUID, + ADD COLUMN enrollment_materializer_binding_digest VARCHAR(64), + ADD COLUMN enrollment_materializer_config_revision VARCHAR(128), + ADD COLUMN enrollment_api_binding_digest VARCHAR(64), + ADD COLUMN enrollment_api_config_revision VARCHAR(128), + ADD COLUMN enrollment_public_config_map_uid UUID, + ADD COLUMN enrollment_public_config_map_resource_version VARCHAR(256), + ADD COLUMN enrollment_public_config_map_snapshot_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_signer_enrollment_shape_check + CHECK ((enrollment_cluster_incarnation_uid IS NULL + AND enrollment_namespace_uid IS NULL + AND enrollment_materializer_binding_digest IS NULL + AND enrollment_materializer_config_revision IS NULL + AND enrollment_api_binding_digest IS NULL + AND enrollment_api_config_revision IS NULL + AND enrollment_public_config_map_uid IS NULL + AND enrollment_public_config_map_resource_version IS NULL + AND enrollment_public_config_map_snapshot_digest IS NULL) + OR (enrollment_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_cluster_incarnation_uid IS NOT NULL + AND enrollment_namespace_uid IS NOT NULL + AND enrollment_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_materializer_binding_digest IS NOT NULL + AND enrollment_materializer_binding_digest ~ '^[0-9a-f]{64}$' + AND enrollment_materializer_config_revision IS NOT NULL + AND enrollment_materializer_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND enrollment_api_binding_digest IS NOT NULL + AND enrollment_api_binding_digest ~ '^[0-9a-f]{64}$' + AND enrollment_api_config_revision IS NOT NULL + AND enrollment_api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND enrollment_public_config_map_uid IS NOT NULL + AND enrollment_public_config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_public_config_map_resource_version IS NOT NULL + AND enrollment_public_config_map_resource_version ~ '^[!-~]+$' + AND char_length(enrollment_public_config_map_resource_version) BETWEEN 1 AND 256 + AND enrollment_public_config_map_snapshot_digest IS NOT NULL + AND enrollment_public_config_map_snapshot_digest ~ '^[0-9a-f]{64}$')); + +-- PREPARED proof is immutable. Account first durably records its one-way peer dispatch before +-- returning mutation authority. Only the two exact public-only CAS receipts may then be filled +-- once, followed by one terminal state transition. No receipt includes, hashes, or returns +-- private Secret bytes. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_signer_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + private_receipt_changed BOOLEAN; + private_dispatch_changed BOOLEAN; + jwks_receipt_changed BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer promotion history cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF (NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, NEW.request_digest_version, NEW.request_digest, + NEW.expected_record_version, NEW.expected_previous_generation, NEW.expected_previous_kid, + NEW.target_generation, NEW.target_kid, NEW.target_algorithm, + NEW.target_public_key_fingerprint, NEW.expected_private_secret_resource_version, + NEW.expected_public_jwks_resource_version, NEW.expected_public_active_generation, + NEW.expected_public_active_kid, NEW.operation_action, + NEW.allowed_private_slots_canonical_bytes, NEW.generation_operation_id, + NEW.expected_cluster_incarnation_uid, NEW.expected_namespace_uid, + NEW.materializer_trust_binding_digest, NEW.materializer_trust_config_revision, + NEW.api_binding_digest, NEW.api_config_revision, NEW.expected_private_secret_uid, + NEW.expected_public_config_map_uid, NEW.prepublication_intent_digest, + NEW.prepublication_receipt_digest, NEW.mounted_observation_digest, + NEW.readiness_plan_digest, NEW.readiness_evidence_digest, + NEW.expected_public_jwks_json, NEW.expected_active_generation_marker_json, + NEW.created_at) + IS DISTINCT FROM + (OLD.operation_id, OLD.environment_id, OLD.cluster_id, OLD.kubernetes_namespace, + OLD.custody_mode, OLD.request_digest_version, OLD.request_digest, + OLD.expected_record_version, OLD.expected_previous_generation, OLD.expected_previous_kid, + OLD.target_generation, OLD.target_kid, OLD.target_algorithm, + OLD.target_public_key_fingerprint, OLD.expected_private_secret_resource_version, + OLD.expected_public_jwks_resource_version, OLD.expected_public_active_generation, + OLD.expected_public_active_kid, OLD.operation_action, + OLD.allowed_private_slots_canonical_bytes, OLD.generation_operation_id, + OLD.expected_cluster_incarnation_uid, OLD.expected_namespace_uid, + OLD.materializer_trust_binding_digest, OLD.materializer_trust_config_revision, + OLD.api_binding_digest, OLD.api_config_revision, OLD.expected_private_secret_uid, + OLD.expected_public_config_map_uid, OLD.prepublication_intent_digest, + OLD.prepublication_receipt_digest, OLD.mounted_observation_digest, + OLD.readiness_plan_digest, OLD.readiness_evidence_digest, + OLD.expected_public_jwks_json, OLD.expected_active_generation_marker_json, + OLD.created_at) THEN + RAISE EXCEPTION 'Account JWT signer promotion request is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF OLD.status <> 'PREPARED' OR NEW.status NOT IN ('PREPARED', 'COMMITTED', 'ABORTED') THEN + RAISE EXCEPTION 'Account JWT signer promotion is already terminal' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + + private_receipt_changed := + (NEW.private_promotion_observed_resource_version, + NEW.private_promotion_receipt_digest) + IS DISTINCT FROM + (OLD.private_promotion_observed_resource_version, + OLD.private_promotion_receipt_digest); + private_dispatch_changed := + NEW.private_promotion_dispatched_at IS DISTINCT FROM OLD.private_promotion_dispatched_at; + jwks_receipt_changed := + (NEW.active_jwks_observed_resource_version, NEW.active_jwks_public_data_digest, + NEW.active_jwks_receipt_digest) + IS DISTINCT FROM + (OLD.active_jwks_observed_resource_version, OLD.active_jwks_public_data_digest, + OLD.active_jwks_receipt_digest); + + IF private_receipt_changed THEN + IF OLD.private_promotion_receipt_digest IS NOT NULL + OR NEW.private_promotion_receipt_digest IS NULL + OR NEW.private_promotion_observed_resource_version IS NULL + OR jwks_receipt_changed OR NEW.status <> 'PREPARED' THEN + RAISE EXCEPTION 'JWT private promotion receipt is not a first exact readback' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF private_dispatch_changed THEN + IF OLD.private_promotion_dispatched_at IS NOT NULL + OR NEW.private_promotion_dispatched_at IS NULL + OR NEW.status <> 'PREPARED' + OR private_receipt_changed OR jwks_receipt_changed THEN + RAISE EXCEPTION 'JWT private promotion dispatch is not a first durable authorization' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF jwks_receipt_changed THEN + IF OLD.active_jwks_receipt_digest IS NOT NULL + OR NEW.active_jwks_receipt_digest IS NULL + OR NEW.active_jwks_observed_resource_version IS NULL + OR NEW.active_jwks_public_data_digest IS NULL + OR OLD.private_promotion_receipt_digest IS NULL + OR NEW.status <> 'PREPARED' THEN + RAISE EXCEPTION 'JWT active JWKS receipt is not a first exact readback' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF NEW.status = OLD.status AND NOT private_dispatch_changed + AND NOT private_receipt_changed AND NOT jwks_receipt_changed THEN + RAISE EXCEPTION 'JWT promotion update has no exact receipt transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF NEW.status = 'COMMITTED' + AND (NEW.private_promotion_dispatched_at IS NULL + OR NEW.private_promotion_receipt_digest IS NULL + OR NEW.active_jwks_receipt_digest IS NULL) THEN + RAISE EXCEPTION 'JWT promotion cannot commit without both exact resource receipts' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF NEW.status = 'ABORTED' + AND (OLD.private_promotion_dispatched_at IS NOT NULL + OR OLD.private_promotion_receipt_digest IS NOT NULL + OR OLD.active_jwks_receipt_digest IS NOT NULL) THEN + RAISE EXCEPTION 'Dispatched JWT promotion must remain PREPARED for reconciliation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_jwt_signer_desired_state_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer desired state cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + IF (NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode, + NEW.private_secret_name, NEW.public_jwks_config_map_name, NEW.created_at, + NEW.enrollment_cluster_incarnation_uid, NEW.enrollment_namespace_uid, + NEW.enrollment_materializer_binding_digest, NEW.enrollment_materializer_config_revision, + NEW.enrollment_api_binding_digest, NEW.enrollment_api_config_revision, + NEW.enrollment_public_config_map_uid, NEW.enrollment_public_config_map_resource_version, + NEW.enrollment_public_config_map_snapshot_digest) + IS DISTINCT FROM + (OLD.environment_id, OLD.cluster_id, OLD.kubernetes_namespace, OLD.custody_mode, + OLD.private_secret_name, OLD.public_jwks_config_map_name, OLD.created_at, + OLD.enrollment_cluster_incarnation_uid, OLD.enrollment_namespace_uid, + OLD.enrollment_materializer_binding_digest, OLD.enrollment_materializer_config_revision, + OLD.enrollment_api_binding_digest, OLD.enrollment_api_config_revision, + OLD.enrollment_public_config_map_uid, OLD.enrollment_public_config_map_resource_version, + OLD.enrollment_public_config_map_snapshot_digest) + OR NEW.record_version <> OLD.record_version + 1 THEN + RAISE EXCEPTION 'Account JWT signer desired state permits only a versioned owner transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + -- Creating a generation operation is the only transition from an idle state to a new key + -- request. Active identities and publication fences remain unchanged. + IF OLD.generation_operation_id IS NULL AND OLD.prepared_operation_id IS NULL + AND NEW.generation_operation_id IS NOT NULL AND NEW.prepared_operation_id IS NULL + AND NEW.durable_active_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND NEW.durable_active_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND NEW.published_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND NEW.published_active_kid IS NOT DISTINCT FROM OLD.published_active_kid THEN + IF OLD.enrollment_cluster_incarnation_uid IS NULL + OR OLD.enrollment_namespace_uid IS NULL + OR OLD.enrollment_materializer_binding_digest IS NULL + OR OLD.enrollment_api_binding_digest IS NULL + OR OLD.enrollment_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'JWT signer state has no independently protected enrollment pins' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + PERFORM 1 FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.generation_operation_id + AND generation_op.environment_id = NEW.environment_id + AND generation_op.cluster_id = NEW.cluster_id + AND generation_op.kubernetes_namespace = NEW.kubernetes_namespace + AND generation_op.custody_mode = NEW.custody_mode + AND generation_op.expected_record_version = OLD.record_version + AND generation_op.expected_previous_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND generation_op.expected_previous_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND generation_op.expected_published_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND generation_op.expected_published_kid IS NOT DISTINCT FROM OLD.published_active_kid; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT generation pointer is not the exact current Account operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + RETURN NEW; + END IF; + + -- Enter PREPARED only after insertion of the exact durable promotion request. + IF OLD.generation_operation_id IS NOT NULL AND OLD.prepared_operation_id IS NULL + AND NEW.generation_operation_id IS NULL AND NEW.prepared_operation_id IS NOT NULL + AND NEW.durable_active_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND NEW.durable_active_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND NEW.published_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND NEW.published_active_kid IS NOT DISTINCT FROM OLD.published_active_kid THEN + SELECT promotion.* INTO operation_row + FROM account_jwt_signer_promotion_operations AS promotion + WHERE promotion.operation_id = NEW.prepared_operation_id + AND promotion.generation_operation_id = OLD.generation_operation_id + AND promotion.environment_id = OLD.environment_id + AND promotion.cluster_id = OLD.cluster_id + AND promotion.kubernetes_namespace = OLD.kubernetes_namespace + AND promotion.custody_mode = OLD.custody_mode + AND promotion.expected_record_version = OLD.record_version + AND promotion.expected_previous_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND promotion.expected_previous_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND promotion.expected_public_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND promotion.expected_public_active_kid IS NOT DISTINCT FROM OLD.published_active_kid + AND promotion.status = 'PREPARED' + AND promotion.operation_action = 'PROMOTE_PENDING'; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT PREPARED pointer is not the exact Account promotion operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + RETURN NEW; + END IF; + + -- Close only the exact PREPARED operation. COMMITTED changes both active fences to target; + -- ABORTED preserves both previous fences. No resource observation can perform either CAS. + IF OLD.generation_operation_id IS NULL AND OLD.prepared_operation_id IS NOT NULL + AND NEW.generation_operation_id IS NULL AND NEW.prepared_operation_id IS NULL THEN + SELECT promotion.* INTO operation_row + FROM account_jwt_signer_promotion_operations AS promotion + WHERE promotion.operation_id = OLD.prepared_operation_id + AND promotion.environment_id = OLD.environment_id + AND promotion.cluster_id = OLD.cluster_id + AND promotion.kubernetes_namespace = OLD.kubernetes_namespace + AND promotion.custody_mode = OLD.custody_mode + AND promotion.expected_record_version + 1 = OLD.record_version + AND promotion.status IN ('COMMITTED', 'ABORTED'); + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT promotion terminal transition has no exact durable result' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + IF operation_row.status = 'COMMITTED' THEN + IF NEW.durable_active_generation IS DISTINCT FROM operation_row.target_generation + OR NEW.durable_active_kid IS DISTINCT FROM operation_row.target_kid + OR NEW.published_active_generation IS DISTINCT FROM operation_row.target_generation + OR NEW.published_active_kid IS DISTINCT FROM operation_row.target_kid THEN + RAISE EXCEPTION 'Committed JWT signer and published active fences must equal target' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + ELSIF NEW.durable_active_generation IS DISTINCT FROM OLD.durable_active_generation + OR NEW.durable_active_kid IS DISTINCT FROM OLD.durable_active_kid + OR NEW.published_active_generation IS DISTINCT FROM OLD.published_active_generation + OR NEW.published_active_kid IS DISTINCT FROM OLD.published_active_kid THEN + RAISE EXCEPTION 'Aborted JWT signer operation must preserve previous active fences' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + RETURN NEW; + END IF; + + RAISE EXCEPTION 'Account JWT signer state transition is not in the lifecycle CAS' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; +END; +$$; + +CREATE FUNCTION account_jwt_signer_promotion_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_row RECORD; + generation_row RECORD; + result_row RECORD; + plan_inventory_complete BOOLEAN; + plan_expires_at BIGINT; + entry_count BIGINT; + verified_count BIGINT; +BEGIN + IF NEW.operation_action <> 'PROMOTE_PENDING' + OR NEW.generation_operation_id IS NULL + OR NEW.expected_cluster_incarnation_uid IS NULL + OR NEW.expected_namespace_uid IS NULL + OR NEW.expected_private_secret_uid IS NULL + OR NEW.expected_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'Promotion request lacks its exact lifecycle binding' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + -- Lock order is desired state, then source generation, then immutable evidence. + SELECT * INTO state_row FROM account_jwt_signer_desired_states + WHERE environment_id = NEW.environment_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT signer desired state is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO generation_row FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation operation is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO result_row FROM account_jwt_signer_generation_results + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation result is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + IF state_row.generation_operation_id IS DISTINCT FROM NEW.generation_operation_id + OR state_row.prepared_operation_id IS NOT NULL + OR state_row.record_version IS DISTINCT FROM NEW.expected_record_version + OR (state_row.cluster_id, state_row.kubernetes_namespace, state_row.custody_mode) + IS DISTINCT FROM (NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode) + OR (state_row.durable_active_generation, state_row.durable_active_kid) + IS DISTINCT FROM (NEW.expected_previous_generation, NEW.expected_previous_kid) + OR (state_row.published_active_generation, state_row.published_active_kid) + IS DISTINCT FROM (NEW.expected_public_active_generation, NEW.expected_public_active_kid) + OR state_row.enrollment_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR state_row.enrollment_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR state_row.enrollment_materializer_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR state_row.enrollment_materializer_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR state_row.enrollment_api_binding_digest IS DISTINCT FROM NEW.api_binding_digest + OR state_row.enrollment_api_config_revision IS DISTINCT FROM NEW.api_config_revision + OR state_row.enrollment_public_config_map_uid IS DISTINCT FROM NEW.expected_public_config_map_uid + OR generation_row.operation_id IS NULL + OR generation_row.environment_id IS DISTINCT FROM NEW.environment_id + OR generation_row.expected_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR generation_row.expected_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR generation_row.trust_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR generation_row.trust_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR generation_row.target_generation IS DISTINCT FROM NEW.target_generation + OR generation_row.target_kid IS DISTINCT FROM NEW.target_kid + OR generation_row.expected_record_version + 1 IS DISTINCT FROM result_row.desired_state_version + OR result_row.secret_uid IS DISTINCT FROM NEW.expected_private_secret_uid + OR result_row.observed_resource_version IS DISTINCT FROM NEW.expected_private_secret_resource_version + OR result_row.receipt_digest IS DISTINCT FROM NEW.generation_receipt_digest + OR result_row.public_key_fingerprint IS DISTINCT FROM NEW.target_public_key_fingerprint THEN + RAISE EXCEPTION 'JWT promotion request does not match current Account generation evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + SELECT validator_inventory_complete, expires_at_epoch_seconds + INTO plan_inventory_complete, plan_expires_at + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest FOR SHARE; + IF plan_inventory_complete IS DISTINCT FROM TRUE + OR plan_expires_at IS NULL + OR plan_expires_at <= floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT THEN + RAISE EXCEPTION 'JWT promotion requires current complete validator inventory proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + SELECT count(*), count(*) FILTER (WHERE state = 'VERIFIED' + AND verified_at_epoch_seconds < expires_at_epoch_seconds) + INTO entry_count, verified_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest; + IF entry_count = 0 OR verified_count <> entry_count THEN + RAISE EXCEPTION 'JWT promotion requires every exact readiness probe to be VERIFIED' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + + IF NOT EXISTS ( + SELECT 1 FROM account_jwt_jwks_prepublication_intents AS intent + JOIN account_jwt_jwks_publication_receipts AS receipt + ON receipt.operation_id = intent.operation_id + AND receipt.intent_digest = intent.intent_digest + JOIN account_jwt_jwks_mount_observations AS mount + ON mount.operation_id = intent.operation_id + WHERE intent.operation_id = NEW.generation_operation_id + AND intent.intent_digest = NEW.prepublication_intent_digest + AND receipt.receipt_digest = NEW.prepublication_receipt_digest + AND mount.observation_digest = NEW.mounted_observation_digest + AND intent.config_map_uid = NEW.expected_public_config_map_uid + AND intent.api_binding_digest = NEW.api_binding_digest + AND intent.api_config_revision = NEW.api_config_revision + AND receipt.observed_resource_version = NEW.expected_public_jwks_resource_version + AND intent.public_key_fingerprint = NEW.target_public_key_fingerprint + AND intent.jwks_json = NEW.expected_public_jwks_json) THEN + RAISE EXCEPTION 'JWT promotion request does not match exact current prepublication evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_signer_promotion_insert_guard + BEFORE INSERT ON account_jwt_signer_promotion_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_promotion_insert_guard(); + +CREATE FUNCTION account_jwt_signer_promotion_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer promotion history cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; +CREATE TRIGGER account_jwt_signer_promotion_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_promotion_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_promotion_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql b/services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql new file mode 100644 index 0000000000..65c13414a5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql @@ -0,0 +1,125 @@ +-- One durable winner may emit the exact current operation's readiness probes to its authenticated +-- harness. A claim is a one-shot concurrency fence, not delivery proof, validator evidence, or +-- signer authority; it is never cleared after an ambiguous response. +CREATE TABLE account_jwt_readiness_delivery_claims ( + rotation_operation_id UUID PRIMARY KEY, + plan_digest VARCHAR(64) NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + materializer_trust_binding_digest VARCHAR(64) NOT NULL, + materializer_trust_config_revision VARCHAR(128) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + readiness_binding_digest VARCHAR(64) NOT NULL, + readiness_config_revision VARCHAR(128) NOT NULL, + readiness_binding_valid_until_epoch_seconds BIGINT NOT NULL, + validator_id VARCHAR(63) NOT NULL, + validator_instance_id VARCHAR(128) NOT NULL, + validator_peer_uri VARCHAR(256) NOT NULL, + validator_peer_spki_sha256 VARCHAR(64) NOT NULL, + claimed_at_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + claim_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_readiness_delivery_claim_plan_fk + FOREIGN KEY (rotation_operation_id, plan_digest) + REFERENCES account_jwt_readiness_probe_plans(rotation_operation_id, plan_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_delivery_claim_shape_check + CHECK (rotation_operation_id::text ~ + '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND materializer_trust_binding_digest ~ '^[0-9a-f]{64}$' + AND materializer_trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid + AND readiness_binding_digest ~ '^[0-9a-f]{64}$' + AND readiness_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND readiness_binding_valid_until_epoch_seconds > claimed_at_epoch_seconds + AND validator_id = 'account-service' + AND validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness$' + AND validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$' + AND claimed_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > claimed_at_epoch_seconds + AND claim_digest ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_readiness_delivery_claim_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + expected_entry_count integer; + actual_entry_count integer; +BEGIN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.expected_cluster_incarnation_uid IS DISTINCT FROM plan_row.expected_cluster_incarnation_uid + OR NEW.expected_namespace_uid IS DISTINCT FROM plan_row.expected_namespace_uid + OR NEW.materializer_trust_binding_digest IS DISTINCT FROM plan_row.trust_binding_digest + OR NEW.materializer_trust_config_revision IS DISTINCT FROM plan_row.trust_config_revision + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds + OR NEW.validator_id <> 'account-service' + OR NEW.readiness_binding_valid_until_epoch_seconds <= NEW.claimed_at_epoch_seconds + OR NEW.validator_peer_uri IS DISTINCT FROM + 'spiffe://firemud/ns/' || plan_row.kubernetes_namespace || '/sa/account-jwt-readiness-harness' + OR NEW.claimed_at_epoch_seconds < plan_row.not_before_epoch_seconds + OR NEW.claimed_at_epoch_seconds >= plan_row.expires_at_epoch_seconds + OR CURRENT_TIMESTAMP < to_timestamp(plan_row.not_before_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(plan_row.expires_at_epoch_seconds) THEN + RAISE EXCEPTION 'Account readiness delivery claim differs from its current exact plan' + USING ERRCODE = '23514'; + END IF; + expected_entry_count := + 1 + jsonb_array_length(plan_row.applicability_matrix_json::jsonb #> + '{validators,0,applicableProfiles}'); + SELECT COUNT(*) INTO actual_entry_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest + AND state = 'PLANNED' + AND compact_token_sha256 IS NULL + AND signing_attempted_at_epoch_seconds IS NULL + AND verification_receipt_sha256 IS NULL; + IF actual_entry_count <> expected_entry_count THEN + RAISE EXCEPTION 'Account readiness delivery claim requires untouched planned entries' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_delivery_claim_insert_guard + BEFORE INSERT ON account_jwt_readiness_delivery_claims + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_delivery_claim_guard(); + +CREATE FUNCTION account_jwt_readiness_delivery_claim_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT readiness delivery claims are immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_delivery_claim_immutable + BEFORE UPDATE OR DELETE ON account_jwt_readiness_delivery_claims + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_delivery_claim_immutable_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V51__account_gameplay_delegation_committed_issuance.sql b/services/account-service/src/main/resources/db/migration/V51__account_gameplay_delegation_committed_issuance.sql new file mode 100644 index 0000000000..22f833342c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V51__account_gameplay_delegation_committed_issuance.sql @@ -0,0 +1,352 @@ +-- A signed candidate becomes durably COMMITTED only after Account has verified the signer-owned +-- candidate proof, exact pinned Coordination Redis receipt, current authority projection and +-- current source/evidence rows. COMMITTED remains non-authorizing; this migration adds no active +-- registry state or token recovery surface. +ALTER TABLE account_gameplay_delegation_issuance_operations + DROP CONSTRAINT account_gameplay_delegation_status_check; + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD COLUMN commit_proof_version SMALLINT, + ADD COLUMN commit_proof_sha256 VARCHAR(64), + ADD COLUMN commit_proof_canonical_bytes BYTEA, + ADD COLUMN committed_at TIMESTAMPTZ; + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD CONSTRAINT account_gameplay_delegation_status_check + CHECK (status IN ('PENDING', 'COMMITTED')); + +-- [jooq ignore start] +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD CONSTRAINT account_gameplay_delegation_commit_proof_check + CHECK ( + (status = 'PENDING' + AND commit_proof_version IS NULL + AND commit_proof_sha256 IS NULL + AND commit_proof_canonical_bytes IS NULL + AND committed_at IS NULL) + OR + (status = 'COMMITTED' + AND commit_proof_version IS NOT NULL + AND commit_proof_version = 1 + AND commit_proof_sha256 IS NOT NULL + AND commit_proof_sha256 ~ '^[0-9a-f]{64}$' + AND commit_proof_canonical_bytes IS NOT NULL + AND octet_length(commit_proof_canonical_bytes) BETWEEN 1 AND 32768 + AND committed_at IS NOT NULL + AND jsonb_typeof(convert_from(commit_proof_canonical_bytes, 'UTF8')::jsonb) = 'object' + AND (convert_from(commit_proof_canonical_bytes, 'UTF8')::jsonb) ?& ARRAY[ + 'schema', 'identity', 'tokenSha256', 'registryRecordSha256', + 'registry', 'bundle', 'authority', 'signer', 'envelope'] + AND convert_from(commit_proof_canonical_bytes, 'UTF8')::jsonb->>'schema' = + 'account-game-session-delegation-commit-proof/v1') + ); +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_delegation_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + proof JSONB; + bundle_row RECORD; + envelope_row RECORD; + identity_proof JSONB; + registry JSONB; + bundle JSONB; + authority JSONB; + signer JSONB; + envelope JSONB; + proof_key_count INTEGER; + identity_key_count INTEGER; + registry_key_count INTEGER; + bundle_key_count INTEGER; + authority_key_count INTEGER; + signer_key_count INTEGER; + envelope_key_count INTEGER; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status IS DISTINCT FROM 'PENDING' + OR NEW.token_hash IS NOT NULL + OR NEW.signer_kid IS NOT NULL + OR NEW.signer_generation IS NOT NULL + OR NEW.pending_registry_candidate_bytes IS NOT NULL + OR NEW.commit_proof_version IS NOT NULL + OR NEW.commit_proof_sha256 IS NOT NULL + OR NEW.commit_proof_canonical_bytes IS NOT NULL + OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Account gameplay delegation issuance must begin as unbound PENDING intent' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_initial_pending_only'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account gameplay delegation issuance evidence cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + + IF NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.caller_workload IS DISTINCT FROM OLD.caller_workload + OR NEW.caller_context_id IS DISTINCT FROM OLD.caller_context_id + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.token_jti IS DISTINCT FROM OLD.token_jti + OR NEW.token_generation IS DISTINCT FROM OLD.token_generation + OR NEW.issued_at_epoch_second IS DISTINCT FROM OLD.issued_at_epoch_second + OR NEW.not_before_epoch_second IS DISTINCT FROM OLD.not_before_epoch_second + OR NEW.expires_at_epoch_second IS DISTINCT FROM OLD.expires_at_epoch_second + OR NEW.authority_issuer_generation IS DISTINCT FROM OLD.authority_issuer_generation + OR NEW.authority_issuer_source_version IS DISTINCT FROM OLD.authority_issuer_source_version + OR NEW.authority_account_generation IS DISTINCT FROM OLD.authority_account_generation + OR NEW.authority_account_source_version IS DISTINCT FROM OLD.authority_account_source_version + OR NEW.issuance_fence IS DISTINCT FROM OLD.issuance_fence + OR NEW.issuance_fence_source_version IS DISTINCT FROM OLD.issuance_fence_source_version + OR NEW.authority_tuple_canonical_bytes IS DISTINCT FROM OLD.authority_tuple_canonical_bytes + OR NEW.membership_version_canonical_bytes IS DISTINCT FROM OLD.membership_version_canonical_bytes + OR NEW.authority_source_versions_canonical_bytes IS DISTINCT FROM OLD.authority_source_versions_canonical_bytes + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Account gameplay delegation intent is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + + IF OLD.status = 'COMMITTED' + OR OLD.commit_proof_version IS NOT NULL + OR OLD.commit_proof_sha256 IS NOT NULL + OR OLD.commit_proof_canonical_bytes IS NOT NULL + OR OLD.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Account gameplay delegation commit evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_immutable'; + END IF; + + IF NEW.status = 'PENDING' THEN + IF NEW.commit_proof_version IS NOT NULL + OR NEW.commit_proof_sha256 IS NOT NULL + OR NEW.commit_proof_canonical_bytes IS NOT NULL + OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Pending issuance cannot carry commit proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + IF OLD.token_hash IS NOT NULL OR OLD.signer_kid IS NOT NULL + OR OLD.signer_generation IS NOT NULL OR OLD.pending_registry_candidate_bytes IS NOT NULL + OR NEW.token_hash IS NULL OR NEW.signer_kid IS NULL + OR NEW.signer_generation IS NULL OR NEW.pending_registry_candidate_bytes IS NULL THEN + RAISE EXCEPTION 'Account gameplay delegation token identity may be bound exactly once' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_candidate_one_way'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status IS DISTINCT FROM 'COMMITTED' OR OLD.status IS DISTINCT FROM 'PENDING' + OR OLD.token_hash IS NULL OR OLD.signer_kid IS NULL + OR OLD.signer_generation IS NULL OR OLD.pending_registry_candidate_bytes IS NULL + OR NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.signer_kid IS DISTINCT FROM OLD.signer_kid + OR NEW.signer_generation IS DISTINCT FROM OLD.signer_generation + OR NEW.pending_registry_candidate_bytes IS DISTINCT FROM OLD.pending_registry_candidate_bytes + OR NEW.commit_proof_version IS DISTINCT FROM 1 + OR NEW.commit_proof_sha256 IS NULL + OR NEW.commit_proof_sha256 !~ '^[0-9a-f]{64}$' + OR NEW.commit_proof_canonical_bytes IS NULL + OR NEW.committed_at IS NULL THEN + RAISE EXCEPTION 'Account gameplay delegation COMMITTED transition is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + + proof := convert_from(NEW.commit_proof_canonical_bytes, 'UTF8')::jsonb; + IF jsonb_typeof(proof) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof is not a canonical object' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + SELECT count(*) INTO proof_key_count FROM jsonb_object_keys(proof); + IF proof_key_count <> 9 THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has unknown or missing fields' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + + identity_proof := proof->'identity'; + registry := proof->'registry'; + bundle := proof->'bundle'; + authority := proof->'authority'; + signer := proof->'signer'; + envelope := proof->'envelope'; + + IF jsonb_typeof(identity_proof) IS DISTINCT FROM 'object' + OR jsonb_typeof(registry) IS DISTINCT FROM 'object' + OR jsonb_typeof(bundle) IS DISTINCT FROM 'object' + OR jsonb_typeof(authority) IS DISTINCT FROM 'object' + OR jsonb_typeof(signer) IS DISTINCT FROM 'object' + OR jsonb_typeof(envelope) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof fields must be objects' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + SELECT count(*) INTO identity_key_count FROM jsonb_object_keys(identity_proof); + SELECT count(*) INTO registry_key_count FROM jsonb_object_keys(registry); + SELECT count(*) INTO bundle_key_count FROM jsonb_object_keys(bundle); + SELECT count(*) INTO authority_key_count FROM jsonb_object_keys(authority); + SELECT count(*) INTO signer_key_count FROM jsonb_object_keys(signer); + SELECT count(*) INTO envelope_key_count FROM jsonb_object_keys(envelope); + + IF identity_key_count <> 12 + OR NOT (identity_proof ?& ARRAY[ + 'operationId', 'requestId', 'accountId', 'requestDigest', 'callerWorkload', + 'callerContextId', 'tokenJti', 'tokenGeneration', 'issuedAtEpochSecond', + 'notBeforeEpochSecond', 'expiresAtEpochSecond', 'tokenSha256']) + OR registry_key_count <> 16 + OR NOT (registry ?& ARRAY[ + 'state', 'registryVersion', 'tokenKey', 'tokenHash', 'kid', 'signerGeneration', + 'operationId', 'requestId', 'requestDigest', 'absoluteExpiryMillis', + 'localAofCount', 'replicaAofCount', 'outcome', 'canonicalRecordSha256', + 'evidenceBundleSha256', 'aclIdentity']) + OR bundle_key_count <> 4 + OR NOT (bundle ?& ARRAY['bundleVersion', 'sourceVersion', 'linearization', 'canonicalSha256']) + OR authority_key_count <> 12 + OR NOT (authority ?& ARRAY[ + 'issuerGeneration', 'issuerSourceVersion', 'accountGeneration', + 'accountSourceVersion', 'issuanceFence', 'issuanceFenceSourceVersion', + 'authorityTuple', 'authoritySourceVersions', 'issuerProjectionGeneration', + 'accountProjectionGeneration', 'issuerProjectionSha256', 'accountProjectionSha256']) + OR signer_key_count <> 7 + OR NOT (signer ?& ARRAY[ + 'promotionStatus', 'promotionOperationId', 'generationOperationId', + 'targetKid', 'targetGeneration', 'correspondenceSha256', 'correspondence']) + OR envelope_key_count <> 10 + OR NOT (envelope ?& ARRAY[ + 'operationId', 'requestId', 'tokenHash', 'kid', 'signerGeneration', + 'authorityEvidenceBundleSha256', 'issuanceFence', + 'responseRecoveryExpiryEpochMillis', 'envelopeSha256', 'envelopeBytesLength']) + OR proof->>'tokenSha256' IS DISTINCT FROM NEW.token_hash + OR proof->>'registryRecordSha256' IS DISTINCT FROM registry->>'canonicalRecordSha256' + OR identity_proof->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR identity_proof->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR identity_proof->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR identity_proof->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR identity_proof->>'callerWorkload' IS DISTINCT FROM NEW.caller_workload + OR identity_proof->>'callerContextId' IS DISTINCT FROM NEW.caller_context_id::TEXT + OR identity_proof->>'tokenJti' IS DISTINCT FROM NEW.token_jti::TEXT + OR identity_proof->>'tokenGeneration' IS DISTINCT FROM NEW.token_generation::TEXT + OR identity_proof->>'issuedAtEpochSecond' IS DISTINCT FROM NEW.issued_at_epoch_second::TEXT + OR identity_proof->>'notBeforeEpochSecond' IS DISTINCT FROM NEW.not_before_epoch_second::TEXT + OR identity_proof->>'expiresAtEpochSecond' IS DISTINCT FROM NEW.expires_at_epoch_second::TEXT + OR identity_proof->>'tokenSha256' IS DISTINCT FROM NEW.token_hash + OR registry->>'state' IS DISTINCT FROM 'pending' + OR registry->>'registryVersion' IS DISTINCT FROM '1' + OR registry->>'tokenKey' IS DISTINCT FROM ('session:auth:token:' || NEW.token_hash) + OR registry->>'tokenHash' IS DISTINCT FROM NEW.token_hash + OR registry->>'kid' IS DISTINCT FROM NEW.signer_kid + OR registry->>'signerGeneration' IS DISTINCT FROM NEW.signer_generation + OR registry->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR registry->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR registry->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR registry->>'aclIdentity' IS DISTINCT FROM 'account_coord_app' + OR registry->>'absoluteExpiryMillis' IS NULL + OR registry->>'absoluteExpiryMillis' !~ '^[1-9][0-9]{0,18}$' + OR registry->>'localAofCount' IS NULL + OR registry->>'localAofCount' !~ '^[1-9][0-9]{0,3}$' + OR registry->>'replicaAofCount' IS NULL + OR registry->>'replicaAofCount' !~ '^[1-9][0-9]{0,3}$' + OR registry->>'outcome' IS NULL + OR registry->>'outcome' NOT IN ('CREATED', 'EXACT_RETRY') + OR registry->>'canonicalRecordSha256' IS NULL + OR registry->>'canonicalRecordSha256' !~ '^[0-9a-f]{64}$' + OR registry->>'evidenceBundleSha256' IS DISTINCT FROM bundle->>'canonicalSha256' + OR bundle->>'canonicalSha256' IS NULL + OR bundle->>'canonicalSha256' !~ '^[0-9a-f]{64}$' + OR authority->>'issuerGeneration' IS DISTINCT FROM NEW.authority_issuer_generation::TEXT + OR authority->>'issuerSourceVersion' IS DISTINCT FROM NEW.authority_issuer_source_version::TEXT + OR authority->>'accountGeneration' IS DISTINCT FROM NEW.authority_account_generation::TEXT + OR authority->>'accountSourceVersion' IS DISTINCT FROM NEW.authority_account_source_version::TEXT + OR authority->>'issuanceFence' IS DISTINCT FROM NEW.issuance_fence::TEXT + OR authority->>'issuanceFenceSourceVersion' IS DISTINCT FROM NEW.issuance_fence_source_version::TEXT + OR authority->'authorityTuple' IS DISTINCT FROM + convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR authority->'authoritySourceVersions' IS DISTINCT FROM + convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8')::jsonb + OR authority->>'issuerProjectionGeneration' IS DISTINCT FROM NEW.authority_issuer_generation::TEXT + OR authority->>'accountProjectionGeneration' IS DISTINCT FROM NEW.authority_account_generation::TEXT + OR authority->>'issuerProjectionSha256' IS NULL + OR authority->>'issuerProjectionSha256' !~ '^[0-9a-f]{64}$' + OR authority->>'accountProjectionSha256' IS NULL + OR authority->>'accountProjectionSha256' !~ '^[0-9a-f]{64}$' + OR signer->>'promotionStatus' IS DISTINCT FROM 'COMMITTED' + OR signer->>'promotionOperationId' IS NULL + OR signer->>'promotionOperationId' !~ '^[0-9a-f-]{36}$' + OR signer->>'generationOperationId' IS NULL + OR signer->>'generationOperationId' !~ '^[0-9a-f-]{36}$' + OR signer->>'targetKid' IS DISTINCT FROM NEW.signer_kid + OR signer->>'targetGeneration' IS DISTINCT FROM NEW.signer_generation + OR signer->>'correspondenceSha256' IS NULL + OR signer->>'correspondenceSha256' !~ '^[0-9a-f]{64}$' + OR envelope->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR envelope->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR envelope->>'tokenHash' IS DISTINCT FROM NEW.token_hash + OR envelope->>'kid' IS DISTINCT FROM NEW.signer_kid + OR envelope->>'signerGeneration' IS DISTINCT FROM NEW.signer_generation THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof does not match its immutable intent' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + IF (registry->>'absoluteExpiryMillis')::BIGINT < NEW.expires_at_epoch_second * 1000 + OR (registry->>'absoluteExpiryMillis')::BIGINT > NEW.expires_at_epoch_second * 1000 + 300000 THEN + RAISE EXCEPTION 'Account gameplay delegation Redis receipt expiry is outside the immutable token bound' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + SELECT request_id, account_uuid, bundle_schema, bundle_version, source_version, + issuance_fence, linearization, canonical_sha256, canonical_bundle_bytes + INTO bundle_row + FROM account_gameplay_delegation_auth_evidence_bundles + WHERE operation_id = NEW.operation_id; + IF bundle_row.request_id IS NULL + OR bundle_row.request_id <> NEW.request_id + OR bundle_row.account_uuid <> NEW.account_uuid + OR bundle_row.bundle_schema <> 'account-auth-evidence-bundle/v1' + OR bundle_row.bundle_version <> bundle->>'bundleVersion' + OR bundle_row.source_version <> bundle->>'sourceVersion' + OR bundle_row.linearization <> bundle->>'linearization' + OR bundle_row.canonical_sha256 <> bundle->>'canonicalSha256' + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'authorityTuple' IS DISTINCT FROM + convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'membershipVersion' IS DISTINCT FROM + convert_from(NEW.membership_version_canonical_bytes, 'UTF8')::jsonb + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'authoritySourceVersions' IS DISTINCT FROM + convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8')::jsonb THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has no exact owner evidence bundle' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, + authority_evidence_bundle_sha256, issuance_fence, response_recovery_expiry_epoch_ms, + envelope_sha256, octet_length(envelope_bytes) AS envelope_bytes_length + INTO envelope_row + FROM account_gameplay_delegation_response_envelopes + WHERE operation_id = NEW.operation_id; + IF envelope_row.operation_id IS NULL + OR envelope_row.request_id <> NEW.request_id + OR envelope_row.token_hash <> NEW.token_hash + OR envelope_row.signer_kid <> NEW.signer_kid + OR envelope_row.signer_generation <> NEW.signer_generation + OR envelope_row.authority_evidence_bundle_sha256 <> bundle_row.canonical_sha256 + OR envelope_row.issuance_fence <> NEW.issuance_fence + OR envelope_row.response_recovery_expiry_epoch_ms / 1000 <> NEW.expires_at_epoch_second + OR envelope->>'authorityEvidenceBundleSha256' IS DISTINCT FROM envelope_row.authority_evidence_bundle_sha256 + OR envelope->>'issuanceFence' IS DISTINCT FROM envelope_row.issuance_fence::TEXT + OR envelope->>'responseRecoveryExpiryEpochMillis' IS DISTINCT FROM envelope_row.response_recovery_expiry_epoch_ms::TEXT + OR envelope->>'envelopeSha256' IS DISTINCT FROM envelope_row.envelope_sha256 + OR envelope->>'envelopeBytesLength' IS DISTINCT FROM envelope_row.envelope_bytes_length::TEXT THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has no exact sealed owner envelope' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + RETURN NEW; +END; +$$; + +DROP TRIGGER account_gameplay_delegation_operation_guard + ON account_gameplay_delegation_issuance_operations; +CREATE TRIGGER account_gameplay_delegation_operation_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_gameplay_delegation_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_gameplay_delegation_operation_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql b/services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql new file mode 100644 index 0000000000..c82bb9ed23 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql @@ -0,0 +1,67 @@ +-- Durable immutable owner observations are bound to a readiness plan, but remain partial +-- non-authorizing evidence. A stored Deployment/ReplicaSet/Pod inventory is not probe acceptance. +CREATE TABLE account_jwt_validator_inventory_snapshots ( + snapshot_digest VARCHAR(64) PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + cluster_incarnation_uid UUID NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + namespace_uid UUID NOT NULL, + api_binding_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + inventory_binding_revision VARCHAR(128) NOT NULL, + inventory_binding_digest VARCHAR(64) NOT NULL, + observed_at VARCHAR(40) NOT NULL, + canonical_snapshot BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_validator_inventory_snapshot_identity_check + CHECK (snapshot_digest ~ '^[0-9a-f]{64}$' + AND environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND api_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND inventory_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND inventory_binding_digest ~ '^[0-9a-f]{64}$' + AND length(observed_at) BETWEEN 20 AND 40 + AND observed_at ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T.*Z$' + AND octet_length(canonical_snapshot) BETWEEN 2 AND 4194304), + CONSTRAINT account_jwt_validator_inventory_snapshot_plan_identity_unique + UNIQUE (snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT validator inventory snapshots are immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_validator_inventory_snapshot_immutable + BEFORE UPDATE OR DELETE ON account_jwt_validator_inventory_snapshots + FOR EACH ROW EXECUTE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard(); + +CREATE TRIGGER account_jwt_validator_inventory_snapshot_no_truncate + BEFORE TRUNCATE ON account_jwt_validator_inventory_snapshots + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard(); +-- [jooq ignore end] + +ALTER TABLE account_jwt_readiness_probe_plans + ADD COLUMN inventory_snapshot_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_digest_check + CHECK (inventory_snapshot_digest IS NULL + OR inventory_snapshot_digest ~ '^[0-9a-f]{64}$'), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, + kubernetes_namespace, expected_cluster_incarnation_uid, expected_namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT; diff --git a/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql b/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql new file mode 100644 index 0000000000..3c9fdf95bb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql @@ -0,0 +1,427 @@ +-- Explicit, protected-fixture-only non-paid entitlement state. Tenant identity is UUID-native; +-- source row IDs are retained solely as authenticated provenance. +CREATE TABLE account_tenant_entitlement_outbox_streams ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + last_sequence BIGINT NOT NULL DEFAULT 0 CHECK (last_sequence >= 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE account_tenant_entitlement_outbox_events ( + tenant_uuid UUID NOT NULL, + tenant_billing_sequence BIGINT NOT NULL CHECK (tenant_billing_sequence > 0), + request_id UUID NOT NULL CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + event_id UUID NOT NULL UNIQUE CHECK (event_id <> '00000000-0000-0000-0000-000000000000'::UUID), + event_digest VARCHAR(71) NOT NULL CHECK (event_digest ~ '^sha256:[0-9a-f]{64}$'), + payload BYTEA NOT NULL CHECK (octet_length(payload) BETWEEN 1 AND 32768), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (tenant_uuid, tenant_billing_sequence), + UNIQUE (tenant_uuid, request_id), + UNIQUE (tenant_uuid, tenant_billing_sequence, event_id, event_digest), + FOREIGN KEY (tenant_uuid) REFERENCES account_tenant_entitlement_outbox_streams (tenant_uuid) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED +); + +CREATE TABLE account_demo_tenant_entitlement_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + tenant_uuid UUID NOT NULL + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_creation_request_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL CHECK (source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + status VARCHAR(16) NOT NULL CHECK (status IN ('PENDING', 'COMMITTED')), + tenant_billing_sequence BIGINT, + event_id UUID, + event_digest VARCHAR(71), + entitlement_version BIGINT, + tenant_authority_generation BIGINT, + tenant_authority_source_version BIGINT, + committed_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_demo_entitlement_operation_receipt_shape CHECK ( + (status = 'PENDING' AND tenant_billing_sequence IS NULL AND event_id IS NULL + AND event_digest IS NULL AND entitlement_version IS NULL + AND tenant_authority_generation IS NULL AND tenant_authority_source_version IS NULL + AND committed_at IS NULL) + OR + (status = 'COMMITTED' AND tenant_billing_sequence IS NOT NULL AND tenant_billing_sequence > 0 + AND event_id IS NOT NULL + AND event_digest IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND entitlement_version IS NOT NULL AND entitlement_version > 0 + AND tenant_authority_generation IS NOT NULL AND tenant_authority_generation > 0 + AND tenant_authority_source_version IS NOT NULL AND tenant_authority_source_version > 0 + AND committed_at IS NOT NULL) + ), + UNIQUE (tenant_uuid, request_id), + FOREIGN KEY (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + REFERENCES account_tenant_entitlement_outbox_events + (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + DEFERRABLE INITIALLY DEFERRED +); + +CREATE TABLE account_demo_tenant_entitlements ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + source_schema_version INTEGER NOT NULL CHECK (source_schema_version = 1), + source_target_namespace VARCHAR(128) NOT NULL + CHECK (source_target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + source_creation_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_request_digest VARCHAR(71) NOT NULL CHECK (source_request_digest ~ '^sha256:[0-9a-f]{64}$'), + source_game_row_id BIGINT NOT NULL CHECK (source_game_row_id > 0), + source_game_tenant_key VARCHAR(36) NOT NULL CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36), + source_provenance_kind VARCHAR(32) NOT NULL CHECK (source_provenance_kind = 'NEW_GAME_ROW'), + source_evidence_digest VARCHAR(71) NOT NULL CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + entitlement_kind VARCHAR(32) NOT NULL DEFAULT 'NON_PAID_DEMO' CHECK (entitlement_kind = 'NON_PAID_DEMO'), + status VARCHAR(16) NOT NULL DEFAULT 'ACTIVE' CHECK (status = 'ACTIVE'), + subscription_status VARCHAR(32) CHECK (subscription_status IS NULL), + paid BOOLEAN NOT NULL DEFAULT FALSE CHECK (paid = FALSE), + gameplay_available BOOLEAN NOT NULL, + allow_public_join BOOLEAN NOT NULL, + allow_new_gameplay_bindings BOOLEAN NOT NULL, + allow_new_instance_starts BOOLEAN NOT NULL, + max_active_sessions BIGINT NOT NULL CHECK (max_active_sessions >= 0), + max_concurrent_game_instances BIGINT NOT NULL CHECK (max_concurrent_game_instances >= 0), + max_storage_bytes BIGINT NOT NULL CHECK (max_storage_bytes >= 0), + entitlement_version BIGINT NOT NULL CHECK (entitlement_version > 0), + tenant_authority_generation BIGINT NOT NULL CHECK (tenant_authority_generation > 0), + tenant_authority_source_version BIGINT NOT NULL CHECK (tenant_authority_source_version > 0), + tenant_billing_sequence BIGINT NOT NULL CHECK (tenant_billing_sequence > 0), + event_id UUID NOT NULL, + event_digest VARCHAR(71) NOT NULL CHECK (event_digest ~ '^sha256:[0-9a-f]{64}$'), + last_request_id UUID NOT NULL, + last_request_digest VARCHAR(71) NOT NULL CHECK (last_request_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + REFERENCES account_tenant_entitlement_outbox_events + (tenant_uuid, tenant_billing_sequence, event_id, event_digest) + DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (tenant_uuid, last_request_id) + REFERENCES account_demo_tenant_entitlement_operations (tenant_uuid, request_id) + DEFERRABLE INITIALLY DEFERRED +); + +-- [jooq ignore start] +CREATE FUNCTION account_tenant_entitlement_stream_guard() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.last_sequence <> 0 THEN + RAISE EXCEPTION 'Tenant entitlement stream must begin at sequence zero' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'UPDATE' + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.last_sequence <> OLD.last_sequence + 1 THEN + RAISE EXCEPTION 'Tenant entitlement stream is immutable and advances by exactly one' + USING ERRCODE = '23514'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_tenant_entitlement_outbox_event_guard() RETURNS trigger AS $$ +DECLARE + current_sequence BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Tenant entitlement outbox events are immutable' + USING ERRCODE = '23514'; + END IF; + SELECT last_sequence INTO current_sequence FROM account_tenant_entitlement_outbox_streams + WHERE tenant_uuid = NEW.tenant_uuid; + IF current_sequence IS DISTINCT FROM NEW.tenant_billing_sequence THEN + RAISE EXCEPTION 'Tenant entitlement event does not match its stream checkpoint' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_tenant_entitlement_stream_consistency() RETURNS trigger AS $$ +DECLARE + stream_tenant UUID; + stream_sequence BIGINT; + max_sequence BIGINT; + event_count BIGINT; +BEGIN + stream_tenant := COALESCE(NEW.tenant_uuid, OLD.tenant_uuid); + SELECT last_sequence INTO stream_sequence FROM account_tenant_entitlement_outbox_streams + WHERE tenant_uuid = stream_tenant; + SELECT COALESCE(MAX(tenant_billing_sequence), 0), COUNT(*) + INTO max_sequence, event_count FROM account_tenant_entitlement_outbox_events + WHERE tenant_uuid = stream_tenant; + IF stream_sequence IS NULL OR stream_sequence <> max_sequence OR stream_sequence <> event_count THEN + RAISE EXCEPTION 'Tenant entitlement outbox stream and events are inconsistent' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_operation_guard() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'Demo entitlement operation must start pending' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'UPDATE' OR OLD.status <> 'PENDING' OR NEW.status <> 'COMMITTED' + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.source_creation_request_id IS DISTINCT FROM OLD.source_creation_request_id + OR NEW.source_request_digest IS DISTINCT FROM OLD.source_request_digest + OR NEW.source_operation_id IS DISTINCT FROM OLD.source_operation_id + OR NEW.source_evidence_digest IS DISTINCT FROM OLD.source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement operation identity is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_current_guard() RETURNS trigger AS $$ +DECLARE + authority_generation BIGINT; + authority_source_version BIGINT; + source_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Demo entitlement state cannot be deleted' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.source_schema_version IS DISTINCT FROM OLD.source_schema_version + OR NEW.source_target_namespace IS DISTINCT FROM OLD.source_target_namespace + OR NEW.source_creation_request_id IS DISTINCT FROM OLD.source_creation_request_id + OR NEW.source_operation_id IS DISTINCT FROM OLD.source_operation_id + OR NEW.source_request_digest IS DISTINCT FROM OLD.source_request_digest + OR NEW.source_game_row_id IS DISTINCT FROM OLD.source_game_row_id + OR NEW.source_game_tenant_key IS DISTINCT FROM OLD.source_game_tenant_key + OR NEW.source_provenance_kind IS DISTINCT FROM OLD.source_provenance_kind + OR NEW.source_evidence_digest IS DISTINCT FROM OLD.source_evidence_digest + OR NEW.entitlement_version <> OLD.entitlement_version + 1 THEN + RAISE EXCEPTION 'Demo entitlement identity is immutable and version advances by one' + USING ERRCODE = '23514'; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + ELSIF NEW.entitlement_version <> 1 THEN + RAISE EXCEPTION 'Demo entitlement must begin at version one' + USING ERRCODE = '23514'; + END IF; + SELECT generation, source_version INTO authority_generation, authority_source_version + FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + IF authority_generation IS DISTINCT FROM NEW.tenant_authority_generation + OR authority_source_version IS DISTINCT FROM NEW.tenant_authority_source_version THEN + RAISE EXCEPTION 'Demo entitlement is not fenced by current tenant authority' + USING ERRCODE = '23514'; + END IF; + SELECT EXISTS ( + SELECT 1 FROM account_fresh_tenant_identity_associations fresh + WHERE fresh.canonical_tenant_id = NEW.tenant_uuid + AND fresh.schema_version = NEW.source_schema_version + AND fresh.target_namespace = NEW.source_target_namespace + AND fresh.creation_request_id = NEW.source_creation_request_id + AND fresh.operation_id = NEW.source_operation_id + AND fresh.request_digest = NEW.source_request_digest + AND fresh.source_game_row_id = NEW.source_game_row_id + AND fresh.source_game_tenant_key = NEW.source_game_tenant_key + AND fresh.provenance_kind = NEW.source_provenance_kind + AND fresh.evidence_digest = NEW.source_evidence_digest + ) INTO source_matches; + IF NOT source_matches THEN + RAISE EXCEPTION 'Demo entitlement requires exact fresh Game Design source evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_operation_terminal_guard() RETURNS trigger AS $$ +DECLARE + operation_status VARCHAR(16); + operation_tenant UUID; + operation_sequence BIGINT; + operation_event_id UUID; + operation_event_digest VARCHAR(71); + operation_request_digest VARCHAR(71); + operation_entitlement_version BIGINT; + operation_authority_generation BIGINT; + operation_authority_source_version BIGINT; + operation_source_creation_request_id UUID; + operation_source_request_digest VARCHAR(71); + operation_source_operation_id UUID; + operation_source_evidence_digest VARCHAR(71); + event_payload JSONB; +BEGIN + SELECT status, tenant_uuid, tenant_billing_sequence, event_id, event_digest, request_digest, + entitlement_version, tenant_authority_generation, tenant_authority_source_version, + source_creation_request_id, source_request_digest, source_operation_id, + source_evidence_digest + INTO operation_status, operation_tenant, operation_sequence, operation_event_id, + operation_event_digest, operation_request_digest, operation_entitlement_version, + operation_authority_generation, operation_authority_source_version, + operation_source_creation_request_id, operation_source_request_digest, + operation_source_operation_id, operation_source_evidence_digest + FROM account_demo_tenant_entitlement_operations + WHERE request_id = NEW.request_id; + IF operation_status IS DISTINCT FROM 'COMMITTED' THEN + RAISE EXCEPTION 'Demo entitlement operation cannot commit pending' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(event.payload, 'UTF8')::JSONB INTO event_payload + FROM account_tenant_entitlement_outbox_events event + WHERE event.tenant_uuid = operation_tenant + AND event.tenant_billing_sequence = operation_sequence + AND event.event_id = operation_event_id + AND event.event_digest = operation_event_digest; + IF event_payload IS NULL + OR event_payload->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR event_payload->>'requestDigest' IS DISTINCT FROM operation_request_digest + OR event_payload->>'tenantId' IS DISTINCT FROM operation_tenant::TEXT + OR event_payload->>'tenantBillingSequence' IS DISTINCT FROM operation_sequence::TEXT + OR event_payload->>'eventId' IS DISTINCT FROM operation_event_id::TEXT + OR event_payload->>'eventDigest' IS DISTINCT FROM operation_event_digest + OR event_payload->>'entitlementVersion' IS DISTINCT FROM operation_entitlement_version::TEXT + OR event_payload->>'tenantAuthorityGeneration' + IS DISTINCT FROM operation_authority_generation::TEXT + OR event_payload->>'tenantAuthoritySourceVersion' + IS DISTINCT FROM operation_authority_source_version::TEXT + OR event_payload->'sourceEvidence'->>'creationRequestId' + IS DISTINCT FROM operation_source_creation_request_id::TEXT + OR event_payload->'sourceEvidence'->>'requestDigest' + IS DISTINCT FROM operation_source_request_digest + OR event_payload->'sourceEvidence'->>'operationId' + IS DISTINCT FROM operation_source_operation_id::TEXT + OR event_payload->'sourceEvidence'->>'evidenceDigest' + IS DISTINCT FROM operation_source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement operation receipt differs from its exact event' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM account_fresh_tenant_identity_associations fresh + WHERE fresh.canonical_tenant_id = operation_tenant + AND fresh.creation_request_id = operation_source_creation_request_id + AND fresh.request_digest = operation_source_request_digest + AND fresh.operation_id = operation_source_operation_id + AND fresh.evidence_digest = operation_source_evidence_digest + AND fresh.provenance_kind = 'NEW_GAME_ROW' + ) THEN + RAISE EXCEPTION 'Demo entitlement operation has no exact fresh tenant source' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_current_event_guard() RETURNS trigger AS $$ +DECLARE + payload JSONB; +BEGIN + SELECT convert_from(event.payload, 'UTF8')::JSONB INTO payload + FROM account_tenant_entitlement_outbox_events event + WHERE event.tenant_uuid = NEW.tenant_uuid + AND event.tenant_billing_sequence = NEW.tenant_billing_sequence + AND event.event_id = NEW.event_id + AND event.event_digest = NEW.event_digest; + IF payload IS NULL + OR payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-entitlement-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_ENTITLEMENT_CHANGED' + OR payload->>'outboxStreamKey' IS DISTINCT FROM + ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantBillingSequence' IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.event_id::TEXT + OR payload->>'eventDigest' IS DISTINCT FROM NEW.event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload->>'entitlementVersion' IS DISTINCT FROM NEW.entitlement_version::TEXT + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload->>'entitlementKind' IS DISTINCT FROM NEW.entitlement_kind + OR payload->>'status' IS DISTINCT FROM NEW.status + OR payload->>'paid' IS DISTINCT FROM 'false' + OR payload->>'gameplayAvailable' IS DISTINCT FROM NEW.gameplay_available::TEXT + OR payload->>'allowPublicJoin' IS DISTINCT FROM NEW.allow_public_join::TEXT + OR payload->>'allowNewGameplayBindings' IS DISTINCT FROM NEW.allow_new_gameplay_bindings::TEXT + OR payload->>'allowNewInstanceStarts' IS DISTINCT FROM NEW.allow_new_instance_starts::TEXT + OR payload->'quotas'->>'maxActiveSessions' IS DISTINCT FROM NEW.max_active_sessions::TEXT + OR payload->'quotas'->>'maxConcurrentGameInstances' IS DISTINCT FROM NEW.max_concurrent_game_instances::TEXT + OR payload->'quotas'->>'maxStorageBytes' IS DISTINCT FROM NEW.max_storage_bytes::TEXT + OR payload->'sourceEvidence'->>'schemaVersion' IS DISTINCT FROM NEW.source_schema_version::TEXT + OR payload->'sourceEvidence'->>'targetNamespace' IS DISTINCT FROM NEW.source_target_namespace + OR payload->'sourceEvidence'->>'creationRequestId' IS DISTINCT FROM NEW.source_creation_request_id::TEXT + OR payload->'sourceEvidence'->>'operationId' IS DISTINCT FROM NEW.source_operation_id::TEXT + OR payload->'sourceEvidence'->>'requestDigest' IS DISTINCT FROM NEW.source_request_digest + OR payload->'sourceEvidence'->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->'sourceEvidence'->>'sourceGameRowId' IS DISTINCT FROM NEW.source_game_row_id::TEXT + OR payload->'sourceEvidence'->>'sourceGameTenantKey' IS DISTINCT FROM NEW.source_game_tenant_key + OR payload->'sourceEvidence'->>'provenanceKind' IS DISTINCT FROM NEW.source_provenance_kind + OR payload->'sourceEvidence'->>'evidenceDigest' IS DISTINCT FROM NEW.source_evidence_digest THEN + RAISE EXCEPTION 'Demo entitlement state differs from its canonical outbox event' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION account_demo_entitlement_reject_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Account demo entitlement history cannot be truncated' + USING ERRCODE = '23514'; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER account_tenant_entitlement_stream_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_tenant_entitlement_outbox_streams + FOR EACH ROW EXECUTE FUNCTION account_tenant_entitlement_stream_guard(); +CREATE TRIGGER account_tenant_entitlement_stream_no_truncate + BEFORE TRUNCATE ON account_tenant_entitlement_outbox_streams + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE TRIGGER account_tenant_entitlement_event_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_tenant_entitlement_outbox_events + FOR EACH ROW EXECUTE FUNCTION account_tenant_entitlement_outbox_event_guard(); +CREATE TRIGGER account_tenant_entitlement_event_no_truncate + BEFORE TRUNCATE ON account_tenant_entitlement_outbox_events + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_tenant_entitlement_stream_consistency_stream + AFTER INSERT OR UPDATE ON account_tenant_entitlement_outbox_streams + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_entitlement_stream_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_entitlement_stream_consistency_event + AFTER INSERT ON account_tenant_entitlement_outbox_events + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_entitlement_stream_consistency(); +CREATE TRIGGER account_demo_entitlement_operation_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_demo_tenant_entitlement_operations + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_operation_guard(); +CREATE TRIGGER account_demo_entitlement_operation_no_truncate + BEFORE TRUNCATE ON account_demo_tenant_entitlement_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_demo_entitlement_operation_terminal + AFTER INSERT OR UPDATE ON account_demo_tenant_entitlement_operations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_demo_entitlement_operation_terminal_guard(); +CREATE TRIGGER account_demo_entitlement_current_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_demo_tenant_entitlements + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_current_guard(); +CREATE TRIGGER account_demo_entitlement_current_no_truncate + BEFORE TRUNCATE ON account_demo_tenant_entitlements + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_demo_entitlement_current_event + AFTER INSERT OR UPDATE ON account_demo_tenant_entitlements + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_demo_entitlement_current_event_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql new file mode 100644 index 0000000000..1b641d4d2e --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql @@ -0,0 +1,482 @@ +-- Preserve source-owner initialization provenance for future exact tenant-authority enrollment. +-- Existing rows remain NULL and are deliberately not assigned a synthetic generation-one proof. +ALTER TABLE account_fresh_tenant_identity_associations + ADD COLUMN authority_source_transaction_id BIGINT; +ALTER TABLE account_fresh_tenant_identity_associations + ADD CONSTRAINT account_fresh_tenant_authority_source_transaction_check + CHECK (authority_source_transaction_id IS NULL OR authority_source_transaction_id > 0); + +-- This is an Account-owned typed head over the generic authority outbox, not a second event log. +-- A sequence-zero row exists only inside the first authority transaction and cannot commit. +CREATE TABLE account_tenant_authority_source_records ( + outbox_stream_key VARCHAR(2048) PRIMARY KEY + REFERENCES account_authority_outbox_streams (outbox_stream_key) ON DELETE RESTRICT, + tenant_uuid UUID NOT NULL UNIQUE + REFERENCES account_fresh_tenant_identity_associations (canonical_tenant_id) ON DELETE RESTRICT, + initialization_transaction_id BIGINT NOT NULL CHECK (initialization_transaction_id > 0), + baseline_generation BIGINT NOT NULL DEFAULT 1 CHECK (baseline_generation = 1), + baseline_source_version BIGINT NOT NULL DEFAULT 1 CHECK (baseline_source_version = 1), + current_generation BIGINT NOT NULL CHECK (current_generation > 0), + current_source_version BIGINT NOT NULL CHECK (current_source_version > 0), + last_outbox_sequence BIGINT NOT NULL DEFAULT 0 CHECK (last_outbox_sequence >= 0), + last_request_id UUID, + last_request_digest VARCHAR(71), + last_event_id VARCHAR(512), + last_event_digest VARCHAR(71), + tenant_billing_sequence BIGINT, + tenant_billing_event_id UUID, + tenant_billing_event_digest VARCHAR(71), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_tenant_authority_source_key_check CHECK ( + outbox_stream_key = 'account:auth-authority:v1:tenant/' || tenant_uuid::TEXT), + CONSTRAINT account_tenant_authority_source_version_check CHECK ( + current_generation = baseline_generation + last_outbox_sequence + AND current_source_version = baseline_source_version + last_outbox_sequence), + CONSTRAINT account_tenant_authority_source_head_check CHECK ( + (last_outbox_sequence = 0 AND last_request_id IS NULL AND last_request_digest IS NULL + AND last_event_id IS NULL AND last_event_digest IS NULL + AND tenant_billing_sequence IS NULL AND tenant_billing_event_id IS NULL + AND tenant_billing_event_digest IS NULL) + OR (last_outbox_sequence > 0 AND last_request_id IS NOT NULL + AND last_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND last_event_id IS NOT NULL AND length(btrim(last_event_id)) > 0 + AND last_event_digest ~ '^sha256:[0-9a-f]{64}$' + AND tenant_billing_sequence > 0 AND tenant_billing_event_id IS NOT NULL + AND tenant_billing_event_digest ~ '^sha256:[0-9a-f]{64}$')) +); + +ALTER TABLE account_demo_tenant_entitlement_operations + ADD COLUMN tenant_authority_outbox_stream_key VARCHAR(2048), + ADD COLUMN tenant_authority_outbox_sequence BIGINT, + ADD COLUMN tenant_authority_event_id VARCHAR(512), + ADD COLUMN tenant_authority_event_digest VARCHAR(71); +-- [jooq ignore start] +-- PostgreSQL retains historical rows without validating this new source receipt constraint. +ALTER TABLE account_demo_tenant_entitlement_operations + ADD CONSTRAINT account_demo_entitlement_authority_receipt_shape CHECK ( + (status = 'PENDING' AND tenant_authority_outbox_stream_key IS NULL + AND tenant_authority_outbox_sequence IS NULL AND tenant_authority_event_id IS NULL + AND tenant_authority_event_digest IS NULL) + OR (status = 'COMMITTED' AND tenant_authority_outbox_stream_key IS NOT NULL + AND tenant_authority_outbox_sequence > 0 + AND tenant_authority_event_id IS NOT NULL + AND tenant_authority_event_digest ~ '^sha256:[0-9a-f]{64}$')) NOT VALID; +-- [jooq ignore stop] +ALTER TABLE account_demo_tenant_entitlement_operations + ADD CONSTRAINT account_demo_tenant_entitlement_operations_authority_event_fk + FOREIGN KEY (tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE account_demo_tenant_entitlements + ADD COLUMN tenant_authority_outbox_stream_key VARCHAR(2048), + ADD COLUMN tenant_authority_outbox_sequence BIGINT, + ADD COLUMN tenant_authority_event_id VARCHAR(512), + ADD COLUMN tenant_authority_event_digest VARCHAR(71); +-- [jooq ignore start] +-- PostgreSQL retains historical rows without validating this new source head constraint. +ALTER TABLE account_demo_tenant_entitlements + ADD CONSTRAINT account_demo_entitlement_authority_head_shape CHECK ( + (tenant_authority_outbox_stream_key IS NULL AND tenant_authority_outbox_sequence IS NULL + AND tenant_authority_event_id IS NULL AND tenant_authority_event_digest IS NULL) + OR (tenant_authority_outbox_stream_key IS NOT NULL + AND tenant_authority_outbox_sequence > 0 AND tenant_authority_event_id IS NOT NULL + AND tenant_authority_event_digest ~ '^sha256:[0-9a-f]{64}$')) NOT VALID; +-- [jooq ignore stop] +ALTER TABLE account_demo_tenant_entitlements + ADD CONSTRAINT account_demo_tenant_entitlements_authority_event_fk + FOREIGN KEY (tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED; + +-- Only Account's fresh tenant import path stamps this transaction ID. Retained rows are untouched. +-- [jooq ignore start] +CREATE FUNCTION account_fresh_tenant_authority_source_transaction_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + NEW.authority_source_transaction_id := txid_current(); + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_fresh_tenant_authority_source_transaction + BEFORE INSERT ON account_fresh_tenant_identity_associations + FOR EACH ROW EXECUTE FUNCTION account_fresh_tenant_authority_source_transaction_guard(); + +CREATE FUNCTION account_tenant_authority_source_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + fresh_row RECORD; + generation_row RECORD; + stream_sequence BIGINT; +BEGIN + SELECT authority_source_transaction_id, provenance_kind INTO fresh_row + FROM account_fresh_tenant_identity_associations + WHERE canonical_tenant_id = NEW.tenant_uuid; + SELECT generation, source_version, created_transaction_id INTO generation_row + FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + SELECT last_sequence INTO stream_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF NEW.outbox_stream_key <> 'account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT + OR NEW.initialization_transaction_id IS NULL + OR fresh_row.authority_source_transaction_id IS DISTINCT FROM NEW.initialization_transaction_id + OR fresh_row.provenance_kind IS DISTINCT FROM 'NEW_GAME_ROW' + OR generation_row.created_transaction_id IS DISTINCT FROM NEW.initialization_transaction_id + OR generation_row.generation IS DISTINCT FROM 1 + OR generation_row.source_version IS DISTINCT FROM 1 + OR stream_sequence IS DISTINCT FROM 0 + OR NEW.baseline_generation IS DISTINCT FROM 1 + OR NEW.baseline_source_version IS DISTINCT FROM 1 + OR NEW.current_generation IS DISTINCT FROM 1 + OR NEW.current_source_version IS DISTINCT FROM 1 + OR NEW.last_outbox_sequence IS DISTINCT FROM 0 + OR NEW.last_event_id IS NOT NULL OR NEW.last_event_digest IS NOT NULL + OR EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.outbox_stream_key) THEN + RAISE EXCEPTION 'Tenant authority baseline lacks fresh Account source initialization proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_baseline'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_authority_source_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; + billing_event RECORD; + fresh_row RECORD; +BEGIN + IF NEW.outbox_stream_key IS DISTINCT FROM OLD.outbox_stream_key + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.initialization_transaction_id IS DISTINCT FROM OLD.initialization_transaction_id + OR NEW.baseline_generation IS DISTINCT FROM OLD.baseline_generation + OR NEW.baseline_source_version IS DISTINCT FROM OLD.baseline_source_version + OR NEW.last_outbox_sequence <> OLD.last_outbox_sequence + 1 + OR NEW.current_generation <> OLD.current_generation + 1 + OR NEW.current_source_version <> OLD.current_source_version + 1 + OR NEW.current_generation <> NEW.baseline_generation + NEW.last_outbox_sequence + OR NEW.current_source_version <> NEW.baseline_source_version + NEW.last_outbox_sequence + OR NEW.last_request_id IS NULL OR NEW.last_request_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.last_event_id IS NULL OR NEW.last_event_digest !~ '^sha256:[0-9a-f]{64}$' + OR NEW.tenant_billing_sequence IS NULL OR NEW.tenant_billing_sequence <= 0 + OR NEW.tenant_billing_event_id IS NULL + OR NEW.tenant_billing_event_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Tenant authority source must advance one exact immutable event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_monotonic'; + END IF; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.last_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.last_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.last_event_digest THEN + RAISE EXCEPTION 'Tenant authority source head differs from its exact event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_event_link'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + IF payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-authority-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_AUTHORITY_CHANGED' + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'outboxStreamKey' IS DISTINCT FROM NEW.outbox_stream_key + OR payload->>'outboxSequence' IS DISTINCT FROM NEW.last_outbox_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.last_event_id + OR payload->>'eventDigest' IS DISTINCT FROM NEW.last_event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.current_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT + OR payload#>>'{tenantBillingReceipt,outboxStreamKey}' + IS DISTINCT FROM ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.tenant_billing_event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.tenant_billing_event_digest THEN + RAISE EXCEPTION 'Tenant authority source event does not match its exact checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_event_values'; + END IF; + SELECT schema_version, target_namespace, creation_request_id, operation_id, request_digest, + source_game_row_id, source_game_tenant_key, provenance_kind, evidence_digest + INTO fresh_row FROM account_fresh_tenant_identity_associations + WHERE canonical_tenant_id = NEW.tenant_uuid; + IF payload#>>'{sourceEvidence,schemaVersion}' IS DISTINCT FROM fresh_row.schema_version::TEXT + OR payload#>>'{sourceEvidence,targetNamespace}' IS DISTINCT FROM fresh_row.target_namespace + OR payload#>>'{sourceEvidence,creationRequestId}' IS DISTINCT FROM fresh_row.creation_request_id::TEXT + OR payload#>>'{sourceEvidence,operationId}' IS DISTINCT FROM fresh_row.operation_id::TEXT + OR payload#>>'{sourceEvidence,requestDigest}' IS DISTINCT FROM fresh_row.request_digest + OR payload#>>'{sourceEvidence,canonicalTenantId}' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload#>>'{sourceEvidence,sourceGameRowId}' IS DISTINCT FROM fresh_row.source_game_row_id::TEXT + OR payload#>>'{sourceEvidence,sourceGameTenantKey}' IS DISTINCT FROM fresh_row.source_game_tenant_key + OR payload#>>'{sourceEvidence,provenanceKind}' IS DISTINCT FROM fresh_row.provenance_kind + OR payload#>>'{sourceEvidence,evidenceDigest}' IS DISTINCT FROM fresh_row.evidence_digest THEN + RAISE EXCEPTION 'Tenant authority event differs from fresh Game Design source evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_evidence'; + END IF; + SELECT billing_event_row.event_id, billing_event_row.event_digest, + billing_event_row.payload INTO billing_event + FROM account_tenant_entitlement_outbox_events AS billing_event_row + WHERE billing_event_row.tenant_uuid = NEW.tenant_uuid + AND billing_event_row.tenant_billing_sequence = NEW.tenant_billing_sequence; + IF billing_event.event_id IS DISTINCT FROM NEW.tenant_billing_event_id + OR billing_event.event_digest IS DISTINCT FROM NEW.tenant_billing_event_digest THEN + RAISE EXCEPTION 'Tenant authority event does not link to the exact tenant billing event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_billing_link'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_authority_source_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + head RECORD; + generation_row RECORD; + stream_sequence BIGINT; + operation_row RECORD; + entitlement_row RECORD; +BEGIN + SELECT * INTO head FROM account_tenant_authority_source_records + WHERE outbox_stream_key = NEW.outbox_stream_key; + SELECT generation, source_version INTO generation_row FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + SELECT last_sequence INTO stream_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF head.outbox_stream_key IS NULL OR head.last_outbox_sequence <= 0 + OR head.current_generation IS DISTINCT FROM generation_row.generation + OR head.current_source_version IS DISTINCT FROM generation_row.source_version + OR stream_sequence IS DISTINCT FROM head.last_outbox_sequence THEN + RAISE EXCEPTION 'Tenant authority source checkpoint is not the current Account generation' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_consistent'; + END IF; + SELECT request_id, tenant_uuid, request_digest, source_creation_request_id, + source_request_digest, source_operation_id, source_evidence_digest, status, + tenant_billing_sequence, event_id, event_digest, + tenant_authority_outbox_stream_key, tenant_authority_outbox_sequence, + tenant_authority_event_id, tenant_authority_event_digest + INTO operation_row FROM account_demo_tenant_entitlement_operations + WHERE request_id = head.last_request_id; + SELECT * INTO entitlement_row FROM account_demo_tenant_entitlements + WHERE tenant_uuid = NEW.tenant_uuid; + IF operation_row.status IS DISTINCT FROM 'COMMITTED' + OR operation_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR operation_row.request_digest IS DISTINCT FROM head.last_request_digest + OR operation_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR operation_row.event_id IS DISTINCT FROM head.tenant_billing_event_id + OR operation_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR operation_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR operation_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR operation_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id + OR operation_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest + OR entitlement_row.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR entitlement_row.tenant_authority_generation IS DISTINCT FROM head.current_generation + OR entitlement_row.tenant_authority_source_version IS DISTINCT FROM head.current_source_version + OR entitlement_row.tenant_billing_sequence IS DISTINCT FROM head.tenant_billing_sequence + OR entitlement_row.event_id IS DISTINCT FROM head.tenant_billing_event_id + OR entitlement_row.event_digest IS DISTINCT FROM head.tenant_billing_event_digest + OR entitlement_row.tenant_authority_outbox_stream_key IS DISTINCT FROM head.outbox_stream_key + OR entitlement_row.tenant_authority_outbox_sequence IS DISTINCT FROM head.last_outbox_sequence + OR entitlement_row.tenant_authority_event_id IS DISTINCT FROM head.last_event_id + OR entitlement_row.tenant_authority_event_digest IS DISTINCT FROM head.last_event_digest THEN + RAISE EXCEPTION 'Tenant authority source lacks its exact current Account receipt and entitlement' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_source_receipt'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_tenant_authority_generation_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + source_row RECORD; +BEGIN + IF NEW.scope_kind = 'TENANT' THEN + SELECT current_generation, current_source_version INTO source_row + FROM account_tenant_authority_source_records WHERE tenant_uuid = NEW.tenant_uuid; + IF source_row.current_generation IS DISTINCT FROM NEW.generation + OR source_row.current_source_version IS DISTINCT FROM NEW.source_version THEN + RAISE EXCEPTION 'Tenant authority generation advance lacks its canonical source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_generation_source'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_tenant_authority_stream_consistency() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + source_row RECORD; + stream_head BIGINT; +BEGIN + IF left(NEW.outbox_stream_key, length('account:auth-authority:v1:tenant/')) + = 'account:auth-authority:v1:tenant/' THEN + -- This is deferred: the queued NEW image may be the temporary sequence-zero row + -- created while the first source head is enrolled. Validate the final live head instead. + SELECT last_sequence INTO stream_head + FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.outbox_stream_key; + SELECT last_outbox_sequence INTO source_row + FROM account_tenant_authority_source_records + WHERE outbox_stream_key = NEW.outbox_stream_key; + IF stream_head IS NULL + OR source_row.last_outbox_sequence IS DISTINCT FROM stream_head + OR stream_head <= 0 THEN + RAISE EXCEPTION 'Tenant authority outbox head lacks an Account-owned source checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_tenant_authority_stream_source'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_demo_entitlement_authority_event_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; + generation_row RECORD; +BEGIN + IF NEW.tenant_authority_outbox_stream_key IS NULL + OR NEW.tenant_authority_outbox_sequence IS NULL + OR NEW.tenant_authority_event_id IS NULL + OR NEW.tenant_authority_event_digest IS NULL THEN + RAISE EXCEPTION 'Demo entitlement requires a distinct canonical tenant authority event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_required'; + END IF; + IF NEW.tenant_authority_outbox_stream_key + IS DISTINCT FROM ('account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT) THEN + RAISE EXCEPTION 'Demo entitlement tenant authority event has the wrong scope' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_scope'; + END IF; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.tenant_authority_outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.tenant_authority_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.tenant_authority_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.tenant_authority_event_digest THEN + RAISE EXCEPTION 'Demo entitlement authority receipt differs from its exact source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_event_link'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + SELECT generation, source_version INTO generation_row FROM account_authority_generations + WHERE scope_kind = 'TENANT' AND tenant_uuid = NEW.tenant_uuid; + IF payload->>'schemaVersion' IS DISTINCT FROM 'account-tenant-authority-event/v1' + OR payload->>'eventType' IS DISTINCT FROM 'TENANT_AUTHORITY_CHANGED' + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantAuthorityGeneration' IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload->>'outboxStreamKey' IS DISTINCT FROM NEW.tenant_authority_outbox_stream_key + OR payload->>'outboxSequence' IS DISTINCT FROM NEW.tenant_authority_outbox_sequence::TEXT + OR payload->>'eventId' IS DISTINCT FROM NEW.tenant_authority_event_id + OR payload->>'eventDigest' IS DISTINCT FROM NEW.tenant_authority_event_digest + OR payload->>'requestId' IS DISTINCT FROM NEW.last_request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.last_request_digest + OR payload#>>'{tenantBillingReceipt,outboxStreamKey}' + IS DISTINCT FROM ('account:tenant-entitlement:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.event_digest + OR generation_row.generation IS DISTINCT FROM NEW.tenant_authority_generation + OR generation_row.source_version IS DISTINCT FROM NEW.tenant_authority_source_version THEN + RAISE EXCEPTION 'Demo entitlement differs from its actual tenant authority source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_values'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_demo_entitlement_authority_receipt_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + authority_event RECORD; + payload JSONB; +BEGIN + IF NEW.status = 'COMMITTED' THEN + IF NEW.tenant_authority_outbox_stream_key + IS DISTINCT FROM ('account:auth-authority:v1:tenant/' || NEW.tenant_uuid::TEXT) + OR NEW.tenant_authority_outbox_sequence IS NULL + OR NEW.tenant_authority_event_id IS NULL + OR NEW.tenant_authority_event_digest IS NULL THEN + RAISE EXCEPTION 'Committed demo receipt requires its exact tenant authority checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_required'; + END IF; + SELECT authority_event_row.event_id, authority_event_row.event_digest, + authority_event_row.payload INTO authority_event + FROM account_authority_outbox_events AS authority_event_row + WHERE authority_event_row.outbox_stream_key = NEW.tenant_authority_outbox_stream_key + AND authority_event_row.outbox_sequence = NEW.tenant_authority_outbox_sequence; + IF authority_event.event_id IS DISTINCT FROM NEW.tenant_authority_event_id + OR authority_event.event_digest IS DISTINCT FROM NEW.tenant_authority_event_digest THEN + RAISE EXCEPTION 'Committed demo receipt authority event differs from Account outbox' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_event'; + END IF; + payload := convert_from(authority_event.payload, 'UTF8')::JSONB; + IF payload->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR payload->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR payload->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR payload->>'tenantAuthorityGeneration' + IS DISTINCT FROM NEW.tenant_authority_generation::TEXT + OR payload->>'tenantAuthoritySourceVersion' + IS DISTINCT FROM NEW.tenant_authority_source_version::TEXT + OR payload#>>'{tenantBillingReceipt,tenantBillingSequence}' + IS DISTINCT FROM NEW.tenant_billing_sequence::TEXT + OR payload#>>'{tenantBillingReceipt,eventId}' IS DISTINCT FROM NEW.event_id::TEXT + OR payload#>>'{tenantBillingReceipt,eventDigest}' IS DISTINCT FROM NEW.event_digest THEN + RAISE EXCEPTION 'Committed demo receipt differs from its canonical authority event' + USING ERRCODE = '23514', CONSTRAINT = 'account_demo_entitlement_authority_receipt_values'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_tenant_authority_source_insert + BEFORE INSERT ON account_tenant_authority_source_records + FOR EACH ROW EXECUTE FUNCTION account_tenant_authority_source_insert_guard(); +CREATE TRIGGER account_tenant_authority_source_update + BEFORE UPDATE OR DELETE ON account_tenant_authority_source_records + FOR EACH ROW EXECUTE FUNCTION account_tenant_authority_source_update_guard(); +CREATE TRIGGER account_tenant_authority_source_no_truncate + BEFORE TRUNCATE ON account_tenant_authority_source_records + FOR EACH STATEMENT EXECUTE FUNCTION account_demo_entitlement_reject_truncate(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_source_consistency + AFTER INSERT OR UPDATE ON account_tenant_authority_source_records + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_source_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_generation_consistency + AFTER UPDATE ON account_authority_generations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_generation_consistency(); +CREATE CONSTRAINT TRIGGER account_tenant_authority_stream_consistency + AFTER INSERT OR UPDATE ON account_authority_outbox_streams + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_tenant_authority_stream_consistency(); +CREATE TRIGGER account_demo_entitlement_authority_event + BEFORE INSERT OR UPDATE ON account_demo_tenant_entitlements + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_authority_event_guard(); +CREATE TRIGGER account_demo_entitlement_authority_receipt + BEFORE INSERT OR UPDATE ON account_demo_tenant_entitlement_operations + FOR EACH ROW EXECUTE FUNCTION account_demo_entitlement_authority_receipt_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V74.1__account_global_role_source.sql b/services/account-service/src/main/resources/db/migration/V74.1__account_global_role_source.sql new file mode 100644 index 0000000000..78047e0790 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V74.1__account_global_role_source.sql @@ -0,0 +1,158 @@ +ALTER TABLE accounts + ADD CONSTRAINT accounts_global_role_source_identity_uq + UNIQUE (account_uuid, account_uuid_source_numeric_id, account_uuid_provenance); + +CREATE TABLE account_global_role_sources ( + account_uuid UUID PRIMARY KEY, + account_uuid_source_numeric_id BIGINT NOT NULL, + account_uuid_provenance VARCHAR(40) NOT NULL, + global_roles TEXT[] NOT NULL, + global_role_source_version BIGINT NOT NULL, + CONSTRAINT account_global_role_sources_account_identity_fk + FOREIGN KEY ( + account_uuid, + account_uuid_source_numeric_id, + account_uuid_provenance + ) + REFERENCES accounts ( + account_uuid, + account_uuid_source_numeric_id, + account_uuid_provenance + ) + ON DELETE RESTRICT, + CONSTRAINT account_global_role_sources_account_numeric_id_check + CHECK (account_uuid_source_numeric_id > 0), + CONSTRAINT account_global_role_sources_account_uuid_check + CHECK (account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_global_role_sources_fresh_provenance_check + CHECK (account_uuid_provenance IN ( + 'ACCOUNT_REPOSITORY_INSERT', + 'ACCOUNT_DATABASE_INSERT' + )), + CONSTRAINT account_global_role_sources_empty_roles_check + CHECK (global_roles = ARRAY[]::TEXT[]), + CONSTRAINT account_global_role_sources_positive_version_check + CHECK (global_role_source_version > 0) +); + +-- This prerequisite admits only the explicit-empty state. Role mutations need a +-- separately versioned, fenced producer before this immutable source can advance. +-- [jooq ignore start] +CREATE FUNCTION account_global_role_source_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Fresh Account global-role source is immutable until a versioned writer exists' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_global_role_source_immutable + BEFORE UPDATE OR DELETE ON account_global_role_sources + FOR EACH ROW EXECUTE FUNCTION account_global_role_source_immutable_guard(); + +CREATE FUNCTION account_global_role_source_truncate_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Fresh Account global-role source cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_truncate_denied'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_global_role_source_truncate_guard + BEFORE TRUNCATE ON account_global_role_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_global_role_source_truncate_guard(); + +CREATE FUNCTION account_global_role_source_birth_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + account_identity_exists BOOLEAN; +BEGIN + IF pg_trigger_depth() <> 2 THEN + RAISE EXCEPTION 'Account global-role source may only be inserted by its fresh Account birth path' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_birth_only'; + END IF; + + -- The source table and its Account owner may be written through a + -- schema-qualified relation while the connection search_path names another + -- schema. Resolve the paired Account row in the trigger table's own schema. + EXECUTE format( + 'SELECT EXISTS ( + SELECT 1 + FROM %I.accounts account_row + WHERE account_row.id = $1 + AND account_row.account_uuid = $2 + AND account_row.account_uuid_source_numeric_id = $3 + AND account_row.account_uuid_provenance = $4 + AND account_row.account_uuid_provenance IN ( + ''ACCOUNT_REPOSITORY_INSERT'', + ''ACCOUNT_DATABASE_INSERT'' + ) + AND account_row.role IS NULL + )', + TG_TABLE_SCHEMA + ) INTO account_identity_exists + USING NEW.account_uuid_source_numeric_id, + NEW.account_uuid, + NEW.account_uuid_source_numeric_id, + NEW.account_uuid_provenance; + + IF NOT account_identity_exists THEN + RAISE EXCEPTION 'Account global-role source may only be inserted by its fresh Account birth path' + USING ERRCODE = '23514', CONSTRAINT = 'account_global_role_source_birth_only'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_global_role_source_birth_insert_guard + BEFORE INSERT ON account_global_role_sources + FOR EACH ROW EXECUTE FUNCTION account_global_role_source_birth_insert_guard(); + +CREATE FUNCTION account_global_role_source_birth() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.account_uuid_provenance IN ( + 'ACCOUNT_REPOSITORY_INSERT', + 'ACCOUNT_DATABASE_INSERT' + ) AND NEW.role IS NULL THEN + IF NEW.account_uuid IS NULL + OR NEW.account_uuid = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM NEW.id THEN + RAISE EXCEPTION 'Fresh Account has no exact canonical UUID source identity' + USING ERRCODE = '23514', + CONSTRAINT = 'account_global_role_source_birth_identity'; + END IF; + + -- Bind the fresh source row to the schema that owns this Account row, + -- even when the caller inserted through a qualified table name. + EXECUTE format( + 'INSERT INTO %I.account_global_role_sources ( + account_uuid, + account_uuid_source_numeric_id, + account_uuid_provenance, + global_roles, + global_role_source_version + ) VALUES ($1, $2, $3, ARRAY[]::TEXT[], 1)', + TG_TABLE_SCHEMA + ) USING NEW.account_uuid, + NEW.account_uuid_source_numeric_id, + NEW.account_uuid_provenance; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER accounts_global_role_source_birth + AFTER INSERT ON accounts + FOR EACH ROW EXECUTE FUNCTION account_global_role_source_birth(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V74__account_gameplay_token_identity_fences.sql b/services/account-service/src/main/resources/db/migration/V74__account_gameplay_token_identity_fences.sql new file mode 100644 index 0000000000..00b9ddbbdb --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V74__account_gameplay_token_identity_fences.sql @@ -0,0 +1,85 @@ +-- Only the real COMMITTED issuance transaction establishes initial fences; no registry adoption. +-- Historical COMMITTED rows with no fence fail closed and require fresh LOGIN. +CREATE TABLE account_gameplay_token_identity_fences ( + operation_id UUID PRIMARY KEY REFERENCES account_gameplay_delegation_issuance_operations (operation_id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts (account_uuid) ON DELETE RESTRICT, + issuance_request_id UUID NOT NULL UNIQUE, + token_hash VARCHAR(64) NOT NULL UNIQUE, + token_jti UUID NOT NULL UNIQUE, + not_before_epoch_second BIGINT NOT NULL, + token_generation BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + token_identity_fence BIGINT NOT NULL DEFAULT 1, + state VARCHAR(16) NOT NULL DEFAULT 'ACTIVE', + revocation_request_id UUID UNIQUE, + revocation_digest VARCHAR(64), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_gameplay_token_identity_shape CHECK ( + token_hash ~ '^[0-9a-f]{64}$' AND not_before_epoch_second > 0 + AND token_generation = 1 AND issuance_fence > 0 + AND account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND issuance_request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND token_jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_gameplay_token_revocation_shape CHECK ( + (state = 'ACTIVE' AND token_identity_fence = 1 + AND revocation_request_id IS NULL AND revocation_digest IS NULL) + OR (state IN ('PENDING', 'COMMITTED') + AND token_identity_fence = CASE WHEN state = 'PENDING' THEN 2 ELSE 3 END + AND revocation_request_id IS NOT NULL AND revocation_digest IS NOT NULL + AND revocation_request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND revocation_digest ~ '^[0-9a-f]{64}$')) +); + +-- Retain immutable identity and forbid reset/recreation. Triggers reinforce the repository's +-- account-row-first lock order; callers must acquire that Account lock before row mutations. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_token_identity_fence_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account token fence retention cannot be bypassed by deletion' USING ERRCODE = '23514'; + END IF; + PERFORM account_uuid FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account token fence Account source absent' USING ERRCODE = '23514'; + END IF; + PERFORM operation_id FROM account_gameplay_delegation_issuance_operations + WHERE operation_id = NEW.operation_id AND account_uuid = NEW.account_uuid + AND request_id = NEW.issuance_request_id AND token_hash = NEW.token_hash + AND token_jti = NEW.token_jti AND not_before_epoch_second = NEW.not_before_epoch_second + AND token_generation = NEW.token_generation AND issuance_fence = NEW.issuance_fence + AND status = 'COMMITTED' FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account token fence requires exact COMMITTED issuance' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'ACTIVE' OR NEW.token_identity_fence <> 1 + OR NEW.revocation_request_id IS NOT NULL OR NEW.revocation_digest IS NOT NULL THEN + RAISE EXCEPTION 'Account token fence must begin ACTIVE' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.operation_id, NEW.account_uuid, NEW.issuance_request_id, NEW.token_hash, + NEW.token_jti, NEW.not_before_epoch_second, NEW.token_generation, NEW.issuance_fence, NEW.created_at) + IS DISTINCT FROM ROW(OLD.operation_id, OLD.account_uuid, OLD.issuance_request_id, OLD.token_hash, + OLD.token_jti, OLD.not_before_epoch_second, OLD.token_generation, OLD.issuance_fence, OLD.created_at) THEN + RAISE EXCEPTION 'Account token fence identity is immutable' USING ERRCODE = '23514'; + END IF; + IF NEW IS NOT DISTINCT FROM OLD THEN RETURN NEW; END IF; + IF OLD.state = 'ACTIVE' AND NEW.state = 'PENDING' AND NEW.token_identity_fence = 2 THEN + RETURN NEW; + END IF; + -- Storage only: there is no completion API until the real Gateway deny/clear owner exists. + IF OLD.state = 'PENDING' AND NEW.state = 'COMMITTED' AND NEW.token_identity_fence = 3 + AND NEW.revocation_request_id = OLD.revocation_request_id + AND NEW.revocation_digest = OLD.revocation_digest THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Account token fence transition or revocation identity conflicts' USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER account_gameplay_token_identity_fence_guard +BEFORE INSERT OR UPDATE OR DELETE ON account_gameplay_token_identity_fences +FOR EACH ROW EXECUTE FUNCTION account_gameplay_token_identity_fence_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V75__account_password_reset_operation_receipts.sql b/services/account-service/src/main/resources/db/migration/V75__account_password_reset_operation_receipts.sql new file mode 100644 index 0000000000..33b0cb2992 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V75__account_password_reset_operation_receipts.sql @@ -0,0 +1,91 @@ +-- Immutable source receipts make a consumed Account-issued reset token an exact retry identity. +CREATE TABLE account_password_reset_operation_receipts ( + token_hash BYTEA NOT NULL, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL, + operation_kind VARCHAR(32) NOT NULL DEFAULT 'PASSWORD_RESET', + request_id VARCHAR(128) NOT NULL UNIQUE, + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + token_expires_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, + password_verifier_digest BYTEA NOT NULL, + outbox_stream_key VARCHAR(2048) NOT NULL, + outbox_sequence BIGINT NOT NULL, + event_id VARCHAR(128) NOT NULL, + event_digest VARCHAR(71) NOT NULL, + account_authority_generation BIGINT NOT NULL, + account_source_version BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + issuance_fence_source_version BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_password_reset_operation_token_hash_check + CHECK (octet_length(token_hash) = 32), + CONSTRAINT account_password_reset_operation_identity_check + CHECK (account_id > 0 + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_kind = 'PASSWORD_RESET' + AND length(btrim(request_id)) BETWEEN 1 AND 128 + AND request_id = 'account-password-reset-request-v1:' || encode(token_hash, 'hex') + AND request_digest_version = 1 + AND octet_length(request_digest) = 32 + AND octet_length(password_verifier_digest) = 32), + CONSTRAINT account_password_reset_operation_checkpoint_check + CHECK (outbox_stream_key = 'account:auth-authority:v1:account/' || account_uuid::TEXT + AND outbox_sequence > 0 + AND length(btrim(event_id)) BETWEEN 1 AND 128 + AND event_id = 'account-password-reset-event-v1:' || encode(token_hash, 'hex') + AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_authority_generation > 0 + AND account_source_version > 0 + AND issuance_fence > 0 + AND issuance_fence_source_version > 0), + CONSTRAINT account_password_reset_operation_event_uq + UNIQUE (outbox_stream_key, event_id), + CONSTRAINT account_password_reset_operation_outbox_fk + FOREIGN KEY (outbox_stream_key, outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT +); + +-- Bind the private numeric association and canonical Account UUID at the immutable insert point. +-- [jooq ignore start] +ALTER TABLE account_password_reset_operation_receipts + ADD CONSTRAINT account_password_reset_operation_receipts_pk PRIMARY KEY (token_hash); + +CREATE FUNCTION account_password_reset_operation_account_binding_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + persisted_uuid UUID; +BEGIN + SELECT account_uuid INTO persisted_uuid + FROM accounts + WHERE id = NEW.account_id; + IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN + RAISE EXCEPTION 'Password-reset receipt Account identity does not match its source row' + USING ERRCODE = '23514', CONSTRAINT = 'account_password_reset_operation_account_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_password_reset_operation_account_binding + BEFORE INSERT ON account_password_reset_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_password_reset_operation_account_binding_guard(); + +CREATE FUNCTION account_password_reset_operation_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Password-reset operation receipts are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_password_reset_operation_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_password_reset_operation_immutable + BEFORE UPDATE OR DELETE ON account_password_reset_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_password_reset_operation_immutable_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql b/services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql new file mode 100644 index 0000000000..6cfd73f856 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql @@ -0,0 +1,188 @@ +-- Internal storage only. No source writer or authenticated authorization producer is enabled. +CREATE TABLE account_draft_authorization_source_locks ( + source_key VARCHAR(512) PRIMARY KEY CHECK (length(source_key) > 0 AND octet_length(source_key) <= 512) +); + +CREATE TABLE account_draft_authorization_fences ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + commit_id UUID NOT NULL UNIQUE, + fence_id UUID NOT NULL UNIQUE, + binding BYTEA NOT NULL CHECK (octet_length(binding) > 0), + ordering VARCHAR(20) NOT NULL CHECK (ordering IN ('RESERVED', 'COMMIT_ORDER', 'REVOKE_ORDER')), + reserved_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + ordered_at TIMESTAMPTZ, + CHECK ((ordering = 'RESERVED') = (ordered_at IS NULL)) +); + +CREATE TABLE account_draft_authorization_sources ( + operation_id UUID NOT NULL REFERENCES account_draft_authorization_fences(operation_id), + source_key VARCHAR(512) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_draft_authorization_sources_by_scope + ON account_draft_authorization_sources(source_key, operation_id); + +CREATE TABLE account_draft_authorization_owner_readbacks ( + operation_id UUID NOT NULL REFERENCES account_draft_authorization_fences(operation_id), + owner VARCHAR(16) NOT NULL CHECK (owner IN ('GAME_DESIGN', 'WORLD')), + outcome VARCHAR(24) NOT NULL CHECK (outcome IN ('COMMITTED', 'DEFINITIVELY_ABORTED')), + readback BYTEA NOT NULL CHECK (octet_length(readback) > 0), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (operation_id, owner) +); + +CREATE TABLE account_draft_authorization_source_changes ( + change_id UUID PRIMARY KEY, + binding BYTEA NOT NULL CHECK (octet_length(binding) > 0), + status VARCHAR(16) NOT NULL + CHECK (status IN ('WAITING', 'SOURCE_COMMITTED', 'SOURCE_ABORTED')), + requested_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + aborted_at TIMESTAMPTZ, + abort_reason VARCHAR(32) CHECK (abort_reason IN ('EXPIRED', 'DEFINITIVE_ABORT')), + CHECK ( + (status = 'WAITING' + AND committed_at IS NULL + AND aborted_at IS NULL + AND abort_reason IS NULL) + OR (status = 'SOURCE_COMMITTED' + AND committed_at IS NOT NULL + AND aborted_at IS NULL + AND abort_reason IS NULL) + OR (status = 'SOURCE_ABORTED' + AND committed_at IS NULL + AND aborted_at IS NOT NULL + AND abort_reason IS NOT NULL) + ) +); + +CREATE TABLE account_draft_authorization_changed_scopes ( + change_id UUID NOT NULL REFERENCES account_draft_authorization_source_changes(change_id), + source_key VARCHAR(512) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + PRIMARY KEY (change_id, source_key) +); +CREATE INDEX account_draft_authorization_changes_by_scope + ON account_draft_authorization_changed_scopes(source_key, change_id); + +-- [jooq ignore start] +CREATE FUNCTION account_draft_authorization_immutable_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Draft authorization evidence is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_draft_authorization_order_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Draft authorization fence cannot be deleted'; + END IF; + IF OLD.ordering <> 'RESERVED' OR NEW.ordering NOT IN ('COMMIT_ORDER', 'REVOKE_ORDER') + OR NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.commit_id IS DISTINCT FROM OLD.commit_id + OR NEW.fence_id IS DISTINCT FROM OLD.fence_id + OR NEW.binding IS DISTINCT FROM OLD.binding + OR NEW.reserved_at IS DISTINCT FROM OLD.reserved_at + OR NEW.ordered_at IS NULL THEN + RAISE EXCEPTION 'Draft commit/revoke ordering is immutable'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_draft_authorization_source_change_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Draft source change cannot be deleted'; + END IF; + IF OLD.status <> 'WAITING' OR NEW.status NOT IN ('SOURCE_COMMITTED', 'SOURCE_ABORTED') + OR NEW.change_id IS DISTINCT FROM OLD.change_id + OR NEW.binding IS DISTINCT FROM OLD.binding + OR NEW.requested_at IS DISTINCT FROM OLD.requested_at + OR (NEW.status = 'SOURCE_COMMITTED' + AND (NEW.committed_at IS NULL OR NEW.aborted_at IS NOT NULL OR NEW.abort_reason IS NOT NULL)) + OR (NEW.status = 'SOURCE_ABORTED' + AND (NEW.committed_at IS NOT NULL OR NEW.aborted_at IS NULL + OR NEW.abort_reason IS NULL + OR NEW.abort_reason NOT IN ('EXPIRED', 'DEFINITIVE_ABORT'))) THEN + RAISE EXCEPTION 'Draft source change result is immutable'; + END IF; + IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_draft_authorization_sources source USING (source_key) + JOIN account_draft_authorization_fences fence USING (operation_id) + WHERE changed.change_id = OLD.change_id + AND NOT ((fence.ordering = 'REVOKE_ORDER' AND ( + SELECT count(*) FROM account_draft_authorization_owner_readbacks readback + WHERE readback.operation_id = fence.operation_id + AND readback.outcome = 'DEFINITIVELY_ABORTED' + ) = 2) OR (fence.ordering = 'COMMIT_ORDER' AND ( + SELECT count(*) FROM account_draft_authorization_owner_readbacks readback + WHERE readback.operation_id = fence.operation_id + ) = 2)) + ) THEN + RAISE EXCEPTION 'Both definitive owner outcomes are required before source commit'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_draft_authorization_insert_phase_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + phase TEXT; +BEGIN + IF TG_TABLE_NAME = 'account_draft_authorization_changed_scopes' THEN + SELECT status INTO phase FROM account_draft_authorization_source_changes + WHERE change_id = NEW.change_id FOR UPDATE; + IF phase IS DISTINCT FROM 'WAITING' THEN + RAISE EXCEPTION 'Completed source change cannot acquire new scopes'; + END IF; + ELSE + SELECT ordering INTO phase FROM account_draft_authorization_fences + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF TG_TABLE_NAME = 'account_draft_authorization_sources' AND phase IS DISTINCT FROM 'RESERVED' THEN + RAISE EXCEPTION 'Ordered Draft operation cannot acquire new sources'; + ELSIF TG_TABLE_NAME = 'account_draft_authorization_owner_readbacks' + AND (phase IS NULL OR phase = 'RESERVED') THEN + RAISE EXCEPTION 'Reservation alone cannot produce owner terminal evidence'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_draft_authorization_fence_guard + BEFORE UPDATE OR DELETE ON account_draft_authorization_fences + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_order_guard(); +CREATE TRIGGER account_draft_authorization_change_guard + BEFORE UPDATE OR DELETE ON account_draft_authorization_source_changes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_source_change_guard(); +CREATE TRIGGER account_draft_authorization_sources_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_readbacks_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_owner_readbacks + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_scopes_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_changed_scopes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_source_locks_immutable + BEFORE UPDATE OR DELETE ON account_draft_authorization_source_locks + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_draft_authorization_source_insert_phase + BEFORE INSERT ON account_draft_authorization_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard(); +CREATE TRIGGER account_draft_authorization_readback_insert_phase + BEFORE INSERT ON account_draft_authorization_owner_readbacks + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard(); +CREATE TRIGGER account_draft_authorization_scope_insert_phase + BEFORE INSERT ON account_draft_authorization_changed_scopes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_insert_phase_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V77__account_logout_all_operation_receipts.sql b/services/account-service/src/main/resources/db/migration/V77__account_logout_all_operation_receipts.sql new file mode 100644 index 0000000000..09ae1789ae --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V77__account_logout_all_operation_receipts.sql @@ -0,0 +1,90 @@ +-- Immutable lifecycle receipts bind one logout-all request and presented token to its source event. +CREATE TABLE account_logout_all_operation_receipts ( + request_id UUID NOT NULL, + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL, + operation_kind VARCHAR(32) NOT NULL DEFAULT 'ACCOUNT_LOGOUT_ALL', + request_digest_version INTEGER NOT NULL, + request_digest BYTEA NOT NULL, + presented_token_hash BYTEA NOT NULL, + token_profile VARCHAR(32) NOT NULL, + outbox_stream_key VARCHAR(2048) NOT NULL, + outbox_sequence BIGINT NOT NULL, + event_id VARCHAR(128) NOT NULL, + event_digest VARCHAR(71) NOT NULL, + account_authority_generation BIGINT NOT NULL, + account_source_version BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + issuance_fence_source_version BIGINT NOT NULL, + lifecycle_result VARCHAR(32) NOT NULL DEFAULT 'LOGOUT_ALL_COMMITTED', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_logout_all_operation_identity_check + CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_kind = 'ACCOUNT_LOGOUT_ALL' + AND request_digest_version = 1 + AND octet_length(request_digest) = 32 + AND octet_length(presented_token_hash) = 32 + AND token_profile IN ('control-ui', 'player-bootstrap') + AND lifecycle_result = 'LOGOUT_ALL_COMMITTED'), + CONSTRAINT account_logout_all_operation_checkpoint_check + CHECK (outbox_stream_key = 'account:auth-authority:v1:account/' || account_uuid::TEXT + AND outbox_sequence > 0 + AND event_id = 'account-logout-all-event-v1:' || request_id::TEXT + AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_authority_generation > 0 + AND account_source_version > 0 + AND issuance_fence > 0 + AND issuance_fence_source_version > 0), + CONSTRAINT account_logout_all_operation_event_uq + UNIQUE (outbox_stream_key, event_id), + CONSTRAINT account_logout_all_operation_outbox_fk + FOREIGN KEY (outbox_stream_key, outbox_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT +); + +-- [jooq ignore start] +ALTER TABLE account_logout_all_operation_receipts + ADD CONSTRAINT account_logout_all_operation_receipts_pk PRIMARY KEY (request_id); + +CREATE UNIQUE INDEX account_logout_all_operation_presented_token_uq + ON account_logout_all_operation_receipts (presented_token_hash); + +CREATE FUNCTION account_logout_all_operation_account_binding_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + persisted_uuid UUID; +BEGIN + SELECT account_uuid INTO persisted_uuid + FROM accounts + WHERE id = NEW.account_id; + IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN + RAISE EXCEPTION 'Logout-all receipt Account identity does not match its source row' + USING ERRCODE = '23514', CONSTRAINT = 'account_logout_all_operation_account_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_logout_all_operation_account_binding + BEFORE INSERT ON account_logout_all_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_logout_all_operation_account_binding_guard(); + +CREATE FUNCTION account_logout_all_operation_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Logout-all operation receipts are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_logout_all_operation_immutable'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_logout_all_operation_immutable + BEFORE UPDATE OR DELETE ON account_logout_all_operation_receipts + FOR EACH ROW EXECUTE FUNCTION account_logout_all_operation_immutable_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V78__account_security_state_operations.sql b/services/account-service/src/main/resources/db/migration/V78__account_security_state_operations.sql new file mode 100644 index 0000000000..78309fc3fd --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V78__account_security_state_operations.sql @@ -0,0 +1,401 @@ +-- Correlation/receipt storage only. No source writer, authorization grant, or retained-row backfill. +CREATE TABLE account_security_state_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'), + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL, + account_provenance VARCHAR(40) NOT NULL, + caller_proof_binding BYTEA NOT NULL CHECK (octet_length(caller_proof_binding) BETWEEN 1 AND 16384), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0), + request_digest VARCHAR(64) NOT NULL CHECK (request_digest ~ '^[0-9a-f]{64}$'), + expected_generation BIGINT NOT NULL CHECK (expected_generation > 0), + expected_source_version BIGINT NOT NULL CHECK (expected_source_version > 0), + expected_fence BIGINT NOT NULL CHECK (expected_fence > 0), + expected_fence_source_version BIGINT NOT NULL CHECK (expected_fence_source_version > 0), + checkpoint_sequence BIGINT NOT NULL CHECK (checkpoint_sequence >= 0), + checkpoint_payload BYTEA NOT NULL, + global_role_source_version BIGINT NOT NULL CHECK (global_role_source_version > 0), + before_state BYTEA NOT NULL, + after_state BYTEA NOT NULL, + mutation_kinds TEXT[] NOT NULL CHECK (cardinality(mutation_kinds) BETWEEN 1 AND 4), + source_change_id UUID NOT NULL UNIQUE REFERENCES account_draft_authorization_source_changes(change_id), + source_change_binding BYTEA NOT NULL CHECK (octet_length(source_change_binding) > 0), + capture_payload BYTEA NOT NULL CHECK (octet_length(capture_payload) > 0), + status VARCHAR(12) NOT NULL CHECK (status IN ('WAITING', 'COMMITTED')), + event_sequence BIGINT CHECK (event_sequence > 0), + event_id VARCHAR(128), + event_digest VARCHAR(71), + event_payload BYTEA, + result_generation BIGINT CHECK (result_generation > 0), + result_source_version BIGINT CHECK (result_source_version > 0), + result_fence BIGINT CHECK (result_fence > 0), + result_fence_source_version BIGINT CHECK (result_fence_source_version > 0), + result_global_role_source_version BIGINT CHECK (result_global_role_source_version > 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + FOREIGN KEY (account_uuid, account_id, account_provenance) + REFERENCES accounts(account_uuid, account_uuid_source_numeric_id, account_uuid_provenance) + ON DELETE RESTRICT, + CONSTRAINT account_security_state_result_shape CHECK ( + (status = 'WAITING' AND event_sequence IS NULL AND event_id IS NULL AND event_digest IS NULL + AND event_payload IS NULL AND result_generation IS NULL AND result_source_version IS NULL + AND result_fence IS NULL AND result_fence_source_version IS NULL + AND result_global_role_source_version IS NULL AND committed_at IS NULL) + OR (status = 'COMMITTED' AND event_sequence IS NOT NULL AND event_id IS NOT NULL + AND event_digest IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$' AND event_payload IS NOT NULL + AND result_generation IS NOT NULL AND result_source_version IS NOT NULL + AND result_fence IS NOT NULL AND result_fence_source_version IS NOT NULL + AND result_global_role_source_version IS NOT NULL AND committed_at IS NOT NULL)) +); + +CREATE UNIQUE INDEX account_security_state_event_checkpoint_unique + ON account_security_state_operations(account_uuid, event_sequence) WHERE event_sequence IS NOT NULL; + +-- [jooq ignore start] +CREATE FUNCTION account_security_state_frame(value BYTEA) +RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT int4send(octet_length(value)) || value; +$$; + +CREATE FUNCTION account_security_state_canonical_state(value BYTEA) +RETURNS TEXT LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + state JSONB := convert_from(value, 'UTF8')::JSONB; + modes TEXT[]; + roles TEXT[]; + canonical TEXT; +BEGIN + IF jsonb_typeof(state) <> 'object' + OR (SELECT array_agg(k ORDER BY k) FROM jsonb_object_keys(state) k) + <> ARRAY['emailVerified','globalRoles','lifecycleState','loginAuthModes'] + OR jsonb_typeof(state->'emailVerified') <> 'boolean' + OR jsonb_typeof(state->'loginAuthModes') <> 'array' + OR jsonb_typeof(state->'globalRoles') <> 'array' + OR jsonb_typeof(state->'lifecycleState') <> 'string' + OR state->>'lifecycleState' NOT IN ('ACTIVE','SECURITY_LOCKED','DEACTIVATED_PENDING_DELETE','DELETED') THEN + RAISE EXCEPTION 'Unsupported security-state representation' USING ERRCODE = '23514'; + END IF; + SELECT COALESCE(array_agg(v ORDER BY ordinal), ARRAY[]::TEXT[]) INTO modes + FROM jsonb_array_elements_text(state->'loginAuthModes') WITH ORDINALITY AS t(v, ordinal); + SELECT COALESCE(array_agg(v ORDER BY ordinal), ARRAY[]::TEXT[]) INTO roles + FROM jsonb_array_elements_text(state->'globalRoles') WITH ORDINALITY AS t(v, ordinal); + IF cardinality(modes) = 0 OR NOT modes <@ ARRAY['EMAIL_OTP','PASSWORD']::TEXT[] + OR modes <> (SELECT array_agg(DISTINCT v ORDER BY v) FROM unnest(modes) v) + OR NOT roles <@ ARRAY['billingAdmin','platformAdmin','support']::TEXT[] + OR roles <> (SELECT COALESCE(array_agg(DISTINCT v ORDER BY v), ARRAY[]::TEXT[]) FROM unnest(roles) v) THEN + RAISE EXCEPTION 'Unsupported security-state arrays' USING ERRCODE = '23514'; + END IF; + canonical := '{"emailVerified":' || (state->'emailVerified')::TEXT + || ',"globalRoles":' || replace((state->'globalRoles')::TEXT, ', ', ',') + || ',"lifecycleState":"' || (state->>'lifecycleState') || '"' + || ',"loginAuthModes":' || replace((state->'loginAuthModes')::TEXT, ', ', ',') || '}'; + IF value IS DISTINCT FROM convert_to(canonical, 'UTF8') THEN + RAISE EXCEPTION 'Security-state bytes must be complete canonical JSON' USING ERRCODE = '23514'; + END IF; + RETURN canonical; +END; +$$; + +CREATE FUNCTION account_security_state_operation_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + before_json JSONB; + after_json JSONB; + kinds TEXT[] := ARRAY[]::TEXT[]; + request_bytes BYTEA; + capture_bytes BYTEA; + account_source_bytes BYTEA; + role_source_bytes BYTEA; + change_bytes BYTEA; + kind TEXT; + source_row RECORD; + baseline_row RECORD; + account_row RECORD; + role_row RECORD; + authority_row RECORD; + fence_row RECORD; + outbox_row RECORD; + stream_row RECORD; + key TEXT; + preimage TEXT; + expected_digest TEXT; + expected_wire TEXT; + caller_json JSONB; + canonical_caller TEXT; + checkpoint_json JSONB; + checkpoint_text TEXT; + checkpoint_preimage TEXT; +BEGIN + IF TG_OP = 'UPDATE' THEN + IF OLD.status <> 'WAITING' OR NEW.status <> 'COMMITTED' + OR (to_jsonb(NEW) - ARRAY['status','event_sequence','event_id','event_digest','event_payload', + 'result_generation','result_source_version','result_fence','result_fence_source_version', + 'result_global_role_source_version','committed_at']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status','event_sequence','event_id','event_digest','event_payload', + 'result_generation','result_source_version','result_fence','result_fence_source_version', + 'result_global_role_source_version','committed_at']) THEN + RAISE EXCEPTION 'Original security-state request/capture and committed results are immutable' + USING ERRCODE = '23514'; + END IF; + NEW.committed_at := CURRENT_TIMESTAMP; + ELSIF NEW.status <> 'WAITING' THEN + RAISE EXCEPTION 'Security-state operation must start WAITING' USING ERRCODE = '23514'; + END IF; + before_json := account_security_state_canonical_state(NEW.before_state)::JSONB; + after_json := account_security_state_canonical_state(NEW.after_state)::JSONB; + caller_json := convert_from(NEW.caller_proof_binding,'UTF8')::JSONB; + IF jsonb_typeof(caller_json) <> 'object' + OR (SELECT array_agg(k ORDER BY k) FROM jsonb_object_keys(caller_json) k) + <> ARRAY['actorAccountUuid','ownerEvidenceDigest','ownerOperationId','schemaVersion'] + OR caller_json->>'schemaVersion' <> 'account-security-state-caller-correlation/v1' + OR jsonb_typeof(caller_json->'actorAccountUuid') <> 'string' + OR jsonb_typeof(caller_json->'ownerOperationId') <> 'string' + OR jsonb_typeof(caller_json->'ownerEvidenceDigest') <> 'string' + OR jsonb_typeof(caller_json->'schemaVersion') <> 'string' + OR caller_json->>'actorAccountUuid' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR caller_json->>'ownerOperationId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR caller_json->>'actorAccountUuid' = '00000000-0000-0000-0000-000000000000' + OR caller_json->>'ownerOperationId' = '00000000-0000-0000-0000-000000000000' + OR caller_json->>'ownerEvidenceDigest' !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Unsupported original caller correlation shape' USING ERRCODE = '23514'; + END IF; + canonical_caller := '{"actorAccountUuid":"' || (caller_json->>'actorAccountUuid') + || '","ownerEvidenceDigest":"' || (caller_json->>'ownerEvidenceDigest') + || '","ownerOperationId":"' || (caller_json->>'ownerOperationId') + || '","schemaVersion":"account-security-state-caller-correlation/v1"}'; + IF NEW.caller_proof_binding IS DISTINCT FROM convert_to(canonical_caller,'UTF8') THEN + RAISE EXCEPTION 'Original caller correlation bytes must be canonical' USING ERRCODE = '23514'; + END IF; + IF before_json->'emailVerified' <> after_json->'emailVerified' THEN + kinds := array_append(kinds, 'EMAIL_LOGIN_ELIGIBILITY_CHANGED'); + END IF; + IF before_json->'globalRoles' <> after_json->'globalRoles' THEN + kinds := array_append(kinds, 'GLOBAL_ROLE_CHANGED'); + END IF; + IF before_json->'lifecycleState' <> after_json->'lifecycleState' THEN + kinds := array_append(kinds, 'LIFECYCLE_STATE_CHANGED'); + END IF; + IF before_json->'loginAuthModes' <> after_json->'loginAuthModes' THEN + kinds := array_append(kinds, 'LOGIN_AUTH_MODES_CHANGED'); + END IF; + IF kinds <> NEW.mutation_kinds OR cardinality(kinds) = 0 THEN + RAISE EXCEPTION 'Complete changed-family set differs from state images' USING ERRCODE = '23514'; + END IF; + request_bytes := account_security_state_frame(convert_to('firemud/account/security-state/request/v1','UTF8')) + || account_security_state_frame(convert_to(NEW.request_id::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.account_uuid::TEXT,'UTF8')) + || account_security_state_frame(NEW.caller_proof_binding) + || account_security_state_frame(convert_to(NEW.expected_generation::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.expected_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to(cardinality(kinds)::TEXT,'UTF8')); + FOREACH kind IN ARRAY kinds LOOP + request_bytes := request_bytes || account_security_state_frame(convert_to(kind,'UTF8')); + END LOOP; + request_bytes := request_bytes || account_security_state_frame(NEW.after_state); + capture_bytes := account_security_state_frame(convert_to('firemud/account/security-state/capture/v1','UTF8')) + || account_security_state_frame(request_bytes) + || account_security_state_frame(convert_to(NEW.account_id::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.account_provenance,'UTF8')) + || account_security_state_frame(NEW.before_state) + || account_security_state_frame(convert_to(NEW.expected_fence::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.expected_fence_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.checkpoint_sequence::TEXT,'UTF8')) + || account_security_state_frame(NEW.checkpoint_payload) + || account_security_state_frame(convert_to(NEW.global_role_source_version::TEXT,'UTF8')); + IF request_bytes <> NEW.request_payload OR encode(sha256(request_bytes),'hex') <> NEW.request_digest + OR capture_bytes <> NEW.capture_payload THEN + RAISE EXCEPTION 'Security-state request/capture bytes or digest differ' USING ERRCODE = '23514'; + END IF; + -- Reuse the exact V57 framing; correlation cannot substitute a different source vector. + key := 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT; + account_source_bytes := account_security_state_frame(convert_to('account-draft-source-evidence/v1','UTF8')) + || account_security_state_frame(convert_to('ACCOUNT','UTF8')) + || account_security_state_frame(convert_to(NEW.account_uuid::TEXT,'UTF8')) + || account_security_state_frame(convert_to('PRESENT','UTF8')) + || account_security_state_frame(convert_to(NEW.expected_generation::TEXT,'UTF8')) + || account_security_state_frame(convert_to(NEW.expected_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to('PRESENT','UTF8')) + || account_security_state_frame(convert_to(key,'UTF8')) + || account_security_state_frame(convert_to(NEW.checkpoint_sequence::TEXT,'UTF8')) + || account_security_state_frame(capture_bytes); + change_bytes := account_security_state_frame(convert_to('account-draft-source-change/v1','UTF8')) + || account_security_state_frame(convert_to(NEW.source_change_id::TEXT,'UTF8')) + || account_security_state_frame(convert_to(CASE WHEN 'GLOBAL_ROLE_CHANGED' = ANY(kinds) THEN '2' ELSE '1' END,'UTF8')) + || account_security_state_frame(account_source_bytes); + IF 'GLOBAL_ROLE_CHANGED' = ANY(kinds) THEN + role_source_bytes := account_security_state_frame(convert_to('account-draft-source-evidence/v1','UTF8')) + || account_security_state_frame(convert_to('GLOBAL_ROLES','UTF8')) + || account_security_state_frame(convert_to(NEW.account_uuid::TEXT,'UTF8')) + || account_security_state_frame(convert_to('ABSENT','UTF8')) + || account_security_state_frame(convert_to(NEW.global_role_source_version::TEXT,'UTF8')) + || account_security_state_frame(convert_to('ABSENT','UTF8')) + || account_security_state_frame(capture_bytes); + change_bytes := change_bytes || account_security_state_frame(role_source_bytes); + END IF; + change_bytes := change_bytes || account_security_state_frame(capture_bytes); + IF change_bytes <> NEW.source_change_binding THEN + RAISE EXCEPTION 'Security-state exact V57 participation binding differs' USING ERRCODE = '23514'; + END IF; + SELECT * INTO account_row FROM accounts WHERE id = NEW.account_id FOR UPDATE; + IF NOT FOUND OR account_row.account_uuid <> NEW.account_uuid + OR account_row.account_uuid_source_numeric_id <> NEW.account_id + OR account_row.account_uuid_provenance <> NEW.account_provenance THEN + RAISE EXCEPTION 'Security-state Account association differs' USING ERRCODE = '23514'; + END IF; + SELECT * INTO source_row FROM account_draft_authorization_source_changes + WHERE change_id = NEW.source_change_id FOR SHARE; + IF NOT FOUND OR source_row.binding <> NEW.source_change_binding + OR source_row.status <> (CASE WHEN TG_OP = 'INSERT' THEN 'WAITING' ELSE 'SOURCE_COMMITTED' END) THEN + RAISE EXCEPTION 'Security-state V57 source change differs' USING ERRCODE = '23514'; + END IF; + SELECT * INTO authority_row FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid FOR SHARE; + SELECT * INTO fence_row FROM account_authority_issuance_fences WHERE account_uuid = NEW.account_uuid FOR SHARE; + SELECT * INTO role_row FROM account_global_role_sources WHERE account_uuid = NEW.account_uuid FOR SHARE; + IF authority_row IS NULL OR fence_row IS NULL OR role_row IS NULL THEN + RAISE EXCEPTION 'Security-state current source evidence is missing' USING ERRCODE = '23514'; + END IF; + key := 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT; + IF TG_OP = 'INSERT' THEN + IF NEW.expected_generation = 9223372036854775807 OR NEW.expected_source_version = 9223372036854775807 + OR NEW.expected_fence = 9223372036854775807 OR NEW.expected_fence_source_version = 9223372036854775807 + OR NEW.checkpoint_sequence = 9223372036854775807 + OR ('GLOBAL_ROLE_CHANGED' = ANY(kinds) AND NEW.global_role_source_version = 9223372036854775807) THEN + RAISE EXCEPTION 'Account source counter overflow' USING ERRCODE = '23514'; + END IF; + IF authority_row.generation <> NEW.expected_generation OR authority_row.source_version <> NEW.expected_source_version + OR fence_row.issuance_fence <> NEW.expected_fence OR fence_row.source_version <> NEW.expected_fence_source_version + OR role_row.global_role_source_version <> NEW.global_role_source_version THEN + RAISE EXCEPTION 'Security-state original source capture is stale' USING ERRCODE = '23514'; + END IF; + IF NEW.checkpoint_sequence = 0 THEN + SELECT * INTO baseline_row FROM account_authority_source_records + WHERE outbox_stream_key = key FOR SHARE; + SELECT * INTO stream_row FROM account_authority_outbox_streams + WHERE outbox_stream_key = key FOR SHARE; + -- V40 retains an explicit zero stream; counters alone never prove fresh provenance. + IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1 + OR NEW.expected_fence <> 1 OR NEW.expected_fence_source_version <> 1 + OR octet_length(NEW.checkpoint_payload) <> 0 + OR baseline_row IS NULL OR stream_row IS NULL + OR stream_row.last_sequence IS DISTINCT FROM 0 + OR baseline_row.scope_kind IS DISTINCT FROM 'ACCOUNT' + OR baseline_row.issuer_id IS NOT NULL + OR baseline_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR baseline_row.baseline_generation IS DISTINCT FROM 1 + OR baseline_row.baseline_source_version IS DISTINCT FROM 1 + OR baseline_row.baseline_issuance_fence IS DISTINCT FROM 1 + OR baseline_row.current_generation IS DISTINCT FROM 1 + OR baseline_row.current_source_version IS DISTINCT FROM 1 + OR baseline_row.current_issuance_fence IS DISTINCT FROM 1 + OR baseline_row.current_issuance_fence_source_version IS DISTINCT FROM 1 + OR baseline_row.last_outbox_sequence IS DISTINCT FROM 0 + OR baseline_row.last_event_id IS NOT NULL OR baseline_row.last_event_digest IS NOT NULL + OR baseline_row.cutoff_generation IS NOT NULL OR baseline_row.cutoff_stream_key IS NOT NULL + OR baseline_row.cutoff_sequence IS NOT NULL + OR baseline_row.initialization_provenance IS DISTINCT FROM 'ACCOUNT_REPOSITORY_INSERT' + OR baseline_row.account_uuid_provenance IS DISTINCT FROM NEW.account_provenance + OR baseline_row.account_source_numeric_id IS DISTINCT FROM NEW.account_id + OR baseline_row.initialization_transaction_id <= 0 + OR baseline_row.initialization_transaction_id IS DISTINCT FROM authority_row.created_transaction_id + OR baseline_row.initialization_transaction_id IS DISTINCT FROM account_row.account_repository_insert_transaction_id + OR baseline_row.account_repository_insert_transaction_id IS DISTINCT FROM account_row.account_repository_insert_transaction_id + OR EXISTS (SELECT 1 FROM account_authority_outbox_events WHERE outbox_stream_key = key) THEN + RAISE EXCEPTION 'Security-state pristine baseline is not proved' USING ERRCODE = '23514'; + END IF; + ELSE + SELECT * INTO stream_row FROM account_authority_outbox_streams WHERE outbox_stream_key = key; + SELECT * INTO outbox_row FROM account_authority_outbox_events + WHERE outbox_stream_key = key AND outbox_sequence = NEW.checkpoint_sequence; + IF stream_row IS NULL OR outbox_row IS NULL OR stream_row.last_sequence <> NEW.checkpoint_sequence + OR outbox_row.payload <> NEW.checkpoint_payload THEN + RAISE EXCEPTION 'Security-state original checkpoint differs' USING ERRCODE = '23514'; + END IF; + checkpoint_text := convert_from(NEW.checkpoint_payload,'UTF8'); + checkpoint_json := checkpoint_text::JSONB; + checkpoint_preimage := replace(checkpoint_text, + '"eventDigest":"' || outbox_row.event_digest || '",', ''); + IF COALESCE(checkpoint_json->>'schemaVersion','') NOT IN ('account-auth-password-reset-event/v1', + 'account-auth-logout-all-event/v1', 'account-auth-account-security-state-event/v1') + OR checkpoint_json->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR checkpoint_json->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT + OR checkpoint_json->>'outboxStreamKey' IS DISTINCT FROM key + OR checkpoint_json->>'outboxSequence' IS DISTINCT FROM NEW.checkpoint_sequence::TEXT + OR checkpoint_json->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.expected_generation::TEXT + OR checkpoint_json->>'sourceVersion' IS DISTINCT FROM NEW.expected_source_version::TEXT + OR checkpoint_json->>'requestId' IS DISTINCT FROM outbox_row.request_id + OR checkpoint_json->>'eventId' IS DISTINCT FROM outbox_row.event_id + OR checkpoint_json->>'eventDigest' IS DISTINCT FROM outbox_row.event_digest + OR checkpoint_json->'accountSecurityCutoff'->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.expected_generation::TEXT + OR checkpoint_json->'accountSecurityCutoff'->>'outboxStreamKey' IS DISTINCT FROM key + OR checkpoint_json->'accountSecurityCutoff'->>'outboxSequence' IS DISTINCT FROM NEW.checkpoint_sequence::TEXT + OR outbox_row.event_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(checkpoint_preimage,'UTF8')),'hex') + OR checkpoint_preimage = checkpoint_text THEN + RAISE EXCEPTION 'Security-state checkpoint identity/counters/digest differ' USING ERRCODE = '23514'; + END IF; + END IF; + ELSE + IF NEW.result_generation::NUMERIC <> NEW.expected_generation::NUMERIC + 1 + OR NEW.result_source_version::NUMERIC <> NEW.expected_source_version::NUMERIC + 1 + OR NEW.result_fence::NUMERIC <> NEW.expected_fence::NUMERIC + 1 + OR NEW.result_fence_source_version::NUMERIC <> NEW.expected_fence_source_version::NUMERIC + 1 + OR NEW.event_sequence::NUMERIC <> NEW.checkpoint_sequence::NUMERIC + 1 + OR NEW.result_global_role_source_version::NUMERIC <> NEW.global_role_source_version::NUMERIC + + (CASE WHEN 'GLOBAL_ROLE_CHANGED' = ANY(kinds) THEN 1 ELSE 0 END) + OR authority_row.generation <> NEW.result_generation OR authority_row.source_version <> NEW.result_source_version + OR fence_row.issuance_fence <> NEW.result_fence OR fence_row.source_version <> NEW.result_fence_source_version + OR role_row.global_role_source_version <> NEW.result_global_role_source_version THEN + RAISE EXCEPTION 'Security-state producer result counters differ' USING ERRCODE = '23514'; + END IF; + SELECT * INTO outbox_row FROM account_authority_outbox_events + WHERE outbox_stream_key = key AND request_id = NEW.request_id::TEXT; + SELECT * INTO stream_row FROM account_authority_outbox_streams WHERE outbox_stream_key = key; + IF outbox_row IS NULL OR stream_row IS NULL OR outbox_row.outbox_sequence <> NEW.event_sequence + OR outbox_row.event_id <> NEW.event_id OR outbox_row.event_digest <> NEW.event_digest + OR outbox_row.payload <> NEW.event_payload OR stream_row.last_sequence <> NEW.event_sequence THEN + RAISE EXCEPTION 'Security-state exact outbox receipt differs' USING ERRCODE = '23514'; + END IF; + preimage := '{"accountAuthorityGeneration":"' || NEW.result_generation::TEXT + || '","accountId":"' || NEW.account_uuid::TEXT + || '","accountSecurityCutoff":{"accountAuthorityGeneration":"' || NEW.result_generation::TEXT + || '","outboxSequence":"' || NEW.event_sequence::TEXT || '","outboxStreamKey":"' || key + || '"},"accountState":' || convert_from(NEW.after_state,'UTF8') + || ',"eventId":"account-security-state-event-v1:' || NEW.request_id::TEXT + || '","eventType":"ACCOUNT_SECURITY_STATE_CHANGED","mutationKinds":' + || replace(to_jsonb(kinds)::TEXT, ', ', ',') + || ',"outboxSequence":"' || NEW.event_sequence::TEXT || '","outboxStreamKey":"' || key + || '","requestId":"' || NEW.request_id::TEXT + || '","schemaVersion":"account-auth-account-security-state-event/v1","sourceScope":"account/' + || NEW.account_uuid::TEXT || '","sourceVersion":"' || NEW.result_source_version::TEXT || '"}'; + expected_digest := 'sha256:' || encode(sha256(convert_to(preimage,'UTF8')),'hex'); + expected_wire := replace(preimage, ',"eventId":', ',"eventDigest":"' || expected_digest || '","eventId":'); + IF NEW.event_digest IS DISTINCT FROM expected_digest OR NEW.event_payload IS DISTINCT FROM convert_to(expected_wire,'UTF8') THEN + RAISE EXCEPTION 'Security-state canonical event/digest differs' USING ERRCODE = '23514'; + END IF; + before_json := after_json; + END IF; + IF (before_json->'emailVerified')::BOOLEAN IS DISTINCT FROM account_row.email_verified + OR before_json->>'lifecycleState' IS DISTINCT FROM upper(account_row.lifecycle_state) + OR before_json->'globalRoles' IS DISTINCT FROM to_jsonb(role_row.global_roles) + OR before_json->'loginAuthModes' IS DISTINCT FROM (SELECT jsonb_agg(v ORDER BY v) + FROM unnest(string_to_array(account_row.login_auth_modes, ',')) v) THEN + RAISE EXCEPTION 'Security-state exact owner-state readback differs' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_security_state_operation_guard BEFORE INSERT OR UPDATE + ON account_security_state_operations FOR EACH ROW EXECUTE FUNCTION account_security_state_operation_guard(); + +CREATE FUNCTION account_security_state_retention_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Security-state operation evidence must be retained' USING ERRCODE = '23514'; + RETURN OLD; +END; +$$; +CREATE TRIGGER account_security_state_delete_denied BEFORE DELETE ON account_security_state_operations + FOR EACH ROW EXECUTE FUNCTION account_security_state_retention_guard(); +CREATE TRIGGER account_security_state_truncate_denied BEFORE TRUNCATE ON account_security_state_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_security_state_retention_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V81__account_gameplay_login_credential_request_binding.sql b/services/account-service/src/main/resources/db/migration/V81__account_gameplay_login_credential_request_binding.sql new file mode 100644 index 0000000000..17f416099c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V81__account_gameplay_login_credential_request_binding.sql @@ -0,0 +1,87 @@ +-- Bind each newly prepared gameplay LOGIN operation to the exact transient credential +-- presentation using an Account-owned HMAC key. The key ID identifies real retained key +-- material; it is distinct from this digest schema version. Existing v1 rows remain unchanged +-- and non-authorizing because they have no credential binding. +ALTER TABLE account_gameplay_delegation_issuance_operations + DROP CONSTRAINT account_gameplay_delegation_digest_check; + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD CONSTRAINT account_gameplay_delegation_digest_check + CHECK (request_digest_version IN (1, 2) AND request_digest ~ '^[0-9a-f]{64}$'); + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD COLUMN credential_request_digest_version SMALLINT; + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD COLUMN credential_digest_key_id VARCHAR(32); + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD COLUMN credential_request_digest VARCHAR(64); + +ALTER TABLE account_gameplay_delegation_issuance_operations + ADD CONSTRAINT account_gameplay_delegation_credential_request_binding_check + CHECK ((credential_request_digest_version IS NULL + AND credential_digest_key_id IS NULL + AND credential_request_digest IS NULL) + OR (credential_request_digest_version = 1 + AND credential_digest_key_id IS NOT NULL + AND credential_digest_key_id ~ '^[A-Za-z0-9_-]{1,32}$' + AND credential_request_digest IS NOT NULL + AND credential_request_digest ~ '^[0-9a-f]{64}$')); + +-- New operations must be keyed from inception. Historical unbound operations are retained, but +-- cannot bind a token candidate or advance to COMMITTED after this migration. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_delegation_credential_request_binding_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.credential_request_digest_version IS DISTINCT FROM 1 + OR NEW.credential_digest_key_id IS NULL + OR NEW.credential_request_digest IS NULL THEN + RAISE EXCEPTION 'Gameplay LOGIN requires an immutable keyed credential request binding' + USING ERRCODE = '23514', + CONSTRAINT = 'account_gameplay_delegation_credential_request_binding_required'; + END IF; + RETURN NEW; + END IF; + + IF NEW.credential_request_digest_version IS DISTINCT FROM OLD.credential_request_digest_version + OR NEW.credential_digest_key_id IS DISTINCT FROM OLD.credential_digest_key_id + OR NEW.credential_request_digest IS DISTINCT FROM OLD.credential_request_digest THEN + RAISE EXCEPTION 'Gameplay LOGIN credential request binding is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'account_gameplay_delegation_credential_request_binding_immutable'; + END IF; + + IF OLD.credential_request_digest_version IS NULL + AND (NEW.status IS DISTINCT FROM OLD.status + OR NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.signer_kid IS DISTINCT FROM OLD.signer_kid + OR NEW.signer_generation IS DISTINCT FROM OLD.signer_generation + OR NEW.pending_registry_candidate_bytes IS DISTINCT FROM OLD.pending_registry_candidate_bytes) THEN + RAISE EXCEPTION 'Historical unbound gameplay LOGIN evidence cannot advance' + USING ERRCODE = '23514', + CONSTRAINT = 'account_gameplay_delegation_unbound_request_cannot_advance'; + END IF; + + IF NEW.status = 'COMMITTED' + AND (NEW.request_digest_version IS DISTINCT FROM 2 + OR NEW.credential_request_digest_version IS DISTINCT FROM 1 + OR NEW.credential_digest_key_id IS NULL + OR NEW.credential_request_digest IS NULL) THEN + RAISE EXCEPTION 'Unbound gameplay LOGIN evidence cannot commit' + USING ERRCODE = '23514', + CONSTRAINT = 'account_gameplay_delegation_unbound_request_cannot_advance'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_gameplay_delegation_credential_request_binding_guard + BEFORE INSERT OR UPDATE ON account_gameplay_delegation_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_gameplay_delegation_credential_request_binding_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V83__account_security_event_source_guard.sql b/services/account-service/src/main/resources/db/migration/V83__account_security_event_source_guard.sql new file mode 100644 index 0000000000..59aadb67c7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V83__account_security_event_source_guard.sql @@ -0,0 +1,398 @@ +-- Extend the V40 source-head guard for the immutable V78 security-state event without changing +-- historical migrations or treating the legacy scalar Account role as canonical role authority. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_authority_source_record_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + event_row RECORD; + event_payload JSONB; + account_row RECORD; + expected_modes JSONB; + authority_row RECORD; + fence_row RECORD; + role_source_row RECORD; + operation_row RECORD; + account_state JSONB; + security_request_id UUID; +BEGIN + IF NEW.outbox_stream_key IS DISTINCT FROM OLD.outbox_stream_key + OR NEW.scope_kind IS DISTINCT FROM OLD.scope_kind + OR NEW.issuer_id IS DISTINCT FROM OLD.issuer_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.initialization_transaction_id IS DISTINCT FROM OLD.initialization_transaction_id + OR NEW.baseline_generation IS DISTINCT FROM OLD.baseline_generation + OR NEW.baseline_source_version IS DISTINCT FROM OLD.baseline_source_version + OR NEW.baseline_issuance_fence IS DISTINCT FROM OLD.baseline_issuance_fence + OR NEW.initialization_provenance IS DISTINCT FROM OLD.initialization_provenance + OR NEW.account_source_numeric_id IS DISTINCT FROM OLD.account_source_numeric_id + OR NEW.account_uuid_provenance IS DISTINCT FROM OLD.account_uuid_provenance + OR NEW.account_repository_insert_transaction_id + IS DISTINCT FROM OLD.account_repository_insert_transaction_id + OR NEW.last_outbox_sequence <> OLD.last_outbox_sequence + 1 + OR NEW.current_generation <> OLD.current_generation + 1 + OR NEW.current_source_version <> OLD.current_source_version + 1 + OR (NEW.scope_kind = 'ACCOUNT' AND ( + NEW.current_issuance_fence <> OLD.current_issuance_fence + 1 + OR NEW.current_issuance_fence_source_version <> OLD.current_issuance_fence_source_version + 1 + OR NEW.cutoff_generation IS DISTINCT FROM NEW.current_generation + OR NEW.cutoff_stream_key IS DISTINCT FROM NEW.outbox_stream_key + OR NEW.cutoff_sequence IS DISTINCT FROM NEW.last_outbox_sequence)) + OR NEW.last_event_id IS NULL OR NEW.last_event_digest IS NULL THEN + RAISE EXCEPTION 'Account authority source record must advance one exact immutable event' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_record_monotonic'; + END IF; + + SELECT event_id, event_digest, payload INTO event_row + FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.outbox_stream_key + AND outbox_sequence = NEW.last_outbox_sequence; + IF event_row.event_id IS DISTINCT FROM NEW.last_event_id + OR event_row.event_digest IS DISTINCT FROM NEW.last_event_digest THEN + RAISE EXCEPTION 'Account authority source head does not match its exact outbox event' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_link'; + END IF; + event_payload := convert_from(event_row.payload, 'UTF8')::JSONB; + IF event_payload->>'outboxStreamKey' IS DISTINCT FROM NEW.outbox_stream_key + OR event_payload->>'outboxSequence' IS DISTINCT FROM NEW.last_outbox_sequence::TEXT + OR event_payload->>'eventId' IS DISTINCT FROM NEW.last_event_id + OR event_payload->>'eventDigest' IS DISTINCT FROM NEW.last_event_digest THEN + RAISE EXCEPTION 'Account authority source event does not match its exact outbox head' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_link'; + END IF; + + IF NEW.scope_kind = 'ISSUER' THEN + IF event_payload->>'eventType' IS DISTINCT FROM 'ISSUER_AUTHORITY_CHANGED' + OR event_payload->>'issuerId' IS DISTINCT FROM NEW.issuer_id + OR event_payload->>'issuerAuthGeneration' IS DISTINCT FROM NEW.current_generation::TEXT + OR event_payload->>'sourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT THEN + RAISE EXCEPTION 'Issuer source event does not match exact advanced owner rows' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF; + ELSIF NEW.scope_kind = 'ACCOUNT' THEN + SELECT id, account_uuid_provenance, account_uuid_source_numeric_id, email_verified, + login_auth_modes, role, lifecycle_state + INTO account_row FROM accounts WHERE account_uuid = NEW.account_uuid; + SELECT COALESCE(jsonb_agg(to_jsonb(login_mode) ORDER BY login_mode), '[]'::JSONB) + INTO expected_modes + FROM unnest(string_to_array(account_row.login_auth_modes, ',')) AS modes(login_mode); + IF account_row.id IS NULL + OR account_row.id IS DISTINCT FROM NEW.account_source_numeric_id + OR account_row.account_uuid_source_numeric_id IS DISTINCT FROM NEW.account_source_numeric_id + OR account_row.account_uuid_provenance IS DISTINCT FROM NEW.account_uuid_provenance THEN + RAISE EXCEPTION 'Account source event has no exact Account identity/provenance' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_account_state'; + END IF; + + IF event_payload->>'eventType' = 'ACCOUNT_AUTHORITY_CHANGED' THEN + -- Preserve the pre-V78 Account source event contract exactly. + IF event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.current_generation::TEXT + OR event_payload->>'sourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT + OR event_payload->>'issuanceFence' IS DISTINCT FROM NEW.current_issuance_fence::TEXT + OR event_payload->>'issuanceFenceSourceVersion' IS DISTINCT FROM NEW.current_issuance_fence_source_version::TEXT + OR event_payload#>>'{accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM NEW.cutoff_generation::TEXT + OR event_payload#>>'{accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM NEW.cutoff_stream_key + OR event_payload#>>'{accountSecurityCutoff,outboxSequence}' IS DISTINCT FROM NEW.cutoff_sequence::TEXT + OR event_payload#>>'{accountState,emailVerified}' IS DISTINCT FROM account_row.email_verified::TEXT + OR event_payload#>'{accountState,loginAuthModes}' IS DISTINCT FROM expected_modes + OR event_payload#>>'{accountState,globalRole}' IS DISTINCT FROM account_row.role + OR event_payload#>>'{accountState,lifecycleState}' IS DISTINCT FROM upper(account_row.lifecycle_state) THEN + RAISE EXCEPTION 'Account source event does not match exact current Account state' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_account_state'; + END IF; + ELSIF event_payload->>'eventType' = 'ACCOUNT_SECURITY_STATE_CHANGED' THEN + -- V78 deliberately omits issuance-fence fields from its canonical event. Bind that + -- state to the actual Account authority/fence and global-role source owners instead. + SELECT generation, source_version INTO authority_row + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL; + SELECT issuance_fence, source_version INTO fence_row + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid; + SELECT account_uuid_source_numeric_id, account_uuid_provenance, + global_roles, global_role_source_version + INTO role_source_row FROM account_global_role_sources + WHERE account_uuid = NEW.account_uuid; + + account_state := event_payload->'accountState'; + IF event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-account-security-state-event/v1' + OR event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR event_payload->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT + OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.current_generation::TEXT + OR event_payload->>'sourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT + OR event_payload#>>'{accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM NEW.cutoff_generation::TEXT + OR event_payload#>>'{accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM NEW.cutoff_stream_key + OR event_payload#>>'{accountSecurityCutoff,outboxSequence}' IS DISTINCT FROM NEW.cutoff_sequence::TEXT + OR authority_row.generation IS DISTINCT FROM NEW.current_generation + OR authority_row.source_version IS DISTINCT FROM NEW.current_source_version + OR fence_row.issuance_fence IS DISTINCT FROM NEW.current_issuance_fence + OR fence_row.source_version IS DISTINCT FROM NEW.current_issuance_fence_source_version + OR role_source_row.account_uuid_source_numeric_id IS DISTINCT FROM NEW.account_source_numeric_id + OR role_source_row.account_uuid_provenance IS DISTINCT FROM NEW.account_uuid_provenance + OR role_source_row.global_role_source_version IS NULL + OR jsonb_typeof(account_state) IS DISTINCT FROM 'object' + OR (account_state - ARRAY['emailVerified','globalRoles','lifecycleState','loginAuthModes']) <> '{}'::JSONB + OR NOT (account_state ?& ARRAY['emailVerified','globalRoles','lifecycleState','loginAuthModes']) + OR account_state->'emailVerified' IS DISTINCT FROM to_jsonb(account_row.email_verified) + OR account_state->'loginAuthModes' IS DISTINCT FROM expected_modes + OR account_state->'globalRoles' IS DISTINCT FROM to_jsonb(role_source_row.global_roles) + OR account_state->>'lifecycleState' IS DISTINCT FROM upper(account_row.lifecycle_state) + OR role_source_row.global_roles IS DISTINCT FROM + (SELECT COALESCE(array_agg(DISTINCT role_name ORDER BY role_name), ARRAY[]::TEXT[]) + FROM unnest(role_source_row.global_roles) AS roles(role_name)) THEN + RAISE EXCEPTION 'Security-state source event does not match exact Account authority/fence/role owners' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF; + + IF event_payload->>'requestId' IS NULL + OR event_payload->>'requestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN + RAISE EXCEPTION 'Security-state source event request identity is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF; + security_request_id := (event_payload->>'requestId')::UUID; + SELECT * INTO operation_row FROM account_security_state_operations + WHERE request_id = security_request_id; + IF operation_row.request_id IS NULL + OR operation_row.status IS DISTINCT FROM 'COMMITTED' + OR operation_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR operation_row.account_id IS DISTINCT FROM account_row.id + OR operation_row.account_provenance IS DISTINCT FROM NEW.account_uuid_provenance + OR operation_row.event_sequence IS DISTINCT FROM NEW.last_outbox_sequence + OR operation_row.event_id IS DISTINCT FROM NEW.last_event_id + OR operation_row.event_digest IS DISTINCT FROM NEW.last_event_digest + OR operation_row.event_payload IS DISTINCT FROM event_row.payload + OR operation_row.result_generation IS DISTINCT FROM NEW.current_generation + OR operation_row.result_source_version IS DISTINCT FROM NEW.current_source_version + OR operation_row.result_fence IS DISTINCT FROM NEW.current_issuance_fence + OR operation_row.result_fence_source_version IS DISTINCT FROM NEW.current_issuance_fence_source_version + OR operation_row.result_global_role_source_version IS DISTINCT FROM role_source_row.global_role_source_version + OR convert_from(operation_row.after_state, 'UTF8')::JSONB IS DISTINCT FROM account_state + OR event_payload->>'eventId' IS DISTINCT FROM 'account-security-state-event-v1:' || security_request_id::TEXT THEN + RAISE EXCEPTION 'Security-state source event has no exact committed owner receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF; + ELSE + RAISE EXCEPTION 'Unsupported Account source event type' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF; + END IF; + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_authority_account_security_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + source_row RECORD; + event_row RECORD; + event_payload JSONB; + expected_modes JSONB; + expected_old_modes JSONB; + authority_row RECORD; + fence_row RECORD; + role_source_row RECORD; + operation_row RECORD; + before_state JSONB; + after_state JSONB; + expected_before_state JSONB; + expected_after_state JSONB; + changed_kinds TEXT[] := ARRAY[]::TEXT[]; + security_request_id UUID; +BEGIN + IF OLD.password_hash IS NOT DISTINCT FROM NEW.password_hash + AND OLD.email_verified IS NOT DISTINCT FROM NEW.email_verified + AND OLD.login_auth_modes IS NOT DISTINCT FROM NEW.login_auth_modes + AND OLD.role IS NOT DISTINCT FROM NEW.role + AND OLD.lifecycle_state IS NOT DISTINCT FROM NEW.lifecycle_state THEN + RETURN NULL; + END IF; + + SELECT source_record.* INTO source_row + FROM account_authority_source_records source_record + WHERE source_record.scope_kind = 'ACCOUNT' + AND source_record.account_uuid = NEW.account_uuid; + IF source_row.outbox_stream_key IS NULL OR source_row.last_outbox_sequence < 1 + OR source_row.last_event_id IS NULL OR source_row.last_event_digest IS NULL THEN + RAISE EXCEPTION 'Account security mutation requires an appended Account authority source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_required'; + END IF; + + SELECT payload INTO event_row + FROM account_authority_outbox_events + WHERE outbox_stream_key = source_row.outbox_stream_key + AND outbox_sequence = source_row.last_outbox_sequence + AND event_id = source_row.last_event_id + AND event_digest = source_row.last_event_digest; + event_payload := convert_from(event_row.payload, 'UTF8')::JSONB; + SELECT COALESCE(jsonb_agg(to_jsonb(login_mode) ORDER BY login_mode), '[]'::JSONB) + INTO expected_modes + FROM unnest(string_to_array(NEW.login_auth_modes, ',')) AS modes(login_mode); + + IF event_payload->>'eventType' = 'ACCOUNT_SECURITY_STATE_CHANGED' THEN + SELECT generation, source_version INTO authority_row + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL; + SELECT issuance_fence, source_version INTO fence_row + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid; + SELECT account_uuid_source_numeric_id, account_uuid_provenance, + global_roles, global_role_source_version + INTO role_source_row FROM account_global_role_sources + WHERE account_uuid = NEW.account_uuid; + SELECT COALESCE(jsonb_agg(to_jsonb(login_mode) ORDER BY login_mode), '[]'::JSONB) + INTO expected_old_modes + FROM unnest(string_to_array(OLD.login_auth_modes, ',')) AS modes(login_mode); + IF OLD.password_hash IS DISTINCT FROM NEW.password_hash + OR OLD.role IS DISTINCT FROM NEW.role THEN + RAISE EXCEPTION 'V78 security-state events cannot authorize password or scalar-role changes' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + IF event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-account-security-state-event/v1' + OR event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR event_payload->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT + OR event_payload->>'outboxStreamKey' IS DISTINCT FROM source_row.outbox_stream_key + OR event_payload->>'outboxSequence' IS DISTINCT FROM source_row.last_outbox_sequence::TEXT + OR event_payload->>'eventId' IS DISTINCT FROM source_row.last_event_id + OR event_payload->>'eventDigest' IS DISTINCT FROM source_row.last_event_digest + OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM source_row.current_generation::TEXT + OR event_payload->>'sourceVersion' IS DISTINCT FROM source_row.current_source_version::TEXT + OR event_payload#>>'{accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM source_row.cutoff_generation::TEXT + OR event_payload#>>'{accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM source_row.cutoff_stream_key + OR event_payload#>>'{accountSecurityCutoff,outboxSequence}' IS DISTINCT FROM source_row.cutoff_sequence::TEXT + OR authority_row.generation IS DISTINCT FROM source_row.current_generation + OR authority_row.source_version IS DISTINCT FROM source_row.current_source_version + OR fence_row.issuance_fence IS DISTINCT FROM source_row.current_issuance_fence + OR fence_row.source_version IS DISTINCT FROM source_row.current_issuance_fence_source_version + OR role_source_row.account_uuid_source_numeric_id IS DISTINCT FROM NEW.account_uuid_source_numeric_id + OR role_source_row.account_uuid_provenance IS DISTINCT FROM NEW.account_uuid_provenance + OR role_source_row.global_role_source_version IS NULL + OR role_source_row.global_roles IS DISTINCT FROM + (SELECT COALESCE(array_agg(DISTINCT role_name ORDER BY role_name), ARRAY[]::TEXT[]) + FROM unnest(role_source_row.global_roles) AS roles(role_name)) THEN + RAISE EXCEPTION 'V78 security-state event does not match current Account source owners' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + + IF event_payload->>'requestId' IS NULL + OR event_payload->>'requestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN + RAISE EXCEPTION 'V78 security-state event request identity is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + security_request_id := (event_payload->>'requestId')::UUID; + SELECT * INTO operation_row FROM account_security_state_operations + WHERE request_id = security_request_id; + IF operation_row.request_id IS NULL + OR operation_row.status IS DISTINCT FROM 'COMMITTED' + OR operation_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR operation_row.account_id IS DISTINCT FROM NEW.id + OR operation_row.account_provenance IS DISTINCT FROM NEW.account_uuid_provenance + OR operation_row.event_sequence IS DISTINCT FROM source_row.last_outbox_sequence + OR operation_row.event_id IS DISTINCT FROM source_row.last_event_id + OR operation_row.event_digest IS DISTINCT FROM source_row.last_event_digest + OR operation_row.event_payload IS DISTINCT FROM event_row.payload + OR operation_row.expected_generation + 1 IS DISTINCT FROM source_row.current_generation + OR operation_row.expected_source_version + 1 IS DISTINCT FROM source_row.current_source_version + OR operation_row.expected_fence + 1 IS DISTINCT FROM source_row.current_issuance_fence + OR operation_row.expected_fence_source_version + 1 IS DISTINCT FROM source_row.current_issuance_fence_source_version + OR operation_row.checkpoint_sequence + 1 IS DISTINCT FROM source_row.last_outbox_sequence + OR operation_row.result_generation IS DISTINCT FROM source_row.current_generation + OR operation_row.result_source_version IS DISTINCT FROM source_row.current_source_version + OR operation_row.result_fence IS DISTINCT FROM source_row.current_issuance_fence + OR operation_row.result_fence_source_version IS DISTINCT FROM source_row.current_issuance_fence_source_version + OR operation_row.result_global_role_source_version IS DISTINCT FROM role_source_row.global_role_source_version + OR event_payload->>'eventId' IS DISTINCT FROM 'account-security-state-event-v1:' || security_request_id::TEXT THEN + RAISE EXCEPTION 'V78 security-state event has no exact committed Account operation receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + + before_state := convert_from(operation_row.before_state, 'UTF8')::JSONB; + after_state := convert_from(operation_row.after_state, 'UTF8')::JSONB; + expected_before_state := jsonb_build_object( + 'emailVerified', OLD.email_verified, + 'globalRoles', to_jsonb(role_source_row.global_roles), + 'lifecycleState', upper(OLD.lifecycle_state), + 'loginAuthModes', expected_old_modes); + expected_after_state := jsonb_build_object( + 'emailVerified', NEW.email_verified, + 'globalRoles', to_jsonb(role_source_row.global_roles), + 'lifecycleState', upper(NEW.lifecycle_state), + 'loginAuthModes', expected_modes); + IF before_state IS DISTINCT FROM expected_before_state + OR after_state IS DISTINCT FROM expected_after_state + OR event_payload->'accountState' IS DISTINCT FROM after_state THEN + RAISE EXCEPTION 'V78 security-state receipt does not bind the exact original and current Account states' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + + IF before_state->'emailVerified' IS DISTINCT FROM after_state->'emailVerified' THEN + changed_kinds := array_append(changed_kinds, 'EMAIL_LOGIN_ELIGIBILITY_CHANGED'); + END IF; + IF before_state->'globalRoles' IS DISTINCT FROM after_state->'globalRoles' THEN + changed_kinds := array_append(changed_kinds, 'GLOBAL_ROLE_CHANGED'); + END IF; + IF before_state->'lifecycleState' IS DISTINCT FROM after_state->'lifecycleState' THEN + changed_kinds := array_append(changed_kinds, 'LIFECYCLE_STATE_CHANGED'); + END IF; + IF before_state->'loginAuthModes' IS DISTINCT FROM after_state->'loginAuthModes' THEN + changed_kinds := array_append(changed_kinds, 'LOGIN_AUTH_MODES_CHANGED'); + END IF; + IF cardinality(changed_kinds) = 0 + OR changed_kinds IS DISTINCT FROM operation_row.mutation_kinds + OR changed_kinds IS DISTINCT FROM ARRAY( + SELECT jsonb_array_elements_text(event_payload->'mutationKinds')) THEN + RAISE EXCEPTION 'V78 security-state receipt mutation families differ from the original states' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + RETURN NULL; + END IF; + + -- Keep the legacy Account-auth event checks and mutation-family interpretation unchanged. + SELECT source_record.* INTO source_row + FROM account_authority_source_records source_record + WHERE source_record.scope_kind = 'ACCOUNT' + AND source_record.account_uuid = NEW.account_uuid; + IF event_payload IS NULL + OR event_payload->>'eventType' IS DISTINCT FROM 'ACCOUNT_AUTHORITY_CHANGED' + OR event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM source_row.current_generation::TEXT + OR event_payload->>'sourceVersion' IS DISTINCT FROM source_row.current_source_version::TEXT + OR event_payload->>'issuanceFence' IS DISTINCT FROM source_row.current_issuance_fence::TEXT + OR event_payload->>'issuanceFenceSourceVersion' IS DISTINCT FROM source_row.current_issuance_fence_source_version::TEXT + OR event_payload#>>'{accountState,emailVerified}' IS DISTINCT FROM NEW.email_verified::TEXT + OR event_payload#>'{accountState,loginAuthModes}' IS DISTINCT FROM expected_modes + OR event_payload#>>'{accountState,globalRole}' IS DISTINCT FROM NEW.role + OR event_payload#>>'{accountState,lifecycleState}' IS DISTINCT FROM upper(NEW.lifecycle_state) + OR (OLD.password_hash IS DISTINCT FROM NEW.password_hash + AND NOT (event_payload->'mutationKinds' ? 'PASSWORD_RESET')) + OR (OLD.password_hash IS NOT DISTINCT FROM NEW.password_hash + AND (event_payload->'mutationKinds' ? 'PASSWORD_RESET')) + OR (OLD.email_verified IS DISTINCT FROM NEW.email_verified + AND NOT (event_payload->'mutationKinds' ? 'EMAIL_LOGIN_ELIGIBILITY_CHANGED')) + OR (OLD.email_verified IS NOT DISTINCT FROM NEW.email_verified + AND (event_payload->'mutationKinds' ? 'EMAIL_LOGIN_ELIGIBILITY_CHANGED')) + OR (OLD.login_auth_modes IS DISTINCT FROM NEW.login_auth_modes + AND NOT (event_payload->'mutationKinds' ? 'LOGIN_AUTH_MODES_CHANGED')) + OR (OLD.login_auth_modes IS NOT DISTINCT FROM NEW.login_auth_modes + AND (event_payload->'mutationKinds' ? 'LOGIN_AUTH_MODES_CHANGED')) + OR (OLD.role IS DISTINCT FROM NEW.role + AND NOT (event_payload->'mutationKinds' ? 'GLOBAL_ROLE_CHANGED')) + OR (OLD.role IS NOT DISTINCT FROM NEW.role + AND (event_payload->'mutationKinds' ? 'GLOBAL_ROLE_CHANGED')) + OR (OLD.lifecycle_state IS DISTINCT FROM NEW.lifecycle_state + AND NOT (event_payload->'mutationKinds' ? 'LIFECYCLE_STATE_CHANGED')) + OR (OLD.lifecycle_state IS NOT DISTINCT FROM NEW.lifecycle_state + AND (event_payload->'mutationKinds' ? 'LIFECYCLE_STATE_CHANGED')) THEN + RAISE EXCEPTION 'Account security mutation differs from its exact current source event' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + RETURN NULL; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V84.1__account_auth_evidence_checkpoint_key_count.sql b/services/account-service/src/main/resources/db/migration/V84.1__account_auth_evidence_checkpoint_key_count.sql new file mode 100644 index 0000000000..a9541e87bf --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V84.1__account_auth_evidence_checkpoint_key_count.sql @@ -0,0 +1,231 @@ +-- Repair the existing exact checkpoint shape checks with PostgreSQL-supported JSONB key counts. +-- Retain the V46 migration checksum, populated owner rows, immutable bundles, and all guard predicates. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_auth_evidence_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; + account_row RECORD; + bundle JSONB; + checkpoint JSONB; + expected_account_stream TEXT; + expected_issuer_stream TEXT := 'account:auth-authority:v1:issuer/firemud-account-service'; + capture_transaction_id TEXT; + allocated_source_fence BIGINT; + allocated_operation_id UUID; + allocated_transaction_id TEXT; + checkpoint_count INTEGER; + matched_account_checkpoint BOOLEAN := FALSE; + matched_issuer_checkpoint BOOLEAN := FALSE; + checkpoint_sequence BIGINT; + stream_sequence BIGINT; + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + current_account_generation BIGINT; + current_account_source_version BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + event_row RECORD; +BEGIN + bundle := convert_from(NEW.canonical_bundle_bytes, 'UTF8')::jsonb; + capture_transaction_id := pg_current_xact_id()::text; + + SELECT last_source_fence, last_operation_id, last_transaction_id + INTO allocated_source_fence, allocated_operation_id, allocated_transaction_id + FROM account_gameplay_auth_evidence_source_fence + WHERE allocator_id = TRUE + FOR UPDATE; + IF allocated_source_fence IS NULL + OR allocated_source_fence <= 0 + OR NEW.source_fence IS DISTINCT FROM allocated_source_fence::text + OR allocated_operation_id IS DISTINCT FROM NEW.operation_id + OR allocated_transaction_id IS DISTINCT FROM capture_transaction_id + OR NEW.source_version IS DISTINCT FROM capture_transaction_id + OR NEW.linearization IS DISTINCT FROM capture_transaction_id THEN + RAISE EXCEPTION 'Account auth-evidence bundle reference is not the exact persisted capture allocation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_capture_reference'; + END IF; + + -- Match the Account owner lock order used by source snapshots and issuance: Account row, + -- issuer/account generations, issuance fence, then the operation row. The Account identity is + -- read-only here, so FOR SHARE also avoids upgrading the source reader's existing lock. + SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id + INTO account_row + FROM accounts + WHERE account_uuid = NEW.account_uuid + FOR SHARE; + IF account_row.id IS NULL + OR account_row.id <> account_row.account_uuid_source_numeric_id + OR account_row.account_uuid_provenance NOT IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT') + OR bundle#>>'{accountIdentitySource,sourceRowId}' IS DISTINCT FROM account_row.id::text + OR bundle#>>'{accountIdentitySource,sourceNumericId}' IS DISTINCT FROM account_row.account_uuid_source_numeric_id::text + OR bundle#>>'{accountIdentitySource,provenance}' IS DISTINCT FROM account_row.account_uuid_provenance THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the Account identity row' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_identity_match'; + END IF; + + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + + SELECT * INTO operation_row + FROM account_gameplay_delegation_issuance_operations + WHERE operation_id = NEW.operation_id + FOR UPDATE; + IF operation_row.operation_id IS NULL + OR operation_row.request_id <> NEW.request_id + OR operation_row.account_uuid <> NEW.account_uuid + OR operation_row.status <> 'PENDING' + OR bundle->>'schema' IS DISTINCT FROM NEW.bundle_schema + OR bundle->>'profile' IS DISTINCT FROM 'game-session-account-delegation' + OR bundle->>'issuer' IS DISTINCT FROM 'firemud-account-service' + OR bundle->>'audience' IS DISTINCT FROM 'account-service' + OR bundle#>>'{bundleRef,bundleVersion}' IS DISTINCT FROM NEW.bundle_version + OR bundle#>>'{bundleRef,sourceVersion}' IS DISTINCT FROM NEW.source_version + OR bundle#>>'{bundleRef,sourceFence}' IS DISTINCT FROM NEW.source_fence + OR bundle#>>'{bundleRef,linearization}' IS DISTINCT FROM NEW.linearization + OR bundle#>>'{scope,kind}' IS DISTINCT FROM 'account' + OR bundle#>>'{scope,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR jsonb_typeof(bundle#>'{scope,tenantIds}') IS DISTINCT FROM 'array' + OR COALESCE(jsonb_array_length(bundle#>'{scope,tenantIds}'), -1) <> 0 + OR bundle#>>'{operation,operationId}' IS DISTINCT FROM NEW.operation_id::text + OR bundle#>>'{operation,requestId}' IS DISTINCT FROM NEW.request_id::text + OR bundle#>>'{operation,requestDigest}' IS DISTINCT FROM operation_row.request_digest + OR bundle#>>'{operation,callerWorkload}' IS DISTINCT FROM operation_row.caller_workload + OR bundle#>>'{operation,callerContextId}' IS DISTINCT FROM operation_row.caller_context_id::text + OR bundle#>>'{operation,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR bundle#>>'{tokenIdentity,jti}' IS DISTINCT FROM operation_row.token_jti::text + OR bundle#>>'{tokenIdentity,tokenGeneration}' IS DISTINCT FROM operation_row.token_generation::text + OR bundle#>>'{tokenIdentity,iat}' IS DISTINCT FROM operation_row.issued_at_epoch_second::text + OR bundle#>>'{tokenIdentity,nbf}' IS DISTINCT FROM operation_row.not_before_epoch_second::text + OR bundle#>>'{tokenIdentity,exp}' IS DISTINCT FROM operation_row.expires_at_epoch_second::text + OR bundle->'authorityTuple' IS DISTINCT FROM + convert_from(operation_row.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR bundle->'membershipVersion' IS DISTINCT FROM + convert_from(operation_row.membership_version_canonical_bytes, 'UTF8')::jsonb + OR bundle->>'issuanceFence' IS DISTINCT FROM operation_row.issuance_fence::text + OR bundle->'authoritySourceVersions' IS DISTINCT FROM + jsonb_build_object( + 'issuerSourceVersion', operation_row.authority_issuer_source_version::text, + 'accountSourceVersion', operation_row.authority_account_source_version::text, + 'issuanceFenceSourceVersion', operation_row.issuance_fence_source_version::text) + OR NEW.issuance_fence <> operation_row.issuance_fence::text THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the exact pending operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_operation_match'; + END IF; + + IF current_issuer_generation IS NULL + OR current_account_generation IS NULL + OR current_issuance_fence IS NULL + OR operation_row.authority_issuer_generation <> current_issuer_generation + OR operation_row.authority_issuer_source_version <> current_issuer_source_version + OR operation_row.authority_account_generation <> current_account_generation + OR operation_row.authority_account_source_version <> current_account_source_version + OR operation_row.issuance_fence <> current_issuance_fence + OR operation_row.issuance_fence_source_version <> current_fence_source_version THEN + RAISE EXCEPTION 'Account auth-evidence bundle is stale against current authority' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_current_authority'; + END IF; + + expected_account_stream := 'account:auth-authority:v1:account/' || NEW.account_uuid::text; + IF jsonb_typeof(bundle->'outboxCheckpoints') <> 'array' + OR jsonb_array_length(bundle->'outboxCheckpoints') <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle requires exact issuer and Account checkpoints' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT count(*) INTO checkpoint_count FROM jsonb_array_elements(bundle->'outboxCheckpoints'); + IF checkpoint_count <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are ambiguous' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + FOR checkpoint IN SELECT value FROM jsonb_array_elements(bundle->'outboxCheckpoints') LOOP + IF checkpoint->>'outboxStreamKey' = expected_account_stream THEN + matched_account_checkpoint := TRUE; + ELSIF checkpoint->>'outboxStreamKey' = expected_issuer_stream THEN + matched_issuer_checkpoint := TRUE; + ELSE + RAISE EXCEPTION 'Account auth-evidence bundle has an out-of-scope checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF COALESCE(checkpoint->>'outboxSequence', '') !~ '^(0|[1-9][0-9]{0,18})$' THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint sequence is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + checkpoint_sequence := (checkpoint->>'outboxSequence')::BIGINT; + SELECT last_sequence INTO stream_sequence + FROM account_authority_outbox_streams + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + FOR SHARE; + IF checkpoint_sequence = 0 THEN + IF (SELECT count(*) FROM jsonb_object_keys(checkpoint)) <> 2 + OR checkpoint ? 'sourceEventId' + OR checkpoint ? 'sourceEventDigest' + OR stream_sequence IS DISTINCT FROM 0 + OR EXISTS ( + SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey') THEN + RAISE EXCEPTION 'Account zero checkpoint is not an exact initialized empty stream' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + ELSE + IF (SELECT count(*) FROM jsonb_object_keys(checkpoint)) <> 4 + OR checkpoint->>'sourceEventId' IS NULL + OR checkpoint->>'sourceEventDigest' IS NULL THEN + RAISE EXCEPTION 'Account positive checkpoint is missing exact event identity' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT event_id, event_digest INTO event_row + FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + AND outbox_sequence = checkpoint_sequence; + IF stream_sequence IS DISTINCT FROM checkpoint_sequence + OR event_row.event_id IS NULL + OR checkpoint->>'sourceEventId' <> event_row.event_id + OR checkpoint->>'sourceEventDigest' <> event_row.event_digest THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not match a current stored event' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + END IF; + END LOOP; + IF NOT matched_account_checkpoint OR NOT matched_issuer_checkpoint THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are incomplete' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF bundle#>'{authorityTuple,accountSecurityCutoff}' IS NOT NULL THEN + IF bundle#>>'{authorityTuple,accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM expected_account_stream + OR bundle#>>'{authorityTuple,accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM + operation_row.authority_account_generation::text + OR COALESCE(bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}', '') !~ '^[1-9][0-9]{0,18}$' THEN + RAISE EXCEPTION 'Account auth-evidence security cutoff is malformed or out of scope' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + IF (bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}')::BIGINT > ( + SELECT (item->>'outboxSequence')::BIGINT + FROM jsonb_array_elements(bundle->'outboxCheckpoints') AS item + WHERE item->>'outboxStreamKey' = expected_account_stream) THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not cover its cutoff' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] + diff --git a/services/account-service/src/main/resources/db/migration/V84.2__account_auth_evidence_shared_issuer_guard.sql b/services/account-service/src/main/resources/db/migration/V84.2__account_auth_evidence_shared_issuer_guard.sql new file mode 100644 index 0000000000..bec4ba5947 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V84.2__account_auth_evidence_shared_issuer_guard.sql @@ -0,0 +1,232 @@ +-- Preserve shared issuer locking during exact auth-evidence bundle capture. +-- Retain prior migration checksums, populated owner rows, immutable bundles, and all guard predicates. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_auth_evidence_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; + account_row RECORD; + bundle JSONB; + checkpoint JSONB; + expected_account_stream TEXT; + expected_issuer_stream TEXT := 'account:auth-authority:v1:issuer/firemud-account-service'; + capture_transaction_id TEXT; + allocated_source_fence BIGINT; + allocated_operation_id UUID; + allocated_transaction_id TEXT; + checkpoint_count INTEGER; + matched_account_checkpoint BOOLEAN := FALSE; + matched_issuer_checkpoint BOOLEAN := FALSE; + checkpoint_sequence BIGINT; + stream_sequence BIGINT; + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + current_account_generation BIGINT; + current_account_source_version BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + event_row RECORD; +BEGIN + bundle := convert_from(NEW.canonical_bundle_bytes, 'UTF8')::jsonb; + capture_transaction_id := pg_current_xact_id()::text; + + SELECT last_source_fence, last_operation_id, last_transaction_id + INTO allocated_source_fence, allocated_operation_id, allocated_transaction_id + FROM account_gameplay_auth_evidence_source_fence + WHERE allocator_id = TRUE + FOR UPDATE; + IF allocated_source_fence IS NULL + OR allocated_source_fence <= 0 + OR NEW.source_fence IS DISTINCT FROM allocated_source_fence::text + OR allocated_operation_id IS DISTINCT FROM NEW.operation_id + OR allocated_transaction_id IS DISTINCT FROM capture_transaction_id + OR NEW.source_version IS DISTINCT FROM capture_transaction_id + OR NEW.linearization IS DISTINCT FROM capture_transaction_id THEN + RAISE EXCEPTION 'Account auth-evidence bundle reference is not the exact persisted capture allocation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_capture_reference'; + END IF; + + -- Match the Account owner lock order used by source snapshots and issuance: Account row, + -- issuer/account generations, issuance fence, then the operation row. The Account identity is + -- read-only here, so FOR SHARE also avoids upgrading the source reader's existing lock. + SELECT id, account_uuid, account_uuid_provenance, account_uuid_source_numeric_id + INTO account_row + FROM accounts + WHERE account_uuid = NEW.account_uuid + FOR SHARE; + IF account_row.id IS NULL + OR account_row.id <> account_row.account_uuid_source_numeric_id + OR account_row.account_uuid_provenance NOT IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT') + OR bundle#>>'{accountIdentitySource,sourceRowId}' IS DISTINCT FROM account_row.id::text + OR bundle#>>'{accountIdentitySource,sourceNumericId}' IS DISTINCT FROM account_row.account_uuid_source_numeric_id::text + OR bundle#>>'{accountIdentitySource,provenance}' IS DISTINCT FROM account_row.account_uuid_provenance THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the Account identity row' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_identity_match'; + END IF; + + -- This guard only reads issuer authority. Keep the source reader's shared lock so concurrent + -- captures cannot deadlock while one waits for the account generation and another inserts. + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR SHARE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + + SELECT * INTO operation_row + FROM account_gameplay_delegation_issuance_operations + WHERE operation_id = NEW.operation_id + FOR UPDATE; + IF operation_row.operation_id IS NULL + OR operation_row.request_id <> NEW.request_id + OR operation_row.account_uuid <> NEW.account_uuid + OR operation_row.status <> 'PENDING' + OR bundle->>'schema' IS DISTINCT FROM NEW.bundle_schema + OR bundle->>'profile' IS DISTINCT FROM 'game-session-account-delegation' + OR bundle->>'issuer' IS DISTINCT FROM 'firemud-account-service' + OR bundle->>'audience' IS DISTINCT FROM 'account-service' + OR bundle#>>'{bundleRef,bundleVersion}' IS DISTINCT FROM NEW.bundle_version + OR bundle#>>'{bundleRef,sourceVersion}' IS DISTINCT FROM NEW.source_version + OR bundle#>>'{bundleRef,sourceFence}' IS DISTINCT FROM NEW.source_fence + OR bundle#>>'{bundleRef,linearization}' IS DISTINCT FROM NEW.linearization + OR bundle#>>'{scope,kind}' IS DISTINCT FROM 'account' + OR bundle#>>'{scope,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR jsonb_typeof(bundle#>'{scope,tenantIds}') IS DISTINCT FROM 'array' + OR COALESCE(jsonb_array_length(bundle#>'{scope,tenantIds}'), -1) <> 0 + OR bundle#>>'{operation,operationId}' IS DISTINCT FROM NEW.operation_id::text + OR bundle#>>'{operation,requestId}' IS DISTINCT FROM NEW.request_id::text + OR bundle#>>'{operation,requestDigest}' IS DISTINCT FROM operation_row.request_digest + OR bundle#>>'{operation,callerWorkload}' IS DISTINCT FROM operation_row.caller_workload + OR bundle#>>'{operation,callerContextId}' IS DISTINCT FROM operation_row.caller_context_id::text + OR bundle#>>'{operation,accountId}' IS DISTINCT FROM NEW.account_uuid::text + OR bundle#>>'{tokenIdentity,jti}' IS DISTINCT FROM operation_row.token_jti::text + OR bundle#>>'{tokenIdentity,tokenGeneration}' IS DISTINCT FROM operation_row.token_generation::text + OR bundle#>>'{tokenIdentity,iat}' IS DISTINCT FROM operation_row.issued_at_epoch_second::text + OR bundle#>>'{tokenIdentity,nbf}' IS DISTINCT FROM operation_row.not_before_epoch_second::text + OR bundle#>>'{tokenIdentity,exp}' IS DISTINCT FROM operation_row.expires_at_epoch_second::text + OR bundle->'authorityTuple' IS DISTINCT FROM + convert_from(operation_row.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR bundle->'membershipVersion' IS DISTINCT FROM + convert_from(operation_row.membership_version_canonical_bytes, 'UTF8')::jsonb + OR bundle->>'issuanceFence' IS DISTINCT FROM operation_row.issuance_fence::text + OR bundle->'authoritySourceVersions' IS DISTINCT FROM + jsonb_build_object( + 'issuerSourceVersion', operation_row.authority_issuer_source_version::text, + 'accountSourceVersion', operation_row.authority_account_source_version::text, + 'issuanceFenceSourceVersion', operation_row.issuance_fence_source_version::text) + OR NEW.issuance_fence <> operation_row.issuance_fence::text THEN + RAISE EXCEPTION 'Account auth-evidence bundle does not match the exact pending operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_operation_match'; + END IF; + + IF current_issuer_generation IS NULL + OR current_account_generation IS NULL + OR current_issuance_fence IS NULL + OR operation_row.authority_issuer_generation <> current_issuer_generation + OR operation_row.authority_issuer_source_version <> current_issuer_source_version + OR operation_row.authority_account_generation <> current_account_generation + OR operation_row.authority_account_source_version <> current_account_source_version + OR operation_row.issuance_fence <> current_issuance_fence + OR operation_row.issuance_fence_source_version <> current_fence_source_version THEN + RAISE EXCEPTION 'Account auth-evidence bundle is stale against current authority' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_current_authority'; + END IF; + + expected_account_stream := 'account:auth-authority:v1:account/' || NEW.account_uuid::text; + IF jsonb_typeof(bundle->'outboxCheckpoints') <> 'array' + OR jsonb_array_length(bundle->'outboxCheckpoints') <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle requires exact issuer and Account checkpoints' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT count(*) INTO checkpoint_count FROM jsonb_array_elements(bundle->'outboxCheckpoints'); + IF checkpoint_count <> 2 THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are ambiguous' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + FOR checkpoint IN SELECT value FROM jsonb_array_elements(bundle->'outboxCheckpoints') LOOP + IF checkpoint->>'outboxStreamKey' = expected_account_stream THEN + matched_account_checkpoint := TRUE; + ELSIF checkpoint->>'outboxStreamKey' = expected_issuer_stream THEN + matched_issuer_checkpoint := TRUE; + ELSE + RAISE EXCEPTION 'Account auth-evidence bundle has an out-of-scope checkpoint' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF COALESCE(checkpoint->>'outboxSequence', '') !~ '^(0|[1-9][0-9]{0,18})$' THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint sequence is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + checkpoint_sequence := (checkpoint->>'outboxSequence')::BIGINT; + SELECT last_sequence INTO stream_sequence + FROM account_authority_outbox_streams + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + FOR SHARE; + IF checkpoint_sequence = 0 THEN + IF (SELECT count(*) FROM jsonb_object_keys(checkpoint)) <> 2 + OR checkpoint ? 'sourceEventId' + OR checkpoint ? 'sourceEventDigest' + OR stream_sequence IS DISTINCT FROM 0 + OR EXISTS ( + SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey') THEN + RAISE EXCEPTION 'Account zero checkpoint is not an exact initialized empty stream' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + ELSE + IF (SELECT count(*) FROM jsonb_object_keys(checkpoint)) <> 4 + OR checkpoint->>'sourceEventId' IS NULL + OR checkpoint->>'sourceEventDigest' IS NULL THEN + RAISE EXCEPTION 'Account positive checkpoint is missing exact event identity' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + SELECT event_id, event_digest INTO event_row + FROM account_authority_outbox_events + WHERE outbox_stream_key = checkpoint->>'outboxStreamKey' + AND outbox_sequence = checkpoint_sequence; + IF stream_sequence IS DISTINCT FROM checkpoint_sequence + OR event_row.event_id IS NULL + OR checkpoint->>'sourceEventId' <> event_row.event_id + OR checkpoint->>'sourceEventDigest' <> event_row.event_digest THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not match a current stored event' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + END IF; + END LOOP; + IF NOT matched_account_checkpoint OR NOT matched_issuer_checkpoint THEN + RAISE EXCEPTION 'Account auth-evidence bundle checkpoints are incomplete' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_checkpoints'; + END IF; + IF bundle#>'{authorityTuple,accountSecurityCutoff}' IS NOT NULL THEN + IF bundle#>>'{authorityTuple,accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM expected_account_stream + OR bundle#>>'{authorityTuple,accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM + operation_row.authority_account_generation::text + OR COALESCE(bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}', '') !~ '^[1-9][0-9]{0,18}$' THEN + RAISE EXCEPTION 'Account auth-evidence security cutoff is malformed or out of scope' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + IF (bundle#>>'{authorityTuple,accountSecurityCutoff,outboxSequence}')::BIGINT > ( + SELECT (item->>'outboxSequence')::BIGINT + FROM jsonb_array_elements(bundle->'outboxCheckpoints') AS item + WHERE item->>'outboxStreamKey' = expected_account_stream) THEN + RAISE EXCEPTION 'Account auth-evidence checkpoint does not cover its cutoff' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_auth_evidence_cutoff'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V84.3__account_gameplay_commit_bundle_source_fence.sql b/services/account-service/src/main/resources/db/migration/V84.3__account_gameplay_commit_bundle_source_fence.sql new file mode 100644 index 0000000000..5763382e78 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V84.3__account_gameplay_commit_bundle_source_fence.sql @@ -0,0 +1,309 @@ +-- Align the commit-proof bundle reference with the immutable V46/V84.2 source-fence contract. +-- Preserve the original transition and evidence predicates; accept only the exact stored fence. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_delegation_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + proof JSONB; + bundle_row RECORD; + envelope_row RECORD; + identity_proof JSONB; + registry JSONB; + bundle JSONB; + authority JSONB; + signer JSONB; + envelope JSONB; + proof_key_count INTEGER; + identity_key_count INTEGER; + registry_key_count INTEGER; + bundle_key_count INTEGER; + authority_key_count INTEGER; + signer_key_count INTEGER; + envelope_key_count INTEGER; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status IS DISTINCT FROM 'PENDING' + OR NEW.token_hash IS NOT NULL + OR NEW.signer_kid IS NOT NULL + OR NEW.signer_generation IS NOT NULL + OR NEW.pending_registry_candidate_bytes IS NOT NULL + OR NEW.commit_proof_version IS NOT NULL + OR NEW.commit_proof_sha256 IS NOT NULL + OR NEW.commit_proof_canonical_bytes IS NOT NULL + OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Account gameplay delegation issuance must begin as unbound PENDING intent' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_initial_pending_only'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account gameplay delegation issuance evidence cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + + IF NEW.operation_id IS DISTINCT FROM OLD.operation_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.caller_workload IS DISTINCT FROM OLD.caller_workload + OR NEW.caller_context_id IS DISTINCT FROM OLD.caller_context_id + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.token_jti IS DISTINCT FROM OLD.token_jti + OR NEW.token_generation IS DISTINCT FROM OLD.token_generation + OR NEW.issued_at_epoch_second IS DISTINCT FROM OLD.issued_at_epoch_second + OR NEW.not_before_epoch_second IS DISTINCT FROM OLD.not_before_epoch_second + OR NEW.expires_at_epoch_second IS DISTINCT FROM OLD.expires_at_epoch_second + OR NEW.authority_issuer_generation IS DISTINCT FROM OLD.authority_issuer_generation + OR NEW.authority_issuer_source_version IS DISTINCT FROM OLD.authority_issuer_source_version + OR NEW.authority_account_generation IS DISTINCT FROM OLD.authority_account_generation + OR NEW.authority_account_source_version IS DISTINCT FROM OLD.authority_account_source_version + OR NEW.issuance_fence IS DISTINCT FROM OLD.issuance_fence + OR NEW.issuance_fence_source_version IS DISTINCT FROM OLD.issuance_fence_source_version + OR NEW.authority_tuple_canonical_bytes IS DISTINCT FROM OLD.authority_tuple_canonical_bytes + OR NEW.membership_version_canonical_bytes IS DISTINCT FROM OLD.membership_version_canonical_bytes + OR NEW.authority_source_versions_canonical_bytes IS DISTINCT FROM OLD.authority_source_versions_canonical_bytes + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Account gameplay delegation intent is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_operation_immutable'; + END IF; + + IF OLD.status = 'COMMITTED' + OR OLD.commit_proof_version IS NOT NULL + OR OLD.commit_proof_sha256 IS NOT NULL + OR OLD.commit_proof_canonical_bytes IS NOT NULL + OR OLD.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Account gameplay delegation commit evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_immutable'; + END IF; + + IF NEW.status = 'PENDING' THEN + IF NEW.commit_proof_version IS NOT NULL + OR NEW.commit_proof_sha256 IS NOT NULL + OR NEW.commit_proof_canonical_bytes IS NOT NULL + OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Pending issuance cannot carry commit proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + IF OLD.token_hash IS NOT NULL OR OLD.signer_kid IS NOT NULL + OR OLD.signer_generation IS NOT NULL OR OLD.pending_registry_candidate_bytes IS NOT NULL + OR NEW.token_hash IS NULL OR NEW.signer_kid IS NULL + OR NEW.signer_generation IS NULL OR NEW.pending_registry_candidate_bytes IS NULL THEN + RAISE EXCEPTION 'Account gameplay delegation token identity may be bound exactly once' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_candidate_one_way'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status IS DISTINCT FROM 'COMMITTED' OR OLD.status IS DISTINCT FROM 'PENDING' + OR OLD.token_hash IS NULL OR OLD.signer_kid IS NULL + OR OLD.signer_generation IS NULL OR OLD.pending_registry_candidate_bytes IS NULL + OR NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.signer_kid IS DISTINCT FROM OLD.signer_kid + OR NEW.signer_generation IS DISTINCT FROM OLD.signer_generation + OR NEW.pending_registry_candidate_bytes IS DISTINCT FROM OLD.pending_registry_candidate_bytes + OR NEW.commit_proof_version IS DISTINCT FROM 1 + OR NEW.commit_proof_sha256 IS NULL + OR NEW.commit_proof_sha256 !~ '^[0-9a-f]{64}$' + OR NEW.commit_proof_canonical_bytes IS NULL + OR NEW.committed_at IS NULL THEN + RAISE EXCEPTION 'Account gameplay delegation COMMITTED transition is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + + proof := convert_from(NEW.commit_proof_canonical_bytes, 'UTF8')::jsonb; + IF jsonb_typeof(proof) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof is not a canonical object' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + SELECT count(*) INTO proof_key_count FROM jsonb_object_keys(proof); + IF proof_key_count <> 9 THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has unknown or missing fields' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + + identity_proof := proof->'identity'; + registry := proof->'registry'; + bundle := proof->'bundle'; + authority := proof->'authority'; + signer := proof->'signer'; + envelope := proof->'envelope'; + + IF jsonb_typeof(identity_proof) IS DISTINCT FROM 'object' + OR jsonb_typeof(registry) IS DISTINCT FROM 'object' + OR jsonb_typeof(bundle) IS DISTINCT FROM 'object' + OR jsonb_typeof(authority) IS DISTINCT FROM 'object' + OR jsonb_typeof(signer) IS DISTINCT FROM 'object' + OR jsonb_typeof(envelope) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof fields must be objects' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_shape'; + END IF; + SELECT count(*) INTO identity_key_count FROM jsonb_object_keys(identity_proof); + SELECT count(*) INTO registry_key_count FROM jsonb_object_keys(registry); + SELECT count(*) INTO bundle_key_count FROM jsonb_object_keys(bundle); + SELECT count(*) INTO authority_key_count FROM jsonb_object_keys(authority); + SELECT count(*) INTO signer_key_count FROM jsonb_object_keys(signer); + SELECT count(*) INTO envelope_key_count FROM jsonb_object_keys(envelope); + + IF identity_key_count <> 12 + OR NOT (identity_proof ?& ARRAY[ + 'operationId', 'requestId', 'accountId', 'requestDigest', 'callerWorkload', + 'callerContextId', 'tokenJti', 'tokenGeneration', 'issuedAtEpochSecond', + 'notBeforeEpochSecond', 'expiresAtEpochSecond', 'tokenSha256']) + OR registry_key_count <> 16 + OR NOT (registry ?& ARRAY[ + 'state', 'registryVersion', 'tokenKey', 'tokenHash', 'kid', 'signerGeneration', + 'operationId', 'requestId', 'requestDigest', 'absoluteExpiryMillis', + 'localAofCount', 'replicaAofCount', 'outcome', 'canonicalRecordSha256', + 'evidenceBundleSha256', 'aclIdentity']) + OR bundle_key_count <> 5 + OR NOT (bundle ?& ARRAY[ + 'bundleVersion', 'sourceVersion', 'sourceFence', 'linearization', 'canonicalSha256']) + OR jsonb_typeof(bundle->'sourceFence') IS DISTINCT FROM 'string' + OR bundle->>'sourceFence' IS NULL + OR bundle->>'sourceFence' !~ '^[1-9][0-9]{0,18}$' + OR authority_key_count <> 12 + OR NOT (authority ?& ARRAY[ + 'issuerGeneration', 'issuerSourceVersion', 'accountGeneration', + 'accountSourceVersion', 'issuanceFence', 'issuanceFenceSourceVersion', + 'authorityTuple', 'authoritySourceVersions', 'issuerProjectionGeneration', + 'accountProjectionGeneration', 'issuerProjectionSha256', 'accountProjectionSha256']) + OR signer_key_count <> 7 + OR NOT (signer ?& ARRAY[ + 'promotionStatus', 'promotionOperationId', 'generationOperationId', + 'targetKid', 'targetGeneration', 'correspondenceSha256', 'correspondence']) + OR envelope_key_count <> 10 + OR NOT (envelope ?& ARRAY[ + 'operationId', 'requestId', 'tokenHash', 'kid', 'signerGeneration', + 'authorityEvidenceBundleSha256', 'issuanceFence', + 'responseRecoveryExpiryEpochMillis', 'envelopeSha256', 'envelopeBytesLength']) + OR proof->>'tokenSha256' IS DISTINCT FROM NEW.token_hash + OR proof->>'registryRecordSha256' IS DISTINCT FROM registry->>'canonicalRecordSha256' + OR identity_proof->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR identity_proof->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR identity_proof->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR identity_proof->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR identity_proof->>'callerWorkload' IS DISTINCT FROM NEW.caller_workload + OR identity_proof->>'callerContextId' IS DISTINCT FROM NEW.caller_context_id::TEXT + OR identity_proof->>'tokenJti' IS DISTINCT FROM NEW.token_jti::TEXT + OR identity_proof->>'tokenGeneration' IS DISTINCT FROM NEW.token_generation::TEXT + OR identity_proof->>'issuedAtEpochSecond' IS DISTINCT FROM NEW.issued_at_epoch_second::TEXT + OR identity_proof->>'notBeforeEpochSecond' IS DISTINCT FROM NEW.not_before_epoch_second::TEXT + OR identity_proof->>'expiresAtEpochSecond' IS DISTINCT FROM NEW.expires_at_epoch_second::TEXT + OR identity_proof->>'tokenSha256' IS DISTINCT FROM NEW.token_hash + OR registry->>'state' IS DISTINCT FROM 'pending' + OR registry->>'registryVersion' IS DISTINCT FROM '1' + OR registry->>'tokenKey' IS DISTINCT FROM ('session:auth:token:' || NEW.token_hash) + OR registry->>'tokenHash' IS DISTINCT FROM NEW.token_hash + OR registry->>'kid' IS DISTINCT FROM NEW.signer_kid + OR registry->>'signerGeneration' IS DISTINCT FROM NEW.signer_generation + OR registry->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR registry->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR registry->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR registry->>'aclIdentity' IS DISTINCT FROM 'account_coord_app' + OR registry->>'absoluteExpiryMillis' IS NULL + OR registry->>'absoluteExpiryMillis' !~ '^[1-9][0-9]{0,18}$' + OR registry->>'localAofCount' IS NULL + OR registry->>'localAofCount' !~ '^[1-9][0-9]{0,3}$' + OR registry->>'replicaAofCount' IS NULL + OR registry->>'replicaAofCount' !~ '^[1-9][0-9]{0,3}$' + OR registry->>'outcome' IS NULL + OR registry->>'outcome' NOT IN ('CREATED', 'EXACT_RETRY') + OR registry->>'canonicalRecordSha256' IS NULL + OR registry->>'canonicalRecordSha256' !~ '^[0-9a-f]{64}$' + OR registry->>'evidenceBundleSha256' IS DISTINCT FROM bundle->>'canonicalSha256' + OR bundle->>'canonicalSha256' IS NULL + OR bundle->>'canonicalSha256' !~ '^[0-9a-f]{64}$' + OR authority->>'issuerGeneration' IS DISTINCT FROM NEW.authority_issuer_generation::TEXT + OR authority->>'issuerSourceVersion' IS DISTINCT FROM NEW.authority_issuer_source_version::TEXT + OR authority->>'accountGeneration' IS DISTINCT FROM NEW.authority_account_generation::TEXT + OR authority->>'accountSourceVersion' IS DISTINCT FROM NEW.authority_account_source_version::TEXT + OR authority->>'issuanceFence' IS DISTINCT FROM NEW.issuance_fence::TEXT + OR authority->>'issuanceFenceSourceVersion' IS DISTINCT FROM NEW.issuance_fence_source_version::TEXT + OR authority->'authorityTuple' IS DISTINCT FROM + convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR authority->'authoritySourceVersions' IS DISTINCT FROM + convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8')::jsonb + OR authority->>'issuerProjectionGeneration' IS DISTINCT FROM NEW.authority_issuer_generation::TEXT + OR authority->>'accountProjectionGeneration' IS DISTINCT FROM NEW.authority_account_generation::TEXT + OR authority->>'issuerProjectionSha256' IS NULL + OR authority->>'issuerProjectionSha256' !~ '^[0-9a-f]{64}$' + OR authority->>'accountProjectionSha256' IS NULL + OR authority->>'accountProjectionSha256' !~ '^[0-9a-f]{64}$' + OR signer->>'promotionStatus' IS DISTINCT FROM 'COMMITTED' + OR signer->>'promotionOperationId' IS NULL + OR signer->>'promotionOperationId' !~ '^[0-9a-f-]{36}$' + OR signer->>'generationOperationId' IS NULL + OR signer->>'generationOperationId' !~ '^[0-9a-f-]{36}$' + OR signer->>'targetKid' IS DISTINCT FROM NEW.signer_kid + OR signer->>'targetGeneration' IS DISTINCT FROM NEW.signer_generation + OR signer->>'correspondenceSha256' IS NULL + OR signer->>'correspondenceSha256' !~ '^[0-9a-f]{64}$' + OR envelope->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR envelope->>'requestId' IS DISTINCT FROM NEW.request_id::TEXT + OR envelope->>'tokenHash' IS DISTINCT FROM NEW.token_hash + OR envelope->>'kid' IS DISTINCT FROM NEW.signer_kid + OR envelope->>'signerGeneration' IS DISTINCT FROM NEW.signer_generation THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof does not match its immutable intent' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + IF (registry->>'absoluteExpiryMillis')::BIGINT < NEW.expires_at_epoch_second * 1000 + OR (registry->>'absoluteExpiryMillis')::BIGINT > NEW.expires_at_epoch_second * 1000 + 300000 THEN + RAISE EXCEPTION 'Account gameplay delegation Redis receipt expiry is outside the immutable token bound' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + SELECT request_id, account_uuid, bundle_schema, bundle_version, source_version, + source_fence, issuance_fence, linearization, canonical_sha256, canonical_bundle_bytes + INTO bundle_row + FROM account_gameplay_delegation_auth_evidence_bundles + WHERE operation_id = NEW.operation_id; + IF bundle_row.request_id IS NULL + OR bundle_row.request_id <> NEW.request_id + OR bundle_row.account_uuid <> NEW.account_uuid + OR bundle_row.bundle_schema <> 'account-auth-evidence-bundle/v1' + OR bundle_row.bundle_version <> bundle->>'bundleVersion' + OR bundle_row.source_version <> bundle->>'sourceVersion' + OR bundle_row.source_fence <> bundle->>'sourceFence' + OR bundle_row.linearization <> bundle->>'linearization' + OR bundle_row.canonical_sha256 <> bundle->>'canonicalSha256' + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'authorityTuple' IS DISTINCT FROM + convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8')::jsonb + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'membershipVersion' IS DISTINCT FROM + convert_from(NEW.membership_version_canonical_bytes, 'UTF8')::jsonb + OR convert_from(bundle_row.canonical_bundle_bytes, 'UTF8')::jsonb->'authoritySourceVersions' IS DISTINCT FROM + convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8')::jsonb THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has no exact owner evidence bundle' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + SELECT operation_id, request_id, token_hash, signer_kid, signer_generation, + authority_evidence_bundle_sha256, issuance_fence, response_recovery_expiry_epoch_ms, + envelope_sha256, octet_length(envelope_bytes) AS envelope_bytes_length + INTO envelope_row + FROM account_gameplay_delegation_response_envelopes + WHERE operation_id = NEW.operation_id; + IF envelope_row.operation_id IS NULL + OR envelope_row.request_id <> NEW.request_id + OR envelope_row.token_hash <> NEW.token_hash + OR envelope_row.signer_kid <> NEW.signer_kid + OR envelope_row.signer_generation <> NEW.signer_generation + OR envelope_row.authority_evidence_bundle_sha256 <> bundle_row.canonical_sha256 + OR envelope_row.issuance_fence <> NEW.issuance_fence + OR envelope_row.response_recovery_expiry_epoch_ms / 1000 <> NEW.expires_at_epoch_second + OR envelope->>'authorityEvidenceBundleSha256' IS DISTINCT FROM envelope_row.authority_evidence_bundle_sha256 + OR envelope->>'issuanceFence' IS DISTINCT FROM envelope_row.issuance_fence::TEXT + OR envelope->>'responseRecoveryExpiryEpochMillis' IS DISTINCT FROM envelope_row.response_recovery_expiry_epoch_ms::TEXT + OR envelope->>'envelopeSha256' IS DISTINCT FROM envelope_row.envelope_sha256 + OR envelope->>'envelopeBytesLength' IS DISTINCT FROM envelope_row.envelope_bytes_length::TEXT THEN + RAISE EXCEPTION 'Account gameplay delegation commit proof has no exact sealed owner envelope' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_commit_evidence_match'; + END IF; + + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V84.4__account_gameplay_authority_shared_issuer_guard.sql b/services/account-service/src/main/resources/db/migration/V84.4__account_gameplay_authority_shared_issuer_guard.sql new file mode 100644 index 0000000000..9bec2c5c0b --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V84.4__account_gameplay_authority_shared_issuer_guard.sql @@ -0,0 +1,135 @@ +-- Keep the global issuer rows read-shared during issuance authority checks so distinct Account +-- snapshots and pending issuance transactions do not serialize on issuer state. Account-scoped +-- generations, fences, and source rows remain exclusively locked at their mutation boundary. +-- Preserve all V84 predicates and the immutable V1-V84.3 migration history. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_delegation_authority_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + source_issuer_generation BIGINT; + source_issuer_source_version BIGINT; + current_issuer_sequence BIGINT; + current_issuer_stream VARCHAR(2048); + current_account_generation BIGINT; + current_account_source_version BIGINT; + source_account_generation BIGINT; + source_account_source_version BIGINT; + current_account_sequence BIGINT; + current_account_stream VARCHAR(2048); + current_account_cutoff_generation BIGINT; + current_account_cutoff_stream VARCHAR(2048); + current_account_cutoff_sequence BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + expected_authority_tuple TEXT; +BEGIN + -- Keep the owner lock order: Account row, issuer/account generations and fence, then the + -- source rows whose exact optional cutoff is carried by the immutable pending intent. + PERFORM account_uuid FROM accounts WHERE account_uuid = NEW.account_uuid FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account gameplay delegation Account source is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR SHARE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + SELECT outbox_stream_key, current_generation, current_source_version, last_outbox_sequence + INTO current_issuer_stream, source_issuer_generation, source_issuer_source_version, + current_issuer_sequence + FROM account_authority_source_records + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL + AND outbox_stream_key = 'account:auth-authority:v1:issuer/firemud-account-service' + FOR SHARE; + SELECT outbox_stream_key, current_generation, current_source_version, last_outbox_sequence, + cutoff_generation, cutoff_stream_key, cutoff_sequence + INTO current_account_stream, source_account_generation, source_account_source_version, + current_account_sequence, current_account_cutoff_generation, + current_account_cutoff_stream, current_account_cutoff_sequence + FROM account_authority_source_records + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL + AND outbox_stream_key = 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + FOR UPDATE; + + IF current_account_sequence = 0 + AND current_account_cutoff_generation IS NULL + AND current_account_cutoff_stream IS NULL + AND current_account_cutoff_sequence IS NULL THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":"' || source_account_generation::TEXT + || '","issuerAuthGeneration":"' || source_issuer_generation::TEXT || '"' + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + ELSIF current_account_sequence > 0 + AND current_account_cutoff_generation = source_account_generation + AND current_account_cutoff_stream = current_account_stream + AND current_account_cutoff_sequence = current_account_sequence THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":"' || source_account_generation::TEXT || '"' + || ',"accountSecurityCutoff":{"accountAuthorityGeneration":"' + || current_account_cutoff_generation::TEXT || '","outboxSequence":"' + || current_account_cutoff_sequence::TEXT || '","outboxStreamKey":"' + || current_account_cutoff_stream || '"},"issuerAuthGeneration":"' + || source_issuer_generation::TEXT || '"' + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + END IF; + + IF current_issuer_generation IS NULL OR current_account_generation IS NULL + OR current_issuance_fence IS NULL OR current_issuer_stream IS NULL + OR current_account_stream IS NULL OR current_issuer_sequence IS NULL + OR current_account_sequence IS NULL OR source_issuer_generation IS NULL + OR source_issuer_source_version IS NULL OR source_account_generation IS NULL + OR source_account_source_version IS NULL OR current_fence_source_version IS NULL + OR expected_authority_tuple IS NULL + OR current_issuer_stream <> 'account:auth-authority:v1:issuer/firemud-account-service' + OR current_account_stream <> 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + OR source_issuer_generation <> current_issuer_generation + OR source_issuer_source_version <> current_issuer_source_version + OR source_account_generation <> current_account_generation + OR source_account_source_version <> current_account_source_version + OR source_issuer_generation <> source_issuer_source_version + OR source_issuer_generation <> current_issuer_sequence + 1 + OR source_account_generation <> source_account_source_version + OR source_account_generation <> current_account_sequence + 1 + OR current_issuance_fence <> current_account_sequence + 1 + OR current_fence_source_version <> current_account_sequence + 1 + OR NEW.authority_issuer_generation <> current_issuer_generation + OR NEW.authority_issuer_source_version <> current_issuer_source_version + OR NEW.authority_account_generation <> current_account_generation + OR NEW.authority_account_source_version <> current_account_source_version + OR NEW.issuance_fence <> current_issuance_fence + OR NEW.issuance_fence_source_version <> current_fence_source_version + OR convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8') <> + expected_authority_tuple + OR convert_from(NEW.membership_version_canonical_bytes, 'UTF8') <> '{}' + OR convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8') <> + '{"accountSourceVersion":"' || current_account_source_version::text + || '","issuanceFenceSourceVersion":"' || current_fence_source_version::text + || '","issuerSourceVersion":"' || current_issuer_source_version::text || '"}' THEN + RAISE EXCEPTION 'Account gameplay delegation authority snapshot is stale or missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V84__account_gameplay_delegation_decimal_source_versions.sql b/services/account-service/src/main/resources/db/migration/V84__account_gameplay_delegation_decimal_source_versions.sql new file mode 100644 index 0000000000..b86a1f0340 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V84__account_gameplay_delegation_decimal_source_versions.sql @@ -0,0 +1,133 @@ +-- V44 compared the emitted authority tuple and authoritySourceVersions against the exact current +-- owner snapshot. Both generations and source versions are protocol decimal strings, not JSON numbers. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_gameplay_delegation_authority_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + current_issuer_generation BIGINT; + current_issuer_source_version BIGINT; + source_issuer_generation BIGINT; + source_issuer_source_version BIGINT; + current_issuer_sequence BIGINT; + current_issuer_stream VARCHAR(2048); + current_account_generation BIGINT; + current_account_source_version BIGINT; + source_account_generation BIGINT; + source_account_source_version BIGINT; + current_account_sequence BIGINT; + current_account_stream VARCHAR(2048); + current_account_cutoff_generation BIGINT; + current_account_cutoff_stream VARCHAR(2048); + current_account_cutoff_sequence BIGINT; + current_issuance_fence BIGINT; + current_fence_source_version BIGINT; + expected_authority_tuple TEXT; +BEGIN + -- Keep the owner lock order: Account row, issuer/account generations and fence, then the + -- source rows whose exact optional cutoff is carried by the immutable pending intent. + PERFORM account_uuid FROM accounts WHERE account_uuid = NEW.account_uuid FOR SHARE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account gameplay delegation Account source is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + SELECT generation, source_version + INTO current_issuer_generation, current_issuer_source_version + FROM account_authority_generations + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT generation, source_version + INTO current_account_generation, current_account_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL AND tenant_uuid IS NULL + FOR UPDATE; + SELECT issuance_fence, source_version + INTO current_issuance_fence, current_fence_source_version + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + FOR UPDATE; + SELECT outbox_stream_key, current_generation, current_source_version, last_outbox_sequence + INTO current_issuer_stream, source_issuer_generation, source_issuer_source_version, + current_issuer_sequence + FROM account_authority_source_records + WHERE scope_kind = 'ISSUER' AND issuer_id = 'firemud-account-service' + AND account_uuid IS NULL + AND outbox_stream_key = 'account:auth-authority:v1:issuer/firemud-account-service' + FOR UPDATE; + SELECT outbox_stream_key, current_generation, current_source_version, last_outbox_sequence, + cutoff_generation, cutoff_stream_key, cutoff_sequence + INTO current_account_stream, source_account_generation, source_account_source_version, + current_account_sequence, current_account_cutoff_generation, + current_account_cutoff_stream, current_account_cutoff_sequence + FROM account_authority_source_records + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND issuer_id IS NULL + AND outbox_stream_key = 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + FOR UPDATE; + + IF current_account_sequence = 0 + AND current_account_cutoff_generation IS NULL + AND current_account_cutoff_stream IS NULL + AND current_account_cutoff_sequence IS NULL THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":"' || source_account_generation::TEXT + || '","issuerAuthGeneration":"' || source_issuer_generation::TEXT || '"' + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + ELSIF current_account_sequence > 0 + AND current_account_cutoff_generation = source_account_generation + AND current_account_cutoff_stream = current_account_stream + AND current_account_cutoff_sequence = current_account_sequence THEN + expected_authority_tuple := + '{"accountAuthorityGeneration":"' || source_account_generation::TEXT || '"' + || ',"accountSecurityCutoff":{"accountAuthorityGeneration":"' + || current_account_cutoff_generation::TEXT || '","outboxSequence":"' + || current_account_cutoff_sequence::TEXT || '","outboxStreamKey":"' + || current_account_cutoff_stream || '"},"issuerAuthGeneration":"' + || source_issuer_generation::TEXT || '"' + || ',"membershipAuthorityGeneration":{},"privateRealmGrantVersions":[]' + || ',"tenantAuthorityGeneration":{}}'; + END IF; + + IF current_issuer_generation IS NULL OR current_account_generation IS NULL + OR current_issuance_fence IS NULL OR current_issuer_stream IS NULL + OR current_account_stream IS NULL OR current_issuer_sequence IS NULL + OR current_account_sequence IS NULL OR source_issuer_generation IS NULL + OR source_issuer_source_version IS NULL OR source_account_generation IS NULL + OR source_account_source_version IS NULL OR current_fence_source_version IS NULL + OR expected_authority_tuple IS NULL + OR current_issuer_stream <> 'account:auth-authority:v1:issuer/firemud-account-service' + OR current_account_stream <> 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + OR source_issuer_generation <> current_issuer_generation + OR source_issuer_source_version <> current_issuer_source_version + OR source_account_generation <> current_account_generation + OR source_account_source_version <> current_account_source_version + OR source_issuer_generation <> source_issuer_source_version + OR source_issuer_generation <> current_issuer_sequence + 1 + OR source_account_generation <> source_account_source_version + OR source_account_generation <> current_account_sequence + 1 + OR current_issuance_fence <> current_account_sequence + 1 + OR current_fence_source_version <> current_account_sequence + 1 + OR NEW.authority_issuer_generation <> current_issuer_generation + OR NEW.authority_issuer_source_version <> current_issuer_source_version + OR NEW.authority_account_generation <> current_account_generation + OR NEW.authority_account_source_version <> current_account_source_version + OR NEW.issuance_fence <> current_issuance_fence + OR NEW.issuance_fence_source_version <> current_fence_source_version + OR convert_from(NEW.authority_tuple_canonical_bytes, 'UTF8') <> + expected_authority_tuple + OR convert_from(NEW.membership_version_canonical_bytes, 'UTF8') <> '{}' + OR convert_from(NEW.authority_source_versions_canonical_bytes, 'UTF8') <> + '{"accountSourceVersion":"' || current_account_source_version::text + || '","issuanceFenceSourceVersion":"' || current_fence_source_version::text + || '","issuerSourceVersion":"' || current_issuer_source_version::text || '"}' THEN + RAISE EXCEPTION 'Account gameplay delegation authority snapshot is stale or missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_gameplay_delegation_authority_current'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V86__account_lifecycle_serving_operations.sql b/services/account-service/src/main/resources/db/migration/V86__account_lifecycle_serving_operations.sql new file mode 100644 index 0000000000..9b05b42da4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V86__account_lifecycle_serving_operations.sql @@ -0,0 +1,191 @@ +-- Immutable Account pending-intent and World terminal-receipt correlation only. +-- No logical Account state/source/generation/fence/outbox mutation, serving authorization producer, +-- expiry, or retained-row backfill. BEFORE INSERT versions the unchanged Account row to fence +-- older REPEATABLE_READ and SERIALIZABLE snapshots. +CREATE TABLE account_lifecycle_serving_operations ( + request_id UUID PRIMARY KEY + CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + actor_account_uuid UUID NOT NULL + CHECK (actor_account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) + REFERENCES accounts (account_uuid) ON DELETE RESTRICT, + account_uuid UUID NOT NULL, + account_id BIGINT NOT NULL CHECK (account_id > 0), + account_provenance VARCHAR(40) NOT NULL + CHECK (account_provenance IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT')), + tenant_uuid UUID NOT NULL + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + purpose VARCHAR(48) NOT NULL CHECK (purpose = 'WORLD_ACTIVATION_INVALIDATION'), + caller_proof_binding BYTEA NOT NULL + CHECK (octet_length(caller_proof_binding) BETWEEN 1 AND 16384), + world_activation_request_id UUID NOT NULL + CHECK (world_activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + world_activation_request_digest VARCHAR(71) NOT NULL + CHECK (world_activation_request_digest ~ '^sha256:[0-9a-f]{64}$'), + world_activation_request_bytes BYTEA NOT NULL + CHECK (octet_length(world_activation_request_bytes) BETWEEN 1 AND 1048576), + world_activation_preparing_evidence BYTEA NOT NULL + CHECK (octet_length(world_activation_preparing_evidence) BETWEEN 1 AND 1048576), + request_payload BYTEA NOT NULL + CHECK (octet_length(request_payload) BETWEEN 1 AND 2200000), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + account_stream_key VARCHAR(2048) NOT NULL, + account_generation BIGINT NOT NULL CHECK (account_generation > 0), + account_source_version BIGINT NOT NULL CHECK (account_source_version > 0), + account_issuance_fence BIGINT NOT NULL CHECK (account_issuance_fence > 0), + account_fence_source_version BIGINT NOT NULL CHECK (account_fence_source_version > 0), + checkpoint_sequence BIGINT NOT NULL CHECK (checkpoint_sequence >= 0), + checkpoint_event_sequence BIGINT CHECK (checkpoint_event_sequence > 0), + checkpoint_event_request_id VARCHAR(512), + checkpoint_event_id VARCHAR(512), + checkpoint_event_digest VARCHAR(512), + checkpoint_payload BYTEA NOT NULL CHECK (octet_length(checkpoint_payload) <= 1048576), + capture_payload BYTEA NOT NULL + CHECK (octet_length(capture_payload) BETWEEN 1 AND 1100000), + capture_digest VARCHAR(71) NOT NULL CHECK (capture_digest ~ '^sha256:[0-9a-f]{64}$'), + status VARCHAR(16) NOT NULL CHECK (status IN ('PENDING', 'WORLD_TERMINAL')), + world_result_outcome VARCHAR(16), + world_result_payload BYTEA, + world_result_digest VARCHAR(71), + world_terminal_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_lifecycle_serving_account_identity_fk + FOREIGN KEY (account_uuid, account_id, account_provenance) + REFERENCES accounts (account_uuid, account_uuid_source_numeric_id, account_uuid_provenance) + ON DELETE RESTRICT, + CONSTRAINT account_lifecycle_serving_stream_fk + FOREIGN KEY (account_stream_key) + REFERENCES account_authority_source_records (outbox_stream_key) ON DELETE RESTRICT, + CONSTRAINT account_lifecycle_serving_checkpoint_event_fk + FOREIGN KEY (account_stream_key, checkpoint_event_sequence) + REFERENCES account_authority_outbox_events (outbox_stream_key, outbox_sequence) + ON DELETE RESTRICT, + CONSTRAINT account_lifecycle_serving_checkpoint_shape CHECK ( + account_stream_key = 'account:auth-authority:v1:account/' || account_uuid::TEXT + AND account_generation = account_source_version + AND account_issuance_fence = account_generation + AND account_fence_source_version = account_source_version + AND account_generation = checkpoint_sequence + 1 + AND account_source_version = checkpoint_sequence + 1 + AND account_issuance_fence = checkpoint_sequence + 1 + AND account_fence_source_version = checkpoint_sequence + 1 + AND ( + (checkpoint_sequence = 0 + AND checkpoint_event_sequence IS NULL + AND checkpoint_event_request_id IS NULL + AND checkpoint_event_id IS NULL + AND checkpoint_event_digest IS NULL + AND octet_length(checkpoint_payload) = 0) + OR + (checkpoint_sequence > 0 + AND checkpoint_event_sequence = checkpoint_sequence + AND checkpoint_event_request_id IS NOT NULL + AND length(btrim(checkpoint_event_request_id)) > 0 + AND checkpoint_event_id IS NOT NULL + AND length(btrim(checkpoint_event_id)) > 0 + AND checkpoint_event_digest IS NOT NULL + AND checkpoint_event_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(checkpoint_payload) BETWEEN 1 AND 1048576) + )), + CONSTRAINT account_lifecycle_serving_result_shape CHECK ( + (status = 'PENDING' + AND world_result_outcome IS NULL + AND world_result_payload IS NULL + AND world_result_digest IS NULL + AND world_terminal_at IS NULL) + OR + (status = 'WORLD_TERMINAL' + AND world_result_outcome IN ('COMMITTED', 'ABORTED') + AND world_result_payload IS NOT NULL + AND octet_length(world_result_payload) BETWEEN 1 AND 2200000 + AND world_result_digest IS NOT NULL + AND world_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_terminal_at IS NOT NULL) + ) +); + +CREATE UNIQUE INDEX account_lifecycle_serving_one_pending_scope_uq + ON account_lifecycle_serving_operations (account_uuid, tenant_uuid) + WHERE status IN ('PENDING', 'WORLD_TERMINAL'); + +-- [jooq ignore start] +CREATE FUNCTION account_lifecycle_serving_account_row_version_fence() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + touched_rows INTEGER; +BEGIN + UPDATE accounts + SET id = id + WHERE account_uuid = NEW.account_uuid + AND id = NEW.account_id + AND account_uuid_provenance = NEW.account_provenance + AND account_uuid_source_numeric_id = NEW.account_id; + GET DIAGNOSTICS touched_rows = ROW_COUNT; + IF touched_rows <> 1 THEN + RAISE EXCEPTION 'Account lifecycle operation requires the exact persisted Account row' + USING ERRCODE = '23514', + CONSTRAINT = 'account_lifecycle_serving_account_row_version_fence'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_lifecycle_serving_account_row_version_fence + BEFORE INSERT ON account_lifecycle_serving_operations + FOR EACH ROW EXECUTE FUNCTION account_lifecycle_serving_account_row_version_fence(); + +CREATE FUNCTION account_lifecycle_serving_operation_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF OLD.status <> 'PENDING' OR NEW.status <> 'WORLD_TERMINAL' + OR (to_jsonb(NEW) - ARRAY['status', 'world_result_outcome', 'world_result_payload', + 'world_result_digest', 'world_terminal_at']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['status', 'world_result_outcome', 'world_result_payload', + 'world_result_digest', 'world_terminal_at']) THEN + RAISE EXCEPTION 'Account lifecycle request and capture are immutable; only one terminal World receipt may be added' + USING ERRCODE = '23514', CONSTRAINT = 'account_lifecycle_serving_operation_immutable'; + END IF; + NEW.world_terminal_at := CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_lifecycle_serving_operation_update + BEFORE UPDATE ON account_lifecycle_serving_operations + FOR EACH ROW EXECUTE FUNCTION account_lifecycle_serving_operation_update_guard(); + +CREATE FUNCTION account_lifecycle_serving_operation_delete_denied() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account lifecycle pending operations are retained' + USING ERRCODE = '23514', CONSTRAINT = 'account_lifecycle_serving_operation_no_delete'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_lifecycle_serving_operation_delete + BEFORE DELETE ON account_lifecycle_serving_operations + FOR EACH ROW EXECUTE FUNCTION account_lifecycle_serving_operation_delete_denied(); + +CREATE FUNCTION account_lifecycle_serving_operation_truncate_denied() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account lifecycle pending-operation history cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_lifecycle_serving_operation_no_truncate'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_lifecycle_serving_operation_truncate + BEFORE TRUNCATE ON account_lifecycle_serving_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_lifecycle_serving_operation_truncate_denied(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V87__account_gameplay_admission_lease_operations.sql b/services/account-service/src/main/resources/db/migration/V87__account_gameplay_admission_lease_operations.sql new file mode 100644 index 0000000000..c2675aded2 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V87__account_gameplay_admission_lease_operations.sql @@ -0,0 +1,113 @@ +-- Storage foundation only. No row, fence or terminal status establishes authenticated admission. +-- The lease fence is an independent per-Account domain, never an issuance/token fence. +CREATE TABLE account_gameplay_admission_lease_fences ( + account_uuid UUID PRIMARY KEY REFERENCES accounts(account_uuid) + CHECK (account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + last_fence BIGINT NOT NULL CHECK (last_fence > 0) +); + +CREATE TABLE account_gameplay_admission_lease_allocations ( + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) + CHECK (account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + request_id UUID PRIMARY KEY CHECK (request_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + lease_id UUID NOT NULL UNIQUE CHECK (lease_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + lease_fence BIGINT NOT NULL CHECK (lease_fence > 0), + UNIQUE (account_uuid, lease_fence), + UNIQUE (account_uuid, request_id, lease_id, lease_fence) +); + +CREATE TABLE account_gameplay_admission_lease_operations ( + account_uuid UUID NOT NULL, + request_id UUID PRIMARY KEY, + lease_id UUID NOT NULL UNIQUE, + lease_fence BIGINT NOT NULL, + caller_workload TEXT NOT NULL, + evidence_json TEXT NOT NULL CHECK (octet_length(evidence_json) BETWEEN 1 AND 65536), + evidence_sha256 VARCHAR(64) NOT NULL CHECK (evidence_sha256 ~ '^[0-9a-f]{64}$'), + evaluated_at_ms BIGINT NOT NULL CHECK (evaluated_at_ms > 0), + expires_at_ms BIGINT NOT NULL, + status VARCHAR(16) NOT NULL CHECK (status IN ('PENDING', 'COMMITTED', 'ABORTED')), + binding_decision_id UUID CHECK (binding_decision_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + orphan_cleanup_id UUID UNIQUE CHECK (orphan_cleanup_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + FOREIGN KEY (account_uuid, request_id, lease_id, lease_fence) + REFERENCES account_gameplay_admission_lease_allocations(account_uuid, request_id, lease_id, lease_fence), + CHECK (expires_at_ms > evaluated_at_ms AND expires_at_ms - evaluated_at_ms <= 15000), + CHECK ((status = 'PENDING' AND binding_decision_id IS NULL AND orphan_cleanup_id IS NULL) + OR (status = 'COMMITTED' AND binding_decision_id IS NOT NULL AND orphan_cleanup_id IS NULL) + OR (status = 'ABORTED' AND binding_decision_id IS NOT NULL AND orphan_cleanup_id IS NOT NULL)) +); + +-- PostgreSQL executes these exact digest and JSON identity constraints. The jOOQ/H2 schema +-- simulation cannot interpret their PostgreSQL expressions; omission from that simulation +-- does not replace physical PostgreSQL migration and negative-case proof. +-- [jooq ignore start] +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_lease_evidence_digest_check + CHECK (evidence_sha256 = encode(sha256(convert_to(evidence_json, 'UTF8')), 'hex')); +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_lease_evidence_identity_check + CHECK (COALESCE((evidence_json::jsonb ->> 'requestId') = request_id::text + AND (evidence_json::jsonb ->> 'leaseId') = lease_id::text + AND (evidence_json::jsonb ->> 'leaseFence') = lease_fence::text + AND (evidence_json::jsonb ->> 'callerWorkload') = caller_workload + AND (evidence_json::jsonb -> 'bindingScope' ->> 'accountId') = account_uuid::text + AND (evidence_json::jsonb ->> 'evaluatedAt') = evaluated_at_ms::text + AND (evidence_json::jsonb ->> 'expiresAt') = expires_at_ms::text, FALSE)); +-- [jooq ignore stop] + +-- ABORTED's immutable original evidence_json includes every exact orphan binding and token +-- coordinate. orphan_cleanup_id identifies durable PENDING work, not delivery/retirement success. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_admission_storage_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Account admission storage evidence cannot be removed' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'account_gameplay_admission_lease_fences' THEN + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF TG_OP = 'INSERT' THEN + IF NEW.last_fence <> 1 THEN RAISE EXCEPTION 'Lease fence must start at one' USING ERRCODE = '23514'; END IF; + ELSIF NEW.account_uuid IS DISTINCT FROM OLD.account_uuid OR NEW.last_fence <> OLD.last_fence + 1 THEN + RAISE EXCEPTION 'Lease fence must advance exactly once' USING ERRCODE = '23514'; + END IF; + ELSIF TG_TABLE_NAME = 'account_gameplay_admission_lease_allocations' THEN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Lease allocation is immutable' USING ERRCODE = '23514'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT EXISTS (SELECT 1 FROM account_gameplay_admission_lease_fences + WHERE account_uuid = NEW.account_uuid AND last_fence = NEW.lease_fence) THEN + RAISE EXCEPTION 'Lease allocation must bind current Account allocator' USING ERRCODE = '23514'; + END IF; + ELSE + IF TG_OP = 'INSERT' AND NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'Lease operation must start pending' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' AND (OLD.status <> 'PENDING' + OR (to_jsonb(NEW) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id'])) THEN + RAISE EXCEPTION 'Exact lease evidence and terminal decisions are immutable' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' OR NEW.status = 'COMMITTED') + AND (NEW.evaluated_at_ms > floor(extract(epoch FROM clock_timestamp()) * 1000) + OR NEW.expires_at_ms <= floor(extract(epoch FROM clock_timestamp()) * 1000)) THEN + RAISE EXCEPTION 'Lease operation storage deadline expired' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_admission_fence_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_lease_fences FOR EACH ROW EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_allocation_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_lease_allocations FOR EACH ROW EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_operation_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_lease_operations FOR EACH ROW EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_fence_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_lease_fences FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_allocation_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_lease_allocations FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +CREATE TRIGGER account_admission_operation_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_lease_operations FOR EACH STATEMENT EXECUTE FUNCTION account_gameplay_admission_storage_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V88__account_platform_restriction_birth_sources.sql b/services/account-service/src/main/resources/db/migration/V88__account_platform_restriction_birth_sources.sql new file mode 100644 index 0000000000..eb6d9daf0d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V88__account_platform_restriction_birth_sources.sql @@ -0,0 +1,261 @@ +-- Explicit birth-only CATEGORY evidence for genuinely new repository-created Accounts. +-- Historical birth generation/fence values are independent of current Account authority. +-- No retained enrollment, moderation mutation API, current-lock proof, or activation is added. +CREATE TABLE account_platform_restriction_births ( + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + category VARCHAR(32) NOT NULL, + revision BIGINT NOT NULL, + enforcement_epoch BIGINT NOT NULL, + source_kind VARCHAR(16) NOT NULL, + restriction_state VARCHAR(16) NOT NULL, + operation_id UUID NOT NULL UNIQUE, + result_id UUID NOT NULL UNIQUE, + event_id UUID NOT NULL UNIQUE, + payload_digest VARCHAR(64) NOT NULL, + account_source_numeric_id BIGINT NOT NULL REFERENCES accounts(id), + account_insert_transaction_id BIGINT NOT NULL, + account_generation BIGINT NOT NULL, + account_source_version BIGINT NOT NULL, + issuance_fence BIGINT NOT NULL, + fence_source_version BIGINT NOT NULL, + CONSTRAINT account_restriction_birth_pk PRIMARY KEY (account_uuid, category), + CONSTRAINT account_restriction_birth_category CHECK ( + category IN ('account_security_lock', 'platform_access_ban')), + CONSTRAINT account_restriction_birth_baseline CHECK ( + revision = 1 AND enforcement_epoch = 1 + AND source_kind = 'CATEGORY' AND restriction_state = 'NONRESTRICTED' + AND account_source_numeric_id > 0 AND account_insert_transaction_id > 0 + AND account_generation = 1 AND account_source_version = 1 + AND issuance_fence = 1 AND fence_source_version = 1), + CONSTRAINT account_restriction_birth_digest_shape CHECK ( + payload_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_restriction_birth_uuid_shape CHECK ( + account_uuid::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND result_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND event_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_restriction_birth_distinct_ids CHECK ( + operation_id <> result_id AND operation_id <> event_id AND result_id <> event_id), + CONSTRAINT account_restriction_birth_projection_identity UNIQUE ( + account_uuid, category, revision, enforcement_epoch, result_id), + CONSTRAINT account_restriction_birth_event_identity UNIQUE ( + account_uuid, category, revision, enforcement_epoch, operation_id, + result_id, event_id, payload_digest, source_kind, restriction_state) +); + +CREATE TABLE account_platform_restriction_projections ( + account_uuid UUID NOT NULL, + category VARCHAR(32) NOT NULL, + revision BIGINT NOT NULL CHECK (revision > 0), + enforcement_epoch BIGINT NOT NULL CHECK (enforcement_epoch > 0), + result_id UUID NOT NULL, + CONSTRAINT account_restriction_projection_pk PRIMARY KEY (account_uuid, category), + CONSTRAINT account_restriction_projection_exact_result FOREIGN KEY ( + account_uuid, category, revision, enforcement_epoch, result_id) + REFERENCES account_platform_restriction_births ( + account_uuid, category, revision, enforcement_epoch, result_id) +); + +CREATE TABLE account_platform_restriction_birth_outbox ( + account_uuid UUID NOT NULL, + category VARCHAR(32) NOT NULL, + revision BIGINT NOT NULL, + enforcement_epoch BIGINT NOT NULL, + operation_id UUID NOT NULL, + result_id UUID NOT NULL, + event_id UUID NOT NULL UNIQUE, + payload_digest VARCHAR(64) NOT NULL, + outbox_stream_key VARCHAR(160) NOT NULL UNIQUE, + outbox_sequence BIGINT NOT NULL, + source_kind VARCHAR(16) NOT NULL, + restriction_state VARCHAR(16) NOT NULL, + CONSTRAINT account_restriction_birth_outbox_pk PRIMARY KEY (account_uuid, category), + CONSTRAINT account_restriction_birth_outbox_stream CHECK ( + outbox_sequence = 1 + AND outbox_stream_key = + 'account:restriction-birth:v1:' || account_uuid::text || '/' || category), + CONSTRAINT account_restriction_birth_outbox_exact_result FOREIGN KEY ( + account_uuid, category, revision, enforcement_epoch, operation_id, + result_id, event_id, payload_digest, source_kind, restriction_state) + REFERENCES account_platform_restriction_births ( + account_uuid, category, revision, enforcement_epoch, operation_id, + result_id, event_id, payload_digest, source_kind, restriction_state) +); + +-- Closed UTF-8 preimage matches AccountPlatformRestrictionBirthSource.birthDigest exactly. +-- PostgreSQL proof must verify these checks; jOOQ's schema simulation does not execute them. +-- [jooq ignore start] +CREATE FUNCTION account_restriction_birth_digest( + birth account_platform_restriction_births) +RETURNS TEXT LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT encode(sha256(convert_to( + concat_ws(E'\n', + 'account-restriction-birth/v1', + birth.account_uuid::text, + birth.account_source_numeric_id::text, + 'ACCOUNT_REPOSITORY_INSERT', + birth.account_insert_transaction_id::text, + birth.category, + birth.source_kind, + birth.restriction_state, + birth.revision::text, + birth.enforcement_epoch::text, + birth.account_generation::text, + birth.account_source_version::text, + birth.issuance_fence::text, + birth.fence_source_version::text, + birth.operation_id::text, + birth.result_id::text, + birth.event_id::text, + 'account:restriction-birth:v1:' || birth.account_uuid::text || '/' || birth.category, + '1') || E'\n', 'UTF8')), 'hex') +$$; + +ALTER TABLE account_platform_restriction_births + ADD CONSTRAINT account_restriction_birth_exact_digest + CHECK (payload_digest = account_restriction_birth_digest( + ROW(account_uuid, category, revision, enforcement_epoch, source_kind, + restriction_state, operation_id, result_id, event_id, payload_digest, + account_source_numeric_id, account_insert_transaction_id, + account_generation, account_source_version, issuance_fence, + fence_source_version)::account_platform_restriction_births)); + +CREATE FUNCTION account_restriction_birth_storage_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + account_row RECORD; +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Restriction source evidence cannot be removed' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_birth_no_remove'; + END IF; + + IF TG_OP = 'UPDATE' + AND TG_TABLE_NAME <> 'account_platform_restriction_projections' THEN + RAISE EXCEPTION 'Restriction birth result and outbox are immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_birth_immutable'; + END IF; + + SELECT * INTO account_row FROM accounts + WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Restriction source requires exact Account' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_birth_account_required'; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.category IS DISTINCT FROM OLD.category + OR NEW.revision <> OLD.revision + 1 + OR NEW.enforcement_epoch <> OLD.enforcement_epoch + 1 + OR NEW.result_id IS NOT DISTINCT FROM OLD.result_id THEN + RAISE EXCEPTION 'Restriction projection requires next exact revision' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_projection_monotonic'; + END IF; + -- The exact-result FK remains birth-only, so no later revision is supported here. + ELSIF TG_TABLE_NAME = 'account_platform_restriction_births' THEN + IF account_row.account_uuid_provenance IS DISTINCT FROM 'ACCOUNT_REPOSITORY_INSERT' + OR account_row.lifecycle_state IS DISTINCT FROM 'active' + OR account_row.id IS DISTINCT FROM NEW.account_source_numeric_id + OR account_row.account_uuid_source_numeric_id + IS DISTINCT FROM NEW.account_source_numeric_id + OR account_row.account_repository_insert_transaction_id + IS DISTINCT FROM txid_current() + OR NEW.account_insert_transaction_id IS DISTINCT FROM txid_current() + OR NOT EXISTS ( + SELECT 1 FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND generation = 1 AND source_version = 1 + AND created_transaction_id = txid_current()) + OR NOT EXISTS ( + SELECT 1 FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid + AND issuance_fence = 1 AND source_version = 1) + OR NOT EXISTS ( + SELECT 1 FROM account_authority_source_records + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid + AND initialization_provenance = 'ACCOUNT_REPOSITORY_INSERT' + AND initialization_transaction_id = txid_current() + AND account_repository_insert_transaction_id = txid_current() + AND account_source_numeric_id = NEW.account_source_numeric_id + AND current_generation = 1 AND current_source_version = 1 + AND current_issuance_fence = 1 + AND current_issuance_fence_source_version = 1 + AND last_outbox_sequence = 0 + AND last_event_id IS NULL AND last_event_digest IS NULL) THEN + RAISE EXCEPTION 'Restriction birth requires genuine fresh Account source' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_birth_fresh_provenance'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_restriction_birth_storage + BEFORE INSERT OR UPDATE OR DELETE ON account_platform_restriction_births + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_storage_guard(); +CREATE TRIGGER account_restriction_projection_storage + BEFORE INSERT OR UPDATE OR DELETE ON account_platform_restriction_projections + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_storage_guard(); +CREATE TRIGGER account_restriction_birth_outbox_storage + BEFORE INSERT OR UPDATE OR DELETE ON account_platform_restriction_birth_outbox + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_storage_guard(); +CREATE TRIGGER account_restriction_birth_no_truncate + BEFORE TRUNCATE ON account_platform_restriction_births + FOR EACH STATEMENT EXECUTE FUNCTION account_restriction_birth_storage_guard(); +CREATE TRIGGER account_restriction_projection_no_truncate + BEFORE TRUNCATE ON account_platform_restriction_projections + FOR EACH STATEMENT EXECUTE FUNCTION account_restriction_birth_storage_guard(); +CREATE TRIGGER account_restriction_birth_outbox_no_truncate + BEFORE TRUNCATE ON account_platform_restriction_birth_outbox + FOR EACH STATEMENT EXECUTE FUNCTION account_restriction_birth_storage_guard(); + +CREATE FUNCTION account_restriction_birth_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + -- Existing/unmapped rows are not enrolled. This branch uses only the accounts row type. + IF TG_TABLE_NAME = 'accounts' THEN + IF NEW.account_uuid_provenance IS DISTINCT FROM 'ACCOUNT_REPOSITORY_INSERT' + OR NEW.id IS DISTINCT FROM NEW.account_uuid_source_numeric_id + OR NEW.account_repository_insert_transaction_id IS DISTINCT FROM txid_current() THEN + RETURN NEW; + END IF; + END IF; + + IF (SELECT count(*) + FROM account_platform_restriction_births b + JOIN account_platform_restriction_projections p + USING (account_uuid, category, revision, enforcement_epoch, result_id) + JOIN account_platform_restriction_birth_outbox o + USING (account_uuid, category, revision, enforcement_epoch, + operation_id, result_id, event_id, payload_digest, + source_kind, restriction_state) + WHERE b.account_uuid = NEW.account_uuid) <> 2 THEN + RAISE EXCEPTION 'Fresh Account restriction birth must be complete' + USING ERRCODE = '23514', + CONSTRAINT = 'account_restriction_birth_complete'; + END IF; + RETURN NEW; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_restriction_account_birth_complete + AFTER INSERT ON accounts DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard(); +CREATE CONSTRAINT TRIGGER account_restriction_birth_complete + AFTER INSERT ON account_platform_restriction_births DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard(); +CREATE CONSTRAINT TRIGGER account_restriction_projection_complete + AFTER INSERT OR UPDATE ON account_platform_restriction_projections + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard(); +CREATE CONSTRAINT TRIGGER account_restriction_birth_outbox_complete + AFTER INSERT ON account_platform_restriction_birth_outbox + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_restriction_birth_complete_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V89__account_admission_unknown_decision_abort.sql b/services/account-service/src/main/resources/db/migration/V89__account_admission_unknown_decision_abort.sql new file mode 100644 index 0000000000..20ed2b8443 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V89__account_admission_unknown_decision_abort.sql @@ -0,0 +1,31 @@ +-- An aborted attempt may have an unknown binding decision. Its exact cleanup identity remains +-- mandatory pending work, never proof of decision absence, cleanup delivery or token retirement. +-- V87's existing rows, immutable evidence, deadline, digest and allocation guards are unchanged. + +-- V87 declared this table-level CHECK without an explicit name. Resolve only its exact three +-- constrained columns; fail rather than removing an unrelated or ambiguous constraint. +-- PostgreSQL catalog lookup is excluded only from jOOQ's schema simulation, not runtime proof. +-- [jooq ignore start] +DO $$ +DECLARE + original_shape_constraint TEXT; +BEGIN + SELECT c.conname INTO STRICT original_shape_constraint + FROM pg_constraint c + WHERE c.conrelid = 'account_gameplay_admission_lease_operations'::regclass + AND c.contype = 'c' + AND ARRAY(SELECT a.attname::text + FROM pg_attribute a + WHERE a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey) + ORDER BY a.attname) = ARRAY['binding_decision_id', 'orphan_cleanup_id', 'status']; + EXECUTE format('ALTER TABLE account_gameplay_admission_lease_operations DROP CONSTRAINT %I', + original_shape_constraint); +END; +$$; +-- [jooq ignore stop] + +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_lease_operation_shape_check + CHECK ((status = 'PENDING' AND binding_decision_id IS NULL AND orphan_cleanup_id IS NULL) + OR (status = 'COMMITTED' AND binding_decision_id IS NOT NULL AND orphan_cleanup_id IS NULL) + OR (status = 'ABORTED' AND orphan_cleanup_id IS NOT NULL)); diff --git a/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql b/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql new file mode 100644 index 0000000000..579800746a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql @@ -0,0 +1,404 @@ +-- Temporal storage durability only: neither COMMITTED nor this confirmation grants admission. +-- Retained terminal rows are deliberately not backfilled from xmin or inferred transaction time. +ALTER TABLE account_gameplay_admission_lease_operations ADD COLUMN finalization_xid VARCHAR(20); + +-- [jooq ignore start] +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_finalization_xid_check CHECK ( + CASE WHEN finalization_xid IS NULL THEN TRUE + WHEN finalization_xid ~ '^[1-9][0-9]{0,19}$' THEN + status = 'COMMITTED' AND finalization_xid::numeric <= 18446744073709551615 + ELSE FALSE END); +-- [jooq ignore stop] + +ALTER TABLE account_gameplay_admission_lease_operations + ADD CONSTRAINT account_admission_confirmation_binding_unique + UNIQUE (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid); + +CREATE TABLE account_gameplay_admission_commit_confirmations ( + confirmation_version SMALLINT NOT NULL DEFAULT 1 CHECK (confirmation_version = 1), + request_id UUID PRIMARY KEY, + account_uuid UUID NOT NULL, + lease_id UUID NOT NULL, + lease_fence BIGINT NOT NULL CHECK (lease_fence > 0), + evidence_sha256 VARCHAR(64) NOT NULL CHECK (evidence_sha256 ~ '^[0-9a-f]{64}$'), + binding_decision_id UUID NOT NULL, + expires_at_ms BIGINT NOT NULL CHECK (expires_at_ms > 0), + finalization_xid VARCHAR(20) NOT NULL, + wal_insert_lsn TEXT NOT NULL, + wal_flush_lsn TEXT NOT NULL, + committed_before_ms BIGINT NOT NULL CHECK (committed_before_ms > 0 AND committed_before_ms < expires_at_ms), + confirmation_xid VARCHAR(20) NOT NULL, + FOREIGN KEY (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid) + REFERENCES account_gameplay_admission_lease_operations + (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid) +); + +-- Only PostgreSQL-specific expressions and procedural enforcement are omitted from simulation. +-- All receipt columns and the exact original-operation foreign key remain visible to jOOQ. +-- [jooq ignore start] +ALTER TABLE account_gameplay_admission_commit_confirmations + ADD CONSTRAINT account_admission_confirmation_proof_shape_check CHECK ( + CASE WHEN finalization_xid ~ '^[1-9][0-9]{0,19}$' + AND confirmation_xid ~ '^[1-9][0-9]{0,19}$' + AND wal_insert_lsn ~ '^(0|[1-9A-F][0-9A-F]{0,7})/(0|[1-9A-F][0-9A-F]{0,7})$' + AND wal_flush_lsn ~ '^(0|[1-9A-F][0-9A-F]{0,7})/(0|[1-9A-F][0-9A-F]{0,7})$' THEN + finalization_xid::numeric <= 18446744073709551615 + AND confirmation_xid::numeric <= 18446744073709551615 + AND finalization_xid <> confirmation_xid + AND wal_insert_lsn::pg_lsn > '0/0'::pg_lsn + AND wal_flush_lsn::pg_lsn >= wal_insert_lsn::pg_lsn + ELSE FALSE END); + +-- Preserve every V87 guard and the V89 terminal shape; stamp only the original transition. +CREATE OR REPLACE FUNCTION account_gameplay_admission_storage_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Account admission storage evidence cannot be removed' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'account_gameplay_admission_lease_fences' THEN + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF TG_OP = 'INSERT' THEN + IF NEW.last_fence <> 1 THEN RAISE EXCEPTION 'Lease fence must start at one' USING ERRCODE = '23514'; END IF; + ELSIF NEW.account_uuid IS DISTINCT FROM OLD.account_uuid OR NEW.last_fence <> OLD.last_fence + 1 THEN + RAISE EXCEPTION 'Lease fence must advance exactly once' USING ERRCODE = '23514'; + END IF; + ELSIF TG_TABLE_NAME = 'account_gameplay_admission_lease_allocations' THEN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Lease allocation is immutable' USING ERRCODE = '23514'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = NEW.account_uuid FOR UPDATE; + IF NOT EXISTS (SELECT 1 FROM account_gameplay_admission_lease_fences + WHERE account_uuid = NEW.account_uuid AND last_fence = NEW.lease_fence) THEN + RAISE EXCEPTION 'Lease allocation must bind current Account allocator' USING ERRCODE = '23514'; + END IF; + ELSE + IF TG_OP = 'INSERT' AND NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'Lease operation must start pending' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' AND NEW.finalization_xid IS NOT NULL) + OR (TG_OP = 'UPDATE' AND NEW.finalization_xid IS DISTINCT FROM OLD.finalization_xid) THEN + RAISE EXCEPTION 'Account admission finalization transaction is database stamped' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_finalization_xid_db_stamp'; + END IF; + IF TG_OP = 'UPDATE' AND (OLD.status <> 'PENDING' + OR (to_jsonb(NEW) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id', 'finalization_xid']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status', 'binding_decision_id', 'orphan_cleanup_id', 'finalization_xid'])) THEN + RAISE EXCEPTION 'Exact lease evidence and terminal decisions are immutable' USING ERRCODE = '23514'; + END IF; + IF (TG_OP = 'INSERT' OR NEW.status = 'COMMITTED') + AND (NEW.evaluated_at_ms > floor(extract(epoch FROM clock_timestamp()) * 1000) + OR NEW.expires_at_ms <= floor(extract(epoch FROM clock_timestamp()) * 1000)) THEN + RAISE EXCEPTION 'Lease operation storage deadline expired' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' AND NEW.status = 'COMMITTED' THEN + NEW.finalization_xid := pg_current_xact_id()::text; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_gameplay_admission_confirmation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + locked_receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + own_xid TEXT; + finalization_status TEXT; + fixed_snapshot pg_snapshot; + insert_fence pg_lsn; + initial_flush_fence pg_lsn; + flush_fence pg_lsn; + observed_before_ms BIGINT; + observation INTEGER; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Account admission confirmation is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_immutable'; + END IF; + IF NEW.confirmation_version IS DISTINCT FROM 1 OR NEW.account_uuid IS NOT NULL + OR NEW.lease_id IS NOT NULL OR NEW.lease_fence IS NOT NULL OR NEW.expires_at_ms IS NOT NULL + OR NEW.finalization_xid IS NOT NULL OR NEW.wal_insert_lsn IS NOT NULL + OR NEW.wal_flush_lsn IS NOT NULL OR NEW.committed_before_ms IS NOT NULL + OR NEW.confirmation_xid IS NOT NULL THEN + RAISE EXCEPTION 'Account admission confirmation proof is database derived' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_db_proof'; + END IF; + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Account admission confirmation writable SERIALIZABLE transaction required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_transaction_required'; + END IF; + IF pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Account admission confirmation durable primary required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; + END IF; + -- Establish the fixed transaction snapshot before the fence and before any heap read. + -- A subsequently visible independent row committed before this snapshot, hence before + -- this WAL upper bound. Even a SELECT can emit heap-pruning WAL; capture must precede it. + fixed_snapshot := pg_current_snapshot(); + own_xid := pg_current_xact_id_if_assigned()::text; + insert_fence := pg_current_wal_insert_lsn(); + initial_flush_fence := pg_current_wal_flush_lsn(); + IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = NEW.request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; + END IF; + IF operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL + OR NEW.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR NEW.binding_decision_id IS DISTINCT FROM operation.binding_decision_id THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + -- The stamp is top-level even when finalization ran in a released subtransaction. + IF operation.finalization_xid = own_xid THEN + RAISE EXCEPTION 'Account admission confirmation requires independent finalization commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_independent'; + END IF; + SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations WHERE request_id = NEW.request_id; + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + IF receipt.request_id IS NOT NULL THEN + SELECT * INTO locked_receipt FROM account_gameplay_admission_commit_confirmations + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt + OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid THEN + RAISE EXCEPTION 'Account admission confirmation immutable binding conflict' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_conflict'; + END IF; + -- Suppress an exact replay INSERT, including after expiry. The caller reads the retained + -- receipt; no new proof, XID, deadline or timing bound replaces its original evidence. + RETURN NULL; + END IF; + BEGIN + finalization_status := pg_xact_status(operation.finalization_xid::xid8); + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Account admission confirmation finalization proof unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_unavailable'; + END; + IF finalization_status IS DISTINCT FROM 'committed' THEN + RAISE EXCEPTION 'Account admission confirmation requires independent finalization commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_finalization_independent'; + END IF; + -- Account-first locking serializes first receipt creation, and exact locked revalidation + -- preserves the independently observed immutable operation. Only the pre-lock fence needs + -- coverage; this bounded polling creates no marker, forces no flush and renews no deadline. + FOR observation IN 1..50 LOOP + flush_fence := pg_current_wal_flush_lsn(); + -- A separate statement AFTER each flush observation is essential: SQL expression order + -- is not a temporal guarantee. CEIL supplies a conservative DB wall-clock upper bound. + observed_before_ms := ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint; + IF observed_before_ms <= 0 OR observed_before_ms >= operation.expires_at_ms THEN + RAISE EXCEPTION 'Account admission confirmation original deadline expired' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_original_deadline'; + END IF; + EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= insert_fence; + IF observation = 50 THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage', + DETAIL = format('phase=create snapshot=%s own_xid_if_assigned=%s finalization_xid=%s receipt_xid=%s insert_fence=%s initial_flush=%s final_flush=%s observed_db_ms=%s unchanged_expiry_ms=%s', + fixed_snapshot, own_xid, operation.finalization_xid, receipt.confirmation_xid, + insert_fence, initial_flush_fence, flush_fence, observed_before_ms, operation.expires_at_ms); + END IF; + PERFORM pg_sleep(0.01); + END LOOP; + NEW.account_uuid := operation.account_uuid; + NEW.lease_id := operation.lease_id; + NEW.lease_fence := operation.lease_fence; + NEW.expires_at_ms := operation.expires_at_ms; + NEW.finalization_xid := operation.finalization_xid; + NEW.wal_insert_lsn := insert_fence::text; + NEW.wal_flush_lsn := flush_fence::text; + NEW.committed_before_ms := observed_before_ms; + NEW.confirmation_xid := pg_current_xact_id()::text; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_admission_confirmation_guard BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_commit_confirmations FOR EACH ROW + EXECUTE FUNCTION account_gameplay_admission_confirmation_guard(); +CREATE TRIGGER account_admission_confirmation_truncate_guard BEFORE TRUNCATE + ON account_gameplay_admission_commit_confirmations FOR EACH STATEMENT + EXECUTE FUNCTION account_gameplay_admission_confirmation_guard(); + +CREATE FUNCTION account_gameplay_admission_confirm_committed( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS SETOF account_gameplay_admission_commit_confirmations LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_commit_confirmations%ROWTYPE; +BEGIN + -- Enter the guard before either operation/receipt heap read. It owns the snapshot/fence + -- and suppresses exact retained replay without renewing proof. A stale SERIALIZABLE + -- conflict must surface as 40001 rather than a raw uniqueness failure. + INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) + VALUES (requested_request_id, expected_sha, expected_decision) + ON CONFLICT (request_id) DO NOTHING RETURNING * INTO receipt; + IF FOUND THEN + RETURN NEXT receipt; + RETURN; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; + END IF; + IF operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + -- Exact retained replay may occur after expiry. It locks Account first and revalidates the + -- immutable original decision, but neither re-proves nor replaces the receipt's timing bound. + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR operation.status <> 'COMMITTED' OR operation.finalization_xid IS NULL + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id THEN + RAISE EXCEPTION 'Account admission confirmation exact committed binding required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_required'; + END IF; + SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid THEN + RAISE EXCEPTION 'Account admission confirmation immutable binding conflict' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_binding_conflict'; + END IF; + RETURN NEXT receipt; +END; +$$; + +CREATE FUNCTION account_gameplay_admission_read_commit_confirmation( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS SETOF account_gameplay_admission_commit_confirmations LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_receipt account_gameplay_admission_commit_confirmations%ROWTYPE; + own_xid TEXT; + fixed_snapshot pg_snapshot; + insert_fence pg_lsn; + initial_flush_fence pg_lsn; + flush_fence pg_lsn; + observed_before_ms BIGINT; + observation INTEGER; +BEGIN + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Account admission confirmation writable SERIALIZABLE transaction required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_transaction_required'; + END IF; + IF pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Account admission confirmation durable primary required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_durable_primary'; + END IF; + -- Fix the snapshot and WAL upper bound before heap reads or assigning our own XID. + -- Independent receipt visibility in that same snapshot covers its prior COMMIT. + fixed_snapshot := pg_current_snapshot(); + own_xid := pg_current_xact_id_if_assigned()::text; + insert_fence := pg_current_wal_insert_lsn(); + initial_flush_fence := pg_current_wal_flush_lsn(); + IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage'; + END IF; + SELECT * INTO operation FROM account_gameplay_admission_lease_operations WHERE request_id = requested_request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_operation_required'; + END IF; + SELECT * INTO receipt FROM account_gameplay_admission_commit_confirmations WHERE request_id = requested_request_id; + IF NOT FOUND OR operation.status IS DISTINCT FROM 'COMMITTED' + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id + OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid THEN + RAISE EXCEPTION 'Account admission confirmation exact durable receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_required'; + END IF; + -- MVCC visibility plus exclusion of our own top-level XID also excludes our subtransactions. + -- Historical receipts need not retain pg_xact_status data forever: fresh WAL coverage below + -- covers their independently visible original COMMIT without consulting vacuum-pruned status. + IF receipt.confirmation_xid = own_xid THEN + RAISE EXCEPTION 'Account admission confirmation requires independent receipt commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_independent'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account admission confirmation owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation THEN + RAISE EXCEPTION 'Account admission confirmation exact durable receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_required'; + END IF; + SELECT * INTO locked_receipt FROM account_gameplay_admission_commit_confirmations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt THEN + RAISE EXCEPTION 'Account admission confirmation exact durable receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_receipt_required'; + END IF; + FOR observation IN 1..50 LOOP + flush_fence := pg_current_wal_flush_lsn(); + EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= insert_fence; + IF observation = 50 THEN + observed_before_ms := ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint; + RAISE EXCEPTION 'Account admission confirmation WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_wal_coverage', + DETAIL = format('phase=receipt-read snapshot=%s own_xid_if_assigned=%s finalization_xid=%s receipt_xid=%s insert_fence=%s initial_flush=%s final_flush=%s observed_db_ms=%s unchanged_expiry_ms=%s', + fixed_snapshot, own_xid, operation.finalization_xid, receipt.confirmation_xid, + insert_fence, initial_flush_fence, flush_fence, observed_before_ms, operation.expires_at_ms); + END IF; + PERFORM pg_sleep(0.01); + END LOOP; + -- Return immutable historical timing evidence even after expiry; never restamp or renew it. + RETURN NEXT receipt; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V91__account_global_pending_admission_fences.sql b/services/account-service/src/main/resources/db/migration/V91__account_global_pending_admission_fences.sql new file mode 100644 index 0000000000..007bf4ea03 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V91__account_global_pending_admission_fences.sql @@ -0,0 +1,89 @@ +-- Account-wide negative pending-intent protection only. Unchanged tuple versions fence stale +-- REPEATABLE_READ/SERIALIZABLE snapshots; no logical source, restriction or authority is created. +-- Retained WAITING evidence is preserved, including unmatched or contradictory historical rows. +-- [jooq ignore start] +CREATE FUNCTION account_security_state_account_row_version_fence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + touched_rows INTEGER; +BEGIN + IF NEW.status = 'WAITING' THEN + UPDATE accounts SET id = id + WHERE account_uuid = NEW.account_uuid + AND id = NEW.account_id + AND account_uuid_source_numeric_id = NEW.account_id + AND account_uuid_provenance = NEW.account_provenance; + GET DIAGNOSTICS touched_rows = ROW_COUNT; + IF touched_rows <> 1 THEN + RAISE EXCEPTION 'Security-state intent requires the exact persisted Account row' + USING ERRCODE = '23514', + CONSTRAINT = 'account_security_state_account_row_version_fence'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_security_state_account_row_version_fence + BEFORE INSERT ON account_security_state_operations + FOR EACH ROW EXECUTE FUNCTION account_security_state_account_row_version_fence(); + +CREATE FUNCTION account_draft_authorization_account_row_version_fence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + account_key TEXT; + touched_rows INTEGER; +BEGIN + IF split_part(NEW.source_key, ':', 1) IN ('ACCOUNT', 'GLOBAL_ROLES') THEN + IF NEW.source_key !~ '^(ACCOUNT|GLOBAL_ROLES):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN + RAISE EXCEPTION 'Account source scope must use the exact canonical UUID key' + USING ERRCODE = '23514', + CONSTRAINT = 'account_draft_authorization_account_row_version_fence'; + END IF; + account_key := split_part(NEW.source_key, ':', 2); + UPDATE accounts SET id = id + WHERE account_uuid = account_key::UUID + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND id > 0 AND account_uuid_source_numeric_id = id + AND account_uuid_provenance IN ( + 'ACCOUNT_V29_MIGRATION', 'ACCOUNT_REPOSITORY_INSERT', 'ACCOUNT_DATABASE_INSERT'); + GET DIAGNOSTICS touched_rows = ROW_COUNT; + IF touched_rows <> 1 THEN + RAISE EXCEPTION 'Account source scope requires the exact persisted Account row' + USING ERRCODE = '23514', + CONSTRAINT = 'account_draft_authorization_account_row_version_fence'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +-- Alphabetically earlier than V76's scope_insert_phase: Account is touched before parent locking. +CREATE TRIGGER account_draft_authorization_account_row_version_fence + BEFORE INSERT ON account_draft_authorization_changed_scopes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_account_row_version_fence(); + +-- Protect snapshots predating installation without asserting retained intent provenance or +-- enrolling an Account. Exact UUID/key matching supplies negative protection only. +DO $$ +DECLARE + pending_account UUID; +BEGIN + FOR pending_account IN + SELECT a.account_uuid FROM accounts a + WHERE EXISTS ( + SELECT 1 FROM account_security_state_operations security + WHERE security.account_uuid = a.account_uuid AND security.status = 'WAITING') + OR EXISTS ( + SELECT 1 FROM account_draft_authorization_source_changes change + JOIN account_draft_authorization_changed_scopes changed USING (change_id) + WHERE change.status = 'WAITING' + AND changed.source_key IN ( + 'ACCOUNT:' || a.account_uuid::TEXT, 'GLOBAL_ROLES:' || a.account_uuid::TEXT)) + ORDER BY a.account_uuid::TEXT + LOOP + UPDATE accounts SET id = id WHERE account_uuid = pending_account; + END LOOP; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V92__account_admission_original_ack_receipt.sql b/services/account-service/src/main/resources/db/migration/V92__account_admission_original_ack_receipt.sql new file mode 100644 index 0000000000..431fcc9a56 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V92__account_admission_original_ack_receipt.sql @@ -0,0 +1,259 @@ +-- Persist only an opaque trusted-JVM acknowledgement of the original physical COMMIT and its +-- subsequent database-clock bound. The bound is not SQL-derived or authenticated by this schema. +-- This receipt supplies no current authority or gameplay-admission result. +CREATE TABLE account_gameplay_admission_original_commit_ack_receipts ( + schema_version SMALLINT NOT NULL DEFAULT 1 CHECK (schema_version = 1), + request_id UUID PRIMARY KEY, + account_uuid UUID NOT NULL, + lease_id UUID NOT NULL, + lease_fence BIGINT NOT NULL CHECK (lease_fence > 0), + evidence_sha256 VARCHAR(64) NOT NULL CHECK (evidence_sha256 ~ '^[0-9a-f]{64}$'), + binding_decision_id UUID NOT NULL, + expires_at_ms BIGINT NOT NULL CHECK (expires_at_ms > 0), + finalization_xid VARCHAR(20) NOT NULL, + committed_before_ms BIGINT NOT NULL CHECK ( + committed_before_ms > 0 AND committed_before_ms < expires_at_ms), + receipt_xid VARCHAR(20) NOT NULL, + FOREIGN KEY (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid) + REFERENCES account_gameplay_admission_lease_operations + (request_id, account_uuid, lease_id, lease_fence, evidence_sha256, + binding_decision_id, expires_at_ms, finalization_xid) +); + +-- The typed JVM acknowledgement supplies committed_before_ms. SQL validates its shape and exact +-- immutable operation binding, but cannot authenticate that opaque capability or prove its clock. +-- [jooq ignore start] +ALTER TABLE account_gameplay_admission_original_commit_ack_receipts + ADD CONSTRAINT account_admission_original_ack_receipt_xid_check CHECK ( + CASE WHEN finalization_xid ~ '^[1-9][0-9]{0,19}$' + AND receipt_xid ~ '^[1-9][0-9]{0,19}$' THEN + finalization_xid::numeric <= 18446744073709551615 + AND receipt_xid::numeric <= 18446744073709551615 + AND finalization_xid <> receipt_xid + ELSE FALSE END); + +CREATE FUNCTION account_gameplay_admission_original_ack_receipt_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + locked_receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + own_xid TEXT; + finalization_status TEXT; + version_num INTEGER; +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_immutable'; + END IF; + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_immutable'; + END IF; + IF NEW.schema_version IS DISTINCT FROM 1 + OR NEW.account_uuid IS NOT NULL OR NEW.lease_id IS NOT NULL + OR NEW.lease_fence IS NOT NULL OR NEW.expires_at_ms IS NOT NULL + OR NEW.receipt_xid IS NOT NULL THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt binding is database derived' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_db_binding'; + END IF; + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Writable SERIALIZABLE Account acknowledgement receipt transaction required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_transaction_required'; + END IF; + version_num := current_setting('server_version_num')::integer; + IF version_num < 160000 OR version_num >= 170000 + OR pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Supported durable PostgreSQL 16 primary required for Account acknowledgement receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_durable_primary'; + END IF; + + -- The request lookup only discovers the owning Account. All locked reads follow Account first. + SELECT * INTO operation FROM account_gameplay_admission_lease_operations + WHERE request_id = NEW.request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_operation_required'; + END IF; + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation + OR locked_operation.status IS DISTINCT FROM 'COMMITTED' + OR locked_operation.finalization_xid IS NULL + OR NEW.evidence_sha256 IS DISTINCT FROM locked_operation.evidence_sha256 + OR NEW.binding_decision_id IS DISTINCT FROM locked_operation.binding_decision_id + OR NEW.finalization_xid IS DISTINCT FROM locked_operation.finalization_xid + OR NEW.committed_before_ms <= 0 + OR NEW.committed_before_ms >= locked_operation.expires_at_ms THEN + RAISE EXCEPTION 'Exact original Account COMMIT acknowledgement required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_binding_required'; + END IF; + + SELECT * INTO receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = NEW.request_id; + IF FOUND THEN + SELECT * INTO locked_receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = NEW.request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt + OR receipt.schema_version IS DISTINCT FROM 1 + OR receipt.account_uuid IS DISTINCT FROM locked_operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM locked_operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM locked_operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM locked_operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM locked_operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM locked_operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM locked_operation.finalization_xid + OR receipt.committed_before_ms IS DISTINCT FROM NEW.committed_before_ms THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt retry conflicts' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_conflict'; + END IF; + -- An exact retained ACK retry never rewrites or restamps the original receipt. + RETURN NULL; + END IF; + + own_xid := pg_current_xact_id()::text; + IF own_xid = locked_operation.finalization_xid THEN + RAISE EXCEPTION 'Original Account COMMIT acknowledgement receipt requires independent transaction' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_independent'; + END IF; + BEGIN + finalization_status := pg_xact_status(locked_operation.finalization_xid::xid8); + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Original Account finalization status unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_finalization_unavailable'; + END; + IF finalization_status IS DISTINCT FROM 'committed' THEN + RAISE EXCEPTION 'Original Account finalization is not independently committed' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_independent'; + END IF; + + NEW.account_uuid := locked_operation.account_uuid; + NEW.lease_id := locked_operation.lease_id; + NEW.lease_fence := locked_operation.lease_fence; + NEW.expires_at_ms := locked_operation.expires_at_ms; + NEW.receipt_xid := own_xid; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_admission_original_ack_receipt_guard + BEFORE INSERT OR UPDATE OR DELETE + ON account_gameplay_admission_original_commit_ack_receipts FOR EACH ROW + EXECUTE FUNCTION account_gameplay_admission_original_ack_receipt_guard(); +CREATE TRIGGER account_admission_original_ack_receipt_truncate_guard + BEFORE TRUNCATE ON account_gameplay_admission_original_commit_ack_receipts FOR EACH STATEMENT + EXECUTE FUNCTION account_gameplay_admission_original_ack_receipt_guard(); + +CREATE FUNCTION account_gameplay_admission_read_original_ack_receipt_durably( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS SETOF account_gameplay_admission_original_commit_ack_receipts LANGUAGE plpgsql AS $$ +DECLARE + operation account_gameplay_admission_lease_operations%ROWTYPE; + receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + locked_operation account_gameplay_admission_lease_operations%ROWTYPE; + locked_receipt account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + own_xid TEXT; + fixed_snapshot pg_snapshot; + insert_fence pg_lsn; + initial_flush_fence pg_lsn; + flush_fence pg_lsn; + observation INTEGER; +BEGIN + IF current_setting('transaction_isolation') IS DISTINCT FROM 'serializable' + OR current_setting('transaction_read_only') IS DISTINCT FROM 'off' THEN + RAISE EXCEPTION 'Writable SERIALIZABLE Account acknowledgement receipt read required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_transaction_required'; + END IF; + IF current_setting('server_version_num')::integer < 160000 + OR current_setting('server_version_num')::integer >= 170000 + OR pg_is_in_recovery() OR current_setting('fsync') IS DISTINCT FROM 'on' THEN + RAISE EXCEPTION 'Supported durable PostgreSQL 16 primary required for Account acknowledgement receipt read' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_durable_primary'; + END IF; + -- Establish one fixed snapshot and its WAL upper fence before any heap read or row lock. + -- A receipt visible in this snapshot committed independently before this fence. + fixed_snapshot := pg_current_snapshot(); + own_xid := pg_current_xact_id_if_assigned()::text; + insert_fence := pg_current_wal_insert_lsn(); + initial_flush_fence := pg_current_wal_flush_lsn(); + IF insert_fence IS NULL OR insert_fence <= '0/0'::pg_lsn THEN + RAISE EXCEPTION 'Original Account acknowledgement receipt WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_wal_coverage'; + END IF; + + SELECT * INTO operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account acknowledgement operation missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_operation_required'; + END IF; + SELECT * INTO receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = requested_request_id; + IF NOT FOUND OR operation.status IS DISTINCT FROM 'COMMITTED' + OR operation.finalization_xid IS NULL + OR expected_sha IS DISTINCT FROM operation.evidence_sha256 + OR expected_decision IS DISTINCT FROM operation.binding_decision_id + OR receipt.schema_version IS DISTINCT FROM 1 + OR receipt.account_uuid IS DISTINCT FROM operation.account_uuid + OR receipt.lease_id IS DISTINCT FROM operation.lease_id + OR receipt.lease_fence IS DISTINCT FROM operation.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM operation.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM operation.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM operation.expires_at_ms + OR receipt.finalization_xid IS DISTINCT FROM operation.finalization_xid + OR receipt.committed_before_ms <= 0 + OR receipt.committed_before_ms >= operation.expires_at_ms THEN + RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; + END IF; + -- receipt_xid is the database-stamped top-level XID, so this excludes the current transaction + -- and any released subtransaction while retaining an independently committed historical row. + IF receipt.receipt_xid = own_xid THEN + RAISE EXCEPTION 'Original Account acknowledgement receipt requires independent commit' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_independent'; + END IF; + + PERFORM 1 FROM accounts WHERE account_uuid = operation.account_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Original Account acknowledgement owner missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_owner_required'; + END IF; + SELECT * INTO locked_operation FROM account_gameplay_admission_lease_operations + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_operation IS DISTINCT FROM operation THEN + RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; + END IF; + SELECT * INTO locked_receipt FROM account_gameplay_admission_original_commit_ack_receipts + WHERE request_id = requested_request_id FOR UPDATE; + IF NOT FOUND OR locked_receipt IS DISTINCT FROM receipt THEN + RAISE EXCEPTION 'Exact durable original Account acknowledgement receipt required' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_required'; + END IF; + + -- Bounded observation checks current WAL coverage only. It creates no marker, forces no flush, + -- consults no new clock, and never changes the original committed_before_ms or expiry. + FOR observation IN 1..50 LOOP + flush_fence := pg_current_wal_flush_lsn(); + EXIT WHEN flush_fence IS NOT NULL AND flush_fence >= insert_fence; + IF observation = 50 THEN + RAISE EXCEPTION 'Original Account acknowledgement receipt WAL coverage unavailable' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_original_ack_receipt_wal_coverage', + DETAIL = format('snapshot=%s own_xid_if_assigned=%s finalization_xid=%s receipt_xid=%s insert_fence=%s initial_flush=%s final_flush=%s unchanged_expiry_ms=%s', + fixed_snapshot, own_xid, operation.finalization_xid, receipt.receipt_xid, + insert_fence, initial_flush_fence, flush_fence, operation.expires_at_ms); + END IF; + PERFORM pg_sleep(0.01); + END LOOP; + RETURN NEXT receipt; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V93__account_draft_required_owner_fence.sql b/services/account-service/src/main/resources/db/migration/V93__account_draft_required_owner_fence.sql new file mode 100644 index 0000000000..e9c94764f2 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V93__account_draft_required_owner_fence.sql @@ -0,0 +1,371 @@ +-- Forward-only Account Draft required-owner/readback closure. Preserve every original binding and readback byte. +-- Shared byte-frame helpers are used by this Account owner only; no publication tables or authority are installed. +-- Source keys are shared with current Account issuer evidence. Widen without rewriting stored values. +-- PostgreSQL and the H2 schema simulator assign different names to V76's inline constraints. +-- jOOQ omits only these name-dependent swaps from H2 simulation; Flyway executes all swaps below. +-- [jooq ignore start] +ALTER TABLE account_draft_authorization_sources + DROP CONSTRAINT account_draft_authorization_sources_source_key_fkey; +ALTER TABLE account_draft_authorization_changed_scopes + DROP CONSTRAINT account_draft_authorization_changed_scopes_source_key_fkey; +-- [jooq ignore stop] +-- [jooq ignore start] +ALTER TABLE account_draft_authorization_source_locks + DROP CONSTRAINT account_draft_authorization_source_locks_source_key_check; +-- [jooq ignore stop] + +ALTER TABLE account_draft_authorization_source_locks + ALTER COLUMN source_key TYPE VARCHAR(2048); +ALTER TABLE account_draft_authorization_sources + ALTER COLUMN source_key TYPE VARCHAR(2048); +ALTER TABLE account_draft_authorization_changed_scopes + ALTER COLUMN source_key TYPE VARCHAR(2048); + +-- [jooq ignore start] +ALTER TABLE account_draft_authorization_source_locks + ADD CONSTRAINT account_draft_authorization_source_locks_source_key_check + CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048); +-- [jooq ignore stop] +-- [jooq ignore start] +ALTER TABLE account_draft_authorization_sources + ADD CONSTRAINT account_draft_authorization_sources_source_key_fkey + FOREIGN KEY (source_key) REFERENCES account_draft_authorization_source_locks(source_key); +ALTER TABLE account_draft_authorization_changed_scopes + ADD CONSTRAINT account_draft_authorization_changed_scopes_source_key_fkey + FOREIGN KEY (source_key) REFERENCES account_draft_authorization_source_locks(source_key); +-- [jooq ignore stop] + +-- [jooq ignore start] +ALTER TABLE account_draft_authorization_owner_readbacks + DROP CONSTRAINT account_draft_authorization_owner_readbacks_owner_check; +ALTER TABLE account_draft_authorization_owner_readbacks + ADD CONSTRAINT account_draft_authorization_owner_readbacks_owner_check + CHECK (owner IN ('GAME_DESIGN', 'WORLD', 'ENTITY', 'GAME_LOGIC', 'AUTOMATION')); +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE FUNCTION account_publication_authorization_source_sort_key(value TEXT) +RETURNS INTEGER[] LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + units INTEGER[] := ARRAY[]::INTEGER[]; + codepoint INTEGER; + character_index INTEGER; +BEGIN + FOR character_index IN 1..char_length(value) LOOP + codepoint := ascii(substring(value FROM character_index FOR 1)); + IF codepoint > 65535 THEN + units := array_append(units, 55296 + ((codepoint - 65536) / 1024)); + units := array_append(units, 56320 + ((codepoint - 65536) % 1024)); + ELSE + units := array_append(units, codepoint); + END IF; + END LOOP; + RETURN units; +END; +$$; + +CREATE FUNCTION account_publication_authorization_read_frame( + encoded BYTEA, + position_value INTEGER, + OUT frame_value BYTEA, + OUT next_position INTEGER) +RETURNS RECORD LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + frame_length BIGINT; + encoded_length INTEGER := octet_length(encoded); +BEGIN + IF position_value < 1 OR position_value > encoded_length - 3 + OR get_byte(encoded, position_value - 1) >= 128 THEN + RAISE EXCEPTION 'Publication terminal byte frame is truncated or oversized' + USING ERRCODE = '23514'; + END IF; + frame_length := get_byte(encoded, position_value - 1)::BIGINT * 16777216 + + get_byte(encoded, position_value)::BIGINT * 65536 + + get_byte(encoded, position_value + 1)::BIGINT * 256 + + get_byte(encoded, position_value + 2)::BIGINT; + IF frame_length > encoded_length - position_value - 3 THEN + RAISE EXCEPTION 'Publication terminal byte frame is incomplete' + USING ERRCODE = '23514'; + END IF; + frame_value := substring(encoded FROM position_value + 4 FOR frame_length::INTEGER); + next_position := position_value + 4 + frame_length::INTEGER; + RETURN; +END; +$$; + +-- Forward-only structural validation. Retained bindings and owner evidence are never rewritten. +CREATE FUNCTION account_draft_authorization_required_owners(encoded BYTEA) +RETURNS TEXT[] LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + frames BYTEA[] := ARRAY[]::BYTEA[]; + position_value INTEGER := 1; + parsed BYTEA; + schema_value TEXT; + source_count INTEGER; + owner_start INTEGER; + owners TEXT[] := ARRAY[]::TEXT[]; + derived TEXT[]; + complete JSONB; + declared TEXT[]; + revision_owners TEXT[]; + affected_owners TEXT[]; + allowed TEXT[] := ARRAY['WORLD_MANAGEMENT', 'ENTITY_MANAGEMENT', 'GAME_LOGIC', + 'AUTOMATION_SCRIPTING', 'GAME_DESIGN_CONTROL_PLANE']; + i INTEGER; +BEGIN + WHILE position_value <= octet_length(encoded) LOOP + SELECT frame_value, next_position INTO parsed, position_value + FROM account_publication_authorization_read_frame(encoded, position_value); + IF octet_length(parsed) = 0 THEN + RAISE EXCEPTION 'Draft authorization contains an empty frame' USING ERRCODE = '23514'; + END IF; + frames := array_append(frames, parsed); + END LOOP; + schema_value := convert_from(frames[1], 'UTF8'); + IF schema_value NOT IN ('account-draft-authorization-fence/v1', 'account-draft-authorization-fence/v2') + OR cardinality(frames) < 18 + OR convert_from(frames[10], 'UTF8') <> 'DRAFT' + OR convert_from(frames[11], 'UTF8') !~ '^(0|[1-9][0-9]*)$' + OR convert_from(frames[15], 'UTF8') !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Invalid original Draft authorization framing' USING ERRCODE = '23514'; + END IF; + source_count := convert_from(frames[15], 'UTF8')::INTEGER; + owner_start := 16 + source_count; + IF owner_start > cardinality(frames) THEN + RAISE EXCEPTION 'Incomplete original Draft source capture' USING ERRCODE = '23514'; + END IF; + IF schema_value = 'account-draft-authorization-fence/v1' THEN + IF cardinality(frames) <> owner_start + 1 + OR convert_from(frames[owner_start], 'UTF8') <> 'GAME_DESIGN' + OR convert_from(frames[owner_start + 1], 'UTF8') <> 'WORLD' THEN + RAISE EXCEPTION 'V1 original owner set is immutable' USING ERRCODE = '23514'; + END IF; + RETURN ARRAY['GAME_DESIGN', 'WORLD']; + END IF; + IF convert_from(frames[owner_start], 'UTF8') !~ '^[1-5]$' + OR cardinality(frames) <> owner_start + convert_from(frames[owner_start], 'UTF8')::INTEGER THEN + RAISE EXCEPTION 'Incomplete or trailing V2 owner vector' USING ERRCODE = '23514'; + END IF; + FOR i IN owner_start + 1 .. cardinality(frames) LOOP + owners := array_append(owners, convert_from(frames[i], 'UTF8')); + END LOOP; + complete := convert_from(frames[12], 'UTF8')::JSONB; + IF frames[12] IS DISTINCT FROM frames[13] + OR convert_from(frames[14], 'UTF8') IS DISTINCT FROM 'sha256:' || encode(sha256(frames[12]), 'hex') + OR complete->>'schemaVersion' IS DISTINCT FROM '1' + OR complete->>'requestId' IS DISTINCT FROM convert_from(frames[3], 'UTF8') + OR complete->>'commitId' IS DISTINCT FROM convert_from(frames[4], 'UTF8') + OR complete->>'canonicalTenantId' IS DISTINCT FROM convert_from(frames[7], 'UTF8') + OR complete->>'canonicalVersionId' IS DISTINCT FROM convert_from(frames[8], 'UTF8') + OR complete->>'baseCommitId' IS DISTINCT FROM convert_from(frames[9], 'UTF8') + OR jsonb_typeof(complete->'requiredOwners') IS DISTINCT FROM 'array' + OR jsonb_typeof(complete->'revisions') IS DISTINCT FROM 'array' + OR jsonb_typeof(complete->'affectedUnits') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'V2 requires the complete original Game Design binding' USING ERRCODE = '23514'; + END IF; + SELECT array_agg(value ORDER BY ordinal) INTO declared + FROM jsonb_array_elements_text(complete->'requiredOwners') WITH ORDINALITY entry(value, ordinal); + SELECT array_agg(DISTINCT value->>'owner' ORDER BY value->>'owner') INTO revision_owners + FROM jsonb_array_elements(complete->'revisions'); + SELECT array_agg(DISTINCT value->>'owner' ORDER BY value->>'owner') INTO affected_owners + FROM jsonb_array_elements(complete->'affectedUnits'); + IF declared IS NULL OR revision_owners IS NULL OR affected_owners IS NULL + OR NOT declared <@ allowed OR NOT revision_owners <@ allowed OR NOT affected_owners <@ allowed + OR array_position(revision_owners, NULL) IS NOT NULL + OR array_position(affected_owners, NULL) IS NOT NULL + OR declared IS DISTINCT FROM (SELECT array_agg(label ORDER BY ordinal) + FROM unnest(allowed) WITH ORDINALITY entry(label, ordinal) WHERE label = ANY(revision_owners)) + OR revision_owners IS DISTINCT FROM affected_owners THEN + RAISE EXCEPTION 'Required owners differ from complete revision and affected-owner coverage' + USING ERRCODE = '23514'; + END IF; + SELECT array_agg(label ORDER BY ordinal) INTO derived + FROM unnest(ARRAY['GAME_DESIGN', 'WORLD', 'ENTITY', 'GAME_LOGIC', 'AUTOMATION']) + WITH ORDINALITY entry(label, ordinal) + WHERE label = 'GAME_DESIGN' OR label = ANY(SELECT CASE value + WHEN 'WORLD_MANAGEMENT' THEN 'WORLD' WHEN 'ENTITY_MANAGEMENT' THEN 'ENTITY' + WHEN 'GAME_LOGIC' THEN 'GAME_LOGIC' WHEN 'AUTOMATION_SCRIPTING' THEN 'AUTOMATION' + WHEN 'GAME_DESIGN_CONTROL_PLANE' THEN 'GAME_DESIGN' END FROM unnest(declared) value); + IF owners IS DISTINCT FROM derived THEN + RAISE EXCEPTION 'V2 owner vector differs from complete original binding' USING ERRCODE = '23514'; + END IF; + RETURN owners; +END; +$$; + +CREATE FUNCTION account_draft_authorization_valid_readback( + encoded BYTEA, original BYTEA, operation UUID, commit_value UUID, fence_value UUID, + owner_value TEXT, outcome_value TEXT) +RETURNS BOOLEAN LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + position_value INTEGER := 1; + parsed BYTEA; + values_array BYTEA[] := ARRAY[]::BYTEA[]; + original_position INTEGER := 1; + original_frames BYTEA[] := ARRAY[]::BYTEA[]; +BEGIN + WHILE position_value <= octet_length(encoded) LOOP + SELECT frame_value, next_position INTO parsed, position_value + FROM account_publication_authorization_read_frame(encoded, position_value); + values_array := array_append(values_array, parsed); + END LOOP; + -- The original decoder validates its complete owner vector and trailing-free framing. + IF NOT owner_value = ANY(account_draft_authorization_required_owners(original)) THEN + RETURN FALSE; + END IF; + FOR i IN 1..14 LOOP + SELECT frame_value, next_position INTO parsed, original_position + FROM account_publication_authorization_read_frame(original, original_position); + original_frames := array_append(original_frames, parsed); + END LOOP; + RETURN cardinality(values_array) = 9 AND octet_length(values_array[9]) > 0 + AND convert_from(values_array[1], 'UTF8') = replace(convert_from(original_frames[1], 'UTF8'), + 'account-draft-authorization-fence/', 'account-draft-owner-readback/') + AND convert_from(values_array[2], 'UTF8') = owner_value + AND convert_from(values_array[3], 'UTF8') = outcome_value + AND values_array[4] = original_frames[2] + AND convert_from(values_array[4], 'UTF8') = operation::TEXT + AND values_array[5] = original_frames[4] + AND convert_from(values_array[5], 'UTF8') = commit_value::TEXT + AND values_array[6] = original_frames[5] + AND convert_from(values_array[6], 'UTF8') = fence_value::TEXT + AND values_array[7] = original_frames[14] AND values_array[8] = original; +EXCEPTION WHEN OTHERS THEN + RETURN FALSE; +END; +$$; + +CREATE FUNCTION account_draft_authorization_complete_sources(operation UUID, original BYTEA) +RETURNS BOOLEAN LANGUAGE plpgsql STABLE STRICT AS $$ +DECLARE + position_value INTEGER := 1; + parsed BYTEA; + source_count INTEGER; + source_bytes BYTEA; + source_position INTEGER; + source_kind TEXT; + source_scope TEXT; + source_key_value TEXT; + seen TEXT[] := ARRAY[]::TEXT[]; +BEGIN + FOR i IN 1..15 LOOP + SELECT frame_value, next_position INTO parsed, position_value + FROM account_publication_authorization_read_frame(original, position_value); + END LOOP; + source_count := convert_from(parsed, 'UTF8')::INTEGER; + IF source_count < 1 OR source_count <> (SELECT count(*) + FROM account_draft_authorization_sources WHERE operation_id = operation) THEN + RETURN FALSE; + END IF; + FOR i IN 1..source_count LOOP + SELECT frame_value, next_position INTO source_bytes, position_value + FROM account_publication_authorization_read_frame(original, position_value); + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(source_bytes, 1); + IF convert_from(parsed, 'UTF8') <> 'account-draft-source-evidence/v1' THEN RETURN FALSE; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_kind, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_scope, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := source_kind || ':' || source_scope; + IF source_key_value = ANY(seen) OR NOT EXISTS ( + SELECT 1 FROM account_draft_authorization_sources + WHERE operation_id = operation AND source_key = source_key_value + AND source_evidence = source_bytes) THEN + RETURN FALSE; + END IF; + seen := array_append(seen, source_key_value); + END LOOP; + RETURN TRUE; +EXCEPTION WHEN OTHERS THEN + RETURN FALSE; +END; +$$; + +CREATE FUNCTION account_draft_authorization_owner_readback_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + fence account_draft_authorization_fences%ROWTYPE; + key_value TEXT; +BEGIN + FOR key_value IN SELECT source_key FROM account_draft_authorization_sources + WHERE operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(source_key) LOOP + PERFORM 1 FROM account_draft_authorization_source_locks WHERE source_key = key_value FOR UPDATE; + END LOOP; + SELECT * INTO fence FROM account_draft_authorization_fences WHERE operation_id = NEW.operation_id FOR UPDATE; + IF fence.ordering IS NULL OR fence.ordering = 'RESERVED' + OR NOT account_draft_authorization_complete_sources(fence.operation_id, fence.binding) + OR NOT account_draft_authorization_valid_readback(NEW.readback, fence.binding, + fence.operation_id, fence.commit_id, fence.fence_id, NEW.owner, NEW.outcome) THEN + RAISE EXCEPTION 'Owner result must exactly bind one original required owner' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +-- Replace only the Draft readback insert-phase trigger; other independent guards remain intact. +DROP TRIGGER account_draft_authorization_readback_insert_phase ON account_draft_authorization_owner_readbacks; +CREATE TRIGGER account_draft_authorization_readback_insert_phase + BEFORE INSERT ON account_draft_authorization_owner_readbacks + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_owner_readback_guard(); + +CREATE FUNCTION account_draft_authorization_is_settled(operation UUID) +RETURNS BOOLEAN LANGUAGE plpgsql STABLE STRICT AS $$ +DECLARE + fence account_draft_authorization_fences%ROWTYPE; + owners TEXT[]; + actual TEXT[]; + outcomes INTEGER; +BEGIN + SELECT * INTO fence FROM account_draft_authorization_fences WHERE operation_id = operation; + IF NOT FOUND OR fence.ordering = 'RESERVED' THEN RETURN FALSE; END IF; + IF NOT account_draft_authorization_complete_sources(fence.operation_id, fence.binding) THEN RETURN FALSE; END IF; + owners := account_draft_authorization_required_owners(fence.binding); + SELECT array_agg(owner ORDER BY array_position(owners, owner)), count(DISTINCT outcome) + INTO actual, outcomes FROM account_draft_authorization_owner_readbacks WHERE operation_id = operation; + RETURN actual IS NOT DISTINCT FROM owners AND outcomes = 1 + AND NOT EXISTS (SELECT 1 FROM account_draft_authorization_owner_readbacks r + WHERE r.operation_id = operation AND ( + NOT account_draft_authorization_valid_readback(r.readback, fence.binding, + fence.operation_id, fence.commit_id, fence.fence_id, r.owner, r.outcome) + OR (fence.ordering = 'REVOKE_ORDER' AND r.outcome <> 'DEFINITIVELY_ABORTED'))); +EXCEPTION WHEN OTHERS THEN + RETURN FALSE; +END; +$$; + +CREATE OR REPLACE FUNCTION account_draft_authorization_source_change_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + key_value TEXT; + operation UUID; +BEGIN + IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Draft source change cannot be deleted'; END IF; + IF OLD.status <> 'WAITING' OR NEW.status NOT IN ('SOURCE_COMMITTED', 'SOURCE_ABORTED') + OR NEW.change_id IS DISTINCT FROM OLD.change_id OR NEW.binding IS DISTINCT FROM OLD.binding + OR NEW.requested_at IS DISTINCT FROM OLD.requested_at + OR (NEW.status = 'SOURCE_COMMITTED' AND (NEW.committed_at IS NULL OR NEW.aborted_at IS NOT NULL OR NEW.abort_reason IS NOT NULL)) + OR (NEW.status = 'SOURCE_ABORTED' AND (NEW.committed_at IS NOT NULL OR NEW.aborted_at IS NULL + OR NEW.abort_reason IS NULL OR NEW.abort_reason NOT IN ('EXPIRED', 'DEFINITIVE_ABORT'))) THEN + RAISE EXCEPTION 'Draft source change result is immutable' USING ERRCODE = '23514'; + END IF; + FOR key_value IN SELECT source_key FROM account_draft_authorization_changed_scopes + WHERE change_id = OLD.change_id ORDER BY account_publication_authorization_source_sort_key(source_key) LOOP + PERFORM 1 FROM account_draft_authorization_source_locks WHERE source_key = key_value FOR UPDATE; + END LOOP; + FOR operation IN SELECT DISTINCT source.operation_id + FROM account_draft_authorization_changed_scopes changed + JOIN account_draft_authorization_sources source USING (source_key) + WHERE changed.change_id = OLD.change_id ORDER BY source.operation_id LOOP + PERFORM 1 FROM account_draft_authorization_fences WHERE operation_id = operation FOR UPDATE; + IF NOT account_draft_authorization_is_settled(operation) THEN + RAISE EXCEPTION 'Every original required owner must have one uniform exact terminal outcome' + USING ERRCODE = '23514'; + END IF; + END LOOP; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/redis/account_generation_projection_cas.lua b/services/account-service/src/main/resources/redis/account_generation_projection_cas.lua new file mode 100644 index 0000000000..a89652374a --- /dev/null +++ b/services/account-service/src/main/resources/redis/account_generation_projection_cas.lua @@ -0,0 +1,54 @@ +if #KEYS ~= 1 or #ARGV ~= 3 then + return -2 +end + +local mode = ARGV[1] +local expectedBytes = ARGV[2] +local candidateBytes = ARGV[3] + +if mode ~= 'ABSENT' and mode ~= 'PRESENT' and mode ~= 'VERIFY' then + return -2 +end + +if mode == 'VERIFY' then + if expectedBytes == '' or candidateBytes ~= '' then + return -2 + end +elseif mode == 'ABSENT' then + if expectedBytes ~= '' or candidateBytes == '' then + return -2 + end +elseif expectedBytes == '' or candidateBytes == '' then + return -2 +end + +local currentBytes = redis.call('GET', KEYS[1]) +if currentBytes ~= false and redis.call('PTTL', KEYS[1]) ~= -1 then + return -3 +end + +if mode == 'VERIFY' then + if currentBytes == expectedBytes then + return 0 + end + return -1 +end + +if currentBytes == candidateBytes then + return 0 +end + +if mode == 'ABSENT' then + if currentBytes ~= false then + return -1 + end + redis.call('SET', KEYS[1], candidateBytes) + return 1 +end + +if currentBytes ~= expectedBytes then + return -1 +end + +redis.call('SET', KEYS[1], candidateBytes) +return 1 diff --git a/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-activate-committed.lua b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-activate-committed.lua new file mode 100644 index 0000000000..4ff851f865 --- /dev/null +++ b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-activate-committed.lua @@ -0,0 +1,62 @@ +if #KEYS ~= 1 or #ARGV ~= 3 then + return -4 +end + +local key = KEYS[1] +if not string.match(key, '^session:auth:token:[0-9a-f]+$') + or string.len(key) ~= string.len('session:auth:token:') + 64 then + return -4 +end + +local pending = ARGV[1] +local active = ARGV[2] +if not pending or string.len(pending) == 0 or string.len(pending) > 16384 + or not active or string.len(active) == 0 or string.len(active) > 16384 then + return -4 +end + +-- The two canonical values may differ in exactly the lifecycle pair. String operations preserve +-- every potentially large integer byte-for-byte and avoid cjson's lossy numeric conversion. +local versioned, versionCount = string.gsub(pending, '"registryVersion":1', '"registryVersion":2') +local expectedActive, stateCount = string.gsub(versioned, '"state":"pending"', '"state":"active"') +if versionCount ~= 1 or stateCount ~= 1 or expectedActive ~= active then + return -4 +end + +local deadline = ARGV[3] +if not deadline or not string.match(deadline, '^[1-9][0-9]*$') or string.len(deadline) > 16 then + return -4 +end +local targetExpiry = tonumber(deadline) +if not targetExpiry or targetExpiry <= 0 or targetExpiry > 9007199254740991 + or targetExpiry ~= math.floor(targetExpiry) then + return -4 +end + +local current = redis.call('GET', key) +if not current then + return -3 +end +local currentExpiry = redis.call('PEXPIRETIME', key) +if currentExpiry ~= targetExpiry then + return -2 +end + +if current == pending then + local stored = redis.call('SET', key, active, 'PXAT', deadline, 'XX') + if stored ~= 'OK' then + return -5 + end + return 1 +end + +if current == active then + -- Exact lost-ack retry: reassert only the original absolute deadline, never a relative TTL. + local stored = redis.call('SET', key, active, 'PXAT', deadline, 'XX') + if stored ~= 'OK' then + return -5 + end + return 0 +end + +return -1 diff --git a/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-authority-project.lua b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-authority-project.lua new file mode 100644 index 0000000000..84d10934df --- /dev/null +++ b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-authority-project.lua @@ -0,0 +1,127 @@ +local MAX_RECORD_BYTES = 8192 +-- Issuer only. Account source projections use account.account-generation-projection.v1. + +local function exact_fields(value, required, optional) + if type(value) ~= 'table' then return false end + local allowed = {} + for _, field in ipairs(required) do allowed[field] = true end + for _, field in ipairs(optional or {}) do allowed[field] = true end + for field, _ in pairs(value) do + if type(field) ~= 'string' or not allowed[field] then return false end + end + for _, field in ipairs(required) do + if value[field] == nil then return false end + end + return true +end + +local function positive_decimal(value) + if type(value) ~= 'string' + or string.match(value, '^[1-9][0-9]*$') == nil then + return false + end + return true +end + +local function nonnegative_decimal(value) + return type(value) == 'string' + and (value == '0' or string.match(value, '^[1-9][0-9]*$') ~= nil) +end + +local function decrement_decimal(value) + local digits = {} + for index = 1, string.len(value) do + digits[index] = tonumber(string.sub(value, index, index)) + end + local index = #digits + while index > 0 and digits[index] == 0 do + digits[index] = 9 + index = index - 1 + end + if index == 0 then return nil end + digits[index] = digits[index] - 1 + local result = '' + local first = 1 + while first < #digits and digits[first] == 0 do first = first + 1 end + for position = first, #digits do result = result .. tostring(digits[position]) end + return result +end + +local function generation_greater(left, right) + if string.len(left) ~= string.len(right) then + return string.len(left) > string.len(right) + end + return left > right +end + +local function validate_record(record, key) + if type(record) ~= 'string' or string.len(record) == 0 or string.len(record) > MAX_RECORD_BYTES then + return nil + end + local ok, value = pcall(cjson.decode, record) + if not ok or type(value) ~= 'table' then return nil end + + local scope = nil + local scope_id = nil + local expected_stream = nil + local issuer_prefix = 'session:auth:generation:issuer:' + if string.sub(key, 1, string.len(issuer_prefix)) == issuer_prefix then + scope = 'issuer' + scope_id = string.sub(key, string.len(issuer_prefix) + 1) + if scope_id ~= 'firemud-account-service' then return nil end + expected_stream = 'account:auth-authority:v1:issuer/' .. scope_id + else + return nil + end + + local required = { + 'schemaVersion', 'issuerId', 'issuerAuthGeneration', 'sourceVersion', + 'outboxStreamKey', 'lastAppliedSourceOutboxSequence' + } + local optional = {'lastAppliedSourceEventId', 'lastAppliedSourceEventDigest', 'sourceEvent'} + if not exact_fields(value, required, optional) + or value.schemaVersion ~= 'account-auth-issuer-generation-projection/v1' + or value.issuerId ~= scope_id + or not positive_decimal(value.issuerAuthGeneration) + or not positive_decimal(value.sourceVersion) + or value.outboxStreamKey ~= expected_stream + or not nonnegative_decimal(value.lastAppliedSourceOutboxSequence) then return nil end + if value.lastAppliedSourceOutboxSequence == '0' then + if value.issuerAuthGeneration ~= '1' or value.sourceVersion ~= '1' + or value.lastAppliedSourceEventId ~= nil or value.lastAppliedSourceEventDigest ~= nil + or value.sourceEvent ~= nil then return nil end + else + if value.issuerAuthGeneration == '1' or value.sourceVersion == '1' + or type(value.lastAppliedSourceEventId) ~= 'string' + or string.len(value.lastAppliedSourceEventId) == 0 + or type(value.lastAppliedSourceEventDigest) ~= 'string' + or string.match(value.lastAppliedSourceEventDigest, '^sha256:[0-9a-f]+$') == nil + or string.len(value.lastAppliedSourceEventDigest) ~= 71 + or type(value.sourceEvent) ~= 'string' or string.len(value.sourceEvent) == 0 then return nil end + end + + return value +end + +if #KEYS ~= 1 or #ARGV ~= 1 then return -4 end +local key = KEYS[1] +local generation_prefix = 'session:auth:generation:' +if string.len(key) > 256 + or string.sub(key, 1, string.len(generation_prefix)) ~= generation_prefix then return -4 end +local incoming = validate_record(ARGV[1], key) +if not incoming then return -4 end + +local current = redis.call('GET', key) +if current then + local existing = validate_record(current, key) + if not existing or redis.call('PTTL', key) ~= -1 then return -5 end + if generation_greater(existing.issuerAuthGeneration, incoming.issuerAuthGeneration) then return -1 end + if existing.issuerAuthGeneration == incoming.issuerAuthGeneration then + if current == ARGV[1] then return 0 end + return -2 + end +end + +local stored = redis.call('SET', key, ARGV[1]) +if stored ~= 'OK' then return -3 end +return 1 diff --git a/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-pending-register.lua b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-pending-register.lua new file mode 100644 index 0000000000..e418c31961 --- /dev/null +++ b/services/account-service/src/main/resources/redis/lua/account-game-session-delegation-pending-register.lua @@ -0,0 +1,39 @@ +if #KEYS ~= 1 or #ARGV ~= 2 then + return -4 +end + +local key = KEYS[1] +if not string.match(key, '^session:auth:token:[0-9a-f]+$') + or string.len(key) ~= string.len('session:auth:token:') + 64 then + return -4 +end + +local record = ARGV[1] +if not record or string.len(record) == 0 or string.len(record) > 16384 then + return -4 +end + +local targetExpiry = tonumber(ARGV[2]) +if not targetExpiry or targetExpiry <= 0 or targetExpiry > 9007199254740991 + or targetExpiry ~= math.floor(targetExpiry) then + return -4 +end + +local current = redis.call('GET', key) +if current then + if current ~= record then + return -1 + end + local currentExpiry = redis.call('PEXPIRETIME', key) + if currentExpiry ~= targetExpiry then + return -2 + end + redis.call('SET', key, record, 'PXAT', ARGV[2]) + return 0 +end + +local stored = redis.call('SET', key, record, 'PXAT', ARGV[2], 'NX') +if stored ~= 'OK' then + return -3 +end +return 1 diff --git a/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-activate-committed.json b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-activate-committed.json new file mode 100644 index 0000000000..3e74df4555 --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-activate-committed.json @@ -0,0 +1,75 @@ +{ + "scriptId": "account-game-session-delegation-activate-committed.v1", + "resourcePath": "redis/lua/account-game-session-delegation-activate-committed.lua", + "sha256": "cb3c1ddd9ae008fa857427f721c1cabcf3d6b1502259849701baff081bc9a698", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "tokenRecord", + "ownedPrefix": "session:auth:token:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + { + "name": "exactCanonicalPendingRecordUtf8" + }, + { + "name": "exactCanonicalActiveRecordUtf8" + }, + { + "name": "originalAbsoluteExpiryEpochMillis" + } + ], + "category": "SESSION_CAS", + "outcomes": [ + { + "code": "COMMITTED_PENDING_ACTIVATED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "EXACT_ACTIVE_RETRY", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "CONFLICTING_REGISTRY_RECORD", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "ABSOLUTE_EXPIRY_MISMATCH", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + }, + { + "code": "PENDING_RECORD_MISSING", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "INVALID_ARGUMENTS_OR_NONCANONICAL_TRANSITION", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + }, + { + "code": "CONDITIONAL_ACTIVE_STORE_FAILED", + "category": "CONTENTION", + "effect": "NON_MUTATING" + } + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "A missing, stale, or unacknowledged Account registry transition denies token use; only exact durable Account issuance owner evidence can support a retry.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + { + "callerVersion": "v1", + "payloadVersion": "v1" + } + ], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer.json b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer.json new file mode 100644 index 0000000000..a9577dc215 --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-authority-project-issuer.json @@ -0,0 +1,69 @@ +{ + "scriptId": "account-game-session-delegation-authority-project-issuer.v1", + "resourcePath": "redis/lua/account-game-session-delegation-authority-project.lua", + "sha256": "ae5a0a23b2712c7509fbe9ff2448a688f26635efde26d2d9981cc6016eafc36d", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "authorityProjection", + "ownedPrefix": "session:auth:generation:issuer:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + { + "name": "canonicalProjectionUtf8" + } + ], + "category": "SESSION_CAS", + "outcomes": [ + { + "code": "PROJECTION_ADVANCED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "EXACT_PROJECTION_RETRY", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "STALE_GENERATION", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "EQUAL_GENERATION_CONFLICT", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "CONDITIONAL_STORE_FAILED", + "category": "CONTENTION", + "effect": "NON_MUTATING" + }, + { + "code": "INVALID_ARGUMENTS", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + }, + { + "code": "STORED_PROJECTION_MALFORMED", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + } + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "Missing or stale source projection denies delegation use until Account reprojects exact owner evidence.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + { + "callerVersion": "v1", + "payloadVersion": "v1" + } + ], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-pending-register.json b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-pending-register.json new file mode 100644 index 0000000000..1e55cfced0 --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-game-session-delegation-pending-register.json @@ -0,0 +1,67 @@ +{ + "scriptId": "account-game-session-delegation-pending-register.v1", + "resourcePath": "redis/lua/account-game-session-delegation-pending-register.lua", + "sha256": "a35fe1e46e6ebdd6522a17daaefd8a3773fbe8e3a0eaf405d5abce5cdeedc3a2", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "tokenRecord", + "ownedPrefix": "session:auth:token:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + { + "name": "canonicalPendingRecordUtf8" + }, + { + "name": "absoluteExpiryEpochMillis" + } + ], + "category": "SESSION_CAS", + "outcomes": [ + { + "code": "PENDING_CREATED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "EXACT_PENDING_RETRY", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "CONFLICTING_RECORD", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "EXPIRY_MISMATCH", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + }, + { + "code": "CONDITIONAL_STORE_FAILED", + "category": "CONTENTION", + "effect": "NON_MUTATING" + }, + { + "code": "INVALID_ARGUMENTS", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + } + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "A missing token registry projection denies token use; Account recovery requires exact durable issuance evidence.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + { + "callerVersion": "v1", + "payloadVersion": "v1" + } + ], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/main/resources/redis/scripts/account-generation-projection-cas.json b/services/account-service/src/main/resources/redis/scripts/account-generation-projection-cas.json new file mode 100644 index 0000000000..4529588b08 --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-generation-projection-cas.json @@ -0,0 +1,65 @@ +{ + "scriptId": "account.account-generation-projection.v1", + "resourcePath": "redis/account_generation_projection_cas.lua", + "sha256": "b8cf7abd202786a0b45b59444d1396a6c821e65284092e21a46a995e19e72507", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "accountGenerationProjection", + "ownedPrefix": "session:auth:generation:account:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + { + "name": "expectedMode" + }, + { + "name": "expectedBytes" + }, + { + "name": "candidateBytes" + } + ], + "category": "SESSION_CAS", + "outcomes": [ + { + "code": "APPLIED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "REPLAY", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "STALE", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "INVALID", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + }, + { + "code": "TTL_PRESENT", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + } + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "On loss, fail closed and rebuild only from Account's exact current durable source snapshot.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + { + "callerVersion": "v1", + "payloadVersion": "v1" + } + ], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/main/resources/redis/scripts/account-selected-membership-generation-projection.json b/services/account-service/src/main/resources/redis/scripts/account-selected-membership-generation-projection.json new file mode 100644 index 0000000000..74996c7d65 --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-selected-membership-generation-projection.json @@ -0,0 +1,65 @@ +{ + "scriptId": "account.selected-membership-generation-projection.v1", + "resourcePath": "redis/account_generation_projection_cas.lua", + "sha256": "b8cf7abd202786a0b45b59444d1396a6c821e65284092e21a46a995e19e72507", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "membershipGenerationProjection", + "ownedPrefix": "session:auth:generation:membership:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + { + "name": "expectedMode" + }, + { + "name": "expectedBytes" + }, + { + "name": "candidateBytes" + } + ], + "category": "SESSION_CAS", + "outcomes": [ + { + "code": "APPLIED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "REPLAY", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "STALE", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "INVALID", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + }, + { + "code": "TTL_PRESENT", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + } + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "On loss deny selected gameplay use; reapply exact Account membership events without sequence gaps.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + { + "callerVersion": "v1", + "payloadVersion": "v1" + } + ], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/main/resources/redis/scripts/account-selected-tenant-generation-projection.json b/services/account-service/src/main/resources/redis/scripts/account-selected-tenant-generation-projection.json new file mode 100644 index 0000000000..ff2e21b7bd --- /dev/null +++ b/services/account-service/src/main/resources/redis/scripts/account-selected-tenant-generation-projection.json @@ -0,0 +1,65 @@ +{ + "scriptId": "account.selected-tenant-generation-projection.v1", + "resourcePath": "redis/account_generation_projection_cas.lua", + "sha256": "b8cf7abd202786a0b45b59444d1396a6c821e65284092e21a46a995e19e72507", + "owner": "account-service", + "principal": "account_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "tenantGenerationProjection", + "ownedPrefix": "session:auth:generation:tenant:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + { + "name": "expectedMode" + }, + { + "name": "expectedBytes" + }, + { + "name": "candidateBytes" + } + ], + "category": "SESSION_CAS", + "outcomes": [ + { + "code": "APPLIED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "REPLAY", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "STALE", + "category": "STALE", + "effect": "NON_MUTATING" + }, + { + "code": "INVALID", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + }, + { + "code": "TTL_PRESENT", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + } + ], + "resetSensitivity": "CLUSTER", + "lossClass": "SESSION_LEASE_CACHE_OR_WAKE_UP", + "tailLossBehavior": "On loss deny selected gameplay use; reapply exact Account source events without sequence gaps.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + { + "callerVersion": "v1", + "payloadVersion": "v1" + } + ], + "legacyPayloadShape": null +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java new file mode 100644 index 0000000000..2f60946867 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -0,0 +1,1932 @@ +package integration.net.firedevops.firemud.accountservice.authordraft; + +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.when; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftTerminalReconciliationService; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Component fixtures stipulate authenticated current-source capture and authenticated definitive + * owner readback. They do not implement or prove those absent producers, RPC or source-writer + * gates. + */ +@Testcontainers(disabledWithoutDocker = true) +class DraftAuthorizationFencePostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void accountAndGlobalRolePendingScopesVersionOnlyTheirExistingAccountTuple() throws Exception { + for (SourceKind kind : List.of(SourceKind.ACCOUNT, SourceKind.GLOBAL_ROLES)) { + for (int isolation : + List.of(Connection.TRANSACTION_REPEATABLE_READ, Connection.TRANSACTION_SERIALIZABLE)) { + Context context = context(); + UUID account = binding(context).actorAccountId(); + UUID other = binding(context).actorAccountId(); + var before = context.dsl().fetch("SELECT * FROM accounts ORDER BY id"); + var authority = context.dsl().fetch("SELECT * FROM account_authority_generations"); + var fences = context.dsl().fetch("SELECT * FROM account_authority_issuance_fences"); + var sources = context.dsl().fetch("SELECT * FROM account_authority_source_records"); + var roles = context.dsl().fetch("SELECT * FROM account_global_role_sources"); + var events = context.dsl().fetch("SELECT * FROM account_authority_outbox_events"); + String originalVersion = accountVersion(context, account); + String otherVersion = accountVersion(context, other); + try (Connection stale = context.dataSource().getConnection()) { + stale.setAutoCommit(false); + stale.setTransactionIsolation(isolation); + try (var statement = stale.createStatement()) { + statement.executeQuery("SELECT id FROM accounts").close(); + var absent = + statement.executeQuery( + "SELECT count(*) FROM account_draft_authorization_source_changes"); + assertThat(absent.next()).isTrue(); + assertThat(absent.getInt(1)).isZero(); + absent.close(); + } + SourceChange change = + new SourceChange(UUID.randomUUID(), List.of(source(kind, account)), new byte[] {12}); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isTrue(); + assertThat(accountVersion(context, account)).isNotEqualTo(originalVersion); + assertThat(accountVersion(context, other)).isEqualTo(otherVersion); + assertThat(context.dsl().fetch("SELECT * FROM accounts ORDER BY id")).isEqualTo(before); + assertThat(context.dsl().fetch("SELECT * FROM account_authority_generations")) + .isEqualTo(authority); + assertThat(context.dsl().fetch("SELECT * FROM account_authority_issuance_fences")) + .isEqualTo(fences); + assertThat(context.dsl().fetch("SELECT * FROM account_authority_source_records")) + .isEqualTo(sources); + assertThat(context.dsl().fetch("SELECT * FROM account_global_role_sources")) + .isEqualTo(roles); + assertThat(context.dsl().fetch("SELECT * FROM account_authority_outbox_events")) + .isEqualTo(events); + try (var lock = + stale.prepareStatement("SELECT id FROM accounts WHERE account_uuid = ? FOR SHARE")) { + lock.setObject(1, account); + assertThatThrownBy(lock::executeQuery) + .isInstanceOf(SQLException.class) + .extracting("SQLState") + .isEqualTo("40001"); + } + stale.rollback(); + } + } + } + } + + @Test + void producerLocksDeduplicatedAccountsInUuidOrderBeforeAnySourceLocks() throws Exception { + Context context = context(); + List accounts = + List.of(binding(context).actorAccountId(), binding(context).actorAccountId()).stream() + .sorted(java.util.Comparator.comparing(UUID::toString)) + .toList(); + UUID first = accounts.getFirst(); + UUID last = accounts.getLast(); + SourceChange change = + new SourceChange( + UUID.randomUUID(), + List.of( + source(SourceKind.ACCOUNT, last), + source(SourceKind.GLOBAL_ROLES, first), + source(SourceKind.GLOBAL_ROLES, last)), + new byte[] {12}); + tx( + context, + () -> { + for (SourceEvidence source : change.sources()) { + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + source.key()); + } + return null; + }); + CountDownLatch started = new CountDownLatch(1); + AtomicInteger waitingPid = new AtomicInteger(); + try (var executor = Executors.newSingleThreadExecutor()) { + var claimed = + tx( + context, + () -> { + context + .dsl() + .fetchOne("SELECT id FROM accounts WHERE account_uuid = ? FOR UPDATE", first); + int blockerPid = + Objects.requireNonNull( + context.dsl().fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected blocking PostgreSQL backend") + .get("pid", Integer.class); + var task = + executor.submit( + () -> + tx( + context, + () -> { + context.dsl().execute("SET LOCAL lock_timeout = '10s'"); + waitingPid.set( + Objects.requireNonNull( + context + .dsl() + .fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected waiting PostgreSQL backend") + .get("pid", Integer.class)); + started.countDown(); + return context.repository().requestSourceChange(change); + })); + await(started); + awaitBlocked(context, waitingPid.get(), blockerPid); + context + .dsl() + .fetchOne( + "SELECT id FROM accounts WHERE account_uuid = ? FOR UPDATE NOWAIT", last); + for (SourceEvidence source : change.sources()) { + context + .dsl() + .fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE NOWAIT", + source.key()); + } + return task; + }); + assertThat(claimed.get(15, TimeUnit.SECONDS)).isTrue(); + } + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isTrue(); + } + + @Test + void scopeInsertVersionsAccountBeforeTheExistingParentLockingTrigger() throws Exception { + Context context = context(); + UUID account = binding(context).actorAccountId(); + UUID change = UUID.randomUUID(); + String key = "ACCOUNT:" + account; + tx( + context, + () -> { + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change, + new byte[] {12}); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + key); + return null; + }); + CountDownLatch started = new CountDownLatch(1); + AtomicInteger waitingPid = new AtomicInteger(); + try (var executor = Executors.newSingleThreadExecutor()) { + var inserted = + tx( + context, + () -> { + context + .dsl() + .fetchOne( + "SELECT change_id FROM account_draft_authorization_source_changes WHERE change_id = ? FOR UPDATE", + change); + int blockerPid = + Objects.requireNonNull( + context.dsl().fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected blocking PostgreSQL backend") + .get("pid", Integer.class); + var task = + executor.submit( + () -> + tx( + context, + () -> { + context.dsl().execute("SET LOCAL lock_timeout = '10s'"); + waitingPid.set( + Objects.requireNonNull( + context + .dsl() + .fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected waiting PostgreSQL backend") + .get("pid", Integer.class)); + started.countDown(); + return context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", + change, + key); + })); + await(started); + awaitBlocked(context, waitingPid.get(), blockerPid); + try (Connection observer = context.dataSource().getConnection(); + var lock = + observer.prepareStatement( + "SELECT id FROM accounts WHERE account_uuid = ? FOR UPDATE NOWAIT")) { + lock.setObject(1, account); + assertThatThrownBy(lock::executeQuery) + .isInstanceOf(SQLException.class) + .extracting("SQLState") + .isEqualTo("55P03"); + } catch (SQLException failure) { + throw new IllegalStateException(failure); + } + return task; + }); + assertThat(inserted.get(15, TimeUnit.SECONDS)).isEqualTo(1); + } + } + + @Test + void applicableMissingOrMalformedAccountScopesDenyWithoutCreatingAccountOrIntent() { + Context context = context(); + UUID absent = UUID.randomUUID(); + SourceChange missing = + new SourceChange( + UUID.randomUUID(), List.of(source(SourceKind.ACCOUNT, absent)), new byte[] {12}); + assertThatThrownBy(() -> tx(context, () -> context.repository().requestSourceChange(missing))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("persisted Account"); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_locks"))) + .isZero(); + for (String key : + List.of( + "ACCOUNT:" + absent, + "GLOBAL_ROLES:" + absent, + "ACCOUNT:42", + "GLOBAL_ROLES:00000000-0000-0000-0000-000000000000", + "ACCOUNT")) { + assertThatThrownBy(() -> insertScope(context, key)).isInstanceOf(DataAccessException.class); + } + assertThat(context.dsl().fetchCount(DSL.table("accounts"))).isZero(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isZero(); + insertScope(context, "TENANT:" + absent); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_changed_scopes"))) + .isEqualTo(1); + } + + @Test + void twoOwnerConsumerPersistsWorldOnceAndRecoversMissingGameDesignOnRetry() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + OwnerReadback worldAbort = + ownerReadback(binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {31}); + OwnerReadback gameDesignAbort = + ownerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {32}); + GameDesignDraftTerminalReadClient gameDesignClient = + mock(GameDesignDraftTerminalReadClient.class); + WorldDraftTerminalReadClient worldClient = mock(WorldDraftTerminalReadClient.class); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + assertThat(request.originalAccountBinding()) + .containsExactly(binding.canonicalBytes()); + return new GameDesignDraftTerminalReadEvidence(request, Optional.empty()); + }) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + assertThat(request.originalAccountBinding()) + .containsExactly(binding.canonicalBytes()); + return new GameDesignDraftTerminalReadEvidence(request, Optional.of(gameDesignAbort)); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + assertThat(request.originalAccountBinding()) + .containsExactly(binding.canonicalBytes()); + return new WorldDraftTerminalReadEvidence(request, Optional.of(worldAbort)); + }); + var service = + new AccountDraftTerminalReconciliationService( + context.repository(), + context.transaction().getTransactionManager(), + gameDesignClient, + worldClient, + "firemud-test"); + + assertThat(service.reconcile(binding.operationId())).contains(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD))) + .get() + .satisfies( + stored -> assertThat(stored.readback()).containsExactly(worldAbort.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .isEmpty(); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + + assertThat(service.reconcile(binding.operationId())).contains(Settlement.FAILED_NONPUBLICATION); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD))) + .get() + .satisfies( + stored -> assertThat(stored.readback()).containsExactly(worldAbort.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .get() + .satisfies( + stored -> + assertThat(stored.readback()).containsExactly(gameDesignAbort.canonicalBytes())); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + verify(gameDesignClient, times(2)).read(any()); + verify(worldClient).read(any()); + } + + @Test + void mixedCommitOrderPreservesOriginalWorldCommitAndHoldsSourceFence() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + OwnerReadback originalWorldCommit = + ownerReadback(binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {41, 42}); + OwnerReadback gameDesignAbort = + ownerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {43}); + GameDesignDraftTerminalReadClient gameDesignClient = + mock(GameDesignDraftTerminalReadClient.class); + WorldDraftTerminalReadClient worldClient = mock(WorldDraftTerminalReadClient.class); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence(request, Optional.of(gameDesignAbort)); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return worldEvidence(request, originalWorldCommit); + }); + var service = + new AccountDraftTerminalReconciliationService( + context.repository(), + context.transaction().getTransactionManager(), + gameDesignClient, + worldClient, + "firemud-test"); + + assertThat(service.reconcile(binding.operationId())).contains(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD))) + .get() + .satisfies( + stored -> + assertThat(stored.readback()) + .containsExactly(originalWorldCommit.canonicalBytes())); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + assertThat(service.reconcile(binding.operationId())).contains(Settlement.PENDING); + verify(gameDesignClient).read(any()); + verify(worldClient).read(any()); + } + + @Test + void concurrentExactConsumerRetriesReturnTheSameOriginalSettlement() throws Exception { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + OwnerReadback worldAbort = + ownerReadback(binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {51}); + OwnerReadback gameDesignAbort = + ownerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {52}); + CountDownLatch concurrentWorldReads = new CountDownLatch(2); + GameDesignDraftTerminalReadClient gameDesignClient = + mock(GameDesignDraftTerminalReadClient.class); + WorldDraftTerminalReadClient worldClient = mock(WorldDraftTerminalReadClient.class); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence(request, Optional.of(gameDesignAbort)); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + concurrentWorldReads.countDown(); + await(concurrentWorldReads); + return new WorldDraftTerminalReadEvidence(request, Optional.of(worldAbort)); + }); + var service = + new AccountDraftTerminalReconciliationService( + context.repository(), + context.transaction().getTransactionManager(), + gameDesignClient, + worldClient, + "firemud-test"); + + try (var executor = Executors.newFixedThreadPool(2)) { + var first = executor.submit(() -> reconcileAttempt(service, binding.operationId())); + var second = executor.submit(() -> reconcileAttempt(service, binding.operationId())); + List attempts = + List.of(first.get(15, TimeUnit.SECONDS), second.get(15, TimeUnit.SECONDS)); + assertThat(attempts) + .allSatisfy( + attempt -> { + assertThat(attempt.failure()).isNull(); + assertThat(attempt.settlement()).isEqualTo(Settlement.FAILED_NONPUBLICATION); + }); + } + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD))) + .get() + .satisfies( + stored -> assertThat(stored.readback()).containsExactly(worldAbort.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .get() + .satisfies( + stored -> + assertThat(stored.readback()).containsExactly(gameDesignAbort.canonicalBytes())); + } + + @Test + void concurrentConflictingOwnerEvidenceRejectsRetryAndPreservesWinningBytes() throws Exception { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + OwnerReadback gameDesignAbort = + ownerReadback(binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {61}); + CountDownLatch concurrentWorldReads = new CountDownLatch(2); + AtomicInteger resultSequence = new AtomicInteger(); + Map returnedWorldResults = new ConcurrentHashMap<>(); + GameDesignDraftTerminalReadClient gameDesignClient = + mock(GameDesignDraftTerminalReadClient.class); + WorldDraftTerminalReadClient worldClient = mock(WorldDraftTerminalReadClient.class); + when(gameDesignClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence(request, Optional.of(gameDesignAbort)); + }); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + assertOutsideOwnerTransaction(); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + int resultNumber = resultSequence.incrementAndGet(); + OwnerReadback worldAbort = + ownerReadback( + binding, + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {(byte) (60 + resultNumber)}); + returnedWorldResults.put(request.readRequestId(), worldAbort); + concurrentWorldReads.countDown(); + await(concurrentWorldReads); + return new WorldDraftTerminalReadEvidence(request, Optional.of(worldAbort)); + }); + var service = + new AccountDraftTerminalReconciliationService( + context.repository(), + context.transaction().getTransactionManager(), + gameDesignClient, + worldClient, + "firemud-test"); + + List attempts; + try (var executor = Executors.newFixedThreadPool(2)) { + var first = executor.submit(() -> reconcileAttempt(service, binding.operationId())); + var second = executor.submit(() -> reconcileAttempt(service, binding.operationId())); + attempts = List.of(first.get(15, TimeUnit.SECONDS), second.get(15, TimeUnit.SECONDS)); + } + List successes = + attempts.stream().filter(attempt -> attempt.failure() == null).toList(); + List rejected = + attempts.stream().filter(attempt -> attempt.failure() != null).toList(); + assertThat(successes).hasSize(1); + assertThat(successes.getFirst().settlement()).isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat(rejected).hasSize(1); + assertThat(rejected.getFirst().failure()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Concurrent owner recovery changed immutable evidence"); + byte[] storedWorldReadback = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow() + .readback(); + assertThat(returnedWorldResults.values()) + .anySatisfy( + returned -> assertThat(returned.canonicalBytes()).containsExactly(storedWorldReadback)); + assertThat(tx(context, () -> context.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .get() + .satisfies( + stored -> + assertThat(stored.readback()).containsExactly(gameDesignAbort.canonicalBytes())); + } + + @Test + void revokeBeforeCommitDeniesDelayedRequestsUntilBothDefinitiveAborts() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + SourceChange change = change(binding); + tx(context, () -> context.repository().reserve(binding)); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThatThrownBy(() -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {1}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + owner(context, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {2}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + assertThatThrownBy(() -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void worldCommittedAndGameDesignUnknownSurviveRestartAndBlockSourceUntilExactBothReadbacks() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {4}); + Context restarted = + new Context( + context.dsl(), + context.dataSource(), + new DraftAuthorizationFenceRepository(context.dsl()), + context.transaction()); + assertThat(tx(restarted, () -> restarted.repository().sourceMutationPermitted(change))) + .isFalse(); + assertThat(tx(restarted, () -> restarted.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat( + tx(restarted, () -> restarted.repository().readOwnerResult(binding, Owner.GAME_DESIGN))) + .isEmpty(); + assertSourceGuardBlocked(restarted, change); + // Missing GD evidence models timeout/unavailable/absent owner row: no terminality is + // synthesized. + assertThat(tx(restarted, () -> restarted.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(restarted, binding, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {5}); + assertThat(tx(restarted, () -> restarted.repository().readSettlement(binding))) + .isEqualTo(Settlement.COMMITTED); + assertThat(tx(restarted, () -> restarted.repository().sourceMutationPermitted(change))) + .isTrue(); + tx( + restarted, + () -> { + restarted.repository().markSourceCommitted(change); + return null; + }); + assertThat(tx(restarted, () -> restarted.repository().requestSourceChange(change))).isTrue(); + assertThat(tx(restarted, () -> restarted.repository().claimCommitOrder(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(restarted, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {4}); + assertThatThrownBy( + () -> owner(restarted, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {9})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void commitOrderWithBothDefinitiveAbortsReleasesOriginalWaitingIntentWithoutReopening() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {21}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + owner(context, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {22}); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + var waiting = tx(context, () -> context.repository().readSourceChange(change)); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + var committed = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(committed.status()).isEqualTo("SOURCE_COMMITTED"); + assertThat(committed.requestedAt()).isEqualTo(waiting.requestedAt()); + assertThat(committed.binding()).containsExactly(waiting.binding()); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + var replay = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(replay.committedAt()).isEqualTo(committed.committedAt()); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + assertThat(tx(context, () -> context.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {21}); + assertThatThrownBy( + () -> owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {23})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void bothMixedDirectionsRemainPendingAndPreserveOriginalReadbacks() { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + var ordered = tx(context, () -> context.repository().claimCommitOrder(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + var waiting = tx(context, () -> context.repository().readSourceChange(change)); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + var originalWorld = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + Outcome gameDesignOutcome = + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED; + owner(context, binding, Owner.GAME_DESIGN, gameDesignOutcome, new byte[] {2}); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThat(tx(context, () -> context.repository().sourceAbortPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + var held = tx(context, () -> context.repository().readSourceChange(change)); + assertThat(held.status()).isEqualTo("WAITING"); + assertThat(held.binding()).containsExactly(waiting.binding()); + assertThat(held.requestedAt()).isEqualTo(waiting.requestedAt()); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + assertThat(tx(context, () -> context.repository().read(binding)).orderedAt()) + .isEqualTo(ordered.orderedAt()); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + var replay = + tx(context, () -> context.repository().readOwnerResult(binding, Owner.WORLD)) + .orElseThrow(); + assertThat(replay.outcome()).isEqualTo(originalWorld.outcome()); + assertThat(replay.readback()).containsExactly(originalWorld.readback()); + assertThat(replay.recordedAt()).isEqualTo(originalWorld.recordedAt()); + assertThatThrownBy(() -> owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {9})) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> owner(context, binding, Owner.WORLD, gameDesignOutcome, new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void revokeOrderWithEitherMixedDirectionCannotAuthorizeSourceMutation() { + for (Outcome worldOutcome : List.of(Outcome.COMMITTED, Outcome.DEFINITIVELY_ABORTED)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + owner(context, binding, Owner.WORLD, worldOutcome, new byte[] {1}); + owner( + context, + binding, + Owner.GAME_DESIGN, + worldOutcome == Outcome.COMMITTED ? Outcome.DEFINITIVELY_ABORTED : Outcome.COMMITTED, + new byte[] {2}); + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(Ordering.REVOKE_ORDER); + assertThat(tx(context, () -> context.repository().readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertSourceGuardBlocked(context, change); + } + } + + @Test + void changedCompleteBindingsConflictWithoutRewritingOriginal() { + Context context = context(); + DraftAuthorizationFenceBinding original = binding(context); + var stored = tx(context, () -> context.repository().reserve(original)); + assertThat(tx(context, () -> context.repository().readSettlement(original))) + .isEqualTo(Settlement.PENDING); + for (int field = 0; field < 6; field++) { + DraftAuthorizationFenceBinding changed = changed(original, field); + assertThatThrownBy(() -> tx(context, () -> context.repository().reserve(changed))) + .isInstanceOf(IllegalArgumentException.class); + } + var replay = tx(context, () -> context.repository().reserve(original)); + assertThat(replay.binding()).containsExactly(stored.binding()); + assertThat(replay.reservedAt()).isEqualTo(stored.reservedAt()); + } + + @Test + void inconsistentOrMalformedCompleteBindingsFailBeforeReservationStorage() { + Context context = context(); + DraftAuthorizationFenceBinding b = binding(context); + for (int field = 0; field < 9; field++) { + int changedField = field; + byte[] bytes = field == 6 ? new byte[] {11} : b.gameDesignBinding(); + if (field == 8) { + bytes = + new String(bytes, StandardCharsets.UTF_8) + .replace("\"revisionOrder\":\"0\"", "\"revisionOrder\":\"1\"") + .getBytes(StandardCharsets.UTF_8); + } + byte[] gameDesign = bytes; + byte[] input = field == 5 ? new byte[] {10} : gameDesign; + String digest = + field == 7 + ? DraftAuthorizationFenceBinding.digest(new byte[] {12}) + : DraftAuthorizationFenceBinding.digest(input); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .repository() + .reserve( + new DraftAuthorizationFenceBinding( + b.operationId(), + changedField == 0 ? UUID.randomUUID() : b.requestId(), + changedField == 1 ? UUID.randomUUID() : b.commitId(), + b.fenceId(), + b.actorAccountId(), + changedField == 2 ? UUID.randomUUID() : b.tenantId(), + changedField == 3 ? UUID.randomUUID() : b.versionId(), + changedField == 4 ? "different/base" : b.baseCommitId(), + b.expectedDraftEpoch(), + gameDesign, + input, + digest, + b.sources())))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_sources"))) + .isZero(); + } + var stored = tx(context, () -> context.repository().reserve(b)); + assertThat(tx(context, () -> context.repository().reserve(b)).binding()) + .containsExactly(stored.binding()); + } + + @Test + void rollbackPreservesReservationAndIntentTogetherAndDisjointSourcesDoNotConflict() { + Context context = context(); + DraftAuthorizationFenceBinding original = binding(context); + assertThatThrownBy( + () -> + tx( + context, + () -> { + context.repository().reserve(original); + context.repository().requestSourceChange(change(original)); + throw new IllegalStateException("injected rollback"); + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> tx(context, () -> context.repository().read(original))) + .isInstanceOf(IllegalArgumentException.class); + tx(context, () -> context.repository().reserve(original)); + tx(context, () -> context.repository().requestSourceChange(change(original))); + DraftAuthorizationFenceBinding independent = binding(context); + tx(context, () -> context.repository().reserve(independent)); + assertThat(tx(context, () -> context.repository().claimCommitOrder(independent)).ordering()) + .isEqualTo(Ordering.COMMIT_ORDER); + } + + @Test + void distinctPendingChangesCannotRetainTwoOldCapturesForTheSameSource() { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + SourceChange first = change(binding); + SourceChange second = change(binding); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + var original = tx(context, () -> context.repository().readSourceChange(first)); + + assertThatThrownBy(() -> tx(context, () -> context.repository().requestSourceChange(second))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("already pending"); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(1); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + var exactRetry = tx(context, () -> context.repository().readSourceChange(first)); + assertThat(exactRetry.binding()).containsExactly(original.binding()); + assertThat(exactRetry.requestedAt()).isEqualTo(original.requestedAt()); + + // This storage fixture stipulates definitive owner evidence; it does not authenticate it. + owner(context, binding, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + owner(context, binding, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {2}); + tx( + context, + () -> { + context.repository().markSourceCommitted(first); + return null; + }); + assertThat(tx(context, () -> context.repository().requestSourceChange(second))).isTrue(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(2); + } + + @Test + void concurrentDistinctSourceClaimsAdmitOnlyOnePendingCaptureWithoutBlockingDisjointSources() + throws Exception { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + SourceChange first = change(binding); + SourceChange second = change(binding); + tx(context, () -> context.repository().reserve(binding)); + tx(context, () -> context.repository().claimCommitOrder(binding)); + CountDownLatch firstClaimed = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var firstTask = + executor.submit( + () -> + tx( + context, + () -> { + boolean permitted = context.repository().requestSourceChange(first); + firstClaimed.countDown(); + await(secondStarted); + return permitted; + })); + var secondTask = + executor.submit( + () -> { + await(firstClaimed); + secondStarted.countDown(); + assertThatThrownBy( + () -> tx(context, () -> context.repository().requestSourceChange(second))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("already pending"); + }); + assertThat(firstTask.get(15, TimeUnit.SECONDS)).isFalse(); + secondTask.get(15, TimeUnit.SECONDS); + } + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(1); + assertThat(tx(context, () -> context.repository().requestSourceChange(first))).isFalse(); + SourceChange disjoint = change(binding(context)); + assertThat(tx(context, () -> context.repository().requestSourceChange(disjoint))).isTrue(); + assertThat(context.dsl().fetchCount(DSL.table("account_draft_authorization_source_changes"))) + .isEqualTo(2); + } + + @Test + void concurrentCommitOrderAndRevocationChooseExactlyOneDurableOrdering() throws Exception { + for (boolean commitWins : List.of(true, false)) { + Context context = context(); + DraftAuthorizationFenceBinding binding = binding(context); + SourceChange change = change(binding); + tx(context, () -> context.repository().reserve(binding)); + CountDownLatch firstOrdered = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var first = + executor.submit( + () -> + tx( + context, + () -> { + if (commitWins) { + context.repository().claimCommitOrder(binding); + } else { + context.repository().requestSourceChange(change); + } + firstOrdered.countDown(); + await(secondStarted); + return null; + })); + var second = + executor.submit( + () -> { + await(firstOrdered); + secondStarted.countDown(); + if (commitWins) { + return tx(context, () -> context.repository().requestSourceChange(change)); + } + assertThatThrownBy( + () -> tx(context, () -> context.repository().claimCommitOrder(binding))) + .isInstanceOf(IllegalStateException.class); + return false; + }); + first.get(15, TimeUnit.SECONDS); + assertThat(second.get(15, TimeUnit.SECONDS)).isFalse(); + } + assertThat(tx(context, () -> context.repository().read(binding)).ordering()) + .isEqualTo(commitWins ? Ordering.COMMIT_ORDER : Ordering.REVOKE_ORDER); + } + } + + @Test + void originalBindingSurvivesRestartAndAbsenceRemainsUnknownUnderOwnerTransaction() { + Context context = context(); + var binding = binding(context); + tx(context, () -> context.repository().reserve(binding)); + Context restarted = + new Context( + context.dsl(), + context.dataSource(), + new DraftAuthorizationFenceRepository(context.dsl()), + context.transaction()); + var restored = + tx(restarted, () -> restarted.repository().readOriginalBinding(binding.operationId())) + .orElseThrow(); + assertThat(restored.canonicalBytes()).containsExactly(binding.canonicalBytes()); + assertThat(tx(restarted, () -> restarted.repository().readOriginalBinding(UUID.randomUUID()))) + .isEmpty(); + assertThatThrownBy(() -> restarted.repository().readOriginalBinding(binding.operationId())) + .isInstanceOf(IllegalStateException.class); + restarted.transaction().setReadOnly(true); + try { + assertThatThrownBy( + () -> + tx( + restarted, + () -> restarted.repository().readOriginalBinding(binding.operationId()))) + .isInstanceOf(IllegalStateException.class); + } finally { + restarted.transaction().setReadOnly(false); + } + assertThatThrownBy( + () -> tx(restarted, () -> restarted.repository().readUnresolvedOperations(null, 0))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> tx(restarted, () -> restarted.repository().readUnresolvedOperations(null, 101))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void discoveryPagesOriginalPendingOperationsAndExcludesEverySettledVector() { + Context context = context(); + var reserved = binding(context); + var committedUnknown = binding(context); + var revokedUnknown = binding(context); + var revokedContradiction = binding(context); + var committed = binding(context); + var mixed = binding(context); + var aborted = binding(context); + var revokedAborted = binding(context); + List all = + List.of( + reserved, + committedUnknown, + revokedUnknown, + revokedContradiction, + committed, + mixed, + aborted, + revokedAborted); + // One timestamp tests the UUID tie-breaker rather than relying on clock resolution. + tx( + context, + () -> { + for (var b : all) context.repository().reserve(b); + return null; + }); + for (var b : List.of(committedUnknown, committed, mixed, aborted)) { + tx(context, () -> context.repository().claimCommitOrder(b)); + } + for (var b : List.of(revokedUnknown, revokedContradiction, revokedAborted)) { + tx(context, () -> context.repository().requestSourceChange(change(b))); + } + owner(context, committedUnknown, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + owner(context, revokedContradiction, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + owner( + context, + revokedContradiction, + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {2}); + for (var b : List.of(committed, mixed, aborted, revokedAborted)) { + owner( + context, + b, + Owner.WORLD, + b == committed || b == mixed ? Outcome.COMMITTED : Outcome.DEFINITIVELY_ABORTED, + new byte[] {1}); + owner( + context, + b, + Owner.GAME_DESIGN, + b == committed ? Outcome.COMMITTED : Outcome.DEFINITIVELY_ABORTED, + new byte[] {2}); + } + var expected = + List.of(reserved, committedUnknown, revokedUnknown, revokedContradiction, mixed).stream() + .sorted(java.util.Comparator.comparing(b -> b.operationId().toString())) + .toList(); + var first = tx(context, () -> context.repository().readUnresolvedOperations(null, 2)); + var second = + tx( + context, + () -> context.repository().readUnresolvedOperations(first.getLast().cursor(), 3)); + assertThat(first).hasSize(2); + assertThat(second).hasSize(3); + var combined = java.util.stream.Stream.concat(first.stream(), second.stream()).toList(); + assertThat(combined.stream().map(item -> item.binding().operationId()).toList()) + .containsExactlyElementsOf( + expected.stream().map(DraftAuthorizationFenceBinding::operationId).toList()); + for (int i = 0; i < expected.size(); i++) { + assertThat(combined.get(i).binding().canonicalBytes()) + .containsExactly(expected.get(i).canonicalBytes()); + } + assertThat( + tx( + context, + () -> context.repository().readUnresolvedOperations(second.getLast().cursor(), 2))) + .isEmpty(); + owner(context, committedUnknown, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {2}); + assertThat(tx(context, () -> context.repository().readUnresolvedOperations(null, 100))) + .extracting(item -> item.binding().operationId()) + .doesNotContain(committedUnknown.operationId()); + } + + @Test + void originalRecoveryRejectsMalformedBytesAndEveryConflictingIdentityColumn() { + for (int field = 0; field < 5; field++) { + Context context = context(); + var b = binding(context); + UUID operation = field == 0 ? UUID.randomUUID() : b.operationId(); + UUID request = field == 1 ? UUID.randomUUID() : b.requestId(); + UUID commit = field == 2 ? UUID.randomUUID() : b.commitId(); + UUID fence = field == 3 ? UUID.randomUUID() : b.fenceId(); + byte[] stored = field == 4 ? new byte[] {1} : b.canonicalBytes(); + // The production guard permits first insertion of opaque bytes; recovery must verify them. + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_fences" + + " (operation_id, request_id, commit_id, fence_id, binding, ordering)" + + " VALUES (?, ?, ?, ?, ?, 'RESERVED')", + operation, + request, + commit, + fence, + stored)); + assertThatThrownBy( + () -> tx(context, () -> context.repository().readOriginalBinding(operation))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> tx(context, () -> context.repository().readUnresolvedOperations(null, 10))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void ownerRecoveryRejectsReadbackThatContradictsItsOutcomeColumn() { + Context context = context(); + var b = binding(context); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var readback = + new OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + b.operationId(), + b.commitId(), + b.fenceId(), + b.inputDigest(), + b.canonicalBytes(), + new byte[] {1}); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_owner_readbacks" + + " (operation_id, owner, outcome, readback) VALUES (?, 'WORLD', 'DEFINITIVELY_ABORTED', ?)", + b.operationId(), + readback.canonicalBytes()))) + .isInstanceOf(DataAccessException.class); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))).isEmpty(); + } + + @Test + void v2WorldEntityAndCoordinatorRequireAllThreeExactOriginalResults() { + Context context = context(); + var b = multiOwnerBinding(context); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var change = change(b); + tx(context, () -> context.repository().requestSourceChange(change)); + owner(context, b, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {1}); + owner(context, b, Owner.WORLD, Outcome.COMMITTED, new byte[] {2}); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isFalse(); + assertSourceGuardBlocked(context, change); + assertThat(tx(context, () -> context.repository().readUnresolvedOperations(null, 100))) + .extracting(item -> item.binding().operationId()) + .contains(b.operationId()); + var entity = ownerReadback(b, Owner.ENTITY, Outcome.COMMITTED, new byte[] {3}); + // Structurally substituted owner, digest, full binding, result and trailing frames all fail. + for (byte[] invalid : + List.of( + java.util.Arrays.copyOf(entity.canonicalBytes(), entity.canonicalBytes().length - 1), + java.util.Arrays.copyOf(entity.canonicalBytes(), entity.canonicalBytes().length + 1), + ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {3}).canonicalBytes(), + ownerReadback(binding(context), Owner.WORLD, Outcome.COMMITTED, new byte[] {3}) + .canonicalBytes())) { + assertThatThrownBy(() -> insertOwner(context, b, "ENTITY", "COMMITTED", invalid)) + .isInstanceOf(DataAccessException.class); + } + assertThatThrownBy( + () -> insertOwner(context, b, "AUTOMATION", "COMMITTED", entity.canonicalBytes())) + .isInstanceOf(DataAccessException.class); + owner(context, b, Owner.ENTITY, Outcome.COMMITTED, new byte[] {3}); + assertThatThrownBy( + () -> insertOwner(context, b, "ENTITY", "COMMITTED", entity.canonicalBytes())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> owner(context, b, Owner.ENTITY, Outcome.COMMITTED, new byte[] {4})) + .isInstanceOf(IllegalArgumentException.class); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.COMMITTED); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + } + + @Test + void v2FreshDraftEpochZeroAcceptsExactRequiredOwnerReadback() { + Context context = context(); + var prior = multiOwnerBinding(context); + var b = + new DraftAuthorizationFenceBinding( + prior.operationId(), + prior.requestId(), + prior.commitId(), + prior.fenceId(), + prior.actorAccountId(), + prior.tenantId(), + prior.versionId(), + prior.baseCommitId(), + "0", + prior.gameDesignBinding(), + prior.normalizedInput(), + prior.inputDigest(), + prior.sources()) + .withRequiredOwners(); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var readback = ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + insertOwner(context, b, "WORLD", "COMMITTED", readback.canonicalBytes()); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))) + .get() + .satisfies( + result -> assertThat(result.readback()).containsExactly(readback.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + } + + @Test + void rawSqlCannotRecordOwnerProofWithMissingChangedOrExtraSourceParticipation() { + for (int sourceShape = 0; sourceShape < 4; sourceShape++) { + Context context = context(); + var b = multiOwnerBinding(context); + var source = b.sources().getFirst(); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_fences" + + " (operation_id, request_id, commit_id, fence_id, binding, ordering)" + + " VALUES (?, ?, ?, ?, ?, 'RESERVED')", + b.operationId(), + b.requestId(), + b.commitId(), + b.fenceId(), + b.canonicalBytes()); + if (sourceShape != 0) { + String key = sourceShape == 2 ? source.key() + "/changed" : source.key(); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + key); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + b.operationId(), + key, + sourceShape == 1 ? new byte[] {99} : source.canonicalBytes()); + if (sourceShape == 3) { + String extraKey = source.key() + "/extra"; + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + extraKey); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + b.operationId(), + extraKey, + source.canonicalBytes()); + } + } + context + .dsl() + .execute( + "UPDATE account_draft_authorization_fences SET ordering = 'COMMIT_ORDER'," + + " ordered_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + b.operationId()); + var readback = ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + assertThatThrownBy( + () -> insertOwner(context, b, "WORLD", "COMMITTED", readback.canonicalBytes())) + .isInstanceOf(DataAccessException.class); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(*) FROM account_draft_authorization_owner_readbacks WHERE operation_id = ?", + b.operationId())) + .get(0, Integer.class)) + .isZero(); + } + } + + @Test + void v2RequiredOwnerDecoderRejectsMissingExtraDuplicateAndReorderedOwners() { + Context context = context(); + var b = multiOwnerBinding(context); + for (var labels : + List.of( + List.of("GAME_DESIGN", "WORLD"), + List.of("GAME_DESIGN", "WORLD", "ENTITY", "AUTOMATION"), + List.of("GAME_DESIGN", "WORLD", "WORLD"), + List.of("GAME_DESIGN", "ENTITY", "WORLD"))) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(b.canonicalBytes()); + var output = new java.io.ByteArrayOutputStream(); + for (int i = 0; i < 15 + b.sources().size(); i++) { + DraftAuthorizationFenceBinding.frame(output, reader.bytes()); + } + DraftAuthorizationFenceBinding.frame(output, Integer.toString(labels.size())); + labels.forEach(label -> DraftAuthorizationFenceBinding.frame(output, label)); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .fetch( + "SELECT account_draft_authorization_required_owners(?::bytea)", + output.toByteArray()))) + .isInstanceOf(DataAccessException.class); + } + } + + @Test + void v2AllRequiredAbortsSettleBothCommitAndRevokeOrdering() { + for (boolean commitOrder : List.of(true, false)) { + Context context = context(); + var b = multiOwnerBinding(context); + tx(context, () -> context.repository().reserve(b)); + if (commitOrder) tx(context, () -> context.repository().claimCommitOrder(b)); + var change = change(b); + tx(context, () -> context.repository().requestSourceChange(change)); + owner(context, b, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {1}); + owner(context, b, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {2}); + assertSourceGuardBlocked(context, change); + owner(context, b, Owner.ENTITY, Outcome.DEFINITIVELY_ABORTED, new byte[] {3}); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.FAILED_NONPUBLICATION); + tx( + context, + () -> { + context.repository().markSourceCommitted(change); + return null; + }); + assertThat(tx(context, () -> context.repository().readSourceChange(change)).status()) + .isEqualTo("SOURCE_COMMITTED"); + } + } + + @Test + void v2MixedResultsHoldBothSourceTransitionsAndPreserveAppliedBytes() { + Context context = context(); + var b = multiOwnerBinding(context); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var change = change(b); + tx(context, () -> context.repository().requestSourceChange(change)); + owner(context, b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}); + owner(context, b, Owner.ENTITY, Outcome.DEFINITIVELY_ABORTED, new byte[] {2}); + owner(context, b, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {3}); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + assertSourceGuardBlocked(context, change); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes SET status = 'SOURCE_ABORTED'," + + " aborted_at = CURRENT_TIMESTAMP, abort_reason = 'DEFINITIVE_ABORT' WHERE change_id = ?", + change.changeId()))) + .isInstanceOf(DataAccessException.class); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))) + .get() + .satisfies( + result -> + assertThat(result.readback()) + .containsExactly( + ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {1}) + .canonicalBytes())); + } + + @Test + void forwardMigrationRetainsV1BindingReadbackAndFlywayChecksumsExactly() { + Context context = context("92"); + DraftAuthorizationFenceBinding base = binding(context); + SourceEvidence legacy512 = + new SourceEvidence( + SourceKind.ISSUER, "x".repeat(505), "3", "5", "stream/legacy512", "2", new byte[] {9}); + var b = withSources(base, List.of(base.sources().getFirst(), legacy512)); + tx(context, () -> context.repository().reserve(b)); + tx(context, () -> context.repository().claimCommitOrder(b)); + var original = ownerReadback(b, Owner.WORLD, Outcome.COMMITTED, new byte[] {8}); + owner(context, b, Owner.WORLD, Outcome.COMMITTED, new byte[] {8}); + var checksums = + context + .dsl() + .fetch("SELECT version, checksum FROM flyway_schema_history ORDER BY installed_rank"); + String schema = + Objects.requireNonNull(context.dsl().fetchOne("SELECT current_schema()")) + .get(0, String.class); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("93") + .load() + .migrate(); + assertThat( + context + .dsl() + .fetch("SELECT version, checksum FROM flyway_schema_history WHERE version = '93'")) + .hasSize(1); + assertThat( + context + .dsl() + .fetch( + "SELECT version, checksum FROM flyway_schema_history WHERE version IS DISTINCT FROM '93' ORDER BY installed_rank")) + .isEqualTo(checksums); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ?", + legacy512.key()), + "Expected migrated physical source-lock row") + .get(0, String.class)) + .isEqualTo(legacy512.key()); + assertThat(tx(context, () -> context.repository().read(b)).binding()) + .containsExactly(b.canonicalBytes()); + assertThat(tx(context, () -> context.repository().readOwnerResult(b, Owner.WORLD))) + .get() + .satisfies( + result -> assertThat(result.readback()).containsExactly(original.canonicalBytes())); + assertThat(tx(context, () -> context.repository().readSettlement(b))) + .isEqualTo(Settlement.PENDING); + } + + private void insertOwner( + Context context, + DraftAuthorizationFenceBinding binding, + String owner, + String outcome, + byte[] bytes) { + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_owner_readbacks (operation_id, owner, outcome, readback) VALUES (?, ?, ?, ?)", + binding.operationId(), + owner, + outcome, + bytes)); + } + + private void assertSourceGuardBlocked(Context context, SourceChange change) { + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes" + + " SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP" + + " WHERE change_id = ?", + change.changeId()))) + .isInstanceOf(DataAccessException.class); + } + + @Test + void issuerSourceKeysPreserveLegacyAndUnicodeIdentityThroughExactByteBound() { + Context context = context(); + DraftAuthorizationFenceBinding base = binding(context); + SourceEvidence legacy512 = issuerSource("x".repeat(505)); + SourceEvidence longer513 = issuerSource("x".repeat(506)); + SourceEvidence unicode512Characters = issuerSource("a".repeat(8) + "😀".repeat(504)); + SourceEvidence exact2048Bytes = issuerSource("😀".repeat(510) + "a"); + + assertThat(legacy512.key().getBytes(StandardCharsets.UTF_8)).hasSize(512); + assertThat(longer513.key().getBytes(StandardCharsets.UTF_8)).hasSize(513); + assertThat(longer513.key()).startsWith(legacy512.key()).isNotEqualTo(legacy512.key()); + assertThat( + unicode512Characters + .scopeId() + .codePointCount(0, unicode512Characters.scopeId().length())) + .isEqualTo(512); + assertThat(unicode512Characters.key().getBytes(StandardCharsets.UTF_8)).hasSize(2031); + assertThat(exact2048Bytes.key().getBytes(StandardCharsets.UTF_8)).hasSize(2048); + assertThat(exact2048Bytes.scopeId().codePointCount(0, exact2048Bytes.scopeId().length())) + .isEqualTo(511); + assertThatThrownBy(() -> issuerSource("😀".repeat(510) + "ab")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("2048 UTF-8 bytes"); + + var binding = + withSources( + base, + List.of( + base.sources().getFirst(), + legacy512, + longer513, + unicode512Characters, + exact2048Bytes)); + tx(context, () -> context.repository().reserve(binding)); + SourceChange change = change(binding); + assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); + + List exactKeys = binding.sources().stream().map(SourceEvidence::key).toList(); + assertThat( + context + .dsl() + .fetch("SELECT source_key FROM account_draft_authorization_source_locks") + .getValues(0, String.class)) + .containsExactlyInAnyOrderElementsOf(exactKeys); + assertThat( + context + .dsl() + .fetch("SELECT source_key FROM account_draft_authorization_sources") + .getValues(0, String.class)) + .containsExactlyInAnyOrderElementsOf(exactKeys); + assertThat( + context + .dsl() + .fetch("SELECT source_key FROM account_draft_authorization_changed_scopes") + .getValues(0, String.class)) + .containsExactlyInAnyOrderElementsOf(exactKeys); + for (SourceEvidence source : binding.sources()) { + var stored = + context + .dsl() + .fetchOne( + "SELECT source_evidence FROM account_draft_authorization_sources" + + " WHERE operation_id = ? AND source_key = ?", + binding.operationId(), + source.key()); + assertThat(Objects.requireNonNull(stored).get(0, byte[].class)) + .containsExactly(source.canonicalBytes()); + } + + owner(context, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {1}); + owner(context, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {2}); + assertThat(tx(context, () -> context.repository().sourceMutationPermitted(change))).isTrue(); + } + + private void insertScope(Context context, String key) { + tx( + context, + () -> { + UUID change = UUID.randomUUID(); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change, + new byte[] {12}); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + key); + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", + change, + key); + return null; + }); + } + + private static SourceEvidence source(SourceKind kind, UUID account) { + // Stipulated capture is retained exactly; its counters/payload never establish authority. + return new SourceEvidence( + kind, account.toString(), "3", "5", "stream/" + account, "2", new byte[] {7}); + } + + private static String accountVersion(Context context, UUID account) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT xmin::TEXT AS version FROM accounts WHERE account_uuid = ?", account), + "Expected persisted Account tuple version") + .get("version", String.class); + } + + private static void awaitBlocked(Context context, int waitingPid, int blockerPid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + if (Boolean.TRUE.equals( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT ? = ANY(pg_blocking_pids(?)) AS blocked", blockerPid, waitingPid), + "Expected PostgreSQL blocking-state readback") + .get("blocked", Boolean.class))) { + return; + } + Thread.onSpinWait(); + } + throw new IllegalStateException("Source producer did not block on the first Account lock"); + } + + private Context context() { + return context("latest"); + } + + private Context context(String target) { + String schema = "draft_fence_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = new DriverManagerDataSource(); + source.setUrl(postgres.getJdbcUrl()); + source.setUsername(postgres.getUsername()); + source.setPassword(postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context(dsl, source, new DraftAuthorizationFenceRepository(dsl), transaction); + } + + private DraftAuthorizationFenceBinding withSources( + DraftAuthorizationFenceBinding binding, List sources) { + return new DraftAuthorizationFenceBinding( + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.actorAccountId(), + binding.tenantId(), + binding.versionId(), + binding.baseCommitId(), + binding.expectedDraftEpoch(), + binding.gameDesignBinding(), + binding.normalizedInput(), + binding.inputDigest(), + sources, + binding.schemaVersion(), + binding.requiredOwners()); + } + + private static SourceEvidence issuerSource(String scopeId) { + return new SourceEvidence(SourceKind.ISSUER, scopeId, null, "5", null, null, new byte[] {7}); + } + + private DraftAuthorizationFenceBinding binding(Context context) { + UUID account = + tx( + context, + () -> { + Account row = new Account(); + String suffix = UUID.randomUUID().toString(); + row.setUsername("draft-" + suffix); + row.setEmail(suffix + "@example.test"); + row.setPasswordHash("synthetic-verifier"); + return new AccountRepository(context.dsl()).save(row).getAccountUuid(); + }); + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + "3", + "5", + "stream/" + account, + "2", + new byte[] {7}); + DraftCommitBinding complete = + completeBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "opaque/base:9007199254740993", + "world-payload", + UUID.randomUUID()); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + account, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "2", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of(source)); + } + + private DraftAuthorizationFenceBinding multiOwnerBinding(Context context) { + var prior = binding(context); + var complete = + DraftCommitBinding.fromStored( + new String(prior.gameDesignBinding(), StandardCharsets.UTF_8), prior.inputDigest()); + var entity = DraftCommitBinding.Owner.ENTITY_MANAGEMENT; + var multi = + DraftCommitBinding.create( + complete.target(), + complete.requestId(), + complete.commitId(), + complete.baseCommitId(), + List.of( + complete.revisions().getFirst(), + new RevisionPayload("1", UUID.randomUUID(), entity, "entity-payload")), + List.of( + complete.affectedUnits().getFirst(), + new AffectedUnit(entity, "entity", "entity-1", "aggregate", "entity-1", "0"))); + return new DraftAuthorizationFenceBinding( + prior.operationId(), + prior.requestId(), + prior.commitId(), + prior.fenceId(), + prior.actorAccountId(), + prior.tenantId(), + prior.versionId(), + prior.baseCommitId(), + prior.expectedDraftEpoch(), + multi.canonicalBytes(), + multi.canonicalBytes(), + multi.digest(), + prior.sources()) + .withRequiredOwners(); + } + + private DraftAuthorizationFenceBinding changed(DraftAuthorizationFenceBinding b, int field) { + SourceEvidence prior = b.sources().getFirst(); + SourceEvidence changedSource = + new SourceEvidence( + prior.kind(), + prior.scopeId(), + "4", + prior.sourceVersion(), + prior.checkpointStream(), + prior.checkpointSequence(), + prior.evidence()); + DraftCommitBinding priorComplete = + DraftCommitBinding.fromStored( + new String(b.gameDesignBinding(), StandardCharsets.UTF_8), b.inputDigest()); + DraftCommitBinding complete = + completeBinding( + field == 1 ? UUID.randomUUID() : b.tenantId(), + field == 2 ? UUID.randomUUID() : b.versionId(), + b.requestId(), + b.commitId(), + b.baseCommitId(), + field == 4 ? "changed-world-payload" : priorComplete.revisions().getFirst().payload(), + field == 5 ? UUID.randomUUID() : priorComplete.revisions().getFirst().revisionId()); + return new DraftAuthorizationFenceBinding( + b.operationId(), + b.requestId(), + b.commitId(), + b.fenceId(), + field == 0 ? UUID.randomUUID() : b.actorAccountId(), + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + b.baseCommitId(), + b.expectedDraftEpoch(), + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + field == 3 ? List.of(changedSource) : b.sources()); + } + + private DraftCommitBinding completeBinding( + UUID tenant, + UUID version, + UUID request, + UUID commit, + String base, + String payload, + UUID revision) { + return DraftCommitBinding.create( + new TargetProof(tenant, version, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + base, + List.of( + new RevisionPayload("0", revision, DraftCommitBinding.Owner.WORLD_MANAGEMENT, payload)), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"))); + } + + private SourceChange change(DraftAuthorizationFenceBinding binding) { + return new SourceChange(UUID.randomUUID(), binding.sources(), new byte[] {12}); + } + + private void owner( + Context context, + DraftAuthorizationFenceBinding b, + Owner owner, + Outcome outcome, + byte[] bytes) { + OwnerReadback readback = ownerReadback(b, owner, outcome, bytes); + tx( + context, + () -> { + context.repository().recordOwnerReadback(b, readback); + return null; + }); + } + + private static OwnerReadback ownerReadback( + DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome, byte[] result) { + return new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + result); + } + + private static WorldDraftTerminalReadEvidence worldEvidence( + WorldDraftTerminalReadEvidence.Request request, OwnerReadback readback) { + if (readback.outcome() != Outcome.COMMITTED) { + return new WorldDraftTerminalReadEvidence(request, Optional.of(readback)); + } + WorldDraftTerminalReadEvidence response = mock(WorldDraftTerminalReadEvidence.class); + when(response.request()).thenReturn(request); + when(response.ownerReadback()).thenReturn(Optional.of(readback)); + return response; + } + + private static void assertOutsideOwnerTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static ReconciliationAttempt reconcileAttempt( + AccountDraftTerminalReconciliationService service, UUID operationId) { + try { + return new ReconciliationAttempt(service.reconcile(operationId).orElseThrow(), null); + } catch (RuntimeException failure) { + return new ReconciliationAttempt(null, failure); + } + } + + private static T tx(Context context, Supplier work) { + return context.transaction().execute(status -> work.get()); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Ordering fixture timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + + private record Context( + DSLContext dsl, + DriverManagerDataSource dataSource, + DraftAuthorizationFenceRepository repository, + TransactionTemplate transaction) {} + + private record ReconciliationAttempt(Settlement settlement, RuntimeException failure) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java new file mode 100644 index 0000000000..0c73f6f2ba --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -0,0 +1,2638 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DelegatingDataSource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Real PostgreSQL definitions for non-admitting storage only. Carriers are fabricated shape + * fixtures, never authenticated source snapshots or evidence that a binding may be admitted. + */ +class AccountGameplayAdmissionLeasePersistenceIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(true); + private static final String TENANT = "22222222-2222-4222-8222-222222222222"; + private static final String OTHER = "33333333-3333-4333-8333-333333333333"; + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @Test + void fixtureUsesDurablePrimarySettingsRequiredByCommitConfirmation() { + var settings = POSTGRES.verifyDurablePrimary(); + assertThat(settings.inRecovery()).isFalse(); + assertThat(settings.fsync()).isEqualTo("on"); + assertThat(settings.synchronousCommit()).isEqualTo("on"); + } + + @Test + void originalExecutorAcknowledgesActualCommitWithoutCreatingTemporalReceipt() { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var before = operation(context, original); + // Upstream carrier and authority fields are component-only fixtures, never admission proof. + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision); + var committed = operation(context, original); + assertThat(acknowledgement.evidence().canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(acknowledgement.evidence().sha256()).isEqualTo(original.sha256()); + assertThat(acknowledgement.decisionId()).isEqualTo(decision); + assertThat(acknowledgement.finalizationXid()) + .isEqualTo(committed.get("finalization_xid", String.class)); + assertThat(acknowledgement.committedBeforeMs()).isPositive().isLessThan(expiresAt(original)); + assertThat(committed.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(committed.get("binding_decision_id", UUID.class)).isEqualTo(decision); + for (String field : + List.of( + "request_id", + "account_uuid", + "lease_id", + "lease_fence", + "evidence_json", + "evidence_sha256", + "evaluated_at_ms", + "expires_at_ms")) { + assertThat(committed.get(field)).as(field).isEqualTo(before.get(field)); + } + assertThat(committed.get("expires_at_ms", Long.class)).isEqualTo(expiresAt(original)); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + // The in-process ACK and bound are not a persisted temporal confirmation or durable receipt. + } + + @Test + void originalExecutorReadsClockOnOriginalConnectionOnlyAfterActualCommitAcknowledgement() { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var clockQueries = new AtomicInteger(); + // Component-only upstream evidence. The wrapper delegates the actual commit and clock query. + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor( + postCommitClockDataSource(context.dataSource(), 0L, false, clockQueries)) + .execute(original, decision); + assertThat(clockQueries.get()).isEqualTo(1); + assertThat(acknowledgement.committedBeforeMs()).isPositive().isLessThan(expiresAt(original)); + assertThat(databaseNow(context)).isGreaterThanOrEqualTo(acknowledgement.committedBeforeMs()); + var committed = operation(context, original); + assertThat(committed.get("finalization_xid", String.class)) + .isEqualTo(acknowledgement.finalizationXid()); + assertThat(committed.get("binding_decision_id", UUID.class)).isEqualTo(decision); + assertThat(committed.get("evidence_json", String.class)).isEqualTo(original.canonicalJson()); + assertThat(committed.get("evidence_sha256", String.class)).isEqualTo(original.sha256()); + assertThat(committed.get("expires_at_ms", Long.class)).isEqualTo(expiresAt(original)); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + } + + @Test + void delayedPostAcknowledgementClockDeniesWithoutUndoingOriginalCommitOrRenewingExpiry() { + var context = context(null); + var original = pending(context, account(context), 1000L); + UUID decision = UUID.randomUUID(); + var clockQueries = new AtomicInteger(); + var executor = + new AccountGameplayAdmissionOriginalCommitExecutor( + postCommitClockDataSource( + context.dataSource(), expiresAt(original), false, clockQueries)); + assertThatThrownBy(() -> executor.execute(original, decision)) + .hasMessageContaining("post-COMMIT clock bound unavailable"); + assertThat(clockQueries.get()).isEqualTo(1); + assertThat(databaseNow(context)).isGreaterThanOrEqualTo(expiresAt(original)); + var committed = operation(context, original); + assertThat(committed.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(committed.get("binding_decision_id", UUID.class)).isEqualTo(decision); + assertThat(committed.get("finalization_xid", String.class)).isNotBlank(); + assertThat(committed.get("evidence_json", String.class)).isEqualTo(original.canonicalJson()); + assertThat(committed.get("expires_at_ms", Long.class)).isEqualTo(expiresAt(original)); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(operation(context, original)).isEqualTo(committed); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + } + + @Test + void lostPostAcknowledgementClockResponseCannotBeRemintedFromCommittedRetry() { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var clockQueries = new AtomicInteger(); + var executor = + new AccountGameplayAdmissionOriginalCommitExecutor( + postCommitClockDataSource(context.dataSource(), 0L, true, clockQueries)); + assertThatThrownBy(() -> executor.execute(original, decision)) + .hasMessageContaining("post-COMMIT clock unavailable"); + assertThat(clockQueries.get()).isEqualTo(1); + var committed = operation(context, original); + assertThat(committed.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(committed.get("binding_decision_id", UUID.class)).isEqualTo(decision); + assertThat(committed.get("finalization_xid", String.class)).isNotBlank(); + assertThat(committed.get("evidence_json", String.class)).isEqualTo(original.canonicalJson()); + assertThat(committed.get("expires_at_ms", Long.class)).isEqualTo(expiresAt(original)); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(operation(context, original)).isEqualTo(committed); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + } + + /** Real database clock faults on the original connection, strictly after successful COMMIT. */ + private static DataSource postCommitClockDataSource( + DataSource source, long waitUntilMs, boolean loseClockResponse, AtomicInteger clockQueries) { + return new DelegatingDataSource(source) { + @Override + public Connection getConnection() throws SQLException { + return clockConnection(super.getConnection()); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return clockConnection(super.getConnection(username, password)); + } + + private Connection clockConnection(Connection physical) { + var committed = new AtomicBoolean(); + return (Connection) + Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("commit") && method.getParameterCount() == 0) { + physical.commit(); + committed.set(true); + return null; + } + if (method.getName().equals("createStatement") && method.getParameterCount() == 0) + return clockStatement(physical.createStatement(), committed); + try { + return method.invoke(physical, arguments); + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } + + private Statement clockStatement(Statement physical, AtomicBoolean committed) { + return (Statement) + Proxy.newProxyInstance( + Statement.class.getClassLoader(), + new Class[] {Statement.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("executeQuery") + && arguments != null + && arguments.length == 1 + && "SELECT ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint" + .equals(arguments[0])) { + assertThat(committed.get()).isTrue(); + clockQueries.incrementAndGet(); + if (waitUntilMs > 0) { + // Delay only this test's post-ACK clock query using database time. + physical.execute( + "SELECT pg_sleep(GREATEST(0, (" + + waitUntilMs + + " - ceil(extract(epoch FROM clock_timestamp()) * 1000) + 50) / 1000.0))"); + } + if (loseClockResponse) { + try (ResultSet discarded = physical.executeQuery((String) arguments[0])) { + assertThat(discarded.next()).isTrue(); + } + throw new SQLException("Test lost post-COMMIT clock response", "08006"); + } + } + try { + return method.invoke(physical, arguments); + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } + }; + } + + @Test + void originalExecutorRejectsCommittedRetryWithoutRefreshingEvidence() { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var executor = new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()); + var acknowledgement = executor.execute(original, decision); + var committed = operation(context, original); + assertThatThrownBy(() -> executor.execute(original, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(operation(context, original)).isEqualTo(committed); + assertThat(operation(context, original).get("finalization_xid", String.class)) + .isEqualTo(acknowledgement.finalizationXid()); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + } + + @Test + void lostOriginalCommitAcknowledgementDeniesDespiteActualCommittedReadback() { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var physicalCommits = new AtomicInteger(); + var executor = + new AccountGameplayAdmissionOriginalCommitExecutor( + originalCommitFailureDataSource(context.dataSource(), true, physicalCommits)); + assertThatThrownBy(() -> executor.execute(original, decision)) + .hasMessageContaining("Original Account physical COMMIT unavailable"); + assertThat(physicalCommits.get()).isEqualTo(1); + var committed = operation(context, original); + assertThat(committed.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(committed.get("binding_decision_id", UUID.class)).isEqualTo(decision); + assertThat(committed.get("finalization_xid", String.class)).isNotBlank(); + assertThat(committed.get("evidence_json", String.class)).isEqualTo(original.canonicalJson()); + assertThat(committed.get("evidence_sha256", String.class)).isEqualTo(original.sha256()); + assertThat(committed.get("expires_at_ms", Long.class)).isEqualTo(expiresAt(original)); + // Retry on a normal physical connection cannot turn raw visibility into the missing ACK. + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(operation(context, original)).isEqualTo(committed); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + } + + @Test + void rejectionBeforeOriginalPhysicalCommitRollsBackPendingWithoutAcknowledgement() { + var context = context(null); + var original = pending(context, account(context)); + var unchanged = storageSnapshot(context); + var physicalCommits = new AtomicInteger(); + var executor = + new AccountGameplayAdmissionOriginalCommitExecutor( + originalCommitFailureDataSource(context.dataSource(), false, physicalCommits)); + assertThatThrownBy(() -> executor.execute(original, UUID.randomUUID())) + .hasMessageContaining("Original Account physical COMMIT unavailable"); + assertThat(physicalCommits.get()).isZero(); + assertThat(operation(context, original).get("status", String.class)).isEqualTo("PENDING"); + assertThat(operation(context, original).get("finalization_xid", String.class)).isNull(); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + } + + /** Test-only transport fault around real JDBC COMMIT, with no production success injection. */ + private static DataSource originalCommitFailureDataSource( + DataSource source, boolean afterPhysicalCommit, AtomicInteger physicalCommits) { + return new DelegatingDataSource(source) { + @Override + public Connection getConnection() throws SQLException { + return faultConnection(super.getConnection()); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return faultConnection(super.getConnection(username, password)); + } + + private Connection faultConnection(Connection physical) { + return (Connection) + Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("commit") && method.getParameterCount() == 0) { + if (!afterPhysicalCommit) + throw new SQLException("Test rejection before physical COMMIT", "08006"); + physical.commit(); + physicalCommits.incrementAndGet(); + throw new SQLException("Test lost original COMMIT acknowledgement", "08006"); + } + try { + return method.invoke(physical, arguments); + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } + }; + } + + @Test + void actualAbortOwnerRecoversLostResponseAndRetainsOriginalDecisionAndCleanup() throws Exception { + var context = context(null); + var original = pending(context, account(context)); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var transactionManager = new DataSourceTransactionManager(context.dataSource()); + var owner = new AccountGameplayAdmissionAbortOwner(repository, transactionManager, "test"); + var readOwner = new AccountGameplayAdmissionReadOwner(repository, transactionManager, "test"); + UUID decision = UUID.randomUUID(); + var request = + AbortGameplayAdmissionLeaseRequest.newBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(original)) + .setBindingDecisionId(decision.toString()) + .build(); + // The trusted context is synthetic: this exercises real SQL ownership, never actual mTLS. + syntheticAbortPeer().call(() -> owner.abort(request)); // Discard the first response. + var stored = tx(context, () -> repository.readExact(original).orElseThrow()); + var recoveredAfterLostAbortAck = + syntheticReadPeer().call(() -> readOwner.read(readRequest(original))); + assertThat(recoveredAfterLostAbortAck).isEqualTo(stored); + assertThat(recoveredAfterLostAbortAck.state()).isEqualTo(State.ABORTED); + assertThat(recoveredAfterLostAbortAck.evidence().canonicalJson()) + .isEqualTo(original.canonicalJson()); + assertThat(recoveredAfterLostAbortAck.evidence().sha256()).isEqualTo(original.sha256()); + assertThat(recoveredAfterLostAbortAck.orphanCleanupId()).isEqualTo(stored.orphanCleanupId()); + assertThat(recoveredAfterLostAbortAck.hasPendingOrphanCleanup()).isTrue(); + var replay = syntheticAbortPeer().call(() -> owner.abort(request)); + assertThat(replay).isEqualTo(stored); + assertThat(replay.state()).isEqualTo(State.ABORTED); + assertThat(replay.bindingDecisionId()).isEqualTo(decision); + assertThat(replay.orphanCleanupId()).isNotNull(); + assertThat(replay.evidence().canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(replay.evidence().sha256()).isEqualTo(original.sha256()); + assertThat(AccountGameplayAdmissionLeaseWireCodec.encodeReference(replay.evidence())) + .isEqualTo(request.getLease()); + for (var changed : + List.of( + request.toBuilder().clearBindingDecisionId().build(), + request.toBuilder().setBindingDecisionId(UUID.randomUUID().toString()).build())) { + assertThatThrownBy(() -> syntheticAbortPeer().call(() -> owner.abort(changed))) + .isInstanceOf(AccountGameplayAdmissionAbortOwner.AbortDeniedException.class) + .satisfies( + failure -> + assertThat( + ((AccountGameplayAdmissionAbortOwner.AbortDeniedException) failure) + .code()) + .isEqualTo("IDEMPOTENCY_CONFLICT")); + assertThat(tx(context, () -> repository.readExact(original))).contains(stored); + } + } + + @Test + void concurrentActualAbortOwnersRetainOneCleanupAndDenySubstitutionOrCommittedLease() + throws Exception { + var context = context(null); + UUID account = account(context); + var original = pending(context, account); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var owner = + new AccountGameplayAdmissionAbortOwner( + repository, new DataSourceTransactionManager(context.dataSource()), "test"); + var request = + AbortGameplayAdmissionLeaseRequest.newBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(original)) + .build(); + var start = new CountDownLatch(1); + Callable abort = + () -> { + if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); + try { + // DriverManagerDataSource supplies each thread's owned transaction its own SQL + // connection. + return syntheticAbortPeer().call(() -> owner.abort(request)); + } catch (RuntimeException failure) { + Throwable cause = failure; + while (cause != null) { + if (cause instanceof java.sql.SQLException sql && "40001".equals(sql.getSQLState())) + return null; + cause = cause.getCause(); + } + throw failure; + } + }; + AccountGameplayAdmissionLeaseOperation left; + AccountGameplayAdmissionLeaseOperation right; + try (var executor = Executors.newFixedThreadPool(2)) { + var first = executor.submit(abort); + var second = executor.submit(abort); + start.countDown(); + left = first.get(30, TimeUnit.SECONDS); + right = second.get(30, TimeUnit.SECONDS); + } + assertThat(left != null || right != null).isTrue(); + var replay = syntheticAbortPeer().call(() -> owner.abort(request)); + if (left != null) assertThat(left).isEqualTo(replay); + if (right != null) assertThat(right).isEqualTo(replay); + assertThat(replay.state()).isEqualTo(State.ABORTED); + assertThat(replay.bindingDecisionId()).isNull(); + assertThat(replay.orphanCleanupId()).isNotNull(); + assertThat(tx(context, () -> repository.readExact(original))).contains(replay); + assertThat(context.dsl().fetchCount(DSL.table("account_gameplay_admission_lease_operations"))) + .isEqualTo(1); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT count(DISTINCT orphan_cleanup_id) AS cleanups FROM account_gameplay_admission_lease_operations")) + .get("cleanups", Long.class)) + .isEqualTo(1L); + var changedCarrier = new LinkedHashMap<>(original.carrier()); + changedCarrier.put("leaseId", UUID.randomUUID().toString()); + var changed = + request.toBuilder() + .setLease( + AccountGameplayAdmissionLeaseWireCodec.encodeReference( + AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier))) + .build(); + assertThatThrownBy(() -> syntheticAbortPeer().call(() -> owner.abort(changed))) + .isInstanceOf(AccountGameplayAdmissionAbortOwner.AbortDeniedException.class); + var mismatchedRequest = + request.toBuilder() + .setLease(request.getLease().toBuilder().setRequestId(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy(() -> syntheticAbortPeer().call(() -> owner.abort(mismatchedRequest))) + .isInstanceOf(IllegalArgumentException.class); + var changedDecision = + request.toBuilder().setBindingDecisionId(UUID.randomUUID().toString()).build(); + assertThatThrownBy(() -> syntheticAbortPeer().call(() -> owner.abort(changedDecision))) + .isInstanceOf(AccountGameplayAdmissionAbortOwner.AbortDeniedException.class); + assertThat(tx(context, () -> repository.readExact(original))).contains(replay); + + var committedEvidence = pending(context, account); + var committed = + tx(context, () -> repository.recordCommitted(committedEvidence, UUID.randomUUID())); + var committedRequest = + request.toBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(committedEvidence)) + .build(); + assertThatThrownBy(() -> syntheticAbortPeer().call(() -> owner.abort(committedRequest))) + .isInstanceOf(AccountGameplayAdmissionAbortOwner.AbortDeniedException.class) + .satisfies( + failure -> + assertThat( + ((AccountGameplayAdmissionAbortOwner.AbortDeniedException) failure).code()) + .isEqualTo("ADMISSION_LEASE_NOT_ABORTABLE")); + assertThat(tx(context, () -> repository.readExact(committedEvidence))).contains(committed); + assertThat(committed.orphanCleanupId()).isNull(); + } + + @Test + void exactReadRejectsMissingRawCommittedAndMismatchedOperations() { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var readOwner = + new AccountGameplayAdmissionReadOwner( + repository, new DataSourceTransactionManager(context.dataSource()), "test"); + + var allocation = + tx(context, () -> repository.allocate(account, UUID.randomUUID(), UUID.randomUUID())); + var missing = evidence(allocation); + assertFailedExactRead(readOwner, missing); + assertThat(tx(context, () -> repository.readExact(missing))).isEmpty(); + + var original = pending(context, account); + var changedCarrier = new LinkedHashMap<>(original.carrier()); + changedCarrier.put( + "leaseFence", Long.toString(Long.parseLong((String) changedCarrier.get("leaseFence")) + 1)); + assertFailedExactRead( + readOwner, AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier)); + assertThat(tx(context, () -> repository.readExact(original).orElseThrow().state())) + .isEqualTo(State.PENDING); + + var committedEvidence = pending(context, account); + var committed = + tx(context, () -> repository.recordCommitted(committedEvidence, UUID.randomUUID())); + assertThat(committed.state()).isEqualTo(State.COMMITTED); + assertFailedExactRead(readOwner, committedEvidence); + assertThat(tx(context, () -> repository.readExact(committedEvidence))).contains(committed); + } + + /** Synthetic trusted caller only; the existing carriers remain fabricated storage fixtures. */ + private static io.grpc.Context syntheticAbortPeer() { + return io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow()); + } + + /** Synthetic peer only; neither this identity nor the fabricated carrier proves mTLS. */ + private static io.grpc.Context syntheticReadPeer() { + return io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow()); + } + + private static ReadGameplayAdmissionLeaseRequest readRequest( + AccountGameplayAdmissionLeaseEvidence evidence) { + return ReadGameplayAdmissionLeaseRequest.newBuilder() + .setRequestId((String) evidence.carrier().get("requestId")) + .setExpectedLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence)) + .build(); + } + + private static void assertFailedExactRead( + AccountGameplayAdmissionReadOwner owner, AccountGameplayAdmissionLeaseEvidence evidence) { + assertThatThrownBy(() -> syntheticReadPeer().call(() -> owner.read(readRequest(evidence)))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + + @Test + void lostResponseRecoveryUsesOriginalRequestWithoutReconstructingServerLeaseIdentity() { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + var allocation = tx(context, () -> repository.allocate(account, request, lease)); + assertThat(tx(context, () -> repository.findAllocation(account, request))).contains(allocation); + assertThat( + tx( + context, + () -> + repository.findByRequest( + account, request, "spiffe://firemud/ns/test/sa/game-session-service"))) + .isEmpty(); + var original = evidence(allocation); + var pending = tx(context, () -> repository.beginPending(original)); + assertThat( + tx( + context, + () -> + repository.findByRequest( + account, request, "spiffe://firemud/ns/test/sa/game-session-service"))) + .contains(pending); + UUID decision = UUID.randomUUID(); + var committed = tx(context, () -> repository.recordCommitted(original, decision)); + assertThat( + tx( + context, + () -> + repository.findByRequest( + account, request, "spiffe://firemud/ns/test/sa/game-session-service"))) + .contains(committed); + assertThat(tx(context, () -> repository.findAllocation(account, request))).contains(allocation); + UUID wrongAccount = account(context); + assertThatThrownBy(() -> tx(context, () -> repository.findAllocation(wrongAccount, request))) + .hasMessageContaining("identity conflict"); + assertThatThrownBy( + () -> + tx( + context, + () -> + repository.findByRequest( + wrongAccount, + request, + "spiffe://firemud/ns/test/sa/game-session-service"))) + .hasMessageContaining("identity conflict"); + assertThatThrownBy( + () -> + tx( + context, + () -> + repository.findByRequest( + account, request, "spiffe://firemud/ns/other/sa/game-session-service"))) + .hasMessageContaining("identity conflict"); + UUID missingRequest = UUID.randomUUID(); + assertThat(tx(context, () -> repository.findAllocation(account, missingRequest))).isEmpty(); + assertThat( + tx( + context, + () -> + repository.findByRequest( + account, + missingRequest, + "spiffe://firemud/ns/test/sa/game-session-service"))) + .isEmpty(); + assertThat(context.dsl().fetchCount(DSL.table("account_gameplay_admission_lease_allocations"))) + .isEqualTo(1); + } + + @Test + void freshMigrationStoresExactReplayAndRejectsChangedBaselineDigestOrAllocation() { + var context = context(null); + UUID account = account(context); + var evidence = pending(context, account); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + assertThat(tx(context, () -> repository.beginPending(evidence)).evidence()).isEqualTo(evidence); + var changed = new LinkedHashMap<>(evidence.carrier()); + changed.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "INACTIVE", + "membershipVersion", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + "1")); + var changedEvidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); + assertThatThrownBy(() -> tx(context, () -> repository.beginPending(changedEvidence))) + .hasMessageContaining("identity conflict"); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET evidence_sha256 = ? WHERE request_id = ?", + "b".repeat(64), + UUID.fromString((String) evidence.carrier().get("requestId"))))) + .isInstanceOf(RuntimeException.class); + changed.put("requestId", UUID.randomUUID().toString()); + changed.put("leaseId", UUID.randomUUID().toString()); + var unallocated = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); + assertThatThrownBy(() -> tx(context, () -> repository.beginPending(unallocated))) + .hasMessageContaining("identity conflict"); + var otherAllocation = + tx(context, () -> repository.allocate(account, UUID.randomUUID(), UUID.randomUUID())); + var substituted = new LinkedHashMap<>(evidence.carrier()); + substituted.put("leaseFence", Long.toString(otherAllocation.leaseFence())); + var substitutedEvidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(substituted); + assertThatThrownBy(() -> tx(context, () -> repository.beginPending(substitutedEvidence))) + .hasMessageContaining("identity conflict"); + var original = evidence(otherAllocation); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_gameplay_admission_lease_operations " + + "(account_uuid, request_id, lease_id, lease_fence, caller_workload, evidence_json, " + + "evidence_sha256, evaluated_at_ms, expires_at_ms, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING')", + account, + otherAllocation.requestId(), + otherAllocation.leaseId(), + otherAllocation.leaseFence(), + original.carrier().get("callerWorkload"), + original.canonicalJson(), + "b".repeat(64), + Long.parseLong((String) original.carrier().get("evaluatedAt")), + Long.parseLong((String) original.carrier().get("expiresAt"))))) + .isInstanceOf(RuntimeException.class); + } + + @Test + void retainedAccountMigrationPreservesAccountAndAddsIndependentFenceDomain() { + var context = context("84.4"); + UUID account = + tx( + context, + () -> + PreRestrictionBirthAccountFixture.create( + context.dsl(), + "lease-" + UUID.randomUUID(), + UUID.randomUUID() + "@example.test", + "storage-fixture-only", + "PASSWORD") + .getAccountUuid()); + migrate(context, null); + var first = pending(context, account); + var second = pending(context, account); + assertThat(first.leaseFence().longValueExact()).isEqualTo(1); + assertThat(second.leaseFence().longValueExact()).isEqualTo(2); + assertThat(context.dsl().fetchCount(DSL.table("accounts"))).isEqualTo(1); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_fences SET last_fence = 1 WHERE account_uuid = ?", + account))) + .isInstanceOf(RuntimeException.class); + for (String table : + List.of( + "account_gameplay_admission_lease_fences", + "account_gameplay_admission_lease_allocations", + "account_gameplay_admission_lease_operations")) { + assertThatThrownBy(() -> tx(context, () -> context.dsl().execute("DELETE FROM " + table))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> tx(context, () -> context.dsl().execute("TRUNCATE " + table))) + .isInstanceOf(RuntimeException.class); + } + } + + @Test + void commitsExactDecisionAndAtomicallyRetainsAbortedOrphanIntentWithTerminalConflict() { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var committed = pending(context, account); + UUID decision = UUID.randomUUID(); + var result = tx(context, () -> repository.recordCommitted(committed, decision)); + assertThat(result.state()).isEqualTo(State.COMMITTED); + assertThat(tx(context, () -> repository.recordCommitted(committed, decision))) + .isEqualTo(result); + assertThatThrownBy( + () -> tx(context, () -> repository.recordCommitted(committed, UUID.randomUUID()))) + .hasMessageContaining("identity conflict"); + assertThatThrownBy( + () -> + tx(context, () -> repository.recordAborted(committed, decision, UUID.randomUUID()))) + .hasMessageContaining("identity conflict"); + var aborted = pending(context, account); + UUID cleanup = UUID.randomUUID(); + assertThatThrownBy( + () -> + tx( + context, + () -> { + repository.recordAborted(aborted, decision, cleanup); + throw new IllegalStateException("simulate transaction rollback"); + })) + .hasMessageContaining("rollback"); + assertThat(tx(context, () -> repository.readExact(aborted).orElseThrow()).state()) + .isEqualTo(State.PENDING); + var orphan = tx(context, () -> repository.recordAborted(aborted, decision, cleanup)); + assertThat(orphan.hasPendingOrphanCleanup()).isTrue(); + assertThat(orphan.evidence()).isEqualTo(aborted); + assertThat(orphan.orphanCleanupId()).isEqualTo(cleanup); + assertThat(tx(context, () -> repository.recordAborted(aborted, decision, cleanup))) + .isEqualTo(orphan); + assertThatThrownBy( + () -> tx(context, () -> repository.recordAborted(aborted, decision, UUID.randomUUID()))) + .hasMessageContaining("identity conflict"); + } + + @Test + void forwardMigrationPreservesRetainedReceiptsAndAllowsUnknownDecisionAbort() { + var context = context("88"); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var retainedPending = pending(context, account); + var retainedKnown = pending(context, account); + UUID decision = UUID.randomUUID(); + UUID knownCleanup = UUID.randomUUID(); + var known = tx(context, () -> repository.recordAborted(retainedKnown, decision, knownCleanup)); + var retainedCommitted = pending(context, account); + var committed = tx(context, () -> repository.recordCommitted(retainedCommitted, decision)); + + migrate(context, null); + + assertThat(tx(context, () -> repository.readExact(retainedKnown))).contains(known); + assertThat(tx(context, () -> repository.readExact(retainedCommitted))).contains(committed); + UUID cleanup = UUID.randomUUID(); + var unknown = tx(context, () -> repository.recordAborted(retainedPending, null, cleanup)); + assertThat(unknown.state()).isEqualTo(State.ABORTED); + assertThat(unknown.bindingDecisionId()).isNull(); + assertThat(unknown.orphanCleanupId()).isEqualTo(cleanup); + assertThat(unknown.hasPendingOrphanCleanup()).isTrue(); + assertThat(unknown.evidence()).isEqualTo(retainedPending); + assertThat(tx(context, () -> repository.recordAborted(retainedPending, null, cleanup))) + .isEqualTo(unknown); + assertThat(tx(context, () -> repository.readExact(retainedPending))).contains(unknown); + assertThatThrownBy( + () -> + tx( + context, + () -> repository.recordAborted(retainedPending, UUID.randomUUID(), cleanup))) + .hasMessageContaining("identity conflict"); + assertThatThrownBy( + () -> + tx( + context, + () -> repository.recordAborted(retainedPending, null, UUID.randomUUID()))) + .hasMessageContaining("identity conflict"); + // The unchanged V87 trigger prevents a direct rewrite of the unknown terminal observation. + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET binding_decision_id = ? WHERE request_id = ?", + UUID.randomUUID(), + UUID.fromString( + (String) retainedPending.carrier().get("requestId"))))) + .isInstanceOf(RuntimeException.class); + } + + @Test + void relaxedAbortShapeStillRejectsMissingCleanupAndCommittedWithoutDecision() { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var original = pending(context, account); + UUID request = UUID.fromString((String) original.carrier().get("requestId")); + assertThatThrownBy(() -> tx(context, () -> repository.recordAborted(original, null, null))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> tx(context, () -> repository.recordCommitted(original, null))) + .isInstanceOf(IllegalArgumentException.class); + for (String state : List.of("ABORTED", "COMMITTED")) { + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET status = ? WHERE request_id = ?", + state, + request))) + .isInstanceOf(RuntimeException.class); + } + assertThat(tx(context, () -> repository.readExact(original).orElseThrow()).state()) + .isEqualTo(State.PENDING); + } + + @Test + void expiredPendingCannotCommitOrRenewButKeepsExactReadbackAndCanAbort() throws Exception { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var evidence = pending(context, account); + tx(context, () -> context.dsl().fetchOne("SELECT pg_sleep(16)")); + assertThat(tx(context, () -> repository.beginPending(evidence)).evidence()).isEqualTo(evidence); + var readOwner = + new AccountGameplayAdmissionReadOwner( + repository, new DataSourceTransactionManager(context.dataSource()), "test"); + var expiredRead = syntheticReadPeer().call(() -> readOwner.read(readRequest(evidence))); + assertThat(expiredRead.state()).isEqualTo(State.PENDING); + assertThat(expiredRead.evidence().canonicalJson()).isEqualTo(evidence.canonicalJson()); + assertThat(expiredRead.evidence().sha256()).isEqualTo(evidence.sha256()); + assertThat(expiredRead.bindingDecisionId()).isNull(); + assertThat(expiredRead.orphanCleanupId()).isNull(); + assertThatThrownBy( + () -> tx(context, () -> repository.recordCommitted(evidence, UUID.randomUUID()))) + .hasMessageContaining("deadline expired"); + var changed = new LinkedHashMap<>(evidence.carrier()); + long now = Instant.now().toEpochMilli(); + changed.put("evaluatedAt", Long.toString(now)); + changed.put("expiresAt", Long.toString(now + 15000)); + var renewed = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); + assertThatThrownBy(() -> tx(context, () -> repository.beginPending(renewed))) + .hasMessageContaining("identity conflict"); + var aborted = tx(context, () -> repository.recordAborted(evidence, null, UUID.randomUUID())); + assertThat(aborted.state()).isEqualTo(State.ABORTED); + var expiredAbortRead = syntheticReadPeer().call(() -> readOwner.read(readRequest(evidence))); + assertThat(expiredAbortRead).isEqualTo(aborted); + assertThat(expiredAbortRead.evidence().canonicalJson()).isEqualTo(evidence.canonicalJson()); + assertThat(expiredAbortRead.evidence().sha256()).isEqualTo(evidence.sha256()); + assertThat(expiredAbortRead.bindingDecisionId()).isNull(); + assertThat(expiredAbortRead.orphanCleanupId()).isEqualTo(aborted.orphanCleanupId()); + assertThat(expiredAbortRead.hasPendingOrphanCleanup()).isTrue(); + } + + @Test + void concurrentDuplicatesReplayOneAllocationAndDistinctRequestsAdvanceFence() throws Exception { + var context = context(null); + UUID account = account(context); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var start = new CountDownLatch(1); + Callable duplicate = + () -> { + if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); + return retrySerialization( + () -> tx(context, () -> repository.allocate(account, request, lease))); + }; + try (var executor = Executors.newFixedThreadPool(2)) { + var left = executor.submit(duplicate); + var right = executor.submit(duplicate); + start.countDown(); + assertThat(left.get(30, TimeUnit.SECONDS)).isEqualTo(right.get(30, TimeUnit.SECONDS)); + var a = + executor.submit( + () -> + retrySerialization( + () -> + tx( + context, + () -> + repository.allocate( + account, UUID.randomUUID(), UUID.randomUUID())))); + var b = + executor.submit( + () -> + retrySerialization( + () -> + tx( + context, + () -> + repository.allocate( + account, UUID.randomUUID(), UUID.randomUUID())))); + assertThat( + List.of( + a.get(30, TimeUnit.SECONDS).leaseFence(), + b.get(30, TimeUnit.SECONDS).leaseFence())) + .containsExactlyInAnyOrder(2L, 3L); + } + } + + @Test + void durableConfirmationStoresOriginalCommitProofAndRecoversLostResponseAfterExpiry() + throws Exception { + var context = context(null); + UUID account = account(context); + var original = pending(context, account); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(original, decision)); + var unchanged = storageSnapshot(context); + var transactionManager = new DataSourceTransactionManager(context.dataSource()); + var confirmationOwner = + new AccountGameplayAdmissionCommitConfirmationOwner(context.dataSource(), "test"); + var request = + FinalizeGameplayAdmissionLeaseRequest.newBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(original)) + .setBindingDecisionId(decision.toString()) + .build(); + + // The loopback peer, carrier and decision are synthetic upstream fixtures. The real Java + // owner creates and independently reads Account SQL proof; this does not prove mTLS. + syntheticReadPeer().call(() -> confirmationOwner.confirm(request)); // Discard the response. + // Inspect stored fields separately; this visible row alone is not durable readback proof. + var receipt = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_commit_confirmations WHERE request_id = ?", + requestId(original))); + assertThat(receipt.get("confirmation_version", Short.class)).isEqualTo((short) 1); + assertThat(receipt.get("request_id", UUID.class)).isEqualTo(requestId(original)); + assertThat(receipt.get("account_uuid", UUID.class)).isEqualTo(account); + assertThat(receipt.get("lease_id", UUID.class)) + .isEqualTo(UUID.fromString((String) original.carrier().get("leaseId"))); + assertThat(receipt.get("lease_fence", Long.class)) + .isEqualTo(original.leaseFence().longValueExact()); + assertThat(receipt.get("evidence_sha256", String.class)).isEqualTo(original.sha256()); + assertThat(receipt.get("binding_decision_id", UUID.class)).isEqualTo(decision); + assertThat(receipt.get("expires_at_ms", Long.class)).isEqualTo(expiresAt(original)); + assertThat(receipt.get("committed_before_ms", Long.class)) + .isPositive() + .isLessThan(expiresAt(original)); + assertThat(receipt.get("finalization_xid", String.class)) + .isEqualTo(operation(context, original).get("finalization_xid", String.class)); + assertThat(receipt.get("confirmation_xid", String.class)) + .isNotEqualTo(receipt.get("finalization_xid", String.class)); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT ?::pg_lsn >= ?::pg_lsn AS covered", + receipt.get("wal_flush_lsn", String.class), + receipt.get("wal_insert_lsn", String.class))) + .get("covered", Boolean.class)) + .isTrue(); + // Recovery opens the real owner's fresh transaction and covers the independently committed + // receipt's WAL before returning the immutable DTO, without reconstructing any proof fields. + var recovered = syntheticReadPeer().call(() -> confirmationOwner.read(request)); + assertThat(recovered.operation().state()).isEqualTo(State.COMMITTED); + assertThat(recovered.operation().evidence().canonicalJson()) + .isEqualTo(original.canonicalJson()); + assertThat(recovered.operation().evidence().sha256()).isEqualTo(original.sha256()); + assertThat(recovered.operation().bindingDecisionId()).isEqualTo(decision); + assertThat(recovered.requestId()).isEqualTo(receipt.get("request_id", UUID.class)); + assertThat(recovered.accountId()).isEqualTo(receipt.get("account_uuid", UUID.class)); + assertThat(recovered.leaseId()).isEqualTo(receipt.get("lease_id", UUID.class)); + assertThat(recovered.leaseFence()).isEqualTo(receipt.get("lease_fence", Long.class)); + assertThat(recovered.confirmationVersion()) + .isEqualTo(receipt.get("confirmation_version", Short.class)); + assertThat(recovered.evidenceSha256()).isEqualTo(receipt.get("evidence_sha256", String.class)); + assertThat(recovered.bindingDecisionId()) + .isEqualTo(receipt.get("binding_decision_id", UUID.class)); + assertThat(recovered.expiresAtMs()).isEqualTo(receipt.get("expires_at_ms", Long.class)); + assertThat(recovered.committedBeforeMs()) + .isEqualTo(receipt.get("committed_before_ms", Long.class)); + assertThat(recovered.finalizationXid()) + .isEqualTo(receipt.get("finalization_xid", String.class)); + assertThat(recovered.confirmationXid()) + .isEqualTo(receipt.get("confirmation_xid", String.class)); + assertThat(recovered.walInsertLsn()).isEqualTo(receipt.get("wal_insert_lsn", String.class)); + assertThat(recovered.walFlushLsn()).isEqualTo(receipt.get("wal_flush_lsn", String.class)); + waitPastDeadline(context, original); + assertThat(tx(context, () -> confirm(context, original, decision))).isEqualTo(receipt); + assertThat(syntheticReadPeer().call(() -> confirmationOwner.read(request))) + .isEqualTo(recovered); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + var readOwner = new AccountGameplayAdmissionReadOwner(repository, transactionManager, "test"); + assertFailedExactRead(readOwner, original); + } + + @Test + void receiptPhysicalCommitPrecedesIndependentV90ReadOnAnotherConnection() throws Exception { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision); + var trace = new ReceiptCommitTrace(); + var owner = + new AccountGameplayAdmissionCommitConfirmationOwner( + receiptCommitDataSource(context.dataSource(), ReceiptCommitFault.NONE, trace), "test"); + + var receipt = + syntheticReadPeer().call(() -> owner.confirm(confirmationRequest(original, decision))); + + assertThat(trace.count("physical-commit")).isEqualTo(2); + assertThat(trace.count("v90-read")).isEqualTo(1); + var receiptCommit = firstEvent(trace, "physical-commit"); + var independentRead = firstEvent(trace, "v90-read"); + assertThat(trace.events().indexOf(receiptCommit)) + .isLessThan(trace.events().indexOf(independentRead)); + assertThat(independentRead.connectionId()).isNotEqualTo(receiptCommit.connectionId()); + assertThat(receipt.operation().evidence().canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(receipt.operation().evidence().sha256()).isEqualTo(original.sha256()); + assertThat(receipt.bindingDecisionId()).isEqualTo(decision); + assertThat(receipt.expiresAtMs()).isEqualTo(expiresAt(original)); + assertThat(receipt.committedBeforeMs()).isPositive().isLessThan(expiresAt(original)); + assertThat(receipt.confirmationXid()).isNotEqualTo(receipt.finalizationXid()); + assertThat(operation(context, original).get("finalization_xid", String.class)) + .isEqualTo(receipt.finalizationXid()); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isEqualTo(1); + } + + @Test + void lostReceiptCommitAcknowledgementDeniesThenRecoversOnlyThroughIndependentV90Read() + throws Exception { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision); + var trace = new ReceiptCommitTrace(); + var owner = + new AccountGameplayAdmissionCommitConfirmationOwner( + receiptCommitDataSource( + context.dataSource(), ReceiptCommitFault.AFTER_FIRST_COMMIT, trace), + "test"); + var request = confirmationRequest(original, decision); + + assertThatThrownBy(() -> syntheticReadPeer().call(() -> owner.confirm(request))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(trace.count("physical-commit")).isEqualTo(1); + assertThat(trace.count("v90-read")).isZero(); + + var retainedRow = confirmationRow(context, original); + assertThat(retainedRow.get("request_id", UUID.class)).isEqualTo(requestId(original)); + assertThat(retainedRow.get("evidence_sha256", String.class)).isEqualTo(original.sha256()); + assertThat(retainedRow.get("binding_decision_id", UUID.class)).isEqualTo(decision); + assertThat(retainedRow.get("expires_at_ms", Long.class)).isEqualTo(expiresAt(original)); + assertThat(retainedRow.get("committed_before_ms", Long.class)) + .isPositive() + .isLessThan(expiresAt(original)); + assertThat(retainedRow.get("finalization_xid", String.class)) + .isEqualTo(operation(context, original).get("finalization_xid", String.class)); + assertThat(retainedRow.get("confirmation_xid", String.class)) + .isNotEqualTo(retainedRow.get("finalization_xid", String.class)); + + // Recovery is an explicit fresh owner read, which invokes the existing V90 independent WAL + // coverage observer. No confirm retry can mint or acknowledge the lost receipt COMMIT. + var recovered = syntheticReadPeer().call(() -> owner.read(request)); + assertThat(trace.count("v90-read")).isEqualTo(1); + var lostAckCommit = firstEvent(trace, "physical-commit"); + var independentRead = firstEvent(trace, "v90-read"); + assertThat(trace.events().indexOf(lostAckCommit)) + .isLessThan(trace.events().indexOf(independentRead)); + assertThat(independentRead.connectionId()).isNotEqualTo(lostAckCommit.connectionId()); + assertThat(recovered.requestId()).isEqualTo(retainedRow.get("request_id", UUID.class)); + assertThat(recovered.evidenceSha256()) + .isEqualTo(retainedRow.get("evidence_sha256", String.class)); + assertThat(recovered.bindingDecisionId()) + .isEqualTo(retainedRow.get("binding_decision_id", UUID.class)); + assertThat(recovered.expiresAtMs()).isEqualTo(retainedRow.get("expires_at_ms", Long.class)); + assertThat(recovered.committedBeforeMs()) + .isEqualTo(retainedRow.get("committed_before_ms", Long.class)); + assertThat(recovered.finalizationXid()) + .isEqualTo(retainedRow.get("finalization_xid", String.class)); + assertThat(recovered.confirmationXid()) + .isEqualTo(retainedRow.get("confirmation_xid", String.class)); + assertThat(confirmationRow(context, original).intoMap()).isEqualTo(retainedRow.intoMap()); + } + + @Test + void receiptCommitFailureBeforePhysicalDelegateRollsBackWithoutReceiptOrIndependentRead() { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision); + var committedOperation = operation(context, original).intoMap(); + var unchanged = storageSnapshot(context); + var trace = new ReceiptCommitTrace(); + var owner = + new AccountGameplayAdmissionCommitConfirmationOwner( + receiptCommitDataSource( + context.dataSource(), ReceiptCommitFault.BEFORE_FIRST_COMMIT, trace), + "test"); + + assertThatThrownBy( + () -> + syntheticReadPeer() + .call(() -> owner.confirm(confirmationRequest(original, decision)))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(trace.count("commit-attempt")).isEqualTo(1); + assertThat(trace.count("physical-commit")).isZero(); + assertThat(trace.count("v90-read")).isZero(); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + assertThat(operation(context, original).intoMap()).isEqualTo(committedOperation); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + @Test + void idlePrimaryConfirmationCapturesBeforeLocksAndIndependentlyReadsExactReceipt() { + var context = context(null); + var original = pending(context, account(context)); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(original, decision)); + var unchanged = storageSnapshot(context); + + String finalizationXid = operation(context, original).get("finalization_xid", String.class); + // No marker, forced flush or unrelated writer is used to make proof succeed. Establish a + // fixed snapshot before the call and prove the original finalizer is independently visible. + // Background WAL may advance, so a pre-call global LSN need not equal the stored fence. + var receipt = + tx( + context, + () -> { + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT pg_visible_in_snapshot(?::xid8, pg_current_snapshot()) " + + "AND pg_current_xact_id_if_assigned() IS NULL AS independent", + finalizationXid)) + .get("independent", Boolean.class)) + .isTrue(); + String beforeHeapReads = + Objects.requireNonNull( + context.dsl().fetchOne("SELECT pg_current_wal_insert_lsn()::text AS lsn")) + .get("lsn", String.class); + var created = confirm(context, original, decision); + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT ?::pg_lsn >= ?::pg_lsn " + + "AND ?::pg_lsn >= ?::pg_lsn AS snapshot_fence_covered", + created.get("wal_insert_lsn", String.class), + beforeHeapReads, + created.get("wal_flush_lsn", String.class), + created.get("wal_insert_lsn", String.class))) + .get("snapshot_fence_covered", Boolean.class)) + .isTrue(); + return created; + }); + + tx( + context, + () -> { + assertThat( + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT pg_visible_in_snapshot(?::xid8, pg_current_snapshot()) " + + "AND pg_current_xact_id_if_assigned() IS NULL AS independent", + receipt.get("confirmation_xid", String.class))) + .get("independent", Boolean.class)) + .isTrue(); + assertThat(readConfirmation(context, original, decision)).isEqualTo(receipt); + return null; + }); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + @Test + void staleSerializableConfirmationInsertRetriesInsteadOfLeakingUniqueViolation() + throws Exception { + var context = context(null); + var original = pending(context, account(context)); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(original, decision)); + var unchanged = storageSnapshot(context); + var snapshotReady = new CountDownLatch(1); + var winnerCommitted = new CountDownLatch(1); + try (var executor = Executors.newSingleThreadExecutor()) { + var stale = + executor.submit( + () -> + tx( + context, + () -> { + assertThat( + context + .dsl() + .fetchCount( + DSL.table( + "account_gameplay_admission_commit_confirmations"))) + .isZero(); + snapshotReady.countDown(); + try { + if (!winnerCommitted.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("winner commit timeout"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return confirm(context, original, decision); + })); + Record retained; + try { + assertThat(snapshotReady.await(10, TimeUnit.SECONDS)).isTrue(); + retained = tx(context, () -> confirm(context, original, decision)); + } finally { + winnerCommitted.countDown(); + } + assertThatThrownBy(() -> stale.get(30, TimeUnit.SECONDS)) + .satisfies( + failure -> { + Throwable cause = failure; + while (cause != null && !(cause instanceof java.sql.SQLException)) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(java.sql.SQLException.class); + assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("40001"); + }); + assertThat(tx(context, () -> confirm(context, original, decision))).isEqualTo(retained); + assertThat(tx(context, () -> readConfirmation(context, original, decision))) + .isEqualTo(retained); + } + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isEqualTo(1); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + @Test + void updateBeforeExpiryButPhysicalCommitAfterExpiryCannotCreateConfirmation() { + var context = context(null); + var original = pending(context, account(context), 1000); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx( + context, + () -> { + repository.recordCommitted(original, decision); + assertThat(databaseNow(context)).isLessThan(expiresAt(original)); + waitPastDeadline(context, original); + return null; + }); + assertThat(operation(context, original).get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(operation(context, original).get("finalization_xid", String.class)).isNotNull(); + var unchanged = storageSnapshot(context); + assertThatThrownBy(() -> tx(context, () -> confirm(context, original, decision))) + .hasMessageContaining("original deadline expired"); + assertThatThrownBy(() -> tx(context, () -> readConfirmation(context, original, decision))) + .hasMessageContaining("exact durable receipt required"); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + @Test + void sameTransactionAndReleasedSubtransactionCannotConfirmOriginalFinalization() { + var context = context(null); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + for (boolean subtransaction : List.of(false, true)) { + var original = pending(context, account); + UUID decision = UUID.randomUUID(); + tx( + context, + () -> { + if (subtransaction) context.dsl().execute("SAVEPOINT original_finalization"); + repository.recordCommitted(original, decision); + if (subtransaction) context.dsl().execute("RELEASE SAVEPOINT original_finalization"); + var stamp = operation(context, original).get("finalization_xid", String.class); + assertThat(stamp) + .isEqualTo( + Objects.requireNonNull( + context.dsl().fetchOne("SELECT pg_current_xact_id()::text AS xid")) + .get("xid", String.class)); + assertDeniedInSavepoint( + context, + () -> confirm(context, original, decision), + "requires independent finalization commit"); + assertDeniedInSavepoint( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) VALUES (?, ?, ?)", + requestId(original), + original.sha256(), + decision), + "requires independent finalization commit"); + return null; + }); + } + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + } + + @Test + void missingPendingRolledBackAbortedAndRetainedUnstampedCommitsStayUnproved() { + var context = context("89"); + UUID account = account(context); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var retained = pending(context, account); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(retained, decision)); + var retainedPending = pending(context, account); + var aborted = pending(context, account); + tx(context, () -> repository.recordAborted(aborted, null, UUID.randomUUID())); + migrate(context, null); + assertThat(operation(context, retained).get("finalization_xid", String.class)).isNull(); + assertThat(operation(context, retainedPending).get("finalization_xid", String.class)).isNull(); + assertThat(operation(context, aborted).get("finalization_xid", String.class)).isNull(); + var rolledBack = pending(context, account); + assertThatThrownBy( + () -> + tx( + context, + () -> { + repository.recordCommitted(rolledBack, decision); + throw new IllegalStateException("roll back physical finalization"); + })) + .hasMessageContaining("roll back physical finalization"); + assertThat(operation(context, rolledBack).get("status", String.class)).isEqualTo("PENDING"); + assertThat(operation(context, rolledBack).get("finalization_xid", String.class)).isNull(); + var unchanged = storageSnapshot(context); + for (var unproved : List.of(retained, retainedPending, aborted, rolledBack)) { + assertThatThrownBy(() -> tx(context, () -> confirm(context, unproved, decision))) + .hasMessageContaining("exact committed binding required"); + assertThatThrownBy(() -> tx(context, () -> readConfirmation(context, unproved, decision))) + .hasMessageContaining("exact durable receipt required"); + } + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + UUID.randomUUID(), + retained.sha256(), + decision))) + .hasMessageContaining("operation missing"); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + @Test + void confirmationRejectsChangedBindingsAndCallerProofAndRemainsImmutable() { + var context = context(null); + UUID account = account(context); + var original = pending(context, account); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + UUID request = requestId(original); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET status = 'COMMITTED', binding_decision_id = ?, finalization_xid = '1' WHERE request_id = ?", + decision, + request))) + .hasMessageContaining("finalization transaction is database stamped"); + tx(context, () -> repository.recordCommitted(original, decision)); + var unchanged = storageSnapshot(context); + // SQL owns the transaction prerequisite even for callers bypassing the Java owner. + for (int isolation : + List.of( + TransactionDefinition.ISOLATION_READ_COMMITTED, + TransactionDefinition.ISOLATION_REPEATABLE_READ)) { + var unsupported = + new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); + unsupported.setIsolationLevel(isolation); + for (Supplier action : + List.>of( + () -> confirm(context, original, decision), + () -> readConfirmation(context, original, decision), + () -> + context + .dsl() + .execute( + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) VALUES (?, ?, ?)", + request, + original.sha256(), + decision))) { + assertThatThrownBy(() -> unsupported.execute(status -> action.get())) + .hasMessageContaining("writable SERIALIZABLE transaction required"); + } + } + var readOnly = new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); + readOnly.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> readOnly.execute(status -> readConfirmation(context, original, decision))) + .hasMessageContaining("writable SERIALIZABLE transaction required"); + assertThatThrownBy(() -> readOnly.execute(status -> confirm(context, original, decision))) + .hasMessageContaining("read-only transaction"); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + request, + "b".repeat(64), + decision))) + .hasMessageContaining("exact committed binding required"); + assertThatThrownBy(() -> tx(context, () -> confirm(context, original, UUID.randomUUID()))) + .hasMessageContaining("exact committed binding required"); + // Every proof/identity field is database-derived even if supplied values look plausible. + for (String assignment : + List.of( + "account_uuid = '" + account + "'::uuid", + "lease_id = '" + original.carrier().get("leaseId") + "'::uuid", + "lease_fence = 1", + "expires_at_ms = " + expiresAt(original), + "finalization_xid = '1'", + "wal_insert_lsn = '0/1'", + "wal_flush_lsn = '0/1'", + "committed_before_ms = 1", + "confirmation_xid = '1'")) { + String[] fieldAndValue = assignment.split(" = ", 2); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id, " + + fieldAndValue[0] + + ") VALUES (?, ?, ?, " + + fieldAndValue[1] + + ")", + request, + original.sha256(), + decision))) + .hasMessageContaining("proof is database derived"); + } + var receipt = tx(context, () -> confirm(context, original, decision)); + for (String mutation : + List.of( + "UPDATE account_gameplay_admission_commit_confirmations SET committed_before_ms = 1", + "UPDATE account_gameplay_admission_commit_confirmations SET expires_at_ms = expires_at_ms + 1", + "UPDATE account_gameplay_admission_commit_confirmations SET evidence_sha256 = '" + + "b".repeat(64) + + "'", + "DELETE FROM account_gameplay_admission_commit_confirmations", + "TRUNCATE account_gameplay_admission_commit_confirmations")) { + assertThatThrownBy(() -> tx(context, () -> context.dsl().execute(mutation))) + .hasMessageContaining("confirmation is immutable"); + } + assertThatThrownBy( + () -> tx(context, () -> readConfirmation(context, original, UUID.randomUUID()))) + .hasMessageContaining("exact durable receipt required"); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET finalization_xid = '1' WHERE request_id = ?", + request))) + .hasMessageContaining("finalization transaction is database stamped"); + assertThat(tx(context, () -> readConfirmation(context, original, decision))).isEqualTo(receipt); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + @Test + void sameTransactionReceiptReadAndRolledBackConfirmationCannotProveDurability() { + var context = context(null); + var original = pending(context, account(context)); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(original, decision)); + for (boolean subtransaction : List.of(false, true)) { + assertThatThrownBy( + () -> + tx( + context, + () -> { + if (subtransaction) context.dsl().execute("SAVEPOINT receipt_creation"); + confirm(context, original, decision); + if (subtransaction) + context.dsl().execute("RELEASE SAVEPOINT receipt_creation"); + assertDeniedInSavepoint( + context, + () -> readConfirmation(context, original, decision), + "requires independent receipt commit"); + throw new IllegalStateException("roll back confirmation commit"); + })) + .hasMessageContaining("roll back confirmation commit"); + } + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + assertThatThrownBy(() -> tx(context, () -> readConfirmation(context, original, decision))) + .hasMessageContaining("exact durable receipt required"); + var receipt = tx(context, () -> confirm(context, original, decision)); + assertThat(tx(context, () -> readConfirmation(context, original, decision))).isEqualTo(receipt); + } + + @Test + void concurrentConfirmationsRetainOneOriginalReceiptWithoutAdvancingSources() throws Exception { + var context = context(null); + var original = pending(context, account(context)); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + UUID decision = UUID.randomUUID(); + tx(context, () -> repository.recordCommitted(original, decision)); + var unchanged = storageSnapshot(context); + var start = new CountDownLatch(1); + Callable duplicate = + () -> { + if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); + return retrySerialization(() -> tx(context, () -> confirm(context, original, decision))); + }; + try (var executor = Executors.newFixedThreadPool(2)) { + var left = executor.submit(duplicate); + var right = executor.submit(duplicate); + start.countDown(); + assertThat(left.get(30, TimeUnit.SECONDS)).isEqualTo(right.get(30, TimeUnit.SECONDS)); + } + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isEqualTo(1); + var retained = tx(context, () -> confirm(context, original, decision)); + waitPastDeadline(context, original); + assertThat( + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) VALUES (?, ?, ?) ON CONFLICT (request_id) DO NOTHING", + requestId(original), + original.sha256(), + decision))) + .isZero(); + // Both duplicates enter the INSERT guard but replay the expired retained receipt without + // taking fresh temporal proof, restamping its bound or allocating replacement evidence. + try (var executor = Executors.newFixedThreadPool(2)) { + var left = executor.submit(duplicate); + var right = executor.submit(duplicate); + assertThat(left.get(30, TimeUnit.SECONDS)).isEqualTo(retained); + assertThat(right.get(30, TimeUnit.SECONDS)).isEqualTo(retained); + } + assertThat(tx(context, () -> readConfirmation(context, original, decision))) + .isEqualTo(retained); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + + @Test + void originalAckReceiptMigrationPreservesV91HistoryWithoutInventingAcknowledgement() { + var context = context("91"); + UUID committedAccount = account(context); + var retainedCommittedEvidence = pending(context, committedAccount); + UUID retainedDecision = UUID.randomUUID(); + var leaseRepository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var retainedCommitted = + tx( + context, + () -> leaseRepository.recordCommitted(retainedCommittedEvidence, retainedDecision)); + assertThat(retainedCommitted.state()).isEqualTo(State.COMMITTED); + var committedBefore = operation(context, retainedCommittedEvidence).intoMap(); + + UUID pendingAccount = account(context); + var retainedPendingEvidence = pending(context, pendingAccount); + var pendingBefore = operation(context, retainedPendingEvidence).intoMap(); + var v91Checksums = flywayChecksums(context); + assertThat(v91Checksums).containsKey("91").doesNotContainKey("92"); + + migrate(context, null); + + var latestChecksums = flywayChecksums(context); + for (var entry : v91Checksums.entrySet()) + assertThat(latestChecksums).containsEntry(entry.getKey(), entry.getValue()); + assertThat(latestChecksums.get("92")).isNotNull(); + assertThat(operation(context, retainedCommittedEvidence).intoMap()).isEqualTo(committedBefore); + assertThat(operation(context, retainedPendingEvidence).intoMap()).isEqualTo(pendingBefore); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isZero(); + + var originalExecutor = new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()); + UUID pendingDecision = UUID.randomUUID(); + var acknowledgement = originalExecutor.execute(retainedPendingEvidence, pendingDecision); + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.dataSource()) + .confirm(acknowledgement); + var newlyCommitted = operation(context, retainedPendingEvidence); + for (String field : + List.of( + "request_id", + "account_uuid", + "lease_id", + "lease_fence", + "evidence_json", + "evidence_sha256", + "evaluated_at_ms", + "expires_at_ms")) { + assertThat(newlyCommitted.get(field)).as(field).isEqualTo(pendingBefore.get(field)); + } + assertThat(receipt.operation().evidence()).isEqualTo(retainedPendingEvidence); + assertThat(receipt.operation().bindingDecisionId()).isEqualTo(pendingDecision); + assertThat(receipt.expiresAtMs()).isEqualTo((Long) pendingBefore.get("expires_at_ms")); + assertThat(receipt.committedBeforeMs()) + .isEqualTo(acknowledgement.committedBeforeMs()) + .isLessThan(receipt.expiresAtMs()); + assertThat(receipt.finalizationXid()) + .isEqualTo(newlyCommitted.get("finalization_xid", String.class)); + + assertThatThrownBy(() -> originalExecutor.execute(retainedCommittedEvidence, retainedDecision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(operation(context, retainedCommittedEvidence).intoMap()).isEqualTo(committedBefore); + + var retainedReceiptRow = originalAckReceiptRow(context, retainedPendingEvidence).intoMap(); + String receiptTable = "account_gameplay_admission_original_commit_ack_receipts"; + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "UPDATE " + + receiptTable + + " SET committed_before_ms = committed_before_ms + 1 " + + "WHERE request_id = ?", + requestId(retainedPendingEvidence)))) + .hasMessageContaining("Original Account COMMIT acknowledgement receipt is immutable"); + assertThat(originalAckReceiptRow(context, retainedPendingEvidence).intoMap()) + .isEqualTo(retainedReceiptRow); + assertThatThrownBy( + () -> + tx( + context, + () -> + context + .dsl() + .execute( + "DELETE FROM " + receiptTable + " WHERE request_id = ?", + requestId(retainedPendingEvidence)))) + .hasMessageContaining("Original Account COMMIT acknowledgement receipt is immutable"); + assertThat(originalAckReceiptRow(context, retainedPendingEvidence).intoMap()) + .isEqualTo(retainedReceiptRow); + assertThatThrownBy(() -> tx(context, () -> context.dsl().execute("TRUNCATE " + receiptTable))) + .hasMessageContaining("Original Account COMMIT acknowledgement receipt is immutable"); + assertThat(originalAckReceiptRow(context, retainedPendingEvidence).intoMap()) + .isEqualTo(retainedReceiptRow); + var finalChecksums = flywayChecksums(context); + for (var entry : latestChecksums.entrySet()) + assertThat(finalChecksums).containsEntry(entry.getKey(), entry.getValue()); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isEqualTo(1); + } + + @Test + void originalAckReceiptCommitsThenIndependentlyReadsExactOriginalBound() { + var context = context(null); + var original = pending(context, account(context)); + var before = operation(context, original).intoMap(); + UUID decision = UUID.randomUUID(); + var trace = new ReceiptCommitTrace(); + var receiptPhase = new AtomicBoolean(); + var dataSource = originalAckReceiptDataSource(context.dataSource(), trace, receiptPhase, false); + + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(dataSource).execute(original, decision); + receiptPhase.set(true); + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(dataSource) + .confirm(acknowledgement); + + var committed = operation(context, original); + assertThat(receipt.operation().evidence().canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(receipt.operation().evidence().sha256()).isEqualTo(original.sha256()); + assertThat(receipt.operation().bindingDecisionId()).isEqualTo(decision); + assertThat(receipt.schemaVersion()).isEqualTo((short) 1); + assertThat(receipt.requestId()).isEqualTo(requestId(original)); + var scope = (Map) original.carrier().get("bindingScope"); + assertThat(receipt.accountId()).isEqualTo(UUID.fromString((String) scope.get("accountId"))); + assertThat(receipt.leaseId()) + .isEqualTo(UUID.fromString((String) original.carrier().get("leaseId"))); + assertThat(receipt.leaseFence()).isEqualTo(original.leaseFence().longValueExact()); + assertThat(receipt.evidenceSha256()).isEqualTo(original.sha256()); + assertThat(receipt.bindingDecisionId()).isEqualTo(decision); + assertThat(receipt.expiresAtMs()).isEqualTo(expiresAt(original)); + assertThat(receipt.committedBeforeMs()) + .isEqualTo(acknowledgement.committedBeforeMs()) + .isPositive() + .isLessThan(receipt.expiresAtMs()); + assertThat(receipt.finalizationXid()).isEqualTo(acknowledgement.finalizationXid()); + assertThat(receipt.finalizationXid()) + .isEqualTo(committed.get("finalization_xid", String.class)); + assertThat(receipt.receiptXid()).isNotEqualTo(receipt.finalizationXid()); + assertThat(committed.get("expires_at_ms", Long.class)).isEqualTo(before.get("expires_at_ms")); + assertThat(trace.count("original-physical-commit")).isEqualTo(1); + assertThat(trace.count("receipt-physical-commit")).isEqualTo(1); + assertThat(trace.count("receipt-exact-read")).isEqualTo(1); + assertThat(trace.count("receipt-readback-physical-commit")).isEqualTo(1); + var receiptCommit = firstEvent(trace, "receipt-physical-commit"); + var exactRead = firstEvent(trace, "receipt-exact-read"); + var readbackCommit = firstEvent(trace, "receipt-readback-physical-commit"); + assertThat(trace.events().indexOf(receiptCommit)).isLessThan(trace.events().indexOf(exactRead)); + assertThat(trace.events().indexOf(exactRead)) + .isLessThan(trace.events().indexOf(readbackCommit)); + assertThat(exactRead.connectionId()).isNotEqualTo(receiptCommit.connectionId()); + assertThat(exactRead.connectionId()).isEqualTo(readbackCommit.connectionId()); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isEqualTo(1); + // This immutable storage receipt is non-authorizing and does not establish gameplay admission. + } + + @Test + void originalAckReceiptRejectsAnotherDataSourceAndChangedBindings() throws SQLException { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision); + + var foreignAcquisitions = new AtomicInteger(); + DataSource anotherIdentityForSamePostgres = + new DelegatingDataSource(context.dataSource()) { + @Override + public Connection getConnection() throws SQLException { + foreignAcquisitions.incrementAndGet(); + return super.getConnection(); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + foreignAcquisitions.incrementAndGet(); + return super.getConnection(username, password); + } + }; + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor( + anotherIdentityForSamePostgres) + .confirm(acknowledgement)) + .hasMessageContaining("Fresh owned Account receipt COMMIT required"); + assertThat(foreignAcquisitions.get()).isZero(); + + var executor = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.dataSource()); + var receipt = executor.confirm(acknowledgement); + var retained = originalAckReceiptRow(context, original).intoMap(); + var changedCarrier = new LinkedHashMap<>(original.carrier()); + changedCarrier.put("leaseId", UUID.randomUUID().toString()); + var changedEvidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + + assertThatThrownBy(() -> executor.read(original, UUID.randomUUID())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> executor.read(changedEvidence, decision)) + .isInstanceOf(RuntimeException.class); + assertThat(originalAckReceiptRow(context, original).intoMap()).isEqualTo(retained); + assertThat(receipt.requestId()).isEqualTo(requestId(original)); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isEqualTo(1); + } + + @Test + void lostOriginalAcknowledgementCannotCreateOriginalAckReceipt() { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var physicalCommits = new AtomicInteger(); + var executor = + new AccountGameplayAdmissionOriginalCommitExecutor( + originalCommitFailureDataSource(context.dataSource(), true, physicalCommits)); + + assertThatThrownBy(() -> executor.execute(original, decision)) + .hasMessageContaining("Original Account physical COMMIT unavailable"); + assertThat(physicalCommits.get()).isEqualTo(1); + var committed = operation(context, original).intoMap(); + assertThat(committed.get("status")).isEqualTo("COMMITTED"); + assertThat(committed.get("binding_decision_id")).isEqualTo(decision); + assertThat(committed.get("expires_at_ms")).isEqualTo(expiresAt(original)); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(operation(context, original).intoMap()).isEqualTo(committed); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isZero(); + } + + @Test + void originalAckReceiptCreatedInCurrentTransactionIsNotDurableReadback() { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision); + + assertThatThrownBy( + () -> + tx( + context, + () -> { + var dsl = context.dsl(); + var repository = + new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + repository.create(acknowledgement); + repository.readDurably(original, decision); + return null; + })) + .satisfies( + failure -> { + Throwable cause = failure; + while (cause != null && !(cause instanceof SQLException)) cause = cause.getCause(); + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); + assertThat(cause.getMessage()) + .contains("Original Account acknowledgement receipt requires independent commit"); + }); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isZero(); + } + + @Test + void lostOriginalAckReceiptAcknowledgementDeniesWithoutRemintingOriginalProof() { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var trace = new ReceiptCommitTrace(); + var receiptPhase = new AtomicBoolean(); + var dataSource = originalAckReceiptDataSource(context.dataSource(), trace, receiptPhase, true); + var originalExecutor = new AccountGameplayAdmissionOriginalCommitExecutor(dataSource); + var acknowledgement = originalExecutor.execute(original, decision); + receiptPhase.set(true); + var receiptExecutor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(dataSource); + + assertThatThrownBy(() -> receiptExecutor.confirm(acknowledgement)) + .hasMessageContaining("Account receipt physical COMMIT unavailable"); + assertThat(trace.count("original-physical-commit")).isEqualTo(1); + assertThat(trace.count("receipt-commit-attempt")).isEqualTo(1); + assertThat(trace.count("receipt-physical-commit")).isEqualTo(1); + assertThat(trace.count("receipt-exact-read")).isZero(); + assertThat(trace.count("receipt-durable-read")).isZero(); + + // This raw row inspection is diagnostic visibility only, not the executor's historical + // WAL-coverage recovery proof. No independent receipt read is attempted after lost COMMIT ACK. + var retained = originalAckReceiptRow(context, original); + assertThat(retained.get("request_id", UUID.class)).isEqualTo(requestId(original)); + assertThat(retained.get("evidence_sha256", String.class)).isEqualTo(original.sha256()); + assertThat(retained.get("binding_decision_id", UUID.class)).isEqualTo(decision); + assertThat(retained.get("expires_at_ms", Long.class)).isEqualTo(expiresAt(original)); + assertThat(retained.get("committed_before_ms", Long.class)) + .isEqualTo(acknowledgement.committedBeforeMs()) + .isPositive() + .isLessThan(expiresAt(original)); + assertThat(retained.get("finalization_xid", String.class)) + .isEqualTo(acknowledgement.finalizationXid()); + assertThat(retained.get("receipt_xid", String.class)) + .isNotEqualTo(retained.get("finalization_xid", String.class)); + + var committed = operation(context, original).intoMap(); + assertThatThrownBy(() -> originalExecutor.execute(original, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(operation(context, original).intoMap()).isEqualTo(committed); + assertThat(trace.count("original-physical-commit")).isEqualTo(1); + assertThat(trace.count("receipt-exact-read")).isZero(); + assertThat(trace.count("receipt-durable-read")).isZero(); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isEqualTo(1); + } + + @Test + void originalAckReceiptRecoversExactOriginalProofAfterLostReceiptAcknowledgement() { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var trace = new ReceiptCommitTrace(); + var receiptPhase = new AtomicBoolean(); + var dataSource = originalAckReceiptDataSource(context.dataSource(), trace, receiptPhase, true); + var originalExecutor = new AccountGameplayAdmissionOriginalCommitExecutor(dataSource); + var acknowledgement = originalExecutor.execute(original, decision); + receiptPhase.set(true); + var receiptExecutor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(dataSource); + + assertThatThrownBy(() -> receiptExecutor.confirm(acknowledgement)) + .hasMessageContaining("Account receipt physical COMMIT unavailable"); + assertThat(trace.count("receipt-durable-read")).isZero(); + var operationBeforeRecovery = operation(context, original).intoMap(); + var rowBeforeRecoveryRecord = originalAckReceiptRow(context, original); + var rowBeforeRecovery = rowBeforeRecoveryRecord.intoMap(); + assertThat(rowBeforeRecoveryRecord.get("committed_before_ms", Long.class)) + .isEqualTo(acknowledgement.committedBeforeMs()); + assertThat(rowBeforeRecoveryRecord.get("finalization_xid", String.class)) + .isEqualTo(acknowledgement.finalizationXid()); + assertThat(rowBeforeRecoveryRecord.get("expires_at_ms", Long.class)) + .isEqualTo(expiresAt(original)); + assertThat(rowBeforeRecoveryRecord.get("receipt_xid", String.class)) + .isNotEqualTo(rowBeforeRecoveryRecord.get("finalization_xid", String.class)); + + var recovered = receiptExecutor.read(original, decision); + + assertThat(trace.count("receipt-physical-commit")).isEqualTo(2); + assertThat(trace.count("receipt-durable-read")).isEqualTo(1); + assertThat(trace.count("receipt-exact-read")).isZero(); + var lostReceiptCommit = firstEvent(trace, "receipt-physical-commit"); + var historicalRead = firstEvent(trace, "receipt-durable-read"); + assertThat(trace.events().indexOf(lostReceiptCommit)) + .isLessThan(trace.events().indexOf(historicalRead)); + assertThat(historicalRead.connectionId()).isNotEqualTo(lostReceiptCommit.connectionId()); + assertThat(recovered.operation().evidence().canonicalJson()) + .isEqualTo(original.canonicalJson()); + assertThat(recovered.operation().evidence().sha256()).isEqualTo(original.sha256()); + assertThat(recovered.operation().bindingDecisionId()).isEqualTo(decision); + assertThat(recovered.schemaVersion()) + .isEqualTo(rowBeforeRecoveryRecord.get("schema_version", Short.class)); + assertThat(recovered.requestId()).isEqualTo(requestId(original)); + assertThat(recovered.accountId()) + .isEqualTo(rowBeforeRecoveryRecord.get("account_uuid", UUID.class)); + assertThat(recovered.leaseId()).isEqualTo(rowBeforeRecoveryRecord.get("lease_id", UUID.class)); + assertThat(recovered.leaseFence()) + .isEqualTo(rowBeforeRecoveryRecord.get("lease_fence", Long.class)); + assertThat(recovered.evidenceSha256()).isEqualTo(original.sha256()); + assertThat(recovered.bindingDecisionId()).isEqualTo(decision); + assertThat(recovered.expiresAtMs()) + .isEqualTo(rowBeforeRecoveryRecord.get("expires_at_ms", Long.class)); + assertThat(recovered.committedBeforeMs()) + .isEqualTo(rowBeforeRecoveryRecord.get("committed_before_ms", Long.class)) + .isLessThan(recovered.expiresAtMs()); + assertThat(recovered.finalizationXid()) + .isEqualTo(rowBeforeRecoveryRecord.get("finalization_xid", String.class)); + assertThat(recovered.receiptXid()) + .isEqualTo(rowBeforeRecoveryRecord.get("receipt_xid", String.class)); + assertThat(originalAckReceiptRow(context, original).intoMap()).isEqualTo(rowBeforeRecovery); + assertThat(operation(context, original).intoMap()).isEqualTo(operationBeforeRecovery); + + assertThatThrownBy(() -> originalExecutor.execute(original, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(operation(context, original).intoMap()).isEqualTo(operationBeforeRecovery); + assertThat(trace.count("original-physical-commit")).isEqualTo(1); + } + + private static Record confirm( + Context context, AccountGameplayAdmissionLeaseEvidence original, UUID decision) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + requestId(original), + original.sha256(), + decision)); + } + + private static FinalizeGameplayAdmissionLeaseRequest confirmationRequest( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + return FinalizeGameplayAdmissionLeaseRequest.newBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence)) + .setBindingDecisionId(decision.toString()) + .build(); + } + + private static Record confirmationRow( + Context context, AccountGameplayAdmissionLeaseEvidence original) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_commit_confirmations WHERE request_id = ?", + requestId(original))); + } + + private static Record originalAckReceiptRow( + Context context, AccountGameplayAdmissionLeaseEvidence original) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_original_commit_ack_receipts " + + "WHERE request_id = ?", + requestId(original))); + } + + private enum ReceiptCommitFault { + NONE, + BEFORE_FIRST_COMMIT, + AFTER_FIRST_COMMIT + } + + private record ReceiptCommitEvent(String kind, int connectionId) {} + + private static final class ReceiptCommitTrace { + private final AtomicInteger connectionIds = new AtomicInteger(); + private final AtomicInteger commitAttempts = new AtomicInteger(); + private final List events = new java.util.ArrayList<>(); + + private void record(String kind, int connectionId) { + events.add(new ReceiptCommitEvent(kind, connectionId)); + } + + private int count(String kind) { + return (int) events.stream().filter(event -> event.kind().equals(kind)).count(); + } + + private List events() { + return events; + } + } + + /** Traces only JDBC work performed by the real receipt owner over the supplied PostgreSQL DS. */ + private static DataSource receiptCommitDataSource( + DataSource source, ReceiptCommitFault fault, ReceiptCommitTrace trace) { + return new DelegatingDataSource(source) { + @Override + public Connection getConnection() throws SQLException { + return tracedConnection(super.getConnection()); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return tracedConnection(super.getConnection(username, password)); + } + + private Connection tracedConnection(Connection physical) { + int connectionId = trace.connectionIds.incrementAndGet(); + return (Connection) + Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("commit") && method.getParameterCount() == 0) { + int attempt = trace.commitAttempts.incrementAndGet(); + if (attempt == 1 && fault == ReceiptCommitFault.BEFORE_FIRST_COMMIT) { + trace.record("commit-attempt", connectionId); + throw new SQLException("Test failed before physical receipt COMMIT", "08006"); + } + physical.commit(); + trace.record("physical-commit", connectionId); + if (attempt == 1 && fault == ReceiptCommitFault.AFTER_FIRST_COMMIT) + throw new SQLException("Test lost physical receipt COMMIT response", "08006"); + return null; + } + try { + Object result = method.invoke(physical, arguments); + if (result instanceof PreparedStatement statement) { + String sql = ""; + if (arguments != null + && arguments.length > 0 + && arguments[0] instanceof String statementSql) { + sql = statementSql; + } + return tracedStatement(statement, sql, connectionId, trace); + } + return result; + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } + }; + } + + /** + * Traces real original/receipt JDBC commits and ensures the exact read follows receipt COMMIT. + */ + private static DataSource originalAckReceiptDataSource( + DataSource source, + ReceiptCommitTrace trace, + AtomicBoolean receiptPhase, + boolean loseFirstReceiptCommitAcknowledgement) { + return new DelegatingDataSource(source) { + @Override + public Connection getConnection() throws SQLException { + return tracedConnection(super.getConnection()); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return tracedConnection(super.getConnection(username, password)); + } + + private Connection tracedConnection(Connection physical) { + int connectionId = trace.connectionIds.incrementAndGet(); + var exactReadOnConnection = new AtomicBoolean(); + return (Connection) + Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("commit") && method.getParameterCount() == 0) { + if (!receiptPhase.get()) { + physical.commit(); + trace.record("original-physical-commit", connectionId); + return null; + } + int attempt = trace.commitAttempts.incrementAndGet(); + trace.record("receipt-commit-attempt", connectionId); + physical.commit(); + trace.record( + exactReadOnConnection.get() + ? "receipt-readback-physical-commit" + : "receipt-physical-commit", + connectionId); + if (attempt == 1 && loseFirstReceiptCommitAcknowledgement) + throw new SQLException("Test lost physical receipt COMMIT response", "08006"); + return null; + } + try { + Object result = method.invoke(physical, arguments); + if (result instanceof PreparedStatement statement) { + String sql = + arguments != null + && arguments.length > 0 + && arguments[0] instanceof String statementSql + ? statementSql + : ""; + return originalAckReceiptStatement( + statement, sql, connectionId, trace, exactReadOnConnection); + } + return result; + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } + }; + } + + private static PreparedStatement originalAckReceiptStatement( + PreparedStatement physical, + String sql, + int connectionId, + ReceiptCommitTrace trace, + AtomicBoolean exactReadOnConnection) { + String normalized = sql.toLowerCase(java.util.Locale.ROOT).stripLeading(); + boolean exactRead = + normalized.startsWith("select") + && normalized.contains("account_gameplay_admission_original_commit_ack_receipts"); + boolean durableRead = + normalized.contains("account_gameplay_admission_read_original_ack_receipt_durably"); + return (PreparedStatement) + Proxy.newProxyInstance( + PreparedStatement.class.getClassLoader(), + new Class[] {PreparedStatement.class}, + (proxy, method, arguments) -> { + if (method.getName().startsWith("execute")) { + if (exactRead) { + exactReadOnConnection.set(true); + trace.record("receipt-exact-read", connectionId); + } + if (durableRead) trace.record("receipt-durable-read", connectionId); + } + try { + return method.invoke(physical, arguments); + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } + + private static PreparedStatement tracedStatement( + PreparedStatement physical, String sql, int connectionId, ReceiptCommitTrace trace) { + return (PreparedStatement) + Proxy.newProxyInstance( + PreparedStatement.class.getClassLoader(), + new Class[] {PreparedStatement.class}, + (proxy, method, arguments) -> { + if (method.getName().startsWith("execute") && isV90IndependentRead(sql)) + trace.record("v90-read", connectionId); + try { + return method.invoke(physical, arguments); + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } + + private static boolean isV90IndependentRead(String sql) { + return sql.toLowerCase(java.util.Locale.ROOT) + .contains("account_gameplay_admission_read_commit_confirmation"); + } + + private static ReceiptCommitEvent firstEvent(ReceiptCommitTrace trace, String kind) { + return trace.events().stream() + .filter(event -> event.kind().equals(kind)) + .findFirst() + .orElseThrow(() -> new AssertionError("Missing receipt JDBC event: " + kind)); + } + + private static Record readConfirmation( + Context context, AccountGameplayAdmissionLeaseEvidence original, UUID decision) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_read_commit_confirmation(?, ?, ?)", + requestId(original), + original.sha256(), + decision)); + } + + private static void assertDeniedInSavepoint( + Context context, Supplier action, String expectedMessage) { + context.dsl().execute("SAVEPOINT denied_confirmation"); + try { + assertThatThrownBy(action::get) + .hasMessageContaining(expectedMessage) + .satisfies( + failure -> { + Throwable cause = failure; + while (cause != null && !(cause instanceof java.sql.SQLException)) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(java.sql.SQLException.class); + assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("23514"); + }); + } finally { + context.dsl().execute("ROLLBACK TO SAVEPOINT denied_confirmation"); + context.dsl().execute("RELEASE SAVEPOINT denied_confirmation"); + } + } + + private static Record operation(Context context, AccountGameplayAdmissionLeaseEvidence original) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_admission_lease_operations WHERE request_id = ?", + requestId(original))); + } + + private static Map>> storageSnapshot(Context context) { + Map>> snapshot = new LinkedHashMap<>(); + for (String table : + List.of( + "accounts", + "account_gameplay_admission_lease_fences", + "account_gameplay_admission_lease_allocations", + "account_gameplay_admission_lease_operations", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_source_records", + "account_authority_outbox_streams", + "account_authority_outbox_events")) { + snapshot.put( + table, + context.dsl().fetch("SELECT * FROM " + table + " ORDER BY 1").stream() + .map(Record::intoMap) + .toList()); + } + return snapshot; + } + + private static UUID requestId(AccountGameplayAdmissionLeaseEvidence original) { + return UUID.fromString((String) original.carrier().get("requestId")); + } + + private static long expiresAt(AccountGameplayAdmissionLeaseEvidence original) { + return Long.parseLong((String) original.carrier().get("expiresAt")); + } + + private static long databaseNow(Context context) { + return Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint AS now_ms")) + .get("now_ms", Long.class); + } + + private static void waitPastDeadline( + Context context, AccountGameplayAdmissionLeaseEvidence original) { + context + .dsl() + .fetchOne( + "SELECT pg_sleep(GREATEST(0, (? - ceil(extract(epoch FROM clock_timestamp()) * 1000) + 50) / 1000.0))", + expiresAt(original)); + assertThat(databaseNow(context)).isGreaterThanOrEqualTo(expiresAt(original)); + } + + private static AccountGameplayAdmissionLeaseEvidence pending( + Context context, UUID account, long lifetimeMs) { + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + return tx( + context, + () -> { + var allocation = repository.allocate(account, UUID.randomUUID(), UUID.randomUUID()); + var carrier = new LinkedHashMap<>(evidence(allocation).carrier()); + carrier.put( + "expiresAt", + Long.toString(Long.parseLong((String) carrier.get("evaluatedAt")) + lifetimeMs)); + var evidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + repository.beginPending(evidence); + return evidence; + }); + } + + private static T retrySerialization(Supplier action) { + for (int attempt = 0; ; attempt++) { + try { + return action.get(); + } catch (RuntimeException failure) { + Throwable cause = failure; + boolean serialization = false; + while (cause != null) { + if (cause instanceof java.sql.SQLException sql && "40001".equals(sql.getSQLState())) + serialization = true; + cause = cause.getCause(); + } + if (!serialization || attempt >= 4) throw failure; + } + } + } + + private static AccountGameplayAdmissionLeaseEvidence pending(Context context, UUID account) { + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + return tx( + context, + () -> { + var allocation = repository.allocate(account, UUID.randomUUID(), UUID.randomUUID()); + var evidence = evidence(allocation); + repository.beginPending(evidence); + return evidence; + }); + } + + private static AccountGameplayAdmissionLeaseEvidence evidence( + AccountGameplayAdmissionLeaseRepository.Allocation allocation) { + String account = allocation.accountId().toString(); + long now = Instant.now().toEpochMilli(); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", "test"); + carrier.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + carrier.put("requestId", allocation.requestId().toString()); + carrier.put("leaseId", allocation.leaseId().toString()); + carrier.put("leaseFence", Long.toString(allocation.leaseFence())); + carrier.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, OTHER); + scope.put("accountId", account); + scope.put("tenantId", TENANT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "1"); + carrier.put("bindingScope", scope); + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + Map.of(TENANT, "1"), + "privateRealmGrantVersions", + List.of())); + carrier.put("issuanceFence", "7"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + "1")); + carrier.put( + "outboxCheckpoints", + List.of( + "account/" + account, + "issuer/firemud-account-service", + "membership/" + account + "/" + TENANT, + "tenant/" + TENANT) + .stream() + .map( + suffix -> + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + "1")) + .toList()); + Map token = new LinkedHashMap<>(); + token.put("accountId", account); + for (String key : List.of("operationId", "issuanceRequestId", "tokenJti")) + token.put(key, OTHER); + token.put("tokenSHA256", "a".repeat(64)); + token.put("tokenProfile", "game-session-account-delegation"); + token.put("tokenGeneration", "1"); + token.put("issuanceFence", "7"); + token.put("tokenIdentityFence", "9"); + token.put("issuedAt", Long.toString(now / 1000 - 1)); + token.put("notBefore", Long.toString(now / 1000 - 1)); + token.put("expiresAt", Long.toString(now / 1000 + 300)); + carrier.put("tokenIdentityEvidence", token); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put("expiresAt", Long.toString(now + 15000)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private static UUID account(Context context) { + var authorities = new AccountAuthorityGenerationRepository(context.dsl()); + var sources = + new AccountAuthoritySourceEvidenceRepository( + context.dsl(), authorities, new AccountAuthorityOutboxRepository(context.dsl())); + return tx( + context, + () -> { + sources.initializeIssuerIfAbsent("firemud-account-service"); + var account = new Account(); + account.setUsername("lease-" + UUID.randomUUID()); + account.setEmail(UUID.randomUUID() + "@example.test"); + account.setPasswordHash("storage-fixture-only"); + account.setLoginAuthModes("PASSWORD"); + return new AccountRepository(context.dsl(), sources).save(account).getAccountUuid(); + }); + } + + private static Context context(String target) { + String schema = "admission_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = POSTGRES.dataSource(schema); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + var context = + new Context( + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES), + transaction, + dataSource, + schema); + migrate(context, target); + return context; + } + + private static void migrate(Context context, String target) { + var configuration = + Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration"); + if (target != null) configuration.target(target); + configuration.load().migrate(); + } + + private static Map flywayChecksums(Context context) { + Map checksums = new LinkedHashMap<>(); + for (Record row : + context + .dsl() + .fetch( + "SELECT version, checksum FROM flyway_schema_history " + + "WHERE version IS NOT NULL ORDER BY installed_rank")) { + checksums.put(row.get("version", String.class), row.get("checksum", Integer.class)); + } + return checksums; + } + + private static T tx(Context context, Supplier action) { + return context.transaction().execute(status -> action.get()); + } + + private record Context( + DSLContext dsl, + TransactionTemplate transaction, + DriverManagerDataSource dataSource, + String schema) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadPostgresIntegrationTest.java new file mode 100644 index 0000000000..f014ca494f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadPostgresIntegrationTest.java @@ -0,0 +1,484 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountIssuerSourceSnapshotReadOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountIssuerAuthoritySourceGrpcService; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotEvidence; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Physical PostgreSQL proof for current issuer reads, exact retry fences and writer concurrency. + */ +class AccountIssuerSourceSnapshotReadPostgresIntegrationTest { + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String NAMESPACE = "test"; + private static final String CALLER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String SCHEMA_PREFIX = "account_issuer_read"; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void configurePostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopOwnedContainer() { + POSTGRES.stop(); + } + + @Test + void genuineEnrollmentAdvancedEventAndWholeSnapshotRetryAreReadWithoutMutation() + throws Exception { + TestContext context = newTestContext(); + initializeCanonicalIssuer(context); + UUID operation = UUID.randomUUID(); + var baseline = withPeer(() -> context.owner().read(request(operation))); + + assertThat(baseline.evidence().issuerAuthGeneration()).isEqualTo("1"); + assertThat(baseline.evidence().sourceVersion()).isEqualTo("1"); + assertThat(baseline.evidence().lastCommittedOutboxSequence()).isEqualTo("0"); + assertThat(baseline.evidence().sourceEvent()).isEmpty(); + assertThat(baseline.evidence().callerWorkload()).isEqualTo(CALLER); + assertThat(context.sourceHead()).containsEntry("current_generation", 1L); + + var exactInitialRetry = + withPeer(() -> context.owner().read(request(operation, Optional.of(baseline.evidence())))); + assertThat(exactInitialRetry.evidence()).isEqualTo(baseline.evidence()); + + String mutationRequestId = "historical-issuer-change-" + UUID.randomUUID(); + context + .transaction() + .executeWithoutResult( + status -> + context + .sources() + .appendIssuerAuthorityChange(ISSUER, "SIGNER_COMPROMISE", mutationRequestId)); + + Map beforeStaleRetry = context.sourceHead(); + var advanced = withPeer(() -> context.owner().read(request(UUID.randomUUID()))); + assertThat(advanced.evidence().issuerAuthGeneration()).isEqualTo("2"); + assertThat(advanced.evidence().sourceVersion()).isEqualTo("2"); + assertThat(advanced.evidence().lastCommittedOutboxSequence()).isEqualTo("1"); + assertThat(advanced.evidence().sourceEvent()).isPresent(); + var event = + (AccountAuthoritySourceEventV1Codec.IssuerEvent) + AccountAuthoritySourceEventV1Codec.verify( + advanced.evidence().sourceEvent().orElseThrow()); + assertThat(event.eventId()).isEqualTo(mutationRequestId); + assertThat(event.requestId()).isEqualTo(mutationRequestId); + assertThat(event.eventId()) + .isNotEqualTo(advanced.evidence().reconciliationOperationId().toString()); + assertThat(event.issuerId()).isEqualTo(ISSUER); + assertThat(event.outboxStreamKey()).isEqualTo(advanced.evidence().outboxStreamKey()); + assertThat(event.outboxSequence()).isEqualTo(advanced.evidence().lastCommittedOutboxSequence()); + assertThat(event.issuerAuthGeneration()).isEqualTo(advanced.evidence().issuerAuthGeneration()); + assertThat(event.sourceVersion()).isEqualTo(advanced.evidence().sourceVersion()); + + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> + withPeer( + () -> context.owner().read(request(operation, Optional.of(baseline.evidence()))))); + assertThat(context.sourceHead()).isEqualTo(beforeStaleRetry); + + var exactAdvancedRetry = + withPeer( + () -> + context + .owner() + .read( + request( + advanced.evidence().reconciliationOperationId(), + Optional.of(advanced.evidence())))); + assertThat(exactAdvancedRetry.evidence()).isEqualTo(advanced.evidence()); + assertThat(context.sourceHead()).isEqualTo(beforeStaleRetry); + } + + @Test + void missingAndUnsupportedIssuerReadsDenyWithoutEnrollmentOrOutboxMutation() throws Exception { + TestContext context = newTestContext(); + Map before = context.allIssuerRows(); + + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> withPeer(() -> context.owner().read(request(UUID.randomUUID())))); + + // In-process adapter proof with a synthetic same-namespace peer; this does not exercise live + // mTLS. + var unsupportedObserver = new RecordingObserver(); + var adapter = new AccountIssuerAuthoritySourceGrpcService(context.owner()); + withPeer( + () -> { + adapter.readCurrentIssuerAuthoritySource( + request(UUID.randomUUID(), "unsupported-issuer", Optional.empty()), + unsupportedObserver); + return null; + }); + + assertThat(unsupportedObserver.error.getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(unsupportedObserver.error.getDescription()) + .isEqualTo("Malformed Account issuer source request"); + assertThat(unsupportedObserver.observedValue).isFalse(); + assertThat(unsupportedObserver.completed).isFalse(); + + assertThat(context.allIssuerRows()).isEqualTo(before); + assertThat(context.allIssuerRows()).containsEntry("generation_rows", 0L); + assertThat(context.allIssuerRows()).containsEntry("source_rows", 0L); + assertThat(context.allIssuerRows()).containsEntry("stream_rows", 0L); + assertThat(context.allIssuerRows()).containsEntry("event_rows", 0L); + } + + @Test + void serializableSnapshotWaitsForIssuerAdvanceAndExactRetryCannotSilentlyRefresh() + throws Exception { + TestContext context = newTestContext(); + initializeCanonicalIssuer(context); + UUID operation = UUID.randomUUID(); + var original = withPeer(() -> context.owner().read(request(operation))); + + CountDownLatch writerLocked = new CountDownLatch(1); + CountDownLatch writerAppended = new CountDownLatch(1); + CountDownLatch releaseWriter = new CountDownLatch(1); + CountDownLatch readerStarted = new CountDownLatch(1); + var writerPid = new java.util.concurrent.CompletableFuture(); + var readerPid = new java.util.concurrent.CompletableFuture(); + ExecutorService executor = Executors.newFixedThreadPool(2); + String mutationRequestId = "concurrent-issuer-change-" + UUID.randomUUID(); + Future writer = + executor.submit( + () -> + context + .transaction() + .executeWithoutResult( + status -> { + var writerBackendPidRow = + Objects.requireNonNull( + context.dsl().fetchOne("SELECT pg_backend_pid()"), + "Writer backend PID query returned no row"); + writerPid.complete( + Objects.requireNonNull( + writerBackendPidRow.get(0, Integer.class), + "Writer backend PID query returned NULL")); + var locked = + context + .dsl() + .fetchOne( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'ISSUER' AND issuer_id = ? FOR UPDATE", + ISSUER); + assertThat(locked).isNotNull(); + writerLocked.countDown(); + context + .sources() + .appendIssuerAuthorityChange( + ISSUER, "SIGNER_COMPROMISE", mutationRequestId); + writerAppended.countDown(); + await(releaseWriter, "Issuer writer was not released to commit"); + })); + Future reader = + executor.submit( + () -> { + await(writerAppended, "Issuer writer did not append the source event"); + readerStarted.countDown(); + context.sources().captureNextReadBackendPid(readerPid); + return withPeer( + () -> context.owner().read(request(operation, Optional.of(original.evidence())))); + }); + + try { + assertThat(writerLocked.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(writerAppended.await(30, TimeUnit.SECONDS)).isTrue(); + assertThat(readerStarted.await(30, TimeUnit.SECONDS)).isTrue(); + int exactWriterPid = writerPid.get(10, TimeUnit.SECONDS); + int exactReaderPid = readerPid.get(10, TimeUnit.SECONDS); + assertThat(exactReaderPid).isNotEqualTo(exactWriterPid); + awaitBlockedReader(context.dsl(), exactReaderPid, exactWriterPid); + releaseWriter.countDown(); + writer.get(30, TimeUnit.SECONDS); + + try { + reader.get(30, TimeUnit.SECONDS); + throw new AssertionError( + "The exact old source snapshot must conflict after issuer advance"); + } catch (ExecutionException conflicted) { + Status.Code code = Status.fromThrowable(conflicted.getCause()).getCode(); + assertThat(code).isIn(Status.Code.FAILED_PRECONDITION, Status.Code.UNAVAILABLE); + } + + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> + withPeer( + () -> + context.owner().read(request(operation, Optional.of(original.evidence()))))); + + var current = withPeer(() -> context.owner().read(request(UUID.randomUUID()))).evidence(); + assertThat(current.issuerAuthGeneration()).isEqualTo("2"); + assertThat(current.sourceVersion()).isEqualTo("2"); + assertThat(current.lastCommittedOutboxSequence()).isEqualTo("1"); + var event = + (AccountAuthoritySourceEventV1Codec.IssuerEvent) + AccountAuthoritySourceEventV1Codec.verify(current.sourceEvent().orElseThrow()); + assertThat(event.eventId()).isEqualTo(mutationRequestId); + assertThat(event.requestId()).isEqualTo(mutationRequestId); + assertThat(event.issuerAuthGeneration()).isEqualTo(current.issuerAuthGeneration()); + assertThat(event.sourceVersion()).isEqualTo(current.sourceVersion()); + assertThat(event.outboxSequence()).isEqualTo(current.lastCommittedOutboxSequence()); + assertThat(context.sourceHead()).containsEntry("current_generation", 2L); + assertThat(context.sourceHead()).containsEntry("current_source_version", 2L); + assertThat(context.sourceHead()).containsEntry("last_outbox_sequence", 1L); + } finally { + releaseWriter.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(30, TimeUnit.SECONDS)) { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static void initializeCanonicalIssuer(TestContext context) { + context + .transaction() + .executeWithoutResult(status -> context.sources().initializeIssuerIfAbsent(ISSUER)); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var transactionManager = new DataSourceTransactionManager(dataSource); + var transaction = new TransactionTemplate(transactionManager); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new BackendPidCapturingSourceRepository(dsl, generations, outbox); + var owner = new AccountIssuerSourceSnapshotReadOwner(sources, transactionManager, NAMESPACE); + return new TestContext(dsl, transaction, sources, owner); + } + + private static void awaitBlockedReader(DSLContext dsl, int readerPid, int writerPid) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30); + while (System.nanoTime() < deadline) { + var blockedReader = + dsl.fetchOne( + "SELECT pid FROM pg_stat_activity " + + "WHERE pid = ? AND pid <> pg_backend_pid() " + + "AND datname = current_database() AND wait_event_type = 'Lock' " + + "AND ? = ANY(pg_blocking_pids(pid)) LIMIT 1", + readerPid, + writerPid); + if (blockedReader != null) return; + Thread.sleep(25L); + } + throw new AssertionError( + "The owned issuer source reader did not wait for the exact concurrent writer"); + } + + private static void await(CountDownLatch latch, String failureMessage) { + try { + if (!latch.await(30, TimeUnit.SECONDS)) throw new IllegalStateException(failureMessage); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(failureMessage, interrupted); + } + } + + private static ReadCurrentIssuerAuthoritySourceRequest request(UUID operation) { + return request(operation, ISSUER, Optional.empty()); + } + + private static ReadCurrentIssuerAuthoritySourceRequest request( + UUID operation, Optional expected) { + return request(operation, ISSUER, expected); + } + + private static ReadCurrentIssuerAuthoritySourceRequest request( + UUID operation, String issuer, Optional expected) { + if (!ISSUER.equals(issuer)) { + return ReadCurrentIssuerAuthoritySourceRequest.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .setTargetNamespace(NAMESPACE) + .setReconciliationOperationId(operation.toString()) + .setIssuerId(issuer) + .build(); + } + var typed = + new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, issuer, expected); + return AccountIssuerSourceSnapshotGrpcCodec.toRequest(typed, NAMESPACE, CALLER); + } + + private static T withPeer(java.util.concurrent.Callable call) throws Exception { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(CALLER).orElseThrow(); + return Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).call(call); + } + + private static void assertStatus( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static final class RecordingObserver + implements StreamObserver { + private Status error; + private boolean observedValue; + private boolean completed; + + @Override + public void onNext(AccountIssuerAuthoritySourceSnapshot ignored) { + observedValue = true; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private record TestContext( + DSLContext dsl, + TransactionTemplate transaction, + BackendPidCapturingSourceRepository sources, + AccountIssuerSourceSnapshotReadOwner owner) { + private Map sourceHead() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT g.generation AS authority_generation, " + + "g.source_version AS authority_source_version, " + + "s.current_generation, s.current_source_version, s.last_outbox_sequence, " + + "stream.last_sequence AS stream_last_sequence, " + + "(SELECT count(*) FROM account_authority_outbox_events event " + + "WHERE event.outbox_stream_key = stream.outbox_stream_key) AS retained_events " + + "FROM account_authority_generations g " + + "JOIN account_authority_source_records s " + + "ON s.outbox_stream_key = 'account:auth-authority:v1:issuer/' || g.issuer_id " + + "JOIN account_authority_outbox_streams stream " + + "ON stream.outbox_stream_key = s.outbox_stream_key " + + "WHERE g.scope_kind = 'ISSUER' AND g.issuer_id = ?", + ISSUER), + "Issuer source head query returned no row") + .intoMap(); + } + + private Map allIssuerRows() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT " + + "(SELECT count(*) FROM account_authority_generations WHERE scope_kind = 'ISSUER') AS generation_rows, " + + "(SELECT count(*) FROM account_authority_source_records WHERE scope_kind = 'ISSUER') AS source_rows, " + + "(SELECT count(*) FROM account_authority_outbox_streams WHERE outbox_stream_key LIKE 'account:auth-authority:v1:issuer/%') AS stream_rows, " + + "(SELECT count(*) FROM account_authority_outbox_events WHERE outbox_stream_key LIKE 'account:auth-authority:v1:issuer/%') AS event_rows"), + "Issuer source row-count query returned no row") + .intoMap(); + } + } + + /** Captures only the next owner's real PostgreSQL backend before delegating the actual read. */ + private static final class BackendPidCapturingSourceRepository + extends AccountAuthoritySourceEvidenceRepository { + private final DSLContext dsl; + private final AtomicReference> nextReadPid = + new AtomicReference<>(); + + private BackendPidCapturingSourceRepository( + DSLContext dsl, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox) { + super(dsl, generations, outbox); + this.dsl = dsl; + } + + private void captureNextReadBackendPid( + java.util.concurrent.CompletableFuture capturedPid) { + if (!nextReadPid.compareAndSet(null, capturedPid)) { + throw new IllegalStateException("A PostgreSQL owner-read PID capture is already armed"); + } + } + + @Override + public CanonicalIssuerSourceSnapshot readCurrentCanonicalIssuerSource(String exactIssuerId) { + var capture = nextReadPid.getAndSet(null); + if (capture != null) { + try { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_SERIALIZABLE) + .equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "The captured Account owner read must use its writable SERIALIZABLE transaction"); + } + var readerBackendPidRow = + Objects.requireNonNull( + dsl.fetchOne("SELECT pg_backend_pid()"), + "Reader backend PID query returned no row"); + int backendPid = + Objects.requireNonNull( + readerBackendPidRow.get(0, Integer.class), + "Reader backend PID query returned NULL"); + capture.complete(backendPid); + } catch (RuntimeException failure) { + capture.completeExceptionally(failure); + throw failure; + } + } + return super.readCurrentCanonicalIssuerSource(exactIssuerId); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java index 0aaedf7407..7f6ceb2993 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java @@ -4,7 +4,7 @@ import java.net.URI; import java.util.Properties; -import net.firedevops.firemud.test.TestContainerImages; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.PostgreSQLContainer; @@ -15,21 +15,32 @@ public final class AccountPostgresIntegrationFixture { private final PostgreSQLContainer container; private final String externalJdbcUrl; + private final boolean requireDurablePrimary; private boolean started; public AccountPostgresIntegrationFixture() { + this(false); + } + + public AccountPostgresIntegrationFixture(boolean requireDurablePrimary) { + this.requireDurablePrimary = requireDurablePrimary; String configuredUrl = System.getenv(JDBC_URL_ENV); if (configuredUrl != null && !configuredUrl.isBlank()) { externalJdbcUrl = validateLoopbackJdbcUrl(configuredUrl); container = null; } else { externalJdbcUrl = null; - container = new PostgreSQLContainer<>(TestContainerImages.postgres()); + container = + new PostgreSQLContainer<>("postgres:16-alpine") + .withCommand(postgresCommand(requireDurablePrimary)); } } public void start() { if (container == null) { + if (requireDurablePrimary) { + verifyDurablePrimary(); + } return; } assumeTrue( @@ -37,6 +48,14 @@ public void start() { "Docker is unavailable; set " + JDBC_URL_ENV + " to an isolated loopback PostgreSQL URL"); container.start(); started = true; + if (requireDurablePrimary) { + try { + verifyDurablePrimary(); + } catch (RuntimeException unsuitable) { + stop(); + throw unsuitable; + } + } } public void stop() { @@ -91,6 +110,48 @@ public DriverManagerDataSource dataSource(String schema) { return dataSource; } + /** Reads and validates the live PostgreSQL settings required by durable commit confirmation. */ + public DurablePrimarySettings verifyDurablePrimary() { + DurablePrimarySettings settings = + new JdbcTemplate(dataSource()) + .queryForObject( + "SELECT pg_is_in_recovery(), current_setting('fsync'), " + + "current_setting('synchronous_commit')", + (result, rowNumber) -> + new DurablePrimarySettings( + result.getBoolean(1), result.getString(2), result.getString(3))); + if (settings == null) { + throw new IllegalStateException("Durable PostgreSQL primary settings are unavailable"); + } + validateDurablePrimarySettings( + settings.inRecovery(), settings.fsync(), settings.synchronousCommit()); + return settings; + } + + static String[] postgresCommand(boolean requireDurablePrimary) { + if (requireDurablePrimary) { + return new String[] {"postgres", "-c", "fsync=on", "-c", "synchronous_commit=on"}; + } + return new String[] {"postgres", "-c", "fsync=off"}; + } + + static void validateDurablePrimarySettings( + boolean inRecovery, String fsync, String synchronousCommit) { + if (inRecovery || !"on".equals(fsync) || !"on".equals(synchronousCommit)) { + throw new IllegalStateException( + "Durable PostgreSQL primary required (pg_is_in_recovery=false, fsync=on, " + + "synchronous_commit=on); observed pg_is_in_recovery=" + + inRecovery + + ", fsync=" + + fsync + + ", synchronous_commit=" + + synchronousCommit); + } + } + + public record DurablePrimarySettings( + boolean inRecovery, String fsync, String synchronousCommit) {} + static String validateLoopbackJdbcUrl(String jdbcUrl) { final URI uri; try { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java new file mode 100644 index 0000000000..7cc0220fb2 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java @@ -0,0 +1,182 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountLoginAuthModes; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.common.EmailCanonicalization; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Seeds the canonical pre-V88 repository-created Account image in historical migration fixtures. + * + *

This reproduces the V40 sequence-zero Account source setup, including the immutable V74.1 + * empty-role source inserted by its Account trigger. It deliberately does not create V88 + * restriction-birth evidence, enroll a retained Account, or establish admission authority. + */ +public final class PreRestrictionBirthAccountFixture { + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + private static final String ACCOUNT_STREAM_PREFIX = "account:auth-authority:v1:account/"; + + private PreRestrictionBirthAccountFixture() {} + + /** + * Inserts an Account and its pre-V88 fresh-source rows in one test transaction. + * + *

The target schema must already include V40 and V74.1. Use only when a test intentionally + * starts from a historical schema before V88 and then verifies forward migration preservation. + */ + public static Account create( + DSLContext dsl, String username, String email, String passwordHash, String loginAuthModes) { + Objects.requireNonNull(dsl, "DSLContext is required"); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Historical Account setup requires a writable transaction"); + } + Record restrictionBirthSchemaReadback = + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM information_schema.tables " + + "WHERE table_schema = current_schema() AND table_name = ?)", + "account_platform_restriction_births"); + if (restrictionBirthSchemaReadback == null) { + throw new IllegalStateException("Could not read restriction-birth schema guard"); + } + Boolean restrictionBirthSchemaInstalled = + Objects.requireNonNull( + restrictionBirthSchemaReadback.get(0, Boolean.class), + "Restriction-birth schema guard readback is required"); + if (Boolean.TRUE.equals(restrictionBirthSchemaInstalled)) { + throw new IllegalStateException( + "Pre-V88 Account fixture cannot run after restriction-birth schema installation"); + } + Objects.requireNonNull(username, "username is required"); + Objects.requireNonNull(passwordHash, "password hash is required"); + + String canonicalEmail = EmailCanonicalization.normalize(email); + String normalizedLoginAuthModes = AccountLoginAuthModes.normalize(loginAuthModes); + Account account = new Account(); + account.setUsername(username); + account.setEmail(canonicalEmail); + account.setPasswordHash(passwordHash); + account.setLoginAuthModes(normalizedLoginAuthModes); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(dsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); + AccountAuthoritySourceEvidenceRepository sources = + new PreV88SourceEvidence(dsl, generations, outbox); + sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + return new AccountRepository(dsl, sources).save(account); + } + + private static final class PreV88SourceEvidence extends AccountAuthoritySourceEvidenceRepository { + private final DSLContext dsl; + private final AccountAuthorityGenerationRepository generations; + + private PreV88SourceEvidence( + DSLContext dsl, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox) { + super(dsl, generations, outbox); + this.dsl = dsl; + this.generations = generations; + } + + @Override + @Transactional(propagation = Propagation.MANDATORY) + public void initializeFreshAccount(AccountRepository.FreshAccountInsert proof) { + Objects.requireNonNull(proof, "fresh Account repository insert proof is required"); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Historical Account setup requires a writable transaction"); + } + + Record account = + dsl.fetchOne( + "SELECT id, account_uuid, account_uuid_provenance, " + + "account_uuid_source_numeric_id, account_repository_insert_transaction_id, " + + "lifecycle_state, txid_current() AS current_xid " + + "FROM accounts WHERE id = ? FOR UPDATE", + proof.accountId()); + if (account == null + || !Objects.equals(account.get("id", Long.class), proof.accountId()) + || !Objects.equals(account.get("account_uuid", UUID.class), proof.accountUuid()) + || !Objects.equals( + account.get("account_uuid_provenance", String.class), + proof.accountUuidProvenance().name()) + || !Objects.equals( + account.get("account_uuid_source_numeric_id", Long.class), proof.accountId()) + || !Objects.equals( + account.get("account_repository_insert_transaction_id", Long.class), + account.get("current_xid", Long.class)) + || !"active".equals(account.get("lifecycle_state", String.class))) { + throw new IllegalStateException( + "Historical source baseline requires the exact repository-created Account row"); + } + + long insertTransactionId = + positive( + account.get("account_repository_insert_transaction_id", Long.class), + "Account insert transaction ID"); + ScopeState state = + Objects.requireNonNull( + generations.initializeAccountForFreshRepositoryInsert(proof), + "Account generation baseline is required"); + long generation = positive(state.generation(), "Account generation"); + long sourceVersion = positive(state.sourceVersion(), "Account source version"); + IssuanceFence fence = + Objects.requireNonNull( + state.issuanceFence(), "Account issuance-fence baseline is required"); + positive(fence.value(), "Account issuance fence"); + positive(fence.sourceVersion(), "Account issuance-fence source version"); + String streamKey = ACCOUNT_STREAM_PREFIX + proof.accountUuid(); + requireOne( + dsl.execute( + "INSERT INTO account_authority_outbox_streams (outbox_stream_key, last_sequence) " + + "VALUES (?, 0)", + streamKey), + "Account authority outbox stream"); + requireOne( + dsl.execute( + "INSERT INTO account_authority_source_records " + + "(outbox_stream_key, scope_kind, issuer_id, account_uuid, " + + "baseline_generation, baseline_source_version, baseline_issuance_fence, " + + "initialization_provenance, account_source_numeric_id, account_uuid_provenance, " + + "account_repository_insert_transaction_id, current_generation, " + + "current_source_version, current_issuance_fence, " + + "current_issuance_fence_source_version, last_outbox_sequence) " + + "VALUES (?, 'ACCOUNT', NULL, ?, 1, 1, ?, 'ACCOUNT_REPOSITORY_INSERT', ?, ?, " + + "?, ?, ?, ?, ?, 0)", + streamKey, + proof.accountUuid(), + fence.value(), + proof.accountId(), + proof.accountUuidProvenance().name(), + insertTransactionId, + generation, + sourceVersion, + fence.value(), + fence.sourceVersion()), + "Account sequence-zero source record"); + readCurrentIssuerAccountSources(ACCOUNT_ISSUER, proof.accountUuid()); + } + } + + private static long positive(Long value, String label) { + if (value == null || value <= 0L) { + throw new IllegalStateException(label + " must be positive"); + } + return value; + } + + private static void requireOne(int affectedRows, String label) { + if (affectedRows != 1) { + throw new IllegalStateException(label + " insert did not affect exactly one row"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java new file mode 100644 index 0000000000..c5c6195c2a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java @@ -0,0 +1,817 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.OffsetDateTime; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftTerminalReconciliationService; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Synthetic owner clients prove recovery composition, not peer authentication or SQL atomicity. */ +class AccountDraftTerminalReconciliationServiceTest { + private static final String NAMESPACE = "firemud-test"; + + @Test + void unknownFromBothOwnersStaysPendingAndRemoteReadsRunOutsideTransactions() { + Fixture f = fixture(Ordering.COMMIT_ORDER); + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.originalAccountBinding()) + .containsExactly(f.binding().canonicalBytes()); + return new GameDesignDraftTerminalReadEvidence(request, Optional.empty()); + }); + when(f.worldClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.originalAccountBinding()) + .containsExactly(f.binding().canonicalBytes()); + return new WorldDraftTerminalReadEvidence(request, Optional.empty()); + }); + + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); + assertThat(f.manager().commits).isEqualTo(2); + assertThat(f.stored()).isEmpty(); + verify(f.repository(), never()).recordOwnerReadback(any(), any()); + } + + @Test + void storedWorldOutcomeNeverSkipsMissingGameDesignAndRemainsImmutable() { + Fixture f = fixture(Ordering.COMMIT_ORDER); + OwnerReadback world = + readback(f.binding(), Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {7}); + f.stored().put(Owner.WORLD, world); + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {8}))); + }); + + assertThat(f.service().reconcile(f.binding().operationId())) + .contains(Settlement.FAILED_NONPUBLICATION); + verify(f.gameDesignClient()).read(any()); + verifyNoInteractions(f.worldClient()); + assertThat(f.stored().get(Owner.WORLD).canonicalBytes()) + .containsExactly(world.canonicalBytes()); + assertThat(f.stored().get(Owner.GAME_DESIGN).owner()).isEqualTo(Owner.GAME_DESIGN); + } + + @Test + void storedGameDesignOutcomeReadsOnlyMissingWorldAndRevokeOrderNeedsBothAborts() { + Fixture f = fixture(Ordering.REVOKE_ORDER); + OwnerReadback gameDesign = + readback(f.binding(), Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {9}); + f.stored().put(Owner.GAME_DESIGN, gameDesign); + when(f.worldClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new WorldDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {10}))); + }); + + assertThat(f.service().reconcile(f.binding().operationId())) + .contains(Settlement.FAILED_NONPUBLICATION); + verify(f.worldClient()).read(any()); + verifyNoInteractions(f.gameDesignClient()); + assertThat(f.stored().get(Owner.GAME_DESIGN).canonicalBytes()) + .containsExactly(gameDesign.canonicalBytes()); + } + + @Test + void storedGameDesignCorruptionDeniesEvenWhenWorldResultAlreadyExists() { + Fixture f = fixture(Ordering.COMMIT_ORDER); + f.stored() + .put( + Owner.WORLD, + readback(f.binding(), Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {24})); + when(f.repository().readOwnerResult(any(), eq(Owner.GAME_DESIGN))) + .thenThrow(new IllegalArgumentException("synthetic strict persisted-readback rejection")); + + assertThatThrownBy(() -> f.service().reconcile(f.binding().operationId())) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(f.gameDesignClient(), f.worldClient()); + verify(f.repository(), never()).recordOwnerReadback(any(), any()); + } + + @Test + void changedRequestWrongOwnerAndWrongBindingAreRejected() { + for (int mismatch = 0; mismatch < 3; mismatch++) { + Fixture f = fixture(Ordering.COMMIT_ORDER); + int selectedMismatch = mismatch; + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + var expected = + (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + var response = mock(GameDesignDraftTerminalReadEvidence.class); + var returnedRequest = + selectedMismatch == 0 + ? new GameDesignDraftTerminalReadEvidence.Request( + expected.schemaVersion(), + "other-namespace", + expected.readRequestId(), + expected.originalAccountBinding()) + : expected; + var wrongBinding = binding(); + var resultBinding = selectedMismatch == 2 ? wrongBinding : f.binding(); + OwnerReadback value = + readback( + resultBinding, + selectedMismatch == 1 ? Owner.WORLD : Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {11}); + when(response.request()).thenReturn(returnedRequest); + when(response.ownerReadback()).thenReturn(Optional.of(value)); + return response; + }); + + assertThatThrownBy(() -> f.service().reconcile(f.binding().operationId())) + .isInstanceOf(IllegalArgumentException.class); + verify(f.repository(), never()).recordOwnerReadback(any(), any()); + verifyNoInteractions(f.worldClient()); + } + } + + @Test + void orderingDriftDuringOwnerReadsPreventsAnyReadbackWrite() { + Fixture f = fixture(Ordering.COMMIT_ORDER); + when(f.repository().read(any())) + .thenAnswer( + new org.mockito.stubbing.Answer<>() { + private int reads; + + @Override + public DraftAuthorizationFenceRepository.FenceSnapshot answer( + org.mockito.invocation.InvocationOnMock invocation) { + Ordering current = reads++ == 0 ? Ordering.COMMIT_ORDER : Ordering.REVOKE_ORDER; + return fenceSnapshot(f.binding(), current); + } + }); + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {12}))); + }); + when(f.worldClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new WorldDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {13}))); + }); + + assertThatThrownBy(() -> f.service().reconcile(f.binding().operationId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Original Draft ordering changed during recovery"); + assertThat(f.stored()).isEmpty(); + assertThat(f.manager().rollbacks).isEqualTo(1); + } + + @Test + void disappearedOrChangedOriginalDuringOwnerReadsIsDeniedAndRollsBack() { + for (boolean absent : List.of(false, true)) { + Fixture f = fixture(Ordering.COMMIT_ORDER); + DraftAuthorizationFenceBinding original = f.binding(); + DraftAuthorizationFenceBinding changed = + new DraftAuthorizationFenceBinding( + original.operationId(), + original.requestId(), + original.commitId(), + original.fenceId(), + original.actorAccountId(), + original.tenantId(), + original.versionId(), + original.baseCommitId(), + "1", + original.gameDesignBinding(), + original.normalizedInput(), + original.inputDigest(), + original.sources()); + assertThat(changed.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = + (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + doAnswer( + originalRead -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat( + TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + return absent ? Optional.empty() : Optional.of(changed); + }) + .when(f.repository()) + .readOriginalBinding(any()); + return new GameDesignDraftTerminalReadEvidence(request, Optional.empty()); + }); + when(f.worldClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + return new WorldDraftTerminalReadEvidence( + invocation.getArgument(0), Optional.empty()); + }); + + assertThatThrownBy(() -> f.service().reconcile(original.operationId())) + .isInstanceOf(IllegalStateException.class); + verify(f.repository(), never()).recordOwnerReadback(any(), any()); + assertThat(f.manager().rollbacks).isEqualTo(1); + } + } + + @Test + void lostResponseDoesNotInventAbortAndExactRetrySettlesFromBothImmutableResults() { + Fixture f = fixture(Ordering.COMMIT_ORDER); + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {14}))); + }); + when(f.worldClient().read(any())) + .thenThrow(new IllegalStateException("synthetic lost response")); + assertThatThrownBy(() -> f.service().reconcile(f.binding().operationId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("synthetic lost response"); + assertThat(f.stored()).isEmpty(); + + doAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new WorldDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {15}))); + }) + .when(f.worldClient()) + .read(any()); + assertThat(f.service().reconcile(f.binding().operationId())) + .contains(Settlement.FAILED_NONPUBLICATION); + assertThat(f.stored()).containsKeys(Owner.GAME_DESIGN, Owner.WORLD); + assertThat(f.manager().commits).isEqualTo(3); + } + + @Test + void unknownOwnerResponsesObserveConcurrentGenuineSettlementWithoutInventingResults() { + Fixture f = fixture(Ordering.COMMIT_ORDER); + OwnerReadback gameDesignAbort = + readback(f.binding(), Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {25}); + OwnerReadback worldAbort = + readback(f.binding(), Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {26}); + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + f.stored().put(Owner.GAME_DESIGN, gameDesignAbort); + f.stored().put(Owner.WORLD, worldAbort); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence(request, Optional.empty()); + }); + when(f.worldClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new WorldDraftTerminalReadEvidence(request, Optional.empty()); + }); + + assertThat(f.service().reconcile(f.binding().operationId())) + .contains(Settlement.FAILED_NONPUBLICATION); + verify(f.repository(), never()).recordOwnerReadback(any(), any()); + assertThat(f.stored().get(Owner.GAME_DESIGN).canonicalBytes()) + .containsExactly(gameDesignAbort.canonicalBytes()); + assertThat(f.stored().get(Owner.WORLD).canonicalBytes()) + .containsExactly(worldAbort.canonicalBytes()); + } + + @Test + void mixedCommitOrderPreservesOriginalWorldCommitAndTerminalRetry() { + Fixture f = fixture(Ordering.COMMIT_ORDER); + OwnerReadback originalWorld = + readback(f.binding(), Owner.WORLD, Outcome.COMMITTED, new byte[] {16}); + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {17}))); + }); + when(f.worldClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return worldEvidence(request, originalWorld); + }); + + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); + assertThat(f.stored().get(Owner.WORLD).canonicalBytes()) + .containsExactly(originalWorld.canonicalBytes()); + byte[] originalGameDesignBytes = f.stored().get(Owner.GAME_DESIGN).canonicalBytes(); + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); + assertThat(f.stored().get(Owner.WORLD).canonicalBytes()) + .containsExactly(originalWorld.canonicalBytes()); + assertThat(f.stored().get(Owner.GAME_DESIGN).canonicalBytes()) + .containsExactly(originalGameDesignBytes); + verify(f.gameDesignClient()).read(any()); + verify(f.worldClient()).read(any()); + } + + @Test + void bothCommitOrderCommitsSettleAndRevokeOrderNeverAcceptsACommit() { + Fixture committed = fixture(Ordering.COMMIT_ORDER); + when(committed.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(committed); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + committed.binding(), + Owner.GAME_DESIGN, + Outcome.COMMITTED, + new byte[] {20}))); + }); + when(committed.worldClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(committed); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return worldEvidence( + request, + readback(committed.binding(), Owner.WORLD, Outcome.COMMITTED, new byte[] {21})); + }); + assertThat(committed.service().reconcile(committed.binding().operationId())) + .contains(Settlement.COMMITTED); + + Fixture revoked = fixture(Ordering.REVOKE_ORDER); + revoked + .stored() + .put( + Owner.GAME_DESIGN, + readback(revoked.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {22})); + when(revoked.worldClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(revoked); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new WorldDraftTerminalReadEvidence( + request, + Optional.of( + readback( + revoked.binding(), + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {23}))); + }); + assertThat(revoked.service().reconcile(revoked.binding().operationId())) + .contains(Settlement.PENDING); + assertThat(revoked.stored().get(Owner.GAME_DESIGN).outcome()).isEqualTo(Outcome.COMMITTED); + } + + @Test + void absentReservedTerminalAndAmbientCasesNeverCallOwners() { + Fixture missing = fixture(Ordering.COMMIT_ORDER); + when(missing.repository().readOriginalBinding(any())).thenReturn(Optional.empty()); + assertThat(missing.service().reconcile(missing.binding().operationId())).isEmpty(); + verifyNoInteractions(missing.gameDesignClient(), missing.worldClient()); + + Fixture reserved = fixture(Ordering.RESERVED); + assertThat(reserved.service().reconcile(reserved.binding().operationId())) + .contains(Settlement.PENDING); + verifyNoInteractions(reserved.gameDesignClient(), reserved.worldClient()); + + Fixture terminal = fixture(Ordering.COMMIT_ORDER); + terminal + .stored() + .put( + Owner.GAME_DESIGN, + readback(terminal.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {18})); + terminal + .stored() + .put( + Owner.WORLD, + readback(terminal.binding(), Owner.WORLD, Outcome.COMMITTED, new byte[] {19})); + assertThat(terminal.service().reconcile(terminal.binding().operationId())) + .contains(Settlement.COMMITTED); + verifyNoInteractions(terminal.gameDesignClient(), terminal.worldClient()); + + Fixture ambient = fixture(Ordering.COMMIT_ORDER); + var ambientTransaction = new TransactionTemplate(ambient.manager()); + ambientTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ambientTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ambientTransaction.execute( + status -> { + assertThatThrownBy(() -> ambient.service().reconcile(ambient.binding().operationId())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions( + ambient.repository(), ambient.gameDesignClient(), ambient.worldClient()); + return null; + }); + } + + @Test + void v2WithoutWorldNeverReadsLooksUpOrRetainsWorldEvidence() { + Fixture f = + fixture( + Ordering.COMMIT_ORDER, + requiredBinding(List.of(DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE))); + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {31}))); + }); + + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.COMMITTED); + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.COMMITTED); + verifyNoInteractions(f.worldClient()); + verify(f.repository(), never()).readOwnerResult(any(), eq(Owner.WORLD)); + verify(f.repository()).recordOwnerReadback(eq(f.binding()), any()); + assertThat(f.stored()).containsOnlyKeys(Owner.GAME_DESIGN); + verify(f.gameDesignClient()).read(any()); + } + + @Test + void v2WorldAndGameDesignResultsCannotSettleMissingIndependentEntity() { + Fixture f = + fixture( + Ordering.COMMIT_ORDER, + requiredBinding( + List.of( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitBinding.Owner.ENTITY_MANAGEMENT))); + when(f.gameDesignClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {32}))); + }); + when(f.worldClient().read(any())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return worldEvidence( + request, readback(f.binding(), Owner.WORLD, Outcome.COMMITTED, new byte[] {33})); + }); + + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); + byte[] originalWorld = f.stored().get(Owner.WORLD).canonicalBytes(); + byte[] originalGameDesign = f.stored().get(Owner.GAME_DESIGN).canonicalBytes(); + assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); + assertThat(f.stored()).containsOnlyKeys(Owner.GAME_DESIGN, Owner.WORLD); + assertThat(f.stored().get(Owner.WORLD).canonicalBytes()).containsExactly(originalWorld); + assertThat(f.stored().get(Owner.GAME_DESIGN).canonicalBytes()) + .containsExactly(originalGameDesign); + verify(f.gameDesignClient()).read(any()); + verify(f.worldClient()).read(any()); + verify(f.repository(), never()).readOwnerResult(any(), eq(Owner.ENTITY)); + } + + private static DraftAuthorizationFenceBinding requiredBinding( + List owners) { + var original = binding(); + var prior = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), java.nio.charset.StandardCharsets.UTF_8), + original.inputDigest()); + var revisions = + java.util.stream.IntStream.range(0, owners.size()) + .mapToObj( + index -> + new DraftCommitBinding.RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + owners.get(index), + "payload-" + index)) + .toList(); + var affected = + owners.stream() + .map( + owner -> + new DraftCommitBinding.AffectedUnit( + owner, "aggregate", owner.name(), "aggregate", owner.name(), "0")) + .toList(); + var complete = + DraftCommitBinding.create( + prior.target(), + prior.requestId(), + prior.commitId(), + prior.baseCommitId(), + revisions, + affected); + return new DraftAuthorizationFenceBinding( + original.operationId(), + original.requestId(), + original.commitId(), + original.fenceId(), + original.actorAccountId(), + original.tenantId(), + original.versionId(), + original.baseCommitId(), + original.expectedDraftEpoch(), + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + original.sources()) + .withRequiredOwners(); + } + + private static Fixture fixture(Ordering ordering) { + return fixture(ordering, binding()); + } + + private static Fixture fixture(Ordering ordering, DraftAuthorizationFenceBinding binding) { + DraftAuthorizationFenceRepository repository = mock(DraftAuthorizationFenceRepository.class); + GameDesignDraftTerminalReadClient gameDesignClient = + mock(GameDesignDraftTerminalReadClient.class); + WorldDraftTerminalReadClient worldClient = mock(WorldDraftTerminalReadClient.class); + TestTransactionManager manager = new TestTransactionManager(); + Map stored = new EnumMap<>(Owner.class); + when(repository.readOriginalBinding(any())).thenReturn(Optional.of(binding)); + when(repository.read(any())).thenAnswer(invocation -> fenceSnapshot(binding, ordering)); + when(repository.readOwnerResult(any(), any())) + .thenAnswer( + invocation -> { + Owner owner = invocation.getArgument(1); + OwnerReadback value = stored.get(owner); + return value == null + ? Optional.empty() + : Optional.of( + new DraftAuthorizationFenceRepository.OwnerResultSnapshot( + value.outcome(), value.canonicalBytes(), OffsetDateTime.now())); + }); + when(repository.readSettlement(any())) + .thenAnswer( + invocation -> { + if (ordering == Ordering.RESERVED + || !stored.keySet().equals(java.util.Set.copyOf(binding.requiredOwners()))) { + return Settlement.PENDING; + } + if (ordering == Ordering.COMMIT_ORDER + && stored.values().stream() + .allMatch(value -> value.outcome() == Outcome.COMMITTED)) { + return Settlement.COMMITTED; + } + return stored.values().stream() + .allMatch(value -> value.outcome() == Outcome.DEFINITIVELY_ABORTED) + ? Settlement.FAILED_NONPUBLICATION + : Settlement.PENDING; + }); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + OwnerReadback value = invocation.getArgument(1); + OwnerReadback prior = stored.putIfAbsent(value.owner(), value); + if (prior != null + && !java.util.Arrays.equals(prior.canonicalBytes(), value.canonicalBytes())) { + throw new IllegalArgumentException("Changed owner terminal evidence"); + } + return null; + }) + .when(repository) + .recordOwnerReadback(any(), any()); + return new Fixture( + repository, + gameDesignClient, + worldClient, + manager, + binding, + stored, + new AccountDraftTerminalReconciliationService( + repository, manager, gameDesignClient, worldClient, NAMESPACE)); + } + + private static DraftAuthorizationFenceRepository.FenceSnapshot fenceSnapshot( + DraftAuthorizationFenceBinding binding, Ordering ordering) { + return new DraftAuthorizationFenceRepository.FenceSnapshot( + ordering, + binding.canonicalBytes(), + OffsetDateTime.parse("2026-10-06T00:00:00Z"), + ordering == Ordering.RESERVED ? null : OffsetDateTime.parse("2026-10-06T00:00:01Z")); + } + + private static void assertOutsideTransaction(Fixture f) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(f.manager().commits).isGreaterThanOrEqualTo(1); + } + + private static OwnerReadback readback( + DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome, byte[] result) { + return new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + result); + } + + private static WorldDraftTerminalReadEvidence worldEvidence( + WorldDraftTerminalReadEvidence.Request request, OwnerReadback readback) { + if (readback.outcome() != Outcome.COMMITTED) { + return new WorldDraftTerminalReadEvidence(request, Optional.of(readback)); + } + WorldDraftTerminalReadEvidence response = mock(WorldDraftTerminalReadEvidence.class); + when(response.request()).thenReturn(request); + when(response.ownerReadback()).thenReturn(Optional.of(readback)); + return response; + } + + private static DraftAuthorizationFenceBinding binding() { + UUID account = UUID.randomUUID(); + var gameDesign = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "tenant-key", + 2, + "tenant-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "payload")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + gameDesign.requestId(), + gameDesign.commitId(), + UUID.randomUUID(), + account, + gameDesign.target().canonicalTenantId(), + gameDesign.target().canonicalVersionId(), + "base", + "0", + gameDesign.canonicalBytes(), + gameDesign.canonicalBytes(), + gameDesign.digest(), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, account.toString(), "1", "1", "stream", "0", new byte[] {1}))); + } + + private record Fixture( + DraftAuthorizationFenceRepository repository, + GameDesignDraftTerminalReadClient gameDesignClient, + WorldDraftTerminalReadClient worldClient, + TestTransactionManager manager, + DraftAuthorizationFenceBinding binding, + Map stored, + AccountDraftTerminalReconciliationService service) {} + + private static final class TestTransactionManager extends AbstractPlatformTransactionManager { + private int commits; + private int rollbacks; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected boolean isExistingTransaction(Object transaction) { + return false; + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.isReadOnly()).isFalse(); + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + rollbacks++; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwnerTest.java new file mode 100644 index 0000000000..acc29d1582 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionAbortOwnerTest.java @@ -0,0 +1,304 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Owner/storage/transaction doubles only; fabricated carriers prove no current source authority. + */ +public class AccountGameplayAdmissionAbortOwnerTest { + private final AccountGameplayAdmissionLeaseRepository repository = + mock(AccountGameplayAdmissionLeaseRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final TransactionStatus status = mock(TransactionStatus.class); + private final AccountGameplayAdmissionAbortOwner owner = + new AccountGameplayAdmissionAbortOwner(repository, manager, "test"); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void missingWrongAndCrossNamespacePeersNeverReachStorage() { + assertThatThrownBy(() -> owner.abort(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + f -> + assertThat(Status.fromThrowable(f).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + for (String uri : + List.of( + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/game-session-service")) { + assertThatThrownBy(() -> peer(uri).call(() -> owner.abort(request()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + f -> + assertThat(Status.fromThrowable(f).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsAmbientTransactionBeforeOwnedTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> peer().call(() -> owner.abort(request()))) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsAmbientSynchronizationBeforeOwnedTransaction() { + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> peer().call(() -> owner.abort(request()))) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(repository, manager); + } + + @Test + void pendingAbortAndLostResponseRetryRetainOneCleanupAndOriginalExpiredEvidence() + throws Exception { + var original = fixture(); + var stored = + new AtomicReference<>( + new AccountGameplayAdmissionLeaseOperation(original, State.PENDING, null, null)); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.readExact(any())).thenAnswer(invocation -> Optional.of(stored.get())); + when(repository.recordAborted(eq(original), eq(null), any())) + .thenAnswer( + invocation -> { + var value = + new AccountGameplayAdmissionLeaseOperation( + original, State.ABORTED, null, invocation.getArgument(2)); + stored.set(value); + return value; + }); + var first = peer().call(() -> owner.abort(request())); + var retry = peer().call(() -> owner.abort(request())); + assertThat(retry).isSameAs(first); + assertThat(first.evidence()).isEqualTo(original); + assertThat(first.bindingDecisionId()).isNull(); + assertThat(first.orphanCleanupId().version()).isEqualTo(4); + verify(repository).recordAborted(eq(original), eq(null), eq(first.orphanCleanupId())); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(manager, org.mockito.Mockito.times(2)).getTransaction(definition.capture()); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(manager, org.mockito.Mockito.times(2)).commit(status); + } + + @Test + void suppliedDecisionIsOnlyCorrelationAndChangedPresenceOrValueConflicts() throws Exception { + UUID decision = UUID.randomUUID(); + var aborted = + new AccountGameplayAdmissionLeaseOperation( + fixture(), State.ABORTED, decision, UUID.randomUUID()); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.readExact(any())).thenReturn(Optional.of(aborted)); + var exact = request().toBuilder().setBindingDecisionId(decision.toString()).build(); + assertThat(peer().call(() -> owner.abort(exact))).isSameAs(aborted); + for (var changed : + List.of( + request(), + request().toBuilder().setBindingDecisionId(UUID.randomUUID().toString()).build())) { + assertThatThrownBy(() -> peer().call(() -> owner.abort(changed))) + .isInstanceOf(IllegalStateException.class); + } + verify(repository, never()).recordAborted(any(), any(), any()); + verify(manager, org.mockito.Mockito.times(2)).rollback(status); + } + + @Test + void committedAbsentAndChangedStoredEvidenceDenyAndRollBack() { + when(manager.getTransaction(any())).thenReturn(status); + when(repository.readExact(any())) + .thenReturn( + Optional.of( + new AccountGameplayAdmissionLeaseOperation( + fixture(), State.COMMITTED, UUID.randomUUID(), null))) + .thenReturn(Optional.empty()) + .thenThrow(new AccountGameplayAdmissionLeaseRepository.IdentityConflictException()); + for (int attempt = 0; attempt < 3; attempt++) { + assertThatThrownBy(() -> peer().call(() -> owner.abort(request()))) + .isInstanceOf(IllegalStateException.class); + } + verify(repository, never()).recordAborted(any(), any(), any()); + verify(manager, org.mockito.Mockito.times(3)).rollback(status); + } + + @Test + void failedWriteRollsBackWithoutReturningAnAbort() { + when(manager.getTransaction(any())).thenReturn(status); + when(repository.readExact(any())) + .thenReturn( + Optional.of( + new AccountGameplayAdmissionLeaseOperation(fixture(), State.PENDING, null, null))); + when(repository.recordAborted(any(), any(), any())) + .thenThrow(new IllegalStateException("write failed")); + assertThatThrownBy(() -> peer().call(() -> owner.abort(request()))) + .isInstanceOf(IllegalStateException.class); + verify(manager).rollback(status); + verify(manager, never()).commit(status); + } + + @Test + void mismatchedCarrierNamespaceAndMalformedDecisionFailBeforeSql() { + var carrier = new LinkedHashMap<>(fixture().carrier()); + carrier.put("targetNamespace", "other"); + carrier.put("callerWorkload", "spiffe://firemud/ns/other/sa/game-session-service"); + var wrongCaller = + request().toBuilder() + .setLease( + AccountGameplayAdmissionLeaseWireCodec.encodeReference( + AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier))) + .build(); + assertThatThrownBy(() -> peer().call(() -> owner.abort(wrongCaller))) + .isInstanceOf(StatusRuntimeException.class); + assertThatThrownBy( + () -> + peer() + .call( + () -> owner.abort(request().toBuilder().setBindingDecisionId("").build()))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(repository, manager); + } + + public static AbortGameplayAdmissionLeaseRequest request() { + return AbortGameplayAdmissionLeaseRequest.newBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(fixture())) + .build(); + } + + private static Context peer() { + return peer("spiffe://firemud/ns/test/sa/game-session-service"); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } + + /** Deliberately fabricated expired storage carrier, not issuer or current authority evidence. */ + public static AccountGameplayAdmissionLeaseEvidence fixture() { + String account = "11111111-1111-4111-8111-111111111111"; + String tenant = "22222222-2222-4222-8222-222222222222"; + String other = "33333333-3333-4333-8333-333333333333"; + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "test"); + value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + value.put("requestId", other); + value.put("leaseId", tenant); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, other); + scope.put("accountId", account); + scope.put("tenantId", tenant); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "1"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenant, "1"), + "membershipAuthorityGeneration", + Map.of(tenant, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(tenant, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + "account/" + account, + "issuer/firemud-account-service", + "membership/" + account + "/" + tenant, + "tenant/" + tenant) + .stream() + .map( + suffix -> + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + suffix.startsWith("account/") || suffix.startsWith("issuer/") ? "0" : "1")) + .toList()); + Map token = new LinkedHashMap<>(); + token.put("accountId", account); + for (String key : List.of("operationId", "issuanceRequestId", "tokenJti")) + token.put(key, other); + token.put("tokenSHA256", "a".repeat(64)); + token.put("tokenProfile", "game-session-account-delegation"); + for (String key : List.of("tokenGeneration", "issuanceFence", "tokenIdentityFence")) + token.put(key, "1"); + token.put("issuedAt", "999"); + token.put("notBefore", "999"); + token.put("expiresAt", "1300"); + value.put("tokenIdentityEvidence", token); + value.put("evaluatedAt", "1000000"); + value.put("expiresAt", "1015000"); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java new file mode 100644 index 0000000000..8cd7a8c4d1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java @@ -0,0 +1,239 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.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 com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionCommitConfirmation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner/executor doubles only; no PostgreSQL durability or live mTLS is established. */ +class AccountGameplayAdmissionCommitConfirmationOwnerTest { + private final AccountGameplayAdmissionReceiptCommitExecutor executor = + mock(AccountGameplayAdmissionReceiptCommitExecutor.class); + private final DataSource source = mock(DataSource.class); + private final AccountGameplayAdmissionCommitConfirmationOwner owner = + new AccountGameplayAdmissionCommitConfirmationOwner(source, executor, "test"); + + @AfterEach + void clearTransaction() { + if (TransactionSynchronizationManager.hasResource(source)) { + TransactionSynchronizationManager.unbindResource(source); + } + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatedConfirmationDelegatesOnlyToPhysicalReceiptExecutor() throws Exception { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var receipt = receipt(evidence, decision); + when(executor.confirm(evidence, decision)).thenReturn(receipt); + assertThat(peer().call(() -> owner.confirm(request(evidence, decision)))).isSameAs(receipt); + verify(executor).confirm(evidence, decision); + verify(executor, never()).read(any(), any()); + } + + @Test + void dependencyUnavailableDescriptionAndTrailersAreReplacedWithBoundedOwnerFailure() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + Metadata trailers = new Metadata(); + Metadata.Key privateKey = + Metadata.Key.of("private-detail", Metadata.ASCII_STRING_MARSHALLER); + trailers.put(privateKey, "private dependency trailer"); + var dependencyFailure = + Status.UNAVAILABLE + .withDescription("private dependency description") + .asRuntimeException(trailers); + when(executor.confirm(evidence, decision)).thenThrow(dependencyFailure); + + assertUnavailableIsRedacted( + () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + + TransactionSynchronizationManager.clear(); + org.mockito.Mockito.reset(executor); + when(executor.read(evidence, decision)).thenThrow(dependencyFailure); + assertUnavailableIsRedacted(() -> peer().call(() -> owner.read(request(evidence, decision)))); + } + + @Test + void readReturnsHistoricalTemporalProofWithoutCreatingOrReevaluatingItsDeadline() + throws Exception { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var receipt = receipt(evidence, decision); + when(executor.read(evidence, decision)).thenReturn(receipt); + + var returned = peer().call(() -> owner.read(request(evidence, decision))); + + assertThat(returned).isSameAs(receipt); + assertThat(returned.expiresAtMs()).isEqualTo(1_015_000L); + assertThat(returned.committedBeforeMs()).isLessThan(returned.expiresAtMs()); + verify(executor).read(evidence, decision); + verify(executor, never()).confirm(any(), any()); + } + + @Test + void rejectsMissingWrongPeerAndNamespaceBeforeRequestParsingOrTransaction() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + var malformed = FinalizeGameplayAdmissionLeaseRequest.getDefaultInstance(); + assertStatus(Status.Code.UNAUTHENTICATED, () -> owner.confirm(malformed)); + for (String uri : + List.of( + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/game-session-service")) { + assertStatus( + Status.Code.PERMISSION_DENIED, () -> peer(uri).call(() -> owner.read(malformed))); + } + assertStatus( + Status.Code.UNAUTHENTICATED, () -> owner.read(request(evidence, UUID.randomUUID()))); + verifyNoInteractions(executor, source); + } + + @Test + void rejectsMalformedEnvelopeDecisionUnknownFieldsAndCallerBindingBeforeTransaction() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var reference = AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence); + for (var request : + List.of( + FinalizeGameplayAdmissionLeaseRequest.getDefaultInstance(), + request(evidence, decision).toBuilder().setUnknownFields(unknown).build(), + request(evidence, decision).toBuilder() + .setLease(reference.toBuilder().setUnknownFields(unknown)) + .build(), + request(evidence, decision).toBuilder() + .setLease( + reference.toBuilder().setEvidenceCanonicalJson(ByteString.copyFromUtf8("{}"))) + .build(), + request(evidence, UUID.randomUUID()).toBuilder() + .setBindingDecisionId("not-a-uuid") + .build(), + request(evidence, decision).toBuilder() + .setBindingDecisionId(decision.toString().toUpperCase()) + .build())) { + assertStatus(Status.Code.INVALID_ARGUMENT, () -> peer().call(() -> owner.confirm(request))); + } + var changedCarrier = new LinkedHashMap<>(evidence.carrier()); + changedCarrier.put("targetNamespace", "other"); + changedCarrier.put("callerWorkload", "spiffe://firemud/ns/other/sa/game-session-service"); + var otherCaller = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> peer().call(() -> owner.read(request(otherCaller, decision)))); + verifyNoInteractions(executor, source); + } + + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeOwnedTransaction() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.initSynchronization(); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(evidence, decision)))); + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.bindResource( + source, new ConnectionHolder(mock(java.sql.Connection.class))); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + verifyNoInteractions(executor, source); + } + + static AccountGameplayAdmissionCommitConfirmation receipt( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + var operation = + new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, decision, null); + return new AccountGameplayAdmissionCommitConfirmation( + operation, + (short) 1, + UUID.fromString((String) evidence.carrier().get("requestId")), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString((String) evidence.carrier().get("leaseId")), + 1L, + evidence.sha256(), + decision, + 1_015_000L, + "123456", + "1/20", + "1/21", + 1_014_999L, + "123457"); + } + + private static FinalizeGameplayAdmissionLeaseRequest request( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + return FinalizeGameplayAdmissionLeaseRequest.newBuilder() + .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence)) + .setBindingDecisionId(decision.toString()) + .build(); + } + + private static Context peer() { + return peer("spiffe://firemud/ns/test/sa/game-session-service"); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } + + private static void assertStatus( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static void assertUnavailableIsRedacted( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + var statusFailure = (StatusRuntimeException) failure; + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(failure).getDescription()) + .isEqualTo("Durable Account admission commit confirmation unavailable"); + assertThat(statusFailure.getTrailers()).isNull(); + assertThat(statusFailure.getCause()).isNull(); + }); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java new file mode 100644 index 0000000000..20b32aca03 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java @@ -0,0 +1,290 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Repository and SQL function doubles only; no PostgreSQL durability is established here. */ +class AccountGameplayAdmissionCommitConfirmationRepositoryTest { + private static final String CONFIRM_SQL = + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)"; + private static final String READ_SQL = + "SELECT * FROM account_gameplay_admission_read_commit_confirmation(?, ?, ?)"; + private static final String ACCOUNT_LOCK_SQL = + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE"; + private static final String OPERATION_SELECT_SQL = + "SELECT * FROM account_gameplay_admission_lease_operations WHERE request_id = ? FOR UPDATE"; + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void confirmAndReadCallOnlyTheirDatabaseFunctionWithOriginalRequestDigestAndDecision() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + var confirmDsl = dsl(evidence, operation, proofRow(evidence, decision)); + var confirmRepository = repository(confirmDsl); + + var created = confirmRepository.confirmCommitted(evidence, decision); + + assertThat(created.operation()).isEqualTo(operation); + assertThat(created.operation().evidence().canonicalJson()).isEqualTo(evidence.canonicalJson()); + assertThat(created.operation().evidence().sha256()).isEqualTo(evidence.sha256()); + assertThat(created.operation().state()).isEqualTo(State.COMMITTED); + assertThat(created.operation().bindingDecisionId()).isEqualTo(decision); + assertThat(created.requestId()) + .isEqualTo(UUID.fromString((String) evidence.carrier().get("requestId"))); + assertThat(created.accountId()) + .isEqualTo(UUID.fromString("11111111-1111-4111-8111-111111111111")); + assertThat(created.leaseId()) + .isEqualTo(UUID.fromString((String) evidence.carrier().get("leaseId"))); + assertThat(created.leaseFence()).isEqualTo(1L); + assertThat(created.evidenceSha256()).isEqualTo(evidence.sha256()); + assertThat(created.bindingDecisionId()).isEqualTo(decision); + assertThat(created.expiresAtMs()).isEqualTo(1_015_000L); + assertThat(created.finalizationXid()).isEqualTo("123456"); + assertThat(created.walInsertLsn()).isEqualTo("1/20"); + assertThat(created.walFlushLsn()).isEqualTo("1/21"); + assertThat(created.committedBeforeMs()).isEqualTo(1_014_999L); + assertThat(created.confirmationXid()).isEqualTo("123457"); + verify(confirmDsl) + .fetchOne( + CONFIRM_SQL, + UUID.fromString((String) evidence.carrier().get("requestId")), + evidence.sha256(), + decision); + var confirmOrder = inOrder(confirmDsl); + confirmOrder + .verify(confirmDsl) + .fetchOne( + CONFIRM_SQL, + UUID.fromString((String) evidence.carrier().get("requestId")), + evidence.sha256(), + decision); + confirmOrder.verify(confirmDsl).fetchOne(ACCOUNT_LOCK_SQL, ACCOUNT_ID); + confirmOrder + .verify(confirmDsl) + .fetchOne( + OPERATION_SELECT_SQL, UUID.fromString((String) evidence.carrier().get("requestId"))); + + var readDsl = dsl(evidence, operation, proofRow(evidence, decision)); + var readRepository = repository(readDsl); + assertThat(readRepository.readCommitConfirmation(evidence, decision)).isEqualTo(created); + verify(readDsl) + .fetchOne( + READ_SQL, + UUID.fromString((String) evidence.carrier().get("requestId")), + evidence.sha256(), + decision); + var readOrder = inOrder(readDsl); + readOrder + .verify(readDsl) + .fetchOne( + READ_SQL, + UUID.fromString((String) evidence.carrier().get("requestId")), + evidence.sha256(), + decision); + readOrder.verify(readDsl).fetchOne(ACCOUNT_LOCK_SQL, ACCOUNT_ID); + readOrder + .verify(readDsl) + .fetchOne( + OPERATION_SELECT_SQL, UUID.fromString((String) evidence.carrier().get("requestId"))); + verify(readDsl, never()).fetchOne(eq(CONFIRM_SQL), any(Object[].class)); + } + + @Test + void requiresWritableSerializableAccountTransactionBeforeAnyStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = + new AccountGameplayAdmissionCommitConfirmationRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + assertThatThrownBy(() -> repository.readCommitConfirmation(evidence, UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.readCommitConfirmation(evidence, UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.confirmCommitted(evidence, UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @Test + void pendingAbortedMissingAndDecisionMismatchFailClosedAfterProofLookup() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + for (var operation : + java.util.List.of( + new AccountGameplayAdmissionLeaseOperation(evidence, State.PENDING, null, null), + new AccountGameplayAdmissionLeaseOperation( + evidence, State.ABORTED, null, UUID.randomUUID()), + new AccountGameplayAdmissionLeaseOperation( + evidence, State.COMMITTED, UUID.randomUUID(), null))) { + DSLContext dsl = dsl(evidence, operation, proofRow(evidence, decision)); + assertThatThrownBy(() -> repository(dsl).confirmCommitted(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + verify(dsl).fetchOne(eq(CONFIRM_SQL), any(Object[].class)); + verify(dsl, never()).fetchOne(eq(READ_SQL), any(Object[].class)); + } + + DSLContext missingDsl = dsl(evidence, null, proofRow(evidence, decision)); + assertThatThrownBy(() -> repository(missingDsl).readCommitConfirmation(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + verify(missingDsl).fetchOne(eq(READ_SQL), any(Object[].class)); + } + + @Test + void missingOrContradictoryDatabaseProofFailsClosed() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + for (String field : + java.util.List.of( + "confirmation_version", + "request_id", + "account_uuid", + "lease_id", + "lease_fence", + "evidence_sha256", + "binding_decision_id", + "expires_at_ms", + "finalization_xid", + "wal_insert_lsn", + "wal_flush_lsn", + "committed_before_ms", + "confirmation_xid")) { + Record bad = proofRow(evidence, decision); + overrideBadField(bad, field); + DSLContext dsl = dsl(evidence, operation, bad); + assertThatThrownBy(() -> repository(dsl).readCommitConfirmation(evidence, decision)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Durable Account admission commit confirmation unavailable"); + } + + DSLContext missing = dsl(evidence, operation, null); + assertThatThrownBy(() -> repository(missing).readCommitConfirmation(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + verify(missing).fetchOne(eq(READ_SQL), any(Object[].class)); + verify(missing, never()).fetchOne(eq(ACCOUNT_LOCK_SQL), any(Object[].class)); + } + + private static AccountGameplayAdmissionCommitConfirmationRepository repository(DSLContext dsl) { + serializableTransaction(); + return new AccountGameplayAdmissionCommitConfirmationRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + } + + private static DSLContext dsl( + AccountGameplayAdmissionLeaseEvidence evidence, + AccountGameplayAdmissionLeaseOperation operation, + Record proof) { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record operationRow = operation == null ? null : operationRow(evidence, operation); + when(dsl.fetchOne(eq(CONFIRM_SQL), any(Object[].class))).thenReturn(proof); + when(dsl.fetchOne(eq(READ_SQL), any(Object[].class))).thenReturn(proof); + when(dsl.fetchOne(eq(ACCOUNT_LOCK_SQL), any(Object[].class))).thenReturn(account); + when(dsl.fetchOne(eq(OPERATION_SELECT_SQL), any(Object[].class))).thenReturn(operationRow); + return dsl; + } + + private static Record operationRow( + AccountGameplayAdmissionLeaseEvidence evidence, + AccountGameplayAdmissionLeaseOperation operation) { + Record row = mock(Record.class); + when(row.get("evidence_json", String.class)).thenReturn(evidence.canonicalJson()); + when(row.get("evidence_sha256", String.class)).thenReturn(evidence.sha256()); + when(row.get("account_uuid", UUID.class)) + .thenReturn(UUID.fromString("11111111-1111-4111-8111-111111111111")); + when(row.get("request_id", UUID.class)) + .thenReturn(UUID.fromString((String) evidence.carrier().get("requestId"))); + when(row.get("lease_id", UUID.class)) + .thenReturn(UUID.fromString((String) evidence.carrier().get("leaseId"))); + when(row.get("lease_fence", Long.class)).thenReturn(1L); + when(row.get("caller_workload", String.class)) + .thenReturn("spiffe://firemud/ns/test/sa/game-session-service"); + when(row.get("evaluated_at_ms", Long.class)).thenReturn(1_000_000L); + when(row.get("expires_at_ms", Long.class)).thenReturn(1_015_000L); + when(row.get("status", String.class)).thenReturn(operation.state().name()); + when(row.get("binding_decision_id", UUID.class)).thenReturn(operation.bindingDecisionId()); + when(row.get("orphan_cleanup_id", UUID.class)).thenReturn(operation.orphanCleanupId()); + return row; + } + + private static Record proofRow(AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + Record row = mock(Record.class); + when(row.get("confirmation_version", Short.class)).thenReturn((short) 1); + when(row.get("request_id", UUID.class)) + .thenReturn(UUID.fromString((String) evidence.carrier().get("requestId"))); + when(row.get("account_uuid", UUID.class)) + .thenReturn(UUID.fromString("11111111-1111-4111-8111-111111111111")); + when(row.get("lease_id", UUID.class)) + .thenReturn(UUID.fromString((String) evidence.carrier().get("leaseId"))); + when(row.get("lease_fence", Long.class)).thenReturn(1L); + when(row.get("evidence_sha256", String.class)).thenReturn(evidence.sha256()); + when(row.get("binding_decision_id", UUID.class)).thenReturn(decision); + when(row.get("expires_at_ms", Long.class)).thenReturn(1_015_000L); + when(row.get("finalization_xid", String.class)).thenReturn("123456"); + when(row.get("wal_insert_lsn", String.class)).thenReturn("1/20"); + when(row.get("wal_flush_lsn", String.class)).thenReturn("1/21"); + when(row.get("committed_before_ms", Long.class)).thenReturn(1_014_999L); + when(row.get("confirmation_xid", String.class)).thenReturn("123457"); + return row; + } + + private static void overrideBadField(Record row, String field) { + switch (field) { + case "confirmation_version" -> when(row.get(field, Short.class)).thenReturn((short) 2); + case "request_id", "account_uuid", "lease_id", "binding_decision_id" -> + when(row.get(field, UUID.class)).thenReturn(UUID.randomUUID()); + case "lease_fence", "expires_at_ms" -> when(row.get(field, Long.class)).thenReturn(2L); + case "committed_before_ms" -> when(row.get(field, Long.class)).thenReturn(1_015_000L); + case "evidence_sha256" -> when(row.get(field, String.class)).thenReturn("0".repeat(64)); + case "finalization_xid", "confirmation_xid" -> + when(row.get(field, String.class)).thenReturn("01"); + case "wal_insert_lsn" -> when(row.get(field, String.class)).thenReturn("2/20"); + case "wal_flush_lsn" -> when(row.get(field, String.class)).thenReturn("1/20 "); + default -> throw new IllegalArgumentException("Unknown proof field"); + } + } + + private static AccountGameplayAdmissionLeaseOperation committed( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + return new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, decision, null); + } + + private static void serializableTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java new file mode 100644 index 0000000000..d882831428 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java @@ -0,0 +1,312 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Modifier; +import java.sql.Connection; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Foundation storage proof; deliberately supplies no authenticated admission source. */ +class AccountGameplayAdmissionLeaseRepositoryTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void remainsUnregisteredWithNoPublicMutationOrAuthorizationFacade() { + assertThat(AccountGameplayAdmissionLeaseRepository.class.isAnnotationPresent(Repository.class)) + .isFalse(); + assertThat( + Arrays.stream(AccountGameplayAdmissionLeaseRepository.class.getDeclaredMethods()) + .filter(method -> !method.isSynthetic()) + .anyMatch( + method -> + Modifier.isPublic(method.getModifiers()) + || Modifier.isProtected(method.getModifiers()))) + .isFalse(); + } + + @Test + void requiresWritableSerializableAccountTransactionBeforeReadingOrWriting() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + assertThatThrownBy(() -> repository.allocate(account, request, lease)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.allocate(account, request, lease)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.allocate(account, request, lease)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + @Test + void rejectsNonV4AccountIdentityBeforeAnyStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + assertThatThrownBy( + () -> + repository.allocate( + UUID.fromString("11111111-1111-1111-8111-111111111111"), + UUID.randomUUID(), + UUID.randomUUID())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("UUIDv4"); + verifyNoInteractions(dsl); + } + + @Test + void missingCounterReadbackCannotPersistAnAllocation() { + assertCounterReadbackRejected(null, "unavailable"); + } + + @ParameterizedTest + @NullSource + @ValueSource(longs = {0L, -1L}) + void nullOrNonpositiveCounterCannotPersistAnAllocation(Long fence) { + Record counter = mock(Record.class); + when(counter.get("last_fence", Long.class)).thenReturn(fence); + assertCounterReadbackRejected(counter, "invalid"); + } + + @Test + void insertedAllocationMustBeReadBackBeforeItCanBeReturned() { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + Record row = allocationRow(account, request, lease, 1L); + DSLContext dsl = allocationDsl(row, 1); + assertThat(new AccountGameplayAdmissionLeaseRepository(dsl).allocate(account, request, lease)) + .isEqualTo( + new AccountGameplayAdmissionLeaseRepository.Allocation(account, request, lease, 1L)); + } + + @Test + void missingInsertedAllocationReadbackIsNotReturnedAsAnInMemoryIdentity() { + DSLContext dsl = allocationDsl(null, 1); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) + .hasMessage("Account admission lease allocation readback unavailable"); + } + + @ParameterizedTest + @ValueSource(ints = {0, 2}) + void allocationInsertRequiresExactlyOneStoredRow(int insertCount) { + DSLContext dsl = allocationDsl(null, insertCount); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) + .hasMessage("Account admission lease allocation insert unavailable"); + } + + @ParameterizedTest + @ValueSource(strings = {"account_uuid", "request_id", "lease_id", "lease_fence"}) + void changedInsertedAllocationIdentityFailsClosed(String field) { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + Record row = allocationRow(account, request, lease, 1L); + if (field.equals("lease_fence")) when(row.get(field, Long.class)).thenReturn(2L); + else when(row.get(field, UUID.class)).thenReturn(UUID.randomUUID()); + DSLContext dsl = allocationDsl(row, 1); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl).allocate(account, request, lease)) + .hasMessageContaining("identity conflict"); + } + + @Test + void allocationRecoveryReturnsOnlyOriginalStoredIdentity() { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID lease = UUID.randomUUID(); + DSLContext dsl = recoveryDsl(allocationRow(account, request, lease, 17L)); + assertThat(new AccountGameplayAdmissionLeaseRepository(dsl).findAllocation(account, request)) + .contains( + new AccountGameplayAdmissionLeaseRepository.Allocation(account, request, lease, 17L)); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @ParameterizedTest + @ValueSource(strings = {"account_uuid", "request_id"}) + void allocationRecoveryRejectsDifferentStoredOwnerOrRequest(String field) { + UUID account = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + Record row = allocationRow(account, request, UUID.randomUUID(), 1L); + when(row.get(field, UUID.class)).thenReturn(UUID.randomUUID()); + DSLContext dsl = recoveryDsl(row); + assertThatThrownBy( + () -> new AccountGameplayAdmissionLeaseRepository(dsl).findAllocation(account, request)) + .hasMessageContaining("identity conflict"); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void missingRecoveryRowsRemainEmptyStorageWithoutAllocating() { + DSLContext allocationDsl = recoveryDsl(null); + assertThat( + new AccountGameplayAdmissionLeaseRepository(allocationDsl) + .findAllocation(UUID.randomUUID(), UUID.randomUUID())) + .isEmpty(); + verify(allocationDsl, never()).execute(anyString(), any(Object[].class)); + DSLContext operationDsl = recoveryDsl(null); + assertThat( + new AccountGameplayAdmissionLeaseRepository(operationDsl) + .findByRequest( + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service")) + .isEmpty(); + verify(operationDsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void operationRecoveryRejectsMalformedStoredCarrierWithoutWrites() { + Record row = mock(Record.class); + when(row.get("evidence_json", String.class)).thenReturn("{}"); + DSLContext dsl = recoveryDsl(row); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .findByRequest( + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service")) + .isInstanceOf(IllegalArgumentException.class); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void abortedStorageShapeRetainsUnknownDecisionAndMandatoryPendingCleanup() { + var evidence = mock(AccountGameplayAdmissionLeaseEvidence.class); + UUID cleanup = UUID.randomUUID(); + var unknown = + new AccountGameplayAdmissionLeaseOperation(evidence, State.ABORTED, null, cleanup); + assertThat(unknown.bindingDecisionId()).isNull(); + assertThat(unknown.orphanCleanupId()).isEqualTo(cleanup); + assertThat(unknown.evidence()).isSameAs(evidence); + assertThat(unknown.hasPendingOrphanCleanup()).isTrue(); + assertThatThrownBy( + () -> new AccountGameplayAdmissionLeaseOperation(evidence, State.ABORTED, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseOperation( + evidence, State.ABORTED, new UUID(0, 0), cleanup)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseOperation( + evidence, State.ABORTED, null, new UUID(0, 0))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void invalidTerminalPresenceAndPresentUuidsRejectBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + var evidence = mock(AccountGameplayAdmissionLeaseEvidence.class); + UUID cleanup = UUID.randomUUID(); + assertThatThrownBy(() -> repository.recordCommitted(evidence, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.recordAborted(evidence, null, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.recordAborted(evidence, new UUID(0, 0), cleanup)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.recordAborted(evidence, null, new UUID(0, 0))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(dsl); + } + + private static Record allocationRow(UUID account, UUID request, UUID lease, Long fence) { + Record row = mock(Record.class); + when(row.get("account_uuid", UUID.class)).thenReturn(account); + when(row.get("request_id", UUID.class)).thenReturn(request); + when(row.get("lease_id", UUID.class)).thenReturn(lease); + when(row.get("lease_fence", Long.class)).thenReturn(fence); + return row; + } + + private static DSLContext allocationDsl(Record readback, int insertCount) { + DSLContext dsl = mock(DSLContext.class); + Record owner = mock(Record.class); + Record counter = mock(Record.class); + when(counter.get("last_fence", Long.class)).thenReturn(1L); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(owner, null, counter, readback); + when(dsl.execute( + startsWith("INSERT INTO account_gameplay_admission_lease_allocations "), + any(Object[].class))) + .thenReturn(insertCount); + serializableTransaction(); + return dsl; + } + + private static DSLContext recoveryDsl(Record readback) { + DSLContext dsl = mock(DSLContext.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(mock(Record.class), readback); + serializableTransaction(); + return dsl; + } + + private static void serializableTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + } + + /** Mocked storage failure only; this does not establish PostgreSQL or source authority proof. */ + private static void assertCounterReadbackRejected(Record counter, String failureKind) { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(account, null, counter); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + assertThatThrownBy( + () -> repository.allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account admission lease counter readback " + failureKind); + verify(dsl, never()) + .execute( + startsWith("INSERT INTO account_gameplay_admission_lease_allocations "), + any(Object[].class)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java new file mode 100644 index 0000000000..a3a2fa0a3a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java @@ -0,0 +1,489 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockingDetails; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Answers; +import org.mockito.MockedConstruction; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * JDBC/repository/opaque-ACK doubles; not PostgreSQL durability, authentication or admission proof. + */ +class AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest { + @AfterEach + void clearTransaction() { + for (Object key : TransactionSynchronizationManager.getResourceMap().keySet()) { + TransactionSynchronizationManager.unbindResource(key); + } + TransactionSynchronizationManager.clear(); + } + + @Test + void physicalReceiptCommitPrecedesNewConnectionAndExactHistoricalRead() throws Exception { + var fixture = new Fixture(); + try (var repositories = fixture.repositories()) { + assertThat(fixture.executor.confirm(fixture.acknowledgement)).isSameAs(fixture.receipt); + assertThat(repositories.constructed()).hasSize(2); + var order = + inOrder( + fixture.first.connection, + fixture.second.connection, + repositories.constructed().get(0), + repositories.constructed().get(1)); + order.verify(repositories.constructed().get(0)).create(fixture.acknowledgement); + order.verify(fixture.first.connection).commit(); + order.verify(fixture.first.connection).close(); + order.verify(repositories.constructed().get(1)).readExact(fixture.evidence, fixture.decision); + order.verify(fixture.second.connection).commit(); + assertIndependentAcquisition(fixture, repositories.constructed().get(1)); + // This is a historical receipt: receipt persistence does not restamp original expiry. + assertThat(fixture.receipt.expiresAtMs()).isLessThan(System.currentTimeMillis()); + verify(fixture.first.statement).execute("SET LOCAL synchronous_commit = on"); + verify(fixture.second.statement).execute("SET LOCAL synchronous_commit = on"); + } + } + + @Test + void creationApiAcceptsOnlyOpaqueAcknowledgement() { + assertThat( + java.util.Arrays.stream( + AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.class + .getDeclaredMethods()) + .filter(method -> method.getName().equals("confirm")) + .map(method -> java.util.List.of(method.getParameterTypes()))) + .containsExactly(java.util.List.of(OriginalCommitAcknowledgement.class)); + } + + @Test + void anotherDataSourceIsRejectedBeforeAnyConnection() throws Exception { + var fixture = new Fixture(); + var other = mock(DataSource.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(other) + .confirm(fixture.acknowledgement)) + .hasMessageContaining("Fresh owned"); + verifyNoInteractions(other); + } + + @Test + void missingOpaqueAcknowledgementCannotStartReceiptPersistence() throws Exception { + var fixture = new Fixture(); + assertThatThrownBy(() -> fixture.executor.confirm(null)) + .isInstanceOf(NullPointerException.class); + verifyNoInteractions(fixture.source); + } + + @ParameterizedTest + @ValueSource(strings = {"xid", "clock"}) + void changedOriginalProofRollsBackWithoutIndependentRead(String fault) throws Exception { + var fixture = new Fixture(); + if (fault.equals("xid")) { + when(fixture.acknowledgement.finalizationXid()).thenReturn("987654"); + } else { + when(fixture.acknowledgement.committedBeforeMs()).thenReturn(1L); + } + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .hasMessageContaining("Fresh owned"); + assertThat(repositories.constructed()).hasSize(1); + verify(fixture.first.connection, never()).commit(); + verify(fixture.first.connection).rollback(); + verifyNoInteractions(fixture.second.connection); + } + } + + @Test + void retryCommitCannotSubstituteForUnavailableHistoricalDurability() throws Exception { + var fixture = new Fixture(); + fixture.inserted = false; + fixture.failRead = true; + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .hasMessage("read unavailable"); + verify(fixture.first.connection).commit(); + verify(repositories.constructed().get(1)).readDurably(fixture.evidence, fixture.decision); + verify(repositories.constructed().get(1), never()).create(any()); + verify(fixture.second.connection, never()).commit(); + } + } + + @Test + void retainedReceiptUsesHistoricalDurabilityRatherThanRetryCommitProof() throws Exception { + var fixture = new Fixture(); + fixture.inserted = false; + try (var repositories = fixture.repositories()) { + assertThat(fixture.executor.confirm(fixture.acknowledgement)).isSameAs(fixture.receipt); + var read = repositories.constructed().get(1); + verify(read).readDurably(fixture.evidence, fixture.decision); + verify(read, never()).readExact(any(), any()); + verify(read, never()).create(any()); + int[] closes = invocationSequences(fixture.first.connection, "close"); + int[] reads = invocationSequences(read, "readDurably"); + assertThat(reads[0]).isGreaterThan(closes[0]); + } + } + + @Test + void uncertainPhysicalReceiptCommitNeverStartsIndependentRead() throws Exception { + var fixture = new Fixture(); + doThrow(new SQLException("COMMIT acknowledgement lost", "08006")) + .when(fixture.first.connection) + .commit(); + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .hasMessageContaining("physical COMMIT unavailable"); + assertThat(repositories.constructed()).hasSize(1); + verify(fixture.first.connection).rollback(); + verifyNoInteractions(fixture.second.connection); + } + } + + @ParameterizedTest + @ValueSource(strings = {"failure", "null", "decision", "evidence"}) + void unavailableOrNonExactCreationNeverCommitsOrReads(String fault) throws Exception { + var fixture = new Fixture(); + try (var repositories = fixture.repositories()) { + fixture.creationFault = fault; + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .isInstanceOf(RuntimeException.class); + assertThat(repositories.constructed()).hasSize(1); + verify(fixture.first.connection, never()).commit(); + verify(fixture.first.connection).rollback(); + verifyNoInteractions(fixture.second.connection); + } + } + + @ParameterizedTest + @ValueSource(strings = {"different", "failure", "commit-failure"}) + void readMismatchOrFailureDoesNotExposeCreatedReceipt(String fault) throws Exception { + var fixture = new Fixture(); + if (fault.equals("different")) { + var r = fixture.receipt; + fixture.readReceipt = + new AccountGameplayAdmissionOriginalAckReceipt( + r.operation(), + r.schemaVersion(), + r.requestId(), + r.accountId(), + r.leaseId(), + r.leaseFence(), + r.evidenceSha256(), + r.bindingDecisionId(), + r.expiresAtMs(), + r.finalizationXid(), + r.committedBeforeMs(), + "123458"); + } + fixture.failRead = fault.equals("failure"); + if (fault.equals("commit-failure")) { + doThrow(new SQLException("read commit lost")).when(fixture.second.connection).commit(); + } + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .isInstanceOf(RuntimeException.class); + verify(fixture.first.connection).commit(); + assertThat(repositories.constructed()).hasSize(2); + } + } + + @Test + void poolMayReuseConnectionAfterCompletedCommitAndCleanup() throws Exception { + var fixture = new Fixture(); + when(fixture.source.getConnection()).thenReturn(fixture.first.connection); + fixture.readConnection = fixture.first.connection; + try (var repositories = fixture.repositories()) { + assertThat(fixture.executor.confirm(fixture.acknowledgement)).isSameAs(fixture.receipt); + assertThat(repositories.constructed()).hasSize(2); + var order = inOrder(fixture.first.connection, repositories.constructed().get(1)); + order.verify(fixture.first.connection).commit(); + order.verify(fixture.first.connection).close(); + order.verify(repositories.constructed().get(1)).readExact(fixture.evidence, fixture.decision); + order.verify(fixture.first.connection).commit(); + assertIndependentAcquisition(fixture, repositories.constructed().get(1)); + verify(fixture.first.connection, never()).rollback(); + } + } + + @Test + void readOnlyValidatesExistingReceipt() throws Exception { + var fixture = new Fixture(); + try (var repositories = fixture.repositories()) { + assertThat(fixture.executor.read(fixture.evidence, fixture.decision)) + .isSameAs(fixture.receipt); + verify(repositories.constructed().getFirst(), never()).create(any()); + verify(repositories.constructed().getFirst(), never()).readExact(any(), any()); + verify(repositories.constructed().getFirst()).readDurably(fixture.evidence, fixture.decision); + verify(fixture.first.connection).commit(); + verifyNoInteractions(fixture.second.connection); + } + } + + @ParameterizedTest + @ValueSource(strings = {"actual", "synchronization", "bound"}) + void ambientContextDeniesBeforeConnectionAcquisition(String ambient) throws Exception { + var fixture = new Fixture(); + switch (ambient) { + case "actual" -> TransactionSynchronizationManager.setActualTransactionActive(true); + case "synchronization" -> TransactionSynchronizationManager.initSynchronization(); + case "bound" -> + TransactionSynchronizationManager.bindResource( + fixture.source, new ConnectionHolder(fixture.first.connection)); + default -> throw new IllegalArgumentException(ambient); + } + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .hasMessageContaining("Fresh owned"); + assertThatThrownBy(() -> fixture.executor.read(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned"); + verifyNoInteractions(fixture.source, fixture.first.connection); + } + + @ParameterizedTest + @ValueSource( + strings = { + "version", + "recovery", + "fsync", + "sync", + "isolation", + "readonly", + "engine", + "jdbc-isolation", + "jdbc-readonly", + "jdbc-autocommit", + "set-failure" + }) + void invalidDurabilityRollsBackBeforeAutoCommitCleanup(String fault) throws Exception { + var fixture = new Fixture(); + var jdbc = fixture.first; + switch (fault) { + case "version" -> when(jdbc.settings.getInt(1)).thenReturn(170000); + case "recovery" -> when(jdbc.settings.getBoolean(2)).thenReturn(true); + case "fsync" -> when(jdbc.settings.getString(3)).thenReturn("off"); + case "sync" -> when(jdbc.settings.getString(4)).thenReturn("off"); + case "isolation" -> when(jdbc.settings.getString(5)).thenReturn("read committed"); + case "readonly" -> when(jdbc.settings.getString(6)).thenReturn("on"); + case "engine" -> when(jdbc.metadata.getDatabaseProductName()).thenReturn("Other"); + case "jdbc-isolation" -> jdbc.badIsolation = true; + case "jdbc-readonly" -> when(jdbc.connection.isReadOnly()).thenReturn(true); + case "jdbc-autocommit" -> jdbc.badAutoCommit = true; + case "set-failure" -> + doThrow(new SQLException("SET rejected")) + .when(jdbc.statement) + .execute("SET LOCAL synchronous_commit = on"); + default -> throw new IllegalArgumentException(fault); + } + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.acknowledgement)) + .isInstanceOf(RuntimeException.class); + verify(jdbc.connection, never()).commit(); + var order = inOrder(jdbc.connection); + order.verify(jdbc.connection).rollback(); + order.verify(jdbc.connection).setAutoCommit(true); + assertThat(repositories.constructed()).hasSize(1); + verifyNoInteractions(fixture.second.connection); + } + } + + private static void assertIndependentAcquisition( + Fixture fixture, AccountGameplayAdmissionOriginalAckReceiptRepository readRepository) { + int[] acquisitions = invocationSequences(fixture.source, "getConnection"); + int[] commits = invocationSequences(fixture.first.connection, "commit"); + int[] closes = invocationSequences(fixture.first.connection, "close"); + int[] reads = invocationSequences(readRepository, "readExact"); + assertThat(acquisitions).hasSize(2); + assertThat(reads).hasSize(1); + assertThat(commits).isNotEmpty(); + assertThat(closes).isNotEmpty(); + assertThat(acquisitions[0]).isLessThan(commits[0]); + assertThat(commits[0]).isLessThan(closes[0]); + assertThat(closes[0]).isLessThan(acquisitions[1]); + assertThat(acquisitions[1]).isLessThan(reads[0]); + } + + private static int[] invocationSequences(Object mock, String method) { + return mockingDetails(mock).getInvocations().stream() + .filter(invocation -> invocation.getMethod().getName().equals(method)) + .mapToInt(invocation -> invocation.getSequenceNumber()) + .toArray(); + } + + private static final class Fixture { + private final DataSource source = mock(DataSource.class); + private final Jdbc first = new Jdbc(); + private final Jdbc second = new Jdbc(); + private Connection readConnection = second.connection; + private final AccountGameplayAdmissionLeaseEvidence evidence = + AccountGameplayAdmissionAbortOwnerTest.fixture(); + private final UUID decision = UUID.randomUUID(); + private final OriginalCommitAcknowledgement acknowledgement = + mock(OriginalCommitAcknowledgement.class); + private final AccountGameplayAdmissionOriginalAckReceipt receipt = receipt(evidence, decision); + private boolean inserted = true; + private AccountGameplayAdmissionOriginalAckReceipt readReceipt = receipt; + private boolean failRead; + private String creationFault; + private final AccountGameplayAdmissionOriginalAckReceiptCommitExecutor executor = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source); + + private Fixture() throws SQLException { + when(source.getConnection()).thenReturn(first.connection, second.connection); + when(acknowledgement.belongsTo(source)).thenReturn(true); + when(acknowledgement.evidence()).thenReturn(evidence); + when(acknowledgement.decisionId()).thenReturn(decision); + when(acknowledgement.finalizationXid()).thenReturn(receipt.finalizationXid()); + when(acknowledgement.committedBeforeMs()).thenReturn(receipt.committedBeforeMs()); + } + + private MockedConstruction + repositories() { + return mockConstruction( + AccountGameplayAdmissionOriginalAckReceiptRepository.class, + (repository, context) -> { + DSLContext dsl = (DSLContext) context.arguments().getFirst(); + Connection enlisted = dsl.connectionResult(value -> value); + assertThat(enlisted) + .isSameAs(context.getCount() == 1 ? first.connection : readConnection); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); + when(repository.create(acknowledgement)) + .thenAnswer( + ignored -> { + if (creationFault == null) + return new AccountGameplayAdmissionOriginalAckReceiptRepository.Creation( + receipt, inserted); + AccountGameplayAdmissionOriginalAckReceipt value = + switch (creationFault) { + case "failure" -> + throw new IllegalStateException("creation unavailable"); + case "null" -> null; + case "decision" -> receipt(evidence, UUID.randomUUID()); + case "evidence" -> { + var carrier = new java.util.LinkedHashMap<>(evidence.carrier()); + carrier.put("requestId", UUID.randomUUID().toString()); + yield receipt( + AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier), + decision); + } + default -> throw new IllegalArgumentException(creationFault); + }; + return new AccountGameplayAdmissionOriginalAckReceiptRepository.Creation( + value, inserted); + }); + when(repository.readExact(evidence, decision)).thenAnswer(ignored -> readResult()); + when(repository.readDurably(evidence, decision)).thenAnswer(ignored -> readResult()); + }); + } + + private AccountGameplayAdmissionOriginalAckReceipt readResult() { + if (failRead) throw new IllegalStateException("read unavailable"); + return readReceipt; + } + } + + private static AccountGameplayAdmissionOriginalAckReceipt receipt( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + var old = AccountGameplayAdmissionCommitConfirmationOwnerTest.receipt(evidence, decision); + return new AccountGameplayAdmissionOriginalAckReceipt( + old.operation(), + (short) 1, + old.requestId(), + old.accountId(), + old.leaseId(), + old.leaseFence(), + old.evidenceSha256(), + old.bindingDecisionId(), + old.expiresAtMs(), + old.finalizationXid(), + old.committedBeforeMs(), + old.confirmationXid()); + } + + private static final class Jdbc { + private final DatabaseMetaData metadata = mock(DatabaseMetaData.class); + private final ResultSet settings = mock(ResultSet.class); + private final Statement statement = + mock( + Statement.class, + invocation -> { + if (invocation.getMethod().getName().equals("executeQuery")) { + when(settings.next()).thenReturn(true, false); + return settings; + } + return Answers.RETURNS_DEFAULTS.answer(invocation); + }); + private final Connection connection = + mock( + Connection.class, + invocation -> + invocation.getMethod().getName().equals("createStatement") + ? statement + : Answers.RETURNS_DEFAULTS.answer(invocation)); + private boolean badIsolation; + private boolean badAutoCommit; + + private Jdbc() throws SQLException { + var autoCommit = new AtomicBoolean(true); + var isolation = new AtomicInteger(Connection.TRANSACTION_READ_COMMITTED); + when(connection.getAutoCommit()).thenAnswer(ignored -> badAutoCommit || autoCommit.get()); + doAnswer( + ignored -> { + autoCommit.set(ignored.getArgument(0)); + return null; + }) + .when(connection) + .setAutoCommit(anyBoolean()); + when(connection.getTransactionIsolation()) + .thenAnswer( + ignored -> badIsolation ? Connection.TRANSACTION_READ_COMMITTED : isolation.get()); + doAnswer( + ignored -> { + isolation.set(ignored.getArgument(0)); + return null; + }) + .when(connection) + .setTransactionIsolation(anyInt()); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getDatabaseProductName()).thenReturn("PostgreSQL"); + when(settings.getInt(1)).thenReturn(160011); + when(settings.getString(3)).thenReturn("on"); + when(settings.getString(4)).thenReturn("on"); + when(settings.getString(5)).thenReturn("serializable"); + when(settings.getString(6)).thenReturn("off"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepositoryTest.java new file mode 100644 index 0000000000..9a05727b98 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepositoryTest.java @@ -0,0 +1,521 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Repository doubles verify exact storage binding only; they do not prove PostgreSQL durability. + */ +class AccountGameplayAdmissionOriginalAckReceiptRepositoryTest { + private static final String INSERT_SQL = + "INSERT INTO account_gameplay_admission_original_commit_ack_receipts " + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) " + + "VALUES (?, ?, ?, ?, ?) ON CONFLICT (request_id) DO NOTHING RETURNING *"; + private static final String SELECT_SQL = + "SELECT * FROM account_gameplay_admission_original_commit_ack_receipts WHERE request_id = ?"; + private static final String READ_DURABLY_SQL = + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)"; + private static final String ACCOUNT_LOCK_SQL = + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE"; + private static final String OPERATION_SELECT_SQL = + "SELECT * FROM account_gameplay_admission_lease_operations WHERE request_id = ? FOR UPDATE"; + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void createInsertsTypedAckAndReturnsReattachedExactReceipt() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + Record inserted = receiptRow(evidence, decision, "123456", 1_014_999L); + DSLContext dsl = dsl(evidence, operation, inserted, inserted); + var repository = repository(dsl); + var acknowledgement = acknowledgement(evidence, decision, "123456", 1_014_999L); + + var created = repository.create(acknowledgement); + + assertThat(created.inserted()).isTrue(); + assertThat(created.receipt()).isEqualTo(decoded(operation, evidence, decision)); + verify(dsl) + .fetchOne( + INSERT_SQL, requestId(evidence), evidence.sha256(), decision, "123456", 1_014_999L); + var order = inOrder(dsl); + order + .verify(dsl) + .fetchOne( + INSERT_SQL, requestId(evidence), evidence.sha256(), decision, "123456", 1_014_999L); + order.verify(dsl).fetchOne(ACCOUNT_LOCK_SQL, accountId(evidence)); + order.verify(dsl).fetchOne(OPERATION_SELECT_SQL, requestId(evidence)); + verify(dsl, never()).fetchOne(eq(READ_DURABLY_SQL), any(Object[].class)); + } + + @Test + void exactRetainedAckReturnsInsertedFalseWithoutChangingOriginalClockOrXids() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + Record retained = receiptRow(evidence, decision, "123456", 1_014_999L); + var repository = repository(dsl(evidence, operation, null, retained)); + + var created = repository.create(acknowledgement(evidence, decision, "123456", 1_014_999L)); + + assertThat(created.inserted()).isFalse(); + assertThat(created.receipt()).isEqualTo(decoded(operation, evidence, decision)); + } + + @Test + void retainedAckWithChangedOriginalClockOrXidIsRejected() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + Record retained = receiptRow(evidence, decision, "123456", 1_014_999L); + var repository = repository(dsl(evidence, operation, null, retained)); + + assertThatThrownBy( + () -> repository.create(acknowledgement(evidence, decision, "123456", 1_014_998L))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> repository.create(acknowledgement(evidence, decision, "123457", 1_014_999L))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void storageOnlyReadAndDurableReadUseDistinctPathsAndSameExactOperation() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + Record receipt = receiptRow(evidence, decision, "123456", 1_014_999L); + + DSLContext exactDsl = dsl(evidence, operation, null, receipt); + var repository = repository(exactDsl); + assertThat(repository.readExact(evidence, decision)) + .isEqualTo(decoded(operation, evidence, decision)); + verify(exactDsl).fetchOne(SELECT_SQL, requestId(evidence)); + verify(exactDsl, never()).fetchOne(eq(READ_DURABLY_SQL), any(Object[].class)); + + DSLContext durableDsl = dsl(evidence, operation, receipt, receipt); + assertThat(repository(durableDsl).readDurably(evidence, decision)) + .isEqualTo(decoded(operation, evidence, decision)); + verify(durableDsl).fetchOne(READ_DURABLY_SQL, requestId(evidence), evidence.sha256(), decision); + verify(durableDsl, never()).fetchOne(eq(INSERT_SQL), any(Object[].class)); + } + + @Test + void rejectsMissingChangedAndNonCommittedOriginalOperation() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + Record receipt = receiptRow(evidence, decision, "123456", 1_014_999L); + DSLContext missing = dsl(evidence, null, null, receipt); + assertThatThrownBy(() -> repository(missing).readExact(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + + for (var state : State.values()) { + if (state == State.COMMITTED) continue; + var operation = + new AccountGameplayAdmissionLeaseOperation( + evidence, state, null, state == State.ABORTED ? UUID.randomUUID() : null); + DSLContext mismatched = dsl(evidence, operation, null, receipt); + assertThatThrownBy(() -> repository(mismatched).readExact(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + } + var wrongDecision = committed(evidence, UUID.randomUUID()); + assertThatThrownBy( + () -> + repository(dsl(evidence, wrongDecision, null, receipt)) + .readExact(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + + var changedCarrier = new java.util.LinkedHashMap<>(evidence.carrier()); + changedCarrier.put("leaseId", UUID.randomUUID().toString()); + var changedEvidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + DSLContext changedDsl = dsl(evidence, committed(evidence, decision), null, receipt); + assertThatThrownBy(() -> repository(changedDsl).readExact(changedEvidence, decision)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void validatesReceiptVersionFullBindingClockAndCanonicalDistinctUnsignedXids() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var operation = committed(evidence, decision); + var valid = decoded(operation, evidence, decision); + assertThat(valid.schemaVersion()).isEqualTo((short) 1); + assertThat(valid.receiptXid()).isEqualTo("123457"); + assertThat(valid.committedBeforeMs()).isLessThan(valid.expiresAtMs()); + + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 2, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + UUID.randomUUID(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + UUID.randomUUID(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + UUID.randomUUID(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence() + 1, + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + "0".repeat(64), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + UUID.randomUUID(), + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs() + 1, + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.expiresAtMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + "18446744073709551616", + valid.committedBeforeMs(), + valid.receiptXid())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.finalizationXid())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void receiptValueExposesOnlyImmutableRecordAccessors() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + var receipt = decoded(committed(evidence, decision), evidence, decision); + assertThat(AccountGameplayAdmissionOriginalAckReceipt.class.isRecord()).isTrue(); + assertThat( + java.util.Arrays.stream( + AccountGameplayAdmissionOriginalAckReceipt.class.getDeclaredFields()) + .filter(field -> !field.isSynthetic()) + .allMatch(field -> java.lang.reflect.Modifier.isFinal(field.getModifiers()))) + .isTrue(); + assertThat( + java.util.Arrays.stream(AccountGameplayAdmissionOriginalAckReceipt.class.getMethods()) + .map(java.lang.reflect.Method::getName) + .noneMatch(name -> name.startsWith("set"))) + .isTrue(); + assertThat(receipt.toString()) + .doesNotContain("committedBeforeMs", "finalizationXid", "receiptXid"); + } + + @Test + void everyRepositoryMethodRequiresWritableSerializableTransactionBeforeStorage() { + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID decision = UUID.randomUUID(); + DSLContext dsl = mock(DSLContext.class); + var repository = + new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + var acknowledgement = acknowledgement(evidence, decision, "123456", 1_014_999L); + + assertThatThrownBy(() -> repository.create(acknowledgement)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.readExact(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.readDurably(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.readDurably(evidence, decision)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.create(acknowledgement)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } + + private static AccountGameplayAdmissionOriginalAckReceiptRepository repository(DSLContext dsl) { + serializableTransaction(); + return new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + } + + private static DSLContext dsl( + AccountGameplayAdmissionLeaseEvidence evidence, + AccountGameplayAdmissionLeaseOperation operation, + Record inserted, + Record receipt) { + DSLContext dsl = mock(DSLContext.class); + Record account = mock(Record.class); + Record operationRow = operation == null ? null : operationRow(evidence, operation); + when(dsl.fetchOne(eq(INSERT_SQL), any(Object[].class))).thenReturn(inserted); + when(dsl.fetchOne(eq(SELECT_SQL), any(Object[].class))).thenReturn(receipt); + when(dsl.fetchOne(eq(READ_DURABLY_SQL), any(Object[].class))).thenReturn(inserted); + when(dsl.fetchOne(eq(ACCOUNT_LOCK_SQL), any(Object[].class))).thenReturn(account); + when(dsl.fetchOne(eq(OPERATION_SELECT_SQL), any(Object[].class))).thenReturn(operationRow); + return dsl; + } + + private static Record operationRow( + AccountGameplayAdmissionLeaseEvidence evidence, + AccountGameplayAdmissionLeaseOperation operation) { + Record row = mock(Record.class); + when(row.get("evidence_json", String.class)).thenReturn(evidence.canonicalJson()); + when(row.get("evidence_sha256", String.class)).thenReturn(evidence.sha256()); + when(row.get("account_uuid", UUID.class)).thenReturn(accountId(evidence)); + when(row.get("request_id", UUID.class)).thenReturn(requestId(evidence)); + when(row.get("lease_id", UUID.class)).thenReturn(leaseId(evidence)); + when(row.get("lease_fence", Long.class)).thenReturn(evidence.leaseFence().longValueExact()); + when(row.get("caller_workload", String.class)) + .thenReturn((String) evidence.carrier().get("callerWorkload")); + when(row.get("evaluated_at_ms", Long.class)) + .thenReturn(Long.parseLong((String) evidence.carrier().get("evaluatedAt"))); + when(row.get("expires_at_ms", Long.class)) + .thenReturn(Long.parseLong((String) evidence.carrier().get("expiresAt"))); + when(row.get("status", String.class)).thenReturn(operation.state().name()); + when(row.get("binding_decision_id", UUID.class)).thenReturn(operation.bindingDecisionId()); + when(row.get("orphan_cleanup_id", UUID.class)).thenReturn(operation.orphanCleanupId()); + return row; + } + + private static Record receiptRow( + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decision, + String finalizationXid, + long committedBeforeMs) { + Record row = mock(Record.class); + when(row.get("schema_version", Short.class)).thenReturn((short) 1); + when(row.get("request_id", UUID.class)).thenReturn(requestId(evidence)); + when(row.get("account_uuid", UUID.class)).thenReturn(accountId(evidence)); + when(row.get("lease_id", UUID.class)).thenReturn(leaseId(evidence)); + when(row.get("lease_fence", Long.class)).thenReturn(evidence.leaseFence().longValueExact()); + when(row.get("evidence_sha256", String.class)).thenReturn(evidence.sha256()); + when(row.get("binding_decision_id", UUID.class)).thenReturn(decision); + when(row.get("expires_at_ms", Long.class)) + .thenReturn(Long.parseLong((String) evidence.carrier().get("expiresAt"))); + when(row.get("finalization_xid", String.class)).thenReturn(finalizationXid); + when(row.get("committed_before_ms", Long.class)).thenReturn(committedBeforeMs); + when(row.get("receipt_xid", String.class)).thenReturn("123457"); + return row; + } + + private static AccountGameplayAdmissionOriginalAckReceipt decoded( + AccountGameplayAdmissionLeaseOperation operation, + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decision) { + return new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + requestId(evidence), + accountId(evidence), + leaseId(evidence), + evidence.leaseFence().longValueExact(), + evidence.sha256(), + decision, + Long.parseLong((String) evidence.carrier().get("expiresAt")), + "123456", + 1_014_999L, + "123457"); + } + + private static OriginalCommitAcknowledgement acknowledgement( + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decision, + String finalizationXid, + long committedBeforeMs) { + OriginalCommitAcknowledgement acknowledgement = mock(OriginalCommitAcknowledgement.class); + when(acknowledgement.evidence()).thenReturn(evidence); + when(acknowledgement.decisionId()).thenReturn(decision); + when(acknowledgement.finalizationXid()).thenReturn(finalizationXid); + when(acknowledgement.committedBeforeMs()).thenReturn(committedBeforeMs); + return acknowledgement; + } + + private static AccountGameplayAdmissionLeaseOperation committed( + AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { + return new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, decision, null); + } + + private static UUID requestId(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString((String) evidence.carrier().get("requestId")); + } + + private static UUID leaseId(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString((String) evidence.carrier().get("leaseId")); + } + + private static UUID accountId(AccountGameplayAdmissionLeaseEvidence evidence) { + var scope = (Map) evidence.carrier().get("bindingScope"); + return UUID.fromString((String) scope.get("accountId")); + } + + private static void serializableTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java new file mode 100644 index 0000000000..0741ec96ba --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java @@ -0,0 +1,412 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockingDetails; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.io.Serializable; +import java.lang.reflect.Modifier; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Answers; +import org.mockito.MockedConstruction; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Concrete Spring/JDBC lifecycle with mocked JDBC responses and repository storage. These unit + * doubles prove neither physical PostgreSQL durability nor a persisted receipt, authentication or + * admission. + */ +class AccountGameplayAdmissionOriginalCommitExecutorTest { + @AfterEach + void clearTransaction() { + for (Object key : TransactionSynchronizationManager.getResourceMap().keySet()) { + TransactionSynchronizationManager.unbindResource(key); + } + TransactionSynchronizationManager.clear(); + } + + @Test + void actualJdbcCommitPrecedesOpaqueAcknowledgement() throws Exception { + var fixture = new Fixture(); + var returned = + new AtomicReference< + AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement>(); + doAnswer( + ignored -> { + assertThat(returned.get()).isNull(); + return null; + }) + .when(fixture.connection) + .commit(); + try (var repositories = fixture.repositories(State.PENDING)) { + returned.set(fixture.executor.execute(fixture.evidence, fixture.decision)); + var acknowledgement = returned.get(); + assertThat(acknowledgement.evidence()).isSameAs(fixture.evidence); + assertThat(acknowledgement.decisionId()).isEqualTo(fixture.decision); + assertThat(acknowledgement.finalizationXid()).isEqualTo("42"); + assertThat(acknowledgement.committedBeforeMs()).isEqualTo(9000L); + assertThat(acknowledgement.belongsTo(fixture.source)).isTrue(); + assertThat(acknowledgement.belongsTo(mock(DataSource.class))).isFalse(); + assertThat(acknowledgement.belongsTo(null)).isFalse(); + assertThat(Serializable.class.isAssignableFrom(acknowledgement.getClass())).isFalse(); + assertThat(Arrays.stream(acknowledgement.getClass().getDeclaredConstructors())) + .allMatch(constructor -> Modifier.isPrivate(constructor.getModifiers())); + var order = + inOrder( + repositories.constructed().getFirst(), + fixture.stamp, + fixture.settingsStatement, + fixture.connection, + fixture.clockStatement); + order + .verify(repositories.constructed().getFirst()) + .recordCommitted(fixture.evidence, fixture.decision); + // Verify completed query lifecycles without invoking JDBC resource factories on verify mocks. + order.verify(fixture.stamp).close(); + order.verify(fixture.settingsStatement).execute("SET LOCAL synchronous_commit = on"); + order.verify(fixture.settingsStatement).close(); + order.verify(fixture.connection).commit(); + order.verify(fixture.clockStatement).close(); + var commits = + mockingDetails(fixture.connection).getInvocations().stream() + .filter(invocation -> invocation.getMethod().getName().equals("commit")) + .mapToInt(invocation -> invocation.getSequenceNumber()) + .toArray(); + var clockQueries = + mockingDetails(fixture.clockStatement).getInvocations().stream() + .filter(invocation -> invocation.getMethod().getName().equals("executeQuery")) + .mapToInt(invocation -> invocation.getSequenceNumber()) + .toArray(); + assertThat(commits).hasSize(1); + assertThat(clockQueries).hasSize(1); + assertThat(clockQueries[0]).isGreaterThan(commits[0]); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + } + + @Test + void acknowledgementRetainsConfiguredSourceIdentityWhenSpringUnwrapsProxy() throws Exception { + var fixture = new Fixture(); + var configured = new TransactionAwareDataSourceProxy(fixture.source); + try (var repositories = fixture.repositories(State.PENDING)) { + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(configured) + .execute(fixture.evidence, fixture.decision); + assertThat(acknowledgement.belongsTo(configured)).isTrue(); + assertThat(acknowledgement.belongsTo(fixture.source)).isFalse(); + assertThat(repositories.constructed()).hasSize(1); + } + } + + @ParameterizedTest + @ValueSource(strings = {"10000", "11000", "0", "-1", "9223372036854775808", "9000.5"}) + void invalidOrLatePostCommitClockCannotReturnCapability(String value) throws Exception { + var fixture = new Fixture(); + when(fixture.clockRow.getBigDecimal(1)).thenReturn(new BigDecimal(value)); + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("post-COMMIT clock bound unavailable"); + verify(fixture.connection).commit(); + verify(fixture.connection).rollback(); + verify(repositories.constructed().getFirst()) + .recordCommitted(fixture.evidence, fixture.decision); + } + } + + @ParameterizedTest + @ValueSource(strings = {"missing", "null", "query-error"}) + void unavailableClockAfterAcknowledgedCommitCannotReturnCapability(String fault) + throws Exception { + var fixture = new Fixture(); + switch (fault) { + case "missing" -> when(fixture.clockRow.next()).thenReturn(false); + case "null" -> when(fixture.clockRow.getBigDecimal(1)).thenReturn(null); + case "query-error" -> fixture.clockFailure = new SQLException("clock response lost", "08006"); + default -> throw new IllegalArgumentException(fault); + } + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("post-COMMIT clock"); + verify(fixture.connection).commit(); + verify(fixture.connection).rollback(); + verify(repositories.constructed().getFirst()) + .recordCommitted(fixture.evidence, fixture.decision); + } + } + + @Test + void ambiguousPhysicalCommitThrowsWithoutReturningAcknowledgement() throws Exception { + var fixture = new Fixture(); + doThrow(new SQLException("connection lost during COMMIT", "08006")) + .when(fixture.connection) + .commit(); + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("physical COMMIT unavailable"); + verify(fixture.connection).commit(); + verify(fixture.connection).rollback(); + assertThat(repositories.constructed()).hasSize(1); + } + } + + @Test + void failureToEnforceSynchronousCommitRollsBackBeforeConnectionCleanup() throws Exception { + var fixture = new Fixture(); + doThrow(new SQLException("SET LOCAL rejected")) + .when(fixture.settingsStatement) + .execute("SET LOCAL synchronous_commit = on"); + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("physical COMMIT unavailable"); + verify(fixture.connection, never()).commit(); + var order = inOrder(fixture.settingsStatement, fixture.connection); + order.verify(fixture.settingsStatement).execute("SET LOCAL synchronous_commit = on"); + order.verify(fixture.connection).rollback(); + order.verify(fixture.connection).setAutoCommit(true); + assertThat(repositories.constructed()).hasSize(1); + } + } + + @Test + void retainedCommittedRetryCannotMintAnotherAcknowledgement() throws Exception { + var fixture = new Fixture(); + try (var repositories = fixture.repositories(State.COMMITTED)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + verify(repositories.constructed().getFirst(), never()) + .recordCommitted(fixture.evidence, fixture.decision); + verify(fixture.connection, never()).commit(); + verify(fixture.connection).rollback(); + verifyNoInteractions(fixture.stamp, fixture.settingsStatement); + } + } + + @ParameterizedTest + @ValueSource(strings = {"actual", "synchronization", "bound"}) + void ambientContextDeniesBeforeAcquiringConnection(String ambient) throws Exception { + var fixture = new Fixture(); + switch (ambient) { + case "actual" -> TransactionSynchronizationManager.setActualTransactionActive(true); + case "synchronization" -> TransactionSynchronizationManager.initSynchronization(); + case "bound" -> + TransactionSynchronizationManager.bindResource( + fixture.source, new ConnectionHolder(fixture.connection)); + default -> throw new IllegalArgumentException(ambient); + } + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + verifyNoInteractions(fixture.source, fixture.connection); + } + + @ParameterizedTest + @ValueSource( + strings = {"version", "recovery", "fsync", "sync", "isolation", "readonly", "engine"}) + void unsupportedDurabilityAtCommitDenies(String fault) throws Exception { + var fixture = new Fixture(); + switch (fault) { + case "version" -> when(fixture.settings.getInt(1)).thenReturn(170000); + case "recovery" -> when(fixture.settings.getBoolean(2)).thenReturn(true); + case "fsync" -> when(fixture.settings.getString(3)).thenReturn("off"); + case "sync" -> when(fixture.settings.getString(4)).thenReturn("off"); + case "isolation" -> when(fixture.settings.getString(5)).thenReturn("read committed"); + case "readonly" -> when(fixture.settings.getString(6)).thenReturn("on"); + case "engine" -> when(fixture.metadata.getDatabaseProductName()).thenReturn("Other"); + default -> throw new IllegalArgumentException(fault); + } + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + verify(fixture.connection, never()).commit(); + verify(fixture.connection).rollback(); + assertThat(repositories.constructed()).hasSize(1); + } + } + + @Test + void finalizationStampMustBelongToActualOriginalTransaction() throws Exception { + var fixture = new Fixture(); + when(fixture.stampRow.getString(2)).thenReturn("43"); + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + verify(fixture.connection, never()).commit(); + verify(fixture.connection).rollback(); + assertThat(repositories.constructed()).hasSize(1); + } + } + + @Test + void replacingEnlistedConnectionCannotCommitOriginalBinding() throws Exception { + var fixture = new Fixture(); + Connection different = mock(Connection.class); + var calls = new AtomicInteger(); + when(fixture.stampRow.next()) + .thenAnswer( + ignored -> { + if (calls.getAndIncrement() == 0) return true; + TransactionSynchronizationManager.unbindResource(fixture.source); + TransactionSynchronizationManager.bindResource( + fixture.source, new ConnectionHolder(different)); + return false; + }); + try (var repositories = fixture.repositories(State.PENDING)) { + assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + verify(fixture.connection, never()).commit(); + verify(different, never()).commit(); + assertThat(repositories.constructed()).hasSize(1); + } + } + + private static final class Fixture { + private final DataSource source = mock(DataSource.class); + private final ResultSet clockRow = mock(ResultSet.class); + private SQLException clockFailure; + private final Statement clockStatement = + mock( + Statement.class, + invocation -> { + if (invocation.getMethod().getName().equals("executeQuery")) { + assertThat(invocation.getArgument(0, String.class)) + .isEqualTo("SELECT ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint"); + if (clockFailure != null) throw clockFailure; + return clockRow; + } + return Answers.RETURNS_DEFAULTS.answer(invocation); + }); + private final AtomicInteger statementCalls = new AtomicInteger(); + private final ResultSet settings = mock(ResultSet.class); + private final Statement settingsStatement = + mock( + Statement.class, + invocation -> + invocation.getMethod().getName().equals("executeQuery") + ? settings + : Answers.RETURNS_DEFAULTS.answer(invocation)); + private final ResultSet stampRow = mock(ResultSet.class); + private final PreparedStatement stamp = + mock( + PreparedStatement.class, + invocation -> + invocation.getMethod().getName().equals("executeQuery") + ? stampRow + : Answers.RETURNS_DEFAULTS.answer(invocation)); + private final Connection connection = + mock( + Connection.class, + invocation -> + switch (invocation.getMethod().getName()) { + case "createStatement" -> + statementCalls.getAndIncrement() == 0 ? settingsStatement : clockStatement; + case "prepareStatement" -> stamp; + default -> Answers.RETURNS_DEFAULTS.answer(invocation); + }); + private final DatabaseMetaData metadata = mock(DatabaseMetaData.class); + private final AccountGameplayAdmissionLeaseEvidence evidence = + mock(AccountGameplayAdmissionLeaseEvidence.class); + private final UUID decision = UUID.randomUUID(); + private final AccountGameplayAdmissionOriginalCommitExecutor executor = + new AccountGameplayAdmissionOriginalCommitExecutor(source); + + private Fixture() throws SQLException { + var autoCommit = new AtomicBoolean(true); + var isolation = new AtomicInteger(Connection.TRANSACTION_READ_COMMITTED); + when(source.getConnection()).thenReturn(connection); + when(connection.getAutoCommit()).thenAnswer(ignored -> autoCommit.get()); + doAnswer( + ignored -> { + autoCommit.set(ignored.getArgument(0)); + return null; + }) + .when(connection) + .setAutoCommit(anyBoolean()); + when(connection.getTransactionIsolation()).thenAnswer(ignored -> isolation.get()); + doAnswer( + ignored -> { + isolation.set(ignored.getArgument(0)); + return null; + }) + .when(connection) + .setTransactionIsolation(anyInt()); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getDatabaseProductName()).thenReturn("PostgreSQL"); + when(stampRow.next()).thenReturn(true, false); + when(stampRow.getString(1)).thenReturn("42"); + when(stampRow.getString(2)).thenReturn("42"); + when(settings.next()).thenReturn(true, false); + when(settings.getInt(1)).thenReturn(160011); + when(settings.getString(3)).thenReturn("on"); + when(settings.getString(4)).thenReturn("on"); + when(settings.getString(5)).thenReturn("serializable"); + when(settings.getString(6)).thenReturn("off"); + when(clockRow.next()).thenReturn(true, false); + when(clockRow.getBigDecimal(1)).thenReturn(BigDecimal.valueOf(9000L)); + when(evidence.carrier()) + .thenReturn( + Map.of( + "requestId", UUID.randomUUID().toString(), + "leaseId", UUID.randomUUID().toString(), + "expiresAt", "10000")); + when(evidence.sha256()).thenReturn("a".repeat(64)); + when(evidence.canonicalJson()).thenReturn("synthetic-unit-carrier"); + } + + private MockedConstruction repositories(State prior) { + return mockConstruction( + AccountGameplayAdmissionLeaseRepository.class, + (repository, context) -> { + DSLContext dsl = (DSLContext) context.arguments().getFirst(); + Connection enlisted = dsl.connectionResult(value -> value); + assertThat(enlisted).isSameAs(connection); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); + when(repository.readExact(evidence)) + .thenReturn( + Optional.of( + new AccountGameplayAdmissionLeaseOperation( + evidence, prior, prior == State.COMMITTED ? decision : null, null))); + when(repository.recordCommitted(evidence, decision)) + .thenReturn( + new AccountGameplayAdmissionLeaseOperation( + evidence, State.COMMITTED, decision, null)); + }); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwnerTest.java new file mode 100644 index 0000000000..4d05e73c46 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReadOwnerTest.java @@ -0,0 +1,203 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Owner/transaction doubles and fabricated carriers only; no current source authority is proven. + */ +class AccountGameplayAdmissionReadOwnerTest { + private final AccountGameplayAdmissionLeaseRepository repository = + mock(AccountGameplayAdmissionLeaseRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final TransactionStatus transactionStatus = mock(TransactionStatus.class); + private final AccountGameplayAdmissionReadOwner owner = + new AccountGameplayAdmissionReadOwner(repository, manager, "test"); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void returnsOnlyExactPendingOrAbortedHistoricalEvidenceInOwnedSerializableTransactions() + throws Exception { + var original = AccountGameplayAdmissionAbortOwnerTest.fixture(); + UUID cleanup = UUID.randomUUID(); + var pending = new AccountGameplayAdmissionLeaseOperation(original, State.PENDING, null, null); + var aborted = + new AccountGameplayAdmissionLeaseOperation(original, State.ABORTED, null, cleanup); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.readExact(original)).thenReturn(Optional.of(pending), Optional.of(aborted)); + + var first = peer().call(() -> owner.read(request(original))); + var second = peer().call(() -> owner.read(request(original))); + + assertThat(first).isSameAs(pending); + assertThat(second).isSameAs(aborted); + assertThat(first.evidence().canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(first.evidence().sha256()).isEqualTo(original.sha256()); + assertThat(first.state()).isEqualTo(State.PENDING); + assertThat(second.state()).isEqualTo(State.ABORTED); + assertThat(second.bindingDecisionId()).isNull(); + assertThat(second.orphanCleanupId()).isEqualTo(cleanup); + assertThat(second.hasPendingOrphanCleanup()).isTrue(); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(manager, times(2)).getTransaction(definition.capture()); + assertThat(definition.getAllValues()) + .allSatisfy( + value -> { + assertThat(value.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(value.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(value.isReadOnly()).isFalse(); + }); + verify(manager, times(2)).commit(transactionStatus); + verify(repository, times(2)).readExact(original); + verify(repository, never()).recordCommitted(any(), any()); + verify(repository, never()).recordAborted(any(), any(), any()); + } + + @Test + void rejectsMissingRowsCommittedStorageAndFullCarrierMismatchAsUnresolved() { + var original = AccountGameplayAdmissionAbortOwnerTest.fixture(); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.readExact(original)) + .thenReturn(Optional.empty()) + .thenReturn( + Optional.of( + new AccountGameplayAdmissionLeaseOperation( + original, State.COMMITTED, UUID.randomUUID(), null))) + .thenThrow(new AccountGameplayAdmissionLeaseRepository.IdentityConflictException()); + var changedCarrier = new LinkedHashMap<>(original.carrier()); + changedCarrier.put("leaseFence", "2"); + var changed = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + when(repository.readExact(changed)) + .thenThrow(new AccountGameplayAdmissionLeaseRepository.IdentityConflictException()); + + for (int attempt = 0; attempt < 3; attempt++) { + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> peer().call(() -> owner.read(request(original)))); + } + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> peer().call(() -> owner.read(request(changed)))); + verify(manager, times(4)).rollback(transactionStatus); + } + + @Test + void wrongPeerAndOriginalCallerNamespaceAreRejectedBeforeTransactionOrRepository() { + var original = AccountGameplayAdmissionAbortOwnerTest.fixture(); + var changedCarrier = new LinkedHashMap<>(original.carrier()); + changedCarrier.put("targetNamespace", "other"); + changedCarrier.put("callerWorkload", "spiffe://firemud/ns/other/sa/game-session-service"); + var otherNamespace = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + + assertStatus(Status.Code.UNAUTHENTICATED, () -> owner.read(request(original))); + for (String uri : + List.of( + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/game-session-service")) { + assertStatus( + Status.Code.PERMISSION_DENIED, () -> peer(uri).call(() -> owner.read(request(original)))); + } + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> peer().call(() -> owner.read(request(otherNamespace)))); + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsMalformedEnvelopeAndOuterRequestMismatchBeforeTransactionOrRepository() { + var original = AccountGameplayAdmissionAbortOwnerTest.fixture(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var reference = AccountGameplayAdmissionLeaseWireCodec.encodeReference(original); + for (var request : + List.of( + ReadGameplayAdmissionLeaseRequest.getDefaultInstance(), + request(original).toBuilder().setUnknownFields(unknown).build(), + request(original).toBuilder() + .setExpectedLease(reference.toBuilder().setUnknownFields(unknown)) + .build(), + request(original).toBuilder().setRequestId(UUID.randomUUID().toString()).build())) { + assertThatThrownBy(() -> peer().call(() -> owner.read(request))) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeOpeningOwnedTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> + peer() + .call(() -> owner.read(request(AccountGameplayAdmissionAbortOwnerTest.fixture())))); + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.initSynchronization(); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> + peer() + .call(() -> owner.read(request(AccountGameplayAdmissionAbortOwnerTest.fixture())))); + verifyNoInteractions(repository, manager); + } + + private static ReadGameplayAdmissionLeaseRequest request( + AccountGameplayAdmissionLeaseEvidence evidence) { + return ReadGameplayAdmissionLeaseRequest.newBuilder() + .setRequestId((String) evidence.carrier().get("requestId")) + .setExpectedLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence)) + .build(); + } + + private static void assertStatus(Status.Code expected, ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static Context peer() { + return peer("spiffe://firemud/ns/test/sa/game-session-service"); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutorTest.java new file mode 100644 index 0000000000..b80321d457 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutorTest.java @@ -0,0 +1,384 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockingDetails; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionCommitConfirmation; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Answers; +import org.mockito.MockedConstruction; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Concrete Spring transaction lifecycle with JDBC/repository doubles; not PostgreSQL proof. */ +class AccountGameplayAdmissionReceiptCommitExecutorTest { + @AfterEach + void clearTransaction() { + for (Object key : TransactionSynchronizationManager.getResourceMap().keySet()) { + TransactionSynchronizationManager.unbindResource(key); + } + TransactionSynchronizationManager.clear(); + } + + @Test + void physicalReceiptCommitPrecedesNewConnectionAndExactHistoricalRead() throws Exception { + var fixture = new Fixture(); + try (var repositories = fixture.repositories()) { + assertThat(fixture.executor.confirm(fixture.evidence, fixture.decision)) + .isSameAs(fixture.receipt); + assertThat(repositories.constructed()).hasSize(2); + var order = + inOrder( + fixture.first.connection, + fixture.second.connection, + repositories.constructed().get(0), + repositories.constructed().get(1)); + order + .verify(repositories.constructed().get(0)) + .confirmCommitted(fixture.evidence, fixture.decision); + order.verify(fixture.first.connection).commit(); + order.verify(fixture.first.connection).close(); + order + .verify(repositories.constructed().get(1)) + .readCommitConfirmation(fixture.evidence, fixture.decision); + order.verify(fixture.second.connection).commit(); + assertIndependentAcquisition(fixture, repositories.constructed().get(1)); + // This is a historical receipt: receipt persistence does not restamp original expiry. + assertThat(fixture.receipt.expiresAtMs()).isLessThan(System.currentTimeMillis()); + verify(fixture.first.statement).execute("SET LOCAL synchronous_commit = on"); + verify(fixture.second.statement).execute("SET LOCAL synchronous_commit = on"); + } + } + + @Test + void uncertainPhysicalReceiptCommitNeverStartsIndependentRead() throws Exception { + var fixture = new Fixture(); + doThrow(new SQLException("COMMIT acknowledgement lost", "08006")) + .when(fixture.first.connection) + .commit(); + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.evidence, fixture.decision)) + .hasMessageContaining("physical COMMIT unavailable"); + assertThat(repositories.constructed()).hasSize(1); + verify(fixture.first.connection).rollback(); + verifyNoInteractions(fixture.second.connection); + } + } + + @ParameterizedTest + @ValueSource(strings = {"failure", "null", "decision", "evidence"}) + void unavailableOrNonExactCreationNeverCommitsOrReads(String fault) throws Exception { + var fixture = new Fixture(); + try (var repositories = fixture.repositories()) { + fixture.creationFault = fault; + assertThatThrownBy(() -> fixture.executor.confirm(fixture.evidence, fixture.decision)) + .isInstanceOf(RuntimeException.class); + assertThat(repositories.constructed()).hasSize(1); + verify(fixture.first.connection, never()).commit(); + verify(fixture.first.connection).rollback(); + verifyNoInteractions(fixture.second.connection); + } + } + + @ParameterizedTest + @ValueSource(strings = {"different", "failure", "commit-failure"}) + void readMismatchOrFailureDoesNotExposeCreatedReceipt(String fault) throws Exception { + var fixture = new Fixture(); + if (fault.equals("different")) { + var r = fixture.receipt; + fixture.readReceipt = + new AccountGameplayAdmissionCommitConfirmation( + r.operation(), + r.confirmationVersion(), + r.requestId(), + r.accountId(), + r.leaseId(), + r.leaseFence(), + r.evidenceSha256(), + r.bindingDecisionId(), + r.expiresAtMs(), + r.finalizationXid(), + r.walInsertLsn(), + r.walFlushLsn(), + r.committedBeforeMs(), + "123458"); + } + fixture.failRead = fault.equals("failure"); + if (fault.equals("commit-failure")) { + doThrow(new SQLException("read commit lost")).when(fixture.second.connection).commit(); + } + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.evidence, fixture.decision)) + .isInstanceOf(RuntimeException.class); + verify(fixture.first.connection).commit(); + assertThat(repositories.constructed()).hasSize(2); + } + } + + @Test + void poolMayReuseConnectionAfterCompletedCommitAndCleanup() throws Exception { + var fixture = new Fixture(); + when(fixture.source.getConnection()).thenReturn(fixture.first.connection); + fixture.readConnection = fixture.first.connection; + try (var repositories = fixture.repositories()) { + assertThat(fixture.executor.confirm(fixture.evidence, fixture.decision)) + .isSameAs(fixture.receipt); + assertThat(repositories.constructed()).hasSize(2); + var order = inOrder(fixture.first.connection, repositories.constructed().get(1)); + order.verify(fixture.first.connection).commit(); + order.verify(fixture.first.connection).close(); + order + .verify(repositories.constructed().get(1)) + .readCommitConfirmation(fixture.evidence, fixture.decision); + order.verify(fixture.first.connection).commit(); + assertIndependentAcquisition(fixture, repositories.constructed().get(1)); + verify(fixture.first.connection, never()).rollback(); + } + } + + @Test + void readOnlyValidatesExistingReceipt() throws Exception { + var fixture = new Fixture(); + try (var repositories = fixture.repositories()) { + assertThat(fixture.executor.read(fixture.evidence, fixture.decision)) + .isSameAs(fixture.receipt); + verify(repositories.constructed().getFirst(), never()).confirmCommitted(any(), any()); + verify(repositories.constructed().getFirst()) + .readCommitConfirmation(fixture.evidence, fixture.decision); + verify(fixture.first.connection).commit(); + verifyNoInteractions(fixture.second.connection); + } + } + + @ParameterizedTest + @ValueSource(strings = {"actual", "synchronization", "bound"}) + void ambientContextDeniesBeforeConnectionAcquisition(String ambient) throws Exception { + var fixture = new Fixture(); + switch (ambient) { + case "actual" -> TransactionSynchronizationManager.setActualTransactionActive(true); + case "synchronization" -> TransactionSynchronizationManager.initSynchronization(); + case "bound" -> + TransactionSynchronizationManager.bindResource( + fixture.source, new ConnectionHolder(fixture.first.connection)); + default -> throw new IllegalArgumentException(ambient); + } + assertThatThrownBy(() -> fixture.executor.confirm(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned"); + assertThatThrownBy(() -> fixture.executor.read(fixture.evidence, fixture.decision)) + .hasMessageContaining("Fresh owned"); + verifyNoInteractions(fixture.source, fixture.first.connection); + } + + @ParameterizedTest + @ValueSource( + strings = { + "version", + "recovery", + "fsync", + "sync", + "isolation", + "readonly", + "engine", + "jdbc-isolation", + "jdbc-readonly", + "jdbc-autocommit", + "set-failure" + }) + void invalidDurabilityRollsBackBeforeAutoCommitCleanup(String fault) throws Exception { + var fixture = new Fixture(); + var jdbc = fixture.first; + switch (fault) { + case "version" -> when(jdbc.settings.getInt(1)).thenReturn(170000); + case "recovery" -> when(jdbc.settings.getBoolean(2)).thenReturn(true); + case "fsync" -> when(jdbc.settings.getString(3)).thenReturn("off"); + case "sync" -> when(jdbc.settings.getString(4)).thenReturn("off"); + case "isolation" -> when(jdbc.settings.getString(5)).thenReturn("read committed"); + case "readonly" -> when(jdbc.settings.getString(6)).thenReturn("on"); + case "engine" -> when(jdbc.metadata.getDatabaseProductName()).thenReturn("Other"); + case "jdbc-isolation" -> jdbc.badIsolation = true; + case "jdbc-readonly" -> when(jdbc.connection.isReadOnly()).thenReturn(true); + case "jdbc-autocommit" -> jdbc.badAutoCommit = true; + case "set-failure" -> + doThrow(new SQLException("SET rejected")) + .when(jdbc.statement) + .execute("SET LOCAL synchronous_commit = on"); + default -> throw new IllegalArgumentException(fault); + } + try (var repositories = fixture.repositories()) { + assertThatThrownBy(() -> fixture.executor.confirm(fixture.evidence, fixture.decision)) + .isInstanceOf(RuntimeException.class); + verify(jdbc.connection, never()).commit(); + var order = inOrder(jdbc.connection); + order.verify(jdbc.connection).rollback(); + order.verify(jdbc.connection).setAutoCommit(true); + assertThat(repositories.constructed()).hasSize(1); + verifyNoInteractions(fixture.second.connection); + } + } + + private static void assertIndependentAcquisition( + Fixture fixture, AccountGameplayAdmissionCommitConfirmationRepository readRepository) { + int[] acquisitions = invocationSequences(fixture.source, "getConnection"); + int[] commits = invocationSequences(fixture.first.connection, "commit"); + int[] closes = invocationSequences(fixture.first.connection, "close"); + int[] reads = invocationSequences(readRepository, "readCommitConfirmation"); + assertThat(acquisitions).hasSize(2); + assertThat(reads).hasSize(1); + assertThat(commits).isNotEmpty(); + assertThat(closes).isNotEmpty(); + assertThat(acquisitions[0]).isLessThan(commits[0]); + assertThat(commits[0]).isLessThan(closes[0]); + assertThat(closes[0]).isLessThan(acquisitions[1]); + assertThat(acquisitions[1]).isLessThan(reads[0]); + } + + private static int[] invocationSequences(Object mock, String method) { + return mockingDetails(mock).getInvocations().stream() + .filter(invocation -> invocation.getMethod().getName().equals(method)) + .mapToInt(invocation -> invocation.getSequenceNumber()) + .toArray(); + } + + private static final class Fixture { + private final DataSource source = mock(DataSource.class); + private final Jdbc first = new Jdbc(); + private final Jdbc second = new Jdbc(); + private Connection readConnection = second.connection; + private final AccountGameplayAdmissionLeaseEvidence evidence = + AccountGameplayAdmissionAbortOwnerTest.fixture(); + private final UUID decision = UUID.randomUUID(); + private final AccountGameplayAdmissionCommitConfirmation receipt = + AccountGameplayAdmissionCommitConfirmationOwnerTest.receipt(evidence, decision); + private AccountGameplayAdmissionCommitConfirmation readReceipt = receipt; + private boolean failRead; + private String creationFault; + private final AccountGameplayAdmissionReceiptCommitExecutor executor = + new AccountGameplayAdmissionReceiptCommitExecutor(source); + + private Fixture() throws SQLException { + when(source.getConnection()).thenReturn(first.connection, second.connection); + } + + private MockedConstruction + repositories() { + return mockConstruction( + AccountGameplayAdmissionCommitConfirmationRepository.class, + (repository, context) -> { + DSLContext dsl = (DSLContext) context.arguments().getFirst(); + Connection enlisted = dsl.connectionResult(value -> value); + assertThat(enlisted) + .isSameAs(context.getCount() == 1 ? first.connection : readConnection); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); + when(repository.confirmCommitted(evidence, decision)) + .thenAnswer( + ignored -> { + if (creationFault == null) return receipt; + return switch (creationFault) { + case "failure" -> throw new IllegalStateException("creation unavailable"); + case "null" -> null; + case "decision" -> + AccountGameplayAdmissionCommitConfirmationOwnerTest.receipt( + evidence, UUID.randomUUID()); + case "evidence" -> { + var carrier = new java.util.LinkedHashMap<>(evidence.carrier()); + carrier.put("requestId", UUID.randomUUID().toString()); + yield AccountGameplayAdmissionCommitConfirmationOwnerTest.receipt( + AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier), decision); + } + default -> throw new IllegalArgumentException(creationFault); + }; + }); + when(repository.readCommitConfirmation(evidence, decision)) + .thenAnswer( + ignored -> { + if (failRead) throw new IllegalStateException("read unavailable"); + return readReceipt; + }); + }); + } + } + + private static final class Jdbc { + private final DatabaseMetaData metadata = mock(DatabaseMetaData.class); + private final ResultSet settings = mock(ResultSet.class); + private final Statement statement = + mock( + Statement.class, + invocation -> { + if (invocation.getMethod().getName().equals("executeQuery")) { + when(settings.next()).thenReturn(true, false); + return settings; + } + return Answers.RETURNS_DEFAULTS.answer(invocation); + }); + private final Connection connection = + mock( + Connection.class, + invocation -> + invocation.getMethod().getName().equals("createStatement") + ? statement + : Answers.RETURNS_DEFAULTS.answer(invocation)); + private boolean badIsolation; + private boolean badAutoCommit; + + private Jdbc() throws SQLException { + var autoCommit = new AtomicBoolean(true); + var isolation = new AtomicInteger(Connection.TRANSACTION_READ_COMMITTED); + when(connection.getAutoCommit()).thenAnswer(ignored -> badAutoCommit || autoCommit.get()); + doAnswer( + ignored -> { + autoCommit.set(ignored.getArgument(0)); + return null; + }) + .when(connection) + .setAutoCommit(anyBoolean()); + when(connection.getTransactionIsolation()) + .thenAnswer( + ignored -> badIsolation ? Connection.TRANSACTION_READ_COMMITTED : isolation.get()); + doAnswer( + ignored -> { + isolation.set(ignored.getArgument(0)); + return null; + }) + .when(connection) + .setTransactionIsolation(anyInt()); + when(connection.getMetaData()).thenReturn(metadata); + when(metadata.getDatabaseProductName()).thenReturn("PostgreSQL"); + when(settings.getInt(1)).thenReturn(160011); + when(settings.getString(3)).thenReturn("on"); + when(settings.getString(4)).thenReturn("on"); + when(settings.getString(5)).thenReturn("serializable"); + when(settings.getString(6)).thenReturn("off"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwnerTest.java new file mode 100644 index 0000000000..7f80c00f46 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountIssuerSourceSnapshotReadOwnerTest.java @@ -0,0 +1,342 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotEvidence; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountIssuerSourceSnapshotReadOwnerTest { + private static final String NAMESPACE = "test"; + private static final String CALLER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + private final AccountAuthoritySourceEvidenceRepository sourceRepository = + mock(AccountAuthoritySourceEvidenceRepository.class); + private final PlatformTransactionManager transactionManager = + mock(PlatformTransactionManager.class); + private final TransactionStatus transactionStatus = mock(TransactionStatus.class); + private final AccountIssuerSourceSnapshotReadOwner owner = + new AccountIssuerSourceSnapshotReadOwner(sourceRepository, transactionManager, NAMESPACE); + + @BeforeEach + void installTransactionManagerBehavior() { + when(transactionManager.getTransaction(any())) + .thenAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + return transactionStatus; + }); + doAnswer( + invocation -> { + clearTransactionMarkers(); + return null; + }) + .when(transactionManager) + .commit(transactionStatus); + doAnswer( + invocation -> { + clearTransactionMarkers(); + return null; + }) + .when(transactionManager) + .rollback(transactionStatus); + } + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void missingWrongAndCrossNamespacePeersAreRejectedBeforeRequestParsingOrStorage() { + assertStatus(Status.Code.UNAUTHENTICATED, () -> owner.read(null)); + for (String uri : + List.of( + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/game-session-service")) { + assertStatus(Status.Code.PERMISSION_DENIED, () -> peer(uri).call(() -> owner.read(null))); + } + verifyNoInteractions(sourceRepository, transactionManager); + } + + @Test + void rejectsAmbientTransactionSynchronizationAndReadOnlyContextBeforeStorage() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + clearTransactionMarkers(); + + TransactionSynchronizationManager.initSynchronization(); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + TransactionSynchronizationManager.clearSynchronization(); + + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + verifyNoInteractions(sourceRepository, transactionManager); + } + + @Test + void readsZeroAndAdvancedOwnerSnapshotsAndRejectsChangedExpectedSource() throws Exception { + UUID operation = UUID.randomUUID(); + UUID freshOperation = UUID.randomUUID(); + var zero = sourceSnapshot(1, Optional.empty(), Optional.empty()); + var advanced = sourceSnapshot(2, Optional.of(issuerEvent()), Optional.of(issuerEvent())); + var eventDrift = + sourceSnapshot( + 2, + Optional.of(issuerEvent("different-historical-event-18")), + Optional.of(issuerEvent("different-historical-event-18"))); + when(sourceRepository.readCurrentCanonicalIssuerSource(ISSUER)) + .thenReturn(zero, zero, advanced, advanced, advanced, eventDrift); + + var captured = peer().call(() -> owner.read(request(operation))); + assertThat(captured.evidence().issuerAuthGeneration()).isEqualTo("1"); + assertThat(captured.evidence().sourceVersion()).isEqualTo("1"); + assertThat(captured.evidence().lastCommittedOutboxSequence()).isEqualTo("0"); + assertThat(captured.evidence().sourceEvent()).isEmpty(); + + var exactRetry = + peer().call(() -> owner.read(request(operation, Optional.of(captured.evidence())))); + assertThat(exactRetry.evidence()).isEqualTo(captured.evidence()); + + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(operation, Optional.of(captured.evidence()))))); + + var newCapture = peer().call(() -> owner.read(request(freshOperation))); + assertThat(newCapture.evidence().issuerAuthGeneration()).isEqualTo("2"); + assertThat(newCapture.evidence().sourceVersion()).isEqualTo("2"); + assertThat(newCapture.evidence().lastCommittedOutboxSequence()).isEqualTo("1"); + assertThat(newCapture.evidence().reconciliationOperationId()).isEqualTo(freshOperation); + var retained = + (AccountAuthoritySourceEventV1Codec.IssuerEvent) + AccountAuthoritySourceEventV1Codec.verify( + newCapture.evidence().sourceEvent().orElseThrow()); + assertThat(retained.eventId()).isEqualTo("historical-issuer-event-17"); + assertThat(retained.requestId()).isEqualTo("historical-issuer-event-17"); + assertThat(retained.eventId()).isNotEqualTo(freshOperation.toString()); + + var exactAdvancedRetry = + peer().call(() -> owner.read(request(freshOperation, Optional.of(newCapture.evidence())))); + assertThat(exactAdvancedRetry.evidence()).isEqualTo(newCapture.evidence()); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> + peer() + .call( + () -> owner.read(request(freshOperation, Optional.of(newCapture.evidence()))))); + + ArgumentCaptor definitions = + ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactionManager, times(6)).getTransaction(definitions.capture()); + assertThat(definitions.getAllValues()) + .allSatisfy( + definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(definition.isReadOnly()).isFalse(); + }); + verify(transactionManager, times(4)).commit(transactionStatus); + verify(transactionManager, times(2)).rollback(transactionStatus); + } + + @Test + void malformedUnknownUnsupportedAndMismatchedExpectedRequestsFailBeforeSql() { + UUID operation = UUID.randomUUID(); + var valid = request(operation); + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var wrongNamespace = valid.toBuilder().setTargetNamespace("other").build(); + var unsupportedIssuer = valid.toBuilder().setIssuerId("other-issuer").build(); + var wrongExpected = + valid.toBuilder() + .setExpectedSource( + AccountIssuerSourceSnapshotGrpcCodec.toWire( + AccountIssuerSourceSnapshotEvidenceForTest.zero(UUID.randomUUID()))) + .build(); + + for (ReadCurrentIssuerAuthoritySourceRequest request : + List.of(unknown, wrongNamespace, unsupportedIssuer, wrongExpected)) { + assertThatThrownBy(() -> peer().call(() -> owner.read(request))) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(sourceRepository, transactionManager); + } + + @Test + void sourceOutageMapsUnavailableAndContradictoryRetainedEventMapsFailedPrecondition() { + when(sourceRepository.readCurrentCanonicalIssuerSource(ISSUER)) + .thenThrow(new DataAccessException("database offline")); + assertStatus( + Status.Code.UNAVAILABLE, () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + + var corrupt = sourceSnapshot(2, Optional.of(issuerEvent()), Optional.of(issuerEvent())); + var source = corrupt.source(); + Event validEvent = corrupt.latestEvent().orElseThrow(); + Event malformedEvent = + new Event( + validEvent.outboxStreamKey(), + validEvent.requestId(), + validEvent.outboxSequence(), + validEvent.eventId(), + validEvent.eventDigest(), + "not-json".getBytes(StandardCharsets.UTF_8)); + var badHistory = + new AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot( + source, Optional.of(malformedEvent)); + doReturn(badHistory).when(sourceRepository).readCurrentCanonicalIssuerSource(ISSUER); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + } + + @Test + void missingCanonicalIssuerDeniesWithoutCreatingOrReadingAnotherScope() { + when(sourceRepository.readCurrentCanonicalIssuerSource(ISSUER)) + .thenThrow( + new AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException()); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> peer().call(() -> owner.read(request(UUID.randomUUID())))); + verify(sourceRepository).readCurrentCanonicalIssuerSource(ISSUER); + verify(sourceRepository, never()).initializeIssuerIfAbsent(any()); + } + + private static AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot + sourceSnapshot( + long generation, + Optional event, + Optional eventForOutbox) { + long sequence = generation - 1L; + Optional eventId = event.map(AccountAuthoritySourceEventV1Codec.IssuerEvent::eventId); + Optional digest = + event.map(AccountAuthoritySourceEventV1Codec.IssuerEvent::eventDigest); + var checkpoint = + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + STREAM, sequence, eventId, digest); + var current = + new AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence( + AuthorityScope.issuer(ISSUER), + generation, + generation, + null, + checkpoint, + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 9L, + null); + Optional latest = + eventForOutbox.map( + sourceEvent -> + new Event( + STREAM, + sourceEvent.requestId(), + sequence, + sourceEvent.eventId(), + sourceEvent.eventDigest(), + sourceEvent.canonicalJsonUtf8())); + return new AccountAuthoritySourceEvidenceRepository.CanonicalIssuerSourceSnapshot( + current, latest); + } + + private static AccountAuthoritySourceEventV1Codec.IssuerEvent issuerEvent() { + return issuerEvent("historical-issuer-event-17"); + } + + private static AccountAuthoritySourceEventV1Codec.IssuerEvent issuerEvent(String eventId) { + return AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + eventId, eventId, STREAM, "1", ISSUER, "2", "2", "SIGNER_COMPROMISE")); + } + + private static ReadCurrentIssuerAuthoritySourceRequest request(UUID operation) { + return request(operation, Optional.empty()); + } + + private static ReadCurrentIssuerAuthoritySourceRequest request( + UUID operation, Optional expected) { + var typed = + new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, ISSUER, expected); + return AccountIssuerSourceSnapshotGrpcCodec.toRequest(typed, NAMESPACE, CALLER); + } + + private static void assertStatus( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static Context peer() { + return peer(CALLER); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } + + private static void clearTransactionMarkers() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + } + + /** Builds a fully typed initial source for request-shape tests without asserting authority. */ + private static final class AccountIssuerSourceSnapshotEvidenceForTest { + private static AccountIssuerSourceSnapshotEvidence zero(UUID operation) { + return new AccountIssuerSourceSnapshotEvidence( + operation, NAMESPACE, CALLER, ISSUER, "1", "1", STREAM, "0", Optional.empty()); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java new file mode 100644 index 0000000000..b18a1a5002 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGameplayPublicAdmissionSourceReaderTest.java @@ -0,0 +1,666 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.UnaryOperator; +import net.firedevops.firemud.accountservice.dto.AccountGameplayPublicAdmissionSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.AccountMembershipRoleSourceSnapshot.MembershipSource; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountLifecyclePendingDenialReader; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.service.AccountGameplayPublicAdmissionSourceReader; +import net.firedevops.firemud.accountservice.service.AccountMembershipRoleSourceReader; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedGameplayAuthorityProjectionTest; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner API doubles prove exact composition and guards, not SQL or token authentication. */ +class AccountGameplayPublicAdmissionSourceReaderTest { + private static final UUID ACCOUNT = AccountSelectedGameplayAuthorityProjectionTest.ACCOUNT; + private static final UUID TENANT = AccountSelectedGameplayAuthorityProjectionTest.TENANT; + + @BeforeEach + void transaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_REPEATABLE_READ); + } + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void composesExactExistingOwnerReadsInAccountFirstOrder() { + Fixture fixture = new Fixture(); + + AccountGameplayPublicAdmissionSourceSnapshot result = fixture.read(); + + assertThat(result.membershipSource()).isSameAs(fixture.membership); + assertThat(result.accountLifecycleState()).isEqualTo(AccountLifecycleState.ACTIVE); + assertThat(result.entitlementSource()).isEqualTo(fixture.entitlement); + assertThat(result.tokenIdentityFence()).isEqualTo(fixture.activeFence); + var ordered = + inOrder( + fixture.memberships, + fixture.lifecyclePendingDenials, + fixture.accounts, + fixture.entitlements, + fixture.tokenFences); + ordered.verify(fixture.memberships).readCurrent(ACCOUNT, TENANT); + ordered.verify(fixture.lifecyclePendingDenials).requireNoPending(ACCOUNT, TENANT); + ordered.verify(fixture.accounts).findByAccountUuid(ACCOUNT); + ordered.verify(fixture.entitlements).readCurrent(TENANT); + ordered.verify(fixture.entitlements).revalidate(fixture.entitlement); + ordered.verify(fixture.tokenFences).requireActiveForUpdate(fixture.identity); + verifyNoMoreInteractions( + fixture.memberships, + fixture.lifecyclePendingDenials, + fixture.accounts, + fixture.entitlements, + fixture.tokenFences); + } + + @Test + void pendingLifecycleDenialStopsBeforeEntitlementAndTokenReads() { + Fixture fixture = new Fixture(); + doThrow( + new AccountLifecyclePendingDenialReader.PendingOperationException( + "Account-wide or target-tenant invalidation is unresolved")) + .when(fixture.lifecyclePendingDenials) + .requireNoPending(ACCOUNT, TENANT); + + assertThatThrownBy(fixture::read) + .isInstanceOf(AccountLifecyclePendingDenialReader.PendingOperationException.class) + .hasMessage("Account-wide or target-tenant invalidation is unresolved"); + + var ordered = inOrder(fixture.memberships, fixture.lifecyclePendingDenials); + ordered.verify(fixture.memberships).readCurrent(ACCOUNT, TENANT); + ordered.verify(fixture.lifecyclePendingDenials).requireNoPending(ACCOUNT, TENANT); + verifyNoInteractions(fixture.accounts, fixture.entitlements, fixture.tokenFences); + } + + @Test + void nonActiveAccountLifecycleStatesDenyBeforeEntitlementOrTokenReads() { + for (AccountLifecycleState state : + List.of( + AccountLifecycleState.SECURITY_LOCKED, + AccountLifecycleState.DEACTIVATED_PENDING_DELETE, + AccountLifecycleState.DELETED)) { + Fixture fixture = new Fixture(); + fixture.account.setLifecycleState(state); + + assertThatThrownBy(fixture::read) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Current Account lifecycle does not allow gameplay admission"); + verifyNoInteractions(fixture.entitlements, fixture.tokenFences); + } + } + + @Test + void missingOrMismatchedPersistedAccountIdentityAndProvenanceDeny() { + List> changes = + List.of( + f -> when(f.accounts.findByAccountUuid(ACCOUNT)).thenReturn(Optional.empty()), + f -> f.account.setAccountUuid(UUID.randomUUID()), + f -> f.account.setId(99L), + f -> f.account.setAccountUuidProvenance(null), + f -> + f.account.setAccountUuidProvenance( + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT), + f -> f.account.setAccountUuidSourceNumericId(99L), + f -> f.account.setAccountUuidSourceNumericId(null)); + + for (Consumer change : changes) { + Fixture fixture = new Fixture(); + change.accept(fixture); + + assertDenied(fixture); + verifyNoInteractions(fixture.entitlements, fixture.tokenFences); + } + } + + @Test + void changedTenantBillingCheckpointFenceScopeVersionLifecycleRolesAndFlagsDeny() { + List> changes = + List.of( + f -> + f.replaceEntitlement( + entitlement( + AccountSelectedGameplayAuthorityProjectionTest.tenant(UUID.randomUUID()))), + f -> f.updateEntitlement(fields -> fields.tenantBillingSequence++), + f -> f.updateEntitlement(fields -> fields.tenantAuthorityOutboxSequence++), + f -> f.identityWithIssuanceFence(2L), + f -> + f.replaceMembership( + member -> copyMember(member, UUID.randomUUID(), TENANT, null, null)), + f -> f.updateEntitlement(fields -> fields.tenantAuthorityGeneration++), + f -> + f.replaceMembership( + member -> copyMember(member, ACCOUNT, TENANT, "INACTIVE", null)), + f -> + f.replaceMembership( + member -> copyMember(member, ACCOUNT, TENANT, null, List.of("tenantAdmin"))), + f -> + f.replaceMembership( + member -> copyMember(member, ACCOUNT, TENANT, null, null, false)), + f -> f.updateEntitlement(fields -> fields.gameplayAvailable = false), + f -> f.updateEntitlement(fields -> fields.allowNewGameplayBindings = false)); + + for (Consumer change : changes) { + Fixture fixture = new Fixture(); + change.accept(fixture); + assertDenied(fixture); + } + } + + @Test + void changedExactTenantSourceAndBillingReceiptIdentitiesDeny() { + for (Consumer change : + List.>of( + fields -> fields.sourceEvidence = differentSourceEvidence(), + fields -> fields.tenantAuthoritySourceVersion++, + fields -> fields.tenantAuthorityEventId = UUID.randomUUID(), + fields -> fields.tenantAuthorityEventDigest = "sha256:" + "0".repeat(64), + fields -> fields.eventId = UUID.randomUUID(), + fields -> { + fields.eventDigest = "sha256:" + "0".repeat(64); + fields.snapshotIdentity = fields.eventDigest; + })) { + Fixture fixture = new Fixture(); + fixture.updateEntitlement(change); + assertDenied(fixture); + } + } + + @Test + void missingOrNullOwnerEvidenceFailsClosed() { + Fixture missingMembership = new Fixture(); + when(missingMembership.memberships.readCurrent(ACCOUNT, TENANT)).thenReturn(null); + assertDenied(missingMembership); + verifyNoInteractions(missingMembership.entitlements, missingMembership.tokenFences); + + Fixture missingEntitlement = new Fixture(); + when(missingEntitlement.entitlements.readCurrent(TENANT)).thenReturn(null); + assertDenied(missingEntitlement); + verifyNoInteractions(missingEntitlement.tokenFences); + + Fixture missingRevalidation = new Fixture(); + when(missingRevalidation.entitlements.revalidate(missingRevalidation.entitlement)) + .thenReturn(null); + assertDenied(missingRevalidation); + verifyNoInteractions(missingRevalidation.tokenFences); + + Fixture missingFence = new Fixture(); + when(missingFence.tokenFences.requireActiveForUpdate(missingFence.identity)).thenReturn(null); + assertDenied(missingFence); + } + + @Test + void inactiveSqlFenceAndChangedRevalidatedSnapshotDeny() { + Fixture inactive = new Fixture(); + when(inactive.tokenFences.requireActiveForUpdate(inactive.identity)) + .thenReturn( + new AccountGameplayTokenIdentityFence( + inactive.identity, 2L, State.PENDING, UUID.randomUUID(), "0".repeat(64))); + assertDenied(inactive); + + Fixture changedDuringRevalidation = new Fixture(); + EntitlementFields changedFields = new EntitlementFields(changedDuringRevalidation.entitlement); + changedFields.entitlementVersion++; + DemoTenantEntitlementSnapshot changed = changedFields.build(); + when(changedDuringRevalidation.entitlements.revalidate(changedDuringRevalidation.entitlement)) + .thenReturn(changed); + assertDenied(changedDuringRevalidation); + verifyNoInteractions(changedDuringRevalidation.tokenFences); + } + + @Test + void transactionAndIsolationGuardRunsBeforeAnyOwnerRead() { + for (Consumer invalidTransaction : + List.>of( + f -> TransactionSynchronizationManager.setActualTransactionActive(false), + f -> TransactionSynchronizationManager.setCurrentTransactionReadOnly(true), + f -> + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED))) { + Fixture fixture = new Fixture(); + invalidTransaction.accept(fixture); + assertDenied(fixture); + verifyNoInteractions( + fixture.memberships, fixture.accounts, fixture.entitlements, fixture.tokenFences); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_REPEATABLE_READ); + } + } + + @Test + void onlyExactCanonicalAccountAndTenantSelectorsAreAccepted() { + Fixture fixture = new Fixture(); + assertThatThrownBy( + () -> fixture.reader.readCurrent(UUID.randomUUID(), TENANT, fixture.identity)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions( + fixture.memberships, fixture.accounts, fixture.entitlements, fixture.tokenFences); + } + + @Test + void acceptsSerializableOwnerTransaction() { + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_SERIALIZABLE); + + assertThat(new Fixture().read()).isNotNull(); + } + + private static void assertDenied(Fixture fixture) { + assertThatThrownBy(fixture::read).isInstanceOf(RuntimeException.class); + } + + private static AccountMembershipRoleSourceSnapshot copyMember( + AccountMembershipRoleSourceSnapshot source, + UUID accountId, + UUID tenantId, + String lifecycle, + List roleIdentifiers) { + return copyMember(source, accountId, tenantId, lifecycle, roleIdentifiers, null); + } + + private static AccountMembershipRoleSourceSnapshot copyMember( + AccountMembershipRoleSourceSnapshot source, + UUID accountId, + UUID tenantId, + String lifecycle, + List roleIdentifiers, + Boolean gameplayAllowed) { + MembershipSource old = source.membership(); + MembershipSource member = + new MembershipSource( + old.membershipId(), + old.accountRowId(), + accountId, + old.accountIdentityProvenance(), + old.accountSourceNumericId(), + tenantId, + old.tenantProvenance(), + lifecycle == null ? old.lifecycleState() : lifecycle, + gameplayAllowed == null ? old.gameplayAdmissionAllowed() : gameplayAllowed, + old.membershipVersion(), + old.membershipAuthorityGeneration(), + old.authorityProvenance()); + RoleSnapshot oldRoles = source.roles(); + RoleSnapshot roles = + roleIdentifiers == null + ? oldRoles + : new RoleSnapshot( + oldRoles.accountId(), + oldRoles.tenantId(), + oldRoles.membershipId(), + oldRoles.snapshotVersion(), + roleIdentifiers, + oldRoles.accountUuid(), + oldRoles.tenantUuid(), + oldRoles.tenantProvenance()); + return new AccountMembershipRoleSourceSnapshot( + source.issuerAccountSources(), + source.currentAuthority(), + source.tenantSource(), + source.pair(), + member, + roles, + source.membershipCheckpoint(), + source.storedMembershipEvent(), + source.membershipEvent()); + } + + private static final class Fixture { + final AccountMembershipRoleSourceReader memberships = + mock(AccountMembershipRoleSourceReader.class); + final AccountRepository accounts = mock(AccountRepository.class); + final AccountDemoTenantEntitlementRepository entitlements = + mock(AccountDemoTenantEntitlementRepository.class); + final AccountGameplayTokenIdentityFenceRepository tokenFences = + mock(AccountGameplayTokenIdentityFenceRepository.class); + final AccountLifecyclePendingDenialReader lifecyclePendingDenials = + mock(AccountLifecyclePendingDenialReader.class); + final Account account = account(); + final AccountGameplayPublicAdmissionSourceReader reader = + new AccountGameplayPublicAdmissionSourceReader( + memberships, accounts, entitlements, tokenFences, lifecyclePendingDenials); + TokenIdentity identity = + new TokenIdentity( + ACCOUNT, + UUID.fromString("efcfc7ed-1019-4ef7-9f27-87218fe0e911"), + UUID.fromString("f1b119cf-095f-4f03-b571-0fdd3d749c57"), + "a".repeat(64), + UUID.fromString("a1c51e75-ec05-4d9b-9ce0-965e775a9ac4"), + 1_800_000_000L, + 1L, + 1L); + final AccountGameplayTokenIdentityFence activeFence = + new AccountGameplayTokenIdentityFence(identity, 1L, State.ACTIVE, null, null); + final AccountMembershipRoleSourceSnapshot membership = membershipSnapshot(); + DemoTenantEntitlementSnapshot entitlement = + entitlement(AccountSelectedGameplayAuthorityProjectionTest.tenant(TENANT)); + + Fixture() { + when(memberships.readCurrent(ACCOUNT, TENANT)).thenReturn(membership); + when(accounts.findByAccountUuid(ACCOUNT)).thenReturn(Optional.of(account)); + when(entitlements.readCurrent(TENANT)).thenReturn(entitlement); + when(entitlements.revalidate(entitlement)).thenReturn(entitlement); + when(tokenFences.requireActiveForUpdate(identity)).thenReturn(activeFence); + } + + private static Account account() { + Account account = new Account(); + account.setId(4L); + account.setAccountUuid(ACCOUNT); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(4L); + return account; + } + + AccountGameplayPublicAdmissionSourceSnapshot read() { + return reader.readCurrent(ACCOUNT, TENANT, identity); + } + + void identityWithIssuanceFence(long fence) { + // A mismatched identity reaches the same owner read but cannot match Account's source fence. + TokenIdentity changed = + new TokenIdentity( + identity.accountId(), + identity.operationId(), + identity.issuanceRequestId(), + identity.tokenSha256(), + identity.tokenJti(), + identity.notBeforeEpochSecond(), + identity.tokenGeneration(), + fence); + when(tokenFences.requireActiveForUpdate(changed)) + .thenReturn(new AccountGameplayTokenIdentityFence(changed, 1L, State.ACTIVE, null, null)); + identity = changed; + } + + void replaceMembership(UnaryOperator change) { + AccountMembershipRoleSourceSnapshot changed = change.apply(membership); + when(memberships.readCurrent(ACCOUNT, TENANT)).thenReturn(changed); + } + + void updateEntitlement(Consumer change) { + EntitlementFields fields = new EntitlementFields(entitlement); + change.accept(fields); + entitlement = fields.build(); + when(entitlements.readCurrent(TENANT)).thenReturn(entitlement); + when(entitlements.revalidate(entitlement)).thenReturn(entitlement); + } + + void replaceEntitlement(DemoTenantEntitlementSnapshot changed) { + entitlement = changed; + when(entitlements.readCurrent(TENANT)).thenReturn(entitlement); + when(entitlements.revalidate(entitlement)).thenReturn(entitlement); + } + + private AccountMembershipRoleSourceSnapshot membershipSnapshot() { + String issuer = GameSessionAccountDelegationProfile.ISSUER; + var issuanceFence = new IssuanceFence(ACCOUNT, 1L, 1L); + var issuerSource = + new CurrentSourceEvidence( + AuthorityScope.issuer(issuer), + 1L, + 1L, + null, + new SourceCheckpoint( + "account:auth-authority:v1:issuer/" + issuer, + 0L, + Optional.empty(), + Optional.empty()), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 10L, + null); + var accountSource = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT), + 1L, + 1L, + issuanceFence, + new SourceCheckpoint( + "account:auth-authority:v1:account/" + ACCOUNT, + 0L, + Optional.empty(), + Optional.empty()), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 4L, + "ACCOUNT_REPOSITORY_INSERT", + 11L, + 11L); + var sources = new IssuerAccountSourceSnapshot(issuerSource, accountSource, issuanceFence); + var authority = + new CompositeSnapshot( + new ScopeState(AuthorityScope.issuer(issuer), 1L, 1L, null), + new ScopeState(AuthorityScope.account(ACCOUNT), 1L, 1L, issuanceFence), + List.of(new ScopeState(AuthorityScope.tenant(TENANT), 2L, 2L, null)), + List.of( + new ScopeState( + AuthorityScope.membership(ACCOUNT, TENANT), 1L, 1L, issuanceFence)), + issuanceFence); + TenantAuthorityEventV1Codec.Event tenant = + AccountSelectedGameplayAuthorityProjectionTest.tenant(TENANT); + var provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenant.sourceEvidence().operationId(), + tenant.sourceEvidence().evidenceDigest()); + var memberEvent = + AccountSelectedGameplayAuthorityProjectionTest.member(ACCOUNT, TENANT, "1", "2", "1"); + String membershipStream = "account:auth-authority:v1:membership/" + ACCOUNT + "/" + TENANT; + var pair = + new PairAuthority( + ACCOUNT, + TENANT, + provenance, + true, + 2L, + 1L, + 1L, + memberEvent.eventId(), + memberEvent.eventDigest(), + false); + var roles = + new RoleSnapshot(4L, null, 5L, 2L, List.of("player"), ACCOUNT, TENANT, provenance); + var member = + new MembershipSource( + 5L, + 4L, + ACCOUNT, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT, + 4L, + TENANT, + provenance, + "ACTIVE", + true, + 2L, + 1L, + "EXPLICIT_JOIN"); + var checkpoint = + new Checkpoint(membershipStream, 1L, memberEvent.eventId(), memberEvent.eventDigest()); + var stored = + new Event( + membershipStream, + memberEvent.requestId(), + 1L, + memberEvent.eventId(), + memberEvent.eventDigest(), + memberEvent.canonicalJsonUtf8()); + return new AccountMembershipRoleSourceSnapshot( + sources, authority, tenant, pair, member, roles, checkpoint, stored, memberEvent); + } + } + + private static DemoTenantEntitlementSnapshot entitlement( + TenantAuthorityEventV1Codec.Event tenant) { + return new DemoTenantEntitlementSnapshot( + tenant.tenantId(), + tenant.sourceEvidence(), + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + true, + true, + true, + true, + new net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest.Quotas( + 1L, 1L, 1L), + 1L, + tenant.tenantAuthorityGeneration(), + tenant.tenantAuthoritySourceVersion(), + tenant.tenantBillingStreamKey(), + tenant.tenantBillingSequence(), + tenant.tenantBillingEventId(), + tenant.tenantBillingEventDigest(), + tenant.tenantBillingEventDigest(), + tenant.outboxStreamKey(), + tenant.outboxSequence(), + tenant.eventId(), + tenant.eventDigest()); + } + + private static FreshTenantCreationEvidence differentSourceEvidence() { + var source = AccountSelectedGameplayAuthorityProjectionTest.tenant(TENANT).sourceEvidence(); + long changedRowId = source.sourceGameRowId() + 1L; + String changedTenantKey = source.sourceGameTenantKey() + "-different"; + return new FreshTenantCreationEvidence( + source.schemaVersion(), + source.targetNamespace(), + source.creationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + changedRowId, + changedTenantKey, + source.provenanceKind(), + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + source.creationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + changedRowId, + changedTenantKey, + source.provenanceKind())); + } + + private static final class EntitlementFields { + UUID canonicalTenantId; + net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence sourceEvidence; + boolean gameplayAvailable; + boolean allowNewGameplayBindings; + long entitlementVersion; + long tenantAuthorityGeneration; + long tenantAuthoritySourceVersion; + String outboxStreamKey; + long tenantBillingSequence; + UUID eventId; + String eventDigest; + String snapshotIdentity; + String tenantAuthorityOutboxStreamKey; + long tenantAuthorityOutboxSequence; + UUID tenantAuthorityEventId; + String tenantAuthorityEventDigest; + + EntitlementFields(DemoTenantEntitlementSnapshot source) { + canonicalTenantId = source.canonicalTenantId(); + sourceEvidence = source.sourceEvidence(); + gameplayAvailable = source.gameplayAvailable(); + allowNewGameplayBindings = source.allowNewGameplayBindings(); + entitlementVersion = source.entitlementVersion(); + tenantAuthorityGeneration = source.tenantAuthorityGeneration(); + tenantAuthoritySourceVersion = source.tenantAuthoritySourceVersion(); + outboxStreamKey = source.outboxStreamKey(); + tenantBillingSequence = source.tenantBillingSequence(); + eventId = source.eventId(); + eventDigest = source.eventDigest(); + snapshotIdentity = source.snapshotIdentity(); + tenantAuthorityOutboxStreamKey = source.tenantAuthorityOutboxStreamKey(); + tenantAuthorityOutboxSequence = source.tenantAuthorityOutboxSequence(); + tenantAuthorityEventId = source.tenantAuthorityEventId(); + tenantAuthorityEventDigest = source.tenantAuthorityEventDigest(); + } + + DemoTenantEntitlementSnapshot build() { + return new DemoTenantEntitlementSnapshot( + canonicalTenantId, + sourceEvidence, + "NON_PAID_DEMO", + "ACTIVE", + null, + false, + gameplayAvailable, + true, + allowNewGameplayBindings, + true, + new net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest.Quotas( + 1L, 1L, 1L), + entitlementVersion, + tenantAuthorityGeneration, + tenantAuthoritySourceVersion, + outboxStreamKey, + tenantBillingSequence, + eventId, + eventDigest, + snapshotIdentity, + tenantAuthorityOutboxStreamKey, + tenantAuthorityOutboxSequence, + tenantAuthorityEventId, + tenantAuthorityEventDigest); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountRedisScriptDescriptorLoaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountRedisScriptDescriptorLoaderTest.java new file mode 100644 index 0000000000..9f50870882 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountRedisScriptDescriptorLoaderTest.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import org.junit.jupiter.api.Test; + +class AccountRedisScriptDescriptorLoaderTest { + @Test + void sixOwnerResourcesUseCanonicalClosedMetadata() { + var descriptors = new java.util.ArrayList(); + descriptors.addAll(new AccountGenerationProjectionRedisScriptContribution().descriptors()); + descriptors.addAll(new AccountGameplayDelegationRedisScriptContribution().descriptors()); + + assertThat(descriptors).hasSize(6); + assertThat(descriptors).extracting(RedisScriptDescriptor::scriptId).doesNotHaveDuplicates(); + for (var descriptor : descriptors) { + assertThat(descriptor.owner()).isEqualTo("account-service"); + assertThat(descriptor.principal()).isEqualTo("account_coord_app"); + assertThat(descriptor.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(descriptor.category()).isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_CAS); + assertThat(descriptor.resetSensitivity()) + .isEqualTo(RedisScriptDescriptor.ResetSensitivity.CLUSTER); + assertThat(descriptor.compatibilityLevel()) + .isEqualTo(RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET); + assertThat(descriptor.lossClass()) + .isEqualTo(RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP); + assertThat(descriptor.supportedCoexistence()) + .isEqualTo(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1"))); + assertThat(descriptor.legacyPayloadShape()).isNull(); + assertThat(descriptor.keys()).hasSize(1); + assertThat(descriptor.keys().getFirst().hashTagDeclaration()) + .isEqualTo(RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED); + } + } + + @Test + void deniesUnknownDuplicateMissingAndMalformedFields() throws Exception { + String source; + try (var input = + getClass().getResourceAsStream("/redis/scripts/account-generation-projection-cas.json")) { + source = + new String( + java.util.Objects.requireNonNull(input).readAllBytes(), StandardCharsets.UTF_8); + } + assertThatThrownBy(() -> parse(source.replaceFirst("\\{", "{\"unknown\":true,"))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> parse(source.replaceFirst("\\{", "{\"scriptId\":\"duplicate.v1\","))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> parse(source.replace("\"principal\": \"account_coord_app\",", ""))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> parse(source.replace("\"CLUSTER\"", "\"UNSUPPORTED\""))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> parse(source.replace("\"expectedMode\"", "7"))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> parse(source + "{}")).isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> parse("{")).isInstanceOf(RuntimeException.class); + } + + @Test + void deniesEmptyAndOversizeInputBeforeParsing() { + assertThatThrownBy(() -> AccountRedisScriptDescriptorLoader.parse(new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountRedisScriptDescriptorLoader.parse( + new byte[AccountRedisScriptDescriptorLoader.MAX_DESCRIPTOR_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + } + + private static RedisScriptDescriptor parse(String source) { + return AccountRedisScriptDescriptorLoader.parse(source.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java new file mode 100644 index 0000000000..15706e3e31 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGameplayAdmissionLeaseGrpcServiceTest.java @@ -0,0 +1,396 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +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.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.AcquirePublicGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AcquirePublicGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseState; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.ReconcileGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReconcileGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwner; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionAbortOwnerTest; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionReadOwner; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; + +/** Transport/owner doubles only; no registration, actual TLS or source-authority proof. */ +class AccountGameplayAdmissionLeaseGrpcServiceTest { + @Test + void encodesExactAbortedCarrierAndUnknownDecisionOnly() { + var owner = mock(AccountGameplayAdmissionAbortOwner.class); + UUID cleanup = UUID.randomUUID(); + when(owner.abort(any())) + .thenReturn( + new AccountGameplayAdmissionLeaseOperation( + AccountGameplayAdmissionAbortOwnerTest.fixture(), State.ABORTED, null, cleanup)); + var observer = new Capture(); + service(owner) + .abortGameplayAdmissionLease(AccountGameplayAdmissionAbortOwnerTest.request(), observer); + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + var operation = observer.value.getOperation(); + assertThat(operation.getState()) + .isEqualTo(GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED); + assertThat(operation.getPendingOrphanCleanup()).isTrue(); + assertThat(operation.hasBindingDecisionId()).isFalse(); + assertThat(operation.getOrphanCleanupId()).isEqualTo(cleanup.toString()); + assertThat(AccountGameplayAdmissionLeaseWireCodec.validateOperation(operation)) + .isEqualTo(AccountGameplayAdmissionAbortOwnerTest.fixture()); + } + + @Test + void committedCannotEscapeAbortTransport() { + var owner = mock(AccountGameplayAdmissionAbortOwner.class); + when(owner.abort(any())) + .thenReturn( + new AccountGameplayAdmissionLeaseOperation( + AccountGameplayAdmissionAbortOwnerTest.fixture(), + State.COMMITTED, + UUID.randomUUID(), + null)); + var observer = new Capture(); + service(owner) + .abortGameplayAdmissionLease(AccountGameplayAdmissionAbortOwnerTest.request(), observer); + assertFailure(observer, Status.Code.UNAVAILABLE); + } + + @Test + void actualOwnerDomainDenialsAreTypedButStorageFailuresAreUnavailable() { + var stored = + new java.util.concurrent.atomic.AtomicReference< + Optional>(Optional.empty()); + var repository = + mock( + AccountGameplayAdmissionLeaseRepository.class, + invocation -> { + if (invocation.getMethod().getName().equals("readExact")) return stored.get(); + return org.mockito.Answers.RETURNS_DEFAULTS.answer(invocation); + }); + var manager = mock(PlatformTransactionManager.class); + when(manager.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); + var service = + new AccountGameplayAdmissionLeaseGrpcService( + new AccountGameplayAdmissionAbortOwner(repository, manager, "test"), + mock(AccountGameplayAdmissionReadOwner.class)); + UUID decision = UUID.randomUUID(); + var aborted = + new AccountGameplayAdmissionLeaseOperation( + AccountGameplayAdmissionAbortOwnerTest.fixture(), + State.ABORTED, + decision, + UUID.randomUUID()); + for (String code : + List.of( + "ADMISSION_LEASE_UNRESOLVED", + "ADMISSION_LEASE_NOT_ABORTABLE", + "IDEMPOTENCY_CONFLICT")) { + if (code.equals("ADMISSION_LEASE_NOT_ABORTABLE")) + stored.set( + Optional.of( + new AccountGameplayAdmissionLeaseOperation( + AccountGameplayAdmissionAbortOwnerTest.fixture(), + State.COMMITTED, + decision, + null))); + if (code.equals("IDEMPOTENCY_CONFLICT")) stored.set(Optional.of(aborted)); + var observer = new Capture(); + peer() + .run( + () -> + service.abortGameplayAdmissionLease( + AccountGameplayAdmissionAbortOwnerTest.request(), observer)); + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.hasOperation()).isFalse(); + assertThat(observer.value.getDenied().getCode()).isEqualTo(code); + assertThat(observer.value.getDenied().getMessage()) + .isEqualTo("Account admission abort denied"); + } + var failingRepository = + mock( + AccountGameplayAdmissionLeaseRepository.class, + invocation -> { + throw new IllegalStateException("secret storage read failure"); + }); + var unavailable = new Capture(); + var failingService = + new AccountGameplayAdmissionLeaseGrpcService( + new AccountGameplayAdmissionAbortOwner(failingRepository, manager, "test"), + mock(AccountGameplayAdmissionReadOwner.class)); + peer() + .run( + () -> + failingService.abortGameplayAdmissionLease( + AccountGameplayAdmissionAbortOwnerTest.request(), unavailable)); + assertFailure(unavailable, Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(unavailable.failure).getDescription()).doesNotContain("secret"); + } + + @Test + void rejectsMalformedOuterReferenceAndClosedJsonBeforeSql() { + var repository = mock(AccountGameplayAdmissionLeaseRepository.class); + var manager = mock(PlatformTransactionManager.class); + var service = + new AccountGameplayAdmissionLeaseGrpcService( + new AccountGameplayAdmissionAbortOwner(repository, manager, "test"), + mock(AccountGameplayAdmissionReadOwner.class)); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var original = AccountGameplayAdmissionAbortOwnerTest.request(); + var reference = original.getLease(); + for (var request : + List.of( + AbortGameplayAdmissionLeaseRequest.getDefaultInstance(), + original.toBuilder().setUnknownFields(unknown).build(), + original.toBuilder().setLease(reference.toBuilder().setUnknownFields(unknown)).build(), + original.toBuilder() + .setLease(reference.toBuilder().setRequestId(UUID.randomUUID().toString())) + .build(), + original.toBuilder() + .setLease(reference.toBuilder().setEvidenceSha256("0".repeat(64))) + .build(), + original.toBuilder() + .setLease( + reference.toBuilder().setEvidenceCanonicalJson(ByteString.copyFromUtf8("{}"))) + .build(), + original.toBuilder() + .setLease( + reference.toBuilder() + .setEvidenceCanonicalJson( + ByteString.copyFromUtf8( + reference + .getEvidenceCanonicalJson() + .toStringUtf8() + .replace( + "\"schemaVersion\":\"1\"", "\"schemaVersion\":\"2\"")))) + .build())) { + var observer = new Capture(); + peer().run(() -> service.abortGameplayAdmissionLease(request, observer)); + assertFailure(observer, Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(repository, manager); + } + + @Test + void returnsBoundedRedactedErrorsWithoutSuccessfulOutcome() { + var owner = mock(AccountGameplayAdmissionAbortOwner.class); + var service = service(owner); + for (var failure : + List.of( + new IllegalArgumentException("secret evidence"), + new IllegalStateException("secret evidence"), + new RuntimeException("secret evidence"))) { + doThrow(failure).when(owner).abort(any()); + var observer = new Capture(); + service.abortGameplayAdmissionLease( + AccountGameplayAdmissionAbortOwnerTest.request(), observer); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(Status.fromThrowable(observer.failure).getDescription()) + .doesNotContain("secret evidence"); + assertThat(observer.failure.getCause()).isNull(); + } + } + + @Test + void acquireFinalizeAndReconcileRemainUnimplemented() { + var owner = mock(AccountGameplayAdmissionAbortOwner.class); + var readOwner = mock(AccountGameplayAdmissionReadOwner.class); + var service = new AccountGameplayAdmissionLeaseGrpcService(owner, readOwner); + var acquire = new Capture(); + var finalize = new Capture(); + var reconcile = new Capture(); + service.acquirePublicGameplayAdmissionLease( + AcquirePublicGameplayAdmissionLeaseRequest.getDefaultInstance(), acquire); + service.finalizeGameplayAdmissionLease( + FinalizeGameplayAdmissionLeaseRequest.getDefaultInstance(), finalize); + service.reconcileGameplayAdmissionLease( + ReconcileGameplayAdmissionLeaseRequest.getDefaultInstance(), reconcile); + for (var observer : List.of(acquire, finalize, reconcile)) + assertFailure(observer, Status.Code.UNIMPLEMENTED); + verifyNoInteractions(owner, readOwner); + } + + @Test + void encodesExactPendingAndAbortedReadbackWithoutFabricatingCleanupCompletion() { + var abortOwner = mock(AccountGameplayAdmissionAbortOwner.class); + var readOwner = mock(AccountGameplayAdmissionReadOwner.class); + var service = new AccountGameplayAdmissionLeaseGrpcService(abortOwner, readOwner); + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + var request = readRequest(evidence); + UUID cleanup = UUID.randomUUID(); + for (var operation : + List.of( + new AccountGameplayAdmissionLeaseOperation(evidence, State.PENDING, null, null), + new AccountGameplayAdmissionLeaseOperation(evidence, State.ABORTED, null, cleanup))) { + when(readOwner.read(request)).thenReturn(operation); + var observer = new Capture(); + service.readGameplayAdmissionLease(request, observer); + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.hasOperation()).isTrue(); + assertThat(observer.value.hasNotObserved()).isFalse(); + var encoded = observer.value.getOperation(); + assertThat(AccountGameplayAdmissionLeaseWireCodec.validateOperation(encoded)) + .isEqualTo(evidence); + assertThat(encoded.getLease().getEvidenceCanonicalJson()) + .isEqualTo(com.google.protobuf.ByteString.copyFromUtf8(evidence.canonicalJson())); + assertThat(encoded.getLease().getEvidenceSha256()).isEqualTo(evidence.sha256()); + if (operation.state() == State.PENDING) { + assertThat(encoded.getState()) + .isEqualTo(GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_PENDING); + assertThat(encoded.hasBindingDecisionId()).isFalse(); + assertThat(encoded.hasOrphanCleanupId()).isFalse(); + assertThat(encoded.getPendingOrphanCleanup()).isFalse(); + } else { + assertThat(encoded.getState()) + .isEqualTo(GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED); + assertThat(encoded.hasBindingDecisionId()).isFalse(); + assertThat(encoded.getOrphanCleanupId()).isEqualTo(cleanup.toString()); + assertThat(encoded.getPendingOrphanCleanup()).isTrue(); + } + } + verifyNoInteractions(abortOwner); + } + + @Test + void readFailuresUseRedactedNonOkStatusAndNeverReturnSuccess() { + var abortOwner = mock(AccountGameplayAdmissionAbortOwner.class); + var readOwner = mock(AccountGameplayAdmissionReadOwner.class); + var service = new AccountGameplayAdmissionLeaseGrpcService(abortOwner, readOwner); + var request = readRequest(AccountGameplayAdmissionAbortOwnerTest.fixture()); + for (var failure : + List.of( + Status.FAILED_PRECONDITION.withDescription("secret mismatch").asRuntimeException(), + Status.UNAVAILABLE.withDescription("secret storage").asRuntimeException())) { + doThrow(failure).when(readOwner).read(request); + var observer = new Capture(); + service.readGameplayAdmissionLease(request, observer); + assertFailure(observer, Status.fromThrowable(failure).getCode()); + assertThat(Status.fromThrowable(observer.failure).getDescription()).doesNotContain("secret"); + assertThat(observer.failure.getCause()).isNull(); + } + doThrow(new IllegalStateException("secret storage")).when(readOwner).read(request); + var unavailable = new Capture(); + service.readGameplayAdmissionLease(request, unavailable); + assertFailure(unavailable, Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(unavailable.failure).getDescription()).doesNotContain("secret"); + + var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); + var committedReadOwner = mock(AccountGameplayAdmissionReadOwner.class); + var committedService = + new AccountGameplayAdmissionLeaseGrpcService(abortOwner, committedReadOwner); + when(committedReadOwner.read(request)) + .thenReturn( + new AccountGameplayAdmissionLeaseOperation( + evidence, State.COMMITTED, UUID.randomUUID(), null)); + var committed = new Capture(); + committedService.readGameplayAdmissionLease(request, committed); + assertFailure(committed, Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(committed.failure).getDescription()).doesNotContain("secret"); + } + + @Test + void mapsMalformedReadEnvelopeToInvalidArgumentBeforeSql() { + var repository = mock(AccountGameplayAdmissionLeaseRepository.class); + var manager = mock(PlatformTransactionManager.class); + var readOwner = new AccountGameplayAdmissionReadOwner(repository, manager, "test"); + var service = + new AccountGameplayAdmissionLeaseGrpcService( + mock(AccountGameplayAdmissionAbortOwner.class), readOwner); + var observer = new Capture(); + + peer() + .run( + () -> + service.readGameplayAdmissionLease( + ReadGameplayAdmissionLeaseRequest.getDefaultInstance(), observer)); + + assertFailure(observer, Status.Code.INVALID_ARGUMENT); + assertThat(Status.fromThrowable(observer.failure).getDescription()) + .isEqualTo("Malformed Account admission lease read request"); + verifyNoInteractions(repository, manager); + } + + private static AccountGameplayAdmissionLeaseGrpcService service( + AccountGameplayAdmissionAbortOwner abortOwner) { + return new AccountGameplayAdmissionLeaseGrpcService( + abortOwner, mock(AccountGameplayAdmissionReadOwner.class)); + } + + private static ReadGameplayAdmissionLeaseRequest readRequest( + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + evidence) { + return ReadGameplayAdmissionLeaseRequest.newBuilder() + .setRequestId((String) evidence.carrier().get("requestId")) + .setExpectedLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence)) + .build(); + } + + private static Context peer() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow()); + } + + private static void assertFailure(Capture observer, Status.Code code) { + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(Status.fromThrowable(observer.failure).getCode()).isEqualTo(code); + } + + private static final class Capture implements StreamObserver { + private T value; + private Throwable failure; + private boolean completed; + + @Override + public void onNext(T value) { + this.value = value; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Test observer retains the exact supplied failure for redaction assertions.") + public void onError(Throwable failure) { + this.failure = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcServiceTest.java new file mode 100644 index 0000000000..65e4f62a04 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountIssuerAuthoritySourceGrpcServiceTest.java @@ -0,0 +1,111 @@ +package unit.net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.accountservice.repository.AccountIssuerSourceSnapshotReadOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountIssuerAuthoritySourceGrpcService; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotEvidence; +import net.firedevops.firemud.common.account.authority.AccountIssuerSourceSnapshotGrpcCodec; +import org.junit.jupiter.api.Test; + +class AccountIssuerAuthoritySourceGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String CALLER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + private final AccountIssuerSourceSnapshotReadOwner owner = + mock(AccountIssuerSourceSnapshotReadOwner.class); + private final AccountIssuerAuthoritySourceGrpcService service = + new AccountIssuerAuthoritySourceGrpcService(owner); + + @Test + void encodesOnlyTheOwnerReturnedClosedSnapshotAndCompletesOnce() { + UUID operation = UUID.randomUUID(); + var typedRequest = + new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, ISSUER, Optional.empty()); + var request = AccountIssuerSourceSnapshotGrpcCodec.toRequest(typedRequest, NAMESPACE, CALLER); + var evidence = + new AccountIssuerSourceSnapshotEvidence( + operation, NAMESPACE, CALLER, ISSUER, "1", "1", STREAM, "0", Optional.empty()); + when(owner.read(request)) + .thenReturn( + new AccountIssuerSourceSnapshotReadOwner.ReadResult(typedRequest, CALLER, evidence)); + var observer = new RecordingObserver(); + + service.readCurrentIssuerAuthoritySource(request, observer); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value).isEqualTo(AccountIssuerSourceSnapshotGrpcCodec.toWire(evidence)); + verify(owner).read(request); + } + + @Test + void preservesCanonicalStatusClassesAndSanitizesTheirDescriptions() { + var observer = new RecordingObserver(); + when(owner.read(any())) + .thenThrow( + Status.FAILED_PRECONDITION + .withDescription("raw SQL row and event payload") + .asRuntimeException()); + + service.readCurrentIssuerAuthoritySource( + ReadCurrentIssuerAuthoritySourceRequest.getDefaultInstance(), observer); + + assertThat(observer.error.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.error.getDescription()).doesNotContain("raw SQL"); + assertThat(observer.completed).isFalse(); + } + + @Test + void mapsMalformedRequestAndUnexpectedOwnerFailureWithoutLeakingDetails() { + var invalid = new RecordingObserver(); + when(owner.read(any())) + .thenThrow( + new IllegalArgumentException("raw request data"), + new IllegalStateException("connection password detail")); + service.readCurrentIssuerAuthoritySource( + ReadCurrentIssuerAuthoritySourceRequest.getDefaultInstance(), invalid); + assertThat(invalid.error.getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(invalid.error.getDescription()).doesNotContain("raw request"); + + var unavailable = new RecordingObserver(); + service.readCurrentIssuerAuthoritySource( + ReadCurrentIssuerAuthoritySourceRequest.getDefaultInstance(), unavailable); + assertThat(unavailable.error.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.error.getDescription()).doesNotContain("password detail"); + } + + private static final class RecordingObserver implements StreamObserver { + private T value; + private Status error; + private boolean completed; + + @Override + public void onNext(T next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticatorTest.java new file mode 100644 index 0000000000..b5657e4550 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionInitialTokenAuthenticatorTest.java @@ -0,0 +1,509 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.RSAKeyGenParameterSpec; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Focused signature/profile tests; owner evidence is mocked and is not DB/Redis runtime proof. */ +class AccountGameplayAdmissionInitialTokenAuthenticatorTest { + private static final Instant NOW = Instant.parse("2026-10-08T00:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final String NAMESPACE = "firemud-test"; + private static final String KID = "account-key-42"; + private static final UUID ACCOUNT_ID = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final UUID TOKEN_JTI = UUID.fromString("1a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"); + private static final UUID OPERATION_ID = UUID.fromString("c5c31332-e560-41c8-a55a-97674e7a317c"); + private static final UUID REQUEST_ID = UUID.fromString("1ee95a1e-83f2-4a63-a7ba-6288e246ac76"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("e16fdce5-96eb-49e1-a9bd-3f429816cbf0"); + private static final String PEER_URI = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final GrpcPeerIdentity GAME_SESSION_PEER = + new GrpcPeerIdentity(PEER_URI, NAMESPACE, "game-session-service"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void acceptsCorrectlySignedInitialTokenAndExactCommittedMetadata() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + + var observation = + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt())); + + assertThat(observation.candidate()).isSameAs(fixture.candidate()); + assertThat(observation.observedAtEpochSecond()).isEqualTo(NOW.getEpochSecond()); + assertThat(observation.toString()).doesNotContain(fixture.compactJwt()); + verify(fixture.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void rejectsAbsentPeerBeforeReadingJwksOrOwnerState() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + + assertDenied( + () -> + withRootContext( + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.jwksLoads().get()).isZero(); + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsWrongPeerBeforeReadingJwksOrOwnerState() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + GrpcPeerIdentity wrongService = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", + NAMESPACE, + "account-service"); + + assertDenied( + () -> + withPeer( + wrongService, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.jwksLoads().get()).isZero(); + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsInvalidSignatureOnOtherwiseValidInitialTokenBeforeOwnerRead() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + String invalidSignature = corruptSignature(fixture.compactJwt()); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(invalidSignature))); + + assertThat(fixture.jwksLoads().get()).isEqualTo(1); + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsWrongTrustedNamespaceBeforeReadingJwksOrOwnerState() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + GrpcPeerIdentity otherNamespace = + new GrpcPeerIdentity( + "spiffe://firemud/ns/other-test/sa/game-session-service", + "other-test", + "game-session-service"); + + assertDenied( + () -> + withPeer( + otherNamespace, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.jwksLoads().get()).isZero(); + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsAValidlySignedTenantBoundTokenAtTheInitialOnlyPolicy() throws Exception { + String tenantId = "fb71a28c-b82f-4f79-9aaf-472324a0011e"; + Map tenantAuthority = new LinkedHashMap<>(initialAuthorityTuple()); + tenantAuthority.put("tenantAuthorityGeneration", Map.of(tenantId, "1")); + tenantAuthority.put("membershipAuthorityGeneration", Map.of(tenantId, "1")); + Map tenantClaims = + Map.of( + "tenantId", tenantId, + "authorityTuple", tenantAuthority, + "membershipVersion", Map.of(tenantId, "1")); + Fixture fixture = fixture(tenantClaims, null, KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.jwksLoads().get()).isZero(); + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsAnyRoleClaimsAtInitialAcquire() throws Exception { + Fixture fixture = fixture(Map.of("globalRoles", List.of("admin")), null, KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsCompactHashThatDiffersFromCommittedCandidate() throws Exception { + Fixture fixture = fixture(Map.of(), "a".repeat(64), KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + verify(fixture.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void rejectsGenerationOrFenceClaimsThatDifferFromCommittedInitialState() throws Exception { + Fixture wrongGeneration = fixture(Map.of("tokenGeneration", "2"), null, KID); + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> + wrongGeneration + .authenticator() + .authenticateInitialToken(wrongGeneration.compactJwt()))); + verify(wrongGeneration.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + + Fixture wrongFence = fixture(Map.of("issuanceFence", "2"), null, KID); + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> + wrongFence.authenticator().authenticateInitialToken(wrongFence.compactJwt()))); + verify(wrongFence.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void rejectsAuthorityTupleThatDoesNotMatchCommittedGlobalVersions() throws Exception { + Map differentAuthority = + GameSessionAccountDelegationProfile.authorityTuple(2L, 1L); + Fixture fixture = fixture(Map.of("authorityTuple", differentAuthority), null, KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + verify(fixture.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void rejectsSignerIdentityOrDurableTimeMismatch() throws Exception { + Fixture wrongSigner = fixture(Map.of(), null, "different-key"); + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> + wrongSigner + .authenticator() + .authenticateInitialToken(wrongSigner.compactJwt()))); + verify(wrongSigner.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + + Fixture wrongExpiry = fixture(Map.of("exp", NOW.getEpochSecond() + 121L), null, KID); + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> + wrongExpiry + .authenticator() + .authenticateInitialToken(wrongExpiry.compactJwt()))); + verify(wrongExpiry.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void rejectsExpiredButOtherwiseValidSignedTokenBeforeOwnerRead() throws Exception { + long issuedAt = NOW.getEpochSecond() - 120L; + Fixture fixture = + fixture( + Map.of( + "iat", issuedAt, + "nbf", issuedAt, + "exp", NOW.getEpochSecond() - 1L), + null, + KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + verifyNoInteractions(fixture.owner()); + } + + @Test + void rejectsChangedSubjectAndAccountAgainstOriginalCandidateWithSameJtiAndPresentedHash() + throws Exception { + UUID otherAccountId = UUID.fromString("751eb539-3238-4aa6-b86c-15d037a765c3"); + Fixture fixture = + fixture( + Map.of("sub", otherAccountId.toString(), "accountId", otherAccountId.toString()), + null, + KID); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.candidate().tokenSha256()).isEqualTo(sha256(fixture.compactJwt())); + verify(fixture.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void ownerFailureIsRedactedAndDenied() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + when(fixture.owner().requireCurrentActiveCommittedCandidateByJti(any())) + .thenThrow(new IllegalStateException("storage detail must not escape")); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + verify(fixture.owner()).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void refusesAmbientSqlTransactionBeforeJwksOrOwnerAccess() throws Exception { + Fixture fixture = fixture(Map.of(), null, KID); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertDenied( + () -> + withPeer( + GAME_SESSION_PEER, + () -> fixture.authenticator().authenticateInitialToken(fixture.compactJwt()))); + + assertThat(fixture.jwksLoads().get()).isZero(); + verifyNoInteractions(fixture.owner()); + } + + private static Fixture fixture( + Map claimOverrides, String storedHash, String committedSignerKid) + throws Exception { + KeyPair keyPair = rsa3072(); + AtomicInteger jwksLoads = new AtomicInteger(); + AccountPublicJwksCache.SourceIdentity sourceIdentity = sourceIdentity(); + byte[] jwks = jwks(KID, (RSAPublicKey) keyPair.getPublic()); + AccountPublicJwksCache cache = + new AccountPublicJwksCache( + () -> { + jwksLoads.incrementAndGet(); + return new AccountPublicJwksCache.PublicJwksSnapshot(sourceIdentity, jwks); + }, + sourceIdentity, + CLOCK, + Duration.ofSeconds(30)); + AccountAsymmetricJwtVerifier verifier = new AccountAsymmetricJwtVerifier(cache, CLOCK); + AccountGameplayDelegationCommittedIssuanceOwner owner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + + Map claims = initialClaims(); + claims.putAll(claimOverrides); + String compactJwt = sign(claims, keyPair); + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + PEER_URI, + CALLER_CONTEXT_ID, + AccountGameplayCredentialRequestBindingFixture.binding(), + "b".repeat(64), + TOKEN_JTI, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(120L).getEpochSecond()); + AccountAuthoritySnapshot authority = + new AccountAuthoritySnapshot(ACCOUNT_ID, 1L, 1L, 1L, 1L, 1L, 1L, Optional.empty()); + CommittedCandidateVerificationData candidate = mock(CommittedCandidateVerificationData.class); + when(candidate.identity()).thenReturn(identity); + when(candidate.authoritySnapshot()).thenReturn(authority); + when(candidate.tokenSha256()).thenReturn(storedHash == null ? sha256(compactJwt) : storedHash); + when(candidate.signerKid()).thenReturn(committedSignerKid); + when(candidate.signerGeneration()).thenReturn("42"); + when(owner.requireCurrentActiveCommittedCandidateByJti(any())).thenReturn(candidate); + + return new Fixture( + new AccountGameplayAdmissionInitialTokenAuthenticator(verifier, owner, NAMESPACE, CLOCK), + owner, + candidate, + compactJwt, + jwksLoads); + } + + private static Map initialClaims() { + Map claims = new LinkedHashMap<>(); + claims.put("iss", GameSessionAccountDelegationProfile.ISSUER); + claims.put("sub", ACCOUNT_ID.toString()); + claims.put("jti", TOKEN_JTI.toString()); + claims.put("accountId", ACCOUNT_ID.toString()); + claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + claims.put("iat", NOW.getEpochSecond()); + claims.put("nbf", NOW.getEpochSecond()); + claims.put("exp", NOW.plusSeconds(120L).getEpochSecond()); + claims.put("tokenGeneration", "1"); + claims.put("authorityTuple", initialAuthorityTuple()); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", "1"); + return claims; + } + + private static Map initialAuthorityTuple() { + return GameSessionAccountDelegationProfile.authorityTuple(1L, 1L); + } + + private static AccountPublicJwksCache.SourceIdentity sourceIdentity() { + return new AccountPublicJwksCache.SourceIdentity( + "prod", + "prod-cluster-1", + "11111111-1111-4111-8111-111111111111", + "firemud-test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "account-api-r1", + "https://kubernetes.example:6443", + "9".repeat(64)); + } + + private static byte[] jwks(String kid, RSAPublicKey key) { + String jwk = + "{\"keys\":[{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\"" + + kid + + "\",\"n\":\"" + + encode(unsigned(key.getModulus())) + + "\",\"e\":\"" + + encode(unsigned(key.getPublicExponent())) + + "\"}]}"; + return jwk.getBytes(StandardCharsets.UTF_8); + } + + private static String sign(Map claims, KeyPair keyPair) throws Exception { + Map header = Map.of("alg", "RS256", "kid", KID, "typ", "JWT"); + String signingInput = + encode(JSON.writeValueAsBytes(header)) + + "." + + encode(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(claims))); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keyPair.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return signingInput + "." + encode(signature.sign()); + } + + private static byte[] unsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + if (bytes.length > 1 && bytes[0] == 0) { + return java.util.Arrays.copyOfRange(bytes, 1, bytes.length); + } + return bytes; + } + + private static String encode(byte[] bytes) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private static String sha256(String value) throws Exception { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.US_ASCII))); + } + + private static KeyPair rsa3072() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(new RSAKeyGenParameterSpec(3072, RSAKeyGenParameterSpec.F4)); + return generator.generateKeyPair(); + } + + private static void assertDenied(Runnable attempt) { + assertThatThrownBy(attempt::run) + .isInstanceOf( + AccountGameplayAdmissionInitialTokenAuthenticator.InitialTokenAuthenticationException + .class) + .hasNoCause() + .hasMessage("Initial Account token authentication failed"); + } + + private static T withPeer(GrpcPeerIdentity peer, java.util.function.Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + return withContext(context, action); + } + + private static T withRootContext(java.util.function.Supplier action) { + return withContext(Context.ROOT, action); + } + + private static T withContext(Context context, java.util.function.Supplier action) { + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static String corruptSignature(String compactJwt) { + String[] parts = compactJwt.split("\\.", -1); + byte[] signature = Base64.getUrlDecoder().decode(parts[2]); + signature[0] ^= 0x01; + return parts[0] + "." + parts[1] + "." + encode(signature); + } + + private record Fixture( + AccountGameplayAdmissionInitialTokenAuthenticator authenticator, + AccountGameplayDelegationCommittedIssuanceOwner owner, + CommittedCandidateVerificationData candidate, + String compactJwt, + AtomicInteger jwksLoads) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwnerTest.java new file mode 100644 index 0000000000..f0114b0dc8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticatedPublicSourceOwnerTest.java @@ -0,0 +1,343 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doReturn; +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 java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.accountservice.dto.AccountGameplayPublicAdmissionSourceSnapshot; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.service.AccountGameplayPublicAdmissionSourceReader; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionInitialTokenAuthenticator; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionInitialTokenAuthenticator.CurrentInitialTokenObservation; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAuthenticatedPublicSourceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAuthenticatedPublicSourceOwner.PublicSourceObservationException; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.DefaultTransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner doubles prove composition only; signed-token and PostgreSQL/Redis proof are separate. */ +class AccountGameplayAuthenticatedPublicSourceOwnerTest { + private static final UUID ACCOUNT = UUID.randomUUID(); + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID OPERATION = UUID.randomUUID(); + private static final UUID REQUEST = UUID.randomUUID(); + private static final UUID JTI = UUID.randomUUID(); + private static final String TOKEN = "compact-secret-token"; + private static final long NOW = 1_800_000_000L; + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeOwnedWritableSerializableSnapshotAndPreservesSources() { + Fixture f = new Fixture(); + + var result = f.observe(); + + assertThat(f.events).containsExactly("authenticate", "begin", "source", "commit"); + assertThat(f.transactions.definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_SERIALIZABLE); + assertThat(f.transactions.definition.isReadOnly()).isFalse(); + assertThat(f.transactions.definition.getTimeout()).isEqualTo(3); + assertThat(result.tokenIdentity()).isEqualTo(f.identity); + assertThat(result.tokenIssuedAtEpochSecond()).isEqualTo(NOW - 5); + assertThat(result.tokenExpiresAtEpochSecond()).isEqualTo(NOW + 20); + assertThat(result.capturedAtEpochSecond()).isEqualTo(NOW); + assertThat(result.sourceSnapshot()).isSameAs(f.snapshot); + assertThat(result.toString()).contains("non-authorizing", "redacted").doesNotContain(TOKEN); + verify(f.sources).readCurrent(ACCOUNT, TENANT, f.identity); + // No comparison with the initial token's empty membershipVersion: current evidence is kept. + } + + @Test + void ambientTransactionRejectsBeforeAuthentication() { + Fixture f = new Fixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertDenied(f); + + verifyNoInteractions(f.authenticator, f.sources); + assertThat(f.events).isEmpty(); + } + + @Test + void authenticationFailureNeverStartsSourceTransaction() { + Fixture f = new Fixture(); + doThrow(new IllegalStateException(TOKEN)).when(f.authenticator).authenticateInitialToken(TOKEN); + + assertDenied(f); + + assertThat(f.events).isEmpty(); + verifyNoInteractions(f.sources); + } + + @Test + void rejectsWrongSubjectsTenantLifecycleGlobalGenerationFenceCutoffAndSqlIdentity() { + List> changes = + List.of( + f -> when(f.snapshot.membershipSource().membership().accountId()).thenReturn(TENANT), + f -> when(f.snapshot.membershipSource().membership().tenantId()).thenReturn(ACCOUNT), + f -> when(f.snapshot.accountLifecycleState()).thenReturn(AccountLifecycleState.DELETED), + f -> + when(f.snapshot.membershipSource().currentAuthority().issuer().generation()) + .thenReturn(2L), + f -> + when(f.snapshot.membershipSource().currentAuthority().account().generation()) + .thenReturn(2L), + f -> + when(f.snapshot.membershipSource().issuerAccountSources().issuer().generation()) + .thenReturn(2L), + f -> + when(f.snapshot.membershipSource().issuerAccountSources().account().generation()) + .thenReturn(2L), + f -> + when(f.snapshot.membershipSource().issuerAccountSources().account().scope()) + .thenReturn(AuthorityScope.account(TENANT)), + f -> + when(f.snapshot.membershipSource().currentAuthority().issuanceFence()) + .thenReturn(new IssuanceFence(ACCOUNT, 2, 2)), + f -> + when(f.snapshot + .membershipSource() + .issuerAccountSources() + .account() + .accountSecurityCutoff()) + .thenReturn(null), + f -> + when(f.snapshot.tokenIdentityFence()) + .thenReturn( + new AccountGameplayTokenIdentityFence( + new TokenIdentity( + ACCOUNT, OPERATION, REQUEST, "b".repeat(64), JTI, NOW - 5, 1, 1), + 1, + State.ACTIVE, + null, + null)), + f -> + when(f.snapshot.tokenIdentityFence()) + .thenReturn( + new AccountGameplayTokenIdentityFence( + f.identity, 2, State.PENDING, UUID.randomUUID(), "c".repeat(64)))); + for (Consumer change : changes) { + Fixture f = new Fixture(); + change.accept(f); + + assertDenied(f); + + assertThat(f.events).containsExactly("authenticate", "begin", "source", "rollback"); + } + } + + @Test + void changedApplicableAccountCutoffRejects() { + Fixture f = new Fixture(); + AccountAuthoritySnapshot signed = mock(AccountAuthoritySnapshot.class); + when(signed.accountId()).thenReturn(ACCOUNT); + when(signed.issuerGeneration()).thenReturn(1L); + when(signed.accountGeneration()).thenReturn(1L); + when(signed.issuanceFence()).thenReturn(1L); + when(signed.accountSecurityCutoff()) + .thenReturn( + Optional.of(mock(GameSessionAccountDelegationProfile.AccountSecurityCutoff.class))); + when(f.candidate.authoritySnapshot()).thenReturn(signed); + + assertDenied(f); + } + + @Test + void expiryBeforeSourceReadAndDuringReadRejects() { + Fixture before = new Fixture(); + when(before.clock.instant()).thenReturn(Instant.ofEpochSecond(NOW + 20)); + assertDenied(before); + verifyNoInteractions(before.sources); + + Fixture during = new Fixture(); + when(during.clock.instant()) + .thenReturn( + Instant.ofEpochSecond(NOW), + Instant.ofEpochSecond(NOW), + Instant.ofEpochSecond(NOW + 20)); + assertDenied(during); + assertThat(during.events).containsExactly("authenticate", "begin", "source", "rollback"); + } + + @Test + void expiryDuringTransactionCompletionRejectsReturnedObservation() { + Fixture f = new Fixture(); + when(f.clock.instant()) + .thenReturn( + Instant.ofEpochSecond(NOW), + Instant.ofEpochSecond(NOW), + Instant.ofEpochSecond(NOW), + Instant.ofEpochSecond(NOW + 20)); + + assertDenied(f); + + assertThat(f.events).containsExactly("authenticate", "begin", "source", "commit"); + } + + @Test + void unavailableSourcesAndIncorrectTransactionContextFailClosed() { + Fixture unavailable = new Fixture(); + doThrow(new IllegalStateException(TOKEN)) + .when(unavailable.sources) + .readCurrent(ACCOUNT, TENANT, unavailable.identity); + assertDenied(unavailable); + + Fixture missing = new Fixture(); + doReturn(null).when(missing.sources).readCurrent(ACCOUNT, TENANT, missing.identity); + assertDenied(missing); + + Fixture wrongIsolation = new Fixture(); + wrongIsolation.transactions.establishedIsolation = + TransactionDefinition.ISOLATION_READ_COMMITTED; + assertDenied(wrongIsolation); + verifyNoInteractions(wrongIsolation.sources); + } + + private static void assertDenied(Fixture f) { + assertThatThrownBy(f::observe) + .isInstanceOf(PublicSourceObservationException.class) + .hasMessage("Current Account public source observation failed") + .hasNoCause(); + } + + private static final class Fixture { + private final List events = new ArrayList<>(); + private final AccountGameplayAdmissionInitialTokenAuthenticator authenticator = + mock(AccountGameplayAdmissionInitialTokenAuthenticator.class); + private final AccountGameplayPublicAdmissionSourceReader sources = + mock(AccountGameplayPublicAdmissionSourceReader.class); + private final CommittedCandidateVerificationData candidate = + mock(CommittedCandidateVerificationData.class); + private final AccountGameplayPublicAdmissionSourceSnapshot snapshot = + mock(AccountGameplayPublicAdmissionSourceSnapshot.class, RETURNS_DEEP_STUBS); + private final Clock clock = mock(Clock.class); + private final RecordingTransactions transactions = new RecordingTransactions(events); + private final TokenIdentity identity = + new TokenIdentity(ACCOUNT, OPERATION, REQUEST, "a".repeat(64), JTI, NOW - 5, 1, 1); + private final AccountGameplayAuthenticatedPublicSourceOwner owner; + + private Fixture() { + when(clock.instant()).thenReturn(Instant.ofEpochSecond(NOW)); + var pending = mock(AccountGameplayDelegationPendingIdentity.class); + when(pending.accountId()).thenReturn(ACCOUNT); + when(pending.operationId()).thenReturn(OPERATION); + when(pending.requestId()).thenReturn(REQUEST); + when(pending.tokenJti()).thenReturn(JTI); + when(pending.issuedAtEpochSecond()).thenReturn(NOW - 5); + when(pending.notBeforeEpochSecond()).thenReturn(NOW - 5); + when(pending.expiresAtEpochSecond()).thenReturn(NOW + 20); + when(candidate.identity()).thenReturn(pending); + when(candidate.tokenSha256()).thenReturn("a".repeat(64)); + when(candidate.authoritySnapshot()) + .thenReturn(new AccountAuthoritySnapshot(ACCOUNT, 1, 1, 1, 1, 1, 1, Optional.empty())); + var observation = mock(CurrentInitialTokenObservation.class); + when(observation.candidate()).thenReturn(candidate); + when(authenticator.authenticateInitialToken(TOKEN)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("authenticate"); + return observation; + }); + when(snapshot.accountLifecycleState()).thenReturn(AccountLifecycleState.ACTIVE); + when(snapshot.membershipSource().membership().accountId()).thenReturn(ACCOUNT); + when(snapshot.membershipSource().membership().tenantId()).thenReturn(TENANT); + var issuerScope = AuthorityScope.issuer(GameSessionAccountDelegationProfile.ISSUER); + var accountScope = AuthorityScope.account(ACCOUNT); + var current = snapshot.membershipSource().currentAuthority(); + when(current.issuer().scope()).thenReturn(issuerScope); + when(current.account().scope()).thenReturn(accountScope); + when(current.issuer().generation()).thenReturn(1L); + when(current.account().generation()).thenReturn(1L); + var fence = new IssuanceFence(ACCOUNT, 1, 1); + when(current.issuanceFence()).thenReturn(fence); + var source = snapshot.membershipSource().issuerAccountSources(); + when(source.issuer().scope()).thenReturn(issuerScope); + when(source.account().scope()).thenReturn(accountScope); + when(source.issuer().generation()).thenReturn(1L); + when(source.account().generation()).thenReturn(1L); + when(source.account().accountSecurityCutoff()).thenReturn(Optional.empty()); + when(source.issuanceFence()).thenReturn(fence); + when(source.account().issuanceFence()).thenReturn(fence); + when(snapshot.tokenIdentityFence()) + .thenReturn(new AccountGameplayTokenIdentityFence(identity, 1, State.ACTIVE, null, null)); + when(sources.readCurrent(ACCOUNT, TENANT, identity)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + events.add("source"); + return snapshot; + }); + owner = + new AccountGameplayAuthenticatedPublicSourceOwner( + authenticator, sources, transactions, clock, 3); + } + + private AccountGameplayAuthenticatedPublicSourceOwner.CurrentPublicSourceObservation observe() { + return owner.observeCurrent(TOKEN, TENANT); + } + } + + private static final class RecordingTransactions implements PlatformTransactionManager { + private final List events; + private TransactionDefinition definition; + private int establishedIsolation = TransactionDefinition.ISOLATION_SERIALIZABLE; + + private RecordingTransactions(List events) { + this.events = events; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + this.definition = definition == null ? new DefaultTransactionDefinition() : definition; + events.add("begin"); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(this.definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(establishedIsolation); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + events.add("commit"); + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + events.add("rollback"); + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java new file mode 100644 index 0000000000..c746be4046 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java @@ -0,0 +1,217 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +/** Pure encoding fixtures are not owner/currentness or installation proof. */ +public class AccountSelectedGameplayAuthorityProjectionTest { + public static final UUID TENANT = UUID.fromString("6271a559-6f2d-4f82-bb1e-9d4c13884e51"); + public static final UUID ACCOUNT = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + + @Test + void independentMembershipVersionAndGenerationSurviveExactEventRoundTrip() { + var value = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "1", "7", "2"), 9L); + assertThat(value.generation()).isEqualTo(new BigInteger("2")); + assertThat(value.membershipVersion()).isEqualTo(new BigInteger("7")); + assertThat(value.sourceVersion()).isEqualTo(new BigInteger("9")); + assertThat( + AccountSelectedGameplayAuthorityProjection.decode( + value.canonicalBytes(), ACCOUNT, TENANT) + .canonicalBytes()) + .containsExactly(value.canonicalBytes()); + assertThatThrownBy( + () -> + AccountSelectedGameplayAuthorityProjection.decode( + value.canonicalBytes(), UUID.randomUUID(), TENANT)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void noSequenceGapEqualCheckpointConflictOrRegressionIsAdopted() { + var first = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "1", "7", "2"), 9L); + first.requireSuccessorOf(null); + first.requireSuccessorOf(first); + var second = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "2", "8", "2"), 9L); + second.requireSuccessorOf(first); // Non-revoking version advancement is independent. + var gap = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "3", "9", "2"), 9L); + assertThatThrownBy(() -> gap.requireSuccessorOf(first)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> second.requireSuccessorOf(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> first.requireSuccessorOf(second)) + .isInstanceOf(IllegalArgumentException.class); + var conflict = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "1", "8", "2"), 9L); + assertThatThrownBy(() -> conflict.requireSuccessorOf(first)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void duplicateExtraAliasAndMissingEventFailClosed() { + var value = + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "1", "7", "2"), 9L); + String json = new String(value.canonicalBytes(), StandardCharsets.UTF_8); + for (String malformed : + List.of( + json.replace( + "\"sourceVersion\":\"9\"", "\"sourceVersion\":\"9\",\"sourceVersion\":\"9\""), + json.replace("\"sourceVersion\":\"9\"", "\"generation\":\"9\""), + json.replace("\"sourceVersion\":\"9\"", "\"sourceVersion\":\"9\",\"extra\":true"), + json.replace("\"sourceVersion\":\"9\"", "\"sourceVersion\":9"))) { + assertThatThrownBy( + () -> + AccountSelectedGameplayAuthorityProjection.decode( + malformed.getBytes(StandardCharsets.UTF_8), ACCOUNT, TENANT)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void tenantProjectionUsesAuthorityStreamNotLinkedBillingStream() { + var event = tenant(TENANT); + var value = AccountSelectedGameplayAuthorityProjection.tenant(event); + assertThat(new String(value.canonicalBytes(), StandardCharsets.UTF_8)) + .contains("account:auth-authority:v1:tenant/" + TENANT) + .contains("account:tenant-entitlement:v1:tenant/" + TENANT); + assertThat(value.key()).isEqualTo("session:auth:generation:tenant:" + TENANT); + assertThat( + AccountSelectedGameplayAuthorityProjection.decode(value.canonicalBytes(), null, TENANT) + .canonicalBytes()) + .containsExactly(value.canonicalBytes()); + } + + public static byte[][] selected(byte[][] initial, UUID account, UUID tenant) { + return new byte[][] { + initial[0], + initial[1], + AccountSelectedGameplayAuthorityProjection.tenant(tenant(tenant)).canonicalBytes(), + AccountSelectedGameplayAuthorityProjection.membership( + member(account, tenant, "1", "2", "1"), 1L) + .canonicalBytes() + }; + } + + public static byte[][] selected( + byte[][] initial, + TenantAuthorityEventV1Codec.Event tenant, + MembershipAuthorityEventV1Codec.MembershipEvent member, + long memberSourceVersion) { + return new byte[][] { + initial[0], + initial[1], + AccountSelectedGameplayAuthorityProjection.tenant(tenant).canonicalBytes(), + AccountSelectedGameplayAuthorityProjection.membership(member, memberSourceVersion) + .canonicalBytes() + }; + } + + public static byte[] membershipBytes( + UUID account, UUID tenant, String sequence, String version, String generation) { + return AccountSelectedGameplayAuthorityProjection.membership( + member(account, tenant, sequence, version, generation), 1L) + .canonicalBytes(); + } + + public static MembershipAuthorityEventV1Codec.MembershipEvent member( + UUID account, UUID tenant, String sequence, String version, String generation) { + return MembershipAuthorityEventV1Codec.seal( + Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", "member-event-" + sequence), + Map.entry("requestId", "member-request-" + sequence), + Map.entry( + "outboxStreamKey", + "account:auth-authority:v1:membership/" + account + "/" + tenant), + Map.entry("outboxSequence", sequence), + Map.entry("sourceScope", "membership/" + account + "/" + tenant), + Map.entry("accountId", account.toString()), + Map.entry("tenantId", tenant.toString()), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(tenant.toString(), version)), + Map.entry("membershipAuthorityGeneration", generation), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenant.toString(), "2"), + "membershipAuthorityGeneration", + Map.of(tenant.toString(), generation), + "privateRealmGrantVersions", + List.of())), + Map.entry("issuanceFence", "1"), + Map.entry("roles", List.of("player")), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false))); + } + + public static TenantAuthorityEventV1Codec.Event tenant(UUID tenant) { + UUID creation = UUID.fromString("72a18e29-57c0-48be-a9e7-bd7b681d7720"); + UUID operation = UUID.fromString("a750fb1f-3e5d-40e6-b51e-160ef64d24ec"); + String digest = "sha256:" + "a".repeat(64); + var source = + new FreshTenantCreationEvidence( + 1, + "account-service", + creation, + operation, + digest, + tenant, + 91L, + "demo-source", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "account-service", + creation, + operation, + digest, + tenant, + 91L, + "demo-source", + "NEW_GAME_ROW")); + var request = + new DemoTenantEntitlementRequest( + UUID.fromString("15aad6f4-3c5b-4cd9-b1b9-654e6d9bc51a"), + tenant, + creation, + digest, + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(1L, 1L, 1L)); + var billing = DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 2L, 2L, 1L); + return TenantAuthorityEventV1Codec.seal(request, source, 2L, 2L, 1L, billing); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBindingFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBindingFixture.java new file mode 100644 index 0000000000..7123f0a367 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBindingFixture.java @@ -0,0 +1,11 @@ +package net.firedevops.firemud.accountservice.repository; + +/** Deterministic, non-production keyed-binding fixture shared by the Account owner proofs. */ +public final class AccountGameplayCredentialRequestBindingFixture { + private AccountGameplayCredentialRequestBindingFixture() {} + + public static AccountGameplayCredentialRequestBinding binding() { + return new AccountGameplayCredentialRequestBinding( + 1, "test-account-login-key", "ab".repeat(32)); + } +} diff --git a/services/common-platform-core/build.gradle.kts b/services/common-platform-core/build.gradle.kts index 7e67ecc121..c0ff7af025 100644 --- a/services/common-platform-core/build.gradle.kts +++ b/services/common-platform-core/build.gradle.kts @@ -16,6 +16,7 @@ dependencies { implementation(libs.opentelemetry.sdk) implementation(libs.opentelemetry.exporter.otlp) implementation(libs.spring.boot.starter) + implementation("org.springframework:spring-tx") implementation(libs.spring.boot.starter.actuator) implementation(libs.spring.boot.starter.validation) compileOnly(libs.spring.boot.starter.web) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClient.java new file mode 100644 index 0000000000..a4e63c239e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClient.java @@ -0,0 +1,224 @@ +package net.firedevops.firemud.common.account.authority; + +import io.grpc.ManagedChannel; +import jakarta.annotation.PostConstruct; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.util.Collection; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceServiceGrpc; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered, fail-closed mTLS client for Account's issuer-authority source read. */ +public final class AccountIssuerAuthoritySourceClient + extends AbstractReloadingBlockingGrpcClient< + AccountIssuerAuthoritySourceServiceGrpc.AccountIssuerAuthoritySourceServiceBlockingStub> { + private static final Duration RPC_DEADLINE = Duration.ofSeconds(5); + private static final int DEFAULT_PORT = 6565; + + private final String configuredNamespace; + private final String clientWorkloadUri; + private final String accountWorkloadUri; + private final CommonGrpcClientProperties tlsPropertiesForValidation; + private volatile boolean initialized; + private volatile boolean clientClosed; + + public AccountIssuerAuthoritySourceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String configuredNamespace) { + super( + Objects.requireNonNull(endpoints, "endpoints is required"), + requireFileBackedMutualTls(tlsProperties), + Objects.requireNonNull(channelFactory, "channelFactory is required"), + AccountIssuerAuthoritySourceClient.class); + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("configuredNamespace must be one canonical DNS label"); + } + this.configuredNamespace = configuredNamespace; + this.clientWorkloadUri = + "spiffe://firemud/ns/" + configuredNamespace + "/sa/game-session-service"; + this.accountWorkloadUri = "spiffe://firemud/ns/" + configuredNamespace + "/sa/account-service"; + this.tlsPropertiesForValidation = tlsProperties.copy(); + } + + /** + * Initializes this explicitly constructed client; it is not component-scanned or auto-configured. + */ + @PostConstruct + public synchronized void init() throws SSLException, IOException { + if (clientClosed) { + throw new IllegalStateException("issuer-source client is closed"); + } + if (initialized) { + return; + } + try { + validateFileBackedMutualTls(); + initReloadingClient(); + initialized = true; + } catch (IOException | RuntimeException | Error failure) { + clientClosed = true; + throw failure; + } + } + + /** + * Reads and independently validates the exact Account issuer snapshot for the supplied request. + */ + public AccountIssuerSourceSnapshotEvidence read( + AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request) { + requireReadableLifecycle(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "issuer-source read cannot run inside an ambient transaction or synchronization"); + } + Objects.requireNonNull(request, "request is required"); + + // A hot-reloaded certificate must retain the exact client workload identity before any RPC is + // sent. + validateFileBackedMutualTls(); + var wireRequest = + AccountIssuerSourceSnapshotGrpcCodec.toRequest( + request, configuredNamespace, clientWorkloadUri); + AccountIssuerAuthoritySourceSnapshot wireResponse = + stub() + .withDeadlineAfter(RPC_DEADLINE.toMillis(), TimeUnit.MILLISECONDS) + .readCurrentIssuerAuthoritySource(wireRequest); + return decodeResponse(wireResponse, request, clientWorkloadUri); + } + + @Override + public synchronized void close() throws IOException { + clientClosed = true; + initialized = false; + super.close(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected int defaultPort() { + return DEFAULT_PORT; + } + + @Override + protected AccountIssuerAuthoritySourceServiceGrpc.AccountIssuerAuthoritySourceServiceBlockingStub + buildStub(ManagedChannel channel) { + return AccountIssuerAuthoritySourceServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(accountWorkloadUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(accountWorkloadUri)); + } + + static AccountIssuerSourceSnapshotEvidence decodeResponse( + AccountIssuerAuthoritySourceSnapshot wireResponse, + AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request, + String authenticatedCallerWorkload) { + return AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + wireResponse, request, authenticatedCallerWorkload); + } + + private void requireReadableLifecycle() { + if (clientClosed) { + throw new IllegalStateException("issuer-source client is closed"); + } + if (!initialized || stub() == null) { + throw new IllegalStateException("issuer-source client is not initialized"); + } + } + + private void validateFileBackedMutualTls() { + requireFileBackedMutualTls(tlsPropertiesForValidation); + validateClientCertificateIdentity(); + } + + private static CommonGrpcClientProperties requireFileBackedMutualTls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "issuer-source client requires TLS with file-backed client mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certChain"); + requireReadableFile(tlsProperties.getPrivateKey(), "privateKey"); + requireReadableFile(tlsProperties.getCaCert(), "caCert"); + return tlsProperties; + } + + private void validateClientCertificateIdentity() { + CommonGrpcClientProperties tlsProperties = currentTlsProperties(); + String certificatePath = tlsProperties.getCertChain(); + if (certificatePath == null || certificatePath.isBlank()) { + throw new IllegalStateException("issuer-source client certificate chain is not configured"); + } + Path path = Path.of(certificatePath); + try (InputStream input = Files.newInputStream(path)) { + Collection certificates = + CertificateFactory.getInstance("X.509").generateCertificates(input); + if (certificates.isEmpty() + || !(certificates.iterator().next() instanceof X509Certificate leaf)) { + throw new IllegalStateException("issuer-source client certificate chain has no X.509 leaf"); + } + GrpcPeerIdentity identity = + GrpcPeerIdentity.fromCertificate(leaf) + .orElseThrow( + () -> + new IllegalStateException( + "issuer-source client leaf must contain one canonical workload URI SAN")); + if (!clientWorkloadUri.equals(identity.uri())) { + throw new IllegalStateException( + "issuer-source client leaf SAN must match the configured Game Session workload"); + } + } catch (IOException | java.security.cert.CertificateException failure) { + throw new IllegalStateException( + "issuer-source client certificate chain cannot be read", failure); + } + } + + private static void requireReadableFile(String configuredPath, String name) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException("issuer-source client " + name + " file is required"); + } + Path path; + try { + path = Path.of(configuredPath); + } catch (RuntimeException invalidPath) { + throw new IllegalArgumentException( + "issuer-source client " + name + " must be a file-backed path", invalidPath); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "issuer-source client " + name + " must be a readable regular file"); + } + } + + private CommonGrpcClientProperties currentTlsProperties() { + return tlsPropertiesForValidation; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidence.java new file mode 100644 index 0000000000..20cc916ad6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidence.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.common.account.authority; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Immutable, closed Account issuer-source snapshot evidence. Shape validation alone does not + * authenticate an Account response or authorize a Game Session projection update. + */ +public record AccountIssuerSourceSnapshotEvidence( + UUID reconciliationOperationId, + String targetNamespace, + String callerWorkload, + String issuerId, + String issuerAuthGeneration, + String sourceVersion, + String outboxStreamKey, + String lastCommittedOutboxSequence, + Optional sourceEvent) { + public static final int SCHEMA_VERSION = 1; + public static final String ISSUER_ID = "firemud-account-service"; + public static final String ISSUER_STREAM_KEY = + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + "issuer/" + ISSUER_ID; + public static final int MAX_SOURCE_EVENT_BYTES = 64 * 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern NONNEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]*)"); + + public AccountIssuerSourceSnapshotEvidence { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + validateCallerWorkload(targetNamespace, callerWorkload); + requireNonNil(reconciliationOperationId, "reconciliationOperationId"); + if (!ISSUER_ID.equals(issuerId)) { + throw new IllegalArgumentException("issuerId must be the supported Account issuer"); + } + if (!ISSUER_STREAM_KEY.equals(outboxStreamKey)) { + throw new IllegalArgumentException("outboxStreamKey must be the canonical issuer stream"); + } + requirePositiveDecimal(issuerAuthGeneration, "issuerAuthGeneration"); + requirePositiveDecimal(sourceVersion, "sourceVersion"); + BigInteger sequence = + requireNonnegativeDecimal(lastCommittedOutboxSequence, "lastCommittedOutboxSequence"); + sourceEvent = Objects.requireNonNull(sourceEvent, "sourceEvent presence is required"); + + if (sequence.signum() == 0) { + if (!"1".equals(issuerAuthGeneration) || !"1".equals(sourceVersion)) { + throw new IllegalArgumentException( + "sequence-zero issuer source must have generation and source version one"); + } + if (sourceEvent.isPresent()) { + throw new IllegalArgumentException("sequence-zero issuer source must omit sourceEvent"); + } + } else { + BigInteger generation = new BigInteger(issuerAuthGeneration); + BigInteger version = new BigInteger(sourceVersion); + if (generation.compareTo(BigInteger.ONE) <= 0 || version.compareTo(BigInteger.ONE) <= 0) { + throw new IllegalArgumentException( + "advanced issuer source must have generation and source version greater than one"); + } + String canonicalEvent = + sourceEvent.orElseThrow( + () -> new IllegalArgumentException("positive issuer sequence requires sourceEvent")); + byte[] eventBytes = strictUtf8(canonicalEvent, "sourceEvent"); + if (eventBytes.length == 0 || eventBytes.length > MAX_SOURCE_EVENT_BYTES) { + throw new IllegalArgumentException("sourceEvent must be nonempty and at most 64 KiB"); + } + verifyIssuerEvent( + canonicalEvent, issuerAuthGeneration, sourceVersion, lastCommittedOutboxSequence); + } + } + + /** Returns fresh UTF-8 storage on every call so callers cannot mutate retained evidence. */ + public Optional sourceEventBytes() { + return sourceEvent.map(value -> strictUtf8(value, "sourceEvent")); + } + + public static void validateCallerWorkload(String targetNamespace, String callerWorkload) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + String expected = "spiffe://firemud/ns/" + targetNamespace + "/sa/game-session-service"; + var identity = GrpcPeerIdentity.parseUri(callerWorkload); + if (identity.isEmpty() + || !expected.equals(callerWorkload) + || !identity.orElseThrow().isInNamespace(targetNamespace) + || !identity.orElseThrow().isService("game-session-service")) { + throw new IllegalArgumentException( + "callerWorkload must be the canonical same-namespace Game Session SPIFFE URI"); + } + } + + private static void verifyIssuerEvent( + String canonicalEvent, String generation, String version, String sequence) { + AccountAuthoritySourceEventV1Codec.SourceEvent verified = + AccountAuthoritySourceEventV1Codec.verify(canonicalEvent); + if (!(verified instanceof AccountAuthoritySourceEventV1Codec.IssuerEvent issuerEvent)) { + throw new IllegalArgumentException("sourceEvent must use the closed issuer event schema"); + } + if (!canonicalEvent.equals(issuerEvent.canonicalJson())) { + throw new IllegalArgumentException("sourceEvent must use the exact canonical JSON encoding"); + } + if (!issuerEvent.eventId().equals(issuerEvent.requestId())) { + throw new IllegalArgumentException("issuer source eventId must equal requestId"); + } + if (!ISSUER_ID.equals(issuerEvent.issuerId()) + || !ISSUER_STREAM_KEY.equals(issuerEvent.outboxStreamKey()) + || !generation.equals(issuerEvent.issuerAuthGeneration()) + || !version.equals(issuerEvent.sourceVersion()) + || !sequence.equals(issuerEvent.outboxSequence())) { + throw new IllegalArgumentException( + "issuer source event must exactly match the snapshot issuer checkpoint"); + } + } + + private static BigInteger requirePositiveDecimal(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (!POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a positive canonical decimal string"); + } + return new BigInteger(value); + } + + private static BigInteger requireNonnegativeDecimal(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (!NONNEGATIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a nonnegative canonical decimal string"); + } + return new BigInteger(value); + } + + private static byte[] strictUtf8(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException(field + " is not valid Unicode for UTF-8", malformed); + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodec.java new file mode 100644 index 0000000000..688f4faee6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodec.java @@ -0,0 +1,250 @@ +package net.firedevops.firemud.common.account.authority; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Strict closed-proto mapping for the Account issuer-source owner read. */ +public final class AccountIssuerSourceSnapshotGrpcCodec { + private AccountIssuerSourceSnapshotGrpcCodec() {} + + /** Immutable request value; unknown wire fields are rejected before one can be constructed. */ + public record ReadRequest( + UUID reconciliationOperationId, + String targetNamespace, + String issuerId, + Optional expectedSource) { + public ReadRequest { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(reconciliationOperationId, "reconciliationOperationId"); + if (!AccountIssuerSourceSnapshotEvidence.ISSUER_ID.equals(issuerId)) { + throw new IllegalArgumentException("issuerId must be the supported Account issuer"); + } + expectedSource = + Objects.requireNonNull(expectedSource, "expectedSource presence is required"); + expectedSource.ifPresent( + source -> + requireRequestBinding(source, targetNamespace, reconciliationOperationId, issuerId)); + } + } + + public static ReadCurrentIssuerAuthoritySourceRequest toRequest( + ReadRequest request, String configuredNamespace, String authenticatedCallerWorkload) { + validateCallContext(configuredNamespace, authenticatedCallerWorkload); + requireConfiguredNamespace(request, configuredNamespace); + request + .expectedSource() + .ifPresent(source -> requireCaller(source, authenticatedCallerWorkload)); + + ReadCurrentIssuerAuthoritySourceRequest.Builder builder = + ReadCurrentIssuerAuthoritySourceRequest.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setReconciliationOperationId(request.reconciliationOperationId().toString()) + .setIssuerId(request.issuerId()); + request.expectedSource().ifPresent(source -> builder.setExpectedSource(toWire(source))); + return builder.build(); + } + + public static ReadRequest fromRequest( + ReadCurrentIssuerAuthoritySourceRequest wire, + String configuredNamespace, + String authenticatedCallerWorkload) { + requireNoUnknownFields(wire, "issuer source request"); + validateCallContext(configuredNamespace, authenticatedCallerWorkload); + requireSchemaVersion(wire.getSchemaVersion(), "issuer source request"); + Optional expected = + wire.hasExpectedSource() + ? Optional.of(fromWire(wire.getExpectedSource())) + : Optional.empty(); + ReadRequest request = + new ReadRequest( + canonicalNonNilUuid(wire.getReconciliationOperationId(), "reconciliationOperationId"), + wire.getTargetNamespace(), + wire.getIssuerId(), + expected); + requireConfiguredNamespace(request, configuredNamespace); + request + .expectedSource() + .ifPresent(source -> requireCaller(source, authenticatedCallerWorkload)); + return request; + } + + /** Maps the response only when it still matches the exact request and authenticated caller. */ + public static AccountIssuerAuthoritySourceSnapshot toResponse( + AccountIssuerSourceSnapshotEvidence source, + ReadRequest request, + String authenticatedCallerWorkload) { + validateCallContext(request.targetNamespace(), authenticatedCallerWorkload); + requireResponseBinding(source, request, authenticatedCallerWorkload); + return toWire(source); + } + + /** Parses a response without permitting a changed source to replace an expected snapshot. */ + public static AccountIssuerSourceSnapshotEvidence fromResponse( + AccountIssuerAuthoritySourceSnapshot wire, + ReadRequest request, + String authenticatedCallerWorkload) { + AccountIssuerSourceSnapshotEvidence source = fromWire(wire); + validateCallContext(request.targetNamespace(), authenticatedCallerWorkload); + requireResponseBinding(source, request, authenticatedCallerWorkload); + return source; + } + + public static AccountIssuerAuthoritySourceSnapshot toWire( + AccountIssuerSourceSnapshotEvidence source) { + AccountIssuerAuthoritySourceSnapshot.Builder builder = + AccountIssuerAuthoritySourceSnapshot.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .setTargetNamespace(source.targetNamespace()) + .setCallerWorkload(source.callerWorkload()) + .setReconciliationOperationId(source.reconciliationOperationId().toString()) + .setIssuerId(source.issuerId()) + .setIssuerAuthGeneration(source.issuerAuthGeneration()) + .setSourceVersion(source.sourceVersion()) + .setOutboxStreamKey(source.outboxStreamKey()) + .setLastCommittedOutboxSequence(source.lastCommittedOutboxSequence()); + source + .sourceEventBytes() + .ifPresent(bytes -> builder.setSourceEvent(ByteString.copyFrom(bytes))); + return builder.build(); + } + + public static AccountIssuerSourceSnapshotEvidence fromWire( + AccountIssuerAuthoritySourceSnapshot wire) { + requireNoUnknownFields(wire, "issuer source snapshot"); + requireSchemaVersion(wire.getSchemaVersion(), "issuer source snapshot"); + Optional sourceEvent = + wire.hasSourceEvent() + ? Optional.of(decodeUtf8(wire.getSourceEvent().toByteArray(), "sourceEvent")) + : Optional.empty(); + return new AccountIssuerSourceSnapshotEvidence( + canonicalNonNilUuid(wire.getReconciliationOperationId(), "reconciliationOperationId"), + wire.getTargetNamespace(), + wire.getCallerWorkload(), + wire.getIssuerId(), + wire.getIssuerAuthGeneration(), + wire.getSourceVersion(), + wire.getOutboxStreamKey(), + wire.getLastCommittedOutboxSequence(), + sourceEvent); + } + + private static void requireResponseBinding( + AccountIssuerSourceSnapshotEvidence source, + ReadRequest request, + String authenticatedCallerWorkload) { + requireRequestBinding(source, request); + requireCaller(source, authenticatedCallerWorkload); + request + .expectedSource() + .ifPresent( + expected -> { + if (!expected.equals(source)) { + throw new IllegalArgumentException( + "current issuer source differs from the exact expected snapshot"); + } + }); + } + + private static void requireRequestBinding( + AccountIssuerSourceSnapshotEvidence source, ReadRequest request) { + requireRequestBinding( + source, request.targetNamespace(), request.reconciliationOperationId(), request.issuerId()); + } + + private static void requireRequestBinding( + AccountIssuerSourceSnapshotEvidence source, + String targetNamespace, + UUID reconciliationOperationId, + String issuerId) { + if (!source.targetNamespace().equals(targetNamespace) + || !source.reconciliationOperationId().equals(reconciliationOperationId) + || !source.issuerId().equals(issuerId)) { + throw new IllegalArgumentException("issuer source snapshot does not match the request scope"); + } + } + + private static void requireCaller( + AccountIssuerSourceSnapshotEvidence source, String authenticatedCallerWorkload) { + if (!source.callerWorkload().equals(authenticatedCallerWorkload)) { + throw new IllegalArgumentException("issuer source snapshot caller workload changed"); + } + } + + private static void requireConfiguredNamespace(ReadRequest request, String configuredNamespace) { + if (!request.targetNamespace().equals(configuredNamespace)) { + throw new IllegalArgumentException( + "issuer source request namespace is not configured namespace"); + } + } + + private static void validateCallContext(String namespace, String callerWorkload) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("configured namespace must be one canonical DNS label"); + } + AccountIssuerSourceSnapshotEvidence.validateCallerWorkload(namespace, callerWorkload); + } + + private static void requireNoUnknownFields(Message message, String description) { + Objects.requireNonNull(message, description + " is required"); + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(description + " contains unknown protobuf fields"); + } + } + + private static void requireSchemaVersion(int schemaVersion, String description) { + if (schemaVersion != AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) { + throw new IllegalArgumentException(description + " has an unsupported schema version"); + } + } + + private static UUID canonicalNonNilUuid(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + final UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException(field + " must be a canonical lowercase UUID", malformed); + } + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException(field + " must be a canonical lowercase non-nil UUID"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must be a non-nil UUID"); + } + } + + private static String decodeUtf8(byte[] bytes, String field) { + if (bytes.length == 0 + || bytes.length > AccountIssuerSourceSnapshotEvidence.MAX_SOURCE_EVENT_BYTES) { + throw new IllegalArgumentException(field + " must be nonempty and at most 64 KiB"); + } + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException(field + " contains malformed UTF-8", malformed); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java new file mode 100644 index 0000000000..a9234264b4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountLogoutAllAuthorityEventV1Codec.java @@ -0,0 +1,355 @@ +package net.firedevops.firemud.common.account.authority; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Strict codec for committed Account logout-all authority events. */ +public final class AccountLogoutAllAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-logout-all-event/v1"; + public static final String EVENT_TYPE = "LOGOUT_ALL_COMMITTED"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + public static final String EVENT_ID_PREFIX = "account-logout-all-event-v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "accountId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "accountAuthorityGeneration", + "sourceVersion", + "accountSecurityCutoff"); + private static final Set WIRE_FIELDS; + private static final Set ACCOUNT_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); + wireFields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(wireFields); + } + + private AccountLogoutAllAuthorityEventV1Codec() {} + + /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */ + public static AccountLogoutAllAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "preimage must not be null"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event", "must be a JSON object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return toEvidence(wire, digest, canonicalJson(wire)); + } + + /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */ + public static AccountLogoutAllAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "wireJson must not be null"); + final JsonNode tree; + try { + // Canonicalization rejects duplicate JSON object properties before Jackson builds a tree. + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + private static AccountLogoutAllAuthorityEvent verifyWireNode(ObjectNode wire) { + requireExactFields(wire, WIRE_FIELDS, "event"); + String suppliedDigest = requireText(wire, "eventDigest", "event"); + if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + String expectedDigest = digest(preimage); + if (!MessageDigest.isEqual( + suppliedDigest.getBytes(StandardCharsets.US_ASCII), + expectedDigest.getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest", "does not match the canonical event preimage"); + } + return toEvidence(wire, suppliedDigest, canonicalJson(wire)); + } + + private static void validatePreimage(ObjectNode event) { + requireExactFields(event, PREIMAGE_FIELDS, "event preimage"); + requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event"); + requireExactText(event, "eventType", EVENT_TYPE, "event"); + + String requestId = requireUuid(event, "requestId", "event"); + requireExactText(event, "eventId", EVENT_ID_PREFIX + requestId, "event"); + String accountId = requireUuid(event, "accountId", "event"); + String sourceScope = "account/" + accountId; + String streamKey = EVENT_STREAM_PREFIX + sourceScope; + requireExactText(event, "sourceScope", sourceScope, "event"); + requireExactText(event, "outboxStreamKey", streamKey, "event"); + + String outboxSequence = requirePositiveDecimal(event, "outboxSequence", "event"); + String accountAuthorityGeneration = + requirePositiveDecimal(event, "accountAuthorityGeneration", "event"); + requirePositiveDecimal(event, "sourceVersion", "event"); + + JsonNode cutoffNode = event.get("accountSecurityCutoff"); + if (!(cutoffNode instanceof ObjectNode cutoff)) { + throw invalid("accountSecurityCutoff", "must be a required JSON object"); + } + requireExactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, "accountSecurityCutoff"); + String cutoffGeneration = + requirePositiveDecimal(cutoff, "accountAuthorityGeneration", "accountSecurityCutoff"); + String cutoffStream = requireText(cutoff, "outboxStreamKey", "accountSecurityCutoff"); + String cutoffSequence = + requirePositiveDecimal(cutoff, "outboxSequence", "accountSecurityCutoff"); + if (!accountAuthorityGeneration.equals(cutoffGeneration)) { + throw invalid( + "accountSecurityCutoff.accountAuthorityGeneration", + "must equal event.accountAuthorityGeneration"); + } + if (!streamKey.equals(cutoffStream)) { + throw invalid("accountSecurityCutoff.outboxStreamKey", "must equal event.outboxStreamKey"); + } + if (!outboxSequence.equals(cutoffSequence)) { + throw invalid("accountSecurityCutoff.outboxSequence", "must equal event.outboxSequence"); + } + } + + private static AccountLogoutAllAuthorityEvent toEvidence( + ObjectNode wire, String digest, String canonicalJson) { + ObjectNode cutoff = (ObjectNode) wire.get("accountSecurityCutoff"); + return new AccountLogoutAllAuthorityEvent( + wire.path("schemaVersion").textValue(), + wire.path("eventType").textValue(), + wire.path("eventId").textValue(), + wire.path("requestId").textValue(), + wire.path("accountId").textValue(), + wire.path("sourceScope").textValue(), + wire.path("outboxStreamKey").textValue(), + wire.path("outboxSequence").textValue(), + wire.path("accountAuthorityGeneration").textValue(), + wire.path("sourceVersion").textValue(), + new AccountSecurityCutoff( + cutoff.path("accountAuthorityGeneration").textValue(), + cutoff.path("outboxStreamKey").textValue(), + cutoff.path("outboxSequence").textValue()), + digest, + canonicalJson); + } + + private static void requireExactFields(ObjectNode object, Set required, String path) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(required)) { + Set missing = new java.util.HashSet<>(required); + missing.removeAll(actual); + Set unexpected = new java.util.HashSet<>(actual); + unexpected.removeAll(required); + StringBuilder message = new StringBuilder("must contain exactly the declared fields"); + if (!missing.isEmpty()) { + message.append("; missing ").append(missing); + } + if (!unexpected.isEmpty()) { + message.append("; unexpected ").append(unexpected); + } + throw invalid(path, message.toString()); + } + } + + private static String requireExactText( + ObjectNode object, String field, String expected, String path) { + String value = requireText(object, field, path); + if (!expected.equals(value)) { + throw invalid(path + "." + field, "must equal " + expected); + } + return value; + } + + private static String requireText(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(path + "." + field, "must be a required string"); + } + return value.textValue(); + } + + private static String requireUuid(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(path + "." + field, "must be a canonical lowercase non-nil UUID"); + } + return value; + } + + private static String requirePositiveDecimal(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!POSITIVE_DECIMAL_PATTERN.matcher(value).matches()) { + throw invalid(path + "." + field, "must be a positive canonical decimal string"); + } + return value; + } + + private static String digest(ObjectNode preimage) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString()); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical); + return "sha256:" + java.util.HexFormat.of().formatHex(hash); + } catch (IOException exception) { + throw new IllegalArgumentException("event preimage cannot be canonicalized", exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String canonicalJson(ObjectNode wire) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(wire.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + /** Immutable verified or producer-sealed logout-all event evidence. */ + public static final class AccountLogoutAllAuthorityEvent { + private final String schemaVersion; + private final String eventType; + private final String eventId; + private final String requestId; + private final String accountId; + private final String sourceScope; + private final String outboxStreamKey; + private final String outboxSequence; + private final String accountAuthorityGeneration; + private final String sourceVersion; + private final AccountSecurityCutoff accountSecurityCutoff; + private final String eventDigest; + private final String canonicalJson; + + private AccountLogoutAllAuthorityEvent( + String schemaVersion, + String eventType, + String eventId, + String requestId, + String accountId, + String sourceScope, + String outboxStreamKey, + String outboxSequence, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + String eventDigest, + String canonicalJson) { + this.schemaVersion = schemaVersion; + this.eventType = eventType; + this.eventId = eventId; + this.requestId = requestId; + this.accountId = accountId; + this.sourceScope = sourceScope; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.accountAuthorityGeneration = accountAuthorityGeneration; + this.sourceVersion = sourceVersion; + this.accountSecurityCutoff = accountSecurityCutoff; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return schemaVersion; + } + + public String eventType() { + return eventType; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return accountId; + } + + public String sourceScope() { + return sourceScope; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String accountAuthorityGeneration() { + return accountAuthorityGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public AccountSecurityCutoff accountSecurityCutoff() { + return accountSecurityCutoff; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a caller-owned copy of the canonical complete wire event bytes. */ + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } + + /** Immutable Account security cutoff checkpoint. */ + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {} +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java new file mode 100644 index 0000000000..c9ebc30d2f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java @@ -0,0 +1,391 @@ +package net.firedevops.firemud.common.account.authority; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Closed source evidence for one Account-owned, non-password security-state mutation. */ +public final class AccountSecurityStateAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-account-security-state-event/v1"; + public static final String EVENT_TYPE = "ACCOUNT_SECURITY_STATE_CHANGED"; + public static final String EVENT_ID_PREFIX = "account-security-state-event-v1:"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "accountId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "accountAuthorityGeneration", + "sourceVersion", + "accountSecurityCutoff", + "mutationKinds", + "accountState"); + private static final Set WIRE_FIELDS; + private static final Set CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Set STATE_FIELDS = + Set.of("emailVerified", "loginAuthModes", "globalRoles", "lifecycleState"); + private static final Set MUTATION_KINDS = + Set.of( + "EMAIL_LOGIN_ELIGIBILITY_CHANGED", + "LOGIN_AUTH_MODES_CHANGED", + "GLOBAL_ROLE_CHANGED", + "LIFECYCLE_STATE_CHANGED"); + private static final Set LOGIN_MODES = Set.of("EMAIL_OTP", "PASSWORD"); + private static final Set GLOBAL_ROLES = + Set.of("platformAdmin", "support", "billingAdmin"); + private static final Set LIFECYCLE_STATES = + Set.of("ACTIVE", "SECURITY_LOCKED", "DEACTIVATED_PENDING_DELETE", "DELETED"); + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var fields = new java.util.HashSet<>(PREIMAGE_FIELDS); + fields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(fields); + } + + private AccountSecurityStateAuthorityEventV1Codec() {} + + /** Seals the complete declared preimage; caller authorization and receipt proof are separate. */ + public static AccountSecurityStateAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "event preimage is required"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event preimage must be an object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return evidence(wire, digest); + } + + /** Verifies the closed payload and digest, returning complete immutable canonical evidence. */ + public static AccountSecurityStateAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "event JSON is required"); + final JsonNode tree; + try { + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event must be an object"); + } + exactFields(wire, WIRE_FIELDS); + String supplied = text(wire, "eventDigest"); + if (!DIGEST_PATTERN.matcher(supplied).matches()) { + throw invalid("eventDigest must be canonical sha256 hexadecimal"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + if (!MessageDigest.isEqual( + supplied.getBytes(StandardCharsets.US_ASCII), + digest(preimage).getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest does not match the complete canonical preimage"); + } + return evidence(wire, supplied); + } + + private static void validatePreimage(ObjectNode event) { + exactFields(event, PREIMAGE_FIELDS); + equalText(event, "schemaVersion", SCHEMA_VERSION); + equalText(event, "eventType", EVENT_TYPE); + String requestId = uuid(event, "requestId"); + equalText(event, "eventId", EVENT_ID_PREFIX + requestId); + String scope = "account/" + uuid(event, "accountId"); + equalText(event, "sourceScope", scope); + equalText(event, "outboxStreamKey", EVENT_STREAM_PREFIX + scope); + positive(event, "outboxSequence"); + positive(event, "accountAuthorityGeneration"); + positive(event, "sourceVersion"); + ObjectNode cutoff = object(event, "accountSecurityCutoff"); + exactFields(cutoff, CUTOFF_FIELDS); + positive(cutoff, "accountAuthorityGeneration"); + positive(cutoff, "outboxSequence"); + for (String field : CUTOFF_FIELDS) { + equalText(cutoff, field, text(event, field)); + } + orderedValues(event.get("mutationKinds"), MUTATION_KINDS, "mutationKinds"); + ObjectNode state = object(event, "accountState"); + exactFields(state, STATE_FIELDS); + if (!state.get("emailVerified").isBoolean()) { + throw invalid("accountState.emailVerified must be a boolean"); + } + orderedValues(state.get("loginAuthModes"), LOGIN_MODES, "accountState.loginAuthModes"); + orderedValues(state.get("globalRoles"), GLOBAL_ROLES, "accountState.globalRoles", true); + if (!LIFECYCLE_STATES.contains(text(state, "lifecycleState"))) { + throw invalid("accountState.lifecycleState is unsupported"); + } + } + + private static List orderedValues(JsonNode array, Set allowed, String field) { + return orderedValues(array, allowed, field, false); + } + + private static List orderedValues( + JsonNode array, Set allowed, String field, boolean allowEmpty) { + if (array == null || !array.isArray() || (!allowEmpty && array.isEmpty())) { + throw invalid(field + " must be a declared array with supported cardinality"); + } + List values = new ArrayList<>(); + String previous = null; + for (JsonNode item : array) { + if (!item.isTextual() || !allowed.contains(item.textValue())) { + throw invalid(field + " contains an unsupported value"); + } + String value = item.textValue(); + if (previous != null && previous.compareTo(value) >= 0) { + throw invalid(field + " must be sorted and unique"); + } + values.add(value); + previous = value; + } + return List.copyOf(values); + } + + private static ObjectNode object(ObjectNode parent, String field) { + if (!(parent.get(field) instanceof ObjectNode value)) { + throw invalid(field + " must be a required object"); + } + return value; + } + + private static void exactFields(ObjectNode object, Set expected) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(expected)) { + throw invalid("object must contain exactly the declared fields"); + } + } + + private static String text(ObjectNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(field + " must be a required string"); + } + return value.textValue(); + } + + private static void equalText(ObjectNode object, String field, String expected) { + if (!expected.equals(text(object, field))) { + throw invalid(field + " does not match its exact binding"); + } + } + + private static String uuid(ObjectNode object, String field) { + String value = text(object, field); + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + return value; + } + + private static void positive(ObjectNode object, String field) { + if (!POSITIVE_DECIMAL.matcher(text(object, field)).matches()) { + throw invalid(field + " must be a positive canonical decimal string"); + } + } + + private static String canonicalJson(ObjectNode object) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(object.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static String digest(ObjectNode object) { + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(canonicalJson(object).getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static AccountSecurityStateAuthorityEvent evidence(ObjectNode wire, String digest) { + ObjectNode state = object(wire, "accountState"); + ObjectNode cutoff = object(wire, "accountSecurityCutoff"); + return new AccountSecurityStateAuthorityEvent( + text(wire, "eventId"), + text(wire, "requestId"), + text(wire, "accountId"), + text(wire, "outboxStreamKey"), + text(wire, "outboxSequence"), + text(wire, "accountAuthorityGeneration"), + text(wire, "sourceVersion"), + new AccountSecurityCutoff( + text(cutoff, "accountAuthorityGeneration"), + text(cutoff, "outboxStreamKey"), + text(cutoff, "outboxSequence")), + orderedValues(wire.get("mutationKinds"), MUTATION_KINDS, "mutationKinds"), + new AccountState( + state.get("emailVerified").booleanValue(), + orderedValues(state.get("loginAuthModes"), LOGIN_MODES, "loginAuthModes"), + orderedValues(state.get("globalRoles"), GLOBAL_ROLES, "globalRoles", true), + text(state, "lifecycleState")), + digest, + canonicalJson(wire)); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {} + + public record AccountState( + boolean emailVerified, + List loginAuthModes, + List globalRoles, + String lifecycleState) { + public AccountState { + loginAuthModes = List.copyOf(loginAuthModes); + globalRoles = List.copyOf(globalRoles); + } + } + + /** Immutable evidence constructible only by sealing or verifying this exact schema. */ + public static final class AccountSecurityStateAuthorityEvent { + private final String eventId; + private final String requestId; + private final String accountId; + private final String outboxStreamKey; + private final String outboxSequence; + private final String accountAuthorityGeneration; + private final String sourceVersion; + private final AccountSecurityCutoff accountSecurityCutoff; + private final List mutationKinds; + private final AccountState accountState; + private final String eventDigest; + private final String canonicalJson; + + private AccountSecurityStateAuthorityEvent( + String eventId, + String requestId, + String accountId, + String outboxStreamKey, + String outboxSequence, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + List mutationKinds, + AccountState accountState, + String eventDigest, + String canonicalJson) { + this.eventId = eventId; + this.requestId = requestId; + this.accountId = accountId; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.accountAuthorityGeneration = accountAuthorityGeneration; + this.sourceVersion = sourceVersion; + this.accountSecurityCutoff = accountSecurityCutoff; + this.mutationKinds = List.copyOf(mutationKinds); + this.accountState = accountState; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return SCHEMA_VERSION; + } + + public String eventType() { + return EVENT_TYPE; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return accountId; + } + + public String sourceScope() { + return "account/" + accountId; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String accountAuthorityGeneration() { + return accountAuthorityGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public AccountSecurityCutoff accountSecurityCutoff() { + return accountSecurityCutoff; + } + + public List mutationKinds() { + return mutationKinds; + } + + public AccountState accountState() { + return accountState; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java new file mode 100644 index 0000000000..f2068dcc0f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java @@ -0,0 +1,372 @@ +package net.firedevops.firemud.common.account.authority; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Strict codec for committed Account password-reset authority events. */ +public final class PasswordResetAuthorityEventV1Codec { + public static final String SCHEMA_VERSION = "account-auth-password-reset-event/v1"; + public static final String EVENT_TYPE = "PASSWORD_RESET_COMMITTED"; + public static final String EVENT_STREAM_PREFIX = "account:auth-authority:v1:"; + + private static final Set PREIMAGE_FIELDS = + Set.of( + "schemaVersion", + "eventType", + "eventId", + "requestId", + "accountId", + "sourceScope", + "outboxStreamKey", + "outboxSequence", + "accountAuthorityGeneration", + "sourceVersion", + "accountSecurityCutoff"); + private static final Set WIRE_FIELDS; + private static final Set ACCOUNT_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final Pattern POSITIVE_DECIMAL_PATTERN = Pattern.compile("[1-9][0-9]*"); + private static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + + static { + var wireFields = new java.util.HashSet<>(PREIMAGE_FIELDS); + wireFields.add("eventDigest"); + WIRE_FIELDS = Set.copyOf(wireFields); + } + + private PasswordResetAuthorityEventV1Codec() {} + + /** Validates a preimage and returns immutable evidence sealed with its canonical digest. */ + public static PasswordResetAuthorityEvent seal(Map preimage) { + Objects.requireNonNull(preimage, "preimage must not be null"); + JsonNode tree = JSON.valueToTree(preimage); + if (!(tree instanceof ObjectNode object)) { + throw invalid("event", "must be a JSON object"); + } + validatePreimage(object); + String digest = digest(object); + ObjectNode wire = object.deepCopy(); + wire.put("eventDigest", digest); + return toEvidence(wire, digest, canonicalJson(wire)); + } + + /** Validates and verifies one wire event from JSON, rejecting duplicate properties. */ + public static PasswordResetAuthorityEvent verify(String wireJson) { + Objects.requireNonNull(wireJson, "wireJson must not be null"); + final JsonNode tree; + try { + // JCS parsing rejects duplicate JSON object properties before Jackson builds a tree. + Rfc8785CanonicalJson.canonicalizeUtf8(wireJson); + tree = JSON.readTree(wireJson); + } catch (IOException exception) { + throw new IllegalArgumentException("event JSON is malformed", exception); + } + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + /** Validates and verifies one wire event supplied as JSON-compatible map data. */ + public static PasswordResetAuthorityEvent verify(Map wireEvent) { + Objects.requireNonNull(wireEvent, "wireEvent must not be null"); + JsonNode tree = JSON.valueToTree(wireEvent); + if (!(tree instanceof ObjectNode wire)) { + throw invalid("event", "must be a JSON object"); + } + return verifyWireNode(wire); + } + + private static PasswordResetAuthorityEvent verifyWireNode(ObjectNode wire) { + requireExactFields(wire, WIRE_FIELDS, "event"); + String suppliedDigest = requireText(wire, "eventDigest", "event"); + if (!DIGEST_PATTERN.matcher(suppliedDigest).matches()) { + throw invalid("eventDigest", "must be lowercase sha256: followed by 64 lowercase hex digits"); + } + ObjectNode preimage = wire.deepCopy(); + preimage.remove("eventDigest"); + validatePreimage(preimage); + String expectedDigest = digest(preimage); + if (!MessageDigest.isEqual( + suppliedDigest.getBytes(StandardCharsets.US_ASCII), + expectedDigest.getBytes(StandardCharsets.US_ASCII))) { + throw invalid("eventDigest", "does not match the canonical event preimage"); + } + return toEvidence(wire, suppliedDigest, canonicalJson(wire)); + } + + private static void validatePreimage(ObjectNode event) { + requireExactFields(event, PREIMAGE_FIELDS, "event preimage"); + requireExactText(event, "schemaVersion", SCHEMA_VERSION, "event"); + requireExactText(event, "eventType", EVENT_TYPE, "event"); + requireNonEmptyText(event, "eventId", "event"); + requireNonEmptyText(event, "requestId", "event"); + + String accountId = requireUuid(event, "accountId", "event"); + String sourceScope = "account/" + accountId; + String streamKey = EVENT_STREAM_PREFIX + sourceScope; + requireExactText(event, "sourceScope", sourceScope, "event"); + requireExactText(event, "outboxStreamKey", streamKey, "event"); + + String outboxSequence = requirePositiveDecimal(event, "outboxSequence", "event"); + String accountAuthorityGeneration = + requirePositiveDecimal(event, "accountAuthorityGeneration", "event"); + requirePositiveDecimal(event, "sourceVersion", "event"); + + JsonNode cutoffNode = event.get("accountSecurityCutoff"); + if (!(cutoffNode instanceof ObjectNode cutoff)) { + throw invalid("accountSecurityCutoff", "must be a required JSON object"); + } + requireExactFields(cutoff, ACCOUNT_CUTOFF_FIELDS, "accountSecurityCutoff"); + String cutoffGeneration = + requirePositiveDecimal(cutoff, "accountAuthorityGeneration", "accountSecurityCutoff"); + String cutoffStream = requireText(cutoff, "outboxStreamKey", "accountSecurityCutoff"); + String cutoffSequence = + requirePositiveDecimal(cutoff, "outboxSequence", "accountSecurityCutoff"); + if (!accountAuthorityGeneration.equals(cutoffGeneration)) { + throw invalid( + "accountSecurityCutoff.accountAuthorityGeneration", + "must equal event.accountAuthorityGeneration"); + } + if (!streamKey.equals(cutoffStream)) { + throw invalid("accountSecurityCutoff.outboxStreamKey", "must equal event.outboxStreamKey"); + } + if (!outboxSequence.equals(cutoffSequence)) { + throw invalid("accountSecurityCutoff.outboxSequence", "must equal event.outboxSequence"); + } + } + + private static PasswordResetAuthorityEvent toEvidence( + ObjectNode wire, String digest, String canonicalJson) { + ObjectNode cutoff = (ObjectNode) wire.get("accountSecurityCutoff"); + return new PasswordResetAuthorityEvent( + wire.path("schemaVersion").textValue(), + wire.path("eventType").textValue(), + wire.path("eventId").textValue(), + wire.path("requestId").textValue(), + wire.path("accountId").textValue(), + wire.path("sourceScope").textValue(), + wire.path("outboxStreamKey").textValue(), + wire.path("outboxSequence").textValue(), + wire.path("accountAuthorityGeneration").textValue(), + wire.path("sourceVersion").textValue(), + new AccountSecurityCutoff( + cutoff.path("accountAuthorityGeneration").textValue(), + cutoff.path("outboxStreamKey").textValue(), + cutoff.path("outboxSequence").textValue()), + digest, + canonicalJson); + } + + private static void requireExactFields(ObjectNode object, Set required, String path) { + Set actual = new java.util.HashSet<>(); + object.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(required)) { + Set missing = new java.util.HashSet<>(required); + missing.removeAll(actual); + Set unexpected = new java.util.HashSet<>(actual); + unexpected.removeAll(required); + StringBuilder message = new StringBuilder("must contain exactly the declared fields"); + if (!missing.isEmpty()) { + message.append("; missing ").append(missing); + } + if (!unexpected.isEmpty()) { + message.append("; unexpected ").append(unexpected); + } + throw invalid(path, message.toString()); + } + } + + private static String requireExactText( + ObjectNode object, String field, String expected, String path) { + String value = requireText(object, field, path); + if (!expected.equals(value)) { + throw invalid(path + "." + field, "must equal " + expected); + } + return value; + } + + private static String requireNonEmptyText(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (value.isEmpty()) { + throw invalid(path + "." + field, "must be nonempty"); + } + return value; + } + + private static String requireText(ObjectNode object, String field, String path) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw invalid(path + "." + field, "must be a required string"); + } + return value.textValue(); + } + + private static String requireUuid(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(path + "." + field, "must be a canonical lowercase non-nil UUID"); + } + return value; + } + + private static String requirePositiveDecimal(ObjectNode object, String field, String path) { + String value = requireText(object, field, path); + if (!POSITIVE_DECIMAL_PATTERN.matcher(value).matches()) { + throw invalid(path + "." + field, "must be a positive canonical decimal string"); + } + return value; + } + + private static String digest(ObjectNode preimage) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(preimage.toString()); + byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical); + return "sha256:" + java.util.HexFormat.of().formatHex(hash); + } catch (IOException exception) { + throw new IllegalArgumentException("event preimage cannot be canonicalized", exception); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String canonicalJson(ObjectNode wire) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(wire.toString()), StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("event cannot be canonicalized", exception); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + /** Immutable verified or producer-sealed event evidence. */ + public static final class PasswordResetAuthorityEvent { + private final String schemaVersion; + private final String eventType; + private final String eventId; + private final String requestId; + private final String accountId; + private final String sourceScope; + private final String outboxStreamKey; + private final String outboxSequence; + private final String accountAuthorityGeneration; + private final String sourceVersion; + private final AccountSecurityCutoff accountSecurityCutoff; + private final String eventDigest; + private final String canonicalJson; + + private PasswordResetAuthorityEvent( + String schemaVersion, + String eventType, + String eventId, + String requestId, + String accountId, + String sourceScope, + String outboxStreamKey, + String outboxSequence, + String accountAuthorityGeneration, + String sourceVersion, + AccountSecurityCutoff accountSecurityCutoff, + String eventDigest, + String canonicalJson) { + this.schemaVersion = schemaVersion; + this.eventType = eventType; + this.eventId = eventId; + this.requestId = requestId; + this.accountId = accountId; + this.sourceScope = sourceScope; + this.outboxStreamKey = outboxStreamKey; + this.outboxSequence = outboxSequence; + this.accountAuthorityGeneration = accountAuthorityGeneration; + this.sourceVersion = sourceVersion; + this.accountSecurityCutoff = accountSecurityCutoff; + this.eventDigest = eventDigest; + this.canonicalJson = canonicalJson; + } + + public String schemaVersion() { + return schemaVersion; + } + + public String eventType() { + return eventType; + } + + public String eventId() { + return eventId; + } + + public String requestId() { + return requestId; + } + + public String accountId() { + return accountId; + } + + public String sourceScope() { + return sourceScope; + } + + public String outboxStreamKey() { + return outboxStreamKey; + } + + public String outboxSequence() { + return outboxSequence; + } + + public String accountAuthorityGeneration() { + return accountAuthorityGeneration; + } + + public String sourceVersion() { + return sourceVersion; + } + + public AccountSecurityCutoff accountSecurityCutoff() { + return accountSecurityCutoff; + } + + public String eventDigest() { + return eventDigest; + } + + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a caller-owned copy of the canonical complete wire event bytes. */ + public byte[] canonicalJsonUtf8() { + return canonicalJson.getBytes(StandardCharsets.UTF_8); + } + } + + /** Immutable Account security cutoff checkpoint. */ + public record AccountSecurityCutoff( + String accountAuthorityGeneration, String outboxStreamKey, String outboxSequence) {} +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java new file mode 100644 index 0000000000..ece7e54a82 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBinding.java @@ -0,0 +1,662 @@ +package net.firedevops.firemud.common.authoring; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Comparator; +import java.util.EnumSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +/** Exact immutable source material, not an authorization decision or authenticated actor proof. */ +public record DraftAuthorizationFenceBinding( + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + UUID actorAccountId, + UUID tenantId, + UUID versionId, + String baseCommitId, + String expectedDraftEpoch, + byte[] gameDesignBinding, + byte[] normalizedInput, + String inputDigest, + List sources, + String schemaVersion, + List requiredOwners) { + + public static final String SCHEMA = "account-draft-authorization-fence/v1"; + public static final String SCHEMA_V1 = SCHEMA; + public static final String SCHEMA_V2 = "account-draft-authorization-fence/v2"; + private static final List V1_OWNERS = List.of(Owner.GAME_DESIGN, Owner.WORLD); + + /** Retains the original producer's exact v1 frame and fixed owner vector. */ + public DraftAuthorizationFenceBinding( + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + UUID actorAccountId, + UUID tenantId, + UUID versionId, + String baseCommitId, + String expectedDraftEpoch, + byte[] gameDesignBinding, + byte[] normalizedInput, + String inputDigest, + List sources) { + this( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources, + SCHEMA_V1, + V1_OWNERS); + } + + public DraftAuthorizationFenceBinding { + Objects.requireNonNull(schemaVersion, "schemaVersion"); + requiredOwners = List.copyOf(Objects.requireNonNull(requiredOwners, "requiredOwners")); + for (UUID id : + List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { + requireUuid(id); + } + text(baseCommitId); + if (baseCommitId.getBytes(StandardCharsets.UTF_8).length > 256) { + throw new IllegalArgumentException("Base commit exceeds 256 UTF-8 bytes"); + } + decimal(expectedDraftEpoch, true); + gameDesignBinding = bytes(gameDesignBinding); + normalizedInput = bytes(normalizedInput); + DraftCommitBinding completeBinding; + try { + completeBinding = + DraftCommitBinding.fromStored( + new String(gameDesignBinding, StandardCharsets.UTF_8), digest(gameDesignBinding)); + } catch (IllegalStateException corrupt) { + throw new IllegalArgumentException( + "Complete canonical Game Design binding required", corrupt); + } + if (!Arrays.equals(gameDesignBinding, completeBinding.canonicalBytes()) + || !requestId.equals(completeBinding.requestId()) + || !commitId.equals(completeBinding.commitId()) + || !tenantId.equals(completeBinding.target().canonicalTenantId()) + || !versionId.equals(completeBinding.target().canonicalVersionId()) + || !baseCommitId.equals(completeBinding.baseCommitId())) { + throw new IllegalArgumentException("Account fence differs from complete Game Design binding"); + } + if (!Arrays.equals(normalizedInput, gameDesignBinding) + || !completeBinding.digest().equals(inputDigest)) { + throw new IllegalArgumentException( + "Draft input must be the exact complete canonical binding"); + } + sources = List.copyOf(Objects.requireNonNull(sources)); + if (sources.isEmpty()) { + throw new IllegalArgumentException("Applicable Account sources are required"); + } + sources = sources.stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + if (sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Duplicate Account source scope"); + } + if (SCHEMA_V1.equals(schemaVersion)) { + if (!V1_OWNERS.equals(requiredOwners)) { + throw new IllegalArgumentException("V1 Draft authorization owners are fixed"); + } + } else if (SCHEMA_V2.equals(schemaVersion)) { + List canonicalOwners = requiredOwners(completeBinding); + if (!canonicalOwners.equals(requiredOwners)) { + throw new IllegalArgumentException( + "V2 Draft authorization owners must exactly match the complete binding"); + } + } else { + throw new IllegalArgumentException("Unsupported Draft authorization fence schema"); + } + } + + /** Converts this exact authorization input to v2 with its canonical complete owner set. */ + public DraftAuthorizationFenceBinding withRequiredOwners() { + DraftCommitBinding completeBinding = completeGameDesignBinding(); + return new DraftAuthorizationFenceBinding( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources, + SCHEMA_V2, + requiredOwners(completeBinding)); + } + + private DraftCommitBinding completeGameDesignBinding() { + return DraftCommitBinding.fromStored( + new String(gameDesignBinding, StandardCharsets.UTF_8), digest(gameDesignBinding)); + } + + private static List requiredOwners(DraftCommitBinding binding) { + EnumSet owners = EnumSet.of(Owner.GAME_DESIGN); + for (DraftCommitBinding.Owner owner : binding.requiredOwners()) { + owners.add( + switch (owner) { + case WORLD_MANAGEMENT -> Owner.WORLD; + case ENTITY_MANAGEMENT -> Owner.ENTITY; + case GAME_LOGIC -> Owner.GAME_LOGIC; + case AUTOMATION_SCRIPTING -> Owner.AUTOMATION; + case GAME_DESIGN_CONTROL_PLANE -> Owner.GAME_DESIGN; + }); + } + return Arrays.stream(Owner.values()).filter(owners::contains).toList(); + } + + /** + * Reconstructs only exact supported immutable Draft-fence framing; this grants no authorization. + */ + public static DraftAuthorizationFenceBinding fromStored(byte[] original) { + byte[] stored = bytes(original); + FrameReader reader = new FrameReader(stored); + String schemaVersion = reader.text(); + if (!SCHEMA_V1.equals(schemaVersion) && !SCHEMA_V2.equals(schemaVersion)) { + throw new IllegalArgumentException("Unsupported immutable source schema"); + } + UUID operationId = canonicalUuidValue(reader.text()); + UUID requestId = canonicalUuidValue(reader.text()); + UUID commitId = canonicalUuidValue(reader.text()); + UUID fenceId = canonicalUuidValue(reader.text()); + UUID actorAccountId = canonicalUuidValue(reader.text()); + UUID tenantId = canonicalUuidValue(reader.text()); + UUID versionId = canonicalUuidValue(reader.text()); + String baseCommitId = reader.text(); + reader.expect("DRAFT"); + String expectedDraftEpoch = reader.text(); + byte[] gameDesignBinding = reader.bytes(); + byte[] normalizedInput = reader.bytes(); + String inputDigest = reader.text(); + String countText = reader.text(); + decimal(countText, false); + BigInteger sourceCount = new BigInteger(countText); + if (sourceCount.compareTo(BigInteger.valueOf(reader.remaining() / Integer.BYTES)) > 0) { + throw new IllegalArgumentException("Incomplete stored source vector"); + } + int sourceCountValue = sourceCount.intValueExact(); + java.util.ArrayList sources = new java.util.ArrayList<>(); + for (int index = 0; index < sourceCountValue; index++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + List requiredOwners; + if (SCHEMA_V1.equals(schemaVersion)) { + reader.expect("GAME_DESIGN"); + reader.expect("WORLD"); + requiredOwners = V1_OWNERS; + } else { + String ownerCountText = reader.text(); + decimal(ownerCountText, false); + BigInteger ownerCount = new BigInteger(ownerCountText); + if (ownerCount.compareTo(BigInteger.valueOf(Owner.values().length)) > 0 + || ownerCount.compareTo(BigInteger.valueOf(reader.remaining() / Integer.BYTES)) > 0) { + throw new IllegalArgumentException("Invalid stored required-owner vector"); + } + int ownerCountValue = ownerCount.intValueExact(); + java.util.ArrayList storedOwners = new java.util.ArrayList<>(); + for (int index = 0; index < ownerCountValue; index++) { + storedOwners.add(Owner.valueOf(reader.text())); + } + requiredOwners = List.copyOf(storedOwners); + } + reader.requireEnd(); + + DraftAuthorizationFenceBinding binding = + new DraftAuthorizationFenceBinding( + operationId, + requestId, + commitId, + fenceId, + actorAccountId, + tenantId, + versionId, + baseCommitId, + expectedDraftEpoch, + gameDesignBinding, + normalizedInput, + inputDigest, + sources, + schemaVersion, + requiredOwners); + if (!Arrays.equals(stored, binding.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored authorization fence binding"); + } + return binding; + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + @Override + public List requiredOwners() { + return List.copyOf(requiredOwners); + } + + @Override + public byte[] gameDesignBinding() { + return gameDesignBinding.clone(); + } + + @Override + public byte[] normalizedInput() { + return normalizedInput.clone(); + } + + /** Closed, ordered UTF-8/binary length frames; counters are exact decimal strings. */ + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + frame(output, schemaVersion); + for (UUID id : + List.of(operationId, requestId, commitId, fenceId, actorAccountId, tenantId, versionId)) { + frame(output, id.toString()); + } + frame(output, baseCommitId); + frame(output, "DRAFT"); + frame(output, expectedDraftEpoch); + frame(output, gameDesignBinding); + frame(output, normalizedInput); + frame(output, inputDigest); + frame(output, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + frame(output, source.canonicalBytes()); + } + if (SCHEMA_V1.equals(schemaVersion)) { + frame(output, "GAME_DESIGN"); + frame(output, "WORLD"); + } else { + frame(output, Integer.toString(requiredOwners.size())); + for (Owner owner : requiredOwners) { + frame(output, owner.name()); + } + } + return output.toByteArray(); + } + + public enum SourceKind { + ISSUER, + ACCOUNT, + TENANT, + MEMBERSHIP, + GLOBAL_ROLES, + CREATOR_PARTY, + HOSTED_TERMS + } + + /** + * Independent owner counters/checkpoints and exact existing source evidence; no inferred epochs. + */ + public record SourceEvidence( + SourceKind kind, + String scopeId, + String generation, + String sourceVersion, + String checkpointStream, + String checkpointSequence, + byte[] evidence) { + public SourceEvidence { + Objects.requireNonNull(kind); + text(scopeId); + // Preserve the exact configured issuer, including its supported 512-character Unicode + // identity. Bound the complete index key in bytes rather than truncating or aliasing it. + if ((kind.name() + ":" + scopeId).getBytes(StandardCharsets.UTF_8).length > 2048) { + throw new IllegalArgumentException("Source participation key exceeds 2048 UTF-8 bytes"); + } + if (kind == SourceKind.ACCOUNT + || kind == SourceKind.TENANT + || kind == SourceKind.GLOBAL_ROLES) { + canonicalUuid(scopeId); + } + if (kind == SourceKind.MEMBERSHIP) { + String[] pair = scopeId.split("/", -1); + if (pair.length != 2) { + throw new IllegalArgumentException("Canonical membership pair required"); + } + canonicalUuid(pair[0]); + canonicalUuid(pair[1]); + } + if (generation != null) { + decimal(generation, false); + } + decimal(sourceVersion, false); + if ((checkpointStream == null) != (checkpointSequence == null)) { + throw new IllegalArgumentException("Checkpoint fields must be applicable together"); + } + if (checkpointStream != null) { + text(checkpointStream); + decimal(checkpointSequence, true); + } + evidence = bytes(evidence); + } + + @Override + public byte[] evidence() { + return evidence.clone(); + } + + public String key() { + return kind.name() + ":" + scopeId; + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : List.of("account-draft-source-evidence/v1", kind.name(), scopeId)) { + frame(output, value); + } + frame(output, generation == null ? "ABSENT" : "PRESENT"); + if (generation != null) { + frame(output, generation); + } + frame(output, sourceVersion); + frame(output, checkpointStream == null ? "ABSENT" : "PRESENT"); + if (checkpointStream != null) { + frame(output, checkpointStream); + frame(output, checkpointSequence); + } + frame(output, evidence); + return output.toByteArray(); + } + + /** Decodes only the exact immutable framing written by this source owner. */ + public static SourceEvidence fromStored(byte[] stored) { + FrameReader reader = new FrameReader(stored); + reader.expect("account-draft-source-evidence/v1"); + SourceKind kind = SourceKind.valueOf(reader.text()); + String scope = reader.text(); + String generation = reader.optionalText(); + String version = reader.text(); + String stream = reader.optionalText(); + String sequence = stream == null ? null : reader.text(); + SourceEvidence source = + new SourceEvidence(kind, scope, generation, version, stream, sequence, reader.bytes()); + reader.requireEnd(); + if (!Arrays.equals(stored, source.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored source evidence"); + } + return source; + } + } + + /** Bounded exact frame decoding for persisted source evidence and source-change intent. */ + public static final class FrameReader { + private final ByteBuffer input; + + public FrameReader(byte[] stored) { + input = ByteBuffer.wrap(DraftAuthorizationFenceBinding.bytes(stored)); + } + + public byte[] bytes() { + if (input.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("Truncated immutable source frame"); + } + int size = input.getInt(); + if (size < 0 || size > input.remaining()) { + throw new IllegalArgumentException("Invalid immutable source frame size"); + } + byte[] value = new byte[size]; + input.get(value); + return value; + } + + public String text() { + byte[] value = bytes(); + String text = new String(value, StandardCharsets.UTF_8); + DraftAuthorizationFenceBinding.text(text); + if (!Arrays.equals(value, text.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Invalid UTF-8 source frame"); + } + return text; + } + + public String optionalText() { + String presence = text(); + if ("ABSENT".equals(presence)) { + return null; + } + if (!"PRESENT".equals(presence)) { + throw new IllegalArgumentException("Invalid immutable source presence"); + } + return text(); + } + + public void expect(String expected) { + if (!expected.equals(text())) { + throw new IllegalArgumentException("Unsupported immutable source schema"); + } + } + + public int remaining() { + return input.remaining(); + } + + public void requireEnd() { + if (input.hasRemaining()) { + throw new IllegalArgumentException("Trailing immutable source frames"); + } + } + } + + public enum Owner { + GAME_DESIGN, + WORLD, + ENTITY, + GAME_LOGIC, + AUTOMATION + } + + public enum Outcome { + COMMITTED, + DEFINITIVELY_ABORTED + } + + private static final String OWNER_READBACK_SCHEMA_V1 = "account-draft-owner-readback/v1"; + private static final String OWNER_READBACK_SCHEMA_V2 = "account-draft-owner-readback/v2"; + + /** Only a future authenticated owner verifier may supply this exact durable readback. */ + public record OwnerReadback( + Owner owner, + Outcome outcome, + UUID operationId, + UUID commitId, + UUID fenceId, + String inputDigest, + byte[] fullBinding, + byte[] result) { + public OwnerReadback { + Objects.requireNonNull(owner); + Objects.requireNonNull(outcome); + requireUuid(operationId); + requireUuid(commitId); + requireUuid(fenceId); + if (inputDigest == null || !inputDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical digest required"); + } + fullBinding = bytes(fullBinding); + result = bytes(result); + } + + /** Reads only canonical original evidence; decoding does not authenticate its producer. */ + public static OwnerReadback fromStored(byte[] original) { + byte[] stored = bytes(original); + FrameReader reader = new FrameReader(stored); + String schema = reader.text(); + if (!OWNER_READBACK_SCHEMA_V1.equals(schema) && !OWNER_READBACK_SCHEMA_V2.equals(schema)) { + throw new IllegalArgumentException("Unsupported stored owner readback schema"); + } + OwnerReadback readback = + new OwnerReadback( + Owner.valueOf(reader.text()), + Outcome.valueOf(reader.text()), + canonicalUuidValue(reader.text()), + canonicalUuidValue(reader.text()), + canonicalUuidValue(reader.text()), + reader.text(), + reader.bytes(), + reader.bytes()); + reader.requireEnd(); + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(readback.fullBinding()); + if (!schema.equals(readbackSchema(binding))) { + throw new IllegalArgumentException("Owner readback schema differs from its full binding"); + } + readback.requireBinding(binding); + if (!Arrays.equals(stored, readback.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored owner readback"); + } + return readback; + } + + @Override + public byte[] fullBinding() { + return fullBinding.clone(); + } + + @Override + public byte[] result() { + return result.clone(); + } + + public void requireBinding(DraftAuthorizationFenceBinding binding) { + if (!operationId.equals(binding.operationId()) + || !commitId.equals(binding.commitId()) + || !fenceId.equals(binding.fenceId()) + || !inputDigest.equals(binding.inputDigest()) + || !Arrays.equals(fullBinding, binding.canonicalBytes())) { + throw new IllegalArgumentException("Owner readback differs from complete Draft binding"); + } + if (SCHEMA_V2.equals(binding.schemaVersion()) && !binding.requiredOwners().contains(owner)) { + throw new IllegalArgumentException("Owner readback owner is not required by Draft binding"); + } + if (SCHEMA_V1.equals(binding.schemaVersion()) && !V1_OWNERS.contains(owner)) { + throw new IllegalArgumentException("V1 owner readback owner is outside its closed schema"); + } + } + + public byte[] canonicalBytes() { + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(fullBinding); + requireBinding(binding); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : + List.of( + readbackSchema(binding), + owner.name(), + outcome.name(), + operationId.toString(), + commitId.toString(), + fenceId.toString(), + inputDigest)) { + frame(output, value); + } + frame(output, fullBinding); + frame(output, result); + return output.toByteArray(); + } + + private static String readbackSchema(DraftAuthorizationFenceBinding binding) { + return SCHEMA_V1.equals(binding.schemaVersion()) + ? OWNER_READBACK_SCHEMA_V1 + : OWNER_READBACK_SCHEMA_V2; + } + } + + public static byte[] bytes(byte[] value) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException("Exact bytes required"); + } + return value.clone(); + } + + public static void requireUuid(UUID value) { + if (value == null || value.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Non-nil UUID required"); + } + } + + public static void canonicalUuid(String value) { + UUID id = UUID.fromString(value); + requireUuid(id); + if (!id.toString().equals(value)) { + throw new IllegalArgumentException("Canonical UUID required"); + } + } + + static void text(String value) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) { + throw new IllegalArgumentException("Nonempty canonical text required"); + } + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (Character.isHighSurrogate(c)) { + if (++i >= value.length() || !Character.isLowSurrogate(value.charAt(i))) { + throw new IllegalArgumentException("Unpaired surrogate"); + } + } else if (Character.isLowSurrogate(c)) { + throw new IllegalArgumentException("Unpaired surrogate"); + } + } + } + + public static void decimal(String value, boolean zero) { + if (value == null || !value.matches(zero ? "0|[1-9][0-9]*" : "[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical decimal string required"); + } + } + + public static void frame(ByteArrayOutputStream output, String value) { + text(value); + frame(output, value.getBytes(StandardCharsets.UTF_8)); + } + + public static void frame(ByteArrayOutputStream output, byte[] value) { + try { + DataOutputStream data = new DataOutputStream(output); + data.writeInt(value.length); + data.write(value); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + public static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID canonicalUuidValue(String value) { + canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java new file mode 100644 index 0000000000..99241c05f8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitBinding.java @@ -0,0 +1,454 @@ +package net.firedevops.firemud.common.authoring; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Complete immutable Game Design binding for one coordinated Draft commit. + * + *

This type retains a declared mutation and its affected tuple set exactly. Its owner labels and + * opaque payloads are not proof that the declaration is semantically complete; each typed owner + * producer must derive and verify its required tuple subset before any owner action. + */ +public final class DraftCommitBinding { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Comparator AFFECTED_ORDER = + Comparator.comparing(AffectedUnit::owner) + .thenComparing(AffectedUnit::aggregateType) + .thenComparing(AffectedUnit::aggregateId) + .thenComparing(AffectedUnit::scopeType) + .thenComparing(AffectedUnit::scopeId); + + /** Owners participating in the canonical multi-owner Draft commit contract. */ + public enum Owner { + WORLD_MANAGEMENT, + ENTITY_MANAGEMENT, + GAME_LOGIC, + AUTOMATION_SCRIPTING, + GAME_DESIGN_CONTROL_PLANE + } + + /** Canonical identity plus the exact private Game Design Version/source lineage. */ + public record TargetProof( + UUID canonicalTenantId, + UUID canonicalVersionId, + long gameDesignVersionRowId, + String gameDesignVersionTenantKey, + long sourceGameRowId, + String sourceGameTenantKey, + String sourceProvenanceKind) { + public TargetProof { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + if (gameDesignVersionRowId <= 0 || sourceGameRowId <= 0) { + throw new IllegalArgumentException("Game Design source row identities must be positive"); + } + requireBoundedText(gameDesignVersionTenantKey, 36, "gameDesignVersionTenantKey"); + requireBoundedText(sourceGameTenantKey, 36, "sourceGameTenantKey"); + if (!gameDesignVersionTenantKey.equals(sourceGameTenantKey)) { + throw new IllegalArgumentException( + "Version and source Game Design tenant keys must match exactly"); + } + if (!"NEW_GAME_ROW".equals(sourceProvenanceKind) + && !"RETAINED_GAME_V29".equals(sourceProvenanceKind)) { + throw new IllegalArgumentException("Unsupported canonical Version source provenance"); + } + } + } + + /** One full owner-typed revision payload. The payload is opaque and is never normalized here. */ + public record RevisionPayload( + String revisionOrder, UUID revisionId, Owner owner, String payload) { + public RevisionPayload { + Objects.requireNonNull(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(payload, "payload"); + } + } + + /** The expected epoch for one owner-local aggregate and scope fence. */ + public record AffectedUnit( + Owner owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public AffectedUnit { + Objects.requireNonNull(owner, "owner"); + requireBoundedText(aggregateType, 128, "aggregateType"); + requireBoundedText(aggregateId, 256, "aggregateId"); + requireBoundedText(scopeType, 128, "scopeType"); + requireBoundedText(scopeId, 256, "scopeId"); + requireCanonicalCounter(expectedEpoch, "expectedEpoch"); + } + } + + private final TargetProof target; + private final UUID requestId; + private final UUID commitId; + private final String baseCommitId; + private final List revisions; + private final List affectedUnits; + private final List requiredOwners; + private final String canonicalJson; + private final byte[] canonicalBytes; + private final String digest; + + private DraftCommitBinding( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + List revisions, + List affectedUnits) { + this.target = Objects.requireNonNull(target, "target"); + requireNonNil(requestId, "requestId"); + requireNonNil(commitId, "commitId"); + requireBoundedText(baseCommitId, 256, "baseCommitId"); + this.requestId = requestId; + this.commitId = commitId; + this.baseCommitId = baseCommitId; + this.revisions = validateRevisions(revisions); + this.affectedUnits = validateAffectedUnits(affectedUnits); + this.requiredOwners = validateOwnerCoverage(this.revisions, this.affectedUnits); + try { + canonicalBytes = Rfc8785CanonicalJson.canonicalizeUtf8(serialize(toJsonObject())); + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = sha256(canonicalBytes); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Draft commit binding could not be canonicalized", exception); + } + } + + public static DraftCommitBinding create( + TargetProof target, + UUID requestId, + UUID commitId, + String baseCommitId, + List revisions, + List affectedUnits) { + return new DraftCommitBinding( + target, requestId, commitId, baseCommitId, revisions, affectedUnits); + } + + /** Reconstructs an immutable binding from owner storage and rejects noncanonical/corrupt rows. */ + public static DraftCommitBinding fromStored(String storedJson, String storedDigest) { + Objects.requireNonNull(storedJson, "storedJson"); + Objects.requireNonNull(storedDigest, "storedDigest"); + try { + JsonNode root = JSON.readTree(storedJson); + JsonNode targetNode = requireObject(root, "target"); + TargetProof target = + new TargetProof( + UUID.fromString(requiredText(root, "canonicalTenantId")), + UUID.fromString(requiredText(root, "canonicalVersionId")), + positiveLong(targetNode, "gameDesignVersionRowId"), + requiredText(targetNode, "gameDesignVersionTenantKey"), + positiveLong(targetNode, "sourceGameRowId"), + requiredText(targetNode, "sourceGameTenantKey"), + requiredText(targetNode, "sourceProvenanceKind")); + List revisions = new ArrayList<>(); + for (JsonNode node : requiredArray(root, "revisions")) { + revisions.add( + new RevisionPayload( + requiredText(node, "revisionOrder"), + UUID.fromString(requiredText(node, "revisionId")), + Owner.valueOf(requiredText(node, "owner")), + requiredText(node, "payload"))); + } + List affectedUnits = new ArrayList<>(); + for (JsonNode node : requiredArray(root, "affectedUnits")) { + affectedUnits.add( + new AffectedUnit( + Owner.valueOf(requiredText(node, "owner")), + requiredText(node, "aggregateType"), + requiredText(node, "aggregateId"), + requiredText(node, "scopeType"), + requiredText(node, "scopeId"), + requiredText(node, "expectedEpoch"))); + } + DraftCommitBinding binding = + create( + target, + UUID.fromString(requiredText(root, "requestId")), + UUID.fromString(requiredText(root, "commitId")), + requiredText(root, "baseCommitId"), + revisions, + affectedUnits); + if (!binding.canonicalJson.equals(storedJson) + || !binding.digest.equals(storedDigest) + || !Arrays.equals(binding.canonicalBytes, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Stored Draft commit binding is not exact canonical JSON"); + } + return binding; + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored Draft commit binding is corrupt", exception); + } + } + + public TargetProof target() { + return target; + } + + public UUID requestId() { + return requestId; + } + + public UUID commitId() { + return commitId; + } + + public String baseCommitId() { + return baseCommitId; + } + + public List revisions() { + return List.copyOf(revisions); + } + + public List affectedUnits() { + return List.copyOf(affectedUnits); + } + + public List requiredOwners() { + return List.copyOf(requiredOwners); + } + + /** The canonical UTF-8 representation, retained as text for exact database equality. */ + public String canonicalJson() { + return canonicalJson; + } + + /** Returns a defensive copy of the exact RFC 8785 bytes stored with this binding. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + public List affectedUnits(Owner owner) { + return affectedUnits.stream().filter(unit -> unit.owner() == owner).toList(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof DraftCommitBinding binding + && digest.equals(binding.digest) + && Arrays.equals(canonicalBytes, binding.canonicalBytes)); + } + + @Override + public int hashCode() { + return 31 * digest.hashCode() + Arrays.hashCode(canonicalBytes); + } + + private Map toJsonObject() { + Map object = new LinkedHashMap<>(); + object.put("schemaVersion", "1"); + object.put("canonicalTenantId", target.canonicalTenantId().toString()); + object.put("canonicalVersionId", target.canonicalVersionId().toString()); + Map targetObject = new LinkedHashMap<>(); + targetObject.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + targetObject.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + targetObject.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + targetObject.put("sourceGameTenantKey", target.sourceGameTenantKey()); + targetObject.put("sourceProvenanceKind", target.sourceProvenanceKind()); + object.put("target", targetObject); + object.put("requestId", requestId.toString()); + object.put("commitId", commitId.toString()); + object.put("baseCommitId", baseCommitId); + object.put("revisions", revisions.stream().map(DraftCommitBinding::revisionJson).toList()); + object.put( + "affectedUnits", affectedUnits.stream().map(DraftCommitBinding::affectedUnitJson).toList()); + object.put("requiredOwners", requiredOwners.stream().map(Enum::name).toList()); + return object; + } + + private static Map revisionJson(RevisionPayload revision) { + Map object = new LinkedHashMap<>(); + object.put("revisionOrder", revision.revisionOrder()); + object.put("revisionId", revision.revisionId().toString()); + object.put("owner", revision.owner().name()); + object.put("payload", revision.payload()); + return object; + } + + private static Map affectedUnitJson(AffectedUnit unit) { + Map object = new LinkedHashMap<>(); + object.put("owner", unit.owner().name()); + object.put("aggregateType", unit.aggregateType()); + object.put("aggregateId", unit.aggregateId()); + object.put("scopeType", unit.scopeType()); + object.put("scopeId", unit.scopeId()); + object.put("expectedEpoch", unit.expectedEpoch()); + return object; + } + + private static List validateRevisions(List requested) { + Objects.requireNonNull(requested, "revisions"); + if (requested.isEmpty()) { + throw new IllegalArgumentException("Draft commit must contain at least one full revision"); + } + List copy = List.copyOf(requested); + Set revisionIds = new HashSet<>(); + for (int index = 0; index < copy.size(); index++) { + RevisionPayload revision = Objects.requireNonNull(copy.get(index), "revision"); + if (!Integer.toString(index).equals(revision.revisionOrder())) { + throw new IllegalArgumentException( + "Revision order must be the contiguous canonical array order"); + } + if (!revisionIds.add(revision.revisionId())) { + throw new IllegalArgumentException("Draft commit contains a duplicate revision identity"); + } + if (revision.payload().isEmpty()) { + throw new IllegalArgumentException("A full revision payload must not be omitted"); + } + } + return copy; + } + + private static List validateAffectedUnits(List requested) { + Objects.requireNonNull(requested, "affectedUnits"); + if (requested.isEmpty()) { + throw new IllegalArgumentException("Draft commit must declare its complete affected units"); + } + List copy = new ArrayList<>(requested.size()); + Set identities = new HashSet<>(); + for (AffectedUnit unit : requested) { + Objects.requireNonNull(unit, "affectedUnit"); + String identity = + unit.owner() + + "\u0000" + + unit.aggregateType() + + "\u0000" + + unit.aggregateId() + + "\u0000" + + unit.scopeType() + + "\u0000" + + unit.scopeId(); + if (!identities.add(identity)) { + throw new IllegalArgumentException( + "Draft commit contains a duplicate affected owner scope"); + } + copy.add(unit); + } + copy.sort(AFFECTED_ORDER); + return List.copyOf(copy); + } + + private static List validateOwnerCoverage( + List revisions, List affectedUnits) { + Set revisionOwners = new HashSet<>(); + revisions.forEach(revision -> revisionOwners.add(revision.owner())); + Set affectedOwners = new HashSet<>(); + affectedUnits.forEach(unit -> affectedOwners.add(unit.owner())); + if (!revisionOwners.equals(affectedOwners)) { + throw new IllegalArgumentException( + "Required owner set must exactly match owners derived from revisions and affected units"); + } + return Arrays.stream(Owner.values()).filter(revisionOwners::contains).toList(); + } + + private static String serialize(Object object) { + return JSON.writeValueAsString(object); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing text field " + field); + } + return value.textValue(); + } + + private static JsonNode requireObject(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing object field " + field); + } + return value; + } + + private static JsonNode requiredArray(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isArray()) { + throw new IllegalArgumentException( + "Stored Draft commit binding is missing array field " + field); + } + return value; + } + + private static long positiveLong(JsonNode object, String field) { + String value = requiredText(object, field); + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "Stored source row ID is not a positive canonical decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Stored source row ID is outside the supported range", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireCanonicalCounter(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal string"); + } + new BigInteger(value); + } + + private static void requireBoundedText(String value, int maxUtf8Bytes, String label) { + Objects.requireNonNull(value, label); + if (value.isBlank() + || value.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes + || !value.equals(value.trim())) { + throw new IllegalArgumentException(label + " must be nonblank canonical bounded text"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClient.java new file mode 100644 index 0000000000..3429a85c45 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClient.java @@ -0,0 +1,151 @@ +package net.firedevops.firemud.common.authoring; + +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.GameDesignDraftTerminalReadServiceGrpc; + +/** Explicit mTLS client for exact same-namespace Game Design terminal readback. */ +public final class GameDesignDraftTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignDraftTerminalReadServiceGrpc.GameDesignDraftTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameDesignDraftTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameDesignDraftTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Account service explicitly starts this opt-in client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Game Design terminal read client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Game Design terminal read client has no gRPC stub"); + } + initialized = true; + } + + /** Reads exact immutable Game Design terminal evidence; missing evidence stays UNKNOWN. */ + public GameDesignDraftTerminalReadEvidence read( + GameDesignDraftTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Design terminal read request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readGameDesignDraftTerminalOutcome( + GameDesignDraftTerminalReadGrpcCodec.toRequest(request)); + try { + return GameDesignDraftTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid terminal readback evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignDraftTerminalReadServiceGrpc.GameDesignDraftTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignDraftTerminalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignDraftTerminalReadServiceGrpc.GameDesignDraftTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Design terminal read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Game Design terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Design terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Design terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Game Design terminal read " + label + " must be a readable file-backed path", exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Design terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadEvidence.java new file mode 100644 index 0000000000..f6671fdad3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadEvidence.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.common.authoring; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +/** Validated Game Design terminal-read value; producer authentication comes only from transport. */ +public record GameDesignDraftTerminalReadEvidence( + Request request, Optional ownerReadback) { + public GameDesignDraftTerminalReadEvidence { + Objects.requireNonNull(request, "request"); + ownerReadback = Objects.requireNonNull(ownerReadback, "ownerReadback"); + ownerReadback.ifPresent( + value -> { + if (value.owner() != DraftAuthorizationFenceBinding.Owner.GAME_DESIGN + || (value.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED + && value.outcome() + != DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED)) { + throw new IllegalArgumentException( + "Game Design readback must be a committed or definitive-abort owner result"); + } + value.requireBinding(request.accountBinding()); + if (!Arrays.equals(value.fullBinding(), request.originalAccountBinding()) + || value.result().length == 0) { + throw new IllegalArgumentException( + "Game Design readback differs from the original binding or lacks result bytes"); + } + }); + } + + /** The canonical original Account binding and a separate fresh caller-owned read identity. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] originalAccountBinding) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported Game Design terminal read schema version"); + } + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace is required"); + } + requireNonNil(readRequestId, "readRequestId"); + if (originalAccountBinding == null || originalAccountBinding.length == 0) { + throw new IllegalArgumentException("Complete original Account binding is required"); + } + originalAccountBinding = originalAccountBinding.clone(); + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.requestId()) + || readRequestId.equals(binding.commitId()) + || readRequestId.equals(binding.fenceId())) { + throw new IllegalArgumentException("Game Design terminal read requires a fresh identity"); + } + } + + public static Request create(String targetNamespace, byte[] originalAccountBinding) { + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.requestId()) + || readRequestId.equals(binding.commitId()) + || readRequestId.equals(binding.fenceId())); + return new Request(SCHEMA_VERSION, targetNamespace, readRequestId, originalAccountBinding); + } + + @Override + public byte[] originalAccountBinding() { + return originalAccountBinding.clone(); + } + + public DraftAuthorizationFenceBinding accountBinding() { + return DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals(originalAccountBinding, that.originalAccountBinding); + } + + @Override + public int hashCode() { + int result = Objects.hash(schemaVersion, targetNamespace, readRequestId); + return 31 * result + Arrays.hashCode(originalAccountBinding); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("Non-nil " + label + " is required"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..8df4ea0838 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadGrpcCodec.java @@ -0,0 +1,169 @@ +package net.firedevops.firemud.common.authoring; + +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.GameDesignDraftTerminalReadStatus; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignDraftTerminalOutcomeRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignDraftTerminalOutcomeResponse; + +/** Closed request mapping and exact echo/outcome validation for authenticated Game Design reads. */ +public final class GameDesignDraftTerminalReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private GameDesignDraftTerminalReadGrpcCodec() {} + + public static ReadGameDesignDraftTerminalOutcomeRequest toRequest( + GameDesignDraftTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadGameDesignDraftTerminalOutcomeRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())) + .build(); + } + + /** Decodes only after the receiver has authenticated its exact same-namespace Account peer. */ + public static GameDesignDraftTerminalReadEvidence.Request fromRequest( + ReadGameDesignDraftTerminalOutcomeRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadGameDesignDraftTerminalOutcomeRequest"); + try { + return new GameDesignDraftTerminalReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + request.getOriginalAccountBinding().toByteArray()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Game Design terminal read request is invalid", exception); + } + } + + /** Emits only UNKNOWN or an exact persisted Game Design terminal readback. */ + public static ReadGameDesignDraftTerminalOutcomeResponse toResponse( + GameDesignDraftTerminalReadEvidence.Request request, + Optional ownerReadback) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(ownerReadback, "ownerReadback"); + var builder = + ReadGameDesignDraftTerminalOutcomeResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())); + if (ownerReadback.isEmpty()) { + return builder + .setStatus( + GameDesignDraftTerminalReadStatus.GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_UNKNOWN) + .build(); + } + var readback = ownerReadback.orElseThrow(); + requireExactOwnerReadback(request, readback); + var status = + readback.outcome() == Outcome.COMMITTED + ? GameDesignDraftTerminalReadStatus.GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_COMMITTED + : GameDesignDraftTerminalReadStatus + .GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED; + return builder + .setStatus(status) + .setOwnerReadbackBytes(com.google.protobuf.ByteString.copyFrom(readback.canonicalBytes())) + .build(); + } + + /** Validates the complete echo and independently framed Game Design owner result. */ + public static GameDesignDraftTerminalReadEvidence fromResponse( + GameDesignDraftTerminalReadEvidence.Request request, + ReadGameDesignDraftTerminalOutcomeResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadGameDesignDraftTerminalOutcomeResponse"); + if (response.getSchemaVersion() != request.schemaVersion() + || !response.getTargetNamespace().equals(request.targetNamespace()) + || !response.getReadRequestId().equals(request.readRequestId().toString()) + || !Arrays.equals( + response.getOriginalAccountBinding().toByteArray(), request.originalAccountBinding())) { + throw new IllegalArgumentException( + "Game Design terminal response changed the exact read request"); + } + Optional readback; + switch (response.getStatus()) { + case GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_UNKNOWN -> { + if (!response.getOwnerReadbackBytes().isEmpty()) { + throw new IllegalArgumentException("UNKNOWN Game Design readback cannot carry a result"); + } + readback = Optional.empty(); + } + case GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_COMMITTED, + GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED -> { + if (response.getOwnerReadbackBytes().isEmpty()) { + throw new IllegalArgumentException( + "Game Design terminal owner readback bytes are required"); + } + var decoded = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + response.getOwnerReadbackBytes().toByteArray()); + requireExactOwnerReadback(request, decoded); + if ((response.getStatus() + == GameDesignDraftTerminalReadStatus + .GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_COMMITTED) + != (decoded.outcome() == Outcome.COMMITTED)) { + throw new IllegalArgumentException("Game Design status differs from the owner outcome"); + } + readback = Optional.of(decoded); + } + case GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("Unsupported Game Design terminal read status"); + default -> throw new IllegalArgumentException("Unsupported Game Design terminal read status"); + } + return new GameDesignDraftTerminalReadEvidence(request, readback); + } + + private static void requireExactOwnerReadback( + GameDesignDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback readback) { + DraftAuthorizationFenceBinding binding = request.accountBinding(); + if (readback.owner() != Owner.GAME_DESIGN + || (readback.outcome() != Outcome.COMMITTED + && readback.outcome() != Outcome.DEFINITIVELY_ABORTED)) { + throw new IllegalArgumentException("Game Design response is not a supported terminal result"); + } + readback.requireBinding(binding); + if (!readback.operationId().equals(binding.operationId()) + || !readback.commitId().equals(binding.commitId()) + || !readback.fenceId().equals(binding.fenceId()) + || !readback.inputDigest().equals(binding.inputDigest()) + || !Arrays.equals(readback.fullBinding(), request.originalAccountBinding()) + || readback.result().length == 0) { + throw new IllegalArgumentException( + "Game Design terminal response differs from the complete original Account binding"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClient.java new file mode 100644 index 0000000000..cd896b8423 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClient.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.common.authoring; + +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.WorldDraftTerminalReadServiceGrpc; + +/** Explicit mTLS client for exact same-namespace World committed/definitive-abort readback. */ +public final class WorldDraftTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + WorldDraftTerminalReadServiceGrpc.WorldDraftTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldDraftTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldDraftTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Account service explicitly starts this opt-in client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World terminal read client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World terminal read client has no gRPC stub"); + } + initialized = true; + } + + /** Reads exact immutable World terminal evidence; no missing row is inferred as abort. */ + public WorldDraftTerminalReadEvidence read(WorldDraftTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World terminal read request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldDraftTerminalOutcome(WorldDraftTerminalReadGrpcCodec.toRequest(request)); + try { + return WorldDraftTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned invalid terminal readback evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldDraftTerminalReadServiceGrpc.WorldDraftTerminalReadServiceBlockingStub buildStub( + ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldDraftTerminalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldDraftTerminalReadServiceGrpc.WorldDraftTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World terminal read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "World terminal read " + label + " must be a readable file-backed path", exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java new file mode 100644 index 0000000000..21aac2639d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.common.authoring; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +/** + * Validated World terminal-read value; peer authentication is supplied only by transport guards. + */ +public record WorldDraftTerminalReadEvidence( + Request request, Optional ownerReadback) { + public WorldDraftTerminalReadEvidence { + Objects.requireNonNull(request, "request"); + ownerReadback = Objects.requireNonNull(ownerReadback, "ownerReadback"); + ownerReadback.ifPresent( + value -> { + if (value.owner() != DraftAuthorizationFenceBinding.Owner.WORLD + || (value.outcome() != DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED + && value.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED)) { + throw new IllegalArgumentException("World readback must be an exact terminal outcome"); + } + DraftAuthorizationFenceBinding binding = request.accountBinding(); + value.requireBinding(binding); + if (!Arrays.equals(value.fullBinding(), request.originalAccountBinding())) { + throw new IllegalArgumentException("World readback differs from the original binding"); + } + if (value.outcome() == DraftAuthorizationFenceBinding.Outcome.COMMITTED) { + WorldDraftTerminalReadGrpcCodec.requireCommittedResult(request, value); + } + }); + } + + /** The canonical original Account binding and a separate caller-owned fresh read identity. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] originalAccountBinding) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World terminal read schema version"); + } + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + requireNonNil(readRequestId, "readRequestId"); + if (originalAccountBinding == null || originalAccountBinding.length == 0) { + throw new IllegalArgumentException("Complete original Account binding is required"); + } + originalAccountBinding = originalAccountBinding.clone(); + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.requestId()) + || readRequestId.equals(binding.commitId()) + || readRequestId.equals(binding.fenceId())) { + throw new IllegalArgumentException("World terminal read requires a fresh request identity"); + } + } + + public static Request create(String targetNamespace, byte[] originalAccountBinding) { + return new Request( + SCHEMA_VERSION, targetNamespace, UUID.randomUUID(), originalAccountBinding); + } + + @Override + public byte[] originalAccountBinding() { + return originalAccountBinding.clone(); + } + + public DraftAuthorizationFenceBinding accountBinding() { + return DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals(originalAccountBinding, that.originalAccountBinding); + } + + @Override + public int hashCode() { + int result = Objects.hash(schemaVersion, targetNamespace, readRequestId); + return 31 * result + Arrays.hashCode(originalAccountBinding); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("Non-nil " + label + " is required"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..a826e79d17 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java @@ -0,0 +1,736 @@ +package net.firedevops.firemud.common.authoring; + +import com.google.protobuf.Message; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Closed request mapping and exact echo/outcome validation for authenticated World readback. */ +public final class WorldDraftTerminalReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String APPLIED_V1 = "world-draft-graph-applied/v1"; + private static final String APPLIED_V2 = "world-draft-graph-applied/v2"; + private static final java.util.List FRESH_GRAPH_FAMILIES = + java.util.List.of( + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", + "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING"); + private static final Set APPLIED_V1_FIELDS = + Set.of( + "schema", + "status", + "operationBytesBase64", + "graphBytesBase64", + "graphDigest", + "appliedEpochs"); + private static final Set APPLIED_V2_FIELDS = + Set.of( + "schema", + "status", + "operationBytesBase64", + "graphBytesBase64", + "graphDigest", + "startLocationReceiptBase64", + "startLocationReceiptDigest", + "appliedEpochs"); + private static final Set FRESH_GRAPH_DECLARATION_FIELDS = + Set.of("tenantId", "versionId", "startLocation", "familyCounts"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final Set FAMILY_COUNT_FIELDS = Set.of("family", "count"); + private static final Set GRAPH_ROW_FIELDS = Set.of("mapping", "content"); + private static final Set GRAPH_MAPPING_FIELDS = + Set.of( + "id", + "target_namespace", + "canonical_tenant_id", + "canonical_version_id", + "family", + "template_id", + "private_row_key", + "tenant_id", + "version_id", + "version_identity_operation_id", + "request_id", + "commit_id", + "revision_id", + "revision_order"); + private static final Set WORLD_MUTATION_FIELDS = + Set.of( + "logicalRevisionId", + "commitId", + "operation", + "aggregateType", + "aggregateId", + "expectedDraftRevisionEpoch", + "scopeType", + "scopeId", + "expectedDraftScopeRevisionEpoch", + "scopeMutationPolicy", + "freshGraphDeclaration", + "region", + "zone", + "room", + "roomExit", + "generationRule", + "worldEntitySpawnBinding", + "worldGenerationSubtree"); + private static final tools.jackson.databind.ObjectMapper JSON = + JsonMapper.builder() + .enable(tools.jackson.core.StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private WorldDraftTerminalReadGrpcCodec() {} + + public static ReadWorldDraftTerminalOutcomeRequest toRequest( + WorldDraftTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadWorldDraftTerminalOutcomeRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())) + .build(); + } + + /** Decodes only after the receiver has authenticated its exact same-namespace Account peer. */ + public static WorldDraftTerminalReadEvidence.Request fromRequest( + ReadWorldDraftTerminalOutcomeRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadWorldDraftTerminalOutcomeRequest"); + try { + return new WorldDraftTerminalReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + request.getOriginalAccountBinding().toByteArray()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("World terminal read request is invalid", exception); + } + } + + /** Emits only UNKNOWN or exact canonical World committed/definitive-abort readback. */ + public static ReadWorldDraftTerminalOutcomeResponse toResponse( + WorldDraftTerminalReadEvidence.Request request, + Optional ownerReadback) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(ownerReadback, "ownerReadback"); + var builder = + ReadWorldDraftTerminalOutcomeResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())); + if (ownerReadback.isEmpty()) { + return builder + .setStatus(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN) + .build(); + } + var readback = ownerReadback.orElseThrow(); + requireExactOwnerReadback(request, readback); + return builder + .setStatus( + readback.outcome() == Outcome.COMMITTED + ? WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED + : WorldDraftTerminalReadStatus + .WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED) + .setOwnerReadbackBytes(com.google.protobuf.ByteString.copyFrom(readback.canonicalBytes())) + .build(); + } + + /** Validates the complete echo and independently framed World owner result. */ + public static WorldDraftTerminalReadEvidence fromResponse( + WorldDraftTerminalReadEvidence.Request request, + ReadWorldDraftTerminalOutcomeResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldDraftTerminalOutcomeResponse"); + if (response.getSchemaVersion() != request.schemaVersion() + || !response.getTargetNamespace().equals(request.targetNamespace()) + || !response.getReadRequestId().equals(request.readRequestId().toString()) + || !Arrays.equals( + response.getOriginalAccountBinding().toByteArray(), request.originalAccountBinding())) { + throw new IllegalArgumentException("World terminal response changed the exact read request"); + } + Optional readback; + switch (response.getStatus()) { + case WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN -> { + if (!response.getOwnerReadbackBytes().isEmpty()) { + throw new IllegalArgumentException("UNKNOWN World readback cannot carry a result"); + } + readback = Optional.empty(); + } + case WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED, + WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED -> { + if (response.getOwnerReadbackBytes().isEmpty()) { + throw new IllegalArgumentException("World terminal readback bytes are required"); + } + var decoded = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + response.getOwnerReadbackBytes().toByteArray()); + requireExactOwnerReadback(request, decoded); + Outcome expected = + response.getStatus() + == WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED + ? Outcome.COMMITTED + : Outcome.DEFINITIVELY_ABORTED; + if (decoded.outcome() != expected) { + throw new IllegalArgumentException( + "World terminal status differs from canonical owner outcome"); + } + readback = Optional.of(decoded); + } + case WORLD_DRAFT_TERMINAL_READ_STATUS_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("Unsupported World terminal read status"); + default -> throw new IllegalArgumentException("Unsupported World terminal read status"); + } + return new WorldDraftTerminalReadEvidence(request, readback); + } + + private static void requireExactOwnerReadback( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback readback) { + DraftAuthorizationFenceBinding binding = request.accountBinding(); + if (readback.owner() != Owner.WORLD + || (readback.outcome() != Outcome.DEFINITIVELY_ABORTED + && readback.outcome() != Outcome.COMMITTED)) { + throw new IllegalArgumentException( + "World terminal response is not an exact World terminal outcome"); + } + readback.requireBinding(binding); + if (!readback.operationId().equals(binding.operationId()) + || !readback.commitId().equals(binding.commitId()) + || !readback.fenceId().equals(binding.fenceId()) + || !readback.inputDigest().equals(binding.inputDigest()) + || !Arrays.equals(readback.fullBinding(), request.originalAccountBinding()) + || readback.result().length == 0) { + throw new IllegalArgumentException( + "World terminal response differs from the complete original Account binding"); + } + if (readback.outcome() == Outcome.COMMITTED) requireCommittedResult(request, readback); + } + + /** + * Checks this World carrier only; mutation/source semantics remain at the authenticated owner. + */ + static void requireCommittedResult( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback readback) { + try { + byte[] bytes = readback.result(); + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(json))) + throw new IllegalArgumentException("Noncanonical World APPLIED result"); + JsonNode result = JSON.readTree(bytes); + String schema = text(result, "schema"); + boolean v2 = APPLIED_V2.equals(schema); + if (!v2 && !APPLIED_V1.equals(schema)) { + throw new IllegalArgumentException("Unsupported World APPLIED result schema"); + } + fields(result, v2 ? APPLIED_V2_FIELDS : APPLIED_V1_FIELDS); + exactText(result, "status", "APPLIED"); + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), + account.inputDigest()); + if (!Arrays.equals(draft.canonicalBytes(), account.normalizedInput()) + || !draft.requestId().equals(account.requestId()) + || !draft.commitId().equals(account.commitId()) + || !draft.target().canonicalTenantId().equals(account.tenantId()) + || !draft.target().canonicalVersionId().equals(account.versionId())) { + throw new IllegalArgumentException("World applied input differs from original binding"); + } + OriginalFreshGraph originalGraph = readOriginalFreshGraph(draft, v2); + if (v2 != (originalGraph != null)) { + throw new IllegalArgumentException( + "World APPLIED schema does not match the original fresh graph declaration"); + } + FrameReader operation = new FrameReader(base64(result, "operationBytesBase64")); + operation.expect("world-draft-terminal-operation/v1"); + for (UUID id : + java.util.List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) operation.expect(id.toString()); + operation.expectBytes(draft.canonicalBytes()); + operation.expect(request.targetNamespace()); + operation.expect(account.tenantId().toString()); + operation.expect(account.versionId().toString()); + UUID versionIdentityOperationId = operation.canonicalUuid(); + operation.expect(Long.toString(draft.target().gameDesignVersionRowId())); + operation.canonicalUuid(); // Intake request + operation.canonicalUuid(); // Intake operation + operation.digest(); // Intake request digest + operation.canonicalUuid(); // Source operation + operation.digest(); // Source evidence digest + operation.digest(); // Intake receipt digest + operation.expect(sha256(request.originalAccountBinding())); + operation.expectBytes(request.originalAccountBinding()); + operation.requireEnd(); + byte[] graph = base64(result, "graphBytesBase64"); + if (v2) { + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(graph)); + } + String graphDigest = sha256(graph); + exactText(result, "graphDigest", graphDigest); + JsonNode graphValue = JSON.readTree(graph); + fields( + graphValue, Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows")); + exactText(graphValue, "schemaVersion", "2"); + exactText(graphValue, "canonicalTenantId", account.tenantId().toString()); + exactText(graphValue, "canonicalVersionId", account.versionId().toString()); + if (!graphValue.get("rows").isArray() || graphValue.get("rows").isEmpty()) + throw new IllegalArgumentException("World applied graph is absent"); + if (v2) { + validateDeclaredGraphRows( + graphValue.get("rows"), + originalGraph, + request.targetNamespace(), + account, + versionIdentityOperationId); + validateStartLocationReceipt(result, graphDigest, originalGraph, request, draft, account); + } + var expected = draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT); + JsonNode epochs = result.get("appliedEpochs"); + if (!epochs.isArray() || expected.isEmpty() || epochs.size() != expected.size()) + throw new IllegalArgumentException("World applied epoch vector is incomplete"); + for (int i = 0; i < expected.size(); i++) { + var unit = expected.get(i); + JsonNode epoch = epochs.get(i); + fields( + epoch, + Set.of( + "aggregateType", + "aggregateId", + "scopeType", + "scopeId", + "expectedEpoch", + "resultingEpoch")); + exactText(epoch, "aggregateType", unit.aggregateType()); + exactText(epoch, "aggregateId", unit.aggregateId()); + exactText(epoch, "scopeType", unit.scopeType()); + exactText(epoch, "scopeId", unit.scopeId()); + exactText(epoch, "expectedEpoch", unit.expectedEpoch()); + exactText( + epoch, + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString()); + } + } catch (java.io.IOException | NoSuchAlgorithmException | RuntimeException invalid) { + throw new IllegalArgumentException( + "World committed readback has an invalid or substituted canonical APPLIED result", + invalid); + } + } + + private static OriginalFreshGraph readOriginalFreshGraph( + DraftCommitBinding draft, boolean requireCompleteDeclaration) throws java.io.IOException { + Map nodes = new LinkedHashMap<>(); + JsonNode declaration = null; + for (DraftCommitBinding.RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + JsonNode mutation; + try { + mutation = JSON.readTree(revision.payload()); + } catch (RuntimeException invalidPayload) { + if (requireCompleteDeclaration) throw invalidPayload; + // Retained v1 payloads predate a common JSON shape; they cannot declare a new typed + // selector. + continue; + } + if (mutation == null || !mutation.isObject()) { + if (requireCompleteDeclaration) { + throw new IllegalArgumentException("Original World mutation payload is not an object"); + } + continue; + } + JsonNode graphDeclaration = mutation.get("freshGraphDeclaration"); + if (!requireCompleteDeclaration) { + if (graphDeclaration != null) { + throw new IllegalArgumentException( + "Historical World APPLIED v1 cannot downgrade a declared fresh graph"); + } + continue; + } + fieldsKnown(mutation, WORLD_MUTATION_FIELDS); + exactText(mutation, "logicalRevisionId", revision.revisionId().toString()); + exactText(mutation, "commitId", draft.commitId().toString()); + String family = text(mutation, "aggregateType"); + if (!FRESH_GRAPH_FAMILIES.contains(family)) { + throw new IllegalArgumentException("Unsupported family in declared World graph input"); + } + UUID templateId = parseCanonicalNonNilUuid(text(mutation, "aggregateId"), "aggregateId"); + String key = family + ":" + templateId; + if (nodes.putIfAbsent( + key, + new OriginalGraphNode( + family, templateId, revision.revisionId(), revision.revisionOrder())) + != null) { + throw new IllegalArgumentException("Original declared World graph repeats a template"); + } + if (graphDeclaration != null) { + if (declaration != null) { + throw new IllegalArgumentException( + "Original World input has multiple graph declarations"); + } + declaration = graphDeclaration; + } + } + if (!requireCompleteDeclaration) return null; + if (declaration == null || nodes.isEmpty()) { + throw new IllegalArgumentException( + "World v2 requires an original complete graph declaration"); + } + return parseOriginalFreshGraph(declaration, nodes, draft); + } + + private static OriginalFreshGraph parseOriginalFreshGraph( + JsonNode declaration, Map nodes, DraftCommitBinding draft) { + fields(declaration, FRESH_GRAPH_DECLARATION_FIELDS); + UUID tenantId = parseCanonicalNonNilUuid(text(declaration, "tenantId"), "declaration tenantId"); + UUID versionId = + parseCanonicalNonNilUuid(text(declaration, "versionId"), "declaration versionId"); + if (!tenantId.equals(draft.target().canonicalTenantId()) + || !versionId.equals(draft.target().canonicalVersionId())) { + throw new IllegalArgumentException("Original World graph declaration has another scope"); + } + JsonNode selector = declaration.get("startLocation"); + fields(selector, ROOM_TEMPLATE_REF_FIELDS); + UUID selectorTenant = + parseCanonicalNonNilUuid(text(selector, "tenantId"), "start selector tenantId"); + UUID selectorVersion = + parseCanonicalNonNilUuid(text(selector, "versionId"), "start selector versionId"); + UUID roomTemplateId = + parseCanonicalNonNilUuid(text(selector, "roomTemplateId"), "start selector roomTemplateId"); + if (!tenantId.equals(selectorTenant) || !versionId.equals(selectorVersion)) { + throw new IllegalArgumentException("Original World start selector has another scope"); + } + JsonNode counts = declaration.get("familyCounts"); + if (counts == null || !counts.isArray() || counts.size() != FRESH_GRAPH_FAMILIES.size()) { + throw new IllegalArgumentException("Original World graph declaration is incomplete"); + } + for (int i = 0; i < FRESH_GRAPH_FAMILIES.size(); i++) { + JsonNode entry = counts.get(i); + fields(entry, FAMILY_COUNT_FIELDS); + String family = text(entry, "family"); + JsonNode countNode = entry.get("count"); + if (!FRESH_GRAPH_FAMILIES.get(i).equals(family) + || countNode == null + || !countNode.isIntegralNumber() + || !countNode.canConvertToInt() + || countNode.intValue() < 0) { + throw new IllegalArgumentException( + "Original World graph family counts must be present, ordered and nonnegative"); + } + int actualCount = + (int) nodes.values().stream().filter(node -> node.family().equals(family)).count(); + if (actualCount != countNode.intValue()) { + throw new IllegalArgumentException( + "Original World graph family count differs from its complete typed input"); + } + } + OriginalGraphNode selectedRoom = + nodes.get("WORLD_DESIGN_AGGREGATE_TYPE_ROOM:" + roomTemplateId); + if (selectedRoom == null) { + throw new IllegalArgumentException( + "Original World start selector is absent from its ROOM graph"); + } + return new OriginalFreshGraph( + tenantId, + versionId, + roomTemplateId, + selectedRoom, + Map.copyOf(nodes), + List.copyOf(nodes.values())); + } + + private static void validateDeclaredGraphRows( + JsonNode rows, + OriginalFreshGraph original, + String targetNamespace, + DraftAuthorizationFenceBinding binding, + UUID versionIdentityOperationId) { + if (rows.size() != original.nodes().size()) { + throw new IllegalArgumentException( + "World v2 graph rows differ from the complete original input"); + } + Set seenNodes = new HashSet<>(); + Set seenMappingIds = new HashSet<>(); + Set seenPrivateRowKeys = new HashSet<>(); + Long privateTenantId = null; + Long privateVersionId = null; + boolean selectedRoomFound = false; + int rowIndex = 0; + for (JsonNode row : rows) { + fields(row, GRAPH_ROW_FIELDS); + JsonNode mapping = row.get("mapping"); + fields(mapping, GRAPH_MAPPING_FIELDS); + if (row.get("content") == null || !row.get("content").isObject()) { + throw new IllegalArgumentException("World v2 graph row content is absent"); + } + exactText(mapping, "target_namespace", targetNamespace); + exactText(mapping, "canonical_tenant_id", binding.tenantId().toString()); + exactText(mapping, "canonical_version_id", binding.versionId().toString()); + exactText(mapping, "request_id", binding.requestId().toString()); + exactText(mapping, "commit_id", binding.commitId().toString()); + String family = text(mapping, "family"); + if (!FRESH_GRAPH_FAMILIES.contains("WORLD_DESIGN_AGGREGATE_TYPE_" + family)) { + throw new IllegalArgumentException("World v2 graph row has an unsupported family"); + } + UUID templateId = parseCanonicalNonNilUuid(text(mapping, "template_id"), "graph template_id"); + String nodeKey = "WORLD_DESIGN_AGGREGATE_TYPE_" + family + ":" + templateId; + OriginalGraphNode originalNode = original.nodes().get(nodeKey); + if (originalNode == null + || !original.orderedNodes().get(rowIndex).equals(originalNode) + || !seenNodes.add(nodeKey) + || !originalNode.revisionId().toString().equals(text(mapping, "revision_id")) + || !originalNode.revisionOrder().equals(text(mapping, "revision_order"))) { + throw new IllegalArgumentException( + "World v2 graph row differs from its exact original revision"); + } + UUID graphVersionIdentityOperationId = + parseCanonicalNonNilUuid( + text(mapping, "version_identity_operation_id"), "graph Version identity operation"); + if (!versionIdentityOperationId.equals(graphVersionIdentityOperationId)) { + throw new IllegalArgumentException( + "World v2 graph uses another Version identity operation"); + } + long mappingId = positiveLong(mapping, "id"); + long tenantId = positiveLong(mapping, "tenant_id"); + long versionId = positiveLong(mapping, "version_id"); + long privateRowKey = positiveLong(mapping, "private_row_key"); + if (privateTenantId == null) { + privateTenantId = tenantId; + privateVersionId = versionId; + } else if (privateTenantId != tenantId || privateVersionId != versionId) { + throw new IllegalArgumentException( + "World v2 graph rows cross private tenant or Version scope"); + } + if (!seenMappingIds.add(mappingId) || !seenPrivateRowKeys.add(family + ":" + privateRowKey)) { + throw new IllegalArgumentException("World v2 graph contains a repeated private mapping"); + } + if (originalNode.equals(original.selectedRoom()) + && "ROOM".equals(family) + && templateId.equals(original.roomTemplateId())) { + selectedRoomFound = true; + } + rowIndex++; + } + if (!selectedRoomFound || seenNodes.size() != original.nodes().size()) { + throw new IllegalArgumentException("World v2 graph omits the exact selected ROOM row"); + } + } + + private static void validateStartLocationReceipt( + JsonNode result, + String graphDigest, + OriginalFreshGraph original, + WorldDraftTerminalReadEvidence.Request request, + DraftCommitBinding draft, + DraftAuthorizationFenceBinding binding) + throws NoSuchAlgorithmException { + var receipt = + WorldDraftStartLocationEvidence.fromStored(base64(result, "startLocationReceiptBase64")); + if (!receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.operationId().equals(binding.operationId()) + || !receipt.requestId().equals(binding.requestId()) + || !receipt.commitId().equals(binding.commitId()) + || !receipt.authorizationFenceId().equals(binding.fenceId()) + || !receipt.accountBindingDigest().equals(sha256(request.originalAccountBinding())) + || !receipt.bindingDigest().equals(draft.digest()) + || !receipt.startLocation().tenantId().equals(original.tenantId()) + || !receipt.startLocation().versionId().equals(original.versionId()) + || !receipt.startLocation().roomTemplateId().equals(original.roomTemplateId()) + || !receipt.graphDigest().equals(graphDigest)) { + throw new IllegalArgumentException( + "World start-location receipt differs from its original Account-bound graph"); + } + exactText(result, "startLocationReceiptDigest", receipt.receiptDigest()); + } + + private static long positiveLong(JsonNode value, String field) { + JsonNode actual = value.get(field); + if (actual == null + || !actual.isIntegralNumber() + || !actual.canConvertToLong() + || actual.longValue() <= 0) { + throw new IllegalArgumentException("World graph requires positive private mapping " + field); + } + return actual.longValue(); + } + + private static String text(JsonNode value, String field) { + JsonNode actual = value == null ? null : value.get(field); + if (actual == null || !actual.isTextual()) { + throw new IllegalArgumentException("World APPLIED carrier requires text " + field); + } + return actual.textValue(); + } + + private static void fieldsKnown(JsonNode value, Set fields) { + if (value == null + || !value.isObject() + || value.properties().stream().anyMatch(entry -> !fields.contains(entry.getKey()))) { + throw new IllegalArgumentException("Original World mutation has unsupported fields"); + } + } + + private record OriginalGraphNode( + String family, UUID templateId, UUID revisionId, String revisionOrder) {} + + private record OriginalFreshGraph( + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + OriginalGraphNode selectedRoom, + Map nodes, + List orderedNodes) {} + + private static void fields(JsonNode value, Set fields) { + if (value == null + || !value.isObject() + || value.size() != fields.size() + || value.properties().stream().anyMatch(entry -> !fields.contains(entry.getKey()))) + throw new IllegalArgumentException("World APPLIED carrier fields differ"); + } + + private static void exactText(JsonNode value, String field, String expected) { + if (value.get(field) == null + || !value.get(field).isTextual() + || !expected.equals(value.get(field).textValue())) + throw new IllegalArgumentException("World APPLIED carrier differs at " + field); + } + + private static String sha256(byte[] value) throws NoSuchAlgorithmException { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static byte[] base64(JsonNode value, String field) { + if (value.get(field) == null || !value.get(field).isTextual()) + throw new IllegalArgumentException("World APPLIED bytes missing"); + String encoded = value.get(field).textValue(); + byte[] decoded = Base64.getDecoder().decode(encoded); + if (decoded.length == 0 || !Base64.getEncoder().encodeToString(decoded).equals(encoded)) + throw new IllegalArgumentException("Noncanonical World APPLIED Base64"); + return decoded; + } + + private static final class FrameReader { + private final ByteBuffer bytes; + + private FrameReader(byte[] value) { + bytes = ByteBuffer.wrap(value); + } + + private byte[] frame() { + if (bytes.remaining() < Integer.BYTES) + throw new IllegalArgumentException("Truncated World operation"); + int size = bytes.getInt(); + if (size <= 0 || size > bytes.remaining()) + throw new IllegalArgumentException("Invalid World operation frame"); + byte[] value = new byte[size]; + bytes.get(value); + return value; + } + + private String text() { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(frame())) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException("Invalid World operation UTF-8", invalid); + } + } + + private void expect(String expected) { + if (!expected.equals(text())) + throw new IllegalArgumentException("Substituted World operation"); + } + + private void expectBytes(byte[] expected) { + if (!Arrays.equals(expected, frame())) + throw new IllegalArgumentException("Substituted World operation bytes"); + } + + private UUID canonicalUuid() { + return parseCanonicalNonNilUuid(text(), "World owner identity"); + } + + private void digest() { + if (!text().matches("(?:sha256:)?[0-9a-f]{64}")) + throw new IllegalArgumentException("Invalid World owner digest"); + } + + private void requireEnd() { + if (bytes.hasRemaining()) + throw new IllegalArgumentException("Trailing World operation bytes"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java new file mode 100644 index 0000000000..0cfe9621fe --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java @@ -0,0 +1,201 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; + +/** + * Explicit mTLS client for exact authored-world launch descriptor resolution and owner readback. + */ +public final class AuthoredWorldLaunchDescriptorClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignServiceGrpc.GameDesignServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AuthoredWorldLaunchDescriptorClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AuthoredWorldLaunchDescriptorClient.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 launch descriptor client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Authored-world launch descriptor client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Resolves a descriptor for exactly the supplied authored-world request tuple. */ + public AuthoredWorldLaunchDescriptorEvidence resolve( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(request)); + try { + return AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid authored-world launch descriptor evidence", exception); + } + } + + /** Reads back the immutable result using a separate read request UUID and the complete tuple. */ + public AuthoredWorldLaunchDescriptorEvidence get( + AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.expectedRequest().targetNamespace()); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getLaunchDescriptor(AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(request)); + try { + return AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid exact authored-world launch descriptor readback", + exception); + } + } + + /** Reads and validates the descriptor and separate release attestation as one exact pair. */ + public CompleteLaunchBindingEvidence getComplete(GetLaunchDescriptorRequest request) { + Objects.requireNonNull(request, "request"); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCompleteLaunchBinding(request); + try { + CompleteLaunchBindingEvidence evidence = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response); + requireNamespace(evidence.descriptor().targetNamespace()); + return evidence; + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid complete authored-world launch binding evidence", + exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub(ManagedChannel channel) { + String expectedGameDesignPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignServiceGrpc.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 GameDesignServiceGrpc.GameDesignServiceBlockingStub requireStub() { + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Authored-world launch descriptor client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Launch descriptor 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("Launch descriptor 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( + "Launch descriptor reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Launch descriptor reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Launch descriptor " + label + " must be a readable file-backed path", exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Launch descriptor " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java new file mode 100644 index 0000000000..5a6be36581 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorEvidence.java @@ -0,0 +1,568 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Closed immutable launch binding evidence for an exact Game Design authored-world source. */ +public record AuthoredWorldLaunchDescriptorEvidence( + int schemaVersion, + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + Long sourceVersionId, + boolean targetVersionIdPresent, + Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + String requestedRuntimeFlagsJson, + String requestDigest, + String launchDescriptorId, + long versionId, + boolean scriptPatchVersionPresent, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long versionStateEpoch, + long releaseBundleId, + String publishedReleaseBundleRef, + boolean remapSetIdPresent, + String remapSetId, + String resultDigest) { + public static final int SCHEMA_VERSION = 1; + private static final String REQUEST_DOMAIN = + "game-design-authored-world-launch-descriptor-request/v1"; + private static final String RESULT_DOMAIN = + "game-design-authored-world-launch-descriptor-result/v1"; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private record Field(String name, String value) {} + + /** The exact request values, including presence for every optional field. */ + public record Request( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + Long sourceVersionId, + boolean targetVersionIdPresent, + Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + String requestedRuntimeFlagsJson) { + public Request { + validateRequest( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + public String requestDigest() { + return AuthoredWorldLaunchDescriptorEvidence.requestDigest(this); + } + } + + public AuthoredWorldLaunchDescriptorEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world launch descriptor schema"); + } + Request request = + new Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + requireOptional(scriptPatchVersionPresent, scriptPatchVersion, "scriptPatchVersion"); + requireOptional(remapSetIdPresent, remapSetId, "remapSetId"); + requireText(launchDescriptorId, "launchDescriptorId"); + requirePositive(versionId, "versionId"); + requireText(runtimeFlagsJson, "runtimeFlagsJson"); + requireText(generationConfigRevision, "generationConfigRevision"); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + requirePositive(releaseBundleId, "releaseBundleId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + requireDigest(requestDigest, "requestDigest"); + if (!request.requestDigest().equals(requestDigest)) { + throw new IllegalArgumentException("Request digest does not match the exact request tuple"); + } + requireDigest(resultDigest, "resultDigest"); + } + + /** Recomputes both closed digests after construction or deserialization. */ + public void requireValid() { + if (!requestDigest(this.request()).equals(requestDigest) + || !resultDigest(this).equals(resultDigest)) { + throw new IllegalArgumentException("Result digest does not match the immutable descriptor"); + } + } + + public Request request() { + return new Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + public static AuthoredWorldLaunchDescriptorEvidence create( + Request request, + String launchDescriptorId, + long versionId, + boolean scriptPatchVersionPresent, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long versionStateEpoch, + long releaseBundleId, + String publishedReleaseBundleRef, + boolean remapSetIdPresent, + String remapSetId) { + Objects.requireNonNull(request, "request"); + AuthoredWorldLaunchDescriptorEvidence provisional = + new AuthoredWorldLaunchDescriptorEvidence( + SCHEMA_VERSION, + request.targetNamespace(), + request.controlPlaneRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + request.authoredWorldSourceOperationId(), + request.authoredWorldSourceEvidenceDigest(), + request.gameTemplateId(), + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion(), + request.sourceVersionIdPresent(), + request.sourceVersionId(), + request.targetVersionIdPresent(), + request.targetVersionId(), + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson(), + request.requestDigest(), + launchDescriptorId, + versionId, + scriptPatchVersionPresent, + scriptPatchVersion, + runtimeFlagsJson, + generationConfigRevision, + versionStateEpoch, + releaseBundleId, + publishedReleaseBundleRef, + remapSetIdPresent, + remapSetId, + "sha256:" + "0".repeat(64)); + AuthoredWorldLaunchDescriptorEvidence evidence = + new AuthoredWorldLaunchDescriptorEvidence( + provisional.schemaVersion(), + provisional.targetNamespace(), + provisional.controlPlaneRequestId(), + provisional.canonicalTenantId(), + provisional.worldSlug(), + provisional.authoredWorldSourceOperationId(), + provisional.authoredWorldSourceEvidenceDigest(), + provisional.gameTemplateId(), + provisional.requestedScriptPatchVersionPresent(), + provisional.requestedScriptPatchVersion(), + provisional.sourceVersionIdPresent(), + provisional.sourceVersionId(), + provisional.targetVersionIdPresent(), + provisional.targetVersionId(), + provisional.requestedRuntimeFlagsJsonPresent(), + provisional.requestedRuntimeFlagsJson(), + provisional.requestDigest(), + provisional.launchDescriptorId(), + provisional.versionId(), + provisional.scriptPatchVersionPresent(), + provisional.scriptPatchVersion(), + provisional.runtimeFlagsJson(), + provisional.generationConfigRevision(), + provisional.versionStateEpoch(), + provisional.releaseBundleId(), + provisional.publishedReleaseBundleRef(), + provisional.remapSetIdPresent(), + provisional.remapSetId(), + resultDigest(provisional)); + evidence.requireValid(); + return evidence; + } + + public static String requestDigest(Request request) { + Objects.requireNonNull(request, "request"); + return digest( + REQUEST_DOMAIN, + field("schemaVersion", Integer.toString(SCHEMA_VERSION)), + field("targetNamespace", request.targetNamespace()), + field("controlPlaneRequestId", request.controlPlaneRequestId()), + field("canonicalTenantId", request.canonicalTenantId().toString()), + field("worldSlug", request.worldSlug()), + field( + "authoredWorldSourceOperationId", request.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", request.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(request.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", request.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", request.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + request.sourceVersionIdPresent(), + decimal(request.sourceVersionId())), + optionalPresence("targetVersionId", request.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + request.targetVersionIdPresent(), + decimal(request.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", request.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson())); + } + + /** Computes the result digest while deliberately excluding only {@code resultDigest}. */ + public static String resultDigest(AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return digest( + RESULT_DOMAIN, + field("schemaVersion", Integer.toString(evidence.schemaVersion())), + field("targetNamespace", evidence.targetNamespace()), + field("controlPlaneRequestId", evidence.controlPlaneRequestId()), + field("canonicalTenantId", evidence.canonicalTenantId().toString()), + field("worldSlug", evidence.worldSlug()), + field( + "authoredWorldSourceOperationId", evidence.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(evidence.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", evidence.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + evidence.requestedScriptPatchVersionPresent(), + evidence.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", evidence.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + evidence.sourceVersionIdPresent(), + decimal(evidence.sourceVersionId())), + optionalPresence("targetVersionId", evidence.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + evidence.targetVersionIdPresent(), + decimal(evidence.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", evidence.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + evidence.requestedRuntimeFlagsJsonPresent(), + evidence.requestedRuntimeFlagsJson()), + field("requestDigest", evidence.requestDigest()), + field("launchDescriptorId", evidence.launchDescriptorId()), + field("versionId", Long.toString(evidence.versionId())), + optionalPresence("scriptPatchVersion", evidence.scriptPatchVersionPresent()), + optionalValue( + "scriptPatchVersion", + evidence.scriptPatchVersionPresent(), + evidence.scriptPatchVersion()), + field("runtimeFlagsJson", evidence.runtimeFlagsJson()), + field("generationConfigRevision", evidence.generationConfigRevision()), + field("versionStateEpoch", Long.toString(evidence.versionStateEpoch())), + field("releaseBundleId", Long.toString(evidence.releaseBundleId())), + field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef()), + optionalPresence("remapSetId", evidence.remapSetIdPresent()), + optionalValue("remapSetId", evidence.remapSetIdPresent(), evidence.remapSetId())); + } + + /** Returns the exact UTF-8 request preimage for shared producer and consumer proof. */ + public static byte[] requestPreimage(Request request) { + return preimage( + REQUEST_DOMAIN, + field("schemaVersion", Integer.toString(SCHEMA_VERSION)), + field("targetNamespace", request.targetNamespace()), + field("controlPlaneRequestId", request.controlPlaneRequestId()), + field("canonicalTenantId", request.canonicalTenantId().toString()), + field("worldSlug", request.worldSlug()), + field( + "authoredWorldSourceOperationId", request.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", request.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(request.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", request.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", request.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + request.sourceVersionIdPresent(), + decimal(request.sourceVersionId())), + optionalPresence("targetVersionId", request.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + request.targetVersionIdPresent(), + decimal(request.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", request.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + request.requestedRuntimeFlagsJsonPresent(), + request.requestedRuntimeFlagsJson())); + } + + /** Returns the exact UTF-8 result preimage, excluding only the result digest itself. */ + public static byte[] resultPreimage(AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return preimage( + RESULT_DOMAIN, + field("schemaVersion", Integer.toString(evidence.schemaVersion())), + field("targetNamespace", evidence.targetNamespace()), + field("controlPlaneRequestId", evidence.controlPlaneRequestId()), + field("canonicalTenantId", evidence.canonicalTenantId().toString()), + field("worldSlug", evidence.worldSlug()), + field( + "authoredWorldSourceOperationId", evidence.authoredWorldSourceOperationId().toString()), + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest()), + field("gameTemplateId", Long.toString(evidence.gameTemplateId())), + optionalPresence( + "requestedScriptPatchVersion", evidence.requestedScriptPatchVersionPresent()), + optionalValue( + "requestedScriptPatchVersion", + evidence.requestedScriptPatchVersionPresent(), + evidence.requestedScriptPatchVersion()), + optionalPresence("sourceVersionId", evidence.sourceVersionIdPresent()), + optionalValue( + "sourceVersionId", + evidence.sourceVersionIdPresent(), + decimal(evidence.sourceVersionId())), + optionalPresence("targetVersionId", evidence.targetVersionIdPresent()), + optionalValue( + "targetVersionId", + evidence.targetVersionIdPresent(), + decimal(evidence.targetVersionId())), + optionalPresence("requestedRuntimeFlagsJson", evidence.requestedRuntimeFlagsJsonPresent()), + optionalValue( + "requestedRuntimeFlagsJson", + evidence.requestedRuntimeFlagsJsonPresent(), + evidence.requestedRuntimeFlagsJson()), + field("requestDigest", evidence.requestDigest()), + field("launchDescriptorId", evidence.launchDescriptorId()), + field("versionId", Long.toString(evidence.versionId())), + optionalPresence("scriptPatchVersion", evidence.scriptPatchVersionPresent()), + optionalValue( + "scriptPatchVersion", + evidence.scriptPatchVersionPresent(), + evidence.scriptPatchVersion()), + field("runtimeFlagsJson", evidence.runtimeFlagsJson()), + field("generationConfigRevision", evidence.generationConfigRevision()), + field("versionStateEpoch", Long.toString(evidence.versionStateEpoch())), + field("releaseBundleId", Long.toString(evidence.releaseBundleId())), + field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef()), + optionalPresence("remapSetId", evidence.remapSetIdPresent()), + optionalValue("remapSetId", evidence.remapSetIdPresent(), evidence.remapSetId())); + } + + private static void validateRequest( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + long gameTemplateId, + boolean requestedPatchPresent, + String requestedPatch, + boolean sourceVersionPresent, + Long sourceVersion, + boolean targetVersionPresent, + Long targetVersion, + boolean runtimeFlagsPresent, + String runtimeFlags) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + if (controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId is required"); + } + if (strictUtf8(controlPlaneRequestId).length > 64) { + throw new IllegalArgumentException("controlPlaneRequestId exceeds its stored byte bound"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(sourceOperationId, "authoredWorldSourceOperationId"); + requireDigest(sourceEvidenceDigest, "authoredWorldSourceEvidenceDigest"); + requirePositive(gameTemplateId, "gameTemplateId"); + requireOptional(requestedPatchPresent, requestedPatch, "requestedScriptPatchVersion"); + requireOptional(sourceVersionPresent, sourceVersion, "sourceVersionId"); + if (sourceVersionPresent) { + requirePositive(sourceVersion, "sourceVersionId"); + } + requireOptional(targetVersionPresent, targetVersion, "targetVersionId"); + if (targetVersionPresent) { + requirePositive(targetVersion, "targetVersionId"); + } + requireOptional(runtimeFlagsPresent, runtimeFlags, "requestedRuntimeFlagsJson"); + } + + private static Field optionalPresence(String name, boolean present) { + return field(name + ".present", Boolean.toString(present)); + } + + private static Field optionalValue(String name, boolean present, String value) { + return field(name + ".value", present ? Objects.requireNonNull(value, name) : ""); + } + + private static Field field(String name, String value) { + return new Field(name, value); + } + + private static String digest(String domain, Field... fields) { + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage(domain, fields))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] preimage(String domain, Field... fields) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + writeSegment(bytes, domain); + for (Field field : fields) { + writeSegment(bytes, field.name()); + writeSegment(bytes, field.value()); + } + return bytes.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must contain valid Unicode", exception); + } + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requirePositive(Long value, String name) { + if (value == null || value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + strictUtf8(value); + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a lowercase SHA-256 digest"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java new file mode 100644 index 0000000000..e60242dd9e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java @@ -0,0 +1,444 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; + +/** Closed mapping and exact-readback validation for authored-world launch descriptor RPCs. */ +public final class AuthoredWorldLaunchDescriptorGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + /** Exact owner read identity and the immutable resolve tuple whose result is being recovered. */ + public record GetRequest( + UUID requestId, + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, + String expectedResultDigest) { + public GetRequest { + if (requestId == null || NIL_UUID.equals(requestId)) { + throw new IllegalArgumentException( + "A nonnil launch descriptor read request ID is required"); + } + Objects.requireNonNull(expectedRequest, "expectedRequest"); + if (requestId.equals(expectedRequest.authoredWorldSourceOperationId()) + || requestId.toString().equals(expectedRequest.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Launch descriptor read request ID must be distinct from the original request"); + } + if (expectedResultDigest == null || !SHA256.matcher(expectedResultDigest).matches()) { + throw new IllegalArgumentException( + "Expected launch descriptor result digest must be canonical SHA-256 text"); + } + } + } + + private AuthoredWorldLaunchDescriptorGrpcCodec() {} + + /** Encodes only the exact request fields owned by the immutable shared request value. */ + public static ResolveLaunchDescriptorRequest toResolveRequest( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + Objects.requireNonNull(request, "request"); + ResolveLaunchDescriptorRequest.Builder builder = + ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setGameTemplateId(request.gameTemplateId()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setWorldSlug(request.worldSlug()) + .setAuthoredWorldSourceOperationId(request.authoredWorldSourceOperationId().toString()) + .setExpectedAuthoredWorldSourceEvidenceDigest( + request.authoredWorldSourceEvidenceDigest()); + if (request.requestedScriptPatchVersionPresent()) { + builder.setRequestedScriptPatchVersion(request.requestedScriptPatchVersion()); + } + if (request.sourceVersionIdPresent()) { + builder.setSourceVersionId(request.sourceVersionId()); + } + if (request.targetVersionIdPresent()) { + builder.setTargetVersionId(request.targetVersionId()); + } + if (request.requestedRuntimeFlagsJsonPresent()) { + builder.setRequestedRuntimeFlagsJson(request.requestedRuntimeFlagsJson()); + } + return builder.build(); + } + + /** Encodes an exact persisted owner read, kept distinct from the original resolve identity. */ + public static GetLaunchDescriptorRequest toGetRequest(GetRequest request) { + Objects.requireNonNull(request, "request"); + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(request.requestId().toString()) + .setCanonicalTenantId(expected.canonicalTenantId().toString()) + .setWorldSlug(expected.worldSlug()) + .setControlPlaneRequestId(expected.controlPlaneRequestId()) + .setExpectedRequestDigest(expected.requestDigest()) + .setExpectedResultDigest(request.expectedResultDigest()) + .build(); + } + + /** Validates the complete response and flat descriptor duplicates against the exact request. */ + public static AuthoredWorldLaunchDescriptorEvidence fromResolveResponse( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, + ResolveLaunchDescriptorResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ResolveLaunchDescriptor response"); + if (response.hasError()) { + throw new IllegalArgumentException("Game Design rejected launch descriptor resolution"); + } + if (!response.hasLaunchDescriptor()) { + throw new IllegalArgumentException("Launch descriptor resolution returned no descriptor"); + } + return decodeDescriptor(expectedRequest, response.getLaunchDescriptor()); + } + + /** Validates an exact read echo, original request tuple, result digest, and duplicate fields. */ + public static AuthoredWorldLaunchDescriptorEvidence fromGetResponse( + GetRequest request, GetLaunchDescriptorResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "GetLaunchDescriptor response"); + if (response.hasError()) { + throw new IllegalArgumentException("Game Design rejected the exact launch descriptor read"); + } + UUID echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "read request ID"); + if (!request.requestId().equals(echoedRequestId)) { + throw new IllegalArgumentException("Launch descriptor read request ID echo changed"); + } + if (!response.hasLaunchDescriptor()) { + throw new IllegalArgumentException("Exact launch descriptor read returned no descriptor"); + } + AuthoredWorldLaunchDescriptorEvidence evidence = + decodeDescriptor(request.expectedRequest(), response.getLaunchDescriptor()); + if (!request.expectedResultDigest().equals(evidence.resultDigest())) { + throw new IllegalArgumentException( + "Launch descriptor result digest does not match the exact read request"); + } + return evidence; + } + + /** + * Validates the complete owner response as one atomic descriptor and attestation pair. The + * request is the exact immutable read selector; neither component is accepted alone. + */ + public static CompleteLaunchBindingEvidence fromCompleteResponse( + GetLaunchDescriptorRequest request, GetCompleteLaunchBindingResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(request, "GetCompleteLaunchBinding request"); + requireNoUnknownFields(response, "GetCompleteLaunchBinding response"); + if (response.hasError()) { + requireNoUnknownFields(response.getError(), "GetCompleteLaunchBinding error"); + throw new IllegalArgumentException("Game Design rejected the complete launch binding read"); + } + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId(), "read request ID"); + UUID echoedRequestId = + parseCanonicalNonNilUuid(response.getRequestId(), "read request ID echo"); + if (!readRequestId.equals(echoedRequestId)) { + throw new IllegalArgumentException("Complete launch binding read request ID echo changed"); + } + if (!response.hasLaunchDescriptor() || !response.hasReleaseAttestation()) { + throw new IllegalArgumentException( + "Complete launch binding read must return both descriptor and release attestation"); + } + + AuthoredWorldLaunchDescriptorEvidence descriptor = + decodeDescriptor(response.getLaunchDescriptor()); + if (readRequestId.equals(descriptor.authoredWorldSourceOperationId()) + || readRequestId.toString().equals(descriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Complete launch binding read request ID must be distinct from the original request"); + } + if (!descriptor.canonicalTenantId().toString().equals(request.getCanonicalTenantId()) + || !descriptor.worldSlug().equals(request.getWorldSlug()) + || !descriptor.controlPlaneRequestId().equals(request.getControlPlaneRequestId()) + || !descriptor.requestDigest().equals(request.getExpectedRequestDigest()) + || !descriptor.resultDigest().equals(request.getExpectedResultDigest())) { + throw new IllegalArgumentException( + "Complete launch binding does not match the exact read selector"); + } + + AuthoredWorldReleaseAttestationEvidence releaseAttestation = + decodeReleaseAttestation(response.getReleaseAttestation()); + try { + return new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Complete launch binding evidence is invalid", exception); + } + } + + /** Encodes the separate closed release attestation without changing descriptor/v1. */ + public static net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence + toReleaseAttestation(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + evidence.requireValid(); + var builder = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setDescriptorResultDigest(evidence.descriptorResultDigest()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setCanonicalVersionId(evidence.canonicalVersionId().toString()) + .setWorldSlug(evidence.worldSlug()) + .setAuthoredWorldSourceOperationId(evidence.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()) + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setPublishWorkflowId(evidence.publishWorkflowId()) + .setCommitId(evidence.commitId()) + .setManifestHash(evidence.manifestHash()) + .setManifestSchemaVersion(evidence.manifestSchemaVersion()) + .addAllRequiredManifestAssetKeys(evidence.requiredManifestAssetKeys()) + .addAllCommandDefinitions(evidence.commandDefinitions()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setEvidenceDigest(evidence.evidenceDigest()); + if (evidence.worldStartLocationEvidence() != null) { + builder.setWorldStartLocationEvidence( + ByteString.copyFrom(evidence.worldStartLocationEvidence().canonicalBytes())); + } + for (AuthoredWorldReleaseAttestationEvidence.Participant participant : + evidence.participantDigests()) { + ParticipantDigest.Builder participantBuilder = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigestPresent()) { + participantBuilder.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + } + builder.addParticipantDigests(participantBuilder); + } + for (AuthoredWorldReleaseAttestationEvidence.Artifact artifact : evidence.artifactDigests()) { + builder.addArtifactDigests( + PublishedArtifactDigest.newBuilder() + .setUsageKey(artifact.usageKey()) + .setArtifactKind(artifact.artifactKind()) + .setImmutableObjectKey(artifact.immutableObjectKey()) + .setContentDigest(artifact.contentDigest()) + .setContentType(artifact.contentType()) + .setArtifactSchemaVersion(artifact.artifactSchemaVersion())); + } + return builder.build(); + } + + private static AuthoredWorldLaunchDescriptorEvidence decodeDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, LaunchDescriptor descriptor) { + AuthoredWorldLaunchDescriptorEvidence evidence = decodeDescriptor(descriptor); + if (!evidence.request().equals(expectedRequest)) { + throw new IllegalArgumentException( + "Launch descriptor does not match the exact authored-world resolve request"); + } + return evidence; + } + + private static AuthoredWorldLaunchDescriptorEvidence decodeDescriptor( + LaunchDescriptor descriptor) { + requireNoUnknownFields(descriptor, "LaunchDescriptor"); + if (!descriptor.getTenantId().isEmpty()) { + throw new IllegalArgumentException( + "Canonical descriptor cannot contain a legacy tenant selector"); + } + if (!descriptor.hasAuthoredWorldBinding()) { + throw new IllegalArgumentException("Launch descriptor has no authored-world binding"); + } + var binding = descriptor.getAuthoredWorldBinding(); + requireNoUnknownFields(binding, "AuthoredWorldLaunchDescriptorEvidence"); + + AuthoredWorldLaunchDescriptorEvidence evidence; + try { + evidence = + new AuthoredWorldLaunchDescriptorEvidence( + binding.getSchemaVersion(), + binding.getTargetNamespace(), + binding.getControlPlaneRequestId(), + parseCanonicalNonNilUuid(binding.getCanonicalTenantId(), "canonical tenant ID"), + binding.getWorldSlug(), + parseCanonicalNonNilUuid( + binding.getAuthoredWorldSourceOperationId(), + "authored-world source operation ID"), + binding.getAuthoredWorldSourceEvidenceDigest(), + binding.getGameTemplateId(), + binding.hasRequestedScriptPatchVersion(), + binding.hasRequestedScriptPatchVersion() + ? binding.getRequestedScriptPatchVersion() + : null, + binding.hasSourceVersionId(), + binding.hasSourceVersionId() ? binding.getSourceVersionId() : null, + binding.hasTargetVersionId(), + binding.hasTargetVersionId() ? binding.getTargetVersionId() : null, + binding.hasRequestedRuntimeFlagsJson(), + binding.hasRequestedRuntimeFlagsJson() + ? binding.getRequestedRuntimeFlagsJson() + : null, + binding.getRequestDigest(), + binding.getLaunchDescriptorId(), + binding.getVersionId(), + binding.hasScriptPatchVersion(), + binding.hasScriptPatchVersion() ? binding.getScriptPatchVersion() : null, + binding.getRuntimeFlagsJson(), + binding.getGenerationConfigRevision(), + binding.getVersionStateEpoch(), + binding.getReleaseBundleId(), + binding.getPublishedReleaseBundleRef(), + binding.hasRemapSetId(), + binding.hasRemapSetId() ? binding.getRemapSetId() : null, + binding.getResultDigest()); + evidence.requireValid(); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Authored-world launch evidence is invalid", exception); + } + + requireFlatDuplicate( + descriptor.getLaunchDescriptorId(), evidence.launchDescriptorId(), "launchDescriptorId"); + requireFlatDuplicate( + descriptor.getCanonicalTenantId(), + evidence.canonicalTenantId().toString(), + "canonicalTenantId"); + requireFlatDuplicate( + descriptor.getGameTemplateId(), evidence.gameTemplateId(), "gameTemplateId"); + requireFlatDuplicate( + descriptor.getControlPlaneRequestId(), + evidence.controlPlaneRequestId(), + "controlPlaneRequestId"); + requireFlatDuplicate(descriptor.getVersionId(), evidence.versionId(), "versionId"); + requireFlatDuplicate( + descriptor.getScriptPatchVersion(), + evidence.scriptPatchVersionPresent() ? evidence.scriptPatchVersion() : "", + "scriptPatchVersion"); + requireFlatDuplicate( + descriptor.getRuntimeFlagsJson(), evidence.runtimeFlagsJson(), "runtimeFlagsJson"); + requireFlatDuplicate( + descriptor.getGenerationConfigRevision(), + evidence.generationConfigRevision(), + "generationConfigRevision"); + requireFlatDuplicate( + descriptor.getVersionStateEpoch(), evidence.versionStateEpoch(), "versionStateEpoch"); + requireFlatDuplicate( + descriptor.getReleaseBundleId(), evidence.releaseBundleId(), "releaseBundleId"); + requireFlatDuplicate( + descriptor.getPublishedReleaseBundleRef(), + evidence.publishedReleaseBundleRef(), + "publishedReleaseBundleRef"); + requireFlatDuplicate( + descriptor.getRemapSetId(), + evidence.remapSetIdPresent() ? evidence.remapSetId() : "", + "remapSetId"); + return evidence; + } + + private static AuthoredWorldReleaseAttestationEvidence decodeReleaseAttestation( + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence wire) { + requireNoUnknownFields(wire, "AuthoredWorldReleaseAttestationEvidence"); + List participants = + new java.util.ArrayList<>(wire.getParticipantDigestsCount()); + for (ParticipantDigest participant : wire.getParticipantDigestsList()) { + requireNoUnknownFields(participant, "ParticipantDigest"); + participants.add( + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.getParticipantKey(), + participant.getScopeValue(), + false, + null, + participant.getAppliedCommitId(), + participant.getContentDigest(), + participant.getDigestSchemaVersion(), + participant.hasAbilitySchemaDigest(), + participant.hasAbilitySchemaDigest() ? participant.getAbilitySchemaDigest() : null)); + } + List artifacts = + new java.util.ArrayList<>(wire.getArtifactDigestsCount()); + for (PublishedArtifactDigest artifact : wire.getArtifactDigestsList()) { + requireNoUnknownFields(artifact, "PublishedArtifactDigest"); + artifacts.add( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + artifact.getUsageKey(), + artifact.getArtifactKind(), + artifact.getImmutableObjectKey(), + artifact.getContentDigest(), + artifact.getContentType(), + artifact.getArtifactSchemaVersion())); + } + try { + return new AuthoredWorldReleaseAttestationEvidence( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + wire.getDescriptorResultDigest(), + parseCanonicalNonNilUuid(wire.getCanonicalTenantId(), "canonical tenant ID"), + parseCanonicalNonNilUuid(wire.getCanonicalVersionId(), "canonical version ID"), + wire.getWorldSlug(), + parseCanonicalNonNilUuid( + wire.getAuthoredWorldSourceOperationId(), "authored-world source operation ID"), + wire.getAuthoredWorldSourceEvidenceDigest(), + wire.getLaunchDescriptorId(), + wire.getPublishedReleaseBundleRef(), + wire.getVersionStateEpoch(), + wire.getPublishWorkflowId(), + wire.getCommitId(), + participants, + wire.getManifestHash(), + wire.getManifestSchemaVersion(), + wire.getRequiredManifestAssetKeysList(), + artifacts, + wire.getCommandDefinitionsList(), + wire.getGenerationConfigRevision(), + wire.getEvidenceDigest(), + wire.hasWorldStartLocationEvidence() + ? WorldPublishedStartLocationEvidence.fromStored( + wire.getWorldStartLocationEvidence().toByteArray()) + : null); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Release-attestation evidence is invalid", exception); + } + } + + 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); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static void requireFlatDuplicate(String actual, String expected, String field) { + if (!Objects.equals(actual, expected)) { + throw new IllegalArgumentException( + "Flat launch descriptor " + field + " does not match evidence"); + } + } + + private static void requireFlatDuplicate(long actual, long expected, String field) { + if (actual != expected) { + throw new IllegalArgumentException( + "Flat launch descriptor " + field + " does not match evidence"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java new file mode 100644 index 0000000000..b58a5b34d1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java @@ -0,0 +1,732 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Closed immutable full release-attestation evidence for an authored-world launch. */ +public record AuthoredWorldReleaseAttestationEvidence( + int schemaVersion, + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + String evidenceDigest, + @JsonInclude(JsonInclude.Include.NON_NULL) + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + public static final int SCHEMA_VERSION = 1; + public static final int SELECTOR_SCHEMA_VERSION = 2; + private static final String EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v1"; + private static final String SELECTOR_EVIDENCE_DOMAIN = + "game-design-authored-world-release-attestation/v2"; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern PARTICIPANT_CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final List PARTICIPANT_ORDER = + List.of( + "WORLD_MANAGEMENT", + "ENTITY_MANAGEMENT", + "GAME_LOGIC", + "AUTOMATION_SCRIPTING", + "GAME_DESIGN_CONTROL_PLANE"); + private static final Map SUPPORTED_PARTICIPANT_DIGEST_SCHEMAS = + Map.of( + "WORLD_MANAGEMENT", 3, + "ENTITY_MANAGEMENT", 2, + "GAME_LOGIC", 1, + "AUTOMATION_SCRIPTING", 5, + "GAME_DESIGN_CONTROL_PLANE", 1); + private static final Comparator UNSIGNED_UTF8_ORDER = + AuthoredWorldReleaseAttestationEvidence::compareUnsignedUtf8; + + private record Field(String name, String value) {} + + /** Returns the required full-Version participant owner order. */ + public static List requiredParticipantOrder() { + return PARTICIPANT_ORDER; + } + + /** Returns the one supported digest schema for a required participant owner. */ + public static int supportedParticipantDigestSchema(String participantKey) { + Objects.requireNonNull(participantKey, "participantKey"); + Integer version = SUPPORTED_PARTICIPANT_DIGEST_SCHEMAS.get(participantKey); + if (version == null) { + throw new IllegalArgumentException("Unsupported full-Version participant owner"); + } + return version; + } + + /** One successful, immutable owner digest included in the release attestation. */ + public record Participant( + String participantKey, + String scopeValue, + boolean baseVersionIdPresent, + Long baseVersionId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + boolean abilitySchemaDigestPresent, + String abilitySchemaDigest) { + public Participant { + requireText(participantKey, "participantKey"); + requireText(scopeValue, "scopeValue"); + requireOptional(baseVersionIdPresent, baseVersionId, "baseVersionId"); + if (baseVersionIdPresent) { + requirePositive(baseVersionId, "baseVersionId"); + } + requireText(appliedCommitId, "appliedCommitId"); + requireParticipantContentDigest(contentDigest); + requirePositiveSchema(digestSchemaVersion, "digestSchemaVersion"); + requireOptional(abilitySchemaDigestPresent, abilitySchemaDigest, "abilitySchemaDigest"); + if (abilitySchemaDigestPresent) { + requireDigest(abilitySchemaDigest, "abilitySchemaDigest"); + } + } + } + + /** One content-addressed artifact included in the immutable release manifest. */ + public record Artifact( + String usageKey, + String artifactKind, + String immutableObjectKey, + String contentDigest, + String contentType, + int artifactSchemaVersion) { + public Artifact { + requireText(usageKey, "usageKey"); + requireText(artifactKind, "artifactKind"); + requireText(immutableObjectKey, "immutableObjectKey"); + requireDigest(contentDigest, "contentDigest"); + requireText(contentType, "contentType"); + requireSupportedSchema(artifactSchemaVersion, "artifactSchemaVersion"); + String digestHex = contentDigest.substring("sha256:".length()); + String expectedObjectKey = "artifacts/sha256/" + digestHex; + if (!expectedObjectKey.equals(immutableObjectKey)) { + throw new IllegalArgumentException( + "immutableObjectKey must be the content-addressed key for contentDigest"); + } + } + } + + public AuthoredWorldReleaseAttestationEvidence { + if (schemaVersion != SCHEMA_VERSION && schemaVersion != SELECTOR_SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); + } + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + requireDigest(descriptorResultDigest, "descriptorResultDigest"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(authoredWorldSourceOperationId, "authoredWorldSourceOperationId"); + requireDigest(authoredWorldSourceEvidenceDigest, "authoredWorldSourceEvidenceDigest"); + requireText(launchDescriptorId, "launchDescriptorId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef"); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(commitId, "commitId"); + participantDigests = + List.copyOf(Objects.requireNonNull(participantDigests, "participantDigests")); + validateParticipants(participantDigests, commitId); + requireDigest(manifestHash, "manifestHash"); + requireSupportedSchema(manifestSchemaVersion, "manifestSchemaVersion"); + requiredManifestAssetKeys = + List.copyOf(Objects.requireNonNull(requiredManifestAssetKeys, "requiredManifestAssetKeys")); + validateOrderedUniqueStrings(requiredManifestAssetKeys, "requiredManifestAssetKeys"); + artifactDigests = List.copyOf(Objects.requireNonNull(artifactDigests, "artifactDigests")); + validateArtifacts(artifactDigests, requiredManifestAssetKeys); + commandDefinitions = + List.copyOf(Objects.requireNonNull(commandDefinitions, "commandDefinitions")); + for (String commandDefinition : commandDefinitions) { + strictUtf8(Objects.requireNonNull(commandDefinition, "commandDefinition")); + } + requireText(generationConfigRevision, "generationConfigRevision"); + requireDigest(evidenceDigest, "evidenceDigest"); + if ((schemaVersion == SELECTOR_SCHEMA_VERSION) != (worldStartLocationEvidence != null)) { + throw new IllegalArgumentException( + "Only release-attestation/v2 requires World selector evidence"); + } + if (worldStartLocationEvidence != null) { + WorldPublishedStartLocationEvidence.fromStored(worldStartLocationEvidence.canonicalBytes()); + var selected = worldStartLocationEvidence.request(); + var world = participantDigests.getFirst(); + if (!targetNamespace.equals(selected.targetNamespace()) + || !canonicalTenantId.equals(selected.canonicalTenantId()) + || !canonicalVersionId.equals(selected.canonicalVersionId()) + || !publishWorkflowId.equals(selected.publishWorkflowId()) + || !commitId.equals(selected.appliedCommitId()) + || !world.contentDigest().equals(selected.contentDigest()) + || world.digestSchemaVersion() != selected.digestSchemaVersion()) { + throw new IllegalArgumentException( + "World selector differs from the exact attested release checkpoint"); + } + } + } + + /** Original v1 constructor: retained bytes never gain a selector. */ + public AuthoredWorldReleaseAttestationEvidence( + int schemaVersion, + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + String evidenceDigest) { + this( + schemaVersion, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + evidenceDigest, + null); + } + + /** Creates v2 from the exact unchanged World evidence retained in the immutable release. */ + public static AuthoredWorldReleaseAttestationEvidence create( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + Objects.requireNonNull(worldStartLocationEvidence, "worldStartLocationEvidence"); + var provisional = + new AuthoredWorldReleaseAttestationEvidence( + SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + "sha256:" + "0".repeat(64), + worldStartLocationEvidence); + return new AuthoredWorldReleaseAttestationEvidence( + SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + computeEvidenceDigest(provisional), + worldStartLocationEvidence); + } + + /** Creates evidence from the complete owner attestation and derives its evidence digest. */ + public static AuthoredWorldReleaseAttestationEvidence create( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision) { + AuthoredWorldReleaseAttestationEvidence provisional = + new AuthoredWorldReleaseAttestationEvidence( + SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + "sha256:" + "0".repeat(64)); + AuthoredWorldReleaseAttestationEvidence evidence = + new AuthoredWorldReleaseAttestationEvidence( + provisional.schemaVersion(), + provisional.targetNamespace(), + provisional.descriptorResultDigest(), + provisional.canonicalTenantId(), + provisional.canonicalVersionId(), + provisional.worldSlug(), + provisional.authoredWorldSourceOperationId(), + provisional.authoredWorldSourceEvidenceDigest(), + provisional.launchDescriptorId(), + provisional.publishedReleaseBundleRef(), + provisional.versionStateEpoch(), + provisional.publishWorkflowId(), + provisional.commitId(), + provisional.participantDigests(), + provisional.manifestHash(), + provisional.manifestSchemaVersion(), + provisional.requiredManifestAssetKeys(), + provisional.artifactDigests(), + provisional.commandDefinitions(), + provisional.generationConfigRevision(), + computeEvidenceDigest(provisional)); + evidence.requireValid(); + return evidence; + } + + /** Recomputes the closed evidence digest after construction or deserialization. */ + public void requireValid() { + if (!computeEvidenceDigest(this).equals(evidenceDigest)) { + throw new IllegalArgumentException( + "Evidence digest does not match the exact release attestation"); + } + } + + /** Recomputes both closed digests and binds every applicable descriptor field exactly. */ + public void requireValid(AuthoredWorldLaunchDescriptorEvidence descriptor) { + Objects.requireNonNull(descriptor, "descriptor"); + requireValid(); + descriptor.requireValid(); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !descriptorResultDigest.equals(descriptor.resultDigest()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !authoredWorldSourceOperationId.equals(descriptor.authoredWorldSourceOperationId()) + || !authoredWorldSourceEvidenceDigest.equals(descriptor.authoredWorldSourceEvidenceDigest()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId()) + || !publishedReleaseBundleRef.equals(descriptor.publishedReleaseBundleRef()) + || versionStateEpoch != descriptor.versionStateEpoch() + || !generationConfigRevision.equals(descriptor.generationConfigRevision())) { + throw new IllegalArgumentException( + "Release attestation does not match the exact launch descriptor binding"); + } + String descriptorVersionScope = Long.toString(descriptor.versionId()); + for (Participant participant : participantDigests) { + if (!descriptorVersionScope.equals(participant.scopeValue())) { + throw new IllegalArgumentException( + "Participant scope does not match the launch descriptor Version"); + } + } + } + + /** Computes the digest using the schema-specific domain and exhaustive field order. */ + public static String computeEvidenceDigest(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return "sha256:" + HexFormat.of().formatHex(sha256(evidencePreimage(evidence))); + } + + /** Returns the exact strict-UTF-8 preimage for cross-language codec proof. */ + public static byte[] evidencePreimage(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + List fields = new ArrayList<>(); + fields.add(field("schemaVersion", Integer.toString(evidence.schemaVersion()))); + fields.add(field("targetNamespace", evidence.targetNamespace())); + fields.add(field("descriptorResultDigest", evidence.descriptorResultDigest())); + fields.add(field("canonicalTenantId", evidence.canonicalTenantId().toString())); + fields.add(field("canonicalVersionId", evidence.canonicalVersionId().toString())); + fields.add(field("worldSlug", evidence.worldSlug())); + fields.add( + field( + "authoredWorldSourceOperationId", + evidence.authoredWorldSourceOperationId().toString())); + fields.add( + field("authoredWorldSourceEvidenceDigest", evidence.authoredWorldSourceEvidenceDigest())); + fields.add(field("launchDescriptorId", evidence.launchDescriptorId())); + fields.add(field("publishedReleaseBundleRef", evidence.publishedReleaseBundleRef())); + fields.add(field("versionStateEpoch", Long.toString(evidence.versionStateEpoch()))); + fields.add(field("publishWorkflowId", evidence.publishWorkflowId())); + fields.add(field("commitId", evidence.commitId())); + fields.add( + field("participantDigests.size", Integer.toString(evidence.participantDigests().size()))); + for (int index = 0; index < evidence.participantDigests().size(); index++) { + Participant participant = evidence.participantDigests().get(index); + String prefix = "participantDigests[" + index + "]."; + fields.add(field(prefix + "participantKey", participant.participantKey())); + fields.add(field(prefix + "scopeValue", participant.scopeValue())); + fields.add(optionalPresence(prefix + "baseVersionId", participant.baseVersionIdPresent())); + fields.add( + optionalValue( + prefix + "baseVersionId", + participant.baseVersionIdPresent(), + decimal(participant.baseVersionId()))); + fields.add(field(prefix + "appliedCommitId", participant.appliedCommitId())); + fields.add(field(prefix + "contentDigest", participant.contentDigest())); + fields.add( + field( + prefix + "digestSchemaVersion", Integer.toString(participant.digestSchemaVersion()))); + fields.add( + optionalPresence( + prefix + "abilitySchemaDigest", participant.abilitySchemaDigestPresent())); + fields.add( + optionalValue( + prefix + "abilitySchemaDigest", + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())); + } + fields.add(field("manifestHash", evidence.manifestHash())); + fields.add(field("manifestSchemaVersion", Integer.toString(evidence.manifestSchemaVersion()))); + fields.add( + field( + "requiredManifestAssetKeys.size", + Integer.toString(evidence.requiredManifestAssetKeys().size()))); + for (int index = 0; index < evidence.requiredManifestAssetKeys().size(); index++) { + fields.add( + field( + "requiredManifestAssetKeys[" + index + "]", + evidence.requiredManifestAssetKeys().get(index))); + } + fields.add(field("artifactDigests.size", Integer.toString(evidence.artifactDigests().size()))); + for (int index = 0; index < evidence.artifactDigests().size(); index++) { + Artifact artifact = evidence.artifactDigests().get(index); + String prefix = "artifactDigests[" + index + "]."; + fields.add(field(prefix + "usageKey", artifact.usageKey())); + fields.add(field(prefix + "artifactKind", artifact.artifactKind())); + fields.add(field(prefix + "immutableObjectKey", artifact.immutableObjectKey())); + fields.add(field(prefix + "contentDigest", artifact.contentDigest())); + fields.add(field(prefix + "contentType", artifact.contentType())); + fields.add( + field( + prefix + "artifactSchemaVersion", + Integer.toString(artifact.artifactSchemaVersion()))); + } + fields.add( + field("commandDefinitions.size", Integer.toString(evidence.commandDefinitions().size()))); + for (int index = 0; index < evidence.commandDefinitions().size(); index++) { + fields.add( + field("commandDefinitions[" + index + "]", evidence.commandDefinitions().get(index))); + } + fields.add(field("generationConfigRevision", evidence.generationConfigRevision())); + if (evidence.schemaVersion() == SELECTOR_SCHEMA_VERSION) { + fields.add( + field( + "worldStartLocationEvidence.canonicalBytesBase64", + Base64.getEncoder() + .encodeToString(evidence.worldStartLocationEvidence().canonicalBytes()))); + } + return preimage( + evidence.schemaVersion() == SCHEMA_VERSION ? EVIDENCE_DOMAIN : SELECTOR_EVIDENCE_DOMAIN, + fields.toArray(Field[]::new)); + } + + private static void validateParticipants(List participants, String commitId) { + if (participants.size() != PARTICIPANT_ORDER.size()) { + throw new IllegalArgumentException( + "A complete attestation requires exactly five participants"); + } + for (int index = 0; index < PARTICIPANT_ORDER.size(); index++) { + Participant participant = + Objects.requireNonNull(participants.get(index), "participantDigest"); + String expectedKey = PARTICIPANT_ORDER.get(index); + if (!expectedKey.equals(participant.participantKey())) { + throw new IllegalArgumentException("Participant digests are not in canonical owner order"); + } + if (supportedParticipantDigestSchema(participant.participantKey()) + != participant.digestSchemaVersion()) { + throw new IllegalArgumentException( + "Participant digest schema is unsupported for its owner"); + } + if (participant.baseVersionIdPresent()) { + throw new IllegalArgumentException( + "Full-Version participants must not have a baseVersionId"); + } + if (participant.scopeValue() == null + || !CANONICAL_POSITIVE_DECIMAL.matcher(participant.scopeValue()).matches()) { + throw new IllegalArgumentException( + "Full-Version participant scope must be a positive decimal Version"); + } + try { + if (Long.parseLong(participant.scopeValue()) <= 0) { + throw new IllegalArgumentException("Participant scope must be positive"); + } + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Participant scope must fit a positive Version id", exception); + } + if (!commitId.equals(participant.appliedCommitId())) { + throw new IllegalArgumentException("Every participant must report the attested commitId"); + } + boolean requiresAbilityDigest = "GAME_LOGIC".equals(participant.participantKey()); + if (participant.abilitySchemaDigestPresent() != requiresAbilityDigest) { + throw new IllegalArgumentException( + "Only GAME_LOGIC may supply the dedicated ability-schema digest"); + } + } + } + + private static void validateOrderedUniqueStrings(List values, String name) { + String previous = null; + for (String value : values) { + Objects.requireNonNull(value, name + " entry"); + requireText(value, name + " entry"); + if (previous != null && UNSIGNED_UTF8_ORDER.compare(previous, value) >= 0) { + throw new IllegalArgumentException(name + " must be unique and unsigned-UTF-8 ordered"); + } + previous = value; + } + } + + private static void validateArtifacts(List artifacts, List requiredKeys) { + String previous = null; + Map byUsageKey = new java.util.HashMap<>(); + for (Artifact artifact : artifacts) { + Objects.requireNonNull(artifact, "artifactDigest"); + if (previous != null && UNSIGNED_UTF8_ORDER.compare(previous, artifact.usageKey()) >= 0) { + throw new IllegalArgumentException( + "artifactDigests must be unique and unsigned-UTF-8 ordered"); + } + previous = artifact.usageKey(); + byUsageKey.put(artifact.usageKey(), artifact); + } + for (String requiredKey : requiredKeys) { + if (!byUsageKey.containsKey(requiredKey)) { + throw new IllegalArgumentException("Every required manifest key must select an artifact"); + } + } + } + + private static Field optionalPresence(String name, boolean present) { + return field(name + ".present", Boolean.toString(present)); + } + + private static Field optionalValue(String name, boolean present, String value) { + return field(name + ".value", present ? Objects.requireNonNull(value, name) : ""); + } + + private static Field field(String name, String value) { + return new Field(name, value); + } + + private static byte[] preimage(String domain, Field... fields) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + writeSegment(bytes, domain); + for (Field field : fields) { + writeSegment(bytes, field.name()); + writeSegment(bytes, field.value()); + } + return bytes.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] result = new byte[encoded.remaining()]; + encoded.get(result); + return result; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must contain valid Unicode", exception); + } + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static int compareUnsignedUtf8(String left, String right) { + byte[] leftBytes = strictUtf8(left); + byte[] rightBytes = strictUtf8(right); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int difference = Byte.toUnsignedInt(leftBytes[index]) - Byte.toUnsignedInt(rightBytes[index]); + if (difference != 0) { + return difference; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + private static void requirePositive(Long value, String name) { + if (value == null || value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireSupportedSchema(int value, String name) { + if (value != SCHEMA_VERSION) { + throw new IllegalArgumentException(name + " is unsupported"); + } + } + + private static void requirePositiveSchema(int value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + strictUtf8(value); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireParticipantContentDigest(String value) { + Objects.requireNonNull(value, "contentDigest"); + if (!PARTICIPANT_CONTENT_DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException( + "Participant contentDigest must be 64 lowercase hexadecimal characters"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java new file mode 100644 index 0000000000..dbeb0b0b1f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClient.java @@ -0,0 +1,157 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; + +/** Explicit mTLS client for exact source-qualified current Game Design version-state reads. */ +public final class AuthoredWorldVersionStateClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignServiceGrpc.GameDesignServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AuthoredWorldVersionStateClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AuthoredWorldVersionStateClient.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 version-state client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Authored-world version-state client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Reads current state for the exact already-intaken source and source-owned version. */ + public AuthoredWorldVersionStateEvidence read(AuthoredWorldVersionStateEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getAuthoredWorldVersionState(AuthoredWorldVersionStateGrpcCodec.toRequest(request)); + try { + return AuthoredWorldVersionStateGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid authored-world version-state evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub(ManagedChannel channel) { + String expectedGameDesignPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignServiceGrpc.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 GameDesignServiceGrpc.GameDesignServiceBlockingStub requireStub() { + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Authored-world version-state client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Version-state 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("Version-state 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( + "Version-state reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Version-state reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Version-state " + label + " must be a readable file-backed path", exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Version-state " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidence.java new file mode 100644 index 0000000000..ec95c8bd6a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateEvidence.java @@ -0,0 +1,218 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; + +/** Closed, source-qualified current Game Design version-state evidence for World Management. */ +public record AuthoredWorldVersionStateEvidence( + Request request, + AuthoredWorldSourceEvidence sourceEvidence, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch, + String evidenceDigest) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final String EVIDENCE_DOMAIN = "game-design-authored-world-version-state/v1"; + + /** The exact selector and caller-owned read identity for one current version-state read. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest, + long versionId) { + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world version-state schema"); + } + Objects.requireNonNull(readRequestId, "readRequestId"); + Objects.requireNonNull(sourceOperationId, "sourceOperationId"); + if (NIL_UUID.equals(readRequestId) || NIL_UUID.equals(sourceOperationId)) { + throw new IllegalArgumentException("Read and source operation IDs must be non-nil UUIDs"); + } + if (readRequestId.equals(sourceOperationId)) { + throw new IllegalArgumentException("readRequestId must be separate from sourceOperationId"); + } + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + if (expectedSourceEvidenceDigest == null + || !SHA256.matcher(expectedSourceEvidenceDigest).matches()) { + throw new IllegalArgumentException( + "Expected source evidence digest must be canonical SHA-256 text"); + } + if (versionId <= 0) { + throw new IllegalArgumentException("versionId must be positive"); + } + } + } + + public AuthoredWorldVersionStateEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + requireCanonicalVersionId(canonicalVersionId); + requireLifecycleState(versionState); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + if (!request.targetNamespace().equals(sourceEvidence.targetNamespace()) + || !request.canonicalTenantId().equals(sourceEvidence.canonicalTenantId()) + || !request.worldSlug().equals(sourceEvidence.worldSlug()) + || !request.sourceOperationId().equals(sourceEvidence.operationId()) + || !request.expectedSourceEvidenceDigest().equals(sourceEvidence.evidenceDigest())) { + throw new IllegalArgumentException( + "Complete authored-world source receipt does not match the exact version-state request"); + } + if (request.readRequestId().equals(sourceEvidence.registrationRequestId())) { + throw new IllegalArgumentException( + "readRequestId must be separate from the original source registration request"); + } + if (evidenceDigest == null || !SHA256.matcher(evidenceDigest).matches()) { + throw new IllegalArgumentException("evidenceDigest must be canonical SHA-256 text"); + } + if (!evidenceDigest.equals( + evidenceDigest(request, canonicalVersionId, versionState, versionStateEpoch))) { + throw new IllegalArgumentException( + "Version-state evidence digest does not match the exact current-state tuple"); + } + } + + public static AuthoredWorldVersionStateEvidence create( + Request request, + AuthoredWorldSourceEvidence sourceEvidence, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + Objects.requireNonNull(request, "request"); + requireCanonicalVersionId(canonicalVersionId); + requireLifecycleState(versionState); + return new AuthoredWorldVersionStateEvidence( + request, + sourceEvidence, + canonicalVersionId, + versionState, + versionStateEpoch, + evidenceDigest(request, canonicalVersionId, versionState, versionStateEpoch)); + } + + /** Recomputes the complete outer binding after construction or wire decoding. */ + public void requireValid() { + if (!evidenceDigest.equals( + evidenceDigest(request, canonicalVersionId, versionState, versionStateEpoch))) { + throw new IllegalArgumentException("Version-state evidence digest is invalid"); + } + } + + public static String evidenceDigest( + Request request, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + Objects.requireNonNull(request, "request"); + requireCanonicalVersionId(canonicalVersionId); + requireLifecycleState(versionState); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + return sha256(evidencePreimage(request, canonicalVersionId, versionState, versionStateEpoch)); + } + + /** Fixed-order UTF-8 length-framed preimage owned by the Game Design API contract. */ + public static byte[] evidencePreimage( + Request request, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + Objects.requireNonNull(request, "request"); + requireCanonicalVersionId(canonicalVersionId); + requireLifecycleState(versionState); + if (versionStateEpoch <= 0) { + throw new IllegalArgumentException("versionStateEpoch must be positive"); + } + return frame( + EVIDENCE_DOMAIN, + Integer.toString(request.schemaVersion()), + request.targetNamespace(), + request.readRequestId().toString(), + request.canonicalTenantId().toString(), + request.worldSlug(), + request.sourceOperationId().toString(), + request.expectedSourceEvidenceDigest(), + Long.toString(request.versionId()), + canonicalVersionId.toString(), + lifecycleStateName(versionState), + Long.toString(versionStateEpoch)); + } + + private static String lifecycleStateName(VersionLifecycleState value) { + return value.name().substring("VERSION_LIFECYCLE_STATE_".length()); + } + + private static byte[] frame(String... segments) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + for (String segment : segments) { + byte[] bytes = strictUtf8(segment); + preimage.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8)); + preimage.write(':'); + preimage.writeBytes(bytes); + } + return preimage.toByteArray(); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest segment"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest segments must contain valid Unicode", exception); + } + } + + private static String sha256(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void requireLifecycleState(VersionLifecycleState value) { + if (value == null + || value == VersionLifecycleState.VERSION_LIFECYCLE_STATE_UNSPECIFIED + || value == VersionLifecycleState.UNRECOGNIZED) { + throw new IllegalArgumentException("A recognized version lifecycle state is required"); + } + } + + private static void requireCanonicalVersionId(UUID value) { + Objects.requireNonNull(value, "canonicalVersionId"); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException("canonicalVersionId must be a non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodec.java new file mode 100644 index 0000000000..21ca27f45e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateGrpcCodec.java @@ -0,0 +1,191 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.AuthoredWorldSourceReceipt; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; + +/** Closed request mapping and exact response validation for authored-world version-state reads. */ +public final class AuthoredWorldVersionStateGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AuthoredWorldVersionStateGrpcCodec() {} + + /** Encodes exactly the schema-v1 source-qualified read tuple. */ + public static GetAuthoredWorldVersionStateRequest toRequest( + AuthoredWorldVersionStateEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .setVersionId(request.versionId()) + .build(); + } + + /** Decodes a strict request after the authenticated handler has checked its peer. */ + public static AuthoredWorldVersionStateEvidence.Request fromRequest( + GetAuthoredWorldVersionStateRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "GetAuthoredWorldVersionStateRequest"); + try { + return new AuthoredWorldVersionStateEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getSourceOperationId(), "sourceOperationId"), + request.getExpectedSourceEvidenceDigest(), + request.getVersionId()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Authored-world version-state request is invalid", exception); + } + } + + /** Encodes the complete validated source receipt and exact current-state evidence. */ + public static GetAuthoredWorldVersionStateResponse toResponse( + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + evidence.requireValid(); + AuthoredWorldSourceEvidence source = evidence.sourceEvidence(); + var request = evidence.request(); + AuthoredWorldSourceReceipt sourceReceipt = + AuthoredWorldSourceReceipt.newBuilder() + .setSchemaVersion(source.schemaVersion()) + .setTargetNamespace(source.targetNamespace()) + .setRegistrationRequestId(source.registrationRequestId().toString()) + .setOperationId(source.operationId().toString()) + .setRequestDigest(source.requestDigest()) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setTenantSlug(source.tenantSlug()) + .setWorldSlug(source.worldSlug()) + .setWorldDisplayName(source.worldDisplayName()) + .setSourceGameRowId(source.sourceGameRowId()) + .setSourceGameTenantKey(source.sourceGameTenantKey()) + .setProvenanceKind(source.provenanceKind()) + .setEvidenceDigest(source.evidenceDigest()) + .build(); + return GetAuthoredWorldVersionStateResponse.newBuilder() + .setEvidence( + net.firedevops.firemud.gamedesign.v1.AuthoredWorldVersionStateEvidence.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setExpectedSourceEvidenceDigest(request.expectedSourceEvidenceDigest()) + .setVersionId(request.versionId()) + .setCanonicalVersionId(evidence.canonicalVersionId().toString()) + .setSourceEvidence(sourceReceipt) + .setVersionState(evidence.versionState()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setEvidenceDigest(evidence.evidenceDigest())) + .build(); + } + + /** Validates every response carrier and binds every echo to the exact read request. */ + public static net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence + fromResponse( + AuthoredWorldVersionStateEvidence.Request request, + GetAuthoredWorldVersionStateResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "GetAuthoredWorldVersionStateResponse"); + if (!response.hasEvidence()) { + throw new IllegalArgumentException("Version-state response has no evidence"); + } + var wireEvidence = response.getEvidence(); + requireNoUnknownFields(wireEvidence, "AuthoredWorldVersionStateEvidence"); + if (!wireEvidence.hasSourceEvidence()) { + throw new IllegalArgumentException("Version-state evidence has no complete source receipt"); + } + AuthoredWorldSourceReceipt wireSource = wireEvidence.getSourceEvidence(); + requireNoUnknownFields(wireSource, "AuthoredWorldSourceReceipt"); + + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence evidence; + try { + var echoedRequest = + new AuthoredWorldVersionStateEvidence.Request( + wireEvidence.getSchemaVersion(), + wireEvidence.getTargetNamespace(), + parseCanonicalNonNilUuid(wireEvidence.getReadRequestId(), "readRequestId"), + parseCanonicalNonNilUuid(wireEvidence.getCanonicalTenantId(), "canonicalTenantId"), + wireEvidence.getWorldSlug(), + parseCanonicalNonNilUuid(wireEvidence.getSourceOperationId(), "sourceOperationId"), + wireEvidence.getExpectedSourceEvidenceDigest(), + wireEvidence.getVersionId()); + if (!request.equals(echoedRequest)) { + throw new IllegalArgumentException( + "Version-state response does not echo the exact read request"); + } + AuthoredWorldSourceEvidence sourceEvidence = + new AuthoredWorldSourceEvidence( + wireSource.getSchemaVersion(), + wireSource.getTargetNamespace(), + parseCanonicalNonNilUuid( + wireSource.getRegistrationRequestId(), "registrationRequestId"), + parseCanonicalNonNilUuid(wireSource.getOperationId(), "source operationId"), + wireSource.getRequestDigest(), + parseCanonicalNonNilUuid( + wireSource.getCanonicalTenantId(), "source canonicalTenantId"), + wireSource.getTenantSlug(), + wireSource.getWorldSlug(), + wireSource.getWorldDisplayName(), + wireSource.getSourceGameRowId(), + wireSource.getSourceGameTenantKey(), + wireSource.getProvenanceKind(), + wireSource.getEvidenceDigest()); + VersionLifecycleState versionState = + VersionLifecycleState.forNumber(wireEvidence.getVersionStateValue()); + if (versionState == null) { + throw new IllegalArgumentException("Version-state enum value is unsupported"); + } + evidence = + new net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence( + echoedRequest, + sourceEvidence, + parseCanonicalNonNilUuid(wireEvidence.getCanonicalVersionId(), "canonicalVersionId"), + versionState, + wireEvidence.getVersionStateEpoch(), + wireEvidence.getEvidenceDigest()); + evidence.requireValid(); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Game Design authored-world version-state response is invalid", exception); + } + return evidence; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java new file mode 100644 index 0000000000..8b6089e638 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CompleteLaunchBindingEvidence.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.util.Objects; + +/** The exact independently validated descriptor and release-attestation pair for a launch. */ +public record CompleteLaunchBindingEvidence( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation) { + public CompleteLaunchBindingEvidence { + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(releaseAttestation, "releaseAttestation"); + releaseAttestation.requireValid(descriptor); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityClient.java new file mode 100644 index 0000000000..4460e9a9b2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityClient.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.DraftSynchronizedVisibilityServiceGrpc; + +/** Explicit mTLS client for exact same-namespace durable synchronized Draft reads. */ +public final class DraftSynchronizedVisibilityClient + extends AbstractReloadingBlockingGrpcClient< + DraftSynchronizedVisibilityServiceGrpc.DraftSynchronizedVisibilityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public DraftSynchronizedVisibilityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + DraftSynchronizedVisibilityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning service explicitly starts this opt-in client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Synchronized visibility client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Synchronized visibility client has no gRPC stub"); + } + initialized = true; + } + + public DraftSynchronizedVisibilityEvidence read( + DraftSynchronizedVisibilityEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Synchronized visibility request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readDraftSynchronizedVisibility( + DraftSynchronizedVisibilityGrpcCodec.toRequest(request)); + try { + return DraftSynchronizedVisibilityGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid synchronized Draft visibility evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected DraftSynchronizedVisibilityServiceGrpc.DraftSynchronizedVisibilityServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return DraftSynchronizedVisibilityServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private DraftSynchronizedVisibilityServiceGrpc.DraftSynchronizedVisibilityServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Synchronized visibility client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Synchronized visibility 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( + "Synchronized visibility reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Synchronized visibility reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Synchronized visibility " + label + " must be a readable file-backed path", exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Synchronized visibility " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java new file mode 100644 index 0000000000..cdf1d221e6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidence.java @@ -0,0 +1,359 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Closed read evidence for one exact durable synchronized Game Design Draft visibility fence. */ +public final class DraftSynchronizedVisibilityEvidence { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper JSON = new ObjectMapper(); + + /** Complete Game Design target selector, plus a distinct caller-owned read identity. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + DraftCommitBinding.TargetProof target) { + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported synchronized visibility schema"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("A canonical target namespace is required"); + } + requireNonNil(readRequestId, "readRequestId"); + Objects.requireNonNull(target, "target"); + } + } + + /** Exact immutable fence tuple as retained by the Game Design coordinator. */ + public record Fence( + UUID requestId, + UUID commitId, + String inputDigest, + String resultVectorJson, + OffsetDateTime createdAt) { + public Fence { + requireNonNil(requestId, "fence requestId"); + requireNonNil(commitId, "fence commitId"); + requireDigest(inputDigest, "fence inputDigest"); + Objects.requireNonNull(resultVectorJson, "resultVectorJson"); + Objects.requireNonNull(createdAt, "createdAt"); + } + } + + /** One exact APPLIED owner result decoded from the coordinator's immutable result vector. */ + public static final class AppliedOwnerResult { + private final Owner owner; + private final UUID commitId; + private final String bindingDigest; + private final String resultIdentity; + private final byte[] resultBytes; + private final List appliedEpochs; + + private AppliedOwnerResult( + Owner owner, + UUID commitId, + String bindingDigest, + String resultIdentity, + byte[] resultBytes, + List appliedEpochs) { + this.owner = Objects.requireNonNull(owner, "owner"); + this.commitId = Objects.requireNonNull(commitId, "commitId"); + this.bindingDigest = Objects.requireNonNull(bindingDigest, "bindingDigest"); + this.resultIdentity = Objects.requireNonNull(resultIdentity, "resultIdentity"); + this.resultBytes = Objects.requireNonNull(resultBytes, "resultBytes").clone(); + this.appliedEpochs = List.copyOf(appliedEpochs); + } + + public Owner owner() { + return owner; + } + + public UUID commitId() { + return commitId; + } + + public String bindingDigest() { + return bindingDigest; + } + + public String resultIdentity() { + return resultIdentity; + } + + public byte[] resultBytes() { + return resultBytes.clone(); + } + + public List appliedEpochs() { + return appliedEpochs; + } + } + + public record AppliedEpoch( + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch, + String resultingEpoch) { + public AppliedEpoch { + Objects.requireNonNull(aggregateType, "aggregateType"); + Objects.requireNonNull(aggregateId, "aggregateId"); + Objects.requireNonNull(scopeType, "scopeType"); + Objects.requireNonNull(scopeId, "scopeId"); + requireCounter(expectedEpoch, "expectedEpoch"); + requireCounter(resultingEpoch, "resultingEpoch"); + } + } + + private final Request request; + private final DraftCommitBinding binding; + private final String workflowState; + private final Fence fence; + private final List appliedOwnerResults; + + public DraftSynchronizedVisibilityEvidence( + Request request, DraftCommitBinding binding, String workflowState, Fence fence) { + this.request = Objects.requireNonNull(request, "request"); + this.binding = Objects.requireNonNull(binding, "binding"); + this.workflowState = Objects.requireNonNull(workflowState, "workflowState"); + this.fence = Objects.requireNonNull(fence, "fence"); + this.appliedOwnerResults = validateAndReadOwnerResults(); + } + + public Request request() { + return request; + } + + public DraftCommitBinding binding() { + return binding; + } + + public String workflowState() { + return workflowState; + } + + public Fence fence() { + return fence; + } + + public List appliedOwnerResults() { + return List.copyOf(appliedOwnerResults); + } + + public AppliedOwnerResult appliedOwnerResult(Owner owner) { + Objects.requireNonNull(owner, "owner"); + return appliedOwnerResults.stream() + .filter(result -> result.owner() == owner) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Owner is not in the applied fence")); + } + + /** Revalidates every redundant carrier before this evidence is used as a selector. */ + public void requireValid() { + validateAndReadOwnerResults(); + } + + private List validateAndReadOwnerResults() { + if (!binding.target().equals(request.target()) + || !binding.requiredOwners().contains(Owner.WORLD_MANAGEMENT) + || request.readRequestId().equals(binding.requestId()) + || request.readRequestId().equals(binding.commitId())) { + throw new IllegalArgumentException( + "Synchronized visibility request and complete Draft target differ"); + } + if (!"SYNCHRONIZED".equals(workflowState) + || !fence.requestId().equals(binding.requestId()) + || !fence.commitId().equals(binding.commitId()) + || !fence.inputDigest().equals(binding.digest())) { + throw new IllegalArgumentException( + "Draft visibility fence is not bound to this synchronized full input"); + } + + byte[] supplied = fence.resultVectorJson().getBytes(StandardCharsets.UTF_8); + byte[] canonical; + JsonNode vector; + try { + canonical = Rfc8785CanonicalJson.canonicalizeUtf8(fence.resultVectorJson()); + vector = JSON.readTree(fence.resultVectorJson()); + } catch (IOException | RuntimeException exception) { + throw new IllegalArgumentException( + "Draft result vector is not valid canonical JSON", exception); + } + if (!java.util.Arrays.equals(supplied, canonical)) { + throw new IllegalArgumentException("Draft result vector is not exact canonical JSON"); + } + if (vector == null || !vector.isArray() || vector.size() != binding.requiredOwners().size()) { + throw new IllegalArgumentException("Draft result vector is incomplete"); + } + + List results = new ArrayList<>(); + Set seen = new HashSet<>(); + for (int index = 0; index < vector.size(); index++) { + JsonNode item = vector.get(index); + requireFields( + item, + Set.of( + "owner", + "status", + "commitId", + "bindingDigest", + "resultIdentity", + "resultBytesBase64", + "appliedEpochs")); + Owner owner = enumText(item, "owner", Owner.class); + if (owner != binding.requiredOwners().get(index) || !seen.add(owner)) { + throw new IllegalArgumentException("Draft owner result order/set differs from binding"); + } + if (!"APPLIED".equals(text(item, "status"))) { + throw new IllegalArgumentException("Only terminal APPLIED owner results are visible"); + } + UUID commitId = parseCanonicalUuid(text(item, "commitId"), "commitId"); + String bindingDigest = text(item, "bindingDigest"); + requireDigest(bindingDigest, "owner bindingDigest"); + String resultIdentity = text(item, "resultIdentity"); + if (resultIdentity.isBlank() || !resultIdentity.equals(resultIdentity.trim())) { + throw new IllegalArgumentException("Owner result identity must be exact nonblank text"); + } + String bytesBase64 = text(item, "resultBytesBase64"); + byte[] resultBytes; + try { + resultBytes = Base64.getDecoder().decode(bytesBase64); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Owner result bytes must be canonical Base64", exception); + } + if (!Base64.getEncoder().encodeToString(resultBytes).equals(bytesBase64)) { + throw new IllegalArgumentException("Owner result bytes must be canonical Base64"); + } + if (!binding.commitId().equals(commitId) || !binding.digest().equals(bindingDigest)) { + throw new IllegalArgumentException("Owner result is bound to different Draft input"); + } + List epochs = parseEpochs(item.get("appliedEpochs"), binding, owner); + results.add( + new AppliedOwnerResult( + owner, commitId, bindingDigest, resultIdentity, resultBytes, epochs)); + } + return List.copyOf(results); + } + + private static List parseEpochs( + JsonNode vector, DraftCommitBinding binding, Owner owner) { + List expected = binding.affectedUnits(owner); + if (vector == null || !vector.isArray() || vector.size() != expected.size()) { + throw new IllegalArgumentException("Applied owner epoch vector is incomplete"); + } + List epochs = new ArrayList<>(); + for (int index = 0; index < vector.size(); index++) { + JsonNode item = vector.get(index); + requireFields( + item, + Set.of( + "aggregateType", + "aggregateId", + "scopeType", + "scopeId", + "expectedEpoch", + "resultingEpoch")); + AppliedEpoch epoch = + new AppliedEpoch( + text(item, "aggregateType"), + text(item, "aggregateId"), + text(item, "scopeType"), + text(item, "scopeId"), + text(item, "expectedEpoch"), + text(item, "resultingEpoch")); + AffectedUnit unit = expected.get(index); + if (!unit.aggregateType().equals(epoch.aggregateType()) + || !unit.aggregateId().equals(epoch.aggregateId()) + || !unit.scopeType().equals(epoch.scopeType()) + || !unit.scopeId().equals(epoch.scopeId()) + || !unit.expectedEpoch().equals(epoch.expectedEpoch()) + || new BigInteger(epoch.resultingEpoch()).compareTo(new BigInteger(epoch.expectedEpoch())) + <= 0) { + throw new IllegalArgumentException( + "Applied owner tuple differs from the complete bound epoch declaration"); + } + epochs.add(epoch); + } + return List.copyOf(epochs); + } + + private static void requireFields(JsonNode node, Set fields) { + if (node == null + || !node.isObject() + || node.size() != fields.size() + || node.properties().stream().anyMatch(entry -> !fields.contains(entry.getKey()))) { + throw new IllegalArgumentException("Draft owner result contains missing or unknown fields"); + } + } + + private static String text(JsonNode node, String field) { + JsonNode value = node == null ? null : node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Draft owner result text field is missing: " + field); + } + return value.textValue(); + } + + private static > T enumText(JsonNode node, String field, Class type) { + try { + return Enum.valueOf(type, text(node, field)); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Draft owner result enum is unsupported: " + field, exception); + } + } + + private static UUID parseCanonicalUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (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 canonical SHA-256 text"); + } + } + + private static void requireCounter(String value, String label) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityGrpcCodec.java new file mode 100644 index 0000000000..374dfa7e1b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityGrpcCodec.java @@ -0,0 +1,182 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Message; +import com.google.protobuf.Timestamp; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.v1.DraftSynchronizedVisibilityFence; +import net.firedevops.firemud.gamedesign.v1.DraftVisibilityTarget; +import net.firedevops.firemud.gamedesign.v1.ReadDraftSynchronizedVisibilityRequest; +import net.firedevops.firemud.gamedesign.v1.ReadDraftSynchronizedVisibilityResponse; + +/** Closed wire mapping and exact echo validation for synchronized Draft visibility reads. */ +public final class DraftSynchronizedVisibilityGrpcCodec { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private DraftSynchronizedVisibilityGrpcCodec() {} + + public static ReadDraftSynchronizedVisibilityRequest toRequest( + DraftSynchronizedVisibilityEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadDraftSynchronizedVisibilityRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setTarget(toTarget(request.target())) + .build(); + } + + /** Decodes only after the receiver has authenticated its exact same-namespace peer. */ + public static DraftSynchronizedVisibilityEvidence.Request fromRequest( + ReadDraftSynchronizedVisibilityRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadDraftSynchronizedVisibilityRequest"); + if (!request.hasTarget()) { + throw new IllegalArgumentException("Complete synchronized visibility target is required"); + } + try { + return new DraftSynchronizedVisibilityEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + fromTarget(request.getTarget())); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Synchronized visibility request is invalid", exception); + } + } + + public static ReadDraftSynchronizedVisibilityResponse toResponse( + DraftSynchronizedVisibilityEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + evidence.requireValid(); + var fence = evidence.fence(); + Timestamp timestamp = + Timestamp.newBuilder() + .setSeconds(fence.createdAt().toEpochSecond()) + .setNanos(fence.createdAt().getNano()) + .build(); + return ReadDraftSynchronizedVisibilityResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setTargetNamespace(evidence.request().targetNamespace()) + .setReadRequestId(evidence.request().readRequestId().toString()) + .setTarget(toTarget(evidence.binding().target())) + .setBindingJson(evidence.binding().canonicalJson()) + .setBindingDigest(evidence.binding().digest()) + .setWorkflowState(evidence.workflowState()) + .setFence( + DraftSynchronizedVisibilityFence.newBuilder() + .setRequestId(fence.requestId().toString()) + .setCommitId(fence.commitId().toString()) + .setInputDigest(fence.inputDigest()) + .setResultVectorJson(fence.resultVectorJson()) + .setCreatedAt(timestamp)) + .build(); + } + + /** Decodes the full binding and rejects every changed or missing request/fence carrier. */ + public static DraftSynchronizedVisibilityEvidence fromResponse( + DraftSynchronizedVisibilityEvidence.Request request, + ReadDraftSynchronizedVisibilityResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadDraftSynchronizedVisibilityResponse"); + if (!response.hasTarget() || !response.hasFence()) { + throw new IllegalArgumentException("Synchronized visibility response is incomplete"); + } + requireNoUnknownFields(response.getTarget(), "DraftVisibilityTarget"); + requireNoUnknownFields(response.getFence(), "DraftSynchronizedVisibilityFence"); + + try { + DraftSynchronizedVisibilityEvidence.Request echoed = + new DraftSynchronizedVisibilityEvidence.Request( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getReadRequestId(), "readRequestId"), + fromTarget(response.getTarget())); + if (!request.equals(echoed)) { + throw new IllegalArgumentException( + "Game Design response does not echo the exact read ID and complete target"); + } + DraftCommitBinding binding = + DraftCommitBinding.fromStored(response.getBindingJson(), response.getBindingDigest()); + Timestamp timestamp = response.getFence().getCreatedAt(); + if (!response.getFence().hasCreatedAt()) { + throw new IllegalArgumentException("Synchronized fence timestamp is required"); + } + requireNoUnknownFields(timestamp, "Timestamp"); + if (timestamp.getSeconds() < -62135596800L + || timestamp.getSeconds() > 253402300799L + || timestamp.getNanos() < 0 + || timestamp.getNanos() > 999999999) { + throw new IllegalArgumentException( + "Synchronized fence timestamp must be valid protobuf time"); + } + return new DraftSynchronizedVisibilityEvidence( + request, + binding, + response.getWorkflowState(), + new DraftSynchronizedVisibilityEvidence.Fence( + parseCanonicalNonNilUuid(response.getFence().getRequestId(), "fence requestId"), + parseCanonicalNonNilUuid(response.getFence().getCommitId(), "fence commitId"), + response.getFence().getInputDigest(), + response.getFence().getResultVectorJson(), + OffsetDateTime.ofInstant( + Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()), + ZoneOffset.UTC))); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Game Design synchronized visibility response is invalid", exception); + } + } + + private static DraftVisibilityTarget toTarget(DraftCommitBinding.TargetProof target) { + return DraftVisibilityTarget.newBuilder() + .setCanonicalTenantId(target.canonicalTenantId().toString()) + .setCanonicalVersionId(target.canonicalVersionId().toString()) + .setGameDesignVersionRowId(target.gameDesignVersionRowId()) + .setGameDesignVersionTenantKey(target.gameDesignVersionTenantKey()) + .setSourceGameRowId(target.sourceGameRowId()) + .setSourceGameTenantKey(target.sourceGameTenantKey()) + .setSourceProvenanceKind(target.sourceProvenanceKind()) + .build(); + } + + private static DraftCommitBinding.TargetProof fromTarget(DraftVisibilityTarget target) { + Objects.requireNonNull(target, "target"); + requireNoUnknownFields(target, "DraftVisibilityTarget"); + return new DraftCommitBinding.TargetProof( + parseCanonicalNonNilUuid(target.getCanonicalTenantId(), "canonicalTenantId"), + parseCanonicalNonNilUuid(target.getCanonicalVersionId(), "canonicalVersionId"), + target.getGameDesignVersionRowId(), + target.getGameDesignVersionTenantKey(), + target.getSourceGameRowId(), + target.getSourceGameTenantKey(), + target.getSourceProvenanceKind()); + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + return parsed; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required", exception); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java new file mode 100644 index 0000000000..f83405fcb5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -0,0 +1,517 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Immutable original owner result. Decoding establishes integrity, never transport authority. */ +public final class GameDesignPublicationTerminalEvidence { + public static final String SCHEMA = "game-design-publication-terminal/v1"; + public static final String RELEASE_SCHEMA = "game-design-published-release-bundle/v1"; + + public enum Outcome { + PUBLISHED, + NO_PUBLICATION + } + + /** Lossless participant content, including the presence of nullable publication result fields. */ + public record Participant( + String participantKey, + String scopeValue, + Long baseVersionId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + String abilitySchemaDigest, + String errorCode, + String errorMessage) { + public Participant { + new AuthoredWorldReleaseAttestationEvidence.Participant( + participantKey, + scopeValue, + baseVersionId != null, + baseVersionId, + appliedCommitId, + contentDigest, + digestSchemaVersion, + abilitySchemaDigest != null, + abilitySchemaDigest); + if (errorCode != null && !errorCode.isEmpty()) { + throw new IllegalArgumentException("Published participant cannot carry an error"); + } + if (errorMessage != null) utf8(errorMessage); + } + } + + /** Complete full-Version content; private SQL aliases and publishedAt are excluded. */ + public record ReleaseContent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + int versionNumber, + String attestationSchemaVersion, + String publishWorkflowId, + String manifestHash, + int manifestSchemaVersion, + List artifactDigests, + List requiredManifestAssetKeys, + List participantDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + public ReleaseContent { + uuid(canonicalTenantId); + uuid(canonicalVersionId); + text(publishedReleaseBundleRef); + text(publishWorkflowId); + text(generationConfigRevision); + if (versionNumber <= 0 + || !"v2".equals(attestationSchemaVersion) + || manifestSchemaVersion != 1) { + throw new IllegalArgumentException("Complete full-Version bundle/v2 required"); + } + digest(manifestHash); + artifactDigests = List.copyOf(artifactDigests); + requiredManifestAssetKeys = List.copyOf(requiredManifestAssetKeys); + participantDigests = List.copyOf(participantDigests); + commandDefinitions = List.copyOf(commandDefinitions); + commandDefinitions.forEach(GameDesignPublicationTerminalEvidence::utf8); + worldStartLocationEvidence = + WorldPublishedStartLocationEvidence.fromStored( + Objects.requireNonNull(worldStartLocationEvidence).canonicalBytes()); + var selected = worldStartLocationEvidence.request(); + if (!canonicalTenantId.equals(selected.canonicalTenantId()) + || !canonicalVersionId.equals(selected.canonicalVersionId()) + || !publishWorkflowId.equals(selected.publishWorkflowId())) { + throw new IllegalArgumentException("Release identity differs from World checkpoint"); + } + var owners = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); + if (participantDigests.size() != owners.size()) { + throw new IllegalArgumentException("Exactly five participant owners required"); + } + for (int i = 0; i < owners.size(); i++) { + var p = participantDigests.get(i); + if (!owners.get(i).equals(p.participantKey()) + || p.digestSchemaVersion() + != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + p.participantKey()) + || p.baseVersionId() != null + || !selected.appliedCommitId().equals(p.appliedCommitId()) + || !p.scopeValue().matches("[1-9][0-9]*") + || new BigInteger(p.scopeValue()).compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0 + || ((p.abilitySchemaDigest() != null) != "GAME_LOGIC".equals(p.participantKey()))) { + throw new IllegalArgumentException("Incomplete or changed required participant proof"); + } + } + var world = participantDigests.getFirst(); + if (!world.contentDigest().equals(selected.contentDigest()) + || world.digestSchemaVersion() != selected.digestSchemaVersion()) { + throw new IllegalArgumentException("World participant differs from frozen checkpoint"); + } + ordered(requiredManifestAssetKeys); + ordered( + artifactDigests.stream() + .map(AuthoredWorldReleaseAttestationEvidence.Artifact::usageKey) + .toList()); + if (!artifactDigests.stream() + .map(AuthoredWorldReleaseAttestationEvidence.Artifact::usageKey) + .toList() + .containsAll(requiredManifestAssetKeys)) { + throw new IllegalArgumentException( + "Every required asset must have actual-byte artifact proof"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + segment(out, RELEASE_SCHEMA); + segment(out, canonicalTenantId.toString()); + segment(out, canonicalVersionId.toString()); + segment(out, publishedReleaseBundleRef); + segment(out, Integer.toString(versionNumber)); + segment(out, attestationSchemaVersion); + segment(out, publishWorkflowId); + segment(out, manifestHash); + segment(out, Integer.toString(manifestSchemaVersion)); + segment(out, Integer.toString(artifactDigests.size())); + for (var a : artifactDigests) { + var entry = new ByteArrayOutputStream(); + segment(entry, a.usageKey()); + segment(entry, a.artifactKind()); + segment(entry, a.immutableObjectKey()); + segment(entry, a.contentDigest()); + segment(entry, a.contentType()); + segment(entry, Integer.toString(a.artifactSchemaVersion())); + segment(out, entry.toByteArray()); + } + strings(out, requiredManifestAssetKeys); + segment(out, Integer.toString(participantDigests.size())); + for (var p : participantDigests) { + var entry = new ByteArrayOutputStream(); + segment(entry, p.participantKey()); + segment(entry, p.scopeValue()); + optional(entry, p.baseVersionId() == null ? null : p.baseVersionId().toString()); + segment(entry, p.appliedCommitId()); + segment(entry, p.contentDigest()); + segment(entry, Integer.toString(p.digestSchemaVersion())); + optional(entry, p.abilitySchemaDigest()); + optional(entry, p.errorCode()); + optional(entry, p.errorMessage()); + segment(out, entry.toByteArray()); + } + strings(out, commandDefinitions); + segment(out, generationConfigRevision); + segment(out, worldStartLocationEvidence.canonicalBytes()); + // Full versions cannot carry a script patch; explicit presence is still part of content. + segment(out, "false"); + optional(out, null); + return out.toByteArray(); + } + + public String contentDigest() { + return sha256(canonicalBytes()); + } + + public static ReleaseContent fromStored(byte[] bytes) { + var r = new Reader(bytes); + r.expect(RELEASE_SCHEMA); + UUID tenant = UUID.fromString(r.text()); + UUID version = UUID.fromString(r.text()); + String ref = r.text(); + int number = r.positiveInt(); + String schema = r.text(); + String workflow = r.text(); + String manifest = r.text(); + int manifestSchema = r.positiveInt(); + var artifacts = new ArrayList(); + for (int remaining = r.count(); remaining > 0; remaining--) { + var a = new Reader(r.bytes()); + artifacts.add( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + a.text(), a.text(), a.text(), a.text(), a.text(), a.positiveInt())); + a.end(); + } + List required = r.strings(); + var participants = new ArrayList(); + for (int remaining = r.count(); remaining > 0; remaining--) { + var p = new Reader(r.bytes()); + String owner = p.text(); + String scope = p.text(); + String base = p.optional(); + participants.add( + new Participant( + owner, + scope, + base == null ? null : positiveLong(base), + p.text(), + p.text(), + p.positiveInt(), + p.optional(), + p.optional(), + p.optional())); + p.end(); + } + List commands = r.strings(); + String generation = r.text(); + var world = WorldPublishedStartLocationEvidence.fromStored(r.bytes()); + r.expect("false"); + if (r.optional() != null) throw new IllegalArgumentException("Full version has script patch"); + r.end(); + var result = + new ReleaseContent( + tenant, + version, + ref, + number, + schema, + workflow, + manifest, + manifestSchema, + artifacts, + required, + participants, + commands, + generation, + world); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical release content"); + return result; + } + } + + private final GameDesignPublicationOperationBinding operation; + private final Outcome outcome; + private final ReleaseContent release; + private final Long epoch; + + public GameDesignPublicationTerminalEvidence( + byte[] operationBytes, + Outcome outcome, + ReleaseContent release, + Long publicationVersionStateEpoch) { + this.operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + this.outcome = Objects.requireNonNull(outcome); + if ((outcome == Outcome.PUBLISHED) != (release != null && publicationVersionStateEpoch != null) + || (outcome == Outcome.NO_PUBLICATION + && (release != null || publicationVersionStateEpoch != null))) { + throw new IllegalArgumentException("Outcome-inapplicable release or epoch"); + } + this.release = release == null ? null : ReleaseContent.fromStored(release.canonicalBytes()); + this.epoch = publicationVersionStateEpoch; + if (release != null) { + if (epoch <= 0 + || epoch != Math.addExact(operation.world().request().versionStateEpoch(), 1L) + || !Arrays.equals( + release.worldStartLocationEvidence().canonicalBytes(), + operation.world().canonicalBytes())) { + throw new IllegalArgumentException( + "Terminal release differs from original publication operation"); + } + String scope = + Long.toString(operation.account().input().selection().target().gameDesignVersionRowId()); + if (release.participantDigests().stream().anyMatch(p -> !scope.equals(p.scopeValue()))) { + throw new IllegalArgumentException("Participant scope differs from selected owner Version"); + } + } + } + + public Outcome outcome() { + return outcome; + } + + public byte[] operationBytes() { + return operation.canonicalBytes(); + } + + public WorldPublishedStartLocationEvidence worldEvidence() { + return operation.world(); + } + + public String publishedReleaseBundleRef() { + return requireRelease().publishedReleaseBundleRef(); + } + + public String publishedReleaseBundleDigest() { + return requireRelease().contentDigest(); + } + + public long publicationVersionStateEpoch() { + requireRelease(); + return epoch; + } + + public ReleaseContent releaseContent() { + return requireRelease(); + } + + private ReleaseContent requireRelease() { + if (release == null) + throw new IllegalStateException( + "NO_PUBLICATION has no release or committed publication epoch"); + return release; + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, operationBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome.name()); + if (release != null) { + DraftAuthorizationFenceBinding.frame(out, release.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, Long.toString(epoch)); + } + return out.toByteArray(); + } + + public static GameDesignPublicationTerminalEvidence fromStored(byte[] bytes) { + var r = new DraftAuthorizationFenceBinding.FrameReader(bytes); + r.expect(SCHEMA); + byte[] operation = r.bytes(); + Outcome outcome = Outcome.valueOf(r.text()); + ReleaseContent release = + outcome == Outcome.PUBLISHED ? ReleaseContent.fromStored(r.bytes()) : null; + Long epoch = outcome == Outcome.PUBLISHED ? positiveLong(r.text()) : null; + r.requireEnd(); + var result = new GameDesignPublicationTerminalEvidence(operation, outcome, release, epoch); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical terminal evidence"); + return result; + } + + private static void uuid(UUID id) { + if (id == null || id.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException("Non-nil UUID required"); + } + + private static void text(String s) { + if (s == null || s.isBlank() || s.codePoints().anyMatch(Character::isISOControl)) + throw new IllegalArgumentException("Canonical nonblank text required"); + utf8(s); + } + + private static void digest(String s) { + if (s == null || !s.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException("SHA256 digest required"); + } + + private static long positiveLong(String s) { + if (!s.matches("[1-9][0-9]*")) + throw new IllegalArgumentException("Canonical positive decimal required"); + try { + return Long.parseLong(s); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Counter exceeds owner range", e); + } + } + + private static byte[] utf8(String s) { + try { + var b = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .encode(java.nio.CharBuffer.wrap(Objects.requireNonNull(s))); + var bytes = new byte[b.remaining()]; + b.get(bytes); + return bytes; + } catch (CharacterCodingException e) { + throw new IllegalArgumentException("Invalid UTF-8", e); + } + } + + private static void ordered(List values) { + String prior = null; + for (String value : values) { + text(value); + if (prior != null && Arrays.compareUnsigned(utf8(prior), utf8(value)) >= 0) + throw new IllegalArgumentException("Array must be unique and unsigned UTF-8 ordered"); + prior = value; + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private static void segment(ByteArrayOutputStream out, String value) { + segment(out, utf8(value)); + } + + private static void segment(ByteArrayOutputStream out, byte[] bytes) { + out.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + out.write(':'); + out.writeBytes(bytes); + } + + private static void optional(ByteArrayOutputStream out, String value) { + segment(out, value == null ? "false" : "true"); + segment(out, value == null ? "" : value); + } + + private static void strings(ByteArrayOutputStream out, List values) { + segment(out, Integer.toString(values.size())); + values.forEach(v -> segment(out, v)); + } + + private static final class Reader { + private final byte[] bytes; + private int offset; + + Reader(byte[] bytes) { + this.bytes = Objects.requireNonNull(bytes).clone(); + } + + byte[] bytes() { + int start = offset; + while (offset < bytes.length && bytes[offset] >= '0' && bytes[offset] <= '9') offset++; + if (start == offset || offset == bytes.length || bytes[offset] != ':') + throw new IllegalArgumentException("Malformed byte-length frame"); + String decimal = new String(bytes, start, offset - start, StandardCharsets.US_ASCII); + if (!decimal.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Noncanonical frame length"); + int length; + try { + length = new BigInteger(decimal).intValueExact(); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("Frame too large", e); + } + offset++; + if (length > bytes.length - offset) throw new IllegalArgumentException("Truncated frame"); + byte[] value = Arrays.copyOfRange(bytes, offset, offset + length); + offset += length; + return value; + } + + String text() { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes())) + .toString(); + } catch (CharacterCodingException e) { + throw new IllegalArgumentException("Invalid UTF-8", e); + } + } + + void expect(String value) { + if (!value.equals(text())) throw new IllegalArgumentException("Unexpected canonical field"); + } + + int positiveInt() { + return Math.toIntExact(positiveLong(text())); + } + + int count() { + String s = text(); + if (!s.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Noncanonical array count"); + int n; + try { + n = new BigInteger(s).intValueExact(); + } catch (ArithmeticException e) { + throw new IllegalArgumentException("Array too large", e); + } + if (n > (bytes.length - offset) / 2) throw new IllegalArgumentException("Incomplete array"); + return n; + } + + String optional() { + String present = text(); + String value = text(); + if ("true".equals(present)) return value; + if (!"false".equals(present) || !value.isEmpty()) + throw new IllegalArgumentException("Malformed optional field"); + return null; + } + + List strings() { + var result = new ArrayList(); + for (int n = count(); n > 0; n--) result.add(text()); + return result; + } + + void end() { + if (offset != bytes.length) throw new IllegalArgumentException("Trailing fields"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClient.java new file mode 100644 index 0000000000..cc172b2528 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClient.java @@ -0,0 +1,155 @@ +package net.firedevops.firemud.common.gamesession; + +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.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Result; +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.gamesession.v1.GameSessionControlPlaneServiceGrpc; + +/** Explicit file-backed mTLS client for the exact Game Session launch-association owner read. */ +public final class CanonicalGameInstanceLaunchAssociationClient + extends AbstractReloadingBlockingGrpcClient< + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public CanonicalGameInstanceLaunchAssociationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + CanonicalGameInstanceLaunchAssociationClient.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("Canonical launch association client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Canonical launch association client has no gRPC stub"); + } + initialized = true; + } + + /** Reads a single exact owner association; the response is not World lifecycle evidence. */ + public Result read(Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Launch association request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCanonicalGameInstanceLaunchAssociation( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toRequest(request)); + try { + return CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Session returned invalid canonical launch association evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub buildStub( + ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + return GameSessionControlPlaneServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Canonical launch association client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Canonical launch association 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( + "Canonical launch association reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Canonical launch association reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Canonical launch association " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Canonical launch association " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java new file mode 100644 index 0000000000..a72c3401d3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.common.gamesession; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** + * Exact selector and readback evidence for a Game Session-owned launch association. + * + *

Value construction and codec validation alone do not authenticate the owner; the explicit mTLS + * client establishes the Game Session peer before accepting response headers or content. + */ +public final class CanonicalGameInstanceLaunchAssociationReadEvidence { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + private CanonicalGameInstanceLaunchAssociationReadEvidence() {} + + /** Separate transient read identity and the complete immutable association selector. */ + public record Request( + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID gameInstanceUuid, + String controlPlaneRequestId, + String launchDescriptorId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationEvidenceDigest) { + public Request { + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireText(controlPlaneRequestId, "controlPlaneRequestId"); + requireText(launchDescriptorId, "launchDescriptorId"); + requireDigest(expectedDescriptorRequestDigest, "expectedDescriptorRequestDigest"); + requireDigest(expectedDescriptorResultDigest, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationEvidenceDigest, "expectedReleaseAttestationEvidenceDigest"); + } + } + + /** Current Game Session row states; these do not represent World lifecycle or admission. */ + public enum CurrentGameInstanceStatus { + STARTING, + RUNNING, + STOPPING, + STOPPED + } + + /** + * The exact World composition result, including the independently closed descriptor/release pair. + */ + public record Result( + Request request, + UUID playableStateNamespaceId, + RealmEntryPolicy.StateScope playableStateScope, + boolean publicProduction, + CurrentGameInstanceStatus currentGameInstanceStatus, + long currentRowVersion, + CompleteLaunchBindingEvidence launchBindingEvidence) { + public Result { + Objects.requireNonNull(request, "request"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (playableStateScope != RealmEntryPolicy.StateScope.SHARED) { + throw new IllegalArgumentException( + "Launch association read requires SHARED playable state"); + } + if (!publicProduction) { + throw new IllegalArgumentException("Launch association read requires public production"); + } + Objects.requireNonNull(currentGameInstanceStatus, "currentGameInstanceStatus"); + if (currentRowVersion < 0) { + throw new IllegalArgumentException("currentRowVersion must not be negative"); + } + Objects.requireNonNull(launchBindingEvidence, "launchBindingEvidence"); + var descriptor = launchBindingEvidence.descriptor(); + descriptor.requireValid(); + launchBindingEvidence.releaseAttestation().requireValid(descriptor); + if (!request.targetNamespace().equals(descriptor.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.worldSlug().equals(descriptor.worldSlug()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(launchBindingEvidence.releaseAttestation().evidenceDigest())) { + throw new IllegalArgumentException( + "Launch association read result differs from its exact selector or complete binding"); + } + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank() || value.length() > 256) { + throw new IllegalArgumentException(name + " must be non-blank and bounded"); + } + } + + private static void requireDigest(String value, String name) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java new file mode 100644 index 0000000000..b11c479e75 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java @@ -0,0 +1,188 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Result; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; + +/** Closed request mapping and strict exact-readback validation for the Game Session owner API. */ +public final class CanonicalGameInstanceLaunchAssociationReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private CanonicalGameInstanceLaunchAssociationReadGrpcCodec() {} + + public static GetCanonicalGameInstanceLaunchAssociationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + return GetCanonicalGameInstanceLaunchAssociationRequest.newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setGameInstanceUuid(request.gameInstanceUuid().toString()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setLaunchDescriptorId(request.launchDescriptorId()) + .setExpectedDescriptorRequestDigest(request.expectedDescriptorRequestDigest()) + .setExpectedDescriptorResultDigest(request.expectedDescriptorResultDigest()) + .setExpectedReleaseAttestationEvidenceDigest( + request.expectedReleaseAttestationEvidenceDigest()) + .build(); + } + + /** Validates all ten request echoes and the complete unchanged descriptor/release evidence. */ + public static Result fromResponse( + Request expectedRequest, GetCanonicalGameInstanceLaunchAssociationResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "GetCanonicalGameInstanceLaunchAssociation response"); + if (response.hasError()) { + requireNoUnknownFields( + response.getError(), "GetCanonicalGameInstanceLaunchAssociation error"); + throw new IllegalArgumentException( + "Game Session rejected the exact canonical launch association read"); + } + + requireEcho( + expectedRequest.readRequestId().toString(), response.getReadRequestId(), "readRequestId"); + requireEcho( + expectedRequest.targetNamespace(), response.getTargetNamespace(), "targetNamespace"); + requireEcho( + expectedRequest.canonicalTenantId().toString(), + response.getCanonicalTenantId(), + "canonicalTenantId"); + requireEcho(expectedRequest.worldSlug(), response.getWorldSlug(), "worldSlug"); + requireEcho( + expectedRequest.gameInstanceUuid().toString(), + response.getGameInstanceUuid(), + "gameInstanceUuid"); + requireEcho( + expectedRequest.controlPlaneRequestId(), + response.getControlPlaneRequestId(), + "controlPlaneRequestId"); + requireEcho( + expectedRequest.launchDescriptorId(), + response.getLaunchDescriptorId(), + "launchDescriptorId"); + requireEcho( + expectedRequest.expectedDescriptorRequestDigest(), + response.getDescriptorRequestDigest(), + "descriptorRequestDigest"); + requireEcho( + expectedRequest.expectedDescriptorResultDigest(), + response.getDescriptorResultDigest(), + "descriptorResultDigest"); + requireEcho( + expectedRequest.expectedReleaseAttestationEvidenceDigest(), + response.getReleaseAttestationEvidenceDigest(), + "releaseAttestationEvidenceDigest"); + + if (!response.hasLaunchDescriptor() || !response.hasReleaseAttestation()) { + throw new IllegalArgumentException( + "Game Session must return the complete descriptor and release attestation pair"); + } + var completeRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(expectedRequest.readRequestId().toString()) + .setCanonicalTenantId(expectedRequest.canonicalTenantId().toString()) + .setWorldSlug(expectedRequest.worldSlug()) + .setControlPlaneRequestId(expectedRequest.controlPlaneRequestId()) + .setExpectedRequestDigest(expectedRequest.expectedDescriptorRequestDigest()) + .setExpectedResultDigest(expectedRequest.expectedDescriptorResultDigest()) + .build(); + var completeResponse = + GetCompleteLaunchBindingResponse.newBuilder() + .setRequestId(response.getReadRequestId()) + .setLaunchDescriptor(response.getLaunchDescriptor()) + .setReleaseAttestation(response.getReleaseAttestation()) + .build(); + CompleteLaunchBindingEvidence binding = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + completeRequest, completeResponse); + + UUID playableStateNamespaceId = + parseCanonicalNonNilUuid( + response.getPlayableStateNamespaceId(), "playableStateNamespaceId"); + RealmEntryPolicy.StateScope scope; + try { + scope = RealmEntryPolicy.StateScope.valueOf(response.getPlayableStateScope()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Unknown playable state scope", invalid); + } + if (scope != RealmEntryPolicy.StateScope.SHARED) { + throw new IllegalArgumentException("Canonical launch association requires SHARED scope"); + } + if (!response.getPublicProduction()) { + throw new IllegalArgumentException("Canonical launch association requires public production"); + } + + CurrentGameInstanceStatus status; + try { + status = CurrentGameInstanceStatus.valueOf(response.getCurrentGameInstanceStatus()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Unknown current Game Session instance status", invalid); + } + if (response.getCurrentRowVersion() < 0) { + throw new IllegalArgumentException("Current Game Session row version is missing or invalid"); + } + return new Result( + expectedRequest, + playableStateNamespaceId, + scope, + response.getPublicProduction(), + status, + response.getCurrentRowVersion(), + binding); + } + + private static void requireEcho(String expected, String actual, String field) { + if (actual.isEmpty() || !expected.equals(actual)) { + throw new IllegalArgumentException( + "Game Session launch association " + field + " echo changed"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value.isEmpty()) { + throw new IllegalArgumentException("Missing " + label); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid " + label, invalid); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) { + continue; + } + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java new file mode 100644 index 0000000000..a53c0b5511 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.CallCredentials; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.Status; +import java.util.concurrent.Executor; + +/** Authenticates the exact server workload before gRPC releases request headers or body. */ +public final class GrpcServerPeerIdentityCallCredentials extends CallCredentials { + private final String expectedPeerUri; + + public GrpcServerPeerIdentityCallCredentials(String expectedPeerUri) { + this.expectedPeerUri = + GrpcPeerIdentity.parseUri(expectedPeerUri) + .map(GrpcPeerIdentity::uri) + .filter(uri -> uri.equals(expectedPeerUri)) + .orElseThrow( + () -> new IllegalArgumentException("Exact server workload URI is required")); + } + + @Override + public void applyRequestMetadata( + RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { + var sslSession = + requestInfo == null || requestInfo.getTransportAttrs() == null + ? null + : requestInfo.getTransportAttrs().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + boolean exactPeer = + GrpcPeerIdentity.fromSslSession(sslSession) + .map(peer -> expectedPeerUri.equals(peer.uri())) + .orElse(false); + if (!exactPeer) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Request requires the exact authenticated server workload identity")); + return; + } + applier.apply(new Metadata()); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java new file mode 100644 index 0000000000..8d4257ef55 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.common.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.FrameReader; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; + +/** + * Distinct publication operation's immutable original input and Account source participation. This + * validates complete selected Draft structure, not actor authentication or positive source + * authority. The future Account producer must independently establish the complete current source + * vector, including party and operative hosted terms. Draft COMMIT_ORDER and creation results never + * authorize or settle this operation. Later World captures and release/artifact results remain + * separate and must never rewrite the original selection digest. + */ +public record AccountPublicationAuthorizationBinding( + UUID operationId, UUID fenceId, PreallocationInput input, List sources) { + public static final String SCHEMA = "account-publication-authorization/v1"; + + public AccountPublicationAuthorizationBinding { + DraftAuthorizationFenceBinding.requireUuid(operationId); + DraftAuthorizationFenceBinding.requireUuid(fenceId); + Objects.requireNonNull(input); + sources = + List.copyOf(Objects.requireNonNull(sources)).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Distinct applicable publication sources required"); + } + for (SourceEvidence source : sources) { + String requiredScope = + switch (source.kind()) { + case ACCOUNT, GLOBAL_ROLES -> input.actorAccountId().toString(); + case TENANT -> input.selection().intent().canonicalTenantId().toString(); + case MEMBERSHIP -> + input.actorAccountId() + "/" + input.selection().intent().canonicalTenantId(); + default -> null; + }; + if (requiredScope != null && !requiredScope.equals(source.scopeId())) { + throw new IllegalArgumentException( + "Publication source differs from exact actor/tenant scope"); + } + } + } + + /** Stable caller/selection inputs, before any Account operation/fence or World allocation. */ + public record PreallocationInput( + UUID actorAccountId, AuthoredDraftPublishSelectionBinding selection) { + public PreallocationInput { + DraftAuthorizationFenceBinding.requireUuid(actorAccountId); + Objects.requireNonNull(selection); + // Reconstruct the whole closed selection, including target, commit and synchronized fence. + selection = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-publication-input/v1"); + DraftAuthorizationFenceBinding.frame(out, actorAccountId.toString()); + DraftAuthorizationFenceBinding.frame(out, selection.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, selection.digest()); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + } + + public UUID tenantId() { + return input.selection().intent().canonicalTenantId(); + } + + public String publishRequestId() { + return input.selection().intent().publishRequestId(); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, operationId.toString()); + DraftAuthorizationFenceBinding.frame(out, fenceId.toString()); + DraftAuthorizationFenceBinding.frame(out, input.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes()); + } + return out.toByteArray(); + } + + public static AccountPublicationAuthorizationBinding fromStored(byte[] stored) { + FrameReader reader = new FrameReader(stored); + reader.expect(SCHEMA); + UUID operationId = uuid(reader.text()); + UUID fenceId = uuid(reader.text()); + FrameReader inputReader = new FrameReader(reader.bytes()); + inputReader.expect("account-publication-input/v1"); + UUID actor = uuid(inputReader.text()); + byte[] selectionBytes = inputReader.bytes(); + String digest = inputReader.text(); + inputReader.requireEnd(); + var selection = + AuthoredDraftPublishSelectionBinding.fromStored( + new String(selectionBytes, StandardCharsets.UTF_8), digest); + String countText = reader.text(); + DraftAuthorizationFenceBinding.decimal(countText, false); + final int count; + try { + count = Integer.parseInt(countText); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Publication source count out of range", invalid); + } + if (count > reader.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Incomplete publication source vector"); + } + List sources = new ArrayList<>(); + for (int i = 0; i < count; i++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + reader.requireEnd(); + var binding = + new AccountPublicationAuthorizationBinding( + operationId, fenceId, new PreallocationInput(actor, selection), sources); + if (!Arrays.equals(stored, binding.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical publication authorization binding"); + } + return binding; + } + + private static UUID uuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java new file mode 100644 index 0000000000..9c1d742629 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionBinding.java @@ -0,0 +1,359 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Immutable exact selection of an existing synchronized authored Draft for full-version + * publication. This is retained selection evidence, not authorization, owner freeze, or release + * evidence. + */ +public final class AuthoredDraftPublishSelectionBinding { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final PublishIntent intent; + private final TargetProof target; + private final DraftCommitBinding selectedCommit; + private final UUID fenceRequestId; + private final UUID fenceCommitId; + private final String fenceInputDigest; + private final String fenceResultVectorJson; + private final String fenceCreatedAt; + private final String canonicalJson; + private final byte[] canonicalBytes; + private final String digest; + + private AuthoredDraftPublishSelectionBinding( + PublishIntent intent, + TargetProof target, + DraftCommitBinding selectedCommit, + VisibilityFence fence) { + this.intent = Objects.requireNonNull(intent, "intent"); + this.target = Objects.requireNonNull(target, "target"); + this.selectedCommit = Objects.requireNonNull(selectedCommit, "selectedCommit"); + Objects.requireNonNull(fence, "fence"); + if (!intent.canonicalTenantId().equals(target.canonicalTenantId()) + || !intent.canonicalVersionId().equals(target.canonicalVersionId()) + || !target.equals(selectedCommit.target()) + || !intent.selectedCommitRequestId().equals(selectedCommit.requestId()) + || !intent.selectedCommitId().equals(selectedCommit.commitId()) + || !intent.selectedCommitDigest().equals(selectedCommit.digest()) + || !target.equals(fence.target()) + || !intent.selectedCommitRequestId().equals(fence.requestId()) + || !intent.selectedCommitId().equals(fence.commitId()) + || !intent.selectedCommitDigest().equals(fence.inputDigest())) { + throw new IllegalArgumentException( + "Authored Draft publication selection differs from its exact synchronized commit fence"); + } + requireCanonicalArray(fence.resultVectorJson()); + this.fenceRequestId = fence.requestId(); + this.fenceCommitId = fence.commitId(); + this.fenceInputDigest = fence.inputDigest(); + this.fenceResultVectorJson = fence.resultVectorJson(); + this.fenceCreatedAt = fence.createdAt().toInstant().toString(); + try { + canonicalBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(toJsonObject())); + canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + digest = sha256(canonicalBytes); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Authored Draft publication selection could not be canonicalized", exception); + } + } + + /** + * Constructs the exact retained value after the repository has independently verified the locked + * Version, durable commit, owner result vector, and current visibility fence. + */ + public static AuthoredDraftPublishSelectionBinding capture( + PublishIntent intent, TargetProof target, DraftCommitBinding binding, VisibilityFence fence) { + return new AuthoredDraftPublishSelectionBinding(intent, target, binding, fence); + } + + /** Reconstructs a retained selection and rejects malformed or noncanonical stored bytes. */ + public static AuthoredDraftPublishSelectionBinding fromStored( + String storedJson, String storedDigest) { + Objects.requireNonNull(storedJson, "storedJson"); + Objects.requireNonNull(storedDigest, "storedDigest"); + try { + JsonNode root = JSON.readTree(storedJson); + if (root == null || !root.isObject() || !"1".equals(requiredText(root, "schemaVersion"))) { + throw new IllegalArgumentException("Unsupported authored Draft selection schema"); + } + JsonNode intentNode = requiredObject(root, "intent"); + PublishIntent intent = + new PublishIntent( + UUID.fromString(requiredText(intentNode, "canonicalTenantId")), + UUID.fromString(requiredText(intentNode, "canonicalVersionId")), + requiredText(intentNode, "publishRequestId"), + requiredText(intentNode, "expectedVersionStateEpoch"), + requiredText(intentNode, "notes"), + UUID.fromString(requiredText(intentNode, "selectedCommitRequestId")), + UUID.fromString(requiredText(intentNode, "selectedCommitId")), + requiredText(intentNode, "selectedCommitDigest")); + JsonNode targetNode = requiredObject(root, "target"); + TargetProof target = + new TargetProof( + UUID.fromString(requiredText(targetNode, "canonicalTenantId")), + UUID.fromString(requiredText(targetNode, "canonicalVersionId")), + positiveLong(targetNode, "gameDesignVersionRowId"), + requiredText(targetNode, "gameDesignVersionTenantKey"), + positiveLong(targetNode, "sourceGameRowId"), + requiredText(targetNode, "sourceGameTenantKey"), + requiredText(targetNode, "sourceProvenanceKind")); + DraftCommitBinding selectedCommit = + DraftCommitBinding.fromStored( + requiredText(root, "selectedCommitBindingJson"), + requiredText(root, "selectedCommitDigest")); + JsonNode fenceNode = requiredObject(root, "synchronizedFence"); + String fenceResultVectorJson = requiredText(fenceNode, "resultVectorJson"); + requireCanonicalArray(fenceResultVectorJson); + VisibilityFence fence = + new VisibilityFence( + target, + UUID.fromString(requiredText(fenceNode, "requestId")), + UUID.fromString(requiredText(fenceNode, "commitId")), + requiredText(fenceNode, "inputDigest"), + fenceResultVectorJson, + OffsetDateTime.parse(requiredText(fenceNode, "createdAt"))); + AuthoredDraftPublishSelectionBinding selection = + new AuthoredDraftPublishSelectionBinding(intent, target, selectedCommit, fence); + if (!selection.canonicalJson.equals(storedJson) + || !selection.digest.equals(storedDigest) + || !Arrays.equals( + selection.canonicalBytes, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Stored authored Draft publication selection is not exact canonical JSON"); + } + return selection; + } catch (RuntimeException exception) { + throw new IllegalStateException("Stored authored Draft selection is corrupt", exception); + } + } + + public PublishIntent intent() { + return intent; + } + + public TargetProof target() { + return target; + } + + public DraftCommitBinding selectedCommit() { + return selectedCommit; + } + + public UUID fenceRequestId() { + return fenceRequestId; + } + + public UUID fenceCommitId() { + return fenceCommitId; + } + + public String fenceInputDigest() { + return fenceInputDigest; + } + + public String fenceResultVectorJson() { + return fenceResultVectorJson; + } + + public String fenceCreatedAt() { + return fenceCreatedAt; + } + + public String canonicalJson() { + return canonicalJson; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof AuthoredDraftPublishSelectionBinding selection + && digest.equals(selection.digest) + && Arrays.equals(canonicalBytes, selection.canonicalBytes)); + } + + @Override + public int hashCode() { + return 31 * digest.hashCode() + Arrays.hashCode(canonicalBytes); + } + + private Map toJsonObject() { + Map root = new LinkedHashMap<>(); + root.put("schemaVersion", "1"); + root.put("intent", intentJson(intent)); + root.put("target", targetJson(target)); + root.put("selectedCommitBindingJson", selectedCommit.canonicalJson()); + root.put("selectedCommitDigest", selectedCommit.digest()); + Map fence = new LinkedHashMap<>(); + fence.put("requestId", fenceRequestId.toString()); + fence.put("commitId", fenceCommitId.toString()); + fence.put("inputDigest", fenceInputDigest); + fence.put("resultVectorJson", fenceResultVectorJson); + fence.put("createdAt", fenceCreatedAt); + root.put("synchronizedFence", fence); + return root; + } + + private static Map intentJson(PublishIntent intent) { + Map object = new LinkedHashMap<>(); + object.put("canonicalTenantId", intent.canonicalTenantId().toString()); + object.put("canonicalVersionId", intent.canonicalVersionId().toString()); + object.put("publishRequestId", intent.publishRequestId()); + object.put("expectedVersionStateEpoch", intent.expectedVersionStateEpoch()); + object.put("notes", intent.notes()); + object.put("selectedCommitRequestId", intent.selectedCommitRequestId().toString()); + object.put("selectedCommitId", intent.selectedCommitId().toString()); + object.put("selectedCommitDigest", intent.selectedCommitDigest()); + return object; + } + + private static Map targetJson(TargetProof target) { + Map object = new LinkedHashMap<>(); + object.put("canonicalTenantId", target.canonicalTenantId().toString()); + object.put("canonicalVersionId", target.canonicalVersionId().toString()); + object.put("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())); + object.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + object.put("sourceGameRowId", Long.toString(target.sourceGameRowId())); + object.put("sourceGameTenantKey", target.sourceGameTenantKey()); + object.put("sourceProvenanceKind", target.sourceProvenanceKind()); + return object; + } + + private static JsonNode requiredObject(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isObject()) { + throw new IllegalArgumentException( + "Stored authored Draft selection is missing object field " + field); + } + return value; + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException( + "Stored authored Draft selection is missing text field " + field); + } + return value.textValue(); + } + + private static long positiveLong(JsonNode object, String field) { + String value = requiredText(object, field); + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException( + "Stored source row ID is not a positive canonical decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "Stored source row ID is outside the supported range", exception); + } + } + + private static void requireCanonicalArray(String storedJson) { + try { + JsonNode node = JSON.readTree(storedJson); + if (node == null || !node.isArray()) { + throw new IllegalArgumentException("Stored owner result vector is not an array"); + } + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(storedJson); + if (!Arrays.equals(canonical, storedJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Stored owner result vector is not canonical JSON"); + } + } catch (IOException exception) { + throw new IllegalArgumentException("Stored owner result vector is malformed JSON", exception); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + /** Full caller-supplied intent for selecting one exact Draft commit to publish. */ + public record PublishIntent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishRequestId, + String expectedVersionStateEpoch, + String notes, + UUID selectedCommitRequestId, + UUID selectedCommitId, + String selectedCommitDigest) { + public PublishIntent { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + PublicationDigestRequestBinding.validatePublicationIdentity( + canonicalTenantId.toString(), publishRequestId); + requirePositiveCounter(expectedVersionStateEpoch, "expectedVersionStateEpoch"); + Objects.requireNonNull(notes, "notes"); + requireNonNil(selectedCommitRequestId, "selectedCommitRequestId"); + requireNonNil(selectedCommitId, "selectedCommitId"); + requireDigest(selectedCommitDigest, "selectedCommitDigest"); + } + } + + private static void requirePositiveCounter(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal string"); + } + } + + private static void requireDigest(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + } + + /** + * Exact previously captured synchronized fence; its structure does not authenticate its owner. + */ + public record VisibilityFence( + TargetProof target, + UUID requestId, + UUID commitId, + String inputDigest, + String resultVectorJson, + OffsetDateTime createdAt) {} + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java new file mode 100644 index 0000000000..0d664c9a04 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java @@ -0,0 +1,67 @@ +package net.firedevops.firemud.common.publication; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Original closed publication input; byte integrity never authenticates its producer. */ +public record GameDesignPublicationOperationBinding( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + public static final String SCHEMA = "game-design-publication-operation/v1"; + + public GameDesignPublicationOperationBinding { + account = + AccountPublicationAuthorizationBinding.fromStored( + Objects.requireNonNull(account).canonicalBytes()); + world = + WorldPublishedStartLocationEvidence.fromStored( + Objects.requireNonNull(world).canonicalBytes()); + var selection = account.input().selection(); + var intent = selection.intent(); + var freeze = world.request(); + if (!account.tenantId().equals(freeze.canonicalTenantId()) + || !intent.canonicalVersionId().equals(freeze.canonicalVersionId()) + || !intent.publishRequestId().equals(freeze.publicationRequestId()) + || !selection.digest().equals("sha256:" + freeze.requestDigest()) + || !intent.expectedVersionStateEpoch().equals(Long.toString(freeze.versionStateEpoch())) + || !intent.selectedCommitId().toString().equals(freeze.appliedCommitId()) + || !Arrays.equals( + selection.selectedCommit().canonicalBytes(), + DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()) + .normalizedInput())) { + throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + } + if (!PublicationDigestRequestBinding.full( + account.tenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity() + .equals(freeze.publishWorkflowId())) { + throw new IllegalArgumentException("PUBLICATION_OPERATION_WORKFLOW_CONFLICT"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, account.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, world.canonicalBytes()); + return out.toByteArray(); + } + + public static GameDesignPublicationOperationBinding fromStored(byte[] bytes) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + var operation = + new GameDesignPublicationOperationBinding( + AccountPublicationAuthorizationBinding.fromStored(reader.bytes()), + WorldPublishedStartLocationEvidence.fromStored(reader.bytes())); + reader.requireEnd(); + if (!Arrays.equals(bytes, operation.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical publication operation"); + } + return operation; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java new file mode 100644 index 0000000000..75ccc90dc2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Closed v1 authored realm-entry policy shared by the publication owner and runtime receivers. */ +public record RealmEntryPolicy( + int schemaVersion, + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + StateScope stateScope, + EntryPolicy entryPolicy, + String canonicalJson) { + public static final String REVISION_KIND = "REALM_ENTRY_POLICY"; + public static final int SCHEMA_VERSION = 1; + public static final int MAX_JSON_BYTES = 4096; + public static final int MAX_SLUG_LENGTH = 64; + public static final int MAX_DISPLAY_NAME_CODE_POINTS = 128; + + private static final Set FIELDS = + Set.of( + "schemaVersion", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "visible", + "publicProduction", + "stateScope", + "entryPolicy"); + private static final Pattern SLUG_PATTERN = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + + public enum StateScope { + SHARED, + ISOLATED + } + + public enum EntryPolicy { + PRESEEDED_ONLY + } + + /** Parses valid v1 JSON and returns the RFC 8785 canonical policy representation. */ + public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { + if (json == null || json.isBlank()) { + throw invalid("data is required"); + } + if (!StandardCharsets.UTF_8.newEncoder().canEncode(json)) { + throw invalid("data must be valid UTF-8"); + } + ByteBuffer inputBytes = StandardCharsets.UTF_8.encode(json); + if (inputBytes.remaining() > MAX_JSON_BYTES) { + throw invalid("data exceeds the v1 byte limit"); + } + + JsonNode root; + String canonicalJson; + try { + canonicalJson = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + root = objectMapper.readTree(canonicalJson); + } catch (IOException | RuntimeException exception) { + throw invalid("data must be valid unambiguous JSON"); + } + if (root == null || !root.isObject()) { + throw invalid("must be a JSON object"); + } + for (String field : FIELDS) { + if (!root.has(field)) { + throw invalid(field + " is required"); + } + } + if (root.size() != FIELDS.size()) { + throw invalid("must contain exactly the v1 fields"); + } + + JsonNode schemaVersion = root.get("schemaVersion"); + if (schemaVersion == null + || !schemaVersion.isIntegralNumber() + || !schemaVersion.canConvertToInt() + || schemaVersion.intValue() != SCHEMA_VERSION) { + throw invalid("schemaVersion must be the integer 1"); + } + String worldSlug = requireSlug(root, "worldSlug"); + String worldDisplayName = requireDisplayName(root, "worldDisplayName"); + String realmSlug = requireSlug(root, "realmSlug"); + String realmDisplayName = requireDisplayName(root, "realmDisplayName"); + boolean visible = requireBoolean(root, "visible"); + boolean publicProduction = requireBoolean(root, "publicProduction"); + StateScope stateScope = requireEnum(root, "stateScope", StateScope.class); + EntryPolicy entryPolicy = requireEnum(root, "entryPolicy", EntryPolicy.class); + + return new RealmEntryPolicy( + SCHEMA_VERSION, + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + entryPolicy, + canonicalJson); + } + + /** Parses policy evidence that is required to already use its exact canonical JSON spelling. */ + public static RealmEntryPolicy parseCanonical(String json, ObjectMapper objectMapper) { + RealmEntryPolicy policy = parse(json, objectMapper); + if (!json.equals(policy.canonicalJson())) { + throw invalid("published policy JSON is not canonical"); + } + return policy; + } + + public static boolean isCanonicalSlug(String value) { + return value != null + && value.length() <= MAX_SLUG_LENGTH + && SLUG_PATTERN.matcher(value).matches(); + } + + private static String requireSlug(JsonNode root, String field) { + String value = requireText(root, field); + if (!isCanonicalSlug(value)) { + throw invalid(field + " must be a canonical lower-case slug"); + } + return value; + } + + private static String requireDisplayName(JsonNode root, String field) { + String value = requireText(root, field); + if (!value.equals(value.strip()) + || value.codePointCount(0, value.length()) > MAX_DISPLAY_NAME_CODE_POINTS + || value.codePoints().anyMatch(Character::isISOControl)) { + throw invalid(field + " is outside the v1 text bounds"); + } + return value; + } + + private static String requireText(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isTextual() || value.asText().isBlank()) { + throw invalid(field + " must be a nonblank string"); + } + return value.asText(); + } + + private static boolean requireBoolean(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isBoolean()) { + throw invalid(field + " must be an explicit boolean"); + } + return value.booleanValue(); + } + + private static > T requireEnum(JsonNode root, String field, Class type) { + String value = requireText(root, field); + try { + return Enum.valueOf(type, value); + } catch (IllegalArgumentException exception) { + throw invalid("unsupported " + field); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException("INVALID_ARGUMENT: realmEntryPolicy " + message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/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/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClient.java new file mode 100644 index 0000000000..3f306a6075 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClient.java @@ -0,0 +1,185 @@ +package net.firedevops.firemud.common.world; + +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.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +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.WorldCanonicalInstancePreparationServiceGrpc; + +/** Explicit file-backed mTLS client for the unregistered canonical World preparation RPC. */ +public final class CanonicalWorldInstancePreparationClient + extends AbstractReloadingBlockingGrpcClient< + WorldCanonicalInstancePreparationServiceGrpc + .WorldCanonicalInstancePreparationServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public CanonicalWorldInstancePreparationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + CanonicalWorldInstancePreparationClient.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("Canonical World preparation client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Canonical World preparation client has no gRPC stub"); + } + initialized = true; + } + + /** + * Sends the exact committed association selector and validates World-owned lifecycle readback. + */ + public WorldCanonicalInstanceLifecycleEvidence prepare( + Request request, WorldCanonicalInstanceLifecycleEvidence.Request expectedLifecycleRequest) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(expectedLifecycleRequest, "expectedLifecycleRequest"); + if (!workloadNamespace.equals(request.targetNamespace()) + || !workloadNamespace.equals(expectedLifecycleRequest.targetNamespace())) { + throw new IllegalArgumentException( + "Canonical preparation requests must use the configured workload namespace"); + } + requireSameSelector(request, expectedLifecycleRequest); + + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .prepareCanonicalWorldInstance( + CanonicalWorldInstancePreparationGrpcCodec.toRequest(request)); + try { + return CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, expectedLifecycleRequest, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid canonical instance preparation evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldCanonicalInstancePreparationServiceGrpc + .WorldCanonicalInstancePreparationServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldCanonicalInstancePreparationServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldCanonicalInstancePreparationServiceGrpc + .WorldCanonicalInstancePreparationServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Canonical World preparation client is not initialized and available"); + } + return currentStub; + } + + private static void requireSameSelector( + Request request, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + if (!request.readRequestId().equals(lifecycleRequest.readRequestId()) + || !request.targetNamespace().equals(lifecycleRequest.targetNamespace()) + || !request.canonicalTenantId().equals(lifecycleRequest.canonicalTenantId()) + || !request.worldSlug().equals(lifecycleRequest.worldSlug()) + || !request.gameInstanceUuid().equals(lifecycleRequest.canonicalGameInstanceId()) + || !request.controlPlaneRequestId().equals(lifecycleRequest.controlPlaneRequestId()) + || !request + .expectedDescriptorRequestDigest() + .equals(lifecycleRequest.expectedDescriptorRequestDigest()) + || !request + .expectedDescriptorResultDigest() + .equals(lifecycleRequest.expectedDescriptorResultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(lifecycleRequest.expectedReleaseAttestationDigest())) { + throw new IllegalArgumentException( + "Canonical preparation selector differs from the expected World lifecycle request"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Canonical World preparation 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( + "Canonical World preparation requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Canonical World preparation requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Canonical World preparation " + label + " must be a readable file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Canonical World preparation " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodec.java new file mode 100644 index 0000000000..710bf4adc7 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodec.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; + +/** Closed transport mapping for the explicitly unwired canonical World preparation handoff. */ +public final class CanonicalWorldInstancePreparationGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private CanonicalWorldInstancePreparationGrpcCodec() {} + + /** Encodes the exact committed Game Session launch-association selector. */ + public static PrepareCanonicalWorldInstanceRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + return PrepareCanonicalWorldInstanceRequest.newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setGameInstanceUuid(request.gameInstanceUuid().toString()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setLaunchDescriptorId(request.launchDescriptorId()) + .setExpectedDescriptorRequestDigest(request.expectedDescriptorRequestDigest()) + .setExpectedDescriptorResultDigest(request.expectedDescriptorResultDigest()) + .setExpectedReleaseAttestationEvidenceDigest( + request.expectedReleaseAttestationEvidenceDigest()) + .build(); + } + + /** Decodes the exact selector through the existing validated Game Session request value. */ + public static Request fromRequest(PrepareCanonicalWorldInstanceRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "PrepareCanonicalWorldInstanceRequest"); + return new Request( + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getGameInstanceUuid(), "gameInstanceUuid"), + request.getControlPlaneRequestId(), + request.getLaunchDescriptorId(), + request.getExpectedDescriptorRequestDigest(), + request.getExpectedDescriptorResultDigest(), + request.getExpectedReleaseAttestationEvidenceDigest()); + } + + /** + * Encodes lifecycle evidence only when its inner request and complete pair match the selector. + */ + public static PrepareCanonicalWorldInstanceResponse toResponse( + Request request, WorldCanonicalInstanceLifecycleEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + requireSameBinding(request, evidence.request(), evidence); + ReadWorldCanonicalInstanceLifecycleResponse lifecycle = + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(evidence.request(), evidence); + return PrepareCanonicalWorldInstanceResponse.newBuilder() + .setRequest(toRequest(request)) + .setLifecycle(lifecycle) + .build(); + } + + /** Validates the exact outer echo and the complete inner lifecycle owner snapshot. */ + public static WorldCanonicalInstanceLifecycleEvidence fromResponse( + Request request, + WorldCanonicalInstanceLifecycleEvidence.Request expectedLifecycleRequest, + PrepareCanonicalWorldInstanceResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(expectedLifecycleRequest, "expectedLifecycleRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "PrepareCanonicalWorldInstanceResponse"); + if (response.hasError()) { + throw new IllegalArgumentException("World rejected canonical instance preparation"); + } + if (!response.hasRequest()) { + throw new IllegalArgumentException("Canonical World preparation request echo is required"); + } + if (!response.hasLifecycle()) { + throw new IllegalArgumentException("Canonical World lifecycle response is required"); + } + + Request echoedRequest = fromRequest(response.getRequest()); + if (!request.equals(echoedRequest)) { + throw new IllegalArgumentException("World changed the exact canonical preparation request"); + } + requireSameBinding(request, expectedLifecycleRequest, null); + + WorldCanonicalInstanceLifecycleEvidence evidence = + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse( + expectedLifecycleRequest, response.getLifecycle()); + requireSameBinding(request, evidence.request(), evidence); + return evidence; + } + + private static void requireSameBinding( + Request request, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, + WorldCanonicalInstanceLifecycleEvidence evidence) { + if (!request.readRequestId().equals(lifecycleRequest.readRequestId()) + || !request.targetNamespace().equals(lifecycleRequest.targetNamespace()) + || !request.canonicalTenantId().equals(lifecycleRequest.canonicalTenantId()) + || !request.worldSlug().equals(lifecycleRequest.worldSlug()) + || !request.gameInstanceUuid().equals(lifecycleRequest.canonicalGameInstanceId()) + || !request.controlPlaneRequestId().equals(lifecycleRequest.controlPlaneRequestId()) + || !request + .expectedDescriptorRequestDigest() + .equals(lifecycleRequest.expectedDescriptorRequestDigest()) + || !request + .expectedDescriptorResultDigest() + .equals(lifecycleRequest.expectedDescriptorResultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(lifecycleRequest.expectedReleaseAttestationDigest())) { + throw new IllegalArgumentException( + "Canonical preparation selector differs from the World lifecycle request"); + } + if (evidence != null + && !request + .launchDescriptorId() + .equals(evidence.launchBinding().descriptor().launchDescriptorId())) { + throw new IllegalArgumentException( + "Canonical preparation selector differs from the complete launch descriptor"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null || value.isEmpty()) { + throw new IllegalArgumentException("Missing " + label); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) { + continue; + } + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProof.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProof.java new file mode 100644 index 0000000000..b6e7d46d8a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProof.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.common.world; + +import java.time.Instant; +import java.util.Objects; +import java.util.regex.Pattern; + +/** Closed typed Game Session owner outcome bound to the exact World-issued hold identity. */ +public record GameSessionCanonicalInitialAdmissionOwnerProof( + WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity, + Outcome outcome, + Long committedPointerVersion, + Long auditEventId, + String proofDigest, + boolean positiveDurableAbort, + Instant terminalAt) { + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + public enum Outcome { + PENDING, + COMMITTED, + ABORTED + } + + public GameSessionCanonicalInitialAdmissionOwnerProof { + Objects.requireNonNull(holdIdentity, "holdIdentity"); + Objects.requireNonNull(outcome, "outcome"); + if (outcome == Outcome.PENDING) { + if (committedPointerVersion != null + || auditEventId != null + || proofDigest != null + || positiveDurableAbort + || terminalAt != null) { + throw new IllegalArgumentException("PENDING is not terminal owner proof"); + } + } else if (outcome == Outcome.COMMITTED) { + requirePositive(committedPointerVersion, "committedPointerVersion"); + requirePositive(auditEventId, "auditEventId"); + requireProofDigest(proofDigest); + Objects.requireNonNull(terminalAt, "terminalAt"); + if (positiveDurableAbort) { + throw new IllegalArgumentException("COMMITTED cannot assert durable abort"); + } + } else { + if (committedPointerVersion != null || auditEventId != null) { + throw new IllegalArgumentException("ABORTED cannot carry pointer or audit commit fields"); + } + requireProofDigest(proofDigest); + Objects.requireNonNull(terminalAt, "terminalAt"); + if (!positiveDurableAbort) { + throw new IllegalArgumentException("ABORTED requires positive durable fencing"); + } + } + } + + private static void requirePositive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalArgumentException(field + " must be present and positive"); + } + } + + private static void requireProofDigest(String value) { + if (value == null || !PREFIXED_SHA256.matcher(value).matches()) { + throw new IllegalArgumentException("Terminal owner proof requires a prefixed SHA-256 digest"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodec.java new file mode 100644 index 0000000000..765f33aa5f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodec.java @@ -0,0 +1,114 @@ +package net.firedevops.firemud.common.world; + +import java.io.ByteArrayOutputStream; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed length-framed codec for durable Game Session canonical initial-admission outcomes. */ +public final class GameSessionCanonicalInitialAdmissionOwnerProofCodec { + private static final String SCHEMA = "game-session-canonical-initial-admission-owner-proof/v1"; + + private GameSessionCanonicalInitialAdmissionOwnerProofCodec() {} + + public static byte[] canonicalBytes(GameSessionCanonicalInitialAdmissionOwnerProof proof) { + Objects.requireNonNull(proof, "proof"); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, proof.holdIdentity().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(output, proof.outcome().name()); + frameOptional( + output, + proof.committedPointerVersion() == null + ? null + : Long.toString(proof.committedPointerVersion())); + frameOptional( + output, proof.auditEventId() == null ? null : Long.toString(proof.auditEventId())); + frameOptional(output, proof.proofDigest()); + DraftAuthorizationFenceBinding.frame(output, proof.positiveDurableAbort() ? "true" : "false"); + frameOptional(output, proof.terminalAt() == null ? null : proof.terminalAt().toString()); + return output.toByteArray(); + } + + /** Returns the canonical owner outcome only when the complete framed value round-trips. */ + public static GameSessionCanonicalInitialAdmissionOwnerProof fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(SCHEMA); + var holdIdentity = WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(reader.bytes()); + var outcome = parseOutcome(reader.text()); + Long pointerVersion = optionalPositiveLong(reader.optionalText(), "committedPointerVersion"); + Long auditEventId = optionalPositiveLong(reader.optionalText(), "auditEventId"); + String proofDigest = reader.optionalText(); + boolean positiveDurableAbort = parseBoolean(reader.text()); + String terminalText = reader.optionalText(); + reader.requireEnd(); + Instant terminalAt = terminalText == null ? null : parseInstant(terminalText); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + holdIdentity, + outcome, + pointerVersion, + auditEventId, + proofDigest, + positiveDurableAbort, + terminalAt); + if (!Arrays.equals(stored, canonicalBytes(proof))) { + throw new IllegalArgumentException("Noncanonical Game Session owner proof"); + } + return proof; + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof.Outcome parseOutcome(String value) { + try { + return GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.valueOf(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Unsupported canonical initial-admission owner outcome", invalid); + } + } + + private static Long optionalPositiveLong(String value, String field) { + if (value == null) { + return null; + } + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal text"); + } + try { + return Long.valueOf(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static void frameOptional(ByteArrayOutputStream output, String value) { + if (value == null) { + DraftAuthorizationFenceBinding.frame(output, "ABSENT"); + } else { + DraftAuthorizationFenceBinding.frame(output, "PRESENT"); + DraftAuthorizationFenceBinding.frame(output, value); + } + } + + private static boolean parseBoolean(String value) { + return switch (value) { + case "true" -> true; + case "false" -> false; + default -> throw new IllegalArgumentException("Canonical boolean frame required"); + }; + } + + private static Instant parseInstant(String value) { + try { + Instant parsed = Instant.parse(value); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("Terminal timestamp is not canonical"); + } + return parsed; + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Terminal timestamp is not canonical", invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java new file mode 100644 index 0000000000..7da2b1ad7f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/RoomTemplateRef.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.common.world; + +import java.util.Objects; +import java.util.UUID; + +/** Canonical owner-authored World room identity; never a runtime instance or private row key. */ +public record RoomTemplateRef(UUID tenantId, UUID versionId, UUID roomTemplateId) { + private static final UUID NIL = new UUID(0L, 0L); + + public RoomTemplateRef { + requireNonNil(tenantId, "tenantId"); + requireNonNil(versionId, "versionId"); + requireNonNil(roomTemplateId, "roomTemplateId"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil canonical UUID"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java new file mode 100644 index 0000000000..67c1e2408e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHold.java @@ -0,0 +1,391 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed request and immutable World-issued identity for canonical initial admission. + * + *

This carrier records acquisition identity only. It does not represent a hold status, an + * admission outcome, current lifecycle proof, an authorization grant, or an expiry authority. + */ +public final class WorldCanonicalInitialAdmissionHold { + public static final String REQUEST_SCHEMA = "world-canonical-initial-admission-hold-request/v1"; + public static final String IDENTITY_SCHEMA = "world-canonical-initial-admission-hold-identity/v1"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern LOWER_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set REQUEST_ENVELOPE_FIELDS = Set.of("schema", "request"); + private static final Set REQUEST_FIELDS = + Set.of( + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "realmId", + "playableStateNamespaceId", + "playableStateScope", + "canonicalGameInstanceId", + "canonicalVersionId", + "activeLifecycleEpoch", + "initialAdmissionRequestId", + "initialAdmissionRequestDigest", + "initialAdmissionOrigin", + "expectedCatalogRevision", + "expectedPriorPointerVersion"); + private static final Set IDENTITY_FIELDS = + Set.of("schema", "holdId", "holdFence", "holdBindingDigest", "requestBytesBase64"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private WorldCanonicalInitialAdmissionHold() {} + + /** The only initial-admission origin preconditions accepted by the first-OPEN contract. */ + public enum InitialAdmissionOrigin { + NO_PRIOR_POINTER, + EXPECT_CLOSED + } + + /** + * Complete immutable acquisition input. The supplied Game Session digest remains opaque here; + * World computes a separate hold binding digest over this complete versioned request. + */ + public record Request( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + long activeLifecycleEpoch, + String initialAdmissionRequestId, + String initialAdmissionRequestDigest, + InitialAdmissionOrigin initialAdmissionOrigin, + long expectedCatalogRevision, + Long expectedPriorPointerVersion) { + public Request { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(realmId, "realmId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "Only SHARED playableStateScope is supported for initial admission"); + } + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + if (activeLifecycleEpoch <= 0) { + throw new IllegalArgumentException("activeLifecycleEpoch must be positive"); + } + requireBoundedText(initialAdmissionRequestId, "initialAdmissionRequestId", 128); + requireLowerSha256(initialAdmissionRequestDigest, "initialAdmissionRequestDigest"); + Objects.requireNonNull(initialAdmissionOrigin, "initialAdmissionOrigin"); + if (expectedCatalogRevision <= 0) { + throw new IllegalArgumentException("expectedCatalogRevision must be positive"); + } + if (expectedPriorPointerVersion != null && expectedPriorPointerVersion <= 0) { + throw new IllegalArgumentException( + "expectedPriorPointerVersion must be positive when present"); + } + if (initialAdmissionOrigin == InitialAdmissionOrigin.NO_PRIOR_POINTER + && expectedPriorPointerVersion != null) { + throw new IllegalArgumentException( + "NO_PRIOR_POINTER cannot carry expectedPriorPointerVersion"); + } + if (initialAdmissionOrigin == InitialAdmissionOrigin.EXPECT_CLOSED + && expectedPriorPointerVersion == null) { + throw new IllegalArgumentException("EXPECT_CLOSED requires expectedPriorPointerVersion"); + } + } + + /** Complete versioned request bytes in RFC 8785 canonical JSON form. */ + public byte[] canonicalRequestBytes() { + Map envelope = new LinkedHashMap<>(); + envelope.put("schema", REQUEST_SCHEMA); + envelope.put("request", requestJson(this)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(envelope)); + } catch (IOException impossible) { + throw new IllegalStateException( + "Canonical initial-admission request cannot be encoded", impossible); + } + } + + /** World hold-binding digest; distinct from the opaque Game Session request digest. */ + public String holdBindingDigest() { + return sha256(canonicalRequestBytes()); + } + + /** Decodes only the complete exact request shape and requires canonical retained bytes. */ + public static Request fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, REQUEST_ENVELOPE_FIELDS, "Canonical initial-admission request"); + if (!REQUEST_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported initial-admission request schema"); + } + JsonNode value = root.get("request"); + requireFields(value, REQUEST_FIELDS, "Canonical initial-admission request body"); + Request request = + new Request( + text(value, "targetNamespace"), + parseUuid(text(value, "canonicalTenantId"), "canonicalTenantId"), + text(value, "worldSlug"), + parseUuid(text(value, "realmId"), "realmId"), + parseUuid(text(value, "playableStateNamespaceId"), "playableStateNamespaceId"), + text(value, "playableStateScope"), + parseUuid(text(value, "canonicalGameInstanceId"), "canonicalGameInstanceId"), + parseUuid(text(value, "canonicalVersionId"), "canonicalVersionId"), + positiveLong(text(value, "activeLifecycleEpoch"), "activeLifecycleEpoch"), + text(value, "initialAdmissionRequestId"), + text(value, "initialAdmissionRequestDigest"), + parseOrigin(text(value, "initialAdmissionOrigin")), + positiveLong(text(value, "expectedCatalogRevision"), "expectedCatalogRevision"), + optionalPositiveLong(value, "expectedPriorPointerVersion")); + if (!Arrays.equals(stored, request.canonicalRequestBytes())) { + throw new IllegalArgumentException( + "Canonical initial-admission request is not canonical"); + } + return request; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException( + "Canonical initial-admission request is invalid", invalid); + } + } + } + + /** + * Immutable acquired identity: a complete request plus World-issued non-nil hold identity and + * equality-only fence. Exact acquisition retries retain this object and its request digest. + */ + public record HoldIdentity(Request request, UUID holdId, UUID holdFence) { + public HoldIdentity { + Objects.requireNonNull(request, "request"); + requireNonNil(holdId, "holdId"); + requireNonNil(holdFence, "holdFence"); + } + + public byte[] canonicalRequestBytes() { + return request.canonicalRequestBytes(); + } + + public String holdBindingDigest() { + return request.holdBindingDigest(); + } + + /** Canonical retained identity bytes; no lifecycle or mutable hold state is represented. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", IDENTITY_SCHEMA); + value.put("holdId", holdId.toString()); + value.put("holdFence", holdFence.toString()); + value.put("holdBindingDigest", holdBindingDigest()); + value.put("requestBytesBase64", Base64.getEncoder().encodeToString(canonicalRequestBytes())); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "Canonical initial-admission hold identity cannot be encoded", impossible); + } + } + + /** Decodes and verifies the entire immutable request/hold identity readback. */ + public static HoldIdentity fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, IDENTITY_FIELDS, "Canonical initial-admission hold identity"); + if (!IDENTITY_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported initial-admission hold identity schema"); + } + Request request = Request.fromStored(decodeBase64(root, "requestBytesBase64")); + String storedDigest = text(root, "holdBindingDigest"); + if (!request.holdBindingDigest().equals(storedDigest)) { + throw new IllegalArgumentException( + "Initial-admission hold binding digest differs from request"); + } + HoldIdentity identity = + new HoldIdentity( + request, + parseUuid(text(root, "holdId"), "holdId"), + parseUuid(text(root, "holdFence"), "holdFence")); + if (!Arrays.equals(stored, identity.canonicalBytes())) { + throw new IllegalArgumentException( + "Canonical initial-admission hold identity is not canonical"); + } + return identity; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException( + "Canonical initial-admission hold identity is invalid", invalid); + } + } + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("worldSlug", request.worldSlug()); + value.put("realmId", request.realmId().toString()); + value.put("playableStateNamespaceId", request.playableStateNamespaceId().toString()); + value.put("playableStateScope", request.playableStateScope()); + value.put("canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("activeLifecycleEpoch", Long.toString(request.activeLifecycleEpoch())); + value.put("initialAdmissionRequestId", request.initialAdmissionRequestId()); + value.put("initialAdmissionRequestDigest", request.initialAdmissionRequestDigest()); + value.put("initialAdmissionOrigin", request.initialAdmissionOrigin().name()); + value.put("expectedCatalogRevision", Long.toString(request.expectedCatalogRevision())); + value.put( + "expectedPriorPointerVersion", + request.expectedPriorPointerVersion() == null + ? null + : Long.toString(request.expectedPriorPointerVersion())); + return value; + } + + private static InitialAdmissionOrigin parseOrigin(String value) { + try { + return InitialAdmissionOrigin.valueOf(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Unsupported initialAdmissionOrigin", invalid); + } + } + + private static Long optionalPositiveLong(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null) { + throw new IllegalArgumentException(field + " must be present as text or null"); + } + if (value.isNull()) { + return null; + } + if (!value.isTextual()) { + throw new IllegalArgumentException( + field + " must be canonical positive decimal text or null"); + } + return positiveLong(value.textValue(), field); + } + + private static long positiveLong(String value, String field) { + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal text"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static UUID parseUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be non-nil"); + } + } + + private static void requireBoundedText(String value, String field, int maximumCodePoints) { + if (value == null + || value.isBlank() + || value.codePointCount(0, value.length()) > maximumCodePoints) { + throw new IllegalArgumentException(field + " must be nonempty and bounded"); + } + } + + private static void requireLowerSha256(String value, String field) { + if (value == null || !LOWER_SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be lowercase 64-character SHA-256 hex"); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException(field + " must be text"); + } + return value.textValue(); + } + + private static byte[] decodeBase64(JsonNode object, String field) { + try { + return Base64.getDecoder().decode(text(object, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must be canonical base64", invalid); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException("Canonical hold bytes are not strict UTF-8", invalid); + } + } + + private static void requireFields(JsonNode object, Set expected, String label) { + if (object == null || !object.isObject() || object.size() != expected.size()) { + throw new IllegalArgumentException(label + " has an invalid closed object shape"); + } + for (String name : object.propertyNames()) { + if (!expected.contains(name)) { + throw new IllegalArgumentException(label + " has an unknown field"); + } + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocation.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocation.java new file mode 100644 index 0000000000..4cecd02d4b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocation.java @@ -0,0 +1,550 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +/** Closed, local World-owned initial placement operation; it does not authenticate its evidence. */ +public final class WorldCanonicalInitialPlayerLocation { + public static final String REQUEST_SCHEMA = "world-canonical-initial-player-location-request/v1"; + public static final String RESULT_SCHEMA = "world-canonical-initial-player-location-result/v1"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set RESULT_FIELDS = + Set.of( + "schema", + "operationId", + "requestDigest", + "requestBytesBase64", + "outcome", + "conflictCode", + "startLocation", + "runtimeRoomInstanceId"); + private static final Set REQUEST_FIELDS = + Set.of( + "schema", + "operationId", + "canonicalTenantId", + "realmId", + "worldSlug", + "canonicalGameInstanceId", + "playableStateNamespaceId", + "playableStateScope", + "canonicalAccountId", + "characterId", + "entityAssignmentOperationId", + "entityAssignmentDigest", + "initialAdmissionHoldId", + "initialAdmissionHoldFence", + "initialAdmissionRequestId", + "initialAdmissionRequestDigest", + "catalogRevision", + "initialAdmissionOrigin", + "initialAdmissionOwnerProofId", + "initialAdmissionOwnerProofDigest", + "pointerAuditId", + "pointerVersion", + "activeLifecycleEvidence"); + private static final Set ROOM_FIELDS = Set.of("tenantId", "versionId", "roomTemplateId"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private WorldCanonicalInitialPlayerLocation() {} + + /** The current World hold schema only proves a first bind from a never-opened catalog. */ + public enum InitialAdmissionOrigin { + NO_PRIOR_POINTER, + EXPECT_CLOSED + } + + public enum Outcome { + APPLIED, + CONFLICT + } + + /** + * Caller-stable operation input. The supplied lifecycle proof is re-read and byte-compared + * against current World owner state in the same writable transaction as the placement write. + * Entity and Game Session producer authentication remains an external, default-denied gate. + */ + public record Request( + UUID operationId, + UUID canonicalTenantId, + UUID realmId, + String worldSlug, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String playableStateScope, + UUID canonicalAccountId, + UUID characterId, + UUID entityAssignmentOperationId, + String entityAssignmentDigest, + UUID initialAdmissionHoldId, + UUID initialAdmissionHoldFence, + String initialAdmissionRequestId, + String initialAdmissionRequestDigest, + long catalogRevision, + String initialAdmissionOwnerProofId, + String initialAdmissionOwnerProofDigest, + String pointerAuditId, + long pointerVersion, + InitialAdmissionOrigin initialAdmissionOrigin, + WorldCanonicalInstanceLifecycleEvidence activeLifecycleEvidence) { + public Request { + requireNonNil(operationId, "operationId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireSlug(worldSlug); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope) && !"ISOLATED".equals(playableStateScope)) { + throw invalid("playableStateScope must be SHARED or ISOLATED"); + } + requireNonNil(canonicalAccountId, "canonicalAccountId"); + requireNonNil(characterId, "characterId"); + requireNonNil(entityAssignmentOperationId, "entityAssignmentOperationId"); + requireDigest(entityAssignmentDigest, "entityAssignmentDigest"); + requireNonNil(initialAdmissionHoldId, "initialAdmissionHoldId"); + requireNonNil(initialAdmissionHoldFence, "initialAdmissionHoldFence"); + requireText(initialAdmissionRequestId, 128, "initialAdmissionRequestId"); + requireDigest(initialAdmissionRequestDigest, "initialAdmissionRequestDigest"); + requirePositive(catalogRevision, "catalogRevision"); + requireText(initialAdmissionOwnerProofId, 128, "initialAdmissionOwnerProofId"); + requireDigest(initialAdmissionOwnerProofDigest, "initialAdmissionOwnerProofDigest"); + requireText(pointerAuditId, 128, "pointerAuditId"); + requirePositive(pointerVersion, "pointerVersion"); + Objects.requireNonNull(initialAdmissionOrigin, "initialAdmissionOrigin"); + Objects.requireNonNull(activeLifecycleEvidence, "activeLifecycleEvidence"); + if (!"ACTIVE".equals(activeLifecycleEvidence.lifecycleStatus())) { + throw invalid("initial placement requires exact current ACTIVE World lifecycle evidence"); + } + var lifecycle = activeLifecycleEvidence.request(); + if (!canonicalTenantId.equals(lifecycle.canonicalTenantId()) + || !worldSlug.equals(lifecycle.worldSlug()) + || !canonicalGameInstanceId.equals(lifecycle.canonicalGameInstanceId()) + || !playableStateNamespaceId.equals(lifecycle.playableStateNamespaceId()) + || !playableStateScope.equals(lifecycle.playableStateScope())) { + throw invalid("initial placement scope differs from its complete World lifecycle proof"); + } + } + + public byte[] canonicalRequestBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", REQUEST_SCHEMA); + value.put("operationId", operationId.toString()); + value.put("canonicalTenantId", canonicalTenantId.toString()); + value.put("realmId", realmId.toString()); + value.put("worldSlug", worldSlug); + value.put("canonicalGameInstanceId", canonicalGameInstanceId.toString()); + value.put("playableStateNamespaceId", playableStateNamespaceId.toString()); + value.put("playableStateScope", playableStateScope); + value.put("canonicalAccountId", canonicalAccountId.toString()); + value.put("characterId", characterId.toString()); + value.put("entityAssignmentOperationId", entityAssignmentOperationId.toString()); + value.put("entityAssignmentDigest", entityAssignmentDigest); + value.put("initialAdmissionHoldId", initialAdmissionHoldId.toString()); + value.put("initialAdmissionHoldFence", initialAdmissionHoldFence.toString()); + value.put("initialAdmissionRequestId", initialAdmissionRequestId); + value.put("initialAdmissionRequestDigest", initialAdmissionRequestDigest); + value.put("catalogRevision", Long.toString(catalogRevision)); + value.put("initialAdmissionOrigin", initialAdmissionOrigin.name()); + value.put("initialAdmissionOwnerProofId", initialAdmissionOwnerProofId); + value.put("initialAdmissionOwnerProofDigest", initialAdmissionOwnerProofDigest); + value.put("pointerAuditId", pointerAuditId); + value.put("pointerVersion", Long.toString(pointerVersion)); + try { + value.put("activeLifecycleEvidence", JSON.readTree(normalizedLifecycleEvidenceBytes())); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World initial-location request cannot be encoded", impossible); + } + } + + public String requestDigest() { + return prefixedDigest(canonicalRequestBytes()); + } + + /** Decodes a canonical stored request while retaining its complete original lifecycle proof. */ + public static Request fromStored( + byte[] completeCanonicalRequestBytes, byte[] originalCompleteLifecycleEvidenceBytes) { + Objects.requireNonNull(completeCanonicalRequestBytes, "completeCanonicalRequestBytes"); + Objects.requireNonNull( + originalCompleteLifecycleEvidenceBytes, "originalCompleteLifecycleEvidenceBytes"); + try { + JsonNode root = JSON.readTree(strictUtf8(completeCanonicalRequestBytes)); + requireFields(root, REQUEST_FIELDS, "initial-location request"); + if (!REQUEST_SCHEMA.equals(text(root, "schema"))) { + throw invalid("unsupported initial-location request schema"); + } + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + originalCompleteLifecycleEvidenceBytes); + Request request = + new Request( + canonicalUuid(root, "operationId"), + canonicalUuid(root, "canonicalTenantId"), + canonicalUuid(root, "realmId"), + text(root, "worldSlug"), + canonicalUuid(root, "canonicalGameInstanceId"), + canonicalUuid(root, "playableStateNamespaceId"), + text(root, "playableStateScope"), + canonicalUuid(root, "canonicalAccountId"), + canonicalUuid(root, "characterId"), + canonicalUuid(root, "entityAssignmentOperationId"), + text(root, "entityAssignmentDigest"), + canonicalUuid(root, "initialAdmissionHoldId"), + canonicalUuid(root, "initialAdmissionHoldFence"), + text(root, "initialAdmissionRequestId"), + text(root, "initialAdmissionRequestDigest"), + positiveLong(text(root, "catalogRevision"), "catalogRevision"), + text(root, "initialAdmissionOwnerProofId"), + text(root, "initialAdmissionOwnerProofDigest"), + text(root, "pointerAuditId"), + positiveLong(text(root, "pointerVersion"), "pointerVersion"), + InitialAdmissionOrigin.valueOf(text(root, "initialAdmissionOrigin")), + lifecycleEvidence); + if (!Arrays.equals(completeCanonicalRequestBytes, request.canonicalRequestBytes())) { + throw invalid( + "retained initial-location request is not canonical or differs from evidence"); + } + return request; + } catch (tools.jackson.core.JacksonException | IllegalArgumentException invalid) { + if (invalid instanceof IllegalArgumentException argument + && argument.getMessage() != null + && argument.getMessage().startsWith("INVALID_ARGUMENT:")) { + throw argument; + } + throw invalid("retained initial-location request is invalid", invalid); + } + } + + /** Full source/lifecycle evidence with only the per-read correlation UUID removed. */ + public byte[] originalLifecycleEvidenceBytes() { + return activeLifecycleEvidence.canonicalBytes(); + } + + /** Canonical identity form used to compare fresh reads of the same owner evidence. */ + public byte[] normalizedLifecycleEvidenceBytes() { + return WorldCanonicalInitialPlayerLocation.normalizedLifecycleEvidenceBytes( + activeLifecycleEvidence.canonicalBytes()); + } + } + + /** Immutable result carrier; stored canonical result bytes are preserved on exact replay. */ + public static final class Result { + private final Request request; + private final Outcome outcome; + private final String conflictCode; + private final RoomTemplateRef startLocation; + private final Long runtimeRoomInstanceId; + private final byte[] canonicalBytes; + + private Result( + Request request, + Outcome outcome, + String conflictCode, + RoomTemplateRef startLocation, + Long runtimeRoomInstanceId, + byte[] canonicalBytes) { + this.request = Objects.requireNonNull(request, "request"); + this.outcome = Objects.requireNonNull(outcome, "outcome"); + this.conflictCode = conflictCode; + this.startLocation = startLocation; + this.runtimeRoomInstanceId = runtimeRoomInstanceId; + this.canonicalBytes = Arrays.copyOf(canonicalBytes, canonicalBytes.length); + } + + public static Result applied( + Request request, RoomTemplateRef room, long runtimeRoomInstanceId) { + return create(request, Outcome.APPLIED, null, room, runtimeRoomInstanceId); + } + + public static Result conflict(Request request, String conflictCode) { + requireConflictCode(conflictCode); + return create(request, Outcome.CONFLICT, conflictCode, null, null); + } + + public static Result fromStored(Request request, byte[] storedBytes) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(storedBytes, "storedBytes"); + try { + JsonNode root = + JSON.readTree(new String(storedBytes, java.nio.charset.StandardCharsets.UTF_8)); + requireFields(root, RESULT_FIELDS, "initial-location result"); + if (!RESULT_SCHEMA.equals(text(root, "schema")) + || !request.operationId().toString().equals(text(root, "operationId")) + || !request.requestDigest().equals(text(root, "requestDigest")) + || !Base64.getEncoder() + .encodeToString(request.canonicalRequestBytes()) + .equals(text(root, "requestBytesBase64"))) { + throw invalid("retained initial-location result differs from its exact request"); + } + Outcome outcome = Outcome.valueOf(text(root, "outcome")); + JsonNode conflictNode = root.get("conflictCode"); + String conflict = + conflictNode == null || conflictNode.isNull() ? null : conflictNode.textValue(); + JsonNode roomNode = root.get("startLocation"); + Long runtimeRoom = + root.hasNonNull("runtimeRoomInstanceId") + ? positiveLong(text(root, "runtimeRoomInstanceId"), "runtimeRoomInstanceId") + : null; + RoomTemplateRef room = roomNode == null || roomNode.isNull() ? null : parseRoom(roomNode); + if (outcome == Outcome.APPLIED + ? conflict != null || room == null || runtimeRoom == null + : conflict == null || room != null || runtimeRoom != null) { + throw invalid("retained initial-location result has an invalid outcome shape"); + } + Result result = create(request, outcome, conflict, room, runtimeRoom); + if (!Arrays.equals(storedBytes, result.canonicalBytes())) { + throw invalid("retained initial-location result is not canonical"); + } + return result; + } catch (tools.jackson.core.JacksonException | IllegalArgumentException invalid) { + if (invalid instanceof IllegalArgumentException argument + && argument.getMessage() != null + && argument.getMessage().startsWith("INVALID_ARGUMENT:")) { + throw argument; + } + throw invalid("retained initial-location result is invalid", invalid); + } + } + + public Request request() { + return request; + } + + public String requestDigest() { + return request.requestDigest(); + } + + public Outcome outcome() { + return outcome; + } + + public String conflictCode() { + return conflictCode; + } + + public RoomTemplateRef startLocation() { + return startLocation; + } + + public Long runtimeRoomInstanceId() { + return runtimeRoomInstanceId; + } + + public byte[] canonicalBytes() { + return Arrays.copyOf(canonicalBytes, canonicalBytes.length); + } + + private static Result create( + Request request, + Outcome outcome, + String conflictCode, + RoomTemplateRef room, + Long runtimeRoomInstanceId) { + Objects.requireNonNull(request, "request"); + if (outcome == Outcome.APPLIED) { + if (conflictCode != null + || room == null + || runtimeRoomInstanceId == null + || runtimeRoomInstanceId <= 0) { + throw invalid( + "APPLIED initial-location result requires a typed room and positive runtime room id"); + } + if (!room.equals(request.activeLifecycleEvidence().startLocation()) + || runtimeRoomInstanceId.longValue() + != request.activeLifecycleEvidence().runtimeRoomInstanceId()) { + throw invalid("initial-location result differs from the request's exact V2 ROOM mapping"); + } + } else { + requireConflictCode(conflictCode); + if (room != null || runtimeRoomInstanceId != null) { + throw invalid("CONFLICT initial-location result cannot carry a room mapping"); + } + } + Map value = new LinkedHashMap<>(); + value.put("schema", RESULT_SCHEMA); + value.put("operationId", request.operationId().toString()); + value.put("requestDigest", request.requestDigest()); + value.put( + "requestBytesBase64", + Base64.getEncoder().encodeToString(request.canonicalRequestBytes())); + value.put("outcome", outcome.name()); + value.put("conflictCode", conflictCode); + value.put("startLocation", room == null ? null : roomJson(room)); + value.put( + "runtimeRoomInstanceId", + runtimeRoomInstanceId == null ? null : runtimeRoomInstanceId.toString()); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return new Result(request, outcome, conflictCode, room, runtimeRoomInstanceId, bytes); + } catch (IOException impossible) { + throw new IllegalStateException( + "World initial-location result cannot be encoded", impossible); + } + } + } + + private static void requireConflictCode(String value) { + requireText(value, 64, "conflictCode"); + if (!value.matches("[A-Z][A-Z0-9_]{0,63}")) { + throw invalid("conflictCode must be an uppercase ASCII machine code"); + } + } + + private static Map roomJson(RoomTemplateRef room) { + Map value = new LinkedHashMap<>(); + value.put("tenantId", room.tenantId().toString()); + value.put("versionId", room.versionId().toString()); + value.put("roomTemplateId", room.roomTemplateId().toString()); + return value; + } + + /** Removes only the lifecycle read correlation UUID while preserving the complete proof. */ + public static byte[] normalizedLifecycleEvidenceBytes(byte[] evidenceBytes) { + Objects.requireNonNull(evidenceBytes, "evidenceBytes"); + try { + JsonNode evidence = JSON.readTree(evidenceBytes); + JsonNode requestNode = evidence == null ? null : evidence.get("request"); + if (evidence == null + || !evidence.isObject() + || !(requestNode instanceof ObjectNode request)) { + throw invalid("World lifecycle evidence must contain its complete request object"); + } + JsonNode readRequestId = request.get("readRequestId"); + if (readRequestId == null || !readRequestId.isTextual()) { + throw invalid("World lifecycle evidence must contain its read correlation UUID"); + } + request.remove("readRequestId"); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(evidence)); + } catch (IOException invalid) { + throw invalid("World lifecycle evidence cannot be normalized", invalid); + } + } + + private static RoomTemplateRef parseRoom(JsonNode node) { + requireFields(node, ROOM_FIELDS, "startLocation"); + return new RoomTemplateRef( + UUID.fromString(text(node, "tenantId")), + UUID.fromString(text(node, "versionId")), + UUID.fromString(text(node, "roomTemplateId"))); + } + + private static void requireFields(JsonNode node, Set fields, String label) { + if (node == null || !node.isObject() || node.size() != fields.size()) { + throw invalid(label + " must be a closed object"); + } + node.propertyNames() + .forEach( + field -> { + if (!fields.contains(field)) throw invalid(label + " contains an unknown field"); + }); + } + + private static String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) throw invalid(field + " must be text"); + return value.textValue(); + } + + private static UUID canonicalUuid(JsonNode node, String field) { + String value = text(node, field); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) throw new IllegalArgumentException(); + return parsed; + } catch (IllegalArgumentException invalid) { + throw invalid(field + " must be a canonical UUID", invalid); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw invalid("stored initial-location request is not valid UTF-8", invalid); + } + } + + private static long positiveLong(String value, String label) { + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) throw new NumberFormatException(); + return parsed; + } catch (NumberFormatException invalid) { + throw invalid(label + " must be a canonical positive signed-64-bit integer", invalid); + } + } + + private static String prefixedDigest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) throw invalid(label + " must be a non-nil UUID"); + } + + private static void requireSlug(String value) { + requireText(value, 120, "worldSlug"); + if (!value.matches("[a-z0-9]+(-[a-z0-9]+)*")) throw invalid("worldSlug is not canonical"); + } + + private static void requireText(String value, int max, String label) { + if (value == null + || value.isBlank() + || value.length() > max + || value.chars().anyMatch(Character::isISOControl)) + throw invalid(label + " is required and bounded"); + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) + throw invalid(label + " must be lowercase SHA-256"); + } + + private static void requirePositive(long value, String label) { + if (value <= 0) throw invalid(label + " must be positive"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException("INVALID_ARGUMENT: " + message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException("INVALID_ARGUMENT: " + message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceActivation.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceActivation.java new file mode 100644 index 0000000000..69ef500a82 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceActivation.java @@ -0,0 +1,251 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable operation identity and result for the default-denied canonical World activation cut. + */ +public final class WorldCanonicalInstanceActivation { + private static final String REQUEST_SCHEMA = "world-canonical-instance-activation-request/v1"; + private static final String RESULT_SCHEMA = "world-canonical-instance-activation-result/v1"; + private static final Set RESULT_FIELDS = + Set.of( + "schema", + "activationRequestId", + "requestDigest", + "requestBytesBase64", + "preparingEvidenceBytesBase64", + "outcome", + "terminalCode", + "lifecycleEvidenceBytesBase64"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private WorldCanonicalInstanceActivation() {} + + /** + * Stable operation identity. The nested World lifecycle read UUID is correlation metadata and is + * excluded from {@link #canonicalRequestBytes()}, while the original complete proof remains in + * {@link #preparingEvidenceBytes()} and the immutable operation result. + */ + public record Request( + UUID activationRequestId, WorldCanonicalInstanceLifecycleEvidence preparing) { + public Request { + requireNonNil(activationRequestId, "activationRequestId"); + Objects.requireNonNull(preparing, "preparing"); + if (!"PREPARING".equals(preparing.lifecycleStatus())) { + throw new IllegalArgumentException( + "Canonical activation requires exact PREPARING evidence"); + } + } + + public UUID canonicalGameInstanceId() { + return preparing.request().canonicalGameInstanceId(); + } + + public long expectedLifecycleEpoch() { + return preparing.lifecycleEpoch(); + } + + public long expectedRowVersion() { + return preparing.rowVersion(); + } + + /** Canonical operation bytes omit only the transport lifecycle-read UUID. */ + public byte[] canonicalRequestBytes() { + try { + JsonNode evidence = JSON.readTree(preparing.canonicalBytes()); + JsonNode lifecycleRequest = evidence.path("request"); + if (!lifecycleRequest.isObject()) { + throw new IllegalArgumentException("Canonical PREPARING proof has no closed request"); + } + ((tools.jackson.databind.node.ObjectNode) lifecycleRequest).remove("readRequestId"); + Map request = new LinkedHashMap<>(); + request.put("schema", REQUEST_SCHEMA); + request.put("activationRequestId", activationRequestId.toString()); + request.put("preparingEvidence", evidence); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(request)); + } catch (IOException invalid) { + throw new IllegalArgumentException("Canonical activation request is invalid", invalid); + } + } + + public byte[] preparingEvidenceBytes() { + return preparing.canonicalBytes(); + } + + public String requestDigest() { + return digest(canonicalRequestBytes()); + } + } + + public enum Outcome { + COMMITTED, + ABORTED + } + + /** Immutable success or terminal stale-precondition outcome; ABORTED never grants admission. */ + public record Result( + Request request, + Outcome outcome, + String terminalCode, + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence) { + public Result { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(outcome, "outcome"); + Objects.requireNonNull(lifecycleEvidence, "lifecycleEvidence"); + if (!request.preparing().request().equals(lifecycleEvidence.request())) { + throw new IllegalArgumentException( + "Canonical activation result differs from its original lifecycle-read request"); + } + if (outcome == Outcome.COMMITTED) { + if (terminalCode != null + || !"ACTIVE".equals(lifecycleEvidence.lifecycleStatus()) + || lifecycleEvidence.lifecycleEpoch() + != Math.addExact(request.expectedLifecycleEpoch(), 1L) + || lifecycleEvidence.rowVersion() != Math.addExact(request.expectedRowVersion(), 1L)) { + throw new IllegalArgumentException( + "Committed activation result is not the exact next ACTIVE state"); + } + } else if (terminalCode == null || terminalCode.isBlank()) { + throw new IllegalArgumentException("Aborted activation result requires a terminal code"); + } + } + + public byte[] canonicalBytes() { + Map result = new LinkedHashMap<>(); + result.put("schema", RESULT_SCHEMA); + result.put("activationRequestId", request.activationRequestId().toString()); + result.put("requestDigest", request.requestDigest()); + result.put( + "requestBytesBase64", + Base64.getEncoder().encodeToString(request.canonicalRequestBytes())); + result.put( + "preparingEvidenceBytesBase64", + Base64.getEncoder().encodeToString(request.preparingEvidenceBytes())); + result.put("outcome", outcome.name()); + result.put("terminalCode", terminalCode); + result.put( + "lifecycleEvidenceBytesBase64", + Base64.getEncoder().encodeToString(lifecycleEvidence.canonicalBytes())); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(result)); + } catch (IOException impossible) { + throw new IllegalStateException( + "Canonical activation result cannot be encoded", impossible); + } + } + + public static Result fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(stored)) + .toString(); + JsonNode root = JSON.readTree(json); + requireFields(root, RESULT_FIELDS, "Canonical World activation result"); + if (!RESULT_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported canonical activation result schema"); + } + UUID activationId = UUID.fromString(text(root, "activationRequestId")); + WorldCanonicalInstanceLifecycleEvidence preparing = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + decodeBase64(root, "preparingEvidenceBytesBase64")); + Request request = new Request(activationId, preparing); + if (!request.requestDigest().equals(text(root, "requestDigest")) + || !Arrays.equals( + request.canonicalRequestBytes(), decodeBase64(root, "requestBytesBase64"))) { + throw new IllegalArgumentException("Stored activation request digest or bytes differ"); + } + Outcome outcome = Outcome.valueOf(text(root, "outcome")); + JsonNode terminal = root.get("terminalCode"); + if (terminal != null && !terminal.isNull() && !terminal.isTextual()) { + throw new IllegalArgumentException("Stored activation terminalCode must be text or null"); + } + String terminalCode = terminal == null || terminal.isNull() ? null : terminal.textValue(); + Result result = + new Result( + request, + outcome, + terminalCode, + WorldCanonicalInstanceLifecycleEvidence.fromStored( + decodeBase64(root, "lifecycleEvidenceBytesBase64"))); + if (!Arrays.equals(stored, result.canonicalBytes())) { + throw new IllegalArgumentException("Stored canonical activation result is not canonical"); + } + return result; + } catch (IOException invalid) { + throw new IllegalArgumentException( + "Stored canonical activation result is invalid", invalid); + } + } + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static byte[] decodeBase64(JsonNode node, String field) { + try { + return Base64.getDecoder().decode(text(node, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Stored activation " + field + " is invalid", invalid); + } + } + + private static String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Stored activation " + field + " must be text"); + } + return value.textValue(); + } + + private static void requireFields(JsonNode node, Set fields, String label) { + if (node == null || !node.isObject() || node.size() != fields.size()) { + throw new IllegalArgumentException(label + " has an invalid closed object shape"); + } + for (String name : node.propertyNames()) { + if (!fields.contains(name)) { + throw new IllegalArgumentException(label + " has an unknown field"); + } + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(label + " must be non-nil"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java new file mode 100644 index 0000000000..33aef52809 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.world; + +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.WorldCanonicalInstanceLifecycleReadServiceGrpc; + +/** Explicit mTLS client for the exact World canonical instance lifecycle read. */ +public final class WorldCanonicalInstanceLifecycleClient + extends AbstractReloadingBlockingGrpcClient< + WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldCanonicalInstanceLifecycleClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldCanonicalInstanceLifecycleClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Game Session service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World canonical lifecycle client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World canonical lifecycle client has no gRPC stub"); + } + initialized = true; + } + + /** Reads and validates World-owned lifecycle evidence for this exact canonical request. */ + public WorldCanonicalInstanceLifecycleEvidence read( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World canonical lifecycle request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldCanonicalInstanceLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request)); + try { + return WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid canonical instance lifecycle evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldCanonicalInstanceLifecycleReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World canonical lifecycle client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World canonical lifecycle read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World canonical lifecycle read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World canonical lifecycle read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World canonical lifecycle read " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World canonical lifecycle read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java new file mode 100644 index 0000000000..6ad7be6478 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java @@ -0,0 +1,555 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact, non-admitting World lifecycle owner readback for an authenticated canonical caller. + * + *

Decoding this carrier does not authenticate World, establish current Account authority, or + * grant lifecycle activation or gameplay admission. The transport endpoint owns workload + * authentication; the consumer must keep admission and its current-authority checks separate. + */ +public record WorldCanonicalInstanceLifecycleEvidence( + Request request, + CompleteLaunchBindingEvidence launchBinding, + RoomTemplateRef startLocation, + long runtimeRoomInstanceId, + String lifecycleStatus, + long lifecycleEpoch, + long rowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest, + Map operationalRegionAssignments) { + public static final String SCHEMA = "world-canonical-instance-lifecycle-evidence/v1"; + public static final String REQUEST_SCHEMA = "world-canonical-instance-lifecycle-read-request/v1"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern PREFIXED_SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern BARE_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set EVIDENCE_FIELDS = + Set.of( + "schema", + "request", + "launchBindingBytesBase64", + "startLocation", + "runtimeRoomInstanceId", + "lifecycleStatus", + "lifecycleEpoch", + "rowVersion", + "captureId", + "graphSha256", + "preparationInputDigest", + "operationalRegionAssignments"); + private static final Set REQUEST_FIELDS = + Set.of( + "schemaVersion", + "readRequestId", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "canonicalGameInstanceId", + "playableStateNamespaceId", + "playableStateScope", + "publicProduction", + "controlPlaneRequestId", + "canonicalVersionId", + "expectedDescriptorRequestDigest", + "expectedDescriptorResultDigest", + "expectedReleaseAttestationDigest"); + private static final Set REQUEST_ENVELOPE_FIELDS = Set.of("schema", "request"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final Set LIFECYCLE_STATUSES = + Set.of("PREPARING", "ACTIVE", "FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + + public WorldCanonicalInstanceLifecycleEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(launchBinding, "launchBinding"); + Objects.requireNonNull(startLocation, "startLocation"); + if (runtimeRoomInstanceId <= 0) { + throw new IllegalArgumentException("runtimeRoomInstanceId must be positive"); + } + if (lifecycleStatus == null || !LIFECYCLE_STATUSES.contains(lifecycleStatus)) { + throw new IllegalArgumentException("Unsupported World lifecycle status"); + } + if (lifecycleEpoch <= 0) { + throw new IllegalArgumentException("World lifecycleEpoch must be positive"); + } + if (rowVersion < 0) { + throw new IllegalArgumentException("World lifecycle rowVersion must be nonnegative"); + } + requireNonNil(captureId, "captureId"); + requireDigest(graphSha256, BARE_SHA256, "graphSha256"); + requireDigest(preparationInputDigest, PREFIXED_SHA256, "preparationInputDigest"); + operationalRegionAssignments = + immutableOperationalRegionAssignments(operationalRegionAssignments); + requireExactBinding(request, launchBinding, startLocation, graphSha256); + } + + /** Returns an immutable ordered copy without exposing the retained map representation. */ + @Override + public Map operationalRegionAssignments() { + return Collections.unmodifiableMap(new LinkedHashMap<>(operationalRegionAssignments)); + } + + /** Closed canonical representation with the complete descriptor and separate attestation. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("request", requestJson(request)); + value.put( + "launchBindingBytesBase64", + Base64.getEncoder().encodeToString(closedLaunchBindingBytes(launchBinding))); + value.put("startLocation", roomTemplateRefJson(startLocation)); + value.put("runtimeRoomInstanceId", Long.toString(runtimeRoomInstanceId)); + value.put("lifecycleStatus", lifecycleStatus); + value.put("lifecycleEpoch", Long.toString(lifecycleEpoch)); + value.put("rowVersion", Long.toString(rowVersion)); + value.put("captureId", captureId.toString()); + value.put("graphSha256", graphSha256); + value.put("preparationInputDigest", preparationInputDigest); + value.put( + "operationalRegionAssignments", + operationalRegionAssignmentsJson(operationalRegionAssignments)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World canonical lifecycle evidence cannot be encoded", impossible); + } + } + + /** Decodes closed retained bytes; this does not authenticate the producing World workload. */ + public static WorldCanonicalInstanceLifecycleEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, EVIDENCE_FIELDS, "World canonical lifecycle evidence"); + if (!SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported World canonical lifecycle evidence schema"); + } + Request request = parseRequest(root.get("request")); + CompleteLaunchBindingEvidence launchBinding = + parseLaunchBinding(base64(root, "launchBindingBytesBase64")); + WorldCanonicalInstanceLifecycleEvidence evidence = + new WorldCanonicalInstanceLifecycleEvidence( + request, + launchBinding, + parseRoomTemplateRef(root.get("startLocation")), + positiveLong(text(root, "runtimeRoomInstanceId"), "runtimeRoomInstanceId"), + text(root, "lifecycleStatus"), + positiveLong(text(root, "lifecycleEpoch"), "lifecycleEpoch"), + nonNegativeLong(text(root, "rowVersion"), "rowVersion"), + parseUuid(text(root, "captureId"), "captureId"), + text(root, "graphSha256"), + text(root, "preparationInputDigest"), + parseOperationalRegionAssignments(root.get("operationalRegionAssignments"))); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("World canonical lifecycle evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World canonical lifecycle evidence is invalid", invalid); + } + } + + private static void requireExactBinding( + Request request, + CompleteLaunchBindingEvidence binding, + RoomTemplateRef startLocation, + String graphSha256) { + AuthoredWorldLaunchDescriptorEvidence descriptor = binding.descriptor(); + AuthoredWorldReleaseAttestationEvidence release = binding.releaseAttestation(); + descriptor.requireValid(); + release.requireValid(descriptor); + if (!request.targetNamespace().equals(descriptor.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.worldSlug().equals(descriptor.worldSlug()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request.expectedReleaseAttestationDigest().equals(release.evidenceDigest()) + || !request.canonicalVersionId().equals(release.canonicalVersionId())) { + throw new IllegalArgumentException( + "World lifecycle request differs from the complete launch binding"); + } + if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || release.worldStartLocationEvidence() == null) { + throw new IllegalArgumentException( + "World lifecycle evidence requires the complete selector/v2 release attestation"); + } + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored( + release.worldStartLocationEvidence().selectorReceiptBytes()); + String selectedGraphSha256 = selectorReceipt.graphDigest().substring("sha256:".length()); + if (!selectorReceipt.startLocation().equals(startLocation) + || !selectedGraphSha256.equals(graphSha256)) { + throw new IllegalArgumentException( + "World lifecycle ROOM selector or graph digest differs from the complete release selector"); + } + } + + private static byte[] closedLaunchBindingBytes(CompleteLaunchBindingEvidence binding) { + try { + // Preserve every original descriptor/release value, including long numeric fields, inside + // the opaque outer base64 envelope instead of subjecting those owner bytes to RFC 8785's + // JavaScript-number range. + return JSON.writeValueAsString(binding).getBytes(StandardCharsets.UTF_8); + } catch (tools.jackson.core.JacksonException impossible) { + throw new IllegalStateException("Complete launch binding cannot be encoded", impossible); + } + } + + private static CompleteLaunchBindingEvidence parseLaunchBinding(byte[] stored) { + try { + JsonNode node = JSON.readTree(strictUtf8(stored)); + requireFields(node, Set.of("descriptor", "releaseAttestation"), "complete launch binding"); + CompleteLaunchBindingEvidence binding = + JSON.treeToValue(node, CompleteLaunchBindingEvidence.class); + if (!Arrays.equals(stored, closedLaunchBindingBytes(binding))) { + throw new IllegalArgumentException( + "Nested complete launch binding bytes are not canonical"); + } + return binding; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException( + "Nested complete launch binding bytes are invalid", invalid); + } + } + + private static Request parseRequest(JsonNode node) { + requireFields(node, REQUEST_FIELDS, "World canonical lifecycle request"); + JsonNode publicProduction = node.get("publicProduction"); + if (publicProduction == null || !publicProduction.isBoolean()) { + throw new IllegalArgumentException("publicProduction must be present as a boolean"); + } + return new Request( + intValue(node, "schemaVersion"), + parseUuid(text(node, "readRequestId"), "readRequestId"), + text(node, "targetNamespace"), + parseUuid(text(node, "canonicalTenantId"), "canonicalTenantId"), + text(node, "worldSlug"), + parseUuid(text(node, "canonicalGameInstanceId"), "canonicalGameInstanceId"), + parseUuid(text(node, "playableStateNamespaceId"), "playableStateNamespaceId"), + text(node, "playableStateScope"), + publicProduction.booleanValue(), + text(node, "controlPlaneRequestId"), + parseUuid(text(node, "canonicalVersionId"), "canonicalVersionId"), + text(node, "expectedDescriptorRequestDigest"), + text(node, "expectedDescriptorResultDigest"), + text(node, "expectedReleaseAttestationDigest")); + } + + private static RoomTemplateRef parseRoomTemplateRef(JsonNode node) { + requireFields(node, ROOM_TEMPLATE_REF_FIELDS, "World lifecycle startLocation"); + return new RoomTemplateRef( + parseUuid(text(node, "tenantId"), "startLocation.tenantId"), + parseUuid(text(node, "versionId"), "startLocation.versionId"), + parseUuid(text(node, "roomTemplateId"), "startLocation.roomTemplateId")); + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("schemaVersion", request.schemaVersion()); + value.put("readRequestId", request.readRequestId().toString()); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("worldSlug", request.worldSlug()); + value.put("canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + value.put("playableStateNamespaceId", request.playableStateNamespaceId().toString()); + value.put("playableStateScope", request.playableStateScope()); + value.put("publicProduction", request.publicProduction()); + value.put("controlPlaneRequestId", request.controlPlaneRequestId()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("expectedDescriptorRequestDigest", request.expectedDescriptorRequestDigest()); + value.put("expectedDescriptorResultDigest", request.expectedDescriptorResultDigest()); + value.put("expectedReleaseAttestationDigest", request.expectedReleaseAttestationDigest()); + return value; + } + + private static Map roomTemplateRefJson(RoomTemplateRef reference) { + Map value = new LinkedHashMap<>(); + value.put("tenantId", reference.tenantId().toString()); + value.put("versionId", reference.versionId().toString()); + value.put("roomTemplateId", reference.roomTemplateId().toString()); + return value; + } + + private static Map operationalRegionAssignmentsJson(Map assignments) { + Map value = new LinkedHashMap<>(); + assignments.entrySet().stream() + .sorted((left, right) -> left.getKey().toString().compareTo(right.getKey().toString())) + .forEach(entry -> value.put(entry.getKey().toString(), entry.getValue().toString())); + return value; + } + + private static Map parseOperationalRegionAssignments(JsonNode node) { + if (node == null || !node.isObject() || node.size() == 0) { + throw new IllegalArgumentException("operationalRegionAssignments must be a nonempty object"); + } + Map assignments = new LinkedHashMap<>(); + node.propertyNames() + .forEach( + canonicalRegionId -> { + JsonNode operationalRegion = node.get(canonicalRegionId); + if (operationalRegion == null || !operationalRegion.isTextual()) { + throw new IllegalArgumentException( + "operationalRegionAssignments values must be canonical UUID strings"); + } + UUID canonical = parseUuid(canonicalRegionId, "operationalRegionAssignments key"); + UUID operational = + parseUuid(operationalRegion.textValue(), "operationalRegionAssignments value"); + if (assignments.putIfAbsent(canonical, operational) != null) { + throw new IllegalArgumentException( + "operationalRegionAssignments contains duplicate canonical region identities"); + } + }); + return immutableOperationalRegionAssignments(assignments); + } + + private static Map immutableOperationalRegionAssignments( + Map assignments) { + Objects.requireNonNull(assignments, "operationalRegionAssignments"); + if (assignments.isEmpty()) { + throw new IllegalArgumentException("operationalRegionAssignments must be nonempty"); + } + assignments.forEach( + (canonical, operational) -> { + requireNonNil(canonical, "operationalRegionAssignments canonical region ID"); + requireNonNil(operational, "operationalRegionAssignments operational region ID"); + }); + Map ordered = new LinkedHashMap<>(); + Set operationalIdentities = new HashSet<>(); + assignments.entrySet().stream() + .sorted((left, right) -> left.getKey().toString().compareTo(right.getKey().toString())) + .forEach( + entry -> { + UUID canonical = entry.getKey(); + UUID operational = entry.getValue(); + if (canonical.equals(operational)) { + throw new IllegalArgumentException( + "Canonical and operational region identities must be distinct"); + } + if (!operationalIdentities.add(operational)) { + throw new IllegalArgumentException( + "operationalRegionAssignments contains duplicate operational region identities"); + } + ordered.put(canonical, operational); + }); + return Collections.unmodifiableMap(ordered); + } + + private static byte[] base64(JsonNode node, String field) { + try { + return Base64.getDecoder().decode(text(node, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid base64 field " + field, invalid); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + return value.textValue(); + } + + private static int intValue(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException(field + " must be an integer"); + } + return value.intValue(); + } + + private static long positiveLong(String value, String field) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static long nonNegativeLong(String value, String field) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical nonnegative decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "Canonical World lifecycle bytes are not strict UTF-8", invalid); + } + } + + private static UUID parseUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static void 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, Pattern pattern, String label) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is not a canonical SHA-256 digest"); + } + } + + private static void requireFields(JsonNode object, Set fields, String label) { + if (object == null || !object.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + Set actual = new java.util.HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + /** Exact shared request envelope for the read-only World lifecycle capture. */ + public record Request( + int schemaVersion, + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String playableStateScope, + boolean publicProduction, + String controlPlaneRequestId, + UUID canonicalVersionId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationDigest) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World canonical lifecycle read schema"); + } + requireNonNil(readRequestId, "readRequestId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "This lifecycle carrier accepts SHARED scope only; private/playtest proof is unavailable"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "This lifecycle carrier requires public-production evidence"); + } + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireDigest( + expectedDescriptorRequestDigest, PREFIXED_SHA256, "expectedDescriptorRequestDigest"); + requireDigest( + expectedDescriptorResultDigest, PREFIXED_SHA256, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationDigest, PREFIXED_SHA256, "expectedReleaseAttestationDigest"); + } + + /** Closed canonical request bytes used by the standalone World read RPC. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", REQUEST_SCHEMA); + value.put("request", requestJson(this)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World canonical lifecycle request cannot be encoded", impossible); + } + } + + /** Decodes only a complete closed request; this does not authenticate its sender. */ + public static Request fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root, REQUEST_ENVELOPE_FIELDS, "World canonical lifecycle read request"); + if (!REQUEST_SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException( + "Unsupported World canonical lifecycle request schema"); + } + Request request = parseRequest(root.get("request")); + if (!Arrays.equals(stored, request.canonicalBytes())) { + throw new IllegalArgumentException("World canonical lifecycle request is not canonical"); + } + return request; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World canonical lifecycle request is invalid", invalid); + } + } + + private static void requireText(String value, String label, int maxLength) { + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(label + " is required and must fit its limit"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java new file mode 100644 index 0000000000..9caf305d68 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleGrpcCodec.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; + +/** Closed byte-carrier mapping for the authenticated, read-only World lifecycle RPC. */ +public final class WorldCanonicalInstanceLifecycleGrpcCodec { + private WorldCanonicalInstanceLifecycleGrpcCodec() {} + + /** Encodes the complete closed request as one canonical byte value. */ + public static ReadWorldCanonicalInstanceLifecycleRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + return ReadWorldCanonicalInstanceLifecycleRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFrom(request.canonicalBytes())) + .build(); + } + + /** Decodes only after the World receiver authenticates its exact same-namespace caller. */ + public static Request fromRequest(ReadWorldCanonicalInstanceLifecycleRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadWorldCanonicalInstanceLifecycleRequest"); + if (request.getCanonicalRequestBytes().isEmpty()) { + throw new IllegalArgumentException("World canonical lifecycle request bytes are required"); + } + return Request.fromStored(request.getCanonicalRequestBytes().toByteArray()); + } + + /** Encodes a complete response only when it contains the exact immutable caller request. */ + public static ReadWorldCanonicalInstanceLifecycleResponse toResponse( + Request request, WorldCanonicalInstanceLifecycleEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "World lifecycle evidence differs from exact read request"); + } + return ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(evidence.canonicalBytes())) + .build(); + } + + /** Validates the complete closed response and its exact request echo. */ + public static WorldCanonicalInstanceLifecycleEvidence fromResponse( + Request request, ReadWorldCanonicalInstanceLifecycleResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldCanonicalInstanceLifecycleResponse"); + if (response.getCanonicalResponseBytes().isEmpty()) { + throw new IllegalArgumentException("World canonical lifecycle response bytes are required"); + } + WorldCanonicalInstanceLifecycleEvidence evidence = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + response.getCanonicalResponseBytes().toByteArray()); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException("World lifecycle response changed exact read request"); + } + return evidence; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java new file mode 100644 index 0000000000..d3f440a6b6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidence.java @@ -0,0 +1,286 @@ +package net.firedevops.firemud.common.world; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Closed, canonical World evidence for the original authored start-location selector. */ +public record WorldDraftStartLocationEvidence( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID authorizationFenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef startLocation, + String graphDigest, + String receiptDigest) { + public static final String SCHEMA = "world-draft-start-location-receipt/v1"; + + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Set FIELDS = + Set.of( + "schema", + "targetNamespace", + "operationId", + "requestId", + "commitId", + "authorizationFenceId", + "accountBindingDigest", + "bindingDigest", + "startLocation", + "graphDigest", + "receiptDigest"); + private static final Set ROOM_TEMPLATE_REF_FIELDS = + Set.of("tenantId", "versionId", "roomTemplateId"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldDraftStartLocationEvidence { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + requireCanonicalNonNilUuid(operationId, "operationId"); + requireCanonicalNonNilUuid(requestId, "requestId"); + requireCanonicalNonNilUuid(commitId, "commitId"); + requireCanonicalNonNilUuid(authorizationFenceId, "authorizationFenceId"); + requireDigest(accountBindingDigest, "accountBindingDigest"); + requireDigest(bindingDigest, "bindingDigest"); + Objects.requireNonNull(startLocation, "startLocation"); + requireDigest(graphDigest, "graphDigest"); + requireDigest(receiptDigest, "receiptDigest"); + if (!receiptDigest.equals( + computeReceiptDigest( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest))) { + throw new IllegalArgumentException("World start-location receipt digest is invalid"); + } + } + + /** Creates the one canonical representation from the complete original receipt fields. */ + public static WorldDraftStartLocationEvidence create( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID authorizationFenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef startLocation, + String graphDigest) { + return new WorldDraftStartLocationEvidence( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest, + computeReceiptDigest( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest)); + } + + /** + * Decodes a complete canonical receipt and verifies its closed fields and digest. This does not + * authenticate the producer or prove the receipt's Account-bound meaning. + */ + public static WorldDraftStartLocationEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(stored)) + .toString(); + JsonNode value = JSON.readTree(json); + requireFields(value, FIELDS, "World start-location receipt"); + if (!SCHEMA.equals(text(value, "schema"))) { + throw new IllegalArgumentException("Unsupported World start-location receipt schema"); + } + JsonNode selector = value.get("startLocation"); + requireFields(selector, ROOM_TEMPLATE_REF_FIELDS, "World start-location selector"); + var evidence = + new WorldDraftStartLocationEvidence( + text(value, "targetNamespace"), + parseCanonicalNonNilUuid(text(value, "operationId"), "operationId"), + parseCanonicalNonNilUuid(text(value, "requestId"), "requestId"), + parseCanonicalNonNilUuid(text(value, "commitId"), "commitId"), + parseCanonicalNonNilUuid(text(value, "authorizationFenceId"), "authorizationFenceId"), + text(value, "accountBindingDigest"), + text(value, "bindingDigest"), + new RoomTemplateRef( + parseCanonicalNonNilUuid(text(selector, "tenantId"), "selector tenantId"), + parseCanonicalNonNilUuid(text(selector, "versionId"), "selector versionId"), + parseCanonicalNonNilUuid( + text(selector, "roomTemplateId"), "selector roomTemplateId")), + text(value, "graphDigest"), + text(value, "receiptDigest")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("World start-location receipt is not canonical"); + } + return evidence; + } catch (IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World start-location receipt is invalid", invalid); + } + } + + /** Returns the exact canonical receipt bytes retained by World. */ + public byte[] canonicalBytes() { + Map selector = new LinkedHashMap<>(); + selector.put("tenantId", startLocation.tenantId().toString()); + selector.put("versionId", startLocation.versionId().toString()); + selector.put("roomTemplateId", startLocation.roomTemplateId().toString()); + Map json = new LinkedHashMap<>(); + json.put("schema", SCHEMA); + json.put("targetNamespace", targetNamespace); + json.put("operationId", operationId.toString()); + json.put("requestId", requestId.toString()); + json.put("commitId", commitId.toString()); + json.put("authorizationFenceId", authorizationFenceId.toString()); + json.put("accountBindingDigest", accountBindingDigest); + json.put("bindingDigest", bindingDigest); + json.put("startLocation", selector); + json.put("graphDigest", graphDigest); + json.put("receiptDigest", receiptDigest); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(json)); + } catch (IOException impossible) { + throw new IllegalStateException("World start-location receipt cannot be encoded", impossible); + } + } + + private static String computeReceiptDigest( + String namespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef selector, + String graphDigest) { + Objects.requireNonNull(namespace, "targetNamespace"); + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(commitId, "commitId"); + Objects.requireNonNull(fenceId, "authorizationFenceId"); + Objects.requireNonNull(accountBindingDigest, "accountBindingDigest"); + Objects.requireNonNull(bindingDigest, "bindingDigest"); + Objects.requireNonNull(selector, "startLocation"); + Objects.requireNonNull(graphDigest, "graphDigest"); + ByteArrayOutputStream framed = new ByteArrayOutputStream(); + for (String segment : + new String[] { + SCHEMA, + namespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + selector.tenantId().toString(), + selector.versionId().toString(), + selector.roomTemplateId().toString(), + graphDigest + }) { + byte[] bytes = segment.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(framed.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static void requireCanonicalNonNilUuid(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireFields(JsonNode value, Set expected, String label) { + if (value == null || !value.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + if (value.size() != expected.size() + || value.properties().stream().anyMatch(entry -> !expected.contains(entry.getKey()))) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + private static String text(JsonNode value, String field) { + JsonNode child = value.get(field); + if (child == null || !child.isTextual()) { + throw new IllegalArgumentException( + "World start-location receipt field " + field + " is invalid"); + } + return child.textValue(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClient.java new file mode 100644 index 0000000000..5b59a148f1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClient.java @@ -0,0 +1,182 @@ +package net.firedevops.firemud.common.world; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +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.WorldPublishedSpawnRequirementsReadServiceGrpc; + +/** + * Explicit file-backed mTLS client for immutable World published spawn-requirement source reads. + */ +public final class WorldPublishedSpawnRequirementsClient + extends AbstractReloadingBlockingGrpcClient< + WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final String ENTITY_SERVICE = "entity-management-service"; + private static final String WORLD_SERVICE = "world-management-service"; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldPublishedSpawnRequirementsClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireEntityMtls(tlsProperties, workloadNamespace), + channelFactory, + WorldPublishedSpawnRequirementsClient.class); + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Entity service explicitly starts this opt-in client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World spawn-requirements client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World spawn-requirements client has no gRPC stub"); + } + initialized = true; + } + + /** Reads and validates the complete immutable source evidence for one exact selector. */ + public WorldPublishedSpawnRequirementsEvidence read( + WorldPublishedSpawnRequirementsEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World spawn-requirements request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldPublishedSpawnRequirements( + WorldPublishedSpawnRequirementsGrpcCodec.toRequest(request)); + try { + return WorldPublishedSpawnRequirementsGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid published spawn-requirements evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/" + WORLD_SERVICE; + return WorldPublishedSpawnRequirementsReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World spawn-requirements client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireEntityMtls( + CommonGrpcClientProperties tlsProperties, String workloadNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World spawn-requirements reads require workload mTLS"); + } + Path certificatePath = requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + requireExactEntityCertificate(certificatePath, workloadNamespace); + return tlsProperties; + } + + private static Path requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World spawn-requirements reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World spawn-requirements reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World spawn-requirements " + label + " must be a readable file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World spawn-requirements " + label + " must be an existing readable file"); + } + return path; + } + + private static void requireExactEntityCertificate(Path certificatePath, String namespace) { + try (InputStream input = Files.newInputStream(certificatePath)) { + X509Certificate certificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + String expectedUri = "spiffe://firemud/ns/" + namespace + "/sa/" + ENTITY_SERVICE; + if (GrpcPeerIdentity.fromCertificate(certificate) + .filter(identity -> identity.uri().equals(expectedUri)) + .isEmpty()) { + throw new IllegalArgumentException( + "World spawn-requirements client certificate must be the exact same-namespace Entity workload identity"); + } + } catch (IOException | CertificateException invalid) { + throw new IllegalArgumentException( + "World spawn-requirements client certificate must contain an exact Entity workload identity", + invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java new file mode 100644 index 0000000000..4cfb655ea6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java @@ -0,0 +1,341 @@ +package net.firedevops.firemud.common.world; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; + +/** Exact immutable published spawn and generation inputs retained from one World source read. */ +public record WorldPublishedSpawnRequirementsEvidence( + Request request, + CompleteLaunchBindingEvidence launchBinding, + UUID captureId, + String graphDigest, + List familyCounts, + List spawnRequirements, + List generationRequirements) { + public static final int SCHEMA_VERSION = 1; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern CANONICAL_DECIMAL = Pattern.compile("0|[1-9][0-9]*"); + private static final List FAMILY_ORDER = + List.of( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING); + + /** Exact source-read selector. The nested Game Design request remains unchanged. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf request messages are immutable value messages.") + public record Request( + String targetNamespace, + UUID readRequestId, + GetLaunchDescriptorRequest launchBindingRequest, + String expectedReleaseAttestationDigest) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Generated protobuf request messages are immutable value messages.") + public Request { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a canonical DNS label"); + } + requireNonNil(readRequestId, "readRequestId"); + Objects.requireNonNull(launchBindingRequest, "launchBindingRequest"); + requireNoUnknownFields(launchBindingRequest, "launch binding request"); + UUID nestedReadRequestId = + parseCanonicalUuid(launchBindingRequest.getRequestId(), "launch binding request ID"); + if (!readRequestId.equals(nestedReadRequestId)) { + throw new IllegalArgumentException( + "Launch binding request ID must equal the published spawn read request ID"); + } + if (readRequestId.toString().equals(launchBindingRequest.getControlPlaneRequestId())) { + throw new IllegalArgumentException( + "Published spawn read request ID must be distinct from the original control-plane request"); + } + parseCanonicalUuid(launchBindingRequest.getCanonicalTenantId(), "canonical tenant ID"); + requireText(launchBindingRequest.getWorldSlug(), "worldSlug"); + requireText(launchBindingRequest.getControlPlaneRequestId(), "controlPlaneRequestId"); + requireSha256(launchBindingRequest.getExpectedRequestDigest(), "expectedRequestDigest"); + requireSha256(launchBindingRequest.getExpectedResultDigest(), "expectedResultDigest"); + requireSha256(expectedReleaseAttestationDigest, "expectedReleaseAttestationDigest"); + } + } + + /** One explicit count from the original ordered six-family declaration. */ + public record FamilyCount(WorldDesignAggregateType family, int count) { + public FamilyCount { + Objects.requireNonNull(family, "family"); + if (count < 0) { + throw new IllegalArgumentException("Published World family count must be nonnegative"); + } + } + } + + /** Exact authored Entity template reference; the owner payload is intentionally absent. */ + public record EntityTemplateReference( + EntityTemplateReferenceType kind, UUID tenantId, UUID versionId, UUID templateId) { + public EntityTemplateReference { + Objects.requireNonNull(kind, "kind"); + if (kind != EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM + && kind != EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) { + throw new IllegalArgumentException("Published spawn Entity kind must be ITEM or NPC"); + } + requireNonNil(tenantId, "entity tenantId"); + requireNonNil(versionId, "entity versionId"); + requireNonNil(templateId, "entity templateId"); + } + } + + /** One unchanged authored spawn binding at its original revision position. */ + public record SpawnRequirement( + String revisionOrder, + UUID revisionId, + UUID spawnBindingId, + RoomTemplateRef roomTemplate, + EntityTemplateReference entityTemplate, + int spawnCount, + int respawnDelaySeconds) { + public SpawnRequirement { + requireCanonicalDecimal(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + requireNonNil(spawnBindingId, "spawnBindingId"); + Objects.requireNonNull(roomTemplate, "roomTemplate"); + Objects.requireNonNull(entityTemplate, "entityTemplate"); + if (spawnCount < 0 || respawnDelaySeconds < 0) { + throw new IllegalArgumentException( + "Published spawn count and respawn delay must be nonnegative"); + } + } + } + + /** One unchanged authored generation-rule intent at its original revision position. */ + public record GenerationRequirement( + String revisionOrder, + UUID revisionId, + UUID ruleTemplateId, + WorldDesignAggregateType scopeFamily, + UUID scopeId, + String name, + String value) { + public GenerationRequirement { + requireCanonicalDecimal(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + requireNonNil(ruleTemplateId, "ruleTemplateId"); + Objects.requireNonNull(scopeFamily, "scopeFamily"); + if (scopeFamily != WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + && scopeFamily != WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) { + throw new IllegalArgumentException("Generation requirement scope must be REGION or ZONE"); + } + requireNonNil(scopeId, "scopeId"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(value, "value"); + } + } + + public WorldPublishedSpawnRequirementsEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(launchBinding, "launchBinding"); + requireNonNil(captureId, "captureId"); + requireSha256(graphDigest, "graphDigest"); + familyCounts = List.copyOf(Objects.requireNonNull(familyCounts, "familyCounts")); + spawnRequirements = List.copyOf(Objects.requireNonNull(spawnRequirements, "spawnRequirements")); + generationRequirements = + List.copyOf(Objects.requireNonNull(generationRequirements, "generationRequirements")); + + var descriptor = launchBinding.descriptor(); + var release = launchBinding.releaseAttestation(); + if (!request.targetNamespace().equals(descriptor.targetNamespace()) + || !request.targetNamespace().equals(release.targetNamespace()) + || !descriptor + .canonicalTenantId() + .toString() + .equals(request.launchBindingRequest().getCanonicalTenantId()) + || !descriptor.worldSlug().equals(request.launchBindingRequest().getWorldSlug()) + || !descriptor + .controlPlaneRequestId() + .equals(request.launchBindingRequest().getControlPlaneRequestId()) + || !descriptor + .requestDigest() + .equals(request.launchBindingRequest().getExpectedRequestDigest()) + || !descriptor + .resultDigest() + .equals(request.launchBindingRequest().getExpectedResultDigest())) { + throw new IllegalArgumentException( + "Complete launch binding differs from the exact source-read selector and namespace"); + } + if (request.readRequestId().equals(descriptor.authoredWorldSourceOperationId())) { + throw new IllegalArgumentException( + "Published spawn read request ID must be distinct from the original source operation"); + } + if (!request.expectedReleaseAttestationDigest().equals(release.evidenceDigest())) { + throw new IllegalArgumentException( + "Release attestation digest differs from the exact source-read selector"); + } + if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || release.worldStartLocationEvidence() == null) { + throw new IllegalArgumentException( + "Published spawn requirements require the schema-2 release World selector"); + } + String boundGraphDigest = + WorldDraftStartLocationEvidence.fromStored( + release.worldStartLocationEvidence().selectorReceiptBytes()) + .graphDigest(); + if (!boundGraphDigest.equals(graphDigest)) { + throw new IllegalArgumentException( + "Published spawn graph digest differs from the exact release World selector receipt"); + } + + if (familyCounts.size() != FAMILY_ORDER.size()) { + throw new IllegalArgumentException("Exactly six ordered World family counts are required"); + } + for (int index = 0; index < FAMILY_ORDER.size(); index++) { + if (familyCounts.get(index).family() != FAMILY_ORDER.get(index)) { + throw new IllegalArgumentException( + "World family counts must use the canonical ordered six-family declaration"); + } + } + requireCount( + familyCounts, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + generationRequirements.size()); + requireCount( + familyCounts, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + spawnRequirements.size()); + + UUID tenantId = release.canonicalTenantId(); + UUID versionId = release.canonicalVersionId(); + Set revisionIds = new HashSet<>(); + Set spawnBindingIds = new HashSet<>(); + Set> spawnIdentities = new HashSet<>(); + Set ruleTemplateIds = new HashSet<>(); + requireIncreasingOrders( + spawnRequirements.stream().map(SpawnRequirement::revisionOrder).toList()); + for (SpawnRequirement spawn : spawnRequirements) { + if (!revisionIds.add(spawn.revisionId())) { + throw new IllegalArgumentException("Published requirements repeat a revision identity"); + } + if (!spawnBindingIds.add(spawn.spawnBindingId())) { + throw new IllegalArgumentException( + "Published spawn requirements repeat a binding identity"); + } + if (!tenantId.equals(spawn.roomTemplate().tenantId()) + || !versionId.equals(spawn.roomTemplate().versionId()) + || !tenantId.equals(spawn.entityTemplate().tenantId()) + || !versionId.equals(spawn.entityTemplate().versionId())) { + throw new IllegalArgumentException( + "Published spawn references differ from the exact canonical tenant/version context"); + } + List identity = + List.of( + spawn.roomTemplate().roomTemplateId(), + spawn.entityTemplate().kind(), + spawn.entityTemplate().templateId()); + if (!spawnIdentities.add(identity)) { + throw new IllegalArgumentException( + "Published spawn requirements repeat an authored identity"); + } + } + + Set> generationIdentities = new HashSet<>(); + requireIncreasingOrders( + generationRequirements.stream().map(GenerationRequirement::revisionOrder).toList()); + for (GenerationRequirement generation : generationRequirements) { + if (!revisionIds.add(generation.revisionId())) { + throw new IllegalArgumentException("Published requirements repeat a revision identity"); + } + if (!ruleTemplateIds.add(generation.ruleTemplateId())) { + throw new IllegalArgumentException( + "Published generation requirements repeat a rule template identity"); + } + List identity = + List.of(generation.scopeFamily(), generation.scopeId(), generation.name()); + if (!generationIdentities.add(identity)) { + throw new IllegalArgumentException( + "Published generation requirements repeat an authored identity"); + } + } + } + + private static void requireCount( + List familyCounts, WorldDesignAggregateType family, int expectedCount) { + FamilyCount count = + familyCounts.stream().filter(entry -> entry.family() == family).findFirst().orElseThrow(); + if (count.count() != expectedCount) { + throw new IllegalArgumentException( + "Published World family count differs from its complete source list"); + } + } + + private static void requireIncreasingOrders(List orders) { + BigInteger previous = null; + for (String order : orders) { + BigInteger current = new BigInteger(order); + if (previous != null && current.compareTo(previous) <= 0) { + throw new IllegalArgumentException( + "Published requirements must preserve strictly increasing revision order"); + } + previous = current; + } + } + + static UUID parseCanonicalUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + static void requireCanonicalDecimal(String value, String label) { + Objects.requireNonNull(value, label); + if (!CANONICAL_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal string"); + } + } + + static void requireNoUnknownFields(com.google.protobuf.Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireSha256(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be canonical tagged SHA-256 text"); + } + } + + private static void requireText(String value, String label) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(label + " must not be blank"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodec.java new file mode 100644 index 0000000000..9e3962ca09 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodec.java @@ -0,0 +1,322 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.Message; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedGenerationRequirement; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirement; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsEntityTemplateReference; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsFamilyCount; + +/** Closed mapping and exact request-echo validation for published spawn-requirement reads. */ +public final class WorldPublishedSpawnRequirementsGrpcCodec { + private WorldPublishedSpawnRequirementsGrpcCodec() {} + + public static ReadWorldPublishedSpawnRequirementsRequest toRequest( + WorldPublishedSpawnRequirementsEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadWorldPublishedSpawnRequirementsRequest.newBuilder() + .setSchemaVersion(WorldPublishedSpawnRequirementsEvidence.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setLaunchBindingRequest(request.launchBindingRequest()) + .setExpectedReleaseAttestationDigest(request.expectedReleaseAttestationDigest()) + .build(); + } + + /** Parses the closed owner request only after transport authentication by its caller. */ + public static WorldPublishedSpawnRequirementsEvidence.Request fromRequest( + ReadWorldPublishedSpawnRequirementsRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFieldsRecursively(request, "ReadWorldPublishedSpawnRequirementsRequest"); + if (request.getSchemaVersion() != WorldPublishedSpawnRequirementsEvidence.SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported published spawn-requirements schema version"); + } + if (!request.hasLaunchBindingRequest()) { + throw new IllegalArgumentException( + "Published spawn request lacks its complete binding selector"); + } + return new WorldPublishedSpawnRequirementsEvidence.Request( + request.getTargetNamespace(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + request.getReadRequestId(), "readRequestId"), + request.getLaunchBindingRequest(), + request.getExpectedReleaseAttestationDigest()); + } + + /** + * Encodes complete immutable evidence without changing its request selector or authored values. + */ + public static ReadWorldPublishedSpawnRequirementsResponse toResponse( + WorldPublishedSpawnRequirementsEvidence.Request request, + WorldPublishedSpawnRequirementsEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "Published spawn evidence differs from the exact source-read request"); + } + var builder = + ReadWorldPublishedSpawnRequirementsResponse.newBuilder() + .setRequest(toRequest(request)) + .setCompleteLaunchBinding( + toCompleteLaunchBindingResponse( + request.launchBindingRequest(), evidence.launchBinding())) + .setCaptureId(evidence.captureId().toString()) + .setGraphDigest(evidence.graphDigest()); + for (WorldPublishedSpawnRequirementsEvidence.FamilyCount familyCount : + evidence.familyCounts()) { + builder.addFamilyCounts( + WorldPublishedSpawnRequirementsFamilyCount.newBuilder() + .setFamily(familyCount.family()) + .setCount(familyCount.count())); + } + for (WorldPublishedSpawnRequirementsEvidence.SpawnRequirement spawn : + evidence.spawnRequirements()) { + builder.addSpawnRequirements( + WorldPublishedSpawnRequirement.newBuilder() + .setRevisionOrder(spawn.revisionOrder()) + .setRevisionId(spawn.revisionId().toString()) + .setSpawnBindingId(spawn.spawnBindingId().toString()) + .setRoomTemplate( + RoomTemplateRef.newBuilder() + .setTenantId(spawn.roomTemplate().tenantId().toString()) + .setVersionId(spawn.roomTemplate().versionId().toString()) + .setRoomTemplateId(spawn.roomTemplate().roomTemplateId().toString())) + .setEntityTemplate( + WorldPublishedSpawnRequirementsEntityTemplateReference.newBuilder() + .setKind(spawn.entityTemplate().kind()) + .setTenantId(spawn.entityTemplate().tenantId().toString()) + .setVersionId(spawn.entityTemplate().versionId().toString()) + .setTemplateId(spawn.entityTemplate().templateId().toString())) + .setSpawnCount(spawn.spawnCount()) + .setRespawnDelaySeconds(spawn.respawnDelaySeconds())); + } + for (WorldPublishedSpawnRequirementsEvidence.GenerationRequirement generation : + evidence.generationRequirements()) { + builder.addGenerationRequirements( + WorldPublishedGenerationRequirement.newBuilder() + .setRevisionOrder(generation.revisionOrder()) + .setRevisionId(generation.revisionId().toString()) + .setRuleTemplateId(generation.ruleTemplateId().toString()) + .setScopeFamily(generation.scopeFamily()) + .setScopeId(generation.scopeId().toString()) + .setName(generation.name()) + .setValue(generation.value())); + } + return builder.build(); + } + + /** Validates the complete source response, exact request echo and complete Game Design pair. */ + public static WorldPublishedSpawnRequirementsEvidence fromResponse( + WorldPublishedSpawnRequirementsEvidence.Request request, + ReadWorldPublishedSpawnRequirementsResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFieldsRecursively(response, "ReadWorldPublishedSpawnRequirementsResponse"); + if (response.hasError()) { + throw new IllegalArgumentException("World rejected the published spawn-requirements read"); + } + if (!response.hasRequest() || !response.hasCompleteLaunchBinding()) { + throw new IllegalArgumentException( + "Published spawn response lacks its exact request or complete launch binding"); + } + WorldPublishedSpawnRequirementsEvidence.Request echoed = fromRequest(response.getRequest()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException( + "Published spawn response changed the exact source-read request"); + } + CompleteLaunchBindingEvidence launchBinding = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request.launchBindingRequest(), response.getCompleteLaunchBinding()); + + List familyCounts = + new ArrayList<>(response.getFamilyCountsCount()); + for (WorldPublishedSpawnRequirementsFamilyCount count : response.getFamilyCountsList()) { + requireNoUnknownFieldsRecursively(count, "WorldPublishedSpawnRequirementsFamilyCount"); + if (!count.hasCount()) { + throw new IllegalArgumentException( + "Published World family count is not explicitly present"); + } + familyCounts.add( + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + count.getFamily(), count.getCount())); + } + + List spawns = + new ArrayList<>(response.getSpawnRequirementsCount()); + for (WorldPublishedSpawnRequirement spawn : response.getSpawnRequirementsList()) { + requireNoUnknownFieldsRecursively(spawn, "WorldPublishedSpawnRequirement"); + if (!spawn.hasRoomTemplate() || !spawn.hasEntityTemplate()) { + throw new IllegalArgumentException("Published spawn requirement lacks typed references"); + } + var room = spawn.getRoomTemplate(); + var entity = spawn.getEntityTemplate(); + spawns.add( + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + spawn.getRevisionOrder(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + spawn.getRevisionId(), "revisionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + spawn.getSpawnBindingId(), "spawnBindingId"), + new net.firedevops.firemud.common.world.RoomTemplateRef( + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + room.getTenantId(), "room tenantId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + room.getVersionId(), "room versionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + room.getRoomTemplateId(), "roomTemplateId")), + new WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference( + entity.getKind(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + entity.getTenantId(), "entity tenantId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + entity.getVersionId(), "entity versionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + entity.getTemplateId(), "entity templateId")), + spawn.getSpawnCount(), + spawn.getRespawnDelaySeconds())); + } + + List generations = + new ArrayList<>(response.getGenerationRequirementsCount()); + for (WorldPublishedGenerationRequirement generation : + response.getGenerationRequirementsList()) { + requireNoUnknownFieldsRecursively(generation, "WorldPublishedGenerationRequirement"); + generations.add( + new WorldPublishedSpawnRequirementsEvidence.GenerationRequirement( + generation.getRevisionOrder(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + generation.getRevisionId(), "revisionId"), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + generation.getRuleTemplateId(), "ruleTemplateId"), + generation.getScopeFamily(), + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + generation.getScopeId(), "scopeId"), + generation.getName(), + generation.getValue())); + } + return new WorldPublishedSpawnRequirementsEvidence( + request, + launchBinding, + WorldPublishedSpawnRequirementsEvidence.parseCanonicalUuid( + response.getCaptureId(), "captureId"), + response.getGraphDigest(), + familyCounts, + spawns, + generations); + } + + /** Encodes a parsed launch pair for the outer response while validating its exact selector. */ + public static GetCompleteLaunchBindingResponse toCompleteLaunchBindingResponse( + GetLaunchDescriptorRequest request, CompleteLaunchBindingEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + var bindingBuilder = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.newBuilder() + .setSchemaVersion(descriptor.schemaVersion()) + .setTargetNamespace(descriptor.targetNamespace()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setAuthoredWorldSourceOperationId( + descriptor.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(descriptor.authoredWorldSourceEvidenceDigest()) + .setGameTemplateId(descriptor.gameTemplateId()) + .setRequestDigest(descriptor.requestDigest()) + .setLaunchDescriptorId(descriptor.launchDescriptorId()) + .setVersionId(descriptor.versionId()) + .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) + .setGenerationConfigRevision(descriptor.generationConfigRevision()) + .setVersionStateEpoch(descriptor.versionStateEpoch()) + .setReleaseBundleId(descriptor.releaseBundleId()) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setResultDigest(descriptor.resultDigest()); + if (descriptor.requestedScriptPatchVersionPresent()) { + bindingBuilder.setRequestedScriptPatchVersion(descriptor.requestedScriptPatchVersion()); + } + if (descriptor.sourceVersionIdPresent()) { + bindingBuilder.setSourceVersionId(descriptor.sourceVersionId()); + } + if (descriptor.targetVersionIdPresent()) { + bindingBuilder.setTargetVersionId(descriptor.targetVersionId()); + } + if (descriptor.requestedRuntimeFlagsJsonPresent()) { + bindingBuilder.setRequestedRuntimeFlagsJson(descriptor.requestedRuntimeFlagsJson()); + } + if (descriptor.scriptPatchVersionPresent()) { + bindingBuilder.setScriptPatchVersion(descriptor.scriptPatchVersion()); + } + if (descriptor.remapSetIdPresent()) { + bindingBuilder.setRemapSetId(descriptor.remapSetId()); + } + + var descriptorBuilder = + LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(descriptor.launchDescriptorId()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setGameTemplateId(descriptor.gameTemplateId()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setVersionId(descriptor.versionId()) + .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) + .setGenerationConfigRevision(descriptor.generationConfigRevision()) + .setVersionStateEpoch(descriptor.versionStateEpoch()) + .setReleaseBundleId(descriptor.releaseBundleId()) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setAuthoredWorldBinding(bindingBuilder.build()); + if (descriptor.scriptPatchVersionPresent()) { + descriptorBuilder.setScriptPatchVersion(descriptor.scriptPatchVersion()); + } + if (descriptor.remapSetIdPresent()) { + descriptorBuilder.setRemapSetId(descriptor.remapSetId()); + } + + GetCompleteLaunchBindingResponse response = + GetCompleteLaunchBindingResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setLaunchDescriptor(descriptorBuilder) + .setReleaseAttestation( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation( + evidence.releaseAttestation())) + .build(); + CompleteLaunchBindingEvidence decoded = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response); + if (!decoded.equals(evidence)) { + throw new IllegalArgumentException( + "Encoded complete launch binding differs from its immutable evidence pair"); + } + return response; + } + + private static void requireNoUnknownFieldsRecursively(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (var entry : message.getAllFields().entrySet()) { + FieldDescriptor field = entry.getKey(); + if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) { + continue; + } + Object value = entry.getValue(); + if (field.isRepeated()) { + for (Object element : (List) value) { + requireNoUnknownFieldsRecursively((Message) element, field.getName()); + } + } else { + requireNoUnknownFieldsRecursively((Message) value, field.getName()); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClient.java new file mode 100644 index 0000000000..63565442a3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClient.java @@ -0,0 +1,151 @@ +package net.firedevops.firemud.common.world; + +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.WorldPublishedStartLocationReadServiceGrpc; + +/** Explicit mTLS client for the exact World frozen-selection selector readback. */ +public final class WorldPublishedStartLocationClient + extends AbstractReloadingBlockingGrpcClient< + WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldPublishedStartLocationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldPublishedStartLocationClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Game Design service explicitly starts this opt-in client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("World selector read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World selector read client has no gRPC stub"); + } + initialized = true; + } + + /** Reads immutable selector evidence for this complete frozen selection. */ + public WorldPublishedStartLocationEvidence read( + WorldPublishedStartLocationEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World selector read request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldPublishedStartLocation( + WorldPublishedStartLocationGrpcCodec.toRequest(request)); + try { + return WorldPublishedStartLocationGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid published selector evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldPublishedStartLocationReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World selector read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World selector read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World selector read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World selector read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World selector read " + label + " must be a readable file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World selector read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java new file mode 100644 index 0000000000..2db322fe14 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java @@ -0,0 +1,556 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact World selector readback for an immutable frozen publication selection. + * + *

This evidence does not establish current Account permission, complete release evidence, + * activation, or admission. Decoding and relation checks do not authenticate the producer. The + * explicit mTLS client is responsible for authenticating World before accepting it. + */ +public record WorldPublishedStartLocationEvidence( + Request request, + byte[] selectorReceiptBytes, + byte[] originalAccountBindingBytes, + byte[] appliedResultBytes) { + public static final String SCHEMA = "world-published-start-location-evidence/v1"; + private static final int APPLIED_INTAKE_REQUEST_ID_FRAME = 13; + + private static final Set EVIDENCE_FIELDS = + Set.of( + "schema", + "request", + "selectorReceiptBytesBase64", + "originalAccountBindingBytesBase64", + "appliedResultBytesBase64"); + private static final Set REQUEST_FIELDS = + Set.of( + "targetNamespace", + "canonicalTenantId", + "canonicalVersionId", + "intakeRequestId", + "publicationFence", + "publicationRequestId", + "requestDigest", + "versionStateEpoch", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "worldAffectedTuples"); + private static final Set TUPLE_FIELDS = + Set.of("owner", "aggregateType", "aggregateId", "scopeType", "scopeId", "expectedEpoch"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldPublishedStartLocationEvidence { + Objects.requireNonNull(request, "request"); + selectorReceiptBytes = bytes(selectorReceiptBytes, "selectorReceiptBytes"); + originalAccountBindingBytes = bytes(originalAccountBindingBytes, "originalAccountBindingBytes"); + appliedResultBytes = bytes(appliedResultBytes, "appliedResultBytes"); + requireRelation(request, selectorReceiptBytes, originalAccountBindingBytes, appliedResultBytes); + } + + @Override + public byte[] selectorReceiptBytes() { + return selectorReceiptBytes.clone(); + } + + @Override + public byte[] originalAccountBindingBytes() { + return originalAccountBindingBytes.clone(); + } + + @Override + public byte[] appliedResultBytes() { + return appliedResultBytes.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof WorldPublishedStartLocationEvidence that)) return false; + return request.equals(that.request) + && Arrays.equals(selectorReceiptBytes, that.selectorReceiptBytes) + && Arrays.equals(originalAccountBindingBytes, that.originalAccountBindingBytes) + && Arrays.equals(appliedResultBytes, that.appliedResultBytes); + } + + @Override + public int hashCode() { + int result = Objects.hash(request); + result = 31 * result + Arrays.hashCode(selectorReceiptBytes); + result = 31 * result + Arrays.hashCode(originalAccountBindingBytes); + result = 31 * result + Arrays.hashCode(appliedResultBytes); + return result; + } + + /** Canonical, closed durable representation; this encoding does not authenticate World. */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("request", requestJson(request)); + value.put( + "selectorReceiptBytesBase64", Base64.getEncoder().encodeToString(selectorReceiptBytes)); + value.put( + "originalAccountBindingBytesBase64", + Base64.getEncoder().encodeToString(originalAccountBindingBytes)); + value.put("appliedResultBytesBase64", Base64.getEncoder().encodeToString(appliedResultBytes)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException( + "World published selector evidence cannot be encoded", impossible); + } + } + + /** + * Decodes and validates retained bytes, but does not establish authenticated producer provenance. + */ + public static WorldPublishedStartLocationEvidence fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + try { + JsonNode root = JSON.readTree(stored); + requireFields(root, EVIDENCE_FIELDS, "published World selector evidence"); + if (!SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported published World selector evidence schema"); + } + var evidence = + new WorldPublishedStartLocationEvidence( + parseRequest(root.get("request")), + base64(root, "selectorReceiptBytesBase64"), + base64(root, "originalAccountBindingBytesBase64"), + base64(root, "appliedResultBytesBase64")); + if (!Arrays.equals(stored, evidence.canonicalBytes())) { + throw new IllegalArgumentException("Published World selector evidence is not canonical"); + } + return evidence; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Published World selector evidence is invalid", invalid); + } + } + + private static void requireRelation( + Request request, byte[] receiptBytes, byte[] accountBytes, byte[] appliedBytes) { + var account = DraftAuthorizationFenceBinding.fromStored(accountBytes); + if (!request.canonicalTenantId().equals(account.tenantId()) + || !request.canonicalVersionId().equals(account.versionId()) + || !request.appliedCommitId().equals(account.commitId().toString())) { + throw new IllegalArgumentException( + "Published World selection differs from original Account binding"); + } + + DraftCommitBinding draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + if (!Arrays.equals(draft.canonicalBytes(), account.normalizedInput()) + || !draft.requestId().equals(account.requestId()) + || !draft.commitId().equals(account.commitId()) + || !draft.target().canonicalTenantId().equals(request.canonicalTenantId()) + || !draft.target().canonicalVersionId().equals(request.canonicalVersionId())) { + throw new IllegalArgumentException( + "Published World selection differs from original Draft binding"); + } + List boundTuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .sorted( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)) + .toList(); + if (!request.worldAffectedTuples().equals(boundTuples)) { + throw new IllegalArgumentException( + "Published World selection changed the complete World affected set"); + } + + var terminalRequest = + WorldDraftTerminalReadEvidence.Request.create(request.targetNamespace(), accountBytes); + var terminalReadback = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + accountBytes, + appliedBytes); + var terminalResponse = + WorldDraftTerminalReadGrpcCodec.toResponse( + terminalRequest, java.util.Optional.of(terminalReadback)); + WorldDraftTerminalReadGrpcCodec.fromResponse(terminalRequest, terminalResponse); + + JsonNode applied = readApplied(appliedBytes); + if (!"APPLIED".equals(text(applied, "status"))) { + throw new IllegalArgumentException( + "Published World selector requires the original APPLIED result"); + } + if (!request.intakeRequestId().equals(appliedIntakeRequestId(applied))) { + throw new IllegalArgumentException( + "Published World selection differs from the original APPLIED intake request"); + } + byte[] resultReceipt = base64(applied, "startLocationReceiptBase64"); + if (!Arrays.equals(receiptBytes, resultReceipt)) { + throw new IllegalArgumentException( + "Published World selector differs from original APPLIED receipt"); + } + WorldDraftStartLocationEvidence receipt = + WorldDraftStartLocationEvidence.fromStored(receiptBytes); + if (!receipt.targetNamespace().equals(request.targetNamespace()) + || !receipt.operationId().equals(account.operationId()) + || !receipt.requestId().equals(account.requestId()) + || !receipt.commitId().equals(account.commitId()) + || !receipt.authorizationFenceId().equals(account.fenceId()) + || !receipt.accountBindingDigest().equals(prefixedSha256(accountBytes)) + || !receipt.bindingDigest().equals(draft.digest()) + || !receipt.startLocation().tenantId().equals(request.canonicalTenantId()) + || !receipt.startLocation().versionId().equals(request.canonicalVersionId()) + || !receipt.graphDigest().equals(text(applied, "graphDigest"))) { + throw new IllegalArgumentException( + "Published World selector receipt differs from selected APPLIED commit"); + } + } + + private static JsonNode readApplied(byte[] bytes) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + return JSON.readTree(json); + } catch (IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("World APPLIED result is invalid", invalid); + } + } + + /** Reads the immutable intake identity from the exact operation frame already codec-validated. */ + private static UUID appliedIntakeRequestId(JsonNode applied) { + ByteBuffer operation = ByteBuffer.wrap(base64(applied, "operationBytesBase64")); + String intakeRequestId = null; + for (int frameIndex = 0; frameIndex <= APPLIED_INTAKE_REQUEST_ID_FRAME; frameIndex++) { + if (operation.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("World APPLIED operation frame is truncated"); + } + int frameLength = operation.getInt(); + if (frameLength < 0 || frameLength > operation.remaining()) { + throw new IllegalArgumentException("World APPLIED operation frame has an invalid length"); + } + byte[] frame = new byte[frameLength]; + operation.get(frame); + if (frameIndex == 0 + && !"world-draft-terminal-operation/v1" + .equals(new String(frame, StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Unsupported World APPLIED operation frame schema"); + } + if (frameIndex == APPLIED_INTAKE_REQUEST_ID_FRAME) { + try { + intakeRequestId = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(frame)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "World APPLIED intake request frame is invalid", invalid); + } + } + } + return parseUuid(intakeRequestId, "APPLIED intakeRequestId"); + } + + private static String prefixedSha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static Request parseRequest(JsonNode node) { + requireFields(node, REQUEST_FIELDS, "published World selector request"); + JsonNode tuples = node.get("worldAffectedTuples"); + if (tuples == null || !tuples.isArray()) { + throw new IllegalArgumentException("World affected tuple array is required"); + } + List affected = new ArrayList<>(); + for (JsonNode tuple : tuples) { + requireFields(tuple, TUPLE_FIELDS, "World affected tuple"); + affected.add( + new OwnedAffectedTuple( + text(tuple, "owner"), + text(tuple, "aggregateType"), + text(tuple, "aggregateId"), + text(tuple, "scopeType"), + text(tuple, "scopeId"), + text(tuple, "expectedEpoch"))); + } + Request decoded = + new Request( + text(node, "targetNamespace"), + parseUuid(text(node, "canonicalTenantId"), "canonicalTenantId"), + parseUuid(text(node, "canonicalVersionId"), "canonicalVersionId"), + parseUuid(text(node, "intakeRequestId"), "intakeRequestId"), + parseUuid(text(node, "publicationFence"), "publicationFence"), + text(node, "publicationRequestId"), + text(node, "requestDigest"), + positiveLong(text(node, "versionStateEpoch"), "versionStateEpoch"), + text(node, "publishWorkflowId"), + text(node, "appliedCommitId"), + text(node, "contentDigest"), + intValue(node, "digestSchemaVersion"), + affected); + if (!decoded.worldAffectedTuples().equals(affected)) { + throw new IllegalArgumentException("World affected tuples are not in canonical order"); + } + return decoded; + } + + private static Map requestJson(Request request) { + Map value = new LinkedHashMap<>(); + value.put("targetNamespace", request.targetNamespace()); + value.put("canonicalTenantId", request.canonicalTenantId().toString()); + value.put("canonicalVersionId", request.canonicalVersionId().toString()); + value.put("intakeRequestId", request.intakeRequestId().toString()); + value.put("publicationFence", request.publicationFence().toString()); + value.put("publicationRequestId", request.publicationRequestId()); + value.put("requestDigest", request.requestDigest()); + value.put("versionStateEpoch", Long.toString(request.versionStateEpoch())); + value.put("publishWorkflowId", request.publishWorkflowId()); + value.put("appliedCommitId", request.appliedCommitId()); + value.put("contentDigest", request.contentDigest()); + value.put("digestSchemaVersion", request.digestSchemaVersion()); + value.put( + "worldAffectedTuples", + request.worldAffectedTuples().stream() + .map( + tuple -> { + Map item = new LinkedHashMap<>(); + item.put("owner", tuple.owner()); + item.put("aggregateType", tuple.aggregateType()); + item.put("aggregateId", tuple.aggregateId()); + item.put("scopeType", tuple.scopeType()); + item.put("scopeId", tuple.scopeId()); + item.put("expectedEpoch", tuple.expectedEpoch()); + return item; + }) + .toList()); + return value; + } + + private static byte[] base64(JsonNode node, String field) { + try { + return Base64.getDecoder().decode(text(node, field)); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Invalid base64 field " + field, invalid); + } + } + + private static byte[] bytes(byte[] value, String name) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException(name + " is required"); + } + return value.clone(); + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + return value.textValue(); + } + + private static long positiveLong(String value, String field) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the supported integer range", invalid); + } + } + + private static int intValue(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException(field + " must be an integer"); + } + return value.intValue(); + } + + private static UUID parseUuid(String value, String label) { + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical UUID", invalid); + } + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static void requireFields(JsonNode object, Set fields, String label) { + if (object == null || !object.isObject()) { + throw new IllegalArgumentException(label + " must be an object"); + } + Set actual = new java.util.HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) { + throw new IllegalArgumentException(label + " has missing or unsupported fields"); + } + } + + /** Exact transport-neutral immutable selection input. */ + public record Request( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID intakeRequestId, + UUID publicationFence, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + List worldAffectedTuples) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + requireUuid(canonicalTenantId, "canonicalTenantId"); + requireUuid(canonicalVersionId, "canonicalVersionId"); + requireUuid(intakeRequestId, "intakeRequestId"); + requireUuid(publicationFence, "publicationFence"); + requireText(publicationRequestId, "publicationRequestId"); + requireSha256(requestDigest, "requestDigest"); + if (versionStateEpoch <= 0) + throw new IllegalArgumentException("versionStateEpoch must be positive"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(appliedCommitId, "appliedCommitId"); + requireSha256(contentDigest, "contentDigest"); + if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + throw new IllegalArgumentException("Unsupported World digest schema version"); + } + Objects.requireNonNull(worldAffectedTuples, "worldAffectedTuples"); + List ordered = new ArrayList<>(worldAffectedTuples); + ordered.sort( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)); + if (ordered.stream().distinct().count() != ordered.size()) { + throw new IllegalArgumentException("duplicate World affected tuple"); + } + worldAffectedTuples = List.copyOf(ordered); + } + + private static void requireUuid(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireText(String value, String name) { + if (value == null || value.isBlank()) + throw new IllegalArgumentException(name + " is required"); + } + + private static void requireSha256(String value, String name) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be 64 lowercase hexadecimal digits"); + } + } + } + + public record OwnedAffectedTuple( + String owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public OwnedAffectedTuple { + if (!"WORLD_MANAGEMENT".equals(owner)) { + throw new IllegalArgumentException("Published selector tuples must name WORLD_MANAGEMENT"); + } + requireTupleText(aggregateType, "aggregateType"); + requireTupleText(aggregateId, "aggregateId"); + Objects.requireNonNull(scopeType, "scopeType"); + Objects.requireNonNull(scopeId, "scopeId"); + if (scopeType.isEmpty() != scopeId.isEmpty()) { + throw new IllegalArgumentException("scopeType and scopeId must both be present or absent"); + } + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || new java.math.BigInteger(expectedEpoch) + .compareTo(java.math.BigInteger.valueOf(Long.MAX_VALUE)) + > 0) { + throw new IllegalArgumentException("expectedEpoch must be canonical non-negative decimal"); + } + } + + private static void requireTupleText(String value, String name) { + if (value == null || value.isBlank()) + throw new IllegalArgumentException(name + " is required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java new file mode 100644 index 0000000000..faaa5407b1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodec.java @@ -0,0 +1,216 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.OwnedAffectedTuple; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationAffectedTuple; + +/** Closed wire mapping and exact request-echo validation for the World selector read. */ +public final class WorldPublishedStartLocationGrpcCodec { + private WorldPublishedStartLocationGrpcCodec() {} + + public static ReadWorldPublishedStartLocationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var builder = + ReadWorldPublishedStartLocationRequest.newBuilder() + .setSchemaVersion(Request.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setPublicationFence(request.publicationFence().toString()) + .setPublicationRequestId(request.publicationRequestId()) + .setRequestDigest(request.requestDigest()) + .setVersionStateEpoch(request.versionStateEpoch()) + .setPublishWorkflowId(request.publishWorkflowId()) + .setAppliedCommitId(request.appliedCommitId()) + .setContentDigest(request.contentDigest()) + .setDigestSchemaVersion(request.digestSchemaVersion()); + request.worldAffectedTuples().stream() + .map(WorldPublishedStartLocationGrpcCodec::toWireTuple) + .forEach(builder::addWorldAffectedTuples); + return builder.build(); + } + + /** + * Decodes only after the World receiver authenticates its exact same-namespace Game Design peer. + */ + public static Request fromRequest(ReadWorldPublishedStartLocationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadWorldPublishedStartLocationRequest"); + if (request.getSchemaVersion() != Request.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported World published selector read schema version"); + } + return toEvidenceRequest( + request.getTargetNamespace(), + request.getCanonicalTenantId(), + request.getCanonicalVersionId(), + request.getIntakeRequestId(), + request.getPublicationFence(), + request.getPublicationRequestId(), + request.getRequestDigest(), + request.getVersionStateEpoch(), + request.getPublishWorkflowId(), + request.getAppliedCommitId(), + request.getContentDigest(), + request.getDigestSchemaVersion(), + request.getWorldAffectedTuplesList()); + } + + public static ReadWorldPublishedStartLocationResponse toResponse( + Request request, WorldPublishedStartLocationEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + if (!request.equals(evidence.request())) { + throw new IllegalArgumentException( + "World selector evidence differs from exact selection request"); + } + var builder = + ReadWorldPublishedStartLocationResponse.newBuilder() + .setSchemaVersion(Request.SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setPublicationFence(request.publicationFence().toString()) + .setPublicationRequestId(request.publicationRequestId()) + .setRequestDigest(request.requestDigest()) + .setVersionStateEpoch(request.versionStateEpoch()) + .setPublishWorkflowId(request.publishWorkflowId()) + .setAppliedCommitId(request.appliedCommitId()) + .setContentDigest(request.contentDigest()) + .setDigestSchemaVersion(request.digestSchemaVersion()) + .setSelectorReceiptBytes(ByteString.copyFrom(evidence.selectorReceiptBytes())) + .setOriginalAccountBindingBytes( + ByteString.copyFrom(evidence.originalAccountBindingBytes())) + .setAppliedResultBytes(ByteString.copyFrom(evidence.appliedResultBytes())); + request.worldAffectedTuples().stream() + .map(WorldPublishedStartLocationGrpcCodec::toWireTuple) + .forEach(builder::addWorldAffectedTuples); + return builder.build(); + } + + /** Validates the complete echoed capture tuple and all three exact retained World byte values. */ + public static WorldPublishedStartLocationEvidence fromResponse( + Request request, ReadWorldPublishedStartLocationResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadWorldPublishedStartLocationResponse"); + if (response.getSchemaVersion() != Request.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported World published selector response schema version"); + } + Request echoed = + toEvidenceRequest( + response.getTargetNamespace(), + response.getCanonicalTenantId(), + response.getCanonicalVersionId(), + response.getIntakeRequestId(), + response.getPublicationFence(), + response.getPublicationRequestId(), + response.getRequestDigest(), + response.getVersionStateEpoch(), + response.getPublishWorkflowId(), + response.getAppliedCommitId(), + response.getContentDigest(), + response.getDigestSchemaVersion(), + response.getWorldAffectedTuplesList()); + if (!request.equals(echoed)) { + throw new IllegalArgumentException( + "World published selector response changed exact selection request"); + } + if (response.getSelectorReceiptBytes().isEmpty() + || response.getOriginalAccountBindingBytes().isEmpty() + || response.getAppliedResultBytes().isEmpty()) { + throw new IllegalArgumentException( + "World published selector response lacks retained evidence bytes"); + } + return new WorldPublishedStartLocationEvidence( + request, + response.getSelectorReceiptBytes().toByteArray(), + response.getOriginalAccountBindingBytes().toByteArray(), + response.getAppliedResultBytes().toByteArray()); + } + + private static Request toEvidenceRequest( + String namespace, + String tenant, + String version, + String intakeRequest, + String publicationFence, + String publicationRequest, + String requestDigest, + long versionStateEpoch, + String workflow, + String appliedCommit, + String contentDigest, + int digestSchema, + java.util.List tuples) { + var affected = + tuples.stream().map(WorldPublishedStartLocationGrpcCodec::fromWireTuple).toList(); + Request decoded = + new Request( + namespace, + canonicalUuid(tenant, "canonicalTenantId"), + canonicalUuid(version, "canonicalVersionId"), + canonicalUuid(intakeRequest, "intakeRequestId"), + canonicalUuid(publicationFence, "publicationFence"), + publicationRequest, + requestDigest, + versionStateEpoch, + workflow, + appliedCommit, + contentDigest, + digestSchema, + affected); + if (!decoded.worldAffectedTuples().equals(affected)) { + throw new IllegalArgumentException("World affected tuples are not in canonical order"); + } + return decoded; + } + + private static WorldPublishedStartLocationAffectedTuple toWireTuple(OwnedAffectedTuple tuple) { + return WorldPublishedStartLocationAffectedTuple.newBuilder() + .setOwner(tuple.owner()) + .setAggregateType(tuple.aggregateType()) + .setAggregateId(tuple.aggregateId()) + .setScopeType(tuple.scopeType()) + .setScopeId(tuple.scopeId()) + .setExpectedEpoch(tuple.expectedEpoch()) + .build(); + } + + private static OwnedAffectedTuple fromWireTuple(WorldPublishedStartLocationAffectedTuple tuple) { + requireNoUnknownFields(tuple, "WorldPublishedStartLocationAffectedTuple"); + return new OwnedAffectedTuple( + tuple.getOwner(), + tuple.getAggregateType(), + tuple.getAggregateId(), + tuple.getScopeType(), + tuple.getScopeId(), + tuple.getExpectedEpoch()); + } + + private static java.util.UUID canonicalUuid(String value, String label) { + try { + java.util.UUID parsed = java.util.UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new java.util.UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientMtlsTest.java new file mode 100644 index 0000000000..8e84759b5f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientMtlsTest.java @@ -0,0 +1,489 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener; +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.stub.StreamObserver; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceServiceGrpc; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import net.firedevops.firemud.account.v1.ReadCurrentIssuerAuthoritySourceRequest; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical file-backed workload mTLS transport proof against an issuer-owner transport double. */ +class AccountIssuerAuthoritySourceClientMtlsTest { + private static final String NAMESPACE = "firemud"; + private static final String CALLER = "spiffe://firemud/ns/firemud/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + @Test + void revalidatesSequenceZeroAndPositiveSourcesExactlyOverFileBackedMtls(@TempDir Path directory) + throws Exception { + var clientTls = writeClientTlsMaterial(directory); + var serverTls = writeServerTlsMaterial(directory, ServerIdentity.ACCOUNT); + IssuerOwnerTransportDouble owner = new IssuerOwnerTransportDouble(); + try (TransportServer server = startServer(serverTls, clientTls.caCertificate(), owner); + AccountIssuerAuthoritySourceClient client = newClient(server.port(), clientTls)) { + client.init(); + + UUID zeroOperation = UUID.randomUUID(); + var initialZero = client.read(request(zeroOperation, Optional.empty())); + assertThat(initialZero.lastCommittedOutboxSequence()).isEqualTo("0"); + assertThat(initialZero.sourceEvent()).isEmpty(); + assertThat(client.read(request(zeroOperation, Optional.of(initialZero)))) + .isEqualTo(initialZero); + + UUID positiveOperation = UUID.randomUUID(); + var positive = source(positiveOperation, "1", "2"); + owner.setCurrentSource(positive); + assertThat(client.read(request(positiveOperation, Optional.of(positive)))) + .isEqualTo(positive); + assertThat(positive.sourceEvent()).isPresent(); + + assertThat(owner.observation.metadataCount()).isEqualTo(3); + assertThat(owner.observation.messageCount()).isEqualTo(3); + assertThat(owner.ownerReadCount()).isEqualTo(3); + } + } + + @Test + void rejectsBadUnknownAndChangedSourceResponsesFailClosed(@TempDir Path directory) + throws Exception { + var clientTls = writeClientTlsMaterial(directory); + var serverTls = writeServerTlsMaterial(directory, ServerIdentity.ACCOUNT); + IssuerOwnerTransportDouble owner = new IssuerOwnerTransportDouble(); + try (TransportServer server = startServer(serverTls, clientTls.caCertificate(), owner); + AccountIssuerAuthoritySourceClient client = newClient(server.port(), clientTls)) { + client.init(); + UUID operation = UUID.randomUUID(); + var expected = source(operation, "1", "2"); + owner.setCurrentSource(expected); + + owner.setResponseMode(ResponseMode.MISSING_FIELDS); + assertThatThrownBy(() -> client.read(request(operation, Optional.of(expected)))) + .isInstanceOf(IllegalArgumentException.class); + + owner.setResponseMode(ResponseMode.UNKNOWN_FIELD); + assertThatThrownBy(() -> client.read(request(operation, Optional.of(expected)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown protobuf fields"); + + owner.setResponseMode(ResponseMode.CHANGED_SOURCE); + assertThatThrownBy(() -> client.read(request(operation, Optional.of(expected)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact expected snapshot"); + + assertThat(owner.observation.metadataCount()).isEqualTo(3); + assertThat(owner.observation.messageCount()).isEqualTo(3); + assertThat(owner.ownerReadCount()).isEqualTo(3); + } + } + + @Test + void wrongAccountServiceOrNamespacePeerIsRejectedBeforeAnyRpcMetadataOrOwnerRead( + @TempDir Path directory) throws Exception { + var clientTls = writeClientTlsMaterial(directory); + for (ServerIdentity identity : + new ServerIdentity[] {ServerIdentity.WRONG_SERVICE, ServerIdentity.WRONG_NAMESPACE}) { + Path serverDirectory = Files.createDirectories(directory.resolve(identity.name())); + var serverTls = writeServerTlsMaterial(serverDirectory, identity); + IssuerOwnerTransportDouble owner = new IssuerOwnerTransportDouble(); + try (TransportServer server = startServer(serverTls, clientTls.caCertificate(), owner); + AccountIssuerAuthoritySourceClient client = newClient(server.port(), clientTls)) { + client.init(); + UUID operation = UUID.randomUUID(); + assertThatThrownBy(() -> client.read(request(operation, Optional.empty()))) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + + assertThat(owner.observation.metadataCount()).isZero(); + assertThat(owner.observation.messageCount()).isZero(); + assertThat(owner.ownerReadCount()).isZero(); + } + } + } + + static ClientTlsMaterial writeClientTlsMaterial(Path directory) throws IOException { + return writeClientTlsMaterial(directory, false); + } + + static ClientTlsMaterial writeClientTlsMaterial(Path directory, boolean wrongIdentity) + throws IOException { + Files.createDirectories(directory); + Path ca = write(directory.resolve("test-ca.pem"), TEST_CA); + Path clientCertificate = + write( + directory.resolve("client.crt"), + wrongIdentity ? WRONG_NAMESPACE_SERVER_CERTIFICATE : CLIENT_CERTIFICATE); + Path clientPrivateKey = write(directory.resolve("client.key"), CLIENT_PRIVATE_KEY); + return new ClientTlsMaterial(ca, clientCertificate, clientPrivateKey); + } + + private static ServerTlsMaterial writeServerTlsMaterial(Path directory, ServerIdentity identity) + throws IOException { + Files.createDirectories(directory); + Path ca = write(directory.resolve("test-ca.pem"), TEST_CA); + return switch (identity) { + case ACCOUNT -> + new ServerTlsMaterial( + ca, + write(directory.resolve("server.crt"), ACCOUNT_SERVER_CERTIFICATE), + write(directory.resolve("server.key"), ACCOUNT_SERVER_PRIVATE_KEY)); + case WRONG_SERVICE -> + new ServerTlsMaterial( + ca, + write(directory.resolve("server.crt"), WRONG_SERVICE_SERVER_CERTIFICATE), + write(directory.resolve("server.key"), WRONG_SERVICE_SERVER_PRIVATE_KEY)); + case WRONG_NAMESPACE -> + new ServerTlsMaterial( + ca, + write(directory.resolve("server.crt"), WRONG_NAMESPACE_SERVER_CERTIFICATE), + write(directory.resolve("server.key"), WRONG_NAMESPACE_SERVER_PRIVATE_KEY)); + }; + } + + private static TransportServer startServer( + ServerTlsMaterial serverTls, Path trustedClientCa, IssuerOwnerTransportDouble owner) + throws Exception { + var sslContext = + GrpcSslContexts.forServer( + serverTls.serverCertificate().toFile(), serverTls.serverPrivateKey().toFile()) + .trustManager(trustedClientCa.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build(); + Server server = + NettyServerBuilder.forPort(0) + .sslContext(sslContext) + .addService( + ServerInterceptors.intercept( + owner, owner.observation, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new TransportServer(server); + } + + private static AccountIssuerAuthoritySourceClient newClient( + int port, ClientTlsMaterial tlsMaterial) { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(tlsMaterial.clientCertificate().toString()); + tls.setPrivateKey(tlsMaterial.clientPrivateKey().toString()); + tls.setCaCert(tlsMaterial.caCertificate().toString()); + return new AccountIssuerAuthoritySourceClient( + endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private static AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request( + UUID operation, Optional expected) { + return new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, ISSUER, expected); + } + + private static AccountIssuerSourceSnapshotEvidence source( + UUID operation, String sequence, String generation) { + Optional event = Optional.empty(); + if (!"0".equals(sequence)) { + event = + Optional.of( + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + operation.toString(), + operation.toString(), + STREAM, + sequence, + ISSUER, + generation, + generation, + "SIGNER_COMPROMISE")) + .canonicalJson()); + } + return new AccountIssuerSourceSnapshotEvidence( + operation, NAMESPACE, CALLER, ISSUER, generation, generation, STREAM, sequence, event); + } + + private static Path write(Path path, String contents) throws IOException { + return Files.writeString(path, contents); + } + + record ClientTlsMaterial(Path caCertificate, Path clientCertificate, Path clientPrivateKey) {} + + private record ServerTlsMaterial( + Path caCertificate, Path serverCertificate, Path serverPrivateKey) {} + + private record TransportServer(Server server) implements AutoCloseable { + int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow().awaitTermination(); + } + } + + private enum ServerIdentity { + ACCOUNT, + WRONG_SERVICE, + WRONG_NAMESPACE + } + + private enum ResponseMode { + CURRENT, + MISSING_FIELDS, + UNKNOWN_FIELD, + CHANGED_SOURCE + } + + private static final class TransportObservation implements ServerInterceptor { + private final AtomicInteger metadataCount = new AtomicInteger(); + private final AtomicInteger messageCount = new AtomicInteger(); + + @Override + public io.grpc.ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + metadataCount.incrementAndGet(); + return new SimpleForwardingServerCallListener<>(next.startCall(call, headers)) { + @Override + public void onMessage(RequestT message) { + messageCount.incrementAndGet(); + super.onMessage(message); + } + }; + } + + int metadataCount() { + return metadataCount.get(); + } + + int messageCount() { + return messageCount.get(); + } + } + + /** Synthetic owner transport fixture; it does not execute or claim Account database semantics. */ + private static final class IssuerOwnerTransportDouble + extends AccountIssuerAuthoritySourceServiceGrpc.AccountIssuerAuthoritySourceServiceImplBase { + private final TransportObservation observation = new TransportObservation(); + private final AtomicInteger ownerReadCount = new AtomicInteger(); + private volatile AccountIssuerSourceSnapshotEvidence currentSource; + private volatile ResponseMode responseMode = ResponseMode.CURRENT; + + @Override + public void readCurrentIssuerAuthoritySource( + ReadCurrentIssuerAuthoritySourceRequest request, + StreamObserver responseObserver) { + ownerReadCount.incrementAndGet(); + try { + GrpcPeerIdentity caller = GrpcPeerIdentity.current(); + if (caller == null || !CALLER.equals(caller.uri())) { + responseObserver.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + var parsedRequest = + AccountIssuerSourceSnapshotGrpcCodec.fromRequest(request, NAMESPACE, caller.uri()); + AccountIssuerSourceSnapshotEvidence responseSource = currentSource; + if (responseSource == null && parsedRequest.expectedSource().isPresent()) { + responseSource = parsedRequest.expectedSource().orElseThrow(); + } + if (responseSource == null) { + responseSource = source(parsedRequest.reconciliationOperationId(), "0", "1"); + currentSource = responseSource; + } + + AccountIssuerAuthoritySourceSnapshot wireResponse; + switch (responseMode) { + case MISSING_FIELDS -> + wireResponse = + AccountIssuerAuthoritySourceSnapshot.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .build(); + case UNKNOWN_FIELD -> + wireResponse = + AccountIssuerSourceSnapshotGrpcCodec.toWire(responseSource).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + case CHANGED_SOURCE -> + wireResponse = + AccountIssuerSourceSnapshotGrpcCodec.toWire( + source(parsedRequest.reconciliationOperationId(), "2", "3")); + case CURRENT -> + wireResponse = + AccountIssuerSourceSnapshotGrpcCodec.toResponse( + responseSource, parsedRequest, caller.uri()); + default -> throw new IllegalStateException("unsupported transport-double response mode"); + } + responseObserver.onNext(wireResponse); + responseObserver.onCompleted(); + } catch (RuntimeException failure) { + responseObserver.onError(Status.INVALID_ARGUMENT.withCause(failure).asRuntimeException()); + } + } + + int ownerReadCount() { + return ownerReadCount.get(); + } + + void setCurrentSource(AccountIssuerSourceSnapshotEvidence source) { + currentSource = source; + } + + void setResponseMode(ResponseMode mode) { + responseMode = mode; + } + } + + private static final String TEST_CA = + """ + -----BEGIN CERTIFICATE----- + MIIBtTCCAVugAwIBAgIUEVP0Q8L5Ora/p1kDdJlLB272mNMwCgYIKoZIzj0EAwIw + KDEmMCQGA1UEAwwdRmlyZU1VRCBpc3N1ZXItc291cmNlIHRlc3QgQ0EwHhcNMjYx + MDA4MDIyNjQ4WhcNNDYxMDAzMDIyNjQ4WjAoMSYwJAYDVQQDDB1GaXJlTVVEIGlz + c3Vlci1zb3VyY2UgdGVzdCBDQTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABAqz + jOqtLuabC4VgS1wSj+BNxfFj5P4sPKJ0JxVw1k0rg2DJlGmCLPPU0cq8ow7DgtU0 + Gmi2BoLCuMOWlW719S+jYzBhMB8GA1UdIwQYMBaAFDcLkswEeTQ+ubifCjqS//hA + nQAAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBQ3 + C5LMBHk0Prm4nwo6kv/4QJ0AADAKBggqhkjOPQQDAgNIADBFAiEA+sYWAP6HFISr + qGcbHAXzA9SgrH7nHWVwRX2vgRoA7DMCICnfSOJCWGedTmGbaT2m8xjpDMlgvnrL + Vwi8c/15tJei + -----END CERTIFICATE----- + """; + + private static final String CLIENT_CERTIFICATE = + """ + -----BEGIN CERTIFICATE----- + MIICBTCCAaugAwIBAgIUIbUYSjzVvJpHUY1Y0zoWfQiI9SIwCgYIKoZIzj0EAwIw + KDEmMCQGA1UEAwwdRmlyZU1VRCBpc3N1ZXItc291cmNlIHRlc3QgQ0EwHhcNMjYx + MDA4MDIyNjQ4WhcNNDYxMDAzMDIyNjQ4WjAkMSIwIAYDVQQDDBlmaXJlbXVkIGdh + bWUtc2Vzc2lvbiB0ZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE95+zYl2Q + C1ply40Sa76hBaIBQ3xGRydNUbOq0aie9RWWlhe7Hdfj1jiWa+TfMvDo4g49tOxb + re8OlicZ4c2QXqOBtjCBszAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIHgDAT + BgNVHSUEDDAKBggrBgEFBQcDAjA+BgNVHREENzA1hjNzcGlmZmU6Ly9maXJlbXVk + L25zL2ZpcmVtdWQvc2EvZ2FtZS1zZXNzaW9uLXNlcnZpY2UwHQYDVR0OBBYEFF+C + ZbOODKc5aG50EuJcDYrMvqG4MB8GA1UdIwQYMBaAFDcLkswEeTQ+ubifCjqS//hA + nQAAMAoGCCqGSM49BAMCA0gAMEUCIQCpKhU72Vr+0J/ecKtssCdwL7ZpW/7/tEKu + TqBG3a212gIgZ/d+bD5cEXnHH2s9FiHtthuiJ5TG/M82vsmhLWUWD+I= + -----END CERTIFICATE----- + """; + + private static final String CLIENT_PRIVATE_KEY = + """ + -----BEGIN PRIVATE KEY----- + MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgL7a8bTP2x/haYtxx + ZmHwnXgNeLo+ok4/oOTcChj5IByhRANCAAT3n7NiXZALWmXLjRJrvqEFogFDfEZH + J01Rs6rRqJ71FZaWF7sd1+PWOJZr5N8y8OjiDj207Fut7w6WJxnhzZBe + -----END PRIVATE KEY----- + """; + + private static final String ACCOUNT_SERVER_CERTIFICATE = + """ + -----BEGIN CERTIFICATE----- + MIICBzCCAaygAwIBAgIUM7M4f8TIsmepkFGPEGvzno7AhlAwCgYIKoZIzj0EAwIw + KDEmMCQGA1UEAwwdRmlyZU1VRCBpc3N1ZXItc291cmNlIHRlc3QgQ0EwHhcNMjYx + MDA4MDIyNjQ4WhcNNDYxMDAzMDIyNjQ4WjAfMR0wGwYDVQQDDBRmaXJlbXVkIGFj + Y291bnQgdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJYzdFJrNpJomn8o + vTyLc+w0O6x9ZJH0Ve7DqrpL4151fWjv+QSyunwogecWWDtXyBJg0t1+E1izowFO + Dm/NxKCjgbwwgbkwDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0l + BAwwCgYIKwYBBQUHAwEwRAYDVR0RBD0wO4IJbG9jYWxob3N0hi5zcGlmZmU6Ly9m + aXJlbXVkL25zL2ZpcmVtdWQvc2EvYWNjb3VudC1zZXJ2aWNlMB0GA1UdDgQWBBRP + u+0KoAlDJBd9BZIcftifunH/nDAfBgNVHSMEGDAWgBQ3C5LMBHk0Prm4nwo6kv/4 + QJ0AADAKBggqhkjOPQQDAgNJADBGAiEArSG4oVkjw24XI04ckfdefWeX0FAbo4n5 + uKAGNu+vJjYCIQDO0K7fzv/sD76KIAe6lCjO7uWIMqrXgYcxKM87WtZZwA== + -----END CERTIFICATE----- + """; + + private static final String ACCOUNT_SERVER_PRIVATE_KEY = + """ + -----BEGIN PRIVATE KEY----- + MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgsF8YPfzEzsLMcFwK + jDNpeuA/UYR01ZJJHggn1GuDGRShRANCAASWM3RSazaSaJp/KL08i3PsNDusfWSR + 9FXuw6q6S+NedX1o7/kEsrp8KIHnFlg7V8gSYNLdfhNYs6MBTg5vzcSg + -----END PRIVATE KEY----- + """; + + private static final String WRONG_SERVICE_SERVER_CERTIFICATE = + """ + -----BEGIN CERTIFICATE----- + MIICEDCCAbagAwIBAgIUUoUlbNguY4u1g9cd3CTkLx1ph14wCgYIKoZIzj0EAwIw + KDEmMCQGA1UEAwwdRmlyZU1VRCBpc3N1ZXItc291cmNlIHRlc3QgQ0EwHhcNMjYx + MDA4MDIyNjQ4WhcNNDYxMDAzMDIyNjQ4WjAlMSMwIQYDVQQDDBpmaXJlbXVkIHdy + b25nIHNlcnZpY2UgdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABIfFrRHj + wS3v8/1NseHlHaVgUYBr+qPVgvCNTgOigjT/S/zQ7ObTK0QgjJQkm6qhWhtNNWVb + ViPeGKieLlncC02jgcAwgb0wDAYDVR0TAQH/BAIwADAOBgNVHQ8BAf8EBAMCB4Aw + EwYDVR0lBAwwCgYIKwYBBQUHAwEwSAYDVR0RBEEwP4IJbG9jYWxob3N0hjJzcGlm + ZmU6Ly9maXJlbXVkL25zL2ZpcmVtdWQvc2EvZ2FtZS1kZXNpZ24tc2VydmljZTAd + BgNVHQ4EFgQUAqO+RBJqRVOb8ivvTyWWpWp5QK0wHwYDVR0jBBgwFoAUNwuSzAR5 + ND65uJ8KOpL/+ECdAAAwCgYIKoZIzj0EAwIDSAAwRQIhAIgMjCy7nTnqcGBNexw4 + hKCu4IvM6sYc/yRmzcQ/pq2GAiBQJZOUStWnGJKz35ODoZHndOCSGE3J/ZMehFrW + 3EF8Rg== + -----END CERTIFICATE----- + """; + + private static final String WRONG_SERVICE_SERVER_PRIVATE_KEY = + """ + -----BEGIN PRIVATE KEY----- + MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgU/N/DJ4u72eEVy6M + lBc2ZZoa0id2EkrAXbEIzsbjDYKhRANCAASHxa0R48Et7/P9TbHh5R2lYFGAa/qj + 1YLwjU4DooI0/0v80Ozm0ytEIIyUJJuqoVobTTVlW1Yj3hioni5Z3AtN + -----END PRIVATE KEY----- + """; + + private static final String WRONG_NAMESPACE_SERVER_CERTIFICATE = + """ + -----BEGIN CERTIFICATE----- + MIICDTCCAbKgAwIBAgIUTXRuwVMIcnUSv5EIbCG1IIInpocwCgYIKoZIzj0EAwIw + KDEmMCQGA1UEAwwdRmlyZU1VRCBpc3N1ZXItc291cmNlIHRlc3QgQ0EwHhcNMjYx + MDA4MDIyNjQ4WhcNNDYxMDAzMDIyNjQ4WjAnMSUwIwYDVQQDDBxmaXJlbXVkIHdy + b25nIG5hbWVzcGFjZSB0ZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEqnH+ + OVHMgjnsqHMj2JcGkztSnOzCGrRdMgmqPjQoU6aQKQ6kW6g9QIf+IRuypZqP5gWu + 7P2lpxEiSSwo0tRulKOBujCBtzAMBgNVHRMBAf8EAjAAMA4GA1UdDwEB/wQEAwIH + gDATBgNVHSUEDDAKBggrBgEFBQcDATBCBgNVHREEOzA5gglsb2NhbGhvc3SGLHNw + aWZmZTovL2ZpcmVtdWQvbnMvb3RoZXIvc2EvYWNjb3VudC1zZXJ2aWNlMB0GA1Ud + DgQWBBTQ0iPp7mEFoUWE6jUas8gHr/t6KjAfBgNVHSMEGDAWgBQ3C5LMBHk0Prm4 + nwo6kv/4QJ0AADAKBggqhkjOPQQDAgNJADBGAiEAnmXME6WMdN0ORDptJ0FE1uTM + Muuiz2Z7DbIBd3YihwgCIQCtEaz1wc3t/ecLLNlgy6311eXLc+XTM1ijnLhxFClj + iA== + -----END CERTIFICATE----- + """; + + private static final String WRONG_NAMESPACE_SERVER_PRIVATE_KEY = + """ + -----BEGIN PRIVATE KEY----- + MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg92jz3gfsT5pGQ8+z + Iqw5o8rUe1CwrS3rOs/aEDdK9RShRANCAASqcf45UcyCOeyocyPYlwaTO1Kc7MIa + tF0yCao+NChTppApDqRbqD1Ah/4hG7Klmo/mBa7s/aWnESJJLCjS1G6U + -----END PRIVATE KEY----- + """; +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientTest.java new file mode 100644 index 0000000000..84daf39b05 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerAuthoritySourceClientTest.java @@ -0,0 +1,204 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.nio.file.Path; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +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; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountIssuerAuthoritySourceClientTest { + private static final String NAMESPACE = "firemud"; + private static final String CALLER = "spiffe://firemud/ns/firemud/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + @Test + void rejectsInvalidNamespaceAndUninitializedOrClosedLifecycle(@TempDir Path directory) + throws Exception { + var material = AccountIssuerAuthoritySourceClientMtlsTest.writeClientTlsMaterial(directory); + CommonGrpcClientProperties tls = tlsProperties(material); + assertThatThrownBy(() -> newClient("FireMUD", tls)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + + AccountIssuerAuthoritySourceClient client = newClient(NAMESPACE, tls); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + + client.close(); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + } + + @Test + void requiresReadableFileBackedMutualTlsAndExactClientLeafIdentity(@TempDir Path directory) + throws Exception { + CommonGrpcClientProperties plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(NAMESPACE, plaintext)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires TLS with file-backed client mTLS"); + + var material = AccountIssuerAuthoritySourceClientMtlsTest.writeClientTlsMaterial(directory); + CommonGrpcClientProperties missingKey = tlsProperties(material); + missingKey.setPrivateKey(directory.resolve("missing-key.pem").toString()); + assertThatThrownBy(() -> newClient(NAMESPACE, missingKey)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("privateKey must be a readable regular file"); + + var wrongMaterial = + AccountIssuerAuthoritySourceClientMtlsTest.writeClientTlsMaterial( + directory.resolve("wrong-identity"), true); + AccountIssuerAuthoritySourceClient wrongIdentityClient = + newClient(NAMESPACE, tlsProperties(wrongMaterial)); + assertThatThrownBy(wrongIdentityClient::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must match the configured Game Session workload"); + } + + @Test + void rejectsAmbientTransactionsAndNamespaceMismatchedRequestsBeforeRpc(@TempDir Path directory) + throws Exception { + var material = AccountIssuerAuthoritySourceClientMtlsTest.writeClientTlsMaterial(directory); + AccountIssuerAuthoritySourceClient client = newClient(NAMESPACE, tlsProperties(material)); + client.init(); + try { + var request = request(UUID.randomUUID(), Optional.empty(), "other"); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured namespace"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request(UUID.randomUUID(), Optional.empty(), NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction or synchronization"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(request(UUID.randomUUID(), Optional.empty(), NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction or synchronization"); + TransactionSynchronizationManager.clearSynchronization(); + } finally { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + TransactionSynchronizationManager.setActualTransactionActive(false); + client.close(); + } + } + + @Test + void rejectsMalformedUnknownAndChangedSourceResponses() { + UUID operation = UUID.randomUUID(); + var captured = positiveSource(operation, "1", "2"); + var request = request(operation, Optional.of(captured), NAMESPACE); + + assertThatThrownBy( + () -> + AccountIssuerAuthoritySourceClient.decodeResponse( + AccountIssuerAuthoritySourceSnapshot.newBuilder() + .setSchemaVersion(AccountIssuerSourceSnapshotEvidence.SCHEMA_VERSION) + .build(), + request, + CALLER)) + .isInstanceOf(IllegalArgumentException.class); + + var unknownResponse = + AccountIssuerSourceSnapshotGrpcCodec.toWire(captured).toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1L) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> + AccountIssuerAuthoritySourceClient.decodeResponse(unknownResponse, request, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown protobuf fields"); + + var changedSource = positiveSource(operation, "2", "3"); + assertThatThrownBy( + () -> + AccountIssuerAuthoritySourceClient.decodeResponse( + AccountIssuerSourceSnapshotGrpcCodec.toWire(changedSource), request, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact expected snapshot"); + } + + private static AccountIssuerAuthoritySourceClient newClient( + String namespace, CommonGrpcClientProperties tlsProperties) { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + ManagedChannel channel = mock(ManagedChannel.class); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + try { + when(channelFactory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(channel); + } catch (javax.net.ssl.SSLException impossible) { + throw new AssertionError(impossible); + } + return new AccountIssuerAuthoritySourceClient( + endpoints, tlsProperties, channelFactory, namespace); + } + + private static CommonGrpcClientProperties tlsProperties( + AccountIssuerAuthoritySourceClientMtlsTest.ClientTlsMaterial material) { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(material.clientCertificate().toString()); + properties.setPrivateKey(material.clientPrivateKey().toString()); + properties.setCaCert(material.caCertificate().toString()); + return properties; + } + + private static AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request( + UUID operation, Optional expected, String namespace) { + return new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, namespace, ISSUER, expected); + } + + private static AccountIssuerSourceSnapshotEvidence positiveSource( + UUID operation, String sequence, String generation) { + String event = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + operation.toString(), + operation.toString(), + STREAM, + sequence, + ISSUER, + generation, + generation, + "SIGNER_COMPROMISE")) + .canonicalJson(); + return new AccountIssuerSourceSnapshotEvidence( + operation, + NAMESPACE, + CALLER, + ISSUER, + generation, + generation, + STREAM, + sequence, + Optional.of(event)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidenceTest.java new file mode 100644 index 0000000000..9ccbf7b9e7 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotEvidenceTest.java @@ -0,0 +1,211 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AccountIssuerSourceSnapshotEvidenceTest { + private static final String NAMESPACE = "test"; + private static final String CALLER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + @Test + void sequenceZeroIsTheOriginalEnrollmentAndHasNoInventedEvent() { + var initial = snapshot(UUID.randomUUID(), "1", "1", "0", Optional.empty()); + + assertThat(initial.sourceEvent()).isEmpty(); + assertThat(initial.sourceEventBytes()).isEmpty(); + assertThatThrownBy( + () -> + snapshot( + initial.reconciliationOperationId(), + "1", + "1", + "0", + event(initial.reconciliationOperationId(), "1", "2"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence-zero"); + assertThatThrownBy( + () -> snapshot(initial.reconciliationOperationId(), "2", "1", "0", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence-zero"); + assertThatThrownBy( + () -> snapshot(initial.reconciliationOperationId(), "2", "2", "1", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires sourceEvent"); + } + + @Test + void positiveCheckpointRequiresTheExactClosedIssuerEventAndRetainsItsBytes() { + UUID operation = UUID.randomUUID(); + String wireEvent = sealedIssuerEvent(operation, "1", "2"); + var evidence = snapshot(operation, "2", "2", "1", Optional.of(wireEvent)); + + assertThat(evidence.sourceEvent()).contains(wireEvent); + byte[] first = evidence.sourceEventBytes().orElseThrow(); + first[0] = 0; + assertThat(evidence.sourceEventBytes().orElseThrow()) + .isEqualTo(wireEvent.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + assertThat(AccountAuthoritySourceEventV1Codec.verify(evidence.sourceEvent().orElseThrow())) + .isInstanceOf(AccountAuthoritySourceEventV1Codec.IssuerEvent.class); + } + + @Test + void acceptsHistoricalEventIdentityIndependentFromReconciliationOperation() { + UUID operation = UUID.randomUUID(); + String historicalEventId = "retained-source-event-17"; + String wireEvent = sealedIssuerEvent(historicalEventId, historicalEventId, "1", "2"); + + var evidence = snapshot(operation, "2", "2", "1", Optional.of(wireEvent)); + + assertThat(evidence.reconciliationOperationId().toString()).isNotEqualTo(historicalEventId); + var issuerEvent = + (AccountAuthoritySourceEventV1Codec.IssuerEvent) + AccountAuthoritySourceEventV1Codec.verify(evidence.sourceEvent().orElseThrow()); + assertThat(issuerEvent.eventId()).isEqualTo(historicalEventId); + assertThat(issuerEvent.requestId()).isEqualTo(historicalEventId); + } + + @Test + void rejectsEventIdentityIssuerCheckpointAndSchemaDrift() { + UUID operation = UUID.randomUUID(); + String mismatchedEventIdentity = + sealedIssuerEvent("retained-source-event-17", "different-request-17", "1", "2"); + String wrongCheckpointEvent = sealedIssuerEvent(operation, "2", "3"); + String accountEvent = + AccountAuthoritySourceEventV1Codec.sealAccount( + new AccountAuthoritySourceEventV1Codec.AccountPreimage( + operation.toString(), + operation.toString(), + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + + "account/" + + "11111111-1111-4111-8111-111111111111", + "1", + "11111111-1111-4111-8111-111111111111", + "2", + "2", + "2", + "2", + java.util.List.of("PASSWORD_RESET"), + new AccountAuthoritySourceEventV1Codec.AccountState( + true, java.util.List.of("PASSWORD"), "player", "ACTIVE"))) + .canonicalJson(); + + assertThatThrownBy( + () -> snapshot(operation, "2", "2", "1", Optional.of(mismatchedEventIdentity))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventId must equal requestId"); + assertThatThrownBy(() -> snapshot(operation, "2", "2", "1", Optional.of(wrongCheckpointEvent))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exactly match"); + assertThatThrownBy(() -> snapshot(operation, "2", "2", "1", Optional.of(accountEvent))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsNoncanonicalDuplicateUnknownAndTrailingEventFields() { + UUID operation = UUID.randomUUID(); + String canonical = sealedIssuerEvent(operation, "1", "2"); + String unknown = canonical.substring(0, canonical.length() - 1) + ",\"z\":true}"; + String duplicate = canonical.replaceFirst("\\{", "{\"eventId\":\"duplicate\","); + String noncanonical = " " + canonical; + String trailing = canonical + " {}"; + + for (String malformed : java.util.List.of(unknown, duplicate, noncanonical, trailing)) { + assertThatThrownBy(() -> snapshot(operation, "2", "2", "1", Optional.of(malformed))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> snapshot(operation, "2", "2", "1", Optional.of(noncanonical))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire JSON is not the exact canonical encoding"); + } + + @Test + void comparesLargeCanonicalCountersWithoutFloatingPointOrLongCoercion() { + UUID operation = UUID.randomUUID(); + String sequence = "9007199254740992"; + String generation = new BigInteger(sequence).add(BigInteger.ONE).toString(); + String wireEvent = sealedIssuerEvent(operation, sequence, generation); + + var evidence = snapshot(operation, generation, generation, sequence, Optional.of(wireEvent)); + + assertThat(evidence.lastCommittedOutboxSequence()).isEqualTo("9007199254740992"); + assertThat(evidence.issuerAuthGeneration()).isEqualTo("9007199254740993"); + } + + @Test + void rejectsNoncanonicalCountersWrongCallerNamespaceIssuerAndNilOperation() { + UUID operation = UUID.randomUUID(); + assertThatThrownBy(() -> snapshot(operation, "01", "1", "0", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical decimal"); + assertThatThrownBy(() -> snapshot(operation, "1", "1", "00", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical decimal"); + assertThatThrownBy( + () -> + new AccountIssuerSourceSnapshotEvidence( + operation, + NAMESPACE, + "spiffe://firemud/ns/other/sa/game-session-service", + ISSUER, + "1", + "1", + STREAM, + "0", + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("same-namespace"); + assertThatThrownBy( + () -> + new AccountIssuerSourceSnapshotEvidence( + operation, + NAMESPACE, + CALLER, + "other-issuer", + "1", + "1", + STREAM, + "0", + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("supported Account issuer"); + assertThatThrownBy(() -> snapshot(new UUID(0L, 0L), "1", "1", "0", Optional.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil"); + } + + private static AccountIssuerSourceSnapshotEvidence snapshot( + UUID operation, String generation, String version, String sequence, Optional event) { + return new AccountIssuerSourceSnapshotEvidence( + operation, NAMESPACE, CALLER, ISSUER, generation, version, STREAM, sequence, event); + } + + private static Optional event(UUID operation, String sequence, String generation) { + return Optional.of(sealedIssuerEvent(operation, sequence, generation)); + } + + private static String sealedIssuerEvent(UUID operation, String sequence, String generation) { + return sealedIssuerEvent(operation.toString(), operation.toString(), sequence, generation); + } + + private static String sealedIssuerEvent( + String eventId, String requestId, String sequence, String generation) { + return AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + eventId, + requestId, + STREAM, + sequence, + ISSUER, + generation, + generation, + "SIGNER_COMPROMISE")) + .canonicalJson(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodecTest.java new file mode 100644 index 0000000000..9705f00aaa --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountIssuerSourceSnapshotGrpcCodecTest.java @@ -0,0 +1,273 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.math.BigInteger; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountIssuerAuthoritySourceSnapshot; +import org.junit.jupiter.api.Test; + +class AccountIssuerSourceSnapshotGrpcCodecTest { + private static final String NAMESPACE = "test"; + private static final String CALLER = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ISSUER = AccountIssuerSourceSnapshotEvidence.ISSUER_ID; + private static final String STREAM = AccountIssuerSourceSnapshotEvidence.ISSUER_STREAM_KEY; + + @Test + void initialRequestAndZeroCheckpointResponseRoundTripWithoutEventPresence() { + UUID operation = UUID.randomUUID(); + var request = request(operation, Optional.empty()); + var wireRequest = AccountIssuerSourceSnapshotGrpcCodec.toRequest(request, NAMESPACE, CALLER); + var parsedRequest = + AccountIssuerSourceSnapshotGrpcCodec.fromRequest(wireRequest, NAMESPACE, CALLER); + var source = snapshot(operation, "1", "1", "0", Optional.empty()); + var wireResponse = + AccountIssuerSourceSnapshotGrpcCodec.toResponse(source, parsedRequest, CALLER); + var parsedResponse = + AccountIssuerSourceSnapshotGrpcCodec.fromResponse(wireResponse, parsedRequest, CALLER); + + assertThat(parsedRequest).isEqualTo(request); + assertThat(wireResponse.hasSourceEvent()).isFalse(); + assertThat(parsedResponse).isEqualTo(source); + } + + @Test + void expectedSourceRevalidationAcceptsOnlyTheWholeExactCarrier() { + UUID operation = UUID.randomUUID(); + var captured = advanced(operation, "1", "2"); + var request = request(operation, Optional.of(captured)); + var wireRequest = AccountIssuerSourceSnapshotGrpcCodec.toRequest(request, NAMESPACE, CALLER); + var parsedRequest = + AccountIssuerSourceSnapshotGrpcCodec.fromRequest(wireRequest, NAMESPACE, CALLER); + + assertThat(parsedRequest.expectedSource()).contains(captured); + assertThat( + AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + AccountIssuerSourceSnapshotGrpcCodec.toResponse(captured, parsedRequest, CALLER), + parsedRequest, + CALLER)) + .isEqualTo(captured); + + var changedCheckpoint = advanced(operation, "2", "3"); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + AccountIssuerSourceSnapshotGrpcCodec.toWire(changedCheckpoint), + parsedRequest, + CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact expected snapshot"); + + var changedEvent = + snapshot( + operation, + "2", + "2", + "1", + Optional.of( + sealedIssuerEvent( + "different-retained-event", "different-retained-event", "1", "2"))); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + AccountIssuerSourceSnapshotGrpcCodec.toWire(changedEvent), + parsedRequest, + CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact expected snapshot"); + } + + @Test + void rejectsOperationCallerNamespaceAndExpectedSnapshotScopeChanges() { + UUID operation = UUID.randomUUID(); + var initial = snapshot(operation, "1", "1", "0", Optional.empty()); + var request = request(operation, Optional.empty()); + var otherOperation = request(UUID.randomUUID(), Optional.empty()); + var wireInitial = AccountIssuerSourceSnapshotGrpcCodec.toWire(initial); + + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + wireInitial, otherOperation, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match the request scope"); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromResponse( + wireInitial, request, "spiffe://firemud/ns/other/sa/game-session-service")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("same-namespace"); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.toRequest( + request, "other", "spiffe://firemud/ns/other/sa/game-session-service")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured namespace"); + assertThatThrownBy( + () -> + request( + operation, + Optional.of(snapshot(UUID.randomUUID(), "1", "1", "0", Optional.empty())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match the request scope"); + } + + @Test + void rejectsUnknownFieldsAtRequestSnapshotAndNestedExpectedSnapshotBoundaries() { + UUID operation = UUID.randomUUID(); + var request = request(operation, Optional.empty()); + var wireRequest = AccountIssuerSourceSnapshotGrpcCodec.toRequest(request, NAMESPACE, CALLER); + var unknownRequest = wireRequest.toBuilder().setUnknownFields(oneUnknownField()).build(); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromRequest(unknownRequest, NAMESPACE, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown protobuf fields"); + + var source = snapshot(operation, "1", "1", "0", Optional.empty()); + var wireSource = AccountIssuerSourceSnapshotGrpcCodec.toWire(source); + var unknownSnapshot = wireSource.toBuilder().setUnknownFields(oneUnknownField()).build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(unknownSnapshot)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown protobuf fields"); + + var expectedRequest = request(operation, Optional.of(source)); + var nestedUnknown = wireSource.toBuilder().setUnknownFields(oneUnknownField()).build(); + var outerWithNestedUnknown = + AccountIssuerSourceSnapshotGrpcCodec.toRequest(expectedRequest, NAMESPACE, CALLER) + .toBuilder() + .setExpectedSource(nestedUnknown) + .build(); + assertThatThrownBy( + () -> + AccountIssuerSourceSnapshotGrpcCodec.fromRequest( + outerWithNestedUnknown, NAMESPACE, CALLER)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown protobuf fields"); + } + + @Test + void rejectsMalformedUtf8UnknownEventFieldsAndOversizedSourcePayload() { + UUID operation = UUID.randomUUID(); + var malformedUtf8 = + advancedWire(operation).toBuilder() + .setSourceEvent(ByteString.copyFrom(new byte[] {(byte) 0xc3, 0x28})) + .build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(malformedUtf8)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("malformed UTF-8"); + + String event = sealedIssuerEvent(operation, "1", "2"); + String unknownJson = event.substring(0, event.length() - 1) + ",\"z\":true}"; + var unknownEvent = + advancedWire(operation).toBuilder() + .setSourceEvent(ByteString.copyFromUtf8(unknownJson)) + .build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(unknownEvent)) + .isInstanceOf(IllegalArgumentException.class); + + var oversized = + advancedWire(operation).toBuilder() + .setSourceEvent(ByteString.copyFrom(new byte[64 * 1024 + 1])) + .build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(oversized)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("64 KiB"); + } + + @Test + void roundTripsLargeCountersAsExactDecimalStrings() { + UUID operation = UUID.randomUUID(); + String sequence = "9007199254740992"; + String generation = new BigInteger(sequence).add(BigInteger.ONE).toString(); + var source = advanced(operation, sequence, generation); + + assertThat( + AccountIssuerSourceSnapshotGrpcCodec.fromWire( + AccountIssuerSourceSnapshotGrpcCodec.toWire(source))) + .isEqualTo(source); + } + + @Test + void rejectsAbsentOrChangedSourceOnPositiveSequenceAndCounterDrift() { + UUID operation = UUID.randomUUID(); + var valid = advanced(operation, "1", "2"); + var absent = + AccountIssuerAuthoritySourceSnapshot.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setCallerWorkload(CALLER) + .setReconciliationOperationId(operation.toString()) + .setIssuerId(ISSUER) + .setIssuerAuthGeneration("2") + .setSourceVersion("2") + .setOutboxStreamKey(STREAM) + .setLastCommittedOutboxSequence("1") + .build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(absent)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires sourceEvent"); + + var wrongSequence = + AccountIssuerSourceSnapshotGrpcCodec.toWire(valid).toBuilder() + .setLastCommittedOutboxSequence("2") + .build(); + assertThatThrownBy(() -> AccountIssuerSourceSnapshotGrpcCodec.fromWire(wrongSequence)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UnknownFieldSet oneUnknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static AccountIssuerSourceSnapshotGrpcCodec.ReadRequest request( + UUID operation, Optional expected) { + return new AccountIssuerSourceSnapshotGrpcCodec.ReadRequest( + operation, NAMESPACE, ISSUER, expected); + } + + private static AccountIssuerSourceSnapshotEvidence snapshot( + UUID operation, String generation, String version, String sequence, Optional event) { + return new AccountIssuerSourceSnapshotEvidence( + operation, NAMESPACE, CALLER, ISSUER, generation, version, STREAM, sequence, event); + } + + private static AccountIssuerSourceSnapshotEvidence advanced( + UUID operation, String sequence, String generation) { + return snapshot( + operation, + generation, + generation, + sequence, + Optional.of(sealedIssuerEvent(operation, sequence, generation))); + } + + private static AccountIssuerAuthoritySourceSnapshot advancedWire(UUID operation) { + return AccountIssuerSourceSnapshotGrpcCodec.toWire(advanced(operation, "1", "2")); + } + + private static String sealedIssuerEvent(UUID operation, String sequence, String generation) { + return sealedIssuerEvent(operation.toString(), operation.toString(), sequence, generation); + } + + private static String sealedIssuerEvent( + String eventId, String requestId, String sequence, String generation) { + return AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + eventId, + requestId, + STREAM, + sequence, + ISSUER, + generation, + generation, + "SIGNER_COMPROMISE")) + .canonicalJson(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java new file mode 100644 index 0000000000..c7cdff15e9 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java @@ -0,0 +1,699 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; + +class DraftAuthorizationFenceBindingCodecTest { + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID SOURCE_SCOPE_ID = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final String EXPECTED_DRAFT_EPOCH = "9007199254741009"; + private static final String LARGE_SOURCE_VERSION = "9007199254740993"; + private static final String GAME_DESIGN_DIGEST = + "sha256:2a6fe4b88eb642dac5eb64b04d0123d11a4944ec94f4b4304f9416753c09742f"; + private static final String FENCE_DIGEST = + "sha256:1ee6345cf8420f08f59f4570a62bef8b149b56f12c5b0c66ba5d3f77bd57b7e2"; + private static final String GAME_DESIGN_JSON = + "{\"affectedUnits\":[{\"aggregateId\":\"world-1\",\"aggregateType\":\"WORLD_TEMPLATE\"," + + "\"expectedEpoch\":\"0\",\"owner\":\"WORLD_MANAGEMENT\",\"scopeId\":\"room-1\"," + + "\"scopeType\":\"ROOM_SCOPE\"}],\"baseCommitId\":\"base-source-1\"," + + "\"canonicalTenantId\":\"11111111-1111-4111-8111-111111111111\"," + + "\"canonicalVersionId\":\"22222222-2222-4222-8222-222222222222\"," + + "\"commitId\":\"55555555-5555-4555-8555-555555555555\"," + + "\"requestId\":\"44444444-4444-4444-8444-444444444444\"," + + "\"requiredOwners\":[\"WORLD_MANAGEMENT\"],\"revisions\":[{" + + "\"owner\":\"WORLD_MANAGEMENT\",\"payload\":\"{}\"," + + "\"revisionId\":\"66666666-6666-4666-8666-666666666666\"," + + "\"revisionOrder\":\"0\"}],\"schemaVersion\":\"1\",\"target\":{" + + "\"gameDesignVersionRowId\":\"19\",\"gameDesignVersionTenantKey\":\"tenant-key\"," + + "\"sourceGameRowId\":\"42\",\"sourceGameTenantKey\":\"tenant-key\"," + + "\"sourceProvenanceKind\":\"NEW_GAME_ROW\"}}"; + + @Test + void preservesV57ProducerGoldenBytesAndDigestAndRoundTripsEveryField() { + DraftAuthorizationFenceBinding original = binding(List.of(source())); + byte[] golden = goldenBytes(); + + assertThat(original.gameDesignBinding()) + .containsExactly(GAME_DESIGN_JSON.getBytes(StandardCharsets.UTF_8)); + assertThat(original.inputDigest()).isEqualTo(GAME_DESIGN_DIGEST); + assertThat(original.canonicalBytes()).containsExactly(golden); + assertThat(DraftAuthorizationFenceBinding.digest(golden)).isEqualTo(FENCE_DIGEST); + + DraftAuthorizationFenceBinding restored = DraftAuthorizationFenceBinding.fromStored(golden); + assertBindingValues(original, restored); + assertThat(restored.canonicalBytes()).containsExactly(golden); + assertThat(restored.schemaVersion()).isEqualTo(DraftAuthorizationFenceBinding.SCHEMA_V1); + assertThat(restored.requiredOwners()) + .containsExactly( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD); + } + + @Test + void v2BindsWorldAndEntityAndRoundTripsTheCanonicalRequiredOwnerSet() { + DraftAuthorizationFenceBinding original = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + List expectedOwners = + List.of( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Owner.ENTITY); + + assertThat(original.schemaVersion()).isEqualTo(DraftAuthorizationFenceBinding.SCHEMA_V2); + assertThat(original.requiredOwners()).containsExactlyElementsOf(expectedOwners); + assertThat(original.canonicalBytes()).containsExactly(goldenV2Bytes(original, expectedOwners)); + + DraftAuthorizationFenceBinding restored = + DraftAuthorizationFenceBinding.fromStored(original.canonicalBytes()); + assertBindingValues(original, restored); + assertThat(restored.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(restored.requiredOwners()).containsExactlyElementsOf(expectedOwners); + } + + @Test + void v2MapsEveryCommitOwnerAndAlwaysIncludesTheGameDesignCoordinator() { + DraftAuthorizationFenceBinding multiOwner = + bindingForOwners(Arrays.asList(Owner.values())).withRequiredOwners(); + assertThat(multiOwner.requiredOwners()) + .containsExactly( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Owner.ENTITY, + DraftAuthorizationFenceBinding.Owner.GAME_LOGIC, + DraftAuthorizationFenceBinding.Owner.AUTOMATION); + assertBindingValues( + multiOwner, DraftAuthorizationFenceBinding.fromStored(multiOwner.canonicalBytes())); + + DraftAuthorizationFenceBinding controlPlaneOnly = + bindingForOwners(List.of(Owner.GAME_DESIGN_CONTROL_PLANE)).withRequiredOwners(); + assertThat(controlPlaneOnly.requiredOwners()) + .containsExactly(DraftAuthorizationFenceBinding.Owner.GAME_DESIGN); + assertBindingValues( + controlPlaneOnly, + DraftAuthorizationFenceBinding.fromStored(controlPlaneOnly.canonicalBytes())); + } + + @Test + void v2RejectsMissingExtraUnknownReorderedAndSubstitutedOwners() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + List canonicalFrames = readFrames(binding.canonicalBytes()); + + List missing = new ArrayList<>(canonicalFrames); + missing.set(16, utf8("2")); + missing.remove(missing.size() - 1); + assertInvalid(writeFrames(missing)); + + List extra = new ArrayList<>(canonicalFrames); + extra.set(16, utf8("4")); + extra.add(utf8("AUTOMATION")); + assertInvalid(writeFrames(extra)); + + List unknown = new ArrayList<>(canonicalFrames); + unknown.set(18, utf8("UNKNOWN_OWNER")); + assertInvalid(writeFrames(unknown)); + + List reordered = new ArrayList<>(canonicalFrames); + byte[] gameDesign = reordered.get(17); + reordered.set(17, reordered.get(18)); + reordered.set(18, gameDesign); + assertInvalid(writeFrames(reordered)); + + List substituted = new ArrayList<>(canonicalFrames); + substituted.set(18, utf8("GAME_LOGIC")); + assertInvalid(writeFrames(substituted)); + } + + @Test + void v2RejectsChangedCompleteBindingAndNoncanonicalOwnerCount() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + List changedInput = readFrames(binding.canonicalBytes()); + changedInput.set(11, utf8("{}")); + assertInvalid(writeFrames(changedInput)); + + List noncanonicalCount = readFrames(binding.canonicalBytes()); + noncanonicalCount.set(16, utf8("03")); + assertInvalid(writeFrames(noncanonicalCount)); + + List excessiveCount = readFrames(binding.canonicalBytes()); + excessiveCount.set(16, utf8("999999999999999999999999999999999999")); + assertInvalid(writeFrames(excessiveCount)); + } + + @Test + void v2OwnerReadbackUsesMatchingVersionAndOnlyAllowsRequiredOwners() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT)) + .withRequiredOwners(); + var worldReadback = + ownerReadback(binding, DraftAuthorizationFenceBinding.Owner.WORLD, new byte[] {1}); + List frames = readFrames(worldReadback.canonicalBytes()); + assertThat(new String(frames.get(0), StandardCharsets.UTF_8)) + .isEqualTo("account-draft-owner-readback/v2"); + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(worldReadback.canonicalBytes()) + .requireBinding(binding); + + var wrongOwner = new ArrayList<>(frames); + wrongOwner.set(1, utf8("AUTOMATION")); + assertThatThrownBy( + () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(wrongOwner))) + .isInstanceOf(IllegalArgumentException.class); + + for (int field : List.of(3, 4, 5, 6, 7)) { + var changedBinding = new ArrayList<>(frames); + changedBinding.set( + field, + switch (field) { + case 3, 4, 5 -> utf8("99999999-9999-4999-8999-999999999999"); + case 6 -> utf8("sha256:" + "f".repeat(64)); + default -> binding(List.of(source())).canonicalBytes(); + }); + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + writeFrames(changedBinding))) + .isInstanceOf(IllegalArgumentException.class); + } + + var mismatchedVersion = new ArrayList<>(frames); + mismatchedVersion.set(0, utf8("account-draft-owner-readback/v1")); + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + writeFrames(mismatchedVersion))) + .isInstanceOf(IllegalArgumentException.class); + + var changedResult = new ArrayList<>(frames); + changedResult.set(changedResult.size() - 1, new byte[] {2}); + var changedReadback = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(changedResult)); + assertThat(changedReadback.result()).containsExactly((byte) 2); + assertThat(changedReadback.canonicalBytes()).containsExactly(writeFrames(changedResult)); + assertThat(changedReadback.canonicalBytes()).isNotEqualTo(worldReadback.canonicalBytes()); + } + + @Test + void v1OwnerReadbackSchemaCannotBeSubstitutedForV2Binding() { + DraftAuthorizationFenceBinding binding = + bindingForOwners(List.of(Owner.WORLD_MANAGEMENT)).withRequiredOwners(); + var readback = + ownerReadback(binding, DraftAuthorizationFenceBinding.Owner.WORLD, new byte[] {1}); + List frames = readFrames(readback.canonicalBytes()); + frames.set(0, utf8("account-draft-owner-readback/v1")); + assertThatThrownBy( + () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(frames))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void aDifferentCanonicalOperationDecodesAsDifferentImmutableDataNotAuthorization() { + DraftAuthorizationFenceBinding original = binding(List.of(source())); + List frames = readFrames(original.canonicalBytes()); + frames.set(1, utf8("99999999-9999-4999-8999-999999999999")); + byte[] changedOperation = writeFrames(frames); + + DraftAuthorizationFenceBinding restored = + DraftAuthorizationFenceBinding.fromStored(changedOperation); + + assertThat(restored.operationId()).isNotEqualTo(original.operationId()); + assertThat(restored.canonicalBytes()).containsExactly(changedOperation); + assertThat(DraftAuthorizationFenceBinding.digest(restored.canonicalBytes())) + .isNotEqualTo(DraftAuthorizationFenceBinding.digest(original.canonicalBytes())); + } + + @Test + void rejectsOperationSourceOrderDigestTargetAndCounterSubstitutions() { + byte[] original = goldenBytes(); + + List nilOperation = readFrames(original); + nilOperation.set(1, utf8("00000000-0000-0000-0000-000000000000")); + assertInvalid(writeFrames(nilOperation)); + + List noncanonicalOperation = readFrames(original); + noncanonicalOperation.set(1, utf8("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA")); + assertInvalid(writeFrames(noncanonicalOperation)); + + List changedDigest = readFrames(original); + changedDigest.set(13, utf8("sha256:" + "f".repeat(64))); + assertInvalid(writeFrames(changedDigest)); + + List changedTenant = readFrames(original); + changedTenant.set(6, utf8("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee")); + assertInvalid(writeFrames(changedTenant)); + + List reorderedOwners = readFrames(original); + byte[] gameDesignOwner = reorderedOwners.get(16); + reorderedOwners.set(16, reorderedOwners.get(17)); + reorderedOwners.set(17, gameDesignOwner); + assertInvalid(writeFrames(reorderedOwners)); + + List noncanonicalEpoch = readFrames(original); + noncanonicalEpoch.set(10, utf8("09007199254741009")); + assertInvalid(writeFrames(noncanonicalEpoch)); + + List noncanonicalCount = readFrames(original); + noncanonicalCount.set(14, utf8("01")); + assertInvalid(writeFrames(noncanonicalCount)); + + List excessiveCount = readFrames(original); + excessiveCount.set(14, utf8("999999999999999999999999999999999999")); + assertInvalid(writeFrames(excessiveCount)); + } + + @Test + void rejectsReorderedSourceVectorAndMalformedStoredFrames() { + DraftAuthorizationFenceBinding twoSources = binding(List.of(source(), accountSource())); + List reversedSources = readFrames(twoSources.canonicalBytes()); + byte[] firstSource = reversedSources.get(15); + reversedSources.set(15, reversedSources.get(16)); + reversedSources.set(16, firstSource); + assertInvalid(writeFrames(reversedSources)); + + List invalidUtf8 = readFrames(goldenBytes()); + invalidUtf8.set(8, new byte[] {(byte) 0xc3, 0x28}); + assertInvalid(writeFrames(invalidUtf8)); + + List unknownSchema = readFrames(goldenBytes()); + unknownSchema.set(0, utf8("account-draft-authorization-fence/v2")); + assertInvalid(writeFrames(unknownSchema)); + + byte[] golden = goldenBytes(); + assertInvalid(Arrays.copyOf(golden, golden.length - 1)); + byte[] trailing = Arrays.copyOf(golden, golden.length + 1); + trailing[trailing.length - 1] = 1; + assertInvalid(trailing); + + byte[] negativeLength = golden.clone(); + ByteBuffer.wrap(negativeLength).putInt(0, -1); + assertInvalid(negativeLength); + byte[] oversizedLength = golden.clone(); + ByteBuffer.wrap(oversizedLength).putInt(0, Integer.MAX_VALUE); + assertInvalid(oversizedLength); + } + + @Test + void ownerReadbackRoundTripsExactBytesAndOriginalBindingForEveryOutcome() { + var binding = binding(List.of(source())); + for (var owner : + List.of( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD)) { + for (var outcome : DraftAuthorizationFenceBinding.Outcome.values()) { + var original = + new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {1, 2, 3}); + var decoded = + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(original.canonicalBytes()); + decoded.requireBinding(binding); + assertThat(decoded.owner()).isEqualTo(owner); + assertThat(decoded.outcome()).isEqualTo(outcome); + assertThat(decoded.result()).containsExactly(new byte[] {1, 2, 3}); + assertThat(decoded.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(original.canonicalBytes()) + .containsExactly(goldenOwnerReadbackV1(binding, owner, outcome, new byte[] {1, 2, 3})); + } + } + } + + @Test + void ownerReadbackRejectsCorruptFramingNoncanonicalFieldsAndContradictoryBinding() { + var binding = binding(List.of(source())); + var original = + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {1}); + byte[] bytes = original.canonicalBytes(); + for (int field : List.of(0, 1, 2, 3, 4, 5, 6, 7, 8)) { + var fields = readFrames(bytes); + fields.set( + field, + switch (field) { + case 0 -> utf8("account-draft-owner-readback/v2"); + case 1 -> utf8("world"); + case 2 -> utf8("UNKNOWN"); + case 3 -> utf8(binding.operationId().toString().toUpperCase(java.util.Locale.ROOT)); + case 4, 5 -> utf8("99999999-9999-4999-8999-999999999999"); + case 6 -> utf8("sha256:" + "f".repeat(64)); + case 7 -> new byte[] {1}; + default -> new byte[0]; + }); + assertThatThrownBy( + () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(fields))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + Arrays.copyOf(bytes, bytes.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + Arrays.copyOf(bytes, bytes.length + 1))) + .isInstanceOf(IllegalArgumentException.class); + byte[] negative = bytes.clone(); + ByteBuffer.wrap(negative).putInt(-1); + assertThatThrownBy(() -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(negative)) + .isInstanceOf(IllegalArgumentException.class); + var invalidUtf8 = readFrames(bytes); + invalidUtf8.set(1, new byte[] {(byte) 0xc3, 0x28}); + assertThatThrownBy( + () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(invalidUtf8))) + .isInstanceOf(IllegalArgumentException.class); + + var expandedV1Owner = readFrames(bytes); + expandedV1Owner.set(1, utf8("ENTITY")); + assertThatThrownBy( + () -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + writeFrames(expandedV1Owner))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertBindingValues( + DraftAuthorizationFenceBinding expected, DraftAuthorizationFenceBinding actual) { + assertThat(actual.operationId()).isEqualTo(expected.operationId()); + assertThat(actual.requestId()).isEqualTo(expected.requestId()); + assertThat(actual.commitId()).isEqualTo(expected.commitId()); + assertThat(actual.fenceId()).isEqualTo(expected.fenceId()); + assertThat(actual.actorAccountId()).isEqualTo(expected.actorAccountId()); + assertThat(actual.tenantId()).isEqualTo(expected.tenantId()); + assertThat(actual.versionId()).isEqualTo(expected.versionId()); + assertThat(actual.baseCommitId()).isEqualTo(expected.baseCommitId()); + assertThat(actual.expectedDraftEpoch()).isEqualTo(expected.expectedDraftEpoch()); + assertThat(actual.gameDesignBinding()).containsExactly(expected.gameDesignBinding()); + assertThat(actual.normalizedInput()).containsExactly(expected.normalizedInput()); + assertThat(actual.inputDigest()).isEqualTo(expected.inputDigest()); + assertThat(actual.schemaVersion()).isEqualTo(expected.schemaVersion()); + assertThat(actual.requiredOwners()).containsExactlyElementsOf(expected.requiredOwners()); + assertThat(actual.sources()).hasSize(expected.sources().size()); + for (int index = 0; index < expected.sources().size(); index++) { + SourceEvidence expectedSource = expected.sources().get(index); + SourceEvidence actualSource = actual.sources().get(index); + assertThat(actualSource.kind()).isEqualTo(expectedSource.kind()); + assertThat(actualSource.scopeId()).isEqualTo(expectedSource.scopeId()); + assertThat(actualSource.generation()).isEqualTo(expectedSource.generation()); + assertThat(actualSource.sourceVersion()).isEqualTo(expectedSource.sourceVersion()); + assertThat(actualSource.checkpointStream()).isEqualTo(expectedSource.checkpointStream()); + assertThat(actualSource.checkpointSequence()).isEqualTo(expectedSource.checkpointSequence()); + assertThat(actualSource.evidence()).containsExactly(expectedSource.evidence()); + } + } + + private static DraftAuthorizationFenceBinding binding(List sources) { + DraftCommitBinding gameDesign = gameDesignBinding(); + byte[] gameDesignBytes = gameDesign.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-source-1", + EXPECTED_DRAFT_EPOCH, + gameDesignBytes, + gameDesignBytes, + gameDesign.digest(), + sources); + } + + private static DraftCommitBinding gameDesignBinding() { + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-source-1", + List.of(new RevisionPayload("0", REVISION_ID, Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, "WORLD_TEMPLATE", "world-1", "ROOM_SCOPE", "room-1", "0"))); + } + + private static DraftAuthorizationFenceBinding bindingForOwners(List owners) { + DraftCommitBinding gameDesign = gameDesignBinding(owners); + byte[] gameDesignBytes = gameDesign.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-source-1", + EXPECTED_DRAFT_EPOCH, + gameDesignBytes, + gameDesignBytes, + gameDesign.digest(), + List.of(source())); + } + + private static DraftCommitBinding gameDesignBinding(List owners) { + List revisions = new ArrayList<>(); + List affectedUnits = new ArrayList<>(); + for (int index = 0; index < owners.size(); index++) { + Owner owner = owners.get(index); + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.nameUUIDFromBytes(("revision-" + owner.name()).getBytes(StandardCharsets.UTF_8)), + owner, + "{}")); + affectedUnits.add( + new AffectedUnit( + owner, + "TEST_AGGREGATE", + owner.name().toLowerCase(java.util.Locale.ROOT), + "TEST_SCOPE", + "scope-" + owner.name().toLowerCase(java.util.Locale.ROOT), + "0")); + } + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-source-1", + revisions, + affectedUnits); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback ownerReadback( + DraftAuthorizationFenceBinding binding, + DraftAuthorizationFenceBinding.Owner owner, + byte[] result) { + return new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + result); + } + + private static byte[] goldenV2Bytes( + DraftAuthorizationFenceBinding binding, + List requiredOwners) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + appendFrame(output, DraftAuthorizationFenceBinding.SCHEMA_V2); + for (String value : + List.of( + binding.operationId().toString(), + binding.requestId().toString(), + binding.commitId().toString(), + binding.fenceId().toString(), + binding.actorAccountId().toString(), + binding.tenantId().toString(), + binding.versionId().toString(), + binding.baseCommitId(), + "DRAFT", + binding.expectedDraftEpoch())) { + appendFrame(output, value); + } + appendFrame(output, binding.gameDesignBinding()); + appendFrame(output, binding.normalizedInput()); + appendFrame(output, binding.inputDigest()); + appendFrame(output, Integer.toString(binding.sources().size())); + binding.sources().forEach(source -> appendFrame(output, source.canonicalBytes())); + appendFrame(output, Integer.toString(requiredOwners.size())); + requiredOwners.forEach(owner -> appendFrame(output, owner.name())); + return output.toByteArray(); + } + + private static byte[] goldenOwnerReadbackV1( + DraftAuthorizationFenceBinding binding, + DraftAuthorizationFenceBinding.Owner owner, + DraftAuthorizationFenceBinding.Outcome outcome, + byte[] result) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : + List.of( + "account-draft-owner-readback/v1", + owner.name(), + outcome.name(), + binding.operationId().toString(), + binding.commitId().toString(), + binding.fenceId().toString(), + binding.inputDigest())) { + appendFrame(output, value); + } + appendFrame(output, binding.canonicalBytes()); + appendFrame(output, result); + return output.toByteArray(); + } + + private static SourceEvidence source() { + return new SourceEvidence( + SourceKind.GLOBAL_ROLES, + SOURCE_SCOPE_ID.toString(), + null, + LARGE_SOURCE_VERSION, + null, + null, + new byte[] {1, 2, 3}); + } + + private static SourceEvidence accountSource() { + return new SourceEvidence( + SourceKind.ACCOUNT, + "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", + "1", + "2", + "account:source", + "0", + new byte[] {4, 5}); + } + + private static byte[] goldenBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (String value : + List.of( + "account-draft-authorization-fence/v1", + OPERATION_ID.toString(), + REQUEST_ID.toString(), + COMMIT_ID.toString(), + FENCE_ID.toString(), + ACTOR_ID.toString(), + TENANT_ID.toString(), + VERSION_ID.toString(), + "base-source-1", + "DRAFT", + EXPECTED_DRAFT_EPOCH)) { + appendFrame(output, value); + } + byte[] gameDesign = GAME_DESIGN_JSON.getBytes(StandardCharsets.UTF_8); + appendFrame(output, gameDesign); + appendFrame(output, gameDesign); + appendFrame(output, GAME_DESIGN_DIGEST); + appendFrame(output, "1"); + appendFrame(output, goldenSourceBytes()); + appendFrame(output, "GAME_DESIGN"); + appendFrame(output, "WORLD"); + return output.toByteArray(); + } + + private static byte[] goldenSourceBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + appendFrame(output, "account-draft-source-evidence/v1"); + appendFrame(output, "GLOBAL_ROLES"); + appendFrame(output, SOURCE_SCOPE_ID.toString()); + appendFrame(output, "ABSENT"); + appendFrame(output, LARGE_SOURCE_VERSION); + appendFrame(output, "ABSENT"); + appendFrame(output, new byte[] {1, 2, 3}); + return output.toByteArray(); + } + + private static List readFrames(byte[] stored) { + ByteBuffer input = ByteBuffer.wrap(stored); + List frames = new ArrayList<>(); + while (input.hasRemaining()) { + if (input.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("Incomplete test frame"); + } + int length = input.getInt(); + if (length < 0 || length > input.remaining()) { + throw new IllegalArgumentException("Invalid test frame length"); + } + byte[] frame = new byte[length]; + input.get(frame); + frames.add(frame); + } + return frames; + } + + private static byte[] writeFrames(List frames) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + frames.forEach(frame -> appendFrame(output, frame)); + return output.toByteArray(); + } + + private static void appendFrame(ByteArrayOutputStream output, String value) { + appendFrame(output, utf8(value)); + } + + private static void appendFrame(ByteArrayOutputStream output, byte[] value) { + output.write((value.length >>> 24) & 0xff); + output.write((value.length >>> 16) & 0xff); + output.write((value.length >>> 8) & 0xff); + output.write(value.length & 0xff); + output.writeBytes(value); + } + + private static byte[] utf8(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static void assertInvalid(byte[] stored) { + assertThatThrownBy(() -> DraftAuthorizationFenceBinding.fromStored(stored)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClientTest.java new file mode 100644 index 0000000000..f57193a434 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClientTest.java @@ -0,0 +1,181 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.stub.AbstractStub; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +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.GrpcServerPeerIdentityCallCredentials; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class GameDesignDraftTerminalReadClientTest { + @Test + void rejectsPlaintextBeforeCreatingChannel(@TempDir Path directory) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties tls = tls(directory); + tls.setPlaintext(true); + + assertThatThrownBy( + () -> + new GameDesignDraftTerminalReadClient( + new ServiceEndpointsProperties(), tls, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsWrongNamespaceAndUninitializedUseBeforeTransport(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignDraftTerminalReadClient client = + new GameDesignDraftTerminalReadClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "test"); + try { + assertThatThrownBy(() -> client.read(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(request("test"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesAnExactGameDesignPeerAuthenticatedStubForConfiguredEndpoint( + @TempDir Path directory) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + 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); + GameDesignDraftTerminalReadClient client = + new GameDesignDraftTerminalReadClient(endpoints, tls(directory), channelFactory, "test"); + try { + client.init(); + + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + AbstractStub stub = initializedStub(client); + assertThat(stub.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(stub.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/game-design-service"); + } finally { + client.close(); + } + } + + private static AbstractStub initializedStub(GameDesignDraftTerminalReadClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } + + private static GameDesignDraftTerminalReadEvidence.Request request(String namespace) { + UUID tenant = uuid("11111111-1111-4111-8111-111111111111"); + UUID version = uuid("22222222-2222-4222-8222-222222222222"); + UUID request = uuid("44444444-4444-4444-8444-444444444444"); + UUID commit = uuid("55555555-5555-4555-8555-555555555555"); + DraftCommitBinding draft = + DraftCommitBinding.create( + new TargetProof(tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + byte[] draftBytes = draft.canonicalBytes(); + byte[] accountBinding = + new DraftAuthorizationFenceBinding( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request, + commit, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + tenant, + version, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {1}))) + .canonicalBytes(); + return new GameDesignDraftTerminalReadEvidence.Request( + 1, namespace, uuid("33333333-3333-4333-8333-333333333333"), accountBinding); + } + + private static CommonGrpcClientProperties tls(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; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClientTest.java new file mode 100644 index 0000000000..31ddbcc03d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClientTest.java @@ -0,0 +1,227 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.stub.AbstractStub; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +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.GrpcServerPeerIdentityCallCredentials; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class WorldDraftTerminalReadClientTest { + @Test + void rejectsPlaintextBeforeCreatingAChannel(@TempDir Path directory) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties tls = tls(directory); + tls.setPlaintext(true); + + assertThatThrownBy( + () -> + new WorldDraftTerminalReadClient( + new ServiceEndpointsProperties(), tls, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsWrongNamespaceAndUninitializedUseBeforeTransport(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + WorldDraftTerminalReadClient client = + new WorldDraftTerminalReadClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "test"); + try { + assertThatThrownBy(() -> client.read(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(request("test"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesAnExactWorldPeerAuthenticatedStubForConfiguredEndpoint(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + WorldDraftTerminalReadClient client = + new WorldDraftTerminalReadClient(endpoints, tls(directory), channelFactory, "test"); + try { + client.init(); + + verify(channelFactory) + .buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + AbstractStub stub = initializedStub(client); + assertThat(stub.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(stub.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/world-management-service"); + } finally { + client.close(); + } + } + + private static AbstractStub initializedStub(WorldDraftTerminalReadClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + @Test + void clientDecodesCommittedCarrierAndRejectsSubstitutedResult(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(factory.buildChannel( + any(String.class), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new WorldDraftTerminalReadClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + try { + client.init(); + var stub = + mock( + net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadServiceGrpc + .WorldDraftTerminalReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(eq(5L), eq(java.util.concurrent.TimeUnit.SECONDS))) + .thenReturn(stub); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + var request = request("test"); + var committed = WorldDraftTerminalReadGrpcCodecTest.committedReadback(request); + var response = + WorldDraftTerminalReadGrpcCodec.toResponse(request, java.util.Optional.of(committed)); + when(stub.readWorldDraftTerminalOutcome(any())).thenReturn(response); + assertThat(client.read(request).ownerReadback().orElseThrow().canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + var changed = + new DraftAuthorizationFenceBinding.OwnerReadback( + committed.owner(), + committed.outcome(), + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + new byte[] {1}); + when(stub.readWorldDraftTerminalOutcome(any())) + .thenReturn( + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(changed.canonicalBytes())) + .build()); + assertThatThrownBy(() -> client.read(request)) + .hasMessageContaining("invalid terminal readback evidence"); + } finally { + client.close(); + } + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } + + private static WorldDraftTerminalReadEvidence.Request request(String namespace) { + UUID tenant = uuid("11111111-1111-4111-8111-111111111111"); + UUID version = uuid("22222222-2222-4222-8222-222222222222"); + UUID request = uuid("44444444-4444-4444-8444-444444444444"); + UUID commit = uuid("55555555-5555-4555-8555-555555555555"); + DraftCommitBinding draft = + DraftCommitBinding.create( + new TargetProof(tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + byte[] draftBytes = draft.canonicalBytes(); + byte[] accountBinding = + new DraftAuthorizationFenceBinding( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request, + commit, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + tenant, + version, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + null, + "1", + null, + null, + new byte[] {1}))) + .canonicalBytes(); + return new WorldDraftTerminalReadEvidence.Request( + 1, namespace, uuid("33333333-3333-4333-8333-333333333333"), accountBinding); + } + + private static CommonGrpcClientProperties tls(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; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..35bf6e7387 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java @@ -0,0 +1,891 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; +import org.junit.jupiter.api.Test; + +public class WorldDraftTerminalReadGrpcCodecTest { + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private static final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private static final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private static final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + @Test + void requestCarriesAndDefensivelyRetainsTheCompleteOriginalBinding() { + byte[] original = originalBinding(); + var request = + new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), original); + original[0] ^= 1; + + var wire = WorldDraftTerminalReadGrpcCodec.toRequest(request); + var decoded = WorldDraftTerminalReadGrpcCodec.fromRequest(wire); + assertThat(decoded).isEqualTo(request); + assertThat(decoded.originalAccountBinding()).containsExactly(request.originalAccountBinding()); + assertThat( + WorldDraftTerminalReadEvidence.Request.create("test", request.originalAccountBinding()) + .readRequestId()) + .isNotEqualTo(request.accountBinding().operationId()); + } + + @Test + void unknownIsExplicitAndCarriesNoOwnerResult() { + var request = request(); + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.empty()); + + var evidence = WorldDraftTerminalReadGrpcCodec.fromResponse(request, response); + + assertThat(evidence.request()).isEqualTo(request); + assertThat(evidence.ownerReadback()).isEmpty(); + assertThat(response.getStatus()) + .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN); + assertThat(response.getOwnerReadbackBytes()).isEmpty(); + } + + @Test + void exactAbortMustBeWorldAndMustEchoEveryRequestFieldAndOriginalBinding() { + var request = request(); + var binding = request.accountBinding(); + var abort = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + request.originalAccountBinding(), + new byte[] {1, 2, 3}); + + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(abort)); + var evidence = WorldDraftTerminalReadGrpcCodec.fromResponse(request, response); + + var decodedAbort = evidence.ownerReadback().orElseThrow(); + assertThat(decodedAbort.canonicalBytes()).containsExactly(abort.canonicalBytes()); + assertThat(decodedAbort.fullBinding()).containsExactly(request.originalAccountBinding()); + assertThat(decodedAbort.result()).containsExactly(1, 2, 3); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.toResponse( + request, + Optional.of( + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + request.originalAccountBinding(), + new byte[] {1})))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("World terminal response"); + + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setReadRequestId(uuid("77777777-7777-4777-8777-777777777777").toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact read request"); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(new byte[] {9})) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact read request"); + } + + @Test + void rejectsUnknownFieldsAndContradictoryStatusPayloads() { + var request = request(); + var encoded = WorldDraftTerminalReadGrpcCodec.toRequest(request); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromRequest( + encoded.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + ReadWorldDraftTerminalOutcomeResponse unknownWithBytes = + WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.empty()).toBuilder() + .setOwnerReadbackBytes(com.google.protobuf.ByteString.copyFrom(new byte[] {1})) + .build(); + assertThatThrownBy( + () -> WorldDraftTerminalReadGrpcCodec.fromResponse(request, unknownWithBytes)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("UNKNOWN"); + } + + @Test + void exactCommittedCarrierRoundTripsAndRejectsStatusOwnerResultAndFullBindingSubstitution() { + var request = request(); + var committed = committedReadback(request); + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); + assertThat(response.getStatus()) + .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED); + assertThat( + WorldDraftTerminalReadGrpcCodec.fromResponse(request, response) + .ownerReadback() + .orElseThrow() + .canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setStatus( + WorldDraftTerminalReadStatus + .WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED) + .build())) + .hasMessageContaining("status differs"); + var abort = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + new byte[] {1}); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(abort.canonicalBytes())) + .build())) + .hasMessageContaining("status differs"); + var wrongOwner = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.GAME_DESIGN, + Outcome.COMMITTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + committed.result()); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(wrongOwner.canonicalBytes())) + .build())) + .hasMessageContaining("World terminal response"); + var substituted = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + new byte[] {1, 2, 3}); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(substituted.canonicalBytes())) + .build())) + .hasMessageContaining("substituted canonical APPLIED result"); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(new byte[] {9})) + .build())) + .hasMessageContaining("changed the exact read request"); + assertThatThrownBy( + () -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, response.toBuilder().clearOwnerReadbackBytes().build())) + .hasMessageContaining("bytes are required"); + } + + @Test + void committedCarrierRejectsEmbeddedOperationGraphDigestEpochAndUnknownFieldChanges() + throws Exception { + var request = request(); + var committed = committedReadback(request); + var mapper = new tools.jackson.databind.ObjectMapper(); + for (String field : + List.of("operationBytesBase64", "graphDigest", "appliedEpochs", "unknown")) { + var json = (tools.jackson.databind.node.ObjectNode) mapper.readTree(committed.result()); + switch (field) { + case "operationBytesBase64" -> + json.put(field, java.util.Base64.getEncoder().encodeToString(new byte[] {1})); + case "graphDigest" -> json.put(field, "sha256:" + "0".repeat(64)); + case "appliedEpochs" -> json.set(field, mapper.createArrayNode()); + default -> json.put(field, "unsupported"); + } + var bytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(json)); + var changed = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + committed.operationId(), + committed.commitId(), + committed.fenceId(), + committed.inputDigest(), + committed.fullBinding(), + bytes); + assertThatThrownBy( + () -> WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(changed))) + .hasMessageContaining("substituted canonical APPLIED result"); + } + } + + @Test + void exactDeclaredV2CarrierRoundTripsWithItsOriginalRoomAndCompleteGraphDeclaration() + throws Exception { + var request = freshGraphRequest(); + var committed = committedReadback(request, true); + byte[] graphBytes = + Base64.getDecoder().decode(object(committed.result()).get("graphBytesBase64").textValue()); + assertThat(java.util.Arrays.equals(graphBytes, canonical(JSON.readTree(graphBytes)))).isFalse(); + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); + + assertThat(response.getStatus()) + .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_COMMITTED); + assertThat( + WorldDraftTerminalReadGrpcCodec.fromResponse(request, response) + .ownerReadback() + .orElseThrow() + .canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + } + + @Test + void v2RejectsMalformedOrDigestSubstitutedOriginalOwnerGraphBytes() throws Exception { + var request = freshGraphRequest(); + var committed = committedReadback(request, true); + var result = object(committed.result()); + result.put("graphDigest", "sha256:" + "0".repeat(64)); + assertResultRejected(request, committed, canonical(result)); + + result = object(committed.result()); + byte[] malformedGraph = Base64.getDecoder().decode(result.get("graphBytesBase64").textValue()); + malformedGraph[0] = (byte) 0xff; + String graphDigest = sha256(malformedGraph); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(malformedGraph)); + result.put("graphDigest", graphDigest); + var draft = + DraftCommitBinding.fromStored( + new String(request.accountBinding().gameDesignBinding(), StandardCharsets.UTF_8), + request.accountBinding().inputDigest()); + var changedReceipt = receipt(request, draft, graphDigest); + byte[] changedReceiptBytes = canonical(changedReceipt); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(changedReceiptBytes)); + result.put("startLocationReceiptDigest", changedReceipt.get("receiptDigest").textValue()); + assertResultRejected(request, committed, canonical(result)); + } + + @Test + void v2ReceiptRejectsChangedSelectorScopeRequestCommitFenceAndDigests() throws Exception { + var request = freshGraphRequest(); + var committed = committedReadback(request, true); + for (java.util.function.Consumer change : + List.>of( + receipt -> + selector(receipt) + .put("roomTemplateId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + selector(receipt) + .put("tenantId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + selector(receipt) + .put("versionId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + receipt.put("requestId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + receipt.put("commitId", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> + receipt.put( + "authorizationFenceId", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()), + receipt -> receipt.put("accountBindingDigest", "sha256:" + "0".repeat(64)), + receipt -> receipt.put("bindingDigest", "sha256:" + "0".repeat(64)), + receipt -> receipt.put("graphDigest", "sha256:" + "0".repeat(64)), + receipt -> receipt.put("receiptDigest", "sha256:" + "0".repeat(64)))) { + assertReceiptChangeRejected(request, committed, change); + } + assertReceiptChangeRejected( + request, committed, receipt -> receipt.put("unsupported", "new-field")); + var changedTopLevel = object(committed.result()); + changedTopLevel.put("unsupported", "new-field"); + assertResultRejected(request, committed, canonical(changedTopLevel)); + changedTopLevel = object(committed.result()); + changedTopLevel.put("startLocationReceiptDigest", "sha256:" + "0".repeat(64)); + assertResultRejected(request, committed, canonical(changedTopLevel)); + } + + @Test + void v2RejectsNoncanonicalReceiptBytesAndGraphWithoutTheSelectedRoomRow() throws Exception { + var request = freshGraphRequest(); + var committed = committedReadback(request, true); + var result = object(committed.result()); + byte[] receiptBytes = + Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()); + String receiptJson = new String(receiptBytes, StandardCharsets.UTF_8); + result.put( + "startLocationReceiptBase64", + Base64.getEncoder().encodeToString((" " + receiptJson).getBytes(StandardCharsets.UTF_8))); + assertResultRejected(request, committed, canonical(result)); + + result = object(committed.result()); + byte[] graphBytes = Base64.getDecoder().decode(result.get("graphBytesBase64").textValue()); + var graph = object(graphBytes); + var rows = (tools.jackson.databind.node.ArrayNode) graph.get("rows"); + for (tools.jackson.databind.JsonNode row : rows) { + if ("ROOM".equals(row.get("mapping").get("family").textValue())) { + ((tools.jackson.databind.node.ObjectNode) row.get("mapping")) + .put("template_id", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()); + } + } + byte[] changedGraph = canonical(graph); + String graphDigest = sha256(changedGraph); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(changedGraph)); + result.put("graphDigest", graphDigest); + var binding = request.accountBinding(); + var commitBinding = + DraftCommitBinding.fromStored( + new String(binding.gameDesignBinding(), StandardCharsets.UTF_8), binding.inputDigest()); + var changedReceipt = receipt(request, commitBinding, graphDigest); + byte[] changedReceiptBytes = canonical(JSON.valueToTree(changedReceipt)); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(changedReceiptBytes)); + result.put("startLocationReceiptDigest", changedReceipt.get("receiptDigest").textValue()); + assertResultRejected(request, committed, canonical(result)); + } + + @Test + void declaredV2CannotDowngradeToV1AndV1CannotClaimUndeclaredHistoryAsV2() throws Exception { + var declaredRequest = freshGraphRequest(); + var declaredResult = committedReadback(declaredRequest, true); + var downgraded = object(declaredResult.result()); + downgraded.put("schema", "world-draft-graph-applied/v1"); + downgraded.remove("startLocationReceiptBase64"); + downgraded.remove("startLocationReceiptDigest"); + assertResultRejected(declaredRequest, declaredResult, canonical(downgraded)); + + var historicalRequest = request(); + var historicalResult = committedReadback(historicalRequest); + var upgraded = object(historicalResult.result()); + upgraded.put("schema", "world-draft-graph-applied/v2"); + upgraded.put( + "startLocationReceiptBase64", + Base64.getEncoder().encodeToString("{}".getBytes(StandardCharsets.UTF_8))); + upgraded.put("startLocationReceiptDigest", "sha256:" + "0".repeat(64)); + assertResultRejected(historicalRequest, historicalResult, canonical(upgraded)); + } + + /** + * Transport-only stipulated carrier; real persistence and six-family semantics are World proof. + */ + static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request) { + try { + return committedReadback(request, false); + } catch (Exception impossible) { + throw new AssertionError(impossible); + } + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) throws Exception { + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = freshGraph ? graphBytes(request, draft) : historicalGraphBytes(account); + String graphDigest = sha256(graph); + var result = new java.util.LinkedHashMap(); + result.put( + "schema", freshGraph ? "world-draft-graph-applied/v2" : "world-draft-graph-applied/v1"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + if (freshGraph) { + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + } + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JSON.valueToTree(result))); + } + + private static WorldDraftTerminalReadEvidence.Request request() { + return new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), originalBinding()); + } + + private static byte[] originalBinding() { + DraftCommitBinding draft = + DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", REVISION_ID, DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + return accountBinding(draft); + } + + /** Test-only exact fresh graph request shared with the published selector carrier proof. */ + public static WorldDraftTerminalReadEvidence.Request + freshGraphRequestForStartLocationEvidenceTest() throws Exception { + return freshGraphRequest(); + } + + /** Test-only complete World APPLIED-v2 readback for the exact fresh graph request. */ + public static DraftAuthorizationFenceBinding.OwnerReadback + committedFreshGraphReadbackForStartLocationEvidenceTest( + WorldDraftTerminalReadEvidence.Request request) { + try { + return committedReadback(request, true); + } catch (Exception impossible) { + throw new AssertionError(impossible); + } + } + + private static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + DraftCommitBinding draft = freshGraphBinding(); + return new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), accountBinding(draft)); + } + + private static DraftCommitBinding freshGraphBinding() throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static byte[] historicalGraphBytes(DraftAuthorizationFenceBinding binding) { + return ("{\"schemaVersion\":\"2\",\"canonicalTenantId\":\"" + + binding.tenantId() + + "\",\"canonicalVersionId\":\"" + + binding.versionId() + + "\",\"rows\":[{}]}") + .getBytes(StandardCharsets.UTF_8); + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private static tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var selector = + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()); + String accountBindingDigest = sha256(request.originalAccountBinding()); + String receiptDigest = + startLocationReceiptDigest( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + accountBindingDigest, + draft.digest(), + TENANT_ID, + VERSION_ID, + ROOM_TEMPLATE_ID, + graphDigest); + var value = new java.util.LinkedHashMap(); + value.put("schema", "world-draft-start-location-receipt/v1"); + value.put("targetNamespace", request.targetNamespace()); + value.put("operationId", account.operationId().toString()); + value.put("requestId", account.requestId().toString()); + value.put("commitId", account.commitId().toString()); + value.put("authorizationFenceId", account.fenceId().toString()); + value.put("accountBindingDigest", accountBindingDigest); + value.put("bindingDigest", draft.digest()); + value.put("startLocation", selector); + value.put("graphDigest", graphDigest); + value.put("receiptDigest", receiptDigest); + return (tools.jackson.databind.node.ObjectNode) JSON.valueToTree(value); + } + + private static String startLocationReceiptDigest( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + String graphDigest) + throws Exception { + var framed = new ByteArrayOutputStream(); + for (String value : + List.of( + "world-draft-start-location-receipt/v1", + targetNamespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + tenantId.toString(), + versionId.toString(), + roomTemplateId.toString(), + graphDigest)) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + return sha256(framed.toByteArray()); + } + + private static tools.jackson.databind.node.ObjectNode selector( + tools.jackson.databind.node.ObjectNode receipt) { + return (tools.jackson.databind.node.ObjectNode) receipt.get("startLocation"); + } + + private static void assertReceiptChangeRejected( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback committed, + java.util.function.Consumer change) + throws Exception { + var result = object(committed.result()); + byte[] bytes = Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()); + var receipt = object(bytes); + change.accept(receipt); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(canonical(receipt))); + assertResultRejected(request, committed, canonical(result)); + } + + private static void assertResultRejected( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback committed, + byte[] resultBytes) { + var baseline = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); + var substituted = readbackWithResult(committed, resultBytes); + var response = + baseline.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(substituted.canonicalBytes())) + .build(); + assertThatThrownBy(() -> WorldDraftTerminalReadGrpcCodec.fromResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback readbackWithResult( + DraftAuthorizationFenceBinding.OwnerReadback original, byte[] result) { + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.fullBinding(), + result); + } + + private static tools.jackson.databind.node.ObjectNode object(byte[] bytes) throws Exception { + return (tools.jackson.databind.node.ObjectNode) JSON.readTree(bytes); + } + + private static byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java new file mode 100644 index 0000000000..d190339226 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java @@ -0,0 +1,195 @@ +package net.firedevops.firemud.common.gamedesign; + +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 net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AuthoredWorldLaunchDescriptorClientTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + + @Test + void canonicalDescriptorRejectsRetainedLegacyTenantSelector() { + var response = + net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setTenantId("legacy-tenant")) + .build(); + + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request(NAMESPACE), response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("legacy tenant selector"); + } + + @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 deniesResolveAndReadUntilExplicitInitializationAndAfterClose(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AuthoredWorldLaunchDescriptorClient client = + newClient(fileBackedMtls(directory), channelFactory); + var request = request(NAMESPACE); + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, "sha256:" + "b".repeat(64)); + var completeRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug("copper-coast") + .setControlPlaneRequestId("launch-operation-7") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .build(); + + assertThatThrownBy(() -> client.resolve(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.get(getRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.getComplete(completeRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(channelFactory); + + client.close(); + assertThatThrownBy(() -> client.resolve(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(channelFactory); + } + + @Test + void initializesConfiguredTargetWhenFileBackedTlsFilesExist(@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); + AuthoredWorldLaunchDescriptorClient client = + new AuthoredWorldLaunchDescriptorClient(endpoints, tls, channelFactory, NAMESPACE); + + try { + // The mocked channel factory covers explicit target wiring only; socket peer proof is + // separate. + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + @Test + void rejectsARequestOutsideTheConfiguredNamespace(@TempDir Path directory) throws Exception { + AuthoredWorldLaunchDescriptorClient client = + newClient(fileBackedMtls(directory), mock(GrpcChannelFactory.class)); + try { + assertThatThrownBy(() -> client.resolve(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + } finally { + client.close(); + } + } + + private static AuthoredWorldLaunchDescriptorClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new AuthoredWorldLaunchDescriptorClient( + 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; + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request request(String namespace) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + namespace, + "launch-operation-7", + TENANT_ID, + "copper-coast", + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java new file mode 100644 index 0000000000..f4fde9e072 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java @@ -0,0 +1,290 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodecTest; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AuthoredWorldReleaseAttestationSelectorTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void v2BindsCompleteOriginalEvidenceInItsOwnDomainAndSurvivesStoredReadback() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var release = release(descriptor, selector); + var stored = JSON.writeValueAsString(release); + var readback = JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class); + + assertThat(release.schemaVersion()).isEqualTo(2); + assertThat(readback).isEqualTo(release); + readback.requireValid(descriptor); + assertThat( + new String( + AuthoredWorldReleaseAttestationEvidence.evidencePreimage(release), + StandardCharsets.UTF_8)) + .startsWith("49:game-design-authored-world-release-attestation/v2") + .contains("worldStartLocationEvidence.canonicalBytesBase64") + .endsWith(Base64.getEncoder().encodeToString(selector.canonicalBytes())); + assertThat(readback.worldStartLocationEvidence().selectorReceiptBytes()) + .containsExactly(selector.selectorReceiptBytes()); + assertThat(readback.worldStartLocationEvidence().originalAccountBindingBytes()) + .containsExactly(selector.originalAccountBindingBytes()); + assertThat(readback.worldStartLocationEvidence().appliedResultBytes()) + .containsExactly(selector.appliedResultBytes()); + } + + @Test + void v1BytesAndDigestRemainUnchangedAndCannotBePromotedBySupplyingASelector() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var current = release(descriptor, selector); + var old = + AuthoredWorldReleaseAttestationEvidence.create( + current.targetNamespace(), + current.descriptorResultDigest(), + current.canonicalTenantId(), + current.canonicalVersionId(), + current.worldSlug(), + current.authoredWorldSourceOperationId(), + current.authoredWorldSourceEvidenceDigest(), + current.launchDescriptorId(), + current.publishedReleaseBundleRef(), + current.versionStateEpoch(), + current.publishWorkflowId(), + current.commitId(), + current.participantDigests(), + current.manifestHash(), + current.manifestSchemaVersion(), + current.requiredManifestAssetKeys(), + current.artifactDigests(), + current.commandDefinitions(), + current.generationConfigRevision()); + String stored = JSON.writeValueAsString(old); + assertThat(stored).doesNotContain("worldStartLocationEvidence"); + assertThat( + JSON.writeValueAsString( + JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class))) + .isEqualTo(stored); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(old) + .hasWorldStartLocationEvidence()) + .isFalse(); + assertThat(old.evidenceDigest()).isNotEqualTo(current.evidenceDigest()); + assertThatThrownBy(() -> copy(old, 1, selector)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(current, 2, null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(current, 3, selector)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(old, 2, selector).requireValid()) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void selectorSubstitutionAtAnOtherwiseValidCheckpointChangesTheDigest() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var release = release(descriptor, selector); + var request = selector.request(); + var other = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + UUID.randomUUID(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + assertThat(release(descriptor, other).evidenceDigest()).isNotEqualTo(release.evidenceDigest()); + assertThatThrownBy(() -> copy(release, 2, other).requireValid()) + .isInstanceOf(IllegalArgumentException.class); + var wrongCheckpoint = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + "other-workflow", + request.appliedCommitId(), + "c".repeat(64), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + assertThatThrownBy(() -> copy(release, 2, wrongCheckpoint)) + .isInstanceOf(IllegalArgumentException.class); + } + + static WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + var terminal = + WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); + var applied = + WorldDraftTerminalReadGrpcCodecTest.committedFreshGraphReadbackForStartLocationEvidenceTest( + terminal); + var account = terminal.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + account.tenantId(), + account.versionId(), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var result = JSON.readTree(applied.result()); + return new WorldPublishedStartLocationEvidence( + request, + Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()), + applied.fullBinding(), + applied.result()); + } + + static AuthoredWorldLaunchDescriptorEvidence descriptor( + WorldPublishedStartLocationEvidence selector) { + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "launch-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "b".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor", + 42L, + false, + null, + "{}", + "generation", + 9L, + 7L, + "release", + false, + null); + } + + static AuthoredWorldReleaseAttestationEvidence release( + AuthoredWorldLaunchDescriptorEvidence descriptor, + WorldPublishedStartLocationEvidence selector) { + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + return AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + selector); + } + + private static AuthoredWorldReleaseAttestationEvidence copy( + AuthoredWorldReleaseAttestationEvidence old, + int schema, + WorldPublishedStartLocationEvidence selector) { + return new AuthoredWorldReleaseAttestationEvidence( + schema, + old.targetNamespace(), + old.descriptorResultDigest(), + old.canonicalTenantId(), + old.canonicalVersionId(), + old.worldSlug(), + old.authoredWorldSourceOperationId(), + old.authoredWorldSourceEvidenceDigest(), + old.launchDescriptorId(), + old.publishedReleaseBundleRef(), + old.versionStateEpoch(), + old.publishWorkflowId(), + old.commitId(), + old.participantDigests(), + old.manifestHash(), + old.manifestSchemaVersion(), + old.requiredManifestAssetKeys(), + old.artifactDigests(), + old.commandDefinitions(), + old.generationConfigRevision(), + old.evidenceDigest(), + selector); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClientTest.java new file mode 100644 index 0000000000..fb62cfed6a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldVersionStateClientTest.java @@ -0,0 +1,138 @@ +package net.firedevops.firemud.common.gamedesign; + +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 AuthoredWorldVersionStateClientTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + + @Test + void rejectsPlaintextClasspathAndUnreadableTlsBeforeChannelCreation(@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.setPrivateKey("classpath:certs/client.key"); + 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 requiresExplicitInitializationAndRejectsOtherNamespaces(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AuthoredWorldVersionStateClient client = newClient(fileBackedMtls(directory), channelFactory); + try { + assertThatThrownBy(() -> client.read(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.read(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesOnlyConfiguredTargetFromFileBackedTls(@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); + AuthoredWorldVersionStateClient client = + new AuthoredWorldVersionStateClient(endpoints, tls, channelFactory, NAMESPACE); + + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static AuthoredWorldVersionStateClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new AuthoredWorldVersionStateClient( + 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; + } + + private static AuthoredWorldVersionStateEvidence.Request request() { + return request(NAMESPACE); + } + + private static AuthoredWorldVersionStateEvidence.Request request(String namespace) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + namespace, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 19L); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityClientTest.java new file mode 100644 index 0000000000..dec6cda142 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityClientTest.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.common.gamedesign; + +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 DraftSynchronizedVisibilityClientTest { + @Test + void rejectsPlaintextBeforeChannelCreation(@TempDir Path dir) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties tls = tls(dir); + tls.setPlaintext(true); + + assertThatThrownBy( + () -> + new DraftSynchronizedVisibilityClient( + new ServiceEndpointsProperties(), tls, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + verifyNoInteractions(channelFactory); + } + + @Test + void requiresExplicitInitializationAndRejectsOtherNamespacesBeforeChannelUse(@TempDir Path dir) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + DraftSynchronizedVisibilityClient client = + new DraftSynchronizedVisibilityClient( + new ServiceEndpointsProperties(), tls(dir), channelFactory, "test"); + try { + assertThatThrownBy(() -> client.read(request("test"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.read(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesMtlSStubForConfiguredGameDesignTarget(@TempDir Path dir) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + 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); + DraftSynchronizedVisibilityClient client = + new DraftSynchronizedVisibilityClient(endpoints, tls(dir), channelFactory, "test"); + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static DraftSynchronizedVisibilityEvidence.Request request(String namespace) { + var target = + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + return new DraftSynchronizedVisibilityEvidence.Request( + 1, namespace, UUID.fromString("33333333-3333-4333-8333-333333333333"), target); + } + + private static CommonGrpcClientProperties tls(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/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java new file mode 100644 index 0000000000..46908cdb09 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class DraftSynchronizedVisibilityEvidenceTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID READ_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + + @Test + void completeAllOwnerFenceValidatesAndReturnsDefensiveExactWorldResult() { + var evidence = evidence(binding(), resultVector(binding())); + + evidence.requireValid(); + assertThat(evidence.appliedOwnerResults()).hasSize(2); + assertThat(evidence.appliedOwnerResult(Owner.WORLD_MANAGEMENT).resultIdentity()) + .isEqualTo("world-result"); + byte[] resultBytes = evidence.appliedOwnerResult(Owner.WORLD_MANAGEMENT).resultBytes(); + resultBytes[0] = 0; + assertThat(evidence.appliedOwnerResult(Owner.WORLD_MANAGEMENT).resultBytes()) + .containsExactly("world-result-bytes".getBytes(StandardCharsets.UTF_8)); + } + + @Test + void rejectsIncompleteOrSubstitutedFenceAndOwnerResults() { + DraftCommitBinding binding = binding(); + String vector = resultVector(binding); + + assertThatThrownBy(() -> evidence(binding, vector.replace("APPLIED", "UNKNOWN"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("terminal APPLIED"); + assertThatThrownBy(() -> evidence(binding, vector.replace("WORLD_TEMPLATE", "OTHER"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bound epoch declaration"); + assertThatThrownBy( + () -> + new DraftSynchronizedVisibilityEvidence( + request(), binding, "APPLYING", fence(binding, vector))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not bound"); + assertThatThrownBy( + () -> + new DraftSynchronizedVisibilityEvidence( + request(), + binding, + "SYNCHRONIZED", + new DraftSynchronizedVisibilityEvidence.Fence( + REQUEST_ID, + COMMIT_ID, + "sha256:" + "f".repeat(64), + vector, + OffsetDateTime.now(ZoneOffset.UTC)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("full input"); + } + + private static DraftSynchronizedVisibilityEvidence evidence( + DraftCommitBinding binding, String vector) { + return new DraftSynchronizedVisibilityEvidence( + request(), binding, "SYNCHRONIZED", fence(binding, vector)); + } + + private static DraftSynchronizedVisibilityEvidence.Fence fence( + DraftCommitBinding binding, String vector) { + return new DraftSynchronizedVisibilityEvidence.Fence( + REQUEST_ID, + COMMIT_ID, + binding.digest(), + vector, + OffsetDateTime.of(2026, 10, 6, 0, 0, 0, 0, ZoneOffset.UTC)); + } + + private static DraftSynchronizedVisibilityEvidence.Request request() { + return new DraftSynchronizedVisibilityEvidence.Request(1, NAMESPACE, READ_ID, target()); + } + + private static TargetProof target() { + return new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + } + + private static DraftCommitBinding binding() { + return DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-source-1", + List.of( + new RevisionPayload( + "0", uuid("66666666-6666-4666-8666-666666666666"), Owner.WORLD_MANAGEMENT, "{}"), + new RevisionPayload( + "1", uuid("77777777-7777-4777-8777-777777777777"), Owner.ENTITY_MANAGEMENT, "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, "WORLD_TEMPLATE", "world-1", "ROOM_SCOPE", "room-1", "0"), + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "ENTITY_TEMPLATE", + "entity-1", + "ACTOR_SCOPE", + "actor-1", + "1"))); + } + + private static String resultVector(DraftCommitBinding binding) { + List> vector = new ArrayList<>(); + for (Owner owner : binding.requiredOwners()) { + AffectedUnit unit = binding.affectedUnits(owner).getFirst(); + Map epoch = new LinkedHashMap<>(); + epoch.put("aggregateType", unit.aggregateType()); + epoch.put("aggregateId", unit.aggregateId()); + epoch.put("scopeType", unit.scopeType()); + epoch.put("scopeId", unit.scopeId()); + epoch.put("expectedEpoch", unit.expectedEpoch()); + epoch.put( + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()).add(java.math.BigInteger.ONE).toString()); + Map item = new LinkedHashMap<>(); + item.put("owner", owner.name()); + item.put("status", "APPLIED"); + item.put("commitId", COMMIT_ID.toString()); + item.put("bindingDigest", binding.digest()); + item.put( + "resultIdentity", owner == Owner.WORLD_MANAGEMENT ? "world-result" : "entity-result"); + item.put( + "resultBytesBase64", + Base64.getEncoder() + .encodeToString("world-result-bytes".getBytes(StandardCharsets.UTF_8))); + item.put("appliedEpochs", List.of(epoch)); + vector.add(item); + } + return canonical(new ObjectMapper().writeValueAsString(vector)); + } + + private static String canonical(String json) { + try { + return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + } catch (java.io.IOException exception) { + throw new AssertionError(exception); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityGrpcCodecTest.java new file mode 100644 index 0000000000..4d2b99c687 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityGrpcCodecTest.java @@ -0,0 +1,247 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.gamedesign.v1.ReadDraftSynchronizedVisibilityResponse; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class DraftSynchronizedVisibilityGrpcCodecTest { + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID READ_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + + @Test + void completeRequestBindingAndFenceRoundTrip() { + var request = request(); + var evidence = evidence(binding()); + var response = DraftSynchronizedVisibilityGrpcCodec.toResponse(evidence); + + var decodedRequest = + DraftSynchronizedVisibilityGrpcCodec.fromRequest( + DraftSynchronizedVisibilityGrpcCodec.toRequest(request)); + assertRequestValues(request, decodedRequest); + + var decoded = DraftSynchronizedVisibilityGrpcCodec.fromResponse(request, response); + assertRequestValues(evidence.request(), decoded.request()); + assertBindingValues(evidence.binding(), decoded.binding()); + assertThat(decoded.workflowState()).isEqualTo(evidence.workflowState()); + assertFenceValues(evidence.fence(), decoded.fence()); + assertOwnerResultValues(evidence.appliedOwnerResults(), decoded.appliedOwnerResults()); + } + + private static void assertRequestValues( + DraftSynchronizedVisibilityEvidence.Request expected, + DraftSynchronizedVisibilityEvidence.Request actual) { + assertThat(actual.schemaVersion()).isEqualTo(expected.schemaVersion()); + assertThat(actual.targetNamespace()).isEqualTo(expected.targetNamespace()); + assertThat(actual.readRequestId()).isEqualTo(expected.readRequestId()); + assertThat(actual.target()).isEqualTo(expected.target()); + } + + private static void assertBindingValues(DraftCommitBinding expected, DraftCommitBinding actual) { + assertThat(actual.target()).isEqualTo(expected.target()); + assertThat(actual.requestId()).isEqualTo(expected.requestId()); + assertThat(actual.commitId()).isEqualTo(expected.commitId()); + assertThat(actual.baseCommitId()).isEqualTo(expected.baseCommitId()); + assertThat(actual.revisions()).isEqualTo(expected.revisions()); + assertThat(actual.affectedUnits()).isEqualTo(expected.affectedUnits()); + assertThat(actual.requiredOwners()).isEqualTo(expected.requiredOwners()); + assertThat(actual.canonicalJson()).isEqualTo(expected.canonicalJson()); + assertThat(actual.canonicalBytes()).containsExactly(expected.canonicalBytes()); + assertThat(actual.digest()).isEqualTo(expected.digest()); + } + + private static void assertFenceValues( + DraftSynchronizedVisibilityEvidence.Fence expected, + DraftSynchronizedVisibilityEvidence.Fence actual) { + assertThat(actual.requestId()).isEqualTo(expected.requestId()); + assertThat(actual.commitId()).isEqualTo(expected.commitId()); + assertThat(actual.inputDigest()).isEqualTo(expected.inputDigest()); + assertThat(actual.resultVectorJson()).isEqualTo(expected.resultVectorJson()); + assertThat(actual.createdAt()).isEqualTo(expected.createdAt()); + } + + private static void assertOwnerResultValues( + List expected, + List actual) { + assertThat(actual).hasSize(expected.size()); + for (int index = 0; index < expected.size(); index++) { + var expectedOwner = expected.get(index); + var actualOwner = actual.get(index); + assertThat(actualOwner.owner()).isEqualTo(expectedOwner.owner()); + assertThat(actualOwner.commitId()).isEqualTo(expectedOwner.commitId()); + assertThat(actualOwner.bindingDigest()).isEqualTo(expectedOwner.bindingDigest()); + assertThat(actualOwner.resultIdentity()).isEqualTo(expectedOwner.resultIdentity()); + assertThat(actualOwner.resultBytes()).containsExactly(expectedOwner.resultBytes()); + + var expectedEpochs = expectedOwner.appliedEpochs(); + var actualEpochs = actualOwner.appliedEpochs(); + assertThat(actualEpochs).hasSize(expectedEpochs.size()); + for (int epochIndex = 0; epochIndex < expectedEpochs.size(); epochIndex++) { + var expectedEpoch = expectedEpochs.get(epochIndex); + var actualEpoch = actualEpochs.get(epochIndex); + assertThat(actualEpoch.aggregateType()).isEqualTo(expectedEpoch.aggregateType()); + assertThat(actualEpoch.aggregateId()).isEqualTo(expectedEpoch.aggregateId()); + assertThat(actualEpoch.scopeType()).isEqualTo(expectedEpoch.scopeType()); + assertThat(actualEpoch.scopeId()).isEqualTo(expectedEpoch.scopeId()); + assertThat(actualEpoch.expectedEpoch()).isEqualTo(expectedEpoch.expectedEpoch()); + assertThat(actualEpoch.resultingEpoch()).isEqualTo(expectedEpoch.resultingEpoch()); + } + } + } + + @Test + void rejectsReadTargetBindingWorkflowFenceAndOwnerVectorSubstitutions() { + var request = request(); + var response = DraftSynchronizedVisibilityGrpcCodec.toResponse(evidence(binding())); + + assertInvalid( + request, + response.toBuilder() + .setReadRequestId(uuid("88888888-8888-4888-8888-888888888888").toString()) + .build()); + assertInvalid( + request, + response.toBuilder() + .setTarget(response.getTarget().toBuilder().setSourceGameRowId(43L)) + .build()); + assertInvalid( + request, response.toBuilder().setBindingDigest("sha256:" + "f".repeat(64)).build()); + assertInvalid(request, response.toBuilder().setWorkflowState("APPLYING").build()); + assertInvalid( + request, + response.toBuilder() + .setFence( + response.getFence().toBuilder() + .setCommitId(uuid("99999999-9999-4999-8999-999999999999").toString())) + .build()); + assertInvalid( + request, + response.toBuilder() + .setFence( + response.getFence().toBuilder() + .setResultVectorJson( + response.getFence().getResultVectorJson().replace("APPLIED", "UNKNOWN"))) + .build()); + } + + @Test + void rejectsUnknownWireFieldsAndMissingTargetOrFence() { + var request = request(); + var response = DraftSynchronizedVisibilityGrpcCodec.toResponse(evidence(binding())); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatThrownBy( + () -> + DraftSynchronizedVisibilityGrpcCodec.fromRequest( + DraftSynchronizedVisibilityGrpcCodec.toRequest(request).toBuilder() + .setUnknownFields(unknown) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertInvalid(request, response.toBuilder().clearTarget().build()); + assertInvalid(request, response.toBuilder().clearFence().build()); + assertInvalid( + request, + response.toBuilder() + .setFence(response.getFence().toBuilder().setUnknownFields(unknown)) + .build()); + } + + private static void assertInvalid( + DraftSynchronizedVisibilityEvidence.Request request, + ReadDraftSynchronizedVisibilityResponse response) { + assertThatThrownBy(() -> DraftSynchronizedVisibilityGrpcCodec.fromResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DraftSynchronizedVisibilityEvidence evidence(DraftCommitBinding binding) { + return new DraftSynchronizedVisibilityEvidence( + request(), + binding, + "SYNCHRONIZED", + new DraftSynchronizedVisibilityEvidence.Fence( + REQUEST_ID, + COMMIT_ID, + binding.digest(), + resultVector(binding), + java.time.OffsetDateTime.parse("2026-10-06T00:00:00Z"))); + } + + private static DraftSynchronizedVisibilityEvidence.Request request() { + return new DraftSynchronizedVisibilityEvidence.Request(1, "test", READ_ID, target()); + } + + private static TargetProof target() { + return new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + } + + private static DraftCommitBinding binding() { + return DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-source-1", + List.of( + new RevisionPayload( + "0", uuid("66666666-6666-4666-8666-666666666666"), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, "WORLD_TEMPLATE", "world-1", "ROOM_SCOPE", "room-1", "0"))); + } + + private static String resultVector(DraftCommitBinding binding) { + AffectedUnit unit = binding.affectedUnits(Owner.WORLD_MANAGEMENT).getFirst(); + Map epoch = new LinkedHashMap<>(); + epoch.put("aggregateType", unit.aggregateType()); + epoch.put("aggregateId", unit.aggregateId()); + epoch.put("scopeType", unit.scopeType()); + epoch.put("scopeId", unit.scopeId()); + epoch.put("expectedEpoch", unit.expectedEpoch()); + epoch.put("resultingEpoch", "1"); + Map item = new LinkedHashMap<>(); + item.put("owner", Owner.WORLD_MANAGEMENT.name()); + item.put("status", "APPLIED"); + item.put("commitId", COMMIT_ID.toString()); + item.put("bindingDigest", binding.digest()); + item.put("resultIdentity", "world-result"); + item.put( + "resultBytesBase64", + Base64.getEncoder().encodeToString("result".getBytes(StandardCharsets.UTF_8))); + item.put("appliedEpochs", List.of(epoch)); + return canonical(new ObjectMapper().writeValueAsString(List.of(item))); + } + + private static String canonical(String json) { + try { + return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + } catch (java.io.IOException exception) { + throw new AssertionError(exception); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java new file mode 100644 index 0000000000..682315cc0f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java @@ -0,0 +1,587 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; +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 for the explicit Game Session to World lifecycle-read transport only. */ +class WorldCanonicalInstanceLifecycleClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_WORLD_URI = + "spiffe://firemud/ns/other-test/sa/world-management-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID READ_REQUEST_ID = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private Server server; + private WorldCanonicalInstanceLifecycleClient client; + private AtomicInteger serverCallStarts; + private AtomicInteger applicationCalls; + private AtomicReference receivedPeerUri; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void exactWorldWorkloadPeerReadsTheCompleteEchoedCaptureOverPhysicalMtls() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + startServer(pki.worldServer(), ResponseMode.EXACT, expected); + client = newClient(server); + client.init(); + + WorldCanonicalInstanceLifecycleEvidence actual = client.read(expected.request()); + + assertThat(actual.canonicalBytes()).containsExactly(expected.canonicalBytes()); + assertThat(serverCallStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + assertThat(receivedPeerUri).hasValue(GAME_SESSION_URI); + } + + @Test + void trustedWrongWorldWorkloadAndNamespaceCannotSendRequestMetadataOrBody() throws Exception { + List wrongPeers = List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer()); + for (TestIdentity wrongPeer : wrongPeers) { + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + startServer(wrongPeer, ResponseMode.EXACT, expected); + client = newClient(server); + client.init(); + + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(serverCallStarts).as(wrongPeer.alias()).hasValue(0); + assertThat(applicationCalls).as(wrongPeer.alias()).hasValue(0); + stopTransport(); + } + } + + @Test + void exactPeerResponseMustEchoTheRequestAndContainAValidCompleteCarrier() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + + startServer(pki.worldServer(), ResponseMode.WRONG_READ_REQUEST_ID, expected); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical instance lifecycle evidence"); + assertThat(serverCallStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + stopTransport(); + + startServer(pki.worldServer(), ResponseMode.MALFORMED_EVIDENCE, expected); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid canonical instance lifecycle evidence"); + assertThat(serverCallStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + } + + @Test + void refusesPlaintextClasspathFilesAndCallsBeforeExplicitInitialization() throws Exception { + serverCallStarts = new AtomicInteger(); + applicationCalls = new AtomicInteger(); + receivedPeerUri = new AtomicReference<>(); + var plaintext = pki.clientProperties(tempDirectory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceLifecycleClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var classpath = pki.clientProperties(tempDirectory); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceLifecycleClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + WorldCanonicalInstanceLifecycleEvidence expected = + evidence("PREPARING", 7L, 10L, READ_REQUEST_ID); + startServer(pki.worldServer(), ResponseMode.EXACT, expected); + client = newClient(server); + assertThatThrownBy(() -> client.read(expected.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + assertThat(serverCallStarts).hasValue(0); + assertThat(applicationCalls).hasValue(0); + } + + private void startServer( + TestIdentity identity, + ResponseMode responseMode, + WorldCanonicalInstanceLifecycleEvidence expected) + throws Exception { + serverCallStarts = new AtomicInteger(); + applicationCalls = new AtomicInteger(); + receivedPeerUri = new AtomicReference<>(); + var service = + new WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceImplBase() { + @Override + public void readWorldCanonicalInstanceLifecycle( + ReadWorldCanonicalInstanceLifecycleRequest request, + StreamObserver observer) { + applicationCalls.incrementAndGet(); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + receivedPeerUri.set(peer == null ? null : peer.uri()); + WorldCanonicalInstanceLifecycleEvidence.Request decoded = + WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request); + ReadWorldCanonicalInstanceLifecycleResponse response; + if (responseMode == ResponseMode.MALFORMED_EVIDENCE) { + response = + ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(new byte[] {(byte) 0xff})) + .build(); + } else if (responseMode == ResponseMode.WRONG_READ_REQUEST_ID) { + var changedRequest = + withReadRequestId(decoded, uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")); + var changedEvidence = withRequest(expected, changedRequest); + response = + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse( + changedRequest, changedEvidence); + } else { + response = WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(decoded, expected); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countApplicationHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + serverCallStarts.incrementAndGet(); + return next.startCall(call, headers); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countApplicationHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private WorldCanonicalInstanceLifecycleClient newClient(Server target) + throws IOException, CertificateEncodingException { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + target.getPort()); + return new WorldCanonicalInstanceLifecycleClient( + endpoints, pki.clientProperties(tempDirectory), new GrpcChannelFactory(), NAMESPACE); + } + + private static WorldCanonicalInstanceLifecycleEvidence evidence( + String status, long epoch, long rowVersion, UUID readRequestId) throws Exception { + WorldPublishedStartLocationEvidence selector = + AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldReleaseAttestationSelectorTest.descriptor(selector); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationSelectorTest.release(descriptor, selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + RoomTemplateRef startLocation = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()).startLocation(); + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + readRequestId, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 9_007_199_254_740_993L, + status, + epoch, + rowVersion, + uuid("33333333-3333-4333-8333-333333333333"), + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) + .graphDigest() + .substring("sha256:".length()), + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + + private static WorldCanonicalInstanceLifecycleEvidence withRequest( + WorldCanonicalInstanceLifecycleEvidence evidence, + WorldCanonicalInstanceLifecycleEvidence.Request request) { + return new WorldCanonicalInstanceLifecycleEvidence( + request, + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest(), + evidence.operationalRegionAssignments()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request withReadRequestId( + WorldCanonicalInstanceLifecycleEvidence.Request source, UUID readRequestId) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + source.schemaVersion(), + readRequestId, + source.targetNamespace(), + source.canonicalTenantId(), + source.worldSlug(), + source.canonicalGameInstanceId(), + source.playableStateNamespaceId(), + source.playableStateScope(), + source.publicProduction(), + source.controlPlaneRequestId(), + source.canonicalVersionId(), + source.expectedDescriptorRequestDigest(), + source.expectedDescriptorResultDigest(), + source.expectedReleaseAttestationDigest()); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private enum ResponseMode { + EXACT, + WRONG_READ_REQUEST_ID, + MALFORMED_EVIDENCE + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity worldServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity gameSessionClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD lifecycle test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "world-server", WORLD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-workload-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-namespace-server", OTHER_WORLD_URI, true), + issueIdentity( + directory, caStore, caFile, "game-session-client", GAME_SESSION_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) + throws IOException, CertificateEncodingException { + Path clientCertificate = + writePem( + directory.resolve("game-session-client.crt"), + "CERTIFICATE", + gameSessionClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-session-client.key"), + "PRIVATE KEY", + gameSessionClient.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new java.util.ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/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/world/CanonicalWorldInstancePreparationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java new file mode 100644 index 0000000000..8d2326aea5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java @@ -0,0 +1,706 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstancePreparationServiceGrpc; +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 transport-only World double, not owner/database proof. */ +class CanonicalWorldInstancePreparationClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_SERVER_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String OTHER_NAMESPACE_URI = + "spiffe://firemud/ns/other-test/sa/world-management-service"; + private static final String GAME_SESSION_CLIENT_URI = WRONG_WORKLOAD_URI; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final long ABOVE_JAVASCRIPT_INTEGER = 9_007_199_254_740_993L; + + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private CanonicalWorldInstancePreparationClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createTrustedCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void exactWorldPeerReturnsCompleteV2LifecycleReadback() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + Request request = request(evidence); + startServer(pki.worldManagementServer(), request, response(request, evidence)); + client = newClient(server); + + assertThatThrownBy(() -> client.prepare(request, evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + + client.init(); + var prepared = client.prepare(request, evidence.request()); + assertThat(prepared).isEqualTo(evidence); + assertThat(prepared.launchBinding().releaseAttestation().schemaVersion()) + .isEqualTo(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + assertThat(prepared.runtimeRoomInstanceId()).isEqualTo(ABOVE_JAVASCRIPT_INTEGER); + assertThat(prepared.lifecycleEpoch()).isEqualTo(ABOVE_JAVASCRIPT_INTEGER + 1); + assertThat(prepared.rowVersion()).isEqualTo(ABOVE_JAVASCRIPT_INTEGER + 2); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + + client.close(); + assertThatThrownBy(() -> client.prepare(request, evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + } + + @Test + void trustedWrongWorkloadOrNamespaceReleasesNoRequestHeadersOrBody() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + Request request = request(evidence); + for (TestIdentity identity : List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer())) { + startServer(identity, request, response(request, evidence)); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.prepare(request, evidence.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + exception -> + assertThat(Status.fromThrowable(exception).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + stopTransport(); + } + } + + @Test + void rejectsChangedOuterAndInnerReadbackOverTheSocket() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + Request request = request(evidence); + PrepareCanonicalWorldInstanceResponse valid = response(request, evidence); + List changedResponses = + List.of( + valid.toBuilder() + .setRequest(valid.getRequest().toBuilder().setWorldSlug("other-world")) + .build(), + valid.toBuilder() + .setLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse( + copyLifecycleRequest( + evidence.request(), uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")), + withRequest( + evidence, + copyLifecycleRequest( + evidence.request(), uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"))))) + .build()); + + for (PrepareCanonicalWorldInstanceResponse changedResponse : changedResponses) { + startServer(pki.worldManagementServer(), request, changedResponse); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.prepare(request, evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasRootCauseInstanceOf(IllegalArgumentException.class); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + stopTransport(); + } + } + + @Test + void rejectsUnsafeTlsAndMismatchedSelectorsBeforeSending(@TempDir Path directory) + throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + Request request = request(evidence); + startServer(pki.worldManagementServer(), request, response(request, evidence)); + + var plaintext = pki.clientProperties(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new CanonicalWorldInstancePreparationClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var classpath = pki.clientProperties(directory); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new CanonicalWorldInstancePreparationClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + var absentCertificate = pki.clientProperties(directory); + absentCertificate.setCertChain(directory.resolve("absent-client.crt").toString()); + assertThatThrownBy( + () -> + new CanonicalWorldInstancePreparationClient( + new ServiceEndpointsProperties(), + absentCertificate, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + client = newClient(server); + assertThatThrownBy(() -> client.prepare(request, evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + client.init(); + + Request otherNamespaceRequest = copyAssociationRequest(request, "other-test"); + assertThatThrownBy(() -> client.prepare(otherNamespaceRequest, evidence.request())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + + var differentLifecycleRequest = + copyLifecycleRequest(evidence.request(), uuid("99999999-9999-4999-8999-999999999999")); + assertThatThrownBy(() -> client.prepare(request, differentLifecycleRequest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("expected World lifecycle request"); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + + client.close(); + assertThatThrownBy(() -> client.prepare(request, evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + + private void startServer( + TestIdentity identity, + Request expectedRequest, + PrepareCanonicalWorldInstanceResponse response) + throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var service = + new WorldCanonicalInstancePreparationServiceGrpc + .WorldCanonicalInstancePreparationServiceImplBase() { + @Override + public void prepareCanonicalWorldInstance( + PrepareCanonicalWorldInstanceRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(GAME_SESSION_CLIENT_URI); + assertThat(CanonicalWorldInstancePreparationGrpcCodec.fromRequest(wire)) + .isEqualTo(expectedRequest); + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private CanonicalWorldInstancePreparationClient newClient(Server target) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + target.getPort()); + return new CanonicalWorldInstancePreparationClient( + endpoints, pki.clientProperties(tempDirectory), new GrpcChannelFactory(), NAMESPACE); + } + + private static PrepareCanonicalWorldInstanceResponse response( + Request request, WorldCanonicalInstanceLifecycleEvidence evidence) { + return CanonicalWorldInstancePreparationGrpcCodec.toResponse(request, evidence); + } + + private static Request request(WorldCanonicalInstanceLifecycleEvidence evidence) { + var lifecycleRequest = evidence.request(); + return new Request( + lifecycleRequest.readRequestId(), + lifecycleRequest.targetNamespace(), + lifecycleRequest.canonicalTenantId(), + lifecycleRequest.worldSlug(), + lifecycleRequest.canonicalGameInstanceId(), + lifecycleRequest.controlPlaneRequestId(), + evidence.launchBinding().descriptor().launchDescriptorId(), + lifecycleRequest.expectedDescriptorRequestDigest(), + lifecycleRequest.expectedDescriptorResultDigest(), + lifecycleRequest.expectedReleaseAttestationDigest()); + } + + private static Request copyAssociationRequest(Request source, String targetNamespace) { + return new Request( + source.readRequestId(), + targetNamespace, + source.canonicalTenantId(), + source.worldSlug(), + source.gameInstanceUuid(), + source.controlPlaneRequestId(), + source.launchDescriptorId(), + source.expectedDescriptorRequestDigest(), + source.expectedDescriptorResultDigest(), + source.expectedReleaseAttestationEvidenceDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request copyLifecycleRequest( + WorldCanonicalInstanceLifecycleEvidence.Request source, UUID gameInstanceId) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + source.schemaVersion(), + source.readRequestId(), + source.targetNamespace(), + source.canonicalTenantId(), + source.worldSlug(), + gameInstanceId, + source.playableStateNamespaceId(), + source.playableStateScope(), + source.publicProduction(), + source.controlPlaneRequestId(), + source.canonicalVersionId(), + source.expectedDescriptorRequestDigest(), + source.expectedDescriptorResultDigest(), + source.expectedReleaseAttestationDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence withRequest( + WorldCanonicalInstanceLifecycleEvidence source, + WorldCanonicalInstanceLifecycleEvidence.Request request) { + return new WorldCanonicalInstanceLifecycleEvidence( + request, + source.launchBinding(), + source.startLocation(), + source.runtimeRoomInstanceId(), + source.lifecycleStatus(), + source.lifecycleEpoch(), + source.rowVersion(), + source.captureId(), + source.graphSha256(), + source.preparationInputDigest(), + source.operationalRegionAssignments()); + } + + private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Exception { + WorldPublishedStartLocationEvidence selector = + WorldPublishedStartLocationGrpcCodecTest.evidence(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + selectorReceipt.startLocation(), + ABOVE_JAVASCRIPT_INTEGER, + "PREPARING", + ABOVE_JAVASCRIPT_INTEGER + 1, + ABOVE_JAVASCRIPT_INTEGER + 2, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity worldManagementServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity gameSessionClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD World preparation test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity( + directory, caStore, caFile, "world-management-server", WORLD_SERVER_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-workload-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-namespace-server", OTHER_NAMESPACE_URI, true), + issueIdentity( + directory, caStore, caFile, "game-session-client", GAME_SESSION_CLIENT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) throws Exception { + Path cert = + writePem( + directory.resolve("game-session-client.crt"), + "CERTIFICATE", + gameSessionClient.certificate().getEncoded()); + Path key = + writePem( + directory.resolve("game-session-client.key"), + "PRIVATE KEY", + gameSessionClient.privateKey().getEncoded()); + Path ca = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(cert.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java new file mode 100644 index 0000000000..19c79b3c44 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java @@ -0,0 +1,362 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceResponse; +import org.junit.jupiter.api.Test; + +class CanonicalWorldInstancePreparationGrpcCodecTest { + private static final long ABOVE_JAVASCRIPT_INTEGER = 9_007_199_254_740_993L; + + @Test + void roundTripsV2LaunchBindingAndPreservesLargeLifecycleCounters() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + Request request = request(evidence); + + var wireRequest = CanonicalWorldInstancePreparationGrpcCodec.toRequest(request); + assertThat(CanonicalWorldInstancePreparationGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(request); + + var response = CanonicalWorldInstancePreparationGrpcCodec.toResponse(request, evidence); + var decoded = + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, evidence.request(), response); + assertThat(decoded).isEqualTo(evidence); + assertThat(decoded.launchBinding().releaseAttestation().schemaVersion()) + .isEqualTo(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + assertThat(decoded.runtimeRoomInstanceId()).isEqualTo(ABOVE_JAVASCRIPT_INTEGER); + assertThat(decoded.lifecycleEpoch()).isEqualTo(ABOVE_JAVASCRIPT_INTEGER + 1); + assertThat(decoded.rowVersion()).isEqualTo(ABOVE_JAVASCRIPT_INTEGER + 2); + } + + @Test + void rejectsChangedOuterAndInnerTuplesAndCompleteBindingSelectors() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + Request request = request(evidence); + var response = CanonicalWorldInstancePreparationGrpcCodec.toResponse(request, evidence); + + var changedOuter = + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setWorldSlug("other-world")) + .build(); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, evidence.request(), changedOuter)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact canonical preparation request"); + + var changedLifecycleRequest = + copyLifecycleRequest( + evidence.request(), uuid("99999999-9999-4999-8999-999999999999"), null, null); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, changedLifecycleRequest, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from the World lifecycle request"); + + Request changedDescriptor = + new Request( + request.readRequestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.gameInstanceUuid(), + request.controlPlaneRequestId(), + "different-launch-descriptor", + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationEvidenceDigest()); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.toResponse(changedDescriptor, evidence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete launch descriptor"); + + Request changedDigest = + new Request( + request.readRequestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.gameInstanceUuid(), + request.controlPlaneRequestId(), + request.launchDescriptorId(), + "sha256:" + "f".repeat(64), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationEvidenceDigest()); + assertThatThrownBy( + () -> CanonicalWorldInstancePreparationGrpcCodec.toResponse(changedDigest, evidence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from the World lifecycle request"); + + var changedInnerRequest = + copyLifecycleRequest( + evidence.request(), null, null, uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + WorldCanonicalInstanceLifecycleEvidence changedInnerEvidence = + withRequest(evidence, changedInnerRequest); + var responseWithChangedInner = + response.toBuilder() + .setLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse( + changedInnerRequest, changedInnerEvidence)) + .build(); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, evidence.request(), responseWithChangedInner)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed exact read request"); + } + + @Test + void rejectsMissingLifecycleOwnerErrorsAndUnknownNestedFields() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + Request request = request(evidence); + var response = CanonicalWorldInstancePreparationGrpcCodec.toResponse(request, evidence); + + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, evidence.request(), response.toBuilder().clearLifecycle().build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("lifecycle response is required"); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, + evidence.request(), + PrepareCanonicalWorldInstanceResponse.newBuilder() + .setRequest(CanonicalWorldInstancePreparationGrpcCodec.toRequest(request)) + .setError(ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION")) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("rejected canonical instance preparation"); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + var unknownOuterRequest = + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setUnknownFields(unknown)) + .build(); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, evidence.request(), unknownOuterRequest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var unknownLifecycle = + response.toBuilder() + .setLifecycle(response.getLifecycle().toBuilder().setUnknownFields(unknown)) + .build(); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, evidence.request(), unknownLifecycle)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + @Test + void requestDecoderUsesExistingCanonicalSelectorValidation() throws Exception { + var valid = CanonicalWorldInstancePreparationGrpcCodec.toRequest(request(evidence())); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromRequest( + valid.toBuilder() + .setReadRequestId("32345678-1234-4234-8234-123456789abc ") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil UUID"); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromRequest( + valid.toBuilder().setTargetNamespace("Bad_Namespace").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromRequest( + valid.toBuilder().setExpectedDescriptorResultDigest("not-a-digest").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("expectedDescriptorResultDigest"); + } + + private static Request request(WorldCanonicalInstanceLifecycleEvidence evidence) { + var lifecycleRequest = evidence.request(); + return new Request( + lifecycleRequest.readRequestId(), + lifecycleRequest.targetNamespace(), + lifecycleRequest.canonicalTenantId(), + lifecycleRequest.worldSlug(), + lifecycleRequest.canonicalGameInstanceId(), + lifecycleRequest.controlPlaneRequestId(), + evidence.launchBinding().descriptor().launchDescriptorId(), + lifecycleRequest.expectedDescriptorRequestDigest(), + lifecycleRequest.expectedDescriptorResultDigest(), + lifecycleRequest.expectedReleaseAttestationDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request copyLifecycleRequest( + WorldCanonicalInstanceLifecycleEvidence.Request source, + UUID readRequestId, + String worldSlug, + UUID gameInstanceId) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + source.schemaVersion(), + readRequestId == null ? source.readRequestId() : readRequestId, + source.targetNamespace(), + source.canonicalTenantId(), + worldSlug == null ? source.worldSlug() : worldSlug, + gameInstanceId == null ? source.canonicalGameInstanceId() : gameInstanceId, + source.playableStateNamespaceId(), + source.playableStateScope(), + source.publicProduction(), + source.controlPlaneRequestId(), + source.canonicalVersionId(), + source.expectedDescriptorRequestDigest(), + source.expectedDescriptorResultDigest(), + source.expectedReleaseAttestationDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence withRequest( + WorldCanonicalInstanceLifecycleEvidence source, + WorldCanonicalInstanceLifecycleEvidence.Request request) { + return new WorldCanonicalInstanceLifecycleEvidence( + request, + source.launchBinding(), + source.startLocation(), + source.runtimeRoomInstanceId(), + source.lifecycleStatus(), + source.lifecycleEpoch(), + source.rowVersion(), + source.captureId(), + source.graphSha256(), + source.preparationInputDigest(), + source.operationalRegionAssignments()); + } + + private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Exception { + WorldPublishedStartLocationEvidence selector = + WorldPublishedStartLocationGrpcCodecTest.evidence(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + selectorReceipt.startLocation(), + ABOVE_JAVASCRIPT_INTEGER, + "PREPARING", + ABOVE_JAVASCRIPT_INTEGER + 1, + ABOVE_JAVASCRIPT_INTEGER + 2, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java new file mode 100644 index 0000000000..a51415438a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java @@ -0,0 +1,485 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInitialPlayerLocationTest { + private static final UUID OPERATION_ID = uuid("10000000-0000-4000-8000-000000000001"); + + @Test + void requestDigestBindsActorAssignmentAdmissionOutcomeAndFullLifecycleProof() { + var first = + request( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "proof-a", + "b0000000-0000-4000-8000-000000000001"); + var exact = + request( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "proof-a", + "b0000000-0000-4000-8000-000000000002"); + var changedAssignment = + request("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "proof-a"); + var changedLifecycle = + request("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "proof-b"); + + assertThat(first.canonicalRequestBytes()).containsExactly(exact.canonicalRequestBytes()); + assertThat(first.requestDigest()).isEqualTo(exact.requestDigest()); + assertThat(first.originalLifecycleEvidenceBytes()) + .isNotEqualTo(exact.originalLifecycleEvidenceBytes()); + assertThat(first.normalizedLifecycleEvidenceBytes()) + .containsExactly(exact.normalizedLifecycleEvidenceBytes()); + assertThat(first.requestDigest()).startsWith("sha256:"); + assertThat(changedAssignment.requestDigest()).isNotEqualTo(first.requestDigest()); + assertThat(changedLifecycle.requestDigest()).isNotEqualTo(first.requestDigest()); + } + + @Test + void expectClosedOriginIsRetainedButDoesNotSupplyOwnerProof() { + var request = + new WorldCanonicalInitialPlayerLocation.Request( + OPERATION_ID, + uuid("20000000-0000-4000-8000-000000000001"), + uuid("30000000-0000-4000-8000-000000000001"), + "starter-world", + uuid("40000000-0000-4000-8000-000000000001"), + uuid("50000000-0000-4000-8000-000000000001"), + "SHARED", + uuid("60000000-0000-4000-8000-000000000001"), + uuid("70000000-0000-4000-8000-000000000001"), + uuid("80000000-0000-4000-8000-000000000001"), + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + uuid("90000000-0000-4000-8000-000000000001"), + uuid("a0000000-0000-4000-8000-000000000001"), + "initial-request", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + 1, + "owner-proof", + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "pointer-audit", + 1, + WorldCanonicalInitialPlayerLocation.InitialAdmissionOrigin.EXPECT_CLOSED, + lifecycle("proof", "b0000000-0000-4000-8000-000000000001")); + assertThat(request.initialAdmissionOrigin()) + .isEqualTo(WorldCanonicalInitialPlayerLocation.InitialAdmissionOrigin.EXPECT_CLOSED); + assertThat(new String(request.canonicalRequestBytes(), java.nio.charset.StandardCharsets.UTF_8)) + .contains("\"initialAdmissionOrigin\":\"EXPECT_CLOSED\""); + } + + @Test + void resultRetainsExactRequestBytesAndUsesTypedRoomReference() { + var request = + request("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "proof-a"); + var room = request.activeLifecycleEvidence().startLocation(); + var result = WorldCanonicalInitialPlayerLocation.Result.applied(request, room, 23); + var retry = + WorldCanonicalInitialPlayerLocation.Result.fromStored(request, result.canonicalBytes()); + + assertThat(retry.canonicalBytes()).containsExactly(result.canonicalBytes()); + assertThat(retry.requestDigest()).isEqualTo(result.requestDigest()); + assertThat(retry.startLocation()).isEqualTo(room); + assertThat(retry.runtimeRoomInstanceId()).isEqualTo(23L); + var freshRead = + request( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "proof-a", + "b0000000-0000-4000-8000-000000000002"); + var correlationRetry = + WorldCanonicalInitialPlayerLocation.Result.fromStored(freshRead, result.canonicalBytes()); + assertThat(correlationRetry.canonicalBytes()).containsExactly(result.canonicalBytes()); + assertThat(correlationRetry.request().originalLifecycleEvidenceBytes()) + .isNotEqualTo(request.activeLifecycleEvidence().canonicalBytes()); + assertThatThrownBy( + () -> + WorldCanonicalInitialPlayerLocation.Result.applied( + request, + new net.firedevops.firemud.common.world.RoomTemplateRef( + uuid("21000000-0000-4000-8000-000000000001"), + room.versionId(), + room.roomTemplateId()), + 23)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact V2 ROOM mapping"); + assertThatThrownBy( + () -> + WorldCanonicalInitialPlayerLocation.Result.applied( + request, + new net.firedevops.firemud.common.world.RoomTemplateRef( + room.tenantId(), + uuid("31000000-0000-4000-8000-000000000001"), + room.roomTemplateId()), + 23)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact V2 ROOM mapping"); + assertThatThrownBy( + () -> + WorldCanonicalInitialPlayerLocation.Result.applied( + request, + new net.firedevops.firemud.common.world.RoomTemplateRef( + room.tenantId(), + room.versionId(), + uuid("41000000-0000-4000-8000-000000000001")), + 23)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact V2 ROOM mapping"); + assertThatThrownBy(() -> WorldCanonicalInitialPlayerLocation.Result.applied(request, room, 24)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact V2 ROOM mapping"); + var tampered = + new String(result.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8) + .replace("\"runtimeRoomInstanceId\":\"23\"", "\"runtimeRoomInstanceId\":\"24\"") + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + assertThatThrownBy( + () -> WorldCanonicalInitialPlayerLocation.Result.fromStored(request, tampered)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact V2 ROOM mapping"); + } + + @Test + void conflictCodeAcceptsOnlyBoundedUppercaseAsciiMachineCodes() { + var request = + request("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "proof-a"); + assertThat( + WorldCanonicalInitialPlayerLocation.Result.conflict(request, "ACTOR_CONFLICT") + .outcome()) + .isEqualTo(WorldCanonicalInitialPlayerLocation.Outcome.CONFLICT); + + for (String invalidCode : + new String[] {"", "lowercase", "INVALID\nCODE", "CAFÉ", "A".repeat(65)}) { + assertThatThrownBy( + () -> WorldCanonicalInitialPlayerLocation.Result.conflict(request, invalidCode)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void storedRequestRoundTripsWithItsCompleteOriginalLifecycleEvidence() throws Exception { + var lifecycle = genuineLifecycleEvidence(); + var request = requestWithLifecycle(lifecycle); + + var decoded = + WorldCanonicalInitialPlayerLocation.Request.fromStored( + request.canonicalRequestBytes(), request.originalLifecycleEvidenceBytes()); + + assertThat(decoded.canonicalRequestBytes()).containsExactly(request.canonicalRequestBytes()); + assertThat(decoded.originalLifecycleEvidenceBytes()) + .containsExactly(request.originalLifecycleEvidenceBytes()); + + var alternateRead = + copyLifecycle( + lifecycle, + copyLifecycleRequest(lifecycle, uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")), + lifecycle.lifecycleEpoch()); + assertThat( + WorldCanonicalInitialPlayerLocation.normalizedLifecycleEvidenceBytes( + alternateRead.canonicalBytes())) + .containsExactly(request.normalizedLifecycleEvidenceBytes()); + var sameRequestWithFreshRead = + WorldCanonicalInitialPlayerLocation.Request.fromStored( + request.canonicalRequestBytes(), alternateRead.canonicalBytes()); + assertThat(sameRequestWithFreshRead.originalLifecycleEvidenceBytes()) + .containsExactly(alternateRead.canonicalBytes()); + } + + @Test + void storedRequestRejectsChangedEvidenceAndMalformedClosedRepresentations() throws Exception { + var lifecycle = genuineLifecycleEvidence(); + var request = requestWithLifecycle(lifecycle); + byte[] canonical = request.canonicalRequestBytes(); + String json = new String(canonical, java.nio.charset.StandardCharsets.UTF_8); + var changedEvidence = + copyLifecycle(lifecycle, lifecycle.request(), lifecycle.lifecycleEpoch() + 1); + + assertThatThrownBy( + () -> + WorldCanonicalInitialPlayerLocation.Request.fromStored( + canonical, changedEvidence.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + + for (byte[] malformed : + new byte[][] { + (json.substring(0, json.length() - 1) + ",\"unknown\":true}") + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + json.replace("\"schema\":", "\"schema\":\"duplicate\",\"schema\":") + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + (json + "{}\n").getBytes(java.nio.charset.StandardCharsets.UTF_8), + json.replace( + request.initialAdmissionHoldFence().toString(), + request.initialAdmissionHoldFence().toString().toUpperCase()) + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + json.replace("\"catalogRevision\":\"1\"", "\"catalogRevision\":\"01\"") + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + java.util.Arrays.copyOf(canonical, canonical.length + 1) + }) { + if (malformed[malformed.length - 1] == 0) malformed[malformed.length - 1] = (byte) 0xc3; + assertThatThrownBy( + () -> + WorldCanonicalInitialPlayerLocation.Request.fromStored( + malformed, request.originalLifecycleEvidenceBytes())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static WorldCanonicalInitialPlayerLocation.Request request( + String assignmentDigest, String lifecycleProof) { + return request(assignmentDigest, lifecycleProof, "b0000000-0000-4000-8000-000000000001"); + } + + private static WorldCanonicalInitialPlayerLocation.Request request( + String assignmentDigest, String lifecycleProof, String readRequestId) { + return new WorldCanonicalInitialPlayerLocation.Request( + OPERATION_ID, + uuid("20000000-0000-4000-8000-000000000001"), + uuid("30000000-0000-4000-8000-000000000001"), + "starter-world", + uuid("40000000-0000-4000-8000-000000000001"), + uuid("50000000-0000-4000-8000-000000000001"), + "SHARED", + uuid("60000000-0000-4000-8000-000000000001"), + uuid("70000000-0000-4000-8000-000000000001"), + uuid("80000000-0000-4000-8000-000000000001"), + assignmentDigest, + uuid("90000000-0000-4000-8000-000000000001"), + uuid("a0000000-0000-4000-8000-000000000001"), + "initial-request", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + 1, + "owner-proof", + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "pointer-audit", + 1, + WorldCanonicalInitialPlayerLocation.InitialAdmissionOrigin.NO_PRIOR_POINTER, + lifecycle(lifecycleProof, readRequestId)); + } + + private static WorldCanonicalInstanceLifecycleEvidence lifecycle( + String proof, String readRequestId) { + var request = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(request.canonicalTenantId()).thenReturn(uuid("20000000-0000-4000-8000-000000000001")); + when(request.worldSlug()).thenReturn("starter-world"); + when(request.canonicalGameInstanceId()) + .thenReturn(uuid("40000000-0000-4000-8000-000000000001")); + when(request.playableStateNamespaceId()) + .thenReturn(uuid("50000000-0000-4000-8000-000000000001")); + when(request.playableStateScope()).thenReturn("SHARED"); + when(request.canonicalVersionId()).thenReturn(uuid("30000000-0000-4000-8000-000000000001")); + var evidence = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(evidence.lifecycleStatus()).thenReturn("ACTIVE"); + when(evidence.request()).thenReturn(request); + var room = + new net.firedevops.firemud.common.world.RoomTemplateRef( + uuid("20000000-0000-4000-8000-000000000001"), + uuid("30000000-0000-4000-8000-000000000001"), + uuid("40000000-0000-4000-8000-000000000001")); + when(evidence.startLocation()).thenReturn(room); + when(evidence.runtimeRoomInstanceId()).thenReturn(23L); + String canonicalEvidence = + "{\"schema\":\"world-canonical-instance-lifecycle-evidence/v1\"," + + "\"lifecycleStatus\":\"ACTIVE\",\"lifecycleEpoch\":\"7\",\"request\":{" + + "\"readRequestId\":\"" + + readRequestId + + "\"," + + "\"canonicalTenantId\":\"20000000-0000-4000-8000-000000000001\"," + + "\"canonicalVersionId\":\"30000000-0000-4000-8000-000000000001\"," + + "\"worldSlug\":\"starter-world\"," + + "\"canonicalGameInstanceId\":\"40000000-0000-4000-8000-000000000001\"," + + "\"playableStateNamespaceId\":\"50000000-0000-4000-8000-000000000001\"," + + "\"playableStateScope\":\"SHARED\"},\"startLocation\":{" + + "\"tenantId\":\"20000000-0000-4000-8000-000000000001\"," + + "\"versionId\":\"30000000-0000-4000-8000-000000000001\"," + + "\"roomTemplateId\":\"40000000-0000-4000-8000-000000000001\"}," + + "\"runtimeRoomInstanceId\":\"23\",\"fixtureProof\":\"" + + proof + + "\"}"; + when(evidence.canonicalBytes()) + .thenReturn(canonicalEvidence.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return evidence; + } + + private static WorldCanonicalInitialPlayerLocation.Request requestWithLifecycle( + WorldCanonicalInstanceLifecycleEvidence lifecycle) { + var scope = lifecycle.request(); + return new WorldCanonicalInitialPlayerLocation.Request( + OPERATION_ID, + scope.canonicalTenantId(), + uuid("30000000-0000-4000-8000-000000000001"), + scope.worldSlug(), + scope.canonicalGameInstanceId(), + scope.playableStateNamespaceId(), + scope.playableStateScope(), + uuid("60000000-0000-4000-8000-000000000001"), + uuid("70000000-0000-4000-8000-000000000001"), + uuid("80000000-0000-4000-8000-000000000001"), + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + uuid("90000000-0000-4000-8000-000000000001"), + uuid("a0000000-0000-4000-8000-000000000001"), + "initial-request", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + 1, + "owner-proof", + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "pointer-audit", + 1, + WorldCanonicalInitialPlayerLocation.InitialAdmissionOrigin.NO_PRIOR_POINTER, + lifecycle); + } + + private static WorldCanonicalInstanceLifecycleEvidence genuineLifecycleEvidence() + throws Exception { + WorldPublishedStartLocationEvidence selector = + WorldPublishedStartLocationGrpcCodecTest.evidence(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + var binding = new CompleteLaunchBindingEvidence(descriptor, release); + var selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + selectorReceipt.startLocation(), + 1042L, + "ACTIVE", + 3L, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request copyLifecycleRequest( + WorldCanonicalInstanceLifecycleEvidence source, UUID readRequestId) { + var request = source.request(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + request.schemaVersion(), + readRequestId, + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.publicProduction(), + request.controlPlaneRequestId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence copyLifecycle( + WorldCanonicalInstanceLifecycleEvidence source, + WorldCanonicalInstanceLifecycleEvidence.Request request, + long lifecycleEpoch) { + return new WorldCanonicalInstanceLifecycleEvidence( + request, + source.launchBinding(), + source.startLocation(), + source.runtimeRoomInstanceId(), + source.lifecycleStatus(), + lifecycleEpoch, + source.rowVersion(), + source.captureId(), + source.graphSha256(), + source.preparationInputDigest(), + source.operationalRegionAssignments()); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java new file mode 100644 index 0000000000..50f80d4687 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java @@ -0,0 +1,859 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInstanceLifecycleEvidenceTest { + private static final UUID NIL = new UUID(0L, 0L); + + @Test + void completeOwnerCaptureAndExactRequestEchoRoundTrip() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = evidence(); + Request request = expected.request(); + + assertThat(Request.fromStored(request.canonicalBytes())).isEqualTo(request); + var wireRequest = WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request); + assertThat(WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(request); + + var firstResponse = WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(request, expected); + var retryResponse = WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(request, expected); + assertThat(retryResponse).isEqualTo(firstResponse); + var decoded = WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(request, firstResponse); + var reread = WorldCanonicalInstanceLifecycleEvidence.fromStored(decoded.canonicalBytes()); + assertThat(decoded.canonicalBytes()).containsExactly(expected.canonicalBytes()); + assertThat(reread).isEqualTo(expected); + assertThat(reread.hashCode()).isEqualTo(expected.hashCode()); + assertThat(reread.operationalRegionAssignments()) + .containsExactlyEntriesOf(expected.operationalRegionAssignments()); + } + + @Test + void rejectsMalformedOperationalRegionAssignmentMapsAndFreezesCallerInput() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + UUID canonicalRegionId = uuid("abcdefab-cdef-4abc-8def-abcdefabcdef"); + UUID operationalRegionId = uuid("22222222-2222-4222-8222-222222222222"); + Map mutableAssignments = new java.util.LinkedHashMap<>(); + mutableAssignments.put(canonicalRegionId, operationalRegionId); + var frozen = + new WorldCanonicalInstanceLifecycleEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest(), + mutableAssignments); + mutableAssignments.clear(); + assertThat(frozen.operationalRegionAssignments()) + .containsExactlyEntriesOf(Map.of(canonicalRegionId, operationalRegionId)); + assertThatThrownBy( + () -> frozen.operationalRegionAssignments().put(canonicalRegionId, operationalRegionId)) + .isInstanceOf(UnsupportedOperationException.class); + + UUID secondCanonicalRegionId = uuid("44444444-4444-4444-8444-444444444444"); + UUID secondOperationalRegionId = uuid("55555555-5555-4555-8555-555555555555"); + Map forward = new java.util.LinkedHashMap<>(); + forward.put(canonicalRegionId, operationalRegionId); + forward.put(secondCanonicalRegionId, secondOperationalRegionId); + Map reverse = new java.util.LinkedHashMap<>(); + reverse.put(secondCanonicalRegionId, secondOperationalRegionId); + reverse.put(canonicalRegionId, operationalRegionId); + assertThat(withAssignments(evidence, forward).canonicalBytes()) + .containsExactly(withAssignments(evidence, reverse).canonicalBytes()); + + String stored = new String(frozen.canonicalBytes(), StandardCharsets.UTF_8); + String assignmentField = + "\"operationalRegionAssignments\":{\"" + + canonicalRegionId + + "\":\"" + + operationalRegionId + + "\"}"; + assertThat(stored).contains(assignmentField); + String legacyShape = stored.replace("," + assignmentField, ""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + legacyShape.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing or unsupported fields"); + assertInvalidStoredAssignments(stored, assignmentField, "{}", "nonempty"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"00000000-0000-0000-0000-000000000000\":\"" + operationalRegionId + "\"}", + "non-nil UUID"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + canonicalRegionId + "\":\"00000000-0000-0000-0000-000000000000\"}", + "non-nil UUID"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + canonicalRegionId + "\":\"" + canonicalRegionId + "\"}", + "must be distinct"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + canonicalRegionId.toString().toUpperCase() + "\":\"" + operationalRegionId + "\"}", + "canonical non-nil UUID"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + + canonicalRegionId + + "\":\"" + + operationalRegionId + + "\",\"" + + canonicalRegionId + + "\":\"" + + uuid("33333333-3333-4333-8333-333333333333") + + "\"}", + "invalid"); + assertInvalidStoredAssignments( + stored, + assignmentField, + "{\"" + + canonicalRegionId + + "\":\"" + + operationalRegionId + + "\",\"" + + uuid("44444444-4444-4444-8444-444444444444") + + "\":\"" + + operationalRegionId + + "\"}", + "duplicate operational region identities"); + } + + @Test + void rejectsChangedCanonicalIdentitiesAndEveryExpectedBindingDigest() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + Request request = evidence.request(); + var changedInstance = + copyRequest( + request, + request.readRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + uuid("99999999-9999-4999-8999-999999999999"), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.controlPlaneRequestId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest()); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse( + changedInstance, + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(request, evidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed exact read request"); + + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "1".repeat(64), + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + uuid("66666666-6666-4666-8666-666666666666"), + null, + null, + null, + null, + null, + null, + null, + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, null, null, "another-world", null, null, null, null, null, null, null, null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + "other-control-request", + null, + null, + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + uuid("88888888-8888-4888-8888-888888888888"), + null, + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "2".repeat(64), + null, + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "3".repeat(64), + null), + "complete launch binding"); + assertRejectedRequest( + evidence, + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + "sha256:" + "4".repeat(64)), + "complete launch binding"); + + var changedSelector = + new RoomTemplateRef( + evidence.startLocation().tenantId(), + evidence.startLocation().versionId(), + uuid("66666666-6666-4666-8666-666666666666")); + assertThatThrownBy( + () -> + with( + evidence, + request, + evidence.launchBinding(), + changedSelector, + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("release selector"); + assertThatThrownBy( + () -> + with( + evidence, + request, + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + "f".repeat(64), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graph digest"); + } + + @Test + void rejectsUnselectedV1ReleaseAndMalformedLifecycleCountersOrDigests() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + var request = evidence.request(); + var descriptor = evidence.launchBinding().descriptor(); + var release = evidence.launchBinding().releaseAttestation(); + var v1Release = + AuthoredWorldReleaseAttestationEvidence.create( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + release.publishWorkflowId(), + release.commitId(), + release.participantDigests(), + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision()); + var v1Request = + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + v1Release.evidenceDigest()); + assertThatThrownBy( + () -> + with( + evidence, + v1Request, + new CompleteLaunchBindingEvidence(descriptor, v1Release), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("selector/v2"); + + assertInvalid(evidence, evidence.runtimeRoomInstanceId(), evidence.lifecycleEpoch(), -1); + assertInvalid(evidence, evidence.runtimeRoomInstanceId(), 0, evidence.rowVersion()); + assertInvalid(evidence, 0, evidence.lifecycleEpoch(), evidence.rowVersion()); + assertThatThrownBy( + () -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + NIL, + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("captureId"); + assertThatThrownBy( + () -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + "A".repeat(64), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graphSha256"); + } + + @Test + void requestOnlyAcceptsProvedSharedPublicProductionIdentity() throws Exception { + Request request = evidence().request(); + assertThatThrownBy( + () -> + copyRequest( + request, NIL, null, null, null, null, null, null, null, null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("readRequestId"); + assertThatThrownBy( + () -> + copyRequest( + request, + null, + null, + null, + null, + null, + "ISOLATED", + null, + null, + null, + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SHARED scope only"); + assertThatThrownBy( + () -> + new Request( + request.schemaVersion(), + request.readRequestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + false, + request.controlPlaneRequestId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("public-production evidence"); + assertThatThrownBy( + () -> + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + "not-a-digest", + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("expectedDescriptorRequestDigest"); + } + + @Test + void preservesLongPrecisionAndRejectsOverflowOrNoncanonicalDecimalStrings() throws Exception { + WorldCanonicalInstanceLifecycleEvidence expected = evidence(); + long beyondJavaScriptInteger = 9_007_199_254_740_993L; + WorldCanonicalInstanceLifecycleEvidence precise = + with( + expected, + expected.request(), + expected.launchBinding(), + expected.startLocation(), + beyondJavaScriptInteger, + expected.lifecycleStatus(), + beyondJavaScriptInteger + 2, + beyondJavaScriptInteger + 4, + expected.captureId(), + expected.graphSha256(), + expected.preparationInputDigest()); + assertThat(WorldCanonicalInstanceLifecycleEvidence.fromStored(precise.canonicalBytes())) + .isEqualTo(precise); + + WorldCanonicalInstanceLifecycleEvidence maximum = + with( + expected, + expected.request(), + expected.launchBinding(), + expected.startLocation(), + Long.MAX_VALUE, + expected.lifecycleStatus(), + Long.MAX_VALUE, + Long.MAX_VALUE, + expected.captureId(), + expected.graphSha256(), + expected.preparationInputDigest()); + byte[] maxBytes = maximum.canonicalBytes(); + assertThat(WorldCanonicalInstanceLifecycleEvidence.fromStored(maxBytes)).isEqualTo(maximum); + String maxJson = new String(maxBytes, StandardCharsets.UTF_8); + String overflow = + maxJson.replace( + "\"runtimeRoomInstanceId\":\"" + Long.MAX_VALUE + "\"", + "\"runtimeRoomInstanceId\":\"9223372036854775808\""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + overflow.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("supported integer range"); + String negative = + maxJson.replace( + "\"lifecycleEpoch\":\"" + Long.MAX_VALUE + "\"", "\"lifecycleEpoch\":\"-1\""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + negative.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical positive decimal"); + String leadingZero = + maxJson.replace("\"rowVersion\":\"" + Long.MAX_VALUE + "\"", "\"rowVersion\":\"01\""); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + leadingZero.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical nonnegative decimal"); + } + + @Test + void rejectsClosedJsonAndProtobufUnknownOrDuplicateFields() throws Exception { + WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); + String stored = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); + String unknownField = stored.substring(0, 1) + "\"unsupported\":true," + stored.substring(1); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + unknownField.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + String duplicate = + stored.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + duplicate.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> Request.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strict UTF-8"); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strict UTF-8"); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + ReadWorldCanonicalInstanceLifecycleRequest request = + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(evidence.request()).toBuilder() + .setUnknownFields(unknown) + .build(); + assertThatThrownBy(() -> WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + ReadWorldCanonicalInstanceLifecycleResponse response = + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(evidence.request(), evidence) + .toBuilder() + .setUnknownFields(unknown) + .build(); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(evidence.request(), response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse( + evidence.request(), + ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.EMPTY) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("required"); + } + + private static void assertRejectedRequest( + WorldCanonicalInstanceLifecycleEvidence evidence, Request changed, String message) { + assertThatThrownBy( + () -> + with( + evidence, + changed, + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(message); + } + + private static void assertInvalid( + WorldCanonicalInstanceLifecycleEvidence evidence, + long runtimeRoomInstanceId, + long lifecycleEpoch, + long rowVersion) { + assertThatThrownBy( + () -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + runtimeRoomInstanceId, + evidence.lifecycleStatus(), + lifecycleEpoch, + rowVersion, + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldCanonicalInstanceLifecycleEvidence with( + WorldCanonicalInstanceLifecycleEvidence source, + Request request, + CompleteLaunchBindingEvidence launchBinding, + RoomTemplateRef startLocation, + long runtimeRoomInstanceId, + String lifecycleStatus, + long lifecycleEpoch, + long rowVersion, + UUID captureId, + String graphSha256, + String preparationInputDigest) { + return new WorldCanonicalInstanceLifecycleEvidence( + request, + launchBinding, + startLocation, + runtimeRoomInstanceId, + lifecycleStatus, + lifecycleEpoch, + rowVersion, + captureId, + graphSha256, + preparationInputDigest, + source.operationalRegionAssignments()); + } + + private static Request copyRequest( + Request source, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String playableStateScope, + String controlPlaneRequestId, + UUID canonicalVersionId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationDigest) { + return new Request( + Request.SCHEMA_VERSION, + readRequestId == null ? source.readRequestId() : readRequestId, + source.targetNamespace(), + canonicalTenantId == null ? source.canonicalTenantId() : canonicalTenantId, + worldSlug == null ? source.worldSlug() : worldSlug, + canonicalGameInstanceId == null + ? source.canonicalGameInstanceId() + : canonicalGameInstanceId, + playableStateNamespaceId == null + ? source.playableStateNamespaceId() + : playableStateNamespaceId, + playableStateScope == null ? source.playableStateScope() : playableStateScope, + source.publicProduction(), + controlPlaneRequestId == null ? source.controlPlaneRequestId() : controlPlaneRequestId, + canonicalVersionId == null ? source.canonicalVersionId() : canonicalVersionId, + expectedDescriptorRequestDigest == null + ? source.expectedDescriptorRequestDigest() + : expectedDescriptorRequestDigest, + expectedDescriptorResultDigest == null + ? source.expectedDescriptorResultDigest() + : expectedDescriptorResultDigest, + expectedReleaseAttestationDigest == null + ? source.expectedReleaseAttestationDigest() + : expectedReleaseAttestationDigest); + } + + private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Exception { + WorldPublishedStartLocationEvidence selector = + WorldPublishedStartLocationGrpcCodecTest.evidence(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + RoomTemplateRef startLocation = selectorReceipt.startLocation(); + Request request = + new Request( + Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 1042L, + "PREPARING", + 3L, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64), + Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + + private static void assertInvalidStoredAssignments( + String stored, String assignmentField, String replacement, String message) { + String malformed = + stored.replace(assignmentField, "\"operationalRegionAssignments\":" + replacement); + assertThatThrownBy( + () -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + malformed.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(message); + } + + private static WorldCanonicalInstanceLifecycleEvidence withAssignments( + WorldCanonicalInstanceLifecycleEvidence source, Map assignments) { + return new WorldCanonicalInstanceLifecycleEvidence( + source.request(), + source.launchBinding(), + source.startLocation(), + source.runtimeRoomInstanceId(), + source.lifecycleStatus(), + source.lifecycleEpoch(), + source.rowVersion(), + source.captureId(), + source.graphSha256(), + source.preparationInputDigest(), + assignments); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java new file mode 100644 index 0000000000..207da9778e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java @@ -0,0 +1,493 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsReadServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical mTLS proof against a labeled transport-only World source double. */ +class WorldPublishedSpawnRequirementsClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_WORLD_URI = + "spiffe://firemud/ns/other-test/sa/world-management-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final String WRONG_CLIENT_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private WorldPublishedSpawnRequirementsClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createTrustedCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void exactWorldPeerReturnsUnchangedSourceCarrierAndExactRequestId() throws Exception { + var expected = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + startServer(pki.worldServer(), Mode.EXACT); + client = newClient(server, pki.entityClient()); + client.init(); + + var actual = client.read(expected.request()); + + assertThat(actual).isEqualTo(expected); + assertThat(actual.request().readRequestId()).isEqualTo(expected.request().readRequestId()); + assertThat(actual.familyCounts()).isEqualTo(expected.familyCounts()); + assertThat(actual.spawnRequirements()).isEqualTo(expected.spawnRequirements()); + assertThat(actual.generationRequirements()).isEqualTo(expected.generationRequirements()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + } + + @Test + void trustedWrongWorldWorkloadAndNamespaceReleaseNoRequestMetadataOrBody() throws Exception { + var request = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence().request(); + for (TestIdentity identity : List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer())) { + startServer(identity, Mode.EXACT); + client = newClient(server, pki.entityClient()); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + exception -> + assertThat(Status.fromThrowable(exception).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + stopTransport(); + } + } + + @Test + void rejectsChangedRequestReleaseGraphAndFamilyEvidenceAfterAuthenticatedRead() throws Exception { + var request = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence().request(); + for (Mode mode : + List.of( + Mode.CHANGED_REQUEST, Mode.CHANGED_RELEASE, Mode.CHANGED_GRAPH, Mode.CHANGED_FAMILY)) { + startServer(pki.worldServer(), mode); + client = newClient(server, pki.entityClient()); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid published spawn-requirements evidence"); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + stopTransport(); + } + } + + @Test + void rejectsWrongLocalWorkloadPlaintextAndNonFileBackedTls() throws Exception { + var request = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence().request(); + startServer(pki.worldServer(), Mode.EXACT); + + assertThatThrownBy(() -> newClient(server, pki.wrongClient())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact same-namespace Entity workload identity"); + + var plaintext = pki.clientProperties(tempDirectory, pki.entityClient()); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + endpoints(server), plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var classpath = pki.clientProperties(tempDirectory, pki.entityClient()); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + endpoints(server), classpath, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + client = newClient(server, pki.entityClient()); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + client.init(); + client.close(); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + assertThat(headers).hasValue(0); + } + + private enum Mode { + EXACT, + CHANGED_REQUEST, + CHANGED_RELEASE, + CHANGED_GRAPH, + CHANGED_FAMILY + } + + private void startServer(TestIdentity identity, Mode mode) throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var service = + new WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceImplBase() { + @Override + public void readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ENTITY_URI); + var request = WorldPublishedSpawnRequirementsGrpcCodec.fromRequest(wire); + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + var response = WorldPublishedSpawnRequirementsGrpcCodec.toResponse(request, evidence); + if (mode == Mode.CHANGED_REQUEST) { + response = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setReadRequestId("ffffffff-ffff-4fff-8fff-ffffffffffff")) + .build(); + } else if (mode == Mode.CHANGED_RELEASE) { + response = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setExpectedReleaseAttestationDigest("sha256:" + "f".repeat(64))) + .build(); + } else if (mode == Mode.CHANGED_GRAPH) { + response = response.toBuilder().setGraphDigest("sha256:" + "f".repeat(64)).build(); + } else if (mode == Mode.CHANGED_FAMILY) { + response = + response.toBuilder() + .setFamilyCounts( + 0, + response.getFamilyCounts(0).toBuilder() + .setFamily( + net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_UNSPECIFIED)) + .build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private WorldPublishedSpawnRequirementsClient newClient(Server target, TestIdentity local) + throws Exception { + return new WorldPublishedSpawnRequirementsClient( + endpoints(target), + pki.clientProperties(tempDirectory, local), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ServiceEndpointsProperties endpoints(Server target) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + target.getPort()); + return endpoints; + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity worldServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity entityClient, + TestIdentity wrongClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD spawn-requirements test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "world-server", WORLD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-workload-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-namespace-server", OTHER_WORLD_URI, true), + issueIdentity(directory, caStore, caFile, "entity-client", ENTITY_URI, false), + issueIdentity(directory, caStore, caFile, "wrong-client", WRONG_CLIENT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("entity-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("entity-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new java.util.ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java new file mode 100644 index 0000000000..1e73376529 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +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 org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsClientTest { + @Test + void rejectsPlaintextAndInvalidNamespaceBeforeCreatingTransport() { + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + new ServiceEndpointsProperties(), + plaintext, + mock(GrpcChannelFactory.class), + "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(Path.of("missing.crt").toString()); + tls.setPrivateKey(Path.of("missing.key").toString()); + tls.setCaCert(Path.of("missing-ca.crt").toString()); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "Test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java new file mode 100644 index 0000000000..b2a8dcec71 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsEvidenceTest { + @Test + void retainsImmutableOriginalRequirementsAndArbitraryPrecisionRevisionOrder() { + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + + assertThat(evidence.spawnRequirements()).hasSize(2); + assertThat(evidence.spawnRequirements().get(0).revisionOrder()).isEqualTo("9007199254740993"); + assertThat(evidence.spawnRequirements().get(0).spawnCount()).isEqualTo(7); + assertThat(evidence.spawnRequirements().get(0).respawnDelaySeconds()).isEqualTo(2700); + assertThat(evidence.spawnRequirements().get(0).roomTemplate().tenantId()) + .isEqualTo(evidence.launchBinding().releaseAttestation().canonicalTenantId()); + assertThat(evidence.spawnRequirements().get(0).entityTemplate().kind().name()) + .isEqualTo("ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM"); + assertThat(evidence.generationRequirements().get(0).revisionOrder()) + .isEqualTo("9007199254740992"); + assertThat(evidence.generationRequirements().get(0).value()).isEqualTo(" authored value "); + assertThatThrownBy(evidence.spawnRequirements()::clear) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(evidence.generationRequirements()::clear) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void deniesDuplicateIdentityAndNonIncreasingRevisionOrder() { + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + var first = evidence.spawnRequirements().get(0); + var second = evidence.spawnRequirements().get(1); + + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + evidence.graphDigest(), + evidence.familyCounts(), + List.of( + first, + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + "9007199254740994", + second.revisionId(), + first.spawnBindingId(), + second.roomTemplate(), + second.entityTemplate(), + second.spawnCount(), + second.respawnDelaySeconds())), + evidence.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("binding identity"); + + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + evidence.graphDigest(), + evidence.familyCounts(), + List.of(second, first), + evidence.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strictly increasing revision order"); + } + + @Test + void bindsGraphDigestToTheReleaseSelectorReceipt() { + var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); + + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + "sha256:" + "f".repeat(64), + evidence.familyCounts(), + evidence.spawnRequirements(), + evidence.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graph digest"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java new file mode 100644 index 0000000000..fd3e886c9e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java @@ -0,0 +1,443 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsFamilyCount; +import org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsGrpcCodecTest { + private static final UUID READ_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID OTHER_ID = uuid("44444444-4444-4444-8444-444444444444"); + + @Test + void roundTripsExactRequestCompletePairAndOriginalRequirementValues() { + var expected = evidence(); + var request = WorldPublishedSpawnRequirementsGrpcCodec.toRequest(expected.request()); + assertThat(WorldPublishedSpawnRequirementsGrpcCodec.fromRequest(request)) + .isEqualTo(expected.request()); + + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); + var actual = + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse(expected.request(), response); + + assertThat(actual).isEqualTo(expected); + assertThat(actual.spawnRequirements()).hasSize(2); + assertThat(actual.spawnRequirements().getFirst().revisionOrder()).isEqualTo("9007199254740993"); + assertThat(actual.spawnRequirements().getFirst().spawnCount()).isEqualTo(7); + assertThat(actual.spawnRequirements().getFirst().respawnDelaySeconds()).isEqualTo(2700); + assertThat(actual.spawnRequirements().getFirst().entityTemplate()) + .isEqualTo(expected.spawnRequirements().getFirst().entityTemplate()); + assertThat(actual.generationRequirements().getFirst().revisionOrder()) + .isEqualTo("9007199254740992"); + assertThat(actual.generationRequirements().getFirst().value()).isEqualTo(" authored value "); + } + + @Test + void rejectsChangedRequestScopeReleaseAndMalformedCapture() { + var expected = evidence(); + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); + + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder().setReadRequestId(OTHER_ID.toString())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder().setGraphDigest("sha256:" + "f".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("graph digest"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setExpectedReleaseAttestationDigest("sha256:" + "f".repeat(64))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact source-read request"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setCompleteLaunchBinding( + response.getCompleteLaunchBinding().toBuilder() + .setReleaseAttestation( + response + .getCompleteLaunchBinding() + .getReleaseAttestation() + .toBuilder() + .setCanonicalTenantId(OTHER_ID.toString()))) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setCaptureId("00000000-0000-0000-0000-000000000000") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("captureId"); + } + + @Test + void rejectsMissingNestedEvidenceUnknownFieldsAndChangedAuthoredScope() { + var expected = evidence(); + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().clearRequest().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().clearCompleteLaunchBinding().build())) + .isInstanceOf(IllegalArgumentException.class); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setLaunchBindingRequest( + response.getRequest().getLaunchBindingRequest().toBuilder() + .setUnknownFields(unknown))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setSpawnRequirements( + 0, + response.getSpawnRequirements(0).toBuilder() + .setRoomTemplate( + response.getSpawnRequirements(0).getRoomTemplate().toBuilder() + .setTenantId(OTHER_ID.toString()))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical tenant/version context"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setSpawnRequirements( + 0, + response.getSpawnRequirements(0).toBuilder() + .setRoomTemplate( + response.getSpawnRequirements(0).getRoomTemplate().toBuilder() + .setUnknownFields(unknown))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + @Test + void requiresAllSixExplicitCountsAndRejectsCountListMismatch() { + var empty = emptyEvidence(); + var emptyResponse = WorldPublishedSpawnRequirementsGrpcCodec.toResponse(empty.request(), empty); + assertThat(emptyResponse.getFamilyCountsCount()).isEqualTo(6); + for (var count : emptyResponse.getFamilyCountsList()) { + assertThat(count.hasCount()).isTrue(); + assertThat(count.getCount()).isZero(); + } + assertThat( + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse(empty.request(), emptyResponse)) + .isEqualTo(empty); + + var populated = evidence(); + var response = + WorldPublishedSpawnRequirementsGrpcCodec.toResponse(populated.request(), populated); + var badCount = + WorldPublishedSpawnRequirementsFamilyCount.newBuilder() + .setFamily(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .setCount(1) + .build(); + assertThatThrownBy( + () -> + new WorldPublishedSpawnRequirementsEvidence( + populated.request(), + populated.launchBinding(), + populated.captureId(), + populated.graphDigest(), + List.of( + populated.familyCounts().get(0), + populated.familyCounts().get(1), + populated.familyCounts().get(2), + populated.familyCounts().get(3), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + badCount.getFamily(), badCount.getCount()), + populated.familyCounts().get(5)), + populated.spawnRequirements(), + populated.generationRequirements())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("count differs"); + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + populated.request(), + response.toBuilder() + .setFamilyCounts(4, response.getFamilyCounts(4).toBuilder().setCount(1)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("count differs"); + + assertThatThrownBy( + () -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + empty.request(), + emptyResponse.toBuilder() + .setFamilyCounts( + 0, emptyResponse.getFamilyCounts(0).toBuilder().clearCount()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not explicitly present"); + } + + static WorldPublishedSpawnRequirementsEvidence evidence() { + CompleteLaunchBindingEvidence binding = completeBinding(); + var request = request(binding); + UUID tenant = binding.releaseAttestation().canonicalTenantId(); + UUID version = binding.releaseAttestation().canonicalVersionId(); + var item = + new WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference( + net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType + .ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + tenant, + version, + uuid("66666666-6666-4666-8666-666666666666")); + var npc = + new WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference( + net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType + .ENTITY_TEMPLATE_REFERENCE_TYPE_NPC, + tenant, + version, + uuid("77777777-7777-4777-8777-777777777777")); + return new WorldPublishedSpawnRequirementsEvidence( + request, + binding, + uuid("88888888-8888-4888-8888-888888888888"), + graphDigest(binding), + counts(1, 2, 3, 4, 2, 2), + List.of( + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + "9007199254740993", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + new RoomTemplateRef(tenant, version, uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc")), + item, + 7, + 2700), + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + "9007199254740994", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + new RoomTemplateRef(tenant, version, uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")), + npc, + 0, + 0)), + List.of( + new WorldPublishedSpawnRequirementsEvidence.GenerationRequirement( + "9007199254740992", + uuid("12345678-1234-4234-8234-123456789001"), + uuid("12345678-1234-4234-8234-123456789101"), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + uuid("12345678-1234-4234-8234-123456789201"), + "difficulty.mode", + " authored value "), + new WorldPublishedSpawnRequirementsEvidence.GenerationRequirement( + "9007199254740995", + uuid("12345678-1234-4234-8234-123456789002"), + uuid("12345678-1234-4234-8234-123456789102"), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + uuid("12345678-1234-4234-8234-123456789202"), + "population.mode", + "sparse"))); + } + + static WorldPublishedSpawnRequirementsEvidence emptyEvidence() { + CompleteLaunchBindingEvidence binding = completeBinding(); + return new WorldPublishedSpawnRequirementsEvidence( + request(binding), + binding, + uuid("88888888-8888-4888-8888-888888888888"), + graphDigest(binding), + counts(0, 0, 0, 0, 0, 0), + List.of(), + List.of()); + } + + private static List counts( + int region, int zone, int room, int exit, int generation, int spawn) { + return List.of( + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, region), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, zone), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, room), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, exit), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, generation), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + spawn)); + } + + private static WorldPublishedSpawnRequirementsEvidence.Request request( + CompleteLaunchBindingEvidence binding) { + var descriptor = binding.descriptor(); + GetLaunchDescriptorRequest selector = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_ID.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + return new WorldPublishedSpawnRequirementsEvidence.Request( + descriptor.targetNamespace(), + READ_ID, + selector, + binding.releaseAttestation().evidenceDigest()); + } + + private static String graphDigest(CompleteLaunchBindingEvidence binding) { + return WorldDraftStartLocationEvidence.fromStored( + binding.releaseAttestation().worldStartLocationEvidence().selectorReceiptBytes()) + .graphDigest(); + } + + private static CompleteLaunchBindingEvidence completeBinding() { + WorldPublishedStartLocationEvidence worldStart; + try { + worldStart = WorldPublishedStartLocationGrpcCodecTest.evidence(); + } catch (Exception impossible) { + throw new AssertionError(impossible); + } + var selection = worldStart.request(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selection.targetNamespace(), + "launch-control-request", + selection.canonicalTenantId(), + "synthetic-world", + uuid("99999999-9999-4999-8999-999999999999"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "descriptor", + Long.MAX_VALUE, + false, + null, + "{}", + "generation-config", + 9L, + 7L, + "published-release", + false, + null); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selection.appliedCommitId(), + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selection.canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selection.publishWorkflowId(), + selection.appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + worldStart); + return new CompleteLaunchBindingEvidence(descriptor, release); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java new file mode 100644 index 0000000000..ad31df4c00 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java @@ -0,0 +1,155 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.stub.AbstractStub; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +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.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationReadServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class WorldPublishedStartLocationClientTest { + @Test + void rejectsPlaintextAndWrongNamespaceBeforeCreatingTransport(@TempDir Path directory) + throws Exception { + var channelFactory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var client = + new WorldPublishedStartLocationClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "test"); + try { + var request = WorldPublishedStartLocationGrpcCodecTest.evidence().request(); + assertThatThrownBy(() -> client.read(withNamespace(request, "other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesExactWorldPeerCredentialsAndReadsValidatedEvidence(@TempDir Path directory) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + var channelFactory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new WorldPublishedStartLocationClient(endpoints, tls(directory), channelFactory, "test"); + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + AbstractStub initializedStub = initializedStub(client); + assertThat(initializedStub.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(initializedStub.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/world-management-service"); + + WorldPublishedStartLocationEvidence evidence = + WorldPublishedStartLocationGrpcCodecTest.evidence(); + var stub = + mock( + WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + setStub(client, stub); + var response = WorldPublishedStartLocationGrpcCodec.toResponse(evidence.request(), evidence); + when(stub.readWorldPublishedStartLocation(any())).thenReturn(response); + assertThat(client.read(evidence.request()).canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + + when(stub.readWorldPublishedStartLocation(any())) + .thenReturn( + response.toBuilder() + .setAppliedResultBytes(com.google.protobuf.ByteString.copyFrom(new byte[] {1})) + .build()); + assertThatThrownBy(() -> client.read(evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid published selector evidence"); + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + } finally { + client.close(); + } + } + + private static AbstractStub initializedStub(WorldPublishedStartLocationClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + private static void setStub(WorldPublishedStartLocationClient client, AbstractStub stub) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } + + private static WorldPublishedStartLocationEvidence.Request withNamespace( + WorldPublishedStartLocationEvidence.Request source, String namespace) { + return new WorldPublishedStartLocationEvidence.Request( + namespace, + source.canonicalTenantId(), + source.canonicalVersionId(), + source.intakeRequestId(), + source.publicationFence(), + source.publicationRequestId(), + source.requestDigest(), + source.versionStateEpoch(), + source.publishWorkflowId(), + source.appliedCommitId(), + source.contentDigest(), + source.digestSchemaVersion(), + source.worldAffectedTuples()); + } + + private static CommonGrpcClientProperties tls(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/world/WorldPublishedStartLocationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java new file mode 100644 index 0000000000..58a6606492 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java @@ -0,0 +1,179 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodecTest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import org.junit.jupiter.api.Test; + +class WorldPublishedStartLocationGrpcCodecTest { + private static final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + @Test + void exactSelectionAndRetainedEvidenceRoundTripAcrossReadRetries() throws Exception { + WorldPublishedStartLocationEvidence expected = evidence(); + var wireRequest = WorldPublishedStartLocationGrpcCodec.toRequest(expected.request()); + assertThat(WorldPublishedStartLocationGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(expected.request()); + + var firstResponse = + WorldPublishedStartLocationGrpcCodec.toResponse(expected.request(), expected); + var retryResponse = + WorldPublishedStartLocationGrpcCodec.toResponse(expected.request(), expected); + assertThat(retryResponse).isEqualTo(firstResponse); + var first = + WorldPublishedStartLocationGrpcCodec.fromResponse(expected.request(), firstResponse); + var retry = + WorldPublishedStartLocationGrpcCodec.fromResponse(expected.request(), retryResponse); + assertThat(first.canonicalBytes()).containsExactly(expected.canonicalBytes()); + assertThat(retry.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat( + WorldPublishedStartLocationEvidence.fromStored(first.canonicalBytes()).canonicalBytes()) + .containsExactly(first.canonicalBytes()); + var decoded = WorldPublishedStartLocationEvidence.fromStored(first.canonicalBytes()); + assertThat(decoded).isEqualTo(expected); + assertThat(decoded.hashCode()).isEqualTo(expected.hashCode()); + } + + @Test + void rejectsChangedSelectionAndSubstitutedReceiptAccountOrAppliedBytes() throws Exception { + WorldPublishedStartLocationEvidence evidence = evidence(); + ReadWorldPublishedStartLocationResponse response = + WorldPublishedStartLocationGrpcCodec.toResponse(evidence.request(), evidence); + + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setPublicationFence( + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed exact selection"); + + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setSelectorReceiptBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setOriginalAccountBindingBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setAppliedResultBytes(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new WorldPublishedStartLocationEvidence( + evidence.request(), + evidence.selectorReceiptBytes(), + evidence.originalAccountBindingBytes(), + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + + var changedIntake = + new WorldPublishedStartLocationEvidence.Request( + evidence.request().targetNamespace(), + evidence.request().canonicalTenantId(), + evidence.request().canonicalVersionId(), + uuid("99999999-9999-4999-8999-999999999999"), + evidence.request().publicationFence(), + evidence.request().publicationRequestId(), + evidence.request().requestDigest(), + evidence.request().versionStateEpoch(), + evidence.request().publishWorkflowId(), + evidence.request().appliedCommitId(), + evidence.request().contentDigest(), + evidence.request().digestSchemaVersion(), + evidence.request().worldAffectedTuples()); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationEvidence( + changedIntake, + evidence.selectorReceiptBytes(), + evidence.originalAccountBindingBytes(), + evidence.appliedResultBytes())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intake request"); + } + + static WorldPublishedStartLocationEvidence evidence() throws Exception { + WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); + OwnerReadback committed = freshGraphReadback(terminalRequest); + var account = terminalRequest.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + account.tenantId(), + account.versionId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var applied = JSON.readTree(committed.result()); + byte[] receipt = + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + return new WorldPublishedStartLocationEvidence( + request, receipt, committed.fullBinding(), committed.result()); + } + + private static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + return WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); + } + + private static OwnerReadback freshGraphReadback(WorldDraftTerminalReadEvidence.Request request) + throws Exception { + return WorldDraftTerminalReadGrpcCodecTest + .committedFreshGraphReadbackForStartLocationEvidenceTest(request); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-redis-contracts/build.gradle.kts b/services/common-redis-contracts/build.gradle.kts new file mode 100644 index 0000000000..21b2a9c74b --- /dev/null +++ b/services/common-redis-contracts/build.gradle.kts @@ -0,0 +1,9 @@ +plugins { + `java-library` +} + +dependencies { + implementation("tools.jackson.core:jackson-databind") + + testImplementation(libs.spring.boot.starter.test) +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalog.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalog.java new file mode 100644 index 0000000000..4522628d2a --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalog.java @@ -0,0 +1,80 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.ServiceLoader; + +/** + * Immutable aggregation of the owner contributions installed in this class loader. + * + *

This is a shared schema/aggregation surface, not proof that every repository owner or script + * has contributed to a complete repository-wide catalog. + */ +public final class RedisScriptCatalog { + public static final int MAX_CONTRIBUTIONS = 128; + public static final int MAX_DESCRIPTORS = 1024; + + private final Map descriptorsById; + + private RedisScriptCatalog(Collection contributions) { + Objects.requireNonNull(contributions, "Redis script contributions are required"); + if (contributions.size() > MAX_CONTRIBUTIONS) { + throw new IllegalArgumentException("Redis script contribution count exceeds its bound"); + } + Map collected = new LinkedHashMap<>(); + int count = 0; + for (RedisScriptContribution contribution : contributions) { + Objects.requireNonNull(contribution, "Redis script contribution is required"); + String ownerId = + Objects.requireNonNull(contribution.ownerId(), "Contribution owner is required"); + Collection descriptors = + Objects.requireNonNull( + contribution.descriptors(), "Contribution descriptors are required"); + if (descriptors.isEmpty()) { + throw new IllegalArgumentException("Redis script contribution cannot be empty"); + } + for (RedisScriptDescriptor descriptor : descriptors) { + Objects.requireNonNull(descriptor, "Redis script descriptor is required"); + if (!ownerId.equals(descriptor.owner())) { + throw new IllegalArgumentException( + "Redis script descriptor owner does not match contribution"); + } + if (++count > MAX_DESCRIPTORS) { + throw new IllegalArgumentException("Redis script descriptor count exceeds its bound"); + } + if (collected.putIfAbsent(descriptor.scriptId(), descriptor) != null) { + throw new IllegalArgumentException("Duplicate Redis script descriptor identity"); + } + } + } + this.descriptorsById = Map.copyOf(collected); + } + + /** Aggregates service-provider contributions installed in the supplied class loader. */ + public static RedisScriptCatalog loadInstalled(ClassLoader classLoader) { + Objects.requireNonNull(classLoader, "Class loader is required"); + return new RedisScriptCatalog( + ServiceLoader.load(RedisScriptContribution.class, classLoader).stream() + .map(ServiceLoader.Provider::get) + .toList()); + } + + /** Bounded constructor surface for owner-local tests and explicitly assembled applications. */ + public static RedisScriptCatalog fromContributions( + Collection contributions) { + return new RedisScriptCatalog(contributions); + } + + public RedisScriptDescriptor require(String id) { + Objects.requireNonNull(id, "Redis script id is required"); + RedisScriptDescriptor descriptor = descriptorsById.get(id); + if (descriptor == null) throw new IllegalArgumentException("Redis script is not registered"); + return descriptor; + } + + public Collection descriptors() { + return descriptorsById.values(); + } +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptContribution.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptContribution.java new file mode 100644 index 0000000000..e63270cf29 --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptContribution.java @@ -0,0 +1,11 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.util.Collection; + +/** Service-provider entry point for owner-local Redis script descriptors. */ +public interface RedisScriptContribution { + /** Exact service owner identifier declared by every descriptor returned here. */ + String ownerId(); + + Collection descriptors(); +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java new file mode 100644 index 0000000000..f7203482ba --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java @@ -0,0 +1,264 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; + +/** Immutable declaration of one versioned, owner-executed Redis script contract. */ +public record RedisScriptDescriptor( + String scriptId, + String resourcePath, + String sha256, + String owner, + String principal, + RedisRole role, + List keys, + List arguments, + ScriptCategory category, + List outcomes, + ResetSensitivity resetSensitivity, + LossClass lossClass, + String tailLossBehavior, + CompatibilityLevel compatibilityLevel, + List supportedCoexistence, + String legacyPayloadShape) { + + public static final String NO_PAYLOAD_VERSION = "none"; + public static final String LEGACY_PAYLOAD_VERSION = "legacy"; + + private static final Pattern SCRIPT_ID_PATTERN = + Pattern.compile("[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)*\\.v[1-9][0-9]*"); + private static final Pattern RESOURCE_PATH_PATTERN = + Pattern.compile("redis/(?:[a-z0-9][a-z0-9_-]*/)*[a-z0-9][a-z0-9_-]*\\.lua"); + private static final Pattern OWNER_PATTERN = Pattern.compile("[a-z][a-z0-9-]*"); + private static final Pattern PRINCIPAL_PATTERN = Pattern.compile("[a-z][a-z0-9_]*"); + private static final Pattern PREFIX_PATTERN = + Pattern.compile("[a-z][a-z0-9_-]*(?::[a-z][a-z0-9_-]*)*:"); + private static final Pattern DECLARATION_NAME_PATTERN = Pattern.compile("[a-z][A-Za-z0-9]*"); + private static final Pattern OUTCOME_CODE_PATTERN = Pattern.compile("[A-Z][A-Z0-9_]*"); + private static final Pattern VERSION_PATTERN = Pattern.compile("v[1-9][0-9]*"); + + public RedisScriptDescriptor { + requireMatch(scriptId, SCRIPT_ID_PATTERN, "scriptId must be a supported versioned identifier"); + requireMatch( + resourcePath, + RESOURCE_PATH_PATTERN, + "resourcePath must be a relative redis/ classpath Lua resource path"); + requireMatch(sha256, Pattern.compile("[0-9a-f]{64}"), "sha256 must be 64 lowercase hex digits"); + requireMatch(owner, OWNER_PATTERN, "owner must be a lowercase service identifier"); + requireMatch(principal, PRINCIPAL_PATTERN, "principal must be a lowercase Redis principal"); + Objects.requireNonNull(role, "role is required"); + Objects.requireNonNull(category, "category is required"); + Objects.requireNonNull(resetSensitivity, "resetSensitivity is required"); + Objects.requireNonNull(lossClass, "lossClass is required"); + Objects.requireNonNull(compatibilityLevel, "compatibilityLevel is required"); + + keys = immutableNonEmpty(keys, "KEYS declarations are required"); + arguments = + immutable(arguments, "ARGV declarations are required, including an explicit empty list"); + outcomes = immutableNonEmpty(outcomes, "outcomes are required"); + supportedCoexistence = + immutableNonEmpty( + supportedCoexistence, "supported caller/payload coexistence metadata is required"); + tailLossBehavior = requireDescription(tailLossBehavior, "tailLossBehavior"); + legacyPayloadShape = optionalDescription(legacyPayloadShape, "legacyPayloadShape"); + + Set keyNames = new HashSet<>(); + for (KeySpec key : keys) { + if (!keyNames.add(key.name())) { + throw new IllegalArgumentException("duplicate KEYS declaration name: " + key.name()); + } + } + + Set argumentNames = new HashSet<>(); + for (ArgumentSpec argument : arguments) { + if (!argumentNames.add(argument.name())) { + throw new IllegalArgumentException("duplicate ARGV declaration name: " + argument.name()); + } + } + + Set outcomeCodes = new HashSet<>(); + for (OutcomeSpec outcome : outcomes) { + if (!outcomeCodes.add(outcome.code())) { + throw new IllegalArgumentException("duplicate outcome code: " + outcome.code()); + } + } + + Set combinations = new HashSet<>(); + boolean supportsLegacyPayload = false; + for (SupportedCoexistence combination : supportedCoexistence) { + if (!combinations.add(combination)) { + throw new IllegalArgumentException("duplicate caller/payload coexistence declaration"); + } + supportsLegacyPayload |= combination.payloadVersion().equals(LEGACY_PAYLOAD_VERSION); + } + if (supportsLegacyPayload && legacyPayloadShape == null) { + throw new IllegalArgumentException( + "legacyPayloadShape is required when a versionless payload is supported"); + } + if (!supportsLegacyPayload && legacyPayloadShape != null) { + throw new IllegalArgumentException( + "legacyPayloadShape is only valid when a legacy payload is supported"); + } + + if (keys.size() > 1 + && keys.stream().anyMatch(key -> key.hashTagDeclaration() != HashTagDeclaration.REQUIRED)) { + throw new IllegalArgumentException( + "every KEYS declaration in a multi-key script must require a hash tag"); + } + } + + public List keys() { + return List.copyOf(keys); + } + + public List arguments() { + return List.copyOf(arguments); + } + + public List outcomes() { + return List.copyOf(outcomes); + } + + public List supportedCoexistence() { + return List.copyOf(supportedCoexistence); + } + + public enum RedisRole { + COORDINATION, + CACHE_RATE_LIMIT + } + + public enum HashTagDeclaration { + NOT_REQUIRED, + REQUIRED + } + + public enum ScriptCategory { + TICK_LOCK, + TIMER_QUEUE, + SESSION_CAS, + SESSION_TO_REGION_BRIDGE, + MAINTENANCE, + CACHE, + RATE_LIMIT + } + + public enum OutcomeCategory { + SUCCESS, + REPLAY, + STALE, + VALIDATION_FAILURE, + CONTENTION, + DEFERRAL + } + + public enum MutationEffect { + MUTATING, + NON_MUTATING + } + + public enum ResetSensitivity { + NONE, + SESSION, + REGION, + TENANT, + CLUSTER + } + + /** Work classes from ADR 0058. */ + public enum LossClass { + ACCEPTED_PLAYER_COMMAND, + STAGED_EFFECT_OR_RETRY, + CORRECTNESS_BEARING_TIMER, + LOSSY_TIMER_OR_ADVISORY_HINT, + SESSION_LEASE_CACHE_OR_WAKE_UP, + PREMIUM_FINANCIAL_CROSS_TENANT_OR_UNIQUE_EXTERNAL_EFFECT, + EMPTY_REDIS_COLD_START_OR_RESET + } + + public enum CompatibilityLevel { + COMPATIBLE, + REQUIRES_REGION_RESET, + REQUIRES_TENANT_RESET, + REQUIRES_CLUSTER_RESET + } + + public record KeySpec(String name, String ownedPrefix, HashTagDeclaration hashTagDeclaration) { + public KeySpec { + requireMatch(name, DECLARATION_NAME_PATTERN, "KEYS name must be a supported identifier"); + requireMatch(ownedPrefix, PREFIX_PATTERN, "ownedPrefix must be a colon-delimited key prefix"); + Objects.requireNonNull(hashTagDeclaration, "hashTagDeclaration is required"); + } + } + + public record ArgumentSpec(String name) { + public ArgumentSpec { + requireMatch(name, DECLARATION_NAME_PATTERN, "ARGV name must be a supported identifier"); + } + } + + public record OutcomeSpec(String code, OutcomeCategory category, MutationEffect effect) { + public OutcomeSpec { + requireMatch(code, OUTCOME_CODE_PATTERN, "outcome code must be uppercase and stable"); + Objects.requireNonNull(category, "outcome category is required"); + Objects.requireNonNull(effect, "outcome mutation effect is required"); + if (category != OutcomeCategory.SUCCESS && effect != MutationEffect.NON_MUTATING) { + throw new IllegalArgumentException( + "replay, stale, validation, contention, and deferral outcomes must be non-mutating"); + } + } + } + + /** A caller version and payload version that may coexist for this script version. */ + public record SupportedCoexistence(String callerVersion, String payloadVersion) { + public SupportedCoexistence { + requireMatch(callerVersion, VERSION_PATTERN, "callerVersion must use vN syntax"); + if (!NO_PAYLOAD_VERSION.equals(payloadVersion) + && !LEGACY_PAYLOAD_VERSION.equals(payloadVersion)) { + requireMatch( + payloadVersion, VERSION_PATTERN, "payloadVersion must use vN, none, or legacy"); + } + } + } + + private static void requireMatch(String value, Pattern pattern, String message) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException(message); + } + } + + private static String requireDescription(String value, String fieldName) { + if (value == null || value.isBlank() || !value.equals(value.trim())) { + throw new IllegalArgumentException(fieldName + " is required and must be trimmed"); + } + return value; + } + + private static String optionalDescription(String value, String fieldName) { + if (value == null || value.isBlank()) { + return null; + } + if (!value.equals(value.trim())) { + throw new IllegalArgumentException(fieldName + " must be trimmed"); + } + return value; + } + + private static List immutable(List values, String message) { + if (values == null) { + throw new IllegalArgumentException(message); + } + return List.copyOf(values); + } + + private static List immutableNonEmpty(List values, String message) { + List copy = immutable(values, message); + if (copy.isEmpty()) { + throw new IllegalArgumentException(message); + } + return copy; + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodec.java new file mode 100644 index 0000000000..854d42e15c --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseWireCodec.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.common.account.admission; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseOperationReadback; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseReference; +import net.firedevops.firemud.account.v1.GameplayAdmissionLeaseState; + +/** + * Non-authorizing protobuf wrapper for the existing closed admission evidence codec. + * + *

No signature, peer, current source, registry, restriction, admission or physical commit is + * established here. Even a valid COMMITTED readback shape is not an authenticated owner receipt. + * Counter strings and the original canonical evidence remain unchanged. + */ +public final class AccountGameplayAdmissionLeaseWireCodec { + private AccountGameplayAdmissionLeaseWireCodec() {} + + public static GameplayAdmissionLeaseReference encodeReference( + AccountGameplayAdmissionLeaseEvidence evidence) { + if (evidence == null) throw invalid(); + var reference = + GameplayAdmissionLeaseReference.newBuilder() + .setRequestId((String) evidence.carrier().get("requestId")) + .setEvidenceCanonicalJson( + ByteString.copyFrom(evidence.canonicalJson(), StandardCharsets.UTF_8)) + .setEvidenceSha256(evidence.sha256()) + .build(); + parseReference(reference); + return reference; + } + + /** Parses exact UTF-8 bytes without repairing, reordering or reconstructing any carrier. */ + public static AccountGameplayAdmissionLeaseEvidence parseReference( + GameplayAdmissionLeaseReference reference) { + if (reference == null || !reference.getUnknownFields().asMap().isEmpty()) throw invalid(); + requireUuid(reference.getRequestId()); + ByteString bytes = reference.getEvidenceCanonicalJson(); + if (bytes.isEmpty() + || bytes.size() > AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + || !bytes.isValidUtf8() + || !reference.getEvidenceSha256().matches("[0-9a-f]{64}")) throw invalid(); + try { + var evidence = AccountGameplayAdmissionLeaseEvidence.parseCanonical(bytes.toStringUtf8()); + if (!reference.getRequestId().equals(evidence.carrier().get("requestId")) + || !reference.getEvidenceSha256().equals(evidence.sha256())) throw invalid(); + return evidence; + } catch (RuntimeException failure) { + // No evidence bytes, token metadata or parser internals are included in wire failures. + throw invalid(); + } + } + + /** Encodes terminal presence exactly; absent decision remains unknown, never fabricated. */ + public static GameplayAdmissionLeaseOperationReadback encodeOperation( + AccountGameplayAdmissionLeaseEvidence evidence, + GameplayAdmissionLeaseState state, + UUID bindingDecisionId, + UUID orphanCleanupId) { + if (state == null + || state == GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_UNSPECIFIED + || state == GameplayAdmissionLeaseState.UNRECOGNIZED) throw invalid(); + var result = + GameplayAdmissionLeaseOperationReadback.newBuilder() + .setLease(encodeReference(evidence)) + .setState(state) + .setPendingOrphanCleanup( + state == GameplayAdmissionLeaseState.GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED); + if (bindingDecisionId != null) result.setBindingDecisionId(bindingDecisionId.toString()); + if (orphanCleanupId != null) result.setOrphanCleanupId(orphanCleanupId.toString()); + var operation = result.build(); + validateOperation(operation); + return operation; + } + + /** Validates storage readback shape only and returns its exact original evidence. */ + public static AccountGameplayAdmissionLeaseEvidence validateOperation( + GameplayAdmissionLeaseOperationReadback operation) { + if (operation == null + || !operation.hasLease() + || !operation.getUnknownFields().asMap().isEmpty()) throw invalid(); + var evidence = parseReference(operation.getLease()); + if (operation.hasBindingDecisionId()) requireUuid(operation.getBindingDecisionId()); + if (operation.hasOrphanCleanupId()) requireUuid(operation.getOrphanCleanupId()); + switch (operation.getState()) { + case GAMEPLAY_ADMISSION_LEASE_STATE_PENDING -> { + if (operation.hasBindingDecisionId() + || operation.hasOrphanCleanupId() + || operation.getPendingOrphanCleanup()) throw invalid(); + } + case GAMEPLAY_ADMISSION_LEASE_STATE_COMMITTED -> { + if (!operation.hasBindingDecisionId() + || operation.hasOrphanCleanupId() + || operation.getPendingOrphanCleanup()) throw invalid(); + } + case GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED -> { + if (!operation.hasOrphanCleanupId() || !operation.getPendingOrphanCleanup()) + throw invalid(); + } + default -> throw invalid(); + } + return evidence; + } + + private static void requireUuid(String text) { + try { + UUID value = UUID.fromString(text); + if (!value.toString().equals(text) || value.version() != 4 || value.variant() != 2) + throw invalid(); + } catch (RuntimeException failure) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Malformed Account admission lease wire evidence"); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java new file mode 100644 index 0000000000..051e4009be --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java @@ -0,0 +1,101 @@ +package net.firedevops.firemud.common.security; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** Validates the canonical claim shape of the registry-backed control-ui JWT profile. */ +public final class ControlUiJwtProfileValidator { + public static final String PROFILE = "control-ui"; + public static final String AUDIENCE = "control-ui"; + public static final String TOKEN_TYPE = "control-ui"; + private static final String ISSUER = "firemud-account-service"; + public static final Set REQUIRED_CLAIMS; + public static final Set OPTIONAL_CLAIMS = Set.of("globalRoles"); + + static { + Set required = + new java.util.HashSet<>(AccountJwtProfileClaimSupport.REQUIRED_BASE_CLAIMS); + required.add("scopedRoles"); + REQUIRED_CLAIMS = Set.copyOf(required); + } + + private ControlUiJwtProfileValidator() {} + + /** + * Checks claim shape only; it does not validate a registry record or current Account authority. + * + * @param claims immutable verified claims + * @param maxControlUiTenantScopes explicit finite profile cap for every applicable tenant map + */ + public static void validateClaims(Map claims, int maxControlUiTenantScopes) { + if (maxControlUiTenantScopes <= 0 + || maxControlUiTenantScopes + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw AccountJwtProfileClaimSupport.invalid(); + } + AccountJwtProfileClaimSupport.requireClaimFields(claims, REQUIRED_CLAIMS, OPTIONAL_CLAIMS); + AccountJwtProfileClaimSupport.requireCommonIdentity(claims, ISSUER, AUDIENCE); + + Map tuple = + AccountJwtProfileClaimSupport.requireAuthorityTuple( + claims.get("authorityTuple"), true, false, false); + if (!(tuple.get("privateRealmGrantVersions") instanceof List grants) || !grants.isEmpty()) { + throw AccountJwtProfileClaimSupport.invalid(); + } + Map tenantGenerations = + AccountJwtProfileClaimSupport.requireGenerationMap(tuple.get("tenantAuthorityGeneration")); + Map membershipGenerations = + AccountJwtProfileClaimSupport.requireGenerationMap( + tuple.get("membershipAuthorityGeneration")); + Map membershipVersions = + AccountJwtProfileClaimSupport.requireVersionMap(claims.get("membershipVersion")); + String accountId = (String) claims.get("accountId"); + // The canonical profile forbids an accountId as a tenant-map key; this is shape rejection, + // not evidence about tenant ownership or an authorization predicate. + if (!membershipGenerations.keySet().equals(membershipVersions.keySet()) + || tenantGenerations.containsKey(accountId) + || membershipGenerations.containsKey(accountId) + || membershipVersions.containsKey(accountId)) { + throw AccountJwtProfileClaimSupport.invalid(); + } + + Map scopedRoles = + AccountJwtProfileClaimSupport.requireObjectMap(claims.get("scopedRoles")); + scopedRoles.forEach( + (tenantId, roles) -> { + AccountJwtProfileClaimSupport.requireUuid(tenantId); + AccountJwtProfileClaimSupport.requireRoleList(roles); + if (((List) roles).isEmpty() || tenantId.equals(claims.get("accountId"))) { + throw AccountJwtProfileClaimSupport.invalid(); + } + }); + if (!scopedRoles.keySet().containsAll(tenantGenerations.keySet())) { + throw AccountJwtProfileClaimSupport.invalid(); + } + + requireAtMost(scopedRoles.size(), maxControlUiTenantScopes); + requireAtMost(tenantGenerations.size(), maxControlUiTenantScopes); + requireAtMost(membershipGenerations.size(), maxControlUiTenantScopes); + requireAtMost(membershipVersions.size(), maxControlUiTenantScopes); + + Object billingCutoff = tuple.get("tenantBillingCutoff"); + if (billingCutoff != null) { + Map billingCutoffs = + AccountJwtProfileClaimSupport.requireObjectMap(billingCutoff); + requireAtMost(billingCutoffs.size(), maxControlUiTenantScopes); + if (!scopedRoles.keySet().containsAll(billingCutoffs.keySet())) { + throw AccountJwtProfileClaimSupport.invalid(); + } + } + if (claims.containsKey("globalRoles")) { + AccountJwtProfileClaimSupport.requireRoleList(claims.get("globalRoles")); + } + } + + private static void requireAtMost(int entries, int maximum) { + if (entries > maximum) { + throw AccountJwtProfileClaimSupport.invalid(); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java new file mode 100644 index 0000000000..17584d3171 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java @@ -0,0 +1,890 @@ +package net.firedevops.firemud.common.security; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Strict finite-bounded codec for initial and distinct public-production bound delegation + * candidates. + * + *

Pending records are non-authorizing. This codec checks JOSE/claim shape and exact Account + * snapshot equality, but does not verify the JWS signature or establish signer/currentness proof. + * The signing and Account evidence owners must do that before any active transition is usable. + */ +public final class GameSessionAccountDelegationRegistryRecord { + private static final int SCHEMA_VERSION = 2; + private static final int PENDING_REGISTRY_VERSION = 1; + private static final int ACTIVE_REGISTRY_VERSION = 2; + private static final String PENDING = "pending"; + private static final String ACTIVE = "active"; + private static final Pattern HASH = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern POSITIVE_LINEARIZATION = Pattern.compile("[1-9][0-9]{0,19}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Set TOKEN_CLAIMS = + Set.of( + "iss", + "sub", + "jti", + "accountId", + "aud", + "iat", + "nbf", + "exp", + "tokenGeneration", + "authorityTuple", + "membershipVersion", + "issuanceFence"); + private static final Set HEADER_REQUIRED = Set.of("alg", "kid"); + private static final Set HEADER_ALLOWED = Set.of("alg", "kid", "typ"); + private static final Set RECORD_FIELDS = + Set.of( + "schemaVersion", + "registryVersion", + "tokenHash", + "kid", + "signerGeneration", + "accountId", + "issuer", + "profile", + "type", + "audience", + "jti", + "iat", + "nbf", + "exp", + "tokenGeneration", + "operationId", + "requestId", + "requestDigest", + "state", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "authoritySourceVersions", + "authEvidenceBundle"); + private static final Set AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions", + "accountSecurityCutoff"); + private static final Set ACCOUNT_SECURITY_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Set SOURCE_VERSION_FIELDS = + Set.of("issuerSourceVersion", "accountSourceVersion", "issuanceFenceSourceVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final Map fields; + + private GameSessionAccountDelegationRegistryRecord(Map fields) { + this.fields = immutableMap(fields); + } + + /** Creates the distinct first public-production tenant-bound pending record. */ + public static GameSessionAccountDelegationRegistryRecord fromAccountSignedBoundCompactJwt( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot account, + EvidenceBundleReference evidence, + String tenantId, + Map exactTuple, + Map exactMembershipVersion, + long now, + long maxBytes) { + GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority( + tenantId, exactTuple, exactMembershipVersion); + return fromCandidate( + compactJwt, + signerGeneration, + binding, + account, + evidence, + now, + maxBytes, + new BoundShape(tenantId, exactTuple, exactMembershipVersion)); + } + + private record BoundShape( + String tenantId, Map tuple, Map membershipVersion) {} + + /** Validates the exact signed-token candidate and creates only its pending registry record. */ + public static GameSessionAccountDelegationRegistryRecord fromAccountSignedCompactJwt( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot snapshot, + EvidenceBundleReference evidenceBundleReference, + long nowEpochSecond, + long maxRecordBytes) { + return fromCandidate( + compactJwt, + signerGeneration, + binding, + snapshot, + evidenceBundleReference, + nowEpochSecond, + maxRecordBytes, + null); + } + + private static GameSessionAccountDelegationRegistryRecord fromCandidate( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot snapshot, + EvidenceBundleReference evidenceBundleReference, + long nowEpochSecond, + long maxRecordBytes, + BoundShape bound) { + Objects.requireNonNull(compactJwt, "Compact Account JWT is required"); + Objects.requireNonNull(binding, "Durable issuance binding is required"); + Objects.requireNonNull(snapshot, "Locked Account authority snapshot is required"); + Objects.requireNonNull( + evidenceBundleReference, "Persisted Account evidence bundle is required"); + requirePositiveDecimal(signerGeneration, "signerGeneration"); + requirePositive(nowEpochSecond, "nowEpochSecond"); + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + + CompactToken compact = parseCompactJwt(compactJwt); + Map claims = compact.claims(); + requireExactFields(claims, fieldsFor(TOKEN_CLAIMS, bound != null), "JWT claims"); + String issuer = requireText(claims.get("iss"), "iss", 256); + String subject = requireCanonicalUuid(claims.get("sub"), "sub"); + String accountId = requireCanonicalUuid(claims.get("accountId"), "accountId"); + String jti = requireCanonicalUuid(claims.get("jti"), "jti"); + String audience = requireText(claims.get("aud"), "aud", 128); + long issuedAt = requirePositiveInteger(claims.get("iat"), "iat"); + long notBefore = requirePositiveInteger(claims.get("nbf"), "nbf"); + long expiresAt = requirePositiveInteger(claims.get("exp"), "exp"); + String tokenGeneration = + requirePositiveDecimal(claims.get("tokenGeneration"), "tokenGeneration"); + String issuanceFence = requirePositiveDecimal(claims.get("issuanceFence"), "issuanceFence"); + + requireEqual(GameSessionAccountDelegationProfile.ISSUER, issuer, "Account issuer mismatch"); + requireEqual(GameSessionAccountDelegationProfile.AUDIENCE, audience, "audience mismatch"); + requireEqual(snapshot.accountId().toString(), accountId, "Account UUID mismatch"); + requireEqual(subject, accountId, "sub and accountId mismatch"); + requireEqual(binding.accountId(), accountId, "durable operation account mismatch"); + requireEqual("1", tokenGeneration, "initial delegation tokenGeneration must be one"); + requireEqual( + Long.toString(snapshot.issuanceFence()), issuanceFence, "Account issuance fence mismatch"); + validateTimeWindow(issuedAt, notBefore, expiresAt, nowEpochSecond); + if (bound == null) { + validateAuthorityTuple( + claims.get("authorityTuple"), claims.get("membershipVersion"), snapshot); + } else { + GameSessionAccountDelegationJwtProfileValidator.validatePublicTenantBoundClaims(claims); + requireEqual(bound.tenantId(), claims.get("tenantId"), "bound tenant mismatch"); + requireEqual(bound.tuple(), claims.get("authorityTuple"), "bound tuple mismatch"); + requireEqual( + bound.membershipVersion(), + claims.get("membershipVersion"), + "independent membership version mismatch"); + requireEqual( + Long.toString(snapshot.issuerGeneration()), + bound.tuple().get("issuerAuthGeneration"), + "issuer mismatch"); + requireEqual( + Long.toString(snapshot.accountGeneration()), + bound.tuple().get("accountAuthorityGeneration"), + "account mismatch"); + if (!Objects.equals( + snapshot.accountSecurityCutoff().map(value -> value.toMap()).orElse(null), + bound.tuple().get("accountSecurityCutoff"))) throw invalid("Account cutoff mismatch"); + } + + Map record = new LinkedHashMap<>(); + record.put("schemaVersion", SCHEMA_VERSION); + record.put("registryVersion", PENDING_REGISTRY_VERSION); + record.put("tokenHash", sha256(compactJwt.getBytes(StandardCharsets.US_ASCII))); + record.put("kid", compact.keyId()); + record.put("signerGeneration", signerGeneration); + record.put("accountId", accountId); + if (bound != null) record.put("tenantId", bound.tenantId()); + record.put("issuer", issuer); + record.put("profile", GameSessionAccountDelegationProfile.PROFILE); + record.put("type", GameSessionAccountDelegationProfile.TYPE); + record.put("audience", audience); + record.put("jti", jti); + record.put("iat", issuedAt); + record.put("nbf", notBefore); + record.put("exp", expiresAt); + record.put("tokenGeneration", tokenGeneration); + record.put("operationId", binding.operationId()); + record.put("requestId", binding.requestId()); + record.put("requestDigest", binding.requestDigest()); + record.put("state", PENDING); + record.put("authorityTuple", claims.get("authorityTuple")); + record.put("membershipVersion", claims.get("membershipVersion")); + record.put("issuanceFence", issuanceFence); + record.put("authoritySourceVersions", snapshot.sourceVersions()); + record.put("authEvidenceBundle", evidenceBundleReference.toMap()); + + GameSessionAccountDelegationRegistryRecord result = + new GameSessionAccountDelegationRegistryRecord(record); + result.toCanonicalJsonBytes(maxRecordBytes); + return result; + } + + /** Decodes a supported canonical registry value without granting it authority. */ + public static GameSessionAccountDelegationRegistryRecord decode( + byte[] canonicalUtf8, long maxRecordBytes) { + Objects.requireNonNull(canonicalUtf8, "Registry bytes are required"); + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + if (canonicalUtf8.length == 0 || canonicalUtf8.length > maxRecordBytes) { + throw invalid("Registry record exceeds its byte bound"); + } + String json = strictUtf8(canonicalUtf8); + byte[] canonical = canonicalize(json); + if (!Arrays.equals(canonicalUtf8, canonical)) { + throw invalid("Registry value is not canonical RFC 8785 UTF-8"); + } + Map decoded = parseObject(json, "registry record"); + requireExactFields( + decoded, fieldsFor(RECORD_FIELDS, decoded.containsKey("tenantId")), "registry record"); + validateRecord(decoded); + return new GameSessionAccountDelegationRegistryRecord(decoded); + } + + /** Returns canonical RFC 8785 record bytes, subject to both the caller and profile ceilings. */ + public byte[] toCanonicalJsonBytes(long maxRecordBytes) { + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + byte[] canonical = canonicalize(serialize(fields)); + if (canonical.length == 0 || canonical.length > maxRecordBytes) { + throw invalid("Registry record exceeds its byte bound"); + } + return canonical; + } + + public String tokenHash() { + return textField("tokenHash"); + } + + public String kid() { + return textField("kid"); + } + + public String signerGeneration() { + return textField("signerGeneration"); + } + + public String accountId() { + return textField("accountId"); + } + + public String jti() { + return textField("jti"); + } + + public String operationId() { + return textField("operationId"); + } + + public String requestId() { + return textField("requestId"); + } + + public String requestDigest() { + return textField("requestDigest"); + } + + public String state() { + return textField("state"); + } + + public long issuedAtEpochSecond() { + return requirePositiveInteger(fields.get("iat"), "iat"); + } + + public long notBeforeEpochSecond() { + return requirePositiveInteger(fields.get("nbf"), "nbf"); + } + + public long issuanceFence() { + return requirePositiveDecimalLong(fields.get("issuanceFence"), "issuanceFence"); + } + + public long registryVersion() { + return requirePositiveInteger(fields.get("registryVersion"), "registryVersion"); + } + + public EvidenceBundleReference evidenceBundleReference() { + Map value = + requireObject(fields.get("authEvidenceBundle"), "authEvidenceBundle"); + return new EvidenceBundleReference( + requirePositiveDecimal(value.get("bundleVersion"), "bundleVersion"), + requirePositiveDecimal(value.get("sourceVersion"), "sourceVersion"), + requirePositiveDecimal(value.get("sourceFence"), "sourceFence"), + requirePositiveLinearization(value.get("linearization")), + requireMatchValue(HASH, value.get("canonicalSha256"), "canonicalSha256")); + } + + public long expiresAtEpochSecond() { + return requirePositiveInteger(fields.get("exp"), "exp"); + } + + public Map fields() { + return immutableMap(fields); + } + + private String textField(String field) { + return requireText(fields.get(field), field, 256); + } + + private static Set fieldsFor(Set initial, boolean bound) { + if (!bound) return initial; + var fields = new java.util.HashSet<>(initial); + fields.add("tenantId"); + return Set.copyOf(fields); + } + + private static void validateRecord(Map record) { + requireExactInteger(record.get("schemaVersion"), SCHEMA_VERSION, "schemaVersion"); + long registryVersion = requirePositiveInteger(record.get("registryVersion"), "registryVersion"); + String state = requireText(record.get("state"), "state", 16); + if (PENDING.equals(state)) { + if (registryVersion != PENDING_REGISTRY_VERSION) { + throw invalid("pending registry version mismatch"); + } + } else if (ACTIVE.equals(state)) { + if (registryVersion != ACTIVE_REGISTRY_VERSION) { + throw invalid("active registry version mismatch"); + } + } else { + throw invalid("Unsupported registry lifecycle state"); + } + requireMatch(HASH, record.get("tokenHash"), "tokenHash"); + requireMatch(HASH, record.get("requestDigest"), "requestDigest"); + requireCanonicalUuid(record.get("jti"), "jti"); + requireCanonicalUuid(record.get("operationId"), "operationId"); + requireCanonicalUuid(record.get("requestId"), "requestId"); + requireMatch(KID, record.get("kid"), "kid"); + requirePositiveDecimal(record.get("signerGeneration"), "signerGeneration"); + requireEqual(GameSessionAccountDelegationProfile.ISSUER, record.get("issuer"), "issuer"); + requireEqual(GameSessionAccountDelegationProfile.PROFILE, record.get("profile"), "profile"); + requireEqual(GameSessionAccountDelegationProfile.TYPE, record.get("type"), "type"); + requireEqual(GameSessionAccountDelegationProfile.AUDIENCE, record.get("audience"), "audience"); + String accountId = requireCanonicalUuid(record.get("accountId"), "accountId"); + long issuedAt = requirePositiveInteger(record.get("iat"), "iat"); + long notBefore = requirePositiveInteger(record.get("nbf"), "nbf"); + long expiresAt = requirePositiveInteger(record.get("exp"), "exp"); + requireEqual( + "1", + requirePositiveDecimal(record.get("tokenGeneration"), "tokenGeneration"), + "initial token generation mismatch"); + validateTimeWindow(issuedAt, notBefore, expiresAt, 0L); + Map tuple = requireObject(record.get("authorityTuple"), "authorityTuple"); + String accountGeneration = + requirePositiveDecimal( + tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + boolean hasCutoff = tuple.containsKey("accountSecurityCutoff"); + if (hasCutoff != !"1".equals(accountGeneration)) { + throw invalid("Account security cutoff presence does not match the source generation"); + } + Set tupleFields = + new java.util.HashSet<>( + hasCutoff ? AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF : AUTHORITY_TUPLE_FIELDS); + if (record.containsKey("tenantId") && tuple.containsKey("tenantBillingCutoff")) + tupleFields.add("tenantBillingCutoff"); + requireExactFields(tuple, tupleFields, "authorityTuple"); + requirePositiveDecimal(tuple.get("issuerAuthGeneration"), "issuerAuthGeneration"); + if (record.containsKey("tenantId")) { + GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority( + requireCanonicalUuid(record.get("tenantId"), "tenantId"), + tuple, + requireObject(record.get("membershipVersion"), "membershipVersion")); + } else { + requireEmptyObject(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + requireEmptyObject( + tuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + } + requireEmptyList(tuple.get("privateRealmGrantVersions"), "privateRealmGrantVersions"); + if (hasCutoff) { + Map cutoff = + requireObject(tuple.get("accountSecurityCutoff"), "accountSecurityCutoff"); + requireExactFields(cutoff, ACCOUNT_SECURITY_CUTOFF_FIELDS, "accountSecurityCutoff"); + String cutoffGeneration = + requirePositiveDecimal(cutoff.get("accountAuthorityGeneration"), "cutoff generation"); + String cutoffSequence = + requirePositiveDecimal(cutoff.get("outboxSequence"), "cutoff outbox sequence"); + String cutoffStream = requireText(cutoff.get("outboxStreamKey"), "cutoff stream", 2048); + long accountGenerationValue = + requirePositiveDecimalLong(accountGeneration, "account generation"); + if (!accountGeneration.equals(cutoffGeneration) + || !Long.toString(accountGenerationValue - 1L).equals(cutoffSequence) + || !("account:auth-authority:v1:account/" + accountId).equals(cutoffStream)) { + throw invalid("Account security cutoff scope or sequence is invalid"); + } + } + if (!record.containsKey("tenantId")) + requireEmptyObject(record.get("membershipVersion"), "membershipVersion"); + requirePositiveDecimal(record.get("issuanceFence"), "issuanceFence"); + Map versions = + requireObject(record.get("authoritySourceVersions"), "authoritySourceVersions"); + requireExactFields(versions, SOURCE_VERSION_FIELDS, "authoritySourceVersions"); + for (String field : SOURCE_VERSION_FIELDS) { + requirePositiveDecimal(versions.get(field), field); + } + Map bundle = + requireObject(record.get("authEvidenceBundle"), "authEvidenceBundle"); + requireExactFields( + bundle, + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization", "canonicalSha256"), + "authEvidenceBundle"); + requirePositiveDecimal(bundle.get("bundleVersion"), "bundleVersion"); + requirePositiveDecimal(bundle.get("sourceVersion"), "sourceVersion"); + requirePositiveDecimal(bundle.get("sourceFence"), "sourceFence"); + requirePositiveLinearization(bundle.get("linearization")); + requireMatch(HASH, bundle.get("canonicalSha256"), "canonicalSha256"); + } + + private static void validateAuthorityTuple( + Object tupleValue, Object membershipVersionValue, AccountAuthoritySnapshot snapshot) { + Map tuple = requireObject(tupleValue, "authorityTuple"); + Set expectedFields = + snapshot.accountSecurityCutoff().isPresent() + ? AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF + : AUTHORITY_TUPLE_FIELDS; + requireExactFields(tuple, expectedFields, "authorityTuple"); + if (canonicalize(serialize(tuple)).length + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw invalid("authorityTuple exceeds its finite profile byte bound"); + } + requireEqual( + Long.toString(snapshot.issuerGeneration()), + requirePositiveDecimal(tuple.get("issuerAuthGeneration"), "issuerAuthGeneration"), + "issuer authority generation mismatch"); + requireEqual( + Long.toString(snapshot.accountGeneration()), + requirePositiveDecimal( + tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"), + "Account authority generation mismatch"); + requireEmptyObject(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + requireEmptyObject(tuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + requireEmptyList(tuple.get("privateRealmGrantVersions"), "privateRealmGrantVersions"); + if (snapshot.accountSecurityCutoff().isPresent()) { + Map cutoff = + requireObject(tuple.get("accountSecurityCutoff"), "accountSecurityCutoff"); + requireExactFields(cutoff, ACCOUNT_SECURITY_CUTOFF_FIELDS, "accountSecurityCutoff"); + requirePositiveDecimal(cutoff.get("accountAuthorityGeneration"), "cutoff generation"); + requirePositiveDecimal(cutoff.get("outboxSequence"), "cutoff outbox sequence"); + requireText(cutoff.get("outboxStreamKey"), "cutoff outboxStreamKey", 2048); + if (!snapshot.accountSecurityCutoff().orElseThrow().toMap().equals(cutoff)) { + throw invalid("Account security cutoff does not match the source snapshot"); + } + } + requireEmptyObject(membershipVersionValue, "membershipVersion"); + } + + private static CompactToken parseCompactJwt(String compactJwt) { + byte[] compactBytes = compactJwt.getBytes(StandardCharsets.US_ASCII); + if (compactJwt.length() == 0 + || compactJwt.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + || compactBytes.length != compactJwt.length()) { + throw invalid("Compact JWT is absent or exceeds its profile byte bound"); + } + String[] parts = compactJwt.split("\\.", -1); + if (parts.length != 3 || Arrays.stream(parts).anyMatch(String::isEmpty)) { + throw invalid("Compact JWT is malformed"); + } + byte[] headerBytes = decodeBase64Url(parts[0]); + byte[] claimsBytes = decodeBase64Url(parts[1]); + decodeBase64Url(parts[2]); + Map header = parseObject(strictUtf8(headerBytes), "JOSE header"); + Set headerFields = header.keySet(); + if (!HEADER_ALLOWED.containsAll(headerFields) || !headerFields.containsAll(HEADER_REQUIRED)) { + throw invalid("JOSE header fields are not the exact supported set"); + } + requireEqual("RS256", header.get("alg"), "Account delegation must use RS256"); + String kid = requireText(header.get("kid"), "kid", 64); + requireMatch(KID, kid, "kid"); + if (header.containsKey("typ")) requireEqual("JWT", header.get("typ"), "typ"); + Map claims = parseObject(strictUtf8(claimsBytes), "JWT claims"); + return new CompactToken(kid, claims); + } + + private static void validateTimeWindow(long issuedAt, long notBefore, long expiresAt, long now) { + long lifetime; + try { + lifetime = Math.subtractExact(expiresAt, issuedAt); + } catch (ArithmeticException ex) { + throw invalid("JWT time bounds are invalid or expired"); + } + long latestAllowedIssuedAt = now; + if (now > 0L) { + try { + latestAllowedIssuedAt = Math.addExact(now, 5L); + } catch (ArithmeticException ex) { + latestAllowedIssuedAt = Long.MAX_VALUE; + } + } + if (notBefore > issuedAt + || lifetime <= 0L + || lifetime > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS + || (now > 0L && (issuedAt > latestAllowedIssuedAt || expiresAt <= now))) { + throw invalid("JWT time bounds are invalid or expired"); + } + } + + private static byte[] decodeBase64Url(String value) { + try { + if (value.indexOf('=') >= 0 || !value.matches("[A-Za-z0-9_-]+")) + throw invalid("JWT segment is not base64url"); + byte[] decoded = Base64.getUrlDecoder().decode(value); + if (!Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(value)) { + throw invalid("JWT segment has a non-canonical base64url encoding"); + } + return decoded; + } catch (IllegalArgumentException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid("JWT segment is malformed"); + } + } + + private static Map parseObject(String json, String field) { + try { + Map parsed = JSON.readValue(json, new TypeReference<>() {}); + if (parsed == null || parsed.isEmpty()) throw invalid(field + " must be a non-empty object"); + return parsed; + } catch (RuntimeException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid(field + " is malformed"); + } + } + + private static Map requireObject(Object value, String field) { + if (!(value instanceof Map map)) throw invalid(field + " must be an object"); + Map result = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String name) || item == null || result.put(name, item) != null) { + throw invalid(field + " contains an invalid member"); + } + }); + return result; + } + + private static Map immutableMap(Map input) { + Map copy = new LinkedHashMap<>(); + input.forEach( + (key, value) -> { + if (key == null || value == null) throw invalid("Null registry field is forbidden"); + copy.put(key, deepImmutable(value)); + }); + return Map.copyOf(copy); + } + + private static Object deepImmutable(Object value) { + if (value instanceof Map map) { + Map nested = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String name) || item == null) { + throw invalid("Null or invalid nested registry field is forbidden"); + } + nested.put(name, deepImmutable(item)); + }); + return Map.copyOf(nested); + } + if (value instanceof List list) { + return list.stream().map(GameSessionAccountDelegationRegistryRecord::deepImmutable).toList(); + } + return value; + } + + private static void requireExactFields( + Map value, Set expected, String field) { + if (!value.keySet().equals(expected)) throw invalid(field + " has missing or unknown fields"); + if (value.values().stream().anyMatch(Objects::isNull)) throw invalid(field + " contains null"); + } + + private static void requireEmptyObject(Object value, String field) { + if (!(value instanceof Map map) || !map.isEmpty()) + throw invalid(field + " must be an empty object"); + } + + private static void requireEmptyList(Object value, String field) { + if (!(value instanceof List list) || !list.isEmpty()) + throw invalid(field + " must be an empty list"); + } + + private static long requirePositiveInteger(Object value, String field) { + if (!(value instanceof Number number)) throw invalid(field + " must be a JSON integer"); + String encoded = number.toString(); + if (!POSITIVE_DECIMAL.matcher(encoded).matches()) { + throw invalid(field + " must be a bounded positive integer"); + } + try { + return Long.parseLong(encoded); + } catch (NumberFormatException ex) { + throw invalid(field + " must be a bounded positive integer"); + } + } + + private static long requirePositiveDecimalLong(Object value, String field) { + String decimal = requirePositiveDecimal(value, field); + try { + return Long.parseLong(decimal); + } catch (NumberFormatException ex) { + throw invalid(field + " exceeds the supported range"); + } + } + + private static long requirePositive(long value, String field) { + if (value <= 0L) throw invalid(field + " must be positive"); + return value; + } + + private static String requirePositiveDecimal(Object value, String field) { + if (!(value instanceof String string) || !POSITIVE_DECIMAL.matcher(string).matches()) { + throw invalid(field + " must be a canonical positive decimal string"); + } + try { + Long.parseLong(string); + return string; + } catch (NumberFormatException ex) { + throw invalid(field + " exceeds the supported range"); + } + } + + private static String requireCanonicalUuid(Object value, String field) { + String text = requireText(value, field, 36); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) + throw invalid(field + " is not a canonical UUID"); + return text; + } catch (IllegalArgumentException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid(field + " is not a canonical UUID"); + } + } + + private static String requireText(Object value, String field, int maxLength) { + if (!(value instanceof String text) || text.isEmpty() || text.length() > maxLength) { + throw invalid(field + " must be a bounded non-empty string"); + } + for (int i = 0; i < text.length(); i++) { + if (Character.isISOControl(text.charAt(i))) + throw invalid(field + " contains a control character"); + } + return text; + } + + private static void requireMatch(Pattern pattern, Object value, String field) { + if (!(value instanceof String text) || !pattern.matcher(text).matches()) + throw invalid(field + " has an invalid format"); + } + + private static String requireMatchValue(Pattern pattern, Object value, String field) { + requireMatch(pattern, value, field); + return (String) value; + } + + private static String requirePositiveLinearization(Object value) { + if (!(value instanceof String text) || !POSITIVE_LINEARIZATION.matcher(text).matches()) { + throw invalid("bundle linearization is malformed"); + } + return text; + } + + private static void requireExactInteger(Object value, long expected, String field) { + if (!(value instanceof Number number)) throw invalid(field + " must be an integer"); + String encoded = number.toString(); + if (!encoded.matches("0|[1-9][0-9]{0,18}")) { + throw invalid(field + " is unsupported"); + } + try { + if (Long.parseLong(encoded) != expected) throw invalid(field + " is unsupported"); + } catch (NumberFormatException ex) { + throw invalid(field + " is unsupported"); + } + } + + private static void requireEqual(Object expected, Object actual, String message) { + if (!Objects.equals(expected, actual)) throw invalid(message); + } + + private static void requireBound(long value, long maximum, String field) { + if (value <= 0L || value > maximum) + throw invalid(field + " is outside the finite profile bound"); + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw invalid("JWT/registry JSON is not valid UTF-8"); + } + } + + private static String serialize(Object value) { + try { + return JSON.writeValueAsString(value); + } catch (RuntimeException ex) { + throw invalid("Registry JSON could not be serialized"); + } + } + + private static byte[] canonicalize(String value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(value); + } catch (IOException | RuntimeException ex) { + throw invalid("RFC 8785 canonicalization failed"); + } + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static InvalidRecordException invalid(String message) { + return new InvalidRecordException(message); + } + + private record CompactToken(String keyId, Map claims) {} + + public record AccountAuthoritySnapshot( + UUID accountId, + long issuerGeneration, + long issuerSourceVersion, + long accountGeneration, + long accountSourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + Optional accountSecurityCutoff) { + public AccountAuthoritySnapshot { + Objects.requireNonNull(accountId, "Canonical Account UUID is required"); + Objects.requireNonNull(accountSecurityCutoff, "Account cutoff applicability is required"); + if (accountId.equals(new UUID(0L, 0L)) + || issuerGeneration <= 0L + || issuerSourceVersion <= 0L + || accountGeneration <= 0L + || accountSourceVersion <= 0L + || issuanceFence <= 0L + || issuanceFenceSourceVersion <= 0L + || issuerGeneration != issuerSourceVersion + || accountGeneration != accountSourceVersion + || accountGeneration != issuanceFence + || accountGeneration != issuanceFenceSourceVersion) { + throw invalid("Durable Account authority snapshot is malformed"); + } + String expectedStream = "account:auth-authority:v1:account/" + accountId; + if (accountGeneration == 1L) { + if (accountSecurityCutoff.isPresent()) { + throw invalid("Fresh sequence-zero Account authority cannot carry a cutoff"); + } + } else { + GameSessionAccountDelegationProfile.AccountSecurityCutoff cutoff = + accountSecurityCutoff.orElseThrow( + () -> invalid("Advanced Account authority requires its source cutoff")); + if (!Long.toString(accountGeneration).equals(cutoff.accountAuthorityGeneration()) + || !expectedStream.equals(cutoff.outboxStreamKey()) + || !Long.toString(accountGeneration - 1L).equals(cutoff.outboxSequence())) { + throw invalid("Account security cutoff scope or sequence is stale"); + } + } + } + + public Map sourceVersions() { + return Map.of( + "issuerSourceVersion", Long.toString(issuerSourceVersion), + "accountSourceVersion", Long.toString(accountSourceVersion), + "issuanceFenceSourceVersion", Long.toString(issuanceFenceSourceVersion)); + } + } + + public record IssuanceBinding( + String operationId, String requestId, String requestDigest, String accountId) { + public IssuanceBinding { + requireCanonicalUuid(operationId, "operationId"); + requireCanonicalUuid(requestId, "requestId"); + requireMatch(HASH, requestDigest, "requestDigest"); + requireCanonicalUuid(accountId, "accountId"); + } + } + + /** Exact immutable V46 bundle reference and digest bound into the registry projection. */ + public record EvidenceBundleReference( + String bundleVersion, + String sourceVersion, + String sourceFence, + String linearization, + String canonicalSha256) { + public EvidenceBundleReference { + requirePositiveDecimal(bundleVersion, "bundleVersion"); + requirePositiveDecimal(sourceVersion, "sourceVersion"); + requirePositiveDecimal(sourceFence, "sourceFence"); + requirePositiveLinearization(linearization); + requireMatch(HASH, canonicalSha256, "canonicalSha256"); + } + + public Map toMap() { + return Map.of( + "bundleVersion", bundleVersion, + "sourceVersion", sourceVersion, + "sourceFence", sourceFence, + "linearization", linearization, + "canonicalSha256", canonicalSha256); + } + } + + public static final class InvalidRecordException extends IllegalArgumentException { + public InvalidRecordException(String message) { + super(message); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java index adec1fad6a..6d00f6d741 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtClaims.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.security; import io.jsonwebtoken.Claims; +import java.util.UUID; import org.springframework.util.StringUtils; /** Shared helpers for canonical JWT claim extraction and normalization. */ @@ -42,6 +43,32 @@ public static long requireSignedActorAccountId(Claims claims, String mismatchMes return claimedAccountId; } + public static String requireCanonicalAccountUuid(Object value, String claimName) { + if (!(value instanceof String text) + || !StringUtils.hasText(text) + || !text.equals(text.trim())) { + throw new IllegalArgumentException("Malformed claim: " + claimName); + } + try { + UUID accountUuid = UUID.fromString(text); + if (!accountUuid.toString().equals(text) || accountUuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Invalid claim: " + claimName); + } + return text; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Malformed claim: " + claimName, ex); + } + } + + public static String requireSignedGameplayAccountUuid(Claims claims, String mismatchMessage) { + String subjectAccountUuid = requireCanonicalAccountUuid(claims.getSubject(), "sub"); + String claimedAccountUuid = requireCanonicalAccountUuid(claims.get("accountId"), "accountId"); + if (!subjectAccountUuid.equals(claimedAccountUuid)) { + throw new IllegalArgumentException(mismatchMessage); + } + return claimedAccountUuid; + } + public static SignedGameplayRoutingClaims requireSignedGameplayRoutingClaims( Claims claims, String accountMismatchMessage) { return new SignedGameplayRoutingClaims( diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java new file mode 100644 index 0000000000..86d11650b4 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.common.security; + +import java.util.Map; +import java.util.Set; + +/** Validates the canonical, tenant-free player-bootstrap JWT claim shape. */ +public final class PlayerBootstrapJwtProfileValidator { + public static final String PROFILE = "player-bootstrap"; + public static final String AUDIENCE = "player-bootstrap"; + public static final String TOKEN_TYPE = "player-bootstrap"; + private static final String ISSUER = "firemud-account-service"; + public static final Set REQUIRED_CLAIMS; + public static final Set OPTIONAL_CLAIMS = Set.of("globalRoles"); + + static { + Set required = + new java.util.HashSet<>(AccountJwtProfileClaimSupport.REQUIRED_BASE_CLAIMS); + required.add("scopedRoles"); + REQUIRED_CLAIMS = Set.copyOf(required); + } + + private PlayerBootstrapJwtProfileValidator() {} + + /** Checks profile shape only; it does not validate current membership or authorize a route. */ + public static void validateClaims(Map claims) { + AccountJwtProfileClaimSupport.requireClaimFields(claims, REQUIRED_CLAIMS, OPTIONAL_CLAIMS); + AccountJwtProfileClaimSupport.requireCommonIdentity(claims, ISSUER, AUDIENCE); + AccountJwtProfileClaimSupport.requireAuthorityTuple( + claims.get("authorityTuple"), false, true, false); + if (!AccountJwtProfileClaimSupport.requireVersionMap(claims.get("membershipVersion")).isEmpty() + || !AccountJwtProfileClaimSupport.requireObjectMap(claims.get("scopedRoles")).isEmpty()) { + throw AccountJwtProfileClaimSupport.invalid(); + } + if (claims.containsKey("globalRoles")) { + AccountJwtProfileClaimSupport.requireRoleList(claims.get("globalRoles")); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java index 5383df3e6f..4a930bd905 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/SessionContext.java @@ -119,6 +119,19 @@ public static Long currentAccountIdOrNull() { return JwtClaims.requireLong(data.accountId, "accountId", false); } + /** + * Returns the current canonical Account UUID when present. + * + *

Blank or missing claims return {@code null}. Malformed, nil, or non-UUID claims fail closed. + */ + public static String currentAccountUuidOrNull() { + ClaimsData data = currentData(); + if (data == null || data.accountId == null || data.accountId.isBlank()) { + return null; + } + return JwtClaims.requireCanonicalAccountUuid(data.accountId, "accountId"); + } + /** Throws 403 when the current caller cannot act on the provided tenant. */ public static void requireTenantAccess(Long tenantId) { if (tenantId == null) { diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java b/services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java new file mode 100644 index 0000000000..ba635250e4 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidence.java @@ -0,0 +1,312 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.JsonParser; +import tools.jackson.core.JsonToken; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Distinct World-owned player-admission lifecycle hold. This is neither a first-pointer hold nor + * Account authorization, Game Session's binding decision, or gameplay admission permission. + * + *

The complete original lease and exact World owner evidence remain immutable. Its deadline is + * diagnostic only. Release requires independently authenticated exact Account terminal evidence AND + * Game Session installation/cleanup evidence; those producers do not exist in this slice. + */ +public record WorldCanonicalPlayerAdmissionHoldEvidence( + UUID holdId, + UUID holdFence, + Request request, + WorldCanonicalInstanceLifecycleEvidence worldEvidence) { + public static final String SCHEMA = "world-canonical-player-admission-hold-evidence/v1"; + public static final int MAX_EVIDENCE_BYTES = 1024 * 1024; + public static final int MAX_LIFECYCLE_BYTES = 512 * 1024; + private static final Set FIELDS = + Set.of( + "schema", + "schemaVersion", + "holdId", + "holdFence", + "request", + "worldLifecycleEvidenceBase64"); + private static final Set REQUEST_FIELDS = + Set.of( + "accountLeaseJson", "accountLeaseSha256", "expectedLifecycleEpoch", "expectedRowVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + public WorldCanonicalPlayerAdmissionHoldEvidence { + requireOpaque(holdId); + requireOpaque(holdFence); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(worldEvidence, "worldEvidence"); + request.requireExactActiveWorld(worldEvidence); + } + + /** Closed outer carrier; nested original Account and World bytes are preserved exactly. */ + public byte[] canonicalBytes() { + byte[] lifecycle = worldEvidence.canonicalBytes(); + requireBound(lifecycle, MAX_LIFECYCLE_BYTES); + Map value = + Map.of( + "schema", + SCHEMA, + "schemaVersion", + "1", + "holdId", + holdId.toString(), + "holdFence", + holdFence.toString(), + "request", + Map.of( + "accountLeaseJson", + request.lease().canonicalJson(), + "accountLeaseSha256", + request.lease().sha256(), + "expectedLifecycleEpoch", + Long.toString(request.expectedLifecycleEpoch()), + "expectedRowVersion", + Long.toString(request.expectedRowVersion())), + "worldLifecycleEvidenceBase64", + Base64.getEncoder().encodeToString(lifecycle)); + try { + byte[] result = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + requireBound(result, MAX_EVIDENCE_BYTES); + return result; + } catch (IOException failure) { + throw new IllegalStateException("Cannot encode canonical World player hold", failure); + } + } + + /** Separate digest of the complete canonical outer bytes; never a self-referential field. */ + public String sha256() { + return digest(canonicalBytes()); + } + + /** Shape and exact binding only: decoding does not authenticate World or authorize admission. */ + public static WorldCanonicalPlayerAdmissionHoldEvidence fromCanonical( + byte[] bytes, String sha256) { + requireBound(bytes, MAX_EVIDENCE_BYTES); + if (sha256 == null || !sha256.matches("[0-9a-f]{64}") || !digest(bytes).equals(sha256)) { + throw new IllegalArgumentException("World hold evidence SHA256 differs from original bytes"); + } + return parseCanonical(bytes); + } + + public static WorldCanonicalPlayerAdmissionHoldEvidence parseCanonical(byte[] bytes) { + requireBound(bytes, MAX_EVIDENCE_BYTES); + String json = strictUtf8(bytes); + try { + try (JsonParser parser = JSON.createParser(json)) { + int depth = 0; + JsonToken token; + while ((token = parser.nextToken()) != null) { + if ((token == JsonToken.START_OBJECT || token == JsonToken.START_ARRAY) && ++depth > 4) + throw new IllegalArgumentException("World hold evidence exceeds closed nesting bound"); + if (token == JsonToken.END_OBJECT || token == JsonToken.END_ARRAY) depth--; + } + } + JsonNode root = JSON.readTree(json); + exact(root, FIELDS); + if (!SCHEMA.equals(text(root, "schema")) || !"1".equals(text(root, "schemaVersion"))) { + throw new IllegalArgumentException("Unsupported World player hold evidence schema"); + } + JsonNode bound = root.get("request"); + exact(bound, REQUEST_FIELDS); + var lease = + AccountGameplayAdmissionLeaseEvidence.parseCanonical(text(bound, "accountLeaseJson")); + if (!lease.sha256().equals(text(bound, "accountLeaseSha256"))) { + throw new IllegalArgumentException( + "World hold request substituted its original Account lease digest"); + } + var request = + new Request( + lease, + decimal(text(bound, "expectedLifecycleEpoch"), true), + decimal(text(bound, "expectedRowVersion"), false)); + String encoded = text(root, "worldLifecycleEvidenceBase64"); + byte[] lifecycle = Base64.getDecoder().decode(encoded); + requireBound(lifecycle, MAX_LIFECYCLE_BYTES); + if (!Base64.getEncoder().encodeToString(lifecycle).equals(encoded)) { + throw new IllegalArgumentException("World lifecycle evidence base64 is not canonical"); + } + var result = + new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.fromString(text(root, "holdId")), + UUID.fromString(text(root, "holdFence")), + request, + WorldCanonicalInstanceLifecycleEvidence.fromStored(lifecycle)); + if (!Arrays.equals(bytes, result.canonicalBytes())) { + throw new IllegalArgumentException("World hold evidence bytes are not canonical"); + } + return result; + } catch (tools.jackson.core.JacksonException failure) { + throw new IllegalArgumentException("Malformed World player hold evidence", failure); + } + } + + private static String digest(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA256 is unavailable", failure); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException failure) { + throw new IllegalArgumentException("World hold evidence must be strict UTF-8", failure); + } + } + + private static void requireBound(byte[] bytes, int maximum) { + if (bytes == null || bytes.length == 0 || bytes.length > maximum) { + throw new IllegalArgumentException( + "World hold evidence exceeds its byte bound or is missing"); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || value.textValue().isEmpty()) { + throw new IllegalArgumentException("World hold evidence requires textual " + field); + } + return value.textValue(); + } + + private static void exact(JsonNode node, Set fields) { + if (node == null || !node.isObject()) { + throw new IllegalArgumentException("World hold evidence contains unknown or missing fields"); + } + Set actual = new java.util.HashSet<>(); + node.propertyNames().forEach(actual::add); + if (!actual.equals(fields)) + throw new IllegalArgumentException("World hold evidence contains unknown or missing fields"); + } + + public static long decimal(String value, boolean positive) { + if (value == null + || !value.matches(positive ? "[1-9][0-9]*" : "0|[1-9][0-9]*") + || value.length() > 19) { + throw new IllegalArgumentException("World hold counters require canonical decimal strings"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException failure) { + throw new IllegalArgumentException("World hold counter exceeds signed-long range", failure); + } + } + + /** Retained lease deadline triggers recovery diagnostics, never automatic release. */ + public long diagnosticExpiresAtMillis() { + return Long.parseLong((String) request.lease().carrier().get("expiresAt")); + } + + /** + * Complete original Account lease plus independently expected World lifecycle tuple. Account's + * regionEpoch is a separate domain and is never interpreted as this World lifecycle epoch. + */ + public record Request( + AccountGameplayAdmissionLeaseEvidence lease, + long expectedLifecycleEpoch, + long expectedRowVersion) { + public Request { + Objects.requireNonNull(lease, "lease"); + if (expectedLifecycleEpoch <= 0 || expectedRowVersion < 0) { + throw new IllegalArgumentException("Expected World lifecycle tuple is invalid"); + } + if (!(lease.carrier().get("bindingScope") instanceof Map scope) + || !"SHARED".equals(scope.get("playableStateScope")) + || !(lease.carrier().get("membershipBaseline") instanceof Map baseline) + || !"ACTIVE".equals(baseline.get("membershipLifecycleState"))) { + throw new IllegalArgumentException("Unsupported or non-admitting original lease scope"); + } + } + + public UUID leaseId() { + return UUID.fromString((String) lease.carrier().get("leaseId")); + } + + public UUID attemptId() { + return UUID.fromString((String) lease.carrier().get("requestId")); + } + + public UUID canonicalGameInstanceId() { + return UUID.fromString((String) scope().get("gameInstanceId")); + } + + public String targetNamespace() { + return (String) lease.carrier().get("targetNamespace"); + } + + public boolean sameBinding(Request other) { + return other != null + && lease.hasSameIdentity(other.lease) + && expectedLifecycleEpoch == other.expectedLifecycleEpoch + && expectedRowVersion == other.expectedRowVersion; + } + + public void requireExactActiveWorld(WorldCanonicalInstanceLifecycleEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + requireExactWorldSelector(evidence.request()); + if (!"ACTIVE".equals(evidence.lifecycleStatus()) + || expectedLifecycleEpoch != evidence.lifecycleEpoch() + || expectedRowVersion != evidence.rowVersion()) { + throw new IllegalArgumentException("World target is not the exact expected ACTIVE tuple"); + } + } + + public void requireExactWorldSelector( + WorldCanonicalInstanceLifecycleEvidence.Request selector) { + if (!targetNamespace().equals(selector.targetNamespace()) + || !scope().get("tenantId").equals(selector.canonicalTenantId().toString()) + || !scope().get("worldSlug").equals(selector.worldSlug()) + || !scope().get("gameInstanceId").equals(selector.canonicalGameInstanceId().toString()) + || !scope() + .get("playableStateNamespaceId") + .equals(selector.playableStateNamespaceId().toString()) + || !scope().get("playableStateScope").equals(selector.playableStateScope()) + || !selector.publicProduction()) { + throw new IllegalArgumentException("Original lease differs from canonical World scope"); + } + } + + @SuppressWarnings("unchecked") + private Map scope() { + return (Map) lease.carrier().get("bindingScope"); + } + } + + private static void requireOpaque(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException("Hold identity and fence must be opaque UUIDs"); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java new file mode 100644 index 0000000000..4970705c72 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java @@ -0,0 +1,808 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import org.junit.jupiter.api.Test; + +/** Real nested codecs over explicitly synthetic source/application/release and lease fixtures. */ +class WorldCanonicalPlayerAdmissionHoldEvidenceTest { + private static final String ID = "11111111-1111-4111-8111-111111111111"; + private static final String ACCOUNT = "22222222-2222-4222-8222-222222222222"; + + @Test + void closedCanonicalRoundtripPreservesEveryOriginalNestedByteAndDigest() throws Exception { + var original = hold(); + byte[] bytes = original.canonicalBytes(); + var decoded = WorldCanonicalPlayerAdmissionHoldEvidence.fromCanonical(bytes, original.sha256()); + assertThat(decoded).isEqualTo(original); + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + assertThat(decoded.request().lease().canonicalJson()) + .isEqualTo(original.request().lease().canonicalJson()); + assertThat(decoded.request().lease().sha256()).isEqualTo(original.request().lease().sha256()); + assertThat(decoded.worldEvidence().canonicalBytes()) + .containsExactly(original.worldEvidence().canonicalBytes()); + assertThat(decoded.diagnosticExpiresAtMillis()).isEqualTo(original.diagnosticExpiresAtMillis()); + bytes[0] ^= 1; + assertThat(original.canonicalBytes()).isEqualTo(decoded.canonicalBytes()); + } + + @Test + void rejectsUnknownMissingDuplicateAndNoncanonicalOuterBytes() throws Exception { + var original = hold(); + var root = JSON.readTree(original.canonicalBytes()); + var unknown = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) unknown).put("unknown", "value"); + assertRejected(canonical(unknown)); + var missing = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) missing).remove("schemaVersion"); + assertRejected(canonical(missing)); + var nestedUnknown = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) nestedUnknown.get("request")).put("unknown", "value"); + assertRejected(canonical(nestedUnknown)); + String text = new String(original.canonicalBytes(), StandardCharsets.UTF_8); + assertRejected( + text.replace("\"schemaVersion\":\"1\"", "\"schemaVersion\":\"1\",\"schemaVersion\":\"1\"") + .getBytes(StandardCharsets.UTF_8)); + assertRejected((" " + text).getBytes(StandardCharsets.UTF_8)); + assertRejected((text + "{}").getBytes(StandardCharsets.UTF_8)); + assertRejected( + text.replace("\"schemaVersion\":\"1\"", "\"schemaVersion\":1") + .getBytes(StandardCharsets.UTF_8)); + } + + @Test + void substitutedLeaseDigestOriginalScopeWorldEpochAndOpaqueIdentityFailClosed() throws Exception { + var original = hold(); + var root = JSON.readTree(original.canonicalBytes()); + var leaseDigest = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) leaseDigest.get("request")) + .put("accountLeaseSha256", "b".repeat(64)); + assertRejected(canonical(leaseDigest)); + var changedCarrier = new LinkedHashMap<>(original.request().lease().carrier()); + var changedScope = new LinkedHashMap<>(scope(changedCarrier)); + changedScope.put("worldSlug", "another-world"); + changedCarrier.put("bindingScope", changedScope); + var changedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + var changed = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("accountLeaseJson", changedLease.canonicalJson()); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("accountLeaseSha256", changedLease.sha256()); + assertRejected(canonical(changed)); + var epoch = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) epoch.get("request")) + .put("expectedLifecycleEpoch", "4"); + assertRejected(canonical(epoch)); + var uuid = root.deepCopy(); + ((tools.jackson.databind.node.ObjectNode) uuid) + .put("holdId", "00000000-0000-1000-8000-000000000001"); + assertRejected(canonical(uuid)); + assertThatThrownBy( + () -> + WorldCanonicalPlayerAdmissionHoldEvidence.fromCanonical( + original.canonicalBytes(), "c".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactDecimalStringsPreserveHighAndMaximumLongsAndRejectEveryOtherShape() throws Exception { + var original = hold(); + for (long value : List.of(9_007_199_254_740_993L, Long.MAX_VALUE)) { + var world = original.worldEvidence(); + var preciseWorld = + new WorldCanonicalInstanceLifecycleEvidence( + world.request(), + world.launchBinding(), + world.startLocation(), + world.runtimeRoomInstanceId(), + "ACTIVE", + value, + value, + world.captureId(), + world.graphSha256(), + world.preparationInputDigest(), + world.operationalRegionAssignments()); + var precise = + new WorldCanonicalPlayerAdmissionHoldEvidence( + original.holdId(), + original.holdFence(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + original.request().lease(), value, value), + preciseWorld); + assertThat(WorldCanonicalPlayerAdmissionHoldEvidence.parseCanonical(precise.canonicalBytes())) + .isEqualTo(precise); + } + for (String invalid : List.of("01", "-1", "+1", "1.0", "1e0", " 1", "9223372036854775808")) { + var changed = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("expectedRowVersion", invalid); + assertRejected(canonical(changed)); + } + var numeric = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) numeric.get("request")) + .put("expectedLifecycleEpoch", 3); + assertRejected(canonical(numeric)); + var zeroEpoch = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) zeroEpoch.get("request")) + .put("expectedLifecycleEpoch", "0"); + assertRejected(canonical(zeroEpoch)); + } + + @Test + void rejectsUtf8Base64ByteAndNestingBoundsWithoutMockedNestedDecoders() throws Exception { + assertRejected(new byte[] {(byte) 0xc3, 0x28}); + assertRejected(new byte[WorldCanonicalPlayerAdmissionHoldEvidence.MAX_EVIDENCE_BYTES + 1]); + assertRejected("{\"request\":{\"a\":{\"b\":{\"c\":{}}}}}".getBytes(StandardCharsets.UTF_8)); + var original = hold(); + var invalidBase64 = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) invalidBase64) + .put("worldLifecycleEvidenceBase64", "%%%"); + assertRejected(canonical(invalidBase64)); + var oversizedLifecycle = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) oversizedLifecycle) + .put( + "worldLifecycleEvidenceBase64", + Base64.getEncoder() + .encodeToString( + new byte[WorldCanonicalPlayerAdmissionHoldEvidence.MAX_LIFECYCLE_BYTES + 1])); + assertRejected(canonical(oversizedLifecycle)); + var corruptedWorld = JSON.readTree(original.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) corruptedWorld) + .put( + "worldLifecycleEvidenceBase64", + Base64.getEncoder().encodeToString("{}".getBytes(StandardCharsets.UTF_8))); + assertRejected(canonical(corruptedWorld)); + } + + private static void assertRejected(byte[] bytes) throws Exception { + String digest = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + assertThatThrownBy(() -> WorldCanonicalPlayerAdmissionHoldEvidence.fromCanonical(bytes, digest)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence hold() throws Exception { + var world = lifecycleEvidence(); + var carrier = carrier(); + var boundScope = new LinkedHashMap<>(scope(carrier)); + boundScope.put("worldSlug", world.request().worldSlug()); + boundScope.put( + "playableStateNamespaceId", world.request().playableStateNamespaceId().toString()); + carrier.put("bindingScope", boundScope); + var lease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + return new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + lease, world.lifecycleEpoch(), world.rowVersion()), + world); + } + + // Only synthetic fixture construction is adapted from existing Common Core codec tests below. + + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private static final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private static final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private static final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence() throws Exception { + WorldPublishedStartLocationEvidence selector = publishedSelector(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + RoomTemplateRef startLocation = selectorReceipt.startLocation(); + Request request = + new Request( + Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + startLocation, + 1042L, + "ACTIVE", + 3L, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + + static WorldPublishedStartLocationEvidence publishedSelector() throws Exception { + WorldDraftTerminalReadEvidence.Request terminalRequest = freshGraphRequest(); + OwnerReadback committed = committedReadback(terminalRequest, true); + var account = terminalRequest.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + account.tenantId(), + account.versionId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var applied = JSON.readTree(committed.result()); + byte[] receipt = + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + return new WorldPublishedStartLocationEvidence( + request, receipt, committed.fullBinding(), committed.result()); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) throws Exception { + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = freshGraph ? graphBytes(request, draft) : historicalGraphBytes(account); + String graphDigest = sha256(graph); + var result = new java.util.LinkedHashMap(); + result.put( + "schema", freshGraph ? "world-draft-graph-applied/v2" : "world-draft-graph-applied/v1"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + if (freshGraph) { + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + } + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JSON.valueToTree(result))); + } + + private static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + DraftCommitBinding draft = freshGraphBinding(); + return new WorldDraftTerminalReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), accountBinding(draft)); + } + + private static DraftCommitBinding freshGraphBinding() throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static byte[] historicalGraphBytes(DraftAuthorizationFenceBinding binding) { + return ("{\"schemaVersion\":\"2\",\"canonicalTenantId\":\"" + + binding.tenantId() + + "\",\"canonicalVersionId\":\"" + + binding.versionId() + + "\",\"rows\":[{}]}") + .getBytes(StandardCharsets.UTF_8); + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private static tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var selector = + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()); + String accountBindingDigest = sha256(request.originalAccountBinding()); + String receiptDigest = + startLocationReceiptDigest( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + accountBindingDigest, + draft.digest(), + TENANT_ID, + VERSION_ID, + ROOM_TEMPLATE_ID, + graphDigest); + var value = new java.util.LinkedHashMap(); + value.put("schema", "world-draft-start-location-receipt/v1"); + value.put("targetNamespace", request.targetNamespace()); + value.put("operationId", account.operationId().toString()); + value.put("requestId", account.requestId().toString()); + value.put("commitId", account.commitId().toString()); + value.put("authorizationFenceId", account.fenceId().toString()); + value.put("accountBindingDigest", accountBindingDigest); + value.put("bindingDigest", draft.digest()); + value.put("startLocation", selector); + value.put("graphDigest", graphDigest); + value.put("receiptDigest", receiptDigest); + return (tools.jackson.databind.node.ObjectNode) JSON.valueToTree(value); + } + + private static String startLocationReceiptDigest( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountBindingDigest, + String bindingDigest, + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + String graphDigest) + throws Exception { + var framed = new ByteArrayOutputStream(); + for (String value : + List.of( + "world-draft-start-location-receipt/v1", + targetNamespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountBindingDigest, + bindingDigest, + tenantId.toString(), + versionId.toString(), + roomTemplateId.toString(), + graphDigest)) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + return sha256(framed.toByteArray()); + } + + private static byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + static Map carrier() { + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "test"); + value.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + value.put("requestId", ID); + value.put("leaseId", ACCOUNT); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "tenantId", + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, ID); + scope.put("accountId", ACCOUNT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "9007199254740993"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + Map.of(ID, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + checkpoint("account/" + ACCOUNT, "0"), + checkpoint("issuer/firemud-account-service", "0"), + checkpoint("membership/" + ACCOUNT + "/" + ID, "1"), checkpoint("tenant/" + ID, "1"))); + long now = System.currentTimeMillis(); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", ACCOUNT), + Map.entry("operationId", ID), + Map.entry("issuanceRequestId", ID), + Map.entry("tokenJti", ID), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("issuedAt", Long.toString(now / 1000)), + Map.entry("notBefore", Long.toString(now / 1000)), + Map.entry("expiresAt", Long.toString(now / 1000 + 300)))); + value.put("evaluatedAt", Long.toString(now)); + value.put("expiresAt", Long.toString(now + 15000)); + return value; + } + + @SuppressWarnings("unchecked") + static Map scope(Map carrier) { + return (Map) carrier.get("bindingScope"); + } + + private static Map checkpoint(String suffix, String sequence) { + return Map.of( + "outboxStreamKey", "account:auth-authority:v1:" + suffix, "outboxSequence", sequence); + } +} diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 264cc3ebfc..27fab397ed 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -1,3 +1,4 @@ +import org.gradle.api.plugins.jvm.JvmTestSuite apply(from = "${rootDir}/gradle/proto-convention.gradle") @@ -11,7 +12,21 @@ firemudJooq { packageName.set("net.firedevops.firemud.gamedesign.jooq") } +testing { + suites { + named("test") { + sources.java.srcDir("src/sharedTest/java") + } + named("integrationTest") { + sources.java.srcDir("src/sharedTest/java") + } + } +} + dependencies { compileOnly(libs.spotbugs.annotations) + testCompileOnly(libs.spotbugs.annotations) + add("integrationTestCompileOnly", libs.spotbugs.annotations) + testImplementation(libs.bouncycastle.pkix) implementation(libs.aws.sdk.s3) } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java new file mode 100644 index 0000000000..94ec38dc56 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelection.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; + +/** + * Exact existing synchronized Draft selection. The shared codec preserves the original V43 bytes + * and digest; neither this retained selection nor codec validation establishes publication + * authority. + */ +public final class AuthoredDraftPublishSelection { + private final AuthoredDraftPublishSelectionBinding binding; + + private AuthoredDraftPublishSelection(AuthoredDraftPublishSelectionBinding binding) { + this.binding = Objects.requireNonNull(binding); + } + + public static AuthoredDraftPublishSelection capture( + PublishIntent intent, TargetProof target, PublicationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + var fence = evidence.visibilityFence(); + return new AuthoredDraftPublishSelection( + AuthoredDraftPublishSelectionBinding.capture( + sharedIntent(intent), + target, + evidence.binding(), + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + fence.target(), + fence.requestId(), + fence.commitId(), + fence.inputDigest(), + fence.resultVectorJson(), + fence.createdAt()))); + } + + public static AuthoredDraftPublishSelection fromStored(String storedJson, String storedDigest) { + return new AuthoredDraftPublishSelection( + AuthoredDraftPublishSelectionBinding.fromStored(storedJson, storedDigest)); + } + + public PublishIntent intent() { + var intent = binding.intent(); + return new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + } + + public TargetProof target() { + return binding.target(); + } + + public DraftCommitBinding selectedCommit() { + return binding.selectedCommit(); + } + + public UUID fenceRequestId() { + return binding.fenceRequestId(); + } + + public UUID fenceCommitId() { + return binding.fenceCommitId(); + } + + public String fenceInputDigest() { + return binding.fenceInputDigest(); + } + + public String fenceResultVectorJson() { + return binding.fenceResultVectorJson(); + } + + public String fenceCreatedAt() { + return binding.fenceCreatedAt(); + } + + public String canonicalJson() { + return binding.canonicalJson(); + } + + public byte[] canonicalBytes() { + return binding.canonicalBytes(); + } + + public String digest() { + return binding.digest(); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof AuthoredDraftPublishSelection selection + && binding.equals(selection.binding)); + } + + @Override + public int hashCode() { + return binding.hashCode(); + } + + private static AuthoredDraftPublishSelectionBinding.PublishIntent sharedIntent( + PublishIntent intent) { + Objects.requireNonNull(intent, "intent"); + return new AuthoredDraftPublishSelectionBinding.PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + } + + /** Full original eight caller inputs, retaining the existing public API. */ + public record PublishIntent( + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishRequestId, + String expectedVersionStateEpoch, + String notes, + UUID selectedCommitRequestId, + UUID selectedCommitId, + String selectedCommitDigest) { + public PublishIntent { + new AuthoredDraftPublishSelectionBinding.PublishIntent( + canonicalTenantId, + canonicalVersionId, + publishRequestId, + expectedVersionStateEpoch, + notes, + selectedCommitRequestId, + selectedCommitId, + selectedCommitDigest); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java new file mode 100644 index 0000000000..31adbd248b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionRepository.java @@ -0,0 +1,272 @@ +package net.firedevops.firemud.gamedesign.draft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.SQLException; +import java.time.OffsetDateTime; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.DraftCommitStateConflictException; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.LockedVersion; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.PublicationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Retains the first exact authored-Draft selection for a full-version publication request. The + * durable row is a reservation; this repository does not release it or infer any World freeze or + * terminal participant outcome. Later workflow code must recover the same selection and persist + * only definitive authenticated owner readback in its separately owned boundary. + */ +@Repository +public class AuthoredDraftPublishSelectionRepository { + private static final String SELECTION_TABLE = "game_design_authored_draft_publish_selection"; + private final DSLContext dsl; + private final DraftCommitCoordinatorRepository coordinator; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Internal collaborators only; no resources are acquired and no finalizer is used.") + public AuthoredDraftPublishSelectionRepository( + DSLContext dsl, DraftCommitCoordinatorRepository coordinator) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.coordinator = Objects.requireNonNull(coordinator, "coordinator"); + } + + /** + * Selects exactly one caller-named current synchronized commit for an existing full Draft + * Version. Exact request replay returns the immutable first selection before reading mutable + * Version state or current-fence state again. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public SelectionSnapshot reserve(PublishIntent intent) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(intent, "intent"); + + Optional prior = + readByPublishRequest(intent.canonicalTenantId(), intent.publishRequestId()); + if (prior.isPresent()) { + requireExactIntent(intent, prior.get().selection().intent()); + return prior.get(); + } + + LockedVersion version = + coordinator.lockVersionTarget(intent.canonicalTenantId(), intent.canonicalVersionId()); + SelectionSnapshot existing = findByTarget(version.target(), false); + if (existing != null) { + requireExactIntent(intent, existing.selection().intent()); + return existing; + } + + requireEligibleFirstSelection(version, intent); + if (coordinator.readApplicationSlot(version.target()).isPresent()) { + throw new DraftCommitStateConflictException( + "An active or unresolved owner application prevents Draft publication selection"); + } + PublicationEvidence evidence = + coordinator.requireSynchronizedPublicationEvidence( + version.target(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.capture(intent, version.target(), evidence); + + int inserted; + try { + inserted = insert(selection); + } catch (DataAccessException exception) { + if (isUniqueConstraintViolation(exception)) { + throw new DraftCommitIdentityConflictException( + "An authored Draft publication operation already reserves an exact Version", exception); + } + throw exception; + } + SelectionSnapshot persisted = findByTarget(version.target(), false); + if (persisted == null) { + throw new IllegalStateException( + "Durable authored Draft publication selection disappeared after insert"); + } + requireExactIntent(intent, persisted.selection().intent()); + if (inserted == 0 && !selection.equals(persisted.selection())) { + throw new DraftCommitIdentityConflictException( + "An authored Draft publish request was reused with changed exact binding data"); + } + return persisted; + } + + /** Reads the immutable selection only when all canonical target and request fields match. */ + public Optional readByPublishRequest( + UUID canonicalTenantId, String publishRequestId) { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + net.firedevops.firemud.common.publication.PublicationDigestRequestBinding + .validatePublicationIdentity(canonicalTenantId.toString(), publishRequestId); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND publish_request_id = ?", + canonicalTenantId, + publishRequestId); + return row == null ? Optional.empty() : Optional.of(toSnapshot(row)); + } + + /** Reads the immutable selection only when all canonical target and request fields match. */ + public Optional read( + UUID canonicalTenantId, UUID canonicalVersionId, String publishRequestId) { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + net.firedevops.firemud.common.publication.PublicationDigestRequestBinding + .validatePublicationIdentity(canonicalTenantId.toString(), publishRequestId); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + canonicalTenantId, + canonicalVersionId); + if (row == null || !publishRequestId.equals(row.get("publish_request_id", String.class))) { + return Optional.empty(); + } + return Optional.of(toSnapshot(row)); + } + + private int insert(AuthoredDraftPublishSelection selection) { + TargetProof target = selection.target(); + PublishIntent intent = selection.intent(); + return dsl.execute( + "INSERT INTO " + + SELECTION_TABLE + + " (canonical_tenant_id, canonical_version_id, game_design_version_row_id, " + + "game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, publish_request_id, version_state_epoch, " + + "selected_commit_request_id, selected_commit_id, selected_commit_digest, " + + "selection_digest, selection_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id) DO NOTHING", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest(), + selection.digest(), + selection.canonicalJson()); + } + + private SelectionSnapshot findByTarget(TargetProof target, boolean forUpdate) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId()); + return row == null ? null : toSnapshot(row); + } + + private SelectionSnapshot toSnapshot(Record row) { + AuthoredDraftPublishSelection selection = + AuthoredDraftPublishSelection.fromStored( + row.get("selection_json", String.class), row.get("selection_digest", String.class)); + TargetProof target = selection.target(); + PublishIntent intent = selection.intent(); + if (!row.get("canonical_tenant_id", UUID.class).equals(target.canonicalTenantId()) + || !row.get("canonical_version_id", UUID.class).equals(target.canonicalVersionId()) + || !row.get("game_design_version_row_id", Long.class) + .equals(target.gameDesignVersionRowId()) + || !row.get("game_design_version_tenant_key", String.class) + .equals(target.gameDesignVersionTenantKey()) + || !row.get("source_game_row_id", Long.class).equals(target.sourceGameRowId()) + || !row.get("source_game_tenant_key", String.class).equals(target.sourceGameTenantKey()) + || !row.get("source_provenance_kind", String.class).equals(target.sourceProvenanceKind()) + || !row.get("publish_request_id", String.class).equals(intent.publishRequestId()) + || !Long.toString(row.get("version_state_epoch", Long.class)) + .equals(intent.expectedVersionStateEpoch()) + || !row.get("selected_commit_request_id", UUID.class) + .equals(intent.selectedCommitRequestId()) + || !row.get("selected_commit_id", UUID.class).equals(intent.selectedCommitId()) + || !row.get("selected_commit_digest", String.class).equals(intent.selectedCommitDigest())) { + throw new IllegalStateException( + "Authored Draft publication selection indexed identity differs from exact stored binding"); + } + return new SelectionSnapshot(selection, row.get("created_at", OffsetDateTime.class)); + } + + private static void requireEligibleFirstSelection(LockedVersion version, PublishIntent intent) { + if (!"DRAFT".equals(version.versionState()) + || version.scriptOnly() + || version.scriptPatchVersion() != null + || version.baseVersionId() != null) { + throw new DraftCommitStateConflictException( + "Only an existing non-script-only full Version in DRAFT can be selected for publication"); + } + if (!Long.toString(version.versionStateEpoch()).equals(intent.expectedVersionStateEpoch())) { + throw new DraftCommitStateConflictException( + "Authored Draft publication selection has a stale Version state epoch"); + } + } + + private static void requireExactIntent(PublishIntent expected, PublishIntent actual) { + if (!expected.equals(actual)) { + throw new DraftCommitIdentityConflictException( + "Publish request identity was reused with changed notes, target, epoch, or commit selection"); + } + } + + private void requireWritableReadCommittedTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED).equals(isolation)) { + throw new IllegalStateException( + "Authored Draft selection mutations require a caller-owned writable READ_COMMITTED transaction"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static boolean isUniqueConstraintViolation(Throwable failure) { + Throwable current = failure; + while (current != null) { + if (current instanceof SQLException sqlException + && "23505".equals(sqlException.getSQLState())) { + return true; + } + current = current.getCause(); + } + return false; + } + + public record SelectionSnapshot( + AuthoredDraftPublishSelection selection, OffsetDateTime createdAt) { + public SelectionSnapshot { + Objects.requireNonNull(selection, "selection"); + Objects.requireNonNull(createdAt, "createdAt"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java new file mode 100644 index 0000000000..680d974385 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java @@ -0,0 +1,1679 @@ +package net.firedevops.firemud.gamedesign.draft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.EnumMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** Durable, owner-local persistence for exact Game Design multi-owner Draft commit coordination. */ +@Repository +public class DraftCommitCoordinatorRepository { + private static final String COMMIT_TABLE = "game_design_draft_commit"; + private static final String OWNER_RESULT_TABLE = "game_design_draft_commit_owner_result"; + private static final String FINAL_ABORT_TABLE = "game_design_draft_commit_final_abort"; + private static final String APPLICATION_SLOT_TABLE = "game_design_draft_commit_application_slot"; + private static final String VISIBILITY_FENCE_TABLE = "game_design_draft_commit_visibility_fence"; + private static final String VISIBILITY_TABLE = "game_design_draft_commit_visibility"; + private static final String PUBLISH_SELECTION_TABLE = + "game_design_authored_draft_publish_selection"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Comparator APPLIED_EPOCH_ORDER = + Comparator.comparing(AppliedEpoch::aggregateType) + .thenComparing(AppliedEpoch::aggregateId) + .thenComparing(AppliedEpoch::scopeType) + .thenComparing(AppliedEpoch::scopeId); + + private final DSLContext dsl; + private final GameDesignDraftTerminalOutcomeRepository terminalOutcomes; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Internal collaborator only; no resources are acquired and no finalizer is used.") + public DraftCommitCoordinatorRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.terminalOutcomes = new GameDesignDraftTerminalOutcomeRepository(dsl); + } + + /** + * Durably claims one complete immutable request binding and initializes every required owner. An + * exact replay performs no writes; either identity reused with changed binding data conflicts. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public CommitSnapshot claim(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(binding, "binding"); + CommitRecord existing = findCommit(binding, true); + if (existing != null) { + requireExactBinding(binding, existing.binding()); + return snapshot(existing); + } + + int inserted = + dsl.execute( + "INSERT INTO " + + COMMIT_TABLE + + " (canonical_tenant_id, canonical_version_id, game_design_version_row_id, " + + "game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, request_id, commit_id, base_commit_id, input_digest, " + + "binding_json, workflow_state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'QUEUED') " + // Request and commit are independent immutable identities; suppress either unique + // collision in PostgreSQL so the transaction remains readable for exact readback. + + "ON CONFLICT DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.target().gameDesignVersionRowId(), + binding.target().gameDesignVersionTenantKey(), + binding.target().sourceGameRowId(), + binding.target().sourceGameTenantKey(), + binding.target().sourceProvenanceKind(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + binding.digest(), + binding.canonicalJson()); + + if (inserted == 0) { + CommitRecord concurrent = findCommit(binding, true); + if (concurrent == null) { + throw new DraftCommitIdentityConflictException( + "Draft commit identity conflicts with another immutable request"); + } + requireExactBinding(binding, concurrent.binding()); + return snapshot(concurrent); + } + + for (Owner owner : binding.requiredOwners()) { + dsl.execute( + "INSERT INTO " + + OWNER_RESULT_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, owner, status) " + + "VALUES (?, ?, ?, ?, 'NOT_ATTEMPTED')", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + owner.name()); + } + CommitRecord persisted = findCommit(binding, true); + if (persisted == null) { + throw new IllegalStateException("Durable Draft commit binding disappeared after insert"); + } + requireExactBinding(binding, persisted.binding()); + return snapshot(persisted); + } + + /** + * Claims a complete Account operation alongside its coordinator binding before dispatch. The + * Account bytes are exact source material only; this storage operation does not authenticate them + * or authorize owner writes. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public CommitSnapshot claim( + DraftCommitBinding binding, DraftAuthorizationFenceBinding originalAccountBinding) { + requireWritableReadCommittedTransaction(); + GameDesignDraftTerminalOperation operation = + new GameDesignDraftTerminalOperation(originalAccountBinding, binding); + LockedVersion lockedVersion = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + terminalOutcomes.validateClaim(operation, lockedVersion); + CommitSnapshot snapshot = claim(binding); + terminalOutcomes.claim(operation, lockedVersion); + return snapshot; + } + + /** Reads one durable binding and its exact per-owner status vector. */ + public Optional read(DraftCommitBinding.TargetProof target, UUID requestId) { + requireTargetAndRequest(target, requestId); + CommitRecord record = findCommit(target, requestId, false); + return record == null ? Optional.empty() : Optional.of(snapshot(record)); + } + + /** Reads the current active dispatch/recovery slot for one canonical Version. */ + public Optional readApplicationSlot(DraftCommitBinding.TargetProof target) { + requireTarget(target); + Record record = findSlot(target, false); + return record == null ? Optional.empty() : Optional.of(toApplicationSlot(record)); + } + + /** + * Claims the single active owner-application slot for this canonical Version. The persisted + * binding remains queued if another exact commit currently owns the slot. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public ApplicationSlot claimApplicationSlot(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(binding, "binding"); + LockedVersion version = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + CommitRecord commit = findCommit(binding, true); + if (commit == null) { + throw new DraftCommitNotFoundException( + "Draft commit must be durably claimed before slot claim"); + } + requireExactBinding(binding, commit.binding()); + if (commit.workflowState() == WorkflowState.SYNCHRONIZED + || commit.workflowState() == WorkflowState.REJECTED + || commit.workflowState() == WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "A terminal Draft commit cannot reclaim its slot"); + } + Record existing = findSlot(binding.target(), true); + if (existing != null) { + ApplicationSlot slot = toApplicationSlot(existing); + requireSameSlot(binding, slot); + return slot; + } + int inserted = + dsl.execute( + "INSERT INTO " + + APPLICATION_SLOT_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + Record persisted = findSlot(binding.target(), true); + if (persisted == null) { + throw new DraftCommitStateConflictException( + "Another coordinated Draft commit currently owns the Version application slot"); + } + ApplicationSlot slot = toApplicationSlot(persisted); + requireSameSlot(binding, slot); + if (inserted == 1 && slot.claimedAt() == null) { + throw new IllegalStateException("Draft commit application slot lacks durable claim time"); + } + return slot; + } + + /** Marks an owner dispatch in progress before the caller makes any remote owner call. */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public OwnerState markOwnerInProgress(DraftCommitBinding binding, Owner owner) { + requireWritableReadCommittedTransaction(); + LockedVersion version = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + requireExactCommitInTransaction(binding); + requireActiveSlot(binding); + OwnerState current = requireOwnerState(binding, owner, true); + if (current.status() == OwnerStatus.IN_PROGRESS) { + return current; + } + if (current.status() != OwnerStatus.NOT_ATTEMPTED) { + throw new DraftCommitStateConflictException( + "Only a not-yet-attempted owner can enter IN_PROGRESS"); + } + int updated = + dsl.execute( + "UPDATE " + + OWNER_RESULT_TABLE + + " SET status = 'IN_PROGRESS', updated_at = CAST(? AS timestamptz) " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = ? AND status = 'NOT_ATTEMPTED'", + now(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + owner.name()); + if (updated != 1) { + throw new DraftCommitStateConflictException("Draft owner status changed concurrently"); + } + CommitRecord commit = requireCommit(binding, true); + if (commit.workflowState() == WorkflowState.QUEUED) { + updateWorkflowState(binding, WorkflowState.APPLYING); + } + return requireOwnerState(binding, owner, false); + } + + /** + * Retains one full owner result. UNKNOWN remains unresolved and can only be resolved through an + * exact later APPLIED/REJECTED result for the same commit and binding digest. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public OwnerState recordOwnerOutcome(DraftCommitBinding binding, OwnerOutcome outcome) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(outcome, "outcome"); + LockedVersion version = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + requireExactCommitInTransaction(binding); + requireOutcomeMatches(binding, outcome); + OwnerState current = requireOwnerState(binding, outcome.owner(), true); + if (current.outcome().filter(outcome::equals).isPresent()) { + return current; + } + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + requireActiveSlot(binding); + if (current.status() != OwnerStatus.IN_PROGRESS && current.status() != OwnerStatus.UNKNOWN) { + throw new DraftCommitStateConflictException( + "A Draft owner outcome cannot replace its durable prior result"); + } + if (current.status() == OwnerStatus.UNKNOWN && outcome.status() == OwnerStatus.UNKNOWN) { + throw new DraftCommitStateConflictException( + "UNKNOWN remains unresolved until exact owner readback supplies a terminal result"); + } + String appliedUnitsJson = + outcome.status() == OwnerStatus.UNKNOWN + ? null + : canonicalJson(outcome.appliedEpochs().stream().map(this::appliedEpochJson).toList()); + int updated = + dsl.execute( + "UPDATE " + + OWNER_RESULT_TABLE + + " SET status = ?, result_commit_id = ?, result_binding_digest = ?, " + + "result_identity = ?, result_bytes = ?, applied_units_json = ?, updated_at = CAST(? AS timestamptz) " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = ? AND status = ?", + outcome.status().name(), + outcome.commitId(), + outcome.bindingDigest(), + outcome.resultIdentity(), + outcome.resultBytes(), + appliedUnitsJson, + now(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + outcome.owner().name(), + current.status().name()); + if (updated != 1) { + throw new DraftCommitStateConflictException("Draft owner result changed concurrently"); + } + updateWorkflowStateAfterOwnerOutcome(binding, outcome); + return requireOwnerState(binding, outcome.owner(), false); + } + + /** + * Canonical source-aware fence handoff. The caller still supplies independently verified owner + * proof; both complete source snapshots become visible in this same owner transaction. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public VisibilityFence advanceSourceVisibilityFence( + DraftCommitBinding binding, CoordinatorProof coordinatorProof) { + requireWritableReadCommittedTransaction(); + var sources = new GameDesignSourceRepository(dsl); + if (sources.readGenesis(binding.target()).isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_UNAVAILABLE"); + } + VisibilityFence fence = advanceVisibilityFence(binding, coordinatorProof); + sources.captureSynchronized(binding); + return fence; + } + + /** + * Advances the internal synchronized visibility record only from the complete exact APPLIED + * result vector. This storage primitive is intentionally not wired to an owner producer or read + * API; callers must validate each remote producer's authority before invoking it. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public VisibilityFence advanceVisibilityFence( + DraftCommitBinding binding, CoordinatorProof coordinatorProof) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(coordinatorProof, "coordinatorProof"); + LockedVersion version = lockVersionTarget(binding.target()); + terminalOutcomes.requireNotDefinitivelyAborted(binding); + CommitRecord commit = requireCommit(binding, true); + requireExactBinding(binding, commit.binding()); + if (!coordinatorProof.matches(binding)) { + throw new DraftCommitIdentityConflictException( + "Visibility fence requires coordinator proof for this exact Draft binding"); + } + List ownerStates = lockAndReadOwnerStates(binding); + coordinatorProof.requireSameOutcomes(ownerStates); + String resultVectorJson = exactAppliedResultVector(binding, ownerStates); + VisibilityFence existing = findVisibilityFence(binding, false); + if (existing != null) { + if (!existing.inputDigest().equals(binding.digest()) + || !existing.resultVectorJson().equals(resultVectorJson)) { + throw new DraftCommitIdentityConflictException( + "A Draft commit visibility fence already retains different owner evidence"); + } + terminalOutcomes.recordCommitted(binding, existing, resultVectorJson, false); + return existing; + } + if (commit.workflowState() == WorkflowState.SYNCHRONIZED + || commit.workflowState() == WorkflowState.REJECTED + || commit.workflowState() == WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "Terminal Draft commit has no matching immutable visibility fence"); + } + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + requireActiveSlot(binding); + int inserted = + dsl.execute( + "INSERT INTO " + + VISIBILITY_FENCE_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "input_digest, result_vector_json) VALUES (?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + resultVectorJson); + VisibilityFence persisted = findVisibilityFence(binding, false); + if (persisted == null) { + throw new IllegalStateException("Draft visibility fence insert returned no persisted row"); + } + if (inserted == 0) { + if (!persisted.inputDigest().equals(binding.digest()) + || !persisted.resultVectorJson().equals(resultVectorJson)) { + throw new DraftCommitIdentityConflictException( + "A concurrent Draft visibility fence retained different owner evidence"); + } + CommitRecord concurrent = requireCommit(binding, true); + if (concurrent.workflowState() != WorkflowState.SYNCHRONIZED) { + throw new DraftCommitStateConflictException( + "A pre-existing visibility fence is not paired with synchronized workflow state"); + } + terminalOutcomes.recordCommitted(binding, persisted, resultVectorJson, false); + return persisted; + } + dsl.execute( + "INSERT INTO " + + VISIBILITY_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest) " + + "VALUES (?, ?, ?, ?, ?) ON CONFLICT (canonical_tenant_id, canonical_version_id) " + + "DO UPDATE SET request_id = EXCLUDED.request_id, commit_id = EXCLUDED.commit_id, " + + "input_digest = EXCLUDED.input_digest, updated_at = EXCLUDED.updated_at", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest()); + updateWorkflowState(binding, WorkflowState.SYNCHRONIZED); + terminalOutcomes.recordCommitted(binding, persisted, resultVectorJson, true); + return persisted; + } + + /** + * Reads the current internal visibility pointer without claiming that downstream reads use it. + */ + public Optional readVisibilityFence(DraftCommitBinding.TargetProof target) { + requireTarget(target); + Record pointer = + dsl.fetchOne( + "SELECT request_id, commit_id FROM " + + VISIBILITY_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (pointer == null) { + return Optional.empty(); + } + UUID requestId = pointer.get("request_id", UUID.class); + UUID commitId = pointer.get("commit_id", UUID.class); + Record fence = + dsl.fetchOne( + "SELECT input_digest, result_vector_json, created_at FROM " + + VISIBILITY_FENCE_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId, + commitId); + if (fence == null) { + throw new IllegalStateException("Draft visibility pointer lacks its immutable fence record"); + } + return Optional.of(toVisibilityFence(target, requestId, commitId, fence)); + } + + /** + * Captures only an explicitly selected current synchronized commit while the caller's publication + * transaction owns the exact Version row lock. It does not authorize publication or assert any + * remote freeze/participant result. + */ + PublicationEvidence requireSynchronizedPublicationEvidence( + DraftCommitBinding.TargetProof target, UUID requestId, UUID commitId, String inputDigest) { + requireWritableReadCommittedTransaction(); + LockedVersion version = lockVersionTarget(target); + requireDraftVersion(version); + if (findSlot(target, false) != null) { + throw new DraftCommitStateConflictException( + "An active owner application prevents authored Draft publication selection"); + } + + CommitRecord commit = findCommit(target, requestId, true); + if (commit == null + || !commit.binding().commitId().equals(commitId) + || !commit.binding().digest().equals(inputDigest)) { + throw new DraftCommitIdentityConflictException( + "Selected authored Draft commit identity or digest does not match durable input"); + } + if (commit.workflowState() != WorkflowState.SYNCHRONIZED) { + throw new DraftCommitStateConflictException( + "Only an explicitly selected synchronized authored Draft commit can be published"); + } + List ownerStates = lockAndReadOwnerStates(commit.binding()); + String exactVector = exactAppliedResultVector(commit.binding(), ownerStates); + VisibilityFence fence = findVisibilityFence(commit.binding(), true); + if (fence == null + || !fence.inputDigest().equals(inputDigest) + || !fence.resultVectorJson().equals(exactVector)) { + throw new DraftCommitStateConflictException( + "Selected authored Draft commit lacks its exact complete synchronized result fence"); + } + VisibilityFence current = + readVisibilityFence(target) + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Selected authored Draft commit is not the current synchronized fence")); + if (!current.requestId().equals(requestId) + || !current.commitId().equals(commitId) + || !current.inputDigest().equals(inputDigest) + || !current.resultVectorJson().equals(exactVector)) { + throw new DraftCommitStateConflictException( + "Selected authored Draft commit is stale relative to the current synchronized fence"); + } + return new PublicationEvidence(commit.binding(), fence); + } + + /** + * Releases the Version application slot after complete success, definite no-application + * rejection, or exact final-abort evidence with every owner definitive. Unresolved outcomes and + * partial application without that final-abort proof keep the slot held. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public void releaseApplicationSlot(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + LockedVersion version = lockVersionTarget(binding.target()); + CommitRecord commit = requireCommit(binding, true); + requireExactBinding(binding, commit.binding()); + Record slotRecord = findSlot(binding.target(), true); + if (commit.workflowState() == WorkflowState.FAILED_NONPUBLICATION) { + requireFinalAbortSlotRelease(binding, commit); + if (slotRecord == null || !isSameSlot(binding, toApplicationSlot(slotRecord))) { + return; + } + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + deleteApplicationSlot(binding); + return; + } + if (slotRecord == null) { + if (commit.workflowState() == WorkflowState.SYNCHRONIZED + || commit.workflowState() == WorkflowState.REJECTED) { + return; + } + throw new DraftCommitStateConflictException( + "Draft commit does not own the active Version slot"); + } + requireSameSlot(binding, toApplicationSlot(slotRecord)); + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + List outcomes = lockAndReadOwnerStates(binding); + boolean anyApplied = outcomes.stream().anyMatch(state -> state.status() == OwnerStatus.APPLIED); + boolean unresolved = + outcomes.stream() + .anyMatch( + state -> + state.status() == OwnerStatus.UNKNOWN + || state.status() == OwnerStatus.IN_PROGRESS); + boolean allApplied = outcomes.stream().allMatch(state -> state.status() == OwnerStatus.APPLIED); + boolean definiteNoApply = + outcomes.stream() + .allMatch( + state -> + state.status() == OwnerStatus.NOT_ATTEMPTED + || state.status() == OwnerStatus.REJECTED) + && outcomes.stream().anyMatch(state -> state.status() == OwnerStatus.REJECTED); + if (unresolved || (anyApplied && !allApplied) || (!allApplied && !definiteNoApply)) { + throw new DraftCommitStateConflictException( + "Unresolved or partially applied Draft commit cannot release its Version slot"); + } else if (allApplied) { + VisibilityFence fence = findVisibilityFence(binding, false); + if (commit.workflowState() != WorkflowState.SYNCHRONIZED + || fence == null + || !fence.inputDigest().equals(binding.digest())) { + throw new DraftCommitStateConflictException( + "All-owner Draft application must have its exact synchronized visibility fence first"); + } + } else if (definiteNoApply) { + if (anyApplied) { + throw new DraftCommitStateConflictException( + "A rejected Draft commit with any applied owner requires reconciliation"); + } + if (terminalOutcomes.isAccountBound(binding)) { + throw new DraftCommitStateConflictException( + "An Account-bound Draft commit requires its exact final-abort tombstone and complete owner vector"); + } + if (commit.workflowState() != WorkflowState.APPLYING + && commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + throw new DraftCommitStateConflictException( + "Definite rejected Draft commit is not in an applicable workflow state"); + } + updateWorkflowState(binding, WorkflowState.REJECTED); + } + deleteApplicationSlot(binding); + } + + private void deleteApplicationSlot(DraftCommitBinding binding) { + int deleted = + dsl.execute( + "DELETE FROM " + + APPLICATION_SLOT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (deleted != 1) { + throw new DraftCommitStateConflictException( + "Draft Version application slot changed concurrently"); + } + } + + /** + * Stores exact, already-authenticated producer no-commit evidence for a definitive owner vector + * and atomically makes this commit terminally non-publishable. This storage method does not + * authenticate arbitrary bytes; only a future authenticated recovery producer may call it. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public FinalAbortReceipt recordDefinitiveFinalAbort( + DraftCommitBinding binding, byte[] exactAbortBytes) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(exactAbortBytes, "exactAbortBytes"); + if (exactAbortBytes.length == 0) { + throw new IllegalArgumentException("Final-abort evidence bytes must not be empty"); + } + + LockedVersion version = lockVersionTarget(binding.target()); + CommitRecord commit = requireCommit(binding, true); + Record slotRecord = findSlot(binding.target(), true); + Record existingAbort = findFinalAbort(binding, true); + if (existingAbort != null) { + requireExactFinalAbort(binding, exactAbortBytes, existingAbort); + if (commit.workflowState() != WorkflowState.FAILED_NONPUBLICATION) { + throw new IllegalStateException( + "Durable final-abort evidence is not paired with terminal nonpublication state"); + } + requireFinalAbortSlotRelease(binding, commit); + terminalOutcomes.recordAborted( + binding, + toFinalAbortReceipt(binding, existingAbort), + exactTerminalAbortResultVector(binding, lockAndReadOwnerStates(binding)), + false); + return toFinalAbortReceipt(binding, existingAbort); + } + + terminalOutcomes.requireNotDefinitivelyAborted(binding); + requireDraftVersion(version); + requireNoPublicationSelection(binding.target()); + if (slotRecord == null) { + throw new DraftCommitStateConflictException( + "Definitive final-abort evidence requires the active Version application slot"); + } + requireSameSlot(binding, toApplicationSlot(slotRecord)); + if (commit.workflowState() != WorkflowState.APPLYING + && commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + throw new DraftCommitStateConflictException( + "Only an unresolved owner-application workflow can record final-abort evidence"); + } + if (findVisibilityFence(binding, true) != null) { + throw new DraftCommitStateConflictException( + "A commit with a successful visibility fence cannot be finalized as nonpublication"); + } + + List ownerStates = lockAndReadOwnerStates(binding); + requireCompleteTerminalAbortVector(binding, ownerStates); + int inserted = + dsl.execute( + "INSERT INTO " + + FINAL_ABORT_TABLE + + " (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "input_digest, binding_json, abort_bytes) VALUES (?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "DO NOTHING", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + binding.canonicalJson(), + exactAbortBytes.clone()); + Record persisted = findFinalAbort(binding, true); + if (persisted == null) { + throw new IllegalStateException("Final-abort evidence insert returned no durable row"); + } + requireExactFinalAbort(binding, exactAbortBytes, persisted); + if (inserted == 0) { + CommitRecord concurrent = requireCommit(binding, true); + if (concurrent.workflowState() != WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "Concurrent final-abort evidence has no terminal nonpublication state"); + } + terminalOutcomes.recordAborted( + binding, + toFinalAbortReceipt(binding, persisted), + exactTerminalAbortResultVector(binding, ownerStates), + false); + return toFinalAbortReceipt(binding, persisted); + } + + updateWorkflowState(binding, WorkflowState.FAILED_NONPUBLICATION); + terminalOutcomes.recordAborted( + binding, + toFinalAbortReceipt(binding, persisted), + exactTerminalAbortResultVector(binding, ownerStates), + true); + return toFinalAbortReceipt(binding, persisted); + } + + private void requireFinalAbortSlotRelease(DraftCommitBinding binding, CommitRecord commit) { + if (commit.workflowState() != WorkflowState.FAILED_NONPUBLICATION) { + throw new DraftCommitStateConflictException( + "Only a terminal nonpublication commit can release by final-abort evidence"); + } + Record abort = findFinalAbort(binding, true); + if (abort == null) { + throw new DraftCommitStateConflictException( + "Failed nonpublication state lacks exact durable final-abort evidence"); + } + requireExactFinalAbort(binding, abort.get("abort_bytes", byte[].class), abort); + if (findVisibilityFence(binding, true) != null) { + throw new DraftCommitStateConflictException( + "A final-aborted Draft commit cannot own a successful visibility fence"); + } + requireCompleteTerminalAbortVector(binding, lockAndReadOwnerStates(binding)); + } + + private void requireCompleteTerminalAbortVector( + DraftCommitBinding binding, List ownerStates) { + if (ownerStates.size() != binding.requiredOwners().size()) { + throw new DraftCommitStateConflictException( + "Definitive final-abort evidence requires every exact required owner result"); + } + for (Owner owner : binding.requiredOwners()) { + OwnerState state = + ownerStates.stream() + .filter(candidate -> candidate.owner() == owner) + .findFirst() + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Definitive final-abort evidence cannot omit a required owner result")); + if (state.status() != OwnerStatus.APPLIED && state.status() != OwnerStatus.REJECTED) { + throw new DraftCommitStateConflictException( + "Definitive final-abort evidence requires only exact terminal APPLIED or REJECTED owners"); + } + OwnerOutcome outcome = + state + .outcome() + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Definitive final-abort evidence requires durable owner result bytes")); + requireOutcomeMatches(binding, outcome); + } + } + + private String exactTerminalAbortResultVector( + DraftCommitBinding binding, List ownerStates) { + requireCompleteTerminalAbortVector(binding, ownerStates); + List> resultVector = new ArrayList<>(); + for (Owner owner : binding.requiredOwners()) { + OwnerState state = + ownerStates.stream() + .filter(candidate -> candidate.owner() == owner) + .findFirst() + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Definitive final-abort evidence cannot omit a required owner result")); + resultVector.add(ownerResultJson(state.outcome().orElseThrow())); + } + return canonicalJson(resultVector); + } + + private void updateWorkflowStateAfterOwnerOutcome( + DraftCommitBinding binding, OwnerOutcome outcome) { + CommitRecord commit = requireCommit(binding, true); + if (commit.workflowState() == WorkflowState.QUEUED) { + updateWorkflowState(binding, WorkflowState.APPLYING); + commit = requireCommit(binding, true); + } + if (outcome.status() == OwnerStatus.UNKNOWN) { + if (commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + updateWorkflowState(binding, WorkflowState.RECONCILIATION_REQUIRED); + } + return; + } + List states = lockAndReadOwnerStates(binding); + boolean hasApplied = states.stream().anyMatch(state -> state.status() == OwnerStatus.APPLIED); + boolean hasRejected = states.stream().anyMatch(state -> state.status() == OwnerStatus.REJECTED); + boolean hasUnknown = states.stream().anyMatch(state -> state.status() == OwnerStatus.UNKNOWN); + if (hasUnknown || (hasApplied && hasRejected)) { + if (commit.workflowState() != WorkflowState.RECONCILIATION_REQUIRED) { + updateWorkflowState(binding, WorkflowState.RECONCILIATION_REQUIRED); + } + } + } + + private void updateWorkflowState(DraftCommitBinding binding, WorkflowState state) { + int updated = + dsl.execute( + "UPDATE " + + COMMIT_TABLE + + " SET workflow_state = ?, updated_at = CAST(? AS timestamptz) " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? " + + "AND workflow_state <> ?", + state.name(), + now(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + state.name()); + if (updated != 1) { + throw new DraftCommitStateConflictException( + "Draft commit workflow state changed concurrently"); + } + } + + private CommitRecord requireExactCommitInTransaction(DraftCommitBinding binding) { + requireWritableReadCommittedTransaction(); + return requireCommit(binding, true); + } + + private CommitRecord requireCommit(DraftCommitBinding binding, boolean forUpdate) { + Objects.requireNonNull(binding, "binding"); + CommitRecord record = findCommit(binding, forUpdate); + if (record == null) { + throw new DraftCommitNotFoundException("Draft commit binding is missing"); + } + requireExactBinding(binding, record.binding()); + return record; + } + + private CommitRecord findCommit(DraftCommitBinding binding, boolean forUpdate) { + return findCommit(binding.target(), binding.requestId(), forUpdate); + } + + private CommitRecord findCommit( + DraftCommitBinding.TargetProof target, UUID requestId, boolean forUpdate) { + String suffix = forUpdate ? " FOR UPDATE" : ""; + Record row = + dsl.fetchOne( + "SELECT * FROM " + + COMMIT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ?" + + suffix, + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId); + if (row == null) { + return null; + } + DraftCommitBinding binding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + if (!target.equals(binding.target()) + || !requestId.equals(binding.requestId()) + || !row.get("commit_id", UUID.class).equals(binding.commitId()) + || !row.get("base_commit_id", String.class).equals(binding.baseCommitId()) + || !row.get("game_design_version_row_id", Long.class) + .equals(binding.target().gameDesignVersionRowId()) + || !row.get("game_design_version_tenant_key", String.class) + .equals(binding.target().gameDesignVersionTenantKey()) + || !row.get("source_game_row_id", Long.class).equals(binding.target().sourceGameRowId()) + || !row.get("source_game_tenant_key", String.class) + .equals(binding.target().sourceGameTenantKey()) + || !row.get("source_provenance_kind", String.class) + .equals(binding.target().sourceProvenanceKind())) { + throw new IllegalStateException( + "Draft commit indexed identity differs from its exact JSON binding"); + } + return new CommitRecord( + binding, + WorkflowState.valueOf(row.get("workflow_state", String.class)), + row.get("created_at", OffsetDateTime.class), + row.get("updated_at", OffsetDateTime.class)); + } + + private CommitSnapshot snapshot(CommitRecord record) { + return new CommitSnapshot(record, readOwnerStates(record.binding(), false)); + } + + private List lockAndReadOwnerStates(DraftCommitBinding binding) { + return readOwnerStates(binding, true); + } + + private List readOwnerStates(DraftCommitBinding binding, boolean forUpdate) { + List states = + dsl + .fetch( + "SELECT * FROM " + + OWNER_RESULT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? ORDER BY owner" + + (forUpdate ? " FOR UPDATE" : ""), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId()) + .stream() + .map(this::toOwnerState) + .toList(); + Map byOwner = new EnumMap<>(Owner.class); + for (OwnerState state : states) { + if (byOwner.put(state.owner(), state) != null) { + throw new IllegalStateException("Duplicate durable Draft owner status row"); + } + } + if (!byOwner.keySet().equals(new HashSet<>(binding.requiredOwners()))) { + throw new IllegalStateException( + "Durable Draft owner status set differs from its complete binding"); + } + return binding.requiredOwners().stream().map(byOwner::get).toList(); + } + + private OwnerState requireOwnerState(DraftCommitBinding binding, Owner owner, boolean forUpdate) { + Objects.requireNonNull(owner, "owner"); + if (!binding.requiredOwners().contains(owner)) { + throw new DraftCommitStateConflictException( + "Owner is not in this Draft commit's required set"); + } + String suffix = forUpdate ? " FOR UPDATE" : ""; + Record row = + dsl.fetchOne( + "SELECT * FROM " + + OWNER_RESULT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = ?" + + suffix, + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + owner.name()); + if (row == null) { + throw new IllegalStateException("Required Draft owner status row is missing"); + } + return toOwnerState(row); + } + + private OwnerState toOwnerState(Record row) { + Owner owner = Owner.valueOf(row.get("owner", String.class)); + OwnerStatus status = OwnerStatus.valueOf(row.get("status", String.class)); + UUID resultCommitId = row.get("result_commit_id", UUID.class); + String digest = row.get("result_binding_digest", String.class); + String resultIdentity = row.get("result_identity", String.class); + byte[] resultBytes = row.get("result_bytes", byte[].class); + String appliedUnitsJson = row.get("applied_units_json", String.class); + OwnerOutcome outcome = null; + if (resultCommitId != null || digest != null || resultIdentity != null || resultBytes != null) { + if (resultCommitId == null || digest == null) { + throw new IllegalStateException("Draft owner result has incomplete commit identity"); + } + List epochs = + appliedUnitsJson == null ? List.of() : parseAppliedEpochs(appliedUnitsJson); + outcome = + new OwnerOutcome( + owner, status, resultCommitId, digest, resultIdentity, resultBytes, epochs); + } + return new OwnerState( + owner, + status, + Optional.ofNullable(outcome), + row.get("created_at", OffsetDateTime.class), + row.get("updated_at", OffsetDateTime.class)); + } + + private List parseAppliedEpochs(String appliedUnitsJson) { + try { + List epochs = new ArrayList<>(); + for (tools.jackson.databind.JsonNode node : JSON.readTree(appliedUnitsJson)) { + epochs.add( + new AppliedEpoch( + requiredText(node, "aggregateType"), + requiredText(node, "aggregateId"), + requiredText(node, "scopeType"), + requiredText(node, "scopeId"), + requiredText(node, "expectedEpoch"), + requiredText(node, "resultingEpoch"))); + } + if (!canonicalJson(epochs.stream().map(this::appliedEpochJson).toList()) + .equals(appliedUnitsJson)) { + throw new IllegalStateException("Persisted Draft owner epoch vector is not canonical"); + } + return List.copyOf(epochs); + } catch (RuntimeException exception) { + throw new IllegalStateException("Persisted Draft owner epoch vector is corrupt", exception); + } + } + + private Record findSlot(DraftCommitBinding.TargetProof target, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + APPLICATION_SLOT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId()); + } + + private ApplicationSlot toApplicationSlot(Record row) { + return new ApplicationSlot( + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("request_id", UUID.class), + row.get("commit_id", UUID.class), + row.get("claimed_at", OffsetDateTime.class)); + } + + private void requireActiveSlot(DraftCommitBinding binding) { + Record row = findSlot(binding.target(), true); + if (row == null) { + throw new DraftCommitStateConflictException( + "Owner dispatch requires the durable Version slot"); + } + requireSameSlot(binding, toApplicationSlot(row)); + } + + private static boolean isSameSlot(DraftCommitBinding binding, ApplicationSlot slot) { + return slot.canonicalTenantId().equals(binding.target().canonicalTenantId()) + && slot.canonicalVersionId().equals(binding.target().canonicalVersionId()) + && slot.requestId().equals(binding.requestId()) + && slot.commitId().equals(binding.commitId()); + } + + private static void requireSameSlot(DraftCommitBinding binding, ApplicationSlot slot) { + if (!isSameSlot(binding, slot)) { + throw new DraftCommitStateConflictException( + "Another exact Draft commit owns the Version application slot"); + } + } + + private VisibilityFence findVisibilityFence(DraftCommitBinding binding, boolean forUpdate) { + Record row = + dsl.fetchOne( + "SELECT input_digest, result_vector_json, created_at FROM " + + VISIBILITY_FENCE_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + return row == null + ? null + : toVisibilityFence(binding.target(), binding.requestId(), binding.commitId(), row); + } + + private Record findFinalAbort(DraftCommitBinding binding, boolean forUpdate) { + return dsl.fetchOne( + "SELECT input_digest, binding_json, abort_bytes, created_at FROM " + + FINAL_ABORT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + } + + private void requireExactFinalAbort( + DraftCommitBinding binding, byte[] expectedAbortBytes, Record row) { + if (!binding.digest().equals(row.get("input_digest", String.class)) + || !binding.canonicalJson().equals(row.get("binding_json", String.class)) + || !Arrays.equals(expectedAbortBytes, row.get("abort_bytes", byte[].class))) { + throw new DraftCommitIdentityConflictException( + "Final-abort identity was reused with changed binding or exact evidence bytes"); + } + } + + private FinalAbortReceipt toFinalAbortReceipt(DraftCommitBinding binding, Record row) { + requireExactFinalAbort(binding, row.get("abort_bytes", byte[].class), row); + return new FinalAbortReceipt( + binding, row.get("abort_bytes", byte[].class), row.get("created_at", OffsetDateTime.class)); + } + + private VisibilityFence toVisibilityFence( + DraftCommitBinding.TargetProof target, UUID requestId, UUID commitId, Record row) { + return new VisibilityFence( + target, + requestId, + commitId, + row.get("input_digest", String.class), + row.get("result_vector_json", String.class), + row.get("created_at", OffsetDateTime.class)); + } + + private String exactAppliedResultVector( + DraftCommitBinding binding, List ownerStates) { + if (ownerStates.size() != binding.requiredOwners().size()) { + throw new DraftCommitStateConflictException("Complete Draft owner result vector is required"); + } + List> resultVector = new ArrayList<>(); + for (Owner owner : binding.requiredOwners()) { + OwnerState state = + ownerStates.stream() + .filter(candidate -> candidate.owner() == owner) + .findFirst() + .orElseThrow( + () -> + new DraftCommitStateConflictException( + "Required Draft owner result is missing")); + OwnerOutcome outcome = state.outcome().orElse(null); + if (state.status() != OwnerStatus.APPLIED || outcome == null) { + throw new DraftCommitStateConflictException( + "Draft visibility cannot advance before every required owner is exactly APPLIED"); + } + requireOutcomeMatches(binding, outcome); + List expected = binding.affectedUnits(owner); + if (!hasExpectedTuples(expected, outcome.appliedEpochs())) { + throw new DraftCommitStateConflictException( + "Draft owner result does not prove the complete bound affected tuple set"); + } + resultVector.add(ownerResultJson(outcome)); + } + return canonicalJson(resultVector); + } + + private Map ownerResultJson(OwnerOutcome outcome) { + Map item = new LinkedHashMap<>(); + item.put("owner", outcome.owner().name()); + item.put("status", outcome.status().name()); + item.put("commitId", outcome.commitId().toString()); + item.put("bindingDigest", outcome.bindingDigest()); + item.put("resultIdentity", outcome.resultIdentity()); + item.put( + "resultBytesBase64", + outcome.resultBytes() == null + ? "" + : Base64.getEncoder().encodeToString(outcome.resultBytes())); + item.put( + "appliedEpochs", outcome.appliedEpochs().stream().map(this::appliedEpochJson).toList()); + return item; + } + + private Map appliedEpochJson(AppliedEpoch epoch) { + Map item = new LinkedHashMap<>(); + item.put("aggregateType", epoch.aggregateType()); + item.put("aggregateId", epoch.aggregateId()); + item.put("scopeType", epoch.scopeType()); + item.put("scopeId", epoch.scopeId()); + item.put("expectedEpoch", epoch.expectedEpoch()); + item.put("resultingEpoch", epoch.resultingEpoch()); + return item; + } + + private void requireOutcomeMatches(DraftCommitBinding binding, OwnerOutcome outcome) { + if (!binding.requiredOwners().contains(outcome.owner()) + || !binding.commitId().equals(outcome.commitId()) + || !binding.digest().equals(outcome.bindingDigest())) { + throw new DraftCommitIdentityConflictException( + "Draft owner outcome is not bound to this exact commit and full input digest"); + } + if (outcome.status() == OwnerStatus.APPLIED) { + List expected = binding.affectedUnits(outcome.owner()); + if (!hasExpectedTuples(expected, outcome.appliedEpochs())) { + throw new DraftCommitStateConflictException( + "Draft owner result omitted a declared aggregate/scope epoch tuple"); + } + for (AppliedEpoch actualEpoch : outcome.appliedEpochs()) { + if (new BigInteger(actualEpoch.resultingEpoch()) + .compareTo(new BigInteger(actualEpoch.expectedEpoch())) + <= 0) { + throw new DraftCommitStateConflictException( + "Draft owner result does not exactly advance every declared tuple"); + } + } + } else if (!outcome.appliedEpochs().isEmpty()) { + throw new DraftCommitStateConflictException( + "Only an APPLIED owner result may report advanced aggregate/scope epochs"); + } + } + + private boolean hasExpectedTuples(List expected, List actual) { + if (expected.size() != actual.size()) { + return false; + } + for (int index = 0; index < expected.size(); index++) { + if (!actual.get(index).matchesExpectedTuple(expected.get(index))) { + return false; + } + } + return true; + } + + private void requireExactBinding(DraftCommitBinding expected, DraftCommitBinding actual) { + if (!expected.digest().equals(actual.digest()) + || !Arrays.equals(expected.canonicalBytes(), actual.canonicalBytes())) { + throw new DraftCommitIdentityConflictException( + "Draft request or commit identity was reused with changed complete binding data"); + } + } + + /** + * Locks and proves one canonical Game Design Version before any Draft commit/application lock. + */ + LockedVersion lockVersionTarget(UUID canonicalTenantId, UUID canonicalVersionId) { + requireWritableReadCommittedTransaction(); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + Record row = + dsl.fetchOne( + "SELECT v.id AS version_row_id, v.tenant_id AS version_tenant_key, " + + "v.canonical_tenant_id, v.canonical_version_id, " + + "v.identity_source_game_row_id, v.identity_source_game_tenant_key, " + + "v.identity_source_provenance_kind, v.version_state, v.version_state_epoch, " + + "v.is_script_only, v.script_patch_version, v.base_version_id " + + "FROM version v JOIN game g " + + "ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id > 0 " + + "AND v.identity_source_game_tenant_key = v.tenant_id " + + "AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') " + + "FOR UPDATE OF v", + canonicalTenantId, + canonicalVersionId); + if (row == null) { + throw new DraftCommitNotFoundException( + "Exact canonical Version and immutable Game source provenance were not found"); + } + Long stateEpoch = row.get("version_state_epoch", Long.class); + if (stateEpoch == null || stateEpoch <= 0) { + throw new DraftCommitStateConflictException( + "Canonical Version lacks a positive persisted version-state epoch"); + } + TargetProof target = + new TargetProof( + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("version_row_id", Long.class), + row.get("version_tenant_key", String.class), + row.get("identity_source_game_row_id", Long.class), + row.get("identity_source_game_tenant_key", String.class), + row.get("identity_source_provenance_kind", String.class)); + return new LockedVersion( + target, + row.get("version_state", String.class), + stateEpoch, + row.get("is_script_only", Boolean.class), + row.get("script_patch_version", String.class), + row.get("base_version_id", Long.class)); + } + + private LockedVersion lockVersionTarget(TargetProof expected) { + Objects.requireNonNull(expected, "expected"); + LockedVersion locked = + lockVersionTarget(expected.canonicalTenantId(), expected.canonicalVersionId()); + if (!expected.equals(locked.target())) { + throw new DraftCommitIdentityConflictException( + "Draft binding source proof differs from its locked canonical Version"); + } + return locked; + } + + private static void requireDraftVersion(LockedVersion version) { + if (!"DRAFT".equals(version.versionState())) { + throw new DraftCommitStateConflictException( + "Owner application requires the exact Version to remain DRAFT"); + } + } + + private void requireNoPublicationSelection(TargetProof target) { + Record selection = + dsl.fetchOne( + "SELECT publish_request_id FROM " + + PUBLISH_SELECTION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (selection != null) { + throw new DraftCommitStateConflictException( + "Authored Draft publication reservation prevents later owner application"); + } + } + + private void requireWritableReadCommittedTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED).equals(isolation)) { + throw new IllegalStateException( + "Draft coordinator mutations require a caller-owned writable READ_COMMITTED transaction"); + } + } + + private static void requireTargetAndRequest( + DraftCommitBinding.TargetProof target, UUID requestId) { + requireTarget(target); + requireNonNil(requestId, "requestId"); + } + + private static void requireTarget(DraftCommitBinding.TargetProof target) { + Objects.requireNonNull(target, "target"); + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + private static OffsetDateTime now() { + return OffsetDateTime.now(ZoneOffset.UTC); + } + + private String canonicalJson(Object value) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return new String(canonical, StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Draft owner result evidence could not be canonicalized", exception); + } + } + + private static String requiredText(tools.jackson.databind.JsonNode node, String field) { + tools.jackson.databind.JsonNode value = node == null ? null : node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Persisted Draft owner epoch field is missing: " + field); + } + return value.textValue(); + } + + private record CommitRecord( + DraftCommitBinding binding, + WorkflowState workflowState, + OffsetDateTime createdAt, + OffsetDateTime updatedAt) {} + + record LockedVersion( + DraftCommitBinding.TargetProof target, + String versionState, + long versionStateEpoch, + boolean scriptOnly, + String scriptPatchVersion, + Long baseVersionId) {} + + public record PublicationEvidence(DraftCommitBinding binding, VisibilityFence visibilityFence) { + public PublicationEvidence { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(visibilityFence, "visibilityFence"); + } + } + + public enum WorkflowState { + QUEUED, + APPLYING, + RECONCILIATION_REQUIRED, + SYNCHRONIZED, + REJECTED, + FAILED_NONPUBLICATION + } + + public enum OwnerStatus { + NOT_ATTEMPTED, + IN_PROGRESS, + APPLIED, + REJECTED, + UNKNOWN + } + + public record OwnerState( + Owner owner, + OwnerStatus status, + Optional outcome, + OffsetDateTime createdAt, + OffsetDateTime updatedAt) { + public OwnerState { + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(status, "status"); + outcome = Objects.requireNonNull(outcome, "outcome"); + Objects.requireNonNull(createdAt, "createdAt"); + Objects.requireNonNull(updatedAt, "updatedAt"); + if ((status == OwnerStatus.NOT_ATTEMPTED || status == OwnerStatus.IN_PROGRESS) + != outcome.isEmpty()) { + throw new IllegalArgumentException("Draft owner status/result shape is inconsistent"); + } + if (outcome.isPresent() + && (outcome.orElseThrow().owner() != owner || outcome.orElseThrow().status() != status)) { + throw new IllegalArgumentException( + "Draft owner result identity differs from its status row"); + } + } + } + + public record CommitSnapshot( + DraftCommitBinding binding, + WorkflowState workflowState, + OffsetDateTime createdAt, + OffsetDateTime updatedAt, + Map ownerStates) { + private CommitSnapshot(CommitRecord record, List states) { + this( + record.binding(), + record.workflowState(), + record.createdAt(), + record.updatedAt(), + ownerStateMap(states)); + } + + public CommitSnapshot { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(workflowState, "workflowState"); + Objects.requireNonNull(createdAt, "createdAt"); + Objects.requireNonNull(updatedAt, "updatedAt"); + ownerStates = Map.copyOf(ownerStates); + } + + private static Map ownerStateMap(List states) { + Map result = new EnumMap<>(Owner.class); + states.forEach(state -> result.put(state.owner(), state)); + return result; + } + } + + public record ApplicationSlot( + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID requestId, + UUID commitId, + OffsetDateTime claimedAt) { + public ApplicationSlot { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(requestId, "requestId"); + requireNonNil(commitId, "commitId"); + Objects.requireNonNull(claimedAt, "claimedAt"); + } + } + + public record VisibilityFence( + DraftCommitBinding.TargetProof target, + UUID requestId, + UUID commitId, + String inputDigest, + String resultVectorJson, + OffsetDateTime createdAt) { + public VisibilityFence { + Objects.requireNonNull(target, "target"); + requireNonNil(requestId, "requestId"); + requireNonNil(commitId, "commitId"); + Objects.requireNonNull(inputDigest, "inputDigest"); + Objects.requireNonNull(resultVectorJson, "resultVectorJson"); + Objects.requireNonNull(createdAt, "createdAt"); + } + } + + /** Exact immutable producer evidence that a commit is fenced from any later GD commit. */ + public record FinalAbortReceipt( + DraftCommitBinding binding, byte[] abortBytes, OffsetDateTime createdAt) { + public FinalAbortReceipt { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(abortBytes, "abortBytes"); + if (abortBytes.length == 0) { + throw new IllegalArgumentException("Final-abort evidence bytes must not be empty"); + } + abortBytes = abortBytes.clone(); + Objects.requireNonNull(createdAt, "createdAt"); + } + + @Override + public byte[] abortBytes() { + return abortBytes.clone(); + } + } + + public record AppliedEpoch( + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch, + String resultingEpoch) { + public AppliedEpoch { + requireResultText(aggregateType, "aggregateType"); + requireResultText(aggregateId, "aggregateId"); + requireResultText(scopeType, "scopeType"); + requireResultText(scopeId, "scopeId"); + requireDecimal(expectedEpoch, "expectedEpoch"); + requireDecimal(resultingEpoch, "resultingEpoch"); + } + + private boolean matchesExpectedTuple(AffectedUnit expected) { + return aggregateType.equals(expected.aggregateType()) + && aggregateId.equals(expected.aggregateId()) + && scopeType.equals(expected.scopeType()) + && scopeId.equals(expected.scopeId()) + && expectedEpoch.equals(expected.expectedEpoch()); + } + } + + /** + * Internal handoff token for the future coordinator after every authenticated owner producer has + * been validated. Its package-private constructor deliberately leaves this storage slice unwired; + * a repository can persist a fence only when a same-package coordinator supplies the exact + * durable owner outcomes it has independently verified. + */ + public static final class CoordinatorProof { + private final DraftCommitBinding binding; + private final List outcomes; + + CoordinatorProof(DraftCommitBinding binding, List outcomes) { + this.binding = Objects.requireNonNull(binding, "binding"); + this.outcomes = List.copyOf(outcomes); + } + + private boolean matches(DraftCommitBinding candidate) { + return binding.equals(candidate); + } + + private void requireSameOutcomes(List states) { + Map verified = new EnumMap<>(Owner.class); + for (OwnerOutcome outcome : outcomes) { + if (outcome.status() != OwnerStatus.APPLIED + || verified.put(outcome.owner(), outcome) != null) { + throw new DraftCommitStateConflictException( + "Coordinator proof must contain one exact APPLIED result per required owner"); + } + } + if (!verified.keySet().equals(new HashSet<>(binding.requiredOwners()))) { + throw new DraftCommitStateConflictException( + "Coordinator proof omits or adds a required Draft owner"); + } + for (OwnerState state : states) { + OwnerOutcome outcome = verified.get(state.owner()); + if (state.status() != OwnerStatus.APPLIED + || outcome == null + || state.outcome().isEmpty() + || !state.outcome().orElseThrow().equals(outcome)) { + throw new DraftCommitStateConflictException( + "Coordinator proof differs from the exact durable owner result row"); + } + } + } + } + + /** Immutable copy of an owner's full terminal or uncertain result evidence. */ + public static final class OwnerOutcome { + private final Owner owner; + private final OwnerStatus status; + private final UUID commitId; + private final String bindingDigest; + private final String resultIdentity; + private final byte[] resultBytes; + private final List appliedEpochs; + + public OwnerOutcome( + Owner owner, + OwnerStatus status, + UUID commitId, + String bindingDigest, + String resultIdentity, + byte[] resultBytes, + List appliedEpochs) { + this.owner = Objects.requireNonNull(owner, "owner"); + this.status = Objects.requireNonNull(status, "status"); + if (status == OwnerStatus.NOT_ATTEMPTED || status == OwnerStatus.IN_PROGRESS) { + throw new IllegalArgumentException( + "OwnerOutcome must carry an observed owner result state"); + } + requireNonNil(commitId, "commitId"); + this.commitId = commitId; + this.bindingDigest = Objects.requireNonNull(bindingDigest, "bindingDigest"); + if (!bindingDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("bindingDigest must be a canonical SHA-256 digest"); + } + if ((resultIdentity == null) != (resultBytes == null)) { + throw new IllegalArgumentException( + "Owner result identity and exact result bytes must be paired"); + } + if (status == OwnerStatus.APPLIED || status == OwnerStatus.REJECTED) { + requireResultText(resultIdentity, "resultIdentity"); + } else if (resultIdentity != null) { + requireResultText(resultIdentity, "resultIdentity"); + } + this.resultIdentity = resultIdentity; + this.resultBytes = resultBytes == null ? null : resultBytes.clone(); + Objects.requireNonNull(appliedEpochs, "appliedEpochs"); + List epochCopy = new ArrayList<>(appliedEpochs); + epochCopy.sort(APPLIED_EPOCH_ORDER); + if (!epochCopy.equals(appliedEpochs)) { + throw new IllegalArgumentException("Applied owner epoch tuples must be in canonical order"); + } + if ((status == OwnerStatus.APPLIED) != !epochCopy.isEmpty()) { + throw new IllegalArgumentException("APPLIED result must contain its complete tuple vector"); + } + this.appliedEpochs = List.copyOf(epochCopy); + } + + public Owner owner() { + return owner; + } + + public OwnerStatus status() { + return status; + } + + public UUID commitId() { + return commitId; + } + + public String bindingDigest() { + return bindingDigest; + } + + public String resultIdentity() { + return resultIdentity; + } + + public byte[] resultBytes() { + return resultBytes == null ? null : resultBytes.clone(); + } + + public List appliedEpochs() { + return appliedEpochs; + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof OwnerOutcome result + && owner == result.owner + && status == result.status + && commitId.equals(result.commitId) + && bindingDigest.equals(result.bindingDigest) + && Objects.equals(resultIdentity, result.resultIdentity) + && Arrays.equals(resultBytes, result.resultBytes) + && appliedEpochs.equals(result.appliedEpochs)); + } + + @Override + public int hashCode() { + return Objects.hash( + owner, + status, + commitId, + bindingDigest, + resultIdentity, + Arrays.hashCode(resultBytes), + appliedEpochs); + } + } + + private static void requireDecimal(String value, String label) { + Objects.requireNonNull(value, label); + if (!value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal string"); + } + } + + private static void requireResultText(String value, String label) { + Objects.requireNonNull(value, label); + if (value.isBlank() || !value.equals(value.trim())) { + throw new IllegalArgumentException(label + " must be nonblank exact text"); + } + } + + public static class DraftCommitIdentityConflictException extends IllegalStateException { + public DraftCommitIdentityConflictException(String message) { + super(message); + } + + public DraftCommitIdentityConflictException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class DraftCommitStateConflictException extends IllegalStateException { + public DraftCommitStateConflictException(String message) { + super(message); + } + } + + public static final class DraftCommitNotFoundException extends IllegalStateException { + public DraftCommitNotFoundException(String message) { + super(message); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOperation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOperation.java new file mode 100644 index 0000000000..535f147e1d --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOperation.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** + * Exact Account operation material paired with the complete Game Design commit binding. + * + *

This value validates identity and canonical bytes only. It does not authenticate the Account + * source evidence or authorize a write; that decision belongs to the protected Account producer. + */ +public final class GameDesignDraftTerminalOperation { + private final DraftAuthorizationFenceBinding accountBinding; + private final DraftCommitBinding gameDesignBinding; + private final byte[] accountBindingBytes; + private final String accountBindingDigest; + + public GameDesignDraftTerminalOperation(DraftAuthorizationFenceBinding accountBinding) { + this(accountBinding, bindingFrom(accountBinding)); + } + + public GameDesignDraftTerminalOperation( + DraftAuthorizationFenceBinding accountBinding, DraftCommitBinding gameDesignBinding) { + this.accountBinding = Objects.requireNonNull(accountBinding, "accountBinding"); + this.gameDesignBinding = Objects.requireNonNull(gameDesignBinding, "gameDesignBinding"); + this.accountBindingBytes = accountBinding.canonicalBytes(); + this.accountBindingDigest = sha256(accountBindingBytes); + if (!Arrays.equals(accountBinding.gameDesignBinding(), gameDesignBinding.canonicalBytes()) + || !accountBinding.inputDigest().equals(gameDesignBinding.digest()) + || !accountBinding.requestId().equals(gameDesignBinding.requestId()) + || !accountBinding.commitId().equals(gameDesignBinding.commitId()) + || !accountBinding.tenantId().equals(gameDesignBinding.target().canonicalTenantId()) + || !accountBinding.versionId().equals(gameDesignBinding.target().canonicalVersionId()) + || !accountBinding.baseCommitId().equals(gameDesignBinding.baseCommitId())) { + throw new IllegalArgumentException( + "Account terminal operation differs from the exact complete Game Design binding"); + } + } + + public DraftAuthorizationFenceBinding accountBinding() { + return accountBinding; + } + + public DraftCommitBinding gameDesignBinding() { + return gameDesignBinding; + } + + public byte[] accountBindingBytes() { + return accountBindingBytes.clone(); + } + + public String accountBindingDigest() { + return accountBindingDigest; + } + + public boolean exactlyMatches(GameDesignDraftTerminalOperation other) { + return other != null + && accountBindingDigest.equals(other.accountBindingDigest) + && Arrays.equals(accountBindingBytes, other.accountBindingBytes) + && gameDesignBinding.digest().equals(other.gameDesignBinding.digest()) + && Arrays.equals( + gameDesignBinding.canonicalBytes(), other.gameDesignBinding.canonicalBytes()); + } + + private static DraftCommitBinding bindingFrom(DraftAuthorizationFenceBinding accountBinding) { + Objects.requireNonNull(accountBinding, "accountBinding"); + return DraftCommitBinding.fromStored( + new String(accountBinding.gameDesignBinding(), StandardCharsets.UTF_8), + accountBinding.inputDigest()); + } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcome.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcome.java new file mode 100644 index 0000000000..9e64a5488b --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcome.java @@ -0,0 +1,177 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Immutable final Game Design owner result for one exact Account operation. + * + *

A missing outcome is unresolved, never an abort. The retained owner vector is Game Design's + * internal participant evidence; it is not a substitute for Account's independent World outcome. + * This record is readback data, not an authorization decision or an authenticated RPC receipt. + */ +public final class GameDesignDraftTerminalOutcome { + private static final ObjectMapper JSON = new ObjectMapper(); + + public enum Result { + COMMITTED, + DEFINITIVELY_ABORTED + } + + private final GameDesignDraftTerminalOperation operation; + private final Result result; + private final String ownerResultVectorJson; + private final byte[] finalEvidenceBytes; + private final String finalEvidenceDigest; + private final OffsetDateTime createdAt; + + GameDesignDraftTerminalOutcome( + GameDesignDraftTerminalOperation operation, + Result result, + String ownerResultVectorJson, + byte[] finalEvidenceBytes, + String finalEvidenceDigest, + OffsetDateTime createdAt) { + this.operation = Objects.requireNonNull(operation, "operation"); + this.result = Objects.requireNonNull(result, "result"); + this.ownerResultVectorJson = + Objects.requireNonNull(ownerResultVectorJson, "ownerResultVectorJson"); + if (ownerResultVectorJson.isBlank()) { + throw new IllegalArgumentException( + "A final outcome requires its complete owner result vector"); + } + validateOwnerResultVector(); + this.finalEvidenceBytes = + Objects.requireNonNull(finalEvidenceBytes, "finalEvidenceBytes").clone(); + if (this.finalEvidenceBytes.length == 0) { + throw new IllegalArgumentException("A final outcome requires exact terminal evidence bytes"); + } + this.finalEvidenceDigest = Objects.requireNonNull(finalEvidenceDigest, "finalEvidenceDigest"); + if (!finalEvidenceDigest.matches("sha256:[0-9a-f]{64}") + || !finalEvidenceDigest.equals( + GameDesignDraftTerminalOperation.sha256(this.finalEvidenceBytes))) { + throw new IllegalArgumentException( + "Terminal evidence digest differs from exact evidence bytes"); + } + if (result == Result.COMMITTED + && !Arrays.equals( + this.finalEvidenceBytes, ownerResultVectorJson.getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Committed terminal evidence must be the exact synchronized owner result vector"); + } + this.createdAt = Objects.requireNonNull(createdAt, "createdAt"); + } + + public GameDesignDraftTerminalOperation operation() { + return operation; + } + + public Result result() { + return result; + } + + public DraftAuthorizationFenceBinding.Owner owner() { + return DraftAuthorizationFenceBinding.Owner.GAME_DESIGN; + } + + /** + * Maps this durable Game Design result to Account's existing canonical owner-readback value. This + * is only a byte-for-byte schema adapter; it does not authenticate the producer or make this + * otherwise unregistered component an authorization source. + */ + public DraftAuthorizationFenceBinding.OwnerReadback toOwnerReadback() { + DraftAuthorizationFenceBinding accountBinding = operation.accountBinding(); + return new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.valueOf(result.name()), + accountBinding.operationId(), + accountBinding.commitId(), + accountBinding.fenceId(), + accountBinding.inputDigest(), + operation.accountBindingBytes(), + finalEvidenceBytes); + } + + public String ownerResultVectorJson() { + return ownerResultVectorJson; + } + + public byte[] finalEvidenceBytes() { + return finalEvidenceBytes.clone(); + } + + public String finalEvidenceDigest() { + return finalEvidenceDigest; + } + + public OffsetDateTime createdAt() { + return createdAt; + } + + public boolean exactlyMatches(GameDesignDraftTerminalOutcome other) { + return other != null + && operation.exactlyMatches(other.operation) + && result == other.result + && ownerResultVectorJson.equals(other.ownerResultVectorJson) + && Arrays.equals(finalEvidenceBytes, other.finalEvidenceBytes) + && finalEvidenceDigest.equals(other.finalEvidenceDigest); + } + + private void validateOwnerResultVector() { + try { + byte[] vectorBytes = ownerResultVectorJson.getBytes(StandardCharsets.UTF_8); + if (!Arrays.equals( + vectorBytes, Rfc8785CanonicalJson.canonicalizeUtf8(ownerResultVectorJson))) { + throw new IllegalArgumentException("Terminal owner result vector is not canonical JSON"); + } + JsonNode vector = JSON.readTree(ownerResultVectorJson); + if (vector == null + || !vector.isArray() + || vector.size() != operation.gameDesignBinding().requiredOwners().size()) { + throw new IllegalArgumentException("Terminal owner result vector is incomplete"); + } + for (int index = 0; index < vector.size(); index++) { + JsonNode item = vector.get(index); + Owner expectedOwner = operation.gameDesignBinding().requiredOwners().get(index); + String expectedStatus = result == Result.COMMITTED ? "APPLIED" : null; + if (item == null + || !item.isObject() + || item.size() != 7 + || !text(item, "owner").equals(expectedOwner.name()) + || !text(item, "commitId").equals(operation.gameDesignBinding().commitId().toString()) + || !text(item, "bindingDigest").equals(operation.gameDesignBinding().digest()) + || (expectedStatus != null && !text(item, "status").equals(expectedStatus)) + || (result == Result.DEFINITIVELY_ABORTED + && !ListStatus.TERMINAL.contains(text(item, "status"))) + || !item.path("appliedEpochs").isArray() + || !item.path("resultBytesBase64").isTextual() + || !item.path("resultIdentity").isTextual()) { + throw new IllegalArgumentException( + "Terminal owner result vector differs from its complete commit binding"); + } + } + } catch (java.io.IOException exception) { + throw new IllegalArgumentException( + "Terminal owner result vector is not valid JSON", exception); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Terminal owner result is missing text field " + field); + } + return value.textValue(); + } + + private static final class ListStatus { + private static final java.util.Set TERMINAL = java.util.Set.of("APPLIED", "REJECTED"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java new file mode 100644 index 0000000000..d434024b79 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomeRepository.java @@ -0,0 +1,637 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Owner-local durable Account-operation claim and final Game Design outcome readback. + * + *

This class deliberately has no Spring component annotation or RPC registration. It stores + * exact source material and coordinator results only; it neither authenticates Account sources nor + * treats those results as Account's independent owner outcomes. + */ +public final class GameDesignDraftTerminalOutcomeRepository { + private static final String OPERATION_TABLE = "game_design_draft_terminal_operation"; + private static final String OUTCOME_TABLE = "game_design_draft_terminal_outcome"; + private static final String COMMIT_TABLE = "game_design_draft_commit"; + private static final String VISIBILITY_FENCE_TABLE = "game_design_draft_commit_visibility_fence"; + private static final String FINAL_ABORT_TABLE = "game_design_draft_commit_final_abort"; + + private final DSLContext dsl; + + public GameDesignDraftTerminalOutcomeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Retains the exact original Account operation before any owner dispatch. The caller must hold + * the same canonical Version row lock used by coordinator transitions. + */ + GameDesignDraftTerminalOperation claim( + GameDesignDraftTerminalOperation operation, + DraftCommitCoordinatorRepository.LockedVersion lockedVersion) { + requireWritableReadCommittedTransaction(); + validateClaim(operation, lockedVersion); + DraftCommitBinding binding = operation.gameDesignBinding(); + + Record byOperation = findOperation(operation.accountBinding().operationId(), true); + if (byOperation != null) { + GameDesignDraftTerminalOperation persisted = toOperation(byOperation); + requireExactOperation(operation, persisted); + return persisted; + } + Record byCommit = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (byCommit != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "A Game Design commit is already claimed by a different Account operation"); + } + + Record commit = + dsl.fetchOne( + "SELECT input_digest, binding_json, workflow_state FROM " + + COMMIT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ? FOR UPDATE", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (commit == null) { + throw new DraftCommitCoordinatorRepository.DraftCommitNotFoundException( + "Game Design commit must be claimed before its Account operation"); + } + DraftCommitBinding storedBinding = + DraftCommitBinding.fromStored( + commit.get("binding_json", String.class), commit.get("input_digest", String.class)); + requireExactGameDesignBinding(binding, storedBinding); + if (!"QUEUED".equals(commit.get("workflow_state", String.class))) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "Original Account operation must be retained before owner dispatch begins"); + } + if (!"DRAFT".equals(lockedVersion.versionState())) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "An Account operation can be newly claimed only while its exact Version is DRAFT"); + } + Record slot = + dsl.fetchOne( + "SELECT 1 FROM game_design_draft_commit_application_slot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + if (slot != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "An Account operation must be claimed before the Version dispatch slot is acquired"); + } + + DraftAuthorizationFenceBinding account = operation.accountBinding(); + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (operation_id, request_id, commit_id, fence_id, actor_account_id, " + + "canonical_tenant_id, canonical_version_id, base_commit_id, expected_draft_epoch, " + + "account_binding_bytes, account_binding_digest, game_design_binding_json, " + + "game_design_input_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT DO NOTHING", + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.actorAccountId(), + account.tenantId(), + account.versionId(), + account.baseCommitId(), + account.expectedDraftEpoch(), + operation.accountBindingBytes(), + operation.accountBindingDigest(), + binding.canonicalJson(), + binding.digest()); + Record persistedRow = findOperation(account.operationId(), true); + if (persistedRow == null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Account operation identity conflicts with a retained Game Design binding"); + } + GameDesignDraftTerminalOperation persisted = toOperation(persistedRow); + requireExactOperation(operation, persisted); + return persisted; + } + + /** + * Fails before the coordinator creates any row if a supplied Account binding is not claimable. + */ + void validateClaim( + GameDesignDraftTerminalOperation operation, + DraftCommitCoordinatorRepository.LockedVersion lockedVersion) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(lockedVersion, "lockedVersion"); + DraftCommitBinding binding = operation.gameDesignBinding(); + if (!binding.target().equals(lockedVersion.target())) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Account operation differs from the same-Version claim lock"); + } + + Record byOperation = findOperation(operation.accountBinding().operationId(), true); + if (byOperation != null) { + GameDesignDraftTerminalOperation persisted = toOperation(byOperation); + requireExactOperation(operation, persisted); + return; + } + Record byCommit = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (byCommit != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "A Game Design commit is already claimed by a different Account operation"); + } + Record commit = + dsl.fetchOne( + "SELECT input_digest, binding_json, workflow_state FROM " + + COMMIT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ? FOR UPDATE", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (commit != null) { + DraftCommitBinding storedBinding = + DraftCommitBinding.fromStored( + commit.get("binding_json", String.class), commit.get("input_digest", String.class)); + requireExactGameDesignBinding(binding, storedBinding); + if (!"QUEUED".equals(commit.get("workflow_state", String.class))) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "Original Account operation must be retained before owner dispatch begins"); + } + } + if (!"DRAFT".equals(lockedVersion.versionState())) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "An Account operation can be newly claimed only while its exact Version is DRAFT"); + } + Record slot = + dsl.fetchOne( + "SELECT 1 FROM game_design_draft_commit_application_slot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + if (slot != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "An Account operation must be claimed before the Version dispatch slot is acquired"); + } + } + + /** Reads the immutable operation claim, whether or not a terminal outcome exists yet. */ + Optional readOperation(UUID operationId) { + Objects.requireNonNull(operationId, "operationId"); + Record row = findOperation(operationId, false); + return row == null ? Optional.empty() : Optional.of(toOperation(row)); + } + + /** + * Reads only an explicitly persisted terminal outcome. Empty means unresolved or unclaimed; it + * never means definitively aborted. + */ + Optional read(UUID operationId) { + Objects.requireNonNull(operationId, "operationId"); + GameDesignDraftTerminalOperation operation = readOperation(operationId).orElse(null); + if (operation == null) { + return Optional.empty(); + } + Record row = findOutcome(operationId, false); + return row == null + ? Optional.empty() + : Optional.of(readAndVerifyTerminalOutcome(operation, row)); + } + + /** Exact-binding readback for Account; changed original bytes conflict instead of aliasing. */ + public Optional read(GameDesignDraftTerminalOperation expected) { + Objects.requireNonNull(expected, "expected"); + GameDesignDraftTerminalOperation persisted = + readOperation(expected.accountBinding().operationId()).orElse(null); + if (persisted == null) { + if (findOperation( + expected.gameDesignBinding().target(), + expected.gameDesignBinding().requestId(), + expected.gameDesignBinding().commitId(), + false) + != null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Game Design commit is retained under a different Account operation identity"); + } + return Optional.empty(); + } + requireExactOperation(expected, persisted); + Record row = findOutcome(expected.accountBinding().operationId(), false); + return row == null + ? Optional.empty() + : Optional.of(readAndVerifyTerminalOutcome(persisted, row)); + } + + /** + * Reconstructs only the complete binding already embedded in the original Account bytes, then + * reads its explicit immutable terminal row. Missing operation or result remains unresolved. + */ + public Optional readAccountBound( + byte[] originalAccountBindingBytes) { + requireCommittedReadBoundary(); + if (originalAccountBindingBytes == null || originalAccountBindingBytes.length == 0) { + throw new IllegalArgumentException("Complete original Account binding is required"); + } + DraftAuthorizationFenceBinding accountBinding = + DraftAuthorizationFenceBinding.fromStored(originalAccountBindingBytes.clone()); + return read(new GameDesignDraftTerminalOperation(accountBinding)); + } + + /** + * External Account readback cannot observe rows before the caller's owner transaction commits. + */ + private static void requireCommittedReadBoundary() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account-bound terminal readback requires a committed owner transaction boundary"); + } + } + + /** Records the local committed outcome in the same transaction as synchronized visibility. */ + Optional recordCommitted( + DraftCommitBinding binding, + DraftCommitCoordinatorRepository.VisibilityFence visibilityFence, + String exactOwnerResultVectorJson, + boolean allowInsert) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(visibilityFence, "visibilityFence"); + Objects.requireNonNull(exactOwnerResultVectorJson, "exactOwnerResultVectorJson"); + Record operationRow = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (operationRow == null) { + return Optional.empty(); + } + GameDesignDraftTerminalOperation operation = toOperation(operationRow); + requireExactGameDesignBinding(binding, operation.gameDesignBinding()); + if (!visibilityFence.target().equals(binding.target()) + || !visibilityFence.requestId().equals(binding.requestId()) + || !visibilityFence.commitId().equals(binding.commitId()) + || !visibilityFence.inputDigest().equals(binding.digest()) + || !visibilityFence.resultVectorJson().equals(exactOwnerResultVectorJson)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Committed terminal evidence differs from the exact synchronized visibility fence"); + } + byte[] evidence = exactOwnerResultVectorJson.getBytes(StandardCharsets.UTF_8); + if (!allowInsert) { + return Optional.of( + requireExistingOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.COMMITTED, + exactOwnerResultVectorJson, + evidence)); + } + return Optional.of( + insertOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.COMMITTED, + exactOwnerResultVectorJson, + evidence)); + } + + /** Records the local no-commit outcome beside the exact abort tombstone and owner vector. */ + Optional recordAborted( + DraftCommitBinding binding, + DraftCommitCoordinatorRepository.FinalAbortReceipt abortReceipt, + String exactOwnerResultVectorJson, + boolean allowInsert) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(abortReceipt, "abortReceipt"); + Objects.requireNonNull(exactOwnerResultVectorJson, "exactOwnerResultVectorJson"); + Record operationRow = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (operationRow == null) { + return Optional.empty(); + } + GameDesignDraftTerminalOperation operation = toOperation(operationRow); + requireExactGameDesignBinding(binding, operation.gameDesignBinding()); + requireExactGameDesignBinding(binding, abortReceipt.binding()); + if (!allowInsert) { + return Optional.of( + requireExistingOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED, + exactOwnerResultVectorJson, + abortReceipt.abortBytes())); + } + return Optional.of( + insertOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED, + exactOwnerResultVectorJson, + abortReceipt.abortBytes())); + } + + /** Prevents a late coordinator transition from mutating a definitively aborted operation. */ + void requireNotDefinitivelyAborted(DraftCommitBinding binding) { + Record operation = + findOperation(binding.target(), binding.requestId(), binding.commitId(), true); + if (operation == null) { + return; + } + Record outcome = findOutcome(operation.get("operation_id", UUID.class), true); + if (outcome != null + && GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED + .name() + .equals(outcome.get("outcome", String.class))) { + throw new DraftCommitCoordinatorRepository.DraftCommitStateConflictException( + "A definitively aborted Account-bound Draft operation cannot accept a late writer"); + } + } + + boolean isAccountBound(DraftCommitBinding binding) { + return findOperation(binding.target(), binding.requestId(), binding.commitId(), false) != null; + } + + private GameDesignDraftTerminalOutcome insertOutcome( + GameDesignDraftTerminalOperation operation, + GameDesignDraftTerminalOutcome.Result result, + String ownerResultVectorJson, + byte[] finalEvidenceBytes) { + UUID operationId = operation.accountBinding().operationId(); + Record existing = findOutcome(operationId, true); + String evidenceDigest = GameDesignDraftTerminalOperation.sha256(finalEvidenceBytes); + if (existing != null) { + GameDesignDraftTerminalOutcome retained = toOutcome(operation, existing); + GameDesignDraftTerminalOutcome candidate = + new GameDesignDraftTerminalOutcome( + operation, + result, + ownerResultVectorJson, + finalEvidenceBytes, + evidenceDigest, + retained.createdAt()); + if (!retained.exactlyMatches(candidate)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Game Design terminal outcome identity was reused with changed final evidence"); + } + return retained; + } + + int inserted = + dsl.execute( + "INSERT INTO " + + OUTCOME_TABLE + + " (operation_id, outcome, owner_result_vector_json, terminal_evidence_bytes, " + + "terminal_evidence_digest) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + operationId, + result.name(), + ownerResultVectorJson, + finalEvidenceBytes.clone(), + evidenceDigest); + Record persisted = findOutcome(operationId, true); + if (persisted == null) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Concurrent Game Design terminal result conflicts with another operation identity"); + } + GameDesignDraftTerminalOutcome retained = toOutcome(operation, persisted); + GameDesignDraftTerminalOutcome candidate = + new GameDesignDraftTerminalOutcome( + operation, + result, + ownerResultVectorJson, + finalEvidenceBytes, + evidenceDigest, + retained.createdAt()); + if (!retained.exactlyMatches(candidate)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Concurrent Game Design terminal result retained different final evidence"); + } + if (inserted == 0) { + return retained; + } + return retained; + } + + private GameDesignDraftTerminalOutcome requireExistingOutcome( + GameDesignDraftTerminalOperation operation, + GameDesignDraftTerminalOutcome.Result expectedResult, + String ownerResultVectorJson, + byte[] finalEvidenceBytes) { + UUID operationId = operation.accountBinding().operationId(); + Record existing = findOutcome(operationId, true); + if (existing == null) { + throw new IllegalStateException( + "A retained Game Design terminal fence lacks its atomic Account-bound outcome row"); + } + GameDesignDraftTerminalOutcome retained = toOutcome(operation, existing); + GameDesignDraftTerminalOutcome expected = + new GameDesignDraftTerminalOutcome( + operation, + expectedResult, + ownerResultVectorJson, + finalEvidenceBytes, + GameDesignDraftTerminalOperation.sha256(finalEvidenceBytes), + retained.createdAt()); + if (!retained.exactlyMatches(expected)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Game Design terminal readback differs from its retained final fence"); + } + return retained; + } + + private Record findOperation(UUID operationId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + OPERATION_TABLE + + " WHERE operation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + operationId); + } + + private Record findOperation( + DraftCommitBinding.TargetProof target, UUID requestId, UUID commitId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + OPERATION_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId, + commitId); + } + + private Record findOutcome(UUID operationId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + OUTCOME_TABLE + + " WHERE operation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + operationId); + } + + private GameDesignDraftTerminalOperation toOperation(Record row) { + byte[] accountBytes = row.get("account_binding_bytes", byte[].class); + String accountDigest = row.get("account_binding_digest", String.class); + DraftAuthorizationFenceBinding account; + try { + account = DraftAuthorizationFenceBinding.fromStored(accountBytes); + } catch (RuntimeException exception) { + throw new IllegalStateException("Persisted Account Draft binding is corrupt", exception); + } + if (!GameDesignDraftTerminalOperation.sha256(accountBytes).equals(accountDigest) + || !account.operationId().equals(row.get("operation_id", UUID.class)) + || !account.requestId().equals(row.get("request_id", UUID.class)) + || !account.commitId().equals(row.get("commit_id", UUID.class)) + || !account.fenceId().equals(row.get("fence_id", UUID.class)) + || !account.actorAccountId().equals(row.get("actor_account_id", UUID.class)) + || !account.tenantId().equals(row.get("canonical_tenant_id", UUID.class)) + || !account.versionId().equals(row.get("canonical_version_id", UUID.class)) + || !account.baseCommitId().equals(row.get("base_commit_id", String.class)) + || !account.expectedDraftEpoch().equals(row.get("expected_draft_epoch", String.class))) { + throw new IllegalStateException( + "Stored Account Draft binding differs from its indexed identity"); + } + DraftCommitBinding gameDesignBinding = + DraftCommitBinding.fromStored( + row.get("game_design_binding_json", String.class), + row.get("game_design_input_digest", String.class)); + GameDesignDraftTerminalOperation operation = + new GameDesignDraftTerminalOperation(account, gameDesignBinding); + if (!Arrays.equals(accountBytes, operation.accountBindingBytes())) { + throw new IllegalStateException("Persisted Account Draft binding is not canonical"); + } + return operation; + } + + private GameDesignDraftTerminalOutcome toOutcome( + GameDesignDraftTerminalOperation operation, Record row) { + byte[] evidence = row.get("terminal_evidence_bytes", byte[].class); + String evidenceDigest = row.get("terminal_evidence_digest", String.class); + if (!GameDesignDraftTerminalOperation.sha256(evidence).equals(evidenceDigest)) { + throw new IllegalStateException("Persisted terminal evidence digest differs from its bytes"); + } + return new GameDesignDraftTerminalOutcome( + operation, + GameDesignDraftTerminalOutcome.Result.valueOf(row.get("outcome", String.class)), + row.get("owner_result_vector_json", String.class), + evidence, + evidenceDigest, + row.get("created_at", OffsetDateTime.class)); + } + + /** + * Confirms that a returned status row still has its exact durable coordinator terminal fence; + * workflow status alone is never treated as a participant result. + */ + private GameDesignDraftTerminalOutcome readAndVerifyTerminalOutcome( + GameDesignDraftTerminalOperation operation, Record outcomeRow) { + GameDesignDraftTerminalOutcome outcome = toOutcome(operation, outcomeRow); + DraftCommitBinding binding = operation.gameDesignBinding(); + Record commit = + dsl.fetchOne( + "SELECT workflow_state, input_digest, binding_json FROM " + + COMMIT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (commit == null + || !binding.digest().equals(commit.get("input_digest", String.class)) + || !binding.canonicalJson().equals(commit.get("binding_json", String.class))) { + throw new IllegalStateException( + "Game Design terminal outcome lacks its exact retained coordinator commit"); + } + + if (outcome.result() == GameDesignDraftTerminalOutcome.Result.COMMITTED) { + Record fence = + dsl.fetchOne( + "SELECT input_digest, result_vector_json FROM " + + VISIBILITY_FENCE_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (!"SYNCHRONIZED".equals(commit.get("workflow_state", String.class)) + || fence == null + || !binding.digest().equals(fence.get("input_digest", String.class)) + || !outcome.ownerResultVectorJson().equals(fence.get("result_vector_json", String.class)) + || !Arrays.equals( + outcome.finalEvidenceBytes(), + outcome.ownerResultVectorJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalStateException( + "Committed Game Design terminal outcome lacks its exact synchronized visibility fence"); + } + return outcome; + } + + Record abort = + dsl.fetchOne( + "SELECT input_digest, binding_json, abort_bytes FROM " + + FINAL_ABORT_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + Record fence = + dsl.fetchOne( + "SELECT 1 FROM " + + VISIBILITY_FENCE_TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (!"FAILED_NONPUBLICATION".equals(commit.get("workflow_state", String.class)) + || abort == null + || !binding.digest().equals(abort.get("input_digest", String.class)) + || !binding.canonicalJson().equals(abort.get("binding_json", String.class)) + || !Arrays.equals(outcome.finalEvidenceBytes(), abort.get("abort_bytes", byte[].class)) + || fence != null) { + throw new IllegalStateException( + "Aborted Game Design terminal outcome lacks its exact final-abort tombstone"); + } + return outcome; + } + + private void requireExactOperation( + GameDesignDraftTerminalOperation expected, GameDesignDraftTerminalOperation actual) { + if (!expected.exactlyMatches(actual)) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Account operation identity was reused with changed original canonical bytes"); + } + } + + private void requireExactGameDesignBinding( + DraftCommitBinding expected, DraftCommitBinding actual) { + if (!expected.digest().equals(actual.digest()) + || !Arrays.equals(expected.canonicalBytes(), actual.canonicalBytes())) { + throw new DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException( + "Terminal operation differs from its complete canonical Game Design binding"); + } + } + + private void requireWritableReadCommittedTransaction() { + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED).equals(isolation)) { + throw new IllegalStateException( + "Game Design terminal mutations require a caller-owned writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalReadGrpcService.java new file mode 100644 index 0000000000..e48d22b4bb --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalReadGrpcService.java @@ -0,0 +1,126 @@ +package net.firedevops.firemud.gamedesign.draft; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.GameDesignDraftTerminalReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignDraftTerminalOutcomeRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignDraftTerminalOutcomeResponse; +import org.springframework.dao.DataAccessException; + +/** + * Standalone authenticated read-only adapter for exact Game Design Draft terminal evidence. + * Authentication is checked before decoding the original Account binding or reading owner storage. + * This type is deliberately not registered as a runtime gRPC service in this slice. + */ +public final class GameDesignDraftTerminalReadGrpcService + extends GameDesignDraftTerminalReadServiceGrpc.GameDesignDraftTerminalReadServiceImplBase { + private final GameDesignDraftTerminalOutcomeRepository repository; + private final String trustedNamespace; + + public GameDesignDraftTerminalReadGrpcService( + GameDesignDraftTerminalOutcomeRepository repository, String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Game Design workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readGameDesignDraftTerminalOutcome( + ReadGameDesignDraftTerminalOutcomeRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedAccountPeer(responseObserver)) { + return; + } + + final GameDesignDraftTerminalReadEvidence.Request readRequest; + try { + readRequest = GameDesignDraftTerminalReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalidRequest) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical Game Design terminal read request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Game Design terminal read namespace must match the authenticated peer") + .asRuntimeException()); + return; + } + + final Optional outcome; + try { + outcome = repository.readAccountBound(readRequest.originalAccountBinding()); + } catch (DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException conflict) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription( + "Game Design terminal identity conflicts with retained owner evidence") + .asRuntimeException()); + return; + } catch (DataAccessException | org.jooq.exception.DataAccessException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Game Design terminal storage could not complete the read") + .asRuntimeException()); + return; + } catch (IllegalArgumentException invalidBinding) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical original Account binding is required") + .asRuntimeException()); + return; + } catch (IllegalStateException inconsistentEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Game Design terminal evidence is inconsistent") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Game Design terminal readback failed") + .asRuntimeException()); + return; + } + + Optional ownerReadback = + outcome.map(GameDesignDraftTerminalOutcome::toOwnerReadback); + final ReadGameDesignDraftTerminalOutcomeResponse response; + try { + response = GameDesignDraftTerminalReadGrpcCodec.toResponse(readRequest, ownerReadback); + } catch (IllegalArgumentException invalidEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Game Design terminal readback is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean requireAuthenticatedAccountPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expectedPeer = "spiffe://firemud/ns/" + trustedNamespace + "/sa/account-service"; + if (peer != null && expectedPeer.equals(peer.uri())) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace Account workload is required") + .asRuntimeException()); + return false; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java new file mode 100644 index 0000000000..e012bac30e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.gamedesign.dto; + +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; + +/** The closed descriptor and its independently validated full release attestation. */ +public record CompleteLaunchBindingDto( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation) { + public CompleteLaunchBindingDto { + Objects.requireNonNull(descriptor, "descriptor").requireValid(); + Objects.requireNonNull(releaseAttestation, "releaseAttestation").requireValid(descriptor); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java index 8a4f73b3ba..5b44c7f491 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishParticipantDigestDto.java @@ -7,8 +7,30 @@ public record PublishParticipantDigestDto( String appliedCommitId, String contentDigest, Integer digestSchemaVersion, + String abilitySchemaDigest, String errorCode, String errorMessage) { + public PublishParticipantDigestDto( + String participantKey, + String scopeValue, + Long baseVersionId, + String appliedCommitId, + String contentDigest, + Integer digestSchemaVersion, + String errorCode, + String errorMessage) { + this( + participantKey, + scopeValue, + baseVersionId, + appliedCommitId, + contentDigest, + digestSchemaVersion, + null, + errorCode, + errorMessage); + } + /** * Preserve the full-version construction shape while the typed patch scope is introduced. * Full-version digests have no base version and therefore keep this field null. @@ -28,6 +50,7 @@ public PublishParticipantDigestDto( appliedCommitId, contentDigest, digestSchemaVersion, + null, errorCode, errorMessage); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java index a510179f25..e694d7fba7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java @@ -2,6 +2,9 @@ import java.time.LocalDateTime; import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; public record PublishedReleaseBundleDto( Long id, @@ -17,12 +20,151 @@ public record PublishedReleaseBundleDto( String generationConfigRevision, boolean scriptOnly, String scriptPatchVersion, - LocalDateTime publishedAt) { + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests, + WorldPublishedStartLocationEvidence worldPublishedStartLocationEvidence) { public PublishedReleaseBundleDto { requiredManifestAssetKeys = List.copyOf(requiredManifestAssetKeys == null ? List.of() : requiredManifestAssetKeys); participantDigests = List.copyOf(participantDigests == null ? List.of() : participantDigests); commandDefinitions = List.copyOf(commandDefinitions == null ? List.of() : commandDefinitions); + if ((manifestSchemaVersion == null) != (artifactDigests == null)) { + throw new IllegalArgumentException( + "Manifest schema and artifact proof must be present together"); + } + artifactDigests = artifactDigests == null ? null : List.copyOf(artifactDigests); + if ("v2".equals(attestationSchemaVersion) != (worldPublishedStartLocationEvidence != null)) { + throw new IllegalArgumentException( + "Selector evidence requires bundle v2 and is mandatory for v2"); + } + } + + /** Original retained bundle construction shape; cannot construct a selector-bearing v2 bundle. */ + public PublishedReleaseBundleDto( + Long id, + String tenantId, + Long versionId, + int versionNumber, + String attestationSchemaVersion, + String publishWorkflowId, + String manifestHash, + List requiredManifestAssetKeys, + List participantDigests, + List commandDefinitions, + String generationConfigRevision, + boolean scriptOnly, + String scriptPatchVersion, + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests) { + this( + id, + tenantId, + versionId, + versionNumber, + attestationSchemaVersion, + publishWorkflowId, + manifestHash, + requiredManifestAssetKeys, + participantDigests, + commandDefinitions, + generationConfigRevision, + scriptOnly, + scriptPatchVersion, + publishedAt, + canonicalTenantId, + canonicalVersionId, + publishedReleaseBundleRef, + manifestSchemaVersion, + artifactDigests, + null); + } + + public PublishedReleaseBundleDto( + Long id, + String tenantId, + Long versionId, + int versionNumber, + String attestationSchemaVersion, + String publishWorkflowId, + String manifestHash, + List requiredManifestAssetKeys, + List participantDigests, + String generationConfigRevision, + boolean scriptOnly, + String scriptPatchVersion, + LocalDateTime publishedAt, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publishedReleaseBundleRef, + Integer manifestSchemaVersion, + List artifactDigests) { + this( + id, + tenantId, + versionId, + versionNumber, + attestationSchemaVersion, + publishWorkflowId, + manifestHash, + requiredManifestAssetKeys, + participantDigests, + List.of(), + generationConfigRevision, + scriptOnly, + scriptPatchVersion, + publishedAt, + canonicalTenantId, + canonicalVersionId, + publishedReleaseBundleRef, + manifestSchemaVersion, + artifactDigests); + } + + /** Retained rows may lack canonical identity; this shape grants no launch authority. */ + public PublishedReleaseBundleDto( + Long id, + String tenantId, + Long versionId, + int versionNumber, + String attestationSchemaVersion, + String publishWorkflowId, + String manifestHash, + List requiredManifestAssetKeys, + List participantDigests, + List commandDefinitions, + String generationConfigRevision, + boolean scriptOnly, + String scriptPatchVersion, + LocalDateTime publishedAt) { + this( + id, + tenantId, + versionId, + versionNumber, + attestationSchemaVersion, + publishWorkflowId, + manifestHash, + requiredManifestAssetKeys, + participantDigests, + commandDefinitions, + generationConfigRevision, + scriptOnly, + scriptPatchVersion, + publishedAt, + null, + null, + null, + null, + null, + null); } public PublishedReleaseBundleDto( @@ -53,6 +195,12 @@ public PublishedReleaseBundleDto( generationConfigRevision, scriptOnly, scriptPatchVersion, - publishedAt); + publishedAt, + null, + null, + null, + null, + null, + null); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java index 251dc5129e..363db4bd74 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.gamedesign.dto; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; + public record ResolvedLaunchDescriptorDto( String launchDescriptorId, - String tenantId, + String canonicalTenantId, long gameTemplateId, String controlPlaneRequestId, long versionId, @@ -12,31 +14,5 @@ public record ResolvedLaunchDescriptorDto( long versionStateEpoch, long releaseBundleId, String publishedReleaseBundleRef, - String remapSetId) { - public ResolvedLaunchDescriptorDto( - String launchDescriptorId, - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - long versionId, - String scriptPatchVersion, - String runtimeFlagsJson, - String generationConfigRevision, - long versionStateEpoch, - long releaseBundleId, - String publishedReleaseBundleRef) { - this( - launchDescriptorId, - tenantId, - gameTemplateId, - controlPlaneRequestId, - versionId, - scriptPatchVersion, - runtimeFlagsJson, - generationConfigRevision, - versionStateEpoch, - releaseBundleId, - publishedReleaseBundleRef, - null); - } -} + String remapSetId, + AuthoredWorldLaunchDescriptorEvidence authoredWorldBinding) {} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java index 357d46c8e8..2626699e67 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java @@ -5,6 +5,9 @@ @Data public class LaunchDescriptor { + public static final String OUTCOME_SUCCESS = "SUCCESS"; + public static final String OUTCOME_FAILED = "FAILED"; + private Long id; private String launchDescriptorId; private String tenantId; @@ -19,5 +22,18 @@ public class LaunchDescriptor { private Long releaseBundleId; private String publishedReleaseBundleRef; private String remapSetId; + private Integer descriptorSchemaVersion; + private String targetNamespace; + private String canonicalTenantId; + private String worldSlug; + private String authoredWorldSourceOperationId; + private String authoredWorldSourceEvidenceDigest; + private String requestDigest; + private String resultDigest; + private String originalRequestJson; + private String sourceEvidenceJson; + private String outcomeStatus = OUTCOME_SUCCESS; + private String failureCode; + private String failureMessage; private LocalDateTime createdAt = LocalDateTime.now(); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java index 9fd7a4f5ed..83853a7800 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishedReleaseBundle.java @@ -1,21 +1,28 @@ package net.firedevops.firemud.gamedesign.entity; import java.time.LocalDateTime; +import java.util.UUID; import lombok.Data; @Data public class PublishedReleaseBundle { private Long id; + private String publishedReleaseBundleRef; private String tenantId; private Long versionId; + private UUID canonicalTenantId; + private UUID canonicalVersionId; private int versionNumber; private String attestationSchemaVersion; private String publishWorkflowId; private String manifestHash; + private Integer manifestSchemaVersion; + private String artifactDigestsJson; private String generationConfigRevision; private String requiredManifestAssetKeysJson; private String participantDigestsJson = "[]"; private String commandDefinitionsJson = "[]"; + private String worldPublishedStartLocationEvidenceJson; private boolean scriptOnly; private String scriptPatchVersion; private LocalDateTime publishedAt = LocalDateTime.now(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java index 9be9dded8b..760243d04c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/Version.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.entity; import java.time.LocalDateTime; +import java.util.UUID; import lombok.Data; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; @@ -8,6 +9,11 @@ public class Version { private Long id; private String tenantId; + private UUID canonicalVersionId; + private UUID canonicalTenantId; + private Long identitySourceGameRowId; + private String identitySourceGameTenantKey; + private String identitySourceProvenanceKind; private int versionNumber; private VersionLifecycleState versionState = VersionLifecycleState.DRAFT; private Long versionStateEpoch = 1L; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java index 0d026b3526..90ad7a65a2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/VersionAssetArtifact.java @@ -17,5 +17,9 @@ public class VersionAssetArtifact { private String lastErrorCode; private String lastErrorMessage; private String exportedManifestAssetKeysJson = "[]"; + private Integer manifestSchemaVersion; + private String artifactDigestsJson; + private String publishedObjectProofsJson; + private Long candidateSnapshotVersionId; private LocalDateTime updatedAt = LocalDateTime.now(); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java new file mode 100644 index 0000000000..65f7993ee8 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; + +/** Exact staged command-source application evidence, separate from the combined owner outcome. */ +public record CommandApplication( + DraftCommitBinding binding, + UUID inheritedCommitId, + String expectedEpoch, + List mutations, + CommandSnapshot snapshot) { + public CommandApplication { + Objects.requireNonNull(binding, "binding"); + if (inheritedCommitId != null && new UUID(0, 0).equals(inheritedCommitId)) { + throw new IllegalArgumentException("inheritedCommitId must be non-nil when present"); + } + requireCounter(expectedEpoch); + mutations = List.copyOf(Objects.requireNonNull(mutations, "mutations")); + if (mutations.isEmpty()) { + throw new IllegalArgumentException( + "Command application must contain explicit command mutations"); + } + if (!CommandSource.mutationsFromStored(CommandSource.mutationsJson(mutations)) + .equals(mutations)) { + throw new IllegalArgumentException( + "Command application mutations must retain canonical revision order"); + } + Objects.requireNonNull(snapshot, "snapshot"); + if (!binding.equals(snapshot.binding()) + || !Objects.equals(inheritedCommitId, snapshot.inheritedCommitId()) + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch()) + || mutations.stream() + .anyMatch(mutation -> !binding.commitId().equals(mutation.commitId()))) { + throw new IllegalArgumentException( + "Command application evidence differs from its exact binding"); + } + List commandScopes = + binding.affectedUnits(DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(CommandApplication::isCommandScope) + .toList(); + if (commandScopes.size() != 1 + || !expectedEpoch.equals(commandScopes.getFirst().expectedEpoch())) { + throw new IllegalArgumentException("Exact command source scope and epoch are required"); + } + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, CommandSource.APPLICATION_SCHEMA); + DraftAuthorizationFenceBinding.frame( + out, + inheritedCommitId == null + ? new byte[0] + : inheritedCommitId.toString().getBytes(StandardCharsets.UTF_8)); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, CommandSource.mutationsJson(mutations)); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public String resultIdentity() { + return "command-source:" + binding.commitId() + ":" + CommandSource.sha256(canonicalBytes()); + } + + public AppliedEpoch commandAppliedEpoch() { + return new AppliedEpoch( + CommandSource.SCOPE, + binding.target().canonicalVersionId().toString(), + CommandSource.SCOPE, + CommandSource.SCOPE_ID, + expectedEpoch, + snapshot.sourceEpoch()); + } + + private static boolean isCommandScope(DraftCommitBinding.AffectedUnit unit) { + return CommandSource.SCOPE.equals(unit.aggregateType()) + && CommandSource.SCOPE.equals(unit.scopeType()) + && CommandSource.SCOPE_ID.equals(unit.scopeId()); + } + + private static void requireCounter(String value) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("expectedEpoch must be a canonical nonnegative decimal"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java new file mode 100644 index 0000000000..a4085e12d4 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Complete effective command set captured at one actual synchronized Draft commit. */ +public record CommandSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + String genesisReceiptDigest, + List definitions) { + public CommandSnapshot { + Objects.requireNonNull(binding, "binding"); + requireCounter(sourceEpoch, "sourceEpoch"); + if (inheritedCommitId != null && new UUID(0, 0).equals(inheritedCommitId)) { + throw new IllegalArgumentException("inheritedCommitId must be non-nil when present"); + } + if (genesisReceiptDigest == null || !genesisReceiptDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Exact command source genesis receipt digest required"); + } + definitions = List.copyOf(Objects.requireNonNull(definitions, "definitions")); + CommandSource.requireCanonicalDefinitions(definitions); + } + + @Override + public List definitions() { + return List.copyOf(definitions); + } + + public String canonicalJson() { + return CommandSource.canonical( + Map.of( + "schema", + CommandSource.SNAPSHOT_SCHEMA, + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptDigest", + genesisReceiptDigest, + "definitions", + CommandSource.tree(CommandSource.definitionsJson(definitions)))); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static CommandSnapshot fromStored(String json) { + var root = CommandSource.tree(json); + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptDigest", + "definitions"); + if (!CommandSource.SNAPSHOT_SCHEMA.equals(CommandSource.requiredStoredText(root, "schema"))) { + throw new IllegalArgumentException("Unsupported command source snapshot schema"); + } + var inheritedNode = root.get("inheritedCommitId"); + if (inheritedNode == null || !inheritedNode.isTextual()) { + throw new IllegalArgumentException("Stored command source inheritedCommitId must be text"); + } + String inherited = inheritedNode.textValue(); + UUID inheritedCommitId = inherited.isEmpty() ? null : UUID.fromString(inherited); + if (inheritedCommitId != null && !inheritedCommitId.toString().equals(inherited)) { + throw new IllegalArgumentException( + "Stored command source inheritedCommitId must be a canonical UUID"); + } + var result = + new CommandSnapshot( + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(root, "bindingJson"), + CommandSource.requiredStoredText(root, "bindingDigest")), + CommandSource.requiredStoredText(root, "sourceEpoch"), + inheritedCommitId, + CommandSource.requiredStoredText(root, "genesisReceiptDigest"), + CommandSource.definitionsFromStored(root.get("definitions").toString())); + if (!result.canonicalJson().equals(json)) { + throw new IllegalArgumentException( + "Stored command source snapshot is not exact canonical JSON"); + } + return result; + } + + /** Frozen source paired with the actual operation bytes and selected synchronized snapshot. */ + public record Capture(GameDesignPublicationOperation operation, CommandSnapshot snapshot) { + public Capture { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(snapshot, "snapshot"); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) { + throw new IllegalArgumentException( + "Frozen command source differs from the exact selected synchronized commit"); + } + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, "game-design-command-source-capture/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, operation.canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + } + + private static void requireCounter(String value, String name) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(name + " must be a canonical nonnegative decimal"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java new file mode 100644 index 0000000000..40a0d14213 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java @@ -0,0 +1,645 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.command.CommandEffectDeclarationConstraints; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Typed complete effective source for Game Design's authored command definitions. */ +public final class CommandSource { + public static final String SCOPE = "COMMAND_DEFINITION_SET"; + public static final String SCOPE_ID = "effective"; + public static final String SNAPSHOT_SCHEMA = "game-design-command-source-snapshot/v1"; + public static final String APPLICATION_SCHEMA = "game-design-command-source-application/v1"; + public static final String REALM_POLICY_REVISION_KIND = "REALM_ENTRY_POLICY"; + + private static final String REVISION_KIND = "COMMAND_DEFINITION"; + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0, 0); + private static final ObjectMapper JSON = new ObjectMapper(); + + private CommandSource() {} + + public enum OperationKind { + UPSERT, + DELETE + } + + /** One exact authored command definition with its creating revision and commit provenance. */ + public record Definition( + String commandId, + String definitionJson, + UUID sourceCommitId, + UUID sourceRevisionId, + String revisionOrder) { + public Definition { + requireText(commandId, "commandId"); + Objects.requireNonNull(definitionJson, "definitionJson"); + requireNonNil(sourceCommitId, "sourceCommitId"); + requireNonNil(sourceRevisionId, "sourceRevisionId"); + requireCounter(revisionOrder, "revisionOrder"); + validateCommandDefinition(definitionJson); + if (!commandId.equals(commandIdFrom(definitionJson))) { + throw new IllegalArgumentException("Command source key differs from the exact definition"); + } + } + + public String stableKey() { + return normalizeToken(commandId); + } + } + + /** One explicit command mutation. DELETE retains identity and source revision provenance. */ + public record Mutation( + String revisionOrder, + UUID revisionId, + UUID commitId, + OperationKind operation, + String commandId, + String definitionJson) { + public Mutation { + requireCounter(revisionOrder, "revisionOrder"); + requireNonNil(revisionId, "revisionId"); + requireNonNil(commitId, "commitId"); + Objects.requireNonNull(operation, "operation"); + requireText(commandId, "commandId"); + if ((operation == OperationKind.UPSERT) != (definitionJson != null)) { + throw new IllegalArgumentException("Command mutation definition presence is invalid"); + } + if (definitionJson != null) { + validateCommandDefinition(definitionJson); + if (!commandId.equals(commandIdFrom(definitionJson))) { + throw new IllegalArgumentException("Upsert identity differs from its command definition"); + } + } + } + + public String stableKey() { + return normalizeToken(commandId); + } + + public Map canonicalObject() { + Map value = new LinkedHashMap<>(); + value.put("revisionOrder", revisionOrder); + value.put("revisionId", revisionId.toString()); + value.put("commitId", commitId.toString()); + value.put("operation", operation.name()); + value.put("commandId", commandId); + if (definitionJson != null) value.put("definitionJson", definitionJson); + return value; + } + } + + /** Exact receipt supplied only by the owner path that inserted a genuinely new Draft Version. */ + public record NewDraftGenesisReceipt( + DraftCommitBinding.TargetProof target, UUID receiptId, String creationTransactionId) { + public NewDraftGenesisReceipt { + Objects.requireNonNull(target, "target"); + requireNonNil(receiptId, "receiptId"); + if (creationTransactionId == null || !creationTransactionId.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "Exact Version insertion transaction identity is required"); + } + } + + public String targetProofJson() { + return canonical(targetObject(target)); + } + + public byte[] canonicalBytes() { + return canonical( + Map.of( + "schema", + "game-design-command-source-new-draft-genesis/v1", + "targetProof", + tree(targetProofJson()), + "receiptId", + receiptId.toString(), + "creationTransactionId", + creationTransactionId)) + .getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return sha256(canonicalBytes()); + } + } + + /** + * Converts the closed Draft owner payloads to command mutations. Realm policy payloads are a + * separate Game Design owner scope and are deliberately left for their own source writer. Unknown + * kinds deny rather than being guessed from omitted or legacy rows. + */ + public static List mutations(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + List mutations = new ArrayList<>(); + for (DraftCommitBinding.RevisionPayload revision : binding.revisions()) { + if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; + JsonNode payload = tree(revision.payload()); + if (!payload.isObject() || !payload.path("revisionKind").isTextual()) { + throw new IllegalArgumentException("Closed Game Design owner revision kind is required"); + } + String revisionKind = payload.path("revisionKind").asText(); + if (REALM_POLICY_REVISION_KIND.equals(revisionKind)) continue; + if (!REVISION_KIND.equals(revisionKind)) { + throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); + } + if (!payload.path("schemaVersion").isInt() + || payload.path("schemaVersion").asInt() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported command source operation schema"); + } + String operation = requiredText(payload, "operation"); + if ("UPSERT".equals(operation)) { + fields(payload, "schemaVersion", "revisionKind", "operation", "definitionJson"); + String definitionJson = requiredText(payload, "definitionJson"); + mutations.add( + new Mutation( + revision.revisionOrder(), + revision.revisionId(), + binding.commitId(), + OperationKind.UPSERT, + commandIdFrom(definitionJson), + definitionJson)); + } else if ("DELETE".equals(operation)) { + fields(payload, "schemaVersion", "revisionKind", "operation", "commandId"); + mutations.add( + new Mutation( + revision.revisionOrder(), + revision.revisionId(), + binding.commitId(), + OperationKind.DELETE, + requiredText(payload, "commandId"), + null)); + } else { + throw new IllegalArgumentException("Unsupported command source operation"); + } + } + return List.copyOf(mutations); + } + + public static boolean hasRealmPolicyRevision(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + boolean found = false; + for (DraftCommitBinding.RevisionPayload revision : binding.revisions()) { + if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; + JsonNode payload = tree(revision.payload()); + if (!payload.isObject() || !payload.path("revisionKind").isTextual()) { + throw new IllegalArgumentException("Closed Game Design owner revision kind is required"); + } + String revisionKind = payload.path("revisionKind").asText(); + if (REALM_POLICY_REVISION_KIND.equals(revisionKind)) { + found = true; + } else if (!REVISION_KIND.equals(revisionKind)) { + throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); + } + } + return found; + } + + /** Payload builder for a new immutable Draft binding; its result is part of binding.digest(). */ + public static String upsertPayload(String definitionJson) { + validateCommandDefinition(definitionJson); + return canonical( + Map.of( + "schemaVersion", SCHEMA_VERSION, + "revisionKind", REVISION_KIND, + "operation", "UPSERT", + "definitionJson", definitionJson)); + } + + /** + * Payload builder for an explicit digest-bound delete; absence is never interpreted as delete. + */ + public static String deletePayload(String commandId) { + requireText(commandId, "commandId"); + return canonical( + Map.of( + "schemaVersion", SCHEMA_VERSION, + "revisionKind", REVISION_KIND, + "operation", "DELETE", + "commandId", commandId)); + } + + public static List replay(List inherited, List mutations) { + Objects.requireNonNull(inherited, "inherited"); + Objects.requireNonNull(mutations, "mutations"); + Map effective = new HashMap<>(); + for (Definition definition : inherited) { + if (effective.putIfAbsent(definition.stableKey(), definition) != null) { + throw new IllegalArgumentException("Inherited command source repeats a stable command key"); + } + } + String previousOrder = null; + UUID commitId = null; + java.util.HashSet revisionIds = new java.util.HashSet<>(); + for (Mutation mutation : mutations) { + if ((previousOrder != null + && new java.math.BigInteger(mutation.revisionOrder()) + .compareTo(new java.math.BigInteger(previousOrder)) + <= 0) + || (commitId != null && !commitId.equals(mutation.commitId())) + || !revisionIds.add(mutation.revisionId())) { + throw new IllegalArgumentException( + "Command mutations must retain one canonical commit and increasing revision order"); + } + previousOrder = mutation.revisionOrder(); + commitId = mutation.commitId(); + if (mutation.operation() == OperationKind.DELETE) { + effective.remove(mutation.stableKey()); + } else { + effective.put( + mutation.stableKey(), + new Definition( + mutation.commandId(), + mutation.definitionJson(), + mutation.commitId(), + mutation.revisionId(), + mutation.revisionOrder())); + } + } + List result = + effective.values().stream().sorted(Comparator.comparing(Definition::stableKey)).toList(); + validateDistinctCommandTokens(result); + return result; + } + + static String definitionsJson(List definitions) { + return canonical( + definitions.stream() + .sorted(Comparator.comparing(Definition::stableKey)) + .map(CommandSource::definitionObject) + .toList()); + } + + static List definitionsFromStored(String json) { + JsonNode root = tree(json); + if (!root.isArray()) throw new IllegalArgumentException("Complete command array is required"); + List definitions = new ArrayList<>(); + for (JsonNode item : root) { + fields( + item, + "commandId", + "definitionJson", + "sourceCommitId", + "sourceRevisionId", + "revisionOrder"); + definitions.add( + new Definition( + requiredText(item, "commandId"), + requiredText(item, "definitionJson"), + UUID.fromString(requiredText(item, "sourceCommitId")), + UUID.fromString(requiredText(item, "sourceRevisionId")), + requiredText(item, "revisionOrder"))); + } + List result = + definitions.stream().sorted(Comparator.comparing(Definition::stableKey)).toList(); + if (!definitionsJson(result).equals(json)) { + throw new IllegalArgumentException("Stored command source set is not canonical"); + } + validateDistinctCommandTokens(result); + return List.copyOf(result); + } + + static String mutationsJson(List mutations) { + return canonical(mutations.stream().map(Mutation::canonicalObject).toList()); + } + + static List mutationsFromStored(String json) { + JsonNode root = tree(json); + if (!root.isArray()) + throw new IllegalArgumentException("Complete command operation list is required"); + List result = new ArrayList<>(); + for (JsonNode item : root) { + String operation = requiredText(item, "operation"); + if ("UPSERT".equals(operation)) { + fields( + item, + "revisionOrder", + "revisionId", + "commitId", + "operation", + "commandId", + "definitionJson"); + result.add( + new Mutation( + requiredText(item, "revisionOrder"), + UUID.fromString(requiredText(item, "revisionId")), + UUID.fromString(requiredText(item, "commitId")), + OperationKind.UPSERT, + requiredText(item, "commandId"), + requiredText(item, "definitionJson"))); + } else if ("DELETE".equals(operation)) { + fields(item, "revisionOrder", "revisionId", "commitId", "operation", "commandId"); + result.add( + new Mutation( + requiredText(item, "revisionOrder"), + UUID.fromString(requiredText(item, "revisionId")), + UUID.fromString(requiredText(item, "commitId")), + OperationKind.DELETE, + requiredText(item, "commandId"), + null)); + } else { + throw new IllegalArgumentException("Stored command operation kind is unsupported"); + } + } + String previousOrder = null; + java.util.HashSet revisionIds = new java.util.HashSet<>(); + for (Mutation mutation : result) { + if ((previousOrder != null + && new java.math.BigInteger(mutation.revisionOrder()) + .compareTo(new java.math.BigInteger(previousOrder)) + <= 0) + || !revisionIds.add(mutation.revisionId())) { + throw new IllegalArgumentException( + "Stored command operations are not in exact revision order"); + } + previousOrder = mutation.revisionOrder(); + } + return List.copyOf(result); + } + + static void requireCanonicalDefinitions(List definitions) { + List sorted = + definitions.stream().sorted(Comparator.comparing(Definition::stableKey)).toList(); + if (!definitions.equals(sorted)) { + throw new IllegalArgumentException( + "Command source definitions are not in canonical stable-key order"); + } + Map unique = new HashMap<>(); + for (Definition definition : definitions) { + if (unique.putIfAbsent(definition.stableKey(), definition) != null) { + throw new IllegalArgumentException("Command source repeats a stable command key"); + } + } + validateDistinctCommandTokens(definitions); + } + + static void requireStoredFields(JsonNode node, String... fields) { + CommandSource.fields(node, fields); + } + + static String requiredStoredText(JsonNode node, String field) { + return requiredText(node, field); + } + + static String canonical(Object value) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } catch (IOException failure) { + throw new IllegalArgumentException("Canonical command source encoding failed", failure); + } + } + + static JsonNode tree(String json) { + try { + return JSON.readTree(Rfc8785CanonicalJson.canonicalizeUtf8(json)); + } catch (IOException | RuntimeException failure) { + throw new IllegalArgumentException("Unambiguous command source JSON required", failure); + } + } + + static byte[] canonicalBytes(String json) { + return json.getBytes(StandardCharsets.UTF_8); + } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 unavailable", failure); + } + } + + static Map targetObject(DraftCommitBinding.TargetProof target) { + Map result = new LinkedHashMap<>(); + result.put("canonicalTenantId", target.canonicalTenantId().toString()); + result.put("canonicalVersionId", target.canonicalVersionId().toString()); + result.put("gameDesignVersionRowId", target.gameDesignVersionRowId()); + result.put("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()); + result.put("sourceGameRowId", target.sourceGameRowId()); + result.put("sourceGameTenantKey", target.sourceGameTenantKey()); + result.put("sourceProvenanceKind", target.sourceProvenanceKind()); + return result; + } + + private static Map definitionObject(Definition definition) { + return Map.of( + "commandId", definition.commandId(), + "definitionJson", definition.definitionJson(), + "sourceCommitId", definition.sourceCommitId().toString(), + "sourceRevisionId", definition.sourceRevisionId().toString(), + "revisionOrder", definition.revisionOrder()); + } + + private static void validateDistinctCommandTokens(List definitions) { + Map tokenOwners = new HashMap<>(); + Map commandIds = new HashMap<>(); + for (Definition definition : definitions) { + String commandId = normalizeToken(definition.commandId()); + if (commandIds.putIfAbsent(commandId, Boolean.TRUE) != null) { + throw new IllegalArgumentException("Duplicate command definition id " + commandId); + } + ensureSingleTokenOwner(tokenOwners, commandId, commandId); + JsonNode aliases = tree(definition.definitionJson()).get("aliases"); + for (JsonNode alias : aliases) { + String normalized = normalizeToken(alias.asText()); + ensureSingleTokenOwner(tokenOwners, normalized, commandId); + } + } + } + + private static void ensureSingleTokenOwner( + Map owners, String token, String commandId) { + String existing = owners.putIfAbsent(token, commandId); + if (existing != null && !existing.equals(commandId)) { + throw new IllegalArgumentException("Ambiguous published command token " + token); + } + } + + private static String commandIdFrom(String definitionJson) { + validateCommandDefinition(definitionJson); + return requiredText(tree(definitionJson), "commandId"); + } + + /** Mirrors the currently accepted revision and release schema while preserving the raw JSON. */ + private static void validateCommandDefinition(String json) { + JsonNode definition = tree(json); + if (!definition.isObject() || definition.path("schemaVersion").asInt() != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported command definition schema"); + } + requiredText(definition, "commandId"); + requiredText(definition, "semanticOwner"); + requireEnum(definition, "executionDiscipline", "DURABLE_GAMEPLAY"); + requireEnum(definition, "stageRequirement", "NONE", "LOGIN", "GAMEPLAY"); + requireEnum(definition, "promptPolicy", "NEVER", "WHEN_LOGGED_IN", "WHEN_GAMEPLAY"); + requireEnum(definition, "actionCategory", "GAMEPLAY", "SOCIAL", "META", "ADMIN", "SYSTEM"); + JsonNode history = definition.get("historyRecordable"); + if (history == null || !history.isBoolean()) { + throw new IllegalArgumentException("historyRecordable must be a boolean"); + } + requireTextArray(definition, "aliases"); + requireEnumArray( + definition, + "actionTags", + "MOVEMENT", + "COMMUNICATION", + "COMBAT", + "INVENTORY", + "WORLD_BROWSE", + "SOCIAL_PRESENCE", + "AUTHORING", + "SESSION", + "UI"); + JsonNode effects = definition.get("effects"); + if (effects == null || !effects.isArray()) { + throw new IllegalArgumentException("effects must be an array"); + } + for (JsonNode effect : effects) validateEffect(effect); + } + + private static void validateEffect(JsonNode effect) { + if (!effect.isObject() + || !"APPLY_ACTION_STATE".equals(requiredText(effect, "effectKind")) + || !effect.path("schemaVersion").isInt() + || effect.path("schemaVersion").asInt() != 1 + || !"SELF".equals(requiredText(effect, "targeting")) + || !"EFFECT_IDEMPOTENT".equals(requiredText(effect, "replayPolicy"))) { + throw new IllegalArgumentException("Unsupported command effect declaration"); + } + JsonNode payload = effect.get("payload"); + if (payload == null || !payload.isObject()) + throw new IllegalArgumentException("Effect payload must be an object"); + requireIdentifier(payload, "conditionKey"); + JsonNode duration = payload.get("durationSeconds"); + if (duration == null + || !duration.isInt() + || !CommandEffectDeclarationConstraints.isValidDurationSeconds(duration.asInt())) { + throw new IllegalArgumentException("Command action-state duration is unsupported"); + } + JsonNode effectPayload = payload.get("effectPayload"); + JsonNode modifiers = effectPayload == null ? null : effectPayload.get("modifiers"); + if (effectPayload == null + || !effectPayload.isObject() + || modifiers == null + || !modifiers.isArray()) { + throw new IllegalArgumentException("Command effect modifiers must be an array"); + } + for (JsonNode modifier : modifiers) { + if (!modifier.isObject()) + throw new IllegalArgumentException("Command effect modifier must be an object"); + String operation = requiredText(modifier, "operation"); + if (!CommandEffectDeclarationConstraints.SUPPORTED_MODIFIER_OPERATIONS.contains(operation)) { + throw new IllegalArgumentException("Unsupported command effect modifier operation"); + } + requireIdentifier(modifier, "target_key"); + JsonNode value = modifier.get("value"); + if (value == null || !value.isNumber()) + throw new IllegalArgumentException("Command effect modifier value must be numeric"); + optionalIdentifier(modifier, "scope_kind"); + optionalIdentifier(modifier, "scope_key"); + JsonNode priority = modifier.get("priority"); + if (priority != null && !priority.isInt()) + throw new IllegalArgumentException("Command effect priority must be an integer"); + } + } + + private static void requireIdentifier(JsonNode source, String field) { + String value = requiredText(source, field); + if (!CommandEffectDeclarationConstraints.isIdentifier(value)) { + throw new IllegalArgumentException("Command effect identifier is invalid: " + field); + } + } + + private static void optionalIdentifier(JsonNode source, String field) { + if (source.get(field) != null) requireIdentifier(source, field); + } + + private static void requireEnum(JsonNode source, String field, String... allowed) { + String actual = requiredText(source, field); + for (String value : allowed) if (value.equals(actual)) return; + throw new IllegalArgumentException("Unsupported command definition field " + field); + } + + private static void requireEnumArray(JsonNode source, String field, String... allowed) { + requireTextArray(source, field); + List supported = List.of(allowed); + for (JsonNode item : source.get(field)) { + if (!supported.contains(item.asText())) { + throw new IllegalArgumentException("Unsupported command definition value in " + field); + } + } + } + + private static void requireTextArray(JsonNode source, String field) { + JsonNode values = source.get(field); + if (values == null || !values.isArray()) { + throw new IllegalArgumentException("Command definition array is required: " + field); + } + for (JsonNode value : values) { + if (!value.isTextual() || value.asText().isBlank()) { + throw new IllegalArgumentException( + "Command definition array has an invalid entry: " + field); + } + } + } + + private static String requiredText(JsonNode source, String field) { + JsonNode value = source.get(field); + if (value == null || !value.isTextual() || value.asText().isBlank()) { + throw new IllegalArgumentException("Command definition text is required: " + field); + } + return value.asText(); + } + + private static String normalizeToken(String token) { + if (token == null || token.isBlank()) { + throw new IllegalArgumentException("Command token must not be blank"); + } + return token.trim().toLowerCase(Locale.ROOT); + } + + private static void fields(JsonNode node, String... names) { + if (!node.isObject() || node.size() != names.length) { + throw new IllegalArgumentException("Closed command source operation fields are required"); + } + for (String name : names) { + if (node.get(name) == null) + throw new IllegalArgumentException("Missing command source field " + name); + } + } + + private static void requireCounter(String value, String name) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(name + " must be a canonical nonnegative decimal"); + } + } + + private static void requireText(String value, String name) { + if (value == null || value.isBlank() || !StandardCharsets.UTF_8.newEncoder().canEncode(value)) { + throw new IllegalArgumentException(name + " must be nonblank valid UTF-8 text"); + } + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) + throw new IllegalArgumentException(name + " must be non-nil"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java new file mode 100644 index 0000000000..ffc60d15a4 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java @@ -0,0 +1,809 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal owner storage for a complete effective command set. Writes require the caller's + * coordinator transaction; this repository does not register an owner outcome or authorize a + * publication. + */ +public final class CommandSourceRepository { + private final DSLContext dsl; + + public CommandSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Explicit empty genesis for a Version known by its creation owner to be newly inserted as a + * Draft. Call only in that exact Version insertion transaction. Missing source rows alone never + * establish genesis, and this receipt is not a Draft commit. + */ + public CommandSource.NewDraftGenesisReceipt enrollNewDraftGenesis( + CommandSource.NewDraftGenesisReceipt receipt) { + requireWrite(); + Objects.requireNonNull(receipt, "receipt"); + TargetProof target = receipt.target(); + lockAuthority(target); + Record version = version(target); + if (!"DRAFT".equals(version.get("version_state", String.class)) + || !Long.valueOf(1L).equals(version.get("version_state_epoch", Long.class)) + || Boolean.TRUE.equals(version.get("is_script_only", Boolean.class)) + || version.get("script_patch_version") != null + || version.get("base_version_id") != null) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_REQUIRES_NEW_FULL_DRAFT_EPOCH_ONE"); + } + Optional existing = baseline(target); + if (existing.isPresent()) { + Record row = existing.orElseThrow(); + if (!Arrays.equals(receipt.canonicalBytes(), row.get("receipt_bytes", byte[].class)) + || !receipt.digest().equals(row.get("receipt_digest", String.class)) + || !receipt.targetProofJson().equals(row.get("target_proof_json", String.class)) + || !receipt.receiptId().equals(row.get("receipt_id", UUID.class)) + || !receipt + .creationTransactionId() + .equals(row.get("creation_transaction_id", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_RECEIPT_CONFLICT"); + } + requireVersionInsertWitness(target, receipt.creationTransactionId(), false); + requireHeadBaseline(target, receipt.digest()); + return receipt; + } + requireVersionInsertWitness(target, receipt.creationTransactionId(), true); + if (head(target).isPresent() + || new DraftCommitCoordinatorRepository(dsl).readVisibilityFence(target).isPresent()) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_AFTER_DRAFT_COMMIT_DENIED"); + } + dsl.execute( + "INSERT INTO game_design_command_source_baseline " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, baseline_kind, " + + "receipt_id, creation_transaction_id, target_proof_json, receipt_bytes, receipt_digest) " + + "VALUES (?, ?, ?, 'NEW_DRAFT_EMPTY', ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + receipt.receiptId(), + receipt.creationTransactionId(), + receipt.targetProofJson(), + receipt.canonicalBytes(), + receipt.digest()); + dsl.execute( + "INSERT INTO game_design_command_source_head " + + "(canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id, applied_commit_id, baseline_digest) " + + "VALUES (?, ?, '0', NULL, NULL, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + receipt.digest()); + requireHeadBaseline(target, receipt.digest()); + return receipt; + } + + /** Exact readback of an explicitly enrolled empty new-Draft baseline; absence stays absent. */ + public Optional readNewDraftGenesis(TargetProof target) { + Objects.requireNonNull(target, "target"); + Optional stored = baseline(target); + if (stored.isEmpty()) return Optional.empty(); + Record row = stored.orElseThrow(); + CommandSource.NewDraftGenesisReceipt receipt = + new CommandSource.NewDraftGenesisReceipt( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class)); + if (row.get("game_design_version_row_id", Long.class) != target.gameDesignVersionRowId() + || !receipt.targetProofJson().equals(row.get("target_proof_json", String.class)) + || !Arrays.equals(receipt.canonicalBytes(), row.get("receipt_bytes", byte[].class)) + || !receipt.digest().equals(row.get("receipt_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_RECEIPT_READBACK_CONFLICT"); + } + requireVersionInsertWitness(target, receipt.creationTransactionId(), false); + return Optional.of(receipt); + } + + /** + * Applies command operations to private staged source. The returned evidence is one component of + * GAME_DESIGN_CONTROL_PLANE's combined APPLIED result; this method never records that result. + */ + public Optional apply(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + TargetProof target = binding.target(); + lockAuthority(target); + exactCommit(binding); + List mutations = CommandSource.mutations(binding); + boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); + requireCompleteControlPlaneScopes(binding, mutations, policyMutation); + Optional existing = application(binding); + if (existing.isPresent()) return existing; + if (mutations.isEmpty()) return Optional.empty(); + requireOpenDraft(target); + requireNoPublicationSelection(target); + requireCoordinatorApplicationSlot(binding); + requireOwnerApplyStarted(binding); + + Record head = requireHead(target); + String expectedEpoch = commandScope(binding).expectedEpoch(); + if (!expectedEpoch.equals(head.get("source_epoch", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_EPOCH_CONFLICT"); + } + UUID inheritedCommitId = head.get("visible_commit_id", UUID.class); + requireVisibleHeadMatchesFence(target, inheritedCommitId); + String baselineDigest = head.get("baseline_digest", String.class); + List inheritedDefinitions; + if (inheritedCommitId == null) { + inheritedDefinitions = List.of(); + if (!"0".equals(expectedEpoch)) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_EPOCH_CHANGED"); + } + } else { + CommandSnapshot inherited = + readSnapshot(target, inheritedCommitId) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_VISIBLE_SNAPSHOT_UNAVAILABLE")); + if (!inherited.sourceEpoch().equals(expectedEpoch) + || !inherited.genesisReceiptDigest().equals(baselineDigest)) { + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_STATE_CONFLICT"); + } + inheritedDefinitions = inherited.definitions(); + } + for (CommandSource.Mutation mutation : mutations) + requireRevisionIdentityUnused(target, mutation); + String resultEpoch = new BigInteger(expectedEpoch).add(BigInteger.ONE).toString(); + CommandSnapshot snapshot = + new CommandSnapshot( + binding, + resultEpoch, + inheritedCommitId, + baselineDigest, + CommandSource.replay(inheritedDefinitions, mutations)); + CommandApplication result = + new CommandApplication(binding, inheritedCommitId, expectedEpoch, mutations, snapshot); + insertApplication(result, baselineDigest); + insertOperations(result); + int advanced = + dsl.execute( + "UPDATE game_design_command_source_head SET source_epoch = ?, applied_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM ?", + resultEpoch, + binding.commitId(), + target.canonicalTenantId(), + target.canonicalVersionId(), + expectedEpoch, + inheritedCommitId); + if (advanced != 1) throw new IllegalStateException("COMMAND_SOURCE_EPOCH_CONFLICT"); + return Optional.of( + application(binding) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_APPLICATION_READBACK_FAILED"))); + } + + /** + * Makes the staged complete source visible only after the coordinator's exact synchronized fence + * and combined owner outcome are durable in this same transaction. + */ + public CommandSnapshot captureSynchronized(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + TargetProof target = binding.target(); + lockAuthority(target); + exactCommit(binding); + Optional existing = readSnapshot(target, binding.commitId()); + if (existing.isPresent()) { + if (!existing.orElseThrow().binding().equals(binding)) { + throw new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + } + return existing.orElseThrow(); + } + requireOpenDraft(target); + requireNoPublicationSelection(target); + requireExactSynchronizedOwnerResult(binding); + Record head = requireHead(target); + UUID inheritedCommitId = head.get("visible_commit_id", UUID.class); + String baselineDigest = head.get("baseline_digest", String.class); + String sourceEpoch = head.get("source_epoch", String.class); + List mutations = CommandSource.mutations(binding); + requireCompleteControlPlaneScopes( + binding, mutations, CommandSource.hasRealmPolicyRevision(binding)); + List definitions; + if (!mutations.isEmpty()) { + CommandApplication applied = + application(binding) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_APPLICATION_UNAVAILABLE")); + if (!applied.snapshot().sourceEpoch().equals(sourceEpoch) + || !applied.snapshot().genesisReceiptDigest().equals(baselineDigest) + || !Objects.equals(applied.inheritedCommitId(), inheritedCommitId)) { + throw new IllegalStateException("COMMAND_SOURCE_APPLICATION_NOT_CURRENT"); + } + definitions = applied.snapshot().definitions(); + } else if (inheritedCommitId == null) { + if (!"0".equals(sourceEpoch)) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_EPOCH_CHANGED"); + } + definitions = List.of(); + } else { + CommandSnapshot inherited = + readSnapshot(target, inheritedCommitId) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_VISIBLE_SNAPSHOT_UNAVAILABLE")); + if (!inherited.sourceEpoch().equals(sourceEpoch) + || !inherited.genesisReceiptDigest().equals(baselineDigest)) { + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_STATE_CONFLICT"); + } + definitions = inherited.definitions(); + } + CommandSnapshot snapshot = + new CommandSnapshot(binding, sourceEpoch, inheritedCommitId, baselineDigest, definitions); + dsl.execute( + "INSERT INTO game_design_command_source_snapshot " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, input_digest, " + + "binding_json, inherited_commit_id, baseline_digest, source_epoch, snapshot_json, snapshot_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.commitId(), + binding.requestId(), + binding.digest(), + binding.canonicalJson(), + inheritedCommitId, + baselineDigest, + sourceEpoch, + snapshot.canonicalJson(), + snapshot.digest()); + int advanced = + dsl.execute( + "UPDATE game_design_command_source_head SET visible_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND visible_commit_id IS NOT DISTINCT FROM ? AND source_epoch = ?", + binding.commitId(), + target.canonicalTenantId(), + target.canonicalVersionId(), + inheritedCommitId, + sourceEpoch); + if (advanced != 1) throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_FENCE_CONFLICT"); + return readSnapshot(target, binding.commitId()) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_READBACK_FAILED")); + } + + /** Captures source against the actual original publication operation and exact selected fence. */ + public CommandSnapshot.Capture freeze(GameDesignPublicationOperation operation) { + requireWrite(); + Objects.requireNonNull(operation, "operation"); + var selection = operation.account().input().selection(); + TargetProof target = selection.target(); + lockAuthority(target); + Optional existing = readCapture(operation); + if (existing.isPresent()) return existing.orElseThrow(); + requireOpenDraft(target); + Record selected = + dsl.fetchOne( + "SELECT selection_json, selection_digest FROM game_design_authored_draft_publish_selection " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (selected == null + || !selection.canonicalJson().equals(selected.get("selection_json", String.class)) + || !selection.digest().equals(selected.get("selection_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_SELECTION_UNAVAILABLE"); + } + var retainedOperation = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow( + () -> + new IllegalStateException("COMMAND_SOURCE_PUBLICATION_OPERATION_UNAVAILABLE")); + GameDesignPublicationOperationRepository.exact(retainedOperation.operation(), operation); + if (!"PENDING".equals(retainedOperation.outcome())) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_OPERATION_SEALED"); + } + Record versionRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT version_state_epoch FROM version WHERE id = ?", + target.gameDesignVersionRowId()), + "COMMAND_SOURCE_VERSION_UNAVAILABLE"); + Long versionEpoch = versionRow.get("version_state_epoch", Long.class); + if (versionEpoch == null + || !selection.intent().expectedVersionStateEpoch().equals(Long.toString(versionEpoch))) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_VERSION_EPOCH_CHANGED"); + } + DraftCommitBinding selectedCommit = selection.selectedCommit(); + requireCurrentFence(selectedCommit); + CommandSnapshot snapshot = + readSnapshot(target, selectedCommit.commitId()) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_SELECTED_SNAPSHOT_UNAVAILABLE")); + Record head = requireHead(target); + if (!selectedCommit.equals(snapshot.binding()) + || !selectedCommit.commitId().equals(head.get("visible_commit_id", UUID.class)) + || !snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_SELECTED_SOURCE_NOT_SYNCHRONIZED"); + } + CommandSnapshot.Capture capture = new CommandSnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_command_source_capture " + + "(canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, " + + "operation_bytes, capture_bytes, capture_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + operation.workflowId(), + selectedCommit.commitId(), + operation.canonicalBytes(), + capture.canonicalBytes(), + capture.digest()); + return readCapture(operation) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_CAPTURE_READBACK_FAILED")); + } + + public Optional readSnapshot(TargetProof target, UUID commitId) { + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(commitId, "commitId"); + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_command_source_snapshot WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId); + if (row == null) return Optional.empty(); + CommandSnapshot snapshot = CommandSnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId) + || !snapshot.binding().requestId().equals(row.get("request_id", UUID.class)) + || !snapshot.binding().digest().equals(row.get("input_digest", String.class)) + || !snapshot.binding().canonicalJson().equals(row.get("binding_json", String.class)) + || !snapshot.sourceEpoch().equals(row.get("source_epoch", String.class)) + || !snapshot.genesisReceiptDigest().equals(row.get("baseline_digest", String.class)) + || !snapshot.digest().equals(row.get("snapshot_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_STORAGE_CONFLICT"); + } + var commit = + new DraftCommitCoordinatorRepository(dsl) + .read(target, snapshot.binding().requestId()) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_COMMIT_UNAVAILABLE")); + Record fence = + dsl.fetchOne( + "SELECT input_digest FROM game_design_draft_commit_visibility_fence " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.binding().requestId(), + commitId); + if (!commit.binding().equals(snapshot.binding()) + || fence == null + || !snapshot.binding().digest().equals(fence.get("input_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_SNAPSHOT_FENCE_CONFLICT"); + } + verifyDefinitionProvenance(snapshot); + return Optional.of(snapshot); + } + + public Optional readCapture(GameDesignPublicationOperation operation) { + Objects.requireNonNull(operation, "operation"); + var selection = operation.account().input().selection(); + TargetProof target = selection.target(); + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_command_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !operation.workflowId().equals(row.get("publish_workflow_id", String.class)) + || !selection.selectedCommit().commitId().equals(row.get("commit_id", UUID.class))) { + throw new IllegalArgumentException("COMMAND_SOURCE_FREEZE_OPERATION_CONFLICT"); + } + CommandSnapshot snapshot = + readSnapshot(target, row.get("commit_id", UUID.class)) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_CAPTURE_SNAPSHOT_UNAVAILABLE")); + CommandSnapshot.Capture capture = new CommandSnapshot.Capture(operation, snapshot); + if (!Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class)) + || !capture.digest().equals(row.get("capture_digest", String.class))) { + throw new IllegalStateException("COMMAND_SOURCE_CAPTURE_STORAGE_CONFLICT"); + } + return Optional.of(capture); + } + + private void insertApplication(CommandApplication application, String baselineDigest) { + DraftCommitBinding binding = application.binding(); + dsl.execute( + "INSERT INTO game_design_command_source_application " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, input_digest, " + + "binding_json, inherited_commit_id, baseline_digest, expected_epoch, snapshot_json, " + + "operations_json, result_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + binding.digest(), + binding.canonicalJson(), + application.inheritedCommitId(), + baselineDigest, + application.expectedEpoch(), + application.snapshot().canonicalJson(), + CommandSource.mutationsJson(application.mutations()), + application.canonicalBytes()); + } + + private void insertOperations(CommandApplication application) { + for (CommandSource.Mutation mutation : application.mutations()) { + String operationJson = CommandSource.canonical(mutation.canonicalObject()); + dsl.execute( + "INSERT INTO game_design_command_source_operation " + + "(canonical_tenant_id, canonical_version_id, commit_id, revision_order, revision_id, " + + "operation_kind, command_id, command_key, definition_json, operation_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + application.binding().target().canonicalTenantId(), + application.binding().target().canonicalVersionId(), + application.binding().commitId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.revisionId(), + mutation.operation().name(), + mutation.commandId(), + mutation.stableKey(), + mutation.definitionJson(), + operationJson); + } + } + + private Optional application(DraftCommitBinding binding) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_command_source_application WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) return Optional.empty(); + DraftCommitBinding stored = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + CommandSnapshot snapshot = CommandSnapshot.fromStored(row.get("snapshot_json", String.class)); + String operationsJson = row.get("operations_json", String.class); + List mutations = CommandSource.mutationsFromStored(operationsJson); + CommandApplication result = + new CommandApplication( + stored, + row.get("inherited_commit_id", UUID.class), + row.get("expected_epoch", String.class), + mutations, + snapshot); + if (!stored.equals(binding) + || !binding.requestId().equals(row.get("request_id", UUID.class)) + || !CommandSource.mutationsJson(mutations).equals(operationsJson) + || !Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class))) { + throw new IllegalStateException("COMMAND_SOURCE_APPLICATION_EXACT_BINDING_CONFLICT"); + } + List storedOperations = + dsl.fetch( + "SELECT operation_json FROM game_design_command_source_operation " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ? ORDER BY revision_order", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()) + .getValues("operation_json", String.class); + if (!storedOperations.equals( + result.mutations().stream() + .map(m -> CommandSource.canonical(m.canonicalObject())) + .toList())) { + throw new IllegalStateException("COMMAND_SOURCE_OPERATION_READBACK_CONFLICT"); + } + return Optional.of(result); + } + + private void verifyDefinitionProvenance(CommandSnapshot snapshot) { + for (CommandSource.Definition definition : snapshot.definitions()) { + Record row = + dsl.fetchOne( + "SELECT binding_json, input_digest FROM game_design_draft_commit " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + definition.sourceCommitId()); + if (row == null) + throw new IllegalStateException("COMMAND_SOURCE_AUTHORED_COMMIT_UNAVAILABLE"); + DraftCommitBinding original = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + if (!original.target().equals(snapshot.binding().target())) { + throw new IllegalStateException("COMMAND_SOURCE_AUTHORED_TARGET_CHANGED"); + } + CommandSource.Mutation source = + CommandSource.mutations(original).stream() + .filter(mutation -> mutation.revisionId().equals(definition.sourceRevisionId())) + .filter(mutation -> mutation.operation() == CommandSource.OperationKind.UPSERT) + .findFirst() + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_AUTHORED_REVISION_UNAVAILABLE")); + if (!source.commandId().equals(definition.commandId()) + || !source.definitionJson().equals(definition.definitionJson()) + || !source.commitId().equals(definition.sourceCommitId())) { + throw new IllegalStateException("COMMAND_SOURCE_AUTHORED_PROVENANCE_CHANGED"); + } + } + } + + private void requireCompleteControlPlaneScopes( + DraftCommitBinding binding, + List commandMutations, + boolean policyMutation) { + List units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE); + List commands = + units.stream().filter(this::isCommandScope).toList(); + List policies = + units.stream().filter(this::isPolicyScope).toList(); + if (commands.size() != (commandMutations.isEmpty() ? 0 : 1) + || policies.size() != (policyMutation ? 1 : 0) + || commands.size() + policies.size() != units.size()) { + throw new IllegalArgumentException( + "Complete supported Game Design control-plane scopes are required"); + } + if (!commands.isEmpty()) requireScopeTarget(commands.getFirst(), binding.target()); + if (!policies.isEmpty()) requireScopeTarget(policies.getFirst(), binding.target()); + } + + private boolean isCommandScope(DraftCommitBinding.AffectedUnit unit) { + return CommandSource.SCOPE.equals(unit.aggregateType()) + && CommandSource.SCOPE.equals(unit.scopeType()) + && CommandSource.SCOPE_ID.equals(unit.scopeId()); + } + + private boolean isPolicyScope(DraftCommitBinding.AffectedUnit unit) { + return RealmPolicySource.SCOPE.equals(unit.aggregateType()) + && RealmPolicySource.SCOPE.equals(unit.scopeType()) + && "effective".equals(unit.scopeId()); + } + + private void requireScopeTarget(DraftCommitBinding.AffectedUnit unit, TargetProof target) { + if (!target.canonicalVersionId().toString().equals(unit.aggregateId())) { + throw new IllegalArgumentException( + "Control-plane scope must bind the exact canonical Version"); + } + } + + private DraftCommitBinding.AffectedUnit commandScope(DraftCommitBinding binding) { + return binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(this::isCommandScope) + .findFirst() + .orElseThrow( + () -> new IllegalArgumentException("Command source affected scope is omitted")); + } + + private void requireCoordinatorApplicationSlot(DraftCommitBinding binding) { + var slot = + new DraftCommitCoordinatorRepository(dsl) + .readApplicationSlot(binding.target()) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_APPLICATION_SLOT_UNAVAILABLE")); + if (!slot.requestId().equals(binding.requestId()) + || !slot.commitId().equals(binding.commitId())) { + throw new IllegalStateException("COMMAND_SOURCE_APPLICATION_SLOT_CHANGED"); + } + } + + private void requireOwnerApplyStarted(DraftCommitBinding binding) { + var state = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (state == null + || (state.status() != OwnerStatus.IN_PROGRESS && state.status() != OwnerStatus.UNKNOWN)) { + throw new IllegalStateException("COMMAND_SOURCE_OWNER_APPLICATION_NOT_STARTED"); + } + } + + private void requireExactSynchronizedOwnerResult(DraftCommitBinding binding) { + DraftCommitCoordinatorRepository coordinator = new DraftCommitCoordinatorRepository(dsl); + var commit = coordinator.read(binding.target(), binding.requestId()).orElseThrow(); + var owner = commit.ownerStates().get(Owner.GAME_DESIGN_CONTROL_PLANE); + var fence = coordinator.readVisibilityFence(binding.target()).orElseThrow(); + if (!commit.binding().equals(binding) + || commit.workflowState() != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED + || !binding.requestId().equals(fence.requestId()) + || !binding.commitId().equals(fence.commitId()) + || !binding.digest().equals(fence.inputDigest())) { + throw new IllegalStateException("COMMAND_SOURCE_SYNCHRONIZED_OWNER_RESULT_UNAVAILABLE"); + } + if (binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE) + && (owner == null + || owner.status() != OwnerStatus.APPLIED + || owner.outcome().isEmpty() + || !binding.commitId().equals(owner.outcome().orElseThrow().commitId()) + || !binding.digest().equals(owner.outcome().orElseThrow().bindingDigest()))) { + throw new IllegalStateException("COMMAND_SOURCE_SYNCHRONIZED_OWNER_RESULT_UNAVAILABLE"); + } + } + + private void requireVisibleHeadMatchesFence(TargetProof target, UUID visibleCommitId) { + var fence = new DraftCommitCoordinatorRepository(dsl).readVisibilityFence(target); + if (visibleCommitId == null) { + if (fence.isPresent()) + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_FENCE_CHANGED"); + } else if (fence.isEmpty() || !visibleCommitId.equals(fence.orElseThrow().commitId())) { + throw new IllegalStateException("COMMAND_SOURCE_VISIBLE_FENCE_CHANGED"); + } + } + + private void requireCurrentFence(DraftCommitBinding binding) { + var fence = + new DraftCommitCoordinatorRepository(dsl) + .readVisibilityFence(binding.target()) + .orElseThrow( + () -> new IllegalStateException("COMMAND_SOURCE_SYNCHRONIZED_FENCE_UNAVAILABLE")); + if (!binding.requestId().equals(fence.requestId()) + || !binding.commitId().equals(fence.commitId()) + || !binding.digest().equals(fence.inputDigest())) { + throw new IllegalStateException("COMMAND_SOURCE_SELECTED_COMMIT_NOT_CURRENT"); + } + } + + private void exactCommit(DraftCommitBinding binding) { + var retained = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_COMMIT_UNAVAILABLE")); + if (!retained.binding().equals(binding)) { + throw new IllegalArgumentException("COMMAND_SOURCE_COMMIT_BINDING_CONFLICT"); + } + } + + private void requireRevisionIdentityUnused(TargetProof target, CommandSource.Mutation mutation) { + if (dsl.fetchOne( + "SELECT 1 FROM game_design_command_source_operation " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + mutation.revisionId()) + != null) { + throw new IllegalArgumentException("COMMAND_SOURCE_REVISION_ID_REUSE"); + } + } + + private Optional baseline(TargetProof target) { + return Optional.ofNullable( + dsl.fetchOne( + "SELECT * FROM game_design_command_source_baseline WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId())); + } + + private Optional head(TargetProof target) { + return Optional.ofNullable( + dsl.fetchOne( + "SELECT * FROM game_design_command_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + target.canonicalTenantId(), + target.canonicalVersionId())); + } + + private Record requireHead(TargetProof target) { + return head(target) + .orElseThrow(() -> new IllegalStateException("COMMAND_SOURCE_BASELINE_UNAVAILABLE")); + } + + private void requireHeadBaseline(TargetProof target, String digest) { + Record row = requireHead(target); + if (!digest.equals(row.get("baseline_digest", String.class)) + || !"0".equals(row.get("source_epoch", String.class)) + || row.get("visible_commit_id", UUID.class) != null + || row.get("applied_commit_id", UUID.class) != null) { + throw new IllegalStateException("COMMAND_SOURCE_GENESIS_READBACK_CONFLICT"); + } + } + + private void requireVersionInsertWitness( + TargetProof target, String creationTransactionId, boolean requireCurrentTransaction) { + Record witness = + dsl.fetchOne( + "SELECT creation_transaction_id FROM game_design_realm_policy_version_insert " + + "WHERE version_id = ?", + target.gameDesignVersionRowId()); + Record currentTransaction = + Objects.requireNonNull( + dsl.fetchOne("SELECT pg_current_xact_id()::TEXT AS transaction_id"), + "COMMAND_SOURCE_CURRENT_TRANSACTION_UNAVAILABLE"); + String currentTransactionId = currentTransaction.get("transaction_id", String.class); + if (witness == null + || !creationTransactionId.equals(witness.get("creation_transaction_id", String.class)) + || (requireCurrentTransaction && !creationTransactionId.equals(currentTransactionId))) { + throw new IllegalStateException("COMMAND_SOURCE_NEW_DRAFT_INSERTION_WITNESS_UNAVAILABLE"); + } + } + + private void requireOpenDraft(TargetProof target) { + Record version = version(target); + if (!"DRAFT".equals(version.get("version_state", String.class)) + || Boolean.TRUE.equals(version.get("is_script_only", Boolean.class)) + || version.get("script_patch_version") != null + || version.get("base_version_id") != null + || dsl.fetchOne( + "SELECT 1 FROM game_design_command_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) { + throw new IllegalStateException("COMMAND_SOURCE_NOT_OPEN_FULL_DRAFT"); + } + } + + private void requireNoPublicationSelection(TargetProof target) { + if (dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) { + throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_SELECTION_RESERVED"); + } + } + + private void lockAuthority(TargetProof target) { + Record row = + dsl.fetchOne( + "SELECT v.id FROM version v JOIN game g ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id = ? AND v.identity_source_game_tenant_key = ? " + + "AND v.identity_source_provenance_kind = ? FOR UPDATE OF v", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()); + if (row == null) throw new IllegalStateException("COMMAND_SOURCE_CANONICAL_OWNER_UNAVAILABLE"); + } + + private Record version(TargetProof target) { + Record row = + dsl.fetchOne( + "SELECT v.id, v.tenant_id, v.canonical_tenant_id, v.canonical_version_id, " + + "v.identity_source_game_row_id, v.identity_source_game_tenant_key, v.identity_source_provenance_kind, " + + "v.version_state, v.version_state_epoch, v.is_script_only, v.script_patch_version, v.base_version_id " + + "FROM version v JOIN game g ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id = ? AND v.identity_source_game_tenant_key = ? " + + "AND v.identity_source_provenance_kind = ?", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()); + if (row == null) throw new IllegalStateException("COMMAND_SOURCE_CANONICAL_OWNER_UNAVAILABLE"); + return row; + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Command source writes require caller-owned writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java new file mode 100644 index 0000000000..45d095299a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.gamedesign.publication; + +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Closed original operation input. Codec validation supplies integrity, never authorization. */ +public record GameDesignPublicationOperation( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + public static final String SCHEMA = GameDesignPublicationOperationBinding.SCHEMA; + + public GameDesignPublicationOperation { + var binding = new GameDesignPublicationOperationBinding(account, world); + account = binding.account(); + world = binding.world(); + } + + public byte[] canonicalBytes() { + return new GameDesignPublicationOperationBinding(account, world).canonicalBytes(); + } + + public static GameDesignPublicationOperation fromStored(byte[] bytes) { + var binding = GameDesignPublicationOperationBinding.fromStored(bytes); + return new GameDesignPublicationOperation(binding.account(), binding.world()); + } + + public String workflowId() { + return world.request().publishWorkflowId(); + } + + public String tenantKey() { + return account.input().selection().target().gameDesignVersionTenantKey(); + } + + public long versionId() { + return account.input().selection().target().gameDesignVersionRowId(); + } + + public String selectionDigest() { + return account.input().selection().digest(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java new file mode 100644 index 0000000000..0714337e59 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java @@ -0,0 +1,254 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner storage only. Deliberately has no runtime bean or authenticated ingress. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal owner storage collaborator.") +public final class GameDesignPublicationOperationRepository { + private final DSLContext dsl; + + public GameDesignPublicationOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public void reserve(GameDesignPublicationOperation operation) { + requireTransaction(); + lock(operation.tenantKey(), operation.workflowId(), operation.versionId()); + Optional existing = read(operation.workflowId()); + if (existing.isPresent()) { + exact(existing.get().operation(), operation); + return; + } + dsl.execute( + "INSERT INTO game_design_publication_operation " + + "(publish_workflow_id, tenant_id, version_id, selection_digest, request_bytes) VALUES (?, ?, ?, ?, ?)", + operation.workflowId(), + operation.tenantKey(), + operation.versionId(), + operation.selectionDigest(), + operation.canonicalBytes()); + } + + /** Caller has already proved authorization; reservation and source freeze are one transaction. */ + public GameDesignSourceRepository.Capture reserveSourceBacked( + GameDesignPublicationOperation operation) { + reserve(operation); + return new GameDesignSourceRepository(dsl).freeze(operation); + } + + public Optional readSourceCapture( + GameDesignPublicationOperation operation) { + return new GameDesignSourceRepository(dsl).readCapture(operation); + } + + public GameDesignPublicationOperation requirePending( + String tenant, String workflow, long version, String digest) { + requireTransaction(); + lock(tenant, workflow, version); + Readback result = + read(workflow) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + var operation = result.operation(); + if (!operation.tenantKey().equals(tenant) + || operation.versionId() != version + || !operation.selectionDigest().equals(digest) + || !result.outcome().equals("PENDING")) { + throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); + } + return operation; + } + + public void seal(String tenant, String workflow, long version, String digest, boolean published) { + GameDesignPublicationOperation operation = requirePending(tenant, workflow, version, digest); + Record release = + dsl.fetchOne( + "SELECT r.*, to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + tenant, + version); + String evidence = release == null ? null : release.get("evidence", String.class); + if (published != (evidence != null)) + throw new IllegalStateException("PUBLICATION_READBACK_UNRESOLVED"); + String outcome = published ? "PUBLISHED" : "NO_PUBLICATION"; + byte[] result = receipt(operation, outcome, evidence); + Long publicationEpoch = null; + if (published) { + Record committedVersion = + dsl.fetchOne( + "SELECT version_state, version_state_epoch FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenant, + version); + if (committedVersion == null + || !"PUBLISHED".equals(committedVersion.get("version_state", String.class))) { + throw new IllegalStateException("PUBLICATION_VERSION_NOT_COMMITTED"); + } + publicationEpoch = committedVersion.get("version_state_epoch", Long.class); + } + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.valueOf(outcome), + published ? PublicationReleaseContent.fromRow(release) : null, + publicationEpoch); + int changed = + dsl.execute( + "UPDATE game_design_publication_operation SET outcome = ?, result_bytes = ?, release_row_json = ?, terminal_evidence_bytes = ?, publication_version_state_epoch = ?, release_content_bytes = ?, published_release_bundle_digest = ?, revision = revision + 1 WHERE publish_workflow_id = ? AND outcome = 'PENDING' AND revision = 1", + outcome, + result, + evidence, + terminal.canonicalBytes(), + publicationEpoch, + published ? terminal.releaseContent().canonicalBytes() : null, + published ? terminal.publishedReleaseBundleDigest() : null, + workflow); + if (changed != 1) throw new IllegalStateException("PUBLICATION_OPERATION_CAS_CONFLICT"); + } + + public Optional read(String workflow) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_publication_operation WHERE publish_workflow_id = ?", + workflow); + if (row == null) return Optional.empty(); + var operation = + GameDesignPublicationOperation.fromStored(row.get("request_bytes", byte[].class)); + String outcome = row.get("outcome", String.class); + byte[] bytes = row.get("result_bytes", byte[].class); + String evidence = row.get("release_row_json", String.class); + byte[] terminalBytes = row.get("terminal_evidence_bytes", byte[].class); + if (!operation.workflowId().equals(workflow) + || !operation.tenantKey().equals(row.get("tenant_id", String.class)) + || operation.versionId() != row.get("version_id", Long.class) + || !operation.selectionDigest().equals(row.get("selection_digest", String.class))) { + throw new IllegalStateException("PUBLICATION_OPERATION_STORAGE_CONFLICT"); + } + if (!"PENDING".equals(outcome)) { + if (!Arrays.equals(bytes, receipt(operation, outcome, evidence))) + throw new IllegalStateException("PUBLICATION_RECEIPT_CORRUPT"); + Record release = + dsl.fetchOne( + "SELECT to_jsonb(r)::TEXT AS evidence FROM published_release_bundle r WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()); + String actual = release == null ? null : release.get("evidence", String.class); + if (!Objects.equals(actual, evidence) || ("PUBLISHED".equals(outcome) != (actual != null))) { + throw new IllegalStateException("PUBLICATION_RECEIPT_BACKING_CONFLICT"); + } + // V50 history remains readable but never acquires unverifiable forward evidence. + if (terminalBytes != null) { + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + if (!Arrays.equals(terminal.operationBytes(), operation.canonicalBytes()) + || !terminal.outcome().name().equals(outcome)) { + throw new IllegalStateException("PUBLICATION_TERMINAL_IDENTITY_CONFLICT"); + } + if (terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED) { + Record immutableRelease = + dsl.fetchOne( + "SELECT * FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()); + if (!Arrays.equals( + terminal.releaseContent().canonicalBytes(), + PublicationReleaseContent.fromRow(immutableRelease).canonicalBytes()) + || !Arrays.equals( + terminal.releaseContent().canonicalBytes(), + row.get("release_content_bytes", byte[].class)) + || !Objects.equals( + terminal.publicationVersionStateEpoch(), + row.get("publication_version_state_epoch", Long.class)) + || !terminal + .publishedReleaseBundleDigest() + .equals(row.get("published_release_bundle_digest", String.class))) { + throw new IllegalStateException("PUBLICATION_TERMINAL_BACKING_CONFLICT"); + } + } + } + Record attempt = + dsl.fetchOne( + "SELECT status FROM publish_attempt WHERE publish_workflow_id = ?", workflow); + if (attempt == null) { + throw new IllegalStateException("PUBLICATION_RECEIPT_ATTEMPT_CONFLICT"); + } + String attemptStatus = attempt.get("status", String.class); + if (!("PUBLISHED".equals(outcome) ? "SUCCEEDED" : "FAILED").equals(attemptStatus)) { + throw new IllegalStateException("PUBLICATION_RECEIPT_ATTEMPT_CONFLICT"); + } + } + return Optional.of(new Readback(operation, outcome, bytes, terminalBytes)); + } + + private void lock(String tenant, String workflow, long version) { + if (dsl.fetchOne("SELECT id FROM game WHERE tenant_id = ? FOR UPDATE", tenant) == null + || dsl.fetchOne( + "SELECT id FROM publish_attempt WHERE tenant_id = ? AND publish_workflow_id = ? AND version_id = ? FOR UPDATE", + tenant, + workflow, + version) + == null + || dsl.fetchOne( + "SELECT id FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", tenant, version) + == null) { + throw new IllegalStateException("PUBLICATION_OWNER_IDENTITY_UNAVAILABLE"); + } + } + + public static void exact( + GameDesignPublicationOperation retained, GameDesignPublicationOperation requested) { + if (!Arrays.equals(retained.canonicalBytes(), requested.canonicalBytes())) + throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + } + + private static byte[] receipt( + GameDesignPublicationOperation operation, String outcome, String evidence) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-publication-owner-readback/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome); + if (evidence == null) { + DraftAuthorizationFenceBinding.frame(out, new byte[0]); + } else { + DraftAuthorizationFenceBinding.frame(out, evidence); + } + return out.toByteArray(); + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) + throw new IllegalStateException("Publication owner transaction required"); + } + + public record Readback( + GameDesignPublicationOperation operation, + String outcome, + byte[] receiptBytes, + byte[] terminalEvidenceBytes) { + public Readback { + receiptBytes = receiptBytes == null ? null : receiptBytes.clone(); + terminalEvidenceBytes = terminalEvidenceBytes == null ? null : terminalEvidenceBytes.clone(); + } + + public Readback(GameDesignPublicationOperation operation, String outcome, byte[] receiptBytes) { + this(operation, outcome, receiptBytes, null); + } + + @Override + public byte[] terminalEvidenceBytes() { + return terminalEvidenceBytes == null ? null : terminalEvidenceBytes.clone(); + } + + @Override + public byte[] receiptBytes() { + return receiptBytes == null ? null : receiptBytes.clone(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java new file mode 100644 index 0000000000..a9892ae52d --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java @@ -0,0 +1,301 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import org.jooq.DSLContext; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Joins the two actual Game Design sources under one caller-owned coordinator transaction. */ +public final class GameDesignSourceRepository { + private final RealmPolicySourceRepository policies; + private final CommandSourceRepository commands; + private final DraftCommitCoordinatorRepository coordinator; + + public GameDesignSourceRepository(DSLContext dsl) { + Objects.requireNonNull(dsl, "dsl"); + policies = new RealmPolicySourceRepository(dsl); + commands = new CommandSourceRepository(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + } + + /** Call only on the actual new full-Draft Version insertion branch, in that transaction. */ + public Genesis enrollFreshDraft(TargetProof target) { + requireWrite(); + Objects.requireNonNull(target, "target"); + RealmPolicyGenesis policy = policies.recordFreshGenesis(target); + CommandSource.NewDraftGenesisReceipt command = + commands.enrollNewDraftGenesis( + new CommandSource.NewDraftGenesisReceipt( + target, policy.receiptId(), policy.creationTransactionId())); + Genesis result = new Genesis(policy, command); + if (!result.equals( + readGenesis(target) + .orElseThrow( + () -> + new IllegalStateException( + "GAME_DESIGN_SOURCE_GENESIS_READBACK_UNAVAILABLE")))) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_READBACK_CONFLICT"); + } + return result; + } + + public Optional readGenesis(TargetProof target) { + Objects.requireNonNull(target, "target"); + var policy = policies.readGenesis(target); + var command = commands.readNewDraftGenesis(target); + if (policy.isEmpty() && command.isEmpty()) return Optional.empty(); + if (policy.isEmpty() || command.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); + } + return Optional.of(new Genesis(policy.orElseThrow(), command.orElseThrow())); + } + + /** Stage actual source writes and record exactly one complete local owner outcome. */ + public Application apply(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + List commandMutations = CommandSource.mutations(binding); + boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); + requireCompleteScopes(binding, !commandMutations.isEmpty(), policyMutation); + requireGenesis(binding.target()); + Optional command = commands.apply(binding); + if (command.isPresent() != !commandMutations.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_COMMAND_APPLICATION_INCOMPLETE"); + } + Optional policy = Optional.empty(); + if (policyMutation) { + // The policy-only path retains its existing exact owner result. Mixed input stages policy + // first, then records the combined result using the command store's actual readback bytes. + policy = + Optional.of( + command.isPresent() ? policies.applyMutation(binding) : policies.apply(binding)); + } + OwnerOutcome expected; + if (policy.isPresent() && command.isPresent()) { + var policyResult = policy.orElseThrow(); + var commandResult = command.orElseThrow(); + List epochs = + List.of( + commandResult.commandAppliedEpoch(), + policyResult.ownerOutcome().appliedEpochs().getFirst()); + policies.recordCombinedOwnerOutcome(binding, commandResult.canonicalBytes(), epochs); + expected = policyResult.combinedOwnerOutcome(commandResult.canonicalBytes(), epochs); + } else if (policy.isPresent()) { + expected = policy.orElseThrow().ownerOutcome(); + } else { + CommandApplication commandResult = command.orElseThrow(); + expected = commandOnlyOutcome(binding, commandResult); + coordinator.recordOwnerOutcome(binding, expected); + } + OwnerOutcome retained = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow(() -> new IllegalStateException("GAME_DESIGN_COMMIT_READBACK_UNAVAILABLE")) + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE) + .outcome() + .orElseThrow( + () -> new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_UNAVAILABLE")); + if (!expected.equals(retained)) { + throw new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_CONFLICT"); + } + return new Application(binding, command, policy, retained); + } + + /** Invoke after the actual coordinator fence advances, before releasing its application slot. */ + public SynchronizedSources captureSynchronized(DraftCommitBinding binding) { + requireWrite(); + Objects.requireNonNull(binding, "binding"); + requireGenesis(binding.target()); + CommandSnapshot command = commands.captureSynchronized(binding); + RealmPolicySnapshot policy = policies.captureSynchronized(binding); + if (!binding.equals(command.binding()) || !binding.equals(policy.binding())) { + throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_BINDING_CONFLICT"); + } + return new SynchronizedSources(command, policy); + } + + /** Freeze both complete, selected source snapshots against the same retained operation. */ + public Capture freeze(GameDesignPublicationOperation operation) { + requireWrite(); + Objects.requireNonNull(operation, "operation"); + requireGenesis(operation.account().input().selection().target()); + RealmPolicySnapshot.Capture policy = policies.freeze(operation); + CommandSnapshot.Capture command = commands.freeze(operation); + Capture result = new Capture(command, policy); + Capture retained = + readCapture(operation) + .orElseThrow( + () -> new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_UNAVAILABLE")); + if (!Arrays.equals(result.command().canonicalBytes(), retained.command().canonicalBytes()) + || !Arrays.equals(result.policy().canonicalBytes(), retained.policy().canonicalBytes())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_CONFLICT"); + } + return retained; + } + + /** Exact stored captures for a bundle producer; partial capture cannot authorize publication. */ + public Optional readCapture(GameDesignPublicationOperation operation) { + Objects.requireNonNull(operation, "operation"); + var command = commands.readCapture(operation); + var policy = policies.readCapture(operation); + if (command.isEmpty() && policy.isEmpty()) return Optional.empty(); + if (command.isEmpty() || policy.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); + } + return Optional.of(new Capture(command.orElseThrow(), policy.orElseThrow())); + } + + public Optional readSynchronized(TargetProof target, UUID commitId) { + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(commitId, "commitId"); + var command = commands.readSnapshot(target, commitId); + var policy = policies.readSnapshot(target, commitId); + if (command.isEmpty() && policy.isEmpty()) return Optional.empty(); + if (command.isEmpty() || policy.isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); + } + return Optional.of(new SynchronizedSources(command.orElseThrow(), policy.orElseThrow())); + } + + private void requireGenesis(TargetProof target) { + if (readGenesis(target).isEmpty()) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_UNAVAILABLE"); + } + } + + private static OwnerOutcome commandOnlyOutcome( + DraftCommitBinding binding, CommandApplication command) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-control-plane-command-application/v1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, command.canonicalBytes()); + return new OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + command.resultIdentity(), + out.toByteArray(), + List.of(command.commandAppliedEpoch())); + } + + private static void requireCompleteScopes( + DraftCommitBinding binding, boolean hasCommand, boolean hasPolicy) { + if (!hasCommand && !hasPolicy + || !binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE)) { + throw new IllegalArgumentException("Game Design owner requires typed source revisions"); + } + List units = binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE); + List commands = + units.stream() + .filter( + unit -> + CommandSource.SCOPE.equals(unit.aggregateType()) + && CommandSource.SCOPE.equals(unit.scopeType()) + && CommandSource.SCOPE_ID.equals(unit.scopeId())) + .toList(); + List policies = + units.stream() + .filter( + unit -> + RealmPolicySource.SCOPE.equals(unit.aggregateType()) + && RealmPolicySource.SCOPE.equals(unit.scopeType()) + && "effective".equals(unit.scopeId())) + .toList(); + if (commands.size() != (hasCommand ? 1 : 0) + || policies.size() != (hasPolicy ? 1 : 0) + || commands.size() + policies.size() != units.size() + || units.stream() + .anyMatch( + unit -> + !binding.target().canonicalVersionId().toString().equals(unit.aggregateId()))) { + throw new IllegalArgumentException("Complete supported Game Design source scopes required"); + } + if (hasPolicy) { + binding.revisions().stream() + .filter(revision -> revision.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .filter(RealmPolicySource::isPolicyRevision) + .forEach(revision -> RealmPolicySource.revision(binding, revision)); + } + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Game Design source writes require caller-owned writable READ_COMMITTED transaction"); + } + } + + public record Genesis(RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command) { + public Genesis { + Objects.requireNonNull(policy, "policy"); + Objects.requireNonNull(command, "command"); + if (!policy.target().equals(command.target()) + || !policy.receiptId().equals(command.receiptId()) + || !policy.creationTransactionId().equals(command.creationTransactionId())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_IDENTITY_CONFLICT"); + } + } + } + + public record Application( + DraftCommitBinding binding, + Optional command, + Optional policy, + OwnerOutcome ownerOutcome) { + public Application { + Objects.requireNonNull(binding, "binding"); + command = Objects.requireNonNull(command, "command"); + policy = Objects.requireNonNull(policy, "policy"); + Objects.requireNonNull(ownerOutcome, "ownerOutcome"); + if (command.isEmpty() && policy.isEmpty() + || command.isPresent() && !binding.equals(command.orElseThrow().binding()) + || policy.isPresent() && !binding.equals(policy.orElseThrow().snapshot().binding()) + || ownerOutcome.owner() != Owner.GAME_DESIGN_CONTROL_PLANE + || ownerOutcome.status() != OwnerStatus.APPLIED + || !binding.commitId().equals(ownerOutcome.commitId()) + || !binding.digest().equals(ownerOutcome.bindingDigest())) { + throw new IllegalArgumentException("Owner application differs from exact Draft binding"); + } + } + } + + public record SynchronizedSources(CommandSnapshot command, RealmPolicySnapshot policy) { + public SynchronizedSources { + Objects.requireNonNull(command, "command"); + Objects.requireNonNull(policy, "policy"); + if (!command.binding().equals(policy.binding())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + } + } + } + + public record Capture(CommandSnapshot.Capture command, RealmPolicySnapshot.Capture policy) { + public Capture { + Objects.requireNonNull(command, "command"); + Objects.requireNonNull(policy, "policy"); + if (!Arrays.equals(command.operation().canonicalBytes(), policy.operation().canonicalBytes()) + || !command.snapshot().binding().equals(policy.snapshot().binding())) { + throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_BINDING_CONFLICT"); + } + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java new file mode 100644 index 0000000000..e330e02684 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import org.jooq.Record; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.ObjectMapper; + +/** Maps the actual immutable release row, never a launch descriptor or a mutable Version read. */ +final class PublicationReleaseContent { + private PublicationReleaseContent() {} + + static GameDesignPublicationTerminalEvidence.ReleaseContent fromRow(Record row) { + if (row == null + || !Boolean.FALSE.equals(row.get("script_only", Boolean.class)) + || row.get("script_patch_version", String.class) != null) { + throw new IllegalStateException("PUBLICATION_RELEASE_NOT_FULL_VERSION"); + } + var mapper = new ObjectMapper(); + List participants = + mapper.readValue( + row.get("participant_digests_json", String.class), new TypeReference<>() {}); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("published_release_bundle_ref", String.class), + row.get("version_number", Integer.class), + row.get("attestation_schema_version", String.class), + row.get("publish_workflow_id", String.class), + row.get("manifest_hash", String.class), + row.get("manifest_schema_version", Integer.class), + mapper.readValue( + row.get("artifact_digests_json", String.class), + new TypeReference>() {}), + mapper.readValue( + row.get("required_manifest_asset_keys_json", String.class), + new TypeReference>() {}), + participants.stream() + .map( + p -> + new GameDesignPublicationTerminalEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionId(), + p.appliedCommitId(), + p.contentDigest(), + p.digestSchemaVersion(), + p.abilitySchemaDigest(), + p.errorCode(), + p.errorMessage())) + .toList(), + mapper.readValue( + row.get("command_definitions_json", String.class), + new TypeReference>() {}), + row.get("generation_config_revision", String.class), + WorldPublishedStartLocationEvidence.fromStored( + row.get("world_published_start_location_evidence_json", String.class) + .getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java new file mode 100644 index 0000000000..edc8cc59da --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; + +/** Actual owner application result, returned only after the atomic source write/readback. */ +public record RealmPolicyApplication( + RealmPolicyGenesis genesis, + UUID inheritedCommitId, + String expectedEpoch, + RealmPolicySnapshot snapshot) { + public RealmPolicyApplication( + UUID inheritedCommitId, String expectedEpoch, RealmPolicySnapshot snapshot) { + this(null, inheritedCommitId, expectedEpoch, snapshot); + } + + public RealmPolicyApplication { + if ((inheritedCommitId == null && genesis == null) + || new UUID(0, 0).equals(inheritedCommitId) + || (genesis != null && !genesis.target().equals(snapshot.binding().target())) + || expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch())) { + throw new IllegalArgumentException("Policy application must advance its exact source epoch"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-realm-policy-application/v1"); + DraftAuthorizationFenceBinding.frame(out, genesis == null ? "false" : "true"); + DraftAuthorizationFenceBinding.frame( + out, genesis == null ? new byte[0] : genesis.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, inheritedCommitId == null ? "false" : "true"); + DraftAuthorizationFenceBinding.frame( + out, inheritedCommitId == null ? "" : inheritedCommitId.toString()); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public OwnerOutcome ownerOutcome() { + var binding = snapshot.binding(); + return new OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "realm-policy:" + binding.commitId(), + canonicalBytes(), + List.of( + new AppliedEpoch( + RealmPolicySource.SCOPE, + binding.target().canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + expectedEpoch, + snapshot.sourceEpoch()))); + } + + /** Parent composes actual sibling source evidence and its complete exact epoch vector once. */ + public OwnerOutcome combinedOwnerOutcome( + byte[] siblingEvidence, List completeEpochs) { + if (siblingEvidence == null || siblingEvidence.length == 0) { + throw new IllegalArgumentException("Actual sibling owner application evidence required"); + } + var binding = snapshot.binding(); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-control-plane-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, siblingEvidence); + return new OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "control-plane-source:" + binding.commitId(), + out.toByteArray(), + completeEpochs); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java new file mode 100644 index 0000000000..af88d5d246 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java @@ -0,0 +1,48 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; + +/** Empty new-Draft baseline receipt, distinct from every actual authored commit. */ +public record RealmPolicyGenesis(TargetProof target, UUID receiptId, String creationTransactionId) { + public RealmPolicyGenesis { + if (target == null + || receiptId == null + || new UUID(0, 0).equals(receiptId) + || creationTransactionId == null + || !creationTransactionId.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Exact persisted new-Draft genesis identity required"); + } + } + + public String canonicalJson() { + return RealmPolicySource.canonical( + Map.of( + "schema", + "game-design-realm-policy-genesis/v1", + "receiptId", + receiptId.toString(), + "creationTransactionId", + creationTransactionId, + "canonicalTenantId", + target.canonicalTenantId().toString(), + "canonicalVersionId", + target.canonicalVersionId().toString(), + "gameDesignVersionRowId", + Long.toString(target.gameDesignVersionRowId()), + "gameDesignVersionTenantKey", + target.gameDesignVersionTenantKey(), + "sourceGameRowId", + Long.toString(target.sourceGameRowId()), + "sourceGameTenantKey", + target.sourceGameTenantKey(), + "sourceProvenanceKind", + target.sourceProvenanceKind())); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java new file mode 100644 index 0000000000..6dd212cb71 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java @@ -0,0 +1,537 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** + * Internal immutable policy association; all writes join the actual Game Design seal transaction. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal owner storage collaborator.") +public final class RealmPolicyPublicationRepository { + private static final int MAX_POLICY_ROWS = RealmPolicySource.MAX_POLICIES; + private static final ObjectMapper JSON = new ObjectMapper(); + + private final DSLContext dsl; + + public RealmPolicyPublicationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** + * Retains an association only from the operation's actual sealed PUBLISHED owner readback. A + * release with no policy source/capture remains a valid unrelated release and creates no row. + */ + public Optional retainSealedPublished( + String publishWorkflowId) { + requireWrite(); + if (publishWorkflowId == null || publishWorkflowId.isBlank()) { + throw new IllegalArgumentException("Exact publication workflow required"); + } + var operationReadback = + new GameDesignPublicationOperationRepository(dsl) + .read(publishWorkflowId) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + if (!"PUBLISHED".equals(operationReadback.outcome()) + || operationReadback.terminalEvidenceBytes() == null) { + throw new IllegalStateException("POLICY_PUBLICATION_REQUIRES_SEALED_PUBLISHED_OPERATION"); + } + var operation = operationReadback.operation(); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(operationReadback.terminalEvidenceBytes()); + if (!operation.workflowId().equals(publishWorkflowId) + || terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operation.canonicalBytes())) { + throw new IllegalStateException("POLICY_PUBLICATION_TERMINAL_BINDING_CONFLICT"); + } + TargetProof target = operation.account().input().selection().target(); + var sourceRepository = new RealmPolicySourceRepository(dsl); + Optional captureResult = sourceRepository.readCapture(operation); + if (captureResult.isEmpty()) { + if (sourceExists(target) || selectedCommitDeclaresRealmPolicy(operation)) { + throw new IllegalStateException("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE"); + } + return Optional.empty(); + } + var capture = captureResult.orElseThrow(); + if (!capture.operation().equals(operation) + || !capture.snapshot().binding().target().equals(target)) { + throw new IllegalStateException("POLICY_PUBLICATION_CAPTURE_BINDING_CONFLICT"); + } + + var existing = + dsl.fetchOne( + "SELECT * FROM game_design_published_realm_policy_set " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (existing != null) { + var retained = readPublishedSet(target, existing).orElseThrow(); + requireExactRetry(retained, operation, capture, terminal); + return Optional.of(retained); + } + + requireOwner(target, terminal, true); + requireCurrentVisibleSource(target, capture.snapshot()); + requireActualRelease(operation, terminal); + + var release = terminal.releaseContent(); + var rows = new ArrayList(); + for (RealmPolicySource.Policy source : capture.snapshot().policies()) { + UUID id = UUID.randomUUID(); + rows.add( + new RealmPolicyPublishedEvidence.Policy( + id, + source, + RealmPolicyPublishedEvidence.policyDigest( + id, + target, + release.versionNumber(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + source))); + } + List orderedSources = + RealmPolicySource.ordered( + rows.stream().map(RealmPolicyPublishedEvidence.Policy::source).toList()); + if (!orderedSources.equals(capture.snapshot().policies()) + || rows.size() != capture.snapshot().policies().size()) { + throw new IllegalStateException("POLICY_PUBLICATION_SOURCE_SET_CHANGED"); + } + String setDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + release.versionNumber(), + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture.canonicalBytes(), + terminal.canonicalBytes(), + rows); + + dsl.execute( + "INSERT INTO game_design_published_realm_policy_set " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, version_number, " + + "source_commit_id, source_epoch, target_proof_json, operation_bytes, capture_bytes, " + + "terminal_evidence_bytes, release_content_bytes, published_release_bundle_ref, " + + "published_release_bundle_digest, publish_workflow_id, manifest_hash, " + + "publication_version_state_epoch, policy_count, policy_set_digest, sealed) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, FALSE)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + release.versionNumber(), + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + RealmPolicyPublishedEvidence.targetProofJson(target), + operation.canonicalBytes(), + capture.canonicalBytes(), + terminal.canonicalBytes(), + release.canonicalBytes(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + rows.size(), + setDigest); + + for (int ordinal = 0; ordinal < rows.size(); ordinal++) { + var row = rows.get(ordinal); + var source = row.source(); + var policy = source.policy(); + dsl.execute( + "INSERT INTO game_design_published_realm_policy " + + "(canonical_tenant_id, canonical_version_id, ordinal, realm_policy_id, " + + "source_commit_id, source_revision_id, logical_revision_id, world_slug, realm_slug, " + + "policy_json, policy_digest, visible, public_production) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + ordinal, + row.policyId(), + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + policy.worldSlug(), + policy.realmSlug(), + policy.canonicalJson(), + row.policyDigest(), + policy.visible(), + policy.publicProduction()); + } + int sealed = + dsl.execute( + "UPDATE game_design_published_realm_policy_set SET sealed = TRUE " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND sealed = FALSE", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (sealed != 1) throw new IllegalStateException("POLICY_PUBLICATION_SET_SEAL_CONFLICT"); + + var stored = + dsl.fetchOne( + "SELECT * FROM game_design_published_realm_policy_set " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (stored == null) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_READBACK_UNAVAILABLE"); + } + var readback = readPublishedSet(target, stored).orElseThrow(); + requireExactRetry(readback, operation, capture, terminal); + return Optional.of(readback); + } + + /** + * Caller supplies a REPEATABLE_READ snapshot; no caller state substitutes for stored evidence. + */ + public Optional readPublishedSet(TargetProof target) { + Objects.requireNonNull(target, "target"); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_published_realm_policy_set " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + return row == null ? Optional.empty() : readPublishedSet(target, row); + } + + private Optional readPublishedSet( + TargetProof target, Record header) { + if (!Boolean.TRUE.equals(header.get("sealed", Boolean.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_INCOMPLETE"); + } + if (!Objects.equals( + header.get("target_proof_json", String.class), + RealmPolicyPublishedEvidence.targetProofJson(target)) + || !Objects.equals( + header.get("canonical_tenant_id", UUID.class), target.canonicalTenantId()) + || !Objects.equals( + header.get("canonical_version_id", UUID.class), target.canonicalVersionId()) + || !Objects.equals( + header.get("game_design_version_row_id", Long.class), + target.gameDesignVersionRowId())) { + throw new IllegalStateException("POLICY_PUBLICATION_TARGET_PROOF_CONFLICT"); + } + + byte[] operationBytes = header.get("operation_bytes", byte[].class); + var operation = GameDesignPublicationOperation.fromStored(operationBytes); + if (!operation.account().input().selection().target().equals(target)) { + throw new IllegalStateException("POLICY_PUBLICATION_OPERATION_TARGET_CONFLICT"); + } + var operationReadback = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + if (!"PUBLISHED".equals(operationReadback.outcome()) + || !Arrays.equals(operationReadback.operation().canonicalBytes(), operationBytes)) { + throw new IllegalStateException("POLICY_PUBLICATION_OPERATION_NOT_SEALED"); + } + byte[] terminalBytes = operationReadback.terminalEvidenceBytes(); + byte[] retainedTerminalBytes = header.get("terminal_evidence_bytes", byte[].class); + if (terminalBytes == null || !Arrays.equals(terminalBytes, retainedTerminalBytes)) { + throw new IllegalStateException("POLICY_PUBLICATION_TERMINAL_CHANGED"); + } + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + var release = terminal.releaseContent(); + if (!Arrays.equals(release.canonicalBytes(), header.get("release_content_bytes", byte[].class)) + || !Objects.equals( + release.publishedReleaseBundleRef(), + header.get("published_release_bundle_ref", String.class)) + || !Objects.equals( + terminal.publishedReleaseBundleDigest(), + header.get("published_release_bundle_digest", String.class)) + || !Objects.equals( + release.publishWorkflowId(), header.get("publish_workflow_id", String.class)) + || !Objects.equals(release.manifestHash(), header.get("manifest_hash", String.class)) + || !Objects.equals( + terminal.publicationVersionStateEpoch(), + header.get("publication_version_state_epoch", Long.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_RELEASE_CONTENT_CHANGED"); + } + + Record version = requireOwner(target, terminal, false); + int versionNumber = header.get("version_number", Integer.class); + if (release.versionNumber() != versionNumber + || version.get("version_number", Integer.class) != versionNumber) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_NUMBER_CHANGED"); + } + var sourceRepository = new RealmPolicySourceRepository(dsl); + var capture = + sourceRepository + .readCapture(operation) + .orElseThrow(() -> new IllegalStateException("POLICY_PUBLICATION_CAPTURE_UNAVAILABLE")); + byte[] captureBytes = header.get("capture_bytes", byte[].class); + if (!Arrays.equals(capture.canonicalBytes(), captureBytes) + || !capture.snapshot().binding().target().equals(target) + || !Objects.equals( + capture.snapshot().binding().commitId(), header.get("source_commit_id", UUID.class)) + || !Objects.equals( + capture.snapshot().sourceEpoch(), header.get("source_epoch", String.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_CAPTURE_CHANGED"); + } + requireCurrentVisibleSource(target, capture.snapshot()); + + int expectedCount = header.get("policy_count", Integer.class); + if (expectedCount < 1 || expectedCount > MAX_POLICY_ROWS) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_OVERSIZED_OR_EMPTY"); + } + List storedRows = + dsl.fetch( + "SELECT * FROM game_design_published_realm_policy " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "ORDER BY ordinal LIMIT ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + MAX_POLICY_ROWS + 1); + if (storedRows.size() != expectedCount || storedRows.size() > MAX_POLICY_ROWS) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_CARDINALITY_CONFLICT"); + } + List policies = new ArrayList<>(); + for (int ordinal = 0; ordinal < storedRows.size(); ordinal++) { + Record row = storedRows.get(ordinal); + RealmPolicySource.Policy source = sourcePolicy(row); + if (!Objects.equals(row.get("ordinal", Integer.class), ordinal)) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_ORDER_CONFLICT"); + } + policies.add( + new RealmPolicyPublishedEvidence.Policy( + row.get("realm_policy_id", UUID.class), + source, + row.get("policy_digest", String.class))); + } + List expectedPolicies = capture.snapshot().policies(); + if (!expectedPolicies.equals( + policies.stream().map(RealmPolicyPublishedEvidence.Policy::source).toList())) { + throw new IllegalStateException("POLICY_PUBLICATION_SOURCE_ROWS_CHANGED"); + } + for (var policy : policies) { + String digest = + RealmPolicyPublishedEvidence.policyDigest( + policy.policyId(), + target, + versionNumber, + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + policy.source()); + if (!digest.equals(policy.policyDigest())) { + throw new IllegalStateException("POLICY_PUBLICATION_POLICY_DIGEST_CONFLICT"); + } + } + String setDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + versionNumber, + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operationBytes, + captureBytes, + terminalBytes, + policies); + if (!setDigest.equals(header.get("policy_set_digest", String.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_SET_DIGEST_CONFLICT"); + } + return Optional.of( + new RealmPolicyPublishedEvidence.PublishedSet( + target, + versionNumber, + capture.snapshot().binding().commitId(), + capture.snapshot().sourceEpoch(), + release.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operationBytes, + captureBytes, + terminalBytes, + expectedCount, + setDigest, + policies)); + } + + private RealmPolicySource.Policy sourcePolicy(Record row) { + RealmEntryPolicy policy = + RealmEntryPolicy.parseCanonical(row.get("policy_json", String.class), JSON); + if (!Objects.equals(row.get("world_slug", String.class), policy.worldSlug()) + || !Objects.equals(row.get("realm_slug", String.class), policy.realmSlug()) + || !Objects.equals(row.get("visible", Boolean.class), policy.visible()) + || !Objects.equals( + row.get("public_production", Boolean.class), policy.publicProduction())) { + throw new IllegalStateException("POLICY_PUBLICATION_TYPED_POLICY_CONFLICT"); + } + return new RealmPolicySource.Policy( + row.get("source_commit_id", UUID.class), + row.get("source_revision_id", UUID.class), + row.get("logical_revision_id", String.class), + policy); + } + + /** This reads without acquiring earlier publication locks; the seal already holds Version. */ + private Record requireOwner( + TargetProof target, GameDesignPublicationTerminalEvidence terminal, boolean atSeal) { + Record owner = + dsl.fetchOne( + "SELECT v.version_state, v.version_state_epoch, v.version_number, v.is_script_only, " + + "v.script_patch_version, v.base_version_id " + + "FROM version v JOIN game g ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? " + + "AND v.canonical_version_id = ? AND v.identity_source_game_row_id = ? " + + "AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? " + + "AND g.id = ? AND g.tenant_id = ? AND g.canonical_tenant_id = ? " + + "AND g.tenant_identity_provenance_kind = ? AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.canonicalTenantId(), + target.sourceProvenanceKind()); + if (owner == null + || !Boolean.FALSE.equals(owner.get("is_script_only", Boolean.class)) + || owner.get("script_patch_version", String.class) != null + || owner.get("base_version_id", Long.class) != null) { + throw new IllegalStateException("POLICY_PUBLICATION_CANONICAL_OWNER_UNAVAILABLE"); + } + String state = owner.get("version_state", String.class); + long epoch = owner.get("version_state_epoch", Long.class); + if (atSeal) { + if (!"PUBLISHED".equals(state) || epoch != terminal.publicationVersionStateEpoch()) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_NOT_AT_SEAL"); + } + } else if (("PUBLISHED".equals(state) && epoch != terminal.publicationVersionStateEpoch()) + || ("ACTIVE".equals(state) && epoch <= terminal.publicationVersionStateEpoch()) + || (!"PUBLISHED".equals(state) && !"ACTIVE".equals(state))) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_NOT_CURRENT"); + } + return owner; + } + + private void requireCurrentVisibleSource(TargetProof target, RealmPolicySnapshot snapshot) { + Record source = + dsl.fetchOne( + "SELECT source_epoch, visible_commit_id FROM game_design_realm_policy_source " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (source == null + || !Objects.equals(source.get("source_epoch", String.class), snapshot.sourceEpoch()) + || !Objects.equals( + source.get("visible_commit_id", UUID.class), snapshot.binding().commitId())) { + throw new IllegalStateException("POLICY_PUBLICATION_SOURCE_VISIBILITY_CHANGED"); + } + var fence = + new DraftCommitCoordinatorRepository(dsl) + .readVisibilityFence(target) + .orElseThrow( + () -> new IllegalStateException("POLICY_PUBLICATION_VISIBILITY_FENCE_UNAVAILABLE")); + if (!fence.commitId().equals(snapshot.binding().commitId()) + || !fence.requestId().equals(snapshot.binding().requestId()) + || !fence.inputDigest().equals(snapshot.binding().digest())) { + throw new IllegalStateException("POLICY_PUBLICATION_VISIBILITY_FENCE_CHANGED"); + } + } + + private void requireActualRelease( + GameDesignPublicationOperation operation, GameDesignPublicationTerminalEvidence terminal) { + Record row = + dsl.fetchOne( + "SELECT * FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + operation.tenantKey(), + operation.versionId()); + if (row == null) throw new IllegalStateException("POLICY_PUBLICATION_RELEASE_UNAVAILABLE"); + var release = PublicationReleaseContent.fromRow(row); + if (!Arrays.equals(release.canonicalBytes(), terminal.releaseContent().canonicalBytes()) + || !Objects.equals(row.get("publish_workflow_id", String.class), operation.workflowId()) + || !Objects.equals( + row.get("published_release_bundle_ref", String.class), + terminal.publishedReleaseBundleRef()) + || !Objects.equals(terminal.publishedReleaseBundleDigest(), release.contentDigest())) { + throw new IllegalStateException("POLICY_PUBLICATION_RELEASE_CONTENT_CONFLICT"); + } + } + + private boolean sourceExists(TargetProof target) { + return dsl.fetchExists( + dsl.selectOne() + .from("game_design_realm_policy_source") + .where( + "canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId())); + } + + private boolean selectedCommitDeclaresRealmPolicy(GameDesignPublicationOperation operation) { + return operation.account().input().selection().selectedCommit().revisions().stream() + .filter(revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) + .anyMatch( + revision -> { + JsonNode root = RealmPolicySource.tree(revision.payload()); + return root.path("revisionKind").isTextual() + && RealmEntryPolicy.REVISION_KIND.equals(root.path("revisionKind").asText()); + }); + } + + private void requireExactRetry( + RealmPolicyPublishedEvidence.PublishedSet retained, + GameDesignPublicationOperation operation, + RealmPolicySnapshot.Capture capture, + GameDesignPublicationTerminalEvidence terminal) { + if (!Arrays.equals(retained.operationBytes(), operation.canonicalBytes()) + || !Arrays.equals(retained.captureBytes(), capture.canonicalBytes()) + || !Arrays.equals(retained.terminalEvidenceBytes(), terminal.canonicalBytes())) { + throw new IllegalStateException("POLICY_PUBLICATION_IDENTITY_CONFLICT"); + } + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Published policy association requires the owner READ_COMMITTED seal transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java new file mode 100644 index 0000000000..496d2113a7 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java @@ -0,0 +1,281 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; + +/** Immutable internal evidence associating a frozen source set with its actual sealed release. */ +public final class RealmPolicyPublishedEvidence { + public static final String SET_DIGEST_SCHEMA = "game-design-published-realm-policy-set/v1"; + public static final String POLICY_DIGEST_SCHEMA = "game-design-published-realm-policy/v1"; + + private RealmPolicyPublishedEvidence() {} + + /** One Game Design allocated immutable identity for one effective authored policy. */ + public record Policy(UUID policyId, RealmPolicySource.Policy source, String policyDigest) { + public Policy { + nonNil(policyId, "policyId"); + Objects.requireNonNull(source, "source"); + if (policyDigest == null || !policyDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical policy digest required"); + } + } + } + + /** Complete immutable set and the original owner evidence that authorized its publication. */ + public record PublishedSet( + DraftCommitBinding.TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + int policyCount, + String policySetDigest, + List policies) { + public PublishedSet { + Objects.requireNonNull(target, "target"); + nonNil(sourceCommitId, "sourceCommitId"); + if (versionNumber <= 0 + || sourceEpoch == null + || !sourceEpoch.matches("0|[1-9][0-9]*") + || publishedReleaseBundleRef == null + || publishedReleaseBundleRef.isBlank() + || !digest(publishedReleaseBundleDigest) + || publishWorkflowId == null + || publishWorkflowId.isBlank() + || !digest(manifestHash) + || publicationVersionStateEpoch <= 0) { + throw new IllegalArgumentException("Complete publication-bound policy identity required"); + } + operationBytes = nonEmptyCopy(operationBytes, "operationBytes"); + captureBytes = nonEmptyCopy(captureBytes, "captureBytes"); + terminalEvidenceBytes = nonEmptyCopy(terminalEvidenceBytes, "terminalEvidenceBytes"); + policies = List.copyOf(Objects.requireNonNull(policies, "policies")); + if (policyCount < 1 + || policyCount > RealmPolicySource.MAX_POLICIES + || policyCount != policies.size() + || !digest(policySetDigest)) { + throw new IllegalArgumentException("Complete bounded policy-set evidence required"); + } + RealmPolicySource.ordered(policies.stream().map(Policy::source).toList()); + var operation = GameDesignPublicationOperation.fromStored(operationBytes); + if (!operation.account().input().selection().target().equals(target) + || !operation.workflowId().equals(publishWorkflowId)) { + throw new IllegalArgumentException("Publication evidence differs from exact TargetProof"); + } + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalEvidenceBytes); + var release = terminal.releaseContent(); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operationBytes) + || !release.canonicalTenantId().equals(target.canonicalTenantId()) + || !release.canonicalVersionId().equals(target.canonicalVersionId()) + || release.versionNumber() != versionNumber + || !release.publishedReleaseBundleRef().equals(publishedReleaseBundleRef) + || !release.contentDigest().equals(publishedReleaseBundleDigest) + || !release.publishWorkflowId().equals(publishWorkflowId) + || !release.manifestHash().equals(manifestHash) + || terminal.publicationVersionStateEpoch() != publicationVersionStateEpoch) { + throw new IllegalArgumentException("Terminal release evidence differs from policy set"); + } + if (!computePolicySetDigest( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policies) + .equals(policySetDigest)) { + throw new IllegalArgumentException("Published policy-set digest differs from evidence"); + } + } + + @Override + public byte[] operationBytes() { + return operationBytes.clone(); + } + + @Override + public byte[] captureBytes() { + return captureBytes.clone(); + } + + @Override + public byte[] terminalEvidenceBytes() { + return terminalEvidenceBytes.clone(); + } + + @Override + public List policies() { + return List.copyOf(policies); + } + } + + public static String targetProofJson(DraftCommitBinding.TargetProof target) { + Objects.requireNonNull(target, "target"); + return RealmPolicySource.canonical( + Map.of( + "canonicalTenantId", target.canonicalTenantId().toString(), + "canonicalVersionId", target.canonicalVersionId().toString(), + "gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId()), + "gameDesignVersionTenantKey", target.gameDesignVersionTenantKey(), + "sourceGameRowId", Long.toString(target.sourceGameRowId()), + "sourceGameTenantKey", target.sourceGameTenantKey(), + "sourceProvenanceKind", target.sourceProvenanceKind())); + } + + public static String policyDigest( + UUID policyId, + DraftCommitBinding.TargetProof target, + int versionNumber, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + RealmPolicySource.Policy source) { + nonNil(policyId, "policyId"); + Objects.requireNonNull(source, "source"); + String evidence = + RealmPolicySource.canonical( + map( + "schema", + POLICY_DIGEST_SCHEMA, + "policyId", + policyId.toString(), + "target", + RealmPolicySource.tree(targetProofJson(target)), + "versionNumber", + versionNumber, + "sourceCommitId", + source.commitId().toString(), + "sourceRevisionId", + source.revisionId().toString(), + "logicalRevisionId", + source.logicalRevisionId(), + "publishedReleaseBundleRef", + publishedReleaseBundleRef, + "publishedReleaseBundleDigest", + publishedReleaseBundleDigest, + "publishWorkflowId", + publishWorkflowId, + "manifestHash", + manifestHash, + "policy", + RealmPolicySource.tree(source.policy().canonicalJson()))); + return sha256(evidence.getBytes(StandardCharsets.UTF_8)); + } + + public static String computePolicySetDigest( + DraftCommitBinding.TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + List policies) { + var ordered = RealmPolicySource.ordered(policies.stream().map(Policy::source).toList()); + if (ordered.size() != policies.size()) { + throw new IllegalArgumentException("Canonical policy order required"); + } + var bySource = + policies.stream().collect(java.util.stream.Collectors.toMap(Policy::source, p -> p)); + var orderedEvidence = + ordered.stream() + .map( + source -> { + Policy policy = bySource.get(source); + return Map.of( + "policyId", policy.policyId().toString(), + "sourceCommitId", source.commitId().toString(), + "sourceRevisionId", source.revisionId().toString(), + "logicalRevisionId", source.logicalRevisionId(), + "worldSlug", source.policy().worldSlug(), + "realmSlug", source.policy().realmSlug(), + "policyDigest", policy.policyDigest()); + }) + .toList(); + String evidence = + RealmPolicySource.canonical( + map( + "schema", SET_DIGEST_SCHEMA, + "target", RealmPolicySource.tree(targetProofJson(target)), + "versionNumber", versionNumber, + "sourceCommitId", sourceCommitId.toString(), + "sourceEpoch", sourceEpoch, + "publishedReleaseBundleRef", publishedReleaseBundleRef, + "publishedReleaseBundleDigest", publishedReleaseBundleDigest, + "publishWorkflowId", publishWorkflowId, + "manifestHash", manifestHash, + "publicationVersionStateEpoch", Long.toString(publicationVersionStateEpoch), + "operationDigest", sha256(operationBytes), + "captureDigest", sha256(captureBytes), + "terminalEvidenceDigest", sha256(terminalEvidenceBytes), + "policyCount", orderedEvidence.size(), + "policies", orderedEvidence)); + return sha256(evidence.getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] nonEmptyCopy(byte[] bytes, String name) { + if (bytes == null || bytes.length == 0) { + throw new IllegalArgumentException("Nonempty " + name + " required"); + } + return bytes.clone(); + } + + private static Map map(Object... entries) { + if (entries.length % 2 != 0) { + throw new IllegalArgumentException("Even evidence key/value entries required"); + } + var result = new java.util.LinkedHashMap(); + for (int index = 0; index < entries.length; index += 2) { + result.put((String) entries[index], entries[index + 1]); + } + return result; + } + + private static boolean digest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void nonNil(UUID value, String name) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("Non-nil " + name + " required"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java new file mode 100644 index 0000000000..a024a75b5a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Complete effective source at one synchronized fence, including original revision provenance. */ +public record RealmPolicySnapshot( + DraftCommitBinding binding, String sourceEpoch, List policies) { + public RealmPolicySnapshot { + if (binding == null || sourceEpoch == null || !sourceEpoch.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("Exact source binding and canonical epoch required"); + } + policies = RealmPolicySource.draftOrdered(policies); + } + + @Override + public List policies() { + return List.copyOf(policies); + } + + public String canonicalJson() { + return RealmPolicySource.canonical( + Map.of( + "schema", + "game-design-realm-policy-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "policies", + RealmPolicySource.tree(RealmPolicySource.policiesJson(policies)))); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public static RealmPolicySnapshot fromStored(String json) { + var node = RealmPolicySource.tree(json); + RealmPolicySource.fields( + node, "schema", "bindingJson", "bindingDigest", "sourceEpoch", "policies"); + if (!"game-design-realm-policy-snapshot/v1".equals(RealmPolicySource.text(node, "schema"))) { + throw new IllegalArgumentException("Unsupported policy snapshot schema"); + } + var result = + new RealmPolicySnapshot( + DraftCommitBinding.fromStored( + RealmPolicySource.text(node, "bindingJson"), + RealmPolicySource.text(node, "bindingDigest")), + RealmPolicySource.text(node, "sourceEpoch"), + RealmPolicySource.policiesFromStored(node.get("policies").toString())); + if (!result.canonicalJson().equals(json)) + throw new IllegalArgumentException("Policy snapshot bytes changed"); + return result; + } + + /** Frozen source only. No terminal association or PUBLISHED claim is represented here. */ + public record Capture(GameDesignPublicationOperation operation, RealmPolicySnapshot snapshot) { + public Capture { + RealmPolicySource.ordered(snapshot.policies()); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) { + throw new IllegalArgumentException( + "Frozen policy snapshot differs from original selected commit"); + } + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-realm-policy-source-capture/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java new file mode 100644 index 0000000000..504e5cc3e9 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java @@ -0,0 +1,192 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Owner-local typed source; neither these bytes nor a caller's declaration grant authority. */ +public final class RealmPolicySource { + private static final ObjectMapper JSON = new ObjectMapper(); + public static final String SCOPE = "REALM_ENTRY_POLICY_SET"; + public static final int MAX_POLICIES = 128; + + private RealmPolicySource() {} + + /** Original authored UUID and logical identity survive every inherited snapshot. */ + public record Policy( + UUID commitId, UUID revisionId, String logicalRevisionId, RealmEntryPolicy policy) { + public Policy { + nonNil(commitId); + nonNil(revisionId); + if (logicalRevisionId == null + || logicalRevisionId.isBlank() + || logicalRevisionId.length() > 128 + || !StandardCharsets.UTF_8.newEncoder().canEncode(logicalRevisionId)) { + throw new IllegalArgumentException("Exact authored logical revision identity required"); + } + policy = RealmEntryPolicy.parseCanonical(policy.canonicalJson(), JSON); + } + } + + /** Closed owner payload, distinct from the policy JSON itself. */ + public static boolean isPolicyRevision(DraftCommitBinding.RevisionPayload input) { + var kind = text(tree(input.payload()), "revisionKind"); + if (RealmEntryPolicy.REVISION_KIND.equals(kind)) return true; + if ("COMMAND_DEFINITION".equals(kind)) return false; + throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); + } + + public static Policy revision( + DraftCommitBinding binding, DraftCommitBinding.RevisionPayload input) { + if (input.owner() != DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) { + throw new IllegalArgumentException("Policy revision belongs to Game Design control plane"); + } + JsonNode root = tree(input.payload()); + fields(root, "revisionKind", "logicalRevisionId", "policy"); + if (!RealmEntryPolicy.REVISION_KIND.equals(text(root, "revisionKind"))) { + throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); + } + return new Policy( + binding.commitId(), + input.revisionId(), + text(root, "logicalRevisionId"), + RealmEntryPolicy.parse(root.get("policy").toString(), JSON)); + } + + public static List effective(List inherited, List updates) { + Map policies = new LinkedHashMap<>(); + for (Policy policy : draftOrdered(inherited)) policies.put(selector(policy), policy); + var seen = new HashSet(); + for (Policy policy : updates) { + if (!seen.add(selector(policy))) { + throw new IllegalArgumentException("A commit repeats a policy selector"); + } + policies.put(selector(policy), policy); + } + return draftOrdered(new ArrayList<>(policies.values())); + } + + public static List ordered(List policies) { + var ordered = draftOrdered(policies); + if (policies.isEmpty() || policies.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Complete policy set must contain 1 through 128 policies"); + } + int production = 0; + for (Policy policy : policies) { + if (policy.policy().visible() && policy.policy().publicProduction()) production++; + } + if (production != 1) { + throw new IllegalArgumentException("Exactly one visible public-production realm required"); + } + return ordered; + } + + /** Draft source may be empty or not yet publication-complete. */ + public static List draftOrdered(List policies) { + if (policies.size() > MAX_POLICIES) + throw new IllegalArgumentException("Draft policy set exceeds 128 policies"); + var realms = new HashSet(); + var revisions = new HashSet(); + for (Policy policy : policies) { + if (!realms.add(policy.policy().realmSlug()) || !revisions.add(policy.revisionId())) { + throw new IllegalArgumentException("Duplicate tenant realm selector or authored revision"); + } + } + return policies.stream() + .sorted( + Comparator.comparing((Policy p) -> p.policy().worldSlug()) + .thenComparing(p -> p.policy().realmSlug())) + .toList(); + } + + static String policiesJson(List policies) { + return canonical( + draftOrdered(policies).stream() + .map( + policy -> + Map.of( + "commitId", + policy.commitId().toString(), + "revisionId", + policy.revisionId().toString(), + "logicalRevisionId", + policy.logicalRevisionId(), + "policy", + tree(policy.policy().canonicalJson()))) + .toList()); + } + + static List policiesFromStored(String bytes) { + JsonNode root = tree(bytes); + if (!root.isArray() || root.size() > MAX_POLICIES) { + throw new IllegalArgumentException("Complete stored policy array required"); + } + var policies = new ArrayList(); + for (JsonNode node : root) { + fields(node, "commitId", "revisionId", "logicalRevisionId", "policy"); + policies.add( + new Policy( + UUID.fromString(text(node, "commitId")), + UUID.fromString(text(node, "revisionId")), + text(node, "logicalRevisionId"), + RealmEntryPolicy.parseCanonical(node.get("policy").toString(), JSON))); + } + var result = draftOrdered(policies); + if (!policiesJson(result).equals(bytes)) { + throw new IllegalArgumentException("Stored policy snapshot is not canonical"); + } + return result; + } + + static String canonical(Object value) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } catch (IOException failure) { + throw new IllegalArgumentException("Canonical owner source encoding failed", failure); + } + } + + static JsonNode tree(String value) { + try { + return JSON.readTree(Rfc8785CanonicalJson.canonicalizeUtf8(value)); + } catch (IOException | RuntimeException failure) { + throw new IllegalArgumentException("Unambiguous owner source JSON required", failure); + } + } + + static void fields(JsonNode node, String... fields) { + if (!node.isObject() || node.size() != fields.length) { + throw new IllegalArgumentException("Closed owner source fields required"); + } + for (String field : fields) + if (!node.has(field)) throw new IllegalArgumentException("Missing " + field); + } + + static String text(JsonNode node, String field) { + if (!node.path(field).isTextual()) + throw new IllegalArgumentException("Text required: " + field); + return node.get(field).asText(); + } + + private static String selector(Policy policy) { + return policy.policy().worldSlug() + "/" + policy.policy().realmSlug(); + } + + private static void nonNil(UUID value) { + if (value == null || new UUID(0, 0).equals(value)) + throw new IllegalArgumentException("Non-nil authored UUID required"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java new file mode 100644 index 0000000000..a68f69c8e1 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java @@ -0,0 +1,607 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal owner storage, with no runtime registration or creator authorization. Missing actual + * source baseline denies. Empty genesis can only be enrolled in the actual Version insert + * transaction. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal owner storage collaborator.") +public final class RealmPolicySourceRepository { + private final DSLContext dsl; + + public RealmPolicySourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Parent invokes only from the new Version insert branch, in that same owner transaction. */ + public RealmPolicyGenesis recordFreshGenesis(TargetProof target) { + requireWrite(); + lockAuthority(target); + var prior = readGenesis(target); + if (prior.isPresent()) return prior.orElseThrow(); + requireDraftAndUnfrozen(target); + var witness = + dsl.fetchOne( + "SELECT creation_transaction_id FROM game_design_realm_policy_version_insert " + + "WHERE version_id = ? AND creation_transaction_id = pg_current_xact_id()::TEXT", + target.gameDesignVersionRowId()); + if (witness == null) + throw new IllegalStateException("POLICY_FRESH_VERSION_INSERT_PROOF_UNAVAILABLE"); + var receipt = new RealmPolicyGenesis(target, UUID.randomUUID(), witness.get(0, String.class)); + dsl.execute( + "INSERT INTO game_design_realm_policy_genesis " + + "(canonical_tenant_id, canonical_version_id, receipt_id, version_id, creation_transaction_id, receipt_json) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + receipt.receiptId(), + target.gameDesignVersionRowId(), + receipt.creationTransactionId(), + receipt.canonicalJson()); + dsl.execute( + "INSERT INTO game_design_realm_policy_source " + + "(canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id, genesis_receipt_id) VALUES (?, ?, '0', NULL, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + receipt.receiptId()); + return readGenesis(target).orElseThrow(); + } + + public Optional readGenesis(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_genesis WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + var receipt = + new RealmPolicyGenesis( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class)); + if (!receipt.canonicalJson().equals(row.get("receipt_json", String.class)) + || target.gameDesignVersionRowId() != row.get("version_id", Long.class)) { + throw new IllegalStateException("POLICY_GENESIS_TARGET_CONFLICT"); + } + return Optional.of(receipt); + } + + /** Caller must already own the authorized coordinator application slot. */ + public RealmPolicyApplication apply(DraftCommitBinding binding) { + requirePolicyOnly(binding); + var result = applyMutation(binding); + recordCompleteOwnerOutcome(binding, result.ownerOutcome()); + return result; + } + + /** + * Stages only policy mutation evidence; parent records one complete owner outcome before commit. + */ + public RealmPolicyApplication applyMutation(DraftCommitBinding binding) { + requireWrite(); + lockAuthority(binding.target()); + exactCommit(binding); + var prior = application(binding); + if (prior.isPresent()) { + var result = prior.orElseThrow(); + return result; + } + requireDraftAndUnfrozen(binding.target()); + if (dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()) + != null) { + throw new IllegalStateException("POLICY_PUBLICATION_SELECTION_ALREADY_RESERVED"); + } + var coordinator = new DraftCommitCoordinatorRepository(dsl); + var slot = + coordinator + .readApplicationSlot(binding.target()) + .orElseThrow(() -> new IllegalStateException("POLICY_APPLICATION_SLOT_UNAVAILABLE")); + if (!slot.requestId().equals(binding.requestId()) + || !slot.commitId().equals(binding.commitId())) { + throw new IllegalStateException("POLICY_APPLICATION_SLOT_CHANGED"); + } + var state = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (state == null + || (state.status() != DraftCommitCoordinatorRepository.OwnerStatus.IN_PROGRESS + && state.status() != DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN)) { + throw new IllegalStateException("POLICY_OWNER_APPLICATION_NOT_STARTED"); + } + var source = source(binding.target()); + UUID inherited = source.get("visible_commit_id", UUID.class); + String epoch = source.get("source_epoch", String.class); + var genesis = + source.get("genesis_receipt_id", UUID.class) == null + ? null + : readGenesis(binding.target()).orElseThrow(); + if (genesis != null + && !genesis.receiptId().equals(source.get("genesis_receipt_id", UUID.class))) { + throw new IllegalStateException("POLICY_GENESIS_SOURCE_CONFLICT"); + } + List inheritedPolicies; + if (inherited == null) { + if (genesis == null + || !"0".equals(epoch) + || new DraftCommitCoordinatorRepository(dsl) + .readVisibilityFence(binding.target()) + .isPresent()) { + throw new IllegalStateException("POLICY_SOURCE_GENESIS_NOT_CURRENT"); + } + inheritedPolicies = List.of(); + } else { + requireCurrentFence(binding.target(), inherited); + var previous = readSnapshot(binding.target(), inherited).orElseThrow(); + if (!previous.sourceEpoch().equals(epoch)) + throw new IllegalStateException("POLICY_SOURCE_UNSYNCHRONIZED"); + inheritedPolicies = previous.policies(); + } + var units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(u -> RealmPolicySource.SCOPE.equals(u.aggregateType())) + .toList(); + if (units.size() != 1 + || !RealmPolicySource.SCOPE.equals(units.getFirst().aggregateType()) + || !binding.target().canonicalVersionId().toString().equals(units.getFirst().aggregateId()) + || !RealmPolicySource.SCOPE.equals(units.getFirst().scopeType()) + || !"effective".equals(units.getFirst().scopeId()) + || !epoch.equals(units.getFirst().expectedEpoch())) { + throw new IllegalArgumentException( + "Complete policy-set containing scope and exact epoch required"); + } + var updates = + binding.revisions().stream() + .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .filter(RealmPolicySource::isPolicyRevision) + .map(r -> RealmPolicySource.revision(binding, r)) + .toList(); + if (updates.isEmpty()) + throw new IllegalArgumentException("Typed authored policy revisions required"); + for (var update : updates) { + if (dsl.fetchExists( + dsl.selectOne() + .from("game_design_realm_policy_application") + .where( + "canonical_tenant_id = ? AND canonical_version_id = ? AND snapshot_json::jsonb -> 'policies' @> ?::jsonb", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + RealmPolicySource.canonical( + List.of(java.util.Map.of("revisionId", update.revisionId().toString())))))) { + throw new IllegalArgumentException("Authored policy revision identity cannot be reused"); + } + if (inheritedPolicies.stream().anyMatch(p -> p.revisionId().equals(update.revisionId()))) { + throw new IllegalArgumentException("Authored baseline revision identity cannot be reused"); + } + } + var snapshot = + new RealmPolicySnapshot( + binding, + new BigInteger(epoch).add(BigInteger.ONE).toString(), + RealmPolicySource.effective(inheritedPolicies, updates)); + var result = new RealmPolicyApplication(genesis, inherited, epoch, snapshot); + int advanced = + dsl.execute( + "UPDATE game_design_realm_policy_source SET source_epoch = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID)", + snapshot.sourceEpoch(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + epoch, + inherited); + if (advanced != 1) throw new IllegalStateException("POLICY_SOURCE_EPOCH_CONFLICT"); + dsl.execute( + "INSERT INTO game_design_realm_policy_application " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, inherited_commit_id, genesis_receipt_id, expected_epoch, snapshot_json, result_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + inherited, + genesis == null ? null : genesis.receiptId(), + epoch, + snapshot.canonicalJson(), + result.canonicalBytes()); + var retained = application(binding).orElseThrow(); + return retained; + } + + /** Parent supplies actual sibling evidence and every exact owned epoch to one shared result. */ + public void recordCombinedOwnerOutcome( + DraftCommitBinding binding, + byte[] siblingEvidence, + List completeEpochs) { + requireWrite(); + lockAuthority(binding.target()); + var result = application(binding).orElseThrow(); + recordCompleteOwnerOutcome( + binding, result.combinedOwnerOutcome(siblingEvidence, completeEpochs)); + } + + private void recordCompleteOwnerOutcome( + DraftCommitBinding binding, DraftCommitCoordinatorRepository.OwnerOutcome outcome) { + requireWrite(); + var row = + dsl.fetchOne( + "SELECT owner_result_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) throw new IllegalStateException("POLICY_OWNER_APPLICATION_UNAVAILABLE"); + byte[] previous = row.get(0, byte[].class); + if (previous != null && !Arrays.equals(previous, outcome.resultBytes())) { + throw new IllegalArgumentException("POLICY_COMPLETE_OWNER_RESULT_CHANGED"); + } + new DraftCommitCoordinatorRepository(dsl).recordOwnerOutcome(binding, outcome); + if (previous == null) + dsl.execute( + "UPDATE game_design_realm_policy_application SET owner_result_bytes = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + outcome.resultBytes(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + requireCoordinatorResult(application(binding).orElseThrow()); + } + + private static void requirePolicyOnly(DraftCommitBinding binding) { + if (binding.revisions().stream() + .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .anyMatch(r -> !RealmPolicySource.isPolicyRevision(r)) + || binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .anyMatch(u -> !RealmPolicySource.SCOPE.equals(u.aggregateType()))) { + throw new IllegalArgumentException( + "Mixed Game Design commit requires one combined owner result"); + } + } + + /** + * Invoke in the transaction that advances the coordinator fence, before releasing its slot. A + * disjoint synchronized commit inherits the last complete snapshot; staged owner rows never + * become visible. Absence of a baseline is a denial, including for retained content. + */ + public RealmPolicySnapshot captureSynchronized(DraftCommitBinding binding) { + requireWrite(); + lockAuthority(binding.target()); + exactCommit(binding); + requireCurrentFence(binding.target(), binding.commitId()); + var existing = readSnapshot(binding.target(), binding.commitId()); + if (existing.isPresent()) { + if (!existing.orElseThrow().binding().equals(binding)) + throw new IllegalStateException("POLICY_SNAPSHOT_BINDING_CONFLICT"); + return existing.orElseThrow(); + } + requireDraftAndUnfrozen(binding.target()); + var source = source(binding.target()); + UUID previousCommit = source.get("visible_commit_id", UUID.class); + var previous = + previousCommit == null + ? null + : readSnapshot(binding.target(), previousCommit).orElseThrow(); + if (previous == null + && (source.get("genesis_receipt_id", UUID.class) == null + || readGenesis(binding.target()).isEmpty())) { + throw new IllegalStateException("POLICY_SOURCE_BASELINE_UNAVAILABLE"); + } + var applied = application(binding); + RealmPolicySnapshot snapshot; + if (binding.revisions().stream() + .anyMatch( + r -> + r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE + && RealmPolicySource.isPolicyRevision(r))) { + var result = + applied.orElseThrow(() -> new IllegalStateException("POLICY_OWNER_RESULT_UNAVAILABLE")); + requireCoordinatorResult(result); + if (!Objects.equals(result.inheritedCommitId(), previousCommit)) { + throw new IllegalStateException("POLICY_SNAPSHOT_PREDECESSOR_CHANGED"); + } + snapshot = result.snapshot(); + } else { + snapshot = + new RealmPolicySnapshot( + binding, + previous == null ? "0" : previous.sourceEpoch(), + previous == null ? List.of() : previous.policies()); + } + if (!snapshot.sourceEpoch().equals(source.get("source_epoch", String.class))) { + throw new IllegalStateException("PARTIAL_POLICY_OWNER_WRITE_NOT_VISIBLE"); + } + dsl.execute( + "INSERT INTO game_design_realm_policy_snapshot " + + "(canonical_tenant_id, canonical_version_id, commit_id, request_id, inherited_commit_id, snapshot_json) VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + previousCommit, + snapshot.canonicalJson()); + dsl.execute( + "UPDATE game_design_realm_policy_source SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + return readSnapshot(binding.target(), binding.commitId()).orElseThrow(); + } + + public RealmPolicySnapshot.Capture freeze(GameDesignPublicationOperation operation) { + requireWrite(); + var selection = operation.account().input().selection(); + var target = selection.target(); + lockAuthority(target); + var existing = readCapture(operation); + if (existing.isPresent()) return existing.orElseThrow(); + requireDraftAndUnfrozen(target); + var row = + dsl.fetchOne( + "SELECT selection_json, selection_digest FROM game_design_authored_draft_publish_selection " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null + || !selection.canonicalJson().equals(row.get("selection_json", String.class)) + || !selection.digest().equals(row.get("selection_digest", String.class))) { + throw new IllegalStateException("POLICY_PUBLICATION_SELECTION_UNAVAILABLE"); + } + // The Version lock serializes this check with the owner finalizer. Do not acquire its earlier + // game/attempt locks after the Version lock and invert the existing publication lock order. + var retainedOperation = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(); + GameDesignPublicationOperationRepository.exact(retainedOperation.operation(), operation); + if (!"PENDING".equals(retainedOperation.outcome())) + throw new IllegalStateException("POLICY_PUBLICATION_OPERATION_SEALED"); + var versionEpoch = + dsl.fetchOne( + "SELECT version_state_epoch FROM version WHERE id = ?", + target.gameDesignVersionRowId()); + Long persistedEpoch = versionEpoch == null ? null : versionEpoch.get(0, Long.class); + if (persistedEpoch == null || persistedEpoch <= 0) { + throw new IllegalStateException("POLICY_PUBLICATION_VERSION_EPOCH_UNAVAILABLE"); + } + if (!selection.intent().expectedVersionStateEpoch().equals(Long.toString(persistedEpoch))) { + throw new IllegalStateException("POLICY_PUBLICATION_DRAFT_EPOCH_CHANGED"); + } + requireCurrentFence(target, selection.selectedCommit().commitId()); + var source = source(target); + var snapshot = readSnapshot(target, selection.selectedCommit().commitId()).orElseThrow(); + if (!source.get("visible_commit_id", UUID.class).equals(snapshot.binding().commitId()) + || !source.get("source_epoch", String.class).equals(snapshot.sourceEpoch())) { + throw new IllegalStateException("POLICY_FROZEN_SOURCE_NOT_SYNCHRONIZED"); + } + var capture = new RealmPolicySnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_realm_policy_capture " + + "(canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, operation_bytes, capture_bytes) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + operation.workflowId(), + snapshot.binding().commitId(), + operation.canonicalBytes(), + capture.canonicalBytes()); + return readCapture(operation).orElseThrow(); + } + + public Optional readCapture( + GameDesignPublicationOperation operation) { + var target = operation.account().input().selection().target(); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !operation.workflowId().equals(row.get("publish_workflow_id", String.class))) { + throw new IllegalArgumentException("POLICY_FREEZE_OPERATION_CONFLICT"); + } + var snapshot = readSnapshot(target, row.get("commit_id", UUID.class)).orElseThrow(); + var capture = new RealmPolicySnapshot.Capture(operation, snapshot); + if (!Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class))) { + throw new IllegalStateException("POLICY_CAPTURE_STORAGE_CONFLICT"); + } + return Optional.of(capture); + } + + public Optional readSnapshot(TargetProof target, UUID commitId) { + var row = + dsl.fetchOne( + "SELECT snapshot_json FROM game_design_realm_policy_snapshot WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId); + if (row == null) return Optional.empty(); + var snapshot = RealmPolicySnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId)) { + throw new IllegalStateException("POLICY_SNAPSHOT_OWNER_CONFLICT"); + } + exactCommit(snapshot.binding()); + var fence = + dsl.fetchOne( + "SELECT input_digest FROM game_design_draft_commit_visibility_fence " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ? AND request_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId, + snapshot.binding().requestId()); + if (fence == null + || !snapshot.binding().digest().equals(fence.get("input_digest", String.class))) { + throw new IllegalStateException("POLICY_SNAPSHOT_SYNCHRONIZED_FENCE_UNAVAILABLE"); + } + for (var policy : snapshot.policies()) { + var authored = + dsl.fetchOne( + "SELECT binding_json, input_digest FROM game_design_draft_commit " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + policy.commitId()); + if (authored == null) + throw new IllegalStateException("POLICY_AUTHORED_PROVENANCE_UNAVAILABLE"); + var binding = + DraftCommitBinding.fromStored( + authored.get("binding_json", String.class), + authored.get("input_digest", String.class)); + var revision = + binding.revisions().stream() + .filter(r -> r.revisionId().equals(policy.revisionId())) + .findFirst() + .orElseThrow(); + if (!binding.target().equals(target) + || !RealmPolicySource.revision(binding, revision).equals(policy)) { + throw new IllegalStateException("POLICY_AUTHORED_PROVENANCE_CHANGED"); + } + } + return Optional.of(snapshot); + } + + private Optional application(DraftCommitBinding binding) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) return Optional.empty(); + var result = + new RealmPolicyApplication( + row.get("genesis_receipt_id", UUID.class) == null + ? null + : readGenesis(binding.target()).orElseThrow(), + row.get("inherited_commit_id", UUID.class), + row.get("expected_epoch", String.class), + RealmPolicySnapshot.fromStored(row.get("snapshot_json", String.class))); + if (!result.snapshot().binding().equals(binding) + || !binding.requestId().equals(row.get("request_id", UUID.class)) + || !Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class))) { + throw new IllegalStateException("POLICY_APPLICATION_EXACT_BINDING_CONFLICT"); + } + return Optional.of(result); + } + + private void requireCoordinatorResult(RealmPolicyApplication result) { + var binding = result.snapshot().binding(); + var state = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + var stored = + dsl.fetchOne( + "SELECT owner_result_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (state == null + || state.outcome().isEmpty() + || stored == null + || !Arrays.equals(state.outcome().orElseThrow().resultBytes(), stored.get(0, byte[].class)) + || !state + .outcome() + .orElseThrow() + .appliedEpochs() + .contains(result.ownerOutcome().appliedEpochs().getFirst())) { + throw new IllegalStateException("POLICY_COORDINATOR_RESULT_CONFLICT"); + } + } + + private Record source(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_realm_policy_source WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) throw new IllegalStateException("POLICY_SOURCE_BASELINE_UNAVAILABLE"); + return row; + } + + private void requireCurrentFence(TargetProof target, UUID commitId) { + var current = + new DraftCommitCoordinatorRepository(dsl).readVisibilityFence(target).orElseThrow(); + if (!current.commitId().equals(commitId)) + throw new IllegalStateException("POLICY_VISIBLE_FENCE_CHANGED"); + } + + private void exactCommit(DraftCommitBinding binding) { + var retained = + new DraftCommitCoordinatorRepository(dsl) + .read(binding.target(), binding.requestId()) + .orElseThrow(); + if (!retained.binding().equals(binding)) + throw new IllegalArgumentException("POLICY_COMMIT_BINDING_CONFLICT"); + } + + private void requireDraftAndUnfrozen(TargetProof target) { + var version = + dsl.fetchOne( + "SELECT version_state, is_script_only, script_patch_version, base_version_id FROM version WHERE id = ?", + target.gameDesignVersionRowId()); + if (version == null + || !"DRAFT".equals(version.get("version_state", String.class)) + || !Boolean.FALSE.equals(version.get("is_script_only", Boolean.class)) + || version.get("script_patch_version") != null + || version.get("base_version_id") != null + || dsl.fetchOne( + "SELECT 1 FROM game_design_realm_policy_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) { + throw new IllegalStateException("POLICY_SOURCE_NOT_OPEN_FULL_DRAFT"); + } + } + + private void lockAuthority(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT v.id FROM version v JOIN game g ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND v.identity_source_game_row_id = ? AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? FOR UPDATE OF v", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()); + if (row == null) + throw new IllegalStateException("POLICY_CANONICAL_OWNER_AUTHORITY_UNAVAILABLE"); + } + + private static void requireWrite() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Policy writes require caller-owned writable READ_COMMITTED transaction"); + } + } +} 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..a2a7947737 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java @@ -0,0 +1,627 @@ +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 net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +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.TransactionDefinition; +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 static final Table VERSION = DSL.table(DSL.name("version")); + private static final Field VERSION_ID = DSL.field(DSL.name("id"), Long.class); + private static final Field VERSION_TENANT_ID = + DSL.field(DSL.name("tenant_id"), String.class); + private static final Field VERSION_CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("identity_source_game_row_id"), Long.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("identity_source_game_tenant_key"), String.class); + private static final Field VERSION_IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("identity_source_provenance_kind"), String.class); + private static final Field VERSION_STATE = + DSL.field(DSL.name("version_state"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); + 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); + } + + /** + * Reads the exact source receipt and its source-owned version from the caller's owner snapshot. + * + *

This method is intentionally separate from {@link #read}: the latter suspends any ambient + * transaction to read a committed outcome, while this owner-current read requires the dedicated + * read-only REPEATABLE_READ transaction opened by AuthoredWorldVersionStateService. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional readVersionStateSnapshot( + String targetNamespace, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String expectedSourceEvidenceDigest, + long versionId) { + requireOwnerSnapshot(); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + if (readRequestId.equals(sourceOperationId)) { + throw new IllegalArgumentException("readRequestId must be separate from sourceOperationId"); + } + if (!GameTenantCreationDigest.isDigest(expectedSourceEvidenceDigest)) { + throw new IllegalArgumentException("Expected source evidence digest is not canonical"); + } + if (versionId <= 0) { + throw new IllegalArgumentException("versionId must be positive"); + } + + Record sourceRecord = + dsl.selectFrom(OPERATION).where(OPERATION_ID.eq(sourceOperationId)).fetchOne(); + if (sourceRecord == null) { + return Optional.empty(); + } + AuthoredWorldSourceEvidence receipt = toEvidence(sourceRecord); + if (!targetNamespace.equals(receipt.targetNamespace()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !worldSlug.equals(receipt.worldSlug()) + || !sourceOperationId.equals(receipt.operationId())) { + throw new InvalidSourceEvidenceException( + "Authored-world source operation does not match the exact requested scope"); + } + if (!expectedSourceEvidenceDigest.equals(receipt.evidenceDigest())) { + throw new InvalidSourceEvidenceException( + "Authored-world source evidence digest no longer matches the requested binding"); + } + + GameSource source = findGameSourceByRow(receipt.sourceGameRowId()); + if (source == null) { + throw new InvalidSourceEvidenceException("Authored-world source game row is missing"); + } + requireConsistentGameSource(source); + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + + Record versionRecord = + dsl.select( + VERSION_ID, + VERSION_TENANT_ID, + VERSION_CANONICAL_VERSION_ID, + VERSION_CANONICAL_TENANT_ID, + VERSION_IDENTITY_SOURCE_GAME_ROW_ID, + VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY, + VERSION_IDENTITY_SOURCE_PROVENANCE_KIND, + VERSION_STATE, + VERSION_STATE_EPOCH) + .from(VERSION) + .where(VERSION_ID.eq(versionId)) + .fetchOne(); + if (versionRecord == null) { + return Optional.empty(); + } + String versionTenantId = versionRecord.get(VERSION_TENANT_ID); + if (versionTenantId == null || !source.sourceGameTenantKey().equals(versionTenantId)) { + throw new InvalidSourceEvidenceException( + "Requested version is not owned by the exact Game Design source game"); + } + UUID canonicalVersionId = versionRecord.get(VERSION_CANONICAL_VERSION_ID); + if (canonicalVersionId == null || NIL_UUID.equals(canonicalVersionId)) { + throw new InvalidSourceEvidenceException( + "Requested version has no persisted canonical non-nil Version UUID"); + } + if (!source.canonicalTenantId().equals(versionRecord.get(VERSION_CANONICAL_TENANT_ID)) + || !Long.valueOf(source.sourceGameRowId()) + .equals(versionRecord.get(VERSION_IDENTITY_SOURCE_GAME_ROW_ID)) + || !source + .sourceGameTenantKey() + .equals(versionRecord.get(VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY)) + || !source + .provenanceKind() + .equals(versionRecord.get(VERSION_IDENTITY_SOURCE_PROVENANCE_KIND))) { + throw new InvalidSourceEvidenceException( + "Requested version canonical identity provenance does not match " + + "the exact Game Design source game"); + } + + VersionLifecycleState versionState; + Long versionStateEpoch = versionRecord.get(VERSION_STATE_EPOCH); + try { + String versionStateName = versionRecord.get(VERSION_STATE); + if (versionStateName == null || versionStateEpoch == null || versionStateEpoch <= 0) { + throw new IllegalArgumentException("Version lifecycle state or epoch is invalid"); + } + versionState = VersionLifecycleState.valueOf(versionStateName); + } catch (IllegalArgumentException exception) { + throw new InvalidSourceEvidenceException( + "Persisted version lifecycle state or epoch is invalid", exception); + } + return Optional.of( + new AuthoredWorldVersionStateSnapshot( + receipt, canonicalVersionId, versionState, versionStateEpoch)); + } + + 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 void requireOwnerSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Authored-world version-state read requires a read-only REPEATABLE_READ owner snapshot"); + } + } + + private void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + } + + public record AuthoredWorldVersionStateSnapshot( + AuthoredWorldSourceEvidence sourceEvidence, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) {} + + 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/repository/LaunchDescriptorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java index 4e18a44aea..3f09f54f70 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java @@ -4,6 +4,7 @@ import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; import org.jooq.DSLContext; import org.jooq.Field; @@ -12,6 +13,7 @@ import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; +/** Owner-local immutable launch descriptor history. */ @Repository @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -43,6 +45,31 @@ public class LaunchDescriptorRepository { DSL.field(DSL.name("published_release_bundle_ref"), String.class); private static final Field REMAP_SET_ID = DSL.field(DSL.name("remap_set_id"), String.class); + private static final Field DESCRIPTOR_SCHEMA_VERSION = + DSL.field(DSL.name("descriptor_schema_version"), Integer.class); + 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 WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("authored_world_source_operation_id"), UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("authored_world_source_evidence_digest"), String.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field RESULT_DIGEST = + DSL.field(DSL.name("result_digest"), String.class); + private static final Field ORIGINAL_REQUEST_JSON = + DSL.field(DSL.name("original_request_json"), String.class); + private static final Field SOURCE_EVIDENCE_JSON = + DSL.field(DSL.name("source_evidence_json"), String.class); + private static final Field OUTCOME_STATUS = + DSL.field(DSL.name("outcome_status"), String.class); + private static final Field FAILURE_CODE = + DSL.field(DSL.name("failure_code"), String.class); + private static final Field FAILURE_MESSAGE = + DSL.field(DSL.name("failure_message"), String.class); private static final Field CREATED_AT = DSL.field(DSL.name("created_at"), Timestamp.class); @@ -52,71 +79,98 @@ public LaunchDescriptorRepository(DSLContext dsl) { this.dsl = dsl; } - public Optional findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - String tenantId, Long gameTemplateId, String controlPlaneRequestId) { + /** Serializes one launch request identity before source, template, or version resolution. */ + public void lockBoundRequest(String targetNamespace, UUID canonicalTenantId, String requestId) { + String lockIdentity = canonicalTenantId + ":" + requestId; + dsl.fetch( + "select pg_advisory_xact_lock(hashtext(?), hashtext(?))", targetNamespace, lockIdentity); + } + + public Optional findBoundByRequest( + String targetNamespace, UUID canonicalTenantId, String controlPlaneRequestId) { return Optional.ofNullable( dsl.selectFrom(TABLE_REF) .where( - TENANT_ID - .eq(tenantId) - .and(GAME_TEMPLATE_ID.eq(gameTemplateId)) + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) .and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) .limit(1) .fetchOne(this::toEntity)); } + /** Reads the legacy private owner/request tuple only to deny unbound retained history. */ + public Optional findByPrivateRequest( + String tenantId, String controlPlaneRequestId) { + return Optional.ofNullable( + dsl.selectFrom(TABLE_REF) + .where(TENANT_ID.eq(tenantId).and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) + .limit(1) + .fetchOne(this::toEntity)); + } + public boolean existsByTenantIdAndVersionId(String tenantId, Long versionId) { return dsl.fetchExists(TABLE_REF, TENANT_ID.eq(tenantId).and(VERSION_ID.eq(versionId))); } - public LaunchDescriptor save(LaunchDescriptor descriptor) { + /** Inserts one immutable descriptor; conflicting identities can only return their stored row. */ + public LaunchDescriptor insertImmutable(LaunchDescriptor descriptor) { + if (descriptor.getId() != null || descriptor.getDescriptorSchemaVersion() == null) { + throw new IllegalArgumentException("Only a new bound launch descriptor can be inserted"); + } + if (descriptor.getOutcomeStatus() == null + || !(LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()))) { + throw new IllegalArgumentException("A known launch descriptor outcome is required"); + } LocalDateTime createdAt = descriptor.getCreatedAt() == null ? LocalDateTime.now() : descriptor.getCreatedAt(); - if (descriptor.getId() == null) { - dsl.insertInto(TABLE_REF) - .set(LAUNCH_DESCRIPTOR_ID, descriptor.getLaunchDescriptorId()) - .set(TENANT_ID, descriptor.getTenantId()) - .set(GAME_TEMPLATE_ID, descriptor.getGameTemplateId()) - .set(CONTROL_PLANE_REQUEST_ID, descriptor.getControlPlaneRequestId()) - .set(REQUEST_HASH, descriptor.getRequestHash()) - .set(VERSION_ID, descriptor.getVersionId()) - .set(SCRIPT_PATCH_VERSION, descriptor.getScriptPatchVersion()) - .set(RUNTIME_FLAGS_JSON, descriptor.getRuntimeFlagsJson()) - .set(GENERATION_CONFIG_REVISION, descriptor.getGenerationConfigRevision()) - .set(VERSION_STATE_EPOCH, descriptor.getVersionStateEpoch()) - .set(RELEASE_BUNDLE_ID, descriptor.getReleaseBundleId()) - .set(PUBLISHED_RELEASE_BUNDLE_REF, descriptor.getPublishedReleaseBundleRef()) - .set(REMAP_SET_ID, descriptor.getRemapSetId()) - .set(CREATED_AT, Timestamp.valueOf(createdAt)) - .execute(); - return findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - descriptor.getTenantId(), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId()) - .orElseThrow(); + int inserted = + dsl.insertInto(TABLE_REF) + .set(LAUNCH_DESCRIPTOR_ID, descriptor.getLaunchDescriptorId()) + .set(TENANT_ID, descriptor.getTenantId()) + .set(GAME_TEMPLATE_ID, descriptor.getGameTemplateId()) + .set(CONTROL_PLANE_REQUEST_ID, descriptor.getControlPlaneRequestId()) + .set(REQUEST_HASH, descriptor.getRequestDigest()) + .set(VERSION_ID, descriptor.getVersionId()) + .set(SCRIPT_PATCH_VERSION, descriptor.getScriptPatchVersion()) + .set(RUNTIME_FLAGS_JSON, descriptor.getRuntimeFlagsJson()) + .set(GENERATION_CONFIG_REVISION, descriptor.getGenerationConfigRevision()) + .set(VERSION_STATE_EPOCH, descriptor.getVersionStateEpoch()) + .set(RELEASE_BUNDLE_ID, descriptor.getReleaseBundleId()) + .set(PUBLISHED_RELEASE_BUNDLE_REF, descriptor.getPublishedReleaseBundleRef()) + .set(REMAP_SET_ID, descriptor.getRemapSetId()) + .set(DESCRIPTOR_SCHEMA_VERSION, descriptor.getDescriptorSchemaVersion()) + .set(TARGET_NAMESPACE, descriptor.getTargetNamespace()) + .set(CANONICAL_TENANT_ID, UUID.fromString(descriptor.getCanonicalTenantId())) + .set(WORLD_SLUG, descriptor.getWorldSlug()) + .set( + SOURCE_OPERATION_ID, + UUID.fromString(descriptor.getAuthoredWorldSourceOperationId())) + .set(SOURCE_EVIDENCE_DIGEST, descriptor.getAuthoredWorldSourceEvidenceDigest()) + .set(REQUEST_DIGEST, descriptor.getRequestDigest()) + .set(RESULT_DIGEST, descriptor.getResultDigest()) + .set(ORIGINAL_REQUEST_JSON, descriptor.getOriginalRequestJson()) + .set(SOURCE_EVIDENCE_JSON, descriptor.getSourceEvidenceJson()) + .set(OUTCOME_STATUS, descriptor.getOutcomeStatus()) + .set(FAILURE_CODE, descriptor.getFailureCode()) + .set(FAILURE_MESSAGE, descriptor.getFailureMessage()) + .set(CREATED_AT, Timestamp.valueOf(createdAt)) + .onConflictDoNothing() + .execute(); + Optional stored = + findBoundByRequest( + descriptor.getTargetNamespace(), + UUID.fromString(descriptor.getCanonicalTenantId()), + descriptor.getControlPlaneRequestId()); + if (stored.isEmpty()) { + throw new IllegalStateException( + "Launch descriptor identity conflicts with existing immutable history"); + } + if (inserted == 0 && stored.orElseThrow().getDescriptorSchemaVersion() == null) { + throw new IllegalStateException("An unbound launch descriptor cannot be reused canonically"); } - dsl.update(TABLE_REF) - .set(LAUNCH_DESCRIPTOR_ID, descriptor.getLaunchDescriptorId()) - .set(TENANT_ID, descriptor.getTenantId()) - .set(GAME_TEMPLATE_ID, descriptor.getGameTemplateId()) - .set(CONTROL_PLANE_REQUEST_ID, descriptor.getControlPlaneRequestId()) - .set(REQUEST_HASH, descriptor.getRequestHash()) - .set(VERSION_ID, descriptor.getVersionId()) - .set(SCRIPT_PATCH_VERSION, descriptor.getScriptPatchVersion()) - .set(RUNTIME_FLAGS_JSON, descriptor.getRuntimeFlagsJson()) - .set(GENERATION_CONFIG_REVISION, descriptor.getGenerationConfigRevision()) - .set(VERSION_STATE_EPOCH, descriptor.getVersionStateEpoch()) - .set(RELEASE_BUNDLE_ID, descriptor.getReleaseBundleId()) - .set(PUBLISHED_RELEASE_BUNDLE_REF, descriptor.getPublishedReleaseBundleRef()) - .set(REMAP_SET_ID, descriptor.getRemapSetId()) - .set(CREATED_AT, Timestamp.valueOf(createdAt)) - .where(ID.eq(descriptor.getId())) - .execute(); - return findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - descriptor.getTenantId(), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId()) - .orElseThrow(); + return stored.orElseThrow(); } private LaunchDescriptor toEntity(Record record) { @@ -138,7 +192,24 @@ private LaunchDescriptor toEntity(Record record) { descriptor.setReleaseBundleId(record.get(RELEASE_BUNDLE_ID)); descriptor.setPublishedReleaseBundleRef(record.get(PUBLISHED_RELEASE_BUNDLE_REF)); descriptor.setRemapSetId(record.get(REMAP_SET_ID)); - Timestamp createdAt = record.get(CREATED_AT); + descriptor.setDescriptorSchemaVersion(record.get(DESCRIPTOR_SCHEMA_VERSION, Integer.class)); + descriptor.setTargetNamespace(record.get(TARGET_NAMESPACE)); + UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID, UUID.class); + descriptor.setCanonicalTenantId( + canonicalTenantId == null ? null : canonicalTenantId.toString()); + descriptor.setWorldSlug(record.get(WORLD_SLUG)); + UUID sourceOperationId = record.get(SOURCE_OPERATION_ID, UUID.class); + descriptor.setAuthoredWorldSourceOperationId( + sourceOperationId == null ? null : sourceOperationId.toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(record.get(SOURCE_EVIDENCE_DIGEST)); + descriptor.setRequestDigest(record.get(REQUEST_DIGEST)); + descriptor.setResultDigest(record.get(RESULT_DIGEST)); + descriptor.setOriginalRequestJson(record.get(ORIGINAL_REQUEST_JSON)); + descriptor.setSourceEvidenceJson(record.get(SOURCE_EVIDENCE_JSON)); + descriptor.setOutcomeStatus(record.get(OUTCOME_STATUS)); + descriptor.setFailureCode(record.get(FAILURE_CODE)); + descriptor.setFailureMessage(record.get(FAILURE_MESSAGE)); + Timestamp createdAt = record.get(CREATED_AT, Timestamp.class); descriptor.setCreatedAt(createdAt == null ? null : createdAt.toLocalDateTime()); return descriptor; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java index 51c60a2779..2776b9394d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java @@ -8,6 +8,8 @@ import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Field; @@ -61,6 +63,60 @@ public Optional findByPublishWorkflowId(String publishWorkflowId .fetchOne(this::toEntity)); } + /** The owning Game lock always precedes the exact attempt lock. */ + public Optional findByPublishWorkflowIdForUpdate(String workflow) { + Optional initial = findByPublishWorkflowId(workflow); + if (initial.isEmpty()) return initial; + dsl.fetchOne("SELECT id FROM game WHERE tenant_id = ? FOR UPDATE", initial.get().getTenantId()); + return Optional.ofNullable( + dsl.selectFrom(PUBLISH_ATTEMPT_TABLE) + .where(PUBLISH_WORKFLOW_ID.eq(workflow)) + .forUpdate() + .fetchOne(this::toEntity)); + } + + public net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence + requirePublicationPending(PublishAttempt attempt) { + return new GameDesignPublicationOperationRepository(dsl) + .requirePending( + attempt.getTenantId(), + attempt.getPublishWorkflowId(), + attempt.getVersionId(), + attempt.getRequestDigest()) + .world(); + } + + public void sealPublication(PublishAttempt attempt, boolean published) { + new GameDesignPublicationOperationRepository(dsl) + .seal( + attempt.getTenantId(), + attempt.getPublishWorkflowId(), + attempt.getVersionId(), + attempt.getRequestDigest(), + published); + if (published) { + new RealmPolicyPublicationRepository(dsl) + .retainSealedPublished(attempt.getPublishWorkflowId()); + } + } + + public void requirePublishedOperation(PublishAttempt attempt) { + requireTerminalOperation(attempt, "PUBLISHED"); + } + + private void requireTerminalOperation(PublishAttempt attempt, String outcome) { + var result = + new GameDesignPublicationOperationRepository(dsl) + .read(attempt.getPublishWorkflowId()) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + if (!outcome.equals(result.outcome()) + || !result.operation().selectionDigest().equals(attempt.getRequestDigest()) + || result.operation().versionId() != attempt.getVersionId() + || !result.operation().tenantKey().equals(attempt.getTenantId())) { + throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); + } + } + /** * Installs a compatibility digest only once, and only on the exact legacy full-version row whose * identity was validated by the caller. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index f57a7af717..516dfa2a06 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java @@ -1,10 +1,20 @@ package net.firedevops.firemud.gamedesign.repository; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; import java.sql.Timestamp; import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -18,9 +28,18 @@ justification = "Injected DSLContext is an internal Spring collaborator.") public class PublishedReleaseBundleRepository { private static final Table TABLE_REF = DSL.table(DSL.name("published_release_bundle")); + private static final Table VERSION_SOURCE = + DSL.table(DSL.name("version")).as("source_version"); + private static final Table GAME_SOURCE = DSL.table(DSL.name("game")).as("source_game"); private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + DSL.field(DSL.name("published_release_bundle_ref"), String.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); private static final Field VERSION_NUMBER = DSL.field(DSL.name("version_number"), Integer.class); private static final Field ATTESTATION_SCHEMA_VERSION = @@ -29,6 +48,10 @@ public class PublishedReleaseBundleRepository { DSL.field(DSL.name("publish_workflow_id"), String.class); private static final Field MANIFEST_HASH = DSL.field(DSL.name("manifest_hash"), String.class); + private static final Field MANIFEST_SCHEMA_VERSION = + DSL.field(DSL.name("manifest_schema_version"), Integer.class); + private static final Field ARTIFACT_DIGESTS_JSON = + DSL.field(DSL.name("artifact_digests_json"), String.class); private static final Field GENERATION_CONFIG_REVISION = DSL.field(DSL.name("generation_config_revision"), String.class); private static final Field REQUIRED_MANIFEST_ASSET_KEYS_JSON = @@ -37,6 +60,8 @@ public class PublishedReleaseBundleRepository { DSL.field(DSL.name("participant_digests_json"), String.class); private static final Field COMMAND_DEFINITIONS_JSON = DSL.field(DSL.name("command_definitions_json"), String.class); + private static final Field WORLD_SELECTOR_EVIDENCE_JSON = + DSL.field(DSL.name("world_published_start_location_evidence_json"), String.class); private static final Field SCRIPT_ONLY = DSL.field(DSL.name("script_only"), Boolean.class); private static final Field SCRIPT_PATCH_VERSION = @@ -44,6 +69,35 @@ public class PublishedReleaseBundleRepository { private static final Field PUBLISHED_AT = DSL.field(DSL.name("published_at"), Timestamp.class); + private static final Field SOURCE_VERSION_ID = + DSL.field(DSL.name("source_version", "id"), Long.class); + private static final Field SOURCE_VERSION_TENANT_ID = + DSL.field(DSL.name("source_version", "tenant_id"), String.class); + private static final Field SOURCE_VERSION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("source_version", "canonical_tenant_id"), UUID.class); + private static final Field SOURCE_VERSION_CANONICAL_VERSION_ID = + DSL.field(DSL.name("source_version", "canonical_version_id"), UUID.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_version", "identity_source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_version", "identity_source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_version", "identity_source_provenance_kind"), String.class); + private static final Field SOURCE_GAME_ID = + DSL.field(DSL.name("source_game", "id"), Long.class); + private static final Field SOURCE_GAME_TENANT_ID = + DSL.field(DSL.name("source_game", "tenant_id"), String.class); + private static final Field SOURCE_GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("source_game", "canonical_tenant_id"), UUID.class); + private static final Field SOURCE_GAME_PROVENANCE_KIND = + DSL.field(DSL.name("source_game", "tenant_identity_provenance_kind"), String.class); + private static final Field SOURCE_GAME_SOURCE_ROW_ID = + DSL.field(DSL.name("source_game", "tenant_identity_source_game_id"), Long.class); + private static final Field SOURCE_GAME_SOURCE_TENANT_KEY = + DSL.field(DSL.name("source_game", "tenant_identity_source_legacy_tenant_id"), String.class); + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final DSLContext dsl; public PublishedReleaseBundleRepository(DSLContext dsl) { @@ -59,46 +113,215 @@ public Optional findByTenantIdAndVersionId( .fetchOne(this::toEntity)); } + /** + * Reads the exact full-version command snapshot frozen for the retained publication operation. + * The requested Version tuple, operation selection, World evidence, and both source captures are + * checked before a bundle producer can persist command bytes. + */ + public List requireSelectedCommandDefinitions( + String tenantId, + Long versionId, + String publishWorkflowId, + WorldPublishedStartLocationEvidence worldEvidence) { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(versionId, "versionId"); + Objects.requireNonNull(publishWorkflowId, "publishWorkflowId"); + Objects.requireNonNull(worldEvidence, "worldEvidence"); + + GameDesignPublicationOperation operation = + new GameDesignPublicationOperationRepository(dsl) + .read(publishWorkflowId) + .map(GameDesignPublicationOperationRepository.Readback::operation) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_OPERATION_UNAVAILABLE")); + var selection = operation.account().input().selection(); + var target = selection.target(); + if (!tenantId.equals(operation.tenantKey()) + || !versionId.equals(operation.versionId()) + || !publishWorkflowId.equals(operation.workflowId()) + || !tenantId.equals(target.gameDesignVersionTenantKey()) + || !versionId.equals(target.gameDesignVersionRowId()) + || !Arrays.equals(operation.world().canonicalBytes(), worldEvidence.canonicalBytes()) + || !target.canonicalTenantId().equals(worldEvidence.request().canonicalTenantId()) + || !target.canonicalVersionId().equals(worldEvidence.request().canonicalVersionId()) + || !publishWorkflowId.equals(worldEvidence.request().publishWorkflowId())) { + throw new IllegalStateException("SELECTED_PUBLICATION_OPERATION_BINDING_CONFLICT"); + } + + GameDesignSourceRepository.Capture capture = + new GameDesignSourceRepository(dsl) + .readCapture(operation) + .orElseThrow(() -> new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); + if (!Arrays.equals( + capture.command().operation().canonicalBytes(), operation.canonicalBytes())) { + throw new IllegalStateException("SELECTED_COMMAND_CAPTURE_OPERATION_CONFLICT"); + } + return capture.command().snapshot().definitions().stream() + .map(CommandSource.Definition::definitionJson) + .toList(); + } + public PublishedReleaseBundle save(PublishedReleaseBundle bundle) { - LocalDateTime publishedAt = - bundle.getPublishedAt() == null ? LocalDateTime.now() : bundle.getPublishedAt(); - if (bundle.getId() == null) { - Long generatedId = - dsl.insertInto(TABLE_REF) - .set(TENANT_ID, bundle.getTenantId()) - .set(VERSION_ID, bundle.getVersionId()) - .set(VERSION_NUMBER, bundle.getVersionNumber()) - .set(ATTESTATION_SCHEMA_VERSION, bundle.getAttestationSchemaVersion()) - .set(PUBLISH_WORKFLOW_ID, bundle.getPublishWorkflowId()) - .set(MANIFEST_HASH, bundle.getManifestHash()) - .set(GENERATION_CONFIG_REVISION, bundle.getGenerationConfigRevision()) - .set(REQUIRED_MANIFEST_ASSET_KEYS_JSON, bundle.getRequiredManifestAssetKeysJson()) - .set(PARTICIPANT_DIGESTS_JSON, bundle.getParticipantDigestsJson()) - .set(COMMAND_DEFINITIONS_JSON, bundle.getCommandDefinitionsJson()) - .set(SCRIPT_ONLY, bundle.isScriptOnly()) - .set(SCRIPT_PATCH_VERSION, bundle.getScriptPatchVersion()) - .set(PUBLISHED_AT, Timestamp.valueOf(publishedAt)) - .returningResult(ID) - .fetchOne(ID); - return dsl.selectFrom(TABLE_REF).where(ID.eq(generatedId)).fetchOne(this::toEntity); + Objects.requireNonNull(bundle, "bundle"); + if (bundle.getId() != null) { + throw new IllegalStateException( + "Published release bundle is immutable; read the stored row instead of saving it again"); + } + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + LocalDateTime publishedAt = + bundle.getPublishedAt() == null ? LocalDateTime.now() : bundle.getPublishedAt(); + return insertNewBundle(tx, bundle, publishedAt); + }); + } + + private PublishedReleaseBundle insertNewBundle( + DSLContext tx, PublishedReleaseBundle bundle, LocalDateTime publishedAt) { + CanonicalSource source = findExactCanonicalSource(tx, bundle); + rejectCallerIdentitySubstitution(bundle, source); + verifySelectorSource(bundle, source); + if ("v2".equals(bundle.getAttestationSchemaVersion())) { + PublishedReleaseBundle existing = + tx.selectFrom(TABLE_REF) + .where(TENANT_ID.eq(bundle.getTenantId()).and(VERSION_ID.eq(bundle.getVersionId()))) + .fetchOne(this::toEntity); + if (existing != null) { + try { + verifyPersistedSource(existing, bundle, source, existing.getPublishedReleaseBundleRef()); + } catch (IllegalStateException conflict) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: changed immutable selector release input", conflict); + } + return existing; + } } - dsl.update(TABLE_REF) - .set(TENANT_ID, bundle.getTenantId()) - .set(VERSION_ID, bundle.getVersionId()) - .set(VERSION_NUMBER, bundle.getVersionNumber()) - .set(ATTESTATION_SCHEMA_VERSION, bundle.getAttestationSchemaVersion()) - .set(PUBLISH_WORKFLOW_ID, bundle.getPublishWorkflowId()) - .set(MANIFEST_HASH, bundle.getManifestHash()) - .set(GENERATION_CONFIG_REVISION, bundle.getGenerationConfigRevision()) - .set(REQUIRED_MANIFEST_ASSET_KEYS_JSON, bundle.getRequiredManifestAssetKeysJson()) - .set(PARTICIPANT_DIGESTS_JSON, bundle.getParticipantDigestsJson()) - .set(COMMAND_DEFINITIONS_JSON, bundle.getCommandDefinitionsJson()) - .set(SCRIPT_ONLY, bundle.isScriptOnly()) - .set(SCRIPT_PATCH_VERSION, bundle.getScriptPatchVersion()) - .set(PUBLISHED_AT, Timestamp.valueOf(publishedAt)) - .where(ID.eq(bundle.getId())) - .execute(); - return findByTenantIdAndVersionId(bundle.getTenantId(), bundle.getVersionId()).orElseThrow(); + String publishedReleaseBundleRef = UUID.randomUUID().toString(); + + Long generatedId = + tx.insertInto(TABLE_REF) + .set(PUBLISHED_RELEASE_BUNDLE_REF, publishedReleaseBundleRef) + .set(TENANT_ID, bundle.getTenantId()) + .set(VERSION_ID, bundle.getVersionId()) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(CANONICAL_VERSION_ID, source.canonicalVersionId()) + .set(VERSION_NUMBER, bundle.getVersionNumber()) + .set(ATTESTATION_SCHEMA_VERSION, bundle.getAttestationSchemaVersion()) + .set(PUBLISH_WORKFLOW_ID, bundle.getPublishWorkflowId()) + .set(MANIFEST_HASH, bundle.getManifestHash()) + .set(MANIFEST_SCHEMA_VERSION, bundle.getManifestSchemaVersion()) + .set(ARTIFACT_DIGESTS_JSON, bundle.getArtifactDigestsJson()) + .set(GENERATION_CONFIG_REVISION, bundle.getGenerationConfigRevision()) + .set(REQUIRED_MANIFEST_ASSET_KEYS_JSON, bundle.getRequiredManifestAssetKeysJson()) + .set(PARTICIPANT_DIGESTS_JSON, bundle.getParticipantDigestsJson()) + .set(COMMAND_DEFINITIONS_JSON, bundle.getCommandDefinitionsJson()) + .set(WORLD_SELECTOR_EVIDENCE_JSON, bundle.getWorldPublishedStartLocationEvidenceJson()) + .set(SCRIPT_ONLY, bundle.isScriptOnly()) + .set(SCRIPT_PATCH_VERSION, bundle.getScriptPatchVersion()) + .set(PUBLISHED_AT, Timestamp.valueOf(publishedAt)) + .returningResult(ID) + .fetchOne(ID); + if (generatedId == null) { + throw new IllegalStateException("Published release bundle insert returned no row id"); + } + + PublishedReleaseBundle persisted = findById(tx, generatedId).orElseThrow(); + verifyPersistedSource(persisted, bundle, source, publishedReleaseBundleRef); + return persisted; + } + + private CanonicalSource findExactCanonicalSource(DSLContext tx, PublishedReleaseBundle bundle) { + if (bundle.getTenantId() == null || bundle.getVersionId() == null) { + throw new IllegalArgumentException( + "Published release bundle requires tenant and Version row"); + } + + Record source = + tx.select(SOURCE_VERSION_CANONICAL_TENANT_ID, SOURCE_VERSION_CANONICAL_VERSION_ID) + .from(VERSION_SOURCE.join(GAME_SOURCE).on(SOURCE_GAME_ROW_ID.eq(SOURCE_GAME_ID))) + .where( + SOURCE_VERSION_ID + .eq(bundle.getVersionId()) + .and(SOURCE_VERSION_TENANT_ID.eq(bundle.getTenantId())) + .and(SOURCE_VERSION_CANONICAL_TENANT_ID.isNotNull()) + .and(SOURCE_VERSION_CANONICAL_TENANT_ID.ne(NIL_UUID)) + .and(SOURCE_VERSION_CANONICAL_VERSION_ID.isNotNull()) + .and(SOURCE_VERSION_CANONICAL_VERSION_ID.ne(NIL_UUID)) + .and(SOURCE_VERSION_TENANT_ID.eq(SOURCE_GAME_TENANT_ID)) + .and(SOURCE_GAME_TENANT_KEY.eq(SOURCE_GAME_TENANT_ID)) + .and(SOURCE_VERSION_CANONICAL_TENANT_ID.eq(SOURCE_GAME_CANONICAL_TENANT_ID)) + .and(SOURCE_PROVENANCE_KIND.eq(SOURCE_GAME_PROVENANCE_KIND)) + .and(SOURCE_PROVENANCE_KIND.in("NEW_GAME_ROW", "RETAINED_GAME_V29")) + .and(SOURCE_GAME_SOURCE_ROW_ID.eq(SOURCE_GAME_ID)) + .and(SOURCE_GAME_SOURCE_TENANT_KEY.eq(SOURCE_GAME_TENANT_ID))) + .forUpdate() + .fetchOne(); + if (source == null) { + throw new IllegalStateException( + "No exact canonical Game Design source association exists for the requested Version"); + } + + UUID canonicalTenantId = source.get(SOURCE_VERSION_CANONICAL_TENANT_ID); + UUID canonicalVersionId = source.get(SOURCE_VERSION_CANONICAL_VERSION_ID); + if (canonicalTenantId == null + || NIL_UUID.equals(canonicalTenantId) + || canonicalVersionId == null + || NIL_UUID.equals(canonicalVersionId)) { + throw new IllegalStateException("Exact Game Design source has an invalid canonical identity"); + } + return new CanonicalSource(canonicalTenantId, canonicalVersionId); + } + + private void rejectCallerIdentitySubstitution( + PublishedReleaseBundle bundle, CanonicalSource source) { + if ((bundle.getCanonicalTenantId() != null + && !bundle.getCanonicalTenantId().equals(source.canonicalTenantId())) + || (bundle.getCanonicalVersionId() != null + && !bundle.getCanonicalVersionId().equals(source.canonicalVersionId()))) { + throw new IllegalArgumentException( + "Caller-supplied canonical release identity does not match the exact Version source"); + } + } + + private void verifyPersistedSource( + PublishedReleaseBundle persisted, + PublishedReleaseBundle requested, + CanonicalSource source, + String publishedReleaseBundleRef) { + if (!Objects.equals(persisted.getTenantId(), requested.getTenantId()) + || !Objects.equals(persisted.getVersionId(), requested.getVersionId()) + || !Objects.equals(persisted.getCanonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(persisted.getCanonicalVersionId(), source.canonicalVersionId()) + || !Objects.equals(persisted.getManifestHash(), requested.getManifestHash()) + || !Objects.equals( + persisted.getManifestSchemaVersion(), requested.getManifestSchemaVersion()) + || !Objects.equals(persisted.getArtifactDigestsJson(), requested.getArtifactDigestsJson()) + || !Objects.equals( + persisted.getWorldPublishedStartLocationEvidenceJson(), + requested.getWorldPublishedStartLocationEvidenceJson()) + || !Objects.equals( + persisted.getAttestationSchemaVersion(), requested.getAttestationSchemaVersion()) + || !Objects.equals(persisted.getPublishWorkflowId(), requested.getPublishWorkflowId()) + || persisted.getVersionNumber() != requested.getVersionNumber() + || !Objects.equals( + persisted.getGenerationConfigRevision(), requested.getGenerationConfigRevision()) + || !Objects.equals( + persisted.getCommandDefinitionsJson(), requested.getCommandDefinitionsJson()) + || persisted.isScriptOnly() != requested.isScriptOnly() + || !Objects.equals(persisted.getScriptPatchVersion(), requested.getScriptPatchVersion()) + || !Objects.equals( + persisted.getRequiredManifestAssetKeysJson(), + requested.getRequiredManifestAssetKeysJson()) + || !Objects.equals( + persisted.getParticipantDigestsJson(), requested.getParticipantDigestsJson()) + || !Objects.equals(persisted.getPublishedReleaseBundleRef(), publishedReleaseBundleRef)) { + throw new IllegalStateException( + "Published release bundle readback does not match its source identity and owner reference"); + } + } + + private Optional findById(DSLContext tx, Long id) { + return Optional.ofNullable(tx.selectFrom(TABLE_REF).where(ID.eq(id)).fetchOne(this::toEntity)); } private PublishedReleaseBundle toEntity(Record record) { @@ -107,20 +330,53 @@ private PublishedReleaseBundle toEntity(Record record) { } PublishedReleaseBundle bundle = new PublishedReleaseBundle(); bundle.setId(record.get(ID)); + bundle.setPublishedReleaseBundleRef(record.get(PUBLISHED_RELEASE_BUNDLE_REF)); bundle.setTenantId(record.get(TENANT_ID)); bundle.setVersionId(record.get(VERSION_ID)); + bundle.setCanonicalTenantId(record.get(CANONICAL_TENANT_ID)); + bundle.setCanonicalVersionId(record.get(CANONICAL_VERSION_ID)); bundle.setVersionNumber(record.get(VERSION_NUMBER)); bundle.setAttestationSchemaVersion(record.get(ATTESTATION_SCHEMA_VERSION)); bundle.setPublishWorkflowId(record.get(PUBLISH_WORKFLOW_ID)); bundle.setManifestHash(record.get(MANIFEST_HASH)); + bundle.setManifestSchemaVersion(record.get(MANIFEST_SCHEMA_VERSION)); + bundle.setArtifactDigestsJson(record.get(ARTIFACT_DIGESTS_JSON)); bundle.setGenerationConfigRevision(record.get(GENERATION_CONFIG_REVISION)); bundle.setRequiredManifestAssetKeysJson(record.get(REQUIRED_MANIFEST_ASSET_KEYS_JSON)); bundle.setParticipantDigestsJson(record.get(PARTICIPANT_DIGESTS_JSON)); bundle.setCommandDefinitionsJson(record.get(COMMAND_DEFINITIONS_JSON)); + bundle.setWorldPublishedStartLocationEvidenceJson(record.get(WORLD_SELECTOR_EVIDENCE_JSON)); bundle.setScriptOnly(Boolean.TRUE.equals(record.get(SCRIPT_ONLY))); bundle.setScriptPatchVersion(record.get(SCRIPT_PATCH_VERSION)); Timestamp publishedAt = record.get(PUBLISHED_AT); bundle.setPublishedAt(publishedAt == null ? null : publishedAt.toLocalDateTime()); + verifySelectorSource( + bundle, new CanonicalSource(bundle.getCanonicalTenantId(), bundle.getCanonicalVersionId())); return bundle; } + + private static void verifySelectorSource(PublishedReleaseBundle bundle, CanonicalSource source) { + String bytes = bundle.getWorldPublishedStartLocationEvidenceJson(); + if (!"v2".equals(bundle.getAttestationSchemaVersion())) { + if (bytes != null) { + throw new IllegalArgumentException( + "Selector evidence is forbidden on historical release schemas"); + } + return; + } + if (bytes == null) { + throw new IllegalArgumentException("World selector evidence is mandatory for release v2"); + } + var request = + WorldPublishedStartLocationEvidence.fromStored(bytes.getBytes(StandardCharsets.UTF_8)) + .request(); + if (!request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.canonicalVersionId().equals(source.canonicalVersionId()) + || !request.publishWorkflowId().equals(bundle.getPublishWorkflowId())) { + throw new IllegalArgumentException( + "World selector differs from exact Version source/workflow"); + } + } + + private record CanonicalSource(UUID canonicalTenantId, UUID canonicalVersionId) {} } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java index c92f1271b1..c800f4c55d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepository.java @@ -38,6 +38,14 @@ public class VersionAssetArtifactRepository { DSL.field(DSL.name("last_error_message"), String.class); private static final Field EXPORTED_MANIFEST_ASSET_KEYS_JSON = DSL.field(DSL.name("exported_manifest_asset_keys_json"), String.class); + private static final Field MANIFEST_SCHEMA_VERSION = + DSL.field(DSL.name("manifest_schema_version"), Integer.class); + private static final Field ARTIFACT_DIGESTS_JSON = + DSL.field(DSL.name("artifact_digests_json"), String.class); + private static final Field PUBLISHED_OBJECT_PROOFS_JSON = + DSL.field(DSL.name("published_object_proofs_json"), String.class); + private static final Field CANDIDATE_SNAPSHOT_VERSION_ID = + DSL.field(DSL.name("candidate_snapshot_version_id"), Long.class); private static final Field UPDATED_AT = DSL.field(DSL.name("updated_at"), Timestamp.class); @@ -72,6 +80,10 @@ public VersionAssetArtifact save(VersionAssetArtifact artifact) { .set(LAST_ERROR_CODE, artifact.getLastErrorCode()) .set(LAST_ERROR_MESSAGE, artifact.getLastErrorMessage()) .set(EXPORTED_MANIFEST_ASSET_KEYS_JSON, artifact.getExportedManifestAssetKeysJson()) + .set(MANIFEST_SCHEMA_VERSION, artifact.getManifestSchemaVersion()) + .set(ARTIFACT_DIGESTS_JSON, artifact.getArtifactDigestsJson()) + .set(PUBLISHED_OBJECT_PROOFS_JSON, artifact.getPublishedObjectProofsJson()) + .set(CANDIDATE_SNAPSHOT_VERSION_ID, artifact.getCandidateSnapshotVersionId()) .set(UPDATED_AT, JooqPersistenceSupport.toTimestamp(updatedAt)) .returning(ID) .fetchOne(); @@ -95,6 +107,10 @@ public VersionAssetArtifact save(VersionAssetArtifact artifact) { .set(LAST_ERROR_CODE, artifact.getLastErrorCode()) .set(LAST_ERROR_MESSAGE, artifact.getLastErrorMessage()) .set(EXPORTED_MANIFEST_ASSET_KEYS_JSON, artifact.getExportedManifestAssetKeysJson()) + .set(MANIFEST_SCHEMA_VERSION, artifact.getManifestSchemaVersion()) + .set(ARTIFACT_DIGESTS_JSON, artifact.getArtifactDigestsJson()) + .set(PUBLISHED_OBJECT_PROOFS_JSON, artifact.getPublishedObjectProofsJson()) + .set(CANDIDATE_SNAPSHOT_VERSION_ID, artifact.getCandidateSnapshotVersionId()) .set(UPDATED_AT, JooqPersistenceSupport.toTimestamp(updatedAt)) .where(ID.eq(artifact.getId())) .execute(); @@ -120,6 +136,10 @@ private VersionAssetArtifact toEntity(Record record) { artifact.setLastErrorCode(record.get(LAST_ERROR_CODE)); artifact.setLastErrorMessage(record.get(LAST_ERROR_MESSAGE)); artifact.setExportedManifestAssetKeysJson(record.get(EXPORTED_MANIFEST_ASSET_KEYS_JSON)); + artifact.setManifestSchemaVersion(record.get(MANIFEST_SCHEMA_VERSION)); + artifact.setArtifactDigestsJson(record.get(ARTIFACT_DIGESTS_JSON)); + artifact.setPublishedObjectProofsJson(record.get(PUBLISHED_OBJECT_PROOFS_JSON)); + artifact.setCandidateSnapshotVersionId(record.get(CANDIDATE_SNAPSHOT_VERSION_ID)); artifact.setUpdatedAt(JooqPersistenceSupport.toLocalDateTime(record.get(UPDATED_AT))); return artifact; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java new file mode 100644 index 0000000000..de00d10285 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java @@ -0,0 +1,570 @@ +package net.firedevops.firemud.gamedesign.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +/** Owner-local persistence boundary for Draft asset mappings and durable export snapshots. */ +@Repository +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring rejects a missing DSLContext before publication; this repository has no finalizer") +public class VersionAssetPublicationRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Comparator UTF8_BYTE_ORDER = + VersionAssetPublicationRepository::compareUtf8; + + private final DSLContext dsl; + + public VersionAssetPublicationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Associates an ordinary source asset with an exact tenant-owned Draft Version. Numeric ids in + * this method are private Game Design owner keys and are not public identity aliases. + */ + public void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType) { + requireTenantId(tenantId); + if (versionId <= 0 || assetId <= 0) { + throw new IllegalArgumentException("Version and asset owner keys must be positive"); + } + + VersionRow version = + lockVersionByTenantAndId(tenantId, versionId) + .orElseThrow(() -> new IllegalStateException("Exact tenant Version row was not found")); + qualifyVersion(version); + requireDraft(version); + requireNoSnapshot(tenantId, versionId); + + AssetRow asset = + findAssetForUpdate(tenantId, assetId) + .orElseThrow( + () -> new IllegalStateException("Exact tenant game asset row was not found")); + validateUsageKey(asset.fileName()); + + Record existing = + dsl.fetchOne( + "SELECT usage_key, usage_type FROM version_asset " + + "WHERE tenant_id = ? AND version_id = ? AND asset_id = ?", + tenantId, + versionId, + assetId); + if (existing != null) { + if (Objects.equals(existing.get("usage_key", String.class), asset.fileName()) + && Objects.equals(existing.get("usage_type", String.class), usageType)) { + return; + } + throw new IllegalStateException("Conflicting Version asset association already exists"); + } + + Record usageCollision = + dsl.fetchOne( + "SELECT asset_id FROM version_asset " + + "WHERE tenant_id = ? AND version_id = ? AND usage_key = ?", + tenantId, + versionId, + asset.fileName()); + if (usageCollision != null) { + throw new IllegalStateException("Version asset usage key is already mapped to another asset"); + } + + dsl.execute( + "INSERT INTO version_asset " + + "(tenant_id, version_id, asset_id, usage_key, usage_type) VALUES (?, ?, ?, ?, ?)", + tenantId, + versionId, + assetId, + asset.fileName(), + usageType); + } + + /** + * Freezes the current exact Draft mapping set or reads an earlier frozen snapshot. The caller + * must hold a transaction because the Version lock serializes mapping writes with first freeze. + */ + public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + VersionRow version = + lockVersionByTenantAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException("Exact tenant Version was not found")); + qualifyVersion(version); + + if (hasSnapshot(tenantId, version.id())) { + return readSnapshot(version); + } + requireDraft(version); + + List selected = lockMappedSourceAssets(tenantId, version.id()); + selected.sort(Comparator.comparing(asset -> asset.usageKey(), UTF8_BYTE_ORDER)); + Set usageKeys = new HashSet<>(); + Set assetIds = new HashSet<>(); + List prepared = new ArrayList<>(selected.size()); + for (SourceAsset source : selected) { + validateUsageKey(source.usageKey()); + if (source.assetId() == null) { + throw new IllegalStateException("Version asset source row identity is missing"); + } + if (!Objects.equals(source.usageKey(), source.fileName())) { + throw new IllegalStateException( + "Version asset usage key no longer matches its source file name"); + } + if (!usageKeys.add(source.usageKey()) || !assetIds.add(source.assetId())) { + throw new IllegalStateException( + "Version asset mapping contains a duplicate source or usage key"); + } + byte[] bytes = requireBytes(source.bytes()); + prepared.add( + new PreparedAsset( + source.usageKey(), + source.assetId(), + requireContentType(source.contentType()), + bytes, + digest(bytes))); + } + + for (PreparedAsset asset : prepared) { + dsl.execute( + "INSERT INTO version_asset_export_item " + + "(tenant_id, version_id, usage_key, asset_id, content_type, content_hash, byte_size) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + tenantId, + version.id(), + asset.usageKey(), + asset.assetId(), + asset.contentType(), + asset.contentDigest(), + (long) asset.bytes().length); + } + dsl.execute( + "INSERT INTO version_asset_export_snapshot " + + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, version_number, " + + "captured_version_state_epoch, item_count) VALUES (?, ?, ?, ?, ?, ?, ?)", + tenantId, + version.id(), + version.canonicalTenantId(), + version.canonicalVersionId(), + version.versionNumber(), + version.stateEpoch(), + prepared.size()); + + return readSnapshot(version); + } + + /** + * Reads only an already committed owner-local snapshot; absence is never interpreted as empty. + */ + public ExportSnapshot readFrozenSnapshot(String tenantId, int versionNumber) { + requireTenantId(tenantId); + if (versionNumber <= 0) { + throw new IllegalArgumentException("Version number must be positive"); + } + VersionRow version = + readVersionByTenantAndVersionNumber(tenantId, versionNumber) + .orElseThrow(() -> new IllegalStateException("Exact tenant Version was not found")); + qualifyVersion(version); + return readSnapshot(version); + } + + private ExportSnapshot readSnapshot(VersionRow version) { + Record header = + dsl.fetchOne( + "SELECT canonical_tenant_id, canonical_version_id, version_number, " + + "captured_version_state_epoch, item_count " + + "FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + version.tenantId(), + version.id()); + if (header == null) { + throw new IllegalStateException("No durable frozen Version asset snapshot exists"); + } + + UUID canonicalTenantId = header.get("canonical_tenant_id", UUID.class); + UUID canonicalVersionId = header.get("canonical_version_id", UUID.class); + Integer storedVersionNumber = header.get("version_number", Integer.class); + Long capturedEpoch = header.get("captured_version_state_epoch", Long.class); + Integer itemCount = header.get("item_count", Integer.class); + if (!Objects.equals(canonicalTenantId, version.canonicalTenantId()) + || !Objects.equals(canonicalVersionId, version.canonicalVersionId()) + || !Objects.equals(storedVersionNumber, version.versionNumber()) + || capturedEpoch == null + || capturedEpoch <= 0 + || version.stateEpoch() < capturedEpoch + || itemCount == null + || itemCount < 0) { + throw new IllegalStateException("Frozen Version asset snapshot identity is inconsistent"); + } + + long mappingCount = + Optional.ofNullable( + dsl.fetchOne( + "SELECT count(*) AS item_count FROM version_asset " + + "WHERE tenant_id = ? AND version_id = ?", + version.tenantId(), + version.id())) + .map(row -> row.get("item_count", Long.class)) + .orElse(0L); + if (mappingCount != itemCount.longValue()) { + throw new IllegalStateException( + "Frozen snapshot no longer matches its complete Version mapping set"); + } + + List rows = + dsl.fetch( + "SELECT i.usage_key AS snapshot_usage_key, i.asset_id AS snapshot_asset_id, " + + "i.content_type AS snapshot_content_type, i.content_hash AS snapshot_content_hash, " + + "i.byte_size AS snapshot_byte_size, va.usage_key AS mapping_usage_key, " + + "va.asset_id AS mapping_asset_id, ga.id AS source_asset_id, " + + "ga.tenant_id AS source_tenant_id, ga.file_name AS source_file_name, " + + "ga.content_type AS source_content_type, ga.data AS source_data " + + "FROM version_asset_export_item i " + + "LEFT JOIN version_asset va ON va.tenant_id = i.tenant_id " + + "AND va.version_id = i.version_id AND va.asset_id = i.asset_id " + + "AND va.usage_key = i.usage_key " + + "LEFT JOIN game_assets ga ON ga.tenant_id = i.tenant_id AND ga.id = i.asset_id " + + "WHERE i.tenant_id = ? AND i.version_id = ?", + version.tenantId(), + version.id()); + if (rows.size() != itemCount) { + throw new IllegalStateException("Frozen Version asset snapshot is incomplete"); + } + + List items = new ArrayList<>(rows.size()); + Set usageKeys = new HashSet<>(); + Set assetIds = new HashSet<>(); + for (Record row : rows) { + String usageKey = row.get("snapshot_usage_key", String.class); + Long snapshotAssetId = row.get("snapshot_asset_id", Long.class); + String snapshotType = row.get("snapshot_content_type", String.class); + String snapshotDigest = row.get("snapshot_content_hash", String.class); + Long snapshotSize = row.get("snapshot_byte_size", Long.class); + Long mappingAssetId = row.get("mapping_asset_id", Long.class); + String mappingUsageKey = row.get("mapping_usage_key", String.class); + Long sourceAssetId = row.get("source_asset_id", Long.class); + String sourceTenantId = row.get("source_tenant_id", String.class); + String sourceFileName = row.get("source_file_name", String.class); + String sourceType = row.get("source_content_type", String.class); + byte[] sourceData = row.get("source_data", byte[].class); + + validateUsageKey(usageKey); + requireContentType(sourceType); + if (snapshotAssetId == null + || snapshotType == null + || snapshotDigest == null + || snapshotSize == null + || !snapshotAssetId.equals(mappingAssetId) + || !Objects.equals(usageKey, mappingUsageKey) + || !snapshotAssetId.equals(sourceAssetId) + || !Objects.equals(version.tenantId(), sourceTenantId) + || !Objects.equals(usageKey, sourceFileName) + || !Objects.equals(snapshotType, sourceType) + || sourceData == null + || snapshotSize != sourceData.length + || !snapshotDigest.equals(digest(sourceData))) { + throw new IllegalStateException( + "Frozen Version asset source bytes or mapping failed verification"); + } + if (!usageKeys.add(usageKey) || !assetIds.add(snapshotAssetId)) { + throw new IllegalStateException( + "Frozen Version asset snapshot contains duplicate keys or sources"); + } + items.add( + new AssetSelection(usageKey, snapshotAssetId, sourceData, sourceType, snapshotDigest)); + } + items.sort(Comparator.comparing(AssetSelection::usageKey, UTF8_BYTE_ORDER)); + + return new ExportSnapshot( + version.tenantId(), + version.id(), + storedVersionNumber, + capturedEpoch, + canonicalTenantId, + canonicalVersionId, + items); + } + + private List lockMappedSourceAssets(String tenantId, long versionId) { + return dsl.fetch( + "SELECT va.usage_key, va.asset_id, ga.file_name, ga.content_type, ga.data " + + "FROM version_asset va " + + "JOIN game_assets ga ON ga.tenant_id = va.tenant_id AND ga.id = va.asset_id " + + "AND ga.file_name = va.usage_key " + + "WHERE va.tenant_id = ? AND va.version_id = ? " + + "ORDER BY va.asset_id FOR UPDATE OF ga", + tenantId, + versionId) + .map( + row -> + new SourceAsset( + row.get("usage_key", String.class), + row.get("asset_id", Long.class), + row.get("file_name", String.class), + row.get("content_type", String.class), + row.get("data", byte[].class))); + } + + private Optional findAssetForUpdate(String tenantId, long assetId) { + Record row = + dsl.fetchOne( + "SELECT file_name FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + assetId); + if (row == null) { + return Optional.empty(); + } + return Optional.of(new AssetRow(row.get("file_name", String.class))); + } + + private Optional lockVersionByTenantAndId(String tenantId, long versionId) { + return readVersion( + "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, " + + "identity_source_game_tenant_key, identity_source_provenance_kind " + + "FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + versionId); + } + + private Optional lockVersionByTenantAndVersionNumber( + String tenantId, int versionNumber) { + return readVersion( + "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, " + + "identity_source_game_tenant_key, identity_source_provenance_kind " + + "FROM version WHERE tenant_id = ? AND version_number = ? FOR UPDATE", + tenantId, + versionNumber); + } + + private Optional readVersionByTenantAndVersionNumber( + String tenantId, int versionNumber) { + return readVersion( + "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, " + + "identity_source_game_tenant_key, identity_source_provenance_kind " + + "FROM version WHERE tenant_id = ? AND version_number = ?", + tenantId, + versionNumber); + } + + private Optional readVersion(String sql, Object first, Object second) { + Record row = dsl.fetchOne(sql, first, second); + if (row == null) { + return Optional.empty(); + } + return Optional.of( + new VersionRow( + row.get("id", Long.class), + row.get("tenant_id", String.class), + row.get("version_number", Integer.class), + row.get("version_state", String.class), + row.get("version_state_epoch", Long.class), + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("identity_source_game_row_id", Long.class), + row.get("identity_source_game_tenant_key", String.class), + row.get("identity_source_provenance_kind", String.class))); + } + + private void qualifyVersion(VersionRow version) { + if (version.id() == null + || version.id() <= 0 + || version.tenantId() == null + || version.versionNumber() == null + || version.versionNumber() <= 0 + || version.stateEpoch() == null + || version.stateEpoch() <= 0 + || version.canonicalTenantId() == null + || version.canonicalVersionId() == null + || NIL_UUID.equals(version.canonicalTenantId()) + || NIL_UUID.equals(version.canonicalVersionId()) + || version.identitySourceGameRowId() == null + || version.identitySourceGameRowId() <= 0 + || !Objects.equals(version.tenantId(), version.identitySourceGameTenantKey()) + || !("NEW_GAME_ROW".equals(version.identitySourceProvenanceKind()) + || "RETAINED_GAME_V29".equals(version.identitySourceProvenanceKind()))) { + throw new IllegalStateException("Version lacks a complete canonical owner identity"); + } + Record game = + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id " + + "FROM game WHERE id = ? AND tenant_id = ?", + version.identitySourceGameRowId(), + version.identitySourceGameTenantKey()); + if (game == null + || !Objects.equals(game.get("canonical_tenant_id", UUID.class), version.canonicalTenantId()) + || !Objects.equals( + game.get("tenant_identity_provenance_kind", String.class), + version.identitySourceProvenanceKind()) + || !Objects.equals( + game.get("tenant_identity_source_game_id", Long.class), game.get("id", Long.class)) + || !Objects.equals( + game.get("tenant_identity_source_legacy_tenant_id", String.class), + version.tenantId())) { + throw new IllegalStateException( + "Version canonical identity does not match its exact source Game row"); + } + if (version.state() == null) { + throw new IllegalStateException("Version has an unexpected lifecycle state"); + } + try { + net.firedevops.firemud.gamedesign.model.VersionLifecycleState.valueOf(version.state()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Version has an unexpected lifecycle state", exception); + } + } + + private void requireDraft(VersionRow version) { + if (!"DRAFT".equals(version.state())) { + throw new IllegalStateException( + "Version asset mappings and first freeze require a Draft Version"); + } + } + + private void requireNoSnapshot(String tenantId, long versionId) { + if (hasSnapshot(tenantId, versionId)) { + throw new IllegalStateException( + "Version asset mappings are frozen by the durable export snapshot"); + } + } + + private boolean hasSnapshot(String tenantId, long versionId) { + return dsl.fetchOne( + "SELECT 1 FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId) + != null; + } + + private static void requireTenantId(String tenantId) { + if (tenantId == null || tenantId.isBlank()) { + throw new IllegalArgumentException("Owner-local tenant key is required"); + } + } + + private static void validateUsageKey(String usageKey) { + if (usageKey == null || usageKey.isBlank()) { + throw new IllegalStateException("Asset source file name cannot be a blank usage key"); + } + if ("manifest.json".equals(usageKey)) { + throw new IllegalStateException( + "Asset source file name collides with the reserved manifest.json key"); + } + } + + private static String requireContentType(String contentType) { + if (contentType == null || contentType.isBlank()) { + throw new IllegalStateException("Asset source content type is missing"); + } + return contentType; + } + + private static byte[] requireBytes(byte[] bytes) { + if (bytes == null) { + throw new IllegalStateException("Asset source bytes are missing"); + } + return bytes.clone(); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is not available", exception); + } + } + + private static int compareUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int compared = + Integer.compare( + Byte.toUnsignedInt(leftBytes[index]), Byte.toUnsignedInt(rightBytes[index])); + if (compared != 0) { + return compared; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private record VersionRow( + Long id, + String tenantId, + Integer versionNumber, + String state, + Long stateEpoch, + UUID canonicalTenantId, + UUID canonicalVersionId, + Long identitySourceGameRowId, + String identitySourceGameTenantKey, + String identitySourceProvenanceKind) {} + + private record AssetRow(String fileName) {} + + private record SourceAsset( + String usageKey, Long assetId, String fileName, String contentType, byte[] bytes) {} + + private record PreparedAsset( + String usageKey, long assetId, String contentType, byte[] bytes, String contentDigest) {} + + /** + * A defensive byte selection persisted in the immutable per-Version export projection. The + * numeric asset id is a private Game Design owner key, not an external identifier. + */ + public record AssetSelection( + String usageKey, long assetId, byte[] bytes, String contentType, String contentDigest) { + public AssetSelection { + Objects.requireNonNull(usageKey, "usageKey"); + Objects.requireNonNull(bytes, "bytes"); + Objects.requireNonNull(contentType, "contentType"); + Objects.requireNonNull(contentDigest, "contentDigest"); + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } + } + + /** + * Complete owner-local immutable readback for a frozen Version asset selection. Its tenant, + * Version, and asset numeric ids remain private owner keys; canonical UUIDs are read from + * persisted provenance and do not alias those keys. + */ + public record ExportSnapshot( + String tenantId, + long versionId, + int versionNumber, + long capturedVersionStateEpoch, + UUID canonicalTenantId, + UUID canonicalVersionId, + List items) { + public ExportSnapshot { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + items = List.copyOf(Objects.requireNonNull(items, "items")); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java index 8177e4b751..f8cdc098c5 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java @@ -6,14 +6,21 @@ import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; 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.TransactionDefinition; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; @Repository @SuppressFBWarnings( @@ -21,8 +28,40 @@ justification = "Injected DSLContext is an internal Spring collaborator.") public class VersionRepository { private static final Table VERSION_TABLE = DSL.table(DSL.name("version")); + private static final Table GAME_TABLE = DSL.table(DSL.name("game")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("identity_source_game_row_id"), Long.class); + private static final Field IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("identity_source_game_tenant_key"), String.class); + private static final Field IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("identity_source_provenance_kind"), String.class); + private static final Field VERSION_TENANT_ID = + DSL.field(DSL.name("version", "tenant_id"), String.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + DSL.field(DSL.name("version", "canonical_tenant_id"), UUID.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("version", "identity_source_game_row_id"), Long.class); + private static final Field VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("version", "identity_source_game_tenant_key"), String.class); + private static final Field VERSION_IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("version", "identity_source_provenance_kind"), String.class); + private static final Field GAME_ID = DSL.field(DSL.name("game", "id"), Long.class); + private static final Field GAME_TENANT_ID = + DSL.field(DSL.name("game", "tenant_id"), String.class); + private static final Field GAME_CANONICAL_TENANT_ID = + DSL.field(DSL.name("game", "canonical_tenant_id"), UUID.class); + private static final Field GAME_TENANT_PROVENANCE_KIND = + DSL.field(DSL.name("game", "tenant_identity_provenance_kind"), String.class); + private static final Field GAME_TENANT_SOURCE_GAME_ID = + DSL.field(DSL.name("game", "tenant_identity_source_game_id"), Long.class); + private static final Field GAME_TENANT_SOURCE_LEGACY_KEY = + DSL.field(DSL.name("game", "tenant_identity_source_legacy_tenant_id"), String.class); private static final Field VERSION_NUMBER = DSL.field(DSL.name("version_number"), Integer.class); private static final Field VERSION_STATE = @@ -40,6 +79,7 @@ public class VersionRepository { DSL.field(DSL.name("created_at"), Timestamp.class); private static final Field UPDATED_AT = DSL.field(DSL.name("updated_at"), Timestamp.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); private final DSLContext dsl; @@ -79,6 +119,56 @@ public Optional findByTenantIdAndId(String tenantId, Long id) { .fetchOne(this::toEntity)); } + /** Reads and locks the exact version row for owner-local guarded lifecycle writes. */ + public Optional findByTenantIdAndIdForUpdate(String tenantId, Long id) { + return Optional.ofNullable( + dsl.selectFrom(VERSION_TABLE) + .where(TENANT_ID.eq(tenantId).and(ID.eq(id))) + .forUpdate() + .fetchOne(this::toEntity)); + } + + /** + * Resolves only a canonical version UUID whose persisted tenant/source provenance still matches + * the exact Game Design owner row. Numeric Version IDs remain private to owner-local callers. + */ + public Optional findByCanonicalTenantIdAndCanonicalVersionId( + UUID canonicalTenantId, UUID canonicalVersionId) { + if (canonicalTenantId == null + || canonicalVersionId == null + || canonicalTenantId.equals(NIL_UUID) + || canonicalVersionId.equals(NIL_UUID)) { + return Optional.empty(); + } + + return Optional.ofNullable( + dsl.selectFrom(VERSION_TABLE) + .where( + CANONICAL_VERSION_ID + .eq(canonicalVersionId) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and( + DSL.exists( + DSL.selectOne() + .from(GAME_TABLE) + .where( + GAME_ID + .eq(VERSION_IDENTITY_SOURCE_GAME_ROW_ID) + .and( + GAME_TENANT_ID.eq( + VERSION_IDENTITY_SOURCE_GAME_TENANT_KEY)) + .and(GAME_TENANT_ID.eq(VERSION_TENANT_ID)) + .and( + GAME_CANONICAL_TENANT_ID.eq( + VERSION_CANONICAL_TENANT_ID)) + .and( + GAME_TENANT_PROVENANCE_KIND.eq( + VERSION_IDENTITY_SOURCE_PROVENANCE_KIND)) + .and(GAME_TENANT_SOURCE_GAME_ID.eq(GAME_ID)) + .and(GAME_TENANT_SOURCE_LEGACY_KEY.eq(GAME_TENANT_ID)))))) + .fetchOne(this::toEntity)); + } + /** * Returns every retained publication metadata candidate for an exact tenant/base/patch scope. * Callers reject anything other than one row so missing or duplicate retained scope is @@ -135,16 +225,36 @@ public long count() { return dsl.fetchCount(VERSION_TABLE); } + @Transactional(isolation = Isolation.READ_COMMITTED) public Version save(Version version) { + if (version.getId() == null + && version.getVersionState() == VersionLifecycleState.DRAFT + && !version.isScriptOnly() + && version.getBaseVersionId() == null + && version.getScriptPatchVersion() == null + && (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()))) { + throw new IllegalStateException( + "New full Draft creation requires one writable READ_COMMITTED source transaction"); + } LocalDateTime createdAt = version.getCreatedAt() == null ? LocalDateTime.now() : version.getCreatedAt(); LocalDateTime updatedAt = version.getUpdatedAt() == null ? LocalDateTime.now() : version.getUpdatedAt(); if (version.getId() == null) { + VersionSource source = findExactGameSource(version.getTenantId()); + UUID canonicalVersionId = newNonNilUuid(); Record record = Objects.requireNonNull( dsl.insertInto(VERSION_TABLE) .set(TENANT_ID, version.getTenantId()) + .set(CANONICAL_VERSION_ID, canonicalVersionId) + .set(CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(IDENTITY_SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(IDENTITY_SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(IDENTITY_SOURCE_PROVENANCE_KIND, source.provenanceKind()) .set(VERSION_NUMBER, version.getVersionNumber()) .set(VERSION_STATE, version.getVersionState().name()) .set(VERSION_STATE_EPOCH, version.getVersionStateEpoch()) @@ -157,6 +267,11 @@ public Version save(Version version) { .returning( ID, TENANT_ID, + CANONICAL_VERSION_ID, + CANONICAL_TENANT_ID, + IDENTITY_SOURCE_GAME_ROW_ID, + IDENTITY_SOURCE_GAME_TENANT_KEY, + IDENTITY_SOURCE_PROVENANCE_KIND, VERSION_NUMBER, VERSION_STATE, VERSION_STATE_EPOCH, @@ -167,7 +282,25 @@ public Version save(Version version) { CREATED_AT, UPDATED_AT) .fetchOne()); - return toEntity(record); + Version inserted = toEntity(record); + Version persisted = findById(inserted.getId()).orElseThrow(); + requireIssuedIdentityReadback(persisted, inserted.getTenantId(), canonicalVersionId, source); + if (persisted.getVersionState() == VersionLifecycleState.DRAFT + && !persisted.isScriptOnly() + && persisted.getBaseVersionId() == null + && persisted.getScriptPatchVersion() == null) { + new GameDesignSourceRepository(dsl) + .enrollFreshDraft( + new TargetProof( + persisted.getCanonicalTenantId(), + persisted.getCanonicalVersionId(), + persisted.getId(), + persisted.getTenantId(), + persisted.getIdentitySourceGameRowId(), + persisted.getIdentitySourceGameTenantKey(), + persisted.getIdentitySourceProvenanceKind())); + } + return persisted; } dsl.update(VERSION_TABLE) .set(TENANT_ID, version.getTenantId()) @@ -192,9 +325,25 @@ public void delete(Version version) { } private Version toEntity(Record record) { + return toEntity(record, true); + } + + /** The restricted baseline-lock function intentionally returns only its historical projection. */ + private Version toEntityWithoutCanonicalIdentity(Record record) { + return toEntity(record, false); + } + + private Version toEntity(Record record, boolean includeCanonicalIdentity) { Version version = new Version(); version.setId(record.get(ID)); version.setTenantId(record.get(TENANT_ID)); + if (includeCanonicalIdentity) { + version.setCanonicalVersionId(record.get(CANONICAL_VERSION_ID)); + version.setCanonicalTenantId(record.get(CANONICAL_TENANT_ID)); + version.setIdentitySourceGameRowId(record.get(IDENTITY_SOURCE_GAME_ROW_ID)); + version.setIdentitySourceGameTenantKey(record.get(IDENTITY_SOURCE_GAME_TENANT_KEY)); + version.setIdentitySourceProvenanceKind(record.get(IDENTITY_SOURCE_PROVENANCE_KIND)); + } version.setVersionNumber(record.get(VERSION_NUMBER)); String versionState = record.get(VERSION_STATE); version.setVersionState( @@ -212,4 +361,74 @@ private Version toEntity(Record record) { version.setUpdatedAt(updatedAt == null ? null : updatedAt.toLocalDateTime()); return version; } + + private VersionSource findExactGameSource(String tenantId) { + if (tenantId == null || tenantId.isBlank()) { + throw new IllegalStateException( + "New Version requires an exact Game Design source tenant key"); + } + Record source = + dsl.select( + GAME_ID, + GAME_TENANT_ID, + GAME_CANONICAL_TENANT_ID, + GAME_TENANT_PROVENANCE_KIND, + GAME_TENANT_SOURCE_GAME_ID, + GAME_TENANT_SOURCE_LEGACY_KEY) + .from(GAME_TABLE) + .where(GAME_TENANT_ID.eq(tenantId)) + .fetchOne(); + if (source == null) { + throw new IllegalStateException("New Version tenant has no exact Game Design source row"); + } + + Long sourceGameRowId = source.get(GAME_ID); + String sourceGameTenantKey = source.get(GAME_TENANT_ID); + UUID canonicalTenantId = source.get(GAME_CANONICAL_TENANT_ID); + String provenanceKind = source.get(GAME_TENANT_PROVENANCE_KIND); + Long tenantSourceGameRowId = source.get(GAME_TENANT_SOURCE_GAME_ID); + String tenantSourceGameTenantKey = source.get(GAME_TENANT_SOURCE_LEGACY_KEY); + if (sourceGameRowId == null + || sourceGameRowId <= 0 + || !tenantId.equals(sourceGameTenantKey) + || canonicalTenantId == null + || canonicalTenantId.equals(NIL_UUID) + || provenanceKind == null + || !("NEW_GAME_ROW".equals(provenanceKind) || "RETAINED_GAME_V29".equals(provenanceKind)) + || !sourceGameRowId.equals(tenantSourceGameRowId) + || !tenantId.equals(tenantSourceGameTenantKey)) { + throw new IllegalStateException( + "New Version tenant source provenance is incomplete or invalid"); + } + return new VersionSource( + canonicalTenantId, sourceGameRowId, sourceGameTenantKey, provenanceKind); + } + + private void requireIssuedIdentityReadback( + Version persisted, String requestedTenantKey, UUID canonicalVersionId, VersionSource source) { + if (persisted.getId() == null + || persisted.getId() <= 0 + || !requestedTenantKey.equals(persisted.getTenantId()) + || !canonicalVersionId.equals(persisted.getCanonicalVersionId()) + || !source.canonicalTenantId().equals(persisted.getCanonicalTenantId()) + || !source.sourceGameRowId().equals(persisted.getIdentitySourceGameRowId()) + || !source.sourceGameTenantKey().equals(persisted.getIdentitySourceGameTenantKey()) + || !source.provenanceKind().equals(persisted.getIdentitySourceProvenanceKind())) { + throw new IllegalStateException("Persisted Version identity did not match owner issuance"); + } + } + + private UUID newNonNilUuid() { + UUID uuid; + do { + uuid = UUID.randomUUID(); + } while (NIL_UUID.equals(uuid)); + return uuid; + } + + private record VersionSource( + UUID canonicalTenantId, + Long sourceGameRowId, + String sourceGameTenantKey, + String provenanceKind) {} } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java new file mode 100644 index 0000000000..a929542f41 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.gamedesign.service; + +import java.util.UUID; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; + +public interface CompleteLaunchBindingService { + CompleteLaunchBindingDto getCompleteLaunchBinding( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest); +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java index 8408f36f1c..c7706057dc 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/ExportedAssetManifest.java @@ -1,15 +1,65 @@ package net.firedevops.firemud.gamedesign.service; import java.util.List; +import java.util.Objects; + +/** Immutable result of constructing and verifying a version-scoped asset manifest. */ +public record ExportedAssetManifest( + String manifestHash, + Integer manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests) { + /** Process-local exports retain their original shape and carry no publication proof. */ + public ExportedAssetManifest(String manifestHash, List requiredManifestAssetKeys) { + this(manifestHash, null, requiredManifestAssetKeys, null); + } -public record ExportedAssetManifest(String manifestHash, List requiredManifestAssetKeys) { public ExportedAssetManifest { + if ((manifestSchemaVersion == null) != (artifactDigests == null)) { + throw new IllegalArgumentException( + "Manifest schema and artifact evidence must be present together"); + } + if (manifestSchemaVersion != null) { + Objects.requireNonNull(requiredManifestAssetKeys, "requiredManifestAssetKeys"); + } requiredManifestAssetKeys = - requiredManifestAssetKeys == null ? List.of() : List.copyOf(requiredManifestAssetKeys); + List.copyOf(requiredManifestAssetKeys == null ? List.of() : requiredManifestAssetKeys); + if (manifestSchemaVersion != null) { + if (manifestHash == null || !manifestHash.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "manifestHash must be a sha256-prefixed lowercase SHA-256 digest"); + } + if (manifestSchemaVersion <= 0) { + throw new IllegalArgumentException("manifestSchemaVersion must be positive"); + } + artifactDigests = List.copyOf(Objects.requireNonNull(artifactDigests)); + + List digestUsageKeys = + artifactDigests.stream().map(PublishedArtifactDigest::usageKey).toList(); + if (!requiredManifestAssetKeys.equals(digestUsageKeys)) { + throw new IllegalArgumentException( + "required manifest keys must exactly match the ordered artifact digest usage keys"); + } + for (int index = 1; index < requiredManifestAssetKeys.size(); index++) { + if (PublishedArtifactDigest.compareUsageKeysUtf8( + requiredManifestAssetKeys.get(index - 1), requiredManifestAssetKeys.get(index)) + >= 0) { + throw new IllegalArgumentException( + "manifest asset keys must be unique and in UTF-8 byte order"); + } + } + } + } + + public List artifactDigests() { + return artifactDigests == null ? null : List.copyOf(artifactDigests); } - @Override - public List requiredManifestAssetKeys() { - return requiredManifestAssetKeys; + /** Requires complete immutable evidence at the publication boundary. */ + public void requireImmutableArtifactEvidence() { + if (manifestSchemaVersion == null || artifactDigests == null) { + throw new IllegalStateException( + "Version-scoped immutable artifact evidence is required for publication"); + } } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java index 6403542e21..f80eee397f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java @@ -1,14 +1,39 @@ package net.firedevops.firemud.gamedesign.service; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; public interface LaunchDescriptorService { - ResolvedLaunchDescriptorDto resolveLaunchDescriptor( + /** Legacy caller cannot resolve a launch without the exact authored-world source binding. */ + default ResolvedLaunchDescriptorDto resolveLaunchDescriptor( String tenantId, long gameTemplateId, String controlPlaneRequestId, String requestedScriptPatchVersion, Long sourceVersionId, Long targetVersionId, - String requestedRuntimeFlagsJson); + String requestedRuntimeFlagsJson) { + throw new IllegalStateException( + "Canonical authored-world source binding is required for launch descriptor resolution"); + } + + ResolvedLaunchDescriptorDto resolveLaunchDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request request); + + ResolvedLaunchDescriptorDto getLaunchDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest); + + ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java new file mode 100644 index 0000000000..515197a302 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedArtifactDigest.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.gamedesign.service; + +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.StandardCharsets; +import java.util.Objects; + +/** Mandatory actual-byte proof for one immutable published asset object. */ +public record PublishedArtifactDigest( + String usageKey, + String artifactKind, + String immutableObjectKey, + String contentDigest, + String contentType, + int artifactSchemaVersion) { + private static final String SHA256_PREFIX = "sha256:"; + + public PublishedArtifactDigest { + requireCanonicalText(usageKey, "usageKey"); + requireCanonicalText(artifactKind, "artifactKind"); + requireCanonicalText(contentType, "contentType"); + if (artifactSchemaVersion <= 0) { + throw new IllegalArgumentException("artifactSchemaVersion must be positive"); + } + if (contentDigest == null || !contentDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "contentDigest must be a sha256-prefixed lowercase SHA-256 digest"); + } + String expectedObjectKey = + "artifacts/sha256/" + contentDigest.substring(SHA256_PREFIX.length()); + if (!Objects.equals(expectedObjectKey, immutableObjectKey)) { + throw new IllegalArgumentException("immutableObjectKey must address contentDigest"); + } + } + + public static int compareUsageKeysUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int comparison = Byte.compareUnsigned(leftBytes[index], rightBytes[index]); + if (comparison != 0) { + return comparison; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static void requireCanonicalText(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(fieldName + " must be nonblank"); + } + if (value.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(fieldName + " must not contain control characters"); + } + try { + StandardCharsets.UTF_8.newEncoder().encode(CharBuffer.wrap(value)); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(fieldName + " must be valid UTF-8 text", exception); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java index 4265e6884c..2b09e9d3e1 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishedReleaseBundleService.java @@ -6,6 +6,17 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; public interface PublishedReleaseBundleService { + /** + * Requires evidence already obtained over the authenticated World client before this transaction. + */ + PublishedReleaseBundleDto createFullVersionBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + java.util.List participantDigests, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence worldEvidence); + PublishedReleaseBundleDto createFullVersionBundle( VersionDto version, String publishWorkflowId, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java new file mode 100644 index 0000000000..8484c9dd2d --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcService.java @@ -0,0 +1,110 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import org.springframework.dao.DataAccessException; +import org.springframework.transaction.TransactionException; + +/** + * Standalone handler for the source-qualified version-state RPC. + * + *

This handler is deliberately not registered as a Spring gRPC service. The authenticated World + * intake remains disabled until the owning orchestrator explicitly wires and proves this boundary. + */ +public final class AuthoredWorldVersionStateGrpcService + extends GameDesignServiceGrpc.GameDesignServiceImplBase { + private final AuthoredWorldVersionStateService service; + private final String workloadNamespace; + + public AuthoredWorldVersionStateGrpcService( + AuthoredWorldVersionStateService service, String workloadNamespace) { + this.service = Objects.requireNonNull(service, "service"); + this.workloadNamespace = workloadNamespace; + } + + @Override + public void getAuthoredWorldVersionState( + GetAuthoredWorldVersionStateRequest request, + StreamObserver responseObserver) { + if (!isWorldManagementPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace World Management identity is required") + .asRuntimeException()); + return; + } + + final net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence.Request + decodedRequest; + try { + decodedRequest = AuthoredWorldVersionStateGrpcCodec.fromRequest(request); + if (!workloadNamespace.equals(decodedRequest.targetNamespace())) { + throw new IllegalArgumentException( + "Target namespace does not match this Game Design owner"); + } + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical authored-world version-state request is required") + .asRuntimeException()); + return; + } + + try { + var evidence = service.read(decodedRequest); + responseObserver.onNext(AuthoredWorldVersionStateGrpcCodec.toResponse(evidence)); + responseObserver.onCompleted(); + } catch (AuthoredWorldVersionStateService.NotFoundException exception) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No version state exists for the exact authored-world source") + .asRuntimeException()); + } catch (GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException + | IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source or version ownership is inconsistent") + .asRuntimeException()); + } catch (org.jooq.exception.TooManyRowsException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source or version ownership is ambiguous") + .asRuntimeException()); + } catch (DataAccessException | org.jooq.exception.DataAccessException exception) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Game Design owner storage is temporarily unavailable") + .asRuntimeException()); + } catch (TransactionException exception) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Game Design owner snapshot is temporarily unavailable") + .asRuntimeException()); + } catch (IllegalStateException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source or version state is invalid") + .asRuntimeException()); + } catch (RuntimeException exception) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Game Design could not read authored-world version state") + .asRuntimeException()); + } + } + + private boolean isWorldManagementPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java new file mode 100644 index 0000000000..4b3f130926 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Reads current version state only through the exact persisted authored-world source owner. */ +@Service +public final class AuthoredWorldVersionStateService { + private final GameAuthoredWorldSourceRepository sourceRepository; + private final TransactionTemplate ownerSnapshot; + + public AuthoredWorldVersionStateService( + PlatformTransactionManager transactionManager, + GameAuthoredWorldSourceRepository sourceRepository) { + this.sourceRepository = Objects.requireNonNull(sourceRepository, "sourceRepository"); + this.ownerSnapshot = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + this.ownerSnapshot.setName("authored-world-version-state-read"); + this.ownerSnapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerSnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.ownerSnapshot.setReadOnly(true); + this.ownerSnapshot.setTimeout(5); + } + + /** Reads source provenance, selector binding, and exact version state from one fresh snapshot. */ + public AuthoredWorldVersionStateEvidence read(AuthoredWorldVersionStateEvidence.Request request) { + Objects.requireNonNull(request, "request"); + Optional snapshot = + ownerSnapshot.execute( + status -> + sourceRepository.readVersionStateSnapshot( + request.targetNamespace(), + request.readRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + request.versionId())); + if (snapshot == null || snapshot.isEmpty()) { + throw new NotFoundException( + "No authored-world source or version exists for the exact requested owner tuple"); + } + AuthoredWorldVersionStateSnapshot result = snapshot.orElseThrow(); + return AuthoredWorldVersionStateEvidence.create( + request, + result.sourceEvidence(), + result.canonicalVersionId(), + toProtoState(result.versionState()), + result.versionStateEpoch()); + } + + private static VersionLifecycleState toProtoState( + net.firedevops.firemud.gamedesign.model.VersionLifecycleState state) { + Objects.requireNonNull(state, "state"); + try { + return VersionLifecycleState.valueOf("VERSION_LIFECYCLE_STATE_" + state.name()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Persisted version state has no closed wire enum", exception); + } + } + + public static final class NotFoundException extends RuntimeException { + public NotFoundException(String message) { + super(message); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java new file mode 100644 index 0000000000..d27efee5cf --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java @@ -0,0 +1,489 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.micrometer.core.annotation.Timed; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** Reads the already committed immutable launch descriptor and complete release evidence. */ +@Service +public class CompleteLaunchBindingServiceImpl implements CompleteLaunchBindingService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final int SUPPORTED_MANIFEST_SCHEMA_VERSION = 1; + private static final int SUPPORTED_ARTIFACT_SCHEMA_VERSION = 1; + + private final LaunchDescriptorService launchDescriptorService; + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + private final PublishedReleaseBundleService publishedReleaseBundleService; + private final VersionRepository versionRepository; + + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected Spring collaborators are internal; construction acquires no resources and this service has no finalizer.") + public CompleteLaunchBindingServiceImpl( + LaunchDescriptorService launchDescriptorService, + GameAuthoredWorldSourceRepository authoredWorldSourceRepository, + PublishedReleaseBundleService publishedReleaseBundleService, + VersionRepository versionRepository) { + this.launchDescriptorService = + Objects.requireNonNull(launchDescriptorService, "launchDescriptorService"); + this.authoredWorldSourceRepository = + Objects.requireNonNull(authoredWorldSourceRepository, "authoredWorldSourceRepository"); + this.publishedReleaseBundleService = + Objects.requireNonNull(publishedReleaseBundleService, "publishedReleaseBundleService"); + this.versionRepository = Objects.requireNonNull(versionRepository, "versionRepository"); + } + + @Override + @Transactional( + propagation = Propagation.REQUIRES_NEW, + readOnly = true, + isolation = Isolation.REPEATABLE_READ) + @Timed(value = "gamedesign.completeLaunchBinding.read") + public CompleteLaunchBindingDto getCompleteLaunchBinding( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + ResolvedLaunchDescriptorDto resolved = + launchDescriptorService.getLaunchDescriptorInOwnerSnapshot( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + AuthoredWorldLaunchDescriptorEvidence descriptor = + requireDescriptorMatchesSelector( + resolved, + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + + AuthoredWorldVersionStateSnapshot sourceSnapshot = + authoredWorldSourceRepository + .readVersionStateSnapshot( + workloadNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.versionId()) + .orElseThrow( + () -> + deny( + "AUTHORED_WORLD_SOURCE_NOT_FOUND", + "exact committed source or descriptor version is missing")); + AuthoredWorldSourceEvidence source = sourceSnapshot.sourceEvidence(); + requireSourceMatchesDescriptor(source, descriptor, canonicalTenantId, worldSlug); + if (sourceSnapshot.versionState() == null + || sourceSnapshot.versionStateEpoch() <= 0 + || sourceSnapshot.versionStateEpoch() < descriptor.versionStateEpoch()) { + throw deny("VERSION_STATE_INVALID", "same-snapshot Version state evidence is incomplete"); + } + // The current snapshot state is provenance/current-state context. The immutable descriptor + // epoch below remains the historical release binding and is not an activation decision. + + PublishedReleaseBundleDto bundle; + try { + bundle = + publishedReleaseBundleService.getPublishedReleaseBundle( + source.sourceGameTenantKey(), descriptor.versionId()); + } catch (PublishedReleaseBundleNotFoundException missing) { + throw deny( + "RELEASE_BUNDLE_NOT_FOUND", "the descriptor's committed release is missing", missing); + } + requireExactBundleBinding(bundle, source, descriptor, sourceSnapshot.canonicalVersionId()); + Version canonicalVersion = requireCanonicalVersion(bundle, source, descriptor, sourceSnapshot); + requireFullVersion(canonicalVersion, bundle); + + List participants = + requireParticipantEvidence(bundle, descriptor.versionId()); + String commitId = participants.getFirst().appliedCommitId(); + List artifacts = + requireManifestAndArtifactEvidence(bundle); + + AuthoredWorldReleaseAttestationEvidence releaseAttestation; + if ("v2".equals(bundle.attestationSchemaVersion())) { + releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersion.getCanonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + bundle.publishWorkflowId(), + commitId, + participants, + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + artifacts, + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.worldPublishedStartLocationEvidence()); + } else { + releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersion.getCanonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + bundle.publishWorkflowId(), + commitId, + participants, + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + artifacts, + bundle.commandDefinitions(), + bundle.generationConfigRevision()); + } + releaseAttestation.requireValid(descriptor); + return new CompleteLaunchBindingDto(descriptor, releaseAttestation); + } + + private AuthoredWorldLaunchDescriptorEvidence requireDescriptorMatchesSelector( + ResolvedLaunchDescriptorDto resolved, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + if (readRequestId == null || NIL_UUID.equals(readRequestId)) { + throw deny("INVALID_READ_REQUEST", "readRequestId must be a canonical non-nil UUID"); + } + if (resolved == null || resolved.authoredWorldBinding() == null) { + throw deny("LAUNCH_DESCRIPTOR_NOT_FOUND", "the exact committed descriptor is missing"); + } + AuthoredWorldLaunchDescriptorEvidence descriptor = resolved.authoredWorldBinding(); + try { + descriptor.requireValid(); + } catch (RuntimeException invalid) { + throw deny("LAUNCH_DESCRIPTOR_CONFLICT", "the exact descriptor evidence is invalid", invalid); + } + if (!Objects.equals(workloadNamespace, descriptor.targetNamespace()) + || !Objects.equals(canonicalTenantId, descriptor.canonicalTenantId()) + || !Objects.equals(worldSlug, descriptor.worldSlug()) + || !Objects.equals(controlPlaneRequestId, descriptor.controlPlaneRequestId()) + || !Objects.equals(expectedRequestDigest, descriptor.requestDigest()) + || !Objects.equals(expectedResultDigest, descriptor.resultDigest()) + || !Objects.equals(resolved.launchDescriptorId(), descriptor.launchDescriptorId()) + || !Objects.equals(resolved.canonicalTenantId(), descriptor.canonicalTenantId().toString()) + || !Objects.equals(resolved.controlPlaneRequestId(), descriptor.controlPlaneRequestId()) + || resolved.gameTemplateId() != descriptor.gameTemplateId() + || resolved.versionId() != descriptor.versionId() + || !Objects.equals(resolved.scriptPatchVersion(), descriptor.scriptPatchVersion()) + || !Objects.equals(resolved.runtimeFlagsJson(), descriptor.runtimeFlagsJson()) + || !Objects.equals( + resolved.generationConfigRevision(), descriptor.generationConfigRevision()) + || resolved.versionStateEpoch() != descriptor.versionStateEpoch() + || resolved.releaseBundleId() != descriptor.releaseBundleId() + || !Objects.equals( + resolved.publishedReleaseBundleRef(), descriptor.publishedReleaseBundleRef()) + || !Objects.equals(resolved.remapSetId(), descriptor.remapSetId())) { + throw deny( + "LAUNCH_DESCRIPTOR_CONFLICT", + "the resolved descriptor does not match the exact read selector and evidence"); + } + return descriptor; + } + + private void requireSourceMatchesDescriptor( + AuthoredWorldSourceEvidence source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID canonicalTenantId, + String worldSlug) { + if (source == null + || !Objects.equals(workloadNamespace, source.targetNamespace()) + || !Objects.equals(canonicalTenantId, source.canonicalTenantId()) + || !Objects.equals(worldSlug, source.worldSlug()) + || !Objects.equals(descriptor.canonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(descriptor.worldSlug(), source.worldSlug()) + || !Objects.equals(descriptor.authoredWorldSourceOperationId(), source.operationId()) + || !Objects.equals(descriptor.authoredWorldSourceEvidenceDigest(), source.evidenceDigest()) + || source.sourceGameRowId() <= 0 + || source.sourceGameTenantKey() == null + || source.sourceGameTenantKey().isBlank() + || source.provenanceKind() == null + || source.provenanceKind().isBlank()) { + throw deny("AUTHORED_WORLD_SOURCE_CHANGED", "source evidence does not match the descriptor"); + } + } + + private void requireExactBundleBinding( + PublishedReleaseBundleDto bundle, + AuthoredWorldSourceEvidence source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID snapshotCanonicalVersionId) { + if (bundle == null + || bundle.id() == null + || bundle.id() <= 0 + || bundle.versionId() == null + || bundle.versionId() <= 0 + || bundle.versionNumber() <= 0 + || bundle.canonicalTenantId() == null + || bundle.canonicalVersionId() == null + || NIL_UUID.equals(bundle.canonicalTenantId()) + || NIL_UUID.equals(bundle.canonicalVersionId()) + || snapshotCanonicalVersionId == null + || NIL_UUID.equals(snapshotCanonicalVersionId) + || !Objects.equals(snapshotCanonicalVersionId, bundle.canonicalVersionId()) + || !("v1".equals(bundle.attestationSchemaVersion()) + && bundle.worldPublishedStartLocationEvidence() == null + || "v2".equals(bundle.attestationSchemaVersion()) + && bundle.worldPublishedStartLocationEvidence() != null) + || !Objects.equals(bundle.id(), descriptor.releaseBundleId()) + || !Objects.equals(bundle.versionId(), descriptor.versionId()) + || !Objects.equals(bundle.tenantId(), source.sourceGameTenantKey()) + || !Objects.equals(bundle.canonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(bundle.generationConfigRevision(), descriptor.generationConfigRevision()) + || !Objects.equals( + bundle.publishedReleaseBundleRef(), descriptor.publishedReleaseBundleRef()) + || bundle.publishWorkflowId() == null + || bundle.publishWorkflowId().isBlank()) { + throw deny( + "RELEASE_ATTESTATION_MISMATCH", + "release bundle identity does not match the exact descriptor and source"); + } + } + + private Version requireCanonicalVersion( + PublishedReleaseBundleDto bundle, + AuthoredWorldSourceEvidence source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldVersionStateSnapshot sourceSnapshot) { + Version version = + versionRepository + .findByCanonicalTenantIdAndCanonicalVersionId( + bundle.canonicalTenantId(), bundle.canonicalVersionId()) + .orElseThrow( + () -> + deny( + "CANONICAL_VERSION_NOT_FOUND", + "release canonical Version identity has no exact persisted owner source")); + if (!Objects.equals(version.getId(), descriptor.versionId()) + || !Objects.equals(version.getTenantId(), source.sourceGameTenantKey()) + || !Objects.equals(version.getCanonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(version.getCanonicalVersionId(), bundle.canonicalVersionId()) + || !Objects.equals(version.getCanonicalVersionId(), sourceSnapshot.canonicalVersionId()) + || !Objects.equals(version.getIdentitySourceGameRowId(), source.sourceGameRowId()) + || !Objects.equals(version.getIdentitySourceGameTenantKey(), source.sourceGameTenantKey()) + || !Objects.equals(version.getIdentitySourceProvenanceKind(), source.provenanceKind()) + || !Objects.equals(version.getVersionNumber(), bundle.versionNumber()) + || version.getVersionState() != sourceSnapshot.versionState() + || !Objects.equals(version.getVersionStateEpoch(), sourceSnapshot.versionStateEpoch())) { + throw deny( + "CANONICAL_VERSION_MISMATCH", + "persisted Version UUID and Game source provenance do not match this release"); + } + return version; + } + + private void requireFullVersion(Version version, PublishedReleaseBundleDto bundle) { + if (version.isScriptOnly() + || version.getBaseVersionId() != null + || version.getScriptPatchVersion() != null + || bundle.scriptOnly() + || bundle.scriptPatchVersion() != null) { + throw deny( + "RELEASE_ATTESTATION_MISMATCH", + "a script-only publication cannot attest a full-Version launch descriptor"); + } + } + + private List requireParticipantEvidence( + PublishedReleaseBundleDto bundle, long versionId) { + List observed = bundle.participantDigests(); + List requiredParticipantOrder = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); + if (observed == null || observed.size() != requiredParticipantOrder.size()) { + throw deny( + "PARTICIPANT_EVIDENCE_INCOMPLETE", "exactly five full-Version owners are required"); + } + List participants = + new ArrayList<>(requiredParticipantOrder.size()); + String expectedScope = Long.toString(versionId); + String appliedCommitId = null; + for (int index = 0; index < requiredParticipantOrder.size(); index++) { + String expectedParticipantKey = requiredParticipantOrder.get(index); + int supportedDigestSchemaVersion = + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + expectedParticipantKey); + PublishParticipantDigestDto digest = observed.get(index); + if (digest == null + || !expectedParticipantKey.equals(digest.participantKey()) + || !expectedScope.equals(digest.scopeValue()) + || digest.baseVersionId() != null + || !digest.succeeded() + || (digest.errorMessage() != null && !digest.errorMessage().isBlank()) + || !isParticipantContentDigest(digest.contentDigest()) + || digest.digestSchemaVersion() == null + || digest.digestSchemaVersion() != supportedDigestSchemaVersion + || digest.appliedCommitId() == null + || digest.appliedCommitId().isBlank()) { + throw deny( + "PARTICIPANT_EVIDENCE_INVALID", + "full-Version participant evidence is missing, failed, unsupported, or out of order"); + } + if (appliedCommitId == null) { + appliedCommitId = digest.appliedCommitId(); + } else if (!appliedCommitId.equals(digest.appliedCommitId())) { + throw deny("PARTICIPANT_COMMIT_MISMATCH", "full-Version owners attest different commits"); + } + boolean abilityPresent = digest.abilitySchemaDigest() != null; + if ("GAME_LOGIC".equals(expectedParticipantKey)) { + if (!abilityPresent || !isDigest(digest.abilitySchemaDigest())) { + throw deny( + "ABILITY_SCHEMA_EVIDENCE_MISSING", + "Game Logic must provide its dedicated ability-schema digest"); + } + } else if (abilityPresent) { + throw deny( + "ABILITY_SCHEMA_EVIDENCE_OWNER_MISMATCH", + "only Game Logic may provide the ability-schema digest"); + } + participants.add( + new AuthoredWorldReleaseAttestationEvidence.Participant( + digest.participantKey(), + digest.scopeValue(), + false, + null, + digest.appliedCommitId(), + digest.contentDigest(), + digest.digestSchemaVersion(), + abilityPresent, + digest.abilitySchemaDigest())); + } + if (appliedCommitId == null || appliedCommitId.isBlank()) { + throw deny("PARTICIPANT_COMMIT_MISSING", "full-Version commit identity is missing"); + } + return List.copyOf(participants); + } + + private List requireManifestAndArtifactEvidence( + PublishedReleaseBundleDto bundle) { + if (!isDigest(bundle.manifestHash()) + || bundle.manifestSchemaVersion() == null + || bundle.manifestSchemaVersion() != SUPPORTED_MANIFEST_SCHEMA_VERSION + || bundle.requiredManifestAssetKeys() == null + || bundle.artifactDigests() == null + || bundle.commandDefinitions() == null + || bundle.commandDefinitions().stream().anyMatch(value -> value == null || value.isBlank()) + || bundle.generationConfigRevision() == null + || bundle.generationConfigRevision().isBlank()) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_INCOMPLETE", + "manifest, required-key, actual-artifact, command, or generation proof is missing"); + } + List requiredKeys = bundle.requiredManifestAssetKeys(); + for (int index = 0; index < requiredKeys.size(); index++) { + String key = requiredKeys.get(index); + if (key == null + || key.isBlank() + || (index > 0 + && PublishedArtifactDigest.compareUsageKeysUtf8(requiredKeys.get(index - 1), key) + >= 0)) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_INVALID", + "required manifest asset keys must be unique and in unsigned UTF-8 order"); + } + } + List observedArtifacts = bundle.artifactDigests(); + List artifacts = + new ArrayList<>(observedArtifacts.size()); + String previousUsageKey = null; + for (PublishedArtifactDigest artifact : observedArtifacts) { + if (artifact == null + || artifact.artifactSchemaVersion() != SUPPORTED_ARTIFACT_SCHEMA_VERSION + || (previousUsageKey != null + && PublishedArtifactDigest.compareUsageKeysUtf8(previousUsageKey, artifact.usageKey()) + >= 0)) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_INVALID", + "artifact entries must be unique and in unsigned UTF-8 usage-key order"); + } + previousUsageKey = artifact.usageKey(); + artifacts.add( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + artifact.usageKey(), + artifact.artifactKind(), + artifact.immutableObjectKey(), + artifact.contentDigest(), + artifact.contentType(), + artifact.artifactSchemaVersion())); + } + for (String requiredKey : requiredKeys) { + long matches = + observedArtifacts.stream() + .filter(artifact -> requiredKey.equals(artifact.usageKey())) + .count(); + if (matches != 1) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_MISMATCH", + "each required manifest key must select exactly one actual-byte artifact proof"); + } + } + return List.copyOf(artifacts); + } + + private boolean isDigest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private boolean isParticipantContentDigest(String value) { + return value != null && value.matches("[0-9a-f]{64}"); + } + + private IllegalArgumentException deny(String code, String detail) { + return new IllegalArgumentException("COMPLETE_LAUNCH_BINDING_" + code + ": " + detail); + } + + private IllegalArgumentException deny(String code, String detail, Throwable cause) { + return new IllegalArgumentException("COMPLETE_LAUNCH_BINDING_" + code + ": " + detail, cause); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java new file mode 100644 index 0000000000..5bc425144a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java @@ -0,0 +1,23 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +/** A deterministic launch business denial whose exact request outcome is stored by the owner. */ +final class FrozenLaunchDescriptorDenialException extends IllegalArgumentException { + private final String failureCode; + + static FrozenLaunchDescriptorDenialException create(String failureCode, String detail) { + return new FrozenLaunchDescriptorDenialException(failureCode, failureCode + ": " + detail); + } + + private FrozenLaunchDescriptorDenialException(String failureCode, String message) { + super(message); + this.failureCode = failureCode; + } + + static FrozenLaunchDescriptorDenialException fromStored(String failureCode, String message) { + return new FrozenLaunchDescriptorDenialException(failureCode, message); + } + + String failureCode() { + return failureCode; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 24087faa9f..6cdfb6c087 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -874,7 +874,7 @@ public void resolveLaunchDescriptor( builder.setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId(descriptor.launchDescriptorId()) - .setTenantId(descriptor.tenantId()) + .setCanonicalTenantId(descriptor.canonicalTenantId()) .setGameTemplateId(descriptor.gameTemplateId()) .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) .setVersionId(descriptor.versionId()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index 5b2c3139bb..f295ad77fc 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -1,20 +1,23 @@ package net.firedevops.firemud.gamedesign.service.impl; import io.micrometer.core.annotation.Timed; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.LinkedHashMap; -import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.UUID; import lombok.RequiredArgsConstructor; -import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +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 net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; @@ -22,249 +25,666 @@ import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; -import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import tools.jackson.core.exc.StreamReadException; +import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.ObjectMapper; @Service @RequiredArgsConstructor public class LaunchDescriptorServiceImpl implements LaunchDescriptorService { - private static final Logger logger = LoggingUtil.getLogger(LaunchDescriptorServiceImpl.class); - + private static final UUID NIL_UUID = new UUID(0L, 0L); private final GameTemplateRepository gameTemplateRepository; private final LaunchDescriptorRepository launchDescriptorRepository; private final VersionRepository versionRepository; private final PublishedReleaseBundleService publishedReleaseBundleService; private final TemplateRemapSetService templateRemapSetService; + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private final ObjectMapper objectMapper; + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + @Override - @Transactional + @Transactional(noRollbackFor = FrozenLaunchDescriptorDenialException.class) @Timed(value = "gamedesign.launchDescriptor.resolve") public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - String requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson) { - if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { + AuthoredWorldLaunchDescriptorEvidence.Request request) { + requireConfiguredNamespace(request.targetNamespace()); + launchDescriptorRepository.lockBoundRequest( + workloadNamespace, request.canonicalTenantId(), request.controlPlaneRequestId()); + String requestJson = writeJson(request); + + Optional stored = + launchDescriptorRepository.findBoundByRequest( + workloadNamespace, request.canonicalTenantId(), request.controlPlaneRequestId()); + if (stored.isPresent()) { + LaunchDescriptor descriptor = stored.orElseThrow(); + requireStoredRequestMatches(descriptor, request, requestJson); + AuthoredWorldSourceEvidence source = readExactSource(request); + String sourceJson = writeJson(source); + if (LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus())) { + throwStoredFailure( + descriptor, request, requestJson, sourceJson, source.sourceGameTenantKey()); + } + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { + throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_CONFLICT: stored outcome is unknown"); + } + return readStored(descriptor, request, requestJson, sourceJson); + } + AuthoredWorldSourceEvidence source = readExactSource(request); + String sourceJson = writeJson(source); + if (launchDescriptorRepository + .findByPrivateRequest(source.sourceGameTenantKey(), request.controlPlaneRequestId()) + .isPresent()) { throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: controlPlaneRequestId is required"); + "LAUNCH_DESCRIPTOR_CONFLICT: retained private-owner request history is unbound or bound to another canonical identity"); + } + + try { + return resolveNewLaunchDescriptor(request, source, requestJson, sourceJson); + } catch (FrozenLaunchDescriptorDenialException denial) { + LaunchDescriptor failure = frozenFailure(request, source, requestJson, sourceJson, denial); + LaunchDescriptor persisted = launchDescriptorRepository.insertImmutable(failure); + throwStoredFailure(persisted, request, requestJson, sourceJson, source.sourceGameTenantKey()); + throw new IllegalStateException("Persisted deterministic launch denial was not returned"); } + } + + private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { GameTemplateLaunchConfigView template = gameTemplateRepository - .findLaunchConfigByTenantIdAndId(tenantId, gameTemplateId) + .findLaunchConfigByTenantIdAndId(source.sourceGameTenantKey(), request.gameTemplateId()) + .filter(row -> row.getId() == request.gameTemplateId()) + .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) .orElseThrow( () -> - new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: game template not found")); - String requestHash = - hashRequest( - tenantId, - gameTemplateId, - controlPlaneRequestId, - requestedScriptPatchVersion, - sourceVersionId, - targetVersionId, - requestedRuntimeFlagsJson); - var existing = - launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - tenantId, gameTemplateId, controlPlaneRequestId); - if (existing.isPresent()) { - if (!existing.get().getRequestHash().equals(requestHash)) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: controlPlaneRequestId already resolved with different inputs"); - } - return toDto(existing.get()); - } + denial( + "INVALID_TEMPLATE_CONFIGURATION", + "template is not owned by the source game")); if (template.getTemplateReferencePhase() != TemplateReferencePhase.ENFORCED) { - throw new IllegalArgumentException( - "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + throw denial( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", "template reference phase is not enforced"); } - Long resolvedVersionId = - targetVersionId != null ? targetVersionId : template.getDefaultVersionId(); - if (resolvedVersionId == null || resolvedVersionId <= 0L) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: template defaultVersionId is required"); + Long versionId = + request.targetVersionIdPresent() + ? request.targetVersionId() + : template.getDefaultVersionId(); + if (versionId == null || versionId <= 0) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "template defaultVersionId is required"); } VersionDto version = versionRepository - .findById(resolvedVersionId) - .filter(found -> found.getTenantId().equals(tenantId)) + .findById(versionId) + .filter(row -> row.getId().equals(versionId)) + .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) .map( - found -> + row -> new VersionDto( - found.getId(), - found.getTenantId(), - found.getVersionNumber(), - found.getVersionState(), - found.getVersionStateEpoch(), - found.getScriptPatchVersion(), - found.getBaseVersionId(), - found.isScriptOnly(), - found.getNotes(), - found.getCreatedAt(), - found.getUpdatedAt())) + row.getId(), + row.getTenantId(), + row.getVersionNumber(), + row.getVersionState(), + row.getVersionStateEpoch(), + row.getScriptPatchVersion(), + row.getBaseVersionId(), + row.isScriptOnly(), + row.getNotes(), + row.getCreatedAt(), + row.getUpdatedAt())) .orElseThrow( () -> - new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: target version not found")); + denial( + "INVALID_TEMPLATE_CONFIGURATION", + "target version is not owned by the source game")); if (version.versionState() != VersionLifecycleState.PUBLISHED && version.versionState() != VersionLifecycleState.ACTIVE) { - throw new IllegalArgumentException( - "VERSION_STATE_EPOCH_STALE: resolved version is not activation-eligible"); + throw denial("VERSION_STATE_EPOCH_STALE", "resolved version is not activation-eligible"); } - String resolvedScriptPatchVersion = - resolveScriptPatchVersion(template, requestedScriptPatchVersion, version); - String resolvedRuntimeFlagsJson = resolveRuntimeFlagsJson(template, requestedRuntimeFlagsJson); + requireReadyScriptPatch( + request.requestedScriptPatchVersionPresent() + ? request.requestedScriptPatchVersion() + : null); + requireReadyScriptPatch(template.getDefaultScriptPatchVersion()); + requireReadyScriptPatch(version.scriptPatchVersion()); + String scriptPatch = resolveScriptPatchVersion(template, request, version); + String runtimeFlags = resolveRuntimeFlagsJson(template, request); + String remapSetId = null; - if (sourceVersionId != null && !sourceVersionId.equals(resolvedVersionId)) { - TemplateRemapSetDto remapSet = + if (request.sourceVersionIdPresent() && !request.sourceVersionId().equals(versionId)) { + TemplateRemapSetDto remap = templateRemapSetService - .findApprovedTemplateRemapSet(tenantId, sourceVersionId, resolvedVersionId) + .findApprovedTemplateRemapSet( + source.sourceGameTenantKey(), request.sourceVersionId(), versionId) .orElseThrow( () -> - new IllegalArgumentException( - "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); - remapSetId = remapSet.remapSetId(); + denial( + "LAUNCH_REMAP_REQUIRED", + "replacement-instance launch requires an approved remapSetId")); + remapSetId = remap.remapSetId(); + } + PublishedReleaseBundleDto bundle = + requirePublishedReleaseBundle(source.sourceGameTenantKey(), versionId); + if (!source.sourceGameTenantKey().equals(bundle.tenantId()) + || !Objects.equals(bundle.versionId(), versionId)) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "release bundle is not owned by the resolved source version"); + } + try { + PublishedReleaseBundleContract.requireSupportedSchemaForLaunchDescriptor(bundle); + } catch (IllegalArgumentException invalid) { + if (invalid.getMessage() != null + && invalid + .getMessage() + .startsWith(PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED + ":")) { + throw denial( + PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED, + "unsupported published release bundle attestation schema " + + bundle.attestationSchemaVersion()); + } + throw invalid; } - var bundle = requirePublishedReleaseBundle(tenantId, resolvedVersionId); - PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(bundle); + if (bundle.publishedReleaseBundleRef() == null + || bundle.publishedReleaseBundleRef().isBlank()) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "published release bundle has no persisted opaque reference"); + } + + String descriptorId = "ld-" + UUID.randomUUID(); + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptorId, + versionId, + scriptPatch != null, + scriptPatch, + runtimeFlags, + bundle.generationConfigRevision(), + version.versionStateEpoch(), + bundle.id(), + bundle.publishedReleaseBundleRef(), + remapSetId != null, + remapSetId); LaunchDescriptor descriptor = new LaunchDescriptor(); - descriptor.setLaunchDescriptorId("ld-" + UUID.randomUUID()); - descriptor.setTenantId(tenantId); - descriptor.setGameTemplateId(gameTemplateId); - descriptor.setControlPlaneRequestId(controlPlaneRequestId); - descriptor.setRequestHash(requestHash); - descriptor.setVersionId(resolvedVersionId); - descriptor.setScriptPatchVersion(resolvedScriptPatchVersion); - descriptor.setRuntimeFlagsJson(resolvedRuntimeFlagsJson); + descriptor.setLaunchDescriptorId(descriptorId); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setGameTemplateId(request.gameTemplateId()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(versionId); + descriptor.setScriptPatchVersion(scriptPatch); + descriptor.setRuntimeFlagsJson(runtimeFlags); descriptor.setGenerationConfigRevision(bundle.generationConfigRevision()); descriptor.setVersionStateEpoch(version.versionStateEpoch()); descriptor.setReleaseBundleId(bundle.id()); - descriptor.setPublishedReleaseBundleRef( - releaseBundleRef(tenantId, bundle.id(), resolvedVersionId)); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); descriptor.setRemapSetId(remapSetId); - logger.info( - "Resolved launch descriptor tenant={} template={} controlPlaneRequestId={} version={} remapSetId={}", - tenantId, - gameTemplateId, - controlPlaneRequestId, - resolvedVersionId, - remapSetId); - return toDto(launchDescriptorRepository.save(descriptor)); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(workloadNamespace); + descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); + descriptor.setWorldSlug(request.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + request.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + return readStored( + launchDescriptorRepository.insertImmutable(descriptor), request, requestJson, sourceJson); + } + + @Override + @Transactional(readOnly = true) + @Timed(value = "gamedesign.launchDescriptor.read") + public ResolvedLaunchDescriptorDto getLaunchDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + DescriptorReadContext context = + findExactSuccessfulDescriptor( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + LaunchDescriptor descriptor = context.descriptor(); + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = context.request(); + AuthoredWorldSourceEvidence source = readExactSource(storedRequest); + String sourceJson = writeJson(source); + if (!sourceJson.equals(descriptor.getSourceEvidenceJson())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); + } + return readStored( + descriptor, + storedRequest, + descriptor.getOriginalRequestJson(), + descriptor.getSourceEvidenceJson()); + } + + @Override + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + @Timed(value = "gamedesign.launchDescriptor.readOwnerSnapshot") + public ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + requireOwnerSnapshot(); + DescriptorReadContext context = + findExactSuccessfulDescriptor( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + LaunchDescriptor descriptor = context.descriptor(); + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = context.request(); + var sourceSnapshot = + authoredWorldSourceRepository + .readVersionStateSnapshot( + workloadNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + storedRequest.authoredWorldSourceOperationId(), + storedRequest.authoredWorldSourceEvidenceDigest(), + Objects.requireNonNull(descriptor.getVersionId(), "descriptor versionId")) + .orElseThrow( + () -> + new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source or version is missing")); + AuthoredWorldSourceEvidence source = sourceSnapshot.sourceEvidence(); + requireExactSource(storedRequest, source); + String sourceJson = writeJson(source); + if (!sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !Objects.equals(source.sourceGameTenantKey(), descriptor.getTenantId())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); + } + return readStored( + descriptor, + storedRequest, + descriptor.getOriginalRequestJson(), + descriptor.getSourceEvidenceJson()); + } + + private DescriptorReadContext findExactSuccessfulDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + if (readRequestId == null || NIL_UUID.equals(readRequestId)) { + throw new IllegalArgumentException("Canonical nonnil read request ID is required"); + } + requireConfiguredNamespace(workloadNamespace); + AuthoredWorldSourceDigest.validateReadSelector(workloadNamespace, canonicalTenantId, worldSlug); + if (controlPlaneRequestId == null + || controlPlaneRequestId.isBlank() + || !GameTenantCreationDigest.isDigest(expectedRequestDigest) + || !GameTenantCreationDigest.isDigest(expectedResultDigest)) { + throw new IllegalArgumentException("Exact descriptor read selector and digests are required"); + } + LaunchDescriptor descriptor = + launchDescriptorRepository + .findBoundByRequest(workloadNamespace, canonicalTenantId, controlPlaneRequestId) + .orElseThrow( + () -> + new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_NOT_FOUND: no descriptor exists for the exact request")); + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: request outcome is not a successful descriptor"); + } + if (descriptor.getDescriptorSchemaVersion() == null) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: retained descriptor history has no authored-world binding"); + } + if (!worldSlug.equals(descriptor.getWorldSlug()) + || !canonicalTenantId.toString().equals(descriptor.getCanonicalTenantId()) + || !expectedRequestDigest.equals(descriptor.getRequestDigest()) + || !expectedResultDigest.equals(descriptor.getResultDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match"); + } + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = + readRequest(descriptor.getOriginalRequestJson()); + return new DescriptorReadContext(descriptor, storedRequest); + } + + private AuthoredWorldSourceEvidence readExactSource( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + AuthoredWorldSourceEvidence source = + authoredWorldSourceRepository + .read( + request.authoredWorldSourceOperationId(), + request.canonicalTenantId(), + request.worldSlug(), + workloadNamespace) + .orElseThrow( + () -> + new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing")); + requireExactSource(request, source); + return source; + } + + private void requireExactSource( + AuthoredWorldLaunchDescriptorEvidence.Request request, AuthoredWorldSourceEvidence source) { + if (!workloadNamespace.equals(source.targetNamespace()) + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.worldSlug().equals(source.worldSlug()) + || !request.authoredWorldSourceOperationId().equals(source.operationId()) + || !request.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: source evidence does not match the exact request"); + } + } + + private void requireOwnerSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Launch descriptor snapshot read requires a read-only REPEATABLE_READ owner snapshot"); + } + } + + private record DescriptorReadContext( + LaunchDescriptor descriptor, AuthoredWorldLaunchDescriptorEvidence.Request request) {} + + private ResolvedLaunchDescriptorDto readStored( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + String sourceJson) { + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || descriptor.getFailureCode() != null + || descriptor.getFailureMessage() != null + || descriptor.getDescriptorSchemaVersion() == null + || !Objects.equals( + descriptor.getDescriptorSchemaVersion(), + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || request.gameTemplateId() != descriptor.getGameTemplateId() + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !request.requestDigest().equals(descriptor.getRequestDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored descriptor is not the exact immutable request"); + } + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptor.getLaunchDescriptorId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion() != null, + descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getVersionStateEpoch(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getRemapSetId() != null, + descriptor.getRemapSetId()); + evidence.requireValid(); + if (!evidence.resultDigest().equals(descriptor.getResultDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored resolved result digest is inconsistent"); + } + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private LaunchDescriptor frozenFailure( + AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson, + FrozenLaunchDescriptorDenialException denial) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(request.requestDigest()); + descriptor.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); + descriptor.setTargetNamespace(workloadNamespace); + descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); + descriptor.setWorldSlug(request.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + request.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(request.requestDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + descriptor.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); + descriptor.setFailureCode(denial.failureCode()); + descriptor.setFailureMessage(denial.getMessage()); + return descriptor; + } + + private void requireStoredRequestMatches( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson) { + if (!workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !requestJson.equals(descriptor.getOriginalRequestJson())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input"); + } + } + + private void throwStoredFailure( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + String sourceJson, + String sourceGameTenantKey) { + if (!LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()) + || !Objects.equals( + descriptor.getDescriptorSchemaVersion(), + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !sourceGameTenantKey.equals(descriptor.getTenantId()) + || descriptor.getLaunchDescriptorId() != null + || descriptor.getGameTemplateId() != null + || descriptor.getVersionId() != null + || descriptor.getScriptPatchVersion() != null + || descriptor.getRuntimeFlagsJson() != null + || descriptor.getGenerationConfigRevision() != null + || descriptor.getVersionStateEpoch() != null + || descriptor.getReleaseBundleId() != null + || descriptor.getPublishedReleaseBundleRef() != null + || descriptor.getRemapSetId() != null + || descriptor.getResultDigest() != null + || !isPersistableFailureCode(descriptor.getFailureCode()) + || descriptor.getFailureMessage() == null + || descriptor.getFailureMessage().isBlank()) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored failure is not the exact immutable request outcome"); + } + throw FrozenLaunchDescriptorDenialException.fromStored( + descriptor.getFailureCode(), descriptor.getFailureMessage()); + } + + private boolean isPersistableFailureCode(String failureCode) { + return switch (failureCode == null ? "" : failureCode) { + case "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", + "INVALID_TEMPLATE_CONFIGURATION", + "SCRIPT_PATCH_OVERRIDE_CONFLICT", + "SCRIPT_PATCH_NOT_READY", + "RELEASE_BUNDLE_NOT_FOUND", + "RELEASE_ATTESTATION_MISMATCH", + "VERSION_STATE_EPOCH_STALE", + "LAUNCH_REMAP_REQUIRED", + PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED -> + true; + default -> false; + }; + } + + private static FrozenLaunchDescriptorDenialException denial(String code, String detail) { + return FrozenLaunchDescriptorDenialException.create(code, detail); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request readRequest(String json) { + if (json == null) { + throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_UNBOUND: original request is missing"); + } + try { + AuthoredWorldLaunchDescriptorEvidence.Request request = + objectMapper.readValue(json, AuthoredWorldLaunchDescriptorEvidence.Request.class); + if (!writeJson(request).equals(json)) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: original request is not the closed owner encoding"); + } + return request; + } catch (Exception exception) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: original request is unreadable", exception); + } + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException( + "Launch descriptor evidence could not be serialized", exception); + } + } + + private void requireConfiguredNamespace(String requestNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !workloadNamespace.equals(requestNamespace)) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_NAMESPACE_MISMATCH: configured workload namespace is required"); + } } private String resolveScriptPatchVersion( GameTemplateLaunchConfigView template, - String requestedScriptPatchVersion, + AuthoredWorldLaunchDescriptorEvidence.Request request, VersionDto version) { String templateDefault = normalizeBlank(template.getDefaultScriptPatchVersion()); - String requested = normalizeBlank(requestedScriptPatchVersion); + String requested = + request.requestedScriptPatchVersionPresent() + ? normalizeBlank(request.requestedScriptPatchVersion()) + : null; if (templateDefault != null && requested != null && !templateDefault.equals(requested)) { - throw new IllegalArgumentException( - "SCRIPT_PATCH_OVERRIDE_CONFLICT: requested script patch conflicts with template default"); + throw denial( + "SCRIPT_PATCH_OVERRIDE_CONFLICT", + "requested script patch conflicts with template default"); } String resolved = requested != null ? requested : templateDefault; if (resolved != null && version.scriptPatchVersion() != null && !version.scriptPatchVersion().isBlank() && !version.scriptPatchVersion().equals(resolved)) { - throw new IllegalArgumentException( - "SCRIPT_PATCH_NOT_READY: requested script patch is not published for the resolved version"); + throw denial( + "SCRIPT_PATCH_NOT_READY", + "requested script patch is not published for the resolved version"); } return resolved; } private String resolveRuntimeFlagsJson( - GameTemplateLaunchConfigView template, String requestedRuntimeFlagsJson) { + GameTemplateLaunchConfigView template, + AuthoredWorldLaunchDescriptorEvidence.Request request) { String templateFlags = normalizeBlank(template.getDefaultRuntimeFlagsJson()) == null ? "{}" : template.getDefaultRuntimeFlagsJson(); - String requested = normalizeBlank(requestedRuntimeFlagsJson); + String requested = + request.requestedRuntimeFlagsJsonPresent() + ? normalizeBlank(request.requestedRuntimeFlagsJson()) + : null; if (requested == null) { return templateFlags; } if (!"{}".equals(templateFlags)) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: template-owned runtime flags cannot be overridden"); + throw denial( + "INVALID_TEMPLATE_CONFIGURATION", "template-owned runtime flags cannot be overridden"); } return requested; } - private net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto - requirePublishedReleaseBundle(String tenantId, long resolvedVersionId) { - try { - return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, resolvedVersionId); - } catch (PublishedReleaseBundleNotFoundException ex) { - throw new IllegalArgumentException( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version"); + private void requireReadyScriptPatch(String scriptPatchVersion) { + if (scriptPatchVersion != null && !scriptPatchVersion.isBlank()) { + throw denial( + "SCRIPT_PATCH_NOT_READY", + "exact published-for-base and Automation READY evidence is unavailable"); } } - private ResolvedLaunchDescriptorDto toDto(LaunchDescriptor descriptor) { - return new ResolvedLaunchDescriptorDto( - descriptor.getLaunchDescriptorId(), - descriptor.getTenantId(), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId(), - descriptor.getVersionId(), - descriptor.getScriptPatchVersion(), - descriptor.getRuntimeFlagsJson(), - descriptor.getGenerationConfigRevision(), - descriptor.getVersionStateEpoch(), - descriptor.getReleaseBundleId(), - descriptor.getPublishedReleaseBundleRef(), - descriptor.getRemapSetId()); - } - - private String hashRequest( - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - String requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson) { - Map request = new LinkedHashMap<>(); - request.put("tenantId", tenantId); - request.put("gameTemplateId", gameTemplateId); - request.put("controlPlaneRequestId", controlPlaneRequestId); - request.put("requestedScriptPatchVersion", normalizeBlank(requestedScriptPatchVersion)); - request.put("sourceVersionId", sourceVersionId); - request.put("targetVersionId", targetVersionId); - request.put("requestedRuntimeFlagsJson", normalizeBlank(requestedRuntimeFlagsJson)); + private PublishedReleaseBundleDto requirePublishedReleaseBundle(String tenantId, long versionId) { try { - return sha256(objectMapper.writeValueAsString(request)); - } catch (StreamReadException | tools.jackson.databind.DatabindException ex) { - throw new IllegalStateException("failed to hash launch descriptor request", ex); - } - } - - private String releaseBundleRef(String tenantId, long bundleId, long versionId) { - return "prb:" + tenantId + ":" + versionId + ":" + bundleId; - } - - private String sha256(String value) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] bytes = digest.digest(value.getBytes(StandardCharsets.UTF_8)); - StringBuilder builder = new StringBuilder(bytes.length * 2); - for (byte current : bytes) { - builder.append(String.format("%02x", current)); - } - return builder.toString(); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("sha-256 unavailable", ex); + return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, versionId); + } catch (PublishedReleaseBundleNotFoundException exception) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "no published release bundle for the resolved version"); } } - private String normalizeBlank(String value) { + private static String normalizeBlank(String value) { return value == null || value.isBlank() ? null : value; } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java index 2ccccc8651..24f62bbc0c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java @@ -1,18 +1,112 @@ package net.firedevops.firemud.gamedesign.service.impl; +import java.util.Arrays; +import java.util.HashSet; import java.util.List; import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; final class PublishedReleaseBundleContract { static final String SUPPORTED_ATTESTATION_SCHEMA_VERSION = "v1"; + static final String SELECTOR_ATTESTATION_SCHEMA_VERSION = "v2"; static final String SCHEMA_VERSION_UNSUPPORTED = "SCHEMA_VERSION_UNSUPPORTED"; static final String REPAIR_ATTESTATION_MISMATCH = "REPAIR_ATTESTATION_MISMATCH"; static final String REPAIR_ATTESTED_ASSET_KEY_MISMATCH = "REPAIR_ATTESTED_ASSET_KEY_MISMATCH"; private PublishedReleaseBundleContract() {} + static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { + new ExportedAssetManifest( + bundle.manifestHash(), + Objects.requireNonNull(bundle.manifestSchemaVersion(), "manifestSchemaVersion"), + bundle.requiredManifestAssetKeys(), + Objects.requireNonNull(bundle.artifactDigests(), "artifactDigests")); + var evidence = + Objects.requireNonNull(bundle.worldPublishedStartLocationEvidence(), "World evidence"); + var request = evidence.request(); + if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion()) + || bundle.scriptOnly() + || bundle.scriptPatchVersion() != null + || !request.canonicalTenantId().equals(bundle.canonicalTenantId()) + || !request.canonicalVersionId().equals(bundle.canonicalVersionId()) + || !request.publishWorkflowId().equals(bundle.publishWorkflowId()) + || bundle.manifestSchemaVersion() == null + || bundle.artifactDigests() == null) { + throw new IllegalArgumentException( + "World selector differs from complete immutable release binding"); + } + var required = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); + var seen = new HashSet(); + for (var participant : bundle.participantDigests()) { + if (!required.contains(participant.participantKey()) + || !seen.add(participant.participantKey()) + || !participant.succeeded() + || participant.baseVersionId() != null + || !Long.toString(bundle.versionId()).equals(participant.scopeValue()) + || !request.appliedCommitId().equals(participant.appliedCommitId()) + || participant.contentDigest() == null + || !participant.contentDigest().matches("[0-9a-f]{64}") + || !Objects.equals( + participant.digestSchemaVersion(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant.participantKey()))) { + throw new IllegalArgumentException( + "World selector requires all exact successful release participants"); + } + if ("WORLD_MANAGEMENT".equals(participant.participantKey()) + && (!request.contentDigest().equals(participant.contentDigest()) + || request.digestSchemaVersion() != participant.digestSchemaVersion())) { + throw new IllegalArgumentException( + "World selector differs from World participant digest/schema"); + } + if ("GAME_LOGIC".equals(participant.participantKey()) + && (participant.abilitySchemaDigest() == null + || !participant.abilitySchemaDigest().matches("sha256:[0-9a-f]{64}"))) { + throw new IllegalArgumentException( + "World selector release lacks Game Logic ability schema proof"); + } + } + if (seen.size() != required.size()) { + throw new IllegalArgumentException("World selector release lacks required participants"); + } + } + + static void requireExactSelectorRetry( + PublishedReleaseBundleDto stored, + VersionDto version, + String workflow, + ExportedAssetManifest manifest, + String generationRevision, + List participants, + WorldPublishedStartLocationEvidence evidence) { + if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: historical release is selector-ineligible"); + } + requireSelectorBinding(stored); + if (stored.versionNumber() != version.versionNumber() + || version.scriptOnly() + || version.scriptPatchVersion() != null + || !Objects.equals(stored.publishWorkflowId(), workflow) + || !Objects.equals(stored.manifestHash(), manifest.manifestHash()) + || !Objects.equals(stored.manifestSchemaVersion(), manifest.manifestSchemaVersion()) + || !Objects.equals(stored.artifactDigests(), manifest.artifactDigests()) + || !stored.requiredManifestAssetKeys().equals(manifest.requiredManifestAssetKeys()) + || !Objects.equals(stored.generationConfigRevision(), generationRevision) + || !stored.participantDigests().equals(participants) + || !Arrays.equals( + stored.worldPublishedStartLocationEvidence().canonicalBytes(), + evidence.canonicalBytes())) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: changed immutable selector release input"); + } + } + static void requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalStateException( @@ -22,6 +116,17 @@ static void requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { } } + /** + * Publication reconciliation only; does not widen launch or repair authorization/schema support. + */ + static void requireSupportedSchemaForPublicationRead(PublishedReleaseBundleDto bundle) { + if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectorBinding(bundle); + return; + } + requireSupportedSchemaForRead(bundle); + } + static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { if (!SUPPORTED_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { throw new IllegalArgumentException( @@ -31,9 +136,26 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { } } + /** + * Descriptor resolution only; descriptor/v1 remains separate from the complete release carrier. + */ + static void requireSupportedSchemaForLaunchDescriptor(PublishedReleaseBundleDto bundle) { + if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + requireSelectorBinding(bundle); + return; + } + requireSupportedSchemaForLaunch(bundle); + } + static void requireExactRepairMatch( PublishedReleaseBundleDto bundle, ExportedAssetManifest exportedManifest) { requireSupportedSchemaForRead(bundle); + if (!Objects.equals(bundle.manifestSchemaVersion(), exportedManifest.manifestSchemaVersion()) + || !Objects.equals(bundle.artifactDigests(), exportedManifest.artifactDigests())) { + throw new IllegalStateException( + REPAIR_ATTESTATION_MISMATCH + + ": repair could not reproduce the attested artifact/schema proof"); + } if (!Objects.equals(bundle.manifestHash(), exportedManifest.manifestHash())) { throw new IllegalStateException( REPAIR_ATTESTATION_MISMATCH + ": repair could not reproduce the attested manifest hash"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index 61800e105d..cabb5d10ce 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -9,13 +10,17 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -29,15 +34,19 @@ public class PublishedReleaseBundleServiceImpl implements PublishedReleaseBundle private final PublishedReleaseBundleRepository repository; private final RevisionRepository revisionRepository; + private final VersionRepository versionRepository; private final ObjectMapper objectMapper; public PublishedReleaseBundleServiceImpl( PublishedReleaseBundleRepository repository, RevisionRepository revisionRepository, + VersionRepository versionRepository, ObjectMapper objectMapper) { this.repository = Objects.requireNonNull(repository, "repository must not be null"); this.revisionRepository = Objects.requireNonNull(revisionRepository, "revisionRepository must not be null"); + this.versionRepository = + Objects.requireNonNull(versionRepository, "versionRepository must not be null"); this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); } @@ -49,38 +58,125 @@ public PublishedReleaseBundleDto createFullVersionBundle( ExportedAssetManifest exportedManifest, String generationConfigRevision, List participantDigests) { + return createBundle( + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests, + null); + } + + @Override + @Transactional + public PublishedReleaseBundleDto createFullVersionBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + List participantDigests, + WorldPublishedStartLocationEvidence worldEvidence) { + Objects.requireNonNull(worldEvidence, "Authenticated World evidence is required"); + return createBundle( + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests, + worldEvidence); + } + + private PublishedReleaseBundleDto createBundle( + VersionDto version, + String publishWorkflowId, + ExportedAssetManifest exportedManifest, + String generationConfigRevision, + List participantDigests, + WorldPublishedStartLocationEvidence worldEvidence) { Objects.requireNonNull(version, "version must not be null"); Objects.requireNonNull(exportedManifest, "exportedManifest must not be null"); + exportedManifest.requireImmutableArtifactEvidence(); Objects.requireNonNull(participantDigests, "participantDigests must not be null"); - repository - .findByTenantIdAndVersionId(version.tenantId(), version.id()) - .ifPresent( - ignored -> { - throw new IllegalStateException("published release bundle already exists"); - }); + Optional existing = + repository.findByTenantIdAndVersionId(version.tenantId(), version.id()); + if (existing.isPresent() && worldEvidence == null) { + throw new IllegalStateException("published release bundle already exists"); + } + if (existing.isPresent()) { + PublishedReleaseBundleDto stored = toDto(existing.orElseThrow()); + PublishedReleaseBundleContract.requireExactSelectorRetry( + stored, + version, + publishWorkflowId, + exportedManifest, + generationConfigRevision, + participantDigests, + worldEvidence); + List originalCommandDefinitions = + repository.requireSelectedCommandDefinitions( + stored.tenantId(), + stored.versionId(), + stored.publishWorkflowId(), + stored.worldPublishedStartLocationEvidence()); + if (!stored.commandDefinitions().equals(originalCommandDefinitions)) { + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: stored command definitions differ from the original source capture"); + } + return stored; + } + var identitySource = + versionRepository + .findByTenantIdAndId(version.tenantId(), version.id()) + .orElseThrow( + () -> + new IllegalStateException( + "published release canonical identity source missing")); + UUID canonicalTenantId = identitySource.getCanonicalTenantId(); + UUID canonicalVersionId = identitySource.getCanonicalVersionId(); + if (!version.id().equals(identitySource.getId()) + || !version.tenantId().equals(identitySource.getTenantId()) + || !isCanonicalNonNilUuid(canonicalTenantId) + || !isCanonicalNonNilUuid(canonicalVersionId)) { + throw new IllegalStateException("published release canonical identity source is invalid"); + } PublishedReleaseBundle entity = new PublishedReleaseBundle(); entity.setTenantId(version.tenantId()); entity.setVersionId(version.id()); + entity.setCanonicalTenantId(canonicalTenantId); + entity.setCanonicalVersionId(canonicalVersionId); entity.setVersionNumber(version.versionNumber()); entity.setAttestationSchemaVersion( - PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION); + worldEvidence == null + ? PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION + : PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION); + entity.setWorldPublishedStartLocationEvidenceJson( + worldEvidence == null + ? null + : new String(worldEvidence.canonicalBytes(), StandardCharsets.UTF_8)); entity.setPublishWorkflowId(publishWorkflowId); entity.setManifestHash(exportedManifest.manifestHash()); + entity.setManifestSchemaVersion(exportedManifest.manifestSchemaVersion()); + entity.setArtifactDigestsJson( + objectMapper.writeValueAsString(exportedManifest.artifactDigests())); entity.setGenerationConfigRevision(generationConfigRevision); entity.setRequiredManifestAssetKeysJson( serializeKeys(exportedManifest.requiredManifestAssetKeys())); entity.setParticipantDigestsJson(serializeParticipantDigests(participantDigests)); List commandDefinitions = - revisionRepository - .findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( - version.tenantId(), version.id(), "COMMAND_DEFINITION") - .stream() - .map(revision -> revision.getData()) - .toList(); + worldEvidence == null + ? revisionRepository + .findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( + version.tenantId(), version.id(), "COMMAND_DEFINITION") + .stream() + .map(revision -> revision.getData()) + .toList() + : repository.requireSelectedCommandDefinitions( + version.tenantId(), version.id(), publishWorkflowId, worldEvidence); validateDistinctCommandDefinitions(commandDefinitions); entity.setCommandDefinitionsJson(serializeCommandDefinitions(commandDefinitions)); entity.setScriptOnly(version.scriptOnly()); entity.setScriptPatchVersion(version.scriptPatchVersion()); + if (worldEvidence != null) toDto(entity); return toDto(repository.save(entity)); } @@ -99,21 +195,48 @@ public Optional findPublishedReleaseBundle( } private PublishedReleaseBundleDto toDto(PublishedReleaseBundle entity) { - return new PublishedReleaseBundleDto( - entity.getId(), - entity.getTenantId(), - entity.getVersionId(), - entity.getVersionNumber(), - entity.getAttestationSchemaVersion(), - entity.getPublishWorkflowId(), - entity.getManifestHash(), - deserializeKeys(entity.getRequiredManifestAssetKeysJson()), - deserializeParticipantDigests(entity.getParticipantDigestsJson()), - deserializeCommandDefinitions(entity.getCommandDefinitionsJson()), - entity.getGenerationConfigRevision(), - entity.isScriptOnly(), - entity.getScriptPatchVersion(), - entity.getPublishedAt()); + PublishedReleaseBundleDto dto = + new PublishedReleaseBundleDto( + entity.getId(), + entity.getTenantId(), + entity.getVersionId(), + entity.getVersionNumber(), + entity.getAttestationSchemaVersion(), + entity.getPublishWorkflowId(), + entity.getManifestHash(), + deserializeKeys(entity.getRequiredManifestAssetKeysJson()), + deserializeParticipantDigests(entity.getParticipantDigestsJson()), + deserializeCommandDefinitions(entity.getCommandDefinitionsJson()), + entity.getGenerationConfigRevision(), + entity.isScriptOnly(), + entity.getScriptPatchVersion(), + entity.getPublishedAt(), + entity.getCanonicalTenantId(), + entity.getCanonicalVersionId(), + entity.getPublishedReleaseBundleRef(), + entity.getManifestSchemaVersion(), + entity.getArtifactDigestsJson() == null + ? null + : objectMapper.readValue( + entity.getArtifactDigestsJson(), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)), + entity.getWorldPublishedStartLocationEvidenceJson() == null + ? null + : WorldPublishedStartLocationEvidence.fromStored( + entity + .getWorldPublishedStartLocationEvidenceJson() + .getBytes(StandardCharsets.UTF_8))); + if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + dto.attestationSchemaVersion())) { + PublishedReleaseBundleContract.requireSelectorBinding(dto); + } + return dto; + } + + private boolean isCanonicalNonNilUuid(UUID value) { + return value != null && !value.equals(new UUID(0L, 0L)); } private String serializeKeys(List keys) { diff --git a/services/game-design-service/src/main/resources/db/migration/V33__authored_world_source_operations.sql b/services/game-design-service/src/main/resources/db/migration/V33__authored_world_source_operations.sql new file mode 100644 index 0000000000..61da5a5085 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V33__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/V35.1__canonical_version_identity.sql b/services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql new file mode 100644 index 0000000000..c96657e892 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql @@ -0,0 +1,116 @@ +ALTER TABLE version + ADD COLUMN canonical_version_id UUID, + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN identity_source_game_row_id BIGINT, + ADD COLUMN identity_source_game_tenant_key VARCHAR(36), + ADD COLUMN identity_source_provenance_kind VARCHAR(32); + +ALTER TABLE version + ADD CONSTRAINT uq_version_canonical_version_id UNIQUE (canonical_version_id), + ADD CONSTRAINT fk_version_identity_source_game + FOREIGN KEY (identity_source_game_row_id) REFERENCES game(id), + ADD CONSTRAINT chk_version_canonical_identity_shape CHECK ( + (canonical_version_id IS NULL + AND canonical_tenant_id IS NULL + AND identity_source_game_row_id IS NULL + AND identity_source_game_tenant_key IS NULL + AND identity_source_provenance_kind IS NULL) + OR + (canonical_version_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND identity_source_game_row_id IS NOT NULL + AND identity_source_game_row_id > 0 + AND identity_source_game_tenant_key IS NOT NULL + AND char_length(identity_source_game_tenant_key) BETWEEN 1 AND 36 + AND identity_source_game_tenant_key !~ '^[[:space:]]*$' + AND identity_source_provenance_kind IS NOT NULL + AND identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29')) + ); + +-- [jooq ignore start] +CREATE FUNCTION enforce_version_canonical_identity() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.canonical_version_id IS NOT NULL THEN + RAISE EXCEPTION 'canonical Version identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.canonical_version_id IS NULL + OR NEW.canonical_tenant_id IS NULL + OR NEW.identity_source_game_row_id IS NULL + OR NEW.identity_source_game_tenant_key IS NULL + OR NEW.identity_source_provenance_kind IS NULL THEN + RAISE EXCEPTION 'new Version rows require an owner-issued canonical identity' + USING ERRCODE = 'check_violation'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM game g + WHERE g.id = NEW.identity_source_game_row_id + AND g.tenant_id = NEW.identity_source_game_tenant_key + AND NEW.tenant_id = g.tenant_id + AND g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind = NEW.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) THEN + RAISE EXCEPTION 'canonical Version identity source does not match its exact game row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF OLD.canonical_version_id IS NULL THEN + IF NEW.canonical_version_id IS NOT NULL + OR NEW.canonical_tenant_id IS NOT NULL + OR NEW.identity_source_game_row_id IS NOT NULL + OR NEW.identity_source_game_tenant_key IS NOT NULL + OR NEW.identity_source_provenance_kind IS NOT NULL THEN + RAISE EXCEPTION 'retained Version rows cannot be assigned a canonical identity' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.id IS DISTINCT FROM OLD.id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.identity_source_game_row_id IS DISTINCT FROM OLD.identity_source_game_row_id + OR NEW.identity_source_game_tenant_key IS DISTINCT FROM OLD.identity_source_game_tenant_key + OR NEW.identity_source_provenance_kind IS DISTINCT FROM OLD.identity_source_provenance_kind THEN + RAISE EXCEPTION 'canonical Version identity and its tenant source are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_canonical_identity_immutable + BEFORE INSERT OR UPDATE OR DELETE ON version + FOR EACH ROW + EXECUTE FUNCTION enforce_version_canonical_identity(); + +CREATE FUNCTION reject_version_canonical_identity_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM version WHERE canonical_version_id IS NOT NULL) THEN + RAISE EXCEPTION 'canonical Version identities cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_canonical_identity_no_truncate + BEFORE TRUNCATE ON version + FOR EACH STATEMENT + EXECUTE FUNCTION reject_version_canonical_identity_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql b/services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql new file mode 100644 index 0000000000..298842ed3f --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql @@ -0,0 +1,86 @@ +ALTER TABLE version + ADD CONSTRAINT uq_version_release_canonical_identity + UNIQUE (id, canonical_tenant_id, canonical_version_id); + +ALTER TABLE published_release_bundle + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN canonical_version_id UUID, + ADD CONSTRAINT chk_published_release_bundle_canonical_identity CHECK ( + (canonical_tenant_id IS NULL AND canonical_version_id IS NULL) + OR + (canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID) + ), + ADD CONSTRAINT fk_published_release_bundle_canonical_version + FOREIGN KEY (version_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id); + +-- [jooq ignore start] +CREATE FUNCTION enforce_published_release_bundle_immutability() RETURNS trigger AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'published release bundle metadata is retained' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.canonical_tenant_id IS NULL + OR NEW.canonical_version_id IS NULL + OR NEW.canonical_tenant_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.canonical_version_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'new published release bundles require a non-nil canonical identity' + USING ERRCODE = 'check_violation'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + WHERE v.id = NEW.version_id + AND v.tenant_id = NEW.tenant_id + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id > 0 + AND v.identity_source_game_tenant_key = v.tenant_id + AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + AND g.tenant_id = v.tenant_id + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) THEN + RAISE EXCEPTION 'published release bundle identity does not match its exact Version and Game source' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + RAISE EXCEPTION 'published release bundle attestation is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_published_release_bundle_immutable + BEFORE INSERT OR UPDATE OR DELETE ON published_release_bundle + FOR EACH ROW + EXECUTE FUNCTION enforce_published_release_bundle_immutability(); + +CREATE FUNCTION reject_published_release_bundle_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM published_release_bundle) THEN + RAISE EXCEPTION 'published release bundle metadata cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_published_release_bundle_no_truncate + BEFORE TRUNCATE ON published_release_bundle + FOR EACH STATEMENT + EXECUTE FUNCTION reject_published_release_bundle_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql b/services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql new file mode 100644 index 0000000000..d539f6021d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql @@ -0,0 +1,147 @@ +ALTER TABLE launch_descriptor ADD COLUMN descriptor_schema_version SMALLINT; +ALTER TABLE launch_descriptor ADD COLUMN target_namespace VARCHAR(63); +ALTER TABLE launch_descriptor ADD COLUMN canonical_tenant_id UUID; +ALTER TABLE launch_descriptor ADD COLUMN world_slug VARCHAR(120); +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_operation_id UUID; +ALTER TABLE launch_descriptor ADD COLUMN authored_world_source_evidence_digest VARCHAR(72); +ALTER TABLE launch_descriptor ADD COLUMN request_digest VARCHAR(72); +ALTER TABLE launch_descriptor ADD COLUMN result_digest VARCHAR(72); +ALTER TABLE launch_descriptor ADD COLUMN original_request_json TEXT; +ALTER TABLE launch_descriptor ADD COLUMN source_evidence_json TEXT; +ALTER TABLE launch_descriptor ADD COLUMN outcome_status VARCHAR(16) NOT NULL DEFAULT 'SUCCESS'; +ALTER TABLE launch_descriptor ADD COLUMN failure_code VARCHAR(64); +ALTER TABLE launch_descriptor ADD COLUMN failure_message TEXT; + +-- A deterministic denial is a request outcome, not a descriptor. Keep the successful tuple +-- nullable at the row level and require its complete shape below for SUCCESS outcomes. +ALTER TABLE launch_descriptor ALTER COLUMN launch_descriptor_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN game_template_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN version_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN runtime_flags_json DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN generation_config_revision DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN version_state_epoch DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN release_bundle_id DROP NOT NULL; +ALTER TABLE launch_descriptor ALTER COLUMN published_release_bundle_ref DROP NOT NULL; + +ALTER TABLE launch_descriptor + ADD CONSTRAINT ck_launch_descriptor_authored_binding_complete + CHECK ( + (outcome_status = 'SUCCESS' + AND descriptor_schema_version IS NULL + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND world_slug IS NULL + AND authored_world_source_operation_id IS NULL + AND authored_world_source_evidence_digest IS NULL + AND request_digest IS NULL + AND result_digest IS NULL + AND original_request_json IS NULL + AND source_evidence_json IS NULL + AND failure_code IS NULL + AND failure_message IS NULL + AND launch_descriptor_id IS NOT NULL + AND tenant_id IS NOT NULL + AND game_template_id IS NOT NULL + AND control_plane_request_id IS NOT NULL + AND request_hash IS NOT NULL + AND version_id IS NOT NULL + AND runtime_flags_json IS NOT NULL + AND generation_config_revision IS NOT NULL + AND version_state_epoch IS NOT NULL + AND release_bundle_id IS NOT NULL + AND published_release_bundle_ref IS NOT NULL) + OR + (outcome_status = 'SUCCESS' + AND descriptor_schema_version IS NOT NULL + AND descriptor_schema_version = 1 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug IS NOT NULL + AND authored_world_source_operation_id IS NOT NULL + AND authored_world_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authored_world_source_evidence_digest IS NOT NULL + AND request_digest IS NOT NULL + AND result_digest IS NOT NULL + AND original_request_json IS NOT NULL + AND source_evidence_json IS NOT NULL + AND failure_code IS NULL + AND failure_message IS NULL + AND launch_descriptor_id IS NOT NULL + AND tenant_id IS NOT NULL + AND game_template_id IS NOT NULL + AND control_plane_request_id IS NOT NULL + AND version_id IS NOT NULL + AND runtime_flags_json IS NOT NULL + AND generation_config_revision IS NOT NULL + AND version_state_epoch IS NOT NULL + AND release_bundle_id IS NOT NULL + AND published_release_bundle_ref IS NOT NULL + AND request_hash = request_digest) + OR + (outcome_status = 'FAILED' + AND descriptor_schema_version IS NOT NULL + AND descriptor_schema_version = 1 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug IS NOT NULL + AND authored_world_source_operation_id IS NOT NULL + AND authored_world_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authored_world_source_evidence_digest IS NOT NULL + AND request_digest IS NOT NULL + AND result_digest IS NULL + AND original_request_json IS NOT NULL + AND source_evidence_json IS NOT NULL + AND failure_code IS NOT NULL + AND failure_code IN ( + 'TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED', + 'INVALID_TEMPLATE_CONFIGURATION', + 'SCRIPT_PATCH_OVERRIDE_CONFLICT', + 'SCRIPT_PATCH_NOT_READY', + 'RELEASE_BUNDLE_NOT_FOUND', + 'RELEASE_ATTESTATION_MISMATCH', + 'VERSION_STATE_EPOCH_STALE', + 'LAUNCH_REMAP_REQUIRED', + 'SCHEMA_VERSION_UNSUPPORTED') + AND failure_message IS NOT NULL + AND CHAR_LENGTH(failure_message) > 0 + AND launch_descriptor_id IS NULL + AND tenant_id IS NOT NULL + AND game_template_id IS NULL + AND control_plane_request_id IS NOT NULL + AND request_hash = request_digest + AND version_id IS NULL + AND script_patch_version IS NULL + AND runtime_flags_json IS NULL + AND generation_config_revision IS NULL + AND version_state_epoch IS NULL + AND release_bundle_id IS NULL + AND published_release_bundle_ref IS NULL + AND remap_set_id IS NULL) + ); + +ALTER TABLE launch_descriptor + ADD CONSTRAINT ck_launch_descriptor_outcome_status + CHECK (outcome_status IN ('SUCCESS', 'FAILED')); + +CREATE UNIQUE INDEX uq_launch_descriptor_bound_request + ON launch_descriptor(target_namespace, canonical_tenant_id, control_plane_request_id) + WHERE descriptor_schema_version IS NOT NULL; + +-- PostgreSQL enforces the immutable history; the schema generator needs only the table shape. +-- [jooq ignore start] +CREATE FUNCTION reject_launch_descriptor_history_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'launch descriptors are immutable'; +END; +$$; + +CREATE TRIGGER trg_launch_descriptor_immutable + BEFORE UPDATE OR DELETE ON launch_descriptor + FOR EACH ROW + EXECUTE FUNCTION reject_launch_descriptor_history_mutation(); +-- [jooq ignore end] diff --git a/services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql b/services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql new file mode 100644 index 0000000000..d1a0bc0b5b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql @@ -0,0 +1,56 @@ +ALTER TABLE published_release_bundle + ADD COLUMN published_release_bundle_ref VARCHAR(128); + +ALTER TABLE published_release_bundle + ADD CONSTRAINT ck_published_release_bundle_ref_nonblank + CHECK (published_release_bundle_ref IS NULL OR BTRIM(published_release_bundle_ref) <> ''); + +CREATE UNIQUE INDEX uq_published_release_bundle_opaque_ref + ON published_release_bundle(published_release_bundle_ref) + WHERE published_release_bundle_ref IS NOT NULL; + +-- Retained bundles intentionally remain NULL. New owner inserts must supply an identity, and +-- once assigned the opaque reference cannot be changed independently of the bundle. +-- [jooq ignore start] +CREATE FUNCTION enforce_published_release_bundle_reference() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.published_release_bundle_ref IS NULL + OR BTRIM(NEW.published_release_bundle_ref) = '' THEN + RAISE EXCEPTION 'new published release bundles require an opaque reference'; + END IF; + ELSE + IF NEW.published_release_bundle_ref IS DISTINCT FROM OLD.published_release_bundle_ref THEN + RAISE EXCEPTION 'published release bundle reference is immutable'; + END IF; + IF OLD.published_release_bundle_ref IS NOT NULL AND ( + NEW.id IS DISTINCT FROM OLD.id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id + OR NEW.version_number IS DISTINCT FROM OLD.version_number + OR NEW.attestation_schema_version IS DISTINCT FROM OLD.attestation_schema_version + OR NEW.publish_workflow_id IS DISTINCT FROM OLD.publish_workflow_id + OR NEW.manifest_hash IS DISTINCT FROM OLD.manifest_hash + OR NEW.generation_config_revision IS DISTINCT FROM OLD.generation_config_revision + OR NEW.required_manifest_asset_keys_json + IS DISTINCT FROM OLD.required_manifest_asset_keys_json + OR NEW.participant_digests_json IS DISTINCT FROM OLD.participant_digests_json + OR NEW.command_definitions_json IS DISTINCT FROM OLD.command_definitions_json + OR NEW.script_only IS DISTINCT FROM OLD.script_only + OR NEW.script_patch_version IS DISTINCT FROM OLD.script_patch_version + OR NEW.published_at IS DISTINCT FROM OLD.published_at) THEN + RAISE EXCEPTION 'published release bundle attestation is immutable'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_published_release_bundle_reference + BEFORE INSERT OR UPDATE ON published_release_bundle + FOR EACH ROW + EXECUTE FUNCTION enforce_published_release_bundle_reference(); +-- [jooq ignore end] diff --git a/services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql b/services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql new file mode 100644 index 0000000000..36656d1c58 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql @@ -0,0 +1,348 @@ +ALTER TABLE game + ADD CONSTRAINT uq_game_tenant_id_id UNIQUE (tenant_id, id); + +ALTER TABLE version + ADD CONSTRAINT uq_version_tenant_id_id UNIQUE (tenant_id, id); + +ALTER TABLE game_assets + ADD CONSTRAINT uq_game_assets_tenant_id_id UNIQUE (tenant_id, id), + ADD CONSTRAINT uq_game_assets_tenant_id_name UNIQUE (tenant_id, id, file_name); + +CREATE TABLE version_asset ( + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL, + asset_id BIGINT NOT NULL, + usage_key VARCHAR(255) NOT NULL, + usage_type VARCHAR(100), + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_version_asset PRIMARY KEY (tenant_id, version_id, asset_id), + CONSTRAINT uq_version_asset_usage UNIQUE (tenant_id, version_id, usage_key), + CONSTRAINT uq_version_asset_exact UNIQUE (tenant_id, version_id, asset_id, usage_key), + CONSTRAINT fk_version_asset_version FOREIGN KEY (tenant_id, version_id) + REFERENCES version (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT fk_version_asset_asset FOREIGN KEY (tenant_id, asset_id) + REFERENCES game_assets (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT fk_version_asset_asset_name FOREIGN KEY (tenant_id, asset_id, usage_key) + REFERENCES game_assets (tenant_id, id, file_name) ON DELETE RESTRICT, + CONSTRAINT chk_version_asset_usage_key CHECK (char_length(usage_key) > 0) +); + +CREATE TABLE version_asset_export_snapshot ( + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + version_number INTEGER NOT NULL, + captured_version_state_epoch BIGINT NOT NULL, + item_count INTEGER NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_version_asset_export_snapshot PRIMARY KEY (tenant_id, version_id), + CONSTRAINT fk_version_asset_snapshot_version FOREIGN KEY (tenant_id, version_id) + REFERENCES version (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT chk_version_asset_snapshot_values CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_number > 0 + AND captured_version_state_epoch > 0 + AND item_count >= 0 + ) +); + +CREATE TABLE version_asset_export_item ( + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL, + usage_key VARCHAR(255) NOT NULL, + asset_id BIGINT NOT NULL, + content_type VARCHAR(100) NOT NULL, + content_hash VARCHAR(71) NOT NULL, + byte_size BIGINT NOT NULL, + CONSTRAINT pk_version_asset_export_item PRIMARY KEY (tenant_id, version_id, usage_key), + CONSTRAINT uq_version_asset_export_item_asset UNIQUE (tenant_id, version_id, asset_id), + CONSTRAINT fk_version_asset_export_item_snapshot FOREIGN KEY (tenant_id, version_id) + REFERENCES version_asset_export_snapshot (tenant_id, version_id) + DEFERRABLE INITIALLY DEFERRED, + CONSTRAINT fk_version_asset_export_item_mapping FOREIGN KEY + (tenant_id, version_id, asset_id, usage_key) + REFERENCES version_asset (tenant_id, version_id, asset_id, usage_key) + ON DELETE RESTRICT, + CONSTRAINT chk_version_asset_export_item_hash CHECK (content_hash ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_version_asset_export_item_size CHECK (byte_size >= 0) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_version_asset_mapping() RETURNS trigger AS $$ +DECLARE + target_tenant_id VARCHAR(36); + target_version_id BIGINT; + target_state VARCHAR(32); + target_epoch BIGINT; +BEGIN + IF TG_OP = 'UPDATE' AND ( + NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id + OR NEW.asset_id IS DISTINCT FROM OLD.asset_id + OR NEW.usage_key IS DISTINCT FROM OLD.usage_key + ) THEN + RAISE EXCEPTION 'version asset association identity is immutable; create a new Draft mapping' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'DELETE' THEN + target_tenant_id := OLD.tenant_id; + target_version_id := OLD.version_id; + ELSE + target_tenant_id := NEW.tenant_id; + target_version_id := NEW.version_id; + END IF; + + SELECT v.version_state, v.version_state_epoch + INTO target_state, target_epoch + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.tenant_id = v.tenant_id + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.tenant_id = target_tenant_id AND v.id = target_version_id + AND v.canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND v.canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + FOR UPDATE OF v; + + IF NOT FOUND THEN + RAISE EXCEPTION 'version asset mapping requires the exact canonical tenant Version source' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF target_state <> 'DRAFT' OR target_epoch IS NULL OR target_epoch <= 0 THEN + RAISE EXCEPTION 'version asset mappings can change only while the Version is DRAFT' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM version_asset_export_snapshot s + WHERE s.tenant_id = target_tenant_id AND s.version_id = target_version_id + ) THEN + RAISE EXCEPTION 'version asset mappings are frozen by the durable export snapshot' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP <> 'DELETE' AND NOT EXISTS ( + SELECT 1 FROM game_assets a + WHERE a.tenant_id = NEW.tenant_id + AND a.id = NEW.asset_id + AND a.file_name = NEW.usage_key + ) THEN + RAISE EXCEPTION 'version asset usage key must equal the exact source file name' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_mapping_guard + BEFORE INSERT OR UPDATE OR DELETE ON version_asset + FOR EACH ROW + EXECUTE FUNCTION guard_version_asset_mapping(); + +CREATE FUNCTION guard_version_asset_export_item() RETURNS trigger AS $$ +DECLARE + source_type VARCHAR(100); + source_size BIGINT; + target_state VARCHAR(32); +BEGIN + IF TG_OP <> 'INSERT' THEN + IF EXISTS ( + SELECT 1 FROM version_asset_export_snapshot s + WHERE s.tenant_id = OLD.tenant_id AND s.version_id = OLD.version_id + ) THEN + RAISE EXCEPTION 'version asset export snapshot items are immutable' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END IF; + + SELECT version_state INTO target_state + FROM version + WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id + FOR UPDATE; + IF NOT FOUND OR target_state <> 'DRAFT' THEN + RAISE EXCEPTION 'version asset export items require the exact Draft Version row' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM version_asset_export_snapshot s + WHERE s.tenant_id = NEW.tenant_id AND s.version_id = NEW.version_id + ) THEN + RAISE EXCEPTION 'version asset export snapshot items are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT a.content_type, octet_length(a.data)::BIGINT + INTO source_type, source_size + FROM game_assets a + JOIN version_asset va + ON va.tenant_id = a.tenant_id + AND va.asset_id = a.id + AND va.tenant_id = NEW.tenant_id + AND va.version_id = NEW.version_id + AND va.usage_key = NEW.usage_key + AND va.asset_id = NEW.asset_id + WHERE a.tenant_id = NEW.tenant_id AND a.id = NEW.asset_id; + + IF NOT FOUND OR source_type IS DISTINCT FROM NEW.content_type + OR source_size IS DISTINCT FROM NEW.byte_size THEN + RAISE EXCEPTION 'version asset export item source metadata does not match game_assets' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_export_item_guard + BEFORE INSERT OR UPDATE OR DELETE ON version_asset_export_item + FOR EACH ROW + EXECUTE FUNCTION guard_version_asset_export_item(); + +CREATE FUNCTION guard_version_asset_export_snapshot() RETURNS trigger AS $$ +DECLARE + source_version_number INTEGER; + source_epoch BIGINT; + source_state VARCHAR(32); + source_canonical_tenant_id UUID; + source_canonical_version_id UUID; + item_rows BIGINT; + mapping_rows BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'version asset export snapshot headers are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.version_number, + v.version_state_epoch, + v.version_state, + v.canonical_tenant_id, + v.canonical_version_id + INTO source_version_number, + source_epoch, + source_state, + source_canonical_tenant_id, + source_canonical_version_id + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.tenant_id = v.tenant_id + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.tenant_id = NEW.tenant_id AND v.id = NEW.version_id + FOR UPDATE OF v; + + IF NOT FOUND + OR source_state <> 'DRAFT' + OR source_epoch IS NULL OR source_epoch <= 0 + OR source_version_number IS DISTINCT FROM NEW.version_number + OR source_epoch IS DISTINCT FROM NEW.captured_version_state_epoch + OR source_canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR source_canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR source_canonical_tenant_id = '00000000-0000-0000-0000-000000000000'::UUID + OR source_canonical_version_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'version asset export snapshot requires the exact canonical Draft Version source' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT count(*) INTO item_rows + FROM version_asset_export_item i + WHERE i.tenant_id = NEW.tenant_id AND i.version_id = NEW.version_id; + SELECT count(*) INTO mapping_rows + FROM version_asset va + WHERE va.tenant_id = NEW.tenant_id AND va.version_id = NEW.version_id; + IF item_rows <> NEW.item_count OR mapping_rows <> NEW.item_count THEN + RAISE EXCEPTION 'version asset export snapshot item count does not prove the complete mapping set' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_export_snapshot_guard + BEFORE INSERT OR UPDATE OR DELETE ON version_asset_export_snapshot + FOR EACH ROW + EXECUTE FUNCTION guard_version_asset_export_snapshot(); + +CREATE FUNCTION guard_frozen_game_asset_source() RETURNS trigger AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM version_asset_export_item i + WHERE i.tenant_id = OLD.tenant_id AND i.asset_id = OLD.id + ) THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'game asset source rows are immutable while a frozen version snapshot references them' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.id IS DISTINCT FROM OLD.id + OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.file_name IS DISTINCT FROM OLD.file_name + OR NEW.content_type IS DISTINCT FROM OLD.content_type + OR NEW.data IS DISTINCT FROM OLD.data THEN + RAISE EXCEPTION 'game asset source rows are immutable while a frozen version snapshot references them' + USING ERRCODE = 'check_violation'; + END IF; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_game_assets_frozen_source + BEFORE UPDATE OR DELETE ON game_assets + FOR EACH ROW + EXECUTE FUNCTION guard_frozen_game_asset_source(); + +CREATE FUNCTION reject_frozen_asset_publication_truncate() RETURNS trigger AS $$ +BEGIN + IF TG_TABLE_NAME = 'game_assets' AND EXISTS ( + SELECT 1 FROM version_asset_export_item + ) THEN + RAISE EXCEPTION 'game asset source rows are retained by frozen version snapshots' + USING ERRCODE = 'check_violation'; + END IF; + IF TG_TABLE_NAME IN ('version_asset', 'version_asset_export_item', 'version_asset_export_snapshot') + AND EXISTS (SELECT 1 FROM version_asset_export_snapshot) THEN + RAISE EXCEPTION 'frozen version asset publication evidence cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_game_assets_frozen_source_no_truncate + BEFORE TRUNCATE ON game_assets + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); + +CREATE TRIGGER trg_version_asset_mapping_no_truncate + BEFORE TRUNCATE ON version_asset + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); + +CREATE TRIGGER trg_version_asset_export_item_no_truncate + BEFORE TRUNCATE ON version_asset_export_item + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); + +CREATE TRIGGER trg_version_asset_export_snapshot_no_truncate + BEFORE TRUNCATE ON version_asset_export_snapshot + FOR EACH STATEMENT + EXECUTE FUNCTION reject_frozen_asset_publication_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql new file mode 100644 index 0000000000..ac4bf05d03 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql @@ -0,0 +1,75 @@ +ALTER TABLE published_release_bundle + ADD COLUMN manifest_schema_version INTEGER, + ADD COLUMN artifact_digests_json TEXT, + ADD CONSTRAINT chk_published_asset_digest_evidence_shape CHECK ( + (manifest_schema_version IS NULL AND artifact_digests_json IS NULL) + OR (manifest_schema_version IS NOT NULL AND manifest_schema_version = 1 + AND artifact_digests_json IS NOT NULL) + ); + +-- Existing immutable release rows remain explicitly without complete asset proof. +-- V35.2's INSERT/UPDATE/DELETE guard also protects these added attestation fields. +-- Do not backfill retained evidence from mutable assets or object-store listings. + +ALTER TABLE version_asset_artifact + ADD COLUMN manifest_schema_version INTEGER, + ADD COLUMN artifact_digests_json TEXT, + ADD COLUMN published_object_proofs_json TEXT, + ADD COLUMN candidate_snapshot_version_id BIGINT, + ADD CONSTRAINT chk_asset_export_candidate_evidence CHECK ( + (manifest_schema_version IS NULL AND artifact_digests_json IS NULL + AND published_object_proofs_json IS NULL AND candidate_snapshot_version_id IS NULL) + OR (manifest_schema_version IS NOT NULL AND manifest_schema_version = 1 + AND artifact_digests_json IS NOT NULL + AND published_object_proofs_json IS NOT NULL + AND candidate_snapshot_version_id IS NOT NULL AND manifest_hash IS NOT NULL + AND candidate_snapshot_version_id = version_id + AND manifest_hash ~ '^sha256:[0-9a-f]{64}$') + ), + ADD CONSTRAINT fk_asset_export_candidate_snapshot + FOREIGN KEY (tenant_id, candidate_snapshot_version_id) + REFERENCES version_asset_export_snapshot (tenant_id, version_id); + +-- [jooq ignore start] +CREATE FUNCTION guard_asset_export_candidate_evidence() RETURNS TRIGGER AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.manifest_schema_version IS NOT NULL THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED'; + END IF; + RETURN OLD; + END IF; + IF OLD.manifest_schema_version IS NOT NULL AND ( + NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.version_id IS DISTINCT FROM OLD.version_id + OR NEW.exported_version_number IS DISTINCT FROM OLD.exported_version_number + OR NEW.manifest_hash IS DISTINCT FROM OLD.manifest_hash + OR NEW.manifest_schema_version IS DISTINCT FROM OLD.manifest_schema_version + OR NEW.artifact_digests_json IS DISTINCT FROM OLD.artifact_digests_json + OR NEW.published_object_proofs_json IS DISTINCT FROM OLD.published_object_proofs_json + OR NEW.candidate_snapshot_version_id IS DISTINCT FROM OLD.candidate_snapshot_version_id + OR NEW.exported_manifest_asset_keys_json IS DISTINCT FROM OLD.exported_manifest_asset_keys_json + ) THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_IMMUTABLE'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_asset_export_candidate_immutable + BEFORE UPDATE OR DELETE ON version_asset_artifact + FOR EACH ROW EXECUTE FUNCTION guard_asset_export_candidate_evidence(); + +CREATE FUNCTION guard_asset_export_candidate_truncate() RETURNS TRIGGER AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM version_asset_artifact WHERE manifest_schema_version IS NOT NULL) THEN + RAISE EXCEPTION 'ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_asset_export_candidate_no_truncate + BEFORE TRUNCATE ON version_asset_artifact + FOR EACH STATEMENT EXECUTE FUNCTION guard_asset_export_candidate_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql b/services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql new file mode 100644 index 0000000000..b002f13613 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql @@ -0,0 +1,11 @@ +ALTER TABLE published_release_bundle + ALTER COLUMN generation_config_revision TYPE TEXT; + +ALTER TABLE launch_descriptor + ALTER COLUMN generation_config_revision TYPE TEXT; + +ALTER TABLE version_asset_artifact + ALTER COLUMN last_error_message TYPE TEXT; + +ALTER TABLE publish_attempt + ALTER COLUMN failure_message TYPE TEXT; diff --git a/services/game-design-service/src/main/resources/db/migration/V40__publish_attempt_ability_schema_digest.sql b/services/game-design-service/src/main/resources/db/migration/V40__publish_attempt_ability_schema_digest.sql new file mode 100644 index 0000000000..559b432b86 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V40__publish_attempt_ability_schema_digest.sql @@ -0,0 +1,2 @@ +ALTER TABLE publish_attempt_participant_digest + ADD COLUMN ability_schema_digest VARCHAR(128); diff --git a/services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql b/services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql new file mode 100644 index 0000000000..90883b945b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V41__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/main/resources/db/migration/V42__durable_draft_commit_coordination.sql b/services/game-design-service/src/main/resources/db/migration/V42__durable_draft_commit_coordination.sql new file mode 100644 index 0000000000..1dfcbba765 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V42__durable_draft_commit_coordination.sql @@ -0,0 +1,865 @@ +CREATE TABLE game_design_draft_commit ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL, + game_design_version_tenant_key VARCHAR(36) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + base_commit_id VARCHAR(256) NOT NULL, + input_digest VARCHAR(71) NOT NULL, + binding_json TEXT NOT NULL, + workflow_state VARCHAR(32) NOT NULL DEFAULT 'QUEUED', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id + ), + CONSTRAINT uq_gd_draft_commit_target_commit UNIQUE ( + canonical_tenant_id, + canonical_version_id, + commit_id + ), + CONSTRAINT uq_gd_draft_commit_exact_identity UNIQUE ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT fk_gd_draft_commit_canonical_version FOREIGN KEY ( + game_design_version_row_id, + canonical_tenant_id, + canonical_version_id + ) REFERENCES version (id, canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + CONSTRAINT fk_gd_draft_commit_source_game FOREIGN KEY ( + source_game_tenant_key, + source_game_row_id + ) REFERENCES game (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_identity CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_row_id > 0 + AND source_game_row_id > 0 + AND game_design_version_tenant_key = source_game_tenant_key + AND char_length(game_design_version_tenant_key) BETWEEN 1 AND 36 + AND game_design_version_tenant_key !~ '^[[:space:]]*$' + AND source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + AND octet_length(base_commit_id) BETWEEN 1 AND 256 + AND base_commit_id !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gd_draft_commit_digest CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gd_draft_commit_binding_json CHECK ( + jsonb_typeof(binding_json::jsonb) = 'object' + ), + CONSTRAINT chk_gd_draft_commit_state CHECK ( + workflow_state IN ( + 'QUEUED', 'APPLYING', 'RECONCILIATION_REQUIRED', 'SYNCHRONIZED', + 'REJECTED', 'FAILED_NONPUBLICATION' + ) + ) +); + +CREATE TABLE game_design_draft_commit_owner_result ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + owner VARCHAR(32) NOT NULL, + status VARCHAR(24) NOT NULL, + result_commit_id UUID, + result_binding_digest VARCHAR(71), + result_identity VARCHAR(512), + result_bytes BYTEA, + applied_units_json TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_owner_result PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + owner + ), + CONSTRAINT fk_gd_draft_commit_owner_result_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_owner CHECK ( + owner IN ( + 'WORLD_MANAGEMENT', + 'ENTITY_MANAGEMENT', + 'GAME_LOGIC', + 'AUTOMATION_SCRIPTING', + 'GAME_DESIGN_CONTROL_PLANE' + ) + ), + CONSTRAINT chk_gd_draft_commit_owner_status CHECK ( + status IN ('NOT_ATTEMPTED', 'IN_PROGRESS', 'APPLIED', 'REJECTED', 'UNKNOWN') + ), + CONSTRAINT chk_gd_draft_commit_owner_result_shape CHECK ( + ( + status IN ('NOT_ATTEMPTED', 'IN_PROGRESS') + AND result_commit_id IS NULL + AND result_binding_digest IS NULL + AND result_identity IS NULL + AND result_bytes IS NULL + AND applied_units_json IS NULL + ) + OR + ( + status = 'UNKNOWN' + AND ( + (result_identity IS NULL AND result_bytes IS NULL) + OR (result_identity IS NOT NULL AND result_bytes IS NOT NULL) + ) + AND ( + (result_commit_id IS NULL AND result_binding_digest IS NULL AND applied_units_json IS NULL) + OR (result_commit_id IS NOT NULL AND result_binding_digest IS NOT NULL) + ) + ) + OR + ( + status IN ('APPLIED', 'REJECTED') + AND result_commit_id IS NOT NULL + AND result_binding_digest IS NOT NULL + AND result_identity IS NOT NULL + AND result_bytes IS NOT NULL + AND applied_units_json IS NOT NULL + AND jsonb_typeof(applied_units_json::jsonb) = 'array' + AND (status <> 'REJECTED' OR applied_units_json::jsonb = '[]'::jsonb) + ) + ), + CONSTRAINT chk_gd_draft_commit_owner_result_digest CHECK ( + result_binding_digest IS NULL OR result_binding_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_draft_commit_owner_result_identity CHECK ( + result_identity IS NULL OR ( + char_length(result_identity) BETWEEN 1 AND 512 + AND result_identity !~ '^[[:space:]]*$' + ) + ) +); + +CREATE TABLE game_design_draft_commit_visibility_fence ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL, + result_vector_json TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_visibility_fence PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT fk_gd_draft_commit_visibility_fence_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_visibility_digest CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gd_draft_commit_visibility_vector CHECK ( + jsonb_typeof(result_vector_json::jsonb) = 'array' + ) +); + +CREATE TABLE game_design_draft_commit_visibility ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_visibility PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id + ), + CONSTRAINT fk_gd_draft_commit_visibility_fence FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit_visibility_fence ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_visibility_pointer_digest CHECK ( + input_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE game_design_draft_commit_application_slot ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + claimed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_application_slot PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id + ), + CONSTRAINT fk_gd_draft_commit_application_slot_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT +); + +CREATE TABLE game_design_draft_commit_final_abort ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL, + binding_json TEXT NOT NULL, + abort_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_commit_final_abort PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT fk_gd_draft_commit_final_abort_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_commit_final_abort_digest CHECK ( + input_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_draft_commit_final_abort_binding CHECK ( + jsonb_typeof(binding_json::jsonb) = 'object' + ), + CONSTRAINT chk_gd_draft_commit_final_abort_bytes CHECK (octet_length(abort_bytes) > 0) +); + +-- [jooq ignore start] +CREATE FUNCTION gd_draft_commit_has_exact_terminal_abort_vector( + target_tenant UUID, + target_version UUID, + target_request UUID, + target_commit UUID +) RETURNS BOOLEAN AS $$ +DECLARE + parent_record RECORD; + expected_count INTEGER; + actual_count INTEGER; +BEGIN + SELECT input_digest, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = target_tenant + AND canonical_version_id = target_version + AND request_id = target_request + AND commit_id = target_commit; + IF NOT FOUND THEN + RETURN FALSE; + END IF; + IF jsonb_typeof(parent_record.binding_json::jsonb -> 'requiredOwners') IS DISTINCT FROM 'array' + OR jsonb_array_length(parent_record.binding_json::jsonb -> 'requiredOwners') = 0 THEN + RETURN FALSE; + END IF; + + expected_count := jsonb_array_length(parent_record.binding_json::jsonb -> 'requiredOwners'); + SELECT count(*) INTO actual_count + FROM game_design_draft_commit_owner_result + WHERE canonical_tenant_id = target_tenant + AND canonical_version_id = target_version + AND request_id = target_request; + IF actual_count <> expected_count THEN + RETURN FALSE; + END IF; + + RETURN NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(parent_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = target_tenant + AND outcome.canonical_version_id = target_version + AND outcome.request_id = target_request + AND outcome.owner = required.owner + WHERE outcome.owner IS NULL + OR outcome.status NOT IN ('APPLIED', 'REJECTED') + OR outcome.result_commit_id IS DISTINCT FROM target_commit + OR outcome.result_binding_digest IS DISTINCT FROM parent_record.input_digest + OR outcome.result_identity IS NULL + OR outcome.result_bytes IS NULL + OR outcome.applied_units_json IS NULL + ); +END; +$$ LANGUAGE plpgsql STABLE; + +CREATE FUNCTION enforce_gd_draft_commit_final_abort() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design Draft final-abort evidence is immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT commit_id, input_digest, binding_json, workflow_state + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + AND commit_id = NEW.commit_id + FOR UPDATE; + IF NOT FOUND + OR parent_record.input_digest IS DISTINCT FROM NEW.input_digest + OR parent_record.binding_json IS DISTINCT FROM NEW.binding_json + OR parent_record.workflow_state NOT IN ('APPLYING', 'RECONCILIATION_REQUIRED') THEN + RAISE EXCEPTION 'Final-abort evidence must bind the exact active Draft commit' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id + AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.request_id + AND f.commit_id = NEW.commit_id + ) THEN + RAISE EXCEPTION 'A successful Draft visibility fence cannot be final-aborted' + USING ERRCODE = 'check_violation'; + END IF; + IF NOT gd_draft_commit_has_exact_terminal_abort_vector( + NEW.canonical_tenant_id, + NEW.canonical_version_id, + NEW.request_id, + NEW.commit_id + ) THEN + RAISE EXCEPTION 'Final-abort evidence requires every exact owner result to be terminal' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_final_abort + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_final_abort + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_final_abort(); + +CREATE FUNCTION reject_gd_draft_commit_final_abort_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_commit_final_abort) THEN + RAISE EXCEPTION 'Game Design Draft final-abort evidence cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_final_abort_no_truncate + BEFORE TRUNCATE ON game_design_draft_commit_final_abort + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_commit_final_abort_truncate(); + +CREATE FUNCTION enforce_gd_draft_commit_binding() RETURNS trigger AS $$ +DECLARE + version_matches BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Design Draft commit bindings are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.game_design_version_row_id IS DISTINCT FROM OLD.game_design_version_row_id + OR NEW.game_design_version_tenant_key IS DISTINCT FROM OLD.game_design_version_tenant_key + OR NEW.source_game_row_id IS DISTINCT FROM OLD.source_game_row_id + OR NEW.source_game_tenant_key IS DISTINCT FROM OLD.source_game_tenant_key + OR NEW.source_provenance_kind IS DISTINCT FROM OLD.source_provenance_kind + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.commit_id IS DISTINCT FROM OLD.commit_id + OR NEW.base_commit_id IS DISTINCT FROM OLD.base_commit_id + OR NEW.input_digest IS DISTINCT FROM OLD.input_digest + OR NEW.binding_json IS DISTINCT FROM OLD.binding_json + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Game Design Draft commit binding identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.workflow_state IS DISTINCT FROM OLD.workflow_state THEN + IF OLD.workflow_state IN ('SYNCHRONIZED', 'REJECTED', 'FAILED_NONPUBLICATION') + OR NOT ( + (OLD.workflow_state = 'QUEUED' + AND NEW.workflow_state = 'APPLYING') + OR (OLD.workflow_state = 'APPLYING' + AND NEW.workflow_state IN ( + 'RECONCILIATION_REQUIRED', 'SYNCHRONIZED', 'REJECTED', + 'FAILED_NONPUBLICATION' + )) + OR (OLD.workflow_state = 'RECONCILIATION_REQUIRED' + AND NEW.workflow_state IN ( + 'SYNCHRONIZED', 'REJECTED', 'FAILED_NONPUBLICATION' + )) + ) THEN + RAISE EXCEPTION 'Invalid Game Design Draft commit workflow transition' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.updated_at IS DISTINCT FROM OLD.updated_at THEN + RAISE EXCEPTION 'An unchanged Draft commit workflow state is not rewritten' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.workflow_state = 'REJECTED' + AND ( + EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status IN ('APPLIED', 'IN_PROGRESS', 'UNKNOWN') + ) + OR NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status = 'REJECTED' + ) + ) THEN + RAISE EXCEPTION 'Unresolved or applied Draft owner outcomes cannot be finalized REJECTED' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.workflow_state = 'FAILED_NONPUBLICATION' + AND ( + NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = OLD.canonical_tenant_id + AND abort.canonical_version_id = OLD.canonical_version_id + AND abort.request_id = OLD.request_id + AND abort.commit_id = OLD.commit_id + AND abort.input_digest = OLD.input_digest + AND abort.binding_json = OLD.binding_json + ) + OR NOT gd_draft_commit_has_exact_terminal_abort_vector( + OLD.canonical_tenant_id, + OLD.canonical_version_id, + OLD.request_id, + OLD.commit_id + ) + OR EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = OLD.canonical_tenant_id + AND f.canonical_version_id = OLD.canonical_version_id + AND f.request_id = OLD.request_id + AND f.commit_id = OLD.commit_id + ) + ) THEN + RAISE EXCEPTION 'Failed nonpublication requires exact final-abort evidence and no visibility fence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.binding_json::jsonb ->> 'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.binding_json::jsonb ->> 'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.binding_json::jsonb ->> 'requestId' IS DISTINCT FROM NEW.request_id::text + OR NEW.binding_json::jsonb ->> 'commitId' IS DISTINCT FROM NEW.commit_id::text + OR NEW.binding_json::jsonb ->> 'baseCommitId' IS DISTINCT FROM NEW.base_commit_id + OR NEW.binding_json::jsonb ->> 'schemaVersion' IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Stored Draft commit JSON differs from its indexed identity' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.binding_json::jsonb -> 'target' ->> 'gameDesignVersionRowId' + IS DISTINCT FROM NEW.game_design_version_row_id::text + OR NEW.binding_json::jsonb -> 'target' ->> 'gameDesignVersionTenantKey' + IS DISTINCT FROM NEW.game_design_version_tenant_key + OR NEW.binding_json::jsonb -> 'target' ->> 'sourceGameRowId' + IS DISTINCT FROM NEW.source_game_row_id::text + OR NEW.binding_json::jsonb -> 'target' ->> 'sourceGameTenantKey' + IS DISTINCT FROM NEW.source_game_tenant_key + OR NEW.binding_json::jsonb -> 'target' ->> 'sourceProvenanceKind' + IS DISTINCT FROM NEW.source_provenance_kind THEN + RAISE EXCEPTION 'Stored Draft commit JSON differs from its private Version source proof' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT EXISTS ( + SELECT 1 + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.id = NEW.game_design_version_row_id + AND v.tenant_id = NEW.game_design_version_tenant_key + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id = NEW.source_game_row_id + AND v.identity_source_game_tenant_key = NEW.source_game_tenant_key + AND v.identity_source_provenance_kind = NEW.source_provenance_kind + AND g.id = NEW.source_game_row_id + AND g.tenant_id = NEW.source_game_tenant_key + ) INTO version_matches; + IF NOT version_matches THEN + RAISE EXCEPTION 'Draft commit target lacks exact canonical Game Design Version source proof' + USING ERRCODE = 'foreign_key_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_binding + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_binding(); + +CREATE FUNCTION reject_gd_draft_commit_binding_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_commit) THEN + RAISE EXCEPTION 'Game Design Draft commit bindings cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_binding_no_truncate + BEFORE TRUNCATE ON game_design_draft_commit + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_commit_binding_truncate(); + +CREATE FUNCTION enforce_gd_draft_commit_owner_result() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Design Draft owner results are retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT commit_id, input_digest, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Game Design Draft owner result has no exact commit binding' + USING ERRCODE = 'foreign_key_violation'; + END IF; + + IF NOT ((parent_record.binding_json::jsonb -> 'requiredOwners') ? NEW.owner) THEN + RAISE EXCEPTION 'Game Design Draft owner result is outside the bound required owner set' + USING ERRCODE = 'check_violation'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'NOT_ATTEMPTED' + OR NEW.result_commit_id IS NOT NULL + OR NEW.result_binding_digest IS NOT NULL + OR NEW.result_identity IS NOT NULL + OR NEW.result_bytes IS NOT NULL + OR NEW.applied_units_json IS NOT NULL THEN + RAISE EXCEPTION 'Draft commit owner result must begin NOT_ATTEMPTED without evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.owner IS DISTINCT FROM OLD.owner + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Game Design Draft owner result identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.status = OLD.status THEN + IF NEW.result_commit_id IS DISTINCT FROM OLD.result_commit_id + OR NEW.result_binding_digest IS DISTINCT FROM OLD.result_binding_digest + OR NEW.result_identity IS DISTINCT FROM OLD.result_identity + OR NEW.result_bytes IS DISTINCT FROM OLD.result_bytes + OR NEW.applied_units_json IS DISTINCT FROM OLD.applied_units_json + OR NEW.updated_at IS DISTINCT FROM OLD.updated_at THEN + RAISE EXCEPTION 'Exact Draft owner result retries do not rewrite persisted evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NOT ( + (OLD.status = 'NOT_ATTEMPTED' AND NEW.status = 'IN_PROGRESS') + OR (OLD.status = 'IN_PROGRESS' AND NEW.status IN ('APPLIED', 'REJECTED', 'UNKNOWN')) + OR (OLD.status = 'UNKNOWN' AND NEW.status IN ('APPLIED', 'REJECTED')) + ) THEN + RAISE EXCEPTION 'Invalid Game Design Draft owner result transition' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.status IN ('APPLIED', 'REJECTED') + AND (NEW.result_commit_id IS DISTINCT FROM parent_record.commit_id + OR NEW.result_binding_digest IS DISTINCT FROM parent_record.input_digest) THEN + RAISE EXCEPTION 'Game Design Draft owner result does not match its exact commit binding' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_owner_result + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_owner_result + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_owner_result(); + +CREATE FUNCTION enforce_gd_draft_commit_visibility_fence() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design Draft visibility fences are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT commit_id, input_digest, workflow_state, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + FOR UPDATE; + IF NOT FOUND + OR parent_record.commit_id IS DISTINCT FROM NEW.commit_id + OR parent_record.input_digest IS DISTINCT FROM NEW.input_digest + OR parent_record.workflow_state NOT IN ('APPLYING', 'RECONCILIATION_REQUIRED') THEN + RAISE EXCEPTION 'Draft visibility fence lacks a matching nonterminal commit binding' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = NEW.canonical_tenant_id + AND abort.canonical_version_id = NEW.canonical_version_id + AND abort.request_id = NEW.request_id + AND abort.commit_id = NEW.commit_id + ) THEN + RAISE EXCEPTION 'Final-aborted Draft commits cannot gain a visibility fence' + USING ERRCODE = 'check_violation'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(parent_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = NEW.canonical_tenant_id + AND outcome.canonical_version_id = NEW.canonical_version_id + AND outcome.request_id = NEW.request_id + AND outcome.owner = required.owner + WHERE outcome.status IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Draft visibility fence requires every exact required owner to be APPLIED' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_fence + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_visibility_fence + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_visibility_fence(); + +CREATE FUNCTION reject_gd_draft_commit_visibility_fence_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_commit_visibility_fence) THEN + RAISE EXCEPTION 'Game Design Draft visibility fences cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_fence_no_truncate + BEFORE TRUNCATE ON game_design_draft_commit_visibility_fence + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_commit_visibility_fence_truncate(); + +CREATE FUNCTION enforce_gd_draft_commit_visibility_pointer() RETURNS trigger AS $$ +DECLARE + fence_digest VARCHAR(71); + workflow_state VARCHAR(32); +BEGIN + SELECT f.input_digest, c.workflow_state INTO fence_digest, workflow_state + FROM game_design_draft_commit_visibility_fence f + JOIN game_design_draft_commit c + ON c.canonical_tenant_id = f.canonical_tenant_id + AND c.canonical_version_id = f.canonical_version_id + AND c.request_id = f.request_id + AND c.commit_id = f.commit_id + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id + AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.request_id + AND f.commit_id = NEW.commit_id; + IF NOT FOUND OR fence_digest IS DISTINCT FROM NEW.input_digest + OR workflow_state = 'FAILED_NONPUBLICATION' + OR EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = NEW.canonical_tenant_id + AND abort.canonical_version_id = NEW.canonical_version_id + AND abort.request_id = NEW.request_id + AND abort.commit_id = NEW.commit_id + ) THEN + RAISE EXCEPTION 'Draft visibility pointer must name its exact durable fence' + USING ERRCODE = 'foreign_key_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_visibility_pointer + BEFORE INSERT OR UPDATE ON game_design_draft_commit_visibility + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_visibility_pointer(); + +CREATE FUNCTION enforce_gd_draft_commit_application_slot() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + SELECT workflow_state, input_digest, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = OLD.canonical_tenant_id + AND canonical_version_id = OLD.canonical_version_id + AND request_id = OLD.request_id + AND commit_id = OLD.commit_id + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Draft application slot has no exact commit binding' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF parent_record.workflow_state = 'SYNCHRONIZED' THEN + IF NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = OLD.canonical_tenant_id + AND f.canonical_version_id = OLD.canonical_version_id + AND f.request_id = OLD.request_id + AND f.commit_id = OLD.commit_id + AND f.input_digest = parent_record.input_digest + ) OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(parent_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = OLD.canonical_tenant_id + AND outcome.canonical_version_id = OLD.canonical_version_id + AND outcome.request_id = OLD.request_id + AND outcome.owner = required.owner + WHERE outcome.status IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Synchronized Draft application slot requires its exact complete fence' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF parent_record.workflow_state = 'REJECTED' THEN + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status IN ('APPLIED', 'IN_PROGRESS', 'UNKNOWN') + ) OR NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = OLD.canonical_tenant_id + AND r.canonical_version_id = OLD.canonical_version_id + AND r.request_id = OLD.request_id + AND r.status = 'REJECTED' + ) THEN + RAISE EXCEPTION 'Rejected Draft application slot cannot hide unresolved or applied owners' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF parent_record.workflow_state = 'FAILED_NONPUBLICATION' THEN + IF NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_final_abort abort + WHERE abort.canonical_tenant_id = OLD.canonical_tenant_id + AND abort.canonical_version_id = OLD.canonical_version_id + AND abort.request_id = OLD.request_id + AND abort.commit_id = OLD.commit_id + AND abort.input_digest = parent_record.input_digest + AND abort.binding_json = parent_record.binding_json + ) OR NOT gd_draft_commit_has_exact_terminal_abort_vector( + OLD.canonical_tenant_id, + OLD.canonical_version_id, + OLD.request_id, + OLD.commit_id + ) OR EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = OLD.canonical_tenant_id + AND f.canonical_version_id = OLD.canonical_version_id + AND f.request_id = OLD.request_id + AND f.commit_id = OLD.commit_id + ) THEN + RAISE EXCEPTION 'Failed nonpublication slot release requires exact abort proof and terminal owners' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + RAISE EXCEPTION 'Draft application slot cannot be released before a terminal outcome' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; + END IF; + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Game Design Draft application slot identity is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT workflow_state INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + AND commit_id = NEW.commit_id + FOR UPDATE; + IF NOT FOUND OR parent_record.workflow_state IN ( + 'SYNCHRONIZED', 'REJECTED', 'FAILED_NONPUBLICATION' + ) THEN + RAISE EXCEPTION 'Draft application slot requires an exact nonterminal commit' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_commit_application_slot + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_commit_application_slot + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_commit_application_slot(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql b/services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql new file mode 100644 index 0000000000..a1496e12a2 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V43__authored_draft_publish_selection.sql @@ -0,0 +1,265 @@ +CREATE TABLE game_design_authored_draft_publish_selection ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL, + game_design_version_tenant_key VARCHAR(36) NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + source_provenance_kind VARCHAR(32) NOT NULL, + publish_request_id VARCHAR(1024) NOT NULL, + version_state_epoch BIGINT NOT NULL, + selected_commit_request_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + selected_commit_digest VARCHAR(71) NOT NULL, + selection_digest VARCHAR(71) NOT NULL, + selection_json TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_authored_draft_publish_selection PRIMARY KEY ( + canonical_tenant_id, + canonical_version_id + ), + CONSTRAINT uq_gd_authored_draft_publish_selection_request UNIQUE ( + canonical_tenant_id, + canonical_version_id, + publish_request_id + ), + CONSTRAINT fk_gd_authored_draft_publish_selection_version FOREIGN KEY ( + game_design_version_row_id, + canonical_tenant_id, + canonical_version_id + ) REFERENCES version (id, canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + CONSTRAINT fk_gd_authored_draft_publish_selection_source_game FOREIGN KEY ( + source_game_tenant_key, + source_game_row_id + ) REFERENCES game (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT fk_gd_authored_draft_publish_selection_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + selected_commit_request_id, + selected_commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT fk_gd_authored_draft_publish_selection_fence FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + selected_commit_request_id, + selected_commit_id + ) REFERENCES game_design_draft_commit_visibility_fence ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_authored_draft_publish_selection_identity CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_row_id > 0 + AND source_game_row_id > 0 + AND game_design_version_tenant_key = source_game_tenant_key + AND char_length(game_design_version_tenant_key) BETWEEN 1 AND 36 + AND game_design_version_tenant_key !~ '^[[:space:]]*$' + AND source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + AND char_length(publish_request_id) BETWEEN 1 AND 1024 + AND publish_request_id !~ '^[[:space:]]*$' + AND publish_request_id !~ ':' + AND version_state_epoch > 0 + AND selected_commit_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gd_authored_draft_publish_selection_digests CHECK ( + selected_commit_digest ~ '^sha256:[0-9a-f]{64}$' + AND selection_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_authored_draft_publish_selection_json CHECK ( + jsonb_typeof(selection_json::jsonb) = 'object' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_authored_draft_publish_selection() RETURNS trigger AS $$ +DECLARE + version_record RECORD; + commit_record RECORD; + current_fence RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Authored Draft publication selections are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.selection_json::jsonb ->> 'schemaVersion' IS DISTINCT FROM '1' + OR NEW.selection_json::jsonb -> 'intent' ->> 'canonicalTenantId' + IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'canonicalVersionId' + IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'publishRequestId' + IS DISTINCT FROM NEW.publish_request_id + OR NEW.selection_json::jsonb -> 'intent' ->> 'expectedVersionStateEpoch' + IS DISTINCT FROM NEW.version_state_epoch::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'selectedCommitRequestId' + IS DISTINCT FROM NEW.selected_commit_request_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'selectedCommitId' + IS DISTINCT FROM NEW.selected_commit_id::text + OR NEW.selection_json::jsonb -> 'intent' ->> 'selectedCommitDigest' + IS DISTINCT FROM NEW.selected_commit_digest THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from its complete caller intent' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.selection_json::jsonb -> 'target' ->> 'canonicalTenantId' + IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'canonicalVersionId' + IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'gameDesignVersionRowId' + IS DISTINCT FROM NEW.game_design_version_row_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'gameDesignVersionTenantKey' + IS DISTINCT FROM NEW.game_design_version_tenant_key + OR NEW.selection_json::jsonb -> 'target' ->> 'sourceGameRowId' + IS DISTINCT FROM NEW.source_game_row_id::text + OR NEW.selection_json::jsonb -> 'target' ->> 'sourceGameTenantKey' + IS DISTINCT FROM NEW.source_game_tenant_key + OR NEW.selection_json::jsonb -> 'target' ->> 'sourceProvenanceKind' + IS DISTINCT FROM NEW.source_provenance_kind THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from its private Version source proof' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.version_state, v.version_state_epoch, v.is_script_only, + v.script_patch_version, v.base_version_id + INTO version_record + FROM version v + JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.id = NEW.game_design_version_row_id + AND v.tenant_id = NEW.game_design_version_tenant_key + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id = NEW.source_game_row_id + AND v.identity_source_game_tenant_key = NEW.source_game_tenant_key + AND v.identity_source_provenance_kind = NEW.source_provenance_kind + AND v.version_state = 'DRAFT' + AND v.version_state_epoch = NEW.version_state_epoch + AND v.version_state_epoch > 0 + AND v.is_script_only = FALSE + AND v.script_patch_version IS NULL + AND v.base_version_id IS NULL + FOR UPDATE OF v; + IF NOT FOUND THEN + RAISE EXCEPTION 'Authored Draft publication selection lacks an exact current full Draft Version source' + USING ERRCODE = 'foreign_key_violation'; + END IF; + + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_application_slot s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + ) THEN + RAISE EXCEPTION 'Active or unresolved owner application prevents Draft publication selection' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT c.commit_id, c.input_digest, c.binding_json, c.workflow_state + INTO commit_record + FROM game_design_draft_commit c + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = NEW.selected_commit_request_id + AND c.commit_id = NEW.selected_commit_id; + IF NOT FOUND + OR commit_record.workflow_state <> 'SYNCHRONIZED' + OR commit_record.input_digest <> NEW.selected_commit_digest + OR NEW.selection_json::jsonb ->> 'selectedCommitDigest' + IS DISTINCT FROM commit_record.input_digest + OR NEW.selection_json::jsonb ->> 'selectedCommitBindingJson' + IS DISTINCT FROM commit_record.binding_json THEN + RAISE EXCEPTION 'Selected authored Draft commit is missing or differs from exact durable binding' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'requestId' + IS DISTINCT FROM NEW.selected_commit_request_id::text + OR NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'commitId' + IS DISTINCT FROM NEW.selected_commit_id::text + OR NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'inputDigest' + IS DISTINCT FROM NEW.selected_commit_digest THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from exact synchronized fence identity' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT f.input_digest, f.result_vector_json + INTO current_fence + FROM game_design_draft_commit_visibility_fence f + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id + AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.selected_commit_request_id + AND f.commit_id = NEW.selected_commit_id; + IF NOT FOUND + OR current_fence.input_digest <> NEW.selected_commit_digest + OR NEW.selection_json::jsonb -> 'synchronizedFence' ->> 'resultVectorJson' + IS DISTINCT FROM current_fence.result_vector_json THEN + RAISE EXCEPTION 'Stored authored Draft selection differs from the exact immutable result fence' + USING ERRCODE = 'check_violation'; + END IF; + + IF NOT EXISTS ( + SELECT 1 FROM game_design_draft_commit_visibility v + WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.request_id = NEW.selected_commit_request_id + AND v.commit_id = NEW.selected_commit_id + AND v.input_digest = NEW.selected_commit_digest + ) THEN + RAISE EXCEPTION 'Selected authored Draft commit is stale relative to current synchronized visibility' + USING ERRCODE = 'check_violation'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(commit_record.binding_json::jsonb -> 'requiredOwners') required(owner) + LEFT JOIN game_design_draft_commit_owner_result outcome + ON outcome.canonical_tenant_id = NEW.canonical_tenant_id + AND outcome.canonical_version_id = NEW.canonical_version_id + AND outcome.request_id = NEW.selected_commit_request_id + AND outcome.owner = required.owner + WHERE outcome.status IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Selected authored Draft commit lacks every required APPLIED owner outcome' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_authored_draft_publish_selection + BEFORE INSERT OR UPDATE OR DELETE ON game_design_authored_draft_publish_selection + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_authored_draft_publish_selection(); + +CREATE FUNCTION reject_gd_draft_application_during_authored_publication() RETURNS trigger AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + ) THEN + RAISE EXCEPTION 'Authored Draft publication reservation prevents later owner application' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_application_authored_publication_interlock + BEFORE INSERT ON game_design_draft_commit_application_slot + FOR EACH ROW + EXECUTE FUNCTION reject_gd_draft_application_during_authored_publication(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql b/services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql new file mode 100644 index 0000000000..6ea648cf2f --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V44__authored_draft_publish_request_identity.sql @@ -0,0 +1,5 @@ +-- A publication operation selects one exact Version in its canonical tenant. +-- Conflicting retained reservations deliberately fail migration; no history is discarded. +ALTER TABLE game_design_authored_draft_publish_selection + ADD CONSTRAINT uq_gd_authored_draft_publish_operation + UNIQUE (canonical_tenant_id, publish_request_id); diff --git a/services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql b/services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql new file mode 100644 index 0000000000..5f3b79686d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V45__selected_publish_attempt_digest_capacity.sql @@ -0,0 +1,5 @@ +-- Full-version attempts retain the exact authored-Draft selection digest, +-- including its algorithm prefix. Widen only; preserve every existing attempt +-- and its original request digest, including absent historical evidence. +ALTER TABLE publish_attempt + ALTER COLUMN request_digest TYPE VARCHAR(71); diff --git a/services/game-design-service/src/main/resources/db/migration/V48__game_design_draft_terminal_outcomes.sql b/services/game-design-service/src/main/resources/db/migration/V48__game_design_draft_terminal_outcomes.sql new file mode 100644 index 0000000000..6558e157d0 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V48__game_design_draft_terminal_outcomes.sql @@ -0,0 +1,405 @@ +-- Account-bound Game Design terminal readback is retained independently of coordinator workflow +-- status. Existing V42 rows are deliberately not backfilled: status-only history is not a receipt. +CREATE TABLE game_design_draft_terminal_operation ( + operation_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + fence_id UUID NOT NULL, + actor_account_id UUID NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + base_commit_id VARCHAR(256) NOT NULL, + expected_draft_epoch TEXT NOT NULL, + account_binding_bytes BYTEA NOT NULL, + account_binding_digest VARCHAR(71) NOT NULL, + game_design_binding_json TEXT NOT NULL, + game_design_input_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_terminal_operation PRIMARY KEY (operation_id), + CONSTRAINT uq_gd_draft_terminal_operation_commit UNIQUE ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ), + CONSTRAINT uq_gd_draft_terminal_operation_fence UNIQUE (fence_id), + CONSTRAINT fk_gd_draft_terminal_operation_commit FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) REFERENCES game_design_draft_commit ( + canonical_tenant_id, + canonical_version_id, + request_id, + commit_id + ) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_terminal_operation_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND actor_account_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND octet_length(base_commit_id) BETWEEN 1 AND 256 + AND base_commit_id !~ '^[[:space:]]*$' + AND expected_draft_epoch ~ '^(0|[1-9][0-9]*)$' + AND octet_length(account_binding_bytes) > 0 + ), + CONSTRAINT chk_gd_draft_terminal_operation_digests CHECK ( + account_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_design_input_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gd_draft_terminal_operation_binding CHECK ( + jsonb_typeof(game_design_binding_json::jsonb) = 'object' + ) +); + +CREATE TABLE game_design_draft_terminal_outcome ( + operation_id UUID NOT NULL, + outcome VARCHAR(32) NOT NULL, + owner_result_vector_json TEXT NOT NULL, + terminal_evidence_bytes BYTEA NOT NULL, + terminal_evidence_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_draft_terminal_outcome PRIMARY KEY (operation_id), + CONSTRAINT fk_gd_draft_terminal_outcome_operation FOREIGN KEY (operation_id) + REFERENCES game_design_draft_terminal_operation (operation_id) ON DELETE RESTRICT, + CONSTRAINT chk_gd_draft_terminal_outcome_kind CHECK ( + outcome IN ('COMMITTED', 'DEFINITIVELY_ABORTED') + ), + CONSTRAINT chk_gd_draft_terminal_outcome_evidence CHECK ( + octet_length(terminal_evidence_bytes) > 0 + AND terminal_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND jsonb_typeof(owner_result_vector_json::jsonb) = 'array' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION gd_draft_terminal_vector_matches_owner_results( + target_tenant UUID, + target_version UUID, + target_request UUID, + target_commit UUID, + vector_json TEXT +) RETURNS BOOLEAN AS $$ +DECLARE + parent_record RECORD; + expected_count INTEGER; +BEGIN + SELECT input_digest, binding_json + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = target_tenant + AND canonical_version_id = target_version + AND request_id = target_request + AND commit_id = target_commit; + IF NOT FOUND THEN + RETURN FALSE; + END IF; + IF jsonb_typeof(vector_json::jsonb) IS DISTINCT FROM 'array' + OR jsonb_typeof(parent_record.binding_json::jsonb -> 'requiredOwners') IS DISTINCT FROM 'array' THEN + RETURN FALSE; + END IF; + + expected_count := jsonb_array_length(parent_record.binding_json::jsonb -> 'requiredOwners'); + IF jsonb_array_length(vector_json::jsonb) <> expected_count THEN + RETURN FALSE; + END IF; + + RETURN NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements_text(parent_record.binding_json::jsonb -> 'requiredOwners') required(owner) + WHERE NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(vector_json::jsonb) actual + JOIN game_design_draft_commit_owner_result stored + ON stored.canonical_tenant_id = target_tenant + AND stored.canonical_version_id = target_version + AND stored.request_id = target_request + AND stored.owner = required.owner + WHERE actual ->> 'owner' = required.owner + AND actual ->> 'status' = stored.status + AND actual ->> 'commitId' = stored.result_commit_id::text + AND actual ->> 'bindingDigest' = stored.result_binding_digest + AND actual ->> 'resultIdentity' = stored.result_identity + AND actual ->> 'resultBytesBase64' = replace(encode(stored.result_bytes, 'base64'), E'\n', '') + AND actual -> 'appliedEpochs' = stored.applied_units_json::jsonb + ) + ); +END; +$$ LANGUAGE plpgsql STABLE; + +CREATE FUNCTION enforce_gd_draft_terminal_operation() RETURNS trigger AS $$ +DECLARE + parent_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design Account operation bindings are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT input_digest, binding_json, workflow_state + INTO parent_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + AND commit_id = NEW.commit_id + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account operation must claim an existing Game Design commit' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF parent_record.input_digest IS DISTINCT FROM NEW.game_design_input_digest + OR parent_record.binding_json IS DISTINCT FROM NEW.game_design_binding_json + OR parent_record.workflow_state IS DISTINCT FROM 'QUEUED' + OR NEW.game_design_binding_json::jsonb ->> 'canonicalTenantId' + IS DISTINCT FROM NEW.canonical_tenant_id::text + OR NEW.game_design_binding_json::jsonb ->> 'canonicalVersionId' + IS DISTINCT FROM NEW.canonical_version_id::text + OR NEW.game_design_binding_json::jsonb ->> 'requestId' IS DISTINCT FROM NEW.request_id::text + OR NEW.game_design_binding_json::jsonb ->> 'commitId' IS DISTINCT FROM NEW.commit_id::text + OR NEW.game_design_binding_json::jsonb ->> 'baseCommitId' IS DISTINCT FROM NEW.base_commit_id THEN + RAISE EXCEPTION 'Account operation must claim the exact queued Game Design binding before dispatch' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 + FROM game_design_draft_commit_application_slot slot + WHERE slot.canonical_tenant_id = NEW.canonical_tenant_id + AND slot.canonical_version_id = NEW.canonical_version_id + ) OR EXISTS ( + SELECT 1 + FROM game_design_draft_commit_owner_result owner_result + WHERE owner_result.canonical_tenant_id = NEW.canonical_tenant_id + AND owner_result.canonical_version_id = NEW.canonical_version_id + AND owner_result.request_id = NEW.request_id + AND owner_result.status <> 'NOT_ATTEMPTED' + ) THEN + RAISE EXCEPTION 'Account operation binding was not retained before owner dispatch' + USING ERRCODE = 'check_violation'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM version v + WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.version_state = 'DRAFT' + ) THEN + RAISE EXCEPTION 'Account operation can be claimed only for the exact DRAFT Version' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_operation + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_terminal_operation + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_terminal_operation(); + +CREATE FUNCTION reject_gd_draft_terminal_operation_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_terminal_operation) THEN + RAISE EXCEPTION 'Game Design Account operation bindings cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_operation_no_truncate + BEFORE TRUNCATE ON game_design_draft_terminal_operation + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_terminal_operation_truncate(); + +CREATE FUNCTION enforce_gd_draft_terminal_outcome() RETURNS trigger AS $$ +DECLARE + operation_record RECORD; + commit_record RECORD; + fence_record RECORD; + abort_record RECORD; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Design terminal outcomes are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * + INTO operation_record + FROM game_design_draft_terminal_operation + WHERE operation_id = NEW.operation_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Game Design terminal outcome lacks its exact Account operation binding' + USING ERRCODE = 'foreign_key_violation'; + END IF; + SELECT workflow_state, input_digest, binding_json + INTO commit_record + FROM game_design_draft_commit + WHERE canonical_tenant_id = operation_record.canonical_tenant_id + AND canonical_version_id = operation_record.canonical_version_id + AND request_id = operation_record.request_id + AND commit_id = operation_record.commit_id + FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Game Design terminal outcome lacks its exact coordinator commit' + USING ERRCODE = 'foreign_key_violation'; + END IF; + IF NOT gd_draft_terminal_vector_matches_owner_results( + operation_record.canonical_tenant_id, + operation_record.canonical_version_id, + operation_record.request_id, + operation_record.commit_id, + NEW.owner_result_vector_json + ) THEN + RAISE EXCEPTION 'Terminal outcome requires the complete exact retained owner result vector' + USING ERRCODE = 'check_violation'; + END IF; + + IF NEW.outcome = 'COMMITTED' THEN + SELECT input_digest, result_vector_json + INTO fence_record + FROM game_design_draft_commit_visibility_fence + WHERE canonical_tenant_id = operation_record.canonical_tenant_id + AND canonical_version_id = operation_record.canonical_version_id + AND request_id = operation_record.request_id + AND commit_id = operation_record.commit_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Committed terminal outcome lacks its exact visibility fence' + USING ERRCODE = 'check_violation'; + END IF; + IF commit_record.workflow_state IS DISTINCT FROM 'SYNCHRONIZED' + OR fence_record.input_digest IS DISTINCT FROM operation_record.game_design_input_digest + OR fence_record.result_vector_json IS DISTINCT FROM NEW.owner_result_vector_json + OR NEW.terminal_evidence_bytes IS DISTINCT FROM convert_to(NEW.owner_result_vector_json, 'UTF8') + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(NEW.owner_result_vector_json::jsonb) result_item + WHERE result_item ->> 'status' IS DISTINCT FROM 'APPLIED' + ) THEN + RAISE EXCEPTION 'Committed terminal outcome must match synchronized visibility and every APPLIED owner' + USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.outcome = 'DEFINITIVELY_ABORTED' THEN + SELECT abort_bytes + INTO abort_record + FROM game_design_draft_commit_final_abort + WHERE canonical_tenant_id = operation_record.canonical_tenant_id + AND canonical_version_id = operation_record.canonical_version_id + AND request_id = operation_record.request_id + AND commit_id = operation_record.commit_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Aborted terminal outcome lacks its exact final-abort tombstone' + USING ERRCODE = 'check_violation'; + END IF; + IF commit_record.workflow_state IS DISTINCT FROM 'FAILED_NONPUBLICATION' + OR abort_record.abort_bytes IS DISTINCT FROM NEW.terminal_evidence_bytes + OR EXISTS ( + SELECT 1 + FROM game_design_draft_commit_visibility_fence fence + WHERE fence.canonical_tenant_id = operation_record.canonical_tenant_id + AND fence.canonical_version_id = operation_record.canonical_version_id + AND fence.request_id = operation_record.request_id + AND fence.commit_id = operation_record.commit_id + ) + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(NEW.owner_result_vector_json::jsonb) result_item + WHERE result_item ->> 'status' NOT IN ('APPLIED', 'REJECTED') + ) THEN + RAISE EXCEPTION 'Aborted terminal outcome must match exact final-abort evidence and definitive participants' + USING ERRCODE = 'check_violation'; + END IF; + ELSE + RAISE EXCEPTION 'Unknown Game Design terminal outcome' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_outcome + BEFORE INSERT OR UPDATE OR DELETE ON game_design_draft_terminal_outcome + FOR EACH ROW + EXECUTE FUNCTION enforce_gd_draft_terminal_outcome(); + +CREATE FUNCTION reject_gd_draft_terminal_outcome_truncate() RETURNS trigger AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_draft_terminal_outcome) THEN + RAISE EXCEPTION 'Game Design terminal outcomes cannot be truncated' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_draft_terminal_outcome_no_truncate + BEFORE TRUNCATE ON game_design_draft_terminal_outcome + FOR EACH STATEMENT + EXECUTE FUNCTION reject_gd_draft_terminal_outcome_truncate(); + +CREATE FUNCTION require_gd_draft_account_terminal_readback() RETURNS trigger AS $$ +DECLARE + current_commit RECORD; + operation_record RECORD; + terminal_record RECORD; + expected_outcome VARCHAR(32); +BEGIN + SELECT workflow_state, canonical_tenant_id, canonical_version_id, request_id, commit_id + INTO current_commit + FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id; + IF NOT FOUND THEN + RETURN NULL; + END IF; + IF current_commit.workflow_state NOT IN ('SYNCHRONIZED', 'FAILED_NONPUBLICATION', 'REJECTED') THEN + RETURN NULL; + END IF; + + SELECT operation_id + INTO operation_record + FROM game_design_draft_terminal_operation + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id + AND commit_id = NEW.commit_id; + IF NOT FOUND THEN + RETURN NULL; + END IF; + + IF current_commit.workflow_state = 'REJECTED' THEN + RAISE EXCEPTION 'Account-bound rejection is not a terminal readback; exact final-abort evidence is required' + USING ERRCODE = 'check_violation'; + END IF; + + expected_outcome := + CASE current_commit.workflow_state + WHEN 'SYNCHRONIZED' THEN 'COMMITTED' + ELSE 'DEFINITIVELY_ABORTED' + END; + SELECT outcome + INTO terminal_record + FROM game_design_draft_terminal_outcome + WHERE operation_id = operation_record.operation_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account-bound terminal workflow state requires its same-transaction exact outcome row' + USING ERRCODE = 'check_violation'; + END IF; + IF terminal_record.outcome IS DISTINCT FROM expected_outcome THEN + RAISE EXCEPTION 'Account-bound terminal workflow state requires its same-transaction exact outcome row' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER trg_gd_draft_account_terminal_readback + AFTER UPDATE ON game_design_draft_commit + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW + EXECUTE FUNCTION require_gd_draft_account_terminal_readback(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql new file mode 100644 index 0000000000..4b7d6eb4c7 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql @@ -0,0 +1,238 @@ +-- Retained attestations keep their original schema and bytes; no selector is inferred or backfilled. +ALTER TABLE published_release_bundle + ADD COLUMN world_published_start_location_evidence_json TEXT; + +-- This adds an insertion guard beside (and does not replace) the existing immutable row/source guards. +-- Payload decoding checks storage relations, not authenticated World producer provenance. +-- [jooq ignore start] +-- The retained Account and World operation use big-endian byte-length frames. +CREATE FUNCTION published_world_selector_frame(payload BYTEA, wanted INTEGER) RETURNS BYTEA AS $$ +DECLARE + offset_bytes INTEGER := 0; + frame_index INTEGER := 0; + frame_length BIGINT; +BEGIN + WHILE offset_bytes < octet_length(payload) LOOP + IF offset_bytes + 4 > octet_length(payload) THEN + RAISE EXCEPTION 'truncated published World evidence frame' USING ERRCODE = 'check_violation'; + END IF; + frame_length := get_byte(payload, offset_bytes)::BIGINT * 16777216 + + get_byte(payload, offset_bytes + 1)::BIGINT * 65536 + + get_byte(payload, offset_bytes + 2)::BIGINT * 256 + get_byte(payload, offset_bytes + 3); + offset_bytes := offset_bytes + 4; + IF frame_length > octet_length(payload) - offset_bytes THEN + RAISE EXCEPTION 'invalid published World evidence frame length' USING ERRCODE = 'check_violation'; + END IF; + IF frame_index = wanted THEN + RETURN substring(payload FROM offset_bytes + 1 FOR frame_length::INTEGER); + END IF; + offset_bytes := offset_bytes + frame_length::INTEGER; + frame_index := frame_index + 1; + END LOOP; + RAISE EXCEPTION 'missing published World evidence frame' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION enforce_published_world_start_location_evidence() RETURNS trigger AS $$ +DECLARE + evidence JSONB; + selection JSONB; + applied JSONB; + receipt JSONB; + participants JSONB; + item JSONB; + owner_key TEXT; + required_schema INTEGER; + field_name TEXT; + account_bytes BYTEA; + operation_bytes BYTEA; + draft JSONB; + affected JSONB; +BEGIN + IF NEW.attestation_schema_version <> 'v2' THEN + IF NEW.world_published_start_location_evidence_json IS NOT NULL THEN + RAISE EXCEPTION 'historical release schemas cannot carry a World selector' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.world_published_start_location_evidence_json IS NULL + OR NEW.script_only OR NEW.script_patch_version IS NOT NULL + OR NEW.canonical_tenant_id IS NULL OR NEW.canonical_version_id IS NULL + OR NEW.manifest_schema_version IS NULL OR NEW.artifact_digests_json IS NULL THEN + RAISE EXCEPTION 'release v2 requires complete full-Version selector evidence' + USING ERRCODE = 'check_violation'; + END IF; + evidence := NEW.world_published_start_location_evidence_json::JSONB; + selection := evidence->'request'; + FOR field_name IN SELECT unnest(ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'publishWorkflowId','appliedCommitId','contentDigest']) + LOOP + IF jsonb_typeof(selection->field_name) IS DISTINCT FROM 'string' + OR coalesce(selection->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 has missing selection text binding' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + IF jsonb_typeof(evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR NOT evidence ?& ARRAY['schema','request','selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64'] + OR evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR jsonb_typeof(selection) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selection)) <> 13 + OR NOT selection ?& ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'versionStateEpoch','publishWorkflowId','appliedCommitId','contentDigest', + 'digestSchemaVersion','worldAffectedTuples'] + OR selection->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR selection->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR selection->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR selection->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR selection->>'intakeRequestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'intakeRequestId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'publicationFence' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'publicationFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'appliedCommitId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'appliedCommitId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR coalesce(selection->>'publicationRequestId','') = '' + OR selection->>'requestDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'versionStateEpoch' !~ '^[1-9][0-9]*$' + OR jsonb_typeof(selection->'versionStateEpoch') IS DISTINCT FROM 'string' + OR length(selection->>'versionStateEpoch') > 19 + OR (length(selection->>'versionStateEpoch') = 19 + AND selection->>'versionStateEpoch' > '9223372036854775807') + OR jsonb_typeof(selection->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR selection->>'digestSchemaVersion' IS DISTINCT FROM '3' + OR jsonb_typeof(selection->'worldAffectedTuples') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'release v2 World selection has missing, unsupported or mismatched bindings' + USING ERRCODE = 'check_violation'; + END IF; + IF jsonb_array_length(selection->'worldAffectedTuples') = 0 THEN + RAISE EXCEPTION 'release v2 requires the complete World affected set' USING ERRCODE = 'check_violation'; + END IF; + -- Binary Account and APPLIED bytes remain intact; Java independently checks their full relation. + IF jsonb_typeof(evidence->'originalAccountBindingBytesBase64') IS DISTINCT FROM 'string' + OR octet_length(decode(evidence->>'originalAccountBindingBytesBase64','base64')) = 0 + OR jsonb_typeof(evidence->'appliedResultBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(evidence->'selectorReceiptBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'release v2 requires complete original owner bytes' + USING ERRCODE = 'check_violation'; + END IF; + applied := convert_from(decode(evidence->>'appliedResultBytesBase64','base64'),'UTF8')::JSONB; + receipt := convert_from(decode(evidence->>'selectorReceiptBytesBase64','base64'),'UTF8')::JSONB; + FOR field_name IN SELECT unnest(ARRAY['selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64']) + LOOP + IF replace(encode(decode(evidence->>field_name,'base64'),'base64'), E'\n','') + IS DISTINCT FROM evidence->>field_name THEN + RAISE EXCEPTION 'release v2 owner bytes are not canonical base64' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest']) + LOOP + IF jsonb_typeof(applied->field_name) IS DISTINCT FROM 'string' + OR coalesce(applied->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 APPLIED result has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','graphDigest','receiptDigest']) + LOOP + IF jsonb_typeof(receipt->field_name) IS DISTINCT FROM 'string' + OR coalesce(receipt->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 selector receipt has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + account_bytes := decode(evidence->>'originalAccountBindingBytesBase64','base64'); + operation_bytes := decode(applied->>'operationBytesBase64','base64'); + draft := convert_from(published_world_selector_frame(account_bytes, 11),'UTF8')::JSONB; + SELECT coalesce(jsonb_agg(unit ORDER BY unit->>'owner', unit->>'aggregateType', + unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId', unit->>'expectedEpoch'),'[]'::JSONB) + INTO affected FROM jsonb_array_elements(draft->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF applied->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR applied->>'status' IS DISTINCT FROM 'APPLIED' + OR applied->>'startLocationReceiptBase64' IS DISTINCT FROM evidence->>'selectorReceiptBytesBase64' + OR receipt->>'schema' IS DISTINCT FROM 'world-draft-start-location-receipt/v1' + OR receipt->>'targetNamespace' IS DISTINCT FROM selection->>'targetNamespace' + OR receipt->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR receipt->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR receipt->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR receipt->>'receiptDigest' IS DISTINCT FROM applied->>'startLocationReceiptDigest' + OR jsonb_typeof(applied) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(applied)) <> 8 + OR NOT applied ?& ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest','appliedEpochs'] + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 11 + OR NOT receipt ?& ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','startLocation','graphDigest','receiptDigest'] + OR jsonb_typeof(receipt->'startLocation') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt->'startLocation')) <> 3 + OR NOT (receipt->'startLocation') ?& ARRAY['tenantId','versionId','roomTemplateId'] + OR selection->'worldAffectedTuples' IS DISTINCT FROM affected + OR draft->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR draft->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR draft->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR draft->'target'->>'gameDesignVersionRowId' IS DISTINCT FROM NEW.version_id::TEXT + OR draft->'target'->>'gameDesignVersionTenantKey' IS DISTINCT FROM NEW.tenant_id + OR published_world_selector_frame(account_bytes, 11) IS DISTINCT FROM published_world_selector_frame(account_bytes, 12) + OR published_world_selector_frame(operation_bytes, 7) IS DISTINCT FROM published_world_selector_frame(account_bytes, 11) + OR convert_from(published_world_selector_frame(account_bytes, 13),'UTF8') IS DISTINCT FROM receipt->>'bindingDigest' + OR receipt->>'accountBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes),'hex') + OR applied->>'graphDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(applied->>'graphBytesBase64','base64')),'hex') + OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1' + OR convert_from(published_world_selector_frame(account_bytes, 1),'UTF8') IS DISTINCT FROM receipt->>'operationId' + OR convert_from(published_world_selector_frame(account_bytes, 2),'UTF8') IS DISTINCT FROM receipt->>'requestId' + OR convert_from(published_world_selector_frame(account_bytes, 3),'UTF8') IS DISTINCT FROM selection->>'appliedCommitId' + OR convert_from(published_world_selector_frame(account_bytes, 4),'UTF8') IS DISTINCT FROM receipt->>'authorizationFenceId' + OR convert_from(published_world_selector_frame(account_bytes, 6),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(account_bytes, 7),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 0),'UTF8') IS DISTINCT FROM 'world-draft-terminal-operation/v1' + OR published_world_selector_frame(operation_bytes, 20) IS DISTINCT FROM account_bytes + OR convert_from(published_world_selector_frame(operation_bytes, 13),'UTF8') IS DISTINCT FROM selection->>'intakeRequestId' + OR convert_from(published_world_selector_frame(operation_bytes, 8),'UTF8') IS DISTINCT FROM selection->>'targetNamespace' + OR convert_from(published_world_selector_frame(operation_bytes, 9),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 10),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->'startLocation'->>'roomTemplateId' IS NULL THEN + RAISE EXCEPTION 'release v2 selector differs from original selected APPLIED receipt' + USING ERRCODE = 'check_violation'; + END IF; + participants := NEW.participant_digests_json::JSONB; + IF jsonb_typeof(participants) IS DISTINCT FROM 'array' OR jsonb_array_length(participants) <> 5 THEN + RAISE EXCEPTION 'release v2 requires all five participant owners' USING ERRCODE = 'check_violation'; + END IF; + FOR owner_key, required_schema IN SELECT * FROM (VALUES + ('WORLD_MANAGEMENT',3),('ENTITY_MANAGEMENT',2),('GAME_LOGIC',1), + ('AUTOMATION_SCRIPTING',5),('GAME_DESIGN_CONTROL_PLANE',1)) owners(owner_key, required_schema) + LOOP + IF (SELECT count(*) FROM jsonb_array_elements(participants) p + WHERE p->>'participantKey' = owner_key) <> 1 THEN + RAISE EXCEPTION 'release v2 has missing or duplicate participant owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT p INTO item FROM jsonb_array_elements(participants) p WHERE p->>'participantKey' = owner_key; + IF item->>'scopeValue' IS DISTINCT FROM NEW.version_id::TEXT + OR item->>'baseVersionId' IS NOT NULL + OR item->>'appliedCommitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR item->>'digestSchemaVersion' IS DISTINCT FROM required_schema::TEXT + OR coalesce(item->>'contentDigest','') !~ '^[0-9a-f]{64}$' + OR coalesce(item->>'errorCode','') <> '' + OR (owner_key = 'WORLD_MANAGEMENT' AND item->>'contentDigest' IS DISTINCT FROM selection->>'contentDigest') + OR (owner_key = 'GAME_LOGIC' AND coalesce(item->>'abilitySchemaDigest','') !~ '^sha256:[0-9a-f]{64}$') THEN + RAISE EXCEPTION 'release v2 participant differs from selected commit/digest/schema' + USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_published_world_start_location_evidence + BEFORE INSERT ON published_release_bundle + FOR EACH ROW EXECUTE FUNCTION enforce_published_world_start_location_evidence(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql b/services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql new file mode 100644 index 0000000000..056e74b3a5 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V50__publication_operation_terminal_seal.sql @@ -0,0 +1,180 @@ +ALTER TABLE publish_attempt ADD COLUMN revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0); + +CREATE TABLE game_design_publication_operation ( + publish_workflow_id VARCHAR(1024) PRIMARY KEY REFERENCES publish_attempt(publish_workflow_id) ON DELETE RESTRICT, + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL REFERENCES version(id) ON DELETE RESTRICT, + selection_digest VARCHAR(71) NOT NULL, + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) > 0), + outcome TEXT NOT NULL DEFAULT 'PENDING' CHECK (outcome IN ('PENDING', 'PUBLISHED', 'NO_PUBLICATION')), + revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0), + result_bytes BYTEA, + release_row_json TEXT, + CHECK ((outcome = 'PENDING') = (result_bytes IS NULL)), + CHECK ((outcome = 'PUBLISHED') = (release_row_json IS NOT NULL)), + UNIQUE (tenant_id, version_id) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_game_design_publication_operation() RETURNS trigger AS $$ +DECLARE attempt publish_attempt%ROWTYPE; selected game_design_authored_draft_publish_selection%ROWTYPE; + account_bytes BYTEA; input_bytes BYTEA; world_json JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'publication operation history is immutable' USING ERRCODE = 'check_violation'; + END IF; + PERFORM 1 FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM publish_attempt + WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + PERFORM 1 FROM version WHERE id = NEW.version_id AND tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT selected FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = NEW.tenant_id AND game_design_version_row_id = NEW.version_id; + account_bytes := published_world_selector_frame(NEW.request_bytes, 1); + input_bytes := published_world_selector_frame(account_bytes, 3); + world_json := convert_from(published_world_selector_frame(NEW.request_bytes, 2), 'UTF8')::JSONB; + IF convert_from(published_world_selector_frame(NEW.request_bytes, 0), 'UTF8') <> 'game-design-publication-operation/v1' + OR convert_from(published_world_selector_frame(account_bytes, 0), 'UTF8') <> 'account-publication-authorization/v1' + OR convert_from(published_world_selector_frame(input_bytes, 0), 'UTF8') <> 'account-publication-input/v1' + OR published_world_selector_frame(input_bytes, 2) IS DISTINCT FROM convert_to(selected.selection_json, 'UTF8') + OR convert_from(published_world_selector_frame(input_bytes, 3), 'UTF8') IS DISTINCT FROM selected.selection_digest + OR world_json->'request'->>'requestDigest' IS DISTINCT FROM substring(selected.selection_digest FROM 8) + OR world_json->'request'->>'canonicalTenantId' IS DISTINCT FROM selected.canonical_tenant_id::TEXT + OR world_json->'request'->>'canonicalVersionId' IS DISTINCT FROM selected.canonical_version_id::TEXT + OR world_json->'request'->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR world_json->'request'->>'publicationRequestId' IS DISTINCT FROM selected.publish_request_id + OR world_json->'request'->>'versionStateEpoch' IS DISTINCT FROM selected.version_state_epoch::TEXT THEN + RAISE EXCEPTION 'publication operation bytes differ from exact owner selection' USING ERRCODE = 'check_violation'; + END IF; + IF attempt.tenant_id <> NEW.tenant_id OR attempt.version_id <> NEW.version_id + OR attempt.publish_type <> 'FULL_VERSION' OR attempt.request_digest IS DISTINCT FROM NEW.selection_digest + OR NOT EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.game_design_version_tenant_key = NEW.tenant_id + AND s.game_design_version_row_id = NEW.version_id AND s.selection_digest = NEW.selection_digest) THEN + RAISE EXCEPTION 'publication operation does not bind exact selected attempt' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.outcome <> 'PENDING' OR NEW.revision <> 1 OR attempt.status <> 'PENDING' + OR EXISTS (SELECT 1 FROM published_release_bundle WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id) THEN + RAISE EXCEPTION 'historical attempts cannot acquire publication authority' USING ERRCODE = 'check_violation'; + END IF; + ELSE + IF OLD.outcome <> 'PENDING' OR NEW.outcome = 'PENDING' + OR NEW.revision <> OLD.revision + 1 + OR (NEW.publish_workflow_id, NEW.tenant_id, NEW.version_id, NEW.selection_digest, NEW.request_bytes) + IS DISTINCT FROM (OLD.publish_workflow_id, OLD.tenant_id, OLD.version_id, OLD.selection_digest, OLD.request_bytes) THEN + RAISE EXCEPTION 'publication operation identity or terminal outcome is immutable' USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER game_design_publication_operation_guard BEFORE INSERT OR UPDATE OR DELETE + ON game_design_publication_operation FOR EACH ROW EXECUTE FUNCTION guard_game_design_publication_operation(); + +CREATE FUNCTION guard_selected_publication_release() RETURNS trigger AS $$ +DECLARE attempt publish_attempt%ROWTYPE; operation game_design_publication_operation%ROWTYPE; +BEGIN + IF NEW.script_only THEN RETURN NEW; END IF; + -- Old unselected history keeps its original read semantics; no operation is backfilled. + IF NEW.attestation_schema_version <> 'v2' AND NOT EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = NEW.tenant_id AND game_design_version_row_id = NEW.version_id) THEN + RETURN NEW; + END IF; + PERFORM 1 FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM publish_attempt WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + PERFORM 1 FROM version WHERE id = NEW.version_id AND tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF attempt.status <> 'PENDING' OR operation.outcome <> 'PENDING' + OR operation.tenant_id <> NEW.tenant_id OR operation.version_id <> NEW.version_id + OR attempt.request_digest IS DISTINCT FROM operation.selection_digest + OR NEW.attestation_schema_version <> 'v2' + OR convert_to(NEW.world_published_start_location_evidence_json, 'UTF8') + IS DISTINCT FROM published_world_selector_frame(operation.request_bytes, 2) THEN + RAISE EXCEPTION 'selected publication is absent, sealed, or changed' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER selected_publication_release_guard BEFORE INSERT ON published_release_bundle + FOR EACH ROW EXECUTE FUNCTION guard_selected_publication_release(); + +CREATE FUNCTION verify_publication_operation_commit() RETURNS trigger AS $$ +DECLARE operation game_design_publication_operation%ROWTYPE; release_json TEXT; attempt_status TEXT; +BEGIN + SELECT * INTO operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF NOT FOUND THEN RETURN NULL; END IF; + SELECT status INTO attempt_status FROM publish_attempt WHERE publish_workflow_id = operation.publish_workflow_id; + SELECT to_jsonb(r)::TEXT INTO release_json FROM published_release_bundle r + WHERE r.tenant_id = operation.tenant_id AND r.version_id = operation.version_id; + IF operation.outcome <> 'PENDING' AND operation.result_bytes IS DISTINCT FROM + int4send(octet_length(convert_to('game-design-publication-owner-readback/v1', 'UTF8'))) + || convert_to('game-design-publication-owner-readback/v1', 'UTF8') + || int4send(octet_length(operation.request_bytes)) || operation.request_bytes + || int4send(octet_length(convert_to(operation.outcome, 'UTF8'))) || convert_to(operation.outcome, 'UTF8') + || int4send(octet_length(convert_to(COALESCE(operation.release_row_json, ''), 'UTF8'))) + || convert_to(COALESCE(operation.release_row_json, ''), 'UTF8') THEN + RAISE EXCEPTION 'publication result bytes are not the exact owner receipt' USING ERRCODE = 'check_violation'; + END IF; + IF operation.outcome = 'PENDING' AND (release_json IS NOT NULL OR attempt_status <> 'PENDING') THEN + RAISE EXCEPTION 'selected publication must commit receipt and owner result together' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'NO_PUBLICATION' AND (release_json IS NOT NULL OR attempt_status <> 'FAILED') THEN + RAISE EXCEPTION 'no-publication seal contradicts owner commit' USING ERRCODE = 'check_violation'; + ELSIF operation.outcome = 'PUBLISHED' AND (release_json IS DISTINCT FROM operation.release_row_json + OR attempt_status <> 'SUCCEEDED' + OR NOT EXISTS (SELECT 1 FROM version WHERE id = operation.version_id AND tenant_id = operation.tenant_id AND version_state = 'PUBLISHED') + OR NOT EXISTS (SELECT 1 FROM version_asset_artifact WHERE tenant_id = operation.tenant_id AND version_id = operation.version_id AND artifact_state = 'PUBLISHED')) THEN + RAISE EXCEPTION 'publication receipt lacks atomic owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER publication_operation_commit_guard AFTER INSERT OR UPDATE + ON game_design_publication_operation DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); +CREATE CONSTRAINT TRIGGER selected_publication_release_commit_guard AFTER INSERT + ON published_release_bundle DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); +CREATE CONSTRAINT TRIGGER selected_publication_attempt_commit_guard AFTER UPDATE + ON publish_attempt DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_operation_commit(); + +CREATE FUNCTION guard_publish_attempt_revision() RETURNS trigger AS $$ +BEGIN + IF OLD.status <> 'PENDING' OR NEW.revision <> OLD.revision + 1 + OR (NEW.id, NEW.tenant_id, NEW.publish_workflow_id, NEW.publish_type, NEW.version_id, + NEW.version_number, NEW.script_patch_version, NEW.base_version_id, NEW.created_at) + IS DISTINCT FROM (OLD.id, OLD.tenant_id, OLD.publish_workflow_id, OLD.publish_type, OLD.version_id, + OLD.version_number, OLD.script_patch_version, OLD.base_version_id, OLD.created_at) + OR (NEW.request_digest IS DISTINCT FROM OLD.request_digest AND + (OLD.request_digest IS NOT NULL OR EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = OLD.tenant_id AND game_design_version_row_id = OLD.version_id))) THEN + RAISE EXCEPTION 'publish attempt is stale or terminal' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publish_attempt_revision_guard BEFORE UPDATE ON publish_attempt + FOR EACH ROW EXECUTE FUNCTION guard_publish_attempt_revision(); + +CREATE FUNCTION guard_sealed_candidate_admission() RETURNS trigger AS $$ +BEGIN + -- Private puts already in flight may finish; this guards admission/retained candidate changes, + -- not cancellation, reachability, abandonment, deletion, or distributed object-store writes. + IF NEW.artifact_state = 'STAGED' AND EXISTS (SELECT 1 FROM game_design_publication_operation + WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id AND outcome <> 'PENDING') THEN + RAISE EXCEPTION 'sealed publication refuses candidate admission' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER sealed_candidate_admission_guard BEFORE INSERT OR UPDATE ON version_asset_artifact + FOR EACH ROW EXECUTE FUNCTION guard_sealed_candidate_admission(); + +CREATE FUNCTION forbid_publication_operation_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'publication operation history cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publication_operation_no_truncate BEFORE TRUNCATE ON game_design_publication_operation + FOR EACH STATEMENT EXECUTE FUNCTION forbid_publication_operation_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql b/services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql new file mode 100644 index 0000000000..a40cd4fd14 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V51__publication_terminal_content_and_epoch.sql @@ -0,0 +1,141 @@ +-- Retained V50 terminal rows keep their original bytes and gain no unverifiable epoch. +ALTER TABLE game_design_publication_operation ADD COLUMN terminal_evidence_bytes BYTEA; +ALTER TABLE game_design_publication_operation ADD COLUMN publication_version_state_epoch BIGINT; +ALTER TABLE game_design_publication_operation ADD COLUMN release_content_bytes BYTEA; +ALTER TABLE game_design_publication_operation ADD COLUMN published_release_bundle_digest VARCHAR(71); +ALTER TABLE game_design_publication_operation ADD CONSTRAINT publication_terminal_extension_shape CHECK ( + (terminal_evidence_bytes IS NULL AND publication_version_state_epoch IS NULL + AND release_content_bytes IS NULL AND published_release_bundle_digest IS NULL) + OR (terminal_evidence_bytes IS NOT NULL AND octet_length(terminal_evidence_bytes) > 0 AND + ((outcome = 'NO_PUBLICATION' AND publication_version_state_epoch IS NULL + AND release_content_bytes IS NULL AND published_release_bundle_digest IS NULL) + OR (outcome = 'PUBLISHED' AND publication_version_state_epoch IS NOT NULL AND publication_version_state_epoch > 0 + AND release_content_bytes IS NOT NULL AND octet_length(release_content_bytes) > 0 + AND published_release_bundle_digest IS NOT NULL AND published_release_bundle_digest ~ '^sha256:[0-9a-f]{64}$')))); + +-- [jooq ignore start] +-- ADR byte-length framing for complete immutable release content, distinct from launch evidence. +CREATE FUNCTION publication_content_frame(value BYTEA) RETURNS BYTEA AS $$ + SELECT convert_to(octet_length(value)::TEXT || ':', 'UTF8') || value; +$$ LANGUAGE SQL IMMUTABLE STRICT; +CREATE FUNCTION publication_content_text(value TEXT) RETURNS BYTEA AS $$ + SELECT publication_content_frame(convert_to(value, 'UTF8')); +$$ LANGUAGE SQL IMMUTABLE STRICT; +CREATE FUNCTION publication_content_optional(value TEXT) RETURNS BYTEA AS $$ + SELECT publication_content_text(CASE WHEN value IS NULL THEN 'false' ELSE 'true' END) + || publication_content_text(COALESCE(value, '')); +$$ LANGUAGE SQL IMMUTABLE; +CREATE FUNCTION publication_content_strings(values_json JSONB) RETURNS BYTEA AS $$ +DECLARE result BYTEA; value JSONB; +BEGIN + result := publication_content_text(jsonb_array_length(values_json)::TEXT); + FOR value IN SELECT * FROM jsonb_array_elements(values_json) LOOP + result := result || publication_content_text(value #>> '{}'); + END LOOP; + RETURN result; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION publication_release_content(release published_release_bundle) RETURNS BYTEA AS $$ +DECLARE result BYTEA; entry BYTEA; item JSONB; +BEGIN + IF release.script_only OR release.script_patch_version IS NOT NULL + OR release.attestation_schema_version <> 'v2' THEN + RAISE EXCEPTION 'terminal publication requires complete full-version v2 content' USING ERRCODE = 'check_violation'; + END IF; + result := publication_content_text('game-design-published-release-bundle/v1') + || publication_content_text(release.canonical_tenant_id::TEXT) + || publication_content_text(release.canonical_version_id::TEXT) + || publication_content_text(release.published_release_bundle_ref) + || publication_content_text(release.version_number::TEXT) + || publication_content_text(release.attestation_schema_version) + || publication_content_text(release.publish_workflow_id) + || publication_content_text(release.manifest_hash) + || publication_content_text(release.manifest_schema_version::TEXT) + || publication_content_text(jsonb_array_length(release.artifact_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.artifact_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'usageKey') || publication_content_text(item->>'artifactKind') + || publication_content_text(item->>'immutableObjectKey') || publication_content_text(item->>'contentDigest') + || publication_content_text(item->>'contentType') || publication_content_text(item->>'artifactSchemaVersion'); + result := result || publication_content_frame(entry); + END LOOP; + result := result || publication_content_strings(release.required_manifest_asset_keys_json::JSONB) + || publication_content_text(jsonb_array_length(release.participant_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.participant_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'participantKey') || publication_content_text(item->>'scopeValue') + || publication_content_optional(item->>'baseVersionId') || publication_content_text(item->>'appliedCommitId') + || publication_content_text(item->>'contentDigest') || publication_content_text(item->>'digestSchemaVersion') + || publication_content_optional(item->>'abilitySchemaDigest') || publication_content_optional(item->>'errorCode') + || publication_content_optional(item->>'errorMessage'); + result := result || publication_content_frame(entry); + END LOOP; + RETURN result || publication_content_strings(release.command_definitions_json::JSONB) + || publication_content_text(release.generation_config_revision) + || publication_content_text(release.world_published_start_location_evidence_json) + || publication_content_text('false') || publication_content_optional(NULL); +END; +$$ LANGUAGE plpgsql STABLE STRICT; + +CREATE FUNCTION guard_publication_terminal_extension() RETURNS trigger AS $$ +DECLARE release published_release_bundle%ROWTYPE; owner_version version%ROWTYPE; + expected BYTEA; content BYTEA; freeze_epoch BIGINT; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.terminal_evidence_bytes IS NOT NULL THEN + RAISE EXCEPTION 'new publication operation must remain pending' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + -- This extension is captured only at the original seal, never backfilled onto V50 history. + IF OLD.outcome <> 'PENDING' OR OLD.terminal_evidence_bytes IS NOT NULL + OR NEW.outcome = 'PENDING' OR NEW.terminal_evidence_bytes IS NULL THEN + RAISE EXCEPTION 'publication terminal extension is immutable and cannot be backfilled' USING ERRCODE = 'check_violation'; + END IF; + expected := int4send(octet_length(convert_to('game-design-publication-terminal/v1', 'UTF8'))) + || convert_to('game-design-publication-terminal/v1', 'UTF8') + || int4send(octet_length(NEW.request_bytes)) || NEW.request_bytes + || int4send(octet_length(convert_to(NEW.outcome, 'UTF8'))) || convert_to(NEW.outcome, 'UTF8'); + IF NEW.outcome = 'PUBLISHED' THEN + SELECT * INTO STRICT release FROM published_release_bundle + WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id; + SELECT * INTO STRICT owner_version FROM version + WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id FOR UPDATE; + freeze_epoch := ((convert_from(published_world_selector_frame(NEW.request_bytes, 2), 'UTF8')::JSONB) + ->'request'->>'versionStateEpoch')::BIGINT; + content := publication_release_content(release); + IF owner_version.version_state <> 'PUBLISHED' + OR owner_version.version_state_epoch <> freeze_epoch + 1 + OR NEW.publication_version_state_epoch IS DISTINCT FROM owner_version.version_state_epoch + OR NEW.release_content_bytes IS DISTINCT FROM content + OR NEW.published_release_bundle_digest IS DISTINCT FROM 'sha256:' || encode(sha256(content), 'hex') + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR to_jsonb(release)::TEXT IS DISTINCT FROM NEW.release_row_json THEN + RAISE EXCEPTION 'publication terminal content or committed epoch differs from owner seal' USING ERRCODE = 'check_violation'; + END IF; + expected := expected || int4send(octet_length(content)) || content + || int4send(octet_length(convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'))) + || convert_to(NEW.publication_version_state_epoch::TEXT, 'UTF8'); + END IF; + IF NEW.terminal_evidence_bytes IS DISTINCT FROM expected THEN + RAISE EXCEPTION 'publication terminal bytes differ from original owner result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER publication_terminal_extension_guard BEFORE INSERT OR UPDATE + ON game_design_publication_operation FOR EACH ROW EXECUTE FUNCTION guard_publication_terminal_extension(); + +CREATE FUNCTION verify_publication_terminal_epoch_commit() RETURNS trigger AS $$ +BEGIN + IF NEW.outcome = 'PUBLISHED' AND NEW.terminal_evidence_bytes IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM version WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id + AND version_state = 'PUBLISHED' AND version_state_epoch = NEW.publication_version_state_epoch) THEN + RAISE EXCEPTION 'publication terminal epoch lacks its exact atomic Version commit' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER publication_terminal_epoch_commit_guard AFTER UPDATE + ON game_design_publication_operation DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_publication_terminal_epoch_commit(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V52__immutable_realm_policy_source.sql b/services/game-design-service/src/main/resources/db/migration/V52__immutable_realm_policy_source.sql new file mode 100644 index 0000000000..c391045127 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V52__immutable_realm_policy_source.sql @@ -0,0 +1,311 @@ +-- Explicit new-Draft genesis requires the Version's actual insertion transaction witness. +-- No retained backfill or inferred empty baseline is installed. +CREATE TABLE game_design_realm_policy_version_insert ( + version_id BIGINT PRIMARY KEY REFERENCES version (id), + creation_transaction_id TEXT NOT NULL CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); + +CREATE TABLE game_design_realm_policy_genesis ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + receipt_id UUID NOT NULL UNIQUE, + version_id BIGINT NOT NULL UNIQUE REFERENCES game_design_realm_policy_version_insert (version_id), + creation_transaction_id TEXT NOT NULL, + receipt_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (version_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000') +); + +CREATE TABLE game_design_realm_policy_snapshot ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + inherited_commit_id UUID, + snapshot_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit_visibility_fence + (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- PostgreSQL JSON extraction is unsupported by the jOOQ DDL simulation; retain the exact owner checks. +-- [jooq ignore start] +ALTER TABLE game_design_realm_policy_snapshot + ADD CONSTRAINT realm_policy_snapshot_schema CHECK (snapshot_json::JSONB->>'schema' = 'game-design-realm-policy-snapshot/v1'), + ADD CONSTRAINT realm_policy_snapshot_epoch CHECK (snapshot_json::JSONB->>'sourceEpoch' ~ '^(0|[1-9][0-9]*)$'), + ADD CONSTRAINT realm_policy_snapshot_set_shape CHECK (jsonb_typeof(snapshot_json::JSONB->'policies') = 'array' + AND jsonb_array_length(snapshot_json::JSONB->'policies') BETWEEN 0 AND 128); +-- [jooq ignore stop] + +CREATE TABLE game_design_realm_policy_source ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + visible_commit_id UUID, + genesis_receipt_id UUID REFERENCES game_design_realm_policy_genesis (receipt_id), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id), + CHECK (visible_commit_id IS NOT NULL OR genesis_receipt_id IS NOT NULL) +); + +CREATE TABLE game_design_realm_policy_application ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + inherited_commit_id UUID, + genesis_receipt_id UUID REFERENCES game_design_realm_policy_genesis (receipt_id), + expected_epoch TEXT NOT NULL CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), + snapshot_json TEXT NOT NULL, + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + owner_result_bytes BYTEA, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id), + CHECK (inherited_commit_id IS NOT NULL OR genesis_receipt_id IS NOT NULL) +); + +-- [jooq ignore start] +ALTER TABLE game_design_realm_policy_application + ADD CONSTRAINT realm_policy_application_schema CHECK (snapshot_json::JSONB->>'schema' = 'game-design-realm-policy-snapshot/v1'), + ADD CONSTRAINT realm_policy_application_set_shape CHECK (jsonb_typeof(snapshot_json::JSONB->'policies') = 'array' + AND jsonb_array_length(snapshot_json::JSONB->'policies') BETWEEN 0 AND 128); +-- [jooq ignore stop] + +CREATE TABLE game_design_realm_policy_capture ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE REFERENCES game_design_publication_operation (publish_workflow_id), + commit_id UUID NOT NULL, + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + capture_bytes BYTEA NOT NULL CHECK (octet_length(capture_bytes) > 0), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION witness_realm_policy_version_insert() RETURNS trigger AS $$ +BEGIN + IF NEW.canonical_tenant_id IS NOT NULL AND NEW.canonical_version_id IS NOT NULL + AND NEW.version_state = 'DRAFT' AND NOT NEW.is_script_only + AND NEW.script_patch_version IS NULL AND NEW.base_version_id IS NULL THEN + INSERT INTO game_design_realm_policy_version_insert (version_id, creation_transaction_id) + VALUES (NEW.id, pg_current_xact_id()::TEXT); + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER realm_policy_version_insert_witness AFTER INSERT ON version + FOR EACH ROW EXECUTE FUNCTION witness_realm_policy_version_insert(); + +CREATE FUNCTION guard_realm_policy_genesis() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; witness game_design_realm_policy_version_insert%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'new-Draft insertion and genesis evidence is immutable' USING ERRCODE = 'check_violation'; + END IF; + IF TG_TABLE_NAME = 'game_design_realm_policy_version_insert' THEN + IF pg_trigger_depth() < 2 OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT THEN + RAISE EXCEPTION 'new-Draft witness requires the actual Version insertion trigger' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT owner_version FROM version WHERE id = NEW.version_id FOR UPDATE; + SELECT * INTO STRICT witness FROM game_design_realm_policy_version_insert WHERE version_id = NEW.version_id; + IF witness.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NEW.creation_transaction_id <> witness.creation_transaction_id + OR NEW.canonical_tenant_id <> owner_version.canonical_tenant_id + OR NEW.canonical_version_id <> owner_version.canonical_version_id + OR owner_version.version_state <> 'DRAFT' OR owner_version.is_script_only + OR owner_version.script_patch_version IS NOT NULL OR owner_version.base_version_id IS NOT NULL + OR EXISTS (SELECT 1 FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id) + OR NEW.receipt_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-realm-policy-genesis/v1' + OR NEW.receipt_json::JSONB->>'receiptId' IS DISTINCT FROM NEW.receipt_id::TEXT + OR NEW.receipt_json::JSONB->>'creationTransactionId' IS DISTINCT FROM witness.creation_transaction_id + OR NEW.receipt_json::JSONB->>'canonicalTenantId' IS DISTINCT FROM owner_version.canonical_tenant_id::TEXT + OR NEW.receipt_json::JSONB->>'canonicalVersionId' IS DISTINCT FROM owner_version.canonical_version_id::TEXT + OR NEW.receipt_json::JSONB->>'gameDesignVersionRowId' IS DISTINCT FROM owner_version.id::TEXT + OR NEW.receipt_json::JSONB->>'gameDesignVersionTenantKey' IS DISTINCT FROM owner_version.tenant_id + OR NEW.receipt_json::JSONB->>'sourceGameRowId' IS DISTINCT FROM owner_version.identity_source_game_row_id::TEXT + OR NEW.receipt_json::JSONB->>'sourceGameTenantKey' IS DISTINCT FROM owner_version.identity_source_game_tenant_key + OR NEW.receipt_json::JSONB->>'sourceProvenanceKind' IS DISTINCT FROM owner_version.identity_source_provenance_kind THEN + RAISE EXCEPTION 'realm policy genesis lacks the exact fresh owner insertion' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER realm_policy_version_insert_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_version_insert + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_genesis(); +CREATE TRIGGER realm_policy_genesis_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_genesis + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_genesis(); + +CREATE FUNCTION guard_realm_policy_source_write() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; operation game_design_publication_operation%ROWTYPE; + snapshot game_design_realm_policy_snapshot%ROWTYPE; selection game_design_authored_draft_publish_selection%ROWTYPE; + expected BYTEA; payload BYTEA; policies JSONB; source_binding game_design_draft_commit%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'realm policy source history cannot be deleted' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT owner_version FROM version + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF owner_version.version_state <> 'DRAFT' OR owner_version.is_script_only + OR owner_version.script_patch_version IS NOT NULL OR owner_version.base_version_id IS NOT NULL THEN + RAISE EXCEPTION 'realm policy source requires canonical full Draft owner' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF TG_TABLE_NAME = 'game_design_realm_policy_application' THEN + IF OLD.owner_result_bytes IS NOT NULL OR NEW.owner_result_bytes IS NULL + OR (to_jsonb(NEW) - 'owner_result_bytes') IS DISTINCT FROM (to_jsonb(OLD) - 'owner_result_bytes') THEN + RAISE EXCEPTION 'realm policy application permits only its one atomic complete owner result' USING ERRCODE = 'check_violation'; + END IF; + ELSIF TG_TABLE_NAME <> 'game_design_realm_policy_source' THEN + RAISE EXCEPTION 'realm policy history is immutable' USING ERRCODE = 'check_violation'; + ELSIF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.genesis_receipt_id IS DISTINCT FROM OLD.genesis_receipt_id THEN + RAISE EXCEPTION 'realm policy history is immutable' USING ERRCODE = 'check_violation'; + END IF; + END IF; + IF EXISTS (SELECT 1 FROM game_design_realm_policy_capture WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'realm policy source is frozen' USING ERRCODE = 'check_violation'; + END IF; + IF TG_TABLE_NAME = 'game_design_realm_policy_source' THEN + IF TG_OP = 'INSERT' AND NEW.genesis_receipt_id IS NOT NULL THEN + IF NEW.source_epoch <> '0' OR NEW.visible_commit_id IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_genesis g WHERE g.receipt_id = NEW.genesis_receipt_id + AND g.canonical_tenant_id = NEW.canonical_tenant_id AND g.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'genesis source must begin empty at its exact owner epoch zero' USING ERRCODE = 'check_violation'; + END IF; + END IF; + END IF; + IF TG_TABLE_NAME IN ('game_design_realm_policy_snapshot', 'game_design_realm_policy_application') THEN + SELECT * INTO STRICT source_binding FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + policies := NEW.snapshot_json::JSONB->'policies'; + IF NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM source_binding.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM source_binding.input_digest + OR jsonb_typeof(policies) IS DISTINCT FROM 'array' + OR jsonb_array_length(policies) NOT BETWEEN 0 AND 128 + OR (SELECT count(DISTINCT p->'policy'->>'realmSlug') FROM jsonb_array_elements(policies) p) <> jsonb_array_length(policies) THEN + RAISE EXCEPTION 'realm policy snapshot lacks exact source binding or unique bounded selectors' USING ERRCODE = 'check_violation'; + END IF; + END IF; + IF TG_TABLE_NAME = 'game_design_realm_policy_capture' THEN + SELECT * INTO STRICT operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selection FROM game_design_authored_draft_publish_selection + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + policies := snapshot.snapshot_json::JSONB->'policies'; + IF jsonb_array_length(policies) NOT BETWEEN 1 AND 128 + OR (SELECT count(*) FROM jsonb_array_elements(policies) p WHERE p->'policy'->'visible' = 'true'::JSONB + AND p->'policy'->'publicProduction' = 'true'::JSONB) <> 1 + OR operation.outcome <> 'PENDING' OR operation.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR operation.version_id <> owner_version.id OR operation.tenant_id <> owner_version.tenant_id + OR operation.selection_digest <> selection.selection_digest OR selection.selected_commit_id <> NEW.commit_id + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_source s WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id AND s.visible_commit_id = NEW.commit_id + AND s.source_epoch = snapshot.snapshot_json::JSONB->>'sourceEpoch') + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility v WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id AND v.commit_id = NEW.commit_id) THEN + RAISE EXCEPTION 'realm policy capture differs from original synchronized publication' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to('game-design-realm-policy-source-capture/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload + || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + payload := convert_to(snapshot.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF expected IS DISTINCT FROM NEW.capture_bytes THEN + RAISE EXCEPTION 'realm policy capture bytes differ from immutable source' USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER realm_policy_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); +CREATE TRIGGER realm_policy_source_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_source + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); +CREATE TRIGGER realm_policy_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_application + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); +CREATE TRIGGER realm_policy_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_realm_policy_capture + FOR EACH ROW EXECUTE FUNCTION guard_realm_policy_source_write(); + +CREATE FUNCTION verify_realm_policy_application_commit() RETURNS trigger AS $$ +DECLARE binding game_design_draft_commit%ROWTYPE; result game_design_draft_commit_owner_result%ROWTYPE; + expected BYTEA; payload BYTEA; application game_design_realm_policy_application%ROWTYPE; genesis game_design_realm_policy_genesis%ROWTYPE; +BEGIN + SELECT * INTO STRICT application FROM game_design_realm_policy_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT binding FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT result FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + payload := convert_to('game-design-realm-policy-application/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload; + payload := convert_to(CASE WHEN NEW.genesis_receipt_id IS NULL THEN 'false' ELSE 'true' END, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := ''::BYTEA; + IF NEW.genesis_receipt_id IS NOT NULL THEN + SELECT * INTO STRICT genesis FROM game_design_realm_policy_genesis WHERE receipt_id = NEW.genesis_receipt_id; + IF genesis.canonical_tenant_id <> NEW.canonical_tenant_id OR genesis.canonical_version_id <> NEW.canonical_version_id THEN + RAISE EXCEPTION 'policy application changed genesis target' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to(genesis.receipt_json, 'UTF8'); + END IF; + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(CASE WHEN NEW.inherited_commit_id IS NULL THEN 'false' ELSE 'true' END, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(COALESCE(NEW.inherited_commit_id::TEXT, ''), 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.expected_epoch, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF result.status <> 'APPLIED' OR application.owner_result_bytes IS NULL + OR result.result_bytes IS DISTINCT FROM application.owner_result_bytes OR NEW.result_bytes IS DISTINCT FROM expected + OR result.result_commit_id <> NEW.commit_id OR result.result_binding_digest <> binding.input_digest + OR NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM binding.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM binding.input_digest + OR (NEW.snapshot_json::JSONB->>'sourceEpoch')::NUMERIC <> NEW.expected_epoch::NUMERIC + 1 THEN + RAISE EXCEPTION 'realm policy application lacks atomic exact coordinator result' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER realm_policy_application_commit_guard AFTER INSERT ON game_design_realm_policy_application + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_realm_policy_application_commit(); + +CREATE FUNCTION deny_realm_policy_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'realm policy owner evidence cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER realm_policy_snapshot_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_snapshot + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_source_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_source + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_application_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_application + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_capture_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_capture + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_version_insert_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_version_insert + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +CREATE TRIGGER realm_policy_genesis_no_truncate BEFORE TRUNCATE ON game_design_realm_policy_genesis + FOR EACH STATEMENT EXECUTE FUNCTION deny_realm_policy_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V53__sealed_realm_policy_publication_evidence.sql b/services/game-design-service/src/main/resources/db/migration/V53__sealed_realm_policy_publication_evidence.sql new file mode 100644 index 0000000000..80a635e3f7 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V53__sealed_realm_policy_publication_evidence.sql @@ -0,0 +1,278 @@ +CREATE TABLE game_design_published_realm_policy_set ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL CHECK (game_design_version_row_id > 0), + version_number INTEGER NOT NULL CHECK (version_number > 0), + source_commit_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + target_proof_json TEXT NOT NULL, + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + capture_bytes BYTEA NOT NULL CHECK (octet_length(capture_bytes) > 0), + terminal_evidence_bytes BYTEA NOT NULL CHECK (octet_length(terminal_evidence_bytes) > 0), + release_content_bytes BYTEA NOT NULL CHECK (octet_length(release_content_bytes) > 0), + published_release_bundle_ref VARCHAR(1024) NOT NULL CHECK (char_length(published_release_bundle_ref) > 0), + published_release_bundle_digest VARCHAR(71) NOT NULL CHECK (published_release_bundle_digest ~ '^sha256:[0-9a-f]{64}$'), + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE, + manifest_hash VARCHAR(71) NOT NULL CHECK (manifest_hash ~ '^sha256:[0-9a-f]{64}$'), + publication_version_state_epoch BIGINT NOT NULL CHECK (publication_version_state_epoch > 0), + policy_count INTEGER NOT NULL CHECK (policy_count BETWEEN 1 AND 128), + policy_set_digest VARCHAR(71) NOT NULL CHECK (policy_set_digest ~ '^sha256:[0-9a-f]{64}$'), + sealed BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, source_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_realm_policy_capture (canonical_tenant_id, canonical_version_id) +); + +CREATE TABLE game_design_published_realm_policy ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + ordinal INTEGER NOT NULL CHECK (ordinal BETWEEN 0 AND 127), + realm_policy_id UUID NOT NULL UNIQUE, + source_commit_id UUID NOT NULL, + source_revision_id UUID NOT NULL, + logical_revision_id VARCHAR(128) NOT NULL CHECK (char_length(logical_revision_id) BETWEEN 1 AND 128), + world_slug VARCHAR(64) NOT NULL, + realm_slug VARCHAR(64) NOT NULL, + policy_json TEXT NOT NULL CHECK (char_length(policy_json) BETWEEN 2 AND 4096), + policy_digest VARCHAR(71) NOT NULL CHECK (policy_digest ~ '^sha256:[0-9a-f]{64}$'), + visible BOOLEAN NOT NULL, + public_production BOOLEAN NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, realm_policy_id), + UNIQUE (canonical_tenant_id, canonical_version_id, ordinal), + UNIQUE (canonical_tenant_id, canonical_version_id, world_slug, realm_slug), + UNIQUE (canonical_tenant_id, canonical_version_id, realm_slug), + UNIQUE (canonical_tenant_id, canonical_version_id, source_revision_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_published_realm_policy_set (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, source_commit_id) + REFERENCES game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_published_realm_policy_set() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; owner_game game%ROWTYPE; + operation game_design_publication_operation%ROWTYPE; + capture game_design_realm_policy_capture%ROWTYPE; + snapshot game_design_realm_policy_snapshot%ROWTYPE; + release published_release_bundle%ROWTYPE; + row_count BIGINT; realm_count BIGINT; production_count BIGINT; target_proof_key_count BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'published realm policy set is immutable' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF OLD.sealed IS DISTINCT FROM FALSE OR NEW.sealed IS DISTINCT FROM TRUE + OR (to_jsonb(NEW) - 'sealed') IS DISTINCT FROM (to_jsonb(OLD) - 'sealed') THEN + RAISE EXCEPTION 'published realm policy set may only be sealed once' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.source_commit_id; + SELECT count(*), count(DISTINCT realm_slug), + count(*) FILTER (WHERE visible AND public_production) + INTO row_count, realm_count, production_count + FROM game_design_published_realm_policy + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + IF row_count <> NEW.policy_count + OR row_count <> jsonb_array_length(snapshot.snapshot_json::JSONB->'policies') + OR realm_count <> row_count OR production_count <> 1 + OR NEW.policy_set_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'published realm policy set is incomplete or has invalid cardinality' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.sealed IS DISTINCT FROM FALSE + OR jsonb_typeof(NEW.target_proof_json::JSONB) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'published realm policy set requires a closed complete TargetProof' USING ERRCODE = 'check_violation'; + END IF; + SELECT count(*) INTO target_proof_key_count + FROM jsonb_object_keys(NEW.target_proof_json::JSONB); + IF target_proof_key_count <> 7 + OR (NEW.target_proof_json::JSONB - ARRAY['canonicalTenantId', 'canonicalVersionId', 'gameDesignVersionRowId', + 'gameDesignVersionTenantKey', 'sourceGameRowId', 'sourceGameTenantKey', 'sourceProvenanceKind']) + IS DISTINCT FROM '{}'::JSONB + OR jsonb_typeof(NEW.target_proof_json::JSONB->'canonicalTenantId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'canonicalVersionId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'gameDesignVersionRowId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'gameDesignVersionTenantKey') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceGameRowId') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceGameTenantKey') IS DISTINCT FROM 'string' + OR jsonb_typeof(NEW.target_proof_json::JSONB->'sourceProvenanceKind') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'published realm policy set requires a closed complete TargetProof' USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.* INTO owner_version FROM version v JOIN game g + ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.id = NEW.game_design_version_row_id + AND v.tenant_id = NEW.target_proof_json::JSONB->>'gameDesignVersionTenantKey' + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id::TEXT = NEW.target_proof_json::JSONB->>'sourceGameRowId' + AND v.identity_source_game_tenant_key = NEW.target_proof_json::JSONB->>'sourceGameTenantKey' + AND v.identity_source_provenance_kind = NEW.target_proof_json::JSONB->>'sourceProvenanceKind'; + IF NOT FOUND OR owner_version.id IS DISTINCT FROM NEW.game_design_version_row_id + OR owner_version.version_state IS DISTINCT FROM 'PUBLISHED' + OR owner_version.version_state_epoch IS DISTINCT FROM NEW.publication_version_state_epoch + OR owner_version.version_number IS DISTINCT FROM NEW.version_number + OR owner_version.is_script_only IS DISTINCT FROM FALSE + OR owner_version.script_patch_version IS NOT NULL + OR owner_version.base_version_id IS NOT NULL + OR NEW.target_proof_json::JSONB->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR NEW.target_proof_json::JSONB->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR NEW.target_proof_json::JSONB->>'gameDesignVersionRowId' IS DISTINCT FROM owner_version.id::TEXT + OR NEW.target_proof_json::JSONB->>'gameDesignVersionTenantKey' IS DISTINCT FROM owner_version.tenant_id + OR NEW.target_proof_json::JSONB->>'sourceGameRowId' IS DISTINCT FROM owner_version.identity_source_game_row_id::TEXT + OR NEW.target_proof_json::JSONB->>'sourceGameTenantKey' IS DISTINCT FROM owner_version.identity_source_game_tenant_key + OR NEW.target_proof_json::JSONB->>'sourceProvenanceKind' IS DISTINCT FROM owner_version.identity_source_provenance_kind THEN + RAISE EXCEPTION 'published realm policy set differs from exact full Version owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT g.* INTO STRICT owner_game FROM game g WHERE g.id = owner_version.identity_source_game_row_id; + IF owner_game.id::TEXT IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceGameRowId' + OR owner_game.tenant_id IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceGameTenantKey' + OR owner_game.tenant_identity_provenance_kind IS DISTINCT FROM NEW.target_proof_json::JSONB->>'sourceProvenanceKind' + OR owner_game.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id THEN + RAISE EXCEPTION 'published realm policy set source provenance changed' USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO operation FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set operation is unavailable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO capture FROM game_design_realm_policy_capture + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set source capture is unavailable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.source_commit_id; + SELECT * INTO release FROM published_release_bundle + WHERE tenant_id = owner_version.tenant_id AND version_id = owner_version.id; + IF NOT FOUND THEN + RAISE EXCEPTION 'published realm policy set release bundle is unavailable' USING ERRCODE = 'check_violation'; + END IF; + IF operation.outcome IS DISTINCT FROM 'PUBLISHED' + OR operation.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR operation.terminal_evidence_bytes IS DISTINCT FROM NEW.terminal_evidence_bytes + OR operation.release_content_bytes IS DISTINCT FROM NEW.release_content_bytes + OR operation.published_release_bundle_digest IS DISTINCT FROM NEW.published_release_bundle_digest + OR operation.publication_version_state_epoch IS DISTINCT FROM NEW.publication_version_state_epoch + OR operation.tenant_id IS DISTINCT FROM owner_version.tenant_id + OR operation.version_id IS DISTINCT FROM owner_version.id + OR operation.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.operation_bytes IS DISTINCT FROM NEW.operation_bytes + OR capture.capture_bytes IS DISTINCT FROM NEW.capture_bytes + OR capture.commit_id IS DISTINCT FROM NEW.source_commit_id + OR snapshot.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR publication_release_content(release) IS DISTINCT FROM NEW.release_content_bytes + OR 'sha256:' || encode(sha256(publication_release_content(release)), 'hex') + IS DISTINCT FROM NEW.published_release_bundle_digest + OR release.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR release.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR release.version_number IS DISTINCT FROM NEW.version_number + OR release.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR release.manifest_hash IS DISTINCT FROM NEW.manifest_hash + OR to_jsonb(release)::TEXT IS DISTINCT FROM operation.release_row_json + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_source s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.visible_commit_id = NEW.source_commit_id AND s.source_epoch = NEW.source_epoch) + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility v + WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.commit_id = NEW.source_commit_id) + OR jsonb_array_length(snapshot.snapshot_json::JSONB->'policies') <> NEW.policy_count THEN + RAISE EXCEPTION 'published realm policy set is not bound to exact sealed operation, capture, source, and release' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER published_realm_policy_set_guard BEFORE INSERT OR UPDATE OR DELETE + ON game_design_published_realm_policy_set FOR EACH ROW EXECUTE FUNCTION guard_published_realm_policy_set(); + +CREATE FUNCTION guard_published_realm_policy_row() RETURNS trigger AS $$ +DECLARE set_row game_design_published_realm_policy_set%ROWTYPE; + snapshot game_design_realm_policy_snapshot%ROWTYPE; + matching JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'published realm policy rows are immutable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO set_row FROM game_design_published_realm_policy_set + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF NOT FOUND OR set_row.sealed THEN + RAISE EXCEPTION 'published realm policy row requires its open atomic set' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT snapshot FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = set_row.source_commit_id; + SELECT p INTO matching FROM jsonb_array_elements(snapshot.snapshot_json::JSONB->'policies') + WITH ORDINALITY AS entries(p, source_ordinal) + WHERE source_ordinal = NEW.ordinal + 1 + AND p->>'commitId' = NEW.source_commit_id::TEXT + AND p->>'revisionId' = NEW.source_revision_id::TEXT + AND p->>'logicalRevisionId' = NEW.logical_revision_id + AND p->'policy' = NEW.policy_json::JSONB; + IF matching IS NULL + OR NEW.world_slug IS DISTINCT FROM matching->'policy'->>'worldSlug' + OR NEW.realm_slug IS DISTINCT FROM matching->'policy'->>'realmSlug' + OR NEW.visible IS DISTINCT FROM (matching->'policy'->>'visible')::BOOLEAN + OR NEW.public_production IS DISTINCT FROM (matching->'policy'->>'publicProduction')::BOOLEAN + OR jsonb_typeof(NEW.policy_json::JSONB) IS DISTINCT FROM 'object' + OR NEW.policy_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'published realm policy row differs from exact captured source revision' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER published_realm_policy_row_guard BEFORE INSERT OR UPDATE OR DELETE + ON game_design_published_realm_policy FOR EACH ROW EXECUTE FUNCTION guard_published_realm_policy_row(); + +CREATE FUNCTION verify_published_realm_policy_set_commit() RETURNS trigger AS $$ +DECLARE set_row game_design_published_realm_policy_set%ROWTYPE; row_count BIGINT; + realm_count BIGINT; production_count BIGINT; +BEGIN + SELECT * INTO STRICT set_row FROM game_design_published_realm_policy_set + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*), count(DISTINCT realm_slug), + count(*) FILTER (WHERE visible AND public_production) + INTO row_count, realm_count, production_count + FROM game_design_published_realm_policy + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF NOT set_row.sealed OR row_count <> set_row.policy_count OR realm_count <> row_count + OR production_count <> 1 OR row_count NOT BETWEEN 1 AND 128 THEN + RAISE EXCEPTION 'published realm policy set did not commit as one complete canonical set' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE CONSTRAINT TRIGGER published_realm_policy_set_commit_guard + AFTER INSERT OR UPDATE ON game_design_published_realm_policy_set + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_published_realm_policy_set_commit(); + +CREATE FUNCTION deny_published_realm_policy_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'published realm policy evidence cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER published_realm_policy_set_no_truncate BEFORE TRUNCATE + ON game_design_published_realm_policy_set FOR EACH STATEMENT EXECUTE FUNCTION deny_published_realm_policy_truncate(); +CREATE TRIGGER published_realm_policy_no_truncate BEFORE TRUNCATE + ON game_design_published_realm_policy FOR EACH STATEMENT EXECUTE FUNCTION deny_published_realm_policy_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql b/services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql new file mode 100644 index 0000000000..c2c62ae98b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql @@ -0,0 +1,480 @@ +CREATE TABLE game_design_command_source_baseline ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_row_id BIGINT NOT NULL, + baseline_kind VARCHAR(32) NOT NULL, + receipt_id UUID NOT NULL, + creation_transaction_id TEXT NOT NULL, + target_proof_json TEXT NOT NULL, + receipt_bytes BYTEA NOT NULL CHECK (octet_length(receipt_bytes) > 0), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + UNIQUE (receipt_id), + UNIQUE (game_design_version_row_id), + FOREIGN KEY (game_design_version_row_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + FOREIGN KEY (game_design_version_row_id) + REFERENCES game_design_realm_policy_version_insert (version_id) ON DELETE RESTRICT, + CHECK (baseline_kind = 'NEW_DRAFT_EMPTY'), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); + +CREATE TABLE game_design_command_source_snapshot ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + binding_json TEXT NOT NULL, + inherited_commit_id UUID, + baseline_digest VARCHAR(71) NOT NULL CHECK (baseline_digest ~ '^sha256:[0-9a-f]{64}$'), + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + snapshot_json TEXT NOT NULL, + snapshot_digest VARCHAR(71) NOT NULL CHECK (snapshot_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit_visibility_fence + (canonical_tenant_id, canonical_version_id, request_id, commit_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +CREATE TABLE game_design_command_source_application ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + request_id UUID NOT NULL, + input_digest VARCHAR(71) NOT NULL CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + binding_json TEXT NOT NULL, + inherited_commit_id UUID, + baseline_digest VARCHAR(71) NOT NULL CHECK (baseline_digest ~ '^sha256:[0-9a-f]{64}$'), + expected_epoch TEXT NOT NULL CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), + snapshot_json TEXT NOT NULL, + operations_json TEXT NOT NULL, + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit + (canonical_tenant_id, canonical_version_id, request_id, commit_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, inherited_commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +CREATE TABLE game_design_command_source_operation ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), + revision_id UUID NOT NULL, + operation_kind VARCHAR(16) NOT NULL CHECK (operation_kind IN ('UPSERT', 'DELETE')), + command_id TEXT NOT NULL CHECK (char_length(command_id) > 0), + command_key TEXT NOT NULL CHECK (char_length(command_key) > 0), + definition_json TEXT, + operation_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + UNIQUE (canonical_tenant_id, canonical_version_id, revision_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_command_source_application + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT, + CHECK (revision_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK ((operation_kind = 'UPSERT' AND definition_json IS NOT NULL) + OR (operation_kind = 'DELETE' AND definition_json IS NULL)) +); + +CREATE TABLE game_design_command_source_head ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + visible_commit_id UUID, + applied_commit_id UUID, + baseline_digest VARCHAR(71) NOT NULL CHECK (baseline_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_command_source_baseline (canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, applied_commit_id) + REFERENCES game_design_command_source_application + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +CREATE TABLE game_design_command_source_capture ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE + REFERENCES game_design_publication_operation (publish_workflow_id) ON DELETE RESTRICT, + commit_id UUID NOT NULL, + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + capture_bytes BYTEA NOT NULL CHECK (octet_length(capture_bytes) > 0), + capture_digest VARCHAR(71) NOT NULL CHECK (capture_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_command_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT +); + +-- [jooq ignore start] +ALTER TABLE game_design_command_source_application + ADD CONSTRAINT command_source_application_json_shape CHECK ( + jsonb_typeof(snapshot_json::JSONB) = 'object' + AND jsonb_typeof(operations_json::JSONB) = 'array' + AND jsonb_array_length(operations_json::JSONB) > 0); +ALTER TABLE game_design_command_source_operation + ADD CONSTRAINT command_source_operation_json_shape CHECK ( + jsonb_typeof(operation_json::JSONB) = 'object'); + +CREATE FUNCTION guard_command_source_write() RETURNS trigger AS $$ +DECLARE owner_version version%ROWTYPE; binding game_design_draft_commit%ROWTYPE; + witness game_design_realm_policy_version_insert%ROWTYPE; source_head game_design_command_source_head%ROWTYPE; + owner_result game_design_draft_commit_owner_result%ROWTYPE; selection game_design_authored_draft_publish_selection%ROWTYPE; + operation game_design_publication_operation%ROWTYPE; snapshot game_design_command_source_snapshot%ROWTYPE; + expected BYTEA; payload BYTEA; receipt JSONB; proof JSONB; stored_operation JSONB; revision_payload JSONB; + revision_payload_text TEXT; declared_command_count BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'command source evidence cannot be deleted' USING ERRCODE = 'check_violation'; + END IF; + + SELECT v.* INTO STRICT owner_version FROM version v JOIN game g + ON g.id = v.identity_source_game_row_id AND g.tenant_id = v.identity_source_game_tenant_key + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF v; + IF owner_version.version_state <> 'DRAFT' OR owner_version.is_script_only + OR owner_version.script_patch_version IS NOT NULL OR owner_version.base_version_id IS NOT NULL THEN + RAISE EXCEPTION 'command source requires canonical full Draft owner' USING ERRCODE = 'check_violation'; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_baseline' THEN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'command source baseline is immutable' USING ERRCODE = 'check_violation'; + END IF; + SELECT * INTO STRICT witness FROM game_design_realm_policy_version_insert + WHERE version_id = NEW.game_design_version_row_id; + proof := NEW.target_proof_json::JSONB; + receipt := convert_from(NEW.receipt_bytes, 'UTF8')::JSONB; + IF NEW.baseline_kind <> 'NEW_DRAFT_EMPTY' OR owner_version.id <> NEW.game_design_version_row_id + OR owner_version.version_state_epoch <> 1 OR witness.creation_transaction_id <> NEW.creation_transaction_id + OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') + OR proof->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR proof->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR proof->>'gameDesignVersionRowId' IS DISTINCT FROM owner_version.id::TEXT + OR proof->>'gameDesignVersionTenantKey' IS DISTINCT FROM owner_version.tenant_id + OR proof->>'sourceGameRowId' IS DISTINCT FROM owner_version.identity_source_game_row_id::TEXT + OR proof->>'sourceGameTenantKey' IS DISTINCT FROM owner_version.identity_source_game_tenant_key + OR proof->>'sourceProvenanceKind' IS DISTINCT FROM owner_version.identity_source_provenance_kind + OR jsonb_typeof(proof) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(proof)) <> 7 + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 4 + OR receipt->>'schema' IS DISTINCT FROM 'game-design-command-source-new-draft-genesis/v1' + OR receipt->'targetProof' IS DISTINCT FROM proof + OR receipt->>'receiptId' IS DISTINCT FROM NEW.receipt_id::TEXT + OR receipt->>'creationTransactionId' IS DISTINCT FROM NEW.creation_transaction_id THEN + RAISE EXCEPTION 'command source baseline lacks exact fresh Version insertion evidence' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_head' THEN + IF TG_OP = 'INSERT' THEN + IF NEW.source_epoch <> '0' OR NEW.visible_commit_id IS NOT NULL OR NEW.applied_commit_id IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM game_design_command_source_baseline b + WHERE b.canonical_tenant_id = NEW.canonical_tenant_id + AND b.canonical_version_id = NEW.canonical_version_id + AND b.receipt_digest = NEW.baseline_digest) THEN + RAISE EXCEPTION 'command source head must start at its exact empty Draft baseline' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.baseline_digest IS DISTINCT FROM OLD.baseline_digest + OR EXISTS (SELECT 1 FROM game_design_command_source_capture c + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id AND c.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id AND s.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'command source head is frozen or its identity changed' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id + OR NEW.applied_commit_id IS NULL OR NEW.applied_commit_id IS NOT DISTINCT FROM OLD.applied_commit_id + OR NOT EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.applied_commit_id + AND a.expected_epoch = OLD.source_epoch) THEN + RAISE EXCEPTION 'command source staged epoch must advance by its exact application' USING ERRCODE = 'check_violation'; + END IF; + ELSIF NEW.applied_commit_id IS DISTINCT FROM OLD.applied_commit_id THEN + RAISE EXCEPTION 'command source applied pointer changes only with an epoch advance' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + SELECT * INTO STRICT snapshot FROM game_design_command_source_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.visible_commit_id; + IF snapshot.inherited_commit_id IS DISTINCT FROM OLD.visible_commit_id + OR snapshot.source_epoch IS DISTINCT FROM NEW.source_epoch + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility_fence f + JOIN game_design_draft_commit_visibility v USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + JOIN game_design_draft_commit c USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = snapshot.request_id AND f.commit_id = snapshot.commit_id + AND f.input_digest = snapshot.input_digest AND c.workflow_state = 'SYNCHRONIZED' + AND v.request_id = f.request_id AND v.commit_id = f.commit_id AND v.input_digest = f.input_digest) THEN + RAISE EXCEPTION 'command source visibility must advance to the exact synchronized coordinator fence' USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; + END IF; + + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'command source history is immutable' USING ERRCODE = 'check_violation'; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_application' + OR TG_TABLE_NAME = 'game_design_command_source_snapshot' THEN + SELECT * INTO STRICT binding FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF binding.binding_json IS DISTINCT FROM NEW.binding_json OR binding.input_digest IS DISTINCT FROM NEW.input_digest THEN + RAISE EXCEPTION 'command source differs from exact Draft binding' USING ERRCODE = 'check_violation'; + END IF; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_application' THEN + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF source_head.source_epoch IS DISTINCT FROM NEW.expected_epoch + OR source_head.visible_commit_id IS DISTINCT FROM NEW.inherited_commit_id + OR source_head.baseline_digest IS DISTINCT FROM NEW.baseline_digest + OR EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id AND s.canonical_version_id = NEW.canonical_version_id) + OR NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-command-source-snapshot/v1' + OR NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM NEW.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM NEW.input_digest + OR NEW.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM (NEW.expected_epoch::NUMERIC + 1)::TEXT + OR NEW.snapshot_json::JSONB->>'genesisReceiptDigest' IS DISTINCT FROM NEW.baseline_digest + OR NEW.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(NEW.inherited_commit_id::TEXT, '') + OR jsonb_typeof(NEW.snapshot_json::JSONB->'definitions') IS DISTINCT FROM 'array' + OR jsonb_typeof(NEW.operations_json::JSONB) IS DISTINCT FROM 'array' + OR jsonb_array_length(NEW.operations_json::JSONB) = 0 THEN + RAISE EXCEPTION 'command application must bind exact predecessor, baseline, epoch, and complete set' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_operation' THEN + SELECT * INTO STRICT binding FROM game_design_draft_commit c + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id AND c.canonical_version_id = NEW.canonical_version_id + AND c.commit_id = NEW.commit_id AND EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = c.canonical_tenant_id AND a.canonical_version_id = c.canonical_version_id + AND a.commit_id = c.commit_id); + SELECT rev->>'payload' INTO STRICT revision_payload_text FROM jsonb_array_elements(binding.binding_json::JSONB->'revisions') rev + WHERE rev->>'revisionOrder' = NEW.revision_order::TEXT AND rev->>'revisionId' = NEW.revision_id::TEXT + AND rev->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + revision_payload := revision_payload_text::JSONB; + stored_operation := NEW.operation_json::JSONB; + IF revision_payload->>'revisionKind' IS DISTINCT FROM 'COMMAND_DEFINITION' + OR revision_payload->>'schemaVersion' IS DISTINCT FROM '1' + OR (SELECT count(*) FROM jsonb_object_keys(revision_payload)) <> 4 + OR revision_payload->>'operation' IS DISTINCT FROM NEW.operation_kind + OR (SELECT count(*) FROM jsonb_object_keys(stored_operation)) + <> CASE WHEN NEW.operation_kind = 'UPSERT' THEN 6 ELSE 5 END + OR stored_operation->>'revisionOrder' IS DISTINCT FROM NEW.revision_order::TEXT + OR stored_operation->>'revisionId' IS DISTINCT FROM NEW.revision_id::TEXT + OR stored_operation->>'commitId' IS DISTINCT FROM NEW.commit_id::TEXT + OR stored_operation->>'operation' IS DISTINCT FROM NEW.operation_kind + OR stored_operation->>'commandId' IS DISTINCT FROM NEW.command_id THEN + RAISE EXCEPTION 'command operation must retain its exact authored revision identity' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.operation_kind = 'UPSERT' THEN + IF revision_payload->>'definitionJson' IS DISTINCT FROM NEW.definition_json + OR revision_payload->>'definitionJson' IS DISTINCT FROM stored_operation->>'definitionJson' + OR NEW.definition_json::JSONB->>'commandId' IS DISTINCT FROM NEW.command_id THEN + RAISE EXCEPTION 'command upsert definition differs from digest-bound authored payload' USING ERRCODE = 'check_violation'; + END IF; + ELSIF revision_payload->>'commandId' IS DISTINCT FROM NEW.command_id + OR revision_payload ? 'definitionJson' OR stored_operation ? 'definitionJson' THEN + RAISE EXCEPTION 'command delete must retain explicit identity without inferred absence' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_snapshot' THEN + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + SELECT count(*) INTO declared_command_count FROM jsonb_array_elements(binding.binding_json::JSONB->'revisions') revision + WHERE CASE WHEN revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + THEN (revision->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION' ELSE FALSE END; + IF (declared_command_count > 0) IS DISTINCT FROM (EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.commit_id)) THEN + RAISE EXCEPTION 'command-bearing synchronized commit requires its exact staged command application' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-command-source-snapshot/v1' + OR NEW.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM NEW.binding_json + OR NEW.snapshot_json::JSONB->>'bindingDigest' IS DISTINCT FROM NEW.input_digest + OR NEW.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR NEW.snapshot_json::JSONB->>'genesisReceiptDigest' IS DISTINCT FROM NEW.baseline_digest + OR NEW.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(NEW.inherited_commit_id::TEXT, '') + OR jsonb_typeof(NEW.snapshot_json::JSONB->'definitions') IS DISTINCT FROM 'array' + OR source_head.visible_commit_id IS DISTINCT FROM NEW.inherited_commit_id + OR source_head.baseline_digest IS DISTINCT FROM NEW.baseline_digest + OR source_head.source_epoch IS DISTINCT FROM NEW.source_epoch + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility_fence f + JOIN game_design_draft_commit_visibility v USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + JOIN game_design_draft_commit c USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.request_id AND f.commit_id = NEW.commit_id + AND f.input_digest = NEW.input_digest AND v.request_id = f.request_id + AND v.commit_id = f.commit_id AND v.input_digest = f.input_digest AND c.workflow_state = 'SYNCHRONIZED') THEN + RAISE EXCEPTION 'command snapshot must retain complete source at exact synchronized fence' USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.commit_id AND a.snapshot_json IS DISTINCT FROM NEW.snapshot_json) THEN + RAISE EXCEPTION 'command snapshot differs from exact staged application' USING ERRCODE = 'check_violation'; + END IF; + IF NOT EXISTS (SELECT 1 FROM game_design_command_source_application a + WHERE a.canonical_tenant_id = NEW.canonical_tenant_id AND a.canonical_version_id = NEW.canonical_version_id + AND a.commit_id = NEW.commit_id) + AND coalesce(NEW.snapshot_json::JSONB->'definitions', '[]'::JSONB) + IS DISTINCT FROM coalesce((SELECT s.snapshot_json::JSONB->'definitions' + FROM game_design_command_source_snapshot s WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id AND s.commit_id = NEW.inherited_commit_id), '[]'::JSONB) THEN + RAISE EXCEPTION 'disjoint synchronized commit must inherit exact complete command set' USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id AND s.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'command source is frozen by publication selection' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF TG_TABLE_NAME = 'game_design_command_source_capture' THEN + SELECT * INTO STRICT operation FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selection FROM game_design_authored_draft_publish_selection + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT snapshot FROM game_design_command_source_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.commit_id; + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF operation.outcome <> 'PENDING' OR operation.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR operation.version_id <> owner_version.id OR operation.tenant_id <> owner_version.tenant_id + OR operation.selection_digest <> selection.selection_digest OR selection.selected_commit_id <> NEW.commit_id + OR source_head.visible_commit_id IS DISTINCT FROM NEW.commit_id + OR source_head.source_epoch IS DISTINCT FROM snapshot.source_epoch + OR NEW.capture_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.capture_bytes), 'hex') THEN + RAISE EXCEPTION 'command capture must bind actual pending operation and exact selected synchronized source' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to('game-design-command-source-capture/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload; + expected := expected || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + payload := convert_to(snapshot.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF expected IS DISTINCT FROM NEW.capture_bytes THEN + RAISE EXCEPTION 'command capture bytes differ from immutable source and operation' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION verify_command_source_application_commit() RETURNS trigger AS $$ +DECLARE binding game_design_draft_commit%ROWTYPE; owner_result game_design_draft_commit_owner_result%ROWTYPE; + source_head game_design_command_source_head%ROWTYPE; + expected BYTEA; payload BYTEA; operation_count BIGINT; declared_count BIGINT; mutation_count BIGINT; +BEGIN + SELECT * INTO STRICT binding FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT owner_result FROM game_design_draft_commit_owner_result + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT source_head FROM game_design_command_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO operation_count FROM game_design_command_source_operation + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.commit_id; + SELECT jsonb_array_length(NEW.operations_json::JSONB) INTO declared_count; + SELECT count(*) INTO mutation_count FROM jsonb_array_elements(binding.binding_json::JSONB->'revisions') revision + WHERE CASE WHEN revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + THEN (revision->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION' ELSE FALSE END; + IF owner_result.status <> 'APPLIED' OR owner_result.result_commit_id <> NEW.commit_id + OR owner_result.result_binding_digest <> binding.input_digest OR declared_count <> operation_count + OR mutation_count <> operation_count + OR source_head.source_epoch IS DISTINCT FROM (NEW.expected_epoch::NUMERIC + 1)::TEXT + OR source_head.applied_commit_id IS DISTINCT FROM NEW.commit_id + OR owner_result.applied_units_json IS NULL + OR NOT owner_result.applied_units_json::JSONB @> jsonb_build_array(jsonb_build_object( + 'aggregateType', 'COMMAND_DEFINITION_SET', 'aggregateId', NEW.canonical_version_id::TEXT, + 'scopeType', 'COMMAND_DEFINITION_SET', 'scopeId', 'effective', + 'expectedEpoch', NEW.expected_epoch, + 'resultingEpoch', (NEW.expected_epoch::NUMERIC + 1)::TEXT)) THEN + RAISE EXCEPTION 'command application requires exact combined control-plane APPLIED owner outcome' USING ERRCODE = 'check_violation'; + END IF; + payload := convert_to('game-design-command-source-application/v1', 'UTF8'); + expected := int4send(octet_length(payload)) || payload; + payload := convert_to(coalesce(NEW.inherited_commit_id::TEXT, ''), 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.expected_epoch, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.operations_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + payload := convert_to(NEW.snapshot_json, 'UTF8'); + expected := expected || int4send(octet_length(payload)) || payload; + IF expected IS DISTINCT FROM NEW.result_bytes THEN + RAISE EXCEPTION 'command application result bytes do not encode exact mutation and effective snapshot' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER command_source_baseline_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_baseline + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_application + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_operation_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_operation + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_head_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_head + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE TRIGGER command_source_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_command_source_capture + FOR EACH ROW EXECUTE FUNCTION guard_command_source_write(); +CREATE CONSTRAINT TRIGGER command_source_application_commit_guard AFTER INSERT ON game_design_command_source_application + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_command_source_application_commit(); + +CREATE FUNCTION deny_command_source_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'command source evidence cannot be truncated' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER command_source_baseline_no_truncate BEFORE TRUNCATE ON game_design_command_source_baseline + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_snapshot_no_truncate BEFORE TRUNCATE ON game_design_command_source_snapshot + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_application_no_truncate BEFORE TRUNCATE ON game_design_command_source_application + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_operation_no_truncate BEFORE TRUNCATE ON game_design_command_source_operation + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_head_no_truncate BEFORE TRUNCATE ON game_design_command_source_head + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +CREATE TRIGGER command_source_capture_no_truncate BEFORE TRUNCATE ON game_design_command_source_capture + FOR EACH STATEMENT EXECUTE FUNCTION deny_command_source_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java new file mode 100644 index 0000000000..1bc06dd84b --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -0,0 +1,200 @@ +package net.firedevops.firemud.gamedesign.draft; + +import java.math.BigInteger; +import java.util.List; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.jooq.DSLContext; + +/** + * ISOLATED upstream authority; executes actual GD synchronized selection/attempt/operation writes. + */ +public final class IsolatedPublicationOwnerSetup { + private IsolatedPublicationOwnerSetup() {} + + /** Fixture-only visibility advance; supplied owner authority remains explicitly isolated. */ + public static void advanceIsolatedVisibility( + DSLContext dsl, + DraftCommitBinding binding, + List outcomes) { + new DraftCommitCoordinatorRepository(dsl) + .advanceVisibilityFence( + binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + } + + /** + * Caller supplies a writable READ_COMMITTED owner transaction and an actual Draft target/epoch. + */ + public static GameDesignPublicationOperation retain( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch) throws Exception { + return retain(dsl, target, draftEpoch, "ISOLATED owner transaction proof"); + } + + public static GameDesignPublicationOperation retain( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + return retain(dsl, target, draftEpoch, notes, false); + } + + /** Actual source inheritance precedes selection; only the remote owner inputs are isolated. */ + public static GameDesignPublicationOperation retainSourceBacked( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch) throws Exception { + return retain(dsl, target, draftEpoch, "ISOLATED remote owner transaction proof", true); + } + + private static GameDesignPublicationOperation retain( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + boolean captureSources) + throws Exception { + var seed = IsolatedPublicationOperationFixtures.fresh(target); + var draft = seed.account().input().selection().selectedCommit(); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + // The original Draft Account/World result is stipulated upstream fixture evidence, not a new + // GD Draft-authorization operation or live Account authority issued by this helper. + coordinator.claim(draft); + coordinator.claimApplicationSlot(draft); + var epochs = + draft.affectedUnits().stream() + .map( + unit -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + draft.commitId(), + draft.digest(), + "ISOLATED-world-applied", + seed.world().appliedResultBytes(), + epochs); + coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.WORLD_MANAGEMENT); + coordinator.recordOwnerOutcome(draft, outcome); + var proof = new DraftCommitCoordinatorRepository.CoordinatorProof(draft, List.of(outcome)); + if (captureSources) { + coordinator.advanceSourceVisibilityFence(draft, proof); + } else { + coordinator.advanceVisibilityFence(draft, proof); + } + coordinator.releaseApplicationSlot(draft); + var selection = + new AuthoredDraftPublishSelectionRepository(dsl, coordinator) + .reserve( + new AuthoredDraftPublishSelection.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + java.util.UUID.randomUUID().toString(), + Long.toString(draftEpoch), + notes, + draft.requestId(), + draft.commitId(), + draft.digest())) + .selection(); + var operation = + IsolatedPublicationOperationFixtures.forSelection( + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + seed.world()); + var attempt = new PublishAttempt(); + attempt.setTenantId(target.gameDesignVersionTenantKey()); + attempt.setPublishWorkflowId(operation.workflowId()); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(target.gameDesignVersionRowId()); + var versionRow = + dsl.fetchOne( + "SELECT version_number FROM version WHERE id = ?", target.gameDesignVersionRowId()); + if (versionRow == null) { + throw new IllegalStateException("Selected authored Version row is absent"); + } + attempt.setVersionNumber(versionRow.get(0, Integer.class)); + attempt.setRequestDigest(selection.digest()); + new PublishAttemptRepository(dsl).save(attempt); + new GameDesignPublicationOperationRepository(dsl).reserve(operation); + return operation; + } + + /** Storage fixture commit only; does not substitute for actual command finalization proof. */ + public static PublishedReleaseBundle commitStorage( + DSLContext dsl, + VersionRepository versions, + GameDesignPublicationOperation operation, + Supplier releaseWrite) { + var attempts = new PublishAttemptRepository(dsl); + var attempt = attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + if (attempt.getStatus() == PublishAttemptStatus.SUCCEEDED) { + attempts.requirePublishedOperation(attempt); + return releaseWrite.get(); + } + attempts.requirePublicationPending(attempt); + var version = + versions + .findByTenantIdAndIdForUpdate(operation.tenantKey(), operation.versionId()) + .orElseThrow(); + var snapshot = + new VersionAssetPublicationRepository(dsl) + .freezeOrReadSnapshot(operation.tenantKey(), version.getVersionNumber()); + PublishedReleaseBundle bundle = releaseWrite.get(); + if (snapshot.versionId() != operation.versionId() + || !snapshot.items().isEmpty() + || bundle.getManifestSchemaVersion() == null + || bundle.getManifestSchemaVersion() != 1 + || !"[]".equals(bundle.getArtifactDigestsJson()) + || !"[]".equals(bundle.getRequiredManifestAssetKeysJson()) + || bundle.getManifestHash() == null + || !bundle.getManifestHash().matches("sha256:[0-9a-f]{64}")) { + throw new IllegalStateException( + "Isolated publication fixture requires the exact empty asset candidate for its Version"); + } + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1)); + versions.save(version); + var artifact = new VersionAssetArtifact(); + artifact.setTenantId(operation.tenantKey()); + artifact.setVersionId(operation.versionId()); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(1); + artifact.setExportedVersionNumber(version.getVersionNumber()); + artifact.setManifestHash(bundle.getManifestHash()); + artifact.setLastWorkflowId(operation.workflowId()); + artifact.setManifestSchemaVersion(bundle.getManifestSchemaVersion()); + artifact.setArtifactDigestsJson(bundle.getArtifactDigestsJson()); + artifact.setExportedManifestAssetKeysJson(bundle.getRequiredManifestAssetKeysJson()); + String manifestDigest = bundle.getManifestHash(); + artifact.setPublishedObjectProofsJson( + "[{\"immutableObjectKey\":\"manifests/sha256/" + + manifestDigest.substring("sha256:".length()) + + "\",\"contentDigest\":\"" + + manifestDigest + + "\"}]"); + artifact.setCandidateSnapshotVersionId(snapshot.versionId()); + new VersionAssetArtifactRepository(dsl).save(artifact); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + attempts.save(attempt); + attempts.sealPublication(attempt, true); + return bundle; + } +} diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java new file mode 100644 index 0000000000..967d8e48fa --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -0,0 +1,162 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import tools.jackson.databind.ObjectMapper; + +/** + * ISOLATED stipulated upstream source/World bytes; only callers' GD owner writes are real proof. + */ +public final class IsolatedPublicationOperationFixtures { + private IsolatedPublicationOperationFixtures() {} + + /** + * A new fixture operation and freeze, never a reinterpretation of retained publication history. + */ + public static GameDesignPublicationOperation fresh(DraftCommitBinding.TargetProof target) + throws Exception { + var seed = PublishedWorldSelectorFixtures.evidence(target); + var originalDraftAccount = + DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(originalDraftAccount.gameDesignBinding(), StandardCharsets.UTF_8), + originalDraftAccount.inputDigest()); + var appliedEpochs = + draft.affectedUnits().stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + String vector = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + new ObjectMapper() + .writeValueAsString( + List.of( + Map.of( + "owner", + "WORLD_MANAGEMENT", + "status", + "APPLIED", + "commitId", + draft.commitId().toString(), + "bindingDigest", + draft.digest(), + "resultIdentity", + "ISOLATED-world-applied", + "resultBytesBase64", + Base64.getEncoder().encodeToString(seed.appliedResultBytes()), + "appliedEpochs", + appliedEpochs)))), + StandardCharsets.UTF_8); + var intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "ISOLATED-publication-request", + "5", + "ISOLATED owner transaction proof", + draft.requestId(), + draft.commitId(), + draft.digest()); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + intent, + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + vector, + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + return forSelection(selected, seed); + } + + public static GameDesignPublicationOperation forSelection( + AuthoredDraftPublishSelectionBinding selected, WorldPublishedStartLocationEvidence seed) { + var originalDraftAccount = + DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var target = selected.target(); + var intent = selected.intent(); + var draft = selected.selectedCommit(); + var account = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + originalDraftAccount.actorAccountId(), selected), + java.util.Arrays.stream(DraftAuthorizationFenceBinding.SourceKind.values()) + .map( + kind -> + new DraftAuthorizationFenceBinding.SourceEvidence( + kind, + switch (kind) { + case ACCOUNT, GLOBAL_ROLES -> + originalDraftAccount.actorAccountId().toString(); + case TENANT -> target.canonicalTenantId().toString(); + case MEMBERSHIP -> + originalDraftAccount.actorAccountId() + + "/" + + target.canonicalTenantId(); + default -> "ISOLATED-" + kind; + }, + "1", + "1", + null, + null, + ("ISOLATED-stipulated-" + kind).getBytes(StandardCharsets.UTF_8))) + .toList()); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + "test", + target.canonicalTenantId(), + target.canonicalVersionId(), + seed.request().intakeRequestId(), + UUID.randomUUID(), + intent.publishRequestId(), + selected.digest().substring(7), + Long.parseLong(intent.expectedVersionStateEpoch()), + FiremudWorkflowIds.workflowId( + "publish", + target.canonicalTenantId().toString(), + "publish-request", + intent.publishRequestId()), + draft.commitId().toString(), + seed.request().contentDigest(), + 3, + seed.request().worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); + return new GameDesignPublicationOperation(account, world); + } +} diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java new file mode 100644 index 0000000000..566327ef2d --- /dev/null +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -0,0 +1,406 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** Stipulated original Account/APPLIED component bytes; no live producer/currentness proof. */ +public final class PublishedWorldSelectorFixtures { + private final TargetProof target; + + private PublishedWorldSelectorFixtures(TargetProof target) { + this.target = target; + this.TENANT_ID = target.canonicalTenantId(); + this.VERSION_ID = target.canonicalVersionId(); + } + + public static WorldPublishedStartLocationEvidence evidence(TargetProof target) throws Exception { + return new PublishedWorldSelectorFixtures(target).build(); + } + + public static List + participants(long versionId, WorldPublishedStartLocationEvidence evidence) { + return net + .firedevops + .firemud + .common + .gamedesign + .AuthoredWorldReleaseAttestationEvidence + .requiredParticipantOrder() + .stream() + .map( + owner -> + new net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto( + owner, + Long.toString(versionId), + null, + evidence.request().appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) + ? evidence.request().contentDigest() + : "c".repeat(64), + net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence + .supportedParticipantDigestSchema(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, + null, + null)) + .toList(); + } + + private WorldPublishedStartLocationEvidence build() throws Exception { + var draft = freshGraphBinding(); + var terminal = WorldDraftTerminalReadEvidence.Request.create("test", accountBinding(draft)); + var result = committedReadback(terminal, true); + var applied = JSON.readTree(result.result()); + var tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + TENANT_ID, + VERSION_ID, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + draft.commitId().toString(), + "b".repeat(64), + 3, + tuples); + return new WorldPublishedStartLocationEvidence( + request, + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()), + result.fullBinding(), + result.result()); + } + + private final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private final UUID TENANT_ID; + private final UUID VERSION_ID; + private final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + private DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) throws Exception { + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = freshGraph ? graphBytes(request, draft) : historicalGraphBytes(account); + String graphDigest = sha256(graph); + var result = new java.util.LinkedHashMap(); + result.put( + "schema", freshGraph ? "world-draft-graph-applied/v2" : "world-draft-graph-applied/v1"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + if (freshGraph) { + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + } + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JSON.valueToTree(result))); + } + + private DraftCommitBinding freshGraphBinding() throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, + VERSION_ID, + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()), + REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACTOR_ID, + TENANT_ID, + VERSION_ID, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private byte[] historicalGraphBytes(DraftAuthorizationFenceBinding account) { + throw new IllegalArgumentException("This fixture supplies only selector-bearing APPLIED v2"); + } + + private tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var receipt = + WorldDraftStartLocationEvidence.create( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + sha256(account.canonicalBytes()), + draft.digest(), + new RoomTemplateRef(TENANT_ID, VERSION_ID, ROOM_TEMPLATE_ID), + graphDigest); + return (tools.jackson.databind.node.ObjectNode) JSON.readTree(receipt.canonicalBytes()); + } + + private byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java new file mode 100644 index 0000000000..217077a055 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepositoryIntegrationTest.java @@ -0,0 +1,1017 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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 java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.ApplicationSlot; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.CommitSnapshot; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.FinalAbortReceipt; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerState; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.WorkflowState; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class DraftCommitCoordinatorRepositoryIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String LARGE_EPOCH = "900719925474099312345678901234567890"; + + @Container + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + + private static Fixture fixture; + + @BeforeAll + static void setUpSchema() { + fixture = createFixture(); + } + + @Test + void exactClaimReplayRetainsFullBindingAndChangedRetryConflictsWithoutRewrite() { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + + CommitSnapshot first = inTransaction(() -> fixture.coordinator().claim(binding)); + OffsetDateTimePair firstTimes = + new OffsetDateTimePair( + first.createdAt(), first.ownerStates().get(Owner.WORLD_MANAGEMENT).updatedAt()); + CommitSnapshot exactReplay = inTransaction(() -> fixture.coordinator().claim(binding)); + + assertThat(exactReplay.binding().canonicalBytes()).containsExactly(binding.canonicalBytes()); + assertThat(exactReplay.binding().digest()).isEqualTo(binding.digest()); + assertThat(exactReplay.createdAt()).isEqualTo(firstTimes.commitCreatedAt()); + assertThat(exactReplay.ownerStates().get(Owner.WORLD_MANAGEMENT).updatedAt()) + .isEqualTo(firstTimes.ownerUpdatedAt()); + assertThat(exactReplay.ownerStates().values()) + .allMatch(state -> state.status() == OwnerStatus.NOT_ATTEMPTED); + + var changed = + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + List.of( + new RevisionPayload( + "0", + binding.revisions().getFirst().revisionId(), + Owner.WORLD_MANAGEMENT, + "{\"room\":\"changed but still typed input\"}"), + binding.revisions().get(1)), + binding.affectedUnits()); + assertThatThrownBy(() -> inTransaction(() -> fixture.coordinator().claim(changed))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + } + + @Test + void pendingBindingAndOwnerRowsRollBackTogether() { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + + fixture + .ownerTransaction() + .executeWithoutResult( + status -> { + fixture.coordinator().claim(binding); + status.setRollbackOnly(); + }); + + assertThat(fixture.coordinator().read(target, binding.requestId())).isEmpty(); + assertThat(fixture.coordinator().readApplicationSlot(target)).isEmpty(); + } + + @Test + void concurrentExactClaimsConvergeOnOneImmutableBinding() throws Exception { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future left = + executor.submit( + () -> { + ready.countDown(); + await(start); + return inTransaction(() -> fixture.coordinator().claim(binding)); + }); + Future right = + executor.submit( + () -> { + ready.countDown(); + await(start); + return inTransaction(() -> fixture.coordinator().claim(binding)); + }); + await(ready); + start.countDown(); + CommitSnapshot first = left.get(20, TimeUnit.SECONDS); + CommitSnapshot second = right.get(20, TimeUnit.SECONDS); + + assertThat(first.binding().canonicalBytes()) + .containsExactly(second.binding().canonicalBytes()); + assertThat(fixture.coordinator().read(target, binding.requestId())).isPresent(); + assertThat( + fixture.coordinator().read(target, binding.requestId()).orElseThrow().ownerStates()) + .containsOnlyKeys(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit")), + DSL.field(DSL.name("request_id"), UUID.class).eq(binding.requestId()))) + .isEqualTo(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void concurrentDifferentRequestsCannotClaimTheSameCommitIdentity() throws Exception { + TargetProof target = fixture.newTarget(); + UUID commitId = UUID.randomUUID(); + var firstBinding = binding(target, UUID.randomUUID(), commitId); + var secondBinding = binding(target, UUID.randomUUID(), commitId); + + ConcurrentClaims claims = concurrentlyClaim(firstBinding, secondBinding); + assertExactlyOneClaimSucceeded(claims); + DraftCommitBinding winningBinding = + claims.left().snapshot() == null ? secondBinding : firstBinding; + DraftCommitBinding rejectedBinding = + claims.left().snapshot() == null ? firstBinding : secondBinding; + + CommitSnapshot persisted = + fixture.coordinator().read(target, winningBinding.requestId()).orElseThrow(); + assertThat(persisted.binding().canonicalBytes()) + .containsExactly(winningBinding.canonicalBytes()); + assertThat(persisted.ownerStates()) + .containsOnlyKeys(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT); + assertThat(fixture.coordinator().read(target, rejectedBinding.requestId())).isEmpty(); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit")), + DSL.field(DSL.name("commit_id"), UUID.class).eq(commitId))) + .isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit_owner_result")), + DSL.field(DSL.name("request_id"), UUID.class).eq(winningBinding.requestId()))) + .isEqualTo(winningBinding.requiredOwners().size()); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit_owner_result")), + DSL.field(DSL.name("request_id"), UUID.class).eq(rejectedBinding.requestId()))) + .isZero(); + } + + @Test + void concurrentChangedInputForOneRequestIsRejectedWithoutExtraOwnerRows() throws Exception { + TargetProof target = fixture.newTarget(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + var firstBinding = binding(target, requestId, commitId); + var changedBinding = + DraftCommitBinding.create( + firstBinding.target(), + firstBinding.requestId(), + firstBinding.commitId(), + firstBinding.baseCommitId(), + List.of( + new RevisionPayload( + "0", + firstBinding.revisions().getFirst().revisionId(), + Owner.WORLD_MANAGEMENT, + "{\"room\":\"changed concurrent input\"}"), + firstBinding.revisions().get(1)), + firstBinding.affectedUnits()); + + ConcurrentClaims claims = concurrentlyClaim(firstBinding, changedBinding); + assertExactlyOneClaimSucceeded(claims); + DraftCommitBinding winningBinding = + claims.left().snapshot() == null ? changedBinding : firstBinding; + + CommitSnapshot persisted = fixture.coordinator().read(target, requestId).orElseThrow(); + assertThat(persisted.binding().canonicalBytes()) + .containsExactly(winningBinding.canonicalBytes()); + assertThat(persisted.ownerStates()) + .containsOnlyKeys(Owner.WORLD_MANAGEMENT, Owner.ENTITY_MANAGEMENT); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit")), + DSL.field(DSL.name("request_id"), UUID.class).eq(requestId))) + .isEqualTo(1); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit_owner_result")), + DSL.field(DSL.name("request_id"), UUID.class).eq(requestId))) + .isEqualTo(winningBinding.requiredOwners().size()); + } + + @Test + void partialUnknownOwnerResultKeepsApplicationSlotAndCannotCreateVisibilityFence() { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + inTransaction(() -> fixture.coordinator().claim(binding)); + ApplicationSlot slot = inTransaction(() -> fixture.coordinator().claimApplicationSlot(binding)); + assertThat(slot.commitId()).isEqualTo(binding.commitId()); + + inTransaction( + () -> { + fixture.coordinator().markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT); + fixture.coordinator().recordOwnerOutcome(binding, appliedWorldOutcome(binding)); + fixture.coordinator().markOwnerInProgress(binding, Owner.ENTITY_MANAGEMENT); + fixture + .coordinator() + .recordOwnerOutcome( + binding, + new OwnerOutcome( + Owner.ENTITY_MANAGEMENT, + OwnerStatus.UNKNOWN, + binding.commitId(), + binding.digest(), + null, + null, + List.of())); + return null; + }); + + CommitSnapshot partial = fixture.coordinator().read(target, binding.requestId()).orElseThrow(); + assertThat(partial.workflowState()).isEqualTo(WorkflowState.RECONCILIATION_REQUIRED); + assertThat(partial.ownerStates().get(Owner.WORLD_MANAGEMENT).status()) + .isEqualTo(OwnerStatus.APPLIED); + assertThat(partial.ownerStates().get(Owner.ENTITY_MANAGEMENT).status()) + .isEqualTo(OwnerStatus.UNKNOWN); + assertThat(fixture.coordinator().readApplicationSlot(target)).isPresent(); + assertThat(fixture.coordinator().readVisibilityFence(target)).isEmpty(); + assertThatThrownBy( + () -> + inTransaction( + () -> { + fixture.coordinator().releaseApplicationSlot(binding); + return null; + })) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class) + .hasMessageContaining("cannot release"); + + OwnerState world = partial.ownerStates().get(Owner.WORLD_MANAGEMENT); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .coordinator() + .recordOwnerOutcome( + binding, + new OwnerOutcome( + Owner.WORLD_MANAGEMENT, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "world-result-exact-1", + "different bytes".getBytes(StandardCharsets.UTF_8), + appliedWorldOutcome(binding).appliedEpochs())))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThat( + fixture + .coordinator() + .read(target, binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.WORLD_MANAGEMENT) + .updatedAt()) + .isEqualTo(world.updatedAt()); + } + + @Test + void exactAppliedResultReplayIsImmutableBeforeAndAfterSlotRelease() { + TargetProof target = fixture.newTarget(); + var binding = worldOnlyBinding(target, UUID.randomUUID(), UUID.randomUUID()); + inTransaction(() -> fixture.coordinator().claim(binding)); + inTransaction(() -> fixture.coordinator().claimApplicationSlot(binding)); + + OwnerOutcome original = appliedWorldOutcome(binding); + OwnerState first = + inTransaction( + () -> { + fixture.coordinator().markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT); + return fixture.coordinator().recordOwnerOutcome(binding, original); + }); + OwnerOutcome exactRetry = appliedWorldOutcome(binding); + OwnerState beforeRelease = + inTransaction(() -> fixture.coordinator().recordOwnerOutcome(binding, exactRetry)); + assertThat(beforeRelease.updatedAt()).isEqualTo(first.updatedAt()); + assertThat(beforeRelease.outcome()).contains(original); + assertThat(beforeRelease.outcome().orElseThrow().resultBytes()) + .containsExactly(original.resultBytes()); + + OwnerOutcome changed = + new OwnerOutcome( + Owner.WORLD_MANAGEMENT, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + original.resultIdentity(), + "changed owner evidence".getBytes(StandardCharsets.UTF_8), + original.appliedEpochs()); + assertThatThrownBy( + () -> inTransaction(() -> fixture.coordinator().recordOwnerOutcome(binding, changed))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + + inTransaction( + () -> { + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(original))); + fixture.coordinator().releaseApplicationSlot(binding); + return null; + }); + assertThat(fixture.coordinator().readApplicationSlot(target)).isEmpty(); + + OwnerState afterRelease = + inTransaction(() -> fixture.coordinator().recordOwnerOutcome(binding, exactRetry)); + assertThat(afterRelease.updatedAt()).isEqualTo(first.updatedAt()); + assertThat(afterRelease.outcome()).contains(original); + assertThat(afterRelease.outcome().orElseThrow().resultBytes()) + .containsExactly(original.resultBytes()); + } + + @Test + void mixedFinalAbortPreservesPriorFenceAndOwnerEvidenceAndFencesDelayedAttempts() { + TargetProof target = fixture.newTarget(); + var priorBinding = worldOnlyBinding(target, UUID.randomUUID(), UUID.randomUUID()); + OwnerOutcome priorWorld = appliedWorldOutcome(priorBinding); + inTransaction( + () -> { + fixture.coordinator().claim(priorBinding); + fixture.coordinator().claimApplicationSlot(priorBinding); + fixture.coordinator().markOwnerInProgress(priorBinding, Owner.WORLD_MANAGEMENT); + fixture.coordinator().recordOwnerOutcome(priorBinding, priorWorld); + fixture + .coordinator() + .advanceVisibilityFence( + priorBinding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + priorBinding, List.of(priorWorld))); + fixture.coordinator().releaseApplicationSlot(priorBinding); + return null; + }); + var priorFence = fixture.coordinator().readVisibilityFence(target).orElseThrow(); + + var failedBinding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + OwnerOutcome appliedWorld = appliedWorldOutcome(failedBinding); + OwnerOutcome rejectedEntity = + new OwnerOutcome( + Owner.ENTITY_MANAGEMENT, + OwnerStatus.REJECTED, + failedBinding.commitId(), + failedBinding.digest(), + "entity-rejected-final-1", + "durable exact rejection".getBytes(StandardCharsets.UTF_8), + List.of()); + byte[] abortBytes = "trusted producer final-abort receipt".getBytes(StandardCharsets.UTF_8); + inTransaction( + () -> { + fixture.coordinator().claim(failedBinding); + fixture.coordinator().claimApplicationSlot(failedBinding); + fixture.coordinator().markOwnerInProgress(failedBinding, Owner.WORLD_MANAGEMENT); + fixture.coordinator().recordOwnerOutcome(failedBinding, appliedWorld); + fixture.coordinator().markOwnerInProgress(failedBinding, Owner.ENTITY_MANAGEMENT); + fixture.coordinator().recordOwnerOutcome(failedBinding, rejectedEntity); + return null; + }); + + FinalAbortReceipt first = + inTransaction( + () -> fixture.coordinator().recordDefinitiveFinalAbort(failedBinding, abortBytes)); + CommitSnapshot failed = + fixture.coordinator().read(target, failedBinding.requestId()).orElseThrow(); + assertThat(failed.workflowState()).isEqualTo(WorkflowState.FAILED_NONPUBLICATION); + assertThat(failed.ownerStates().get(Owner.WORLD_MANAGEMENT).outcome()).contains(appliedWorld); + assertThat(failed.ownerStates().get(Owner.ENTITY_MANAGEMENT).outcome()) + .contains(rejectedEntity); + assertThat(fixture.coordinator().readVisibilityFence(target)).contains(priorFence); + + FinalAbortReceipt exactReplay = + inTransaction( + () -> fixture.coordinator().recordDefinitiveFinalAbort(failedBinding, abortBytes)); + assertThat(exactReplay.binding()).isEqualTo(first.binding()); + assertThat(exactReplay.abortBytes()).containsExactly(first.abortBytes()); + assertThat(exactReplay.createdAt()).isEqualTo(first.createdAt()); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .coordinator() + .recordDefinitiveFinalAbort( + failedBinding, + "changed final-abort bytes".getBytes(StandardCharsets.UTF_8)))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + + assertThat( + inTransaction( + () -> fixture.coordinator().recordOwnerOutcome(failedBinding, appliedWorld)) + .outcome()) + .contains(appliedWorld); + OwnerOutcome changedWorld = + new OwnerOutcome( + Owner.WORLD_MANAGEMENT, + OwnerStatus.APPLIED, + failedBinding.commitId(), + failedBinding.digest(), + appliedWorld.resultIdentity(), + "changed World result".getBytes(StandardCharsets.UTF_8), + appliedWorld.appliedEpochs()); + assertThatThrownBy( + () -> + inTransaction( + () -> fixture.coordinator().recordOwnerOutcome(failedBinding, changedWorld))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + + assertThatThrownBy( + () -> inTransaction(() -> fixture.coordinator().claimApplicationSlot(failedBinding))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .coordinator() + .markOwnerInProgress(failedBinding, Owner.WORLD_MANAGEMENT))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_draft_commit_owner_result " + + "SET status = 'IN_PROGRESS', updated_at = CURRENT_TIMESTAMP " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = 'WORLD_MANAGEMENT'", + target.canonicalTenantId(), + target.canonicalVersionId(), + failedBinding.requestId()))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_visibility_fence " + + "(canonical_tenant_id, canonical_version_id, request_id, " + + "commit_id, input_digest, result_vector_json) " + + "VALUES (?, ?, ?, ?, ?, '[]')", + target.canonicalTenantId(), + target.canonicalVersionId(), + failedBinding.requestId(), + failedBinding.commitId(), + failedBinding.digest()))) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_application_slot " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "VALUES (?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + failedBinding.requestId(), + failedBinding.commitId()))) + .isInstanceOf(RuntimeException.class); + + inTransaction( + () -> { + fixture.coordinator().releaseApplicationSlot(failedBinding); + return null; + }); + assertThat(fixture.coordinator().readApplicationSlot(target)).isEmpty(); + assertThat(fixture.coordinator().readVisibilityFence(target)).contains(priorFence); + + var laterBinding = worldOnlyBinding(target, UUID.randomUUID(), UUID.randomUUID()); + inTransaction( + () -> { + fixture.coordinator().claim(laterBinding); + fixture.coordinator().claimApplicationSlot(laterBinding); + return null; + }); + FinalAbortReceipt replayAfterReclaim = + inTransaction( + () -> fixture.coordinator().recordDefinitiveFinalAbort(failedBinding, abortBytes)); + assertThat(replayAfterReclaim.createdAt()).isEqualTo(first.createdAt()); + inTransaction( + () -> { + fixture.coordinator().releaseApplicationSlot(failedBinding); + return null; + }); + assertThat(fixture.coordinator().readApplicationSlot(target).orElseThrow().requestId()) + .isEqualTo(laterBinding.requestId()); + assertThat(fixture.coordinator().readVisibilityFence(target)).contains(priorFence); + } + + @Test + void unknownOwnerAndMissingRowsCannotProduceFinalAbort() { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + OwnerOutcome world = appliedWorldOutcome(binding); + inTransaction( + () -> { + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT); + fixture.coordinator().recordOwnerOutcome(binding, world); + fixture.coordinator().markOwnerInProgress(binding, Owner.ENTITY_MANAGEMENT); + fixture + .coordinator() + .recordOwnerOutcome( + binding, + new OwnerOutcome( + Owner.ENTITY_MANAGEMENT, + OwnerStatus.UNKNOWN, + binding.commitId(), + binding.digest(), + null, + null, + List.of())); + return null; + }); + + byte[] abortBytes = "not enough proof".getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + inTransaction( + () -> fixture.coordinator().recordDefinitiveFinalAbort(binding, abortBytes))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThat( + fixture.coordinator().read(target, binding.requestId()).orElseThrow().workflowState()) + .isEqualTo(WorkflowState.RECONCILIATION_REQUIRED); + assertThat(fixture.coordinator().readApplicationSlot(target)).isPresent(); + + assertThatThrownBy( + () -> + inTransaction( + () -> { + fixture + .dsl() + .execute( + "DELETE FROM game_design_draft_commit_owner_result " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = 'ENTITY_MANAGEMENT'", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId()); + return null; + })) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_final_abort " + + "(canonical_tenant_id, canonical_version_id, request_id, " + + "commit_id, input_digest, binding_json, abort_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + binding.canonicalJson(), + abortBytes))) + .isInstanceOf(RuntimeException.class); + } + + @Test + void allAppliedOwnersIncludingGameDesignCanBeFinalAbortedWithoutVisibility() { + TargetProof target = fixture.newTarget(); + var binding = allOwnerBinding(target, UUID.randomUUID(), UUID.randomUUID()); + inTransaction( + () -> { + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + for (Owner owner : binding.requiredOwners()) { + OwnerOutcome outcome = appliedOutcome(binding, owner); + fixture.coordinator().markOwnerInProgress(binding, owner); + fixture.coordinator().recordOwnerOutcome(binding, outcome); + } + return null; + }); + + FinalAbortReceipt receipt = + inTransaction( + () -> + fixture + .coordinator() + .recordDefinitiveFinalAbort( + binding, + "Game Design final no-commit proof".getBytes(StandardCharsets.UTF_8))); + CommitSnapshot snapshot = fixture.coordinator().read(target, binding.requestId()).orElseThrow(); + assertThat(snapshot.workflowState()).isEqualTo(WorkflowState.FAILED_NONPUBLICATION); + assertThat(snapshot.ownerStates()).containsKeys(Owner.GAME_DESIGN_CONTROL_PLANE); + assertThat(snapshot.ownerStates().values()) + .allMatch(state -> state.status() == OwnerStatus.APPLIED); + assertThat(receipt.binding()).isEqualTo(binding); + assertThat(fixture.coordinator().readVisibilityFence(target)).isEmpty(); + List allApplied = + binding.requiredOwners().stream().map(owner -> appliedOutcome(binding, owner)).toList(); + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, allApplied)))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + inTransaction( + () -> { + fixture.coordinator().releaseApplicationSlot(binding); + return null; + }); + assertThat(fixture.coordinator().readApplicationSlot(target)).isEmpty(); + } + + @Test + void directSqlFinalAbortRejectsMissingRequiredOwnerRows() { + TargetProof target = fixture.newTarget(); + var binding = binding(target, UUID.randomUUID(), UUID.randomUUID()); + byte[] abortBytes = "missing owner is not no-commit proof".getBytes(StandardCharsets.UTF_8); + inTransaction( + () -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit " + + "(canonical_tenant_id, canonical_version_id, " + + "game_design_version_row_id, game_design_version_tenant_key, " + + "source_game_row_id, source_game_tenant_key, source_provenance_kind, " + + "request_id, commit_id, base_commit_id, input_digest, binding_json, " + + "workflow_state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'APPLYING')", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + binding.digest(), + binding.canonicalJson()); + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_application_slot " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id) " + + "VALUES (?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId()); + return null; + }); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit")), + DSL.field(DSL.name("request_id"), UUID.class).eq(binding.requestId()))) + .isEqualTo(1); + assertThat(fixture.coordinator().readApplicationSlot(target).orElseThrow().requestId()) + .isEqualTo(binding.requestId()); + + assertThatThrownBy( + () -> + inTransaction( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_final_abort " + + "(canonical_tenant_id, canonical_version_id, request_id, " + + "commit_id, input_digest, binding_json, abort_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + binding.canonicalJson(), + abortBytes))) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining( + "Final-abort evidence requires every exact owner result to be terminal"); + } + + private static Fixture createFixture() { + String schema = "gd_draft_coord_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + GameRepository gameRepository = new GameRepository(dsl); + VersionRepository versionRepository = new VersionRepository(dsl); + DraftCommitCoordinatorRepository coordinator = new DraftCommitCoordinatorRepository(dsl); + return new Fixture(dsl, transactionTemplate, gameRepository, versionRepository, coordinator); + } + + private static DraftCommitBinding binding(TargetProof target, UUID requestId, UUID commitId) { + return DraftCommitBinding.create( + target, + requestId, + commitId, + "base-commit-source-7", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + Owner.WORLD_MANAGEMENT, + "{\"completeWorldMutation\":{\"opaque\":\"preserved\"}}"), + new RevisionPayload( + "1", + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + "{\"completeEntityMutation\":{\"opaque\":\"preserved\"}}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-scope-1", + LARGE_EPOCH), + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "ENTITY_TEMPLATE", + "entity-1", + "ACTOR_SCOPE", + "actor-scope-1", + "0"))); + } + + private static DraftCommitBinding worldOnlyBinding( + TargetProof target, UUID requestId, UUID commitId) { + return DraftCommitBinding.create( + target, + requestId, + commitId, + "base-commit-source-7", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + Owner.WORLD_MANAGEMENT, + "{\"completeWorldMutation\":{\"opaque\":\"preserved\"}}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-scope-1", + LARGE_EPOCH))); + } + + private static DraftCommitBinding allOwnerBinding( + TargetProof target, UUID requestId, UUID commitId) { + List revisions = new java.util.ArrayList<>(); + List affected = new java.util.ArrayList<>(); + int index = 0; + for (Owner owner : Owner.values()) { + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + owner, + "{\"ownerMutation\":\"" + owner.name() + "\"}")); + affected.add( + new AffectedUnit( + owner, + owner.name() + "_AGGREGATE", + "aggregate-" + owner.name().toLowerCase(java.util.Locale.ROOT), + owner.name() + "_SCOPE", + "scope-" + owner.name().toLowerCase(java.util.Locale.ROOT), + "0")); + index++; + } + return DraftCommitBinding.create( + target, requestId, commitId, "base-commit-source-7", revisions, affected); + } + + private static OwnerOutcome appliedOutcome(DraftCommitBinding binding, Owner owner) { + AffectedUnit expected = binding.affectedUnits(owner).getFirst(); + String resultingEpoch = + new java.math.BigInteger(expected.expectedEpoch()).add(java.math.BigInteger.ONE).toString(); + return new OwnerOutcome( + owner, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + owner.name().toLowerCase(java.util.Locale.ROOT) + "-result-exact-1", + ("full durable " + owner.name() + " response").getBytes(StandardCharsets.UTF_8), + List.of( + new AppliedEpoch( + expected.aggregateType(), + expected.aggregateId(), + expected.scopeType(), + expected.scopeId(), + expected.expectedEpoch(), + resultingEpoch))); + } + + private static OwnerOutcome appliedWorldOutcome(DraftCommitBinding binding) { + AffectedUnit expected = binding.affectedUnits(Owner.WORLD_MANAGEMENT).getFirst(); + String resultingEpoch = + new java.math.BigInteger(expected.expectedEpoch()).add(java.math.BigInteger.ONE).toString(); + return new OwnerOutcome( + Owner.WORLD_MANAGEMENT, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "world-result-exact-1", + "full durable owner response".getBytes(StandardCharsets.UTF_8), + List.of( + new AppliedEpoch( + expected.aggregateType(), + expected.aggregateId(), + expected.scopeType(), + expected.scopeId(), + expected.expectedEpoch(), + resultingEpoch))); + } + + private static T inTransaction(Supplier work) { + return fixture.ownerTransaction().execute(status -> work.get()); + } + + private static ConcurrentClaims concurrentlyClaim( + DraftCommitBinding leftBinding, DraftCommitBinding rightBinding) throws Exception { + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future left = + executor.submit( + () -> { + ready.countDown(); + await(start); + return claimAttempt(leftBinding); + }); + Future right = + executor.submit( + () -> { + ready.countDown(); + await(start); + return claimAttempt(rightBinding); + }); + await(ready); + start.countDown(); + return new ConcurrentClaims(left.get(20, TimeUnit.SECONDS), right.get(20, TimeUnit.SECONDS)); + } finally { + executor.shutdownNow(); + } + } + + private static ClaimAttempt claimAttempt(DraftCommitBinding binding) { + try { + return new ClaimAttempt(inTransaction(() -> fixture.coordinator().claim(binding)), null); + } catch (RuntimeException exception) { + return new ClaimAttempt(null, exception); + } + } + + private static void assertExactlyOneClaimSucceeded(ConcurrentClaims claims) { + assertThat(claims.left().snapshot() == null).isNotEqualTo(claims.right().snapshot() == null); + ClaimAttempt rejected = claims.left().snapshot() == null ? claims.left() : claims.right(); + ClaimAttempt succeeded = claims.left().snapshot() == null ? claims.right() : claims.left(); + assertThat(rejected.failure()) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + assertThat(succeeded.failure()).isNull(); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for concurrent Draft commit claim"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while coordinating concurrent Draft claims", exception); + } + } + + private record ClaimAttempt(CommitSnapshot snapshot, RuntimeException failure) {} + + private record ConcurrentClaims(ClaimAttempt left, ClaimAttempt right) {} + + private record Fixture( + DSLContext dsl, + TransactionTemplate ownerTransaction, + GameRepository games, + VersionRepository versions, + DraftCommitCoordinatorRepository coordinator) { + TargetProof newTarget() { + String tenantKey = "d-" + UUID.randomUUID().toString().replace("-", ""); + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName("Draft coordinator integration source"); + game.setDescription("Canonical Version source fixture"); + Game savedGame = Objects.requireNonNull(ownerTransaction.execute(status -> games.save(game))); + + Version version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(net.firedevops.firemud.gamedesign.model.VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + Version savedVersion = + Objects.requireNonNull(ownerTransaction.execute(status -> versions.save(version))); + return new TargetProof( + savedVersion.getCanonicalTenantId(), + savedVersion.getCanonicalVersionId(), + savedVersion.getId(), + savedVersion.getTenantId(), + savedVersion.getIdentitySourceGameRowId(), + savedVersion.getIdentitySourceGameTenantKey(), + savedVersion.getIdentitySourceProvenanceKind()); + } + } + + private record OffsetDateTimePair( + java.time.OffsetDateTime commitCreatedAt, java.time.OffsetDateTime ownerUpdatedAt) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java new file mode 100644 index 0000000000..8577af395e --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java @@ -0,0 +1,772 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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 java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** + * Persistence proof only. Account source authentication and remote owner producer authenticity are + * stipulated by fixture inputs here; this test wires neither a protected Account producer nor a + * permission verifier and does not establish genuine authorization. + */ +@Testcontainers(disabledWithoutDocker = true) +class GameDesignDraftTerminalOutcomePostgresIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Container + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + + private static Fixture fixture; + + @BeforeAll + static void setUpSchema() { + fixture = createFixture(null); + } + + @Test + void exactAccountClaimAndTerminalReadbackRetainOriginalBytes() { + TargetProof target = fixture.newTarget(); + DraftCommitBinding binding = binding(target); + DraftAuthorizationFenceBinding account = accountBinding(binding, "stipulated-source-a"); + GameDesignDraftTerminalOperation operation = + new GameDesignDraftTerminalOperation(account, binding); + + fixture.inTransaction(() -> fixture.coordinator().claim(binding, account)); + fixture.inTransaction(() -> fixture.coordinator().claim(binding, account)); + + var retainedOperation = + new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) + .readOperation(account.operationId()) + .orElseThrow(); + assertThat(retainedOperation.accountBindingBytes()).containsExactly(account.canonicalBytes()); + assertThat(retainedOperation.accountBindingDigest()) + .isEqualTo(operation.accountBindingDigest()); + assertThat( + new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) + .readAccountBound(account.canonicalBytes())) + .isEmpty(); + + DraftAuthorizationFenceBinding changed = + accountBinding( + binding, + account.operationId(), + account.fenceId(), + account.actorAccountId(), + "stipulated-source-b"); + assertThatThrownBy( + () -> fixture.inTransaction(() -> fixture.coordinator().claim(binding, changed))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + assertThat(retainedOperation.accountBindingBytes()).containsExactly(account.canonicalBytes()); + } + + @Test + void committedOutcomeIsAtomicWithSynchronizedFenceAndCompleteOwnerVector() { + TargetProof target = fixture.newTarget(); + DraftCommitBinding binding = binding(target); + DraftAuthorizationFenceBinding account = accountBinding(binding, "stipulated-source-commit"); + List outcomes = + beginAndApplyOwners(binding, account, null); + + fixture.inTransaction( + () -> { + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + return null; + }); + + GameDesignDraftTerminalOutcome readback = + new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) + .readAccountBound(account.canonicalBytes()) + .orElseThrow(); + assertThat(readback.result()).isEqualTo(GameDesignDraftTerminalOutcome.Result.COMMITTED); + assertThat(readback.operation().accountBindingBytes()) + .containsExactly(account.canonicalBytes()); + assertThat(readback.ownerResultVectorJson()) + .isEqualTo( + fixture.coordinator().readVisibilityFence(target).orElseThrow().resultVectorJson()); + assertThat(readback.finalEvidenceBytes()) + .containsExactly(readback.ownerResultVectorJson().getBytes(StandardCharsets.UTF_8)); + OwnerReadback ownerReadback = readback.toOwnerReadback(); + assertThat(ownerReadback.owner()).isEqualTo(DraftAuthorizationFenceBinding.Owner.GAME_DESIGN); + assertThat(ownerReadback.outcome()).isEqualTo(DraftAuthorizationFenceBinding.Outcome.COMMITTED); + assertThat(ownerReadback.operationId()).isEqualTo(account.operationId()); + assertThat(ownerReadback.commitId()).isEqualTo(account.commitId()); + assertThat(ownerReadback.fenceId()).isEqualTo(account.fenceId()); + assertThat(ownerReadback.inputDigest()).isEqualTo(account.inputDigest()); + assertThat(ownerReadback.fullBinding()).containsExactly(account.canonicalBytes()); + assertThat(ownerReadback.result()).containsExactly(readback.finalEvidenceBytes()); + OwnerReadback storedOwnerReadback = OwnerReadback.fromStored(ownerReadback.canonicalBytes()); + assertThat(storedOwnerReadback.canonicalBytes()) + .containsExactly(ownerReadback.canonicalBytes()); + storedOwnerReadback.requireBinding(account); + DraftAuthorizationFenceBinding changedAccount = + accountBinding( + binding, + account.operationId(), + account.fenceId(), + account.actorAccountId(), + "changed-original-account-bytes"); + assertThatThrownBy(() -> storedOwnerReadback.requireBinding(changedAccount)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) + .readAccountBound(changedAccount.canonicalBytes())) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> { + fixture + .dsl() + .execute( + "UPDATE game_design_draft_terminal_outcome " + + "SET terminal_evidence_digest = ? WHERE operation_id = ?", + "sha256:" + "0".repeat(64), + account.operationId()); + return null; + })) + .isInstanceOf(RuntimeException.class); + fixture.inTransaction( + () -> { + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + return null; + }); + assertThat( + new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) + .readAccountBound(account.canonicalBytes()) + .orElseThrow() + .createdAt()) + .isEqualTo(readback.createdAt()); + assertThat( + fixture.coordinator().read(target, binding.requestId()).orElseThrow().workflowState()) + .isEqualTo(DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED); + } + + @Test + void abortRetainsMixedAppliedAndRejectedParticipantsAndDeniesLateWriters() { + TargetProof target = fixture.newTarget(); + DraftCommitBinding binding = binding(target); + DraftAuthorizationFenceBinding account = accountBinding(binding, "stipulated-source-abort"); + beginAndApplyOwners(binding, account, Owner.ENTITY_MANAGEMENT); + byte[] abortEvidence = + "stipulated exact final-abort producer evidence".getBytes(StandardCharsets.UTF_8); + + fixture.inTransaction( + () -> { + fixture.coordinator().recordDefinitiveFinalAbort(binding, abortEvidence); + return null; + }); + + GameDesignDraftTerminalOutcome readback = + new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) + .readAccountBound(account.canonicalBytes()) + .orElseThrow(); + assertThat(readback.result()) + .isEqualTo(GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED); + assertThat(readback.finalEvidenceBytes()).containsExactly(abortEvidence); + OwnerReadback ownerReadback = + OwnerReadback.fromStored(readback.toOwnerReadback().canonicalBytes()); + assertThat(ownerReadback.owner()).isEqualTo(DraftAuthorizationFenceBinding.Owner.GAME_DESIGN); + assertThat(ownerReadback.outcome()) + .isEqualTo(DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED); + assertThat(ownerReadback.fullBinding()).containsExactly(account.canonicalBytes()); + assertThat(ownerReadback.result()).containsExactly(abortEvidence); + ownerReadback.requireBinding(account); + assertThat(readback.ownerResultVectorJson()).contains("\"owner\":\"WORLD_MANAGEMENT\""); + assertThat(readback.ownerResultVectorJson()).contains("\"status\":\"APPLIED\""); + assertThat(readback.ownerResultVectorJson()).contains("\"owner\":\"ENTITY_MANAGEMENT\""); + assertThat(readback.ownerResultVectorJson()).contains("\"status\":\"REJECTED\""); + assertThat(fixture.coordinator().readVisibilityFence(target)).isEmpty(); + var firstAbortReplay = + fixture.inTransaction( + () -> fixture.coordinator().recordDefinitiveFinalAbort(binding, abortEvidence)); + var secondAbortReplay = + fixture.inTransaction( + () -> fixture.coordinator().recordDefinitiveFinalAbort(binding, abortEvidence)); + assertThat(secondAbortReplay.createdAt()).isEqualTo(firstAbortReplay.createdAt()); + + assertThatThrownBy( + () -> fixture.inTransaction(() -> fixture.coordinator().claim(binding, account))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture.coordinator().markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture + .coordinator() + .recordOwnerOutcome( + binding, appliedOutcome(binding, Owner.WORLD_MANAGEMENT)))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThatThrownBy( + () -> fixture.inTransaction(() -> fixture.coordinator().claimApplicationSlot(binding))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + assertThatThrownBy( + () -> + fixture.inTransaction( + () -> + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, allAppliedOutcomes(binding))))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + } + + @Test + void terminalCommitAndAbortRaceHasOneSameVersionWinner() throws Exception { + TargetProof target = fixture.newTarget(); + DraftCommitBinding binding = binding(target); + DraftAuthorizationFenceBinding account = accountBinding(binding, "stipulated-source-race"); + GameDesignDraftTerminalOperation operation = + new GameDesignDraftTerminalOperation(account, binding); + List outcomes = + beginAndApplyOwners(binding, account, null); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future commit = + executor.submit( + () -> { + awaitStart(ready, start); + return attempt( + () -> + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, outcomes))); + }); + Future abort = + executor.submit( + () -> { + awaitStart(ready, start); + return attempt( + () -> + fixture + .coordinator() + .recordDefinitiveFinalAbort( + binding, + "stipulated race-abort evidence".getBytes(StandardCharsets.UTF_8))); + }); + await(ready); + start.countDown(); + FinalizeAttempt commitResult = commit.get(20, TimeUnit.SECONDS); + FinalizeAttempt abortResult = abort.get(20, TimeUnit.SECONDS); + + assertThat(commitResult.succeeded()).isNotEqualTo(abortResult.succeeded()); + GameDesignDraftTerminalOutcome result = + new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()).read(operation).orElseThrow(); + if (commitResult.succeeded()) { + assertThat(result.result()).isEqualTo(GameDesignDraftTerminalOutcome.Result.COMMITTED); + } else { + assertThat(result.result()) + .isEqualTo(GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED); + } + } finally { + executor.shutdownNow(); + } + } + + @Test + void rollbackCannotLeaveAVisibilityFenceWithoutItsTerminalOutcome() { + TargetProof target = fixture.newTarget(); + DraftCommitBinding binding = binding(target); + DraftAuthorizationFenceBinding account = accountBinding(binding, "stipulated-source-rollback"); + GameDesignDraftTerminalOperation operation = + new GameDesignDraftTerminalOperation(account, binding); + List outcomes = + beginAndApplyOwners(binding, account, null); + + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + status.setRollbackOnly(); + }); + + assertThat(new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()).read(operation)) + .isEmpty(); + assertThat(fixture.coordinator().readVisibilityFence(target)).isEmpty(); + assertThat( + fixture.coordinator().read(target, binding.requestId()).orElseThrow().workflowState()) + .isEqualTo(DraftCommitCoordinatorRepository.WorkflowState.APPLYING); + } + + @Test + void rollbackCannotLeaveFinalAbortTombstoneWithoutItsTerminalOutcome() { + TargetProof target = fixture.newTarget(); + DraftCommitBinding binding = binding(target); + DraftAuthorizationFenceBinding account = + accountBinding(binding, "stipulated-source-abort-rollback"); + GameDesignDraftTerminalOperation operation = + new GameDesignDraftTerminalOperation(account, binding); + beginAndApplyOwners(binding, account, Owner.ENTITY_MANAGEMENT); + byte[] abortEvidence = "stipulated rollback abort evidence".getBytes(StandardCharsets.UTF_8); + + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.coordinator().recordDefinitiveFinalAbort(binding, abortEvidence); + status.setRollbackOnly(); + }); + + assertThat(new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()).read(operation)) + .isEmpty(); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table(DSL.name("game_design_draft_commit_final_abort")), + DSL.field(DSL.name("request_id"), UUID.class).eq(binding.requestId()))) + .isZero(); + assertThat( + fixture.coordinator().read(target, binding.requestId()).orElseThrow().workflowState()) + .isEqualTo(DraftCommitCoordinatorRepository.WorkflowState.RECONCILIATION_REQUIRED); + } + + @Test + void migrationDoesNotInventAccountOutcomesForRetainedStatusOnlyRows() { + Fixture legacy = createFixture(MigrationVersion.fromVersion("45")); + TargetProof target = legacy.newTarget(); + DraftCommitBinding binding = binding(target); + List outcomes = allAppliedOutcomes(binding); + + legacy.inTransaction(() -> legacy.coordinator().claim(binding)); + legacy + .transaction() + .executeWithoutResult( + status -> { + legacy + .dsl() + .execute( + "UPDATE game_design_draft_commit SET workflow_state = 'APPLYING' " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId()); + for (DraftCommitCoordinatorRepository.OwnerOutcome outcome : outcomes) { + legacy + .dsl() + .execute( + "UPDATE game_design_draft_commit_owner_result SET status = 'IN_PROGRESS', " + + "updated_at = CURRENT_TIMESTAMP WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND request_id = ? AND owner = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + outcome.owner().name()); + legacy + .dsl() + .execute( + "UPDATE game_design_draft_commit_owner_result SET status = 'APPLIED', " + + "result_commit_id = ?, result_binding_digest = ?, result_identity = ?, " + + "result_bytes = ?, applied_units_json = ?, updated_at = CURRENT_TIMESTAMP " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = ?", + outcome.commitId(), + outcome.bindingDigest(), + outcome.resultIdentity(), + outcome.resultBytes(), + appliedEpochsJson(outcome.appliedEpochs()), + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + outcome.owner().name()); + } + String vector = ownerVectorJson(binding, outcomes); + legacy + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_visibility_fence " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "input_digest, result_vector_json) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + vector); + legacy + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_visibility " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest) " + + "VALUES (?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest()); + legacy + .dsl() + .execute( + "UPDATE game_design_draft_commit SET workflow_state = 'SYNCHRONIZED', " + + "updated_at = CURRENT_TIMESTAMP WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND request_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId()); + }); + legacy.migrateToLatest(); + + assertThat( + new GameDesignDraftTerminalOutcomeRepository(legacy.dsl()) + .readOperation(UUID.randomUUID())) + .isEmpty(); + assertThat(legacy.dsl().fetchCount(DSL.table(DSL.name("game_design_draft_terminal_operation")))) + .isZero(); + assertThat(legacy.dsl().fetchCount(DSL.table(DSL.name("game_design_draft_terminal_outcome")))) + .isZero(); + } + + private static List beginAndApplyOwners( + DraftCommitBinding binding, DraftAuthorizationFenceBinding account, Owner rejectedOwner) { + fixture.inTransaction(() -> fixture.coordinator().claim(binding, account)); + List outcomes = + binding.requiredOwners().stream() + .map( + owner -> + owner == rejectedOwner + ? rejectedOutcome(binding, owner) + : appliedOutcome(binding, owner)) + .toList(); + fixture.inTransaction( + () -> { + fixture.coordinator().claimApplicationSlot(binding); + for (DraftCommitCoordinatorRepository.OwnerOutcome outcome : outcomes) { + fixture.coordinator().markOwnerInProgress(binding, outcome.owner()); + fixture.coordinator().recordOwnerOutcome(binding, outcome); + } + return null; + }); + return outcomes; + } + + private static List allAppliedOutcomes( + DraftCommitBinding binding) { + return binding.requiredOwners().stream().map(owner -> appliedOutcome(binding, owner)).toList(); + } + + private static DraftCommitCoordinatorRepository.OwnerOutcome appliedOutcome( + DraftCommitBinding binding, Owner owner) { + List epochs = + binding.affectedUnits(owner).stream() + .map( + unit -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + return new DraftCommitCoordinatorRepository.OwnerOutcome( + owner, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + owner.name().toLowerCase(java.util.Locale.ROOT) + "-stipulated-result", + (owner.name() + " stipulated full producer result bytes").getBytes(StandardCharsets.UTF_8), + epochs); + } + + private static DraftCommitCoordinatorRepository.OwnerOutcome rejectedOutcome( + DraftCommitBinding binding, Owner owner) { + return new DraftCommitCoordinatorRepository.OwnerOutcome( + owner, + DraftCommitCoordinatorRepository.OwnerStatus.REJECTED, + binding.commitId(), + binding.digest(), + owner.name().toLowerCase(java.util.Locale.ROOT) + "-stipulated-rejection", + (owner.name() + " stipulated full rejection result bytes").getBytes(StandardCharsets.UTF_8), + List.of()); + } + + private static DraftCommitBinding binding(TargetProof target) { + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-7", + List.of( + new RevisionPayload("0", UUID.randomUUID(), Owner.WORLD_MANAGEMENT, "world change"), + new RevisionPayload("1", UUID.randomUUID(), Owner.ENTITY_MANAGEMENT, "entity change")), + List.of( + new AffectedUnit(Owner.WORLD_MANAGEMENT, "WORLD", "world-1", "ROOM", "room-1", "0"), + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, "ENTITY", "entity-1", "ACTOR", "actor-1", "0"))); + } + + private static DraftAuthorizationFenceBinding accountBinding( + DraftCommitBinding binding, String evidence) { + return accountBinding( + binding, UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), evidence); + } + + private static DraftAuthorizationFenceBinding accountBinding( + DraftCommitBinding binding, UUID operationId, UUID fenceId, UUID actorId, String evidence) { + return new DraftAuthorizationFenceBinding( + operationId, + binding.requestId(), + binding.commitId(), + fenceId, + actorId, + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.baseCommitId(), + "7", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of( + new SourceEvidence( + SourceKind.TENANT, + binding.target().canonicalTenantId().toString(), + null, + "1", + null, + null, + evidence.getBytes(StandardCharsets.UTF_8)))); + } + + private static String ownerVectorJson( + DraftCommitBinding binding, List outcomes) { + Map byOwner = + new java.util.EnumMap<>(Owner.class); + outcomes.forEach(outcome -> byOwner.put(outcome.owner(), outcome)); + List> vector = new ArrayList<>(); + for (Owner owner : binding.requiredOwners()) { + DraftCommitCoordinatorRepository.OwnerOutcome outcome = byOwner.get(owner); + Map item = new LinkedHashMap<>(); + item.put("owner", outcome.owner().name()); + item.put("status", outcome.status().name()); + item.put("commitId", outcome.commitId().toString()); + item.put("bindingDigest", outcome.bindingDigest()); + item.put("resultIdentity", outcome.resultIdentity()); + item.put("resultBytesBase64", Base64.getEncoder().encodeToString(outcome.resultBytes())); + item.put( + "appliedEpochs", + outcome.appliedEpochs().stream() + .map(GameDesignDraftTerminalOutcomePostgresIntegrationTest::epochMap) + .toList()); + vector.add(item); + } + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(vector)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalStateException( + "Fixture owner result vector cannot be canonicalized", exception); + } + } + + private static String appliedEpochsJson( + List epochs) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString( + epochs.stream() + .map(GameDesignDraftTerminalOutcomePostgresIntegrationTest::epochMap) + .toList())), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalStateException( + "Fixture applied epoch vector cannot be canonicalized", exception); + } + } + + private static Map epochMap(DraftCommitCoordinatorRepository.AppliedEpoch epoch) { + Map value = new LinkedHashMap<>(); + value.put("aggregateType", epoch.aggregateType()); + value.put("aggregateId", epoch.aggregateId()); + value.put("scopeType", epoch.scopeType()); + value.put("scopeId", epoch.scopeId()); + value.put("expectedEpoch", epoch.expectedEpoch()); + value.put("resultingEpoch", epoch.resultingEpoch()); + return value; + } + + private static FinalizeAttempt attempt(Supplier finalize) { + try { + fixture.inTransaction(finalize); + return new FinalizeAttempt(true, null); + } catch (RuntimeException exception) { + return new FinalizeAttempt(false, exception); + } + } + + private static void awaitStart(CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out coordinating concurrent terminal finalization"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while coordinating terminal finalization", exception); + } + } + + private static Fixture createFixture(MigrationVersion targetVersion) { + String schema = "gd_terminal_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setSchema(schema); + var flywayConfiguration = + Flyway.configure() + .dataSource(dataSource) + .placeholders(Map.of("serviceSchema", schema)) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE); + if (targetVersion != null) { + flywayConfiguration.target(targetVersion); + } + flywayConfiguration.locations("classpath:db/migration").load().migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Fixture( + schema, + dataSource, + dsl, + transaction, + new GameRepository(dsl), + new VersionRepository(dsl), + new DraftCommitCoordinatorRepository(dsl)); + } + + private record FinalizeAttempt(boolean succeeded, RuntimeException failure) {} + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transaction, + GameRepository games, + VersionRepository versions, + DraftCommitCoordinatorRepository coordinator) { + TargetProof newTarget() { + String tenantKey = "d-" + UUID.randomUUID().toString().replace("-", ""); + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName("Game Design terminal evidence source"); + game.setDescription("Canonical Version fixture"); + Game savedGame = Objects.requireNonNull(transaction.execute(status -> games.save(game))); + + Version version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(net.firedevops.firemud.gamedesign.model.VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + Version savedVersion = + Objects.requireNonNull(transaction.execute(status -> versions.save(version))); + return new TargetProof( + savedVersion.getCanonicalTenantId(), + savedVersion.getCanonicalVersionId(), + savedVersion.getId(), + savedVersion.getTenantId(), + savedVersion.getIdentitySourceGameRowId(), + savedVersion.getIdentitySourceGameTenantKey(), + savedVersion.getIdentitySourceProvenanceKind()); + } + + T inTransaction(Supplier action) { + return transaction.execute(status -> action.get()); + } + + void migrateToLatest() { + Flyway.configure() + .dataSource(dataSource) + .placeholders(Map.of("serviceSchema", schema)) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .locations("classpath:db/migration") + .load() + .migrate(); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..25221e737f --- /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 registersAndReadsExactFreshAndRetainedV29ToV30Sources() { + 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/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java new file mode 100644 index 0000000000..53367c29d4 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -0,0 +1,1075 @@ +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.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.Table; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.jooq.impl.DataSourceConnectionProvider; +import org.jooq.impl.DefaultConfiguration; +import org.junit.jupiter.api.Test; +import org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider; +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; +import tools.jackson.databind.ObjectMapper; + +@Testcontainers(disabledWithoutDocker = true) +class PublishedReleaseCanonicalIdentityIntegrationTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String OTHER_MANIFEST_HASH = "sha256:" + "b".repeat(64); + private static final String GENERATION_CONFIG_REVISION = "generation-1"; + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final MigrationVersion V35 = MigrationVersion.fromVersion("35"); + private static final MigrationVersion V35_1 = MigrationVersion.fromVersion("35.1"); + private static final MigrationVersion V35_2 = MigrationVersion.fromVersion("35.2"); + private static final MigrationVersion V36 = MigrationVersion.fromVersion("36"); + private static final MigrationVersion V38 = MigrationVersion.fromVersion("38"); + private static final Table VERSION = DSL.table(DSL.name("version")); + private static final Table RELEASE_BUNDLE = DSL.table(DSL.name("published_release_bundle")); + private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + DSL.field(DSL.name("published_release_bundle_ref"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field MANIFEST_SCHEMA_VERSION = + DSL.field(DSL.name("manifest_schema_version"), Integer.class); + private static final Field ARTIFACT_DIGESTS_JSON = + DSL.field(DSL.name("artifact_digests_json"), String.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void migrationLeavesRetainedReleaseTupleAndXminUnchangedAndUnmapped() { + Fixture fixture = fixture(V35); + Game game = saveGame(fixture, "retained-release-tenant"); + Long retainedVersionId = insertRetainedVersion(fixture.dsl(), game.getTenantId()); + Long retainedBundleId = + insertRetainedBundle(fixture.dsl(), game.getTenantId(), retainedVersionId); + Map retainedTupleBefore = retainedTuple(fixture.dsl(), retainedBundleId); + String retainedXminBefore = bundleXmin(fixture.dsl(), retainedBundleId); + + migrate(fixture.dataSource(), fixture.schema(), V35_1); + migrate(fixture.dataSource(), fixture.schema(), V35_2); + + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .dsl() + .select(CANONICAL_TENANT_ID, CANONICAL_VERSION_ID) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); + assertThat(row.get(CANONICAL_VERSION_ID)).isNull(); + }); + migrate(fixture.dataSource(), fixture.schema(), V36); + + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .dsl() + .select(CANONICAL_TENANT_ID, CANONICAL_VERSION_ID) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); + assertThat(row.get(CANONICAL_VERSION_ID)).isNull(); + }); + assertThat( + fixture + .dsl() + .select(PUBLISHED_RELEASE_BUNDLE_REF) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne(PUBLISHED_RELEASE_BUNDLE_REF)) + .isNull(); + + // V38 only adds nullable proof columns; it must not rewrite or invent proof for this row. + migrate(fixture.dataSource(), fixture.schema(), V38); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .dsl() + .select(MANIFEST_SCHEMA_VERSION, ARTIFACT_DIGESTS_JSON) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get(MANIFEST_SCHEMA_VERSION)).isNull(); + assertThat(row.get(ARTIFACT_DIGESTS_JSON)).isNull(); + }); + migrate(fixture.dataSource(), fixture.schema(), null); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); + assertThat( + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT world_published_start_location_evidence_json FROM published_release_bundle WHERE id = ?", + retainedBundleId)) + .get(0)) + .isNull(); + PublishedReleaseBundle retained = + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), retainedVersionId) + .orElseThrow(); + assertThat(retained.getCanonicalTenantId()).isNull(); + assertThat(retained.getCanonicalVersionId()).isNull(); + assertThat(retained.getPublishedReleaseBundleRef()).isNull(); + assertThat(retained.getManifestSchemaVersion()).isNull(); + assertThat(retained.getArtifactDigestsJson()).isNull(); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(retained)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + assertThatThrownBy( + () -> + fixture + .releaseBundleRepository() + .save(bundle(game.getTenantId(), retainedVersionId))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + + @Test + void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTransaction() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "fresh-release-source"); + Game other = saveGame(fixture, "other-release-source"); + Version version = saveVersion(fixture, owner); + + PublishedReleaseBundle saved = + fixture.releaseBundleRepository().save(bundle(owner.getTenantId(), version.getId())); + assertThat(saved.getCanonicalTenantId()).isEqualTo(owner.getCanonicalTenantId()); + assertThat(saved.getCanonicalVersionId()).isEqualTo(version.getCanonicalVersionId()); + assertThat(saved.getPublishedReleaseBundleRef()).isNotBlank(); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + + Map bundleTupleBeforeSourceMutation = + releaseBundleTuple(fixture.dsl(), saved.getId()); + String bundleXminBeforeSourceMutation = bundleXmin(fixture.dsl(), saved.getId()); + String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); + String gameXminBefore = gameXmin(fixture.dsl(), owner.getId()); + String otherGameXminBefore = gameXmin(fixture.dsl(), other.getId()); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_TENANT_ID, other.getCanonicalTenantId()) + .where(ID.eq(version.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identity and its tenant source are immutable"); + + assertThat(releaseBundleTuple(fixture.dsl(), saved.getId())) + .isEqualTo(bundleTupleBeforeSourceMutation); + assertThat(bundleXmin(fixture.dsl(), saved.getId())).isEqualTo(bundleXminBeforeSourceMutation); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + assertThat(versionXmin(fixture.dsl(), version.getId())).isEqualTo(versionXminBefore); + assertThat(gameXmin(fixture.dsl(), owner.getId())).isEqualTo(gameXminBefore); + assertThat(gameXmin(fixture.dsl(), other.getId())).isEqualTo(otherGameXminBefore); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(saved); + } + + @Test + void repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "outer-release-rollback-owner"); + Version version = saveVersion(fixture, owner); + String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); + String gameXminBefore = gameXmin(fixture.dsl(), owner.getId()); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> { + PublishedReleaseBundle saved = + fixture + .releaseBundleRepository() + .save(bundle(owner.getTenantId(), version.getId())); + assertThat(saved.getCanonicalTenantId()) + .isEqualTo(owner.getCanonicalTenantId()); + assertThat(saved.getCanonicalVersionId()) + .isEqualTo(version.getCanonicalVersionId()); + assertThat(saved.getPublishedReleaseBundleRef()).isNotBlank(); + Version publishingVersion = + fixture + .versionRepository() + .findByTenantIdAndId(owner.getTenantId(), version.getId()) + .orElseThrow(); + publishingVersion.setVersionState(VersionLifecycleState.PUBLISHED); + publishingVersion.setVersionStateEpoch( + publishingVersion.getVersionStateEpoch() + 1L); + fixture.versionRepository().save(publishingVersion); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + assertThat( + fixture + .versionRepository() + .findByTenantIdAndId(owner.getTenantId(), version.getId()) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.PUBLISHED); + throw new IllegalStateException("simulate failed outer publication"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("simulate failed outer publication"); + + assertThat(bundleCount(fixture.dsl())).isZero(); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId())) + .isEmpty(); + assertThat(versionXmin(fixture.dsl(), version.getId())).isEqualTo(versionXminBefore); + assertThat(gameXmin(fixture.dsl(), owner.getId())).isEqualTo(gameXminBefore); + Version exactVersionAfterRollback = + fixture + .versionRepository() + .findByTenantIdAndId(owner.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(exactVersionAfterRollback.getCanonicalTenantId()) + .isEqualTo(owner.getCanonicalTenantId()); + assertThat(exactVersionAfterRollback.getCanonicalVersionId()) + .isEqualTo(version.getCanonicalVersionId()); + assertThat(exactVersionAfterRollback.getVersionState()).isEqualTo(VersionLifecycleState.DRAFT); + assertThat(exactVersionAfterRollback.getVersionStateEpoch()) + .isEqualTo(version.getVersionStateEpoch()); + assertThat(exactVersionAfterRollback.getIdentitySourceGameRowId()).isEqualTo(owner.getId()); + assertThat(exactVersionAfterRollback.getIdentitySourceGameTenantKey()) + .isEqualTo(owner.getTenantId()); + } + + @Test + void deniesWrongTenantNilAndSubstitutedCallerOrDatabaseIdentityWithoutGrowingBundles() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "denied-release-owner"); + Game other = saveGame(fixture, "denied-release-other"); + Version version = saveVersion(fixture, owner); + + assertThatThrownBy( + () -> + fixture + .releaseBundleRepository() + .save(bundle(other.getTenantId(), version.getId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No exact canonical Game Design source association"); + + PublishedReleaseBundle substitutedTenant = bundle(owner.getTenantId(), version.getId()); + substitutedTenant.setCanonicalTenantId(other.getCanonicalTenantId()); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(substitutedTenant)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Caller-supplied canonical release identity"); + + PublishedReleaseBundle substitutedVersion = bundle(owner.getTenantId(), version.getId()); + substitutedVersion.setCanonicalVersionId(UUID.randomUUID()); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(substitutedVersion)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Caller-supplied canonical release identity"); + + assertThatThrownBy( + () -> + insertRawBundle( + fixture.dsl(), + owner.getTenantId(), + version.getId(), + NIL_UUID, + version.getCanonicalVersionId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("non-nil canonical identity"); + assertThatThrownBy( + () -> + insertRawBundle( + fixture.dsl(), + owner.getTenantId(), + version.getId(), + other.getCanonicalTenantId(), + version.getCanonicalVersionId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("does not match its exact Version and Game source"); + assertThatThrownBy( + () -> + insertRawBundle( + fixture.dsl(), + other.getTenantId(), + version.getId(), + owner.getCanonicalTenantId(), + version.getCanonicalVersionId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("does not match its exact Version and Game source"); + assertThat(bundleCount(fixture.dsl())).isZero(); + } + + @Test + void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeDeleted() { + Fixture fixture = fixture(V35); + Game game = saveGame(fixture, "release-retention-owner"); + Long retainedVersionId = insertRetainedVersion(fixture.dsl(), game.getTenantId()); + Long retainedBundleId = + insertRetainedBundle(fixture.dsl(), game.getTenantId(), retainedVersionId); + Map retainedTupleBeforeIdentityMigration = + retainedTuple(fixture.dsl(), retainedBundleId); + String retainedXminBeforeIdentityMigration = bundleXmin(fixture.dsl(), retainedBundleId); + migrate(fixture.dataSource(), fixture.schema(), V35_1); + migrate(fixture.dataSource(), fixture.schema(), V35_2); + + Map retainedTupleBeforeV36 = retainedTuple(fixture.dsl(), retainedBundleId); + String retainedXminBeforeV36 = bundleXmin(fixture.dsl(), retainedBundleId); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)) + .isEqualTo(retainedTupleBeforeIdentityMigration); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)) + .isEqualTo(retainedXminBeforeIdentityMigration); + assertThat( + fixture + .dsl() + .select(CANONICAL_TENANT_ID, CANONICAL_VERSION_ID) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); + assertThat(row.get(CANONICAL_VERSION_ID)).isNull(); + }); + migrate(fixture.dataSource(), fixture.schema(), V36); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBeforeV36); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBeforeV36); + assertThat( + fixture + .dsl() + .select(PUBLISHED_RELEASE_BUNDLE_REF) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne(PUBLISHED_RELEASE_BUNDLE_REF)) + .isNull(); + + Map retainedTupleBeforeV38 = retainedTuple(fixture.dsl(), retainedBundleId); + String retainedXminBeforeV38 = bundleXmin(fixture.dsl(), retainedBundleId); + migrate(fixture.dataSource(), fixture.schema(), V38); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBeforeV38); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBeforeV38); + assertThat( + fixture + .dsl() + .select( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + PUBLISHED_RELEASE_BUNDLE_REF, + MANIFEST_SCHEMA_VERSION, + ARTIFACT_DIGESTS_JSON) + .from(RELEASE_BUNDLE) + .where(ID.eq(retainedBundleId)) + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); + assertThat(row.get(CANONICAL_VERSION_ID)).isNull(); + assertThat(row.get(PUBLISHED_RELEASE_BUNDLE_REF)).isNull(); + assertThat(row.get(MANIFEST_SCHEMA_VERSION)).isNull(); + assertThat(row.get(ARTIFACT_DIGESTS_JSON)).isNull(); + }); + + Version mappedVersion = saveVersion(fixture, game); + migrate(fixture.dataSource(), fixture.schema(), null); + assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBeforeV38); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBeforeV38); + PublishedReleaseBundle mapped = + fixture.releaseBundleRepository().save(bundle(game.getTenantId(), mappedVersion.getId())); + Map mappedTupleBefore = releaseBundleTuple(fixture.dsl(), mapped.getId()); + String mappedXminBefore = bundleXmin(fixture.dsl(), mapped.getId()); + Map retainedTupleBefore = releaseBundleTuple(fixture.dsl(), retainedBundleId); + String retainedXminBefore = bundleXmin(fixture.dsl(), retainedBundleId); + + PublishedReleaseBundle exactReadback = + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), mappedVersion.getId()) + .orElseThrow(); + assertThat(exactReadback).usingRecursiveComparison().isEqualTo(mapped); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(exactReadback)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + exactReadback.setManifestHash(OTHER_MANIFEST_HASH); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(exactReadback)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(DSL.field(DSL.name("manifest_hash"), String.class), OTHER_MANIFEST_HASH) + .where(ID.eq(mapped.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE published_release_bundle SET manifest_hash = manifest_hash " + + "WHERE id = ?", + mapped.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_TENANT_ID, UUID.randomUUID()) + .where(ID.eq(mapped.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .where(ID.eq(mapped.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(DSL.field(DSL.name("manifest_hash"), String.class), OTHER_MANIFEST_HASH) + .where(ID.eq(retainedBundleId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(PUBLISHED_RELEASE_BUNDLE_REF, "attempted-retained-release-reference") + .where(ID.eq(retainedBundleId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_TENANT_ID, game.getCanonicalTenantId()) + .set(CANONICAL_VERSION_ID, mappedVersion.getCanonicalVersionId()) + .where(ID.eq(retainedBundleId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle attestation is immutable"); + + PublishedReleaseBundle retained = + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), retainedVersionId) + .orElseThrow(); + assertThat(retained.getCanonicalTenantId()).isNull(); + assertThat(retained.getCanonicalVersionId()).isNull(); + assertThat(retained.getPublishedReleaseBundleRef()).isNull(); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(retained)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + retained.setCanonicalTenantId(game.getCanonicalTenantId()); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(retained)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Published release bundle is immutable"); + + assertThat(releaseBundleTuple(fixture.dsl(), mapped.getId())).isEqualTo(mappedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), mapped.getId())).isEqualTo(mappedXminBefore); + assertThat(releaseBundleTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBefore); + assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), mappedVersion.getId()) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(mapped); + PublishedReleaseBundle retainedAfterAttempts = + fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(game.getTenantId(), retainedVersionId) + .orElseThrow(); + assertThat(retainedAfterAttempts.getCanonicalTenantId()).isNull(); + assertThat(retainedAfterAttempts.getCanonicalVersionId()).isNull(); + assertThat(retainedAfterAttempts.getPublishedReleaseBundleRef()).isNull(); + assertThat(retainedAfterAttempts.getManifestHash()).isEqualTo(MANIFEST_HASH); + + assertThatThrownBy( + () -> fixture.dsl().deleteFrom(RELEASE_BUNDLE).where(ID.eq(mapped.getId())).execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("published release bundle metadata is retained"); + assertThatThrownBy( + () -> fixture.dsl().execute("TRUNCATE TABLE published_release_bundle CASCADE")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("metadata cannot be truncated"); + assertThat(bundleCount(fixture.dsl())).isEqualTo(2); + } + + @Test + void selectorV2RetainsCompleteOriginalEvidenceAndExactlyReplaysWithoutReplacingRelease() + throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selector-release-source"); + Version version = saveVersion(fixture, owner); + var operation = selectorOperation(fixture, version); + WorldPublishedStartLocationEvidence evidence = operation.world(); + PublishedReleaseBundle requested = selectorBundle(version, evidence); + PublishedReleaseBundle saved = + fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> fixture.releaseBundleRepository().save(requested))); + String beforeXmin = bundleXmin(fixture.dsl(), saved.getId()); + String original = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); + assertThat(saved.getWorldPublishedStartLocationEvidenceJson()).isEqualTo(original); + PublishedReleaseBundle independent = + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow(); + assertThat( + WorldPublishedStartLocationEvidence.fromStored( + independent + .getWorldPublishedStartLocationEvidenceJson() + .getBytes(StandardCharsets.UTF_8)) + .canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + assertThat(fixture.releaseBundleRepository().save(selectorBundle(version, evidence))) + .usingRecursiveComparison() + .isEqualTo(saved); + assertThat(bundleXmin(fixture.dsl(), saved.getId())).isEqualTo(beforeXmin); + + PublishedReleaseBundle changed = selectorBundle(version, evidence); + changed.setGenerationConfigRevision("changed-generation"); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE published_release_bundle SET world_published_start_location_evidence_json = NULL WHERE id = ?", + saved.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("DELETE FROM published_release_bundle WHERE id = ?", saved.getId())) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("retained"); + assertThat(bundleXmin(fixture.dsl(), saved.getId())).isEqualTo(beforeXmin); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + + @Test + void concurrentExactSelectorRetriesCommitOneImmutableBundle() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selector-concurrent-source"); + Version version = saveVersion(fixture, owner); + var operation = selectorOperation(fixture, version); + var evidence = operation.world(); + var start = new java.util.concurrent.CountDownLatch(1); + try (var executor = java.util.concurrent.Executors.newFixedThreadPool(2)) { + java.util.concurrent.Callable save = + () -> { + start.await(); + return fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> + new PublishedReleaseBundleRepository(fixture.dsl()) + .save(selectorBundle(version, evidence)))); + }; + var first = executor.submit(save); + var second = executor.submit(save); + start.countDown(); + var one = first.get(20, java.util.concurrent.TimeUnit.SECONDS); + var two = second.get(20, java.util.concurrent.TimeUnit.SECONDS); + assertThat(two).usingRecursiveComparison().isEqualTo(one); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + } + + @Test + void sqlGuardRejectsMissingInjectedAndMismatchedSelectorBindingsWithoutAnyRelease() + throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selector-denial-source"); + Version version = saveVersion(fixture, owner); + var operation = selectorOperation(fixture, version); + WorldPublishedStartLocationEvidence evidence = operation.world(); + var json = new ObjectMapper(); + String original = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); + String participants = + json.writeValueAsString( + PublishedWorldSelectorFixtures.participants(version.getId(), evidence)); + var originalRequest = json.readTree(original).path("request"); + assertThat(originalRequest.path("versionStateEpoch").isTextual()).isTrue(); + assertThat(originalRequest.path("versionStateEpoch").asText()).matches("[1-9][0-9]*"); + assertThatThrownBy(() -> insertRawSelector(fixture, version, "v2", null, participants)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> insertRawSelector(fixture, version, "v1", original, participants)) + .isInstanceOf(DataAccessException.class); + for (String invalidEpoch : List.of("0", "01", "-1", "9223372036854775808")) { + var root = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + ((tools.jackson.databind.node.ObjectNode) root.get("request")) + .put("versionStateEpoch", invalidEpoch); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, version, "v2", json.writeValueAsString(root), participants)) + .isInstanceOf(DataAccessException.class); + } + var numericEpoch = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + ((tools.jackson.databind.node.ObjectNode) numericEpoch.get("request")) + .put("versionStateEpoch", 1L); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, version, "v2", json.writeValueAsString(numericEpoch), participants)) + .isInstanceOf(DataAccessException.class); + for (String field : + List.of( + "canonicalTenantId", + "canonicalVersionId", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "intakeRequestId")) { + var root = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + var request = (tools.jackson.databind.node.ObjectNode) root.get("request"); + if (field.equals("digestSchemaVersion")) request.put(field, 2); + else + request.put( + field, + field.endsWith("Id") || field.equals("publicationFence") + ? UUID.randomUUID().toString() + : "changed"); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, version, "v2", json.writeValueAsString(root), participants)) + .isInstanceOf(DataAccessException.class); + } + for (String field : + List.of( + "selectorReceiptBytesBase64", + "originalAccountBindingBytesBase64", + "appliedResultBytesBase64")) { + var root = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + root.remove(field); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, version, "v2", json.writeValueAsString(root), participants)) + .isInstanceOf(DataAccessException.class); + } + assertThatThrownBy(() -> insertRawSelector(fixture, version, "v2", original, "[]")) + .isInstanceOf(DataAccessException.class); + var changedParticipants = (tools.jackson.databind.node.ArrayNode) json.readTree(participants); + ((tools.jackson.databind.node.ObjectNode) changedParticipants.get(0)) + .put("contentDigest", "c".repeat(64)); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, version, "v2", original, json.writeValueAsString(changedParticipants))) + .isInstanceOf(DataAccessException.class); + assertThat(bundleCount(fixture.dsl())).isZero(); + fixture + .transactionTemplate() + .executeWithoutResult( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> { + insertRawSelector(fixture, version, "v2", original, participants); + return fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(version.getTenantId(), version.getId()) + .orElseThrow(); + })); + assertThat( + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(version.getTenantId(), version.getId()) + .orElseThrow() + .getWorldPublishedStartLocationEvidenceJson()) + .isEqualTo(original); + } + + private WorldPublishedStartLocationEvidence selectorEvidence(Version version) throws Exception { + return PublishedWorldSelectorFixtures.evidence( + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind())); + } + + /** + * ISOLATED upstream sources/freeze; synchronized selection and terminal GD rows are actual DB + * writes. + */ + private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation + selectorOperation(Fixture fixture, Version version) { + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + return fixture + .transactionTemplate() + .execute( + status -> { + try { + return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.retain( + fixture.dsl(), target, version.getVersionStateEpoch()); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + + private PublishedReleaseBundle selectorBundle( + Version version, WorldPublishedStartLocationEvidence evidence) { + PublishedReleaseBundle bundle = bundle(version.getTenantId(), version.getId()); + bundle.setAttestationSchemaVersion("v2"); + bundle.setPublishWorkflowId(evidence.request().publishWorkflowId()); + bundle.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString( + PublishedWorldSelectorFixtures.participants(version.getId(), evidence))); + bundle.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); + return bundle; + } + + private void insertRawSelector( + Fixture fixture, Version version, String schema, String evidence, String participants) { + var operationRow = + fixture + .dsl() + .fetchOne( + "SELECT publish_workflow_id FROM game_design_publication_operation WHERE tenant_id = ? AND version_id = ?", + version.getTenantId(), + version.getId()); + if (operationRow == null) { + throw new IllegalStateException( + "Selected publication operation row is absent for release selector fixture"); + } + fixture + .dsl() + .execute( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, " + + "canonical_tenant_id, canonical_version_id, published_release_bundle_ref, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, generation_config_revision, manifest_schema_version, artifact_digests_json, " + + "required_manifest_asset_keys_json, participant_digests_json, command_definitions_json, script_only, " + + "world_published_start_location_evidence_json) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", + version.getTenantId(), + version.getId(), + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + UUID.randomUUID().toString(), + schema, + operationRow.get(0, String.class), + MANIFEST_HASH, + GENERATION_CONFIG_REVISION, + participants, + evidence); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "game_design_release_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, target); + return fixtureFromMigratedSchema(schema, dataSource); + } + + private Fixture fixtureFromMigratedSchema(String schema, DriverManagerDataSource dataSource) { + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + DefaultConfiguration jooqConfiguration = new DefaultConfiguration(); + jooqConfiguration.set(SQLDialect.POSTGRES); + jooqConfiguration.set( + new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(dataSource))); + jooqConfiguration.set(new SpringTransactionProvider(transactionManager)); + DSLContext dsl = DSL.using(jooqConfiguration); + GameRepository gameRepository = new GameRepository(dsl); + VersionRepository versionRepository = new VersionRepository(dsl); + PublishedReleaseBundleRepository releaseBundleRepository = + new PublishedReleaseBundleRepository(dsl); + return new Fixture( + schema, + dataSource, + dsl, + transactionTemplate, + gameRepository, + versionRepository, + releaseBundleRepository); + } + + 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 Game saveGame(Fixture fixture, String tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName("Published Release Identity Owner"); + game.setDescription("Exact immutable Game source association"); + return fixture.transactionTemplate().execute(status -> fixture.gameRepository().save(game)); + } + + private Version saveVersion(Fixture fixture, Game game) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version.setNotes("fresh release source"); + return fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version)); + } + + private Long insertRetainedVersion(DSLContext dsl, String tenantId) { + return dsl.resultQuery( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes) " + + "VALUES (?, 4, 'FAILED', 3, NULL, NULL, FALSE, 'retained release source') " + + "RETURNING id", + tenantId) + .fetchOne(0, Long.class); + } + + private Long insertRetainedBundle(DSLContext dsl, String tenantId, Long versionId) { + return dsl.resultQuery( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, " + + "attestation_schema_version, publish_workflow_id, manifest_hash, " + + "generation_config_revision, required_manifest_asset_keys_json, " + + "participant_digests_json, command_definitions_json, script_only, " + + "script_patch_version) VALUES (?, ?, 4, 'v1', 'retained-workflow', " + + "?, 'retained-config', '[\"asset-a\"]', '[]', '[]', FALSE, NULL) " + + "RETURNING id", + tenantId, + versionId, + MANIFEST_HASH) + .fetchOne(0, Long.class); + } + + private PublishedReleaseBundle bundle(String tenantId, Long versionId) { + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(tenantId); + bundle.setVersionId(versionId); + bundle.setVersionNumber(1); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId("workflow-" + versionId); + bundle.setManifestHash(MANIFEST_HASH); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson("[]"); + bundle.setGenerationConfigRevision(GENERATION_CONFIG_REVISION); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + return bundle; + } + + private void insertRawBundle( + DSLContext dsl, + String tenantId, + Long versionId, + UUID canonicalTenantId, + UUID canonicalVersionId) { + dsl.execute( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, " + + "attestation_schema_version, publish_workflow_id, manifest_hash, " + + "generation_config_revision, required_manifest_asset_keys_json, " + + "participant_digests_json, command_definitions_json, manifest_schema_version, " + + "artifact_digests_json, script_only, " + + "canonical_tenant_id, canonical_version_id, published_release_bundle_ref) " + + "VALUES (?, ?, 1, 'v1', 'direct-write-test', ?, 'generation-1', " + + "'[]', '[]', '[]', 1, '[]', FALSE, ?, ?, ?)", + tenantId, + versionId, + MANIFEST_HASH, + canonicalTenantId, + canonicalVersionId, + UUID.randomUUID().toString()); + } + + private long bundleCount(DSLContext dsl) { + return dsl.fetchCount(RELEASE_BUNDLE); + } + + private Map retainedTuple(DSLContext dsl, Long bundleId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, required_manifest_asset_keys_json, " + + "script_only, script_patch_version, published_at, " + + "generation_config_revision, participant_digests_json, " + + "command_definitions_json FROM published_release_bundle WHERE id = ?", + bundleId), + "Retained release bundle query returned no row") + .intoMap(); + } + + private Map releaseBundleTuple(DSLContext dsl, Long bundleId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, tenant_id, version_id, canonical_tenant_id, canonical_version_id, " + + "published_release_bundle_ref, " + + "version_number, attestation_schema_version, publish_workflow_id, " + + "manifest_hash, generation_config_revision, " + + "required_manifest_asset_keys_json, participant_digests_json, " + + "command_definitions_json, script_only, script_patch_version, published_at, " + + "manifest_schema_version, artifact_digests_json " + + "FROM published_release_bundle WHERE id = ?", + bundleId), + "Published release bundle tuple query returned no row") + .intoMap(); + } + + private String bundleXmin(DSLContext dsl, Long bundleId) { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS xmin FROM published_release_bundle WHERE id = ?", bundleId), + "Published release bundle xmin query returned no row"); + return Objects.requireNonNull( + row.get("xmin", String.class), "Published release bundle xmin readback returned null"); + } + + private String versionXmin(DSLContext dsl, Long versionId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM version WHERE id = ?", versionId), + "Version xmin query returned no row"); + return Objects.requireNonNull(row.get("xmin", String.class)); + } + + private String gameXmin(DSLContext dsl, Long gameId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM game WHERE id = ?", gameId), + "Game xmin query returned no row"); + return Objects.requireNonNull(row.get("xmin", String.class)); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transactionTemplate, + GameRepository gameRepository, + VersionRepository versionRepository, + PublishedReleaseBundleRepository releaseBundleRepository) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java new file mode 100644 index 0000000000..3895f262de --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java @@ -0,0 +1,508 @@ +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.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.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 VersionCanonicalIdentityIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final MigrationVersion V35 = MigrationVersion.fromVersion("35"); + private static final Table VERSION = DSL.table(DSL.name("version")); + private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field VERSION_NUMBER = + DSL.field(DSL.name("version_number"), Integer.class); + private static final Field VERSION_STATE = + DSL.field(DSL.name("version_state"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final Field SCRIPT_PATCH_VERSION = + DSL.field(DSL.name("script_patch_version"), String.class); + private static final Field BASE_VERSION_ID = + DSL.field(DSL.name("base_version_id"), Long.class); + private static final Field IS_SCRIPT_ONLY = + DSL.field(DSL.name("is_script_only"), Boolean.class); + private static final Field NOTES = DSL.field(DSL.name("notes"), String.class); + private static final Field CREATED_AT = + DSL.field(DSL.name("created_at"), java.sql.Timestamp.class); + private static final Field UPDATED_AT = + DSL.field(DSL.name("updated_at"), java.sql.Timestamp.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field IDENTITY_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("identity_source_game_row_id"), Long.class); + private static final Field IDENTITY_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("identity_source_game_tenant_key"), String.class); + private static final Field IDENTITY_SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("identity_source_provenance_kind"), String.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void v35_1PreservesRetainedVersionHistoryAndLeavesIdentityUnmapped() { + Fixture fixture = fixture(V35); + Game game = saveGame(fixture, "retained-version-source"); + Long retainedVersionId = insertRetainedVersion(fixture.dsl(), game.getTenantId()); + Map retainedFieldsBefore = retainedFields(fixture.dsl(), retainedVersionId); + String retainedXminBefore = versionXmin(fixture.dsl(), retainedVersionId); + + migrate(fixture.dataSource(), fixture.schema(), null); + + assertThat(retainedFields(fixture.dsl(), retainedVersionId)).isEqualTo(retainedFieldsBefore); + assertThat(versionXmin(fixture.dsl(), retainedVersionId)).isEqualTo(retainedXminBefore); + assertThat( + fixture + .dsl() + .select(CANONICAL_VERSION_ID) + .from(VERSION) + .where(ID.eq(retainedVersionId)) + .fetchOne(CANONICAL_VERSION_ID)) + .isNull(); + assertThat( + fixture + .dsl() + .select(CANONICAL_TENANT_ID) + .from(VERSION) + .where(ID.eq(retainedVersionId)) + .fetchOne(CANONICAL_TENANT_ID)) + .isNull(); + assertThat( + fixture + .dsl() + .select(IDENTITY_SOURCE_GAME_ROW_ID) + .from(VERSION) + .where(ID.eq(retainedVersionId)) + .fetchOne(IDENTITY_SOURCE_GAME_ROW_ID)) + .isNull(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + game.getCanonicalTenantId(), UUID.randomUUID())) + .isEmpty(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .set(CANONICAL_TENANT_ID, game.getCanonicalTenantId()) + .set(IDENTITY_SOURCE_GAME_ROW_ID, game.getId()) + .set(IDENTITY_SOURCE_GAME_TENANT_KEY, game.getTenantId()) + .set(IDENTITY_SOURCE_PROVENANCE_KIND, "NEW_GAME_ROW") + .where(ID.eq(retainedVersionId)) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("retained Version rows cannot be assigned a canonical identity"); + } + + @Test + void savePersistsAndReadsBackFreshCanonicalIdentityAcrossUpdate() { + Fixture fixture = fixture(null); + Game game = saveGame(fixture, "fresh-version-source"); + + Version inserted = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(game))); + assertThat(inserted).isNotNull(); + assertThat(inserted.getCanonicalVersionId()).isNotNull().isNotEqualTo(NIL_UUID); + assertThat(inserted.getCanonicalTenantId()).isEqualTo(game.getCanonicalTenantId()); + assertThat(inserted.getIdentitySourceGameRowId()).isEqualTo(game.getId()); + assertThat(inserted.getIdentitySourceGameTenantKey()).isEqualTo(game.getTenantId()); + assertThat(inserted.getIdentitySourceProvenanceKind()).isEqualTo("NEW_GAME_ROW"); + + Version exactRead = + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + game.getCanonicalTenantId(), inserted.getCanonicalVersionId()) + .orElseThrow(); + assertIdentityMatches(exactRead, game, inserted.getCanonicalVersionId()); + assertIdentityMatches( + fixture.versionRepository().findById(inserted.getId()).orElseThrow(), + game, + inserted.getCanonicalVersionId()); + + inserted.setNotes("updated without replacing owner identity"); + Version updated = + fixture.transactionTemplate().execute(status -> fixture.versionRepository().save(inserted)); + assertThat(updated).isNotNull(); + assertThat(updated.getNotes()).isEqualTo("updated without replacing owner identity"); + assertIdentityMatches(updated, game, inserted.getCanonicalVersionId()); + assertIdentityMatches( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + game.getCanonicalTenantId(), inserted.getCanonicalVersionId()) + .orElseThrow(), + game, + inserted.getCanonicalVersionId()); + } + + @Test + void newVersionIdentityUsesExactRetainedGameSourceProvenance() { + Fixture fixture = fixtureWithRetainedGame(); + Game retainedGame = fixture.gameRepository().findByTenantId("retained-version-game-source"); + assertThat(retainedGame).isNotNull(); + + Version saved = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(retainedGame))); + + assertThat(saved).isNotNull(); + assertThat(saved.getCanonicalVersionId()).isNotNull().isNotEqualTo(NIL_UUID); + assertThat(saved.getIdentitySourceProvenanceKind()).isEqualTo("RETAINED_GAME_V29"); + assertIdentityMatches( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + retainedGame.getCanonicalTenantId(), saved.getCanonicalVersionId()) + .orElseThrow(), + retainedGame, + saved.getCanonicalVersionId(), + "RETAINED_GAME_V29"); + } + + @Test + void canonicalLookupRejectsWrongTenantMissingAndNilIdsWithoutMutation() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "lookup-version-owner"); + Game other = saveGame(fixture, "lookup-version-other"); + Version saved = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(owner))); + assertThat(saved).isNotNull(); + String versionXminBefore = versionXmin(fixture.dsl(), saved.getId()); + String ownerXminBefore = gameXmin(fixture.dsl(), owner.getId()); + String otherXminBefore = gameXmin(fixture.dsl(), other.getId()); + + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + other.getCanonicalTenantId(), saved.getCanonicalVersionId())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + owner.getCanonicalTenantId(), UUID.randomUUID())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId(owner.getCanonicalTenantId(), null)) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId(null, saved.getCanonicalVersionId())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + NIL_UUID, saved.getCanonicalVersionId())) + .isEmpty(); + assertThat( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + owner.getCanonicalTenantId(), NIL_UUID)) + .isEmpty(); + assertIdentityMatches( + fixture + .versionRepository() + .findByCanonicalTenantIdAndCanonicalVersionId( + owner.getCanonicalTenantId(), saved.getCanonicalVersionId()) + .orElseThrow(), + owner, + saved.getCanonicalVersionId()); + + assertThat(versionXmin(fixture.dsl(), saved.getId())).isEqualTo(versionXminBefore); + assertThat(gameXmin(fixture.dsl(), owner.getId())).isEqualTo(ownerXminBefore); + assertThat(gameXmin(fixture.dsl(), other.getId())).isEqualTo(otherXminBefore); + } + + @Test + void databaseRejectsIdentityMutationNilIdentityAndMismatchedSource() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "mutation-version-owner"); + Game other = saveGame(fixture, "mutation-version-other"); + Version saved = + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(version(owner))); + assertThat(saved).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .where(ID.eq(saved.getId())) + .execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identity and its tenant source are immutable"); + assertThatThrownBy( + () -> fixture.dsl().deleteFrom(VERSION).where(ID.eq(saved.getId())).execute()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identity is immutable"); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO version (tenant_id, version_number, version_state, " + + "version_state_epoch, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) " + + "VALUES (?, 2, 'DRAFT', 1, ?, ?, ?, ?, ?)", + owner.getTenantId(), + NIL_UUID, + owner.getCanonicalTenantId(), + owner.getId(), + owner.getTenantId(), + "NEW_GAME_ROW")) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO version (tenant_id, version_number, version_state, " + + "version_state_epoch, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) " + + "VALUES (?, 3, 'DRAFT', 1, ?, ?, ?, ?, ?)", + owner.getTenantId(), + UUID.randomUUID(), + owner.getCanonicalTenantId(), + other.getId(), + other.getTenantId(), + "NEW_GAME_ROW")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining( + "canonical Version identity source does not match its exact game row"); + + Version wrongTenantAlias = version(owner); + wrongTenantAlias.setTenantId(owner.getCanonicalTenantId().toString()); + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(wrongTenantAlias))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no exact Game Design source row"); + } + + @Test + void canonicalIdentityRejectsTruncateWhileUnmappedRetainedVersionRemainsDeletable() { + Fixture mappedFixture = fixture(null); + Game mappedGame = saveGame(mappedFixture, "truncate-version-owner"); + Version mapped = + mappedFixture + .transactionTemplate() + .execute(status -> mappedFixture.versionRepository().save(version(mappedGame))); + assertThat(mapped).isNotNull(); + + assertThatThrownBy(() -> mappedFixture.dsl().execute("TRUNCATE TABLE version CASCADE")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("canonical Version identities cannot be truncated"); + + Fixture retainedFixture = fixture(V35); + Game retainedGame = saveGame(retainedFixture, "delete-retained-version-owner"); + Long retainedVersionId = + insertRetainedVersion(retainedFixture.dsl(), retainedGame.getTenantId()); + migrate(retainedFixture.dataSource(), retainedFixture.schema(), null); + assertThat(retainedFixture.dsl().deleteFrom(VERSION).where(ID.eq(retainedVersionId)).execute()) + .isEqualTo(1); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "game_design_version_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, target); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + GameRepository gameRepository = new GameRepository(dsl); + VersionRepository versionRepository = new VersionRepository(dsl); + return new Fixture( + schema, dataSource, dsl, gameRepository, versionRepository, transactionTemplate); + } + + private Fixture fixtureWithRetainedGame() { + String schema = "gd_retained_version_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("28")); + DSLContext legacyDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + legacyDsl.execute( + "INSERT INTO game (tenant_id, name, description) VALUES (?, ?, ?)", + "retained-version-game-source", + "Retained Version Source", + "Source row predating canonical tenant identity"); + migrate(dataSource, schema, null); + return fixtureFromMigratedSchema(schema, dataSource); + } + + private Fixture fixtureFromMigratedSchema(String schema, DriverManagerDataSource dataSource) { + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setIsolationLevel( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); + GameRepository gameRepository = new GameRepository(dsl); + VersionRepository versionRepository = new VersionRepository(dsl); + return new Fixture( + schema, dataSource, dsl, gameRepository, versionRepository, transactionTemplate); + } + + 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 Game saveGame(Fixture fixture, String tenantKey) { + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName("Version Identity Owner"); + game.setDescription("Source row for canonical Version identity"); + return fixture.transactionTemplate().execute(status -> fixture.gameRepository().save(game)); + } + + private Long insertRetainedVersion(DSLContext dsl, String tenantId) { + return dsl.resultQuery( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes) " + + "VALUES (?, 4, 'FAILED', 3, NULL, NULL, FALSE, 'retained history') RETURNING id", + tenantId) + .fetchOne(0, Long.class); + } + + private Map retainedFields(DSLContext dsl, Long versionId) { + return dsl.select( + ID, + TENANT_ID, + VERSION_NUMBER, + VERSION_STATE, + VERSION_STATE_EPOCH, + SCRIPT_PATCH_VERSION, + BASE_VERSION_ID, + IS_SCRIPT_ONLY, + NOTES, + CREATED_AT, + UPDATED_AT) + .from(VERSION) + .where(ID.eq(versionId)) + .fetchSingle() + .intoMap(); + } + + private String versionXmin(DSLContext dsl, Long versionId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM version WHERE id = ?", versionId), + "Version xmin query returned no row"); + return Objects.requireNonNull( + row.get("xmin", String.class), "Version xmin readback returned null"); + } + + private String gameXmin(DSLContext dsl, Long gameId) { + var row = + Objects.requireNonNull( + dsl.fetchOne("SELECT xmin::text AS xmin FROM game WHERE id = ?", gameId), + "Game xmin query returned no row"); + return Objects.requireNonNull( + row.get("xmin", String.class), "Game xmin readback returned null"); + } + + private Version version(Game game) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version.setNotes("fresh version"); + return version; + } + + private void assertIdentityMatches(Version version, Game game, UUID canonicalVersionId) { + assertIdentityMatches(version, game, canonicalVersionId, "NEW_GAME_ROW"); + } + + private void assertIdentityMatches( + Version version, Game game, UUID canonicalVersionId, String provenanceKind) { + assertThat(version.getTenantId()).isEqualTo(game.getTenantId()); + assertThat(version.getCanonicalVersionId()).isEqualTo(canonicalVersionId); + assertThat(version.getCanonicalTenantId()).isEqualTo(game.getCanonicalTenantId()); + assertThat(version.getIdentitySourceGameRowId()).isEqualTo(game.getId()); + assertThat(version.getIdentitySourceGameTenantKey()).isEqualTo(game.getTenantId()); + assertThat(version.getIdentitySourceProvenanceKind()).isEqualTo(provenanceKind); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + GameRepository gameRepository, + VersionRepository versionRepository, + TransactionTemplate transactionTemplate) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java new file mode 100644 index 0000000000..d6f7f00c9e --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java @@ -0,0 +1,582 @@ +package integration.net.firedevops.firemud.gamedesign.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import 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 java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameTemplate; +import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.Configuration; +import org.jooq.ExecuteContext; +import org.jooq.ExecuteListenerProvider; +import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** PostgreSQL proof for the immutable descriptor/release pair read from one owner snapshot. */ +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + classes = GameDesignServiceApplication.class, + properties = { + "spring.profiles.active=test", + "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "firemud.grpc.plaintext=true", + "firemud.grpc.workload-namespace=complete-launch-binding-test", + "spring.grpc.server.port=0", + "asset.store.endpoint=http://localhost:9000", + "asset.store.bucket=test-bucket", + "asset.store.region=us-east-1", + "asset.store.access-key=test-access-key", + "asset.store.secret-key=test-secret-key" + }) +@Import(NoGrpcServerTestConfiguration.class) +class CompleteLaunchBindingServiceIntegrationTest { + private static final String NAMESPACE = "complete-launch-binding-test"; + private static final org.jooq.Table VERSION_TABLE = DSL.table(DSL.name("version")); + private static final org.jooq.Field VERSION_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field VERSION_STATE = + DSL.field(DSL.name("version_state"), String.class); + private static final org.jooq.Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "game_design_service"); + } + + @Autowired private CompleteLaunchBindingService completeLaunchBindingService; + @Autowired private LaunchDescriptorService launchDescriptorService; + @Autowired private GameRepository gameRepository; + @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + @Autowired private GameTemplateRepository gameTemplateRepository; + @Autowired private VersionRepository versionRepository; + @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; + @Autowired private LaunchDescriptorRepository launchDescriptorRepository; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private org.jooq.DSLContext dsl; + @Autowired private ObjectMapper objectMapper; + + @Test + void returnsAndRetriesThePersistedCompletePairWithoutChangingOwnerRows() { + Fixture fixture = fixture("complete-pair", true); + Map before = rowVersions(fixture); + + CompleteLaunchBindingDto first = readComplete(fixture); + CompleteLaunchBindingDto retry = readComplete(fixture); + + assertThat(first).isEqualTo(retry); + assertThat(first.descriptor()).isEqualTo(fixture.descriptor().authoredWorldBinding()); + first.releaseAttestation().requireValid(first.descriptor()); + assertThat(first.releaseAttestation().canonicalTenantId()) + .isEqualTo(fixture.canonicalTenantId()); + assertThat(first.releaseAttestation().canonicalVersionId()) + .isEqualTo(fixture.version().getCanonicalVersionId()); + assertThat(first.releaseAttestation().versionStateEpoch()) + .isEqualTo(fixture.descriptor().versionStateEpoch()); + assertThat(fixture.descriptor().releaseBundleId()).isEqualTo(fixture.bundle().getId()); + assertThat(fixture.descriptor().publishedReleaseBundleRef()) + .isEqualTo(fixture.bundle().getPublishedReleaseBundleRef()); + assertThat(first.releaseAttestation().participantDigests()) + .extracting(AuthoredWorldReleaseAttestationEvidence.Participant::participantKey) + .containsExactlyElementsOf( + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()); + assertThat(first.releaseAttestation().artifactDigests()).hasSize(1); + + LaunchDescriptor persisted = persistedDescriptor(fixture); + assertThat(persisted.getLaunchDescriptorId()) + .isEqualTo(first.descriptor().launchDescriptorId()); + assertThat(persisted.getResultDigest()).isEqualTo(first.descriptor().resultDigest()); + assertThat(rowVersions(fixture)).isEqualTo(before); + } + + @Test + void retainsTheHistoricalAttestationWhenCurrentVersionStateAdvances() { + Fixture fixture = fixture("historical-epoch", true); + CompleteLaunchBindingDto original = readComplete(fixture); + Map immutableRowsBefore = immutableRowVersions(fixture); + + advanceVersion(fixture, VersionLifecycleState.RETIRED, 2L); + CompleteLaunchBindingDto later = readComplete(fixture); + + assertThat(later.descriptor()).isEqualTo(original.descriptor()); + assertThat(later.releaseAttestation()).isEqualTo(original.releaseAttestation()); + assertThat(later.releaseAttestation().versionStateEpoch()) + .isEqualTo(original.descriptor().versionStateEpoch()); + assertThat( + dsl.select(VERSION_STATE) + .from(VERSION_TABLE) + .where(VERSION_ID.eq(fixture.version().getId())) + .fetchOne(VERSION_STATE)) + .isEqualTo(VersionLifecycleState.RETIRED.name()); + assertThat( + dsl.select(VERSION_STATE_EPOCH) + .from(VERSION_TABLE) + .where(VERSION_ID.eq(fixture.version().getId())) + .fetchOne(VERSION_STATE_EPOCH)) + .isEqualTo(2L); + assertThat(immutableRowVersions(fixture)).isEqualTo(immutableRowsBefore); + // This is historical evidence equality, not a claim that RETIRED is currently launch-eligible. + } + + @Test + void deniesCrossTenantAndSubstitutedSourceSelectorsWithoutMutatingPersistedEvidence() { + Fixture first = fixture("cross-tenant-first", true); + Fixture second = fixture("cross-tenant-second", true); + Map firstBefore = rowVersions(first); + Map secondBefore = rowVersions(second); + UUID absentCanonicalTenant = UUID.randomUUID(); + + assertDenied( + () -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + second.canonicalTenantId(), + second.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); + assertDenied( + () -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + first.canonicalTenantId(), + second.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); + assertDenied( + () -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + absentCanonicalTenant, + first.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); + + PublishedReleaseBundle swappedCanonicalSource = new PublishedReleaseBundle(); + swappedCanonicalSource.setTenantId(first.privateTenantKey()); + swappedCanonicalSource.setVersionId(first.version().getId()); + swappedCanonicalSource.setCanonicalTenantId(second.canonicalTenantId()); + swappedCanonicalSource.setCanonicalVersionId(second.version().getCanonicalVersionId()); + assertThatThrownBy(() -> publishedReleaseBundleRepository.save(swappedCanonicalSource)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical release identity"); + + assertThat(rowVersions(first)).isEqualTo(firstBefore); + assertThat(rowVersions(second)).isEqualTo(secondBefore); + } + + @Test + void deniesPersistedDescriptorWhoseBundleLacksCompleteOwnerEvidenceWithoutMutation() { + Fixture fixture = fixture("missing-owner-evidence", false); + Map before = rowVersions(fixture); + + assertThatThrownBy(() -> readComplete(fixture)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("PARTICIPANT_EVIDENCE_INCOMPLETE"); + + assertThat(rowVersions(fixture)).isEqualTo(before); + } + + @Test + void descriptorSnapshotRejectsNonRepeatableReadBeforeAnyWrite() { + Fixture fixture = fixture("snapshot-guard", true); + Map before = rowVersions(fixture); + TransactionTemplate readCommitted = new TransactionTemplate(transactionManager); + readCommitted.setReadOnly(true); + readCommitted.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + assertThatThrownBy( + () -> + readCommitted.execute( + status -> + launchDescriptorService.getLaunchDescriptorInOwnerSnapshot( + fixture.readRequestId(), + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.controlPlaneRequestId(), + fixture.descriptor().authoredWorldBinding().requestDigest(), + fixture.descriptor().authoredWorldBinding().resultDigest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("read-only REPEATABLE_READ"); + + assertThat(rowVersions(fixture)).isEqualTo(before); + } + + @Test + void concurrentVersionAdvanceCannotSplitTheCompleteOwnerSnapshot() throws Exception { + Fixture fixture = fixture("concurrent-owner-snapshot", true); + Map immutableRowsBefore = immutableRowVersions(fixture); + CountDownLatch producerVersionReadCompleted = new CountDownLatch(1); + CountDownLatch continueRead = new CountDownLatch(1); + AtomicInteger versionStateSnapshotReads = new AtomicInteger(); + AtomicReference readOnlyObserved = new AtomicReference<>(false); + AtomicReference isolationObserved = new AtomicReference<>(); + DefaultExecuteListener interlock = + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && isVersionStateSnapshotQuery(sql) + && versionStateSnapshotReads.incrementAndGet() == 2) { + readOnlyObserved.set( + TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + isolationObserved.set( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()); + producerVersionReadCompleted.countDown(); + awaitInterlock(continueRead); + } + } + }; + Configuration configuration = dsl.configuration(); + ExecuteListenerProvider[] originalProviders = configuration.executeListenerProviders(); + List providers = new ArrayList<>(Arrays.asList(originalProviders)); + providers.add(new DefaultExecuteListenerProvider(interlock)); + configuration.set(providers.toArray(ExecuteListenerProvider[]::new)); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future inFlightRead = executor.submit(() -> readComplete(fixture)); + assertThat(producerVersionReadCompleted.await(10, TimeUnit.SECONDS)).isTrue(); + + advanceVersion(fixture, VersionLifecycleState.RETIRED, 2L); + continueRead.countDown(); + + CompleteLaunchBindingDto snapshot = inFlightRead.get(20, TimeUnit.SECONDS); + assertThat(readOnlyObserved.get()).isTrue(); + assertThat(isolationObserved.get()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(snapshot.descriptor()).isEqualTo(fixture.descriptor().authoredWorldBinding()); + assertThat(snapshot.releaseAttestation().versionStateEpoch()) + .isEqualTo(fixture.descriptor().versionStateEpoch()); + assertThat(snapshot.releaseAttestation()) + .isEqualTo(readComplete(fixture).releaseAttestation()); + assertThat(immutableRowVersions(fixture)).isEqualTo(immutableRowsBefore); + assertThat( + dsl.select(VERSION_STATE_EPOCH) + .from(VERSION_TABLE) + .where(VERSION_ID.eq(fixture.version().getId())) + .fetchOne(VERSION_STATE_EPOCH)) + .isEqualTo(2L); + } finally { + continueRead.countDown(); + executor.shutdownNow(); + executor.awaitTermination(5, TimeUnit.SECONDS); + configuration.set(originalProviders); + } + } + + private boolean isVersionStateSnapshotQuery(String sql) { + String compact = sql.toLowerCase(Locale.ROOT).replace("\"", "").replaceAll("\\s+", ""); + return compact.contains( + "selectid,tenant_id,canonical_version_id,canonical_tenant_id," + + "identity_source_game_row_id,identity_source_game_tenant_key," + + "identity_source_provenance_kind,version_state,version_state_epoch" + + "fromversionwhereid=?"); + } + + private Fixture fixture(String label, boolean completeEvidence) { + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + String privateTenantKey = "gd-" + UUID.randomUUID().toString().replace("-", ""); + assertThat(privateTenantKey).matches("gd-[0-9a-f]{32}").hasSize(35); + Game game = new Game(); + game.setTenantId(privateTenantKey); + game.setName("Complete binding source " + label + " " + suffix); + game.setDescription("Fresh persisted Game provenance for complete-binding proof"); + Game persistedGame = gameRepository.save(game); + assertThat(privateTenantKey).isNotEqualTo(persistedGame.getCanonicalTenantId().toString()); + + AuthoredWorldSourceEvidence source = + new TransactionTemplate(transactionManager) + .execute( + status -> + authoredWorldSourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Synthetic Complete Binding World")); + + Version version = new Version(); + version.setTenantId(privateTenantKey); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(1L); + version.setNotes("synthetic complete-release evidence fixture"); + version.setUpdatedAt(LocalDateTime.now()); + version = versionRepository.save(version); + + GameTemplate template = new GameTemplate(); + template.setTenantId(privateTenantKey); + template.setName("Complete Binding Template " + suffix); + template.setDescription("Persisted launch descriptor fixture"); + template.setConfig("{}"); + template.setDefaultVersionId(version.getId()); + template.setDefaultRuntimeFlagsJson("{}"); + template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); + template = gameTemplateRepository.save(template); + + PublishedReleaseBundle bundle = + syntheticBundle(privateTenantKey, version, suffix, completeEvidence); + PublishedReleaseBundle persistedBundle = publishedReleaseBundleRepository.save(bundle); + String controlPlaneRequestId = "complete-launch-" + suffix; + UUID readRequestId = UUID.randomUUID(); + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + persistedGame.getCanonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + template.getId(), + false, + null, + false, + null, + false, + null, + false, + null); + ResolvedLaunchDescriptorDto descriptor = + launchDescriptorService.resolveLaunchDescriptor(request); + LaunchDescriptor storedDescriptor = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, persistedGame.getCanonicalTenantId(), controlPlaneRequestId) + .orElseThrow(); + + return new Fixture( + readRequestId, + controlPlaneRequestId, + persistedGame.getId(), + persistedGame.getCanonicalTenantId(), + privateTenantKey, + source, + version, + template, + persistedBundle, + descriptor, + storedDescriptor); + } + + private PublishedReleaseBundle syntheticBundle( + String privateTenantKey, Version version, String suffix, boolean completeEvidence) { + // Synthetic fixture bytes produce real content-addressed hashes; this is not a claim that + // Game Logic or external object storage performed a normal publication in this test. + byte[] artifactBytes = + ("synthetic complete-binding artifact " + suffix).getBytes(StandardCharsets.UTF_8); + String artifactHex = sha256Hex(artifactBytes); + String artifactDigest = "sha256:" + artifactHex; + String manifestBytes = + "{\"schemaVersion\":1,\"assets\":[{\"usageKey\":\"world.navmesh\",\"contentDigest\":\"" + + artifactDigest + + "\"}]}"; + String manifestHash = "sha256:" + sha256Hex(manifestBytes.getBytes(StandardCharsets.UTF_8)); + PublishedArtifactDigest artifact = + new PublishedArtifactDigest( + "world.navmesh", + "world-navmesh", + "artifacts/sha256/" + artifactHex, + artifactDigest, + "application/octet-stream", + 1); + + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(privateTenantKey); + bundle.setVersionId(version.getId()); + bundle.setVersionNumber(version.getVersionNumber()); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId("synthetic-publish-workflow:" + suffix); + bundle.setManifestHash(manifestHash); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson(objectMapper.writeValueAsString(List.of(artifact))); + bundle.setGenerationConfigRevision("generation-config:" + suffix + ":" + "g".repeat(180)); + bundle.setRequiredManifestAssetKeysJson( + objectMapper.writeValueAsString(List.of("world.navmesh"))); + bundle.setParticipantDigestsJson( + objectMapper.writeValueAsString( + completeEvidence ? syntheticParticipants(version) : List.of())); + bundle.setCommandDefinitionsJson( + objectMapper.writeValueAsString(List.of("{\"commandId\":\"look\"}"))); + bundle.setScriptOnly(false); + return bundle; + } + + private List syntheticParticipants(Version version) { + List participants = new ArrayList<>(); + for (String participantKey : + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()) { + boolean gameLogic = "GAME_LOGIC".equals(participantKey); + participants.add( + new PublishParticipantDigestDto( + participantKey, + Long.toString(version.getId()), + null, + "synthetic-applied-commit-" + version.getId(), + "a".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey), + gameLogic ? "sha256:" + "b".repeat(64) : null, + null, + null)); + } + return List.copyOf(participants); + } + + private CompleteLaunchBindingDto readComplete(Fixture fixture) { + AuthoredWorldLaunchDescriptorEvidence descriptor = fixture.descriptor().authoredWorldBinding(); + return completeLaunchBindingService.getCompleteLaunchBinding( + fixture.readRequestId(), + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.controlPlaneRequestId(), + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + private void advanceVersion(Fixture fixture, VersionLifecycleState state, long epoch) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.execute( + status -> { + Version current = + versionRepository + .findByTenantIdAndId(fixture.privateTenantKey(), fixture.version().getId()) + .orElseThrow(); + current.setVersionState(state); + current.setVersionStateEpoch(epoch); + return versionRepository.save(current); + }); + } + + private Map rowVersions(Fixture fixture) { + Map snapshot = immutableRowVersions(fixture); + snapshot.put("version", rowXmin("version", "id", fixture.version().getId())); + return snapshot; + } + + private Map immutableRowVersions(Fixture fixture) { + Map snapshot = new LinkedHashMap<>(); + snapshot.put("game", rowXmin("game", "id", fixture.gameRowId())); + snapshot.put( + "source", + rowXmin( + "game_design_authored_world_source_operations", + "operation_id", + fixture.source().operationId())); + snapshot.put("template", rowXmin("game_templates", "id", fixture.template().getId())); + snapshot.put("bundle", rowXmin("published_release_bundle", "id", fixture.bundle().getId())); + snapshot.put( + "descriptor", rowXmin("launch_descriptor", "id", fixture.storedDescriptor().getId())); + return snapshot; + } + + private String rowXmin(String table, String idColumn, Object id) { + var row = dsl.fetchOne("SELECT xmin::text FROM " + table + " WHERE " + idColumn + " = ?", id); + return row == null ? "" : row.get(0, String.class); + } + + private LaunchDescriptor persistedDescriptor(Fixture fixture) { + return launchDescriptorRepository + .findBoundByRequest(NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + } + + private void assertDenied(Runnable operation) { + assertThatThrownBy(operation::run).isInstanceOf(IllegalArgumentException.class); + } + + private void awaitInterlock(CountDownLatch continueRead) { + try { + if (!continueRead.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to resume complete-binding snapshot"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while holding complete-binding snapshot", exception); + } + } + + private static String sha256Hex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is required by the JDK", impossible); + } + } + + private record Fixture( + UUID readRequestId, + String controlPlaneRequestId, + long gameRowId, + UUID canonicalTenantId, + String privateTenantKey, + AuthoredWorldSourceEvidence source, + Version version, + GameTemplate template, + PublishedReleaseBundle bundle, + ResolvedLaunchDescriptorDto descriptor, + LaunchDescriptor storedDescriptor) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 1dbcec0d96..ea71e0f5dc 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -1,30 +1,66 @@ package integration.net.firedevops.firemud.gamedesign.service; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.LocalDateTime; +import java.util.LinkedHashMap; +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.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameTemplate; +import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; +import net.firedevops.firemud.gamedesign.service.impl.LaunchDescriptorServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; -import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; @Testcontainers(disabledWithoutDocker = true) @SpringBootTest( @@ -33,6 +69,7 @@ "spring.profiles.active=test", "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "firemud.grpc.plaintext=true", + "firemud.grpc.workload-namespace=launch-descriptor-test", "spring.grpc.server.port=0", "asset.store.endpoint=http://localhost:9000", "asset.store.bucket=test-bucket", @@ -42,9 +79,20 @@ }) @Import(NoGrpcServerTestConfiguration.class) class LaunchDescriptorServiceIntegrationTest { + private static final String NAMESPACE = "launch-descriptor-test"; + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final org.jooq.Table LAUNCH_DESCRIPTOR = + DSL.table(DSL.name("launch_descriptor")); + private static final org.jooq.Field LAUNCH_ROW_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field LAUNCH_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final org.jooq.Field LAUNCH_CANONICAL_TENANT = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field LAUNCH_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + @Container - static PostgreSQLContainer postgres = - new PostgreSQLContainer<>(TestContainerImages.postgres()); + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { @@ -53,51 +101,1309 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private LaunchDescriptorService launchDescriptorService; + @Autowired private GameRepository gameRepository; + @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Autowired private GameTemplateRepository gameTemplateRepository; @Autowired private VersionRepository versionRepository; @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; + @Autowired private PublishedReleaseBundleService publishedReleaseBundleService; + @Autowired private LaunchDescriptorRepository launchDescriptorRepository; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private DSLContext dsl; + + @Test + void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionChange() { + Fixture fixture = fixture("cp-persisted"); + + ResolvedLaunchDescriptorDto original = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + String generationConfigRevision = fixture.bundle().getGenerationConfigRevision(); + assertThat(generationConfigRevision.length()).isGreaterThan(128); + assertThat(original.generationConfigRevision()).isEqualTo(generationConfigRevision); + assertThat(original.canonicalTenantId()).isEqualTo(fixture.canonicalTenantId().toString()); + assertThat(original.publishedReleaseBundleRef()) + .isEqualTo(fixture.bundle().getPublishedReleaseBundleRef()); + assertThat( + publishedReleaseBundleRepository + .findByTenantIdAndVersionId( + fixture.privateSourceTenantKey(), fixture.version().getId()) + .orElseThrow() + .getPublishedReleaseBundleRef()) + .isEqualTo(original.publishedReleaseBundleRef()); + assertThat(original.authoredWorldBinding()).isNotNull(); + assertThat(original.authoredWorldBinding().authoredWorldSourceOperationId()) + .isEqualTo(fixture.source().operationId()); + assertThat(original.authoredWorldBinding().authoredWorldSourceEvidenceDigest()) + .isEqualTo(fixture.source().evidenceDigest()); + assertThat(original.canonicalTenantId()).isNotEqualTo(fixture.privateSourceTenantKey()); + + Version newDraft = new Version(); + newDraft.setTenantId(fixture.privateSourceTenantKey()); + newDraft.setVersionNumber(2); + newDraft.setVersionState(VersionLifecycleState.DRAFT); + newDraft.setVersionStateEpoch(1L); + newDraft.setNotes("new mutable template default"); + newDraft.setUpdatedAt(LocalDateTime.now()); + newDraft = versionRepository.save(newDraft); + fixture.template().setDefaultVersionId(newDraft.getId()); + gameTemplateRepository.save(fixture.template()); + fixture.version().setVersionState(VersionLifecycleState.RETIRED); + fixture.version().setVersionStateEpoch(2L); + versionRepository.save(fixture.version()); + + ResolvedLaunchDescriptorDto retry = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + + assertThat(retry).isEqualTo(original); + assertThat(retry.versionId()).isEqualTo(fixture.version().getId()); + LaunchDescriptor persisted = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(persisted.getLaunchDescriptorId()).isEqualTo(original.launchDescriptorId()); + assertThat(persisted.getRequestDigest()) + .isEqualTo(original.authoredWorldBinding().requestDigest()); + assertThat(persisted.getResultDigest()) + .isEqualTo(original.authoredWorldBinding().resultDigest()); + assertThat(persisted.getPublishedReleaseBundleRef()) + .isEqualTo(original.publishedReleaseBundleRef()); + assertThat(persisted.getGenerationConfigRevision()).isEqualTo(generationConfigRevision); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + + ResolvedLaunchDescriptorDto readback = + launchDescriptorService.getLaunchDescriptor( + UUID.randomUUID(), + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.controlPlaneRequestId(), + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest()); + assertThat(readback).isEqualTo(original); + } + + @Test + void concurrentExactRetriesPersistOneOriginalDescriptor() throws Exception { + Fixture fixture = fixture("cp-concurrent"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> resolveAfterLatch(fixture, ready, start)); + Future second = + executor.submit(() -> resolveAfterLatch(fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + ResolvedLaunchDescriptorDto firstResult = first.get(20, TimeUnit.SECONDS); + ResolvedLaunchDescriptorDto secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(secondResult).isEqualTo(firstResult); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + LaunchDescriptor persisted = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(persisted.getLaunchDescriptorId()).isEqualTo(firstResult.launchDescriptorId()); + assertThat(persisted.getResultDigest()) + .isEqualTo(firstResult.authoredWorldBinding().resultDigest()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } @Test - void resolvesLaunchDescriptorForJsonConfiguredTemplate() { + void deterministicFailureIsFrozenAcrossDependencyChangeAndConcurrentExactRetries() + throws Exception { + Fixture fixture = fixture("cp-frozen-phase"); + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.LEGACY); + gameTemplateRepository.save(fixture.template()); + + assertThatThrownBy(() -> launchDescriptorService.resolveLaunchDescriptor(fixture.request())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + + LaunchDescriptor failed = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(failed.getOutcomeStatus()).isEqualTo(LaunchDescriptor.OUTCOME_FAILED); + assertThat(failed.getFailureCode()).isEqualTo("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED"); + assertThat(failed.getFailureMessage()) + .isEqualTo( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + assertThat(failed.getRequestDigest()).isEqualTo(fixture.request().requestDigest()); + assertThat(failed.getOriginalRequestJson()).isNotBlank(); + assertThat(failed.getSourceEvidenceJson()).isNotBlank(); + assertThat(failed.getLaunchDescriptorId()).isNull(); + assertThat(failed.getGameTemplateId()).isNull(); + assertThat(failed.getVersionId()).isNull(); + assertThat(failed.getReleaseBundleId()).isNull(); + assertThat(failed.getResultDigest()).isNull(); + assertFailedShapeRejected(failed, "cp-frozen-null-schema", true); + assertFailedShapeRejected(failed, "cp-frozen-null-failure-code", false); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); + gameTemplateRepository.save(fixture.template()); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = executor.submit(() -> resolveFailureAfterLatch(fixture, ready, start)); + Future second = + executor.submit(() -> resolveFailureAfterLatch(fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(first.get(20, TimeUnit.SECONDS)).isEqualTo(failed.getFailureMessage()); + assertThat(second.get(20, TimeUnit.SECONDS)).isEqualTo(failed.getFailureMessage()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + + assertThatThrownBy( + () -> + launchDescriptorService.resolveLaunchDescriptor( + fixture.requestWithPatch("different-patch"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("control-plane request identity was reused with changed input"); + + ResolvedLaunchDescriptorDto freshAttempt = + launchDescriptorService.resolveLaunchDescriptor(fixture.request("cp-frozen-phase-fresh")); + assertThat(freshAttempt.versionId()).isEqualTo(fixture.version().getId()); + assertThat( + launchDescriptorRepository + .findBoundByRequest(NAMESPACE, fixture.canonicalTenantId(), "cp-frozen-phase-fresh") + .orElseThrow() + .getOutcomeStatus()) + .isEqualTo(LaunchDescriptor.OUTCOME_SUCCESS); + } + + @Test + void corruptFailureReadbackRollsBackTheOutcomeInsert() { + Fixture fixture = fixture("cp-corrupt-failure-readback"); + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.LEGACY); + gameTemplateRepository.save(fixture.template()); + LaunchDescriptorRepository corruptingRepository = + new LaunchDescriptorRepository(dsl) { + @Override + public LaunchDescriptor insertImmutable(LaunchDescriptor descriptor) { + LaunchDescriptor persisted = super.insertImmutable(descriptor); + persisted.setFailureCode("UNRECOGNIZED_FAILURE"); + return persisted; + } + }; + LaunchDescriptorServiceImpl corruptingService = + new LaunchDescriptorServiceImpl( + gameTemplateRepository, + corruptingRepository, + versionRepository, + Mockito.mock(PublishedReleaseBundleService.class), + Mockito.mock(TemplateRemapSetService.class), + authoredWorldSourceRepository, + new ObjectMapper()); + ReflectionTestUtils.setField(corruptingService, "workloadNamespace", NAMESPACE); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transaction.execute( + status -> corruptingService.resolveLaunchDescriptor(fixture.request()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("stored failure is not the exact immutable request outcome"); + + assertThat( + launchDescriptorRepository.findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId())) + .isEmpty(); + } + + @Test + void concurrentSuccessAndFailureCandidatesPersistOnlyTheFirstOutcome() throws Exception { + Fixture fixture = fixture("cp-mixed-candidates"); + CountDownLatch lockArrivals = new CountDownLatch(2); + CountDownLatch viewReached = new CountDownLatch(1); + CountDownLatch continueResolution = new CountDownLatch(1); + LaunchDescriptorRepository serializedRepository = + new LaunchDescriptorRepository(dsl) { + @Override + public void lockBoundRequest(String targetNamespace, UUID tenantId, String requestId) { + lockArrivals.countDown(); + super.lockBoundRequest(targetNamespace, tenantId, requestId); + } + }; + LaunchDescriptorServiceImpl failureCandidate = + candidateForPhase( + fixture, + serializedRepository, + TemplateReferencePhase.LEGACY, + viewReached, + continueResolution); + LaunchDescriptorServiceImpl successCandidate = + candidateForPhase( + fixture, + serializedRepository, + TemplateReferencePhase.ENFORCED, + viewReached, + continueResolution); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> resolveCandidateInOwnerTransaction(failureCandidate, fixture, ready, start)); + Future second = + executor.submit( + () -> resolveCandidateInOwnerTransaction(successCandidate, fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(viewReached.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(lockArrivals.await(10, TimeUnit.SECONDS)).isTrue(); + continueResolution.countDown(); + + String firstResult = first.get(20, TimeUnit.SECONDS); + String secondResult = second.get(20, TimeUnit.SECONDS); + assertThat(secondResult).isEqualTo(firstResult); + LaunchDescriptor stored = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(stored.getOutcomeStatus()) + .isEqualTo( + firstResult.startsWith("FAILED:") + ? LaunchDescriptor.OUTCOME_FAILED + : LaunchDescriptor.OUTCOME_SUCCESS); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + } finally { + continueResolution.countDown(); + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim() { + Fixture fixture = fixture("cp-rollback"); + AuthoredWorldLaunchDescriptorEvidence evidence = evidence(fixture, "ld-rollback-candidate"); + LaunchDescriptor candidate = entity(evidence, fixture); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transaction.execute( + status -> { + launchDescriptorRepository.insertImmutable(candidate); + throw new IllegalStateException("force owner transaction rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("force owner transaction rollback"); + + assertThat( + launchDescriptorRepository.findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId())) + .isEmpty(); + assertThat( + launchDescriptorRepository.findByPrivateRequest( + fixture.privateSourceTenantKey(), fixture.controlPlaneRequestId())) + .isEmpty(); + ResolvedLaunchDescriptorDto committed = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + assertThat(committed.authoredWorldBinding().requestDigest()) + .isEqualTo(evidence.requestDigest()); + } + + @Test + void v39MigrationPreservesRetainedPublicationEvidenceAndStoresLongDiagnostics() { + String schema = "game_design_publication_text_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = isolatedDataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("33")); + DSLContext isolatedDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + + String tenantId = privateTenantKey(); + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + // Synthetic pre-identity rows seed migration preservation only; no source identity is inferred. + long versionId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO version " + + "(tenant_id, version_number, version_state, version_state_epoch) " + + "VALUES (?, 1, 'PUBLISHED', 7) RETURNING id", + tenantId) + .fetchOne(0, Long.class), + "retained Version"); + long templateId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, ?, '{}'::jsonb) RETURNING id", + tenantId, + "Retained Publication Template " + suffix) + .fetchOne(0, Long.class), + "retained Game Template"); + String generationRevision = "retained-generation-rév-🧭-" + suffix; + long bundleId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO published_release_bundle " + + "(tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, required_manifest_asset_keys_json, " + + "participant_digests_json, generation_config_revision) " + + "VALUES (?, ?, 1, 'v1', ?, ?, '[]', '[]', ?) RETURNING id", + tenantId, + versionId, + "v38-retained-bundle-" + suffix, + "sha256:" + "f".repeat(64), + generationRevision) + .fetchOne(0, Long.class), + "retained release bundle"); + long descriptorId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO launch_descriptor " + + "(launch_descriptor_id, tenant_id, game_template_id, " + + "control_plane_request_id, request_hash, version_id, runtime_flags_json, " + + "generation_config_revision, version_state_epoch, release_bundle_id, " + + "published_release_bundle_ref) " + + "VALUES (?, ?, ?, ?, ?, ?, '{}', ?, 7, ?, ?) RETURNING id", + "ld-v38-retained-" + suffix, + tenantId, + templateId, + "v38-retained-request-" + suffix, + "retained-request-hash-" + suffix, + versionId, + generationRevision, + bundleId, + "retained-release-ref-" + suffix) + .fetchOne(0, Long.class), + "retained launch descriptor"); + + migrate(dataSource, schema, MigrationVersion.fromVersion("38")); + String retainedFailure = "retained-failure-雪-" + suffix; + String retainedArtifactError = "retained-artifact-error-🧭-" + suffix; + String attemptWorkflowId = "v38-retained-attempt-" + suffix; + long attemptId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO publish_attempt " + + "(tenant_id, publish_workflow_id, publish_type, status, version_id, " + + "version_number, failure_code, failure_message, completed_at) " + + "VALUES (?, ?, 'FULL_VERSION', 'FAILED', ?, 1, 'PUBLISH_FAILED', ?, " + + "TIMESTAMP '2026-09-30 12:34:56') RETURNING id", + tenantId, + attemptWorkflowId, + versionId, + retainedFailure) + .fetchOne(0, Long.class), + "retained publish attempt"); + long artifactId = + requiredId( + isolatedDsl + .resultQuery( + "INSERT INTO version_asset_artifact " + + "(tenant_id, version_id, artifact_state, state_epoch, " + + "exported_version_number, manifest_hash, last_workflow_id, " + + "last_error_code, last_error_message) " + + "VALUES (?, ?, 'FAILED', 11, 1, ?, ?, 'PUBLISH_FAILED', ?) RETURNING id", + tenantId, + versionId, + "sha256:" + "a".repeat(64), + "v38-retained-artifact-" + suffix, + retainedArtifactError) + .fetchOne(0, Long.class), + "retained version asset artifact"); + + Map> retainedRows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + migrate(dataSource, schema, MigrationVersion.fromVersion("39")); + Map> v39Rows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(priorPublicationEvidenceColumns(v39Rows)) + .isEqualTo(priorPublicationEvidenceColumns(retainedRows)); + assertThat( + requiredSnapshot(retainedRows, "published_release_bundle") + .get("generation_config_revision")) + .isEqualTo(generationRevision); + assertThat( + requiredSnapshot(retainedRows, "launch_descriptor").get("generation_config_revision")) + .isEqualTo(generationRevision); + assertThat(requiredSnapshot(retainedRows, "publish_attempt").get("failure_message")) + .isEqualTo(retainedFailure); + assertThat(requiredSnapshot(retainedRows, "version_asset_artifact").get("last_error_message")) + .isEqualTo(retainedArtifactError); + + String longFailure = "complete-failure-雪-" + "f".repeat(540); + String longArtifactError = "complete-artifact-error-🧭-" + "e".repeat(540); + isolatedDsl.execute( + "UPDATE publish_attempt SET failure_message = ? WHERE id = ?", longFailure, attemptId); + isolatedDsl.execute( + "UPDATE version_asset_artifact SET last_error_message = ? WHERE id = ?", + longArtifactError, + artifactId); + Map> v39LongDiagnosticsRows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(requiredSnapshot(v39LongDiagnosticsRows, "publish_attempt").get("failure_message")) + .isEqualTo(longFailure); + assertThat( + requiredSnapshot(v39LongDiagnosticsRows, "version_asset_artifact") + .get("last_error_message")) + .isEqualTo(longArtifactError); + assertThat( + requiredRow( + isolatedDsl, + "SELECT failure_message FROM publish_attempt WHERE id = ?", + attemptId, + "long publish-attempt failure readback") + .get("failure_message")) + .isEqualTo(longFailure); + assertThat( + requiredRow( + isolatedDsl, + "SELECT last_error_message FROM version_asset_artifact WHERE id = ?", + artifactId, + "long artifact-error readback") + .get("last_error_message")) + .isEqualTo(longArtifactError); + assertThat( + requiredRow( + isolatedDsl, + "SELECT status, version_number FROM publish_attempt WHERE id = ?", + attemptId, + "publish-attempt state readback")) + .containsEntry("status", "FAILED") + .containsEntry("version_number", 1); + assertThat( + requiredRow( + isolatedDsl, + "SELECT artifact_state, state_epoch FROM version_asset_artifact WHERE id = ?", + artifactId, + "artifact state readback")) + .containsEntry("artifact_state", "FAILED") + .containsEntry("state_epoch", 11L); + + migrate(dataSource, schema, null); + Map> migratedRows = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(priorPublicationEvidenceColumns(migratedRows)) + .isEqualTo(priorPublicationEvidenceColumns(v39LongDiagnosticsRows)); + assertThat(requiredSnapshot(migratedRows, "publish_attempt").get("revision")).isEqualTo(1L); + assertThat( + requiredSnapshot(migratedRows, "published_release_bundle") + .get("world_published_start_location_evidence_json")) + .isNull(); + var publicationOperationCount = + isolatedDsl.fetchOne( + "SELECT count(*) FROM game_design_publication_operation WHERE publish_workflow_id = ?", + attemptWorkflowId); + if (publicationOperationCount == null) { + throw new IllegalStateException("Publication operation count query returned no row"); + } + Long publicationOperationCountValue = publicationOperationCount.get(0, Long.class); + if (publicationOperationCountValue == null) { + throw new IllegalStateException("Publication operation count query returned no count"); + } + assertThat(publicationOperationCountValue).isZero(); + assertThat(requiredSnapshot(migratedRows, "publish_attempt").get("failure_message")) + .isEqualTo(longFailure); + assertThat(requiredSnapshot(migratedRows, "version_asset_artifact").get("last_error_message")) + .isEqualTo(longArtifactError); + + assertThatThrownBy( + () -> + isolatedDsl.execute( + "UPDATE publish_attempt SET failure_message = ? WHERE id = ?", + "forbidden-terminal-rewrite-" + suffix, + attemptId)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("publish attempt is stale or terminal"); + Map> afterRejectedTerminalRewrite = + publicationEvidenceRows( + isolatedDsl, versionId, bundleId, descriptorId, attemptId, artifactId); + assertThat(afterRejectedTerminalRewrite).isEqualTo(migratedRows); + var publicationOperationCountAfterRejectedRewrite = + isolatedDsl.fetchOne( + "SELECT count(*) FROM game_design_publication_operation WHERE publish_workflow_id = ?", + attemptWorkflowId); + if (publicationOperationCountAfterRejectedRewrite == null) { + throw new IllegalStateException("Publication operation count query returned no row"); + } + Long publicationOperationCountAfterRejectedRewriteValue = + publicationOperationCountAfterRejectedRewrite.get(0, Long.class); + if (publicationOperationCountAfterRejectedRewriteValue == null) { + throw new IllegalStateException("Publication operation count query returned no count"); + } + assertThat(publicationOperationCountAfterRejectedRewriteValue).isZero(); + } + + @Test + void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill() { + String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = isolatedDataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("33")); + DSLContext isolatedDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager isolatedTransactionManager = + new DataSourceTransactionManager(dataSource); + TransactionTemplate isolatedTransaction = new TransactionTemplate(isolatedTransactionManager); + + String privateTenantKey = privateTenantKey(); + Game game = new Game(); + game.setTenantId(privateTenantKey); + game.setName("Retained launch source"); + game.setDescription("Persisted V34 source fixture"); + Game persistedGame = + isolatedTransaction.execute(status -> new GameRepository(isolatedDsl).save(game)); + assertThat(persistedGame).isNotNull(); + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + AuthoredWorldSourceEvidence source = + seedPreV41AuthoredWorldSource( + isolatedDsl, + isolatedTransaction, + persistedGame, + UUID.randomUUID(), + "tenant-" + suffix, + "world-" + suffix, + "Retained World 🐉"); + assertThat(source).isNotNull(); + + Long versionId = + isolatedDsl + .resultQuery( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch) " + + "VALUES (?, 1, 'PUBLISHED', 1) RETURNING id", + privateTenantKey) + .fetchOne(0, Long.class); + Long templateId = + isolatedDsl + .resultQuery( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, ?, '{}'::jsonb) RETURNING id", + privateTenantKey, + "Retained Template " + suffix) + .fetchOne(0, Long.class); + // Synthetic retained-row seed for storage compatibility only; not live publication proof. + Long bundleId = + isolatedDsl + .resultQuery( + "INSERT INTO published_release_bundle " + + "(tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, required_manifest_asset_keys_json, " + + "participant_digests_json, generation_config_revision) " + + "VALUES (?, ?, 1, 'v1', ?, ?, '[]', '[]', ?) RETURNING id", + privateTenantKey, + versionId, + "synthetic-retained-fixture-" + suffix, + "sha256:" + "d".repeat(64), + "gen-rev:" + suffix) + .fetchOne(0, Long.class); + if (bundleId == null) { + throw new IllegalStateException("Retained V34 release bundle insertion returned no identity"); + } + String requestId = "retained-cp-" + suffix; + String legacyDescriptorId = "ld-retained-" + suffix; + isolatedDsl.execute( + "INSERT INTO launch_descriptor " + + "(launch_descriptor_id, tenant_id, game_template_id, control_plane_request_id, " + + "request_hash, version_id, runtime_flags_json, generation_config_revision, " + + "version_state_epoch, release_bundle_id, published_release_bundle_ref) " + + "VALUES (?, ?, ?, ?, ?, ?, '{}', ?, 1, ?, ?)", + legacyDescriptorId, + privateTenantKey, + templateId, + requestId, + "legacy-request-hash-" + suffix, + versionId, + "gen-rev:" + suffix, + bundleId, + "legacy-release-ref-" + suffix); + Map retainedV34Snapshot = + legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId); + Map retainedBundleSnapshot = + retainedReleaseBundleSnapshot(isolatedDsl, bundleId); + + migrate(dataSource, schema, null); + LaunchDescriptorRepository launchRepository = new LaunchDescriptorRepository(isolatedDsl); + var retainedBundleReference = + isolatedDsl.fetchOne( + "SELECT published_release_bundle_ref FROM published_release_bundle WHERE id = ?", + bundleId); + if (retainedBundleReference == null) { + throw new IllegalStateException("Retained V34 release bundle reference row is missing"); + } + assertThat(retainedBundleReference.get("published_release_bundle_ref", String.class)).isNull(); + assertThat(retainedReleaseBundleSnapshot(isolatedDsl, bundleId)) + .isEqualTo(retainedBundleSnapshot); + assertThat( + new PublishedReleaseBundleRepository(isolatedDsl) + .findByTenantIdAndVersionId(privateTenantKey, versionId) + .orElseThrow() + .getPublishedReleaseBundleRef()) + .isNull(); + assertThat(legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId)) + .isEqualTo(retainedV34Snapshot); + LaunchDescriptor before = + launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow(); + assertThat(before.getDescriptorSchemaVersion()).isNull(); + assertThat(before.getCanonicalTenantId()).isNull(); + assertThat(before.getRequestHash()).isEqualTo("legacy-request-hash-" + suffix); + + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + requestId, + persistedGame.getCanonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + templateId, + false, + null, + false, + null, + false, + null, + false, + null); + LaunchDescriptorServiceImpl isolatedService = + new LaunchDescriptorServiceImpl( + Mockito.mock(GameTemplateRepository.class), + launchRepository, + Mockito.mock(VersionRepository.class), + Mockito.mock(PublishedReleaseBundleService.class), + Mockito.mock(TemplateRemapSetService.class), + new GameAuthoredWorldSourceRepository(isolatedDsl), + new ObjectMapper()); + ReflectionTestUtils.setField(isolatedService, "workloadNamespace", NAMESPACE); + + assertThatThrownBy(() -> isolatedService.resolveLaunchDescriptor(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("LAUNCH_DESCRIPTOR_CONFLICT") + .hasMessageContaining("unbound"); + assertThat( + launchRepository.findBoundByRequest( + NAMESPACE, persistedGame.getCanonicalTenantId(), requestId)) + .isEmpty(); + assertRetainedRowUnchanged( + before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); + + assertThatThrownBy( + () -> + isolatedDsl.execute( + "UPDATE launch_descriptor SET runtime_flags_json = ? WHERE id = ?", + "{\"changed\":true}", + before.getId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("launch descriptors are immutable"); + assertRetainedRowUnchanged( + before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); + } + + private Fixture fixture(String controlPlaneRequestId) { + String privateTenantKey = privateTenantKey(); + Game sourceGame = new Game(); + sourceGame.setTenantId(privateTenantKey); + sourceGame.setName("Launch Source " + UUID.randomUUID()); + sourceGame.setDescription("Persisted fresh Game Design tenant source"); + Game persistedGame = + new TransactionTemplate(transactionManager) + .execute(status -> gameRepository.save(sourceGame)); + assertThat(persistedGame).isNotNull(); + + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + AuthoredWorldSourceEvidence source = + new TransactionTemplate(transactionManager) + .execute( + status -> + authoredWorldSourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Launch World 🐉")); + assertThat(source).isNotNull(); + Version version = new Version(); - version.setTenantId("1"); + version.setTenantId(privateTenantKey); version.setVersionNumber(1); version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(1L); - version.setNotes("integration test version"); + version.setNotes("synthetic release storage proof fixture"); version.setUpdatedAt(LocalDateTime.now()); version = versionRepository.save(version); GameTemplate template = new GameTemplate(); - template.setTenantId("1"); - template.setName("Integration Template"); - template.setDescription("launch descriptor integration template"); + template.setTenantId(privateTenantKey); + template.setName("Launch Template " + suffix); + template.setDescription("Persisted descriptor resolution fixture"); template.setConfig("{}"); template.setDefaultVersionId(version.getId()); template.setDefaultRuntimeFlagsJson("{}"); template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); template = gameTemplateRepository.save(template); + // This row exercises descriptor storage and resolution only; it is not live publication proof. PublishedReleaseBundle bundle = new PublishedReleaseBundle(); - bundle.setTenantId("1"); + bundle.setTenantId(privateTenantKey); bundle.setVersionId(version.getId()); bundle.setVersionNumber(1); bundle.setAttestationSchemaVersion("v1"); - bundle.setPublishWorkflowId("integration-seed"); - bundle.setManifestHash("integration-manifest"); - bundle.setGenerationConfigRevision("genrev:integration"); + bundle.setPublishWorkflowId("synthetic-storage-proof-" + suffix); + bundle.setManifestHash("sha256:" + "e".repeat(64)); + bundle.setGenerationConfigRevision("gen-rev:" + suffix + ":" + "g".repeat(180)); bundle.setRequiredManifestAssetKeysJson("[]"); bundle.setParticipantDigestsJson("[]"); bundle.setScriptOnly(false); - publishedReleaseBundleRepository.save(bundle); + bundle = publishedReleaseBundleRepository.save(bundle); + + return new Fixture( + controlPlaneRequestId, + persistedGame.getCanonicalTenantId(), + privateTenantKey, + source, + version, + template, + bundle); + } + + private void assertFailedShapeRejected( + LaunchDescriptor failed, String controlPlaneRequestId, boolean nullSchemaVersion) { + assertThatThrownBy( + () -> + dsl.execute( + """ + INSERT INTO launch_descriptor ( + tenant_id, + control_plane_request_id, + request_hash, + descriptor_schema_version, + target_namespace, + canonical_tenant_id, + world_slug, + authored_world_source_operation_id, + authored_world_source_evidence_digest, + request_digest, + original_request_json, + source_evidence_json, + outcome_status, + failure_code, + failure_message) + VALUES (?, ?, ?, CAST(? AS SMALLINT), ?, CAST(? AS UUID), ?, + CAST(? AS UUID), ?, ?, ?, ?, 'FAILED', CAST(? AS VARCHAR(64)), ?) + """, + failed.getTenantId(), + controlPlaneRequestId, + failed.getRequestHash(), + nullSchemaVersion ? null : failed.getDescriptorSchemaVersion(), + failed.getTargetNamespace(), + failed.getCanonicalTenantId(), + failed.getWorldSlug(), + failed.getAuthoredWorldSourceOperationId(), + failed.getAuthoredWorldSourceEvidenceDigest(), + failed.getRequestDigest(), + failed.getOriginalRequestJson(), + failed.getSourceEvidenceJson(), + nullSchemaVersion ? failed.getFailureCode() : null, + failed.getFailureMessage())) + .isInstanceOf(DataIntegrityViolationException.class) + .hasStackTraceContaining("ck_launch_descriptor_authored_binding_complete"); + } + + private ResolvedLaunchDescriptorDto resolveAfterLatch( + Fixture fixture, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + return launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + } + + private String resolveFailureAfterLatch( + Fixture fixture, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + try { + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + return "unexpected success"; + } catch (IllegalArgumentException exception) { + return exception.getMessage(); + } + } + + private String resolveCandidateInOwnerTransaction( + LaunchDescriptorServiceImpl service, + Fixture fixture, + CountDownLatch ready, + CountDownLatch start) { + ready.countDown(); + await(start); + return new TransactionTemplate(transactionManager) + .execute( + status -> { + try { + return "SUCCESS:" + + service + .resolveLaunchDescriptor(fixture.request()) + .authoredWorldBinding() + .resultDigest(); + } catch (IllegalArgumentException exception) { + return "FAILED:" + exception.getMessage(); + } + }); + } + + private LaunchDescriptorServiceImpl candidateForPhase( + Fixture fixture, + LaunchDescriptorRepository repository, + TemplateReferencePhase phase, + CountDownLatch viewReached, + CountDownLatch continueResolution) { + GameTemplateRepository templateRepository = Mockito.mock(GameTemplateRepository.class); + GameTemplateLaunchConfigView view = Mockito.mock(GameTemplateLaunchConfigView.class); + Mockito.when(view.getId()).thenReturn(fixture.template().getId()); + Mockito.when(view.getTenantId()).thenReturn(fixture.privateSourceTenantKey()); + Mockito.when(view.getDefaultVersionId()).thenReturn(fixture.version().getId()); + Mockito.when(view.getDefaultRuntimeFlagsJson()).thenReturn("{}"); + Mockito.when(view.getTemplateReferencePhase()) + .thenAnswer( + invocation -> { + viewReached.countDown(); + await(continueResolution); + return phase; + }); + Mockito.when( + templateRepository.findLaunchConfigByTenantIdAndId( + fixture.privateSourceTenantKey(), fixture.template().getId())) + .thenReturn(java.util.Optional.of(view)); + LaunchDescriptorServiceImpl service = + new LaunchDescriptorServiceImpl( + templateRepository, + repository, + versionRepository, + publishedReleaseBundleService, + Mockito.mock(TemplateRemapSetService.class), + authoredWorldSourceRepository, + new ObjectMapper()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + return service; + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for descriptor retry race"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for descriptor retry race", exception); + } + } + + private AuthoredWorldLaunchDescriptorEvidence evidence(Fixture fixture, String descriptorId) { + return AuthoredWorldLaunchDescriptorEvidence.create( + fixture.request(), + descriptorId, + fixture.version().getId(), + false, + null, + "{}", + fixture.bundle().getGenerationConfigRevision(), + fixture.version().getVersionStateEpoch(), + fixture.bundle().getId(), + "release-bundle:" + + fixture.canonicalTenantId() + + ":" + + fixture.version().getId() + + ":" + + fixture.bundle().getId(), + false, + null); + } + + private LaunchDescriptor entity(AuthoredWorldLaunchDescriptorEvidence evidence, Fixture fixture) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); + descriptor.setTenantId(fixture.privateSourceTenantKey()); + descriptor.setGameTemplateId(evidence.gameTemplateId()); + descriptor.setControlPlaneRequestId(evidence.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(evidence.versionId()); + descriptor.setScriptPatchVersion(evidence.scriptPatchVersion()); + descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); + descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); + descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); + descriptor.setReleaseBundleId(evidence.releaseBundleId()); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); + descriptor.setRemapSetId(evidence.remapSetId()); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(evidence.targetNamespace()); + descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(json(evidence.request())); + descriptor.setSourceEvidenceJson(json(fixture.source())); + return descriptor; + } + + private String json(Object value) { + try { + return new ObjectMapper().writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException("Test evidence serialization failed", exception); + } + } + + private DriverManagerDataSource isolatedDataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + /** Seeds the immutable source/binding shape written before V41 added automatic delivery. */ + private AuthoredWorldSourceEvidence seedPreV41AuthoredWorldSource( + DSLContext isolatedDsl, + TransactionTemplate isolatedTransaction, + Game sourceGame, + UUID registrationRequestId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + UUID operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + sourceGame.getId(), + sourceGame.getTenantId(), + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + sourceGame.getId(), + sourceGame.getTenantId(), + "NEW_GAME_ROW", + evidenceDigest); + + isolatedTransaction.execute( + status -> { + isolatedDsl.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()); + isolatedDsl.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 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 Map legacyLaunchDescriptorSnapshot( + DSLContext isolatedDsl, String privateTenantKey, String controlPlaneRequestId) { + var record = + isolatedDsl.fetchOne( + "SELECT id, launch_descriptor_id, tenant_id, game_template_id, " + + "control_plane_request_id, request_hash, version_id, script_patch_version, " + + "runtime_flags_json, generation_config_revision, version_state_epoch, " + + "release_bundle_id, published_release_bundle_ref, remap_set_id, created_at " + + "FROM launch_descriptor WHERE tenant_id = ? AND control_plane_request_id = ?", + privateTenantKey, + controlPlaneRequestId); + if (record == null) { + throw new IllegalStateException("Retained V34 launch descriptor fixture is missing"); + } + return record.intoMap(); + } + + private Map retainedReleaseBundleSnapshot(DSLContext isolatedDsl, long bundleId) { + var record = + isolatedDsl.fetchOne( + "SELECT id, tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, generation_config_revision, " + + "required_manifest_asset_keys_json, participant_digests_json, " + + "command_definitions_json, script_only, script_patch_version, published_at " + + "FROM published_release_bundle WHERE id = ?", + bundleId); + if (record == null) { + throw new IllegalStateException("Retained V34 release bundle fixture is missing"); + } + return record.intoMap(); + } + + private Map> publicationEvidenceRows( + DSLContext isolatedDsl, + long versionId, + long bundleId, + long descriptorId, + long attemptId, + long artifactId) { + return Map.of( + "version", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM version WHERE id = ?", + versionId, + "Version"), + "published_release_bundle", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM published_release_bundle WHERE id = ?", + bundleId, + "published release bundle"), + "launch_descriptor", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM launch_descriptor WHERE id = ?", + descriptorId, + "launch descriptor"), + "publish_attempt", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM publish_attempt WHERE id = ?", + attemptId, + "publish attempt"), + "version_asset_artifact", + requiredRow( + isolatedDsl, + "SELECT *, xmin::text AS xmin FROM version_asset_artifact WHERE id = ?", + artifactId, + "version asset artifact")); + } + + private Map> priorPublicationEvidenceColumns( + Map> snapshots) { + Map> originalColumns = new LinkedHashMap<>(); + snapshots.forEach( + (table, snapshot) -> { + Map original = new LinkedHashMap<>(snapshot); + if ("published_release_bundle".equals(table)) { + original.remove("world_published_start_location_evidence_json"); + } else if ("publish_attempt".equals(table)) { + original.remove("revision"); + } + originalColumns.put(table, original); + }); + return originalColumns; + } + + private Map requiredRow( + DSLContext isolatedDsl, String query, long rowId, String description) { + var row = isolatedDsl.fetchOne(query, rowId); + if (row == null) { + throw new IllegalStateException(description + " readback is absent"); + } + return row.intoMap(); + } + + private Map requiredSnapshot( + Map> snapshots, String description) { + Map snapshot = snapshots.get(description); + if (snapshot == null) { + throw new IllegalStateException(description + " snapshot is absent"); + } + return snapshot; + } + + private long requiredId(Long id, String description) { + if (id == null) { + throw new IllegalStateException(description + " insert returned no identity"); + } + return id; + } + + private String privateTenantKey() { + return "src-" + UUID.randomUUID().toString().replace("-", ""); + } + + private void assertRetainedRowUnchanged(LaunchDescriptor expected, LaunchDescriptor actual) { + assertThat(actual.getId()).isEqualTo(expected.getId()); + assertThat(actual.getLaunchDescriptorId()).isEqualTo(expected.getLaunchDescriptorId()); + assertThat(actual.getTenantId()).isEqualTo(expected.getTenantId()); + assertThat(actual.getGameTemplateId()).isEqualTo(expected.getGameTemplateId()); + assertThat(actual.getControlPlaneRequestId()).isEqualTo(expected.getControlPlaneRequestId()); + assertThat(actual.getRequestHash()).isEqualTo(expected.getRequestHash()); + assertThat(actual.getVersionId()).isEqualTo(expected.getVersionId()); + assertThat(actual.getScriptPatchVersion()).isEqualTo(expected.getScriptPatchVersion()); + assertThat(actual.getRuntimeFlagsJson()).isEqualTo(expected.getRuntimeFlagsJson()); + assertThat(actual.getGenerationConfigRevision()) + .isEqualTo(expected.getGenerationConfigRevision()); + assertThat(actual.getVersionStateEpoch()).isEqualTo(expected.getVersionStateEpoch()); + assertThat(actual.getReleaseBundleId()).isEqualTo(expected.getReleaseBundleId()); + assertThat(actual.getPublishedReleaseBundleRef()) + .isEqualTo(expected.getPublishedReleaseBundleRef()); + assertThat(actual.getRemapSetId()).isEqualTo(expected.getRemapSetId()); + assertThat(actual.getCreatedAt()).isEqualTo(expected.getCreatedAt()); + assertThat(actual.getDescriptorSchemaVersion()).isNull(); + assertThat(actual.getTargetNamespace()).isNull(); + assertThat(actual.getCanonicalTenantId()).isNull(); + assertThat(actual.getWorldSlug()).isNull(); + assertThat(actual.getAuthoredWorldSourceOperationId()).isNull(); + assertThat(actual.getAuthoredWorldSourceEvidenceDigest()).isNull(); + assertThat(actual.getRequestDigest()).isNull(); + assertThat(actual.getResultDigest()).isNull(); + assertThat(actual.getOriginalRequestJson()).isNull(); + assertThat(actual.getSourceEvidenceJson()).isNull(); + } + + private record Fixture( + String controlPlaneRequestId, + UUID canonicalTenantId, + String privateSourceTenantKey, + AuthoredWorldSourceEvidence source, + Version version, + GameTemplate template, + PublishedReleaseBundle bundle) { + AuthoredWorldLaunchDescriptorEvidence.Request request() { + return request(controlPlaneRequestId); + } - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - "1", template.getId(), "integration-cp-1", null, null, null, null); + AuthoredWorldLaunchDescriptorEvidence.Request request(String requestId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + requestId, + canonicalTenantId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + template.getId(), + false, + null, + false, + null, + false, + null, + false, + null); + } - assertThat(descriptor.gameTemplateId()).isEqualTo(template.getId()); - assertThat(descriptor.versionId()).isEqualTo(version.getId()); - assertThat(descriptor.generationConfigRevision()).isEqualTo("genrev:integration"); - assertThat(descriptor.versionStateEpoch()).isEqualTo(1L); + AuthoredWorldLaunchDescriptorEvidence.Request requestWithPatch(String patch) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + canonicalTenantId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + template.getId(), + true, + patch, + false, + null, + false, + null, + false, + null); + } } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalReadGrpcServiceTest.java new file mode 100644 index 0000000000..7d5eeb7d29 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalReadGrpcServiceTest.java @@ -0,0 +1,296 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.GameDesignDraftTerminalReadStatus; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignDraftTerminalOutcomeRequest; +import net.firedevops.firemud.gamedesign.v1.ReadGameDesignDraftTerminalOutcomeResponse; +import org.junit.jupiter.api.Test; + +/** Receiver adapter proof with stipulated Account peer identity and mocked terminal storage. */ +class GameDesignDraftTerminalReadGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final DraftAuthorizationFenceBinding ACCOUNT_BINDING = accountBinding(); + private static final byte[] ACCOUNT_BINDING_BYTES = ACCOUNT_BINDING.canonicalBytes(); + + @Test + void rejectsMissingOrWrongAccountPeerBeforeDecodingOrReading() { + GameDesignDraftTerminalOutcomeRepository repository = + mock(GameDesignDraftTerminalOutcomeRepository.class); + var service = new GameDesignDraftTerminalReadGrpcService(repository, NAMESPACE); + ReadGameDesignDraftTerminalOutcomeRequest malformed = + ReadGameDesignDraftTerminalOutcomeRequest.newBuilder().setSchemaVersion(-1).build(); + + Collector noPeer = new Collector(); + service.readGameDesignDraftTerminalOutcome(malformed, noPeer); + assertThat(noPeer.errorCode).isEqualTo(Status.Code.PERMISSION_DENIED); + + Collector wrongService = new Collector(); + invokeAs(service, malformed, wrongService, peer("world-management-service", NAMESPACE)); + assertThat(wrongService.errorCode).isEqualTo(Status.Code.PERMISSION_DENIED); + + Collector wrongNamespace = new Collector(); + invokeAs(service, malformed, wrongNamespace, peer("account-service", "other")); + assertThat(wrongNamespace.errorCode).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void authenticatedAccountGetsUnknownForMissingOperationWithoutInventedOutcome() { + GameDesignDraftTerminalOutcomeRepository repository = + mock(GameDesignDraftTerminalOutcomeRepository.class); + when(repository.readAccountBound(any(byte[].class))).thenReturn(Optional.empty()); + var service = new GameDesignDraftTerminalReadGrpcService(repository, NAMESPACE); + var request = + GameDesignDraftTerminalReadEvidence.Request.create(NAMESPACE, ACCOUNT_BINDING_BYTES); + Collector response = new Collector(); + + invokeAs( + service, + GameDesignDraftTerminalReadGrpcCodec.toRequest(request), + response, + peer("account-service", NAMESPACE)); + + verify(repository).readAccountBound(eq(ACCOUNT_BINDING_BYTES)); + assertThat(response.errorCode).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value.getStatus()) + .isEqualTo( + GameDesignDraftTerminalReadStatus.GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_UNKNOWN); + assertThat(response.value.getOwnerReadbackBytes()).isEmpty(); + } + + @Test + void returnsOnlyPersistedCommittedOrDefinitiveAbortOwnerReadbacks() { + for (GameDesignDraftTerminalOutcome.Result result : + List.of( + GameDesignDraftTerminalOutcome.Result.COMMITTED, + GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED)) { + GameDesignDraftTerminalOutcomeRepository repository = + mock(GameDesignDraftTerminalOutcomeRepository.class); + var outcome = terminalOutcome(result); + when(repository.readAccountBound(any(byte[].class))).thenReturn(Optional.of(outcome)); + var service = new GameDesignDraftTerminalReadGrpcService(repository, NAMESPACE); + var request = + GameDesignDraftTerminalReadEvidence.Request.create(NAMESPACE, ACCOUNT_BINDING_BYTES); + Collector response = new Collector(); + + invokeAs( + service, + GameDesignDraftTerminalReadGrpcCodec.toRequest(request), + response, + peer("account-service", NAMESPACE)); + + verify(repository).readAccountBound(eq(ACCOUNT_BINDING_BYTES)); + assertThat(response.errorCode).isNull(); + assertThat(response.completed).isTrue(); + var evidence = GameDesignDraftTerminalReadGrpcCodec.fromResponse(request, response.value); + assertThat(evidence.ownerReadback()).isPresent(); + assertThat(evidence.ownerReadback().orElseThrow().canonicalBytes()) + .containsExactly(outcome.toOwnerReadback().canonicalBytes()); + assertThat(response.value.getStatus()) + .isEqualTo( + result == GameDesignDraftTerminalOutcome.Result.COMMITTED + ? GameDesignDraftTerminalReadStatus + .GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_COMMITTED + : GameDesignDraftTerminalReadStatus + .GAME_DESIGN_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED); + } + } + + @Test + void malformedAuthenticatedRequestAndCrossNamespaceRequestNeverReachRepository() { + GameDesignDraftTerminalOutcomeRepository repository = + mock(GameDesignDraftTerminalOutcomeRepository.class); + var service = new GameDesignDraftTerminalReadGrpcService(repository, NAMESPACE); + + Collector malformed = new Collector(); + invokeAs( + service, + ReadGameDesignDraftTerminalOutcomeRequest.newBuilder().setSchemaVersion(-1).build(), + malformed, + peer("account-service", NAMESPACE)); + assertThat(malformed.errorCode).isEqualTo(Status.Code.INVALID_ARGUMENT); + + var otherNamespaceRequest = + GameDesignDraftTerminalReadEvidence.Request.create("other", ACCOUNT_BINDING_BYTES); + Collector wrongNamespace = new Collector(); + invokeAs( + service, + GameDesignDraftTerminalReadGrpcCodec.toRequest(otherNamespaceRequest), + wrongNamespace, + peer("account-service", NAMESPACE)); + assertThat(wrongNamespace.errorCode).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void ownerStorageFailureIsUnavailableWithoutPartialBytes() { + GameDesignDraftTerminalOutcomeRepository repository = + mock(GameDesignDraftTerminalOutcomeRepository.class); + when(repository.readAccountBound(any(byte[].class))) + .thenThrow(new org.jooq.exception.DataAccessException("owner store unavailable")); + var service = new GameDesignDraftTerminalReadGrpcService(repository, NAMESPACE); + var request = + GameDesignDraftTerminalReadEvidence.Request.create(NAMESPACE, ACCOUNT_BINDING_BYTES); + Collector response = new Collector(); + + invokeAs( + service, + GameDesignDraftTerminalReadGrpcCodec.toRequest(request), + response, + peer("account-service", NAMESPACE)); + + assertThat(response.errorCode).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + } + + private static GameDesignDraftTerminalOutcome terminalOutcome( + GameDesignDraftTerminalOutcome.Result result) { + var operation = new GameDesignDraftTerminalOperation(ACCOUNT_BINDING); + String owner = operation.gameDesignBinding().requiredOwners().get(0).name(); + String status = + result == GameDesignDraftTerminalOutcome.Result.COMMITTED ? "APPLIED" : "REJECTED"; + String vector = + "[{\"appliedEpochs\":[],\"bindingDigest\":\"" + + operation.gameDesignBinding().digest() + + "\",\"commitId\":\"" + + operation.gameDesignBinding().commitId() + + "\",\"owner\":\"" + + owner + + "\",\"resultBytesBase64\":\"AQ==\",\"resultIdentity\":\"test-result\",\"status\":\"" + + status + + "\"}]"; + byte[] evidence = + result == GameDesignDraftTerminalOutcome.Result.COMMITTED + ? vector.getBytes(StandardCharsets.UTF_8) + : new byte[] {8, 9}; + return new GameDesignDraftTerminalOutcome( + operation, + result, + vector, + evidence, + GameDesignDraftTerminalOperation.sha256(evidence), + OffsetDateTime.now()); + } + + private static void invokeAs( + GameDesignDraftTerminalReadGrpcService service, + ReadGameDesignDraftTerminalOutcomeRequest request, + Collector collector, + GrpcPeerIdentity peer) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readGameDesignDraftTerminalOutcome(request, collector); + } finally { + context.detach(previous); + } + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static DraftAuthorizationFenceBinding accountBinding() { + UUID tenant = uuid("11111111-1111-4111-8111-111111111111"); + UUID version = uuid("22222222-2222-4222-8222-222222222222"); + UUID request = uuid("44444444-4444-4444-8444-444444444444"); + UUID commit = uuid("55555555-5555-4555-8555-555555555555"); + DraftCommitBinding draft = + DraftCommitBinding.create( + new TargetProof(tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request, + commit, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + tenant, + version, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Collector + implements StreamObserver { + private ReadGameDesignDraftTerminalOutcomeResponse value; + private Status.Code errorCode; + private boolean completed; + + @Override + public void onNext(ReadGameDesignDraftTerminalOutcomeResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + errorCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java index 3146193994..f700bfddb2 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java @@ -47,6 +47,10 @@ public void executeStart(ExecuteContext context) { + "\"last_error_code\" VARCHAR(255), " + "\"last_error_message\" VARCHAR(1000), " + "\"exported_manifest_asset_keys_json\" VARCHAR(4000), " + + "\"manifest_schema_version\" INTEGER, " + + "\"artifact_digests_json\" TEXT, " + + "\"published_object_proofs_json\" TEXT, " + + "\"candidate_snapshot_version_id\" BIGINT, " + "\"updated_at\" TIMESTAMP NOT NULL, " + "UNIQUE (\"tenant_id\", \"version_id\"))"); @@ -59,6 +63,10 @@ public void executeStart(ExecuteContext context) { artifact.setManifestHash("manifest-7"); artifact.setLastWorkflowId("publish-7"); artifact.setExportedManifestAssetKeysJson("[\"manifest.json\"]"); + artifact.setManifestSchemaVersion(1); + artifact.setArtifactDigestsJson("[]"); + artifact.setPublishedObjectProofsJson("[]"); + artifact.setCandidateSnapshotVersionId(7L); VersionAssetArtifact inserted = new VersionAssetArtifactRepository(dsl).save(artifact); @@ -70,6 +78,10 @@ public void executeStart(ExecuteContext context) { assertThat(inserted.getManifestHash()).isEqualTo("manifest-7"); assertThat(inserted.getLastWorkflowId()).isEqualTo("publish-7"); assertThat(inserted.getExportedManifestAssetKeysJson()).isEqualTo("[\"manifest.json\"]"); + assertThat(inserted.getManifestSchemaVersion()).isEqualTo(1); + assertThat(inserted.getArtifactDigestsJson()).isEqualTo("[]"); + assertThat(inserted.getPublishedObjectProofsJson()).isEqualTo("[]"); + assertThat(inserted.getCandidateSnapshotVersionId()).isEqualTo(7L); assertThat(inserted.getUpdatedAt()).isNotNull(); assertThat(executedSql) .filteredOn(sql -> sql.toLowerCase().contains(" where ")) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java index ffc5d472c2..e6a946f2ce 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java @@ -22,6 +22,11 @@ void scriptPatchPublicationLookupUsesExactRetainedScopeAndLeavesAmbiguityVisible "CREATE TABLE \"version\" (" + "\"id\" BIGINT PRIMARY KEY, " + "\"tenant_id\" VARCHAR(36) NOT NULL, " + + "\"canonical_version_id\" UUID, " + + "\"canonical_tenant_id\" UUID, " + + "\"identity_source_game_row_id\" BIGINT, " + + "\"identity_source_game_tenant_key\" VARCHAR(36), " + + "\"identity_source_provenance_kind\" VARCHAR(32), " + "\"version_number\" INT NOT NULL, " + "\"version_state\" VARCHAR(32) NOT NULL, " + "\"version_state_epoch\" BIGINT NOT NULL, " diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/ExportedAssetManifestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/ExportedAssetManifestTest.java new file mode 100644 index 0000000000..b9181f7bfd --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/ExportedAssetManifestTest.java @@ -0,0 +1,23 @@ +package net.firedevops.firemud.gamedesign.service; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class ExportedAssetManifestTest { + @Test + void processLocalExportCannotSupplyImmutablePublicationProof() { + var exported = new ExportedAssetManifest("process-local-hash", List.of("manifest.json")); + assertEquals(List.of("manifest.json"), exported.requiredManifestAssetKeys()); + assertThrows(IllegalStateException.class, exported::requireImmutableArtifactEvidence); + } + + @Test + void completeEmptyManifestCarriesExplicitImmutableArtifactProof() { + var exported = new ExportedAssetManifest("sha256:" + "a".repeat(64), 1, List.of(), List.of()); + assertDoesNotThrow(exported::requireImmutableArtifactEvidence); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java new file mode 100644 index 0000000000..67feb4debf --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateGrpcServiceTest.java @@ -0,0 +1,211 @@ +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.junit.jupiter.api.Test; + +class AuthoredWorldVersionStateGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REGISTRATION_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID CANONICAL_VERSION_ID = uuid("55555555-5555-4555-8555-555555555555"); + + @Test + void exactWorldPeerMayReadAndReceivesClosedEvidence() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + var request = request(); + var evidence = + AuthoredWorldVersionStateEvidence.create( + request, + sourceEvidence(), + CANONICAL_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 7L); + when(service.read(request)).thenReturn(evidence); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + TestObserver observer = new TestObserver<>(); + + withPeer( + peer(NAMESPACE, "world-management-service"), + () -> + handler.getAuthoredWorldVersionState( + AuthoredWorldVersionStateGrpcCodec.toRequest(request), observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getEvidence().getCanonicalVersionId()) + .isEqualTo(CANONICAL_VERSION_ID.toString()); + assertThat( + observer + .value + .getEvidence() + .getDescriptorForType() + .findFieldByName("canonical_version_id") + .getNumber()) + .isEqualTo(13); + assertThat(AuthoredWorldVersionStateGrpcCodec.fromResponse(request, observer.value)) + .isEqualTo(evidence); + verify(service).read(request); + } + + @Test + void exactPeerGuardRunsBeforeMalformedRequestDecodeOrOwnerAccess() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + GetAuthoredWorldVersionStateRequest malformed = + GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(99) + .setReadRequestId("not-a-uuid") + .build(); + + TestObserver absent = new TestObserver<>(); + handler.getAuthoredWorldVersionState(malformed, absent); + assertStatus(absent, Status.Code.PERMISSION_DENIED); + + TestObserver wrongService = new TestObserver<>(); + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> handler.getAuthoredWorldVersionState(malformed, wrongService)); + assertStatus(wrongService, Status.Code.PERMISSION_DENIED); + + TestObserver wrongNamespace = new TestObserver<>(); + withPeer( + peer("other", "world-management-service"), + () -> handler.getAuthoredWorldVersionState(malformed, wrongNamespace)); + assertStatus(wrongNamespace, Status.Code.PERMISSION_DENIED); + + verifyNoInteractions(service); + } + + @Test + void exactPeerGetsInvalidArgumentBeforeAnyOwnerReadForMalformedClosedRequest() { + AuthoredWorldVersionStateService service = mock(AuthoredWorldVersionStateService.class); + var handler = new AuthoredWorldVersionStateGrpcService(service, NAMESPACE); + GetAuthoredWorldVersionStateRequest malformed = + GetAuthoredWorldVersionStateRequest.newBuilder() + .setSchemaVersion(2) + .setTargetNamespace(NAMESPACE) + .setReadRequestId(READ_REQUEST_ID.toString()) + .build(); + TestObserver observer = new TestObserver<>(); + + withPeer( + peer(NAMESPACE, "world-management-service"), + () -> handler.getAuthoredWorldVersionState(malformed, observer)); + + assertStatus(observer, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(service); + } + + private static void assertStatus(TestObserver observer, Status.Code expectedCode) { + assertThat(observer.error).isNotNull(); + assertThat(observer.error.type()).isEqualTo(StatusRuntimeException.class); + assertThat(observer.error.code()).isEqualTo(expectedCode); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static AuthoredWorldVersionStateEvidence.Request request() { + AuthoredWorldSourceEvidence source = sourceEvidence(); + return new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String displayName = "Café 🐉"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT_ID, "tenant-one", "cafe-coast", displayName); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW")); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class TestObserver implements StreamObserver { + private T value; + private ErrorEvidence error; + private boolean completed; + + @Override + public void onNext(T next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + error = new ErrorEvidence(failure.getClass(), Status.fromThrowable(failure).getCode()); + } + + @Override + public void onCompleted() { + completed = true; + } + + private record ErrorEvidence(Class type, Status.Code code) {} + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateServiceTest.java new file mode 100644 index 0000000000..77743c83e2 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateServiceTest.java @@ -0,0 +1,227 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; + +class AuthoredWorldVersionStateServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID SOURCE_OPERATION_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REGISTRATION_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID CANONICAL_VERSION_ID = uuid("55555555-5555-4555-8555-555555555555"); + + @Test + void readsCompleteSourceAndVersionInsideFreshReadOnlyRepeatableReadTransaction() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + GameAuthoredWorldSourceRepository repository = mock(GameAuthoredWorldSourceRepository.class); + AuthoredWorldSourceEvidence source = sourceEvidence(); + when(repository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, + CANONICAL_VERSION_ID, + net.firedevops.firemud.gamedesign.model.VersionLifecycleState.PUBLISHED, + 7L))); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + AuthoredWorldVersionStateEvidence evidence = service.read(request(source.evidenceDigest())); + + assertThat(evidence.sourceEvidence()).isEqualTo(source); + assertThat(evidence.canonicalVersionId()).isEqualTo(CANONICAL_VERSION_ID); + assertThat(evidence.versionState()) + .isEqualTo(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED); + assertThat(evidence.versionStateEpoch()).isEqualTo(7L); + assertThat(transactionManager.definition).isNotNull(); + assertThat(transactionManager.definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(transactionManager.definition.isReadOnly()).isTrue(); + verify(repository) + .readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L); + } + + @Test + void missingExactSourceOrVersionFailsClosed() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + GameAuthoredWorldSourceRepository repository = mock(GameAuthoredWorldSourceRepository.class); + when(repository.readVersionStateSnapshot( + eq(NAMESPACE), + eq(READ_REQUEST_ID), + eq(TENANT_ID), + eq("cafe-coast"), + eq(SOURCE_OPERATION_ID), + any(String.class), + eq(19L))) + .thenReturn(Optional.empty()); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + assertThatThrownBy(() -> service.read(request("sha256:" + "a".repeat(64)))) + .isInstanceOf(AuthoredWorldVersionStateService.NotFoundException.class) + .hasMessageContaining("exact requested owner tuple"); + } + + @Test + void repositoryOwnerConsistencyFailuresDoNotBecomeEvidence() { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + GameAuthoredWorldSourceRepository repository = mock(GameAuthoredWorldSourceRepository.class); + when(repository.readVersionStateSnapshot( + eq(NAMESPACE), + eq(READ_REQUEST_ID), + eq(TENANT_ID), + eq("cafe-coast"), + eq(SOURCE_OPERATION_ID), + any(String.class), + eq(19L))) + .thenThrow( + new GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException( + "source binding changed")); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + assertThatThrownBy(() -> service.read(request("sha256:" + "a".repeat(64)))) + .isInstanceOf(GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException.class) + .hasMessageContaining("source binding changed"); + } + + @Test + void missingOrNilPersistedCanonicalVersionIdFailsClosed() { + for (UUID canonicalVersionId : new UUID[] {null, new UUID(0L, 0L)}) { + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + GameAuthoredWorldSourceRepository repository = mock(GameAuthoredWorldSourceRepository.class); + AuthoredWorldSourceEvidence source = sourceEvidence(); + when(repository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + source.evidenceDigest(), + 19L)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, + canonicalVersionId, + net.firedevops.firemud.gamedesign.model.VersionLifecycleState.PUBLISHED, + 7L))); + AuthoredWorldVersionStateService service = + new AuthoredWorldVersionStateService(transactionManager, repository); + + if (canonicalVersionId == null) { + assertThatThrownBy(() -> service.read(request(source.evidenceDigest()))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("canonicalVersionId"); + } else { + assertThatThrownBy(() -> service.read(request(source.evidenceDigest()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + } + } + } + + private static AuthoredWorldVersionStateEvidence.Request request(String sourceDigest) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + READ_REQUEST_ID, + TENANT_ID, + "cafe-coast", + SOURCE_OPERATION_ID, + sourceDigest, + 19L); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + String displayName = "Café 🐉"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST_ID, TENANT_ID, "tenant-one", "cafe-coast", displayName); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + TENANT_ID, + "tenant-one", + "cafe-coast", + displayName, + 42L, + "game-owner-tenant", + "NEW_GAME_ROW")); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class RecordingTransactionManager + extends AbstractPlatformTransactionManager { + private TransactionDefinition definition; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition transactionDefinition) { + definition = transactionDefinition; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java new file mode 100644 index 0000000000..3917711ae3 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -0,0 +1,1011 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.test.util.ReflectionTestUtils; + +class CompleteLaunchBindingServiceImplTest { + @Test + void selectorReleaseIsAssembledFromImmutableLocalBundleWithoutMutableOwnerReads() + throws Exception { + var selector = + PublishedWorldSelectorFixtures.evidence( + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_ID, + PRIVATE_TENANT_KEY, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); + var selected = + new PublishedReleaseBundleDto( + bundle.id(), + bundle.tenantId(), + bundle.versionId(), + bundle.versionNumber(), + "v2", + selector.request().publishWorkflowId(), + bundle.manifestHash(), + bundle.requiredManifestAssetKeys(), + PublishedWorldSelectorFixtures.participants(VERSION_ID, selector), + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.scriptOnly(), + bundle.scriptPatchVersion(), + bundle.publishedAt(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.publishedReleaseBundleRef(), + bundle.manifestSchemaVersion(), + bundle.artifactDigests(), + selector); + givenBundle(selected); + var result = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + assertEquals(2, result.releaseAttestation().schemaVersion()); + assertEquals(selector, result.releaseAttestation().worldStartLocationEvidence()); + result.releaseAttestation().requireValid(descriptor); + verifyReadOnlyCallsOnly(); + } + + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = + UUID.fromString("72345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_REGISTRATION_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final String WORLD_SLUG = "silver-march"; + private static final String PRIVATE_TENANT_KEY = "game-owner-key-901"; + private static final long VERSION_ID = 7L; + private static final int VERSION_NUMBER = 12; + private static final long BUNDLE_ID = 211L; + private static final String CONTROL_PLANE_REQUEST_ID = "launch-request-901"; + private static final String BUNDLE_REF = "opaque-release-reference-from-owner"; + private static final String WORKFLOW_ID = + "publish:game-owner-key-901:publish-request:publish-901"; + private static final String MANIFEST_HASH = "sha256:" + "c".repeat(64); + private static final String CONTENT_DIGEST = "d".repeat(64); + private static final String ABILITY_SCHEMA_DIGEST = "sha256:" + "e".repeat(64); + private static final String ARTIFACT_DIGEST = "sha256:" + "f".repeat(64); + + @Mock private LaunchDescriptorService launchDescriptorService; + @Mock private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + @Mock private PublishedReleaseBundleService publishedReleaseBundleService; + @Mock private VersionRepository versionRepository; + + private CompleteLaunchBindingServiceImpl service; + private AuthoredWorldSourceEvidence source; + private AuthoredWorldLaunchDescriptorEvidence descriptor; + private ResolvedLaunchDescriptorDto resolved; + private PublishedReleaseBundleDto bundle; + private Version version; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + source = sourceEvidence(WORLD_SLUG); + descriptor = descriptorEvidence(source); + resolved = resolvedDescriptor(descriptor); + bundle = validBundle(); + version = canonicalVersion(); + service = + new CompleteLaunchBindingServiceImpl( + launchDescriptorService, + authoredWorldSourceRepository, + publishedReleaseBundleService, + versionRepository); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + givenValidSnapshot(); + } + + @Test + void returnsImmutableFullBindingUsingTheDescriptorEpochAfterCurrentVersionStateAdvances() { + var first = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + version.setVersionState(VersionLifecycleState.RETIRED); + version.setVersionStateEpoch(44L); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.RETIRED, 44L))); + + var later = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + + assertEquals(descriptor, first.descriptor()); + assertEquals(descriptor.versionStateEpoch(), first.releaseAttestation().versionStateEpoch()); + assertEquals(first.releaseAttestation(), later.releaseAttestation()); + assertEquals( + first.releaseAttestation().evidenceDigest(), later.releaseAttestation().evidenceDigest()); + verifyReadOnlyCallsOnly(); + } + + @Test + void rejectsMissingOrSubstitutedSourceEvidence() { + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn(Optional.empty()); + assertDenied(); + + AuthoredWorldSourceEvidence substituted = sourceEvidence("other-world"); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + substituted, CANONICAL_VERSION_ID, VersionLifecycleState.PUBLISHED, 17L))); + assertDenied(); + } + + @Test + void rejectsMissingOrSubstitutedReleaseIdentityAndReference() { + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_TENANT_KEY, VERSION_ID)) + .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_TENANT_KEY, VERSION_ID)); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID + 1, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + bundle.publishedReleaseBundleRef(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + "substituted-reference", + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + "other-private-key", + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID + 1, + VERSION_NUMBER, + BUNDLE_REF, + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER + 1, + BUNDLE_REF, + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + } + + @Test + void rejectsMissingCanonicalVersionOrContradictoryPersistedGameProvenance() { + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.empty()); + assertDenied(); + + version.setIdentitySourceGameRowId(74L); + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.of(version)); + assertDenied(); + } + + @Test + void rejectsCanonicalTenantOrVersionUuidSubstitution() { + UUID otherCanonicalTenant = UUID.fromString("92345678-1234-4234-8234-123456789abc"); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + otherCanonicalTenant, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + UUID otherCanonicalVersion = UUID.fromString("a2345678-1234-4234-8234-123456789abc"); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + otherCanonicalVersion, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + } + + @Test + void requiresOneConsistentOwnerSnapshotAndMonotonicHistoricalEpoch() { + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.PUBLISHED, 16L))); + assertDenied(); + + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.RETIRED, 23L))); + assertDenied(); + } + + @Test + void rejectsReleaseVersionUuidThatDiffersFromTheSameSourceSnapshot() { + UUID differentVersionId = UUID.fromString("b2345678-1234-4234-8234-123456789abc"); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, differentVersionId, VersionLifecycleState.PUBLISHED, 23L))); + + assertDenied(); + verify(versionRepository, never()) + .findByCanonicalTenantIdAndCanonicalVersionId(CANONICAL_TENANT_ID, CANONICAL_VERSION_ID); + } + + @Test + void rejectsAbsentOrNilCanonicalVersionUuidWithoutNumericInference() { + UUID nil = new UUID(0L, 0L); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + nil, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + verify(versionRepository, never()) + .findByCanonicalTenantIdAndCanonicalVersionId(CANONICAL_TENANT_ID, nil); + } + + @Test + void rejectsScriptOnlyVersionMetadata() { + version.setScriptOnly(true); + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.of(version)); + assertDenied(); + + version.setScriptOnly(false); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + true, + "patch-1")); + assertDenied(); + } + + @Test + void rejectsMissingOrContradictoryManifestAndArtifactProof() { + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + null, + bundle.manifestHash(), + null, + false, + null)); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + "not-a-digest", + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + List.of("world.navmesh"), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + List.of(), + false, + null)); + assertDenied(); + } + + @Test + void rejectsMissingFailedUnsupportedAndMisorderedParticipantEvidence() { + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + List.of(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List unsupported = + new java.util.ArrayList<>(bundle.participantDigests()); + unsupported.set( + 0, + new PublishParticipantDigestDto( + PublishParticipantKey.WORLD_MANAGEMENT.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 99, + null, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + unsupported, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List failed = + new java.util.ArrayList<>(bundle.participantDigests()); + failed.set( + 0, + new PublishParticipantDigestDto( + PublishParticipantKey.WORLD_MANAGEMENT.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 2, + null, + "OWNER_FAILED", + "owner failed")); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + failed, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List misordered = + new java.util.ArrayList<>(bundle.participantDigests()); + java.util.Collections.swap(misordered, 0, 1); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + misordered, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + } + + @Test + void requiresGameLogicOwnedAbilityProofAndOneSharedParticipantCommit() { + List missingAbility = + new java.util.ArrayList<>(bundle.participantDigests()); + missingAbility.set( + 2, + new PublishParticipantDigestDto( + PublishParticipantKey.GAME_LOGIC.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 1, + null, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + missingAbility, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List mismatchedCommit = + new java.util.ArrayList<>(bundle.participantDigests()); + mismatchedCommit.set( + 4, + new PublishParticipantDigestDto( + PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE.name(), + Long.toString(VERSION_ID), + null, + "different-commit", + CONTENT_DIGEST, + 1, + null, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + mismatchedCommit, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List wrongAbilityOwner = + new java.util.ArrayList<>(bundle.participantDigests()); + wrongAbilityOwner.set( + 0, + new PublishParticipantDigestDto( + PublishParticipantKey.WORLD_MANAGEMENT.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 2, + ABILITY_SCHEMA_DIGEST, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + wrongAbilityOwner, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + } + + private void givenValidSnapshot() { + when(launchDescriptorService.getLaunchDescriptorInOwnerSnapshot( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest())) + .thenReturn(resolved); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.PUBLISHED, 23L))); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_TENANT_KEY, VERSION_ID)) + .thenReturn(bundle); + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.of(version)); + } + + private void givenBundle(PublishedReleaseBundleDto replacement) { + doReturn(replacement) + .when(publishedReleaseBundleService) + .getPublishedReleaseBundle(PRIVATE_TENANT_KEY, VERSION_ID); + } + + private void assertDenied() { + IllegalArgumentException denied = + assertThrows( + IllegalArgumentException.class, + () -> + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest())); + assertTrue( + denied.getMessage().startsWith("COMPLETE_LAUNCH_BINDING_") + || denied.getMessage().startsWith("LAUNCH_DESCRIPTOR_") + || denied.getMessage().startsWith("AUTHORED_WORLD_SOURCE_")); + verifyReadOnlyCallsOnly(); + } + + private void verifyReadOnlyCallsOnly() { + verify(launchDescriptorService, never()).resolveLaunchDescriptor(any()); + verify(authoredWorldSourceRepository, never()) + .register( + anyString(), any(UUID.class), any(UUID.class), anyString(), anyString(), anyString()); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle(any(), anyString(), any(), anyString(), any()); + verify(versionRepository, never()).save(any(Version.class)); + verify(versionRepository, never()).delete(any(Version.class)); + } + + private AuthoredWorldSourceEvidence sourceEvidence(String worldSlug) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + CANONICAL_TENANT_ID, + "silver-tenant", + worldSlug, + "Silver March"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + "silver-tenant", + worldSlug, + "Silver March", + 73L, + PRIVATE_TENANT_KEY, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + "silver-tenant", + worldSlug, + "Silver March", + 73L, + PRIVATE_TENANT_KEY, + "NEW_GAME_ROW", + evidenceDigest); + } + + private AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( + AuthoredWorldSourceEvidence sourceEvidence) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + CONTROL_PLANE_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence.evidenceDigest(), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-71234567-1234-4234-8234-123456789abc", + VERSION_ID, + false, + null, + "{}", + "generation-config-12", + 17L, + BUNDLE_ID, + BUNDLE_REF, + false, + null); + } + + private ResolvedLaunchDescriptorDto resolvedDescriptor( + AuthoredWorldLaunchDescriptorEvidence evidence) { + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private PublishedReleaseBundleDto validBundle() { + String artifactObjectKey = "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()); + return new PublishedReleaseBundleDto( + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + "v1", + WORKFLOW_ID, + MANIFEST_HASH, + List.of("world.navmesh"), + validParticipants(), + List.of("{\"commandId\":\"look\"}"), + "generation-config-12", + false, + null, + null, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + BUNDLE_REF, + 1, + List.of( + new PublishedArtifactDigest( + "world.navmesh", + "world-navmesh", + artifactObjectKey, + ARTIFACT_DIGEST, + "application/octet-stream", + 1))); + } + + private List validParticipants() { + return List.of( + participant(PublishParticipantKey.WORLD_MANAGEMENT.name(), 3, null), + participant(PublishParticipantKey.ENTITY_MANAGEMENT.name(), 2, null), + participant(PublishParticipantKey.GAME_LOGIC.name(), 1, ABILITY_SCHEMA_DIGEST), + participant(PublishParticipantKey.AUTOMATION_SCRIPTING.name(), 5, null), + participant(PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE.name(), 1, null)); + } + + private PublishParticipantDigestDto participant( + String participantKey, int digestSchemaVersion, String abilitySchemaDigest) { + return new PublishParticipantDigestDto( + participantKey, + Long.toString(VERSION_ID), + null, + "commit-12", + CONTENT_DIGEST, + digestSchemaVersion, + abilitySchemaDigest, + null, + null); + } + + private Version canonicalVersion() { + Version result = new Version(); + result.setId(VERSION_ID); + result.setTenantId(PRIVATE_TENANT_KEY); + result.setCanonicalTenantId(CANONICAL_TENANT_ID); + result.setCanonicalVersionId(CANONICAL_VERSION_ID); + result.setIdentitySourceGameRowId(73L); + result.setIdentitySourceGameTenantKey(PRIVATE_TENANT_KEY); + result.setIdentitySourceProvenanceKind("NEW_GAME_ROW"); + result.setVersionNumber((int) VERSION_NUMBER); + result.setVersionState(VersionLifecycleState.PUBLISHED); + result.setVersionStateEpoch(23L); + return result; + } + + private PublishedReleaseBundleDto copyBundle( + PublishedReleaseBundleDto original, + long id, + String tenantId, + long versionId, + int versionNumber, + String releaseRef, + UUID canonicalTenantId, + UUID canonicalVersionId, + List requiredKeys, + List participants, + Integer manifestSchemaVersion, + String manifestHash, + List artifacts, + boolean scriptOnly, + String scriptPatchVersion) { + return new PublishedReleaseBundleDto( + id, + tenantId, + versionId, + versionNumber, + original.attestationSchemaVersion(), + original.publishWorkflowId(), + manifestHash, + requiredKeys, + participants, + original.commandDefinitions(), + original.generationConfigRevision(), + scriptOnly, + scriptPatchVersion, + original.publishedAt(), + canonicalTenantId, + canonicalVersionId, + releaseRef, + manifestSchemaVersion, + artifacts); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index 6cdbaa103c..e642671375 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -98,7 +98,19 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { "1", 9L, "cp-1", null, null, null, null)) .thenReturn( new ResolvedLaunchDescriptorDto( - "ld-1", "1", 9L, "cp-1", 7L, null, "{}", "genrev-1", 11L, 11L, "prb:1:7:11", null)); + "ld-1", + "12345678-1234-4234-8234-123456789abc", + 9L, + "cp-1", + 7L, + null, + "{}", + "genrev-1", + 11L, + 11L, + "prb:1:7:11", + null, + null)); GameDesignGrpcService service = new GameDesignGrpcService( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 436a406852..285de48841 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -1060,7 +1060,7 @@ void resolveLaunchDescriptorReturnsDeterministicDescriptor() { .thenReturn( new ResolvedLaunchDescriptorDto( "ld-1", - "tenant-1", + "12345678-1234-4234-8234-123456789abc", 9L, "cp-1", 7L, @@ -1070,7 +1070,8 @@ void resolveLaunchDescriptorReturnsDeterministicDescriptor() { 11L, 11L, "prb:tenant-1:7:11", - "")); + "", + null)); AtomicReference ref = new AtomicReference<>(); try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index 78f7b1d6ec..b32c139c2e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -1,13 +1,28 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; @@ -15,6 +30,7 @@ import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; @@ -24,21 +40,127 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.test.util.ReflectionTestUtils; import tools.jackson.databind.ObjectMapper; class LaunchDescriptorServiceImplTest { + private static final String NAMESPACE = "test"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_REGISTRATION_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final String WORLD_SLUG = "silver-march"; + private static final String PRIVATE_SOURCE_TENANT_KEY = "game-owner-key-901"; + private static final String PUBLISHED_RELEASE_BUNDLE_REF = "opaque-release-reference-from-owner"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + @Mock private GameTemplateRepository gameTemplateRepository; @Mock private LaunchDescriptorRepository launchDescriptorRepository; @Mock private VersionRepository versionRepository; @Mock private PublishedReleaseBundleService publishedReleaseBundleService; @Mock private TemplateRemapSetService templateRemapSetService; + @Mock private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private LaunchDescriptorServiceImpl service; + @Test + void legacyLaunchEntryCannotResolveWithoutCanonicalSourceBinding() { + assertThrows( + IllegalStateException.class, + () -> + service.resolveLaunchDescriptor( + "legacy-owner-key", 9L, "legacy-request", null, null, null, null)); + Mockito.verifyNoInteractions( + gameTemplateRepository, + launchDescriptorRepository, + versionRepository, + publishedReleaseBundleService, + templateRemapSetService, + authoredWorldSourceRepository); + } + + @Test + void completeSelectorV2ResolvesTheUnchangedDescriptorV1Binding() throws Exception { + var request = request("cp-selector-v2", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + var bundle = selectorBundle(false); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(bundle); + + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(7L, resolved.versionId()); + assertEquals(11L, resolved.releaseBundleId()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); + assertEquals( + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION, + resolved.authoredWorldBinding().schemaVersion()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals(17L, resolved.versionStateEpoch()); + verify(launchDescriptorRepository).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void selectorV2WithoutCompleteParticipantProofCannotResolveOrFreezeSyntheticSuccess() + throws Exception { + var request = request("cp-incomplete-selector-v2", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(selectorBundle(true)); + + assertThrows(IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + private PublishedReleaseBundleDto selectorBundle(boolean omitParticipant) throws Exception { + // Stipulated original component bytes; this fixture does not authenticate a producer or admit + // gameplay. + WorldPublishedStartLocationEvidence evidence = + PublishedWorldSelectorFixtures.evidence( + new TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + 7L, + PRIVATE_SOURCE_TENANT_KEY, + 1L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW")); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + return new PublishedReleaseBundleDto( + 11L, + PRIVATE_SOURCE_TENANT_KEY, + 7L, + 8, + "v2", + evidence.request().publishWorkflowId(), + MANIFEST_HASH, + List.of(), + omitParticipant ? participants.subList(0, 4) : participants, + List.of(), + "genrev-1", + false, + null, + LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + PUBLISHED_RELEASE_BUNDLE_REF, + 1, + List.of(), + evidence); + } + @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); service = new LaunchDescriptorServiceImpl( gameTemplateRepository, @@ -46,122 +168,387 @@ void setUp() { versionRepository, publishedReleaseBundleService, templateRemapSetService, + authoredWorldSourceRepository, new ObjectMapper()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); } @Test - void resolveLaunchDescriptorPersistsDeterministicDescriptor() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); + void resolveLaunchDescriptorPersistsCanonicalBindingAndResolvedRelease() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-1", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + AtomicReference inserted = new AtomicReference<>(); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + inserted.set(descriptor); + return descriptor; + }); + + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(CANONICAL_TENANT_ID.toString(), resolved.canonicalTenantId()); + assertEquals(9L, resolved.gameTemplateId()); + assertEquals(7L, resolved.versionId()); + assertEquals("genrev-1", resolved.generationConfigRevision()); + assertEquals(17L, resolved.versionStateEpoch()); + assertEquals(11L, resolved.releaseBundleId()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); + assertNotNull(resolved.authoredWorldBinding()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals( + PRIVATE_SOURCE_TENANT_KEY, + inserted.get().getTenantId(), + "The private source key remains owner-local and is not the canonical tenant UUID"); + assertEquals(CANONICAL_TENANT_ID.toString(), inserted.get().getCanonicalTenantId()); + verify(authoredWorldSourceRepository) + .read(SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE); + verify(gameTemplateRepository).findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verify(gameTemplateRepository, never()) + .findLaunchConfigByTenantIdAndId(CANONICAL_TENANT_ID.toString(), 9L); + } + + @Test + void exactRetryReturnsStoredResultWithoutReadingChangedTemplateDefaultsVersionOrRelease() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-retry", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + stubBundle(7L, 11L, "v1"); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + stubSource(request, source); + AtomicReference stored = new AtomicReference<>(); + when(launchDescriptorRepository.findBoundByRequest(NAMESPACE, CANONICAL_TENANT_ID, "cp-retry")) + .thenAnswer(invocation -> Optional.ofNullable(stored.get())); + when(launchDescriptorRepository.findByPrivateRequest(PRIVATE_SOURCE_TENANT_KEY, "cp-retry")) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + stored.set(descriptor); + return descriptor; + }); + + var first = service.resolveLaunchDescriptor(request); + when(template.getDefaultVersionId()).thenReturn(8L); when(template.getDefaultScriptPatchVersion()).thenReturn("patch-1"); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) + clearInvocations(template); + when(versionRepository.findById(8L)).thenReturn(Optional.empty()); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 8L)) + .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_SOURCE_TENANT_KEY, 8L)); + + var retry = service.resolveLaunchDescriptor(request); + + assertEquals(first, retry); + assertEquals(7L, retry.versionId()); + verify(gameTemplateRepository, times(1)) + .findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verifyNoInteractions(template); + verify(versionRepository, times(1)).findById(7L); + verify(versionRepository, never()).findById(8L); + verify(publishedReleaseBundleService, times(1)) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 8L); + verify(launchDescriptorRepository, times(1)).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void changedSourceScopeTemplateOrRequestCannotReplaceOriginalDescriptor() { + AuthoredWorldLaunchDescriptorEvidence.Request original = request("cp-conflict", 9L); + stubSuccessfulLaunch(original, 7L, 11L); + LaunchDescriptor stored = descriptorFor(original, 7L, 11L); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, "cp-conflict")) + .thenReturn(Optional.of(stored)); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + AuthoredWorldLaunchDescriptorEvidence.Request changedTemplate = request("cp-conflict", 10L); + IllegalArgumentException templateConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedTemplate)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + templateConflict.getMessage()); + + AuthoredWorldLaunchDescriptorEvidence.Request changedRequest = + request("cp-conflict", 9L, true, "other-patch"); + IllegalArgumentException requestConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedRequest)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + requestConflict.getMessage()); + + UUID otherOperation = UUID.fromString("42345678-1234-4234-8234-123456789abc"); + AuthoredWorldLaunchDescriptorEvidence.Request changedSource = + request("cp-conflict", 9L, otherOperation, WORLD_SLUG, CANONICAL_TENANT_ID); + when(authoredWorldSourceRepository.read( + otherOperation, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE)) .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - version.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v1", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); - when(launchDescriptorRepository.save(any(LaunchDescriptor.class))) + IllegalArgumentException sourceConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedSource)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + sourceConflict.getMessage()); + + UUID otherCanonicalTenant = UUID.fromString("52345678-1234-4234-8234-123456789abc"); + AuthoredWorldLaunchDescriptorEvidence.Request changedTenantScope = + request("cp-conflict", 9L, SOURCE_OPERATION_ID, WORLD_SLUG, otherCanonicalTenant); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, otherCanonicalTenant, WORLD_SLUG, NAMESPACE)) + .thenReturn(Optional.empty()); + IllegalArgumentException scopeConflict = + assertThrows( + IllegalArgumentException.class, + () -> service.resolveLaunchDescriptor(changedTenantScope)); + assertEquals( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing", + scopeConflict.getMessage()); + + AuthoredWorldLaunchDescriptorEvidence.Request changedWorldScope = + request("cp-conflict", 9L, SOURCE_OPERATION_ID, "other-world", CANONICAL_TENANT_ID); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, "other-world", NAMESPACE)) + .thenReturn(Optional.empty()); + IllegalArgumentException worldConflict = + assertThrows( + IllegalArgumentException.class, + () -> service.resolveLaunchDescriptor(changedWorldScope)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + worldConflict.getMessage()); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void exactReadbackReturnsOriginalEvidenceAndRejectsDigestOrScopeSubstitution() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-read", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + when(launchDescriptorRepository.findBoundByRequest(NAMESPACE, CANONICAL_TENANT_ID, "cp-read")) + .thenReturn(Optional.of(stored)); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) .thenAnswer(invocation -> invocation.getArgument(0)); + var original = service.resolveLaunchDescriptor(request); + + var readback = + service.getLaunchDescriptor( + UUID.fromString("62345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest()); + + assertEquals(original, readback); + IllegalArgumentException changedRequestDigest = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("72345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + "sha256:" + "b".repeat(64), + original.authoredWorldBinding().resultDigest())); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedRequestDigest.getMessage()); - var descriptor = - service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null); + IllegalArgumentException changedResultDigest = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + original.authoredWorldBinding().requestDigest(), + "sha256:" + "c".repeat(64))); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedResultDigest.getMessage()); - assertEquals("tenant-1", descriptor.tenantId()); - assertEquals(7L, descriptor.versionId()); - assertEquals("genrev-1", descriptor.generationConfigRevision()); - assertEquals(17L, descriptor.versionStateEpoch()); - assertEquals(11L, descriptor.releaseBundleId()); + IllegalArgumentException changedWorld = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("92345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + "other-world", + "cp-read", + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest())); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedWorld.getMessage()); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); } @Test - void resolveLaunchDescriptorRejectsConflictingRequestReuse() { - LaunchDescriptor existing = new LaunchDescriptor(); - existing.setRequestHash("other-hash"); - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) - .thenReturn(Optional.of(existing)); + void selectedPatchWithoutExactPublicationAndReadinessEvidenceCannotResolve() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-patch", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, "patch-1"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + assertEquals( + "SCRIPT_PATCH_NOT_READY: exact published-for-base and Automation READY evidence is unavailable", + thrown.getMessage()); + verify(template).getDefaultScriptPatchVersion(); + org.mockito.ArgumentCaptor failure = + org.mockito.ArgumentCaptor.forClass(LaunchDescriptor.class); + verify(launchDescriptorRepository).insertImmutable(failure.capture()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, failure.getValue().getOutcomeStatus()); + assertEquals("SCRIPT_PATCH_NOT_READY", failure.getValue().getFailureCode()); + assertEquals(request.requestDigest(), failure.getValue().getRequestDigest()); + assertEquals(null, failure.getValue().getLaunchDescriptorId()); + assertEquals(null, failure.getValue().getVersionId()); + } + + @Test + void sourceAndTransientDependencyFailuresDoNotCreateFrozenOutcomes() { + AuthoredWorldLaunchDescriptorEvidence.Request missingSource = request("cp-no-source", 9L); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE)) + .thenReturn(Optional.empty()); + + IllegalArgumentException sourceFailure = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(missingSource)); + assertEquals( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing", + sourceFailure.getMessage()); + + AuthoredWorldLaunchDescriptorEvidence.Request changedSourceEvidence = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "cp-changed-source", + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + "sha256:" + "f".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + stubSource(changedSourceEvidence, sourceEvidence(WORLD_SLUG)); assertThrows( IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null)); + () -> service.resolveLaunchDescriptor(changedSourceEvidence)); + + AuthoredWorldLaunchDescriptorEvidence.Request unavailableDependency = + request("cp-unavailable", 9L); + stubSource(unavailableDependency, sourceEvidence(WORLD_SLUG)); + when(gameTemplateRepository.findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L)) + .thenThrow(new DataAccessResourceFailureException("temporary database outage")); + + assertThrows( + DataAccessResourceFailureException.class, + () -> service.resolveLaunchDescriptor(unavailableDependency)); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void exactRetryOfStoredFailureReturnsItsOriginalCodeAndMessageBeforeMutableReads() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-frozen-failure", 9L); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + LaunchDescriptor failure = new LaunchDescriptor(); + failure.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + failure.setControlPlaneRequestId(request.controlPlaneRequestId()); + failure.setRequestHash(request.requestDigest()); + failure.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); + failure.setTargetNamespace(NAMESPACE); + failure.setCanonicalTenantId(CANONICAL_TENANT_ID.toString()); + failure.setWorldSlug(WORLD_SLUG); + failure.setAuthoredWorldSourceOperationId(SOURCE_OPERATION_ID.toString()); + failure.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + failure.setRequestDigest(request.requestDigest()); + failure.setOriginalRequestJson(new ObjectMapper().writeValueAsString(request)); + failure.setSourceEvidenceJson(new ObjectMapper().writeValueAsString(source)); + failure.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); + failure.setFailureCode("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED"); + failure.setFailureMessage("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: frozen phase denial"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.of(failure)); + stubSource(request, source); + + FrozenLaunchDescriptorDenialException thrown = + assertThrows( + FrozenLaunchDescriptorDenialException.class, + () -> service.resolveLaunchDescriptor(request)); + + assertEquals("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", thrown.failureCode()); + assertEquals("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: frozen phase denial", thrown.getMessage()); + verify(gameTemplateRepository, never()) + .findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void tamperedStoredPatchCannotReplayOutsideItsCommittedResultDigest() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-tampered", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + stored.setScriptPatchVersion("patch-1"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, "cp-tampered")) + .thenReturn(Optional.of(stored)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: stored resolved result digest is inconsistent", + thrown.getMessage()); + } + + @Test + void resolveLaunchDescriptorPreservesTemplatePhaseGate() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-phase", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.LEGACY); + stubSource(request, sourceEvidence(WORLD_SLUG)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced", + thrown.getMessage()); } @Test void resolveLaunchDescriptorFailsClosedOnUnsupportedAttestationSchema() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn("patch-1"); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - version.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v2", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-schema", 9L); + stubTemplate(request, 7L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(releaseBundle(7L, 11L, "v999")); IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( true, @@ -173,33 +560,16 @@ void resolveLaunchDescriptorFailsClosedOnUnsupportedAttestationSchema() { @Test void resolveLaunchDescriptorReportsMissingReleaseBundleDeterministically() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-2")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenThrow(new PublishedReleaseBundleNotFoundException("tenant-1", 7L)); + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-missing-release", 9L); + stubTemplate(request, 7L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_SOURCE_TENANT_KEY, 7L)); IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-2", null, null, null, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version", @@ -207,34 +577,107 @@ void resolveLaunchDescriptorReportsMissingReleaseBundleDeterministically() { } @Test - void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-3")) + void missingOpaqueBundleReferenceDeniesCreationAndExactRetryWithoutSynthesizing() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-missing-reference", 9L); + stubTemplate(request, 7L, null); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + stubSource(request, source); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(releaseBundle(7L, 11L, "v1", null)); + AtomicReference stored = new AtomicReference<>(); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenAnswer(invocation -> Optional.ofNullable(stored.get())); + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(8L); - version.setTenantId("tenant-1"); - version.setVersionNumber(9); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(18L); - when(versionRepository.findById(8L)).thenReturn(Optional.of(version)); - when(templateRemapSetService.findApprovedTemplateRemapSet("tenant-1", 7L, 8L)) + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + stored.set(descriptor); + return descriptor; + }); + + IllegalArgumentException first = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + IllegalArgumentException retry = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "RELEASE_BUNDLE_NOT_FOUND: published release bundle has no persisted opaque reference", + first.getMessage()); + assertEquals(first.getMessage(), retry.getMessage()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, stored.get().getOutcomeStatus()); + assertEquals("RELEASE_BUNDLE_NOT_FOUND", stored.get().getFailureCode()); + assertNull(stored.get().getPublishedReleaseBundleRef()); + verify(publishedReleaseBundleService, times(1)) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + + @Test + void resolveLaunchDescriptorAcceptsEqualLargeReleaseVersionIdsByValue() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-large-version", 9L); + Long resolvedVersionId = boxedLargeVersionId(); + Long bundleVersionId = boxedLargeVersionId(); + assertNotSame(resolvedVersionId, bundleVersionId); + stubTemplate(request, resolvedVersionId, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(1_000L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 1_000L)) + .thenReturn(releaseBundle(bundleVersionId, 11L, "v1")); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) .thenReturn(Optional.empty()); + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(CANONICAL_TENANT_ID.toString(), resolved.canonicalTenantId()); + assertEquals(9L, resolved.gameTemplateId()); + assertEquals(1_000L, resolved.versionId()); + assertEquals(11L, resolved.releaseBundleId()); + assertNotNull(resolved.authoredWorldBinding()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); + } + + @Test + void resolveLaunchDescriptorRejectsReleaseBundleForDifferentVersionDeterministically() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-mismatched-release", 9L); + stubTemplate(request, 1_000L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(1_000L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 1_000L)) + .thenReturn(releaseBundle(1_001L, 11L, "v1")); IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-3", null, 7L, 8L, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "RELEASE_BUNDLE_NOT_FOUND: release bundle is not owned by the resolved source version", + thrown.getMessage()); + } + + @Test + void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-remap-required", 9L, 7L, 8L); + stubTemplate(request, 8L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(8L, VersionLifecycleState.PUBLISHED, 18L, null); + when(templateRemapSetService.findApprovedTemplateRemapSet(PRIVATE_SOURCE_TENANT_KEY, 7L, 8L)) + .thenReturn(Optional.empty()); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId", @@ -243,61 +686,292 @@ void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { @Test void resolveLaunchDescriptorUsesApprovedRemapSetForCrossVersionReplacementLaunch() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(8L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-4")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(8L); - version.setTenantId("tenant-1"); - version.setVersionNumber(9); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(18L); - when(versionRepository.findById(8L)).thenReturn(Optional.of(version)); - when(templateRemapSetService.findApprovedTemplateRemapSet("tenant-1", 7L, 8L)) + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-remap-approved", 9L, 7L, 8L); + stubTemplate(request, 8L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(8L, VersionLifecycleState.PUBLISHED, 18L, null); + when(templateRemapSetService.findApprovedTemplateRemapSet(PRIVATE_SOURCE_TENANT_KEY, 7L, 8L)) .thenReturn( Optional.of( new TemplateRemapSetDto( "remap-1", - "tenant-1", + PRIVATE_SOURCE_TENANT_KEY, 7L, 8L, TemplateRemapSetStatus.APPROVED, - "prep", + "preparation", "approved", LocalDateTime.now(), LocalDateTime.now(), List.of()))); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 8L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 8L, - 9, - "v1", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); - when(launchDescriptorRepository.save(any(LaunchDescriptor.class))) + stubBundle(8L, 11L, "v1"); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) .thenAnswer(invocation -> invocation.getArgument(0)); - var descriptor = service.resolveLaunchDescriptor("tenant-1", 9L, "cp-4", null, 7L, 8L, null); + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals("remap-1", resolved.remapSetId()); + assertEquals("remap-1", resolved.authoredWorldBinding().remapSetId()); + } + + private void stubSuccessfulLaunch( + AuthoredWorldLaunchDescriptorEvidence.Request request, long versionId, long bundleId) { + stubTemplate(request, versionId, null); + stubSource(request, sourceEvidence(request.worldSlug())); + stubVersion(versionId, VersionLifecycleState.PUBLISHED, 17L, null); + stubBundle(versionId, bundleId, "v1"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + } + + private GameTemplateLaunchConfigView stubTemplate( + AuthoredWorldLaunchDescriptorEvidence.Request request, + Long defaultVersionId, + String defaultPatch) { + GameTemplateLaunchConfigView template = Mockito.mock(GameTemplateLaunchConfigView.class); + when(template.getId()).thenReturn(request.gameTemplateId()); + when(template.getTenantId()).thenReturn(PRIVATE_SOURCE_TENANT_KEY); + when(template.getDefaultVersionId()).thenReturn(defaultVersionId); + when(template.getDefaultScriptPatchVersion()).thenReturn(defaultPatch); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); + when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); + when(gameTemplateRepository.findLaunchConfigByTenantIdAndId( + PRIVATE_SOURCE_TENANT_KEY, request.gameTemplateId())) + .thenReturn(Optional.of(template)); + return template; + } + + private void stubSource( + AuthoredWorldLaunchDescriptorEvidence.Request request, AuthoredWorldSourceEvidence source) { + when(authoredWorldSourceRepository.read( + request.authoredWorldSourceOperationId(), + request.canonicalTenantId(), + request.worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(source)); + } + + private void stubVersion( + long versionId, VersionLifecycleState state, long epoch, String scriptPatchVersion) { + Version version = new Version(); + version.setId(versionId); + version.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + version.setVersionNumber(8); + version.setVersionState(state); + version.setVersionStateEpoch(epoch); + version.setScriptPatchVersion(scriptPatchVersion); + version.setUpdatedAt(LocalDateTime.now()); + when(versionRepository.findById(versionId)).thenReturn(Optional.of(version)); + } + + private void stubBundle(long versionId, long bundleId, String schemaVersion) { + when(publishedReleaseBundleService.getPublishedReleaseBundle( + PRIVATE_SOURCE_TENANT_KEY, versionId)) + .thenReturn(releaseBundle(versionId, bundleId, schemaVersion)); + } + + private PublishedReleaseBundleDto releaseBundle( + Long versionId, long bundleId, String schemaVersion) { + return releaseBundle(versionId, bundleId, schemaVersion, PUBLISHED_RELEASE_BUNDLE_REF); + } + + private PublishedReleaseBundleDto releaseBundle( + Long versionId, long bundleId, String schemaVersion, String publishedReleaseBundleRef) { + return new PublishedReleaseBundleDto( + bundleId, + PRIVATE_SOURCE_TENANT_KEY, + versionId, + 8, + schemaVersion, + "workflow-1", + MANIFEST_HASH, + List.of(), + List.of(), + "genrev-1", + false, + null, + LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + publishedReleaseBundleRef, + 1, + List.of()); + } + + @SuppressWarnings("removal") + private Long boxedLargeVersionId() { + return new Long(1_000L); + } + + private LaunchDescriptor descriptorFor( + AuthoredWorldLaunchDescriptorEvidence.Request request, long versionId, long bundleId) { + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-stored-" + request.controlPlaneRequestId(), + versionId, + false, + null, + "{}", + "genrev-1", + 17L, + bundleId, + PUBLISHED_RELEASE_BUNDLE_REF, + false, + null); + AuthoredWorldSourceEvidence source = sourceEvidence(request.worldSlug()); + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); + descriptor.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + descriptor.setGameTemplateId(request.gameTemplateId()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(evidence.versionId()); + descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); + descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); + descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); + descriptor.setReleaseBundleId(evidence.releaseBundleId()); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(evidence.targetNamespace()); + descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(new ObjectMapper().writeValueAsString(request)); + descriptor.setSourceEvidenceJson(new ObjectMapper().writeValueAsString(source)); + return descriptor; + } + + private AuthoredWorldSourceEvidence sourceEvidence(String worldSlug) { + String tenantSlug = "silver-company"; + String displayName = "Silver March 🐉"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 901L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 901L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW")); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, long gameTemplateId) { + return request( + controlPlaneRequestId, + gameTemplateId, + SOURCE_OPERATION_ID, + WORLD_SLUG, + CANONICAL_TENANT_ID); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + long sourceVersionId, + long targetVersionId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + false, + null, + true, + sourceVersionId, + true, + targetVersionId, + false, + null); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + boolean requestedPatchPresent, + String requestedPatch) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + requestedPatchPresent, + requestedPatch, + false, + null, + false, + null, + false, + null); + } - assertEquals("remap-1", descriptor.remapSetId()); + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + UUID operationId, + String worldSlug, + UUID canonicalTenantId) { + String evidenceDigest = + SOURCE_OPERATION_ID.equals(operationId) + && WORLD_SLUG.equals(worldSlug) + && CANONICAL_TENANT_ID.equals(canonicalTenantId) + ? sourceEvidence(WORLD_SLUG).evidenceDigest() + : "sha256:" + "a".repeat(64); + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + operationId, + evidenceDigest, + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 22cfa90253..fabdc0d60f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -2,22 +2,32 @@ import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.commandDefinition; import static net.firedevops.firemud.gamedesign.service.impl.CommandDefinitionFixtures.validCommandDefinition; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Revision; +import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -25,16 +35,237 @@ import tools.jackson.databind.ObjectMapper; class PublishedReleaseBundleServiceImplTest { + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + private static final String LOGO_DIGEST = "sha256:" + "b".repeat(64); + @Mock private PublishedReleaseBundleRepository repository; @Mock private RevisionRepository revisionRepository; + @Mock private VersionRepository versionRepository; private PublishedReleaseBundleServiceImpl service; + @Test + void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults() + throws Exception { + var evidence = selectorEvidence(); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + // ISOLATED source-repository response; this test covers service assembly only. + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenReturn(List.of(validCommandDefinition())); + when(repository.save(any(PublishedReleaseBundle.class))) + .thenAnswer( + invocation -> { + PublishedReleaseBundle saved = invocation.getArgument(0); + saved.setId(11L); + saved.setPublishedReleaseBundleRef("owner-release"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)) + .thenReturn(Optional.of(saved)); + return saved; + }); + var first = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence); + assertEquals("v2", first.attestationSchemaVersion()); + assertThat(first.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + assertThat(first.commandDefinitions()).containsExactly(validCommandDefinition()); + org.mockito.Mockito.verifyNoInteractions(revisionRepository); + org.mockito.Mockito.clearInvocations(versionRepository, revisionRepository, repository); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.empty()); + var retry = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + WorldPublishedStartLocationEvidence.fromStored(evidence.canonicalBytes())); + assertEquals(first.id(), retry.id()); + assertThat(retry.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(first.worldPublishedStartLocationEvidence().canonicalBytes()); + org.mockito.Mockito.verifyNoInteractions(versionRepository, revisionRepository); + org.mockito.Mockito.verify(repository) + .requireSelectedCommandDefinitions(any(), any(), any(), any()); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "changed", + participants, + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThatThrownBy(() -> PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(first)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SCHEMA_VERSION_UNSUPPORTED"); + assertThatThrownBy( + () -> PublishedReleaseBundleContract.requireExactRepairMatch(first, emptyManifest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SCHEMA_VERSION_UNSUPPORTED"); + } + + @Test + void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest() + throws Exception { + var evidence = selectorEvidence(); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "wrong-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants.subList(0, 4), + evidence)) + .isInstanceOf(IllegalArgumentException.class); + var world = participants.getFirst(); + var changed = new java.util.ArrayList<>(participants); + changed.set( + 0, + new PublishParticipantDigestDto( + world.participantKey(), + world.scopeValue(), + null, + world.appliedCommitId(), + "e".repeat(64), + 3, + null, + null, + null)); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + changed, + evidence)) + .isInstanceOf(IllegalArgumentException.class); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + } + + @Test + void selectorV2RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception { + var evidence = selectorEvidence(); + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenThrow(new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); + + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants(7L, evidence), + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + org.mockito.Mockito.verifyNoInteractions(revisionRepository); + } + + @Test + void historicalReleaseNeverGainsSelectorAndCorruptedStoredCarrierFailsReadback() + throws Exception { + PublishedReleaseBundle retained = new PublishedReleaseBundle(); + retained.setAttestationSchemaVersion("v1"); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); + assertNull( + service.getPublishedReleaseBundle("tenant-1", 7L).worldPublishedStartLocationEvidence()); + var evidence = selectorEvidence(); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants(7L, evidence), + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("selector-ineligible"); + retained.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); + assertThatThrownBy(() -> service.getPublishedReleaseBundle("tenant-1", 7L)) + .isInstanceOf(IllegalArgumentException.class); + retained.setAttestationSchemaVersion("v2"); + retained.setWorldPublishedStartLocationEvidenceJson("{}"); + assertThatThrownBy(() -> service.getPublishedReleaseBundle("tenant-1", 7L)) + .isInstanceOf(IllegalArgumentException.class); + } + + private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + return PublishedWorldSelectorFixtures.evidence( + new TargetProof( + sourceIdentity().getCanonicalTenantId(), + sourceIdentity().getCanonicalVersionId(), + 7L, + "tenant-1", + 42L, + "tenant-1", + "NEW_GAME_ROW")); + } + + private VersionDto selectorVersion() { + return new VersionDto( + 7L, + "tenant-1", + 8, + VersionLifecycleState.PUBLISHED, + 2L, + null, + null, + false, + "notes", + LocalDateTime.now(), + LocalDateTime.now()); + } + @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); service = - new PublishedReleaseBundleServiceImpl(repository, revisionRepository, new ObjectMapper()); + new PublishedReleaseBundleServiceImpl( + repository, revisionRepository, versionRepository, new ObjectMapper()); + Version source = new Version(); + source.setId(7L); + source.setTenantId("tenant-1"); + source.setCanonicalTenantId(UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda")); + source.setCanonicalVersionId(UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8")); + when(versionRepository.findByTenantIdAndId("tenant-1", 7L)).thenReturn(Optional.of(source)); } @Test @@ -63,6 +294,7 @@ void createFullVersionBundlePersistsImmutableAttestation() { invocation -> { PublishedReleaseBundle entity = invocation.getArgument(0); entity.setId(11L); + entity.setPublishedReleaseBundleRef("owner-issued-reference-11"); return entity; }); @@ -70,21 +302,79 @@ void createFullVersionBundlePersistsImmutableAttestation() { service.createFullVersionBundle( version, "workflow-1", - new ExportedAssetManifest("abc123", List.of("logo.png", "manifest.json")), + logoManifest(), "genrev-1", List.of( + new PublishParticipantDigestDto( + "GAME_LOGIC", + "7", + null, + "version:7", + "digest-logic", + 1, + "ability-schema-v1", + null, + null), new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-1", 1, null, null))); assertEquals(11L, dto.id()); assertEquals("tenant-1", dto.tenantId()); assertEquals(7L, dto.versionId()); - assertEquals("abc123", dto.manifestHash()); + assertEquals(MANIFEST_HASH, dto.manifestHash()); + assertEquals(1, dto.manifestSchemaVersion()); + assertEquals(List.of(logoProof()), dto.artifactDigests()); assertEquals("genrev-1", dto.generationConfigRevision()); - assertEquals(List.of("logo.png", "manifest.json"), dto.requiredManifestAssetKeys()); - assertEquals(1, dto.participantDigests().size()); + assertEquals(List.of("logo.png"), dto.requiredManifestAssetKeys()); + assertEquals(2, dto.participantDigests().size()); + assertEquals("GAME_LOGIC", dto.participantDigests().getFirst().participantKey()); + assertEquals("version:7", dto.participantDigests().getFirst().appliedCommitId()); + assertEquals("digest-logic", dto.participantDigests().getFirst().contentDigest()); + assertEquals(1, dto.participantDigests().getFirst().digestSchemaVersion()); + assertEquals("ability-schema-v1", dto.participantDigests().getFirst().abilitySchemaDigest()); assertEquals(List.of(validCommandDefinition()), dto.commandDefinitions()); assertEquals("v1", dto.attestationSchemaVersion()); + assertEquals("owner-issued-reference-11", dto.publishedReleaseBundleRef()); + assertEquals(sourceIdentity().getCanonicalTenantId(), dto.canonicalTenantId()); + assertEquals(sourceIdentity().getCanonicalVersionId(), dto.canonicalVersionId()); + org.mockito.Mockito.verify(repository) + .save( + org.mockito.ArgumentMatchers.argThat( + saved -> + sourceIdentity().getCanonicalTenantId().equals(saved.getCanonicalTenantId()) + && sourceIdentity() + .getCanonicalVersionId() + .equals(saved.getCanonicalVersionId()))); + } + + @Test + void retainedBundleWithoutCanonicalIdentityStaysAbsent() { + PublishedReleaseBundle retained = new PublishedReleaseBundle(); + retained.setId(11L); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + retained.setParticipantDigestsJson( + "[{\"participantKey\":\"GAME_LOGIC\",\"scopeValue\":\"7\"," + + "\"baseVersionId\":null,\"appliedCommitId\":\"version:7\"," + + "\"contentDigest\":\"legacy-aggregate\",\"digestSchemaVersion\":1," + + "\"errorCode\":null,\"errorMessage\":null}]"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); + + var dto = service.findPublishedReleaseBundle("tenant-1", 7L).orElseThrow(); + + assertNull(dto.canonicalTenantId()); + assertNull(dto.canonicalVersionId()); + assertNull(dto.publishedReleaseBundleRef()); + assertNull(dto.manifestSchemaVersion()); + assertNull(dto.artifactDigests()); + assertNull(dto.participantDigests().getFirst().abilitySchemaDigest()); + } + + private Version sourceIdentity() { + Version version = new Version(); + version.setCanonicalTenantId(UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda")); + version.setCanonicalVersionId(UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8")); + return version; } @Test @@ -109,11 +399,7 @@ void createFullVersionBundleRejectsDuplicateAttestation() { IllegalStateException.class, () -> service.createFullVersionBundle( - version, - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version, "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -154,11 +440,7 @@ void createFullVersionBundleRejectsDuplicateCommandDefinitionAlias() { IllegalStateException.class, () -> service.createFullVersionBundle( - version, - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version, "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -176,11 +458,7 @@ void createFullVersionBundleRejectsDuplicateCanonicalCommandIds() { IllegalStateException.class, () -> service.createFullVersionBundle( - version(), - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version(), "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -198,11 +476,7 @@ void createFullVersionBundleRejectsCanonicalIdAndAliasCollisions() { IllegalStateException.class, () -> service.createFullVersionBundle( - version(), - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version(), "workflow-1", emptyManifest(), "genrev-1", List.of())); } @Test @@ -219,11 +493,7 @@ void createFullVersionBundleRejectsMalformedCommandEffectDeclaration() { IllegalArgumentException.class, () -> service.createFullVersionBundle( - version, - "workflow-1", - new ExportedAssetManifest("abc123", List.of("manifest.json")), - "genrev-1", - List.of())); + version, "workflow-1", emptyManifest(), "genrev-1", List.of())); } private VersionDto version() { @@ -240,4 +510,22 @@ private VersionDto version() { LocalDateTime.now(), LocalDateTime.now()); } + + private static ExportedAssetManifest emptyManifest() { + return new ExportedAssetManifest(MANIFEST_HASH, 1, List.of(), List.of()); + } + + private static ExportedAssetManifest logoManifest() { + return new ExportedAssetManifest(MANIFEST_HASH, 1, List.of("logo.png"), List.of(logoProof())); + } + + private static PublishedArtifactDigest logoProof() { + return new PublishedArtifactDigest( + "logo.png", + "BINARY", + "artifacts/sha256/" + LOGO_DIGEST.substring("sha256:".length()), + LOGO_DIGEST, + "image/png", + 1); + } } diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index d6bd731255..e1e883e154 100644 --- a/services/world-management-service/build.gradle.kts +++ b/services/world-management-service/build.gradle.kts @@ -14,4 +14,7 @@ firemudJooq { dependencies { implementation(project(":common-security")) + testImplementation(libs.bouncycastle.pkix) + testCompileOnly(libs.spotbugs.annotations) + add("integrationTestCompileOnly", libs.spotbugs.annotations) } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/RegionInstance.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/RegionInstance.java index a546172ffa..c7c293722e 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/RegionInstance.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/RegionInstance.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.worldmanagement.entity; +import java.util.UUID; import lombok.Data; @Data @@ -9,6 +10,7 @@ public class RegionInstance { private Long gameInstanceId; private WorldInstance worldInstance; private Integer shardId = 0; + private UUID operationalRegionId; private String name; private String weather; private Long generationSeed = 0L; diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java index de672ba3bb..09805f65ac 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldEntitySpawnBinding.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.worldmanagement.entity; +import java.util.UUID; import lombok.Data; @Data @@ -10,6 +11,9 @@ public class WorldEntitySpawnBinding { private Room room; private String entityTemplateType; private Long entityTemplateId; + private UUID entityCanonicalTenantId; + private UUID entityCanonicalVersionId; + private UUID entityCanonicalTemplateId; private int spawnCount = 1; private int respawnDelaySeconds; diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RegionInstanceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RegionInstanceRepository.java index f14b22bac8..80fa12e8d3 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RegionInstanceRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RegionInstanceRepository.java @@ -4,7 +4,9 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.worldmanagement.entity.RegionInstance; import net.firedevops.firemud.worldmanagement.jooq.tables.records.RegionInstanceRecord; import org.jooq.DSLContext; @@ -59,16 +61,34 @@ public Optional findById(Long id) { public RegionInstance save(RegionInstance entity) { if (entity.getId() == null) { + if (entity.getOperationalRegionId() != null) { + throw new IllegalArgumentException( + "operational region ID is allocated by World when a region instance is inserted"); + } + UUID operationalRegionId = UUID.randomUUID(); RegionInstanceRecord record = dsl.newRecord(REGION_INSTANCE); populate(record, entity); + record.setOperationalRegionId(operationalRegionId); record.store(); return findById(record.getId()).orElseThrow(); } + RegionInstance current = findById(entity.getId()).orElse(null); + if (current == null) { + throw JooqWorldManagementRepositorySupport.staleWrite("region_instance", entity.getId()); + } + Long worldInstanceId = worldInstanceId(entity); + if (!Objects.equals(entity.getOperationalRegionId(), current.getOperationalRegionId()) + || (current.getOperationalRegionId() != null + && (!Objects.equals(entity.getTenantId(), current.getTenantId()) + || !Objects.equals(entity.getGameInstanceId(), current.getGameInstanceId()) + || !Objects.equals(worldInstanceId, current.getWorldInstance().getId())))) { + throw new IllegalStateException("operational region assignment tuple is immutable"); + } int updated = dsl.update(REGION_INSTANCE) .set(REGION_INSTANCE.TENANT_ID, entity.getTenantId()) .set(REGION_INSTANCE.GAME_INSTANCE_ID, entity.getGameInstanceId()) - .set(REGION_INSTANCE.WORLD_INSTANCE_ID, entity.getWorldInstance().getId()) + .set(REGION_INSTANCE.WORLD_INSTANCE_ID, worldInstanceId) .set(REGION_INSTANCE.SHARD_ID, entity.getShardId()) .set(REGION_INSTANCE.NAME, entity.getName()) .set(REGION_INSTANCE.WEATHER, entity.getWeather()) @@ -89,11 +109,16 @@ public RegionInstance save(RegionInstance entity) { return findById(entity.getId()).orElseThrow(); } + private Long worldInstanceId(RegionInstance entity) { + return entity.getWorldInstance() == null ? null : entity.getWorldInstance().getId(); + } + private void populate(RegionInstanceRecord record, RegionInstance entity) { record.setTenantId(entity.getTenantId()); record.setGameInstanceId(entity.getGameInstanceId()); record.setWorldInstanceId(entity.getWorldInstance().getId()); record.setShardId(entity.getShardId()); + record.setOperationalRegionId(entity.getOperationalRegionId()); record.setName(entity.getName()); record.setWeather(entity.getWeather()); record.setGenerationSeed(entity.getGenerationSeed()); @@ -112,6 +137,7 @@ private RegionInstance toEntity(Record record) { JooqWorldManagementRepositorySupport.partialWorldInstance( record.get(REGION_INSTANCE.WORLD_INSTANCE_ID))); entity.setShardId(record.get(REGION_INSTANCE.SHARD_ID)); + entity.setOperationalRegionId(record.get(REGION_INSTANCE.OPERATIONAL_REGION_ID)); entity.setName(record.get(REGION_INSTANCE.NAME)); entity.setWeather(record.get(REGION_INSTANCE.WEATHER)); entity.setGenerationSeed(record.get(REGION_INSTANCE.GENERATION_SEED)); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java index c62b8cbc3f..fbccb4f069 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldEntitySpawnBindingRepository.java @@ -85,6 +85,15 @@ public WorldEntitySpawnBinding save(WorldEntitySpawnBinding entity) { .set(WORLD_ENTITY_SPAWN_BINDING.ROOM_ID, entity.getRoom().getId()) .set(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_TYPE, entity.getEntityTemplateType()) .set(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_ID, entity.getEntityTemplateId()) + .set( + WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TENANT_ID, + entity.getEntityCanonicalTenantId()) + .set( + WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_VERSION_ID, + entity.getEntityCanonicalVersionId()) + .set( + WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TEMPLATE_ID, + entity.getEntityCanonicalTemplateId()) .set(WORLD_ENTITY_SPAWN_BINDING.SPAWN_COUNT, entity.getSpawnCount()) .set(WORLD_ENTITY_SPAWN_BINDING.RESPAWN_DELAY_SECONDS, entity.getRespawnDelaySeconds()) .set(WORLD_ENTITY_SPAWN_BINDING.VERSION, entity.getVersion() + 1) @@ -124,6 +133,9 @@ private void populate(WorldEntitySpawnBindingRecord record, WorldEntitySpawnBind record.setRoomId(entity.getRoom().getId()); record.setEntityTemplateType(entity.getEntityTemplateType()); record.setEntityTemplateId(entity.getEntityTemplateId()); + record.setEntityCanonicalTenantId(entity.getEntityCanonicalTenantId()); + record.setEntityCanonicalVersionId(entity.getEntityCanonicalVersionId()); + record.setEntityCanonicalTemplateId(entity.getEntityCanonicalTemplateId()); record.setSpawnCount(entity.getSpawnCount()); record.setRespawnDelaySeconds(entity.getRespawnDelaySeconds()); record.setVersion(entity.getVersion()); @@ -139,6 +151,12 @@ private WorldEntitySpawnBinding toEntity(Record record) { record.get(WORLD_ENTITY_SPAWN_BINDING.ROOM_ID))); entity.setEntityTemplateType(record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_TYPE)); entity.setEntityTemplateId(record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_TEMPLATE_ID)); + entity.setEntityCanonicalTenantId( + record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TENANT_ID)); + entity.setEntityCanonicalVersionId( + record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_VERSION_ID)); + entity.setEntityCanonicalTemplateId( + record.get(WORLD_ENTITY_SPAWN_BINDING.ENTITY_CANONICAL_TEMPLATE_ID)); Integer spawnCount = record.get(WORLD_ENTITY_SPAWN_BINDING.SPAWN_COUNT); entity.setSpawnCount(spawnCount == null ? 1 : spawnCount); Integer respawnDelaySeconds = record.get(WORLD_ENTITY_SPAWN_BINDING.RESPAWN_DELAY_SECONDS); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java index 48306bfc76..491f70ea1f 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java @@ -4,8 +4,14 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; +import java.util.UUID; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.worldmanagement.entity.WorldEntitySpawnBinding; import net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository; import net.firedevops.firemud.worldmanagement.repository.RegionRepository; import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; @@ -20,8 +26,8 @@ @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Spring-managed repositories and mapper are stored internally for digesting") -public class WorldDraftDesignDigestServiceImpl implements WorldDraftDesignDigestService { - private static final int DIGEST_SCHEMA_VERSION = 2; +public final class WorldDraftDesignDigestServiceImpl implements WorldDraftDesignDigestService { + private static final int DIGEST_SCHEMA_VERSION = 3; private final RegionRepository regionRepository; private final ZoneRepository zoneRepository; @@ -45,7 +51,9 @@ public WorldDraftDesignDigestServiceImpl( this.roomExitRepository = roomExitRepository; this.generationRuleRepository = generationRuleRepository; this.worldEntitySpawnBindingRepository = worldEntitySpawnBindingRepository; - this.objectMapper = objectMapper; + Objects.requireNonNull(objectMapper, "objectMapper"); + // Schema serialization must not inherit application-wide pretty-printing or map-order options. + this.objectMapper = new ObjectMapper(); } @Override @@ -58,7 +66,7 @@ public WorldDraftDesignDigest getDraftDesignDigest(String tenantId, String versi try { String canonicalJson = objectMapper.writeValueAsString( - Map.of( + tables( "regions", regionRepository .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) @@ -138,7 +146,7 @@ public WorldDraftDesignDigest getDraftDesignDigest(String tenantId, String versi "id", binding.getId(), "roomId", binding.getRoom().getId(), "entityTemplateType", binding.getEntityTemplateType(), - "entityTemplateId", binding.getEntityTemplateId(), + "entityReference", entityReference(binding), "spawnCount", binding.getSpawnCount(), "respawnDelaySeconds", binding.getRespawnDelaySeconds())) .toList())); @@ -157,6 +165,55 @@ private String value(String value) { return value == null ? "" : value; } + // Top-level table order is part of the manifest, while every nested object is field-sorted. + private Map tables(Object... entries) { + Map tables = new LinkedHashMap<>(); + for (int index = 0; index < entries.length; index += 2) { + tables.put((String) entries[index], canonical(entries[index + 1])); + } + return tables; + } + + private Object canonical(Object value) { + if (value instanceof Map fields) { + Map sorted = new TreeMap<>(); + fields.forEach((key, item) -> sorted.put((String) key, canonical(item))); + return sorted; + } + if (value instanceof List rows) { + return rows.stream().map(this::canonical).toList(); + } + return value; + } + + private Map entityReference(WorldEntitySpawnBinding binding) { + UUID tenant = binding.getEntityCanonicalTenantId(); + UUID version = binding.getEntityCanonicalVersionId(); + UUID template = binding.getEntityCanonicalTemplateId(); + Long numeric = binding.getEntityTemplateId(); + if (numeric != null) { + if (numeric <= 0 || tenant != null || version != null || template != null) { + throw new IllegalArgumentException("spawn Entity reference is mixed or nonpositive"); + } + return Map.of("kind", "RETAINED_PRIVATE_KEY", "templateId", numeric.toString()); + } + requireNonNil(tenant); + requireNonNil(version); + requireNonNil(template); + return Map.of( + "kind", "CANONICAL_UUID", + "tenantId", tenant.toString(), + "versionId", version.toString(), + "templateId", template.toString()); + } + + private void requireNonNil(UUID value) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException( + "spawn Entity reference must contain complete non-nil UUIDs"); + } + } + private String sha256(String value) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClient.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClient.java new file mode 100644 index 0000000000..51ce1523b5 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClient.java @@ -0,0 +1,237 @@ +package net.firedevops.firemud.worldmanagement.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 java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +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.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldFinalizationService.HeldOwnerProof; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldFinalizationService.OwnerProofVerifier; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit mTLS client for the exact Game Session canonical initial-admission owner read. */ +public final class GameSessionCanonicalInitialAdmissionOwnerClient + extends AbstractReloadingBlockingGrpcClient< + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub> + implements OwnerProofVerifier { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + private final AtomicLong lifecycleGeneration = new AtomicLong(); + + public GameSessionCanonicalInitialAdmissionOwnerClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + Objects.requireNonNull(channelFactory, "channelFactory"), + GameSessionCanonicalInitialAdmissionOwnerClient.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("Game Session owner-proof client is closed"); + } + if (initialized) { + return; + } + try { + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Game Session owner-proof client has no gRPC stub"); + } + initialized = true; + } catch (IOException | RuntimeException failure) { + closed = true; + lifecycleGeneration.incrementAndGet(); + throw failure; + } + } + + /** Performs an authenticated owner read and holds only its immutable local result. */ + @Override + public HeldOwnerProof verifyAndHold( + HoldIdentity expectedIdentity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome expectedOutcome) { + Objects.requireNonNull(expectedIdentity, "expectedIdentity"); + Objects.requireNonNull(expectedOutcome, "expectedOutcome"); + requireNoAmbientTransaction(); + if (expectedOutcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + throw denied("PENDING is not a terminal owner-proof selection"); + } + if (!workloadNamespace.equals(expectedIdentity.request().targetNamespace())) { + throw denied("Canonical Game Session owner read must use the configured workload namespace"); + } + + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub currentStub = + requireStub(); + long requestGeneration = lifecycleGeneration.get(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCanonicalInitialAdmissionOwnerProof( + GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.toRequest(expectedIdentity)); + + GameSessionCanonicalInitialAdmissionOwnerProof proof; + try { + proof = + GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.fromResponse( + expectedIdentity, expectedOutcome, response); + } catch (IllegalArgumentException invalid) { + throw denied("Game Session returned invalid canonical initial-admission owner proof"); + } + requireGeneration(requestGeneration); + return new LocalHeldOwnerProof(proof, requestGeneration); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub buildStub( + ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + return GameSessionControlPlaneServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + lifecycleGeneration.incrementAndGet(); + super.close(); + } + + private GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub + requireStub() { + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub currentStub = + stub(); + if (closed || !initialized || currentStub == null) { + throw denied("Game Session owner-proof client is not initialized and available"); + } + return currentStub; + } + + private void requireGeneration(long expectedGeneration) { + if (closed || !initialized || lifecycleGeneration.get() != expectedGeneration) { + throw denied("Game Session owner-proof client closed during owner verification"); + } + } + + private synchronized void requireHeld(long expectedGeneration, boolean handleOpen) { + if (!handleOpen || closed || !initialized || lifecycleGeneration.get() != expectedGeneration) { + throw denied("Authenticated Game Session owner proof is no longer held"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw denied("Game Session owner proof must be read outside an ambient World transaction"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Game Session canonical owner 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( + "Game Session canonical owner reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Session canonical owner reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Session owner-proof " + label + " must be a readable file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Session owner-proof " + label + " must be an existing readable file"); + } + } + + private static WorldCanonicalInitialAdmissionHoldFinalizationService.FinalizationDeniedException + denied(String message) { + return new WorldCanonicalInitialAdmissionHoldFinalizationService.FinalizationDeniedException( + message); + } + + private final class LocalHeldOwnerProof implements HeldOwnerProof { + private final GameSessionCanonicalInitialAdmissionOwnerProof proof; + private final long proofGeneration; + private final AtomicBoolean open = new AtomicBoolean(true); + + private LocalHeldOwnerProof( + GameSessionCanonicalInitialAdmissionOwnerProof proof, long proofGeneration) { + this.proof = proof; + this.proofGeneration = proofGeneration; + } + + @Override + public GameSessionCanonicalInitialAdmissionOwnerProof proof() { + requireHeld(); + return proof; + } + + @Override + public void requireHeld() { + GameSessionCanonicalInitialAdmissionOwnerClient.this.requireHeld(proofGeneration, open.get()); + } + + @Override + public void close() { + open.set(false); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.java new file mode 100644 index 0000000000..3e023275c8 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.java @@ -0,0 +1,223 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.Timestamp; +import java.time.DateTimeException; +import java.time.Instant; +import java.util.Objects; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOrigin; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOwnerProofOutcome; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofResponse; + +/** Closed wire codec for reading Game Session's exact canonical initial-admission owner proof. */ +public final class GameSessionCanonicalInitialAdmissionOwnerGrpcCodec { + private static final long MIN_PROTOBUF_TIMESTAMP_SECONDS = -62_135_596_800L; + private static final long MAX_PROTOBUF_TIMESTAMP_SECONDS = 253_402_300_799L; + + private GameSessionCanonicalInitialAdmissionOwnerGrpcCodec() {} + + public static GetCanonicalInitialAdmissionOwnerProofRequest toRequest(HoldIdentity identity) { + Objects.requireNonNull(identity, "identity"); + Request request = identity.request(); + var builder = + GetCanonicalInitialAdmissionOwnerProofRequest.newBuilder() + .setTargetNamespace(request.targetNamespace()) + .setInitialAdmissionRequestId(request.initialAdmissionRequestId()) + .setInitialAdmissionRequestDigest(request.initialAdmissionRequestDigest()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setRealmId(request.realmId().toString()) + .setPlayableStateNamespaceId(request.playableStateNamespaceId().toString()) + .setPlayableStateScope(request.playableStateScope()) + .setCanonicalGameInstanceId(request.canonicalGameInstanceId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setActiveLifecycleEpoch(request.activeLifecycleEpoch()) + .setExpectedCatalogRevision(request.expectedCatalogRevision()) + .setOrigin(toWireOrigin(request.initialAdmissionOrigin())) + .setHoldId(identity.holdId().toString()) + .setHoldFence(identity.holdFence().toString()) + .setHoldBindingDigest(identity.holdBindingDigest()); + if (request.expectedPriorPointerVersion() != null) { + builder.setExpectedPriorPointerVersion(request.expectedPriorPointerVersion()); + } + return builder.build(); + } + + public static GameSessionCanonicalInitialAdmissionOwnerProof fromResponse( + HoldIdentity expectedIdentity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome expectedOutcome, + GetCanonicalInitialAdmissionOwnerProofResponse response) { + Objects.requireNonNull(expectedIdentity, "expectedIdentity"); + Objects.requireNonNull(expectedOutcome, "expectedOutcome"); + Objects.requireNonNull(response, "response"); + if (expectedOutcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + throw invalid("PENDING is not a terminal owner-proof selection"); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw invalid("Game Session owner proof response contains unknown fields"); + } + + requireExactIdentityEcho(expectedIdentity, response); + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome = + fromWireOutcome(response.getOutcome()); + if (outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING + || outcome != expectedOutcome) { + throw invalid("Game Session returned no proof for the exact requested terminal outcome"); + } + + Long committedPointerVersion = + response.hasCommittedPointerVersion() ? response.getCommittedPointerVersion() : null; + Long auditEventId = response.hasAuditEventId() ? response.getAuditEventId() : null; + if (outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + if (committedPointerVersion == null || auditEventId == null) { + throw invalid("COMMITTED owner proof requires pointer and audit fields"); + } + requireExactNextPointerVersion(expectedIdentity, committedPointerVersion); + if (response.getPositiveDurableAbort()) { + throw invalid("COMMITTED owner proof cannot assert durable abort"); + } + } else if (committedPointerVersion != null + || auditEventId != null + || !response.getPositiveDurableAbort()) { + throw invalid("ABORTED owner proof requires positive fencing without commit fields"); + } + + Instant terminalAt = toInstant(response); + try { + GameSessionCanonicalInitialAdmissionOwnerProof proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + expectedIdentity, + outcome, + committedPointerVersion, + auditEventId, + response.getProofDigest(), + response.getPositiveDurableAbort(), + terminalAt); + return GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof)); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Game Session owner proof terminal fields are invalid", malformed); + } + } + + private static void requireExactIdentityEcho( + HoldIdentity expectedIdentity, GetCanonicalInitialAdmissionOwnerProofResponse response) { + Request expected = expectedIdentity.request(); + if (!expected.targetNamespace().equals(response.getTargetNamespace()) + || !expected.initialAdmissionRequestId().equals(response.getInitialAdmissionRequestId()) + || !expected + .initialAdmissionRequestDigest() + .equals(response.getInitialAdmissionRequestDigest()) + || !expected.canonicalTenantId().toString().equals(response.getCanonicalTenantId()) + || !expected.worldSlug().equals(response.getWorldSlug()) + || !expected.realmId().toString().equals(response.getRealmId()) + || !expected + .playableStateNamespaceId() + .toString() + .equals(response.getPlayableStateNamespaceId()) + || !expected.playableStateScope().equals(response.getPlayableStateScope()) + || !expected + .canonicalGameInstanceId() + .toString() + .equals(response.getCanonicalGameInstanceId()) + || !expected.canonicalVersionId().toString().equals(response.getCanonicalVersionId()) + || expected.activeLifecycleEpoch() != response.getActiveLifecycleEpoch() + || expected.expectedCatalogRevision() != response.getExpectedCatalogRevision() + || toWireOrigin(expected.initialAdmissionOrigin()) != response.getOrigin() + || !expectedIdentity.holdId().toString().equals(response.getHoldId()) + || !expectedIdentity.holdFence().toString().equals(response.getHoldFence()) + || !expectedIdentity.holdBindingDigest().equals(response.getHoldBindingDigest())) { + throw invalid("Game Session owner proof response changed the requested hold identity"); + } + if (expected.expectedPriorPointerVersion() == null) { + if (response.hasExpectedPriorPointerVersion()) { + throw invalid("Game Session owner proof added an absent prior-pointer version"); + } + } else if (!response.hasExpectedPriorPointerVersion() + || expected.expectedPriorPointerVersion() != response.getExpectedPriorPointerVersion()) { + throw invalid("Game Session owner proof changed the expected prior-pointer version"); + } + } + + private static void requireExactNextPointerVersion( + HoldIdentity identity, long committedPointerVersion) { + long expectedPointerVersion; + try { + expectedPointerVersion = + switch (identity.request().initialAdmissionOrigin()) { + case NO_PRIOR_POINTER -> 1L; + case EXPECT_CLOSED -> + Math.addExact(identity.request().expectedPriorPointerVersion(), 1L); + }; + } catch (ArithmeticException overflow) { + throw invalid("Expected prior pointer version cannot advance without overflow", overflow); + } + if (committedPointerVersion != expectedPointerVersion) { + throw invalid("COMMITTED owner proof does not name the exact next pointer version"); + } + } + + private static Instant toInstant(GetCanonicalInitialAdmissionOwnerProofResponse response) { + if (!response.hasTerminalAt()) { + throw invalid("Terminal owner proof requires a timestamp"); + } + Timestamp timestamp = response.getTerminalAt(); + long seconds = timestamp.getSeconds(); + int nanos = timestamp.getNanos(); + if (!timestamp.getUnknownFields().asMap().isEmpty()) { + throw invalid("Terminal owner proof timestamp contains unknown fields"); + } + if (seconds < MIN_PROTOBUF_TIMESTAMP_SECONDS || seconds > MAX_PROTOBUF_TIMESTAMP_SECONDS) { + throw invalid("Terminal owner proof timestamp is outside the protobuf range"); + } + if (nanos < 0 || nanos >= 1_000_000_000) { + throw invalid("Terminal owner proof timestamp has invalid nanoseconds"); + } + if (nanos % 1_000 != 0) { + throw invalid("Terminal owner proof timestamp exceeds World microsecond precision"); + } + try { + return Instant.ofEpochSecond(seconds, nanos); + } catch (DateTimeException invalidTimestamp) { + throw invalid("Terminal owner proof timestamp is invalid", invalidTimestamp); + } + } + + private static CanonicalInitialAdmissionOrigin toWireOrigin( + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin origin) { + return switch (origin) { + case NO_PRIOR_POINTER -> + CanonicalInitialAdmissionOrigin.CANONICAL_INITIAL_ADMISSION_ORIGIN_NO_PRIOR_POINTER; + case EXPECT_CLOSED -> + CanonicalInitialAdmissionOrigin.CANONICAL_INITIAL_ADMISSION_ORIGIN_EXPECT_CLOSED; + }; + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof.Outcome fromWireOutcome( + CanonicalInitialAdmissionOwnerProofOutcome outcome) { + return switch (outcome) { + case CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING -> + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING; + case CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED -> + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED; + case CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED -> + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED; + case CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_UNSPECIFIED, UNRECOGNIZED -> + throw invalid("Unsupported Game Session owner-proof outcome"); + }; + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java new file mode 100644 index 0000000000..8956b4f184 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraph.java @@ -0,0 +1,471 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Function; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Immutable World-owned value and codec for the six version-scoped authored content families. */ +public final class WorldAuthoredGraph { + private static final int SNAPSHOT_SCHEMA_VERSION = 1; + private static final ObjectMapper STRICT_JSON_MAPPER = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final List> regions; + private final List> zones; + private final List> rooms; + private final List> roomExits; + private final List> generationRules; + private final List> spawnBindings; + + public WorldAuthoredGraph( + List> regions, + List> zones, + List> rooms, + List> roomExits, + List> generationRules, + List> spawnBindings) { + this.regions = copyRows(regions, false); + this.zones = copyRows(zones, false); + this.rooms = copyRows(rooms, false); + this.roomExits = copyRows(roomExits, false); + this.generationRules = copyRows(generationRules, false); + this.spawnBindings = copyRows(spawnBindings, false); + } + + public List> regions() { + return copyRows(regions, true); + } + + public List> zones() { + return copyRows(zones, true); + } + + public List> rooms() { + return copyRows(rooms, true); + } + + public List> roomExits() { + return copyRows(roomExits, true); + } + + public List> generationRules() { + return copyRows(generationRules, true); + } + + public List> spawnBindings() { + return copyRows(spawnBindings, true); + } + + /** + * Encodes the canonical snapshot representation using the capture component's configured mapper. + */ + public byte[] encode(ObjectMapper objectMapper) { + Objects.requireNonNull(objectMapper, "objectMapper"); + LinkedHashMap root = new LinkedHashMap<>(); + root.put("snapshotSchemaVersion", SNAPSHOT_SCHEMA_VERSION); + root.put("regions", regions); + root.put("zones", zones); + root.put("rooms", rooms); + root.put("roomExits", roomExits); + root.put("generationRules", generationRules); + root.put("worldEntitySpawnBindings", spawnBindings); + try { + return objectMapper.writeValueAsBytes(root); + } catch (Exception exception) { + throw new SnapshotConflictException("World authored graph bytes could not be encoded"); + } + } + + /** + * Decodes only the exact canonical representation emitted by {@link #encode(ObjectMapper)}. This + * validates stored representation, not graph relationships or publication eligibility. + */ + static WorldAuthoredGraph decode(byte[] encoded, ObjectMapper objectMapper) { + if (encoded == null || objectMapper == null) { + throw malformed("World authored graph bytes or mapper are missing"); + } + byte[] original = encoded.clone(); + String json; + try { + json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(original)) + .toString(); + } catch (CharacterCodingException exception) { + throw malformed("World authored graph bytes are not valid UTF-8", exception); + } + + JsonNode root; + try { + root = STRICT_JSON_MAPPER.readTree(json); + } catch (JacksonException exception) { + throw malformed("World authored graph bytes are not strict JSON", exception); + } + requireObject(root, "root"); + requireFields( + root, + "root", + "snapshotSchemaVersion", + "regions", + "zones", + "rooms", + "roomExits", + "generationRules", + "worldEntitySpawnBindings"); + JsonNode schemaVersion = root.get("snapshotSchemaVersion"); + if (!schemaVersion.isInt() || schemaVersion.intValue() != SNAPSHOT_SCHEMA_VERSION) { + throw malformed("World authored graph snapshot schema version is unsupported"); + } + + WorldAuthoredGraph graph = + new WorldAuthoredGraph( + decodeRows(root.get("regions"), "regions", WorldAuthoredGraph::decodeRegion), + decodeRows(root.get("zones"), "zones", WorldAuthoredGraph::decodeZone), + decodeRows(root.get("rooms"), "rooms", WorldAuthoredGraph::decodeRoom), + decodeRows(root.get("roomExits"), "roomExits", WorldAuthoredGraph::decodeRoomExit), + decodeRows( + root.get("generationRules"), + "generationRules", + WorldAuthoredGraph::decodeGenerationRule), + decodeRows( + root.get("worldEntitySpawnBindings"), + "worldEntitySpawnBindings", + WorldAuthoredGraph::decodeSpawnBinding)); + if (!Arrays.equals(graph.encode(objectMapper), original)) { + throw malformed("World authored graph bytes are not in canonical encoding"); + } + return graph; + } + + private static List> decodeRows( + JsonNode rows, String family, Function> decoder) { + if (rows == null || !rows.isArray()) { + throw malformed("World authored graph family " + family + " is not an array"); + } + List> decodedRows = new ArrayList<>(rows.size()); + for (JsonNode row : rows) { + decodedRows.add(decoder.apply(row)); + } + return decodedRows; + } + + private static LinkedHashMap decodeRegion(JsonNode row) { + requireFields( + row, + "regions row", + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "regions row")); + decoded.put("shardId", nonNegativeInt(row, "shardId", "regions row")); + decoded.put("name", nonBlankString(row, "name", "regions row")); + decoded.put("weather", nullableString(row, "weather", "regions row")); + decoded.put("generationSeed", longValue(row, "generationSeed", "regions row")); + decoded.put("generatorType", nullableString(row, "generatorType", "regions row")); + decoded.put("generatorParams", nullableString(row, "generatorParams", "regions row")); + JsonNode spacing = row.get("spacingMultiplier"); + if (spacing == null || !spacing.isFloatingPointNumber()) { + throw malformed("World authored graph regions row spacingMultiplier is not a Double"); + } + double spacingValue = spacing.doubleValue(); + if (!Double.isFinite(spacingValue) || spacingValue <= 0.0d) { + throw malformed("World authored graph regions row spacingMultiplier is unsupported"); + } + decoded.put("spacingMultiplier", spacingValue); + return decoded; + } + + private static LinkedHashMap decodeZone(JsonNode row) { + requireFields(row, "zones row", "id", "regionId", "name"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "zones row")); + decoded.put("regionId", positiveLong(row, "regionId", "zones row")); + decoded.put("name", nonBlankString(row, "name", "zones row")); + return decoded; + } + + private static LinkedHashMap decodeRoom(JsonNode row) { + requireFields( + row, + "rooms row", + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "rooms row")); + decoded.put("zoneId", positiveLong(row, "zoneId", "rooms row")); + decoded.put("name", nonBlankString(row, "name", "rooms row")); + decoded.put("description", nullableString(row, "description", "rooms row")); + decoded.put( + "nameLocalizedVariantsJson", nullableString(row, "nameLocalizedVariantsJson", "rooms row")); + decoded.put( + "descriptionLocalizedVariantsJson", + nullableString(row, "descriptionLocalizedVariantsJson", "rooms row")); + return decoded; + } + + private static LinkedHashMap decodeRoomExit(JsonNode row) { + requireFields(row, "roomExits row", "id", "fromRoomId", "toRoomId", "direction", "cost"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "roomExits row")); + decoded.put("fromRoomId", positiveLong(row, "fromRoomId", "roomExits row")); + decoded.put("toRoomId", positiveLong(row, "toRoomId", "roomExits row")); + decoded.put("direction", nonBlankString(row, "direction", "roomExits row")); + decoded.put("cost", positiveInt(row, "cost", "roomExits row")); + return decoded; + } + + private static LinkedHashMap decodeGenerationRule(JsonNode row) { + requireFields(row, "generationRules row", "id", "name", "scopeType", "scopeId", "value"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "generationRules row")); + decoded.put("name", nonBlankString(row, "name", "generationRules row")); + String scopeType = nullableString(row, "scopeType", "generationRules row"); + String scopeId = nullableString(row, "scopeId", "generationRules row"); + if ((scopeType == null) != (scopeId == null)) { + throw malformed("World authored graph generationRules row has a partial scope"); + } + if (scopeType != null + && (!scopeType.equals("REGION_SUBTREE") && !scopeType.equals("ZONE_SUBTREE"))) { + throw malformed("World authored graph generationRules row scopeType is unsupported"); + } + if (scopeId != null) { + try { + long parsedScopeId = Long.parseLong(scopeId); + if (parsedScopeId <= 0L || !Long.toString(parsedScopeId).equals(scopeId)) { + throw malformed("World authored graph generationRules row scopeId is noncanonical"); + } + } catch (NumberFormatException exception) { + throw malformed( + "World authored graph generationRules row scopeId is unsupported", exception); + } + } + decoded.put("scopeType", scopeType); + decoded.put("scopeId", scopeId); + decoded.put("value", nullableString(row, "value", "generationRules row")); + return decoded; + } + + private static LinkedHashMap decodeSpawnBinding(JsonNode row) { + requireFields( + row, + "worldEntitySpawnBindings row", + "id", + "roomId", + "entityTemplateType", + "entityTemplateId", + "spawnCount", + "respawnDelaySeconds"); + LinkedHashMap decoded = new LinkedHashMap<>(); + decoded.put("id", positiveLong(row, "id", "worldEntitySpawnBindings row")); + decoded.put("roomId", positiveLong(row, "roomId", "worldEntitySpawnBindings row")); + String entityType = nonBlankString(row, "entityTemplateType", "worldEntitySpawnBindings row"); + if (!entityType.equals("ITEM") && !entityType.equals("NPC")) { + throw malformed("World authored graph worldEntitySpawnBindings row type is unsupported"); + } + decoded.put("entityTemplateType", entityType); + decoded.put( + "entityTemplateId", positiveLong(row, "entityTemplateId", "worldEntitySpawnBindings row")); + decoded.put("spawnCount", positiveInt(row, "spawnCount", "worldEntitySpawnBindings row")); + decoded.put( + "respawnDelaySeconds", + nonNegativeInt(row, "respawnDelaySeconds", "worldEntitySpawnBindings row")); + return decoded; + } + + private static void requireFields(JsonNode object, String label, String... fields) { + requireObject(object, label); + Set expected = Set.of(fields); + if (object.size() != expected.size()) { + throw malformed("World authored graph " + label + " has missing or extra fields"); + } + for (Map.Entry entry : object.properties()) { + if (!expected.contains(entry.getKey())) { + throw malformed("World authored graph " + label + " has an unknown field"); + } + } + for (String field : fields) { + if (object.get(field) == null) { + throw malformed("World authored graph " + label + " is missing field " + field); + } + } + } + + private static void requireObject(JsonNode node, String label) { + if (node == null || !node.isObject()) { + throw malformed("World authored graph " + label + " is not an object"); + } + } + + private static long positiveLong(JsonNode object, String field, String label) { + long value = longValue(object, field, label); + if (value <= 0L) { + throw malformed("World authored graph " + label + " " + field + " is not positive"); + } + return value; + } + + private static long longValue(JsonNode object, String field, String label) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw malformed("World authored graph " + label + " " + field + " is not a Long"); + } + return value.longValue(); + } + + private static int positiveInt(JsonNode object, String field, String label) { + int value = intValue(object, field, label); + if (value <= 0) { + throw malformed("World authored graph " + label + " " + field + " is not positive"); + } + return value; + } + + private static int nonNegativeInt(JsonNode object, String field, String label) { + int value = intValue(object, field, label); + if (value < 0) { + throw malformed("World authored graph " + label + " " + field + " is negative"); + } + return value; + } + + private static int intValue(JsonNode object, String field, String label) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw malformed("World authored graph " + label + " " + field + " is not an Integer"); + } + return value.intValue(); + } + + private static String nonBlankString(JsonNode object, String field, String label) { + String value = stringValue(object, field, label, false); + if (value.isBlank()) { + throw malformed("World authored graph " + label + " " + field + " is blank"); + } + return value; + } + + private static String nullableString(JsonNode object, String field, String label) { + return stringValue(object, field, label, true); + } + + private static String stringValue(JsonNode object, String field, String label, boolean nullable) { + JsonNode value = object.get(field); + if (value == null) { + throw malformed("World authored graph " + label + " is missing field " + field); + } + if (value.isNull() && nullable) { + return null; + } + if (!value.isString()) { + throw malformed("World authored graph " + label + " " + field + " is not a string"); + } + return value.stringValue(); + } + + private static SnapshotConflictException malformed(String message) { + return new SnapshotConflictException(message); + } + + private static SnapshotConflictException malformed(String message, Exception cause) { + SnapshotConflictException failure = new SnapshotConflictException(message); + failure.initCause(cause); + return failure; + } + + WorldAuthoredGraph withRegions(List> updatedRegions) { + return new WorldAuthoredGraph( + updatedRegions, zones, rooms, roomExits, generationRules, spawnBindings); + } + + private static List> copyRows( + List> rows, boolean immutable) { + Objects.requireNonNull(rows, "rows"); + List> copiedRows = new ArrayList<>(rows.size()); + for (Map row : rows) { + Objects.requireNonNull(row, "row"); + LinkedHashMap copiedRow = new LinkedHashMap<>(); + for (Map.Entry entry : row.entrySet()) { + copiedRow.put( + Objects.requireNonNull(entry.getKey(), "row key"), + copyValue(entry.getValue(), immutable)); + } + copiedRows.add(immutable ? Collections.unmodifiableMap(copiedRow) : copiedRow); + } + return immutable ? Collections.unmodifiableList(copiedRows) : copiedRows; + } + + private static Object copyValue(Object value, boolean immutable) { + if (value == null + || value instanceof String + || value instanceof Byte + || value instanceof Short + || value instanceof Integer + || value instanceof Long + || value instanceof Float + || value instanceof Double + || value instanceof BigInteger + || value instanceof BigDecimal + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum) { + return value; + } + if (value instanceof byte[] bytes) { + return bytes.clone(); + } + if (value instanceof Map map) { + LinkedHashMap copiedMap = new LinkedHashMap<>(); + for (Map.Entry entry : map.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw new IllegalArgumentException("Authored graph object keys must be strings"); + } + copiedMap.put(key, copyValue(entry.getValue(), immutable)); + } + return immutable ? Collections.unmodifiableMap(copiedMap) : copiedMap; + } + if (value instanceof List list) { + List copiedList = new ArrayList<>(list.size()); + for (Object item : list) { + copiedList.add(copyValue(item, immutable)); + } + return immutable ? Collections.unmodifiableList(copiedList) : copiedList; + } + throw new IllegalArgumentException( + "Unsupported mutable value in authored graph: " + value.getClass().getName()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java new file mode 100644 index 0000000000..3409cc3665 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphReader.java @@ -0,0 +1,325 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; + +/** + * Shared internal six-family graph reader; callers must hold their exact owner transaction lock. + */ +final class WorldAuthoredGraphReader { + private static final Table REGION = table("region"); + private static final Table ZONE = table("zone"); + private static final Table ROOM = table("room"); + private static final Table ROOM_EXIT = table("room_exit"); + private static final Table GENERATION_RULE = table("generation_rule"); + private static final Table SPAWN_BINDING = table("world_entity_spawn_binding"); + + private static final Field ID = field("id", Long.class); + private static final Field TENANT_ID = field("tenant_id", Long.class); + private static final Field VERSION_ID = field("version_id", Long.class); + private static final Field REGION_ID = field("region_id", Long.class); + private static final Field ZONE_ID = field("zone_id", Long.class); + private static final Field FROM_ROOM_ID = field("from_room_id", Long.class); + private static final Field TO_ROOM_ID = field("to_room_id", Long.class); + private static final Field ROOM_ID = field("room_id", Long.class); + private static final Field GENERATION_SEED = field("generation_seed", Long.class); + private static final Field SHARD_ID = field("shard_id", Integer.class); + private static final Field NAME = field("name", String.class); + private static final Field WEATHER = field("weather", String.class); + private static final Field GENERATOR_TYPE = field("generator_type", String.class); + private static final Field GENERATOR_PARAMS = field("generator_params", String.class); + private static final Field SPACING_MULTIPLIER = field("spacing_multiplier", Double.class); + private static final Field DESCRIPTION = field("description", String.class); + private static final Field NAME_LOCALIZED_VARIANTS_JSON = + field("name_localized_variants_json", String.class); + private static final Field DESCRIPTION_LOCALIZED_VARIANTS_JSON = + field("description_localized_variants_json", String.class); + private static final Field DIRECTION = field("direction", String.class); + private static final Field COST = field("cost", Integer.class); + private static final Field SCOPE_TYPE = field("scope_type", String.class); + private static final Field SCOPE_ID = field("scope_id", String.class); + private static final Field RULE_VALUE = field("value", String.class); + private static final Field ENTITY_TEMPLATE_TYPE = + field("entity_template_type", String.class); + private static final Field ENTITY_TEMPLATE_ID = field("entity_template_id", Long.class); + private static final Field SPAWN_COUNT = field("spawn_count", Integer.class); + private static final Field RESPAWN_DELAY_SECONDS = + field("respawn_delay_seconds", Integer.class); + + private final DSLContext dsl; + + WorldAuthoredGraphReader(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + WorldAuthoredGraph readAndValidateGraph(long tenantKey, long versionKey) { + List regionRows = fetch(REGION, tenantKey, versionKey); + List zoneRows = fetch(ZONE, tenantKey, versionKey); + List roomRows = fetch(ROOM, tenantKey, versionKey); + List exitRows = fetch(ROOM_EXIT, tenantKey, versionKey); + List ruleRows = fetch(GENERATION_RULE, tenantKey, versionKey); + List bindingRows = fetch(SPAWN_BINDING, tenantKey, versionKey); + + Map regionIds = new HashMap<>(); + Map zoneIds = new HashMap<>(); + Map roomIds = new HashMap<>(); + List> regions = new ArrayList<>(); + List> zones = new ArrayList<>(); + List> rooms = new ArrayList<>(); + List> exits = new ArrayList<>(); + List> rules = new ArrayList<>(); + List> bindings = new ArrayList<>(); + + for (Record row : regionRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "region.id"); + unique(regionIds, id, "region"); + Integer shard = required(row, SHARD_ID); + Long seed = required(row, GENERATION_SEED); + Double spacing = required(row, SPACING_MULTIPLIER); + String name = required(row, NAME); + if (shard < 0 || !Double.isFinite(spacing) || spacing <= 0.0d || name.isBlank()) { + throw incomplete("region", id, "unsupported required region data"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("shardId", shard); + item.put("name", name); + item.put("weather", row.get(WEATHER, String.class)); + item.put("generationSeed", seed); + item.put("generatorType", row.get(GENERATOR_TYPE, String.class)); + item.put("generatorParams", row.get(GENERATOR_PARAMS, String.class)); + item.put("spacingMultiplier", spacing); + regions.add(item); + } + + for (Record row : zoneRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "zone.id"); + unique(zoneIds, id, "zone"); + long regionId = positive(row, REGION_ID, "zone.region_id"); + if (!regionIds.containsKey(regionId)) { + throw incomplete( + "zone", id, "region parent is missing or belongs to another tenant/Version"); + } + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("zone", id, "zone name is blank"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("regionId", regionId); + item.put("name", name); + zones.add(item); + } + + for (Record row : roomRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "room.id"); + unique(roomIds, id, "room"); + long zoneId = positive(row, ZONE_ID, "room.zone_id"); + if (!zoneIds.containsKey(zoneId)) { + throw incomplete("room", id, "zone parent is missing or belongs to another tenant/Version"); + } + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("room", id, "room name is blank"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("zoneId", zoneId); + item.put("name", name); + item.put("description", row.get(DESCRIPTION, String.class)); + item.put("nameLocalizedVariantsJson", row.get(NAME_LOCALIZED_VARIANTS_JSON, String.class)); + item.put( + "descriptionLocalizedVariantsJson", + row.get(DESCRIPTION_LOCALIZED_VARIANTS_JSON, String.class)); + rooms.add(item); + } + + for (Record row : exitRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "room_exit.id"); + long from = positive(row, FROM_ROOM_ID, "room_exit.from_room_id"); + long to = positive(row, TO_ROOM_ID, "room_exit.to_room_id"); + if (!roomIds.containsKey(from) || !roomIds.containsKey(to)) { + throw incomplete( + "room_exit", id, "exit endpoint is missing or belongs to another tenant/Version"); + } + String direction = required(row, DIRECTION); + Integer cost = required(row, COST); + if (direction.isBlank() || cost <= 0) { + throw incomplete("room_exit", id, "unsupported required room-exit data"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("fromRoomId", from); + item.put("toRoomId", to); + item.put("direction", direction); + item.put("cost", cost); + exits.add(item); + } + + Set exactRuleKeys = new HashSet<>(); + Set unscopedRuleNames = new HashSet<>(); + for (Record row : ruleRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "generation_rule.id"); + String name = required(row, NAME); + if (name.isBlank()) { + throw incomplete("generation_rule", id, "generation rule name is blank"); + } + String scopeType = row.get(SCOPE_TYPE, String.class); + String scopeId = row.get(SCOPE_ID, String.class); + if ((scopeType == null) != (scopeId == null)) { + throw incomplete( + "generation_rule", id, "scope_type and scope_id are only partially present"); + } + String stableScope; + if (scopeType == null) { + if (!unscopedRuleNames.add(name)) { + throw incomplete( + "generation_rule", id, "duplicate ambiguous unscoped generation rule name"); + } + stableScope = ""; + } else { + if (!"REGION_SUBTREE".equals(scopeType) && !"ZONE_SUBTREE".equals(scopeType)) { + throw incomplete("generation_rule", id, "unsupported generation rule scope type"); + } + long parsedScopeId = parseCanonicalPositiveId(scopeId, "generation_rule.scope_id", id); + if (("REGION_SUBTREE".equals(scopeType) && !regionIds.containsKey(parsedScopeId)) + || ("ZONE_SUBTREE".equals(scopeType) && !zoneIds.containsKey(parsedScopeId))) { + throw incomplete( + "generation_rule", id, "generation rule scope parent is missing or mismatched"); + } + stableScope = scopeType + ":" + scopeId; + } + if (!exactRuleKeys.add(stableScope + "\u0000" + name)) { + throw incomplete("generation_rule", id, "duplicate generation rule identity"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("name", name); + item.put("scopeType", scopeType); + item.put("scopeId", scopeId); + item.put("value", row.get(RULE_VALUE, String.class)); + rules.add(item); + } + + Set spawnKeys = new HashSet<>(); + for (Record row : bindingRows) { + requireExactScope(row, tenantKey, versionKey); + long id = positive(row, ID, "world_entity_spawn_binding.id"); + long roomId = positive(row, ROOM_ID, "world_entity_spawn_binding.room_id"); + if (!roomIds.containsKey(roomId)) { + throw incomplete( + "world_entity_spawn_binding", + id, + "spawn room is missing or belongs to another tenant/Version"); + } + String entityType = required(row, ENTITY_TEMPLATE_TYPE); + Long entityId = required(row, ENTITY_TEMPLATE_ID); + Integer spawnCount = required(row, SPAWN_COUNT); + Integer delay = required(row, RESPAWN_DELAY_SECONDS); + if ((!"ITEM".equals(entityType) && !"NPC".equals(entityType)) + || entityId <= 0L + || spawnCount <= 0 + || delay < 0) { + throw incomplete( + "world_entity_spawn_binding", id, "unsupported required spawn binding data"); + } + String spawnKey = roomId + "\u0000" + entityType + "\u0000" + entityId; + if (!spawnKeys.add(spawnKey)) { + throw incomplete("world_entity_spawn_binding", id, "duplicate spawn binding identity"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", id); + item.put("roomId", roomId); + item.put("entityTemplateType", entityType); + item.put("entityTemplateId", entityId); + item.put("spawnCount", spawnCount); + item.put("respawnDelaySeconds", delay); + bindings.add(item); + } + return new WorldAuthoredGraph(regions, zones, rooms, exits, rules, bindings); + } + + private List fetch(Table table, long tenantKey, long versionKey) { + List fetchedRows = + dsl.selectFrom(table) + .where(TENANT_ID.eq(tenantKey).and(VERSION_ID.eq(versionKey))) + .orderBy(ID.asc()) + .fetch(); + List rows = new ArrayList<>(fetchedRows.size()); + rows.addAll(fetchedRows); + return rows; + } + + private void requireExactScope(Record row, long tenantKey, long versionKey) { + if (!Objects.equals(row.get(TENANT_ID, Long.class), tenantKey) + || !Objects.equals(row.get(VERSION_ID, Long.class), versionKey)) { + throw new SnapshotConflictException( + "World graph row returned outside the exact V27 tenant/Version scope"); + } + } + + private long positive(Record row, Field field, String label) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw new SnapshotConflictException(label + " is missing or non-positive"); + } + return value; + } + + private long parseCanonicalPositiveId(String value, String label, long rowId) { + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new NumberFormatException("not canonical positive decimal"); + } + return parsed; + } catch (NumberFormatException exception) { + throw incomplete("generation_rule", rowId, label + " is unsupported"); + } + } + + private T required(Record row, Field field) { + T value = row.get(field, field.getType()); + if (value == null) { + throw new SnapshotConflictException( + "World graph contains null required field " + field.getName()); + } + return value; + } + + private SnapshotConflictException incomplete(String family, long id, String reason) { + return new SnapshotConflictException( + "World graph capture denied incomplete " + family + " row " + id + ": " + reason); + } + + private void unique(Map ids, long id, String family) { + if (ids.putIfAbsent(id, Boolean.TRUE) != null) { + throw incomplete(family, id, "duplicate row identity"); + } + } + + private static Table table(String name) { + return DSL.table(DSL.name(name)); + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java new file mode 100644 index 0000000000..a3065249e6 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Immutable, owner-private capture of the six authored World template families. */ +public record WorldAuthoredGraphSnapshot( + UUID snapshotId, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + String worldSlug, + long gameDesignVersionId, + long localVersionKey, + long localTenantKey, + short ownerBindingSchemaVersion, + UUID intakeOperationId, + UUID intakeRequestId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest, + UUID publicationFence, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + String captureRequestDigest, + String suppliedOwnedAffectedTuplesJson, + String ownerRevisionEvidenceJson, + byte[] graphBytes, + String graphSha256, + OwnerCommitProofStatus ownerCommitProofStatus) { + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + public WorldAuthoredGraphSnapshot { + requireNonNil(snapshotId, "snapshotId"); + requireText(targetNamespace, "targetNamespace"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(versionIdentityOperationId, "versionIdentityOperationId"); + requireText(worldSlug, "worldSlug"); + requirePositive(gameDesignVersionId, "gameDesignVersionId"); + requirePositive(localVersionKey, "localVersionKey"); + requirePositive(localTenantKey, "localTenantKey"); + if (ownerBindingSchemaVersion != 1) { + throw new IllegalArgumentException( + "World snapshot requires exact V27 owner binding schema 1"); + } + requireNonNil(intakeOperationId, "intakeOperationId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requirePrefixedSha256(intakeRequestDigest, "intakeRequestDigest"); + requireNonNil(sourceOperationId, "sourceOperationId"); + requirePrefixedSha256(sourceEvidenceDigest, "sourceEvidenceDigest"); + requirePrefixedSha256(intakeReceiptDigest, "intakeReceiptDigest"); + requireNonNil(publicationFence, "publicationFence"); + requireText(publicationRequestId, "publicationRequestId"); + requireSha256(requestDigest, "requestDigest"); + requirePositive(versionStateEpoch, "versionStateEpoch"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(appliedCommitId, "appliedCommitId"); + requireSha256(contentDigest, "contentDigest"); + if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + throw new IllegalArgumentException( + "World graph snapshot requires retained schema 2 or current schema 3"); + } + requireSha256(captureRequestDigest, "captureRequestDigest"); + requireText(suppliedOwnedAffectedTuplesJson, "suppliedOwnedAffectedTuplesJson"); + requireText(ownerRevisionEvidenceJson, "ownerRevisionEvidenceJson"); + graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + if (graphBytes.length == 0) { + throw new IllegalArgumentException("graphBytes must contain a complete graph representation"); + } + requireSha256(graphSha256, "graphSha256"); + Objects.requireNonNull(ownerCommitProofStatus, "ownerCommitProofStatus"); + if (ownerCommitProofStatus != OwnerCommitProofStatus.CAPTURED_UNVERIFIED) { + throw new IllegalArgumentException( + "This component cannot claim complete owner commit application proof"); + } + } + + @Override + public byte[] graphBytes() { + return graphBytes.clone(); + } + + /** Proof state is deliberately non-eligible until the complete World commit fence is wired. */ + public enum OwnerCommitProofStatus { + CAPTURED_UNVERIFIED + } + + /** One supplied World-owned affected tuple, retained as input evidence without validating it. */ + public record OwnedAffectedTuple( + String owner, + String aggregateType, + String aggregateId, + String scopeType, + String scopeId, + String expectedEpoch) { + public OwnedAffectedTuple { + if (!"WORLD_MANAGEMENT".equals(owner)) { + throw new IllegalArgumentException("World snapshot tuples must name WORLD_MANAGEMENT"); + } + requireText(aggregateType, "aggregateType"); + requireText(aggregateId, "aggregateId"); + Objects.requireNonNull(scopeType, "scopeType"); + Objects.requireNonNull(scopeId, "scopeId"); + if (scopeType.isEmpty() != scopeId.isEmpty()) { + throw new IllegalArgumentException( + "scopeType and scopeId must be both present or both absent"); + } + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || new java.math.BigInteger(expectedEpoch) + .compareTo(java.math.BigInteger.valueOf(Long.MAX_VALUE)) + > 0) { + throw new IllegalArgumentException("expectedEpoch must be canonical non-negative decimal"); + } + } + } + + /** Exact external binding. All private World keys are resolved from immutable owner records. */ + public record CaptureRequest( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID intakeRequestId, + UUID publicationFence, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion, + List suppliedOwnedAffectedTuples) { + public CaptureRequest { + requireText(targetNamespace, "targetNamespace"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(publicationFence, "publicationFence"); + requireText(publicationRequestId, "publicationRequestId"); + requireSha256(requestDigest, "requestDigest"); + requirePositive(versionStateEpoch, "versionStateEpoch"); + requireText(publishWorkflowId, "publishWorkflowId"); + requireText(appliedCommitId, "appliedCommitId"); + requireSha256(contentDigest, "contentDigest"); + if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + throw new IllegalArgumentException( + "World graph snapshot requires retained schema 2 or current schema 3"); + } + Objects.requireNonNull(suppliedOwnedAffectedTuples, "suppliedOwnedAffectedTuples"); + List ordered = new ArrayList<>(suppliedOwnedAffectedTuples); + ordered.sort( + Comparator.comparing(OwnedAffectedTuple::owner) + .thenComparing(OwnedAffectedTuple::aggregateType) + .thenComparing(OwnedAffectedTuple::aggregateId) + .thenComparing(OwnedAffectedTuple::scopeType) + .thenComparing(OwnedAffectedTuple::scopeId) + .thenComparing(OwnedAffectedTuple::expectedEpoch)); + for (int index = 1; index < ordered.size(); index++) { + if (ordered.get(index - 1).equals(ordered.get(index))) { + throw new IllegalArgumentException("duplicate World affected tuple"); + } + } + suppliedOwnedAffectedTuples = List.copyOf(ordered); + } + } + + private static void requireText(String value, String label) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(label + " is required"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0L) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireSha256(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be 64 lowercase hexadecimal digits"); + } + } + + private static void requirePrefixedSha256(String value, String label) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be a canonical prefixed SHA-256 digest"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java new file mode 100644 index 0000000000..c1767c1e1a --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java @@ -0,0 +1,329 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.WorldDraftDesignDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnerCommitProofStatus; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.OwnerProvenance; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** + * Internal-only World graph snapshot capture. Captured rows are representation evidence, not + * publication eligibility or proof that World applied a complete synchronized owner commit. + */ +public class WorldAuthoredGraphSnapshotCapture { + private static final int WORLD_DIGEST_SCHEMA_VERSION = 3; + + private static final Table REVISION_LEDGER = table("world_design_revision_ledger"); + + private static final Field ID = field("id", Long.class); + private static final Field TENANT_ID = field("tenant_id", Long.class); + private static final Field VERSION_ID = field("version_id", Long.class); + + private static final Field COMMIT_ID = field("commit_id", String.class); + private static final Field REVISION_ID = field("revision_id", String.class); + private static final Field OPERATION_TYPE = field("operation_type", String.class); + private static final Field AGGREGATE_TYPE = field("aggregate_type", String.class); + private static final Field REQUESTED_AGGREGATE_ID = + field("requested_aggregate_id", String.class); + private static final Field APPLIED_AGGREGATE_ID = field("applied_aggregate_id", Long.class); + private static final Field RESULT = field("result", String.class); + private static final Field AGGREGATE_EPOCH_AFTER = + field("aggregate_epoch_after", Long.class); + private static final Field SCOPE_EPOCH_AFTER = field("scope_epoch_after", Long.class); + + private final DSLContext dsl; + private final WorldAuthoredGraphReader graphReader; + private final WorldDraftDesignDigestService draftDigestService; + private final WorldAuthoredGraphSnapshotRepository snapshotRepository; + private final ObjectMapper objectMapper; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected World collaborators are internal; construction acquires no resources and this class has no finalizer.") + public WorldAuthoredGraphSnapshotCapture( + DSLContext dsl, + WorldDraftDesignDigestService draftDigestService, + WorldAuthoredGraphSnapshotRepository snapshotRepository, + ObjectMapper objectMapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.graphReader = new WorldAuthoredGraphReader(dsl); + this.draftDigestService = + Objects.requireNonNull(draftDigestService, "draftDigestService must not be null"); + this.snapshotRepository = + Objects.requireNonNull(snapshotRepository, "snapshotRepository must not be null"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null"); + } + + /** + * Captures the current six-family authored graph while holding the exact V25 owner row. + * + *

The caller owns the writable READ COMMITTED transaction. This method is deliberately unwired + * from public publication/activation surfaces and persists every result as {@code + * CAPTURED_UNVERIFIED}; V19 currently lacks the revision-to-complete-scope proof needed to claim + * synchronized owner application. + */ + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredGraphSnapshot capture(CaptureRequest request) { + Objects.requireNonNull(request, "request"); + requireWritableReadCommittedOwnerTransaction(); + OwnerProvenance provenance = snapshotRepository.lockAndResolve(request); + String tuplesJson = encodeTuples(request.suppliedOwnedAffectedTuples()); + String captureRequestDigest = captureRequestDigest(request, provenance, tuplesJson); + + WorldAuthoredGraphSnapshot prior = snapshotRepository.findByFence(request.publicationFence()); + if (prior != null) { + snapshotRepository.requireSameRequest( + prior, request, provenance, captureRequestDigest, tuplesJson); + return prior; + } + if (request.digestSchemaVersion() != WORLD_DIGEST_SCHEMA_VERSION) { + throw new SnapshotConflictException("New World graph capture requires digest schema 3"); + } + if (!"FROZEN".equals(provenance.ownerFreezePhase())) { + throw new SnapshotConflictException( + "World graph capture cannot create a new snapshot after its V25 fence leaves FROZEN"); + } + + String revisionEvidenceJson = captureOwnerRevisionEvidence(request, provenance); + WorldAuthoredGraph graph = + graphReader.readAndValidateGraph(provenance.localTenantKey(), provenance.localVersionKey()); + byte[] graphBytes = graph.encode(objectMapper); + WorldDraftDesignDigest currentDigest = + draftDigestService.getDraftDesignDigest( + Long.toString(provenance.localTenantKey()), + Long.toString(provenance.localVersionKey())); + if (!Long.toString(provenance.localTenantKey()).equals(currentDigest.tenantId()) + || !Long.toString(provenance.localVersionKey()).equals(currentDigest.scopeValue()) + || currentDigest.digestSchemaVersion() != WORLD_DIGEST_SCHEMA_VERSION + || !request.contentDigest().equals(currentDigest.contentDigest())) { + throw new SnapshotConflictException( + "World graph capture differs from the V25 frozen checkpoint under the V27 private Version key"); + } + + WorldAuthoredGraphSnapshot snapshot = + new WorldAuthoredGraphSnapshot( + newNonNilUuid(), + provenance.targetNamespace(), + provenance.canonicalTenantId(), + provenance.canonicalVersionId(), + provenance.versionIdentityOperationId(), + provenance.worldSlug(), + provenance.gameDesignVersionId(), + provenance.localVersionKey(), + provenance.localTenantKey(), + (short) 1, + provenance.intakeOperationId(), + provenance.intakeRequestId(), + provenance.intakeRequestDigest(), + provenance.sourceOperationId(), + provenance.sourceEvidenceDigest(), + provenance.intakeReceiptDigest(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + captureRequestDigest, + tuplesJson, + revisionEvidenceJson, + graphBytes, + sha256(graphBytes), + OwnerCommitProofStatus.CAPTURED_UNVERIFIED); + return snapshotRepository.insertAndReadback(snapshot); + } + + private String captureOwnerRevisionEvidence(CaptureRequest request, OwnerProvenance provenance) { + Result rows = + dsl.select( + ID, + COMMIT_ID, + REVISION_ID, + OPERATION_TYPE, + AGGREGATE_TYPE, + REQUESTED_AGGREGATE_ID, + APPLIED_AGGREGATE_ID, + RESULT, + AGGREGATE_EPOCH_AFTER, + SCOPE_EPOCH_AFTER) + .from(REVISION_LEDGER) + .where( + TENANT_ID + .eq(provenance.localTenantKey()) + .and(VERSION_ID.eq(provenance.localVersionKey())) + .and(COMMIT_ID.eq(request.appliedCommitId()))) + .orderBy(ID.asc()) + .fetch(); + if (rows.isEmpty()) { + throw new WorldAuthoredGraphSnapshotRepository.MissingOwnerHistoryException( + "World graph capture requires retained V19 revision history for the named commit"); + } + List> evidence = new ArrayList<>(); + for (Record row : rows) { + if (!"APPLIED".equals(row.get(RESULT, String.class))) { + throw new SnapshotConflictException( + "World graph capture encountered non-APPLIED V19 revision history"); + } + LinkedHashMap item = new LinkedHashMap<>(); + item.put("id", required(row, ID)); + item.put("commitId", required(row, COMMIT_ID)); + item.put("revisionId", required(row, REVISION_ID)); + item.put("operationType", required(row, OPERATION_TYPE)); + item.put("aggregateType", required(row, AGGREGATE_TYPE)); + item.put("requestedAggregateId", required(row, REQUESTED_AGGREGATE_ID)); + item.put("appliedAggregateId", required(row, APPLIED_AGGREGATE_ID)); + item.put("result", required(row, RESULT)); + item.put("aggregateEpochAfter", required(row, AGGREGATE_EPOCH_AFTER)); + item.put("scopeEpochAfter", row.get(SCOPE_EPOCH_AFTER, Long.class)); + evidence.add(item); + } + return writeJson(evidence); + } + + private String encodeTuples(List tuples) { + List> values = new ArrayList<>(); + for (OwnedAffectedTuple tuple : tuples) { + LinkedHashMap item = new LinkedHashMap<>(); + item.put("owner", tuple.owner()); + item.put("aggregateType", tuple.aggregateType()); + item.put("aggregateId", tuple.aggregateId()); + item.put("scopeType", tuple.scopeType()); + item.put("scopeId", tuple.scopeId()); + item.put("expectedEpoch", tuple.expectedEpoch()); + values.add(item); + } + return writeJson(values); + } + + private String captureRequestDigest( + CaptureRequest request, OwnerProvenance provenance, String tuplesJson) { + LinkedHashMap binding = new LinkedHashMap<>(); + binding.put("targetNamespace", request.targetNamespace()); + binding.put("canonicalTenantId", request.canonicalTenantId().toString()); + binding.put("canonicalVersionId", request.canonicalVersionId().toString()); + binding.put("versionIdentityOperationId", provenance.versionIdentityOperationId().toString()); + binding.put("worldSlug", provenance.worldSlug()); + binding.put("gameDesignVersionId", provenance.gameDesignVersionId()); + binding.put("localVersionKey", provenance.localVersionKey()); + binding.put("localTenantKey", provenance.localTenantKey()); + binding.put("intakeOperationId", provenance.intakeOperationId().toString()); + binding.put("intakeRequestId", request.intakeRequestId().toString()); + binding.put("intakeRequestDigest", provenance.intakeRequestDigest()); + binding.put("sourceOperationId", provenance.sourceOperationId().toString()); + binding.put("sourceEvidenceDigest", provenance.sourceEvidenceDigest()); + binding.put("intakeReceiptDigest", provenance.intakeReceiptDigest()); + binding.put("publicationFence", request.publicationFence().toString()); + binding.put("publicationRequestId", request.publicationRequestId()); + binding.put("requestDigest", request.requestDigest()); + binding.put("versionStateEpoch", request.versionStateEpoch()); + binding.put("publishWorkflowId", request.publishWorkflowId()); + binding.put("appliedCommitId", request.appliedCommitId()); + binding.put("contentDigest", request.contentDigest()); + binding.put("digestSchemaVersion", request.digestSchemaVersion()); + binding.put("suppliedOwnedAffectedTuplesJson", tuplesJson); + return sha256(writeJsonBytes(binding)); + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception exception) { + throw new SnapshotConflictException("World authored graph evidence could not be encoded"); + } + } + + private byte[] writeJsonBytes(Object value) { + try { + return objectMapper.writeValueAsBytes(value); + } catch (Exception exception) { + throw new SnapshotConflictException("World authored graph bytes could not be encoded"); + } + } + + private T required(Record row, Field field) { + T value = row.get(field, field.getType()); + if (value == null) { + throw new SnapshotConflictException( + "World graph contains null required field " + field.getName()); + } + return value; + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("World graph capture requires a caller-owned transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("World graph capture requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World graph capture 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 graph capture requires a writable READ COMMITTED owner transaction"); + } + } + + private static Table table(String name) { + return DSL.table(DSL.name(name)); + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } + + private static UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + static String sha256(byte[] bytes) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + StringBuilder builder = new StringBuilder(digest.length * 2); + for (byte current : digest) { + builder.append(String.format("%02x", current)); + } + return builder.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.java new file mode 100644 index 0000000000..749d06c7f6 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotRepository.java @@ -0,0 +1,599 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnerCommitProofStatus; +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; + +/** Owner-private persistence for immutable World authored graph captures. */ +@Repository +public class WorldAuthoredGraphSnapshotRepository { + private static final String FROZEN = "FROZEN"; + private static final Set RETAINED_FENCE_PHASES = + Set.of(FROZEN, "PUBLISHED", "ABORTED", "RECONCILIATION_REQUIRED"); + private static final String CAPTURED_UNVERIFIED = "CAPTURED_UNVERIFIED"; + + private static final Table SNAPSHOT = DSL.table(DSL.name("world_authored_graph_snapshot")); + private static final Table VERSION_IDENTITY = + DSL.table(DSL.name("world_authored_version_identity")); + private static final Table SOURCE_INTAKE = DSL.table(DSL.name("world_authored_source_intake")); + private static final Table FENCE_OWNER = + DSL.table(DSL.name("world_design_publication_fence_owner")); + private static final Table FENCE_ATTEMPT = + DSL.table(DSL.name("world_design_publication_fence_attempt")); + + private static final Field SNAPSHOT_ID = field("snapshot_id", UUID.class); + private static final Field CAPTURE_REQUEST_DIGEST = + field("capture_request_digest", String.class); + private static final Field PUBLICATION_FENCE = field("publication_fence", UUID.class); + private static final Field TARGET_NAMESPACE = field("target_namespace", String.class); + private static final Field CANONICAL_TENANT_ID = field("canonical_tenant_id", UUID.class); + private static final Field CANONICAL_VERSION_ID = field("canonical_version_id", UUID.class); + private static final Field VERSION_IDENTITY_OPERATION_ID = + field("version_identity_operation_id", UUID.class); + private static final Field WORLD_SLUG = field("world_slug", String.class); + private static final Field GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field LOCAL_VERSION_KEY = field("local_version_key", Long.class); + private static final Field LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field OWNER_BINDING_SCHEMA_VERSION = + field("owner_binding_schema_version", Short.class); + private static final Field INTAKE_OPERATION_ID = field("intake_operation_id", UUID.class); + private static final Field INTAKE_REQUEST_ID = field("intake_request_id", UUID.class); + private static final Field INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field SOURCE_OPERATION_ID = field("source_operation_id", UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field PUBLICATION_REQUEST_ID = + field("publication_request_id", String.class); + private static final Field REQUEST_DIGEST = field("request_digest", String.class); + private static final Field VERSION_STATE_EPOCH = field("version_state_epoch", Long.class); + private static final Field PUBLISH_WORKFLOW_ID = + field("publish_workflow_id", String.class); + private static final Field APPLIED_COMMIT_ID = field("applied_commit_id", String.class); + private static final Field CONTENT_DIGEST = field("content_digest", String.class); + private static final Field DIGEST_SCHEMA_VERSION = + field("digest_schema_version", Integer.class); + private static final Field SUPPLIED_TUPLES_JSON = + field("supplied_owned_affected_tuples_json", String.class); + private static final Field OWNER_REVISION_EVIDENCE_JSON = + field("owner_revision_evidence_json", String.class); + private static final Field OWNER_COMMIT_PROOF_STATUS = + field("owner_commit_proof_status", String.class); + private static final Field GRAPH_BYTES = field("graph_bytes", byte[].class); + private static final Field GRAPH_SHA256 = field("graph_sha256", String.class); + + private static final Field VERSION_OPERATION_ID = field("operation_id", UUID.class); + private static final Field VERSION_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field VERSION_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field VERSION_WORLD_SLUG = field("world_slug", String.class); + private static final Field VERSION_GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field VERSION_LOCAL_VERSION_KEY = + field("local_version_key", Long.class); + private static final Field VERSION_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field VERSION_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field VERSION_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field VERSION_INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field VERSION_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field VERSION_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field VERSION_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + + private static final Field INTAKE_OPERATION = field("operation_id", UUID.class); + private static final Field INTAKE_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field INTAKE_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field INTAKE_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field INTAKE_REQUEST = field("intake_request_id", UUID.class); + private static final Field INTAKE_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field INTAKE_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field INTAKE_RECEIPT = field("receipt_digest", String.class); + private static final Field INTAKE_WORLD_SLUG = field("world_slug", String.class); + + private static final Field OWNER_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field OWNER_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field OWNER_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field OWNER_VERSION_ID = field("version_id", Long.class); + private static final Field OWNER_FREEZE_PHASE = field("owner_freeze_phase", String.class); + private static final Field OWNER_CURRENT_FENCE = + field("current_publication_fence", UUID.class); + + private static final Field ATTEMPT_FENCE = field("publication_fence", UUID.class); + private static final Field ATTEMPT_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field ATTEMPT_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field ATTEMPT_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field ATTEMPT_VERSION_ID = field("version_id", Long.class); + private static final Field ATTEMPT_OWNER_BINDING_SCHEMA_VERSION = + field("owner_binding_schema_version", Short.class); + private static final Field ATTEMPT_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field ATTEMPT_VERSION_IDENTITY_OPERATION_ID = + field("version_identity_operation_id", UUID.class); + private static final Field ATTEMPT_GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field ATTEMPT_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field ATTEMPT_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field ATTEMPT_INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field ATTEMPT_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field ATTEMPT_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field ATTEMPT_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field ATTEMPT_PUBLICATION_REQUEST_ID = + field("publication_request_id", String.class); + private static final Field ATTEMPT_REQUEST_DIGEST = field("request_digest", String.class); + private static final Field ATTEMPT_VERSION_STATE_EPOCH = + field("version_state_epoch", Long.class); + private static final Field ATTEMPT_PUBLISH_WORKFLOW_ID = + field("publish_workflow_id", String.class); + private static final Field ATTEMPT_APPLIED_COMMIT_ID = + field("applied_commit_id", String.class); + private static final Field ATTEMPT_CONTENT_DIGEST = field("content_digest", String.class); + private static final Field ATTEMPT_DIGEST_SCHEMA_VERSION = + field("digest_schema_version", Integer.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected DSLContext is an internal Spring collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldAuthoredGraphSnapshotRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** Resolves all private keys and locks the existing V25 FROZEN owner row. */ + @Transactional(propagation = Propagation.MANDATORY) + public OwnerProvenance lockAndResolve(CaptureRequest request) { + requireWritableReadCommittedOwnerTransaction(); + Record version = + dsl.selectFrom(VERSION_IDENTITY) + .where( + VERSION_TARGET_NAMESPACE + .eq(request.targetNamespace()) + .and(VERSION_CANONICAL_TENANT_ID.eq(request.canonicalTenantId())) + .and(VERSION_CANONICAL_VERSION_ID.eq(request.canonicalVersionId())) + .and(VERSION_INTAKE_REQUEST_ID.eq(request.intakeRequestId()))) + .forShare() + .fetchOne(); + if (version == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires an exact retained V27 authored-Version identity"); + } + Record intake = + dsl.selectFrom(SOURCE_INTAKE) + .where( + INTAKE_TARGET_NAMESPACE + .eq(request.targetNamespace()) + .and(INTAKE_REQUEST.eq(request.intakeRequestId()))) + .forShare() + .fetchOne(); + if (intake == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires the exact retained authored-source intake"); + } + Record owner = + dsl.selectFrom(FENCE_OWNER) + .where( + OWNER_TARGET_NAMESPACE + .eq(request.targetNamespace()) + .and(OWNER_CANONICAL_TENANT_ID.eq(request.canonicalTenantId())) + .and(OWNER_VERSION_ID.eq(required(version, VERSION_LOCAL_VERSION_KEY)))) + .forUpdate() + .fetchOne(); + if (owner == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires an existing V25 shared publication-fence owner row"); + } + String ownerFreezePhase = owner.get(OWNER_FREEZE_PHASE, String.class); + OwnerProvenance provenance = toProvenance(version, ownerFreezePhase); + requireExactIntake(intake, request, provenance); + if (!Objects.equals(owner.get(OWNER_LOCAL_TENANT_KEY), provenance.localTenantKey()) + || !RETAINED_FENCE_PHASES.contains(ownerFreezePhase) + || !request.publicationFence().equals(owner.get(OWNER_CURRENT_FENCE, UUID.class))) { + throw new SnapshotConflictException( + "World graph capture requires the exact retained V25 owner binding"); + } + + Record attempt = + dsl.selectFrom(FENCE_ATTEMPT) + .where( + ATTEMPT_FENCE + .eq(request.publicationFence()) + .and(ATTEMPT_TARGET_NAMESPACE.eq(request.targetNamespace())) + .and(ATTEMPT_CANONICAL_TENANT_ID.eq(request.canonicalTenantId())) + .and(ATTEMPT_LOCAL_TENANT_KEY.eq(provenance.localTenantKey())) + .and(ATTEMPT_VERSION_ID.eq(provenance.localVersionKey()))) + .forShare() + .fetchOne(); + if (attempt == null) { + throw new MissingOwnerHistoryException( + "World graph capture requires the immutable V25 publication attempt"); + } + requireExactAttempt(attempt, request, provenance); + return provenance; + } + + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredGraphSnapshot findByFence(UUID publicationFence) { + Record row = + dsl.selectFrom(SNAPSHOT) + .where(PUBLICATION_FENCE.eq(Objects.requireNonNull(publicationFence))) + .fetchOne(); + return row == null ? null : toSnapshot(row); + } + + @Transactional(propagation = Propagation.MANDATORY) + public WorldAuthoredGraphSnapshot insertAndReadback(WorldAuthoredGraphSnapshot snapshot) { + Objects.requireNonNull(snapshot, "snapshot"); + int inserted = + dsl.insertInto(SNAPSHOT) + .set(SNAPSHOT_ID, snapshot.snapshotId()) + .set(CAPTURE_REQUEST_DIGEST, snapshot.captureRequestDigest()) + .set(PUBLICATION_FENCE, snapshot.publicationFence()) + .set(TARGET_NAMESPACE, snapshot.targetNamespace()) + .set(CANONICAL_TENANT_ID, snapshot.canonicalTenantId()) + .set(CANONICAL_VERSION_ID, snapshot.canonicalVersionId()) + .set(VERSION_IDENTITY_OPERATION_ID, snapshot.versionIdentityOperationId()) + .set(WORLD_SLUG, snapshot.worldSlug()) + .set(GAME_DESIGN_VERSION_ID, snapshot.gameDesignVersionId()) + .set(LOCAL_VERSION_KEY, snapshot.localVersionKey()) + .set(LOCAL_TENANT_KEY, snapshot.localTenantKey()) + .set(OWNER_BINDING_SCHEMA_VERSION, snapshot.ownerBindingSchemaVersion()) + .set(INTAKE_OPERATION_ID, snapshot.intakeOperationId()) + .set(INTAKE_REQUEST_ID, snapshot.intakeRequestId()) + .set(INTAKE_REQUEST_DIGEST, snapshot.intakeRequestDigest()) + .set(SOURCE_OPERATION_ID, snapshot.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, snapshot.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, snapshot.intakeReceiptDigest()) + .set(PUBLICATION_REQUEST_ID, snapshot.publicationRequestId()) + .set(REQUEST_DIGEST, snapshot.requestDigest()) + .set(VERSION_STATE_EPOCH, snapshot.versionStateEpoch()) + .set(PUBLISH_WORKFLOW_ID, snapshot.publishWorkflowId()) + .set(APPLIED_COMMIT_ID, snapshot.appliedCommitId()) + .set(CONTENT_DIGEST, snapshot.contentDigest()) + .set(DIGEST_SCHEMA_VERSION, snapshot.digestSchemaVersion()) + .set(SUPPLIED_TUPLES_JSON, snapshot.suppliedOwnedAffectedTuplesJson()) + .set(OWNER_REVISION_EVIDENCE_JSON, snapshot.ownerRevisionEvidenceJson()) + .set(OWNER_COMMIT_PROOF_STATUS, CAPTURED_UNVERIFIED) + .set(GRAPH_BYTES, snapshot.graphBytes()) + .set(GRAPH_SHA256, snapshot.graphSha256()) + .execute(); + if (inserted != 1) { + throw new SnapshotConflictException("World authored graph snapshot was not inserted"); + } + Record row = dsl.selectFrom(SNAPSHOT).where(SNAPSHOT_ID.eq(snapshot.snapshotId())).fetchOne(); + if (row == null) { + throw new SnapshotConflictException( + "World authored graph snapshot disappeared before immutable readback"); + } + WorldAuthoredGraphSnapshot stored = toSnapshot(row); + requireSameSnapshot(snapshot, stored); + return stored; + } + + public void requireSameRequest( + WorldAuthoredGraphSnapshot snapshot, + CaptureRequest request, + OwnerProvenance provenance, + String captureRequestDigest, + String tuplesJson) { + if (!snapshot.targetNamespace().equals(request.targetNamespace()) + || !snapshot.canonicalTenantId().equals(request.canonicalTenantId()) + || !snapshot.canonicalVersionId().equals(request.canonicalVersionId()) + || !snapshot.versionIdentityOperationId().equals(provenance.versionIdentityOperationId()) + || !snapshot.worldSlug().equals(provenance.worldSlug()) + || snapshot.gameDesignVersionId() != provenance.gameDesignVersionId() + || snapshot.localVersionKey() != provenance.localVersionKey() + || snapshot.localTenantKey() != provenance.localTenantKey() + || snapshot.ownerBindingSchemaVersion() != 1 + || !snapshot.intakeOperationId().equals(provenance.intakeOperationId()) + || !snapshot.intakeRequestId().equals(request.intakeRequestId()) + || !snapshot.intakeRequestDigest().equals(provenance.intakeRequestDigest()) + || !snapshot.sourceOperationId().equals(provenance.sourceOperationId()) + || !snapshot.sourceEvidenceDigest().equals(provenance.sourceEvidenceDigest()) + || !snapshot.intakeReceiptDigest().equals(provenance.intakeReceiptDigest()) + || !snapshot.publicationFence().equals(request.publicationFence()) + || !snapshot.publicationRequestId().equals(request.publicationRequestId()) + || !snapshot.requestDigest().equals(request.requestDigest()) + || snapshot.versionStateEpoch() != request.versionStateEpoch() + || !snapshot.publishWorkflowId().equals(request.publishWorkflowId()) + || !snapshot.appliedCommitId().equals(request.appliedCommitId()) + || !snapshot.contentDigest().equals(request.contentDigest()) + || snapshot.digestSchemaVersion() != request.digestSchemaVersion() + || !snapshot.captureRequestDigest().equals(captureRequestDigest) + || !snapshot.suppliedOwnedAffectedTuplesJson().equals(tuplesJson)) { + throw new SnapshotConflictException( + "World graph capture identity was reused with changed source or request binding"); + } + verifyGraphHash(snapshot); + } + + private OwnerProvenance toProvenance(Record version, String ownerFreezePhase) { + return new OwnerProvenance( + required(version, VERSION_OPERATION_ID), + required(version, VERSION_TARGET_NAMESPACE), + required(version, VERSION_CANONICAL_TENANT_ID), + required(version, VERSION_CANONICAL_VERSION_ID), + required(version, VERSION_WORLD_SLUG), + required(version, VERSION_GAME_DESIGN_VERSION_ID), + required(version, VERSION_LOCAL_VERSION_KEY), + required(version, VERSION_LOCAL_TENANT_KEY), + required(version, VERSION_INTAKE_OPERATION_ID), + required(version, VERSION_INTAKE_REQUEST_ID), + required(version, VERSION_INTAKE_REQUEST_DIGEST), + required(version, VERSION_SOURCE_OPERATION_ID), + required(version, VERSION_SOURCE_EVIDENCE_DIGEST), + required(version, VERSION_INTAKE_RECEIPT_DIGEST), + ownerFreezePhase); + } + + private void requireExactIntake( + Record intake, CaptureRequest request, OwnerProvenance provenance) { + if (!request.targetNamespace().equals(intake.get(INTAKE_TARGET_NAMESPACE, String.class)) + || !request.canonicalTenantId().equals(intake.get(INTAKE_CANONICAL_TENANT_ID, UUID.class)) + || !request.intakeRequestId().equals(intake.get(INTAKE_REQUEST, UUID.class)) + || !provenance.intakeOperationId().equals(intake.get(INTAKE_OPERATION, UUID.class)) + || !provenance.intakeRequestDigest().equals(intake.get("request_digest", String.class)) + || !Objects.equals( + provenance.localTenantKey(), intake.get(INTAKE_LOCAL_TENANT_KEY, Long.class)) + || !provenance + .sourceOperationId() + .equals(intake.get(INTAKE_SOURCE_OPERATION_ID, UUID.class)) + || !provenance + .sourceEvidenceDigest() + .equals(intake.get(INTAKE_SOURCE_EVIDENCE_DIGEST, String.class)) + || !provenance.intakeReceiptDigest().equals(intake.get(INTAKE_RECEIPT, String.class)) + || !provenance.worldSlug().equals(intake.get(INTAKE_WORLD_SLUG, String.class))) { + throw new SnapshotConflictException( + "World Version provenance differs from its exact authored-source intake"); + } + } + + private void requireExactAttempt( + Record attempt, CaptureRequest request, OwnerProvenance provenance) { + if (!request.publicationFence().equals(attempt.get(ATTEMPT_FENCE, UUID.class)) + || !request.targetNamespace().equals(attempt.get(ATTEMPT_TARGET_NAMESPACE, String.class)) + || !request.canonicalTenantId().equals(attempt.get(ATTEMPT_CANONICAL_TENANT_ID, UUID.class)) + || !Objects.equals( + provenance.localTenantKey(), attempt.get(ATTEMPT_LOCAL_TENANT_KEY, Long.class)) + || !Objects.equals( + provenance.localVersionKey(), attempt.get(ATTEMPT_VERSION_ID, Long.class)) + || !Short.valueOf((short) 1) + .equals(attempt.get(ATTEMPT_OWNER_BINDING_SCHEMA_VERSION, Short.class)) + || !request + .canonicalVersionId() + .equals(attempt.get(ATTEMPT_CANONICAL_VERSION_ID, UUID.class)) + || !provenance + .versionIdentityOperationId() + .equals(attempt.get(ATTEMPT_VERSION_IDENTITY_OPERATION_ID, UUID.class)) + || !Objects.equals( + provenance.gameDesignVersionId(), + attempt.get(ATTEMPT_GAME_DESIGN_VERSION_ID, Long.class)) + || !provenance + .intakeOperationId() + .equals(attempt.get(ATTEMPT_INTAKE_OPERATION_ID, UUID.class)) + || !request.intakeRequestId().equals(attempt.get(ATTEMPT_INTAKE_REQUEST_ID, UUID.class)) + || !provenance + .intakeRequestDigest() + .equals(attempt.get(ATTEMPT_INTAKE_REQUEST_DIGEST, String.class)) + || !provenance + .sourceOperationId() + .equals(attempt.get(ATTEMPT_SOURCE_OPERATION_ID, UUID.class)) + || !provenance + .sourceEvidenceDigest() + .equals(attempt.get(ATTEMPT_SOURCE_EVIDENCE_DIGEST, String.class)) + || !provenance + .intakeReceiptDigest() + .equals(attempt.get(ATTEMPT_INTAKE_RECEIPT_DIGEST, String.class)) + || !request + .publicationRequestId() + .equals(attempt.get(ATTEMPT_PUBLICATION_REQUEST_ID, String.class)) + || !request.requestDigest().equals(attempt.get(ATTEMPT_REQUEST_DIGEST, String.class)) + || request.versionStateEpoch() != attempt.get(ATTEMPT_VERSION_STATE_EPOCH, Long.class) + || !request + .publishWorkflowId() + .equals(attempt.get(ATTEMPT_PUBLISH_WORKFLOW_ID, String.class)) + || !request.appliedCommitId().equals(attempt.get(ATTEMPT_APPLIED_COMMIT_ID, String.class)) + || !request.contentDigest().equals(attempt.get(ATTEMPT_CONTENT_DIGEST, String.class)) + || request.digestSchemaVersion() + != attempt.get(ATTEMPT_DIGEST_SCHEMA_VERSION, Integer.class)) { + throw new SnapshotConflictException( + "World graph capture differs from the complete immutable V25 freeze attempt"); + } + } + + private WorldAuthoredGraphSnapshot toSnapshot(Record row) { + WorldAuthoredGraphSnapshot snapshot = + new WorldAuthoredGraphSnapshot( + required(row, SNAPSHOT_ID), + required(row, TARGET_NAMESPACE), + required(row, CANONICAL_TENANT_ID), + required(row, CANONICAL_VERSION_ID), + required(row, VERSION_IDENTITY_OPERATION_ID), + required(row, WORLD_SLUG), + required(row, GAME_DESIGN_VERSION_ID), + required(row, LOCAL_VERSION_KEY), + required(row, LOCAL_TENANT_KEY), + required(row, OWNER_BINDING_SCHEMA_VERSION), + required(row, INTAKE_OPERATION_ID), + required(row, INTAKE_REQUEST_ID), + required(row, INTAKE_REQUEST_DIGEST), + required(row, SOURCE_OPERATION_ID), + required(row, SOURCE_EVIDENCE_DIGEST), + required(row, INTAKE_RECEIPT_DIGEST), + required(row, PUBLICATION_FENCE), + required(row, PUBLICATION_REQUEST_ID), + required(row, REQUEST_DIGEST), + required(row, VERSION_STATE_EPOCH), + required(row, PUBLISH_WORKFLOW_ID), + required(row, APPLIED_COMMIT_ID), + required(row, CONTENT_DIGEST), + required(row, DIGEST_SCHEMA_VERSION), + required(row, CAPTURE_REQUEST_DIGEST), + required(row, SUPPLIED_TUPLES_JSON), + required(row, OWNER_REVISION_EVIDENCE_JSON), + required(row, GRAPH_BYTES), + required(row, GRAPH_SHA256), + parseProofStatus(required(row, OWNER_COMMIT_PROOF_STATUS))); + verifyGraphHash(snapshot); + return snapshot; + } + + private OwnerCommitProofStatus parseProofStatus(String value) { + if (!CAPTURED_UNVERIFIED.equals(value)) { + throw new SnapshotConflictException("Unsupported World owner commit proof status"); + } + return OwnerCommitProofStatus.CAPTURED_UNVERIFIED; + } + + private void requireSameSnapshot( + WorldAuthoredGraphSnapshot expected, WorldAuthoredGraphSnapshot stored) { + if (!expected.snapshotId().equals(stored.snapshotId()) + || !expected.targetNamespace().equals(stored.targetNamespace()) + || !expected.canonicalTenantId().equals(stored.canonicalTenantId()) + || !expected.canonicalVersionId().equals(stored.canonicalVersionId()) + || !expected.versionIdentityOperationId().equals(stored.versionIdentityOperationId()) + || !expected.worldSlug().equals(stored.worldSlug()) + || expected.gameDesignVersionId() != stored.gameDesignVersionId() + || expected.localVersionKey() != stored.localVersionKey() + || expected.localTenantKey() != stored.localTenantKey() + || expected.ownerBindingSchemaVersion() != stored.ownerBindingSchemaVersion() + || !expected.intakeOperationId().equals(stored.intakeOperationId()) + || !expected.intakeRequestId().equals(stored.intakeRequestId()) + || !expected.intakeRequestDigest().equals(stored.intakeRequestDigest()) + || !expected.sourceOperationId().equals(stored.sourceOperationId()) + || !expected.sourceEvidenceDigest().equals(stored.sourceEvidenceDigest()) + || !expected.intakeReceiptDigest().equals(stored.intakeReceiptDigest()) + || !expected.publicationFence().equals(stored.publicationFence()) + || !expected.publicationRequestId().equals(stored.publicationRequestId()) + || !expected.requestDigest().equals(stored.requestDigest()) + || expected.versionStateEpoch() != stored.versionStateEpoch() + || !expected.publishWorkflowId().equals(stored.publishWorkflowId()) + || !expected.appliedCommitId().equals(stored.appliedCommitId()) + || !expected.contentDigest().equals(stored.contentDigest()) + || expected.digestSchemaVersion() != stored.digestSchemaVersion() + || !expected.captureRequestDigest().equals(stored.captureRequestDigest()) + || !expected + .suppliedOwnedAffectedTuplesJson() + .equals(stored.suppliedOwnedAffectedTuplesJson()) + || !expected.ownerRevisionEvidenceJson().equals(stored.ownerRevisionEvidenceJson()) + || !Arrays.equals(expected.graphBytes(), stored.graphBytes()) + || !expected.graphSha256().equals(stored.graphSha256()) + || expected.ownerCommitProofStatus() != stored.ownerCommitProofStatus()) { + throw new SnapshotConflictException( + "World graph snapshot differs from its immutable committed readback"); + } + } + + private void verifyGraphHash(WorldAuthoredGraphSnapshot snapshot) { + if (!WorldAuthoredGraphSnapshotCapture.sha256(snapshot.graphBytes()) + .equals(snapshot.graphSha256())) { + throw new SnapshotConflictException( + "World authored graph snapshot bytes failed their stored SHA-256 readback"); + } + } + + private T required(Record row, Field field) { + T value = row.get(field); + if (value == null) { + throw new SnapshotConflictException( + "World graph snapshot is missing required " + field.getName()); + } + return value; + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("World graph capture requires a caller-owned transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("World graph capture requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World graph capture 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 graph capture requires a writable READ COMMITTED owner transaction"); + } + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } + + public record OwnerProvenance( + UUID versionIdentityOperationId, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + long gameDesignVersionId, + long localVersionKey, + long localTenantKey, + UUID intakeOperationId, + UUID intakeRequestId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest, + String ownerFreezePhase) {} + + public static class SnapshotConflictException extends IllegalStateException { + public SnapshotConflictException(String message) { + super(message); + } + } + + public static class MissingOwnerHistoryException extends IllegalStateException { + public MissingOwnerHistoryException(String message) { + super(message); + } + } +} 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..78bb4d7ff5 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java @@ -0,0 +1,258 @@ +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.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; + +/** + * 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. + */ +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..9ad35f6623 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeRepository.java @@ -0,0 +1,687 @@ +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); + } + + /** Reads the same immutable intake and tenant reservation within a verified owner snapshot. */ + Optional readInOwnerReadOnlyRepeatableRead( + String namespace, UUID intakeRequestId) { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readValidated(namespace, intakeRequestId); + } + + /** + * Reconstructs the same immutable intake inside the writable canonical activation transaction. + */ + Optional readInOwnerActivationTransaction( + String namespace, UUID intakeRequestId) { + requireWritableActivationTransaction(); + 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 requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World authored-source snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"repeatable read".equals(state.get("isolation", String.class)) + || !"on".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World authored-source snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + } + + private void requireWritableActivationTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World authored-source activation read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World authored-source activation read requires a writable READ COMMITTED 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/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityReceipt.java new file mode 100644 index 0000000000..2d70ec8b9d --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityReceipt.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; + +/** + * Immutable World-local identity association for one fresh authored Version. + * + *

This retains source-qualified identity evidence and allocates a private World version key. It + * does not materialize content, authorize a Draft write, or permit lifecycle preparation. + */ +public record WorldAuthoredVersionIdentityReceipt( + int schemaVersion, + UUID operationId, + long localVersionKey, + WorldAuthoredSourceIntakeReceipt sourceIntakeReceipt, + AuthoredWorldVersionStateEvidence versionStateEvidence) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public WorldAuthoredVersionIdentityReceipt { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-Version identity version"); + } + requireNonNil(operationId, "operationId"); + if (localVersionKey <= 0) { + throw new IllegalArgumentException("localVersionKey must be positive"); + } + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(versionStateEvidence, "versionStateEvidence"); + versionStateEvidence.requireValid(); + + var source = sourceIntakeReceipt.source(); + var request = versionStateEvidence.request(); + if (!"NEW_GAME_ROW".equals(source.provenanceKind()) + || !sourceIntakeReceipt.targetNamespace().equals(request.targetNamespace()) + || !sourceIntakeReceipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !sourceIntakeReceipt.worldSlug().equals(request.worldSlug()) + || !sourceIntakeReceipt.sourceOperationId().equals(request.sourceOperationId()) + || !sourceIntakeReceipt + .sourceEvidenceDigest() + .equals(request.expectedSourceEvidenceDigest()) + || !source.equals(versionStateEvidence.sourceEvidence())) { + throw new IllegalArgumentException( + "World Version identity differs from its exact fresh source intake"); + } + UUID readRequestId = request.readRequestId(); + if (readRequestId.equals(versionStateEvidence.canonicalVersionId()) + || readRequestId.equals(operationId) + || readRequestId.equals(sourceIntakeReceipt.operationId()) + || readRequestId.equals(sourceIntakeReceipt.intakeRequestId()) + || readRequestId.equals(sourceIntakeReceipt.sourceOperationId()) + || readRequestId.equals(source.registrationRequestId())) { + throw new IllegalArgumentException( + "Version-state readRequestId must be separate from source and owner identities"); + } + if (versionStateEvidence.versionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT + && versionStateEvidence.versionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && versionStateEvidence.versionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new IllegalArgumentException( + "World Version identity requires DRAFT, PUBLISHED, or ACTIVE owner evidence"); + } + } + + public UUID canonicalVersionId() { + return versionStateEvidence.canonicalVersionId(); + } + + public long gameDesignVersionId() { + return versionStateEvidence.request().versionId(); + } + + public String targetNamespace() { + return sourceIntakeReceipt.targetNamespace(); + } + + public UUID canonicalTenantId() { + return sourceIntakeReceipt.canonicalTenantId(); + } + + public String worldSlug() { + return sourceIntakeReceipt.worldSlug(); + } + + 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/WorldAuthoredVersionIdentityRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java new file mode 100644 index 0000000000..a842eb9005 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java @@ -0,0 +1,453 @@ +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.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Owner-local immutable association between a fresh authored Version UUID and a World key. */ +public class WorldAuthoredVersionIdentityRepository { + private static final Table VERSION_IDENTITY = + DSL.table(DSL.name("world_authored_version_identity")); + private static final JsonMapper CLOSED_JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + 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 WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field GAME_DESIGN_VERSION_ID = + DSL.field(DSL.name("game_design_version_id"), Long.class); + private static final Field LOCAL_VERSION_KEY = + DSL.field(DSL.name("local_version_key"), Long.class); + private static final Field INTAKE_OPERATION_ID = + DSL.field(DSL.name("intake_operation_id"), UUID.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_digest"), String.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("intake_receipt_digest"), String.class); + private static final Field VERSION_STATE_SCHEMA_VERSION = + DSL.field(DSL.name("version_state_schema_version"), Short.class); + private static final Field VERSION_STATE_READ_REQUEST_ID = + DSL.field(DSL.name("version_state_read_request_id"), UUID.class); + private static final Field VERSION_STATE_STATE = + DSL.field(DSL.name("version_state_state"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final Field VERSION_STATE_EVIDENCE_DIGEST = + DSL.field(DSL.name("version_state_evidence_digest"), String.class); + private static final Field VERSION_STATE_EVIDENCE_JSON = + DSL.field(DSL.name("version_state_evidence_json"), String.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The injected DSLContext is an internal collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldAuthoredVersionIdentityRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** Reads the immutable identity by canonical Version UUID after the owner transaction commits. */ + public Optional readByCanonicalVersion( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + requireNoActiveTransaction("World authored-Version identity read"); + return readByCanonicalVersionValidated( + namespace, canonicalTenantId, worldSlug, canonicalVersionId); + } + + /** Reads the exact immutable Version receipt within a verified owner snapshot. */ + Optional readByCanonicalVersionInOwnerReadOnlyRepeatableRead( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readByCanonicalVersionValidated( + namespace, canonicalTenantId, worldSlug, canonicalVersionId); + } + + /** + * Reconstructs the same immutable Version receipt inside canonical activation's owner + * transaction. + */ + Optional readByCanonicalVersionInOwnerActivationTransaction( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + requireWritableActivationTransaction(); + return readByCanonicalVersionValidated( + namespace, canonicalTenantId, worldSlug, canonicalVersionId); + } + + private Optional readByCanonicalVersionValidated( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + validateIdentityKey(namespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + Record row = + findByCanonicalVersion(namespace, canonicalTenantId, worldSlug, canonicalVersionId); + return row == null ? Optional.empty() : Optional.of(toReceipt(row)); + } + + /** Reads an immutable identity by the exact Game Design-owned numeric Version selector. */ + public Optional readByGameDesignVersion( + String namespace, UUID canonicalTenantId, String worldSlug, long gameDesignVersionId) { + requireNoActiveTransaction("World authored-Version identity read"); + validateIdentityKey(namespace, canonicalTenantId, worldSlug); + requirePositive(gameDesignVersionId, "gameDesignVersionId"); + Record row = + findByGameDesignVersion(namespace, canonicalTenantId, worldSlug, gameDesignVersionId); + return row == null ? Optional.empty() : Optional.of(toReceipt(row)); + } + + /** + * Atomically claims the source-qualified Version identity with a World-allocated local key. + * + *

Concurrent requests for the same stable source, canonical UUID, and Game Design selector + * return the first stored receipt even when their transport read IDs or current state epochs + * differ. Changed source or selector evidence conflicts without replacing that receipt. + */ + public WorldAuthoredVersionIdentityReceipt acceptFresh( + WorldAuthoredSourceIntakeReceipt sourceReceipt, + AuthoredWorldVersionStateEvidence versionStateEvidence) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + Objects.requireNonNull(versionStateEvidence, "versionStateEvidence"); + validateFreshEvidence(sourceReceipt, versionStateEvidence); + + AuthoredWorldVersionStateEvidence.Request request = versionStateEvidence.request(); + UUID operationId = newNonNilUuid(); + int inserted = + dsl.insertInto(VERSION_IDENTITY) + .set(OPERATION_ID, operationId) + .set(TARGET_NAMESPACE, sourceReceipt.targetNamespace()) + .set(CANONICAL_TENANT_ID, sourceReceipt.canonicalTenantId()) + .set(WORLD_SLUG, sourceReceipt.worldSlug()) + .set(CANONICAL_VERSION_ID, versionStateEvidence.canonicalVersionId()) + .set(GAME_DESIGN_VERSION_ID, request.versionId()) + .set(INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(LOCAL_TENANT_KEY, sourceReceipt.localTenantKey()) + .set(INTAKE_REQUEST_DIGEST, sourceReceipt.requestDigest()) + .set(SOURCE_OPERATION_ID, sourceReceipt.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, sourceReceipt.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(VERSION_STATE_SCHEMA_VERSION, (short) request.schemaVersion()) + .set(VERSION_STATE_READ_REQUEST_ID, request.readRequestId()) + .set(VERSION_STATE_STATE, lifecycleToken(versionStateEvidence.versionState())) + .set(VERSION_STATE_EPOCH, versionStateEvidence.versionStateEpoch()) + .set(VERSION_STATE_EVIDENCE_DIGEST, versionStateEvidence.evidenceDigest()) + .set(VERSION_STATE_EVIDENCE_JSON, writeJson(versionStateEvidence)) + .onConflictDoNothing() + .execute(); + + Record row = + findByCanonicalVersion( + sourceReceipt.targetNamespace(), + sourceReceipt.canonicalTenantId(), + sourceReceipt.worldSlug(), + versionStateEvidence.canonicalVersionId()); + if (row == null) { + row = + findByGameDesignVersion( + sourceReceipt.targetNamespace(), + sourceReceipt.canonicalTenantId(), + sourceReceipt.worldSlug(), + request.versionId()); + } + if (row == null) { + throw new InvalidIdentityEvidenceException( + "World authored-Version identity is missing after its owner claim"); + } + + WorldAuthoredVersionIdentityReceipt receipt = toReceipt(row); + requireSameIdentity(receipt, sourceReceipt, versionStateEvidence); + if (inserted == 0) { + // A duplicate request resolves only to the original immutable receipt; never rewrite it. + return receipt; + } + return receipt; + } + + private Record findByCanonicalVersion( + String namespace, UUID canonicalTenantId, String worldSlug, UUID canonicalVersionId) { + return dsl.selectFrom(VERSION_IDENTITY) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(CANONICAL_VERSION_ID.eq(canonicalVersionId))) + .fetchOne(); + } + + private Record findByGameDesignVersion( + String namespace, UUID canonicalTenantId, String worldSlug, long gameDesignVersionId) { + return dsl.selectFrom(VERSION_IDENTITY) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(GAME_DESIGN_VERSION_ID.eq(gameDesignVersionId))) + .fetchOne(); + } + + private WorldAuthoredVersionIdentityReceipt toReceipt(Record row) { + try { + UUID operationId = required(row, OPERATION_ID); + String namespace = required(row, TARGET_NAMESPACE); + UUID canonicalTenantId = required(row, CANONICAL_TENANT_ID); + String worldSlug = required(row, WORLD_SLUG); + UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); + Long gameDesignVersionId = required(row, GAME_DESIGN_VERSION_ID); + Long localVersionKey = required(row, LOCAL_VERSION_KEY); + UUID intakeOperationId = required(row, INTAKE_OPERATION_ID); + UUID intakeRequestId = required(row, INTAKE_REQUEST_ID); + Long localTenantKey = required(row, LOCAL_TENANT_KEY); + String intakeRequestDigest = required(row, INTAKE_REQUEST_DIGEST); + UUID sourceOperationId = required(row, SOURCE_OPERATION_ID); + String sourceEvidenceDigest = required(row, SOURCE_EVIDENCE_DIGEST); + String intakeReceiptDigest = required(row, INTAKE_RECEIPT_DIGEST); + Short versionStateSchemaVersion = required(row, VERSION_STATE_SCHEMA_VERSION); + UUID readRequestId = required(row, VERSION_STATE_READ_REQUEST_ID); + String versionStateToken = required(row, VERSION_STATE_STATE); + Long versionStateEpoch = required(row, VERSION_STATE_EPOCH); + String versionStateEvidenceDigest = required(row, VERSION_STATE_EVIDENCE_DIGEST); + AuthoredWorldVersionStateEvidence evidence = + readJson(required(row, VERSION_STATE_EVIDENCE_JSON)); + + if (versionStateSchemaVersion != evidence.request().schemaVersion() + || !readRequestId.equals(evidence.request().readRequestId()) + || !versionStateToken.equals(lifecycleToken(evidence.versionState())) + || !versionStateEpoch.equals(evidence.versionStateEpoch()) + || !versionStateEvidenceDigest.equals(evidence.evidenceDigest()) + || !canonicalVersionId.equals(evidence.canonicalVersionId()) + || gameDesignVersionId != evidence.request().versionId()) { + throw new IllegalArgumentException( + "Persisted World Version identity columns differ from their closed evidence"); + } + + WorldAuthoredSourceIntakeReceipt sourceReceipt = + new WorldAuthoredSourceIntakeReceipt( + 1, + namespace, + intakeRequestId, + intakeOperationId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + intakeRequestDigest, + intakeReceiptDigest, + localTenantKey, + evidence.sourceEvidence()); + return new WorldAuthoredVersionIdentityReceipt( + 1, operationId, localVersionKey, sourceReceipt, evidence); + } catch (RuntimeException exception) { + if (exception instanceof InvalidIdentityEvidenceException) { + throw exception; + } + throw new InvalidIdentityEvidenceException( + "Persisted World authored-Version identity evidence is invalid", exception); + } + } + + private static void validateFreshEvidence( + WorldAuthoredSourceIntakeReceipt sourceReceipt, AuthoredWorldVersionStateEvidence evidence) { + evidence.requireValid(); + AuthoredWorldVersionStateEvidence.Request request = evidence.request(); + if (!"NEW_GAME_ROW".equals(sourceReceipt.source().provenanceKind()) + || !sourceReceipt.targetNamespace().equals(request.targetNamespace()) + || !sourceReceipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !sourceReceipt.worldSlug().equals(request.worldSlug()) + || !sourceReceipt.sourceOperationId().equals(request.sourceOperationId()) + || !sourceReceipt.sourceEvidenceDigest().equals(request.expectedSourceEvidenceDigest()) + || !sourceReceipt.source().equals(evidence.sourceEvidence())) { + throw new RegistrationConflictException( + "World Version identity evidence differs from the exact fresh source intake"); + } + } + + private static void requireSameIdentity( + WorldAuthoredVersionIdentityReceipt receipt, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + AuthoredWorldVersionStateEvidence candidate) { + if (!receipt.sourceIntakeReceipt().equals(sourceReceipt) + || !receipt.canonicalVersionId().equals(candidate.canonicalVersionId()) + || receipt.gameDesignVersionId() != candidate.request().versionId()) { + throw new RegistrationConflictException( + "World Version identity scope, source intake, or Game Design selector conflicts"); + } + } + + private static String writeJson(Object value) { + try { + return CLOSED_JSON.writeValueAsString(value); + } catch (Exception exception) { + throw new InvalidIdentityEvidenceException( + "World Version identity evidence could not be encoded", exception); + } + } + + private static AuthoredWorldVersionStateEvidence readJson(String json) { + try { + AuthoredWorldVersionStateEvidence evidence = + CLOSED_JSON.readValue(json, AuthoredWorldVersionStateEvidence.class); + if (!writeJson(evidence).equals(json)) { + throw new IllegalArgumentException( + "Persisted Version-state evidence JSON is not in its closed form"); + } + evidence.requireValid(); + return evidence; + } catch (Exception exception) { + throw new InvalidIdentityEvidenceException( + "Persisted Version-state JSON is not closed evidence", exception); + } + } + + private static String lifecycleToken(VersionLifecycleState state) { + return switch (state) { + case VERSION_LIFECYCLE_STATE_DRAFT -> "DRAFT"; + case VERSION_LIFECYCLE_STATE_PUBLISHED -> "PUBLISHED"; + case VERSION_LIFECYCLE_STATE_ACTIVE -> "ACTIVE"; + default -> + throw new InvalidIdentityEvidenceException( + "World Version identity requires DRAFT, PUBLISHED, or ACTIVE owner evidence"); + }; + } + + private static T required(Record row, Field field) { + return Objects.requireNonNull(row.get(field), "Persisted " + field.getName() + " is null"); + } + + private static void validateIdentityKey( + String namespace, UUID canonicalTenantId, String worldSlug) { + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " requires an independent committed owner read"); + } + } + + private void requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World authored-Version snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"repeatable read".equals(state.get("isolation", String.class)) + || !"on".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World authored-Version snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + } + + private void requireWritableActivationTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World authored-Version activation read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World authored-Version activation read requires a writable READ COMMITTED owner transaction"); + } + } + + private static void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World authored-Version identity requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World authored-Version identity requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World authored-Version identity requires READ COMMITTED isolation"); + } + } + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidIdentityEvidenceException extends IllegalStateException { + public InvalidIdentityEvidenceException(String message) { + super(message); + } + + public InvalidIdentityEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java new file mode 100644 index 0000000000..45355f38ed --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java @@ -0,0 +1,340 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired World owner step that associates a fresh source-owned Version UUID with a + * private World identity key. + * + *

This identity receipt is non-admitting. It does not materialize content or authorize Draft + * writes, publication, lifecycle preparation, or runtime activation. + */ +public final class WorldAuthoredVersionIdentityService { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AuthoredWorldVersionStateClient versionStateClient; + private final WorldAuthoredVersionIdentityRepository repository; + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public WorldAuthoredVersionIdentityService( + AuthoredWorldVersionStateClient versionStateClient, + WorldAuthoredVersionIdentityRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.versionStateClient = Objects.requireNonNull(versionStateClient, "versionStateClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + this.sourceIntakeRepository = + Objects.requireNonNull(sourceIntakeRepository, "sourceIntakeRepository"); + 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); + } + + /** + * Associates one source-owned Version selector and canonical UUID with a World-local key. + * + *

The stable identity is `(namespace, canonical tenant, world, canonical Version UUID)`. + * `readRequestId` is transport correlation only. Exact retries read the original stored receipt + * before calling Game Design again. + */ + public WorldAuthoredVersionIdentityReceipt associate( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + UUID expectedCanonicalVersionId, + long gameDesignVersionId, + UUID readRequestId) { + requireAuthenticatedGameDesignCaller(); + requireNoAmbientTransaction(); + validateRequest( + targetNamespace, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + expectedCanonicalVersionId, + gameDesignVersionId, + readRequestId); + + WorldAuthoredSourceIntakeReceipt sourceReceipt = + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest); + requireFreshReadRequestId(readRequestId, expectedCanonicalVersionId, sourceReceipt); + + Optional prior = + repository.readByCanonicalVersion( + workloadNamespace, canonicalTenantId, worldSlug, expectedCanonicalVersionId); + if (prior.isPresent()) { + return requireSameIdentity( + prior.orElseThrow(), sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + } + Optional priorByGameDesignVersion = + repository.readByGameDesignVersion( + workloadNamespace, canonicalTenantId, worldSlug, gameDesignVersionId); + if (priorByGameDesignVersion.isPresent()) { + return requireSameIdentity( + priorByGameDesignVersion.orElseThrow(), + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId); + } + + AuthoredWorldVersionStateEvidence.Request currentRequest = + new AuthoredWorldVersionStateEvidence.Request( + SCHEMA_VERSION, + workloadNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + gameDesignVersionId); + AuthoredWorldVersionStateEvidence current; + try { + current = versionStateClient.read(currentRequest); + } catch (RuntimeException exception) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design source-qualified Version identity evidence is unavailable or invalid", + exception); + } + requireCurrentEvidence(current, currentRequest, sourceReceipt, expectedCanonicalVersionId); + + WorldAuthoredVersionIdentityReceipt accepted; + try { + accepted = ownerTransaction.execute(status -> repository.acceptFresh(sourceReceipt, current)); + } catch (RuntimeException ownerFailure) { + Optional committed = + repository.readByCanonicalVersion( + workloadNamespace, canonicalTenantId, worldSlug, expectedCanonicalVersionId); + if (committed.isPresent()) { + requireSameSourceIntake( + sourceReceipt, + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest)); + return requireSameIdentity( + committed.orElseThrow(), + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId); + } + Optional claimedSelector = + repository.readByGameDesignVersion( + workloadNamespace, canonicalTenantId, worldSlug, gameDesignVersionId); + if (claimedSelector.isPresent()) { + requireSameSourceIntake( + sourceReceipt, + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest)); + return requireSameIdentity( + claimedSelector.orElseThrow(), + sourceReceipt, + expectedCanonicalVersionId, + gameDesignVersionId); + } + throw ownerFailure; + } + if (accepted == null) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World owner transaction returned no Version identity receipt"); + } + requireSameIdentity(accepted, sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + + Optional committed = + repository.readByCanonicalVersion( + workloadNamespace, canonicalTenantId, worldSlug, expectedCanonicalVersionId); + if (committed.isEmpty()) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World Version identity is missing after its owner commit"); + } + WorldAuthoredVersionIdentityReceipt readback = committed.orElseThrow(); + requireSameSourceIntake( + sourceReceipt, + readExactSourceIntake( + canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest)); + requireSameIdentity(readback, sourceReceipt, expectedCanonicalVersionId, gameDesignVersionId); + if (!accepted.equals(readback)) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World Version identity changed during independent commit readback"); + } + return readback; + } + + private WorldAuthoredVersionIdentityReceipt requireSameIdentity( + WorldAuthoredVersionIdentityReceipt receipt, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + UUID expectedCanonicalVersionId, + long gameDesignVersionId) { + if (!receipt.targetNamespace().equals(workloadNamespace) + || !receipt.sourceIntakeReceipt().equals(sourceReceipt) + || !receipt.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !receipt.worldSlug().equals(sourceReceipt.worldSlug()) + || !receipt.canonicalVersionId().equals(expectedCanonicalVersionId) + || receipt.gameDesignVersionId() != gameDesignVersionId) { + throw new WorldAuthoredVersionIdentityRepository.RegistrationConflictException( + "World Version identity scope, source intake, or selector conflicts with its first claim"); + } + return receipt; + } + + private void requireCurrentEvidence( + AuthoredWorldVersionStateEvidence evidence, + AuthoredWorldVersionStateEvidence.Request expectedRequest, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + UUID expectedCanonicalVersionId) { + if (evidence == null) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design returned no source-qualified Version identity evidence"); + } + try { + evidence.requireValid(); + } catch (RuntimeException exception) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design source-qualified Version identity evidence is invalid", exception); + } + if (!expectedRequest.equals(evidence.request()) + || !sourceReceipt.source().equals(evidence.sourceEvidence()) + || !expectedCanonicalVersionId.equals(evidence.canonicalVersionId())) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design Version identity evidence differs from the exact source and expected UUID"); + } + VersionLifecycleState state = evidence.versionState(); + if (state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT + && state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Game Design Version identity evidence must be DRAFT, PUBLISHED, or ACTIVE"); + } + } + + private void requireExactFreshSourceIntake( + WorldAuthoredSourceIntakeReceipt sourceReceipt, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + if (!workloadNamespace.equals(sourceReceipt.targetNamespace()) + || !canonicalTenantId.equals(sourceReceipt.canonicalTenantId()) + || !worldSlug.equals(sourceReceipt.worldSlug()) + || !sourceOperationId.equals(sourceReceipt.sourceOperationId()) + || !sourceEvidenceDigest.equals(sourceReceipt.sourceEvidenceDigest()) + || !"NEW_GAME_ROW".equals(sourceReceipt.source().provenanceKind())) { + throw new WorldAuthoredVersionIdentityRepository.RegistrationConflictException( + "World Version identity requires the exact fresh NEW_GAME_ROW source intake"); + } + } + + private WorldAuthoredSourceIntakeReceipt readExactSourceIntake( + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest) { + WorldAuthoredSourceIntakeReceipt sourceReceipt = + sourceIntakeRepository + .readBySource( + workloadNamespace, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest) + .orElseThrow( + () -> + new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World Version identity requires an exact committed fresh source intake")); + requireExactFreshSourceIntake( + sourceReceipt, canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest); + return sourceReceipt; + } + + private static void requireSameSourceIntake( + WorldAuthoredSourceIntakeReceipt expected, WorldAuthoredSourceIntakeReceipt actual) { + if (!expected.equals(actual)) { + throw new WorldAuthoredVersionIdentityRepository.RegistrationConflictException( + "World source intake changed during Version identity readback"); + } + } + + private void requireAuthenticatedGameDesignCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(workloadNamespace)) { + throw new SecurityException( + "World Version identity requires the authenticated same-namespace Game Design workload"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World Version identity cannot enter from an ambient transaction"); + } + } + + private void validateRequest( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + UUID expectedCanonicalVersionId, + long gameDesignVersionId, + UUID readRequestId) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new SecurityException("World Version identity namespace does not match this workload"); + } + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(sourceOperationId, "sourceOperationId"); + requireNonNil(expectedCanonicalVersionId, "expectedCanonicalVersionId"); + requireNonNil(readRequestId, "readRequestId"); + if (!GameTenantCreationDigest.isDigest(sourceEvidenceDigest)) { + throw new IllegalArgumentException("sourceEvidenceDigest must be a canonical SHA-256 digest"); + } + if (gameDesignVersionId <= 0) { + throw new IllegalArgumentException("gameDesignVersionId must be positive"); + } + } + + private static void requireFreshReadRequestId( + UUID readRequestId, + UUID expectedCanonicalVersionId, + WorldAuthoredSourceIntakeReceipt sourceReceipt) { + if (readRequestId.equals(expectedCanonicalVersionId) + || readRequestId.equals(sourceReceipt.operationId()) + || readRequestId.equals(sourceReceipt.intakeRequestId()) + || readRequestId.equals(sourceReceipt.sourceOperationId()) + || readRequestId.equals(sourceReceipt.source().registrationRequestId())) { + throw new IllegalArgumentException( + "Version-state readRequestId must be fresh and separate from source identities"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(NIL_UUID)) { + 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/WorldCanonicalAuthoredGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java new file mode 100644 index 0000000000..854495eb61 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.EntityTemplateReference; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; + +/** Owner-private, validated graph/2 storage view, never synchronized or released content. */ +public final class WorldCanonicalAuthoredGraph { + public enum Family { + REGION, + ZONE, + ROOM, + ROOM_EXIT, + GENERATION_RULE, + WORLD_ENTITY_SPAWN_BINDING + } + + /** Family is part of identity: equal UUIDs in different families are distinct templates. */ + public record Template(Family family, UUID templateId) { + public Template { + Objects.requireNonNull(family, "family"); + Objects.requireNonNull(templateId, "templateId"); + if (templateId.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Canonical template ID must be non-nil"); + } + } + } + + /** Private World selectors never become Entity selectors or public template identifiers. */ + @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Protobuf messages are immutable.") + public record Row( + Template template, + long mappingKey, + long privateRowKey, + Node authored, + WorldDesignMutationRevision content) { + public Row { + Objects.requireNonNull(template, "template"); + Objects.requireNonNull(authored, "authored"); + Objects.requireNonNull(content, "content"); + if (mappingKey <= 0 || privateRowKey <= 0) { + throw new IllegalArgumentException("World private keys must be positive"); + } + } + + public Template scope() { + boolean region = authored.mutation().getScopeType().name().endsWith("REGION_SUBTREE"); + return new Template(region ? Family.REGION : Family.ZONE, authored.scopeId()); + } + + public EntityTemplateReference entityReference() { + return authored.entityReference(); + } + } + + private final UUID tenantId; + private final UUID versionId; + private final long localTenantKey; + private final long localVersionKey; + private final List rows; + + WorldCanonicalAuthoredGraph( + UUID tenantId, UUID versionId, long localTenantKey, long localVersionKey, List rows) { + this.tenantId = tenantId; + this.versionId = versionId; + this.localTenantKey = localTenantKey; + this.localVersionKey = localVersionKey; + this.rows = List.copyOf(rows); + } + + public UUID tenantId() { + return tenantId; + } + + public UUID versionId() { + return versionId; + } + + public long localTenantKey() { + return localTenantKey; + } + + public long localVersionKey() { + return localVersionKey; + } + + public List rows() { + return rows; + } + + public List family(Family family) { + return rows.stream().filter(row -> row.template().family() == family).toList(); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java new file mode 100644 index 0000000000..4c4ac48632 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Row; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Template; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Closed graph/2 decoder. Retained numeric graph/1 remains a separate explicit reader. */ +public final class WorldCanonicalAuthoredGraphReader { + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Set MAPPING_FIELDS = + Set.of( + "id", + "target_namespace", + "canonical_tenant_id", + "canonical_version_id", + "family", + "template_id", + "private_row_key", + "tenant_id", + "version_id", + "version_identity_operation_id", + "request_id", + "commit_id", + "revision_id", + "revision_order"); + + /** Complete original input supplies typed hierarchy/scope/Entity closure, never authority. */ + public WorldCanonicalAuthoredGraph read(WorldDraftTopologyCommitPlan plan, byte[] bytes) { + JsonNode root = JSON.readTree(bytes); + fields(root, Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows")); + text(root, "schemaVersion", "2"); + text(root, "canonicalTenantId", plan.graph().tenantId().toString()); + text(root, "canonicalVersionId", plan.graph().versionId().toString()); + JsonNode rows = root.get("rows"); + if (!rows.isArray() || rows.size() != plan.graph().nodes().size()) { + throw invalid("Missing or extra canonical graph rows"); + } + Map keys = new HashMap<>(); + Set privateKeys = new HashSet<>(); + Set mappingKeys = new HashSet<>(); + List decoded = new ArrayList<>(); + long tenant = 0; + long version = 0; + for (int i = 0; i < rows.size(); i++) { + JsonNode item = rows.get(i); + fields(item, Set.of("mapping", "content")); + JsonNode mapping = item.get("mapping"); + fields(mapping, MAPPING_FIELDS); + var node = plan.graph().nodes().get(i); + String family = WorldDraftTopologyCommitRepository.family(node); + var owner = plan.ownerBinding(); + text(mapping, "target_namespace", owner.targetNamespace()); + text(mapping, "canonical_tenant_id", plan.graph().tenantId().toString()); + text(mapping, "canonical_version_id", plan.graph().versionId().toString()); + text(mapping, "family", family); + text(mapping, "template_id", node.templateId().toString()); + text(mapping, "version_identity_operation_id", owner.versionIdentityOperationId().toString()); + text(mapping, "request_id", plan.binding().requestId().toString()); + text(mapping, "commit_id", plan.binding().commitId().toString()); + text(mapping, "revision_id", node.revisionId().toString()); + text(mapping, "revision_order", node.revisionOrder()); + long localTenant = positive(mapping, "tenant_id"); + long localVersion = positive(mapping, "version_id"); + if (i == 0) { + tenant = localTenant; + version = localVersion; + } + if (tenant != localTenant || version != localVersion) { + throw invalid("Canonical graph crosses private tenant or Version scope"); + } + long key = positive(mapping, "private_row_key"); + long mappingKey = positive(mapping, "id"); + if (keys.put(family + ":" + node.templateId(), key) != null + || !privateKeys.add(family + ":" + key) + || !mappingKeys.add(mappingKey)) { + throw invalid("Canonical graph mapping is not one-to-one within its typed family"); + } + decoded.add( + new Row( + new Template(Family.valueOf(family), node.templateId()), + mappingKey, + key, + node, + node.mutation())); + } + for (int i = 0; i < rows.size(); i++) { + JsonNode actual = rows.get(i).get("content"); + JsonNode expected = + JSON.valueToTree( + WorldDraftTopologyCommitRepository.expectedContent( + plan.graph().nodes().get(i), keys, tenant, version)); + if (!actual.isObject() || !WorldDraftTopologyCommitRepository.sameContent(actual, expected)) { + throw invalid("Canonical graph content differs from exact typed original payload"); + } + if (expected.properties().stream() + .anyMatch( + entry -> + entry.getValue().isIntegralNumber() + && !actual.get(entry.getKey()).isIntegralNumber())) { + throw invalid( + "Canonical graph private selectors and integer content require integer representation"); + } + Row original = decoded.get(i); + var content = original.authored().mutation().toBuilder(); + if (content.hasRegion()) { + content.setRegion( + content.getRegion().toBuilder() + .setSpacingMultiplier(actual.get("spacing_multiplier").doubleValue())); + } else if (content.hasRoomExit()) { + content.setRoomExit( + content.getRoomExit().toBuilder().setCost(actual.get("cost").intValue())); + } else if (content.hasWorldEntitySpawnBinding()) { + content.setWorldEntitySpawnBinding( + content.getWorldEntitySpawnBinding().toBuilder() + .setSpawnCount(actual.get("spawn_count").intValue())); + } + decoded.set( + i, + new Row( + original.template(), + original.mappingKey(), + original.privateRowKey(), + original.authored(), + content.build())); + } + return new WorldCanonicalAuthoredGraph( + plan.graph().tenantId(), plan.graph().versionId(), tenant, version, decoded); + } + + private static void fields(JsonNode node, Set expected) { + if (node == null + || !node.isObject() + || node.size() != expected.size() + || node.properties().stream().anyMatch(entry -> !expected.contains(entry.getKey()))) { + throw invalid("Canonical graph has unsupported or missing fields"); + } + } + + private static void text(JsonNode node, String field, String expected) { + JsonNode actual = node.get(field); + if (actual == null || !actual.isString() || !actual.asText().equals(expected)) { + throw invalid("Canonical graph differs at " + field); + } + } + + private static long positive(JsonNode node, String field) { + JsonNode actual = node.get(field); + if (actual == null + || !actual.isIntegralNumber() + || !actual.canConvertToLong() + || actual.longValue() <= 0) { + throw invalid("Canonical graph requires a positive private integer at " + field); + } + return actual.longValue(); + } + + private static ConflictException invalid(String message) { + return new ConflictException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationRepository.java new file mode 100644 index 0000000000..97912ad7ea --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationRepository.java @@ -0,0 +1,347 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered World-local current read of one initial actor placement. It proves no external + * Entity, Account, or Game Session authority by itself. + */ +public final class WorldCanonicalCurrentPlayerLocationRepository { + private final DSLContext dsl; + private final TransactionTemplate readTransaction; + private final WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository; + private final WorldCanonicalInstanceAssociationRepository associationRepository; + private final WorldCanonicalInitialAdmissionHoldFinalizationRepository holdRepository; + private final WorldCanonicalInitialPlayerLocationRepository placementRepository; + + public WorldCanonicalCurrentPlayerLocationRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository, + WorldCanonicalInstanceAssociationRepository associationRepository, + WorldCanonicalInitialAdmissionHoldFinalizationRepository holdRepository, + WorldCanonicalInitialPlayerLocationRepository placementRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.lifecycleRepository = Objects.requireNonNull(lifecycleRepository, "lifecycleRepository"); + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository"); + this.holdRepository = Objects.requireNonNull(holdRepository, "holdRepository"); + this.placementRepository = Objects.requireNonNull(placementRepository, "placementRepository"); + readTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readTransaction.setReadOnly(true); + } + + /** Requires current owner authority even for an empty read and never opens a nested snapshot. */ + public Optional read( + WorldCanonicalInitialPlayerLocation.Request request, + WorldCanonicalInitialPlayerLocationService.HeldPlacementAuthority authority) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(authority, "authority"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World current-location read must start outside an ambient transaction"); + } + return readTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + authority.requireHeld(); + + WorldCanonicalInstanceLifecycleEvidence current = + lifecycleRepository + .readForCurrentLocationInOwnerTransaction( + request.activeLifecycleEvidence().request()) + .orElseThrow( + () -> denied("exact canonical World lifecycle association is missing")); + if (!"ACTIVE".equals(current.lifecycleStatus()) + || !Arrays.equals( + request.normalizedLifecycleEvidenceBytes(), + WorldCanonicalInitialPlayerLocation.normalizedLifecycleEvidenceBytes( + current.canonicalBytes()))) { + throw denied("current ACTIVE lifecycle or V42 ROOM evidence differs from the request"); + } + + WorldCanonicalInstanceAssociation association = + associationRepository + .readOwnerAssociationInOwnerTransaction(request.canonicalGameInstanceId()) + .orElseThrow(() -> denied("exact canonical World association is missing")); + placementRepository.requireAssociation(request, current, association); + + GameSessionCanonicalInitialAdmissionOwnerProof hold = + holdRepository + .readCommittedInOwnerTransaction(request.initialAdmissionHoldId()) + .orElseThrow(() -> denied("initial-admission hold is missing")); + WorldCanonicalInitialPlayerLocationRepository.requireCommittedCanonicalHold( + request, current, association, hold); + + StoredOperation operation = readOperation(request, association); + var locations = placementRepository.findExistingLocationsForCurrentRead(request); + if (locations.isEmpty()) { + if (operation != null + && operation.result().outcome() + == WorldCanonicalInitialPlayerLocation.Outcome.APPLIED) { + throw denied("retained APPLIED operation has no exact current location row"); + } + authority.requireHeld(); + return Optional.empty(); + } + if (locations.size() != 1) { + throw denied("actor and Entity assignment resolve to different World locations"); + } + Record location = locations.getFirst(); + if (!WorldCanonicalInitialPlayerLocationRepository.sameInitialPlacement( + request, current, location) + || !request + .canonicalGameInstanceId() + .equals(location.get("canonical_game_instance_id", UUID.class)) + || association.worldInstanceId() != location.get("world_instance_id", Long.class) + || !request + .operationId() + .equals(location.get("initial_location_operation_id", UUID.class)) + || !request + .requestDigest() + .equals(location.get("initial_location_request_digest", String.class))) { + throw denied( + "current World location differs from the exact actor or assignment binding"); + } + + if (operation == null + || operation.result().outcome() + != WorldCanonicalInitialPlayerLocation.Outcome.APPLIED) { + throw denied("current World location has no matching APPLIED operation result"); + } + WorldCanonicalInitialPlayerLocation.Result result = operation.result(); + if (result.outcome() != WorldCanonicalInitialPlayerLocation.Outcome.APPLIED + || !result.startLocation().equals(current.startLocation()) + || !Objects.equals(result.runtimeRoomInstanceId(), current.runtimeRoomInstanceId())) { + throw denied("retained placement operation is not the exact current APPLIED result"); + } + + RegionBinding region = readRegionBinding(request, association, current); + byte[] originalEvidence = operation.originalLifecycleEvidenceBytes(); + if (!Arrays.equals( + originalEvidence, location.get("initial_lifecycle_evidence_bytes", byte[].class)) + || !Arrays.equals( + request.normalizedLifecycleEvidenceBytes(), + WorldCanonicalInitialPlayerLocation.normalizedLifecycleEvidenceBytes( + originalEvidence))) { + throw denied("retained World lifecycle evidence differs from its exact placement"); + } + authority.requireHeld(); + return Optional.of( + new CurrentLocation( + request, + current, + association.worldInstanceId(), + current.startLocation(), + current.runtimeRoomInstanceId(), + region.worldRegionInstanceId(), + region.canonicalRegionInstanceId(), + region.operationalRegionId(), + result, + originalEvidence)); + }); + } + + private StoredOperation readOperation( + WorldCanonicalInitialPlayerLocation.Request request, + WorldCanonicalInstanceAssociation association) { + Record operation = + dsl.fetchOne( + "SELECT canonical_tenant_id, playable_state_namespace_id, canonical_game_instance_id, " + + "world_instance_id, request_digest, request_bytes, original_lifecycle_evidence_bytes, " + + "outcome, conflict_code, result_bytes, result_digest " + + "FROM world_canonical_initial_player_location_operation " + + "WHERE operation_id = ?", + request.operationId()); + if (operation == null) return null; + byte[] originalEvidence = operation.get("original_lifecycle_evidence_bytes", byte[].class); + byte[] resultBytes = operation.get("result_bytes", byte[].class); + if (!request.canonicalTenantId().equals(operation.get("canonical_tenant_id", UUID.class)) + || !request + .playableStateNamespaceId() + .equals(operation.get("playable_state_namespace_id", UUID.class)) + || !request + .canonicalGameInstanceId() + .equals(operation.get("canonical_game_instance_id", UUID.class)) + || association.worldInstanceId() != operation.get("world_instance_id", Long.class) + || !request.requestDigest().equals(operation.get("request_digest", String.class)) + || !Arrays.equals( + request.canonicalRequestBytes(), operation.get("request_bytes", byte[].class)) + || !Arrays.equals( + request.normalizedLifecycleEvidenceBytes(), + WorldCanonicalInitialPlayerLocation.normalizedLifecycleEvidenceBytes(originalEvidence)) + || !WorldCanonicalInitialPlayerLocationRepository.prefixedDigest(resultBytes) + .equals(operation.get("result_digest", String.class))) { + throw denied("World operation result differs from its exact request or retained proof"); + } + WorldCanonicalInitialPlayerLocation.Result result; + try { + result = WorldCanonicalInitialPlayerLocation.Result.fromStored(request, resultBytes); + } catch (IllegalArgumentException invalid) { + throw denied("World operation result is not the exact canonical retained result"); + } + if (!result.outcome().name().equals(operation.get("outcome", String.class)) + || !Objects.equals(result.conflictCode(), operation.get("conflict_code", String.class))) { + throw denied("World operation result differs from its retained outcome"); + } + return new StoredOperation(result, originalEvidence); + } + + private RegionBinding readRegionBinding( + WorldCanonicalInitialPlayerLocation.Request request, + WorldCanonicalInstanceAssociation association, + WorldCanonicalInstanceLifecycleEvidence current) { + var fields = association.worldPrepareFields(); + Record region = + dsl.fetchOne( + "SELECT ri.id AS world_region_instance_id, ri.canonical_region_instance_id, " + + "ri.operational_region_id " + + "FROM world_canonical_preparation_start_location s " + + "JOIN world_canonical_instance_topology_identity m " + + "ON m.world_instance_id = s.world_instance_id " + + "AND m.canonical_game_instance_id = s.canonical_game_instance_id " + + "AND m.family = 'ROOM' AND m.template_id = s.room_template_id " + + "JOIN room_instance r ON r.id = m.runtime_row_id " + + "AND r.room_instance_row_id = s.runtime_room_instance_id " + + "JOIN region_instance ri ON ri.id = r.region_instance_id " + + "JOIN world_canonical_instance_topology_identity region_map " + + "ON region_map.world_instance_id = s.world_instance_id " + + "AND region_map.canonical_game_instance_id = s.canonical_game_instance_id " + + "AND region_map.family = 'REGION' " + + "AND region_map.runtime_row_id = ri.id " + + "AND region_map.runtime_identity = ri.canonical_region_instance_id " + + "WHERE s.canonical_game_instance_id = ? AND s.world_instance_id = ? " + + "AND s.canonical_tenant_id = ? AND s.canonical_version_id = ? " + + "AND s.room_template_id = ? AND s.runtime_room_instance_id = ? " + + "AND m.runtime_room_instance_id = s.runtime_room_instance_id " + + "AND m.runtime_row_id = s.runtime_room_instance_id " + + "AND r.tenant_id = ? AND r.game_instance_id = ? " + + "AND ri.tenant_id = ? AND ri.game_instance_id = ? AND ri.world_instance_id = ?", + request.canonicalGameInstanceId(), + association.worldInstanceId(), + request.canonicalTenantId(), + current.request().canonicalVersionId(), + current.startLocation().roomTemplateId(), + current.runtimeRoomInstanceId(), + fields.privateTenantKey(), + fields.privateGameInstanceKey(), + fields.privateTenantKey(), + fields.privateGameInstanceKey(), + association.worldInstanceId()); + if (region == null) { + throw denied("current V42 ROOM has no exact scoped World region row"); + } + UUID operationalRegionId = region.get("operational_region_id", UUID.class); + UUID canonicalRegionId = region.get("canonical_region_instance_id", UUID.class); + if (canonicalRegionId == null + || new UUID(0L, 0L).equals(canonicalRegionId) + || operationalRegionId == null + || new UUID(0L, 0L).equals(operationalRegionId) + || operationalRegionId.equals(canonicalRegionId)) { + throw denied("current World region has invalid V35 identity or V45 operational assignment"); + } + return new RegionBinding( + region.get("world_region_instance_id", Long.class), canonicalRegionId, operationalRegionId); + } + + private void requireReadOnlyRepeatableReadTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World current-location read requires a read-only REPEATABLE READ owner transaction"); + } + Record mode = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + if (mode == null + || !"repeatable read".equals(mode.get("isolation", String.class)) + || !"on".equals(mode.get("read_only", String.class))) { + throw new IllegalStateException("World current-location snapshot has an unexpected mode"); + } + } + + private static IllegalStateException denied(String message) { + return new IllegalStateException("CURRENT_PLAYER_LOCATION_DENIED: " + message); + } + + private record RegionBinding( + long worldRegionInstanceId, UUID canonicalRegionInstanceId, UUID operationalRegionId) {} + + private record StoredOperation( + WorldCanonicalInitialPlayerLocation.Result result, byte[] originalLifecycleEvidenceBytes) { + private StoredOperation { + originalLifecycleEvidenceBytes = + Arrays.copyOf(originalLifecycleEvidenceBytes, originalLifecycleEvidenceBytes.length); + } + + @Override + public byte[] originalLifecycleEvidenceBytes() { + return Arrays.copyOf(originalLifecycleEvidenceBytes, originalLifecycleEvidenceBytes.length); + } + } + + public record CurrentLocation( + WorldCanonicalInitialPlayerLocation.Request binding, + WorldCanonicalInstanceLifecycleEvidence currentLifecycleEvidence, + long worldInstanceId, + RoomTemplateRef startLocation, + long runtimeRoomInstanceId, + long worldRegionInstanceId, + UUID canonicalRegionInstanceId, + UUID operationalRegionId, + WorldCanonicalInitialPlayerLocation.Result placementResult, + byte[] originalLifecycleEvidenceBytes) { + public CurrentLocation { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(currentLifecycleEvidence, "currentLifecycleEvidence"); + Objects.requireNonNull(startLocation, "startLocation"); + Objects.requireNonNull(canonicalRegionInstanceId, "canonicalRegionInstanceId"); + Objects.requireNonNull(operationalRegionId, "operationalRegionId"); + Objects.requireNonNull(placementResult, "placementResult"); + originalLifecycleEvidenceBytes = + Arrays.copyOf( + Objects.requireNonNull( + originalLifecycleEvidenceBytes, "originalLifecycleEvidenceBytes"), + originalLifecycleEvidenceBytes.length); + if (worldInstanceId <= 0 + || runtimeRoomInstanceId <= 0 + || worldRegionInstanceId <= 0 + || new UUID(0L, 0L).equals(canonicalRegionInstanceId) + || new UUID(0L, 0L).equals(operationalRegionId) + || canonicalRegionInstanceId.equals(operationalRegionId) + || !"ACTIVE".equals(currentLifecycleEvidence.lifecycleStatus()) + || !startLocation.equals(currentLifecycleEvidence.startLocation()) + || runtimeRoomInstanceId != currentLifecycleEvidence.runtimeRoomInstanceId() + || placementResult.outcome() != WorldCanonicalInitialPlayerLocation.Outcome.APPLIED + || !binding.requestDigest().equals(placementResult.requestDigest())) { + throw new IllegalArgumentException( + "World current-location result is not an exact ACTIVE placement"); + } + } + + @Override + public byte[] originalLifecycleEvidenceBytes() { + return Arrays.copyOf(originalLifecycleEvidenceBytes, originalLifecycleEvidenceBytes.length); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationService.java new file mode 100644 index 0000000000..f6768defc9 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationService.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered, default-denied reader for exact World-owned initial actor placement. */ +public final class WorldCanonicalCurrentPlayerLocationService { + private final WorldCanonicalCurrentPlayerLocationRepository repository; + private final WorldCanonicalInitialPlayerLocationService.PlacementAuthorityVerifier verifier; + + /** Production-safe default while authenticated actor/admission owner proofs are unavailable. */ + public WorldCanonicalCurrentPlayerLocationService( + WorldCanonicalCurrentPlayerLocationRepository repository) { + this(repository, WorldCanonicalCurrentPlayerLocationService::denyByDefault); + } + + /** Explicit verifier injection is intended for a real owner producer or isolated proof only. */ + public WorldCanonicalCurrentPlayerLocationService( + WorldCanonicalCurrentPlayerLocationRepository repository, + WorldCanonicalInitialPlayerLocationService.PlacementAuthorityVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + } + + /** + * Requires current actor, Account and Game Session authority for every read. A retained placement + * result alone is never current caller authority. + */ + public Optional read( + WorldCanonicalInitialPlayerLocation.Request request) { + Objects.requireNonNull(request, "request"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World current-location read must verify authority outside an ambient transaction"); + } + var held = + Objects.requireNonNull( + verifier.verifyAndHold(request), + "Current-location verifier returned no held authority"); + try (held) { + held.requireHeld(); + var current = repository.read(request, held); + held.requireHeld(); + return current; + } + } + + private static WorldCanonicalInitialPlayerLocationService.HeldPlacementAuthority denyByDefault( + WorldCanonicalInitialPlayerLocation.Request request) { + throw new WorldCanonicalInitialPlayerLocationService.PlacementDeniedException( + "World current-location read has no authenticated current Entity assignment, Account, and Game Session authority producer"); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java new file mode 100644 index 0000000000..20ee3b41a1 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; + +/** + * Immutable component capture, never Account authorization or complete participant/release proof. + */ +public final class WorldCanonicalFrozenTopology { + public static final String STATUS = "CAPTURED_UNVERIFIED"; + + public record Request(WorldDraftTopologyCommitPlan plan, CaptureRequest freeze) { + public Request { + Objects.requireNonNull(plan, "plan"); + Objects.requireNonNull(freeze, "freeze"); + var owner = plan.ownerBinding(); + if (!freeze.targetNamespace().equals(owner.targetNamespace()) + || !freeze.canonicalTenantId().equals(owner.canonicalTenantId()) + || !freeze.canonicalVersionId().equals(owner.canonicalVersionId()) + || !freeze.intakeRequestId().equals(owner.intakeRequestId()) + || !freeze.appliedCommitId().equals(plan.binding().commitId().toString())) { + throw new IllegalArgumentException( + "Frozen topology must bind the exact selected complete commit and source"); + } + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId()); + var expected = + plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + if (expected.size() != freeze.suppliedOwnedAffectedTuples().size() + || !new java.util.HashSet<>(expected) + .equals(new java.util.HashSet<>(freeze.suppliedOwnedAffectedTuples()))) { + throw new IllegalArgumentException( + "Frozen topology must retain every exact original World affected tuple"); + } + } + } + + private final UUID captureId; + private final Request request; + private final WorldAuthoredVersionIdentityReceipt sourceIdentity; + private final WorldCanonicalAuthoredGraph graph; + private final byte[] graphBytes; + private final byte[] storageResultBytes; + private final byte[] resultBytes; + + WorldCanonicalFrozenTopology( + UUID captureId, + Request request, + WorldAuthoredVersionIdentityReceipt sourceIdentity, + WorldCanonicalAuthoredGraph graph, + byte[] graphBytes, + byte[] storageResultBytes, + byte[] resultBytes) { + this.captureId = Objects.requireNonNull(captureId, "captureId"); + if (captureId.equals(new UUID(0, 0))) + throw new IllegalArgumentException("Capture ID must be non-nil"); + this.request = Objects.requireNonNull(request, "request"); + this.sourceIdentity = Objects.requireNonNull(sourceIdentity, "sourceIdentity"); + this.graph = Objects.requireNonNull(graph, "graph"); + this.graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + this.storageResultBytes = + Objects.requireNonNull(storageResultBytes, "storageResultBytes").clone(); + this.resultBytes = Objects.requireNonNull(resultBytes, "resultBytes").clone(); + } + + public UUID captureId() { + return captureId; + } + + public Request request() { + return request; + } + + public WorldAuthoredVersionIdentityReceipt sourceIdentity() { + return sourceIdentity; + } + + public WorldCanonicalAuthoredGraph graph() { + return graph; + } + + public byte[] graphBytes() { + return graphBytes.clone(); + } + + public byte[] storageResultBytes() { + return storageResultBytes.clone(); + } + + public byte[] resultBytes() { + return resultBytes.clone(); + } + + public String status() { + return STATUS; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java new file mode 100644 index 0000000000..3055518042 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java @@ -0,0 +1,288 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Explicitly unwired immutable graph/2 journal; historical reads never reenter an owner writer. */ +public class WorldCanonicalFrozenTopologyRepository { + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + private final DSLContext dsl; + private final WorldAuthoredGraphSnapshotRepository owner; + private final WorldDraftTopologyCommitRepository topology; + private final WorldDraftDesignDigestService digestService; + + @SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW", justification = "No resources or finalizer.") + public WorldCanonicalFrozenTopologyRepository( + DSLContext dsl, + WorldAuthoredGraphSnapshotRepository owner, + WorldDraftTopologyCommitRepository topology, + WorldDraftDesignDigestService digestService) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.owner = Objects.requireNonNull(owner, "owner"); + this.topology = Objects.requireNonNull(topology, "topology"); + this.digestService = Objects.requireNonNull(digestService, "digestService"); + } + + /** Absence is UNKNOWN, not abort or permission to reopen an owner operation. */ + public Optional readCommitted(Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("Frozen topology readback requires no caller transaction"); + } + return Optional.ofNullable(find(Objects.requireNonNull(request, "request"))); + } + + /** Complete publication selection; owner and original commit are reconstructed internally. */ + public Optional readCommitted(CaptureRequest request) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("Frozen topology readback requires no caller transaction"); + } + return readFrozen(Objects.requireNonNull(request, "request")); + } + + /** Reads this immutable selector only inside the caller-owned read-only RR snapshot. */ + Optional readInOwnedSnapshot(CaptureRequest request) { + requireOwnedReadOnlyRepeatableReadSnapshot(); + return readFrozen(Objects.requireNonNull(request, "request")); + } + + private Optional readFrozen(CaptureRequest request) { + Record row = + dsl.resultQuery( + "SELECT binding_json,binding_digest,owner_binding_json FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.publicationFence()) + .fetchOne(); + if (row == null) return Optional.empty(); + var binding = + DraftCommitBinding.fromStored( + required(row, "binding_json", String.class), + required(row, "binding_digest", String.class)); + var ownerBinding = + JSON.readValue(required(row, "owner_binding_json", String.class), OwnerBinding.class); + return Optional.ofNullable( + find(new Request(WorldDraftTopologyCommitPlan.create(binding, ownerBinding), request))); + } + + private void requireOwnedReadOnlyRepeatableReadSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new ConflictException( + "Frozen topology snapshot read requires an active read-only REPEATABLE READ owner transaction"); + } + Integer jdbcIsolation = dsl.connectionResult(Connection::getTransactionIsolation); + if (!Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ).equals(jdbcIsolation)) { + throw new ConflictException( + "Frozen topology snapshot read requires actual JDBC REPEATABLE READ isolation"); + } + } + + WorldCanonicalFrozenTopology capture(Request request) { + // This seam validates actual PostgreSQL isolation and serializes through the existing V25 row. + var provenance = owner.lockAndResolve(request.freeze()); + WorldCanonicalFrozenTopology prior = find(request); + if (prior != null) return prior; + if (request.freeze().digestSchemaVersion() != 3) { + throw new ConflictException("New canonical graph capture requires digest schema 3"); + } + if (!"FROZEN".equals(provenance.ownerFreezePhase())) { + throw new ConflictException( + "New canonical graph capture requires the exact current FROZEN attempt"); + } + var stored = topology.readUnderFrozenLock(request.plan()); + Record original = + dsl.resultQuery( + "SELECT to_jsonb(v)::text AS identity_json, to_jsonb(i)::text AS intake_json " + + "FROM world_authored_version_identity v JOIN world_authored_source_intake i " + + "ON i.operation_id=v.intake_operation_id WHERE v.operation_id=?", + request.plan().ownerBinding().versionIdentityOperationId()) + .fetchOne(); + if (original == null) + throw new ConflictException("Frozen topology has no exact original source identity"); + String identityJson = required(original, "identity_json", String.class); + String intakeJson = required(original, "intake_json", String.class); + var identity = topology.verifyOriginalSource(request.plan(), identityJson, intakeJson); + var graph = + topology.verifyImmutableBytes(request.plan(), stored.graphBytes(), stored.resultBytes()); + requirePrivateKeys(graph, identity); + var digest = + digestService.getDraftDesignDigest( + Long.toString(provenance.localTenantKey()), + Long.toString(provenance.localVersionKey())); + if (!Long.toString(provenance.localTenantKey()).equals(digest.tenantId()) + || !Long.toString(provenance.localVersionKey()).equals(digest.scopeValue()) + || digest.digestSchemaVersion() != 3 + || !request.freeze().contentDigest().equals(digest.contentDigest())) { + throw new ConflictException( + "Canonical graph capture differs from exact schema-3 frozen content checkpoint"); + } + UUID captureId = UUID.randomUUID(); + String freezeJson = JSON.writeValueAsString(request.freeze()); + String ownerJson = JSON.writeValueAsString(request.plan().ownerBinding()); + byte[] result = + result( + captureId, + request, + identityJson, + intakeJson, + stored.graphBytes(), + stored.resultBytes()); + dsl.execute( + "INSERT INTO world_canonical_frozen_topology (capture_id,publication_fence," + + "request_id,commit_id,version_identity_operation_id,freeze_request_json,owner_binding_json," + + "binding_json,binding_digest,identity_json,intake_json,graph_bytes,graph_sha256," + + "storage_result_bytes,result_bytes,capture_status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + captureId, + request.freeze().publicationFence(), + request.plan().binding().requestId(), + request.plan().binding().commitId(), + request.plan().ownerBinding().versionIdentityOperationId(), + freezeJson, + ownerJson, + request.plan().binding().canonicalJson(), + request.plan().binding().digest(), + identityJson, + intakeJson, + stored.graphBytes(), + WorldAuthoredGraphSnapshotCapture.sha256(stored.graphBytes()), + stored.resultBytes(), + result, + WorldCanonicalFrozenTopology.STATUS); + WorldCanonicalFrozenTopology readback = find(request); + if (readback == null + || !captureId.equals(readback.captureId()) + || !Arrays.equals(result, readback.resultBytes())) { + throw new ConflictException( + "Frozen topology differs from exact immutable insertion readback"); + } + return readback; + } + + private WorldCanonicalFrozenTopology find(Request supplied) { + Record row = + dsl.resultQuery( + "SELECT * FROM world_canonical_frozen_topology WHERE publication_fence=?", + supplied.freeze().publicationFence()) + .fetchOne(); + if (row == null) return null; + String bindingJson = required(row, "binding_json", String.class); + var binding = + DraftCommitBinding.fromStored(bindingJson, required(row, "binding_digest", String.class)); + String ownerJson = required(row, "owner_binding_json", String.class); + var ownerBinding = JSON.readValue(ownerJson, OwnerBinding.class); + String freezeJson = required(row, "freeze_request_json", String.class); + var freeze = JSON.readValue(freezeJson, CaptureRequest.class); + Request retained = + new Request(WorldDraftTopologyCommitPlan.create(binding, ownerBinding), freeze); + if (!binding.equals(supplied.plan().binding()) + || !ownerBinding.equals(supplied.plan().ownerBinding()) + || !freeze.equals(supplied.freeze()) + || !bindingJson.equals(binding.canonicalJson()) + || !ownerJson.equals(JSON.writeValueAsString(ownerBinding)) + || !freezeJson.equals(JSON.writeValueAsString(freeze))) { + throw new ConflictException( + "Frozen topology request was reused with changed complete input or checkpoint"); + } + UUID captureId = required(row, "capture_id", UUID.class); + if (!freeze.publicationFence().equals(required(row, "publication_fence", UUID.class)) + || !binding.requestId().equals(required(row, "request_id", UUID.class)) + || !binding.commitId().equals(required(row, "commit_id", UUID.class)) + || !ownerBinding + .versionIdentityOperationId() + .equals(required(row, "version_identity_operation_id", UUID.class)) + || !WorldCanonicalFrozenTopology.STATUS.equals( + required(row, "capture_status", String.class))) { + throw new ConflictException("Frozen topology journal identity or proof state differs"); + } + String identityJson = required(row, "identity_json", String.class); + String intakeJson = required(row, "intake_json", String.class); + JSON.readTree(identityJson); + JSON.readTree(intakeJson); + var identity = topology.verifyOriginalSource(retained.plan(), identityJson, intakeJson); + byte[] graphBytes = required(row, "graph_bytes", byte[].class); + byte[] storageResult = required(row, "storage_result_bytes", byte[].class); + if (!WorldAuthoredGraphSnapshotCapture.sha256(graphBytes) + .equals(required(row, "graph_sha256", String.class))) { + throw new ConflictException( + "Frozen canonical graph bytes failed immutable integrity readback"); + } + var graph = topology.verifyImmutableBytes(retained.plan(), graphBytes, storageResult); + requirePrivateKeys(graph, identity); + byte[] resultBytes = required(row, "result_bytes", byte[].class); + if (!Arrays.equals( + resultBytes, + result(captureId, retained, identityJson, intakeJson, graphBytes, storageResult))) { + throw new ConflictException( + "Frozen topology result differs from every original retained field"); + } + return new WorldCanonicalFrozenTopology( + captureId, retained, identity, graph, graphBytes, storageResult, resultBytes); + } + + private static void requirePrivateKeys( + WorldCanonicalAuthoredGraph graph, WorldAuthoredVersionIdentityReceipt identity) { + if (graph.localTenantKey() != identity.sourceIntakeReceipt().localTenantKey() + || graph.localVersionKey() != identity.localVersionKey()) { + throw new ConflictException( + "Canonical graph private keys differ from original source identity"); + } + } + + private byte[] result( + UUID id, + Request request, + String identityJson, + String intakeJson, + byte[] graph, + byte[] storageResult) { + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", "1"); + result.put("status", WorldCanonicalFrozenTopology.STATUS); + result.put( + "missingProof", + java.util.List.of( + "ACCOUNT_AUTHORIZATION", + "COMPLETE_PARTICIPANT_COMMIT", + "PUBLICATION_CHECKPOINT_DIGEST")); + result.put("captureId", id.toString()); + result.put("freeze", request.freeze()); + result.put("ownerBinding", request.plan().ownerBinding()); + result.put("bindingJson", request.plan().binding().canonicalJson()); + result.put("bindingDigest", request.plan().binding().digest()); + result.put("identityJson", identityJson); + result.put("intakeJson", intakeJson); + result.put("graphBytes", graph); + result.put("storageResultBytes", storageResult); + return JSON.writeValueAsBytes(result); + } + + private static T required(Record row, String name, Class type) { + T value = row.get(name, type); + if (value == null) throw new ConflictException("Frozen topology is missing " + name); + return value; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyService.java new file mode 100644 index 0000000000..3e8dceb9f2 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyService.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Owner-private, explicitly unwired capture; this adds no publication or runtime entry point. */ +public final class WorldCanonicalFrozenTopologyService { + private final WorldCanonicalFrozenTopologyRepository repository; + private final TransactionTemplate transaction; + + public WorldCanonicalFrozenTopologyService( + WorldCanonicalFrozenTopologyRepository repository, PlatformTransactionManager manager) { + this.repository = Objects.requireNonNull(repository, "repository"); + transaction = new TransactionTemplate(Objects.requireNonNull(manager, "manager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** Exact retry reads the journal first, including after terminal state, without a writer. */ + public WorldCanonicalFrozenTopology capture(Request request) { + requireNoCallerTransaction(); + var prior = repository.readCommitted(request); + if (prior.isPresent()) return prior.orElseThrow(); + return Objects.requireNonNull(transaction.execute(status -> repository.capture(request))); + } + + public Optional readCommitted(Request request) { + requireNoCallerTransaction(); + return repository.readCommitted(request); + } + + private static void requireNoCallerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("Frozen topology requires an independent owner operation"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepository.java new file mode 100644 index 0000000000..a2a4fbcd50 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepository.java @@ -0,0 +1,587 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Owner-local terminal storage and immutable Game Session proof readback for canonical holds. */ +public final class WorldCanonicalInitialAdmissionHoldFinalizationRepository { + private static final String TRANSACTION_STATE_SQL = + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"; + private static final String HOLD_SELECT = + "SELECT hold_id, hold_fence, tenant_id, realm_uuid, playable_state_namespace_uuid, " + + "playable_state_scope, game_instance_id, version_id, active_lifecycle_epoch, " + + "initial_admission_request_id, request_digest, expected_no_prior_pointer, " + + "expected_catalog_revision, status, owner_proof_id, owner_proof_digest, " + + "owner_pointer_audit_id, owner_pointer_version, terminal_at, row_version, " + + "canonical_target_namespace, canonical_tenant_id, canonical_world_slug, " + + "canonical_game_instance_id, canonical_version_id, initial_admission_origin, " + + "expected_prior_pointer_version, canonical_request_bytes, hold_binding_digest, " + + "canonical_owner_proof_bytes, canonical_owner_proof_digest " + + "FROM initial_admission_bind_hold "; + private static final String FINALIZE_SQL = + "SELECT world_finalize_canonical_initial_admission_hold(" + + "?::uuid, ?::uuid, ?::text, ?::text, ?::text, ?::text, ?::bigint, " + + "?::timestamptz, ?::boolean, ?::bytea, ?::text)"; + + private final DSLContext dsl; + private final TransactionTemplate writeTransaction; + private final WorldCanonicalInstanceAssociationRepository associationRepository; + private final WorldCanonicalInstanceLifecycleReadRepository lifecycleReadRepository; + + public WorldCanonicalInitialAdmissionHoldFinalizationRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceAssociationRepository associationRepository, + WorldCanonicalInstanceLifecycleReadRepository lifecycleReadRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository"); + this.lifecycleReadRepository = + Objects.requireNonNull(lifecycleReadRepository, "lifecycleReadRepository"); + writeTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Reads and verifies a committed typed hold in the caller's exact owner snapshot. The caller owns + * lifecycle freshness; this method returns no current ACTIVE or admission authority. + */ + public Optional readCommittedInOwnerTransaction( + UUID holdId) { + Objects.requireNonNull(holdId, "holdId"); + OwnerTransaction owner = requireOwnerTransaction(); + Record row = readByHoldId(holdId, false); + if (row == null) return Optional.empty(); + if (!hasCanonicalRequest(row)) { + requireNoPartialCanonicalMetadata(row); + return Optional.empty(); + } + + Request request = readRequest(row); + WorldCanonicalInstanceAssociation association = + associationForOwnerSnapshot(request.canonicalGameInstanceId(), owner); + HoldIdentity identity = verifyStoredIdentity(row, request, association); + String status = required(row, "status", String.class); + if ("PENDING".equals(status)) { + requireNoTerminalProof(row); + return Optional.empty(); + } + if (!"COMMITTED".equals(status) && !"ABORTED".equals(status)) { + throw invalid("Canonical initial-admission hold has an unsupported terminal state"); + } + GameSessionCanonicalInitialAdmissionOwnerProof proof = verifyStoredProof(row, identity); + return proof.outcome() == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED + ? Optional.of(proof) + : Optional.empty(); + } + + /** + * Applies one authenticated terminal outcome in an independent writable READ COMMITTED + * transaction. The held verifier is checked both before mutation and in the transaction's + * before-commit phase, so authority loss rolls back the terminal write. + */ + GameSessionCanonicalInitialAdmissionOwnerProof finalizeTerminal( + HoldIdentity expectedIdentity, + GameSessionCanonicalInitialAdmissionOwnerProof proof, + WorldCanonicalInitialAdmissionHoldFinalizationService.HeldOwnerProof heldProof) { + Objects.requireNonNull(expectedIdentity, "expectedIdentity"); + Objects.requireNonNull(proof, "proof"); + Objects.requireNonNull(heldProof, "heldProof"); + requireNoAmbientTransaction("World canonical initial-admission hold finalization"); + requireProofForIdentity(expectedIdentity, proof); + + return writeTransaction.execute( + status -> { + requireWritableReadCommittedTransaction(); + heldProof.requireHeld(); + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void beforeCommit(boolean readOnly) { + heldProof.requireHeld(); + } + }); + + Record candidate = readByHoldId(expectedIdentity.holdId(), false); + if (candidate == null) { + throw denied("Canonical initial-admission hold identity is missing"); + } + if (!hasCanonicalRequest(candidate)) { + requireNoPartialCanonicalMetadata(candidate); + throw denied("Legacy untyped initial-admission hold cannot be finalized canonically"); + } + Request request = readRequest(candidate); + WorldCanonicalInstanceAssociation association = + associationRepository + .readOwnerAssociationInActivationTransaction(request.canonicalGameInstanceId()) + .orElseThrow(() -> denied("Canonical World association is missing")); + HoldIdentity candidateIdentity = verifyStoredIdentity(candidate, request, association); + if (!Arrays.equals( + candidateIdentity.canonicalBytes(), expectedIdentity.canonicalBytes())) { + throw denied( + "Canonical World hold identity or fence differs from the requested outcome"); + } + + String candidateStatus = required(candidate, "status", String.class); + if (isTerminal(candidateStatus)) { + return exactTerminalRetry(candidate, candidateIdentity, proof); + } + if (!"PENDING".equals(candidateStatus)) { + throw denied("Canonical World hold is not a terminalizable PENDING row"); + } + + WorldCanonicalInstanceLifecycleEvidence.Request selector = lifecycleSelector(association); + WorldCanonicalInstanceLifecycleEvidence lifecycle = + lifecycleReadRepository + .readForActivationInOwnerTransaction(selector) + .orElseThrow(() -> denied("Canonical World lifecycle row is missing")); + if (!selector.equals(lifecycle.request()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != request.activeLifecycleEpoch()) { + throw denied( + "Canonical World target is not the exact requested ACTIVE lifecycle epoch"); + } + + Record locked = readByHoldId(expectedIdentity.holdId(), true); + if (locked == null) { + throw denied("Canonical initial-admission hold disappeared before terminalization"); + } + HoldIdentity lockedIdentity = verifyStoredIdentity(locked, request, association); + if (!Arrays.equals(lockedIdentity.canonicalBytes(), expectedIdentity.canonicalBytes())) { + throw denied("Canonical World hold identity changed before terminalization"); + } + String lockedStatus = required(locked, "status", String.class); + if (isTerminal(lockedStatus)) { + return exactTerminalRetry(locked, lockedIdentity, proof); + } + if (!"PENDING".equals(lockedStatus)) { + throw denied("Canonical World hold is not a terminalizable PENDING row"); + } + + heldProof.requireHeld(); + dsl.fetchOne( + FINALIZE_SQL, + expectedIdentity.holdId(), + expectedIdentity.holdFence(), + proof.outcome().name(), + request.initialAdmissionRequestId(), + proof.proofDigest().substring("sha256:".length()), + proof.auditEventId() == null ? null : proof.auditEventId().toString(), + proof.committedPointerVersion(), + proof.terminalAt().atOffset(ZoneOffset.UTC), + proof.positiveDurableAbort(), + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof), + sha256Prefix( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof))); + + Record stored = readByHoldId(expectedIdentity.holdId(), false); + if (stored == null) { + throw invalid("Canonical initial-admission terminal write has no owner readback"); + } + GameSessionCanonicalInitialAdmissionOwnerProof readback = + verifyStoredProof(stored, expectedIdentity); + if (!Arrays.equals( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(readback), + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof))) { + throw invalid( + "Canonical initial-admission terminal readback differs from Game Session proof"); + } + heldProof.requireHeld(); + return readback; + }); + } + + private GameSessionCanonicalInitialAdmissionOwnerProof exactTerminalRetry( + Record row, + HoldIdentity identity, + GameSessionCanonicalInitialAdmissionOwnerProof requestedProof) { + GameSessionCanonicalInitialAdmissionOwnerProof stored = verifyStoredProof(row, identity); + if (!Arrays.equals( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(stored), + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(requestedProof))) { + throw denied("Canonical initial-admission hold already has a different terminal owner proof"); + } + return stored; + } + + private WorldCanonicalInstanceAssociation associationForOwnerSnapshot( + UUID canonicalGameInstanceId, OwnerTransaction owner) { + return (owner == OwnerTransaction.READ_ONLY_REPEATABLE_READ + ? associationRepository.readOwnerAssociationInOwnerTransaction(canonicalGameInstanceId) + : associationRepository.readOwnerAssociationInActivationTransaction( + canonicalGameInstanceId)) + .orElseThrow(() -> denied("Canonical World association is missing")); + } + + private WorldCanonicalInstanceLifecycleEvidence.Request lifecycleSelector( + WorldCanonicalInstanceAssociation association) { + var identity = association.identity(); + var descriptor = association.completeLaunchBinding().descriptor(); + var release = association.completeLaunchBinding().evidence().releaseAttestation(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.randomUUID(), + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.worldSlug(), + identity.canonicalGameInstanceId(), + identity.playableStateNamespaceId(), + identity.playableStateScope(), + identity.publicProduction(), + identity.controlPlaneRequestId(), + association.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + } + + private Record readByHoldId(UUID holdId, boolean lock) { + return dsl.fetchOne(HOLD_SELECT + "WHERE hold_id = ?" + (lock ? " FOR UPDATE" : ""), holdId); + } + + private HoldIdentity verifyStoredIdentity( + Record row, Request request, WorldCanonicalInstanceAssociation association) { + try { + byte[] requestBytes = required(row, "canonical_request_bytes", byte[].class); + Request storedRequest = WorldCanonicalInitialAdmissionHold.Request.fromStored(requestBytes); + if (!request.equals(storedRequest) + || !Arrays.equals(requestBytes, request.canonicalRequestBytes()) + || !request + .holdBindingDigest() + .equals(required(row, "hold_binding_digest", String.class))) { + throw invalid("Persisted canonical World hold request bytes or digest are inconsistent"); + } + + var canonical = association.identity(); + var privateKeys = association.worldPrepareFields(); + if (!request.targetNamespace().equals(canonical.targetNamespace()) + || !request.canonicalTenantId().equals(canonical.canonicalTenantId()) + || !request.worldSlug().equals(canonical.worldSlug()) + || !request.playableStateNamespaceId().equals(canonical.playableStateNamespaceId()) + || !request.playableStateScope().equals(canonical.playableStateScope()) + || !request.canonicalGameInstanceId().equals(canonical.canonicalGameInstanceId()) + || !request.canonicalVersionId().equals(association.canonicalVersionId()) + || required(row, "tenant_id", Long.class) != privateKeys.privateTenantKey() + || required(row, "game_instance_id", Long.class) != privateKeys.privateGameInstanceKey() + || required(row, "version_id", Long.class) != privateKeys.localVersionKey() + || !request.realmId().equals(required(row, "realm_uuid", UUID.class)) + || !request + .playableStateNamespaceId() + .equals(required(row, "playable_state_namespace_uuid", UUID.class)) + || !request + .playableStateScope() + .equals(required(row, "playable_state_scope", String.class)) + || request.activeLifecycleEpoch() != required(row, "active_lifecycle_epoch", Long.class) + || !request + .initialAdmissionRequestId() + .equals(required(row, "initial_admission_request_id", String.class)) + || !request + .initialAdmissionRequestDigest() + .equals(required(row, "request_digest", String.class)) + || request.expectedCatalogRevision() + != required(row, "expected_catalog_revision", Long.class) + || (request.initialAdmissionOrigin() == InitialAdmissionOrigin.NO_PRIOR_POINTER) + != required(row, "expected_no_prior_pointer", Boolean.class) + || !request + .targetNamespace() + .equals(required(row, "canonical_target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(row, "canonical_tenant_id", UUID.class)) + || !request.worldSlug().equals(required(row, "canonical_world_slug", String.class)) + || !request + .canonicalGameInstanceId() + .equals(required(row, "canonical_game_instance_id", UUID.class)) + || !request.canonicalVersionId().equals(required(row, "canonical_version_id", UUID.class)) + || !request + .initialAdmissionOrigin() + .name() + .equals(required(row, "initial_admission_origin", String.class)) + || !Objects.equals( + row.get("expected_prior_pointer_version", Long.class), + request.expectedPriorPointerVersion())) { + throw invalid( + "Persisted canonical hold differs from its actual association or private keys"); + } + return new HoldIdentity( + request, required(row, "hold_id", UUID.class), required(row, "hold_fence", UUID.class)); + } catch (InvalidFinalizationEvidenceException invalid) { + throw invalid; + } catch (RuntimeException invalid) { + throw new InvalidFinalizationEvidenceException( + "Persisted canonical initial-admission identity is incomplete or invalid", invalid); + } + } + + private Request readRequest(Record row) { + try { + byte[] bytes = required(row, "canonical_request_bytes", byte[].class); + return WorldCanonicalInitialAdmissionHold.Request.fromStored(bytes); + } catch (RuntimeException invalid) { + throw new InvalidFinalizationEvidenceException( + "Persisted canonical initial-admission request is invalid", invalid); + } + } + + private GameSessionCanonicalInitialAdmissionOwnerProof verifyStoredProof( + Record row, HoldIdentity identity) { + try { + byte[] bytes = required(row, "canonical_owner_proof_bytes", byte[].class); + String storedDigest = required(row, "canonical_owner_proof_digest", String.class); + if (!sha256Prefix(bytes).equals(storedDigest)) { + throw invalid("Persisted canonical owner proof digest differs from its complete bytes"); + } + GameSessionCanonicalInitialAdmissionOwnerProof proof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored(bytes); + if (!identity.equals(proof.holdIdentity())) { + throw invalid( + "Persisted Game Session owner proof differs from the exact World hold identity"); + } + String status = required(row, "status", String.class); + String expectedStatus = proof.outcome().name(); + if (!expectedStatus.equals(status) + || "PENDING".equals(status) + || !identity + .request() + .initialAdmissionRequestId() + .equals(required(row, "owner_proof_id", String.class)) + || !proof + .proofDigest() + .substring("sha256:".length()) + .equals(required(row, "owner_proof_digest", String.class))) { + throw invalid("Persisted canonical terminal fields differ from the complete owner proof"); + } + + LocalDateTime terminalAt = required(row, "terminal_at", LocalDateTime.class); + Instant terminalInstant = terminalAt.toInstant(ZoneOffset.UTC); + if (!proof.terminalAt().equals(terminalInstant)) { + throw invalid("Persisted canonical terminal timestamp differs from the exact owner proof"); + } + if (proof.outcome() == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + if (!Long.toString(proof.auditEventId()) + .equals(required(row, "owner_pointer_audit_id", String.class)) + || !Objects.equals( + proof.committedPointerVersion(), + required(row, "owner_pointer_version", Long.class))) { + throw invalid("Persisted committed pointer and audit fields differ from owner proof"); + } + requireNextPointerVersion(identity.request(), proof); + } else if (proof.auditEventId() != null + || proof.committedPointerVersion() != null + || row.get("owner_pointer_audit_id", String.class) != null + || row.get("owner_pointer_version", Long.class) != null + || !proof.positiveDurableAbort()) { + throw invalid("Persisted aborted outcome lacks positive durable abort-only evidence"); + } + return proof; + } catch (InvalidFinalizationEvidenceException invalid) { + throw invalid; + } catch (RuntimeException invalid) { + throw new InvalidFinalizationEvidenceException( + "Persisted canonical Game Session terminal proof is incomplete or invalid", invalid); + } + } + + private static void requireProofForIdentity( + HoldIdentity expectedIdentity, GameSessionCanonicalInitialAdmissionOwnerProof proof) { + if (!expectedIdentity.equals(proof.holdIdentity()) + || proof.outcome() == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + throw denied("Game Session owner proof is not terminal for the exact requested hold"); + } + if (proof.terminalAt().getNano() % 1_000 != 0) { + throw denied("Game Session terminal timestamp exceeds World storage precision"); + } + if (proof.outcome() == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + requireNextPointerVersion(expectedIdentity.request(), proof); + if (proof.positiveDurableAbort()) { + throw denied("Committed owner proof cannot assert durable abort"); + } + } else if (!proof.positiveDurableAbort()) { + throw denied("Aborted owner proof requires positive durable fencing"); + } + } + + private static void requireNextPointerVersion( + Request request, GameSessionCanonicalInitialAdmissionOwnerProof proof) { + long expectedVersion; + try { + expectedVersion = + switch (request.initialAdmissionOrigin()) { + case NO_PRIOR_POINTER -> 1L; + case EXPECT_CLOSED -> Math.addExact(request.expectedPriorPointerVersion(), 1L); + }; + } catch (ArithmeticException overflow) { + throw denied("Expected prior pointer version cannot advance without overflow"); + } + if (!Long.valueOf(expectedVersion).equals(proof.committedPointerVersion())) { + throw denied("Committed owner proof does not name the exact next pointer version"); + } + } + + private static void requireNoTerminalProof(Record row) { + if (row.get("canonical_owner_proof_bytes", byte[].class) != null + || row.get("canonical_owner_proof_digest", String.class) != null + || row.get("owner_proof_id", String.class) != null + || row.get("owner_proof_digest", String.class) != null + || row.get("owner_pointer_audit_id", String.class) != null + || row.get("owner_pointer_version", Long.class) != null + || row.get("terminal_at", LocalDateTime.class) != null) { + throw invalid("Canonical PENDING hold contains terminal owner proof fields"); + } + } + + private static boolean hasCanonicalRequest(Record row) { + return row.get("canonical_request_bytes", byte[].class) != null; + } + + private static void requireNoPartialCanonicalMetadata(Record row) { + for (String field : + new String[] { + "canonical_target_namespace", + "canonical_tenant_id", + "canonical_world_slug", + "canonical_game_instance_id", + "canonical_version_id", + "initial_admission_origin", + "expected_prior_pointer_version", + "hold_binding_digest", + "canonical_owner_proof_bytes", + "canonical_owner_proof_digest" + }) { + if (row.get(field, Object.class) != null) { + throw invalid("Retained legacy hold has partial canonical metadata"); + } + } + } + + private static boolean isTerminal(String status) { + return "COMMITTED".equals(status) || "ABORTED".equals(status); + } + + private OwnerTransaction requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Typed hold read requires the caller's active owner transaction"); + } + boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + OwnerTransaction owner; + if (readOnly && Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ).equals(isolation)) { + owner = OwnerTransaction.READ_ONLY_REPEATABLE_READ; + } else if (!readOnly + && Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED).equals(isolation)) { + owner = OwnerTransaction.WRITABLE_READ_COMMITTED; + } else { + throw new IllegalStateException( + "Typed hold read requires a read-only REPEATABLE READ or writable READ COMMITTED owner transaction"); + } + Record state = transactionState(); + if (owner == OwnerTransaction.READ_ONLY_REPEATABLE_READ + && (!"repeatable read".equals(required(state, "isolation", String.class)) + || !"on".equals(required(state, "read_only", String.class)))) { + throw new IllegalStateException( + "Typed hold read requires a read-only REPEATABLE READ owner transaction"); + } + if (owner == OwnerTransaction.WRITABLE_READ_COMMITTED + && (!"read committed".equals(required(state, "isolation", String.class)) + || !"off".equals(required(state, "read_only", String.class)))) { + throw new IllegalStateException( + "Typed hold read requires a writable READ COMMITTED owner transaction"); + } + return owner; + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Canonical World initial-admission finalization requires writable READ COMMITTED"); + } + Record state = transactionState(); + if (!"read committed".equals(required(state, "isolation", String.class)) + || !"off".equals(required(state, "read_only", String.class))) { + throw new IllegalStateException( + "Canonical World initial-admission finalization requires writable READ COMMITTED"); + } + } + + private Record transactionState() { + return Objects.requireNonNull( + dsl.fetchOne(TRANSACTION_STATE_SQL), "World transaction state query returned no row"); + } + + private static String sha256Prefix(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static T required(Record row, String field, Class type) { + return Objects.requireNonNull(row.get(field, type), "Persisted " + field + " is null"); + } + + private static void requireNoAmbientTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException(label + " must start outside an ambient transaction"); + } + } + + private static InvalidFinalizationEvidenceException invalid(String message) { + return new InvalidFinalizationEvidenceException(message); + } + + private static FinalizationDeniedException denied(String message) { + return new FinalizationDeniedException(message); + } + + private enum OwnerTransaction { + READ_ONLY_REPEATABLE_READ, + WRITABLE_READ_COMMITTED + } + + public static final class InvalidFinalizationEvidenceException extends IllegalStateException { + public InvalidFinalizationEvidenceException(String message) { + super(message); + } + + public InvalidFinalizationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } + + public static final class FinalizationDeniedException extends IllegalStateException { + public FinalizationDeniedException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationService.java new file mode 100644 index 0000000000..88e861e0b5 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationService.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicitly gated World owner boundary for terminalizing a canonical first-open hold. + * + *

The injected verifier must obtain and hold an operation-specific authenticated Game Session + * owner readback. This class has no permissive verifier and does not make elapsed time, missing + * evidence, or a pending result terminal. + */ +public final class WorldCanonicalInitialAdmissionHoldFinalizationService { + private final WorldCanonicalInitialAdmissionHoldFinalizationRepository repository; + private final OwnerProofVerifier verifier; + + public WorldCanonicalInitialAdmissionHoldFinalizationService( + WorldCanonicalInitialAdmissionHoldFinalizationRepository repository, + OwnerProofVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + } + + /** + * Finalizes one exact acquired identity while the authenticated owner proof remains held through + * the independent World commit and exact readback. + */ + public GameSessionCanonicalInitialAdmissionOwnerProof finalizeHold( + HoldIdentity expectedIdentity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome expectedOutcome) { + Objects.requireNonNull(expectedIdentity, "expectedIdentity"); + Objects.requireNonNull(expectedOutcome, "expectedOutcome"); + requireNoAmbientTransaction(); + if (expectedOutcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + throw denied("PENDING Game Session owner evidence cannot terminalize a World hold"); + } + + HeldOwnerProof held = + Objects.requireNonNull( + verifier.verifyAndHold(expectedIdentity, expectedOutcome), + "Game Session owner proof verifier returned no held proof"); + try { + GameSessionCanonicalInitialAdmissionOwnerProof proof = + Objects.requireNonNull(held.proof(), "held owner proof"); + requireExactProof(expectedIdentity, expectedOutcome, proof); + held.requireHeld(); + GameSessionCanonicalInitialAdmissionOwnerProof stored = + repository.finalizeTerminal(expectedIdentity, proof, held); + held.requireHeld(); + return stored; + } finally { + held.close(); + } + } + + /** Explicit fail-closed verifier for configurations that have no authenticated GS adapter. */ + public static OwnerProofVerifier denyAllVerifier() { + return (identity, outcome) -> { + throw denied( + "Authenticated Game Session canonical initial-admission owner proof is unavailable"); + }; + } + + private static void requireExactProof( + HoldIdentity expectedIdentity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome expectedOutcome, + GameSessionCanonicalInitialAdmissionOwnerProof proof) { + if (!expectedIdentity.equals(proof.holdIdentity()) || proof.outcome() != expectedOutcome) { + throw denied("Game Session owner proof differs from the exact requested hold or outcome"); + } + if (proof.terminalAt().getNano() % 1_000 != 0) { + throw denied("Game Session terminal timestamp exceeds World storage precision"); + } + if (expectedOutcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + long expectedPointerVersion; + try { + expectedPointerVersion = + switch (expectedIdentity.request().initialAdmissionOrigin()) { + case NO_PRIOR_POINTER -> 1L; + case EXPECT_CLOSED -> + Math.addExact(expectedIdentity.request().expectedPriorPointerVersion(), 1L); + }; + } catch (ArithmeticException overflow) { + throw denied("Expected prior pointer version cannot advance without overflow"); + } + if (!Long.valueOf(expectedPointerVersion).equals(proof.committedPointerVersion()) + || proof.positiveDurableAbort()) { + throw denied("Committed Game Session owner proof has a noncanonical pointer version"); + } + } else if (!proof.positiveDurableAbort() + || proof.committedPointerVersion() != null + || proof.auditEventId() != null) { + throw denied("Aborted Game Session owner proof lacks positive durable fencing"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World canonical initial-admission hold finalization must start outside an ambient transaction"); + } + } + + private static FinalizationDeniedException denied(String message) { + return new FinalizationDeniedException(message); + } + + /** Operation-specific verifier for the complete authenticated Game Session outcome. */ + @FunctionalInterface + public interface OwnerProofVerifier { + HeldOwnerProof verifyAndHold( + HoldIdentity expectedIdentity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome expectedOutcome); + } + + /** A verified exact owner outcome held valid until the enclosing World commit returns. */ + public interface HeldOwnerProof extends AutoCloseable { + GameSessionCanonicalInitialAdmissionOwnerProof proof(); + + void requireHeld(); + + @Override + void close(); + } + + public static final class FinalizationDeniedException extends IllegalStateException { + public FinalizationDeniedException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcService.java new file mode 100644 index 0000000000..3fa0ad6b6c --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcService.java @@ -0,0 +1,322 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.ByteString; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicitly gated authenticated hold adapter; no default runtime registration. */ +public final class WorldCanonicalInitialAdmissionHoldGrpcService + extends WorldCanonicalInitialAdmissionHoldServiceGrpc + .WorldCanonicalInitialAdmissionHoldServiceImplBase { + private final WorldCanonicalInitialAdmissionHoldRepository repository; + private final String trustedNamespace; + + public WorldCanonicalInitialAdmissionHoldGrpcService( + WorldCanonicalInitialAdmissionHoldRepository repository, + @Value("${firemud.grpc.workload-namespace:}") String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void acquireCanonicalInitialAdmissionHold( + AcquireCanonicalInitialAdmissionHoldRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameSessionPeer(responseObserver)) return; + if (!requireIndependentOwnerOperation(responseObserver)) return; + + ParsedAcquire parsed; + try { + parsed = parseAcquireRequest(request); + } catch (IllegalArgumentException invalid) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Complete canonical World initial-admission hold evidence is required"); + return; + } + if (!trustedNamespace.equals(parsed.holdRequest().targetNamespace()) + || !trustedNamespace.equals(parsed.lifecycleRequest().targetNamespace())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World hold and lifecycle namespaces must match the authenticated peer"); + return; + } + if (!sameTarget(parsed.holdRequest(), parsed.lifecycleRequest())) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World lifecycle evidence does not match the complete hold target"); + return; + } + + HoldIdentity identity; + try { + identity = repository.acquire(parsed.holdRequest(), parsed.lifecycleRequest()); + } catch (WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException conflict) { + fail( + responseObserver, + Status.ALREADY_EXISTS, + "Canonical World initial-admission hold conflicts with existing owner state"); + return; + } catch ( + WorldCanonicalInitialAdmissionHoldRepository.InvalidHoldIdentityException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World initial-admission hold identity is inconsistent"); + return; + } catch (TransientDataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Canonical World initial-admission hold storage is temporarily unavailable"); + return; + } catch (DataAccessException storageFailure) { + fail( + responseObserver, + Status.INTERNAL, + "Canonical World initial-admission hold storage failed"); + return; + } catch (RuntimeException failure) { + fail( + responseObserver, + Status.INTERNAL, + "Canonical World initial-admission hold acquisition failed"); + return; + } + + byte[] identityBytes; + try { + identityBytes = requireExactIdentity(parsed.holdRequest(), identity); + } catch (RuntimeException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World hold owner returned a substituted or incomplete identity"); + return; + } + responseObserver.onNext( + AcquireCanonicalInitialAdmissionHoldResponse.newBuilder() + .setHoldIdentityBytes(ByteString.copyFrom(identityBytes)) + .build()); + responseObserver.onCompleted(); + } + + @Override + public void readCanonicalInitialAdmissionHoldIdentity( + ReadCanonicalInitialAdmissionHoldIdentityRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameSessionPeer(responseObserver)) return; + if (!requireIndependentOwnerOperation(responseObserver)) return; + + ParsedRead parsed; + try { + parsed = parseReadRequest(request); + } catch (IllegalArgumentException invalid) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A canonical read UUID and complete hold request are required"); + return; + } + if (!trustedNamespace.equals(parsed.holdRequest().targetNamespace())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World hold namespace must match the authenticated peer"); + return; + } + + Optional maybeIdentity; + try { + maybeIdentity = repository.readIdentity(parsed.holdRequest()); + } catch (WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException conflict) { + fail( + responseObserver, + Status.ALREADY_EXISTS, + "Canonical World initial-admission hold identity conflicts with owner state"); + return; + } catch ( + WorldCanonicalInitialAdmissionHoldRepository.InvalidHoldIdentityException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World initial-admission hold identity is inconsistent"); + return; + } catch (TransientDataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Canonical World initial-admission hold storage is temporarily unavailable"); + return; + } catch (DataAccessException storageFailure) { + fail( + responseObserver, + Status.INTERNAL, + "Canonical World initial-admission hold storage failed"); + return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.INTERNAL, "Canonical World initial-admission hold read failed"); + return; + } + if (maybeIdentity == null) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World hold owner returned no read result"); + return; + } + if (maybeIdentity.isEmpty()) { + fail( + responseObserver, + Status.NOT_FOUND, + "No exact historical canonical World hold identity was found"); + return; + } + + byte[] identityBytes; + try { + identityBytes = requireExactIdentity(parsed.holdRequest(), maybeIdentity.orElseThrow()); + } catch (RuntimeException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World hold owner returned a substituted or incomplete identity"); + return; + } + responseObserver.onNext( + ReadCanonicalInitialAdmissionHoldIdentityResponse.newBuilder() + .setReadRequestId(parsed.readRequestId()) + .setHoldIdentityBytes(ByteString.copyFrom(identityBytes)) + .build()); + responseObserver.onCompleted(); + } + + private static ParsedAcquire parseAcquireRequest( + AcquireCanonicalInitialAdmissionHoldRequest request) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed canonical acquire request is required"); + } + Request holdRequest = + WorldCanonicalInitialAdmissionHold.Request.fromStored( + request.getCanonicalHoldRequestBytes().toByteArray()); + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest = + WorldCanonicalInstanceLifecycleEvidence.Request.fromStored( + request.getCanonicalLifecycleReadRequestBytes().toByteArray()); + return new ParsedAcquire(holdRequest, lifecycleRequest); + } + + private static ParsedRead parseReadRequest( + ReadCanonicalInitialAdmissionHoldIdentityRequest request) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed canonical read request is required"); + } + String readId = request.getReadRequestId(); + UUID parsedReadId; + try { + parsedReadId = UUID.fromString(readId); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Read request ID must be a canonical UUID", invalid); + } + if (new UUID(0L, 0L).equals(parsedReadId) || !parsedReadId.toString().equals(readId)) { + throw new IllegalArgumentException("Read request ID must be a canonical non-nil UUID"); + } + Request holdRequest = + WorldCanonicalInitialAdmissionHold.Request.fromStored( + request.getCanonicalHoldRequestBytes().toByteArray()); + return new ParsedRead(readId, holdRequest); + } + + private static boolean sameTarget( + Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + return holdRequest.canonicalTenantId().equals(lifecycleRequest.canonicalTenantId()) + && holdRequest.worldSlug().equals(lifecycleRequest.worldSlug()) + && holdRequest + .playableStateNamespaceId() + .equals(lifecycleRequest.playableStateNamespaceId()) + && holdRequest.playableStateScope().equals(lifecycleRequest.playableStateScope()) + && holdRequest.canonicalGameInstanceId().equals(lifecycleRequest.canonicalGameInstanceId()) + && holdRequest.canonicalVersionId().equals(lifecycleRequest.canonicalVersionId()) + && lifecycleRequest.publicProduction(); + } + + private static byte[] requireExactIdentity(Request expected, HoldIdentity actual) { + if (actual == null + || actual.request() == null + || !expected.equals(actual.request()) + || !Arrays.equals(expected.canonicalRequestBytes(), actual.canonicalRequestBytes()) + || !expected.holdBindingDigest().equals(actual.holdBindingDigest())) { + throw new IllegalStateException("Canonical World hold identity differs from the request"); + } + byte[] bytes = actual.canonicalBytes(); + HoldIdentity decoded = WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(bytes); + if (!expected.equals(decoded.request()) + || !Arrays.equals(expected.canonicalRequestBytes(), decoded.canonicalRequestBytes()) + || !expected.holdBindingDigest().equals(decoded.holdBindingDigest()) + || decoded.holdId() == null + || decoded.holdFence() == null) { + throw new IllegalStateException("Canonical World hold identity failed exact readback"); + } + return bytes; + } + + private boolean requireAuthenticatedGameSessionPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-session-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Only the verified same-namespace Game Session workload without end-user context is allowed"); + return false; + } + + private static boolean requireIndependentOwnerOperation(StreamObserver responseObserver) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + && !TransactionSynchronizationManager.isSynchronizationActive()) { + return true; + } + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World hold operations require independent owner transactions"); + return false; + } + + private static void fail(StreamObserver responseObserver, Status status, String description) { + responseObserver.onError(status.withDescription(description).asRuntimeException()); + } + + private record ParsedAcquire( + Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) {} + + private record ParsedRead(String readRequestId, Request holdRequest) {} +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java new file mode 100644 index 0000000000..c9e49ec29e --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java @@ -0,0 +1,397 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered owner-local acquisition and immutable readback for canonical first-open holds. + * + *

This repository records acquisition identity only. It does not resolve or terminalize the + * hold, establish current admission authority, or supply Game Session outcome evidence. + */ +public final class WorldCanonicalInitialAdmissionHoldRepository { + private static final String HOLD_SELECT = + "SELECT hold_id, hold_fence, tenant_id, realm_uuid, playable_state_namespace_uuid, " + + "playable_state_scope, game_instance_id, version_id, active_lifecycle_epoch, " + + "initial_admission_request_id, request_digest, expected_no_prior_pointer, " + + "expected_catalog_revision, canonical_target_namespace, canonical_tenant_id, " + + "canonical_world_slug, canonical_game_instance_id, canonical_version_id, " + + "initial_admission_origin, expected_prior_pointer_version, canonical_request_bytes, " + + "hold_binding_digest FROM initial_admission_bind_hold "; + private static final String TRANSACTION_STATE_SQL = + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"; + + private final DSLContext dsl; + private final TransactionTemplate readTransaction; + private final TransactionTemplate writeTransaction; + private final WorldCanonicalInstanceAssociationRepository associationRepository; + private final WorldCanonicalInstanceLifecycleReadRepository lifecycleReadRepository; + + public WorldCanonicalInitialAdmissionHoldRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceAssociationRepository associationRepository, + WorldCanonicalInstanceLifecycleReadRepository lifecycleReadRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + PlatformTransactionManager manager = + Objects.requireNonNull(transactionManager, "transactionManager"); + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository"); + this.lifecycleReadRepository = + Objects.requireNonNull(lifecycleReadRepository, "lifecycleReadRepository"); + + readTransaction = new TransactionTemplate(manager); + readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readTransaction.setReadOnly(true); + + writeTransaction = new TransactionTemplate(manager); + writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Acquires one immutable hold after locking and proving the exact current ACTIVE lifecycle row. + * Exact retries return the original hold identity; changed request bindings fail closed. + */ + public HoldIdentity acquire( + Request request, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleSelector) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(lifecycleSelector, "lifecycleSelector"); + requireNoAmbientTransaction("World canonical initial-admission hold acquisition"); + requireSelectorMatchesRequest(request, lifecycleSelector); + + return writeTransaction.execute( + status -> { + requireWritableReadCommittedTransaction(); + WorldCanonicalInstanceLifecycleEvidence lifecycle = + lifecycleReadRepository + .readForActivationInOwnerTransaction(lifecycleSelector) + .orElseThrow( + () -> + new HoldConflictException( + "Canonical World initial-admission lifecycle selector is not materialized")); + if (!lifecycleSelector.equals(lifecycle.request()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != request.activeLifecycleEpoch()) { + throw new HoldConflictException( + "Canonical World initial-admission target is not the exact requested ACTIVE epoch"); + } + + WorldCanonicalInstanceAssociation association = + associationRepository + .readOwnerAssociationInActivationTransaction(request.canonicalGameInstanceId()) + .orElseThrow( + () -> + new HoldConflictException( + "Canonical World initial-admission association is missing")); + requireAssociationMatchesRequest(request, association); + requireSelectorMatchesAssociation(lifecycleSelector, association); + WorldCanonicalInstanceAssociation.WorldPrepareFields privateKeys = + association.worldPrepareFields(); + Record existing = readByOwnerRequest(privateKeys.privateTenantKey(), request); + if (existing != null) { + return verifyStoredIdentity(existing, request, association); + } + + HoldIdentity allocated = new HoldIdentity(request, UUID.randomUUID(), UUID.randomUUID()); + int inserted = insert(request, privateKeys, allocated); + + Record stored = readByOwnerRequest(privateKeys.privateTenantKey(), request); + if (stored == null) { + throw new HoldConflictException( + "Canonical World initial-admission hold insert did not produce exact request readback"); + } + HoldIdentity readback = verifyStoredIdentity(stored, request, association); + if (inserted == 1 + && !Arrays.equals(readback.canonicalBytes(), allocated.canonicalBytes())) { + throw new InvalidHoldIdentityException( + "Canonical World initial-admission hold readback changed its newly allocated identity"); + } + return readback; + }); + } + + /** + * Reads immutable acquisition identity from an independent read-only owner snapshot. A present + * result is historical identity only, not current lifecycle or admission proof. + */ + public Optional readIdentity(Request request) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction("World canonical initial-admission hold identity read"); + return Optional.ofNullable( + readTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + Optional maybeAssociation = + associationRepository.readOwnerAssociationInOwnerTransaction( + request.canonicalGameInstanceId()); + if (maybeAssociation.isEmpty()) return null; + WorldCanonicalInstanceAssociation association = maybeAssociation.orElseThrow(); + requireAssociationMatchesRequest(request, association); + Record row = + readByOwnerRequest(association.worldPrepareFields().privateTenantKey(), request); + return row == null ? null : verifyStoredIdentity(row, request, association); + })); + } + + private int insert( + Request request, + WorldCanonicalInstanceAssociation.WorldPrepareFields privateKeys, + HoldIdentity allocated) { + boolean noPriorPointer = + request.initialAdmissionOrigin() == InitialAdmissionOrigin.NO_PRIOR_POINTER; + int inserted = + dsl.execute( + "INSERT INTO initial_admission_bind_hold (" + + "hold_id, hold_fence, tenant_id, realm_uuid, playable_state_namespace_uuid, " + + "playable_state_scope, game_instance_id, version_id, active_lifecycle_epoch, " + + "initial_admission_request_id, request_digest, expected_no_prior_pointer, " + + "expected_catalog_revision, status, diagnostic_expires_at, created_at, updated_at, " + + "row_version, canonical_target_namespace, canonical_tenant_id, canonical_world_slug, " + + "canonical_game_instance_id, canonical_version_id, initial_admission_origin, " + + "expected_prior_pointer_version, canonical_request_bytes, hold_binding_digest) " + + "VALUES (?::uuid, ?::uuid, ?, ?::uuid, ?::uuid, ?, ?, ?, ?, ?, ?, ?, ?, " + + "'PENDING', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 0, ?, ?::uuid, " + + "?, ?::uuid, ?::uuid, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + allocated.holdId(), + allocated.holdFence(), + privateKeys.privateTenantKey(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + privateKeys.privateGameInstanceKey(), + privateKeys.localVersionKey(), + request.activeLifecycleEpoch(), + request.initialAdmissionRequestId(), + request.initialAdmissionRequestDigest(), + noPriorPointer, + request.expectedCatalogRevision(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + request.initialAdmissionOrigin().name(), + request.expectedPriorPointerVersion(), + allocated.canonicalRequestBytes(), + allocated.holdBindingDigest()); + if (inserted < 0 || inserted > 1) { + throw new InvalidHoldIdentityException( + "Canonical World initial-admission hold insert returned an invalid row count"); + } + return inserted; + } + + private Record readByOwnerRequest(long privateTenantKey, Request request) { + return dsl.fetchOne( + HOLD_SELECT + "WHERE tenant_id = ? AND initial_admission_request_id = ?", + privateTenantKey, + request.initialAdmissionRequestId()); + } + + private HoldIdentity verifyStoredIdentity( + Record row, Request expected, WorldCanonicalInstanceAssociation association) { + try { + if (!associationMatchesRequest(expected, association)) { + throw new InvalidHoldIdentityException( + "Canonical World hold request differs from its persisted owner association"); + } + byte[] requestBytes = required(row, "canonical_request_bytes", byte[].class); + String bindingDigest = required(row, "hold_binding_digest", String.class); + if (requestBytes == null || bindingDigest == null) { + throw new InvalidHoldIdentityException( + "Legacy untyped World initial-admission hold cannot prove canonical identity"); + } + Request storedRequest = Request.fromStored(requestBytes); + if (!Arrays.equals(requestBytes, expected.canonicalRequestBytes()) + || !storedRequest.equals(expected) + || !storedRequest.holdBindingDigest().equals(bindingDigest)) { + throw new HoldConflictException( + "Canonical World initial-admission request identity was reused with changed bindings"); + } + + var privateKeys = association.worldPrepareFields(); + if (required(row, "tenant_id", Long.class) != privateKeys.privateTenantKey() + || required(row, "game_instance_id", Long.class) != privateKeys.privateGameInstanceKey() + || required(row, "version_id", Long.class) != privateKeys.localVersionKey() + || !required(row, "realm_uuid", UUID.class).equals(expected.realmId()) + || !required(row, "playable_state_namespace_uuid", UUID.class) + .equals(expected.playableStateNamespaceId()) + || !required(row, "playable_state_scope", String.class) + .equals(expected.playableStateScope()) + || required(row, "active_lifecycle_epoch", Long.class) != expected.activeLifecycleEpoch() + || !required(row, "initial_admission_request_id", String.class) + .equals(expected.initialAdmissionRequestId()) + || !required(row, "request_digest", String.class) + .equals(expected.initialAdmissionRequestDigest()) + || required(row, "expected_no_prior_pointer", Boolean.class) + != (expected.initialAdmissionOrigin() == InitialAdmissionOrigin.NO_PRIOR_POINTER) + || required(row, "expected_catalog_revision", Long.class) + != expected.expectedCatalogRevision() + || !required(row, "canonical_target_namespace", String.class) + .equals(expected.targetNamespace()) + || !required(row, "canonical_tenant_id", UUID.class).equals(expected.canonicalTenantId()) + || !required(row, "canonical_world_slug", String.class).equals(expected.worldSlug()) + || !required(row, "canonical_game_instance_id", UUID.class) + .equals(expected.canonicalGameInstanceId()) + || !required(row, "canonical_version_id", UUID.class) + .equals(expected.canonicalVersionId()) + || !required(row, "initial_admission_origin", String.class) + .equals(expected.initialAdmissionOrigin().name()) + || !Objects.equals( + row.get("expected_prior_pointer_version", Long.class), + expected.expectedPriorPointerVersion())) { + throw new InvalidHoldIdentityException( + "Persisted canonical World initial-admission hold differs from its request or private association"); + } + + HoldIdentity identity = + new HoldIdentity( + storedRequest, + required(row, "hold_id", UUID.class), + required(row, "hold_fence", UUID.class)); + if (!identity.holdBindingDigest().equals(bindingDigest)) { + throw new InvalidHoldIdentityException( + "Persisted canonical World initial-admission hold digest is inconsistent"); + } + return identity; + } catch (InvalidHoldIdentityException | HoldConflictException invalid) { + throw invalid; + } catch (RuntimeException invalid) { + throw new InvalidHoldIdentityException( + "Persisted canonical World initial-admission hold identity is incomplete or invalid", + invalid); + } + } + + private static void requireSelectorMatchesRequest( + Request request, WorldCanonicalInstanceLifecycleEvidence.Request selector) { + if (!selector.targetNamespace().equals(request.targetNamespace()) + || !selector.canonicalTenantId().equals(request.canonicalTenantId()) + || !selector.worldSlug().equals(request.worldSlug()) + || !selector.playableStateNamespaceId().equals(request.playableStateNamespaceId()) + || !selector.playableStateScope().equals(request.playableStateScope()) + || !selector.canonicalGameInstanceId().equals(request.canonicalGameInstanceId()) + || !selector.canonicalVersionId().equals(request.canonicalVersionId()) + || !selector.publicProduction()) { + throw new HoldConflictException( + "Canonical World lifecycle selector differs from the complete hold target scope"); + } + } + + private static void requireSelectorMatchesAssociation( + WorldCanonicalInstanceLifecycleEvidence.Request selector, + WorldCanonicalInstanceAssociation association) { + var identity = association.identity(); + if (!selector.targetNamespace().equals(identity.targetNamespace()) + || !selector.canonicalTenantId().equals(identity.canonicalTenantId()) + || !selector.worldSlug().equals(identity.worldSlug()) + || !selector.playableStateNamespaceId().equals(identity.playableStateNamespaceId()) + || !selector.playableStateScope().equals(identity.playableStateScope()) + || !selector.canonicalGameInstanceId().equals(identity.canonicalGameInstanceId()) + || !selector.controlPlaneRequestId().equals(identity.controlPlaneRequestId()) + || !selector.canonicalVersionId().equals(association.canonicalVersionId())) { + throw new HoldConflictException( + "Canonical World lifecycle selector differs from its persisted association"); + } + } + + private static void requireAssociationMatchesRequest( + Request request, WorldCanonicalInstanceAssociation association) { + if (!associationMatchesRequest(request, association)) { + throw new HoldConflictException( + "Canonical World initial-admission request differs from its persisted association"); + } + } + + private static boolean associationMatchesRequest( + Request request, WorldCanonicalInstanceAssociation association) { + var identity = association.identity(); + return request.targetNamespace().equals(identity.targetNamespace()) + && request.canonicalTenantId().equals(identity.canonicalTenantId()) + && request.worldSlug().equals(identity.worldSlug()) + && request.playableStateNamespaceId().equals(identity.playableStateNamespaceId()) + && request.playableStateScope().equals(identity.playableStateScope()) + && request.canonicalGameInstanceId().equals(identity.canonicalGameInstanceId()) + && request.canonicalVersionId().equals(association.canonicalVersionId()); + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Canonical World initial-admission acquisition requires a writable READ COMMITTED transaction"); + } + Record state = transactionState(); + if (!"read committed".equals(required(state, "isolation", String.class)) + || !"off".equals(required(state, "read_only", String.class))) { + throw new IllegalStateException( + "Canonical World initial-admission acquisition requires a writable READ COMMITTED transaction"); + } + } + + private void requireReadOnlyRepeatableReadTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Canonical World initial-admission identity read requires read-only REPEATABLE READ"); + } + Record state = transactionState(); + if (!"repeatable read".equals(required(state, "isolation", String.class)) + || !"on".equals(required(state, "read_only", String.class))) { + throw new IllegalStateException( + "Canonical World initial-admission identity read requires read-only REPEATABLE READ"); + } + } + + private Record transactionState() { + return Objects.requireNonNull( + dsl.fetchOne(TRANSACTION_STATE_SQL), "World transaction state query returned no row"); + } + + private static void requireNoAmbientTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException(label + " must not join an ambient transaction"); + } + } + + private static T required(Record row, String column, Class type) { + return Objects.requireNonNull(row.get(column, type), "Persisted " + column + " is null"); + } + + public static final class HoldConflictException extends IllegalStateException { + public HoldConflictException(String message) { + super(message); + } + } + + public static final class InvalidHoldIdentityException extends IllegalStateException { + public InvalidHoldIdentityException(String message) { + super(message); + } + + public InvalidHoldIdentityException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldTerminalGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldTerminalGrpcService.java new file mode 100644 index 0000000000..fe9783255e --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldTerminalGrpcService.java @@ -0,0 +1,200 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.ByteString; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.worldmanagement.v1.FinalizeCanonicalInitialAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.FinalizeCanonicalInitialAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldTerminalServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicitly gated transport adapter for terminalizing an exact canonical initial-admission hold. + */ +public final class WorldCanonicalInitialAdmissionHoldTerminalGrpcService + extends WorldCanonicalInitialAdmissionHoldTerminalServiceGrpc + .WorldCanonicalInitialAdmissionHoldTerminalServiceImplBase { + private final WorldCanonicalInitialAdmissionHoldFinalizationService finalizationService; + private final String trustedNamespace; + + public WorldCanonicalInitialAdmissionHoldTerminalGrpcService( + WorldCanonicalInitialAdmissionHoldFinalizationService finalizationService, + @Value("${firemud.grpc.workload-namespace:}") String trustedNamespace) { + this.finalizationService = Objects.requireNonNull(finalizationService, "finalizationService"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void finalizeCanonicalInitialAdmissionHold( + FinalizeCanonicalInitialAdmissionHoldRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameSessionPeer(responseObserver)) return; + if (!requireIndependentOwnerOperation(responseObserver)) return; + + HoldIdentity identity; + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome; + try { + ParsedRequest parsed = parseRequest(request); + identity = parsed.identity(); + outcome = parsed.outcome(); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A complete canonical hold identity and terminal outcome are required"); + return; + } + if (!trustedNamespace.equals(identity.request().targetNamespace())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World hold namespace must match the authenticated peer"); + return; + } + + GameSessionCanonicalInitialAdmissionOwnerProof proof; + try { + // Only the caller's exact hold selection and terminal outcome cross this boundary. Owner + // proof is independently obtained and held by the World finalization service. + proof = finalizationService.finalizeHold(identity, outcome); + } catch (WorldCanonicalInitialAdmissionHoldFinalizationService.FinalizationDeniedException + | WorldCanonicalInitialAdmissionHoldFinalizationRepository.FinalizationDeniedException + denied) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Authenticated Game Session terminal owner proof is unavailable or does not match"); + return; + } catch (TransientDataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Canonical World hold storage is temporarily unavailable"); + return; + } catch (DataAccessException storageFailure) { + fail(responseObserver, Status.INTERNAL, "Canonical World hold storage failed"); + return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.INTERNAL, "Canonical World hold finalization failed"); + return; + } + + byte[] proofBytes; + try { + proofBytes = requireExactProof(identity, outcome, proof); + } catch (RuntimeException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World hold owner returned a substituted or incomplete terminal proof"); + return; + } + responseObserver.onNext( + FinalizeCanonicalInitialAdmissionHoldResponse.newBuilder() + .setOwnerProofBytes(ByteString.copyFrom(proofBytes)) + .build()); + responseObserver.onCompleted(); + } + + private static ParsedRequest parseRequest(FinalizeCanonicalInitialAdmissionHoldRequest request) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed terminal request is required"); + } + byte[] bytes = request.getHoldIdentityBytes().toByteArray(); + HoldIdentity identity = WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(bytes); + if (!Arrays.equals(bytes, identity.canonicalBytes())) { + throw new IllegalArgumentException("Hold identity bytes are not canonical"); + } + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome = + switch (request.getExpectedOutcome()) { + case COMMITTED -> GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED; + case ABORTED -> GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED; + case EXPECTED_OUTCOME_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("A terminal expected outcome is required"); + }; + return new ParsedRequest(identity, outcome); + } + + private static byte[] requireExactProof( + HoldIdentity expectedIdentity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome expectedOutcome, + GameSessionCanonicalInitialAdmissionOwnerProof actual) { + if (actual == null + || !expectedIdentity.equals(actual.holdIdentity()) + || expectedOutcome != actual.outcome() + || !Arrays.equals( + expectedIdentity.canonicalBytes(), actual.holdIdentity().canonicalBytes())) { + throw new IllegalStateException("Game Session terminal proof differs from the request"); + } + if (expectedOutcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + long expectedPointerVersion = + switch (expectedIdentity.request().initialAdmissionOrigin()) { + case NO_PRIOR_POINTER -> 1L; + case EXPECT_CLOSED -> + Math.addExact(expectedIdentity.request().expectedPriorPointerVersion(), 1L); + }; + if (!Long.valueOf(expectedPointerVersion).equals(actual.committedPointerVersion()) + || actual.positiveDurableAbort()) { + throw new IllegalStateException("Committed Game Session proof has noncanonical semantics"); + } + } else if (!actual.positiveDurableAbort() + || actual.committedPointerVersion() != null + || actual.auditEventId() != null) { + throw new IllegalStateException("Aborted Game Session proof lacks positive durable fencing"); + } + byte[] bytes = GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(actual); + var decoded = GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored(bytes); + if (!expectedIdentity.equals(decoded.holdIdentity()) || decoded.outcome() != expectedOutcome) { + throw new IllegalStateException("Game Session terminal proof failed canonical round-trip"); + } + return bytes; + } + + private boolean requireAuthenticatedGameSessionPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-session-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Only the verified same-namespace Game Session workload without end-user context is allowed"); + return false; + } + + private static boolean requireIndependentOwnerOperation(StreamObserver responseObserver) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + && !TransactionSynchronizationManager.isSynchronizationActive()) { + return true; + } + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World hold finalization requires an independent owner transaction"); + return false; + } + + private static void fail(StreamObserver responseObserver, Status status, String description) { + responseObserver.onError(status.withDescription(description).asRuntimeException()); + } + + private record ParsedRequest( + HoldIdentity identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome) {} +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java new file mode 100644 index 0000000000..b2a02cf38e --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java @@ -0,0 +1,462 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * World-local initial actor placement storage. This repository has no transport registration and + * its positive write result is not authenticated Entity assignment or gameplay readiness. + */ +public final class WorldCanonicalInitialPlayerLocationRepository { + private final DSLContext dsl; + private final TransactionTemplate writeTransaction; + private final WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository; + private final WorldCanonicalInstanceAssociationRepository associationRepository; + private final WorldCanonicalInitialAdmissionHoldFinalizationRepository holdRepository; + + public WorldCanonicalInitialPlayerLocationRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository, + WorldCanonicalInstanceAssociationRepository associationRepository, + WorldCanonicalInitialAdmissionHoldFinalizationRepository holdRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.lifecycleRepository = Objects.requireNonNull(lifecycleRepository, "lifecycleRepository"); + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository"); + this.holdRepository = Objects.requireNonNull(holdRepository, "holdRepository"); + writeTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Rechecks current exact lifecycle, canonical association, and committed initial hold while the + * World row is locked, then stores the first placement and immutable operation result atomically. + * The caller must hold an operation-specific current-authority verifier through this commit. + */ + public WorldCanonicalInitialPlayerLocation.Result place( + WorldCanonicalInitialPlayerLocation.Request request, + WorldCanonicalInitialPlayerLocationService.HeldPlacementAuthority authority) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(authority, "authority"); + requireNoActiveTransaction(); + return writeTransaction.execute( + status -> { + requireWritableTransaction(); + authority.requireHeld(); + WorldCanonicalInstanceLifecycleEvidence current = + lifecycleRepository + .readForActivationInOwnerTransaction(request.activeLifecycleEvidence().request()) + .orElseThrow( + () -> denied("exact canonical World lifecycle association is missing")); + if (!"ACTIVE".equals(current.lifecycleStatus()) + || !Arrays.equals( + request.normalizedLifecycleEvidenceBytes(), + WorldCanonicalInitialPlayerLocation.normalizedLifecycleEvidenceBytes( + current.canonicalBytes()))) { + throw denied( + "current ACTIVE lifecycle evidence differs from the complete request proof"); + } + + WorldCanonicalInstanceAssociation association = + associationRepository + .readOwnerAssociationInActivationTransaction(request.canonicalGameInstanceId()) + .orElseThrow(() -> denied("exact canonical World association is missing")); + requireAssociation(request, current, association); + GameSessionCanonicalInitialAdmissionOwnerProof hold = + holdRepository + .readCommittedInOwnerTransaction(request.initialAdmissionHoldId()) + .orElseThrow(() -> denied("initial-admission hold is missing")); + requireCommittedCanonicalHold(request, current, association, hold); + + Optional prior = findOperation(request); + if (prior.isPresent()) { + StoredOperation stored = prior.orElseThrow(); + if (!request.requestDigest().equals(stored.requestDigest()) + || !Arrays.equals(request.canonicalRequestBytes(), stored.requestBytes()) + || !Arrays.equals( + request.normalizedLifecycleEvidenceBytes(), + WorldCanonicalInitialPlayerLocation.normalizedLifecycleEvidenceBytes( + stored.originalLifecycleEvidenceBytes()))) { + throw conflict("initial-location operation identity was reused with changed input"); + } + var result = + WorldCanonicalInitialPlayerLocation.Result.fromStored( + request, stored.resultBytes()); + if (result.outcome() == WorldCanonicalInitialPlayerLocation.Outcome.APPLIED) { + List locations = findExistingLocations(request); + if (locations.size() != 1 + || !sameInitialPlacement(request, current, locations.get(0)) + || !result.startLocation().equals(current.startLocation()) + || !Objects.equals( + result.runtimeRoomInstanceId(), current.runtimeRoomInstanceId())) { + throw denied("retained APPLIED result has no exact current immutable location row"); + } + } + return result; + } + + List existingLocations = findExistingLocations(request); + boolean splitIdentityConflict = existingLocations.size() > 1; + Record existing = existingLocations.size() == 1 ? existingLocations.get(0) : null; + boolean samePlacement = + existing != null && sameInitialPlacement(request, current, existing); + var result = + splitIdentityConflict + ? WorldCanonicalInitialPlayerLocation.Result.conflict( + request, "CHARACTER_AND_ASSIGNMENT_IDENTIFY_DIFFERENT_PLACEMENTS") + : samePlacement + ? WorldCanonicalInitialPlayerLocation.Result.applied( + request, current.startLocation(), current.runtimeRoomInstanceId()) + : existing == null + ? WorldCanonicalInitialPlayerLocation.Result.applied( + request, current.startLocation(), current.runtimeRoomInstanceId()) + : WorldCanonicalInitialPlayerLocation.Result.conflict( + request, "INITIAL_LOCATION_ALREADY_ASSIGNED"); + + insertOperation(request, association.worldInstanceId(), result); + if (result.outcome() == WorldCanonicalInitialPlayerLocation.Outcome.APPLIED + && existing == null) { + insertLocation(request, current, association.worldInstanceId()); + } + authority.requireHeld(); + return result; + }); + } + + void requireAssociation( + WorldCanonicalInitialPlayerLocation.Request request, + WorldCanonicalInstanceLifecycleEvidence current, + WorldCanonicalInstanceAssociation association) { + var identity = association.identity(); + var lifecycle = current.request(); + if (!request.canonicalGameInstanceId().equals(identity.canonicalGameInstanceId()) + || !request.canonicalTenantId().equals(identity.canonicalTenantId()) + || !request.worldSlug().equals(identity.worldSlug()) + || !request.playableStateNamespaceId().equals(identity.playableStateNamespaceId()) + || !request.playableStateScope().equals(identity.playableStateScope()) + || !request.canonicalTenantId().equals(lifecycle.canonicalTenantId()) + || !request.worldSlug().equals(lifecycle.worldSlug()) + || !request.canonicalGameInstanceId().equals(lifecycle.canonicalGameInstanceId()) + || !request.playableStateNamespaceId().equals(lifecycle.playableStateNamespaceId()) + || !request.playableStateScope().equals(lifecycle.playableStateScope()) + || !request.canonicalTenantId().equals(current.startLocation().tenantId()) + || !lifecycle.canonicalVersionId().equals(current.startLocation().versionId())) { + throw denied( + "canonical placement scope differs from the exact World association or ROOM selector"); + } + } + + static void requireCommittedCanonicalHold( + WorldCanonicalInitialPlayerLocation.Request request, + WorldCanonicalInstanceLifecycleEvidence current, + WorldCanonicalInstanceAssociation association, + GameSessionCanonicalInitialAdmissionOwnerProof proof) { + var identity = proof.holdIdentity(); + var hold = identity.request(); + var lifecycle = current.request(); + long expectedPointerVersion = + hold.initialAdmissionOrigin() + == WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER + ? 1L + : Math.addExact(hold.expectedPriorPointerVersion(), 1L); + if (proof.outcome() != GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED + || !request.initialAdmissionOrigin().name().equals(hold.initialAdmissionOrigin().name()) + || !request.initialAdmissionHoldId().equals(identity.holdId()) + || !request.initialAdmissionHoldFence().equals(identity.holdFence()) + || !lifecycle.targetNamespace().equals(hold.targetNamespace()) + || !request.canonicalTenantId().equals(hold.canonicalTenantId()) + || !request.worldSlug().equals(hold.worldSlug()) + || !request.canonicalGameInstanceId().equals(hold.canonicalGameInstanceId()) + || !lifecycle.canonicalVersionId().equals(hold.canonicalVersionId()) + || !request.realmId().equals(hold.realmId()) + || !request.playableStateNamespaceId().equals(hold.playableStateNamespaceId()) + || !request.playableStateScope().equals(hold.playableStateScope()) + || !request.initialAdmissionRequestId().equals(hold.initialAdmissionRequestId()) + || !request.initialAdmissionRequestDigest().equals(hold.initialAdmissionRequestDigest()) + || hold.expectedCatalogRevision() != request.catalogRevision() + || !request.initialAdmissionOwnerProofId().equals(hold.initialAdmissionRequestId()) + || !request.initialAdmissionOwnerProofDigest().equals(proof.proofDigest().substring(7)) + || !request.pointerAuditId().equals(Long.toString(proof.auditEventId())) + || !Objects.equals(request.pointerVersion(), proof.committedPointerVersion()) + || hold.activeLifecycleEpoch() != current.lifecycleEpoch() + || !association.identity().canonicalTenantId().equals(hold.canonicalTenantId()) + || !association.identity().canonicalGameInstanceId().equals(hold.canonicalGameInstanceId()) + || proof.committedPointerVersion() != expectedPointerVersion) { + throw denied("initial placement requires the exact typed committed hold and pointer outcome"); + } + } + + private Optional findOperation( + WorldCanonicalInitialPlayerLocation.Request request) { + Record row = + dsl.fetchOne( + "SELECT request_digest, request_bytes, original_lifecycle_evidence_bytes, result_bytes FROM " + + "world_canonical_initial_player_location_operation " + + "WHERE operation_id = ?", + request.operationId()); + if (row == null) return Optional.empty(); + return Optional.of( + new StoredOperation( + row.get("request_digest", String.class), + row.get("request_bytes", byte[].class), + row.get("original_lifecycle_evidence_bytes", byte[].class), + row.get("result_bytes", byte[].class))); + } + + private List findExistingLocations(WorldCanonicalInitialPlayerLocation.Request request) { + return dsl.fetch( + "SELECT canonical_tenant_id, realm_id, world_slug, playable_state_namespace_id, " + + "playable_state_scope, canonical_account_id, character_id, entity_assignment_operation_id, " + + "entity_assignment_digest, canonical_version_id, active_lifecycle_epoch, " + + "initial_room_template_id, initial_runtime_room_instance_id, runtime_room_instance_id, initial_admission_hold_id, " + + "initial_admission_hold_fence, initial_admission_request_id, " + + "initial_admission_request_digest, catalog_revision, initial_admission_owner_proof_id, " + + "initial_admission_owner_proof_digest, pointer_audit_id, pointer_version, " + + "initial_lifecycle_evidence_bytes, initial_lifecycle_evidence_digest " + + "FROM character_location WHERE canonical_game_instance_id = ? " + + "AND playable_state_namespace_id = ? AND (character_id = ? " + + "OR entity_assignment_operation_id = ?) FOR UPDATE", + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.characterId(), + request.entityAssignmentOperationId()); + } + + List findExistingLocationsForCurrentRead( + WorldCanonicalInitialPlayerLocation.Request request) { + return dsl.fetch( + "SELECT canonical_tenant_id, realm_id, world_slug, playable_state_namespace_id, " + + "playable_state_scope, canonical_game_instance_id, world_instance_id, canonical_account_id, character_id, " + + "entity_assignment_operation_id, entity_assignment_digest, canonical_version_id, " + + "active_lifecycle_epoch, initial_room_template_id, initial_runtime_room_instance_id, " + + "runtime_room_instance_id, initial_admission_hold_id, initial_admission_hold_fence, " + + "initial_admission_request_id, initial_admission_request_digest, catalog_revision, " + + "initial_admission_owner_proof_id, initial_admission_owner_proof_digest, pointer_audit_id, " + + "pointer_version, initial_location_operation_id, initial_location_request_digest, " + + "initial_lifecycle_evidence_bytes, initial_lifecycle_evidence_digest " + + "FROM character_location WHERE canonical_game_instance_id = ? " + + "AND playable_state_namespace_id = ? AND (character_id = ? " + + "OR entity_assignment_operation_id = ?)", + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.characterId(), + request.entityAssignmentOperationId()); + } + + static boolean sameInitialPlacement( + WorldCanonicalInitialPlayerLocation.Request request, + WorldCanonicalInstanceLifecycleEvidence current, + Record existing) { + return request.canonicalTenantId().equals(existing.get("canonical_tenant_id", UUID.class)) + && request.realmId().equals(existing.get("realm_id", UUID.class)) + && request.worldSlug().equals(existing.get("world_slug", String.class)) + && request + .playableStateNamespaceId() + .equals(existing.get("playable_state_namespace_id", UUID.class)) + && request.playableStateScope().equals(existing.get("playable_state_scope", String.class)) + && request.canonicalAccountId().equals(existing.get("canonical_account_id", UUID.class)) + && request.characterId().equals(existing.get("character_id", UUID.class)) + && request + .entityAssignmentOperationId() + .equals(existing.get("entity_assignment_operation_id", UUID.class)) + && request + .entityAssignmentDigest() + .equals(existing.get("entity_assignment_digest", String.class)) + && current + .request() + .canonicalVersionId() + .equals(existing.get("canonical_version_id", UUID.class)) + && current.lifecycleEpoch() == existing.get("active_lifecycle_epoch", Long.class) + && current + .startLocation() + .roomTemplateId() + .equals(existing.get("initial_room_template_id", UUID.class)) + && current.runtimeRoomInstanceId() + == existing.get("initial_runtime_room_instance_id", Long.class) + && current.runtimeRoomInstanceId() == existing.get("runtime_room_instance_id", Long.class) + && request + .initialAdmissionHoldId() + .equals(existing.get("initial_admission_hold_id", UUID.class)) + && request + .initialAdmissionHoldFence() + .equals(existing.get("initial_admission_hold_fence", UUID.class)) + && request + .initialAdmissionRequestId() + .equals(existing.get("initial_admission_request_id", String.class)) + && request + .initialAdmissionRequestDigest() + .equals(existing.get("initial_admission_request_digest", String.class)) + && request.catalogRevision() == existing.get("catalog_revision", Long.class) + && request + .initialAdmissionOwnerProofId() + .equals(existing.get("initial_admission_owner_proof_id", String.class)) + && request + .initialAdmissionOwnerProofDigest() + .equals(existing.get("initial_admission_owner_proof_digest", String.class)) + && request.pointerAuditId().equals(existing.get("pointer_audit_id", String.class)) + && request.pointerVersion() == existing.get("pointer_version", Long.class) + && Objects.equals( + existing.get("initial_lifecycle_evidence_digest", String.class), + prefixedDigest(existing.get("initial_lifecycle_evidence_bytes", byte[].class))) + && Arrays.equals( + request.normalizedLifecycleEvidenceBytes(), + WorldCanonicalInitialPlayerLocation.normalizedLifecycleEvidenceBytes( + existing.get("initial_lifecycle_evidence_bytes", byte[].class))); + } + + private void insertOperation( + WorldCanonicalInitialPlayerLocation.Request request, + long worldInstanceId, + WorldCanonicalInitialPlayerLocation.Result result) { + byte[] requestBytes = request.canonicalRequestBytes(); + byte[] resultBytes = result.canonicalBytes(); + int inserted = + dsl.execute( + "INSERT INTO world_canonical_initial_player_location_operation " + + "(canonical_tenant_id, playable_state_namespace_id, canonical_game_instance_id, " + + "operation_id, world_instance_id, request_digest, request_bytes, " + + "original_lifecycle_evidence_bytes, outcome, conflict_code, result_bytes, result_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + request.canonicalTenantId(), + request.playableStateNamespaceId(), + request.canonicalGameInstanceId(), + request.operationId(), + worldInstanceId, + request.requestDigest(), + requestBytes, + request.originalLifecycleEvidenceBytes(), + result.outcome().name(), + result.conflictCode(), + resultBytes, + prefixedDigest(resultBytes)); + if (inserted != 1) throw conflict("initial-location operation was concurrently recorded"); + } + + private void insertLocation( + WorldCanonicalInitialPlayerLocation.Request request, + WorldCanonicalInstanceLifecycleEvidence current, + long worldInstanceId) { + int inserted = + dsl.execute( + "INSERT INTO character_location " + + "(canonical_tenant_id, realm_id, world_slug, playable_state_namespace_id, " + + "playable_state_scope, canonical_game_instance_id, world_instance_id, " + + "canonical_account_id, character_id, entity_assignment_operation_id, " + + "entity_assignment_digest, canonical_version_id, active_lifecycle_epoch, " + + "initial_room_template_id, initial_runtime_room_instance_id, runtime_room_instance_id, " + + "initial_admission_hold_id, initial_admission_hold_fence, initial_admission_request_id, " + + "initial_admission_request_digest, catalog_revision, initial_admission_owner_proof_id, " + + "initial_admission_owner_proof_digest, pointer_audit_id, pointer_version, " + + "initial_location_operation_id, initial_location_request_digest, " + + "initial_lifecycle_evidence_bytes, initial_lifecycle_evidence_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT DO NOTHING", + request.canonicalTenantId(), + request.realmId(), + request.worldSlug(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + worldInstanceId, + request.canonicalAccountId(), + request.characterId(), + request.entityAssignmentOperationId(), + request.entityAssignmentDigest(), + current.request().canonicalVersionId(), + current.lifecycleEpoch(), + current.startLocation().roomTemplateId(), + current.runtimeRoomInstanceId(), + current.runtimeRoomInstanceId(), + request.initialAdmissionHoldId(), + request.initialAdmissionHoldFence(), + request.initialAdmissionRequestId(), + request.initialAdmissionRequestDigest(), + request.catalogRevision(), + request.initialAdmissionOwnerProofId(), + request.initialAdmissionOwnerProofDigest(), + request.pointerAuditId(), + request.pointerVersion(), + request.operationId(), + request.requestDigest(), + request.originalLifecycleEvidenceBytes(), + prefixedDigest(request.originalLifecycleEvidenceBytes())); + if (inserted != 1) { + throw conflict("initial character location conflicts with an existing actor assignment"); + } + } + + private static void requireNoActiveTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World initial placement must start outside an ambient transaction"); + } + } + + private void requireWritableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World initial placement requires a writable READ COMMITTED transaction"); + } + Record state = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, current_setting('transaction_read_only') AS read_only"); + if (state == null + || !"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException("World initial placement transaction has an unexpected mode"); + } + } + + static String prefixedDigest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalStateException denied(String message) { + return new IllegalStateException("INITIAL_PLAYER_LOCATION_DENIED: " + message); + } + + private static IllegalArgumentException conflict(String message) { + return new IllegalArgumentException("IDEMPOTENCY_CONFLICT: " + message); + } + + private record StoredOperation( + String requestDigest, + byte[] requestBytes, + byte[] originalLifecycleEvidenceBytes, + byte[] resultBytes) { + private StoredOperation { + requestBytes = Arrays.copyOf(requestBytes, requestBytes.length); + originalLifecycleEvidenceBytes = + Arrays.copyOf(originalLifecycleEvidenceBytes, originalLifecycleEvidenceBytes.length); + resultBytes = Arrays.copyOf(resultBytes, resultBytes.length); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationService.java new file mode 100644 index 0000000000..714bb4f4f5 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationService.java @@ -0,0 +1,76 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, default-denied World initial-placement producer. A real Entity/Account/Game Session + * authenticated producer must supply the held verifier before this local slice can write. + */ +public final class WorldCanonicalInitialPlayerLocationService { + private final WorldCanonicalInitialPlayerLocationRepository repository; + private final PlacementAuthorityVerifier verifier; + + /** Production-safe default while authenticated actor-assignment delivery is unavailable. */ + public WorldCanonicalInitialPlayerLocationService( + WorldCanonicalInitialPlayerLocationRepository repository) { + this(repository, WorldCanonicalInitialPlayerLocationService::denyByDefault); + } + + /** Explicit authority injection is intended for a genuine owner producer or isolated proof. */ + public WorldCanonicalInitialPlayerLocationService( + WorldCanonicalInitialPlayerLocationRepository repository, + PlacementAuthorityVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + } + + /** + * Requires current actor/Account/admission authority on every attempt, including exact retries; + * an immutable historical placement receipt alone never authorizes the caller. + */ + public WorldCanonicalInitialPlayerLocation.Result place( + WorldCanonicalInitialPlayerLocation.Request request) { + Objects.requireNonNull(request, "request"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World initial placement must verify authority outside an ambient transaction"); + } + HeldPlacementAuthority held = + Objects.requireNonNull( + verifier.verifyAndHold(request), + "Initial placement verifier returned no held authority"); + try (held) { + held.requireHeld(); + WorldCanonicalInitialPlayerLocation.Result result = repository.place(request, held); + held.requireHeld(); + return result; + } + } + + private static HeldPlacementAuthority denyByDefault( + WorldCanonicalInitialPlayerLocation.Request request) { + throw new PlacementDeniedException( + "World initial placement has no authenticated current Entity assignment, Account, and Game Session authority producer"); + } + + @FunctionalInterface + public interface PlacementAuthorityVerifier { + HeldPlacementAuthority verifyAndHold(WorldCanonicalInitialPlayerLocation.Request request); + } + + /** Distinct operation-specific current-authority fence held through local commit/readback. */ + public interface HeldPlacementAuthority extends AutoCloseable { + void requireHeld(); + + @Override + void close(); + } + + public static final class PlacementDeniedException extends IllegalStateException { + public PlacementDeniedException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationGrpcService.java new file mode 100644 index 0000000000..424c943710 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationGrpcService.java @@ -0,0 +1,186 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.ByteString; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceActivationServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone authenticated canonical activation adapter; intentionally not runtime-registered. */ +public final class WorldCanonicalInstanceActivationGrpcService + extends WorldCanonicalInstanceActivationServiceGrpc + .WorldCanonicalInstanceActivationServiceImplBase { + private final WorldCanonicalInstanceActivationService activationService; + private final String trustedNamespace; + + public WorldCanonicalInstanceActivationGrpcService( + WorldCanonicalInstanceActivationService activationService, String trustedNamespace) { + this.activationService = Objects.requireNonNull(activationService, "activationService"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void activateCanonicalWorldInstance( + ActivateCanonicalWorldInstanceRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameSessionPeer(responseObserver)) return; + if (hasAmbientTransaction()) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World activation requires independent owner operations"); + return; + } + + WorldCanonicalInstanceActivation.Request activationRequest; + try { + activationRequest = parseRequest(request); + } catch (IllegalArgumentException invalid) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A complete canonical World activation request is required"); + return; + } + if (!trustedNamespace.equals(activationRequest.preparing().request().targetNamespace())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World activation namespace must match the authenticated peer"); + return; + } + + WorldCanonicalInstanceActivation.Result result; + try { + result = activationService.activate(activationRequest); + } catch (WorldCanonicalInstanceActivationService.ActivationDeniedException denied) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World activation authority was denied"); + return; + } catch (WorldCanonicalInstanceActivationRepository.ActivationConflictException conflict) { + fail( + responseObserver, + Status.ALREADY_EXISTS, + "Canonical World activation request conflicts with an existing operation"); + return; + } catch ( + WorldCanonicalInstanceActivationRepository.InvalidActivationEvidenceException + inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World activation evidence is inconsistent"); + return; + } catch (TransientDataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Canonical World activation storage is temporarily unavailable"); + return; + } catch (DataAccessException permanentStorageFailure) { + fail(responseObserver, Status.INTERNAL, "Canonical World activation storage failed"); + return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.INTERNAL, "Canonical World activation failed"); + return; + } + + try { + requireExactResult(activationRequest, result); + byte[] resultBytes = result.canonicalBytes(); + // This is the immutable operation result, including historical retries after later + // lifecycle movement. The caller must use the separate lifecycle-read RPC for current state. + ActivateCanonicalWorldInstanceResponse response = + ActivateCanonicalWorldInstanceResponse.newBuilder() + .setActivationRequestId(result.request().activationRequestId().toString()) + .setCanonicalResultBytes(ByteString.copyFrom(resultBytes)) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (InvalidActivationResponseException | IllegalArgumentException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World activation result does not match the requested operation"); + } + } + + private static WorldCanonicalInstanceActivation.Request parseRequest( + ActivateCanonicalWorldInstanceRequest request) { + Objects.requireNonNull(request, "request"); + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Canonical World activation request has unknown fields"); + } + String activationIdText = request.getActivationRequestId(); + UUID activationId; + try { + activationId = UUID.fromString(activationIdText); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Activation request ID must be a canonical UUID", invalid); + } + if (!activationId.toString().equals(activationIdText)) { + throw new IllegalArgumentException("Activation request ID must be a canonical UUID"); + } + byte[] preparingBytes = request.getPreparingLifecycleEvidenceBytes().toByteArray(); + if (preparingBytes.length == 0) { + throw new IllegalArgumentException("Complete PREPARING lifecycle evidence is required"); + } + WorldCanonicalInstanceLifecycleEvidence preparing = + WorldCanonicalInstanceLifecycleEvidence.fromStored(preparingBytes); + return new WorldCanonicalInstanceActivation.Request(activationId, preparing); + } + + private static void requireExactResult( + WorldCanonicalInstanceActivation.Request activationRequest, + WorldCanonicalInstanceActivation.Result result) { + if (result == null + || !activationRequest.activationRequestId().equals(result.request().activationRequestId()) + || !activationRequest.requestDigest().equals(result.request().requestDigest()) + || !Arrays.equals( + activationRequest.canonicalRequestBytes(), result.request().canonicalRequestBytes())) { + throw new InvalidActivationResponseException(); + } + } + + private boolean requireAuthenticatedGameSessionPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-session-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Only the verified same-namespace Game Session workload without end-user context is allowed"); + return false; + } + + private static boolean hasAmbientTransaction() { + return TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive(); + } + + private static void fail(StreamObserver responseObserver, Status status, String description) { + responseObserver.onError(status.withDescription(description).asRuntimeException()); + } + + private static final class InvalidActivationResponseException extends IllegalStateException {} +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java new file mode 100644 index 0000000000..74d5c02b8a --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java @@ -0,0 +1,296 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Owner-local immutable activation ledger and exact World lifecycle CAS. */ +public final class WorldCanonicalInstanceActivationRepository { + private final DSLContext dsl; + private final TransactionTemplate readTransaction; + private final TransactionTemplate writeTransaction; + private final WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository; + + public WorldCanonicalInstanceActivationRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.lifecycleRepository = Objects.requireNonNull(lifecycleRepository, "lifecycleRepository"); + PlatformTransactionManager manager = + Objects.requireNonNull(transactionManager, "transactionManager"); + readTransaction = new TransactionTemplate(manager); + readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readTransaction.setReadOnly(true); + writeTransaction = new TransactionTemplate(manager); + writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Independently reads an immutable result; exact retries intentionally do not require current + * authority. + */ + public Optional readResult( + WorldCanonicalInstanceActivation.Request request) { + Objects.requireNonNull(request, "request"); + requireNoActiveTransaction("World canonical activation result read"); + return Optional.ofNullable( + readTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + return readResultInCurrentTransaction(request).orElse(null); + })); + } + + /** + * Commits one exact PREPARING-to-ACTIVE CAS or stores a terminal stale-precondition result. The + * caller has already verified remote/current authorities outside this transaction. + */ + public WorldCanonicalInstanceActivation.Result activate( + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceActivationService.HeldActivationAuthority held) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(held, "held"); + requireNoActiveTransaction("World canonical activation"); + return writeTransaction.execute( + status -> { + requireWritableTransaction(); + held.requireHeld(); + WorldCanonicalInstanceLifecycleEvidence current = + lifecycleRepository + .readForActivationInOwnerTransaction(request.preparing().request()) + .orElseThrow( + () -> + new ActivationConflictException( + "Canonical World activation no longer has its exact materialized owner association")); + Optional existing = + readResultInCurrentTransaction(request); + if (existing.isPresent()) return existing.orElseThrow(); + + boolean exactPrecondition = + "PREPARING".equals(current.lifecycleStatus()) + && current.lifecycleEpoch() == request.expectedLifecycleEpoch() + && current.rowVersion() == request.expectedRowVersion() + && Arrays.equals( + request.canonicalRequestBytes(), + new WorldCanonicalInstanceActivation.Request( + request.activationRequestId(), current) + .canonicalRequestBytes()); + if (!exactPrecondition) { + WorldCanonicalInstanceActivation.Result aborted = + new WorldCanonicalInstanceActivation.Result( + request, + WorldCanonicalInstanceActivation.Outcome.ABORTED, + "PRECONDITION_FAILED", + current); + insertResult(request, aborted); + held.requireHeld(); + return aborted; + } + + WorldCanonicalInstanceLifecycleEvidence predicted = nextActiveEvidence(request, current); + WorldCanonicalInstanceActivation.Result committed = + new WorldCanonicalInstanceActivation.Result( + request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, predicted); + insertResult(request, committed); + held.requireHeld(); + int updated = + dsl.execute( + "UPDATE world_instance SET status='ACTIVE', lifecycle_epoch=lifecycle_epoch+1, " + + "row_version=row_version+1, updated_at=CURRENT_TIMESTAMP " + + "WHERE id=(SELECT world_instance_id FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=?) AND canonical_game_instance_id=? " + + "AND status='PREPARING' AND lifecycle_epoch=? AND row_version=?", + request.canonicalGameInstanceId(), + request.canonicalGameInstanceId(), + request.expectedLifecycleEpoch(), + request.expectedRowVersion()); + if (updated != 1) { + throw new ActivationConflictException( + "Canonical World lifecycle changed before its exact activation compare-and-set"); + } + WorldCanonicalInstanceLifecycleEvidence actual = + lifecycleRepository + .readForActivationInOwnerTransaction(request.preparing().request()) + .orElseThrow( + () -> + new InvalidActivationEvidenceException( + "Canonical World activation lost its owner readback")); + if (!Arrays.equals(predicted.canonicalBytes(), actual.canonicalBytes())) { + throw new InvalidActivationEvidenceException( + "Canonical World activation result differs from its exact committed owner readback"); + } + held.requireHeld(); + return committed; + }); + } + + private Optional readResultInCurrentTransaction( + WorldCanonicalInstanceActivation.Request request) { + Record row = + dsl.fetchOne( + "SELECT request_digest, request_bytes, result_bytes, result_digest " + + "FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + request.activationRequestId()); + if (row == null) return Optional.empty(); + byte[] requestBytes = required(row, "request_bytes", byte[].class); + String digest = required(row, "request_digest", String.class); + byte[] resultBytes = required(row, "result_bytes", byte[].class); + if (!digest.equals(request.requestDigest()) + || !Arrays.equals(requestBytes, request.canonicalRequestBytes())) { + throw new ActivationConflictException( + "Canonical World activation request ID was reused with changed immutable bindings"); + } + if (!required(row, "result_digest", String.class).equals(digest(resultBytes))) { + throw new InvalidActivationEvidenceException( + "Stored canonical World activation result digest is inconsistent"); + } + try { + WorldCanonicalInstanceActivation.Result result = + WorldCanonicalInstanceActivation.Result.fromStored(resultBytes); + if (!result.request().activationRequestId().equals(request.activationRequestId()) + || !Arrays.equals(result.request().canonicalRequestBytes(), requestBytes)) { + throw new InvalidActivationEvidenceException( + "Stored canonical World activation result differs from its exact operation identity"); + } + return Optional.of(result); + } catch (IllegalArgumentException invalid) { + throw new InvalidActivationEvidenceException( + "Stored canonical World activation result is invalid", invalid); + } + } + + private void insertResult( + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceActivation.Result result) { + byte[] resultBytes = result.canonicalBytes(); + dsl.execute( + "INSERT INTO world_canonical_instance_activation_operation " + + "(activation_request_id,request_digest,request_bytes,preparing_evidence_bytes," + + "canonical_game_instance_id,world_instance_id,expected_lifecycle_epoch,expected_row_version," + + "outcome,terminal_code,result_lifecycle_epoch,result_row_version,result_bytes,result_digest) " + + "VALUES (?,?,?,?,?,(SELECT world_instance_id FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=?),?,?,?,?,?,?,?,?)", + request.activationRequestId(), + request.requestDigest(), + request.canonicalRequestBytes(), + request.preparingEvidenceBytes(), + request.canonicalGameInstanceId(), + request.canonicalGameInstanceId(), + request.expectedLifecycleEpoch(), + request.expectedRowVersion(), + result.outcome().name(), + result.terminalCode(), + result.lifecycleEvidence().lifecycleEpoch(), + result.lifecycleEvidence().rowVersion(), + resultBytes, + digest(resultBytes)); + } + + private static WorldCanonicalInstanceLifecycleEvidence nextActiveEvidence( + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceLifecycleEvidence current) { + return new WorldCanonicalInstanceLifecycleEvidence( + request.preparing().request(), + current.launchBinding(), + current.startLocation(), + current.runtimeRoomInstanceId(), + "ACTIVE", + Math.addExact(request.expectedLifecycleEpoch(), 1L), + Math.addExact(request.expectedRowVersion(), 1L), + current.captureId(), + current.graphSha256(), + current.preparationInputDigest(), + current.operationalRegionAssignments()); + } + + private void requireReadOnlyRepeatableReadTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World activation result read requires a read-only REPEATABLE READ transaction"); + } + Record state = transactionState(); + if (!"repeatable read".equals(required(state, "isolation", String.class)) + || !"on".equals(required(state, "read_only", String.class))) { + throw new IllegalStateException( + "World activation result read requires a read-only REPEATABLE READ transaction"); + } + } + + private void requireWritableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World activation requires a writable READ COMMITTED transaction"); + } + Record state = transactionState(); + String actualIsolation = required(state, "isolation", String.class); + if (!"read committed".equals(actualIsolation) + || !"off".equals(required(state, "read_only", String.class))) { + throw new IllegalStateException( + "World activation requires a writable READ COMMITTED transaction"); + } + } + + private Record transactionState() { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " must not join an ambient transaction"); + } + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static T required(Record row, String field, Class type) { + return Objects.requireNonNull(row.get(field, type), "Persisted " + field + " is null"); + } + + public static final class ActivationConflictException extends IllegalStateException { + public ActivationConflictException(String message) { + super(message); + } + } + + public static final class InvalidActivationEvidenceException extends IllegalStateException { + public InvalidActivationEvidenceException(String message) { + super(message); + } + + public InvalidActivationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java new file mode 100644 index 0000000000..7e8b8c6932 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Default-denied, unregistered canonical World lifecycle operation. A standalone transport adapter + * does not register this operation or supply its production source/current-Account verifier. + */ +public final class WorldCanonicalInstanceActivationService { + private final WorldCanonicalInstanceActivationRepository repository; + private final ActivationAuthorityVerifier verifier; + + /** + * Production-safe default: new activations remain denied until an explicit verifier is supplied. + */ + public WorldCanonicalInstanceActivationService( + WorldCanonicalInstanceActivationRepository repository) { + this(repository, WorldCanonicalInstanceActivationService::denyByDefault); + } + + /** Constructor for an explicitly supplied owner verifier, including isolated proof fixtures. */ + public WorldCanonicalInstanceActivationService( + WorldCanonicalInstanceActivationRepository repository, ActivationAuthorityVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + } + + /** + * Replays an exact immutable prior result without rechecking current lifecycle state. A new + * operation verifies all remote/current authority outside World transactions and keeps its + * operation-specific local fence held through commit. + */ + public WorldCanonicalInstanceActivation.Result activate( + WorldCanonicalInstanceActivation.Request request) { + Objects.requireNonNull(request, "request"); + requireNoActiveTransaction(); + var prior = repository.readResult(request); + if (prior.isPresent()) return prior.orElseThrow(); + + HeldActivationAuthority held = + Objects.requireNonNull( + verifier.verifyAndHold(request), + "Canonical activation verifier returned no held operation authority"); + try (held) { + held.requireHeld(); + WorldCanonicalInstanceActivation.Result result = repository.activate(request, held); + held.requireHeld(); + return result; + } + } + + private static HeldActivationAuthority denyByDefault( + WorldCanonicalInstanceActivation.Request request) { + throw new ActivationDeniedException( + "Canonical World activation has no authenticated current source/release and Account operation-authority verifier"); + } + + private static void requireNoActiveTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical World activation must verify outside an ambient transaction"); + } + } + + @FunctionalInterface + public interface ActivationAuthorityVerifier { + HeldActivationAuthority verifyAndHold(WorldCanonicalInstanceActivation.Request request); + } + + /** Distinct, operation-specific fence; a Draft/publication fence is not activation authority. */ + public interface HeldActivationAuthority extends AutoCloseable { + void requireHeld(); + + @Override + void close(); + } + + public static final class ActivationDeniedException extends IllegalStateException { + public ActivationDeniedException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java new file mode 100644 index 0000000000..26a18707dd --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java @@ -0,0 +1,455 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** + * Owner-local immutable correlation between a claimed canonical Game Session instance and one + * insert-born World instance row. + * + *

This association is not Game Session producer authentication, released-content authority, + * lifecycle state, activation, JOIN, or admission proof. A caller must establish the authenticated + * same-namespace producer and complete canonical prepare/materialization proof independently. + */ +public record WorldCanonicalInstanceAssociation( + CanonicalIdentity identity, + long worldInstanceId, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldPrepareFields worldPrepareFields) { + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + public WorldCanonicalInstanceAssociation { + Objects.requireNonNull(identity, "identity"); + requirePositive(worldInstanceId, "worldInstanceId"); + Objects.requireNonNull(completeLaunchBinding, "completeLaunchBinding"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + Objects.requireNonNull(worldPrepareFields, "worldPrepareFields"); + if (worldInstanceId != worldPrepareFields.worldInstanceId()) { + throw new IllegalArgumentException( + "World association row id differs from its prepare fields"); + } + requireExactLaunchEvidence(identity, completeLaunchBinding, versionIdentity); + worldPrepareFields.requireMatches(identity, completeLaunchBinding, versionIdentity); + } + + public UUID canonicalVersionId() { + return completeLaunchBinding.evidence().releaseAttestation().canonicalVersionId(); + } + + public UUID launchBindingOperationId() { + return completeLaunchBinding.operationId(); + } + + public UUID versionIdentityOperationId() { + return versionIdentity.operationId(); + } + + /** + * Immutable canonical Game Session identity and owner scope, excluding transient read metadata. + */ + public record CanonicalIdentity( + UUID canonicalGameInstanceId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID playableStateNamespaceId, + String playableStateScope, + boolean publicProduction, + String controlPlaneRequestId) { + public CanonicalIdentity { + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "This association slice accepts SHARED only; ISOLATED/playtest identity requires the missing lifecycle/generation carrier"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "This association slice requires explicit public-production evidence; false or absent evidence is denied"); + } + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + } + } + + /** + * Exact caller-owned selector and expected digests for Gameplay's owner-read RPC. + * + *

The read request UUID and expected digests are transient request metadata; the repository + * validates the separate response echo and does not persist this request identity. + */ + public record GameSessionReadRequest( + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + String controlPlaneRequestId, + String launchDescriptorId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationEvidenceDigest) { + public GameSessionReadRequest { + requireNonNil(readRequestId, "readRequestId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 64); + requireDigest(expectedDescriptorRequestDigest, "expectedDescriptorRequestDigest"); + requireDigest(expectedDescriptorResultDigest, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationEvidenceDigest, "expectedReleaseAttestationEvidenceDigest"); + } + } + + /** + * Typed copy of Gameplay's owner-read response, kept separate from its request selector. + * + *

The echoed fields are checked against {@link GameSessionReadRequest}. Current status and row + * version are transient Game Session projection only; neither is frozen into the association or + * treated as World lifecycle authority. + */ + public record GameSessionReadEvidence( + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID canonicalGameInstanceId, + String controlPlaneRequestId, + String launchDescriptorId, + String descriptorRequestDigest, + String descriptorResultDigest, + String releaseAttestationEvidenceDigest, + UUID playableStateNamespaceId, + String playableStateScope, + boolean publicProduction, + String currentGameSessionStatus, + long currentGameSessionRowVersion, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation) { + public GameSessionReadEvidence { + requireNonNil(readRequestId, "readRequestId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 64); + requireDigest(descriptorRequestDigest, "descriptorRequestDigest"); + requireDigest(descriptorResultDigest, "descriptorResultDigest"); + requireDigest(releaseAttestationEvidenceDigest, "releaseAttestationEvidenceDigest"); + if (!"SHARED".equals(playableStateScope)) { + throw new IllegalArgumentException( + "This association slice accepts SHARED only; ISOLATED/playtest identity requires the missing lifecycle/generation carrier"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "This association slice requires explicit public-production evidence; false or absent evidence is denied"); + } + requireText(currentGameSessionStatus, "currentGameSessionStatus", 32); + requireNonNegative(currentGameSessionRowVersion, "currentGameSessionRowVersion"); + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(releaseAttestation, "releaseAttestation"); + descriptor.requireValid(); + new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId()) + || !descriptorRequestDigest.equals(descriptor.requestDigest()) + || !descriptorResultDigest.equals(descriptor.resultDigest()) + || !releaseAttestationEvidenceDigest.equals(releaseAttestation.evidenceDigest())) { + throw new IllegalArgumentException( + "Game Session launch-association response differs from its typed complete launch evidence"); + } + } + + public CanonicalIdentity canonicalIdentity() { + return new CanonicalIdentity( + canonicalGameInstanceId, + targetNamespace, + canonicalTenantId, + worldSlug, + playableStateNamespaceId, + playableStateScope, + publicProduction, + controlPlaneRequestId); + } + } + + /** + * Non-authorizing persistence input. The transient Game Session read correlation/status fields + * are not association identity; the exact complete binding and source/version receipts are. + */ + public record Claim( + GameSessionReadRequest gameSessionRequest, + GameSessionReadEvidence gameSessionRead, + long worldInstanceId, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + public Claim { + Objects.requireNonNull(gameSessionRequest, "gameSessionRequest"); + Objects.requireNonNull(gameSessionRead, "gameSessionRead"); + requirePositive(worldInstanceId, "worldInstanceId"); + Objects.requireNonNull(completeLaunchBinding, "completeLaunchBinding"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + requireExactReadEcho(gameSessionRequest, gameSessionRead); + CanonicalIdentity identity = gameSessionRead.canonicalIdentity(); + requireExactLaunchEvidence(identity, completeLaunchBinding, versionIdentity); + if (!gameSessionRead.descriptor().equals(completeLaunchBinding.evidence().descriptor()) + || !gameSessionRead + .releaseAttestation() + .equals(completeLaunchBinding.evidence().releaseAttestation()) + || !gameSessionRead + .launchDescriptorId() + .equals(completeLaunchBinding.descriptor().launchDescriptorId()) + || !gameSessionRead + .descriptorRequestDigest() + .equals(completeLaunchBinding.descriptor().requestDigest()) + || !gameSessionRead + .descriptorResultDigest() + .equals(completeLaunchBinding.descriptor().resultDigest()) + || !gameSessionRead + .releaseAttestationEvidenceDigest() + .equals(completeLaunchBinding.evidence().releaseAttestation().evidenceDigest())) { + throw new IllegalArgumentException( + "Game Session read projection differs from the original World V26 complete binding"); + } + } + + public UUID canonicalGameInstanceId() { + return gameSessionRead.canonicalGameInstanceId(); + } + + public CanonicalIdentity identity() { + return gameSessionRead.canonicalIdentity(); + } + + public String targetNamespace() { + return gameSessionRead.targetNamespace(); + } + + public UUID canonicalTenantId() { + return gameSessionRead.canonicalTenantId(); + } + + public String worldSlug() { + return gameSessionRead.worldSlug(); + } + + public UUID playableStateNamespaceId() { + return gameSessionRead.playableStateNamespaceId(); + } + + public String playableStateScope() { + return gameSessionRead.playableStateScope(); + } + + public String controlPlaneRequestId() { + return gameSessionRead.controlPlaneRequestId(); + } + + public String launchDescriptorId() { + return gameSessionRead.launchDescriptorId(); + } + + public String descriptorRequestDigest() { + return gameSessionRead.descriptorRequestDigest(); + } + + public String descriptorResultDigest() { + return gameSessionRead.descriptorResultDigest(); + } + + public String releaseAttestationDigest() { + return gameSessionRead.releaseAttestationEvidenceDigest(); + } + + public UUID canonicalVersionId() { + return completeLaunchBinding.evidence().releaseAttestation().canonicalVersionId(); + } + + public long localTenantKey() { + return completeLaunchBinding.sourceIntakeReceipt().localTenantKey(); + } + + public long localVersionKey() { + return versionIdentity.localVersionKey(); + } + + public UUID launchBindingOperationId() { + return completeLaunchBinding.operationId(); + } + + public UUID versionIdentityOperationId() { + return versionIdentity.operationId(); + } + } + + /** Exact immutable subset of the legacy row created by World's existing prepare owner. */ + public record WorldPrepareFields( + long worldInstanceId, + long privateTenantKey, + long privateGameInstanceKey, + long gameTemplateId, + String controlPlaneRequestId, + String launchDescriptorId, + long localVersionKey, + String scriptPatchVersion, + String runtimeFlagsJson, + String generationConfigRevision, + long releaseBundleId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String remapSetId) { + public WorldPrepareFields { + requirePositive(worldInstanceId, "worldInstanceId"); + requirePositive(privateTenantKey, "privateTenantKey"); + requirePositive(privateGameInstanceKey, "privateGameInstanceKey"); + requirePositive(gameTemplateId, "gameTemplateId"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 64); + requirePositive(localVersionKey, "localVersionKey"); + requireText(runtimeFlagsJson, "runtimeFlagsJson", Integer.MAX_VALUE); + requireText(generationConfigRevision, "generationConfigRevision", 128); + requirePositive(releaseBundleId, "releaseBundleId"); + requireText(publishedReleaseBundleRef, "publishedReleaseBundleRef", 128); + requirePositive(versionStateEpoch, "versionStateEpoch"); + requireOptionalText(scriptPatchVersion, "scriptPatchVersion", 100); + requireOptionalText(remapSetId, "remapSetId", 64); + } + + /** + * Compares immutable prepare and release inputs only; lifecycle state, epoch, termination, and + * timestamps are intentionally not part of this association. + */ + public void requireMatches( + CanonicalIdentity identity, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + Objects.requireNonNull(identity, "identity"); + Objects.requireNonNull(completeLaunchBinding, "completeLaunchBinding"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + var descriptor = completeLaunchBinding.descriptor(); + String expectedScriptPatch = + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null; + String expectedRemapSet = descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null; + if (privateTenantKey != completeLaunchBinding.sourceIntakeReceipt().localTenantKey() + || gameTemplateId != descriptor.gameTemplateId() + || !controlPlaneRequestId.equals(identity.controlPlaneRequestId()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId()) + || localVersionKey != versionIdentity.localVersionKey() + || !Objects.equals(scriptPatchVersion, expectedScriptPatch) + || !runtimeFlagsJson.equals(descriptor.runtimeFlagsJson()) + || !generationConfigRevision.equals(descriptor.generationConfigRevision()) + || releaseBundleId != descriptor.releaseBundleId() + || !publishedReleaseBundleRef.equals(descriptor.publishedReleaseBundleRef()) + || versionStateEpoch != descriptor.versionStateEpoch() + || !Objects.equals(remapSetId, expectedRemapSet)) { + throw new IllegalArgumentException( + "World instance row differs from the exact canonical launch prepare inputs"); + } + } + } + + private static void requireExactLaunchEvidence( + CanonicalIdentity identity, + WorldCompleteLaunchBindingReceipt binding, + WorldAuthoredVersionIdentityReceipt versionIdentity) { + var descriptor = binding.evidence().descriptor(); + var release = binding.evidence().releaseAttestation(); + var source = binding.sourceIntakeReceipt(); + if (!identity.targetNamespace().equals(binding.targetNamespace()) + || !identity.canonicalTenantId().equals(binding.canonicalTenantId()) + || !identity.worldSlug().equals(binding.worldSlug()) + || !identity.controlPlaneRequestId().equals(binding.controlPlaneRequestId()) + || !identity.targetNamespace().equals(descriptor.targetNamespace()) + || !identity.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !identity.worldSlug().equals(descriptor.worldSlug()) + || !identity.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !identity.targetNamespace().equals(release.targetNamespace()) + || !identity.canonicalTenantId().equals(release.canonicalTenantId()) + || !identity.worldSlug().equals(release.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(source.sourceOperationId()) + || !descriptor.authoredWorldSourceEvidenceDigest().equals(source.sourceEvidenceDigest()) + || !source.equals(versionIdentity.sourceIntakeReceipt()) + || !identity.targetNamespace().equals(versionIdentity.targetNamespace()) + || !identity.canonicalTenantId().equals(versionIdentity.canonicalTenantId()) + || !identity.worldSlug().equals(versionIdentity.worldSlug()) + || !release.canonicalVersionId().equals(versionIdentity.canonicalVersionId()) + || descriptor.versionId() != versionIdentity.gameDesignVersionId() + || versionIdentity.sourceIntakeReceipt().localTenantKey() != source.localTenantKey()) { + throw new IllegalArgumentException( + "Canonical instance claim differs from its exact World launch/source/version evidence"); + } + } + + private static void requireExactReadEcho( + GameSessionReadRequest request, GameSessionReadEvidence response) { + if (!request.readRequestId().equals(response.readRequestId()) + || !request.targetNamespace().equals(response.targetNamespace()) + || !request.canonicalTenantId().equals(response.canonicalTenantId()) + || !request.worldSlug().equals(response.worldSlug()) + || !request.canonicalGameInstanceId().equals(response.canonicalGameInstanceId()) + || !request.controlPlaneRequestId().equals(response.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(response.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(response.descriptorRequestDigest()) + || !request.expectedDescriptorResultDigest().equals(response.descriptorResultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(response.releaseAttestationEvidenceDigest())) { + throw new IllegalArgumentException( + "Game Session launch-association response does not echo the exact read request tuple and expected digests"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0L) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static void requireNonNegative(long value, String label) { + if (value < 0L) { + throw new IllegalArgumentException(label + " must not be negative"); + } + } + + private static void requireText(String value, String label, int maxLength) { + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(label + " must be nonblank and within its storage bound"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a lowercase SHA-256 digest"); + } + } + + private static void requireOptionalText(String value, String label, int maxLength) { + if (value != null && (value.isBlank() || value.length() > maxLength)) { + throw new IllegalArgumentException( + label + " must be absent or nonblank within its storage bound"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java new file mode 100644 index 0000000000..d34748d9c6 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java @@ -0,0 +1,938 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.sql.Connection; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +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.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * World-local storage and exact readback for a claimed canonical instance association. + * + *

This component has no public transport and does not authenticate Game Session. A positive + * owner readback only returns retained correlation; JOIN, ACTIVE, and admission remain unavailable + * until an authenticated same-namespace producer and complete prepare/materialization proof are + * integrated by the lifecycle owner. + */ +public final class WorldCanonicalInstanceAssociationRepository { + private static final Table ASSOCIATION = + DSL.table(DSL.name("world_canonical_instance_association")); + private static final Table WORLD_INSTANCE = DSL.table(DSL.name("world_instance")); + private static final Table COMPLETE_BINDING = + DSL.table(DSL.name("world_complete_launch_binding")); + private static final Table SOURCE_INTAKE = DSL.table(DSL.name("world_authored_source_intake")); + private static final Table VERSION_IDENTITY = + DSL.table(DSL.name("world_authored_version_identity")); + private static final JsonMapper CLOSED_JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private static final Field SCHEMA_VERSION = field("schema_version", Short.class); + private static final Field CANONICAL_GAME_INSTANCE_ID = + field("canonical_game_instance_id", UUID.class); + private static final Field CANONICAL_TARGET_NAMESPACE = + field("canonical_target_namespace", String.class); + private static final Field CANONICAL_TENANT_ID = field("canonical_tenant_id", UUID.class); + private static final Field CANONICAL_WORLD_SLUG = + field("canonical_world_slug", String.class); + private static final Field PLAYABLE_STATE_NAMESPACE_ID = + field("playable_state_namespace_id", UUID.class); + private static final Field PLAYABLE_STATE_SCOPE = + field("playable_state_scope", String.class); + private static final Field PUBLIC_PRODUCTION = field("public_production", Boolean.class); + private static final Field PLAYTEST_LIFECYCLE_ID = + field("playtest_lifecycle_id", UUID.class); + private static final Field PLAYTEST_STATE_GENERATION = + field("playtest_state_generation", Long.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + field("control_plane_request_id", String.class); + private static final Field WORLD_INSTANCE_ID = field("world_instance_id", Long.class); + private static final Field LAUNCH_BINDING_OPERATION_ID = + field("canonical_launch_binding_operation_id", UUID.class); + private static final Field VERSION_IDENTITY_OPERATION_ID = + field("version_identity_operation_id", UUID.class); + private static final Field CANONICAL_VERSION_ID = field("canonical_version_id", UUID.class); + private static final Field LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field PRIVATE_GAME_INSTANCE_KEY = + field("private_game_instance_key", Long.class); + private static final Field GAME_TEMPLATE_ID = field("game_template_id", Long.class); + private static final Field LAUNCH_DESCRIPTOR_ID = + field("launch_descriptor_id", String.class); + private static final Field LOCAL_VERSION_KEY = field("local_version_key", Long.class); + private static final Field SCRIPT_PATCH_VERSION = + field("script_patch_version", String.class); + private static final Field RUNTIME_FLAGS_JSON = field("runtime_flags_json", String.class); + private static final Field GENERATION_CONFIG_REVISION = + field("generation_config_revision", String.class); + private static final Field RELEASE_BUNDLE_ID = field("release_bundle_id", Long.class); + private static final Field PUBLISHED_RELEASE_BUNDLE_REF = + field("published_release_bundle_ref", String.class); + private static final Field VERSION_STATE_EPOCH = field("version_state_epoch", Long.class); + private static final Field REMAP_SET_ID = field("remap_set_id", String.class); + private static final Field INTAKE_OPERATION_ID = field("intake_operation_id", UUID.class); + private static final Field INTAKE_REQUEST_ID = field("intake_request_id", UUID.class); + private static final Field SOURCE_OPERATION_ID = field("source_operation_id", UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field DESCRIPTOR_REQUEST_DIGEST = + field("descriptor_request_digest", String.class); + private static final Field DESCRIPTOR_RESULT_DIGEST = + field("descriptor_result_digest", String.class); + private static final Field RELEASE_ATTESTATION_DIGEST = + field("release_attestation_digest", String.class); + + private static final Field INSTANCE_ID = field("id", Long.class); + private static final Field INSTANCE_TENANT_ID = field("tenant_id", Long.class); + private static final Field INSTANCE_GAME_INSTANCE_ID = + field("game_instance_id", Long.class); + private static final Field INSTANCE_GAME_TEMPLATE_ID = + field("game_template_id", Long.class); + private static final Field INSTANCE_CONTROL_PLANE_REQUEST_ID = + field("control_plane_request_id", String.class); + private static final Field INSTANCE_LAUNCH_DESCRIPTOR_ID = + field("launch_descriptor_id", String.class); + private static final Field INSTANCE_VERSION_ID = field("version_id", Long.class); + private static final Field INSTANCE_SCRIPT_PATCH_VERSION = + field("script_patch_version", String.class); + private static final Field INSTANCE_RUNTIME_FLAGS_JSON = + field("runtime_flags_json", String.class); + private static final Field INSTANCE_GENERATION_CONFIG_REVISION = + field("generation_config_revision", String.class); + private static final Field INSTANCE_RELEASE_BUNDLE_ID = + field("release_bundle_id", Long.class); + private static final Field INSTANCE_PUBLISHED_RELEASE_BUNDLE_REF = + field("published_release_bundle_ref", String.class); + private static final Field INSTANCE_VERSION_STATE_EPOCH = + field("version_state_epoch", Long.class); + private static final Field INSTANCE_REMAP_SET_ID = field("remap_set_id", String.class); + private static final Field INSTANCE_CANONICAL_GAME_INSTANCE_ID = + field("canonical_game_instance_id", UUID.class); + private static final Field INSTANCE_CANONICAL_TARGET_NAMESPACE = + field("canonical_target_namespace", String.class); + private static final Field INSTANCE_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field INSTANCE_CANONICAL_WORLD_SLUG = + field("canonical_world_slug", String.class); + private static final Field INSTANCE_PLAYABLE_STATE_NAMESPACE_ID = + field("playable_state_namespace_id", UUID.class); + private static final Field INSTANCE_PLAYABLE_STATE_SCOPE = + field("playable_state_scope", String.class); + private static final Field INSTANCE_PUBLIC_PRODUCTION = + field("public_production", Boolean.class); + private static final Field INSTANCE_PLAYTEST_LIFECYCLE_ID = + field("playtest_lifecycle_id", UUID.class); + private static final Field INSTANCE_PLAYTEST_STATE_GENERATION = + field("playtest_state_generation", Long.class); + private static final Field INSTANCE_LAUNCH_BINDING_OPERATION_ID = + field("canonical_launch_binding_operation_id", UUID.class); + + private static final Field BINDING_OPERATION_ID = + DSL.field(DSL.name("binding_operation_id"), UUID.class); + private static final Field BINDING_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field BINDING_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field BINDING_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field BINDING_WORLD_SLUG = field("world_slug", String.class); + private static final Field BINDING_CONTROL_PLANE_REQUEST_ID = + field("control_plane_request_id", String.class); + private static final Field BINDING_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field BINDING_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field BINDING_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field BINDING_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field BINDING_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field BINDING_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field BINDING_DESCRIPTOR_REQUEST_DIGEST = + field("descriptor_request_digest", String.class); + private static final Field BINDING_DESCRIPTOR_RESULT_DIGEST = + field("descriptor_result_digest", String.class); + private static final Field BINDING_RELEASE_ATTESTATION_DIGEST = + field("release_attestation_digest", String.class); + private static final Field BINDING_DESCRIPTOR_JSON = + field("descriptor_json", String.class); + private static final Field BINDING_RELEASE_ATTESTATION_JSON = + field("release_attestation_json", String.class); + + private static final Field SOURCE_OPERATION_ID_KEY = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field SOURCE_SCHEMA_VERSION = field("schema_version", Short.class); + private static final Field SOURCE_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field SOURCE_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = field("request_digest", String.class); + private static final Field SOURCE_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field SOURCE_EVIDENCE_SCHEMA_VERSION = + field("source_schema_version", Short.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + field("source_registration_request_id", UUID.class); + private static final Field SOURCE_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field SOURCE_SOURCE_REQUEST_DIGEST = + field("source_request_digest", String.class); + private static final Field SOURCE_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field SOURCE_TENANT_SLUG = field("tenant_slug", String.class); + private static final Field SOURCE_WORLD_SLUG = field("world_slug", String.class); + private static final Field SOURCE_WORLD_DISPLAY_NAME = + field("world_display_name", String.class); + private static final Field SOURCE_GAME_ROW_ID = field("source_game_row_id", Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + field("source_game_tenant_key", String.class); + private static final Field SOURCE_PROVENANCE_KIND = + field("source_provenance_kind", String.class); + private static final Field SOURCE_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field SOURCE_RECEIPT_DIGEST = field("receipt_digest", String.class); + + private static final Field VERSION_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field VERSION_TARGET_NAMESPACE = + field("target_namespace", String.class); + private static final Field VERSION_CANONICAL_TENANT_ID = + field("canonical_tenant_id", UUID.class); + private static final Field VERSION_WORLD_SLUG = field("world_slug", String.class); + private static final Field VERSION_CANONICAL_VERSION_ID = + field("canonical_version_id", UUID.class); + private static final Field VERSION_GAME_DESIGN_VERSION_ID = + field("game_design_version_id", Long.class); + private static final Field VERSION_LOCAL_VERSION_KEY = + field("local_version_key", Long.class); + private static final Field VERSION_INTAKE_OPERATION_ID = + field("intake_operation_id", UUID.class); + private static final Field VERSION_INTAKE_REQUEST_ID = + field("intake_request_id", UUID.class); + private static final Field VERSION_LOCAL_TENANT_KEY = field("local_tenant_key", Long.class); + private static final Field VERSION_INTAKE_REQUEST_DIGEST = + field("intake_request_digest", String.class); + private static final Field VERSION_SOURCE_OPERATION_ID = + field("source_operation_id", UUID.class); + private static final Field VERSION_SOURCE_EVIDENCE_DIGEST = + field("source_evidence_digest", String.class); + private static final Field VERSION_INTAKE_RECEIPT_DIGEST = + field("intake_receipt_digest", String.class); + private static final Field VERSION_STATE_SCHEMA_VERSION = + field("version_state_schema_version", Short.class); + private static final Field VERSION_STATE_READ_REQUEST_ID = + field("version_state_read_request_id", UUID.class); + private static final Field VERSION_STATE_STATE = + field("version_state_state", String.class); + private static final Field VERSION_STATE_EVIDENCE_EPOCH = + field("version_state_epoch", Long.class); + private static final Field VERSION_STATE_EVIDENCE_DIGEST = + field("version_state_evidence_digest", String.class); + private static final Field VERSION_STATE_EVIDENCE_JSON = + field("version_state_evidence_json", String.class); + + private final DSLContext dsl; + private final WorldCompleteLaunchBindingRepository launchBindingRepository; + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; + private final WorldAuthoredVersionIdentityRepository versionIdentityRepository; + + public WorldCanonicalInstanceAssociationRepository( + DSLContext dsl, + WorldCompleteLaunchBindingRepository launchBindingRepository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + WorldAuthoredVersionIdentityRepository versionIdentityRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.launchBindingRepository = + Objects.requireNonNull(launchBindingRepository, "launchBindingRepository"); + this.sourceIntakeRepository = + Objects.requireNonNull(sourceIntakeRepository, "sourceIntakeRepository"); + this.versionIdentityRepository = + Objects.requireNonNull(versionIdentityRepository, "versionIdentityRepository"); + } + + /** + * Retains an exact non-authorizing claim in the caller's short writable READ COMMITTED World + * transaction, after the same transaction created or selected its exact canonical World row. + * + *

This method does not commit the caller's transaction. The caller must commit, then use + * {@link #readOwnerAssociation(UUID)} as a separate committed read before reporting storage + * success. An exact retry compares the immutable V26 descriptor/release bytes and V23/V27 source + * and Version provenance already supplied in {@code claim}; it never re-resolves Game Design. + */ + public void retainClaimInOwnerTransaction(WorldCanonicalInstanceAssociation.Claim claim) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(claim, "claim"); + + Record worldRow = lockWorldInstance(claim.worldInstanceId()); + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields = + toWorldPrepareFields(worldRow); + requireInsertBornIdentity(worldRow, claim); + prepareFields.requireMatches( + claim.identity(), claim.completeLaunchBinding(), claim.versionIdentity()); + requireExactImmutableOwnerEvidence(claim); + + Record existing = findConflict(claim); + if (existing != null) { + requireSameStoredClaim(existing, claim, prepareFields); + return; + } + + int inserted = + dsl.insertInto(ASSOCIATION) + .set(SCHEMA_VERSION, (short) 1) + .set(CANONICAL_GAME_INSTANCE_ID, claim.canonicalGameInstanceId()) + .set(CANONICAL_TARGET_NAMESPACE, claim.targetNamespace()) + .set(CANONICAL_TENANT_ID, claim.canonicalTenantId()) + .set(CANONICAL_WORLD_SLUG, claim.worldSlug()) + .set(PLAYABLE_STATE_NAMESPACE_ID, claim.playableStateNamespaceId()) + .set(PLAYABLE_STATE_SCOPE, claim.playableStateScope()) + .set(PUBLIC_PRODUCTION, claim.identity().publicProduction()) + .set(PLAYTEST_LIFECYCLE_ID, (UUID) null) + .set(PLAYTEST_STATE_GENERATION, (Long) null) + .set(CONTROL_PLANE_REQUEST_ID, claim.controlPlaneRequestId()) + .set(WORLD_INSTANCE_ID, prepareFields.worldInstanceId()) + .set(LAUNCH_BINDING_OPERATION_ID, claim.launchBindingOperationId()) + .set(VERSION_IDENTITY_OPERATION_ID, claim.versionIdentityOperationId()) + .set(CANONICAL_VERSION_ID, claim.canonicalVersionId()) + .set(LOCAL_TENANT_KEY, prepareFields.privateTenantKey()) + .set(PRIVATE_GAME_INSTANCE_KEY, prepareFields.privateGameInstanceKey()) + .set(GAME_TEMPLATE_ID, prepareFields.gameTemplateId()) + .set(LAUNCH_DESCRIPTOR_ID, prepareFields.launchDescriptorId()) + .set(LOCAL_VERSION_KEY, prepareFields.localVersionKey()) + .set(SCRIPT_PATCH_VERSION, prepareFields.scriptPatchVersion()) + .set(RUNTIME_FLAGS_JSON, prepareFields.runtimeFlagsJson()) + .set(GENERATION_CONFIG_REVISION, prepareFields.generationConfigRevision()) + .set(RELEASE_BUNDLE_ID, prepareFields.releaseBundleId()) + .set(PUBLISHED_RELEASE_BUNDLE_REF, prepareFields.publishedReleaseBundleRef()) + .set(VERSION_STATE_EPOCH, prepareFields.versionStateEpoch()) + .set(REMAP_SET_ID, prepareFields.remapSetId()) + .set( + INTAKE_OPERATION_ID, + claim.completeLaunchBinding().sourceIntakeReceipt().operationId()) + .set( + INTAKE_REQUEST_ID, + claim.completeLaunchBinding().sourceIntakeReceipt().intakeRequestId()) + .set( + SOURCE_OPERATION_ID, + claim.completeLaunchBinding().sourceIntakeReceipt().sourceOperationId()) + .set( + SOURCE_EVIDENCE_DIGEST, + claim.completeLaunchBinding().sourceIntakeReceipt().sourceEvidenceDigest()) + .set( + INTAKE_REQUEST_DIGEST, + claim.completeLaunchBinding().sourceIntakeReceipt().requestDigest()) + .set( + INTAKE_RECEIPT_DIGEST, + claim.completeLaunchBinding().sourceIntakeReceipt().receiptDigest()) + .set( + DESCRIPTOR_REQUEST_DIGEST, + claim.completeLaunchBinding().descriptor().requestDigest()) + .set( + DESCRIPTOR_RESULT_DIGEST, claim.completeLaunchBinding().descriptor().resultDigest()) + .set( + RELEASE_ATTESTATION_DIGEST, + claim.completeLaunchBinding().evidence().releaseAttestation().evidenceDigest()) + .onConflictDoNothing() + .execute(); + + Record stored = findConflict(claim); + if (stored == null) { + throw new InvalidAssociationEvidenceException( + "World canonical instance association is missing after its owner claim"); + } + requireSameStoredClaim(stored, claim, prepareFields); + if (inserted == 0) { + // The complete exact compare above is the only idempotent conflict outcome. + return; + } + } + + /** + * Independently reads and reconstructs one immutable owner association after the write + * transaction commits. A present result is non-authorizing and carries no lifecycle status. + */ + public Optional readOwnerAssociation( + UUID canonicalGameInstanceId) { + requireNoActiveTransaction("World canonical instance association read"); + return readOwnerAssociation(canonicalGameInstanceId, false); + } + + /** Reconstructs the association without leaving the lifecycle owner's verified snapshot. */ + Optional readOwnerAssociationInOwnerTransaction( + UUID canonicalGameInstanceId) { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readOwnerAssociation(canonicalGameInstanceId, true); + } + + /** Reuses the exact immutable source reconstruction inside a writable activation transaction. */ + Optional readOwnerAssociationInActivationTransaction( + UUID canonicalGameInstanceId) { + requireWritableActivationTransaction(); + return readOwnerAssociation(canonicalGameInstanceId, true, true); + } + + private Optional readOwnerAssociation( + UUID canonicalGameInstanceId, boolean inOwnerSnapshot) { + return readOwnerAssociation(canonicalGameInstanceId, inOwnerSnapshot, false); + } + + private Optional readOwnerAssociation( + UUID canonicalGameInstanceId, boolean inOwnerSnapshot, boolean inActivationTransaction) { + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + Record row = findByCanonicalGameInstance(canonicalGameInstanceId); + if (row == null) { + return Optional.empty(); + } + return Optional.of(toAssociation(row, inOwnerSnapshot, inActivationTransaction)); + } + + private WorldCanonicalInstanceAssociation toAssociation( + Record row, boolean inOwnerSnapshot, boolean inActivationTransaction) { + try { + short schemaVersion = required(row, SCHEMA_VERSION); + if (schemaVersion != 1) { + throw new IllegalArgumentException( + "Unsupported World canonical instance association schema"); + } + String namespace = required(row, CANONICAL_TARGET_NAMESPACE); + UUID tenantId = required(row, CANONICAL_TENANT_ID); + String worldSlug = required(row, CANONICAL_WORLD_SLUG); + String controlRequestId = required(row, CONTROL_PLANE_REQUEST_ID); + UUID bindingOperationId = required(row, LAUNCH_BINDING_OPERATION_ID); + UUID intakeRequestId = required(row, INTAKE_REQUEST_ID); + WorldCompleteLaunchBindingRepository.StoredBinding storedBinding = + (inActivationTransaction + ? launchBindingRepository.readInOwnerActivationTransaction( + namespace, tenantId, controlRequestId) + : inOwnerSnapshot + ? launchBindingRepository.readInOwnerReadOnlyRepeatableRead( + namespace, tenantId, controlRequestId) + : launchBindingRepository.read(namespace, tenantId, controlRequestId)) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "World canonical association lost its immutable launch binding")); + if (!storedBinding.operationId().equals(bindingOperationId)) { + throw new InvalidAssociationEvidenceException( + "World canonical association substituted its complete launch binding"); + } + WorldAuthoredSourceIntakeReceipt sourceReceipt = + (inActivationTransaction + ? sourceIntakeRepository.readInOwnerActivationTransaction( + namespace, intakeRequestId) + : inOwnerSnapshot + ? sourceIntakeRepository.readInOwnerReadOnlyRepeatableRead( + namespace, intakeRequestId) + : sourceIntakeRepository.read(namespace, intakeRequestId)) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "World canonical association lost its original source intake")); + WorldCompleteLaunchBindingReceipt completeBinding = + launchBindingRepository.toReceipt(storedBinding, sourceReceipt); + UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); + WorldAuthoredVersionIdentityReceipt versionIdentity = + (inActivationTransaction + ? versionIdentityRepository.readByCanonicalVersionInOwnerActivationTransaction( + namespace, tenantId, worldSlug, canonicalVersionId) + : inOwnerSnapshot + ? versionIdentityRepository + .readByCanonicalVersionInOwnerReadOnlyRepeatableRead( + namespace, tenantId, worldSlug, canonicalVersionId) + : versionIdentityRepository.readByCanonicalVersion( + namespace, tenantId, worldSlug, canonicalVersionId)) + .orElseThrow( + () -> + new InvalidAssociationEvidenceException( + "World canonical association lost its UUID-to-private-Version receipt")); + WorldCanonicalInstanceAssociation.CanonicalIdentity identity = + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + required(row, CANONICAL_GAME_INSTANCE_ID), + namespace, + tenantId, + worldSlug, + required(row, PLAYABLE_STATE_NAMESPACE_ID), + required(row, PLAYABLE_STATE_SCOPE), + required(row, PUBLIC_PRODUCTION), + controlRequestId); + if (row.get(PLAYTEST_LIFECYCLE_ID) != null || row.get(PLAYTEST_STATE_GENERATION) != null) { + throw new InvalidAssociationEvidenceException( + "Persisted playtest association lacks the current producer's conditional lifecycle/generation proof"); + } + long worldInstanceId = required(row, WORLD_INSTANCE_ID); + Record worldRow = readWorldInstance(worldInstanceId); + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields = + toWorldPrepareFields(worldRow); + requireInsertBornIdentity(worldRow, identity, completeBinding.operationId()); + prepareFields.requireMatches(identity, completeBinding, versionIdentity); + requireStoredAssociationColumns( + row, identity, worldInstanceId, completeBinding, versionIdentity, prepareFields); + return new WorldCanonicalInstanceAssociation( + identity, worldInstanceId, completeBinding, versionIdentity, prepareFields); + } catch (RuntimeException exception) { + if (exception instanceof InvalidAssociationEvidenceException) { + throw exception; + } + throw new InvalidAssociationEvidenceException( + "Persisted World canonical instance association is invalid", exception); + } + } + + private void requireExactImmutableOwnerEvidence(WorldCanonicalInstanceAssociation.Claim claim) { + var sourceReceipt = claim.completeLaunchBinding().sourceIntakeReceipt(); + var evidence = claim.completeLaunchBinding().evidence(); + var descriptor = evidence.descriptor(); + var release = evidence.releaseAttestation(); + + Record binding = + dsl.selectFrom(COMPLETE_BINDING) + .where(BINDING_OPERATION_ID.eq(claim.launchBindingOperationId())) + .fetchOne(); + if (binding == null + || !Objects.equals( + binding.get(BINDING_TARGET_NAMESPACE, String.class), claim.targetNamespace()) + || !Objects.equals( + binding.get(BINDING_CANONICAL_TENANT_ID, UUID.class), claim.canonicalTenantId()) + || !Objects.equals( + binding.get(BINDING_CANONICAL_VERSION_ID, UUID.class), claim.canonicalVersionId()) + || !Objects.equals(binding.get(BINDING_WORLD_SLUG, String.class), claim.worldSlug()) + || !Objects.equals( + binding.get(BINDING_CONTROL_PLANE_REQUEST_ID, String.class), + claim.controlPlaneRequestId()) + || !Objects.equals( + binding.get(BINDING_INTAKE_OPERATION_ID, UUID.class), sourceReceipt.operationId()) + || !Objects.equals( + binding.get(BINDING_INTAKE_REQUEST_ID, UUID.class), sourceReceipt.intakeRequestId()) + || !Objects.equals( + binding.get(BINDING_LOCAL_TENANT_KEY, Long.class), sourceReceipt.localTenantKey()) + || !Objects.equals( + binding.get(BINDING_SOURCE_OPERATION_ID, UUID.class), sourceReceipt.sourceOperationId()) + || !Objects.equals( + binding.get(BINDING_SOURCE_EVIDENCE_DIGEST, String.class), + sourceReceipt.sourceEvidenceDigest()) + || !Objects.equals( + binding.get(BINDING_INTAKE_RECEIPT_DIGEST, String.class), sourceReceipt.receiptDigest()) + || !Objects.equals( + binding.get(BINDING_DESCRIPTOR_REQUEST_DIGEST, String.class), + descriptor.requestDigest()) + || !Objects.equals( + binding.get(BINDING_DESCRIPTOR_RESULT_DIGEST, String.class), descriptor.resultDigest()) + || !Objects.equals( + binding.get(BINDING_RELEASE_ATTESTATION_DIGEST, String.class), release.evidenceDigest()) + || !Objects.equals( + binding.get(BINDING_DESCRIPTOR_JSON, String.class), writeJson(descriptor)) + || !Objects.equals( + binding.get(BINDING_RELEASE_ATTESTATION_JSON, String.class), writeJson(release))) { + throw new RegistrationConflictException( + "Canonical instance claim differs from exact immutable V26 descriptor/release bytes"); + } + + Record source = + dsl.selectFrom(SOURCE_INTAKE) + .where(SOURCE_OPERATION_ID_KEY.eq(sourceReceipt.operationId())) + .fetchOne(); + requireExactSourceColumns(source, sourceReceipt); + + WorldAuthoredVersionIdentityReceipt identity = claim.versionIdentity(); + AuthoredWorldVersionStateEvidence versionEvidence = identity.versionStateEvidence(); + Record version = + dsl.selectFrom(VERSION_IDENTITY) + .where(VERSION_OPERATION_ID.eq(identity.operationId())) + .fetchOne(); + if (version == null + || !Objects.equals( + version.get(VERSION_TARGET_NAMESPACE, String.class), identity.targetNamespace()) + || !Objects.equals( + version.get(VERSION_CANONICAL_TENANT_ID, UUID.class), identity.canonicalTenantId()) + || !Objects.equals(version.get(VERSION_WORLD_SLUG, String.class), identity.worldSlug()) + || !Objects.equals( + version.get(VERSION_CANONICAL_VERSION_ID, UUID.class), identity.canonicalVersionId()) + || !Objects.equals( + version.get(VERSION_GAME_DESIGN_VERSION_ID, Long.class), identity.gameDesignVersionId()) + || !Objects.equals( + version.get(VERSION_LOCAL_VERSION_KEY, Long.class), identity.localVersionKey()) + || !Objects.equals( + version.get(VERSION_INTAKE_OPERATION_ID, UUID.class), sourceReceipt.operationId()) + || !Objects.equals( + version.get(VERSION_INTAKE_REQUEST_ID, UUID.class), sourceReceipt.intakeRequestId()) + || !Objects.equals( + version.get(VERSION_LOCAL_TENANT_KEY, Long.class), sourceReceipt.localTenantKey()) + || !Objects.equals( + version.get(VERSION_INTAKE_REQUEST_DIGEST, String.class), sourceReceipt.requestDigest()) + || !Objects.equals( + version.get(VERSION_SOURCE_OPERATION_ID, UUID.class), sourceReceipt.sourceOperationId()) + || !Objects.equals( + version.get(VERSION_SOURCE_EVIDENCE_DIGEST, String.class), + sourceReceipt.sourceEvidenceDigest()) + || !Objects.equals( + version.get(VERSION_INTAKE_RECEIPT_DIGEST, String.class), sourceReceipt.receiptDigest()) + || !Objects.equals( + version.get(VERSION_STATE_SCHEMA_VERSION, Short.class), + (short) versionEvidence.request().schemaVersion()) + || !Objects.equals( + version.get(VERSION_STATE_READ_REQUEST_ID, UUID.class), + versionEvidence.request().readRequestId()) + || !Objects.equals( + version.get(VERSION_STATE_STATE, String.class), + versionEvidence.versionState().name().replace("VERSION_LIFECYCLE_STATE_", "")) + || !Objects.equals( + version.get(VERSION_STATE_EVIDENCE_EPOCH, Long.class), + versionEvidence.versionStateEpoch()) + || !Objects.equals( + version.get(VERSION_STATE_EVIDENCE_DIGEST, String.class), + versionEvidence.evidenceDigest()) + || !Objects.equals( + version.get(VERSION_STATE_EVIDENCE_JSON, String.class), writeJson(versionEvidence))) { + throw new RegistrationConflictException( + "Canonical instance claim differs from exact immutable V27 Version/source bytes"); + } + } + + private static void requireExactSourceColumns( + Record row, WorldAuthoredSourceIntakeReceipt receipt) { + if (row == null) { + throw new RegistrationConflictException( + "Canonical instance claim lost its original source intake"); + } + AuthoredWorldSourceEvidence source = receipt.source(); + if (!Objects.equals( + row.get(SOURCE_SCHEMA_VERSION, Short.class), (short) receipt.schemaVersion()) + || !Objects.equals( + row.get(SOURCE_TARGET_NAMESPACE, String.class), receipt.targetNamespace()) + || !Objects.equals(row.get(SOURCE_INTAKE_REQUEST_ID, UUID.class), receipt.intakeRequestId()) + || !Objects.equals(row.get(SOURCE_REQUEST_DIGEST, String.class), receipt.requestDigest()) + || !Objects.equals(row.get(SOURCE_LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey()) + || !Objects.equals( + row.get(SOURCE_EVIDENCE_SCHEMA_VERSION, Short.class), (short) source.schemaVersion()) + || !Objects.equals( + row.get(SOURCE_REGISTRATION_REQUEST_ID, UUID.class), source.registrationRequestId()) + || !Objects.equals(row.get(SOURCE_SOURCE_OPERATION_ID, UUID.class), source.operationId()) + || !Objects.equals( + row.get(SOURCE_SOURCE_REQUEST_DIGEST, String.class), source.requestDigest()) + || !Objects.equals( + row.get(SOURCE_CANONICAL_TENANT_ID, UUID.class), source.canonicalTenantId()) + || !Objects.equals(row.get(SOURCE_TENANT_SLUG, String.class), source.tenantSlug()) + || !Objects.equals(row.get(SOURCE_WORLD_SLUG, String.class), source.worldSlug()) + || !Objects.equals( + row.get(SOURCE_WORLD_DISPLAY_NAME, String.class), source.worldDisplayName()) + || !Objects.equals(row.get(SOURCE_GAME_ROW_ID, Long.class), source.sourceGameRowId()) + || !Objects.equals( + row.get(SOURCE_GAME_TENANT_KEY, String.class), source.sourceGameTenantKey()) + || !Objects.equals(row.get(SOURCE_PROVENANCE_KIND, String.class), source.provenanceKind()) + || !Objects.equals( + row.get(SOURCE_SOURCE_EVIDENCE_DIGEST, String.class), source.evidenceDigest()) + || !Objects.equals(row.get(SOURCE_RECEIPT_DIGEST, String.class), receipt.receiptDigest())) { + throw new RegistrationConflictException( + "Canonical instance claim differs from exact immutable World source intake fields"); + } + } + + private void requireSameStoredClaim( + Record stored, + WorldCanonicalInstanceAssociation.Claim claim, + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields) { + requireStoredAssociationColumns( + stored, + claim.identity(), + claim.worldInstanceId(), + claim.completeLaunchBinding(), + claim.versionIdentity(), + prepareFields); + WorldCanonicalInstanceAssociation.WorldPrepareFields actual = + toWorldPrepareFields(readWorldInstance(claim.worldInstanceId())); + if (!actual.equals(prepareFields)) { + throw new InvalidAssociationEvidenceException( + "World canonical association row changed during exact owner retry"); + } + } + + private static void requireStoredAssociationColumns( + Record row, + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + long worldInstanceId, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldCanonicalInstanceAssociation.WorldPrepareFields prepareFields) { + var source = completeLaunchBinding.sourceIntakeReceipt(); + var descriptor = completeLaunchBinding.descriptor(); + var release = completeLaunchBinding.evidence().releaseAttestation(); + if (required(row, SCHEMA_VERSION) != 1 + || !Objects.equals( + required(row, CANONICAL_GAME_INSTANCE_ID), identity.canonicalGameInstanceId()) + || !Objects.equals(required(row, CANONICAL_TARGET_NAMESPACE), identity.targetNamespace()) + || !Objects.equals(required(row, CANONICAL_TENANT_ID), identity.canonicalTenantId()) + || !Objects.equals(required(row, CANONICAL_WORLD_SLUG), identity.worldSlug()) + || !Objects.equals( + required(row, PLAYABLE_STATE_NAMESPACE_ID), identity.playableStateNamespaceId()) + || !Objects.equals(required(row, PLAYABLE_STATE_SCOPE), identity.playableStateScope()) + || !Objects.equals(required(row, PUBLIC_PRODUCTION), identity.publicProduction()) + || row.get(PLAYTEST_LIFECYCLE_ID) != null + || row.get(PLAYTEST_STATE_GENERATION) != null + || !Objects.equals( + required(row, CONTROL_PLANE_REQUEST_ID), identity.controlPlaneRequestId()) + || !Objects.equals(required(row, WORLD_INSTANCE_ID), worldInstanceId) + || !Objects.equals( + required(row, LAUNCH_BINDING_OPERATION_ID), completeLaunchBinding.operationId()) + || !Objects.equals( + required(row, VERSION_IDENTITY_OPERATION_ID), versionIdentity.operationId()) + || !Objects.equals(required(row, CANONICAL_VERSION_ID), release.canonicalVersionId()) + || !Objects.equals(required(row, LOCAL_TENANT_KEY), prepareFields.privateTenantKey()) + || !Objects.equals( + required(row, PRIVATE_GAME_INSTANCE_KEY), prepareFields.privateGameInstanceKey()) + || !Objects.equals(required(row, GAME_TEMPLATE_ID), prepareFields.gameTemplateId()) + || !Objects.equals(required(row, LAUNCH_DESCRIPTOR_ID), prepareFields.launchDescriptorId()) + || !Objects.equals(required(row, LOCAL_VERSION_KEY), prepareFields.localVersionKey()) + || !Objects.equals(row.get(SCRIPT_PATCH_VERSION), prepareFields.scriptPatchVersion()) + || !Objects.equals(required(row, RUNTIME_FLAGS_JSON), prepareFields.runtimeFlagsJson()) + || !Objects.equals( + required(row, GENERATION_CONFIG_REVISION), prepareFields.generationConfigRevision()) + || !Objects.equals(required(row, RELEASE_BUNDLE_ID), prepareFields.releaseBundleId()) + || !Objects.equals( + required(row, PUBLISHED_RELEASE_BUNDLE_REF), prepareFields.publishedReleaseBundleRef()) + || !Objects.equals(required(row, VERSION_STATE_EPOCH), prepareFields.versionStateEpoch()) + || !Objects.equals(row.get(REMAP_SET_ID), prepareFields.remapSetId()) + || !Objects.equals(required(row, INTAKE_OPERATION_ID), source.operationId()) + || !Objects.equals(required(row, INTAKE_REQUEST_ID), source.intakeRequestId()) + || !Objects.equals(required(row, SOURCE_OPERATION_ID), source.sourceOperationId()) + || !Objects.equals(required(row, SOURCE_EVIDENCE_DIGEST), source.sourceEvidenceDigest()) + || !Objects.equals(required(row, INTAKE_REQUEST_DIGEST), source.requestDigest()) + || !Objects.equals(required(row, INTAKE_RECEIPT_DIGEST), source.receiptDigest()) + || !Objects.equals(required(row, DESCRIPTOR_REQUEST_DIGEST), descriptor.requestDigest()) + || !Objects.equals(required(row, DESCRIPTOR_RESULT_DIGEST), descriptor.resultDigest()) + || !Objects.equals(required(row, RELEASE_ATTESTATION_DIGEST), release.evidenceDigest())) { + throw new RegistrationConflictException( + "Canonical Game Instance, World row, request, source, Version, descriptor, or release binding conflicts"); + } + } + + private void requireInsertBornIdentity( + Record row, WorldCanonicalInstanceAssociation.Claim claim) { + requireInsertBornIdentity(row, claim.identity(), claim.launchBindingOperationId()); + } + + private void requireInsertBornIdentity( + Record row, + WorldCanonicalInstanceAssociation.CanonicalIdentity identity, + UUID launchBindingOperationId) { + if (row == null + || !Objects.equals( + row.get(INSTANCE_CANONICAL_GAME_INSTANCE_ID), identity.canonicalGameInstanceId()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_TARGET_NAMESPACE), identity.targetNamespace()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_TENANT_ID), identity.canonicalTenantId()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_WORLD_SLUG), identity.worldSlug()) + || !Objects.equals( + row.get(INSTANCE_PLAYABLE_STATE_NAMESPACE_ID), identity.playableStateNamespaceId()) + || !Objects.equals(row.get(INSTANCE_PLAYABLE_STATE_SCOPE), identity.playableStateScope()) + || !Objects.equals(row.get(INSTANCE_PUBLIC_PRODUCTION), identity.publicProduction()) + || row.get(INSTANCE_PLAYTEST_LIFECYCLE_ID) != null + || row.get(INSTANCE_PLAYTEST_STATE_GENERATION) != null + || !Objects.equals( + row.get(INSTANCE_LAUNCH_BINDING_OPERATION_ID), launchBindingOperationId)) { + throw new InvalidAssociationEvidenceException( + "World row has no matching insert-born canonical prepare identity; retained numeric rows cannot be associated"); + } + } + + private Record lockWorldInstance(long worldInstanceId) { + Record row = + dsl.selectFrom(WORLD_INSTANCE) + .where(INSTANCE_ID.eq(worldInstanceId)) + .forUpdate() + .fetchOne(); + if (row == null) { + throw new InvalidAssociationEvidenceException( + "Canonical instance association requires an already-created World instance row"); + } + return row; + } + + private Record readWorldInstance(long worldInstanceId) { + Record row = dsl.selectFrom(WORLD_INSTANCE).where(INSTANCE_ID.eq(worldInstanceId)).fetchOne(); + if (row == null) { + throw new InvalidAssociationEvidenceException( + "Canonical instance association lost its exact World instance row"); + } + return row; + } + + private WorldCanonicalInstanceAssociation.WorldPrepareFields toWorldPrepareFields(Record row) { + if (row == null) { + throw new InvalidAssociationEvidenceException("World instance row is missing"); + } + try { + return new WorldCanonicalInstanceAssociation.WorldPrepareFields( + required(row, INSTANCE_ID), + required(row, INSTANCE_TENANT_ID), + required(row, INSTANCE_GAME_INSTANCE_ID), + required(row, INSTANCE_GAME_TEMPLATE_ID), + required(row, INSTANCE_CONTROL_PLANE_REQUEST_ID), + required(row, INSTANCE_LAUNCH_DESCRIPTOR_ID), + required(row, INSTANCE_VERSION_ID), + row.get(INSTANCE_SCRIPT_PATCH_VERSION), + required(row, INSTANCE_RUNTIME_FLAGS_JSON), + required(row, INSTANCE_GENERATION_CONFIG_REVISION), + required(row, INSTANCE_RELEASE_BUNDLE_ID), + required(row, INSTANCE_PUBLISHED_RELEASE_BUNDLE_REF), + required(row, INSTANCE_VERSION_STATE_EPOCH), + row.get(INSTANCE_REMAP_SET_ID)); + } catch (RuntimeException exception) { + if (exception instanceof InvalidAssociationEvidenceException) { + throw exception; + } + throw new InvalidAssociationEvidenceException( + "World instance prepare fields are incomplete or invalid", exception); + } + } + + private Record findConflict(WorldCanonicalInstanceAssociation.Claim claim) { + Record row = findByCanonicalGameInstance(claim.canonicalGameInstanceId()); + if (row == null) { + row = + dsl.selectFrom(ASSOCIATION) + .where( + CANONICAL_TARGET_NAMESPACE + .eq(claim.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(claim.canonicalTenantId())) + .and(CONTROL_PLANE_REQUEST_ID.eq(claim.controlPlaneRequestId()))) + .fetchOne(); + } + if (row == null) { + row = + dsl.selectFrom(ASSOCIATION) + .where(WORLD_INSTANCE_ID.eq(claim.worldInstanceId())) + .fetchOne(); + } + if (row == null) { + row = + dsl.selectFrom(ASSOCIATION) + .where(LAUNCH_BINDING_OPERATION_ID.eq(claim.launchBindingOperationId())) + .fetchOne(); + } + return row; + } + + private Record findByCanonicalGameInstance(UUID canonicalGameInstanceId) { + return dsl.selectFrom(ASSOCIATION) + .where(CANONICAL_GAME_INSTANCE_ID.eq(canonicalGameInstanceId)) + .fetchOne(); + } + + private static String writeJson(Object value) { + try { + return CLOSED_JSON.writeValueAsString(value); + } catch (Exception exception) { + throw new InvalidAssociationEvidenceException( + "Immutable World owner evidence could not be encoded for exact comparison", exception); + } + } + + private static T required(Record row, Field field) { + return Objects.requireNonNull(row.get(field), "Persisted " + field.getName() + " is null"); + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " requires an independent committed owner read"); + } + } + + private void requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World canonical association snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"repeatable read".equals(state.get("isolation", String.class)) + || !"on".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World canonical association snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + } + + private void requireWritableActivationTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World canonical association activation read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World canonical association activation read requires a writable READ COMMITTED owner transaction"); + } + } + + private static void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World canonical instance association requires an active World owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World canonical instance association requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation == null || declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World canonical instance association requires READ COMMITTED isolation"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || value.equals(new UUID(0L, 0L))) { + 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 InvalidAssociationEvidenceException extends IllegalStateException { + public InvalidAssociationEvidenceException(String message) { + super(message); + } + + public InvalidAssociationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java new file mode 100644 index 0000000000..106dbff42e --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Exact authenticated lifecycle read; explicitly gated, never default-enabled. */ +public final class WorldCanonicalInstanceLifecycleReadGrpcService + extends WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceImplBase { + private final WorldCanonicalInstanceLifecycleReadRepository repository; + private final String trustedNamespace; + + public WorldCanonicalInstanceLifecycleReadGrpcService( + WorldCanonicalInstanceLifecycleReadRepository repository, + @Value("${firemud.grpc.workload-namespace:}") String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readWorldCanonicalInstanceLifecycle( + ReadWorldCanonicalInstanceLifecycleRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameSessionPeer(responseObserver)) return; + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription( + "Canonical World lifecycle read requires an independent owner operation") + .asRuntimeException()); + return; + } + + WorldCanonicalInstanceLifecycleEvidence.Request readRequest; + try { + readRequest = WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("A complete canonical World lifecycle read request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("World lifecycle namespace must match the authenticated peer") + .asRuntimeException()); + return; + } + + WorldCanonicalInstanceLifecycleEvidence evidence; + try { + evidence = repository.read(readRequest).orElse(null); + } catch ( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException + inconsistent) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical World lifecycle source evidence is inconsistent") + .asRuntimeException()); + return; + } catch (TransientDataAccessException | DataAccessException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Canonical World lifecycle storage is temporarily unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Canonical World lifecycle read failed") + .asRuntimeException()); + return; + } + if (evidence == null) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No exact materialized canonical World instance matches the request") + .asRuntimeException()); + return; + } + + ReadWorldCanonicalInstanceLifecycleResponse response; + try { + response = WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(readRequest, evidence); + } catch (IllegalArgumentException | IllegalStateException invalidEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical World lifecycle response evidence is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean requireAuthenticatedGameSessionPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-session-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Only the verified same-namespace Game Session workload without end-user context is allowed") + .asRuntimeException()); + return false; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java new file mode 100644 index 0000000000..07560e5121 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -0,0 +1,899 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Reconstructs a current canonical World lifecycle snapshot from one owner-local MVCC snapshot. + * + *

This repository is intentionally not registered as a Spring component. A positive result is + * exact World-owned evidence, not current Account authority, an activation command, or gameplay + * admission permission. + */ +public final class WorldCanonicalInstanceLifecycleReadRepository { + private static final Set INPUT_FIELDS = + Set.of( + "schemaVersion", + "identity", + "gameSessionReadRequest", + "gameSessionReadEvidence", + "launchBinding", + "versionIdentity", + "sourceIntake", + "topology", + "worldStartLocationEvidenceBase64"); + private static final JsonMapper CLOSED_JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final WorldCanonicalInstanceAssociationRepository associationRepository; + + public WorldCanonicalInstanceLifecycleReadRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceAssociationRepository associationRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository"); + transaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + transaction.setReadOnly(true); + } + + /** + * Reads only the exact canonical association requested, then follows its private World row key. + * Missing association or not-yet-materialized preparation is an ordinary empty read. + */ + public Optional read( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNoActiveTransaction("World canonical lifecycle read"); + return Optional.ofNullable( + transaction.execute( + status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readInCurrentOwnerTransaction(request, false); + })); + } + + /** + * Reconstructs the same exact owner evidence while a writable activation transaction holds it. + */ + Optional readForActivationInOwnerTransaction( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireWritableOwnerTransaction(); + return Optional.ofNullable(readInCurrentOwnerTransaction(request, true)); + } + + /** Reconstructs current lifecycle evidence inside an existing read-only owner snapshot. */ + Optional readForCurrentLocationInOwnerTransaction( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireReadOnlyRepeatableReadOwnerTransaction(); + return Optional.ofNullable(readInCurrentOwnerTransaction(request, false)); + } + + private WorldCanonicalInstanceLifecycleEvidence readInCurrentOwnerTransaction( + WorldCanonicalInstanceLifecycleEvidence.Request request, boolean lockLifecycleRow) { + try { + Optional maybeAssociation = + lockLifecycleRow + ? associationRepository.readOwnerAssociationInActivationTransaction( + request.canonicalGameInstanceId()) + : associationRepository.readOwnerAssociationInOwnerTransaction( + request.canonicalGameInstanceId()); + if (maybeAssociation.isEmpty()) return null; + WorldCanonicalInstanceAssociation association = maybeAssociation.orElseThrow(); + if (!matchesRequest(request, association)) return null; + + Record preparation = + dsl.fetchOne( + "SELECT canonical_game_instance_id, capture_id, graph_sha256, input_digest, input_json, " + + "graph_bytes, world_instance_id, private_game_instance_key, region_count, zone_count, " + + "room_count, exit_count, storage_status " + + "FROM world_canonical_instance_preparation WHERE canonical_game_instance_id = ?", + request.canonicalGameInstanceId()); + if (preparation == null) return null; + return readMaterialized(request, association, preparation, lockLifecycleRow); + } catch (TransientDataAccessException | DataAccessException unavailable) { + throw unavailable; + } catch ( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException + inconsistent) { + throw new InvalidLifecycleEvidenceException( + "Canonical World association source evidence is inconsistent", inconsistent); + } + } + + private WorldCanonicalInstanceLifecycleEvidence readMaterialized( + WorldCanonicalInstanceLifecycleEvidence.Request request, + WorldCanonicalInstanceAssociation association, + Record preparation, + boolean lockLifecycleRow) { + try { + UUID canonicalGameInstanceId = request.canonicalGameInstanceId(); + UUID captureId = required(preparation, "capture_id", UUID.class); + String graphSha256 = required(preparation, "graph_sha256", String.class); + String inputDigest = required(preparation, "input_digest", String.class); + String inputJson = required(preparation, "input_json", String.class); + byte[] graphBytes = required(preparation, "graph_bytes", byte[].class); + if (!canonicalGameInstanceId.equals( + required(preparation, "canonical_game_instance_id", UUID.class)) + || required(preparation, "world_instance_id", Long.class) != association.worldInstanceId() + || required(preparation, "private_game_instance_key", Long.class) + != association.worldPrepareFields().privateGameInstanceKey() + || !"MATERIALIZED_UNVERIFIED" + .equals(required(preparation, "storage_status", String.class))) { + throw invalid( + "Retained World preparation differs from its immutable canonical association"); + } + String retainedGraphSha = HexFormat.of().formatHex(sha256(graphBytes)); + String retainedInputDigest = digest(inputJson.getBytes(StandardCharsets.UTF_8)); + if (!retainedGraphSha.equals(graphSha256) || !retainedInputDigest.equals(inputDigest)) { + throw invalid("Retained World preparation bytes differ from their immutable digests"); + } + + JsonNode input = parseInput(inputJson); + requireInputIdentity(input, request, association, captureId); + requirePreparationCounts(input, preparation); + Set expectedRegionTemplates = + requireFrozenGraphIdentity(input, preparation, graphBytes, graphSha256); + Map operationalRegionAssignments = + readOperationalRegionAssignments(association, preparation, expectedRegionTemplates); + + var release = association.completeLaunchBinding().evidence().releaseAttestation(); + if (release.schemaVersion() + != net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence + .SELECTOR_SCHEMA_VERSION + || release.worldStartLocationEvidence() == null) { + throw invalid("Receipt-less retained V1 preparation cannot produce lifecycle evidence"); + } + WorldPublishedStartLocationEvidence selector = release.worldStartLocationEvidence(); + byte[] selectorBytes = selector.canonicalBytes(); + if (!input.has("worldStartLocationEvidenceBase64") + || !java.util.Base64.getEncoder() + .encodeToString(selectorBytes) + .equals(input.get("worldStartLocationEvidenceBase64").textValue())) { + throw invalid( + "Retained V2 preparation selector differs from its complete release evidence"); + } + WorldDraftStartLocationEvidence receipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + RoomTemplateRef startLocation = receipt.startLocation(); + if (!request.canonicalTenantId().equals(startLocation.tenantId()) + || !request.canonicalVersionId().equals(startLocation.versionId())) { + throw invalid("Original World ROOM selector differs from the requested canonical Version"); + } + requireOriginalSelector(selector, receipt, graphBytes); + RoomMapping mapping = requireMappedRoom(association, startLocation, selectorBytes); + Record lifecycle = readLifecycleRow(association, request, lockLifecycleRow); + + return new WorldCanonicalInstanceLifecycleEvidence( + request, + association.completeLaunchBinding().evidence(), + startLocation, + mapping.runtimeRoomInstanceId(), + required(lifecycle, "status", String.class), + required(lifecycle, "lifecycle_epoch", Long.class), + required(lifecycle, "row_version", Long.class), + captureId, + graphSha256, + inputDigest, + operationalRegionAssignments); + } catch (InvalidLifecycleEvidenceException invalid) { + throw invalid; + } catch (TransientDataAccessException | DataAccessException unavailable) { + throw unavailable; + } catch (RuntimeException invalid) { + throw new InvalidLifecycleEvidenceException( + "Retained canonical World lifecycle source evidence is inconsistent", invalid); + } + } + + private void requireInputIdentity( + JsonNode input, + WorldCanonicalInstanceLifecycleEvidence.Request request, + WorldCanonicalInstanceAssociation association, + UUID captureId) { + JsonNode identity = requiredObject(input, "identity"); + requireText(identity, "canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + requireText(identity, "targetNamespace", request.targetNamespace()); + requireText(identity, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(identity, "worldSlug", request.worldSlug()); + requireText( + identity, "playableStateNamespaceId", request.playableStateNamespaceId().toString()); + requireText(identity, "playableStateScope", request.playableStateScope()); + requireBoolean(identity, "publicProduction", request.publicProduction()); + requireText(identity, "controlPlaneRequestId", request.controlPlaneRequestId()); + + JsonNode gsRequest = requiredObject(input, "gameSessionReadRequest"); + requireText(gsRequest, "targetNamespace", request.targetNamespace()); + requireText(gsRequest, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(gsRequest, "worldSlug", request.worldSlug()); + requireText(gsRequest, "canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + requireText(gsRequest, "controlPlaneRequestId", request.controlPlaneRequestId()); + requireText( + gsRequest, "expectedDescriptorRequestDigest", request.expectedDescriptorRequestDigest()); + requireText( + gsRequest, "expectedDescriptorResultDigest", request.expectedDescriptorResultDigest()); + requireText( + gsRequest, + "expectedReleaseAttestationEvidenceDigest", + request.expectedReleaseAttestationDigest()); + var descriptor = association.completeLaunchBinding().descriptor(); + requireText(gsRequest, "launchDescriptorId", descriptor.launchDescriptorId()); + + JsonNode gsEvidence = requiredObject(input, "gameSessionReadEvidence"); + requireText(gsEvidence, "targetNamespace", request.targetNamespace()); + requireText(gsEvidence, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(gsEvidence, "worldSlug", request.worldSlug()); + requireText( + gsEvidence, "canonicalGameInstanceId", request.canonicalGameInstanceId().toString()); + requireText(gsEvidence, "controlPlaneRequestId", request.controlPlaneRequestId()); + requireText( + gsEvidence, "playableStateNamespaceId", request.playableStateNamespaceId().toString()); + requireText(gsEvidence, "playableStateScope", request.playableStateScope()); + requireBoolean(gsEvidence, "publicProduction", request.publicProduction()); + requireText(gsEvidence, "descriptorRequestDigest", request.expectedDescriptorRequestDigest()); + requireText(gsEvidence, "descriptorResultDigest", request.expectedDescriptorResultDigest()); + requireText( + gsEvidence, "releaseAttestationEvidenceDigest", request.expectedReleaseAttestationDigest()); + requireText(gsEvidence, "launchDescriptorId", descriptor.launchDescriptorId()); + requireText(gsEvidence, "descriptorJson", writeClosedEvidenceJson(descriptor)); + requireText( + gsEvidence, + "releaseAttestationJson", + writeClosedEvidenceJson( + association.completeLaunchBinding().evidence().releaseAttestation())); + + var binding = association.completeLaunchBinding(); + JsonNode launch = requiredObject(input, "launchBinding"); + requireInteger(launch, "schemaVersion", binding.schemaVersion()); + requireText(launch, "operationId", binding.operationId().toString()); + requireText(launch, "targetNamespace", request.targetNamespace()); + requireText(launch, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(launch, "worldSlug", request.worldSlug()); + requireText(launch, "controlPlaneRequestId", request.controlPlaneRequestId()); + requireText(launch, "descriptorRequestDigest", request.expectedDescriptorRequestDigest()); + requireText(launch, "descriptorResultDigest", request.expectedDescriptorResultDigest()); + requireText(launch, "releaseAttestationDigest", request.expectedReleaseAttestationDigest()); + requireText(launch, "canonicalVersionId", request.canonicalVersionId().toString()); + requireText( + launch, "intakeRequestId", binding.sourceIntakeReceipt().intakeRequestId().toString()); + requireInteger(launch, "localTenantKey", binding.sourceIntakeReceipt().localTenantKey()); + requireText( + launch, "intakeOperationId", binding.sourceIntakeReceipt().operationId().toString()); + requireText( + launch, "sourceOperationId", binding.sourceIntakeReceipt().sourceOperationId().toString()); + requireText( + launch, "sourceEvidenceDigest", binding.sourceIntakeReceipt().sourceEvidenceDigest()); + requireText(launch, "intakeRequestDigest", binding.sourceIntakeReceipt().requestDigest()); + requireText(launch, "intakeReceiptDigest", binding.sourceIntakeReceipt().receiptDigest()); + + var version = association.versionIdentity(); + JsonNode versionJson = requiredObject(input, "versionIdentity"); + requireInteger(versionJson, "schemaVersion", version.schemaVersion()); + requireText(versionJson, "operationId", version.operationId().toString()); + requireText(versionJson, "canonicalVersionId", request.canonicalVersionId().toString()); + requireInteger(versionJson, "localVersionKey", version.localVersionKey()); + requireInteger(versionJson, "gameDesignVersionId", version.gameDesignVersionId()); + requireInteger( + versionJson, "versionStateEpoch", version.versionStateEvidence().versionStateEpoch()); + requireText(versionJson, "versionState", version.versionStateEvidence().versionState().name()); + requireText(versionJson, "evidenceDigest", version.versionStateEvidence().evidenceDigest()); + + JsonNode source = requiredObject(input, "sourceIntake"); + requireInteger(source, "schemaVersion", binding.sourceIntakeReceipt().schemaVersion()); + requireText(source, "targetNamespace", request.targetNamespace()); + requireText( + source, "intakeRequestId", binding.sourceIntakeReceipt().intakeRequestId().toString()); + requireText(source, "operationId", binding.sourceIntakeReceipt().operationId().toString()); + requireText(source, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(source, "worldSlug", request.worldSlug()); + requireText( + source, "sourceOperationId", binding.sourceIntakeReceipt().sourceOperationId().toString()); + requireText( + source, "sourceEvidenceDigest", binding.sourceIntakeReceipt().sourceEvidenceDigest()); + requireText(source, "receiptDigest", binding.sourceIntakeReceipt().receiptDigest()); + requireText(source, "requestDigest", binding.sourceIntakeReceipt().requestDigest()); + requireInteger(source, "localTenantKey", binding.sourceIntakeReceipt().localTenantKey()); + requireSourceEvidenceObject(source, binding.sourceIntakeReceipt().source()); + + JsonNode topology = requiredObject(input, "topology"); + requireText(topology, "captureId", captureId.toString()); + requireText(topology, "targetNamespace", request.targetNamespace()); + requireText(topology, "canonicalTenantId", request.canonicalTenantId().toString()); + requireText(topology, "canonicalVersionId", request.canonicalVersionId().toString()); + requireText(topology, "versionIdentityOperationId", version.operationId().toString()); + } + + private void requirePreparationCounts(JsonNode input, Record preparation) { + JsonNode topology = requiredObject(input, "topology"); + requireInteger(topology, "regionCount", required(preparation, "region_count", Integer.class)); + requireInteger(topology, "zoneCount", required(preparation, "zone_count", Integer.class)); + requireInteger(topology, "roomCount", required(preparation, "room_count", Integer.class)); + requireInteger(topology, "exitCount", required(preparation, "exit_count", Integer.class)); + if (required(preparation, "region_count", Integer.class) <= 0 + || required(preparation, "zone_count", Integer.class) < 0 + || required(preparation, "room_count", Integer.class) < 0 + || required(preparation, "exit_count", Integer.class) < 0) { + throw invalid("Retained World preparation topology counts are invalid"); + } + } + + /** Proves the preparation graph is the immutable graph retained by the exact frozen capture. */ + private Set requireFrozenGraphIdentity( + JsonNode input, Record preparation, byte[] graphBytes, String graphSha256) { + JsonNode topology = requiredObject(input, "topology"); + UUID captureId = required(preparation, "capture_id", UUID.class); + Record frozen = + dsl.fetchOne( + "SELECT capture_id,request_id,commit_id,version_identity_operation_id,publication_fence," + + "graph_bytes,graph_sha256,capture_status FROM world_canonical_frozen_topology " + + "WHERE capture_id=?", + captureId); + if (frozen == null + || !captureId.equals(required(frozen, "capture_id", UUID.class)) + || !"CAPTURED_UNVERIFIED".equals(required(frozen, "capture_status", String.class)) + || !Arrays.equals(graphBytes, required(frozen, "graph_bytes", byte[].class)) + || !graphSha256.equals(required(frozen, "graph_sha256", String.class)) + || !HexFormat.of().formatHex(sha256(graphBytes)).equals(graphSha256)) { + throw invalid("Canonical preparation graph differs from its exact frozen capture"); + } + requireText(topology, "requestId", required(frozen, "request_id", UUID.class).toString()); + requireText(topology, "commitId", required(frozen, "commit_id", UUID.class).toString()); + requireText( + topology, + "versionIdentityOperationId", + required(frozen, "version_identity_operation_id", UUID.class).toString()); + requireText( + topology, "publicationFence", required(frozen, "publication_fence", UUID.class).toString()); + + try { + JsonNode graph = CLOSED_JSON.readTree(graphBytes); + requireFields( + graph, + Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows"), + "Frozen canonical graph"); + requireText(graph, "schemaVersion", "2"); + requireText( + graph, "canonicalTenantId", text(requiredObject(input, "identity"), "canonicalTenantId")); + requireText(graph, "canonicalVersionId", text(topology, "canonicalVersionId")); + JsonNode rows = graph.get("rows"); + if (rows == null || !rows.isArray()) { + throw invalid("Frozen canonical graph rows must be an array"); + } + Map expectedCounts = + Map.of( + "REGION", intValue(topology, "regionCount"), + "ZONE", intValue(topology, "zoneCount"), + "ROOM", intValue(topology, "roomCount"), + "ROOM_EXIT", intValue(topology, "exitCount"), + "GENERATION_RULE", intValue(topology, "generationRuleCount"), + "WORLD_ENTITY_SPAWN_BINDING", intValue(topology, "spawnBindingCount")); + Map actualCounts = new java.util.HashMap<>(); + Set graphIdentities = new HashSet<>(); + Set expectedRegionTemplates = new HashSet<>(); + for (JsonNode row : rows) { + JsonNode mapping = requiredObject(row, "mapping"); + String family = text(mapping, "family"); + String templateText = text(mapping, "template_id"); + UUID templateId = parseCanonicalUuid(templateText, "Frozen graph template_id"); + if (!expectedCounts.containsKey(family) + || !graphIdentities.add(family + ":" + templateId)) { + throw invalid("Frozen canonical graph has an unsupported or duplicate identity"); + } + actualCounts.merge(family, 1, Integer::sum); + if ("REGION".equals(family) && !expectedRegionTemplates.add(templateId)) { + throw invalid("Frozen canonical graph repeats a REGION template identity"); + } + } + if (expectedCounts.entrySet().stream() + .anyMatch( + entry -> + actualCounts.getOrDefault(entry.getKey(), 0).intValue() + != entry.getValue().intValue()) + || rows.size() != expectedCounts.values().stream().mapToInt(Integer::intValue).sum() + || expectedRegionTemplates.size() + != required(preparation, "region_count", Integer.class)) { + throw invalid("Frozen canonical graph family counts differ from exact preparation input"); + } + return Set.copyOf(expectedRegionTemplates); + } catch (tools.jackson.core.JacksonException malformed) { + throw new InvalidLifecycleEvidenceException("Frozen canonical graph is invalid", malformed); + } + } + + /** + * Reads every scoped region row together with its REGION topology identity in this same owner + * snapshot. The immutable graph's template set and persisted materialization count must match + * exactly before World exposes the canonical-runtime UUID to operational-label assignments. + */ + private Map readOperationalRegionAssignments( + WorldCanonicalInstanceAssociation association, + Record preparation, + Set expectedRegionTemplates) { + long worldInstanceId = association.worldInstanceId(); + long tenantKey = association.worldPrepareFields().privateTenantKey(); + long gameInstanceKey = association.worldPrepareFields().privateGameInstanceKey(); + int expectedCount = required(preparation, "region_count", Integer.class); + if (expectedCount <= 0 || expectedRegionTemplates.size() != expectedCount) { + throw invalid("Canonical World region count differs from its frozen graph"); + } + var rows = + dsl.fetch( + "SELECT m.id AS mapping_id,m.world_instance_id AS mapping_world_instance_id," + + "m.canonical_game_instance_id AS mapping_game_instance_id,m.family AS mapping_family," + + "m.template_id AS mapping_template_id,m.runtime_row_id AS mapping_runtime_row_id," + + "m.runtime_identity AS mapping_runtime_identity,ri.id AS region_row_id," + + "ri.world_instance_id AS region_world_instance_id,ri.tenant_id AS region_tenant_key," + + "ri.game_instance_id AS region_game_instance_key," + + "ri.canonical_region_instance_id,ri.operational_region_id " + + "FROM world_canonical_instance_topology_identity m FULL OUTER JOIN region_instance ri " + + "ON m.family='REGION' AND m.runtime_row_id=ri.id " + + "WHERE (m.world_instance_id=? AND m.family='REGION') OR ri.world_instance_id=? " + + "OR (ri.tenant_id=? AND ri.game_instance_id=?)", + worldInstanceId, + worldInstanceId, + tenantKey, + gameInstanceKey); + if (rows.size() != expectedCount) { + throw invalid("Canonical World REGION materialization has missing or extra retained rows"); + } + Map assignments = new LinkedHashMap<>(); + Set seenTemplates = new HashSet<>(); + Set seenOperationalIds = new HashSet<>(); + for (Record row : rows) { + Long mappingId = row.get("mapping_id", Long.class); + Long regionRowId = row.get("region_row_id", Long.class); + if (mappingId == null || regionRowId == null) { + throw invalid( + "Canonical World REGION row lacks its exact topology identity or runtime row"); + } + if (!"REGION".equals(required(row, "mapping_family", String.class)) + || required(row, "mapping_world_instance_id", Long.class) != worldInstanceId + || !association + .identity() + .canonicalGameInstanceId() + .equals(required(row, "mapping_game_instance_id", UUID.class)) + || required(row, "mapping_runtime_row_id", Long.class).longValue() + != regionRowId.longValue() + || required(row, "region_world_instance_id", Long.class) != worldInstanceId + || required(row, "region_tenant_key", Long.class) != tenantKey + || required(row, "region_game_instance_key", Long.class) != gameInstanceKey) { + throw invalid("Canonical World REGION row differs from its exact instance scope"); + } + UUID templateId = required(row, "mapping_template_id", UUID.class); + UUID canonicalRegionId = required(row, "canonical_region_instance_id", UUID.class); + UUID mappedCanonicalRegionId = required(row, "mapping_runtime_identity", UUID.class); + UUID operationalRegionId = required(row, "operational_region_id", UUID.class); + if (!expectedRegionTemplates.contains(templateId) + || !seenTemplates.add(templateId) + || !canonicalRegionId.equals(mappedCanonicalRegionId) + || canonicalRegionId.equals(operationalRegionId) + || !seenOperationalIds.add(operationalRegionId) + || assignments.putIfAbsent(canonicalRegionId, operationalRegionId) != null) { + throw invalid("Canonical World REGION assignment is duplicate or differs from its graph"); + } + } + if (!seenTemplates.equals(expectedRegionTemplates) || assignments.size() != expectedCount) { + throw invalid("Canonical World REGION assignments do not completely cover the frozen graph"); + } + return assignments; + } + + private void requireOriginalSelector( + WorldPublishedStartLocationEvidence selector, + WorldDraftStartLocationEvidence receipt, + byte[] graphBytes) { + Record original = + dsl.fetchOne( + "SELECT s.receipt_bytes,s.account_binding_bytes,s.graph_digest,a.result_bytes,g.graph_bytes " + + "FROM world_draft_start_location_receipt s JOIN world_draft_graph_application a " + + "ON a.operation_id=s.operation_id AND a.request_id=s.request_id AND a.commit_id=s.commit_id " + + "AND a.authorization_fence_id=s.authorization_fence_id " + + "JOIN world_topology_draft_commit g ON g.request_id=s.request_id AND g.commit_id=s.commit_id " + + "WHERE s.operation_id=? AND s.target_namespace=? AND s.canonical_tenant_id=? " + + "AND s.canonical_version_id=? AND s.room_template_id=?", + receipt.operationId(), + receipt.targetNamespace(), + receipt.startLocation().tenantId(), + receipt.startLocation().versionId(), + receipt.startLocation().roomTemplateId()); + if (original == null + || !Arrays.equals( + selector.selectorReceiptBytes(), required(original, "receipt_bytes", byte[].class)) + || !Arrays.equals( + selector.originalAccountBindingBytes(), + required(original, "account_binding_bytes", byte[].class)) + || !Arrays.equals( + selector.appliedResultBytes(), required(original, "result_bytes", byte[].class)) + || !Arrays.equals(graphBytes, required(original, "graph_bytes", byte[].class)) + || !receipt.graphDigest().equals(digest(graphBytes)) + || !receipt.graphDigest().equals(required(original, "graph_digest", String.class))) { + throw invalid("Canonical preparation selector differs from original World source evidence"); + } + } + + private RoomMapping requireMappedRoom( + WorldCanonicalInstanceAssociation association, + RoomTemplateRef startLocation, + byte[] selectorBytes) { + Record selected = + dsl.fetchOne( + "SELECT s.world_instance_id,s.canonical_tenant_id,s.canonical_version_id,s.room_template_id, " + + "s.runtime_room_instance_id,s.receipt_digest,s.graph_digest,s.evidence_bytes, " + + "m.runtime_room_instance_id AS mapped_room_instance_id,m.runtime_row_id AS mapped_room_row_id, " + + "m.template_id AS mapped_template_id,r.room_instance_row_id AS actual_room_instance_id, " + + "r.tenant_id AS room_tenant_key,r.game_instance_id AS room_game_instance_key, " + + "ri.tenant_id AS region_tenant_key,ri.game_instance_id AS region_game_instance_key, " + + "ri.world_instance_id AS room_world_instance_id " + + "FROM world_canonical_preparation_start_location s " + + "JOIN world_canonical_instance_topology_identity m ON m.world_instance_id=s.world_instance_id " + + "AND m.canonical_game_instance_id=s.canonical_game_instance_id AND m.family='ROOM' " + + "AND m.template_id=s.room_template_id " + + "JOIN room_instance r ON r.id=m.runtime_row_id " + + "JOIN region_instance ri ON ri.id=r.region_instance_id " + + "WHERE s.canonical_game_instance_id=?", + association.identity().canonicalGameInstanceId()); + if (selected == null + || required(selected, "world_instance_id", Long.class) != association.worldInstanceId() + || !association + .identity() + .canonicalTenantId() + .equals(required(selected, "canonical_tenant_id", UUID.class)) + || !association + .canonicalVersionId() + .equals(required(selected, "canonical_version_id", UUID.class)) + || !startLocation + .roomTemplateId() + .equals(required(selected, "room_template_id", UUID.class)) + || required(selected, "runtime_room_instance_id", Long.class) + != required(selected, "mapped_room_instance_id", Long.class) + || required(selected, "runtime_room_instance_id", Long.class) + != required(selected, "mapped_room_row_id", Long.class) + || required(selected, "runtime_room_instance_id", Long.class) + != required(selected, "actual_room_instance_id", Long.class) + || !startLocation + .roomTemplateId() + .equals(required(selected, "mapped_template_id", UUID.class)) + || !Arrays.equals(selectorBytes, required(selected, "evidence_bytes", byte[].class)) + || !receiptDigestFromEvidence(selectorBytes) + .equals(required(selected, "receipt_digest", String.class)) + || !WorldDraftStartLocationEvidence.fromStored( + WorldPublishedStartLocationEvidence.fromStored(selectorBytes) + .selectorReceiptBytes()) + .graphDigest() + .equals(required(selected, "graph_digest", String.class)) + || required(selected, "room_tenant_key", Long.class) + != association.worldPrepareFields().privateTenantKey() + || required(selected, "room_game_instance_key", Long.class) + != association.worldPrepareFields().privateGameInstanceKey() + || required(selected, "region_tenant_key", Long.class) + != association.worldPrepareFields().privateTenantKey() + || required(selected, "region_game_instance_key", Long.class) + != association.worldPrepareFields().privateGameInstanceKey() + || required(selected, "room_world_instance_id", Long.class) + != association.worldInstanceId()) { + throw invalid("Canonical ROOM selector is not the exact mapped scoped World runtime room"); + } + return new RoomMapping(required(selected, "runtime_room_instance_id", Long.class)); + } + + private Record readLifecycleRow( + WorldCanonicalInstanceAssociation association, + WorldCanonicalInstanceLifecycleEvidence.Request request, + boolean lockLifecycleRow) { + Record row = + dsl.fetchOne( + "SELECT * FROM world_instance WHERE id=?" + (lockLifecycleRow ? " FOR UPDATE" : ""), + association.worldInstanceId()); + if (row == null + || required(row, "id", Long.class) != association.worldInstanceId() + || !request + .canonicalGameInstanceId() + .equals(required(row, "canonical_game_instance_id", UUID.class)) + || !request + .targetNamespace() + .equals(required(row, "canonical_target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(row, "canonical_tenant_id", UUID.class)) + || !request.worldSlug().equals(required(row, "canonical_world_slug", String.class)) + || !request + .playableStateNamespaceId() + .equals(required(row, "playable_state_namespace_id", UUID.class)) + || !request.playableStateScope().equals(required(row, "playable_state_scope", String.class)) + || request.publicProduction() != required(row, "public_production", Boolean.class) + || !request + .controlPlaneRequestId() + .equals(required(row, "control_plane_request_id", String.class)) + || !association + .launchBindingOperationId() + .equals(required(row, "canonical_launch_binding_operation_id", UUID.class)) + || required(row, "tenant_id", Long.class) + != association.worldPrepareFields().privateTenantKey() + || required(row, "game_instance_id", Long.class) + != association.worldPrepareFields().privateGameInstanceKey() + || required(row, "version_id", Long.class) + != association.worldPrepareFields().localVersionKey()) { + throw invalid( + "Current World lifecycle row differs from its exact canonical owner association"); + } + long lifecycleEpoch = required(row, "lifecycle_epoch", Long.class); + long rowVersion = required(row, "row_version", Long.class); + if (lifecycleEpoch <= 0 || rowVersion < 0) { + throw invalid("Current World lifecycle row has an invalid epoch or row version"); + } + return row; + } + + private static boolean matchesRequest( + WorldCanonicalInstanceLifecycleEvidence.Request request, + WorldCanonicalInstanceAssociation association) { + var identity = association.identity(); + var binding = association.completeLaunchBinding(); + var release = binding.evidence().releaseAttestation(); + return request.canonicalGameInstanceId().equals(identity.canonicalGameInstanceId()) + && request.targetNamespace().equals(identity.targetNamespace()) + && request.canonicalTenantId().equals(identity.canonicalTenantId()) + && request.worldSlug().equals(identity.worldSlug()) + && request.playableStateNamespaceId().equals(identity.playableStateNamespaceId()) + && request.playableStateScope().equals(identity.playableStateScope()) + && request.publicProduction() == identity.publicProduction() + && request.controlPlaneRequestId().equals(identity.controlPlaneRequestId()) + && request.canonicalVersionId().equals(association.canonicalVersionId()) + && request.expectedDescriptorRequestDigest().equals(binding.descriptor().requestDigest()) + && request.expectedDescriptorResultDigest().equals(binding.descriptor().resultDigest()) + && request.expectedReleaseAttestationDigest().equals(release.evidenceDigest()); + } + + private static JsonNode parseInput(String inputJson) { + try { + JsonNode input = CLOSED_JSON.readTree(inputJson); + requireFields(input, INPUT_FIELDS, "Retained World preparation input"); + if (intValue(input, "schemaVersion") != 2) { + throw invalid("Receipt-less retained V1 preparation cannot produce lifecycle evidence"); + } + if (!CLOSED_JSON.writeValueAsString(input).equals(inputJson)) { + throw invalid("Retained World preparation input is not in its original closed form"); + } + return input; + } catch (tools.jackson.core.JacksonException invalidJson) { + throw new InvalidLifecycleEvidenceException( + "Retained World preparation input is not closed JSON", invalidJson); + } + } + + private static void requireFields(JsonNode value, Set expected, String label) { + if (value == null || !value.isObject()) throw invalid(label + " must be an object"); + Set actual = new java.util.HashSet<>(); + value.propertyNames().forEach(actual::add); + if (!actual.equals(expected)) throw invalid(label + " has missing or unsupported fields"); + } + + private static void requireSourceEvidenceObject( + JsonNode retained, AuthoredWorldSourceEvidence evidence) { + JsonNode actual = requiredObject(retained, "sourceEvidence"); + Set fields = + Set.of( + "schemaVersion", + "registrationRequestId", + "sourceOperationId", + "requestDigest", + "canonicalTenantId", + "tenantSlug", + "worldSlug", + "worldDisplayName", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + requireFields(actual, fields, "Retained World source evidence"); + requireInteger(actual, "schemaVersion", evidence.schemaVersion()); + requireText(actual, "registrationRequestId", evidence.registrationRequestId().toString()); + requireText(actual, "sourceOperationId", evidence.operationId().toString()); + requireText(actual, "requestDigest", evidence.requestDigest()); + requireText(actual, "canonicalTenantId", evidence.canonicalTenantId().toString()); + requireText(actual, "tenantSlug", evidence.tenantSlug()); + requireText(actual, "worldSlug", evidence.worldSlug()); + requireText(actual, "worldDisplayName", evidence.worldDisplayName()); + requireInteger(actual, "sourceGameRowId", evidence.sourceGameRowId()); + requireText(actual, "sourceGameTenantKey", evidence.sourceGameTenantKey()); + requireText(actual, "provenanceKind", evidence.provenanceKind()); + requireText(actual, "evidenceDigest", evidence.evidenceDigest()); + } + + private static JsonNode requiredObject(JsonNode parent, String field) { + JsonNode value = parent.get(field); + if (value == null || !value.isObject()) throw invalid(field + " must be an object"); + return value; + } + + private static String text(JsonNode parent, String field) { + JsonNode value = parent == null ? null : parent.get(field); + if (value == null || !value.isTextual() || value.textValue().isBlank()) { + throw invalid("Retained World preparation " + field + " is missing"); + } + return value.textValue(); + } + + private static UUID parseCanonicalUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (parsed.equals(new UUID(0L, 0L)) || !parsed.toString().equals(value)) { + throw invalid(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(label + " must be a canonical non-nil UUID"); + } + } + + private static void requireText(JsonNode parent, String field, String expected) { + JsonNode value = parent.get(field); + if (value == null || !value.isTextual() || !expected.equals(value.textValue())) { + throw invalid("Retained World preparation " + field + " differs from its exact owner input"); + } + } + + private static void requireBoolean(JsonNode parent, String field, boolean expected) { + JsonNode value = parent.get(field); + if (value == null || !value.isBoolean() || expected != value.booleanValue()) { + throw invalid("Retained World preparation " + field + " differs from its exact owner input"); + } + } + + private static void requireInteger(JsonNode parent, String field, long expected) { + JsonNode value = parent.get(field); + if (value == null + || !value.isIntegralNumber() + || !value.canConvertToLong() + || expected != value.longValue()) { + throw invalid("Retained World preparation " + field + " differs from its exact owner input"); + } + } + + private static int intValue(JsonNode parent, String field) { + JsonNode value = parent.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw invalid("Retained World preparation " + field + " must be an integer"); + } + return value.intValue(); + } + + private static String receiptDigestFromEvidence(byte[] selectorBytes) { + return WorldDraftStartLocationEvidence.fromStored( + WorldPublishedStartLocationEvidence.fromStored(selectorBytes).selectorReceiptBytes()) + .receiptDigest(); + } + + private static String digest(byte[] bytes) { + return "sha256:" + HexFormat.of().formatHex(sha256(bytes)); + } + + private static String writeClosedEvidenceJson(Object value) { + try { + return CLOSED_JSON.writeValueAsString(Objects.requireNonNull(value, "value")); + } catch (tools.jackson.core.JacksonException invalid) { + throw new InvalidLifecycleEvidenceException( + "Original World evidence cannot be encoded for exact preparation comparison", invalid); + } + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static T required(Record row, String field, Class type) { + return Objects.requireNonNull(row.get(field, type), "Persisted " + field + " is null"); + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException(label + " must not join an ambient transaction"); + } + } + + private void requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World lifecycle read requires a read-only REPEATABLE READ owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"repeatable read".equals(state.get("isolation", String.class)) + || !"on".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World lifecycle read requires a read-only REPEATABLE READ owner transaction"); + } + } + + private void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World activation evidence requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + String actualIsolation = required(state, "isolation", String.class); + if (!"read committed".equals(actualIsolation) + || !"off".equals(required(state, "read_only", String.class))) { + throw new IllegalStateException( + "World activation evidence requires a writable READ COMMITTED owner transaction"); + } + } + + private static InvalidLifecycleEvidenceException invalid(String message) { + return new InvalidLifecycleEvidenceException(message); + } + + private record RoomMapping(long runtimeRoomInstanceId) { + private RoomMapping { + if (runtimeRoomInstanceId <= 0) throw invalid("Runtime room instance ID must be positive"); + } + } + + public static final class InvalidLifecycleEvidenceException extends IllegalStateException { + public InvalidLifecycleEvidenceException(String message) { + super(message); + } + + public InvalidLifecycleEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java new file mode 100644 index 0000000000..cb23eeebd9 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java @@ -0,0 +1,278 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** + * Typed input and storage result for the owner-private canonical instance materialization cut. + * + *

The input preserves the caller's exact Game Session read tuple, World V26/V27 receipts, and + * the original immutable frozen topology source. It is component input only: construction does not + * authenticate a producer, authorize a release, prove publication delivery, or enable lifecycle + * activation or gameplay admission. + */ +public final class WorldCanonicalInstancePreparation { + private WorldCanonicalInstancePreparation() {} + + /** Complete immutable request to materialize one generation-free selected canonical graph. */ + public record Input( + WorldCanonicalInstanceAssociation.GameSessionReadRequest gameSessionReadRequest, + WorldCanonicalInstanceAssociation.GameSessionReadEvidence gameSessionReadEvidence, + WorldCompleteLaunchBindingReceipt completeLaunchBinding, + WorldAuthoredVersionIdentityReceipt versionIdentity, + WorldCanonicalInstanceTopologyPlan topologyPlan) { + public Input { + Objects.requireNonNull(gameSessionReadRequest, "gameSessionReadRequest"); + Objects.requireNonNull(gameSessionReadEvidence, "gameSessionReadEvidence"); + Objects.requireNonNull(completeLaunchBinding, "completeLaunchBinding"); + Objects.requireNonNull(versionIdentity, "versionIdentity"); + Objects.requireNonNull(topologyPlan, "topologyPlan"); + + // Claim performs the repository's full request-echo and exact V26/V27 source checks without + // allocating or writing anything. The placeholder row id is deliberately not retained. + new WorldCanonicalInstanceAssociation.Claim( + gameSessionReadRequest, + gameSessionReadEvidence, + 1L, + completeLaunchBinding, + versionIdentity); + + var owner = topologyPlan.sourceBinding().plan().ownerBinding(); + if (!topologyPlan.tenantId().equals(versionIdentity.canonicalTenantId()) + || !topologyPlan.versionId().equals(versionIdentity.canonicalVersionId()) + || !owner.targetNamespace().equals(versionIdentity.targetNamespace()) + || !owner.canonicalTenantId().equals(versionIdentity.canonicalTenantId()) + || !owner.canonicalVersionId().equals(versionIdentity.canonicalVersionId()) + || !owner.versionIdentityOperationId().equals(versionIdentity.operationId()) + || !topologyPlan + .sourceBinding() + .plan() + .binding() + .commitId() + .toString() + .equals(topologyPlan.sourceBinding().freeze().appliedCommitId())) { + throw new IllegalArgumentException( + "Canonical preparation topology differs from its exact V27 identity and frozen commit"); + } + requireExactReleaseGraph(completeLaunchBinding.evidence().releaseAttestation(), topologyPlan); + requireGenerationFree(topologyPlan); + if (topologyPlan.regions().isEmpty()) { + throw new IllegalArgumentException("Canonical preparation requires at least one region"); + } + } + + public UUID canonicalGameInstanceId() { + return gameSessionReadEvidence.canonicalGameInstanceId(); + } + + public UUID captureId() { + return topologyPlan.captureId(); + } + } + + /** Durable result reconstructed only after the owner transaction has committed. */ + public record Result( + WorldCanonicalInstanceAssociation association, + UUID captureId, + String graphSha256, + String inputDigest, + int regionCount, + int zoneCount, + int roomCount, + int exitCount, + String storageStatus, + RoomTemplateRef startLocation, + Long runtimeRoomInstanceId) { + public Result { + Objects.requireNonNull(association, "association"); + Objects.requireNonNull(captureId, "captureId"); + Objects.requireNonNull(graphSha256, "graphSha256"); + Objects.requireNonNull(inputDigest, "inputDigest"); + Objects.requireNonNull(storageStatus, "storageStatus"); + if (regionCount <= 0 || zoneCount < 0 || roomCount < 0 || exitCount < 0) { + throw new IllegalArgumentException("Canonical materialization counts are invalid"); + } + if (!"MATERIALIZED_UNVERIFIED".equals(storageStatus)) { + throw new IllegalArgumentException("Unsupported canonical preparation result status"); + } + if ((startLocation == null) != (runtimeRoomInstanceId == null) + || runtimeRoomInstanceId != null && runtimeRoomInstanceId <= 0) { + throw new IllegalArgumentException( + "Canonical selector and runtime mapping must be complete together"); + } + } + + public Result( + WorldCanonicalInstanceAssociation association, + UUID captureId, + String graphSha256, + String inputDigest, + int regionCount, + int zoneCount, + int roomCount, + int exitCount, + String storageStatus) { + this( + association, + captureId, + graphSha256, + inputDigest, + regionCount, + zoneCount, + roomCount, + exitCount, + storageStatus, + null, + null); + } + } + + /** Required intent is rejected before an owner transaction or identifier allocation begins. */ + public static final class GenerationIntentNotSupportedException extends IllegalArgumentException { + public GenerationIntentNotSupportedException(String message) { + super(message); + } + } + + static void requireGenerationFree(WorldCanonicalInstanceTopologyPlan topologyPlan) { + Objects.requireNonNull(topologyPlan, "topologyPlan"); + if (!topologyPlan.generationRules().isEmpty() || !topologyPlan.spawnBindings().isEmpty()) { + throw new GenerationIntentNotSupportedException( + "Canonical preparation cannot allocate or materialize a graph with configured generation or spawn intent"); + } + } + + /** Joins immutable release evidence to the exact selected World checkpoint, including retries. */ + static void requireExactReleaseGraph( + AuthoredWorldReleaseAttestationEvidence release, + WorldCanonicalInstanceTopologyPlan topologyPlan) { + Objects.requireNonNull(release, "release"); + Objects.requireNonNull(topologyPlan, "topologyPlan"); + var source = topologyPlan.sourceBinding(); + var binding = source.plan().binding(); + var owner = source.plan().ownerBinding(); + var freeze = source.freeze(); + var worldParticipants = + release.participantDigests().stream() + .filter(participant -> "WORLD_MANAGEMENT".equals(participant.participantKey())) + .toList(); + if (!release.targetNamespace().equals(owner.targetNamespace()) + || !release.targetNamespace().equals(freeze.targetNamespace()) + || !release.canonicalTenantId().equals(binding.target().canonicalTenantId()) + || !release.canonicalTenantId().equals(topologyPlan.tenantId()) + || !release.canonicalTenantId().equals(freeze.canonicalTenantId()) + || !release.canonicalVersionId().equals(binding.target().canonicalVersionId()) + || !release.canonicalVersionId().equals(topologyPlan.versionId()) + || !release.canonicalVersionId().equals(freeze.canonicalVersionId()) + || !release.commitId().equals(binding.commitId().toString()) + || !release.commitId().equals(freeze.appliedCommitId()) + || !release.publishWorkflowId().equals(freeze.publishWorkflowId()) + || worldParticipants.size() != 1) { + throw new IllegalArgumentException( + "Canonical preparation release differs from the exact selected frozen World graph"); + } + var world = worldParticipants.getFirst(); + if (!world.scopeValue().equals(Long.toString(owner.gameDesignVersionId())) + || world.baseVersionIdPresent() + || world.baseVersionId() != null + || !world.appliedCommitId().equals(freeze.appliedCommitId()) + || !world.contentDigest().equals(freeze.contentDigest()) + || world.digestSchemaVersion() + != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + "WORLD_MANAGEMENT") + || world.digestSchemaVersion() != freeze.digestSchemaVersion()) { + throw new IllegalArgumentException( + "Canonical preparation World participant differs from its exact frozen checkpoint"); + } + // The freeze observes the Draft epoch; the descriptor attests the later published Version + // epoch. Those distinct lifecycle observations must not be treated as an equality join. + requireExactSelector(release, topologyPlan); + } + + /** V1 remains inert history; v2 must carry the complete original selector and frozen request. */ + static void requireExactSelector( + AuthoredWorldReleaseAttestationEvidence release, + WorldCanonicalInstanceTopologyPlan topologyPlan) { + if (release.schemaVersion() == AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION) return; + var selector = + Objects.requireNonNull(release.worldStartLocationEvidence(), "World selector evidence"); + var freeze = topologyPlan.sourceBinding().freeze(); + var expected = + new WorldPublishedStartLocationEvidence.Request( + freeze.targetNamespace(), + freeze.canonicalTenantId(), + freeze.canonicalVersionId(), + freeze.intakeRequestId(), + freeze.publicationFence(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + freeze.contentDigest(), + freeze.digestSchemaVersion(), + freeze.suppliedOwnedAffectedTuples().stream() + .map( + tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()); + var receipt = WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + var declaration = + topologyPlan + .sourceBinding() + .plan() + .graph() + .freshGraphDeclaration() + .orElseThrow( + () -> + new IllegalArgumentException( + "Selected World graph has no original fresh declaration")); + if (!selector.request().equals(expected) + || !declaration.startLocation().equals(receipt.startLocation()) + || !receipt.bindingDigest().equals(topologyPlan.sourceBinding().plan().binding().digest()) + || topologyPlan.rooms().stream() + .filter( + room -> + room.identity() + .templateId() + .equals(receipt.startLocation().roomTemplateId())) + .count() + != 1) { + throw new IllegalArgumentException( + "Release selector differs from the exact frozen request, declaration or ROOM"); + } + } + + static int entryCount(Input input, EntryType family) { + Objects.requireNonNull(input, "input"); + Objects.requireNonNull(family, "family"); + return (int) + input.topologyPlan().entries().stream().filter(entry -> matches(entry, family)).count(); + } + + private static boolean matches(WorldCanonicalInstanceTopologyPlan.Entry entry, EntryType family) { + return switch (family) { + case REGION -> entry instanceof WorldCanonicalInstanceTopologyPlan.Region; + case ZONE -> entry instanceof WorldCanonicalInstanceTopologyPlan.Zone; + case ROOM -> entry instanceof WorldCanonicalInstanceTopologyPlan.Room; + case ROOM_EXIT -> entry instanceof WorldCanonicalInstanceTopologyPlan.RoomExit; + }; + } + + enum EntryType { + REGION, + ZONE, + ROOM, + ROOM_EXIT + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java new file mode 100644 index 0000000000..bbe3963271 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java @@ -0,0 +1,324 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Read-only assembly of exact persisted World preparation inputs and authenticated owner reads. + * + *

This component does not materialize, authorize, or claim World lifecycle state. In particular, + * the Game Session status is preserved as transient read evidence; a later caller remains + * responsible for its separate fresh-STARTING and held-authority checks. + */ +public final class WorldCanonicalInstancePreparationAssemblyService { + private final String workloadNamespace; + private final WorldCompleteLaunchBindingRepository launchBindings; + private final WorldAuthoredSourceIntakeRepository sourceIntakes; + private final WorldAuthoredVersionIdentityRepository versionIdentities; + private final WorldCanonicalFrozenTopologyRepository frozenTopologies; + private final CanonicalGameInstanceLaunchAssociationClient gameSessionClient; + private final AuthoredWorldLaunchDescriptorClient gameDesignClient; + + public WorldCanonicalInstancePreparationAssemblyService( + String workloadNamespace, + WorldCompleteLaunchBindingRepository launchBindings, + WorldAuthoredSourceIntakeRepository sourceIntakes, + WorldAuthoredVersionIdentityRepository versionIdentities, + WorldCanonicalFrozenTopologyRepository frozenTopologies, + CanonicalGameInstanceLaunchAssociationClient gameSessionClient, + AuthoredWorldLaunchDescriptorClient gameDesignClient) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "World workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.launchBindings = Objects.requireNonNull(launchBindings, "launchBindings"); + this.sourceIntakes = Objects.requireNonNull(sourceIntakes, "sourceIntakes"); + this.versionIdentities = Objects.requireNonNull(versionIdentities, "versionIdentities"); + this.frozenTopologies = Objects.requireNonNull(frozenTopologies, "frozenTopologies"); + this.gameSessionClient = Objects.requireNonNull(gameSessionClient, "gameSessionClient"); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); + } + + /** + * Reconstructs an input using only the stable canonical selector and independently authenticated + * immutable owner readbacks. It never calls a World claim, bind, accept, or capture operation. + */ + public WorldCanonicalInstancePreparation.Input assemble(Selector selector) { + Objects.requireNonNull(selector, "selector"); + requireNoAmbientTransaction(); + + WorldCompleteLaunchBindingRepository.StoredBinding storedBinding = + launchBindings + .read(workloadNamespace, selector.canonicalTenantId(), selector.controlPlaneRequestId()) + .orElseThrow( + () -> + new AssemblyRejectedException( + "No committed World complete launch binding matches the stable selector")); + requireStoredSelector(storedBinding, selector); + + WorldAuthoredSourceIntakeReceipt sourceReceipt = + sourceIntakes + .read(workloadNamespace, storedBinding.intakeRequestId()) + .orElseThrow( + () -> + new AssemblyRejectedException( + "World launch binding has no exact committed source intake")); + WorldCompleteLaunchBindingReceipt launchBinding = + launchBindings.toReceipt(storedBinding, sourceReceipt); + + var descriptor = launchBinding.descriptor(); + var release = launchBinding.evidence().releaseAttestation(); + if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || release.worldStartLocationEvidence() == null) { + throw new AssemblyRejectedException( + "Canonical preparation requires the stored v2 release selector and original frozen request"); + } + + // The UUID is the canonical selector. Never resolve the Game Design numeric Version ID here. + WorldAuthoredVersionIdentityReceipt versionIdentity = + versionIdentities + .readByCanonicalVersion( + workloadNamespace, + selector.canonicalTenantId(), + descriptor.worldSlug(), + release.canonicalVersionId()) + .orElseThrow( + () -> + new AssemblyRejectedException( + "World has no committed source-qualified Version identity for the release UUID")); + if (!versionIdentity.sourceIntakeReceipt().equals(sourceReceipt) + || !versionIdentity.canonicalVersionId().equals(release.canonicalVersionId()) + || !versionIdentity.worldSlug().equals(descriptor.worldSlug())) { + throw new AssemblyRejectedException( + "World Version identity differs from the exact committed launch source and release"); + } + + CaptureRequest captureRequest = captureRequest(release.worldStartLocationEvidence()); + WorldCanonicalFrozenTopology frozen = + frozenTopologies + .readCommitted(captureRequest) + .orElseThrow( + () -> + new AssemblyRejectedException( + "Published release selector has no exact committed frozen World topology")); + WorldCanonicalInstanceTopologyPlan topologyPlan = + WorldCanonicalInstanceTopologyPlan.create(frozen); + WorldCanonicalInstancePreparation.requireExactReleaseGraph(release, topologyPlan); + + // Independently authenticate the complete immutable descriptor/release pair with Game Design. + GetLaunchDescriptorRequest gameDesignReadRequest = gameDesignReadRequest(launchBinding); + CompleteLaunchBindingEvidence gameDesignBinding = + gameDesignClient.getComplete(gameDesignReadRequest); + requireSameCompletePair(launchBinding.evidence(), gameDesignBinding); + + var associationRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + newReadRequestId( + descriptor, + selector.canonicalGameInstanceId(), + UUID.fromString(gameDesignReadRequest.getRequestId())), + workloadNamespace, + selector.canonicalTenantId(), + descriptor.worldSlug(), + selector.canonicalGameInstanceId(), + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + CanonicalGameInstanceLaunchAssociationReadEvidence.Result association = + gameSessionClient.read(associationRequest); + requireGameSessionBinding(associationRequest, association, launchBinding.evidence()); + + var evidence = associationToWorldEvidence(associationRequest, association); + return new WorldCanonicalInstancePreparation.Input( + new WorldCanonicalInstanceAssociation.GameSessionReadRequest( + associationRequest.readRequestId(), + associationRequest.targetNamespace(), + associationRequest.canonicalTenantId(), + associationRequest.worldSlug(), + associationRequest.gameInstanceUuid(), + associationRequest.controlPlaneRequestId(), + associationRequest.launchDescriptorId(), + associationRequest.expectedDescriptorRequestDigest(), + associationRequest.expectedDescriptorResultDigest(), + associationRequest.expectedReleaseAttestationEvidenceDigest()), + evidence, + launchBinding, + versionIdentity, + topologyPlan); + } + + private static CaptureRequest captureRequest(WorldPublishedStartLocationEvidence selector) { + var request = Objects.requireNonNull(selector, "World release selector").request(); + return new CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples().stream() + .map( + tuple -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()); + } + + private GetLaunchDescriptorRequest gameDesignReadRequest( + WorldCompleteLaunchBindingReceipt launchBinding) { + AuthoredWorldLaunchDescriptorEvidence descriptor = launchBinding.descriptor(); + UUID requestId = newReadRequestId(descriptor, null, null); + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(requestId.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + } + + private static UUID newReadRequestId( + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID canonicalGameInstanceId, + UUID otherReadRequestId) { + UUID candidate; + do { + candidate = UUID.randomUUID(); + } while (candidate.equals(descriptor.authoredWorldSourceOperationId()) + || candidate.toString().equals(descriptor.controlPlaneRequestId()) + || candidate.equals(canonicalGameInstanceId) + || candidate.equals(otherReadRequestId)); + return candidate; + } + + private void requireStoredSelector( + WorldCompleteLaunchBindingRepository.StoredBinding stored, Selector selector) { + if (!workloadNamespace.equals(stored.targetNamespace()) + || !selector.canonicalTenantId().equals(stored.canonicalTenantId()) + || !selector.controlPlaneRequestId().equals(stored.controlPlaneRequestId())) { + throw new AssemblyRejectedException( + "World complete launch binding differs from the stable tenant/request selector"); + } + } + + static void requireSameCompletePair( + CompleteLaunchBindingEvidence expected, CompleteLaunchBindingEvidence actual) { + if (actual == null + || !expected.equals(actual) + || !expected.descriptor().equals(actual.descriptor()) + || !expected.releaseAttestation().equals(actual.releaseAttestation()) + || !expected.descriptor().requestDigest().equals(actual.descriptor().requestDigest()) + || !expected.descriptor().resultDigest().equals(actual.descriptor().resultDigest()) + || !expected + .releaseAttestation() + .evidenceDigest() + .equals(actual.releaseAttestation().evidenceDigest())) { + throw new AssemblyRejectedException( + "Authenticated Game Design complete launch pair differs from the committed World pair"); + } + } + + static void requireGameSessionBinding( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request, + CanonicalGameInstanceLaunchAssociationReadEvidence.Result result, + CompleteLaunchBindingEvidence expected) { + if (result == null + || !request.equals(result.request()) + || result.playableStateScope() != RealmEntryPolicy.StateScope.SHARED + || !result.publicProduction() + || !expected.equals(result.launchBindingEvidence()) + || !expected.descriptor().equals(result.launchBindingEvidence().descriptor()) + || !expected + .releaseAttestation() + .equals(result.launchBindingEvidence().releaseAttestation())) { + throw new AssemblyRejectedException( + "Authenticated Game Session association differs from the exact World selector or release pair"); + } + } + + static WorldCanonicalInstanceAssociation.GameSessionReadEvidence associationToWorldEvidence( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request, + CanonicalGameInstanceLaunchAssociationReadEvidence.Result result) { + var pair = result.launchBindingEvidence(); + return new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + request.readRequestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.gameInstanceUuid(), + request.controlPlaneRequestId(), + request.launchDescriptorId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationEvidenceDigest(), + result.playableStateNamespaceId(), + result.playableStateScope().name(), + result.publicProduction(), + result.currentGameInstanceStatus().name(), + result.currentRowVersion(), + pair.descriptor(), + pair.releaseAttestation()); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical World preparation input assembly requires independent committed reads"); + } + } + + /** The only caller-selected fields; every other World/owner selector is derived from storage. */ + public record Selector( + UUID canonicalTenantId, UUID canonicalGameInstanceId, String controlPlaneRequestId) { + public Selector { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + if (controlPlaneRequestId == null + || controlPlaneRequestId.isBlank() + || controlPlaneRequestId.length() > 128) { + throw new IllegalArgumentException("controlPlaneRequestId must be non-blank and bounded"); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + } + + public static final class AssemblyRejectedException extends IllegalStateException { + public AssemblyRejectedException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java new file mode 100644 index 0000000000..85c6758afd --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java @@ -0,0 +1,346 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationGrpcCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Result; +import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstancePreparationServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone authenticated canonical preparation adapter; intentionally not runtime-registered. */ +public final class WorldCanonicalInstancePreparationGrpcService + extends WorldCanonicalInstancePreparationServiceGrpc + .WorldCanonicalInstancePreparationServiceImplBase { + private final WorldCompleteLaunchBindingService launchBindingService; + private final WorldCanonicalInstancePreparationAssemblyService assemblyService; + private final WorldCanonicalInstancePreparationService preparationService; + private final WorldCanonicalInstancePreparationRepository preparationRepository; + private final WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository; + private final String trustedNamespace; + + public WorldCanonicalInstancePreparationGrpcService( + WorldCompleteLaunchBindingService launchBindingService, + WorldCanonicalInstancePreparationAssemblyService assemblyService, + WorldCanonicalInstancePreparationService preparationService, + WorldCanonicalInstancePreparationRepository preparationRepository, + WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository, + String trustedNamespace) { + this.launchBindingService = + Objects.requireNonNull(launchBindingService, "launchBindingService"); + this.assemblyService = Objects.requireNonNull(assemblyService, "assemblyService"); + this.preparationService = Objects.requireNonNull(preparationService, "preparationService"); + this.preparationRepository = + Objects.requireNonNull(preparationRepository, "preparationRepository"); + this.lifecycleRepository = Objects.requireNonNull(lifecycleRepository, "lifecycleRepository"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void prepareCanonicalWorldInstance( + PrepareCanonicalWorldInstanceRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameSessionPeer(responseObserver)) return; + if (hasAmbientTransaction()) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World preparation requires independent owner operations"); + return; + } + + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector; + try { + selector = CanonicalWorldInstancePreparationGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A complete canonical World preparation selector is required"); + return; + } + if (!trustedNamespace.equals(selector.targetNamespace())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World preparation namespace must match the authenticated peer"); + return; + } + + try { + WorldCompleteLaunchBindingReceipt bound = launchBindingService.bindCommittedLaunch(selector); + WorldCanonicalInstancePreparationAssemblyService.Selector assemblySelector = + new WorldCanonicalInstancePreparationAssemblyService.Selector( + selector.canonicalTenantId(), + selector.gameInstanceUuid(), + selector.controlPlaneRequestId()); + Input input = assemblyService.assemble(assemblySelector); + requireAssembledInputMatches(selector, bound, input); + + // This independent read proves only that the exact immutable input was previously retained. + // New materialization still requires STARTING and always passes through the held verifier. + Optional retained = preparationRepository.readOwnerPreparation(input); + if (retained.isEmpty() + && !"STARTING".equals(input.gameSessionReadEvidence().currentGameSessionStatus())) { + throw new PreparationPreconditionException( + "Fresh canonical World preparation requires the actual Game Session STARTING state"); + } + + // Exact retries deliberately re-enter prepare so its current source verifier and continuously + // held commit authority remain mandatory through the real owner transaction. + Result prepared = preparationService.prepare(input); + if (prepared == null) { + throw new PreparationPreconditionException( + "Canonical World preparation returned no committed materialization result"); + } + requirePreparedResultMatchesInput(input, prepared); + + Request lifecycleRequest = lifecycleRequest(selector, input); + WorldCanonicalInstanceLifecycleEvidence lifecycle = + lifecycleRepository + .read(lifecycleRequest) + .orElseThrow( + () -> + new PreparationPreconditionException( + "Canonical World lifecycle readback is required after materialization")); + requireLifecycleMatchesPreparation(lifecycleRequest, input, prepared, lifecycle); + + PrepareCanonicalWorldInstanceResponse response = + CanonicalWorldInstancePreparationGrpcCodec.toResponse(selector, lifecycle); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (SecurityException denied) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World preparation producer or namespace evidence was denied"); + } catch (WorldCanonicalInstancePreparationService.PreparationDeniedException denied) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World preparation authority was denied"); + } catch (TransientDataAccessException | DataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Canonical World preparation storage is temporarily unavailable"); + } catch (StatusRuntimeException ownerFailure) { + failForOwnerRpcFailure(responseObserver, ownerFailure); + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World preparation evidence is unavailable or inconsistent"); + } catch (RuntimeException failure) { + fail(responseObserver, Status.INTERNAL, "Canonical World preparation failed"); + } + } + + private static void requireAssembledInputMatches( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector, + WorldCompleteLaunchBindingReceipt bound, + Input input) { + if (bound == null || input == null) { + throw new PreparationPreconditionException( + "Canonical World preparation requires exact bound and assembled launch evidence"); + } + var request = input.gameSessionReadRequest(); + var gameSession = input.gameSessionReadEvidence(); + var completeBinding = input.completeLaunchBinding(); + var pair = completeBinding.evidence(); + var descriptor = pair.descriptor(); + var release = pair.releaseAttestation(); + + // The assembly performs fresh internal Game Session reads and therefore owns distinct read + // UUIDs. Every immutable selector, original pair and digest must still match the outer call. + boolean requestMatches = + selector.targetNamespace().equals(request.targetNamespace()) + && selector.canonicalTenantId().equals(request.canonicalTenantId()) + && selector.worldSlug().equals(request.worldSlug()) + && selector.gameInstanceUuid().equals(request.canonicalGameInstanceId()) + && selector.controlPlaneRequestId().equals(request.controlPlaneRequestId()) + && selector.launchDescriptorId().equals(request.launchDescriptorId()) + && selector + .expectedDescriptorRequestDigest() + .equals(request.expectedDescriptorRequestDigest()) + && selector + .expectedDescriptorResultDigest() + .equals(request.expectedDescriptorResultDigest()) + && selector + .expectedReleaseAttestationEvidenceDigest() + .equals(request.expectedReleaseAttestationEvidenceDigest()); + boolean gameSessionMatches = + selector.targetNamespace().equals(gameSession.targetNamespace()) + && selector.canonicalTenantId().equals(gameSession.canonicalTenantId()) + && selector.worldSlug().equals(gameSession.worldSlug()) + && selector.gameInstanceUuid().equals(gameSession.canonicalGameInstanceId()) + && selector.controlPlaneRequestId().equals(gameSession.controlPlaneRequestId()) + && selector.launchDescriptorId().equals(gameSession.launchDescriptorId()) + && selector + .expectedDescriptorRequestDigest() + .equals(gameSession.descriptorRequestDigest()) + && selector + .expectedDescriptorResultDigest() + .equals(gameSession.descriptorResultDigest()) + && selector + .expectedReleaseAttestationEvidenceDigest() + .equals(gameSession.releaseAttestationEvidenceDigest()) + && request.readRequestId().equals(gameSession.readRequestId()) + && descriptor.equals(gameSession.descriptor()) + && release.equals(gameSession.releaseAttestation()); + boolean bindingMatches = + selector.targetNamespace().equals(bound.targetNamespace()) + && selector.canonicalTenantId().equals(bound.canonicalTenantId()) + && selector.worldSlug().equals(bound.worldSlug()) + && selector.controlPlaneRequestId().equals(bound.controlPlaneRequestId()) + && bound.equals(completeBinding) + && bound.evidence().equals(pair) + && selector.targetNamespace().equals(descriptor.targetNamespace()) + && selector.canonicalTenantId().equals(descriptor.canonicalTenantId()) + && selector.worldSlug().equals(descriptor.worldSlug()) + && selector.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + && selector.launchDescriptorId().equals(descriptor.launchDescriptorId()) + && selector.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + && selector.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + && selector.targetNamespace().equals(release.targetNamespace()) + && selector.canonicalTenantId().equals(release.canonicalTenantId()) + && selector.worldSlug().equals(release.worldSlug()) + && selector.launchDescriptorId().equals(release.launchDescriptorId()) + && selector.expectedDescriptorResultDigest().equals(release.descriptorResultDigest()) + && selector.expectedReleaseAttestationEvidenceDigest().equals(release.evidenceDigest()); + + if (!requestMatches || !gameSessionMatches || !bindingMatches) { + throw new PreparationPreconditionException( + "Assembled canonical World input differs from the complete outer launch selector"); + } + } + + private static void requirePreparedResultMatchesInput(Input input, Result prepared) { + var association = prepared.association(); + if (!input.captureId().equals(prepared.captureId()) + || prepared.startLocation() == null + || prepared.runtimeRoomInstanceId() == null + || !input.gameSessionReadEvidence().canonicalIdentity().equals(association.identity()) + || !input.completeLaunchBinding().equals(association.completeLaunchBinding()) + || !input.versionIdentity().equals(association.versionIdentity()) + || !"MATERIALIZED_UNVERIFIED".equals(prepared.storageStatus())) { + throw new PreparationPreconditionException( + "Canonical World materialization result differs from its immutable preparation input"); + } + } + + private static Request lifecycleRequest( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector, Input input) { + var gameSession = input.gameSessionReadEvidence(); + var descriptor = input.completeLaunchBinding().descriptor(); + var release = input.completeLaunchBinding().evidence().releaseAttestation(); + return new Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + selector.readRequestId(), + gameSession.targetNamespace(), + gameSession.canonicalTenantId(), + gameSession.worldSlug(), + gameSession.canonicalGameInstanceId(), + gameSession.playableStateNamespaceId(), + gameSession.playableStateScope(), + gameSession.publicProduction(), + gameSession.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + } + + private static void requireLifecycleMatchesPreparation( + Request request, + Input input, + Result prepared, + WorldCanonicalInstanceLifecycleEvidence lifecycle) { + var association = prepared.association(); + if (!request.equals(lifecycle.request()) + || !input.completeLaunchBinding().evidence().equals(lifecycle.launchBinding()) + || !prepared.captureId().equals(lifecycle.captureId()) + || !prepared.graphSha256().equals(lifecycle.graphSha256()) + || !prepared.inputDigest().equals(lifecycle.preparationInputDigest()) + || !prepared.startLocation().equals(lifecycle.startLocation()) + || prepared.runtimeRoomInstanceId().longValue() != lifecycle.runtimeRoomInstanceId() + || !input.gameSessionReadEvidence().canonicalIdentity().equals(association.identity()) + || !input.completeLaunchBinding().equals(association.completeLaunchBinding()) + || !input.versionIdentity().equals(association.versionIdentity())) { + throw new PreparationPreconditionException( + "Independent World lifecycle readback differs from the prepared immutable input"); + } + } + + private boolean requireAuthenticatedGameSessionPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-session-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Only the verified same-namespace Game Session workload without end-user context is allowed"); + return false; + } + + private static boolean hasAmbientTransaction() { + return TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive(); + } + + private static void fail(StreamObserver responseObserver, Status status, String description) { + responseObserver.onError(status.withDescription(description).asRuntimeException()); + } + + private static void failForOwnerRpcFailure( + StreamObserver responseObserver, StatusRuntimeException ownerFailure) { + switch (Status.fromThrowable(ownerFailure).getCode()) { + case UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED -> + fail( + responseObserver, + Status.UNAVAILABLE, + "A required canonical owner read is temporarily unavailable"); + case PERMISSION_DENIED, UNAUTHENTICATED -> + fail( + responseObserver, + Status.PERMISSION_DENIED, + "A required canonical owner denied the authenticated producer"); + case INVALID_ARGUMENT -> + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A required canonical owner rejected the request selector"); + case FAILED_PRECONDITION, NOT_FOUND, ALREADY_EXISTS, ABORTED -> + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Required canonical owner evidence is unavailable or inconsistent"); + default -> fail(responseObserver, Status.INTERNAL, "Canonical owner read failed"); + } + } + + private static final class PreparationPreconditionException extends IllegalStateException { + private PreparationPreconditionException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java new file mode 100644 index 0000000000..cf3c5fc20f --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -0,0 +1,824 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Result; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.Entry; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * World-owned storage for generation-free canonical instance materialization. + * + *

This repository is deliberately not registered as a Spring component. The only write path is + * the exact V35 database function, followed in the same transaction by V34 association retention. + * It reads the immutable V31 capture independently before writing and reconstructs the exact result + * only after commit. + */ +public final class WorldCanonicalInstancePreparationRepository { + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final WorldCanonicalInstanceAssociationRepository associationRepository; + private final WorldCanonicalFrozenTopologyRepository frozenTopologyRepository; + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; + private final WorldCompleteLaunchBindingRepository launchBindingRepository; + private final WorldAuthoredVersionIdentityRepository versionIdentityRepository; + + public WorldCanonicalInstancePreparationRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceAssociationRepository associationRepository, + WorldCanonicalFrozenTopologyRepository frozenTopologyRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.associationRepository = + Objects.requireNonNull(associationRepository, "associationRepository"); + this.frozenTopologyRepository = + Objects.requireNonNull(frozenTopologyRepository, "frozenTopologyRepository"); + sourceIntakeRepository = new WorldAuthoredSourceIntakeRepository(dsl); + launchBindingRepository = new WorldCompleteLaunchBindingRepository(dsl); + versionIdentityRepository = new WorldAuthoredVersionIdentityRepository(dsl); + transaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Runs the one owner transaction, then independently reads its committed immutable result. The + * supplied continuously held authority handle remains valid through the transaction manager's + * commit path. + */ + public Result materialize( + Input input, WorldCanonicalInstancePreparationService.HeldCommitAuthority authority) { + Objects.requireNonNull(input, "input"); + Objects.requireNonNull(authority, "authority"); + requireNoActiveTransaction("Canonical World preparation"); + requireExactOriginalBindings(input); + requireExactFrozenSource(input); + String inputJson = inputJson(input); + String inputDigest = digest(inputJson.getBytes(StandardCharsets.UTF_8)); + + MaterializedInstance committed = + Objects.requireNonNull( + transaction.execute( + status -> { + requireWritableReadCommittedTransaction(); + authority.requireHeld(); + Record row = + Objects.requireNonNull( + fetchCanonicalPreparation(inputJson, inputDigest), + "V35 canonical preparation function returned no row"); + MaterializedInstance materialized = + new MaterializedInstance( + required(row, "world_instance_id", Long.class), + required(row, "private_game_instance_key", Long.class)); + WorldCanonicalInstanceAssociation.Claim claim = + new WorldCanonicalInstanceAssociation.Claim( + input.gameSessionReadRequest(), + input.gameSessionReadEvidence(), + materialized.worldInstanceId(), + input.completeLaunchBinding(), + input.versionIdentity()); + associationRepository.retainClaimInOwnerTransaction(claim); + authority.requireHeld(); + return materialized; + }), + "Canonical World preparation transaction did not commit"); + + // The authority handle is still open here: TransactionTemplate returned only after commit. + authority.requireHeld(); + Result result = + readOwnerPreparation(input) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Committed canonical World preparation has no independent result readback")); + if (result.association().worldInstanceId() != committed.worldInstanceId()) { + throw new InvalidPreparationEvidenceException( + "Canonical World preparation readback differs from its committed owner row"); + } + return result; + } + + /** + * Calls the V35 writer inside its owner transaction and translates only its explicit + * canonical-identity conflict signals. Throwing the domain exception here keeps the transaction + * rollback behavior while leaving unrelated database uniqueness failures visible as such. + */ + private Record fetchCanonicalPreparation(String inputJson, String inputDigest) { + try { + return dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?, ?)", inputJson, inputDigest); + } catch (DuplicateKeyException exception) { + throw translateCanonicalPreparationConflict(exception); + } + } + + static RuntimeException translateCanonicalPreparationConflict(DuplicateKeyException exception) { + for (Throwable cause = exception; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException + && "23505".equals(sqlException.getSQLState()) + && isCanonicalPreparationConflictMessage(sqlException.getMessage())) { + return new ConflictingPreparationException( + "Canonical gameInstanceId is already bound to a different preparation", exception); + } + } + return exception; + } + + private static boolean isCanonicalPreparationConflictMessage(String message) { + if (message == null) return false; + String ownerMessage = message.lines().findFirst().orElse(""); + if (ownerMessage.startsWith("ERROR: ")) ownerMessage = ownerMessage.substring(7); + return ownerMessage.equals( + "Canonical gameInstanceId is already bound to a different preparation") + || ownerMessage.equals("Canonical game instance or request identity is already reserved"); + } + + /** Independent exact read; lifecycle state is intentionally absent from the retained result. */ + public Optional readOwnerPreparation(Input input) { + Objects.requireNonNull(input, "input"); + requireNoActiveTransaction("Canonical World preparation readback"); + WorldCanonicalInstancePreparation.requireExactReleaseGraph( + input.completeLaunchBinding().evidence().releaseAttestation(), input.topologyPlan()); + String inputJson = inputJson(input); + String inputDigest = digest(inputJson.getBytes(StandardCharsets.UTF_8)); + Record row = + dsl.fetchOne( + "SELECT canonical_game_instance_id, capture_id, graph_sha256, input_digest, input_json, " + + "graph_bytes, world_instance_id, private_game_instance_key, region_count, zone_count, " + + "room_count, exit_count, storage_status " + + "FROM world_canonical_instance_preparation WHERE canonical_game_instance_id = ?", + input.canonicalGameInstanceId()); + if (row == null) return Optional.empty(); + + if (!inputDigest.equals(required(row, "input_digest", String.class)) + || !inputJson.equals(required(row, "input_json", String.class)) + || !input.captureId().equals(required(row, "capture_id", java.util.UUID.class))) { + throw new ConflictingPreparationException( + "Canonical gameInstanceId is already bound to a different complete preparation input"); + } + byte[] graphBytes = required(row, "graph_bytes", byte[].class); + String graphSha256 = required(row, "graph_sha256", String.class); + if (!HexFormat.of().formatHex(sha256(graphBytes)).equals(graphSha256)) { + throw new InvalidPreparationEvidenceException( + "Retained canonical preparation graph bytes differ from their immutable digest"); + } + + WorldCanonicalInstanceAssociation association = + associationRepository + .readOwnerAssociation(input.canonicalGameInstanceId()) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Canonical World preparation result lost its exact V34 association")); + if (!association.identity().equals(input.gameSessionReadEvidence().canonicalIdentity()) + || !association.completeLaunchBinding().equals(input.completeLaunchBinding()) + || !association.versionIdentity().equals(input.versionIdentity()) + || association.worldInstanceId() != required(row, "world_instance_id", Long.class)) { + throw new InvalidPreparationEvidenceException( + "Canonical World preparation association differs from its complete immutable input"); + } + + int regions = required(row, "region_count", Integer.class); + int zones = required(row, "zone_count", Integer.class); + int rooms = required(row, "room_count", Integer.class); + int exits = required(row, "exit_count", Integer.class); + if (regions != input.topologyPlan().regions().size() + || zones != input.topologyPlan().zones().size() + || rooms != input.topologyPlan().rooms().size() + || exits != input.topologyPlan().roomExits().size()) { + throw new InvalidPreparationEvidenceException( + "Canonical World preparation readback omitted or added a selected topology family row"); + } + var selector = + input.completeLaunchBinding().evidence().releaseAttestation().worldStartLocationEvidence(); + RoomTemplateRef startLocation = null; + Long runtimeRoomInstanceId = null; + if (selector != null) { + requireExactOriginalSelector(input, graphBytes); + var receipt = WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + Record selected = + dsl.fetchOne( + "SELECT s.*, m.runtime_room_instance_id AS mapped_room_instance_id, " + + "r.room_instance_row_id AS actual_room_instance_id,r.tenant_id AS room_tenant_key,r.game_instance_id AS room_game_instance_key " + + "FROM world_canonical_preparation_start_location s " + + "JOIN world_canonical_instance_topology_identity m ON m.world_instance_id=s.world_instance_id " + + "AND m.canonical_game_instance_id=s.canonical_game_instance_id AND m.family='ROOM' " + + "AND m.template_id=s.room_template_id JOIN room_instance r ON r.id=m.runtime_row_id " + + "WHERE s.canonical_game_instance_id=?", + input.canonicalGameInstanceId()); + if (selected == null + || !Arrays.equals( + selector.canonicalBytes(), required(selected, "evidence_bytes", byte[].class)) + || !receipt + .startLocation() + .tenantId() + .equals(required(selected, "canonical_tenant_id", java.util.UUID.class)) + || !receipt + .startLocation() + .versionId() + .equals(required(selected, "canonical_version_id", java.util.UUID.class)) + || !receipt + .startLocation() + .roomTemplateId() + .equals(required(selected, "room_template_id", java.util.UUID.class)) + || !receipt.receiptDigest().equals(required(selected, "receipt_digest", String.class)) + || !receipt.graphDigest().equals(required(selected, "graph_digest", String.class)) + || !Objects.equals( + required(selected, "runtime_room_instance_id", Long.class), + required(selected, "mapped_room_instance_id", Long.class)) + || !Objects.equals( + required(selected, "runtime_room_instance_id", Long.class), + required(selected, "actual_room_instance_id", Long.class)) + || required(selected, "room_tenant_key", Long.class) + != input.versionIdentity().sourceIntakeReceipt().localTenantKey() + || !Objects.equals( + required(selected, "room_game_instance_key", Long.class), + required(row, "private_game_instance_key", Long.class)) + || required(selected, "world_instance_id", Long.class) != association.worldInstanceId()) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation lost exact original selector or runtime ROOM mapping"); + } + startLocation = receipt.startLocation(); + runtimeRoomInstanceId = required(selected, "runtime_room_instance_id", Long.class); + } + return Optional.of( + new Result( + association, + input.captureId(), + graphSha256, + inputDigest, + regions, + zones, + rooms, + exits, + required(row, "storage_status", String.class), + startLocation, + runtimeRoomInstanceId)); + } + + private void requireExactFrozenSource(Input input) { + WorldCanonicalFrozenTopology frozen = + frozenTopologyRepository + .readCommitted(input.topologyPlan().sourceBinding()) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Canonical preparation input has no exact committed frozen topology")); + WorldCanonicalInstanceTopologyPlan reconstructed = + WorldCanonicalInstanceTopologyPlan.create(frozen); + if (!frozen.captureId().equals(input.captureId()) + || !matchesCompleteFrozenSource(frozen.request(), input.topologyPlan().sourceBinding()) + || !reconstructed.entries().equals(input.topologyPlan().entries()) + || !reconstructed.regions().equals(input.topologyPlan().regions()) + || !reconstructed.zones().equals(input.topologyPlan().zones()) + || !reconstructed.rooms().equals(input.topologyPlan().rooms()) + || !reconstructed.roomExits().equals(input.topologyPlan().roomExits()) + || !reconstructed.generationRules().equals(input.topologyPlan().generationRules()) + || !reconstructed.spawnBindings().equals(input.topologyPlan().spawnBindings())) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation plan differs from the full immutable capture row/payload/revision/source vector"); + } + WorldCanonicalInstancePreparation.requireGenerationFree(reconstructed); + WorldCanonicalInstancePreparation.requireExactReleaseGraph( + input.completeLaunchBinding().evidence().releaseAttestation(), reconstructed); + requireExactOriginalSelector(input, frozen.graphBytes()); + } + + /** Exact immutable Account/APPLIED/receipt readback; no mutable remote owner read. */ + private void requireExactOriginalSelector(Input input, byte[] graphBytes) { + var evidence = + input.completeLaunchBinding().evidence().releaseAttestation().worldStartLocationEvidence(); + if (evidence == null) return; + var receipt = WorldDraftStartLocationEvidence.fromStored(evidence.selectorReceiptBytes()); + Record original = + dsl.fetchOne( + "SELECT s.receipt_bytes,s.account_binding_bytes,s.graph_digest,a.result_bytes,g.graph_bytes " + + "FROM world_draft_start_location_receipt s JOIN world_draft_graph_application a " + + "ON a.operation_id=s.operation_id AND a.request_id=s.request_id AND a.commit_id=s.commit_id " + + "AND a.authorization_fence_id=s.authorization_fence_id " + + "JOIN world_topology_draft_commit g ON g.request_id=s.request_id AND g.commit_id=s.commit_id " + + "WHERE s.operation_id=? AND s.target_namespace=? AND s.canonical_tenant_id=? " + + "AND s.canonical_version_id=? AND s.room_template_id=?", + receipt.operationId(), + receipt.targetNamespace(), + receipt.startLocation().tenantId(), + receipt.startLocation().versionId(), + receipt.startLocation().roomTemplateId()); + if (original == null + || !Arrays.equals( + evidence.selectorReceiptBytes(), required(original, "receipt_bytes", byte[].class)) + || !Arrays.equals( + evidence.originalAccountBindingBytes(), + required(original, "account_binding_bytes", byte[].class)) + || !Arrays.equals( + evidence.appliedResultBytes(), required(original, "result_bytes", byte[].class)) + || !Arrays.equals(graphBytes, required(original, "graph_bytes", byte[].class)) + || !receipt.graphDigest().equals(digest(graphBytes)) + || !receipt.graphDigest().equals(required(original, "graph_digest", String.class))) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation selector differs from original World Account/APPLIED/graph receipt"); + } + } + + /** + * Compares every immutable value in a frozen request without relying on the enclosing plan's + * object identity. The plan intentionally has no value equality of its own. + */ + static boolean matchesCompleteFrozenSource(Request retained, Request supplied) { + Objects.requireNonNull(retained, "retained"); + Objects.requireNonNull(supplied, "supplied"); + var retainedPlan = retained.plan(); + var suppliedPlan = supplied.plan(); + var retainedGraph = retainedPlan.graph(); + var suppliedGraph = suppliedPlan.graph(); + return retained.freeze().equals(supplied.freeze()) + && retainedPlan.binding().equals(suppliedPlan.binding()) + && retainedPlan.ownerBinding().equals(suppliedPlan.ownerBinding()) + && retainedGraph.tenantId().equals(suppliedGraph.tenantId()) + && retainedGraph.versionId().equals(suppliedGraph.versionId()) + && retainedGraph.freshGraphDeclaration().equals(suppliedGraph.freshGraphDeclaration()) + && retainedGraph.nodes().equals(suppliedGraph.nodes()); + } + + /** Reloads original World-owned source, launch-pair, and Version rows before allocation. */ + private void requireExactOriginalBindings(Input input) { + var launch = input.completeLaunchBinding(); + var source = launch.sourceIntakeReceipt(); + var retainedSource = + sourceIntakeRepository + .read(source.targetNamespace(), source.intakeRequestId()) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Canonical preparation has no exact committed World source intake")); + if (!retainedSource.equals(source)) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation source differs from its complete original immutable intake row"); + } + + var retainedBinding = + launchBindingRepository + .read( + launch.targetNamespace(), + launch.canonicalTenantId(), + launch.controlPlaneRequestId()) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Canonical preparation has no exact committed V26 launch binding")); + if (!retainedBinding.operationId().equals(launch.operationId()) + || !retainedBinding.targetNamespace().equals(launch.targetNamespace()) + || !retainedBinding.canonicalTenantId().equals(launch.canonicalTenantId()) + || !retainedBinding.worldSlug().equals(launch.worldSlug()) + || !retainedBinding.controlPlaneRequestId().equals(launch.controlPlaneRequestId()) + || !retainedBinding.intakeOperationId().equals(source.operationId()) + || !retainedBinding.intakeRequestId().equals(source.intakeRequestId()) + || retainedBinding.localTenantKey() != source.localTenantKey() + || !retainedBinding.sourceOperationId().equals(source.sourceOperationId()) + || !retainedBinding.sourceEvidenceDigest().equals(source.sourceEvidenceDigest()) + || !retainedBinding.intakeReceiptDigest().equals(source.receiptDigest()) + || !retainedBinding.descriptorRequestDigest().equals(launch.descriptor().requestDigest()) + || !retainedBinding.descriptorResultDigest().equals(launch.descriptor().resultDigest()) + || !retainedBinding + .releaseAttestationDigest() + .equals(launch.evidence().releaseAttestation().evidenceDigest()) + || !retainedBinding.evidence().equals(launch.evidence())) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation V26 launch/source bytes differ from the original committed binding"); + } + + var version = input.versionIdentity(); + var retainedVersion = + versionIdentityRepository + .readByCanonicalVersion( + version.targetNamespace(), + version.canonicalTenantId(), + version.worldSlug(), + version.canonicalVersionId()) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Canonical preparation has no exact committed V27 Version identity")); + if (!retainedVersion.equals(version) || !retainedVersion.sourceIntakeReceipt().equals(source)) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation V27 Version/source evidence differs from its original immutable row"); + } + requireExactPublishedTerminal(input); + } + + /** A fresh preparation consumes only the exact retained PUBLISHED terminal release. */ + private void requireExactPublishedTerminal(Input input) { + var source = input.topologyPlan().sourceBinding(); + var release = input.completeLaunchBinding().evidence().releaseAttestation(); + var selector = release.worldStartLocationEvidence(); + if (selector == null) { + throw new InvalidPreparationEvidenceException( + "Fresh canonical preparation requires the complete published World selector terminal"); + } + Record row = + dsl.fetchOne( + "SELECT * " + "FROM world_design_publication_terminal WHERE publication_fence=?", + source.freeze().publicationFence()); + if (row == null || !"PUBLISHED".equals(required(row, "outcome", String.class))) { + throw new InvalidPreparationEvidenceException( + "Fresh canonical preparation requires an exact PUBLISHED World owner terminal"); + } + byte[] terminalBytes = required(row, "terminal_evidence_bytes", byte[].class); + String terminalDigest = required(row, "terminal_evidence_digest", String.class); + if (!digest(terminalBytes).substring("sha256:".length()).equals(terminalDigest)) { + throw new InvalidPreparationEvidenceException( + "Retained Game Design terminal evidence digest differs from its immutable bytes"); + } + final GameDesignPublicationTerminalEvidence terminal; + try { + terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + } catch (IllegalArgumentException invalid) { + throw new InvalidPreparationEvidenceException( + "Retained Game Design terminal evidence is not canonical", invalid); + } + var terminalRequest = new WorldPublicationTerminal.Request(terminal); + var worldRequest = selector.request(); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !worldRequest.publicationFence().equals(required(row, "publication_fence", UUID.class)) + || !worldRequest.targetNamespace().equals(required(row, "target_namespace", String.class)) + || !worldRequest + .canonicalTenantId() + .equals(required(row, "canonical_tenant_id", UUID.class)) + || !worldRequest + .canonicalVersionId() + .equals(required(row, "canonical_version_id", UUID.class)) + || !worldRequest + .publicationRequestId() + .equals(required(row, "publication_request_id", String.class)) + || !worldRequest.requestDigest().equals(required(row, "request_digest", String.class)) + || !worldRequest + .publishWorkflowId() + .equals(required(row, "publish_workflow_id", String.class)) + || worldRequest.versionStateEpoch() + != required(row, "freeze_version_state_epoch", Long.class) + || !worldRequest.appliedCommitId().equals(required(row, "applied_commit_id", String.class)) + || !worldRequest.contentDigest().equals(required(row, "content_digest", String.class)) + || worldRequest.digestSchemaVersion() + != required(row, "digest_schema_version", Integer.class) + || !terminalRequest + .releaseBundleRef() + .equals(required(row, "published_release_bundle_ref", String.class)) + || !terminalRequest + .releaseBundleDigest() + .equals(required(row, "published_release_bundle_digest", String.class)) + || !Objects.equals( + terminalRequest.publicationVersionStateEpoch(), + required(row, "publication_version_state_epoch", Long.class)) + || !Arrays.equals( + terminalRequest.operationBytes(), required(row, "operation_bytes", byte[].class)) + || !Arrays.equals( + terminalRequest.worldEvidenceBytes(), + required(row, "world_evidence_bytes", byte[].class)) + || !Arrays.equals( + terminalRequest.releaseContentBytes(), + required(row, "release_content_bytes", byte[].class)) + || !Arrays.equals(terminal.worldEvidence().canonicalBytes(), selector.canonicalBytes())) { + throw new InvalidPreparationEvidenceException( + "Retained terminal differs from the complete original World selector evidence"); + } + requireExactPublishedRelease(terminal, release); + } + + private static void requireExactPublishedRelease( + GameDesignPublicationTerminalEvidence terminal, + AuthoredWorldReleaseAttestationEvidence release) { + var bundle = terminal.releaseContent(); + if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || !bundle.canonicalTenantId().equals(release.canonicalTenantId()) + || !bundle.canonicalVersionId().equals(release.canonicalVersionId()) + || !bundle.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef()) + || terminal.publicationVersionStateEpoch() > release.versionStateEpoch() + || !bundle.publishWorkflowId().equals(release.publishWorkflowId()) + || !bundle + .publishWorkflowId() + .equals(terminal.worldEvidence().request().publishWorkflowId()) + || !terminal.worldEvidence().request().appliedCommitId().equals(release.commitId()) + || !bundle.manifestHash().equals(release.manifestHash()) + || bundle.manifestSchemaVersion() != release.manifestSchemaVersion() + || !bundle.requiredManifestAssetKeys().equals(release.requiredManifestAssetKeys()) + || !bundle.artifactDigests().equals(release.artifactDigests()) + || !bundle.commandDefinitions().equals(release.commandDefinitions()) + || !bundle.generationConfigRevision().equals(release.generationConfigRevision()) + || !matchesPublishedParticipants( + bundle.participantDigests(), release.participantDigests())) { + throw new InvalidPreparationEvidenceException( + "Retained terminal ReleaseContent differs from the exact immutable launch release binding"); + } + } + + private static boolean matchesPublishedParticipants( + java.util.List terminal, + java.util.List release) { + if (terminal.size() != AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().size() + || release.size() != terminal.size()) return false; + for (int index = 0; index < terminal.size(); index++) { + var actual = terminal.get(index); + var expected = release.get(index); + if (!actual.participantKey().equals(expected.participantKey()) + || !actual.scopeValue().equals(expected.scopeValue()) + || !Objects.equals( + actual.baseVersionId(), + expected.baseVersionIdPresent() ? expected.baseVersionId() : null) + || !actual.appliedCommitId().equals(expected.appliedCommitId()) + || !actual.contentDigest().equals(expected.contentDigest()) + || actual.digestSchemaVersion() != expected.digestSchemaVersion() + || !Objects.equals( + actual.abilitySchemaDigest(), + expected.abilitySchemaDigestPresent() ? expected.abilitySchemaDigest() : null) + || actual.errorCode() != null && !actual.errorCode().isEmpty() + || actual.errorMessage() != null) return false; + } + return true; + } + + static String inputJson(Input input) { + var request = input.gameSessionReadRequest(); + var evidence = input.gameSessionReadEvidence(); + var launch = input.completeLaunchBinding(); + var source = launch.sourceIntakeReceipt(); + var version = input.versionIdentity(); + var versionState = version.versionStateEvidence(); + var topology = input.topologyPlan(); + var topologySource = topology.sourceBinding(); + var owner = topologySource.plan().ownerBinding(); + var freeze = topologySource.freeze(); + + Map root = + object( + "schemaVersion", + launch.evidence().releaseAttestation().worldStartLocationEvidence() == null ? 1 : 2, + "identity", + object( + "canonicalGameInstanceId", evidence.canonicalGameInstanceId().toString(), + "targetNamespace", evidence.targetNamespace(), + "canonicalTenantId", evidence.canonicalTenantId().toString(), + "worldSlug", evidence.worldSlug(), + "playableStateNamespaceId", evidence.playableStateNamespaceId().toString(), + "playableStateScope", evidence.playableStateScope(), + "publicProduction", evidence.publicProduction(), + "controlPlaneRequestId", evidence.controlPlaneRequestId()), + "gameSessionReadRequest", + object( + "targetNamespace", request.targetNamespace(), + "canonicalTenantId", request.canonicalTenantId().toString(), + "worldSlug", request.worldSlug(), + "canonicalGameInstanceId", request.canonicalGameInstanceId().toString(), + "controlPlaneRequestId", request.controlPlaneRequestId(), + "launchDescriptorId", request.launchDescriptorId(), + "expectedDescriptorRequestDigest", request.expectedDescriptorRequestDigest(), + "expectedDescriptorResultDigest", request.expectedDescriptorResultDigest(), + "expectedReleaseAttestationEvidenceDigest", + request.expectedReleaseAttestationEvidenceDigest()), + "gameSessionReadEvidence", + object( + "targetNamespace", evidence.targetNamespace(), + "canonicalTenantId", evidence.canonicalTenantId().toString(), + "worldSlug", evidence.worldSlug(), + "canonicalGameInstanceId", evidence.canonicalGameInstanceId().toString(), + "controlPlaneRequestId", evidence.controlPlaneRequestId(), + "launchDescriptorId", evidence.launchDescriptorId(), + "descriptorRequestDigest", evidence.descriptorRequestDigest(), + "descriptorResultDigest", evidence.descriptorResultDigest(), + "releaseAttestationEvidenceDigest", evidence.releaseAttestationEvidenceDigest(), + "playableStateNamespaceId", evidence.playableStateNamespaceId().toString(), + "playableStateScope", evidence.playableStateScope(), + "publicProduction", evidence.publicProduction(), + "descriptorJson", evidenceJson(evidence.descriptor()), + "releaseAttestationJson", evidenceJson(evidence.releaseAttestation())), + "launchBinding", + object( + "schemaVersion", launch.schemaVersion(), + "operationId", launch.operationId().toString(), + "targetNamespace", launch.targetNamespace(), + "canonicalTenantId", launch.canonicalTenantId().toString(), + "worldSlug", launch.worldSlug(), + "controlPlaneRequestId", launch.controlPlaneRequestId(), + "descriptorRequestDigest", launch.descriptor().requestDigest(), + "descriptorResultDigest", launch.descriptor().resultDigest(), + "releaseAttestationDigest", + launch.evidence().releaseAttestation().evidenceDigest(), + "canonicalVersionId", + launch.evidence().releaseAttestation().canonicalVersionId().toString(), + "localTenantKey", source.localTenantKey(), + "intakeOperationId", source.operationId().toString(), + "intakeRequestId", source.intakeRequestId().toString(), + "sourceOperationId", source.sourceOperationId().toString(), + "sourceEvidenceDigest", source.sourceEvidenceDigest(), + "intakeRequestDigest", source.requestDigest(), + "intakeReceiptDigest", source.receiptDigest()), + "versionIdentity", + object( + "schemaVersion", version.schemaVersion(), + "operationId", version.operationId().toString(), + "canonicalVersionId", version.canonicalVersionId().toString(), + "localVersionKey", version.localVersionKey(), + "gameDesignVersionId", version.gameDesignVersionId(), + "versionState", versionState.versionState().name(), + "versionStateEpoch", versionState.versionStateEpoch(), + "evidenceDigest", versionState.evidenceDigest()), + "sourceIntake", + object( + "schemaVersion", source.schemaVersion(), + "targetNamespace", source.targetNamespace(), + "intakeRequestId", source.intakeRequestId().toString(), + "operationId", source.operationId().toString(), + "canonicalTenantId", source.canonicalTenantId().toString(), + "worldSlug", source.worldSlug(), + "sourceOperationId", source.sourceOperationId().toString(), + "sourceEvidenceDigest", source.sourceEvidenceDigest(), + "requestDigest", source.requestDigest(), + "receiptDigest", source.receiptDigest(), + "localTenantKey", source.localTenantKey(), + "sourceEvidence", + object( + "schemaVersion", source.source().schemaVersion(), + "registrationRequestId", + source.source().registrationRequestId().toString(), + "sourceOperationId", source.source().operationId().toString(), + "requestDigest", source.source().requestDigest(), + "canonicalTenantId", source.source().canonicalTenantId().toString(), + "tenantSlug", source.source().tenantSlug(), + "worldSlug", source.source().worldSlug(), + "worldDisplayName", source.source().worldDisplayName(), + "sourceGameRowId", source.source().sourceGameRowId(), + "sourceGameTenantKey", source.source().sourceGameTenantKey(), + "provenanceKind", source.source().provenanceKind(), + "evidenceDigest", source.source().evidenceDigest())), + "topology", + object( + "captureId", topology.captureId().toString(), + "targetNamespace", owner.targetNamespace(), + "canonicalTenantId", owner.canonicalTenantId().toString(), + "canonicalVersionId", owner.canonicalVersionId().toString(), + "versionIdentityOperationId", owner.versionIdentityOperationId().toString(), + "requestId", topologySource.plan().binding().requestId().toString(), + "commitId", topologySource.plan().binding().commitId().toString(), + "freezeRequestId", freeze.publicationRequestId(), + "publicationFence", freeze.publicationFence().toString(), + "publicationRequestDigest", freeze.requestDigest(), + "appliedCommitId", freeze.appliedCommitId(), + "planDigest", planDigest(topology.entries()), + "regionCount", topology.regions().size(), + "zoneCount", topology.zones().size(), + "roomCount", topology.rooms().size(), + "exitCount", topology.roomExits().size(), + "generationRuleCount", topology.generationRules().size(), + "spawnBindingCount", topology.spawnBindings().size())); + var selector = launch.evidence().releaseAttestation().worldStartLocationEvidence(); + if (selector != null) { + root.put( + "worldStartLocationEvidenceBase64", + Base64.getEncoder().encodeToString(selector.canonicalBytes())); + } + try { + return JSON.writeValueAsString(root); + } catch (JacksonException exception) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation input cannot be serialized exactly", exception); + } + } + + private static String planDigest(List entries) { + List> rows = new ArrayList<>(entries.size()); + for (Entry entry : entries) { + rows.add( + object( + "family", entry.identity().family().name(), + "templateId", entry.identity().templateId().toString(), + "inputPayload", entry.source().inputPayload(), + "authoredRevisionBase64", + Base64.getEncoder() + .encodeToString(entry.source().authoredRevision().toByteArray()), + "effectiveContentBase64", + Base64.getEncoder().encodeToString(entry.source().content().toByteArray()))); + } + try { + return digest(JSON.writeValueAsBytes(rows)); + } catch (JacksonException exception) { + throw new InvalidPreparationEvidenceException( + "Canonical topology source rows cannot be serialized exactly", exception); + } + } + + private static Map object(Object... values) { + if (values.length % 2 != 0) throw new IllegalArgumentException("Map requires key/value pairs"); + Map result = new LinkedHashMap<>(); + for (int index = 0; index < values.length; index += 2) { + result.put((String) values[index], values[index + 1]); + } + return result; + } + + /** Full typed evidence serialization, matching the closed World V26 persistence codec. */ + private static String evidenceJson(Object evidence) { + try { + return JSON.writeValueAsString(Objects.requireNonNull(evidence, "evidence")); + } catch (JacksonException exception) { + throw new InvalidPreparationEvidenceException( + "Canonical preparation launch evidence cannot be serialized exactly", exception); + } + } + + private static String digest(byte[] bytes) { + return "sha256:" + HexFormat.of().formatHex(sha256(bytes)); + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Canonical World preparation requires its owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "Canonical World preparation requires writable READ COMMITTED isolation"); + } + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " must not join an ambient transaction"); + } + } + + private static T required(Record row, String name, Class type) { + T value = row.get(name, type); + if (value == null) throw new InvalidPreparationEvidenceException("Missing " + name); + return value; + } + + private record MaterializedInstance(long worldInstanceId, long privateGameInstanceKey) {} + + public static class ConflictingPreparationException extends IllegalStateException { + public ConflictingPreparationException(String message) { + super(message); + } + + public ConflictingPreparationException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class InvalidPreparationEvidenceException extends IllegalStateException { + public InvalidPreparationEvidenceException(String message) { + super(message); + } + + public InvalidPreparationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java new file mode 100644 index 0000000000..d9437201b9 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Result; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, default-denied owner operation for a canonical generation-free world instance. + * + *

No production verifier is supplied in this slice. A future authenticated integration must + * verify the same-namespace Game Session producer and exact current Game Design release/terminal + * source before the World transaction begins. The original Account-authorized APPLIED result is + * immutable input evidence; preparation must not reauthorize the creator or reuse Draft/publication + * permission. Its held producer evidence must remain valid through commit. This class is + * deliberately not a Spring component and adds no RPC or public activation path. + */ +public final class WorldCanonicalInstancePreparationService { + private final WorldCanonicalInstancePreparationRepository repository; + private final CommitAuthorityVerifier verifier; + + /** Constructs the production-safe default: all attempts fail closed. */ + public WorldCanonicalInstancePreparationService( + WorldCanonicalInstancePreparationRepository repository) { + this(repository, WorldCanonicalInstancePreparationService::denyByDefault); + } + + /** Constructor for an explicitly supplied owner verifier, including labeled synthetic tests. */ + public WorldCanonicalInstancePreparationService( + WorldCanonicalInstancePreparationRepository repository, CommitAuthorityVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + } + + /** + * Verifies before opening the owner transaction and returns only committed exact readback. + * Current lifecycle state is never rewritten by a historical preparation retry. + */ + public Result prepare(Input input) { + Objects.requireNonNull(input, "input"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical World preparation must verify outside an ambient transaction"); + } + WorldCanonicalInstancePreparation.requireGenerationFree(input.topologyPlan()); + + HeldCommitAuthority held = + Objects.requireNonNull( + verifier.verifyAndHold(input), + "Canonical preparation verifier returned no held commit authority"); + try (held) { + held.requireHeld(); + return repository.materialize(input, held); + } + } + + private static HeldCommitAuthority denyByDefault(Input input) { + throw new PreparationDeniedException( + "Canonical World preparation has no authenticated source/release terminal verifier"); + } + + /** Performs authenticated producer checks before returning a continuously held local fence. */ + @FunctionalInterface + public interface CommitAuthorityVerifier { + HeldCommitAuthority verifyAndHold(Input input); + } + + /** + * A verifier-owned, continuously held producer-evidence handle. It stays open throughout the + * World transaction and its commit; implementations must fail closed from {@link #requireHeld()} + * if the evidence they verified is no longer effective. Remote/current-state checks happen before + * the World transaction; {@code requireHeld()} is a local fence/effective-state assertion and + * must never perform RPC while World holds database locks. It is not a new Account creator + * permission. + */ + public interface HeldCommitAuthority extends AutoCloseable { + void requireHeld(); + + @Override + void close(); + } + + public static final class PreparationDeniedException extends IllegalStateException { + public PreparationDeniedException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlan.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlan.java new file mode 100644 index 0000000000..27ce430442 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlan.java @@ -0,0 +1,575 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Row; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Template; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.EntityTemplateReference; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; + +/** + * Pure typed projection of a frozen World topology for a possible instance materialization. + * + *

The source remains {@link WorldCanonicalFrozenTopology#STATUS}; this plan is not release, + * Account authorization, execution, lifecycle, or admission proof. It allocates no runtime IDs, + * persists nothing, and preserves the complete source binding and authored payloads. + */ +public final class WorldCanonicalInstanceTopologyPlan { + /** One source-bound row with both exact input and the frozen storage projection. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record SourceRow( + Template identity, + WorldDesignMutationRevision authoredRevision, + WorldDesignMutationRevision content, + String inputPayload) { + public SourceRow { + Objects.requireNonNull(identity, "identity"); + Objects.requireNonNull(authoredRevision, "authoredRevision"); + Objects.requireNonNull(content, "content"); + Objects.requireNonNull(inputPayload, "inputPayload"); + } + + /** Exact UTF-8 encoding of the immutable input payload retained by the source binding. */ + public byte[] inputPayloadBytes() { + return inputPayload.getBytes(StandardCharsets.UTF_8); + } + } + + public sealed interface Entry + permits Region, Zone, Room, RoomExit, GenerationRuleIntent, SpawnBindingIntent { + SourceRow source(); + + default Template identity() { + return source().identity(); + } + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record Region(SourceRow source, RegionDesignMutation content) implements Entry { + public Region { + requireFamily(source, Family.REGION); + Objects.requireNonNull(content, "content"); + if (!source.content().hasRegion() || !source.content().getRegion().equals(content)) { + throw invalid("REGION content differs from its frozen source row"); + } + } + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record Zone(SourceRow source, Template region, ZoneDesignMutation content) + implements Entry { + public Zone { + requireFamily(source, Family.ZONE); + requireFamily(region, Family.REGION); + Objects.requireNonNull(content, "content"); + if (!source.content().hasZone() || !source.content().getZone().equals(content)) { + throw invalid("ZONE content differs from its frozen source row"); + } + } + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record Room(SourceRow source, Template zone, RoomDesignMutation content) implements Entry { + public Room { + requireFamily(source, Family.ROOM); + requireFamily(zone, Family.ZONE); + Objects.requireNonNull(content, "content"); + if (!source.content().hasRoom() || !source.content().getRoom().equals(content)) { + throw invalid("ROOM content differs from its frozen source row"); + } + } + } + + public record RoomExit( + SourceRow source, Template fromRoom, Template toRoom, RoomExitDesignMutation content) + implements Entry { + public RoomExit { + requireFamily(source, Family.ROOM_EXIT); + requireFamily(fromRoom, Family.ROOM); + requireFamily(toRoom, Family.ROOM); + Objects.requireNonNull(content, "content"); + if (!source.content().hasRoomExit() || !source.content().getRoomExit().equals(content)) { + throw invalid("ROOM_EXIT content differs from its frozen source row"); + } + } + } + + /** A configured rule is required intent; this entry carries no execution or skip outcome. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record GenerationRuleIntent( + SourceRow source, Template scope, GenerationRuleDesignMutation requiredIntent) + implements Entry { + public GenerationRuleIntent { + requireFamily(source, Family.GENERATION_RULE); + requireScopeFamily(scope); + Objects.requireNonNull(requiredIntent, "requiredIntent"); + if (!source.authoredRevision().hasGenerationRule() + || !source.authoredRevision().getGenerationRule().equals(requiredIntent)) { + throw invalid("GENERATION_RULE intent differs from its exact authored input"); + } + } + } + + /** A configured spawn is required intent and retains its canonical Entity UUID reference. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable.") + public record SpawnBindingIntent( + SourceRow source, + Template room, + EntityTemplateReference entityReference, + WorldEntitySpawnBindingDesignMutation requiredIntent) + implements Entry { + public SpawnBindingIntent { + requireFamily(source, Family.WORLD_ENTITY_SPAWN_BINDING); + requireFamily(room, Family.ROOM); + Objects.requireNonNull(entityReference, "entityReference"); + Objects.requireNonNull(requiredIntent, "requiredIntent"); + if (!source.authoredRevision().hasWorldEntitySpawnBinding() + || !source.authoredRevision().getWorldEntitySpawnBinding().equals(requiredIntent)) { + throw invalid("Spawn-binding intent differs from its exact authored input"); + } + } + } + + private final WorldCanonicalFrozenTopology source; + private final List entries; + private final List regions; + private final List zones; + private final List rooms; + private final List roomExits; + private final List generationRules; + private final List spawnBindings; + + private WorldCanonicalInstanceTopologyPlan( + WorldCanonicalFrozenTopology source, + List entries, + List regions, + List zones, + List rooms, + List roomExits, + List generationRules, + List spawnBindings) { + this.source = source; + this.entries = List.copyOf(entries); + this.regions = List.copyOf(regions); + this.zones = List.copyOf(zones); + this.rooms = List.copyOf(rooms); + this.roomExits = List.copyOf(roomExits); + this.generationRules = List.copyOf(generationRules); + this.spawnBindings = List.copyOf(spawnBindings); + } + + /** + * Projects every row from the exact frozen graph, retaining its original binding and ordering. + * + *

Rows and parent references use family-qualified authored UUIDs. The source's private storage + * keys are not used to derive instance identities or Entity references. + */ + public static WorldCanonicalInstanceTopologyPlan create(WorldCanonicalFrozenTopology source) { + Objects.requireNonNull(source, "source"); + if (!WorldCanonicalFrozenTopology.STATUS.equals(source.status())) { + throw invalid("Source topology is not the unverified frozen component"); + } + var request = source.request(); + var plan = request.plan(); + var graph = source.graph(); + var input = plan.graph(); + if (!graph.tenantId().equals(input.tenantId()) + || !graph.versionId().equals(input.versionId()) + || !graph.tenantId().equals(plan.binding().target().canonicalTenantId()) + || !graph.versionId().equals(plan.binding().target().canonicalVersionId()) + || !graph.tenantId().equals(request.freeze().canonicalTenantId()) + || !graph.versionId().equals(request.freeze().canonicalVersionId())) { + throw invalid("Frozen graph differs from its complete canonical source binding"); + } + + Map expected = new HashMap<>(); + for (var node : input.nodes()) { + Template identity = + new Template(family(node.mutation().getAggregateType()), node.templateId()); + if (expected.putIfAbsent(identity, node) != null) { + throw invalid("Complete source repeats a family-qualified authored identity"); + } + } + if (expected.size() != graph.rows().size()) { + throw invalid("Frozen topology omits or adds a complete source row"); + } + + Map payloadByRevision = new HashMap<>(); + for (var revision : plan.binding().revisions()) { + if (revision.owner() == Owner.WORLD_MANAGEMENT + && payloadByRevision.putIfAbsent(revision.revisionId(), revision) != null) { + throw invalid("Complete source repeats a World revision identity"); + } + } + + List entries = new ArrayList<>(); + List regions = new ArrayList<>(); + List zones = new ArrayList<>(); + List rooms = new ArrayList<>(); + List exits = new ArrayList<>(); + List generationRules = new ArrayList<>(); + List spawnBindings = new ArrayList<>(); + Map byIdentity = new HashMap<>(); + + for (Row row : graph.rows()) { + var authored = row.authored(); + Template identity = + new Template(family(authored.mutation().getAggregateType()), row.template().templateId()); + if (!identity.equals(row.template())) { + throw invalid("Frozen row identity confuses authored family or template ID"); + } + var expectedNode = expected.remove(identity); + if (expectedNode == null || !expectedNode.equals(authored)) { + throw invalid("Frozen row is missing, duplicated, or differs from its exact input"); + } + validateContentEnvelope(authored, row.content()); + var inputPayload = payloadByRevision.get(authored.revisionId()); + if (inputPayload == null) { + throw invalid("Frozen row has no exact retained authored payload"); + } + SourceRow sourceRow = + new SourceRow(identity, authored.mutation(), row.content(), inputPayload.payload()); + Entry entry = + project(sourceRow, authored.entityReference(), graph.tenantId(), graph.versionId()); + if (byIdentity.putIfAbsent(identity, entry) != null) { + throw invalid("Frozen topology repeats a family-qualified row identity"); + } + entries.add(entry); + switch (entry) { + case Region region -> regions.add(region); + case Zone zone -> zones.add(zone); + case Room room -> rooms.add(room); + case RoomExit roomExit -> exits.add(roomExit); + case GenerationRuleIntent generationRule -> generationRules.add(generationRule); + case SpawnBindingIntent spawnBinding -> spawnBindings.add(spawnBinding); + } + } + if (!expected.isEmpty()) { + throw invalid("Frozen topology does not cover every typed source row"); + } + + validateClosure(entries, byIdentity); + return new WorldCanonicalInstanceTopologyPlan( + source, entries, regions, zones, rooms, exits, generationRules, spawnBindings); + } + + /** The exact source request, full Draft binding, and freeze evidence retained by the capture. */ + public WorldCanonicalFrozenTopology.Request sourceBinding() { + return source.request(); + } + + public UUID captureId() { + return source.captureId(); + } + + public UUID tenantId() { + return source.graph().tenantId(); + } + + public UUID versionId() { + return source.graph().versionId(); + } + + public List entries() { + return entries; + } + + public List regions() { + return regions; + } + + public List zones() { + return zones; + } + + public List rooms() { + return rooms; + } + + public List roomExits() { + return roomExits; + } + + public List generationRules() { + return generationRules; + } + + public List spawnBindings() { + return spawnBindings; + } + + private static Entry project( + SourceRow source, + EntityTemplateReference entityReference, + UUID canonicalTenantId, + UUID canonicalVersionId) { + var authored = source.authoredRevision(); + var content = source.content(); + return switch (source.identity().family()) { + case REGION -> new Region(source, content.getRegion()); + case ZONE -> + new Zone( + source, + new Template(Family.REGION, uuid(authored.getZone().getRegionId())), + content.getZone()); + case ROOM -> + new Room( + source, + new Template(Family.ZONE, uuid(authored.getRoom().getZoneId())), + content.getRoom()); + case ROOM_EXIT -> + new RoomExit( + source, + new Template(Family.ROOM, uuid(authored.getRoomExit().getFromRoomId())), + new Template(Family.ROOM, uuid(authored.getRoomExit().getToRoomId())), + content.getRoomExit()); + case GENERATION_RULE -> + new GenerationRuleIntent(source, declaredScope(authored), authored.getGenerationRule()); + case WORLD_ENTITY_SPAWN_BINDING -> { + var spawn = authored.getWorldEntitySpawnBinding(); + if (entityReference == null + || entityReference.kind() != spawn.getEntityTemplateType() + || !entityReference.tenantId().equals(canonicalTenantId) + || !entityReference.versionId().equals(canonicalVersionId) + || !entityReference.templateId().equals(uuid(spawn.getEntityTemplateId()))) { + throw invalid("Spawn intent differs from its exact typed canonical Entity reference"); + } + yield new SpawnBindingIntent( + source, new Template(Family.ROOM, uuid(spawn.getRoomId())), entityReference, spawn); + } + }; + } + + private static void validateClosure(List entries, Map byIdentity) { + Map regionsByZone = new HashMap<>(); + Map zonesByRoom = new HashMap<>(); + Set> exitIdentities = new HashSet<>(); + Set> generationRuleIdentities = new HashSet<>(); + Set> spawnBindingIdentities = new HashSet<>(); + for (Entry entry : entries) { + if (entry instanceof Zone zone) { + requireEntry(byIdentity, zone.region(), Region.class, "zone parent region"); + regionsByZone.put(zone.identity(), zone.region()); + } else if (entry instanceof Room room) { + requireEntry(byIdentity, room.zone(), Zone.class, "room parent zone"); + zonesByRoom.put(room.identity(), room.zone()); + } + } + + for (Entry entry : entries) { + Template scope = declaredScope(entry.source().authoredRevision()); + if (entry instanceof Region || entry instanceof Zone || entry instanceof Room) { + requireWithinScope(scope, entry.identity(), regionsByZone, zonesByRoom); + } + if (entry instanceof RoomExit roomExit) { + requireEntry(byIdentity, roomExit.fromRoom(), Room.class, "exit source room"); + requireEntry(byIdentity, roomExit.toRoom(), Room.class, "exit destination room"); + if (!exitIdentities.add( + List.of( + roomExit.fromRoom().templateId().toString(), roomExit.content().getDirection()))) { + throw invalid("Frozen topology repeats a room/direction exit"); + } + requireWithinScope(scope, roomExit.fromRoom(), regionsByZone, zonesByRoom); + requireWithinScope(scope, roomExit.toRoom(), regionsByZone, zonesByRoom); + } else if (entry instanceof GenerationRuleIntent rule) { + requireEntry( + byIdentity, + rule.scope(), + scope.family() == Family.REGION ? Region.class : Zone.class, + "generation-rule scope"); + if (!scope.equals(rule.scope())) { + throw invalid("Generation-rule scope differs from its authored scope"); + } + if (!generationRuleIdentities.add( + List.of( + rule.scope().family().name(), + rule.scope().templateId().toString(), + rule.requiredIntent().getName()))) { + throw invalid("Frozen topology repeats a scoped generation rule"); + } + } else if (entry instanceof SpawnBindingIntent spawn) { + requireEntry(byIdentity, spawn.room(), Room.class, "spawn-binding room"); + if (!spawnBindingIdentities.add( + List.of( + spawn.room().templateId().toString(), + spawn.entityReference().kind().name(), + spawn.entityReference().templateId().toString()))) { + throw invalid("Frozen topology repeats a typed room/entity spawn binding"); + } + requireWithinScope(scope, spawn.room(), regionsByZone, zonesByRoom); + } + } + } + + private static void requireWithinScope( + Template scope, + Template child, + Map regionsByZone, + Map zonesByRoom) { + boolean contained; + if (scope.family() == Family.REGION) { + Template region = regionFor(child, regionsByZone, zonesByRoom); + contained = scope.equals(region); + } else if (scope.family() == Family.ZONE) { + Template zone = zoneFor(child, zonesByRoom); + contained = scope.equals(zone); + } else { + throw invalid("World subtree scope must be a REGION or ZONE"); + } + if (!contained) { + throw invalid("Authored row or exit endpoint falls outside its declared subtree scope"); + } + } + + private static Template regionFor( + Template child, Map regionsByZone, Map zonesByRoom) { + if (child.family() == Family.REGION) { + return child; + } + Template zone = child.family() == Family.ZONE ? child : zonesByRoom.get(child); + Template region = zone == null ? null : regionsByZone.get(zone); + if (region == null) { + throw invalid("Authored parent chain is incomplete at its REGION"); + } + return region; + } + + private static Template zoneFor(Template child, Map zonesByRoom) { + if (child.family() == Family.ZONE) { + return child; + } + Template zone = zonesByRoom.get(child); + if (zone == null) { + throw invalid("Authored parent chain is incomplete at its ZONE"); + } + return zone; + } + + private static void requireEntry( + Map entries, + Template identity, + Class expectedType, + String relationship) { + Entry found = entries.get(identity); + if (found == null || !expectedType.isInstance(found)) { + throw invalid("Missing or type-confused " + relationship); + } + } + + private static void validateContentEnvelope( + WorldDraftTopologyInputGraph.Node authored, WorldDesignMutationRevision content) { + var mutation = authored.mutation(); + var expected = mutation.toBuilder(); + switch (mutation.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> { + if (mutation.getRegion().getSpacingMultiplier() == 0) { + expected.setRegion(mutation.getRegion().toBuilder().setSpacingMultiplier(1.0)); + } + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> { + if (mutation.getRoomExit().getCost() == 0) { + expected.setRoomExit(mutation.getRoomExit().toBuilder().setCost(1)); + } + } + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> { + if (mutation.getWorldEntitySpawnBinding().getSpawnCount() == 0) { + expected.setWorldEntitySpawnBinding( + mutation.getWorldEntitySpawnBinding().toBuilder().setSpawnCount(1)); + } + } + default -> {} + } + if (!content.equals(expected.build())) { + throw invalid("Frozen content differs from its exact authored/default projection"); + } + } + + private static Template declaredScope(WorldDesignMutationRevision revision) { + return switch (revision.getScopeType()) { + case WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE -> + new Template(Family.REGION, uuid(revision.getScopeId())); + case WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE -> + new Template(Family.ZONE, uuid(revision.getScopeId())); + default -> throw invalid("Unsupported World topology scope"); + }; + } + + private static Family family(WorldDesignAggregateType aggregate) { + return switch (aggregate) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> Family.REGION; + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> Family.ZONE; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> Family.ROOM; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> Family.ROOM_EXIT; + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> Family.GENERATION_RULE; + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> + Family.WORLD_ENTITY_SPAWN_BINDING; + default -> throw invalid("Unsupported topology family"); + }; + } + + private static UUID uuid(String value) { + try { + UUID id = UUID.fromString(value); + if (!id.toString().equals(value) || id.equals(new UUID(0, 0))) { + throw invalid("Canonical topology references require non-nil UUIDs"); + } + return id; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "Canonical topology references require non-nil UUIDs", exception); + } + } + + private static void requireScopeFamily(Template scope) { + Objects.requireNonNull(scope, "scope"); + if (scope.family() != Family.REGION && scope.family() != Family.ZONE) { + throw invalid("World subtree scope must be a REGION or ZONE"); + } + } + + private static void requireFamily(SourceRow source, Family expected) { + Objects.requireNonNull(source, "source"); + requireFamily(source.identity(), expected); + } + + private static void requireFamily(Template identity, Family expected) { + Objects.requireNonNull(identity, "identity"); + if (identity.family() != expected) { + throw invalid("Expected " + expected + " family-qualified identity"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcService.java new file mode 100644 index 0000000000..2a220aa6b4 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcService.java @@ -0,0 +1,210 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.ByteString; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalPlayerAdmissionHoldServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered workload-only acquire/read adapter; no accepting release or runtime activation. */ +public final class WorldCanonicalPlayerAdmissionHoldGrpcService + extends WorldCanonicalPlayerAdmissionHoldServiceGrpc + .WorldCanonicalPlayerAdmissionHoldServiceImplBase { + private final WorldCanonicalPlayerAdmissionHoldService service; + private final String namespace; + + public WorldCanonicalPlayerAdmissionHoldGrpcService( + WorldCanonicalPlayerAdmissionHoldService service, String namespace) { + this.service = Objects.requireNonNull(service, "service"); + this.namespace = WorldCanonicalPlayerAdmissionHoldService.requireNamespace(namespace); + } + + @Override + public void acquireCanonicalPlayerAdmissionHold( + AcquireCanonicalPlayerAdmissionHoldRequest request, + StreamObserver observer) { + if (!requireBoundary(observer)) return; + try { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) throw invalid(); + var parsed = + parse( + request.getRequestId(), + request.getOriginalLeaseJson(), + request.getOriginalLeaseSha256(), + request.getExpectedLifecycleEpoch(), + request.getExpectedRowVersion()); + var held = + service.acquire( + parsed.bound().lease().canonicalJson(), + parsed.bound().lease().sha256(), + parsed.bound().expectedLifecycleEpoch(), + parsed.bound().expectedRowVersion()); + var exact = requireResponse(parsed, held); + observer.onNext( + AcquireCanonicalPlayerAdmissionHoldResponse.newBuilder() + .setRequestId(parsed.correlationId()) + .setOriginalLeaseSha256(parsed.bound().lease().sha256()) + .setHoldEvidenceJson(ByteString.copyFrom(exact.canonicalBytes())) + .setHoldEvidenceSha256(exact.sha256()) + .build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + report(observer, failure); + } + } + + @Override + public void readCanonicalPlayerAdmissionHold( + ReadCanonicalPlayerAdmissionHoldRequest request, + StreamObserver observer) { + if (!requireBoundary(observer)) return; + try { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) throw invalid(); + var parsed = + parse( + request.getRequestId(), + request.getOriginalLeaseJson(), + request.getOriginalLeaseSha256(), + request.getExpectedLifecycleEpoch(), + request.getExpectedRowVersion()); + var held = + service + .read( + parsed.bound().lease().canonicalJson(), + parsed.bound().lease().sha256(), + parsed.bound().expectedLifecycleEpoch(), + parsed.bound().expectedRowVersion()) + .orElseThrow( + () -> + new IllegalStateException("Exact World player-admission hold is unresolved")); + var exact = requireResponse(parsed, held); + observer.onNext( + ReadCanonicalPlayerAdmissionHoldResponse.newBuilder() + .setRequestId(parsed.correlationId()) + .setOriginalLeaseSha256(parsed.bound().lease().sha256()) + .setHoldEvidenceJson(ByteString.copyFrom(exact.canonicalBytes())) + .setHoldEvidenceSha256(exact.sha256()) + .build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + report(observer, failure); + } + } + + private boolean requireBoundary(StreamObserver observer) { + try { + WorldCanonicalPlayerAdmissionHoldService.requireAccountPeer(namespace); + } catch (SecurityException denied) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Account workload without end-user context is required") + .asRuntimeException()); + return false; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("World player hold requires an independent owner operation") + .asRuntimeException()); + return false; + } + return true; + } + + private Parsed parse( + String correlation, + ByteString originalLease, + String leaseDigest, + String epoch, + String version) { + UUID requestId; + try { + requestId = UUID.fromString(correlation); + } catch (RuntimeException invalid) { + throw invalid(); + } + if (!requestId.toString().equals(correlation) + || requestId.version() != 4 + || requestId.variant() != 2 + || originalLease.isEmpty() + || originalLease.size() > AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + || !originalLease.isValidUtf8()) throw invalid(); + var lease = AccountGameplayAdmissionLeaseEvidence.parseCanonical(originalLease.toStringUtf8()); + if (leaseDigest == null + || !lease.sha256().equals(leaseDigest) + || !namespace.equals(lease.carrier().get("targetNamespace"))) { + throw invalid(); + } + return new Parsed( + correlation, + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + lease, + WorldCanonicalPlayerAdmissionHoldEvidence.decimal(epoch, true), + WorldCanonicalPlayerAdmissionHoldEvidence.decimal(version, false))); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence requireResponse( + Parsed parsed, WorldCanonicalPlayerAdmissionHoldEvidence held) { + if (held == null || held.request() == null || !parsed.bound().sameBinding(held.request())) { + throw new IllegalStateException( + "World hold response changed the complete original lease binding"); + } + var world = held.worldEvidence(); + if (held.holdId() == null + || held.holdFence() == null + || world == null + || world.request() == null + || world.request().canonicalTenantId() == null + || world.request().canonicalGameInstanceId() == null + || world.request().playableStateNamespaceId() == null) { + throw new IllegalStateException("World hold response has missing owner evidence fields"); + } + try { + parsed.bound().requireExactActiveWorld(world); + // Rebuild the immutable carrier from the exact bound value rather than trusting supplied + // bytes. + var exact = + new WorldCanonicalPlayerAdmissionHoldEvidence( + held.holdId(), held.holdFence(), parsed.bound(), world); + exact.canonicalBytes(); + return exact; + } catch (IllegalArgumentException inconsistent) { + throw new IllegalStateException( + "World hold response has inconsistent owner evidence", inconsistent); + } + } + + private static void report(StreamObserver observer, RuntimeException failure) { + Status status; + if (failure instanceof IllegalArgumentException) status = Status.INVALID_ARGUMENT; + else if (failure instanceof SecurityException) status = Status.PERMISSION_DENIED; + else if (failure instanceof TransientDataAccessException + || failure instanceof DataAccessException) status = Status.UNAVAILABLE; + else if (failure instanceof IllegalStateException) status = Status.FAILED_PRECONDITION; + else status = Status.INTERNAL; + observer.onError( + status + .withDescription( + "World player hold request could not produce exact retained owner evidence") + .asRuntimeException()); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Complete canonical World player hold request is required"); + } + + private record Parsed( + String correlationId, WorldCanonicalPlayerAdmissionHoldEvidence.Request bound) {} +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java new file mode 100644 index 0000000000..442527a3ce --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepository.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Account-to-World acquisition/readback component. V51 serializes insertion and every + * lifecycle mutation on the actual owner row, and versions that tuple without changing its state or + * counters so older MVCC snapshots cannot overlook the committed hold. + */ +public final class WorldCanonicalPlayerAdmissionHoldRepository { + private final DSLContext dsl; + private final String namespace; + private final TransactionTemplate writeTransaction; + private final TransactionTemplate readTransaction; + private final WorldCanonicalInstanceAssociationRepository associations; + private final WorldCanonicalInstanceLifecycleReadRepository lifecycles; + + public WorldCanonicalPlayerAdmissionHoldRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + String namespace, + WorldCanonicalInstanceAssociationRepository associations, + WorldCanonicalInstanceLifecycleReadRepository lifecycles) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.namespace = WorldCanonicalPlayerAdmissionHoldService.requireNamespace(namespace); + this.associations = Objects.requireNonNull(associations, "associations"); + this.lifecycles = Objects.requireNonNull(lifecycles, "lifecycles"); + writeTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readTransaction = new TransactionTemplate(transactionManager); + readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readTransaction.setReadOnly(true); + } + + public WorldCanonicalPlayerAdmissionHoldEvidence acquire( + WorldCanonicalPlayerAdmissionHoldEvidence.Request request) { + requireBoundary(request); + return Objects.requireNonNull( + writeTransaction.execute( + status -> { + requireActualTransaction(false, "read committed"); + Record previous = findOriginal(request); + if (previous != null) return retained(previous, request); + + var association = + associations + .readOwnerAssociationInActivationTransaction( + request.canonicalGameInstanceId()) + .orElseThrow(() -> denied("Canonical World instance association is missing")); + var selector = selector(association, request.attemptId()); + request.requireExactWorldSelector(selector); + var current = + lifecycles + .readForActivationInOwnerTransaction(selector) + .orElseThrow(() -> denied("Canonical World lifecycle source is unavailable")); + request.requireExactActiveWorld(current); + + // Another exact retry may have inserted while this transaction waited on the row. + previous = findOriginal(request); + if (previous != null) return retained(previous, request); + UUID id = UUID.randomUUID(); + UUID fence = UUID.randomUUID(); + dsl.execute( + "INSERT INTO world_canonical_player_admission_hold " + + "(hold_id,hold_fence,lease_id,attempt_id,lease_sha256,lease_bytes," + + "canonical_game_instance_id,world_instance_id,active_lifecycle_epoch," + + "active_row_version,world_evidence_bytes,diagnostic_expires_at_millis) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", + id, + fence, + request.leaseId(), + request.attemptId(), + request.lease().sha256(), + request.lease().canonicalJson().getBytes(StandardCharsets.UTF_8), + request.canonicalGameInstanceId(), + association.worldInstanceId(), + current.lifecycleEpoch(), + current.rowVersion(), + current.canonicalBytes(), + Long.parseLong((String) request.lease().carrier().get("expiresAt"))); + var result = retained(Objects.requireNonNull(findOriginal(request)), request); + if (!id.equals(result.holdId()) || !fence.equals(result.holdFence())) { + throw denied("New hold readback differs from allocated identity"); + } + return result; + })); + } + + /** Exact durable retained identity; absence is UNKNOWN, never an abort or release result. */ + public Optional read( + WorldCanonicalPlayerAdmissionHoldEvidence.Request request) { + requireBoundary(request); + return Optional.ofNullable( + readTransaction.execute( + status -> { + requireActualTransaction(true, "repeatable read"); + Record row = findOriginal(request); + return row == null ? null : retained(row, request); + })); + } + + private void requireBoundary(WorldCanonicalPlayerAdmissionHoldEvidence.Request request) { + WorldCanonicalPlayerAdmissionHoldService.requireAccountPeer(namespace); + requireNoAmbientTransaction(); + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) + throw denied("Lease namespace differs from World"); + } + + private Record findOriginal(WorldCanonicalPlayerAdmissionHoldEvidence.Request request) { + return dsl.fetchOne( + "SELECT * FROM world_canonical_player_admission_hold WHERE lease_id=? OR attempt_id=?", + request.leaseId(), + request.attemptId()); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence retained( + Record row, WorldCanonicalPlayerAdmissionHoldEvidence.Request expected) { + byte[] bytes = Objects.requireNonNull(row.get("lease_bytes", byte[].class)); + var lease = + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + new String(bytes, StandardCharsets.UTF_8)); + var request = + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + lease, + Objects.requireNonNull(row.get("active_lifecycle_epoch", Long.class)), + Objects.requireNonNull(row.get("active_row_version", Long.class))); + if (!expected.sameBinding(request) + || !lease.sha256().equals(row.get("lease_sha256", String.class)) + || !request.leaseId().equals(row.get("lease_id", UUID.class)) + || !request.attemptId().equals(row.get("attempt_id", UUID.class)) + || !request + .canonicalGameInstanceId() + .equals(row.get("canonical_game_instance_id", UUID.class)) + || Long.parseLong((String) lease.carrier().get("expiresAt")) + != Objects.requireNonNull(row.get("diagnostic_expires_at_millis", Long.class)) + || !"HELD".equals(row.get("hold_state", String.class)) + || row.get("account_terminal_evidence_bytes") != null + || row.get("game_session_completion_evidence_bytes") != null) { + throw denied("Retained hold conflicts with the complete original lease/attempt binding"); + } + return new WorldCanonicalPlayerAdmissionHoldEvidence( + row.get("hold_id", UUID.class), + row.get("hold_fence", UUID.class), + request, + WorldCanonicalInstanceLifecycleEvidence.fromStored( + row.get("world_evidence_bytes", byte[].class))); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request selector( + WorldCanonicalInstanceAssociation association, UUID readId) { + var identity = association.identity(); + var binding = association.completeLaunchBinding(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + readId, + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.worldSlug(), + identity.canonicalGameInstanceId(), + identity.playableStateNamespaceId(), + identity.playableStateScope(), + identity.publicProduction(), + identity.controlPlaneRequestId(), + association.canonicalVersionId(), + binding.descriptor().requestDigest(), + binding.descriptor().resultDigest(), + binding.evidence().releaseAttestation().evidenceDigest()); + } + + private void requireActualTransaction(boolean readOnly, String isolation) { + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only")); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() != readOnly + || !isolation.equals(state.get("isolation", String.class)) + || !(readOnly ? "on" : "off").equals(state.get("read_only", String.class))) { + throw denied("World hold requires its owned transaction isolation and mutability"); + } + } + + static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw denied("World hold requires no ambient transaction"); + } + } + + private static IllegalStateException denied(String message) { + return new IllegalStateException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java new file mode 100644 index 0000000000..9787c34237 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldService.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; + +/** + * Unregistered internal boundary. Authenticating the exact Account workload establishes only the + * producer of the original lease; World never interprets the carrier as current Account authority. + */ +public final class WorldCanonicalPlayerAdmissionHoldService { + private final WorldCanonicalPlayerAdmissionHoldRepository repository; + private final String namespace; + + public WorldCanonicalPlayerAdmissionHoldService( + WorldCanonicalPlayerAdmissionHoldRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.namespace = requireNamespace(namespace); + } + + public WorldCanonicalPlayerAdmissionHoldEvidence acquire( + String originalLeaseJson, + String originalLeaseSha256, + long expectedEpoch, + long expectedVersion) { + return repository.acquire( + request(originalLeaseJson, originalLeaseSha256, expectedEpoch, expectedVersion)); + } + + public Optional read( + String originalLeaseJson, + String originalLeaseSha256, + long expectedEpoch, + long expectedVersion) { + return repository.read( + request(originalLeaseJson, originalLeaseSha256, expectedEpoch, expectedVersion)); + } + + /** No caller Boolean, COMMITTED label, expiry, or generic opaque proof can release this hold. */ + public void release() { + requireAccountPeer(namespace); + WorldCanonicalPlayerAdmissionHoldRepository.requireNoAmbientTransaction(); + throw new IllegalStateException( + "Hold release is unavailable without authenticated exact Account terminal AND Game Session installation/cleanup evidence"); + } + + private WorldCanonicalPlayerAdmissionHoldEvidence.Request request( + String originalLeaseJson, + String originalLeaseSha256, + long expectedEpoch, + long expectedVersion) { + requireAccountPeer(namespace); + WorldCanonicalPlayerAdmissionHoldRepository.requireNoAmbientTransaction(); + var lease = AccountGameplayAdmissionLeaseEvidence.parseCanonical(originalLeaseJson); + if (!lease.sha256().equals(originalLeaseSha256) + || !namespace.equals(lease.carrier().get("targetNamespace"))) { + throw new IllegalArgumentException("Original lease digest or namespace differs"); + } + return new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + lease, expectedEpoch, expectedVersion); + } + + static String requireNamespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + return namespace; + } + + static void requireAccountPeer(String namespace) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("account-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "Exact authenticated same-namespace Account workload is required"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcService.java new file mode 100644 index 0000000000..99fa77d580 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcService.java @@ -0,0 +1,430 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.ByteString; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.v1.PlaceCanonicalInitialPlayerLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.PlaceCanonicalInitialPlayerLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalCurrentPlayerLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalCurrentPlayerLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalPlayerLocationServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Standalone protected canonical placement/location adapter; intentionally not runtime-registered. + */ +public final class WorldCanonicalPlayerLocationGrpcService + extends WorldCanonicalPlayerLocationServiceGrpc.WorldCanonicalPlayerLocationServiceImplBase { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final WorldCanonicalInitialPlayerLocationService placementService; + private final WorldCanonicalCurrentPlayerLocationService currentLocationService; + private final String trustedNamespace; + + public WorldCanonicalPlayerLocationGrpcService( + WorldCanonicalInitialPlayerLocationService placementService, + WorldCanonicalCurrentPlayerLocationService currentLocationService, + String trustedNamespace) { + this.placementService = Objects.requireNonNull(placementService, "placementService"); + this.currentLocationService = + Objects.requireNonNull(currentLocationService, "currentLocationService"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void placeCanonicalInitialPlayerLocation( + PlaceCanonicalInitialPlayerLocationRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameSessionPeer(responseObserver)) return; + if (hasAmbientTransaction()) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World placement requires an independent owner operation"); + return; + } + + WorldCanonicalInitialPlayerLocation.Request placementRequest; + try { + placementRequest = parsePlacementRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A complete canonical World placement request is required"); + return; + } + if (!trustedNamespace.equals( + placementRequest.activeLifecycleEvidence().request().targetNamespace())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World placement namespace must match the authenticated peer"); + return; + } + + WorldCanonicalInitialPlayerLocation.Result result; + try { + result = placementService.place(placementRequest); + } catch (WorldCanonicalInitialPlayerLocationService.PlacementDeniedException denied) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World placement authority was denied"); + return; + } catch (IllegalArgumentException failure) { + if (hasPrefix(failure, "IDEMPOTENCY_CONFLICT:")) { + fail( + responseObserver, + Status.ALREADY_EXISTS, + "Canonical World placement operation conflicts with an existing request"); + } else { + fail(responseObserver, Status.INTERNAL, "Canonical World placement failed"); + } + return; + } catch (IllegalStateException inconsistent) { + if (hasPrefix(inconsistent, "INITIAL_PLAYER_LOCATION_DENIED:")) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World placement evidence is inconsistent"); + } else { + fail(responseObserver, Status.INTERNAL, "Canonical World placement failed"); + } + return; + } catch (TransientDataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Canonical World placement storage is temporarily unavailable"); + return; + } catch (DataAccessException permanentStorageFailure) { + fail(responseObserver, Status.INTERNAL, "Canonical World placement storage failed"); + return; + } catch (org.springframework.dao.DataAccessException permanentSpringStorageFailure) { + fail(responseObserver, Status.INTERNAL, "Canonical World placement storage failed"); + return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.INTERNAL, "Canonical World placement failed"); + return; + } + + try { + requireExactPlacementResult(placementRequest, result); + if (result.outcome() == WorldCanonicalInitialPlayerLocation.Outcome.CONFLICT) { + fail( + responseObserver, + Status.ALREADY_EXISTS, + "Canonical World placement conflicts with an existing character location"); + return; + } + if (result.outcome() != WorldCanonicalInitialPlayerLocation.Outcome.APPLIED) { + throw new InvalidOwnerEvidenceException(); + } + byte[] immutableResult = result.canonicalBytes(); + if (immutableResult.length == 0) throw new InvalidOwnerEvidenceException(); + responseObserver.onNext( + PlaceCanonicalInitialPlayerLocationResponse.newBuilder() + .setOperationId(placementRequest.operationId().toString()) + .setCanonicalResultBytes(ByteString.copyFrom(immutableResult)) + .build()); + responseObserver.onCompleted(); + } catch (RuntimeException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World placement result does not match the requested operation"); + } + } + + @Override + public void readCanonicalCurrentPlayerLocation( + ReadCanonicalCurrentPlayerLocationRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameSessionPeer(responseObserver)) return; + if (hasAmbientTransaction()) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World location read requires an independent owner operation"); + return; + } + + ParsedCurrentLocationRequest parsed; + try { + parsed = parseCurrentLocationRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A complete canonical World location read request is required"); + return; + } + if (!trustedNamespace.equals( + parsed.placementRequest().activeLifecycleEvidence().request().targetNamespace())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World location namespace must match the authenticated peer"); + return; + } + + java.util.Optional current; + try { + current = currentLocationService.read(parsed.placementRequest()); + } catch (WorldCanonicalInitialPlayerLocationService.PlacementDeniedException denied) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World current-location authority was denied"); + return; + } catch (IllegalStateException inconsistent) { + if (hasPrefix(inconsistent, "CURRENT_PLAYER_LOCATION_DENIED:")) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World current-location evidence is inconsistent"); + } else { + fail(responseObserver, Status.INTERNAL, "Canonical World location read failed"); + } + return; + } catch (TransientDataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Canonical World location storage is temporarily unavailable"); + return; + } catch (DataAccessException permanentStorageFailure) { + fail(responseObserver, Status.INTERNAL, "Canonical World location storage failed"); + return; + } catch (org.springframework.dao.DataAccessException permanentSpringStorageFailure) { + fail(responseObserver, Status.INTERNAL, "Canonical World location storage failed"); + return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.INTERNAL, "Canonical World location read failed"); + return; + } + + if (current == null) { + fail( + responseObserver, + Status.INTERNAL, + "Canonical World location owner returned no read result"); + return; + } + if (current.isEmpty()) { + fail(responseObserver, Status.NOT_FOUND, "Canonical World current placement was not found"); + return; + } + + try { + WorldCanonicalCurrentPlayerLocationRepository.CurrentLocation location = + current.orElseThrow(); + ValidatedCurrentLocation validated = + validateCurrentLocation(parsed, location, trustedNamespace); + responseObserver.onNext( + ReadCanonicalCurrentPlayerLocationResponse.newBuilder() + .setReadRequestId(parsed.readRequestId().toString()) + .setPlacementOperationId(parsed.placementRequest().operationId().toString()) + .setPlacementRequestDigest(parsed.placementRequest().requestDigest()) + .setCurrentLifecycleEvidenceBytes( + ByteString.copyFrom(validated.currentLifecycleEvidenceBytes())) + .setImmutablePlacementResultBytes( + ByteString.copyFrom(validated.placementResultBytes())) + .setOriginalPlacementLifecycleEvidenceBytes( + ByteString.copyFrom(validated.originalPlacementLifecycleEvidenceBytes())) + .setRegionInstanceId(location.canonicalRegionInstanceId().toString()) + .setOperationalRegionId(location.operationalRegionId().toString()) + .build()); + responseObserver.onCompleted(); + } catch (RuntimeException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World current-location evidence does not match the requested placement"); + } + } + + private static WorldCanonicalInitialPlayerLocation.Request parsePlacementRequest( + PlaceCanonicalInitialPlayerLocationRequest request) { + Objects.requireNonNull(request, "request"); + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Unknown canonical World placement request fields"); + } + byte[] canonicalRequestBytes = request.getCanonicalRequestBytes().toByteArray(); + byte[] lifecycleEvidenceBytes = request.getOriginalLifecycleEvidenceBytes().toByteArray(); + if (canonicalRequestBytes.length == 0 || lifecycleEvidenceBytes.length == 0) { + throw new IllegalArgumentException("Complete canonical World placement evidence is required"); + } + return WorldCanonicalInitialPlayerLocation.Request.fromStored( + canonicalRequestBytes, lifecycleEvidenceBytes); + } + + private static ParsedCurrentLocationRequest parseCurrentLocationRequest( + ReadCanonicalCurrentPlayerLocationRequest request) { + Objects.requireNonNull(request, "request"); + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Unknown canonical World location read request fields"); + } + UUID readRequestId = parseCanonicalUuid(request.getReadRequestId()); + byte[] canonicalRequestBytes = request.getCanonicalPlacementRequestBytes().toByteArray(); + byte[] lifecycleEvidenceBytes = request.getOriginalLifecycleEvidenceBytes().toByteArray(); + if (canonicalRequestBytes.length == 0 || lifecycleEvidenceBytes.length == 0) { + throw new IllegalArgumentException("Complete canonical World location evidence is required"); + } + WorldCanonicalInitialPlayerLocation.Request placementRequest = + WorldCanonicalInitialPlayerLocation.Request.fromStored( + canonicalRequestBytes, lifecycleEvidenceBytes); + if (readRequestId.equals(placementRequest.operationId()) + || !readRequestId.equals( + placementRequest.activeLifecycleEvidence().request().readRequestId())) { + throw new IllegalArgumentException( + "Read correlation must be fresh and match the complete current lifecycle evidence"); + } + return new ParsedCurrentLocationRequest(readRequestId, placementRequest); + } + + private static UUID parseCanonicalUuid(String value) { + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Read request ID must be a canonical UUID", invalid); + } + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Read request ID must be a canonical non-nil UUID"); + } + return parsed; + } + + private static void requireExactPlacementResult( + WorldCanonicalInitialPlayerLocation.Request request, + WorldCanonicalInitialPlayerLocation.Result result) { + if (result == null + || result.request() == null + || !request.operationId().equals(result.request().operationId()) + || !request.requestDigest().equals(result.requestDigest()) + || !Arrays.equals( + request.canonicalRequestBytes(), result.request().canonicalRequestBytes())) { + throw new InvalidOwnerEvidenceException(); + } + } + + private static ValidatedCurrentLocation validateCurrentLocation( + ParsedCurrentLocationRequest parsed, + WorldCanonicalCurrentPlayerLocationRepository.CurrentLocation location, + String trustedNamespace) { + WorldCanonicalInitialPlayerLocation.Request requested = parsed.placementRequest(); + WorldCanonicalInitialPlayerLocation.Request binding = location.binding(); + if (binding == null + || !requested.operationId().equals(binding.operationId()) + || !requested.requestDigest().equals(binding.requestDigest()) + || !Arrays.equals(requested.canonicalRequestBytes(), binding.canonicalRequestBytes())) { + throw new InvalidOwnerEvidenceException(); + } + + WorldCanonicalInstanceLifecycleEvidence currentEvidence = + Objects.requireNonNull(location.currentLifecycleEvidence(), "currentLifecycleEvidence"); + byte[] currentEvidenceBytes = currentEvidence.canonicalBytes(); + WorldCanonicalInstanceLifecycleEvidence parsedCurrentEvidence = + WorldCanonicalInstanceLifecycleEvidence.fromStored(currentEvidenceBytes); + if (!"ACTIVE".equals(parsedCurrentEvidence.lifecycleStatus()) + || !trustedNamespace.equals(parsedCurrentEvidence.request().targetNamespace()) + || !parsed.readRequestId().equals(parsedCurrentEvidence.request().readRequestId()) + || !Arrays.equals( + requested.normalizedLifecycleEvidenceBytes(), + WorldCanonicalInitialPlayerLocation.normalizedLifecycleEvidenceBytes( + currentEvidenceBytes))) { + throw new InvalidOwnerEvidenceException(); + } + + WorldCanonicalInitialPlayerLocation.Result placementResult = location.placementResult(); + requireExactPlacementResult(requested, placementResult); + if (placementResult.outcome() != WorldCanonicalInitialPlayerLocation.Outcome.APPLIED + || !placementResult.startLocation().equals(parsedCurrentEvidence.startLocation()) + || !Objects.equals( + placementResult.runtimeRoomInstanceId(), parsedCurrentEvidence.runtimeRoomInstanceId()) + || !location.startLocation().equals(parsedCurrentEvidence.startLocation()) + || location.runtimeRoomInstanceId() != parsedCurrentEvidence.runtimeRoomInstanceId()) { + throw new InvalidOwnerEvidenceException(); + } + + byte[] originalLifecycleEvidenceBytes = location.originalLifecycleEvidenceBytes(); + if (originalLifecycleEvidenceBytes.length == 0) throw new InvalidOwnerEvidenceException(); + WorldCanonicalInstanceLifecycleEvidence originalEvidence = + WorldCanonicalInstanceLifecycleEvidence.fromStored(originalLifecycleEvidenceBytes); + if (!trustedNamespace.equals(originalEvidence.request().targetNamespace()) + || parsed.readRequestId().equals(requested.operationId()) + || parsed.readRequestId().equals(originalEvidence.request().readRequestId()) + || !Arrays.equals( + requested.normalizedLifecycleEvidenceBytes(), + WorldCanonicalInitialPlayerLocation.normalizedLifecycleEvidenceBytes( + originalLifecycleEvidenceBytes))) { + throw new InvalidOwnerEvidenceException(); + } + + UUID canonicalRegionInstanceId = location.canonicalRegionInstanceId(); + UUID operationalRegionId = location.operationalRegionId(); + if (canonicalRegionInstanceId == null + || operationalRegionId == null + || NIL_UUID.equals(canonicalRegionInstanceId) + || NIL_UUID.equals(operationalRegionId) + || canonicalRegionInstanceId.equals(operationalRegionId)) { + throw new InvalidOwnerEvidenceException(); + } + byte[] immutablePlacementResultBytes = placementResult.canonicalBytes(); + if (immutablePlacementResultBytes.length == 0) throw new InvalidOwnerEvidenceException(); + return new ValidatedCurrentLocation( + currentEvidenceBytes, immutablePlacementResultBytes, originalLifecycleEvidenceBytes); + } + + private boolean requireAuthenticatedGameSessionPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-session-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Only the verified same-namespace Game Session workload without end-user context is allowed"); + return false; + } + + private static boolean hasAmbientTransaction() { + return TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive(); + } + + private static boolean hasPrefix(RuntimeException failure, String prefix) { + return failure.getMessage() != null && failure.getMessage().startsWith(prefix); + } + + private static void fail(StreamObserver responseObserver, Status status, String description) { + responseObserver.onError(status.withDescription(description).asRuntimeException()); + } + + private record ParsedCurrentLocationRequest( + UUID readRequestId, WorldCanonicalInitialPlayerLocation.Request placementRequest) {} + + private record ValidatedCurrentLocation( + byte[] currentLifecycleEvidenceBytes, + byte[] placementResultBytes, + byte[] originalPlacementLifecycleEvidenceBytes) {} + + private static final class InvalidOwnerEvidenceException extends IllegalStateException {} +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingReceipt.java new file mode 100644 index 0000000000..31889f4382 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingReceipt.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; + +/** + * Internal World receipt for a retained authored-world descriptor and complete release pair. + * + *

This is non-admitting released-content evidence. It does not represent local content, + * PREPARING, ACTIVE/current authority, or activation. + */ +public record WorldCompleteLaunchBindingReceipt( + int schemaVersion, + UUID operationId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + WorldAuthoredSourceIntakeReceipt sourceIntakeReceipt, + CompleteLaunchBindingEvidence evidence) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public WorldCompleteLaunchBindingReceipt { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World complete launch binding version"); + } + requireNonNil(operationId, "operationId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(evidence, "evidence"); + + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + var selector = evidence.releaseAttestation().worldStartLocationEvidence(); + if (selector != null + && !selector.request().intakeRequestId().equals(sourceIntakeReceipt.intakeRequestId())) { + throw new IllegalArgumentException( + "World release selector differs from the exact original source intake"); + } + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !targetNamespace.equals(sourceIntakeReceipt.targetNamespace()) + || !canonicalTenantId.equals(sourceIntakeReceipt.canonicalTenantId()) + || !worldSlug.equals(sourceIntakeReceipt.worldSlug()) + || !descriptor + .authoredWorldSourceOperationId() + .equals(sourceIntakeReceipt.sourceOperationId()) + || !descriptor + .authoredWorldSourceEvidenceDigest() + .equals(sourceIntakeReceipt.sourceEvidenceDigest())) { + throw new IllegalArgumentException( + "World complete launch binding differs from its exact authored-source intake"); + } + } + + public AuthoredWorldLaunchDescriptorEvidence descriptor() { + return evidence.descriptor(); + } + + 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/WorldCompleteLaunchBindingRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingRepository.java new file mode 100644 index 0000000000..9a5b9509fe --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingRepository.java @@ -0,0 +1,491 @@ +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.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Owner-local immutable persistence for complete authored-world launch evidence. */ +public class WorldCompleteLaunchBindingRepository { + private static final Table BINDING = DSL.table(DSL.name("world_complete_launch_binding")); + private static final JsonMapper CLOSED_JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private static final Field BINDING_OPERATION_ID = + DSL.field(DSL.name("binding_operation_id"), UUID.class); + 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 CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + private static final Field INTAKE_OPERATION_ID = + DSL.field(DSL.name("intake_operation_id"), UUID.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("intake_receipt_digest"), String.class); + private static final Field DESCRIPTOR_REQUEST_DIGEST = + DSL.field(DSL.name("descriptor_request_digest"), String.class); + private static final Field DESCRIPTOR_RESULT_DIGEST = + DSL.field(DSL.name("descriptor_result_digest"), String.class); + private static final Field RELEASE_ATTESTATION_DIGEST = + DSL.field(DSL.name("release_attestation_digest"), String.class); + private static final Field DESCRIPTOR_JSON = + DSL.field(DSL.name("descriptor_json"), String.class); + private static final Field RELEASE_ATTESTATION_JSON = + DSL.field(DSL.name("release_attestation_json"), String.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The injected DSLContext is an internal collaborator; construction acquires no resources and this repository has no finalizer.") + public WorldCompleteLaunchBindingRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** Reads the immutable owner row by its stable namespace/tenant/control-plane request key. */ + public Optional read( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + requireNoActiveTransaction("World complete launch binding read"); + return readValidated(namespace, canonicalTenantId, controlPlaneRequestId); + } + + /** Reads the same immutable row inside the lifecycle repository's verified owner snapshot. */ + Optional readInOwnerReadOnlyRepeatableRead( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readValidated(namespace, canonicalTenantId, controlPlaneRequestId); + } + + /** + * Reconstructs the same immutable binding inside the writable canonical activation transaction. + */ + Optional readInOwnerActivationTransaction( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + requireWritableActivationTransaction(); + return readValidated(namespace, canonicalTenantId, controlPlaneRequestId); + } + + private Optional readValidated( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + validateKey(namespace, canonicalTenantId, controlPlaneRequestId); + Record row = find(namespace, canonicalTenantId, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(toStoredBinding(row)); + } + + /** + * Retains one complete pair against the exact committed local source receipt. + * + *

The caller must authenticate Game Session, perform all remote and committed reads outside + * the owner transaction, then invoke this method in a fresh writable READ COMMITTED transaction. + */ + public WorldCompleteLaunchBindingReceipt acceptFresh( + String namespace, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + CompleteLaunchBindingEvidence evidence) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + Objects.requireNonNull(evidence, "evidence"); + requireSourceBinding(namespace, sourceReceipt, evidence); + + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + String descriptorJson = writeJson(descriptor); + String attestationJson = writeJson(evidence.releaseAttestation()); + UUID operationId = newNonNilUuid(); + int inserted = + dsl.insertInto(BINDING) + .set(BINDING_OPERATION_ID, operationId) + .set(TARGET_NAMESPACE, namespace) + .set(CANONICAL_TENANT_ID, descriptor.canonicalTenantId()) + .set(CANONICAL_VERSION_ID, evidence.releaseAttestation().canonicalVersionId()) + .set(WORLD_SLUG, descriptor.worldSlug()) + .set(CONTROL_PLANE_REQUEST_ID, descriptor.controlPlaneRequestId()) + .set(INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(LOCAL_TENANT_KEY, sourceReceipt.localTenantKey()) + .set(SOURCE_OPERATION_ID, sourceReceipt.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, sourceReceipt.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(DESCRIPTOR_REQUEST_DIGEST, descriptor.requestDigest()) + .set(DESCRIPTOR_RESULT_DIGEST, descriptor.resultDigest()) + .set(RELEASE_ATTESTATION_DIGEST, evidence.releaseAttestation().evidenceDigest()) + .set(DESCRIPTOR_JSON, descriptorJson) + .set(RELEASE_ATTESTATION_JSON, attestationJson) + .onConflictDoNothing() + .execute(); + + Record row = + find(namespace, descriptor.canonicalTenantId(), descriptor.controlPlaneRequestId()); + if (row == null) { + throw new InvalidBindingEvidenceException( + "World complete launch binding is missing after its owner claim"); + } + StoredBinding stored = toStoredBinding(row); + WorldCompleteLaunchBindingReceipt receipt = toReceipt(stored, sourceReceipt); + requireExactEvidence(receipt, evidence); + if (inserted == 0) { + throwIfInsertDidNotSelectOriginal(receipt, sourceReceipt, evidence); + } + return receipt; + } + + /** + * Rehydrates the internal receipt only after the exact local intake has been read independently. + */ + WorldCompleteLaunchBindingReceipt toReceipt( + StoredBinding stored, WorldAuthoredSourceIntakeReceipt sourceReceipt) { + Objects.requireNonNull(stored, "stored"); + Objects.requireNonNull(sourceReceipt, "sourceReceipt"); + if (!stored.targetNamespace().equals(sourceReceipt.targetNamespace()) + || !stored.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !stored.worldSlug().equals(sourceReceipt.worldSlug()) + || !stored.intakeOperationId().equals(sourceReceipt.operationId()) + || !stored.intakeRequestId().equals(sourceReceipt.intakeRequestId()) + || stored.localTenantKey() != sourceReceipt.localTenantKey() + || !stored.sourceOperationId().equals(sourceReceipt.sourceOperationId()) + || !stored.sourceEvidenceDigest().equals(sourceReceipt.sourceEvidenceDigest()) + || !stored.intakeReceiptDigest().equals(sourceReceipt.receiptDigest())) { + throw new InvalidBindingEvidenceException( + "World complete launch binding differs from its exact local source receipt"); + } + try { + return new WorldCompleteLaunchBindingReceipt( + 1, + stored.operationId(), + stored.targetNamespace(), + stored.canonicalTenantId(), + stored.worldSlug(), + stored.controlPlaneRequestId(), + sourceReceipt, + stored.evidence()); + } catch (RuntimeException exception) { + if (exception instanceof InvalidBindingEvidenceException) { + throw exception; + } + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding conflicts with its local source", exception); + } + } + + void requireExactEvidence( + WorldCompleteLaunchBindingReceipt receipt, CompleteLaunchBindingEvidence expected) { + AuthoredWorldLaunchDescriptorEvidence descriptor = expected.descriptor(); + if (!receipt.evidence().equals(expected) + || !receipt.targetNamespace().equals(descriptor.targetNamespace()) + || !receipt.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !receipt.worldSlug().equals(descriptor.worldSlug()) + || !receipt.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId())) { + throw new RegistrationConflictException( + "World complete launch binding request identity was reused with changed evidence"); + } + } + + private void throwIfInsertDidNotSelectOriginal( + WorldCompleteLaunchBindingReceipt receipt, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + CompleteLaunchBindingEvidence expected) { + if (!receipt.sourceIntakeReceipt().equals(sourceReceipt)) { + throw new RegistrationConflictException( + "World complete launch binding request identity changed its source intake"); + } + requireExactEvidence(receipt, expected); + } + + private Record find(String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + return dsl.selectFrom(BINDING) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) + .fetchOne(); + } + + private StoredBinding toStoredBinding(Record row) { + try { + UUID operationId = required(row, BINDING_OPERATION_ID); + String namespace = required(row, TARGET_NAMESPACE); + UUID canonicalTenantId = required(row, CANONICAL_TENANT_ID); + UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); + String worldSlug = required(row, WORLD_SLUG); + String controlPlaneRequestId = required(row, CONTROL_PLANE_REQUEST_ID); + UUID intakeOperationId = required(row, INTAKE_OPERATION_ID); + UUID intakeRequestId = required(row, INTAKE_REQUEST_ID); + Long localTenantKey = required(row, LOCAL_TENANT_KEY); + UUID sourceOperationId = required(row, SOURCE_OPERATION_ID); + String sourceEvidenceDigest = required(row, SOURCE_EVIDENCE_DIGEST); + String intakeReceiptDigest = required(row, INTAKE_RECEIPT_DIGEST); + String descriptorRequestDigest = required(row, DESCRIPTOR_REQUEST_DIGEST); + String descriptorResultDigest = required(row, DESCRIPTOR_RESULT_DIGEST); + String attestationDigest = required(row, RELEASE_ATTESTATION_DIGEST); + AuthoredWorldLaunchDescriptorEvidence descriptor = + readJson(required(row, DESCRIPTOR_JSON), AuthoredWorldLaunchDescriptorEvidence.class); + AuthoredWorldReleaseAttestationEvidence attestation = + readJson( + required(row, RELEASE_ATTESTATION_JSON), + AuthoredWorldReleaseAttestationEvidence.class); + descriptor.requireValid(); + CompleteLaunchBindingEvidence evidence = + new CompleteLaunchBindingEvidence(descriptor, attestation); + requireStoredColumns( + namespace, + canonicalTenantId, + canonicalVersionId, + worldSlug, + controlPlaneRequestId, + sourceOperationId, + sourceEvidenceDigest, + descriptorRequestDigest, + descriptorResultDigest, + attestationDigest, + descriptor, + attestation); + if (localTenantKey <= 0) { + throw new IllegalArgumentException("Stored local tenant key must be positive"); + } + return new StoredBinding( + operationId, + namespace, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + intakeOperationId, + intakeRequestId, + localTenantKey, + sourceOperationId, + sourceEvidenceDigest, + intakeReceiptDigest, + descriptorRequestDigest, + descriptorResultDigest, + attestationDigest, + evidence); + } catch (RuntimeException exception) { + if (exception instanceof InvalidBindingEvidenceException) { + throw exception; + } + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding evidence is invalid", exception); + } + } + + private static void requireStoredColumns( + String namespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + String controlPlaneRequestId, + UUID sourceOperationId, + String sourceEvidenceDigest, + String descriptorRequestDigest, + String descriptorResultDigest, + String attestationDigest, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence attestation) { + if (!namespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !sourceOperationId.equals(descriptor.authoredWorldSourceOperationId()) + || !sourceEvidenceDigest.equals(descriptor.authoredWorldSourceEvidenceDigest()) + || !descriptorRequestDigest.equals(descriptor.requestDigest()) + || !descriptorResultDigest.equals(descriptor.resultDigest()) + || !canonicalVersionId.equals(attestation.canonicalVersionId()) + || !attestationDigest.equals(attestation.evidenceDigest())) { + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding columns differ from their closed evidence"); + } + } + + private static void requireSourceBinding( + String namespace, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + CompleteLaunchBindingEvidence evidence) { + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + if (!namespace.equals(descriptor.targetNamespace()) + || !namespace.equals(sourceReceipt.targetNamespace()) + || !descriptor.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !descriptor.worldSlug().equals(sourceReceipt.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(sourceReceipt.sourceOperationId()) + || !descriptor + .authoredWorldSourceEvidenceDigest() + .equals(sourceReceipt.sourceEvidenceDigest())) { + throw new RegistrationConflictException( + "Complete launch binding does not match the exact World source intake"); + } + } + + private static T required(Record row, Field field) { + return Objects.requireNonNull(row.get(field), "Persisted " + field.getName() + " is null"); + } + + private static String writeJson(Object value) { + try { + return CLOSED_JSON.writeValueAsString(value); + } catch (Exception exception) { + throw new InvalidBindingEvidenceException( + "World complete launch binding evidence could not be encoded", exception); + } + } + + private static T readJson(String json, Class type) { + try { + T value = CLOSED_JSON.readValue(json, type); + if (!writeJson(value).equals(json)) { + throw new IllegalArgumentException("Persisted evidence JSON is not in its closed form"); + } + return value; + } catch (Exception exception) { + throw new InvalidBindingEvidenceException( + "Persisted World complete launch binding JSON is not closed evidence", exception); + } + } + + private static void validateKey( + String namespace, UUID canonicalTenantId, String controlPlaneRequestId) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("namespace must be one canonical DNS label"); + } + if (canonicalTenantId == null || canonicalTenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("canonicalTenantId must be a non-nil UUID"); + } + if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId must be nonblank"); + } + } + + private static UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(new UUID(0L, 0L))); + return value; + } + + private static void requireNoActiveTransaction(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(label + " requires an independent committed owner read"); + } + } + + private void requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World complete launch binding snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"repeatable read".equals(state.get("isolation", String.class)) + || !"on".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World complete launch binding snapshot read requires a read-only REPEATABLE READ owner transaction"); + } + } + + private void requireWritableActivationTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World complete launch binding activation read requires a writable READ COMMITTED owner transaction"); + } + Record state = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"), + "World transaction state query returned no row"); + if (!"read committed".equals(state.get("isolation", String.class)) + || !"off".equals(state.get("read_only", String.class))) { + throw new IllegalStateException( + "World complete launch binding activation read requires a writable READ COMMITTED owner transaction"); + } + } + + private static void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World complete launch binding requires an active World owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World complete launch binding requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null + && declaredIsolation != java.sql.Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "World complete launch binding requires READ COMMITTED isolation"); + } + } + + static record StoredBinding( + UUID operationId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + UUID intakeOperationId, + UUID intakeRequestId, + long localTenantKey, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest, + String descriptorRequestDigest, + String descriptorResultDigest, + String releaseAttestationDigest, + CompleteLaunchBindingEvidence evidence) {} + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidBindingEvidenceException extends IllegalStateException { + public InvalidBindingEvidenceException(String message) { + super(message); + } + + public InvalidBindingEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java new file mode 100644 index 0000000000..7074f6c0f8 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java @@ -0,0 +1,677 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired World owner step for retaining the complete released-content launch binding. + * + *

Neither binding nor its current-Version read proves local content, commit fencing, lifecycle + * preparation, or runtime admission. + */ +public final class WorldCompleteLaunchBindingService { + private final AuthoredWorldLaunchDescriptorClient client; + private final AuthoredWorldVersionStateClient versionStateClient; + private final WorldCompleteLaunchBindingRepository repository; + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; + private final CanonicalGameInstanceLaunchAssociationClient gameSessionClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public WorldCompleteLaunchBindingService( + AuthoredWorldLaunchDescriptorClient client, + WorldCompleteLaunchBindingRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this( + client, + repository, + sourceIntakeRepository, + transactionManager, + workloadNamespace, + null, + null, + true); + } + + /** + * Constructs the explicitly unwired binding verifier with its separately authenticated Game + * Design current-version reader. + */ + public WorldCompleteLaunchBindingService( + AuthoredWorldLaunchDescriptorClient client, + WorldCompleteLaunchBindingRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace, + AuthoredWorldVersionStateClient versionStateClient) { + this( + client, + repository, + sourceIntakeRepository, + transactionManager, + workloadNamespace, + versionStateClient, + null, + true); + } + + /** + * Constructs the explicitly unwired committed-launch producer with its actual Game Session + * owner-read client. The client is required for the committed-launch entry point. + */ + public WorldCompleteLaunchBindingService( + AuthoredWorldLaunchDescriptorClient client, + WorldCompleteLaunchBindingRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace, + AuthoredWorldVersionStateClient versionStateClient, + CanonicalGameInstanceLaunchAssociationClient gameSessionClient) { + this( + client, + repository, + sourceIntakeRepository, + transactionManager, + workloadNamespace, + versionStateClient, + Objects.requireNonNull(gameSessionClient, "gameSessionClient"), + false); + } + + private WorldCompleteLaunchBindingService( + AuthoredWorldLaunchDescriptorClient client, + WorldCompleteLaunchBindingRepository repository, + WorldAuthoredSourceIntakeRepository sourceIntakeRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace, + AuthoredWorldVersionStateClient versionStateClient, + CanonicalGameInstanceLaunchAssociationClient gameSessionClient, + boolean allowMissingGameSessionClient) { + this.client = Objects.requireNonNull(client, "client"); + this.versionStateClient = versionStateClient; + if (!allowMissingGameSessionClient) { + Objects.requireNonNull(gameSessionClient, "gameSessionClient"); + } + this.gameSessionClient = gameSessionClient; + this.repository = Objects.requireNonNull(repository, "repository"); + this.sourceIntakeRepository = + Objects.requireNonNull(sourceIntakeRepository, "sourceIntakeRepository"); + 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); + } + + /** + * Authenticates Game Session's exact committed launch association, independently rereads the + * complete immutable pair from Game Design, and retains that pair against its exact committed + * World source intake. This is released-content evidence only; it does not prove local content, + * current authorization, lifecycle preparation, or runtime admission. + */ + public WorldCompleteLaunchBindingReceipt bindCommittedLaunch( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request) { + requireAuthenticatedGameSessionCaller(); + requireNoAmbientCommittedLaunchTransaction(); + if (gameSessionClient == null) { + throw new IllegalStateException( + "World committed-launch binding has no configured Game Session owner reader"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new SecurityException( + "Committed launch binding namespace does not match this World workload"); + } + + GetLaunchDescriptorRequest gameDesignReadRequest = + committedLaunchGameDesignReadRequest(request); + CompleteLaunchBindingEvidence fetched = client.getComplete(gameDesignReadRequest); + requireCommittedLaunchEvidence(fetched, gameDesignReadRequest, request); + + CanonicalGameInstanceLaunchAssociationReadEvidence.Result association = + gameSessionClient.read(request); + WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( + request, association, fetched); + + AuthoredWorldLaunchDescriptorEvidence descriptor = fetched.descriptor(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = readExactSourceReceipt(fetched); + requireFreshCommittedLaunchReadId( + gameDesignReadRequest.getRequestId(), request, descriptor, sourceReceipt); + requireCommittedLaunchSourcePair(fetched, sourceReceipt); + Optional prior = + repository.read( + workloadNamespace, descriptor.canonicalTenantId(), descriptor.controlPlaneRequestId()); + if (prior.isPresent()) { + return loadCommittedLaunchReceipt(prior.orElseThrow(), request, fetched, sourceReceipt); + } + + WorldCompleteLaunchBindingReceipt accepted; + try { + accepted = + ownerTransaction.execute( + status -> repository.acceptFresh(workloadNamespace, sourceReceipt, fetched)); + } catch (RuntimeException ownerFailure) { + Optional uncertainCommit = + repository.read( + workloadNamespace, + descriptor.canonicalTenantId(), + descriptor.controlPlaneRequestId()); + if (uncertainCommit.isEmpty()) { + throw ownerFailure; + } + return loadCommittedLaunchReceipt( + uncertainCommit.orElseThrow(), request, fetched, sourceReceipt); + } + if (accepted == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World owner transaction returned no committed launch binding receipt"); + } + requireCommittedLaunchRequest(accepted, request); + requireSamePair(accepted, fetched); + if (!accepted.sourceIntakeReceipt().equals(sourceReceipt)) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World committed launch binding changed its exact source intake"); + } + + Optional committed = + repository.read( + workloadNamespace, descriptor.canonicalTenantId(), descriptor.controlPlaneRequestId()); + if (committed.isEmpty()) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World committed launch binding is missing after its owner commit"); + } + WorldCompleteLaunchBindingReceipt readback = + loadCommittedLaunchReceipt(committed.orElseThrow(), request, fetched, sourceReceipt); + if (!accepted.equals(readback)) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World committed launch binding changed during independent owner readback"); + } + return readback; + } + + /** + * Binds the exact immutable Game Design read selector to the already committed local source. + * + *

The verified same-namespace Game Session workload is required before any owner read or Game + * Design call. Existing claims are resolved first so retries cannot select newer defaults. + */ + public WorldCompleteLaunchBindingReceipt bind(GetRequest request) { + requireAuthenticatedGameSessionCaller(); + requireNoAmbientTransaction(); + validateRequest(request); + + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + Optional prior = + repository.read( + workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()); + if (prior.isPresent()) { + WorldCompleteLaunchBindingRepository.StoredBinding stored = prior.orElseThrow(); + requireStoredRequest(stored, request); + WorldCompleteLaunchBindingReceipt receipt = loadExactSourceReceipt(stored); + return receipt; + } + + CompleteLaunchBindingEvidence fetched = + client.getComplete(AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(request)); + requireFetchedEvidence(fetched, request); + WorldAuthoredSourceIntakeReceipt sourceReceipt = readExactSourceReceipt(fetched); + + WorldCompleteLaunchBindingReceipt accepted; + try { + accepted = + ownerTransaction.execute( + status -> repository.acceptFresh(workloadNamespace, sourceReceipt, fetched)); + } catch (RuntimeException ownerFailure) { + // A commit acknowledgment can be lost after PostgreSQL made the immutable claim durable. + Optional uncertainCommit = + repository.read( + workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()); + if (uncertainCommit.isEmpty()) { + throw ownerFailure; + } + WorldCompleteLaunchBindingReceipt recovered = + recoverExactSourceReceipt(uncertainCommit.orElseThrow(), request); + requireSamePair(recovered, fetched); + return recovered; + } + if (accepted == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World owner transaction returned no complete launch binding receipt"); + } + requireStoredRequest(accepted, request); + requireSamePair(accepted, fetched); + + Optional committed = + repository.read( + workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()); + if (committed.isEmpty()) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World complete launch binding is missing after its owner commit"); + } + WorldCompleteLaunchBindingRepository.StoredBinding stored = committed.orElseThrow(); + requireStoredRequest(stored, request); + WorldCompleteLaunchBindingReceipt readback = loadExactSourceReceipt(stored); + if (!accepted.equals(readback)) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World complete launch binding changed during independent commit readback"); + } + return readback; + } + + /** + * Reads current Game Design version evidence for an already committed, exact World binding. + * + *

This read never creates or changes the historical binding. It establishes only current + * source-owned Version eligibility at the descriptor epoch; it does not prove World content, + * commit fencing, preparation, or admission. + */ + public AuthoredWorldVersionStateEvidence readCurrentVersionState( + GetRequest request, UUID currentReadId) { + requireAuthenticatedGameSessionCaller(); + requireNoAmbientTransaction(); + validateRequest(request); + requireNonNilCurrentReadId(currentReadId); + if (versionStateClient == null) { + throw new IllegalStateException( + "World current-version verification has no configured Game Design reader"); + } + + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + WorldCompleteLaunchBindingRepository.StoredBinding stored = + repository + .read(workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()) + .orElseThrow( + () -> + new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World current-version verification requires a committed launch binding")); + requireStoredRequest(stored, request); + WorldCompleteLaunchBindingReceipt committed = loadExactSourceReceipt(stored); + requireStoredRequest(committed, request); + requireFreshCurrentReadId(currentReadId, request, committed); + + AuthoredWorldLaunchDescriptorEvidence descriptor = committed.descriptor(); + // This is the Game Design-owned Version selector, never World's private local tenant key. + AuthoredWorldVersionStateEvidence.Request currentRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + descriptor.targetNamespace(), + currentReadId, + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.versionId()); + AuthoredWorldVersionStateEvidence current; + try { + current = versionStateClient.read(currentRequest); + } catch (RuntimeException exception) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Current Game Design version-state evidence is unavailable or invalid", exception); + } + if (current == null + || !currentRequest.equals(current.request()) + || !committed.sourceIntakeReceipt().source().equals(current.sourceEvidence())) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current-version evidence differs from the exact committed World source"); + } + UUID committedCanonicalVersionId = + committed.evidence().releaseAttestation().canonicalVersionId(); + if (!committedCanonicalVersionId.equals(current.canonicalVersionId())) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current canonical version UUID differs from the committed release attestation"); + } + if (current.versionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && current.versionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current Version is not PUBLISHED or ACTIVE"); + } + if (current.versionStateEpoch() != descriptor.versionStateEpoch()) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design current Version epoch differs from the immutable launch descriptor"); + } + return current; + } + + private WorldCompleteLaunchBindingReceipt loadExactSourceReceipt( + WorldCompleteLaunchBindingRepository.StoredBinding stored) { + CompleteLaunchBindingEvidence evidence = stored.evidence(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = readExactSourceReceipt(evidence); + return repository.toReceipt(stored, sourceReceipt); + } + + private WorldCompleteLaunchBindingReceipt recoverExactSourceReceipt( + WorldCompleteLaunchBindingRepository.StoredBinding stored, GetRequest request) { + requireStoredRequest(stored, request); + return loadExactSourceReceipt(stored); + } + + private WorldAuthoredSourceIntakeReceipt readExactSourceReceipt( + CompleteLaunchBindingEvidence evidence) { + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + return sourceIntakeRepository + .readBySource( + workloadNamespace, + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest()) + .orElseThrow( + () -> + new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Complete launch binding has no exact committed World source intake")); + } + + private void requireFreshCommittedLaunchReadId( + String readRequestId, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request associationRequest, + AuthoredWorldLaunchDescriptorEvidence descriptor, + WorldAuthoredSourceIntakeReceipt sourceReceipt) { + if (readRequestId.equals(associationRequest.readRequestId().toString()) + || readRequestId.equals(descriptor.authoredWorldSourceOperationId().toString()) + || readRequestId.equals(sourceReceipt.operationId().toString()) + || readRequestId.equals(sourceReceipt.intakeRequestId().toString()) + || readRequestId.equals(sourceReceipt.sourceOperationId().toString()) + || readRequestId.equals(sourceReceipt.source().registrationRequestId().toString()) + || readRequestId.equals(descriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Game Design committed-launch read ID must be distinct from original source and association identities"); + } + } + + private void requireCommittedLaunchSourcePair( + CompleteLaunchBindingEvidence evidence, WorldAuthoredSourceIntakeReceipt sourceReceipt) { + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + if (!workloadNamespace.equals(sourceReceipt.targetNamespace()) + || !descriptor.canonicalTenantId().equals(sourceReceipt.canonicalTenantId()) + || !descriptor.worldSlug().equals(sourceReceipt.worldSlug()) + || !descriptor.authoredWorldSourceOperationId().equals(sourceReceipt.sourceOperationId()) + || !descriptor + .authoredWorldSourceEvidenceDigest() + .equals(sourceReceipt.sourceEvidenceDigest()) + || !sourceReceipt + .intakeRequestId() + .equals( + evidence + .releaseAttestation() + .worldStartLocationEvidence() + .request() + .intakeRequestId())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "Complete launch binding differs from the exact committed World source intake"); + } + } + + private GetLaunchDescriptorRequest committedLaunchGameDesignReadRequest( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request) { + UUID requestId; + do { + requestId = UUID.randomUUID(); + } while (requestId.equals(request.readRequestId()) + || requestId.equals(request.canonicalTenantId()) + || requestId.equals(request.gameInstanceUuid()) + || requestId.toString().equals(request.controlPlaneRequestId())); + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(requestId.toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setExpectedRequestDigest(request.expectedDescriptorRequestDigest()) + .setExpectedResultDigest(request.expectedDescriptorResultDigest()) + .build(); + } + + private void requireCommittedLaunchEvidence( + CompleteLaunchBindingEvidence evidence, + GetLaunchDescriptorRequest gameDesignReadRequest, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request associationRequest) { + if (evidence == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design returned no complete committed launch binding evidence"); + } + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + if (gameDesignReadRequest + .getRequestId() + .equals(descriptor.authoredWorldSourceOperationId().toString())) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design committed launch read ID is not distinct from its source operation"); + } + if (!workloadNamespace.equals(descriptor.targetNamespace()) + || !associationRequest.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !associationRequest.worldSlug().equals(descriptor.worldSlug()) + || !associationRequest.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !associationRequest.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !associationRequest.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !associationRequest.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !associationRequest + .expectedReleaseAttestationEvidenceDigest() + .equals(evidence.releaseAttestation().evidenceDigest()) + || !gameDesignReadRequest + .getCanonicalTenantId() + .equals(descriptor.canonicalTenantId().toString()) + || !gameDesignReadRequest.getWorldSlug().equals(descriptor.worldSlug()) + || !gameDesignReadRequest + .getControlPlaneRequestId() + .equals(descriptor.controlPlaneRequestId()) + || !gameDesignReadRequest.getExpectedRequestDigest().equals(descriptor.requestDigest()) + || !gameDesignReadRequest.getExpectedResultDigest().equals(descriptor.resultDigest())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "Game Design complete launch pair differs from the exact committed association selector"); + } + if (evidence.releaseAttestation().schemaVersion() + != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || evidence.releaseAttestation().worldStartLocationEvidence() == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Committed launch binding requires the full selector-bearing release attestation v2"); + } + } + + private WorldCompleteLaunchBindingReceipt loadCommittedLaunchReceipt( + WorldCompleteLaunchBindingRepository.StoredBinding stored, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request, + CompleteLaunchBindingEvidence expectedPair, + WorldAuthoredSourceIntakeReceipt expectedSourceReceipt) { + requireCommittedLaunchRequest(stored, request); + requireSameStoredPair(stored.evidence(), expectedPair); + WorldAuthoredSourceIntakeReceipt sourceReadback = readExactSourceReceipt(expectedPair); + if (!expectedSourceReceipt.equals(sourceReadback)) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World committed launch binding source intake changed during exact readback"); + } + WorldCompleteLaunchBindingReceipt receipt = repository.toReceipt(stored, sourceReadback); + requireCommittedLaunchRequest(receipt, request); + requireSamePair(receipt, expectedPair); + return receipt; + } + + private void requireCommittedLaunchRequest( + WorldCompleteLaunchBindingRepository.StoredBinding stored, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request) { + AuthoredWorldLaunchDescriptorEvidence descriptor = stored.evidence().descriptor(); + if (!workloadNamespace.equals(stored.targetNamespace()) + || !request.canonicalTenantId().equals(stored.canonicalTenantId()) + || !request.controlPlaneRequestId().equals(stored.controlPlaneRequestId()) + || !request.worldSlug().equals(stored.worldSlug()) + || !workloadNamespace.equals(descriptor.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.worldSlug().equals(descriptor.worldSlug()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(stored.evidence().releaseAttestation().evidenceDigest())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World committed launch binding differs from its exact Game Session selector"); + } + } + + private void requireCommittedLaunchRequest( + WorldCompleteLaunchBindingReceipt receipt, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request) { + AuthoredWorldLaunchDescriptorEvidence descriptor = receipt.descriptor(); + if (!workloadNamespace.equals(receipt.targetNamespace()) + || !request.canonicalTenantId().equals(receipt.canonicalTenantId()) + || !request.worldSlug().equals(receipt.worldSlug()) + || !request.controlPlaneRequestId().equals(receipt.controlPlaneRequestId()) + || !workloadNamespace.equals(descriptor.targetNamespace()) + || !request.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !request.worldSlug().equals(descriptor.worldSlug()) + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(receipt.evidence().releaseAttestation().evidenceDigest())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World committed launch binding differs from its exact Game Session selector"); + } + } + + private void requireSameStoredPair( + CompleteLaunchBindingEvidence stored, CompleteLaunchBindingEvidence expected) { + if (stored == null + || !stored.equals(expected) + || !stored.descriptor().equals(expected.descriptor()) + || !stored.releaseAttestation().equals(expected.releaseAttestation())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World committed launch binding identity was reused with a changed descriptor or release"); + } + } + + private void requireStoredRequest(WorldCompleteLaunchBindingReceipt receipt, GetRequest request) { + requireStoredRequest(receipt.descriptor(), receipt.targetNamespace(), request); + } + + private void requireStoredRequest( + WorldCompleteLaunchBindingRepository.StoredBinding stored, GetRequest request) { + requireStoredRequest(stored.evidence().descriptor(), stored.targetNamespace(), request); + if (!stored.canonicalTenantId().equals(request.expectedRequest().canonicalTenantId()) + || !stored + .controlPlaneRequestId() + .equals(request.expectedRequest().controlPlaneRequestId())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World complete launch binding stable request identity changed"); + } + } + + private void requireStoredRequest( + AuthoredWorldLaunchDescriptorEvidence descriptor, + String targetNamespace, + GetRequest request) { + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + if (!descriptor.request().equals(expected) + || !descriptor.resultDigest().equals(request.expectedResultDigest()) + || !workloadNamespace.equals(descriptor.targetNamespace()) + || !workloadNamespace.equals(targetNamespace)) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World complete launch binding request identity was reused with changed request or result"); + } + } + + private void requireFetchedEvidence(CompleteLaunchBindingEvidence evidence, GetRequest request) { + if (evidence == null) { + throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Game Design returned no complete launch binding evidence"); + } + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + if (!descriptor.request().equals(request.expectedRequest()) + || !descriptor.resultDigest().equals(request.expectedResultDigest()) + || !workloadNamespace.equals(descriptor.targetNamespace())) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "Game Design complete launch binding differs from the exact read request"); + } + } + + private void requireSamePair( + WorldCompleteLaunchBindingReceipt receipt, CompleteLaunchBindingEvidence expected) { + if (!receipt.evidence().equals(expected)) { + throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( + "World complete launch binding request identity was reused with another release pair"); + } + } + + private void validateRequest(GetRequest request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.expectedRequest().targetNamespace())) { + throw new SecurityException( + "Complete launch binding request namespace does not match this World workload"); + } + } + + private static void requireNonNilCurrentReadId(UUID currentReadId) { + if (currentReadId == null || currentReadId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Current version-state read ID must be a non-nil UUID"); + } + } + + private static void requireFreshCurrentReadId( + UUID currentReadId, GetRequest request, WorldCompleteLaunchBindingReceipt committed) { + WorldAuthoredSourceIntakeReceipt intake = committed.sourceIntakeReceipt(); + if (currentReadId.equals(request.requestId()) + || currentReadId.equals(committed.operationId()) + || currentReadId.equals(intake.operationId()) + || currentReadId.equals(intake.intakeRequestId()) + || currentReadId.equals(intake.sourceOperationId()) + || currentReadId.equals(intake.source().registrationRequestId())) { + throw new IllegalArgumentException( + "Current version-state read ID must be separate from source and registration IDs"); + } + } + + private void requireAuthenticatedGameSessionCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-session-service") + || !peer.isInNamespace(workloadNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "World complete launch binding requires only the authenticated same-namespace Game Session workload"); + } + } + + private static void requireNoAmbientCommittedLaunchTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World committed launch binding requires independent owner reads outside ambient transactions"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World complete launch binding cannot enter from an ambient transaction"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java new file mode 100644 index 0000000000..471b6a5801 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidence.java @@ -0,0 +1,183 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; + +/** Exact caller binding and owner-produced checkpoint for one World publication-freeze attempt. */ +public record WorldDesignPublicationFenceEvidence( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + long gameDesignVersionId, + UUID intakeRequestId, + UUID intakeOperationId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest, + String publicationRequestId, + String requestDigest, + long versionStateEpoch, + String publishWorkflowId) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SOURCE_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + + // requestDigest is retained as the supplied full publication-request digest. The existing + // PublicationDigestRequestBinding is used only for workflow identity derivation here; its + // publicationDigestRequest/v1 read-binding digest is not the full freeze-request digest. + + public WorldDesignPublicationFenceEvidence { + new OwnerBinding( + targetNamespace, + canonicalTenantId, + canonicalVersionId, + versionIdentityOperationId, + gameDesignVersionId, + intakeRequestId, + intakeOperationId, + intakeRequestDigest, + sourceOperationId, + sourceEvidenceDigest, + intakeReceiptDigest); + requirePositive(versionStateEpoch, "versionStateEpoch"); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(gameDesignVersionId), publicationRequestId); + if (requestDigest == null || !REQUEST_DIGEST.matcher(requestDigest).matches()) { + throw new IllegalArgumentException("requestDigest must be 64 lowercase hexadecimal digits"); + } + if (!binding.derivedWorkflowIdentity().equals(publishWorkflowId)) { + throw new IllegalArgumentException( + "publishWorkflowId does not match the canonical full-version workflow identity"); + } + } + + /** The common owner scope and complete source binding used by ordinary writers and freezes. */ + public OwnerBinding ownerBinding() { + return new OwnerBinding( + targetNamespace, + canonicalTenantId, + canonicalVersionId, + versionIdentityOperationId, + gameDesignVersionId, + intakeRequestId, + intakeOperationId, + intakeRequestDigest, + sourceOperationId, + sourceEvidenceDigest, + intakeReceiptDigest); + } + + /** + * Scope/source identity needed to serialize an ordinary OPEN writer. It carries no publication + * request, digest, epoch, workflow, fence, or checkpoint. + */ + public record OwnerBinding( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + long gameDesignVersionId, + UUID intakeRequestId, + UUID intakeOperationId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest) { + public OwnerBinding { + if (targetNamespace == null || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(versionIdentityOperationId, "versionIdentityOperationId"); + requirePositive(gameDesignVersionId, "gameDesignVersionId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(intakeOperationId, "intakeOperationId"); + requireDigest(intakeRequestDigest, "intakeRequestDigest"); + requireNonNil(sourceOperationId, "sourceOperationId"); + requireDigest(sourceEvidenceDigest, "sourceEvidenceDigest"); + requireDigest(intakeReceiptDigest, "intakeReceiptDigest"); + } + } + + /** + * Returns the full-version request identity binding used to derive the canonical workflow ID. Its + * separate publicationDigestRequest/v1 digest is not this record's supplied requestDigest. + */ + public PublicationDigestRequestBinding publicationBinding() { + return PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(gameDesignVersionId), publicationRequestId); + } + + /** Owner-local complete digest checkpoint captured only after the shared version lock is held. */ + public record Checkpoint(String appliedCommitId, String contentDigest, int digestSchemaVersion) { + public Checkpoint { + requireText(appliedCommitId, "appliedCommitId"); + if (appliedCommitId.isBlank()) { + throw new IllegalArgumentException("appliedCommitId must not be blank"); + } + if (!CONTENT_DIGEST + .matcher(Objects.requireNonNull(contentDigest, "contentDigest")) + .matches()) { + throw new IllegalArgumentException("contentDigest must be 64 lowercase hexadecimal digits"); + } + if (digestSchemaVersion <= 0) { + throw new IllegalArgumentException("digestSchemaVersion must be positive"); + } + } + + private static void requireText(String value, String label) { + if (value == null || value.isEmpty() || value.getBytes(StandardCharsets.UTF_8).length > 256) { + throw new IllegalArgumentException( + label + " must be non-empty and at most 256 UTF-8 bytes"); + } + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw new IllegalArgumentException(label + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException(label + " contains malformed Unicode"); + } + } + } + } + + /** Stored freeze result. The UUID is opaque and may only be compared for equality. */ + public record FrozenAttempt( + WorldDesignPublicationFenceEvidence request, UUID publicationFence, Checkpoint checkpoint) { + public FrozenAttempt { + Objects.requireNonNull(request, "request"); + requireNonNil(publicationFence, "publicationFence"); + Objects.requireNonNull(checkpoint, "checkpoint"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0L) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + 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 || !SOURCE_DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical prefixed SHA-256 digest"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java new file mode 100644 index 0000000000..e2ddd3823c --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java @@ -0,0 +1,527 @@ +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 java.util.function.Supplier; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +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; + +/** + * Internal owner-local persistence for the World publication fence prerequisite. + * + *

This repository is not wired to an RPC or authoring route. A supplied checkpoint is retained + * as owner evidence only; it is not an authenticated Game Design freeze acknowledgement. + */ +@Repository +public class WorldDesignPublicationFenceRepository { + private static final String OPEN = "OPEN"; + private static final String FROZEN = "FROZEN"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private static final Table OWNER = DSL.table(DSL.name("world_design_publication_fence_owner")); + private static final Table ATTEMPT = + DSL.table(DSL.name("world_design_publication_fence_attempt")); + private static final Table VERSION_IDENTITY = + DSL.table(DSL.name("world_authored_version_identity")); + 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 LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field VERSION_ID = DSL.field(DSL.name("version_id"), Long.class); + private static final Field VERSION_OPERATION_ID = + DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field VERSION_CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field VERSION_GAME_DESIGN_VERSION_ID = + DSL.field(DSL.name("game_design_version_id"), Long.class); + private static final Field VERSION_LOCAL_VERSION_KEY = + DSL.field(DSL.name("local_version_key"), Long.class); + private static final Field VERSION_WORLD_SLUG = + DSL.field(DSL.name("world_slug"), String.class); + private static final Field VERSION_INTAKE_OPERATION_ID = + DSL.field(DSL.name("intake_operation_id"), UUID.class); + private static final Field VERSION_INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field VERSION_LOCAL_TENANT_KEY = + DSL.field(DSL.name("local_tenant_key"), Long.class); + private static final Field VERSION_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_digest"), String.class); + private static final Field VERSION_SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field VERSION_SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field VERSION_INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("intake_receipt_digest"), String.class); + private static final Field INTAKE_OPERATION_ID = + DSL.field(DSL.name("intake_operation_id"), UUID.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_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_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("intake_receipt_digest"), String.class); + private static final Field OWNER_FREEZE_PHASE = + DSL.field(DSL.name("owner_freeze_phase"), String.class); + private static final Field CURRENT_PUBLICATION_FENCE = + DSL.field(DSL.name("current_publication_fence"), UUID.class); + + private static final Field PUBLICATION_FENCE = + DSL.field(DSL.name("publication_fence"), UUID.class); + private static final Field PUBLICATION_REQUEST_ID = + DSL.field(DSL.name("publication_request_id"), String.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final Field PUBLISH_WORKFLOW_ID = + DSL.field(DSL.name("publish_workflow_id"), String.class); + private static final Field APPLIED_COMMIT_ID = + DSL.field(DSL.name("applied_commit_id"), String.class); + private static final Field CONTENT_DIGEST = + DSL.field(DSL.name("content_digest"), String.class); + private static final Field DIGEST_SCHEMA_VERSION = + DSL.field(DSL.name("digest_schema_version"), Integer.class); + private static final Field OWNER_BINDING_SCHEMA_VERSION = + DSL.field(DSL.name("owner_binding_schema_version"), Short.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field VERSION_IDENTITY_OPERATION_ID = + DSL.field(DSL.name("version_identity_operation_id"), UUID.class); + private static final Field GAME_DESIGN_VERSION_ID = + DSL.field(DSL.name("game_design_version_id"), Long.class); + private static final Field INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("intake_request_digest"), String.class); + + private final DSLContext dsl; + private final WorldAuthoredSourceIntakeRepository intakeRepository; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected repositories are internal Spring collaborators; construction acquires no resources and this repository has no finalizer.") + public WorldDesignPublicationFenceRepository( + DSLContext dsl, WorldAuthoredSourceIntakeRepository intakeRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.intakeRepository = Objects.requireNonNull(intakeRepository, "intakeRepository"); + } + + /** + * Acquires the shared writable version row for an ordinary mutation and holds its row lock until + * the caller's owner transaction ends. The exact committed intake is resolved before row create + * or lock; the private local tenant key is always derived from that immutable intake. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void lockOpen(OwnerBinding binding) { + lockOpenAndResolve(binding); + } + + /** Exact retained source and private keys, available only after the OPEN owner lock is held. */ + record OpenOwner( + OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt, long localVersionKey) { + long localTenantKey() { + return receipt.localTenantKey(); + } + } + + @Transactional(propagation = Propagation.MANDATORY) + OpenOwner lockOpenAndResolve(OwnerBinding binding) { + requireWritableReadCommittedOwnerTransaction(); + ResolvedVersion resolvedVersion = resolveVersion(binding); + Record owner = createAndLockOwner(resolvedVersion); + requireMatchingOwnerBinding(owner, resolvedVersion); + if (!OPEN.equals(owner.get(OWNER_FREEZE_PHASE, String.class))) { + throw new ConflictException("World version is not open for an ordinary Draft mutation"); + } + if (owner.get(CURRENT_PUBLICATION_FENCE, UUID.class) != null) { + throw new ConflictException("Open World version unexpectedly retains a publication fence"); + } + return new OpenOwner(binding, resolvedVersion.receipt(), resolvedVersion.localVersionKey()); + } + + /** + * Claims the owner-local freeze after taking the same version row lock as ordinary writers. + * + *

The checkpoint supplier runs only for the first OPEN-to-FROZEN transition, after this + * transaction holds the row lock. An exact retry returns the stored fence and checkpoint without + * recapturing server-derived output. No producer, caller authentication, or public freeze route + * is established by this internal persistence method. + */ + @Transactional(propagation = Propagation.MANDATORY) + public FrozenAttempt claimFreeze( + WorldDesignPublicationFenceEvidence evidence, Supplier checkpointSupplier) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(checkpointSupplier, "checkpointSupplier"); + OwnerBinding binding = evidence.ownerBinding(); + ResolvedVersion resolvedVersion = resolveVersion(binding); + rejectLegacyAttempt(evidence, resolvedVersion.localVersionKey()); + Record owner = createAndLockOwner(resolvedVersion); + requireMatchingOwnerBinding(owner, resolvedVersion); + + String phase = owner.get(OWNER_FREEZE_PHASE, String.class); + UUID currentFence = owner.get(CURRENT_PUBLICATION_FENCE, UUID.class); + if (FROZEN.equals(phase)) { + if (currentFence == null) { + throw new ConflictException("Frozen World owner row has no publication fence"); + } + FrozenAttempt stored = findAttemptByFence(currentFence); + if (stored == null) { + throw new ConflictException("Frozen World owner row has no immutable attempt record"); + } + requireExactRequest(stored, evidence); + return stored; + } + if (!OPEN.equals(phase) || currentFence != null) { + throw new ConflictException( + "World version cannot start a publication freeze in its current phase"); + } + if (findAttemptByRequest(evidence, resolvedVersion.localVersionKey()) != null) { + throw new ConflictException("World publication request already has an immutable attempt"); + } + + Checkpoint checkpoint = + Objects.requireNonNull( + checkpointSupplier.get(), "checkpointSupplier returned no complete World checkpoint"); + UUID publicationFence = newNonNilUuid(); + int inserted = insertAttempt(evidence, resolvedVersion, publicationFence, checkpoint); + if (inserted != 1) { + throw new ConflictException("World publication attempt was not inserted"); + } + + int updated = + dsl.update(OWNER) + .set(OWNER_FREEZE_PHASE, FROZEN) + .set(CURRENT_PUBLICATION_FENCE, publicationFence) + .where( + TARGET_NAMESPACE + .eq(evidence.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(evidence.canonicalTenantId())) + .and(VERSION_ID.eq(resolvedVersion.localVersionKey())) + .and(OWNER_FREEZE_PHASE.eq(OPEN)) + .and(CURRENT_PUBLICATION_FENCE.isNull())) + .execute(); + if (updated != 1) { + throw new ConflictException("World publication freeze lost its locked OPEN owner row"); + } + return new FrozenAttempt(evidence, publicationFence, checkpoint); + } + + /** + * Reads one exact immutable attempt by its full request binding without creating or changing + * rows. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readAttempt(WorldDesignPublicationFenceEvidence evidence) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("World publication attempt read requires a committed read"); + } + ResolvedVersion resolvedVersion = resolveVersion(evidence.ownerBinding()); + rejectLegacyAttempt(evidence, resolvedVersion.localVersionKey()); + FrozenAttempt stored = findAttemptByRequest(evidence, resolvedVersion.localVersionKey()); + if (stored == null) { + return Optional.empty(); + } + requireExactRequest(stored, evidence); + return Optional.of(stored); + } + + private ResolvedVersion resolveVersion(OwnerBinding binding) { + Objects.requireNonNull(binding, "binding"); + WorldAuthoredSourceIntakeReceipt receipt = + intakeRepository + .read(binding.targetNamespace(), binding.intakeRequestId()) + .orElseThrow( + () -> + new MissingIntakeException( + "World publication fence requires an already committed authored-source intake")); + requireExactIntake(binding, receipt); + + Record identity = + dsl.selectFrom(VERSION_IDENTITY) + .where(VERSION_OPERATION_ID.eq(binding.versionIdentityOperationId())) + .forShare() + .fetchOne(); + if (identity == null) { + throw new MissingVersionIdentityException( + "World publication fence requires an exact retained V27 authored-Version identity"); + } + requireExactVersionIdentity(identity, binding, receipt); + Long localVersionKey = identity.get(VERSION_LOCAL_VERSION_KEY, Long.class); + if (localVersionKey == null || localVersionKey <= 0L) { + throw new ConflictException("World Version identity has no valid private local Version key"); + } + return new ResolvedVersion(binding, receipt, localVersionKey); + } + + private void requireExactIntake(OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt) { + if (!binding.targetNamespace().equals(receipt.targetNamespace()) + || !binding.canonicalTenantId().equals(receipt.canonicalTenantId()) + || !binding.intakeRequestId().equals(receipt.intakeRequestId()) + || !binding.intakeOperationId().equals(receipt.operationId()) + || !binding.intakeRequestDigest().equals(receipt.requestDigest()) + || !binding.sourceOperationId().equals(receipt.sourceOperationId()) + || !binding.sourceEvidenceDigest().equals(receipt.sourceEvidenceDigest()) + || !binding.intakeReceiptDigest().equals(receipt.receiptDigest())) { + throw new ConflictException( + "World publication request differs from the complete committed authored-source intake"); + } + } + + private void requireExactVersionIdentity( + Record identity, OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt) { + if (!Objects.equals( + identity.get(VERSION_OPERATION_ID, UUID.class), binding.versionIdentityOperationId()) + || !Objects.equals(identity.get(TARGET_NAMESPACE, String.class), binding.targetNamespace()) + || !Objects.equals( + identity.get(CANONICAL_TENANT_ID, UUID.class), binding.canonicalTenantId()) + || !Objects.equals( + identity.get(VERSION_CANONICAL_VERSION_ID, UUID.class), binding.canonicalVersionId()) + || !Objects.equals( + identity.get(VERSION_GAME_DESIGN_VERSION_ID, Long.class), binding.gameDesignVersionId()) + || !Objects.equals(identity.get(VERSION_WORLD_SLUG, String.class), receipt.worldSlug()) + || !Objects.equals( + identity.get(VERSION_INTAKE_OPERATION_ID, UUID.class), binding.intakeOperationId()) + || !Objects.equals( + identity.get(VERSION_INTAKE_REQUEST_ID, UUID.class), binding.intakeRequestId()) + || !Objects.equals( + identity.get(VERSION_LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey()) + || !Objects.equals( + identity.get(VERSION_INTAKE_REQUEST_DIGEST, String.class), + binding.intakeRequestDigest()) + || !Objects.equals( + identity.get(VERSION_SOURCE_OPERATION_ID, UUID.class), binding.sourceOperationId()) + || !Objects.equals( + identity.get(VERSION_SOURCE_EVIDENCE_DIGEST, String.class), + binding.sourceEvidenceDigest()) + || !Objects.equals( + identity.get(VERSION_INTAKE_RECEIPT_DIGEST, String.class), + binding.intakeReceiptDigest())) { + throw new ConflictException( + "World publication request differs from the exact V27 Version and intake binding"); + } + } + + private Record createAndLockOwner(ResolvedVersion resolvedVersion) { + OwnerBinding binding = resolvedVersion.binding(); + WorldAuthoredSourceIntakeReceipt receipt = resolvedVersion.receipt(); + dsl.insertInto(OWNER) + .set(TARGET_NAMESPACE, binding.targetNamespace()) + .set(CANONICAL_TENANT_ID, binding.canonicalTenantId()) + .set(LOCAL_TENANT_KEY, receipt.localTenantKey()) + .set(VERSION_ID, resolvedVersion.localVersionKey()) + .set(OWNER_FREEZE_PHASE, OPEN) + .onConflictDoNothing() + .execute(); + + Record owner = + dsl.selectFrom(OWNER) + .where( + TARGET_NAMESPACE + .eq(binding.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(binding.canonicalTenantId())) + .and(VERSION_ID.eq(resolvedVersion.localVersionKey()))) + .forUpdate() + .fetchOne(); + if (owner == null) { + throw new ConflictException("World version owner row could not be created or locked"); + } + return owner; + } + + private void requireMatchingOwnerBinding(Record owner, ResolvedVersion resolvedVersion) { + OwnerBinding binding = resolvedVersion.binding(); + WorldAuthoredSourceIntakeReceipt receipt = resolvedVersion.receipt(); + if (!Objects.equals(owner.get(TARGET_NAMESPACE, String.class), binding.targetNamespace()) + || !Objects.equals(owner.get(CANONICAL_TENANT_ID, UUID.class), binding.canonicalTenantId()) + || !Objects.equals(owner.get(LOCAL_TENANT_KEY, Long.class), receipt.localTenantKey()) + || !Objects.equals(owner.get(VERSION_ID, Long.class), resolvedVersion.localVersionKey())) { + throw new ConflictException( + "World version owner row is bound to a different canonical tenant association"); + } + } + + private int insertAttempt( + WorldDesignPublicationFenceEvidence evidence, + ResolvedVersion resolvedVersion, + UUID publicationFence, + Checkpoint checkpoint) { + OwnerBinding binding = resolvedVersion.binding(); + WorldAuthoredSourceIntakeReceipt receipt = resolvedVersion.receipt(); + return dsl.insertInto(ATTEMPT) + .set(PUBLICATION_FENCE, publicationFence) + .set(TARGET_NAMESPACE, binding.targetNamespace()) + .set(CANONICAL_TENANT_ID, binding.canonicalTenantId()) + .set(LOCAL_TENANT_KEY, receipt.localTenantKey()) + .set(VERSION_ID, resolvedVersion.localVersionKey()) + .set(OWNER_BINDING_SCHEMA_VERSION, (short) 1) + .set(CANONICAL_VERSION_ID, binding.canonicalVersionId()) + .set(VERSION_IDENTITY_OPERATION_ID, binding.versionIdentityOperationId()) + .set(GAME_DESIGN_VERSION_ID, binding.gameDesignVersionId()) + .set(INTAKE_OPERATION_ID, receipt.operationId()) + .set(INTAKE_REQUEST_ID, receipt.intakeRequestId()) + .set(INTAKE_REQUEST_DIGEST, receipt.requestDigest()) + .set(SOURCE_OPERATION_ID, receipt.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, receipt.sourceEvidenceDigest()) + .set(INTAKE_RECEIPT_DIGEST, receipt.receiptDigest()) + .set(PUBLICATION_REQUEST_ID, evidence.publicationRequestId()) + .set(REQUEST_DIGEST, evidence.requestDigest()) + .set(VERSION_STATE_EPOCH, evidence.versionStateEpoch()) + .set(PUBLISH_WORKFLOW_ID, evidence.publishWorkflowId()) + .set(APPLIED_COMMIT_ID, checkpoint.appliedCommitId()) + .set(CONTENT_DIGEST, checkpoint.contentDigest()) + .set(DIGEST_SCHEMA_VERSION, checkpoint.digestSchemaVersion()) + .execute(); + } + + private FrozenAttempt findAttemptByFence(UUID publicationFence) { + Record record = + dsl.selectFrom(ATTEMPT).where(PUBLICATION_FENCE.eq(publicationFence)).fetchOne(); + return record == null ? null : toFrozenAttempt(record); + } + + private FrozenAttempt findAttemptByRequest( + WorldDesignPublicationFenceEvidence evidence, long localVersionKey) { + Record record = + dsl.selectFrom(ATTEMPT) + .where( + TARGET_NAMESPACE + .eq(evidence.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(evidence.canonicalTenantId())) + .and(VERSION_ID.eq(localVersionKey)) + .and(PUBLICATION_REQUEST_ID.eq(evidence.publicationRequestId()))) + .fetchOne(); + return record == null ? null : toFrozenAttempt(record); + } + + private void rejectLegacyAttempt( + WorldDesignPublicationFenceEvidence evidence, long localVersionKey) { + Record legacyCandidate = + dsl.selectFrom(ATTEMPT) + .where( + TARGET_NAMESPACE + .eq(evidence.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(evidence.canonicalTenantId())) + .and(VERSION_ID.eq(localVersionKey)) + .and(PUBLICATION_REQUEST_ID.eq(evidence.publicationRequestId()))) + .fetchOne(); + if (legacyCandidate != null + && !Short.valueOf((short) 1) + .equals(legacyCandidate.get(OWNER_BINDING_SCHEMA_VERSION, Short.class))) { + throw new ConflictException( + "Legacy schema-0 World publication attempts are unqualified and cannot be promoted"); + } + } + + private FrozenAttempt toFrozenAttempt(Record record) { + Short ownerBindingSchemaVersion = record.get(OWNER_BINDING_SCHEMA_VERSION, Short.class); + if (!Short.valueOf((short) 1).equals(ownerBindingSchemaVersion)) { + throw new ConflictException( + "Legacy schema-0 World publication attempts are unqualified and cannot be promoted"); + } + WorldDesignPublicationFenceEvidence request = + new WorldDesignPublicationFenceEvidence( + record.get(TARGET_NAMESPACE), + record.get(CANONICAL_TENANT_ID), + record.get(CANONICAL_VERSION_ID), + record.get(VERSION_IDENTITY_OPERATION_ID), + record.get(GAME_DESIGN_VERSION_ID), + record.get(INTAKE_REQUEST_ID), + record.get(INTAKE_OPERATION_ID), + record.get(INTAKE_REQUEST_DIGEST), + record.get(SOURCE_OPERATION_ID), + record.get(SOURCE_EVIDENCE_DIGEST), + record.get(INTAKE_RECEIPT_DIGEST), + record.get(PUBLICATION_REQUEST_ID), + record.get(REQUEST_DIGEST), + record.get(VERSION_STATE_EPOCH), + record.get(PUBLISH_WORKFLOW_ID)); + Checkpoint checkpoint = + new Checkpoint( + record.get(APPLIED_COMMIT_ID), + record.get(CONTENT_DIGEST), + record.get(DIGEST_SCHEMA_VERSION)); + return new FrozenAttempt(request, record.get(PUBLICATION_FENCE), checkpoint); + } + + private void requireExactRequest( + FrozenAttempt stored, WorldDesignPublicationFenceEvidence supplied) { + if (!stored.request().equals(supplied)) { + throw new ConflictException( + "World publication request identity was reused with changed source or request binding"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World publication fence requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World publication fence requires a writable owner transaction"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World publication fence 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 publication fence requires a writable READ COMMITTED owner transaction"); + } + } + + private UUID newNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (NIL_UUID.equals(value)); + return value; + } + + private record ResolvedVersion( + OwnerBinding binding, WorldAuthoredSourceIntakeReceipt receipt, long localVersionKey) {} + + /** Exact input conflicts fail closed without changing either owner or attempt history. */ + public static class ConflictException extends IllegalStateException { + public ConflictException(String message) { + super(message); + } + } + + /** No owner state may be created for a missing or not-yet-committed authored-source intake. */ + public static final class MissingIntakeException extends IllegalStateException { + public MissingIntakeException(String message) { + super(message); + } + } + + /** No owner state may be created for a missing V27 source-qualified Version identity. */ + public static final class MissingVersionIdentityException extends ConflictException { + public MissingVersionIdentityException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplication.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplication.java new file mode 100644 index 0000000000..81cc28eb69 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplication.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** Complete fresh graph and the original Account operation; neither supplies permission. */ +public record WorldDraftGraphApplication( + WorldDraftTerminalOperation operation, WorldDraftTopologyCommitPlan plan) { + public WorldDraftGraphApplication { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(plan, "plan"); + if (!operation.binding().equals(plan.binding()) + || !operation.ownerBinding().equals(plan.ownerBinding())) { + throw new IllegalArgumentException( + "World graph application differs from original Account operation"); + } + plan.graph() + .freshGraphDeclaration() + .ifPresent( + declaration -> { + Map actualCounts = + plan.graph().nodes().stream() + .collect( + Collectors.groupingBy( + node -> + node.mutation() + .getAggregateType() + .name() + .replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""), + Collectors.counting())); + for (var family : declaration.familyCounts()) { + String name = family.family().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + if (actualCounts.getOrDefault(name, 0L) != family.count()) { + throw new IllegalArgumentException( + "Account-bound application differs from its complete family declaration"); + } + } + }); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java new file mode 100644 index 0000000000..ad1f185430 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java @@ -0,0 +1,373 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationService.CommitOrderProof; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** Fresh graph mutations and exact original Account receipt share one owner transaction. */ +public class WorldDraftGraphApplicationRepository { + private final DSLContext dsl; + private final WorldDesignPublicationFenceRepository fence; + private final WorldDraftTopologyCommitRepository topology; + private final WorldDraftStartLocationReceiptRepository startLocations; + private final ObjectMapper mapper; + + @SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW", justification = "No resources or finalizer.") + public WorldDraftGraphApplicationRepository( + DSLContext dsl, WorldDesignPublicationFenceRepository fence, ObjectMapper mapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.fence = Objects.requireNonNull(fence, "fence"); + this.mapper = Objects.requireNonNull(mapper, "mapper"); + topology = new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + startLocations = new WorldDraftStartLocationReceiptRepository(dsl); + } + + public Optional readCommitted( + WorldDraftGraphApplication application) { + requireCommittedRead(); + var rows = find(application.operation()); + if (rows.isEmpty()) return Optional.empty(); + if (rows.size() != 1) + throw new ConflictException("World application identities select conflicting results"); + return Optional.of(readExact(application, rows.getFirst())); + } + + /** Exact original Account recovery selector; decoding is not workload authentication. */ + public Optional readCommitted( + String targetNamespace, byte[] originalAccountBinding) { + requireCommittedRead(); + return readByOriginalAccountBinding(targetNamespace, originalAccountBinding); + } + + /** Reads the original namespace and Account selection inside the caller-owned RR snapshot. */ + Optional readInOwnedSnapshot( + String targetNamespace, byte[] originalAccountBinding) { + requireOwnedReadOnlyRepeatableReadSnapshot(); + return readByOriginalAccountBinding(targetNamespace, originalAccountBinding); + } + + private Optional readByOriginalAccountBinding( + String targetNamespace, byte[] originalAccountBinding) { + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + var account = DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + var rows = + dsl.fetch( + selectSql() + + " WHERE a.operation_id=? OR a.request_id=? OR a.commit_id=? OR a.authorization_fence_id=?", + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId()); + if (rows.isEmpty()) return Optional.empty(); + if (rows.size() != 1) + throw new ConflictException("World recovery identities select conflicting results"); + var application = reconstruct(rows.getFirst()); + if (!targetNamespace.equals(application.operation().ownerBinding().targetNamespace()) + || !Arrays.equals( + account.canonicalBytes(), application.operation().accountBindingBytes())) { + throw new ConflictException( + "World committed recovery differs from original namespace or full Account binding"); + } + return Optional.of(readExact(application, rows.getFirst())); + } + + private void requireOwnedReadOnlyRepeatableReadSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(java.sql.Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new ConflictException( + "World application snapshot read requires an active read-only REPEATABLE READ owner transaction"); + } + Integer jdbcIsolation = dsl.connectionResult(java.sql.Connection::getTransactionIsolation); + if (!Integer.valueOf(java.sql.Connection.TRANSACTION_REPEATABLE_READ).equals(jdbcIsolation)) { + throw new ConflictException( + "World application snapshot read requires actual JDBC REPEATABLE READ isolation"); + } + } + + WorldDraftGraphAppliedResult apply( + WorldDraftGraphApplication application, CommitOrderProof proof) { + requireTransaction(); + proof.requireExact(application.operation()); + var prior = find(application.operation()); + if (!prior.isEmpty()) return readUnique(application, prior); + fence.lockOpenAndResolve(application.operation().ownerBinding()); + prior = find(application.operation()); + if (!prior.isEmpty()) return readUnique(application, prior); + if (application.plan().graph().freshGraphDeclaration().isEmpty()) { + throw new ConflictException( + "New World graph applications require the complete original fresh-graph declaration"); + } + var operation = application.operation(); + if (dsl.fetchOne( + "SELECT 1 FROM world_draft_terminal_outcome WHERE operation_id=? OR request_id=? OR commit_id=? OR authorization_fence_id=?", + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId()) + != null) { + throw new ConflictException("World operation has definitive no-commit evidence"); + } + if (dsl.fetchOne( + "SELECT 1 FROM world_topology_draft_commit WHERE request_id=? OR commit_id=?", + operation.requestId(), + operation.commitId()) + != null + || dsl.fetchOne( + "SELECT 1 FROM world_region_draft_commit WHERE request_id=? OR commit_id=?", + operation.requestId(), + operation.commitId()) + != null) { + throw new ConflictException( + "Existing permission-unverified history cannot be promoted to APPLIED"); + } + // This call genuinely inserts all six families and CAS epochs before the receipt is possible. + // V39 independently requires that history to have been inserted in THIS transaction. + var stored = topology.store(application.plan()); + var result = WorldDraftGraphAppliedResult.create(application, stored.graphBytes()); + result + .startLocationReceipt() + .ifPresent( + receipt -> + startLocations.store(receipt, application.operation().accountBindingBytes())); + dsl.execute( + "INSERT INTO world_draft_graph_application (operation_id,request_id,commit_id,authorization_fence_id," + + "operation_bytes,account_binding_bytes,account_binding_digest,result_bytes,result_digest) VALUES (?,?,?,?,?,?,?,?,?)", + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId(), + operation.canonicalBytes(), + operation.accountBindingBytes(), + operation.accountBindingDigest(), + result.canonicalBytes(), + result.digest()); + return readUnique(application, find(operation)); + } + + public Optional readSynchronized( + DraftSynchronizedVisibilityEvidence evidence) { + requireCommittedRead(); + evidence.requireValid(); + var ownerResult = evidence.appliedOwnerResult(DraftCommitBinding.Owner.WORLD_MANAGEMENT); + var rows = + dsl.fetch( + selectSql() + " WHERE a.request_id=? OR a.commit_id=?", + evidence.binding().requestId(), + evidence.binding().commitId()); + if (rows.isEmpty()) + throw new ConflictException( + "World synchronized selection has no canonical World APPLIED-result carrier"); + if (rows.size() != 1) + throw new ConflictException("World synchronized selection has conflicting results"); + Record row = rows.getFirst(); + WorldDraftGraphApplication application = reconstruct(row); + var result = readExact(application, row); + if (!evidence + .request() + .targetNamespace() + .equals(application.operation().ownerBinding().targetNamespace()) + || !evidence.binding().equals(application.operation().binding()) + || !ownerResult.resultIdentity().equals(result.resultIdentity()) + || !Arrays.equals(ownerResult.resultBytes(), result.canonicalBytes()) + || !ownerResult.appliedEpochs().equals(result.appliedEpochs())) { + throw new ConflictException( + "World synchronized owner result differs from exact canonical retained graph application"); + } + return Optional.of( + new WorldCanonicalAuthoredGraphReader().read(application.plan(), result.graphBytes())); + } + + private WorldDraftGraphApplication reconstruct(Record row) { + try { + var account = + DraftAuthorizationFenceBinding.fromStored(row.get("account_binding_bytes", byte[].class)); + var binding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("binding_digest", String.class)); + var owner = mapper.readValue(row.get("owner_binding_json", String.class), OwnerBinding.class); + var operation = + new WorldDraftTerminalOperation( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId(), + binding, + owner, + account.canonicalBytes()); + return new WorldDraftGraphApplication( + operation, WorldDraftTopologyCommitPlan.create(binding, owner)); + } catch (RuntimeException invalid) { + throw new ConflictException("World application has invalid retained complete operation"); + } + } + + private WorldDraftGraphAppliedResult readUnique( + WorldDraftGraphApplication application, List rows) { + if (rows.size() != 1) + throw new ConflictException("World graph application was not stored exactly once"); + return readExact(application, rows.getFirst()); + } + + private WorldDraftGraphAppliedResult readExact( + WorldDraftGraphApplication application, Record row) { + var operation = application.operation(); + if (dsl.fetchOne( + "SELECT 1 FROM world_draft_graph_terminal_identity WHERE operation_id=? AND request_id=? " + + "AND commit_id=? AND authorization_fence_id=? AND account_binding_bytes=? AND account_binding_digest=? AND outcome='APPLIED'", + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId(), + operation.accountBindingBytes(), + operation.accountBindingDigest()) + == null) { + throw new ConflictException( + "World application identity was reused with changed complete binding or terminal identity"); + } + if (!operation.operationId().equals(row.get("operation_id", UUID.class)) + || !operation.requestId().equals(row.get("request_id", UUID.class)) + || !operation.commitId().equals(row.get("commit_id", UUID.class)) + || !operation.authorizationFenceId().equals(row.get("authorization_fence_id", UUID.class)) + || !Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !Arrays.equals( + operation.accountBindingBytes(), row.get("account_binding_bytes", byte[].class)) + || !operation.accountBindingDigest().equals(row.get("account_binding_digest", String.class)) + || !operation.binding().canonicalJson().equals(row.get("binding_json", String.class)) + || !operation.binding().digest().equals(row.get("binding_digest", String.class)) + || !mapper + .writeValueAsString(operation.ownerBinding()) + .equals(row.get("owner_binding_json", String.class)) + || !Objects.equals( + row.get("application_transaction_id", Long.class), + row.get("graph_transaction_id", Long.class))) { + throw new ConflictException( + "World application identity was reused with changed complete binding"); + } + var original = + topology.verifyOriginalSource( + application.plan(), + row.get("identity_json", String.class), + row.get("intake_json", String.class)); + if (!Objects.equals(original.localVersionKey(), row.get("local_version_key", Long.class)) + || !Objects.equals( + original.sourceIntakeReceipt().localTenantKey(), + row.get("local_tenant_key", Long.class)) + || !operation + .ownerBinding() + .targetNamespace() + .equals(row.get("target_namespace", String.class)) + || !operation.canonicalTenantId().equals(row.get("canonical_tenant_id", UUID.class)) + || !operation.canonicalVersionId().equals(row.get("canonical_version_id", UUID.class)) + || !operation + .ownerBinding() + .versionIdentityOperationId() + .equals(row.get("version_identity_operation_id", UUID.class)) + || !WorldDraftTopologyCommitEvidence.STATUS.equals( + row.get("storage_status", String.class))) { + throw new ConflictException( + "World application differs from retained source/Version association"); + } + byte[] graph = row.get("graph_bytes", byte[].class); + if (!WorldDraftGraphAppliedResult.digest(graph) + .equals("sha256:" + row.get("graph_sha256", String.class))) { + throw new ConflictException("World retained graph digest differs"); + } + var decoded = + topology.verifyImmutableBytes( + application.plan(), graph, row.get("storage_result_bytes", byte[].class)); + if (decoded.localTenantKey() != original.sourceIntakeReceipt().localTenantKey() + || decoded.localVersionKey() != original.localVersionKey()) { + throw new ConflictException("World retained graph differs from original private owner scope"); + } + for (var graphRow : decoded.rows()) { + if (dsl.fetchOne( + "SELECT 1 FROM world_authored_topology_identity WHERE id=? AND private_row_key=? " + + "AND family=? AND template_id=? AND request_id=? AND commit_id=? AND tenant_id=? AND version_id=?", + graphRow.mappingKey(), + graphRow.privateRowKey(), + graphRow.template().family().name(), + graphRow.template().templateId(), + operation.requestId(), + operation.commitId(), + decoded.localTenantKey(), + decoded.localVersionKey()) + == null) { + throw new ConflictException("World retained graph differs from immutable original mapping"); + } + } + try { + var startLocation = startLocations.read(application, graph); + if (application.plan().graph().freshGraphDeclaration().isPresent() + && startLocation.isEmpty()) { + throw new ConflictException("World APPLIED result lacks exact start-location evidence"); + } + return WorldDraftGraphAppliedResult.fromStored( + application, + graph, + row.get("result_bytes", byte[].class), + row.get("result_digest", String.class), + startLocation); + } catch (IllegalArgumentException invalid) { + throw new ConflictException("World APPLIED result failed exact immutable integrity readback"); + } + } + + private List find(WorldDraftTerminalOperation operation) { + return dsl.fetch( + selectSql() + + " WHERE a.operation_id=? OR a.request_id=? OR a.commit_id=? OR a.authorization_fence_id=?", + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId()); + } + + private static String selectSql() { + return "SELECT a.*,c.version_identity_operation_id,c.target_namespace,c.canonical_tenant_id,c.canonical_version_id," + + "c.local_tenant_key,c.local_version_key,c.owner_binding_json,c.binding_json,c.binding_digest," + + "c.graph_bytes,c.graph_sha256,c.storage_status,c.result_bytes AS storage_result_bytes," + + "c.application_transaction_id AS graph_transaction_id,to_jsonb(v)::text AS identity_json," + + "to_jsonb(i)::text AS intake_json FROM world_draft_graph_application a " + + "JOIN world_topology_draft_commit c ON c.request_id=a.request_id AND c.commit_id=a.commit_id " + + "JOIN world_authored_version_identity v ON v.operation_id=c.version_identity_operation_id " + + "JOIN world_authored_source_intake i ON i.operation_id=v.intake_operation_id"; + } + + private static void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) + throw new ConflictException("World applied read requires committed read"); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + throw new ConflictException("Writable World application transaction required"); + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) + throw new ConflictException("World application requires READ_COMMITTED"); + }); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationService.java new file mode 100644 index 0000000000..37e93a3244 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationService.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Account-bound owner component. Production authority is unavailable/default denied. + */ +public final class WorldDraftGraphApplicationService { + /** + * The missing protected Account producer must prove original COMMIT_ORDER remains held until BOTH + * original owner outcomes settle. A preflight, lease or source capture cannot implement this + * contract. Test implementations stipulate that authority; they do not prove a Gameplay handoff. + */ + @FunctionalInterface + public interface CommitOrderVerifier { + CommitOrderProof verifyHeldOriginalCommitOrder(WorldDraftTerminalOperation operation); + } + + /** Typed carrier, deliberately without a boolean authorization shortcut. */ + public static final class CommitOrderProof { + private final byte[] originalOperation; + private final byte[] originalAccountBinding; + + public CommitOrderProof(WorldDraftTerminalOperation operation) { + originalOperation = operation.canonicalBytes(); + originalAccountBinding = operation.accountBindingBytes(); + } + + void requireExact(WorldDraftTerminalOperation operation) { + if (!Arrays.equals(originalOperation, operation.canonicalBytes()) + || !Arrays.equals(originalAccountBinding, operation.accountBindingBytes())) { + throw new ConflictException( + "Account COMMIT_ORDER proof differs from original complete operation"); + } + } + } + + private final WorldDraftGraphApplicationRepository repository; + private final CommitOrderVerifier verifier; + private final TransactionTemplate transaction; + + public WorldDraftGraphApplicationService( + WorldDraftGraphApplicationRepository repository, PlatformTransactionManager manager) { + this( + repository, + manager, + operation -> { + throw new ConflictException( + "Protected Account original COMMIT_ORDER producer is unavailable"); + }); + } + + public WorldDraftGraphApplicationService( + WorldDraftGraphApplicationRepository repository, + PlatformTransactionManager manager, + CommitOrderVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + transaction = new TransactionTemplate(Objects.requireNonNull(manager, "manager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + public WorldDraftGraphAppliedResult apply(WorldDraftGraphApplication application) { + requireCommittedBoundary(); + var prior = repository.readCommitted(application); + if (prior.isPresent()) return prior.orElseThrow(); + CommitOrderProof proof = + Objects.requireNonNull( + verifier.verifyHeldOriginalCommitOrder(application.operation()), "COMMIT_ORDER proof"); + proof.requireExact(application.operation()); + return Objects.requireNonNull( + transaction.execute(status -> repository.apply(application, proof))); + } + + public Optional readCommitted( + WorldDraftGraphApplication application) { + requireCommittedBoundary(); + return repository.readCommitted(application); + } + + public Optional readCommitted( + String targetNamespace, byte[] originalAccountBinding) { + requireCommittedBoundary(); + return repository.readCommitted(targetNamespace, originalAccountBinding); + } + + private static void requireCommittedBoundary() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("World graph application requires no active caller transaction"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphAppliedResult.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphAppliedResult.java new file mode 100644 index 0000000000..4355d6dcb1 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphAppliedResult.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.ObjectMapper; + +/** + * Immutable graph/Account/complete-epoch carrier; only the atomic application writer creates it. + */ +public final class WorldDraftGraphAppliedResult { + private final WorldDraftGraphApplication application; + private final byte[] graphBytes; + private final byte[] canonicalBytes; + private final Optional startLocationReceipt; + + private WorldDraftGraphAppliedResult(WorldDraftGraphApplication application, byte[] graphBytes) { + this.application = Objects.requireNonNull(application, "application"); + this.graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + new WorldCanonicalAuthoredGraphReader().read(application.plan(), this.graphBytes); + startLocationReceipt = + application + .plan() + .graph() + .freshGraphDeclaration() + .map(ignored -> WorldDraftStartLocationReceipt.create(application, this.graphBytes)); + Map result = new LinkedHashMap<>(); + result.put( + "schema", + startLocationReceipt.isPresent() + ? "world-draft-graph-applied/v2" + : "world-draft-graph-applied/v1"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", base64(application.operation().canonicalBytes())); + result.put("graphBytesBase64", base64(this.graphBytes)); + result.put("graphDigest", digest(this.graphBytes)); + startLocationReceipt.ifPresent( + receipt -> { + result.put("startLocationReceiptBase64", base64(receipt.canonicalBytes())); + result.put("startLocationReceiptDigest", receipt.receiptDigest()); + }); + result.put("appliedEpochs", appliedEpochs()); + try { + canonicalBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(new ObjectMapper().writeValueAsString(result)); + } catch (java.io.IOException exception) { + throw new IllegalArgumentException("World applied result cannot be encoded", exception); + } + } + + static WorldDraftGraphAppliedResult create(WorldDraftGraphApplication application, byte[] graph) { + return new WorldDraftGraphAppliedResult(application, graph); + } + + static WorldDraftGraphAppliedResult fromStored( + WorldDraftGraphApplication application, + byte[] graph, + byte[] bytes, + String storedDigest, + Optional retainedStartLocation) { + var result = create(application, graph); + if (!result.startLocationReceipt.equals(retainedStartLocation) + || !Arrays.equals(result.canonicalBytes, bytes) + || !result.digest().equals(storedDigest)) { + throw new IllegalArgumentException( + "World APPLIED result differs from exact operation, graph or epochs"); + } + return result; + } + + public WorldDraftGraphApplication application() { + return application; + } + + public byte[] graphBytes() { + return graphBytes.clone(); + } + + public Optional startLocationReceipt() { + return startLocationReceipt; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest(canonicalBytes); + } + + public String resultIdentity() { + String schema = startLocationReceipt.isPresent() ? "v2" : "v1"; + return "world-draft-graph-applied/" + schema + ":" + application.operation().operationId(); + } + + public String status() { + return "APPLIED"; + } + + /** + * Original local outcome for a future authenticated recovery reader; no fence release authority. + */ + public DraftAuthorizationFenceBinding.OwnerReadback ownerReadback() { + var operation = application.operation(); + var readback = + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + operation.operationId(), + operation.commitId(), + operation.authorizationFenceId(), + operation.binding().digest(), + operation.accountBindingBytes(), + canonicalBytes()); + readback.requireBinding( + DraftAuthorizationFenceBinding.fromStored(operation.accountBindingBytes())); + return readback; + } + + public List appliedEpochs() { + return application.operation().binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + } + + private static String base64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidence.java new file mode 100644 index 0000000000..379b204648 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidence.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; + +/** + * Immutable component storage evidence; never Account permission, APPLIED, or fence release proof. + */ +public final class WorldDraftRegionCommitEvidence { + public static final String STATUS = "STORED_PERMISSION_UNVERIFIED"; + + private final DraftCommitBinding binding; + private final OwnerBinding ownerBinding; + private final byte[] graphBytes; + private final byte[] resultBytes; + + WorldDraftRegionCommitEvidence( + DraftCommitBinding binding, + OwnerBinding ownerBinding, + byte[] graphBytes, + byte[] resultBytes) { + this.binding = Objects.requireNonNull(binding, "binding"); + this.ownerBinding = Objects.requireNonNull(ownerBinding, "ownerBinding"); + this.graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + this.resultBytes = Objects.requireNonNull(resultBytes, "resultBytes").clone(); + if (graphBytes.length == 0 || resultBytes.length == 0) { + throw new IllegalArgumentException("Complete graph and storage result bytes are required"); + } + } + + public DraftCommitBinding binding() { + return binding; + } + + public OwnerBinding ownerBinding() { + return ownerBinding; + } + + public byte[] graphBytes() { + return graphBytes.clone(); + } + + public byte[] resultBytes() { + return resultBytes.clone(); + } + + public String status() { + return STATUS; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlan.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlan.java new file mode 100644 index 0000000000..f74180d733 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlan.java @@ -0,0 +1,234 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; + +/** + * Pure, typed validation of the World-owned region-upsert subset of a complete Draft commit. + * + *

This validates only the supplied owner binding and World revision subset. It does not + * authenticate the source evidence, authorize a write, consult storage, or represent an applied + * owner result. + */ +public final class WorldDraftRegionCommitPlan { + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final JsonFormat.Parser PAYLOAD_PARSER = JsonFormat.parser(); + + /** + * One decoded World revision, retaining its position in the enclosing canonical revision list. + */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable value messages.") + public record RegionRevision( + String revisionOrder, UUID revisionId, WorldDesignMutationRevision mutation) { + public RegionRevision { + Objects.requireNonNull(revisionOrder, "revisionOrder"); + Objects.requireNonNull(revisionId, "revisionId"); + Objects.requireNonNull(mutation, "mutation"); + } + } + + private final DraftCommitBinding binding; + private final WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding; + private final List regionRevisions; + + private WorldDraftRegionCommitPlan( + DraftCommitBinding binding, + WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding, + List regionRevisions) { + this.binding = binding; + this.ownerBinding = ownerBinding; + this.regionRevisions = List.copyOf(regionRevisions); + } + + /** + * Validates the World-owned ordered revision subset against the exact supplied owner scope. + * + *

The {@code ownerBinding} carries caller-supplied source evidence; this method checks that + * its canonical tenant, Version, and Game Design Version selector match the shared binding, but + * does not authenticate that evidence. + */ + public static WorldDraftRegionCommitPlan create( + DraftCommitBinding binding, WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(ownerBinding, "ownerBinding"); + validateTarget(binding.target(), ownerBinding); + + List decoded = new ArrayList<>(); + List expectedWorldUnits = new ArrayList<>(); + Set worldRevisionIds = new HashSet<>(); + Set regionIds = new HashSet<>(); + + for (DraftCommitBinding.RevisionPayload revision : binding.revisions()) { + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + continue; + } + if (!worldRevisionIds.add(revision.revisionId())) { + throw invalid("World subset contains a duplicate revision identity"); + } + + WorldDesignMutationRevision mutation = parseRevision(revision.payload()); + validateRevisionIdentity(binding.commitId(), revision, mutation); + validateSupportedRegionUpsert(mutation); + + String regionId = mutation.getAggregateId(); + parsePositiveId(regionId, "aggregate_id"); + if (!regionId.equals(mutation.getScopeId())) { + throw invalid("REGION_SUBTREE scope_id must exactly match aggregate_id"); + } + if (!regionIds.add(regionId)) { + throw invalid("World subset contains duplicate region mutations"); + } + + long aggregateEpoch = validateEpoch(mutation.getExpectedDraftRevisionEpoch(), "aggregate"); + long scopeEpoch = validateEpoch(mutation.getExpectedDraftScopeRevisionEpoch(), "scope"); + expectedWorldUnits.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + regionId, + "AGGREGATE", + regionId, + Long.toString(aggregateEpoch))); + expectedWorldUnits.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + regionId, + "REGION_SUBTREE", + regionId, + Long.toString(scopeEpoch))); + decoded.add(new RegionRevision(revision.revisionOrder(), revision.revisionId(), mutation)); + } + + if (decoded.isEmpty()) { + throw invalid("Draft commit has no World-owned region revisions"); + } + requireExactWorldUnits(binding.affectedUnits(Owner.WORLD_MANAGEMENT), expectedWorldUnits); + return new WorldDraftRegionCommitPlan(binding, ownerBinding, decoded); + } + + /** Returns the exact immutable enclosing commit binding, including other owners' declarations. */ + public DraftCommitBinding binding() { + return binding; + } + + /** Returns the exact source-qualified World owner scope validated for this plan. */ + public WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding() { + return ownerBinding; + } + + /** Returns the decoded World region revisions in their original enclosing revision order. */ + public List regionRevisions() { + return List.copyOf(regionRevisions); + } + + private static void validateTarget( + DraftCommitBinding.TargetProof target, + WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding) { + // Compare only the canonical identity and Game Design Version selector present in both + // contracts. The World-local numeric key is not part of either input and must not be inferred + // from the Game Design selector. Remaining source-qualified evidence is retained on the plan + // and must be checked against World's retained identity and intake at its owner boundary. + if (!target.canonicalTenantId().equals(ownerBinding.canonicalTenantId()) + || !target.canonicalVersionId().equals(ownerBinding.canonicalVersionId()) + || target.gameDesignVersionRowId() != ownerBinding.gameDesignVersionId()) { + throw invalid("Draft commit target does not match the supplied World owner binding"); + } + } + + private static WorldDesignMutationRevision parseRevision(String payload) { + WorldDesignMutationRevision.Builder builder = WorldDesignMutationRevision.newBuilder(); + try { + // Unknown JSON fields are rejected by the default parser; accepting them would permit + // unvalidated input to disappear from the owner-specific typed interpretation. + PAYLOAD_PARSER.merge(payload, builder); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalArgumentException( + "World revision payload is not valid typed JSON", exception); + } + return builder.build(); + } + + private static void validateRevisionIdentity( + UUID commitId, + DraftCommitBinding.RevisionPayload revision, + WorldDesignMutationRevision mutation) { + if (!commitId.toString().equals(mutation.getCommitId())) { + throw invalid("World payload commit_id does not match the enclosing commit"); + } + if (!revision.revisionId().toString().equals(mutation.getLogicalRevisionId())) { + throw invalid("World payload logical_revision_id does not match the enclosing revision"); + } + } + + private static void validateSupportedRegionUpsert(WorldDesignMutationRevision mutation) { + if (mutation.getOperation() + != WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT + || mutation.getAggregateType() + != WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + || mutation.getScopeType() != WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE + || mutation.getScopeMutationPolicy() + != WorldDesignScopeMutationPolicy.WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED + || mutation.getPayloadCase() != WorldDesignMutationRevision.PayloadCase.REGION) { + throw invalid( + "World commit plan supports only existing REGION UPSERT with REGION_SUBTREE scope"); + } + if (mutation.getRegion().getName().isBlank()) { + throw invalid("REGION UPSERT requires a nonempty region name"); + } + double spacing = mutation.getRegion().getSpacingMultiplier(); + // The existing World mutation contract treats zero as the default multiplier (1.0). + if (!Double.isFinite(spacing) || spacing < 0.0d) { + throw invalid("REGION UPSERT spacing_multiplier must be finite and nonnegative"); + } + } + + private static long parsePositiveId(String value, String label) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw invalid(label + " must be a canonical positive decimal ID"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException(label + " is outside the supported ID range", exception); + } + } + + private static long validateEpoch(long epoch, String label) { + if (epoch < 0L || epoch == Long.MAX_VALUE) { + throw invalid("Expected Draft " + label + " epoch must be nonnegative and advanceable"); + } + return epoch; + } + + private static void requireExactWorldUnits( + List declaredUnits, List expectedUnits) { + if (declaredUnits.size() != expectedUnits.size() + || !new HashSet<>(declaredUnits).equals(new HashSet<>(expectedUnits))) { + throw invalid( + "World affected units must exactly match each REGION aggregate and REGION_SUBTREE fence"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java new file mode 100644 index 0000000000..bf274ff1c1 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepository.java @@ -0,0 +1,249 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.OpenOwner; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** + * Complete region storage over existing owner tables. Immutable graphs are historical evidence, + * never another mutable graph or a publication checkpoint. This component has no runtime bean. + */ +public class WorldDraftRegionCommitRepository { + private final DSLContext dsl; + private final WorldDesignPublicationFenceRepository fence; + private final WorldAuthoredGraphReader reader; + private final WorldDraftRegionGraphStager stager; + private final ObjectMapper mapper; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Construction acquires no resources and this unwired component has no finalizer.") + public WorldDraftRegionCommitRepository( + DSLContext dsl, WorldDesignPublicationFenceRepository fence, ObjectMapper mapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.fence = Objects.requireNonNull(fence, "fence"); + this.mapper = Objects.requireNonNull(mapper, "mapper"); + reader = new WorldAuthoredGraphReader(dsl); + stager = new WorldDraftRegionGraphStager(); + } + + /** + * Independently reads the exact committed storage evidence without claiming an owner lock or + * write permission. Absence is unknown, never proof of abort or that an operation cannot commit. + */ + public Optional readCommitted(WorldDraftRegionCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage readback requires no active caller transaction"); + } + return Optional.ofNullable(find(plan, mapper.writeValueAsString(plan.ownerBinding()))); + } + + WorldDraftRegionCommitEvidence store(WorldDraftRegionCommitPlan plan) { + requireTransaction(); + String ownerJson = mapper.writeValueAsString(plan.ownerBinding()); + WorldDraftRegionCommitEvidence replay = find(plan, ownerJson); + if (replay != null) { + return replay; + } + OpenOwner owner = fence.lockOpenAndResolve(plan.ownerBinding()); + requireSource(plan, owner); + // First claims and all same-Version writers/freeze share the V25 row. A contender may have + // completed while this transaction waited, so retry lookup must follow lock acquisition too. + replay = find(plan, ownerJson); + if (replay != null) { + return replay; + } + WorldAuthoredGraph before = + reader.readAndValidateGraph(owner.localTenantKey(), owner.localVersionKey()); + WorldAuthoredGraph staged = stager.stage(plan, before).graph(); + List> changes = changes(plan, staged); + dsl.resultQuery( + "SELECT world_store_guarded_region_rows(?::jsonb, ?::jsonb, ?::jsonb)", + ownerJson, + plan.binding().canonicalJson(), + mapper.writeValueAsString(changes)) + .fetch(); + byte[] graphBytes = + reader.readAndValidateGraph(owner.localTenantKey(), owner.localVersionKey()).encode(mapper); + if (!Arrays.equals(staged.encode(mapper), graphBytes)) { + throw new ConflictException("Stored World graph differs from the complete staged operation"); + } + byte[] resultBytes = encodeResult(plan, graphBytes); + dsl.execute( + "INSERT INTO world_region_draft_commit (target_namespace, canonical_tenant_id, canonical_version_id, " + + "request_id, commit_id, version_identity_operation_id, local_tenant_key, local_version_key, " + + "owner_binding_json, binding_json, binding_digest, graph_bytes, graph_sha256, result_bytes, storage_status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + plan.ownerBinding().targetNamespace(), + plan.binding().target().canonicalTenantId(), + plan.binding().target().canonicalVersionId(), + plan.binding().requestId(), + plan.binding().commitId(), + plan.ownerBinding().versionIdentityOperationId(), + owner.localTenantKey(), + owner.localVersionKey(), + ownerJson, + plan.binding().canonicalJson(), + plan.binding().digest(), + graphBytes, + sha256(graphBytes), + resultBytes, + WorldDraftRegionCommitEvidence.STATUS); + return new WorldDraftRegionCommitEvidence( + plan.binding(), plan.ownerBinding(), graphBytes, resultBytes); + } + + private byte[] encodeResult(WorldDraftRegionCommitPlan plan, byte[] graphBytes) { + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", "1"); + result.put("status", WorldDraftRegionCommitEvidence.STATUS); + result.put("requestId", plan.binding().requestId().toString()); + result.put("commitId", plan.binding().commitId().toString()); + result.put("bindingDigest", plan.binding().digest()); + result.put("ownerBinding", plan.ownerBinding()); + result.put("graphSha256", sha256(graphBytes)); + result.put( + "affectedEpochsAfter", + plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> { + Map after = new LinkedHashMap<>(); + after.put("aggregateType", unit.aggregateType()); + after.put("aggregateId", unit.aggregateId()); + after.put("scopeType", unit.scopeType()); + after.put("scopeId", unit.scopeId()); + after.put("epoch", Long.toString(Long.parseLong(unit.expectedEpoch()) + 1)); + return after; + }) + .toList()); + return mapper.writeValueAsBytes(result); + } + + private WorldDraftRegionCommitEvidence find(WorldDraftRegionCommitPlan plan, String ownerJson) { + // Request and commit identities cannot be silently reused under a different canonical target. + List rows = + dsl.resultQuery( + "SELECT c.*, v.local_tenant_key AS identity_tenant_key FROM world_region_draft_commit c " + + "JOIN world_authored_version_identity v ON v.operation_id = c.version_identity_operation_id " + + "WHERE c.request_id = ? OR c.commit_id = ?", + plan.binding().requestId(), + plan.binding().commitId()) + .fetch(); + if (rows.isEmpty()) { + return null; + } + if (rows.size() != 1) { + throw new ConflictException("World complete request and commit select conflicting history"); + } + Record row = rows.get(0); + DraftCommitBinding binding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("binding_digest", String.class)); + if (!binding.equals(plan.binding()) + || !ownerJson.equals(row.get("owner_binding_json", String.class))) { + throw new ConflictException( + "World complete request or commit was reused with changed full input or source"); + } + if (!Objects.equals( + row.get("target_namespace", String.class), plan.ownerBinding().targetNamespace()) + || !Objects.equals( + row.get("canonical_tenant_id", java.util.UUID.class), + binding.target().canonicalTenantId()) + || !Objects.equals( + row.get("canonical_version_id", java.util.UUID.class), + binding.target().canonicalVersionId()) + || !Objects.equals(row.get("request_id", java.util.UUID.class), binding.requestId()) + || !Objects.equals(row.get("commit_id", java.util.UUID.class), binding.commitId()) + || !Objects.equals( + row.get("version_identity_operation_id", java.util.UUID.class), + plan.ownerBinding().versionIdentityOperationId()) + || !Objects.equals( + row.get("local_tenant_key", Long.class), row.get("identity_tenant_key", Long.class))) { + throw new ConflictException( + "World complete immutable storage history has inconsistent identity provenance"); + } + byte[] graph = row.get("graph_bytes", byte[].class); + if (!sha256(graph).equals(row.get("graph_sha256", String.class)) + || !WorldDraftRegionCommitEvidence.STATUS.equals(row.get("storage_status", String.class))) { + throw new ConflictException("World complete immutable storage history is inconsistent"); + } + WorldAuthoredGraph.decode(graph, mapper); + byte[] storedResult = row.get("result_bytes", byte[].class); + if (!Arrays.equals(encodeResult(plan, graph), storedResult)) { + throw new ConflictException( + "World complete immutable result differs from its exact input, epochs or graph"); + } + return new WorldDraftRegionCommitEvidence(binding, plan.ownerBinding(), graph, storedResult); + } + + private List> changes( + WorldDraftRegionCommitPlan plan, WorldAuthoredGraph staged) { + return plan.regionRevisions().stream() + .map( + revision -> { + long id = Long.parseLong(revision.mutation().getAggregateId()); + Map region = + staged.regions().stream() + .filter(row -> Objects.equals(row.get("id"), id)) + .findFirst() + .orElseThrow(); + Map change = new LinkedHashMap<>(region); + change.put( + "expectedAggregateEpoch", + Long.toString(revision.mutation().getExpectedDraftRevisionEpoch())); + change.put( + "expectedScopeEpoch", + Long.toString(revision.mutation().getExpectedDraftScopeRevisionEpoch())); + return change; + }) + .toList(); + } + + private void requireSource(WorldDraftRegionCommitPlan plan, OpenOwner owner) { + AuthoredWorldSourceEvidence source = owner.receipt().source(); + DraftCommitBinding.TargetProof target = plan.binding().target(); + if (target.sourceGameRowId() != source.sourceGameRowId() + || !target.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !target.sourceProvenanceKind().equals(source.provenanceKind())) { + throw new ConflictException( + "World complete commit differs from retained intake source provenance"); + } + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Objects.equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(), + java.sql.Connection.TRANSACTION_READ_COMMITTED)) { + throw new ConflictException( + "World complete storage requires writable READ COMMITTED transaction"); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java new file mode 100644 index 0000000000..27b27d7721 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitService.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired complete owner-local storage component, with a fail-closed permission seam. + */ +public final class WorldDraftRegionCommitService { + /** + * Must fail unless the exact complete operation has durable Account ordering that remains held + * continuously through its terminal reconciliation. A preflight permission check is not reusable + * authorization for a later commit. No authenticated implementation is supplied in this slice; + * fixture implementations establish component storage prerequisites only. + */ + @FunctionalInterface + public interface PermissionVerifier { + void verify(WorldDraftRegionCommitPlan plan); + } + + private final WorldDraftRegionCommitRepository repository; + private final PermissionVerifier verifier; + private final TransactionTemplate transaction; + + /** Builds an unwired, denied component by default. */ + public WorldDraftRegionCommitService( + WorldDraftRegionCommitRepository repository, PlatformTransactionManager manager) { + this( + repository, + manager, + plan -> { + throw new ConflictException( + "Authenticated Account Draft commit permission is unavailable"); + }); + } + + public WorldDraftRegionCommitService( + WorldDraftRegionCommitRepository repository, + PlatformTransactionManager manager, + PermissionVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + transaction = new TransactionTemplate(Objects.requireNonNull(manager, "manager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + /** Verifies before opening the dedicated transaction; no external call runs while it is open. */ + public WorldDraftRegionCommitEvidence store(WorldDraftRegionCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage cannot start inside an existing transaction"); + } + verifier.verify(plan); + return Objects.requireNonNull(transaction.execute(status -> repository.store(plan))); + } + + /** + * Reads original committed storage evidence without invoking permission verification or a writer + * transaction. The result remains permission-unverified; absence is unknown rather than an abort + * or definitive no-commit outcome. + */ + public Optional readCommitted(WorldDraftRegionCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage readback requires no active caller transaction"); + } + return repository.readCommitted(plan); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStager.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStager.java new file mode 100644 index 0000000000..fd8273bbe5 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStager.java @@ -0,0 +1,153 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan.RegionRevision; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; + +/** Pure staging transform for an already supplied and validated World REGION commit plan. */ +public final class WorldDraftRegionGraphStager { + private static final Set CAPTURED_REGION_FIELDS = + Set.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"); + + /** + * Immutable in-memory content only; this is not APPLIED proof, commit authorization, synchronized + * Draft visibility, or release-eligible content. + */ + public record UnverifiedStagedContent( + DraftCommitBinding binding, OwnerBinding ownerBinding, WorldAuthoredGraph graph) { + public UnverifiedStagedContent { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(ownerBinding, "ownerBinding"); + Objects.requireNonNull(graph, "graph"); + } + } + + /** Applies all supported plan revisions to a copy of the supplied graph or returns no result. */ + public UnverifiedStagedContent stage( + WorldDraftRegionCommitPlan plan, WorldAuthoredGraph priorGraph) { + Objects.requireNonNull(plan, "plan"); + Objects.requireNonNull(priorGraph, "priorGraph"); + + List> regions = new ArrayList<>(priorGraph.regions()); + Map regionIndexes = indexRegions(regions); + Set updatedRegionIds = new HashSet<>(); + + for (RegionRevision revision : plan.regionRevisions()) { + WorldDesignMutationRevision mutation = revision.mutation(); + long regionId = parseRegionId(mutation.getAggregateId()); + if (!updatedRegionIds.add(regionId)) { + throw invalid("World region plan contains a duplicate staging target"); + } + Integer index = regionIndexes.get(regionId); + if (index == null) { + throw invalid("World region staging target does not exist in the supplied graph"); + } + + Map priorRegion = regions.get(index); + validateExistingRegion(priorRegion, regionId); + RegionDesignMutation payload = mutation.getRegion(); + validatePayload(payload); + LinkedHashMap updatedRegion = new LinkedHashMap<>(priorRegion); + updatedRegion.put("shardId", payload.getShardId()); + updatedRegion.put("name", payload.getName()); + updatedRegion.put("weather", blankToNull(payload.getWeather())); + updatedRegion.put("generationSeed", payload.getGenerationSeed()); + updatedRegion.put("generatorType", blankToNull(payload.getGeneratorType())); + updatedRegion.put("generatorParams", blankToNull(payload.getGeneratorParams())); + updatedRegion.put( + "spacingMultiplier", + payload.getSpacingMultiplier() == 0.0d ? 1.0d : payload.getSpacingMultiplier()); + regions.set(index, updatedRegion); + } + + WorldAuthoredGraph stagedGraph = priorGraph.withRegions(regions); + return new UnverifiedStagedContent(plan.binding(), plan.ownerBinding(), stagedGraph); + } + + private static Map indexRegions(List> regions) { + Map indexes = new HashMap<>(); + for (int index = 0; index < regions.size(); index++) { + Object rawId = regions.get(index).get("id"); + if (!(rawId instanceof Long id) || id <= 0L) { + throw invalid("Supplied World graph contains a missing or inconsistent region ID"); + } + if (indexes.putIfAbsent(id, index) != null) { + throw invalid("Supplied World graph contains duplicate region IDs"); + } + } + return indexes; + } + + private static void validateExistingRegion(Map region, long expectedId) { + if (!region.keySet().equals(CAPTURED_REGION_FIELDS) + || !Objects.equals(region.get("id"), expectedId) + || !(region.get("shardId") instanceof Integer shardId) + || shardId < 0 + || !(region.get("name") instanceof String name) + || name.isBlank() + || !nullableString(region.get("weather")) + || !(region.get("generationSeed") instanceof Long) + || !nullableString(region.get("generatorType")) + || !nullableString(region.get("generatorParams")) + || !(region.get("spacingMultiplier") instanceof Double spacingMultiplier) + || !Double.isFinite(spacingMultiplier) + || spacingMultiplier <= 0.0d) { + throw invalid("Supplied World graph contains an inconsistent existing region target"); + } + } + + private static void validatePayload(RegionDesignMutation payload) { + if (payload.getName().isBlank()) { + throw invalid("World region staging requires a nonempty region name"); + } + if (payload.getShardId() < 0) { + throw invalid("World region staging does not support a negative shard ID"); + } + double spacingMultiplier = payload.getSpacingMultiplier(); + if (!Double.isFinite(spacingMultiplier) || spacingMultiplier < 0.0d) { + throw invalid("World region staging requires finite nonnegative spacing"); + } + } + + private static long parseRegionId(String value) { + try { + long id = Long.parseLong(value); + if (id <= 0L || !Long.toString(id).equals(value)) { + throw new NumberFormatException("not a canonical positive region ID"); + } + return id; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("World region staging target ID is invalid", exception); + } + } + + private static boolean nullableString(Object value) { + return value == null || value instanceof String; + } + + private static String blankToNull(String value) { + return value.isBlank() ? null : value; + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingService.java new file mode 100644 index 0000000000..65d6160c34 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingService.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.OpenOwner; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionGraphStager.UnverifiedStagedContent; +import org.jooq.DSLContext; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** + * Explicitly unwired internal staging prerequisite over the actual source-qualified owner graph. + * This grants no write permission, APPLIED result, synchronized visibility, or publication proof. + */ +public class WorldDraftRegionStagingService { + private final WorldDesignPublicationFenceRepository fenceRepository; + private final WorldAuthoredGraphReader graphReader; + private final WorldDraftRegionGraphStager stager; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Construction acquires no resources and this internal component has no finalizer.") + public WorldDraftRegionStagingService( + DSLContext dsl, WorldDesignPublicationFenceRepository fenceRepository) { + this(fenceRepository, new WorldAuthoredGraphReader(dsl), new WorldDraftRegionGraphStager()); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Construction acquires no resources and this internal component has no finalizer.") + WorldDraftRegionStagingService( + WorldDesignPublicationFenceRepository fenceRepository, + WorldAuthoredGraphReader graphReader, + WorldDraftRegionGraphStager stager) { + this.fenceRepository = Objects.requireNonNull(fenceRepository, "fenceRepository"); + this.graphReader = Objects.requireNonNull(graphReader, "graphReader"); + this.stager = Objects.requireNonNull(stager, "stager"); + } + + /** + * Reads all six families after exact intake/V27 resolution and the shared OPEN owner lock. The + * caller owns the writable READ COMMITTED transaction. Only the existing owner lock row may be + * created; staged content remains in memory. + */ + @Transactional(propagation = Propagation.MANDATORY) + public UnverifiedStagedContent stage(WorldDraftRegionCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + OpenOwner owner = fenceRepository.lockOpenAndResolve(plan.ownerBinding()); + TargetProof target = plan.binding().target(); + AuthoredWorldSourceEvidence source = owner.receipt().source(); + if (target.sourceGameRowId() != source.sourceGameRowId() + || !Objects.equals(target.sourceGameTenantKey(), source.sourceGameTenantKey()) + || !Objects.equals(target.sourceProvenanceKind(), source.provenanceKind())) { + throw new WorldDesignPublicationFenceRepository.ConflictException( + "World Draft commit source provenance differs from the exact retained intake"); + } + WorldAuthoredGraph prior = + graphReader.readAndValidateGraph(owner.localTenantKey(), owner.localVersionKey()); + return stager.stage(plan, prior); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java new file mode 100644 index 0000000000..d7796b0f66 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.UUID; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; + +/** Exact durable selector evidence tied to its original Account operation and stored graph. */ +public record WorldDraftStartLocationReceipt( + String targetNamespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID authorizationFenceId, + String accountBindingDigest, + String bindingDigest, + RoomTemplateRef startLocation, + String graphDigest, + String receiptDigest) { + public WorldDraftStartLocationReceipt { + new WorldDraftStartLocationEvidence( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest, + receiptDigest); + } + + static WorldDraftStartLocationReceipt create( + WorldDraftGraphApplication application, byte[] graphBytes) { + var operation = application.operation(); + RoomTemplateRef selector = + application + .plan() + .graph() + .freshGraphDeclaration() + .orElseThrow( + () -> + new IllegalArgumentException( + "World start-location receipt requires an original graph declaration")) + .startLocation(); + String graphDigest = WorldDraftGraphAppliedResult.digest(graphBytes); + var evidence = + WorldDraftStartLocationEvidence.create( + operation.ownerBinding().targetNamespace(), + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId(), + operation.accountBindingDigest(), + operation.binding().digest(), + selector, + graphDigest); + return new WorldDraftStartLocationReceipt( + evidence.targetNamespace(), + evidence.operationId(), + evidence.requestId(), + evidence.commitId(), + evidence.authorizationFenceId(), + evidence.accountBindingDigest(), + evidence.bindingDigest(), + evidence.startLocation(), + evidence.graphDigest(), + evidence.receiptDigest()); + } + + byte[] canonicalBytes() { + return asEvidence().canonicalBytes(); + } + + private WorldDraftStartLocationEvidence asEvidence() { + return new WorldDraftStartLocationEvidence( + targetNamespace, + operationId, + requestId, + commitId, + authorizationFenceId, + accountBindingDigest, + bindingDigest, + startLocation, + graphDigest, + receiptDigest); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptRepository.java new file mode 100644 index 0000000000..80f6e708e2 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptRepository.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.jooq.DSLContext; +import org.jooq.Record; + +/** Stores and independently checks one immutable original Account-bound start selector. */ +final class WorldDraftStartLocationReceiptRepository { + private final DSLContext dsl; + + WorldDraftStartLocationReceiptRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + void store(WorldDraftStartLocationReceipt receipt, byte[] accountBindingBytes) { + Objects.requireNonNull(receipt, "receipt"); + Objects.requireNonNull(accountBindingBytes, "accountBindingBytes"); + dsl.execute( + "INSERT INTO world_draft_start_location_receipt (operation_id,request_id,commit_id," + + "authorization_fence_id,target_namespace,account_binding_bytes,account_binding_digest,binding_digest," + + "canonical_tenant_id,canonical_version_id,room_template_id,graph_digest,receipt_digest,receipt_bytes) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + receipt.operationId(), + receipt.requestId(), + receipt.commitId(), + receipt.authorizationFenceId(), + receipt.targetNamespace(), + accountBindingBytes, + receipt.accountBindingDigest(), + receipt.bindingDigest(), + receipt.startLocation().tenantId(), + receipt.startLocation().versionId(), + receipt.startLocation().roomTemplateId(), + receipt.graphDigest(), + receipt.receiptDigest(), + receipt.canonicalBytes()); + } + + Optional read( + WorldDraftGraphApplication application, byte[] graphBytes) { + var operation = application.operation(); + List rows = + dsl.fetch( + "SELECT * FROM world_draft_start_location_receipt WHERE operation_id=? OR request_id=? " + + "OR commit_id=? OR authorization_fence_id=?", + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId()); + if (rows.isEmpty()) { + return Optional.empty(); + } + if (rows.size() != 1 || application.plan().graph().freshGraphDeclaration().isEmpty()) { + throw new ConflictException( + "World start-location receipt has changed or lacks its original declaration"); + } + WorldDraftStartLocationReceipt expected = + WorldDraftStartLocationReceipt.create(application, graphBytes); + Record row = rows.getFirst(); + if (!expected.operationId().equals(row.get("operation_id", java.util.UUID.class)) + || !expected.requestId().equals(row.get("request_id", java.util.UUID.class)) + || !expected.commitId().equals(row.get("commit_id", java.util.UUID.class)) + || !expected + .authorizationFenceId() + .equals(row.get("authorization_fence_id", java.util.UUID.class)) + || !expected.targetNamespace().equals(row.get("target_namespace", String.class)) + || !Arrays.equals( + operation.accountBindingBytes(), row.get("account_binding_bytes", byte[].class)) + || !expected.accountBindingDigest().equals(row.get("account_binding_digest", String.class)) + || !expected.bindingDigest().equals(row.get("binding_digest", String.class)) + || !expected + .startLocation() + .tenantId() + .equals(row.get("canonical_tenant_id", java.util.UUID.class)) + || !expected + .startLocation() + .versionId() + .equals(row.get("canonical_version_id", java.util.UUID.class)) + || !expected + .startLocation() + .roomTemplateId() + .equals(row.get("room_template_id", java.util.UUID.class)) + || !expected.graphDigest().equals(row.get("graph_digest", String.class)) + || !expected.receiptDigest().equals(row.get("receipt_digest", String.class)) + || !Arrays.equals(expected.canonicalBytes(), row.get("receipt_bytes", byte[].class))) { + throw new ConflictException( + "World typed start-location receipt differs from exact original request, commit, Account binding or graph"); + } + return Optional.of(expected); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOperation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOperation.java new file mode 100644 index 0000000000..9321d55f70 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOperation.java @@ -0,0 +1,208 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; + +/** + * Exact identity for a World-local terminal result; the retained Account bytes are not permission. + */ +public final class WorldDraftTerminalOperation { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String SCHEMA = "world-draft-terminal-operation/v1"; + + private final UUID operationId; + private final UUID requestId; + private final UUID commitId; + private final UUID authorizationFenceId; + private final UUID canonicalTenantId; + private final UUID canonicalVersionId; + private final DraftCommitBinding binding; + private final OwnerBinding ownerBinding; + private final byte[] accountBindingBytes; + private final String accountBindingDigest; + private final byte[] canonicalBytes; + + public WorldDraftTerminalOperation( + UUID operationId, + UUID requestId, + UUID commitId, + UUID authorizationFenceId, + UUID canonicalTenantId, + UUID canonicalVersionId, + DraftCommitBinding binding, + OwnerBinding ownerBinding, + byte[] accountBindingBytes) { + this.operationId = requireUuid(operationId, "operationId"); + this.requestId = requireUuid(requestId, "requestId"); + this.commitId = requireUuid(commitId, "commitId"); + this.authorizationFenceId = requireUuid(authorizationFenceId, "authorizationFenceId"); + this.canonicalTenantId = requireUuid(canonicalTenantId, "canonicalTenantId"); + this.canonicalVersionId = requireUuid(canonicalVersionId, "canonicalVersionId"); + this.binding = Objects.requireNonNull(binding, "binding"); + this.ownerBinding = Objects.requireNonNull(ownerBinding, "ownerBinding"); + this.accountBindingBytes = requireBytes(accountBindingBytes, "accountBindingBytes"); + this.accountBindingDigest = digest(this.accountBindingBytes); + + DraftAuthorizationFenceBinding accountBinding = + DraftAuthorizationFenceBinding.fromStored(this.accountBindingBytes); + if (!requestId.equals(binding.requestId()) + || !commitId.equals(binding.commitId()) + || !canonicalTenantId.equals(binding.target().canonicalTenantId()) + || !canonicalVersionId.equals(binding.target().canonicalVersionId()) + || !canonicalTenantId.equals(ownerBinding.canonicalTenantId()) + || !canonicalVersionId.equals(ownerBinding.canonicalVersionId()) + || binding.target().gameDesignVersionRowId() != ownerBinding.gameDesignVersionId() + || !binding.requiredOwners().contains(DraftCommitBinding.Owner.WORLD_MANAGEMENT) + || !binding.requiredOwners().contains(DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) + || binding.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).isEmpty()) { + throw new IllegalArgumentException( + "World terminal identity differs from the complete Draft binding"); + } + if (!operationId.equals(accountBinding.operationId()) + || !requestId.equals(accountBinding.requestId()) + || !commitId.equals(accountBinding.commitId()) + || !authorizationFenceId.equals(accountBinding.fenceId()) + || !canonicalTenantId.equals(accountBinding.tenantId()) + || !canonicalVersionId.equals(accountBinding.versionId()) + || !binding.baseCommitId().equals(accountBinding.baseCommitId()) + || !binding.digest().equals(accountBinding.inputDigest()) + || !Arrays.equals(binding.canonicalBytes(), accountBinding.gameDesignBinding()) + || !Arrays.equals(binding.canonicalBytes(), accountBinding.normalizedInput())) { + throw new IllegalArgumentException( + "Complete V57 Account binding differs from the exact World operation"); + } + this.canonicalBytes = encodeCanonicalBytes(); + } + + public UUID operationId() { + return operationId; + } + + public UUID requestId() { + return requestId; + } + + public UUID commitId() { + return commitId; + } + + public UUID authorizationFenceId() { + return authorizationFenceId; + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public UUID canonicalVersionId() { + return canonicalVersionId; + } + + public DraftCommitBinding binding() { + return binding; + } + + public OwnerBinding ownerBinding() { + return ownerBinding; + } + + public byte[] accountBindingBytes() { + return accountBindingBytes.clone(); + } + + public String accountBindingDigest() { + return accountBindingDigest; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest(canonicalBytes); + } + + private byte[] encodeCanonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + frame(output, SCHEMA); + for (UUID id : + List.of( + operationId, + requestId, + commitId, + authorizationFenceId, + canonicalTenantId, + canonicalVersionId)) { + frame(output, id.toString()); + } + frame(output, binding.canonicalBytes()); + OwnerBinding owner = ownerBinding; + for (String value : + List.of( + owner.targetNamespace(), + owner.canonicalTenantId().toString(), + owner.canonicalVersionId().toString(), + owner.versionIdentityOperationId().toString(), + Long.toString(owner.gameDesignVersionId()), + owner.intakeRequestId().toString(), + owner.intakeOperationId().toString(), + owner.intakeRequestDigest(), + owner.sourceOperationId().toString(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest())) { + frame(output, value); + } + frame(output, accountBindingDigest); + frame(output, accountBindingBytes); + return output.toByteArray(); + } + + private static UUID requireUuid(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + return value; + } + + private static byte[] requireBytes(byte[] value, String label) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException(label + " must retain exact nonempty bytes"); + } + return value.clone(); + } + + private static void frame(ByteArrayOutputStream output, String value) { + frame(output, value.getBytes(StandardCharsets.UTF_8)); + } + + private static void frame(ByteArrayOutputStream output, byte[] value) { + try { + DataOutputStream data = new DataOutputStream(output); + data.writeInt(value.length); + data.write(value); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcome.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcome.java new file mode 100644 index 0000000000..aa5fd0d657 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcome.java @@ -0,0 +1,262 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; + +/** + * Immutable World-local definitive no-commit evidence; it is never an APPLIED result or permission. + */ +public final class WorldDraftTerminalOutcome { + private static final String SCHEMA = "world-draft-terminal-outcome/v1"; + private static final String ABORTED = "DEFINITIVELY_ABORTED"; + + /** Epoch observed while the V25 World owner row was locked for the no-commit decision. */ + public record ObservedEpoch(AffectedUnit unit, String epoch) { + public ObservedEpoch { + Objects.requireNonNull(unit, "unit"); + requireDecimal(epoch); + if (!epoch.equals(unit.expectedEpoch())) { + throw new IllegalArgumentException("Observed World epoch differs from the expected epoch"); + } + } + } + + private final WorldDraftTerminalOperation operation; + private final List observedEpochs; + private final byte[] canonicalBytes; + private final String digest; + private final OffsetDateTime recordedAt; + + private WorldDraftTerminalOutcome( + WorldDraftTerminalOperation operation, + List observedEpochs, + byte[] canonicalBytes, + String digest, + OffsetDateTime recordedAt) { + this.operation = Objects.requireNonNull(operation, "operation"); + this.observedEpochs = List.copyOf(observedEpochs); + this.canonicalBytes = canonicalBytes.clone(); + this.digest = Objects.requireNonNull(digest, "digest"); + this.recordedAt = Objects.requireNonNull(recordedAt, "recordedAt"); + requireCompleteEpochVector(operation, this.observedEpochs); + if (!digest(this.canonicalBytes).equals(digest) + || !Arrays.equals(this.canonicalBytes, encode(operation, this.observedEpochs))) { + throw new IllegalArgumentException( + "Stored World terminal outcome is not exact canonical evidence"); + } + } + + public static WorldDraftTerminalOutcome create( + WorldDraftTerminalOperation operation, + List observedEpochs, + OffsetDateTime recordedAt) { + List copy = List.copyOf(observedEpochs); + requireCompleteEpochVector(operation, copy); + byte[] encoded = encode(operation, copy); + return new WorldDraftTerminalOutcome(operation, copy, encoded, digest(encoded), recordedAt); + } + + public static WorldDraftTerminalOutcome fromStored( + WorldDraftTerminalOperation operation, + byte[] canonicalBytes, + String storedDigest, + OffsetDateTime recordedAt) { + List parsed = decode(operation, canonicalBytes); + return new WorldDraftTerminalOutcome( + operation, parsed, canonicalBytes, storedDigest, recordedAt); + } + + public WorldDraftTerminalOperation operation() { + return operation; + } + + public List observedEpochs() { + return List.copyOf(observedEpochs); + } + + public String outcome() { + return ABORTED; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + public OffsetDateTime recordedAt() { + return recordedAt; + } + + private static byte[] encode( + WorldDraftTerminalOperation operation, List observedEpochs) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + frame(output, SCHEMA); + frame(output, ABORTED); + frame(output, operation.canonicalBytes()); + frame(output, Integer.toString(observedEpochs.size())); + for (ObservedEpoch observed : observedEpochs) { + AffectedUnit unit = observed.unit(); + frame(output, unit.owner().name()); + frame(output, unit.aggregateType()); + frame(output, unit.aggregateId()); + frame(output, unit.scopeType()); + frame(output, unit.scopeId()); + frame(output, unit.expectedEpoch()); + frame(output, observed.epoch()); + } + return output.toByteArray(); + } + + private static List decode( + WorldDraftTerminalOperation operation, byte[] canonicalBytes) { + Objects.requireNonNull(canonicalBytes, "canonicalBytes"); + FrameReader reader = new FrameReader(canonicalBytes); + reader.expect(SCHEMA); + reader.expect(ABORTED); + if (!Arrays.equals(reader.bytes(), operation.canonicalBytes())) { + throw new IllegalArgumentException("World terminal outcome binds another operation"); + } + int count = reader.positiveCount(); + List result = new ArrayList<>(count); + for (int index = 0; index < count; index++) { + DraftCommitBinding.Owner owner = DraftCommitBinding.Owner.valueOf(reader.text()); + AffectedUnit unit = + new AffectedUnit( + owner, reader.text(), reader.text(), reader.text(), reader.text(), reader.text()); + result.add(new ObservedEpoch(unit, reader.text())); + } + reader.requireEnd(); + requireCompleteEpochVector(operation, result); + return List.copyOf(result); + } + + private static void requireCompleteEpochVector( + WorldDraftTerminalOperation operation, List observedEpochs) { + List expected = + operation.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT); + if (observedEpochs.size() != expected.size()) { + throw new IllegalArgumentException( + "Definitive World abort requires the complete affected set"); + } + for (int index = 0; index < expected.size(); index++) { + if (!expected.get(index).equals(observedEpochs.get(index).unit()) + || !expected.get(index).expectedEpoch().equals(observedEpochs.get(index).epoch())) { + throw new IllegalArgumentException( + "World abort epoch vector differs from exact Draft binding"); + } + } + } + + private static void frame(ByteArrayOutputStream output, String value) { + frame(output, value.getBytes(StandardCharsets.UTF_8)); + } + + private static void frame(ByteArrayOutputStream output, byte[] value) { + try { + DataOutputStream data = new DataOutputStream(output); + data.writeInt(value.length); + data.write(value); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static void requireDecimal(String value) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical epoch decimal required"); + } + } + + private static final class FrameReader { + private final ByteBuffer buffer; + + private FrameReader(byte[] bytes) { + buffer = ByteBuffer.wrap(bytes); + } + + private byte[] bytes() { + if (buffer.remaining() < Integer.BYTES) { + throw new IllegalArgumentException("Truncated World terminal evidence"); + } + int size = buffer.getInt(); + if (size <= 0 || size > buffer.remaining()) { + throw new IllegalArgumentException("Invalid World terminal evidence frame size"); + } + byte[] value = new byte[size]; + buffer.get(value); + return value; + } + + private String text() { + byte[] bytes = bytes(); + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException invalidUtf8) { + throw new IllegalArgumentException( + "World terminal evidence contains invalid UTF-8", invalidUtf8); + } + } + + private int positiveCount() { + String value = text(); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Complete World terminal epoch vector required"); + } + try { + int count = Integer.parseInt(value); + // Every epoch entry is seven nonempty length-framed strings. Bound allocation by the + // remaining bytes before constructing an attacker-controlled collection size. + if (count > buffer.remaining() / (7 * (Integer.BYTES + 1))) { + throw new IllegalArgumentException("Incomplete World terminal epoch vector"); + } + return count; + } catch (NumberFormatException overflow) { + throw new IllegalArgumentException("World terminal epoch vector is too large", overflow); + } + } + + private void expect(String expected) { + if (!expected.equals(text())) { + throw new IllegalArgumentException("Unsupported World terminal evidence schema/outcome"); + } + } + + private void requireEnd() { + if (buffer.hasRemaining()) { + throw new IllegalArgumentException("Trailing World terminal evidence frames"); + } + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeRepository.java new file mode 100644 index 0000000000..6865e38baf --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeRepository.java @@ -0,0 +1,464 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.sql.Connection; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.OpenOwner; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** + * Internal immutable no-commit storage. It does not authenticate or authorize a Draft operation. + */ +public final class WorldDraftTerminalOutcomeRepository { + private static final String TABLE = "world_draft_terminal_outcome"; + + private final DSLContext dsl; + private final WorldDesignPublicationFenceRepository fence; + private final ObjectMapper mapper; + + public WorldDraftTerminalOutcomeRepository( + DSLContext dsl, WorldDesignPublicationFenceRepository fence, ObjectMapper mapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.fence = Objects.requireNonNull(fence, "fence"); + this.mapper = Objects.requireNonNull(mapper, "mapper"); + } + + /** Absence stays UNKNOWN; committed reads never create rows or infer an abort. */ + public Optional readDefinitiveAbort( + WorldDraftTerminalOperation operation) { + Objects.requireNonNull(operation, "operation"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("World terminal readback requires a committed read"); + } + List rows = find(operation); + if (rows.isEmpty()) { + return Optional.empty(); + } + if (rows.size() != 1) { + throw new ConflictException("World terminal identities resolve to conflicting outcomes"); + } + return Optional.of(readExact(operation, rows.getFirst())); + } + + /** + * Reconstructs an exact read only from retained World terminal/source identity rows. Absence is + * UNKNOWN; conflicts or incomplete retained associations are never translated to an abort. + */ + public Optional readDefinitiveAbort( + String targetNamespace, byte[] originalAccountBinding) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("World terminal readback requires a committed read"); + } + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + byte[] original = DraftAuthorizationFenceBinding.bytes(originalAccountBinding); + DraftAuthorizationFenceBinding account = DraftAuthorizationFenceBinding.fromStored(original); + List rows = find(account); + if (rows.isEmpty()) { + return Optional.empty(); + } + if (rows.size() != 1) { + throw new ConflictException("World terminal identities resolve to conflicting outcomes"); + } + + Record row = rows.getFirst(); + DraftCommitBinding binding; + WorldDesignPublicationFenceEvidence.OwnerBinding owner; + try { + binding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("binding_digest", String.class)); + owner = + mapper.readValue( + row.get("owner_binding_json", String.class), + WorldDesignPublicationFenceEvidence.OwnerBinding.class); + } catch (RuntimeException invalidStoredBinding) { + throw new ConflictException("World terminal row has an invalid retained operation binding"); + } + + WorldDraftTerminalOperation operation; + try { + operation = + new WorldDraftTerminalOperation( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId(), + binding, + owner, + original); + } catch (RuntimeException invalidRetainedEvidence) { + throw new ConflictException( + "World terminal row differs from the complete original Account binding"); + } + requireRetainedSourceAssociation(targetNamespace, operation, row); + try { + return Optional.of(readExact(operation, row)); + } catch (ConflictException conflict) { + throw conflict; + } catch (RuntimeException invalidRetainedOutcome) { + throw new ConflictException("World terminal outcome failed immutable integrity readback"); + } + } + + /** Caller owns a short writable READ_COMMITTED transaction. */ + public WorldDraftTerminalOutcome recordDefinitiveAbort(WorldDraftTerminalOperation operation) { + requireTransaction(); + List prior = find(operation); + if (!prior.isEmpty()) { + if (prior.size() != 1) { + throw new ConflictException("World terminal identities resolve to conflicting outcomes"); + } + return readExact(operation, prior.getFirst()); + } + + OpenOwner owner = fence.lockOpenAndResolve(operation.ownerBinding()); + if (!owner.binding().equals(operation.ownerBinding()) || owner.localVersionKey() <= 0L) { + throw new ConflictException("World terminal request differs from the locked V25 owner scope"); + } + + // Recheck after V25 serialization. A commit that won the row lock is immutable history, + // including the older STORED_PERMISSION_UNVERIFIED component rows. + prior = find(operation); + if (!prior.isEmpty()) { + if (prior.size() != 1) { + throw new ConflictException("World terminal identities resolve to conflicting outcomes"); + } + return readExact(operation, prior.getFirst()); + } + requireNoWorldApplication(operation, owner); + List observed = observeExactEpochs(operation, owner); + OffsetDateTime recordedAt = OffsetDateTime.now(ZoneOffset.UTC); + WorldDraftTerminalOutcome outcome = + WorldDraftTerminalOutcome.create(operation, observed, recordedAt); + insert(operation, owner, outcome); + List inserted = find(operation); + if (inserted.size() != 1) { + throw new ConflictException("World definitive abort was not stored exactly once"); + } + return readExact(operation, inserted.getFirst()); + } + + private void insert( + WorldDraftTerminalOperation operation, OpenOwner owner, WorldDraftTerminalOutcome outcome) { + try { + dsl.execute( + "INSERT INTO " + + TABLE + + " (operation_id,request_id,commit_id,authorization_fence_id,target_namespace," + + "canonical_tenant_id,canonical_version_id,version_identity_operation_id," + + "local_tenant_key,local_version_key,owner_binding_json,binding_json,binding_digest," + + "account_binding_bytes,account_binding_digest,affected_units_json,outcome," + + "outcome_bytes,outcome_digest,recorded_at) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?::jsonb,?,?,?,?::timestamptz)", + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId(), + operation.ownerBinding().targetNamespace(), + operation.canonicalTenantId(), + operation.canonicalVersionId(), + operation.ownerBinding().versionIdentityOperationId(), + owner.localTenantKey(), + owner.localVersionKey(), + mapper.writeValueAsString(operation.ownerBinding()), + operation.binding().canonicalJson(), + operation.binding().digest(), + operation.accountBindingBytes(), + operation.accountBindingDigest(), + encodeAffectedUnits( + operation.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT)), + outcome.outcome(), + outcome.canonicalBytes(), + outcome.digest(), + outcome.recordedAt()); + } catch (RuntimeException failure) { + throw failure; + } + } + + private String encodeAffectedUnits(List affectedUnits) { + List> values = new ArrayList<>(); + for (AffectedUnit unit : affectedUnits) { + java.util.Map value = new java.util.LinkedHashMap<>(); + value.put("owner", unit.owner().name()); + value.put("aggregateType", unit.aggregateType()); + value.put("aggregateId", unit.aggregateId()); + value.put("scopeType", unit.scopeType()); + value.put("scopeId", unit.scopeId()); + value.put("expectedEpoch", unit.expectedEpoch()); + values.add(value); + } + return mapper.writeValueAsString(values); + } + + private List find(WorldDraftTerminalOperation operation) { + return dsl.fetch( + "SELECT * FROM " + + TABLE + + " WHERE operation_id = ? OR request_id = ? OR commit_id = ? OR authorization_fence_id = ?", + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId()); + } + + private List find(DraftAuthorizationFenceBinding account) { + return dsl.fetch( + "SELECT * FROM " + + TABLE + + " WHERE operation_id = ? OR request_id = ? OR commit_id = ? OR authorization_fence_id = ?", + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId()); + } + + private void requireRetainedSourceAssociation( + String targetNamespace, WorldDraftTerminalOperation operation, Record row) { + var owner = operation.ownerBinding(); + if (!targetNamespace.equals(owner.targetNamespace()) + || !targetNamespace.equals(row.get("target_namespace", String.class))) { + throw new ConflictException("World terminal read uses another workload namespace"); + } + Long localTenantKey = row.get("local_tenant_key", Long.class); + Long localVersionKey = row.get("local_version_key", Long.class); + if (localTenantKey == null || localVersionKey == null) { + throw new ConflictException("World terminal source association is incomplete"); + } + + Record identity = + dsl.fetchOne( + "SELECT * FROM world_authored_version_identity WHERE operation_id = ?", + owner.versionIdentityOperationId()); + if (identity == null + || !owner + .versionIdentityOperationId() + .equals(identity.get("operation_id", java.util.UUID.class)) + || !targetNamespace.equals(identity.get("target_namespace", String.class)) + || !owner + .canonicalTenantId() + .equals(identity.get("canonical_tenant_id", java.util.UUID.class)) + || !owner + .canonicalVersionId() + .equals(identity.get("canonical_version_id", java.util.UUID.class)) + || !Objects.equals( + owner.gameDesignVersionId(), identity.get("game_design_version_id", Long.class)) + || !Objects.equals(localTenantKey, identity.get("local_tenant_key", Long.class)) + || !Objects.equals(localVersionKey, identity.get("local_version_key", Long.class)) + || !owner.intakeRequestId().equals(identity.get("intake_request_id", java.util.UUID.class)) + || !owner + .intakeOperationId() + .equals(identity.get("intake_operation_id", java.util.UUID.class)) + || !owner.intakeRequestDigest().equals(identity.get("intake_request_digest", String.class)) + || !owner + .sourceOperationId() + .equals(identity.get("source_operation_id", java.util.UUID.class)) + || !owner + .sourceEvidenceDigest() + .equals(identity.get("source_evidence_digest", String.class)) + || !owner + .intakeReceiptDigest() + .equals(identity.get("intake_receipt_digest", String.class))) { + throw new ConflictException( + "World terminal source binding differs from the retained V27 identity"); + } + + Record versionOwner = + dsl.fetchOne( + "SELECT target_namespace, canonical_tenant_id, local_tenant_key, version_id " + + "FROM world_design_publication_fence_owner " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND local_tenant_key = ? AND version_id = ?", + targetNamespace, + owner.canonicalTenantId(), + localTenantKey, + localVersionKey); + if (versionOwner == null + || !targetNamespace.equals(versionOwner.get("target_namespace", String.class)) + || !owner + .canonicalTenantId() + .equals(versionOwner.get("canonical_tenant_id", java.util.UUID.class)) + || !Objects.equals(localTenantKey, versionOwner.get("local_tenant_key", Long.class)) + || !Objects.equals(localVersionKey, versionOwner.get("version_id", Long.class))) { + throw new ConflictException( + "World terminal source binding differs from the retained V25 owner association"); + } + } + + private WorldDraftTerminalOutcome readExact(WorldDraftTerminalOperation operation, Record row) { + if (!operation.operationId().equals(row.get("operation_id", java.util.UUID.class)) + || !operation.requestId().equals(row.get("request_id", java.util.UUID.class)) + || !operation.commitId().equals(row.get("commit_id", java.util.UUID.class)) + || !operation + .authorizationFenceId() + .equals(row.get("authorization_fence_id", java.util.UUID.class)) + || !operation + .canonicalTenantId() + .equals(row.get("canonical_tenant_id", java.util.UUID.class)) + || !operation + .canonicalVersionId() + .equals(row.get("canonical_version_id", java.util.UUID.class)) + || !operation + .ownerBinding() + .targetNamespace() + .equals(row.get("target_namespace", String.class)) + || !mapper + .writeValueAsString(operation.ownerBinding()) + .equals(row.get("owner_binding_json", String.class)) + || !operation + .ownerBinding() + .versionIdentityOperationId() + .equals(row.get("version_identity_operation_id", java.util.UUID.class)) + || !operation.binding().canonicalJson().equals(row.get("binding_json", String.class)) + || !operation.binding().digest().equals(row.get("binding_digest", String.class)) + || !Arrays.equals( + operation.accountBindingBytes(), row.get("account_binding_bytes", byte[].class)) + || !operation.accountBindingDigest().equals(row.get("account_binding_digest", String.class)) + || !"DEFINITIVELY_ABORTED".equals(row.get("outcome", String.class))) { + throw new ConflictException( + "World terminal identity was reused with changed binding or evidence"); + } + return WorldDraftTerminalOutcome.fromStored( + operation, + row.get("outcome_bytes", byte[].class), + row.get("outcome_digest", String.class), + row.get("recorded_at", OffsetDateTime.class)); + } + + private void requireNoWorldApplication(WorldDraftTerminalOperation operation, OpenOwner owner) { + if (exists( + "SELECT 1 FROM world_region_draft_commit WHERE request_id = ? OR commit_id = ?", + operation.requestId(), + operation.commitId()) + || exists( + "SELECT 1 FROM world_topology_draft_commit WHERE request_id = ? OR commit_id = ?", + operation.requestId(), + operation.commitId()) + || exists( + "SELECT 1 FROM world_authored_topology_identity " + + "WHERE request_id = ? OR commit_id = ?", + operation.requestId(), + operation.commitId()) + || exists( + "SELECT 1 FROM world_design_revision_ledger " + + "WHERE tenant_id = ? AND version_id = ? AND commit_id = ?", + owner.localTenantKey(), + owner.localVersionKey(), + operation.commitId().toString())) { + throw new ConflictException( + "Existing World application or identity history cannot be relabeled as no-commit"); + } + } + + private List observeExactEpochs( + WorldDraftTerminalOperation operation, OpenOwner owner) { + List expected = + operation.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT); + List observed = new ArrayList<>(expected.size()); + for (AffectedUnit unit : expected) { + long current = + "AGGREGATE".equals(unit.scopeType()) + ? aggregateEpoch(unit, operation, owner) + : scopeEpoch(unit, owner); + if (!Long.toString(current).equals(unit.expectedEpoch())) { + throw new ConflictException( + "Affected World epoch changed; definitive no-commit cannot be proved"); + } + observed.add(new WorldDraftTerminalOutcome.ObservedEpoch(unit, Long.toString(current))); + } + return List.copyOf(observed); + } + + private long aggregateEpoch( + AffectedUnit unit, WorldDraftTerminalOperation operation, OpenOwner owner) { + long aggregateKey; + if (unit.aggregateId().matches("[1-9][0-9]*")) { + try { + aggregateKey = Long.parseLong(unit.aggregateId()); + } catch (NumberFormatException overflow) { + throw new ConflictException("World numeric aggregate identity is out of range"); + } + } else { + java.util.UUID templateId; + try { + templateId = java.util.UUID.fromString(unit.aggregateId()); + } catch (IllegalArgumentException malformed) { + throw new ConflictException( + "World aggregate identity is neither canonical UUID nor private key"); + } + if (!templateId.toString().equals(unit.aggregateId())) { + throw new ConflictException("World aggregate UUID is not canonical"); + } + Record mapping = + dsl.fetchOne( + "SELECT private_row_key FROM world_authored_topology_identity " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND family = ? AND template_id = ?", + operation.ownerBinding().targetNamespace(), + operation.canonicalTenantId(), + operation.canonicalVersionId(), + unit.aggregateType(), + templateId); + if (mapping == null) { + return 0L; + } + aggregateKey = mapping.get("private_row_key", Long.class); + } + Record row = + dsl.fetchOne( + "SELECT draft_revision_epoch FROM world_design_aggregate_epoch " + + "WHERE tenant_id = ? AND version_id = ? AND aggregate_type = ? AND aggregate_id = ?", + owner.localTenantKey(), + owner.localVersionKey(), + unit.aggregateType(), + aggregateKey); + return row == null ? 0L : row.get("draft_revision_epoch", Long.class); + } + + private long scopeEpoch(AffectedUnit unit, OpenOwner owner) { + Record row = + dsl.fetchOne( + "SELECT draft_scope_revision_epoch FROM world_design_scope_epoch " + + "WHERE tenant_id = ? AND version_id = ? AND scope_type = ? AND scope_id = ?", + owner.localTenantKey(), + owner.localVersionKey(), + unit.scopeType(), + unit.scopeId()); + return row == null ? 0L : row.get("draft_scope_revision_epoch", Long.class); + } + + private boolean exists(String sql, Object... bindings) { + return dsl.fetchOne(sql, bindings) != null; + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new ConflictException("Writable World owner transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new ConflictException("World terminal outcome requires READ_COMMITTED"); + } + }); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeService.java new file mode 100644 index 0000000000..eb2651280c --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeService.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Non-authorizing internal storage boundary for exact World definitive-abort evidence. */ +public final class WorldDraftTerminalOutcomeService { + private final WorldDraftTerminalOutcomeRepository repository; + private final TransactionTemplate transaction; + + public WorldDraftTerminalOutcomeService( + WorldDraftTerminalOutcomeRepository repository, PlatformTransactionManager manager) { + this.repository = Objects.requireNonNull(repository, "repository"); + transaction = new TransactionTemplate(Objects.requireNonNull(manager, "manager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + /** + * Records a definitive no-commit result only after checking all World application history while + * holding the shared V25 row. This method does not authenticate the supplied Account bytes, + * authorize a caller, or release Account's fence. + */ + public WorldDraftTerminalOutcome recordDefinitiveAbort(WorldDraftTerminalOperation operation) { + Objects.requireNonNull(operation, "operation"); + Optional original = repository.readDefinitiveAbort(operation); + if (original.isPresent()) { + return original.orElseThrow(); + } + return Objects.requireNonNull( + transaction.execute(status -> repository.recordDefinitiveAbort(operation))); + } + + /** Committed readback; an absent row is UNKNOWN and never means no-commit. */ + public Optional readDefinitiveAbort( + WorldDraftTerminalOperation operation) { + return repository.readDefinitiveAbort(operation); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalReadGrpcService.java new file mode 100644 index 0000000000..b99fd116e7 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalReadGrpcService.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadServiceGrpc; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.TransientDataAccessException; + +/** + * Standalone authenticated read-only adapter for exact World committed/definitive-abort evidence. + * Authentication is checked before decoding the binding or querying terminal storage. This type is + * deliberately not registered as a runtime gRPC service in this slice. + */ +public final class WorldDraftTerminalReadGrpcService + extends WorldDraftTerminalReadServiceGrpc.WorldDraftTerminalReadServiceImplBase { + private final WorldDraftTerminalOutcomeRepository repository; + private final WorldDraftGraphApplicationRepository applications; + private final String trustedNamespace; + + public WorldDraftTerminalReadGrpcService( + WorldDraftTerminalOutcomeRepository repository, + WorldDraftGraphApplicationRepository applications, + String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.applications = Objects.requireNonNull(applications, "applications"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readWorldDraftTerminalOutcome( + ReadWorldDraftTerminalOutcomeRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedAccountPeer(responseObserver)) { + return; + } + + WorldDraftTerminalReadEvidence.Request readRequest; + try { + readRequest = WorldDraftTerminalReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalidRequest) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World terminal read request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("World terminal read namespace must match the authenticated peer") + .asRuntimeException()); + return; + } + + Optional outcome; + Optional committed; + try { + outcome = + repository.readDefinitiveAbort(trustedNamespace, readRequest.originalAccountBinding()); + committed = + applications.readCommitted(trustedNamespace, readRequest.originalAccountBinding()); + if (outcome.isPresent() && committed.isPresent()) { + throw new WorldDesignPublicationFenceRepository.ConflictException( + "World operation has contradictory terminal outcomes"); + } + } catch (WorldDesignPublicationFenceRepository.ConflictException conflict) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World terminal identity conflicts with retained owner evidence") + .asRuntimeException()); + return; + } catch (TransientDataAccessException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World terminal readback is temporarily unavailable") + .asRuntimeException()); + return; + } catch (DataAccessException | org.jooq.exception.DataAccessException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World terminal storage could not complete the read") + .asRuntimeException()); + return; + } catch (IllegalArgumentException invalidBinding) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical original Account binding is required") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL.withDescription("World terminal readback failed").asRuntimeException()); + return; + } + + Optional readback = + committed + .map(WorldDraftGraphAppliedResult::ownerReadback) + .or(() -> outcome.map(WorldDraftTerminalReadGrpcService::toOwnerReadback)); + ReadWorldDraftTerminalOutcomeResponse response; + try { + response = WorldDraftTerminalReadGrpcCodec.toResponse(readRequest, readback); + } catch (IllegalArgumentException invalidEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World terminal readback is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean requireAuthenticatedAccountPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null && peer.isService("account-service") && peer.isInNamespace(trustedNamespace)) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Verified same-namespace Account workload is required") + .asRuntimeException()); + return false; + } + + private static DraftAuthorizationFenceBinding.OwnerReadback toOwnerReadback( + WorldDraftTerminalOutcome outcome) { + WorldDraftTerminalOperation operation = outcome.operation(); + return new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED, + operation.operationId(), + operation.commitId(), + operation.authorizationFenceId(), + operation.binding().digest(), + operation.accountBindingBytes(), + outcome.canonicalBytes()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidence.java new file mode 100644 index 0000000000..1148443f7f --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidence.java @@ -0,0 +1,51 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; + +/** + * Immutable component storage evidence; never Account permission, APPLIED, or fence release proof. + */ +public final class WorldDraftTopologyCommitEvidence { + public static final String STATUS = "STORED_PERMISSION_UNVERIFIED"; + + private final DraftCommitBinding binding; + private final OwnerBinding ownerBinding; + private final byte[] graphBytes; + private final byte[] resultBytes; + + WorldDraftTopologyCommitEvidence( + DraftCommitBinding binding, + OwnerBinding ownerBinding, + byte[] graphBytes, + byte[] resultBytes) { + this.binding = Objects.requireNonNull(binding, "binding"); + this.ownerBinding = Objects.requireNonNull(ownerBinding, "ownerBinding"); + this.graphBytes = Objects.requireNonNull(graphBytes, "graphBytes").clone(); + this.resultBytes = Objects.requireNonNull(resultBytes, "resultBytes").clone(); + if (graphBytes.length == 0 || resultBytes.length == 0) { + throw new IllegalArgumentException("Complete graph and storage result bytes are required"); + } + } + + public DraftCommitBinding binding() { + return binding; + } + + public OwnerBinding ownerBinding() { + return ownerBinding; + } + + public byte[] graphBytes() { + return graphBytes.clone(); + } + + public byte[] resultBytes() { + return resultBytes.clone(); + } + + public String status() { + return STATUS; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java new file mode 100644 index 0000000000..ab565785ce --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java @@ -0,0 +1,446 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.EntityTemplateReference; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.FamilyCount; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.FreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Pure UUID-qualified validation of complete fresh six-family World input: PURE_UNVERIFIED only. + * + *

This does not authenticate source or Entity evidence, authorize Account commits, allocate or + * read storage, report APPLIED, expose a public handler, capture released content, or establish + * lifecycle/runtime readiness. Existing numeric REGION plans and historical graph bytes are + * separate. Free-text and localized JSON fields are preserved, not semantically validated. Zero + * spacing, exit cost and spawn count preserve the existing owner-default input convention; a future + * writer must apply those defaults without changing the original binding. + */ +public final class WorldDraftTopologyCommitPlan { + private static final ObjectMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final String TYPE_PREFIX = "WORLD_DESIGN_AGGREGATE_TYPE_"; + private static final String SCOPE_PREFIX = "WORLD_DESIGN_SCOPE_TYPE_"; + private static final List FRESH_FAMILY_ORDER = + List.of( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING); + + private record ObjectReference(WorldDesignAggregateType kind, UUID templateId) {} + + private final DraftCommitBinding binding; + private final OwnerBinding ownerBinding; + private final WorldDraftTopologyInputGraph graph; + + private WorldDraftTopologyCommitPlan( + DraftCommitBinding binding, OwnerBinding ownerBinding, WorldDraftTopologyInputGraph graph) { + this.binding = binding; + this.ownerBinding = ownerBinding; + this.graph = graph; + } + + /** + * Validates the exact supplied target and complete fresh input, without consulting any owner. All + * World references must close inside this graph; existing mappings are never guessed. + */ + public static WorldDraftTopologyCommitPlan create( + DraftCommitBinding binding, OwnerBinding ownerBinding) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(ownerBinding, "ownerBinding"); + var target = binding.target(); + if (!target.canonicalTenantId().equals(ownerBinding.canonicalTenantId()) + || !target.canonicalVersionId().equals(ownerBinding.canonicalVersionId()) + || target.gameDesignVersionRowId() != ownerBinding.gameDesignVersionId() + || !"NEW_GAME_ROW".equals(target.sourceProvenanceKind())) { + throw invalid("Fresh World input differs from its supplied canonical target/source kind"); + } + + Map nodes = new LinkedHashMap<>(); + Set revisionIds = new HashSet<>(); + List expected = new ArrayList<>(); + FreshGraphDeclaration freshGraphDeclaration = null; + for (var revision : binding.revisions()) { + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + continue; + } + WorldDesignMutationRevision mutation = parse(revision.payload()); + if (!binding.commitId().toString().equals(mutation.getCommitId()) + || !revision.revisionId().toString().equals(mutation.getLogicalRevisionId()) + || !revisionIds.add(revision.revisionId())) { + throw invalid("World payload commit/revision identity differs from its complete input"); + } + validateShape(mutation); + if (mutation.hasFreshGraphDeclaration()) { + if (freshGraphDeclaration != null) { + throw invalid("Fresh World input has multiple complete graph declarations"); + } + freshGraphDeclaration = + parseFreshGraphDeclaration( + mutation.getFreshGraphDeclaration(), + target.canonicalTenantId(), + target.canonicalVersionId()); + } + UUID id = uuid(mutation.getAggregateId()); + UUID scope = uuid(mutation.getScopeId()); + EntityTemplateReference entity = null; + if (mutation.hasWorldEntitySpawnBinding()) { + var spawn = mutation.getWorldEntitySpawnBinding(); + entity = + new EntityTemplateReference( + spawn.getEntityTemplateType(), target.canonicalTenantId(), + target.canonicalVersionId(), uuid(spawn.getEntityTemplateId())); + } + Node node = + new Node(revision.revisionOrder(), revision.revisionId(), id, scope, mutation, entity); + if (nodes.putIfAbsent(new ObjectReference(mutation.getAggregateType(), id), node) != null) { + throw invalid("Fresh graph repeats an authored identity within the same World family"); + } + String type = mutation.getAggregateType().name().substring(TYPE_PREFIX.length()); + expected.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, type, id.toString(), "AGGREGATE", id.toString(), "0")); + expected.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + type, + id.toString(), + mutation.getScopeType().name().substring(SCOPE_PREFIX.length()), + scope.toString(), + "0")); + } + if (nodes.isEmpty()) { + throw invalid("Fresh graph requires World input; an empty binding is not topology"); + } + validateClosure(nodes); + if (freshGraphDeclaration != null) { + validateDeclaredFamilies(freshGraphDeclaration, nodes); + } + List actual = binding.affectedUnits(Owner.WORLD_MANAGEMENT); + if (actual.size() != expected.size() + || !new HashSet<>(actual).equals(new HashSet<>(expected))) { + throw invalid("World affected units omit or change a derived aggregate/containing scope"); + } + return new WorldDraftTopologyCommitPlan( + binding, + ownerBinding, + new WorldDraftTopologyInputGraph( + target.canonicalTenantId(), + target.canonicalVersionId(), + new ArrayList<>(nodes.values()), + freshGraphDeclaration)); + } + + /** Exact immutable enclosing binding, including other owners and original payload bytes. */ + public DraftCommitBinding binding() { + return binding; + } + + /** Supplied source-qualified binding, retained unchanged and still unauthenticated. */ + public OwnerBinding ownerBinding() { + return ownerBinding; + } + + /** PURE_UNVERIFIED logical input only; no private row IDs or released snapshot. */ + public WorldDraftTopologyInputGraph graph() { + return graph; + } + + private static WorldDesignMutationRevision parse(String payload) { + try { + var parsed = STRICT_JSON.readTree(payload); + if (parsed == null || !parsed.isObject()) { + throw invalid("World typed payload must be an object"); + } + var builder = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(payload, builder); + return builder.build(); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalArgumentException("Unsupported World typed JSON", exception); + } catch (tools.jackson.core.JacksonException exception) { + throw new IllegalArgumentException( + "World typed JSON is not strict complete input", exception); + } + } + + private static void validateShape(WorldDesignMutationRevision m) { + if (m.getOperation() != WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT + || m.getScopeMutationPolicy() + != WorldDesignScopeMutationPolicy.WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED + || (m.getScopeType() != WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE + && m.getScopeType() != WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE) + || m.getExpectedDraftRevisionEpoch() != 0 + || m.getExpectedDraftScopeRevisionEpoch() != 0) { + throw invalid( + "Fresh input supports scoped UPSERT with zero epochs and no replacement policy"); + } + switch (m.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> { + require(m.hasRegion(), "REGION payload required"); + var p = m.getRegion(); + text(p.getName(), 100); + require( + p.getWeather().codePointCount(0, p.getWeather().length()) <= 50 + && p.getGeneratorType().codePointCount(0, p.getGeneratorType().length()) <= 50, + "Region weather/generator exceeds storage range"); + require( + p.getShardId() >= 0 + && Double.isFinite(p.getSpacingMultiplier()) + && p.getSpacingMultiplier() >= 0, + "Invalid region shard/spacing"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> { + require(m.hasZone(), "ZONE payload required"); + text(m.getZone().getName(), 100); + uuid(m.getZone().getRegionId()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> { + require(m.hasRoom(), "ROOM payload required"); + text(m.getRoom().getName(), 100); + uuid(m.getRoom().getZoneId()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> { + require(m.hasRoomExit(), "ROOM_EXIT payload required"); + var p = m.getRoomExit(); + uuid(p.getFromRoomId()); + uuid(p.getToRoomId()); + text(p.getDirection(), 32); + require(p.getCost() >= 0, "Exit cost must be nonnegative; zero retains the owner default"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> { + require(m.hasGenerationRule(), "GENERATION_RULE payload required"); + text(m.getGenerationRule().getName(), 100); + require( + m.getGenerationRule() + .getValue() + .codePointCount(0, m.getGenerationRule().getValue().length()) + <= 255, + "Rule value exceeds storage range"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> { + require(m.hasWorldEntitySpawnBinding(), "SPAWN payload required"); + var p = m.getWorldEntitySpawnBinding(); + uuid(p.getRoomId()); + uuid(p.getEntityTemplateId()); + require( + (p.getEntityTemplateType() + == EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM + || p.getEntityTemplateType() + == EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + && p.getSpawnCount() >= 0 + && p.getRespawnDelaySeconds() >= 0, + "Invalid spawn type/count/delay"); + } + default -> + throw invalid("Unsupported fresh World family; generated subtrees are not full input"); + } + } + + private static void validateClosure(Map nodes) { + Map zoneRegions = new HashMap<>(); + Map roomZones = new HashMap<>(); + for (Node node : nodes.values()) { + var m = node.mutation(); + if (m.hasZone()) { + UUID region = uuid(m.getZone().getRegionId()); + parent(nodes, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION); + zoneRegions.put(node.templateId(), region); + } else if (m.hasRoom()) { + UUID zone = uuid(m.getRoom().getZoneId()); + parent(nodes, zone, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE); + roomZones.put(node.templateId(), zone); + } + } + Set> rules = new HashSet<>(); + Set> spawns = new HashSet<>(); + Set> exits = new HashSet<>(); + for (Node node : nodes.values()) { + var m = node.mutation(); + boolean regionScope = + m.getScopeType() == WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE; + parent( + nodes, + node.scopeId(), + regionScope + ? WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + : WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE); + switch (m.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> + require( + regionScope && node.templateId().equals(node.scopeId()), + "Region scope must be itself"); + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> + require( + regionScope + ? node.scopeId().equals(zoneRegions.get(node.templateId())) + : node.scopeId().equals(node.templateId()), + "Zone is outside declared scope"); + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> + roomInScope(node.templateId(), node, roomZones, zoneRegions); + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> { + var p = m.getRoomExit(); + UUID from = uuid(p.getFromRoomId()); + UUID to = uuid(p.getToRoomId()); + roomInScope(from, node, roomZones, zoneRegions); + roomInScope(to, node, roomZones, zoneRegions); + require( + exits.add(List.of(from.toString(), p.getDirection())), + "Duplicate room/direction exit"); + } + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> + require( + rules.add( + List.of( + m.getScopeType().name(), + node.scopeId().toString(), + m.getGenerationRule().getName())), + "Duplicate scoped generation rule"); + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> { + var p = m.getWorldEntitySpawnBinding(); + roomInScope(uuid(p.getRoomId()), node, roomZones, zoneRegions); + require( + spawns.add( + List.of( + p.getRoomId(), p.getEntityTemplateType().name(), p.getEntityTemplateId())), + "Duplicate typed room/entity spawn binding"); + } + default -> throw invalid("Unsupported World family"); + } + } + } + + private static FreshGraphDeclaration parseFreshGraphDeclaration( + net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration declaration, + UUID tenantId, + UUID versionId) { + if (!uuid(declaration.getTenantId()).equals(tenantId) + || !uuid(declaration.getVersionId()).equals(versionId) + || !declaration.hasStartLocation()) { + throw invalid("Fresh World declaration differs from its exact canonical tenant/Version"); + } + var ref = declaration.getStartLocation(); + RoomTemplateRef startLocation = + new RoomTemplateRef( + uuid(ref.getTenantId()), uuid(ref.getVersionId()), uuid(ref.getRoomTemplateId())); + if (!startLocation.tenantId().equals(tenantId) + || !startLocation.versionId().equals(versionId)) { + throw invalid("World start-location reference differs from its graph tenant/Version"); + } + if (declaration.getFamilyCountsCount() != FRESH_FAMILY_ORDER.size()) { + throw invalid("Fresh World declaration requires exactly six ordered family counts"); + } + List counts = new ArrayList<>(); + for (int index = 0; index < FRESH_FAMILY_ORDER.size(); index++) { + var entry = declaration.getFamilyCounts(index); + if (entry.getFamily() != FRESH_FAMILY_ORDER.get(index) + || !entry.hasCount() + || entry.getCount() < 0) { + throw invalid("Fresh World family counts must be present, nonnegative and canonical"); + } + counts.add(new FamilyCount(entry.getFamily(), entry.getCount())); + } + return new FreshGraphDeclaration(tenantId, versionId, startLocation, counts); + } + + private static void validateDeclaredFamilies( + FreshGraphDeclaration declaration, Map nodes) { + if (!declaration.tenantId().equals(declaration.startLocation().tenantId()) + || !declaration.versionId().equals(declaration.startLocation().versionId())) { + throw invalid("World start-location selector has another canonical scope"); + } + for (FamilyCount count : declaration.familyCounts()) { + long actual = + nodes.values().stream() + .filter(node -> node.mutation().getAggregateType() == count.family()) + .count(); + if (actual != count.count()) { + throw invalid("Declared fresh World family count differs from complete original nodes"); + } + } + Node selectedRoom = + nodes.get( + new ObjectReference( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + declaration.startLocation().roomTemplateId())); + if (selectedRoom == null) { + throw invalid("World start location must name a ROOM in this complete graph and scope"); + } + } + + private static void roomInScope( + UUID room, Node node, Map rooms, Map zones) { + UUID zone = rooms.get(room); + require(zone != null, "Room reference is not in the complete fresh graph"); + UUID containing = + node.mutation().getScopeType() == WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE + ? zone + : zones.get(zone); + require(node.scopeId().equals(containing), "Room or exit endpoint is outside declared scope"); + } + + private static void parent( + Map nodes, UUID id, WorldDesignAggregateType type) { + Node node = nodes.get(new ObjectReference(type, id)); + require(node != null, "Missing or wrong-family reference in complete fresh graph"); + } + + private static UUID uuid(String value) { + try { + UUID id = UUID.fromString(value); + require( + id.toString().equals(value) && !id.equals(new UUID(0, 0)), + "World logical IDs require canonical non-nil UUIDs"); + return id; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "World logical IDs require canonical non-nil UUIDs", exception); + } + } + + private static void text(String value, int maximum) { + require( + !value.isBlank() && value.codePointCount(0, value.length()) <= maximum, + "Required World text is blank or exceeds storage range"); + } + + private static void require(boolean condition, String message) { + if (!condition) { + throw invalid(message); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java new file mode 100644 index 0000000000..5d3842330e --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java @@ -0,0 +1,617 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.OpenOwner; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Actual fresh six-family storage; explicitly unwired, with owner-internal private keys. */ +public class WorldDraftTopologyCommitRepository { + private final DSLContext dsl; + private final WorldDesignPublicationFenceRepository fence; + private final ObjectMapper mapper; + + @SuppressFBWarnings(value = "CT_CONSTRUCTOR_THROW", justification = "No resources or finalizer.") + public WorldDraftTopologyCommitRepository( + DSLContext dsl, WorldDesignPublicationFenceRepository fence, ObjectMapper mapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.fence = Objects.requireNonNull(fence, "fence"); + this.mapper = Objects.requireNonNull(mapper, "mapper"); + } + + /** Independent committed reconciliation: absence is UNKNOWN, never definitive abort. */ + public Optional readCommitted( + WorldDraftTopologyCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage readback requires no active caller transaction"); + } + return Optional.ofNullable(find(plan, mapper.writeValueAsString(plan.ownerBinding()))); + } + + /** + * Selects the retained immutable graph for one exact synchronized binding. The separate Game + * Design evidence must prove this owner is APPLIED; this row's STORED_PERMISSION_UNVERIFIED label + * is never treated as APPLIED or as authorization. Unlike reconciliation readback, this path + * intentionally does not consult mutable current topology rows or epochs. Selection requires the + * canonical Account-bound result written with a genuine fresh graph in one owner transaction. + */ + public Optional readSynchronized( + DraftSynchronizedVisibilityEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + evidence.requireValid(); + var applied = evidence.appliedOwnerResult(DraftCommitBinding.Owner.WORLD_MANAGEMENT); + if (!applied.commitId().equals(evidence.binding().commitId()) + || !applied.bindingDigest().equals(evidence.binding().digest())) { + throw new ConflictException( + "World owner APPLIED evidence differs from the exact Draft binding"); + } + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World synchronized graph selection requires no active caller transaction"); + } + return new WorldDraftGraphApplicationRepository(dsl, fence, mapper).readSynchronized(evidence); + } + + /** Caller already holds the exact shared V25 FROZEN owner lock; no writer is entered. */ + WorldDraftTopologyCommitEvidence readUnderFrozenLock(WorldDraftTopologyCommitPlan plan) { + requireTransaction(); + WorldDraftTopologyCommitEvidence stored = + find(plan, mapper.writeValueAsString(plan.ownerBinding())); + if (stored == null) { + throw new ConflictException("World frozen capture has no committed complete topology result"); + } + return stored; + } + + /** Validates historical bytes without consulting current content, epochs or owner phase. */ + WorldCanonicalAuthoredGraph verifyImmutableBytes( + WorldDraftTopologyCommitPlan plan, byte[] graph, byte[] result) { + WorldCanonicalAuthoredGraph decoded = new WorldCanonicalAuthoredGraphReader().read(plan, graph); + if (!Arrays.equals(result, encodeResult(plan, graph))) { + throw new ConflictException("World historical topology result differs from original input"); + } + return decoded; + } + + WorldDraftTopologyCommitEvidence store(WorldDraftTopologyCommitPlan plan) { + requireTransaction(); + String ownerJson = mapper.writeValueAsString(plan.ownerBinding()); + WorldDraftTopologyCommitEvidence prior = find(plan, ownerJson); + if (prior != null) { + return prior; + } + OpenOwner owner = fence.lockOpenAndResolve(plan.ownerBinding()); + var source = owner.receipt().source(); + var target = plan.binding().target(); + if (target.sourceGameRowId() != source.sourceGameRowId() + || !target.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !target.sourceProvenanceKind().equals(source.provenanceKind())) { + throw new ConflictException("World topology differs from retained intake source provenance"); + } + // Reconcile again after the shared OPEN/freeze lock: an exact first claimant may have won. + prior = find(plan, ownerJson); + if (prior != null) { + return prior; + } + dsl.resultQuery( + "SELECT world_store_guarded_uuid_topology(?::jsonb, ?::jsonb, ?::jsonb)", + ownerJson, + plan.binding().canonicalJson(), + mapper.writeValueAsString(executionRevisions(plan))) + .fetch(); + byte[] graph = readAndVerifyGraph(plan, owner.localTenantKey(), owner.localVersionKey()); + byte[] result = encodeResult(plan, graph); + dsl.execute( + "INSERT INTO world_topology_draft_commit (request_id,commit_id,version_identity_operation_id," + + "target_namespace,canonical_tenant_id,canonical_version_id,local_tenant_key,local_version_key," + + "owner_binding_json,binding_json,binding_digest,graph_bytes,graph_sha256,result_bytes,storage_status) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + plan.binding().requestId(), + plan.binding().commitId(), + plan.ownerBinding().versionIdentityOperationId(), + plan.ownerBinding().targetNamespace(), + target.canonicalTenantId(), + target.canonicalVersionId(), + owner.localTenantKey(), + owner.localVersionKey(), + ownerJson, + plan.binding().canonicalJson(), + plan.binding().digest(), + graph, + sha256(graph), + result, + WorldDraftTopologyCommitEvidence.STATUS); + return new WorldDraftTopologyCommitEvidence(plan.binding(), plan.ownerBinding(), graph, result); + } + + /** + * Trusted local typed projection, like V29's typed component changes. The complete original + * binding remains unchanged. SQL checks revision identities/order/owner; before storing history, + * actual rows are independently checked against the original parsed plan, so altered projected + * semantics roll back the complete transaction. This is never an input from a public caller. + */ + List executionRevisions(WorldDraftTopologyCommitPlan plan) { + List revisions = new ArrayList<>(); + for (Node node : plan.graph().nodes()) { + try { + revisions.add( + new DraftCommitBinding.RevisionPayload( + node.revisionOrder(), + node.revisionId(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(node.mutation()))); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException( + "World typed execution projection could not be encoded", exception); + } + } + return List.copyOf(revisions); + } + + private WorldDraftTopologyCommitEvidence find( + WorldDraftTopologyCommitPlan plan, String ownerJson) { + List records = + dsl.resultQuery( + "SELECT c.*, to_jsonb(v)::text AS identity_json, " + + "to_jsonb(i)::text AS intake_json FROM world_topology_draft_commit c " + + "JOIN world_authored_version_identity v ON v.operation_id=c.version_identity_operation_id " + + "JOIN world_authored_source_intake i ON i.operation_id=v.intake_operation_id " + + "WHERE c.request_id=? OR c.commit_id=?", + plan.binding().requestId(), + plan.binding().commitId()) + .fetch(); + if (records.isEmpty()) { + return null; + } + if (records.size() != 1) { + throw new ConflictException("World complete request and commit select conflicting history"); + } + Record row = records.getFirst(); + DraftCommitBinding binding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("binding_digest", String.class)); + if (!binding.equals(plan.binding()) + || !ownerJson.equals(row.get("owner_binding_json", String.class))) { + throw new ConflictException( + "World complete request or commit was reused with changed full input or source"); + } + WorldAuthoredVersionIdentityReceipt original = + verifyOriginalSource( + plan, row.get("identity_json", String.class), row.get("intake_json", String.class)); + long tenant = original.sourceIntakeReceipt().localTenantKey(); + long version = original.localVersionKey(); + var o = plan.ownerBinding(); + if (tenant <= 0 + || version <= 0 + || !Objects.equals(row.get("request_id", UUID.class), binding.requestId()) + || !Objects.equals(row.get("commit_id", UUID.class), binding.commitId()) + || !Objects.equals(row.get("target_namespace", String.class), o.targetNamespace()) + || !Objects.equals(row.get("canonical_tenant_id", UUID.class), o.canonicalTenantId()) + || !Objects.equals(row.get("canonical_version_id", UUID.class), o.canonicalVersionId()) + || !Objects.equals(row.get("local_tenant_key", Long.class), tenant) + || !Objects.equals(row.get("local_version_key", Long.class), version) + || !WorldDraftTopologyCommitEvidence.STATUS.equals( + row.get("storage_status", String.class))) { + throw new ConflictException("World immutable topology identity provenance is inconsistent"); + } + byte[] graph = row.get("graph_bytes", byte[].class); + byte[] result = row.get("result_bytes", byte[].class); + if (!sha256(graph).equals(row.get("graph_sha256", String.class)) + || !Arrays.equals(graph, readAndVerifyGraph(plan, tenant, version)) + || !Arrays.equals(result, encodeResult(plan, graph))) { + throw new ConflictException("World immutable topology payload, graph or result differs"); + } + return new WorldDraftTopologyCommitEvidence(binding, o, graph, result); + } + + /** Reuses the original closed source and Version evidence validators for detached history. */ + WorldAuthoredVersionIdentityReceipt verifyOriginalSource( + WorldDraftTopologyCommitPlan plan, String identityJson, String intakeJson) { + DraftCommitBinding binding = plan.binding(); + JsonNode identity = mapper.readTree(identityJson); + JsonNode intake = mapper.readTree(intakeJson); + var o = plan.ownerBinding(); + requireField(identity, "operation_id", o.versionIdentityOperationId()); + requireField(identity, "target_namespace", o.targetNamespace()); + requireField(identity, "canonical_tenant_id", o.canonicalTenantId()); + requireField(identity, "canonical_version_id", o.canonicalVersionId()); + requireField(identity, "game_design_version_id", o.gameDesignVersionId()); + requireField(identity, "intake_operation_id", o.intakeOperationId()); + requireField(identity, "intake_request_id", o.intakeRequestId()); + requireField(identity, "intake_request_digest", o.intakeRequestDigest()); + requireField(identity, "source_operation_id", o.sourceOperationId()); + requireField(identity, "source_evidence_digest", o.sourceEvidenceDigest()); + requireField(identity, "intake_receipt_digest", o.intakeReceiptDigest()); + requireField(intake, "operation_id", o.intakeOperationId()); + requireField(intake, "intake_request_id", o.intakeRequestId()); + requireField(intake, "target_namespace", o.targetNamespace()); + requireField(intake, "canonical_tenant_id", o.canonicalTenantId()); + requireField(intake, "request_digest", o.intakeRequestDigest()); + requireField(intake, "source_operation_id", o.sourceOperationId()); + requireField(intake, "source_evidence_digest", o.sourceEvidenceDigest()); + requireField(intake, "receipt_digest", o.intakeReceiptDigest()); + requireField(intake, "source_game_row_id", binding.target().sourceGameRowId()); + requireField(intake, "source_game_tenant_key", binding.target().sourceGameTenantKey()); + requireField(intake, "source_provenance_kind", binding.target().sourceProvenanceKind()); + long tenant = identity.path("local_tenant_key").asLong(); + long version = identity.path("local_version_key").asLong(); + requireField(intake, "local_tenant_key", tenant); + // Reuse the existing closed source/receipt validators; these are original local evidence, + // not a current upstream Version or permission check. + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + intake.path("source_schema_version").asInt(), + o.targetNamespace(), + UUID.fromString(intake.path("source_registration_request_id").asText()), + o.sourceOperationId(), + intake.path("source_request_digest").asText(), + o.canonicalTenantId(), + intake.path("tenant_slug").asText(), + intake.path("world_slug").asText(), + intake.path("world_display_name").asText(), + binding.target().sourceGameRowId(), + binding.target().sourceGameTenantKey(), + binding.target().sourceProvenanceKind(), + o.sourceEvidenceDigest()); + WorldAuthoredSourceIntakeReceipt receipt = + new WorldAuthoredSourceIntakeReceipt( + intake.path("schema_version").asInt(), + o.targetNamespace(), + o.intakeRequestId(), + o.intakeOperationId(), + o.canonicalTenantId(), + source.worldSlug(), + o.sourceOperationId(), + o.sourceEvidenceDigest(), + o.intakeRequestDigest(), + o.intakeReceiptDigest(), + tenant, + source); + AuthoredWorldVersionStateEvidence state = + mapper.readValue( + identity.path("version_state_evidence_json").asText(), + AuthoredWorldVersionStateEvidence.class); + WorldAuthoredVersionIdentityReceipt retainedIdentity = + new WorldAuthoredVersionIdentityReceipt( + 1, o.versionIdentityOperationId(), version, receipt, state); + requireField(identity, "version_state_schema_version", state.request().schemaVersion()); + requireField(identity, "version_state_read_request_id", state.request().readRequestId()); + requireField(identity, "version_state_epoch", state.versionStateEpoch()); + requireField(identity, "version_state_evidence_digest", state.evidenceDigest()); + requireField( + identity, + "version_state_state", + state.versionState().name().replace("VERSION_LIFECYCLE_STATE_", "")); + requireField(identity, "world_slug", source.worldSlug()); + if (!retainedIdentity.canonicalVersionId().equals(o.canonicalVersionId()) + || retainedIdentity.gameDesignVersionId() != o.gameDesignVersionId()) { + throw new ConflictException( + "World topology differs from retained closed Version/source evidence"); + } + return retainedIdentity; + } + + private byte[] readAndVerifyGraph(WorldDraftTopologyCommitPlan plan, long tenant, long version) { + List mappings = + dsl.resultQuery( + "SELECT to_jsonb(m)::text AS mapping_json FROM " + + "world_authored_topology_identity m WHERE request_id=? ORDER BY revision_order::numeric", + plan.binding().requestId()) + .fetch(); + if (mappings.size() != plan.graph().nodes().size()) { + throw new ConflictException("World topology has missing or extra exact UUID mappings"); + } + for (var type : + List.of( + "REGION", + "ZONE", + "ROOM", + "ROOM_EXIT", + "GENERATION_RULE", + "WORLD_ENTITY_SPAWN_BINDING")) { + long expected = plan.graph().nodes().stream().filter(n -> family(n).equals(type)).count(); + Long actual = + dsl.resultQuery( + "SELECT count(*) FROM " + + type.toLowerCase(java.util.Locale.ROOT) + + " WHERE tenant_id=? AND version_id=?", + tenant, + version) + .fetchOne(0, Long.class); + if (!Objects.equals(actual, expected)) { + throw new ConflictException( + "World topology contains extra or missing actual " + + type.toLowerCase(java.util.Locale.ROOT) + + " rows"); + } + } + Map keys = new HashMap<>(); + List identities = new ArrayList<>(); + for (int i = 0; i < mappings.size(); i++) { + Node node = plan.graph().nodes().get(i); + JsonNode m = mapper.readTree(mappings.get(i).get("mapping_json", String.class)); + String family = family(node); + requireField(m, "target_namespace", plan.ownerBinding().targetNamespace()); + requireField(m, "canonical_tenant_id", plan.graph().tenantId()); + requireField(m, "canonical_version_id", plan.graph().versionId()); + requireField(m, "family", family); + requireField(m, "template_id", node.templateId()); + requireField(m, "tenant_id", tenant); + requireField(m, "version_id", version); + requireField( + m, "version_identity_operation_id", plan.ownerBinding().versionIdentityOperationId()); + requireField(m, "request_id", plan.binding().requestId()); + requireField(m, "commit_id", plan.binding().commitId()); + requireField(m, "revision_id", node.revisionId()); + requireField(m, "revision_order", node.revisionOrder()); + long key = m.path("private_row_key").asLong(); + if (key <= 0 + || m.path("id").asLong() <= 0 + || keys.put(family + ":" + node.templateId(), key) != null) { + throw new ConflictException("World UUID mapping is not one-to-one"); + } + identities.add(m); + } + List> rows = new ArrayList<>(); + for (int i = 0; i < identities.size(); i++) { + Node node = plan.graph().nodes().get(i); + String family = family(node); + long key = keys.get(family + ":" + node.templateId()); + // The table name is selected only from the closed protobuf family enumeration. + Record row = + dsl.resultQuery( + "SELECT to_jsonb(t)::text AS content_json FROM " + + family.toLowerCase(java.util.Locale.ROOT) + + " t WHERE id=?", + key) + .fetchOne(); + if (row == null) { + throw new ConflictException("World UUID association has no actual allocated row"); + } + JsonNode actual = mapper.readTree(row.get("content_json", String.class)); + JsonNode expected = mapper.valueToTree(expectedContent(node, keys, tenant, version)); + if (!sameContent(actual, expected)) { + throw new ConflictException("World allocated row differs from every exact payload field"); + } + Map item = new LinkedHashMap<>(); + item.put("mapping", identities.get(i)); + item.put("content", actual); + rows.add(item); + } + for (Node node : plan.graph().nodes()) { + Long epoch = + dsl.resultQuery( + "SELECT draft_revision_epoch FROM world_design_aggregate_epoch " + + "WHERE tenant_id=? AND version_id=? AND aggregate_type=? AND aggregate_id=?", + tenant, + version, + family(node), + keys.get(family(node) + ":" + node.templateId())) + .fetchOne(0, Long.class); + if (!Objects.equals(epoch, 1L)) { + throw new ConflictException( + "World topology aggregate epoch differs from exact stored result"); + } + } + Long aggregateCount = + dsl.resultQuery( + "SELECT count(*) FROM world_design_aggregate_epoch " + + "WHERE tenant_id=? AND version_id=?", + tenant, + version) + .fetchOne(0, Long.class); + long scopeCountExpected = + plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .filter(u -> !u.scopeType().equals("AGGREGATE")) + .map(u -> u.scopeType() + ":" + u.scopeId()) + .distinct() + .count(); + Long scopeCount = + dsl.resultQuery( + "SELECT count(*) FROM world_design_scope_epoch " + + "WHERE tenant_id=? AND version_id=?", + tenant, + version) + .fetchOne(0, Long.class); + if (!Objects.equals(aggregateCount, (long) plan.graph().nodes().size()) + || !Objects.equals(scopeCount, scopeCountExpected)) { + throw new ConflictException("World topology has extra or missing exact epoch fences"); + } + for (var unit : plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT)) { + if (!unit.scopeType().equals("AGGREGATE")) { + Long epoch = + dsl.resultQuery( + "SELECT draft_scope_revision_epoch FROM world_design_scope_epoch " + + "WHERE tenant_id=? AND version_id=? AND scope_type=? AND scope_id=?", + tenant, + version, + unit.scopeType(), + unit.scopeId()) + .fetchOne(0, Long.class); + if (!Objects.equals(epoch, 1L)) { + throw new ConflictException( + "World topology scope epoch differs from exact stored result"); + } + } + } + Map graph = new LinkedHashMap<>(); + graph.put("schemaVersion", "2"); + graph.put("canonicalTenantId", plan.graph().tenantId().toString()); + graph.put("canonicalVersionId", plan.graph().versionId().toString()); + graph.put("rows", rows); + return mapper.writeValueAsBytes(graph); + } + + static Map expectedContent( + Node node, Map keys, long tenant, long version) { + Map row = new LinkedHashMap<>(); + var m = node.mutation(); + row.put("id", keys.get(family(node) + ":" + node.templateId())); + row.put("tenant_id", tenant); + row.put("version_id", version); + row.put("version", 0); + switch (m.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> { + var p = m.getRegion(); + row.put("name", p.getName()); + row.put("shard_id", p.getShardId()); + row.put("weather", p.getWeather()); + row.put("generation_seed", p.getGenerationSeed()); + row.put("generator_type", p.getGeneratorType()); + row.put("generator_params", p.getGeneratorParams()); + row.put( + "spacing_multiplier", p.getSpacingMultiplier() == 0 ? 1.0 : p.getSpacingMultiplier()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> { + row.put("name", m.getZone().getName()); + row.put("region_id", lookup(keys, "REGION", m.getZone().getRegionId())); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> { + var p = m.getRoom(); + row.put("name", p.getName()); + row.put("description", p.getDescription()); + row.put("zone_id", lookup(keys, "ZONE", p.getZoneId())); + row.put("name_localized_variants_json", p.getNameLocalizedVariantsJson()); + row.put("description_localized_variants_json", p.getDescriptionLocalizedVariantsJson()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> { + var p = m.getRoomExit(); + row.put("from_room_id", lookup(keys, "ROOM", p.getFromRoomId())); + row.put("to_room_id", lookup(keys, "ROOM", p.getToRoomId())); + row.put("direction", p.getDirection()); + row.put("cost", p.getCost() == 0 ? 1 : p.getCost()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> { + var p = m.getGenerationRule(); + row.put("name", p.getName()); + row.put("value", p.getValue()); + String scope = m.getScopeType().name().replace("WORLD_DESIGN_SCOPE_TYPE_", ""); + row.put("scope_type", scope); + row.put( + "scope_id", + lookup( + keys, + scope.equals("REGION_SUBTREE") ? "REGION" : "ZONE", + node.scopeId().toString()) + .toString()); + } + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> { + var p = m.getWorldEntitySpawnBinding(); + var e = node.entityReference(); + row.put("room_id", lookup(keys, "ROOM", p.getRoomId())); + row.put( + "entity_template_type", e.kind().name().replace("ENTITY_TEMPLATE_REFERENCE_TYPE_", "")); + row.put("entity_template_id", null); + row.put("entity_canonical_tenant_id", e.tenantId().toString()); + row.put("entity_canonical_version_id", e.versionId().toString()); + row.put("entity_canonical_template_id", e.templateId().toString()); + row.put("spawn_count", p.getSpawnCount() == 0 ? 1 : p.getSpawnCount()); + row.put("respawn_delay_seconds", p.getRespawnDelaySeconds()); + } + default -> throw new ConflictException("Unsupported exact World family"); + } + return row; + } + + private static Long lookup(Map keys, String family, String id) { + return Objects.requireNonNull( + keys.get(family + ":" + UUID.fromString(id)), "typed parent mapping"); + } + + static String family(Node node) { + return node.mutation().getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + } + + private void requireField(JsonNode node, String name, Object expected) { + if (!node.hasNonNull(name) || !node.path(name).asText().equals(expected.toString())) { + throw new ConflictException("World immutable topology provenance differs at " + name); + } + } + + static boolean sameContent(JsonNode actual, JsonNode expected) { + if (actual.size() != expected.size()) { + return false; + } + for (var entry : expected.properties()) { + JsonNode value = actual.get(entry.getKey()); + JsonNode required = entry.getValue(); + if (value == null + || (value.isNumber() && required.isNumber() + ? value.decimalValue().compareTo(required.decimalValue()) != 0 + : !value.equals(required))) { + return false; + } + } + return true; + } + + private byte[] encodeResult(WorldDraftTopologyCommitPlan plan, byte[] graph) { + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", "2"); + result.put("status", WorldDraftTopologyCommitEvidence.STATUS); + result.put("requestId", plan.binding().requestId().toString()); + result.put("commitId", plan.binding().commitId().toString()); + result.put("bindingDigest", plan.binding().digest()); + result.put("ownerBinding", plan.ownerBinding()); + result.put("graphSha256", sha256(graph)); + result.put( + "affectedEpochsAfter", + plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> { + Map after = new LinkedHashMap<>(); + after.put("aggregateType", u.aggregateType()); + after.put("aggregateId", u.aggregateId()); + after.put("scopeType", u.scopeType()); + after.put("scopeId", u.scopeId()); + after.put("epoch", "1"); + return after; + }) + .toList()); + return mapper.writeValueAsBytes(result); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Objects.equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(), + java.sql.Connection.TRANSACTION_READ_COMMITTED)) { + throw new ConflictException( + "World complete storage requires writable READ COMMITTED transaction"); + } + } + + private String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitService.java new file mode 100644 index 0000000000..81ea939468 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitService.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicitly unwired complete owner-local storage component, with a fail-closed permission seam. + */ +public final class WorldDraftTopologyCommitService { + /** + * Must fail unless the exact complete operation has durable Account ordering that remains held + * continuously through its terminal reconciliation. A preflight permission check is not reusable + * authorization for a later commit. No authenticated implementation is supplied in this slice; + * fixture implementations establish component storage prerequisites only. + */ + @FunctionalInterface + public interface PermissionVerifier { + void verify(WorldDraftTopologyCommitPlan plan); + } + + private final WorldDraftTopologyCommitRepository repository; + private final PermissionVerifier verifier; + private final TransactionTemplate transaction; + + /** Builds an unwired, denied component by default. */ + public WorldDraftTopologyCommitService( + WorldDraftTopologyCommitRepository repository, PlatformTransactionManager manager) { + this( + repository, + manager, + plan -> { + throw new ConflictException( + "Authenticated Account Draft commit permission is unavailable"); + }); + } + + public WorldDraftTopologyCommitService( + WorldDraftTopologyCommitRepository repository, + PlatformTransactionManager manager, + PermissionVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + transaction = new TransactionTemplate(Objects.requireNonNull(manager, "manager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + /** Verifies before opening the dedicated transaction; no external call runs while it is open. */ + public WorldDraftTopologyCommitEvidence store(WorldDraftTopologyCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage cannot start inside an existing transaction"); + } + verifier.verify(plan); + return Objects.requireNonNull(transaction.execute(status -> repository.store(plan))); + } + + /** + * Reads original committed storage evidence without invoking permission verification or a writer + * transaction. The result remains permission-unverified; absence is unknown rather than an abort + * or definitive no-commit outcome. + */ + public Optional readCommitted( + WorldDraftTopologyCommitPlan plan) { + Objects.requireNonNull(plan, "plan"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException( + "World complete storage readback requires no active caller transaction"); + } + return repository.readCommitted(plan); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java new file mode 100644 index 0000000000..3f7ecf4446 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; + +/** + * Immutable PURE_UNVERIFIED logical input, never a stored or released World graph. + * + *

No numeric allocation, source authentication, Account authorization, APPLIED result, + * synchronized visibility, public handler, lifecycle or runtime readiness follows from this value. + * Its protobuf values preserve every supplied payload field without normalizing defaults. + * Preserving free-text and localized JSON fields does not validate their semantics. + */ +public final class WorldDraftTopologyInputGraph { + public static final String STATUS = "PURE_UNVERIFIED"; + + /** One explicit member of the complete six-family declaration; zero is meaningful. */ + public record FamilyCount(WorldDesignAggregateType family, int count) { + public FamilyCount { + Objects.requireNonNull(family, "family"); + if (count < 0) { + throw new IllegalArgumentException("Fresh World family count must be nonnegative"); + } + } + } + + /** Typed start selector and exhaustive family counts from the original Account-bound input. */ + public record FreshGraphDeclaration( + UUID tenantId, + UUID versionId, + RoomTemplateRef startLocation, + List familyCounts) { + public FreshGraphDeclaration { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(versionId, "versionId"); + Objects.requireNonNull(startLocation, "startLocation"); + familyCounts = List.copyOf(familyCounts); + } + } + + /** A typed canonical Entity reference; existence and owner authority remain unverified. */ + public record EntityTemplateReference( + EntityTemplateReferenceType kind, UUID tenantId, UUID versionId, UUID templateId) { + public EntityTemplateReference { + Objects.requireNonNull(kind, "kind"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(versionId, "versionId"); + Objects.requireNonNull(templateId, "templateId"); + } + } + + /** One complete immutable logical mutation in its original enclosing revision position. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf messages are immutable value messages.") + public record Node( + String revisionOrder, + UUID revisionId, + UUID templateId, + UUID scopeId, + WorldDesignMutationRevision mutation, + EntityTemplateReference entityReference) { + public Node { + Objects.requireNonNull(revisionOrder, "revisionOrder"); + Objects.requireNonNull(revisionId, "revisionId"); + Objects.requireNonNull(templateId, "templateId"); + Objects.requireNonNull(scopeId, "scopeId"); + Objects.requireNonNull(mutation, "mutation"); + } + } + + private final UUID tenantId; + private final UUID versionId; + private final List nodes; + private final FreshGraphDeclaration freshGraphDeclaration; + + WorldDraftTopologyInputGraph( + UUID tenantId, + UUID versionId, + List nodes, + FreshGraphDeclaration freshGraphDeclaration) { + this.tenantId = Objects.requireNonNull(tenantId, "tenantId"); + this.versionId = Objects.requireNonNull(versionId, "versionId"); + this.nodes = List.copyOf(nodes); + this.freshGraphDeclaration = freshGraphDeclaration; + } + + public UUID tenantId() { + return tenantId; + } + + public UUID versionId() { + return versionId; + } + + /** All six families in original canonical revision order, including interleaved families. */ + public List nodes() { + return nodes; + } + + /** An immutable family view retaining original order; an empty family is not readiness proof. */ + public List family(WorldDesignAggregateType kind) { + Objects.requireNonNull(kind, "kind"); + return nodes.stream().filter(node -> node.mutation().getAggregateType() == kind).toList(); + } + + /** Absent only for immutable pre-declaration owner history; new APPLIED writes require it. */ + public java.util.Optional freshGraphDeclaration() { + return java.util.Optional.ofNullable(freshGraphDeclaration); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java new file mode 100644 index 0000000000..343ea45c12 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java @@ -0,0 +1,110 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Closed, immutable World handoff to the exact Game Design publication terminal result. */ +public final class WorldPublicationTerminal { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private WorldPublicationTerminal() {} + + /** + * Reconstructs the only accepted terminal carrier; decoding does not authenticate Game Design. + */ + public static Request request(byte[] terminalBytes) { + return new Request(GameDesignPublicationTerminalEvidence.fromStored(terminalBytes)); + } + + public record Request(GameDesignPublicationTerminalEvidence evidence) { + public Request { + Objects.requireNonNull(evidence, "evidence"); + evidence = GameDesignPublicationTerminalEvidence.fromStored(evidence.canonicalBytes()); + } + + public WorldPublishedStartLocationEvidence worldEvidence() { + return evidence.worldEvidence(); + } + + public byte[] terminalBytes() { + return evidence.canonicalBytes(); + } + + public byte[] operationBytes() { + return evidence.operationBytes(); + } + + public byte[] worldEvidenceBytes() { + return evidence.worldEvidence().canonicalBytes(); + } + + public String worldRequestJson() { + try { + JsonNode root = JSON.readTree(worldEvidenceBytes()); + JsonNode request = root == null ? null : root.get("request"); + if (request == null || !request.isObject()) { + throw new IllegalArgumentException("Terminal evidence has no exact World request"); + } + return request.toString(); + } catch (JacksonException invalid) { + throw new IllegalArgumentException( + "Terminal evidence has an invalid World request", invalid); + } + } + + public byte[] originalAccountBindingBytes() { + return worldEvidence().originalAccountBindingBytes(); + } + + public byte[] selectorReceiptBytes() { + return worldEvidence().selectorReceiptBytes(); + } + + public byte[] appliedResultBytes() { + return worldEvidence().appliedResultBytes(); + } + + public byte[] releaseContentBytes() { + return evidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? evidence.releaseContent().canonicalBytes() + : new byte[0]; + } + + public String ownerPhase() { + return evidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + } + + public String releaseBundleRef() { + return evidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? evidence.publishedReleaseBundleRef() + : null; + } + + public String releaseBundleDigest() { + return evidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? evidence.publishedReleaseBundleDigest() + : null; + } + + public Long publicationVersionStateEpoch() { + return evidence.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? evidence.publicationVersionStateEpoch() + : null; + } + + public static Request fromStored(byte[] bytes) { + return request(bytes); + } + + public boolean exactBytes(byte[] bytes) { + return Arrays.equals(terminalBytes(), bytes); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java new file mode 100644 index 0000000000..86a1194249 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java @@ -0,0 +1,443 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Owner-local immutable terminal receipt and exact FROZEN-to-terminal phase transition. */ +public final class WorldPublicationTerminalRepository { + private static final String TERMINAL_WITH_OWNER_READ = + "SELECT t.*, o.owner_freeze_phase AS joined_owner_phase, " + + "o.current_publication_fence AS joined_owner_current_fence, " + + "a.owner_binding_schema_version AS joined_owner_binding_schema_version, " + + "a.target_namespace AS joined_attempt_target_namespace, " + + "a.canonical_tenant_id AS joined_attempt_canonical_tenant_id, " + + "a.canonical_version_id AS joined_attempt_canonical_version_id, " + + "a.local_tenant_key AS joined_attempt_local_tenant_key, " + + "a.version_id AS joined_attempt_local_version_id, " + + "a.intake_request_id AS joined_attempt_intake_request_id, " + + "a.publication_request_id AS joined_attempt_publication_request_id, " + + "a.request_digest AS joined_attempt_request_digest, " + + "a.version_state_epoch AS joined_attempt_version_state_epoch, " + + "a.publish_workflow_id AS joined_attempt_publish_workflow_id, " + + "a.applied_commit_id AS joined_attempt_applied_commit_id, " + + "a.content_digest AS joined_attempt_content_digest, " + + "a.digest_schema_version AS joined_attempt_digest_schema_version " + + "FROM world_design_publication_terminal t " + + "LEFT JOIN world_design_publication_fence_attempt a " + + "ON a.publication_fence=t.publication_fence " + + "LEFT JOIN world_design_publication_fence_owner o " + + "ON o.target_namespace=a.target_namespace " + + "AND o.canonical_tenant_id=a.canonical_tenant_id " + + "AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id " + + "WHERE t.publication_fence=?"; + private static final String ORIGINAL_OWNER_READ = + "SELECT a.*, o.owner_freeze_phase, o.current_publication_fence " + + "FROM world_design_publication_fence_attempt a " + + "JOIN world_design_publication_fence_owner o " + + "ON o.target_namespace=a.target_namespace " + + "AND o.canonical_tenant_id=a.canonical_tenant_id " + + "AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id " + + "WHERE a.publication_fence=? AND a.target_namespace=? " + + "AND a.canonical_tenant_id=? AND a.canonical_version_id=? " + + "AND o.current_publication_fence=a.publication_fence"; + + private final DSLContext dsl; + private final TransactionTemplate independentReadTransaction; + private final TransactionTemplate ownerTransaction; + + public WorldPublicationTerminalRepository( + DSLContext dsl, PlatformTransactionManager transactionManager) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + PlatformTransactionManager manager = Objects.requireNonNull(transactionManager); + independentReadTransaction = new TransactionTemplate(manager); + independentReadTransaction.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + independentReadTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + independentReadTransaction.setReadOnly(true); + ownerTransaction = new TransactionTemplate(manager); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * Persists one exact terminal result under the original V25 owner lock. The supplied authority + * was acquired before this call and remains held until the real owner transaction commits. + */ + public GameDesignPublicationTerminalEvidence complete( + WorldPublicationTerminal.Request request, + WorldPublicationTerminalService.HeldTerminalAuthority authority) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(authority, "authority"); + requireNoAmbientTransaction("World publication terminal"); + GameDesignPublicationTerminalEvidence committed = + Objects.requireNonNull( + ownerTransaction.execute( + status -> { + requireWritableReadCommittedTransaction(); + authority.requireHeld(); + Record owner = lockOriginalOwner(request); + Optional prior = + readInOwnerTransaction(request); + if (prior.isPresent()) return prior.orElseThrow(); + if (!"FROZEN".equals(required(owner, "owner_freeze_phase", String.class))) { + throw new PublicationTerminalConflictException( + "World publication fence is no longer open for its first terminal result"); + } + + insertTerminal(request); + String phase = request.ownerPhase(); + int updated = + dsl.execute( + "UPDATE world_design_publication_fence_owner SET owner_freeze_phase=? " + + "WHERE target_namespace=? AND canonical_tenant_id=? " + + "AND local_tenant_key=? AND version_id=? " + + "AND owner_freeze_phase='FROZEN' AND current_publication_fence=?", + phase, + request.worldEvidence().request().targetNamespace(), + request.worldEvidence().request().canonicalTenantId(), + required(owner, "local_tenant_key", Long.class), + required(owner, "version_id", Long.class), + request.worldEvidence().request().publicationFence()); + if (updated != 1) { + throw new PublicationTerminalConflictException( + "World publication terminal lost the exact locked FROZEN owner row"); + } + authority.requireHeld(); + GameDesignPublicationTerminalEvidence readback = + readInOwnerTransaction(request) + .orElseThrow( + () -> + new PublicationTerminalConflictException( + "World publication terminal has no exact immutable readback")); + if (!Arrays.equals(readback.canonicalBytes(), request.terminalBytes())) { + throw new PublicationTerminalConflictException( + "World publication terminal differs from exact inserted evidence"); + } + return readback; + }), + "World publication terminal transaction did not commit"); + + // Confirm committed immutable readback after TransactionTemplate returns from commit. + GameDesignPublicationTerminalEvidence readback = + readCommitted(request) + .orElseThrow( + () -> + new PublicationTerminalConflictException( + "Committed World publication terminal has no independent readback")); + if (!Arrays.equals(committed.canonicalBytes(), readback.canonicalBytes())) { + throw new PublicationTerminalConflictException( + "Committed World publication terminal differs from its owner transaction readback"); + } + return readback; + } + + /** Independent immutable read. Unknown is not interpreted as publication or abort. */ + public Optional readCommitted( + WorldPublicationTerminal.Request request) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction("World publication terminal readback"); + Record row = + independentReadTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + Record terminal = readTerminalWithOwner(request, false); + if (terminal == null) { + requirePendingOwner(request); + } + return terminal; + }); + if (row == null) return Optional.empty(); + return Optional.of(exactReadback(request, row)); + } + + private Record lockOriginalOwner(WorldPublicationTerminal.Request request) { + var world = request.worldEvidence().request(); + Record row = + dsl.fetchOne( + ORIGINAL_OWNER_READ + " FOR UPDATE OF o", + world.publicationFence(), + world.targetNamespace(), + world.canonicalTenantId(), + world.canonicalVersionId()); + requireOriginalOwnerBinding(world, row); + return row; + } + + private void requirePendingOwner(WorldPublicationTerminal.Request request) { + var world = request.worldEvidence().request(); + Record owner = + dsl.fetchOne( + ORIGINAL_OWNER_READ, + world.publicationFence(), + world.targetNamespace(), + world.canonicalTenantId(), + world.canonicalVersionId()); + if (owner == null) { + throw new PublicationTerminalConflictException( + "World terminal request has no exact retained V25 attempt and current owner association"); + } + requireOriginalOwnerBinding(world, owner); + if (!"FROZEN".equals(required(owner, "owner_freeze_phase", String.class))) { + throw new PublicationTerminalConflictException( + "Missing World publication terminal conflicts with the retained owner phase"); + } + } + + private static void requireOriginalOwnerBinding( + WorldPublishedStartLocationEvidence.Request world, Record row) { + if (row == null) { + throw new PublicationTerminalConflictException( + "World terminal request has no exact retained V25 attempt and current owner association"); + } + if (!Short.valueOf((short) 1).equals(required(row, "owner_binding_schema_version", Short.class)) + || !world.intakeRequestId().equals(required(row, "intake_request_id", java.util.UUID.class)) + || !world + .publicationFence() + .equals(required(row, "publication_fence", java.util.UUID.class)) + || !world + .publicationRequestId() + .equals(required(row, "publication_request_id", String.class)) + || !world.requestDigest().equals(required(row, "request_digest", String.class)) + || world.versionStateEpoch() != required(row, "version_state_epoch", Long.class) + || !world.publishWorkflowId().equals(required(row, "publish_workflow_id", String.class)) + || !world.appliedCommitId().equals(required(row, "applied_commit_id", String.class)) + || !world.contentDigest().equals(required(row, "content_digest", String.class)) + || world.digestSchemaVersion() != required(row, "digest_schema_version", Integer.class)) { + throw new PublicationTerminalConflictException( + "World terminal evidence differs from its exact immutable V25 publication checkpoint"); + } + } + + private void insertTerminal(WorldPublicationTerminal.Request request) { + var world = request.worldEvidence().request(); + GameDesignPublicationTerminalEvidence evidence = request.evidence(); + dsl.execute( + "INSERT INTO world_design_publication_terminal (publication_fence,target_namespace," + + "canonical_tenant_id,canonical_version_id,publication_request_id,request_digest," + + "publish_workflow_id,freeze_version_state_epoch,applied_commit_id,content_digest," + + "digest_schema_version,outcome,publication_version_state_epoch," + + "published_release_bundle_ref,published_release_bundle_digest,operation_bytes," + + "terminal_evidence_bytes,terminal_evidence_digest,world_evidence_bytes,world_request_json," + + "selector_receipt_bytes,original_account_binding_bytes,applied_result_bytes,release_content_bytes) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + world.publicationFence(), + world.targetNamespace(), + world.canonicalTenantId(), + world.canonicalVersionId(), + world.publicationRequestId(), + world.requestDigest(), + world.publishWorkflowId(), + world.versionStateEpoch(), + world.appliedCommitId(), + world.contentDigest(), + world.digestSchemaVersion(), + evidence.outcome().name(), + request.publicationVersionStateEpoch(), + request.releaseBundleRef(), + request.releaseBundleDigest(), + request.operationBytes(), + request.terminalBytes(), + digest(request.terminalBytes()), + request.worldEvidenceBytes(), + request.worldRequestJson(), + request.selectorReceiptBytes(), + request.originalAccountBindingBytes(), + request.appliedResultBytes(), + request.releaseContentBytes()); + } + + private Optional readInOwnerTransaction( + WorldPublicationTerminal.Request request) { + Record row = readTerminalWithOwner(request, true); + if (row == null) return Optional.empty(); + return Optional.of(exactReadback(request, row)); + } + + private Record readTerminalWithOwner(WorldPublicationTerminal.Request request, boolean lock) { + return dsl.fetchOne( + TERMINAL_WITH_OWNER_READ + (lock ? " FOR UPDATE OF t" : ""), + request.worldEvidence().request().publicationFence()); + } + + private GameDesignPublicationTerminalEvidence exactReadback( + WorldPublicationTerminal.Request request, Record row) { + byte[] stored = required(row, "terminal_evidence_bytes", byte[].class); + if (!request.exactBytes(stored)) { + throw new PublicationTerminalConflictException( + "World publication fence was reused with changed complete terminal evidence"); + } + var world = request.worldEvidence().request(); + if (!request.ownerPhase().equals(required(row, "joined_owner_phase", String.class)) + || !world + .publicationFence() + .equals(required(row, "joined_owner_current_fence", java.util.UUID.class)) + || !Short.valueOf((short) 1) + .equals(required(row, "joined_owner_binding_schema_version", Short.class)) + || !world + .targetNamespace() + .equals(required(row, "joined_attempt_target_namespace", String.class)) + || !world + .canonicalTenantId() + .equals(required(row, "joined_attempt_canonical_tenant_id", java.util.UUID.class)) + || !world + .canonicalVersionId() + .equals(required(row, "joined_attempt_canonical_version_id", java.util.UUID.class)) + || required(row, "joined_attempt_local_tenant_key", Long.class) <= 0L + || required(row, "joined_attempt_local_version_id", Long.class) <= 0L + || !world + .intakeRequestId() + .equals(required(row, "joined_attempt_intake_request_id", java.util.UUID.class)) + || !world + .publicationRequestId() + .equals(required(row, "joined_attempt_publication_request_id", String.class)) + || !world + .requestDigest() + .equals(required(row, "joined_attempt_request_digest", String.class)) + || world.versionStateEpoch() + != required(row, "joined_attempt_version_state_epoch", Long.class) + || !world + .publishWorkflowId() + .equals(required(row, "joined_attempt_publish_workflow_id", String.class)) + || !world + .appliedCommitId() + .equals(required(row, "joined_attempt_applied_commit_id", String.class)) + || !world + .contentDigest() + .equals(required(row, "joined_attempt_content_digest", String.class)) + || world.digestSchemaVersion() + != required(row, "joined_attempt_digest_schema_version", Integer.class) + || !digest(stored).equals(required(row, "terminal_evidence_digest", String.class)) + || !world + .publicationFence() + .equals(required(row, "publication_fence", java.util.UUID.class)) + || !world.targetNamespace().equals(required(row, "target_namespace", String.class)) + || !world + .canonicalTenantId() + .equals(required(row, "canonical_tenant_id", java.util.UUID.class)) + || !world + .canonicalVersionId() + .equals(required(row, "canonical_version_id", java.util.UUID.class)) + || !world + .publicationRequestId() + .equals(required(row, "publication_request_id", String.class)) + || !world.requestDigest().equals(required(row, "request_digest", String.class)) + || !world.publishWorkflowId().equals(required(row, "publish_workflow_id", String.class)) + || world.versionStateEpoch() != required(row, "freeze_version_state_epoch", Long.class) + || !world.appliedCommitId().equals(required(row, "applied_commit_id", String.class)) + || !world.contentDigest().equals(required(row, "content_digest", String.class)) + || world.digestSchemaVersion() != required(row, "digest_schema_version", Integer.class) + || !request.evidence().outcome().name().equals(required(row, "outcome", String.class)) + || !Objects.equals( + request.publicationVersionStateEpoch(), + row.get("publication_version_state_epoch", Long.class)) + || !Objects.equals( + request.releaseBundleRef(), row.get("published_release_bundle_ref", String.class)) + || !Objects.equals( + request.releaseBundleDigest(), row.get("published_release_bundle_digest", String.class)) + || !Arrays.equals(request.operationBytes(), required(row, "operation_bytes", byte[].class)) + || !Arrays.equals( + request.worldEvidenceBytes(), required(row, "world_evidence_bytes", byte[].class)) + || !request.worldRequestJson().equals(required(row, "world_request_json", String.class)) + || !Arrays.equals( + request.selectorReceiptBytes(), required(row, "selector_receipt_bytes", byte[].class)) + || !Arrays.equals( + request.originalAccountBindingBytes(), + required(row, "original_account_binding_bytes", byte[].class)) + || !Arrays.equals( + request.appliedResultBytes(), required(row, "applied_result_bytes", byte[].class)) + || !Arrays.equals( + request.releaseContentBytes(), required(row, "release_content_bytes", byte[].class))) { + throw new InvalidPublicationTerminalEvidenceException( + "Retained World publication terminal columns differ from their canonical producer evidence"); + } + return GameDesignPublicationTerminalEvidence.fromStored(stored); + } + + private static String digest(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static T required(Record record, String field, Class type) { + T value = record.get(field, type); + if (value == null) throw new InvalidPublicationTerminalEvidenceException("Missing " + field); + return value; + } + + private static void requireNoAmbientTransaction(String operation) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException(operation + " requires no caller transaction"); + } + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World publication terminal requires a writable owner transaction"); + } + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (isolation != null && isolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World publication terminal requires READ COMMITTED"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + if (settings == null + || !"read committed".equalsIgnoreCase(required(settings, "isolation", String.class)) + || !"off".equalsIgnoreCase(required(settings, "read_only", String.class))) { + throw new IllegalStateException( + "World publication terminal requires writable READ COMMITTED"); + } + } + + private void requireReadOnlyRepeatableReadTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "World publication terminal read requires a read-only REPEATABLE READ transaction"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + if (settings == null + || !"repeatable read".equalsIgnoreCase(required(settings, "isolation", String.class)) + || !"on".equalsIgnoreCase(required(settings, "read_only", String.class))) { + throw new IllegalStateException( + "World publication terminal read requires a read-only REPEATABLE READ transaction"); + } + } + + public static class PublicationTerminalConflictException extends IllegalStateException { + public PublicationTerminalConflictException(String message) { + super(message); + } + } + + public static final class InvalidPublicationTerminalEvidenceException + extends PublicationTerminalConflictException { + public InvalidPublicationTerminalEvidenceException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java new file mode 100644 index 0000000000..faa87bc113 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone, default-denied receiver for one authenticated Game Design terminal publication. */ +public final class WorldPublicationTerminalService { + private final WorldPublicationTerminalRepository repository; + private final TerminalAuthorityVerifier verifier; + + /** + * Production-safe default until an authenticated same-namespace Game Design verifier is wired. + */ + public WorldPublicationTerminalService(WorldPublicationTerminalRepository repository) { + this(repository, WorldPublicationTerminalService::denyByDefault); + } + + /** Explicit verifier seam for a future authenticated producer and isolated component fixtures. */ + public WorldPublicationTerminalService( + WorldPublicationTerminalRepository repository, TerminalAuthorityVerifier verifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + } + + /** + * Authenticates and reconciles the producer before opening the World owner transaction. The + * continuously held fence is checked locally through commit; no remote call occurs under locks. + */ + public GameDesignPublicationTerminalEvidence complete( + byte[] operationBytes, byte[] terminalBytes) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "World publication terminal must authenticate outside an ambient transaction"); + } + VerifiedTerminal verified = + Objects.requireNonNull( + verifier.authenticateAndVerifyAndHold(operationBytes.clone(), terminalBytes.clone()), + "World publication terminal verifier returned no authenticated evidence"); + WorldPublicationTerminal.Request request = Objects.requireNonNull(verified.request()); + if (!request.exactBytes(terminalBytes) + || !java.util.Arrays.equals(request.operationBytes(), operationBytes)) { + verified.authority().close(); + throw new IllegalArgumentException( + "Authenticated Game Design terminal evidence differs from the submitted immutable bytes"); + } + HeldTerminalAuthority held = Objects.requireNonNull(verified.authority()); + try (held) { + held.requireHeld(); + GameDesignPublicationTerminalEvidence result = repository.complete(request, held); + held.requireHeld(); + return result; + } + } + + private static VerifiedTerminal denyByDefault(byte[] operationBytes, byte[] terminalBytes) { + throw new TerminalDeniedException( + "World publication terminal has no authenticated exact Game Design producer verifier"); + } + + @FunctionalInterface + public interface TerminalAuthorityVerifier { + /** Must authenticate the configured Game Design peer before decoding the supplied bytes. */ + VerifiedTerminal authenticateAndVerifyAndHold(byte[] operationBytes, byte[] terminalBytes); + } + + public record VerifiedTerminal( + WorldPublicationTerminal.Request request, HeldTerminalAuthority authority) { + public VerifiedTerminal { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(authority, "authority"); + } + } + + /** + * Local held-authentication/currentness assertion; must not perform RPC while World locks exist. + */ + public interface HeldTerminalAuthority extends AutoCloseable { + void requireHeld(); + + @Override + void close(); + } + + public static final class TerminalDeniedException extends IllegalStateException { + public TerminalDeniedException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java new file mode 100644 index 0000000000..f6d37dbd49 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcService.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedSpawnRequirementsReadServiceGrpc; + +/** Standalone transport adapter; intentionally not registered in production composition. */ +final class WorldPublishedSpawnRequirementsReadGrpcService + extends WorldPublishedSpawnRequirementsReadServiceGrpc + .WorldPublishedSpawnRequirementsReadServiceImplBase { + private static final Map DESCRIPTIONS = + Map.of( + Status.Code.PERMISSION_DENIED, + "Published World source read is not authorized", + Status.Code.INVALID_ARGUMENT, + "Published World source selector is invalid", + Status.Code.NOT_FOUND, + "No exact published World source matches the selector", + Status.Code.FAILED_PRECONDITION, + "Published World source evidence is incomplete or inconsistent", + Status.Code.UNAVAILABLE, + "Published World source is temporarily unavailable", + Status.Code.INTERNAL, + "Published World source read failed"); + + private final WorldPublishedSpawnRequirementsReadOwner owner; + + WorldPublishedSpawnRequirementsReadGrpcService(WorldPublishedSpawnRequirementsReadOwner owner) { + this.owner = Objects.requireNonNull(owner, "owner"); + } + + @Override + public void readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest request, + StreamObserver responseObserver) { + final ReadWorldPublishedSpawnRequirementsResponse response; + try { + var evidence = owner.read(request); + response = WorldPublishedSpawnRequirementsGrpcCodec.toResponse(evidence.request(), evidence); + } catch (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException rejected) { + responseObserver.onError(status(rejected.code())); + return; + } catch (RuntimeException failure) { + responseObserver.onError(status(Status.Code.INTERNAL)); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private static io.grpc.StatusRuntimeException status(Status.Code code) { + return Status.fromCode(code) + .withDescription(DESCRIPTIONS.getOrDefault(code, "Published World source read failed")) + .asRuntimeException(); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java new file mode 100644 index 0000000000..545ef3f6ab --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java @@ -0,0 +1,334 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.FamilyCount; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.GenerationRequirement; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.Request; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.SpawnRequirement; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.GenerationRuleIntent; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.SpawnBindingIntent; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Standalone authenticated read owner for immutable published World spawn requirements. */ +final class WorldPublishedSpawnRequirementsReadOwner { + private final String workloadNamespace; + private final AuthoredWorldLaunchDescriptorClient gameDesignClient; + private final WorldPublishedStartLocationRepository publishedSources; + private final PlatformTransactionManager transactionManager; + + WorldPublishedSpawnRequirementsReadOwner( + String workloadNamespace, + AuthoredWorldLaunchDescriptorClient gameDesignClient, + WorldPublishedStartLocationRepository publishedSources, + PlatformTransactionManager transactionManager) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); + this.publishedSources = Objects.requireNonNull(publishedSources, "publishedSources"); + this.transactionManager = Objects.requireNonNull(transactionManager, "transactionManager"); + } + + WorldPublishedSpawnRequirementsEvidence read( + ReadWorldPublishedSpawnRequirementsRequest wireRequest) { + requireAuthenticatedEntityPeer(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Published spawn-requirement read requires no ambient World transaction"); + } + + final Request request; + try { + request = WorldPublishedSpawnRequirementsGrpcCodec.fromRequest(wireRequest); + } catch (IllegalArgumentException invalid) { + throw rejected(Status.Code.INVALID_ARGUMENT, "Published spawn selector is invalid"); + } + if (!workloadNamespace.equals(request.targetNamespace())) { + throw rejected(Status.Code.PERMISSION_DENIED, "Published spawn namespace is not authorized"); + } + + CompleteLaunchBindingEvidence launchBinding = readLaunchBinding(request); + AuthoredWorldReleaseAttestationEvidence release = launchBinding.releaseAttestation(); + if (!workloadNamespace.equals(launchBinding.descriptor().targetNamespace()) + || !workloadNamespace.equals(release.targetNamespace()) + || !request.expectedReleaseAttestationDigest().equals(release.evidenceDigest()) + || release.schemaVersion() + != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || release.worldStartLocationEvidence() == null) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Authenticated Game Design release differs from the exact published selector"); + } + + CaptureRequest captureRequest = captureRequest(release.worldStartLocationEvidence()); + Optional stored = readInOwnedSnapshot(captureRequest); + if (stored.isEmpty()) { + throw rejected(Status.Code.NOT_FOUND, "No exact frozen World source matches the release"); + } + + WorldPublishedStartLocationSource source = stored.orElseThrow(); + WorldCanonicalInstanceTopologyPlan topology; + try { + topology = WorldCanonicalInstanceTopologyPlan.create(source.frozenTopology()); + WorldCanonicalInstancePreparation.requireExactReleaseGraph(release, topology); + WorldPublishedStartLocationEvidence actualSelector = + actualSelectorEvidence(source, release.worldStartLocationEvidence().request()); + if (!actualSelector.equals(release.worldStartLocationEvidence())) { + throw new IllegalArgumentException( + "Frozen selector, Account binding, or APPLIED result differs from Game Design release"); + } + var projection = projectRequirements(frozenGraph(source.frozenTopology()), topology); + return new WorldPublishedSpawnRequirementsEvidence( + request, + launchBinding, + source.frozenTopology().captureId(), + WorldDraftGraphAppliedResult.digest(source.frozenTopology().graphBytes()), + projection.familyCounts(), + projection.spawnRequirements(), + projection.generationRequirements()); + } catch (RuntimeException invalid) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Frozen World source differs from authenticated release evidence"); + } + } + + private CompleteLaunchBindingEvidence readLaunchBinding(Request request) { + try { + return gameDesignClient.getComplete(request.launchBindingRequest()); + } catch (RuntimeException unavailable) { + throw rejected( + Status.Code.UNAVAILABLE, "Authenticated Game Design release read did not complete"); + } + } + + private Optional readInOwnedSnapshot( + CaptureRequest captureRequest) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + transaction.setReadOnly(true); + try { + return Objects.requireNonNull( + transaction.execute(status -> publishedSources.readInOwnedSnapshot(captureRequest)), + "World published source transaction result"); + } catch (WorldDesignPublicationFenceRepository.ConflictException conflict) { + throw rejected( + Status.Code.FAILED_PRECONDITION, + "Frozen World source conflicts with the exact publication selection"); + } catch (TransientDataAccessException unavailable) { + throw rejected(Status.Code.UNAVAILABLE, "World published source is temporarily unavailable"); + } catch (DataAccessException unavailable) { + throw rejected(Status.Code.UNAVAILABLE, "World published source is temporarily unavailable"); + } catch (RuntimeException failure) { + throw rejected(Status.Code.INTERNAL, "World published source read failed"); + } + } + + static RequirementProjection projectRequirements( + WorldDraftTopologyInputGraph authoredGraph, WorldCanonicalInstanceTopologyPlan topology) { + var declaration = + authoredGraph + .freshGraphDeclaration() + .orElseThrow( + () -> + new IllegalArgumentException( + "Published World source lacks its original complete family declaration")); + + Map spawnsByRevision = new HashMap<>(); + for (SpawnBindingIntent spawn : topology.spawnBindings()) { + UUID revisionId = UUID.fromString(spawn.source().authoredRevision().getLogicalRevisionId()); + if (spawnsByRevision.putIfAbsent(revisionId, spawn) != null) { + throw new IllegalArgumentException("Frozen World source repeats a spawn revision"); + } + } + Map generationsByRevision = new HashMap<>(); + for (GenerationRuleIntent generation : topology.generationRules()) { + UUID revisionId = + UUID.fromString(generation.source().authoredRevision().getLogicalRevisionId()); + if (generationsByRevision.putIfAbsent(revisionId, generation) != null) { + throw new IllegalArgumentException("Frozen World source repeats a generation revision"); + } + } + + List spawns = new ArrayList<>(); + List generations = new ArrayList<>(); + for (var node : authoredGraph.nodes()) { + if (node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) { + SpawnBindingIntent intent = spawnsByRevision.remove(node.revisionId()); + if (intent == null || !node.templateId().equals(intent.identity().templateId())) { + throw new IllegalArgumentException("Spawn projection differs from its original revision"); + } + var entity = intent.entityReference(); + spawns.add( + new SpawnRequirement( + node.revisionOrder(), + node.revisionId(), + intent.identity().templateId(), + new RoomTemplateRef( + topology.tenantId(), topology.versionId(), intent.room().templateId()), + new EntityTemplateReference( + entity.kind(), entity.tenantId(), entity.versionId(), entity.templateId()), + intent.requiredIntent().getSpawnCount(), + intent.requiredIntent().getRespawnDelaySeconds())); + } else if (node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) { + GenerationRuleIntent intent = generationsByRevision.remove(node.revisionId()); + if (intent == null || !node.templateId().equals(intent.identity().templateId())) { + throw new IllegalArgumentException( + "Generation projection differs from its original revision"); + } + WorldDesignAggregateType scopeFamily = + switch (intent.scope().family()) { + case REGION -> WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION; + case ZONE -> WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE; + default -> + throw new IllegalArgumentException( + "Generation scope is not an authored REGION or ZONE"); + }; + generations.add( + new GenerationRequirement( + node.revisionOrder(), + node.revisionId(), + intent.identity().templateId(), + scopeFamily, + intent.scope().templateId(), + intent.requiredIntent().getName(), + intent.requiredIntent().getValue())); + } + } + if (!spawnsByRevision.isEmpty() || !generationsByRevision.isEmpty()) { + throw new IllegalArgumentException("Frozen source projections omit original intent rows"); + } + + List familyCounts = + declaration.familyCounts().stream() + .map(count -> new FamilyCount(count.family(), count.count())) + .toList(); + return new RequirementProjection(familyCounts, spawns, generations); + } + + private static WorldDraftTopologyInputGraph frozenGraph(WorldCanonicalFrozenTopology frozen) { + return frozen.request().plan().graph(); + } + + private static CaptureRequest captureRequest(WorldPublishedStartLocationEvidence selector) { + var request = selector.request(); + return new CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples().stream() + .map( + tuple -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()); + } + + private static WorldPublishedStartLocationEvidence actualSelectorEvidence( + WorldPublishedStartLocationSource source, + WorldPublishedStartLocationEvidence.Request selectorRequest) { + var receipt = source.selectorReceipt(); + var receiptEvidence = + new net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence( + receipt.targetNamespace(), + receipt.operationId(), + receipt.requestId(), + receipt.commitId(), + receipt.authorizationFenceId(), + receipt.accountBindingDigest(), + receipt.bindingDigest(), + receipt.startLocation(), + receipt.graphDigest(), + receipt.receiptDigest()); + return new WorldPublishedStartLocationEvidence( + selectorRequest, + receiptEvidence.canonicalBytes(), + source.appliedResult().application().operation().accountBindingBytes(), + source.appliedResult().canonicalBytes()); + } + + private void requireAuthenticatedEntityPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("entity-management-service") + || !peer.isInNamespace(workloadNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw rejected( + Status.Code.PERMISSION_DENIED, + "Only the verified same-namespace Entity workload without end-user context is allowed"); + } + } + + private static ReadRejectedException rejected(Status.Code code, String message) { + return new ReadRejectedException(code, message); + } + + static final class ReadRejectedException extends IllegalStateException { + private final Status.Code code; + + ReadRejectedException(Status.Code code, String message) { + super(message); + this.code = code; + } + + Status.Code code() { + return code; + } + } + + record RequirementProjection( + List familyCounts, + List spawnRequirements, + List generationRequirements) { + RequirementProjection { + familyCounts = List.copyOf(familyCounts); + spawnRequirements = List.copyOf(spawnRequirements); + generationRequirements = List.copyOf(generationRequirements); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java new file mode 100644 index 0000000000..c07983669b --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationGrpcCodec; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationReadServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; + +/** Standalone authenticated read-only adapter; intentionally not registered as a runtime RPC. */ +public final class WorldPublishedStartLocationReadGrpcService + extends WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceImplBase { + private final WorldPublishedStartLocationRepository repository; + private final String trustedNamespace; + + public WorldPublishedStartLocationReadGrpcService( + WorldPublishedStartLocationRepository repository, String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readWorldPublishedStartLocation( + ReadWorldPublishedStartLocationRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeer(responseObserver)) return; + + WorldPublishedStartLocationEvidence.Request readRequest; + try { + readRequest = WorldPublishedStartLocationGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World published selector request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("World selector namespace must match the authenticated peer") + .asRuntimeException()); + return; + } + + Optional stored; + try { + stored = repository.readCommitted(toCaptureRequest(readRequest)); + } catch (WorldDesignPublicationFenceRepository.ConflictException conflict) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World selector conflicts with exact frozen or APPLIED evidence") + .asRuntimeException()); + return; + } catch (TransientDataAccessException | DataAccessException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World published selector storage is temporarily unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL + .withDescription("World published selector read failed") + .asRuntimeException()); + return; + } + if (stored.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No exact frozen World selector matches the complete selection") + .asRuntimeException()); + return; + } + + ReadWorldPublishedStartLocationResponse response; + try { + WorldPublishedStartLocationSource source = stored.orElseThrow(); + var receipt = source.selectorReceipt(); + byte[] receiptBytes = + new WorldDraftStartLocationEvidence( + receipt.targetNamespace(), + receipt.operationId(), + receipt.requestId(), + receipt.commitId(), + receipt.authorizationFenceId(), + receipt.accountBindingDigest(), + receipt.bindingDigest(), + receipt.startLocation(), + receipt.graphDigest(), + receipt.receiptDigest()) + .canonicalBytes(); + var evidence = + new WorldPublishedStartLocationEvidence( + readRequest, + receiptBytes, + source.appliedResult().application().operation().accountBindingBytes(), + source.appliedResult().canonicalBytes()); + response = WorldPublishedStartLocationGrpcCodec.toResponse(readRequest, evidence); + } catch (IllegalArgumentException | IllegalStateException invalidEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World published selector evidence is inconsistent") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean requireAuthenticatedGameDesignPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-design-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Only the verified same-namespace Game Design workload without end-user context is allowed") + .asRuntimeException()); + return false; + } + + private static CaptureRequest toCaptureRequest( + WorldPublishedStartLocationEvidence.Request request) { + return new CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples().stream() + .map( + tuple -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java new file mode 100644 index 0000000000..02557eb327 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java @@ -0,0 +1,109 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicitly unwired immutable frozen-selection to original APPLIED selector join. */ +public final class WorldPublishedStartLocationRepository { + private final DSLContext dsl; + private final WorldCanonicalFrozenTopologyRepository frozen; + private final WorldDraftGraphApplicationRepository applications; + + public WorldPublishedStartLocationRepository( + DSLContext dsl, + WorldCanonicalFrozenTopologyRepository frozen, + WorldDraftGraphApplicationRepository applications) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.frozen = Objects.requireNonNull(frozen, "frozen"); + this.applications = Objects.requireNonNull(applications, "applications"); + } + + /** Immutable journals need no distributed transaction; absence never authorizes a fallback. */ + public Optional readCommitted(CaptureRequest request) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new ConflictException("World published selector read requires no caller transaction"); + } + return readSource(Objects.requireNonNull(request, "request"), false); + } + + /** Joins both immutable journals within one caller-owned read-only RR snapshot. */ + Optional readInOwnedSnapshot(CaptureRequest request) { + requireOwnedReadOnlyRepeatableReadSnapshot(); + return readSource(Objects.requireNonNull(request, "request"), true); + } + + private Optional readSource( + CaptureRequest request, boolean ownedSnapshot) { + var selected = + ownedSnapshot ? frozen.readInOwnedSnapshot(request) : frozen.readCommitted(request); + if (selected.isEmpty()) return Optional.empty(); + var capture = selected.orElseThrow(); + var plan = capture.request().plan(); + if (!request.equals(capture.request().freeze())) { + throw new ConflictException("World published selector differs from exact frozen selection"); + } + var rows = + dsl.fetch( + "SELECT account_binding_bytes FROM world_draft_graph_application WHERE request_id=? OR commit_id=?", + plan.binding().requestId(), + plan.binding().commitId()); + if (rows.isEmpty()) { + throw new ConflictException("World published selector lacks original APPLIED application"); + } + if (rows.size() != 1) { + throw new ConflictException("World published selector selects conflicting applications"); + } + var account = + DraftAuthorizationFenceBinding.fromStored( + rows.getFirst().get("account_binding_bytes", byte[].class)); + var appliedRead = + ownedSnapshot + ? applications.readInOwnedSnapshot(request.targetNamespace(), account.canonicalBytes()) + : applications.readCommitted(request.targetNamespace(), account.canonicalBytes()); + var applied = + appliedRead.orElseThrow( + () -> new ConflictException("World published selector lacks committed APPLIED")); + var application = applied.application(); + var receipt = + applied + .startLocationReceipt() + .orElseThrow( + () -> + new ConflictException( + "World published selector lacks original selector receipt")); + if (!plan.binding().equals(application.plan().binding()) + || !plan.ownerBinding().equals(application.plan().ownerBinding()) + || !Arrays.equals(account.canonicalBytes(), application.operation().accountBindingBytes()) + || !request.appliedCommitId().equals(application.operation().commitId().toString()) + || !Arrays.equals(capture.graphBytes(), applied.graphBytes()) + || !receipt.graphDigest().equals(WorldDraftGraphAppliedResult.digest(capture.graphBytes())) + || !receipt.equals( + WorldDraftStartLocationReceipt.create(application, capture.graphBytes()))) { + throw new ConflictException( + "World published selector differs from original frozen application"); + } + return Optional.of(new WorldPublishedStartLocationSource(capture, applied, receipt)); + } + + private void requireOwnedReadOnlyRepeatableReadSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new ConflictException( + "World published selector snapshot read requires an active read-only REPEATABLE READ owner transaction"); + } + Integer jdbcIsolation = dsl.connectionResult(Connection::getTransactionIsolation); + if (!Integer.valueOf(Connection.TRANSACTION_REPEATABLE_READ).equals(jdbcIsolation)) { + throw new ConflictException( + "World published selector snapshot read requires actual JDBC REPEATABLE READ isolation"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationSource.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationSource.java new file mode 100644 index 0000000000..0e59008b55 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationSource.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; + +/** + * Original selector and immutable owner evidence for publication transport. This value grants no + * current Account permission, complete release proof or runtime admission authority. + */ +public record WorldPublishedStartLocationSource( + WorldCanonicalFrozenTopology frozenTopology, + WorldDraftGraphAppliedResult appliedResult, + WorldDraftStartLocationReceipt selectorReceipt) { + public WorldPublishedStartLocationSource { + Objects.requireNonNull(frozenTopology, "frozenTopology"); + Objects.requireNonNull(appliedResult, "appliedResult"); + Objects.requireNonNull(selectorReceipt, "selectorReceipt"); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadService.java new file mode 100644 index 0000000000..f20a29f2e2 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadService.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityClient; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence; + +/** + * Standalone, opt-in normal-read selector for the exact immutable World graph behind a GD fence. + */ +public final class WorldSynchronizedDraftTopologyReadService { + private final DraftSynchronizedVisibilityClient visibilityClient; + private final WorldDraftTopologyCommitRepository commitRepository; + + public WorldSynchronizedDraftTopologyReadService( + DraftSynchronizedVisibilityClient visibilityClient, + WorldDraftTopologyCommitRepository commitRepository) { + this.visibilityClient = Objects.requireNonNull(visibilityClient, "visibilityClient"); + this.commitRepository = Objects.requireNonNull(commitRepository, "commitRepository"); + } + + /** + * Reads the durable Game Design fence first, then selects only the retained graph for its full + * binding. This does not authorize writes, publication, preparation, or runtime admission. + */ + public WorldCanonicalAuthoredGraph read(DraftSynchronizedVisibilityEvidence.Request request) { + Objects.requireNonNull(request, "request"); + DraftSynchronizedVisibilityEvidence evidence = visibilityClient.read(request); + if (!request.equals(evidence.request())) { + throw new IllegalStateException("Game Design visibility reply changed the exact read target"); + } + evidence.requireValid(); + if (!evidence.binding().requiredOwners().contains(DraftCommitBinding.Owner.WORLD_MANAGEMENT)) { + throw new IllegalStateException("Synchronized binding has no World owner result"); + } + return commitRepository + .readSynchronized(evidence) + .orElseThrow( + () -> + new IllegalStateException( + "No retained immutable World graph matches the synchronized full binding")); + } +} 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/main/resources/db/migration/V25__world_design_publication_fence.sql b/services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql new file mode 100644 index 0000000000..1542829b59 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql @@ -0,0 +1,220 @@ +ALTER TABLE world_authored_source_intake + ADD CONSTRAINT uq_world_authored_source_intake_publication_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + source_operation_id, + source_evidence_digest, + receipt_digest + ); + +CREATE TABLE world_design_publication_fence_attempt ( + publication_fence UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + version_id BIGINT NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + publication_request_id VARCHAR(256) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + version_state_epoch BIGINT NOT NULL, + publish_workflow_id VARCHAR(537) NOT NULL, + applied_commit_id VARCHAR(256) NOT NULL, + content_digest VARCHAR(64) NOT NULL, + digest_schema_version INTEGER NOT NULL, + CONSTRAINT pk_world_design_publication_fence_attempt + PRIMARY KEY (publication_fence), + CONSTRAINT uq_world_design_publication_attempt_scope_request + UNIQUE (target_namespace, canonical_tenant_id, version_id, publication_request_id), + CONSTRAINT uq_world_design_publication_attempt_owner_fence + UNIQUE ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id + ), + CONSTRAINT fk_world_design_publication_attempt_tenant_association + 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 fk_world_design_publication_attempt_intake + FOREIGN KEY ( + intake_operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) + REFERENCES world_authored_source_intake ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + source_operation_id, + source_evidence_digest, + receipt_digest + ), + CONSTRAINT ck_world_design_publication_attempt_scope + CHECK (version_id > 0 AND version_state_epoch > 0 AND digest_schema_version > 0), + CONSTRAINT ck_world_design_publication_attempt_namespace + CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_design_publication_attempt_ids + CHECK ( + publication_fence <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND local_tenant_key > 0 + ), + CONSTRAINT ck_world_design_publication_attempt_source_digest + CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_design_publication_attempt_receipt_digest + CHECK (intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT ck_world_design_publication_attempt_request + CHECK ( + octet_length(publication_request_id) BETWEEN 1 AND 256 + AND position(':' IN publication_request_id) = 0 + AND octet_length(request_digest) = 64 + AND request_digest ~ '^[0-9a-f]{64}$' + AND publish_workflow_id = + 'publish:' || canonical_tenant_id::TEXT || ':publish-request:' || publication_request_id + AND octet_length(publish_workflow_id) <= 537 + ), + CONSTRAINT ck_world_design_publication_attempt_checkpoint + CHECK ( + octet_length(applied_commit_id) BETWEEN 1 AND 256 + AND content_digest ~ '^[0-9a-f]{64}$' + ) +); + +CREATE TABLE world_design_publication_fence_owner ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + version_id BIGINT NOT NULL, + owner_freeze_phase VARCHAR(32) NOT NULL, + current_publication_fence UUID, + CONSTRAINT pk_world_design_publication_fence_owner + PRIMARY KEY (local_tenant_key, version_id), + CONSTRAINT uq_world_design_publication_fence_owner_scope + UNIQUE (target_namespace, canonical_tenant_id, version_id), + CONSTRAINT fk_world_design_publication_owner_tenant_association + 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 fk_world_design_publication_owner_current_attempt + FOREIGN KEY ( + current_publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id + ) + REFERENCES world_design_publication_fence_attempt ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id + ), + CONSTRAINT ck_world_design_publication_fence_owner_scope + CHECK (version_id > 0 AND local_tenant_key > 0), + CONSTRAINT ck_world_design_publication_fence_owner_ids + CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_design_publication_fence_owner_namespace + CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_design_publication_fence_owner_phase + CHECK ( + (owner_freeze_phase = 'OPEN' AND current_publication_fence IS NULL) + OR + (owner_freeze_phase IN ( + 'FROZEN', + 'PUBLISHED', + 'ABORTED', + 'RECONCILIATION_REQUIRED' + ) AND current_publication_fence IS NOT NULL) + ) +); + +-- [jooq ignore start] +CREATE FUNCTION world_reject_publication_attempt_history_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World publication-fence attempt history is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE FUNCTION world_protect_publication_fence_owner() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'World publication-fence owner rows cannot be deleted' + USING ERRCODE = '55000'; + END IF; + + IF TG_OP = 'INSERT' THEN + IF NEW.owner_freeze_phase = 'OPEN' AND NEW.current_publication_fence IS NULL THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'World publication-fence owner rows must be created OPEN without a fence' + USING ERRCODE = '55000'; + END IF; + + IF OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + AND OLD.local_tenant_key IS NOT DISTINCT FROM NEW.local_tenant_key + AND OLD.version_id IS NOT DISTINCT FROM NEW.version_id + AND OLD.owner_freeze_phase = 'OPEN' + AND NEW.owner_freeze_phase = 'FROZEN' + AND OLD.current_publication_fence IS NULL + AND NEW.current_publication_fence IS NOT NULL + THEN + RETURN NEW; + END IF; + + RAISE EXCEPTION 'World publication-fence owner binding or phase transition is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_publication_attempt_immutable + BEFORE UPDATE OR DELETE ON world_design_publication_fence_attempt + FOR EACH ROW EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); + +CREATE TRIGGER trg_world_publication_attempt_no_truncate + BEFORE TRUNCATE ON world_design_publication_fence_attempt + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); + +CREATE TRIGGER trg_world_publication_owner_protect + BEFORE INSERT OR UPDATE OR DELETE ON world_design_publication_fence_owner + FOR EACH ROW EXECUTE FUNCTION world_protect_publication_fence_owner(); + +CREATE TRIGGER trg_world_publication_owner_no_truncate + BEFORE TRUNCATE ON world_design_publication_fence_owner + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql b/services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql new file mode 100644 index 0000000000..28f26a6f8f --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql @@ -0,0 +1,72 @@ +CREATE TABLE world_complete_launch_binding ( + binding_operation_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + control_plane_request_id TEXT NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + descriptor_request_digest VARCHAR(71) NOT NULL, + descriptor_result_digest VARCHAR(71) NOT NULL, + release_attestation_digest VARCHAR(71) NOT NULL, + descriptor_json TEXT NOT NULL, + release_attestation_json TEXT NOT NULL, + CONSTRAINT pk_world_complete_launch_binding PRIMARY KEY (binding_operation_id), + CONSTRAINT fk_world_complete_launch_binding_source + FOREIGN KEY ( + intake_operation_id, target_namespace, canonical_tenant_id, local_tenant_key, + intake_request_id, source_operation_id, source_evidence_digest, intake_receipt_digest + ) REFERENCES world_authored_source_intake ( + operation_id, target_namespace, canonical_tenant_id, local_tenant_key, + intake_request_id, source_operation_id, source_evidence_digest, receipt_digest + ), + CONSTRAINT ck_world_complete_launch_binding_ids CHECK ( + binding_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND local_tenant_key > 0 + ), + CONSTRAINT ck_world_complete_launch_binding_namespace CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_complete_launch_binding_world CHECK ( + world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT ck_world_complete_launch_binding_request CHECK ( + length(btrim(control_plane_request_id)) > 0 + ), + CONSTRAINT ck_world_complete_launch_binding_digests CHECK ( + source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND release_attestation_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_complete_launch_binding_components CHECK ( + length(descriptor_json) > 0 AND length(release_attestation_json) > 0 + ) +); + +-- [jooq ignore start] +-- The DDL export backend cannot index TEXT. PostgreSQL still enforces this exact +-- unbounded request identity; the runtime repository does not use generated keys. +ALTER TABLE world_complete_launch_binding + ADD CONSTRAINT uq_world_complete_launch_binding_request + UNIQUE (target_namespace, canonical_tenant_id, control_plane_request_id); + +CREATE TRIGGER trg_world_complete_launch_binding_immutable + BEFORE UPDATE OR DELETE ON world_complete_launch_binding + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_complete_launch_binding_no_truncate + BEFORE TRUNCATE ON world_complete_launch_binding + 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/V27__world_authored_version_identity.sql b/services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql new file mode 100644 index 0000000000..d6465727fe --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql @@ -0,0 +1,80 @@ +CREATE TABLE world_authored_version_identity ( + operation_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + canonical_version_id UUID NOT NULL, + game_design_version_id BIGINT NOT NULL, + local_version_key BIGINT GENERATED ALWAYS AS IDENTITY NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + intake_request_digest VARCHAR(71) NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + version_state_schema_version SMALLINT NOT NULL, + version_state_read_request_id UUID NOT NULL, + version_state_state VARCHAR(32) NOT NULL, + version_state_epoch BIGINT NOT NULL, + version_state_evidence_digest VARCHAR(71) NOT NULL, + version_state_evidence_json TEXT NOT NULL, + CONSTRAINT pk_world_authored_version_identity PRIMARY KEY (operation_id), + CONSTRAINT uq_world_authored_version_identity_local_key UNIQUE (local_version_key), + CONSTRAINT uq_world_authored_version_identity_canonical UNIQUE ( + target_namespace, canonical_tenant_id, world_slug, canonical_version_id + ), + CONSTRAINT uq_world_authored_version_identity_game_design_version UNIQUE ( + target_namespace, canonical_tenant_id, world_slug, game_design_version_id + ), + CONSTRAINT fk_world_authored_version_identity_intake FOREIGN KEY ( + intake_operation_id, target_namespace, canonical_tenant_id, local_tenant_key, + intake_request_id, source_operation_id, source_evidence_digest, intake_receipt_digest + ) REFERENCES world_authored_source_intake ( + operation_id, target_namespace, canonical_tenant_id, local_tenant_key, + intake_request_id, source_operation_id, source_evidence_digest, receipt_digest + ), + CONSTRAINT ck_world_authored_version_identity_scope CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(world_slug) BETWEEN 1 AND 120 + ), + CONSTRAINT ck_world_authored_version_identity_counters CHECK ( + game_design_version_id > 0 + AND local_version_key > 0 + AND local_tenant_key > 0 + AND version_state_epoch > 0 + AND version_state_schema_version = 1 + ), + CONSTRAINT ck_world_authored_version_identity_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_state_read_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_authored_version_identity_state CHECK ( + version_state_state IN ('DRAFT', 'PUBLISHED', 'ACTIVE') + ), + CONSTRAINT ck_world_authored_version_identity_digests CHECK ( + intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND version_state_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_authored_version_identity_json CHECK ( + octet_length(version_state_evidence_json) > 0 + ) +); + +-- [jooq ignore start] +CREATE TRIGGER trg_world_authored_version_identity_immutable + BEFORE UPDATE OR DELETE ON world_authored_version_identity + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_authored_version_identity_no_truncate + BEFORE TRUNCATE ON world_authored_version_identity + 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/V28__world_authored_graph_snapshot.sql b/services/world-management-service/src/main/resources/db/migration/V28__world_authored_graph_snapshot.sql new file mode 100644 index 0000000000..7ce80da733 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V28__world_authored_graph_snapshot.sql @@ -0,0 +1,329 @@ +ALTER TABLE world_authored_version_identity + ADD CONSTRAINT uq_world_authored_version_snapshot_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ), + ADD CONSTRAINT uq_world_authored_version_snapshot_attempt_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ); + +ALTER TABLE world_authored_source_intake + ADD CONSTRAINT uq_world_authored_source_intake_snapshot_binding UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + request_digest, + source_operation_id, + source_evidence_digest, + receipt_digest + ); + +ALTER TABLE world_design_publication_fence_attempt + ADD COLUMN owner_binding_schema_version SMALLINT NOT NULL DEFAULT 0, + ADD COLUMN canonical_version_id UUID, + ADD COLUMN version_identity_operation_id UUID, + ADD COLUMN game_design_version_id BIGINT, + ADD COLUMN intake_request_digest VARCHAR(71), + ADD CONSTRAINT ck_world_publication_attempt_owner_binding CHECK ( + (owner_binding_schema_version = 0 + AND canonical_version_id IS NULL + AND version_identity_operation_id IS NULL + AND game_design_version_id IS NULL + AND intake_request_digest IS NULL) + OR + (owner_binding_schema_version = 1 + AND canonical_version_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_identity_operation_id IS NOT NULL + AND version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_id IS NOT NULL + AND game_design_version_id > 0 + AND intake_request_digest IS NOT NULL + AND intake_request_digest ~ '^sha256:[0-9a-f]{64}$') + ), + ADD CONSTRAINT fk_world_publication_attempt_version_identity FOREIGN KEY ( + version_identity_operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + game_design_version_id, + version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) REFERENCES world_authored_version_identity ( + operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ); + +ALTER TABLE world_design_publication_fence_attempt + ADD CONSTRAINT uq_world_publication_snapshot_binding UNIQUE ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id, + owner_binding_schema_version, + canonical_version_id, + version_identity_operation_id, + game_design_version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest, + publication_request_id, + request_digest, + version_state_epoch, + publish_workflow_id, + applied_commit_id, + content_digest, + digest_schema_version + ); + +CREATE TABLE world_authored_graph_snapshot ( + snapshot_id UUID NOT NULL, + capture_request_digest VARCHAR(64) NOT NULL, + publication_fence UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + game_design_version_id BIGINT NOT NULL, + local_version_key BIGINT NOT NULL, + local_tenant_key BIGINT NOT NULL, + owner_binding_schema_version SMALLINT NOT NULL, + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + intake_request_digest VARCHAR(71) NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + publication_request_id VARCHAR(256) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + version_state_epoch BIGINT NOT NULL, + publish_workflow_id VARCHAR(537) NOT NULL, + applied_commit_id VARCHAR(256) NOT NULL, + content_digest VARCHAR(64) NOT NULL, + digest_schema_version INTEGER NOT NULL, + supplied_owned_affected_tuples_json TEXT NOT NULL, + owner_revision_evidence_json TEXT NOT NULL, + owner_commit_proof_status VARCHAR(32) NOT NULL, + graph_bytes BYTEA NOT NULL, + graph_sha256 VARCHAR(64) NOT NULL, + captured_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_world_authored_graph_snapshot PRIMARY KEY (snapshot_id), + CONSTRAINT uq_world_authored_graph_snapshot_fence UNIQUE (publication_fence), + CONSTRAINT uq_world_authored_graph_snapshot_request UNIQUE ( + target_namespace, canonical_tenant_id, canonical_version_id, publication_request_id + ), + CONSTRAINT fk_world_authored_graph_snapshot_attempt FOREIGN KEY ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + local_version_key, + owner_binding_schema_version, + canonical_version_id, + version_identity_operation_id, + game_design_version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest, + publication_request_id, + request_digest, + version_state_epoch, + publish_workflow_id, + applied_commit_id, + content_digest, + digest_schema_version + ) REFERENCES world_design_publication_fence_attempt ( + publication_fence, + target_namespace, + canonical_tenant_id, + local_tenant_key, + version_id, + owner_binding_schema_version, + canonical_version_id, + version_identity_operation_id, + game_design_version_id, + intake_operation_id, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest, + publication_request_id, + request_digest, + version_state_epoch, + publish_workflow_id, + applied_commit_id, + content_digest, + digest_schema_version + ), + CONSTRAINT fk_world_authored_graph_snapshot_version_identity FOREIGN KEY ( + version_identity_operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) REFERENCES world_authored_version_identity ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + game_design_version_id, + local_version_key, + intake_operation_id, + intake_request_id, + intake_request_digest, + local_tenant_key, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ), + CONSTRAINT fk_world_authored_graph_snapshot_intake FOREIGN KEY ( + intake_operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + intake_request_digest, + source_operation_id, + source_evidence_digest, + intake_receipt_digest + ) REFERENCES world_authored_source_intake ( + operation_id, + target_namespace, + canonical_tenant_id, + local_tenant_key, + intake_request_id, + request_digest, + source_operation_id, + source_evidence_digest, + receipt_digest + ), + CONSTRAINT ck_world_authored_graph_snapshot_scope CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_id > 0 + AND local_version_key > 0 + AND local_tenant_key > 0 + AND owner_binding_schema_version = 1 + AND version_state_epoch > 0 + AND digest_schema_version = 2 + ), + CONSTRAINT ck_world_authored_graph_snapshot_ids CHECK ( + snapshot_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND publication_fence <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_authored_graph_snapshot_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_authored_graph_snapshot_source_digests CHECK ( + intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND + source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_authored_graph_snapshot_request CHECK ( + octet_length(publication_request_id) BETWEEN 1 AND 256 + AND position(':' IN publication_request_id) = 0 + AND request_digest ~ '^[0-9a-f]{64}$' + AND capture_request_digest ~ '^[0-9a-f]{64}$' + AND publish_workflow_id = + 'publish:' || canonical_tenant_id::TEXT || ':publish-request:' || publication_request_id + ), + CONSTRAINT ck_world_authored_graph_snapshot_checkpoint CHECK ( + octet_length(applied_commit_id) BETWEEN 1 AND 256 + AND content_digest ~ '^[0-9a-f]{64}$' + AND graph_sha256 ~ '^[0-9a-f]{64}$' + AND octet_length(graph_bytes) > 0 + ), + CONSTRAINT ck_world_authored_graph_snapshot_proof CHECK ( + owner_commit_proof_status = 'CAPTURED_UNVERIFIED' + AND octet_length(supplied_owned_affected_tuples_json) > 0 + AND octet_length(owner_revision_evidence_json) > 0 + ) +); + +-- [jooq ignore start] +CREATE FUNCTION world_reject_authored_graph_snapshot_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World authored graph snapshot history is immutable' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_authored_graph_snapshot_immutable + BEFORE UPDATE OR DELETE ON world_authored_graph_snapshot + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_graph_snapshot_mutation(); + +CREATE TRIGGER trg_world_authored_graph_snapshot_no_truncate + BEFORE TRUNCATE ON world_authored_graph_snapshot + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_graph_snapshot_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V29__world_guarded_region_draft_commits.sql b/services/world-management-service/src/main/resources/db/migration/V29__world_guarded_region_draft_commits.sql new file mode 100644 index 0000000000..1cfada70b8 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V29__world_guarded_region_draft_commits.sql @@ -0,0 +1,392 @@ +-- Complete owner-local component storage only: no Account permission or publication proof. +ALTER TABLE world_authored_version_identity + ADD CONSTRAINT uq_world_region_commit_identity UNIQUE ( + operation_id, target_namespace, canonical_tenant_id, canonical_version_id, local_version_key + ); + +CREATE TABLE world_region_draft_commit ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID PRIMARY KEY, + commit_id UUID NOT NULL UNIQUE, + version_identity_operation_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + local_version_key BIGINT NOT NULL, + owner_binding_json TEXT NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL, + graph_bytes BYTEA NOT NULL, + graph_sha256 VARCHAR(64) NOT NULL, + result_bytes BYTEA NOT NULL, + storage_status VARCHAR(32) NOT NULL, + stored_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_world_region_commit_identity FOREIGN KEY ( + version_identity_operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, local_version_key + ) REFERENCES world_authored_version_identity ( + operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, local_version_key + ), + CONSTRAINT ck_world_region_commit_evidence CHECK ( + binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND graph_sha256 ~ '^[0-9a-f]{64}$' + AND octet_length(graph_bytes) > 0 AND octet_length(result_bytes) > 0 + AND storage_status = 'STORED_PERMISSION_UNVERIFIED' + AND local_tenant_key > 0 AND local_version_key > 0 + ) +); + +-- The function below creates and consumes these exact row transitions within its execution. +-- No manifest survives the function, and ordinary application code never inserts one. +CREATE TABLE world_region_draft_execution_manifest ( + transaction_id BIGINT NOT NULL, + operation_id UUID NOT NULL, + table_name VARCHAR(50) NOT NULL, + row_id BIGINT NOT NULL, + row_operation TEXT NOT NULL, + version_identity_operation_id UUID NOT NULL REFERENCES world_authored_version_identity(operation_id), + local_tenant_key BIGINT NOT NULL, + local_version_key BIGINT NOT NULL, + owner_binding JSONB NOT NULL, + complete_binding JSONB NOT NULL, + expected_old JSONB, + expected_new JSONB NOT NULL, + PRIMARY KEY (transaction_id, operation_id, table_name, row_id), + CHECK (table_name IN ('region', 'world_design_aggregate_epoch', 'world_design_scope_epoch')), + CHECK (row_operation IN ('INSERT', 'UPDATE')), + CHECK ((row_operation = 'INSERT' AND expected_old IS NULL AND table_name <> 'region') + OR (row_operation = 'UPDATE' AND expected_old IS NOT NULL)) +); + +-- [jooq ignore start] +REVOKE ALL ON world_region_draft_execution_manifest FROM PUBLIC; + +CREATE TRIGGER trg_world_region_commit_immutable + BEFORE UPDATE OR DELETE ON world_region_draft_commit + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_region_commit_no_truncate + BEFORE TRUNCATE ON world_region_draft_commit + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_consume_region_execution_manifest( + actual_table TEXT, actual_operation TEXT, actual_old JSONB, actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed BIGINT; +BEGIN + IF actual_operation NOT IN ('INSERT', 'UPDATE') OR actual_new IS NULL THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_region_draft_execution_manifest m + USING "${serviceSchema}".world_authored_version_identity v, + "${serviceSchema}".world_design_publication_fence_owner o + WHERE m.transaction_id = txid_current() + AND m.table_name = actual_table AND m.row_operation = actual_operation + AND m.row_id = (actual_new->>'id')::BIGINT + AND m.expected_old IS NOT DISTINCT FROM actual_old + AND m.expected_new = actual_new + AND m.local_tenant_key = (actual_new->>'tenant_id')::BIGINT + AND m.local_version_key = (actual_new->>'version_id')::BIGINT + AND v.operation_id = m.version_identity_operation_id + AND v.local_tenant_key = m.local_tenant_key + AND v.local_version_key = m.local_version_key + AND v.operation_id::TEXT = m.owner_binding->>'versionIdentityOperationId' + AND v.target_namespace = m.owner_binding->>'targetNamespace' + AND v.canonical_tenant_id::TEXT = m.owner_binding->>'canonicalTenantId' + AND v.canonical_version_id::TEXT = m.owner_binding->>'canonicalVersionId' + AND v.intake_operation_id::TEXT = m.owner_binding->>'intakeOperationId' + AND v.intake_request_id::TEXT = m.owner_binding->>'intakeRequestId' + AND v.intake_request_digest = m.owner_binding->>'intakeRequestDigest' + AND v.source_operation_id::TEXT = m.owner_binding->>'sourceOperationId' + AND v.source_evidence_digest = m.owner_binding->>'sourceEvidenceDigest' + AND v.intake_receipt_digest = m.owner_binding->>'intakeReceiptDigest' + AND v.game_design_version_id = (m.owner_binding->>'gameDesignVersionId')::BIGINT + AND v.canonical_tenant_id::TEXT = m.complete_binding->>'canonicalTenantId' + AND v.canonical_version_id::TEXT = m.complete_binding->>'canonicalVersionId' + AND m.operation_id::TEXT = m.complete_binding->>'commitId' + AND o.target_namespace = v.target_namespace + AND o.canonical_tenant_id = v.canonical_tenant_id + AND o.local_tenant_key = v.local_tenant_key AND o.version_id = v.local_version_key + AND o.owner_freeze_phase = 'OPEN' AND o.current_publication_fence IS NULL + RETURNING m.row_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_consume_region_execution_manifest(TEXT, TEXT, JSONB, JSONB) FROM PUBLIC; + +-- Retain the V24 deny boundary everywhere except an exact, single-use transition created by +-- the dedicated function. Moving a row out of a canonical tenant still enters this branch. +CREATE OR REPLACE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + claimed_key BIGINT; + old_row JSONB; + new_row JSONB; + canonical_old BOOLEAN := FALSE; + canonical_new BOOLEAN := FALSE; +BEGIN + IF TG_OP <> 'INSERT' THEN + old_row := to_jsonb(OLD); + SELECT EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_old; + END IF; + IF TG_OP <> 'DELETE' THEN + new_row := to_jsonb(NEW); + SELECT EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_new; + END IF; + IF canonical_old OR canonical_new THEN + IF TG_TABLE_SCHEMA = '${serviceSchema}' + AND "${serviceSchema}".world_consume_region_execution_manifest(TG_TABLE_NAME, TG_OP, old_row, new_row) + THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + INSERT INTO "${serviceSchema}".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; +$$; + +-- p_changes is the trusted component's typed, independently scope-validated complete World +-- subset. It grants no permission. Its tuples are rechecked against the retained full binding. +-- Neither a tenant allowlist nor a session flag can enable a guarded row write. +CREATE FUNCTION world_store_guarded_region_rows(p_owner JSONB, p_binding JSONB, p_changes JSONB) +RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + old_region "${serviceSchema}".region%ROWTYPE; + new_region "${serviceSchema}".region%ROWTYPE; + old_aggregate "${serviceSchema}".world_design_aggregate_epoch%ROWTYPE; + new_aggregate "${serviceSchema}".world_design_aggregate_epoch%ROWTYPE; + old_scope "${serviceSchema}".world_design_scope_epoch%ROWTYPE; + new_scope "${serviceSchema}".world_design_scope_epoch%ROWTYPE; + change JSONB; + expected_units JSONB := '[]'::JSONB; + supplied_units JSONB; + expected_aggregate BIGINT; + expected_scope BIGINT; + aggregate_exists BOOLEAN; + scope_exists BOOLEAN; + affected INTEGER; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' + OR jsonb_typeof(p_changes) <> 'array' OR jsonb_array_length(p_changes) = 0 + THEN + RAISE EXCEPTION 'Complete World region storage requires writable READ COMMITTED input' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT identity_row FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id = (p_owner->>'versionIdentityOperationId')::UUID FOR SHARE; + SELECT * INTO STRICT intake_row FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id = identity_row.intake_operation_id; + IF p_owner IS DISTINCT FROM jsonb_build_object( + 'targetNamespace', identity_row.target_namespace, + 'canonicalTenantId', identity_row.canonical_tenant_id, + 'canonicalVersionId', identity_row.canonical_version_id, + 'versionIdentityOperationId', identity_row.operation_id, + 'gameDesignVersionId', identity_row.game_design_version_id, + 'intakeRequestId', identity_row.intake_request_id, + 'intakeOperationId', identity_row.intake_operation_id, + 'intakeRequestDigest', identity_row.intake_request_digest, + 'sourceOperationId', identity_row.source_operation_id, + 'sourceEvidenceDigest', identity_row.source_evidence_digest, + 'intakeReceiptDigest', identity_row.intake_receipt_digest) + OR p_binding->>'canonicalTenantId' IS DISTINCT FROM identity_row.canonical_tenant_id::TEXT + OR p_binding->>'canonicalVersionId' IS DISTINCT FROM identity_row.canonical_version_id::TEXT + OR p_binding->'target' IS DISTINCT FROM jsonb_build_object( + 'gameDesignVersionRowId', identity_row.game_design_version_id::TEXT, + 'gameDesignVersionTenantKey', intake_row.source_game_tenant_key, + 'sourceGameRowId', intake_row.source_game_row_id::TEXT, + 'sourceGameTenantKey', intake_row.source_game_tenant_key, + 'sourceProvenanceKind', intake_row.source_provenance_kind) + THEN + RAISE EXCEPTION 'Complete World region source binding differs from retained intake/V27' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = identity_row.target_namespace + AND canonical_tenant_id = identity_row.canonical_tenant_id + AND local_tenant_key = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key FOR UPDATE; + IF owner_row.owner_freeze_phase <> 'OPEN' OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'World region storage requires the shared OPEN owner row' + USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest + WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'World complete region storage already has an execution manifest' + USING ERRCODE = '23514'; + END IF; + IF (SELECT count(DISTINCT value->>'id') FROM jsonb_array_elements(p_changes)) + <> jsonb_array_length(p_changes) THEN + RAISE EXCEPTION 'World complete region storage has duplicate region targets' + USING ERRCODE = '23514'; + END IF; + FOR change IN SELECT value FROM jsonb_array_elements(p_changes) LOOP + expected_units := expected_units || jsonb_build_array( + jsonb_build_object('owner', 'WORLD_MANAGEMENT', 'aggregateType', 'REGION', + 'aggregateId', change->>'id', 'scopeType', 'AGGREGATE', 'scopeId', change->>'id', + 'expectedEpoch', change->>'expectedAggregateEpoch'), + jsonb_build_object('owner', 'WORLD_MANAGEMENT', 'aggregateType', 'REGION', + 'aggregateId', change->>'id', 'scopeType', 'REGION_SUBTREE', 'scopeId', change->>'id', + 'expectedEpoch', change->>'expectedScopeEpoch')); + END LOOP; + SELECT coalesce(jsonb_agg(value ORDER BY value->>'aggregateId', value->>'scopeType'), '[]'::JSONB) + INTO supplied_units FROM jsonb_array_elements(p_binding->'affectedUnits') + WHERE value->>'owner' = 'WORLD_MANAGEMENT'; + SELECT jsonb_agg(value ORDER BY value->>'aggregateId', value->>'scopeType') + INTO expected_units FROM jsonb_array_elements(expected_units); + IF supplied_units IS DISTINCT FROM expected_units THEN + RAISE EXCEPTION 'World complete storage requires every exact REGION and REGION_SUBTREE tuple' + USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(p_changes) + WHERE (value->>'expectedAggregateEpoch')::BIGINT < 0 + OR (value->>'expectedAggregateEpoch')::BIGINT = 9223372036854775807 + OR (value->>'expectedScopeEpoch')::BIGINT < 0 + OR (value->>'expectedScopeEpoch')::BIGINT = 9223372036854775807) THEN + RAISE EXCEPTION 'World epoch is not advanceable' USING ERRCODE = '23514'; + END IF; + + FOR change IN SELECT value FROM jsonb_array_elements(p_changes) LOOP + expected_aggregate := (change->>'expectedAggregateEpoch')::BIGINT; + expected_scope := (change->>'expectedScopeEpoch')::BIGINT; + IF expected_aggregate < 0 OR expected_aggregate = 9223372036854775807 + OR expected_scope < 0 OR expected_scope = 9223372036854775807 THEN + RAISE EXCEPTION 'World epoch is not advanceable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT old_region FROM "${serviceSchema}".region + WHERE id = (change->>'id')::BIGINT AND tenant_id = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key FOR UPDATE; + new_region := old_region; + new_region.name := change->>'name'; + new_region.shard_id := (change->>'shardId')::INTEGER; + new_region.weather := change->>'weather'; + new_region.generation_seed := (change->>'generationSeed')::BIGINT; + new_region.generator_type := change->>'generatorType'; + new_region.generator_params := change->>'generatorParams'; + new_region.spacing_multiplier := (change->>'spacingMultiplier')::DOUBLE PRECISION; + IF new_region.name IS NULL OR btrim(new_region.name) = '' OR new_region.shard_id < 0 + OR new_region.spacing_multiplier <= 0 + OR new_region.spacing_multiplier IN ('NaN'::DOUBLE PRECISION, 'Infinity'::DOUBLE PRECISION) THEN + RAISE EXCEPTION 'World region payload is invalid' USING ERRCODE = '23514'; + END IF; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), (p_binding->>'commitId')::UUID, 'region', old_region.id, 'UPDATE', + identity_row.operation_id, identity_row.local_tenant_key, identity_row.local_version_key, + p_owner, p_binding, to_jsonb(old_region), to_jsonb(new_region)); + UPDATE "${serviceSchema}".region SET name = new_region.name, shard_id = new_region.shard_id, + weather = new_region.weather, generation_seed = new_region.generation_seed, + generator_type = new_region.generator_type, generator_params = new_region.generator_params, + spacing_multiplier = new_region.spacing_multiplier + WHERE id = old_region.id AND to_jsonb(region) = to_jsonb(old_region); + GET DIAGNOSTICS affected = ROW_COUNT; + IF affected <> 1 THEN + RAISE EXCEPTION 'World region changed during complete storage' USING ERRCODE = '23514'; + END IF; + + SELECT * INTO old_aggregate FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key + AND aggregate_type = 'REGION' AND aggregate_id = old_region.id FOR UPDATE; + aggregate_exists := FOUND; + IF (aggregate_exists AND old_aggregate.draft_revision_epoch <> expected_aggregate) + OR (NOT aggregate_exists AND expected_aggregate <> 0) THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION aggregate epoch' USING ERRCODE = '23514'; + END IF; + IF aggregate_exists THEN + new_aggregate := old_aggregate; + ELSE + new_aggregate.id := nextval('"${serviceSchema}".world_design_aggregate_epoch_id_seq'); + new_aggregate.tenant_id := identity_row.local_tenant_key; + new_aggregate.version_id := identity_row.local_version_key; + new_aggregate.aggregate_type := 'REGION'; + new_aggregate.aggregate_id := old_region.id; + END IF; + new_aggregate.draft_revision_epoch := expected_aggregate + 1; + new_aggregate.updated_at := CURRENT_TIMESTAMP; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), (p_binding->>'commitId')::UUID, 'world_design_aggregate_epoch', new_aggregate.id, + CASE WHEN aggregate_exists THEN 'UPDATE' ELSE 'INSERT' END, + identity_row.operation_id, identity_row.local_tenant_key, identity_row.local_version_key, + p_owner, p_binding, CASE WHEN aggregate_exists THEN to_jsonb(old_aggregate) END, to_jsonb(new_aggregate)); + IF aggregate_exists THEN + UPDATE "${serviceSchema}".world_design_aggregate_epoch + SET draft_revision_epoch = new_aggregate.draft_revision_epoch, updated_at = new_aggregate.updated_at + WHERE id = old_aggregate.id AND draft_revision_epoch = expected_aggregate; + ELSE + INSERT INTO "${serviceSchema}".world_design_aggregate_epoch SELECT (new_aggregate).*; + END IF; + GET DIAGNOSTICS affected = ROW_COUNT; + IF affected <> 1 THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION aggregate CAS' USING ERRCODE = '23514'; + END IF; + + SELECT * INTO old_scope FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key + AND scope_type = 'REGION_SUBTREE' AND scope_id = old_region.id::TEXT FOR UPDATE; + scope_exists := FOUND; + IF (scope_exists AND old_scope.draft_scope_revision_epoch <> expected_scope) + OR (NOT scope_exists AND expected_scope <> 0) THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION_SUBTREE epoch' USING ERRCODE = '23514'; + END IF; + IF scope_exists THEN + new_scope := old_scope; + ELSE + new_scope.id := nextval('"${serviceSchema}".world_design_scope_epoch_id_seq'); + new_scope.tenant_id := identity_row.local_tenant_key; + new_scope.version_id := identity_row.local_version_key; + new_scope.scope_type := 'REGION_SUBTREE'; + new_scope.scope_id := old_region.id::TEXT; + END IF; + new_scope.draft_scope_revision_epoch := expected_scope + 1; + new_scope.updated_at := CURRENT_TIMESTAMP; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), (p_binding->>'commitId')::UUID, 'world_design_scope_epoch', new_scope.id, + CASE WHEN scope_exists THEN 'UPDATE' ELSE 'INSERT' END, + identity_row.operation_id, identity_row.local_tenant_key, identity_row.local_version_key, + p_owner, p_binding, CASE WHEN scope_exists THEN to_jsonb(old_scope) END, to_jsonb(new_scope)); + IF scope_exists THEN + UPDATE "${serviceSchema}".world_design_scope_epoch + SET draft_scope_revision_epoch = new_scope.draft_scope_revision_epoch, updated_at = new_scope.updated_at + WHERE id = old_scope.id AND draft_scope_revision_epoch = expected_scope; + ELSE + INSERT INTO "${serviceSchema}".world_design_scope_epoch SELECT (new_scope).*; + END IF; + GET DIAGNOSTICS affected = ROW_COUNT; + IF affected <> 1 THEN + RAISE EXCEPTION 'DRAFT_WRITE_CONFLICT: REGION_SUBTREE CAS' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'Complete World storage left an unconsumed execution manifest' + USING ERRCODE = '23514'; + END IF; +END; +$$; +-- Explicit internal calls only; deployment roles must deliberately grant access when an +-- authenticated producer exists. Schema owners are the trusted database administration boundary. +REVOKE ALL ON FUNCTION world_store_guarded_region_rows(JSONB, JSONB, JSONB) FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V30__world_guarded_uuid_topology_commits.sql b/services/world-management-service/src/main/resources/db/migration/V30__world_guarded_uuid_topology_commits.sql new file mode 100644 index 0000000000..361bee13d2 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V30__world_guarded_uuid_topology_commits.sql @@ -0,0 +1,490 @@ +-- Fresh authored UUID topology is component storage, never permission/release evidence. +-- Retained numeric rows stay unmapped; no canonical identity is inferred from a private key. +ALTER TABLE world_entity_spawn_binding ALTER COLUMN entity_template_id DROP NOT NULL; +ALTER TABLE world_entity_spawn_binding + ADD COLUMN entity_canonical_tenant_id UUID, + ADD COLUMN entity_canonical_version_id UUID, + ADD COLUMN entity_canonical_template_id UUID, + ADD CONSTRAINT ck_world_spawn_reference_representation CHECK ( + (entity_template_id IS NOT NULL AND entity_canonical_tenant_id IS NULL + AND entity_canonical_version_id IS NULL AND entity_canonical_template_id IS NULL) + OR (entity_template_id IS NULL AND entity_canonical_tenant_id IS NOT NULL + AND entity_canonical_version_id IS NOT NULL AND entity_canonical_template_id IS NOT NULL + AND entity_canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND entity_canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND entity_canonical_template_id <> '00000000-0000-0000-0000-000000000000'::UUID) + ); +CREATE UNIQUE INDEX uq_world_spawn_canonical_reference ON world_entity_spawn_binding + (tenant_id, version_id, room_id, entity_template_type, + entity_canonical_tenant_id, entity_canonical_version_id, entity_canonical_template_id) + WHERE entity_template_id IS NULL; + +CREATE TABLE world_topology_draft_commit ( + request_id UUID PRIMARY KEY, + commit_id UUID NOT NULL UNIQUE, + version_identity_operation_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL CHECK (local_tenant_key > 0), + local_version_key BIGINT NOT NULL CHECK (local_version_key > 0), + owner_binding_json TEXT NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + graph_bytes BYTEA NOT NULL CHECK (octet_length(graph_bytes) > 0), + graph_sha256 VARCHAR(64) NOT NULL CHECK (graph_sha256 ~ '^[0-9a-f]{64}$'), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + storage_status VARCHAR(32) NOT NULL CHECK (storage_status = 'STORED_PERMISSION_UNVERIFIED'), + stored_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (request_id, commit_id, version_identity_operation_id, + target_namespace, canonical_tenant_id, canonical_version_id, local_tenant_key, local_version_key), + FOREIGN KEY (version_identity_operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, local_version_key) + REFERENCES world_authored_version_identity(operation_id, target_namespace, + canonical_tenant_id, canonical_version_id, local_version_key) +); +CREATE TABLE world_authored_topology_identity ( + id BIGSERIAL PRIMARY KEY, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + family VARCHAR(50) NOT NULL CHECK (family IN ( + 'REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING')), + template_id UUID NOT NULL CHECK (template_id <> '00000000-0000-0000-0000-000000000000'::UUID), + private_row_key BIGINT NOT NULL CHECK (private_row_key > 0), + tenant_id BIGINT NOT NULL, + version_id BIGINT NOT NULL, + version_identity_operation_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + revision_id UUID NOT NULL, + revision_order TEXT NOT NULL, + UNIQUE (target_namespace, canonical_tenant_id, canonical_version_id, family, template_id), + UNIQUE (family, private_row_key), + FOREIGN KEY (request_id, commit_id, version_identity_operation_id, + target_namespace, canonical_tenant_id, canonical_version_id, tenant_id, version_id) + REFERENCES world_topology_draft_commit(request_id, commit_id, version_identity_operation_id, + target_namespace, canonical_tenant_id, canonical_version_id, local_tenant_key, local_version_key) + DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (version_identity_operation_id, target_namespace, canonical_tenant_id, + canonical_version_id, version_id) + REFERENCES world_authored_version_identity(operation_id, target_namespace, + canonical_tenant_id, canonical_version_id, local_version_key) +); + +-- [jooq ignore start] +-- Reuse V29's exact OLD/NEW, source-qualified, transaction-local, consumed manifest. +ALTER TABLE world_region_draft_execution_manifest + DROP CONSTRAINT world_region_draft_execution_manifest_table_name_check, + DROP CONSTRAINT world_region_draft_execution_manifest_check; +ALTER TABLE world_region_draft_execution_manifest + ADD CONSTRAINT ck_world_execution_table CHECK (table_name IN ( + 'region','zone','room','room_exit','generation_rule','world_entity_spawn_binding', + 'world_authored_topology_identity','world_design_aggregate_epoch','world_design_scope_epoch')), + ADD CONSTRAINT ck_world_execution_transition CHECK ( + (row_operation = 'INSERT' AND expected_old IS NULL) + OR (row_operation = 'UPDATE' AND expected_old IS NOT NULL + AND table_name IN ('region','world_design_aggregate_epoch','world_design_scope_epoch'))); + +CREATE TRIGGER trg_world_topology_history_immutable BEFORE UPDATE OR DELETE + ON world_topology_draft_commit FOR EACH ROW + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_topology_history_no_truncate BEFORE TRUNCATE + ON world_topology_draft_commit FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_protect_topology_identity() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF TG_OP = 'INSERT' AND "${serviceSchema}".world_consume_region_execution_manifest( + TG_TABLE_NAME, TG_OP, NULL, to_jsonb(NEW)) THEN RETURN NEW; END IF; + RAISE EXCEPTION 'World UUID mapping requires an exact fresh execution manifest and is immutable' + USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER trg_world_topology_identity_guard BEFORE INSERT OR UPDATE OR DELETE + ON world_authored_topology_identity FOR EACH ROW EXECUTE FUNCTION world_protect_topology_identity(); +CREATE TRIGGER trg_world_topology_identity_no_truncate BEFORE TRUNCATE + ON world_authored_topology_identity FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_protect_mapped_topology_row() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity + WHERE family = CASE TG_TABLE_NAME WHEN 'world_entity_spawn_binding' + THEN 'WORLD_ENTITY_SPAWN_BINDING' ELSE upper(TG_TABLE_NAME) END + AND private_row_key = OLD.id) THEN + RAISE EXCEPTION 'Mapped UUID World content cannot be changed by numeric writers' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_region_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON region + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_zone_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON zone + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_room_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON room + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_room_exit_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON room_exit + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_generation_rule_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON generation_rule + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +CREATE TRIGGER trg_world_entity_spawn_binding_mapped_uuid_immutable BEFORE UPDATE OR DELETE ON world_entity_spawn_binding + FOR EACH ROW EXECUTE FUNCTION world_protect_mapped_topology_row(); + +-- The trusted local parsed projection uses canonical protobuf JSON for execution only. +-- Exact original full binding/payload bytes remain the manifest/history authority. As in V29, +-- this typed component seam is not a public caller field or permission evidence; the repository +-- verifies every actual stored payload against the original parsed plan before recording history. +CREATE FUNCTION world_store_guarded_uuid_topology( + p_owner JSONB, p_binding JSONB, p_execution_revisions JSONB +) +RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + mapping "${serviceSchema}".world_authored_topology_identity%ROWTYPE; + revision JSONB; + mutation JSONB; + payload JSONB; + family TEXT; + table_name TEXT; + content JSONB; + complete_row JSONB; + scope_key BIGINT; + parent_key BIGINT; + other_key BIGINT; + scope_type TEXT; + scope_uuid UUID; + expected_units JSONB := '[]'::JSONB; + supplied_units JSONB; + expected_sorted JSONB; + epoch_row JSONB; + nodes JSONB; + original_revision_identities JSONB; + execution_revision_identities JSONB; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'World topology requires writable READ COMMITTED' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT identity_row FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id = (p_owner->>'versionIdentityOperationId')::UUID FOR SHARE; + SELECT * INTO STRICT intake_row FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id = identity_row.intake_operation_id; + IF p_owner IS DISTINCT FROM jsonb_build_object( + 'targetNamespace', identity_row.target_namespace, + 'canonicalTenantId', identity_row.canonical_tenant_id, + 'canonicalVersionId', identity_row.canonical_version_id, + 'versionIdentityOperationId', identity_row.operation_id, + 'gameDesignVersionId', identity_row.game_design_version_id, + 'intakeRequestId', identity_row.intake_request_id, + 'intakeOperationId', identity_row.intake_operation_id, + 'intakeRequestDigest', identity_row.intake_request_digest, + 'sourceOperationId', identity_row.source_operation_id, + 'sourceEvidenceDigest', identity_row.source_evidence_digest, + 'intakeReceiptDigest', identity_row.intake_receipt_digest) + OR p_binding->>'canonicalTenantId' IS DISTINCT FROM identity_row.canonical_tenant_id::TEXT + OR p_binding->>'canonicalVersionId' IS DISTINCT FROM identity_row.canonical_version_id::TEXT + OR p_binding->'target' IS DISTINCT FROM jsonb_build_object( + 'gameDesignVersionRowId', identity_row.game_design_version_id::TEXT, + 'gameDesignVersionTenantKey', intake_row.source_game_tenant_key, + 'sourceGameRowId', intake_row.source_game_row_id::TEXT, + 'sourceGameTenantKey', intake_row.source_game_tenant_key, + 'sourceProvenanceKind', intake_row.source_provenance_kind) + THEN + RAISE EXCEPTION 'Complete World region source binding differs from retained intake/V27' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = identity_row.target_namespace + AND canonical_tenant_id = identity_row.canonical_tenant_id + AND local_tenant_key = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key FOR UPDATE; + IF owner_row.owner_freeze_phase <> 'OPEN' OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'World topology storage requires the shared OPEN owner row' + USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest + WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'World complete region storage already has an execution manifest' + USING ERRCODE = '23514'; + END IF; + + IF jsonb_typeof(p_execution_revisions) IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'World typed execution projection must be an array' USING ERRCODE = '23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('revisionOrder',value->>'revisionOrder', + 'revisionId',value->>'revisionId','owner',value->>'owner') + ORDER BY ordinal) INTO original_revision_identities + FROM jsonb_array_elements(p_binding->'revisions') WITH ORDINALITY AS original(value,ordinal) + WHERE value->>'owner' = 'WORLD_MANAGEMENT'; + SELECT jsonb_agg(jsonb_build_object('revisionOrder',value->>'revisionOrder', + 'revisionId',value->>'revisionId','owner',value->>'owner') + ORDER BY ordinal) INTO execution_revision_identities + FROM jsonb_array_elements(p_execution_revisions) WITH ORDINALITY AS execution(value,ordinal); + IF original_revision_identities IS NULL + OR execution_revision_identities IS DISTINCT FROM original_revision_identities THEN + RAISE EXCEPTION 'World typed execution projection differs from exact original revision identities/order/owner' + USING ERRCODE = '23514'; + END IF; + SELECT jsonb_agg(value ORDER BY (value->>'revisionOrder')::NUMERIC) INTO nodes + FROM jsonb_array_elements(p_execution_revisions); + IF nodes IS NULL OR intake_row.source_provenance_kind <> 'NEW_GAME_ROW' THEN + RAISE EXCEPTION 'Fresh topology requires World input and exact fresh source' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_commit + WHERE request_id = (p_binding->>'requestId')::UUID OR commit_id = (p_binding->>'commitId')::UUID) THEN + RAISE EXCEPTION 'World request/commit already has retained numeric history' USING ERRCODE = '23514'; + END IF; + -- Require a wholly fresh local Version. Retained content is never relabelled or overwritten. + IF EXISTS (SELECT 1 FROM "${serviceSchema}".region + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained region' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".zone + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained zone' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".room + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained room' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".room_exit + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained room_exit' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".generation_rule + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained generation_rule' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_entity_spawn_binding + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained world_entity_spawn_binding' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained world_design_aggregate_epoch' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = identity_row.local_tenant_key AND version_id = identity_row.local_version_key) THEN + RAISE EXCEPTION 'Fresh World topology conflicts with retained world_design_scope_epoch' USING ERRCODE = '23514'; + END IF; + + FOR revision IN SELECT value FROM jsonb_array_elements(nodes) LOOP + mutation := (revision->>'payload')::JSONB; + family := replace(mutation->>'aggregateType', 'WORLD_DESIGN_AGGREGATE_TYPE_', ''); + scope_type := replace(mutation->>'scopeType', 'WORLD_DESIGN_SCOPE_TYPE_', ''); + IF family NOT IN ('REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING') + OR scope_type NOT IN ('REGION_SUBTREE','ZONE_SUBTREE') + OR mutation->>'operation' IS DISTINCT FROM 'WORLD_DESIGN_MUTATION_OPERATION_UPSERT' + OR mutation->>'commitId' IS DISTINCT FROM p_binding->>'commitId' + OR mutation->>'logicalRevisionId' IS DISTINCT FROM revision->>'revisionId' + OR coalesce(mutation->>'expectedDraftRevisionEpoch','0') <> '0' + OR coalesce(mutation->>'expectedDraftScopeRevisionEpoch','0') <> '0' + OR coalesce(mutation->>'scopeMutationPolicy','WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED') + <> 'WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED' THEN + RAISE EXCEPTION 'Unsupported exact fresh World revision' USING ERRCODE = '23514'; + END IF; + table_name := lower(family); + mapping.id := nextval('"${serviceSchema}".world_authored_topology_identity_id_seq'); + mapping.target_namespace := identity_row.target_namespace; + mapping.canonical_tenant_id := identity_row.canonical_tenant_id; + mapping.canonical_version_id := identity_row.canonical_version_id; + mapping.family := family; + mapping.template_id := (mutation->>'aggregateId')::UUID; + mapping.private_row_key := nextval( + format('%I.%I', '${serviceSchema}', table_name || '_id_seq')::REGCLASS); + mapping.tenant_id := identity_row.local_tenant_key; + mapping.version_id := identity_row.local_version_key; + mapping.version_identity_operation_id := identity_row.operation_id; + mapping.request_id := (p_binding->>'requestId')::UUID; + mapping.commit_id := (p_binding->>'commitId')::UUID; + mapping.revision_id := (revision->>'revisionId')::UUID; + mapping.revision_order := revision->>'revisionOrder'; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), mapping.commit_id, 'world_authored_topology_identity', mapping.id, 'INSERT', + identity_row.operation_id, mapping.tenant_id, mapping.version_id, + p_owner, p_binding, NULL, to_jsonb(mapping)); + INSERT INTO "${serviceSchema}".world_authored_topology_identity SELECT (mapping).*; + expected_units := expected_units || jsonb_build_array( + jsonb_build_object('owner','WORLD_MANAGEMENT','aggregateType',family, + 'aggregateId',mapping.template_id::TEXT,'scopeType','AGGREGATE', + 'scopeId',mapping.template_id::TEXT,'expectedEpoch','0'), + jsonb_build_object('owner','WORLD_MANAGEMENT','aggregateType',family, + 'aggregateId',mapping.template_id::TEXT,'scopeType',scope_type, + 'scopeId',mutation->>'scopeId','expectedEpoch','0')); + END LOOP; + SELECT jsonb_agg(value ORDER BY value->>'aggregateType',value->>'aggregateId',value->>'scopeType',value->>'scopeId') + INTO expected_sorted FROM jsonb_array_elements(expected_units); + SELECT jsonb_agg(value ORDER BY value->>'aggregateType',value->>'aggregateId',value->>'scopeType',value->>'scopeId') + INTO supplied_units FROM jsonb_array_elements(p_binding->'affectedUnits') + WHERE value->>'owner' = 'WORLD_MANAGEMENT'; + IF expected_sorted IS DISTINCT FROM supplied_units THEN + RAISE EXCEPTION 'World topology requires the exact aggregate and containing tuples' + USING ERRCODE = '23514'; + END IF; + -- Typed mappings are allocated first, then content is inserted in parent-before-child order. + FOR mapping IN SELECT m.* FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = (p_binding->>'requestId')::UUID + ORDER BY CASE m.family WHEN 'REGION' THEN 1 WHEN 'ZONE' THEN 2 WHEN 'ROOM' THEN 3 + WHEN 'ROOM_EXIT' THEN 4 WHEN 'GENERATION_RULE' THEN 5 ELSE 6 END, m.revision_order::NUMERIC + LOOP + SELECT value INTO STRICT revision FROM jsonb_array_elements(nodes) + WHERE value->>'revisionId' = mapping.revision_id::TEXT; + mutation := (revision->>'payload')::JSONB; + family := mapping.family; + table_name := lower(family); + scope_type := replace(mutation->>'scopeType','WORLD_DESIGN_SCOPE_TYPE_',''); + scope_uuid := (mutation->>'scopeId')::UUID; + SELECT m.private_row_key INTO STRICT scope_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.template_id = scope_uuid + AND m.family = CASE scope_type WHEN 'REGION_SUBTREE' THEN 'REGION' ELSE 'ZONE' END; + content := jsonb_build_object('id',mapping.private_row_key,'tenant_id',mapping.tenant_id, + 'version_id',mapping.version_id,'version',0); + CASE family + + WHEN 'REGION' THEN + payload := mutation->'region'; + IF scope_type <> 'REGION_SUBTREE' OR scope_uuid <> mapping.template_id THEN + RAISE EXCEPTION 'Region scope substitution' USING ERRCODE = '23514'; + END IF; + content := content || jsonb_build_object( + 'name',coalesce(payload->>'name',''),'shard_id',coalesce((payload->>'shardId')::INT,0), + 'weather',coalesce(payload->>'weather',''),'generation_seed',coalesce((payload->>'generationSeed')::BIGINT,0), + 'generator_type',coalesce(payload->>'generatorType',''),'generator_params',coalesce(payload->>'generatorParams',''), + 'spacing_multiplier',coalesce(nullif((payload->>'spacingMultiplier')::FLOAT8,0),1)); + WHEN 'ZONE' THEN + payload := mutation->'zone'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'REGION' + AND m.template_id = (payload->>'regionId')::UUID; + IF (scope_type = 'REGION_SUBTREE' AND scope_key <> parent_key) + OR (scope_type = 'ZONE_SUBTREE' AND scope_uuid <> mapping.template_id) THEN + RAISE EXCEPTION 'Zone scope substitution' USING ERRCODE = '23514'; + END IF; + content := content || jsonb_build_object('name',coalesce(payload->>'name',''),'region_id',parent_key); + WHEN 'ROOM' THEN + payload := mutation->'room'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ZONE' + AND m.template_id = (payload->>'zoneId')::UUID; + SELECT z.region_id INTO STRICT other_key FROM "${serviceSchema}".zone z WHERE z.id = parent_key; + IF scope_key <> (CASE scope_type WHEN 'REGION_SUBTREE' THEN other_key ELSE parent_key END) THEN + RAISE EXCEPTION 'Room scope substitution' USING ERRCODE = '23514'; + END IF; + content := content || jsonb_build_object('name',coalesce(payload->>'name',''), + 'description',coalesce(payload->>'description',''),'zone_id',parent_key, + 'name_localized_variants_json',coalesce(payload->>'nameLocalizedVariantsJson',''), + 'description_localized_variants_json',coalesce(payload->>'descriptionLocalizedVariantsJson','')); + WHEN 'ROOM_EXIT' THEN + payload := mutation->'roomExit'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ROOM' + AND m.template_id = (payload->>'fromRoomId')::UUID; + SELECT m.private_row_key INTO STRICT other_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ROOM' + AND m.template_id = (payload->>'toRoomId')::UUID; + content := content || jsonb_build_object('from_room_id',parent_key,'to_room_id',other_key, + 'direction',coalesce(payload->>'direction',''),'cost',coalesce(nullif((payload->>'cost')::INT,0),1)); + WHEN 'GENERATION_RULE' THEN + payload := mutation->'generationRule'; + content := content || jsonb_build_object('name',coalesce(payload->>'name',''), + 'value',coalesce(payload->>'value',''),'scope_type',scope_type,'scope_id',scope_key::TEXT); + WHEN 'WORLD_ENTITY_SPAWN_BINDING' THEN + payload := mutation->'worldEntitySpawnBinding'; + SELECT m.private_row_key INTO STRICT parent_key FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = mapping.request_id AND m.family = 'ROOM' + AND m.template_id = (payload->>'roomId')::UUID; + content := content || jsonb_build_object('room_id',parent_key, + 'entity_template_type',replace(payload->>'entityTemplateType','ENTITY_TEMPLATE_REFERENCE_TYPE_',''), + 'entity_template_id',NULL,'entity_canonical_tenant_id',mapping.canonical_tenant_id, + 'entity_canonical_version_id',mapping.canonical_version_id, + 'entity_canonical_template_id',(payload->>'entityTemplateId')::UUID, + 'spawn_count',coalesce(nullif((payload->>'spawnCount')::INT,0),1), + 'respawn_delay_seconds',coalesce((payload->>'respawnDelaySeconds')::INT,0)); + ELSE RAISE EXCEPTION 'Unsupported World family'; + END CASE; + IF payload IS NULL + OR (content ? 'name' AND btrim(content->>'name') = '') + OR coalesce((content->>'shard_id')::INT,0) < 0 + OR coalesce((content->>'spacing_multiplier')::FLOAT8,1) <= 0 + OR coalesce((content->>'spacing_multiplier')::FLOAT8,1) IN ('NaN'::FLOAT8,'Infinity'::FLOAT8) + OR coalesce((content->>'cost')::INT,1) < 1 + OR coalesce((content->>'spawn_count')::INT,1) < 1 + OR coalesce((content->>'respawn_delay_seconds')::INT,0) < 0 + OR (family = 'WORLD_ENTITY_SPAWN_BINDING' AND content->>'entity_template_type' NOT IN ('ITEM','NPC')) + OR (family = 'ROOM_EXIT' AND btrim(content->>'direction') = '') THEN + RAISE EXCEPTION 'Invalid fresh World payload' USING ERRCODE = '23514'; + END IF; + IF family IN ('ROOM_EXIT','WORLD_ENTITY_SPAWN_BINDING') THEN + IF NOT EXISTS (SELECT 1 FROM "${serviceSchema}".room r + JOIN "${serviceSchema}".zone z ON z.id = r.zone_id + WHERE r.id = parent_key AND CASE scope_type + WHEN 'REGION_SUBTREE' THEN z.region_id ELSE z.id END = scope_key) + OR (family = 'ROOM_EXIT' AND NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".room r JOIN "${serviceSchema}".zone z ON z.id = r.zone_id + WHERE r.id = other_key AND CASE scope_type + WHEN 'REGION_SUBTREE' THEN z.region_id ELSE z.id END = scope_key)) THEN + RAISE EXCEPTION 'World endpoint outside exact scope' USING ERRCODE = '23514'; + END IF; + END IF; + -- Populate the full physical row type so the manifest includes every actual column. + EXECUTE format('SELECT to_jsonb(jsonb_populate_record(NULL::%I.%I, $1))', + '${serviceSchema}',table_name) INTO complete_row USING content; + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), mapping.commit_id, table_name, mapping.private_row_key, 'INSERT', + identity_row.operation_id, mapping.tenant_id, mapping.version_id, + p_owner, p_binding, NULL, complete_row); + EXECUTE format('INSERT INTO %I.%I SELECT (jsonb_populate_record(NULL::%I.%I,$1)).*', + '${serviceSchema}',table_name,'${serviceSchema}',table_name) USING complete_row; + epoch_row := jsonb_build_object( + 'id',nextval('"${serviceSchema}".world_design_aggregate_epoch_id_seq'), + 'tenant_id',mapping.tenant_id,'version_id',mapping.version_id, + 'aggregate_type',family,'aggregate_id',mapping.private_row_key, + 'draft_revision_epoch',1,'updated_at',CURRENT_TIMESTAMP::TIMESTAMP); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(), mapping.commit_id, 'world_design_aggregate_epoch',(epoch_row->>'id')::BIGINT,'INSERT', + identity_row.operation_id,mapping.tenant_id,mapping.version_id,p_owner,p_binding,NULL,epoch_row); + INSERT INTO "${serviceSchema}".world_design_aggregate_epoch + SELECT (jsonb_populate_record(NULL::"${serviceSchema}".world_design_aggregate_epoch,epoch_row)).*; + END LOOP; + -- Each distinct containing fence advances once, even when multiple affected tuples share it. + FOR revision IN SELECT DISTINCT jsonb_build_object('scope_type',value->>'scopeType','scope_id',value->>'scopeId') + FROM jsonb_array_elements(expected_units) WHERE value->>'scopeType' <> 'AGGREGATE' + LOOP + epoch_row := jsonb_build_object( + 'id',nextval('"${serviceSchema}".world_design_scope_epoch_id_seq'), + 'tenant_id',identity_row.local_tenant_key,'version_id',identity_row.local_version_key, + 'scope_type',revision->>'scope_type','scope_id',revision->>'scope_id', + 'draft_scope_revision_epoch',1,'updated_at',CURRENT_TIMESTAMP::TIMESTAMP); + INSERT INTO "${serviceSchema}".world_region_draft_execution_manifest VALUES ( + txid_current(),(p_binding->>'commitId')::UUID,'world_design_scope_epoch',(epoch_row->>'id')::BIGINT,'INSERT', + identity_row.operation_id,identity_row.local_tenant_key,identity_row.local_version_key, + p_owner,p_binding,NULL,epoch_row); + INSERT INTO "${serviceSchema}".world_design_scope_epoch + SELECT (jsonb_populate_record(NULL::"${serviceSchema}".world_design_scope_epoch,epoch_row)).*; + END LOOP; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_region_draft_execution_manifest + WHERE transaction_id = txid_current()) THEN + RAISE EXCEPTION 'Unconsumed World topology execution manifest' USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_store_guarded_uuid_topology(JSONB,JSONB,JSONB) FROM PUBLIC; +REVOKE ALL ON FUNCTION world_protect_topology_identity() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_protect_mapped_topology_row() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V31__world_canonical_frozen_topology.sql b/services/world-management-service/src/main/resources/db/migration/V31__world_canonical_frozen_topology.sql new file mode 100644 index 0000000000..6b72524bfe --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V31__world_canonical_frozen_topology.sql @@ -0,0 +1,96 @@ +-- Immutable component capture only. The V25 checkpoint is retained, never redefined as graph hash. +CREATE TABLE world_canonical_frozen_topology ( + capture_id UUID PRIMARY KEY CHECK (capture_id <> '00000000-0000-0000-0000-000000000000'::UUID), + publication_fence UUID NOT NULL UNIQUE REFERENCES world_design_publication_fence_attempt(publication_fence), + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + freeze_request_json TEXT NOT NULL, + owner_binding_json TEXT NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + identity_json TEXT NOT NULL, + intake_json TEXT NOT NULL, + graph_bytes BYTEA NOT NULL CHECK (octet_length(graph_bytes) > 0), + graph_sha256 VARCHAR(64) NOT NULL CHECK (graph_sha256 ~ '^[0-9a-f]{64}$'), + storage_result_bytes BYTEA NOT NULL CHECK (octet_length(storage_result_bytes) > 0), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + capture_status VARCHAR(32) NOT NULL CHECK (capture_status = 'CAPTURED_UNVERIFIED'), + captured_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (request_id) REFERENCES world_topology_draft_commit(request_id), + FOREIGN KEY (commit_id) REFERENCES world_topology_draft_commit(commit_id), + FOREIGN KEY (version_identity_operation_id) REFERENCES world_authored_version_identity(operation_id) +); + +-- [jooq ignore start] +CREATE FUNCTION world_check_canonical_frozen_capture() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + commit_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + frozen_evidence JSONB; + identity TEXT; + intake TEXT; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'Canonical frozen capture requires writable READ COMMITTED' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT commit_row FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id=NEW.request_id AND commit_id=NEW.commit_id + AND version_identity_operation_id=NEW.version_identity_operation_id; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE local_tenant_key=commit_row.local_tenant_key AND version_id=commit_row.local_version_key FOR UPDATE; + SELECT * INTO STRICT attempt FROM "${serviceSchema}".world_design_publication_fence_attempt + WHERE publication_fence=NEW.publication_fence; + SELECT to_jsonb(v)::text, to_jsonb(i)::text INTO STRICT identity, intake + FROM "${serviceSchema}".world_authored_version_identity v + JOIN "${serviceSchema}".world_authored_source_intake i ON i.operation_id=v.intake_operation_id + WHERE v.operation_id=NEW.version_identity_operation_id; + frozen_evidence := NEW.freeze_request_json::jsonb; + IF owner_row.owner_freeze_phase <> 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence + OR attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR attempt.local_tenant_key IS DISTINCT FROM commit_row.local_tenant_key + OR attempt.version_id IS DISTINCT FROM commit_row.local_version_key + OR attempt.version_identity_operation_id IS DISTINCT FROM NEW.version_identity_operation_id + OR attempt.canonical_tenant_id IS DISTINCT FROM commit_row.canonical_tenant_id + OR attempt.canonical_version_id IS DISTINCT FROM commit_row.canonical_version_id + OR attempt.target_namespace IS DISTINCT FROM commit_row.target_namespace + OR attempt.applied_commit_id IS DISTINCT FROM NEW.commit_id::text + OR frozen_evidence->>'targetNamespace' IS DISTINCT FROM attempt.target_namespace + OR frozen_evidence->>'canonicalTenantId' IS DISTINCT FROM attempt.canonical_tenant_id::text + OR frozen_evidence->>'canonicalVersionId' IS DISTINCT FROM attempt.canonical_version_id::text + OR frozen_evidence->>'intakeRequestId' IS DISTINCT FROM attempt.intake_request_id::text + OR frozen_evidence->>'publicationFence' IS DISTINCT FROM attempt.publication_fence::text + OR frozen_evidence->>'publicationRequestId' IS DISTINCT FROM attempt.publication_request_id + OR frozen_evidence->>'requestDigest' IS DISTINCT FROM attempt.request_digest + OR frozen_evidence->>'versionStateEpoch' IS DISTINCT FROM attempt.version_state_epoch::text + OR frozen_evidence->>'publishWorkflowId' IS DISTINCT FROM attempt.publish_workflow_id + OR frozen_evidence->>'appliedCommitId' IS DISTINCT FROM attempt.applied_commit_id + OR frozen_evidence->>'contentDigest' IS DISTINCT FROM attempt.content_digest + OR frozen_evidence->>'digestSchemaVersion' IS DISTINCT FROM attempt.digest_schema_version::text + OR NEW.owner_binding_json IS DISTINCT FROM commit_row.owner_binding_json + OR NEW.binding_json IS DISTINCT FROM commit_row.binding_json + OR NEW.binding_digest IS DISTINCT FROM commit_row.binding_digest + OR NEW.graph_bytes IS DISTINCT FROM commit_row.graph_bytes + OR NEW.graph_sha256 IS DISTINCT FROM commit_row.graph_sha256 + OR NEW.storage_result_bytes IS DISTINCT FROM commit_row.result_bytes + OR NEW.identity_json IS DISTINCT FROM identity OR NEW.intake_json IS DISTINCT FROM intake THEN + RAISE EXCEPTION 'Canonical frozen capture differs from exact original storage and FROZEN checkpoint' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_canonical_frozen_insert BEFORE INSERT + ON world_canonical_frozen_topology FOR EACH ROW + EXECUTE FUNCTION world_check_canonical_frozen_capture(); +CREATE TRIGGER trg_world_canonical_frozen_immutable BEFORE UPDATE OR DELETE + ON world_canonical_frozen_topology FOR EACH ROW + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_canonical_frozen_no_truncate BEFORE TRUNCATE + ON world_canonical_frozen_topology 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/V32__world_digest_schema3_capture.sql b/services/world-management-service/src/main/resources/db/migration/V32__world_digest_schema3_capture.sql new file mode 100644 index 0000000000..e920f23870 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V32__world_digest_schema3_capture.sql @@ -0,0 +1,39 @@ +-- Preserve exact immutable schema-2 history; only new captures use schema 3. +ALTER TABLE world_authored_graph_snapshot + DROP CONSTRAINT ck_world_authored_graph_snapshot_scope; +ALTER TABLE world_authored_graph_snapshot + ADD CONSTRAINT ck_world_authored_graph_snapshot_scope CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_design_version_id > 0 + AND local_version_key > 0 + AND local_tenant_key > 0 + AND owner_binding_schema_version = 1 + AND version_state_epoch > 0 + AND digest_schema_version IN (2, 3) + ); + +-- [jooq ignore start] +CREATE FUNCTION world_require_new_digest_schema3_capture() RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_TABLE_NAME = 'world_authored_graph_snapshot' THEN + IF NEW.digest_schema_version IS DISTINCT FROM 3 THEN + RAISE EXCEPTION 'New World graph capture requires digest schema 3' USING ERRCODE = '23514'; + END IF; + ELSE + IF (NEW.freeze_request_json::jsonb)->>'digestSchemaVersion' IS DISTINCT FROM '3' THEN + RAISE EXCEPTION 'New canonical graph capture requires digest schema 3' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_authored_graph_snapshot_schema3 BEFORE INSERT + ON world_authored_graph_snapshot FOR EACH ROW + EXECUTE FUNCTION world_require_new_digest_schema3_capture(); +CREATE TRIGGER trg_world_canonical_frozen_00_schema3 BEFORE INSERT + ON world_canonical_frozen_topology FOR EACH ROW + EXECUTE FUNCTION world_require_new_digest_schema3_capture(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V34__world_canonical_instance_association.sql b/services/world-management-service/src/main/resources/db/migration/V34__world_canonical_instance_association.sql new file mode 100644 index 0000000000..d3e4459c95 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V34__world_canonical_instance_association.sql @@ -0,0 +1,506 @@ +-- Canonical creation identity is insert-born. Existing numeric lifecycle rows stay unmapped. +ALTER TABLE world_instance + ADD COLUMN canonical_game_instance_id UUID, + ADD COLUMN canonical_target_namespace VARCHAR(63), + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN canonical_world_slug VARCHAR(120), + ADD COLUMN playable_state_namespace_id UUID, + ADD COLUMN playable_state_scope VARCHAR(16), + ADD COLUMN public_production BOOLEAN, + ADD COLUMN playtest_lifecycle_id UUID, + ADD COLUMN playtest_state_generation BIGINT, + ADD COLUMN canonical_launch_binding_operation_id UUID; + +ALTER TABLE world_instance + ADD CONSTRAINT fk_world_instance_canonical_launch_binding + FOREIGN KEY (canonical_launch_binding_operation_id) + REFERENCES world_complete_launch_binding (binding_operation_id) + ON DELETE RESTRICT, + ADD CONSTRAINT uq_world_instance_canonical_game_instance + UNIQUE (canonical_game_instance_id), + ADD CONSTRAINT uq_world_instance_canonical_binding + UNIQUE (canonical_launch_binding_operation_id), + ADD CONSTRAINT uq_world_instance_canonical_association_fk + UNIQUE ( + id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id + ), + ADD CONSTRAINT ck_world_instance_canonical_creation_identity CHECK ( + ( + canonical_game_instance_id IS NULL + AND canonical_target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND canonical_world_slug IS NULL + AND playable_state_namespace_id IS NULL + AND playable_state_scope IS NULL + AND public_production IS NULL + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + AND canonical_launch_binding_operation_id IS NULL + ) + OR + ( + canonical_game_instance_id IS NOT NULL + AND canonical_target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_world_slug IS NOT NULL + AND playable_state_namespace_id IS NOT NULL + AND playable_state_scope IS NOT NULL + AND public_production IS TRUE + AND canonical_launch_binding_operation_id IS NOT NULL + -- The current Game Session owner-read projection does not carry playtest identity. + -- This foundation therefore admits only SHARED, non-playtest creation rows. + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(canonical_world_slug) BETWEEN 1 AND 120 + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_scope = 'SHARED' + AND canonical_launch_binding_operation_id + <> '00000000-0000-0000-0000-000000000000'::UUID + ) + ); + +-- A canonical World version key must remain explicitly tied to its immutable UUID association. +ALTER TABLE world_authored_version_identity + ADD CONSTRAINT uq_world_authored_version_identity_instance_binding + UNIQUE ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + local_tenant_key, + local_version_key + ); + +CREATE TABLE world_canonical_instance_association ( + schema_version SMALLINT NOT NULL, + canonical_game_instance_id UUID NOT NULL, + canonical_target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_world_slug VARCHAR(120) NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(16) NOT NULL, + public_production BOOLEAN NOT NULL, + playtest_lifecycle_id UUID, + playtest_state_generation BIGINT, + control_plane_request_id VARCHAR(128) NOT NULL, + world_instance_id BIGINT NOT NULL, + canonical_launch_binding_operation_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + private_game_instance_key BIGINT NOT NULL, + game_template_id BIGINT NOT NULL, + launch_descriptor_id VARCHAR(64) NOT NULL, + local_version_key BIGINT NOT NULL, + script_patch_version VARCHAR(100), + runtime_flags_json TEXT NOT NULL, + generation_config_revision VARCHAR(128) NOT NULL, + release_bundle_id BIGINT NOT NULL, + published_release_bundle_ref VARCHAR(128) NOT NULL, + version_state_epoch BIGINT NOT NULL, + remap_set_id VARCHAR(64), + intake_operation_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + intake_request_digest VARCHAR(71) NOT NULL, + intake_receipt_digest VARCHAR(71) NOT NULL, + descriptor_request_digest VARCHAR(71) NOT NULL, + descriptor_result_digest VARCHAR(71) NOT NULL, + release_attestation_digest VARCHAR(71) NOT NULL, + CONSTRAINT pk_world_canonical_instance_association + PRIMARY KEY (canonical_game_instance_id), + CONSTRAINT uq_world_canonical_instance_association_scoped + UNIQUE ( + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + canonical_game_instance_id + ), + CONSTRAINT uq_world_canonical_instance_association_request + UNIQUE (canonical_target_namespace, canonical_tenant_id, control_plane_request_id), + CONSTRAINT uq_world_canonical_instance_association_row UNIQUE (world_instance_id), + CONSTRAINT uq_world_canonical_instance_association_binding + UNIQUE (canonical_launch_binding_operation_id), + CONSTRAINT fk_world_canonical_instance_association_world_row + FOREIGN KEY ( + world_instance_id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id + ) REFERENCES world_instance ( + id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id + ) ON DELETE RESTRICT, + CONSTRAINT fk_world_canonical_instance_association_launch_binding + FOREIGN KEY (canonical_launch_binding_operation_id) + REFERENCES world_complete_launch_binding (binding_operation_id) + ON DELETE RESTRICT, + CONSTRAINT fk_world_canonical_instance_association_version_identity + FOREIGN KEY ( + version_identity_operation_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + canonical_version_id, + local_tenant_key, + local_version_key + ) REFERENCES world_authored_version_identity ( + operation_id, + target_namespace, + canonical_tenant_id, + world_slug, + canonical_version_id, + local_tenant_key, + local_version_key + ) ON DELETE RESTRICT, + CONSTRAINT ck_world_canonical_instance_association_schema + CHECK (schema_version = 1), + CONSTRAINT ck_world_canonical_instance_association_ids CHECK ( + canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_launch_binding_operation_id + <> '00000000-0000-0000-0000-000000000000'::UUID + AND version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_canonical_instance_association_scope CHECK ( + canonical_target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(canonical_world_slug) BETWEEN 1 AND 120 + AND playable_state_scope = 'SHARED' + AND public_production IS TRUE + AND length(btrim(control_plane_request_id)) BETWEEN 1 AND 128 + AND playtest_lifecycle_id IS NULL + AND playtest_state_generation IS NULL + ), + CONSTRAINT ck_world_canonical_instance_association_owner_keys CHECK ( + world_instance_id > 0 + AND local_tenant_key > 0 + AND private_game_instance_key > 0 + AND game_template_id > 0 + AND local_version_key > 0 + AND release_bundle_id > 0 + AND version_state_epoch > 0 + AND length(btrim(launch_descriptor_id)) BETWEEN 1 AND 64 + AND length(btrim(runtime_flags_json)) > 0 + AND length(btrim(generation_config_revision)) BETWEEN 1 AND 128 + AND length(btrim(published_release_bundle_ref)) BETWEEN 1 AND 128 + AND (script_patch_version IS NULL OR length(btrim(script_patch_version)) BETWEEN 1 AND 100) + AND (remap_set_id IS NULL OR length(btrim(remap_set_id)) BETWEEN 1 AND 64) + ), + CONSTRAINT ck_world_canonical_instance_association_digests CHECK ( + source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND release_attestation_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION world_validate_canonical_prepare_identity() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + binding world_complete_launch_binding%ROWTYPE; + version_identity world_authored_version_identity%ROWTYPE; + descriptor JSONB; + release_attestation JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.canonical_game_instance_id IS NOT NULL THEN + RAISE EXCEPTION 'Canonical World instance creation identity is retained' + USING ERRCODE = '55000'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF OLD.canonical_game_instance_id IS NULL THEN + IF NEW.canonical_game_instance_id IS NOT NULL + OR NEW.canonical_target_namespace IS NOT NULL + OR NEW.canonical_tenant_id IS NOT NULL + OR NEW.canonical_world_slug IS NOT NULL + OR NEW.playable_state_namespace_id IS NOT NULL + OR NEW.playable_state_scope IS NOT NULL + OR NEW.public_production IS NOT NULL + OR NEW.playtest_lifecycle_id IS NOT NULL + OR NEW.playtest_state_generation IS NOT NULL + OR NEW.canonical_launch_binding_operation_id IS NOT NULL THEN + RAISE EXCEPTION 'A retained World instance cannot acquire canonical creation identity' + USING ERRCODE = '55000'; + END IF; + RETURN NEW; + END IF; + + IF OLD.id IS DISTINCT FROM NEW.id + OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id + OR OLD.game_instance_id IS DISTINCT FROM NEW.game_instance_id + OR OLD.game_template_id IS DISTINCT FROM NEW.game_template_id + OR OLD.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR OLD.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR OLD.version_id IS DISTINCT FROM NEW.version_id + OR OLD.script_patch_version IS DISTINCT FROM NEW.script_patch_version + OR OLD.runtime_flags_json IS DISTINCT FROM NEW.runtime_flags_json + OR OLD.generation_config_revision IS DISTINCT FROM NEW.generation_config_revision + OR OLD.release_bundle_id IS DISTINCT FROM NEW.release_bundle_id + OR OLD.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR OLD.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch + OR OLD.remap_set_id IS DISTINCT FROM NEW.remap_set_id + OR OLD.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR OLD.canonical_target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR OLD.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR OLD.canonical_world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR OLD.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR OLD.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR OLD.public_production IS DISTINCT FROM NEW.public_production + OR OLD.playtest_lifecycle_id IS DISTINCT FROM NEW.playtest_lifecycle_id + OR OLD.playtest_state_generation IS DISTINCT FROM NEW.playtest_state_generation + OR OLD.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id THEN + RAISE EXCEPTION 'Canonical World instance creation and prepare inputs are immutable' + USING ERRCODE = '55000'; + END IF; + RETURN NEW; + END IF; + + IF NEW.canonical_game_instance_id IS NULL THEN + RETURN NEW; + END IF; + + SELECT * INTO binding + FROM world_complete_launch_binding + WHERE binding_operation_id = NEW.canonical_launch_binding_operation_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Canonical World instance requires its exact retained launch binding' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO version_identity + FROM world_authored_version_identity + WHERE target_namespace = NEW.canonical_target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND world_slug = NEW.canonical_world_slug + AND canonical_version_id = binding.canonical_version_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Canonical World instance requires its exact UUID-to-private-Version association' + USING ERRCODE = '23514'; + END IF; + + descriptor := binding.descriptor_json::jsonb; + release_attestation := binding.release_attestation_json::jsonb; + IF binding.target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR binding.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR binding.world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR binding.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR binding.local_tenant_key IS DISTINCT FROM NEW.tenant_id + OR version_identity.intake_operation_id IS DISTINCT FROM binding.intake_operation_id + OR version_identity.intake_request_id IS DISTINCT FROM binding.intake_request_id + OR version_identity.intake_request_digest IS DISTINCT FROM ( + SELECT request_digest FROM world_authored_source_intake + WHERE operation_id = binding.intake_operation_id + ) + OR version_identity.source_operation_id IS DISTINCT FROM binding.source_operation_id + OR version_identity.source_evidence_digest IS DISTINCT FROM binding.source_evidence_digest + OR version_identity.intake_receipt_digest IS DISTINCT FROM binding.intake_receipt_digest + OR version_identity.local_tenant_key IS DISTINCT FROM NEW.tenant_id + OR version_identity.local_version_key IS DISTINCT FROM NEW.version_id + OR version_identity.canonical_version_id IS DISTINCT FROM binding.canonical_version_id + OR version_identity.game_design_version_id::text IS DISTINCT FROM descriptor->>'versionId' + OR descriptor->>'targetNamespace' IS DISTINCT FROM NEW.canonical_target_namespace + OR descriptor->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::text + OR descriptor->>'worldSlug' IS DISTINCT FROM NEW.canonical_world_slug + OR descriptor->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR descriptor->>'authoredWorldSourceOperationId' + IS DISTINCT FROM binding.source_operation_id::text + OR descriptor->>'authoredWorldSourceEvidenceDigest' + IS DISTINCT FROM binding.source_evidence_digest + OR descriptor->>'requestDigest' IS DISTINCT FROM binding.descriptor_request_digest + OR descriptor->>'resultDigest' IS DISTINCT FROM binding.descriptor_result_digest + OR descriptor->>'launchDescriptorId' IS DISTINCT FROM NEW.launch_descriptor_id + OR descriptor->>'gameTemplateId' IS DISTINCT FROM NEW.game_template_id::text + OR descriptor->>'runtimeFlagsJson' IS DISTINCT FROM NEW.runtime_flags_json + OR descriptor->>'generationConfigRevision' IS DISTINCT FROM NEW.generation_config_revision + OR descriptor->>'releaseBundleId' IS DISTINCT FROM NEW.release_bundle_id::text + OR descriptor->>'publishedReleaseBundleRef' IS DISTINCT FROM NEW.published_release_bundle_ref + OR descriptor->>'versionStateEpoch' IS DISTINCT FROM NEW.version_state_epoch::text + OR ( + CASE WHEN descriptor->>'scriptPatchVersionPresent' = 'true' + THEN descriptor->>'scriptPatchVersion' + ELSE NULL + END + ) IS DISTINCT FROM NEW.script_patch_version + OR ( + CASE WHEN descriptor->>'remapSetIdPresent' = 'true' + THEN descriptor->>'remapSetId' + ELSE NULL + END + ) IS DISTINCT FROM NEW.remap_set_id + OR release_attestation->>'targetNamespace' IS DISTINCT FROM NEW.canonical_target_namespace + OR release_attestation->>'descriptorResultDigest' + IS DISTINCT FROM binding.descriptor_result_digest + OR release_attestation->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::text + OR release_attestation->>'canonicalVersionId' IS DISTINCT FROM binding.canonical_version_id::text + OR release_attestation->>'worldSlug' IS DISTINCT FROM NEW.canonical_world_slug + OR release_attestation->>'authoredWorldSourceOperationId' + IS DISTINCT FROM binding.source_operation_id::text + OR release_attestation->>'authoredWorldSourceEvidenceDigest' + IS DISTINCT FROM binding.source_evidence_digest + OR release_attestation->>'launchDescriptorId' IS DISTINCT FROM NEW.launch_descriptor_id + OR release_attestation->>'publishedReleaseBundleRef' + IS DISTINCT FROM NEW.published_release_bundle_ref + OR release_attestation->>'versionStateEpoch' IS DISTINCT FROM NEW.version_state_epoch::text + OR release_attestation->>'generationConfigRevision' + IS DISTINCT FROM NEW.generation_config_revision + OR release_attestation->>'evidenceDigest' IS DISTINCT FROM binding.release_attestation_digest THEN + RAISE EXCEPTION 'Canonical World instance prepare fields differ from immutable launch/source history' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_instance_canonical_prepare_identity + BEFORE INSERT OR UPDATE OR DELETE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_prepare_identity(); + +CREATE FUNCTION world_validate_canonical_instance_association() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + instance world_instance%ROWTYPE; + binding world_complete_launch_binding%ROWTYPE; + version_identity world_authored_version_identity%ROWTYPE; +BEGIN + SELECT * INTO instance FROM world_instance WHERE id = NEW.world_instance_id FOR KEY SHARE; + IF NOT FOUND OR instance.canonical_game_instance_id IS NULL THEN + RAISE EXCEPTION 'Canonical instance association requires an insert-born canonical World row' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO binding + FROM world_complete_launch_binding + WHERE binding_operation_id = NEW.canonical_launch_binding_operation_id; + SELECT * INTO version_identity + FROM world_authored_version_identity + WHERE operation_id = NEW.version_identity_operation_id; + + IF NOT FOUND + OR instance.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR instance.canonical_target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR instance.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR instance.canonical_world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR instance.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR instance.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR instance.public_production IS DISTINCT FROM NEW.public_production + OR instance.playtest_lifecycle_id IS DISTINCT FROM NEW.playtest_lifecycle_id + OR instance.playtest_state_generation IS DISTINCT FROM NEW.playtest_state_generation + OR instance.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR instance.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id + OR instance.tenant_id IS DISTINCT FROM NEW.local_tenant_key + OR instance.game_instance_id IS DISTINCT FROM NEW.private_game_instance_key + OR instance.game_template_id IS DISTINCT FROM NEW.game_template_id + OR instance.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR instance.version_id IS DISTINCT FROM NEW.local_version_key + OR instance.script_patch_version IS DISTINCT FROM NEW.script_patch_version + OR instance.runtime_flags_json IS DISTINCT FROM NEW.runtime_flags_json + OR instance.generation_config_revision IS DISTINCT FROM NEW.generation_config_revision + OR instance.release_bundle_id IS DISTINCT FROM NEW.release_bundle_id + OR instance.published_release_bundle_ref IS DISTINCT FROM NEW.published_release_bundle_ref + OR instance.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch + OR instance.remap_set_id IS DISTINCT FROM NEW.remap_set_id + OR binding.target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR binding.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR binding.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR binding.world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR binding.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR binding.intake_operation_id IS DISTINCT FROM NEW.intake_operation_id + OR binding.intake_request_id IS DISTINCT FROM NEW.intake_request_id + OR binding.local_tenant_key IS DISTINCT FROM NEW.local_tenant_key + OR binding.source_operation_id IS DISTINCT FROM NEW.source_operation_id + OR binding.source_evidence_digest IS DISTINCT FROM NEW.source_evidence_digest + OR binding.intake_receipt_digest IS DISTINCT FROM NEW.intake_receipt_digest + OR binding.descriptor_request_digest IS DISTINCT FROM NEW.descriptor_request_digest + OR binding.descriptor_result_digest IS DISTINCT FROM NEW.descriptor_result_digest + OR binding.release_attestation_digest IS DISTINCT FROM NEW.release_attestation_digest + OR version_identity.target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR version_identity.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR version_identity.world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR version_identity.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR version_identity.local_tenant_key IS DISTINCT FROM NEW.local_tenant_key + OR version_identity.local_version_key IS DISTINCT FROM NEW.local_version_key + OR version_identity.intake_operation_id IS DISTINCT FROM binding.intake_operation_id + OR version_identity.intake_request_id IS DISTINCT FROM binding.intake_request_id + OR version_identity.source_operation_id IS DISTINCT FROM binding.source_operation_id + OR version_identity.source_evidence_digest IS DISTINCT FROM binding.source_evidence_digest + OR version_identity.intake_receipt_digest IS DISTINCT FROM binding.intake_receipt_digest THEN + RAISE EXCEPTION 'Canonical instance association differs from exact owner creation, source, Version, or release rows' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_canonical_instance_association_exact_insert + BEFORE INSERT ON world_canonical_instance_association + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_instance_association(); + +CREATE TRIGGER trg_world_canonical_instance_association_immutable + BEFORE UPDATE OR DELETE ON world_canonical_instance_association + FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE TRIGGER trg_world_canonical_instance_association_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_association + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_reject_canonical_world_instance_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'World instance creation identity cannot be truncated' + USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_instance_canonical_no_truncate + BEFORE TRUNCATE ON world_instance + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_canonical_world_instance_truncate(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V35__world_guarded_canonical_instance_preparation.sql b/services/world-management-service/src/main/resources/db/migration/V35__world_guarded_canonical_instance_preparation.sql new file mode 100644 index 0000000000..dc71fa0d17 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V35__world_guarded_canonical_instance_preparation.sql @@ -0,0 +1,858 @@ +-- Canonical preparation is an insert-born, owner-private materialization boundary. The existing +-- V24 reserved-tenant guard remains closed except for exact single-use rows emitted below. +ALTER TABLE region_instance ADD COLUMN canonical_region_instance_id UUID; +ALTER TABLE zone_instance ADD COLUMN canonical_zone_instance_id UUID; +CREATE UNIQUE INDEX uq_region_instance_canonical_runtime_id + ON region_instance (canonical_region_instance_id) + WHERE canonical_region_instance_id IS NOT NULL; +CREATE UNIQUE INDEX uq_zone_instance_canonical_runtime_id + ON zone_instance (canonical_zone_instance_id) + WHERE canonical_zone_instance_id IS NOT NULL; + +CREATE SEQUENCE world_canonical_private_game_instance_key_seq AS BIGINT MINVALUE 1; +SELECT setval( + 'world_canonical_private_game_instance_key_seq'::REGCLASS, + coalesce(max(game_instance_id), 0) + 1, + FALSE) +FROM world_instance; + +CREATE TABLE world_canonical_instance_preparation_execution_manifest ( + transaction_id BIGINT NOT NULL, + table_name VARCHAR(64) NOT NULL, + row_id BIGINT NOT NULL, + canonical_game_instance_id UUID NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + capture_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + input_digest VARCHAR(71) NOT NULL, + expected_new JSONB NOT NULL, + PRIMARY KEY (transaction_id, table_name, row_id), + CHECK (table_name IN ( + 'world_instance', 'region_instance', 'zone_instance', 'room_instance', + 'room_instance_exit', 'world_canonical_instance_topology_identity', + 'world_canonical_instance_preparation')), + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (version_identity_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (capture_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (local_tenant_key > 0), + CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE TABLE world_canonical_instance_topology_identity ( + id BIGSERIAL PRIMARY KEY, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + canonical_game_instance_id UUID NOT NULL, + family VARCHAR(32) NOT NULL CHECK (family IN ('REGION', 'ZONE', 'ROOM', 'ROOM_EXIT')), + template_id UUID NOT NULL CHECK (template_id <> '00000000-0000-0000-0000-000000000000'::UUID), + template_private_row_key BIGINT NOT NULL CHECK (template_private_row_key > 0), + runtime_row_id BIGINT NOT NULL CHECK (runtime_row_id > 0), + runtime_identity UUID, + runtime_room_instance_id BIGINT, + UNIQUE (world_instance_id, family, template_id), + UNIQUE (family, runtime_row_id), + FOREIGN KEY (canonical_game_instance_id) REFERENCES world_instance(canonical_game_instance_id) + ON DELETE RESTRICT, + CHECK ( + (family = 'REGION' AND runtime_identity IS NOT NULL AND runtime_room_instance_id IS NULL) + OR (family = 'ZONE' AND runtime_identity IS NOT NULL AND runtime_room_instance_id IS NULL) + OR (family = 'ROOM' AND runtime_identity IS NULL AND runtime_room_instance_id > 0) + OR (family = 'ROOM_EXIT' AND runtime_identity IS NULL AND runtime_room_instance_id IS NULL) + ) +); +CREATE INDEX idx_world_canonical_instance_topology_world + ON world_canonical_instance_topology_identity(world_instance_id, family, id); + +CREATE TABLE world_canonical_instance_preparation ( + id BIGSERIAL PRIMARY KEY, + canonical_game_instance_id UUID NOT NULL UNIQUE, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_version_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + capture_id UUID NOT NULL REFERENCES world_canonical_frozen_topology(capture_id) ON DELETE RESTRICT, + graph_bytes BYTEA NOT NULL CHECK (octet_length(graph_bytes) > 0), + graph_sha256 VARCHAR(64) NOT NULL CHECK (graph_sha256 ~ '^[0-9a-f]{64}$'), + input_digest VARCHAR(71) NOT NULL CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + input_json TEXT NOT NULL CHECK (length(input_json) > 0), + world_instance_id BIGINT NOT NULL UNIQUE REFERENCES world_instance(id) ON DELETE RESTRICT, + private_game_instance_key BIGINT NOT NULL CHECK (private_game_instance_key > 0), + region_count INTEGER NOT NULL CHECK (region_count > 0), + zone_count INTEGER NOT NULL CHECK (zone_count >= 0), + room_count INTEGER NOT NULL CHECK (room_count >= 0), + exit_count INTEGER NOT NULL CHECK (exit_count >= 0), + storage_status VARCHAR(32) NOT NULL CHECK (storage_status = 'MATERIALIZED_UNVERIFIED'), + prepared_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (target_namespace, canonical_tenant_id, control_plane_request_id), + FOREIGN KEY (version_identity_operation_id) + REFERENCES world_authored_version_identity(operation_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_game_instance_id) + REFERENCES world_canonical_instance_association(canonical_game_instance_id) + DEFERRABLE INITIALLY DEFERRED +); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_preparation_execution_manifest FROM PUBLIC; + +CREATE FUNCTION world_consume_canonical_prepare_execution_manifest( + actual_table TEXT, actual_operation TEXT, actual_old JSONB, actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed BIGINT; +BEGIN + IF actual_operation <> 'INSERT' OR actual_old IS NOT NULL OR actual_new IS NULL THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest m + USING "${serviceSchema}".world_authored_version_identity v, + "${serviceSchema}".world_canonical_frozen_topology f, + "${serviceSchema}".world_authored_source_tenant_key_reservation r + WHERE m.transaction_id = txid_current() + AND m.table_name = actual_table + AND m.row_id = (actual_new->>'id')::BIGINT + AND m.expected_new = actual_new + AND v.operation_id = m.version_identity_operation_id + AND v.target_namespace = m.target_namespace + AND v.canonical_tenant_id = m.canonical_tenant_id + AND v.canonical_version_id = m.canonical_version_id + AND v.local_tenant_key = m.local_tenant_key + AND f.capture_id = m.capture_id + AND f.version_identity_operation_id = v.operation_id + AND f.capture_status = 'CAPTURED_UNVERIFIED' + AND r.tenant_key = m.local_tenant_key + AND r.claim_kind = 'CANONICAL_AUTHORED_SOURCE' + AND ( + (actual_table = 'world_instance' + AND actual_new->>'canonical_game_instance_id' = m.canonical_game_instance_id::TEXT + AND actual_new->>'canonical_target_namespace' = m.target_namespace + AND actual_new->>'canonical_tenant_id' = m.canonical_tenant_id::TEXT + AND actual_new->>'tenant_id' = m.local_tenant_key::TEXT) + OR (actual_table IN ('region_instance', 'zone_instance', 'room_instance', 'room_instance_exit') + AND actual_new->>'tenant_id' = m.local_tenant_key::TEXT + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance wi + WHERE wi.canonical_game_instance_id = m.canonical_game_instance_id + AND wi.tenant_id = m.local_tenant_key + AND wi.game_instance_id = (actual_new->>'game_instance_id')::BIGINT + AND wi.canonical_target_namespace = m.target_namespace + AND wi.canonical_tenant_id = m.canonical_tenant_id)) + OR (actual_table IN ('world_canonical_instance_topology_identity', 'world_canonical_instance_preparation') + AND actual_new->>'canonical_game_instance_id' = m.canonical_game_instance_id::TEXT + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance wi + WHERE wi.id = (actual_new->>'world_instance_id')::BIGINT + AND wi.canonical_game_instance_id = m.canonical_game_instance_id + AND wi.tenant_id = m.local_tenant_key + AND wi.canonical_target_namespace = m.target_namespace + AND wi.canonical_tenant_id = m.canonical_tenant_id)) + ) + RETURNING m.row_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_consume_canonical_prepare_execution_manifest(TEXT, TEXT, JSONB, JSONB) + FROM PUBLIC; + +-- V24's reserved-source denial is preserved. Only V29's existing exact draft manifest and this +-- V35 exact insert manifest may consume a canonical tenant mutation; legacy tenants retain the +-- original numeric reservation behavior. +CREATE OR REPLACE FUNCTION world_claim_legacy_numeric_tenant_key() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + claimed_key BIGINT; + old_row JSONB; + new_row JSONB; + canonical_old BOOLEAN := FALSE; + canonical_new BOOLEAN := FALSE; +BEGIN + IF TG_OP <> 'INSERT' THEN + old_row := to_jsonb(OLD); + SELECT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = OLD.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_old; + END IF; + IF TG_OP <> 'DELETE' THEN + new_row := to_jsonb(NEW); + SELECT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation + WHERE tenant_key = NEW.tenant_id AND claim_kind = 'CANONICAL_AUTHORED_SOURCE') + INTO canonical_new; + END IF; + IF canonical_old OR canonical_new THEN + IF TG_TABLE_SCHEMA = '${serviceSchema}' + AND "${serviceSchema}".world_consume_region_execution_manifest( + TG_TABLE_NAME, TG_OP, old_row, new_row) THEN + RETURN NEW; + END IF; + IF TG_TABLE_SCHEMA = '${serviceSchema}' + AND "${serviceSchema}".world_consume_canonical_prepare_execution_manifest( + TG_TABLE_NAME, TG_OP, old_row, new_row) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION + 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + INSERT INTO "${serviceSchema}".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_validate_canonical_preparation_row() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed BOOLEAN; +BEGIN + IF TG_OP = 'INSERT' THEN + consumed := "${serviceSchema}".world_consume_canonical_prepare_execution_manifest( + TG_TABLE_NAME, TG_OP, NULL, to_jsonb(NEW)); + IF consumed THEN RETURN NEW; END IF; + RAISE EXCEPTION 'Canonical topology/preparation rows require the exact V35 owner operation' + USING ERRCODE = '23514'; + END IF; + RAISE EXCEPTION 'Canonical topology/preparation history is immutable' + USING ERRCODE = '55000'; +END; +$$; +CREATE TRIGGER trg_world_canonical_instance_topology_identity_exact_insert + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_instance_topology_identity + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_preparation_row(); +CREATE TRIGGER trg_world_canonical_instance_topology_identity_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_topology_identity + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_canonical_instance_preparation_exact_insert + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_instance_preparation + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_preparation_row(); +CREATE TRIGGER trg_world_canonical_instance_preparation_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_preparation + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +-- Exact insert-only materialization. Configured generation and spawn intent are rejected before +-- any sequence allocation or write. All parent and template selectors come from typed, exact +-- UUID-to-private-key mappings committed by V30; no numeric/UUID inference occurs here. +CREATE FUNCTION world_prepare_canonical_instance(p_input_json TEXT, p_input_digest TEXT) +RETURNS TABLE(world_instance_id BIGINT, private_game_instance_key BIGINT) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + p JSONB; + ident JSONB; + gs_request JSONB; + gs_evidence JSONB; + launch JSONB; + version_input JSONB; + topology JSONB; + source_input JSONB; + source_evidence_input JSONB; + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + binding_row "${serviceSchema}".world_complete_launch_binding%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + capture_row "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; + publication_owner "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + prior "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + world_row "${serviceSchema}".world_instance%ROWTYPE; + region_runtime "${serviceSchema}".region_instance%ROWTYPE; + zone_runtime "${serviceSchema}".zone_instance%ROWTYPE; + room_runtime "${serviceSchema}".room_instance%ROWTYPE; + exit_runtime "${serviceSchema}".room_instance_exit%ROWTYPE; + topology_identity "${serviceSchema}".world_canonical_instance_topology_identity%ROWTYPE; + preparation_row "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + source_region RECORD; + source_zone RECORD; + source_room RECORD; + source_exit RECORD; + parent_row RECORD; + other_row RECORD; + full_row JSONB; + template_count BIGINT; + region_count BIGINT; + zone_count BIGINT; + room_count BIGINT; + exit_count BIGINT; + generation_count BIGINT; + spawn_count BIGINT; + local_game_instance_key BIGINT; + runtime_id BIGINT; + runtime_uuid UUID; + new_world_instance_id BIGINT; + new_result_id BIGINT; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'Canonical preparation requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + IF p_input_json IS NULL OR length(p_input_json) = 0 OR p_input_digest IS NULL + OR p_input_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Canonical preparation input/digest is malformed' USING ERRCODE = '23514'; + END IF; + p := p_input_json::JSONB; + IF p->>'schemaVersion' IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Unsupported canonical preparation input schema' USING ERRCODE = '23514'; + END IF; + ident := p->'identity'; + gs_request := p->'gameSessionReadRequest'; + gs_evidence := p->'gameSessionReadEvidence'; + launch := p->'launchBinding'; + version_input := p->'versionIdentity'; + topology := p->'topology'; + source_input := p->'sourceIntake'; + source_evidence_input := source_input->'sourceEvidence'; + IF ident IS NULL OR gs_request IS NULL OR gs_evidence IS NULL + OR launch IS NULL OR version_input IS NULL OR topology IS NULL + OR source_input IS NULL OR jsonb_typeof(source_input) IS DISTINCT FROM 'object' + OR source_evidence_input IS NULL + OR jsonb_typeof(source_evidence_input) IS DISTINCT FROM 'object' + OR ident->>'publicProduction' IS DISTINCT FROM 'true' + OR ident->>'playableStateScope' IS DISTINCT FROM 'SHARED' + OR ident->>'canonicalGameInstanceId' IS DISTINCT FROM gs_request->>'canonicalGameInstanceId' + OR ident->>'canonicalGameInstanceId' IS DISTINCT FROM gs_evidence->>'canonicalGameInstanceId' + OR ident->>'targetNamespace' IS DISTINCT FROM gs_request->>'targetNamespace' + OR ident->>'canonicalTenantId' IS DISTINCT FROM gs_request->>'canonicalTenantId' + OR ident->>'worldSlug' IS DISTINCT FROM gs_request->>'worldSlug' + OR ident->>'controlPlaneRequestId' IS DISTINCT FROM gs_request->>'controlPlaneRequestId' + OR gs_request->>'launchDescriptorId' IS DISTINCT FROM gs_evidence->>'launchDescriptorId' + OR gs_request->>'expectedDescriptorRequestDigest' IS DISTINCT FROM gs_evidence->>'descriptorRequestDigest' + OR gs_request->>'expectedDescriptorResultDigest' IS DISTINCT FROM gs_evidence->>'descriptorResultDigest' + OR gs_request->>'expectedReleaseAttestationEvidenceDigest' + IS DISTINCT FROM gs_evidence->>'releaseAttestationEvidenceDigest' + OR ident->>'playableStateNamespaceId' IS DISTINCT FROM gs_evidence->>'playableStateNamespaceId' + OR ident->>'playableStateScope' IS DISTINCT FROM gs_evidence->>'playableStateScope' + OR ident->>'publicProduction' IS DISTINCT FROM gs_evidence->>'publicProduction' + OR ident->>'targetNamespace' IS DISTINCT FROM launch->>'targetNamespace' + OR ident->>'canonicalTenantId' IS DISTINCT FROM launch->>'canonicalTenantId' + OR ident->>'worldSlug' IS DISTINCT FROM launch->>'worldSlug' + OR ident->>'controlPlaneRequestId' IS DISTINCT FROM launch->>'controlPlaneRequestId' + OR ident->>'controlPlaneRequestId' IS DISTINCT FROM gs_request->>'controlPlaneRequestId' + OR topology->>'captureId' IS NULL + OR topology->>'planDigest' IS NULL + OR topology->>'planDigest' !~ '^sha256:[0-9a-f]{64}$' + OR jsonb_typeof(topology->'regionCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'zoneCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'roomCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'exitCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'generationRuleCount') IS DISTINCT FROM 'number' + OR jsonb_typeof(topology->'spawnBindingCount') IS DISTINCT FROM 'number' + OR (topology->>'regionCount')::BIGINT < 1 + OR (topology->>'zoneCount')::BIGINT < 0 + OR (topology->>'roomCount')::BIGINT < 0 + OR (topology->>'exitCount')::BIGINT < 0 + OR (topology->>'generationRuleCount')::BIGINT < 0 + OR (topology->>'spawnBindingCount')::BIGINT < 0 THEN + RAISE EXCEPTION 'Canonical preparation identity or exact Game Session echo differs' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT identity_row + FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id = (version_input->>'operationId')::UUID; + SELECT * INTO STRICT binding_row + FROM "${serviceSchema}".world_complete_launch_binding + WHERE binding_operation_id = (launch->>'operationId')::UUID; + SELECT * INTO STRICT intake_row + FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id = binding_row.intake_operation_id; + SELECT * INTO STRICT capture_row + FROM "${serviceSchema}".world_canonical_frozen_topology + WHERE capture_id = (topology->>'captureId')::UUID; + + IF identity_row.operation_id::TEXT IS DISTINCT FROM topology->>'versionIdentityOperationId' + OR identity_row.target_namespace IS DISTINCT FROM ident->>'targetNamespace' + OR identity_row.canonical_tenant_id::TEXT IS DISTINCT FROM ident->>'canonicalTenantId' + OR identity_row.world_slug IS DISTINCT FROM ident->>'worldSlug' + OR identity_row.canonical_version_id::TEXT IS DISTINCT FROM version_input->>'canonicalVersionId' + OR identity_row.canonical_version_id::TEXT IS DISTINCT FROM topology->>'canonicalVersionId' + OR identity_row.local_tenant_key IS DISTINCT FROM (launch->>'localTenantKey')::BIGINT + OR identity_row.local_version_key IS DISTINCT FROM (version_input->>'localVersionKey')::BIGINT + OR identity_row.game_design_version_id IS DISTINCT FROM (version_input->>'gameDesignVersionId')::BIGINT + OR identity_row.intake_operation_id IS DISTINCT FROM (launch->>'intakeOperationId')::UUID + OR identity_row.intake_request_id IS DISTINCT FROM (launch->>'intakeRequestId')::UUID + OR identity_row.source_operation_id IS DISTINCT FROM (launch->>'sourceOperationId')::UUID + OR identity_row.source_evidence_digest IS DISTINCT FROM launch->>'sourceEvidenceDigest' + OR identity_row.intake_request_digest IS DISTINCT FROM launch->>'intakeRequestDigest' + OR identity_row.intake_receipt_digest IS DISTINCT FROM launch->>'intakeReceiptDigest' + OR binding_row.target_namespace IS DISTINCT FROM ident->>'targetNamespace' + OR binding_row.canonical_tenant_id::TEXT IS DISTINCT FROM ident->>'canonicalTenantId' + OR binding_row.world_slug IS DISTINCT FROM ident->>'worldSlug' + OR binding_row.control_plane_request_id IS DISTINCT FROM ident->>'controlPlaneRequestId' + OR binding_row.descriptor_request_digest IS DISTINCT FROM gs_evidence->>'descriptorRequestDigest' + OR binding_row.descriptor_result_digest IS DISTINCT FROM gs_evidence->>'descriptorResultDigest' + OR binding_row.release_attestation_digest IS DISTINCT FROM gs_evidence->>'releaseAttestationEvidenceDigest' + OR binding_row.canonical_version_id::TEXT IS DISTINCT FROM version_input->>'canonicalVersionId' + OR binding_row.canonical_version_id::TEXT IS DISTINCT FROM launch->>'canonicalVersionId' + OR capture_row.request_id IS DISTINCT FROM (topology->>'requestId')::UUID + OR capture_row.commit_id IS DISTINCT FROM (topology->>'commitId')::UUID + OR capture_row.version_identity_operation_id IS DISTINCT FROM identity_row.operation_id + OR capture_row.binding_json IS DISTINCT FROM ( + SELECT binding_json FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id = capture_row.request_id) + OR capture_row.freeze_request_json::JSONB->>'publicationRequestId' + IS DISTINCT FROM topology->>'freezeRequestId' + OR capture_row.freeze_request_json::JSONB->>'publicationFence' + IS DISTINCT FROM topology->>'publicationFence' + OR capture_row.freeze_request_json::JSONB->>'requestDigest' + IS DISTINCT FROM topology->>'publicationRequestDigest' + OR capture_row.freeze_request_json::JSONB->>'appliedCommitId' + IS DISTINCT FROM topology->>'appliedCommitId' + OR capture_row.graph_sha256 !~ '^[0-9a-f]{64}$' + OR intake_row.source_provenance_kind <> 'NEW_GAME_ROW' + OR source_input->>'schemaVersion' IS DISTINCT FROM intake_row.schema_version::TEXT + OR source_input->>'targetNamespace' IS DISTINCT FROM intake_row.target_namespace + OR source_input->>'intakeRequestId' IS DISTINCT FROM intake_row.intake_request_id::TEXT + OR source_input->>'operationId' IS DISTINCT FROM intake_row.operation_id::TEXT + OR source_input->>'canonicalTenantId' IS DISTINCT FROM intake_row.canonical_tenant_id::TEXT + OR source_input->>'worldSlug' IS DISTINCT FROM intake_row.world_slug + OR source_input->>'sourceOperationId' IS DISTINCT FROM intake_row.source_operation_id::TEXT + OR source_input->>'sourceEvidenceDigest' IS DISTINCT FROM intake_row.source_evidence_digest + OR source_input->>'requestDigest' IS DISTINCT FROM intake_row.request_digest + OR source_input->>'receiptDigest' IS DISTINCT FROM intake_row.receipt_digest + OR source_input->>'localTenantKey' IS DISTINCT FROM intake_row.local_tenant_key::TEXT + OR source_evidence_input->>'schemaVersion' IS DISTINCT FROM intake_row.source_schema_version::TEXT + OR source_evidence_input->>'registrationRequestId' IS DISTINCT FROM intake_row.source_registration_request_id::TEXT + OR source_evidence_input->>'sourceOperationId' IS DISTINCT FROM intake_row.source_operation_id::TEXT + OR source_evidence_input->>'requestDigest' IS DISTINCT FROM intake_row.source_request_digest + OR source_evidence_input->>'canonicalTenantId' IS DISTINCT FROM intake_row.canonical_tenant_id::TEXT + OR source_evidence_input->>'tenantSlug' IS DISTINCT FROM intake_row.tenant_slug + OR source_evidence_input->>'worldSlug' IS DISTINCT FROM intake_row.world_slug + OR source_evidence_input->>'worldDisplayName' IS DISTINCT FROM intake_row.world_display_name + OR source_evidence_input->>'sourceGameRowId' IS DISTINCT FROM intake_row.source_game_row_id::TEXT + OR source_evidence_input->>'sourceGameTenantKey' IS DISTINCT FROM intake_row.source_game_tenant_key + OR source_evidence_input->>'provenanceKind' IS DISTINCT FROM intake_row.source_provenance_kind + OR source_evidence_input->>'evidenceDigest' IS DISTINCT FROM intake_row.source_evidence_digest + OR capture_row.graph_bytes IS NULL OR octet_length(capture_row.graph_bytes) = 0 + OR capture_row.graph_sha256 IS NULL OR capture_row.graph_sha256 !~ '^[0-9a-f]{64}$' + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_source_tenant_key_reservation r + WHERE r.tenant_key = identity_row.local_tenant_key + AND r.claim_kind = 'CANONICAL_AUTHORED_SOURCE') THEN + RAISE EXCEPTION 'Canonical preparation differs from exact V26/V27 source, version, or frozen capture' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*) FILTER (WHERE family = 'REGION'), + count(*) FILTER (WHERE family = 'ZONE'), + count(*) FILTER (WHERE family = 'ROOM'), + count(*) FILTER (WHERE family = 'ROOM_EXIT'), + count(*) FILTER (WHERE family = 'GENERATION_RULE'), + count(*) FILTER (WHERE family = 'WORLD_ENTITY_SPAWN_BINDING'), + count(*) + INTO region_count, zone_count, room_count, exit_count, generation_count, spawn_count, template_count + FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = capture_row.request_id AND commit_id = capture_row.commit_id + AND version_identity_operation_id = identity_row.operation_id; + + -- Required intent is a hard pre-allocation rejection; there is no skip/default path. + IF generation_count <> 0 OR spawn_count <> 0 + OR generation_count <> (topology->>'generationRuleCount')::BIGINT + OR spawn_count <> (topology->>'spawnBindingCount')::BIGINT THEN + RAISE EXCEPTION 'Canonical generation-free preparation rejects configured generation/spawn intent' + USING ERRCODE = '23514'; + END IF; + IF region_count <> (topology->>'regionCount')::BIGINT + OR zone_count <> (topology->>'zoneCount')::BIGINT + OR room_count <> (topology->>'roomCount')::BIGINT + OR exit_count <> (topology->>'exitCount')::BIGINT + OR template_count <> region_count + zone_count + room_count + exit_count + OR region_count = 0 THEN + RAISE EXCEPTION 'Canonical preparation plan omits or adds a selected frozen graph row' + USING ERRCODE = '23514'; + END IF; + + -- The capture's V25 version owner is the serialization fence shared with every V29 writer. + -- Hold it through this transaction: a writer that began first completes before this row can be + -- locked (and its phase is then rechecked); a later writer cannot acquire its required UPDATE + -- lock until this exact immutable source graph has been materialized and committed. + SELECT * INTO STRICT publication_owner + FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE local_tenant_key = identity_row.local_tenant_key + AND version_id = identity_row.local_version_key + FOR SHARE; + IF publication_owner.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR publication_owner.current_publication_fence IS DISTINCT FROM capture_row.publication_fence THEN + RAISE EXCEPTION 'Canonical preparation requires the exact still-FROZEN V25 source owner' + USING ERRCODE = '23514'; + END IF; + + -- Serialize exact canonical-id and request retries before checking prior identity or allocating + -- any private key/row identifier. These locks are entered only after the external verifier ran. + PERFORM pg_advisory_xact_lock(hashtextextended( + 'canonical-game-instance:' || (ident->>'canonicalGameInstanceId'), 0)); + PERFORM pg_advisory_xact_lock(hashtextextended( + 'canonical-prepare-request:' || (ident->>'targetNamespace') || ':' + || (ident->>'canonicalTenantId') || ':' || (ident->>'controlPlaneRequestId'), 0)); + + SELECT * INTO prior FROM "${serviceSchema}".world_canonical_instance_preparation + WHERE canonical_game_instance_id = (ident->>'canonicalGameInstanceId')::UUID FOR UPDATE; + IF FOUND THEN + IF prior.input_json IS DISTINCT FROM p_input_json + OR prior.input_digest IS DISTINCT FROM p_input_digest + OR prior.capture_id IS DISTINCT FROM capture_row.capture_id + OR prior.graph_bytes IS DISTINCT FROM capture_row.graph_bytes + OR prior.graph_sha256 IS DISTINCT FROM capture_row.graph_sha256 THEN + RAISE EXCEPTION 'Canonical gameInstanceId is already bound to a different preparation' + USING ERRCODE = '23505'; + END IF; + world_instance_id := prior.world_instance_id; + private_game_instance_key := prior.private_game_instance_key; + RETURN NEXT; + RETURN; + END IF; + IF EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation + WHERE target_namespace = ident->>'targetNamespace' + AND canonical_tenant_id = (ident->>'canonicalTenantId')::UUID + AND control_plane_request_id = ident->>'controlPlaneRequestId') + OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance + WHERE canonical_game_instance_id = (ident->>'canonicalGameInstanceId')::UUID) + OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance + WHERE tenant_id = identity_row.local_tenant_key + AND control_plane_request_id = ident->>'controlPlaneRequestId') THEN + RAISE EXCEPTION 'Canonical game instance or request identity is already reserved' + USING ERRCODE = '23505'; + END IF; + + LOOP + local_game_instance_key := nextval('"${serviceSchema}".world_canonical_private_game_instance_key_seq'); + EXIT WHEN NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_instance + WHERE tenant_id = identity_row.local_tenant_key + AND game_instance_id = local_game_instance_key); + END LOOP; + new_world_instance_id := nextval('"${serviceSchema}".world_instance_id_seq'); + world_row := jsonb_populate_record(NULL::"${serviceSchema}".world_instance, + jsonb_build_object( + 'id', new_world_instance_id, + 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, + 'game_template_id', (binding_row.descriptor_json::JSONB->>'gameTemplateId')::BIGINT, + 'control_plane_request_id', ident->>'controlPlaneRequestId', + 'launch_descriptor_id', binding_row.descriptor_json::JSONB->>'launchDescriptorId', + 'version_id', identity_row.local_version_key, + 'script_patch_version', CASE WHEN binding_row.descriptor_json::JSONB->>'scriptPatchVersionPresent' = 'true' + THEN binding_row.descriptor_json::JSONB->>'scriptPatchVersion' ELSE NULL END, + 'runtime_flags_json', binding_row.descriptor_json::JSONB->>'runtimeFlagsJson', + 'generation_config_revision', binding_row.descriptor_json::JSONB->>'generationConfigRevision', + 'release_bundle_id', (binding_row.descriptor_json::JSONB->>'releaseBundleId')::BIGINT, + 'published_release_bundle_ref', binding_row.descriptor_json::JSONB->>'publishedReleaseBundleRef', + 'version_state_epoch', (binding_row.descriptor_json::JSONB->>'versionStateEpoch')::BIGINT, + 'lifecycle_epoch', 1, + 'status', 'PREPARING', + 'failure_reason', NULL, + 'created_at', CURRENT_TIMESTAMP::TIMESTAMP, + 'updated_at', CURRENT_TIMESTAMP::TIMESTAMP, + 'row_version', 0, + 'termination_request_id', NULL, + 'terminated_at', NULL, + 'remap_set_id', CASE WHEN binding_row.descriptor_json::JSONB->>'remapSetIdPresent' = 'true' + THEN binding_row.descriptor_json::JSONB->>'remapSetId' ELSE NULL END, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'canonical_target_namespace', ident->>'targetNamespace', + 'canonical_tenant_id', (ident->>'canonicalTenantId')::UUID, + 'canonical_world_slug', ident->>'worldSlug', + 'playable_state_namespace_id', (ident->>'playableStateNamespaceId')::UUID, + 'playable_state_scope', 'SHARED', + 'public_production', TRUE, + 'playtest_lifecycle_id', NULL, + 'playtest_state_generation', NULL, + 'canonical_launch_binding_operation_id', binding_row.binding_operation_id)); + full_row := to_jsonb(world_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_instance', new_world_instance_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_instance, full_row)).*; + + FOR source_region IN + SELECT m.template_id, m.private_row_key, r.shard_id, r.name, r.weather, + r.generation_seed, r.generator_type, r.generator_params, r.spacing_multiplier + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".region r ON r.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'REGION' + AND r.tenant_id = identity_row.local_tenant_key AND r.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + runtime_id := nextval('"${serviceSchema}".region_instance_id_seq'); + runtime_uuid := gen_random_uuid(); + region_runtime := jsonb_populate_record(NULL::"${serviceSchema}".region_instance, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, 'world_instance_id', new_world_instance_id, + 'shard_id', source_region.shard_id, 'name', source_region.name, + 'weather', source_region.weather, 'generation_seed', source_region.generation_seed, + 'generator_type', source_region.generator_type, + 'generator_params', source_region.generator_params, + 'spacing_multiplier', source_region.spacing_multiplier, 'version', 0, + 'canonical_region_instance_id', runtime_uuid)); + full_row := to_jsonb(region_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'region_instance', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".region_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".region_instance, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'REGION', 'template_id', source_region.template_id, + 'template_private_row_key', source_region.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', runtime_uuid, + 'runtime_room_instance_id', NULL)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + FOR source_zone IN + SELECT m.template_id, m.private_row_key, z.region_id, z.name + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".zone z ON z.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'ZONE' + AND z.tenant_id = identity_row.local_tenant_key AND z.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + SELECT ti.runtime_row_id INTO STRICT parent_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'REGION' + AND ti.template_private_row_key = source_zone.region_id; + runtime_id := nextval('"${serviceSchema}".zone_instance_id_seq'); + runtime_uuid := gen_random_uuid(); + zone_runtime := jsonb_populate_record(NULL::"${serviceSchema}".zone_instance, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, 'zone_instance_id', runtime_id, + 'template_zone_id', source_zone.private_row_key, + 'region_instance_id', parent_row.runtime_row_id, + 'name', source_zone.name, 'version', 0, + 'canonical_zone_instance_id', runtime_uuid)); + full_row := to_jsonb(zone_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'zone_instance', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".zone_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".zone_instance, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'ZONE', 'template_id', source_zone.template_id, + 'template_private_row_key', source_zone.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', runtime_uuid, + 'runtime_room_instance_id', NULL)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + FOR source_room IN + SELECT m.template_id, m.private_row_key, r.zone_id, r.name, r.description, + r.name_localized_variants_json, r.description_localized_variants_json + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'ROOM' + AND r.tenant_id = identity_row.local_tenant_key AND r.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + SELECT ti.runtime_row_id INTO STRICT parent_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'ZONE' + AND ti.template_private_row_key = source_room.zone_id; + SELECT ti.runtime_row_id INTO STRICT other_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + JOIN "${serviceSchema}".zone z ON z.id = source_room.zone_id + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'REGION' + AND ti.template_private_row_key = z.region_id; + runtime_id := nextval('"${serviceSchema}".room_instance_id_seq'); + room_runtime := jsonb_populate_record(NULL::"${serviceSchema}".room_instance, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, 'room_instance_row_id', runtime_id, + 'template_room_id', source_room.private_row_key, + 'region_instance_id', other_row.runtime_row_id, + 'zone_instance_id', parent_row.runtime_row_id, + 'name', source_room.name, 'description', source_room.description, + 'name_localized_variants_json', source_room.name_localized_variants_json, + 'description_localized_variants_json', source_room.description_localized_variants_json, + 'version', 0)); + full_row := to_jsonb(room_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'room_instance', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".room_instance SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".room_instance, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'ROOM', 'template_id', source_room.template_id, + 'template_private_row_key', source_room.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', NULL, + 'runtime_room_instance_id', runtime_id)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + FOR source_exit IN + SELECT m.template_id, m.private_row_key, e.from_room_id, e.to_room_id, e.direction, e.cost + FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room_exit e ON e.id = m.private_row_key + WHERE m.request_id = capture_row.request_id AND m.commit_id = capture_row.commit_id + AND m.version_identity_operation_id = identity_row.operation_id AND m.family = 'ROOM_EXIT' + AND e.tenant_id = identity_row.local_tenant_key AND e.version_id = identity_row.local_version_key + ORDER BY m.template_id + LOOP + SELECT ti.runtime_room_instance_id INTO STRICT parent_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'ROOM' + AND ti.template_private_row_key = source_exit.from_room_id; + SELECT ti.runtime_room_instance_id INTO STRICT other_row + FROM "${serviceSchema}".world_canonical_instance_topology_identity ti + WHERE ti.world_instance_id = new_world_instance_id AND ti.family = 'ROOM' + AND ti.template_private_row_key = source_exit.to_room_id; + runtime_id := nextval('"${serviceSchema}".room_instance_exit_id_seq'); + exit_runtime := jsonb_populate_record(NULL::"${serviceSchema}".room_instance_exit, + jsonb_build_object( + 'id', runtime_id, 'tenant_id', identity_row.local_tenant_key, + 'game_instance_id', local_game_instance_key, + 'from_room_instance_record_id', parent_row.runtime_room_instance_id, + 'to_room_instance_record_id', other_row.runtime_room_instance_id, + 'direction', source_exit.direction, 'cost', source_exit.cost, 'version', 0)); + full_row := to_jsonb(exit_runtime); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'room_instance_exit', runtime_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".room_instance_exit SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".room_instance_exit, full_row)).*; + + topology_identity := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_topology_identity, + jsonb_build_object('id', nextval('"${serviceSchema}".world_canonical_instance_topology_identity_id_seq'), + 'world_instance_id', new_world_instance_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'family', 'ROOM_EXIT', 'template_id', source_exit.template_id, + 'template_private_row_key', source_exit.private_row_key, + 'runtime_row_id', runtime_id, 'runtime_identity', NULL, + 'runtime_room_instance_id', NULL)); + full_row := to_jsonb(topology_identity); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_topology_identity', topology_identity.id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_topology_identity SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_topology_identity, full_row)).*; + END LOOP; + + IF (SELECT count(*) FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest + WHERE transaction_id = txid_current()) <> 0 THEN + RAISE EXCEPTION 'Canonical preparation left an unconsumed exact execution manifest' + USING ERRCODE = '23514'; + END IF; + + new_result_id := nextval('"${serviceSchema}".world_canonical_instance_preparation_id_seq'); + preparation_row := jsonb_populate_record(NULL::"${serviceSchema}".world_canonical_instance_preparation, + jsonb_build_object( + 'id', new_result_id, + 'canonical_game_instance_id', (ident->>'canonicalGameInstanceId')::UUID, + 'target_namespace', ident->>'targetNamespace', + 'canonical_tenant_id', (ident->>'canonicalTenantId')::UUID, + 'world_slug', ident->>'worldSlug', + 'control_plane_request_id', ident->>'controlPlaneRequestId', + 'canonical_version_id', identity_row.canonical_version_id, + 'version_identity_operation_id', identity_row.operation_id, + 'capture_id', capture_row.capture_id, + 'graph_bytes', capture_row.graph_bytes, + 'graph_sha256', capture_row.graph_sha256, + 'input_digest', p_input_digest, + 'input_json', p_input_json, + 'world_instance_id', new_world_instance_id, + 'private_game_instance_key', local_game_instance_key, + 'region_count', region_count, + 'zone_count', zone_count, + 'room_count', room_count, + 'exit_count', exit_count, + 'storage_status', 'MATERIALIZED_UNVERIFIED', + 'prepared_at', CURRENT_TIMESTAMP)); + full_row := to_jsonb(preparation_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation_execution_manifest VALUES ( + txid_current(), 'world_canonical_instance_preparation', new_result_id, + (ident->>'canonicalGameInstanceId')::UUID, ident->>'targetNamespace', + (ident->>'canonicalTenantId')::UUID, identity_row.canonical_version_id, + identity_row.operation_id, capture_row.capture_id, identity_row.local_tenant_key, + p_input_digest, full_row); + INSERT INTO "${serviceSchema}".world_canonical_instance_preparation SELECT (jsonb_populate_record( + NULL::"${serviceSchema}".world_canonical_instance_preparation, full_row)).*; + + IF (SELECT count(*) FROM "${serviceSchema}".world_canonical_instance_preparation_execution_manifest + WHERE transaction_id = txid_current()) <> 0 THEN + RAISE EXCEPTION 'Canonical preparation left an unconsumed result manifest' + USING ERRCODE = '23514'; + END IF; + world_instance_id := new_world_instance_id; + private_game_instance_key := local_game_instance_key; + RETURN NEXT; +END; +$$; +REVOKE ALL ON FUNCTION world_prepare_canonical_instance(TEXT, TEXT) FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V36__world_draft_terminal_outcomes.sql b/services/world-management-service/src/main/resources/db/migration/V36__world_draft_terminal_outcomes.sql new file mode 100644 index 0000000000..cab3365494 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V36__world_draft_terminal_outcomes.sql @@ -0,0 +1,237 @@ +-- A definitive no-commit result is an immutable, owner-local tombstone. It is not permission, +-- an APPLIED result, or evidence that Account's authorization fence may be released. +CREATE TABLE world_draft_terminal_outcome ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + commit_id UUID NOT NULL UNIQUE, + authorization_fence_id UUID NOT NULL UNIQUE, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + version_identity_operation_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL CHECK (local_tenant_key > 0), + local_version_key BIGINT NOT NULL CHECK (local_version_key > 0), + owner_binding_json TEXT NOT NULL, + binding_json TEXT NOT NULL, + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + account_binding_bytes BYTEA NOT NULL CHECK (octet_length(account_binding_bytes) > 0), + account_binding_digest VARCHAR(71) NOT NULL CHECK (account_binding_digest ~ '^sha256:[0-9a-f]{64}$'), + affected_units_json JSONB NOT NULL CHECK (jsonb_typeof(affected_units_json) = 'array'), + outcome VARCHAR(32) NOT NULL CHECK (outcome = 'DEFINITIVELY_ABORTED'), + outcome_bytes BYTEA NOT NULL CHECK (octet_length(outcome_bytes) > 0), + outcome_digest VARCHAR(71) NOT NULL CHECK (outcome_digest ~ '^sha256:[0-9a-f]{64}$'), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT ck_world_draft_terminal_non_nil CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authorization_fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_draft_terminal_scope CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT fk_world_draft_terminal_version_identity FOREIGN KEY ( + version_identity_operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + local_version_key + ) REFERENCES world_authored_version_identity ( + operation_id, + target_namespace, + canonical_tenant_id, + canonical_version_id, + local_version_key + ) +); +CREATE INDEX idx_world_draft_terminal_scope + ON world_draft_terminal_outcome (target_namespace, canonical_tenant_id, canonical_version_id); + +-- [jooq ignore start] +-- Preserve the PostgreSQL binding constraint; jOOQ's H2 DDL simulation cannot render ->>. +ALTER TABLE world_draft_terminal_outcome ADD CONSTRAINT ck_world_draft_terminal_binding CHECK ( + jsonb_typeof(binding_json::jsonb) = 'object' + AND binding_json::jsonb->>'canonicalTenantId' = canonical_tenant_id::TEXT + AND binding_json::jsonb->>'canonicalVersionId' = canonical_version_id::TEXT + AND binding_json::jsonb->>'requestId' = request_id::TEXT + AND binding_json::jsonb->>'commitId' = commit_id::TEXT + AND jsonb_typeof(owner_binding_json::jsonb) = 'object' + AND owner_binding_json::jsonb->>'targetNamespace' = target_namespace + AND owner_binding_json::jsonb->>'canonicalTenantId' = canonical_tenant_id::TEXT + AND owner_binding_json::jsonb->>'canonicalVersionId' = canonical_version_id::TEXT + AND owner_binding_json::jsonb->>'versionIdentityOperationId' = version_identity_operation_id::TEXT +); +REVOKE ALL ON world_draft_terminal_outcome FROM PUBLIC; + +CREATE FUNCTION world_draft_terminal_outcome_guard() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + unit JSONB; + aggregate_key BIGINT; + observed_epoch BIGINT; + expected_epoch BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World Draft terminal outcomes are immutable and retained' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND local_tenant_key = NEW.local_tenant_key + AND version_id = NEW.local_version_key + FOR UPDATE; + IF NOT FOUND OR owner_row.owner_freeze_phase <> 'OPEN' + OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'First World Draft abort requires the exact OPEN V25 owner row' + USING ERRCODE = '23514'; + END IF; + + IF EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_region_draft_commit c + WHERE c.request_id = NEW.request_id OR c.commit_id = NEW.commit_id + ) OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_topology_draft_commit c + WHERE c.request_id = NEW.request_id OR c.commit_id = NEW.commit_id + ) OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity i + WHERE i.target_namespace = NEW.target_namespace + AND i.canonical_tenant_id = NEW.canonical_tenant_id + AND i.canonical_version_id = NEW.canonical_version_id + AND (i.request_id = NEW.request_id OR i.commit_id = NEW.commit_id) + ) OR EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_design_revision_ledger r + WHERE r.tenant_id = NEW.local_tenant_key + AND r.version_id = NEW.local_version_key + AND r.commit_id = NEW.commit_id::TEXT + ) THEN + RAISE EXCEPTION 'Retained World application history cannot be terminalized as no-commit' + USING ERRCODE = '23514'; + END IF; + + FOR unit IN SELECT value FROM jsonb_array_elements(NEW.affected_units_json) LOOP + IF unit->>'owner' <> 'WORLD_MANAGEMENT' THEN + RAISE EXCEPTION 'World terminal affected-unit vector contains a foreign owner' + USING ERRCODE = '23514'; + END IF; + expected_epoch := (unit->>'expectedEpoch')::BIGINT; + IF unit->>'scopeType' = 'AGGREGATE' THEN + IF unit->>'aggregateId' ~ '^[1-9][0-9]*$' THEN + aggregate_key := (unit->>'aggregateId')::BIGINT; + ELSE + SELECT private_row_key INTO aggregate_key + FROM "${serviceSchema}".world_authored_topology_identity + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND family = unit->>'aggregateType' + AND template_id = (unit->>'aggregateId')::UUID; + IF NOT FOUND AND expected_epoch <> 0 THEN + RAISE EXCEPTION 'World topology mapping is absent for a nonzero expected epoch' + USING ERRCODE = '23514'; + END IF; + END IF; + observed_epoch := 0; + IF aggregate_key IS NOT NULL THEN + SELECT draft_revision_epoch INTO observed_epoch + FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = NEW.local_tenant_key + AND version_id = NEW.local_version_key + AND aggregate_type = unit->>'aggregateType' + AND aggregate_id = aggregate_key; + IF NOT FOUND THEN observed_epoch := 0; END IF; + END IF; + IF observed_epoch IS DISTINCT FROM expected_epoch THEN + RAISE EXCEPTION 'Affected World aggregate advanced before definitive abort' + USING ERRCODE = '23514'; + END IF; + ELSE + observed_epoch := 0; + SELECT draft_scope_revision_epoch INTO observed_epoch + FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = NEW.local_tenant_key + AND version_id = NEW.local_version_key + AND scope_type = unit->>'scopeType' + AND scope_id = unit->>'scopeId'; + IF NOT FOUND THEN observed_epoch := 0; END IF; + IF observed_epoch IS DISTINCT FROM expected_epoch THEN + RAISE EXCEPTION 'Affected World scope advanced before definitive abort' + USING ERRCODE = '23514'; + END IF; + END IF; + aggregate_key := NULL; + END LOOP; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_draft_terminal_outcome_guard + BEFORE INSERT OR UPDATE OR DELETE ON world_draft_terminal_outcome + FOR EACH ROW EXECUTE FUNCTION world_draft_terminal_outcome_guard(); +CREATE TRIGGER trg_world_draft_terminal_outcome_no_truncate + BEFORE TRUNCATE ON world_draft_terminal_outcome + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); + +CREATE FUNCTION world_reject_aborted_draft_attempt() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + request_identity UUID; + commit_identity UUID; + target_tenant UUID; + target_version UUID; + target_namespace TEXT; +BEGIN + IF TG_TABLE_NAME = 'world_region_draft_execution_manifest' THEN + request_identity := (NEW.complete_binding->>'requestId')::UUID; + commit_identity := (NEW.complete_binding->>'commitId')::UUID; + target_tenant := (NEW.complete_binding->>'canonicalTenantId')::UUID; + target_version := (NEW.complete_binding->>'canonicalVersionId')::UUID; + target_namespace := NEW.owner_binding->>'targetNamespace'; + ELSE + request_identity := NEW.request_id; + commit_identity := NEW.commit_id; + target_tenant := NEW.canonical_tenant_id; + target_version := NEW.canonical_version_id; + target_namespace := NEW.target_namespace; + END IF; + IF EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_draft_terminal_outcome terminal + WHERE terminal.target_namespace = target_namespace + AND terminal.canonical_tenant_id = target_tenant + AND terminal.canonical_version_id = target_version + AND (terminal.request_id = request_identity OR terminal.commit_id = commit_identity) + ) THEN + RAISE EXCEPTION 'World Draft operation has immutable definitive no-commit evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +-- The guarded writers first lock the same V25 owner row. The region function creates this +-- manifest before any content or epoch change; topology identity insertion is also protected +-- by its existing deferred history FK. These gates exclude a delayed raw SQL call as well as +-- repository retries after an ABORTED result. +CREATE TRIGGER trg_world_region_manifest_aborted_attempt + BEFORE INSERT ON world_region_draft_execution_manifest + FOR EACH ROW EXECUTE FUNCTION world_reject_aborted_draft_attempt(); +CREATE TRIGGER trg_world_region_commit_aborted_attempt + BEFORE INSERT ON world_region_draft_commit + FOR EACH ROW EXECUTE FUNCTION world_reject_aborted_draft_attempt(); +CREATE TRIGGER trg_world_topology_identity_aborted_attempt + BEFORE INSERT ON world_authored_topology_identity + FOR EACH ROW EXECUTE FUNCTION world_reject_aborted_draft_attempt(); +CREATE TRIGGER trg_world_topology_commit_aborted_attempt + BEFORE INSERT ON world_topology_draft_commit + FOR EACH ROW EXECUTE FUNCTION world_reject_aborted_draft_attempt(); + +REVOKE ALL ON FUNCTION world_draft_terminal_outcome_guard() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_reject_aborted_draft_attempt() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V37__world_draft_terminal_guard_namespace.sql b/services/world-management-service/src/main/resources/db/migration/V37__world_draft_terminal_guard_namespace.sql new file mode 100644 index 0000000000..eae4613a1d --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V37__world_draft_terminal_guard_namespace.sql @@ -0,0 +1,43 @@ +-- V36's terminal guard remains installed for retained rows and trigger bindings. Replace only its +-- trigger function body so the PL/pgSQL variable cannot collide with the terminal table column. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_reject_aborted_draft_attempt() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + v_request_identity UUID; + v_commit_identity UUID; + v_target_tenant UUID; + v_target_version UUID; + v_target_namespace TEXT; +BEGIN + IF TG_TABLE_NAME = 'world_region_draft_execution_manifest' THEN + v_request_identity := (NEW.complete_binding->>'requestId')::UUID; + v_commit_identity := (NEW.complete_binding->>'commitId')::UUID; + v_target_tenant := (NEW.complete_binding->>'canonicalTenantId')::UUID; + v_target_version := (NEW.complete_binding->>'canonicalVersionId')::UUID; + v_target_namespace := NEW.owner_binding->>'targetNamespace'; + ELSE + v_request_identity := NEW.request_id; + v_commit_identity := NEW.commit_id; + v_target_tenant := NEW.canonical_tenant_id; + v_target_version := NEW.canonical_version_id; + v_target_namespace := NEW.target_namespace; + END IF; + IF EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_draft_terminal_outcome terminal + WHERE terminal.target_namespace = v_target_namespace + AND terminal.canonical_tenant_id = v_target_tenant + AND terminal.canonical_version_id = v_target_version + AND (terminal.request_id = v_request_identity + OR terminal.commit_id = v_commit_identity) + ) THEN + RAISE EXCEPTION 'World Draft operation has immutable definitive no-commit evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +REVOKE ALL ON FUNCTION world_reject_aborted_draft_attempt() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V39__world_account_bound_graph_application.sql b/services/world-management-service/src/main/resources/db/migration/V39__world_account_bound_graph_application.sql new file mode 100644 index 0000000000..4a9fb8de4b --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V39__world_account_bound_graph_application.sql @@ -0,0 +1,216 @@ +-- Preserve all V30 histories and bytes. A past unverified row has no application transaction. +ALTER TABLE world_topology_draft_commit ADD COLUMN application_transaction_id BIGINT; + +CREATE TABLE world_draft_graph_application ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + commit_id UUID NOT NULL UNIQUE, + authorization_fence_id UUID NOT NULL UNIQUE, + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + account_binding_bytes BYTEA NOT NULL CHECK (octet_length(account_binding_bytes) > 0), + account_binding_digest VARCHAR(71) NOT NULL CHECK (account_binding_digest ~ '^sha256:[0-9a-f]{64}$'), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + result_digest VARCHAR(71) NOT NULL CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'), + application_transaction_id BIGINT NOT NULL, + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (request_id) REFERENCES world_topology_draft_commit(request_id), + FOREIGN KEY (commit_id) REFERENCES world_topology_draft_commit(commit_id), + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authorization_fence_id <> '00000000-0000-0000-0000-000000000000'::UUID) +); + +-- One immutable identity namespace across positive and no-commit outcomes, including altered +-- target bindings that would otherwise lock different V25 rows. Retained abort bytes are copied +-- exactly; old permission-unverified graphs never receive a positive terminal identity. +CREATE TABLE world_draft_graph_terminal_identity ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + commit_id UUID NOT NULL UNIQUE, + authorization_fence_id UUID NOT NULL UNIQUE, + account_binding_bytes BYTEA NOT NULL, + account_binding_digest VARCHAR(71) NOT NULL, + outcome VARCHAR(32) NOT NULL CHECK (outcome IN ('APPLIED', 'DEFINITIVELY_ABORTED')) +); +INSERT INTO world_draft_graph_terminal_identity + (operation_id,request_id,commit_id,authorization_fence_id,account_binding_bytes,account_binding_digest,outcome) + SELECT operation_id,request_id,commit_id,authorization_fence_id,account_binding_bytes,account_binding_digest,outcome + FROM world_draft_terminal_outcome; + +-- [jooq ignore start] +CREATE FUNCTION world_claim_graph_terminal_identity() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + retained "${serviceSchema}".world_draft_graph_terminal_identity%ROWTYPE; + expected_outcome TEXT; + identity_count BIGINT; +BEGIN + expected_outcome := CASE TG_TABLE_NAME WHEN 'world_draft_graph_application' + THEN 'APPLIED' ELSE 'DEFINITIVELY_ABORTED' END; + INSERT INTO "${serviceSchema}".world_draft_graph_terminal_identity + (operation_id,request_id,commit_id,authorization_fence_id,account_binding_bytes,account_binding_digest,outcome) + VALUES (NEW.operation_id,NEW.request_id,NEW.commit_id,NEW.authorization_fence_id, + NEW.account_binding_bytes,NEW.account_binding_digest,expected_outcome) + ON CONFLICT DO NOTHING; + SELECT count(*) INTO identity_count FROM "${serviceSchema}".world_draft_graph_terminal_identity i + WHERE i.operation_id=NEW.operation_id OR i.request_id=NEW.request_id OR i.commit_id=NEW.commit_id + OR i.authorization_fence_id=NEW.authorization_fence_id; + IF identity_count <> 1 THEN + RAISE EXCEPTION 'World terminal identities select conflicting retained original operations' USING ERRCODE='23514'; + END IF; + SELECT * INTO STRICT retained FROM "${serviceSchema}".world_draft_graph_terminal_identity i + WHERE i.operation_id=NEW.operation_id OR i.request_id=NEW.request_id OR i.commit_id=NEW.commit_id + OR i.authorization_fence_id=NEW.authorization_fence_id FOR UPDATE; + IF retained.operation_id IS DISTINCT FROM NEW.operation_id + OR retained.request_id IS DISTINCT FROM NEW.request_id + OR retained.commit_id IS DISTINCT FROM NEW.commit_id + OR retained.authorization_fence_id IS DISTINCT FROM NEW.authorization_fence_id + OR retained.account_binding_bytes IS DISTINCT FROM NEW.account_binding_bytes + OR retained.account_binding_digest IS DISTINCT FROM NEW.account_binding_digest + OR retained.outcome IS DISTINCT FROM expected_outcome THEN + RAISE EXCEPTION 'World original terminal identity cannot be reused or relabeled' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE FUNCTION world_verify_graph_terminal_identity_receipt() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF NEW.outcome = 'APPLIED' THEN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_graph_application a + WHERE a.operation_id=NEW.operation_id AND a.request_id=NEW.request_id AND a.commit_id=NEW.commit_id + AND a.authorization_fence_id=NEW.authorization_fence_id + AND a.account_binding_bytes=NEW.account_binding_bytes AND a.account_binding_digest=NEW.account_binding_digest) THEN + RETURN NEW; + END IF; + ELSE + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_terminal_outcome a + WHERE a.operation_id=NEW.operation_id AND a.request_id=NEW.request_id AND a.commit_id=NEW.commit_id + AND a.authorization_fence_id=NEW.authorization_fence_id + AND a.account_binding_bytes=NEW.account_binding_bytes AND a.account_binding_digest=NEW.account_binding_digest) THEN + RETURN NEW; + END IF; + END IF; + RAISE EXCEPTION 'World terminal identity lacks its exact immutable owner receipt' USING ERRCODE='23514'; +END; +$$; +CREATE TRIGGER trg_world_terminal_identity_immutable BEFORE UPDATE OR DELETE + ON world_draft_graph_terminal_identity FOR EACH ROW EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE TRIGGER trg_world_terminal_identity_no_truncate BEFORE TRUNCATE + ON world_draft_graph_terminal_identity FOR EACH STATEMENT EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE CONSTRAINT TRIGGER trg_world_terminal_identity_receipt AFTER INSERT ON world_draft_graph_terminal_identity + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION world_verify_graph_terminal_identity_receipt(); +CREATE TRIGGER trg_world_graph_terminal_identity_claim BEFORE INSERT + ON world_draft_graph_application FOR EACH ROW EXECUTE FUNCTION world_claim_graph_terminal_identity(); +CREATE TRIGGER trg_world_abort_terminal_identity_claim BEFORE INSERT + ON world_draft_terminal_outcome FOR EACH ROW EXECUTE FUNCTION world_claim_graph_terminal_identity(); + +CREATE FUNCTION world_stamp_topology_application_transaction() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + NEW.application_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_topology_application_transaction BEFORE INSERT + ON world_topology_draft_commit FOR EACH ROW + EXECUTE FUNCTION world_stamp_topology_application_transaction(); + +CREATE FUNCTION world_guard_graph_application() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + graph_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + unit JSONB; + current_epoch BIGINT; + mapped_key BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World graph APPLIED results are immutable and retained' USING ERRCODE = '23514'; + END IF; + SELECT * INTO graph_row FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF NOT FOUND OR graph_row.application_transaction_id IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'APPLIED requires a genuine fresh graph in the same transaction; old history cannot be promoted' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = graph_row.target_namespace + AND canonical_tenant_id = graph_row.canonical_tenant_id + AND local_tenant_key = graph_row.local_tenant_key + AND version_id = graph_row.local_version_key FOR UPDATE; + IF NOT FOUND OR owner_row.owner_freeze_phase <> 'OPEN' + OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'Fresh graph APPLIED requires exact OPEN V25 owner' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_terminal_outcome t + WHERE t.operation_id = NEW.operation_id OR t.request_id = NEW.request_id + OR t.commit_id = NEW.commit_id OR t.authorization_fence_id = NEW.authorization_fence_id) THEN + RAISE EXCEPTION 'Definitively aborted World operation cannot apply' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(DISTINCT family) FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id) <> 6 THEN + RAISE EXCEPTION 'APPLIED requires all six genuinely mutated World families' USING ERRCODE = '23514'; + END IF; + FOR unit IN SELECT value FROM jsonb_array_elements(graph_row.binding_json::JSONB->'affectedUnits') + WHERE value->>'owner' = 'WORLD_MANAGEMENT' LOOP + IF unit->>'expectedEpoch' <> '0' THEN + RAISE EXCEPTION 'Fresh graph APPLIED requires original zero epochs' USING ERRCODE = '23514'; + END IF; + SELECT private_row_key INTO mapped_key FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id + AND family = unit->>'aggregateType' AND template_id = (unit->>'aggregateId')::UUID; + IF NOT FOUND THEN + RAISE EXCEPTION 'APPLIED affected unit lacks exact fresh mapping' USING ERRCODE = '23514'; + END IF; + IF unit->>'scopeType' = 'AGGREGATE' THEN + SELECT draft_revision_epoch INTO current_epoch FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = graph_row.local_tenant_key AND version_id = graph_row.local_version_key + AND aggregate_type = unit->>'aggregateType' AND aggregate_id = mapped_key; + ELSE + SELECT draft_scope_revision_epoch INTO current_epoch FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = graph_row.local_tenant_key AND version_id = graph_row.local_version_key + AND scope_type = unit->>'scopeType' AND scope_id = unit->>'scopeId'; + END IF; + IF NOT FOUND OR current_epoch IS DISTINCT FROM 1::BIGINT THEN + RAISE EXCEPTION 'APPLIED lacks complete resulting World epochs' USING ERRCODE = '23514'; + END IF; + END LOOP; + NEW.application_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_graph_application_guard BEFORE INSERT OR UPDATE OR DELETE + ON world_draft_graph_application FOR EACH ROW EXECUTE FUNCTION world_guard_graph_application(); +CREATE TRIGGER trg_world_graph_application_no_truncate BEFORE TRUNCATE + ON world_draft_graph_application FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_authored_source_history_mutation(); +CREATE FUNCTION world_abort_excludes_graph_application() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + PERFORM 1 FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = NEW.target_namespace AND canonical_tenant_id = NEW.canonical_tenant_id + AND local_tenant_key = NEW.local_tenant_key AND version_id = NEW.local_version_key FOR UPDATE; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_graph_application a + WHERE a.operation_id = NEW.operation_id OR a.request_id = NEW.request_id + OR a.commit_id = NEW.commit_id OR a.authorization_fence_id = NEW.authorization_fence_id) THEN + RAISE EXCEPTION 'Committed World graph cannot be relabeled as definitive no-commit' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_abort_excludes_graph_application BEFORE INSERT + ON world_draft_terminal_outcome FOR EACH ROW EXECUTE FUNCTION world_abort_excludes_graph_application(); +REVOKE ALL ON world_draft_graph_application FROM PUBLIC; +REVOKE ALL ON world_draft_graph_terminal_identity FROM PUBLIC; +REVOKE ALL ON FUNCTION world_claim_graph_terminal_identity() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_verify_graph_terminal_identity_receipt() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_stamp_topology_application_transaction() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_guard_graph_application() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_abort_excludes_graph_application() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V40__world_preparation_exact_release_graph.sql b/services/world-management-service/src/main/resources/db/migration/V40__world_preparation_exact_release_graph.sql new file mode 100644 index 0000000000..a58b329d7a --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V40__world_preparation_exact_release_graph.sql @@ -0,0 +1,67 @@ +-- Retain the V35 function identity, access grants and complete original guard body. Add the +-- immutable release/checkpoint join before either retry readback or runtime allocation. +-- [jooq ignore start] +DO $migration$ +DECLARE + preparation_function REGPROCEDURE := + '"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE; + original_definition TEXT; + insertion_point TEXT := $anchor$ IF identity_row.operation_id::TEXT IS DISTINCT FROM topology->>'versionIdentityOperationId'$anchor$; + join_guard TEXT := $guard$ IF binding_row.release_attestation_json::JSONB->>'targetNamespace' + IS DISTINCT FROM capture_row.freeze_request_json::JSONB->>'targetNamespace' + OR binding_row.release_attestation_json::JSONB->>'targetNamespace' + IS DISTINCT FROM identity_row.target_namespace + OR binding_row.release_attestation_json::JSONB->>'canonicalTenantId' + IS DISTINCT FROM identity_row.canonical_tenant_id::TEXT + OR binding_row.release_attestation_json::JSONB->>'canonicalTenantId' + IS DISTINCT FROM capture_row.freeze_request_json::JSONB->>'canonicalTenantId' + OR binding_row.release_attestation_json::JSONB->>'canonicalVersionId' + IS DISTINCT FROM identity_row.canonical_version_id::TEXT + OR binding_row.release_attestation_json::JSONB->>'canonicalVersionId' + IS DISTINCT FROM capture_row.freeze_request_json::JSONB->>'canonicalVersionId' + OR binding_row.release_attestation_json::JSONB->>'canonicalVersionId' + IS DISTINCT FROM capture_row.binding_json::JSONB->>'canonicalVersionId' + OR binding_row.release_attestation_json::JSONB->>'canonicalTenantId' + IS DISTINCT FROM capture_row.binding_json::JSONB->>'canonicalTenantId' + OR binding_row.release_attestation_json::JSONB->>'commitId' + IS DISTINCT FROM capture_row.commit_id::TEXT + OR binding_row.release_attestation_json::JSONB->>'commitId' + IS DISTINCT FROM capture_row.binding_json::JSONB->>'commitId' + OR binding_row.release_attestation_json::JSONB->>'commitId' + IS DISTINCT FROM capture_row.freeze_request_json::JSONB->>'appliedCommitId' + OR binding_row.release_attestation_json::JSONB->>'publishWorkflowId' + IS DISTINCT FROM capture_row.freeze_request_json::JSONB->>'publishWorkflowId' + OR (SELECT count(*) FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(binding_row.release_attestation_json::JSONB->'participantDigests') = 'array' + THEN binding_row.release_attestation_json::JSONB->'participantDigests' + ELSE '[]'::JSONB END) participant + WHERE participant->>'participantKey' = 'WORLD_MANAGEMENT') <> 1 + OR NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(binding_row.release_attestation_json::JSONB->'participantDigests') = 'array' + THEN binding_row.release_attestation_json::JSONB->'participantDigests' + ELSE '[]'::JSONB END) participant + WHERE participant->>'participantKey' = 'WORLD_MANAGEMENT' + AND participant->>'scopeValue' = identity_row.game_design_version_id::TEXT + AND participant->>'baseVersionIdPresent' = 'false' + AND participant->'baseVersionId' = 'null'::JSONB + AND participant->>'appliedCommitId' = capture_row.freeze_request_json::JSONB->>'appliedCommitId' + AND participant->>'contentDigest' = capture_row.freeze_request_json::JSONB->>'contentDigest' + AND participant->>'digestSchemaVersion' = capture_row.freeze_request_json::JSONB->>'digestSchemaVersion' + AND participant->>'digestSchemaVersion' = '3' + ) THEN + RAISE EXCEPTION 'Canonical preparation release differs from the exact selected frozen World graph' + USING ERRCODE = '23514'; + END IF; + +$guard$; +BEGIN + SELECT pg_get_functiondef(preparation_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, insertion_point, ''))) + / length(insertion_point) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V35 canonical preparation release-join insertion point'; + END IF; + EXECUTE replace(original_definition, insertion_point, join_guard || insertion_point); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V41__world_explicit_fresh_graph_start_location.sql b/services/world-management-service/src/main/resources/db/migration/V41__world_explicit_fresh_graph_start_location.sql new file mode 100644 index 0000000000..543b4b8c84 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V41__world_explicit_fresh_graph_start_location.sql @@ -0,0 +1,292 @@ +CREATE TABLE world_draft_start_location_receipt ( + operation_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + commit_id UUID NOT NULL UNIQUE, + authorization_fence_id UUID NOT NULL UNIQUE, + target_namespace VARCHAR(128) NOT NULL, + account_binding_bytes BYTEA NOT NULL CHECK (octet_length(account_binding_bytes) > 0), + account_binding_digest VARCHAR(71) NOT NULL CHECK (account_binding_digest ~ '^sha256:[0-9a-f]{64}$'), + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + canonical_tenant_id UUID NOT NULL CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + canonical_version_id UUID NOT NULL CHECK (canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID), + room_template_id UUID NOT NULL CHECK (room_template_id <> '00000000-0000-0000-0000-000000000000'::UUID), + graph_digest VARCHAR(71) NOT NULL CHECK (graph_digest ~ '^sha256:[0-9a-f]{64}$'), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + receipt_bytes BYTEA NOT NULL CHECK (octet_length(receipt_bytes) > 0), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_world_draft_start_location_application + FOREIGN KEY (operation_id) REFERENCES world_draft_graph_application(operation_id) + DEFERRABLE INITIALLY DEFERRED, + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authorization_fence_id <> '00000000-0000-0000-0000-000000000000'::UUID) +); + +-- [jooq ignore start] +CREATE FUNCTION world_reject_draft_start_location_receipt_mutation() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'World original start-location receipts are immutable and retained' + USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER trg_world_start_location_receipt_immutable + BEFORE UPDATE OR DELETE ON world_draft_start_location_receipt + FOR EACH ROW EXECUTE FUNCTION world_reject_draft_start_location_receipt_mutation(); +CREATE TRIGGER trg_world_start_location_receipt_no_truncate + BEFORE TRUNCATE ON world_draft_start_location_receipt + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_draft_start_location_receipt_mutation(); + +CREATE FUNCTION world_guard_draft_start_location_receipt() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + graph_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + declaration JSONB; + start_location JSONB; + declaration_count BIGINT; +BEGIN + SELECT * INTO graph_row FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF NOT FOUND OR graph_row.application_transaction_id IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'World start-location receipt requires its exact fresh graph transaction' + USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO declaration_count + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND ((value->>'payload')::JSONB ? 'freshGraphDeclaration'); + IF declaration_count <> 1 THEN + RAISE EXCEPTION 'World start-location receipt requires exactly one original graph declaration' + USING ERRCODE = '23514'; + END IF; + SELECT ((value->>'payload')::JSONB)->'freshGraphDeclaration' INTO declaration + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND ((value->>'payload')::JSONB ? 'freshGraphDeclaration'); + start_location := declaration->'startLocation'; + IF NEW.operation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.request_id IS DISTINCT FROM graph_row.request_id + OR NEW.commit_id IS DISTINCT FROM graph_row.commit_id + OR NEW.target_namespace IS DISTINCT FROM graph_row.target_namespace + OR NEW.binding_digest IS DISTINCT FROM graph_row.binding_digest + OR NEW.canonical_tenant_id IS DISTINCT FROM graph_row.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM graph_row.canonical_version_id + OR declaration->>'tenantId' IS DISTINCT FROM graph_row.canonical_tenant_id::TEXT + OR declaration->>'versionId' IS DISTINCT FROM graph_row.canonical_version_id::TEXT + OR start_location->>'tenantId' IS DISTINCT FROM graph_row.canonical_tenant_id::TEXT + OR start_location->>'versionId' IS DISTINCT FROM graph_row.canonical_version_id::TEXT + OR start_location->>'roomTemplateId' IS NULL + OR start_location->>'roomTemplateId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR NEW.room_template_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.room_template_id IS DISTINCT FROM (start_location->>'roomTemplateId')::UUID + OR NEW.graph_digest IS DISTINCT FROM ('sha256:' || graph_row.graph_sha256) + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id = m.private_row_key + WHERE m.target_namespace = graph_row.target_namespace + AND m.canonical_tenant_id = graph_row.canonical_tenant_id + AND m.canonical_version_id = graph_row.canonical_version_id + AND m.family = 'ROOM' + AND m.template_id = NEW.room_template_id + AND m.request_id = NEW.request_id + AND m.commit_id = NEW.commit_id + AND m.tenant_id = graph_row.local_tenant_key + AND m.version_id = graph_row.local_version_key + AND r.tenant_id = graph_row.local_tenant_key + AND r.version_id = graph_row.local_version_key) + THEN + RAISE EXCEPTION 'World typed start selector differs from exact original graph/Version/ROOM' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_start_location_receipt_guard + BEFORE INSERT ON world_draft_start_location_receipt + FOR EACH ROW EXECUTE FUNCTION world_guard_draft_start_location_receipt(); + +-- V39 required six populated families. The Account-bound application now proves all six declared +-- counts, including explicit zero families, against the original binding and exact Version rows. +CREATE OR REPLACE FUNCTION world_guard_graph_application() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + graph_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + receipt "${serviceSchema}".world_draft_start_location_receipt%ROWTYPE; + unit JSONB; + declaration JSONB; + start_location JSONB; + family_entry JSONB; + family_names TEXT[] := ARRAY[ + 'REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING']; + family_name TEXT; + declared_count BIGINT; + mapping_count BIGINT; + content_count BIGINT; + declaration_count BIGINT; + receipt_count BIGINT; + family_index INTEGER; + mapped_key BIGINT; + current_epoch BIGINT; + result_json JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World graph APPLIED results are immutable and retained' USING ERRCODE = '23514'; + END IF; + SELECT * INTO graph_row FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF NOT FOUND OR graph_row.application_transaction_id IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'APPLIED requires a genuine fresh graph in the same transaction; old history cannot be promoted' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = graph_row.target_namespace + AND canonical_tenant_id = graph_row.canonical_tenant_id + AND local_tenant_key = graph_row.local_tenant_key + AND version_id = graph_row.local_version_key FOR UPDATE; + IF NOT FOUND OR owner_row.owner_freeze_phase <> 'OPEN' + OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'Fresh graph APPLIED requires exact OPEN V25 owner' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_terminal_outcome t + WHERE t.operation_id = NEW.operation_id OR t.request_id = NEW.request_id + OR t.commit_id = NEW.commit_id OR t.authorization_fence_id = NEW.authorization_fence_id) THEN + RAISE EXCEPTION 'Definitively aborted World operation cannot apply' USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO declaration_count + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND ((value->>'payload')::JSONB ? 'freshGraphDeclaration'); + IF declaration_count <> 1 THEN + RAISE EXCEPTION 'Fresh graph APPLIED requires exactly one original complete declaration' + USING ERRCODE = '23514'; + END IF; + SELECT ((value->>'payload')::JSONB)->'freshGraphDeclaration' INTO declaration + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND ((value->>'payload')::JSONB ? 'freshGraphDeclaration'); + start_location := declaration->'startLocation'; + IF declaration->>'tenantId' IS DISTINCT FROM graph_row.canonical_tenant_id::TEXT + OR declaration->>'versionId' IS DISTINCT FROM graph_row.canonical_version_id::TEXT + OR start_location->>'tenantId' IS DISTINCT FROM graph_row.canonical_tenant_id::TEXT + OR start_location->>'versionId' IS DISTINCT FROM graph_row.canonical_version_id::TEXT + OR jsonb_typeof(declaration->'familyCounts') IS DISTINCT FROM 'array' + OR jsonb_array_length(declaration->'familyCounts') <> 6 THEN + RAISE EXCEPTION 'Fresh graph APPLIED declaration has wrong canonical scope or family vector' + USING ERRCODE = '23514'; + END IF; + FOR family_index IN 1..6 LOOP + family_entry := declaration->'familyCounts'->(family_index - 1); + family_name := family_names[family_index]; + IF family_entry->>'family' IS DISTINCT FROM + ('WORLD_DESIGN_AGGREGATE_TYPE_' || family_name) + OR NOT (family_entry ? 'count') + OR jsonb_typeof(family_entry->'count') IS DISTINCT FROM 'number' + OR (family_entry->>'count') !~ '^(0|[1-9][0-9]*)$' + OR (family_entry->>'count')::NUMERIC > 2147483647 THEN + RAISE EXCEPTION 'Fresh graph APPLIED family declaration is absent, changed or noncanonical' + USING ERRCODE = '23514'; + END IF; + declared_count := (family_entry->>'count')::BIGINT; + SELECT count(*) INTO mapping_count FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id AND family = family_name; + EXECUTE format('SELECT count(*) FROM %I.%I WHERE tenant_id=$1 AND version_id=$2', + '${serviceSchema}', lower(family_name)) + INTO content_count USING graph_row.local_tenant_key, graph_row.local_version_key; + IF mapping_count IS DISTINCT FROM declared_count + OR content_count IS DISTINCT FROM declared_count THEN + RAISE EXCEPTION 'APPLIED requires every declared World family row and explicit empty family for exact Version' + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF start_location->>'roomTemplateId' IS NULL + OR start_location->>'roomTemplateId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (start_location->>'roomTemplateId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id = m.private_row_key + WHERE m.target_namespace = graph_row.target_namespace + AND m.canonical_tenant_id = graph_row.canonical_tenant_id + AND m.canonical_version_id = graph_row.canonical_version_id + AND m.family = 'ROOM' + AND m.template_id = (start_location->>'roomTemplateId')::UUID + AND m.request_id = NEW.request_id AND m.commit_id = NEW.commit_id + AND m.tenant_id = graph_row.local_tenant_key AND m.version_id = graph_row.local_version_key + AND r.tenant_id = graph_row.local_tenant_key AND r.version_id = graph_row.local_version_key) THEN + RAISE EXCEPTION 'APPLIED start selector must name one exact ROOM row in this graph and Version' + USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO receipt_count FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE operation_id = NEW.operation_id OR request_id = NEW.request_id + OR commit_id = NEW.commit_id OR authorization_fence_id = NEW.authorization_fence_id; + IF receipt_count <> 1 THEN + RAISE EXCEPTION 'APPLIED requires one exact durable start-location receipt' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT receipt FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE operation_id = NEW.operation_id OR request_id = NEW.request_id + OR commit_id = NEW.commit_id OR authorization_fence_id = NEW.authorization_fence_id; + IF receipt.operation_id IS DISTINCT FROM NEW.operation_id + OR receipt.request_id IS DISTINCT FROM NEW.request_id + OR receipt.commit_id IS DISTINCT FROM NEW.commit_id + OR receipt.authorization_fence_id IS DISTINCT FROM NEW.authorization_fence_id + OR receipt.target_namespace IS DISTINCT FROM graph_row.target_namespace + OR receipt.account_binding_bytes IS DISTINCT FROM NEW.account_binding_bytes + OR receipt.account_binding_digest IS DISTINCT FROM NEW.account_binding_digest + OR receipt.binding_digest IS DISTINCT FROM graph_row.binding_digest + OR receipt.canonical_tenant_id IS DISTINCT FROM graph_row.canonical_tenant_id + OR receipt.canonical_version_id IS DISTINCT FROM graph_row.canonical_version_id + OR receipt.room_template_id IS DISTINCT FROM (start_location->>'roomTemplateId')::UUID + OR receipt.graph_digest IS DISTINCT FROM ('sha256:' || graph_row.graph_sha256) + OR receipt.receipt_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'APPLIED requires exact durable original Account-bound start selector receipt' + USING ERRCODE = '23514'; + END IF; + result_json := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF result_json->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR result_json->>'status' IS DISTINCT FROM 'APPLIED' + OR result_json->>'graphDigest' IS DISTINCT FROM ('sha256:' || graph_row.graph_sha256) + OR result_json->>'startLocationReceiptDigest' IS DISTINCT FROM receipt.receipt_digest + OR decode(result_json->>'startLocationReceiptBase64', 'base64') IS DISTINCT FROM receipt.receipt_bytes + OR decode(result_json->>'operationBytesBase64', 'base64') IS DISTINCT FROM NEW.operation_bytes + OR decode(result_json->>'graphBytesBase64', 'base64') IS DISTINCT FROM graph_row.graph_bytes THEN + RAISE EXCEPTION 'APPLIED result does not retain the exact graph, operation and start selector' + USING ERRCODE = '23514'; + END IF; + FOR unit IN SELECT value FROM jsonb_array_elements(graph_row.binding_json::JSONB->'affectedUnits') + WHERE value->>'owner' = 'WORLD_MANAGEMENT' LOOP + IF unit->>'expectedEpoch' <> '0' THEN + RAISE EXCEPTION 'Fresh graph APPLIED requires original zero epochs' USING ERRCODE = '23514'; + END IF; + SELECT private_row_key INTO mapped_key FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id + AND family = unit->>'aggregateType' AND template_id = (unit->>'aggregateId')::UUID; + IF NOT FOUND THEN + RAISE EXCEPTION 'APPLIED affected unit lacks exact fresh mapping' USING ERRCODE = '23514'; + END IF; + IF unit->>'scopeType' = 'AGGREGATE' THEN + SELECT draft_revision_epoch INTO current_epoch FROM "${serviceSchema}".world_design_aggregate_epoch + WHERE tenant_id = graph_row.local_tenant_key AND version_id = graph_row.local_version_key + AND aggregate_type = unit->>'aggregateType' AND aggregate_id = mapped_key; + ELSE + SELECT draft_scope_revision_epoch INTO current_epoch FROM "${serviceSchema}".world_design_scope_epoch + WHERE tenant_id = graph_row.local_tenant_key AND version_id = graph_row.local_version_key + AND scope_type = unit->>'scopeType' AND scope_id = unit->>'scopeId'; + END IF; + IF NOT FOUND OR current_epoch IS DISTINCT FROM 1::BIGINT THEN + RAISE EXCEPTION 'APPLIED lacks complete resulting World epochs' USING ERRCODE = '23514'; + END IF; + END LOOP; + NEW.application_transaction_id := txid_current(); + RETURN NEW; +END; +$$; +REVOKE ALL ON world_draft_start_location_receipt FROM PUBLIC; +REVOKE ALL ON FUNCTION world_reject_draft_start_location_receipt_mutation() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_guard_draft_start_location_receipt() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_guard_graph_application() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql b/services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql new file mode 100644 index 0000000000..108d82c335 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V42__world_release_start_location_materialization.sql @@ -0,0 +1,227 @@ +-- Keep V1 materialization history inert and byte-for-byte retryable. V2 retains the authored +-- ROOM reference separately from its exact World-owned runtime mapping; neither activates it. +CREATE TABLE world_canonical_preparation_start_location ( + canonical_game_instance_id UUID PRIMARY KEY REFERENCES world_canonical_instance_preparation(canonical_game_instance_id) ON DELETE RESTRICT, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + room_template_id UUID NOT NULL, + runtime_room_instance_id BIGINT NOT NULL CHECK (runtime_room_instance_id > 0), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + graph_digest VARCHAR(71) NOT NULL CHECK (graph_digest ~ '^sha256:[0-9a-f]{64}$'), + evidence_bytes BYTEA NOT NULL CHECK (octet_length(evidence_bytes) > 0), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_preparation_start_location FROM PUBLIC; + +-- This independently checks immutable producer evidence before allocation and on every retry. +CREATE FUNCTION world_require_preparation_start_location(input JSONB, binding JSONB, capture UUID) +RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + frozen "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; + receipt "${serviceSchema}".world_draft_start_location_receipt%ROWTYPE; + application "${serviceSchema}".world_draft_graph_application%ROWTYPE; + graph "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + evidence JSONB; + selected JSONB; + publication_request JSONB; + retained JSONB; + retained_version_state_epoch BIGINT; + expected_tuples JSONB; +BEGIN + IF input->>'schemaVersion' = '1' THEN + IF binding->>'schemaVersion' IS DISTINCT FROM '1' + OR binding ? 'worldStartLocationEvidence' OR input ? 'worldStartLocationEvidenceBase64' THEN + RAISE EXCEPTION 'V1 preparation cannot acquire selector evidence' USING ERRCODE = '23514'; + END IF; + RETURN; + END IF; + IF input->>'schemaVersion' IS DISTINCT FROM '2' OR binding->>'schemaVersion' IS DISTINCT FROM '2' + OR input->>'worldStartLocationEvidenceBase64' IS NULL + OR jsonb_typeof(binding->'worldStartLocationEvidence') IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'V2 preparation requires original complete World selector evidence' USING ERRCODE = '23514'; + END IF; + evidence := convert_from(decode(input->>'worldStartLocationEvidenceBase64', 'base64'), 'UTF8')::JSONB; + selected := evidence->'request'; + retained := binding->'worldStartLocationEvidence'; + IF jsonb_typeof(retained->'request') IS DISTINCT FROM 'object' + OR jsonb_typeof(retained->'request'->'versionStateEpoch') IS DISTINCT FROM 'number' + OR retained->'request'->>'versionStateEpoch' !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Retained full release selector epoch must be a canonical positive JSON number' + USING ERRCODE = '23514'; + END IF; + retained_version_state_epoch := (retained->'request'->>'versionStateEpoch')::BIGINT; + SELECT * INTO STRICT frozen FROM "${serviceSchema}".world_canonical_frozen_topology WHERE capture_id=capture; + publication_request := frozen.freeze_request_json::JSONB; + SELECT coalesce(jsonb_agg(value ORDER BY value->>'owner',value->>'aggregateType',value->>'aggregateId', + value->>'scopeType',value->>'scopeId',value->>'expectedEpoch'), '[]'::JSONB) + INTO expected_tuples FROM jsonb_array_elements(publication_request->'suppliedOwnedAffectedTuples'); + IF evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR selected IS DISTINCT FROM jsonb_set( + retained->'request', '{versionStateEpoch}', to_jsonb(retained_version_state_epoch::TEXT), FALSE) + OR (SELECT count(*) FROM jsonb_object_keys(selected)) <> 13 + OR selected->>'targetNamespace' IS DISTINCT FROM publication_request->>'targetNamespace' + OR selected->>'canonicalTenantId' IS DISTINCT FROM publication_request->>'canonicalTenantId' + OR selected->>'canonicalVersionId' IS DISTINCT FROM publication_request->>'canonicalVersionId' + OR selected->>'intakeRequestId' IS DISTINCT FROM publication_request->>'intakeRequestId' + OR selected->>'publicationFence' IS DISTINCT FROM publication_request->>'publicationFence' + OR selected->>'publicationRequestId' IS DISTINCT FROM publication_request->>'publicationRequestId' + OR selected->>'requestDigest' IS DISTINCT FROM publication_request->>'requestDigest' + OR selected->>'versionStateEpoch' IS DISTINCT FROM publication_request->>'versionStateEpoch' + OR selected->>'publishWorkflowId' IS DISTINCT FROM publication_request->>'publishWorkflowId' + OR selected->>'appliedCommitId' IS DISTINCT FROM publication_request->>'appliedCommitId' + OR selected->>'contentDigest' IS DISTINCT FROM publication_request->>'contentDigest' + OR selected->>'digestSchemaVersion' IS DISTINCT FROM '3' + OR selected->>'digestSchemaVersion' IS DISTINCT FROM publication_request->>'digestSchemaVersion' + OR selected->'worldAffectedTuples' IS DISTINCT FROM expected_tuples + OR decode(evidence->>'selectorReceiptBytesBase64','base64') IS DISTINCT FROM decode(retained->>'selectorReceiptBytes','base64') + OR decode(evidence->>'originalAccountBindingBytesBase64','base64') IS DISTINCT FROM decode(retained->>'originalAccountBindingBytes','base64') + OR decode(evidence->>'appliedResultBytesBase64','base64') IS DISTINCT FROM decode(retained->>'appliedResultBytes','base64') THEN + RAISE EXCEPTION 'Preparation selector differs from complete frozen request or retained release bytes' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT receipt FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + SELECT * INTO STRICT application FROM "${serviceSchema}".world_draft_graph_application + WHERE operation_id=receipt.operation_id AND request_id=receipt.request_id AND commit_id=receipt.commit_id + AND authorization_fence_id=receipt.authorization_fence_id; + SELECT * INTO STRICT graph FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + IF receipt.target_namespace IS DISTINCT FROM selected->>'targetNamespace' + OR receipt.canonical_tenant_id::TEXT IS DISTINCT FROM selected->>'canonicalTenantId' + OR receipt.canonical_version_id::TEXT IS DISTINCT FROM selected->>'canonicalVersionId' + OR receipt.binding_digest IS DISTINCT FROM graph.binding_digest + OR receipt.graph_digest IS DISTINCT FROM ('sha256:' || frozen.graph_sha256) + OR graph.graph_bytes IS DISTINCT FROM frozen.graph_bytes + OR graph.binding_json IS DISTINCT FROM frozen.binding_json + OR graph.owner_binding_json IS DISTINCT FROM frozen.owner_binding_json + OR receipt.account_binding_bytes IS DISTINCT FROM application.account_binding_bytes + OR receipt.account_binding_digest IS DISTINCT FROM application.account_binding_digest + OR receipt.receipt_bytes IS DISTINCT FROM decode(evidence->>'selectorReceiptBytesBase64','base64') + OR receipt.account_binding_bytes IS DISTINCT FROM decode(evidence->>'originalAccountBindingBytesBase64','base64') + OR application.result_bytes IS DISTINCT FROM decode(evidence->>'appliedResultBytesBase64','base64') + OR convert_from(application.result_bytes,'UTF8')::JSONB->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR convert_from(application.result_bytes,'UTF8')::JSONB->>'status' IS DISTINCT FROM 'APPLIED' + OR NOT EXISTS (SELECT 1 FROM "${serviceSchema}".world_authored_topology_identity m + JOIN "${serviceSchema}".room r ON r.id=m.private_row_key + WHERE m.request_id=frozen.request_id AND m.commit_id=frozen.commit_id AND m.family='ROOM' + AND m.template_id=receipt.room_template_id AND m.canonical_tenant_id=receipt.canonical_tenant_id + AND m.canonical_version_id=receipt.canonical_version_id AND m.target_namespace=receipt.target_namespace + AND r.tenant_id=graph.local_tenant_key AND r.version_id=graph.local_version_key + AND m.tenant_id=r.tenant_id AND m.version_id=r.version_id) THEN + RAISE EXCEPTION 'Preparation selector lacks exact original Account/APPLIED/graph/ROOM evidence' USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_require_preparation_start_location(JSONB, JSONB, UUID) FROM PUBLIC; + +-- Amend only the input-schema gate and insert additional guards. Preserve the complete existing +-- V35/V40 guard body, grants, ownership, materialization writes and V1 historical input bytes. +DO $migration$ +DECLARE + original TEXT; + schema_anchor TEXT := $anchor$ IF p->>'schemaVersion' IS DISTINCT FROM '1' THEN$anchor$; + join_anchor TEXT := $anchor$ IF identity_row.operation_id::TEXT IS DISTINCT FROM topology->>'versionIdentityOperationId'$anchor$; + retry_anchor TEXT := $anchor$ IF FOUND THEN + IF prior.input_json IS DISTINCT FROM p_input_json$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE) INTO STRICT original; + IF (length(original)-length(replace(original,schema_anchor,'')))/length(schema_anchor) <> 1 + OR (length(original)-length(replace(original,join_anchor,'')))/length(join_anchor) <> 1 + OR (length(original)-length(replace(original,retry_anchor,'')))/length(retry_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one original preparation schema/join/retry guard'; + END IF; + original := replace(original,schema_anchor,$replacement$ IF p->>'schemaVersion' IS NULL OR p->>'schemaVersion' NOT IN ('1','2') THEN$replacement$); + original := replace(original,join_anchor,$replacement$ PERFORM "${serviceSchema}".world_require_preparation_start_location(p, binding_row.release_attestation_json::JSONB, capture_row.capture_id); + +$replacement$ || join_anchor); + original := replace(original,retry_anchor,$replacement$ IF FOUND THEN + IF p->>'schemaVersion' = '2' AND NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_preparation_start_location s + WHERE s.canonical_game_instance_id=prior.canonical_game_instance_id + AND s.world_instance_id=prior.world_instance_id + AND s.evidence_bytes=decode(p->>'worldStartLocationEvidenceBase64','base64')) THEN + RAISE EXCEPTION 'V2 preparation retry lacks original selector readback' USING ERRCODE='23514'; + END IF; + IF prior.input_json IS DISTINCT FROM p_input_json$replacement$); + EXECUTE original; +END; +$migration$; + +CREATE FUNCTION world_retain_preparation_start_location() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,"${serviceSchema}" +AS $$ +DECLARE + receipt "${serviceSchema}".world_draft_start_location_receipt%ROWTYPE; + mapping "${serviceSchema}".world_canonical_instance_topology_identity%ROWTYPE; + frozen "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; +BEGIN + IF NEW.input_json::JSONB->>'schemaVersion' = '1' THEN RETURN NEW; END IF; + SELECT * INTO STRICT frozen FROM "${serviceSchema}".world_canonical_frozen_topology WHERE capture_id=NEW.capture_id; + SELECT * INTO STRICT receipt FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + SELECT * INTO STRICT mapping FROM "${serviceSchema}".world_canonical_instance_topology_identity + WHERE world_instance_id=NEW.world_instance_id AND canonical_game_instance_id=NEW.canonical_game_instance_id + AND family='ROOM' AND template_id=receipt.room_template_id; + INSERT INTO "${serviceSchema}".world_canonical_preparation_start_location + (canonical_game_instance_id,world_instance_id,canonical_tenant_id,canonical_version_id,room_template_id, + runtime_room_instance_id,receipt_digest,graph_digest,evidence_bytes) + VALUES (NEW.canonical_game_instance_id,NEW.world_instance_id,receipt.canonical_tenant_id,receipt.canonical_version_id, + receipt.room_template_id,mapping.runtime_room_instance_id,receipt.receipt_digest,receipt.graph_digest, + decode(NEW.input_json::JSONB->>'worldStartLocationEvidenceBase64','base64')); + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_preparation_retain_start_location AFTER INSERT ON world_canonical_instance_preparation + FOR EACH ROW EXECUTE FUNCTION world_retain_preparation_start_location(); + +CREATE FUNCTION world_guard_preparation_start_location() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,"${serviceSchema}" +AS $$ +DECLARE + prepared "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + binding TEXT; + original JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Original canonical preparation selector is immutable and retained' USING ERRCODE='23514'; + END IF; + SELECT p.* INTO STRICT prepared FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id=NEW.canonical_game_instance_id + AND p.xmin::TEXT=(txid_current() % 4294967296)::TEXT; + original := prepared.input_json::JSONB; + SELECT release_attestation_json INTO STRICT binding FROM "${serviceSchema}".world_complete_launch_binding + WHERE binding_operation_id=(original->'launchBinding'->>'operationId')::UUID; + IF original->>'schemaVersion' IS DISTINCT FROM '2' + OR prepared.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR prepared.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR prepared.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR NEW.evidence_bytes IS DISTINCT FROM decode(original->>'worldStartLocationEvidenceBase64','base64') + OR NOT EXISTS (SELECT 1 FROM "${serviceSchema}".world_draft_start_location_receipt s + JOIN "${serviceSchema}".world_canonical_frozen_topology f ON f.request_id=s.request_id AND f.commit_id=s.commit_id + WHERE f.capture_id=prepared.capture_id AND s.canonical_tenant_id=NEW.canonical_tenant_id + AND s.canonical_version_id=NEW.canonical_version_id AND s.room_template_id=NEW.room_template_id + AND s.receipt_digest=NEW.receipt_digest AND s.graph_digest=NEW.graph_digest) + OR NOT EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_topology_identity m + JOIN "${serviceSchema}".room_instance r ON r.id=m.runtime_row_id + JOIN "${serviceSchema}".world_instance w ON w.id=m.world_instance_id + WHERE m.world_instance_id=prepared.world_instance_id AND m.canonical_game_instance_id=NEW.canonical_game_instance_id + AND m.family='ROOM' AND m.template_id=NEW.room_template_id + AND m.runtime_room_instance_id=NEW.runtime_room_instance_id AND r.room_instance_row_id=NEW.runtime_room_instance_id + AND r.tenant_id=w.tenant_id AND r.game_instance_id=w.game_instance_id) THEN + RAISE EXCEPTION 'Original preparation selector differs from exact authored/runtime ROOM mapping' USING ERRCODE='23514'; + END IF; + PERFORM "${serviceSchema}".world_require_preparation_start_location(original,binding::JSONB,prepared.capture_id); + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_preparation_start_location_guard BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_preparation_start_location + FOR EACH ROW EXECUTE FUNCTION world_guard_preparation_start_location(); +CREATE TRIGGER trg_world_preparation_start_location_no_truncate BEFORE TRUNCATE ON world_canonical_preparation_start_location + FOR EACH STATEMENT EXECUTE FUNCTION world_guard_preparation_start_location(); +REVOKE ALL ON FUNCTION world_retain_preparation_start_location() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_guard_preparation_start_location() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql b/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql new file mode 100644 index 0000000000..175c33022a --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V43__canonical_instance_activation_operation.sql @@ -0,0 +1,565 @@ +-- Canonical World activation is one immutable owner operation. A row can become ACTIVE only +-- through the exact PREPARING epoch/row-version CAS retained here. +CREATE TABLE world_canonical_instance_activation_operation ( + activation_request_id UUID PRIMARY KEY, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) > 0), + preparing_evidence_bytes BYTEA NOT NULL CHECK (octet_length(preparing_evidence_bytes) > 0), + canonical_game_instance_id UUID NOT NULL, + world_instance_id BIGINT NOT NULL, + expected_lifecycle_epoch BIGINT NOT NULL CHECK (expected_lifecycle_epoch > 0), + expected_row_version BIGINT NOT NULL CHECK (expected_row_version >= 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + terminal_code VARCHAR(64), + result_lifecycle_epoch BIGINT NOT NULL CHECK (result_lifecycle_epoch > 0), + result_row_version BIGINT NOT NULL CHECK (result_row_version >= 0), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + result_digest VARCHAR(71) NOT NULL CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_world_activation_association + FOREIGN KEY (canonical_game_instance_id) + REFERENCES world_canonical_instance_association(canonical_game_instance_id) + ON DELETE RESTRICT, + CONSTRAINT ck_world_activation_outcome_shape CHECK ( + (outcome = 'COMMITTED' AND terminal_code IS NULL + AND result_lifecycle_epoch = expected_lifecycle_epoch + 1 + AND result_row_version = expected_row_version + 1) + OR (outcome = 'ABORTED' AND terminal_code IS NOT NULL + AND length(btrim(terminal_code)) BETWEEN 1 AND 64) + ), + CONSTRAINT ck_world_activation_request_id_non_nil + CHECK (activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID) +); +CREATE UNIQUE INDEX uq_world_activation_one_commit_per_instance + ON world_canonical_instance_activation_operation(canonical_game_instance_id) + WHERE outcome = 'COMMITTED'; +CREATE INDEX idx_world_activation_world_row + ON world_canonical_instance_activation_operation(world_instance_id, activation_request_id); + +-- Only the validated operation insert may mint this exact, transaction-local UPDATE capability. +CREATE TABLE world_canonical_activation_execution_manifest ( + transaction_id BIGINT NOT NULL, + activation_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + result_digest VARCHAR(71) NOT NULL, + canonical_game_instance_id UUID NOT NULL, + world_instance_id BIGINT NOT NULL, + local_tenant_key BIGINT NOT NULL, + private_game_instance_key BIGINT NOT NULL, + expected_old JSONB NOT NULL, + expected_new JSONB NOT NULL, + PRIMARY KEY (transaction_id, activation_request_id), + UNIQUE (transaction_id, world_instance_id), + FOREIGN KEY (activation_request_id) + REFERENCES world_canonical_instance_activation_operation(activation_request_id) + ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED +); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_activation_operation FROM PUBLIC; +REVOKE ALL ON world_canonical_activation_execution_manifest FROM PUBLIC; + +CREATE FUNCTION world_validate_canonical_activation_operation() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + association_row "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + instance "${serviceSchema}".world_instance%ROWTYPE; + activated_instance "${serviceSchema}".world_instance%ROWTYPE; + preparing JSONB; + normalized_request JSONB; + result JSONB; + lifecycle JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Canonical World activation operation evidence is immutable' + USING ERRCODE = '55000'; + END IF; + preparing := convert_from(NEW.preparing_evidence_bytes, 'UTF8')::JSONB; + normalized_request := convert_from(NEW.request_bytes, 'UTF8')::JSONB; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(preparing) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(preparing)) <> 11 + OR (SELECT count(*) FROM jsonb_object_keys(preparing->'request')) <> 14 + OR preparing->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR preparing->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR (preparing->'request'->>'canonicalGameInstanceId') IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR (preparing->>'lifecycleEpoch') IS DISTINCT FROM NEW.expected_lifecycle_epoch::TEXT + OR (preparing->>'rowVersion') IS DISTINCT FROM NEW.expected_row_version::TEXT + OR jsonb_typeof(normalized_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(normalized_request)) <> 3 + OR (SELECT count(*) FROM jsonb_object_keys(normalized_request->'preparingEvidence')) <> 11 + OR (SELECT count(*) FROM jsonb_object_keys(normalized_request->'preparingEvidence'->'request')) <> 13 + OR normalized_request->>'schema' IS DISTINCT FROM 'world-canonical-instance-activation-request/v1' + OR normalized_request->>'activationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR NEW.request_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.request_bytes), 'hex')) + OR NEW.result_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.result_bytes), 'hex')) + OR normalized_request->'preparingEvidence' IS DISTINCT FROM + (preparing - 'request' || jsonb_build_object( + 'request', (preparing->'request') - 'readRequestId')) THEN + RAISE EXCEPTION 'Canonical activation request differs from its exact retained PREPARING evidence' + USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(result) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(result)) <> 8 + OR result->>'schema' IS DISTINCT FROM 'world-canonical-instance-activation-result/v1' + OR result->>'activationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR result->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR result->>'outcome' IS DISTINCT FROM NEW.outcome + OR result->>'terminalCode' IS DISTINCT FROM NEW.terminal_code + OR (NEW.terminal_code IS NULL AND jsonb_typeof(result->'terminalCode') IS DISTINCT FROM 'null') + OR (NEW.terminal_code IS NOT NULL AND jsonb_typeof(result->'terminalCode') IS DISTINCT FROM 'string') + OR decode(result->>'requestBytesBase64', 'base64') IS DISTINCT FROM NEW.request_bytes + OR decode(result->>'preparingEvidenceBytesBase64', 'base64') IS DISTINCT FROM NEW.preparing_evidence_bytes THEN + RAISE EXCEPTION 'Canonical activation result differs from its immutable request outcome' + USING ERRCODE = '23514'; + END IF; + lifecycle := convert_from(decode(result->>'lifecycleEvidenceBytesBase64', 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(lifecycle) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 11 + OR (SELECT count(*) FROM jsonb_object_keys(lifecycle->'request')) <> 14 + OR lifecycle->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR lifecycle->'request' IS DISTINCT FROM preparing->'request' + OR lifecycle->>'lifecycleEpoch' IS DISTINCT FROM NEW.result_lifecycle_epoch::TEXT + OR lifecycle->>'rowVersion' IS DISTINCT FROM NEW.result_row_version::TEXT + OR (lifecycle - 'lifecycleStatus' - 'lifecycleEpoch' - 'rowVersion') + IS DISTINCT FROM + (preparing - 'lifecycleStatus' - 'lifecycleEpoch' - 'rowVersion') THEN + RAISE EXCEPTION 'Canonical activation result does not retain its exact owner lifecycle snapshot' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO association_row FROM "${serviceSchema}".world_canonical_instance_association + WHERE canonical_game_instance_id = NEW.canonical_game_instance_id; + IF NOT FOUND OR association_row.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR lifecycle->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM association_row.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'Canonical activation operation does not resolve through its exact World association' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO instance FROM "${serviceSchema}".world_instance WHERE id=association_row.world_instance_id FOR UPDATE; + IF NOT FOUND OR instance.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id THEN + RAISE EXCEPTION 'Canonical activation operation lost its associated World row' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance w + ON w.id=a.world_instance_id + JOIN "${serviceSchema}".world_complete_launch_binding b + ON b.binding_operation_id=a.canonical_launch_binding_operation_id + JOIN "${serviceSchema}".world_authored_source_intake s + ON s.operation_id=a.intake_operation_id + JOIN "${serviceSchema}".world_authored_version_identity v + ON v.operation_id=a.version_identity_operation_id + JOIN "${serviceSchema}".world_canonical_instance_preparation p + ON p.canonical_game_instance_id=a.canonical_game_instance_id + JOIN "${serviceSchema}".world_canonical_preparation_start_location start_row + ON start_row.canonical_game_instance_id=a.canonical_game_instance_id + JOIN "${serviceSchema}".world_canonical_instance_topology_identity m + ON m.world_instance_id=a.world_instance_id + AND m.canonical_game_instance_id=a.canonical_game_instance_id + AND m.family='ROOM' AND m.template_id=start_row.room_template_id + JOIN "${serviceSchema}".room_instance r + ON r.id=m.runtime_row_id AND r.room_instance_row_id=start_row.runtime_room_instance_id + JOIN "${serviceSchema}".region_instance runtime_region + ON runtime_region.id=r.region_instance_id AND runtime_region.world_instance_id=a.world_instance_id + WHERE a.canonical_game_instance_id=NEW.canonical_game_instance_id + AND a.world_instance_id=NEW.world_instance_id + AND a.schema_version=1 + AND a.playable_state_scope='SHARED' + AND a.public_production IS TRUE + AND a.playtest_lifecycle_id IS NULL + AND a.playtest_state_generation IS NULL + AND w.canonical_game_instance_id=a.canonical_game_instance_id + AND w.canonical_target_namespace=a.canonical_target_namespace + AND w.canonical_tenant_id=a.canonical_tenant_id + AND w.canonical_world_slug=a.canonical_world_slug + AND w.playable_state_namespace_id=a.playable_state_namespace_id + AND w.playable_state_scope=a.playable_state_scope + AND w.public_production=a.public_production + AND w.control_plane_request_id=a.control_plane_request_id + AND w.canonical_launch_binding_operation_id=a.canonical_launch_binding_operation_id + AND w.tenant_id=a.local_tenant_key + AND w.game_instance_id=a.private_game_instance_key + AND b.target_namespace=a.canonical_target_namespace + AND b.canonical_tenant_id=a.canonical_tenant_id + AND b.canonical_version_id=a.canonical_version_id + AND b.world_slug=a.canonical_world_slug + AND b.control_plane_request_id=a.control_plane_request_id + AND b.intake_operation_id=a.intake_operation_id + AND b.intake_request_id=a.intake_request_id + AND b.local_tenant_key=a.local_tenant_key + AND b.source_operation_id=a.source_operation_id + AND b.source_evidence_digest=a.source_evidence_digest + AND b.intake_receipt_digest=a.intake_receipt_digest + AND b.descriptor_request_digest=a.descriptor_request_digest + AND b.descriptor_result_digest=a.descriptor_result_digest + AND b.release_attestation_digest=a.release_attestation_digest + AND b.descriptor_json::JSONB->>'launchDescriptorId'=a.launch_descriptor_id + AND b.descriptor_json::JSONB->>'versionId'=v.game_design_version_id::TEXT + AND b.descriptor_json::JSONB->>'gameTemplateId'=a.game_template_id::TEXT + AND b.descriptor_json::JSONB->>'targetNamespace'=a.canonical_target_namespace + AND b.descriptor_json::JSONB->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND b.descriptor_json::JSONB->>'worldSlug'=a.canonical_world_slug + AND b.descriptor_json::JSONB->>'controlPlaneRequestId'=a.control_plane_request_id + AND b.descriptor_json::JSONB->>'authoredWorldSourceOperationId'=a.source_operation_id::TEXT + AND b.descriptor_json::JSONB->>'authoredWorldSourceEvidenceDigest'=a.source_evidence_digest + AND b.descriptor_json::JSONB->>'requestDigest'=a.descriptor_request_digest + AND b.descriptor_json::JSONB->>'resultDigest'=a.descriptor_result_digest + AND (CASE WHEN b.descriptor_json::JSONB->>'scriptPatchVersionPresent'='true' + THEN b.descriptor_json::JSONB->>'scriptPatchVersion' ELSE NULL END) + IS NOT DISTINCT FROM a.script_patch_version + AND b.descriptor_json::JSONB->>'runtimeFlagsJson' IS NOT DISTINCT FROM a.runtime_flags_json + AND b.descriptor_json::JSONB->>'generationConfigRevision'=a.generation_config_revision + AND b.descriptor_json::JSONB->>'versionStateEpoch'=a.version_state_epoch::TEXT + AND b.descriptor_json::JSONB->>'releaseBundleId'=a.release_bundle_id::TEXT + AND b.descriptor_json::JSONB->>'publishedReleaseBundleRef'=a.published_release_bundle_ref + AND (CASE WHEN b.descriptor_json::JSONB->>'remapSetIdPresent'='true' + THEN b.descriptor_json::JSONB->>'remapSetId' ELSE NULL END) + IS NOT DISTINCT FROM a.remap_set_id + AND b.release_attestation_json::JSONB->>'targetNamespace'=a.canonical_target_namespace + AND b.release_attestation_json::JSONB->>'descriptorResultDigest'=a.descriptor_result_digest + AND b.release_attestation_json::JSONB->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND b.release_attestation_json::JSONB->>'canonicalVersionId'=a.canonical_version_id::TEXT + AND b.release_attestation_json::JSONB->>'worldSlug'=a.canonical_world_slug + AND b.release_attestation_json::JSONB->>'authoredWorldSourceOperationId'=a.source_operation_id::TEXT + AND b.release_attestation_json::JSONB->>'authoredWorldSourceEvidenceDigest'=a.source_evidence_digest + AND b.release_attestation_json::JSONB->>'launchDescriptorId'=a.launch_descriptor_id + AND b.release_attestation_json::JSONB->>'publishedReleaseBundleRef'=a.published_release_bundle_ref + AND b.release_attestation_json::JSONB->>'versionStateEpoch'=a.version_state_epoch::TEXT + AND b.release_attestation_json::JSONB->>'generationConfigRevision'=a.generation_config_revision + AND b.release_attestation_json::JSONB->>'evidenceDigest'=a.release_attestation_digest + AND s.target_namespace=a.canonical_target_namespace + AND s.canonical_tenant_id=a.canonical_tenant_id + AND s.world_slug=a.canonical_world_slug + AND s.local_tenant_key=a.local_tenant_key + AND s.intake_request_id=a.intake_request_id + AND s.source_operation_id=a.source_operation_id + AND s.source_evidence_digest=a.source_evidence_digest + AND s.request_digest=a.intake_request_digest + AND s.receipt_digest=a.intake_receipt_digest + AND v.target_namespace=a.canonical_target_namespace + AND v.canonical_tenant_id=a.canonical_tenant_id + AND v.world_slug=a.canonical_world_slug + AND v.canonical_version_id=a.canonical_version_id + AND v.local_tenant_key=a.local_tenant_key + AND v.local_version_key=a.local_version_key + AND v.intake_operation_id=a.intake_operation_id + AND v.intake_request_id=a.intake_request_id + AND v.intake_request_digest=a.intake_request_digest + AND v.source_operation_id=a.source_operation_id + AND v.source_evidence_digest=a.source_evidence_digest + AND v.intake_receipt_digest=a.intake_receipt_digest + AND v.game_design_version_id::TEXT=b.descriptor_json::JSONB->>'versionId' + -- Original version intake and later published launch are distinct captures. + -- Each epoch remains bound to its own retained evidence below and above. + AND p.target_namespace=a.canonical_target_namespace + AND p.canonical_tenant_id=a.canonical_tenant_id + AND p.world_slug=a.canonical_world_slug + AND p.control_plane_request_id=a.control_plane_request_id + AND p.canonical_version_id=a.canonical_version_id + AND p.version_identity_operation_id=a.version_identity_operation_id + AND p.world_instance_id=a.world_instance_id + AND p.private_game_instance_key=a.private_game_instance_key + AND p.capture_id::TEXT=lifecycle->>'captureId' + AND p.graph_sha256=lifecycle->>'graphSha256' + AND p.graph_sha256=encode(sha256(p.graph_bytes),'hex') + AND p.input_digest=lifecycle->>'preparationInputDigest' + AND p.input_digest=('sha256:' || encode(sha256(convert_to(p.input_json,'UTF8')),'hex')) + AND p.input_json::JSONB->>'schemaVersion'='2' + AND p.input_json::JSONB->'identity'->>'canonicalGameInstanceId'=a.canonical_game_instance_id::TEXT + AND p.input_json::JSONB->'identity'->>'targetNamespace'=a.canonical_target_namespace + AND p.input_json::JSONB->'identity'->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'identity'->>'worldSlug'=a.canonical_world_slug + AND p.input_json::JSONB->'identity'->>'playableStateNamespaceId'=a.playable_state_namespace_id::TEXT + AND p.input_json::JSONB->'identity'->>'playableStateScope'=a.playable_state_scope + AND p.input_json::JSONB->'identity'->'publicProduction'=to_jsonb(a.public_production) + AND p.input_json::JSONB->'identity'->>'controlPlaneRequestId'=a.control_plane_request_id + AND p.input_json::JSONB->'launchBinding'->>'operationId'=a.canonical_launch_binding_operation_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'targetNamespace'=b.target_namespace + AND p.input_json::JSONB->'launchBinding'->>'canonicalTenantId'=b.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'worldSlug'=b.world_slug + AND p.input_json::JSONB->'launchBinding'->>'controlPlaneRequestId'=b.control_plane_request_id + AND p.input_json::JSONB->'launchBinding'->>'canonicalVersionId'=b.canonical_version_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'descriptorRequestDigest'=b.descriptor_request_digest + AND p.input_json::JSONB->'launchBinding'->>'descriptorResultDigest'=b.descriptor_result_digest + AND p.input_json::JSONB->'launchBinding'->>'releaseAttestationDigest'=b.release_attestation_digest + AND p.input_json::JSONB->'launchBinding'->>'localTenantKey'=b.local_tenant_key::TEXT + AND p.input_json::JSONB->'launchBinding'->>'intakeOperationId'=b.intake_operation_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'intakeRequestId'=b.intake_request_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'sourceOperationId'=b.source_operation_id::TEXT + AND p.input_json::JSONB->'launchBinding'->>'sourceEvidenceDigest'=b.source_evidence_digest + AND p.input_json::JSONB->'launchBinding'->>'intakeRequestDigest'=s.request_digest + AND p.input_json::JSONB->'launchBinding'->>'intakeReceiptDigest'=s.receipt_digest + AND p.input_json::JSONB->'versionIdentity'->>'operationId'=v.operation_id::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'canonicalVersionId'=v.canonical_version_id::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'localVersionKey'=v.local_version_key::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'gameDesignVersionId'=v.game_design_version_id::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'versionState'= + CASE v.version_state_state + WHEN 'DRAFT' THEN 'VERSION_LIFECYCLE_STATE_DRAFT' + WHEN 'PUBLISHED' THEN 'VERSION_LIFECYCLE_STATE_PUBLISHED' + WHEN 'ACTIVE' THEN 'VERSION_LIFECYCLE_STATE_ACTIVE' + END + AND p.input_json::JSONB->'versionIdentity'->>'versionStateEpoch'=v.version_state_epoch::TEXT + AND p.input_json::JSONB->'versionIdentity'->>'evidenceDigest'=v.version_state_evidence_digest + AND p.input_json::JSONB->'sourceIntake'->>'schemaVersion'=s.schema_version::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'targetNamespace'=s.target_namespace + AND p.input_json::JSONB->'sourceIntake'->>'intakeRequestId'=s.intake_request_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'operationId'=s.operation_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'canonicalTenantId'=s.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'worldSlug'=s.world_slug + AND p.input_json::JSONB->'sourceIntake'->>'sourceOperationId'=s.source_operation_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->>'sourceEvidenceDigest'=s.source_evidence_digest + AND p.input_json::JSONB->'sourceIntake'->>'requestDigest'=s.request_digest + AND p.input_json::JSONB->'sourceIntake'->>'receiptDigest'=s.receipt_digest + AND p.input_json::JSONB->'sourceIntake'->>'localTenantKey'=s.local_tenant_key::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'schemaVersion'=s.source_schema_version::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'registrationRequestId'=s.source_registration_request_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'sourceOperationId'=s.source_operation_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'requestDigest'=s.source_request_digest + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'canonicalTenantId'=s.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'tenantSlug'=s.tenant_slug + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'worldSlug'=s.world_slug + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'worldDisplayName'=s.world_display_name + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'sourceGameRowId'=s.source_game_row_id::TEXT + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'sourceGameTenantKey'=s.source_game_tenant_key + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'provenanceKind'=s.source_provenance_kind + AND p.input_json::JSONB->'sourceIntake'->'sourceEvidence'->>'evidenceDigest'=s.source_evidence_digest + AND p.input_json::JSONB->'topology'->>'captureId'=p.capture_id::TEXT + AND p.input_json::JSONB->'topology'->>'targetNamespace'=a.canonical_target_namespace + AND p.input_json::JSONB->'topology'->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND p.input_json::JSONB->'topology'->>'canonicalVersionId'=a.canonical_version_id::TEXT + AND p.input_json::JSONB->'topology'->>'versionIdentityOperationId'=a.version_identity_operation_id::TEXT + AND lifecycle->'request'->>'schemaVersion'='1' + AND lifecycle->'request'->>'targetNamespace'=a.canonical_target_namespace + AND lifecycle->'request'->>'canonicalTenantId'=a.canonical_tenant_id::TEXT + AND lifecycle->'request'->>'worldSlug'=a.canonical_world_slug + AND lifecycle->'request'->>'canonicalGameInstanceId'=a.canonical_game_instance_id::TEXT + AND lifecycle->'request'->>'playableStateNamespaceId'=a.playable_state_namespace_id::TEXT + AND lifecycle->'request'->>'playableStateScope'=a.playable_state_scope + AND lifecycle->'request'->'publicProduction'=to_jsonb(a.public_production) + AND lifecycle->'request'->>'controlPlaneRequestId'=a.control_plane_request_id + AND lifecycle->'request'->>'canonicalVersionId'=a.canonical_version_id::TEXT + AND lifecycle->'request'->>'expectedDescriptorRequestDigest'=a.descriptor_request_digest + AND lifecycle->'request'->>'expectedDescriptorResultDigest'=a.descriptor_result_digest + AND lifecycle->'request'->>'expectedReleaseAttestationDigest'=a.release_attestation_digest + AND decode(preparing->>'launchBindingBytesBase64','base64') IS NOT NULL + AND convert_from(decode(preparing->>'launchBindingBytesBase64','base64'),'UTF8')::JSONB + IS NOT DISTINCT FROM jsonb_build_object( + 'descriptor', b.descriptor_json::JSONB, + 'releaseAttestation', b.release_attestation_json::JSONB) + AND start_row.world_instance_id=a.world_instance_id + AND start_row.canonical_tenant_id=a.canonical_tenant_id + AND start_row.canonical_version_id=a.canonical_version_id + AND lifecycle->'startLocation'->>'tenantId'=start_row.canonical_tenant_id::TEXT + AND lifecycle->'startLocation'->>'versionId'=start_row.canonical_version_id::TEXT + AND lifecycle->'startLocation'->>'roomTemplateId'=start_row.room_template_id::TEXT + AND lifecycle->>'runtimeRoomInstanceId'=start_row.runtime_room_instance_id::TEXT + AND lifecycle->>'captureId'=p.capture_id::TEXT + AND lifecycle->>'graphSha256'=p.graph_sha256 + AND lifecycle->>'preparationInputDigest'=p.input_digest + AND start_row.graph_digest=('sha256:' || p.graph_sha256) + AND start_row.evidence_bytes=decode(p.input_json::JSONB->>'worldStartLocationEvidenceBase64','base64') + AND m.runtime_room_instance_id=start_row.runtime_room_instance_id + AND m.runtime_row_id=r.id + AND r.template_room_id=m.template_private_row_key + AND r.tenant_id=a.local_tenant_key + AND r.game_instance_id=a.private_game_instance_key + AND runtime_region.tenant_id=a.local_tenant_key + AND runtime_region.game_instance_id=a.private_game_instance_key + ) THEN + RAISE EXCEPTION 'Canonical activation proof differs from immutable World association, launch, preparation, or ROOM bindings' + USING ERRCODE = '23514'; + END IF; + IF NEW.outcome = 'COMMITTED' THEN + IF instance.status IS DISTINCT FROM 'PREPARING' + OR instance.lifecycle_epoch IS DISTINCT FROM NEW.expected_lifecycle_epoch + OR instance.row_version IS DISTINCT FROM NEW.expected_row_version + OR lifecycle->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' THEN + RAISE EXCEPTION 'Committed canonical activation lacks the exact current PREPARING CAS' + USING ERRCODE = '23514'; + END IF; + activated_instance := instance; + activated_instance.status := 'ACTIVE'; + activated_instance.lifecycle_epoch := NEW.result_lifecycle_epoch; + activated_instance.row_version := NEW.result_row_version; + activated_instance.updated_at := CURRENT_TIMESTAMP; + INSERT INTO "${serviceSchema}".world_canonical_activation_execution_manifest + (transaction_id, activation_request_id, request_digest, result_digest, + canonical_game_instance_id, world_instance_id, local_tenant_key, + private_game_instance_key, expected_old, expected_new) + VALUES (txid_current(), NEW.activation_request_id, NEW.request_digest, NEW.result_digest, + NEW.canonical_game_instance_id, NEW.world_instance_id, association_row.local_tenant_key, + association_row.private_game_instance_key, to_jsonb(instance), to_jsonb(activated_instance)); + ELSIF lifecycle->>'lifecycleStatus' IS DISTINCT FROM instance.status + OR lifecycle->>'lifecycleEpoch' IS DISTINCT FROM instance.lifecycle_epoch::TEXT + OR lifecycle->>'rowVersion' IS DISTINCT FROM instance.row_version::TEXT THEN + RAISE EXCEPTION 'Aborted canonical activation must retain the actual current lifecycle state' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_validate_canonical_activation_operation() FROM PUBLIC; +CREATE TRIGGER trg_world_canonical_activation_operation + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_instance_activation_operation + FOR EACH ROW EXECUTE FUNCTION world_validate_canonical_activation_operation(); + +CREATE FUNCTION world_reject_canonical_activation_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'Canonical World activation operation evidence is immutable and retained' + USING ERRCODE = '55000'; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_reject_canonical_activation_truncate() FROM PUBLIC; +CREATE TRIGGER trg_world_canonical_activation_operation_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_activation_operation + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_canonical_activation_truncate(); + +CREATE FUNCTION world_consume_canonical_activation_execution_manifest( + actual_schema TEXT, actual_table TEXT, actual_operation TEXT, + actual_old JSONB, actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed UUID; +BEGIN + IF actual_schema IS DISTINCT FROM '${serviceSchema}' + OR actual_table IS DISTINCT FROM 'world_instance' + OR actual_operation IS DISTINCT FROM 'UPDATE' + OR actual_old IS NULL OR actual_new IS NULL THEN + RETURN FALSE; + END IF; + DELETE FROM "${serviceSchema}".world_canonical_activation_execution_manifest m + USING "${serviceSchema}".world_canonical_instance_activation_operation o, + "${serviceSchema}".world_canonical_instance_association a + WHERE m.transaction_id = txid_current() + AND m.expected_old = actual_old AND m.expected_new = actual_new + AND m.world_instance_id = (actual_old->>'id')::BIGINT + AND m.world_instance_id = (actual_new->>'id')::BIGINT + AND m.canonical_game_instance_id::TEXT = actual_old->>'canonical_game_instance_id' + AND m.canonical_game_instance_id::TEXT = actual_new->>'canonical_game_instance_id' + AND m.local_tenant_key = (actual_old->>'tenant_id')::BIGINT + AND m.local_tenant_key = (actual_new->>'tenant_id')::BIGINT + AND m.private_game_instance_key = (actual_old->>'game_instance_id')::BIGINT + AND m.private_game_instance_key = (actual_new->>'game_instance_id')::BIGINT + AND o.activation_request_id = m.activation_request_id + AND o.request_digest = m.request_digest AND o.result_digest = m.result_digest + AND o.canonical_game_instance_id = m.canonical_game_instance_id + AND o.world_instance_id = m.world_instance_id AND o.outcome = 'COMMITTED' + AND actual_old->>'status' = 'PREPARING' AND actual_new->>'status' = 'ACTIVE' + AND o.expected_lifecycle_epoch = (actual_old->>'lifecycle_epoch')::BIGINT + AND o.expected_row_version = (actual_old->>'row_version')::BIGINT + AND o.result_lifecycle_epoch = (actual_new->>'lifecycle_epoch')::BIGINT + AND o.result_row_version = (actual_new->>'row_version')::BIGINT + AND convert_from(o.result_bytes, 'UTF8')::JSONB->>'outcome' = 'COMMITTED' + AND convert_from(o.result_bytes, 'UTF8')::JSONB->>'requestDigest' = m.request_digest + AND a.canonical_game_instance_id = m.canonical_game_instance_id + AND a.world_instance_id = m.world_instance_id + AND a.local_tenant_key = m.local_tenant_key + AND a.private_game_instance_key = m.private_game_instance_key + RETURNING m.activation_request_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_consume_canonical_activation_execution_manifest(TEXT, TEXT, TEXT, JSONB, JSONB) + FROM PUBLIC; + +-- Extend V35's guard at one exact anchor, retaining its region/preparation paths and legacy denial. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ RAISE EXCEPTION + 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest'$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_claim_legacy_numeric_tenant_key()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one reserved-tenant execution denial guard'; + END IF; + original := replace(original,anchor,$replacement$ IF "${serviceSchema}".world_consume_canonical_activation_execution_manifest( + TG_TABLE_SCHEMA, TG_TABLE_NAME, TG_OP, old_row, new_row) THEN + RETURN NEW; + END IF; +$replacement$ || anchor); + EXECUTE original; +END; +$migration$; + +CREATE FUNCTION world_require_committed_activation_at_commit() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + instance "${serviceSchema}".world_instance%ROWTYPE; + result JSONB; +BEGIN + IF NEW.outcome <> 'COMMITTED' THEN RETURN NULL; END IF; + SELECT * INTO instance FROM "${serviceSchema}".world_instance + WHERE id=NEW.world_instance_id AND canonical_game_instance_id=NEW.canonical_game_instance_id; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF NOT FOUND + OR instance.status IS DISTINCT FROM 'ACTIVE' + OR instance.lifecycle_epoch IS DISTINCT FROM NEW.result_lifecycle_epoch + OR instance.row_version IS DISTINCT FROM NEW.result_row_version + OR result->>'outcome' IS DISTINCT FROM 'COMMITTED' + OR result->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_activation_execution_manifest m + WHERE m.transaction_id = txid_current() AND m.activation_request_id = NEW.activation_request_id) + OR convert_from(decode(result->>'lifecycleEvidenceBytesBase64','base64'),'UTF8')::JSONB->>'lifecycleStatus' + IS DISTINCT FROM 'ACTIVE' THEN + RAISE EXCEPTION 'Committed canonical activation must include its exact ACTIVE lifecycle CAS before commit' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_require_committed_activation_at_commit() FROM PUBLIC; +CREATE CONSTRAINT TRIGGER trg_world_canonical_activation_commit_cas + AFTER INSERT ON world_canonical_instance_activation_operation + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_committed_activation_at_commit(); + +CREATE FUNCTION world_guard_canonical_activation_transition() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF OLD.canonical_game_instance_id IS NOT NULL AND NEW.status = 'ACTIVE' + AND (OLD.status IS DISTINCT FROM NEW.status + OR OLD.lifecycle_epoch IS DISTINCT FROM NEW.lifecycle_epoch + OR OLD.row_version IS DISTINCT FROM NEW.row_version) THEN + IF OLD.status IS DISTINCT FROM 'PREPARING' + OR NEW.lifecycle_epoch IS DISTINCT FROM OLD.lifecycle_epoch + 1 + OR NEW.row_version IS DISTINCT FROM OLD.row_version + 1 + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_activation_operation o + WHERE o.canonical_game_instance_id = OLD.canonical_game_instance_id + AND o.world_instance_id = OLD.id + AND o.outcome = 'COMMITTED' + AND o.expected_lifecycle_epoch = OLD.lifecycle_epoch + AND o.expected_row_version = OLD.row_version + AND o.result_lifecycle_epoch = NEW.lifecycle_epoch + AND o.result_row_version = NEW.row_version + AND convert_from(o.result_bytes, 'UTF8')::JSONB->>'outcome' = 'COMMITTED') THEN + RAISE EXCEPTION 'Canonical World PREPARING-to-ACTIVE transition requires its exact activation operation' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_guard_canonical_activation_transition() FROM PUBLIC; +CREATE TRIGGER trg_world_canonical_activation_transition + BEFORE UPDATE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_guard_canonical_activation_transition(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql b/services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql new file mode 100644 index 0000000000..9547215d6c --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V44__world_publication_terminal_handoff.sql @@ -0,0 +1,354 @@ +-- Retain the authenticated Game Design terminal result before World leaves FROZEN. The owner +-- transition and immutable receipt are committed atomically; absence or uncertainty never settles. +CREATE TABLE world_design_publication_terminal ( + publication_fence UUID PRIMARY KEY + REFERENCES world_design_publication_fence_attempt(publication_fence) ON DELETE RESTRICT, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + publication_request_id VARCHAR(256) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + publish_workflow_id VARCHAR(537) NOT NULL, + freeze_version_state_epoch BIGINT NOT NULL CHECK (freeze_version_state_epoch > 0), + applied_commit_id VARCHAR(256) NOT NULL, + content_digest VARCHAR(64) NOT NULL, + digest_schema_version INTEGER NOT NULL CHECK (digest_schema_version > 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('PUBLISHED', 'NO_PUBLICATION')), + publication_version_state_epoch BIGINT, + published_release_bundle_ref VARCHAR(512), + published_release_bundle_digest VARCHAR(71), + operation_bytes BYTEA NOT NULL CHECK (octet_length(operation_bytes) > 0), + terminal_evidence_bytes BYTEA NOT NULL CHECK (octet_length(terminal_evidence_bytes) > 0), + terminal_evidence_digest VARCHAR(64) NOT NULL CHECK (terminal_evidence_digest ~ '^[0-9a-f]{64}$'), + world_evidence_bytes BYTEA NOT NULL CHECK (octet_length(world_evidence_bytes) > 0), + world_request_json TEXT NOT NULL, + selector_receipt_bytes BYTEA NOT NULL CHECK (octet_length(selector_receipt_bytes) > 0), + original_account_binding_bytes BYTEA NOT NULL CHECK (octet_length(original_account_binding_bytes) > 0), + applied_result_bytes BYTEA NOT NULL CHECK (octet_length(applied_result_bytes) > 0), + release_content_bytes BYTEA NOT NULL, + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_world_publication_terminal_scope_request UNIQUE + (target_namespace, canonical_tenant_id, canonical_version_id, publication_request_id), + CONSTRAINT ck_world_publication_terminal_identity CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND octet_length(publication_request_id) BETWEEN 1 AND 256 + AND position(':' IN publication_request_id) = 0 + AND request_digest ~ '^[0-9a-f]{64}$' + AND publish_workflow_id = 'publish:' || canonical_tenant_id::TEXT + || ':publish-request:' || publication_request_id + AND octet_length(applied_commit_id) BETWEEN 1 AND 256 + AND content_digest ~ '^[0-9a-f]{64}$' + ), + CONSTRAINT ck_world_publication_terminal_outcome_shape CHECK ( + (outcome = 'PUBLISHED' + AND publication_version_state_epoch IS NOT NULL + AND publication_version_state_epoch = freeze_version_state_epoch + 1 + AND published_release_bundle_ref IS NOT NULL + AND octet_length(published_release_bundle_ref) BETWEEN 1 AND 512 + AND published_release_bundle_digest IS NOT NULL + AND published_release_bundle_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(release_content_bytes) > 0) + OR + (outcome = 'NO_PUBLICATION' + AND publication_version_state_epoch IS NULL + AND published_release_bundle_ref IS NULL + AND published_release_bundle_digest IS NULL + AND octet_length(release_content_bytes) = 0) + ) +); + +-- [jooq ignore start] +REVOKE ALL ON world_design_publication_terminal FROM PUBLIC; + +CREATE FUNCTION world_validate_publication_terminal() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + frozen "${serviceSchema}".world_canonical_frozen_topology%ROWTYPE; + receipt "${serviceSchema}".world_draft_start_location_receipt%ROWTYPE; + application "${serviceSchema}".world_draft_graph_application%ROWTYPE; + graph "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + identity_row "${serviceSchema}".world_authored_version_identity%ROWTYPE; + intake_row "${serviceSchema}".world_authored_source_intake%ROWTYPE; + world_request JSONB; + world_evidence JSONB; + freeze_request JSONB; + expected_tuples JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World publication terminal evidence is immutable' USING ERRCODE = '55000'; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'World publication terminal requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT attempt FROM "${serviceSchema}".world_design_publication_fence_attempt + WHERE publication_fence=NEW.publication_fence; + SELECT * INTO STRICT owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace=attempt.target_namespace + AND canonical_tenant_id=attempt.canonical_tenant_id + AND local_tenant_key=attempt.local_tenant_key AND version_id=attempt.version_id + FOR UPDATE; + SELECT * INTO STRICT frozen FROM "${serviceSchema}".world_canonical_frozen_topology + WHERE publication_fence=NEW.publication_fence; + SELECT * INTO STRICT identity_row FROM "${serviceSchema}".world_authored_version_identity + WHERE operation_id=attempt.version_identity_operation_id; + SELECT * INTO STRICT intake_row FROM "${serviceSchema}".world_authored_source_intake + WHERE operation_id=attempt.intake_operation_id; + SELECT * INTO STRICT graph FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + SELECT * INTO STRICT receipt FROM "${serviceSchema}".world_draft_start_location_receipt + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id; + SELECT * INTO STRICT application FROM "${serviceSchema}".world_draft_graph_application + WHERE request_id=frozen.request_id AND commit_id=frozen.commit_id + AND operation_id=receipt.operation_id; + + world_request := NEW.world_request_json::JSONB; + world_evidence := convert_from(NEW.world_evidence_bytes, 'UTF8')::JSONB; + freeze_request := frozen.freeze_request_json::JSONB; + SELECT coalesce(jsonb_agg(value ORDER BY value->>'owner',value->>'aggregateType',value->>'aggregateId', + value->>'scopeType',value->>'scopeId',value->>'expectedEpoch'), '[]'::JSONB) + INTO expected_tuples FROM jsonb_array_elements(freeze_request->'suppliedOwnedAffectedTuples'); + + IF attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR owner_row.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence + OR NEW.target_namespace IS DISTINCT FROM attempt.target_namespace + OR NEW.canonical_tenant_id IS DISTINCT FROM attempt.canonical_tenant_id + OR NEW.canonical_version_id IS DISTINCT FROM attempt.canonical_version_id + OR NEW.publication_request_id IS DISTINCT FROM attempt.publication_request_id + OR NEW.request_digest IS DISTINCT FROM attempt.request_digest + OR NEW.publish_workflow_id IS DISTINCT FROM attempt.publish_workflow_id + OR NEW.freeze_version_state_epoch IS DISTINCT FROM attempt.version_state_epoch + OR NEW.applied_commit_id IS DISTINCT FROM attempt.applied_commit_id + OR NEW.content_digest IS DISTINCT FROM attempt.content_digest + OR NEW.digest_schema_version IS DISTINCT FROM attempt.digest_schema_version THEN + RAISE EXCEPTION 'World terminal differs from exact current V25 publication owner' + USING ERRCODE = '23514'; + END IF; + + IF encode(sha256(NEW.terminal_evidence_bytes), 'hex') IS DISTINCT FROM NEW.terminal_evidence_digest + OR jsonb_typeof(world_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(world_request)) <> 13 + OR jsonb_typeof(world_evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(world_evidence)) <> 5 + OR world_evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR world_evidence->'request' IS DISTINCT FROM world_request + OR decode(world_evidence->>'selectorReceiptBytesBase64','base64') IS DISTINCT FROM NEW.selector_receipt_bytes + OR decode(world_evidence->>'originalAccountBindingBytesBase64','base64') IS DISTINCT FROM NEW.original_account_binding_bytes + OR decode(world_evidence->>'appliedResultBytesBase64','base64') IS DISTINCT FROM NEW.applied_result_bytes + OR world_request->>'targetNamespace' IS DISTINCT FROM attempt.target_namespace + OR world_request->>'canonicalTenantId' IS DISTINCT FROM attempt.canonical_tenant_id::TEXT + OR world_request->>'canonicalVersionId' IS DISTINCT FROM attempt.canonical_version_id::TEXT + OR world_request->>'intakeRequestId' IS DISTINCT FROM attempt.intake_request_id::TEXT + OR world_request->>'publicationFence' IS DISTINCT FROM attempt.publication_fence::TEXT + OR world_request->>'publicationRequestId' IS DISTINCT FROM attempt.publication_request_id + OR world_request->>'requestDigest' IS DISTINCT FROM attempt.request_digest + OR world_request->>'versionStateEpoch' IS DISTINCT FROM attempt.version_state_epoch::TEXT + OR world_request->>'publishWorkflowId' IS DISTINCT FROM attempt.publish_workflow_id + OR world_request->>'appliedCommitId' IS DISTINCT FROM attempt.applied_commit_id + OR world_request->>'contentDigest' IS DISTINCT FROM attempt.content_digest + OR world_request->>'digestSchemaVersion' IS DISTINCT FROM attempt.digest_schema_version::TEXT + OR world_request->'worldAffectedTuples' IS DISTINCT FROM expected_tuples + OR freeze_request->>'targetNamespace' IS DISTINCT FROM attempt.target_namespace + OR freeze_request->>'canonicalTenantId' IS DISTINCT FROM attempt.canonical_tenant_id::TEXT + OR freeze_request->>'canonicalVersionId' IS DISTINCT FROM attempt.canonical_version_id::TEXT + OR freeze_request->>'publicationFence' IS DISTINCT FROM attempt.publication_fence::TEXT + OR freeze_request->>'publicationRequestId' IS DISTINCT FROM attempt.publication_request_id + OR freeze_request->>'requestDigest' IS DISTINCT FROM attempt.request_digest + OR freeze_request->>'versionStateEpoch' IS DISTINCT FROM attempt.version_state_epoch::TEXT + OR freeze_request->>'publishWorkflowId' IS DISTINCT FROM attempt.publish_workflow_id + OR freeze_request->>'appliedCommitId' IS DISTINCT FROM attempt.applied_commit_id + OR freeze_request->>'contentDigest' IS DISTINCT FROM attempt.content_digest + OR freeze_request->>'digestSchemaVersion' IS DISTINCT FROM attempt.digest_schema_version::TEXT + OR identity_row.target_namespace IS DISTINCT FROM attempt.target_namespace + OR identity_row.canonical_tenant_id IS DISTINCT FROM attempt.canonical_tenant_id + OR identity_row.canonical_version_id IS DISTINCT FROM attempt.canonical_version_id + OR identity_row.local_tenant_key IS DISTINCT FROM attempt.local_tenant_key + OR identity_row.local_version_key IS DISTINCT FROM attempt.version_id + OR identity_row.intake_operation_id IS DISTINCT FROM attempt.intake_operation_id + OR identity_row.intake_request_id IS DISTINCT FROM attempt.intake_request_id + OR identity_row.source_operation_id IS DISTINCT FROM attempt.source_operation_id + OR identity_row.source_evidence_digest IS DISTINCT FROM attempt.source_evidence_digest + OR identity_row.intake_receipt_digest IS DISTINCT FROM attempt.intake_receipt_digest + OR intake_row.target_namespace IS DISTINCT FROM attempt.target_namespace + OR intake_row.canonical_tenant_id IS DISTINCT FROM attempt.canonical_tenant_id + OR intake_row.local_tenant_key IS DISTINCT FROM attempt.local_tenant_key + OR intake_row.intake_request_id IS DISTINCT FROM attempt.intake_request_id + OR intake_row.source_operation_id IS DISTINCT FROM attempt.source_operation_id + OR intake_row.source_evidence_digest IS DISTINCT FROM attempt.source_evidence_digest + OR intake_row.receipt_digest IS DISTINCT FROM attempt.intake_receipt_digest + OR frozen.request_id IS DISTINCT FROM graph.request_id + OR frozen.commit_id IS DISTINCT FROM graph.commit_id + OR frozen.graph_bytes IS DISTINCT FROM graph.graph_bytes + OR application.account_binding_bytes IS DISTINCT FROM NEW.original_account_binding_bytes + OR receipt.account_binding_bytes IS DISTINCT FROM NEW.original_account_binding_bytes + OR receipt.receipt_bytes IS DISTINCT FROM NEW.selector_receipt_bytes + OR application.result_bytes IS DISTINCT FROM NEW.applied_result_bytes + OR graph.binding_digest IS DISTINCT FROM receipt.binding_digest + OR receipt.graph_digest IS DISTINCT FROM ('sha256:' || frozen.graph_sha256) THEN + RAISE EXCEPTION 'World terminal does not bind the exact immutable source, selector, APPLIED result and freeze checkpoint' + USING ERRCODE = '23514'; + END IF; + IF NEW.outcome='PUBLISHED' + AND (NEW.publication_version_state_epoch IS DISTINCT FROM attempt.version_state_epoch + 1 + OR NEW.published_release_bundle_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.release_content_bytes), 'hex'))) THEN + RAISE EXCEPTION 'PUBLISHED World terminal lacks the exact next Game Design publication epoch' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_publication_terminal_validate + BEFORE INSERT ON world_design_publication_terminal FOR EACH ROW + EXECUTE FUNCTION world_validate_publication_terminal(); +CREATE TRIGGER trg_world_publication_terminal_immutable + BEFORE UPDATE OR DELETE ON world_design_publication_terminal FOR EACH ROW + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +CREATE TRIGGER trg_world_publication_terminal_no_truncate + BEFORE TRUNCATE ON world_design_publication_terminal FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); + +-- A valid-looking receipt is not a terminal result until the same transaction commits the +-- matching owner phase. This deferred check observes the post-CAS row at transaction commit. +CREATE FUNCTION world_require_publication_terminal_owner_phase() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + expected_phase TEXT; + actual_phase TEXT; +BEGIN + expected_phase := CASE WHEN NEW.outcome='PUBLISHED' THEN 'PUBLISHED' ELSE 'ABORTED' END; + SELECT o.owner_freeze_phase INTO actual_phase + FROM "${serviceSchema}".world_design_publication_fence_attempt a + JOIN "${serviceSchema}".world_design_publication_fence_owner o + ON o.target_namespace=a.target_namespace + AND o.canonical_tenant_id=a.canonical_tenant_id + AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id + WHERE a.publication_fence=NEW.publication_fence + AND a.owner_binding_schema_version=1 + AND a.target_namespace=NEW.target_namespace + AND a.canonical_tenant_id=NEW.canonical_tenant_id + AND a.canonical_version_id=NEW.canonical_version_id + AND a.publication_request_id=NEW.publication_request_id + AND a.request_digest=NEW.request_digest + AND a.publish_workflow_id=NEW.publish_workflow_id + AND a.version_state_epoch=NEW.freeze_version_state_epoch + AND a.applied_commit_id=NEW.applied_commit_id + AND a.content_digest=NEW.content_digest + AND a.digest_schema_version=NEW.digest_schema_version + AND o.current_publication_fence=NEW.publication_fence; + IF NOT FOUND OR actual_phase IS DISTINCT FROM expected_phase THEN + RAISE EXCEPTION 'World terminal receipt must commit with its exact owner phase' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER trg_world_publication_terminal_owner_phase_commit + AFTER INSERT ON world_design_publication_terminal + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_publication_terminal_owner_phase(); + +-- Preserve the original OPEN-to-FROZEN writer while allowing only a just-inserted immutable V44 +-- terminal row to authorize FROZEN-to-PUBLISHED/ABORTED. No reopen or reconciliation transition +-- is introduced by this migration. +CREATE OR REPLACE FUNCTION world_protect_publication_fence_owner() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'World publication-fence owner rows cannot be deleted' USING ERRCODE = '55000'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.owner_freeze_phase = 'OPEN' AND NEW.current_publication_fence IS NULL THEN RETURN NEW; END IF; + RAISE EXCEPTION 'World publication-fence owner rows must be created OPEN without a fence' USING ERRCODE = '55000'; + END IF; + IF OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + AND OLD.local_tenant_key IS NOT DISTINCT FROM NEW.local_tenant_key + AND OLD.version_id IS NOT DISTINCT FROM NEW.version_id + AND OLD.owner_freeze_phase='OPEN' AND NEW.owner_freeze_phase='FROZEN' + AND OLD.current_publication_fence IS NULL AND NEW.current_publication_fence IS NOT NULL THEN + RETURN NEW; + END IF; + IF OLD.target_namespace IS NOT DISTINCT FROM NEW.target_namespace + AND OLD.canonical_tenant_id IS NOT DISTINCT FROM NEW.canonical_tenant_id + AND OLD.local_tenant_key IS NOT DISTINCT FROM NEW.local_tenant_key + AND OLD.version_id IS NOT DISTINCT FROM NEW.version_id + AND OLD.owner_freeze_phase='FROZEN' + AND OLD.current_publication_fence IS NOT DISTINCT FROM NEW.current_publication_fence + AND NEW.owner_freeze_phase IN ('PUBLISHED','ABORTED') + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_design_publication_terminal t + WHERE t.publication_fence=OLD.current_publication_fence + AND t.target_namespace=OLD.target_namespace + AND t.canonical_tenant_id=OLD.canonical_tenant_id + AND t.canonical_version_id=(SELECT a.canonical_version_id + FROM "${serviceSchema}".world_design_publication_fence_attempt a + WHERE a.publication_fence=OLD.current_publication_fence) + AND ((NEW.owner_freeze_phase='PUBLISHED' AND t.outcome='PUBLISHED') + OR (NEW.owner_freeze_phase='ABORTED' AND t.outcome='NO_PUBLICATION')) + ) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'World publication-fence owner binding or phase transition is immutable' + USING ERRCODE = '55000'; +END; +$$; + +-- Fresh allocation now requires the completed terminal handoff, not merely the earlier freeze. +-- All other V35/V40 guards, source checks and historical input bytes remain unchanged. +DO $migration$ +DECLARE + original TEXT; + phase_anchor TEXT := $anchor$ IF publication_owner.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR publication_owner.current_publication_fence IS DISTINCT FROM capture_row.publication_fence THEN + RAISE EXCEPTION 'Canonical preparation requires the exact still-FROZEN V25 source owner' + USING ERRCODE = '23514'; + END IF;$anchor$; + replacement TEXT := $replacement$ IF publication_owner.owner_freeze_phase IS DISTINCT FROM 'PUBLISHED' + OR publication_owner.current_publication_fence IS DISTINCT FROM capture_row.publication_fence + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_design_publication_terminal t + WHERE t.publication_fence=capture_row.publication_fence + AND t.target_namespace=identity_row.target_namespace + AND t.canonical_tenant_id=identity_row.canonical_tenant_id + AND t.canonical_version_id=identity_row.canonical_version_id + AND t.outcome='PUBLISHED' + AND t.publication_request_id=capture_row.freeze_request_json::JSONB->>'publicationRequestId' + AND t.request_digest=capture_row.freeze_request_json::JSONB->>'requestDigest' + AND t.publish_workflow_id=capture_row.freeze_request_json::JSONB->>'publishWorkflowId' + AND t.applied_commit_id=capture_row.freeze_request_json::JSONB->>'appliedCommitId' + AND t.content_digest=capture_row.freeze_request_json::JSONB->>'contentDigest' + AND t.digest_schema_version=(capture_row.freeze_request_json::JSONB->>'digestSchemaVersion')::INTEGER + AND t.published_release_bundle_ref=binding_row.release_attestation_json::JSONB->>'publishedReleaseBundleRef' + AND t.publication_version_state_epoch<=(binding_row.release_attestation_json::JSONB->>'versionStateEpoch')::BIGINT + AND t.world_request_json::JSONB=jsonb_set( + binding_row.release_attestation_json::JSONB->'worldStartLocationEvidence'->'request', + '{versionStateEpoch}',to_jsonb(t.freeze_version_state_epoch::TEXT),FALSE) + ) THEN + RAISE EXCEPTION 'Canonical preparation requires the exact published V44 terminal for this retained release and frozen World source' + USING ERRCODE = '23514'; + END IF;$replacement$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,phase_anchor,'')))/length(phase_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V35 FROZEN preparation phase guard'; + END IF; + EXECUTE replace(original,phase_anchor,replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V45__world_operational_region_assignment.sql b/services/world-management-service/src/main/resources/db/migration/V45__world_operational_region_assignment.sql new file mode 100644 index 0000000000..c308d03d0d --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V45__world_operational_region_assignment.sql @@ -0,0 +1,93 @@ +-- World owns the assignment label; Game Session registers it and owns its operational epoch/fence. +-- The assignment is separate from the canonical topology UUID. +-- Historical rows remain unassigned until a separately authorized migration can prove identity. +ALTER TABLE region_instance + ADD COLUMN operational_region_id UUID; + +ALTER TABLE region_instance + ADD CONSTRAINT uq_region_instance_operational_region + UNIQUE (tenant_id, game_instance_id, operational_region_id), + ADD CONSTRAINT ck_region_instance_operational_region_non_nil_and_distinct + CHECK ( + operational_region_id IS NULL + OR (operational_region_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND operational_region_id IS DISTINCT FROM canonical_region_instance_id) + ); + +-- [jooq ignore start] +CREATE FUNCTION reject_region_instance_operational_assignment_tuple_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.operational_region_id IS DISTINCT FROM OLD.operational_region_id + OR ( + OLD.operational_region_id IS NOT NULL + AND ( + NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.game_instance_id IS DISTINCT FROM OLD.game_instance_id + OR NEW.world_instance_id IS DISTINCT FROM OLD.world_instance_id + ) + ) THEN + RAISE EXCEPTION 'region_instance operational assignment tuple is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_region_instance_operational_assignment_tuple_immutable + BEFORE UPDATE ON region_instance + FOR EACH ROW + EXECUTE FUNCTION reject_region_instance_operational_assignment_tuple_change(); + +-- V35 writes region_instance directly, so preserve its manifest and row write while adding an +-- independent operational UUID to the exact composite inserted by that canonical producer. +DO $migration$ +DECLARE + original TEXT; + original_oid OID; + original_acl ACLITEM[]; + declaration_anchor TEXT := $anchor$ runtime_uuid UUID;$anchor$; + declaration_replacement TEXT := $replacement$ runtime_uuid UUID; + operational_runtime_uuid UUID;$replacement$; + allocation_anchor TEXT := $anchor$ runtime_uuid := gen_random_uuid(); + region_runtime := jsonb_populate_record$anchor$; + allocation_replacement TEXT := $replacement$ runtime_uuid := gen_random_uuid(); + operational_runtime_uuid := gen_random_uuid(); + WHILE operational_runtime_uuid = runtime_uuid LOOP + operational_runtime_uuid := gen_random_uuid(); + END LOOP; + region_runtime := jsonb_populate_record$replacement$; + region_anchor TEXT := $anchor$ 'canonical_region_instance_id', runtime_uuid));$anchor$; + region_replacement TEXT := $replacement$ 'canonical_region_instance_id', runtime_uuid, + 'operational_region_id', operational_runtime_uuid));$replacement$; +BEGIN + SELECT p.oid, p.proacl + INTO STRICT original_oid, original_acl + FROM pg_proc p + WHERE p.oid = '"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE; + SELECT pg_get_functiondef( + '"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, declaration_anchor, ''))) + / length(declaration_anchor) <> 1 + OR (length(original) - length(replace(original, allocation_anchor, ''))) + / length(allocation_anchor) <> 1 + OR (length(original) - length(replace(original, region_anchor, ''))) + / length(region_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one canonical region materialization insertion site'; + END IF; + original := replace(original, declaration_anchor, declaration_replacement); + original := replace(original, allocation_anchor, allocation_replacement); + original := replace(original, region_anchor, region_replacement); + EXECUTE original; + IF '"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE + IS DISTINCT FROM original_oid + OR (SELECT p.proacl FROM pg_proc p WHERE p.oid = original_oid) + IS DISTINCT FROM original_acl THEN + RAISE EXCEPTION 'Canonical preparation replacement changed function identity or grants'; + END IF; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V46__world_canonical_initial_player_location.sql b/services/world-management-service/src/main/resources/db/migration/V46__world_canonical_initial_player_location.sql new file mode 100644 index 0000000000..32421ff4cf --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V46__world_canonical_initial_player_location.sql @@ -0,0 +1,458 @@ +-- Fresh canonical actor placement is World-owned and runtime-instance scoped (S3). The target +-- retains its typed V42 authored ROOM selector and mapped runtime room; this migration adds only +-- the actor's first placement and its exact operation result, with no retained-row backfill. +CREATE TABLE world_canonical_initial_player_location_operation ( + canonical_tenant_id UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + canonical_game_instance_id UUID NOT NULL, + operation_id UUID NOT NULL, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) > 0), + original_lifecycle_evidence_bytes BYTEA NOT NULL CHECK (octet_length(original_lifecycle_evidence_bytes) > 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('APPLIED', 'CONFLICT')), + conflict_code VARCHAR(64), + result_bytes BYTEA NOT NULL CHECK (octet_length(result_bytes) > 0), + result_digest VARCHAR(71) NOT NULL CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (operation_id), + CONSTRAINT fk_world_initial_location_operation_association + FOREIGN KEY (canonical_game_instance_id) + REFERENCES world_canonical_instance_association(canonical_game_instance_id) ON DELETE RESTRICT, + CONSTRAINT ck_world_initial_location_operation_ids CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_initial_location_operation_outcome CHECK ( + (outcome = 'APPLIED' AND conflict_code IS NULL) + OR (outcome = 'CONFLICT' AND conflict_code IS NOT NULL + AND conflict_code COLLATE "C" ~ '^[A-Z][A-Z0-9_]{0,63}$' + AND conflict_code COLLATE "C" !~ '[^A-Z0-9_]') + ) +); + +CREATE TABLE character_location ( + canonical_tenant_id UUID NOT NULL, + realm_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(16) NOT NULL CHECK (playable_state_scope IN ('SHARED', 'ISOLATED')), + canonical_game_instance_id UUID NOT NULL, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + canonical_account_id UUID NOT NULL, + character_id UUID NOT NULL, + entity_assignment_operation_id UUID NOT NULL, + entity_assignment_digest CHAR(64) NOT NULL CHECK (entity_assignment_digest ~ '^[0-9a-f]{64}$'), + canonical_version_id UUID NOT NULL, + active_lifecycle_epoch BIGINT NOT NULL CHECK (active_lifecycle_epoch > 0), + initial_room_template_id UUID NOT NULL, + initial_runtime_room_instance_id BIGINT NOT NULL CHECK (initial_runtime_room_instance_id > 0), + runtime_room_instance_id BIGINT NOT NULL CHECK (runtime_room_instance_id > 0), + initial_admission_hold_id UUID NOT NULL, + initial_admission_hold_fence UUID NOT NULL, + initial_admission_request_id VARCHAR(128) NOT NULL CHECK (btrim(initial_admission_request_id) <> ''), + initial_admission_request_digest CHAR(64) NOT NULL CHECK (initial_admission_request_digest ~ '^[0-9a-f]{64}$'), + catalog_revision BIGINT NOT NULL CHECK (catalog_revision > 0), + initial_admission_owner_proof_id VARCHAR(128) NOT NULL CHECK (btrim(initial_admission_owner_proof_id) <> ''), + initial_admission_owner_proof_digest CHAR(64) NOT NULL CHECK (initial_admission_owner_proof_digest ~ '^[0-9a-f]{64}$'), + pointer_audit_id VARCHAR(128) NOT NULL CHECK (btrim(pointer_audit_id) <> ''), + pointer_version BIGINT NOT NULL CHECK (pointer_version > 0), + initial_location_operation_id UUID NOT NULL, + initial_location_request_digest VARCHAR(71) NOT NULL CHECK (initial_location_request_digest ~ '^sha256:[0-9a-f]{64}$'), + initial_lifecycle_evidence_bytes BYTEA NOT NULL CHECK (octet_length(initial_lifecycle_evidence_bytes) > 0), + initial_lifecycle_evidence_digest VARCHAR(71) NOT NULL CHECK (initial_lifecycle_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + row_version BIGINT NOT NULL DEFAULT 0 CHECK (row_version >= 0), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (canonical_tenant_id, playable_state_namespace_id, canonical_game_instance_id, + character_id), + CONSTRAINT uq_world_character_assignment_operation + UNIQUE (canonical_tenant_id, playable_state_namespace_id, canonical_game_instance_id, + entity_assignment_operation_id), + CONSTRAINT fk_world_character_location_association + FOREIGN KEY (canonical_game_instance_id) + REFERENCES world_canonical_instance_association(canonical_game_instance_id) ON DELETE RESTRICT, + CONSTRAINT fk_world_character_location_operation + FOREIGN KEY (initial_location_operation_id) + REFERENCES world_canonical_initial_player_location_operation(operation_id) ON DELETE RESTRICT, + CONSTRAINT fk_world_character_location_admission_hold + FOREIGN KEY (initial_admission_hold_id) + REFERENCES initial_admission_bind_hold(hold_id) ON DELETE RESTRICT, + CONSTRAINT ck_world_character_location_ids CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_account_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND character_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND entity_assignment_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND initial_room_template_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND initial_admission_hold_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND initial_admission_hold_fence <> '00000000-0000-0000-0000-000000000000'::UUID + AND initial_location_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_character_location_slug CHECK ( + octet_length(world_slug) BETWEEN 1 AND 120 AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ) +); + +CREATE INDEX idx_world_character_location_occupants + ON character_location (canonical_tenant_id, playable_state_namespace_id, + canonical_game_instance_id, runtime_room_instance_id); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_initial_player_location_operation FROM PUBLIC; +REVOKE ALL ON character_location FROM PUBLIC; + +CREATE FUNCTION world_guard_initial_location_operation() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + request JSONB; + result JSONB; + canonical_result BYTEA; + canonical_room TEXT; + canonical_conflict_code TEXT; + canonical_runtime_room TEXT; + request_base64 TEXT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World initial-location operation evidence is immutable' USING ERRCODE = '55000'; + END IF; + IF NEW.request_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.request_bytes), 'hex')) + OR NEW.result_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.result_bytes), 'hex')) THEN + RAISE EXCEPTION 'World initial-location operation digests do not match retained bytes' USING ERRCODE = '23514'; + END IF; + request := convert_from(NEW.request_bytes, 'UTF8')::JSONB; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request) IS DISTINCT FROM 'object' + OR request->>'schema' IS DISTINCT FROM 'world-canonical-initial-player-location-request/v1' + OR request->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR request->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR request->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR request->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR request->>'initialAdmissionOrigin' IS DISTINCT FROM 'NO_PRIOR_POINTER' + OR jsonb_typeof(request->'activeLifecycleEvidence') IS DISTINCT FROM 'object' + OR (convert_from(NEW.original_lifecycle_evidence_bytes, 'UTF8')::JSONB #- '{request,readRequestId}') + IS DISTINCT FROM (request->'activeLifecycleEvidence' #- '{request,readRequestId}') + THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical request/result' USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = NEW.canonical_game_instance_id + AND a.world_instance_id = NEW.world_instance_id + AND a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical association' USING ERRCODE = '23514'; + END IF; + + IF jsonb_typeof(result) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'World initial-location result must be a closed canonical object' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(result)) <> 8 + OR NOT (result ?& ARRAY[ + 'conflictCode', 'operationId', 'outcome', 'requestBytesBase64', + 'requestDigest', 'runtimeRoomInstanceId', 'schema', 'startLocation' + ]) THEN + RAISE EXCEPTION 'World initial-location result must have exactly eight fields' USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(result->'schema') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'operationId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'requestDigest') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'requestBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'outcome') IS DISTINCT FROM 'string' + OR result->>'schema' IS DISTINCT FROM 'world-canonical-initial-player-location-result/v1' + OR result->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR result->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR result->>'outcome' IS DISTINCT FROM NEW.outcome THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical result identity' USING ERRCODE = '23514'; + END IF; + + request_base64 := replace(replace(encode(NEW.request_bytes, 'base64'), E'\n', ''), E'\r', ''); + IF result->>'requestBytesBase64' IS DISTINCT FROM request_base64 + OR decode(result->>'requestBytesBase64', 'base64') IS DISTINCT FROM NEW.request_bytes THEN + RAISE EXCEPTION 'World initial-location result request bytes differ from its operation' USING ERRCODE = '23514'; + END IF; + + IF NEW.outcome = 'APPLIED' THEN + IF jsonb_typeof(result->'conflictCode') IS DISTINCT FROM 'null' + OR jsonb_typeof(result->'runtimeRoomInstanceId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation') IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Applied World initial-location result has an invalid field shape' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(result->'startLocation')) <> 3 + OR NOT ((result->'startLocation') ?& ARRAY['roomTemplateId', 'tenantId', 'versionId']) + OR jsonb_typeof(result->'startLocation'->'roomTemplateId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation'->'tenantId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation'->'versionId') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Applied World initial-location result room must have exactly three string fields' USING ERRCODE = '23514'; + END IF; + IF (result->'startLocation'->>'roomTemplateId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'tenantId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'versionId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'roomTemplateId') = '00000000-0000-0000-0000-000000000000' + OR (result->'startLocation'->>'tenantId') = '00000000-0000-0000-0000-000000000000' + OR (result->'startLocation'->>'versionId') = '00000000-0000-0000-0000-000000000000' + OR (result->>'runtimeRoomInstanceId') !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Applied World initial-location result contains a noncanonical room identity' USING ERRCODE = '23514'; + END IF; + IF (result->>'runtimeRoomInstanceId')::NUMERIC > 9223372036854775807 THEN + RAISE EXCEPTION 'Applied World initial-location runtime room id exceeds signed 64-bit range' USING ERRCODE = '23514'; + END IF; + IF (result->'startLocation') IS DISTINCT FROM + (request->'activeLifecycleEvidence'->'startLocation') + OR result->>'runtimeRoomInstanceId' IS DISTINCT FROM + request->'activeLifecycleEvidence'->>'runtimeRoomInstanceId' THEN + RAISE EXCEPTION 'Applied World initial-location result differs from the exact V2 ROOM mapping' USING ERRCODE = '23514'; + END IF; + canonical_room := + '{"roomTemplateId":' || to_jsonb(result->'startLocation'->>'roomTemplateId')::TEXT + || ',"tenantId":' || to_jsonb(result->'startLocation'->>'tenantId')::TEXT + || ',"versionId":' || to_jsonb(result->'startLocation'->>'versionId')::TEXT || '}'; + canonical_conflict_code := 'null'; + canonical_runtime_room := to_jsonb(result->>'runtimeRoomInstanceId')::TEXT; + ELSE + IF jsonb_typeof(result->'conflictCode') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'runtimeRoomInstanceId') IS DISTINCT FROM 'null' + OR jsonb_typeof(result->'startLocation') IS DISTINCT FROM 'null' + OR result->>'conflictCode' IS DISTINCT FROM NEW.conflict_code THEN + RAISE EXCEPTION 'Conflicting World initial-location result has an invalid field shape' USING ERRCODE = '23514'; + END IF; + IF (result->>'conflictCode') COLLATE "C" !~ '^[A-Z][A-Z0-9_]{0,63}$' + OR (result->>'conflictCode') COLLATE "C" ~ '[^A-Z0-9_]' THEN + RAISE EXCEPTION 'Conflicting World initial-location result has an invalid machine code' USING ERRCODE = '23514'; + END IF; + canonical_room := 'null'; + canonical_conflict_code := to_jsonb(result->>'conflictCode')::TEXT; + canonical_runtime_room := 'null'; + END IF; + + canonical_result := convert_to( + '{"conflictCode":' || canonical_conflict_code + || ',"operationId":' || to_jsonb(NEW.operation_id::TEXT)::TEXT + || ',"outcome":' || to_jsonb(NEW.outcome)::TEXT + || ',"requestBytesBase64":' || to_jsonb(request_base64)::TEXT + || ',"requestDigest":' || to_jsonb(NEW.request_digest)::TEXT + || ',"runtimeRoomInstanceId":' || canonical_runtime_room + || ',"schema":"world-canonical-initial-player-location-result/v1"' + || ',"startLocation":' || canonical_room || '}', + 'UTF8'); + IF NEW.result_bytes IS DISTINCT FROM canonical_result THEN + RAISE EXCEPTION 'World initial-location result bytes are not canonical' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_guard_initial_location_operation + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_initial_player_location_operation + FOR EACH ROW EXECUTE FUNCTION world_guard_initial_location_operation(); +REVOKE ALL ON FUNCTION world_guard_initial_location_operation() FROM PUBLIC; + +CREATE FUNCTION world_guard_initial_character_location() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation_row "${serviceSchema}".world_canonical_initial_player_location_operation%ROWTYPE; + request JSONB; + lifecycle JSONB; +BEGIN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Initial placement is immutable; a separate World movement owner must be implemented' USING ERRCODE = '55000'; + END IF; + IF TG_OP <> 'INSERT' THEN RETURN NEW; END IF; + + SELECT * INTO STRICT operation_row + FROM "${serviceSchema}".world_canonical_initial_player_location_operation + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND playable_state_namespace_id = NEW.playable_state_namespace_id + AND canonical_game_instance_id = NEW.canonical_game_instance_id + AND operation_id = NEW.initial_location_operation_id; + request := convert_from(operation_row.request_bytes, 'UTF8')::JSONB; + lifecycle := convert_from(NEW.initial_lifecycle_evidence_bytes, 'UTF8')::JSONB; + + IF operation_row.outcome IS DISTINCT FROM 'APPLIED' + OR operation_row.request_digest IS DISTINCT FROM NEW.initial_location_request_digest + OR request->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR request->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR request->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR request->>'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR request->>'canonicalAccountId' IS DISTINCT FROM NEW.canonical_account_id::TEXT + OR request->>'characterId' IS DISTINCT FROM NEW.character_id::TEXT + OR request->>'entityAssignmentOperationId' IS DISTINCT FROM NEW.entity_assignment_operation_id::TEXT + OR request->>'entityAssignmentDigest' IS DISTINCT FROM NEW.entity_assignment_digest + OR request->>'realmId' IS DISTINCT FROM NEW.realm_id::TEXT + OR request->>'worldSlug' IS DISTINCT FROM NEW.world_slug + OR request->>'initialAdmissionHoldId' IS DISTINCT FROM NEW.initial_admission_hold_id::TEXT + OR request->>'initialAdmissionHoldFence' IS DISTINCT FROM NEW.initial_admission_hold_fence::TEXT + OR request->>'initialAdmissionOrigin' IS DISTINCT FROM 'NO_PRIOR_POINTER' + OR request->>'initialAdmissionRequestId' IS DISTINCT FROM NEW.initial_admission_request_id + OR request->>'initialAdmissionRequestDigest' IS DISTINCT FROM NEW.initial_admission_request_digest + OR request->>'initialAdmissionOwnerProofId' IS DISTINCT FROM NEW.initial_admission_owner_proof_id + OR request->>'initialAdmissionOwnerProofDigest' IS DISTINCT FROM NEW.initial_admission_owner_proof_digest + OR request->>'pointerAuditId' IS DISTINCT FROM NEW.pointer_audit_id + OR request->>'pointerVersion' IS DISTINCT FROM NEW.pointer_version::TEXT + OR request->>'catalogRevision' IS DISTINCT FROM NEW.catalog_revision::TEXT + OR request->'activeLifecycleEvidence' IS NULL + OR (request->'activeLifecycleEvidence' #- '{request,readRequestId}') + IS DISTINCT FROM (lifecycle #- '{request,readRequestId}') + OR NEW.initial_lifecycle_evidence_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.initial_lifecycle_evidence_bytes), 'hex')) + OR lifecycle->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR lifecycle->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' + OR lifecycle->>'lifecycleEpoch' IS DISTINCT FROM NEW.active_lifecycle_epoch::TEXT + OR lifecycle->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR lifecycle->'request'->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR lifecycle->'request'->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR lifecycle->'request'->>'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR lifecycle->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR lifecycle->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR lifecycle->'startLocation'->>'roomTemplateId' IS DISTINCT FROM NEW.initial_room_template_id::TEXT + OR lifecycle->>'runtimeRoomInstanceId' IS DISTINCT FROM NEW.initial_runtime_room_instance_id::TEXT + OR NEW.runtime_room_instance_id IS DISTINCT FROM NEW.initial_runtime_room_instance_id THEN + RAISE EXCEPTION 'World initial placement differs from its retained operation or lifecycle proof' USING ERRCODE = '23514'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance w ON w.id = a.world_instance_id + JOIN "${serviceSchema}".world_canonical_preparation_start_location s + ON s.canonical_game_instance_id = a.canonical_game_instance_id + AND s.world_instance_id = a.world_instance_id + JOIN "${serviceSchema}".world_canonical_instance_topology_identity m + ON m.world_instance_id = a.world_instance_id + AND m.canonical_game_instance_id = a.canonical_game_instance_id + AND m.family = 'ROOM' AND m.template_id = s.room_template_id + AND m.runtime_room_instance_id = s.runtime_room_instance_id + JOIN "${serviceSchema}".room_instance r + ON r.id = m.runtime_row_id AND r.room_instance_row_id = s.runtime_room_instance_id + JOIN "${serviceSchema}".initial_admission_bind_hold h + ON h.hold_id = NEW.initial_admission_hold_id + WHERE a.canonical_game_instance_id = NEW.canonical_game_instance_id + AND a.world_instance_id = NEW.world_instance_id + AND a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.canonical_world_slug = NEW.world_slug + AND a.playable_state_namespace_id = NEW.playable_state_namespace_id + AND a.playable_state_scope = NEW.playable_state_scope + AND a.canonical_version_id = NEW.canonical_version_id + AND w.canonical_game_instance_id = a.canonical_game_instance_id + AND w.canonical_tenant_id = NEW.canonical_tenant_id + AND w.canonical_world_slug = NEW.world_slug + AND w.playable_state_namespace_id = NEW.playable_state_namespace_id + AND w.playable_state_scope = NEW.playable_state_scope + AND w.status = 'ACTIVE' AND w.lifecycle_epoch = NEW.active_lifecycle_epoch + AND s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.room_template_id = NEW.initial_room_template_id + AND s.runtime_room_instance_id = NEW.initial_runtime_room_instance_id + AND r.tenant_id = w.tenant_id AND r.game_instance_id = w.game_instance_id + AND h.tenant_id = w.tenant_id AND h.game_instance_id = w.game_instance_id + AND h.realm_uuid = NEW.realm_id + AND h.playable_state_namespace_uuid = NEW.playable_state_namespace_id + AND h.playable_state_scope = NEW.playable_state_scope + AND h.version_id = w.version_id AND h.active_lifecycle_epoch = w.lifecycle_epoch + AND h.status = 'COMMITTED' AND h.expected_no_prior_pointer IS TRUE + AND h.initial_admission_request_id = NEW.initial_admission_request_id + AND h.request_digest = NEW.initial_admission_request_digest + AND h.expected_catalog_revision = NEW.catalog_revision + AND h.owner_proof_id = NEW.initial_admission_owner_proof_id + AND h.owner_proof_digest = NEW.initial_admission_owner_proof_digest + AND h.owner_pointer_audit_id = NEW.pointer_audit_id + AND h.owner_pointer_version = NEW.pointer_version + AND h.hold_fence = NEW.initial_admission_hold_fence + ) THEN + RAISE EXCEPTION 'World initial location lacks exact current association, V2 ROOM mapping, or committed first-open proof' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_guard_initial_character_location + BEFORE INSERT OR UPDATE ON character_location + FOR EACH ROW EXECUTE FUNCTION world_guard_initial_character_location(); +REVOKE ALL ON FUNCTION world_guard_initial_character_location() FROM PUBLIC; + +CREATE FUNCTION world_require_initial_location_operation_result() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + request JSONB; + result JSONB; + lifecycle JSONB; +BEGIN + request := convert_from(NEW.request_bytes, 'UTF8')::JSONB; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + lifecycle := request->'activeLifecycleEvidence'; + IF NEW.outcome = 'APPLIED' AND NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".character_location l + WHERE l.canonical_tenant_id = NEW.canonical_tenant_id + AND l.playable_state_namespace_id = NEW.playable_state_namespace_id + AND l.canonical_game_instance_id = NEW.canonical_game_instance_id + AND l.canonical_account_id = (convert_from(NEW.request_bytes, 'UTF8')::JSONB->>'canonicalAccountId')::UUID + AND l.character_id = (convert_from(NEW.request_bytes, 'UTF8')::JSONB->>'characterId')::UUID + AND l.entity_assignment_operation_id = (convert_from(NEW.request_bytes, 'UTF8')::JSONB->>'entityAssignmentOperationId')::UUID + AND l.entity_assignment_digest = convert_from(NEW.request_bytes, 'UTF8')::JSONB->>'entityAssignmentDigest' + AND l.canonical_tenant_id = (result->'startLocation'->>'tenantId')::UUID + AND l.canonical_version_id = (result->'startLocation'->>'versionId')::UUID + AND l.initial_room_template_id = (result->'startLocation'->>'roomTemplateId')::UUID + AND l.initial_runtime_room_instance_id = (result->>'runtimeRoomInstanceId')::BIGINT + AND result->'startLocation' IS NOT DISTINCT FROM lifecycle->'startLocation' + AND result->>'runtimeRoomInstanceId' IS NOT DISTINCT FROM lifecycle->>'runtimeRoomInstanceId' + AND l.canonical_account_id = (request->>'canonicalAccountId')::UUID + AND l.initial_admission_hold_id = (request->>'initialAdmissionHoldId')::UUID + AND l.initial_admission_hold_fence = (request->>'initialAdmissionHoldFence')::UUID + AND l.realm_id = (request->>'realmId')::UUID + AND l.world_slug = request->>'worldSlug' + AND l.playable_state_scope = request->>'playableStateScope' + AND l.canonical_version_id = (lifecycle->'request'->>'canonicalVersionId')::UUID + AND l.active_lifecycle_epoch = (lifecycle->>'lifecycleEpoch')::BIGINT + AND l.initial_admission_request_id = request->>'initialAdmissionRequestId' + AND l.initial_admission_request_digest = request->>'initialAdmissionRequestDigest' + AND l.catalog_revision = (request->>'catalogRevision')::BIGINT + AND l.initial_admission_owner_proof_id = request->>'initialAdmissionOwnerProofId' + AND l.initial_admission_owner_proof_digest = request->>'initialAdmissionOwnerProofDigest' + AND l.pointer_audit_id = request->>'pointerAuditId' + AND l.pointer_version = (request->>'pointerVersion')::BIGINT + ) THEN + RAISE EXCEPTION 'Applied World initial-location operation has no atomic location row' USING ERRCODE = '23514'; + END IF; + IF NEW.outcome = 'CONFLICT' AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".character_location l + WHERE l.canonical_tenant_id = NEW.canonical_tenant_id + AND l.playable_state_namespace_id = NEW.playable_state_namespace_id + AND l.canonical_game_instance_id = NEW.canonical_game_instance_id + AND l.initial_location_operation_id = NEW.operation_id + ) THEN + RAISE EXCEPTION 'Conflicting World initial-location operation cannot own a location row' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER trg_world_require_initial_location_operation_result + AFTER INSERT ON world_canonical_initial_player_location_operation + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_initial_location_operation_result(); +REVOKE ALL ON FUNCTION world_require_initial_location_operation_result() FROM PUBLIC; + +CREATE FUNCTION world_reject_initial_location_operation_truncate() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'World initial-location operation evidence cannot be truncated' USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER trg_world_reject_initial_location_operation_truncate + BEFORE TRUNCATE ON world_canonical_initial_player_location_operation + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_initial_location_operation_truncate(); +REVOKE ALL ON FUNCTION world_reject_initial_location_operation_truncate() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V47__canonical_initial_admission_hold_binding.sql b/services/world-management-service/src/main/resources/db/migration/V47__canonical_initial_admission_hold_binding.sql new file mode 100644 index 0000000000..c14e117748 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V47__canonical_initial_admission_hold_binding.sql @@ -0,0 +1,255 @@ +-- Canonical first-open holds retain their complete owner request alongside the legacy numeric +-- termination-blocking record. Retained V23 rows intentionally remain unmapped. +-- PostgreSQL auto-names V23's CHECK; H2 metadata simulator has a different name. +-- [jooq ignore start] +ALTER TABLE initial_admission_bind_hold + DROP CONSTRAINT initial_admission_bind_hold_expected_no_prior_pointer_check; +-- [jooq ignore stop] + +ALTER TABLE initial_admission_bind_hold + ADD COLUMN canonical_target_namespace VARCHAR(63), + ADD COLUMN canonical_tenant_id UUID, + ADD COLUMN canonical_world_slug VARCHAR(120), + ADD COLUMN canonical_game_instance_id UUID, + ADD COLUMN canonical_version_id UUID, + ADD COLUMN initial_admission_origin VARCHAR(32), + ADD COLUMN expected_prior_pointer_version BIGINT, + ADD COLUMN canonical_request_bytes BYTEA, + ADD COLUMN hold_binding_digest VARCHAR(71), + ADD CONSTRAINT fk_initial_admission_bind_canonical_association + FOREIGN KEY ( + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_uuid, + playable_state_scope, + canonical_game_instance_id + ) REFERENCES world_canonical_instance_association ( + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + canonical_game_instance_id + ) ON DELETE RESTRICT, + ADD CONSTRAINT ck_initial_admission_bind_canonical_metadata CHECK ( + ( + canonical_target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND canonical_world_slug IS NULL + AND canonical_game_instance_id IS NULL + AND canonical_version_id IS NULL + AND initial_admission_origin IS NULL + AND expected_prior_pointer_version IS NULL + AND canonical_request_bytes IS NULL + AND hold_binding_digest IS NULL + AND expected_no_prior_pointer IS TRUE + ) + OR + ( + canonical_target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND canonical_world_slug IS NOT NULL + AND canonical_game_instance_id IS NOT NULL + AND canonical_version_id IS NOT NULL + AND initial_admission_origin IS NOT NULL + AND canonical_request_bytes IS NOT NULL + AND hold_binding_digest IS NOT NULL + AND canonical_target_namespace COLLATE "C" ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_world_slug COLLATE "C" ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(canonical_world_slug) BETWEEN 1 AND 120 + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND octet_length(canonical_request_bytes) > 0 + AND hold_binding_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + AND ( + (initial_admission_origin = 'NO_PRIOR_POINTER' + AND expected_no_prior_pointer IS TRUE + AND expected_prior_pointer_version IS NULL) + OR + (initial_admission_origin = 'EXPECT_CLOSED' + AND expected_no_prior_pointer IS FALSE + AND expected_prior_pointer_version IS NOT NULL + AND expected_prior_pointer_version > 0) + ) + ) + ); + +-- [jooq ignore start] +REVOKE ALL ON initial_admission_bind_hold FROM PUBLIC; + +CREATE FUNCTION world_guard_canonical_initial_admission_hold() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + instance_row "${serviceSchema}".world_instance%ROWTYPE; + association_row "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + stored_request JSONB; + expected_request JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.canonical_request_bytes IS NOT NULL THEN + RAISE EXCEPTION 'Canonical initial-admission hold identity cannot be deleted' + USING ERRCODE = '55000'; + END IF; + RETURN OLD; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF OLD.hold_id IS DISTINCT FROM NEW.hold_id + OR OLD.hold_fence IS DISTINCT FROM NEW.hold_fence + OR OLD.tenant_id IS DISTINCT FROM NEW.tenant_id + OR OLD.realm_uuid IS DISTINCT FROM NEW.realm_uuid + OR OLD.playable_state_namespace_uuid IS DISTINCT FROM NEW.playable_state_namespace_uuid + OR OLD.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR OLD.game_instance_id IS DISTINCT FROM NEW.game_instance_id + OR OLD.version_id IS DISTINCT FROM NEW.version_id + OR OLD.active_lifecycle_epoch IS DISTINCT FROM NEW.active_lifecycle_epoch + OR OLD.initial_admission_request_id IS DISTINCT FROM NEW.initial_admission_request_id + OR OLD.request_digest IS DISTINCT FROM NEW.request_digest + OR OLD.expected_no_prior_pointer IS DISTINCT FROM NEW.expected_no_prior_pointer + OR OLD.expected_catalog_revision IS DISTINCT FROM NEW.expected_catalog_revision + OR OLD.diagnostic_expires_at IS DISTINCT FROM NEW.diagnostic_expires_at + OR OLD.created_at IS DISTINCT FROM NEW.created_at + OR OLD.canonical_target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR OLD.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR OLD.canonical_world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR OLD.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR OLD.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR OLD.initial_admission_origin IS DISTINCT FROM NEW.initial_admission_origin + OR OLD.expected_prior_pointer_version IS DISTINCT FROM NEW.expected_prior_pointer_version + OR OLD.canonical_request_bytes IS DISTINCT FROM NEW.canonical_request_bytes + OR OLD.hold_binding_digest IS DISTINCT FROM NEW.hold_binding_digest THEN + RAISE EXCEPTION 'Initial-admission hold acquisition identity is immutable' + USING ERRCODE = '55000'; + END IF; + IF OLD.canonical_request_bytes IS NOT NULL + AND (OLD.status IS DISTINCT FROM NEW.status + OR OLD.owner_proof_id IS DISTINCT FROM NEW.owner_proof_id + OR OLD.owner_proof_digest IS DISTINCT FROM NEW.owner_proof_digest + OR OLD.owner_pointer_audit_id IS DISTINCT FROM NEW.owner_pointer_audit_id + OR OLD.owner_pointer_version IS DISTINCT FROM NEW.owner_pointer_version + OR OLD.terminal_at IS DISTINCT FROM NEW.terminal_at) THEN + RAISE EXCEPTION 'Canonical initial-admission hold requires its deferred typed owner outcome' + USING ERRCODE = '55000'; + END IF; + IF OLD.canonical_request_bytes IS NOT NULL THEN + RAISE EXCEPTION 'Canonical initial-admission hold lifecycle updates are not enabled' + USING ERRCODE = '55000'; + END IF; + RETURN NEW; + END IF; + + -- A retained V23 numeric hold can never be promoted to canonical evidence. New untyped + -- acquisitions are rejected when their actual private World row already has an association. + IF NEW.canonical_request_bytes IS NULL THEN + SELECT wi.* INTO instance_row + FROM "${serviceSchema}".world_instance wi + WHERE wi.tenant_id = NEW.tenant_id + AND wi.game_instance_id = NEW.game_instance_id + FOR UPDATE; + IF FOUND AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.world_instance_id = instance_row.id + ) THEN + RAISE EXCEPTION 'Canonical World instances require a typed initial-admission hold' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + -- Resolve private numeric keys only through the actual association row and its World row. + SELECT a.* INTO association_row + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance wi ON wi.id = a.world_instance_id + WHERE wi.tenant_id = NEW.tenant_id + AND wi.game_instance_id = NEW.game_instance_id + AND wi.version_id = NEW.version_id + FOR UPDATE OF wi; + IF NOT FOUND THEN + RAISE EXCEPTION 'Canonical initial-admission hold lacks its actual World association' + USING ERRCODE = '23514'; + END IF; + + SELECT wi.* INTO instance_row + FROM "${serviceSchema}".world_instance wi + WHERE wi.id = association_row.world_instance_id; + IF NOT FOUND + OR association_row.canonical_target_namespace IS DISTINCT FROM NEW.canonical_target_namespace + OR association_row.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR association_row.canonical_world_slug IS DISTINCT FROM NEW.canonical_world_slug + OR association_row.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_uuid + OR association_row.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR association_row.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR association_row.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR association_row.local_tenant_key IS DISTINCT FROM NEW.tenant_id + OR association_row.private_game_instance_key IS DISTINCT FROM NEW.game_instance_id + OR association_row.local_version_key IS DISTINCT FROM NEW.version_id + OR instance_row.canonical_game_instance_id IS DISTINCT FROM association_row.canonical_game_instance_id + OR instance_row.canonical_target_namespace IS DISTINCT FROM association_row.canonical_target_namespace + OR instance_row.canonical_tenant_id IS DISTINCT FROM association_row.canonical_tenant_id + OR instance_row.canonical_world_slug IS DISTINCT FROM association_row.canonical_world_slug + OR instance_row.playable_state_namespace_id IS DISTINCT FROM association_row.playable_state_namespace_id + OR instance_row.playable_state_scope IS DISTINCT FROM association_row.playable_state_scope + OR instance_row.version_id IS DISTINCT FROM association_row.local_version_key + OR instance_row.status IS DISTINCT FROM 'ACTIVE' + OR instance_row.lifecycle_epoch IS DISTINCT FROM NEW.active_lifecycle_epoch THEN + RAISE EXCEPTION 'Canonical initial-admission hold differs from its actual World association' + USING ERRCODE = '23514'; + END IF; + + IF NEW.hold_binding_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(NEW.canonical_request_bytes), 'hex')) THEN + RAISE EXCEPTION 'Canonical initial-admission hold digest differs from its request bytes' + USING ERRCODE = '23514'; + END IF; + + stored_request := convert_from(NEW.canonical_request_bytes, 'UTF8')::JSONB; + expected_request := jsonb_build_object( + 'schema', 'world-canonical-initial-admission-hold-request/v1', + 'request', jsonb_build_object( + 'targetNamespace', NEW.canonical_target_namespace, + 'canonicalTenantId', NEW.canonical_tenant_id::TEXT, + 'worldSlug', NEW.canonical_world_slug, + 'realmId', NEW.realm_uuid::TEXT, + 'playableStateNamespaceId', NEW.playable_state_namespace_uuid::TEXT, + 'playableStateScope', NEW.playable_state_scope, + 'canonicalGameInstanceId', NEW.canonical_game_instance_id::TEXT, + 'canonicalVersionId', NEW.canonical_version_id::TEXT, + 'activeLifecycleEpoch', NEW.active_lifecycle_epoch::TEXT, + 'initialAdmissionRequestId', NEW.initial_admission_request_id, + 'initialAdmissionRequestDigest', NEW.request_digest::TEXT, + 'initialAdmissionOrigin', NEW.initial_admission_origin, + 'expectedCatalogRevision', NEW.expected_catalog_revision::TEXT, + 'expectedPriorPointerVersion', CASE + WHEN NEW.expected_prior_pointer_version IS NULL THEN NULL + ELSE NEW.expected_prior_pointer_version::TEXT + END + ) + ); + IF jsonb_typeof(stored_request) IS DISTINCT FROM 'object' + OR stored_request IS DISTINCT FROM expected_request THEN + RAISE EXCEPTION 'Canonical initial-admission request bytes differ from hold columns' + USING ERRCODE = '23514'; + END IF; + + IF NEW.status <> 'PENDING' + OR NEW.owner_proof_id IS NOT NULL + OR NEW.owner_proof_digest IS NOT NULL + OR NEW.owner_pointer_audit_id IS NOT NULL + OR NEW.owner_pointer_version IS NOT NULL + OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'Canonical initial-admission acquisition must begin PENDING' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_guard_canonical_initial_admission_hold + BEFORE INSERT OR UPDATE OR DELETE ON initial_admission_bind_hold + FOR EACH ROW EXECUTE FUNCTION world_guard_canonical_initial_admission_hold(); +REVOKE ALL ON FUNCTION world_guard_canonical_initial_admission_hold() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V48__canonical_initial_admission_hold_terminal.sql b/services/world-management-service/src/main/resources/db/migration/V48__canonical_initial_admission_hold_terminal.sql new file mode 100644 index 0000000000..7623c17fe2 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V48__canonical_initial_admission_hold_terminal.sql @@ -0,0 +1,334 @@ +-- Typed terminal outcomes retain the complete authenticated Game Session proof separately from +-- the legacy bare digest columns. Retained V23 rows stay untyped and receive no inferred proof. +ALTER TABLE initial_admission_bind_hold + ADD COLUMN canonical_owner_proof_bytes BYTEA, + ADD COLUMN canonical_owner_proof_digest VARCHAR(71), + ADD CONSTRAINT ck_initial_admission_bind_canonical_owner_proof CHECK ( + ( + canonical_request_bytes IS NULL + AND canonical_owner_proof_bytes IS NULL + AND canonical_owner_proof_digest IS NULL + ) + OR + ( + canonical_request_bytes IS NOT NULL + AND ( + ( + status = 'PENDING' + AND canonical_owner_proof_bytes IS NULL + AND canonical_owner_proof_digest IS NULL + ) + OR + ( + status IN ('COMMITTED', 'ABORTED') + AND canonical_owner_proof_bytes IS NOT NULL + AND octet_length(canonical_owner_proof_bytes) > 0 + AND canonical_owner_proof_digest IS NOT NULL + AND canonical_owner_proof_digest COLLATE "C" ~ '^sha256:[0-9a-f]{64}$' + ) + ) + ) + ); + +-- This transaction-local, exact-row manifest is not owner proof and is never public storage. +CREATE TABLE world_canonical_initial_admission_hold_finalization_manifest ( + transaction_id BIGINT NOT NULL, + hold_id UUID NOT NULL, + hold_fence UUID NOT NULL, + expected_old JSONB NOT NULL, + expected_new JSONB NOT NULL, + PRIMARY KEY (transaction_id, hold_id) +); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_initial_admission_hold_finalization_manifest FROM PUBLIC; + +CREATE FUNCTION world_consume_canonical_initial_admission_hold_finalization_manifest( + actual_operation TEXT, + actual_old JSONB, + actual_new JSONB +) RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + consumed UUID; +BEGIN + IF actual_operation IS DISTINCT FROM 'UPDATE' + OR actual_old IS NULL + OR actual_new IS NULL + OR actual_old->>'status' IS DISTINCT FROM 'PENDING' + OR (actual_new->>'status' IS DISTINCT FROM 'COMMITTED' + AND actual_new->>'status' IS DISTINCT FROM 'ABORTED') THEN + RETURN FALSE; + END IF; + + DELETE FROM "${serviceSchema}".world_canonical_initial_admission_hold_finalization_manifest m + WHERE m.transaction_id = txid_current() + AND m.hold_id::TEXT = actual_old->>'hold_id' + AND m.hold_id::TEXT = actual_new->>'hold_id' + AND m.hold_fence::TEXT = actual_old->>'hold_fence' + AND m.hold_fence::TEXT = actual_new->>'hold_fence' + AND m.expected_old = actual_old + AND m.expected_new = actual_new + AND actual_old->>'canonical_request_bytes' IS NOT NULL + AND actual_new->>'canonical_request_bytes' = actual_old->>'canonical_request_bytes' + AND actual_new->>'hold_binding_digest' = actual_old->>'hold_binding_digest' + AND actual_new->>'canonical_owner_proof_bytes' IS NOT NULL + AND actual_new->>'canonical_owner_proof_digest' IS NOT NULL + RETURNING m.hold_id INTO consumed; + RETURN consumed IS NOT NULL; +END; +$$; +REVOKE ALL ON FUNCTION + world_consume_canonical_initial_admission_hold_finalization_manifest(TEXT, JSONB, JSONB) + FROM PUBLIC; + +CREATE FUNCTION world_finalize_canonical_initial_admission_hold( + p_hold_id UUID, + p_hold_fence UUID, + p_status TEXT, + p_owner_proof_id TEXT, + p_owner_proof_digest TEXT, + p_owner_pointer_audit_id TEXT, + p_owner_pointer_version BIGINT, + p_terminal_at TIMESTAMPTZ, + p_positive_durable_abort BOOLEAN, + p_canonical_owner_proof_bytes BYTEA, + p_canonical_owner_proof_digest TEXT +) RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + candidate "${serviceSchema}".initial_admission_bind_hold%ROWTYPE; + held "${serviceSchema}".initial_admission_bind_hold%ROWTYPE; + next_held "${serviceSchema}".initial_admission_bind_hold%ROWTYPE; + association_row "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + instance_row "${serviceSchema}".world_instance%ROWTYPE; + updated_count INTEGER; +BEGIN + IF p_status NOT IN ('COMMITTED', 'ABORTED') + OR p_terminal_at IS NULL + OR p_canonical_owner_proof_bytes IS NULL + OR octet_length(p_canonical_owner_proof_bytes) = 0 + OR p_canonical_owner_proof_digest !~ '^sha256:[0-9a-f]{64}$' + OR p_canonical_owner_proof_digest IS DISTINCT FROM + ('sha256:' || encode(sha256(p_canonical_owner_proof_bytes), 'hex')) THEN + RAISE EXCEPTION 'Canonical initial-admission terminal proof is incomplete or has an invalid digest' + USING ERRCODE = '23514'; + END IF; + + -- Read the immutable selector without locking, then preserve acquisition order by locking + -- the actual World lifecycle row before the hold itself. + SELECT h.* INTO candidate + FROM "${serviceSchema}".initial_admission_bind_hold h + WHERE h.hold_id = p_hold_id; + IF NOT FOUND + OR candidate.hold_fence IS DISTINCT FROM p_hold_fence + OR candidate.canonical_request_bytes IS NULL THEN + RAISE EXCEPTION 'Canonical initial-admission hold identity is missing or untyped' + USING ERRCODE = '55000'; + END IF; + + SELECT a.* INTO association_row + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance wi ON wi.id = a.world_instance_id + WHERE wi.tenant_id = candidate.tenant_id + AND wi.game_instance_id = candidate.game_instance_id + AND wi.version_id = candidate.version_id + AND a.local_tenant_key = candidate.tenant_id + AND a.private_game_instance_key = candidate.game_instance_id + AND a.local_version_key = candidate.version_id + AND a.canonical_target_namespace = candidate.canonical_target_namespace + AND a.canonical_tenant_id = candidate.canonical_tenant_id + AND a.canonical_world_slug = candidate.canonical_world_slug + AND a.canonical_game_instance_id = candidate.canonical_game_instance_id + AND a.canonical_version_id = candidate.canonical_version_id + AND a.playable_state_namespace_id = candidate.playable_state_namespace_uuid + AND a.playable_state_scope = candidate.playable_state_scope + FOR UPDATE OF wi; + IF NOT FOUND THEN + RAISE EXCEPTION 'Canonical initial-admission terminalization lacks its exact World association' + USING ERRCODE = '23514'; + END IF; + + -- Keep each composite result in one ROWTYPE target. The preceding query already holds + -- this actual lifecycle row; the second read retains that lock and its exact binding. + SELECT wi.* INTO instance_row + FROM "${serviceSchema}".world_instance wi + WHERE wi.id = association_row.world_instance_id + FOR UPDATE; + IF NOT FOUND + OR instance_row.canonical_game_instance_id IS DISTINCT FROM association_row.canonical_game_instance_id + OR instance_row.canonical_target_namespace IS DISTINCT FROM association_row.canonical_target_namespace + OR instance_row.canonical_tenant_id IS DISTINCT FROM association_row.canonical_tenant_id + OR instance_row.canonical_world_slug IS DISTINCT FROM association_row.canonical_world_slug + OR instance_row.playable_state_namespace_id IS DISTINCT FROM association_row.playable_state_namespace_id + OR instance_row.playable_state_scope IS DISTINCT FROM association_row.playable_state_scope + OR instance_row.status IS DISTINCT FROM 'ACTIVE' + OR instance_row.lifecycle_epoch IS DISTINCT FROM candidate.active_lifecycle_epoch THEN + RAISE EXCEPTION 'Canonical initial-admission terminalization lacks its exact ACTIVE World association epoch' + USING ERRCODE = '23514'; + END IF; + + SELECT h.* INTO held + FROM "${serviceSchema}".initial_admission_bind_hold h + WHERE h.hold_id = p_hold_id + FOR UPDATE; + IF NOT FOUND + OR held.hold_fence IS DISTINCT FROM candidate.hold_fence + OR held.tenant_id IS DISTINCT FROM candidate.tenant_id + OR held.realm_uuid IS DISTINCT FROM candidate.realm_uuid + OR held.playable_state_namespace_uuid IS DISTINCT FROM candidate.playable_state_namespace_uuid + OR held.playable_state_scope IS DISTINCT FROM candidate.playable_state_scope + OR held.game_instance_id IS DISTINCT FROM candidate.game_instance_id + OR held.version_id IS DISTINCT FROM candidate.version_id + OR held.active_lifecycle_epoch IS DISTINCT FROM candidate.active_lifecycle_epoch + OR held.initial_admission_request_id IS DISTINCT FROM candidate.initial_admission_request_id + OR held.request_digest IS DISTINCT FROM candidate.request_digest + OR held.expected_no_prior_pointer IS DISTINCT FROM candidate.expected_no_prior_pointer + OR held.expected_catalog_revision IS DISTINCT FROM candidate.expected_catalog_revision + OR held.canonical_target_namespace IS DISTINCT FROM candidate.canonical_target_namespace + OR held.canonical_tenant_id IS DISTINCT FROM candidate.canonical_tenant_id + OR held.canonical_world_slug IS DISTINCT FROM candidate.canonical_world_slug + OR held.canonical_game_instance_id IS DISTINCT FROM candidate.canonical_game_instance_id + OR held.canonical_version_id IS DISTINCT FROM candidate.canonical_version_id + OR held.initial_admission_origin IS DISTINCT FROM candidate.initial_admission_origin + OR held.expected_prior_pointer_version IS DISTINCT FROM candidate.expected_prior_pointer_version + OR held.canonical_request_bytes IS DISTINCT FROM candidate.canonical_request_bytes + OR held.hold_binding_digest IS DISTINCT FROM candidate.hold_binding_digest + OR held.status IS DISTINCT FROM 'PENDING' + OR held.canonical_owner_proof_bytes IS NOT NULL + OR held.canonical_owner_proof_digest IS NOT NULL + OR held.owner_proof_id IS NOT NULL + OR held.owner_proof_digest IS NOT NULL + OR held.owner_pointer_audit_id IS NOT NULL + OR held.owner_pointer_version IS NOT NULL + OR held.terminal_at IS NOT NULL + OR held.row_version = 9223372036854775807 THEN + RAISE EXCEPTION 'Canonical initial-admission hold is not the exact terminalizable PENDING row' + USING ERRCODE = '55000'; + END IF; + + IF p_owner_proof_id IS DISTINCT FROM held.initial_admission_request_id + OR p_owner_proof_digest !~ '^[0-9a-f]{64}$' + OR p_owner_proof_digest IS NULL THEN + RAISE EXCEPTION 'Canonical initial-admission owner proof differs from its original request identity' + USING ERRCODE = '23514'; + END IF; + + IF p_status = 'COMMITTED' THEN + IF p_positive_durable_abort IS DISTINCT FROM FALSE + OR p_owner_pointer_version IS NULL + OR p_owner_pointer_version <= 0 + OR p_owner_pointer_audit_id IS NULL + OR p_owner_pointer_audit_id !~ '^[1-9][0-9]*$' + OR p_owner_pointer_audit_id::NUMERIC > 9223372036854775807 THEN + RAISE EXCEPTION 'Committed canonical initial-admission proof has invalid pointer or audit evidence' + USING ERRCODE = '23514'; + END IF; + IF held.initial_admission_origin = 'NO_PRIOR_POINTER' THEN + IF p_owner_pointer_version IS DISTINCT FROM 1 THEN + RAISE EXCEPTION 'First canonical initial-admission pointer version must be one' + USING ERRCODE = '23514'; + END IF; + ELSIF held.initial_admission_origin = 'EXPECT_CLOSED' THEN + IF held.expected_prior_pointer_version = 9223372036854775807 + OR p_owner_pointer_version IS DISTINCT FROM held.expected_prior_pointer_version + 1 THEN + RAISE EXCEPTION 'Committed canonical initial-admission pointer is not the exact next version' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'Canonical initial-admission origin is unsupported' + USING ERRCODE = '23514'; + END IF; + ELSE + IF p_positive_durable_abort IS DISTINCT FROM TRUE + OR p_owner_pointer_audit_id IS NOT NULL + OR p_owner_pointer_version IS NOT NULL THEN + RAISE EXCEPTION 'Aborted canonical initial-admission proof lacks positive durable fencing' + USING ERRCODE = '23514'; + END IF; + END IF; + + next_held := held; + next_held.status := p_status; + next_held.owner_proof_id := p_owner_proof_id; + next_held.owner_proof_digest := p_owner_proof_digest; + next_held.owner_pointer_audit_id := p_owner_pointer_audit_id; + next_held.owner_pointer_version := p_owner_pointer_version; + next_held.terminal_at := p_terminal_at AT TIME ZONE 'UTC'; + next_held.canonical_owner_proof_bytes := p_canonical_owner_proof_bytes; + next_held.canonical_owner_proof_digest := p_canonical_owner_proof_digest; + next_held.updated_at := CURRENT_TIMESTAMP; + next_held.row_version := held.row_version + 1; + + INSERT INTO "${serviceSchema}".world_canonical_initial_admission_hold_finalization_manifest + (transaction_id, hold_id, hold_fence, expected_old, expected_new) + VALUES (txid_current(), held.hold_id, held.hold_fence, to_jsonb(held), to_jsonb(next_held)); + + UPDATE "${serviceSchema}".initial_admission_bind_hold h + SET status = next_held.status, + owner_proof_id = next_held.owner_proof_id, + owner_proof_digest = next_held.owner_proof_digest, + owner_pointer_audit_id = next_held.owner_pointer_audit_id, + owner_pointer_version = next_held.owner_pointer_version, + terminal_at = next_held.terminal_at, + canonical_owner_proof_bytes = next_held.canonical_owner_proof_bytes, + canonical_owner_proof_digest = next_held.canonical_owner_proof_digest, + updated_at = next_held.updated_at, + row_version = next_held.row_version + WHERE h.hold_id = held.hold_id + AND h.hold_fence = held.hold_fence + AND h.status = 'PENDING' + AND h.row_version = held.row_version; + GET DIAGNOSTICS updated_count = ROW_COUNT; + IF updated_count <> 1 THEN + RAISE EXCEPTION 'Canonical initial-admission hold terminal compare-and-set did not update one row' + USING ERRCODE = '40001'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_finalize_canonical_initial_admission_hold( + UUID, UUID, TEXT, TEXT, TEXT, TEXT, BIGINT, TIMESTAMPTZ, BOOLEAN, BYTEA, TEXT +) FROM PUBLIC; + +-- Replace only V47's typed-update denial branch. Immutable acquisition checks and legacy +-- lifecycle behavior remain in the original trigger function definition. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ IF OLD.canonical_request_bytes IS NOT NULL + AND (OLD.status IS DISTINCT FROM NEW.status + OR OLD.owner_proof_id IS DISTINCT FROM NEW.owner_proof_id + OR OLD.owner_proof_digest IS DISTINCT FROM NEW.owner_proof_digest + OR OLD.owner_pointer_audit_id IS DISTINCT FROM NEW.owner_pointer_audit_id + OR OLD.owner_pointer_version IS DISTINCT FROM NEW.owner_pointer_version + OR OLD.terminal_at IS DISTINCT FROM NEW.terminal_at) THEN + RAISE EXCEPTION 'Canonical initial-admission hold requires its deferred typed owner outcome' + USING ERRCODE = '55000'; + END IF; + IF OLD.canonical_request_bytes IS NOT NULL THEN + RAISE EXCEPTION 'Canonical initial-admission hold lifecycle updates are not enabled' + USING ERRCODE = '55000'; + END IF;$anchor$; + replacement TEXT := $replacement$ IF OLD.canonical_request_bytes IS NOT NULL THEN + IF "${serviceSchema}".world_consume_canonical_initial_admission_hold_finalization_manifest( + TG_OP, to_jsonb(OLD), to_jsonb(NEW)) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Canonical initial-admission hold update lacks its exact one-use owner manifest' + USING ERRCODE = '55000'; + END IF;$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_canonical_initial_admission_hold()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one canonical initial-admission typed update denial'; + END IF; + EXECUTE replace(original, anchor, replacement); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V49__canonical_initial_player_location_typed_hold.sql b/services/world-management-service/src/main/resources/db/migration/V49__canonical_initial_player_location_typed_hold.sql new file mode 100644 index 0000000000..ea91a79df5 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V49__canonical_initial_player_location_typed_hold.sql @@ -0,0 +1,146 @@ +-- Forward alignment of the existing location guard to complete typed first-open outcomes. +-- Retained legacy holds are not promoted or accepted as canonical placement proof. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_guard_initial_character_location() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation_row "${serviceSchema}".world_canonical_initial_player_location_operation%ROWTYPE; + request JSONB; + lifecycle JSONB; +BEGIN + IF TG_OP = 'UPDATE' THEN + RAISE EXCEPTION 'Initial placement is immutable; a separate World movement owner must be implemented' USING ERRCODE = '55000'; + END IF; + IF TG_OP <> 'INSERT' THEN RETURN NEW; END IF; + + SELECT * INTO STRICT operation_row + FROM "${serviceSchema}".world_canonical_initial_player_location_operation + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND playable_state_namespace_id = NEW.playable_state_namespace_id + AND canonical_game_instance_id = NEW.canonical_game_instance_id + AND operation_id = NEW.initial_location_operation_id; + request := convert_from(operation_row.request_bytes, 'UTF8')::JSONB; + lifecycle := convert_from(NEW.initial_lifecycle_evidence_bytes, 'UTF8')::JSONB; + + IF operation_row.outcome IS DISTINCT FROM 'APPLIED' + OR operation_row.request_digest IS DISTINCT FROM NEW.initial_location_request_digest + OR request->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR request->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR request->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR request->>'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR request->>'canonicalAccountId' IS DISTINCT FROM NEW.canonical_account_id::TEXT + OR request->>'characterId' IS DISTINCT FROM NEW.character_id::TEXT + OR request->>'entityAssignmentOperationId' IS DISTINCT FROM NEW.entity_assignment_operation_id::TEXT + OR request->>'entityAssignmentDigest' IS DISTINCT FROM NEW.entity_assignment_digest + OR request->>'realmId' IS DISTINCT FROM NEW.realm_id::TEXT + OR request->>'worldSlug' IS DISTINCT FROM NEW.world_slug + OR request->>'initialAdmissionHoldId' IS DISTINCT FROM NEW.initial_admission_hold_id::TEXT + OR request->>'initialAdmissionHoldFence' IS DISTINCT FROM NEW.initial_admission_hold_fence::TEXT + OR request->>'initialAdmissionOrigin' IS NULL + OR request->>'initialAdmissionOrigin' NOT IN ('NO_PRIOR_POINTER', 'EXPECT_CLOSED') + OR request->>'initialAdmissionRequestId' IS DISTINCT FROM NEW.initial_admission_request_id + OR request->>'initialAdmissionRequestDigest' IS DISTINCT FROM NEW.initial_admission_request_digest + OR request->>'initialAdmissionOwnerProofId' IS DISTINCT FROM NEW.initial_admission_owner_proof_id + OR request->>'initialAdmissionOwnerProofDigest' IS DISTINCT FROM NEW.initial_admission_owner_proof_digest + OR request->>'pointerAuditId' IS DISTINCT FROM NEW.pointer_audit_id + OR request->>'pointerVersion' IS DISTINCT FROM NEW.pointer_version::TEXT + OR request->>'catalogRevision' IS DISTINCT FROM NEW.catalog_revision::TEXT + OR request->'activeLifecycleEvidence' IS NULL + OR (request->'activeLifecycleEvidence' #- '{request,readRequestId}') + IS DISTINCT FROM (lifecycle #- '{request,readRequestId}') + OR NEW.initial_lifecycle_evidence_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.initial_lifecycle_evidence_bytes), 'hex')) + OR lifecycle->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR lifecycle->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' + OR lifecycle->>'lifecycleEpoch' IS DISTINCT FROM NEW.active_lifecycle_epoch::TEXT + OR lifecycle->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR lifecycle->'request'->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR lifecycle->'request'->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR lifecycle->'request'->>'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR lifecycle->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR lifecycle->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR lifecycle->'startLocation'->>'roomTemplateId' IS DISTINCT FROM NEW.initial_room_template_id::TEXT + OR lifecycle->>'runtimeRoomInstanceId' IS DISTINCT FROM NEW.initial_runtime_room_instance_id::TEXT + OR NEW.runtime_room_instance_id IS DISTINCT FROM NEW.initial_runtime_room_instance_id THEN + RAISE EXCEPTION 'World initial placement differs from its retained operation or lifecycle proof' USING ERRCODE = '23514'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance w ON w.id = a.world_instance_id + JOIN "${serviceSchema}".world_canonical_preparation_start_location s + ON s.canonical_game_instance_id = a.canonical_game_instance_id + AND s.world_instance_id = a.world_instance_id + JOIN "${serviceSchema}".world_canonical_instance_topology_identity m + ON m.world_instance_id = a.world_instance_id + AND m.canonical_game_instance_id = a.canonical_game_instance_id + AND m.family = 'ROOM' AND m.template_id = s.room_template_id + AND m.runtime_room_instance_id = s.runtime_room_instance_id + JOIN "${serviceSchema}".room_instance r + ON r.id = m.runtime_row_id AND r.room_instance_row_id = s.runtime_room_instance_id + JOIN "${serviceSchema}".initial_admission_bind_hold h + ON h.hold_id = NEW.initial_admission_hold_id + WHERE a.canonical_game_instance_id = NEW.canonical_game_instance_id + AND a.world_instance_id = NEW.world_instance_id + AND a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.canonical_world_slug = NEW.world_slug + AND a.playable_state_namespace_id = NEW.playable_state_namespace_id + AND a.playable_state_scope = NEW.playable_state_scope + AND a.canonical_version_id = NEW.canonical_version_id + AND w.canonical_game_instance_id = a.canonical_game_instance_id + AND w.canonical_tenant_id = NEW.canonical_tenant_id + AND w.canonical_world_slug = NEW.world_slug + AND w.playable_state_namespace_id = NEW.playable_state_namespace_id + AND w.playable_state_scope = NEW.playable_state_scope + AND w.status = 'ACTIVE' AND w.lifecycle_epoch = NEW.active_lifecycle_epoch + AND s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.room_template_id = NEW.initial_room_template_id + AND s.runtime_room_instance_id = NEW.initial_runtime_room_instance_id + AND r.tenant_id = w.tenant_id AND r.game_instance_id = w.game_instance_id + AND h.tenant_id = w.tenant_id AND h.game_instance_id = w.game_instance_id + AND h.realm_uuid = NEW.realm_id + AND h.playable_state_namespace_uuid = NEW.playable_state_namespace_id + AND h.playable_state_scope = NEW.playable_state_scope + AND h.version_id = w.version_id AND h.active_lifecycle_epoch = w.lifecycle_epoch + AND h.status = 'COMMITTED' + AND h.canonical_target_namespace = a.canonical_target_namespace + AND h.canonical_tenant_id = NEW.canonical_tenant_id + AND h.canonical_world_slug = NEW.world_slug + AND h.canonical_game_instance_id = NEW.canonical_game_instance_id + AND h.canonical_version_id = NEW.canonical_version_id + AND h.canonical_request_bytes IS NOT NULL + AND h.hold_binding_digest = ('sha256:' || encode(sha256(h.canonical_request_bytes), 'hex')) + AND h.canonical_owner_proof_bytes IS NOT NULL + AND h.canonical_owner_proof_digest = ('sha256:' || encode(sha256(h.canonical_owner_proof_bytes), 'hex')) + AND h.initial_admission_origin = request->>'initialAdmissionOrigin' + AND ( + (h.initial_admission_origin = 'NO_PRIOR_POINTER' + AND h.expected_no_prior_pointer IS TRUE + AND h.expected_prior_pointer_version IS NULL + AND h.owner_pointer_version = 1) + OR + (h.initial_admission_origin = 'EXPECT_CLOSED' + AND h.expected_no_prior_pointer IS FALSE + AND h.expected_prior_pointer_version IS NOT NULL + AND h.expected_prior_pointer_version < 9223372036854775807 + AND h.owner_pointer_version = h.expected_prior_pointer_version + 1) + ) + AND h.initial_admission_request_id = NEW.initial_admission_request_id + AND h.request_digest = NEW.initial_admission_request_digest + AND h.expected_catalog_revision = NEW.catalog_revision + AND h.owner_proof_id = NEW.initial_admission_owner_proof_id + AND h.owner_proof_digest = NEW.initial_admission_owner_proof_digest + AND h.owner_pointer_audit_id = NEW.pointer_audit_id + AND h.owner_pointer_version = NEW.pointer_version + AND h.hold_fence = NEW.initial_admission_hold_fence + ) THEN + RAISE EXCEPTION 'World initial location lacks exact current association, V2 ROOM mapping, or committed first-open proof' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_guard_initial_character_location() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V50__canonical_initial_location_operation_origins.sql b/services/world-management-service/src/main/resources/db/migration/V50__canonical_initial_location_operation_origins.sql new file mode 100644 index 0000000000..c3c8d0bfb7 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V50__canonical_initial_location_operation_origins.sql @@ -0,0 +1,148 @@ +-- Forward-align the placement operation guard with the two tagged first-open origins. +-- V46 and V49 remain unchanged; the typed hold and owner-proof checks stay in the V49 location guard. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION world_guard_initial_location_operation() +RETURNS TRIGGER LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + request JSONB; + result JSONB; + canonical_result BYTEA; + canonical_room TEXT; + canonical_conflict_code TEXT; + canonical_runtime_room TEXT; + request_base64 TEXT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World initial-location operation evidence is immutable' USING ERRCODE = '55000'; + END IF; + IF NEW.request_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.request_bytes), 'hex')) + OR NEW.result_digest IS DISTINCT FROM ('sha256:' || encode(sha256(NEW.result_bytes), 'hex')) THEN + RAISE EXCEPTION 'World initial-location operation digests do not match retained bytes' USING ERRCODE = '23514'; + END IF; + request := convert_from(NEW.request_bytes, 'UTF8')::JSONB; + result := convert_from(NEW.result_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request) IS DISTINCT FROM 'object' + OR request->>'schema' IS DISTINCT FROM 'world-canonical-initial-player-location-request/v1' + OR request->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR request->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR request->>'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR request->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR request->>'initialAdmissionOrigin' IS NULL + OR request->>'initialAdmissionOrigin' NOT IN ('NO_PRIOR_POINTER', 'EXPECT_CLOSED') + OR jsonb_typeof(request->'activeLifecycleEvidence') IS DISTINCT FROM 'object' + OR (convert_from(NEW.original_lifecycle_evidence_bytes, 'UTF8')::JSONB #- '{request,readRequestId}') + IS DISTINCT FROM (request->'activeLifecycleEvidence' #- '{request,readRequestId}') + THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical request/result' USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = NEW.canonical_game_instance_id + AND a.world_instance_id = NEW.world_instance_id + AND a.canonical_tenant_id = NEW.canonical_tenant_id + AND a.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical association' USING ERRCODE = '23514'; + END IF; + + IF jsonb_typeof(result) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'World initial-location result must be a closed canonical object' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(result)) <> 8 + OR NOT (result ?& ARRAY[ + 'conflictCode', 'operationId', 'outcome', 'requestBytesBase64', + 'requestDigest', 'runtimeRoomInstanceId', 'schema', 'startLocation' + ]) THEN + RAISE EXCEPTION 'World initial-location result must have exactly eight fields' USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(result->'schema') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'operationId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'requestDigest') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'requestBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'outcome') IS DISTINCT FROM 'string' + OR result->>'schema' IS DISTINCT FROM 'world-canonical-initial-player-location-result/v1' + OR result->>'operationId' IS DISTINCT FROM NEW.operation_id::TEXT + OR result->>'requestDigest' IS DISTINCT FROM NEW.request_digest + OR result->>'outcome' IS DISTINCT FROM NEW.outcome THEN + RAISE EXCEPTION 'World initial-location operation differs from its canonical result identity' USING ERRCODE = '23514'; + END IF; + + request_base64 := replace(replace(encode(NEW.request_bytes, 'base64'), E'\n', ''), E'\r', ''); + IF result->>'requestBytesBase64' IS DISTINCT FROM request_base64 + OR decode(result->>'requestBytesBase64', 'base64') IS DISTINCT FROM NEW.request_bytes THEN + RAISE EXCEPTION 'World initial-location result request bytes differ from its operation' USING ERRCODE = '23514'; + END IF; + + IF NEW.outcome = 'APPLIED' THEN + IF jsonb_typeof(result->'conflictCode') IS DISTINCT FROM 'null' + OR jsonb_typeof(result->'runtimeRoomInstanceId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation') IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Applied World initial-location result has an invalid field shape' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(result->'startLocation')) <> 3 + OR NOT ((result->'startLocation') ?& ARRAY['roomTemplateId', 'tenantId', 'versionId']) + OR jsonb_typeof(result->'startLocation'->'roomTemplateId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation'->'tenantId') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'startLocation'->'versionId') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Applied World initial-location result room must have exactly three string fields' USING ERRCODE = '23514'; + END IF; + IF (result->'startLocation'->>'roomTemplateId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'tenantId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'versionId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (result->'startLocation'->>'roomTemplateId') = '00000000-0000-0000-0000-000000000000' + OR (result->'startLocation'->>'tenantId') = '00000000-0000-0000-0000-000000000000' + OR (result->'startLocation'->>'versionId') = '00000000-0000-0000-0000-000000000000' + OR (result->>'runtimeRoomInstanceId') !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Applied World initial-location result contains a noncanonical room identity' USING ERRCODE = '23514'; + END IF; + IF (result->>'runtimeRoomInstanceId')::NUMERIC > 9223372036854775807 THEN + RAISE EXCEPTION 'Applied World initial-location runtime room id exceeds signed 64-bit range' USING ERRCODE = '23514'; + END IF; + IF (result->'startLocation') IS DISTINCT FROM + (request->'activeLifecycleEvidence'->'startLocation') + OR result->>'runtimeRoomInstanceId' IS DISTINCT FROM + request->'activeLifecycleEvidence'->>'runtimeRoomInstanceId' THEN + RAISE EXCEPTION 'Applied World initial-location result differs from the exact V2 ROOM mapping' USING ERRCODE = '23514'; + END IF; + canonical_room := + '{"roomTemplateId":' || to_jsonb(result->'startLocation'->>'roomTemplateId')::TEXT + || ',"tenantId":' || to_jsonb(result->'startLocation'->>'tenantId')::TEXT + || ',"versionId":' || to_jsonb(result->'startLocation'->>'versionId')::TEXT || '}'; + canonical_conflict_code := 'null'; + canonical_runtime_room := to_jsonb(result->>'runtimeRoomInstanceId')::TEXT; + ELSE + IF jsonb_typeof(result->'conflictCode') IS DISTINCT FROM 'string' + OR jsonb_typeof(result->'runtimeRoomInstanceId') IS DISTINCT FROM 'null' + OR jsonb_typeof(result->'startLocation') IS DISTINCT FROM 'null' + OR result->>'conflictCode' IS DISTINCT FROM NEW.conflict_code THEN + RAISE EXCEPTION 'Conflicting World initial-location result has an invalid field shape' USING ERRCODE = '23514'; + END IF; + IF (result->>'conflictCode') COLLATE "C" !~ '^[A-Z][A-Z0-9_]{0,63}$' + OR (result->>'conflictCode') COLLATE "C" ~ '[^A-Z0-9_]' THEN + RAISE EXCEPTION 'Conflicting World initial-location result has an invalid machine code' USING ERRCODE = '23514'; + END IF; + canonical_room := 'null'; + canonical_conflict_code := to_jsonb(result->>'conflictCode')::TEXT; + canonical_runtime_room := 'null'; + END IF; + + canonical_result := convert_to( + '{"conflictCode":' || canonical_conflict_code + || ',"operationId":' || to_jsonb(NEW.operation_id::TEXT)::TEXT + || ',"outcome":' || to_jsonb(NEW.outcome)::TEXT + || ',"requestBytesBase64":' || to_jsonb(request_base64)::TEXT + || ',"requestDigest":' || to_jsonb(NEW.request_digest)::TEXT + || ',"runtimeRoomInstanceId":' || canonical_runtime_room + || ',"schema":"world-canonical-initial-player-location-result/v1"' + || ',"startLocation":' || canonical_room || '}', + 'UTF8'); + IF NEW.result_bytes IS DISTINCT FROM canonical_result THEN + RAISE EXCEPTION 'World initial-location result bytes are not canonical' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_guard_initial_location_operation() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V51__world_canonical_player_admission_hold.sql b/services/world-management-service/src/main/resources/db/migration/V51__world_canonical_player_admission_hold.sql new file mode 100644 index 0000000000..515121ac2a --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V51__world_canonical_player_admission_hold.sql @@ -0,0 +1,241 @@ +-- Player admission is distinct from initial-pointer opening. No release producer exists yet: +-- every retained row stays HELD, even after its diagnostic lease deadline. +CREATE TABLE world_canonical_player_admission_hold ( + hold_id UUID PRIMARY KEY, + hold_fence UUID NOT NULL UNIQUE, + lease_id UUID NOT NULL UNIQUE, + attempt_id UUID NOT NULL UNIQUE, + lease_sha256 VARCHAR(64) NOT NULL CHECK (lease_sha256 ~ '^[0-9a-f]{64}$'), + lease_bytes BYTEA NOT NULL CHECK (octet_length(lease_bytes) BETWEEN 1 AND 65536), + canonical_game_instance_id UUID NOT NULL + REFERENCES world_canonical_instance_association(canonical_game_instance_id) ON DELETE RESTRICT, + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + active_lifecycle_epoch BIGINT NOT NULL CHECK (active_lifecycle_epoch > 0), + active_row_version BIGINT NOT NULL CHECK (active_row_version >= 0), + world_evidence_bytes BYTEA NOT NULL CHECK (octet_length(world_evidence_bytes) > 0), + diagnostic_expires_at_millis BIGINT NOT NULL CHECK (diagnostic_expires_at_millis > 0), + hold_state VARCHAR(16) NOT NULL DEFAULT 'HELD' CHECK (hold_state = 'HELD'), + -- Future terminalization must retain both exact independently authenticated owner results. + -- NULL means missing proof, never definitive absence. This migration authorizes neither. + account_terminal_evidence_bytes BYTEA CHECK (account_terminal_evidence_bytes IS NULL), + game_session_completion_evidence_bytes BYTEA CHECK (game_session_completion_evidence_bytes IS NULL), + acquisition_transaction_id BIGINT NOT NULL DEFAULT txid_current(), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); +CREATE INDEX idx_world_player_admission_hold_lifecycle + ON world_canonical_player_admission_hold(world_instance_id, hold_state); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_player_admission_hold FROM PUBLIC; + +CREATE FUNCTION world_validate_player_admission_hold() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + instance "${serviceSchema}".world_instance%ROWTYPE; + association "${serviceSchema}".world_canonical_instance_association%ROWTYPE; + preparation "${serviceSchema}".world_canonical_instance_preparation%ROWTYPE; + lease JSONB; + scope JSONB; + evidence JSONB; + selector JSONB; + evaluated BIGINT; + deadline BIGINT; + now_millis BIGINT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World player-admission hold is retained; authenticated dual-owner release is unavailable' + USING ERRCODE = '55000'; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' + OR NEW.acquisition_transaction_id IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'World player-admission hold requires its writable READ COMMITTED owner transaction' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO instance FROM "${serviceSchema}".world_instance + WHERE id = NEW.world_instance_id FOR UPDATE; + IF NOT FOUND OR instance.status IS DISTINCT FROM 'ACTIVE' + OR instance.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR instance.lifecycle_epoch IS DISTINCT FROM NEW.active_lifecycle_epoch + OR instance.row_version IS DISTINCT FROM NEW.active_row_version THEN + RAISE EXCEPTION 'World player-admission hold requires the exact current ACTIVE lifecycle tuple' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO association FROM "${serviceSchema}".world_canonical_instance_association + WHERE canonical_game_instance_id = NEW.canonical_game_instance_id; + IF NOT FOUND OR association.world_instance_id IS DISTINCT FROM instance.id + OR association.local_tenant_key IS DISTINCT FROM instance.tenant_id + OR association.private_game_instance_key IS DISTINCT FROM instance.game_instance_id + OR association.canonical_tenant_id IS DISTINCT FROM instance.canonical_tenant_id + OR association.canonical_target_namespace IS DISTINCT FROM instance.canonical_target_namespace + OR association.canonical_world_slug IS DISTINCT FROM instance.canonical_world_slug + OR association.playable_state_namespace_id IS DISTINCT FROM instance.playable_state_namespace_id + OR association.playable_state_scope IS DISTINCT FROM instance.playable_state_scope + OR association.public_production IS DISTINCT FROM TRUE THEN + RAISE EXCEPTION 'World player-admission hold has no exact canonical owner association' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO preparation FROM "${serviceSchema}".world_canonical_instance_preparation + WHERE canonical_game_instance_id = NEW.canonical_game_instance_id; + IF NOT FOUND OR preparation.world_instance_id IS DISTINCT FROM instance.id + OR preparation.storage_status IS DISTINCT FROM 'MATERIALIZED_UNVERIFIED' + OR preparation.graph_sha256 IS DISTINCT FROM encode(sha256(preparation.graph_bytes), 'hex') + OR preparation.input_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(convert_to(preparation.input_json,'UTF8')), 'hex') THEN + RAISE EXCEPTION 'World player-admission hold requires retained canonical materialization' + USING ERRCODE = '23514'; + END IF; + lease := convert_from(NEW.lease_bytes, 'UTF8')::JSONB; + scope := lease->'bindingScope'; + evidence := convert_from(NEW.world_evidence_bytes, 'UTF8')::JSONB; + selector := evidence->'request'; + evaluated := (lease->>'evaluatedAt')::BIGINT; + deadline := (lease->>'expiresAt')::BIGINT; + now_millis := floor(extract(epoch FROM clock_timestamp()) * 1000)::BIGINT; + IF lease->>'schema' IS DISTINCT FROM 'account-gameplay-admission-lease-evidence/v1' + OR lease->>'schemaVersion' IS DISTINCT FROM '1' + OR lease->>'mode' IS DISTINCT FROM 'PUBLIC_PRODUCTION' + OR lease->>'targetNamespace' IS DISTINCT FROM association.canonical_target_namespace + OR lease->>'callerWorkload' IS DISTINCT FROM + 'spiffe://firemud/ns/' || association.canonical_target_namespace || '/sa/game-session-service' + OR lease->>'leaseId' IS DISTINCT FROM NEW.lease_id::TEXT + OR lease->>'requestId' IS DISTINCT FROM NEW.attempt_id::TEXT + OR NEW.lease_sha256 IS DISTINCT FROM encode(sha256(NEW.lease_bytes), 'hex') + OR lease->'membershipBaseline'->>'membershipLifecycleState' IS DISTINCT FROM 'ACTIVE' + OR evaluated IS NULL OR deadline IS NULL OR evaluated <= 0 + OR evaluated > now_millis OR deadline <= now_millis + OR deadline <= evaluated OR deadline - evaluated > 15000 + OR NEW.diagnostic_expires_at_millis IS DISTINCT FROM deadline + OR scope->>'tenantId' IS DISTINCT FROM association.canonical_tenant_id::TEXT + OR scope->>'worldSlug' IS DISTINCT FROM association.canonical_world_slug + OR scope->>'gameInstanceId' IS DISTINCT FROM association.canonical_game_instance_id::TEXT + OR scope->>'playableStateNamespaceId' IS DISTINCT FROM association.playable_state_namespace_id::TEXT + OR scope->>'playableStateScope' IS DISTINCT FROM association.playable_state_scope + OR evidence->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR evidence->>'lifecycleStatus' IS DISTINCT FROM 'ACTIVE' + OR evidence->>'lifecycleEpoch' IS DISTINCT FROM instance.lifecycle_epoch::TEXT + OR evidence->>'rowVersion' IS DISTINCT FROM instance.row_version::TEXT + OR evidence->>'captureId' IS DISTINCT FROM preparation.capture_id::TEXT + OR evidence->>'graphSha256' IS DISTINCT FROM preparation.graph_sha256 + OR evidence->>'preparationInputDigest' IS DISTINCT FROM preparation.input_digest + OR selector->>'schemaVersion' IS DISTINCT FROM '1' + OR selector->>'readRequestId' IS DISTINCT FROM NEW.attempt_id::TEXT + OR selector->>'targetNamespace' IS DISTINCT FROM association.canonical_target_namespace + OR selector->>'canonicalTenantId' IS DISTINCT FROM association.canonical_tenant_id::TEXT + OR selector->>'worldSlug' IS DISTINCT FROM association.canonical_world_slug + OR selector->>'canonicalGameInstanceId' IS DISTINCT FROM association.canonical_game_instance_id::TEXT + OR selector->>'playableStateNamespaceId' IS DISTINCT FROM association.playable_state_namespace_id::TEXT + OR selector->>'playableStateScope' IS DISTINCT FROM association.playable_state_scope + OR selector->'publicProduction' IS DISTINCT FROM 'true'::JSONB + OR selector->>'controlPlaneRequestId' IS DISTINCT FROM association.control_plane_request_id + OR selector->>'canonicalVersionId' IS DISTINCT FROM association.canonical_version_id::TEXT + OR selector->>'expectedDescriptorRequestDigest' IS DISTINCT FROM association.descriptor_request_digest + OR selector->>'expectedDescriptorResultDigest' IS DISTINCT FROM association.descriptor_result_digest + OR selector->>'expectedReleaseAttestationDigest' IS DISTINCT FROM association.release_attestation_digest THEN + RAISE EXCEPTION 'World player-admission hold differs from the original lease or exact owner evidence' + USING ERRCODE = '23514'; + END IF; + IF NEW.hold_id::TEXT !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + OR NEW.hold_fence::TEXT !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' THEN + RAISE EXCEPTION 'World player-admission hold requires opaque identities' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_validate_player_admission_hold() FROM PUBLIC; +CREATE TRIGGER trg_world_player_admission_hold_retained + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_player_admission_hold + FOR EACH ROW EXECUTE FUNCTION world_validate_player_admission_hold(); + +CREATE FUNCTION world_reject_player_admission_hold_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'World player-admission holds and original evidence are retained' USING ERRCODE='55000'; +END; +$$; +REVOKE ALL ON FUNCTION world_reject_player_admission_hold_truncate() FROM PUBLIC; +CREATE TRIGGER trg_world_player_admission_hold_no_truncate + BEFORE TRUNCATE ON world_canonical_player_admission_hold + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_player_admission_hold_truncate(); + +-- Preserve V35 and all subsequent exact execution-manifest extensions. The one exception is an +-- exact same-value World row UPDATE in the transaction that inserted this bound ACTIVE hold. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ RAISE EXCEPTION + 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest'$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_claim_legacy_numeric_tenant_key()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one reserved-tenant execution denial guard'; + END IF; + original := replace(original,anchor,$replacement$ IF TG_TABLE_SCHEMA = '${serviceSchema}' AND TG_TABLE_NAME = 'world_instance' + AND TG_OP = 'UPDATE' AND old_row = new_row + AND old_row->>'status' = 'ACTIVE' + AND EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_player_admission_hold h + WHERE h.world_instance_id = (old_row->>'id')::BIGINT + AND h.canonical_game_instance_id::TEXT = old_row->>'canonical_game_instance_id' + AND h.active_lifecycle_epoch = (old_row->>'lifecycle_epoch')::BIGINT + AND h.active_row_version = (old_row->>'row_version')::BIGINT + AND h.hold_state = 'HELD' AND h.acquisition_transaction_id = txid_current()) THEN + RETURN NEW; + END IF; +$replacement$ || anchor); + EXECUTE original; +END; +$migration$; + +CREATE FUNCTION world_version_player_admission_lifecycle_tuple() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + -- FOR UPDATE alone cannot refresh an older REPEATABLE READ/SERIALIZABLE snapshot. This exact + -- no-op UPDATE makes its later lifecycle UPDATE fail serialization rather than miss the hold. + UPDATE "${serviceSchema}".world_instance SET row_version = row_version + WHERE id = NEW.world_instance_id AND canonical_game_instance_id = NEW.canonical_game_instance_id + AND status = 'ACTIVE' AND lifecycle_epoch = NEW.active_lifecycle_epoch + AND row_version = NEW.active_row_version; + IF NOT FOUND THEN + RAISE EXCEPTION 'World player-admission hold lost its exact ACTIVE tuple' USING ERRCODE='23514'; + END IF; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_version_player_admission_lifecycle_tuple() FROM PUBLIC; +CREATE TRIGGER trg_world_player_admission_hold_tuple_version + AFTER INSERT ON world_canonical_player_admission_hold + FOR EACH ROW EXECUTE FUNCTION world_version_player_admission_lifecycle_tuple(); + +CREATE FUNCTION world_guard_player_admission_lifecycle() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + -- UPDATE/DELETE owns the same tuple lock used by hold creation. For old MVCC snapshots the + -- hold's tuple UPDATE supplies PostgreSQL's serialization error before a stale change commits. + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_player_admission_hold h + WHERE h.world_instance_id = OLD.id AND h.hold_state = 'HELD') THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'World lifecycle is fenced by a retained player-admission hold' USING ERRCODE='23514'; + END IF; + IF to_jsonb(OLD) IS DISTINCT FROM to_jsonb(NEW) THEN + RAISE EXCEPTION 'World lifecycle is fenced by a retained player-admission hold' USING ERRCODE='23514'; + END IF; + END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_guard_player_admission_lifecycle() FROM PUBLIC; +CREATE TRIGGER aaa_world_player_admission_lifecycle + BEFORE UPDATE OR DELETE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_guard_player_admission_lifecycle(); +-- Existing V34's unconditional World instance TRUNCATE guard remains in force. +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V52__canonical_activation_complete_region_evidence.sql b/services/world-management-service/src/main/resources/db/migration/V52__canonical_activation_complete_region_evidence.sql new file mode 100644 index 0000000000..1b93267ce6 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V52__canonical_activation_complete_region_evidence.sql @@ -0,0 +1,108 @@ +-- Extend V43's canonical activation proof to retain and validate the complete operational REGION +-- assignment map added to WorldCanonicalInstanceLifecycleEvidence. +-- [jooq ignore start] +DO $migration$ +DECLARE + definition TEXT; + original_oid OID; + original_acl ACLITEM[]; + old_fragment TEXT; + new_fragment TEXT; + anchor TEXT; + replacement TEXT; +BEGIN + SELECT p.oid, p.proacl + INTO STRICT original_oid, original_acl + FROM pg_proc p + WHERE p.oid = '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE; + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE) + INTO STRICT definition; + + old_fragment := '(SELECT count(*) FROM jsonb_object_keys(preparing)) <> 11'; + new_fragment := '(SELECT count(*) FROM jsonb_object_keys(preparing)) <> 12'; + IF (length(definition)-length(replace(definition, old_fragment, '')))/length(old_fragment) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one closed PREPARING lifecycle object count in V43 activation guard'; + END IF; + definition := replace(definition, old_fragment, new_fragment); + + old_fragment := '(SELECT count(*) FROM jsonb_object_keys(normalized_request->''preparingEvidence'')) <> 11'; + new_fragment := '(SELECT count(*) FROM jsonb_object_keys(normalized_request->''preparingEvidence'')) <> 12'; + IF (length(definition)-length(replace(definition, old_fragment, '')))/length(old_fragment) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one closed normalized PREPARING lifecycle object count in V43 activation guard'; + END IF; + definition := replace(definition, old_fragment, new_fragment); + + old_fragment := '(SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 11'; + new_fragment := '(SELECT count(*) FROM jsonb_object_keys(lifecycle)) <> 12'; + IF (length(definition)-length(replace(definition, old_fragment, '')))/length(old_fragment) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one closed result lifecycle object count in V43 activation guard'; + END IF; + definition := replace(definition, old_fragment, new_fragment); + + anchor := $$ IF jsonb_typeof(result) IS DISTINCT FROM 'object'$$; + IF (length(definition)-length(replace(definition, anchor, '')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one result-evidence validation anchor in V43 activation guard'; + END IF; + replacement := $replacement$ IF NOT EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_canonical_instance_preparation p + ON p.canonical_game_instance_id=a.canonical_game_instance_id + CROSS JOIN LATERAL ( + SELECT count(*) AS row_count, + count(*) FILTER (WHERE m.id IS NULL OR ri.id IS NULL + OR m.world_instance_id IS DISTINCT FROM a.world_instance_id + OR m.canonical_game_instance_id IS DISTINCT FROM a.canonical_game_instance_id + OR m.family IS DISTINCT FROM 'REGION' + OR m.runtime_row_id IS DISTINCT FROM ri.id + OR ri.world_instance_id IS DISTINCT FROM a.world_instance_id + OR ri.tenant_id IS DISTINCT FROM a.local_tenant_key + OR ri.game_instance_id IS DISTINCT FROM a.private_game_instance_key + OR m.runtime_identity IS NULL + OR m.runtime_identity = '00000000-0000-0000-0000-000000000000'::UUID + OR ri.canonical_region_instance_id IS DISTINCT FROM m.runtime_identity + OR ri.operational_region_id IS NULL + OR ri.operational_region_id = '00000000-0000-0000-0000-000000000000'::UUID + OR ri.operational_region_id = m.runtime_identity) AS invalid_count, + count(DISTINCT m.runtime_identity) AS canonical_identity_count, + count(DISTINCT ri.operational_region_id) AS operational_identity_count, + jsonb_object_agg(m.runtime_identity::TEXT, ri.operational_region_id::TEXT) + FILTER (WHERE m.runtime_identity IS NOT NULL AND ri.operational_region_id IS NOT NULL) + AS assignment_map + FROM "${serviceSchema}".world_canonical_instance_topology_identity m + FULL OUTER JOIN "${serviceSchema}".region_instance ri + ON m.family='REGION' AND m.runtime_row_id=ri.id + WHERE (m.world_instance_id=a.world_instance_id AND m.family='REGION') + OR ri.world_instance_id=a.world_instance_id + OR (ri.tenant_id=a.local_tenant_key AND ri.game_instance_id=a.private_game_instance_key) + ) scoped_regions + WHERE a.canonical_game_instance_id=NEW.canonical_game_instance_id + AND a.world_instance_id=NEW.world_instance_id + AND p.region_count > 0 + AND p.region_count=scoped_regions.row_count + AND scoped_regions.row_count=scoped_regions.canonical_identity_count + AND scoped_regions.row_count=scoped_regions.operational_identity_count + AND scoped_regions.invalid_count=0 + AND jsonb_typeof(preparing->'operationalRegionAssignments')='object' + AND CASE WHEN jsonb_typeof(preparing->'operationalRegionAssignments')='object' + THEN (SELECT count(*) FROM jsonb_object_keys(preparing->'operationalRegionAssignments')) + ELSE -1 END = p.region_count + AND scoped_regions.assignment_map=preparing->'operationalRegionAssignments' + ) THEN + RAISE EXCEPTION 'Canonical activation lifecycle evidence lacks the exact complete operational REGION assignment map' + USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(result) IS DISTINCT FROM 'object'$replacement$; + definition := replace(definition, anchor, replacement); + + EXECUTE definition; + IF '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE + IS DISTINCT FROM original_oid + OR (SELECT p.proacl FROM pg_proc p WHERE p.oid = original_oid) + IS DISTINCT FROM original_acl THEN + RAISE EXCEPTION 'Canonical activation guard replacement changed function identity or grants'; + END IF; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java new file mode 100644 index 0000000000..e20deac775 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java @@ -0,0 +1,1401 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import 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.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +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.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.WorldDraftDesignDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotCapture; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.MissingOwnerHistoryException; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionGraphStager.UnverifiedStagedContent; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionStagingService; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +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.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; +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.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; +import tools.jackson.databind.ObjectMapper; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldAuthoredGraphSnapshotPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final long LARGE_VALUE = 9_007_199_254_740_999L; + private static final long GAME_DESIGN_VERSION_ID = 9_000_000_000_000_001L; + private static final List SYNTHETIC_RETENTION_TABLES = + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_design_revision_ledger"); + + @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 DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository publicationFenceRepository; + @Autowired private WorldAuthoredGraphSnapshotRepository snapshotRepository; + @Autowired private WorldDraftDesignDigestService draftDigestService; + @Autowired private ObjectMapper objectMapper; + + @Autowired + private net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository + spawnRepository; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void exactSnapshotSurvivesRollbackAndConcurrentRetryWithFullGraphReadback() throws Exception { + Fixture fixture = fixture(false); + WorldAuthoredGraphSnapshotCapture capture = captureComponent(); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + captureWithGuardedSessionRole(capture, fixture.request()); + throw new ForcedRollbackException(); + })) + .isInstanceOf(ForcedRollbackException.class); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + + CountDownLatch firstCaptured = new CountDownLatch(1); + CountDownLatch allowFirstCommit = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + WorldAuthoredGraphSnapshot snapshot = + captureWithGuardedSessionRole(capture, fixture.request()); + firstCaptured.countDown(); + await(allowFirstCommit); + return snapshot; + })); + assertThat(firstCaptured.await(15, TimeUnit.SECONDS)).isTrue(); + Future second = + executor.submit( + () -> { + secondStarted.countDown(); + return ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, fixture.request())); + }); + assertThat(secondStarted.await(15, TimeUnit.SECONDS)).isTrue(); + allowFirstCommit.countDown(); + + WorldAuthoredGraphSnapshot firstSnapshot = first.get(20, TimeUnit.SECONDS); + WorldAuthoredGraphSnapshot retrySnapshot = second.get(20, TimeUnit.SECONDS); + assertThat(retrySnapshot.snapshotId()).isEqualTo(firstSnapshot.snapshotId()); + assertThat(retrySnapshot.digestSchemaVersion()).isEqualTo(3); + assertThat(retrySnapshot.graphBytes()).containsExactly(firstSnapshot.graphBytes()); + assertThat(retrySnapshot.ownerCommitProofStatus()) + .isEqualTo(WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED); + assertThat(retrySnapshot.gameDesignVersionId()).isEqualTo(fixture.gameDesignVersionId()); + assertThat(retrySnapshot.localVersionKey()).isEqualTo(fixture.localVersionKey()); + assertThat(retrySnapshot.localVersionKey()).isNotEqualTo(GAME_DESIGN_VERSION_ID); + assertThat(retrySnapshot.versionIdentityOperationId()) + .isEqualTo(fixture.versionIdentityOperationId()); + String graph = new String(retrySnapshot.graphBytes(), StandardCharsets.UTF_8); + assertThat(graph) + .contains( + "\"regions\"", + "\"zones\"", + "\"rooms\"", + "\"roomExits\"", + "\"generationRules\"", + "\"worldEntitySpawnBindings\"", + Long.toString(LARGE_VALUE)); + assertThat(snapshotCount(fixture.request().publicationFence())).isEqualTo(1L); + + CaptureRequest changedTuples = + copyRequest( + fixture.request(), + List.of( + new OwnedAffectedTuple( + "WORLD_MANAGEMENT", "ROOM", "8", "ZONE_SUBTREE", "7", "12"))); + assertThatThrownBy( + () -> + ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, changedTuples))) + .isInstanceOf(SnapshotConflictException.class) + .hasMessageContaining("changed source or request binding"); + + CaptureRequest changedCommit = + new CaptureRequest( + fixture.request().targetNamespace(), + fixture.request().canonicalTenantId(), + fixture.request().canonicalVersionId(), + fixture.request().intakeRequestId(), + fixture.request().publicationFence(), + fixture.request().publicationRequestId(), + fixture.request().requestDigest(), + fixture.request().versionStateEpoch(), + fixture.request().publishWorkflowId(), + "different-commit", + fixture.request().contentDigest(), + fixture.request().digestSchemaVersion(), + fixture.request().suppliedOwnedAffectedTuples()); + assertThatThrownBy( + () -> + ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, changedCommit))) + .isInstanceOf(SnapshotConflictException.class) + .hasMessageContaining("complete immutable V25 freeze attempt"); + + CaptureRequest wrongSource = + new CaptureRequest( + NAMESPACE, + fixture.request().canonicalTenantId(), + UUID.randomUUID(), + fixture.request().intakeRequestId(), + fixture.request().publicationFence(), + fixture.request().publicationRequestId(), + fixture.request().requestDigest(), + fixture.request().versionStateEpoch(), + fixture.request().publishWorkflowId(), + fixture.request().appliedCommitId(), + fixture.request().contentDigest(), + fixture.request().digestSchemaVersion(), + fixture.request().suppliedOwnedAffectedTuples()); + assertThatThrownBy( + () -> + ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, wrongSource))) + .isInstanceOf(MissingOwnerHistoryException.class); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_graph_snapshot SET graph_sha256 = ? WHERE snapshot_id = ?", + "b".repeat(64), + firstSnapshot.snapshotId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + WorldAuthoredGraphSnapshot immutableReadback = + ownerTransaction() + .execute( + status -> snapshotRepository.findByFence(fixture.request().publicationFence())); + assertThat(immutableReadback.graphSha256()).isEqualTo(firstSnapshot.graphSha256()); + } finally { + allowFirstCommit.countDown(); + executor.shutdownNow(); + } + } + + @Test + void wrongTenantVersionParentEdgeDeniesCaptureBeforeSnapshotRetention() { + Fixture fixture = fixture(true); + WorldAuthoredGraphSnapshotCapture capture = captureComponent(); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, fixture.request()))) + .isInstanceOf(SnapshotConflictException.class) + .hasMessageContaining("zone parent is missing or belongs to another tenant/Version"); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + } + + @Test + void schemaOneAttemptCannotOmitExactIntakeRequestDigestOrMutateOwnerHistory() { + Fixture fixture = fixture(false); + WorldAuthoredSourceIntakeReceipt intake = fixture.intakeReceipt(); + long ownerCountBefore = ownerCount(intake.canonicalTenantId(), fixture.localVersionKey()); + long attemptCountBefore = attemptCount(intake.canonicalTenantId(), fixture.localVersionKey()); + + String publicationRequestId = "missing-intake-request-digest-" + UUID.randomUUID(); + String workflowId = + PublicationDigestRequestBinding.full( + intake.canonicalTenantId().toString(), + Long.toString(fixture.gameDesignVersionId()), + publicationRequestId) + .derivedWorkflowIdentity(); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO world_design_publication_fence_attempt (" + + "publication_fence, target_namespace, canonical_tenant_id, " + + "local_tenant_key, version_id, owner_binding_schema_version, " + + "canonical_version_id, version_identity_operation_id, " + + "game_design_version_id, intake_operation_id, intake_request_id, " + + "intake_request_digest, source_operation_id, source_evidence_digest, " + + "intake_receipt_digest, publication_request_id, request_digest, " + + "version_state_epoch, publish_workflow_id, applied_commit_id, " + + "content_digest, digest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, 2)", + UUID.randomUUID(), + NAMESPACE, + intake.canonicalTenantId(), + intake.localTenantKey(), + fixture.localVersionKey(), + fixture.request().canonicalVersionId(), + fixture.versionIdentityOperationId(), + fixture.gameDesignVersionId(), + intake.operationId(), + intake.intakeRequestId(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.receiptDigest(), + publicationRequestId, + REQUEST_DIGEST, + fixture.request().versionStateEpoch(), + workflowId, + "unbound-commit", + fixture.request().contentDigest())) + .isInstanceOf(DataIntegrityViolationException.class) + .satisfies(this::assertPublicationOwnerBindingConstraintDenial); + + assertThat(ownerCount(intake.canonicalTenantId(), fixture.localVersionKey())) + .isEqualTo(ownerCountBefore); + assertThat(attemptCount(intake.canonicalTenantId(), fixture.localVersionKey())) + .isEqualTo(attemptCountBefore); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + } + + @Test + void canonicalAuthoredRowsStillRejectLegacyWritesAfterSyntheticFixtureSetup() { + Fixture fixture = fixture(false); + WorldAuthoredGraphSnapshotCapture capture = captureComponent(); + WorldAuthoredGraphSnapshot retainedSnapshot = + ownerTransaction() + .execute(status -> captureWithGuardedSessionRole(capture, fixture.request())); + List retainedRowsBefore = syntheticRetentionRowCounts(fixture); + + assertThat(retainedRowsBefore).containsExactly(1L, 1L, 1L, 1L, 1L, 1L, 1L); + assertThat(retainedSnapshot.ownerCommitProofStatus()) + .isEqualTo(WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED); + assertThat(snapshotCount(fixture.request().publicationFence())).isEqualTo(1L); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + assertGuardedSessionReplicationRole(); + dsl.execute( + "INSERT INTO region (name, tenant_id, version_id, generation_seed) " + + "VALUES ('legacy bypass attempt', ?, ?, ?)", + fixture.intakeReceipt().localTenantKey(), + fixture.localVersionKey(), + LARGE_VALUE); + return null; + })) + .isInstanceOf(DataIntegrityViolationException.class) + .satisfies(this::assertV24CanonicalKeyDenial); + + assertThat(syntheticRetentionRowCounts(fixture)).isEqualTo(retainedRowsBefore); + assertThat(snapshotCount(fixture.request().publicationFence())).isEqualTo(1L); + WorldAuthoredGraphSnapshot readback = + ownerTransaction() + .execute( + status -> snapshotRepository.findByFence(fixture.request().publicationFence())); + assertThat(readback.snapshotId()).isEqualTo(retainedSnapshot.snapshotId()); + assertThat(readback.graphBytes()).containsExactly(retainedSnapshot.graphBytes()); + assertThat(readback.graphSha256()).isEqualTo(retainedSnapshot.graphSha256()); + assertThat(readback.captureRequestDigest()).isEqualTo(retainedSnapshot.captureRequestDigest()); + assertThat(readback.suppliedOwnedAffectedTuplesJson()) + .isEqualTo(retainedSnapshot.suppliedOwnedAffectedTuplesJson()); + assertThat(readback.ownerRevisionEvidenceJson()) + .isEqualTo(retainedSnapshot.ownerRevisionEvidenceJson()); + assertThat(readback.ownerCommitProofStatus()) + .isEqualTo(WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED); + } + + @Test + void sourceQualifiedOpenStagingReadsAllSixFamiliesWithoutChangingDatabaseContent() { + Fixture fixture = fixture(false, false); + WorldDraftRegionCommitPlan plan = stagingPlan(fixture, ownerBinding(fixture), false); + List before = syntheticRetentionRowCounts(fixture); + UnverifiedStagedContent staged = + ownerTransaction() + .execute( + status -> + new WorldDraftRegionStagingService(dsl, publicationFenceRepository) + .stage(plan)); + + assertThat(staged.binding()).isSameAs(plan.binding()); + assertThat(staged.ownerBinding()).isSameAs(plan.ownerBinding()); + assertThat(fixture.localVersionKey()).isNotEqualTo(fixture.gameDesignVersionId()); + assertThat(fixture.intakeReceipt().localTenantKey()) + .isNotEqualTo(fixture.intakeReceipt().source().sourceGameRowId()); + assertThat(staged.graph().regions()).hasSize(2); + assertThat(staged.graph().regions().get(0)).containsEntry("name", "Staged region"); + assertThat(staged.graph().regions().get(1)).containsEntry("name", "Untouched region"); + assertThat(staged.graph().zones()).hasSize(1); + assertThat(staged.graph().rooms()) + .singleElement() + .satisfies(room -> assertThat(room).containsEntry("description", null)); + assertThat(staged.graph().roomExits()).hasSize(1); + assertThat(staged.graph().generationRules()).hasSize(1); + assertThat(staged.graph().spawnBindings()) + .singleElement() + .satisfies(binding -> assertThat(binding).containsEntry("entityTemplateId", LARGE_VALUE)); + assertThat(syntheticRetentionRowCounts(fixture)).isEqualTo(before); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT owner_freeze_phase FROM world_design_publication_fence_owner " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND version_id = ?", + NAMESPACE, + fixture.request().canonicalTenantId(), + fixture.localVersionKey()), + "Staging must retain its exact OPEN owner row") + .get(0, String.class)) + .isEqualTo("OPEN"); + + // Both components must retain identical field/order/null/number encoding. This synthetic + // snapshot fixture proves representation equality, not synchronized owner application. + WorldAuthoredGraphSnapshot original = + ownerTransaction() + .execute(status -> captureComponent().capture(freezeOpenFixture(fixture))); + String expected = + new String(original.graphBytes(), StandardCharsets.UTF_8) + .replace("\"name\":\"authored region\"", "\"name\":\"Staged region\""); + assertThat(new String(staged.graph().encode(objectMapper), StandardCharsets.UTF_8)) + .isEqualTo(expected); + } + + @Test + void sourceQualifiedStagingRejectsChangedIntakeEvidenceBeforeOwnerCreation() { + Fixture fixture = fixture(false, false); + WorldDesignPublicationFenceEvidence.OwnerBinding exact = ownerBinding(fixture); + WorldDesignPublicationFenceEvidence.OwnerBinding changed = + new WorldDesignPublicationFenceEvidence.OwnerBinding( + exact.targetNamespace(), + exact.canonicalTenantId(), + exact.canonicalVersionId(), + exact.versionIdentityOperationId(), + exact.gameDesignVersionId(), + exact.intakeRequestId(), + exact.intakeOperationId(), + exact.intakeRequestDigest(), + exact.sourceOperationId(), + "sha256:" + "f".repeat(64), + exact.intakeReceiptDigest()); + WorldDraftRegionCommitPlan plan = stagingPlan(fixture, changed, false); + List before = syntheticRetentionRowCounts(fixture); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + new WorldDraftRegionStagingService(dsl, publicationFenceRepository) + .stage(plan))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_fence_owner " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND version_id = ?", + NAMESPACE, + fixture.request().canonicalTenantId(), + fixture.localVersionKey()), + "PostgreSQL must return the owner row count") + .get(0, Long.class)) + .isZero(); + assertThat(syntheticRetentionRowCounts(fixture)).isEqualTo(before); + } + + @Test + void sourceQualifiedStagingRejectsFrozenOwnerBeforeReadingAnInvalidPriorGraph() { + Fixture fixture = fixture(true); + WorldDraftRegionCommitPlan plan = stagingPlan(fixture, ownerBinding(fixture), false); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + new WorldDraftRegionStagingService(dsl, publicationFenceRepository) + .stage(plan))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("not open"); + } + + @Test + void sourceQualifiedStagingRejectsCrossVersionParentAndLateInvalidRevisionWithoutAnyApply() { + Fixture invalidGraph = fixture(true, false); + WorldDraftRegionCommitPlan graphPlan = + stagingPlan(invalidGraph, ownerBinding(invalidGraph), false); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + new WorldDraftRegionStagingService(dsl, publicationFenceRepository) + .stage(graphPlan))) + .isInstanceOf(SnapshotConflictException.class) + .hasMessageContaining("zone parent"); + + Fixture fixture = fixture(false, false); + List before = syntheticRetentionRowCounts(fixture); + WorldDraftRegionCommitPlan lateInvalid = stagingPlan(fixture, ownerBinding(fixture), true); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + new WorldDraftRegionStagingService(dsl, publicationFenceRepository) + .stage(lateInvalid))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not exist"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT name FROM region WHERE tenant_id = ? AND version_id = ? AND id = ?", + fixture.intakeReceipt().localTenantKey(), + fixture.localVersionKey(), + Long.parseLong( + fixture.request().suppliedOwnedAffectedTuples().get(0).aggregateId())), + "Rejected staging must retain the original region row") + .get(0, String.class)) + .isEqualTo("authored region"); + assertThat(syntheticRetentionRowCounts(fixture)).isEqualTo(before); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + } + + private WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding(Fixture fixture) { + WorldAuthoredSourceIntakeReceipt intake = fixture.intakeReceipt(); + return new WorldDesignPublicationFenceEvidence.OwnerBinding( + NAMESPACE, + intake.canonicalTenantId(), + fixture.request().canonicalVersionId(), + fixture.versionIdentityOperationId(), + fixture.gameDesignVersionId(), + intake.intakeRequestId(), + intake.operationId(), + intake.requestDigest(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.receiptDigest()); + } + + private WorldDraftRegionCommitPlan stagingPlan( + Fixture fixture, + WorldDesignPublicationFenceEvidence.OwnerBinding owner, + boolean lateInvalid) { + UUID commitId = UUID.randomUUID(); + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + String regionId = fixture.request().suppliedOwnedAffectedTuples().get(0).aggregateId(); + List ids = + lateInvalid ? List.of(regionId, Long.toString(Long.MAX_VALUE)) : List.of(regionId); + for (String id : ids) { + UUID revisionId = UUID.randomUUID(); + WorldDesignMutationRevision mutation = + WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revisionId.toString()) + .setCommitId(commitId.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setAggregateId(id) + .setExpectedDraftRevisionEpoch(1L) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(id) + .setExpectedDraftScopeRevisionEpoch(1L) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("Staged region") + .setGenerationSeed(LARGE_VALUE) + .setSpacingMultiplier(1.0d)) + .build(); + try { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + revisionId, + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().print(mutation))); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException(exception); + } + units.add(new AffectedUnit(Owner.WORLD_MANAGEMENT, "REGION", id, "AGGREGATE", id, "1")); + units.add(new AffectedUnit(Owner.WORLD_MANAGEMENT, "REGION", id, "REGION_SUBTREE", id, "1")); + } + AuthoredWorldSourceEvidence source = fixture.intakeReceipt().source(); + DraftCommitBinding binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.gameDesignVersionId(), + source.sourceGameTenantKey(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()), + UUID.randomUUID(), + commitId, + "synthetic-base", + revisions, + units); + return WorldDraftRegionCommitPlan.create(binding, owner); + } + + private CaptureRequest freezeOpenFixture(Fixture fixture) { + CaptureRequest request = fixture.request(); + WorldDesignPublicationFenceEvidence.OwnerBinding owner = ownerBinding(fixture); + WorldDesignPublicationFenceEvidence evidence = + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId()); + FrozenAttempt frozen = + publicationFenceRepository.claimFreeze( + evidence, + () -> + new Checkpoint( + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion())); + return new CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + frozen.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.suppliedOwnedAffectedTuples()); + } + + private Fixture fixture(boolean wrongRoomParent) { + return fixture(wrongRoomParent, true); + } + + private Fixture fixture(boolean wrongRoomParent, boolean freeze) { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + // Synthetic authenticated-source prerequisite only. Persist the real intake in its own + // transaction, then read its committed result before any owner resolution or freeze. + AuthoredWorldSourceEvidence source = + source(canonicalTenantId, tenantSlug, worldSlug, positiveLong()); + UUID intakeRequestId = UUID.randomUUID(); + WorldAuthoredSourceIntakeReceipt accepted = + ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, intakeRequestId, source)); + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository.read(NAMESPACE, intakeRequestId).orElseThrow(); + assertThat(intake).isEqualTo(accepted); + return ownerTransaction() + .execute( + status -> { + long gameDesignVersionId = GAME_DESIGN_VERSION_ID; + UUID canonicalVersion = UUID.randomUUID(); + UUID versionStateReadRequestId = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request versionStateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + versionStateReadRequestId, + canonicalTenantId, + worldSlug, + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + gameDesignVersionId); + AuthoredWorldVersionStateEvidence versionStateEvidence = + AuthoredWorldVersionStateEvidence.create( + versionStateRequest, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + WorldAuthoredVersionIdentityReceipt versionIdentity = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh(intake, versionStateEvidence); + long localVersionKey = versionIdentity.localVersionKey(); + + Long wrongParentZoneId = null; + if (wrongRoomParent) { + long legacyTenantId = positiveLong(); + long foreignRegionId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO region (name, tenant_id, version_id) " + + "VALUES ('foreign region', ?, 777777) RETURNING id", + legacyTenantId) + .fetchOne(0, Long.class), + "Foreign region insert did not return its generated ID"); + wrongParentZoneId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO zone (region_id, name, tenant_id, version_id) " + + "VALUES (?, 'foreign zone', ?, 777777) RETURNING id", + foreignRegionId, + legacyTenantId) + .fetchOne(0, Long.class), + "Foreign zone insert did not return its generated ID"); + } + // This synthetic component fixture stipulates owner-applied rows; no authenticated + // canonical World owner producer exists or is proved by this fixture. + SyntheticRows syntheticRows = + seedSyntheticCanonicalRows( + intake.localTenantKey(), localVersionKey, wrongParentZoneId, !freeze); + assertGuardedSessionReplicationRole(); + WorldDraftDesignDigest digest = + draftDigestService.getDraftDesignDigest( + Long.toString(intake.localTenantKey()), Long.toString(localVersionKey)); + + String publicationRequestId = "request-" + UUID.randomUUID(); + String publishWorkflowId = + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), + Long.toString(gameDesignVersionId), + publicationRequestId) + .derivedWorkflowIdentity(); + long versionStateEpoch = 7L; + assertGuardedSessionReplicationRole(); + WorldDesignPublicationFenceEvidence fenceRequest = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + canonicalTenantId, + canonicalVersion, + versionIdentity.operationId(), + gameDesignVersionId, + intake.intakeRequestId(), + intake.operationId(), + intake.requestDigest(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.receiptDigest(), + publicationRequestId, + REQUEST_DIGEST, + versionStateEpoch, + publishWorkflowId); + UUID publicationFence = + freeze + ? publicationFenceRepository + .claimFreeze( + fenceRequest, + () -> + new Checkpoint( + syntheticRows.commitId(), + digest.contentDigest(), + digest.digestSchemaVersion())) + .publicationFence() + : UUID.randomUUID(); + CaptureRequest request = + new CaptureRequest( + NAMESPACE, + canonicalTenantId, + canonicalVersion, + intakeRequestId, + publicationFence, + publicationRequestId, + REQUEST_DIGEST, + versionStateEpoch, + publishWorkflowId, + syntheticRows.commitId(), + digest.contentDigest(), + digest.digestSchemaVersion(), + List.of( + new OwnedAffectedTuple( + "WORLD_MANAGEMENT", + "WORLD_GENERATION_SUBTREE", + Long.toString(syntheticRows.regionId()), + "REGION_SUBTREE", + Long.toString(syntheticRows.regionId()), + "1"))); + return new Fixture( + request, + localVersionKey, + gameDesignVersionId, + versionIdentity.operationId(), + intake); + }); + } + + private WorldAuthoredGraphSnapshotCapture captureComponent() { + return new WorldAuthoredGraphSnapshotCapture( + dsl, draftDigestService, snapshotRepository, objectMapper); + } + + @Test + void retainedNumericSpawnSqlMappingAndPrimaryKeyDigestOrderRemainExact() { + Fixture fixture = fixture(false); + long first = positiveLong() / 2 + 1; + long second = first + 1; + ownerTransaction() + .execute( + status -> { + dsl.execute("SET LOCAL session_replication_role='replica'"); + for (long id : new long[] {Math.max(first, second), Math.min(first, second)}) { + dsl.execute( + "INSERT INTO world_entity_spawn_binding (id, tenant_id, version_id, room_id, entity_template_type, entity_template_id) " + + "SELECT ?, tenant_id, version_id, room_id, entity_template_type, entity_template_id + ? FROM world_entity_spawn_binding " + + "WHERE tenant_id=? AND version_id=? AND entity_template_id=?", + id, + id == first ? 1 : 2, + fixture.intakeReceipt().localTenantKey(), + fixture.localVersionKey(), + LARGE_VALUE); + } + dsl.execute("SET LOCAL session_replication_role='origin'"); + return null; + }); + var rows = + spawnRepository.findByTenantIdAndVersionIdOrderByIdAsc( + fixture.intakeReceipt().localTenantKey(), fixture.localVersionKey()); + assertThat(rows).hasSize(3); + assertThat( + rows.stream() + .map(net.firedevops.firemud.worldmanagement.entity.WorldEntitySpawnBinding::getId) + .toList()) + .isSorted(); + for (var row : rows) { + assertThat(row.getEntityTemplateId()).isPositive(); + assertThat(row.getEntityCanonicalTenantId()).isNull(); + assertThat(row.getEntityCanonicalVersionId()).isNull(); + assertThat(row.getEntityCanonicalTemplateId()).isNull(); + assertThat(spawnRepository.findById(row.getId()).orElseThrow()).isEqualTo(row); + } + var digest = + draftDigestService.getDraftDesignDigest( + Long.toString(fixture.intakeReceipt().localTenantKey()), + Long.toString(fixture.localVersionKey())); + assertThat(digest.digestSchemaVersion()).isEqualTo(3); + assertThat(digest) + .isEqualTo(draftDigestService.getDraftDesignDigest(digest.tenantId(), digest.scopeValue())); + assertGuardedSessionReplicationRole(); + } + + @Test + void newSchema2NumericSnapshotIsRejectedBeforeContentOrRevisionReads() { + Fixture fixture = fixture(false, false); + CaptureRequest r = fixture.request(); + CaptureRequest historical = + new CaptureRequest( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + r.publicationRequestId(), + r.requestDigest(), + r.versionStateEpoch(), + r.publishWorkflowId(), + r.appliedCommitId(), + r.contentDigest(), + 2, + r.suppliedOwnedAffectedTuples()); + Fixture old = + new Fixture( + historical, + fixture.localVersionKey(), + fixture.gameDesignVersionId(), + fixture.versionIdentityOperationId(), + fixture.intakeReceipt()); + CaptureRequest frozen = ownerTransaction().execute(status -> freezeOpenFixture(old)); + assertThatThrownBy( + () -> ownerTransaction().execute(status -> captureComponent().capture(frozen))) + .hasMessageContaining("requires digest schema 3"); + assertThat(snapshotCount(frozen.publicationFence())).isZero(); + } + + @Test + void mismatchedReturnedPrivateVersionDigestCannotCreateSnapshot() { + Fixture fixture = fixture(false); + var capture = + new WorldAuthoredGraphSnapshotCapture( + dsl, + (tenant, version) -> + new WorldDraftDesignDigest( + tenant, + Long.toString(fixture.localVersionKey() + 1), + fixture.request().appliedCommitId(), + fixture.request().contentDigest(), + 3), + snapshotRepository, + objectMapper); + assertThatThrownBy( + () -> ownerTransaction().execute(status -> capture.capture(fixture.request()))) + .hasMessageContaining("differs from the V25 frozen checkpoint"); + assertThat(snapshotCount(fixture.request().publicationFence())).isZero(); + } + + @Test + void v32PreservesOriginalSchema2SnapshotBytesAndExactRetry() throws Exception { + Fixture fixture = fixture(false); + WorldAuthoredGraphSnapshot original = + ownerTransaction().execute(status -> captureComponent().capture(fixture.request())); + CaptureRequest r = fixture.request(); + CaptureRequest historical = + new CaptureRequest( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + r.publicationRequestId(), + r.requestDigest(), + r.versionStateEpoch(), + r.publishWorkflowId(), + r.appliedCommitId(), + r.contentDigest(), + 2, + r.suppliedOwnedAffectedTuples()); + String schema = "retained_snapshot2_" + UUID.randomUUID().toString().replace("-", ""); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("28")) + .load() + .migrate(); + List tables = + List.of( + "world_authored_source_tenant_association", + "world_authored_source_intake", + "world_authored_version_identity", + "world_design_publication_fence_attempt", + "world_design_publication_fence_owner"); + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + DSLContext retained = DSL.using(connection, SQLDialect.POSTGRES); + retained.execute("SET search_path TO " + schema + ", public"); + connection.setAutoCommit(false); + retained.execute("SET LOCAL session_replication_role='replica'"); + for (String table : tables) { + String override = + table.equals("world_authored_version_identity") ? " OVERRIDING SYSTEM VALUE" : ""; + retained.execute( + "INSERT INTO " + + table + + override + + " SELECT * FROM world_management_service." + + table + + " WHERE local_tenant_key=?", + fixture.intakeReceipt().localTenantKey()); + } + retained.execute( + "INSERT INTO world_authored_source_tenant_key_reservation SELECT * " + + "FROM world_management_service.world_authored_source_tenant_key_reservation WHERE tenant_key=?", + fixture.intakeReceipt().localTenantKey()); + retained.execute( + "UPDATE world_design_publication_fence_attempt SET digest_schema_version=2 WHERE publication_fence=?", + r.publicationFence()); + // Install an original synthetic schema-2 capture under V28 before testing its forward + // migration. + retained.execute( + "INSERT INTO world_authored_graph_snapshot SELECT (jsonb_populate_record(NULL::world_authored_graph_snapshot, " + + "to_jsonb(t) || jsonb_build_object('digest_schema_version', 2, 'capture_request_digest', ?))).* " + + "FROM world_management_service.world_authored_graph_snapshot t WHERE publication_fence=?", + historicalCaptureDigest(original), + r.publicationFence()); + retained.execute("SET LOCAL session_replication_role='origin'"); + connection.commit(); + connection.setAutoCommit(true); + String before = + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_authored_graph_snapshot t"), + "expected retained schema-2 snapshot row") + .get(0, String.class); + String attemptBefore = + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_design_publication_fence_attempt t"), + "expected retained publication-fence attempt row") + .get(0, String.class); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat( + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_authored_graph_snapshot t"), + "expected retained schema-2 snapshot row") + .get(0, String.class)) + .isEqualTo(before); + assertThat( + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_design_publication_fence_attempt t"), + "expected retained publication-fence attempt row") + .get(0, String.class)) + .isEqualTo(attemptBefore); + var repo = new WorldAuthoredGraphSnapshotRepository(retained); + var capture = + new WorldAuthoredGraphSnapshotCapture( + retained, + (tenant, version) -> { + throw new AssertionError("Historical retry must never recompute content digest"); + }, + repo, + objectMapper); + var tx = + new TransactionTemplate( + new DataSourceTransactionManager(new SingleConnectionDataSource(connection, true))); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var recovered = tx.execute(status -> capture.capture(historical)); + assertThat(recovered.digestSchemaVersion()).isEqualTo(2); + assertThat(recovered.snapshotId()).isEqualTo(original.snapshotId()); + assertThat(recovered.graphBytes()).containsExactly(original.graphBytes()); + assertThat(recovered.ownerRevisionEvidenceJson()) + .isEqualTo(original.ownerRevisionEvidenceJson()); + assertThat( + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_authored_graph_snapshot t"), + "expected retained schema-2 snapshot row") + .get(0, String.class)) + .isEqualTo(before); + assertThatThrownBy(() -> tx.execute(status -> capture.capture(r))) + .isInstanceOf(SnapshotConflictException.class); + // INSERT-only guard rejects schema 2 (and unsupported values), preserving retained reads. + for (int denied : new int[] {2, 4}) { + assertThatThrownBy( + () -> + retained.execute( + "INSERT INTO world_authored_graph_snapshot SELECT " + + "(jsonb_populate_record(NULL::world_authored_graph_snapshot, to_jsonb(t) || jsonb_build_object('snapshot_id', ?, " + + "'digest_schema_version', ?))).* FROM world_authored_graph_snapshot t", + UUID.randomUUID(), + denied)) + .hasStackTraceContaining("requires digest schema 3"); + } + } finally { + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private String historicalCaptureDigest(WorldAuthoredGraphSnapshot snapshot) throws Exception { + // Independent original V28 capture-request preimage: exact ordered fields, no mutable content. + var fields = objectMapper.valueToTree(snapshot); + Map binding = new LinkedHashMap<>(); + for (String name : + List.of( + "targetNamespace", + "canonicalTenantId", + "canonicalVersionId", + "versionIdentityOperationId", + "worldSlug", + "gameDesignVersionId", + "localVersionKey", + "localTenantKey", + "intakeOperationId", + "intakeRequestId", + "intakeRequestDigest", + "sourceOperationId", + "sourceEvidenceDigest", + "intakeReceiptDigest", + "publicationFence", + "publicationRequestId", + "requestDigest", + "versionStateEpoch", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "suppliedOwnedAffectedTuplesJson")) { + binding.put(name, name.equals("digestSchemaVersion") ? 2 : fields.get(name)); + } + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(objectMapper.writeValueAsBytes(binding))); + } + + private WorldAuthoredGraphSnapshot captureWithGuardedSessionRole( + WorldAuthoredGraphSnapshotCapture capture, CaptureRequest request) { + assertGuardedSessionReplicationRole(); + return capture.capture(request); + } + + private SyntheticRows seedSyntheticCanonicalRows( + long localTenantKey, long localVersionKey, Long wrongParentZoneId, boolean untouchedRegion) { + String originalRole = currentSessionReplicationRole(); + assertThat(originalRole).isEqualTo("origin"); + Throwable seedFailure = null; + try { + // Bypass V24 triggers only while inserting these synthetic six-family and ledger rows. + dsl.execute("SET LOCAL session_replication_role = 'replica'"); + assertThat(currentSessionReplicationRole()).isEqualTo("replica"); + + long regionId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO region (name, tenant_id, version_id, generation_seed) " + + "VALUES ('authored region', ?, ?, ?) RETURNING id", + localTenantKey, + localVersionKey, + LARGE_VALUE) + .fetchOne(0, Long.class), + "Region insert did not return its generated ID"); + if (untouchedRegion) { + dsl.execute( + "INSERT INTO region (name, tenant_id, version_id, generation_seed) " + + "VALUES ('Untouched region', ?, ?, ?)", + localTenantKey, + localVersionKey, + Long.MIN_VALUE); + } + long zoneId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO zone (region_id, name, tenant_id, version_id) " + + "VALUES (?, 'authored zone', ?, ?) RETURNING id", + regionId, + localTenantKey, + localVersionKey) + .fetchOne(0, Long.class), + "Zone insert did not return its generated ID"); + long roomParentZoneId = wrongParentZoneId == null ? zoneId : wrongParentZoneId; + long roomId = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO room (zone_id, name, description, tenant_id, version_id) " + + "VALUES (?, 'authored room', NULL, ?, ?) RETURNING id", + roomParentZoneId, + localTenantKey, + localVersionKey) + .fetchOne(0, Long.class), + "Room insert did not return its generated ID"); + dsl.execute( + "INSERT INTO room_exit (tenant_id, version_id, from_room_id, to_room_id, direction, cost) " + + "VALUES (?, ?, ?, ?, 'NORTH', 2)", + localTenantKey, + localVersionKey, + roomId, + roomId); + dsl.execute( + "INSERT INTO generation_rule (tenant_id, version_id, name, scope_type, scope_id, value) " + + "VALUES (?, ?, 'dungeon', 'REGION_SUBTREE', ?, 'seeded')", + localTenantKey, + localVersionKey, + Long.toString(regionId)); + dsl.execute( + "INSERT INTO world_entity_spawn_binding (tenant_id, version_id, room_id, " + + "entity_template_type, entity_template_id, spawn_count, respawn_delay_seconds) " + + "VALUES (?, ?, ?, 'NPC', ?, 2, 30)", + localTenantKey, + localVersionKey, + roomId, + LARGE_VALUE); + String commitId = "commit-" + UUID.randomUUID(); + dsl.execute( + "INSERT INTO world_design_revision_ledger (tenant_id, version_id, commit_id, " + + "revision_id, operation_type, aggregate_type, requested_aggregate_id, " + + "applied_aggregate_id, result, aggregate_epoch_after, scope_epoch_after) " + + "VALUES (?, ?, ?, 'revision-1', 'UPSERT', 'WORLD_GENERATION_SUBTREE', ?, ?, 'APPLIED', 1, 1)", + localTenantKey, + localVersionKey, + commitId, + Long.toString(regionId), + regionId); + return new SyntheticRows(regionId, commitId); + } catch (RuntimeException | Error failure) { + seedFailure = failure; + throw failure; + } finally { + try { + String restoredRole = + Objects.requireNonNull( + dsl.resultQuery( + "SELECT set_config('session_replication_role', ?, true)", originalRole) + .fetchOne(0, String.class), + "PostgreSQL did not return restored session_replication_role"); + assertThat(restoredRole).isEqualTo(originalRole); + assertThat(currentSessionReplicationRole()).isEqualTo(originalRole); + } catch (RuntimeException | Error restoreFailure) { + if (seedFailure == null) { + throw restoreFailure; + } + // A PostgreSQL setup error aborts the transaction, so SET LOCAL will revert on rollback. + // Preserve that original setup error if this explicit restore cannot run in the aborted tx. + seedFailure.addSuppressed(restoreFailure); + } + } + } + + private String currentSessionReplicationRole() { + return Objects.requireNonNull( + dsl.resultQuery("SELECT current_setting('session_replication_role')") + .fetchOne(0, String.class), + "PostgreSQL did not return session_replication_role"); + } + + private void assertGuardedSessionReplicationRole() { + assertThat(currentSessionReplicationRole()).isEqualTo("origin"); + } + + private void assertV24CanonicalKeyDenial(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 void assertPublicationOwnerBindingConstraintDenial(Throwable throwable) { + assertThat(throwable).hasStackTraceContaining("ck_world_publication_attempt_owner_binding"); + Throwable cause = throwable; + while (cause != null && !(cause instanceof SQLException)) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); + } + + private CaptureRequest copyRequest(CaptureRequest request, List tuples) { + return new CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + tuples); + } + + private AuthoredWorldSourceEvidence source( + UUID tenantId, String tenantSlug, String worldSlug, long sourceGameRowId) { + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String displayName = "Synthetic graph snapshot world"; + String sourceTenantKey = "gd-row-" + sourceGameRowId; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private long snapshotCount(UUID fence) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM world_authored_graph_snapshot WHERE publication_fence = ?", + fence) + .fetchOne(0, Long.class), + "Snapshot count query returned no value"); + } + + private List syntheticRetentionRowCounts(Fixture fixture) { + return SYNTHETIC_RETENTION_TABLES.stream() + .map( + table -> + Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM " + + table + + " WHERE tenant_id = ? AND version_id = ?", + fixture.intakeReceipt().localTenantKey(), + fixture.localVersionKey()) + .fetchOne(0, Long.class), + table + " count query returned no value")) + .toList(); + } + + private long ownerCount(UUID tenantId, long localVersionKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM world_design_publication_fence_owner " + + "WHERE canonical_tenant_id = ? AND version_id = ?", + tenantId, + localVersionKey) + .fetchOne(0, Long.class), + "Owner count query returned no value"); + } + + private long attemptCount(UUID tenantId, long localVersionKey) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM world_design_publication_fence_attempt " + + "WHERE canonical_tenant_id = ? AND version_id = ?", + tenantId, + localVersionKey) + .fetchOne(0, Long.class), + "Attempt count query returned no value"); + } + + private static long positiveLong() { + return Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("World graph snapshot transaction barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "World graph snapshot transaction was interrupted", exception); + } + } + + private record Fixture( + CaptureRequest request, + long localVersionKey, + long gameDesignVersionId, + UUID versionIdentityOperationId, + WorldAuthoredSourceIntakeReceipt intakeReceipt) {} + + private record SyntheticRows(long regionId, String commitId) {} + + private static final class ForcedRollbackException extends RuntimeException {} +} 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..0466e30488 --- /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_V29"); + 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_V29"); + 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..013b3bdbc0 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java @@ -0,0 +1,775 @@ +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.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.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.service.impl.WorldManagementGrpcService; +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.ApplyWorldDesignMutationRequest; +import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationResponse; +import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; +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", + "world_design_publication_fence_attempt", + "world_design_publication_fence_owner", + "world_complete_launch_binding", + "world_authored_version_identity"); + 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; + @Autowired private WorldManagementGrpcService worldManagementGrpcService; + + @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); + } + } + + @Test + void registeredDraftMutationDeniesGameDesignPeerWithoutAccountCommitAuthorization() + throws Exception { + startRegisteredWorldManagementReceiver(); + Map> before = worldMutationRowSnapshot(); + + ApplyWorldDesignMutationResponse response = + applyWorldDesignMutation( + pki.gameDesignClient(), "gd-draft-denial", canonicalLookingDraftMutation()); + + assertDraftMutationDenied(response); + assertThat(worldMutationRowSnapshot()) + .as("World content, source, association, lifecycle and publication rows stay unchanged") + .isEqualTo(before); + } + + @Test + void registeredDraftMutationDeniesOtherAuthenticatedPeerBeforeOwnerMutation() throws Exception { + startRegisteredWorldManagementReceiver(); + Map> before = worldMutationRowSnapshot(); + + ApplyWorldDesignMutationResponse response = + applyWorldDesignMutation( + pki.accountClient(), "account-draft-denial", canonicalLookingDraftMutation()); + + assertDraftMutationDenied(response); + assertThat(worldMutationRowSnapshot()) + .as("World content, source, association, lifecycle and publication rows stay unchanged") + .isEqualTo(before); + } + + 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 void startRegisteredWorldManagementReceiver() throws Exception { + var withPeerIdentity = + ServerInterceptors.intercept(worldManagementGrpcService, new GrpcPeerIdentityInterceptor()); + 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(withPeerIdentity) + .build() + .start(); + } + + private ApplyWorldDesignMutationResponse applyWorldDesignMutation( + TestCertificate certificate, String label, ApplyWorldDesignMutationRequest request) + throws Exception { + ManagedChannel channel = + new GrpcChannelFactory() + .buildChannel( + "127.0.0.1:" + server.getPort(), + server.getPort(), + tlsProperties(certificate, label), + false); + try { + return WorldManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .applyWorldDesignMutation(request); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + 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 ApplyWorldDesignMutationRequest canonicalLookingDraftMutation() { + return ApplyWorldDesignMutationRequest.newBuilder() + .setTenantId("11111111-1111-4111-8111-111111111111") + .setVersionId("22222222-2222-4222-8222-222222222222") + .setCommitId("commit-1") + .setRevisionId("revision-1") + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId("44") + .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) + .build(); + } + + private static void assertDraftMutationDenied(ApplyWorldDesignMutationResponse response) { + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("FAILED_PRECONDITION"); + assertThat(response.getError().getMessage()) + .isEqualTo( + "Canonical World Draft writes are unavailable until current Account commit authorization is verified."); + assertThat(response.getResult()) + .isEqualTo(WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED); + assertThat(response.getTenantId()).isEmpty(); + assertThat(response.getVersionId()).isEmpty(); + assertThat(response.getAggregateId()).isEmpty(); + assertThat(response.getDraftRevisionEpoch()).isZero(); + assertThat(response.getDraftScopeRevisionEpoch()).isZero(); + assertThat(response.getAllFields().keySet()) + .containsExactly(ApplyWorldDesignMutationResponse.getDescriptor().findFieldByName("error")); + } + + 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/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java new file mode 100644 index 0000000000..aa47730226 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java @@ -0,0 +1,957 @@ +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.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +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.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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 java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +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.gamedesign.v1.VersionLifecycleState; +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 net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository.RegistrationConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import org.flywaydb.core.Flyway; +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.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.TransactionStatus; +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 WorldAuthoredVersionIdentityIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final UUID OTHER_CANONICAL_VERSION = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final List WORLD_CONTENT_AND_LIFECYCLE_TABLES = + List.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"); + + @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 DSLContext dsl; + @Autowired private WorldAuthoredSourceIntakeRepository sourceRepository; + @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 persistsExactIdentityAndPrivateKeyWithoutContentOrLifecycleWrites() { + long legacyTenantKey = + 6_900_000_000L + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 100_000L); + String legacyRegionName = "unmapped-legacy-region-" + UUID.randomUUID(); + long legacyRegionId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", + legacyTenantKey, + legacyRegionName), + "legacy region insert returned no row") + .get(0, Long.class); + long legacyGameInstanceId = positiveLong(); + String legacyControlRequest = "retained-legacy-" + UUID.randomUUID(); + long legacyWorldInstanceId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, " + + "generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, status) " + + "VALUES (?, ?, 17, ?, 'retained-descriptor', 29, 'legacy-config', " + + "31, 'retained-release', 3, 'ACTIVE') RETURNING id", + legacyTenantKey, + legacyGameInstanceId, + legacyControlRequest), + "legacy world-instance insert returned no row") + .get(0, Long.class); + + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + Map rowsBeforeIdentity = worldContentAndLifecycleCounts(); + assertThat(sourceReceipt.localTenantKey()).isNotEqualTo(legacyTenantKey); + + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 103L; + AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + return versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 5L); + }); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService service = service(client, repository, transactionManager); + UUID readRequestId = UUID.randomUUID(); + + WorldAuthoredVersionIdentityReceipt receipt = + withGameDesign( + () -> + service.associate( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + canonicalVersionId, + gameDesignVersionId, + readRequestId)); + WorldAuthoredVersionIdentityReceipt independentReadback = + repository + .readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId) + .orElseThrow(); + + assertThat(receipt).isEqualTo(independentReadback); + assertThat(receipt.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(receipt.canonicalVersionId()).isEqualTo(canonicalVersionId); + assertThat(receipt.gameDesignVersionId()).isEqualTo(gameDesignVersionId); + assertThat(receipt.localVersionKey()).isPositive(); + assertThat(receipt.versionStateEvidence().request().readRequestId()).isEqualTo(readRequestId); + assertThat( + repository.readByGameDesignVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), gameDesignVersionId)) + .contains(receipt); + assertThat(identityCount(source)).isEqualTo(1L); + assertThat(worldContentAndLifecycleCounts()).isEqualTo(rowsBeforeIdentity); + + var storedRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM world_authored_version_identity WHERE operation_id = ?", + receipt.operationId()), + "World authored-Version identity row was not persisted"); + assertThat(storedRow.get("operation_id", UUID.class)).isEqualTo(receipt.operationId()); + assertThat(storedRow.get("target_namespace", String.class)).isEqualTo(NAMESPACE); + assertThat(storedRow.get("canonical_tenant_id", UUID.class)) + .isEqualTo(source.canonicalTenantId()); + assertThat(storedRow.get("world_slug", String.class)).isEqualTo(source.worldSlug()); + assertThat(storedRow.get("canonical_version_id", UUID.class)).isEqualTo(canonicalVersionId); + assertThat(storedRow.get("game_design_version_id", Long.class)).isEqualTo(gameDesignVersionId); + assertThat(storedRow.get("local_version_key", Long.class)).isEqualTo(receipt.localVersionKey()); + assertThat(storedRow.get("intake_operation_id", UUID.class)) + .isEqualTo(sourceReceipt.operationId()); + assertThat(storedRow.get("intake_request_id", UUID.class)) + .isEqualTo(sourceReceipt.intakeRequestId()); + assertThat(storedRow.get("local_tenant_key", Long.class)) + .isEqualTo(sourceReceipt.localTenantKey()); + assertThat(storedRow.get("intake_request_digest", String.class)) + .isEqualTo(sourceReceipt.requestDigest()); + assertThat(storedRow.get("source_operation_id", UUID.class)).isEqualTo(source.operationId()); + assertThat(storedRow.get("source_evidence_digest", String.class)) + .isEqualTo(source.evidenceDigest()); + assertThat(storedRow.get("intake_receipt_digest", String.class)) + .isEqualTo(sourceReceipt.receiptDigest()); + assertThat(storedRow.get("version_state_read_request_id", UUID.class)).isEqualTo(readRequestId); + assertThat(storedRow.get("version_state_evidence_digest", String.class)) + .isEqualTo(receipt.versionStateEvidence().evidenceDigest()); + assertThat(storedRow.get("version_state_evidence_json", String.class)) + .contains(source.operationId().toString(), canonicalVersionId.toString()); + var localKeyColumn = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT is_identity, identity_generation FROM information_schema.columns " + + "WHERE table_schema = current_schema() " + + "AND table_name = 'world_authored_version_identity' " + + "AND column_name = 'local_version_key'"), + "World local version key identity metadata was not found"); + assertThat(localKeyColumn.get("is_identity", String.class)).isEqualTo("YES"); + assertThat(localKeyColumn.get("identity_generation", String.class)).isEqualTo("ALWAYS"); + + var retainedRegion = + Objects.requireNonNull( + dsl.fetchOne("SELECT tenant_id, name FROM region WHERE id = ?", legacyRegionId), + "unmapped legacy region disappeared"); + assertThat(retainedRegion.get("tenant_id", Long.class)).isEqualTo(legacyTenantKey); + assertThat(retainedRegion.get("name", String.class)).isEqualTo(legacyRegionName); + var retainedWorld = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_id, game_instance_id, control_plane_request_id, version_id, status " + + "FROM world_instance WHERE id = ?", + legacyWorldInstanceId), + "unmapped legacy world-instance row disappeared"); + assertThat(retainedWorld.get("tenant_id", Long.class)).isEqualTo(legacyTenantKey); + assertThat(retainedWorld.get("game_instance_id", Long.class)).isEqualTo(legacyGameInstanceId); + assertThat(retainedWorld.get("control_plane_request_id", String.class)) + .isEqualTo(legacyControlRequest); + assertThat(retainedWorld.get("version_id", Long.class)).isEqualTo(29L); + assertThat(retainedWorld.get("status", String.class)).isEqualTo("ACTIVE"); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_authored_version_identity SET world_slug = ? " + + "WHERE operation_id = ?", + "rewritten-world", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_authored_version_identity WHERE operation_id = ?", + receipt.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_authored_version_identity")) + .isInstanceOf(DataAccessException.class); + assertThat(identityCount(source)).isEqualTo(1L); + verify(client, times(1)).read(any()); + } + + @Test + void deniesWrongGameDesignIdentitySourceNamespaceAndMissingIntakeBeforeOwnerWrites() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 211L; + + AuthoredWorldVersionStateClient wrongUuidClient = mock(AuthoredWorldVersionStateClient.class); + when(wrongUuidClient.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + invocation.getArgument(0), + source, + OTHER_CANONICAL_VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 8L)); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService wrongUuidService = + service(wrongUuidClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + wrongUuidService, + source, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(InvalidIdentityEvidenceException.class); + assertThat(identityCount(source)).isZero(); + + AuthoredWorldVersionStateClient wrongPeerClient = mock(AuthoredWorldVersionStateClient.class); + WorldAuthoredVersionIdentityService wrongPeerService = + service(wrongPeerClient, repository, transactionManager); + assertThatThrownBy( + () -> + withPeer( + NAMESPACE, + "game-session-service", + () -> + associate( + wrongPeerService, + source, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(SecurityException.class); + verify(wrongPeerClient, never()).read(any()); + assertThat(identityCount(source)).isZero(); + + AuthoredWorldSourceEvidence substitutedSource = source(UUID.randomUUID(), randomWorld()); + AuthoredWorldVersionStateClient wrongSourceClient = mock(AuthoredWorldVersionStateClient.class); + UUID substitutedReadId = UUID.randomUUID(); + when(wrongSourceClient.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + request(substitutedSource, substitutedReadId, gameDesignVersionId), + substitutedSource, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 9L)); + WorldAuthoredVersionIdentityService wrongSourceService = + service(wrongSourceClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + wrongSourceService, + source, + canonicalVersionId, + gameDesignVersionId, + substitutedReadId))) + .isInstanceOf(InvalidIdentityEvidenceException.class); + assertThat(identityCount(source)).isZero(); + assertThat(identityCount(substitutedSource)).isZero(); + + AuthoredWorldVersionStateClient wrongNamespaceClient = + mock(AuthoredWorldVersionStateClient.class); + WorldAuthoredVersionIdentityService wrongNamespaceService = + service(wrongNamespaceClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + wrongNamespaceService.associate( + "other-namespace", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(SecurityException.class); + verify(wrongNamespaceClient, never()).read(any()); + assertThat(identityCount(source)).isZero(); + + AuthoredWorldSourceEvidence missingSource = source(UUID.randomUUID(), randomWorld()); + AuthoredWorldVersionStateClient missingSourceClient = + mock(AuthoredWorldVersionStateClient.class); + when(missingSourceClient.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + invocation.getArgument(0), + missingSource, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 10L)); + WorldAuthoredVersionIdentityService missingSourceService = + service(missingSourceClient, repository, transactionManager); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + missingSourceService, + missingSource, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(InvalidIdentityEvidenceException.class); + assertThat(identityCount(missingSource)).isZero(); + assertThat( + sourceRepository.readBySource( + NAMESPACE, + missingSource.canonicalTenantId(), + missingSource.worldSlug(), + missingSource.operationId(), + missingSource.evidenceDigest())) + .isEmpty(); + } + + @Test + void concurrentExactStableIdentityReturnsOneOriginalHistoricalReceipt() throws Exception { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 307L; + UUID firstReadId = UUID.randomUUID(); + UUID secondReadId = UUID.randomUUID(); + CountDownLatch bothRead = new CountDownLatch(2); + AtomicReference firstEvidence = new AtomicReference<>(); + AtomicReference secondEvidence = new AtomicReference<>(); + AuthoredWorldVersionStateClient firstClient = mock(AuthoredWorldVersionStateClient.class); + AuthoredWorldVersionStateClient secondClient = mock(AuthoredWorldVersionStateClient.class); + when(firstClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + awaitReadBarrier(bothRead); + AuthoredWorldVersionStateEvidence evidence = + versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 12L); + firstEvidence.set(evidence); + return evidence; + }); + when(secondClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + awaitReadBarrier(bothRead); + AuthoredWorldVersionStateEvidence evidence = + versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + 13L); + secondEvidence.set(evidence); + return evidence; + }); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService firstService = + service(firstClient, repository, transactionManager); + WorldAuthoredVersionIdentityService secondService = + service(secondClient, repository, transactionManager); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> + withGameDesign( + () -> + associate( + firstService, + source, + canonicalVersionId, + gameDesignVersionId, + firstReadId))); + Future second = + executor.submit( + () -> + withGameDesign( + () -> + associate( + secondService, + source, + canonicalVersionId, + gameDesignVersionId, + secondReadId))); + WorldAuthoredVersionIdentityReceipt firstReceipt = first.get(25, TimeUnit.SECONDS); + WorldAuthoredVersionIdentityReceipt secondReceipt = second.get(25, TimeUnit.SECONDS); + + assertThat(firstReceipt).isEqualTo(secondReceipt); + assertThat(firstReceipt.operationId()).isEqualTo(secondReceipt.operationId()); + assertThat(firstReceipt.localVersionKey()).isEqualTo(secondReceipt.localVersionKey()); + assertThat(firstReceipt.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(firstReceipt.versionStateEvidence()) + .isIn(firstEvidence.get(), secondEvidence.get()); + assertThat(firstEvidence.get().evidenceDigest()) + .isNotEqualTo(secondEvidence.get().evidenceDigest()); + assertThat(firstEvidence.get().request().readRequestId()) + .isNotEqualTo(secondEvidence.get().request().readRequestId()); + assertThat( + repository.readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId)) + .contains(firstReceipt); + assertThat(identityCount(source)).isEqualTo(1L); + } + verify(firstClient, times(1)).read(any()); + verify(secondClient, times(1)).read(any()); + } + + @Test + void conflictingUuidOrGameDesignSelectorDoesNotRewriteTheOriginalReceipt() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 401L; + AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + UUID returnedCanonicalId = + request.versionId() == gameDesignVersionId + ? canonicalVersionId + : OTHER_CANONICAL_VERSION; + return versionEvidence( + request, + source, + returnedCanonicalId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 16L); + }); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService service = service(client, repository, transactionManager); + WorldAuthoredVersionIdentityReceipt original = + withGameDesign( + () -> + associate( + service, source, canonicalVersionId, gameDesignVersionId, UUID.randomUUID())); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + service, + source, + canonicalVersionId, + gameDesignVersionId + 1, + UUID.randomUUID()))) + .isInstanceOf(RegistrationConflictException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + associate( + service, + source, + OTHER_CANONICAL_VERSION, + gameDesignVersionId, + UUID.randomUUID()))) + .isInstanceOf(RegistrationConflictException.class); + + assertThat( + repository.readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId)) + .contains(original); + assertThat(identityCount(source)).isEqualTo(1L); + verify(client, times(1)).read(any()); + } + + @Test + void recoversLostCommitAcknowledgmentAndRetriesWithoutRereadingOrReminting() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = 503L; + AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> + versionEvidence( + invocation.getArgument(0), + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 21L)); + WorldAuthoredVersionIdentityRepository repository = + new WorldAuthoredVersionIdentityRepository(dsl); + WorldAuthoredVersionIdentityService service = + service( + client, repository, new LostCommitAcknowledgmentTransactionManager(transactionManager)); + UUID originalReadId = UUID.randomUUID(); + + WorldAuthoredVersionIdentityReceipt recovered = + withGameDesign( + () -> + associate( + service, source, canonicalVersionId, gameDesignVersionId, originalReadId)); + WorldAuthoredVersionIdentityReceipt retry = + withGameDesign( + () -> + associate( + service, source, canonicalVersionId, gameDesignVersionId, UUID.randomUUID())); + + assertThat(recovered).isEqualTo(retry); + assertThat(retry.versionStateEvidence().request().readRequestId()).isEqualTo(originalReadId); + assertThat(identityCount(source)).isEqualTo(1L); + assertThat( + repository.readByCanonicalVersion( + NAMESPACE, source.canonicalTenantId(), source.worldSlug(), canonicalVersionId)) + .contains(recovered); + verify(client, times(1)).read(any()); + } + + @Test + void forwardV27MigrationPreservesRetainedRowsWithoutInferringIdentityAssociations() + throws SQLException { + String schema = "world_version_identity_" + UUID.randomUUID().toString().replace("-", ""); + long legacyTenantKey = + 8_300_000_000L + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 100_000L); + String firstRegionName = "retained-v26-region-a-" + UUID.randomUUID(); + String secondRegionName = "retained-v26-region-b-" + UUID.randomUUID(); + long legacyGameInstanceId = positiveLong(); + try { + migrateFixture(schema, MigrationVersion.fromVersion("26")); + try (Connection connection = fixtureConnection(schema)) { + try (PreparedStatement region = + connection.prepareStatement("INSERT INTO region (tenant_id, name) VALUES (?, ?)")) { + region.setLong(1, legacyTenantKey); + region.setString(2, firstRegionName); + region.executeUpdate(); + region.setLong(1, legacyTenantKey + 1); + region.setString(2, secondRegionName); + region.executeUpdate(); + } + try (PreparedStatement world = + connection.prepareStatement( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, " + + "generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, status) " + + "VALUES (?, ?, 23, 'retained-v26-request', 'retained-v26-descriptor', " + + "37, 'retained-v26-config', 41, 'retained-v26-release', 4, 'ACTIVE')")) { + world.setLong(1, legacyTenantKey); + world.setLong(2, legacyGameInstanceId); + world.executeUpdate(); + } + } + + migrateFixture(schema, null); + + try (Connection connection = fixtureConnection(schema); + Statement statement = connection.createStatement()) { + try (PreparedStatement regions = + connection.prepareStatement( + "SELECT tenant_id, name FROM region WHERE tenant_id IN (?, ?) " + + "ORDER BY tenant_id")) { + regions.setLong(1, legacyTenantKey); + regions.setLong(2, legacyTenantKey + 1); + try (ResultSet result = regions.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_id")).isEqualTo(legacyTenantKey); + assertThat(result.getString("name")).isEqualTo(firstRegionName); + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_id")).isEqualTo(legacyTenantKey + 1); + assertThat(result.getString("name")).isEqualTo(secondRegionName); + assertThat(result.next()).isFalse(); + } + } + try (PreparedStatement worlds = + connection.prepareStatement( + "SELECT tenant_id, game_instance_id, version_id, status FROM world_instance " + + "WHERE tenant_id = ?")) { + worlds.setLong(1, legacyTenantKey); + try (ResultSet result = worlds.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_id")).isEqualTo(legacyTenantKey); + assertThat(result.getLong("game_instance_id")).isEqualTo(legacyGameInstanceId); + assertThat(result.getLong("version_id")).isEqualTo(37L); + assertThat(result.getString("status")).isEqualTo("ACTIVE"); + assertThat(result.next()).isFalse(); + } + } + assertCount(statement, "world_authored_version_identity", 0L); + assertCount(statement, "world_authored_source_tenant_association", 0L); + try (PreparedStatement reservations = + connection.prepareStatement( + "SELECT tenant_key, claim_kind, target_namespace, canonical_tenant_id " + + "FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key IN (?, ?) ORDER BY tenant_key")) { + reservations.setLong(1, legacyTenantKey); + reservations.setLong(2, legacyTenantKey + 1); + try (ResultSet result = reservations.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_key")).isEqualTo(legacyTenantKey); + assertThat(result.getString("claim_kind")).isEqualTo("LEGACY_NUMERIC"); + assertThat(result.getString("target_namespace")).isNull(); + assertThat(result.getObject("canonical_tenant_id")).isNull(); + assertThat(result.next()).isTrue(); + assertThat(result.getLong("tenant_key")).isEqualTo(legacyTenantKey + 1); + assertThat(result.getString("claim_kind")).isEqualTo("LEGACY_NUMERIC"); + assertThat(result.getString("target_namespace")).isNull(); + assertThat(result.getObject("canonical_tenant_id")).isNull(); + assertThat(result.next()).isFalse(); + } + } + } + } finally { + dropFixtureSchema(schema); + } + } + + private WorldAuthoredSourceIntakeReceipt acceptSource(AuthoredWorldSourceEvidence source) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + return Objects.requireNonNull( + transaction.execute( + status -> sourceRepository.acceptFresh(NAMESPACE, UUID.randomUUID(), source)), + "World source intake returned no receipt"); + } + + private WorldAuthoredVersionIdentityService service( + AuthoredWorldVersionStateClient client, + WorldAuthoredVersionIdentityRepository repository, + PlatformTransactionManager manager) { + return new WorldAuthoredVersionIdentityService( + client, repository, sourceRepository, manager, NAMESPACE); + } + + private static WorldAuthoredVersionIdentityReceipt associate( + WorldAuthoredVersionIdentityService service, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + long gameDesignVersionId, + UUID readRequestId) { + return service.associate( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + canonicalVersionId, + gameDesignVersionId, + readRequestId); + } + + private Map worldContentAndLifecycleCounts() { + Map counts = new LinkedHashMap<>(); + for (String table : WORLD_CONTENT_AND_LIFECYCLE_TABLES) { + counts.put( + table, + Objects.requireNonNull( + dsl.fetchOne("SELECT COUNT(*) FROM " + table), + "World content count query returned no row") + .get(0, Long.class)); + } + return Map.copyOf(counts); + } + + private long identityCount(AuthoredWorldSourceEvidence source) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_authored_version_identity WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND world_slug = ?", + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug()), + "World authored-Version identity count query returned no row") + .get(0, Long.class); + } + + private static AuthoredWorldSourceEvidence source(UUID tenant, String worldSlug) { + UUID registrationRequest = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String displayName = "Source " + tenant.toString().substring(0, 8); + long sourceGameRowId = Math.max(1L, tenant.getLeastSignificantBits() & Long.MAX_VALUE); + String sourceGameTenantKey = "source-" + tenant.toString().replace("-", "").substring(0, 24); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequest, tenant, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static AuthoredWorldVersionStateEvidence.Request request( + AuthoredWorldSourceEvidence source, UUID readRequestId, long gameDesignVersionId) { + return new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + readRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gameDesignVersionId); + } + + private static AuthoredWorldVersionStateEvidence versionEvidence( + AuthoredWorldVersionStateEvidence.Request request, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + VersionLifecycleState state, + long epoch) { + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, state, epoch); + } + + private static String randomWorld() { + return "world-" + UUID.randomUUID().toString().replace("-", "").substring(0, 18); + } + + private static long positiveLong() { + return Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + } + + private static T withGameDesign(java.util.function.Supplier action) { + return withPeer(NAMESPACE, "game-design-service", action); + } + + private static T withPeer( + String namespace, String service, java.util.function.Supplier 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 { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static void awaitReadBarrier(CountDownLatch latch) { + latch.countDown(); + try { + if (!latch.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent Version identity read barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent Version identity read was interrupted", exception); + } + } + + 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 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 assertCount(Statement statement, String table, long expected) + throws SQLException { + try (ResultSet result = statement.executeQuery("SELECT COUNT(*) FROM " + table)) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong(1)).isEqualTo(expected); + } + } + + private static final class LostCommitAcknowledgmentTransactionManager + implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private boolean firstCommit = true; + + private LostCommitAcknowledgmentTransactionManager(PlatformTransactionManager delegate) { + this.delegate = delegate; + } + + @Override + public TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + return delegate.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + delegate.commit(status); + if (firstCommit) { + firstCommit = false; + throw new IllegalStateException("simulated lost World identity commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + if (!status.isCompleted()) { + delegate.rollback(status); + } + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java new file mode 100644 index 0000000000..9436b9c4c4 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java @@ -0,0 +1,1148 @@ +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.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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 javax.sql.DataSource; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +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.gamedesign.v1.VersionLifecycleState; +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 net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository.RegistrationConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingService; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +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.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.TransactionStatus; +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 WorldCompleteLaunchBindingIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final UUID VERSION = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID OTHER_CANONICAL_VERSION = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + + @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 DSLContext dsl; + @Autowired private DataSource dataSource; + @Autowired private WorldAuthoredSourceIntakeRepository sourceRepository; + @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 persistsCompletePairReadsItBackAndLeavesUnmappedRetainedRowsUntouched() { + long retainedLegacyKey = + 7_900_000_000L + Math.abs(UUID.randomUUID().getLeastSignificantBits() % 100_000L); + String retainedName = "unmapped-retained-" + UUID.randomUUID(); + Long retainedRegionId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region (tenant_id, name) VALUES (?, ?) RETURNING id", + retainedLegacyKey, + retainedName), + "retained region insert returned no row") + .get(0, Long.class); + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 41L); + GetRequest request = request(evidence); + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.getComplete(any())).thenReturn(evidence); + WorldCompleteLaunchBindingService service = service(client, transactionManager); + + WorldCompleteLaunchBindingReceipt first = withGameSession(() -> service.bind(request)); + WorldCompleteLaunchBindingReceipt retry = + withGameSession(() -> service.bind(request(evidence))); + + assertThat(first).isEqualTo(retry); + assertThat(first.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(first.evidence()).isEqualTo(evidence); + assertThat(first.operationId()).isNotEqualTo(sourceReceipt.operationId()); + verify(client).getComplete(any()); + Record bindingRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT binding_operation_id, intake_operation_id, intake_request_id, " + + "local_tenant_key, source_operation_id, source_evidence_digest, " + + "intake_receipt_digest, descriptor_request_digest, descriptor_result_digest, " + + "release_attestation_digest, descriptor_json, release_attestation_json " + + "FROM world_complete_launch_binding WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND control_plane_request_id = ?", + NAMESPACE, + source.canonicalTenantId(), + evidence.descriptor().controlPlaneRequestId()), + "complete launch binding row was not persisted"); + assertThat(bindingRow.get("binding_operation_id", UUID.class)).isEqualTo(first.operationId()); + assertThat(bindingRow.get("intake_operation_id", UUID.class)) + .isEqualTo(sourceReceipt.operationId()); + assertThat(bindingRow.get("intake_request_id", UUID.class)) + .isEqualTo(sourceReceipt.intakeRequestId()); + assertThat(bindingRow.get("local_tenant_key", Long.class)) + .isEqualTo(sourceReceipt.localTenantKey()); + assertThat(bindingRow.get("source_operation_id", UUID.class)).isEqualTo(source.operationId()); + assertThat(bindingRow.get("source_evidence_digest", String.class)) + .isEqualTo(source.evidenceDigest()); + assertThat(bindingRow.get("intake_receipt_digest", String.class)) + .isEqualTo(sourceReceipt.receiptDigest()); + assertThat(bindingRow.get("descriptor_request_digest", String.class)) + .isEqualTo(evidence.descriptor().requestDigest()); + assertThat(bindingRow.get("descriptor_result_digest", String.class)) + .isEqualTo(evidence.descriptor().resultDigest()); + assertThat(bindingRow.get("release_attestation_digest", String.class)) + .isEqualTo(evidence.releaseAttestation().evidenceDigest()); + assertThat(bindingRow.get("descriptor_json", String.class)) + .contains(evidence.descriptor().resultDigest()); + assertThat(bindingRow.get("release_attestation_json", String.class)) + .contains(evidence.releaseAttestation().evidenceDigest()); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_id, name FROM region WHERE id = ?", retainedRegionId), + "retained region readback returned no row") + .get("tenant_id", Long.class)) + .isEqualTo(retainedLegacyKey); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT name FROM region WHERE id = ?", retainedRegionId), + "retained region name readback returned no row") + .get("name", String.class)) + .isEqualTo(retainedName); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_complete_launch_binding SET world_slug = ? " + + "WHERE binding_operation_id = ?", + "changed-world", + first.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_complete_launch_binding WHERE binding_operation_id = ?", + first.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_complete_launch_binding")) + .isInstanceOf(DataAccessException.class); + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + } + + @Test + void forwardV26MigrationPreservesUnmappedRetainedWorldRows() throws SQLException { + String schema = + "world_complete_launch_binding_" + UUID.randomUUID().toString().replace("-", ""); + long retainedLegacyKey = + 8_700_000_000L + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 1_000_000L); + String retainedName = "retained-before-v26-" + UUID.randomUUID(); + try { + migrateFixture(schema, MigrationVersion.fromVersion("25")); + try (Connection connection = fixtureConnection(schema); + PreparedStatement statement = + connection.prepareStatement("INSERT INTO region (tenant_id, name) VALUES (?, ?)")) { + statement.setLong(1, retainedLegacyKey); + statement.setString(2, retainedName); + statement.executeUpdate(); + } + migrateFixture(schema, null); + + try (Connection connection = fixtureConnection(schema); + Statement statement = connection.createStatement()) { + try (PreparedStatement retainedQuery = + connection.prepareStatement("SELECT tenant_id, name FROM region WHERE tenant_id = ?")) { + retainedQuery.setLong(1, retainedLegacyKey); + try (ResultSet retained = retainedQuery.executeQuery()) { + assertThat(retained.next()).isTrue(); + assertThat(retained.getLong("tenant_id")).isEqualTo(retainedLegacyKey); + assertThat(retained.getString("name")).isEqualTo(retainedName); + assertThat(retained.next()).isFalse(); + } + } + try (ResultSet bindingTable = + statement.executeQuery("SELECT COUNT(*) FROM world_complete_launch_binding")) { + assertThat(bindingTable.next()).isTrue(); + assertThat(bindingTable.getLong(1)).isZero(); + } + } + } finally { + dropFixtureSchema(schema); + } + } + + @Test + void deniesMissingOrSubstitutedSourceBeforeAnyWorldOwnerWrite() { + AuthoredWorldSourceEvidence retainedSource = source(UUID.randomUUID(), randomWorld()); + acceptSource(retainedSource); + AuthoredWorldSourceEvidence substitutedSource = source(UUID.randomUUID(), randomWorld()); + CompleteLaunchBindingEvidence substituted = evidence(substitutedSource, controlRequest(), 43L); + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.getComplete(any())).thenReturn(substituted); + WorldCompleteLaunchBindingService service = service(client, transactionManager); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(request(substituted)))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class); + assertThat(countBindings(substitutedSource.canonicalTenantId())).isZero(); + verify(client).getComplete(any()); + } + + @Test + void simultaneousExactRetriesReturnTheSameDurableReceiptAndOwnerOperation() throws Exception { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 50L); + CountDownLatch bothFetched = new CountDownLatch(2); + AuthoredWorldLaunchDescriptorClient firstClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + AuthoredWorldLaunchDescriptorClient secondClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(firstClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return evidence; + }); + when(secondClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return evidence; + }); + WorldCompleteLaunchBindingService firstService = service(firstClient, transactionManager); + WorldCompleteLaunchBindingService secondService = service(secondClient, transactionManager); + GetRequest firstRequest = request(evidence); + GetRequest secondRequest = request(evidence); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit(() -> withGameSession(() -> firstService.bind(firstRequest))); + Future second = + executor.submit(() -> withGameSession(() -> secondService.bind(secondRequest))); + WorldCompleteLaunchBindingReceipt firstReceipt = first.get(20, TimeUnit.SECONDS); + WorldCompleteLaunchBindingReceipt secondReceipt = second.get(20, TimeUnit.SECONDS); + + assertThat(firstReceipt).isEqualTo(secondReceipt); + assertThat(firstReceipt.operationId()).isEqualTo(secondReceipt.operationId()); + assertThat(firstReceipt.evidence()).isEqualTo(evidence); + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT binding_operation_id FROM world_complete_launch_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND control_plane_request_id = ?", + NAMESPACE, + source.canonicalTenantId(), + evidence.descriptor().controlPlaneRequestId()), + "complete launch binding operation readback returned no row") + .get("binding_operation_id", UUID.class)) + .isEqualTo(firstReceipt.operationId()); + } + verify(firstClient).getComplete(any()); + verify(secondClient).getComplete(any()); + } + + @Test + void concurrentExactAndChangedClaimsKeepOneImmutableBinding() throws Exception { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + String stableControlRequest = controlRequest(); + CompleteLaunchBindingEvidence original = evidence(source, stableControlRequest, 51L); + CompleteLaunchBindingEvidence changed = evidence(source, stableControlRequest, 52L); + CountDownLatch bothFetched = new CountDownLatch(2); + AuthoredWorldLaunchDescriptorClient originalClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + AuthoredWorldLaunchDescriptorClient changedClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(originalClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return original; + }); + when(changedClient.getComplete(any())) + .thenAnswer( + invocation -> { + awaitFetchBarrier(bothFetched); + return changed; + }); + WorldCompleteLaunchBindingService originalService = service(originalClient, transactionManager); + WorldCompleteLaunchBindingService changedService = service(changedClient, transactionManager); + GetRequest originalRequest = request(original); + GetRequest changedRequest = request(changed); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = executor.submit(() -> attempt(originalService, originalRequest)); + Future second = executor.submit(() -> attempt(changedService, changedRequest)); + Object firstResult = first.get(20, TimeUnit.SECONDS); + Object secondResult = second.get(20, TimeUnit.SECONDS); + WorldCompleteLaunchBindingReceipt receipt; + if (firstResult instanceof WorldCompleteLaunchBindingReceipt firstReceipt) { + receipt = firstReceipt; + assertThat(secondResult).isInstanceOf(RegistrationConflictException.class); + } else { + assertThat(firstResult).isInstanceOf(RegistrationConflictException.class); + assertThat(secondResult).isInstanceOf(WorldCompleteLaunchBindingReceipt.class); + receipt = (WorldCompleteLaunchBindingReceipt) secondResult; + } + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT binding_operation_id FROM world_complete_launch_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND control_plane_request_id = ?", + NAMESPACE, + source.canonicalTenantId(), + stableControlRequest), + "complete launch binding operation readback returned no row") + .get("binding_operation_id", UUID.class)) + .isEqualTo(receipt.operationId()); + } + } + + @Test + void recoversCommittedBindingWhenOwnerCommitAcknowledgmentIsLost() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 61L); + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.getComplete(any())).thenReturn(evidence); + LostCommitAcknowledgmentTransactionManager manager = + new LostCommitAcknowledgmentTransactionManager(transactionManager); + WorldCompleteLaunchBindingService service = service(client, manager); + + WorldCompleteLaunchBindingReceipt recovered = + withGameSession(() -> service.bind(request(evidence))); + + assertThat(recovered.evidence()).isEqualTo(evidence); + assertThat(countBindings(source.canonicalTenantId())).isEqualTo(1L); + verify(client).getComplete(any()); + LostCommitAcknowledgmentTransactionManager retryManager = + new LostCommitAcknowledgmentTransactionManager(transactionManager); + AuthoredWorldLaunchDescriptorClient retryClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + WorldCompleteLaunchBindingReceipt retry = + withGameSession(() -> service(retryClient, retryManager).bind(request(evidence))); + assertThat(retry.operationId()).isEqualTo(recovered.operationId()); + verify(retryClient, never()).getComplete(any()); + } + + @Test + void readsCurrentVersionForExactCommittedBindingAndPreservesOriginalReceipt() + throws SQLException { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt sourceReceipt = acceptSource(source); + CompleteLaunchBindingEvidence evidence = evidence(source, controlRequest(), 71L); + GetRequest bindingRequest = request(evidence); + AuthoredWorldLaunchDescriptorClient descriptorClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(descriptorClient.getComplete(any())).thenReturn(evidence); + AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + UUID firstReadId = UUID.randomUUID(); + UUID retiredReadId = UUID.randomUUID(); + when(versionStateClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request currentRequest = invocation.getArgument(0); + if (currentRequest.readRequestId().equals(firstReadId)) { + return currentVersionState( + currentRequest, + source, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.descriptor().versionStateEpoch()); + } + if (currentRequest.readRequestId().equals(retiredReadId)) { + return currentVersionState( + currentRequest, + source, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + evidence.descriptor().versionStateEpoch() + 1); + } + throw new IllegalArgumentException("Unexpected synthetic current-read request"); + }); + WorldCompleteLaunchBindingService service = + service(descriptorClient, versionStateClient, transactionManager); + + WorldCompleteLaunchBindingReceipt original = + withGameSession(() -> service.bind(bindingRequest)); + Map>> ownerRowsBeforeRead = + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId()); + + AuthoredWorldVersionStateEvidence eligible = + withGameSession(() -> service.readCurrentVersionState(bindingRequest, firstReadId)); + + assertThat(eligible.versionState()) + .isEqualTo(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED); + assertThat(eligible.versionStateEpoch()).isEqualTo(evidence.descriptor().versionStateEpoch()); + assertThat(eligible.request().versionId()).isEqualTo(evidence.descriptor().versionId()); + assertThat( + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId())) + .isEqualTo(ownerRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(bindingRequest, retiredReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("epoch differs"); + assertThat( + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId())) + .isEqualTo(ownerRowsBeforeRead); + + WorldCompleteLaunchBindingReceipt retry = withGameSession(() -> service.bind(bindingRequest)); + assertThat(retry).isEqualTo(original); + assertThat(retry.operationId()).isEqualTo(original.operationId()); + assertThat(retry.sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(retry.evidence()).isEqualTo(evidence); + assertThat( + worldOwnerRows( + source.canonicalTenantId(), + sourceReceipt.operationId(), + sourceReceipt.localTenantKey(), + evidence.descriptor().controlPlaneRequestId())) + .isEqualTo(ownerRowsBeforeRead); + verify(descriptorClient).getComplete(any()); + verify(versionStateClient, times(2)).read(any()); + } + + @Test + void deniesMixedCurrentVersionEvidenceWithoutChangingCommittedBinding() throws SQLException { + AuthoredWorldSourceEvidence boundSource = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt boundSourceReceipt = acceptSource(boundSource); + CompleteLaunchBindingEvidence bindingEvidence = evidence(boundSource, controlRequest(), 73L); + GetRequest bindingRequest = request(bindingEvidence); + AuthoredWorldLaunchDescriptorClient descriptorClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + when(descriptorClient.getComplete(any())).thenReturn(bindingEvidence); + AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + + AuthoredWorldSourceEvidence otherSource = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt otherSourceReceipt = acceptSource(otherSource); + AuthoredWorldSourceEvidence missingBindingSource = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt missingBindingReceipt = acceptSource(missingBindingSource); + String otherControlPlaneRequestId = controlRequest(); + UUID mixedReadId = UUID.randomUUID(); + UUID changedSelectorReadId = UUID.randomUUID(); + UUID changedCanonicalVersionReadId = UUID.randomUUID(); + UUID unavailableReadId = UUID.randomUUID(); + UUID missingBindingReadId = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence mixedEvidence = + currentVersionState( + otherSource, + mixedReadId, + bindingEvidence.descriptor().versionId() + 1, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence changedSelectorEvidence = + currentVersionState( + boundSource, + changedSelectorReadId, + bindingEvidence.descriptor().versionId() + 1, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence expectedCanonicalVersionEvidence = + currentVersionState( + boundSource, + changedCanonicalVersionReadId, + bindingEvidence.descriptor().versionId(), + bindingEvidence.releaseAttestation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence changedCanonicalVersionEvidence = + currentVersionState( + boundSource, + changedCanonicalVersionReadId, + bindingEvidence.descriptor().versionId(), + OTHER_CANONICAL_VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + bindingEvidence.descriptor().versionStateEpoch()); + mixedEvidence.requireValid(); + changedSelectorEvidence.requireValid(); + changedCanonicalVersionEvidence.requireValid(); + when(versionStateClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request currentRequest = invocation.getArgument(0); + if (currentRequest.readRequestId().equals(mixedReadId)) { + return mixedEvidence; + } + if (currentRequest.readRequestId().equals(changedSelectorReadId)) { + return changedSelectorEvidence; + } + if (currentRequest.readRequestId().equals(changedCanonicalVersionReadId)) { + return changedCanonicalVersionEvidence; + } + if (currentRequest.readRequestId().equals(unavailableReadId)) { + throw new IllegalStateException("Synthetic current-version source is unavailable"); + } + throw new IllegalArgumentException("Unexpected synthetic current-read request"); + }); + WorldCompleteLaunchBindingService service = + service(descriptorClient, versionStateClient, transactionManager); + WorldCompleteLaunchBindingReceipt committed = + withGameSession(() -> service.bind(bindingRequest)); + GetRequest missingBindingRequest = + request(evidence(missingBindingSource, controlRequest(), 74L)); + Map>> committedRowsBeforeRead = + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId()); + Map>> otherSourceRowsBeforeRead = + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId); + Map>> missingBindingRowsBeforeRead = + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId()); + assertThat(mixedEvidence.request().sourceOperationId()).isEqualTo(otherSource.operationId()); + assertThat(mixedEvidence.request().versionId()) + .isNotEqualTo(bindingEvidence.descriptor().versionId()); + assertThat(changedSelectorEvidence.sourceEvidence()).isEqualTo(boundSource); + assertThat(changedSelectorEvidence.request().versionId()) + .isNotEqualTo(bindingEvidence.descriptor().versionId()); + assertThat(changedCanonicalVersionEvidence.request()) + .isEqualTo(expectedCanonicalVersionEvidence.request()); + assertThat(changedCanonicalVersionEvidence.sourceEvidence()) + .isEqualTo(expectedCanonicalVersionEvidence.sourceEvidence()); + assertThat(changedCanonicalVersionEvidence.versionState()) + .isEqualTo(expectedCanonicalVersionEvidence.versionState()); + assertThat(changedCanonicalVersionEvidence.versionStateEpoch()) + .isEqualTo(expectedCanonicalVersionEvidence.versionStateEpoch()); + assertThat(changedCanonicalVersionEvidence.canonicalVersionId()) + .isNotEqualTo(bindingEvidence.releaseAttestation().canonicalVersionId()); + + assertThatThrownBy( + () -> + withGameSession(() -> service.readCurrentVersionState(bindingRequest, mixedReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + assertThat( + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId)) + .isEqualTo(otherSourceRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(bindingRequest, changedSelectorReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + bindingRequest, changedCanonicalVersionReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("canonical version UUID differs"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + assertThat( + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId)) + .isEqualTo(otherSourceRowsBeforeRead); + assertThat( + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId())) + .isEqualTo(missingBindingRowsBeforeRead); + assertThat(committed.evidence()).isEqualTo(bindingEvidence); + assertThat(committed.sourceIntakeReceipt()).isEqualTo(boundSourceReceipt); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(bindingRequest, unavailableReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("unavailable or invalid"); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + missingBindingRequest, missingBindingReadId))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("requires a committed launch binding"); + assertThat( + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId())) + .isEqualTo(missingBindingRowsBeforeRead); + assertThat(missingBindingRowsBeforeRead.get("binding")).isEmpty(); + assertThat(committed.operationId()) + .isEqualTo(committedRowsBeforeRead.get("binding").get(0).get("binding_operation_id")); + assertThat( + worldOwnerRows( + otherSource.canonicalTenantId(), + otherSourceReceipt.operationId(), + otherSourceReceipt.localTenantKey(), + otherControlPlaneRequestId)) + .isEqualTo(otherSourceRowsBeforeRead); + assertThat( + worldOwnerRows( + missingBindingSource.canonicalTenantId(), + missingBindingReceipt.operationId(), + missingBindingReceipt.localTenantKey(), + missingBindingRequest.expectedRequest().controlPlaneRequestId())) + .isEqualTo(missingBindingRowsBeforeRead); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + WorldCompleteLaunchBindingReceipt retried = withGameSession(() -> service.bind(bindingRequest)); + assertThat(retried).isEqualTo(committed); + assertThat(retried.evidence()).isEqualTo(bindingEvidence); + assertThat(retried.sourceIntakeReceipt()).isEqualTo(boundSourceReceipt); + assertThat( + worldOwnerRows( + boundSource.canonicalTenantId(), + boundSourceReceipt.operationId(), + boundSourceReceipt.localTenantKey(), + bindingEvidence.descriptor().controlPlaneRequestId())) + .isEqualTo(committedRowsBeforeRead); + verify(descriptorClient).getComplete(any()); + verify(versionStateClient, times(4)).read(any()); + } + + private WorldAuthoredSourceIntakeReceipt acceptSource(AuthoredWorldSourceEvidence source) { + UUID intakeRequestId = UUID.randomUUID(); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + return Objects.requireNonNull( + transaction.execute( + status -> sourceRepository.acceptFresh(NAMESPACE, intakeRequestId, source)), + "World source intake returned no receipt"); + } + + private WorldCompleteLaunchBindingService service( + AuthoredWorldLaunchDescriptorClient client, PlatformTransactionManager manager) { + return new WorldCompleteLaunchBindingService( + client, + new WorldCompleteLaunchBindingRepository(dsl), + sourceRepository, + manager, + NAMESPACE); + } + + private WorldCompleteLaunchBindingService service( + AuthoredWorldLaunchDescriptorClient descriptorClient, + AuthoredWorldVersionStateClient versionStateClient, + PlatformTransactionManager manager) { + return new WorldCompleteLaunchBindingService( + descriptorClient, + new WorldCompleteLaunchBindingRepository(dsl), + sourceRepository, + manager, + NAMESPACE, + versionStateClient); + } + + private Map>> worldOwnerRows( + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + long localTenantKey, + String controlPlaneRequestId) + throws SQLException { + try (Connection connection = dataSource.getConnection()) { + Map>> rows = new LinkedHashMap<>(); + rows.put( + "association", + readOwnerRows( + connection, + "SELECT * FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + canonicalTenantId)); + rows.put( + "reservation", + readOwnerRows( + connection, + "SELECT * FROM world_authored_source_tenant_key_reservation WHERE tenant_key = ?", + localTenantKey)); + rows.put( + "sourceIntake", + readOwnerRows( + connection, + "SELECT * FROM world_authored_source_intake WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND operation_id = ?", + NAMESPACE, + canonicalTenantId, + sourceIntakeOperationId)); + rows.put( + "binding", + readOwnerRows( + connection, + "SELECT * FROM world_complete_launch_binding WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND control_plane_request_id = ?", + NAMESPACE, + canonicalTenantId, + controlPlaneRequestId)); + return Collections.unmodifiableMap(rows); + } + } + + private static List> readOwnerRows( + Connection connection, String query, Object... parameters) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(query)) { + for (int index = 0; index < parameters.length; index++) { + statement.setObject(index + 1, parameters[index]); + } + try (ResultSet resultSet = statement.executeQuery()) { + ResultSetMetaData metadata = resultSet.getMetaData(); + List> rows = new ArrayList<>(); + while (resultSet.next()) { + Map row = new LinkedHashMap<>(); + for (int index = 1; index <= metadata.getColumnCount(); index++) { + row.put(metadata.getColumnLabel(index), resultSet.getObject(index)); + } + rows.add(Collections.unmodifiableMap(row)); + } + return List.copyOf(rows); + } + } + } + + private long countBindings(UUID tenant) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_complete_launch_binding WHERE target_namespace = ? " + + "AND canonical_tenant_id = ?", + NAMESPACE, + tenant), + "complete launch binding count query returned no row") + .get(0, Long.class); + } + + private static AuthoredWorldSourceEvidence source(UUID tenant, String worldSlug) { + UUID registrationRequest = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String displayName = "Source " + tenant.toString().substring(0, 8); + long sourceGameRowId = Math.max(1L, tenant.getLeastSignificantBits() & Long.MAX_VALUE); + String sourceGameTenantKey = "source-" + tenant.toString().replace("-", "").substring(0, 24); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequest, tenant, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static CompleteLaunchBindingEvidence evidence( + AuthoredWorldSourceEvidence source, String controlPlaneRequestId, long gameTemplateId) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "launch-descriptor-" + gameTemplateId, + 42L, + false, + null, + "{}", + "generation-config-42", + 17L, + 51L, + "release-bundle-51", + false, + null); + String commit = "commit-launch-binding"; + List participants = + List.of( + participant("WORLD_MANAGEMENT", 3, "a", false, commit), + participant("ENTITY_MANAGEMENT", 2, "b", false, commit), + participant("GAME_LOGIC", 1, "c", true, commit), + participant("AUTOMATION_SCRIPTING", 5, "d", false, commit), + participant("GAME_DESIGN_CONTROL_PLANE", 1, "e", false, commit)); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + VERSION, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:owner:launch-binding", + commit, + participants, + digest('f'), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldVersionStateEvidence.Request request, + AuthoredWorldSourceEvidence source, + VersionLifecycleState versionState, + long versionStateEpoch) { + return currentVersionState(request, source, VERSION, versionState, versionStateEpoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldVersionStateEvidence.Request request, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, versionState, versionStateEpoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID readRequestId, + long versionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + return currentVersionState( + source, readRequestId, versionId, VERSION, versionState, versionStateEpoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID readRequestId, + long versionId, + UUID canonicalVersionId, + VersionLifecycleState versionState, + long versionStateEpoch) { + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + source.targetNamespace(), + readRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + versionId); + return currentVersionState( + request, source, canonicalVersionId, versionState, versionStateEpoch); + } + + private static AuthoredWorldReleaseAttestationEvidence.Participant participant( + String owner, int schema, String contentHex, boolean hasAbilityDigest, String commit) { + return new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "42", + false, + null, + commit, + contentHex.repeat(64), + schema, + hasAbilityDigest, + hasAbilityDigest ? digest('c') : null); + } + + private static GetRequest request(CompleteLaunchBindingEvidence evidence) { + UUID requestId; + do { + requestId = UUID.randomUUID(); + } while (requestId.equals(evidence.descriptor().authoredWorldSourceOperationId())); + return new GetRequest( + requestId, evidence.descriptor().request(), evidence.descriptor().resultDigest()); + } + + private static String randomWorld() { + return "world-" + UUID.randomUUID().toString().replace("-", "").substring(0, 18); + } + + private static String controlRequest() { + return "world-control-" + UUID.randomUUID(); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static GrpcPeerIdentity peer() { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service", + NAMESPACE, + "game-session-service"); + } + + private static T withGameSession(java.util.function.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 void awaitFetchBarrier(CountDownLatch latch) { + latch.countDown(); + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent launch-binding fetch barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent launch-binding fetch was interrupted", exception); + } + } + + private static Object attempt(WorldCompleteLaunchBindingService service, GetRequest request) { + return withGameSession( + () -> { + try { + return service.bind(request); + } catch (RegistrationConflictException exception) { + return exception; + } + }); + } + + 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 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 final class LostCommitAcknowledgmentTransactionManager + implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private boolean firstCommit = true; + + private LostCommitAcknowledgmentTransactionManager(PlatformTransactionManager delegate) { + this.delegate = delegate; + } + + @Override + public TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + return delegate.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + delegate.commit(status); + if (firstCommit) { + firstCommit = false; + throw new IllegalStateException("simulated lost owner commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + if (!status.isCompleted()) { + delegate.rollback(status); + } + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java new file mode 100644 index 0000000000..38117d1a40 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java @@ -0,0 +1,975 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.Objects; +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 java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +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 net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +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.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.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 WorldDesignPublicationFenceIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final String FULL_REQUEST_DIGEST = "f".repeat(64); + private static final long GAME_DESIGN_VERSION_A = 9_000_000_042L; + private static final long GAME_DESIGN_VERSION_B = 9_000_000_043L; + private static final Checkpoint SYNTHETIC_CHECKPOINT = + new Checkpoint("synthetic-commit-42", "c".repeat(64), 3); + + @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 intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository repository; + @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 rollbackAndCommittedExactReadbackRetainOneImmutableAttempt() { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-7", GAME_DESIGN_VERSION_A, 9L); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + repository.lockOpen(request.ownerBinding()); + throw new ForcedRollbackException(); + })) + .isInstanceOf(ForcedRollbackException.class); + assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isZero(); + + FrozenAttempt frozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT)); + assertThat(frozen).isNotNull(); + assertThat(repository.readAttempt(request)).contains(frozen); + assertThat(frozen.checkpoint().digestSchemaVersion()).isEqualTo(3); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo("FROZEN"); + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, GAME_DESIGN_VERSION_A); + assertThat(identity.localVersionKey()).isNotEqualTo(GAME_DESIGN_VERSION_A); + var storedBinding = + dsl.fetchOne( + "SELECT owner_binding_schema_version, version_id, canonical_version_id, " + + "version_identity_operation_id, game_design_version_id, intake_request_digest " + + "FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + frozen.publicationFence()); + assertThat(storedBinding).isNotNull(); + assertThat(storedBinding.get("owner_binding_schema_version", Short.class)).isEqualTo((short) 1); + assertThat(storedBinding.get("version_id", Long.class)).isEqualTo(identity.localVersionKey()); + assertThat(storedBinding.get("canonical_version_id", UUID.class)) + .isEqualTo(identity.canonicalVersionId()); + assertThat(storedBinding.get("version_identity_operation_id", UUID.class)) + .isEqualTo(identity.operationId()); + assertThat(storedBinding.get("game_design_version_id", Long.class)) + .isEqualTo(GAME_DESIGN_VERSION_A); + assertThat(storedBinding.get("intake_request_digest", String.class)) + .isEqualTo(receipt.requestDigest()); + + AtomicBoolean retryRecapturedCheckpoint = new AtomicBoolean(); + FrozenAttempt retry = + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + retryRecapturedCheckpoint.set(true); + return new Checkpoint("synthetic-new-commit", "d".repeat(64), 2); + })); + assertThat(retry).isEqualTo(frozen); + assertThat(retryRecapturedCheckpoint).isFalse(); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + + assertDatabaseTriggerRejects( + () -> + dsl.execute( + "UPDATE world_design_publication_fence_attempt SET content_digest = ? " + + "WHERE publication_fence = ?", + "d".repeat(64), + frozen.publicationFence()), + "World publication-fence attempt history is immutable"); + assertDatabaseTriggerRejects( + () -> dsl.execute("TRUNCATE world_design_publication_fence_attempt CASCADE"), + "World publication-fence attempt history is immutable"); + assertDatabaseTriggerRejects( + () -> dsl.execute("TRUNCATE world_design_publication_fence_owner"), + "World publication-fence attempt history is immutable"); + assertDatabaseTriggerRejects( + () -> + dsl.execute( + "UPDATE world_design_publication_fence_owner " + + "SET current_publication_fence = NULL WHERE canonical_tenant_id = ? " + + "AND version_id = ?", + receipt.canonicalTenantId(), + localVersionKey(identity(receipt, GAME_DESIGN_VERSION_A))), + "World publication-fence owner binding or phase transition is immutable"); + + assertThat(repository.readAttempt(request)).contains(frozen); + assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo("FROZEN"); + } + + @Test + void schemaZeroAttemptAtResolvedLocalKeyCannotBePromotedByNumericCoincidence() { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "legacy-world"); + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, GAME_DESIGN_VERSION_A); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "legacy-request", GAME_DESIGN_VERSION_A, 3L); + assertThat(identity.localVersionKey()).isNotEqualTo(GAME_DESIGN_VERSION_A); + + dsl.execute( + "INSERT INTO world_design_publication_fence_attempt (" + + "publication_fence, target_namespace, canonical_tenant_id, local_tenant_key, " + + "version_id, intake_operation_id, intake_request_id, source_operation_id, " + + "source_evidence_digest, intake_receipt_digest, publication_request_id, " + + "request_digest, version_state_epoch, publish_workflow_id, applied_commit_id, " + + "content_digest, digest_schema_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + UUID.randomUUID(), + NAMESPACE, + receipt.canonicalTenantId(), + receipt.localTenantKey(), + identity.localVersionKey(), + receipt.operationId(), + receipt.intakeRequestId(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + "legacy-commit", + "e".repeat(64), + 2); + + assertThatThrownBy(() -> repository.readAttempt(request)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("schema-0"); + assertThatThrownBy( + () -> + ownerTransaction() + .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("schema-0"); + assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isZero(); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + } + + @Test + void sameGameDesignSelectorUsesDistinctWorldLocalVersionRowsAcrossIntakes() { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + WorldAuthoredSourceIntakeReceipt first = + intake(canonicalTenantId, "violet-wilds", tenantSlug, 6_001L); + WorldAuthoredSourceIntakeReceipt second = + intake(canonicalTenantId, "brighter-coast", tenantSlug, 6_001L); + + ownerTransaction() + .execute( + status -> { + repository.lockOpen(ownerBinding(first, GAME_DESIGN_VERSION_A)); + return null; + }); + ownerTransaction() + .execute( + status -> { + repository.lockOpen(ownerBinding(second, GAME_DESIGN_VERSION_A)); + return null; + }); + + assertThat(identity(first, GAME_DESIGN_VERSION_A).localVersionKey()) + .isNotEqualTo(identity(second, GAME_DESIGN_VERSION_A).localVersionKey()); + assertThat(ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(2L); + assertThat(ownerPhase(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo("OPEN"); + } + + @Test + void identicalRequestAcrossVersionsUsesOnlyEachResolvedWorldLocalKey() { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + WorldAuthoredSourceIntakeReceipt first = + intake(canonicalTenantId, "violet-wilds", tenantSlug, 8_101L); + WorldAuthoredVersionIdentityReceipt firstIdentity = identity(first, GAME_DESIGN_VERSION_A); + long secondGameDesignVersionId = firstIdentity.localVersionKey(); + WorldAuthoredSourceIntakeReceipt second = + intake(canonicalTenantId, "brighter-coast", tenantSlug, 8_101L); + WorldAuthoredVersionIdentityReceipt secondIdentity = + identity(second, secondGameDesignVersionId); + assertThat(secondGameDesignVersionId).isEqualTo(firstIdentity.localVersionKey()); + assertThat(secondIdentity.localVersionKey()).isNotEqualTo(secondGameDesignVersionId); + assertThatThrownBy(() -> intake(canonicalTenantId, "contradictory-world", tenantSlug, 8_103L)) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class) + .hasMessageContaining("Canonical tenant source or stable tenant selector conflicts"); + + WorldDesignPublicationFenceEvidence firstRequest = + evidence(first, "shared-publication-request", GAME_DESIGN_VERSION_A, 5L); + WorldDesignPublicationFenceEvidence secondRequest = + evidence(second, "shared-publication-request", secondGameDesignVersionId, 5L); + FrozenAttempt firstFrozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(firstRequest, () -> SYNTHETIC_CHECKPOINT)); + FrozenAttempt secondFrozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(secondRequest, () -> SYNTHETIC_CHECKPOINT)); + + assertThat(secondFrozen.publicationFence()).isNotEqualTo(firstFrozen.publicationFence()); + long firstOwnerCount = ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A); + long secondOwnerCount = ownerCount(canonicalTenantId, secondGameDesignVersionId); + long firstAttemptCount = attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A); + long secondAttemptCount = attemptCount(canonicalTenantId, secondGameDesignVersionId); + assertThat(repository.readAttempt(firstRequest)).contains(firstFrozen); + assertThat(repository.readAttempt(secondRequest)).contains(secondFrozen); + assertThat(ownerCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(firstOwnerCount); + assertThat(ownerCount(canonicalTenantId, secondGameDesignVersionId)) + .isEqualTo(secondOwnerCount); + assertThat(attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(firstAttemptCount); + assertThat(attemptCount(canonicalTenantId, secondGameDesignVersionId)) + .isEqualTo(secondAttemptCount); + } + + @Test + void concurrentExactFreezeRetryReturnsTheSameFenceAndCheckpoint() throws Exception { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-concurrent", GAME_DESIGN_VERSION_A, 9L); + CountDownLatch checkpointCaptured = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + AtomicBoolean secondCapturedCheckpoint = new AtomicBoolean(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + checkpointCaptured.countDown(); + await(releaseFirst); + return SYNTHETIC_CHECKPOINT; + }))); + await(checkpointCaptured); + Future second = + executor.submit( + () -> { + secondStarted.countDown(); + return ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + secondCapturedCheckpoint.set(true); + return new Checkpoint("synthetic-second", "d".repeat(64), 3); + })); + }); + await(secondStarted); + awaitOwnerRowLockWait(); + releaseFirst.countDown(); + + FrozenAttempt firstResult = first.get(10, TimeUnit.SECONDS); + FrozenAttempt secondResult = second.get(10, TimeUnit.SECONDS); + assertThat(secondResult).isEqualTo(firstResult); + assertThat(secondCapturedCheckpoint).isFalse(); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + } + } + + @Test + void writerHoldingTheOpenLockCommitsBeforeFreezeCapturesItsCheckpoint() throws Exception { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-writer-first", GAME_DESIGN_VERSION_A, 9L); + CountDownLatch writerLocked = new CountDownLatch(1); + CountDownLatch releaseWriter = new CountDownLatch(1); + CountDownLatch freezeStarted = new CountDownLatch(1); + AtomicBoolean checkpointCaptured = new AtomicBoolean(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future writer = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + repository.lockOpen(request.ownerBinding()); + writerLocked.countDown(); + await(releaseWriter); + return null; + })); + await(writerLocked); + Future freeze = + executor.submit( + () -> { + freezeStarted.countDown(); + return ownerTransaction() + .execute( + status -> + repository.claimFreeze( + request, + () -> { + checkpointCaptured.set(true); + return SYNTHETIC_CHECKPOINT; + })); + }); + await(freezeStarted); + awaitOwnerRowLockWait(); + assertThat(checkpointCaptured).isFalse(); + releaseWriter.countDown(); + writer.get(10, TimeUnit.SECONDS); + + FrozenAttempt frozen = freeze.get(10, TimeUnit.SECONDS); + assertThat(checkpointCaptured).isTrue(); + assertThat(frozen.checkpoint()).isEqualTo(SYNTHETIC_CHECKPOINT); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)) + .isEqualTo("FROZEN"); + } finally { + releaseWriter.countDown(); + executor.shutdownNow(); + } + } + + @Test + void freezeHoldingTheLockMakesAWaitingOrdinaryWriterFailClosed() throws Exception { + WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "violet-wilds"); + WorldDesignPublicationFenceEvidence request = + evidence(receipt, "request-freeze-first", GAME_DESIGN_VERSION_A, 9L); + CountDownLatch freezeLocked = new CountDownLatch(1); + CountDownLatch releaseFreeze = new CountDownLatch(1); + CountDownLatch writerStarted = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future freeze = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + FrozenAttempt result = + repository.claimFreeze( + request, + () -> { + freezeLocked.countDown(); + return SYNTHETIC_CHECKPOINT; + }); + await(releaseFreeze); + return result; + })); + await(freezeLocked); + Future writer = + executor.submit( + () -> { + writerStarted.countDown(); + try { + ownerTransaction() + .execute( + status -> { + repository.lockOpen(request.ownerBinding()); + return null; + }); + return false; + } catch (WorldDesignPublicationFenceRepository.ConflictException expected) { + return true; + } + }); + await(writerStarted); + awaitOwnerRowLockWait(); + releaseFreeze.countDown(); + + freeze.get(10, TimeUnit.SECONDS); + assertThat(writer.get(10, TimeUnit.SECONDS)).isTrue(); + assertThat(ownerPhase(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)) + .isEqualTo("FROZEN"); + assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); + } finally { + releaseFreeze.countDown(); + executor.shutdownNow(); + } + } + + @Test + void changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate() { + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + canonicalTenantId.toString().replace("-", ""); + WorldAuthoredSourceIntakeReceipt first = + intake(canonicalTenantId, "violet-wilds", tenantSlug, 6_002L); + WorldAuthoredSourceIntakeReceipt second = + intake(canonicalTenantId, "brighter-coast", tenantSlug, 6_002L); + WorldDesignPublicationFenceEvidence request = + evidence(first, "request-7", GAME_DESIGN_VERSION_A, 9L); + FrozenAttempt frozen = + ownerTransaction() + .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT)); + + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + first.canonicalTenantId(), + identity(first, GAME_DESIGN_VERSION_A).canonicalVersionId(), + identity(first, GAME_DESIGN_VERSION_A).operationId(), + GAME_DESIGN_VERSION_A, + first.intakeRequestId(), + first.operationId(), + first.requestDigest(), + first.sourceOperationId(), + second.sourceEvidenceDigest(), + first.receiptDigest(), + "request-7", + FULL_REQUEST_DIGEST, + 9L, + request.publishWorkflowId()), + () -> SYNTHETIC_CHECKPOINT))); + + UUID changedTenantId = UUID.randomUUID(); + WorldDesignPublicationFenceEvidence changedAssociation = + evidence( + changedTenantId, + first, + "request-7", + identity(first, GAME_DESIGN_VERSION_A), + GAME_DESIGN_VERSION_A, + 9L, + PublicationDigestRequestBinding.full( + changedTenantId.toString(), Long.toString(GAME_DESIGN_VERSION_A), "request-7")); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze(changedAssociation, () -> SYNTHETIC_CHECKPOINT))); + assertThat(ownerCount(changedTenantId, GAME_DESIGN_VERSION_A)).isZero(); + + WorldAuthoredVersionIdentityReceipt identity = identity(first, GAME_DESIGN_VERSION_A); + WorldDesignPublicationFenceEvidence changedCanonicalVersion = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + canonicalTenantId, + UUID.randomUUID(), + identity.operationId(), + GAME_DESIGN_VERSION_A, + first.intakeRequestId(), + first.operationId(), + first.requestDigest(), + first.sourceOperationId(), + first.sourceEvidenceDigest(), + first.receiptDigest(), + "request-7", + FULL_REQUEST_DIGEST, + 9L, + request.publishWorkflowId()); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + changedCanonicalVersion, () -> SYNTHETIC_CHECKPOINT))); + + String changedSelectorWorkflow = + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(GAME_DESIGN_VERSION_B), "request-7") + .derivedWorkflowIdentity(); + WorldDesignPublicationFenceEvidence changedGameDesignSelector = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + canonicalTenantId, + identity.canonicalVersionId(), + identity.operationId(), + GAME_DESIGN_VERSION_B, + first.intakeRequestId(), + first.operationId(), + first.requestDigest(), + first.sourceOperationId(), + first.sourceEvidenceDigest(), + first.receiptDigest(), + "request-7", + FULL_REQUEST_DIGEST, + 9L, + changedSelectorWorkflow); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> + repository.claimFreeze( + changedGameDesignSelector, () -> SYNTHETIC_CHECKPOINT))); + + WorldDesignPublicationFenceEvidence changedRequest = + evidence(first, "request-8", GAME_DESIGN_VERSION_A, 9L); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(changedRequest, () -> SYNTHETIC_CHECKPOINT))); + + WorldDesignPublicationFenceEvidence changedEpoch = + evidence(first, "request-7", GAME_DESIGN_VERSION_A, 10L); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(changedEpoch, () -> SYNTHETIC_CHECKPOINT))); + + WorldDesignPublicationFenceEvidence changedDigest = + evidence( + first, + "request-7", + GAME_DESIGN_VERSION_A, + 9L, + "0".repeat(64), + request.publishWorkflowId()); + assertNoStateChange( + canonicalTenantId, + GAME_DESIGN_VERSION_A, + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(changedDigest, () -> SYNTHETIC_CHECKPOINT))); + assertThatThrownBy(() -> repository.readAttempt(changedDigest)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + + assertThat(repository.readAttempt(request)).contains(frozen); + assertThatThrownBy( + () -> + evidence( + first, + "request-7", + GAME_DESIGN_VERSION_A, + 9L, + "F".repeat(64), + request.publishWorkflowId())) + .isInstanceOf(IllegalArgumentException.class); + + WorldAuthoredSourceIntakeReceipt missingCheckpointReceipt = + intake(UUID.randomUUID(), "uncheckpointed-world"); + WorldDesignPublicationFenceEvidence missingCheckpointRequest = + evidence(missingCheckpointReceipt, "request-missing-checkpoint", GAME_DESIGN_VERSION_B, 1L); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> repository.claimFreeze(missingCheckpointRequest, () -> null))) + .isInstanceOf(NullPointerException.class); + assertThat(ownerCount(missingCheckpointReceipt.canonicalTenantId(), GAME_DESIGN_VERSION_B)) + .isZero(); + assertThat(ownerPhase(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo("FROZEN"); + assertThat(attemptCount(canonicalTenantId, GAME_DESIGN_VERSION_A)).isEqualTo(1L); + } + + private void assertNoStateChange( + UUID canonicalTenantId, long gameDesignVersionId, Runnable action) { + long ownersBefore = ownerCount(canonicalTenantId, gameDesignVersionId); + long attemptsBefore = attemptCount(canonicalTenantId, gameDesignVersionId); + String phaseBefore = ownerPhase(canonicalTenantId, gameDesignVersionId); + assertThatThrownBy(action::run) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThat(ownerCount(canonicalTenantId, gameDesignVersionId)).isEqualTo(ownersBefore); + assertThat(attemptCount(canonicalTenantId, gameDesignVersionId)).isEqualTo(attemptsBefore); + assertThat(ownerPhase(canonicalTenantId, gameDesignVersionId)).isEqualTo(phaseBefore); + } + + private WorldAuthoredSourceIntakeReceipt intake(UUID tenantId, String worldSlug) { + return intake( + tenantId, + worldSlug, + "tenant-" + tenantId.toString().replace("-", ""), + sourceRowId(tenantId)); + } + + private WorldAuthoredSourceIntakeReceipt intake( + UUID tenantId, String worldSlug, String tenantSlug, long sourceRowId) { + UUID requestId = UUID.randomUUID(); + AuthoredWorldSourceEvidence source = source(tenantId, tenantSlug, worldSlug, sourceRowId); + return ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, requestId, source)); + } + + private AuthoredWorldSourceEvidence source( + UUID tenantId, String tenantSlug, String worldSlug, long sourceRowId) { + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String displayName = "Synthetic authored world"; + String sourceTenantKey = "gd-row-" + sourceRowId; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceRowId, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private WorldDesignPublicationFenceEvidence evidence( + WorldAuthoredSourceIntakeReceipt receipt, + String publishRequestId, + long gameDesignVersionId, + long versionStateEpoch) { + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, gameDesignVersionId); + return evidence( + receipt.canonicalTenantId(), + receipt, + publishRequestId, + identity, + gameDesignVersionId, + versionStateEpoch, + PublicationDigestRequestBinding.full( + receipt.canonicalTenantId().toString(), + Long.toString(gameDesignVersionId), + publishRequestId)); + } + + private OwnerBinding ownerBinding( + WorldAuthoredSourceIntakeReceipt receipt, long gameDesignVersionId) { + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, gameDesignVersionId); + return new OwnerBinding( + NAMESPACE, + receipt.canonicalTenantId(), + identity.canonicalVersionId(), + identity.operationId(), + gameDesignVersionId, + receipt.intakeRequestId(), + receipt.operationId(), + receipt.requestDigest(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest()); + } + + private static long localVersionKey(WorldAuthoredVersionIdentityReceipt identity) { + return identity.localVersionKey(); + } + + private WorldDesignPublicationFenceEvidence evidence( + UUID tenantId, + WorldAuthoredSourceIntakeReceipt receipt, + String publishRequestId, + WorldAuthoredVersionIdentityReceipt identity, + long gameDesignVersionId, + long versionStateEpoch, + PublicationDigestRequestBinding binding) { + return new WorldDesignPublicationFenceEvidence( + NAMESPACE, + tenantId, + identity.canonicalVersionId(), + identity.operationId(), + gameDesignVersionId, + receipt.intakeRequestId(), + receipt.operationId(), + receipt.requestDigest(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), + publishRequestId, + FULL_REQUEST_DIGEST, + versionStateEpoch, + binding.derivedWorkflowIdentity()); + } + + private WorldDesignPublicationFenceEvidence evidence( + WorldAuthoredSourceIntakeReceipt receipt, + String publishRequestId, + long gameDesignVersionId, + long versionStateEpoch, + String requestDigest, + String workflowId) { + WorldAuthoredVersionIdentityReceipt identity = identity(receipt, gameDesignVersionId); + return new WorldDesignPublicationFenceEvidence( + NAMESPACE, + receipt.canonicalTenantId(), + identity.canonicalVersionId(), + identity.operationId(), + gameDesignVersionId, + receipt.intakeRequestId(), + receipt.operationId(), + receipt.requestDigest(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), + publishRequestId, + requestDigest, + versionStateEpoch, + workflowId); + } + + private WorldAuthoredVersionIdentityReceipt identity( + WorldAuthoredSourceIntakeReceipt receipt, long gameDesignVersionId) { + UUID canonicalVersionId = stableId("canonical-version", receipt, gameDesignVersionId); + UUID readRequestId = stableId("version-state-read", receipt, gameDesignVersionId); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + readRequestId, + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + gameDesignVersionId); + AuthoredWorldVersionStateEvidence stateEvidence = + AuthoredWorldVersionStateEvidence.create( + stateRequest, + receipt.source(), + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + return ownerTransaction() + .execute( + status -> + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh(receipt, stateEvidence)); + } + + private static UUID stableId( + String domain, WorldAuthoredSourceIntakeReceipt receipt, long gameDesignVersionId) { + return UUID.nameUUIDFromBytes( + (domain + ":" + receipt.operationId() + ":" + Long.toString(gameDesignVersionId)) + .getBytes(StandardCharsets.UTF_8)); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private long ownerCount(UUID tenantId, long gameDesignVersionId) { + return count( + "SELECT COUNT(*) FROM world_design_publication_fence_owner fence_owner " + + "JOIN world_authored_version_identity version_identity " + + "ON version_identity.target_namespace = fence_owner.target_namespace " + + "AND version_identity.canonical_tenant_id = fence_owner.canonical_tenant_id " + + "AND version_identity.local_version_key = fence_owner.version_id " + + "WHERE fence_owner.canonical_tenant_id = ? " + + "AND version_identity.game_design_version_id = ?", + tenantId, + gameDesignVersionId); + } + + private long attemptCount(UUID tenantId, long gameDesignVersionId) { + return count( + "SELECT COUNT(*) FROM world_design_publication_fence_attempt fence_attempt " + + "JOIN world_authored_version_identity version_identity " + + "ON version_identity.target_namespace = fence_attempt.target_namespace " + + "AND version_identity.canonical_tenant_id = fence_attempt.canonical_tenant_id " + + "AND version_identity.local_version_key = fence_attempt.version_id " + + "WHERE fence_attempt.canonical_tenant_id = ? " + + "AND version_identity.game_design_version_id = ?", + tenantId, + gameDesignVersionId); + } + + private String ownerPhase(UUID tenantId, long gameDesignVersionId) { + var row = + dsl.fetchOne( + "SELECT CASE WHEN COUNT(*) = 0 THEN NULL " + + "WHEN BOOL_AND(fence_owner.owner_freeze_phase = 'OPEN') THEN 'OPEN' " + + "WHEN BOOL_AND(fence_owner.owner_freeze_phase = 'FROZEN') THEN 'FROZEN' " + + "ELSE 'MIXED' END " + + "FROM world_design_publication_fence_owner fence_owner " + + "JOIN world_authored_version_identity version_identity " + + "ON version_identity.target_namespace = fence_owner.target_namespace " + + "AND version_identity.canonical_tenant_id = fence_owner.canonical_tenant_id " + + "AND version_identity.local_version_key = fence_owner.version_id " + + "WHERE fence_owner.canonical_tenant_id = ? " + + "AND version_identity.game_design_version_id = ?", + tenantId, + gameDesignVersionId); + if (row == null) { + throw new IllegalStateException("World publication-fence owner phase query returned no row"); + } + return row.get(0, String.class); + } + + private long count(String sql, UUID tenantId, long gameDesignVersionId) { + return Objects.requireNonNull(dsl.fetchOne(sql, tenantId, gameDesignVersionId)) + .get(0, Long.class); + } + + private void awaitOwnerRowLockWait() { + long deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadlineNanos) { + var waiterRow = + dsl.fetchOne( + "SELECT COUNT(*) FROM pg_stat_activity WHERE datname = current_database() " + + "AND wait_event_type = 'Lock' AND lower(query) " + + "LIKE '%world_design_publication_fence_owner%'"); + if (waiterRow == null) { + throw new IllegalStateException("PostgreSQL owner-row waiter query returned no row"); + } + Long waiters = waiterRow.get(0, Long.class); + if (waiters != null && waiters > 0L) { + return; + } + pauseBriefly(); + } + throw new IllegalStateException("No PostgreSQL waiter was observed on the World owner row"); + } + + private void assertDatabaseTriggerRejects(Runnable action, String expectedTriggerMessage) { + RuntimeException failure = null; + try { + action.run(); + } catch (RuntimeException exception) { + failure = exception; + } + assertThat(failure).isInstanceOf(DataAccessException.class); + + SQLException sqlException = null; + Throwable cause = failure; + while (cause != null) { + if (cause instanceof SQLException) { + sqlException = (SQLException) cause; + } + cause = cause.getCause(); + } + assertThat((Throwable) sqlException).isNotNull(); + assertThat(sqlException.getSQLState()).isEqualTo("55000"); + assertThat(sqlException.getMessage()).contains(expectedTriggerMessage); + } + + private long sourceRowId(UUID tenantId) { + long positive = tenantId.getLeastSignificantBits() & Long.MAX_VALUE; + return positive == 0L ? 1L : positive; + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for the publication-fence test gate"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Publication-fence test was interrupted", exception); + } + } + + private static void pauseBriefly() { + try { + TimeUnit.MILLISECONDS.sleep(25); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Publication-fence test wait was interrupted", exception); + } + } + + private static final class ForcedRollbackException extends RuntimeException {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java new file mode 100644 index 0000000000..9b4327a641 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java @@ -0,0 +1,1230 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.sql.DriverManager; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +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.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +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; +import tools.jackson.databind.ObjectMapper; + +/** + * Actual V30 rows and V31/V32 capture, with synthetic source/permission and computed schema-3 V25 + * content checkpoints. Selected commit identities remain synthetic complete-application evidence. + * Fixture-only trigger bypasses model terminal/corrupt storage unavailable through the current + * owner API; origin triggers are restored before every tested capture/read boundary. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldCanonicalFrozenTopologyPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final long GAME_DESIGN_VERSION = 9_000_000_000_000_001L; + + @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 DSLContext dsl; + @Autowired private PlatformTransactionManager manager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository fence; + @Autowired private WorldAuthoredGraphSnapshotRepository snapshots; + @Autowired private ObjectMapper mapper; + + @Autowired + private net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository + spawnRepository; + + @Autowired + private net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService + digestService; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void capturesActualSixFamilyGraphAndOriginalFullInputWithExactRetry() { + Fixture f = fixture(); + var p = plan(f); + var stored = component().store(p); + Request request = freeze(p); + var capture = frozen().capture(request); + assertThat(capture.status()).isEqualTo("CAPTURED_UNVERIFIED"); + assertThat(capture.request().freeze().digestSchemaVersion()).isEqualTo(3); + assertThat(capture.graphBytes()).containsExactly(stored.graphBytes()); + assertThat(capture.storageResultBytes()).containsExactly(stored.resultBytes()); + assertThat(capture.request().plan().binding().canonicalBytes()) + .containsExactly(p.binding().canonicalBytes()); + assertThat(capture.sourceIdentity()).isEqualTo(f.version()); + assertThat(capture.graph().rows()).hasSize(7); + assertThat(capture.graph().family(Family.ROOM)).hasSize(2); + for (Family family : Family.values()) assertThat(capture.graph().family(family)).isNotEmpty(); + var region = capture.graph().family(Family.REGION).getFirst(); + var spawn = capture.graph().family(Family.WORLD_ENTITY_SPAWN_BINDING).getFirst(); + assertThat(region.content().getRegion().getSpacingMultiplier()).isEqualTo(1.0); + assertThat(spawn.content().getWorldEntitySpawnBinding().getSpawnCount()).isEqualTo(1); + assertThat(spawn.entityReference()).isEqualTo(p.graph().nodes().getFirst().entityReference()); + assertThat( + capture.graph().family(Family.ROOM_EXIT).getFirst().content().getRoomExit().getCost()) + .isEqualTo(1); + assertThat(new String(capture.resultBytes(), StandardCharsets.UTF_8)) + .contains( + "ACCOUNT_AUTHORIZATION", "COMPLETE_PARTICIPANT_COMMIT", "PUBLICATION_CHECKPOINT_DIGEST") + .doesNotContain("\"APPLIED\"", "permissionFenceReleased", "\"PREPARING\""); + byte[] exposed = capture.graphBytes(); + exposed[0] = 0; + assertThat(capture.graphBytes()).containsExactly(stored.graphBytes()); + assertThat(frozen().capture(request).resultBytes()).containsExactly(capture.resultBytes()); + assertThat(countCaptures(request)).isEqualTo(1); + assertOrigin(); + } + + @Test + void canonicalSpawnSqlMappingIsLosslessAndProducesSchema3DigestWithoutWriteBypass() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + var spawns = + spawnRepository.findByTenantIdAndVersionIdOrderByIdAsc( + f.intake().localTenantKey(), f.version().localVersionKey()); + assertThat(spawns).hasSize(1); + var spawn = spawns.getFirst(); + var row = dsl.fetchOne("SELECT * FROM world_entity_spawn_binding WHERE id=?", spawn.getId()); + assertThat(spawn.getEntityTemplateId()).isNull(); + assertThat(spawn.getEntityCanonicalTenantId()) + .isEqualTo(row.get("entity_canonical_tenant_id", UUID.class)); + assertThat(spawn.getEntityCanonicalVersionId()) + .isEqualTo(row.get("entity_canonical_version_id", UUID.class)); + assertThat(spawn.getEntityCanonicalTemplateId()) + .isEqualTo(row.get("entity_canonical_template_id", UUID.class)); + var digest = + digestService.getDraftDesignDigest( + Long.toString(spawn.getTenantId()), Long.toString(spawn.getVersionId())); + assertThat(digest.digestSchemaVersion()).isEqualTo(3); + assertThat(digest.contentDigest()).matches("[0-9a-f]{64}"); + assertThat(spawnRepository.findById(spawn.getId()).orElseThrow()).isEqualTo(spawn); + assertThatThrownBy(() -> spawnRepository.save(spawn)).isInstanceOf(RuntimeException.class); + assertThat(spawnRepository.findById(spawn.getId()).orElseThrow()).isEqualTo(spawn); + assertOrigin(); + } + + @Test + void freshSchema2CaptureIsDeniedByApplicationAndDatabase() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p, 2); + assertThat(frozen().readCommitted(request)).isEmpty(); + assertThatThrownBy(() -> frozen().capture(request)) + .hasMessageContaining("requires digest schema 3"); + assertThat(countCaptures(request)).isZero(); + var templatePlan = plan(fixture()); + component().store(templatePlan); + Request template = freeze(templatePlan); + // Supply a complete otherwise-valid insertion from an existing schema-3 journal. + frozen().capture(template); + for (int denied : new int[] {2, 4}) { + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO world_canonical_frozen_topology SELECT (jsonb_populate_record(NULL::world_canonical_frozen_topology, " + + "to_jsonb(t) || jsonb_build_object('capture_id', ?, 'freeze_request_json', " + + "replace(freeze_request_json, '\"digestSchemaVersion\":3', ?)))).* " + + "FROM world_canonical_frozen_topology t WHERE publication_fence=?", + UUID.randomUUID(), + "\"digestSchemaVersion\":" + denied, template.freeze().publicationFence())) + .hasStackTraceContaining("requires digest schema 3"); + } + assertOrigin(); + } + + @Test + void newSchema3CaptureRejectsChangedContentDigestAndEveryReturnedScopeField() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + for (int changed = 0; changed < 4; changed++) { + int field = changed; + var bad = + frozen( + (tenant, version) -> + new net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService + .WorldDraftDesignDigest( + field == 0 ? "999999999" : tenant, + field == 1 ? "999999999" : version, + "version:" + version, + field == 2 ? "c".repeat(64) : request.freeze().contentDigest(), + field == 3 ? 2 : 3)); + assertThatThrownBy(() -> bad.capture(request)) + .hasMessageContaining("differs from exact schema-3 frozen content checkpoint"); + assertThat(countCaptures(request)).isZero(); + } + var captured = frozen().capture(request); + assertThat(captured.request().freeze().digestSchemaVersion()).isEqualTo(3); + assertThat( + frozen( + (tenant, version) -> { + throw new AssertionError("Exact retry must use retained journal"); + }) + .capture(request) + .resultBytes()) + .containsExactly(captured.resultBytes()); + } + + @Test + void changedCompleteBindingOrAnyFreezeCheckpointFieldCannotReplayCapture() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request original = freeze(p); + frozen().capture(original); + var b = p.binding(); + var changed = + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + b.target(), + b.requestId(), + b.commitId(), + b.baseCommitId() + "-changed", + b.revisions(), + b.affectedUnits()), + p.ownerBinding()); + assertThatThrownBy(() -> frozen().readCommitted(new Request(changed, original.freeze()))) + .hasMessageContaining("changed complete input"); + CaptureRequest r = original.freeze(); + for (CaptureRequest bad : + List.of( + copy( + r, + r.requestDigest(), + r.contentDigest(), + r.versionStateEpoch() + 1, + r.publicationRequestId(), + r.publishWorkflowId()), + copy( + r, + "c".repeat(64), + r.contentDigest(), + r.versionStateEpoch(), + r.publicationRequestId(), + r.publishWorkflowId()), + copy( + r, + r.requestDigest(), + "c".repeat(64), + r.versionStateEpoch(), + r.publicationRequestId(), + r.publishWorkflowId()), + copy( + r, + r.requestDigest(), + r.contentDigest(), + r.versionStateEpoch(), + r.publicationRequestId() + "-changed", + r.publishWorkflowId() + "-changed"))) { + assertThatThrownBy(() -> frozen().capture(new Request(p, bad))) + .isInstanceOf(RuntimeException.class); + } + assertThat(countCaptures(original)).isEqualTo(1); + } + + @Test + void historicalReadAndExactRetryAfterEveryTerminalPhaseUseOnlyOriginalJournal() { + for (String phase : List.of("PUBLISHED", "ABORTED", "RECONCILIATION_REQUIRED")) { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + byte[] original = frozen().capture(request).resultBytes(); + bypass( + "UPDATE world_design_publication_fence_owner SET owner_freeze_phase=? WHERE local_tenant_key=?", + phase, + f.intake().localTenantKey()); + bypass( + "UPDATE region SET weather='corrupt-current-row' WHERE tenant_id=?", + f.intake().localTenantKey()); + bypass( + "UPDATE world_topology_draft_commit SET result_bytes='corrupt-original-history'::bytea WHERE request_id=?", + p.binding().requestId()); + assertThat(frozen().readCommitted(request).orElseThrow().resultBytes()) + .containsExactly(original); + assertThat(frozen().capture(request).resultBytes()).containsExactly(original); + assertThat(countCaptures(request)).isEqualTo(1); + assertOrigin(); + } + } + + @Test + void noNewCaptureAfterTerminalAndAbsentJournalRemainsUnknown() { + for (String phase : List.of("PUBLISHED", "ABORTED", "RECONCILIATION_REQUIRED")) { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + bypass( + "UPDATE world_design_publication_fence_owner SET owner_freeze_phase=? WHERE local_tenant_key=?", + phase, + f.intake().localTenantKey()); + assertThat(frozen().readCommitted(request)).isEmpty(); + assertThatThrownBy(() -> frozen().capture(request)).hasMessageContaining("current FROZEN"); + assertThat(countCaptures(request)).isZero(); + } + } + + @Test + void captureRejectsActualRowTamperingAndMismatchedCurrentFenceBeforeJournalInsert() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + bypass("UPDATE room_exit SET cost=99 WHERE tenant_id=?", f.intake().localTenantKey()); + assertThatThrownBy(() -> frozen().capture(request)).hasMessageContaining("payload field"); + assertThat(countCaptures(request)).isZero(); + Fixture second = fixture(); + var secondPlan = plan(second); + component().store(secondPlan); + Request exact = freeze(secondPlan); + bypass( + "UPDATE world_design_publication_fence_owner SET current_publication_fence=? WHERE local_tenant_key=?", + UUID.randomUUID(), + second.intake().localTenantKey()); + assertThatThrownBy(() -> frozen().capture(exact)) + .hasMessageContaining("retained V25 owner binding"); + assertThat(countCaptures(exact)).isZero(); + } + + @Test + void frozenCheckpointWithoutCommittedCompleteStorageCannotCreateCapture() { + Fixture f = fixture(); + var p = plan(f); + Request request = freeze(p); + assertThat(frozen().readCommitted(request)).isEmpty(); + assertThatThrownBy(() -> frozen().capture(request)) + .hasMessageContaining("no committed complete topology result"); + assertThat(countCaptures(request)).isZero(); + } + + @Test + void v31UpgradePreservesExistingV30SourceRowsMappingsResultsAndFrozenCheckpoint() + throws Exception { + Fixture f = fixture(); + var p = plan(f); + var stored = component().store(p); + Request request = freeze(p); + String schema = "retained_capture_" + UUID.randomUUID().toString().replace("-", ""); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("30")) + .load() + .migrate(); + Map tables = new LinkedHashMap<>(); + for (String table : + List.of( + "world_authored_source_tenant_association", + "world_authored_source_intake", + "world_authored_version_identity", + "world_design_publication_fence_attempt", + "world_design_publication_fence_owner", + "world_topology_draft_commit")) tables.put(table, "local_tenant_key"); + tables.put("world_authored_source_tenant_key_reservation", "tenant_key"); + for (String table : + List.of( + "world_authored_topology_identity", + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_design_aggregate_epoch", + "world_design_scope_epoch")) { + tables.put(table, "tenant_id"); + } + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + DSLContext retained = DSL.using(connection, SQLDialect.POSTGRES); + retained.execute("SET search_path TO " + schema + ", public"); + connection.setAutoCommit(false); + retained.execute("SET LOCAL session_replication_role='replica'"); + for (var table : tables.entrySet()) { + String columns = retainedColumns(retained, schema, table.getKey()); + String override = + table.getKey().equals("world_authored_version_identity") + ? " OVERRIDING SYSTEM VALUE" + : ""; + retained.execute( + "INSERT INTO " + + table.getKey() + + " (" + + columns + + ")" + + override + + " SELECT " + + columns + + " FROM world_management_service." + + table.getKey() + + " WHERE " + + table.getValue() + + "=?", + f.intake().localTenantKey()); + } + retained.execute("SET LOCAL session_replication_role='origin'"); + connection.commit(); + connection.setAutoCommit(true); + Map> before = retainedRows(retained, tables); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat(retainedRows(retained, tables)).isEqualTo(before); + assertNoPromotionOfRetainedTopology(retained); + assertThat( + retained + .resultQuery("SELECT count(*) FROM world_canonical_frozen_topology") + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + retained + .resultQuery("SELECT graph_bytes FROM world_topology_draft_commit") + .fetchOne(0, byte[].class)) + .containsExactly(stored.graphBytes()); + assertThat( + retained + .resultQuery("SELECT result_bytes FROM world_topology_draft_commit") + .fetchOne(0, byte[].class)) + .containsExactly(stored.resultBytes()); + assertThat( + retained + .resultQuery( + "SELECT publication_fence FROM world_design_publication_fence_attempt") + .fetchOne(0, UUID.class)) + .isEqualTo(request.freeze().publicationFence()); + } finally { + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private Map> retainedRows(DSLContext database, Map tables) { + Map> rows = new LinkedHashMap<>(); + for (String table : tables.keySet()) { + String rowJson = + table.equals("world_topology_draft_commit") + ? "to_jsonb(t) - 'application_transaction_id'" + : "to_jsonb(t)"; + rows.put( + table, + database + .resultQuery( + "SELECT " + + "(" + + rowJson + + ")" + + "::text FROM " + + table + + " t ORDER BY " + + rowJson) + .fetch(0, String.class)); + } + return rows; + } + + private String retainedColumns(DSLContext database, String schema, String table) { + return Objects.requireNonNull( + database + .resultQuery( + "SELECT string_agg(quote_ident(column_name), ', ' ORDER BY ordinal_position) " + + "FROM information_schema.columns WHERE table_schema = ? AND table_name = ?", + schema, + table) + .fetchOne(0, String.class), + "retained fixture must expose its original columns"); + } + + private void assertNoPromotionOfRetainedTopology(DSLContext database) { + assertThat( + database + .resultQuery( + "SELECT count(*) FROM world_topology_draft_commit " + + "WHERE application_transaction_id IS NOT NULL") + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + database + .resultQuery("SELECT count(*) FROM world_draft_graph_application") + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + database + .resultQuery("SELECT count(*) FROM world_draft_graph_terminal_identity") + .fetchOne(0, Long.class)) + .isZero(); + } + + @Test + void immutableJournalDeniesWritesAndHistoricalReadRejectsEveryTamperedField() { + Map mutations = new LinkedHashMap<>(); + mutations.put("result_bytes", "result_bytes='corrupt'::bytea"); + mutations.put("storage_result_bytes", "storage_result_bytes='corrupt'::bytea"); + mutations.put("binding_digest", "binding_digest='sha256:" + "f".repeat(64) + "'"); + mutations.put( + "binding_json", "binding_json=replace(binding_json,'retained-base','tampered-base')"); + mutations.put( + "identity_json", + "identity_json=replace(identity_json,'local_version_key','unsupported_key')"); + mutations.put( + "intake_json", + "intake_json=replace(intake_json,'Synthetic component world','changed source')"); + mutations.put( + "owner_binding_json", "owner_binding_json=replace(owner_binding_json,'firemud','other')"); + mutations.put("freeze_request_json contentDigest", null); + mutations.put("graph_sha256", "graph_sha256='" + "d".repeat(64) + "'"); + + for (var mutation : mutations.entrySet()) { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + frozen().capture(request); + String set = mutation.getValue(); + if (set == null) { + String originalDigest = request.freeze().contentDigest(); + String changedDigest = + (originalDigest.charAt(0) == '0' ? "1" : "0") + originalDigest.substring(1); + assertThat(changedDigest) + .as("replacement for %s differs from the actual schema-3 digest", mutation.getKey()) + .isNotEqualTo(originalDigest); + set = + "freeze_request_json=replace(freeze_request_json,'" + + originalDigest + + "','" + + changedDigest + + "')"; + } + String before = + dsl.resultQuery( + "SELECT to_jsonb(t)::text FROM world_canonical_frozen_topology t " + + "WHERE publication_fence=?", + request.freeze().publicationFence()) + .fetchOne(0, String.class); + assertThat(before).as("original journal row exists for %s", mutation.getKey()).isNotNull(); + String update = "UPDATE world_canonical_frozen_topology SET " + set; + assertThatThrownBy( + () -> + dsl.execute( + update + " WHERE publication_fence=?", request.freeze().publicationFence())) + .as("origin trigger rejects direct update of %s", mutation.getKey()) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.freeze().publicationFence())) + .as("origin trigger rejects direct delete while testing %s", mutation.getKey()) + .isInstanceOf(RuntimeException.class); + bypass(update + " WHERE publication_fence=?", request.freeze().publicationFence()); + String after = + dsl.resultQuery( + "SELECT to_jsonb(t)::text FROM world_canonical_frozen_topology t WHERE publication_fence=?", + request.freeze().publicationFence()) + .fetchOne(0, String.class); + assertThat(after) + .as("bypass mutation changes the complete original journal row for %s", mutation.getKey()) + .isNotNull() + .isNotEqualTo(before); + assertThatThrownBy(() -> frozen().readCommitted(request)) + .as("historical read rejects tampered %s", mutation.getKey()) + .isInstanceOf(RuntimeException.class); + assertOrigin(); + } + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_canonical_frozen_topology")) + .isInstanceOf(RuntimeException.class); + } + + @Test + void recomputedGraphChecksumCannotHideTypedEndpointOrCanonicalEntityTampering() { + for (String replacement : List.of("\"to_room_id\": 0", "\"entity_template_id\": 123")) { + // The replacement string is selected from test constants, never a caller-supplied selector. + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + var captured = frozen().capture(request); + String graph = new String(captured.graphBytes(), StandardCharsets.UTF_8); + String bad = + replacement.startsWith("\"to_room_id\"") + ? graph.replaceAll("\"to_room_id\"\\s*:\\s*[0-9]+", "\"to_room_id\":0") + : graph.replace("\"entity_template_id\":null", "\"entity_template_id\":123"); + assertThat(bad).isNotEqualTo(graph); + byte[] badBytes = bad.getBytes(StandardCharsets.UTF_8); + bypass( + "UPDATE world_canonical_frozen_topology SET graph_bytes=?,graph_sha256=? WHERE publication_fence=?", + badBytes, + WorldAuthoredGraphSnapshotCapture.sha256(badBytes), + request.freeze().publicationFence()); + assertThatThrownBy(() -> frozen().readCommitted(request)) + .hasMessageContaining("exact typed original payload"); + } + } + + @Test + void twoConcurrentCapturesReturnOneOriginalImmutableResult() throws Exception { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request request = freeze(p); + CountDownLatch start = new CountDownLatch(1); + try (var pool = Executors.newFixedThreadPool(2)) { + var first = + pool.submit( + () -> { + assertThat(start.await(15, TimeUnit.SECONDS)).isTrue(); + return frozen().capture(request); + }); + var second = + pool.submit( + () -> { + assertThat(start.await(15, TimeUnit.SECONDS)).isTrue(); + return frozen().capture(request); + }); + start.countDown(); + var one = first.get(20, TimeUnit.SECONDS); + var two = second.get(20, TimeUnit.SECONDS); + assertThat(one.captureId()).isEqualTo(two.captureId()); + assertThat(one.resultBytes()).containsExactly(two.resultBytes()); + } + assertThat(countCaptures(request)).isEqualTo(1); + } + + private WorldCanonicalFrozenTopologyService frozen() { + return frozen(digestService); + } + + private WorldCanonicalFrozenTopologyService frozen( + net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService producer) { + return new WorldCanonicalFrozenTopologyService( + new WorldCanonicalFrozenTopologyRepository(dsl, snapshots, repository(), producer), + manager); + } + + @Test + void v32PreservesOriginalSchema2FrozenJournalAndExactHistoricalRetries() throws Exception { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + Request current = freeze(p); + var captured = frozen().capture(current); + CaptureRequest r = current.freeze(); + Request historical = + new Request( + p, + new CaptureRequest( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + r.publicationRequestId(), + r.requestDigest(), + r.versionStateEpoch(), + r.publishWorkflowId(), + r.appliedCommitId(), + r.contentDigest(), + 2, + r.suppliedOwnedAffectedTuples())); + String schema = "retained_schema2_" + UUID.randomUUID().toString().replace("-", ""); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("31")) + .load() + .migrate(); + Map tables = new LinkedHashMap<>(); + for (String table : + List.of( + "world_authored_source_tenant_association", + "world_authored_source_intake", + "world_authored_version_identity", + "world_design_publication_fence_attempt", + "world_design_publication_fence_owner", + "world_topology_draft_commit")) tables.put(table, "local_tenant_key"); + tables.put("world_authored_source_tenant_key_reservation", "tenant_key"); + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + DSLContext retained = DSL.using(connection, SQLDialect.POSTGRES); + retained.execute("SET search_path TO " + schema + ", public"); + connection.setAutoCommit(false); + retained.execute("SET LOCAL session_replication_role='replica'"); + for (var table : tables.entrySet()) { + String columns = retainedColumns(retained, schema, table.getKey()); + String override = + table.getKey().equals("world_authored_version_identity") + ? " OVERRIDING SYSTEM VALUE" + : ""; + retained.execute( + "INSERT INTO " + + table.getKey() + + " (" + + columns + + ")" + + override + + " SELECT " + + columns + + " FROM world_management_service." + + table.getKey() + + " WHERE " + + table.getValue() + + "=?", + f.intake().localTenantKey()); + } + // Synthetic original schema-2 evidence is installed before V32, never upgraded or rehashed by + // it. + retained.execute( + "UPDATE world_design_publication_fence_attempt SET digest_schema_version=2 WHERE publication_fence=?", + r.publicationFence()); + byte[] originalResult = + new String(captured.resultBytes(), StandardCharsets.UTF_8) + .replace("\"digestSchemaVersion\":3", "\"digestSchemaVersion\":2") + .getBytes(StandardCharsets.UTF_8); + retained.execute( + "INSERT INTO world_canonical_frozen_topology SELECT (jsonb_populate_record(NULL::world_canonical_frozen_topology, " + + "to_jsonb(t) || jsonb_build_object('freeze_request_json', replace(freeze_request_json, '\"digestSchemaVersion\":3', '\"digestSchemaVersion\":2'), " + + "'result_bytes', ?::bytea))).* FROM world_management_service.world_canonical_frozen_topology t WHERE publication_fence=?", + originalResult, + r.publicationFence()); + retained.execute("SET LOCAL session_replication_role='origin'"); + connection.commit(); + connection.setAutoCommit(true); + tables.put("world_canonical_frozen_topology", "publication_fence"); + var before = retainedRows(retained, tables); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat(retainedRows(retained, tables)).isEqualTo(before); + assertNoPromotionOfRetainedTopology(retained); + var repo = + new WorldCanonicalFrozenTopologyRepository( + retained, + new WorldAuthoredGraphSnapshotRepository(retained), + new WorldDraftTopologyCommitRepository( + retained, + new WorldDesignPublicationFenceRepository( + retained, new WorldAuthoredSourceIntakeRepository(retained)), + mapper), + (tenant, version) -> { + throw new AssertionError("Historical retry must never recompute content"); + }); + var service = new WorldCanonicalFrozenTopologyService(repo, manager); + assertThat(service.readCommitted(historical).orElseThrow().resultBytes()) + .containsExactly(originalResult); + assertThat(service.capture(historical).resultBytes()).containsExactly(originalResult); + assertThat(service.capture(historical).request().freeze().digestSchemaVersion()).isEqualTo(2); + assertThatThrownBy(() -> service.readCommitted(current)) + .hasMessageContaining("changed complete input"); + assertThat(retainedRows(retained, tables)).isEqualTo(before); + } finally { + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private Request freeze(WorldDraftTopologyCommitPlan p) { + return freeze(p, 3); + } + + private Request freeze(WorldDraftTopologyCommitPlan p, int schema) { + var o = p.ownerBinding(); + String publicationRequest = "capture-" + UUID.randomUUID(); + var evidence = + new WorldDesignPublicationFenceEvidence( + o.targetNamespace(), + o.canonicalTenantId(), + o.canonicalVersionId(), + o.versionIdentityOperationId(), + o.gameDesignVersionId(), + o.intakeRequestId(), + o.intakeOperationId(), + o.intakeRequestDigest(), + o.sourceOperationId(), + o.sourceEvidenceDigest(), + o.intakeReceiptDigest(), + publicationRequest, + "a".repeat(64), + 1, + "publish:" + o.canonicalTenantId() + ":publish-request:" + publicationRequest); + // Compute content under the exact owner lock; selected commit is still not complete APPLIED. + var attempt = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, + () -> { + var keys = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT local_tenant_key, local_version_key FROM world_authored_version_identity WHERE operation_id=?", + o.versionIdentityOperationId()), + "expected owner version-identity row"); + var digest = + digestService.getDraftDesignDigest( + Long.toString(keys.get("local_tenant_key", Long.class)), + Long.toString(keys.get("local_version_key", Long.class))); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + p.binding().commitId().toString(), + digest.contentDigest(), + schema); + }))); + var tuples = + p.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + new OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList(); + return new Request( + p, + new CaptureRequest( + o.targetNamespace(), + o.canonicalTenantId(), + o.canonicalVersionId(), + o.intakeRequestId(), + attempt.publicationFence(), + publicationRequest, + evidence.requestDigest(), + evidence.versionStateEpoch(), + evidence.publishWorkflowId(), + attempt.checkpoint().appliedCommitId(), + attempt.checkpoint().contentDigest(), + attempt.checkpoint().digestSchemaVersion(), + tuples)); + } + + private CaptureRequest copy( + CaptureRequest r, + String digest, + String content, + long epoch, + String publication, + String workflow) { + return new CaptureRequest( + r.targetNamespace(), + r.canonicalTenantId(), + r.canonicalVersionId(), + r.intakeRequestId(), + r.publicationFence(), + publication, + digest, + epoch, + workflow, + r.appliedCommitId(), + content, + r.digestSchemaVersion(), + r.suppliedOwnedAffectedTuples()); + } + + private void bypass(String sql, Object... values) { + ownerTransaction() + .execute( + status -> { + dsl.execute("SET LOCAL session_replication_role='replica'"); + try { + dsl.execute(sql, values); + } finally { + dsl.execute("SET LOCAL session_replication_role='origin'"); + } + return null; + }); + assertOrigin(); + } + + private long countCaptures(Request request) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT count(*) FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.freeze().publicationFence()) + .fetchOne(0, Long.class)); + } + + private Fixture fixture() { + UUID tenant = UUID.randomUUID(); + UUID registration = UUID.randomUUID(); + UUID sourceOperation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + long sourceRow = Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + String sourceTenant = "gd-row-" + sourceRow; + String digest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, "Synthetic component world"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW", + evidenceDigest); + UUID intakeRequest = UUID.randomUUID(); + ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, intakeRequest, source)); + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository.read(NAMESPACE, intakeRequest).orElseThrow(); + return Objects.requireNonNull( + ownerTransaction() + .execute( + status -> { + UUID canonicalVersion = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + worldSlug, + sourceOperation, + evidenceDigest, + GAME_DESIGN_VERSION); + WorldAuthoredVersionIdentityReceipt version = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + tenant, + canonicalVersion, + version.operationId(), + GAME_DESIGN_VERSION, + intakeRequest, + intake.operationId(), + intake.requestDigest(), + sourceOperation, + evidenceDigest, + intake.receiptDigest()); + assertOrigin(); + return new Fixture(intake, version, owner); + })); + } + + private WorldDraftTopologyCommitPlan plan(Fixture f) { + UUID logical = UUID.randomUUID(); + UUID secondRoom = UUID.randomUUID(); + UUID entity = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + List values = new ArrayList<>(); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("region") + .setWeather("rain") + .setShardId(7) + .setGenerationSeed(9_007_199_254_740_999L) + .setGeneratorType("synthetic") + .setGeneratorParams("{\"seed\":1}")) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder().setName("zone").setRegionId(logical.toString())) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("room") + .setZoneId(logical.toString()) + .setDescription("description") + .setNameLocalizedVariantsJson("{\"en\":\"room\"}") + .setDescriptionLocalizedVariantsJson("{\"en\":\"description\"}")) + .build()); + values.add( + mutation( + commit, + secondRoom, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder().setName("second").setZoneId(logical.toString())) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(logical.toString()) + .setToRoomId(secondRoom.toString()) + .setDirection("NORTH")) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder().setName("rule").setValue("seeded")) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(logical.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(entity.toString()) + .setRespawnDelaySeconds(17)) + .build()); + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + "synthetic opaque Entity input; existence and permission remain unverified")); + units.add( + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "NPC", + entity.toString(), + "AGGREGATE", + entity.toString(), + "0")); + // Original input order deliberately places children before their parents. + for (var m : values.reversed()) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(m.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + json(m))); + String family = m.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "AGGREGATE", + m.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "REGION_SUBTREE", + m.getScopeId(), + "0")); + } + var s = f.intake().source(); + var target = + new DraftCommitBinding.TargetProof( + f.owner().canonicalTenantId(), + f.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + s.sourceGameTenantKey(), + s.sourceGameRowId(), + s.sourceGameTenantKey(), + s.provenanceKind()); + return WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + target, UUID.randomUUID(), commit, "retained-base", revisions, units), + f.owner()); + } + + private WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID id, UUID scope, WorldDesignAggregateType type) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(id.toString()) + .setAggregateType(type) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(scope.toString()); + } + + private WorldDraftTopologyCommitService component() { + return new WorldDraftTopologyCommitService( + repository(), + manager, + p -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertOrigin(); + // Synthetic local-storage fixture only; no Account permission or Entity existence proof. + }); + } + + private WorldDraftTopologyCommitRepository repository() { + return new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate tx = new TransactionTemplate(manager); + tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return tx; + } + + private void assertOrigin() { + assertThat( + dsl.resultQuery("SELECT current_setting('session_replication_role')") + .fetchOne(0, String.class)) + .isEqualTo("origin"); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new AssertionError(exception); + } + } + + private record Fixture( + WorldAuthoredSourceIntakeReceipt intake, + WorldAuthoredVersionIdentityReceipt version, + OwnerBinding owner) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldMigrationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..a671234a01 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldMigrationPostgresIntegrationTest.java @@ -0,0 +1,354 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +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.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.worldmanagement.repository.InitialAdmissionBindHoldRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL definitions for the V46-to-V47 initial-admission hold upgrade boundary. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class WorldCanonicalInitialAdmissionHoldMigrationPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void v46ToV47RetainsLegacyHoldRowsAndDoesNotInferCanonicalIdentity() throws Exception { + String schema = newSchema("initial_hold_retained_"); + try { + migrate(schema, "46"); + List before = new ArrayList<>(); + try (Connection connection = connection()) { + DSLContext dsl = schemaContext(connection, schema); + for (String status : List.of("PENDING", "COMMITTED", "ABORTED")) { + WorldFixture world = worldFixture(); + insertLegacyWorld(dsl, world); + before.add(insertLegacyHold(dsl, world, status)); + } + } + + migrate(schema, "47"); + + try (Connection connection = connection()) { + DSLContext dsl = schemaContext(connection, schema); + for (LegacySnapshot snapshot : before) { + var retained = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT (to_jsonb(h) - ARRAY[" + + "'canonical_target_namespace', 'canonical_tenant_id', 'canonical_world_slug', " + + "'canonical_game_instance_id', 'canonical_version_id', " + + "'initial_admission_origin', 'expected_prior_pointer_version', " + + "'canonical_request_bytes', 'hold_binding_digest']::text[]) = ?::jsonb AS original_row, " + + "h.canonical_target_namespace IS NULL " + + "AND h.canonical_tenant_id IS NULL " + + "AND h.canonical_world_slug IS NULL " + + "AND h.canonical_game_instance_id IS NULL " + + "AND h.canonical_version_id IS NULL " + + "AND h.initial_admission_origin IS NULL " + + "AND h.expected_prior_pointer_version IS NULL " + + "AND h.canonical_request_bytes IS NULL " + + "AND h.hold_binding_digest IS NULL AS unmapped " + + "FROM initial_admission_bind_hold h " + + "WHERE h.initial_admission_request_id = ?", + snapshot.rowJson(), + snapshot.requestId())); + assertThat(retained.get("original_row", Boolean.class)) + .as("all V23 hold, owner-proof, timestamp, and row-version fields remain unchanged") + .isTrue(); + assertThat(retained.get("unmapped", Boolean.class)) + .as("V47 must not infer canonical identity for a retained numeric hold") + .isTrue(); + } + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM initial_admission_bind_hold")) + .get(0, Long.class)) + .isEqualTo(3L); + } + } finally { + dropSchema(schema); + } + } + + @Test + void incompleteCanonicalMetadataIsRejectedByTheV47Constraint() throws Exception { + String schema = newSchema("initial_hold_partial_"); + try { + migrate(schema, "47"); + try (Connection connection = connection()) { + DSLContext dsl = schemaContext(connection, schema); + WorldFixture world = worldFixture(); + insertLegacyWorld(dsl, world); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO initial_admission_bind_hold (hold_id, hold_fence, tenant_id, " + + "realm_uuid, playable_state_namespace_uuid, playable_state_scope, " + + "game_instance_id, version_id, active_lifecycle_epoch, " + + "initial_admission_request_id, request_digest, expected_no_prior_pointer, " + + "expected_catalog_revision, status, diagnostic_expires_at, " + + "canonical_target_namespace) " + + "VALUES (?::uuid, ?::uuid, ?, ?::uuid, ?::uuid, 'SHARED', ?, 71, 4, ?, ?, " + + "TRUE, 1, 'PENDING', CURRENT_TIMESTAMP, 'forged-space')", + UUID.randomUUID(), + UUID.randomUUID(), + world.tenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + world.gameInstanceId(), + "partial-canonical-" + UUID.randomUUID(), + "a".repeat(64))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("ck_initial_admission_bind_canonical_metadata"); + } + } finally { + dropSchema(schema); + } + } + + @Test + void forgedCompleteTypedHoldWithoutAnActualWorldAssociationIsRejected() throws Exception { + String schema = newSchema("initial_hold_forged_assoc_"); + try { + migrate(schema, "47"); + try (Connection connection = connection()) { + DSLContext dsl = schemaContext(connection, schema); + WorldFixture world = worldFixture(); + insertLegacyWorld(dsl, world); + + UUID realmId = UUID.randomUUID(); + UUID playableNamespaceId = UUID.randomUUID(); + UUID canonicalTenantId = UUID.randomUUID(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID canonicalVersionId = UUID.randomUUID(); + String requestId = "forged-canonical-" + UUID.randomUUID(); + String requestDigest = "b".repeat(64); + WorldCanonicalInitialAdmissionHold.Request holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + "test-space", + canonicalTenantId, + "test-world", + realmId, + playableNamespaceId, + "SHARED", + canonicalGameInstanceId, + canonicalVersionId, + 4L, + requestId, + requestDigest, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + byte[] requestBytes = holdRequest.canonicalRequestBytes(); + String bindingDigest = holdRequest.holdBindingDigest(); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO initial_admission_bind_hold (hold_id, hold_fence, tenant_id, " + + "realm_uuid, playable_state_namespace_uuid, playable_state_scope, " + + "game_instance_id, version_id, active_lifecycle_epoch, " + + "initial_admission_request_id, request_digest, expected_no_prior_pointer, " + + "expected_catalog_revision, status, diagnostic_expires_at, " + + "canonical_target_namespace, canonical_tenant_id, canonical_world_slug, " + + "canonical_game_instance_id, canonical_version_id, initial_admission_origin, " + + "canonical_request_bytes, hold_binding_digest) " + + "VALUES (?::uuid, ?::uuid, ?, ?::uuid, ?::uuid, 'SHARED', ?, 71, 4, ?, ?, " + + "TRUE, 1, 'PENDING', CURRENT_TIMESTAMP, 'test-space', ?::uuid, " + + "'test-world', ?::uuid, ?::uuid, 'NO_PRIOR_POINTER', ?::bytea, ?)", + UUID.randomUUID(), + UUID.randomUUID(), + world.tenantId(), + realmId, + playableNamespaceId, + world.gameInstanceId(), + requestId, + requestDigest, + canonicalTenantId, + canonicalGameInstanceId, + canonicalVersionId, + requestBytes, + bindingDigest)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining( + "Canonical initial-admission hold lacks its actual World association"); + } + } finally { + dropSchema(schema); + } + } + + @Test + void legacyReconciliationAndTerminalProofRemainAvailableAndNonterminalRowsBlockRealm() + throws Exception { + String schema = newSchema("initial_hold_legacy_path_"); + try { + migrate(schema, "47"); + try (Connection connection = connection()) { + DSLContext dsl = schemaContext(connection, schema); + WorldFixture world = worldFixture(); + insertLegacyWorld(dsl, world); + LegacySnapshot snapshot = insertLegacyHold(dsl, world, "PENDING"); + InitialAdmissionBindHoldRepository repository = new InitialAdmissionBindHoldRepository(dsl); + + var pending = + repository + .findByTenantIdAndRequestId(world.tenantId(), snapshot.requestId()) + .orElseThrow(); + assertThat(repository.hasNonterminalForRealm(world.tenantId(), pending.realmUuid())) + .isTrue(); + + var reconciling = + repository + .markReconciliationRequired( + pending, "LEGACY_RECONCILIATION_TEST", Instant.parse("2026-01-01T00:00:00Z")) + .orElseThrow(); + assertThat(reconciling.status()).isEqualTo("RECONCILIATION_REQUIRED"); + assertThat(repository.hasNonterminalForRealm(world.tenantId(), reconciling.realmUuid())) + .isTrue(); + + var committed = + repository + .recordTerminalProof( + reconciling, + "COMMITTED", + "legacy-owner-proof", + "c".repeat(64), + "legacy-pointer-audit", + 19L, + Instant.parse("2026-01-01T00:00:01Z")) + .orElseThrow(); + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertThat(committed.ownerProofId()).isEqualTo("legacy-owner-proof"); + assertThat(committed.ownerPointerVersion()).isEqualTo(19L); + assertThat(committed.rowVersion()).isEqualTo(reconciling.rowVersion() + 1L); + assertThat(repository.hasNonterminalForRealm(world.tenantId(), committed.realmUuid())) + .isFalse(); + } + } finally { + dropSchema(schema); + } + } + + private LegacySnapshot insertLegacyHold(DSLContext dsl, WorldFixture world, String status) { + String requestId = "legacy-" + status.toLowerCase() + "-" + UUID.randomUUID(); + UUID holdId = UUID.randomUUID(); + UUID holdFence = UUID.randomUUID(); + UUID realmId = UUID.randomUUID(); + UUID playableNamespaceId = UUID.randomUUID(); + String proofId = status.equals("PENDING") ? null : "retained-proof-" + status.toLowerCase(); + String proofDigest = status.equals("PENDING") ? null : "d".repeat(64); + String pointerAudit = status.equals("COMMITTED") ? "retained-audit" : null; + Long pointerVersion = status.equals("COMMITTED") ? 23L : null; + Instant terminalAt = status.equals("PENDING") ? null : Instant.parse("2025-02-03T04:05:06Z"); + String sql = + "INSERT INTO initial_admission_bind_hold (hold_id, hold_fence, tenant_id, realm_uuid, " + + "playable_state_namespace_uuid, playable_state_scope, game_instance_id, version_id, " + + "active_lifecycle_epoch, initial_admission_request_id, request_digest, " + + "expected_no_prior_pointer, expected_catalog_revision, status, diagnostic_expires_at, " + + "owner_proof_id, owner_proof_digest, owner_pointer_audit_id, owner_pointer_version, " + + "terminal_at, row_version) VALUES (?::uuid, ?::uuid, ?, ?::uuid, ?::uuid, 'SHARED', ?, 71, " + + "4, ?, ?, TRUE, 1, ?, TIMESTAMP '2099-01-01 00:00:00', ?, ?, ?, ?, ?, 17) " + + "RETURNING to_jsonb(initial_admission_bind_hold)::text AS row_json"; + String rowJson = + Objects.requireNonNull( + dsl.fetchOne( + sql, + holdId, + holdFence, + world.tenantId(), + realmId, + playableNamespaceId, + world.gameInstanceId(), + requestId, + "e".repeat(64), + status, + proofId, + proofDigest, + pointerAudit, + pointerVersion, + terminalAt == null ? null : java.time.LocalDateTime.of(2025, 2, 3, 4, 5, 6))) + .get("row_json", String.class); + return new LegacySnapshot(requestId, rowJson); + } + + private void insertLegacyWorld(DSLContext dsl, WorldFixture world) { + dsl.execute( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, runtime_flags_json, " + + "generation_config_revision, release_bundle_id, published_release_bundle_ref, " + + "version_state_epoch, lifecycle_epoch, status, row_version) " + + "VALUES (?, ?, 81, ?, 'legacy-hold-descriptor', 71, '{}', 'legacy-hold-config', " + + "91, 'legacy-hold-release', 31, 4, 'ACTIVE', 0)", + world.tenantId(), + world.gameInstanceId(), + "legacy-hold-world-" + UUID.randomUUID()); + } + + private WorldFixture worldFixture() { + long suffix = Math.abs(UUID.randomUUID().getLeastSignificantBits() % 100_000L); + return new WorldFixture(810_000L + suffix, 820_000L + suffix); + } + + private String newSchema(String prefix) { + return prefix + UUID.randomUUID().toString().replace("-", ""); + } + + private void migrate(String schema, String targetVersion) { + var configuration = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_world_management_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (targetVersion != null) { + configuration.target(MigrationVersion.fromVersion(targetVersion)); + } + configuration.load().migrate(); + } + + private Connection connection() throws Exception { + return DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + } + + private DSLContext schemaContext(Connection connection, String schema) { + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + dsl.execute("SET search_path TO " + schema + ", public"); + return dsl; + } + + private void dropSchema(String schema) throws Exception { + try (Connection connection = connection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } + + private record WorldFixture(long tenantId, long gameInstanceId) {} + + private record LegacySnapshot(String requestId, String rowJson) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java new file mode 100644 index 0000000000..1895de7da7 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -0,0 +1,2429 @@ +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.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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 java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.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.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; +import tools.jackson.databind.ObjectMapper; + +/** + * Focused PostgreSQL proof for guarded, immutable, non-authorizing canonical materialization and + * World canonical-instance association. + * + *

Upstream Game Design and Game Session results, Account ordering, and held preparation + * authority remain explicitly isolated fixture evidence. World source intake, Version identity, + * APPLIED graph, frozen selector, PUBLISHED terminal storage, guarded runtime materialization, + * association, migration, constraints, and independent committed readback use actual migrated + * PostgreSQL repositories and tables. This fixture does not claim authenticated producer/delivery + * evidence, Account commit authority, lifecycle transition success, actor authority, or gameplay + * admission. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldCanonicalInstanceAssociationPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final long VERSION_EPOCH = 7L; + + @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 DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private WorldDesignPublicationFenceRepository publicationFence; + @Autowired private WorldAuthoredGraphSnapshotRepository graphSnapshots; + + @Autowired + private net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService + digestService; + + @Autowired private ObjectMapper objectMapper; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + private WorldAuthoredSourceIntakeRepository sourceRepository; + private WorldCompleteLaunchBindingRepository launchBindingRepository; + private WorldAuthoredVersionIdentityRepository versionIdentityRepository; + private WorldCanonicalInstanceAssociationRepository associationRepository; + private final Map frozenPlans = + new java.util.HashMap<>(); + + @BeforeEach + void createRepositories() { + sourceRepository = new WorldAuthoredSourceIntakeRepository(dsl); + launchBindingRepository = new WorldCompleteLaunchBindingRepository(dsl); + versionIdentityRepository = new WorldAuthoredVersionIdentityRepository(dsl); + associationRepository = + new WorldCanonicalInstanceAssociationRepository( + dsl, launchBindingRepository, sourceRepository, versionIdentityRepository); + } + + @Test + void changedReleaseCommitFailsJavaAndDatabaseBeforeAllocation() { + assertReleaseCheckpointSubstitutionDenied(true); + } + + @Test + void changedWorldContentDigestFailsJavaAndDatabaseBeforeAllocation() { + assertReleaseCheckpointSubstitutionDenied(false); + } + + private void assertReleaseCheckpointSubstitutionDenied(boolean changeCommit) { + Fixture original = fixture(); + var topology = frozenPlan(original); + var checkpoint = topology.sourceBinding().freeze(); + var changedCheckpoint = + new CaptureRequest( + checkpoint.targetNamespace(), + checkpoint.canonicalTenantId(), + checkpoint.canonicalVersionId(), + checkpoint.intakeRequestId(), + checkpoint.publicationFence(), + checkpoint.publicationRequestId(), + checkpoint.requestDigest(), + checkpoint.versionStateEpoch(), + checkpoint.publishWorkflowId(), + changeCommit ? UUID.randomUUID().toString() : checkpoint.appliedCommitId(), + changeCommit + ? checkpoint.contentDigest() + : (checkpoint.contentDigest().startsWith("0") ? "1" : "0") + + checkpoint.contentDigest().substring(1), + checkpoint.digestSchemaVersion(), + checkpoint.suppliedOwnedAffectedTuples()); + var descriptorEvidence = + completeEvidence( + original.source().source(), + controlRequest(), + original.versionIdentity().gameDesignVersionId(), + original.versionIdentity().canonicalVersionId(), + VERSION_EPOCH, + "changed-checkpoint-descriptor", + changedCheckpoint.appliedCommitId()); + var evidence = + new CompleteLaunchBindingEvidence( + descriptorEvidence.descriptor(), + releaseWithWorldCheckpoint(descriptorEvidence.releaseAttestation(), changedCheckpoint)); + // This is a complete, digest-valid five-owner pair for the same Version. Pair retention alone + // must not make its different commit or World content eligible for local materialization. + var changedBinding = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + launchBindingRepository.acceptFresh( + NAMESPACE, original.source().receipt(), evidence))); + UUID instance = UUID.randomUUID(); + UUID playableNamespace = UUID.randomUUID(); + var request = requestFor(evidence, instance, UUID.randomUUID()); + var response = + responseFor( + evidence, instance, playableNamespace, request.readRequestId(), "GS_FIXTURE", 1L); + assertThatThrownBy( + () -> + new WorldCanonicalInstancePreparation.Input( + request, response, changedBinding, original.versionIdentity(), topology)) + .isInstanceOf(IllegalArgumentException.class); + + // Deliberately bypass the Java constructor to exercise the database owner's independent gate. + var rawInput = mock(WorldCanonicalInstancePreparation.Input.class); + when(rawInput.gameSessionReadRequest()).thenReturn(request); + when(rawInput.gameSessionReadEvidence()).thenReturn(response); + when(rawInput.completeLaunchBinding()).thenReturn(changedBinding); + when(rawInput.versionIdentity()).thenReturn(original.versionIdentity()); + when(rawInput.topologyPlan()).thenReturn(topology); + String inputJson = WorldCanonicalInstancePreparationRepository.inputJson(rawInput); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + dsl.fetch( + "SELECT * FROM world_prepare_canonical_instance(?, 'sha256:' || encode(sha256(convert_to(?, 'UTF8')), 'hex'))", + inputJson, + inputJson))) + .rootCause() + .hasMessageContaining("release differs from the exact selected frozen World graph"); + assertThat(preparationCount(instance)).isZero(); + assertThat(associationCount(instance)).isZero(); + assertThat( + dsl.fetchOne( + "SELECT id FROM world_instance WHERE canonical_game_instance_id = ?", instance)) + .isNull(); + assertThat( + dsl.fetchOne( + "SELECT id FROM world_instance WHERE canonical_launch_binding_operation_id = ?", + changedBinding.operationId())) + .isNull(); + assertThat( + launchBindingRepository + .read( + NAMESPACE, + changedBinding.canonicalTenantId(), + changedBinding.controlPlaneRequestId()) + .orElseThrow() + .evidence()) + .isEqualTo(evidence); + } + + @Test + void retainsFullCanonicalAssociationAndReadsItAfterTheOwnerCommit() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Result preparation = + prepareCanonicalWorldRow( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); + long worldInstanceId = preparation.association().worldInstanceId(); + assertThat(preparation.storageStatus()).isEqualTo("MATERIALIZED_UNVERIFIED"); + assertThat(preparation.regionCount()).isEqualTo(1); + assertThat(preparation.zoneCount()).isEqualTo(1); + assertThat(preparation.roomCount()).isEqualTo(2); + assertThat(preparation.exitCount()).isEqualTo(1); + WorldCanonicalInstanceAssociation.Claim claim = + claim( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + worldInstanceId, + 1L, + "GS_FIXTURE"); + + ownerTransaction() + .executeWithoutResult(status -> associationRepository.retainClaimInOwnerTransaction(claim)); + + assertThat(associationCount(canonicalGameInstanceId)).isEqualTo(1L); + WorldCanonicalInstanceAssociation stored = + associationRepository.readOwnerAssociation(canonicalGameInstanceId).orElseThrow(); + assertThat(stored.identity()).isEqualTo(claim.identity()); + assertThat(stored.worldInstanceId()).isEqualTo(worldInstanceId); + assertThat(stored.canonicalVersionId()) + .isEqualTo(fixture.binding().evidence().releaseAttestation().canonicalVersionId()); + assertThat(stored.launchBindingOperationId()).isEqualTo(fixture.binding().operationId()); + assertThat(stored.versionIdentityOperationId()) + .isEqualTo(fixture.versionIdentity().operationId()); + assertThat(stored.completeLaunchBinding()).isEqualTo(fixture.binding()); + assertThat(stored.versionIdentity()).isEqualTo(fixture.versionIdentity()); + assertThat(stored.worldPrepareFields().privateTenantKey()) + .isEqualTo(fixture.source().receipt().localTenantKey()); + assertThat(stored.worldPrepareFields().privateGameInstanceKey()).isPositive(); + assertThat(stored.worldPrepareFields().localVersionKey()) + .isEqualTo(fixture.versionIdentity().localVersionKey()); + assertThat(stored.worldPrepareFields().launchDescriptorId()) + .isEqualTo(fixture.binding().descriptor().launchDescriptorId()); + + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT canonical_game_instance_id, canonical_target_namespace, canonical_tenant_id, " + + "canonical_world_slug, playable_state_namespace_id, playable_state_scope, " + + "public_production, " + + "playtest_lifecycle_id, playtest_state_generation, control_plane_request_id, " + + "world_instance_id, local_tenant_key, local_version_key, " + + "canonical_launch_binding_operation_id, version_identity_operation_id, " + + "source_operation_id, source_evidence_digest, descriptor_request_digest, " + + "descriptor_result_digest, release_attestation_digest " + + "FROM world_canonical_instance_association WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId), + "canonical instance association row missing after committed readback"); + assertThat(row.get("canonical_game_instance_id", UUID.class)) + .isEqualTo(canonicalGameInstanceId); + assertThat(row.get("canonical_target_namespace", String.class)).isEqualTo(NAMESPACE); + assertThat(row.get("canonical_tenant_id", UUID.class)) + .isEqualTo(fixture.source().source().canonicalTenantId()); + assertThat(row.get("canonical_world_slug", String.class)) + .isEqualTo(fixture.source().source().worldSlug()); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(playableStateNamespaceId); + assertThat(row.get("playable_state_scope", String.class)).isEqualTo("SHARED"); + assertThat(row.get("public_production", Boolean.class)).isTrue(); + assertThat(row.get("playtest_lifecycle_id", UUID.class)).isNull(); + assertThat(row.get("playtest_state_generation", Long.class)).isNull(); + assertThat(row.get("world_instance_id", Long.class)).isEqualTo(worldInstanceId); + assertThat(row.get("local_tenant_key", Long.class)) + .isEqualTo(fixture.source().receipt().localTenantKey()); + assertThat(row.get("local_version_key", Long.class)) + .isEqualTo(fixture.versionIdentity().localVersionKey()); + assertThat(row.get("canonical_launch_binding_operation_id", UUID.class)) + .isEqualTo(fixture.binding().operationId()); + assertThat(row.get("version_identity_operation_id", UUID.class)) + .isEqualTo(fixture.versionIdentity().operationId()); + assertThat(row.get("source_operation_id", UUID.class)) + .isEqualTo(fixture.source().receipt().sourceOperationId()); + assertThat(row.get("source_evidence_digest", String.class)) + .isEqualTo(fixture.source().receipt().sourceEvidenceDigest()); + assertThat(row.get("descriptor_request_digest", String.class)) + .isEqualTo(fixture.binding().descriptor().requestDigest()); + assertThat(row.get("descriptor_result_digest", String.class)) + .isEqualTo(fixture.binding().descriptor().resultDigest()); + assertThat(row.get("release_attestation_digest", String.class)) + .isEqualTo(fixture.binding().evidence().releaseAttestation().evidenceDigest()); + Record worldRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT public_production FROM world_instance WHERE id = ?", worldInstanceId), + "canonical World instance row missing after committed readback"); + assertThat(worldRow.get("public_production", Boolean.class)).isTrue(); + long privateGameInstanceKey = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT game_instance_id FROM world_instance WHERE id = ?", worldInstanceId), + "canonical World row missing private instance key") + .get("game_instance_id", Long.class); + Record region = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, canonical_region_instance_id, name, weather, generation_seed " + + "FROM region_instance WHERE tenant_id = ? AND game_instance_id = ?", + fixture.source().receipt().localTenantKey(), + privateGameInstanceKey), + "canonical runtime region missing"); + Record zone = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, canonical_zone_instance_id, template_zone_id, region_instance_id, name " + + "FROM zone_instance WHERE tenant_id = ? AND game_instance_id = ?", + fixture.source().receipt().localTenantKey(), + privateGameInstanceKey), + "canonical runtime zone missing"); + Record room = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT ri.id, ri.room_instance_row_id, ri.template_room_id, ri.region_instance_id, " + + "ri.zone_instance_id, ri.name, ri.description " + + "FROM room_instance ri WHERE ri.tenant_id = ? AND ri.game_instance_id = ? " + + "AND ri.name = 'synthetic room'", + fixture.source().receipt().localTenantKey(), + privateGameInstanceKey), + "canonical runtime room missing"); + assertThat(region.get("canonical_region_instance_id", UUID.class)).isNotNull(); + assertThat(zone.get("canonical_zone_instance_id", UUID.class)).isNotNull(); + assertThat(region.get("name", String.class)).isEqualTo("synthetic region"); + assertThat(region.get("weather", String.class)).isEqualTo("rain"); + assertThat(region.get("generation_seed", Long.class)).isEqualTo(9001L); + assertThat(zone.get("name", String.class)).isEqualTo("synthetic zone"); + assertThat(zone.get("region_instance_id", Long.class)).isEqualTo(region.get("id", Long.class)); + assertThat(room.get("name", String.class)).isEqualTo("synthetic room"); + assertThat(room.get("description", String.class)).isEqualTo("synthetic materialization proof"); + assertThat(room.get("region_instance_id", Long.class)).isEqualTo(region.get("id", Long.class)); + assertThat(room.get("zone_instance_id", Long.class)).isEqualTo(zone.get("id", Long.class)); + List roomRows = + dsl.fetch( + "SELECT room_instance_row_id, template_room_id, region_instance_id, zone_instance_id, name " + + "FROM room_instance WHERE tenant_id = ? AND game_instance_id = ? ORDER BY name", + fixture.source().receipt().localTenantKey(), + privateGameInstanceKey); + assertThat(roomRows).hasSize(2); + assertThat(roomRows) + .allSatisfy( + roomRow -> { + assertThat(roomRow.get("region_instance_id", Long.class)) + .isEqualTo(region.get("id", Long.class)); + assertThat(roomRow.get("zone_instance_id", Long.class)) + .isEqualTo(zone.get("id", Long.class)); + }); + assertThat(roomRows) + .extracting(roomRow -> roomRow.get("name", String.class)) + .containsExactly("synthetic destination", "synthetic room"); + Record exit = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, from_room_instance_record_id, to_room_instance_record_id, direction, cost " + + "FROM room_instance_exit WHERE tenant_id = ? AND game_instance_id = ?", + fixture.source().receipt().localTenantKey(), + privateGameInstanceKey), + "canonical runtime room exit missing"); + assertThat(exit.get("from_room_instance_record_id", Long.class)) + .isEqualTo(room.get("room_instance_row_id", Long.class)); + assertThat(exit.get("to_room_instance_record_id", Long.class)) + .isNotEqualTo(exit.get("from_room_instance_record_id", Long.class)); + assertThat(exit.get("direction", String.class)).isEqualTo("EAST"); + assertThat(exit.get("cost", Integer.class)).isEqualTo(3); + var frozenPlan = frozenPlans.get(fixture.versionIdentity().operationId()); + assertThat(region.get("canonical_region_instance_id", UUID.class)) + .isNotEqualTo(frozenPlan.regions().getFirst().identity().templateId()); + assertThat(zone.get("canonical_zone_instance_id", UUID.class)) + .isNotEqualTo(frozenPlan.zones().getFirst().identity().templateId()); + Record regionIdentity = + topologyIdentity( + worldInstanceId, "REGION", frozenPlan.regions().getFirst().identity().templateId()); + Record zoneIdentity = + topologyIdentity( + worldInstanceId, "ZONE", frozenPlan.zones().getFirst().identity().templateId()); + Record roomIdentity = + topologyIdentity( + worldInstanceId, + "ROOM", + frozenPlan.rooms().stream() + .filter(item -> item.content().getName().equals("synthetic room")) + .findFirst() + .orElseThrow() + .identity() + .templateId()); + Record exitIdentity = + topologyIdentity( + worldInstanceId, + "ROOM_EXIT", + frozenPlan.roomExits().getFirst().identity().templateId()); + assertThat(regionIdentity.get("runtime_row_id", Long.class)) + .isEqualTo(region.get("id", Long.class)); + assertThat(regionIdentity.get("runtime_identity", UUID.class)) + .isEqualTo(region.get("canonical_region_instance_id", UUID.class)); + assertThat(zoneIdentity.get("runtime_row_id", Long.class)) + .isEqualTo(zone.get("id", Long.class)); + assertThat(zoneIdentity.get("runtime_identity", UUID.class)) + .isEqualTo(zone.get("canonical_zone_instance_id", UUID.class)); + assertThat(roomIdentity.get("runtime_room_instance_id", Long.class)) + .isEqualTo(room.get("room_instance_row_id", Long.class)); + assertThat(roomIdentity.get("template_private_row_key", Long.class)) + .isEqualTo(room.get("template_room_id", Long.class)); + assertThat(zoneIdentity.get("template_private_row_key", Long.class)) + .isEqualTo(zone.get("template_zone_id", Long.class)); + assertThat(exitIdentity.get("runtime_row_id", Long.class)) + .isEqualTo(exit.get("id", Long.class)); + Record mappedFamilies = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) AS row_count, COUNT(DISTINCT family) AS family_count " + + "FROM world_canonical_instance_topology_identity WHERE world_instance_id = ?", + worldInstanceId), + "canonical source/runtime association rows missing"); + assertThat(mappedFamilies.get("row_count", Long.class)).isEqualTo(5L); + assertThat(mappedFamilies.get("family_count", Long.class)).isEqualTo(4L); + } + + @Test + void exactRetryReusesOriginalAssociationAfterReadMetadataChangeWithoutLifecycleMutation() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Result originalPreparation = + prepareCanonicalWorldRow( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); + long worldInstanceId = originalPreparation.association().worldInstanceId(); + WorldCanonicalInstanceAssociation.Claim originalClaim = + claim( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + worldInstanceId, + 1L, + "GS_FIXTURE"); + ownerTransaction() + .executeWithoutResult( + status -> associationRepository.retainClaimInOwnerTransaction(originalClaim)); + WorldCanonicalInstanceAssociation original = + associationRepository.readOwnerAssociation(canonicalGameInstanceId).orElseThrow(); + + // This is only a fresh, synthetic Game Session observation/read correlation. No World + // lifecycle owner operation is forged; the current guarded lifecycle transition remains a + // separate unimplemented execution path. + WorldCanonicalInstancePreparation.Result changedObservation = + prepareCanonicalWorldRow( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_RETRIED_FIXTURE", 2L); + assertThat(changedObservation.association()).isEqualTo(original); + assertThat(changedObservation.inputDigest()).isEqualTo(originalPreparation.inputDigest()); + WorldCanonicalInstanceAssociation.Claim retry = + claim( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + worldInstanceId, + 2L, + "GS_RETRIED_FIXTURE"); + ownerTransaction() + .executeWithoutResult(status -> associationRepository.retainClaimInOwnerTransaction(retry)); + + assertThat(associationRepository.readOwnerAssociation(canonicalGameInstanceId)) + .contains(original); + assertThat(associationCount(canonicalGameInstanceId)).isEqualTo(1L); + Record runtime = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT status, lifecycle_epoch, row_version FROM world_instance WHERE id = ?", + worldInstanceId), + "World instance row missing after exact retry"); + assertThat(runtime.get("status", String.class)).isEqualTo("PREPARING"); + assertThat(runtime.get("lifecycle_epoch", Long.class)).isEqualTo(1L); + assertThat(runtime.get("row_version", Long.class)).isZero(); + assertThat(retry.gameSessionRead().readRequestId()) + .isNotEqualTo(originalClaim.gameSessionRead().readRequestId()); + assertThat(retry.gameSessionRead().currentGameSessionStatus()).isEqualTo("GS_RETRIED_FIXTURE"); + } + + @Test + void rejectsChangedRequestEchoDescriptorAttestationAndPlayableScopeWithoutMutation() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + long worldInstanceId = + insertCanonicalWorldRow(fixture, canonicalGameInstanceId, playableStateNamespaceId); + WorldCanonicalInstanceAssociation.Claim valid = + claim( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + worldInstanceId, + 1L, + "GS_FIXTURE"); + ownerTransaction() + .executeWithoutResult(status -> associationRepository.retainClaimInOwnerTransaction(valid)); + WorldCanonicalInstanceAssociation originalStored = + associationRepository.readOwnerAssociation(canonicalGameInstanceId).orElseThrow(); + + var originalRequest = valid.gameSessionRequest(); + var response = valid.gameSessionRead(); + var changedRequest = + new WorldCanonicalInstanceAssociation.GameSessionReadRequest( + originalRequest.readRequestId(), + originalRequest.targetNamespace(), + originalRequest.canonicalTenantId(), + originalRequest.worldSlug(), + originalRequest.canonicalGameInstanceId(), + originalRequest.controlPlaneRequestId(), + "substituted-descriptor", + originalRequest.expectedDescriptorRequestDigest(), + originalRequest.expectedDescriptorResultDigest(), + originalRequest.expectedReleaseAttestationEvidenceDigest()); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.Claim( + changedRequest, + response, + worldInstanceId, + fixture.binding(), + fixture.versionIdentity())) + .isInstanceOf(IllegalArgumentException.class); + + CompleteLaunchBindingEvidence changedDescriptor = + completeEvidence( + fixture.source().source(), + fixture.binding().controlPlaneRequestId(), + fixture.versionIdentity().gameDesignVersionId(), + fixture.versionIdentity().canonicalVersionId(), + VERSION_EPOCH, + "substituted-descriptor", + fixture.binding().evidence().releaseAttestation().commitId(), + Objects.requireNonNull( + fixture.binding().evidence().releaseAttestation().worldStartLocationEvidence())); + UUID changedDescriptorReadId = UUID.randomUUID(); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.Claim( + requestFor(changedDescriptor, canonicalGameInstanceId, changedDescriptorReadId), + responseFor( + changedDescriptor, + canonicalGameInstanceId, + playableStateNamespaceId, + changedDescriptorReadId, + "GS_FIXTURE", + 1L), + worldInstanceId, + fixture.binding(), + fixture.versionIdentity())) + .isInstanceOf(IllegalArgumentException.class); + + AuthoredWorldReleaseAttestationEvidence changedAttestation = + attestation( + fixture.binding().descriptor(), + fixture.source().source(), + fixture.versionIdentity().canonicalVersionId(), + fixture.binding().evidence().releaseAttestation().commitId(), + Objects.requireNonNull( + fixture.binding().evidence().releaseAttestation().worldStartLocationEvidence()), + 'e'); + CompleteLaunchBindingEvidence changedPair = + new CompleteLaunchBindingEvidence(fixture.binding().descriptor(), changedAttestation); + UUID changedAttestationReadId = UUID.randomUUID(); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.Claim( + requestFor(changedPair, canonicalGameInstanceId, changedAttestationReadId), + responseFor( + changedPair, + canonicalGameInstanceId, + playableStateNamespaceId, + changedAttestationReadId, + "GS_FIXTURE", + 1L), + worldInstanceId, + fixture.binding(), + fixture.versionIdentity())) + .isInstanceOf(IllegalArgumentException.class); + + var changedScopeResponse = + new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + response.readRequestId(), + response.targetNamespace(), + response.canonicalTenantId(), + response.worldSlug(), + response.canonicalGameInstanceId(), + response.controlPlaneRequestId(), + response.launchDescriptorId(), + response.descriptorRequestDigest(), + response.descriptorResultDigest(), + response.releaseAttestationEvidenceDigest(), + UUID.randomUUID(), + "SHARED", + true, + response.currentGameSessionStatus(), + response.currentGameSessionRowVersion(), + response.descriptor(), + response.releaseAttestation()); + var changedScopeClaim = + new WorldCanonicalInstanceAssociation.Claim( + valid.gameSessionRequest(), + changedScopeResponse, + worldInstanceId, + fixture.binding(), + fixture.versionIdentity()); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + response.readRequestId(), + response.targetNamespace(), + response.canonicalTenantId(), + response.worldSlug(), + response.canonicalGameInstanceId(), + response.controlPlaneRequestId(), + response.launchDescriptorId(), + response.descriptorRequestDigest(), + response.descriptorResultDigest(), + response.releaseAttestationEvidenceDigest(), + response.playableStateNamespaceId(), + "ISOLATED", + true, + response.currentGameSessionStatus(), + response.currentGameSessionRowVersion(), + response.descriptor(), + response.releaseAttestation())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + associationRepository.retainClaimInOwnerTransaction(changedScopeClaim))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class); + + assertThat(associationCount(canonicalGameInstanceId)).isEqualTo(1L); + assertThat(associationRepository.readOwnerAssociation(canonicalGameInstanceId)) + .contains(originalStored); + } + + @Test + void rejectsMissingPublicProductionAndPrivatePlaytestClassificationBeforeMutation() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + // Invalid public-production evidence is rejected before invoking the owner producer. A + // canonical row cannot be fabricated here just to create an association-free fixture. + UUID readRequestId = UUID.randomUUID(); + + assertThatThrownBy( + () -> + responseFor( + fixture.binding().evidence(), + canonicalGameInstanceId, + playableStateNamespaceId, + readRequestId, + "GS_FIXTURE", + 1L, + false)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("explicit public-production evidence"); + + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + readRequestId, + NAMESPACE, + fixture.source().source().canonicalTenantId(), + fixture.source().source().worldSlug(), + canonicalGameInstanceId, + fixture.binding().controlPlaneRequestId(), + fixture.binding().descriptor().launchDescriptorId(), + fixture.binding().descriptor().requestDigest(), + fixture.binding().descriptor().resultDigest(), + fixture.binding().evidence().releaseAttestation().evidenceDigest(), + playableStateNamespaceId, + "ISOLATED", + true, + "GS_FIXTURE", + 1L, + fixture.binding().descriptor(), + fixture.binding().evidence().releaseAttestation())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("accepts SHARED only"); + + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + assertThat(associationRepository.readOwnerAssociation(canonicalGameInstanceId)).isEmpty(); + } + + @Test + void rejectsStructurallyValidPlanFromAnotherFrozenCaptureBeforeAllocation() { + Fixture selected = fixture(); + Fixture substitutedSource = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + var selectedPair = new SeededPair(selected.binding(), selected.versionIdentity()); + var request = request(selectedPair, canonicalGameInstanceId, UUID.randomUUID()); + var response = + responseFor( + selected.binding().evidence(), + canonicalGameInstanceId, + playableStateNamespaceId, + request.readRequestId(), + "GS_FIXTURE", + 1L); + WorldCanonicalInstanceTopologyPlan validOtherCapture = frozenPlan(substitutedSource); + + assertThatThrownBy( + () -> + new WorldCanonicalInstancePreparation.Input( + request, + response, + selected.binding(), + selected.versionIdentity(), + validOtherCapture)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact V27 identity and frozen commit"); + + assertThat(preparationCount(canonicalGameInstanceId)).isZero(); + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + assertThat( + dsl.fetchOne( + "SELECT id FROM world_instance WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId)) + .isNull(); + } + + @Test + void rejectsDifferentBindingTenantVersionAndPrivateWorldRowWithoutMutation() { + Fixture original = fixture(); + UUID originalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + long originalWorldInstanceId = + insertCanonicalWorldRow(original, originalGameInstanceId, playableStateNamespaceId); + WorldCanonicalInstanceAssociation.Claim originalClaim = + claim( + original, + originalGameInstanceId, + playableStateNamespaceId, + originalWorldInstanceId, + 1L, + "GS_FIXTURE"); + ownerTransaction() + .executeWithoutResult( + status -> associationRepository.retainClaimInOwnerTransaction(originalClaim)); + + SeededPair secondBinding = + seedPair( + original.source(), + original.versionIdentity(), + controlRequest(), + "synthetic-second-binding"); + Fixture changedBindingFixture = + new Fixture(original.source(), secondBinding.binding(), secondBinding.versionIdentity()); + assertThatThrownBy( + () -> + prepareCanonicalWorldRow( + changedBindingFixture, + originalGameInstanceId, + playableStateNamespaceId, + "GS_FIXTURE", + 1L)) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class); + WorldCanonicalInstanceAssociation.Claim changedBindingClaim = + claim( + secondBinding, + originalGameInstanceId, + playableStateNamespaceId, + originalWorldInstanceId, + 1L, + "GS_FIXTURE"); + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + associationRepository.retainClaimInOwnerTransaction( + changedBindingClaim))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class); + + SeededPair otherVersion = + seedPair( + original.source(), + null, + controlRequest(), + "synthetic-version-descriptor", + UUID.randomUUID(), + positiveLong()); + UUID otherGameInstanceId = UUID.randomUUID(); + UUID otherPlayableNamespaceId = UUID.randomUUID(); + long otherWorldInstanceId = + insertCanonicalWorldRow( + otherVersion, original.source(), otherGameInstanceId, otherPlayableNamespaceId); + assertThat(otherWorldInstanceId).isNotEqualTo(originalWorldInstanceId); + assertThat(dsl.fetchOne("SELECT id FROM world_instance WHERE id = ?", otherWorldInstanceId)) + .isNotNull(); + UUID wrongVersionReadId = UUID.randomUUID(); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.Claim( + request(otherVersion, otherGameInstanceId, wrongVersionReadId), + responseFor( + otherVersion.binding().evidence(), + otherGameInstanceId, + otherPlayableNamespaceId, + wrongVersionReadId, + "GS_FIXTURE", + 1L), + otherWorldInstanceId, + otherVersion.binding(), + original.versionIdentity())) + .isInstanceOf(IllegalArgumentException.class); + + WorldCanonicalInstanceAssociation.Claim wrongPrivateWorldRow = + claim( + original, + originalGameInstanceId, + playableStateNamespaceId, + otherWorldInstanceId, + 1L, + "GS_FIXTURE"); + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + associationRepository.retainClaimInOwnerTransaction( + wrongPrivateWorldRow))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class); + + Fixture otherTenant = fixture(); + UUID otherTenantGameInstanceId = UUID.randomUUID(); + WorldCanonicalInstanceAssociation.Claim wrongTenant = + claim( + otherTenant, + otherTenantGameInstanceId, + UUID.randomUUID(), + originalWorldInstanceId, + 1L, + "GS_FIXTURE"); + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> associationRepository.retainClaimInOwnerTransaction(wrongTenant))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class); + + assertThat(associationCount(originalGameInstanceId)).isEqualTo(1L); + assertThat(associationRepository.readOwnerAssociation(originalGameInstanceId)).isPresent(); + assertThat(associationRepository.readOwnerAssociation(otherGameInstanceId)) + .hasValueSatisfying( + association -> + assertThat(association.worldInstanceId()).isEqualTo(otherWorldInstanceId)); + assertThat(associationRepository.readOwnerAssociation(otherTenantGameInstanceId)).isEmpty(); + } + + @Test + void deniesLegacyNumericRowAndRejectsUpdatingItToCanonicalIdentity() throws SQLException { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + long legacyGameInstanceKey = positiveLong(); + long legacyWorldInstanceId = insertLegacyWorldRow(fixture, legacyGameInstanceKey); + WorldCanonicalInstanceAssociation.Claim legacyClaim = + claim( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + legacyWorldInstanceId, + 1L, + "GS_FIXTURE"); + + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> associationRepository.retainClaimInOwnerTransaction(legacyClaim))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class) + .hasMessageContaining("retained numeric rows cannot be associated"); + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET public_production = TRUE, canonical_game_instance_id = ?, " + + "canonical_target_namespace = ?, canonical_tenant_id = ?, " + + "canonical_world_slug = ?, playable_state_namespace_id = ?, " + + "playable_state_scope = 'SHARED', canonical_launch_binding_operation_id = ? " + + "WHERE id = ?", + canonicalGameInstanceId, + NAMESPACE, + fixture.source().source().canonicalTenantId(), + fixture.source().source().worldSlug(), + playableStateNamespaceId, + fixture.binding().operationId(), + legacyWorldInstanceId)) + .isInstanceOf(DataAccessException.class); + Record legacy = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_id, game_instance_id, version_id, public_production, canonical_game_instance_id, " + + "canonical_tenant_id FROM world_instance WHERE id = ?", + legacyWorldInstanceId), + "legacy World row missing after rejected association attempt"); + assertThat(legacy.get("tenant_id", Long.class)) + .isNotEqualTo(fixture.source().receipt().localTenantKey()); + assertThat(legacy.get("game_instance_id", Long.class)).isEqualTo(legacyGameInstanceKey); + assertThat(legacy.get("version_id", Long.class)) + .isEqualTo(fixture.versionIdentity().localVersionKey()); + assertThat(legacy.get("public_production", Boolean.class)).isNull(); + assertThat(legacy.get("canonical_game_instance_id", UUID.class)).isNull(); + assertThat(legacy.get("canonical_tenant_id", UUID.class)).isNull(); + assertThat(associationRepository.readOwnerAssociation(canonicalGameInstanceId)).isEmpty(); + } + + @Test + void rollsBackCompletePreparationWhenHeldCommitAuthorityIsLostBeforeCommit() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Input input = + preparationInput( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); + AtomicInteger heldChecks = new AtomicInteger(); + WorldCanonicalInstancePreparationService service = + preparationService( + () -> { + if (heldChecks.incrementAndGet() == 3) { + throw new IllegalStateException("synthetic held authority lost before commit"); + } + }); + + assertThatThrownBy(() -> service.prepare(input)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synthetic held authority lost before commit"); + + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + assertThat(associationRepository.readOwnerAssociation(canonicalGameInstanceId)).isEmpty(); + assertThat(preparationCount(canonicalGameInstanceId)).isZero(); + assertThat( + dsl.fetchOne( + "SELECT id FROM world_instance WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId)) + .isNull(); + } + + @Test + void concurrentExactPreparationsForTheSameCanonicalGameInstanceRetainOneOwnerResult() + throws Exception { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Input exactInput = + preparationInput( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); + WorldCanonicalInstancePreparationService firstService = preparationService(() -> {}); + WorldCanonicalInstancePreparationService secondService = preparationService(() -> {}); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future first = + executor.submit( + () -> { + ready.countDown(); + await(start); + return firstService.prepare(exactInput); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + await(start); + return secondService.prepare(exactInput); + }); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + WorldCanonicalInstancePreparation.Result firstResult = first.get(25, TimeUnit.SECONDS); + WorldCanonicalInstancePreparation.Result secondResult = second.get(25, TimeUnit.SECONDS); + assertThat(firstResult.association().worldInstanceId()) + .isEqualTo(secondResult.association().worldInstanceId()); + assertThat(firstResult.inputDigest()).isEqualTo(secondResult.inputDigest()); + } + + assertThat(associationCount(canonicalGameInstanceId)).isEqualTo(1L); + assertThat(preparationCount(canonicalGameInstanceId)).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_instance WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId), + "Canonical World row count returned no result") + .get(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void forwardV32MigrationPreservesLegacyRowsWithoutInventingCanonicalMapping() + throws SQLException { + String schema = "world_canonical_instance_v32_" + UUID.randomUUID().toString().replace("-", ""); + long tenantKey = + 8_100_000_000L + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 100_000L); + long gameInstanceKey = positiveLong(); + long worldInstanceId; + try { + migrateFixture(schema, MigrationVersion.fromVersion("32")); + try (Connection connection = fixtureConnection(schema); + PreparedStatement insert = + connection.prepareStatement( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, " + + "generation_config_revision, release_bundle_id, published_release_bundle_ref, " + + "version_state_epoch, status) VALUES (?, ?, 71, 'retained-v32-request', " + + "'retained-v32-descriptor', 83, 'retained-v32-config', 97, " + + "'retained-v32-release', 5, 'LEGACY_FIXTURE') RETURNING id")) { + insert.setLong(1, tenantKey); + insert.setLong(2, gameInstanceKey); + try (ResultSet result = insert.executeQuery()) { + assertThat(result.next()).isTrue(); + worldInstanceId = result.getLong(1); + } + } + + migrateFixture(schema, null); + + try (Connection connection = fixtureConnection(schema)) { + try (PreparedStatement query = + connection.prepareStatement( + "SELECT tenant_id, game_instance_id, version_id, status, public_production, " + + "canonical_game_instance_id, canonical_target_namespace, canonical_tenant_id, " + + "canonical_world_slug, playable_state_namespace_id, playable_state_scope, " + + "playtest_lifecycle_id, playtest_state_generation, " + + "canonical_launch_binding_operation_id FROM world_instance WHERE id = ?")) { + query.setLong(1, worldInstanceId); + try (ResultSet retained = query.executeQuery()) { + assertThat(retained.next()).isTrue(); + assertThat(retained.getLong("tenant_id")).isEqualTo(tenantKey); + assertThat(retained.getLong("game_instance_id")).isEqualTo(gameInstanceKey); + assertThat(retained.getLong("version_id")).isEqualTo(83L); + assertThat(retained.getString("status")).isEqualTo("LEGACY_FIXTURE"); + assertThat(retained.getObject("public_production")).isNull(); + assertThat(retained.getObject("canonical_game_instance_id")).isNull(); + assertThat(retained.getString("canonical_target_namespace")).isNull(); + assertThat(retained.getObject("canonical_tenant_id")).isNull(); + assertThat(retained.getString("canonical_world_slug")).isNull(); + assertThat(retained.getObject("playable_state_namespace_id")).isNull(); + assertThat(retained.getString("playable_state_scope")).isNull(); + assertThat(retained.getObject("playtest_lifecycle_id")).isNull(); + assertThat(retained.getObject("playtest_state_generation")).isNull(); + assertThat(retained.getObject("canonical_launch_binding_operation_id")).isNull(); + assertThat(retained.next()).isFalse(); + } + } + try (Statement statement = connection.createStatement(); + ResultSet associations = + statement.executeQuery( + "SELECT COUNT(*) FROM world_canonical_instance_association")) { + assertThat(associations.next()).isTrue(); + assertThat(associations.getLong(1)).isZero(); + } + + UUID attemptedGameInstanceId = UUID.randomUUID(); + UUID attemptedTenantId = UUID.randomUUID(); + UUID attemptedPlayableNamespaceId = UUID.randomUUID(); + UUID attemptedBindingId = UUID.randomUUID(); + assertThatThrownBy( + () -> { + try (PreparedStatement update = + connection.prepareStatement( + "UPDATE world_instance SET public_production = TRUE, canonical_game_instance_id = ?, " + + "canonical_target_namespace = 'firemud', canonical_tenant_id = ?, " + + "canonical_world_slug = 'retained-v32-world', " + + "playable_state_namespace_id = ?, playable_state_scope = 'SHARED', " + + "canonical_launch_binding_operation_id = ? WHERE id = ?")) { + update.setObject(1, attemptedGameInstanceId); + update.setObject(2, attemptedTenantId); + update.setObject(3, attemptedPlayableNamespaceId); + update.setObject(4, attemptedBindingId); + update.setLong(5, worldInstanceId); + update.executeUpdate(); + } + }) + .isInstanceOf(SQLException.class); + } + + try (Connection connection = fixtureConnection(schema); + Statement statement = connection.createStatement(); + ResultSet count = + statement.executeQuery("SELECT COUNT(*) FROM world_canonical_instance_association")) { + assertThat(count.next()).isTrue(); + assertThat(count.getLong(1)).isZero(); + } + } finally { + dropFixtureSchema(schema); + } + } + + private Fixture fixture() { + SourceFixture source = sourceFixture(); + UUID canonicalVersionId = UUID.randomUUID(); + long gameDesignVersionId = positiveLong(); + WorldAuthoredVersionIdentityReceipt identity = + seedVersionIdentity(source, canonicalVersionId, gameDesignVersionId, VERSION_EPOCH); + SeededPair pair = seedPair(source, identity, controlRequest(), "synthetic-launch-descriptor"); + Fixture fixture = new Fixture(source, pair.binding(), pair.versionIdentity()); + // Build and retain the original v2 publication terminal through World owner storage. Upstream + // Account and Game Design authority in this component fixture remains explicitly stipulated; + // STARTING is only the canonical storage-only Game Session observation carried by this input. + preparationInput(fixture, UUID.randomUUID(), UUID.randomUUID(), "STARTING", 1L); + return fixture; + } + + private SourceFixture sourceFixture() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID(), randomWorld()); + WorldAuthoredSourceIntakeReceipt receipt = + ownerTransaction() + .execute(status -> sourceRepository.acceptFresh(NAMESPACE, UUID.randomUUID(), source)); + return new SourceFixture( + source, Objects.requireNonNull(receipt, "source intake returned no receipt")); + } + + private SeededPair seedPair( + SourceFixture source, + WorldAuthoredVersionIdentityReceipt identity, + String controlPlaneRequestId, + String launchDescriptorId) { + return seedPair( + source, + identity, + controlPlaneRequestId, + launchDescriptorId, + identity.canonicalVersionId(), + identity.gameDesignVersionId()); + } + + private SeededPair seedPair( + SourceFixture source, + WorldAuthoredVersionIdentityReceipt identity, + String controlPlaneRequestId, + String launchDescriptorId, + UUID canonicalVersionId, + long gameDesignVersionId) { + WorldAuthoredVersionIdentityReceipt resolvedIdentity = + identity == null + ? seedVersionIdentity(source, canonicalVersionId, gameDesignVersionId, VERSION_EPOCH) + : identity; + // The source and Account authority remain synthetic, but the graph, frozen selector and + // immutable PUBLISHED terminal are written/read through the actual World owner stores. + Fixture sourceFixture = new Fixture(source, null, resolvedIdentity); + var frozen = frozenPlan(sourceFixture); + var checkpoint = frozen.sourceBinding().freeze(); + var selector = + publishedEvidence( + publishedSelectors() + .readCommitted(checkpoint) + .orElseThrow( + () -> + new IllegalStateException( + "Synthetic APPLIED-v2 selector was not retained"))); + CompleteLaunchBindingEvidence evidence = + completeEvidence( + source.source(), + controlPlaneRequestId, + gameDesignVersionId, + canonicalVersionId, + VERSION_EPOCH, + launchDescriptorId, + checkpoint.appliedCommitId(), + selector); + evidence = + new CompleteLaunchBindingEvidence( + evidence.descriptor(), + releaseWithWorldCheckpoint(evidence.releaseAttestation(), checkpoint)); + CompleteLaunchBindingEvidence exactEvidence = evidence; + WorldCompleteLaunchBindingReceipt binding = + ownerTransaction() + .execute( + status -> + launchBindingRepository.acceptFresh( + NAMESPACE, source.receipt(), exactEvidence)); + return new SeededPair( + Objects.requireNonNull(binding, "launch binding returned no receipt"), resolvedIdentity); + } + + private WorldAuthoredVersionIdentityReceipt seedVersionIdentity( + SourceFixture source, UUID canonicalVersionId, long gameDesignVersionId, long epoch) { + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + source.source().canonicalTenantId(), + source.source().worldSlug(), + source.source().operationId(), + source.source().evidenceDigest(), + gameDesignVersionId); + AuthoredWorldVersionStateEvidence evidence = + AuthoredWorldVersionStateEvidence.create( + request, + source.source(), + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + epoch); + return Objects.requireNonNull( + ownerTransaction() + .execute(status -> versionIdentityRepository.acceptFresh(source.receipt(), evidence)), + "Version identity returned no receipt"); + } + + private long insertCanonicalWorldRow( + Fixture fixture, UUID canonicalGameInstanceId, UUID playableStateNamespaceId) { + return prepareCanonicalWorldRow( + fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L) + .association() + .worldInstanceId(); + } + + private long insertCanonicalWorldRow( + SeededPair pair, + SourceFixture source, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId) { + Fixture fixture = new Fixture(source, pair.binding(), pair.versionIdentity()); + return insertCanonicalWorldRow(fixture, canonicalGameInstanceId, playableStateNamespaceId); + } + + private WorldCanonicalInstancePreparation.Result prepareCanonicalWorldRow( + Fixture fixture, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String observedGameSessionStatus, + long observedGameSessionRowVersion) { + return preparationService(() -> {}) + .prepare( + preparationInput( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + observedGameSessionStatus, + observedGameSessionRowVersion)); + } + + private WorldCanonicalInstancePreparation.Input preparationInput( + Fixture fixture, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + String observedGameSessionStatus, + long observedGameSessionRowVersion) { + var request = + request( + new SeededPair(fixture.binding(), fixture.versionIdentity()), + canonicalGameInstanceId, + UUID.randomUUID()); + var response = + responseFor( + fixture.binding().evidence(), + canonicalGameInstanceId, + playableStateNamespaceId, + request.readRequestId(), + observedGameSessionStatus, + observedGameSessionRowVersion); + WorldCanonicalInstancePreparation.Input input = + new WorldCanonicalInstancePreparation.Input( + request, response, fixture.binding(), fixture.versionIdentity(), frozenPlan(fixture)); + completeIsolatedPublicationTerminal(input); + return input; + } + + private WorldCanonicalInstancePreparationService preparationService(Runnable heldCheck) { + WorldCanonicalFrozenTopologyRepository frozenRepository = + new WorldCanonicalFrozenTopologyRepository( + dsl, + graphSnapshots, + new WorldDraftTopologyCommitRepository(dsl, publicationFence, objectMapper), + digestService); + WorldCanonicalInstancePreparationRepository preparationRepository = + new WorldCanonicalInstancePreparationRepository( + dsl, transactionManager, associationRepository, frozenRepository); + // Synthetic fixture handle only. This does not authenticate GS/GD source or delivery, prove + // APPLIED/IN_SYNC, or supply Account authority. + return new WorldCanonicalInstancePreparationService( + preparationRepository, + input -> + new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + @Override + public void requireHeld() { + heldCheck.run(); + } + + @Override + public void close() {} + }); + } + + private WorldCanonicalInstanceTopologyPlan frozenPlan(Fixture fixture) { + return frozenPlans.computeIfAbsent( + fixture.versionIdentity().operationId(), + ignored -> { + WorldDraftTopologyCommitPlan draft = topologyPlan(fixture); + appliedComponent().apply(draftApplication(draft)); + var owner = draft.ownerBinding(); + String publicationRequest = "preparation-capture-" + UUID.randomUUID(); + // V27/release evidence retains the post-publication epoch; the original Draft freeze + // selection is exactly the preceding epoch. + long freezeEpoch = + Math.subtractExact( + fixture.versionIdentity().versionStateEvidence().versionStateEpoch(), 1L); + String requestDigest = + publicationSelection(draft, publicationRequest, freezeEpoch) + .digest() + .substring("sha256:".length()); + WorldDesignPublicationFenceEvidence evidence = + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + publicationRequest, + requestDigest, + freezeEpoch, + "publish:" + + owner.canonicalTenantId() + + ":publish-request:" + + publicationRequest); + var attempt = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + publicationFence.claimFreeze( + evidence, + () -> { + var digest = + digestService.getDraftDesignDigest( + Long.toString( + fixture.source().receipt().localTenantKey()), + Long.toString( + fixture.versionIdentity().localVersionKey())); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + draft.binding().commitId().toString(), + digest.contentDigest(), + 3); + })), + "Synthetic frozen preparation fixture returned no publication checkpoint"); + List tuples = + draft.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + CaptureRequest captureRequest = + new CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + attempt.publicationFence(), + publicationRequest, + evidence.requestDigest(), + evidence.versionStateEpoch(), + evidence.publishWorkflowId(), + attempt.checkpoint().appliedCommitId(), + attempt.checkpoint().contentDigest(), + attempt.checkpoint().digestSchemaVersion(), + tuples); + WorldCanonicalFrozenTopology frozen = + new WorldCanonicalFrozenTopologyService(frozenRepository(), transactionManager) + .capture(new WorldCanonicalFrozenTopology.Request(draft, captureRequest)); + return WorldCanonicalInstanceTopologyPlan.create(frozen); + }); + } + + private WorldDraftGraphApplicationRepository appliedRepository() { + return new WorldDraftGraphApplicationRepository(dsl, publicationFence, objectMapper); + } + + private WorldDraftGraphApplicationService appliedComponent() { + return new WorldDraftGraphApplicationService( + appliedRepository(), + transactionManager, + operation -> { + // Explicitly isolated Account COMMIT_ORDER authority; this is not producer proof. + return new WorldDraftGraphApplicationService.CommitOrderProof(operation); + }); + } + + private WorldDraftGraphApplication draftApplication(WorldDraftTopologyCommitPlan plan) { + var binding = plan.binding(); + var account = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + binding.requestId(), + binding.commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.baseCommitId(), + "0", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.TENANT, + binding.target().canonicalTenantId().toString(), + null, + "1", + null, + null, + new byte[] {1, 2, 3}))); + var operation = + new WorldDraftTerminalOperation( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId(), + binding, + plan.ownerBinding(), + account.canonicalBytes()); + return new WorldDraftGraphApplication(operation, plan); + } + + private WorldCanonicalFrozenTopologyRepository frozenRepository() { + return new WorldCanonicalFrozenTopologyRepository( + dsl, + graphSnapshots, + new WorldDraftTopologyCommitRepository(dsl, publicationFence, objectMapper), + digestService); + } + + private WorldPublishedStartLocationRepository publishedSelectors() { + return new WorldPublishedStartLocationRepository(dsl, frozenRepository(), appliedRepository()); + } + + private WorldPublishedStartLocationEvidence publishedEvidence( + WorldPublishedStartLocationSource source) { + var freeze = source.frozenTopology().request().freeze(); + return new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + freeze.targetNamespace(), + freeze.canonicalTenantId(), + freeze.canonicalVersionId(), + freeze.intakeRequestId(), + freeze.publicationFence(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + freeze.contentDigest(), + freeze.digestSchemaVersion(), + freeze.suppliedOwnedAffectedTuples().stream() + .map( + tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()), + source.selectorReceipt().canonicalBytes(), + source.appliedResult().application().operation().accountBindingBytes(), + source.appliedResult().canonicalBytes()); + } + + private AuthoredDraftPublishSelectionBinding publicationSelection( + WorldDraftTopologyCommitPlan plan, String publicationRequest, long freezeEpoch) { + var binding = plan.binding(); + var intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + publicationRequest, + Long.toString(freezeEpoch), + "isolated-association-publication-fixture", + binding.requestId(), + binding.commitId(), + binding.digest()); + return AuthoredDraftPublishSelectionBinding.capture( + intent, + binding.target(), + binding, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.digest(), + "[]", + OffsetDateTime.parse("2026-01-01T00:00:00Z"))); + } + + private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( + WorldCanonicalInstancePreparation.Input input) { + var release = input.completeLaunchBinding().evidence().releaseAttestation(); + var world = Objects.requireNonNull(release.worldStartLocationEvidence()); + if (release.versionStateEpoch() != Math.addExact(world.request().versionStateEpoch(), 1L)) { + throw new IllegalStateException( + "Isolated PUBLISHED terminal must retain the next publication epoch after its World freeze"); + } + var originalAccount = + DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()); + var selection = + publicationSelection( + input.topologyPlan().sourceBinding().plan(), + world.request().publicationRequestId(), + world.request().versionStateEpoch()); + if (!selection.digest().equals("sha256:" + world.request().requestDigest())) { + throw new IllegalStateException( + "Isolated publication selection differs from the retained World request digest"); + } + var account = + new AccountPublicationAuthorizationBinding( + UUID.nameUUIDFromBytes( + (world.request().publicationFence() + "/account-operation") + .getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + (world.request().publicationFence() + "/account-fence") + .getBytes(StandardCharsets.UTF_8)), + new AccountPublicationAuthorizationBinding.PreallocationInput( + originalAccount.actorAccountId(), selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + originalAccount.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var operation = new GameDesignPublicationOperationBinding(account, world); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + Outcome.PUBLISHED, + isolatedReleaseContent(input), + release.versionStateEpoch()); + } + + private ReleaseContent isolatedReleaseContent(WorldCanonicalInstancePreparation.Input input) { + var release = input.completeLaunchBinding().evidence().releaseAttestation(); + var world = Objects.requireNonNull(release.worldStartLocationEvidence()); + var participants = + release.participantDigests().stream() + .map( + participant -> + new Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent() ? participant.baseVersionId() : null, + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent() + ? participant.abilitySchemaDigest() + : null, + null, + null)) + .toList(); + return new ReleaseContent( + release.canonicalTenantId(), + release.canonicalVersionId(), + release.publishedReleaseBundleRef(), + 1, + "v2", + release.publishWorkflowId(), + release.manifestHash(), + release.manifestSchemaVersion(), + release.artifactDigests(), + release.requiredManifestAssetKeys(), + participants, + release.commandDefinitions(), + release.generationConfigRevision(), + world); + } + + private void completeIsolatedPublicationTerminal(WorldCanonicalInstancePreparation.Input input) { + var evidence = isolatedTerminalEvidence(input); + GameDesignPublicationTerminalEvidence retained = + publicationTerminalComponent(evidence) + .complete(evidence.operationBytes(), evidence.canonicalBytes()); + if (!Arrays.equals(evidence.canonicalBytes(), retained.canonicalBytes())) { + throw new IllegalStateException( + "Isolated World terminal readback differs from original PUBLISHED v2 evidence"); + } + } + + private WorldPublicationTerminalService publicationTerminalComponent( + GameDesignPublicationTerminalEvidence evidence) { + byte[] operationBytes = evidence.operationBytes(); + return new WorldPublicationTerminalService( + new WorldPublicationTerminalRepository(dsl, transactionManager), + (suppliedOperation, terminalBytes) -> { + GameDesignPublicationTerminalEvidence upstream = + GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + if (!Arrays.equals(operationBytes, suppliedOperation) + || !Arrays.equals(upstream.operationBytes(), suppliedOperation)) { + throw new IllegalArgumentException("isolated terminal operation mismatch"); + } + return new WorldPublicationTerminalService.VerifiedTerminal( + WorldPublicationTerminal.Request.fromStored(terminalBytes), + new WorldPublicationTerminalService.HeldTerminalAuthority() { + public void requireHeld() {} + + public void close() {} + }); + }); + } + + private WorldDraftTopologyCommitPlan topologyPlan(Fixture fixture) { + UUID commitId = UUID.randomUUID(); + UUID regionId = UUID.randomUUID(); + UUID zoneId = UUID.randomUUID(); + UUID roomId = UUID.randomUUID(); + UUID destinationRoomId = UUID.randomUUID(); + UUID entityId = UUID.randomUUID(); + List mutations = + new ArrayList<>( + List.of( + mutation( + commitId, + regionId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + regionId) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("synthetic region") + .setWeather("rain") + .setShardId(7) + .setGenerationSeed(9001) + .setGeneratorType("synthetic") + .setGeneratorParams("{}")) + .build(), + mutation( + commitId, + zoneId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + regionId) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("synthetic zone") + .setRegionId(regionId.toString())) + .build(), + mutation( + commitId, + destinationRoomId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + regionId) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("synthetic destination") + .setZoneId(zoneId.toString()) + .setDescription("synthetic destination room")) + .build(), + mutation( + commitId, + roomId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + regionId) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("synthetic room") + .setZoneId(zoneId.toString()) + .setDescription("synthetic materialization proof")) + .build(), + mutation( + commitId, + UUID.randomUUID(), + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + regionId) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(roomId.toString()) + .setToRoomId(destinationRoomId.toString()) + .setDirection("EAST") + .setCost(3)) + .build())); + WorldFreshGraphDeclaration declaration = + WorldFreshGraphDeclaration.newBuilder() + .setTenantId(fixture.versionIdentity().canonicalTenantId().toString()) + .setVersionId(fixture.versionIdentity().canonicalVersionId().toString()) + .setStartLocation( + RoomTemplateRef.newBuilder() + .setTenantId(fixture.versionIdentity().canonicalTenantId().toString()) + .setVersionId(fixture.versionIdentity().canonicalVersionId().toString()) + .setRoomTemplateId(roomId.toString())) + .addFamilyCounts( + familyCount(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION)) + .addFamilyCounts( + familyCount(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE)) + .addFamilyCounts( + familyCount(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM)) + .addFamilyCounts( + familyCount( + mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT)) + .addFamilyCounts( + familyCount( + mutations, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE)) + .addFamilyCounts( + familyCount( + mutations, + WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) + .build(); + mutations.set( + 0, mutations.getFirst().toBuilder().setFreshGraphDeclaration(declaration).build()); + List revisions = new java.util.ArrayList<>(); + List units = new java.util.ArrayList<>(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.ENTITY_MANAGEMENT, "isolated Entity fixture evidence")); + units.add( + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "NPC", + entityId.toString(), + "AGGREGATE", + entityId.toString(), + "0")); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "1", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + "isolated Game Design control-plane fixture evidence")); + units.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "VERSION", + fixture.versionIdentity().canonicalVersionId().toString(), + "AGGREGATE", + fixture.versionIdentity().canonicalVersionId().toString(), + "0")); + for (WorldDesignMutationRevision mutation : mutations) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(mutation.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + json(mutation))); + String family = + mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "AGGREGATE", + mutation.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "REGION_SUBTREE", + mutation.getScopeId(), + "0")); + } + var source = fixture.source().source(); + var owner = + new OwnerBinding( + NAMESPACE, + source.canonicalTenantId(), + fixture.versionIdentity().canonicalVersionId(), + fixture.versionIdentity().operationId(), + fixture.versionIdentity().gameDesignVersionId(), + fixture.source().receipt().intakeRequestId(), + fixture.source().receipt().operationId(), + fixture.source().receipt().requestDigest(), + source.operationId(), + source.evidenceDigest(), + fixture.source().receipt().receiptDigest()); + var target = + new DraftCommitBinding.TargetProof( + source.canonicalTenantId(), + fixture.versionIdentity().canonicalVersionId(), + fixture.versionIdentity().gameDesignVersionId(), + source.sourceGameTenantKey(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + return WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + target, UUID.randomUUID(), commitId, "synthetic-base-commit", revisions, units), + owner); + } + + private static WorldFreshGraphFamilyCount familyCount( + List mutations, WorldDesignAggregateType family) { + int count = + (int) mutations.stream().filter(mutation -> mutation.getAggregateType() == family).count(); + return WorldFreshGraphFamilyCount.newBuilder().setFamily(family).setCount(count).build(); + } + + private static WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID aggregateId, WorldDesignAggregateType type, UUID containingRegionId) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(aggregateId.toString()) + .setAggregateType(type) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(containingRegionId.toString()); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new AssertionError(exception); + } + } + + private long preparationCount(UUID canonicalGameInstanceId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_canonical_instance_preparation " + + "WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId), + "World preparation count query returned no row") + .get(0, Long.class); + } + + private Record topologyIdentity(long worldInstanceId, String family, UUID templateId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT template_id, template_private_row_key, runtime_row_id, runtime_identity, " + + "runtime_room_instance_id FROM world_canonical_instance_topology_identity " + + "WHERE world_instance_id = ? AND family = ? AND template_id = ?", + worldInstanceId, + family, + templateId), + "canonical source/runtime identity mapping missing for " + + family + + " template " + + templateId); + } + + private long insertLegacyWorldRow(Fixture fixture, long gameInstanceKey) { + var descriptor = fixture.binding().descriptor(); + Record inserted = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, script_patch_version, " + + "runtime_flags_json, generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, remap_set_id, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'LEGACY_FIXTURE') RETURNING id", + 8_100_000_000L + + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), 100_000L), + gameInstanceKey, + descriptor.gameTemplateId(), + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + fixture.versionIdentity().localVersionKey(), + descriptor.scriptPatchVersionPresent() ? descriptor.scriptPatchVersion() : null, + descriptor.runtimeFlagsJson(), + descriptor.generationConfigRevision(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + descriptor.remapSetIdPresent() ? descriptor.remapSetId() : null), + "legacy World row insert returned no row"); + return inserted.get("id", Long.class); + } + + private WorldCanonicalInstanceAssociation.Claim claim( + Fixture fixture, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + long worldInstanceId, + long rowVersion, + String status) { + return claim( + new SeededPair(fixture.binding(), fixture.versionIdentity()), + canonicalGameInstanceId, + playableStateNamespaceId, + worldInstanceId, + rowVersion, + status); + } + + private WorldCanonicalInstanceAssociation.Claim claim( + SeededPair pair, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + long worldInstanceId, + long rowVersion, + String status) { + WorldCanonicalInstanceAssociation.GameSessionReadRequest request = + request(pair, canonicalGameInstanceId, UUID.randomUUID()); + WorldCanonicalInstanceAssociation.GameSessionReadEvidence response = + responseFor( + pair.binding().evidence(), + canonicalGameInstanceId, + playableStateNamespaceId, + request.readRequestId(), + status, + rowVersion); + return new WorldCanonicalInstanceAssociation.Claim( + request, response, worldInstanceId, pair.binding(), pair.versionIdentity()); + } + + private WorldCanonicalInstanceAssociation.GameSessionReadRequest request( + SeededPair pair, UUID canonicalGameInstanceId, UUID readRequestId) { + return requestFor(pair.binding().evidence(), canonicalGameInstanceId, readRequestId); + } + + private WorldCanonicalInstanceAssociation.GameSessionReadRequest requestFor( + CompleteLaunchBindingEvidence evidence, UUID canonicalGameInstanceId, UUID readRequestId) { + var descriptor = evidence.descriptor(); + var release = evidence.releaseAttestation(); + return new WorldCanonicalInstanceAssociation.GameSessionReadRequest( + readRequestId, + NAMESPACE, + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + canonicalGameInstanceId, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + } + + private WorldCanonicalInstanceAssociation.GameSessionReadEvidence responseFor( + CompleteLaunchBindingEvidence evidence, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + UUID readRequestId, + String status, + long rowVersion) { + return responseFor( + evidence, + canonicalGameInstanceId, + playableStateNamespaceId, + readRequestId, + status, + rowVersion, + true); + } + + private WorldCanonicalInstanceAssociation.GameSessionReadEvidence responseFor( + CompleteLaunchBindingEvidence evidence, + UUID canonicalGameInstanceId, + UUID playableStateNamespaceId, + UUID readRequestId, + String status, + long rowVersion, + boolean publicProduction) { + var descriptor = evidence.descriptor(); + var release = evidence.releaseAttestation(); + return new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + readRequestId, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + canonicalGameInstanceId, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest(), + playableStateNamespaceId, + "SHARED", + publicProduction, + status, + rowVersion, + descriptor, + release); + } + + private long associationCount(UUID canonicalGameInstanceId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId), + "World canonical association count query returned no row") + .get(0, Long.class); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private static CompleteLaunchBindingEvidence completeEvidence( + AuthoredWorldSourceEvidence source, + String controlPlaneRequestId, + long gameDesignVersionId, + UUID canonicalVersionId, + long epoch, + String launchDescriptorId, + String attestationCommit) { + return completeEvidence( + source, + controlPlaneRequestId, + gameDesignVersionId, + canonicalVersionId, + epoch, + launchDescriptorId, + attestationCommit, + null); + } + + private static CompleteLaunchBindingEvidence completeEvidence( + AuthoredWorldSourceEvidence source, + String controlPlaneRequestId, + long gameDesignVersionId, + UUID canonicalVersionId, + long epoch, + String launchDescriptorId, + String attestationCommit, + WorldPublishedStartLocationEvidence selector) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + 73L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + launchDescriptorId, + gameDesignVersionId, + false, + null, + "{}", + "generation-config-73", + epoch, + 79L, + "release-bundle-79", + false, + null); + return new CompleteLaunchBindingEvidence( + descriptor, + attestation(descriptor, source, canonicalVersionId, attestationCommit, selector)); + } + + private static AuthoredWorldReleaseAttestationEvidence attestation( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + String commit, + WorldPublishedStartLocationEvidence selector) { + return attestation(descriptor, source, canonicalVersionId, commit, selector, 'f'); + } + + private static AuthoredWorldReleaseAttestationEvidence attestation( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + String commit, + WorldPublishedStartLocationEvidence selector, + char manifestHashDigit) { + AuthoredWorldReleaseAttestationEvidence.Participant worldParticipant = + selector == null + ? participant("WORLD_MANAGEMENT", 3, "a", false, descriptor.versionId(), commit) + : new AuthoredWorldReleaseAttestationEvidence.Participant( + "WORLD_MANAGEMENT", + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + selector.request().digestSchemaVersion(), + false, + null); + List participants = + List.of( + worldParticipant, + participant("ENTITY_MANAGEMENT", 2, "b", false, descriptor.versionId(), commit), + participant("GAME_LOGIC", 1, "c", true, descriptor.versionId(), commit), + participant("AUTOMATION_SCRIPTING", 5, "d", false, descriptor.versionId(), commit), + participant( + "GAME_DESIGN_CONTROL_PLANE", 1, "e", false, descriptor.versionId(), commit)); + if (selector == null) { + return AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersionId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:synthetic:association-fixture", + commit, + participants, + digest(manifestHashDigit), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision()); + } + return AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersionId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + digest(manifestHashDigit), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision(), + selector); + } + + private static AuthoredWorldReleaseAttestationEvidence releaseWithWorldCheckpoint( + AuthoredWorldReleaseAttestationEvidence release, CaptureRequest checkpoint) { + var participants = + release.participantDigests().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + checkpoint.appliedCommitId(), + "WORLD_MANAGEMENT".equals(participant.participantKey()) + ? checkpoint.contentDigest() + : participant.contentDigest(), + "WORLD_MANAGEMENT".equals(participant.participantKey()) + ? checkpoint.digestSchemaVersion() + : participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) + .toList(); + if (release.worldStartLocationEvidence() == null) { + return AuthoredWorldReleaseAttestationEvidence.create( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + checkpoint.publishWorkflowId(), + checkpoint.appliedCommitId(), + participants, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision()); + } + return AuthoredWorldReleaseAttestationEvidence.create( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + checkpoint.publishWorkflowId(), + checkpoint.appliedCommitId(), + participants, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision(), + release.worldStartLocationEvidence()); + } + + private static AuthoredWorldReleaseAttestationEvidence.Participant participant( + String owner, + int schema, + String contentHex, + boolean hasAbilityDigest, + long descriptorVersion, + String commit) { + return new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptorVersion), + false, + null, + commit, + contentHex.repeat(64), + schema, + hasAbilityDigest, + hasAbilityDigest ? digest('c') : null); + } + + private static AuthoredWorldSourceEvidence source(UUID tenant, String worldSlug) { + UUID registrationRequest = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String displayName = "Synthetic source " + tenant.toString().substring(0, 8); + long sourceGameRowId = Math.max(1L, tenant.getLeastSignificantBits() & Long.MAX_VALUE); + String sourceGameTenantKey = "source-" + tenant.toString().replace("-", "").substring(0, 24); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequest, tenant, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequest, + sourceOperationId, + requestDigest, + tenant, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static String randomWorld() { + return "world-" + UUID.randomUUID().toString().replace("-", "").substring(0, 18); + } + + private static String controlRequest() { + return "world-control-" + UUID.randomUUID(); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static long positiveLong() { + return Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent canonical association barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent canonical association was interrupted", exception); + } + } + + 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 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 record SourceFixture( + AuthoredWorldSourceEvidence source, WorldAuthoredSourceIntakeReceipt receipt) {} + + private record SeededPair( + WorldCompleteLaunchBindingReceipt binding, + WorldAuthoredVersionIdentityReceipt versionIdentity) {} + + private record Fixture( + SourceFixture source, + WorldCompleteLaunchBindingReceipt binding, + WorldAuthoredVersionIdentityReceipt versionIdentity) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java new file mode 100644 index 0000000000..93ab4006d1 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java @@ -0,0 +1,251 @@ +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.Objects; +import java.util.UUID; +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.WorldManagementServiceApplication; +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 org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; +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.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; + +/** Actual V35 database denial proof; all external source/authentication data is synthetic. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldCanonicalInstancePreparationPostgresIntegrationTest { + @Test + void selectorGuardPreservesInertV1ShapeAndDeniesPromotionOrMissingV2BeforeAllocation() { + long before = + Objects.requireNonNull(dsl.fetchOne("SELECT count(*) FROM world_instance")) + .get(0, Long.class); + UUID absentCapture = UUID.randomUUID(); + dsl.fetchOne( + "SELECT world_require_preparation_start_location(?::jsonb,?::jsonb,?)", + "{\"schemaVersion\":1}", + "{\"schemaVersion\":1}", + absentCapture); + for (String input : + java.util.List.of( + "{\"schemaVersion\":2}", + "{\"schemaVersion\":1,\"worldStartLocationEvidenceBase64\":\"e30=\"}")) { + assertThatThrownBy( + () -> + dsl.fetchOne( + "SELECT world_require_preparation_start_location(?::jsonb,?::jsonb,?)", + input, + "{\"schemaVersion\":1}", + absentCapture)) + .isInstanceOf(DataIntegrityViolationException.class); + } + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO world_canonical_preparation_start_location (canonical_game_instance_id,world_instance_id," + + "canonical_tenant_id,canonical_version_id,room_template_id,runtime_room_instance_id,receipt_digest,graph_digest,evidence_bytes) " + + "VALUES (?,1,?,?,?,1,?,?,?)", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + new byte[] {1})) + .isInstanceOf(RuntimeException.class); + assertThat( + Objects.requireNonNull(dsl.fetchOne("SELECT count(*) FROM world_instance")) + .get(0, Long.class)) + .isEqualTo(before); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM world_canonical_preparation_start_location")) + .get(0, Long.class)) + .isZero(); + } + + private static final String NAMESPACE = "firemud"; + + @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 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 v35PreservesReservedTenantDenialAndDoesNotExposePrepareFunctionToPublic() { + AuthoredWorldSourceEvidence source = source(UUID.randomUUID()); + WorldAuthoredSourceIntakeReceipt receipt = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + new WorldAuthoredSourceIntakeRepository(dsl) + .acceptFresh(NAMESPACE, UUID.randomUUID(), source)), + "synthetic World source fixture returned no intake receipt"); + + assertThatThrownBy(() -> insertInReservedCanonicalTenant(receipt.localTenantKey())) + .isInstanceOf(DataIntegrityViolationException.class) + .rootCause() + .isInstanceOf(PSQLException.class) + .hasMessageContaining(reservedTenantDenial()); + + long legacyInstance = insertLegacyRow(8_700_000_000L + positiveLong() % 100_000L); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET tenant_id = ? WHERE id = ?", + receipt.localTenantKey(), + legacyInstance)) + .isInstanceOf(DataIntegrityViolationException.class) + .rootCause() + .isInstanceOf(PSQLException.class) + .hasMessageContaining(reservedTenantDenial()); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT tenant_id FROM world_instance WHERE id = ?", legacyInstance), + "Legacy row missing after rejected canonical update") + .get("tenant_id", Long.class)) + .isNotEqualTo(receipt.localTenantKey()); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_proc p " + + "JOIN pg_namespace n ON n.oid = p.pronamespace " + + "CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) acl " + + "WHERE n.nspname = 'world_management_service' " + + "AND p.proname = 'world_prepare_canonical_instance' " + + "AND acl.grantee = 0 AND acl.privilege_type = 'EXECUTE')"), + "Prepare-function access query returned no result") + .get(0, Boolean.class)) + .isFalse(); + } + + private void insertInReservedCanonicalTenant(long tenantKey) { + dsl.execute( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, runtime_flags_json, " + + "generation_config_revision, release_bundle_id, published_release_bundle_ref, " + + "version_state_epoch, status) VALUES (?, ?, 71, 'direct-canonical-insert', " + + "'direct-canonical-descriptor', 83, '{}', 'direct-config', 97, " + + "'direct-release', 5, 'DIRECT_FIXTURE')", + tenantKey, + positiveLong()); + } + + private static String reservedTenantDenial() { + return "World tenant key is reserved for a canonical authored source; " + + "no exact transaction execution manifest"; + } + + private long insertLegacyRow(long tenantKey) { + return Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, " + + "runtime_flags_json, generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, status) " + + "VALUES (?, ?, 71, 'legacy-tenant-row', 'legacy-descriptor', 83, '{}', " + + "'legacy-config', 97, 'legacy-release', 5, 'LEGACY_FIXTURE') RETURNING id", + tenantKey, + positiveLong()), + "synthetic unrelated legacy fixture insert returned no row") + .get("id", Long.class); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return transaction; + } + + private static AuthoredWorldSourceEvidence source(UUID tenant) { + UUID registration = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + String display = "Synthetic guard fixture"; + long rowId = positiveLong(); + String sourceTenantKey = "gd-" + tenant.toString().replace("-", "").substring(0, 20); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, display); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + operation, + requestDigest, + tenant, + tenantSlug, + worldSlug, + display, + rowId, + sourceTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + operation, + requestDigest, + tenant, + tenantSlug, + worldSlug, + display, + rowId, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static long positiveLong() { + return Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java new file mode 100644 index 0000000000..36d0ed2e1e --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest.java @@ -0,0 +1,564 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import java.sql.SQLException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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 org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +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.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; + +/** + * Actual PostgreSQL owner fixture definitions. Account peer context and original lease are + * synthetic; the reused graph/release/preparation/activation path stipulates upstream authority. + * There is no accepting release or canonical termination producer, no real Account finalization, + * Game Session binding installation, protected transport composition, or live admission proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldCanonicalPlayerAdmissionHoldPostgresIntegrationTest { + @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 DSLContext dsl; + @Autowired private PlatformTransactionManager manager; + @Autowired private AutowireCapableBeanFactory beanFactory; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void exactRetryAndReadbackRetainOriginalOpaqueIdentityEvidenceAndAllLogicalState() + throws Exception { + var f = fixture(); + var lease = lease(f, 15000L); + String before = logicalRow(f); + String previousTuple = tupleVersion(f); + var service = service(f); + var hold = account().call(() -> acquire(service, f, lease)); + var retry = account().call(() -> acquire(service, f, lease)); + assertThat(retry.holdId()).isEqualTo(hold.holdId()); + assertThat(retry.holdFence()).isEqualTo(hold.holdFence()); + assertThat(retry.worldEvidence().canonicalBytes()) + .isEqualTo(hold.worldEvidence().canonicalBytes()); + assertThat(retry.request().lease().canonicalJson()).isEqualTo(lease.canonicalJson()); + assertThat( + account() + .call( + () -> + service.read( + lease.canonicalJson(), + lease.sha256(), + f.activeEvidence().lifecycleEpoch(), + f.activeEvidence().rowVersion()))) + .contains(hold); + assertThat(logicalRow(f)).isEqualTo(before); + assertThat(tupleVersion(f)).isNotEqualTo(previousTuple); + assertThat(count(f)).isEqualTo(1L); + } + + @Test + void diagnosticExpiryRetainsHoldAndExactRetryWithoutDeadlineRenewal() throws Exception { + var f = fixture(); + var lease = lease(f, 5000L); + var service = service(f); + var hold = account().call(() -> acquire(service, f, lease)); + long deadline = hold.diagnosticExpiresAtMillis(); + long remaining = deadline - System.currentTimeMillis(); + if (remaining >= 0) TimeUnit.MILLISECONDS.sleep(remaining + 1L); + var retry = account().call(() -> acquire(service, f, lease)); + assertThat(retry).isEqualTo(hold); + assertThat(retry.diagnosticExpiresAtMillis()).isEqualTo(deadline); + assertV51Denied( + () -> + dsl.execute( + "UPDATE world_instance SET status='TERMINATING'," + + "lifecycle_epoch=lifecycle_epoch+1,row_version=row_version+1 WHERE id=?", + f.association().worldInstanceId())); + assertThat(count(f)).isEqualTo(1L); + } + + @Test + void expiredLeaseAndSubstitutedScopeOrExpectedTupleDenyWithoutStateOrHoldChanges() + throws Exception { + var f = fixture(); + var service = service(f); + String before = logicalRow(f); + String tuple = tupleVersion(f); + var valid = lease(f, 15000L); + account() + .run( + () -> { + assertThatThrownBy( + () -> + service.acquire( + valid.canonicalJson(), + valid.sha256(), + f.activeEvidence().lifecycleEpoch() + 1L, + f.activeEvidence().rowVersion())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.acquire( + valid.canonicalJson(), + valid.sha256(), + f.activeEvidence().lifecycleEpoch(), + f.activeEvidence().rowVersion() + 1L)) + .isInstanceOf(IllegalArgumentException.class); + }); + var changedScope = new LinkedHashMap<>(scope(valid.carrier())); + changedScope.put("worldSlug", "substituted-world"); + var changed = changed(valid, "bindingScope", changedScope); + account() + .run( + () -> + assertThatThrownBy(() -> acquire(service, f, changed)) + .isInstanceOf(IllegalArgumentException.class)); + changedScope.put("gameInstanceId", UUID.randomUUID().toString()); + var unmapped = changed(valid, "bindingScope", changedScope); + account() + .run( + () -> + assertThatThrownBy(() -> acquire(service, f, unmapped)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("association is missing")); + var expiredCarrier = new LinkedHashMap<>(valid.carrier()); + // Keep token valid and evaluated time unchanged, but expire this original lease. + long now = System.currentTimeMillis(); + expiredCarrier.put("evaluatedAt", Long.toString(now - 1000L)); + expiredCarrier.put("expiresAt", Long.toString(now - 1L)); + var expired = AccountGameplayAdmissionLeaseEvidence.fromCarrier(expiredCarrier); + account() + .run( + () -> + assertThatThrownBy(() -> acquire(service, f, expired)) + .hasMessageContaining("original lease or exact owner evidence")); + assertThat(count(f)).isZero(); + assertThat(logicalRow(f)).isEqualTo(before); + assertThat(tupleVersion(f)).isEqualTo(tuple); + } + + @Test + void retainedAttemptRejectsChangedLeaseDigestIdentityAndEpoch() throws Exception { + var f = fixture(); + var original = lease(f, 15000L); + var service = service(f); + var hold = account().call(() -> acquire(service, f, original)); + String before = logicalRow(f); + for (var changed : + List.of( + changed(original, "leaseFence", "2"), + changed(original, "leaseId", UUID.randomUUID().toString()), + changed(original, "requestId", UUID.randomUUID().toString()))) { + account() + .run( + () -> + assertThatThrownBy(() -> acquire(service, f, changed)) + .hasMessageContaining("original lease/attempt binding")); + } + account() + .run( + () -> + assertThatThrownBy( + () -> + service.acquire( + original.canonicalJson(), + original.sha256(), + f.activeEvidence().lifecycleEpoch() + 1L, + f.activeEvidence().rowVersion())) + .hasMessageContaining("original lease/attempt binding")); + assertThat(account().call(() -> acquire(service, f, original))).isEqualTo(hold); + assertThat(count(f)).isEqualTo(1L); + assertThat(logicalRow(f)).isEqualTo(before); + } + + @Test + void v51ItselfFencesRawLifecycleCounterMutationAndDeleteWhileReleaseStaysUnavailable() + throws Exception { + var f = fixture(); + var service = service(f); + account().call(() -> acquire(service, f, lease(f, 15000L))); + String before = logicalRow(f); + for (String sql : + List.of( + "UPDATE world_instance SET status='TERMINATING',lifecycle_epoch=lifecycle_epoch+1,row_version=row_version+1 WHERE id=?", + "UPDATE world_instance SET lifecycle_epoch=lifecycle_epoch+1 WHERE id=?", + "UPDATE world_instance SET row_version=row_version+1 WHERE id=?", + "DELETE FROM world_instance WHERE id=?")) { + assertV51Denied(() -> dsl.execute(sql, f.association().worldInstanceId())); + } + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_canonical_player_admission_hold SET hold_state='RELEASED' WHERE world_instance_id=?", + f.association().worldInstanceId())) + .hasMessageContaining("dual-owner release is unavailable"); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_canonical_player_admission_hold WHERE world_instance_id=?", + f.association().worldInstanceId())) + .hasMessageContaining("dual-owner release is unavailable"); + assertThatThrownBy(() -> dsl.execute("TRUNCATE world_canonical_player_admission_hold")) + .hasMessageContaining("original evidence are retained"); + account() + .run( + () -> + assertThatThrownBy(service::release) + .hasMessageContaining("release is unavailable")); + assertThat(count(f)).isEqualTo(1L); + assertThat(logicalRow(f)).isEqualTo(before); + } + + @Test + void twoConcurrentExactAcquisitionsRetainOneIdentity() throws Exception { + var f = fixture(); + var original = lease(f, 15000L); + var service = service(f); + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + java.util.concurrent.Callable operation = + () -> { + ready.countDown(); + await(start); + return account().call(() -> acquire(service, f, original)); + }; + var first = executor.submit(operation); + var second = executor.submit(operation); + await(ready); + start.countDown(); + assertThat(first.get(15, TimeUnit.SECONDS)).isEqualTo(second.get(15, TimeUnit.SECONDS)); + assertThat(count(f)).isEqualTo(1L); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void independentPlayerAttemptsPreserveEveryExistingHoldAndDoNotOpenGenericNoOpBypass() + throws Exception { + var f = fixture(); + var service = service(f); + var firstLease = lease(f, 15000L); + var first = account().call(() -> acquire(service, f, firstLease)); + String before = logicalRow(f); + var second = account().call(() -> acquire(service, f, lease(f, 15000L))); + assertThat(second.holdId()).isNotEqualTo(first.holdId()); + assertThat(second.holdFence()).isNotEqualTo(first.holdFence()); + assertThat(account().call(() -> acquire(service, f, firstLease))).isEqualTo(first); + assertThat(count(f)).isEqualTo(2L); + assertThat(logicalRow(f)).isEqualTo(before); + // V51's exact no-op exception is restricted to the actual insertion transaction. An ordinary + // later caller still reaches the pre-existing V35 canonical-write denial. + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET row_version=row_version WHERE id=?", + f.association().worldInstanceId())) + .hasMessageContaining("no exact transaction execution manifest"); + } + + @Test + void staleRepeatableReadSnapshotCannotMissCommittedHoldTupleVersion() throws Exception { + assertStaleSnapshotFails(TransactionDefinition.ISOLATION_REPEATABLE_READ); + } + + @Test + void staleSerializableSnapshotCannotMissCommittedHoldTupleVersion() throws Exception { + assertStaleSnapshotFails(TransactionDefinition.ISOLATION_SERIALIZABLE); + } + + private void assertStaleSnapshotFails(int isolation) throws Exception { + var f = fixture(); + String before = logicalRow(f); + var snapshotRead = new CountDownLatch(1); + var holdCommitted = new CountDownLatch(1); + var executor = Executors.newSingleThreadExecutor(); + try { + var stale = + executor.submit( + () -> { + try { + transaction(isolation) + .execute( + status -> { + assertThat(logicalRow(f)).isEqualTo(before); + assertThat(count(f)).isZero(); + snapshotRead.countDown(); + await(holdCommitted); + dsl.execute( + "UPDATE world_instance SET status='TERMINATING',lifecycle_epoch=lifecycle_epoch+1," + + "row_version=row_version+1 WHERE id=?", + f.association().worldInstanceId()); + return null; + }); + throw new AssertionError( + "Stale snapshot lifecycle change unexpectedly committed"); + } catch (RuntimeException failure) { + return sqlState(failure); + } finally { + snapshotRead.countDown(); + } + }); + await(snapshotRead); + account().call(() -> acquire(service(f), f, lease(f, 15000L))); + holdCommitted.countDown(); + assertThat(stale.get(15, TimeUnit.SECONDS)).isEqualTo("40001"); + assertThat(logicalRow(f)).isEqualTo(before); + assertThat(count(f)).isEqualTo(1L); + } finally { + holdCommitted.countDown(); + executor.shutdownNow(); + } + } + + private WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture fixture() { + var owner = new WorldDraftGraphApplicationPostgresIntegrationTest(); + beanFactory.autowireBean(owner); + return owner.activePlayerAdmissionFixture(); + } + + private WorldCanonicalPlayerAdmissionHoldService service( + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f) { + var associations = + new WorldCanonicalInstanceAssociationRepository( + dsl, + new WorldCompleteLaunchBindingRepository(dsl), + new WorldAuthoredSourceIntakeRepository(dsl), + new WorldAuthoredVersionIdentityRepository(dsl)); + return new WorldCanonicalPlayerAdmissionHoldService( + new WorldCanonicalPlayerAdmissionHoldRepository( + dsl, manager, "firemud", associations, f.lifecycleRepository()), + "firemud"); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence acquire( + WorldCanonicalPlayerAdmissionHoldService service, + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f, + AccountGameplayAdmissionLeaseEvidence lease) { + return service.acquire( + lease.canonicalJson(), + lease.sha256(), + f.activeEvidence().lifecycleEpoch(), + f.activeEvidence().rowVersion()); + } + + /** Synthetic complete original Account carrier, with no current source or terminal authority. */ + private static AccountGameplayAdmissionLeaseEvidence lease( + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f, + long duration) { + var identity = f.activeEvidence().request(); + String account = UUID.randomUUID().toString(); + String tenant = identity.canonicalTenantId().toString(); + Map scope = new LinkedHashMap<>(); + scope.put("accountId", account); + scope.put("tenantId", tenant); + scope.put("realmId", UUID.randomUUID().toString()); + scope.put("worldSlug", identity.worldSlug()); + scope.put("realmSlug", "synthetic-realm"); + scope.put("playableStateNamespaceId", identity.playableStateNamespaceId().toString()); + scope.put("playableStateScope", identity.playableStateScope()); + scope.put("gameInstanceId", identity.canonicalGameInstanceId().toString()); + for (String key : List.of("characterId", "sessionId", "regionId")) + scope.put(key, UUID.randomUUID().toString()); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "9007199254740993"); + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "firemud"); + value.put("callerWorkload", "spiffe://firemud/ns/firemud/sa/game-session-service"); + value.put("requestId", UUID.randomUUID().toString()); + value.put("leaseId", UUID.randomUUID().toString()); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(tenant, "1"), + "membershipAuthorityGeneration", + Map.of(tenant, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(tenant, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + checkpoint("account/" + account, "0"), + checkpoint("issuer/firemud-account-service", "0"), + checkpoint("membership/" + account + "/" + tenant, "1"), + checkpoint("tenant/" + tenant, "1"))); + long now = System.currentTimeMillis(); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", account), + Map.entry("operationId", UUID.randomUUID().toString()), + Map.entry("issuanceRequestId", UUID.randomUUID().toString()), + Map.entry("tokenJti", UUID.randomUUID().toString()), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("issuedAt", Long.toString(now / 1000 - 2)), + Map.entry("notBefore", Long.toString(now / 1000 - 2)), + Map.entry("expiresAt", Long.toString(now / 1000 + 300)))); + value.put("evaluatedAt", Long.toString(now)); + value.put("expiresAt", Long.toString(now + duration)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); + } + + private static AccountGameplayAdmissionLeaseEvidence changed( + AccountGameplayAdmissionLeaseEvidence original, String field, Object value) { + var carrier = new LinkedHashMap<>(original.carrier()); + carrier.put(field, value); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + @SuppressWarnings("unchecked") + private static Map scope(Map carrier) { + return (Map) carrier.get("bindingScope"); + } + + private static Map checkpoint(String suffix, String sequence) { + return Map.of( + "outboxStreamKey", "account:auth-authority:v1:" + suffix, "outboxSequence", sequence); + } + + private long count( + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_player_admission_hold WHERE world_instance_id=?", + f.association().worldInstanceId())) + .get(0, Long.class); + } + + private String logicalRow( + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(w)::text FROM world_instance w WHERE id=?", + f.association().worldInstanceId())) + .get(0, String.class); + } + + private String tupleVersion( + WorldDraftGraphApplicationPostgresIntegrationTest.ActivePlayerAdmissionFixture f) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text FROM world_instance WHERE id=?", + f.association().worldInstanceId())) + .get(0, String.class); + } + + private TransactionTemplate transaction(int isolation) { + var transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(isolation); + return transaction; + } + + private static Context account() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/account-service") + .orElseThrow()); + } + + private static void assertV51Denied( + org.assertj.core.api.ThrowableAssert.ThrowingCallable operation) { + assertThatThrownBy(operation) + .hasMessageContaining("fenced by a retained player-admission hold") + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) return sql.getSQLState(); + } + throw new AssertionError("Expected real PostgreSQL SQLSTATE", failure); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new AssertionError("Owner fixture coordination timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new AssertionError("Owner fixture interrupted", failure); + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java new file mode 100644 index 0000000000..919e445ffc --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -0,0 +1,6683 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import io.grpc.Context; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import 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 java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.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.world.CanonicalWorldInstancePreparationClient; +import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationGrpcCodec; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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.repository.InitialAdmissionBindHoldRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; +import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceResponse; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceResponse; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceActivationServiceGrpc; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +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; +import tools.jackson.databind.ObjectMapper; + +/** + * PostgreSQL World component fixtures; stipulated upstream owner proof is not live handoff proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldDraftGraphApplicationPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final String GAME_SESSION_WORKLOAD_URI = + "spiffe://firemud/ns/firemud/sa/game-session-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/firemud/sa/game-design-service"; + private static final String WORLD_SERVER_WORKLOAD_URI = + "spiffe://firemud/ns/firemud/sa/world-management-service"; + private static final long GAME_DESIGN_VERSION = 9_000_000_000_000_001L; + + @TempDir Path temporaryDirectory; + + @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 DSLContext dsl; + @Autowired private PlatformTransactionManager manager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository fence; + @Autowired private ObjectMapper mapper; + @Autowired private WorldAuthoredGraphSnapshotRepository snapshots; + @Autowired private WorldLifecycleCommandService lifecycleCommandService; + + @Autowired + private net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService + digestService; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRuntimeMapping() { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var lastRoom = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var application = withStartRoom(original, lastRoom); + appliedComponent().apply(application); + var frozen = capture(application.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var seedInput = preparationInput(f, frozen, selector); + var retainedEpoch = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT jsonb_typeof(release_attestation_json::jsonb->'worldStartLocationEvidence'->'request'->'versionStateEpoch') AS epoch_type," + + "release_attestation_json::jsonb->'worldStartLocationEvidence'->'request'->>'versionStateEpoch' AS epoch_value " + + "FROM world_complete_launch_binding WHERE target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?", + seedInput.gameSessionReadEvidence().targetNamespace(), + seedInput.gameSessionReadEvidence().canonicalTenantId(), + seedInput.gameSessionReadEvidence().controlPlaneRequestId())); + assertThat(retainedEpoch.get("epoch_type", String.class)).isEqualTo("number"); + String retainedEpochValue = retainedEpoch.get("epoch_value", String.class); + assertThat(retainedEpochValue).isEqualTo(Long.toString(selector.request().versionStateEpoch())); + var selectorRequestJson = mapper.readTree(selector.canonicalBytes()).get("request"); + assertThat(selectorRequestJson.get("versionStateEpoch").isTextual()).isTrue(); + assertThat(selectorRequestJson.get("versionStateEpoch").textValue()) + .isEqualTo(retainedEpochValue); + + // This isolated fixture writes and reads back an actual retained World PUBLISHED terminal. + var originalTerminal = isolatedTerminalEvidence(seedInput); + byte[] originalTerminalBytes = originalTerminal.canonicalBytes(); + publicationTerminalComponent(originalTerminal) + .complete(originalTerminal.operationBytes(), originalTerminalBytes); + UUID publicationFence = selector.request().publicationFence(); + assertThat(publicationOwnerPhase(publicationFence)).isEqualTo("PUBLISHED"); + assertThat(publicationTerminalBytes(publicationFence)).containsExactly(originalTerminalBytes); + + UUID canonicalGameInstanceId = UUID.randomUUID(); + var stableSelector = + new WorldCanonicalInstancePreparationAssemblyService.Selector( + f.intake().canonicalTenantId(), + canonicalGameInstanceId, + seedInput.completeLaunchBinding().controlPlaneRequestId()); + var allocationsBefore = canonicalPreparationAllocationRows(f, canonicalGameInstanceId); + assertThat(allocationsBefore.values()).containsOnly(0L); + var substitutedInput = + preparationInput(f, frozen, selector, 2L, List.of("LOOK", "SUBSTITUTED")); + var sourceRowsBefore = retainedPreparationSourceRows(f, seedInput, frozen); + var substitutedCompletePair = + preparationAssemblyFixture( + NAMESPACE, substitutedInput.completeLaunchBinding().evidence(), UUID.randomUUID()); + assertThatThrownBy(() -> substitutedCompletePair.service().assemble(stableSelector)) + .isInstanceOf( + WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) + .hasMessageContaining("Authenticated Game Design complete launch pair differs"); + Mockito.verifyNoInteractions(substitutedCompletePair.gameSessionClient()); + assertThat(canonicalPreparationAllocationRows(f, canonicalGameInstanceId)) + .isEqualTo(allocationsBefore); + assertThat(retainedPreparationSourceRows(f, seedInput, frozen)).isEqualTo(sourceRowsBefore); + + var assembly = + preparationAssemblyFixture( + NAMESPACE, seedInput.completeLaunchBinding().evidence(), UUID.randomUUID()); + var input = assembly.service().assemble(stableSelector); + assertThat(input.completeLaunchBinding()).isEqualTo(seedInput.completeLaunchBinding()); + assertThat(input.versionIdentity()).isEqualTo(f.version()); + assertThat(input.topologyPlan().captureId()).isEqualTo(frozen.captureId()); + assertThat(input.topologyPlan().sourceBinding().freeze()).isEqualTo(frozen.request().freeze()); + assertThat( + input.topologyPlan().rooms().stream() + .map(room -> room.identity().templateId()) + .toList()) + .containsExactlyElementsOf( + WorldCanonicalInstanceTopologyPlan.create(frozen).rooms().stream() + .map(room -> room.identity().templateId()) + .toList()); + assertThat(input.gameSessionReadRequest().canonicalGameInstanceId()) + .isEqualTo(canonicalGameInstanceId); + assertThat(input.gameSessionReadEvidence().currentGameSessionStatus()).isEqualTo("STARTING"); + assertThat(input.gameSessionReadEvidence().playableStateNamespaceId()) + .isEqualTo(assembly.playableStateNamespaceId()); + + var repository = preparationRepository(); + var service = preparationComponentWithRetainedTerminal(repository, originalTerminal); + var result = service.prepare(input); + assertThat(result.startLocation().roomTemplateId()).isEqualTo(lastRoom); + assertThat(result.runtimeRoomInstanceId()).isPositive(); + assertThat(result.storageStatus()).isEqualTo("MATERIALIZED_UNVERIFIED"); + assertThat(result.startLocation().roomTemplateId()) + .isNotEqualTo(input.topologyPlan().rooms().getFirst().identity().templateId()); + var mapped = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT m.template_id,r.room_instance_row_id AS room_instance_id FROM world_canonical_instance_topology_identity m " + + "JOIN room_instance r ON r.id=m.runtime_row_id WHERE m.world_instance_id=? AND m.family='ROOM' AND m.template_id=?", + result.association().worldInstanceId(), + lastRoom)); + assertThat(mapped.get("room_instance_id", Long.class)) + .isEqualTo(result.runtimeRoomInstanceId()); + byte[] before = preparationRows(input.canonicalGameInstanceId()); + var reassembled = assembly.service().assemble(stableSelector); + assertThat(WorldCanonicalInstancePreparationRepository.inputJson(reassembled)) + .isEqualTo(WorldCanonicalInstancePreparationRepository.inputJson(input)); + assertThat(service.prepare(reassembled)).isEqualTo(result); + assertThat(repository.readOwnerPreparation(reassembled)).contains(result); + assertThat(preparationRows(input.canonicalGameInstanceId())).containsExactly(before); + assertThat(retainedPreparationSourceRows(f, seedInput, frozen)).isEqualTo(sourceRowsBefore); + assertThat(publicationOwnerPhase(publicationFence)).isEqualTo("PUBLISHED"); + assertThat(publicationTerminalBytes(publicationFence)).containsExactly(originalTerminalBytes); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_canonical_preparation_start_location SET runtime_room_instance_id=runtime_room_instance_id+1 WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .hasMessageContaining("immutable and retained"); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM world_canonical_preparation_start_location WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .hasMessageContaining("immutable and retained"); + assertOrigin(); + } + + @Test + void authenticatedPreparationAdapterBindsFreshLaunchAndReadsActualPreparingLifecycle() + throws Exception { + // Advance only this isolated fixture's allocator; do not rely on test order to escape Java's + // boxed-Long cache or fabricate a topology mapping for the regression below. + dsl.fetchValue( + "SELECT setval('region_instance_id_seq', GREATEST(last_value, 128), true) " + + "FROM region_instance_id_seq"); + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var selectedRoom = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var application = withStartRoom(original, selectedRoom); + appliedComponent().apply(application); + var frozen = capture(application.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var launchFixture = preparationLaunchFixture(f, frozen, selector, 2L, List.of("LOOK")); + var evidence = launchFixture.evidence(); + var ownerRequest = launchFixture.ownerRequest(); + byte[] originalAppliedRows = retainedApplicationBytes(application); + byte[] originalSelectorBytes = selector.canonicalBytes(); + var stableSelector = + new WorldCanonicalInstancePreparationAssemblyService.Selector( + ownerRequest.canonicalTenantId(), + ownerRequest.gameInstanceUuid(), + ownerRequest.controlPlaneRequestId()); + assertThat( + completeLaunchBindingCount( + ownerRequest.targetNamespace(), + ownerRequest.canonicalTenantId(), + ownerRequest.controlPlaneRequestId())) + .isZero(); + + // Account authorization and Game Design publication inputs are isolated fixture evidence. The + // Game Design and Game Session readers below are isolated doubles; World storage and services + // remain actual. No V26 binding is seeded here; the protected adapter's producer owns that + // write. + var originalTerminal = isolatedTerminalEvidence(evidence, launchFixture.topologyPlan()); + byte[] originalTerminalBytes = originalTerminal.canonicalBytes(); + publicationTerminalComponent(originalTerminal) + .complete(originalTerminal.operationBytes(), originalTerminalBytes); + var publicationFence = selector.request().publicationFence(); + assertThat(publicationOwnerPhase(publicationFence)).isEqualTo("PUBLISHED"); + assertThat(publicationTerminalBytes(publicationFence)).containsExactly(originalTerminalBytes); + + var isolatedOwners = preparationAssemblyFixture(NAMESPACE, evidence, UUID.randomUUID()); + var bindingService = + new WorldCompleteLaunchBindingService( + isolatedOwners.gameDesignClient(), + new WorldCompleteLaunchBindingRepository(dsl), + new WorldAuthoredSourceIntakeRepository(dsl), + manager, + NAMESPACE, + null, + isolatedOwners.gameSessionClient()); + var repository = preparationRepository(); + var verifierInvocations = new AtomicInteger(); + var preparation = + preparationComponentWithRetainedTerminal(repository, originalTerminal, verifierInvocations); + var lifecycleRepository = + new WorldCanonicalInstanceLifecycleReadRepository(dsl, manager, associationRepository()); + var adapter = + new WorldCanonicalInstancePreparationGrpcService( + bindingService, + isolatedOwners.service(), + preparation, + repository, + lifecycleRepository, + NAMESPACE); + + assertThat( + completeLaunchBindingCount( + ownerRequest.targetNamespace(), + ownerRequest.canonicalTenantId(), + ownerRequest.controlPlaneRequestId())) + .isZero(); + var preparationPki = WorldPreparationTestWorkloadPki.create(temporaryDirectory); + Server transport = startPreparationTransport(adapter, preparationPki); + try { + var allocationsBeforeWrongPeer = + canonicalPreparationAllocationRows(f, ownerRequest.gameInstanceUuid()); + var expectedFirstLifecycleRequest = + lifecycleReadRequest(ownerRequest, evidence, isolatedOwners.playableStateNamespaceId()); + try (var wrongPeerClient = + preparationClient(transport, preparationPki.clientProperties(WRONG_WORKLOAD_URI))) { + wrongPeerClient.init(); + assertThatThrownBy( + () -> wrongPeerClient.prepare(ownerRequest, expectedFirstLifecycleRequest)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + assertThat( + completeLaunchBindingCount( + ownerRequest.targetNamespace(), + ownerRequest.canonicalTenantId(), + ownerRequest.controlPlaneRequestId())) + .isZero(); + assertThat(canonicalPreparationAllocationRows(f, ownerRequest.gameInstanceUuid())) + .isEqualTo(allocationsBeforeWrongPeer); + + try (var client = + preparationClient( + transport, preparationPki.clientProperties(GAME_SESSION_WORKLOAD_URI))) { + client.init(); + var firstLifecycle = client.prepare(ownerRequest, expectedFirstLifecycleRequest); + assertThat( + completeLaunchBindingCount( + ownerRequest.targetNamespace(), + ownerRequest.canonicalTenantId(), + ownerRequest.controlPlaneRequestId())) + .isEqualTo(1L); + + var actualInput = isolatedOwners.service().assemble(stableSelector); + assertThat(actualInput.gameSessionReadEvidence().currentGameSessionStatus()) + .isEqualTo("STARTING"); + assertThat(actualInput.topologyPlan().sourceBinding().freeze()) + .isEqualTo(frozen.request().freeze()); + var firstLifecycleRequest = + lifecycleReadRequest( + CanonicalWorldInstancePreparationGrpcCodec.toRequest(ownerRequest), actualInput); + assertThat(firstLifecycleRequest).isEqualTo(expectedFirstLifecycleRequest); + var firstActualLifecycle = lifecycleRepository.read(firstLifecycleRequest).orElseThrow(); + assertThat(firstLifecycle).isEqualTo(firstActualLifecycle); + assertThat(firstLifecycle.operationalRegionAssignments()) + .containsExactlyEntriesOf( + materializedOperationalRegionAssignments(ownerRequest.gameInstanceUuid())); + assertThat(firstLifecycle.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(firstLifecycle.lifecycleEpoch()).isEqualTo(1L); + assertThat(firstLifecycle.launchBinding()).isEqualTo(evidence); + assertThat(firstLifecycle.captureId()).isEqualTo(frozen.captureId()); + assertThat(firstLifecycle.startLocation().roomTemplateId()).isEqualTo(selectedRoom); + assertThat(firstLifecycle.startLocation().roomTemplateId()) + .isNotEqualTo(actualInput.topologyPlan().rooms().getFirst().identity().templateId()); + assertThat(firstLifecycle.runtimeRoomInstanceId()).isPositive(); + assertThat(verifierInvocations).hasValue(1); + + var selectedRoomPlan = + actualInput.topologyPlan().rooms().stream() + .filter(room -> room.identity().templateId().equals(selectedRoom)) + .findFirst() + .orElseThrow(); + var selectedZonePlan = + actualInput.topologyPlan().zones().stream() + .filter(zone -> zone.identity().equals(selectedRoomPlan.zone())) + .findFirst() + .orElseThrow(); + var materializedRegion = + materializedOperationalRegionRow( + ownerRequest.gameInstanceUuid(), + selectedZonePlan.region().templateId(), + selectedRoomPlan.zone().templateId(), + selectedRoom); + UUID operationalRegionId = materializedRegion.get("operational_region_id", UUID.class); + UUID canonicalRegionInstanceId = + materializedRegion.get("canonical_region_instance_id", UUID.class); + assertThat(operationalRegionId).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(operationalRegionId).isNotEqualTo(canonicalRegionInstanceId); + assertThat(materializedRegion.get("canonical_runtime_identity", UUID.class)) + .isEqualTo(canonicalRegionInstanceId); + assertThat(materializedRegion.get("region_tenant_id", Long.class)) + .isEqualTo(materializedRegion.get("room_tenant_id", Long.class)); + assertThat(materializedRegion.get("region_game_instance_id", Long.class)) + .isEqualTo(materializedRegion.get("room_game_instance_id", Long.class)); + assertThat(materializedRegion.get("region_row_id", Long.class)) + .isEqualTo(materializedRegion.get("room_region_instance_id", Long.class)); + assertThat(materializedRegion.get("region_row_id", Long.class)) + .isEqualTo(materializedRegion.get("zone_region_instance_id", Long.class)); + // Exercise the lifecycle reader against PostgreSQL's actual BIGINT key outside the + // boxed-Long cache range; the read above must match this persisted topology mapping. + assertThat(materializedRegion.get("region_row_id", Long.class)).isGreaterThan(127L); + assertThat(materializedRegion.get("zone_row_id", Long.class)) + .isEqualTo(materializedRegion.get("room_zone_instance_id", Long.class)); + String retainedOperationalRegionRow = + materializedRegion.get("region_row_json", String.class); + + var mappedRoom = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT r.room_instance_row_id AS room_instance_id FROM world_canonical_instance_topology_identity m " + + "JOIN room_instance r ON r.id=m.runtime_row_id WHERE m.canonical_game_instance_id=? AND m.family='ROOM' AND m.template_id=?", + ownerRequest.gameInstanceUuid(), + selectedRoom)); + assertThat(mappedRoom.get("room_instance_id", Long.class)) + .isEqualTo(firstLifecycle.runtimeRoomInstanceId()); + + var retainedSourceRows = retainedPreparationSourceRows(f, actualInput, frozen); + byte[] retainedPreparationRows = preparationRows(ownerRequest.gameInstanceUuid()); + String retainedLifecycleRow = + retainedJson( + "SELECT to_jsonb(wi)::text FROM world_instance wi WHERE canonical_game_instance_id=?", + ownerRequest.gameInstanceUuid()); + var retryRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + ownerRequest.targetNamespace(), + ownerRequest.canonicalTenantId(), + ownerRequest.worldSlug(), + ownerRequest.gameInstanceUuid(), + ownerRequest.controlPlaneRequestId(), + ownerRequest.launchDescriptorId(), + ownerRequest.expectedDescriptorRequestDigest(), + ownerRequest.expectedDescriptorResultDigest(), + ownerRequest.expectedReleaseAttestationEvidenceDigest()); + var expectedRetryLifecycleRequest = + lifecycleReadRequest(retryRequest, evidence, isolatedOwners.playableStateNamespaceId()); + var retryLifecycle = client.prepare(retryRequest, expectedRetryLifecycleRequest); + var retryInput = isolatedOwners.service().assemble(stableSelector); + var retryLifecycleRequest = + lifecycleReadRequest( + CanonicalWorldInstancePreparationGrpcCodec.toRequest(retryRequest), retryInput); + assertThat(retryLifecycleRequest).isEqualTo(expectedRetryLifecycleRequest); + var retryActualLifecycle = lifecycleRepository.read(retryLifecycleRequest).orElseThrow(); + var retriedOperationalRegion = + materializedOperationalRegionRow( + ownerRequest.gameInstanceUuid(), + selectedZonePlan.region().templateId(), + selectedRoomPlan.zone().templateId(), + selectedRoom); + assertThat(retryLifecycle).isEqualTo(retryActualLifecycle); + assertThat(retryLifecycle.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(retryLifecycle.lifecycleEpoch()).isEqualTo(1L); + assertThat(retryLifecycle.runtimeRoomInstanceId()) + .isEqualTo(firstLifecycle.runtimeRoomInstanceId()); + assertThat(retryLifecycle.launchBinding()).isEqualTo(firstLifecycle.launchBinding()); + assertThat(retryLifecycle.captureId()).isEqualTo(firstLifecycle.captureId()); + assertThat(retryLifecycle.graphSha256()).isEqualTo(firstLifecycle.graphSha256()); + assertThat(retryLifecycle.preparationInputDigest()) + .isEqualTo(firstLifecycle.preparationInputDigest()); + assertThat(retryLifecycle.startLocation()).isEqualTo(firstLifecycle.startLocation()); + assertThat(retriedOperationalRegion.get("operational_region_id", UUID.class)) + .isEqualTo(operationalRegionId); + assertThat(retriedOperationalRegion.get("canonical_region_instance_id", UUID.class)) + .isEqualTo(canonicalRegionInstanceId); + assertThat(retriedOperationalRegion.get("region_row_json", String.class)) + .isEqualTo(retainedOperationalRegionRow); + assertThat(verifierInvocations).hasValue(2); + assertThat(preparationRows(ownerRequest.gameInstanceUuid())) + .containsExactly(retainedPreparationRows); + assertThat(retainedPreparationSourceRows(f, retryInput, frozen)) + .isEqualTo(retainedSourceRows); + assertThat(retainedApplicationBytes(application)).containsExactly(originalAppliedRows); + assertThat( + publishedSelectors() + .readCommitted(frozen.request().freeze()) + .map(this::publishedEvidence) + .orElseThrow() + .canonicalBytes()) + .containsExactly(originalSelectorBytes); + assertThat( + retainedJson( + "SELECT to_jsonb(wi)::text FROM world_instance wi WHERE canonical_game_instance_id=?", + ownerRequest.gameInstanceUuid())) + .isEqualTo(retainedLifecycleRow); + assertThat( + completeLaunchBindingCount( + ownerRequest.targetNamespace(), + ownerRequest.canonicalTenantId(), + ownerRequest.controlPlaneRequestId())) + .isEqualTo(1L); + assertThat(publicationOwnerPhase(publicationFence)).isEqualTo("PUBLISHED"); + assertThat(publicationTerminalBytes(publicationFence)) + .containsExactly(originalTerminalBytes); + assertOrigin(); + } + } finally { + transport.shutdownNow(); + assertThat(transport.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void canonicalPreparationKeepsOriginalPublicationEpochForLaterReleaseResolution() { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var selectedRoom = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var applied = withStartRoom(original, selectedRoom); + appliedComponent().apply(applied); + var frozen = capture(applied.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + + long publicationEpoch = 2L; + var publicationInput = preparationInput(f, frozen, selector, publicationEpoch); + var originalTerminal = isolatedTerminalEvidence(publicationInput); + byte[] originalTerminalBytes = originalTerminal.canonicalBytes(); + assertThat(originalTerminal.publicationVersionStateEpoch()).isEqualTo(publicationEpoch); + assertThat(originalTerminal.worldEvidence().request().versionStateEpoch()) + .isEqualTo(selector.request().versionStateEpoch()); + publicationTerminalComponent(originalTerminal) + .complete(originalTerminal.operationBytes(), originalTerminalBytes); + UUID fence = selector.request().publicationFence(); + assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); + assertThat(publicationTerminalBytes(fence)).containsExactly(originalTerminalBytes); + + var staleInput = preparationInput(f, frozen, selector, publicationEpoch - 1); + // These later descriptor epochs are isolated GD-resolution inputs: this proves World owner + // storage and binding only, not a live GD lifecycle/currentness or authorization producer. + var laterInput = preparationInput(f, frozen, selector, publicationEpoch + 1); + var changedReleaseInput = + preparationInput(f, frozen, selector, publicationEpoch + 1, List.of("LOOK", "CHANGED")); + var laterRelease = laterInput.completeLaunchBinding().evidence().releaseAttestation(); + assertThat(laterRelease.versionStateEpoch()).isEqualTo(publicationEpoch + 1); + // Compare the later descriptor's immutable content directly. Its later resolution epoch + // cannot be wrapped in a new publication terminal because the terminal keeps the original + // publication operation epoch. + assertThat(isolatedReleaseContent(laterInput).canonicalBytes()) + .containsExactly(originalTerminal.releaseContent().canonicalBytes()); + assertThat(isolatedReleaseContent(changedReleaseInput).canonicalBytes()) + .isNotEqualTo(originalTerminal.releaseContent().canonicalBytes()); + + var repository = preparationRepository(); + var service = preparationComponentWithRetainedTerminal(repository, originalTerminal); + assertThatThrownBy(() -> service.prepare(staleInput)) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.InvalidPreparationEvidenceException.class) + .hasMessageContaining("ReleaseContent differs"); + assertThatThrownBy(() -> service.prepare(changedReleaseInput)) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.InvalidPreparationEvidenceException.class) + .hasMessageContaining("ReleaseContent differs"); + assertThat(count(f, "world_instance")).isZero(); + + var prepared = service.prepare(laterInput); + assertThat(prepared.startLocation().roomTemplateId()).isEqualTo(selectedRoom); + assertThat(repository.readOwnerPreparation(laterInput)).contains(prepared); + assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); + assertThat(publicationTerminalBytes(fence)).containsExactly(originalTerminalBytes); + assertThat( + WorldPublicationTerminal.request(publicationTerminalBytes(fence)) + .publicationVersionStateEpoch()) + .isEqualTo(publicationEpoch); + assertOrigin(); + } + + @Test + void rawTerminalReceiptCannotCommitWithoutMatchingOwnerPhaseCas() { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var selectedRoom = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var applied = withStartRoom(original, selectedRoom); + appliedComponent().apply(applied); + var frozen = capture(applied.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + // This isolated producer fixture exercises the actual retained World rows and SQL guards. + var request = + WorldPublicationTerminal.Request.fromStored( + isolatedTerminalEvidence(input).canonicalBytes()); + UUID fence = selector.request().publicationFence(); + + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + insertPublicationTerminal(request); + return null; + })) + .hasMessageContaining("World terminal receipt must commit with its exact owner phase"); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_terminal WHERE publication_fence=?", + fence)) + .get(0, Long.class)) + .isZero(); + assertOrigin(); + } + + private String publicationOwnerPhase(UUID fence) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT owner_freeze_phase FROM world_design_publication_fence_owner " + + "WHERE current_publication_fence=?", + fence)) + .get("owner_freeze_phase", String.class); + } + + private byte[] publicationTerminalBytes(UUID fence) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT terminal_evidence_bytes FROM world_design_publication_terminal " + + "WHERE publication_fence=?", + fence)) + .get("terminal_evidence_bytes", byte[].class); + } + + private void insertPublicationTerminal(WorldPublicationTerminal.Request request) { + var world = request.worldEvidence().request(); + dsl.execute( + "INSERT INTO world_design_publication_terminal (publication_fence,target_namespace," + + "canonical_tenant_id,canonical_version_id,publication_request_id,request_digest," + + "publish_workflow_id,freeze_version_state_epoch,applied_commit_id,content_digest," + + "digest_schema_version,outcome,publication_version_state_epoch," + + "published_release_bundle_ref,published_release_bundle_digest,operation_bytes," + + "terminal_evidence_bytes,terminal_evidence_digest,world_evidence_bytes,world_request_json," + + "selector_receipt_bytes,original_account_binding_bytes,applied_result_bytes,release_content_bytes) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + world.publicationFence(), + world.targetNamespace(), + world.canonicalTenantId(), + world.canonicalVersionId(), + world.publicationRequestId(), + world.requestDigest(), + world.publishWorkflowId(), + world.versionStateEpoch(), + world.appliedCommitId(), + world.contentDigest(), + world.digestSchemaVersion(), + request.evidence().outcome().name(), + request.publicationVersionStateEpoch(), + request.releaseBundleRef(), + request.releaseBundleDigest(), + request.operationBytes(), + request.terminalBytes(), + sha256Digest(request.terminalBytes()).substring("sha256:".length()), + request.worldEvidenceBytes(), + request.worldRequestJson(), + request.selectorReceiptBytes(), + request.originalAccountBindingBytes(), + request.appliedResultBytes(), + request.releaseContentBytes()); + } + + @Test + void canonicalLifecycleReadRejectsIncompleteOrSubstitutedRegionAssignments() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var firstRegion = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT ri.id AS region_row_id,ri.tenant_id,ri.game_instance_id,ri.world_instance_id," + + "ri.shard_id,ri.name,ri.weather,ri.generation_seed,ri.generator_type," + + "ri.generator_params,ri.spacing_multiplier,ri.version," + + "ri.canonical_region_instance_id,ri.operational_region_id," + + "m.id AS mapping_id,m.canonical_game_instance_id,m.family,m.template_id," + + "m.template_private_row_key,m.runtime_row_id,m.runtime_identity," + + "m.runtime_room_instance_id " + + "FROM region_instance ri JOIN world_canonical_instance_topology_identity m " + + "ON m.runtime_row_id=ri.id AND m.family='REGION' " + + "WHERE m.canonical_game_instance_id=? ORDER BY m.template_id LIMIT 1", + fixture.input().canonicalGameInstanceId())); + long regionRowId = required(firstRegion, "region_row_id", Long.class); + long mappingId = required(firstRegion, "mapping_id", Long.class); + UUID originalOperationalId = required(firstRegion, "operational_region_id", UUID.class); + UUID originalRuntimeIdentity = required(firstRegion, "runtime_identity", UUID.class); + + mutateWithUserTriggersDisabled( + "region_instance", + () -> + dsl.execute( + "UPDATE region_instance SET operational_region_id=NULL WHERE id=?", regionRowId)); + assertThatThrownBy(() -> fixture.lifecycleRepository().read(fixture.readRequest())) + .isInstanceOf( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException.class); + mutateWithUserTriggersDisabled( + "region_instance", + () -> + dsl.execute( + "UPDATE region_instance SET operational_region_id=? WHERE id=?", + originalOperationalId, + regionRowId)); + + UUID substitutedRuntimeIdentity = UUID.randomUUID(); + mutateWithUserTriggersDisabled( + "world_canonical_instance_topology_identity", + () -> + dsl.execute( + "UPDATE world_canonical_instance_topology_identity SET runtime_identity=? WHERE id=?", + substitutedRuntimeIdentity, + mappingId)); + assertThatThrownBy(() -> fixture.lifecycleRepository().read(fixture.readRequest())) + .isInstanceOf( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException.class); + mutateWithUserTriggersDisabled( + "world_canonical_instance_topology_identity", + () -> + dsl.execute( + "UPDATE world_canonical_instance_topology_identity SET runtime_identity=? WHERE id=?", + originalRuntimeIdentity, + mappingId)); + + mutateWithUserTriggersDisabled( + "world_canonical_instance_topology_identity", + () -> + dsl.execute( + "DELETE FROM world_canonical_instance_topology_identity WHERE id=?", mappingId)); + assertThatThrownBy(() -> fixture.lifecycleRepository().read(fixture.readRequest())) + .isInstanceOf( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException.class); + mutateWithUserTriggersDisabled( + "world_canonical_instance_topology_identity", + () -> + dsl.execute( + "INSERT INTO world_canonical_instance_topology_identity " + + "(world_instance_id,canonical_game_instance_id,family,template_id," + + "template_private_row_key,runtime_row_id,runtime_identity,runtime_room_instance_id) " + + "VALUES (?,?, 'REGION', ?,?,?,?,NULL)", + required(firstRegion, "world_instance_id", Long.class), + required(firstRegion, "canonical_game_instance_id", UUID.class), + required(firstRegion, "template_id", UUID.class), + required(firstRegion, "template_private_row_key", Long.class), + required(firstRegion, "runtime_row_id", Long.class), + originalRuntimeIdentity)); + + UUID extraCanonicalId = UUID.randomUUID(); + UUID extraOperationalId = UUID.randomUUID(); + while (extraCanonicalId.equals(extraOperationalId)) { + extraOperationalId = UUID.randomUUID(); + } + final UUID finalExtraOperationalId = extraOperationalId; + Record extraRegion = + queryWithUserTriggersDisabled( + "region_instance", + () -> + dsl.fetchOne( + "INSERT INTO region_instance " + + "(tenant_id,game_instance_id,world_instance_id,shard_id,name,weather," + + "generation_seed,generator_type,generator_params,spacing_multiplier,version," + + "canonical_region_instance_id,operational_region_id) " + + "SELECT tenant_id,game_instance_id,world_instance_id,shard_id,name,weather," + + "generation_seed,generator_type,generator_params,spacing_multiplier,version,?,? " + + "FROM region_instance WHERE id=? RETURNING id", + extraCanonicalId, + finalExtraOperationalId, + regionRowId)); + long extraRegionRowId = required(extraRegion, "id", Long.class); + assertThatThrownBy(() -> fixture.lifecycleRepository().read(fixture.readRequest())) + .isInstanceOf( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException.class); + mutateWithUserTriggersDisabled( + "region_instance", + () -> dsl.execute("DELETE FROM region_instance WHERE id=?", extraRegionRowId)); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(fixture.preparing()); + } + + @Test + void + lifecycleReadPreservesPreparingStateAndDeniesLegacyNumericFailureWithExactCanonicalServiceEcho() { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var roomTemplateId = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var application = withStartRoom(original, roomTemplateId); + appliedComponent().apply(application); + var frozen = capture(application.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var preparation = preparationComponent(preparationRepository()); + var materialized = preparation.prepare(input); + var associationRepository = associationRepository(); + var lifecycleRepository = + new WorldCanonicalInstanceLifecycleReadRepository(dsl, manager, associationRepository); + var request = lifecycleReadRequest(input); + + var preparing = lifecycleRepository.read(request).orElseThrow(); + assertThat(preparing.request()).isEqualTo(request); + assertThat(preparing.startLocation()) + .isEqualTo( + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) + .startLocation()); + assertThat(preparing.startLocation().roomTemplateId()).isEqualTo(roomTemplateId); + assertThat(preparing.runtimeRoomInstanceId()).isEqualTo(materialized.runtimeRoomInstanceId()); + assertThat(preparing.operationalRegionAssignments()) + .containsExactlyEntriesOf( + materializedOperationalRegionAssignments(input.canonicalGameInstanceId())); + var mappedRoomOwnership = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT r.tenant_id AS room_tenant_id,r.game_instance_id AS room_game_instance_id," + + "ri.tenant_id AS region_tenant_id,ri.game_instance_id AS region_game_instance_id," + + "ri.world_instance_id FROM world_canonical_instance_topology_identity m " + + "JOIN room_instance r ON r.id=m.runtime_row_id " + + "JOIN region_instance ri ON ri.id=r.region_instance_id " + + "WHERE m.world_instance_id=? AND m.canonical_game_instance_id=? AND m.family='ROOM' AND m.template_id=?", + materialized.association().worldInstanceId(), + input.canonicalGameInstanceId(), + roomTemplateId)); + assertThat(mappedRoomOwnership.get("room_tenant_id", Long.class)) + .isEqualTo(materialized.association().worldPrepareFields().privateTenantKey()); + assertThat(mappedRoomOwnership.get("room_game_instance_id", Long.class)) + .isEqualTo(materialized.association().worldPrepareFields().privateGameInstanceKey()); + assertThat(mappedRoomOwnership.get("region_tenant_id", Long.class)) + .isEqualTo(materialized.association().worldPrepareFields().privateTenantKey()); + assertThat(mappedRoomOwnership.get("region_game_instance_id", Long.class)) + .isEqualTo(materialized.association().worldPrepareFields().privateGameInstanceKey()); + assertThat(mappedRoomOwnership.get("world_instance_id", Long.class)) + .isEqualTo(materialized.association().worldInstanceId()); + assertThat(preparing.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(preparing.lifecycleEpoch()).isEqualTo(1L); + assertThat(preparing.captureId()).isEqualTo(input.captureId()); + assertThat(preparing.graphSha256()).isEqualTo(materialized.graphSha256()); + assertThat(preparing.preparationInputDigest()).isEqualTo(materialized.inputDigest()); + + TransactionTemplate ownerSnapshot = new TransactionTemplate(manager); + ownerSnapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerSnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownerSnapshot.setReadOnly(true); + ownerSnapshot.execute( + status -> { + assertThatThrownBy( + () -> + associationRepository.readOwnerAssociation(request.canonicalGameInstanceId())) + .hasMessageContaining("independent committed owner read"); + assertThatThrownBy( + () -> + new WorldCompleteLaunchBindingRepository(dsl) + .read( + input.gameSessionReadEvidence().targetNamespace(), + input.gameSessionReadEvidence().canonicalTenantId(), + input.gameSessionReadEvidence().controlPlaneRequestId())) + .hasMessageContaining("independent committed owner read"); + assertThatThrownBy( + () -> + new WorldAuthoredSourceIntakeRepository(dsl) + .read( + input.gameSessionReadEvidence().targetNamespace(), + input.versionIdentity().sourceIntakeReceipt().intakeRequestId())) + .hasMessageContaining("committed-outcome owner read"); + assertThatThrownBy( + () -> + new WorldAuthoredVersionIdentityRepository(dsl) + .readByCanonicalVersion( + input.gameSessionReadEvidence().targetNamespace(), + input.gameSessionReadEvidence().canonicalTenantId(), + input.gameSessionReadEvidence().worldSlug(), + input.versionIdentity().canonicalVersionId())) + .hasMessageContaining("independent committed owner read"); + assertThat( + associationRepository.readOwnerAssociationInOwnerTransaction( + request.canonicalGameInstanceId())) + .isPresent(); + return null; + }); + + assertThat( + lifecycleRepository + .read( + lifecycleReadRequest( + input, + "other", + request.canonicalTenantId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest())) + .isEmpty()) + .isTrue(); + assertThat( + lifecycleRepository + .read( + lifecycleReadRequest( + input, + NAMESPACE, + UUID.randomUUID(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest())) + .isEmpty()) + .isTrue(); + assertThat( + lifecycleRepository + .read( + lifecycleReadRequest( + input, + NAMESPACE, + request.canonicalTenantId(), + UUID.randomUUID(), + request.expectedDescriptorRequestDigest())) + .isEmpty()) + .isTrue(); + assertThat( + lifecycleRepository + .read( + lifecycleReadRequest( + input, + NAMESPACE, + request.canonicalTenantId(), + request.canonicalVersionId(), + "sha256:" + "d".repeat(64))) + .isEmpty()) + .isTrue(); + assertThat( + lifecycleRepository + .read( + lifecycleReadRequest( + input, + NAMESPACE, + request.canonicalTenantId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + "sha256:" + "e".repeat(64))) + .isEmpty()) + .isTrue(); + + var prepareFields = materialized.association().worldPrepareFields(); + // Successful ACTIVE epoch movement and replay while ACTIVE belong to + // canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDenied. Replay after + // canonical termination remains unavailable until this slice has a canonical termination + // owner operation. This front's legacy numeric writer remains denied for reserved tenants. + assertThatThrownBy( + () -> + lifecycleCommandService.failPreparedWorldInstance( + prepareFields.privateTenantKey(), + prepareFields.privateGameInstanceKey(), + preparing.lifecycleEpoch(), + "integration lifecycle read movement")) + .hasStackTraceContaining("no exact transaction execution manifest"); + var afterDeniedFailure = lifecycleRepository.read(request).orElseThrow(); + assertThat(afterDeniedFailure).isEqualTo(preparing); + + // The real V35 retry preserves immutable preparation history and does not rewrite lifecycle. + assertThat(preparation.prepare(input)).isEqualTo(materialized); + var afterRetry = lifecycleRepository.read(request).orElseThrow(); + assertThat(afterRetry).isEqualTo(preparing); + + // Explicitly injected peer identity is a transport double; this does not prove production mTLS. + var adapter = + new WorldCanonicalInstanceLifecycleReadGrpcService(lifecycleRepository, NAMESPACE); + var response = new LifecycleReadCollector(); + Context context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service", + NAMESPACE, + "game-session-service")); + Context previous = context.attach(); + try { + adapter.readWorldCanonicalInstanceLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request), response); + } finally { + context.detach(previous); + } + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat(WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(request, response.value)) + .isEqualTo(afterRetry); + assertOrigin(); + } + + @Test + void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDenied() + throws Exception { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var retainedEpochs = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT v.version_state_state AS source_version_state, " + + "p.input_json::JSONB->'versionIdentity'->>'versionState' AS input_version_state, " + + "v.version_state_epoch AS source_version_state_epoch, " + + "p.input_json::JSONB->'versionIdentity'->>'versionStateEpoch' AS input_version_state_epoch, " + + "b.descriptor_json::JSONB->>'versionStateEpoch' AS descriptor_version_state_epoch, " + + "b.release_attestation_json::JSONB->>'versionStateEpoch' AS release_version_state_epoch, " + + "a.version_state_epoch AS association_version_state_epoch " + + "FROM world_canonical_instance_association a " + + "JOIN world_authored_version_identity v ON v.operation_id=a.version_identity_operation_id " + + "JOIN world_complete_launch_binding b ON b.binding_operation_id=a.canonical_launch_binding_operation_id " + + "JOIN world_canonical_instance_preparation p ON p.canonical_game_instance_id=a.canonical_game_instance_id " + + "WHERE a.canonical_game_instance_id=?", + fixture.input().canonicalGameInstanceId())); + assertThat(retainedEpochs.get("source_version_state", String.class)).isEqualTo("DRAFT"); + assertThat(retainedEpochs.get("input_version_state", String.class)) + .isEqualTo("VERSION_LIFECYCLE_STATE_DRAFT"); + assertThat(retainedEpochs.get("source_version_state_epoch", Long.class)).isEqualTo(1L); + assertThat(retainedEpochs.get("input_version_state_epoch", String.class)).isEqualTo("1"); + assertThat(retainedEpochs.get("descriptor_version_state_epoch", String.class)).isEqualTo("2"); + assertThat(retainedEpochs.get("release_version_state_epoch", String.class)).isEqualTo("2"); + assertThat(retainedEpochs.get("association_version_state_epoch", Long.class)).isEqualTo(2L); + byte[] preparationBefore = preparationRows(fixture.input().canonicalGameInstanceId()); + var rawCommitProof = rawCommittedActivationProof(fixture); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + insertRawActivationOperation( + rawCommitProof, + fixture.materialized().association().worldInstanceId()); + return null; + })) + .hasMessageContaining("must include its exact ACTIVE lifecycle CAS before commit"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + rawCommitProof.request().activationRequestId())) + .get(0, Long.class)) + .isZero(); + assertThat(activationManifestCountForRequest(rawCommitProof.request().activationRequestId())) + .isZero(); + + var first = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var second = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + CountDownLatch bothAuthoritiesChecked = new CountDownLatch(2); + AtomicInteger verifierCalls = new AtomicInteger(); + var service = + canonicalActivationService( + fixture, + request -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + verifierCalls.incrementAndGet(); + bothAuthoritiesChecked.countDown(); + await(bothAuthoritiesChecked); + return stipulatedActivationAuthority(); + }); + ExecutorService executor = Executors.newFixedThreadPool(2); + WorldCanonicalInstanceActivation.Result firstResult; + WorldCanonicalInstanceActivation.Result secondResult; + try { + Future firstFuture = + executor.submit(() -> service.activate(first)); + Future secondFuture = + executor.submit(() -> service.activate(second)); + firstResult = firstFuture.get(45, TimeUnit.SECONDS); + secondResult = secondFuture.get(45, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + } + + assertThat(verifierCalls).hasValue(2); + assertThat(List.of(firstResult.outcome(), secondResult.outcome())) + .containsExactlyInAnyOrder( + WorldCanonicalInstanceActivation.Outcome.COMMITTED, + WorldCanonicalInstanceActivation.Outcome.ABORTED); + var committed = + firstResult.outcome() == WorldCanonicalInstanceActivation.Outcome.COMMITTED + ? firstResult + : secondResult; + var aborted = committed == firstResult ? secondResult : firstResult; + assertThat(committed.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(committed.lifecycleEvidence().lifecycleEpoch()) + .isEqualTo(fixture.preparing().lifecycleEpoch() + 1L); + assertThat(committed.lifecycleEvidence().rowVersion()) + .isEqualTo(fixture.preparing().rowVersion() + 1L); + assertThat(aborted.terminalCode()).isEqualTo("PRECONDITION_FAILED"); + var active = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(active.lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(active.lifecycleEpoch()).isEqualTo(committed.lifecycleEvidence().lifecycleEpoch()); + assertThat(active.rowVersion()).isEqualTo(committed.lifecycleEvidence().rowVersion()); + assertThat(active.operationalRegionAssignments()) + .containsExactlyEntriesOf(fixture.preparing().operationalRegionAssignments()); + assertThat(committed.lifecycleEvidence().operationalRegionAssignments()) + .containsExactlyEntriesOf(fixture.preparing().operationalRegionAssignments()); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + + var repository = + new WorldCanonicalInstanceActivationRepository(dsl, manager, fixture.lifecycleRepository()); + assertThat(repository.readResult(committed.request()).orElseThrow().canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + int callsAfterFirstAttempt = verifierCalls.get(); + assertThat(service.activate(committed.request()).canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + assertThat(verifierCalls).hasValue(callsAfterFirstAttempt); + var changedExpectedVersion = + new WorldCanonicalInstanceLifecycleEvidence( + fixture.preparing().request(), + fixture.preparing().launchBinding(), + fixture.preparing().startLocation(), + fixture.preparing().runtimeRoomInstanceId(), + "PREPARING", + fixture.preparing().lifecycleEpoch(), + fixture.preparing().rowVersion() + 1L, + fixture.preparing().captureId(), + fixture.preparing().graphSha256(), + fixture.preparing().preparationInputDigest(), + fixture.preparing().operationalRegionAssignments()); + var changedRetry = + new WorldCanonicalInstanceActivation.Request( + committed.request().activationRequestId(), changedExpectedVersion); + assertThatThrownBy(() -> service.activate(changedRetry)) + .isInstanceOf(WorldCanonicalInstanceActivationRepository.ActivationConflictException.class) + .hasMessageContaining("reused with changed immutable bindings"); + assertThat(verifierCalls).hasValue(callsAfterFirstAttempt); + + // The single-use activation capability was consumed; its retained ledger cannot authorize a + // second raw lifecycle update. + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + + "row_version=row_version+1 WHERE id=?", + fixture.materialized().association().worldInstanceId())) + .hasMessageContaining("no exact transaction execution manifest"); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + + var privateKeys = fixture.materialized().association().worldPrepareFields(); + assertThatThrownBy( + () -> + lifecycleCommandService.terminateWorldInstance( + privateKeys.privateTenantKey(), + privateKeys.privateGameInstanceKey(), + active.lifecycleEpoch(), + "activation-replay-terminal-move", + "integration lifecycle movement")) + .hasMessageContaining("no exact transaction execution manifest"); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(active); + assertThat(service.activate(committed.request()).canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + assertThat(verifierCalls).hasValue(callsAfterFirstAttempt); + assertThat(preparationRows(fixture.input().canonicalGameInstanceId())) + .containsExactly(preparationBefore); + assertOrigin(); + } + + @Test + void canonicalActivationRawSqlRejectsIncompleteOrSubstitutedOperationalRegionAssignments() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var assignments = fixture.preparing().operationalRegionAssignments(); + assertThat(assignments).isNotEmpty().hasSize(1); + var first = assignments.entrySet().iterator().next(); + + Map missing = new LinkedHashMap<>(assignments); + missing.remove(first.getKey()); + UUID missingCanonicalId = UUID.randomUUID(); + while (assignments.containsKey(missingCanonicalId) + || assignments.containsValue(missingCanonicalId)) { + missingCanonicalId = UUID.randomUUID(); + } + missing.put(missingCanonicalId, first.getValue()); + Map extra = new LinkedHashMap<>(assignments); + UUID extraCanonicalId = UUID.randomUUID(); + while (assignments.containsKey(extraCanonicalId) + || assignments.containsValue(extraCanonicalId)) { + extraCanonicalId = UUID.randomUUID(); + } + UUID extraOperationalId = UUID.randomUUID(); + while (assignments.containsKey(extraOperationalId) + || assignments.containsValue(extraOperationalId) + || extraCanonicalId.equals(extraOperationalId)) { + extraOperationalId = UUID.randomUUID(); + } + extra.put(extraCanonicalId, extraOperationalId); + Map substituted = new LinkedHashMap<>(assignments); + UUID substitutedOperationalId = UUID.randomUUID(); + while (assignments.containsKey(substitutedOperationalId) + || assignments.containsValue(substitutedOperationalId) + || first.getKey().equals(substitutedOperationalId)) { + substitutedOperationalId = UUID.randomUUID(); + } + substituted.put(first.getKey(), substitutedOperationalId); + + ownerTransaction() + .execute( + status -> { + int index = 0; + for (Map invalidAssignments : List.of(missing, extra, substituted)) { + var proof = rawCommittedActivationProofWithAssignments(fixture, invalidAssignments); + String savepoint = "invalid_activation_region_map_" + index++; + dsl.execute("SAVEPOINT " + savepoint); + assertThatThrownBy( + () -> + insertRawActivationOperation( + proof, fixture.materialized().association().worldInstanceId())) + .hasMessageContaining("exact complete operational REGION assignment map"); + dsl.execute("ROLLBACK TO SAVEPOINT " + savepoint); + assertThat( + activationOperationCountForRequest(proof.request().activationRequestId())) + .isZero(); + assertThat(activationManifestCountForRequest(proof.request().activationRequestId())) + .isZero(); + } + return null; + }); + + var retained = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(retained.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(retained.operationalRegionAssignments()).containsExactlyEntriesOf(assignments); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + assertOrigin(); + } + + @Test + void canonicalActivationTransportRequiresGameSessionAndReplaysImmutableOwnerResult() + throws Exception { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var alternatePreparing = + fixture + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(fixture.preparing().request())) + .orElseThrow(); + assertThat(alternatePreparing.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(alternatePreparing.request().readRequestId()) + .isNotEqualTo(fixture.preparing().request().readRequestId()); + + UUID activationRequestId = UUID.randomUUID(); + var originalRequest = + new WorldCanonicalInstanceActivation.Request(activationRequestId, fixture.preparing()); + var equivalentRetry = + new WorldCanonicalInstanceActivation.Request(activationRequestId, alternatePreparing); + assertThat(equivalentRetry.canonicalRequestBytes()) + .containsExactly(originalRequest.canonicalRequestBytes()); + assertThat( + Arrays.equals( + equivalentRetry.preparingEvidenceBytes(), originalRequest.preparingEvidenceBytes())) + .isFalse(); + + // This isolated fixture stipulates upstream held source/release/Account authority only; it is + // not live Account authorization. The socket independently proves Game Session mTLS identity, + // while World performs the actual lifecycle CAS and immutable operation write. + AtomicInteger authorityChecks = new AtomicInteger(); + var activationService = + canonicalActivationService( + fixture, + ignored -> { + authorityChecks.incrementAndGet(); + return stipulatedActivationAuthority(); + }); + var adapter = new WorldCanonicalInstanceActivationGrpcService(activationService, NAMESPACE); + WorldPreparationTestWorkloadPki pki = + WorldPreparationTestWorkloadPki.create(temporaryDirectory); + Server transport = startActivationTransport(adapter, pki); + byte[] preparationBefore = preparationRows(fixture.input().canonicalGameInstanceId()); + var wireRequest = activationTransportRequest(originalRequest); + try { + try (var wrongPeer = + activationTransportClient(transport, pki.clientProperties(WRONG_WORKLOAD_URI))) { + assertThatThrownBy(() -> wrongPeer.activate(wireRequest)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(((StatusRuntimeException) error).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + assertThat(authorityChecks).hasValue(0); + assertThat(activationOperationCountForRequest(activationRequestId)).isZero(); + assertThat(activationManifestCountForRequest(activationRequestId)).isZero(); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(fixture.preparing()); + assertThat(preparationRows(fixture.input().canonicalGameInstanceId())) + .containsExactly(preparationBefore); + + try (var gameSession = + activationTransportClient(transport, pki.clientProperties(GAME_SESSION_WORKLOAD_URI))) { + var firstResponse = gameSession.activate(wireRequest); + assertThat(firstResponse.getActivationRequestId()) + .isEqualTo(activationRequestId.toString()); + byte[] immutableResultBytes = firstResponse.getCanonicalResultBytes().toByteArray(); + var firstResult = WorldCanonicalInstanceActivation.Result.fromStored(immutableResultBytes); + assertThat(firstResult.outcome()) + .isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + assertThat(firstResult.request().canonicalRequestBytes()) + .containsExactly(originalRequest.canonicalRequestBytes()); + assertThat(firstResult.request().preparingEvidenceBytes()) + .containsExactly(originalRequest.preparingEvidenceBytes()); + assertThat(firstResult.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(firstResult.lifecycleEvidence().lifecycleEpoch()) + .isEqualTo(fixture.preparing().lifecycleEpoch() + 1L); + assertThat(firstResult.lifecycleEvidence().rowVersion()) + .isEqualTo(fixture.preparing().rowVersion() + 1L); + assertThat(authorityChecks).hasValue(1); + assertThat(activationOperationCountForRequest(activationRequestId)).isEqualTo(1L); + assertThat(activationManifestCountForRequest(activationRequestId)).isZero(); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + var storedResult = + new WorldCanonicalInstanceActivationRepository( + dsl, manager, fixture.lifecycleRepository()) + .readResult(originalRequest) + .orElseThrow(); + assertThat(storedResult.canonicalBytes()).containsExactly(immutableResultBytes); + + // A separate owner read with fresh correlation establishes current ACTIVE state; the + // immutable activation result remains the historical operation result. + var current = + fixture + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(fixture.readRequest())) + .orElseThrow(); + assertThat(current.lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(current.lifecycleEpoch()) + .isEqualTo(firstResult.lifecycleEvidence().lifecycleEpoch()); + assertThat(current.rowVersion()).isEqualTo(firstResult.lifecycleEvidence().rowVersion()); + assertThat(current.request().readRequestId()) + .isNotEqualTo(firstResult.lifecycleEvidence().request().readRequestId()); + + var exactRetry = gameSession.activate(wireRequest); + assertThat(exactRetry.getCanonicalResultBytes().toByteArray()) + .containsExactly(immutableResultBytes); + var alternateCorrelationRetry = + gameSession.activate(activationTransportRequest(equivalentRetry)); + assertThat(alternateCorrelationRetry.getCanonicalResultBytes().toByteArray()) + .containsExactly(immutableResultBytes); + assertThat(authorityChecks).hasValue(1); + assertThat( + WorldCanonicalInstanceActivation.Result.fromStored( + alternateCorrelationRetry.getCanonicalResultBytes().toByteArray()) + .request() + .preparingEvidenceBytes()) + .containsExactly(originalRequest.preparingEvidenceBytes()); + + var changedExpectedVersion = + new WorldCanonicalInstanceLifecycleEvidence( + fixture.preparing().request(), + fixture.preparing().launchBinding(), + fixture.preparing().startLocation(), + fixture.preparing().runtimeRoomInstanceId(), + "PREPARING", + fixture.preparing().lifecycleEpoch(), + fixture.preparing().rowVersion() + 1L, + fixture.preparing().captureId(), + fixture.preparing().graphSha256(), + fixture.preparing().preparationInputDigest(), + fixture.preparing().operationalRegionAssignments()); + // Reusing the same operation ID with a changed normalized expected version is a conflict + // probe, not evidence that the persisted PREPARING row had that version. + var changedRequest = + new WorldCanonicalInstanceActivation.Request( + activationRequestId, changedExpectedVersion); + assertThatThrownBy(() -> gameSession.activate(activationTransportRequest(changedRequest))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(((StatusRuntimeException) error).getStatus().getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); + assertThat(authorityChecks).hasValue(1); + assertThat(activationOperationCountForRequest(activationRequestId)).isEqualTo(1L); + assertThat(activationManifestCountForRequest(activationRequestId)).isZero(); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + var afterConflict = + fixture + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(fixture.readRequest())) + .orElseThrow(); + assertThat(afterConflict.lifecycleStatus()).isEqualTo(current.lifecycleStatus()); + assertThat(afterConflict.lifecycleEpoch()).isEqualTo(current.lifecycleEpoch()); + assertThat(afterConflict.rowVersion()).isEqualTo(current.rowVersion()); + assertThat(afterConflict.request().canonicalGameInstanceId()) + .isEqualTo(current.request().canonicalGameInstanceId()); + } + } finally { + transport.shutdownNow(); + assertThat(transport.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + assertThat(preparationRows(fixture.input().canonicalGameInstanceId())) + .containsExactly(preparationBefore); + assertOrigin(); + } + + @Test + void canonicalActivationStoresStaleFailedOutcomeAndFreshLifecycleReadRemainsCurrent() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var service = canonicalActivationService(fixture, ignored -> stipulatedActivationAuthority()); + var firstRequest = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var current = service.activate(firstRequest); + assertThat(current.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + assertThat(current.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); + var staleRequest = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + + var aborted = service.activate(staleRequest); + + assertThat(aborted.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.ABORTED); + assertThat(aborted.terminalCode()).isEqualTo("PRECONDITION_FAILED"); + assertThat(aborted.lifecycleEvidence().canonicalBytes()) + .containsExactly(current.lifecycleEvidence().canonicalBytes()); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(current.lifecycleEvidence()); + assertThat(service.activate(staleRequest).canonicalBytes()) + .containsExactly(aborted.canonicalBytes()); + assertThat(activationOperationCountForRequest(staleRequest.activationRequestId())) + .isEqualTo(1L); + assertThat(activationManifestCountForRequest(staleRequest.activationRequestId())).isZero(); + assertOrigin(); + } + + @Test + void canonicalInitialAdmissionHoldAcquiresFromRealActiveLifecycleAndRetainsPendingIdentity() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + // World storage/CAS is real; upstream activation authority remains an isolated fixture. + var activation = + canonicalActivationService(fixture, ignored -> stipulatedActivationAuthority()) + .activate( + new WorldCanonicalInstanceActivation.Request( + UUID.randomUUID(), fixture.preparing())); + assertThat(activation.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + assertThat(activation.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); + + var active = + fixture + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(activation.lifecycleEvidence().request())) + .orElseThrow(); + assertThat(active.lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(active.lifecycleEpoch()).isEqualTo(activation.lifecycleEvidence().lifecycleEpoch()); + assertThat(active.rowVersion()).isEqualTo(activation.lifecycleEvidence().rowVersion()); + + UUID realmId = UUID.randomUUID(); + String requestId = "canonical-admission-" + UUID.randomUUID(); + Request request = + new Request( + active.request().targetNamespace(), + active.request().canonicalTenantId(), + active.request().worldSlug(), + realmId, + active.request().playableStateNamespaceId(), + active.request().playableStateScope(), + active.request().canonicalGameInstanceId(), + active.request().canonicalVersionId(), + active.lifecycleEpoch(), + requestId, + "a".repeat(64), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + var repository = + new WorldCanonicalInitialAdmissionHoldRepository( + dsl, manager, associationRepository(), fixture.lifecycleRepository()); + + var acquired = repository.acquire(request, active.request()); + assertThat(acquired.request()).isEqualTo(request); + assertThat(acquired.canonicalRequestBytes()).containsExactly(request.canonicalRequestBytes()); + assertThat(acquired.holdBindingDigest()).isEqualTo(request.holdBindingDigest()); + + var stored = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(h)::text AS retained_row, h.hold_id, h.hold_fence, h.tenant_id, " + + "h.realm_uuid, h.playable_state_namespace_uuid, h.playable_state_scope, " + + "h.game_instance_id, h.version_id, h.active_lifecycle_epoch, " + + "h.initial_admission_request_id, h.request_digest, " + + "h.expected_no_prior_pointer, h.expected_catalog_revision, h.status, " + + "h.canonical_target_namespace, h.canonical_tenant_id, h.canonical_world_slug, " + + "h.canonical_game_instance_id, h.canonical_version_id, " + + "h.initial_admission_origin, h.expected_prior_pointer_version, " + + "h.canonical_request_bytes, h.hold_binding_digest, h.row_version, " + + "(h.diagnostic_expires_at <= CURRENT_TIMESTAMP) AS diagnostic_due " + + "FROM initial_admission_bind_hold h WHERE h.tenant_id = ? " + + "AND h.initial_admission_request_id = ?", + fixture.materialized().association().worldPrepareFields().privateTenantKey(), + requestId)); + var privateKeys = fixture.materialized().association().worldPrepareFields(); + assertThat(stored.get("hold_id", UUID.class)).isEqualTo(acquired.holdId()); + assertThat(stored.get("hold_fence", UUID.class)).isEqualTo(acquired.holdFence()); + assertThat(stored.get("tenant_id", Long.class)).isEqualTo(privateKeys.privateTenantKey()); + assertThat(stored.get("game_instance_id", Long.class)) + .isEqualTo(privateKeys.privateGameInstanceKey()); + assertThat(stored.get("version_id", Long.class)).isEqualTo(privateKeys.localVersionKey()); + assertThat(stored.get("realm_uuid", UUID.class)).isEqualTo(request.realmId()); + assertThat(stored.get("playable_state_namespace_uuid", UUID.class)) + .isEqualTo(request.playableStateNamespaceId()); + assertThat(stored.get("playable_state_scope", String.class)) + .isEqualTo(request.playableStateScope()); + assertThat(stored.get("active_lifecycle_epoch", Long.class)) + .isEqualTo(request.activeLifecycleEpoch()); + assertThat(stored.get("initial_admission_request_id", String.class)) + .isEqualTo(request.initialAdmissionRequestId()); + assertThat(stored.get("request_digest", String.class)) + .isEqualTo(request.initialAdmissionRequestDigest()); + assertThat(stored.get("expected_no_prior_pointer", Boolean.class)).isTrue(); + assertThat(stored.get("expected_catalog_revision", Long.class)) + .isEqualTo(request.expectedCatalogRevision()); + assertThat(stored.get("canonical_target_namespace", String.class)) + .isEqualTo(request.targetNamespace()); + assertThat(stored.get("canonical_tenant_id", UUID.class)) + .isEqualTo(request.canonicalTenantId()); + assertThat(stored.get("canonical_world_slug", String.class)).isEqualTo(request.worldSlug()); + assertThat(stored.get("canonical_game_instance_id", UUID.class)) + .isEqualTo(request.canonicalGameInstanceId()); + assertThat(stored.get("canonical_version_id", UUID.class)) + .isEqualTo(request.canonicalVersionId()); + assertThat(stored.get("initial_admission_origin", String.class)) + .isEqualTo(InitialAdmissionOrigin.NO_PRIOR_POINTER.name()); + assertThat(stored.get("expected_prior_pointer_version", Long.class)).isNull(); + assertThat(stored.get("canonical_request_bytes", byte[].class)) + .containsExactly(request.canonicalRequestBytes()); + assertThat(stored.get("hold_binding_digest", String.class)) + .isEqualTo(request.holdBindingDigest()); + assertThat(stored.get("status", String.class)).isEqualTo("PENDING"); + assertThat(stored.get("row_version", Long.class)).isZero(); + assertThat(stored.get("diagnostic_due", Boolean.class)).isTrue(); + + assertThat( + new WorldInstanceRepository(dsl) + .hasNonterminalInitialAdmissionBindHold( + privateKeys.privateTenantKey(), privateKeys.privateGameInstanceKey())) + .isTrue(); + assertThat( + new InitialAdmissionBindHoldRepository(dsl) + .hasNonterminalForRealm(privateKeys.privateTenantKey(), realmId.toString())) + .isTrue(); + + UUID closedRealmId = UUID.randomUUID(); + // Acquiring this tagged PENDING hold does not prove Game Session's never-OPEN origin. + Request expectClosedRequest = + new Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + closedRealmId, + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + request.activeLifecycleEpoch(), + "canonical-admission-closed-" + UUID.randomUUID(), + "b".repeat(64), + InitialAdmissionOrigin.EXPECT_CLOSED, + 2L, + 7L); + var expectClosed = repository.acquire(expectClosedRequest, active.request()); + assertThat(expectClosed.request()).isEqualTo(expectClosedRequest); + var storedExpectClosed = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT expected_no_prior_pointer, initial_admission_origin, " + + "expected_prior_pointer_version, canonical_request_bytes, " + + "hold_binding_digest FROM initial_admission_bind_hold " + + "WHERE tenant_id = ? AND initial_admission_request_id = ?", + privateKeys.privateTenantKey(), + expectClosedRequest.initialAdmissionRequestId())); + assertThat(storedExpectClosed.get("expected_no_prior_pointer", Boolean.class)).isFalse(); + assertThat(storedExpectClosed.get("initial_admission_origin", String.class)) + .isEqualTo(InitialAdmissionOrigin.EXPECT_CLOSED.name()); + assertThat(storedExpectClosed.get("expected_prior_pointer_version", Long.class)).isEqualTo(7L); + assertThat(storedExpectClosed.get("canonical_request_bytes", byte[].class)) + .containsExactly(expectClosedRequest.canonicalRequestBytes()); + assertThat(storedExpectClosed.get("hold_binding_digest", String.class)) + .isEqualTo(expectClosedRequest.holdBindingDigest()); + assertThat(repository.readIdentity(expectClosedRequest).orElseThrow().canonicalBytes()) + .containsExactly(expectClosed.canonicalBytes()); + + var identityReadback = repository.readIdentity(request).orElseThrow(); + assertThat(identityReadback.canonicalBytes()).containsExactly(acquired.canonicalBytes()); + assertThat( + WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored( + identityReadback.canonicalBytes())) + .isEqualTo(acquired); + + var retried = repository.acquire(request, active.request()); + assertThat(retried.canonicalBytes()).containsExactly(acquired.canonicalBytes()); + var afterRetry = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(h)::text AS retained_row FROM initial_admission_bind_hold h " + + "WHERE h.tenant_id = ? AND h.initial_admission_request_id = ?", + privateKeys.privateTenantKey(), + requestId)); + assertThat(afterRetry.get("retained_row", String.class)) + .isEqualTo(stored.get("retained_row", String.class)); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM initial_admission_bind_hold " + + "WHERE tenant_id = ? AND initial_admission_request_id = ?", + privateKeys.privateTenantKey(), + requestId)) + .get(0, Long.class)) + .isEqualTo(1L); + + Request changedBinding = + new Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + request.activeLifecycleEpoch(), + request.initialAdmissionRequestId(), + request.initialAdmissionRequestDigest(), + request.initialAdmissionOrigin(), + request.expectedCatalogRevision() + 1L, + request.expectedPriorPointerVersion()); + assertThatThrownBy(() -> repository.acquire(changedBinding, active.request())) + .isInstanceOf(WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException.class) + .hasMessageContaining("request identity was reused with changed bindings"); + assertThat(repository.readIdentity(request).orElseThrow().canonicalBytes()) + .containsExactly(acquired.canonicalBytes()); + assertThat( + new WorldInstanceRepository(dsl) + .hasNonterminalInitialAdmissionBindHold( + privateKeys.privateTenantKey(), privateKeys.privateGameInstanceKey())) + .isTrue(); + assertThat( + new InitialAdmissionBindHoldRepository(dsl) + .hasNonterminalForRealm(privateKeys.privateTenantKey(), realmId.toString())) + .isTrue(); + assertOrigin(); + } + + @Test + void canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas() + throws Exception { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var activationRequest = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + + var forgedPreparing = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(fixture.preparing().canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) forgedPreparing.get("request")) + .put("targetNamespace", "forged-world-namespace"); + byte[] forgedPreparingBytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(forgedPreparing)); + + var normalizedRequest = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(activationRequest.canonicalRequestBytes()); + var normalizedPreparing = + (tools.jackson.databind.node.ObjectNode) mapper.readTree(forgedPreparingBytes); + ((tools.jackson.databind.node.ObjectNode) normalizedPreparing.get("request")) + .remove("readRequestId"); + normalizedRequest.set("preparingEvidence", normalizedPreparing); + byte[] forgedRequestBytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(normalizedRequest)); + String forgedRequestDigest = sha256Digest(forgedRequestBytes); + + var forgedActive = + (tools.jackson.databind.node.ObjectNode) mapper.readTree(forgedPreparingBytes); + forgedActive.put("lifecycleStatus", "ACTIVE"); + forgedActive.put("lifecycleEpoch", Long.toString(fixture.preparing().lifecycleEpoch() + 1L)); + forgedActive.put("rowVersion", Long.toString(fixture.preparing().rowVersion() + 1L)); + byte[] forgedActiveBytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(forgedActive)); + + Map forgedResult = new LinkedHashMap<>(); + forgedResult.put("schema", "world-canonical-instance-activation-result/v1"); + forgedResult.put("activationRequestId", activationRequest.activationRequestId().toString()); + forgedResult.put("requestDigest", forgedRequestDigest); + forgedResult.put( + "requestBytesBase64", java.util.Base64.getEncoder().encodeToString(forgedRequestBytes)); + forgedResult.put( + "preparingEvidenceBytesBase64", + java.util.Base64.getEncoder().encodeToString(forgedPreparingBytes)); + forgedResult.put("outcome", "COMMITTED"); + forgedResult.put("terminalCode", null); + forgedResult.put( + "lifecycleEvidenceBytesBase64", + java.util.Base64.getEncoder().encodeToString(forgedActiveBytes)); + byte[] forgedResultBytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(forgedResult)); + + ownerTransaction() + .execute( + status -> { + dsl.execute("SAVEPOINT forged_world_activation"); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO world_canonical_instance_activation_operation " + + "(activation_request_id,request_digest,request_bytes,preparing_evidence_bytes," + + "canonical_game_instance_id,world_instance_id,expected_lifecycle_epoch,expected_row_version," + + "outcome,terminal_code,result_lifecycle_epoch,result_row_version,result_bytes,result_digest) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + activationRequest.activationRequestId(), + forgedRequestDigest, + forgedRequestBytes, + forgedPreparingBytes, + activationRequest.canonicalGameInstanceId(), + fixture.materialized().association().worldInstanceId(), + activationRequest.expectedLifecycleEpoch(), + activationRequest.expectedRowVersion(), + "COMMITTED", + null, + activationRequest.expectedLifecycleEpoch() + 1L, + activationRequest.expectedRowVersion() + 1L, + forgedResultBytes, + sha256Digest(forgedResultBytes))) + .hasMessageContaining("differs from immutable World association"); + dsl.execute("ROLLBACK TO SAVEPOINT forged_world_activation"); + // V35's reserved-tenant guard denies a raw write without an activation manifest. + dsl.execute("SAVEPOINT forged_active_cas"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + + "row_version=row_version+1 WHERE id=?", + fixture.materialized().association().worldInstanceId())) + .hasMessageContaining("no exact transaction execution manifest"); + dsl.execute("ROLLBACK TO SAVEPOINT forged_active_cas"); + return null; + }); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + activationRequest.activationRequestId())) + .get(0, Long.class)) + .isZero(); + assertThat(activationManifestCountForRequest(activationRequest.activationRequestId())).isZero(); + var lifecycle = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(lifecycle.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(lifecycle.lifecycleEpoch()).isEqualTo(activationRequest.expectedLifecycleEpoch()); + assertThat(lifecycle.rowVersion()).isEqualTo(activationRequest.expectedRowVersion()); + assertOrigin(); + } + + @Test + void lostHeldAuthorityAfterOperationInsertRollsBackActivationAndLedger() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var request = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + AtomicBoolean lossInjectedAfterOperationInsert = new AtomicBoolean(); + var service = + canonicalActivationService( + fixture, + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) return; + long operationCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + request.activationRequestId())) + .get(0, Long.class); + long manifestCount = + activationManifestCountForRequest(request.activationRequestId()); + if (operationCount != 1L || manifestCount != 1L) return; + + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + var lifecycleRow = + dsl.fetchOne( + "SELECT status, lifecycle_epoch, row_version FROM world_instance WHERE id=?", + fixture.materialized().association().worldInstanceId()); + assertThat(lifecycleRow).isNotNull(); + assertThat(lifecycleRow.get("status", String.class)).isEqualTo("PREPARING"); + assertThat(lifecycleRow.get("lifecycle_epoch", Long.class)) + .isEqualTo(request.expectedLifecycleEpoch()); + assertThat(lifecycleRow.get("row_version", Long.class)) + .isEqualTo(request.expectedRowVersion()); + assertThat(operationCount).isEqualTo(1L); + assertThat(manifestCount).isEqualTo(1L); + lossInjectedAfterOperationInsert.set(true); + throw new IllegalStateException("stipulated activation authority loss"); + } + + public void close() {} + }; + }); + + assertThatThrownBy(() -> service.activate(request)) + .hasMessageContaining("stipulated activation authority loss"); + assertThat(lossInjectedAfterOperationInsert).isTrue(); + var current = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(current.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(current.lifecycleEpoch()).isEqualTo(fixture.preparing().lifecycleEpoch()); + assertThat(current.rowVersion()).isEqualTo(fixture.preparing().rowVersion()); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + request.activationRequestId())) + .get(0, Long.class)) + .isZero(); + assertThat(activationManifestCountForRequest(request.activationRequestId())).isZero(); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + assertOrigin(); + } + + @Test + void activationExecutionManifestRequiresExactTransactionInstanceAndRowSnapshots() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + String exactUpdate = + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + + "row_version=row_version+1,updated_at=CURRENT_TIMESTAMP WHERE id=?"; + + assertActivationManifestMismatch( + fixture, + "activation_manifest_wrong_tx", + "UPDATE world_canonical_activation_execution_manifest SET transaction_id=transaction_id+1 " + + "WHERE activation_request_id=?", + exactUpdate); + assertActivationManifestMismatch( + fixture, + "activation_manifest_wrong_instance", + "UPDATE world_canonical_activation_execution_manifest SET world_instance_id=world_instance_id+1 " + + "WHERE activation_request_id=?", + exactUpdate); + assertActivationManifestMismatch( + fixture, + "activation_manifest_extra_old_field", + "UPDATE world_canonical_activation_execution_manifest SET expected_old=expected_old || '{\"extra\":true}'::JSONB " + + "WHERE activation_request_id=?", + exactUpdate); + assertActivationManifestMismatch( + fixture, + "activation_manifest_extra_new_field", + "UPDATE world_canonical_activation_execution_manifest SET expected_new=expected_new || '{\"extra\":true}'::JSONB " + + "WHERE activation_request_id=?", + exactUpdate); + assertActivationManifestMismatch( + fixture, + "activation_manifest_wrong_next_epoch", + null, + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+2," + + "row_version=row_version+1,updated_at=CURRENT_TIMESTAMP WHERE id=?"); + assertActivationManifestMismatch( + fixture, + "activation_manifest_wrong_next_version", + null, + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + + "row_version=row_version+2,updated_at=CURRENT_TIMESTAMP WHERE id=?"); + + var current = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(current).isEqualTo(fixture.preparing()); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + assertOrigin(); + } + + @Test + void canonicalInitialPlayerLocationCommitsAndFreshCorrelationRetryReplaysOriginalEvidence() { + PlacementFixture fixture = initialPlayerLocationFixture(); + byte[] originalEvidence = fixture.request().originalLifecycleEvidenceBytes(); + + WorldCanonicalInitialPlayerLocation.Result first = fixture.service().place(fixture.request()); + + assertThat(first.outcome()).isEqualTo(WorldCanonicalInitialPlayerLocation.Outcome.APPLIED); + Record stored = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT canonical_tenant_id, canonical_account_id, character_id, " + + "entity_assignment_operation_id, entity_assignment_digest, canonical_version_id, " + + "active_lifecycle_epoch, initial_room_template_id, initial_runtime_room_instance_id, " + + "runtime_room_instance_id, initial_lifecycle_evidence_bytes, " + + "initial_lifecycle_evidence_digest, row_version FROM character_location " + + "WHERE canonical_game_instance_id=? AND playable_state_namespace_id=? AND character_id=?", + fixture.request().canonicalGameInstanceId(), + fixture.request().playableStateNamespaceId(), + fixture.request().characterId())); + assertThat(stored.get("canonical_tenant_id", UUID.class)) + .isEqualTo(fixture.request().canonicalTenantId()); + assertThat(stored.get("canonical_account_id", UUID.class)) + .isEqualTo(fixture.request().canonicalAccountId()); + assertThat(stored.get("entity_assignment_operation_id", UUID.class)) + .isEqualTo(fixture.request().entityAssignmentOperationId()); + assertThat(stored.get("entity_assignment_digest", String.class)) + .isEqualTo(fixture.request().entityAssignmentDigest()); + assertThat(stored.get("canonical_version_id", UUID.class)) + .isEqualTo(fixture.activeEvidence().request().canonicalVersionId()); + assertThat(stored.get("active_lifecycle_epoch", Long.class)) + .isEqualTo(fixture.activeEvidence().lifecycleEpoch()); + assertThat(stored.get("initial_room_template_id", UUID.class)) + .isEqualTo(fixture.activeEvidence().startLocation().roomTemplateId()); + assertThat(stored.get("initial_runtime_room_instance_id", Long.class)) + .isEqualTo(fixture.activeEvidence().runtimeRoomInstanceId()); + assertThat(stored.get("runtime_room_instance_id", Long.class)) + .isEqualTo(fixture.activeEvidence().runtimeRoomInstanceId()); + assertThat(stored.get("initial_lifecycle_evidence_bytes", byte[].class)) + .containsExactly(originalEvidence); + assertThat(stored.get("row_version", Long.class)).isZero(); + + Record operation = initialLocationOperation(fixture.request().operationId()); + assertThat(operation.get("request_digest", String.class)) + .isEqualTo(fixture.request().requestDigest()); + assertThat(operation.get("original_lifecycle_evidence_bytes", byte[].class)) + .containsExactly(originalEvidence); + assertThat(operation.get("result_bytes", byte[].class)).containsExactly(first.canonicalBytes()); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isEqualTo(1L); + + var freshEvidence = + fixture + .lifecycle() + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(fixture.activeEvidence().request())) + .orElseThrow(); + var exactRetryRequest = + initialLocationRequest( + fixture, + fixture.request().operationId(), + fixture.request().characterId(), + fixture.request().entityAssignmentOperationId(), + fixture.request().entityAssignmentDigest(), + freshEvidence); + assertThat(exactRetryRequest.requestDigest()).isEqualTo(fixture.request().requestDigest()); + WorldCanonicalInitialPlayerLocation.Result retry = fixture.service().place(exactRetryRequest); + + assertThat(retry.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat( + initialLocationOperation(fixture.request().operationId()) + .get("original_lifecycle_evidence_bytes", byte[].class)) + .containsExactly(originalEvidence); + Record locationAfterRetry = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT initial_lifecycle_evidence_bytes, row_version FROM character_location " + + "WHERE canonical_game_instance_id=? AND playable_state_namespace_id=? AND character_id=?", + fixture.request().canonicalGameInstanceId(), + fixture.request().playableStateNamespaceId(), + fixture.request().characterId()), + "Canonical initial location disappeared during exact retry"); + assertThat(locationAfterRetry.get("initial_lifecycle_evidence_bytes", byte[].class)) + .containsExactly(originalEvidence); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isEqualTo(1L); + assertOrigin(); + } + + @Test + void expectedClosedPlacementUsesExactNextPointerVersionFromStipulatedOwnerProof() { + PlacementFixture fixture = initialPlayerLocationFixture(InitialAdmissionOrigin.EXPECT_CLOSED); + + WorldCanonicalInitialPlayerLocation.Result placed = fixture.service().place(fixture.request()); + + assertThat(fixture.hold().request().initialAdmissionOrigin()) + .isEqualTo(InitialAdmissionOrigin.EXPECT_CLOSED); + assertThat(fixture.hold().request().expectedPriorPointerVersion()).isEqualTo(7L); + assertThat(fixture.ownerProof().committedPointerVersion()).isEqualTo(8L); + assertThat(fixture.request().initialAdmissionOrigin()) + .isEqualTo(WorldCanonicalInitialPlayerLocation.InitialAdmissionOrigin.EXPECT_CLOSED); + assertThat(fixture.request().pointerVersion()).isEqualTo(8L); + assertThat(placed.outcome()).isEqualTo(WorldCanonicalInitialPlayerLocation.Outcome.APPLIED); + assertOrigin(); + } + + @Test + void currentInitialPlayerLocationReadReturnsExactActorRoomRegionAndLifecycleProof() { + PlacementFixture fixture = initialPlayerLocationFixture(); + var placed = fixture.service().place(fixture.request()); + + var current = currentLocationReadService(fixture).read(fixture.request()).orElseThrow(); + + assertThat(current.binding().canonicalTenantId()) + .isEqualTo(fixture.request().canonicalTenantId()); + assertThat(current.binding().realmId()).isEqualTo(fixture.request().realmId()); + assertThat(current.binding().canonicalGameInstanceId()) + .isEqualTo(fixture.request().canonicalGameInstanceId()); + assertThat(current.binding().playableStateNamespaceId()) + .isEqualTo(fixture.request().playableStateNamespaceId()); + assertThat(current.binding().canonicalAccountId()) + .isEqualTo(fixture.request().canonicalAccountId()); + assertThat(current.binding().characterId()).isEqualTo(fixture.request().characterId()); + assertThat(current.binding().entityAssignmentOperationId()) + .isEqualTo(fixture.request().entityAssignmentOperationId()); + assertThat(current.binding().entityAssignmentDigest()) + .isEqualTo(fixture.request().entityAssignmentDigest()); + assertThat(current.currentLifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(current.currentLifecycleEvidence().lifecycleEpoch()) + .isEqualTo(fixture.activeEvidence().lifecycleEpoch()); + assertThat(current.worldInstanceId()) + .isEqualTo(fixture.lifecycle().materialized().association().worldInstanceId()); + assertThat(current.startLocation()).isEqualTo(fixture.activeEvidence().startLocation()); + assertThat(current.runtimeRoomInstanceId()) + .isEqualTo(fixture.activeEvidence().runtimeRoomInstanceId()); + assertThat(current.worldRegionInstanceId()).isPositive(); + assertThat(current.canonicalRegionInstanceId()).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(current.operationalRegionId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(current.canonicalRegionInstanceId()).isNotEqualTo(current.operationalRegionId()); + assertThat(current.placementResult().canonicalBytes()).containsExactly(placed.canonicalBytes()); + assertThat(current.originalLifecycleEvidenceBytes()) + .containsExactly(fixture.request().originalLifecycleEvidenceBytes()); + Record region = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT canonical_region_instance_id, operational_region_id " + + "FROM region_instance WHERE id=?", + current.worldRegionInstanceId())); + assertThat(region.get("canonical_region_instance_id", UUID.class)) + .isEqualTo(current.canonicalRegionInstanceId()); + assertThat(region.get("operational_region_id", UUID.class)) + .isEqualTo(current.operationalRegionId()); + assertThat(region.get("canonical_region_instance_id", UUID.class)) + .isNotEqualTo(region.get("operational_region_id", UUID.class)); + assertOrigin(); + } + + @Test + void currentInitialPlayerLocationReadReturnsAbsentOnlyAfterExactOwnerChecks() { + PlacementFixture fixture = initialPlayerLocationFixture(); + + assertThat(currentLocationReadService(fixture).read(fixture.request())).isEmpty(); + assertThat(countInitialLocationOperations(fixture.request().canonicalGameInstanceId())) + .isZero(); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isZero(); + assertOrigin(); + } + + @Test + void currentInitialPlayerLocationReadRejectsDanglingAppliedReceipt() { + PlacementFixture fixture = initialPlayerLocationFixture(); + fixture.service().place(fixture.request()); + dsl.execute( + "DELETE FROM character_location WHERE canonical_game_instance_id=? " + + "AND playable_state_namespace_id=? AND character_id=?", + fixture.request().canonicalGameInstanceId(), + fixture.request().playableStateNamespaceId(), + fixture.request().characterId()); + + assertThatThrownBy(() -> currentLocationReadService(fixture).read(fixture.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("retained APPLIED operation has no exact current location row"); + assertThat(countInitialLocationOperations(fixture.request().canonicalGameInstanceId())) + .isEqualTo(1L); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isZero(); + assertOrigin(); + } + + @Test + void currentInitialPlayerLocationReadDeniesChangedActorScopeOrAssignment() { + PlacementFixture fixture = initialPlayerLocationFixture(); + fixture.service().place(fixture.request()); + var reader = currentLocationReadService(fixture); + String locationBefore = initialLocationSnapshot(fixture.request().canonicalGameInstanceId()); + Record operationBefore = initialLocationOperation(fixture.request().operationId()); + + var changedActor = + initialLocationRequest( + fixture, + fixture.request().operationId(), + UUID.randomUUID(), + fixture.request().entityAssignmentOperationId(), + fixture.request().entityAssignmentDigest(), + fixture.activeEvidence()); + assertThatThrownBy(() -> reader.read(changedActor)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "World operation result differs from its exact request or retained proof"); + + var changedAssignment = + initialLocationRequest( + fixture, + fixture.request().operationId(), + fixture.request().characterId(), + UUID.randomUUID(), + "b".repeat(64), + fixture.activeEvidence()); + assertThatThrownBy(() -> reader.read(changedAssignment)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "World operation result differs from its exact request or retained proof"); + + var original = fixture.activeEvidence().request(); + var changedNamespaceRead = + new WorldCanonicalInstanceLifecycleEvidence.Request( + original.schemaVersion(), + UUID.randomUUID(), + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + original.canonicalGameInstanceId(), + UUID.randomUUID(), + original.playableStateScope(), + original.publicProduction(), + original.controlPlaneRequestId(), + original.canonicalVersionId(), + original.expectedDescriptorRequestDigest(), + original.expectedDescriptorResultDigest(), + original.expectedReleaseAttestationDigest()); + var changedNamespaceEvidence = + new WorldCanonicalInstanceLifecycleEvidence( + changedNamespaceRead, + fixture.activeEvidence().launchBinding(), + fixture.activeEvidence().startLocation(), + fixture.activeEvidence().runtimeRoomInstanceId(), + fixture.activeEvidence().lifecycleStatus(), + fixture.activeEvidence().lifecycleEpoch(), + fixture.activeEvidence().rowVersion(), + fixture.activeEvidence().captureId(), + fixture.activeEvidence().graphSha256(), + fixture.activeEvidence().preparationInputDigest(), + fixture.activeEvidence().operationalRegionAssignments()); + var changedScope = + initialLocationRequest( + fixture, + fixture.request().operationId(), + fixture.request().characterId(), + fixture.request().entityAssignmentOperationId(), + fixture.request().entityAssignmentDigest(), + changedNamespaceEvidence); + assertThatThrownBy(() -> reader.read(changedScope)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact canonical World lifecycle association is missing"); + + assertThat(initialLocationSnapshot(fixture.request().canonicalGameInstanceId())) + .isEqualTo(locationBefore); + assertThat(initialLocationOperation(fixture.request().operationId()).intoMap()) + .usingRecursiveComparison() + .isEqualTo(operationBefore.intoMap()); + assertThat(countInitialLocationOperations(fixture.request().canonicalGameInstanceId())) + .isEqualTo(1L); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isEqualTo(1L); + assertOrigin(); + } + + @Test + void currentInitialPlayerLocationReadDeniesStaleLifecycleOrSubstitutedRoomMapping() { + PlacementFixture fixture = initialPlayerLocationFixture(); + fixture.service().place(fixture.request()); + var reader = currentLocationReadService(fixture); + var active = fixture.activeEvidence(); + + var staleEvidence = + new WorldCanonicalInstanceLifecycleEvidence( + lifecycleRequestWithFreshReadId(active.request()), + active.launchBinding(), + active.startLocation(), + active.runtimeRoomInstanceId(), + active.lifecycleStatus(), + active.lifecycleEpoch() + 1L, + active.rowVersion(), + active.captureId(), + active.graphSha256(), + active.preparationInputDigest(), + active.operationalRegionAssignments()); + var staleRequest = + initialLocationRequest( + fixture, + fixture.request().operationId(), + fixture.request().characterId(), + fixture.request().entityAssignmentOperationId(), + fixture.request().entityAssignmentDigest(), + staleEvidence); + assertThatThrownBy(() -> reader.read(staleRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("current ACTIVE lifecycle or V42 ROOM evidence differs"); + + var changedRuntimeRoomEvidence = + new WorldCanonicalInstanceLifecycleEvidence( + lifecycleRequestWithFreshReadId(active.request()), + active.launchBinding(), + active.startLocation(), + active.runtimeRoomInstanceId() + 1L, + active.lifecycleStatus(), + active.lifecycleEpoch(), + active.rowVersion(), + active.captureId(), + active.graphSha256(), + active.preparationInputDigest(), + active.operationalRegionAssignments()); + var changedRoomRequest = + initialLocationRequest( + fixture, + fixture.request().operationId(), + fixture.request().characterId(), + fixture.request().entityAssignmentOperationId(), + fixture.request().entityAssignmentDigest(), + changedRuntimeRoomEvidence); + assertThatThrownBy(() -> reader.read(changedRoomRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("current ACTIVE lifecycle or V42 ROOM evidence differs"); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isEqualTo(1L); + assertOrigin(); + } + + @Test + void changedActorOrAssignmentUnderAnExistingPlacementOperationConflictsWithoutMutation() { + PlacementFixture fixture = initialPlayerLocationFixture(); + fixture.service().place(fixture.request()); + String before = initialLocationSnapshot(fixture.request().canonicalGameInstanceId()); + long operationCount = + countInitialLocationOperations(fixture.request().canonicalGameInstanceId()); + + var changedActor = + initialLocationRequest( + fixture, + fixture.request().operationId(), + UUID.randomUUID(), + fixture.request().entityAssignmentOperationId(), + fixture.request().entityAssignmentDigest(), + fixture.activeEvidence()); + assertThatThrownBy(() -> fixture.service().place(changedActor)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + + var changedAssignment = + initialLocationRequest( + fixture, + fixture.request().operationId(), + fixture.request().characterId(), + UUID.randomUUID(), + "b".repeat(64), + fixture.activeEvidence()); + assertThatThrownBy(() -> fixture.service().place(changedAssignment)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + + assertThat(initialLocationSnapshot(fixture.request().canonicalGameInstanceId())) + .isEqualTo(before); + assertThat(countInitialLocationOperations(fixture.request().canonicalGameInstanceId())) + .isEqualTo(operationCount); + assertOrigin(); + } + + @Test + void splitCharacterAndAssignmentMatchesRetainConflictWithoutChangingEitherLocation() { + PlacementFixture fixture = initialPlayerLocationFixture(); + var firstRequest = fixture.request(); + var secondRequest = + initialLocationRequest( + fixture, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "c".repeat(64), + fixture.activeEvidence()); + fixture.service().place(firstRequest); + fixture.service().place(secondRequest); + String before = initialLocationSnapshot(firstRequest.canonicalGameInstanceId()); + + var splitRequest = + initialLocationRequest( + fixture, + UUID.randomUUID(), + firstRequest.characterId(), + secondRequest.entityAssignmentOperationId(), + secondRequest.entityAssignmentDigest(), + fixture.activeEvidence()); + WorldCanonicalInitialPlayerLocation.Result conflict = fixture.service().place(splitRequest); + + assertThat(conflict.outcome()).isEqualTo(WorldCanonicalInitialPlayerLocation.Outcome.CONFLICT); + assertThat(conflict.conflictCode()) + .isEqualTo("CHARACTER_AND_ASSIGNMENT_IDENTIFY_DIFFERENT_PLACEMENTS"); + Record operation = initialLocationOperation(splitRequest.operationId()); + assertThat(operation.get("outcome", String.class)).isEqualTo("CONFLICT"); + assertThat(operation.get("conflict_code", String.class)).isEqualTo(conflict.conflictCode()); + assertThat(initialLocationSnapshot(firstRequest.canonicalGameInstanceId())).isEqualTo(before); + assertThat(countInitialLocations(firstRequest.canonicalGameInstanceId())).isEqualTo(2L); + byte[] conflictBytes = conflict.canonicalBytes(); + var conflictRetry = fixture.service().place(splitRequest); + assertThat(conflictRetry.canonicalBytes()).containsExactly(conflictBytes); + assertThat( + initialLocationOperation(splitRequest.operationId()).get("result_bytes", byte[].class)) + .containsExactly(conflictBytes); + assertThat(initialLocationSnapshot(firstRequest.canonicalGameInstanceId())).isEqualTo(before); + assertOrigin(); + } + + @Test + void sqlRejectsSelfConsistentlyDigestedOpenOrNoncanonicalConflictResults() throws Exception { + PlacementFixture fixture = initialPlayerLocationFixture(); + for (int variant = 0; variant < 5; variant++) { + UUID operationId = UUID.randomUUID(); + var request = + initialLocationRequest( + fixture, + operationId, + UUID.randomUUID(), + UUID.randomUUID(), + "f".repeat(64), + fixture.activeEvidence()); + byte[] validResult = + WorldCanonicalInitialPlayerLocation.Result.conflict(request, "FIXTURE_CONFLICT") + .canonicalBytes(); + byte[] invalidResult; + String conflictCode = variant == 4 ? "lowercase\ncode" : "FIXTURE_CONFLICT"; + if (variant == 0) { + var withUnknownField = + (tools.jackson.databind.node.ObjectNode) mapper.readTree(validResult); + withUnknownField.put("unexpected", "extra"); + invalidResult = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(withUnknownField)); + } else if (variant == 1) { + invalidResult = + (" " + new String(validResult, StandardCharsets.UTF_8)) + .getBytes(StandardCharsets.UTF_8); + } else if (variant == 2) { + String canonical = new String(validResult, StandardCharsets.UTF_8); + invalidResult = + (canonical.substring(0, canonical.length() - 1) + ",\"outcome\":\"CONFLICT\"}") + .getBytes(StandardCharsets.UTF_8); + } else if (variant == 3) { + invalidResult = + new String(validResult, StandardCharsets.UTF_8) + .replace("\"outcome\":\"CONFLICT\"", "\"outcome\":true") + .getBytes(StandardCharsets.UTF_8); + } else { + var withInvalidConflictCode = + (tools.jackson.databind.node.ObjectNode) mapper.readTree(validResult); + withInvalidConflictCode.put("conflictCode", conflictCode); + invalidResult = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(withInvalidConflictCode)); + } + + assertThat(sha256Digest(invalidResult)).isNotEqualTo(sha256Digest(validResult)); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + dsl.execute( + "INSERT INTO world_canonical_initial_player_location_operation " + + "(canonical_tenant_id, playable_state_namespace_id, canonical_game_instance_id, " + + "operation_id, world_instance_id, request_digest, request_bytes, " + + "original_lifecycle_evidence_bytes, outcome, conflict_code, result_bytes, result_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'CONFLICT', ?, ?, ?)", + request.canonicalTenantId(), + request.playableStateNamespaceId(), + request.canonicalGameInstanceId(), + request.operationId(), + fixture.lifecycle().materialized().association().worldInstanceId(), + request.requestDigest(), + request.canonicalRequestBytes(), + request.originalLifecycleEvidenceBytes(), + conflictCode, + invalidResult, + sha256Digest(invalidResult)); + return null; + })) + .hasMessageContaining("World initial-location"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_initial_player_location_operation " + + "WHERE operation_id=?", + request.operationId())) + .get(0, Long.class)) + .isZero(); + } + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isZero(); + assertOrigin(); + } + + @Test + void sqlRejectsNullOrUnknownInitialAdmissionOriginsWithoutWritingOperation() throws Exception { + PlacementFixture fixture = initialPlayerLocationFixture(); + for (String invalidOrigin : new String[] {null, "UNKNOWN"}) { + var request = + initialLocationRequest( + fixture, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "f".repeat(64), + fixture.activeEvidence()); + var invalidRequest = + (tools.jackson.databind.node.ObjectNode) mapper.readTree(request.canonicalRequestBytes()); + if (invalidOrigin == null) { + invalidRequest.putNull("initialAdmissionOrigin"); + } else { + invalidRequest.put("initialAdmissionOrigin", invalidOrigin); + } + byte[] invalidRequestBytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(invalidRequest)); + + var invalidResult = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree( + WorldCanonicalInitialPlayerLocation.Result.conflict(request, "FIXTURE_CONFLICT") + .canonicalBytes()); + invalidResult.put("requestDigest", sha256Digest(invalidRequestBytes)); + invalidResult.put( + "requestBytesBase64", java.util.Base64.getEncoder().encodeToString(invalidRequestBytes)); + byte[] invalidResultBytes = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(invalidResult)); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + dsl.execute( + "INSERT INTO world_canonical_initial_player_location_operation " + + "(canonical_tenant_id, playable_state_namespace_id, canonical_game_instance_id, " + + "operation_id, world_instance_id, request_digest, request_bytes, " + + "original_lifecycle_evidence_bytes, outcome, conflict_code, result_bytes, result_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'CONFLICT', ?, ?, ?)", + request.canonicalTenantId(), + request.playableStateNamespaceId(), + request.canonicalGameInstanceId(), + request.operationId(), + fixture.lifecycle().materialized().association().worldInstanceId(), + sha256Digest(invalidRequestBytes), + invalidRequestBytes, + request.originalLifecycleEvidenceBytes(), + "FIXTURE_CONFLICT", + invalidResultBytes, + sha256Digest(invalidResultBytes)); + return null; + })) + .hasMessageContaining( + "World initial-location operation differs from its canonical request/result"); + assertThat(countInitialLocationOperations(fixture.request().canonicalGameInstanceId())) + .isZero(); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isZero(); + } + assertOrigin(); + } + + @Test + void lostHeldAuthorityAfterLocationAndOperationInsertRollsBackBothRows() { + PlacementFixture fixture = initialPlayerLocationFixture(); + AtomicInteger checks = new AtomicInteger(); + var service = + new WorldCanonicalInitialPlayerLocationService( + fixture.repository(), + ignored -> + new WorldCanonicalInitialPlayerLocationService.HeldPlacementAuthority() { + @Override + public void requireHeld() { + int count = checks.incrementAndGet(); + if (count == 3) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat( + countInitialLocationOperations( + fixture.request().canonicalGameInstanceId())) + .isEqualTo(1L); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())) + .isEqualTo(1L); + throw new IllegalStateException("stipulated placement authority loss"); + } + } + + @Override + public void close() {} + }); + + assertThatThrownBy(() -> service.place(fixture.request())) + .hasMessageContaining("stipulated placement authority loss"); + assertThat(countInitialLocationOperations(fixture.request().canonicalGameInstanceId())) + .isZero(); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isZero(); + assertOrigin(); + } + + @Test + void concurrentExactInitialPlacementRetriesCommitOneLocationAndOneResult() throws Exception { + PlacementFixture fixture = initialPlayerLocationFixture(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + Future first; + Future second; + try { + first = + executor.submit( + () -> { + ready.countDown(); + await(start); + return fixture.service().place(fixture.request()); + }); + second = + executor.submit( + () -> { + ready.countDown(); + await(start); + return fixture.service().place(fixture.request()); + }); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var firstResult = first.get(45, TimeUnit.SECONDS); + var secondResult = second.get(45, TimeUnit.SECONDS); + + assertThat(firstResult.outcome()) + .isEqualTo(WorldCanonicalInitialPlayerLocation.Outcome.APPLIED); + assertThat(secondResult.canonicalBytes()).containsExactly(firstResult.canonicalBytes()); + assertThat(countInitialLocationOperations(fixture.request().canonicalGameInstanceId())) + .isEqualTo(1L); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isEqualTo(1L); + assertThat( + initialLocationOperation(fixture.request().operationId()) + .get("original_lifecycle_evidence_bytes", byte[].class)) + .containsExactly(fixture.request().originalLifecycleEvidenceBytes()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + assertOrigin(); + } + + @Test + void danglingAppliedReceiptDeniesRetryWithoutRecreatingLocation() { + PlacementFixture fixture = initialPlayerLocationFixture(); + fixture.service().place(fixture.request()); + dsl.execute( + "DELETE FROM character_location WHERE canonical_game_instance_id=? " + + "AND playable_state_namespace_id=? AND character_id=?", + fixture.request().canonicalGameInstanceId(), + fixture.request().playableStateNamespaceId(), + fixture.request().characterId()); + + assertThatThrownBy(() -> fixture.service().place(fixture.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "retained APPLIED result has no exact current immutable location row"); + assertThat(countInitialLocationOperations(fixture.request().canonicalGameInstanceId())) + .isEqualTo(1L); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isZero(); + assertOrigin(); + } + + @Test + void changedCanonicalScopeOrRuntimeRoomEvidenceDeniesBeforePlacementWrites() { + PlacementFixture fixture = initialPlayerLocationFixture(); + var active = fixture.activeEvidence(); + assertThatThrownBy( + () -> + new WorldCanonicalInstanceLifecycleEvidence( + lifecycleRequestWithFreshReadId(active.request()), + active.launchBinding(), + new RoomTemplateRef( + active.startLocation().tenantId(), + active.startLocation().versionId(), + UUID.randomUUID()), + active.runtimeRoomInstanceId(), + active.lifecycleStatus(), + active.lifecycleEpoch(), + active.rowVersion(), + active.captureId(), + active.graphSha256(), + active.preparationInputDigest(), + active.operationalRegionAssignments())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ROOM selector or graph digest differs"); + var original = active.request(); + var wrongScopeRead = + new WorldCanonicalInstanceLifecycleEvidence.Request( + original.schemaVersion(), + UUID.randomUUID(), + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + original.canonicalGameInstanceId(), + UUID.randomUUID(), + original.playableStateScope(), + original.publicProduction(), + original.controlPlaneRequestId(), + original.canonicalVersionId(), + original.expectedDescriptorRequestDigest(), + original.expectedDescriptorResultDigest(), + original.expectedReleaseAttestationDigest()); + var wrongScopeEvidence = + new WorldCanonicalInstanceLifecycleEvidence( + wrongScopeRead, + active.launchBinding(), + active.startLocation(), + active.runtimeRoomInstanceId(), + active.lifecycleStatus(), + active.lifecycleEpoch(), + active.rowVersion(), + active.captureId(), + active.graphSha256(), + active.preparationInputDigest(), + active.operationalRegionAssignments()); + var wrongScopeRequest = + initialLocationRequest( + fixture, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "d".repeat(64), + wrongScopeEvidence); + assertThatThrownBy(() -> fixture.service().place(wrongScopeRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact canonical World lifecycle association is missing"); + + var wrongRuntimeEvidence = + new WorldCanonicalInstanceLifecycleEvidence( + lifecycleRequestWithFreshReadId(active.request()), + active.launchBinding(), + active.startLocation(), + active.runtimeRoomInstanceId() + 1L, + active.lifecycleStatus(), + active.lifecycleEpoch(), + active.rowVersion(), + active.captureId(), + active.graphSha256(), + active.preparationInputDigest(), + active.operationalRegionAssignments()); + var wrongRuntimeRequest = + initialLocationRequest( + fixture, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "e".repeat(64), + wrongRuntimeEvidence); + assertThatThrownBy(() -> fixture.service().place(wrongRuntimeRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("current ACTIVE lifecycle evidence differs"); + assertThat(countInitialLocationOperations(fixture.request().canonicalGameInstanceId())) + .isZero(); + assertThat(countInitialLocations(fixture.request().canonicalGameInstanceId())).isZero(); + assertOrigin(); + } + + @Test + void releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeWrites() { + Fixture f = fixture(); + var application = application(generationFreePlan(f)); + appliedComponent().apply(application); + var frozen = capture(application.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var selected = selector.request(); + var changed = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + selected.targetNamespace(), + selected.canonicalTenantId(), + selected.canonicalVersionId(), + selected.intakeRequestId(), + UUID.randomUUID(), + selected.publicationRequestId(), + selected.requestDigest(), + selected.versionStateEpoch(), + selected.publishWorkflowId(), + selected.appliedCommitId(), + selected.contentDigest(), + selected.digestSchemaVersion(), + selected.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + assertThatThrownBy(() -> preparationInput(f, frozen, changed)) + .hasMessageContaining("exact frozen request"); + var input = preparationInput(f, frozen, selector); + var encoded = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(WorldCanonicalInstancePreparationRepository.inputJson(input)); + encoded.put( + "worldStartLocationEvidenceBase64", + java.util.Base64.getEncoder().encodeToString(changed.canonicalBytes())); + String substituted = mapper.writeValueAsString(encoded); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?,?)", + substituted, + WorldDraftGraphAppliedResult.digest( + substituted.getBytes(StandardCharsets.UTF_8))))) + .hasMessageContaining("complete frozen request"); + + var changedEpoch = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + selected.targetNamespace(), + selected.canonicalTenantId(), + selected.canonicalVersionId(), + selected.intakeRequestId(), + selected.publicationFence(), + selected.publicationRequestId(), + selected.requestDigest(), + selected.versionStateEpoch() + 1L, + selected.publishWorkflowId(), + selected.appliedCommitId(), + selected.contentDigest(), + selected.digestSchemaVersion(), + selected.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + var changedEpochInput = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(WorldCanonicalInstancePreparationRepository.inputJson(input)); + changedEpochInput.put( + "worldStartLocationEvidenceBase64", + java.util.Base64.getEncoder().encodeToString(changedEpoch.canonicalBytes())); + String substitutedEpoch = mapper.writeValueAsString(changedEpochInput); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?,?)", + substitutedEpoch, + WorldDraftGraphAppliedResult.digest( + substitutedEpoch.getBytes(StandardCharsets.UTF_8))))) + .hasMessageContaining("complete frozen request"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_instance WHERE tenant_id=?", + f.intake().localTenantKey())) + .get(0, Long.class)) + .isZero(); + assertThat(preparationRepository().readOwnerPreparation(input)).isEmpty(); + assertOrigin(); + } + + @Test + void inertV1PreparationRetainsOriginalBytesAndCannotGainSelectorOnRetry() throws Exception { + HistoricalSchemaFixture schema = historicalSchemaAt("world_v42_inert_v1", "42"); + WorldDraftGraphApplicationPostgresIntegrationTest historical = schema.database(); + Fixture f = historical.fixture(); + var application = historical.application(historical.generationFreePlan(f)); + historical.appliedComponent().apply(application); + var frozen = historical.capture(application.plan()); + var input = historical.preparationInput(f, frozen, null); + var first = historical.prepareV1ThroughOwnerFunction(input); + assertThat(first.startLocation()).isNull(); + assertThat(first.runtimeRoomInstanceId()).isNull(); + byte[] before = historical.preparationRows(input.canonicalGameInstanceId()); + assertThat(historical.prepareV1ThroughOwnerFunction(input)).isEqualTo(first); + assertThat(historical.preparationRows(input.canonicalGameInstanceId())).containsExactly(before); + String originalInputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + assertThat(originalInputJson).doesNotContain("worldStartLocationEvidence"); + assertThat( + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT count(*) FROM world_canonical_preparation_start_location WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class)) + .isZero(); + // V42 cannot reinterpret the immutable selector-null V1 preparation as a V2 materialization. + var selector = + historical.publishedEvidence( + historical.publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var promotedInput = + (tools.jackson.databind.node.ObjectNode) historical.mapper.readTree(originalInputJson); + promotedInput.put("schemaVersion", 2); + promotedInput.put( + "worldStartLocationEvidenceBase64", + java.util.Base64.getEncoder().encodeToString(selector.canonicalBytes())); + String promotedInputJson = historical.mapper.writeValueAsString(promotedInput); + byte[] promotedInputBytes = promotedInputJson.getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + historical + .ownerTransaction() + .execute( + status -> + historical.dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?,?)", + promotedInputJson, + sha256Digest(promotedInputBytes)))) + .hasMessageContaining("V2 preparation requires original complete World selector evidence"); + assertThat(historical.preparationRows(input.canonicalGameInstanceId())).containsExactly(before); + assertThat( + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT count(*) FROM world_canonical_preparation_start_location WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class)) + .isZero(); + historical.assertOrigin(); + } + + @Test + void selectorPreparationLateFenceLossRollsBackSelectorRuntimeAndAssociationTogether() { + Fixture f = fixture(); + var application = application(generationFreePlan(f)); + appliedComponent().apply(application); + var frozen = capture(application.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + completeIsolatedPublicationTerminal(input); + var component = + new WorldCanonicalInstancePreparationService( + preparationRepository(), + ignored -> + new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + private int calls; + + public void requireHeld() { + calls++; + if (calls == 3) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_preparation_start_location WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class)) + .isEqualTo(1L); + throw new IllegalStateException("stipulated late Account fence loss"); + } + } + + public void close() {} + }); + assertThatThrownBy(() -> component.prepare(input)) + .hasMessageContaining("late Account fence loss"); + for (String table : + List.of( + "world_instance", + "world_canonical_instance_association", + "world_canonical_instance_preparation", + "world_canonical_preparation_start_location")) { + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM " + table + " WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class)) + .isZero(); + } + assertThat(appliedRepository().readCommitted(application).orElseThrow().canonicalBytes()) + .containsExactly(selector.appliedResultBytes()); + assertOrigin(); + } + + private WorldDraftTopologyCommitPlan generationFreePlan(Fixture f) { + var original = plan(f); + var binding = original.binding(); + List revisions = new ArrayList<>(); + for (var revision : binding.revisions()) { + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + revision.revisionId(), + revision.owner(), + revision.payload())); + continue; + } + try { + var value = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(revision.payload(), value); + if (value.hasGenerationRule() || value.hasWorldEntitySpawnBinding()) continue; + if (value.hasRegion()) + value.setRegion( + value.getRegion().toBuilder() + .clearGenerationSeed() + .clearGeneratorType() + .clearGeneratorParams()); + if (value.hasFreshGraphDeclaration()) { + var declaration = value.getFreshGraphDeclaration().toBuilder(); + for (int index = 0; index < declaration.getFamilyCountsCount(); index++) { + var family = declaration.getFamilyCounts(index).getFamily(); + if (family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE + || family + == WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) { + declaration.setFamilyCounts( + index, declaration.getFamilyCounts(index).toBuilder().setCount(0)); + } + } + value.setFreshGraphDeclaration(declaration); + } + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + revision.revisionId(), + revision.owner(), + JsonFormat.printer().print(value))); + } catch (InvalidProtocolBufferException failure) { + throw new IllegalStateException(failure); + } + } + return WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + revisions, + binding.affectedUnits().stream() + .filter( + unit -> + !unit.aggregateType().equals("GENERATION_RULE") + && !unit.aggregateType().equals("WORLD_ENTITY_SPAWN_BINDING")) + .toList()), + original.ownerBinding()); + } + + @Test + void v41MaterializedV1HistoryRemainsByteExactAndRetryableAfterV42WithoutSelectorPromotion() { + HistoricalSchemaFixture schema = historicalSchemaAt("world_v41_preparation", "41"); + WorldDraftGraphApplicationPostgresIntegrationTest historical = schema.database(); + Fixture f = historical.fixture(); + var application = historical.application(historical.generationFreePlan(f)); + var applied = historical.appliedComponent().apply(application); + var frozen = historical.capture(application.plan()); + var input = historical.preparationInput(f, frozen, null); + var first = historical.prepareV1ThroughOwnerFunction(input); + Map before = historical.preparationHistoryRows(); + byte[] originalApplied = applied.canonicalBytes(); + historical.migrateHistoricalSchema(schema.schema(), "42"); + assertThat(historical.preparationHistoryRows()).isEqualTo(before); + assertThat(historical.prepareV1ThroughOwnerFunction(input)).isEqualTo(first); + assertThat(historical.preparationHistoryRows()).isEqualTo(before); + assertThat( + historical + .appliedRepository() + .readCommitted(application) + .orElseThrow() + .canonicalBytes()) + .containsExactly(originalApplied); + assertThat(first.startLocation()).isNull(); + assertThat(first.runtimeRoomInstanceId()).isNull(); + assertThat( + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT count(*) FROM world_canonical_preparation_start_location")) + .get(0, Long.class)) + .isZero(); + historical.assertOrigin(); + } + + private HistoricalSchemaFixture historicalSchemaAt(String schemaPrefix, String version) { + String schema = schemaPrefix + "_" + UUID.randomUUID().toString().replace("-", ""); + migrateHistoricalSchema(schema, version); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + var historical = new WorldDraftGraphApplicationPostgresIntegrationTest(); + historical.dsl = + DSL.using( + new TransactionAwareDataSourceProxy(dataSource), + SQLDialect.POSTGRES, + new org.jooq.conf.Settings().withRenderSchema(false)); + historical.manager = new DataSourceTransactionManager(dataSource); + historical.intakeRepository = proxiedIntakeRepository(historical.dsl, historical.manager); + historical.fence = + new WorldDesignPublicationFenceRepository(historical.dsl, historical.intakeRepository); + historical.mapper = mapper; + historical.snapshots = new WorldAuthoredGraphSnapshotRepository(historical.dsl); + historical.digestService = + new net.firedevops.firemud.worldmanagement.service.impl.WorldDraftDesignDigestServiceImpl( + new net.firedevops.firemud.worldmanagement.repository.RegionRepository(historical.dsl), + new net.firedevops.firemud.worldmanagement.repository.ZoneRepository(historical.dsl), + new net.firedevops.firemud.worldmanagement.repository.RoomRepository(historical.dsl), + new net.firedevops.firemud.worldmanagement.repository.RoomExitRepository( + historical.dsl), + new net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository( + historical.dsl), + new net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository( + historical.dsl), + mapper); + return new HistoricalSchemaFixture(schema, historical); + } + + private void migrateHistoricalSchema(String schema, String version) { + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_world_management_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion(version)) + .load() + .migrate(); + } + + /** Executes the real V35/V42 owner SQL path for selector-null V1 migration history. */ + private WorldCanonicalInstancePreparation.Result prepareV1ThroughOwnerFunction( + WorldCanonicalInstancePreparation.Input input) { + String inputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + byte[] inputBytes = inputJson.getBytes(StandardCharsets.UTF_8); + Long worldInstanceId = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?, ?)", + inputJson, + sha256Digest(inputBytes)), + "V35/V42 owner preparation function returned no row"); + Long allocatedWorldInstanceId = + Objects.requireNonNull( + row.get("world_instance_id", Long.class), + "V35/V42 owner preparation result omitted world_instance_id"); + var claim = + new WorldCanonicalInstanceAssociation.Claim( + input.gameSessionReadRequest(), + input.gameSessionReadEvidence(), + allocatedWorldInstanceId.longValue(), + input.completeLaunchBinding(), + input.versionIdentity()); + associationRepository().retainClaimInOwnerTransaction(claim); + return allocatedWorldInstanceId; + }), + "V35/V42 owner transaction returned no allocated world_instance_id"); + var result = + preparationRepository() + .readOwnerPreparation(input) + .orElseThrow( + () -> + new IllegalStateException( + "V35/V42 owner preparation has no exact committed readback")); + assertThat(result.association().worldInstanceId()).isEqualTo(worldInstanceId.longValue()); + return result; + } + + private Map preparationHistoryRows() { + Map result = new LinkedHashMap<>(); + for (String table : + List.of( + "world_authored_source_intake", + "world_authored_version_identity", + "world_complete_launch_binding", + "world_topology_draft_commit", + "world_draft_graph_application", + "world_draft_start_location_receipt", + "world_canonical_frozen_topology", + "world_instance", + "region_instance", + "zone_instance", + "room_instance", + "room_instance_exit", + "world_canonical_instance_topology_identity", + "world_canonical_instance_preparation", + "world_canonical_instance_association")) { + result.put( + table, + Objects.requireNonNull( + dsl.fetchOne( + "SELECT coalesce(jsonb_agg(value ORDER BY value::text),'[]'::jsonb)::text " + + "FROM (SELECT to_jsonb(t) AS value FROM " + + table + + " t) rows")) + .get(0, String.class)); + } + return result; + } + + private WorldPublishedStartLocationEvidence publishedEvidence( + WorldPublishedStartLocationSource source) { + var freeze = source.frozenTopology().request().freeze(); + return new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + freeze.targetNamespace(), + freeze.canonicalTenantId(), + freeze.canonicalVersionId(), + freeze.intakeRequestId(), + freeze.publicationFence(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + freeze.contentDigest(), + freeze.digestSchemaVersion(), + freeze.suppliedOwnedAffectedTuples().stream() + .map( + tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) + .toList()), + source.selectorReceipt().canonicalBytes(), + source.appliedResult().application().operation().accountBindingBytes(), + source.appliedResult().canonicalBytes()); + } + + private WorldCanonicalInstancePreparation.Input preparationInput( + Fixture f, + WorldCanonicalFrozenTopology frozen, + WorldPublishedStartLocationEvidence selector) { + return preparationInput(f, frozen, selector, 2L, List.of("LOOK")); + } + + private WorldCanonicalInstancePreparation.Input preparationInput( + Fixture f, + WorldCanonicalFrozenTopology frozen, + WorldPublishedStartLocationEvidence selector, + long descriptorVersionStateEpoch) { + return preparationInput(f, frozen, selector, descriptorVersionStateEpoch, List.of("LOOK")); + } + + private WorldCanonicalInstancePreparation.Input preparationInput( + Fixture f, + WorldCanonicalFrozenTopology frozen, + WorldPublishedStartLocationEvidence selector, + long descriptorVersionStateEpoch, + List commandDefinitions) { + PreparationLaunchFixture launchFixture = + preparationLaunchFixture( + f, frozen, selector, descriptorVersionStateEpoch, commandDefinitions); + var evidence = launchFixture.evidence(); + var descriptor = evidence.descriptor(); + var release = evidence.releaseAttestation(); + var launch = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + new WorldCompleteLaunchBindingRepository(dsl) + .acceptFresh(NAMESPACE, f.intake(), evidence))); + var ownerRequest = launchFixture.ownerRequest(); + var request = + new WorldCanonicalInstanceAssociation.GameSessionReadRequest( + ownerRequest.readRequestId(), + ownerRequest.targetNamespace(), + ownerRequest.canonicalTenantId(), + ownerRequest.worldSlug(), + ownerRequest.gameInstanceUuid(), + ownerRequest.controlPlaneRequestId(), + ownerRequest.launchDescriptorId(), + ownerRequest.expectedDescriptorRequestDigest(), + ownerRequest.expectedDescriptorResultDigest(), + ownerRequest.expectedReleaseAttestationEvidenceDigest()); + var response = + new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + ownerRequest.readRequestId(), + ownerRequest.targetNamespace(), + ownerRequest.canonicalTenantId(), + ownerRequest.worldSlug(), + ownerRequest.gameInstanceUuid(), + ownerRequest.controlPlaneRequestId(), + ownerRequest.launchDescriptorId(), + ownerRequest.expectedDescriptorRequestDigest(), + ownerRequest.expectedDescriptorResultDigest(), + ownerRequest.expectedReleaseAttestationEvidenceDigest(), + UUID.randomUUID(), + "SHARED", + true, + "PREPARING", + 1L, + descriptor, + release); + return new WorldCanonicalInstancePreparation.Input( + request, response, launch, f.version(), launchFixture.topologyPlan()); + } + + private PreparationLaunchFixture preparationLaunchFixture( + Fixture f, + WorldCanonicalFrozenTopology frozen, + WorldPublishedStartLocationEvidence selector, + long descriptorVersionStateEpoch, + List commandDefinitions) { + var source = f.intake().source(); + String control = "prepare-" + UUID.randomUUID(); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + control, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + 71L, + false, + null, + false, + null, + false, + null, + false, + null), + "ld-" + UUID.randomUUID(), + GAME_DESIGN_VERSION, + false, + null, + "{}", + "generation-free", + descriptorVersionStateEpoch, + 97L, + "release-" + frozen.request().freeze().publicationRequestId(), + false, + null); + var freeze = frozen.request().freeze(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(GAME_DESIGN_VERSION), + false, + null, + freeze.appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) ? freeze.contentDigest() : "a".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "b".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + selector == null + ? AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + f.version().canonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + participants, + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + commandDefinitions, + descriptor.generationConfigRevision()) + : AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + f.version().canonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + participants, + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + commandDefinitions, + descriptor.generationConfigRevision(), + selector); + var evidence = new CompleteLaunchBindingEvidence(descriptor, release); + UUID instance = UUID.randomUUID(); + UUID read = UUID.randomUUID(); + var request = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + read, + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + instance, + control, + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new PreparationLaunchFixture( + evidence, request, WorldCanonicalInstanceTopologyPlan.create(frozen)); + } + + /** + * Isolated upstream client doubles return a complete expected pair and an exact Game Session + * selector echo; they do not claim live producer authentication or currentness. + */ + private PreparationAssemblyFixture preparationAssemblyFixture( + String workloadNamespace, + CompleteLaunchBindingEvidence returnedPair, + UUID playableStateNamespaceId) { + var gameDesign = Mockito.mock(AuthoredWorldLaunchDescriptorClient.class); + Mockito.when(gameDesign.getComplete(Mockito.any())).thenReturn(returnedPair); + + var gameSession = Mockito.mock(CanonicalGameInstanceLaunchAssociationClient.class); + Mockito.when(gameSession.read(Mockito.any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, CanonicalGameInstanceLaunchAssociationReadEvidence.Request.class); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + request, + playableStateNamespaceId, + RealmEntryPolicy.StateScope.SHARED, + true, + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING, + 1L, + returnedPair); + }); + + var assembly = + new WorldCanonicalInstancePreparationAssemblyService( + workloadNamespace, + new WorldCompleteLaunchBindingRepository(dsl), + new WorldAuthoredSourceIntakeRepository(dsl), + new WorldAuthoredVersionIdentityRepository(dsl), + frozenRepository(), + gameSession, + gameDesign); + return new PreparationAssemblyFixture( + assembly, gameDesign, gameSession, playableStateNamespaceId); + } + + private Map retainedPreparationSourceRows( + Fixture fixture, + WorldCanonicalInstancePreparation.Input input, + WorldCanonicalFrozenTopology frozen) { + var descriptor = input.completeLaunchBinding().descriptor(); + return Map.of( + "sourceIntake", + retainedJson( + "SELECT to_jsonb(i)::text FROM world_authored_source_intake i WHERE intake_request_id=?", + fixture.intake().intakeRequestId()), + "versionIdentity", + retainedJson( + "SELECT to_jsonb(v)::text FROM world_authored_version_identity v WHERE operation_id=?", + fixture.version().operationId()), + "completeLaunchBinding", + retainedJson( + "SELECT to_jsonb(b)::text FROM world_complete_launch_binding b WHERE target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?", + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.controlPlaneRequestId()), + "frozenCapture", + retainedJson( + "SELECT to_jsonb(c)::text FROM world_canonical_frozen_topology c WHERE publication_fence=?", + frozen.request().freeze().publicationFence())); + } + + private Map canonicalPreparationAllocationRows( + Fixture fixture, UUID canonicalGameInstanceId) { + Map rows = new LinkedHashMap<>(); + for (String table : + List.of( + "world_instance", + "region_instance", + "zone_instance", + "room_instance", + "room_instance_exit")) { + rows.put(table, count(fixture, table)); + } + for (String table : + List.of( + "world_canonical_instance_association", + "world_canonical_instance_preparation", + "world_canonical_instance_topology_identity", + "world_canonical_preparation_start_location")) { + rows.put( + table, + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM " + table + " WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)) + .get(0, Long.class)); + } + return rows; + } + + private String retainedJson(String sql, Object... bindings) { + return Objects.requireNonNull(dsl.resultQuery(sql, bindings).fetchOne()).get(0, String.class); + } + + private WorldCanonicalInstancePreparationRepository preparationRepository() { + return new WorldCanonicalInstancePreparationRepository( + dsl, + manager, + new WorldCanonicalInstanceAssociationRepository( + dsl, + new WorldCompleteLaunchBindingRepository(dsl), + new WorldAuthoredSourceIntakeRepository(dsl), + new WorldAuthoredVersionIdentityRepository(dsl)), + frozenRepository()); + } + + private WorldCanonicalInstanceAssociationRepository associationRepository() { + return new WorldCanonicalInstanceAssociationRepository( + dsl, + new WorldCompleteLaunchBindingRepository(dsl), + new WorldAuthoredSourceIntakeRepository(dsl), + new WorldAuthoredVersionIdentityRepository(dsl)); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleReadRequest( + WorldCanonicalInstancePreparation.Input input) { + return lifecycleReadRequest( + input, + NAMESPACE, + input.gameSessionReadEvidence().canonicalTenantId(), + input.completeLaunchBinding().evidence().releaseAttestation().canonicalVersionId(), + input.completeLaunchBinding().descriptor().requestDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleReadRequest( + net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceRequest selector, + WorldCanonicalInstancePreparation.Input input) { + var gameSession = input.gameSessionReadEvidence(); + var descriptor = input.completeLaunchBinding().descriptor(); + var release = input.completeLaunchBinding().evidence().releaseAttestation(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.fromString(selector.getReadRequestId()), + gameSession.targetNamespace(), + gameSession.canonicalTenantId(), + gameSession.worldSlug(), + gameSession.canonicalGameInstanceId(), + gameSession.playableStateNamespaceId(), + gameSession.playableStateScope(), + gameSession.publicProduction(), + gameSession.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleReadRequest( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector, + CompleteLaunchBindingEvidence evidence, + UUID playableStateNamespaceId) { + var release = evidence.releaseAttestation(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + selector.readRequestId(), + selector.targetNamespace(), + selector.canonicalTenantId(), + selector.worldSlug(), + selector.gameInstanceUuid(), + playableStateNamespaceId, + RealmEntryPolicy.StateScope.SHARED.name(), + true, + selector.controlPlaneRequestId(), + release.canonicalVersionId(), + selector.expectedDescriptorRequestDigest(), + selector.expectedDescriptorResultDigest(), + selector.expectedReleaseAttestationEvidenceDigest()); + } + + private static Server startPreparationTransport( + WorldCanonicalInstancePreparationGrpcService adapter, WorldPreparationTestWorkloadPki pki) + throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.worldServerCertificate().toFile(), + pki.worldServerPrivateKey().toFile())) + .trustManager(pki.caCertificate().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(adapter, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static Server startActivationTransport( + WorldCanonicalInstanceActivationGrpcService adapter, WorldPreparationTestWorkloadPki pki) + throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.worldServerCertificate().toFile(), + pki.worldServerPrivateKey().toFile())) + .trustManager(pki.caCertificate().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(adapter, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static ActivateCanonicalWorldInstanceRequest activationTransportRequest( + WorldCanonicalInstanceActivation.Request request) { + return ActivateCanonicalWorldInstanceRequest.newBuilder() + .setActivationRequestId(request.activationRequestId().toString()) + .setPreparingLifecycleEvidenceBytes(ByteString.copyFrom(request.preparingEvidenceBytes())) + .build(); + } + + private static CanonicalActivationTransportClient activationTransportClient( + Server server, CommonGrpcClientProperties tlsProperties) throws Exception { + ManagedChannel channel = + new GrpcChannelFactory() + .buildChannel("127.0.0.1:" + server.getPort(), server.getPort(), tlsProperties, false); + var stub = + WorldCanonicalInstanceActivationServiceGrpc.newBlockingStub(channel) + .withCallCredentials( + new GrpcServerPeerIdentityCallCredentials(WORLD_SERVER_WORKLOAD_URI)) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor(WORLD_SERVER_WORKLOAD_URI)); + return new CanonicalActivationTransportClient(channel, stub); + } + + private static CanonicalWorldInstancePreparationClient preparationClient( + Server server, CommonGrpcClientProperties tlsProperties) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + server.getPort()); + return new CanonicalWorldInstancePreparationClient( + endpoints, tlsProperties, new GrpcChannelFactory(), NAMESPACE); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleReadRequest( + WorldCanonicalInstancePreparation.Input input, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String descriptorRequestDigest) { + return lifecycleReadRequest( + input, + targetNamespace, + canonicalTenantId, + canonicalVersionId, + descriptorRequestDigest, + input.completeLaunchBinding().evidence().releaseAttestation().evidenceDigest()); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleReadRequest( + WorldCanonicalInstancePreparation.Input input, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String descriptorRequestDigest, + String expectedReleaseAttestationDigest) { + var gameSession = input.gameSessionReadEvidence(); + var descriptor = input.completeLaunchBinding().descriptor(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.randomUUID(), + targetNamespace, + canonicalTenantId, + gameSession.worldSlug(), + gameSession.canonicalGameInstanceId(), + gameSession.playableStateNamespaceId(), + gameSession.playableStateScope(), + gameSession.publicProduction(), + gameSession.controlPlaneRequestId(), + canonicalVersionId, + descriptorRequestDigest, + descriptor.resultDigest(), + expectedReleaseAttestationDigest); + } + + private WorldCanonicalInstancePreparationService preparationComponent( + WorldCanonicalInstancePreparationRepository repository) { + // Isolated GD-terminal fixture proves the actual World V44 transaction and released gate only. + // It does not prove authenticated GD production or cross-service transport/currentness. + return new WorldCanonicalInstancePreparationService( + repository, + input -> { + completeIsolatedPublicationTerminal(input); + return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + private boolean open = true; + + public void requireHeld() { + if (!open) throw new IllegalStateException("closed fixture authority"); + } + + public void close() { + open = false; + } + }; + }); + } + + /** + * Isolated fixture verifier that preserves and independently reads an already committed V44 + * terminal instead of trying to reseal it from a later descriptor resolution. + */ + private WorldCanonicalInstancePreparationService preparationComponentWithRetainedTerminal( + WorldCanonicalInstancePreparationRepository repository, + GameDesignPublicationTerminalEvidence originalTerminal) { + return preparationComponentWithRetainedTerminal(repository, originalTerminal, null); + } + + private WorldCanonicalInstancePreparationService preparationComponentWithRetainedTerminal( + WorldCanonicalInstancePreparationRepository repository, + GameDesignPublicationTerminalEvidence originalTerminal, + AtomicInteger verifierInvocations) { + byte[] expectedTerminal = originalTerminal.canonicalBytes(); + return new WorldCanonicalInstancePreparationService( + repository, + input -> { + if (verifierInvocations != null) { + verifierInvocations.incrementAndGet(); + } + var retained = + new WorldPublicationTerminalRepository(dsl, manager) + .readCommitted(WorldPublicationTerminal.request(expectedTerminal)) + .orElseThrow( + () -> + new IllegalStateException( + "isolated fixture lost its previously committed World terminal")); + if (!java.util.Arrays.equals(expectedTerminal, retained.canonicalBytes())) { + throw new IllegalStateException( + "isolated fixture World terminal differs from original publication result"); + } + return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + private boolean open = true; + + public void requireHeld() { + if (!open) throw new IllegalStateException("closed fixture authority"); + } + + public void close() { + open = false; + } + }; + }); + } + + private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( + WorldCanonicalInstancePreparation.Input input) { + return isolatedTerminalEvidence(input.completeLaunchBinding().evidence(), input.topologyPlan()); + } + + private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( + CompleteLaunchBindingEvidence launchEvidence, + WorldCanonicalInstanceTopologyPlan topologyPlan) { + var release = launchEvidence.releaseAttestation(); + var world = Objects.requireNonNull(release.worldStartLocationEvidence()); + var originalAccount = + DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()); + var selection = + publicationSelection( + topologyPlan.sourceBinding().plan(), + world.request().publicationRequestId(), + world.request().versionStateEpoch()); + if (!selection.digest().equals("sha256:" + world.request().requestDigest())) { + throw new IllegalStateException( + "Isolated publication selection differs from the retained World request digest"); + } + var account = + new AccountPublicationAuthorizationBinding( + UUID.nameUUIDFromBytes( + (world.request().publicationFence() + "/account-operation") + .getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + (world.request().publicationFence() + "/account-fence") + .getBytes(StandardCharsets.UTF_8)), + new AccountPublicationAuthorizationBinding.PreallocationInput( + originalAccount.actorAccountId(), selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + originalAccount.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var operation = new GameDesignPublicationOperationBinding(account, world); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + Outcome.PUBLISHED, + isolatedReleaseContent(launchEvidence), + release.versionStateEpoch()); + } + + private ReleaseContent isolatedReleaseContent(WorldCanonicalInstancePreparation.Input input) { + return isolatedReleaseContent(input.completeLaunchBinding().evidence()); + } + + private ReleaseContent isolatedReleaseContent(CompleteLaunchBindingEvidence launchEvidence) { + var release = launchEvidence.releaseAttestation(); + var world = Objects.requireNonNull(release.worldStartLocationEvidence()); + var participants = + release.participantDigests().stream() + .map( + participant -> + new Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent() ? participant.baseVersionId() : null, + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent() + ? participant.abilitySchemaDigest() + : null, + null, + null)) + .toList(); + return new ReleaseContent( + release.canonicalTenantId(), + release.canonicalVersionId(), + release.publishedReleaseBundleRef(), + 1, + "v2", + release.publishWorkflowId(), + release.manifestHash(), + release.manifestSchemaVersion(), + release.artifactDigests(), + release.requiredManifestAssetKeys(), + participants, + release.commandDefinitions(), + release.generationConfigRevision(), + world); + } + + private void completeIsolatedPublicationTerminal(WorldCanonicalInstancePreparation.Input input) { + var evidence = isolatedTerminalEvidence(input); + publicationTerminalComponent(evidence) + .complete(evidence.operationBytes(), evidence.canonicalBytes()); + } + + private WorldPublicationTerminalService publicationTerminalComponent( + GameDesignPublicationTerminalEvidence evidence) { + byte[] operationBytes = evidence.operationBytes(); + return new WorldPublicationTerminalService( + new WorldPublicationTerminalRepository(dsl, manager), + (suppliedOperation, terminalBytes) -> { + var upstream = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + if (!java.util.Arrays.equals(operationBytes, suppliedOperation) + || !java.util.Arrays.equals(upstream.operationBytes(), suppliedOperation)) { + throw new IllegalArgumentException("isolated terminal operation mismatch"); + } + return new WorldPublicationTerminalService.VerifiedTerminal( + WorldPublicationTerminal.Request.fromStored(terminalBytes), + new WorldPublicationTerminalService.HeldTerminalAuthority() { + public void requireHeld() {} + + public void close() {} + }); + }); + } + + private AuthoredDraftPublishSelectionBinding publicationSelection( + WorldDraftTopologyCommitPlan plan, String publicationRequest, long freezeEpoch) { + var binding = plan.binding(); + var intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + publicationRequest, + Long.toString(freezeEpoch), + "isolated-world-terminal-fixture", + binding.requestId(), + binding.commitId(), + binding.digest()); + return AuthoredDraftPublishSelectionBinding.capture( + intent, + binding.target(), + binding, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.digest(), + "[]", + OffsetDateTime.parse("2026-01-01T00:00:00Z"))); + } + + /** Reuses genuine graph/release/materialization/activation; upstream authority is stipulated. */ + ActivePlayerAdmissionFixture activePlayerAdmissionFixture() { + var prepared = materializedLifecycleFixture(); + var activation = + canonicalActivationService(prepared, ignored -> stipulatedActivationAuthority()) + .activate( + new WorldCanonicalInstanceActivation.Request( + UUID.randomUUID(), prepared.preparing())); + assertThat(activation.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + var current = + prepared + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(activation.lifecycleEvidence().request())) + .orElseThrow(); + return new ActivePlayerAdmissionFixture( + prepared.materialized().association(), current, prepared.lifecycleRepository()); + } + + record ActivePlayerAdmissionFixture( + WorldCanonicalInstanceAssociation association, + WorldCanonicalInstanceLifecycleEvidence activeEvidence, + WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository) {} + + private PreparedLifecycleFixture materializedLifecycleFixture() { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var selectedRoom = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var applied = withStartRoom(original, selectedRoom); + appliedComponent().apply(applied); + var frozen = capture(applied.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var materialized = preparationComponent(preparationRepository()).prepare(input); + var lifecycleRepository = + new WorldCanonicalInstanceLifecycleReadRepository(dsl, manager, associationRepository()); + var readRequest = lifecycleReadRequest(input); + var preparing = lifecycleRepository.read(readRequest).orElseThrow(); + assertThat(preparing.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(preparing.startLocation().roomTemplateId()).isEqualTo(selectedRoom); + assertThat(preparing.runtimeRoomInstanceId()).isEqualTo(materialized.runtimeRoomInstanceId()); + return new PreparedLifecycleFixture( + input, materialized, lifecycleRepository, readRequest, preparing); + } + + /** Actual materialization and activation with only upstream owner authority stipulated. */ + private PlacementFixture initialPlayerLocationFixture() { + return initialPlayerLocationFixture(InitialAdmissionOrigin.NO_PRIOR_POINTER); + } + + private PlacementFixture initialPlayerLocationFixture(InitialAdmissionOrigin origin) { + PreparedLifecycleFixture lifecycleFixture = materializedLifecycleFixture(); + var activation = + canonicalActivationService(lifecycleFixture, ignored -> stipulatedActivationAuthority()) + .activate( + new WorldCanonicalInstanceActivation.Request( + UUID.randomUUID(), lifecycleFixture.preparing())); + assertThat(activation.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + var activeEvidence = + lifecycleFixture + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(activation.lifecycleEvidence().request())) + .orElseThrow(); + assertThat(activeEvidence.lifecycleStatus()).isEqualTo("ACTIVE"); + + UUID realmId = UUID.randomUUID(); + String initialAdmissionRequestId = "placement-admission-" + UUID.randomUUID(); + String initialAdmissionRequestDigest = "f".repeat(64); + long catalogRevision = origin == InitialAdmissionOrigin.NO_PRIOR_POINTER ? 1L : 2L; + // EXPECT_CLOSED is an upstream stipulation here, not owner proof the realm was never OPEN. + Long expectedPriorPointerVersion = origin == InitialAdmissionOrigin.EXPECT_CLOSED ? 7L : null; + Request holdRequest = + new Request( + activeEvidence.request().targetNamespace(), + activeEvidence.request().canonicalTenantId(), + activeEvidence.request().worldSlug(), + realmId, + activeEvidence.request().playableStateNamespaceId(), + activeEvidence.request().playableStateScope(), + activeEvidence.request().canonicalGameInstanceId(), + activeEvidence.request().canonicalVersionId(), + activeEvidence.lifecycleEpoch(), + initialAdmissionRequestId, + initialAdmissionRequestDigest, + origin, + catalogRevision, + expectedPriorPointerVersion); + var holdRepository = + new WorldCanonicalInitialAdmissionHoldRepository( + dsl, manager, associationRepository(), lifecycleFixture.lifecycleRepository()); + HoldIdentity hold = holdRepository.acquire(holdRequest, activeEvidence.request()); + assertThat(holdRepository.readIdentity(holdRequest)).contains(hold); + + long pointerVersion = + origin == InitialAdmissionOrigin.NO_PRIOR_POINTER + ? 1L + : Math.addExact(Objects.requireNonNull(expectedPriorPointerVersion), 1L); + // This upstream Game Session outcome is supplied to World through a test-only verifier double. + GameSessionCanonicalInitialAdmissionOwnerProof stipulatedOwnerProof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + pointerVersion, + 41L, + "sha256:" + "c".repeat(64), + false, + Instant.parse("2026-10-07T01:02:03.123456Z")); + var holdFinalizationRepository = + new WorldCanonicalInitialAdmissionHoldFinalizationRepository( + dsl, manager, associationRepository(), lifecycleFixture.lifecycleRepository()); + var finalizationService = + new WorldCanonicalInitialAdmissionHoldFinalizationService( + holdFinalizationRepository, + stipulatedCanonicalGameSessionOwnerProofVerifier(stipulatedOwnerProof)); + GameSessionCanonicalInitialAdmissionOwnerProof terminal = + finalizationService.finalizeHold( + hold, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(terminal).isEqualTo(stipulatedOwnerProof); + assertThat(terminal.holdIdentity().canonicalBytes()).containsExactly(hold.canonicalBytes()); + + byte[] canonicalOwnerProofBytes = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(stipulatedOwnerProof); + Record storedHold = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT hold_id, hold_fence, status, initial_admission_request_id, " + + "request_digest, expected_catalog_revision, initial_admission_origin, " + + "expected_prior_pointer_version, canonical_request_bytes, hold_binding_digest, " + + "owner_proof_id, owner_proof_digest, owner_pointer_audit_id, " + + "owner_pointer_version, terminal_at, canonical_owner_proof_bytes, " + + "canonical_owner_proof_digest FROM initial_admission_bind_hold " + + "WHERE hold_id = ?", + hold.holdId())); + assertThat(storedHold.get("hold_id", UUID.class)).isEqualTo(hold.holdId()); + assertThat(storedHold.get("hold_fence", UUID.class)).isEqualTo(hold.holdFence()); + assertThat(storedHold.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(storedHold.get("initial_admission_request_id", String.class)) + .isEqualTo(holdRequest.initialAdmissionRequestId()); + assertThat(storedHold.get("request_digest", String.class)) + .isEqualTo(holdRequest.initialAdmissionRequestDigest()); + assertThat(storedHold.get("expected_catalog_revision", Long.class)) + .isEqualTo(holdRequest.expectedCatalogRevision()); + assertThat(storedHold.get("initial_admission_origin", String.class)).isEqualTo(origin.name()); + assertThat(storedHold.get("expected_prior_pointer_version", Long.class)) + .isEqualTo(expectedPriorPointerVersion); + assertThat(storedHold.get("canonical_request_bytes", byte[].class)) + .containsExactly(holdRequest.canonicalRequestBytes()); + assertThat(storedHold.get("hold_binding_digest", String.class)) + .isEqualTo(hold.holdBindingDigest()); + assertThat(storedHold.get("owner_proof_id", String.class)) + .isEqualTo(holdRequest.initialAdmissionRequestId()); + assertThat(storedHold.get("owner_proof_digest", String.class)) + .isEqualTo(stipulatedOwnerProof.proofDigest().substring("sha256:".length())); + assertThat(storedHold.get("owner_pointer_audit_id", String.class)) + .isEqualTo(Long.toString(Objects.requireNonNull(stipulatedOwnerProof.auditEventId()))); + assertThat(storedHold.get("owner_pointer_version", Long.class)) + .isEqualTo(stipulatedOwnerProof.committedPointerVersion()); + assertThat(storedHold.get("terminal_at", LocalDateTime.class)) + .isEqualTo(LocalDateTime.ofInstant(stipulatedOwnerProof.terminalAt(), ZoneOffset.UTC)); + assertThat(storedHold.get("canonical_owner_proof_bytes", byte[].class)) + .containsExactly(canonicalOwnerProofBytes); + assertThat(storedHold.get("canonical_owner_proof_digest", String.class)) + .isEqualTo(sha256Digest(canonicalOwnerProofBytes)); + + var repository = + new WorldCanonicalInitialPlayerLocationRepository( + dsl, + manager, + lifecycleFixture.lifecycleRepository(), + associationRepository(), + holdFinalizationRepository); + var service = + new WorldCanonicalInitialPlayerLocationService( + repository, ignored -> stipulatedPlacementAuthority()); + var fixture = + new PlacementFixture( + lifecycleFixture, + activeEvidence, + hold, + stipulatedOwnerProof, + repository, + service, + null); + WorldCanonicalInitialPlayerLocation.Request request = + initialLocationRequest( + fixture, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + activeEvidence); + return new PlacementFixture( + lifecycleFixture, activeEvidence, hold, stipulatedOwnerProof, repository, service, request); + } + + private WorldCanonicalCurrentPlayerLocationService currentLocationReadService( + PlacementFixture fixture) { + var repository = + new WorldCanonicalCurrentPlayerLocationRepository( + dsl, + manager, + fixture.lifecycle().lifecycleRepository(), + associationRepository(), + new WorldCanonicalInitialAdmissionHoldFinalizationRepository( + dsl, manager, associationRepository(), fixture.lifecycle().lifecycleRepository()), + fixture.repository()); + return new WorldCanonicalCurrentPlayerLocationService( + repository, ignored -> stipulatedPlacementAuthority()); + } + + private WorldCanonicalInitialPlayerLocation.Request initialLocationRequest( + PlacementFixture fixture, + UUID operationId, + UUID characterId, + UUID assignmentOperationId, + String assignmentDigest, + WorldCanonicalInstanceLifecycleEvidence activeEvidence) { + var hold = fixture.hold(); + var holdRequest = hold.request(); + var ownerProof = fixture.ownerProof(); + return new WorldCanonicalInitialPlayerLocation.Request( + operationId, + activeEvidence.request().canonicalTenantId(), + holdRequest.realmId(), + activeEvidence.request().worldSlug(), + activeEvidence.request().canonicalGameInstanceId(), + activeEvidence.request().playableStateNamespaceId(), + activeEvidence.request().playableStateScope(), + fixture.request() == null ? UUID.randomUUID() : fixture.request().canonicalAccountId(), + characterId, + assignmentOperationId, + assignmentDigest, + hold.holdId(), + hold.holdFence(), + holdRequest.initialAdmissionRequestId(), + holdRequest.initialAdmissionRequestDigest(), + holdRequest.expectedCatalogRevision(), + holdRequest.initialAdmissionRequestId(), + ownerProof.proofDigest().substring("sha256:".length()), + Long.toString(Objects.requireNonNull(ownerProof.auditEventId())), + Objects.requireNonNull(ownerProof.committedPointerVersion()), + WorldCanonicalInitialPlayerLocation.InitialAdmissionOrigin.valueOf( + holdRequest.initialAdmissionOrigin().name()), + activeEvidence); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequestWithFreshReadId( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + request.schemaVersion(), + UUID.randomUUID(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.publicProduction(), + request.controlPlaneRequestId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest()); + } + + private static WorldCanonicalInitialPlayerLocationService.HeldPlacementAuthority + stipulatedPlacementAuthority() { + return new WorldCanonicalInitialPlayerLocationService.HeldPlacementAuthority() { + private boolean open = true; + + @Override + public void requireHeld() { + assertThat(open).isTrue(); + } + + @Override + public void close() { + open = false; + } + }; + } + + /** + * Test double that stipulates a held Game Session proof for World component coverage. This is not + * genuine Game Session authentication or pointer commit evidence, multi-owner proof, or mTLS + * proof. + */ + private static WorldCanonicalInitialAdmissionHoldFinalizationService.OwnerProofVerifier + stipulatedCanonicalGameSessionOwnerProofVerifier( + GameSessionCanonicalInitialAdmissionOwnerProof ownerProof) { + return (identity, expectedOutcome) -> { + if (!identity.equals(ownerProof.holdIdentity()) || ownerProof.outcome() != expectedOutcome) { + throw new IllegalArgumentException( + "Stipulated Game Session owner proof differs from the requested hold or outcome"); + } + return new WorldCanonicalInitialAdmissionHoldFinalizationService.HeldOwnerProof() { + private boolean open = true; + + @Override + public GameSessionCanonicalInitialAdmissionOwnerProof proof() { + return ownerProof; + } + + @Override + public void requireHeld() { + assertThat(open).isTrue(); + } + + @Override + public void close() { + open = false; + } + }; + }; + } + + private Record initialLocationOperation(UUID operationId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT request_digest, request_bytes, original_lifecycle_evidence_bytes, outcome, " + + "conflict_code, result_bytes, result_digest FROM " + + "world_canonical_initial_player_location_operation WHERE operation_id=?", + operationId)); + } + + private long countInitialLocationOperations(UUID canonicalGameInstanceId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_initial_player_location_operation " + + "WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)) + .get(0, Long.class); + } + + private long countInitialLocations(UUID canonicalGameInstanceId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM character_location WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)) + .get(0, Long.class); + } + + private String initialLocationSnapshot(UUID canonicalGameInstanceId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT COALESCE(jsonb_agg(to_jsonb(l) ORDER BY l.character_id)::text,'[]') " + + "FROM character_location l WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)) + .get(0, String.class); + } + + private WorldCanonicalInstanceActivationService canonicalActivationService( + PreparedLifecycleFixture fixture, + WorldCanonicalInstanceActivationService.ActivationAuthorityVerifier verifier) { + return new WorldCanonicalInstanceActivationService( + new WorldCanonicalInstanceActivationRepository(dsl, manager, fixture.lifecycleRepository()), + verifier); + } + + private void assertActivationManifestMismatch( + PreparedLifecycleFixture fixture, + String savepoint, + String manifestTamperSql, + String attemptedUpdateSql) { + ownerTransaction() + .execute( + status -> { + dsl.execute("SAVEPOINT " + savepoint); + var proof = rawCommittedActivationProof(fixture); + insertRawActivationOperation( + proof, fixture.materialized().association().worldInstanceId()); + if (manifestTamperSql != null) { + dsl.execute(manifestTamperSql, proof.request().activationRequestId()); + } + assertThatThrownBy( + () -> + dsl.execute( + attemptedUpdateSql, + fixture.materialized().association().worldInstanceId())) + .hasMessageContaining("no exact transaction execution manifest"); + dsl.execute("ROLLBACK TO SAVEPOINT " + savepoint); + assertThat(activationOperationCountForRequest(proof.request().activationRequestId())) + .isZero(); + assertThat(activationManifestCountForRequest(proof.request().activationRequestId())) + .isZero(); + return null; + }); + } + + private ActivationProof rawCommittedActivationProof(PreparedLifecycleFixture fixture) { + var request = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var predictedActive = + new WorldCanonicalInstanceLifecycleEvidence( + fixture.preparing().request(), + fixture.preparing().launchBinding(), + fixture.preparing().startLocation(), + fixture.preparing().runtimeRoomInstanceId(), + "ACTIVE", + fixture.preparing().lifecycleEpoch() + 1L, + fixture.preparing().rowVersion() + 1L, + fixture.preparing().captureId(), + fixture.preparing().graphSha256(), + fixture.preparing().preparationInputDigest(), + fixture.preparing().operationalRegionAssignments()); + return new ActivationProof( + request, + new WorldCanonicalInstanceActivation.Result( + request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, predictedActive)); + } + + private ActivationProof rawCommittedActivationProofWithAssignments( + PreparedLifecycleFixture fixture, Map assignments) { + var preparing = + new WorldCanonicalInstanceLifecycleEvidence( + fixture.preparing().request(), + fixture.preparing().launchBinding(), + fixture.preparing().startLocation(), + fixture.preparing().runtimeRoomInstanceId(), + "PREPARING", + fixture.preparing().lifecycleEpoch(), + fixture.preparing().rowVersion(), + fixture.preparing().captureId(), + fixture.preparing().graphSha256(), + fixture.preparing().preparationInputDigest(), + assignments); + var request = new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), preparing); + var active = + new WorldCanonicalInstanceLifecycleEvidence( + preparing.request(), + preparing.launchBinding(), + preparing.startLocation(), + preparing.runtimeRoomInstanceId(), + "ACTIVE", + preparing.lifecycleEpoch() + 1L, + preparing.rowVersion() + 1L, + preparing.captureId(), + preparing.graphSha256(), + preparing.preparationInputDigest(), + assignments); + return new ActivationProof( + request, + new WorldCanonicalInstanceActivation.Result( + request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, active)); + } + + private void insertRawActivationOperation(ActivationProof proof, long worldInstanceId) { + var request = proof.request(); + var result = proof.result(); + byte[] requestBytes = request.canonicalRequestBytes(); + byte[] resultBytes = result.canonicalBytes(); + dsl.execute( + "INSERT INTO world_canonical_instance_activation_operation " + + "(activation_request_id,request_digest,request_bytes,preparing_evidence_bytes," + + "canonical_game_instance_id,world_instance_id,expected_lifecycle_epoch,expected_row_version," + + "outcome,terminal_code,result_lifecycle_epoch,result_row_version,result_bytes,result_digest) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + request.activationRequestId(), + request.requestDigest(), + requestBytes, + request.preparingEvidenceBytes(), + request.canonicalGameInstanceId(), + worldInstanceId, + request.expectedLifecycleEpoch(), + request.expectedRowVersion(), + "COMMITTED", + null, + result.lifecycleEvidence().lifecycleEpoch(), + result.lifecycleEvidence().rowVersion(), + resultBytes, + sha256Digest(resultBytes)); + } + + private long activationOperationCountForRequest(UUID requestId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + requestId)) + .get(0, Long.class); + } + + private long activationManifestCount(UUID canonicalGameInstanceId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_activation_execution_manifest WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)) + .get(0, Long.class); + } + + private long activationManifestCountForRequest(UUID requestId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_activation_execution_manifest WHERE activation_request_id=?", + requestId)) + .get(0, Long.class); + } + + /** + * Synthetic fixture fence only; it does not authenticate live source, release, or Account state. + */ + private static WorldCanonicalInstanceActivationService.HeldActivationAuthority + stipulatedActivationAuthority() { + return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + private boolean open = true; + + public void requireHeld() { + assertThat(open).isTrue(); + } + + public void close() { + open = false; + } + }; + } + + private static String sha256Digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new AssertionError(unavailable); + } + } + + private byte[] preparationRows(UUID instance) { + return Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT convert_to(jsonb_build_object('preparation',to_jsonb(p),'selector',to_jsonb(s))::text,'UTF8') " + + "FROM world_canonical_instance_preparation p LEFT JOIN world_canonical_preparation_start_location s USING(canonical_game_instance_id) WHERE p.canonical_game_instance_id=?", + instance)) + .get(0, byte[].class)); + } + + private long completeLaunchBindingCount( + String targetNamespace, UUID canonicalTenantId, String controlPlaneRequestId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_complete_launch_binding WHERE target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?", + targetNamespace, + canonicalTenantId, + controlPlaneRequestId)) + .get(0, Long.class); + } + + private org.jooq.Record materializedOperationalRegionRow( + UUID canonicalGameInstanceId, + UUID regionTemplateId, + UUID zoneTemplateId, + UUID roomTemplateId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(ri)::text AS region_row_json,ri.id AS region_row_id," + + "ri.operational_region_id,ri.canonical_region_instance_id," + + "region_map.runtime_identity AS canonical_runtime_identity," + + "ri.tenant_id AS region_tenant_id,room.tenant_id AS room_tenant_id," + + "ri.game_instance_id AS region_game_instance_id,room.game_instance_id AS room_game_instance_id," + + "room.region_instance_id AS room_region_instance_id," + + "zone.region_instance_id AS zone_region_instance_id,zone.id AS zone_row_id," + + "room.zone_instance_id AS room_zone_instance_id " + + "FROM world_canonical_instance_topology_identity region_map " + + "JOIN region_instance ri ON ri.id=region_map.runtime_row_id " + + "JOIN world_canonical_instance_topology_identity room_map " + + "ON room_map.canonical_game_instance_id=region_map.canonical_game_instance_id " + + "AND room_map.world_instance_id=region_map.world_instance_id " + + "AND room_map.family='ROOM' AND room_map.template_id=? " + + "JOIN room_instance room ON room.id=room_map.runtime_row_id " + + "JOIN zone_instance zone ON zone.id=room.zone_instance_id " + + "JOIN world_canonical_instance_topology_identity zone_map " + + "ON zone_map.canonical_game_instance_id=region_map.canonical_game_instance_id " + + "AND zone_map.world_instance_id=region_map.world_instance_id " + + "AND zone_map.runtime_row_id=zone.id AND zone_map.family='ZONE' " + + "AND zone_map.template_id=? " + + "WHERE region_map.canonical_game_instance_id=? AND region_map.family='REGION' " + + "AND region_map.template_id=? AND region_map.runtime_row_id=room.region_instance_id " + + "AND room.region_instance_id=zone.region_instance_id", + roomTemplateId, + zoneTemplateId, + canonicalGameInstanceId, + regionTemplateId)); + } + + private Map materializedOperationalRegionAssignments(UUID canonicalGameInstanceId) { + var rows = + dsl.fetch( + "SELECT ri.canonical_region_instance_id,ri.operational_region_id " + + "FROM world_canonical_instance_preparation p " + + "JOIN region_instance ri ON ri.world_instance_id=p.world_instance_id " + + "WHERE p.canonical_game_instance_id=? " + + "ORDER BY ri.canonical_region_instance_id", + canonicalGameInstanceId); + Map assignments = new LinkedHashMap<>(); + for (Record row : rows) { + UUID canonical = row.get("canonical_region_instance_id", UUID.class); + UUID operational = row.get("operational_region_id", UUID.class); + assertThat(canonical).isNotNull(); + assertThat(operational).isNotNull().isNotEqualTo(canonical); + assertThat(assignments.putIfAbsent(canonical, operational)).isNull(); + } + return assignments; + } + + private void mutateWithUserTriggersDisabled(String table, Runnable mutation) { + dsl.execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); + try { + mutation.run(); + } finally { + dsl.execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); + } + } + + private Record queryWithUserTriggersDisabled( + String table, java.util.function.Supplier mutation) { + dsl.execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); + try { + return mutation.get(); + } finally { + dsl.execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); + } + } + + private static T required(Record row, String field, Class type) { + return Objects.requireNonNull(row.get(field, type), "Persisted " + field + " is null"); + } + + private PrepareCanonicalWorldInstanceResponse invokePreparationAsGameSession( + WorldCanonicalInstancePreparationGrpcService adapter, + net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceRequest request) { + var response = new PreparationCollector(); + Context context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service", + NAMESPACE, + "game-session-service")); + Context previous = context.attach(); + try { + SessionContext.clear(); + adapter.prepareCanonicalWorldInstance(request, response); + } finally { + context.detach(previous); + SessionContext.clear(); + } + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value).isNotNull(); + return response.value; + } + + @Test + void publishedSelectorJoinsExactFrozenCheckpointToOriginalAppliedWithoutWrites() { + Fixture f = fixture(); + var application = application(f); + var applied = appliedComponent().apply(application); + var capture = capture(application.plan()); + var request = capture.request().freeze(); + var source = publishedSelectors().readCommitted(request).orElseThrow(); + assertThat(source.selectorReceipt()).isEqualTo(applied.startLocationReceipt().orElseThrow()); + assertThat(source.appliedResult().canonicalBytes()).containsExactly(applied.canonicalBytes()); + assertThat(source.frozenTopology().resultBytes()).containsExactly(capture.resultBytes()); + assertThat(source.frozenTopology().status()).isEqualTo("CAPTURED_UNVERIFIED"); + assertThat(source.appliedResult().application().operation().accountBindingBytes()) + .containsExactly(application.operation().accountBindingBytes()); + var another = application(fixture()); + var anotherResult = appliedComponent().apply(another); + var substitutedApplications = + org.mockito.Mockito.mock(WorldDraftGraphApplicationRepository.class); + org.mockito.Mockito.when( + substitutedApplications.readCommitted( + org.mockito.ArgumentMatchers.eq(NAMESPACE), + org.mockito.ArgumentMatchers.any(byte[].class))) + .thenReturn(java.util.Optional.of(anotherResult)); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationRepository( + dsl, frozenRepository(), substitutedApplications) + .readCommitted(request)) + .hasMessageContaining("differs from original frozen application"); + // A plausible result for a distinct Account operation on the same plan is also substitution. + org.mockito.Mockito.when( + substitutedApplications.readCommitted( + org.mockito.ArgumentMatchers.eq(NAMESPACE), + org.mockito.ArgumentMatchers.any(byte[].class))) + .thenReturn( + java.util.Optional.of( + WorldDraftGraphAppliedResult.create( + changedAccountApplication(application), applied.graphBytes()))); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationRepository( + dsl, frozenRepository(), substitutedApplications) + .readCommitted(request)) + .hasMessageContaining("differs from original frozen application"); + byte[] before = retainedApplicationBytes(application); + assertThat(publishedSelectors().readCommitted(request).orElseThrow().selectorReceipt()) + .isEqualTo(source.selectorReceipt()); + assertThat(retainedApplicationBytes(application)).containsExactly(before); + assertThat(count(f, "world_draft_graph_application")).isEqualTo(1); + assertThat(count(f, "world_draft_start_location_receipt")).isEqualTo(1); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.publicationFence())) + .get(0, Long.class)) + .isEqualTo(1L); + assertThatThrownBy( + () -> + publishedSelectors() + .readCommitted( + changedSelection(request, "changed-request", request.contentDigest()))) + .hasMessageContaining("canonical full-version workflow identity"); + assertThatThrownBy( + () -> + publishedSelectors() + .readCommitted( + changedSelection(request, request.publicationRequestId(), "c".repeat(64)))) + .hasMessageContaining("changed complete input or checkpoint"); + assertThatThrownBy( + () -> ownerTransaction().execute(status -> publishedSelectors().readCommitted(request))) + .hasMessageContaining("no caller transaction"); + assertOrigin(); + } + + @Test + void publishedSelectorOwnedReadUsesOneActualReadOnlyRepeatableReadSnapshot() { + Fixture f = fixture(); + var application = application(f); + var applied = appliedComponent().apply(application); + var capture = capture(application.plan()); + var request = capture.request().freeze(); + byte[] originalApplication = retainedApplicationBytes(application); + long applicationCount = count(f, "world_draft_graph_application"); + long receiptCount = count(f, "world_draft_start_location_receipt"); + long frozenCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.publicationFence())) + .get(0, Long.class); + Map preparationRowsBeforeRead = preparationHistoryRows(); + + TransactionTemplate ownedSnapshot = new TransactionTemplate(manager); + ownedSnapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownedSnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownedSnapshot.setReadOnly(true); + var source = + Objects.requireNonNull( + ownedSnapshot.execute( + status -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isTrue(); + assertThat( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_REPEATABLE_READ); + assertThat(dsl.fetchOne("SELECT current_setting('transaction_isolation')").get(0)) + .isEqualTo("repeatable read"); + assertThat(dsl.fetchOne("SELECT current_setting('transaction_read_only')").get(0)) + .isEqualTo("on"); + return publishedSelectors().readInOwnedSnapshot(request).orElseThrow(); + })); + + assertThat(source.selectorReceipt()).isEqualTo(applied.startLocationReceipt().orElseThrow()); + assertThat(source.frozenTopology().captureId()).isEqualTo(capture.captureId()); + assertThat(source.frozenTopology().resultBytes()).containsExactly(capture.resultBytes()); + assertThat(source.appliedResult().canonicalBytes()).containsExactly(applied.canonicalBytes()); + assertThat(source.appliedResult().application().operation().accountBindingBytes()) + .containsExactly(application.operation().accountBindingBytes()); + + TransactionTemplate wrongIsolation = new TransactionTemplate(manager); + wrongIsolation.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + wrongIsolation.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + wrongIsolation.setReadOnly(true); + assertThatThrownBy( + () -> + wrongIsolation.execute(status -> publishedSelectors().readInOwnedSnapshot(request))) + .hasMessageContaining("read-only REPEATABLE READ owner transaction"); + + assertThat(retainedApplicationBytes(application)).containsExactly(originalApplication); + assertThat(count(f, "world_draft_graph_application")).isEqualTo(applicationCount); + assertThat(count(f, "world_draft_start_location_receipt")).isEqualTo(receiptCount); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_frozen_topology WHERE publication_fence=?", + request.publicationFence())) + .get(0, Long.class)) + .isEqualTo(frozenCount); + // The source reader is pre-PREPARING: it does not allocate any runtime world row. + assertThat(preparationHistoryRows()).isEqualTo(preparationRowsBeforeRead); + assertOrigin(); + } + + @Test + void publishedSpawnRequirementsOwnerProjectsOnlyRealFrozenAndAppliedSource() { + Fixture f = fixture(); + var application = application(f); + appliedComponent().apply(application); + var capture = capture(application.plan()); + var frozen = capture.request().freeze(); + var source = publishedSelectors().readCommitted(frozen).orElseThrow(); + var selector = publishedEvidence(source); + var launchBinding = + preparationLaunchFixture(f, source.frozenTopology(), selector, 2L, List.of("LOOK")) + .evidence(); + var descriptor = launchBinding.descriptor(); + UUID readId = UUID.randomUUID(); + var launchRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(readId.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + var request = + new WorldPublishedSpawnRequirementsEvidence.Request( + NAMESPACE, readId, launchRequest, launchBinding.releaseAttestation().evidenceDigest()); + var wireRequest = WorldPublishedSpawnRequirementsGrpcCodec.toRequest(request); + + // The authenticated Game Design pair is a labeled upstream double; the World rows below are + // the actual migrated PostgreSQL application, original APPLIED receipt, and frozen capture. + var gameDesign = Mockito.mock(AuthoredWorldLaunchDescriptorClient.class); + Mockito.when(gameDesign.getComplete(launchRequest)).thenReturn(launchBinding); + var owner = + new WorldPublishedSpawnRequirementsReadOwner( + NAMESPACE, gameDesign, publishedSelectors(), manager); + Map before = preparationHistoryRows(); + var entityContext = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/entity-management-service", + NAMESPACE, + "entity-management-service")); + Context previous = entityContext.attach(); + WorldPublishedSpawnRequirementsEvidence evidence; + try { + SessionContext.clear(); + evidence = owner.read(wireRequest); + } finally { + Context.current().detach(previous); + SessionContext.clear(); + } + + assertThat(evidence.captureId()).isEqualTo(capture.captureId()); + assertThat(evidence.graphDigest()) + .isEqualTo(WorldDraftGraphAppliedResult.digest(capture.graphBytes())); + assertThat(evidence.familyCounts()).hasSize(6); + assertThat(evidence.familyCounts()).extracting("count").contains(1); + assertThat(evidence.spawnRequirements()).hasSize(1); + assertThat(evidence.spawnRequirements().getFirst().respawnDelaySeconds()).isEqualTo(17); + assertThat(evidence.spawnRequirements().getFirst().entityTemplate().kind()) + .isEqualTo(EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC); + assertThat(evidence.generationRequirements()).hasSize(1); + assertThat(evidence.generationRequirements().getFirst().name()).isEqualTo("rule"); + assertThat(evidence.generationRequirements().getFirst().value()).isEqualTo("seeded"); + assertThat(preparationHistoryRows()).isEqualTo(before); + Mockito.verify(gameDesign).getComplete(launchRequest); + assertOrigin(); + } + + @Test + void publishedSpawnRequirementsOwnerPreservesExplicitZeroOptionalFamilies() { + Fixture f = fixture(); + var application = application(plan(f, true)); + appliedComponent().apply(application); + var capture = capture(application.plan()); + var source = publishedSelectors().readCommitted(capture.request().freeze()).orElseThrow(); + var launchBinding = + preparationLaunchFixture( + f, source.frozenTopology(), publishedEvidence(source), 2L, List.of("LOOK")) + .evidence(); + var descriptor = launchBinding.descriptor(); + UUID readId = UUID.randomUUID(); + var launchRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(readId.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + var request = + new WorldPublishedSpawnRequirementsEvidence.Request( + NAMESPACE, readId, launchRequest, launchBinding.releaseAttestation().evidenceDigest()); + var gameDesign = Mockito.mock(AuthoredWorldLaunchDescriptorClient.class); + Mockito.when(gameDesign.getComplete(launchRequest)).thenReturn(launchBinding); + var owner = + new WorldPublishedSpawnRequirementsReadOwner( + NAMESPACE, gameDesign, publishedSelectors(), manager); + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/entity-management-service", + NAMESPACE, + "entity-management-service")); + Context previous = context.attach(); + WorldPublishedSpawnRequirementsEvidence evidence; + try { + SessionContext.clear(); + evidence = owner.read(WorldPublishedSpawnRequirementsGrpcCodec.toRequest(request)); + } finally { + Context.current().detach(previous); + SessionContext.clear(); + } + + assertThat(evidence.familyCounts()).hasSize(6); + assertThat(evidence.familyCounts()) + .filteredOn( + count -> + count.family() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .singleElement() + .extracting("count") + .isEqualTo(0); + assertThat(evidence.familyCounts()) + .filteredOn( + count -> + count.family() + == WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) + .singleElement() + .extracting("count") + .isEqualTo(0); + assertThat(evidence.spawnRequirements()).isEmpty(); + assertThat(evidence.generationRequirements()).isEmpty(); + assertOrigin(); + } + + @Test + void permissionUnverifiedGraphAndFrozenHistoryCannotSupplyPublishedSelector() { + var plan = plan(fixture()); + component().store(plan); + var capture = capture(plan); + assertThat(frozenRepository().readCommitted(capture.request().freeze())).isPresent(); + assertThatThrownBy(() -> publishedSelectors().readCommitted(capture.request().freeze())) + .hasMessageContaining("lacks original APPLIED application"); + TransactionTemplate ownedSnapshot = new TransactionTemplate(manager); + ownedSnapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownedSnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownedSnapshot.setReadOnly(true); + assertThatThrownBy( + () -> + ownedSnapshot.execute( + status -> publishedSelectors().readInOwnedSnapshot(capture.request().freeze()))) + .hasMessageContaining("lacks original APPLIED application"); + assertOrigin(); + } + + private byte[] retainedApplicationBytes(WorldDraftGraphApplication application) { + return Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT convert_to(to_jsonb(a)::text,'UTF8') FROM world_draft_graph_application a WHERE operation_id=?", + application.operation().operationId())) + .get(0, byte[].class)); + } + + private WorldAuthoredGraphSnapshot.CaptureRequest changedSelection( + WorldAuthoredGraphSnapshot.CaptureRequest request, String publicationRequest, String digest) { + return new WorldAuthoredGraphSnapshot.CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + publicationRequest, + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + digest, + request.digestSchemaVersion(), + request.suppliedOwnedAffectedTuples()); + } + + private WorldCanonicalFrozenTopologyRepository frozenRepository() { + return new WorldCanonicalFrozenTopologyRepository(dsl, snapshots, repository(), digestService); + } + + private WorldPublishedStartLocationRepository publishedSelectors() { + return new WorldPublishedStartLocationRepository(dsl, frozenRepository(), appliedRepository()); + } + + private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) { + var owner = plan.ownerBinding(); + String publicationRequest = "selector-" + UUID.randomUUID(); + var selection = publicationSelection(plan, publicationRequest, 1L); + var evidence = + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + publicationRequest, + selection.digest().substring("sha256:".length()), + 1, + "publish:" + owner.canonicalTenantId() + ":publish-request:" + publicationRequest); + var attempt = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, + () -> { + var identity = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT local_tenant_key,local_version_key FROM world_authored_version_identity WHERE operation_id=?", + owner.versionIdentityOperationId())); + var digest = + digestService.getDraftDesignDigest( + identity.get("local_tenant_key", Long.class).toString(), + identity.get("local_version_key", Long.class).toString()); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + plan.binding().commitId().toString(), digest.contentDigest(), 3); + }))); + var tuples = + plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldAuthoredGraphSnapshot.CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + attempt.publicationFence(), + publicationRequest, + evidence.requestDigest(), + evidence.versionStateEpoch(), + evidence.publishWorkflowId(), + attempt.checkpoint().appliedCommitId(), + attempt.checkpoint().contentDigest(), + attempt.checkpoint().digestSchemaVersion(), + tuples); + return new WorldCanonicalFrozenTopologyService(frozenRepository(), manager) + .capture(new WorldCanonicalFrozenTopology.Request(plan, request)); + } + + @Test + void freshApplicationRetainsCompleteExactGraphAndOriginalAccountReadbackAndRetriesAfterFreeze() { + Fixture f = fixture(); + var application = application(f); + var result = appliedComponent().apply(application); + assertThat(result.status()).isEqualTo("APPLIED"); + assertThat(result.appliedEpochs()) + .hasSize(application.operation().binding().affectedUnits(Owner.WORLD_MANAGEMENT).size()); + assertThat(result.appliedEpochs()) + .allMatch(epoch -> epoch.expectedEpoch().equals("0") && epoch.resultingEpoch().equals("1")); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + assertThat(count(f, "world_design_aggregate_epoch")).isEqualTo(7); + assertThat(count(f, "world_design_scope_epoch")).isEqualTo(1); + for (String family : + List.of("region", "zone", "room_exit", "generation_rule", "world_entity_spawn_binding")) { + assertThat(count(f, family)).isEqualTo(1); + } + assertThat(count(f, "room")).isEqualTo(2); + var readback = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback + .fromStored(result.ownerReadback().canonicalBytes()); + assertThat(readback.owner()) + .isEqualTo( + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner.WORLD); + assertThat(readback.outcome()) + .isEqualTo( + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome + .COMMITTED); + readback.requireBinding( + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.fromStored( + application.operation().accountBindingBytes())); + assertThat(readback.fullBinding()) + .containsExactly(application.operation().accountBindingBytes()); + assertThat(readback.result()).containsExactly(result.canonicalBytes()); + assertThat( + appliedRepository() + .readCommitted(NAMESPACE, application.operation().accountBindingBytes()) + .orElseThrow() + .ownerReadback() + .canonicalBytes()) + .containsExactly(readback.canonicalBytes()); + var changed = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.fromStored( + changedAccountApplication(application).operation().accountBindingBytes()); + assertThatThrownBy(() -> readback.requireBinding(changed)) + .hasMessageContaining("complete Draft binding"); + assertThatThrownBy(() -> appliedRepository().readCommitted(NAMESPACE, changed.canonicalBytes())) + .hasMessageContaining("full Account binding"); + assertThatThrownBy( + () -> + appliedRepository() + .readCommitted( + "another-workload", application.operation().accountBindingBytes())) + .hasMessageContaining("namespace"); + freeze(f); + // Exact replay reads immutable evidence and does not need a newly acquired authorization. + var retry = + new WorldDraftGraphApplicationService(appliedRepository(), manager).apply(application); + assertThat(retry.canonicalBytes()).containsExactly(result.canonicalBytes()); + assertThat(retry.graphBytes()).containsExactly(result.graphBytes()); + assertThat(retry.startLocationReceipt()).contains(result.startLocationReceipt().orElseThrow()); + assertThat( + appliedRepository() + .readSynchronized(visibility(application, result, result.canonicalBytes()))) + .isPresent(); + } + + @Test + void explicitEmptyOptionalFamiliesProduceAppliedGraphAndExactTypedStartSelector() { + Fixture f = fixture(); + var application = application(plan(f, true)); + var result = appliedComponent().apply(application); + + assertThat(result.status()).isEqualTo("APPLIED"); + assertThat(result.startLocationReceipt()).isPresent(); + var receipt = result.startLocationReceipt().orElseThrow(); + assertThat(receipt.startLocation().tenantId()) + .isEqualTo(application.operation().canonicalTenantId()); + assertThat(receipt.startLocation().versionId()) + .isEqualTo(application.operation().canonicalVersionId()); + assertThat(receipt.startLocation().roomTemplateId()) + .isEqualTo( + application + .plan() + .graph() + .freshGraphDeclaration() + .orElseThrow() + .startLocation() + .roomTemplateId()); + assertThat(application.plan().graph().freshGraphDeclaration().orElseThrow().familyCounts()) + .extracting(WorldDraftTopologyInputGraph.FamilyCount::count) + .containsExactly(1, 1, 1, 0, 0, 0); + assertThat(count(f, "region")).isEqualTo(1); + assertThat(count(f, "zone")).isEqualTo(1); + assertThat(count(f, "room")).isEqualTo(1); + for (String family : List.of("room_exit", "generation_rule", "world_entity_spawn_binding")) { + assertThat(count(f, family)).isZero(); + } + assertThat(count(f, "world_draft_start_location_receipt")).isEqualTo(1); + assertThat(appliedRepository().readCommitted(application).orElseThrow().startLocationReceipt()) + .contains(receipt); + assertThat( + appliedRepository() + .readCommitted(NAMESPACE, application.operation().accountBindingBytes()) + .orElseThrow() + .startLocationReceipt()) + .contains(receipt); + } + + @Test + void newAccountBoundGraphRequiresCompleteOriginalDeclaration() { + Fixture f = fixture(); + var historicalPlan = withoutFreshGraphDeclaration(plan(f)); + var application = application(historicalPlan); + + assertThatThrownBy(() -> appliedComponent().apply(application)) + .hasMessageContaining("require the complete original fresh-graph declaration"); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_authored_topology_identity", + "world_topology_draft_commit", + "world_draft_graph_application", + "world_draft_start_location_receipt")) { + assertThat(count(f, table)).isZero(); + } + } + + @Test + void authenticatedReceiverReadsGenuineCommittedReceiptAndReplaysAfterFreeze() { + Fixture f = fixture(); + var application = application(f); + var receiver = + new WorldDraftTerminalReadGrpcService( + new WorldDraftTerminalOutcomeRepository(dsl, fence, mapper), + appliedRepository(), + NAMESPACE); + var request = + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence.Request.create( + NAMESPACE, application.operation().accountBindingBytes()); + assertThat(receiverRead(receiver, request).ownerReadback()).isEmpty(); + var result = appliedComponent().apply(application); + var received = receiverRead(receiver, request).ownerReadback().orElseThrow(); + assertThat(received.outcome()) + .isEqualTo( + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome + .COMMITTED); + assertThat(received.canonicalBytes()).containsExactly(result.ownerReadback().canonicalBytes()); + assertThat(received.result()).containsExactly(result.canonicalBytes()); + freeze(f); + var retryRequest = + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence.Request.create( + NAMESPACE, application.operation().accountBindingBytes()); + assertThat(receiverRead(receiver, retryRequest).ownerReadback().orElseThrow().canonicalBytes()) + .containsExactly(received.canonicalBytes()); + } + + private net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence receiverRead( + WorldDraftTerminalReadGrpcService receiver, + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence.Request request) { + var response = + new java.util.concurrent.atomic.AtomicReference< + net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse>(); + var error = new java.util.concurrent.atomic.AtomicReference(); + var completed = new java.util.concurrent.atomic.AtomicBoolean(); + var context = + io.grpc.Context.current() + .withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", + NAMESPACE, + "account-service")); + var previous = context.attach(); + try { + receiver.readWorldDraftTerminalOutcome( + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec.toRequest( + request), + new io.grpc.stub.StreamObserver<>() { + public void onNext( + net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse + value) { + response.set(value); + } + + public void onError(Throwable value) { + error.set(value); + } + + public void onCompleted() { + completed.set(true); + } + }); + } finally { + context.detach(previous); + } + assertThat(error.get()).isNull(); + assertThat(completed.get()).isTrue(); + return net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec.fromResponse( + request, response.get()); + } + + @Test + void oldPermissionUnverifiedRowsCannotBePromotedByWriterOrLateReceiptInsertion() { + Fixture f = fixture(); + var application = application(f); + var old = component().store(application.plan()); + assertThatThrownBy(() -> appliedComponent().apply(application)) + .hasMessageContaining("cannot be promoted"); + assertThat(appliedRepository().readCommitted(application)).isEmpty(); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + insertReceipt(application, new byte[] {1}); + return null; + })) + .hasMessageContaining("same transaction"); + assertThat(appliedRepository().readCommitted(application)).isEmpty(); + assertThat(repository().readCommitted(application.plan()).orElseThrow().graphBytes()) + .containsExactly(old.graphBytes()); + // Even plausible canonical fixture bytes cannot select old unverified history. + var fabricated = WorldDraftGraphAppliedResult.create(application, old.graphBytes()); + assertThatThrownBy( + () -> + repository() + .readSynchronized( + visibility(application, fabricated, fabricated.canonicalBytes()))) + .hasMessageContaining("no canonical World APPLIED-result carrier"); + } + + @Test + void failureAfterGraphAndReceiptInsertionRollsBackEveryFamilyEpochAndHistory() { + Fixture f = fixture(); + var application = application(f); + var failing = + new WorldDraftGraphApplicationRepository(dsl, fence, mapper) { + @Override + WorldDraftGraphAppliedResult apply( + WorldDraftGraphApplication value, + WorldDraftGraphApplicationService.CommitOrderProof proof) { + super.apply(value, proof); + throw new IllegalStateException("after exact receipt insertion"); + } + }; + assertThatThrownBy(() -> appliedComponent(failing).apply(application)) + .hasMessageContaining("after exact receipt"); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_design_aggregate_epoch", + "world_design_scope_epoch", + "world_authored_topology_identity", + "world_topology_draft_commit", + "world_draft_start_location_receipt")) { + assertThat(count(f, table)).isZero(); + } + assertThat(appliedRepository().readCommitted(application)).isEmpty(); + assertThat(aborts().readDefinitiveAbort(application.operation())).isEmpty(); + assertThat(appliedComponent().apply(application).status()).isEqualTo("APPLIED"); + } + + @Test + void definitiveAbortExcludesDelayedTypedAndRawSqlGraphWrites() { + Fixture f = fixture(); + var application = application(f); + aborts().recordDefinitiveAbort(application.operation()); + assertThatThrownBy(() -> appliedComponent().apply(application)) + .hasMessageContaining("definitive no-commit"); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + dsl.fetch( + "SELECT world_store_guarded_uuid_topology(?::jsonb,?::jsonb,?::jsonb)", + mapper.writeValueAsString(application.plan().ownerBinding()), + application.plan().binding().canonicalJson(), + mapper.writeValueAsString( + repository().executionRevisions(application.plan()))); + return null; + })) + .hasMessageContaining("no-commit evidence"); + assertThat(count(f, "world_authored_topology_identity")).isZero(); + assertThat(count(f, "world_topology_draft_commit")).isZero(); + assertThat(appliedRepository().readCommitted(application)).isEmpty(); + } + + @Test + void committedApplicationCannotBeRelabeledAsAbort() { + Fixture f = fixture(); + var application = application(f); + var result = appliedComponent().apply(application); + assertThatThrownBy(() -> aborts().recordDefinitiveAbort(application.operation())) + .hasMessageContaining("cannot be relabeled"); + assertThat(aborts().readDefinitiveAbort(application.operation())).isEmpty(); + assertThat(appliedRepository().readCommitted(application).orElseThrow().canonicalBytes()) + .containsExactly(result.canonicalBytes()); + } + + @Test + void originalAccountActorSourcesAndFenceArePartOfExactReplayIdentity() { + Fixture f = fixture(); + var application = application(f); + appliedComponent().apply(application); + assertThatThrownBy(() -> appliedComponent().apply(changedAccountApplication(application))) + .hasMessageContaining("changed complete binding"); + var a = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.fromStored( + application.operation().accountBindingBytes()); + var changedFence = + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding( + a.operationId(), + a.requestId(), + a.commitId(), + UUID.randomUUID(), + a.actorAccountId(), + a.tenantId(), + a.versionId(), + a.baseCommitId(), + a.expectedDraftEpoch(), + a.gameDesignBinding(), + a.normalizedInput(), + a.inputDigest(), + a.sources()); + assertThatThrownBy( + () -> appliedComponent().apply(withAccount(application.plan(), changedFence))) + .hasMessageContaining("changed complete binding"); + } + + @Test + void changedStartSelectorChangesAccountInputDigestAndConflictsOnReusedIdentity() { + Fixture f = fixture(); + var original = application(f); + appliedComponent().apply(original); + UUID anotherRoom = + original + .plan() + .graph() + .family(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .get(1) + .templateId(); + var changed = withStartRoom(original, anotherRoom); + + assertThat(changed.operation().binding().digest()) + .isNotEqualTo(original.operation().binding().digest()); + assertThat(changed.operation().accountBindingDigest()) + .isNotEqualTo(original.operation().accountBindingDigest()); + assertThatThrownBy(() -> appliedRepository().readCommitted(changed)) + .hasMessageContaining("changed complete binding"); + assertThatThrownBy(() -> appliedComponent().apply(changed)) + .hasMessageContaining("changed complete binding"); + assertThat(count(f, "world_draft_start_location_receipt")).isEqualTo(1); + } + + @Test + void extraRetainedOptionalFamilyRowDeniesFreshGraphApplication() { + Fixture f = fixture(); + var application = application(plan(f, true)); + var priorPlan = plan(f, true, true); + assertThat(component().store(priorPlan).status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + + assertThatThrownBy(() -> appliedComponent().apply(application)) + .hasMessageContaining("Fresh World topology conflicts with retained region"); + assertThat(appliedRepository().readCommitted(application)).isEmpty(); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(4); + assertThat(count(f, "world_draft_start_location_receipt")).isZero(); + } + + @Test + void v39AppliedV1HistoryRemainsByteExactAndRetryableAfterV41() throws Exception { + String schema = "world_v39_history_" + UUID.randomUUID().toString().replace("-", ""); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_world_management_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("39")) + .load() + .migrate(); + + DriverManagerDataSource retainedDataSource = new DriverManagerDataSource(); + retainedDataSource.setUrl(postgres.getJdbcUrl()); + retainedDataSource.setUsername(postgres.getUsername()); + retainedDataSource.setPassword(postgres.getPassword()); + retainedDataSource.setSchema(schema); + DSLContext retainedDsl = + DSL.using(new TransactionAwareDataSourceProxy(retainedDataSource), SQLDialect.POSTGRES); + PlatformTransactionManager retainedManager = + new DataSourceTransactionManager(retainedDataSource); + WorldAuthoredSourceIntakeRepository retainedIntake = + proxiedIntakeRepository(retainedDsl, retainedManager); + Fixture f = fixture(retainedIntake, retainedManager, retainedDsl); + WorldDraftTopologyCommitPlan historicalPlan = withoutFreshGraphDeclaration(plan(f)); + WorldDraftGraphApplication historicalApplication = application(historicalPlan); + TransactionTemplate retainedTransaction = ownerTransaction(retainedManager); + WorldDesignPublicationFenceRepository retainedFence = + new WorldDesignPublicationFenceRepository(retainedDsl, retainedIntake); + WorldDraftTopologyCommitRepository retainedTopology = + new WorldDraftTopologyCommitRepository(retainedDsl, retainedFence, mapper); + WorldDraftGraphAppliedResult legacyResult = + retainedTransaction.execute( + status -> { + var legacyGraph = retainedTopology.store(historicalPlan); + WorldDraftGraphAppliedResult result = + WorldDraftGraphAppliedResult.create( + historicalApplication, legacyGraph.graphBytes()); + retainedDsl.execute( + "INSERT INTO world_draft_graph_application (operation_id,request_id,commit_id,authorization_fence_id," + + "operation_bytes,account_binding_bytes,account_binding_digest,result_bytes,result_digest) VALUES (?,?,?,?,?,?,?,?,?)", + historicalApplication.operation().operationId(), + historicalApplication.operation().requestId(), + historicalApplication.operation().commitId(), + historicalApplication.operation().authorizationFenceId(), + historicalApplication.operation().canonicalBytes(), + historicalApplication.operation().accountBindingBytes(), + historicalApplication.operation().accountBindingDigest(), + result.canonicalBytes(), + result.digest()); + return result; + }); + assertThat(legacyResult.resultIdentity()).contains("/v1:"); + assertThat(legacyResult.startLocationReceipt()).isEmpty(); + + Map originalBytes = + retainedV39ApplicationBytes(retainedDsl, historicalApplication); + Map originalRows = + retainedV39ApplicationRows(retainedDsl, historicalApplication); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_world_management_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + Map migratedBytes = + retainedV39ApplicationBytes(retainedDsl, historicalApplication); + originalBytes.forEach( + (key, value) -> assertThat(migratedBytes.get(key)).containsExactly(value)); + assertThat(retainedV39ApplicationRows(retainedDsl, historicalApplication)) + .isEqualTo(originalRows); + Long receiptsAfterMigration = + Objects.requireNonNull( + retainedDsl.fetchOne("SELECT count(*) FROM world_draft_start_location_receipt")) + .get(0, Long.class); + assertThat(receiptsAfterMigration).isZero(); + + WorldDraftGraphApplicationRepository retainedApplications = + new WorldDraftGraphApplicationRepository(retainedDsl, retainedFence, mapper); + WorldDraftGraphAppliedResult exact = + retainedApplications.readCommitted(historicalApplication).orElseThrow(); + assertThat(exact.canonicalBytes()).containsExactly(legacyResult.canonicalBytes()); + assertThat(exact.graphBytes()).containsExactly(legacyResult.graphBytes()); + assertThat(exact.startLocationReceipt()).isEmpty(); + // Negative source-reader proof uses real retained v1 APPLIED bytes, with a stipulated frozen + // selection only. This is not positive capture or publication-checkpoint proof for v1 history. + var historicalFreeze = + new WorldAuthoredGraphSnapshot.CaptureRequest( + NAMESPACE, + historicalPlan.ownerBinding().canonicalTenantId(), + historicalPlan.ownerBinding().canonicalVersionId(), + historicalPlan.ownerBinding().intakeRequestId(), + UUID.randomUUID(), + "historical-selector-denial", + "a".repeat(64), + 1, + "publish:" + + historicalPlan.ownerBinding().canonicalTenantId() + + ":publish-request:historical-selector-denial", + historicalPlan.binding().commitId().toString(), + "b".repeat(64), + 3, + historicalPlan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList()); + var historicalSelection = + new WorldCanonicalFrozenTopology( + UUID.randomUUID(), + new WorldCanonicalFrozenTopology.Request(historicalPlan, historicalFreeze), + f.version(), + new WorldCanonicalAuthoredGraphReader().read(historicalPlan, exact.graphBytes()), + exact.graphBytes(), + new byte[0], + new byte[0]); + var stipulatedFrozen = org.mockito.Mockito.mock(WorldCanonicalFrozenTopologyRepository.class); + org.mockito.Mockito.when(stipulatedFrozen.readCommitted(historicalFreeze)) + .thenReturn(java.util.Optional.of(historicalSelection)); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationRepository( + retainedDsl, stipulatedFrozen, retainedApplications) + .readCommitted(historicalFreeze)) + .hasMessageContaining("lacks original selector receipt"); + assertThat( + retainedApplications + .readCommitted(NAMESPACE, historicalApplication.operation().accountBindingBytes()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(legacyResult.canonicalBytes()); + WorldDraftGraphAppliedResult retry = + new WorldDraftGraphApplicationService(retainedApplications, retainedManager) + .apply(historicalApplication); + assertThat(retry.canonicalBytes()).containsExactly(legacyResult.canonicalBytes()); + assertThat(retry.startLocationReceipt()).isEmpty(); + Long receiptsAfterRetry = + Objects.requireNonNull( + retainedDsl.fetchOne("SELECT count(*) FROM world_draft_start_location_receipt")) + .get(0, Long.class); + assertThat(receiptsAfterRetry).isZero(); + } + + @Test + void exactDuplicateRaceCommitsOneGraphAndOneImmutableResult() throws Exception { + Fixture f = fixture(); + var application = application(f); + ExecutorService pool = Executors.newFixedThreadPool(2); + CountDownLatch begin = new CountDownLatch(1); + try { + Future first = + pool.submit( + () -> { + await(begin); + return appliedComponent().apply(application); + }); + Future second = + pool.submit( + () -> { + await(begin); + return appliedComponent().apply(application); + }); + begin.countDown(); + assertThat(first.get(20, TimeUnit.SECONDS).canonicalBytes()) + .containsExactly(second.get(20, TimeUnit.SECONDS).canonicalBytes()); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + assertThat( + Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_draft_graph_application WHERE operation_id=?", + application.operation().operationId())) + .get(0, Long.class))) + .isEqualTo(1); + } finally { + pool.shutdownNow(); + } + } + + @Test + void commitAbortRaceHasExactlyOneDefinitiveOutcomeAndNoLateWrite() throws Exception { + Fixture f = fixture(); + var application = application(f); + ExecutorService pool = Executors.newFixedThreadPool(2); + CountDownLatch begin = new CountDownLatch(1); + try { + Future commit = + pool.submit( + () -> { + await(begin); + try { + appliedComponent().apply(application); + return true; + } catch (WorldDesignPublicationFenceRepository.ConflictException conflict) { + return false; + } + }); + Future abort = + pool.submit( + () -> { + await(begin); + try { + aborts().recordDefinitiveAbort(application.operation()); + return true; + } catch (WorldDesignPublicationFenceRepository.ConflictException conflict) { + return false; + } + }); + begin.countDown(); + boolean committed = commit.get(20, TimeUnit.SECONDS); + boolean aborted = abort.get(20, TimeUnit.SECONDS); + assertThat(committed ^ aborted).isTrue(); + assertThat(appliedRepository().readCommitted(application).isPresent()).isEqualTo(committed); + assertThat(aborts().readDefinitiveAbort(application.operation()).isPresent()) + .isEqualTo(aborted); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(committed ? 7 : 0); + if (aborted) + assertThatThrownBy(() -> appliedComponent().apply(application)) + .hasMessageContaining("no-commit evidence"); + else + assertThatThrownBy(() -> aborts().recordDefinitiveAbort(application.operation())) + .hasMessageContaining("cannot be relabeled"); + } finally { + pool.shutdownNow(); + } + } + + @Test + void synchronizedGraphRequiresExactCanonicalAppliedResultNotArbitraryBytes() { + Fixture f = fixture(); + var application = application(f); + var result = appliedComponent().apply(application); + assertThat( + repository().readSynchronized(visibility(application, result, result.canonicalBytes()))) + .isPresent(); + assertThatThrownBy( + () -> + repository() + .readSynchronized(visibility(application, result, new byte[] {1, 2, 3}))) + .hasMessageContaining("exact canonical retained graph application"); + Fixture other = fixture(); + var otherApplication = application(other); + var otherResult = appliedComponent().apply(otherApplication); + assertThatThrownBy( + () -> + repository() + .readSynchronized( + visibility(application, result, otherResult.canonicalBytes()))) + .hasMessageContaining("exact canonical retained graph application"); + } + + @Test + void changedTargetRaceCannotClaimTheSameOriginalOperationAndFenceForBothOutcomes() + throws Exception { + var application = application(fixture()); + var other = application(fixture()); + var original = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.fromStored( + application.operation().accountBindingBytes()); + var changed = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.fromStored( + other.operation().accountBindingBytes()); + var conflicting = + withAccount( + other.plan(), + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding( + original.operationId(), + changed.requestId(), + changed.commitId(), + original.fenceId(), + changed.actorAccountId(), + changed.tenantId(), + changed.versionId(), + changed.baseCommitId(), + changed.expectedDraftEpoch(), + changed.gameDesignBinding(), + changed.normalizedInput(), + changed.inputDigest(), + changed.sources())); + ExecutorService pool = Executors.newFixedThreadPool(2); + CountDownLatch begin = new CountDownLatch(1); + try { + Future commit = + pool.submit( + () -> { + await(begin); + try { + appliedComponent().apply(application); + return true; + } catch (WorldDesignPublicationFenceRepository.ConflictException + | org.springframework.dao.DataIntegrityViolationException conflict) { + return false; + } + }); + Future abort = + pool.submit( + () -> { + await(begin); + try { + aborts().recordDefinitiveAbort(conflicting.operation()); + return true; + } catch (WorldDesignPublicationFenceRepository.ConflictException + | org.springframework.dao.DataIntegrityViolationException conflict) { + return false; + } + }); + begin.countDown(); + boolean committed = commit.get(20, TimeUnit.SECONDS); + boolean aborted = abort.get(20, TimeUnit.SECONDS); + assertThat(committed ^ aborted).isTrue(); + assertThat( + Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_draft_graph_terminal_identity WHERE operation_id=?", + original.operationId())) + .get(0, Long.class))) + .isEqualTo(1); + assertThat( + Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_draft_graph_application WHERE operation_id=?", + original.operationId())) + .get(0, Long.class))) + .isEqualTo(committed ? 1 : 0); + assertThat( + Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_draft_terminal_outcome WHERE operation_id=?", + original.operationId())) + .get(0, Long.class))) + .isEqualTo(aborted ? 1 : 0); + } finally { + pool.shutdownNow(); + } + } + + @Test + void completeResultAndGraphSubstitutionFailImmutableReadback() { + Fixture f = fixture(); + var application = application(f); + var result = appliedComponent().apply(application); + byte[] corrupt = result.canonicalBytes(); + corrupt[corrupt.length - 2] ^= 1; + ownerTransaction() + .execute( + status -> { + dsl.execute( + "ALTER TABLE world_draft_graph_application DISABLE TRIGGER trg_world_graph_application_guard"); + dsl.execute( + "UPDATE world_draft_graph_application SET result_bytes=?,result_digest=? WHERE operation_id=?", + corrupt, + WorldDraftGraphAppliedResult.digest(corrupt), + application.operation().operationId()); + dsl.execute( + "ALTER TABLE world_draft_graph_application ENABLE TRIGGER trg_world_graph_application_guard"); + return null; + }); + assertThatThrownBy(() -> appliedRepository().readCommitted(application)) + .hasMessageContaining("immutable integrity readback"); + assertThatThrownBy( + () -> + repository() + .readSynchronized(visibility(application, result, result.canonicalBytes()))) + .hasMessageContaining("immutable integrity readback"); + + Fixture other = fixture(); + var otherApplication = application(other); + var otherResult = appliedComponent().apply(otherApplication); + ownerTransaction() + .execute( + status -> { + dsl.execute( + "ALTER TABLE world_topology_draft_commit DISABLE TRIGGER trg_world_topology_history_immutable"); + dsl.execute( + "UPDATE world_topology_draft_commit SET graph_bytes=?,graph_sha256=? WHERE request_id=?", + result.graphBytes(), + WorldDraftGraphAppliedResult.digest(result.graphBytes()).substring(7), + otherApplication.operation().requestId()); + dsl.execute( + "ALTER TABLE world_topology_draft_commit ENABLE TRIGGER trg_world_topology_history_immutable"); + return null; + }); + assertThatThrownBy(() -> appliedRepository().readCommitted(otherApplication)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + repository() + .readSynchronized( + visibility(otherApplication, otherResult, otherResult.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + } + + private WorldDraftGraphApplication application(Fixture f) { + return application(plan(f)); + } + + private WorldDraftGraphApplication application(WorldDraftTopologyCommitPlan p) { + var account = + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding( + UUID.randomUUID(), + p.binding().requestId(), + p.binding().commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + p.binding().target().canonicalTenantId(), + p.binding().target().canonicalVersionId(), + p.binding().baseCommitId(), + "0", + p.binding().canonicalBytes(), + p.binding().canonicalBytes(), + p.binding().digest(), + List.of( + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding + .SourceEvidence( + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding + .SourceKind.TENANT, + p.binding().target().canonicalTenantId().toString(), + null, + "1", + null, + null, + new byte[] {1, 2, 3}))); + return withAccount(p, account); + } + + private WorldDraftGraphApplication changedAccountApplication( + WorldDraftGraphApplication application) { + var a = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.fromStored( + application.operation().accountBindingBytes()); + var changed = + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding( + a.operationId(), + a.requestId(), + a.commitId(), + a.fenceId(), + UUID.randomUUID(), + a.tenantId(), + a.versionId(), + a.baseCommitId(), + a.expectedDraftEpoch(), + a.gameDesignBinding(), + a.normalizedInput(), + a.inputDigest(), + List.of( + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding + .SourceEvidence( + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding + .SourceKind.TENANT, + a.tenantId().toString(), + null, + "2", + null, + null, + new byte[] {4, 5, 6}))); + return withAccount(application.plan(), changed); + } + + private WorldDraftGraphApplication withAccount( + WorldDraftTopologyCommitPlan p, + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding account) { + var operation = + new WorldDraftTerminalOperation( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId(), + p.binding(), + p.ownerBinding(), + account.canonicalBytes()); + return new WorldDraftGraphApplication(operation, p); + } + + private WorldDraftGraphApplication withStartRoom( + WorldDraftGraphApplication original, UUID roomTemplateId) { + var binding = original.operation().binding(); + List revisions = new ArrayList<>(binding.revisions()); + for (int index = 0; index < revisions.size(); index++) { + var revision = revisions.get(index); + if (revision.owner() != Owner.WORLD_MANAGEMENT) continue; + try { + var mutation = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(revision.payload(), mutation); + if (!mutation.hasFreshGraphDeclaration()) continue; + var declaration = + mutation.getFreshGraphDeclaration().toBuilder() + .setStartLocation( + mutation.getFreshGraphDeclaration().getStartLocation().toBuilder() + .setRoomTemplateId(roomTemplateId.toString())) + .build(); + revisions.set( + index, + new DraftCommitBinding.RevisionPayload( + revision.revisionOrder(), + revision.revisionId(), + revision.owner(), + JsonFormat.printer() + .print(mutation.setFreshGraphDeclaration(declaration).build()))); + DraftCommitBinding changedBinding = + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + revisions, + binding.affectedUnits()); + var account = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.fromStored( + original.operation().accountBindingBytes()); + var changedAccount = + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.actorAccountId(), + account.tenantId(), + account.versionId(), + account.baseCommitId(), + account.expectedDraftEpoch(), + changedBinding.canonicalBytes(), + changedBinding.canonicalBytes(), + changedBinding.digest(), + account.sources()); + return withAccount( + WorldDraftTopologyCommitPlan.create(changedBinding, original.plan().ownerBinding()), + changedAccount); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException(exception); + } + } + throw new IllegalArgumentException("Original application has no start-location declaration"); + } + + private WorldDraftGraphApplicationRepository appliedRepository() { + return new WorldDraftGraphApplicationRepository(dsl, fence, mapper); + } + + private WorldAuthoredSourceIntakeRepository proxiedIntakeRepository( + DSLContext context, PlatformTransactionManager transactionManager) { + var repository = new WorldAuthoredSourceIntakeRepository(context); + TransactionInterceptor transactions = new TransactionInterceptor(); + transactions.setTransactionManager(transactionManager); + transactions.setTransactionAttributeSource(new AnnotationTransactionAttributeSource()); + ProxyFactory proxy = new ProxyFactory(repository); + proxy.setProxyTargetClass(true); + proxy.addAdvice(transactions); + return (WorldAuthoredSourceIntakeRepository) proxy.getProxy(); + } + + private WorldDraftGraphApplicationService appliedComponent() { + return appliedComponent(appliedRepository()); + } + + private WorldDraftGraphApplicationService appliedComponent( + WorldDraftGraphApplicationRepository repository) { + return new WorldDraftGraphApplicationService( + repository, + manager, + operation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + // STIPULATED fixture authority: original Account COMMIT_ORDER remains held until BOTH + // owners settle. + // No protected producer is supplied and this is not Gameplay handoff completion. + return new WorldDraftGraphApplicationService.CommitOrderProof(operation); + }); + } + + private WorldDraftTerminalOutcomeService aborts() { + return new WorldDraftTerminalOutcomeService( + new WorldDraftTerminalOutcomeRepository(dsl, fence, mapper), manager); + } + + private void insertReceipt(WorldDraftGraphApplication application, byte[] result) { + var operation = application.operation(); + dsl.execute( + "INSERT INTO world_draft_graph_application (operation_id,request_id,commit_id,authorization_fence_id," + + "operation_bytes,account_binding_bytes,account_binding_digest,result_bytes,result_digest) VALUES (?,?,?,?,?,?,?,?,?)", + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId(), + operation.canonicalBytes(), + operation.accountBindingBytes(), + operation.accountBindingDigest(), + result, + WorldDraftGraphAppliedResult.digest(result)); + } + + private WorldDraftTopologyCommitPlan withoutFreshGraphDeclaration( + WorldDraftTopologyCommitPlan original) { + List revisions = new ArrayList<>(); + for (var revision : original.binding().revisions()) { + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + revisions.add(revision); + continue; + } + try { + var mutation = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(revision.payload(), mutation); + revisions.add( + new DraftCommitBinding.RevisionPayload( + revision.revisionOrder(), + revision.revisionId(), + revision.owner(), + JsonFormat.printer() + .omittingInsignificantWhitespace() + .print(mutation.clearFreshGraphDeclaration().build()))); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException(exception); + } + } + var binding = original.binding(); + DraftCommitBinding historicalBinding = + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + revisions, + binding.affectedUnits()); + return WorldDraftTopologyCommitPlan.create(historicalBinding, original.ownerBinding()); + } + + private Map retainedV39ApplicationBytes( + DSLContext retained, WorldDraftGraphApplication application) { + var operation = application.operation(); + var graph = + Objects.requireNonNull( + retained.fetchOne( + "SELECT graph_bytes,result_bytes FROM world_topology_draft_commit WHERE request_id=? AND commit_id=?", + operation.requestId(), + operation.commitId()), + "expected retained V39 graph row"); + var applied = + Objects.requireNonNull( + retained.fetchOne( + "SELECT operation_bytes,account_binding_bytes,result_bytes FROM world_draft_graph_application WHERE operation_id=?", + operation.operationId()), + "expected retained V39 APPLIED row"); + var terminal = + Objects.requireNonNull( + retained.fetchOne( + "SELECT account_binding_bytes FROM world_draft_graph_terminal_identity WHERE operation_id=?", + operation.operationId()), + "expected retained V39 terminal identity"); + return Map.of( + "graphBytes", graph.get("graph_bytes", byte[].class), + "graphResultBytes", graph.get("result_bytes", byte[].class), + "operationBytes", applied.get("operation_bytes", byte[].class), + "accountBindingBytes", applied.get("account_binding_bytes", byte[].class), + "appliedResultBytes", applied.get("result_bytes", byte[].class), + "terminalAccountBindingBytes", terminal.get("account_binding_bytes", byte[].class)); + } + + private Map retainedV39ApplicationRows( + DSLContext retained, WorldDraftGraphApplication application) { + var operation = application.operation(); + var graph = + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_topology_draft_commit t WHERE request_id=? AND commit_id=?", + operation.requestId(), + operation.commitId()), + "expected retained V39 graph row"); + var applied = + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_draft_graph_application t WHERE operation_id=?", + operation.operationId()), + "expected retained V39 APPLIED row"); + var terminal = + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(t)::text FROM world_draft_graph_terminal_identity t WHERE operation_id=?", + operation.operationId()), + "expected retained V39 terminal identity"); + return Map.of( + "graph", graph.get(0, String.class), + "application", applied.get(0, String.class), + "terminal", terminal.get(0, String.class)); + } + + private net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence visibility( + WorldDraftGraphApplication application, + WorldDraftGraphAppliedResult result, + byte[] worldResultBytes) { + var binding = application.operation().binding(); + List> vector = new ArrayList<>(); + for (Owner owner : binding.requiredOwners()) { + Map value = new LinkedHashMap<>(); + value.put("owner", owner.name()); + value.put("status", "APPLIED"); + value.put("commitId", binding.commitId().toString()); + value.put("bindingDigest", binding.digest()); + value.put( + "resultIdentity", + owner == Owner.WORLD_MANAGEMENT ? result.resultIdentity() : "stipulated-" + owner); + value.put( + "resultBytesBase64", + java.util.Base64.getEncoder() + .encodeToString(owner == Owner.WORLD_MANAGEMENT ? worldResultBytes : new byte[] {1})); + value.put( + "appliedEpochs", + binding.affectedUnits(owner).stream() + .map( + unit -> { + Map epoch = new LinkedHashMap<>(); + epoch.put("aggregateType", unit.aggregateType()); + epoch.put("aggregateId", unit.aggregateId()); + epoch.put("scopeType", unit.scopeType()); + epoch.put("scopeId", unit.scopeId()); + epoch.put("expectedEpoch", unit.expectedEpoch()); + epoch.put("resultingEpoch", "1"); + return epoch; + }) + .toList()); + vector.add(value); + } + try { + String json = + new String( + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(vector)), + StandardCharsets.UTF_8); + return new net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence( + new net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.Request( + 1, NAMESPACE, UUID.randomUUID(), binding.target()), + binding, + "SYNCHRONIZED", + new net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.Fence( + binding.requestId(), + binding.commitId(), + binding.digest(), + json, + java.time.OffsetDateTime.now(java.time.ZoneOffset.UTC))); + } catch (java.io.IOException exception) { + throw new AssertionError(exception); + } + } + + private Fixture fixture() { + return fixture(intakeRepository, manager, dsl); + } + + private Fixture fixture( + WorldAuthoredSourceIntakeRepository sourceIntake, + PlatformTransactionManager transactionManager, + DSLContext context) { + UUID tenant = UUID.randomUUID(); + UUID registration = UUID.randomUUID(); + UUID sourceOperation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + long sourceRow = Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + String sourceTenant = "gd-row-" + sourceRow; + String digest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, "Synthetic component world"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW", + evidenceDigest); + UUID intakeRequest = UUID.randomUUID(); + ownerTransaction(transactionManager) + .execute(status -> sourceIntake.acceptFresh(NAMESPACE, intakeRequest, source)); + WorldAuthoredSourceIntakeReceipt intake = + sourceIntake.read(NAMESPACE, intakeRequest).orElseThrow(); + return Objects.requireNonNull( + ownerTransaction(transactionManager) + .execute( + status -> { + UUID canonicalVersion = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + worldSlug, + sourceOperation, + evidenceDigest, + GAME_DESIGN_VERSION); + WorldAuthoredVersionIdentityReceipt version = + new WorldAuthoredVersionIdentityRepository(context) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + tenant, + canonicalVersion, + version.operationId(), + GAME_DESIGN_VERSION, + intakeRequest, + intake.operationId(), + intake.requestDigest(), + sourceOperation, + evidenceDigest, + intake.receiptDigest()); + assertOrigin(context); + return new Fixture(intake, version, owner); + })); + } + + private void freeze(Fixture f) { + OwnerBinding o = f.owner(); + String request = "freeze-" + UUID.randomUUID(); + WorldDesignPublicationFenceEvidence evidence = + new WorldDesignPublicationFenceEvidence( + o.targetNamespace(), + o.canonicalTenantId(), + o.canonicalVersionId(), + o.versionIdentityOperationId(), + o.gameDesignVersionId(), + o.intakeRequestId(), + o.intakeOperationId(), + o.intakeRequestDigest(), + o.sourceOperationId(), + o.sourceEvidenceDigest(), + o.intakeReceiptDigest(), + request, + "a".repeat(64), + 1, + "publish:" + o.canonicalTenantId() + ":publish-request:" + request); + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "synthetic-unverified-checkpoint", "b".repeat(64), 2))); + } + + private WorldDraftTopologyCommitPlan plan(Fixture f) { + return plan(f, false); + } + + private WorldDraftTopologyCommitPlan plan(Fixture f, boolean threeFamilyGraph) { + return plan(f, threeFamilyGraph, false); + } + + private WorldDraftTopologyCommitPlan plan( + Fixture f, boolean threeFamilyGraph, boolean includeGenerationRule) { + UUID logical = UUID.randomUUID(); + UUID secondRoom = UUID.randomUUID(); + UUID entity = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + List values = new ArrayList<>(); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("region") + .setWeather("rain") + .setShardId(7) + .setGenerationSeed(9_007_199_254_740_999L) + .setGeneratorType("synthetic") + .setGeneratorParams("{\"seed\":1}")) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder().setName("zone").setRegionId(logical.toString())) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("room") + .setZoneId(logical.toString()) + .setDescription("description") + .setNameLocalizedVariantsJson("{\"en\":\"room\"}") + .setDescriptionLocalizedVariantsJson("{\"en\":\"description\"}")) + .build()); + values.add( + mutation( + commit, + secondRoom, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder().setName("second").setZoneId(logical.toString())) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(logical.toString()) + .setToRoomId(secondRoom.toString()) + .setDirection("NORTH")) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder().setName("rule").setValue("seeded")) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(logical.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(entity.toString()) + .setRespawnDelaySeconds(17)) + .build()); + if (threeFamilyGraph) { + values = new ArrayList<>(values.subList(0, 3)); + var region = values.getFirst(); + values.set( + 0, + region.toBuilder() + .setRegion( + region.getRegion().toBuilder() + .clearGenerationSeed() + .clearGeneratorType() + .clearGeneratorParams()) + .build()); + } + if (includeGenerationRule) { + values.add( + mutation( + commit, + UUID.randomUUID(), + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder() + .setName("retained-extra") + .setValue("must-deny")) + .build()); + } + var declaration = + WorldFreshGraphDeclaration.newBuilder() + .setTenantId(f.owner().canonicalTenantId().toString()) + .setVersionId(f.owner().canonicalVersionId().toString()) + .setStartLocation( + net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef.newBuilder() + .setTenantId(f.owner().canonicalTenantId().toString()) + .setVersionId(f.owner().canonicalVersionId().toString()) + .setRoomTemplateId(logical.toString())) + .addFamilyCounts( + count(values, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION)) + .addFamilyCounts( + count(values, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE)) + .addFamilyCounts( + count(values, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM)) + .addFamilyCounts( + count(values, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT)) + .addFamilyCounts( + count(values, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE)) + .addFamilyCounts( + count( + values, + WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) + .build(); + values.set(0, values.getFirst().toBuilder().setFreshGraphDeclaration(declaration).build()); + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + "synthetic opaque Entity input; existence and permission remain unverified")); + units.add( + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "NPC", + entity.toString(), + "AGGREGATE", + entity.toString(), + "0")); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "1", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + "synthetic Game Design control-plane input")); + units.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "VERSION", + f.owner().canonicalVersionId().toString(), + "AGGREGATE", + f.owner().canonicalVersionId().toString(), + "0")); + // Original input order deliberately places children before their parents. + for (var m : values.reversed()) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(m.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + json(m))); + String family = m.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "AGGREGATE", + m.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "REGION_SUBTREE", + m.getScopeId(), + "0")); + } + var s = f.intake().source(); + var target = + new DraftCommitBinding.TargetProof( + f.owner().canonicalTenantId(), + f.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + s.sourceGameTenantKey(), + s.sourceGameRowId(), + s.sourceGameTenantKey(), + s.provenanceKind()); + return WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + target, UUID.randomUUID(), commit, "retained-base", revisions, units), + f.owner()); + } + + private WorldFreshGraphFamilyCount count( + List mutations, WorldDesignAggregateType family) { + int count = + (int) mutations.stream().filter(mutation -> mutation.getAggregateType() == family).count(); + return WorldFreshGraphFamilyCount.newBuilder().setFamily(family).setCount(count).build(); + } + + private WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID id, UUID scope, WorldDesignAggregateType type) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(id.toString()) + .setAggregateType(type) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(scope.toString()); + } + + private WorldDraftTopologyCommitService component() { + return new WorldDraftTopologyCommitService( + repository(), + manager, + p -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertOrigin(); + // Synthetic local-storage fixture only; no Account permission or Entity existence proof. + }); + } + + private WorldDraftTopologyCommitRepository repository() { + return new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + } + + private TransactionTemplate ownerTransaction() { + return ownerTransaction(manager); + } + + private TransactionTemplate ownerTransaction(PlatformTransactionManager transactionManager) { + TransactionTemplate tx = new TransactionTemplate(transactionManager); + tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return tx; + } + + private void assertOrigin() { + assertOrigin(dsl); + } + + private void assertOrigin(DSLContext context) { + assertThat( + context + .resultQuery("SELECT current_setting('session_replication_role')") + .fetchOne(0, String.class)) + .isEqualTo("origin"); + } + + private long count(Fixture f, String table) { + if (table.equals("world_draft_graph_application")) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT count(*) FROM world_draft_graph_application a " + + "JOIN world_topology_draft_commit c ON c.request_id=a.request_id AND c.commit_id=a.commit_id " + + "WHERE c.local_tenant_key=?", + f.intake().localTenantKey()) + .fetchOne(0, Long.class)); + } + String tenant = + switch (table) { + case "world_topology_draft_commit" -> "local_tenant_key"; + case "world_draft_start_location_receipt" -> "canonical_tenant_id"; + default -> "tenant_id"; + }; + Object tenantId = + table.equals("world_draft_start_location_receipt") + ? f.owner().canonicalTenantId() + : f.intake().localTenantKey(); + return Objects.requireNonNull( + dsl.resultQuery("SELECT count(*) FROM " + table + " WHERE " + tenant + "=?", tenantId) + .fetchOne(0, Long.class)); + } + + private long privateKey(WorldDraftTopologyCommitPlan p, String family, UUID id) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT private_row_key FROM world_authored_topology_identity " + + "WHERE request_id=? AND family=? AND template_id=?", + p.binding().requestId(), + family, + id) + .fetchOne(0, Long.class)); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new AssertionError(exception); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(15, TimeUnit.SECONDS)) throw new IllegalStateException("Fixture timed out"); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(exception); + } + } + + private static final class PreparationCollector + implements StreamObserver { + private PrepareCanonicalWorldInstanceResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(PrepareCanonicalWorldInstanceResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static final class LifecycleReadCollector + implements StreamObserver< + net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse> { + private net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse + value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext( + net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse + response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private record PreparationAssemblyFixture( + WorldCanonicalInstancePreparationAssemblyService service, + AuthoredWorldLaunchDescriptorClient gameDesignClient, + CanonicalGameInstanceLaunchAssociationClient gameSessionClient, + UUID playableStateNamespaceId) {} + + private record PreparationLaunchFixture( + CompleteLaunchBindingEvidence evidence, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request ownerRequest, + WorldCanonicalInstanceTopologyPlan topologyPlan) {} + + private record PlacementFixture( + PreparedLifecycleFixture lifecycle, + WorldCanonicalInstanceLifecycleEvidence activeEvidence, + HoldIdentity hold, + GameSessionCanonicalInitialAdmissionOwnerProof ownerProof, + WorldCanonicalInitialPlayerLocationRepository repository, + WorldCanonicalInitialPlayerLocationService service, + WorldCanonicalInitialPlayerLocation.Request request) {} + + private record Fixture( + WorldAuthoredSourceIntakeReceipt intake, + WorldAuthoredVersionIdentityReceipt version, + OwnerBinding owner) {} + + private record HistoricalSchemaFixture( + String schema, WorldDraftGraphApplicationPostgresIntegrationTest database) {} + + private record ActivationProof( + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceActivation.Result result) {} + + private static final class CanonicalActivationTransportClient implements AutoCloseable { + private final ManagedChannel channel; + private final WorldCanonicalInstanceActivationServiceGrpc + .WorldCanonicalInstanceActivationServiceBlockingStub + stub; + + private CanonicalActivationTransportClient( + ManagedChannel channel, + WorldCanonicalInstanceActivationServiceGrpc + .WorldCanonicalInstanceActivationServiceBlockingStub + stub) { + this.channel = channel; + this.stub = stub; + } + + private ActivateCanonicalWorldInstanceResponse activate( + ActivateCanonicalWorldInstanceRequest request) { + return stub.withDeadlineAfter(5, TimeUnit.SECONDS).activateCanonicalWorldInstance(request); + } + + @Override + public void close() throws InterruptedException { + channel.shutdownNow(); + if (!channel.awaitTermination(5, TimeUnit.SECONDS)) { + throw new AssertionError("Canonical activation test client did not terminate"); + } + } + } + + private record PreparedLifecycleFixture( + WorldCanonicalInstancePreparation.Input input, + WorldCanonicalInstancePreparation.Result materialized, + WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository, + WorldCanonicalInstanceLifecycleEvidence.Request readRequest, + WorldCanonicalInstanceLifecycleEvidence preparing) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java new file mode 100644 index 0000000000..cb93a4a59b --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java @@ -0,0 +1,1094 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.DriverManager; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import 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.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; +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.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +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; +import tools.jackson.databind.ObjectMapper; + +/** + * Synthetic source/permission fixtures prove component storage only, never authenticated APPLIED. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldDraftRegionCommitPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final long GAME_DESIGN_VERSION = 9_000_000_000_000_001L; + + @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 DSLContext dsl; + @Autowired private PlatformTransactionManager manager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository fence; + @Autowired private ObjectMapper mapper; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void twoRegionsAdvanceFourTuplesWithFullHistoryAndExactLostAckReplay() { + Fixture f = fixture(); + WorldDraftRegionCommitPlan firstPlan = plan(f, List.of(f.first(), f.second()), 0, "first"); + WorldDraftRegionCommitEvidence first = component().store(firstPlan); + assertThat(name(f.first())).isEqualTo("first-" + f.first()); + assertThat(name(f.second())).isEqualTo("first-" + f.second()); + assertEpochs(f, 1, 1); + assertThat(first.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + String graph = new String(first.graphBytes(), StandardCharsets.UTF_8); + assertThat(graph) + .contains( + "\"regions\"", + "\"zones\"", + "\"rooms\"", + "\"roomExits\"", + "\"generationRules\"", + "\"worldEntitySpawnBindings\""); + assertThat(new String(first.resultBytes(), StandardCharsets.UTF_8)) + .contains(firstPlan.binding().digest(), "\"affectedEpochsAfter\"", "\"epoch\":\"1\"") + .doesNotContain("\"APPLIED\"", "permissionFenceReleased"); + WorldDraftRegionCommitEvidence lostAck = component().store(firstPlan); + assertThat(lostAck.graphBytes()).containsExactly(first.graphBytes()); + assertThat(lostAck.resultBytes()).containsExactly(first.resultBytes()); + component().store(plan(f, List.of(f.first(), f.second()), 1, "later")); + freeze(f); + // Historical retry precedes OPEN admission and preserves the original visibility snapshot. + WorldDraftRegionCommitEvidence historical = component().store(firstPlan); + assertThat(historical.graphBytes()).containsExactly(first.graphBytes()); + assertThat(historical.resultBytes()).containsExactly(first.resultBytes()); + assertThat(name(f.first())).startsWith("later-"); + assertEpochs(f, 2, 2); + assertThat(count("world_region_draft_execution_manifest")).isZero(); + } + + @Test + void committedReadbackReturnsOriginalFrozenHistoryWithoutPermissionOrMutation() { + Fixture f = fixture(); + WorldDraftRegionCommitPlan original = plan(f, List.of(f.first(), f.second()), 0, "original"); + // The default verifier denies storage, but independent readback needs no fresh permission. + WorldDraftRegionCommitService readback = + new WorldDraftRegionCommitService(repository(), manager); + Map> absentState = regionOperationState(); + assertThat(readback.readCommitted(original)).isEmpty(); + assertThat(regionOperationState()).isEqualTo(absentState); + assertThatThrownBy(() -> ownerTransaction().execute(status -> readback.readCommitted(original))) + .hasMessageContaining("no active caller transaction"); + assertThat(regionOperationState()).isEqualTo(absentState); + WorldDraftRegionCommitEvidence first = component().store(original); + component().store(plan(f, List.of(f.first(), f.second()), 1, "later")); + freeze(f); + Map> beforeRead = regionOperationState(); + WorldDraftRegionCommitEvidence retained = readback.readCommitted(original).orElseThrow(); + assertThat(retained.binding()).isEqualTo(original.binding()); + assertThat(retained.ownerBinding()).isEqualTo(original.ownerBinding()); + assertThat(retained.graphBytes()).containsExactly(first.graphBytes()); + assertThat(retained.resultBytes()).containsExactly(first.resultBytes()); + assertThat(retained.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + assertThat(name(f.first())).startsWith("later-"); + assertEpochs(f, 2, 2); + assertThat(regionOperationState()).isEqualTo(beforeRead); + } + + @Test + void lastScopeConflictRollsBackEarlierRegionPayloadEpochsAndEntireHistory() { + Fixture f = fixture(); + seedScope(f, f.second(), 3); + long countBefore = count("world_region_draft_commit"); + WorldDraftRegionCommitPlan plan = plan(f, List.of(f.first(), f.second()), 0, "conflicting"); + assertThatThrownBy(() -> component().store(plan)) + .hasStackTraceContaining("DRAFT_WRITE_CONFLICT: REGION_SUBTREE"); + assertThat(name(f.first())).isEqualTo("original-first"); + assertThat(name(f.second())).isEqualTo("original-second"); + assertThat(epochCount(f, "world_design_aggregate_epoch")).isZero(); + assertThat(epochCount(f, "world_design_scope_epoch")).isEqualTo(1); + assertThat(count("world_region_draft_commit")).isEqualTo(countBefore); + assertThat(count("world_region_draft_execution_manifest")).isZero(); + } + + @Test + void disjointTupleCommitsSucceedFromTheSameRetainedBaseWithoutRebasing() { + Fixture f = fixture(); + WorldDraftRegionCommitEvidence first = + component().store(plan(f, List.of(f.first()), 0, "first")); + WorldDraftRegionCommitEvidence second = + component().store(plan(f, List.of(f.second()), 0, "second")); + assertThat(first.binding().baseCommitId()).isEqualTo(second.binding().baseCommitId()); + assertEpochs(f, 1, 1); + assertThat(new String(first.graphBytes(), StandardCharsets.UTF_8)).contains("original-second"); + assertThat(new String(second.graphBytes(), StandardCharsets.UTF_8)) + .contains("first-", "second-"); + } + + @Test + void immutableFullInputRejectsChangedBaseOtherOwnerPayloadOrderAndTuples() { + Fixture f = fixture(); + WorldDraftRegionCommitPlan original = plan(f, List.of(f.first(), f.second()), 0, "original"); + component().store(original); + DraftCommitBinding binding = original.binding(); + assertChanged( + original, + binding.baseCommitId() + "-changed", + binding.revisions(), + binding.affectedUnits()); + List changed = new ArrayList<>(binding.revisions()); + DraftCommitBinding.RevisionPayload other = changed.get(changed.size() - 1); + changed.set( + changed.size() - 1, + new DraftCommitBinding.RevisionPayload( + other.revisionOrder(), other.revisionId(), other.owner(), other.payload() + "changed")); + assertChanged(original, binding.baseCommitId(), changed, binding.affectedUnits()); + List reordered = + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + changed.get(1).revisionId(), + Owner.WORLD_MANAGEMENT, + binding.revisions().get(1).payload()), + new DraftCommitBinding.RevisionPayload( + "1", + changed.get(0).revisionId(), + Owner.WORLD_MANAGEMENT, + binding.revisions().get(0).payload()), + other); + assertChanged(original, binding.baseCommitId(), reordered, binding.affectedUnits()); + assertThatThrownBy( + () -> + WorldDraftRegionCommitPlan.create( + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + binding.revisions(), + binding.affectedUnits().subList(1, binding.affectedUnits().size())), + original.ownerBinding())) + .isInstanceOf(IllegalArgumentException.class); + // Omitting a complete other-owner subset preserves World semantics but must conflict on replay. + assertChanged( + original, + binding.baseCommitId(), + binding.revisions().subList(0, 2), + binding.affectedUnits(Owner.WORLD_MANAGEMENT)); + assertEpochs(f, 1, 1); + } + + @Test + void firstClaimAndExistingEpochContendersHaveOnlyOneWinner() throws Exception { + Fixture f = fixture(); + race(f, 0); + assertEpochs(f, 1, 1); + race(f, 1); + assertEpochs(f, 2, 2); + } + + @Test + void concurrentExactFirstClaimReturnsOneOriginalResult() throws Exception { + Fixture f = fixture(); + WorldDraftRegionCommitPlan plan = plan(f, List.of(f.first(), f.second()), 0, "same"); + CountDownLatch begin = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + await(begin); + return component().store(plan); + }); + Future second = + executor.submit( + () -> { + await(begin); + return component().store(plan); + }); + begin.countDown(); + WorldDraftRegionCommitEvidence one = first.get(20, TimeUnit.SECONDS); + WorldDraftRegionCommitEvidence two = second.get(20, TimeUnit.SECONDS); + assertThat(two.resultBytes()).containsExactly(one.resultBytes()); + assertThat(two.graphBytes()).containsExactly(one.graphBytes()); + assertEpochs(f, 1, 1); + } finally { + begin.countDown(); + executor.shutdownNow(); + } + } + + @Test + void freezeFirstDeniesFreshStorageAndWriterFirstCompletesBeforeFreeze() throws Exception { + Fixture frozen = fixture(); + freeze(frozen); + assertThatThrownBy(() -> component().store(plan(frozen, List.of(frozen.first()), 0, "denied"))) + .hasMessageContaining("not open"); + assertThat(name(frozen.first())).isEqualTo("original-first"); + Fixture writer = fixture(); + CountDownLatch locked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch freezing = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + WorldDraftRegionCommitPlan writerPlan = + plan(writer, List.of(writer.first(), writer.second()), 0, "writer-first"); + WorldDraftRegionCommitRepository pausedRepository = + new WorldDraftRegionCommitRepository(dsl, fence, mapper) { + @Override + WorldDraftRegionCommitEvidence store(WorldDraftRegionCommitPlan plan) { + WorldDraftRegionCommitEvidence evidence = super.store(plan); + locked.countDown(); + await(release); + return evidence; + } + }; + Future first = + executor.submit( + () -> + new WorldDraftRegionCommitService(pausedRepository, manager, plan -> {}) + .store(writerPlan)); + assertThat(locked.await(15, TimeUnit.SECONDS)).isTrue(); + Future freeze = + executor.submit( + () -> { + freezing.countDown(); + freeze(writer); + }); + assertThat(freezing.await(15, TimeUnit.SECONDS)).isTrue(); + assertThat(freeze.isDone()).isFalse(); + // Other connections still see the precommit complete owner graph and no result history. + assertThat(name(writer.first())).isEqualTo("original-first"); + assertThat(name(writer.second())).isEqualTo("original-second"); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM world_region_draft_commit WHERE request_id = ?", + writerPlan.binding().requestId()) + .fetchOne(0, Long.class)) + .isZero(); + release.countDown(); + first.get(20, TimeUnit.SECONDS); + freeze.get(20, TimeUnit.SECONDS); + assertThat(name(writer.first())).startsWith("writer-first-"); + assertThat(name(writer.second())).startsWith("writer-first-"); + assertEpochs(writer, 1, 1); + assertThatThrownBy( + () -> component().store(plan(writer, List.of(writer.first()), 0, "after-freeze"))) + .hasMessageContaining("not open"); + } finally { + release.countDown(); + executor.shutdownNow(); + } + } + + @Test + void productionGuardRejectsUnmanifestedPayloadMoveInsertDeleteEpochAndOtherFamilyWrites() { + Fixture f = fixture(); + component().store(plan(f, List.of(f.first()), 0, "stored")); + List denied = + List.of( + "UPDATE region SET name = 'legacy' WHERE id = " + f.first(), + "UPDATE region SET tenant_id = 123456789 WHERE id = " + f.first(), + "DELETE FROM region WHERE id = " + f.second(), + "INSERT INTO region(name,tenant_id,version_id) VALUES ('new'," + + f.intake().localTenantKey() + + "," + + f.version().localVersionKey() + + ")", + "UPDATE world_design_aggregate_epoch SET draft_revision_epoch = 99 WHERE tenant_id = " + + f.intake().localTenantKey(), + "UPDATE zone SET name = 'unmanifested' WHERE tenant_id = " + + f.intake().localTenantKey(), + "TRUNCATE world_design_scope_epoch", + "TRUNCATE world_region_draft_commit"); + for (String sql : denied) { + assertThatThrownBy(() -> ownerTransaction().execute(status -> dsl.execute(sql))) + .isInstanceOf(RuntimeException.class); + } + assertThat(name(f.first())).startsWith("stored-"); + assertThat(name(f.second())).isEqualTo("original-second"); + assertThat(count("world_region_draft_execution_manifest")).isZero(); + } + + @Test + void defaultPermissionVerifierFailsBeforeTransactionOrOwnerClaim() { + Fixture f = fixture(); + WorldDraftRegionCommitService denied = new WorldDraftRegionCommitService(repository(), manager); + assertThatThrownBy(() -> denied.store(plan(f, List.of(f.first()), 0, "denied"))) + .hasMessageContaining("permission is unavailable"); + assertThat(epochCount(f, "world_design_aggregate_epoch")).isZero(); + assertThat( + dsl.resultQuery( + "SELECT COUNT(*) FROM world_design_publication_fence_owner WHERE local_tenant_key = ?", + f.intake().localTenantKey()) + .fetchOne(0, Long.class)) + .isZero(); + } + + @Test + void corruptCompleteResultIsRejectedOnExactReplayWithoutRewritingContent() { + Fixture f = fixture(); + WorldDraftRegionCommitPlan plan = plan(f, List.of(f.first(), f.second()), 0, "retained"); + WorldDraftRegionCommitEvidence evidence = component().store(plan); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_region_draft_commit SET result_bytes = ? WHERE request_id = ?", + new byte[] {1}, + plan.binding().requestId())) + .hasStackTraceContaining("history is immutable"); + byte[] corrupt = + new String(evidence.resultBytes(), StandardCharsets.UTF_8) + .replace("\"epoch\":\"1\"", "\"epoch\":\"2\"") + .getBytes(StandardCharsets.UTF_8); + ownerTransaction() + .execute( + status -> { + // Deliberate retained-row corruption fixture only; production mutation guards stay + // intact. + dsl.execute("SET LOCAL session_replication_role = 'replica'"); + try { + dsl.execute( + "UPDATE world_region_draft_commit SET result_bytes = ? WHERE request_id = ?", + corrupt, + plan.binding().requestId()); + } finally { + dsl.execute("SET LOCAL session_replication_role = 'origin'"); + } + return null; + }); + assertThatThrownBy(() -> component().store(plan)) + .hasMessageContaining("immutable result differs"); + Map> beforeRead = regionOperationState(); + WorldDraftRegionCommitService readback = + new WorldDraftRegionCommitService(repository(), manager); + assertThatThrownBy(() -> readback.readCommitted(plan)) + .hasMessageContaining("immutable result differs"); + assertThat(regionOperationState()).isEqualTo(beforeRead); + assertEpochs(f, 1, 1); + assertThat(name(f.first())).startsWith("retained-"); + } + + @Test + void staleTransactionAndWrongPayloadExecutionManifestsCannotAuthorizeRows() { + Fixture f = fixture(); + WorldDraftRegionCommitPlan plan = plan(f, List.of(f.first()), 0, "manifest"); + ownerTransaction() + .execute( + status -> { + fence.lockOpen(f.owner()); + return null; + }); + for (boolean staleTransaction : List.of(true, false)) { + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + // Test-only synthetic manifests under the schema-owner administration + // role. The production + // function creates exact manifests internally; arbitrary roles receive + // no table privilege. + dsl.execute( + "INSERT INTO world_region_draft_execution_manifest " + + "SELECT txid_current() + ?, ?, 'region', r.id, 'UPDATE', ?, r.tenant_id, r.version_id, ?::jsonb, ?::jsonb, to_jsonb(r), to_jsonb(r) || '{\"name\":\"expected-only\"}'::jsonb FROM region r WHERE id = ?", + staleTransaction ? 1 : 0, + plan.binding().commitId(), + f.version().operationId(), + mapper.writeValueAsString(f.owner()), + plan.binding().canonicalJson(), + f.first()); + return dsl.execute( + "UPDATE region SET name = ? WHERE id = ?", + staleTransaction ? "expected-only" : "wrong-payload", + f.first()); + })) + .hasStackTraceContaining("no exact transaction execution manifest"); + } + assertThat(name(f.first())).isEqualTo("original-first"); + assertThat(count("world_region_draft_execution_manifest")).isZero(); + } + + @Test + void v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory() throws Exception { + Fixture f = fixture(); + WorldDraftRegionCommitEvidence prior = + component().store(plan(f, List.of(f.first(), f.second()), 0, "retained-v28")); + freeze(f); + String schema = "region_commit_upgrade_" + UUID.randomUUID().toString().replace("-", ""); + var oldConfig = + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("28")); + oldConfig.load().migrate(); + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + connection.setSchema(schema); + DSLContext retained = DSL.using(connection, SQLDialect.POSTGRES); + connection.setAutoCommit(false); + retained.execute("SET LOCAL session_replication_role = 'replica'"); + Map scopes = new LinkedHashMap<>(); + scopes.put("world_authored_source_tenant_association", "local_tenant_key"); + scopes.put("world_authored_source_tenant_key_reservation", "tenant_key"); + scopes.put("world_authored_source_intake", "local_tenant_key"); + scopes.put("world_authored_version_identity", "local_tenant_key"); + scopes.put("world_design_publication_fence_attempt", "local_tenant_key"); + scopes.put("world_design_publication_fence_owner", "local_tenant_key"); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_design_aggregate_epoch", + "world_design_scope_epoch")) { + scopes.put(table, "tenant_id"); + } + try { + // Copy source-qualified synthetic retained rows into the schema while it still has V28. + for (Map.Entry scope : scopes.entrySet()) { + String override = + scope.getKey().equals("world_authored_version_identity") + ? " OVERRIDING SYSTEM VALUE" + : ""; + String columns = + scope.getKey().equals("world_entity_spawn_binding") + ? "id,tenant_id,version_id,room_id,entity_template_type,entity_template_id,spawn_count,respawn_delay_seconds,version" + : null; + retained.execute( + "INSERT INTO " + + scope.getKey() + + (columns == null ? "" : " (" + columns + ")") + + override + + " SELECT " + + (columns == null ? "*" : columns) + + " FROM world_management_service." + + scope.getKey() + + " WHERE " + + scope.getValue() + + " = ?", + f.intake().localTenantKey()); + } + retained.execute( + "INSERT INTO world_authored_graph_snapshot (snapshot_id,capture_request_digest,publication_fence,target_namespace,canonical_tenant_id,canonical_version_id,version_identity_operation_id,world_slug,game_design_version_id,local_version_key,local_tenant_key,owner_binding_schema_version,intake_operation_id,intake_request_id,intake_request_digest,source_operation_id,source_evidence_digest,intake_receipt_digest,publication_request_id,request_digest,version_state_epoch,publish_workflow_id,applied_commit_id,content_digest,digest_schema_version,supplied_owned_affected_tuples_json,owner_revision_evidence_json,owner_commit_proof_status,graph_bytes,graph_sha256) " + + "SELECT ?,?,a.publication_fence,a.target_namespace,a.canonical_tenant_id,a.canonical_version_id,a.version_identity_operation_id,v.world_slug,a.game_design_version_id,a.version_id,a.local_tenant_key,a.owner_binding_schema_version,a.intake_operation_id,a.intake_request_id,a.intake_request_digest,a.source_operation_id,a.source_evidence_digest,a.intake_receipt_digest,a.publication_request_id,a.request_digest,a.version_state_epoch,a.publish_workflow_id,a.applied_commit_id,a.content_digest,a.digest_schema_version,?,?,'CAPTURED_UNVERIFIED',?,? " + + "FROM world_design_publication_fence_attempt a JOIN world_authored_version_identity v ON v.operation_id = a.version_identity_operation_id", + UUID.randomUUID(), + "a".repeat(64), + mapper.writeValueAsString(prior.binding().affectedUnits(Owner.WORLD_MANAGEMENT)), + "[\"synthetic-v28-unverified-history\"]", + prior.graphBytes(), + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(prior.graphBytes()))); + retained.execute("SET LOCAL session_replication_role = 'origin'"); + connection.commit(); + } catch (RuntimeException exception) { + connection.rollback(); + throw exception; + } + connection.setAutoCommit(true); + scopes.put("world_authored_graph_snapshot", "local_tenant_key"); + Map> before = + retainedRows(retained, scopes.keySet().stream().toList(), true); + assertThat( + retained + .resultQuery( + "SELECT owner_commit_proof_status FROM world_authored_graph_snapshot") + .fetchOne(0, String.class)) + .isEqualTo("CAPTURED_UNVERIFIED"); + assertThat( + retained + .resultQuery( + "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = 'world_region_draft_commit'", + schema) + .fetchOne(0, Long.class)) + .isZero(); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + assertThat(retainedRows(retained, scopes.keySet().stream().toList(), true)).isEqualTo(before); + assertThat( + retained + .resultQuery( + "SELECT COUNT(*) FROM world_entity_spawn_binding WHERE entity_canonical_tenant_id IS NOT NULL OR entity_canonical_version_id IS NOT NULL OR entity_canonical_template_id IS NOT NULL") + .fetchOne(0, Long.class)) + .isZero(); + SingleConnectionDataSource dataSource = new SingleConnectionDataSource(connection, true); + DataSourceTransactionManager retainedManager = new DataSourceTransactionManager(dataSource); + DriverManagerDataSource committedReadDataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + committedReadDataSource.setSchema(schema); + // Match the normal repository proxy's NOT_SUPPORTED read boundary. A separate connection + // reads this exact schema's committed intake while the owner transaction is suspended. + TransactionInterceptor readTransactions = new TransactionInterceptor(); + readTransactions.setTransactionManager(retainedManager); + readTransactions.setTransactionAttributeSource(new AnnotationTransactionAttributeSource()); + ProxyFactory intakeProxy = + new ProxyFactory( + new WorldAuthoredSourceIntakeRepository( + DSL.using(committedReadDataSource, SQLDialect.POSTGRES))); + intakeProxy.setProxyTargetClass(true); + intakeProxy.addAdvice(readTransactions); + WorldAuthoredSourceIntakeRepository retainedIntake = + (WorldAuthoredSourceIntakeRepository) intakeProxy.getProxy(); + assertThat(retainedIntake.read(NAMESPACE, f.intake().intakeRequestId()).orElseThrow()) + .isEqualTo(f.intake()); + WorldDesignPublicationFenceRepository retainedFence = + new WorldDesignPublicationFenceRepository(retained, retainedIntake); + WorldDraftRegionCommitService deniedFrozen = + new WorldDraftRegionCommitService( + new WorldDraftRegionCommitRepository(retained, retainedFence, mapper), + retainedManager, + plan -> {}); + assertThatThrownBy( + () -> deniedFrozen.store(plan(f, List.of(f.first()), 1, "must-remain-frozen"))) + .hasMessageContaining("not open"); + assertThat(retainedRows(retained, scopes.keySet().stream().toList(), true)).isEqualTo(before); + assertThat( + retained + .resultQuery("SELECT COUNT(*) FROM world_region_draft_commit") + .fetchOne(0, Long.class)) + .isZero(); + } finally { + // This uniquely named schema is owned exclusively by this migration test. + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private Map> retainedRows(DSLContext retained, List tables) { + return retainedRows(retained, tables, false); + } + + private Map> retainedRows( + DSLContext retained, List tables, boolean retainedSpawnColumnsOnly) { + Map> rows = new LinkedHashMap<>(); + for (String table : tables) { + String expression = + retainedSpawnColumnsOnly && table.equals("world_entity_spawn_binding") + ? "to_jsonb(t) - 'entity_canonical_tenant_id' - 'entity_canonical_version_id' - 'entity_canonical_template_id'" + : "to_jsonb(t)"; + rows.put( + table, + retained + .resultQuery( + "SELECT (" + + expression + + ")::TEXT FROM " + + table + + " t ORDER BY (" + + expression + + ")::TEXT") + .fetch(0, String.class)); + } + return rows; + } + + private Map> regionOperationState() { + return retainedRows( + dsl, + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_design_aggregate_epoch", + "world_design_scope_epoch", + "world_region_draft_commit", + "world_region_draft_execution_manifest", + "world_authored_source_intake", + "world_authored_version_identity", + "world_design_publication_fence_owner", + "world_design_publication_fence_attempt")); + } + + private void race(Fixture f, long epoch) throws Exception { + CountDownLatch begin = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + WorldDraftRegionCommitPlan one = plan(f, List.of(f.first(), f.second()), epoch, "one"); + WorldDraftRegionCommitPlan two = plan(f, List.of(f.first(), f.second()), epoch, "two"); + Future first = executor.submit(() -> contend(one, begin)); + Future second = executor.submit(() -> contend(two, begin)); + begin.countDown(); + assertThat(List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + } finally { + begin.countDown(); + executor.shutdownNow(); + } + } + + private boolean contend(WorldDraftRegionCommitPlan plan, CountDownLatch begin) { + await(begin); + try { + component().store(plan); + return true; + } catch (RuntimeException exception) { + assertThat(exception).hasStackTraceContaining("DRAFT_WRITE_CONFLICT"); + return false; + } + } + + private void assertChanged( + WorldDraftRegionCommitPlan original, + String base, + List revisions, + List units) { + DraftCommitBinding prior = original.binding(); + WorldDraftRegionCommitPlan changed = + WorldDraftRegionCommitPlan.create( + DraftCommitBinding.create( + prior.target(), prior.requestId(), prior.commitId(), base, revisions, units), + original.ownerBinding()); + assertThatThrownBy(() -> component().store(changed)).hasMessageContaining("changed full input"); + Map> beforeRead = regionOperationState(); + WorldDraftRegionCommitService readback = + new WorldDraftRegionCommitService(repository(), manager); + assertThatThrownBy(() -> readback.readCommitted(changed)) + .hasMessageContaining("changed full input"); + assertThat(regionOperationState()).isEqualTo(beforeRead); + } + + private WorldDraftRegionCommitPlan plan(Fixture f, List regions, long epoch, String name) { + UUID request = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + for (long region : regions) { + UUID revision = UUID.randomUUID(); + WorldDesignMutationRevision mutation = + WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revision.toString()) + .setCommitId(commit.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setAggregateId(Long.toString(region)) + .setExpectedDraftRevisionEpoch(epoch) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(Long.toString(region)) + .setExpectedDraftScopeRevisionEpoch(epoch) + .setRegion( + RegionDesignMutation.newBuilder() + .setName(name + "-" + region) + .setShardId(7) + .setWeather("rain") + .setGenerationSeed(9_007_199_254_740_999L) + .setGeneratorType("synthetic") + .setGeneratorParams("{\"seed\":1}") + .setSpacingMultiplier(2.0)) + .build(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + revision, + Owner.WORLD_MANAGEMENT, + json(mutation))); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + Long.toString(region), + "AGGREGATE", + Long.toString(region), + Long.toString(epoch))); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + Long.toString(region), + "REGION_SUBTREE", + Long.toString(region), + Long.toString(epoch))); + } + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + "synthetic opaque other owner payload")); + units.add(new AffectedUnit(Owner.ENTITY_MANAGEMENT, "ITEM", "17", "AGGREGATE", "17", "4")); + AuthoredWorldSourceEvidence source = f.intake().source(); + DraftCommitBinding.TargetProof target = + new DraftCommitBinding.TargetProof( + f.owner().canonicalTenantId(), + f.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + source.sourceGameTenantKey(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + return WorldDraftRegionCommitPlan.create( + DraftCommitBinding.create(target, request, commit, "retained-base", revisions, units), + f.owner()); + } + + private Fixture fixture() { + UUID tenant = UUID.randomUUID(); + UUID registration = UUID.randomUUID(); + UUID sourceOperation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + long sourceRow = Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + String sourceTenant = "gd-row-" + sourceRow; + String digest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, "Synthetic component world"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW", + evidenceDigest); + UUID intakeRequest = UUID.randomUUID(); + ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, intakeRequest, source)); + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository.read(NAMESPACE, intakeRequest).orElseThrow(); + return Objects.requireNonNull( + ownerTransaction() + .execute( + status -> { + UUID canonicalVersion = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + worldSlug, + sourceOperation, + evidenceDigest, + GAME_DESIGN_VERSION); + WorldAuthoredVersionIdentityReceipt version = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + tenant, + canonicalVersion, + version.operationId(), + GAME_DESIGN_VERSION, + intakeRequest, + intake.operationId(), + intake.requestDigest(), + sourceOperation, + evidenceDigest, + intake.receiptDigest()); + // Only this setup disables V24. The tested writer always runs with production + // guards restored. + dsl.execute("SET LOCAL session_replication_role = 'replica'"); + long first; + long second; + try { + first = + insertId( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('original-first',?,?) RETURNING id", + intake.localTenantKey(), + version.localVersionKey()); + second = + insertId( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('original-second',?,?) RETURNING id", + intake.localTenantKey(), + version.localVersionKey()); + long zone = + insertId( + "INSERT INTO zone(region_id,name,tenant_id,version_id) VALUES (?,'zone',?,?) RETURNING id", + first, + intake.localTenantKey(), + version.localVersionKey()); + long room = + insertId( + "INSERT INTO room(zone_id,name,tenant_id,version_id) VALUES (?,'room',?,?) RETURNING id", + zone, + intake.localTenantKey(), + version.localVersionKey()); + dsl.execute( + "INSERT INTO room_exit(tenant_id,version_id,from_room_id,to_room_id,direction,cost) VALUES (?,?,?,?,'NORTH',1)", + intake.localTenantKey(), + version.localVersionKey(), + room, + room); + dsl.execute( + "INSERT INTO generation_rule(tenant_id,version_id,name,scope_type,scope_id,value) VALUES (?,?,'rule','REGION_SUBTREE',?,'seeded')", + intake.localTenantKey(), + version.localVersionKey(), + Long.toString(first)); + dsl.execute( + "INSERT INTO world_entity_spawn_binding(tenant_id,version_id,room_id,entity_template_type,entity_template_id,spawn_count,respawn_delay_seconds) VALUES (?,?,?,'NPC',1,1,0)", + intake.localTenantKey(), + version.localVersionKey(), + room); + } finally { + dsl.execute("SET LOCAL session_replication_role = 'origin'"); + } + assertOrigin(); + return new Fixture(intake, version, owner, first, second); + })); + } + + private void seedScope(Fixture f, long region, long epoch) { + ownerTransaction() + .execute( + status -> { + dsl.execute("SET LOCAL session_replication_role = 'replica'"); + try { + dsl.execute( + "INSERT INTO world_design_scope_epoch(tenant_id,version_id,scope_type,scope_id,draft_scope_revision_epoch) VALUES (?,?,'REGION_SUBTREE',?,?)", + f.intake().localTenantKey(), + f.version().localVersionKey(), + Long.toString(region), + epoch); + } finally { + dsl.execute("SET LOCAL session_replication_role = 'origin'"); + } + return null; + }); + } + + private void freeze(Fixture f) { + OwnerBinding o = f.owner(); + String request = "freeze-" + UUID.randomUUID(); + WorldDesignPublicationFenceEvidence evidence = + new WorldDesignPublicationFenceEvidence( + o.targetNamespace(), + o.canonicalTenantId(), + o.canonicalVersionId(), + o.versionIdentityOperationId(), + o.gameDesignVersionId(), + o.intakeRequestId(), + o.intakeOperationId(), + o.intakeRequestDigest(), + o.sourceOperationId(), + o.sourceEvidenceDigest(), + o.intakeReceiptDigest(), + request, + "a".repeat(64), + 1, + "publish:" + o.canonicalTenantId() + ":publish-request:" + request); + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "synthetic-unverified-checkpoint", "b".repeat(64), 2))); + } + + private WorldDraftRegionCommitService component() { + return new WorldDraftRegionCommitService( + repository(), + manager, + plan -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertOrigin(); + // Synthetic prerequisite only. No authenticated permission, APPLIED, or release evidence. + }); + } + + private WorldDraftRegionCommitRepository repository() { + return new WorldDraftRegionCommitRepository(dsl, fence, mapper); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private void assertOrigin() { + assertThat( + dsl.resultQuery("SELECT current_setting('session_replication_role')") + .fetchOne(0, String.class)) + .isEqualTo("origin"); + } + + private String name(long region) { + return dsl.resultQuery("SELECT name FROM region WHERE id = ?", region) + .fetchOne(0, String.class); + } + + private long insertId(String sql, Object... values) { + return Objects.requireNonNull(dsl.resultQuery(sql, values).fetchOne(0, Long.class)); + } + + private long count(String table) { + return Objects.requireNonNull( + dsl.resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class)); + } + + private long epochCount(Fixture f, String table) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM " + table + " WHERE tenant_id = ? AND version_id = ?", + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetchOne(0, Long.class)); + } + + private void assertEpochs(Fixture f, long aggregate, long scope) { + assertThat( + dsl.resultQuery( + "SELECT draft_revision_epoch FROM world_design_aggregate_epoch WHERE tenant_id = ? AND version_id = ? ORDER BY aggregate_id", + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetch(0, Long.class)) + .containsExactly(aggregate, aggregate); + assertThat( + dsl.resultQuery( + "SELECT draft_scope_revision_epoch FROM world_design_scope_epoch WHERE tenant_id = ? AND version_id = ? ORDER BY scope_id", + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetch(0, Long.class)) + .containsExactly(scope, scope); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new AssertionError(exception); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Storage barrier timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(exception); + } + } + + private record Fixture( + WorldAuthoredSourceIntakeReceipt intake, + WorldAuthoredVersionIdentityReceipt version, + OwnerBinding owner, + long first, + long second) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomePostgresIntegrationTest.java new file mode 100644 index 0000000000..dd4a3a196e --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomePostgresIntegrationTest.java @@ -0,0 +1,1167 @@ +package integration.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +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.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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 net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOperation; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcome; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcomeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcomeService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPlan; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitService; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +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.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; +import tools.jackson.databind.ObjectMapper; + +/** + * Synthetic Account bindings prove immutable World storage only, never authorization or APPLIED. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldDraftTerminalOutcomePostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final long GAME_DESIGN_VERSION = 9_000_000_000_000_001L; + + @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 DSLContext dsl; + @Autowired private PlatformTransactionManager manager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository fence; + @Autowired private ObjectMapper mapper; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void abortBlocksDelayedTopologyAndRawRegionWritesAndExactRetrySurvivesFreeze() { + Fixture topology = fixture(false); + WorldDraftTopologyCommitPlan topologyPlan = + topologyPlan(topology, UUID.randomUUID(), UUID.randomUUID()); + WorldDraftTerminalOperation topologyOperation = operation(topology, topologyPlan.binding()); + WorldDraftTerminalOutcome original = terminalService().recordDefinitiveAbort(topologyOperation); + assertThatThrownBy(() -> topologyComponent().store(topologyPlan)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("no-commit"); + assertThat(count("world_topology_draft_commit", topologyPlan.binding().requestId())).isZero(); + + Fixture region = fixture(true); + WorldDraftRegionCommitPlan regionPlan = + regionPlan(region, UUID.randomUUID(), UUID.randomUUID()); + WorldDraftTerminalOperation regionOperation = operation(region, regionPlan.binding()); + terminalService().recordDefinitiveAbort(regionOperation); + assertThatThrownBy(() -> regionComponent().store(regionPlan)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("no-commit"); + assertRawRegionFunctionDenied(region, regionPlan); + assertThat(regionName(region.seededRegion())).isEqualTo("seeded"); + assertThat(count("world_region_draft_commit", regionPlan.binding().requestId())).isZero(); + + freeze(topology); + WorldDraftTerminalOutcome replay = terminalService().recordDefinitiveAbort(topologyOperation); + assertThat(replay.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(replay.recordedAt()).isEqualTo(original.recordedAt()); + } + + @Test + void v37FunctionReplacementPreservesCommittedAbortEvidenceAndBlocksDelayedWrites() { + Fixture f = fixture(true); + WorldDraftRegionCommitPlan priorRegion = regionPlan(f, UUID.randomUUID(), UUID.randomUUID()); + regionComponent().store(priorRegion); + assertThat(regionEpochs(f)).containsExactly(1L, 1L); + + WorldDraftRegionCommitPlan abortedRegion = + regionPlan(f, UUID.randomUUID(), UUID.randomUUID(), 1L); + WorldDraftTerminalOperation regionOperation = operation(f, abortedRegion.binding()); + WorldDraftTerminalOutcome regionAbort = + terminalService().recordDefinitiveAbort(regionOperation); + assertThat(regionAbort.observedEpochs()) + .extracting(WorldDraftTerminalOutcome.ObservedEpoch::epoch) + .containsOnly("1"); + + Fixture topology = fixture(false); + WorldDraftTopologyCommitPlan abortedTopology = + topologyPlan(topology, UUID.randomUUID(), UUID.randomUUID()); + WorldDraftTerminalOperation topologyOperation = operation(topology, abortedTopology.binding()); + WorldDraftTerminalOutcome topologyAbort = + terminalService().recordDefinitiveAbort(topologyOperation); + assertThat(topologyAbort.observedEpochs()) + .extracting(WorldDraftTerminalOutcome.ObservedEpoch::epoch) + .containsOnly("0"); + + List retainedBefore = + List.of( + retainedTerminalSourceFenceAndEpochSnapshot(regionOperation), + retainedTerminalSourceFenceAndEpochSnapshot(topologyOperation)); + long guardFunctionOid = worldAbortedAttemptGuardFunctionOid(); + assertThat(worldAbortedAttemptGuardTriggerCount()).isEqualTo(4L); + assertThat(worldAbortedAttemptGuardHasPublicExecute()).isFalse(); + + // Controlled function-replacement proof against live retained rows, not a full Flyway upgrade. + replaceV36TerminalGuardWithV37(); + + assertThat(worldAbortedAttemptGuardFunctionOid()).isEqualTo(guardFunctionOid); + assertThat(worldAbortedAttemptGuardTriggerCount()).isEqualTo(4L); + assertThat(worldAbortedAttemptGuardHasPublicExecute()).isFalse(); + assertThat( + List.of( + retainedTerminalSourceFenceAndEpochSnapshot(regionOperation), + retainedTerminalSourceFenceAndEpochSnapshot(topologyOperation))) + .containsExactlyElementsOf(retainedBefore); + WorldDraftTerminalOutcome regionReadback = + terminalService().readDefinitiveAbort(regionOperation).orElseThrow(); + assertThat(regionReadback.canonicalBytes()).containsExactly(regionAbort.canonicalBytes()); + assertThat(regionReadback.observedEpochs()) + .containsExactlyElementsOf(regionAbort.observedEpochs()); + WorldDraftTerminalOutcome topologyReadback = + terminalService().readDefinitiveAbort(topologyOperation).orElseThrow(); + assertThat(topologyReadback.canonicalBytes()).containsExactly(topologyAbort.canonicalBytes()); + assertThat(topologyReadback.observedEpochs()) + .containsExactlyElementsOf(topologyAbort.observedEpochs()); + + assertThatThrownBy(() -> topologyComponent().store(abortedTopology)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("no-commit"); + assertThatThrownBy(() -> regionComponent().store(abortedRegion)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("no-commit"); + assertRawRegionFunctionDenied(f, abortedRegion); + assertThat(count("world_topology_draft_commit", abortedTopology.binding().requestId())) + .isZero(); + assertThat(count("world_region_draft_commit", abortedRegion.binding().requestId())).isZero(); + assertThat(regionName(f.seededRegion())).isEqualTo("committed"); + assertThat(regionEpochs(f)).containsExactly(1L, 1L); + assertThat(draftRegionCount(topology)).isZero(); + assertThat( + List.of( + retainedTerminalSourceFenceAndEpochSnapshot(regionOperation), + retainedTerminalSourceFenceAndEpochSnapshot(topologyOperation))) + .containsExactlyElementsOf(retainedBefore); + } + + @Test + void retainedUnverifiedTopologyOrRegionOutputCannotBeRelabeledAsAborted() { + Fixture topology = fixture(false); + WorldDraftTopologyCommitPlan topologyPlan = + topologyPlan(topology, UUID.randomUUID(), UUID.randomUUID()); + topologyComponent().store(topologyPlan); + assertThatThrownBy( + () -> + terminalService() + .recordDefinitiveAbort(operation(topology, topologyPlan.binding()))) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("history"); + assertThat(count("world_topology_draft_commit", topologyPlan.binding().requestId())) + .isEqualTo(1L); + assertThat(terminalService().readDefinitiveAbort(operation(topology, topologyPlan.binding()))) + .isEmpty(); + + Fixture region = fixture(true); + WorldDraftRegionCommitPlan regionPlan = + regionPlan(region, UUID.randomUUID(), UUID.randomUUID()); + regionComponent().store(regionPlan); + assertThatThrownBy( + () -> terminalService().recordDefinitiveAbort(operation(region, regionPlan.binding()))) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("history"); + assertThat(count("world_region_draft_commit", regionPlan.binding().requestId())).isEqualTo(1L); + } + + @Test + void topologyCommitAndAbortSerializeToExactlyOneImmutableTerminalResult() throws Exception { + Fixture f = fixture(false); + WorldDraftTopologyCommitPlan plan = topologyPlan(f, UUID.randomUUID(), UUID.randomUUID()); + WorldDraftTerminalOperation operation = operation(f, plan.binding()); + Race result = + race( + () -> topologyComponent().store(plan), + () -> terminalService().recordDefinitiveAbort(operation)); + + assertThat(result.commitWon()).isNotEqualTo(result.abortWon()); + assertThat(terminalService().readDefinitiveAbort(operation).isPresent()) + .isEqualTo(result.abortWon()); + assertThat(count("world_topology_draft_commit", plan.binding().requestId()) > 0L) + .isEqualTo(result.commitWon()); + if (result.abortWon()) { + assertThatThrownBy(() -> topologyComponent().store(plan)) + .isInstanceOf(RuntimeException.class); + } + } + + @Test + void rawRegionCommitAndAbortSerializeOnTheSameV25Row() throws Exception { + Fixture f = fixture(true); + WorldDraftRegionCommitPlan plan = regionPlan(f, UUID.randomUUID(), UUID.randomUUID()); + WorldDraftTerminalOperation operation = operation(f, plan.binding()); + Race result = + race( + () -> regionComponent().store(plan), + () -> terminalService().recordDefinitiveAbort(operation)); + + assertThat(result.commitWon()).isNotEqualTo(result.abortWon()); + assertThat(terminalService().readDefinitiveAbort(operation).isPresent()) + .isEqualTo(result.abortWon()); + assertThat(count("world_region_draft_commit", plan.binding().requestId()) > 0L) + .isEqualTo(result.commitWon()); + assertThat(regionName(f.seededRegion())).isEqualTo(result.commitWon() ? "committed" : "seeded"); + } + + @Test + void absentReadbackIsUnknownChangedBindingsConflictAndRolledBackAbortLeavesNoRow() { + Fixture f = fixture(false); + WorldDraftTopologyCommitPlan plan = topologyPlan(f, UUID.randomUUID(), UUID.randomUUID()); + WorldDraftTerminalOperation operation = operation(f, plan.binding()); + WorldDraftTerminalOutcomeService service = terminalService(); + assertThat(service.readDefinitiveAbort(operation)).isEmpty(); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + terminalRepository().recordDefinitiveAbort(operation); + throw new IllegalStateException("rollback fixture"); + })) + .hasMessageContaining("rollback fixture"); + assertThat(service.readDefinitiveAbort(operation)).isEmpty(); + + WorldDraftTerminalOutcome original = service.recordDefinitiveAbort(operation); + byte[] changedAccount = + accountBinding(f, plan.binding(), operationIds(operation), new byte[] {9}).canonicalBytes(); + WorldDraftTerminalOperation changedSource = + new WorldDraftTerminalOperation( + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId(), + operation.canonicalTenantId(), + operation.canonicalVersionId(), + operation.binding(), + operation.ownerBinding(), + changedAccount); + assertThatThrownBy(() -> service.readDefinitiveAbort(changedSource)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("changed binding"); + + OwnerBinding substitutedOwner = + new OwnerBinding( + operation.ownerBinding().targetNamespace(), + operation.ownerBinding().canonicalTenantId(), + operation.ownerBinding().canonicalVersionId(), + operation.ownerBinding().versionIdentityOperationId(), + operation.ownerBinding().gameDesignVersionId(), + operation.ownerBinding().intakeRequestId(), + operation.ownerBinding().intakeOperationId(), + operation.ownerBinding().intakeRequestDigest(), + UUID.randomUUID(), + operation.ownerBinding().sourceEvidenceDigest(), + operation.ownerBinding().intakeReceiptDigest()); + WorldDraftTerminalOperation changedOwnerSource = + new WorldDraftTerminalOperation( + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId(), + operation.canonicalTenantId(), + operation.canonicalVersionId(), + operation.binding(), + substitutedOwner, + operation.accountBindingBytes()); + assertThatThrownBy(() -> service.readDefinitiveAbort(changedOwnerSource)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("changed binding"); + + DraftCommitBinding changedBinding = + changedPayload(plan.binding(), "substituted game design bytes"); + WorldDraftTerminalOperation changedInput = + operation(f, changedBinding, operation.operationId(), operation.authorizationFenceId()); + assertThatThrownBy(() -> service.readDefinitiveAbort(changedInput)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("changed binding"); + assertThat(service.readDefinitiveAbort(operation).orElseThrow().canonicalBytes()) + .containsExactly(original.canonicalBytes()); + } + + @Test + void authenticatedReadReturnsUnknownThenExactAbortAcrossFreezeAndRejectsSubstitution() { + Fixture f = fixture(false); + WorldDraftTopologyCommitPlan plan = topologyPlan(f, UUID.randomUUID(), UUID.randomUUID()); + WorldDraftTerminalOperation operation = operation(f, plan.binding()); + WorldDraftTerminalOutcomeRepository repository = terminalRepository(); + WorldDraftTerminalReadGrpcService receiver = + new WorldDraftTerminalReadGrpcService( + repository, new WorldDraftGraphApplicationRepository(dsl, fence, mapper), NAMESPACE); + + var absentRequest = + WorldDraftTerminalReadEvidence.Request.create(NAMESPACE, operation.accountBindingBytes()); + ReadResult absentCall = readAsAccount(receiver, absentRequest, "account-service"); + ReadWorldDraftTerminalOutcomeResponse absent = absentCall.response(); + assertThat(absentCall.error()).isNull(); + assertThat(absent.getStatus()) + .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN); + assertThat(absent.getOwnerReadbackBytes()).isEmpty(); + + WorldDraftTerminalOutcome stored = terminalService().recordDefinitiveAbort(operation); + var appliedRequest = + WorldDraftTerminalReadEvidence.Request.create(NAMESPACE, operation.accountBindingBytes()); + var appliedCall = readAsAccount(receiver, appliedRequest, "account-service"); + assertThat(appliedCall.error()).isNull(); + var appliedResponse = appliedCall.response(); + var appliedEvidence = + WorldDraftTerminalReadGrpcCodec.fromResponse(appliedRequest, appliedResponse); + var abort = appliedEvidence.ownerReadback().orElseThrow(); + assertThat(abort.owner()).isEqualTo(DraftAuthorizationFenceBinding.Owner.WORLD); + assertThat(abort.outcome()) + .isEqualTo(DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED); + assertThat(abort.fullBinding()).containsExactly(operation.accountBindingBytes()); + assertThat(abort.result()).containsExactly(stored.canonicalBytes()); + + byte[] changedAccount = + accountBinding(f, plan.binding(), operationIds(operation), new byte[] {9}).canonicalBytes(); + var changedBindingRequest = + WorldDraftTerminalReadEvidence.Request.create(NAMESPACE, changedAccount); + var changedBindingCall = readAsAccount(receiver, changedBindingRequest, "account-service"); + assertThat(Status.fromThrowable(changedBindingCall.error()).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + + var changedNamespaceRequest = + WorldDraftTerminalReadEvidence.Request.create("other", operation.accountBindingBytes()); + var changedNamespaceCall = readAsAccount(receiver, changedNamespaceRequest, "account-service"); + assertThat(Status.fromThrowable(changedNamespaceCall.error()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + freeze(f); + var postFreezeRequest = + WorldDraftTerminalReadEvidence.Request.create(NAMESPACE, operation.accountBindingBytes()); + var postFreezeCall = readAsAccount(receiver, postFreezeRequest, "account-service"); + assertThat(postFreezeCall.error()).isNull(); + var postFreeze = postFreezeCall.response(); + var postFreezeEvidence = + WorldDraftTerminalReadGrpcCodec.fromResponse(postFreezeRequest, postFreeze); + assertThat(postFreezeEvidence.ownerReadback().orElseThrow().canonicalBytes()) + .containsExactly(abort.canonicalBytes()); + assertThat(postFreezeEvidence.ownerReadback().orElseThrow().result()) + .containsExactly(stored.canonicalBytes()); + } + + private ReadResult readAsAccount( + WorldDraftTerminalReadGrpcService receiver, + WorldDraftTerminalReadEvidence.Request request, + String peerService) { + Collector observer = new Collector(); + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + peerService, NAMESPACE, peerService); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + receiver.readWorldDraftTerminalOutcome( + WorldDraftTerminalReadGrpcCodec.toRequest(request), observer); + } finally { + context.detach(previous); + } + return new ReadResult(observer.value, observer.error); + } + + private Race race(ThrowingRunnable commit, ThrowingRunnable abort) throws Exception { + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future commitFuture = + executor.submit( + () -> { + ready.countDown(); + await(start); + return succeeded(commit); + }); + Future abortFuture = + executor.submit( + () -> { + ready.countDown(); + await(start); + return succeeded(abort); + }); + await(ready); + start.countDown(); + return new Race( + commitFuture.get(30, TimeUnit.SECONDS), abortFuture.get(30, TimeUnit.SECONDS)); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + private boolean succeeded(ThrowingRunnable action) { + try { + action.run(); + return true; + } catch (RuntimeException expectedRaceLoser) { + return false; + } + } + + private void assertRawRegionFunctionDenied(Fixture f, WorldDraftRegionCommitPlan plan) { + Map change = new LinkedHashMap<>(); + var mutation = plan.regionRevisions().getFirst().mutation(); + change.put("id", f.seededRegion()); + change.put("expectedAggregateEpoch", mutation.getExpectedDraftRevisionEpoch()); + change.put("expectedScopeEpoch", mutation.getExpectedDraftScopeRevisionEpoch()); + change.put("name", "delayed"); + change.put("shardId", 1); + change.put("weather", "rain"); + change.put("generationSeed", 17L); + change.put("generatorType", "test"); + change.put("generatorParams", "{}"); + change.put("spacingMultiplier", 1.0d); + String ownerJson = mapper.writeValueAsString(plan.ownerBinding()); + String changesJson = mapper.writeValueAsString(List.of(change)); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + dsl.resultQuery( + "SELECT world_store_guarded_region_rows(?::jsonb, ?::jsonb, ?::jsonb)", + ownerJson, + plan.binding().canonicalJson(), + changesJson) + .fetch())) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("definitive no-commit"); + } + + private Fixture fixture(boolean seedRegion) { + UUID tenant = UUID.randomUUID(); + UUID registration = UUID.randomUUID(); + UUID sourceOperation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + long sourceRow = Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + String sourceTenant = "gd-row-" + sourceRow; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, "Synthetic terminal world"); + String sourceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + sourceOperation, + requestDigest, + tenant, + tenantSlug, + worldSlug, + "Synthetic terminal world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + sourceOperation, + requestDigest, + tenant, + tenantSlug, + worldSlug, + "Synthetic terminal world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW", + sourceDigest); + UUID intakeRequest = UUID.randomUUID(); + ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, intakeRequest, source)); + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository.read(NAMESPACE, intakeRequest).orElseThrow(); + Fixture created = + ownerTransaction() + .execute( + status -> { + UUID versionId = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + worldSlug, + sourceOperation, + sourceDigest, + GAME_DESIGN_VERSION); + WorldAuthoredVersionIdentityReceipt version = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + versionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + tenant, + versionId, + version.operationId(), + GAME_DESIGN_VERSION, + intakeRequest, + intake.operationId(), + intake.requestDigest(), + sourceOperation, + sourceDigest, + intake.receiptDigest()); + return new Fixture(intake, version, owner, null); + }); + if (!seedRegion) { + return created; + } + Long regionId = + ownerTransaction() + .execute( + status -> { + dsl.execute("SET LOCAL session_replication_role = 'replica'"); + var inserted = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('seeded',?,?) RETURNING id", + intake.localTenantKey(), + created.version().localVersionKey()), + "seeded region insert must return a row"); + return Objects.requireNonNull( + inserted.get(0, Long.class), "seeded region insert must return an id"); + }); + return new Fixture(intake, created.version(), created.owner(), regionId); + } + + private WorldDraftTopologyCommitPlan topologyPlan(Fixture f, UUID request, UUID commit) { + UUID aggregate = UUID.randomUUID(); + UUID revisionId = UUID.randomUUID(); + WorldDesignMutationRevision mutation = + WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(revisionId.toString()) + .setAggregateId(aggregate.toString()) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(aggregate.toString()) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("topology") + .setWeather("clear") + .setShardId(0) + .setGenerationSeed(17) + .setGeneratorType("test") + .setGeneratorParams("{}")) + .build(); + List worldUnits = + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + aggregate.toString(), + "AGGREGATE", + aggregate.toString(), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + aggregate.toString(), + "REGION_SUBTREE", + aggregate.toString(), + "0")); + DraftCommitBinding binding = draftBinding(f, request, commit, mutation, revisionId, worldUnits); + return WorldDraftTopologyCommitPlan.create(binding, f.owner()); + } + + private WorldDraftRegionCommitPlan regionPlan(Fixture f, UUID request, UUID commit) { + return regionPlan(f, request, commit, 0L); + } + + private WorldDraftRegionCommitPlan regionPlan( + Fixture f, UUID request, UUID commit, long expectedEpoch) { + long region = f.seededRegion(); + UUID revisionId = UUID.randomUUID(); + WorldDesignMutationRevision mutation = + WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(revisionId.toString()) + .setAggregateId(Long.toString(region)) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(Long.toString(region)) + .setExpectedDraftRevisionEpoch(expectedEpoch) + .setExpectedDraftScopeRevisionEpoch(expectedEpoch) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("committed") + .setWeather("clear") + .setShardId(1) + .setGenerationSeed(17) + .setGeneratorType("test") + .setGeneratorParams("{}")) + .build(); + List worldUnits = + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + Long.toString(region), + "AGGREGATE", + Long.toString(region), + Long.toString(expectedEpoch)), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + Long.toString(region), + "REGION_SUBTREE", + Long.toString(region), + Long.toString(expectedEpoch))); + DraftCommitBinding binding = draftBinding(f, request, commit, mutation, revisionId, worldUnits); + return WorldDraftRegionCommitPlan.create(binding, f.owner()); + } + + private DraftCommitBinding draftBinding( + Fixture f, + UUID request, + UUID commit, + WorldDesignMutationRevision worldMutation, + UUID worldRevision, + List worldUnits) { + var source = f.intake().source(); + TargetProof target = + new TargetProof( + f.owner().canonicalTenantId(), + f.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + source.sourceGameTenantKey(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + UUID gdRevision = UUID.randomUUID(); + List allUnits = new ArrayList<>(worldUnits); + allUnits.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "VERSION", + f.owner().canonicalVersionId().toString(), + "AGGREGATE", + f.owner().canonicalVersionId().toString(), + "0")); + return DraftCommitBinding.create( + target, + request, + commit, + "retained-base", + List.of( + new RevisionPayload("0", worldRevision, Owner.WORLD_MANAGEMENT, json(worldMutation)), + new RevisionPayload( + "1", gdRevision, Owner.GAME_DESIGN_CONTROL_PLANE, "opaque Game Design input")), + allUnits); + } + + private DraftCommitBinding changedPayload(DraftCommitBinding binding, String payload) { + List revisions = new ArrayList<>(); + for (RevisionPayload revision : binding.revisions()) { + revisions.add( + new RevisionPayload( + revision.revisionOrder(), + revision.revisionId(), + revision.owner(), + revision.owner() == Owner.GAME_DESIGN_CONTROL_PLANE ? payload : revision.payload())); + } + return DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + revisions, + binding.affectedUnits()); + } + + private WorldDraftTerminalOperation operation(Fixture f, DraftCommitBinding binding) { + return operation(f, binding, UUID.randomUUID(), UUID.randomUUID()); + } + + private WorldDraftTerminalOperation operation( + Fixture f, DraftCommitBinding binding, UUID operationId, UUID fenceId) { + UUID actor = UUID.randomUUID(); + DraftAuthorizationFenceBinding accountBinding = + accountBinding( + f, + binding, + new OperationIds(operationId, binding.requestId(), binding.commitId(), fenceId, actor), + new byte[] {1, 2, 3}); + return new WorldDraftTerminalOperation( + operationId, + binding.requestId(), + binding.commitId(), + fenceId, + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding, + f.owner(), + accountBinding.canonicalBytes()); + } + + private DraftAuthorizationFenceBinding accountBinding( + Fixture f, DraftCommitBinding binding, OperationIds ids, byte[] evidence) { + return new DraftAuthorizationFenceBinding( + ids.operation(), + ids.request(), + ids.commit(), + ids.fence(), + ids.actor(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.baseCommitId(), + "0", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of( + new SourceEvidence( + SourceKind.TENANT, + binding.target().canonicalTenantId().toString(), + null, + "1", + null, + null, + evidence))); + } + + private OperationIds operationIds(WorldDraftTerminalOperation operation) { + return new OperationIds( + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId(), + UUID.randomUUID()); + } + + private WorldDraftTopologyCommitService topologyComponent() { + return new WorldDraftTopologyCommitService( + new WorldDraftTopologyCommitRepository(dsl, fence, mapper), manager, plan -> {}); + } + + private WorldDraftRegionCommitService regionComponent() { + return new WorldDraftRegionCommitService( + new WorldDraftRegionCommitRepository(dsl, fence, mapper), manager, plan -> {}); + } + + private WorldDraftTerminalOutcomeService terminalService() { + return new WorldDraftTerminalOutcomeService(terminalRepository(), manager); + } + + private WorldDraftTerminalOutcomeRepository terminalRepository() { + return new WorldDraftTerminalOutcomeRepository(dsl, fence, mapper); + } + + private void freeze(Fixture f) { + OwnerBinding owner = f.owner(); + String request = "terminal-freeze-" + UUID.randomUUID(); + WorldDesignPublicationFenceEvidence evidence = + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + request, + "a".repeat(64), + 1, + "publish:" + owner.canonicalTenantId() + ":publish-request:" + request); + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, () -> new Checkpoint("synthetic-checkpoint", "b".repeat(64), 3))); + } + + private long count(String table, UUID requestId) { + var result = + Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM " + table + " WHERE request_id = ?", requestId), + "count query must return a row"); + return Objects.requireNonNull(result.get(0, Long.class), "count query must return a value"); + } + + private List regionEpochs(Fixture f) { + var aggregateRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT draft_revision_epoch FROM world_design_aggregate_epoch " + + "WHERE tenant_id = ? AND version_id = ? " + + "AND aggregate_type = 'REGION' AND aggregate_id = ?", + f.intake().localTenantKey(), + f.version().localVersionKey(), + f.seededRegion()), + "aggregate epoch row must exist"); + long aggregateEpoch = + Objects.requireNonNull(aggregateRow.get(0, Long.class), "aggregate epoch value must exist"); + var scopeRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT draft_scope_revision_epoch FROM world_design_scope_epoch " + + "WHERE tenant_id = ? AND version_id = ? " + + "AND scope_type = 'REGION_SUBTREE' AND scope_id = ?", + f.intake().localTenantKey(), + f.version().localVersionKey(), + Long.toString(f.seededRegion())), + "scope epoch row must exist"); + long scopeEpoch = + Objects.requireNonNull(scopeRow.get(0, Long.class), "scope epoch value must exist"); + return List.of(aggregateEpoch, scopeEpoch); + } + + private long draftRegionCount(Fixture f) { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM region WHERE tenant_id = ? AND version_id = ?", + f.intake().localTenantKey(), + f.version().localVersionKey()), + "region count query must return a row"); + return Objects.requireNonNull(row.get(0, Long.class), "region count must have a value"); + } + + private String retainedTerminalSourceFenceAndEpochSnapshot( + WorldDraftTerminalOperation operation) { + String snapshot = + Objects.requireNonNull( + dsl.fetchOne( + """ + SELECT jsonb_build_object( + 'intake', to_jsonb(intake), + 'identity', to_jsonb(version_identity), + 'owner', to_jsonb(owner_row), + 'terminal', (to_jsonb(terminal) - 'account_binding_bytes' - 'outcome_bytes') + || jsonb_build_object( + 'account_binding_bytes_hex', + encode(terminal.account_binding_bytes, 'hex'), + 'outcome_bytes_hex', encode(terminal.outcome_bytes, 'hex') + ), + 'aggregate_epochs', COALESCE(( + SELECT jsonb_agg( + to_jsonb(epoch) ORDER BY epoch.aggregate_type, epoch.aggregate_id + ) + FROM world_design_aggregate_epoch epoch + WHERE epoch.tenant_id = terminal.local_tenant_key + AND epoch.version_id = terminal.local_version_key + ), '[]'::jsonb), + 'scope_epochs', COALESCE(( + SELECT jsonb_agg( + to_jsonb(epoch) ORDER BY epoch.scope_type, epoch.scope_id + ) + FROM world_design_scope_epoch epoch + WHERE epoch.tenant_id = terminal.local_tenant_key + AND epoch.version_id = terminal.local_version_key + ), '[]'::jsonb) + )::text + FROM world_draft_terminal_outcome terminal + JOIN world_authored_version_identity version_identity + ON version_identity.operation_id = terminal.version_identity_operation_id + JOIN world_authored_source_intake intake + ON intake.operation_id = version_identity.intake_operation_id + JOIN world_design_publication_fence_owner owner_row + ON owner_row.target_namespace = terminal.target_namespace + AND owner_row.canonical_tenant_id = terminal.canonical_tenant_id + AND owner_row.local_tenant_key = terminal.local_tenant_key + AND owner_row.version_id = terminal.local_version_key + WHERE terminal.operation_id = ? + """, + operation.operationId()), + "retained World source/fence/outcome rows must exist") + .get(0, String.class); + return Objects.requireNonNull( + snapshot, "retained World source/fence/outcome snapshot must exist"); + } + + private void replaceV36TerminalGuardWithV37() { + String serviceSchema = + Objects.requireNonNull( + dsl.fetchOne("SELECT current_schema()"), "World service schema row must exist") + .get(0, String.class); + Objects.requireNonNull(serviceSchema, "World service schema must be selected"); + String v36Function = + migrationFunction( + "db/migration/V36__world_draft_terminal_outcomes.sql", + "CREATE FUNCTION world_reject_aborted_draft_attempt()") + .replaceFirst("^CREATE FUNCTION", "CREATE OR REPLACE FUNCTION") + .replace("${serviceSchema}", serviceSchema); + String v37Function = + migrationFunction( + "db/migration/V37__world_draft_terminal_guard_namespace.sql", + "CREATE OR REPLACE FUNCTION world_reject_aborted_draft_attempt()") + .replace("${serviceSchema}", serviceSchema); + + // PostgreSQL DDL is transactional: a failed V37 replacement rolls back the V36 body too. + ownerTransaction() + .executeWithoutResult( + status -> { + dsl.execute(v36Function); + dsl.execute(v37Function); + dsl.execute( + "REVOKE ALL ON FUNCTION world_reject_aborted_draft_attempt() FROM PUBLIC"); + }); + } + + private String migrationFunction(String resourceName, String declaration) { + try (InputStream resource = + WorldDraftTerminalOutcomePostgresIntegrationTest.class + .getClassLoader() + .getResourceAsStream(resourceName)) { + if (resource == null) { + throw new IllegalStateException("World migration resource is missing: " + resourceName); + } + String migration = new String(resource.readAllBytes(), StandardCharsets.UTF_8); + int start = migration.indexOf(declaration); + int end = start < 0 ? -1 : migration.indexOf("$$;", start); + if (start < 0 || end < 0) { + throw new IllegalStateException("World migration function is missing: " + declaration); + } + return migration.substring(start, end + "$$;".length()); + } catch (IOException exception) { + throw new IllegalStateException("Unable to read World migration: " + resourceName, exception); + } + } + + private long worldAbortedAttemptGuardFunctionOid() { + return Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT 'world_reject_aborted_draft_attempt()'::regprocedure::oid::bigint"), + "World aborted-attempt guard function row must exist") + .get(0, Long.class), + "World aborted-attempt guard function must exist"); + } + + private long worldAbortedAttemptGuardTriggerCount() { + return Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM pg_trigger " + + "WHERE tgfoid = 'world_reject_aborted_draft_attempt()'::regprocedure " + + "AND NOT tgisinternal"), + "World aborted-attempt guard trigger-count row must exist") + .get(0, Long.class), + "World aborted-attempt guard trigger count must exist"); + } + + private boolean worldAbortedAttemptGuardHasPublicExecute() { + return Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + """ + SELECT EXISTS ( + SELECT 1 + FROM pg_proc function_row + CROSS JOIN LATERAL aclexplode( + COALESCE(function_row.proacl, acldefault('f', function_row.proowner)) + ) acl_entry + WHERE function_row.oid = + 'world_reject_aborted_draft_attempt()'::regprocedure + AND acl_entry.grantee = 0 + AND acl_entry.privilege_type = 'EXECUTE' + ) + """), + "World aborted-attempt guard ACL row must exist") + .get(0, Boolean.class), + "World aborted-attempt guard ACL must be readable"); + } + + private String regionName(long regionId) { + var result = + Objects.requireNonNull( + dsl.fetchOne("SELECT name FROM region WHERE id = ?", regionId), + "region lookup must return a row"); + return Objects.requireNonNull(result.get(0, String.class), "region lookup must return a name"); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return transaction; + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new AssertionError(exception); + } + } + + private String digest(byte[] value) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Fixture timed out"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(exception); + } + } + + @FunctionalInterface + private interface ThrowingRunnable { + void run(); + } + + private record Race(boolean commitWon, boolean abortWon) {} + + private record ReadResult(ReadWorldDraftTerminalOutcomeResponse response, Throwable error) {} + + private static final class Collector + implements StreamObserver { + private ReadWorldDraftTerminalOutcomeResponse value; + private Throwable error; + + @Override + public void onNext(ReadWorldDraftTerminalOutcomeResponse response) { + value = response; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The test recorder retains the original throwable for assertion.") + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() {} + } + + private record OperationIds(UUID operation, UUID request, UUID commit, UUID fence, UUID actor) {} + + private record Fixture( + WorldAuthoredSourceIntakeReceipt intake, + WorldAuthoredVersionIdentityReceipt version, + OwnerBinding owner, + Long seededRegionId) { + long seededRegion() { + if (seededRegionId == null) { + throw new IllegalStateException("Fixture has no retained region"); + } + return seededRegionId; + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPostgresIntegrationTest.java new file mode 100644 index 0000000000..3f60f1c759 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPostgresIntegrationTest.java @@ -0,0 +1,1368 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +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.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +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.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +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; +import tools.jackson.databind.ObjectMapper; + +/** + * Synthetic source/permission fixtures prove component storage only, never authenticated APPLIED. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldDraftTopologyCommitPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final long GAME_DESIGN_VERSION = 9_000_000_000_000_001L; + + @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 DSLContext dsl; + @Autowired private PlatformTransactionManager manager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository fence; + @Autowired private ObjectMapper mapper; + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void allSixFamiliesAllocateTypedUuidRowsAndPreserveExactInputWithDefaults() { + Fixture f = fixture(); + var p = plan(f); + var e = component().store(p); + assertThat(e.binding()).isEqualTo(p.binding()); + assertThat(e.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + assertThat(count(f, "world_design_aggregate_epoch")).isEqualTo(7); + assertThat(count(f, "world_design_scope_epoch")).isEqualTo(1); + for (String t : + List.of("region", "zone", "room_exit", "generation_rule", "world_entity_spawn_binding")) { + assertThat(count(f, t)).isEqualTo(1); + } + assertThat(count(f, "room")).isEqualTo(2); + var nodes = p.graph().nodes(); + UUID logical = nodes.getLast().templateId(); + assertThat(nodes.stream().filter(n -> n.templateId().equals(logical)).toList()).hasSize(6); + for (var n : nodes) { + String family = + n.mutation().getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + assertThat(privateKey(p, family, n.templateId())).isPositive(); + assertThat(n.templateId().toString()).contains("-"); + } + assertThat( + dsl.resultQuery( + "SELECT spacing_multiplier FROM region WHERE tenant_id=?", + f.intake().localTenantKey()) + .fetchOne(0, Double.class)) + .isEqualTo(1.0); + assertThat( + dsl.resultQuery( + "SELECT cost FROM room_exit WHERE tenant_id=?", f.intake().localTenantKey()) + .fetchOne(0, Integer.class)) + .isEqualTo(1); + var spawn = nodes.getFirst().entityReference(); + var row = + dsl.resultQuery( + "SELECT * FROM world_entity_spawn_binding WHERE tenant_id=?", + f.intake().localTenantKey()) + .fetchOne(); + assertThat(row).isNotNull(); + assertThat(row.get("entity_template_id")).isNull(); + assertThat(row.get("entity_canonical_template_id", UUID.class)).isEqualTo(spawn.templateId()); + assertThat(row.get("entity_canonical_tenant_id", UUID.class)).isEqualTo(spawn.tenantId()); + assertThat(row.get("entity_canonical_version_id", UUID.class)).isEqualTo(spawn.versionId()); + assertThat(row.get("spawn_count", Integer.class)).isEqualTo(1); + assertThat(new String(e.graphBytes(), StandardCharsets.UTF_8)) + .contains( + "\"schemaVersion\":\"2\"", + "entity_canonical_template_id", + spawn.templateId().toString()); + assertThat(new String(e.resultBytes(), StandardCharsets.UTF_8)) + .contains(p.binding().digest(), "\"epoch\":\"1\"") + .doesNotContain("\"APPLIED\"", "permissionFenceReleased"); + // The retained numeric graph/v1 decoder must fail closed on canonical Entity UUID references. + assertThatThrownBy( + () -> + new WorldAuthoredGraphReader(dsl) + .readAndValidateGraph( + f.intake().localTenantKey(), f.version().localVersionKey())) + .hasMessageContaining("entity_template_id"); + // No canonical Entity private mapping or authenticated Account proof was manufactured. + assertThat( + dsl.resultQuery("SELECT count(*) FROM world_region_draft_execution_manifest") + .fetchOne(0, Long.class)) + .isZero(); + } + + @Test + void snakeCaseAndNumericEnumsStoreDefaultsAndRetainOriginalRawBindingAndRetry() + throws InvalidProtocolBufferException { + Fixture f = fixture(); + var printerPlan = plan(f); + var original = printerPlan.binding(); + List rawRevisions = new ArrayList<>(); + for (var revision : original.revisions()) { + String raw = revision.payload(); + if (revision.owner() == Owner.WORLD_MANAGEMENT) { + var node = + printerPlan.graph().nodes().stream() + .filter(n -> n.revisionId().equals(revision.revisionId())) + .findFirst() + .orElseThrow(); + raw = + JsonFormat.printer() + .preservingProtoFieldNames() + .printingEnumsAsInts() + .omittingInsignificantWhitespace() + .print(node.mutation()); + } + rawRevisions.add( + new DraftCommitBinding.RevisionPayload( + revision.revisionOrder(), revision.revisionId(), revision.owner(), raw)); + } + var rawBinding = + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + rawRevisions, + original.affectedUnits()); + var rawPlan = WorldDraftTopologyCommitPlan.create(rawBinding, printerPlan.ownerBinding()); + var rawFirst = rawBinding.revisions().get(1).payload(); + assertThat(rawFirst) + .contains( + "\"aggregate_type\":" + + rawPlan.graph().nodes().getFirst().mutation().getAggregateType().getNumber(), + "\"entity_template_type\":"); + var stored = component().store(rawPlan); + assertThat(stored.binding().canonicalBytes()).containsExactly(rawBinding.canonicalBytes()); + assertThat(stored.binding().digest()) + .isEqualTo(rawBinding.digest()) + .isNotEqualTo(original.digest()); + var history = + dsl.resultQuery( + "SELECT binding_json,binding_digest FROM world_topology_draft_commit WHERE request_id=?", + rawBinding.requestId()) + .fetchOne(); + assertThat(history).isNotNull(); + assertThat(history.get("binding_json", String.class)).isEqualTo(rawBinding.canonicalJson()); + assertThat(history.get("binding_digest", String.class)).isEqualTo(rawBinding.digest()); + assertThat( + dsl.resultQuery( + "SELECT spacing_multiplier FROM region WHERE tenant_id=?", + f.intake().localTenantKey()) + .fetchOne(0, Double.class)) + .isEqualTo(1.0); + assertThat( + dsl.resultQuery( + "SELECT cost FROM room_exit WHERE tenant_id=?", f.intake().localTenantKey()) + .fetchOne(0, Integer.class)) + .isEqualTo(1); + assertThat( + dsl.resultQuery( + "SELECT spawn_count FROM world_entity_spawn_binding WHERE tenant_id=?", + f.intake().localTenantKey()) + .fetchOne(0, Integer.class)) + .isEqualTo(1); + var retry = component().store(rawPlan); + assertThat(retry.resultBytes()).containsExactly(stored.resultBytes()); + assertThat(retry.graphBytes()).containsExactly(stored.graphBytes()); + var readback = + new WorldDraftTopologyCommitService(repository(), manager) + .readCommitted(rawPlan) + .orElseThrow(); + assertThat(readback.resultBytes()).containsExactly(stored.resultBytes()); + assertThat(readback.binding().revisions()).isEqualTo(rawRevisions); + assertThat(new String(stored.resultBytes(), StandardCharsets.UTF_8)) + .contains(rawBinding.digest()); + // Same parsed semantics with different raw bytes remains a changed complete operation. + rejectReplay(printerPlan); + assertThat(count(f, "world_topology_draft_commit")).isEqualTo(1); + } + + @Test + void alteredTrustedProjectionSemanticsRollBackAgainstOriginalParsedPlan() + throws InvalidProtocolBufferException { + Fixture f = fixture(); + var p = plan(f); + var tampered = + new WorldDraftTopologyCommitRepository(dsl, fence, mapper) { + @Override + List executionRevisions( + WorldDraftTopologyCommitPlan input) { + var revisions = new ArrayList<>(super.executionRevisions(input)); + var node = input.graph().nodes().getFirst(); + var changed = + node.mutation().toBuilder() + .setWorldEntitySpawnBinding( + node.mutation().getWorldEntitySpawnBinding().toBuilder().setSpawnCount(2)) + .build(); + var original = revisions.getFirst(); + revisions.set( + 0, + new DraftCommitBinding.RevisionPayload( + original.revisionOrder(), + original.revisionId(), + original.owner(), + json(changed))); + return revisions; + } + }; + assertThatThrownBy( + () -> new WorldDraftTopologyCommitService(tampered, manager, x -> {}).store(p)) + .hasMessageContaining("every exact payload field"); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_authored_topology_identity", + "world_design_aggregate_epoch", + "world_design_scope_epoch", + "world_topology_draft_commit")) { + assertThat(count(f, table)).as(table).isZero(); + } + assertThat(new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .isEmpty(); + component().store(p); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + } + + @Test + void lostAckAndIndependentFrozenReadbackReturnOriginalExactEvidence() { + Fixture f = fixture(); + var p = plan(f); + var denied = new WorldDraftTopologyCommitService(repository(), manager); + assertThat(denied.readCommitted(p)).isEmpty(); + var first = component().store(p); + var retry = component().store(p); + assertThat(retry.graphBytes()).containsExactly(first.graphBytes()); + assertThat(retry.resultBytes()).containsExactly(first.resultBytes()); + freeze(f); + var read = denied.readCommitted(p).orElseThrow(); + assertThat(read.graphBytes()).containsExactly(first.graphBytes()); + assertThat(read.resultBytes()).containsExactly(first.resultBytes()); + assertThat(component().store(p).resultBytes()).containsExactly(first.resultBytes()); + assertThat(count(f, "world_topology_draft_commit")).isEqualTo(1); + } + + @Test + void completeReplayRejectsChangedBasePayloadOrderAffectedAndSource() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + var b = p.binding(); + var changedBase = + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + b.target(), + b.requestId(), + b.commitId(), + b.baseCommitId() + "-changed", + b.revisions(), + b.affectedUnits()), + p.ownerBinding()); + rejectReplay(changedBase); + var t = b.target(); + var changedTarget = + new DraftCommitBinding.TargetProof( + t.canonicalTenantId(), + t.canonicalVersionId(), + t.gameDesignVersionRowId(), + t.gameDesignVersionTenantKey(), + t.sourceGameRowId() + 1, + t.sourceGameTenantKey(), + t.sourceProvenanceKind()); + rejectReplay( + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + changedTarget, + b.requestId(), + b.commitId(), + b.baseCommitId(), + b.revisions(), + b.affectedUnits()), + p.ownerBinding())); + var revisions = new ArrayList<>(b.revisions()); + var other = revisions.getFirst(); + revisions.set( + 0, + new DraftCommitBinding.RevisionPayload( + other.revisionOrder(), other.revisionId(), other.owner(), other.payload() + "changed")); + rejectReplay( + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + b.target(), + b.requestId(), + b.commitId(), + b.baseCommitId(), + revisions, + b.affectedUnits()), + p.ownerBinding())); + revisions = new ArrayList<>(b.revisions()); + var one = revisions.get(1); + var two = revisions.get(2); + revisions.set( + 1, + new DraftCommitBinding.RevisionPayload("1", two.revisionId(), two.owner(), two.payload())); + revisions.set( + 2, + new DraftCommitBinding.RevisionPayload("2", one.revisionId(), one.owner(), one.payload())); + rejectReplay( + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + b.target(), + b.requestId(), + b.commitId(), + b.baseCommitId(), + revisions, + b.affectedUnits()), + p.ownerBinding())); + assertThatThrownBy( + () -> + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + b.target(), + b.requestId(), + b.commitId(), + b.baseCommitId(), + b.revisions(), + b.affectedUnits().subList(1, b.affectedUnits().size())), + p.ownerBinding())) + .isInstanceOf(IllegalArgumentException.class); + var o = p.ownerBinding(); + var source = + new OwnerBinding( + o.targetNamespace(), + o.canonicalTenantId(), + o.canonicalVersionId(), + o.versionIdentityOperationId(), + o.gameDesignVersionId(), + o.intakeRequestId(), + o.intakeOperationId(), + o.intakeRequestDigest(), + UUID.randomUUID(), + o.sourceEvidenceDigest(), + o.intakeReceiptDigest()); + rejectReplay(WorldDraftTopologyCommitPlan.create(b, source)); + assertThat(count(f, "world_topology_draft_commit")).isEqualTo(1); + } + + private void rejectReplay(WorldDraftTopologyCommitPlan p) { + assertThatThrownBy(() -> component().store(p)) + .hasMessageContaining("changed full input or source"); + assertThatThrownBy( + () -> new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .hasMessageContaining("changed full input or source"); + } + + @Test + void lateFailureRollsBackAllFamiliesMappingsEpochsAndHistory() { + Fixture f = fixture(); + var p = plan(f); + var failing = + new WorldDraftTopologyCommitRepository(dsl, fence, mapper) { + @Override + WorldDraftTopologyCommitEvidence store(WorldDraftTopologyCommitPlan input) { + super.store(input); + throw new IllegalStateException("late complete result conflict"); + } + }; + assertThatThrownBy( + () -> new WorldDraftTopologyCommitService(failing, manager, x -> {}).store(p)) + .hasMessage("late complete result conflict"); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_authored_topology_identity", + "world_design_aggregate_epoch", + "world_design_scope_epoch", + "world_topology_draft_commit")) { + assertThat(count(f, table)).as(table).isZero(); + } + assertThat(new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .isEmpty(); + component().store(p); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + } + + @Test + void exactConcurrentFirstClaimReturnsOneOriginalResult() throws Exception { + Fixture f = fixture(); + var p = plan(f); + CountDownLatch begin = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future one = + executor.submit( + () -> { + await(begin); + return component().store(p); + }); + Future two = + executor.submit( + () -> { + await(begin); + return component().store(p); + }); + begin.countDown(); + var first = one.get(20, TimeUnit.SECONDS); + var second = two.get(20, TimeUnit.SECONDS); + assertThat(second.resultBytes()).containsExactly(first.resultBytes()); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + assertThat(count(f, "world_topology_draft_commit")).isEqualTo(1); + } finally { + begin.countDown(); + executor.shutdownNow(); + } + } + + @Test + void conflictingFirstClaimsCannotRemapPreviouslyAllocatedRows() throws Exception { + Fixture f = fixture(); + var first = plan(f); + var second = plan(f); + CountDownLatch begin = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future one = executor.submit(() -> contend(first, begin)); + Future two = executor.submit(() -> contend(second, begin)); + begin.countDown(); + assertThat(List.of(one.get(20, TimeUnit.SECONDS), two.get(20, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + assertThat(count(f, "world_topology_draft_commit")).isEqualTo(1); + } finally { + begin.countDown(); + executor.shutdownNow(); + } + } + + private boolean contend(WorldDraftTopologyCommitPlan p, CountDownLatch begin) { + await(begin); + try { + component().store(p); + return true; + } catch (RuntimeException exception) { + assertThat(exception).hasStackTraceContaining("conflicts with retained"); + return false; + } + } + + @Test + void freezeFirstDeniesAndWriterFirstSerializesFreezeUntilAtomicCommit() throws Exception { + Fixture frozen = fixture(); + freeze(frozen); + assertThatThrownBy(() -> component().store(plan(frozen))).hasMessageContaining("not open"); + assertThat(count(frozen, "world_authored_topology_identity")).isZero(); + Fixture f = fixture(); + var p = plan(f); + CountDownLatch locked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch freezing = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var paused = + new WorldDraftTopologyCommitRepository(dsl, fence, mapper) { + @Override + WorldDraftTopologyCommitEvidence store(WorldDraftTopologyCommitPlan input) { + var result = super.store(input); + locked.countDown(); + await(release); + return result; + } + }; + Future writer = + executor.submit( + () -> new WorldDraftTopologyCommitService(paused, manager, x -> {}).store(p)); + assertThat(locked.await(15, TimeUnit.SECONDS)).isTrue(); + Future freeze = + executor.submit( + () -> { + freezing.countDown(); + freeze(f); + }); + assertThat(freezing.await(15, TimeUnit.SECONDS)).isTrue(); + assertThat(freeze.isDone()).isFalse(); + assertThat(count(f, "region")).isZero(); + assertThat(count(f, "world_topology_draft_commit")).isZero(); + release.countDown(); + writer.get(20, TimeUnit.SECONDS); + freeze.get(20, TimeUnit.SECONDS); + assertThat(count(f, "world_authored_topology_identity")).isEqualTo(7); + assertThat(new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .isPresent(); + } finally { + release.countDown(); + executor.shutdownNow(); + } + } + + @Test + void ordinaryWritesMappedMovesEpochTamperAndTruncateStayDenied() { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + long tenant = f.intake().localTenantKey(); + long version = f.version().localVersionKey(); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding")) { + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + s -> + dsl.execute( + "INSERT INTO " + + table + + " SELECT (jsonb_populate_record(NULL::" + + table + + ",to_jsonb(t)||'{\"id\":-987654321}'::jsonb)).*" + + " FROM " + + table + + " t WHERE tenant_id=" + + tenant))) + .hasStackTraceContaining("no exact transaction execution manifest"); + for (String statement : + List.of( + "UPDATE " + table + " SET version=99 WHERE tenant_id=" + tenant, + "UPDATE " + table + " SET tenant_id=123456789 WHERE tenant_id=" + tenant, + "DELETE FROM " + table + " WHERE tenant_id=" + tenant, + "TRUNCATE " + table)) { + assertThatThrownBy(() -> ownerTransaction().execute(s -> dsl.execute(statement))) + .isInstanceOf(RuntimeException.class); + } + } + for (String statement : + List.of( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('unmanifested'," + + tenant + + "," + + version + + ")", + "UPDATE world_design_aggregate_epoch SET draft_revision_epoch=99 WHERE tenant_id=" + + tenant, + "DELETE FROM world_design_scope_epoch WHERE tenant_id=" + tenant, + "UPDATE world_authored_topology_identity SET private_row_key=999 WHERE tenant_id=" + + tenant, + "DELETE FROM world_authored_topology_identity WHERE tenant_id=" + tenant, + "TRUNCATE world_authored_topology_identity", + "TRUNCATE world_topology_draft_commit", + "TRUNCATE world_design_aggregate_epoch", + "TRUNCATE world_design_scope_epoch")) { + assertThatThrownBy(() -> ownerTransaction().execute(s -> dsl.execute(statement))) + .isInstanceOf(RuntimeException.class); + } + assertThat(new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .isPresent(); + } + + @Test + void staleOrWrongInsertManifestCannotAuthorizeOrdinaryFreshRows() { + Fixture f = fixture(); + var p = plan(f); + ownerTransaction() + .execute( + s -> { + fence.lockOpen(f.owner()); + return null; + }); + for (boolean stale : List.of(true, false)) { + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + s -> { + dsl.execute( + "INSERT INTO world_region_draft_execution_manifest " + + "SELECT txid_current()+?,?,'region',987654321,'INSERT',?,?,?,?::jsonb,?::jsonb,NULL," + + "to_jsonb(jsonb_populate_record(NULL::region,'{\"id\":987654321,\"name\":\"expected\"}'::jsonb))", + stale ? 1 : 0, + p.binding().commitId(), + f.version().operationId(), + f.intake().localTenantKey(), + f.version().localVersionKey(), + mapper.writeValueAsString(f.owner()), + p.binding().canonicalJson()); + return dsl.execute( + "INSERT INTO region(id,name,tenant_id,version_id) VALUES (987654321,'wrong',?,?)", + f.intake().localTenantKey(), + f.version().localVersionKey()); + })) + .hasStackTraceContaining("no exact transaction execution manifest"); + } + assertThat(count(f, "region")).isZero(); + } + + @Test + void retainedRowsArePreservedUnmappedAndDenyFreshContent() { + Fixture f = fixture(); + var p = plan(f); + ownerTransaction() + .execute( + s -> { + dsl.execute("SET LOCAL session_replication_role='replica'"); + try { + dsl.execute( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('retained',?,?)", + f.intake().localTenantKey(), + f.version().localVersionKey()); + } finally { + dsl.execute("SET LOCAL session_replication_role='origin'"); + } + return null; + }); + assertOrigin(); + assertThatThrownBy(() -> component().store(p)) + .hasStackTraceContaining("conflicts with retained region"); + assertThat(count(f, "region")).isEqualTo(1); + assertThat(count(f, "world_authored_topology_identity")).isZero(); + assertThat(count(f, "world_topology_draft_commit")).isZero(); + } + + @Test + void deniedPermissionAndCallerTransactionCannotClaimOrReadOwnerStorage() { + Fixture f = fixture(); + var p = plan(f); + var denied = new WorldDraftTopologyCommitService(repository(), manager); + assertThatThrownBy(() -> denied.store(p)).hasMessageContaining("permission is unavailable"); + assertThatThrownBy(() -> ownerTransaction().execute(s -> component().store(p))) + .hasMessageContaining("existing transaction"); + assertThatThrownBy(() -> ownerTransaction().execute(s -> denied.readCommitted(p))) + .hasMessageContaining("no active caller transaction"); + assertThat(count(f, "world_authored_topology_identity")).isZero(); + assertThat( + dsl.resultQuery( + "SELECT count(*) FROM world_design_publication_fence_owner WHERE local_tenant_key=?", + f.intake().localTenantKey()) + .fetchOne(0, Long.class)) + .isZero(); + } + + @Test + void v29ToV30PreservesNumericRowsSourceEpochsAndOriginalRegionHistory() throws Exception { + Fixture f = fixture(); + long region = + Objects.requireNonNull( + ownerTransaction() + .execute( + s -> { + dsl.execute("SET LOCAL session_replication_role='replica'"); + try { + long r = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO region(name,tenant_id,version_id) VALUES ('retained',?,?) RETURNING id", + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetchOne(0, Long.class), + "Missing returned region fixture key"); + long z = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO zone(region_id,name,tenant_id,version_id) VALUES (?,'zone',?,?) RETURNING id", + r, + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetchOne(0, Long.class), + "Missing returned zone fixture key"); + long room = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO room(zone_id,name,tenant_id,version_id) VALUES (?,'room',?,?) RETURNING id", + z, + f.intake().localTenantKey(), + f.version().localVersionKey()) + .fetchOne(0, Long.class), + "Missing returned room fixture key"); + dsl.execute( + "INSERT INTO room_exit(tenant_id,version_id,from_room_id,to_room_id) VALUES (?,?,?,?)", + f.intake().localTenantKey(), + f.version().localVersionKey(), + room, + room); + dsl.execute( + "INSERT INTO generation_rule(tenant_id,version_id,name,scope_type,scope_id,value) VALUES (?,?,'rule','REGION_SUBTREE',?,'seeded')", + f.intake().localTenantKey(), + f.version().localVersionKey(), + Long.toString(r)); + dsl.execute( + "INSERT INTO world_entity_spawn_binding(tenant_id,version_id,room_id,entity_template_type,entity_template_id) VALUES (?,?,?,'NPC',123)", + f.intake().localTenantKey(), + f.version().localVersionKey(), + room); + return r; + } finally { + dsl.execute("SET LOCAL session_replication_role='origin'"); + } + })); + UUID commit = UUID.randomUUID(); + UUID revision = UUID.randomUUID(); + var mutation = + WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(revision.toString()) + .setAggregateId(Long.toString(region)) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(Long.toString(region)) + .setRegion(RegionDesignMutation.newBuilder().setName("retained-v29")) + .build(); + var source = f.intake().source(); + var target = + new DraftCommitBinding.TargetProof( + f.owner().canonicalTenantId(), + f.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + source.sourceGameTenantKey(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + commit, + "retained-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", revision, Owner.WORLD_MANAGEMENT, json(mutation))), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + Long.toString(region), + "AGGREGATE", + Long.toString(region), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + Long.toString(region), + "REGION_SUBTREE", + Long.toString(region), + "0"))); + var retainedPlan = WorldDraftRegionCommitPlan.create(binding, f.owner()); + var prior = + new WorldDraftRegionCommitService( + new WorldDraftRegionCommitRepository(dsl, fence, mapper), manager, x -> {}) + .store(retainedPlan); + String schema = "uuid_upgrade_" + UUID.randomUUID().toString().replace("-", ""); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("29")) + .load() + .migrate(); + try (Connection connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + connection.setSchema(schema); + DSLContext retained = DSL.using(connection, SQLDialect.POSTGRES); + connection.setAutoCommit(false); + retained.execute("SET LOCAL session_replication_role='replica'"); + List sourceTables = + List.of( + "world_authored_source_tenant_association", + "world_authored_source_tenant_key_reservation", + "world_authored_source_intake", + "world_authored_version_identity", + "world_design_publication_fence_owner", + "world_region_draft_commit"); + List contentTables = + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding", + "world_design_aggregate_epoch", + "world_design_scope_epoch"); + try { + for (String table : sourceTables) { + String key = + table.equals("world_authored_source_tenant_key_reservation") + ? "tenant_key" + : "local_tenant_key"; + String override = + table.equals("world_authored_version_identity") ? " OVERRIDING SYSTEM VALUE" : ""; + retained.execute( + "INSERT INTO " + + table + + override + + " SELECT * FROM world_management_service." + + table + + " WHERE " + + key + + "=?", + f.intake().localTenantKey()); + } + for (String table : contentTables) { + if (table.equals("world_entity_spawn_binding")) { + retained.execute( + "INSERT INTO world_entity_spawn_binding (id,tenant_id,version_id,room_id,entity_template_type,entity_template_id,spawn_count,respawn_delay_seconds,version) " + + "SELECT id,tenant_id,version_id,room_id,entity_template_type,entity_template_id,spawn_count,respawn_delay_seconds,version " + + "FROM world_management_service.world_entity_spawn_binding WHERE tenant_id=?", + f.intake().localTenantKey()); + } else { + retained.execute( + "INSERT INTO " + + table + + " SELECT * FROM world_management_service." + + table + + " WHERE tenant_id=?", + f.intake().localTenantKey()); + } + } + retained.execute("SET LOCAL session_replication_role='origin'"); + connection.commit(); + } catch (RuntimeException exception) { + connection.rollback(); + throw exception; + } + connection.setAutoCommit(true); + List all = new ArrayList<>(sourceTables); + all.addAll(contentTables); + Map> before = retainedState(retained, all); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + Map> after = retainedState(retained, all); + assertThat(after).isEqualTo(before); + assertThat( + retained + .resultQuery("SELECT count(*) FROM world_authored_topology_identity") + .fetchOne(0, Long.class)) + .isZero(); + assertThat( + retained + .resultQuery("SELECT entity_template_id FROM world_entity_spawn_binding") + .fetchOne(0, Long.class)) + .isEqualTo(123); + assertThat( + retained + .resultQuery( + "SELECT entity_canonical_template_id FROM world_entity_spawn_binding") + .fetchOne(0, UUID.class)) + .isNull(); + assertThat( + retained + .resultQuery("SELECT result_bytes FROM world_region_draft_commit") + .fetchOne(0, byte[].class)) + .containsExactly(prior.resultBytes()); + assertThatThrownBy(() -> retained.execute("UPDATE region SET name='denied'")) + .isInstanceOf(RuntimeException.class); + } finally { + dsl.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private Map> retainedState(DSLContext db, List tables) { + Map> state = new LinkedHashMap<>(); + for (String table : tables) { + String projection = + table.equals("world_entity_spawn_binding") + ? "to_jsonb(t)-'entity_canonical_tenant_id'-'entity_canonical_version_id'-'entity_canonical_template_id'" + : "to_jsonb(t)"; + state.put( + table, + db.resultQuery( + "SELECT (" + + projection + + ")::text FROM " + + table + + " t ORDER BY (" + + projection + + ")::text") + .fetch(0, String.class)); + } + return state; + } + + @Test + void immutableHistoryAndEveryStoredPayloadAreVerifiedOnIndependentReadback() { + for (String corrupt : + List.of( + "UPDATE region SET weather='tampered'", + "UPDATE zone SET name='tampered'", + "UPDATE room SET description_localized_variants_json='tampered'", + "UPDATE room_exit SET cost=19", + "UPDATE generation_rule SET value='tampered'", + "UPDATE world_entity_spawn_binding SET entity_canonical_template_id='" + + UUID.randomUUID() + + "'", + "UPDATE world_authored_topology_identity SET revision_order='99'", + "UPDATE world_design_aggregate_epoch SET draft_revision_epoch=2", + "UPDATE world_design_scope_epoch SET draft_scope_revision_epoch=2", + "UPDATE world_topology_draft_commit SET result_bytes='tampered'::bytea")) { + Fixture f = fixture(); + var p = plan(f); + component().store(p); + String column = + corrupt.contains("world_topology_draft_commit") ? "local_tenant_key" : "tenant_id"; + String statement = corrupt + " WHERE " + column + "=" + f.intake().localTenantKey(); + assertThatThrownBy(() -> dsl.execute(statement)).isInstanceOf(RuntimeException.class); + ownerTransaction() + .execute( + s -> { + dsl.execute("SET LOCAL session_replication_role='replica'"); + try { + dsl.execute(statement); + } finally { + dsl.execute("SET LOCAL session_replication_role='origin'"); + } + return null; + }); + assertOrigin(); + assertThatThrownBy( + () -> new WorldDraftTopologyCommitService(repository(), manager).readCommitted(p)) + .isInstanceOf(RuntimeException.class); + } + } + + private Fixture fixture() { + UUID tenant = UUID.randomUUID(); + UUID registration = UUID.randomUUID(); + UUID sourceOperation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + long sourceRow = Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + String sourceTenant = "gd-row-" + sourceRow; + String digest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, "Synthetic component world"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW", + evidenceDigest); + UUID intakeRequest = UUID.randomUUID(); + ownerTransaction() + .execute(status -> intakeRepository.acceptFresh(NAMESPACE, intakeRequest, source)); + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository.read(NAMESPACE, intakeRequest).orElseThrow(); + return Objects.requireNonNull( + ownerTransaction() + .execute( + status -> { + UUID canonicalVersion = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + worldSlug, + sourceOperation, + evidenceDigest, + GAME_DESIGN_VERSION); + WorldAuthoredVersionIdentityReceipt version = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + tenant, + canonicalVersion, + version.operationId(), + GAME_DESIGN_VERSION, + intakeRequest, + intake.operationId(), + intake.requestDigest(), + sourceOperation, + evidenceDigest, + intake.receiptDigest()); + assertOrigin(); + return new Fixture(intake, version, owner); + })); + } + + private void freeze(Fixture f) { + OwnerBinding o = f.owner(); + String request = "freeze-" + UUID.randomUUID(); + WorldDesignPublicationFenceEvidence evidence = + new WorldDesignPublicationFenceEvidence( + o.targetNamespace(), + o.canonicalTenantId(), + o.canonicalVersionId(), + o.versionIdentityOperationId(), + o.gameDesignVersionId(), + o.intakeRequestId(), + o.intakeOperationId(), + o.intakeRequestDigest(), + o.sourceOperationId(), + o.sourceEvidenceDigest(), + o.intakeReceiptDigest(), + request, + "a".repeat(64), + 1, + "publish:" + o.canonicalTenantId() + ":publish-request:" + request); + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "synthetic-unverified-checkpoint", "b".repeat(64), 2))); + } + + private WorldDraftTopologyCommitPlan plan(Fixture f) { + UUID logical = UUID.randomUUID(); + UUID secondRoom = UUID.randomUUID(); + UUID entity = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + List values = new ArrayList<>(); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("region") + .setWeather("rain") + .setShardId(7) + .setGenerationSeed(9_007_199_254_740_999L) + .setGeneratorType("synthetic") + .setGeneratorParams("{\"seed\":1}")) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder().setName("zone").setRegionId(logical.toString())) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("room") + .setZoneId(logical.toString()) + .setDescription("description") + .setNameLocalizedVariantsJson("{\"en\":\"room\"}") + .setDescriptionLocalizedVariantsJson("{\"en\":\"description\"}")) + .build()); + values.add( + mutation( + commit, + secondRoom, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder().setName("second").setZoneId(logical.toString())) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(logical.toString()) + .setToRoomId(secondRoom.toString()) + .setDirection("NORTH")) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder().setName("rule").setValue("seeded")) + .build()); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(logical.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(entity.toString()) + .setRespawnDelaySeconds(17)) + .build()); + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + "synthetic opaque Entity input; existence and permission remain unverified")); + units.add( + new AffectedUnit( + Owner.ENTITY_MANAGEMENT, + "NPC", + entity.toString(), + "AGGREGATE", + entity.toString(), + "0")); + // Original input order deliberately places children before their parents. + for (var m : values.reversed()) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(m.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + json(m))); + String family = m.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "AGGREGATE", + m.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "REGION_SUBTREE", + m.getScopeId(), + "0")); + } + var s = f.intake().source(); + var target = + new DraftCommitBinding.TargetProof( + f.owner().canonicalTenantId(), + f.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + s.sourceGameTenantKey(), + s.sourceGameRowId(), + s.sourceGameTenantKey(), + s.provenanceKind()); + return WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + target, UUID.randomUUID(), commit, "retained-base", revisions, units), + f.owner()); + } + + private WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID id, UUID scope, WorldDesignAggregateType type) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(id.toString()) + .setAggregateType(type) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(scope.toString()); + } + + private WorldDraftTopologyCommitService component() { + return new WorldDraftTopologyCommitService( + repository(), + manager, + p -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertOrigin(); + // Synthetic local-storage fixture only; no Account permission or Entity existence proof. + }); + } + + private WorldDraftTopologyCommitRepository repository() { + return new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + } + + private TransactionTemplate ownerTransaction() { + TransactionTemplate tx = new TransactionTemplate(manager); + tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return tx; + } + + private void assertOrigin() { + assertThat( + dsl.resultQuery("SELECT current_setting('session_replication_role')") + .fetchOne(0, String.class)) + .isEqualTo("origin"); + } + + private long count(Fixture f, String table) { + String tenant = table.equals("world_topology_draft_commit") ? "local_tenant_key" : "tenant_id"; + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT count(*) FROM " + table + " WHERE " + tenant + "=?", + f.intake().localTenantKey()) + .fetchOne(0, Long.class)); + } + + private long privateKey(WorldDraftTopologyCommitPlan p, String family, UUID id) { + return Objects.requireNonNull( + dsl.resultQuery( + "SELECT private_row_key FROM world_authored_topology_identity " + + "WHERE request_id=? AND family=? AND template_id=?", + p.binding().requestId(), + family, + id) + .fetchOne(0, Long.class)); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new AssertionError(exception); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(15, TimeUnit.SECONDS)) throw new IllegalStateException("Fixture timed out"); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(exception); + } + } + + private record Fixture( + WorldAuthoredSourceIntakeReceipt intake, + WorldAuthoredVersionIdentityReceipt version, + OwnerBinding owner) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java new file mode 100644 index 0000000000..2f4e025238 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java @@ -0,0 +1,383 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.DriverManager; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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.entity.RegionInstance; +import net.firedevops.firemud.worldmanagement.entity.WorldInstance; +import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.JSONB; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +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.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL definition for World-owned operational region assignment persistence. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = {"spring.grpc.server.port=0", "firemud.smoke.seed-demo-runtime.enabled=false"}) +class WorldOperationalRegionAssignmentPostgresIntegrationTest { + @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 DSLContext dsl; + @Autowired private RegionInstanceRepository regionInstances; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + + @Test + void repositoryAllocatesFreshStableWorldIdentityAndDatabasePinsItsAssignedScope() { + Fixture fixture = fixture(); + RegionInstance candidate = candidate(fixture, "fresh-region"); + + RegionInstance inserted = regionInstances.save(candidate); + UUID operationalId = inserted.getOperationalRegionId(); + assertThat(candidate.getOperationalRegionId()).isNull(); + assertThat(operationalId).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(inserted.getOperationalRegionId()).isEqualTo(operationalId); + RegionInstance callerAssigned = candidate(fixture, "caller-assigned"); + callerAssigned.setOperationalRegionId(UUID.randomUUID()); + assertThatThrownBy(() -> regionInstances.save(callerAssigned)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("allocated by World"); + + var stored = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operational_region_id, canonical_region_instance_id " + + "FROM region_instance WHERE id = ?", + inserted.getId())); + assertThat(stored.get("operational_region_id", UUID.class)).isEqualTo(operationalId); + assertThat(stored.get("canonical_region_instance_id", UUID.class)).isNull(); + + inserted.setName("fresh-region-updated"); + RegionInstance updated = regionInstances.save(inserted); + assertThat(updated.getOperationalRegionId()).isEqualTo(operationalId); + + RegionInstance changedScope = regionInstances.findById(updated.getId()).orElseThrow(); + changedScope.setTenantId(fixture.tenantId() + 1); + assertThatThrownBy(() -> regionInstances.save(changedScope)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("assignment tuple is immutable"); + Fixture otherScope = fixture(); + for (String statement : + new String[] { + "UPDATE region_instance SET tenant_id = ? WHERE id = ?", + "UPDATE region_instance SET game_instance_id = ? WHERE id = ?", + "UPDATE region_instance SET world_instance_id = ? WHERE id = ?", + "UPDATE region_instance SET operational_region_id = ? WHERE id = ?" + }) { + Object replacement = + switch (statement) { + case "UPDATE region_instance SET tenant_id = ? WHERE id = ?" -> otherScope.tenantId(); + case "UPDATE region_instance SET game_instance_id = ? WHERE id = ?" -> + otherScope.gameInstanceId(); + case "UPDATE region_instance SET world_instance_id = ? WHERE id = ?" -> + otherScope.worldInstanceId(); + default -> UUID.randomUUID(); + }; + assertThatThrownBy(() -> dsl.execute(statement, replacement, updated.getId())) + .isInstanceOf(DataIntegrityViolationException.class) + .hasMessageContaining("operational assignment tuple is immutable"); + } + } + + @Test + void nullAssignmentIsNotRepairedAndV45KeepsPreparationFunctionClosed() { + Fixture fixture = fixture(); + long legacyId = insertRegionWithoutOperationalIdentity(fixture, "retained-legacy-region"); + + RegionInstance retained = regionInstances.findById(legacyId).orElseThrow(); + assertThat(retained.getOperationalRegionId()).isNull(); + retained.setName("retained-legacy-region-updated"); + RegionInstance updated = regionInstances.save(retained); + assertThat(updated.getOperationalRegionId()).isNull(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operational_region_id FROM region_instance WHERE id = ?", legacyId)) + .get("operational_region_id", UUID.class)) + .isNull(); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM flyway_schema_history_world_management_service " + + "WHERE version IN ('44', '45') AND success")) + .get(0, Long.class)) + .isEqualTo(2); + String prepareDefinition = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT pg_get_functiondef('world_management_service." + + "world_prepare_canonical_instance(text,text)'::regprocedure)")) + .get(0, String.class); + assertThat(prepareDefinition).contains("'operational_region_id', operational_runtime_uuid"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_proc p " + + "JOIN pg_namespace n ON n.oid = p.pronamespace " + + "CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) acl " + + "WHERE n.nspname = 'world_management_service' " + + "AND p.proname = 'world_prepare_canonical_instance' " + + "AND acl.grantee = 0 AND acl.privilege_type = 'EXECUTE')")) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void v44ToV45RetainsLegacyRegionAndPreparationOwnerFunctionIdentity() throws Exception { + String schema = "retained_operational_region_" + UUID.randomUUID().toString().replace("-", ""); + try { + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_world_management_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("44")) + .load() + .migrate(); + + long tenantId = 760_000L + Math.abs(UUID.randomUUID().getLeastSignificantBits() % 100_000L); + long gameInstanceId = + 761_000L + Math.abs(UUID.randomUUID().getLeastSignificantBits() % 100_000L); + UUID canonicalRegionId = UUID.randomUUID(); + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + DSLContext retained = DSL.using(connection, SQLDialect.POSTGRES); + retained.execute("SET search_path TO " + schema + ", public"); + long worldId = + Objects.requireNonNull( + retained.fetchOne( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, " + + "runtime_flags_json, generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, status) " + + "VALUES (?, ?, 71, ?, 'retained-descriptor', 83, '{}', 'retained-config', " + + "97, 'retained-release', 5, 'PREPARING') RETURNING id", + tenantId, + gameInstanceId, + "retained-region-" + UUID.randomUUID())) + .get("id", Long.class); + long regionId = + Objects.requireNonNull( + retained.fetchOne( + "INSERT INTO region_instance (tenant_id, game_instance_id, world_instance_id, " + + "shard_id, name, weather, generation_seed, generator_type, " + + "generator_params, spacing_multiplier, version, canonical_region_instance_id) " + + "VALUES (?, ?, ?, 3, 'retained-region', 'rain', 73, 'legacy', 'kept', " + + "1.25, 4, ?) RETURNING id", + tenantId, + gameInstanceId, + worldId, + canonicalRegionId)) + .get("id", Long.class); + assertThat(regionId).isPositive(); + String regionBefore = + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(r) AS row_json FROM region_instance r WHERE id = ?", + regionId)) + .get("row_json", JSONB.class) + .data(); + String worldBefore = + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(w) AS row_json FROM world_instance w WHERE id = ?", + worldId)) + .get("row_json", JSONB.class) + .data(); + var functionBefore = preparationFunction(retained, schema); + assertThat(functionBefore.body()) + .contains( + "Canonical preparation release differs from the exact selected frozen World graph", + "world_require_preparation_start_location", + "Canonical preparation requires the exact published V44 terminal"); + assertThat( + Objects.requireNonNull( + retained.fetchOne( + "SELECT count(*) FROM information_schema.columns " + + "WHERE table_schema = ? AND table_name = 'region_instance' " + + "AND column_name = 'operational_region_id'", + schema)) + .get(0, Long.class)) + .isZero(); + + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_world_management_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + var functionAfter = preparationFunction(retained, schema); + assertThat(functionAfter.oid()).isEqualTo(functionBefore.oid()); + assertThat(functionAfter.acl()).isEqualTo(functionBefore.acl()); + assertThat(functionAfter.body()) + .contains( + "Canonical preparation release differs from the exact selected frozen World graph", + "world_require_preparation_start_location", + "Canonical preparation requires the exact published V44 terminal", + "'operational_region_id', operational_runtime_uuid"); + assertThat(functionAfter.body()).isNotEqualTo(functionBefore.body()); + assertThat( + Objects.requireNonNull( + retained.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_proc p " + + "CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) acl " + + "WHERE p.oid = to_regprocedure(? || '.world_prepare_canonical_instance(text,text)') " + + "AND acl.grantee = 0 AND acl.privilege_type = 'EXECUTE')", + schema)) + .get(0, Boolean.class)) + .isFalse(); + + var retainedRegion = + Objects.requireNonNull( + retained.fetchOne( + "SELECT (to_jsonb(r) - 'operational_region_id') = ?::jsonb AS original_row, " + + "operational_region_id IS NULL AS unassigned, " + + "canonical_region_instance_id AS canonical_id " + + "FROM region_instance r WHERE id = ?", + regionBefore, + regionId)); + assertThat(retainedRegion.get("original_row", Boolean.class)).isTrue(); + assertThat(retainedRegion.get("unassigned", Boolean.class)).isTrue(); + assertThat(retainedRegion.get("canonical_id", UUID.class)).isEqualTo(canonicalRegionId); + assertThat( + Objects.requireNonNull( + retained.fetchOne( + "SELECT to_jsonb(w) = ?::jsonb FROM world_instance w WHERE id = ?", + worldBefore, + worldId)) + .get(0, Boolean.class)) + .isTrue(); + assertThat( + Objects.requireNonNull( + retained.fetchOne( + "SELECT count(*) FROM flyway_schema_history_world_management_service " + + "WHERE version IN ('40', '42', '44', '45') AND success")) + .get(0, Long.class)) + .isEqualTo(4); + } + } finally { + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())) { + DSL.using(connection, SQLDialect.POSTGRES).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + } + + private PreparationFunction preparationFunction(DSLContext dsl, String schema) { + var function = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT p.oid::bigint AS function_oid, p.proacl::text AS function_acl, " + + "pg_get_functiondef(p.oid) AS function_body FROM pg_proc p " + + "WHERE p.oid = to_regprocedure(? || '.world_prepare_canonical_instance(text,text)')", + schema)); + return new PreparationFunction( + function.get("function_oid", Long.class), + function.get("function_acl", String.class), + function.get("function_body", String.class)); + } + + private RegionInstance candidate(Fixture fixture, String name) { + RegionInstance region = new RegionInstance(); + region.setTenantId(fixture.tenantId()); + region.setGameInstanceId(fixture.gameInstanceId()); + WorldInstance world = new WorldInstance(); + world.setId(fixture.worldInstanceId()); + region.setWorldInstance(world); + region.setName(name); + return region; + } + + private long insertRegionWithoutOperationalIdentity(Fixture fixture, String name) { + return Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO region_instance " + + "(tenant_id, game_instance_id, world_instance_id, name) " + + "VALUES (?, ?, ?, ?) RETURNING id", + fixture.tenantId(), + fixture.gameInstanceId(), + fixture.worldInstanceId(), + name)) + .get("id", Long.class); + } + + private Fixture fixture() { + long tenantId = 740_000L + Math.abs(UUID.randomUUID().getLeastSignificantBits() % 100_000L); + long gameInstanceId = + 741_000L + Math.abs(UUID.randomUUID().getLeastSignificantBits() % 100_000L); + long worldInstanceId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " + + "control_plane_request_id, launch_descriptor_id, version_id, " + + "runtime_flags_json, generation_config_revision, release_bundle_id, " + + "published_release_bundle_ref, version_state_epoch, status) " + + "VALUES (?, ?, 71, ?, 'region-assignment-descriptor', 83, '{}', " + + "'region-assignment-config', 97, 'region-assignment-release', 5, 'PREPARING') " + + "RETURNING id", + tenantId, + gameInstanceId, + "region-assignment-" + UUID.randomUUID())) + .get("id", Long.class); + return new Fixture(tenantId, gameInstanceId, worldInstanceId); + } + + private record Fixture(long tenantId, long gameInstanceId, long worldInstanceId) {} + + private record PreparationFunction(Long oid, String acl, String body) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPreparationTestWorkloadPki.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPreparationTestWorkloadPki.java new file mode 100644 index 0000000000..3f501ca25f --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPreparationTestWorkloadPki.java @@ -0,0 +1,292 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; + +/** Ephemeral, test-only workload certificates for the physical World preparation adapter proof. */ +final class WorldPreparationTestWorkloadPki { + private static final String STORE_PASSWORD = "world-preparation-test-only"; + + private final Path caCertificate; + private final Path worldServerCertificate; + private final Path worldServerPrivateKey; + private final Path gameSessionCertificate; + private final Path gameSessionPrivateKey; + private final Path wrongWorkloadCertificate; + private final Path wrongWorkloadPrivateKey; + + private WorldPreparationTestWorkloadPki( + Path caCertificate, + Path worldServerCertificate, + Path worldServerPrivateKey, + Path gameSessionCertificate, + Path gameSessionPrivateKey, + Path wrongWorkloadCertificate, + Path wrongWorkloadPrivateKey) { + this.caCertificate = caCertificate; + this.worldServerCertificate = worldServerCertificate; + this.worldServerPrivateKey = worldServerPrivateKey; + this.gameSessionCertificate = gameSessionCertificate; + this.gameSessionPrivateKey = gameSessionPrivateKey; + this.wrongWorkloadCertificate = wrongWorkloadCertificate; + this.wrongWorkloadPrivateKey = wrongWorkloadPrivateKey; + } + + static WorldPreparationTestWorkloadPki create(Path directory) throws Exception { + Files.createDirectories(directory); + Path caStore = directory.resolve("test-ca.p12"); + Path caCertificate = directory.resolve("test-ca.crt"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD World preparation test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caCertificate.toString(), + "-rfc"); + + Identity server = + issueIdentity( + directory, caStore, caCertificate, "world-server", "world-management-service", true); + Identity gameSession = + issueIdentity( + directory, caStore, caCertificate, "game-session", "game-session-service", false); + Identity wrongWorkload = + issueIdentity( + directory, caStore, caCertificate, "wrong-workload", "game-design-service", false); + return new WorldPreparationTestWorkloadPki( + caCertificate, + server.certificate(), + server.privateKey(), + gameSession.certificate(), + gameSession.privateKey(), + wrongWorkload.certificate(), + wrongWorkload.privateKey()); + } + + Path caCertificate() { + return caCertificate; + } + + Path worldServerCertificate() { + return worldServerCertificate; + } + + Path worldServerPrivateKey() { + return worldServerPrivateKey; + } + + CommonGrpcClientProperties clientProperties(String workloadUri) throws Exception { + Path cert; + Path key; + if ("spiffe://firemud/ns/firemud/sa/game-session-service".equals(workloadUri)) { + cert = gameSessionCertificate; + key = gameSessionPrivateKey; + } else if ("spiffe://firemud/ns/firemud/sa/game-design-service".equals(workloadUri)) { + cert = wrongWorkloadCertificate; + key = wrongWorkloadPrivateKey; + } else { + throw new IllegalArgumentException("No test identity issued for " + workloadUri); + } + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(cert.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(caCertificate.toString()); + return properties; + } + + private static Identity issueIdentity( + Path directory, + Path caStore, + Path caCertificate, + String alias, + String serviceName, + boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + Path privateKey = directory.resolve(alias + ".key"); + String workloadUri = "spiffe://firemud/ns/firemud/sa/" + serviceName; + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String extendedKeyUsage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caCertificate.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + var key = (java.security.PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()); + var cert = keyStore.getCertificate(alias).getEncoded(); + writePem(certificate, "CERTIFICATE", cert); + writePem(privateKey, "PRIVATE KEY", key.getEncoded()); + return new Identity(certificate, privateKey); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Path outputFile = Files.createTempFile("firemud-world-preparation-keytool-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(outputFile.toFile()) + .start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(5, TimeUnit.SECONDS); + throw new IllegalStateException("keytool exceeded its 30-second test-fixture timeout"); + } + String output = Files.readString(outputFile, StandardCharsets.UTF_8); + if (process.exitValue() != 0) { + throw new IllegalStateException("keytool failed: " + output); + } + } finally { + Files.deleteIfExists(outputFile); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws Exception { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + private record Identity(Path certificate, Path privateKey) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadPostgresIntegrationTest.java new file mode 100644 index 0000000000..71fdd3264f --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadPostgresIntegrationTest.java @@ -0,0 +1,443 @@ +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.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityClient; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** + * Real World PostgreSQL exact-binding graph selection. The synchronized GD evidence and the + * component-store permission callback are explicit synthetic fixtures, not Account authorization or + * proof of a registered creator/write path. + */ +@Testcontainers(disabledWithoutDocker = true) +class WorldSynchronizedDraftTopologyReadPostgresIntegrationTest { + private static final String NAMESPACE = "world-draft-read-test"; + private static final long GAME_DESIGN_VERSION = 9_000_000_000_000_001L; + + @Container + static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine"); + + private static Fixture fixture; + + @BeforeAll + static void migrate() { + String schema = "world_sync_read_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_world_management_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(manager); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + // Match the production proxy's NOT_SUPPORTED source-intake reads inside owner transactions. + TransactionInterceptor intakeTransactions = new TransactionInterceptor(); + intakeTransactions.setTransactionManager(manager); + intakeTransactions.setTransactionAttributeSource(new AnnotationTransactionAttributeSource()); + ProxyFactory intakeProxy = new ProxyFactory(new WorldAuthoredSourceIntakeRepository(dsl)); + intakeProxy.setProxyTargetClass(true); + intakeProxy.addAdvice(intakeTransactions); + WorldAuthoredSourceIntakeRepository intakeRepository = + (WorldAuthoredSourceIntakeRepository) intakeProxy.getProxy(); + WorldDesignPublicationFenceRepository fence = + new WorldDesignPublicationFenceRepository(dsl, intakeRepository); + ObjectMapper mapper = new ObjectMapper(); + var repository = new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + fixture = new Fixture(dsl, transaction, manager, intakeRepository, fence, mapper, repository); + } + + @Test + void deniesArbitraryAppliedFixtureBytesEvenWhenOriginalGraphIsRetained() throws Exception { + Seed seed = fixture.seed(); + WorldDraftTopologyCommitPlan plan = fixture.plan(seed, UUID.randomUUID(), UUID.randomUUID()); + WorldDraftTopologyCommitService writerFixture = + new WorldDraftTopologyCommitService(fixture.repository(), fixture.manager(), ignored -> {}); + var stored = writerFixture.store(plan); + assertThat(stored.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + + // Simulate later unverified current content; synchronized normal reads must use retained bytes. + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role='replica'"); + fixture + .dsl() + .execute( + "UPDATE room SET name='later-unverified-room' WHERE tenant_id=? AND version_id=?", + seed.intake().localTenantKey(), + seed.version().localVersionKey()); + fixture.dsl().execute("SET LOCAL session_replication_role='origin'"); + }); + assertThat( + fixture + .dsl() + .resultQuery( + "SELECT name FROM room WHERE tenant_id=? AND version_id=?", + seed.intake().localTenantKey(), + seed.version().localVersionKey()) + .fetch(0, String.class)) + .contains("later-unverified-room"); + + var request = + new DraftSynchronizedVisibilityEvidence.Request( + 1, NAMESPACE, UUID.randomUUID(), plan.binding().target()); + DraftSynchronizedVisibilityEvidence evidence = evidence(request, plan.binding()); + DraftSynchronizedVisibilityClient client = mock(DraftSynchronizedVisibilityClient.class); + when(client.read(request)).thenReturn(evidence); + + assertThatThrownBy( + () -> + new WorldSynchronizedDraftTopologyReadService(client, fixture.repository()) + .read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no canonical World APPLIED-result carrier"); + } + + @Test + void missingCanonicalOwnerOutputNeverFallsBackToMutableCurrentWorldGraph() throws Exception { + Seed seed = fixture.seed(); + WorldDraftTopologyCommitPlan storedPlan = + fixture.plan(seed, UUID.randomUUID(), UUID.randomUUID()); + new WorldDraftTopologyCommitService(fixture.repository(), fixture.manager(), ignored -> {}) + .store(storedPlan); + + var unretainedBinding = + DraftCommitBinding.create( + storedPlan.binding().target(), + UUID.randomUUID(), + UUID.randomUUID(), + storedPlan.binding().baseCommitId(), + storedPlan.binding().revisions(), + storedPlan.binding().affectedUnits()); + var request = + new DraftSynchronizedVisibilityEvidence.Request( + 1, NAMESPACE, UUID.randomUUID(), unretainedBinding.target()); + DraftSynchronizedVisibilityClient client = mock(DraftSynchronizedVisibilityClient.class); + when(client.read(request)).thenReturn(evidence(request, unretainedBinding)); + + assertThatThrownBy( + () -> + new WorldSynchronizedDraftTopologyReadService(client, fixture.repository()) + .read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no canonical World APPLIED-result carrier"); + } + + private static DraftSynchronizedVisibilityEvidence evidence( + DraftSynchronizedVisibilityEvidence.Request request, DraftCommitBinding binding) { + List> epochs = new java.util.ArrayList<>(); + for (AffectedUnit unit : binding.affectedUnits(Owner.WORLD_MANAGEMENT)) { + Map epoch = new java.util.LinkedHashMap<>(); + epoch.put("aggregateType", unit.aggregateType()); + epoch.put("aggregateId", unit.aggregateId()); + epoch.put("scopeType", unit.scopeType()); + epoch.put("scopeId", unit.scopeId()); + epoch.put("expectedEpoch", unit.expectedEpoch()); + epoch.put( + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()).add(java.math.BigInteger.ONE).toString()); + epochs.add(epoch); + } + Map result = new java.util.LinkedHashMap<>(); + result.put("owner", Owner.WORLD_MANAGEMENT.name()); + result.put("status", "APPLIED"); + result.put("commitId", binding.commitId().toString()); + result.put("bindingDigest", binding.digest()); + // This synthetic identity/bytes pair is not a canonical World APPLIED-output carrier. + result.put("resultIdentity", "fixture-world-result"); + result.put( + "resultBytesBase64", + Base64.getEncoder() + .encodeToString("fixture-world-result-bytes".getBytes(StandardCharsets.UTF_8))); + result.put("appliedEpochs", epochs); + String vector = canonical(new ObjectMapper().writeValueAsString(List.of(result))); + return new DraftSynchronizedVisibilityEvidence( + request, + binding, + "SYNCHRONIZED", + new DraftSynchronizedVisibilityEvidence.Fence( + binding.requestId(), + binding.commitId(), + binding.digest(), + vector, + java.time.OffsetDateTime.parse("2026-10-06T00:00:00Z"))); + } + + private static WorldDesignMutationRevision mutation( + UUID commitId, + UUID revisionId, + UUID aggregateId, + WorldDesignAggregateType type, + UUID regionId) { + var builder = + WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revisionId.toString()) + .setCommitId(commitId.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(type) + .setAggregateId(aggregateId.toString()) + .setExpectedDraftRevisionEpoch(0) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(regionId.toString()) + .setExpectedDraftScopeRevisionEpoch(0) + .setScopeMutationPolicy( + WorldDesignScopeMutationPolicy.WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED); + return builder.build(); + } + + private static String canonical(String json) { + try { + return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + } catch (java.io.IOException exception) { + throw new AssertionError(exception); + } + } + + private record Seed( + AuthoredWorldSourceEvidence source, + WorldAuthoredSourceIntakeReceipt intake, + WorldAuthoredVersionIdentityReceipt version, + OwnerBinding owner) {} + + private record Fixture( + DSLContext dsl, + TransactionTemplate transaction, + org.springframework.transaction.PlatformTransactionManager manager, + WorldAuthoredSourceIntakeRepository intakeRepository, + WorldDesignPublicationFenceRepository fence, + ObjectMapper mapper, + WorldDraftTopologyCommitRepository repository) { + Seed seed() { + UUID tenant = UUID.randomUUID(); + UUID registration = UUID.randomUUID(); + UUID sourceOperation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + long sourceRow = Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + String sourceTenant = "gd-row-" + sourceRow; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, "Synthetic read world"); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + sourceOperation, + sourceRequestDigest, + tenant, + tenantSlug, + worldSlug, + "Synthetic read world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + sourceOperation, + sourceRequestDigest, + tenant, + tenantSlug, + worldSlug, + "Synthetic read world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW", + sourceEvidenceDigest); + UUID intakeRequestId = UUID.randomUUID(); + transaction.executeWithoutResult( + status -> intakeRepository.acceptFresh(NAMESPACE, intakeRequestId, source)); + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository.read(NAMESPACE, intakeRequestId).orElseThrow(); + UUID canonicalVersionId = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + worldSlug, + sourceOperation, + sourceEvidenceDigest, + GAME_DESIGN_VERSION); + WorldAuthoredVersionIdentityReceipt version = + transaction.execute( + status -> + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L))); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + tenant, + canonicalVersionId, + version.operationId(), + GAME_DESIGN_VERSION, + intakeRequestId, + intake.operationId(), + intake.requestDigest(), + sourceOperation, + sourceEvidenceDigest, + intake.receiptDigest()); + return new Seed(source, intake, version, owner); + } + + WorldDraftTopologyCommitPlan plan(Seed seed, UUID requestId, UUID commitId) throws Exception { + UUID region = UUID.randomUUID(); + UUID zone = UUID.randomUUID(); + UUID room = UUID.randomUUID(); + List mutations = + List.of( + mutation( + commitId, + UUID.randomUUID(), + region, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + region) + .toBuilder() + .setRegion( + RegionDesignMutation.newBuilder() + .setName("region") + .setWeather("rain") + .setGeneratorType("fixture")) + .build(), + mutation( + commitId, + UUID.randomUUID(), + zone, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + region) + .toBuilder() + .setZone( + ZoneDesignMutation.newBuilder() + .setName("zone") + .setRegionId(region.toString())) + .build(), + mutation( + commitId, + UUID.randomUUID(), + room, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + region) + .toBuilder() + .setRoom( + RoomDesignMutation.newBuilder() + .setName("original-room") + .setZoneId(zone.toString())) + .build()); + List revisions = new java.util.ArrayList<>(); + List units = new java.util.ArrayList<>(); + for (int index = 0; index < mutations.size(); index++) { + WorldDesignMutationRevision value = mutations.get(index); + String aggregateType = + value.getAggregateType().name().substring("WORLD_DESIGN_AGGREGATE_TYPE_".length()); + String scopeType = + value.getScopeType().name().substring("WORLD_DESIGN_SCOPE_TYPE_".length()); + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.fromString(value.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(value))); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + aggregateType, + value.getAggregateId(), + "AGGREGATE", + value.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + aggregateType, + value.getAggregateId(), + scopeType, + value.getScopeId(), + "0")); + } + DraftCommitBinding binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + seed.owner().canonicalTenantId(), + seed.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + seed.source().sourceGameTenantKey(), + seed.source().sourceGameRowId(), + seed.source().sourceGameTenantKey(), + seed.source().provenanceKind()), + requestId, + commitId, + "base-source-1", + revisions, + units); + return WorldDraftTopologyCommitPlan.create(binding, seed.owner()); + } + } +} diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationHoldProofTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationHoldProofTest.java new file mode 100644 index 0000000000..0edb0d8be4 --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationHoldProofTest.java @@ -0,0 +1,193 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.junit.jupiter.api.Test; + +/** Component comparison proof only; mocks here are not authenticated owner or database evidence. */ +class WorldCanonicalPlayerLocationHoldProofTest { + @Test + void bothTaggedOriginsRequireTheExactTypedFirstOpenOutcome() { + for (var origin : WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.values()) { + var fixture = + fixture( + origin, + origin == WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.EXPECT_CLOSED + ? 9L + : null); + assertThatCode(() -> fixture.verify(fixture.proof())).doesNotThrowAnyException(); + } + } + + @Test + void changedRealmAndNamespaceCannotUseAnotherHold() { + var fixture = + fixture(WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + when(fixture.request().realmId()).thenReturn(UUID.randomUUID()); + assertThatThrownBy(() -> fixture.verify(fixture.proof())) + .isInstanceOf(IllegalStateException.class); + when(fixture.request().realmId()) + .thenReturn(fixture.proof().holdIdentity().request().realmId()); + when(fixture.current().request().targetNamespace()).thenReturn("another-namespace"); + assertThatThrownBy(() -> fixture.verify(fixture.proof())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void changedProofDigestOrAuditCannotReplaceRetainedCommitEvidence() { + var fixture = + fixture(WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + when(fixture.request().initialAdmissionOwnerProofDigest()).thenReturn("d".repeat(64)); + assertThatThrownBy(() -> fixture.verify(fixture.proof())) + .isInstanceOf(IllegalStateException.class); + when(fixture.request().initialAdmissionOwnerProofDigest()).thenReturn("c".repeat(64)); + when(fixture.request().pointerAuditId()).thenReturn("100"); + assertThatThrownBy(() -> fixture.verify(fixture.proof())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void positiveAbortAndPendingNeverAuthorizeLocation() { + var fixture = + fixture(WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + var abort = + new GameSessionCanonicalInitialAdmissionOwnerProof( + fixture.proof().holdIdentity(), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + null, + null, + "sha256:" + "e".repeat(64), + true, + Instant.parse("2026-10-07T00:00:00Z")); + var pending = + new GameSessionCanonicalInitialAdmissionOwnerProof( + fixture.proof().holdIdentity(), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING, + null, + null, + null, + false, + null); + assertThatThrownBy(() -> fixture.verify(abort)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> fixture.verify(pending)).isInstanceOf(IllegalStateException.class); + } + + @Test + void expectClosedCannotSkipPointerVersionsOrOverflow() { + var fixture = + fixture(WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.EXPECT_CLOSED, 9L); + var jumped = + new GameSessionCanonicalInitialAdmissionOwnerProof( + fixture.proof().holdIdentity(), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 11L, + 99L, + fixture.proof().proofDigest(), + false, + fixture.proof().terminalAt()); + when(fixture.request().pointerVersion()).thenReturn(11L); + assertThatThrownBy(() -> fixture.verify(jumped)).isInstanceOf(IllegalStateException.class); + var overflow = + fixture( + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.EXPECT_CLOSED, + Long.MAX_VALUE); + assertThatThrownBy(() -> overflow.verify(overflow.proof())) + .isInstanceOf(ArithmeticException.class); + } + + private static Fixture fixture( + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin origin, Long prior) { + UUID tenant = UUID.randomUUID(); + UUID realm = UUID.randomUUID(); + UUID namespace = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + UUID version = UUID.randomUUID(); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + "world-hold-test", + tenant, + "starter-world", + realm, + namespace, + "SHARED", + instance, + version, + 7L, + "initial-request", + "b".repeat(64), + origin, + 3L, + prior); + var identity = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, UUID.randomUUID(), UUID.randomUUID()); + long pointer = prior == null ? 1L : prior == Long.MAX_VALUE ? 1L : prior + 1; + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + pointer, + 99L, + "sha256:" + "c".repeat(64), + false, + Instant.parse("2026-10-07T00:00:00Z")); + var selector = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(selector.targetNamespace()).thenReturn("world-hold-test"); + when(selector.canonicalVersionId()).thenReturn(version); + var current = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(current.request()).thenReturn(selector); + when(current.lifecycleEpoch()).thenReturn(7L); + var association = mock(WorldCanonicalInstanceAssociation.class); + when(association.identity()) + .thenReturn( + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + instance, + "world-hold-test", + tenant, + "starter-world", + namespace, + "SHARED", + true, + "launch-request")); + var request = mock(WorldCanonicalInitialPlayerLocation.Request.class); + when(request.initialAdmissionOrigin()) + .thenReturn( + WorldCanonicalInitialPlayerLocation.InitialAdmissionOrigin.valueOf(origin.name())); + when(request.initialAdmissionHoldId()).thenReturn(identity.holdId()); + when(request.initialAdmissionHoldFence()).thenReturn(identity.holdFence()); + when(request.canonicalTenantId()).thenReturn(tenant); + when(request.worldSlug()).thenReturn("starter-world"); + when(request.canonicalGameInstanceId()).thenReturn(instance); + when(request.realmId()).thenReturn(realm); + when(request.playableStateNamespaceId()).thenReturn(namespace); + when(request.playableStateScope()).thenReturn("SHARED"); + when(request.initialAdmissionRequestId()).thenReturn("initial-request"); + when(request.initialAdmissionRequestDigest()).thenReturn("b".repeat(64)); + when(request.catalogRevision()).thenReturn(3L); + when(request.initialAdmissionOwnerProofId()).thenReturn("initial-request"); + when(request.initialAdmissionOwnerProofDigest()).thenReturn("c".repeat(64)); + when(request.pointerAuditId()).thenReturn("99"); + when(request.pointerVersion()).thenReturn(pointer); + return new Fixture(request, current, association, proof); + } + + private record Fixture( + WorldCanonicalInitialPlayerLocation.Request request, + WorldCanonicalInstanceLifecycleEvidence current, + WorldCanonicalInstanceAssociation association, + GameSessionCanonicalInitialAdmissionOwnerProof proof) { + void verify(GameSessionCanonicalInitialAdmissionOwnerProof candidate) { + WorldCanonicalInitialPlayerLocationRepository.requireCommittedCanonicalHold( + request, current, association, candidate); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java index 0ddd055ab5..ec02a0e2bb 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java @@ -3,7 +3,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.entity.Room; +import net.firedevops.firemud.worldmanagement.entity.WorldEntitySpawnBinding; import net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository; import net.firedevops.firemud.worldmanagement.repository.RegionRepository; import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; @@ -114,8 +120,136 @@ void computesDigestFromVersionScopedTemplateRows() { assertEquals("1", digest.tenantId()); assertEquals("7", digest.scopeValue()); assertEquals("version:7", digest.appliedCommitId()); - assertEquals(2, digest.digestSchemaVersion()); + assertEquals(3, digest.digestSchemaVersion()); Mockito.verify(regionRepository).findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L); Mockito.verify(regionRepository, Mockito.never()).findByTenantIdOrderByIdAsc(Mockito.anyLong()); } + + @Test + void canonicalEntityReferenceMatchesExactSortedSerializationVector() throws Exception { + WorldEntitySpawnBinding binding = binding(); + canonicalReference(binding); + assertEquals( + vector( + "{\"kind\":\"CANONICAL_UUID\",\"templateId\":\"33333333-3333-4333-8333-333333333333\",\"tenantId\":\"11111111-1111-4111-8111-111111111111\",\"versionId\":\"22222222-2222-4222-8222-222222222222\"}"), + digest(binding)); + } + + @Test + void retainedEntityReferenceMatchesExactSortedSerializationVector() throws Exception { + WorldEntitySpawnBinding binding = binding(); + binding.setEntityTemplateId(Long.MAX_VALUE); + assertEquals( + vector("{\"kind\":\"RETAINED_PRIVATE_KEY\",\"templateId\":\"9223372036854775807\"}"), + digest(binding)); + } + + @Test + void eachCanonicalEntityUuidContributesToDigest() { + WorldEntitySpawnBinding binding = binding(); + canonicalReference(binding); + String original = digest(binding); + for (int field = 0; field < 3; field++) { + canonicalReference(binding); + UUID changed = UUID.fromString("44444444-4444-4444-8444-444444444444"); + if (field == 0) binding.setEntityCanonicalTenantId(changed); + if (field == 1) binding.setEntityCanonicalVersionId(changed); + if (field == 2) binding.setEntityCanonicalTemplateId(changed); + org.junit.jupiter.api.Assertions.assertNotEquals(original, digest(binding)); + } + } + + @Test + void rejectsMissingNilMixedAndNonpositiveEntityReferences() { + WorldEntitySpawnBinding binding = binding(); + assertThrows(IllegalStateException.class, () -> digest(binding)); + for (int field = 0; field < 3; field++) { + for (UUID invalid : new UUID[] {null, new UUID(0L, 0L)}) { + canonicalReference(binding); + if (field == 0) binding.setEntityCanonicalTenantId(invalid); + if (field == 1) binding.setEntityCanonicalVersionId(invalid); + if (field == 2) binding.setEntityCanonicalTemplateId(invalid); + assertThrows(IllegalStateException.class, () -> digest(binding)); + } + } + canonicalReference(binding); + binding.setEntityTemplateId(9L); + assertThrows(IllegalStateException.class, () -> digest(binding)); + binding.setEntityCanonicalTenantId(null); + binding.setEntityCanonicalVersionId(null); + binding.setEntityCanonicalTemplateId(null); + for (long invalid : new long[] {0L, -1L}) { + binding.setEntityTemplateId(invalid); + assertThrows(IllegalStateException.class, () -> digest(binding)); + } + } + + @Test + void repeatedDigestsHaveStableFieldOrder() { + WorldEntitySpawnBinding binding = binding(); + canonicalReference(binding); + String expected = digest(binding); + for (int attempt = 0; attempt < 20; attempt++) assertEquals(expected, digest(binding)); + } + + @Test + void applicationMapperSettingsCannotChangeSchema3Serialization() { + WorldEntitySpawnBinding binding = binding(); + canonicalReference(binding); + var configured = + tools.jackson.databind.json.JsonMapper.builder() + .enable(tools.jackson.databind.SerializationFeature.INDENT_OUTPUT) + .enable(tools.jackson.databind.SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS) + .build(); + assertEquals(digest(binding), digest(binding, configured)); + } + + private String digest(WorldEntitySpawnBinding binding) { + return digest(binding, new ObjectMapper()); + } + + private String digest(WorldEntitySpawnBinding binding, ObjectMapper mapper) { + var spawns = Mockito.mock(WorldEntitySpawnBindingRepository.class); + Mockito.when(spawns.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) + .thenReturn(List.of(binding)); + return new WorldDraftDesignDigestServiceImpl( + Mockito.mock(RegionRepository.class), + Mockito.mock(ZoneRepository.class), + Mockito.mock(RoomRepository.class), + Mockito.mock(RoomExitRepository.class), + Mockito.mock(GenerationRuleRepository.class), + spawns, + mapper) + .getDraftDesignDigest("1", "7") + .contentDigest(); + } + + private String vector(String entityReference) throws Exception { + String json = + "{\"regions\":[],\"zones\":[],\"rooms\":[],\"roomExits\":[],\"generationRules\":[],\"worldEntitySpawnBindings\":[{\"entityReference\":" + + entityReference + + ",\"entityTemplateType\":\"NPC\",\"id\":11,\"respawnDelaySeconds\":30,\"roomId\":5,\"spawnCount\":2}]}"; + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(json.getBytes(StandardCharsets.UTF_8))); + } + + private WorldEntitySpawnBinding binding() { + var binding = new WorldEntitySpawnBinding(); + var room = new Room(); + room.setId(5L); + binding.setId(11L); + binding.setRoom(room); + binding.setEntityTemplateType("NPC"); + binding.setSpawnCount(2); + binding.setRespawnDelaySeconds(30); + return binding; + } + + private void canonicalReference(WorldEntitySpawnBinding binding) { + binding.setEntityTemplateId(null); + binding.setEntityCanonicalTenantId(UUID.fromString("11111111-1111-4111-8111-111111111111")); + binding.setEntityCanonicalVersionId(UUID.fromString("22222222-2222-4222-8222-222222222222")); + binding.setEntityCanonicalTemplateId(UUID.fromString("33333333-3333-4333-8333-333333333333")); + } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java new file mode 100644 index 0000000000..36d5eaaa13 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java @@ -0,0 +1,502 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.Timestamp; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.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.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOrigin; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOwnerProofOutcome; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofResponse; +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 loopback mTLS proof against a transport-only Game Session owner-result double. */ +class GameSessionCanonicalInitialAdmissionOwnerClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String OTHER_NAMESPACE_URI = + "spiffe://firemud/ns/other-test/sa/game-session-service"; + private static final String WRONG_WORKLOAD_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final AtomicInteger CERTIFICATE_SERIAL = new AtomicInteger(1); + + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private GameSessionCanonicalInitialAdmissionOwnerClient client; + private AtomicInteger metadataCalls; + private AtomicInteger bodyCalls; + private ResponseMode responseMode; + + @BeforeAll + static void createTrustedCertificates() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeys = newRsaKeyPair(); + X500Name caName = new X500Name("CN=Canonical Initial Admission Test CA, O=FireMUD Test"); + X509Certificate ca = + issueCertificate(caName, caKeys.getPublic(), caName, caKeys.getPrivate(), true, null); + pki = + new TestPki( + ca, + issueLeaf(caName, caKeys.getPrivate(), GAME_SESSION_URI), + issueLeaf(caName, caKeys.getPrivate(), WRONG_WORKLOAD_URI), + issueLeaf(caName, caKeys.getPrivate(), OTHER_NAMESPACE_URI), + issueLeaf(caName, caKeys.getPrivate(), null), + issueLeaf(caName, caKeys.getPrivate(), WORLD_URI)); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void exactGameSessionServerReturnsCompleteCommittedProofForBothAcceptedOrigins() + throws Exception { + for (InitialAdmissionOrigin origin : InitialAdmissionOrigin.values()) { + startServer(pki.gameSessionServer(), ResponseMode.COMMITTED); + client = newClient(server); + client.init(); + HoldIdentity identity = identity(origin); + + var held = + client.verifyAndHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + try { + held.requireHeld(); + assertThat(held.proof().holdIdentity()).isEqualTo(identity); + assertThat(held.proof().outcome()) + .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(held.proof().committedPointerVersion()) + .isEqualTo(origin == InitialAdmissionOrigin.NO_PRIOR_POINTER ? 1L : 4L); + assertThat(held.proof().auditEventId()).isEqualTo(42L); + } finally { + held.close(); + } + assertThatThrownBy(held::requireHeld) + .isInstanceOf( + WorldCanonicalInitialAdmissionHoldFinalizationService.FinalizationDeniedException + .class); + assertThat(metadataCalls).hasValue(1); + assertThat(bodyCalls).hasValue(1); + stopTransport(); + } + } + + @Test + void positiveDurableAbortIsReturnedAsTerminalOwnerEvidence() throws Exception { + startServer(pki.gameSessionServer(), ResponseMode.ABORTED); + client = newClient(server); + client.init(); + HoldIdentity identity = identity(InitialAdmissionOrigin.EXPECT_CLOSED); + + var held = + client.verifyAndHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + try { + held.requireHeld(); + assertThat(held.proof().holdIdentity()).isEqualTo(identity); + assertThat(held.proof().outcome()) + .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + assertThat(held.proof().positiveDurableAbort()).isTrue(); + assertThat(held.proof().committedPointerVersion()).isNull(); + assertThat(held.proof().auditEventId()).isNull(); + } finally { + held.close(); + } + assertThatThrownBy(held::requireHeld) + .isInstanceOf( + WorldCanonicalInitialAdmissionHoldFinalizationService.FinalizationDeniedException + .class); + assertThat(metadataCalls).hasValue(1); + assertThat(bodyCalls).hasValue(1); + } + + @Test + void changedResponseIdentityAndChangedOutcomeAreRejected() throws Exception { + startServer(pki.gameSessionServer(), ResponseMode.SUBSTITUTED_REALM); + client = newClient(server); + client.init(); + HoldIdentity identity = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER); + + assertThatThrownBy( + () -> + client.verifyAndHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .isInstanceOf(IllegalStateException.class); + stopTransport(); + + startServer(pki.gameSessionServer(), ResponseMode.ABORTED); + client = newClient(server); + client.init(); + assertThatThrownBy( + () -> + client.verifyAndHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void sameCaWrongServiceNamespaceAndMissingUriServerCertificatesAreRejectedBeforeRequest() + throws Exception { + for (TestIdentity identity : + List.of( + pki.wrongWorkloadServer(), + pki.otherNamespaceServer(), + pki.missingWorkloadUriServer())) { + startServer(identity, ResponseMode.COMMITTED); + client = newClient(server); + client.init(); + HoldIdentity request = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER); + + assertThatThrownBy( + () -> + client.verifyAndHold( + request, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(metadataCalls).hasValue(0); + assertThat(bodyCalls).hasValue(0); + stopTransport(); + } + } + + @Test + void closedClientHandleCannotVerifyAnotherProof() throws Exception { + startServer(pki.gameSessionServer(), ResponseMode.COMMITTED); + client = newClient(server); + var identity = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER); + + assertThatThrownBy( + () -> + client.verifyAndHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .isInstanceOf(IllegalStateException.class); + client.init(); + client.close(); + assertThatThrownBy( + () -> + client.verifyAndHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .isInstanceOf(IllegalStateException.class); + assertThat(metadataCalls).hasValue(0); + assertThat(bodyCalls).hasValue(0); + } + + private enum ResponseMode { + COMMITTED, + ABORTED, + SUBSTITUTED_REALM + } + + private void startServer(TestIdentity identity, ResponseMode mode) throws Exception { + responseMode = mode; + metadataCalls = new AtomicInteger(); + bodyCalls = new AtomicInteger(); + var service = + new GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceImplBase() { + @Override + public void getCanonicalInitialAdmissionOwnerProof( + GetCanonicalInitialAdmissionOwnerProofRequest request, + StreamObserver observer) { + bodyCalls.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(WORLD_URI); + GetCanonicalInitialAdmissionOwnerProofResponse response = + responseFor(request, responseMode); + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countMetadata = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + metadataCalls.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countMetadata, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GameSessionCanonicalInitialAdmissionOwnerClient newClient(Server target) + throws IOException, CertificateEncodingException { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("localhost:" + target.getPort()); + return new GameSessionCanonicalInitialAdmissionOwnerClient( + endpoints, pki.clientProperties(tempDirectory), new GrpcChannelFactory(), NAMESPACE); + } + + private static GetCanonicalInitialAdmissionOwnerProofResponse responseFor( + GetCanonicalInitialAdmissionOwnerProofRequest request, ResponseMode mode) { + var builder = + GetCanonicalInitialAdmissionOwnerProofResponse.newBuilder() + .setTargetNamespace(request.getTargetNamespace()) + .setInitialAdmissionRequestId(request.getInitialAdmissionRequestId()) + .setInitialAdmissionRequestDigest(request.getInitialAdmissionRequestDigest()) + .setCanonicalTenantId(request.getCanonicalTenantId()) + .setWorldSlug(request.getWorldSlug()) + .setRealmId( + mode == ResponseMode.SUBSTITUTED_REALM + ? "ffffffff-ffff-4fff-8fff-ffffffffffff" + : request.getRealmId()) + .setPlayableStateNamespaceId(request.getPlayableStateNamespaceId()) + .setPlayableStateScope(request.getPlayableStateScope()) + .setCanonicalGameInstanceId(request.getCanonicalGameInstanceId()) + .setCanonicalVersionId(request.getCanonicalVersionId()) + .setActiveLifecycleEpoch(request.getActiveLifecycleEpoch()) + .setExpectedCatalogRevision(request.getExpectedCatalogRevision()) + .setOrigin(request.getOrigin()) + .setHoldId(request.getHoldId()) + .setHoldFence(request.getHoldFence()) + .setHoldBindingDigest(request.getHoldBindingDigest()) + .setProofDigest("sha256:" + "b".repeat(64)) + .setTerminalAt(Timestamp.newBuilder().setSeconds(1_791_331_200L)); + if (request.hasExpectedPriorPointerVersion()) { + builder.setExpectedPriorPointerVersion(request.getExpectedPriorPointerVersion()); + } + if (mode == ResponseMode.ABORTED) { + builder + .setOutcome( + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED) + .setPositiveDurableAbort(true); + } else { + builder + .setOutcome( + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED) + .setCommittedPointerVersion( + request.getOrigin() + == CanonicalInitialAdmissionOrigin + .CANONICAL_INITIAL_ADMISSION_ORIGIN_EXPECT_CLOSED + ? request.getExpectedPriorPointerVersion() + 1L + : 1L) + .setAuditEventId(42L); + } + return builder.build(); + } + + private static HoldIdentity identity(InitialAdmissionOrigin origin) { + var request = + new Request( + NAMESPACE, + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + "a".repeat(64), + origin, + 12L, + origin == InitialAdmissionOrigin.EXPECT_CLOSED ? 3L : null); + return new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + } + + private static TestIdentity issueLeaf( + X500Name caName, PrivateKey caPrivateKey, String workloadUri) throws Exception { + KeyPair keys = newRsaKeyPair(); + var names = + 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") + }; + X500Name subject = new X500Name("CN=FireMUD Test Workload, O=FireMUD Test"); + X509Certificate certificate = + issueCertificate( + subject, keys.getPublic(), caName, caPrivateKey, false, new GeneralNames(names)); + return new TestIdentity(keys.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); + var 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 static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameSessionServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity missingWorkloadUriServer, + TestIdentity worldClient) { + private CommonGrpcClientProperties clientProperties(Path directory) + throws IOException, CertificateEncodingException { + var properties = new CommonGrpcClientProperties(); + properties.setCertChain( + writePem( + directory.resolve("world-client.crt"), + "CERTIFICATE", + worldClient.certificate().getEncoded()) + .toString()); + properties.setPrivateKey( + writePem( + directory.resolve("world-client.key"), + "PRIVATE KEY", + worldClient.privateKey().getEncoded()) + .toString()); + properties.setCaCert( + writePem(directory.resolve("test-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()) + .toString()); + return properties; + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientTest.java new file mode 100644 index 0000000000..96a464b1d2 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientTest.java @@ -0,0 +1,175 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +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.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldFinalizationService.FinalizationDeniedException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Local lifecycle and guard checks using file-path and channel doubles; not physical TLS proof. */ +class GameSessionCanonicalInitialAdmissionOwnerClientTest { + private static final String NAMESPACE = "world-test"; + + @Test + void requiresExplicitInitializationAndClosePermanentlyDisablesTheClient(@TempDir Path directory) + throws Exception { + var client = client(directory, NAMESPACE); + HoldIdentity identity = identity(NAMESPACE); + try { + assertThrows( + FinalizationDeniedException.class, + () -> + client.verifyAndHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + + client.init(); + client.init(); + assertThrows( + FinalizationDeniedException.class, + () -> + client.verifyAndHold( + identity("other-world"), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + + client.close(); + assertThrows( + FinalizationDeniedException.class, + () -> + client.verifyAndHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + assertThrows(IllegalStateException.class, client::init); + } finally { + client.close(); + } + } + + @Test + void rejectsBothFormsOfAmbientTransactionBeforeAnyOwnerRead(@TempDir Path directory) + throws Exception { + var client = client(directory, NAMESPACE); + HoldIdentity identity = identity(NAMESPACE); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThrows( + FinalizationDeniedException.class, + () -> + client.verifyAndHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThrows( + FinalizationDeniedException.class, + () -> + client.verifyAndHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + } finally { + client.close(); + } + } + + @Test + void requiresReadableFileBackedMtlsConfiguration(@TempDir Path directory) throws Exception { + CommonGrpcClientProperties plaintext = fileBackedProperties(directory); + plaintext.setPlaintext(true); + assertThrows( + IllegalArgumentException.class, + () -> + new GameSessionCanonicalInitialAdmissionOwnerClient( + new ServiceEndpointsProperties(), plaintext, channelFactory(), NAMESPACE)); + + CommonGrpcClientProperties classpath = fileBackedProperties(directory); + classpath.setCertChain("classpath:cert.pem"); + assertThrows( + IllegalArgumentException.class, + () -> + new GameSessionCanonicalInitialAdmissionOwnerClient( + new ServiceEndpointsProperties(), classpath, channelFactory(), NAMESPACE)); + + CommonGrpcClientProperties missing = fileBackedProperties(directory); + missing.setPrivateKey(directory.resolve("missing-key.pem").toString()); + assertThrows( + IllegalArgumentException.class, + () -> + new GameSessionCanonicalInitialAdmissionOwnerClient( + new ServiceEndpointsProperties(), missing, channelFactory(), NAMESPACE)); + } + + private static GameSessionCanonicalInitialAdmissionOwnerClient client( + Path directory, String namespace) throws IOException { + return new GameSessionCanonicalInitialAdmissionOwnerClient( + new ServiceEndpointsProperties(), + fileBackedProperties(directory), + channelFactory(), + namespace); + } + + private static CommonGrpcClientProperties fileBackedProperties(Path directory) + throws IOException { + Path cert = Files.writeString(directory.resolve("client-cert.pem"), "test certificate path"); + Path key = Files.writeString(directory.resolve("client-key.pem"), "test private-key path"); + Path ca = Files.writeString(directory.resolve("ca-cert.pem"), "test CA path"); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(cert.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + + private static GrpcChannelFactory channelFactory() { + return new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + return mock(ManagedChannel.class); + } + }; + } + + private static HoldIdentity identity(String namespace) { + Request request = + new Request( + namespace, + uuid(1), + "test-world", + uuid(2), + uuid(3), + "SHARED", + uuid(4), + uuid(5), + 8L, + "canonical-admission-42", + "a".repeat(64), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 17L, + null); + return new HoldIdentity(request, uuid(6), uuid(7)); + } + + private static UUID uuid(long suffix) { + return UUID.fromString("00000000-0000-0000-0000-" + String.format("%012d", suffix)); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodecTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodecTest.java new file mode 100644 index 0000000000..1b489ed05b --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodecTest.java @@ -0,0 +1,352 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.google.protobuf.Timestamp; +import com.google.protobuf.UnknownFieldSet; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOrigin; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOwnerProofOutcome; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalInitialAdmissionOwnerProofResponse; +import org.junit.jupiter.api.Test; + +class GameSessionCanonicalInitialAdmissionOwnerGrpcCodecTest { + private static final String NAMESPACE = "world-test"; + private static final String REQUEST_ID = "canonical-admission-42"; + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String PROOF_DIGEST = "sha256:" + "b".repeat(64); + private static final Instant TERMINAL_AT = Instant.parse("2026-10-06T12:34:56.123456Z"); + + @Test + void requestCarriesCompleteIdentityAndPreservesTaggedOptionalPresence() { + HoldIdentity noPrior = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + GetCanonicalInitialAdmissionOwnerProofRequest noPriorRequest = + GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.toRequest(noPrior); + + assertEquals(NAMESPACE, noPriorRequest.getTargetNamespace()); + assertEquals(REQUEST_ID, noPriorRequest.getInitialAdmissionRequestId()); + assertEquals(REQUEST_DIGEST, noPriorRequest.getInitialAdmissionRequestDigest()); + assertEquals("00000000-0000-0000-0000-000000000001", noPriorRequest.getCanonicalTenantId()); + assertEquals("test-world", noPriorRequest.getWorldSlug()); + assertEquals("00000000-0000-0000-0000-000000000002", noPriorRequest.getRealmId()); + assertEquals( + "00000000-0000-0000-0000-000000000003", noPriorRequest.getPlayableStateNamespaceId()); + assertEquals("SHARED", noPriorRequest.getPlayableStateScope()); + assertEquals( + "00000000-0000-0000-0000-000000000004", noPriorRequest.getCanonicalGameInstanceId()); + assertEquals("00000000-0000-0000-0000-000000000005", noPriorRequest.getCanonicalVersionId()); + assertEquals(8L, noPriorRequest.getActiveLifecycleEpoch()); + assertEquals(17L, noPriorRequest.getExpectedCatalogRevision()); + assertEquals( + CanonicalInitialAdmissionOrigin.CANONICAL_INITIAL_ADMISSION_ORIGIN_NO_PRIOR_POINTER, + noPriorRequest.getOrigin()); + assertFalse(noPriorRequest.hasExpectedPriorPointerVersion()); + assertEquals(noPrior.holdId().toString(), noPriorRequest.getHoldId()); + assertEquals(noPrior.holdFence().toString(), noPriorRequest.getHoldFence()); + assertEquals(noPrior.holdBindingDigest(), noPriorRequest.getHoldBindingDigest()); + + HoldIdentity expectedClosed = identity(InitialAdmissionOrigin.EXPECT_CLOSED, 19L); + GetCanonicalInitialAdmissionOwnerProofRequest expectedClosedRequest = + GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.toRequest(expectedClosed); + assertEquals( + CanonicalInitialAdmissionOrigin.CANONICAL_INITIAL_ADMISSION_ORIGIN_EXPECT_CLOSED, + expectedClosedRequest.getOrigin()); + assertTrue(expectedClosedRequest.hasExpectedPriorPointerVersion()); + assertEquals(19L, expectedClosedRequest.getExpectedPriorPointerVersion()); + } + + @Test + void decodesCommittedOwnerProofForBothExactPointerSuccessors() { + for (var origin : InitialAdmissionOrigin.values()) { + Long prior = origin == InitialAdmissionOrigin.NO_PRIOR_POINTER ? null : 19L; + HoldIdentity identity = identity(origin, prior); + long expectedPointer = origin == InitialAdmissionOrigin.NO_PRIOR_POINTER ? 1L : 20L; + var proof = + GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.fromResponse( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + terminalResponse( + identity, + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED) + .setCommittedPointerVersion(expectedPointer) + .setAuditEventId(31L) + .setProofDigest(PROOF_DIGEST) + .build()); + + assertEquals(identity, proof.holdIdentity()); + assertEquals( + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, proof.outcome()); + assertEquals(expectedPointer, proof.committedPointerVersion()); + assertEquals(31L, proof.auditEventId()); + assertEquals(PROOF_DIGEST, proof.proofDigest()); + assertFalse(proof.positiveDurableAbort()); + assertEquals(TERMINAL_AT, proof.terminalAt()); + } + } + + @Test + void decodesPositiveDurableAbortWithoutPointerOrAuditEvidence() { + HoldIdentity identity = identity(InitialAdmissionOrigin.EXPECT_CLOSED, 19L); + var proof = + GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.fromResponse( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + terminalResponse( + identity, + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED) + .setProofDigest(PROOF_DIGEST) + .setPositiveDurableAbort(true) + .build()); + + assertEquals(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, proof.outcome()); + assertNull(proof.committedPointerVersion()); + assertNull(proof.auditEventId()); + assertTrue(proof.positiveDurableAbort()); + } + + @Test + void rejectsChangedOrMissingIdentityEchoAndWrongOptionalPresence() { + HoldIdentity identity = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + var outcome = + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED; + + assertInvalid( + identity, terminalResponse(identity, outcome).setWorldSlug("substituted-world").build()); + assertInvalid(identity, terminalResponse(identity, outcome).clearRealmId().build()); + assertInvalid( + identity, terminalResponse(identity, outcome).setExpectedPriorPointerVersion(1L).build()); + + HoldIdentity expectedClosed = identity(InitialAdmissionOrigin.EXPECT_CLOSED, 19L); + assertInvalid( + expectedClosed, + terminalResponse(expectedClosed, outcome).clearExpectedPriorPointerVersion().build()); + } + + @Test + void rejectsPendingUnsupportedAndSubstitutedTerminalOutcomes() { + HoldIdentity identity = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + assertInvalid( + identity, + terminalResponse( + identity, + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING) + .build()); + assertInvalid( + identity, + terminalResponse( + identity, + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING) + .setOutcomeValue(99) + .build()); + assertInvalid( + identity, + terminalResponse( + identity, + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED) + .setProofDigest(PROOF_DIGEST) + .setPositiveDurableAbort(true) + .build()); + } + + @Test + void rejectsInvalidCommitAndAbortSemantics() { + HoldIdentity identity = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + var committed = + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED; + var aborted = + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED; + + assertInvalid( + identity, + terminalResponse(identity, committed) + .setAuditEventId(31L) + .setProofDigest(PROOF_DIGEST) + .build()); + assertInvalid( + identity, + terminalResponse(identity, committed) + .setCommittedPointerVersion(2L) + .setAuditEventId(31L) + .setProofDigest(PROOF_DIGEST) + .build()); + assertInvalid( + identity, + terminalResponse(identity, committed) + .setCommittedPointerVersion(1L) + .setAuditEventId(31L) + .setProofDigest(PROOF_DIGEST) + .setPositiveDurableAbort(true) + .build()); + assertInvalid( + identity, + terminalResponse(identity, aborted) + .setCommittedPointerVersion(1L) + .setProofDigest(PROOF_DIGEST) + .setPositiveDurableAbort(true) + .build(), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + assertInvalid( + identity, + terminalResponse(identity, aborted).setProofDigest(PROOF_DIGEST).build(), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + + HoldIdentity overflow = identity(InitialAdmissionOrigin.EXPECT_CLOSED, Long.MAX_VALUE); + assertInvalid( + overflow, + terminalResponse(overflow, committed) + .setCommittedPointerVersion(Long.MIN_VALUE) + .setAuditEventId(31L) + .setProofDigest(PROOF_DIGEST) + .build()); + } + + @Test + void rejectsUnknownFieldsAndInvalidTimestampRangeOrPrecision() { + HoldIdentity identity = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + var committed = + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED; + var valid = + terminalResponse(identity, committed) + .setCommittedPointerVersion(1L) + .setAuditEventId(31L) + .setProofDigest(PROOF_DIGEST); + + assertInvalid(identity, valid.clone().setUnknownFields(unknownField()).build()); + assertInvalid( + identity, + valid + .clone() + .setTerminalAt(validTimestamp().toBuilder().setUnknownFields(unknownField())) + .build()); + assertInvalid( + identity, + valid.clone().setTerminalAt(Timestamp.newBuilder().setSeconds(253_402_300_800L)).build()); + assertInvalid( + identity, + valid + .clone() + .setTerminalAt( + Timestamp.newBuilder().setSeconds(TERMINAL_AT.getEpochSecond()).setNanos(-1)) + .build()); + assertInvalid( + identity, + valid + .clone() + .setTerminalAt( + Timestamp.newBuilder() + .setSeconds(TERMINAL_AT.getEpochSecond()) + .setNanos(TERMINAL_AT.getNano() + 1)) + .build()); + } + + private static void assertInvalid( + HoldIdentity identity, GetCanonicalInitialAdmissionOwnerProofResponse response) { + assertInvalid( + identity, response, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + } + + private static void assertInvalid( + HoldIdentity identity, + GetCanonicalInitialAdmissionOwnerProofResponse response, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome expectedOutcome) { + assertThrows( + IllegalArgumentException.class, + () -> + GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.fromResponse( + identity, expectedOutcome, response)); + } + + private static HoldIdentity identity(InitialAdmissionOrigin origin, Long priorPointerVersion) { + Request request = + new Request( + NAMESPACE, + uuid(1), + "test-world", + uuid(2), + uuid(3), + "SHARED", + uuid(4), + uuid(5), + 8L, + REQUEST_ID, + REQUEST_DIGEST, + origin, + 17L, + priorPointerVersion); + return new HoldIdentity(request, uuid(6), uuid(7)); + } + + private static GetCanonicalInitialAdmissionOwnerProofResponse.Builder terminalResponse( + HoldIdentity identity, CanonicalInitialAdmissionOwnerProofOutcome outcome) { + Request request = identity.request(); + var builder = + GetCanonicalInitialAdmissionOwnerProofResponse.newBuilder() + .setTargetNamespace(request.targetNamespace()) + .setInitialAdmissionRequestId(request.initialAdmissionRequestId()) + .setInitialAdmissionRequestDigest(request.initialAdmissionRequestDigest()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setRealmId(request.realmId().toString()) + .setPlayableStateNamespaceId(request.playableStateNamespaceId().toString()) + .setPlayableStateScope(request.playableStateScope()) + .setCanonicalGameInstanceId(request.canonicalGameInstanceId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setActiveLifecycleEpoch(request.activeLifecycleEpoch()) + .setExpectedCatalogRevision(request.expectedCatalogRevision()) + .setOrigin(toWireOrigin(request.initialAdmissionOrigin())) + .setHoldId(identity.holdId().toString()) + .setHoldFence(identity.holdFence().toString()) + .setHoldBindingDigest(identity.holdBindingDigest()) + .setOutcome(outcome) + .setTerminalAt(validTimestamp()); + if (request.expectedPriorPointerVersion() != null) { + builder.setExpectedPriorPointerVersion(request.expectedPriorPointerVersion()); + } + return builder; + } + + private static CanonicalInitialAdmissionOrigin toWireOrigin(InitialAdmissionOrigin origin) { + return switch (origin) { + case NO_PRIOR_POINTER -> + CanonicalInitialAdmissionOrigin.CANONICAL_INITIAL_ADMISSION_ORIGIN_NO_PRIOR_POINTER; + case EXPECT_CLOSED -> + CanonicalInitialAdmissionOrigin.CANONICAL_INITIAL_ADMISSION_ORIGIN_EXPECT_CLOSED; + }; + } + + private static Timestamp validTimestamp() { + return Timestamp.newBuilder() + .setSeconds(TERMINAL_AT.getEpochSecond()) + .setNanos(TERMINAL_AT.getNano()) + .build(); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static UUID uuid(long suffix) { + return UUID.fromString("00000000-0000-0000-0000-" + String.format("%012d", suffix)); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java new file mode 100644 index 0000000000..15bbf0f2e0 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java @@ -0,0 +1,162 @@ +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.List; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import org.junit.jupiter.api.Test; + +class WorldAuthoredGraphSnapshotTest { + private static final String DIGEST = "a".repeat(64); + + @Test + void acceptsRetainedSchema2AndCurrentSchema3ButRejectsUnsupportedSchemas() { + for (int schema : new int[] {2, 3}) + assertThat(request(schema).digestSchemaVersion()).isEqualTo(schema); + for (int schema : new int[] {0, 1, 4}) { + assertThatThrownBy(() -> request(schema)).isInstanceOf(IllegalArgumentException.class); + } + } + + private CaptureRequest request(int schema) { + return new CaptureRequest( + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "publish-request-1", + DIGEST, + 1L, + "publish:tenant:publish-request:publish-request-1", + "commit-1", + DIGEST, + schema, + List.of()); + } + + @Test + void captureRequestPreservesTypedEpochAndCanonicalizesTupleOrder() { + OwnedAffectedTuple scope = + new OwnedAffectedTuple( + "WORLD_MANAGEMENT", + "ROOM", + "9223372036854775806", + "ZONE_SUBTREE", + "9223372036854775805", + "9223372036854775807"); + OwnedAffectedTuple aggregate = + new OwnedAffectedTuple("WORLD_MANAGEMENT", "REGION", "4", "", "", "9"); + + CaptureRequest request = + new CaptureRequest( + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "publish-request-1", + DIGEST, + 1L, + "publish:tenant:publish-request:publish-request-1", + "commit-1", + DIGEST, + 2, + List.of(scope, aggregate)); + + assertThat(request.suppliedOwnedAffectedTuples()).containsExactly(aggregate, scope); + assertThat(scope.expectedEpoch()).isEqualTo("9223372036854775807"); + } + + @Test + void changedOrAmbiguousTupleDeclarationsAreRejected() { + assertThatThrownBy( + () -> new OwnedAffectedTuple("GAME_DESIGN", "ROOM", "1", "ZONE_SUBTREE", "2", "3")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new OwnedAffectedTuple("WORLD_MANAGEMENT", "ROOM", "1", "ZONE_SUBTREE", "2", "03")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new OwnedAffectedTuple("WORLD_MANAGEMENT", "ROOM", "1", "ZONE_SUBTREE", "", "3")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void sourceAndReceiptDigestsRetainTheirRequiredPrefix() { + assertThatThrownBy( + () -> + new WorldAuthoredGraphSnapshot( + UUID.randomUUID(), + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "world-one", + 1L, + 2L, + 3L, + (short) 1, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + DIGEST, + UUID.randomUUID(), + DIGEST, + "sha256:" + DIGEST, + UUID.randomUUID(), + "publish-request-1", + DIGEST, + 1L, + "publish:tenant:publish-request:publish-request-1", + "commit-1", + DIGEST, + 2, + DIGEST, + "[]", + "[]", + "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8), + DIGEST, + WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sourceEvidenceDigest"); + + assertThatThrownBy( + () -> + new WorldAuthoredGraphSnapshot( + UUID.randomUUID(), + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "world-one", + 1L, + 2L, + 3L, + (short) 1, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + DIGEST, + UUID.randomUUID(), + "sha256:" + DIGEST, + DIGEST, + UUID.randomUUID(), + "publish-request-1", + DIGEST, + 1L, + "publish:tenant:publish-request:publish-request-1", + "commit-1", + DIGEST, + 2, + DIGEST, + "[]", + "[]", + "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8), + DIGEST, + WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intakeReceiptDigest"); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java new file mode 100644 index 0000000000..279cd7ee30 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java @@ -0,0 +1,327 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshotRepository.SnapshotConflictException; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class WorldAuthoredGraphTest { + + @Test + void encodesTheExistingSixFamilySnapshotShapeAndFieldOrder() { + WorldAuthoredGraph graph = + new WorldAuthoredGraph( + List.of( + row( + "id", + 9_000_000_042L, + "shardId", + 3, + "name", + "Northern Reach", + "weather", + null, + "generationSeed", + Long.MIN_VALUE, + "generatorType", + null, + "generatorParams", + null, + "spacingMultiplier", + 1.0d)), + List.of( + row("id", 900_000_000_000_000_042L, "regionId", 9_000_000_042L, "name", "North")), + List.of( + row( + "id", + 8_000_000_000_000_000_042L, + "zoneId", + 900_000_000_000_000_042L, + "name", + "Keep", + "description", + null, + "nameLocalizedVariantsJson", + null, + "descriptionLocalizedVariantsJson", + "{\"en\":\"Keep\"}")), + List.of( + row( + "id", 7_000_000_000_000_000_042L, + "fromRoomId", 8_000_000_000_000_000_042L, + "toRoomId", 8_000_000_000_000_000_043L, + "direction", "north", + "cost", 2)), + List.of( + row( + "id", 6_000_000_000_000_000_042L, + "name", "weather-profile", + "scopeType", "REGION_SUBTREE", + "scopeId", "9", + "value", "{\"rain\":true}")), + List.of( + row( + "id", + 5_000_000_000_000_000_042L, + "roomId", + 8_000_000_000_000_000_042L, + "entityTemplateType", + "NPC", + "entityTemplateId", + 9_000_000_000_000_000_042L, + "spawnCount", + 4, + "respawnDelaySeconds", + 30))); + + assertThat(new String(graph.encode(new ObjectMapper()), StandardCharsets.UTF_8)) + .isEqualTo( + "{\"snapshotSchemaVersion\":1,\"regions\":[{\"id\":9000000042,\"shardId\":3," + + "\"name\":\"Northern Reach\",\"weather\":null,\"generationSeed\":-9223372036854775808," + + "\"generatorType\":null,\"generatorParams\":null,\"spacingMultiplier\":1.0}]," + + "\"zones\":[{\"id\":900000000000000042,\"regionId\":9000000042,\"name\":\"North\"}]," + + "\"rooms\":[{\"id\":8000000000000000042,\"zoneId\":900000000000000042," + + "\"name\":\"Keep\",\"description\":null,\"nameLocalizedVariantsJson\":null," + + "\"descriptionLocalizedVariantsJson\":\"{\\\"en\\\":\\\"Keep\\\"}\"}]," + + "\"roomExits\":[{\"id\":7000000000000000042,\"fromRoomId\":8000000000000000042," + + "\"toRoomId\":8000000000000000043,\"direction\":\"north\",\"cost\":2}]," + + "\"generationRules\":[{\"id\":6000000000000000042,\"name\":\"weather-profile\"," + + "\"scopeType\":\"REGION_SUBTREE\",\"scopeId\":\"9\"," + + "\"value\":\"{\\\"rain\\\":true}\"}]," + + "\"worldEntitySpawnBindings\":[{\"id\":5000000000000000042," + + "\"roomId\":8000000000000000042,\"entityTemplateType\":\"NPC\"," + + "\"entityTemplateId\":9000000000000000042,\"spawnCount\":4," + + "\"respawnDelaySeconds\":30}]}"); + } + + @Test + void deeplyCopiesNestedRowsCollectionsAndByteArrays() { + byte[] suppliedBytes = {1, 2, 3}; + List suppliedItems = new ArrayList<>(List.of("before", suppliedBytes)); + Map suppliedNested = new LinkedHashMap<>(); + suppliedNested.put("items", suppliedItems); + Map suppliedRow = new LinkedHashMap<>(); + suppliedRow.put("id", 7L); + suppliedRow.put("extension", suppliedNested); + WorldAuthoredGraph graph = + new WorldAuthoredGraph( + List.of(), List.of(suppliedRow), List.of(), List.of(), List.of(), List.of()); + + suppliedItems.set(0, "after"); + suppliedBytes[0] = 9; + Map nested = (Map) graph.zones().getFirst().get("extension"); + List items = (List) nested.get("items"); + byte[] exposedBytes = (byte[]) items.get(1); + exposedBytes[0] = 8; + + assertThat(items.getFirst()).isEqualTo("before"); + Map freshNested = (Map) graph.zones().getFirst().get("extension"); + List freshItems = (List) freshNested.get("items"); + assertThat((byte[]) freshItems.get(1)).containsExactly((byte) 1, (byte) 2, (byte) 3); + assertThatThrownBy(() -> graph.zones().getFirst().put("newField", true)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(items::clear).isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void decodesAndReencodesTheCanonicalSixFamilyGraphWithoutLosingNumericValues() { + ObjectMapper objectMapper = new ObjectMapper(); + byte[] encoded = completeGraph().encode(objectMapper); + + WorldAuthoredGraph decoded = WorldAuthoredGraph.decode(encoded, objectMapper); + + assertThat(decoded.encode(objectMapper)).containsExactly(encoded); + assertThat(decoded.regions()) + .extracting(row -> row.get("generationSeed")) + .containsExactly(Long.MIN_VALUE, Long.MAX_VALUE); + assertThat(decoded.regions().getFirst().get("id")).isEqualTo(Long.MAX_VALUE); + assertThat(decoded.regions().getFirst().get("spacingMultiplier")) + .isInstanceOf(Double.class) + .isEqualTo(0.125d); + assertThat(decoded.zones().getFirst().get("id")).isEqualTo(9_007_199_254_740_993L); + assertThat(decoded.rooms().getFirst().get("description")).isNull(); + assertThat(decoded.generationRules().getFirst().get("scopeId")).isNull(); + assertThat(decoded.spawnBindings().getFirst().get("entityTemplateId")) + .isEqualTo(9_007_199_254_740_999L); + } + + @Test + void rejectsMalformedRootFamiliesAndUnknownOrNoncanonicalSnapshots() { + ObjectMapper objectMapper = new ObjectMapper(); + String emptyGraph = + new String( + new WorldAuthoredGraph(List.of(), List.of(), List.of(), List.of(), List.of(), List.of()) + .encode(objectMapper), + StandardCharsets.UTF_8); + List invalidSnapshots = + List.of( + emptyGraph.replace("\"snapshotSchemaVersion\":1", "\"snapshotSchemaVersion\":2"), + emptyGraph.replace(",\"regions\":[]", ""), + emptyGraph.replace("\"zones\":[]", "\"unknown\":true,\"zones\":[]"), + emptyGraph.replace("\"regions\":[]", "\"regions\":{}"), + emptyGraph.replace("\"zones\":[]", "\"regions\":[],\"zones\":[]"), + " " + emptyGraph, + emptyGraph + " {}", + emptyGraph.replace(",\"zones\":[]", ",\"regions\":[],\"zones\":[]")); + + for (String invalidSnapshot : invalidSnapshots) { + assertThatThrownBy( + () -> + WorldAuthoredGraph.decode( + invalidSnapshot.getBytes(StandardCharsets.UTF_8), objectMapper)) + .isInstanceOf(SnapshotConflictException.class); + } + assertThatThrownBy( + () -> WorldAuthoredGraph.decode(new byte[] {'{', '}', (byte) 0xc3, 0x28}, objectMapper)) + .isInstanceOf(SnapshotConflictException.class); + } + + @Test + void rejectsMalformedRowsDuplicateFieldsAndChangedJsonTypes() { + ObjectMapper objectMapper = new ObjectMapper(); + String graph = new String(completeGraph().encode(objectMapper), StandardCharsets.UTF_8); + List invalidSnapshots = + List.of( + graph.replace("\"shardId\":4", "\"shardId\":\"4\""), + graph.replace("\"id\":9223372036854775807,", ""), + graph.replace( + "\"id\":9223372036854775807,", + "\"id\":9223372036854775807,\"id\":9223372036854775807,"), + graph.replace( + "\"id\":9223372036854775807,", "\"id\":9223372036854775807,\"unexpected\":0,"), + graph.replace("\"spacingMultiplier\":0.125", "\"spacingMultiplier\":\"0.125\""), + graph.replace("\"spacingMultiplier\":0.125", "\"spacingMultiplier\":0.1250"), + graph.replace("\"spacingMultiplier\":0.125", "\"spacingMultiplier\":1e9999"), + graph.replace( + "\"scopeType\":null,\"scopeId\":null", + "\"scopeType\":\"REGION_SUBTREE\",\"scopeId\":\"009\""), + graph.replace("\"shardId\":4,\"name\":\"edge\"", "\"name\":\"edge\",\"shardId\":4")); + + for (String invalidSnapshot : invalidSnapshots) { + assertThatThrownBy( + () -> + WorldAuthoredGraph.decode( + invalidSnapshot.getBytes(StandardCharsets.UTF_8), objectMapper)) + .isInstanceOf(SnapshotConflictException.class); + } + } + + @Test + void decodedGraphDoesNotRetainMutableInputBytesAndExposesImmutableRows() { + ObjectMapper objectMapper = new ObjectMapper(); + byte[] input = completeGraph().encode(objectMapper); + byte[] canonical = input.clone(); + + WorldAuthoredGraph decoded = WorldAuthoredGraph.decode(input, objectMapper); + input[0] = 'x'; + + assertThat(decoded.encode(objectMapper)).containsExactly(canonical); + assertThatThrownBy(() -> decoded.regions().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> decoded.regions().getFirst().put("name", "changed")) + .isInstanceOf(UnsupportedOperationException.class); + } + + private static WorldAuthoredGraph completeGraph() { + return new WorldAuthoredGraph( + List.of( + row( + "id", + Long.MAX_VALUE, + "shardId", + 4, + "name", + "edge", + "weather", + null, + "generationSeed", + Long.MIN_VALUE, + "generatorType", + null, + "generatorParams", + null, + "spacingMultiplier", + 0.125d), + row( + "id", + Long.MAX_VALUE - 1, + "shardId", + 0, + "name", + "edge-two", + "weather", + "clear", + "generationSeed", + Long.MAX_VALUE, + "generatorType", + "grid", + "generatorParams", + "{}", + "spacingMultiplier", + 3.75d)), + List.of( + row("id", 9_007_199_254_740_993L, "regionId", Long.MAX_VALUE, "name", "large-zone")), + List.of( + row( + "id", + 9_007_199_254_740_995L, + "zoneId", + 9_007_199_254_740_993L, + "name", + "large-room", + "description", + null, + "nameLocalizedVariantsJson", + "{}", + "descriptionLocalizedVariantsJson", + null)), + List.of( + row( + "id", + Long.MAX_VALUE - 2, + "fromRoomId", + 9_007_199_254_740_995L, + "toRoomId", + 9_007_199_254_740_995L, + "direction", + "east", + "cost", + 1)), + List.of( + row( + "id", Long.MAX_VALUE - 3, + "name", "unscoped-rule", + "scopeType", null, + "scopeId", null, + "value", null)), + List.of( + row( + "id", + Long.MAX_VALUE - 4, + "roomId", + 9_007_199_254_740_995L, + "entityTemplateType", + "ITEM", + "entityTemplateId", + 9_007_199_254_740_999L, + "spawnCount", + 1, + "respawnDelaySeconds", + 0))); + } + + private static LinkedHashMap row(Object... values) { + LinkedHashMap row = new LinkedHashMap<>(); + for (int index = 0; index < values.length; index += 2) { + row.put((String) values[index], values[index + 1]); + } + return row; + } +} 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(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java new file mode 100644 index 0000000000..e697fdf577 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java @@ -0,0 +1,489 @@ +package unit.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.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +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.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldAuthoredVersionIdentityServiceTest { + private static final String NAMESPACE = "firemud"; + 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 SOURCE_REGISTRATION = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID INTAKE_OPERATION = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID READ_REQUEST = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID VERSION = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID OTHER_VERSION = UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final String WORLD = "violet-wilds"; + private static final long GAME_DESIGN_VERSION_ID = 42L; + + private final AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + private final WorldAuthoredVersionIdentityRepository repository = + mock(WorldAuthoredVersionIdentityRepository.class); + private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository = + mock(WorldAuthoredSourceIntakeRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final WorldAuthoredVersionIdentityService service = + new WorldAuthoredVersionIdentityService( + versionStateClient, repository, sourceIntakeRepository, transactionManager, NAMESPACE); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresExactSameNamespaceGameDesignPeerBeforeAnyOwnerOrRemoteAccess() { + assertThatThrownBy(() -> withoutPeer(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-design-service"), + () -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.associate( + "other", + TENANT, + WORLD, + SOURCE_OPERATION, + source().evidenceDigest(), + VERSION, + GAME_DESIGN_VERSION_ID, + READ_REQUEST))) + .isInstanceOf(SecurityException.class); + verifyNoInteractions(sourceIntakeRepository, repository, versionStateClient); + } + + @Test + void exactRetryReturnsOriginalReceiptWithoutCallingGameDesignAgain() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence originalState = + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 7L); + WorldAuthoredVersionIdentityReceipt original = identityReceipt(intake, originalState, 91L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.of(original)); + + WorldAuthoredVersionIdentityReceipt result = + withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID)); + + assertThat(result).isEqualTo(original); + verifyNoInteractions(versionStateClient); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + verify(repository, never()) + .readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID); + verify(sourceIntakeRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + } + + @Test + void changedCanonicalUuidForAnAlreadyMappedGameDesignSelectorDeniesBeforeRemoteRead() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence oldState = + versionState( + source, + READ_REQUEST, + OTHER_VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 7L); + WorldAuthoredVersionIdentityReceipt existing = identityReceipt(intake, oldState, 91L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty()); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.of(existing)); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("selector conflicts"); + + verifyNoInteractions(versionStateClient); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void retainsExactSourceQualifiedDraftIdentityInItsOwnReadCommittedTransaction() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence current = + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 3L); + WorldAuthoredVersionIdentityReceipt accepted = identityReceipt(intake, current, 101L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty(), Optional.of(accepted)); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())).thenReturn(current); + when(repository.acceptFresh(intake, current)).thenReturn(accepted); + + WorldAuthoredVersionIdentityReceipt result = + withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID)); + + assertThat(result).isEqualTo(accepted); + assertThat(result.localVersionKey()).isEqualTo(101L); + assertThat(result.canonicalVersionId()).isEqualTo(VERSION); + assertThat(result.gameDesignVersionId()).isEqualTo(GAME_DESIGN_VERSION_ID); + assertThat(result.sourceIntakeReceipt()).isEqualTo(intake); + assertThat(result.versionStateEvidence()).isEqualTo(current); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + + InOrder order = inOrder(sourceIntakeRepository, repository, versionStateClient); + order + .verify(sourceIntakeRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + order.verify(repository).readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION); + order + .verify(repository) + .readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID); + order.verify(versionStateClient).read(current.request()); + order.verify(repository).acceptFresh(intake, current); + order.verify(repository).readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION); + order + .verify(sourceIntakeRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + } + + @Test + void rejectsSubstitutedCanonicalVersionAndUnsupportedLifecycleBeforeMutation() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty()); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())) + .thenReturn( + versionState( + source, + READ_REQUEST, + OTHER_VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 5L)); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("expected UUID"); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + + when(versionStateClient.read(any())) + .thenReturn( + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_RETIRED, + 6L)); + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("must be DRAFT, PUBLISHED, or ACTIVE"); + verify(repository, never()).acceptFresh(any(WorldAuthoredSourceIntakeReceipt.class), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void reconcilesLostCommitAcknowledgmentFromTheOriginalStoredReceipt() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt intake = sourceReceipt(source); + AuthoredWorldVersionStateEvidence current = + versionState( + source, + READ_REQUEST, + VERSION, + GAME_DESIGN_VERSION_ID, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 8L); + WorldAuthoredVersionIdentityReceipt accepted = identityReceipt(intake, current, 102L); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(intake)); + when(repository.readByCanonicalVersion(NAMESPACE, TENANT, WORLD, VERSION)) + .thenReturn(Optional.empty(), Optional.of(accepted)); + when(repository.readByGameDesignVersion(NAMESPACE, TENANT, WORLD, GAME_DESIGN_VERSION_ID)) + .thenReturn(Optional.empty()); + when(versionStateClient.read(any())).thenReturn(current); + when(repository.acceptFresh(intake, current)).thenReturn(accepted); + transactionManager.loseCommitAcknowledgment = true; + + WorldAuthoredVersionIdentityReceipt result = + withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID)); + + assertThat(result).isEqualTo(accepted); + assertThat(transactionManager.commitFailureThrown).isTrue(); + verify(repository, times(1)).acceptFresh(intake, current); + } + + @Test + void missingExactFreshIntakeCannotCallGameDesignOrAllocateAnIdentity() { + AuthoredWorldSourceEvidence source = source(); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("exact committed fresh source intake"); + + verifyNoInteractions(repository, versionStateClient); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void substitutedSourceIntakeCannotCallGameDesignOrAllocateAnIdentity() { + AuthoredWorldSourceEvidence requested = source(); + AuthoredWorldSourceEvidence substituted = + source("amber-coast", UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + when(sourceIntakeRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, requested.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt(substituted))); + + assertThatThrownBy(() -> withGameDesign(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("exact fresh NEW_GAME_ROW source intake"); + + verifyNoInteractions(repository, versionStateClient); + assertThat(transactionManager.startedWith).isNull(); + } + + private WorldAuthoredVersionIdentityReceipt associate(UUID canonicalVersionId, long versionId) { + AuthoredWorldSourceEvidence source = source(); + return service.associate( + NAMESPACE, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + canonicalVersionId, + versionId, + READ_REQUEST); + } + + private static WorldAuthoredVersionIdentityReceipt identityReceipt( + WorldAuthoredSourceIntakeReceipt intake, + AuthoredWorldVersionStateEvidence evidence, + long localVersionKey) { + return new WorldAuthoredVersionIdentityReceipt( + 1, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + localVersionKey, + intake, + evidence); + } + + private static AuthoredWorldVersionStateEvidence versionState( + AuthoredWorldSourceEvidence source, + UUID readRequestId, + UUID canonicalVersionId, + long gameDesignVersionId, + VersionLifecycleState state, + long epoch) { + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + readRequestId, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + gameDesignVersionId); + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, state, epoch); + } + + private static WorldAuthoredSourceIntakeReceipt sourceReceipt( + AuthoredWorldSourceEvidence source) { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest( + source.targetNamespace(), INTAKE_REQUEST, source); + return new WorldAuthoredSourceIntakeReceipt( + 1, + source.targetNamespace(), + INTAKE_REQUEST, + INTAKE_OPERATION, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + source.targetNamespace(), INTAKE_OPERATION, requestDigest, source, 90_041L), + 90_041L, + source); + } + + private static AuthoredWorldSourceEvidence source() { + return source(WORLD, SOURCE_OPERATION); + } + + private static AuthoredWorldSourceEvidence source(String worldSlug, UUID sourceOperationId) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, SOURCE_REGISTRATION, TENANT, "north-star", worldSlug, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION, + sourceOperationId, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION, + sourceOperationId, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + 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; + private boolean loseCommitAcknowledgment; + private boolean commitFailureThrown; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + if (loseCommitAcknowledgment) { + loseCommitAcknowledgment = false; + commitFailureThrown = true; + throw new IllegalStateException("simulated lost commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReaderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReaderTest.java new file mode 100644 index 0000000000..5b496c83e8 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReaderTest.java @@ -0,0 +1,153 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.junit.jupiter.api.Test; + +class WorldCanonicalAuthoredGraphReaderTest { + private static final UUID TENANT = new UUID(0, 1); + private static final UUID VERSION = new UUID(0, 2); + private static final UUID COMMIT = new UUID(0, 3); + private static final UUID REGION = new UUID(0, 4); + private static final UUID REVISION = new UUID(0, 5); + + @Test + void consumesClosedActualStorageViewWithPrivateKeysAndEffectiveDefaults() throws Exception { + var graph = new WorldCanonicalAuthoredGraphReader().read(plan(), bytes(graphJson())); + assertThat(graph.tenantId()).isEqualTo(TENANT); + assertThat(graph.localTenantKey()).isEqualTo(9007199254740993L); + assertThat(graph.family(Family.REGION)).hasSize(1); + var row = graph.rows().getFirst(); + assertThat(row.template().templateId()).isEqualTo(REGION); + assertThat(row.scope()).isEqualTo(row.template()); + assertThat(row.authored().mutation().getRegion().getSpacingMultiplier()).isZero(); + assertThat(row.content().getRegion().getSpacingMultiplier()).isEqualTo(1.0); + assertThatThrownBy(() -> graph.rows().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void rejectsUnknownMissingDuplicateTrailingAndWrongRepresentations() throws Exception { + String good = graphJson(); + for (String bad : + List.of( + good.replace("\"schemaVersion\":\"2\"", "\"schemaVersion\":\"1\""), + good.replace("\"schemaVersion\":\"2\"", "\"schemaVersion\":2"), + good.replace("\"schemaVersion\":\"2\"", "\"schemaVersion\":\"2\",\"extra\":true"), + good.replace( + "\"schemaVersion\":\"2\"", "\"schemaVersion\":\"2\",\"schemaVersion\":\"2\""), + good + " {}", + good.replace("\"family\":\"REGION\"", "\"family\":\"ROOM\""), + good.replace("\"private_row_key\":11", "\"private_row_key\":\"11\""), + good.replace("\"private_row_key\":11", "\"private_row_key\":0"), + good.replace("\"private_row_key\":11", "\"private_row_key\":9223372036854775808"), + good.replace("\"weather\":\"rain\"", "\"weather\":\"tampered\""), + good.replace("\"version_id\":31,\"version\":0", "\"version_id\":32,\"version\":0"), + good.replace( + "\"canonicalVersionId\":\"" + VERSION, "\"canonicalVersionId\":\"" + REGION), + good.replace("\"name\":\"region\"", "\"name\":\"region\",\"extra\":null"))) { + assertThatThrownBy(() -> new WorldCanonicalAuthoredGraphReader().read(plan(), bytes(bad))) + .isInstanceOf(RuntimeException.class); + } + } + + static WorldDraftTopologyCommitPlan plan() throws Exception { + var owner = + new OwnerBinding( + "firemud", + TENANT, + VERSION, + new UUID(0, 6), + 41, + new UUID(0, 7), + new UUID(0, 8), + "sha256:" + "a".repeat(64), + new UUID(0, 9), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + var mutation = + WorldDesignMutationRevision.newBuilder() + .setCommitId(COMMIT.toString()) + .setLogicalRevisionId(REVISION.toString()) + .setAggregateId(REGION.toString()) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(REGION.toString()) + .setRegion(RegionDesignMutation.newBuilder().setName("region").setWeather("rain")) + .build(); + var binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 41, "gd-source", 51, "gd-source", "NEW_GAME_ROW"), + new UUID(0, 10), + COMMIT, + "original-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + REVISION, + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(mutation))), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + REGION.toString(), + "AGGREGATE", + REGION.toString(), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + REGION.toString(), + "REGION_SUBTREE", + REGION.toString(), + "0"))); + return WorldDraftTopologyCommitPlan.create(binding, owner); + } + + // Synthetic bytes are deliberate decoder fixtures; real V30 storage is covered by PostgreSQL. + private String graphJson() { + return """ + {"schemaVersion":"2","canonicalTenantId":"%s","canonicalVersionId":"%s","rows":[ + {"mapping":{"id":1,"target_namespace":"firemud","canonical_tenant_id":"%s", + "canonical_version_id":"%s","family":"REGION","template_id":"%s","private_row_key":11, + "tenant_id":9007199254740993,"version_id":31,"version_identity_operation_id":"%s", + "request_id":"%s","commit_id":"%s","revision_id":"%s","revision_order":"0"}, + "content":{"id":11,"tenant_id":9007199254740993,"version_id":31,"version":0,"name":"region", + "shard_id":0,"weather":"rain","generation_seed":0,"generator_type":"","generator_params":"", + "spacing_multiplier":1.0}}]} + """ + .replace("\n", "") + .formatted( + TENANT, + VERSION, + TENANT, + VERSION, + REGION, + new UUID(0, 6), + new UUID(0, 10), + COMMIT, + REVISION); + } + + private byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationServiceTest.java new file mode 100644 index 0000000000..fc16e9c6a8 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalCurrentPlayerLocationServiceTest.java @@ -0,0 +1,107 @@ +package unit.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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalCurrentPlayerLocationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalCurrentPlayerLocationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationService; +import org.junit.jupiter.api.Test; + +class WorldCanonicalCurrentPlayerLocationServiceTest { + @Test + void productionDefaultDeniesBeforeOwnerRead() { + var repository = mock(WorldCanonicalCurrentPlayerLocationRepository.class); + var service = new WorldCanonicalCurrentPlayerLocationService(repository); + + assertThatThrownBy(() -> service.read(request())) + .isInstanceOf(WorldCanonicalInitialPlayerLocationService.PlacementDeniedException.class) + .hasMessageContaining("no authenticated current Entity assignment"); + verifyNoInteractions(repository); + } + + @Test + void currentAuthorityIsHeldAcrossTheOwnerReadIncludingAnAbsentResult() { + var repository = mock(WorldCanonicalCurrentPlayerLocationRepository.class); + when(repository.read(any(), any())).thenReturn(Optional.empty()); + AtomicInteger heldChecks = new AtomicInteger(); + AtomicInteger closes = new AtomicInteger(); + var service = + new WorldCanonicalCurrentPlayerLocationService( + repository, + ignored -> + new WorldCanonicalInitialPlayerLocationService.HeldPlacementAuthority() { + @Override + public void requireHeld() { + heldChecks.incrementAndGet(); + } + + @Override + public void close() { + closes.incrementAndGet(); + } + }); + + assertThat(service.read(request())).isEmpty(); + assertThat(heldChecks).hasValue(2); + assertThat(closes).hasValue(1); + } + + private static WorldCanonicalInitialPlayerLocation.Request request() { + UUID tenantId = uuid("20000000-0000-4000-8000-000000000001"); + UUID versionId = uuid("30000000-0000-4000-8000-000000000001"); + UUID instanceId = uuid("40000000-0000-4000-8000-000000000001"); + UUID namespaceId = uuid("50000000-0000-4000-8000-000000000001"); + var lifecycleRequest = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(lifecycleRequest.canonicalTenantId()).thenReturn(tenantId); + when(lifecycleRequest.worldSlug()).thenReturn("starter-world"); + when(lifecycleRequest.canonicalGameInstanceId()).thenReturn(instanceId); + when(lifecycleRequest.playableStateNamespaceId()).thenReturn(namespaceId); + when(lifecycleRequest.playableStateScope()).thenReturn("SHARED"); + var lifecycle = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(lifecycle.lifecycleStatus()).thenReturn("ACTIVE"); + when(lifecycle.request()).thenReturn(lifecycleRequest); + when(lifecycle.startLocation()) + .thenReturn( + new RoomTemplateRef(tenantId, versionId, uuid("60000000-0000-4000-8000-000000000001"))); + when(lifecycle.runtimeRoomInstanceId()).thenReturn(23L); + + return new WorldCanonicalInitialPlayerLocation.Request( + uuid("10000000-0000-4000-8000-000000000001"), + tenantId, + uuid("70000000-0000-4000-8000-000000000001"), + "starter-world", + instanceId, + namespaceId, + "SHARED", + uuid("80000000-0000-4000-8000-000000000001"), + uuid("90000000-0000-4000-8000-000000000001"), + uuid("a0000000-0000-4000-8000-000000000001"), + "a".repeat(64), + uuid("b0000000-0000-4000-8000-000000000001"), + uuid("c0000000-0000-4000-8000-000000000001"), + "initial-request", + "d".repeat(64), + 1, + "owner-proof", + "e".repeat(64), + "pointer-audit", + 1, + WorldCanonicalInitialPlayerLocation.InitialAdmissionOrigin.NO_PRIOR_POINTER, + lifecycle); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyServiceTest.java new file mode 100644 index 0000000000..8c42c6a388 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyServiceTest.java @@ -0,0 +1,96 @@ +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.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalFrozenTopologyServiceTest { + private final WorldCanonicalFrozenTopologyRepository repository = + mock(WorldCanonicalFrozenTopologyRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final WorldCanonicalFrozenTopology.Request request = + mock(WorldCanonicalFrozenTopology.Request.class); + private final WorldCanonicalFrozenTopology result = mock(WorldCanonicalFrozenTopology.class); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactHistoricalRetryNeverReentersWriterOrOwnerTransaction() { + when(repository.readCommitted(request)).thenReturn(Optional.of(result)); + var service = new WorldCanonicalFrozenTopologyService(repository, manager); + assertThat(service.capture(request)).isSameAs(result); + verifyNoInteractions(manager); + org.mockito.Mockito.verify(repository).readCommitted(request); + org.mockito.Mockito.verifyNoMoreInteractions(repository); + } + + @Test + void absentHistoricalReadRemainsUnknownAndCannotStartCapture() { + when(repository.readCommitted(request)).thenReturn(Optional.empty()); + assertThat(new WorldCanonicalFrozenTopologyService(repository, manager).readCommitted(request)) + .isEmpty(); + verifyNoInteractions(manager); + org.mockito.Mockito.verify(repository).readCommitted(request); + org.mockito.Mockito.verifyNoMoreInteractions(repository); + } + + @Test + void newCaptureUsesDedicatedWritableReadCommittedTransactionAndCommit() { + var status = mock(TransactionStatus.class); + when(repository.readCommitted(request)).thenReturn(Optional.empty()); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.capture(request)).thenReturn(result); + assertThat(new WorldCanonicalFrozenTopologyService(repository, manager).capture(request)) + .isSameAs(result); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + var order = inOrder(repository, manager); + order.verify(repository).readCommitted(request); + order.verify(manager).getTransaction(definition.capture()); + order.verify(repository).capture(request); + order.verify(manager).commit(status); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + } + + @Test + void lateFailureRollsBackWithoutReturningAResult() { + var status = mock(TransactionStatus.class); + when(repository.readCommitted(request)).thenReturn(Optional.empty()); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.capture(request)).thenThrow(new IllegalStateException("mismatched freeze")); + assertThatThrownBy( + () -> new WorldCanonicalFrozenTopologyService(repository, manager).capture(request)) + .hasMessage("mismatched freeze"); + org.mockito.Mockito.verify(manager).rollback(status); + } + + @Test + void rejectsActiveCallerBeforeReadOrCapture() { + TransactionSynchronizationManager.setActualTransactionActive(true); + var service = new WorldCanonicalFrozenTopologyService(repository, manager); + assertThatThrownBy(() -> service.capture(request)) + .hasMessageContaining("independent owner operation"); + assertThatThrownBy(() -> service.readCommitted(request)) + .hasMessageContaining("independent owner operation"); + verifyNoInteractions(repository, manager); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyTest.java new file mode 100644 index 0000000000..69446e4090 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyTest.java @@ -0,0 +1,64 @@ +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.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import org.junit.jupiter.api.Test; + +class WorldCanonicalFrozenTopologyTest { + @Test + void exactFreezeRetainsSyntheticCheckpointWithoutRelabelingItsDigest() throws Exception { + var plan = WorldCanonicalAuthoredGraphReaderTest.plan(); + var request = new Request(plan, freeze(plan, plan.binding().commitId().toString(), true)); + assertThat(request.freeze().contentDigest()).isEqualTo("b".repeat(64)); + assertThat(request.plan().binding()).isSameAs(plan.binding()); + assertThat(WorldCanonicalFrozenTopology.STATUS).isEqualTo("CAPTURED_UNVERIFIED"); + } + + @Test + void rejectsSyntheticAppliedIdentityAndOmittedOriginalAffectedSet() throws Exception { + var plan = WorldCanonicalAuthoredGraphReaderTest.plan(); + assertThatThrownBy(() -> new Request(plan, freeze(plan, "synthetic-commit", true))) + .hasMessageContaining("exact selected complete commit"); + assertThatThrownBy( + () -> new Request(plan, freeze(plan, plan.binding().commitId().toString(), false))) + .hasMessageContaining("every exact original World affected tuple"); + } + + private CaptureRequest freeze( + WorldDraftTopologyCommitPlan plan, String selectedCommit, boolean tuples) { + var owner = plan.ownerBinding(); + var affected = + plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + return new CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + UUID.randomUUID(), + "synthetic-capture", + "a".repeat(64), + 1, + "publish:" + owner.canonicalTenantId() + ":publish-request:synthetic-capture", + selectedCommit, + "b".repeat(64), + 3, + tuples ? affected : List.of()); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepositoryTest.java new file mode 100644 index 0000000000..8d28ac62c9 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepositoryTest.java @@ -0,0 +1,481 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInitialAdmissionHoldFinalizationRepositoryTest { + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final Instant TERMINAL_AT = Instant.parse("2026-10-07T01:02:03.123456Z"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void ownerSnapshotReadReturnsOnlyDigestAndIdentityVerifiedCommittedProof() { + Request request = request(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + GameSessionCanonicalInitialAdmissionOwnerProof proof = committed(identity, 1L); + Map values = terminalValues(request, identity, proof); + Fixture fixture = fixture(values); + WorldCanonicalInstanceAssociation association = association(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_REPEATABLE_READ); + when(fixture.associations.readOwnerAssociationInOwnerTransaction(INSTANCE)) + .thenReturn(Optional.of(association)); + + assertThat(fixture.repository.readCommittedInOwnerTransaction(HOLD_ID)).contains(proof); + assertThat(((LocalDateTime) values.get("terminal_at")).toInstant(ZoneOffset.UTC)) + .isEqualTo(proof.terminalAt()); + } + + @Test + void ownerSnapshotReadVerifiesExpectedClosedPointerVersionsBeyondLongCacheRange() { + Request request = request(InitialAdmissionOrigin.EXPECT_CLOSED, 300L); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + GameSessionCanonicalInitialAdmissionOwnerProof proof = committed(identity, 301L); + Fixture fixture = fixture(terminalValues(request, identity, proof)); + WorldCanonicalInstanceAssociation association = association(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_REPEATABLE_READ); + when(fixture.associations.readOwnerAssociationInOwnerTransaction(INSTANCE)) + .thenReturn(Optional.of(association)); + + assertThat(fixture.repository.readCommittedInOwnerTransaction(HOLD_ID)).contains(proof); + } + + @Test + void persistedProofDigestMismatchIsDeniedInTheSameOwnerSnapshot() { + Request request = request(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + Map values = terminalValues(request, identity, committed(identity, 1L)); + values.put("canonical_owner_proof_digest", "sha256:" + "0".repeat(64)); + Fixture fixture = fixture(values); + WorldCanonicalInstanceAssociation association = association(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_REPEATABLE_READ); + when(fixture.associations.readOwnerAssociationInOwnerTransaction(INSTANCE)) + .thenReturn(Optional.of(association)); + + assertThatThrownBy(() -> fixture.repository.readCommittedInOwnerTransaction(HOLD_ID)) + .isInstanceOf( + WorldCanonicalInitialAdmissionHoldFinalizationRepository + .InvalidFinalizationEvidenceException.class) + .hasMessageContaining("digest"); + } + + @Test + void exactTerminalRetryReturnsRetainedProofWithoutAnotherUpdate() { + Request request = request(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + GameSessionCanonicalInitialAdmissionOwnerProof proof = committed(identity, 1L); + Fixture fixture = fixture(terminalValues(request, identity, proof)); + WorldCanonicalInstanceAssociation association = association(); + when(fixture.associations.readOwnerAssociationInActivationTransaction(INSTANCE)) + .thenReturn(Optional.of(association)); + var held = heldProof(proof); + + assertThat(fixture.repository.finalizeTerminal(identity, proof, held)).isEqualTo(proof); + assertThat(fixture.manager.updateAttempted).isFalse(); + assertThat(fixture.manager.commitCount).isEqualTo(1); + assertThat(fixture.manager.rollbackCount).isZero(); + } + + @Test + void heldOwnerProofLossAfterUpdateRollsBackBeforeCommit() { + Request request = request(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + GameSessionCanonicalInitialAdmissionOwnerProof proof = committed(identity, 1L); + Map values = pendingValues(request, identity); + Fixture fixture = fixture(values); + WorldCanonicalInstanceAssociation association = association(); + when(fixture.associations.readOwnerAssociationInActivationTransaction(INSTANCE)) + .thenReturn(Optional.of(association)); + when(fixture.lifecycle.readForActivationInOwnerTransaction(any())) + .thenAnswer( + invocation -> { + WorldCanonicalInstanceLifecycleEvidence evidence = + Mockito.mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + when(evidence.lifecycleStatus()).thenReturn("ACTIVE"); + when(evidence.lifecycleEpoch()).thenReturn(7L); + return Optional.of(evidence); + }); + + AtomicInteger checks = new AtomicInteger(); + var heldProof = heldProof(proof, () -> fixture.manager.updateAttempted, checks); + + assertThatThrownBy(() -> fixture.repository.finalizeTerminal(identity, proof, heldProof)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("lost before World commit"); + assertThat(fixture.manager.updateAttempted).isTrue(); + assertThat(fixture.manager.commitCount).isZero(); + assertThat(fixture.manager.rollbackCount).isEqualTo(1); + assertThat(values.get("status")).isEqualTo("PENDING"); + assertThat(values.get("canonical_owner_proof_bytes")).isNull(); + } + + private static Fixture fixture(Map values) { + DSLContext dsl = Mockito.mock(DSLContext.class); + RecordingTransactionManager manager = new RecordingTransactionManager(); + WorldCanonicalInstanceAssociationRepository associations = + Mockito.mock(WorldCanonicalInstanceAssociationRepository.class); + WorldCanonicalInstanceLifecycleReadRepository lifecycle = + Mockito.mock(WorldCanonicalInstanceLifecycleReadRepository.class); + Record holdRow = row(values); + when(dsl.fetchOne(contains("current_setting"))).thenAnswer(invocation -> transactionState()); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM initial_admission_bind_hold")) return holdRow; + if (sql.contains("world_finalize_canonical_initial_admission_hold")) { + Object[] bindings = (Object[]) invocation.getRawArguments()[1]; + applyTerminal(values, bindings); + manager.updateAttempted = true; + return holdRow; + } + return null; + }); + manager.rollbackAction = () -> restorePending(values); + return new Fixture( + new WorldCanonicalInitialAdmissionHoldFinalizationRepository( + dsl, manager, associations, lifecycle), + associations, + lifecycle, + manager); + } + + private static WorldCanonicalInitialAdmissionHoldFinalizationService.HeldOwnerProof heldProof( + GameSessionCanonicalInitialAdmissionOwnerProof proof) { + return heldProof(proof, () -> false, new AtomicInteger()); + } + + private static WorldCanonicalInitialAdmissionHoldFinalizationService.HeldOwnerProof heldProof( + GameSessionCanonicalInitialAdmissionOwnerProof proof, + java.util.function.BooleanSupplier updated, + AtomicInteger checks) { + return new WorldCanonicalInitialAdmissionHoldFinalizationService.HeldOwnerProof() { + @Override + public GameSessionCanonicalInitialAdmissionOwnerProof proof() { + return proof; + } + + @Override + public void requireHeld() { + if (updated.getAsBoolean() && checks.incrementAndGet() >= 4) { + throw new IllegalStateException("owner proof hold was lost before World commit"); + } + if (!updated.getAsBoolean()) checks.incrementAndGet(); + } + + @Override + public void close() {} + }; + } + + private static WorldCanonicalInstanceAssociation association() { + WorldCanonicalInstanceAssociation association = + Mockito.mock(WorldCanonicalInstanceAssociation.class); + var identity = + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + INSTANCE, + "prod", + TENANT, + "green-hollow", + PLAYABLE_NAMESPACE, + "SHARED", + true, + "control-request"); + var prepare = + new WorldCanonicalInstanceAssociation.WorldPrepareFields( + 31L, + 41L, + 101L, + 1L, + "control-request", + "launch-descriptor", + 12L, + null, + "{}", + "generation-1", + 1L, + "release-ref", + 1L, + null); + WorldCompleteLaunchBindingReceipt binding = + Mockito.mock(WorldCompleteLaunchBindingReceipt.class); + CompleteLaunchBindingEvidence launchEvidence = + Mockito.mock(CompleteLaunchBindingEvidence.class); + AuthoredWorldLaunchDescriptorEvidence descriptor = + Mockito.mock(AuthoredWorldLaunchDescriptorEvidence.class); + AuthoredWorldReleaseAttestationEvidence release = + Mockito.mock(AuthoredWorldReleaseAttestationEvidence.class); + when(association.identity()).thenReturn(identity); + when(association.worldPrepareFields()).thenReturn(prepare); + when(association.canonicalVersionId()).thenReturn(VERSION); + when(association.completeLaunchBinding()).thenReturn(binding); + when(binding.descriptor()).thenReturn(descriptor); + when(binding.evidence()).thenReturn(launchEvidence); + when(launchEvidence.releaseAttestation()).thenReturn(release); + when(descriptor.requestDigest()).thenReturn("sha256:" + "1".repeat(64)); + when(descriptor.resultDigest()).thenReturn("sha256:" + "2".repeat(64)); + when(release.evidenceDigest()).thenReturn("sha256:" + "3".repeat(64)); + return association; + } + + private static Map pendingValues(Request request, HoldIdentity identity) { + Map values = baseValues(request, identity); + values.put("status", "PENDING"); + values.put("owner_proof_id", null); + values.put("owner_proof_digest", null); + values.put("owner_pointer_audit_id", null); + values.put("owner_pointer_version", null); + values.put("terminal_at", null); + values.put("row_version", 0L); + values.put("canonical_owner_proof_bytes", null); + values.put("canonical_owner_proof_digest", null); + return values; + } + + private static Map terminalValues( + Request request, + HoldIdentity identity, + GameSessionCanonicalInitialAdmissionOwnerProof proof) { + Map values = pendingValues(request, identity); + applyTerminal( + values, + new Object[] { + identity.holdId(), + identity.holdFence(), + proof.outcome().name(), + request.initialAdmissionRequestId(), + proof.proofDigest().substring("sha256:".length()), + proof.auditEventId().toString(), + proof.committedPointerVersion(), + proof.terminalAt().atOffset(ZoneOffset.UTC), + proof.positiveDurableAbort(), + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof), + digest(GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof)) + }); + return values; + } + + private static Map baseValues(Request request, HoldIdentity identity) { + Map values = new HashMap<>(); + values.put("hold_id", identity.holdId()); + values.put("hold_fence", identity.holdFence()); + values.put("tenant_id", 41L); + values.put("realm_uuid", request.realmId()); + values.put("playable_state_namespace_uuid", request.playableStateNamespaceId()); + values.put("playable_state_scope", request.playableStateScope()); + values.put("game_instance_id", 101L); + values.put("version_id", 12L); + values.put("active_lifecycle_epoch", request.activeLifecycleEpoch()); + values.put("initial_admission_request_id", request.initialAdmissionRequestId()); + values.put("request_digest", request.initialAdmissionRequestDigest()); + values.put( + "expected_no_prior_pointer", + request.initialAdmissionOrigin() == InitialAdmissionOrigin.NO_PRIOR_POINTER); + values.put("expected_catalog_revision", request.expectedCatalogRevision()); + values.put("canonical_target_namespace", request.targetNamespace()); + values.put("canonical_tenant_id", request.canonicalTenantId()); + values.put("canonical_world_slug", request.worldSlug()); + values.put("canonical_game_instance_id", request.canonicalGameInstanceId()); + values.put("canonical_version_id", request.canonicalVersionId()); + values.put("initial_admission_origin", request.initialAdmissionOrigin().name()); + values.put("expected_prior_pointer_version", request.expectedPriorPointerVersion()); + values.put("canonical_request_bytes", request.canonicalRequestBytes()); + values.put("hold_binding_digest", request.holdBindingDigest()); + return values; + } + + private static void applyTerminal(Map values, Object[] bindings) { + values.put("status", bindings[2]); + values.put("owner_proof_id", bindings[3]); + values.put("owner_proof_digest", bindings[4]); + values.put("owner_pointer_audit_id", bindings[5]); + values.put("owner_pointer_version", bindings[6]); + values.put( + "terminal_at", + LocalDateTime.ofInstant(((OffsetDateTime) bindings[7]).toInstant(), ZoneOffset.UTC)); + values.put("canonical_owner_proof_bytes", bindings[9]); + values.put("canonical_owner_proof_digest", bindings[10]); + values.put("row_version", 1L); + } + + private static void restorePending(Map values) { + values.put("status", "PENDING"); + values.put("owner_proof_id", null); + values.put("owner_proof_digest", null); + values.put("owner_pointer_audit_id", null); + values.put("owner_pointer_version", null); + values.put("terminal_at", null); + values.put("row_version", 0L); + values.put("canonical_owner_proof_bytes", null); + values.put("canonical_owner_proof_digest", null); + } + + private static Record transactionState() { + boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + String isolationName = + Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ).equals(isolation) + ? "repeatable read" + : "read committed"; + return row(Map.of("isolation", isolationName, "read_only", readOnly ? "on" : "off")); + } + + private static Record row(Map values) { + Record row = Mockito.mock(Record.class); + doAnswer( + invocation -> { + String name = invocation.getArgument(0); + Object value = values.get(name); + Class type = invocation.getArgument(1); + return value == null || type.isInstance(value) ? value : type.cast(value); + }) + .when(row) + .get(anyString(), any(Class.class)); + return row; + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof committed( + HoldIdentity identity, long pointerVersion) { + return new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + pointerVersion, + 27L, + "sha256:" + "a".repeat(64), + false, + TERMINAL_AT); + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + private static Request request(InitialAdmissionOrigin origin, Long priorVersion) { + return new Request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + "a".repeat(64), + origin, + 12L, + priorVersion); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + WorldCanonicalInitialAdmissionHoldFinalizationRepository repository, + WorldCanonicalInstanceAssociationRepository associations, + WorldCanonicalInstanceLifecycleReadRepository lifecycle, + RecordingTransactionManager manager) {} + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private Runnable rollbackAction = () -> {}; + private boolean updateAttempted; + private int commitCount; + private int rollbackCount; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + TransactionDefinition effective = + definition == null ? TransactionDefinition.withDefaults() : definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(effective.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + effective.getIsolationLevel()); + TransactionSynchronizationManager.initSynchronization(); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + try { + for (TransactionSynchronization synchronization : + TransactionSynchronizationManager.getSynchronizations()) { + synchronization.beforeCommit(false); + } + commitCount++; + TransactionSynchronizationManager.clear(); + } catch (RuntimeException failure) { + rollback(status); + throw failure; + } + } + + @Override + public void rollback(TransactionStatus status) { + rollbackCount++; + rollbackAction.run(); + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationServiceTest.java new file mode 100644 index 0000000000..6873fe1285 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationServiceTest.java @@ -0,0 +1,216 @@ +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.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInitialAdmissionHoldFinalizationServiceTest { + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void committedNoPriorPointerRequiresFirstPointerVersionOne() { + HoldIdentity identity = identity(request(InitialAdmissionOrigin.NO_PRIOR_POINTER, null)); + var proof = committed(identity, 1L); + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationRepository.class); + when(repository.finalizeTerminal(Mockito.eq(identity), Mockito.eq(proof), Mockito.any())) + .thenReturn(proof); + AtomicBoolean closed = new AtomicBoolean(); + var service = + new WorldCanonicalInitialAdmissionHoldFinalizationService( + repository, verifier(proof, closed)); + + assertThat( + service.finalizeHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .isEqualTo(proof); + assertThat(closed).isTrue(); + verify(repository).finalizeTerminal(Mockito.eq(identity), Mockito.eq(proof), Mockito.any()); + } + + @Test + void expectedClosedRequiresExactNextPointerAndOverflowFailsClosed() { + HoldIdentity identity = identity(request(InitialAdmissionOrigin.EXPECT_CLOSED, 13L)); + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationRepository.class); + var wrongVersionService = + new WorldCanonicalInitialAdmissionHoldFinalizationService( + repository, verifier(committed(identity, 15L), new AtomicBoolean())); + + assertThatThrownBy( + () -> + wrongVersionService.finalizeHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .isInstanceOf( + WorldCanonicalInitialAdmissionHoldFinalizationService.FinalizationDeniedException.class) + .hasMessageContaining("noncanonical pointer version"); + verifyNoInteractions(repository); + + HoldIdentity overflow = identity(request(InitialAdmissionOrigin.EXPECT_CLOSED, Long.MAX_VALUE)); + var overflowService = + new WorldCanonicalInitialAdmissionHoldFinalizationService( + repository, verifier(committed(overflow, 1L), new AtomicBoolean())); + assertThatThrownBy( + () -> + overflowService.finalizeHold( + overflow, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .isInstanceOf( + WorldCanonicalInitialAdmissionHoldFinalizationService.FinalizationDeniedException.class) + .hasMessageContaining("overflow"); + verifyNoInteractions(repository); + } + + @Test + void positiveDurableAbortRemainsDistinctFromPointerCommit() { + HoldIdentity identity = identity(request(InitialAdmissionOrigin.NO_PRIOR_POINTER, null)); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + null, + null, + "sha256:" + "c".repeat(64), + true, + Instant.parse("2026-10-07T01:02:03.123456Z")); + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationRepository.class); + when(repository.finalizeTerminal(Mockito.eq(identity), Mockito.eq(proof), Mockito.any())) + .thenReturn(proof); + var service = + new WorldCanonicalInitialAdmissionHoldFinalizationService( + repository, verifier(proof, new AtomicBoolean())); + + assertThat( + service.finalizeHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)) + .isEqualTo(proof); + verify(repository).finalizeTerminal(Mockito.eq(identity), Mockito.eq(proof), Mockito.any()); + } + + @Test + void pendingAndUnavailableOwnerProofCannotReleaseTheHold() { + HoldIdentity identity = identity(request(InitialAdmissionOrigin.NO_PRIOR_POINTER, null)); + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationRepository.class); + var service = + new WorldCanonicalInitialAdmissionHoldFinalizationService( + repository, WorldCanonicalInitialAdmissionHoldFinalizationService.denyAllVerifier()); + + assertThatThrownBy( + () -> + service.finalizeHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING)) + .isInstanceOf( + WorldCanonicalInitialAdmissionHoldFinalizationService.FinalizationDeniedException.class) + .hasMessageContaining("PENDING"); + assertThatThrownBy( + () -> + service.finalizeHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)) + .isInstanceOf( + WorldCanonicalInitialAdmissionHoldFinalizationService.FinalizationDeniedException.class) + .hasMessageContaining("unavailable"); + verifyNoInteractions(repository); + } + + @Test + void ambientTransactionsAreRejectedBeforeRemoteOwnerProofVerification() { + HoldIdentity identity = identity(request(InitialAdmissionOrigin.NO_PRIOR_POINTER, null)); + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationRepository.class); + var verifier = + Mockito.mock( + WorldCanonicalInitialAdmissionHoldFinalizationService.OwnerProofVerifier.class); + var service = new WorldCanonicalInitialAdmissionHoldFinalizationService(repository, verifier); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + service.finalizeHold( + identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an ambient transaction"); + verify(verifier, never()).verifyAndHold(Mockito.any(), Mockito.any()); + verifyNoInteractions(repository); + } + + private static WorldCanonicalInitialAdmissionHoldFinalizationService.OwnerProofVerifier verifier( + GameSessionCanonicalInitialAdmissionOwnerProof proof, AtomicBoolean closed) { + return (identity, outcome) -> + new WorldCanonicalInitialAdmissionHoldFinalizationService.HeldOwnerProof() { + @Override + public GameSessionCanonicalInitialAdmissionOwnerProof proof() { + return proof; + } + + @Override + public void requireHeld() { + if (closed.get()) throw new IllegalStateException("held proof already closed"); + } + + @Override + public void close() { + closed.set(true); + } + }; + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof committed( + HoldIdentity identity, long pointerVersion) { + return new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + pointerVersion, + 27L, + "sha256:" + "a".repeat(64), + false, + Instant.parse("2026-10-07T01:02:03.123456Z")); + } + + private static HoldIdentity identity(Request request) { + return new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + } + + private static Request request(InitialAdmissionOrigin origin, Long priorVersion) { + return new Request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + "a".repeat(64), + origin, + 12L, + priorVersion); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcServiceTest.java new file mode 100644 index 0000000000..7115b3248a --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcServiceTest.java @@ -0,0 +1,505 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldRepository; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityResponse; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInitialAdmissionHoldGrpcServiceTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID OTHER_PLAYABLE_NAMESPACE = uuid("34343434-3434-4434-8434-343434343434"); + private static final UUID GAME_INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID LIFECYCLE_READ_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID HOLD_READ_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final String REQUEST_ID = "gs-initial-admission-17"; + private static final String REQUEST_DIGEST = "a".repeat(64); + + @Test + void rejectsMissingWrongAndWrongNamespacePeersBeforeParsingOrOwnerAccess() { + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var grpc = service(repository); + var malformed = acquire(new byte[] {1}, new byte[] {1}); + + Collector missing = + callAcquire(grpc, malformed, null); + Collector wrongService = + callAcquire(grpc, malformed, peer("account-service", "test")); + Collector wrongNamespace = + callAcquire(grpc, malformed, peer("game-session-service", "other")); + + assertThat(missing.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongService.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsEndUserContextBeforeParsingOrOwnerAccess() { + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var grpc = service(repository); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Collector result; + try { + result = + callAcquire( + grpc, acquire(new byte[] {1}, new byte[] {1}), peer("game-session-service", "test")); + } finally { + SessionContext.clear(); + } + + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsAmbientActualAndSynchronizationTransactionsBeforeParsingOrOwnerAccess() { + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var grpc = service(repository); + var malformed = acquire(new byte[] {1}, new byte[] {1}); + + TransactionSynchronizationManager.setActualTransactionActive(true); + Collector actualTransaction; + try { + actualTransaction = callAcquire(grpc, malformed, peer("game-session-service", "test")); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + Collector synchronization; + try { + synchronization = callAcquire(grpc, malformed, peer("game-session-service", "test")); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + + assertThat(actualTransaction.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(synchronization.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(repository); + } + + @Test + void rejectsUnknownFieldsMalformedCanonicalBytesAndNoncanonicalReadIds() { + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var grpc = service(repository); + Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); + var unknownAcquire = + acquire(fixture.holdBytes, fixture.lifecycleBytes).toBuilder() + .setUnknownFields(unknownFields()) + .build(); + var unknownRead = + read(HOLD_READ_ID.toString(), fixture.holdBytes).toBuilder() + .setUnknownFields(unknownFields()) + .build(); + + assertThat(callAcquire(grpc, unknownAcquire, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(callRead(grpc, unknownRead, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callAcquire( + grpc, + acquire("not-json".getBytes(StandardCharsets.UTF_8), fixture.lifecycleBytes), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callAcquire( + grpc, + acquire(fixture.holdBytes, "not-json".getBytes(StandardCharsets.UTF_8)), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callRead( + grpc, + read(HOLD_READ_ID.toString().toUpperCase(), fixture.holdBytes), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callRead( + grpc, + read("00000000-0000-0000-0000-000000000000", fixture.holdBytes), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void requiresTrustedNamespaceOnBothAcquireTuplesAndExactMatchingTargetScope() { + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var grpc = service(repository); + Fixture wrongHoldNamespace = fixture("other", "test", PLAYABLE_NAMESPACE); + Fixture wrongLifecycleNamespace = fixture("test", "other", PLAYABLE_NAMESPACE); + Fixture mismatchedScope = fixture("test", "test", OTHER_PLAYABLE_NAMESPACE); + + assertThat( + callAcquire(grpc, acquire(wrongHoldNamespace), peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + callAcquire( + grpc, acquire(wrongLifecycleNamespace), peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + callAcquire(grpc, acquire(mismatchedScope), peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(repository); + } + + @Test + void acquireReturnsExactCanonicalIdentityAfterRepositoryValidation() { + Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(repository.acquire( + any(Request.class), any(WorldCanonicalInstanceLifecycleEvidence.Request.class))) + .thenReturn(fixture.identity); + var grpc = service(repository); + + Collector result = + callAcquire(grpc, acquire(fixture), peer("game-session-service", "test")); + + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.value.getHoldIdentityBytes().toByteArray()) + .containsExactly(fixture.identity.canonicalBytes()); + assertThat(HoldIdentity.fromStored(result.value.getHoldIdentityBytes().toByteArray())) + .isEqualTo(fixture.identity); + verify(repository).acquire(fixture.holdRequest, fixture.lifecycleRequest); + } + + @Test + void readReturnsExactEchoAndHistoricalImmutableIdentityOnly() { + Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(repository.readIdentity(any(Request.class))).thenReturn(Optional.of(fixture.identity)); + var grpc = service(repository); + + Collector result = + callRead( + grpc, + read(HOLD_READ_ID.toString(), fixture.holdBytes), + peer("game-session-service", "test")); + + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.value.getReadRequestId()).isEqualTo(HOLD_READ_ID.toString()); + assertThat(result.value.getHoldIdentityBytes().toByteArray()) + .containsExactly(fixture.identity.canonicalBytes()); + verify(repository).readIdentity(fixture.holdRequest); + } + + @Test + void emptyHistoricalReadReturnsNotFoundWithoutAnIdentityPayload() { + Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(repository.readIdentity(any(Request.class))).thenReturn(Optional.empty()); + var grpc = service(repository); + + Collector result = + callRead( + grpc, + read(HOLD_READ_ID.toString(), fixture.holdBytes), + peer("game-session-service", "test")); + + assertThat(result.error).isEqualTo(Status.Code.NOT_FOUND); + assertThat(result.value).isNull(); + verify(repository).readIdentity(fixture.holdRequest); + } + + @Test + void mapsOwnerConflictsAndInconsistentIdentitiesToTheirExactStatuses() { + Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); + var conflictRepository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(conflictRepository.acquire( + any(Request.class), any(WorldCanonicalInstanceLifecycleEvidence.Request.class))) + .thenThrow( + new WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException("conflict")); + when(conflictRepository.readIdentity(any(Request.class))) + .thenThrow( + new WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException("conflict")); + var conflictService = service(conflictRepository); + assertThat( + callAcquire(conflictService, acquire(fixture), peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.ALREADY_EXISTS); + assertThat( + callRead( + conflictService, + read(HOLD_READ_ID.toString(), fixture.holdBytes), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.ALREADY_EXISTS); + + var invalidRepository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(invalidRepository.acquire( + any(Request.class), any(WorldCanonicalInstanceLifecycleEvidence.Request.class))) + .thenThrow( + new WorldCanonicalInitialAdmissionHoldRepository.InvalidHoldIdentityException( + "invalid identity")); + when(invalidRepository.readIdentity(any(Request.class))) + .thenThrow( + new WorldCanonicalInitialAdmissionHoldRepository.InvalidHoldIdentityException( + "invalid identity")); + var invalidService = service(invalidRepository); + assertThat( + callAcquire(invalidService, acquire(fixture), peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat( + callRead( + invalidService, + read(HOLD_READ_ID.toString(), fixture.holdBytes), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + @Test + void rejectsNullOrSubstitutedOwnerIdentityAsFailedPrecondition() { + Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); + var nullRepository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(nullRepository.acquire( + any(Request.class), any(WorldCanonicalInstanceLifecycleEvidence.Request.class))) + .thenReturn(null); + var nullResult = + callAcquire( + service(nullRepository), acquire(fixture), peer("game-session-service", "test")); + assertThat(nullResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + + Request changedRequest = holdRequest("test", "b".repeat(64)); + HoldIdentity substituted = new HoldIdentity(changedRequest, HOLD_ID, HOLD_FENCE); + var substitutedRepository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(substitutedRepository.readIdentity(any(Request.class))) + .thenReturn(Optional.of(substituted)); + var substitutedResult = + callRead( + service(substitutedRepository), + read(HOLD_READ_ID.toString(), fixture.holdBytes), + peer("game-session-service", "test")); + assertThat(substitutedResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + @Test + void mapsTransientStorageToUnavailableAndOtherStorageOrUnknownFailuresToInternal() { + Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); + var transientRepository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(transientRepository.acquire( + any(Request.class), any(WorldCanonicalInstanceLifecycleEvidence.Request.class))) + .thenThrow(new TransientDataAccessException("temporary storage issue") {}); + var transientResult = + callAcquire( + service(transientRepository), acquire(fixture), peer("game-session-service", "test")); + assertThat(transientResult.error).isEqualTo(Status.Code.UNAVAILABLE); + + var permanentRepository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(permanentRepository.readIdentity(any(Request.class))) + .thenThrow( + new DataAccessException("permanent storage issue", new SQLException("bad schema")) {}); + var permanentResult = + callRead( + service(permanentRepository), + read(HOLD_READ_ID.toString(), fixture.holdBytes), + peer("game-session-service", "test")); + assertThat(permanentResult.error).isEqualTo(Status.Code.INTERNAL); + + var unknownRepository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(unknownRepository.readIdentity(any(Request.class))) + .thenThrow(new IllegalStateException("unexpected owner failure")); + var unknownResult = + callRead( + service(unknownRepository), + read(HOLD_READ_ID.toString(), fixture.holdBytes), + peer("game-session-service", "test")); + assertThat(unknownResult.error).isEqualTo(Status.Code.INTERNAL); + } + + private static WorldCanonicalInitialAdmissionHoldGrpcService service( + WorldCanonicalInitialAdmissionHoldRepository repository) { + return new WorldCanonicalInitialAdmissionHoldGrpcService(repository, "test"); + } + + private static Fixture fixture( + String holdNamespace, String lifecycleNamespace, UUID lifecyclePlayableNamespace) { + Request holdRequest = holdRequest(holdNamespace, REQUEST_DIGEST); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + LIFECYCLE_READ_ID, + lifecycleNamespace, + TENANT, + "green-hollow", + GAME_INSTANCE, + lifecyclePlayableNamespace, + "SHARED", + true, + REQUEST_ID, + VERSION, + "sha256:" + "c".repeat(64), + "sha256:" + "d".repeat(64), + "sha256:" + "e".repeat(64)); + return new Fixture( + holdRequest, + holdRequest.canonicalRequestBytes(), + lifecycleRequest, + lifecycleRequest.canonicalBytes(), + new HoldIdentity(holdRequest, HOLD_ID, HOLD_FENCE)); + } + + private static Request holdRequest(String namespace, String digest) { + return new Request( + namespace, + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + VERSION, + 7L, + REQUEST_ID, + digest, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null); + } + + private static AcquireCanonicalInitialAdmissionHoldRequest acquire(Fixture fixture) { + return acquire(fixture.holdBytes, fixture.lifecycleBytes); + } + + private static AcquireCanonicalInitialAdmissionHoldRequest acquire( + byte[] holdBytes, byte[] lifecycleBytes) { + return AcquireCanonicalInitialAdmissionHoldRequest.newBuilder() + .setCanonicalHoldRequestBytes(ByteString.copyFrom(holdBytes)) + .setCanonicalLifecycleReadRequestBytes(ByteString.copyFrom(lifecycleBytes)) + .build(); + } + + private static ReadCanonicalInitialAdmissionHoldIdentityRequest read( + String readId, byte[] holdBytes) { + return ReadCanonicalInitialAdmissionHoldIdentityRequest.newBuilder() + .setReadRequestId(readId) + .setCanonicalHoldRequestBytes(ByteString.copyFrom(holdBytes)) + .build(); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static Collector callAcquire( + WorldCanonicalInitialAdmissionHoldGrpcService service, + AcquireCanonicalInitialAdmissionHoldRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector<>(); + Context context = + peer == null + ? Context.current() + : Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.acquireCanonicalInitialAdmissionHold(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static Collector callRead( + WorldCanonicalInitialAdmissionHoldGrpcService service, + ReadCanonicalInitialAdmissionHoldIdentityRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector<>(); + Context context = + peer == null + ? Context.current() + : Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readCanonicalInitialAdmissionHoldIdentity(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + Request holdRequest, + byte[] holdBytes, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, + byte[] lifecycleBytes, + HoldIdentity identity) {} + + private static final class Collector implements StreamObserver { + private T value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(T response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + assertThat(completed).isFalse(); + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java new file mode 100644 index 0000000000..70b808fd51 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java @@ -0,0 +1,482 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation.CanonicalIdentity; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation.WorldPrepareFields; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInitialAdmissionHoldRepositoryTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID CANONICAL_INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID READ_ID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final String REQUEST_ID = "gs-initial-admission-17"; + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String OTHER_REQUEST_DIGEST = "b".repeat(64); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void acquisitionRejectsAmbientActualAndSynchronizationTransactions() { + Fixture fixture = fixture(noPriorRequest(), activeLifecycle("ACTIVE", 7L), null); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> fixture.repository.acquire(noPriorRequest(), selector(noPriorRequest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not join an ambient transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy( + () -> fixture.repository.acquire(noPriorRequest(), selector(noPriorRequest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not join an ambient transaction"); + + verifyNoInteractions(fixture.dsl, fixture.associations, fixture.lifecycle); + assertThat(fixture.manager.startedWith).isNull(); + } + + @Test + void exactRetryReturnsTheOriginalHoldAndFenceWithoutInsertChurn() { + Request request = noPriorRequest(); + Record existing = storedRow(request, HOLD_ID, HOLD_FENCE); + Fixture fixture = fixture(request, activeLifecycle("ACTIVE", 7L), existing); + + HoldIdentity result = fixture.repository.acquire(request, selector(request)); + + assertThat(result.request()).isEqualTo(request); + assertThat(result.holdId()).isEqualTo(HOLD_ID); + assertThat(result.holdFence()).isEqualTo(HOLD_FENCE); + assertThat(result.canonicalRequestBytes()).containsExactly(request.canonicalRequestBytes()); + assertThat(result.holdBindingDigest()).isEqualTo(request.holdBindingDigest()); + verify(fixture.dsl, never()).execute(anyString(), any(Object[].class)); + verify(fixture.lifecycle).readForActivationInOwnerTransaction(selector(request)); + verify(fixture.associations).readOwnerAssociationInActivationTransaction(CANONICAL_INSTANCE); + } + + @Test + void changedRequestAndLegacyUnmappedCollisionAreDenied() { + Request original = noPriorRequest(); + Request changed = request(OTHER_REQUEST_DIGEST, InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + Fixture changedFixture = + fixture(changed, activeLifecycle("ACTIVE", 7L), storedRow(original, HOLD_ID, HOLD_FENCE)); + + assertThatThrownBy(() -> changedFixture.repository.acquire(changed, selector(changed))) + .isInstanceOf(WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException.class); + verify(changedFixture.dsl, never()).execute(anyString(), any(Object[].class)); + + Fixture legacyFixture = + fixture(original, activeLifecycle("ACTIVE", 7L), legacyStoredRow(original)); + assertThatThrownBy(() -> legacyFixture.repository.acquire(original, selector(original))) + .isInstanceOf( + WorldCanonicalInitialAdmissionHoldRepository.InvalidHoldIdentityException.class); + verify(legacyFixture.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void incompleteMetadataBadBindingDigestAndSubstitutedScopeAreDenied() { + Request request = noPriorRequest(); + + Map incomplete = storedValues(request, HOLD_ID, HOLD_FENCE); + incomplete.remove("canonical_version_id"); + assertStoredRowDenied(request, row(incomplete)); + + Map badDigest = storedValues(request, HOLD_ID, HOLD_FENCE); + badDigest.put("hold_binding_digest", "sha256:" + "0".repeat(64)); + assertStoredRowDenied(request, row(badDigest)); + + Map substitutedScope = storedValues(request, HOLD_ID, HOLD_FENCE); + substitutedScope.put("canonical_world_slug", "different-world"); + assertStoredRowDenied(request, row(substitutedScope)); + } + + @Test + void staleEpochOrNonActiveLifecycleCannotAcquire() { + Request request = noPriorRequest(); + for (WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence : + new WorldCanonicalInstanceLifecycleEvidence[] { + activeLifecycle("PREPARING", 7L), activeLifecycle("ACTIVE", 6L) + }) { + Fixture fixture = fixture(request, lifecycleEvidence, null); + + assertThatThrownBy(() -> fixture.repository.acquire(request, selector(request))) + .isInstanceOf(WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException.class); + + verify(fixture.dsl, never()).execute(anyString(), any(Object[].class)); + verify(fixture.associations, never()) + .readOwnerAssociationInActivationTransaction(CANONICAL_INSTANCE); + } + } + + @Test + void expectClosedAcquisitionPersistsItsTagPriorVersionAndExactRequestReadback() { + Request request = expectClosedRequest(13L); + Fixture fixture = fixture(request, activeLifecycle("ACTIVE", 7L), null); + AtomicReference insertedRow = new AtomicReference<>(); + fixture.holdRow.set(null); + doAnswer( + invocation -> { + Object[] bindings = (Object[]) invocation.getRawArguments()[1]; + insertedRow.set( + storedRow( + request, + UUID.fromString(bindings[0].toString()), + UUID.fromString(bindings[1].toString()))); + fixture.holdRow.set(insertedRow.get()); + return 1; + }) + .when(fixture.dsl) + .execute(anyString(), any(Object[].class)); + + HoldIdentity result = fixture.repository.acquire(request, selector(request)); + + assertThat(result.request()).isEqualTo(request); + assertThat(result.holdBindingDigest()).isNotEqualTo(request.initialAdmissionRequestDigest()); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bindings = ArgumentCaptor.forClass(Object[].class); + verify(fixture.dsl).execute(sql.capture(), bindings.capture()); + assertThat(sql.getValue()).contains("'PENDING'").contains("CURRENT_TIMESTAMP"); + assertThat(sql.getValue()).contains("ON CONFLICT DO NOTHING"); + assertThat(bindings.getValue()[11]).isEqualTo(false); + assertThat(bindings.getValue()[18]).isEqualTo("EXPECT_CLOSED"); + assertThat(bindings.getValue()[19]).isEqualTo(13L); + assertThat(bindings.getValue()[20]).isEqualTo(request.canonicalRequestBytes()); + assertThat(bindings.getValue()[21]).isEqualTo(request.holdBindingDigest()); + assertThat(result.holdId()).isEqualTo(UUID.fromString(bindings.getValue()[0].toString())); + assertThat(result.holdFence()).isEqualTo(UUID.fromString(bindings.getValue()[1].toString())); + } + + @Test + void insertWithoutExactReadbackFailsClosed() { + Request request = noPriorRequest(); + Fixture fixture = fixture(request, activeLifecycle("ACTIVE", 7L), null); + when(fixture.dsl.execute(anyString(), any(Object[].class))).thenReturn(0); + + assertThatThrownBy(() -> fixture.repository.acquire(request, selector(request))) + .isInstanceOf(WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException.class) + .hasMessageContaining("did not produce exact request readback"); + } + + @Test + void conflictInsertUsesExactWinningReadbackWithoutReturningItsCandidateIds() { + Request request = noPriorRequest(); + Fixture fixture = fixture(request, activeLifecycle("ACTIVE", 7L), null); + AtomicReference candidateBindings = new AtomicReference<>(); + doAnswer( + invocation -> { + candidateBindings.set((Object[]) invocation.getRawArguments()[1]); + fixture.holdRow.set(storedRow(request, HOLD_ID, HOLD_FENCE)); + return 0; + }) + .when(fixture.dsl) + .execute(anyString(), any(Object[].class)); + + HoldIdentity result = fixture.repository.acquire(request, selector(request)); + Object[] candidate = candidateBindings.get(); + + assertThat(result.holdId()).isEqualTo(HOLD_ID); + assertThat(result.holdFence()).isEqualTo(HOLD_FENCE); + assertThat(candidate[0]).isNotEqualTo(HOLD_ID); + assertThat(candidate[1]).isNotEqualTo(HOLD_FENCE); + } + + @Test + void identityReadReturnsHistoricalAcquisitionWithoutUsingCurrentLifecycleRead() { + Request request = noPriorRequest(); + Fixture fixture = + fixture( + request, activeLifecycle("TERMINATED", 20L), storedRow(request, HOLD_ID, HOLD_FENCE)); + + Optional result = fixture.repository.readIdentity(request); + + assertThat(result).contains(new HoldIdentity(request, HOLD_ID, HOLD_FENCE)); + verify(fixture.lifecycle, never()) + .readForActivationInOwnerTransaction( + any(WorldCanonicalInstanceLifecycleEvidence.Request.class)); + verify(fixture.associations).readOwnerAssociationInOwnerTransaction(CANONICAL_INSTANCE); + } + + private static void assertStoredRowDenied(Request request, Record storedRow) { + Fixture fixture = fixture(request, activeLifecycle("ACTIVE", 7L), storedRow); + assertThatThrownBy(() -> fixture.repository.acquire(request, selector(request))) + .isInstanceOf(IllegalStateException.class); + verify(fixture.dsl, never()).execute(anyString(), any(Object[].class)); + } + + private static Fixture fixture( + Request request, + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence, + Record existingHold) { + DSLContext dsl = Mockito.mock(DSLContext.class); + RecordingTransactionManager manager = new RecordingTransactionManager(); + WorldCanonicalInstanceAssociationRepository associations = + Mockito.mock(WorldCanonicalInstanceAssociationRepository.class); + WorldCanonicalInstanceLifecycleReadRepository lifecycle = + Mockito.mock(WorldCanonicalInstanceLifecycleReadRepository.class); + WorldCanonicalInstanceAssociation association = association(); + AtomicReference holdRow = new AtomicReference<>(existingHold); + + when(lifecycle.readForActivationInOwnerTransaction(selector(request))) + .thenReturn(Optional.of(lifecycleEvidence)); + when(associations.readOwnerAssociationInActivationTransaction(CANONICAL_INSTANCE)) + .thenReturn(Optional.of(association)); + when(associations.readOwnerAssociationInOwnerTransaction(CANONICAL_INSTANCE)) + .thenReturn(Optional.of(association)); + when(dsl.fetchOne(contains("current_setting"))).thenAnswer(invocation -> transactionState()); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM initial_admission_bind_hold")) { + return holdRow.get(); + } + return null; + }); + + return new Fixture( + new WorldCanonicalInitialAdmissionHoldRepository(dsl, manager, associations, lifecycle), + dsl, + manager, + associations, + lifecycle, + holdRow); + } + + private static WorldCanonicalInstanceAssociation association() { + WorldCanonicalInstanceAssociation association = + Mockito.mock(WorldCanonicalInstanceAssociation.class); + CanonicalIdentity identity = + new CanonicalIdentity( + CANONICAL_INSTANCE, + "prod", + TENANT, + "green-hollow", + PLAYABLE_NAMESPACE, + "SHARED", + true, + "control-request"); + WorldPrepareFields prepareFields = + new WorldPrepareFields( + 31L, + 41L, + 101L, + 1L, + "control-request", + "launch-descriptor", + 12L, + null, + "{}", + "generation-1", + 1L, + "release-ref", + 1L, + null); + when(association.identity()).thenReturn(identity); + when(association.worldPrepareFields()).thenReturn(prepareFields); + when(association.canonicalVersionId()).thenReturn(VERSION); + return association; + } + + private static WorldCanonicalInstanceLifecycleEvidence activeLifecycle( + String status, long epoch) { + WorldCanonicalInstanceLifecycleEvidence evidence = + Mockito.mock(WorldCanonicalInstanceLifecycleEvidence.class); + Request request = noPriorRequest(); + when(evidence.request()).thenReturn(selector(request)); + when(evidence.lifecycleStatus()).thenReturn(status); + when(evidence.lifecycleEpoch()).thenReturn(epoch); + return evidence; + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request selector(Request request) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + READ_ID, + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + true, + "control-request", + request.canonicalVersionId(), + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + } + + private static Request noPriorRequest() { + return request(REQUEST_DIGEST, InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + } + + private static Request expectClosedRequest(long pointerVersion) { + return request(REQUEST_DIGEST, InitialAdmissionOrigin.EXPECT_CLOSED, pointerVersion); + } + + private static Request request( + String digest, InitialAdmissionOrigin origin, Long priorPointerVersion) { + return new Request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + CANONICAL_INSTANCE, + VERSION, + 7L, + REQUEST_ID, + digest, + origin, + 12L, + priorPointerVersion); + } + + private static Record storedRow(Request request, UUID holdId, UUID holdFence) { + return row(storedValues(request, holdId, holdFence)); + } + + private static Map storedValues(Request request, UUID holdId, UUID holdFence) { + Map values = new HashMap<>(); + values.put("hold_id", holdId); + values.put("hold_fence", holdFence); + values.put("tenant_id", 41L); + values.put("realm_uuid", request.realmId()); + values.put("playable_state_namespace_uuid", request.playableStateNamespaceId()); + values.put("playable_state_scope", request.playableStateScope()); + values.put("game_instance_id", 101L); + values.put("version_id", 12L); + values.put("active_lifecycle_epoch", request.activeLifecycleEpoch()); + values.put("initial_admission_request_id", request.initialAdmissionRequestId()); + values.put("request_digest", request.initialAdmissionRequestDigest()); + values.put( + "expected_no_prior_pointer", + request.initialAdmissionOrigin() == InitialAdmissionOrigin.NO_PRIOR_POINTER); + values.put("expected_catalog_revision", request.expectedCatalogRevision()); + values.put("canonical_target_namespace", request.targetNamespace()); + values.put("canonical_tenant_id", request.canonicalTenantId()); + values.put("canonical_world_slug", request.worldSlug()); + values.put("canonical_game_instance_id", request.canonicalGameInstanceId()); + values.put("canonical_version_id", request.canonicalVersionId()); + values.put("initial_admission_origin", request.initialAdmissionOrigin().name()); + values.put("expected_prior_pointer_version", request.expectedPriorPointerVersion()); + values.put("canonical_request_bytes", request.canonicalRequestBytes()); + values.put("hold_binding_digest", request.holdBindingDigest()); + return values; + } + + private static Record legacyStoredRow(Request request) { + Map values = storedValues(request, HOLD_ID, HOLD_FENCE); + values.put("canonical_target_namespace", null); + values.put("canonical_tenant_id", null); + values.put("canonical_world_slug", null); + values.put("canonical_game_instance_id", null); + values.put("canonical_version_id", null); + values.put("initial_admission_origin", null); + values.put("expected_prior_pointer_version", null); + values.put("canonical_request_bytes", null); + values.put("hold_binding_digest", null); + return row(values); + } + + private static Record transactionState() { + boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + String isolationName = + Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ).equals(isolation) + ? "repeatable read" + : "read committed"; + return row(Map.of("isolation", isolationName, "read_only", readOnly ? "on" : "off")); + } + + private static Record row(Map values) { + Record row = Mockito.mock(Record.class); + doAnswer( + invocation -> { + String name = invocation.getArgument(0); + Object value = values.get(name); + Class type = invocation.getArgument(1); + return value == null || type.isInstance(value) ? value : type.cast(value); + }) + .when(row) + .get(anyString(), any(Class.class)); + return row; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + WorldCanonicalInitialAdmissionHoldRepository repository, + DSLContext dsl, + RecordingTransactionManager manager, + WorldCanonicalInstanceAssociationRepository associations, + WorldCanonicalInstanceLifecycleReadRepository lifecycle, + AtomicReference holdRow) {} + + private static final class RecordingTransactionManager + implements org.springframework.transaction.PlatformTransactionManager { + private TransactionDefinition startedWith; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + TransactionDefinition effectiveDefinition = + definition == null ? TransactionDefinition.withDefaults() : definition; + startedWith = effectiveDefinition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly( + effectiveDefinition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + effectiveDefinition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldTerminalGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldTerminalGrpcServiceTest.java new file mode 100644 index 0000000000..16f5779107 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldTerminalGrpcServiceTest.java @@ -0,0 +1,368 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldFinalizationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldTerminalGrpcService; +import net.firedevops.firemud.worldmanagement.v1.FinalizeCanonicalInitialAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.FinalizeCanonicalInitialAdmissionHoldResponse; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Transport component tests; downstream finalization is an explicit service double. */ +class WorldCanonicalInitialAdmissionHoldTerminalGrpcServiceTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + @Test + void rejectsUnverifiedWrongServiceAndWrongNamespacePeersBeforeOwnerAccess() { + var finalizer = mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + var grpc = service(finalizer); + var malformed = + request( + new byte[] {1}, FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome.COMMITTED); + + assertThat(call(grpc, malformed, null).error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(grpc, malformed, peer("account-service", "test")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(grpc, malformed, peer("game-session-service", "other")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(finalizer); + } + + @Test + void rejectsEndUserContextBeforeParsingOrOwnerAccess() { + var finalizer = mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + var grpc = service(finalizer); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Collector result; + try { + result = + call( + grpc, + request( + new byte[] {1}, + FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome.ABORTED), + peer("game-session-service", "test")); + } finally { + SessionContext.clear(); + } + + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(finalizer); + } + + @Test + void rejectsAmbientTransactionsBeforeParsingOrOwnerAccess() { + var finalizer = mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + var grpc = service(finalizer); + var malformed = + request( + new byte[] {1}, FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome.COMMITTED); + + TransactionSynchronizationManager.setActualTransactionActive(true); + Collector actual; + try { + actual = call(grpc, malformed, peer("game-session-service", "test")); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + Collector synchronization; + try { + synchronization = call(grpc, malformed, peer("game-session-service", "test")); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + + assertThat(actual.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(synchronization.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(finalizer); + } + + @Test + void rejectsUnknownFieldsMalformedIdentityAndUnspecifiedOutcome() { + var finalizer = mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + var grpc = service(finalizer); + var fixture = fixture("test"); + var peer = peer("game-session-service", "test"); + var unknown = + request( + fixture.identity.canonicalBytes(), + FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome.COMMITTED) + .toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + + assertThat(call(grpc, unknown, peer).error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + call( + grpc, + request( + new byte[] {1}, + FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome.COMMITTED), + peer) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + call( + grpc, + request( + fixture.identity.canonicalBytes(), + FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome + .EXPECTED_OUTCOME_UNSPECIFIED), + peer) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(finalizer); + } + + @Test + void rejectsNamespaceMismatchBeforeOwnerAccess() { + var finalizer = mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + var grpc = service(finalizer); + var fixture = fixture("other"); + + assertThat( + call( + grpc, + request( + fixture.identity.canonicalBytes(), + FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome.COMMITTED), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(finalizer); + } + + @Test + void componentOnlyCommittedSelectionReturnsCompleteOwnerProofBytes() { + var finalizer = mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + var grpc = service(finalizer); + var fixture = fixture("test"); + var proof = + proof(fixture.identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + when(finalizer.finalizeHold( + fixture.identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .thenReturn(proof); + + var result = + call( + grpc, + request( + fixture.identity.canonicalBytes(), + FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome.COMMITTED), + peer("game-session-service", "test")); + + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.value.getOwnerProofBytes().toByteArray()) + .containsExactly(GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof)); + verify(finalizer) + .finalizeHold( + fixture.identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + } + + @Test + void componentOnlyAbortedSelectionReturnsCompleteOwnerProofBytes() { + var finalizer = mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + var grpc = service(finalizer); + var fixture = fixture("test"); + var proof = + proof(fixture.identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + when(finalizer.finalizeHold( + fixture.identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)) + .thenReturn(proof); + + var result = + call( + grpc, + request( + fixture.identity.canonicalBytes(), + FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome.ABORTED), + peer("game-session-service", "test")); + + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.value.getOwnerProofBytes().toByteArray()) + .containsExactly(GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof)); + verify(finalizer) + .finalizeHold( + fixture.identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + } + + @Test + void rejectsSubstitutedReturnedIdentityOrOutcome() { + var finalizer = mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + var grpc = service(finalizer); + var fixture = fixture("test"); + var substituted = fixture("test", uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc")); + when(finalizer.finalizeHold( + fixture.identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .thenReturn( + proof( + substituted.identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + + var wrongIdentity = + call( + grpc, + request( + fixture.identity.canonicalBytes(), + FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome.COMMITTED), + peer("game-session-service", "test")); + when(finalizer.finalizeHold( + fixture.identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)) + .thenReturn( + proof( + fixture.identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + var wrongOutcome = + call( + grpc, + request( + fixture.identity.canonicalBytes(), + FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome.ABORTED), + peer("game-session-service", "test")); + + assertThat(wrongIdentity.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(wrongOutcome.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + private static WorldCanonicalInitialAdmissionHoldTerminalGrpcService service( + WorldCanonicalInitialAdmissionHoldFinalizationService finalizer) { + return new WorldCanonicalInitialAdmissionHoldTerminalGrpcService(finalizer, "test"); + } + + private static Fixture fixture(String namespace) { + return fixture(namespace, HOLD_ID); + } + + private static Fixture fixture(String namespace, UUID holdId) { + Request request = + new Request( + namespace, + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + "a".repeat(64), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null); + return new Fixture(request, new HoldIdentity(request, holdId, HOLD_FENCE)); + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof proof( + HoldIdentity identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome) { + return outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED + ? new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + outcome, + 1L, + 42L, + "sha256:" + "b".repeat(64), + false, + Instant.parse("2026-10-07T00:00:00Z")) + : new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + outcome, + null, + null, + "sha256:" + "b".repeat(64), + true, + Instant.parse("2026-10-07T00:00:00Z")); + } + + private static FinalizeCanonicalInitialAdmissionHoldRequest request( + byte[] identityBytes, FinalizeCanonicalInitialAdmissionHoldRequest.ExpectedOutcome outcome) { + return FinalizeCanonicalInitialAdmissionHoldRequest.newBuilder() + .setHoldIdentityBytes(ByteString.copyFrom(identityBytes)) + .setExpectedOutcome(outcome) + .build(); + } + + private static Collector call( + WorldCanonicalInitialAdmissionHoldTerminalGrpcService service, + FinalizeCanonicalInitialAdmissionHoldRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector<>(); + Context context = + peer == null + ? Context.current() + : Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.finalizeCanonicalInitialAdmissionHold(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture(Request request, HoldIdentity identity) {} + + private static final class Collector implements StreamObserver { + private T value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(T response) { + value = response; + } + + @Override + public void onError(Throwable throwable) { + error = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java new file mode 100644 index 0000000000..391426e176 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java @@ -0,0 +1,514 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.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 java.math.BigInteger; +import java.net.InetSocketAddress; +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.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GameplaySessionAttestationService; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.PublicationReadGuard; +import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; +import net.firedevops.firemud.worldmanagement.service.PingService; +import net.firedevops.firemud.worldmanagement.service.RoomService; +import net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.service.WorldInstanceActivationService; +import net.firedevops.firemud.worldmanagement.service.WorldUpgradeValidationService; +import net.firedevops.firemud.worldmanagement.service.impl.WorldManagementGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldFinalizationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldTerminalGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.FinalizeCanonicalInitialAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldServiceGrpc; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldTerminalServiceGrpc; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; +import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; +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.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; +import tools.jackson.databind.ObjectMapper; + +/** Physical socket proof for the exact-method-protected canonical first-admission handlers. */ +class WorldCanonicalInitialAdmissionMtlsTest { + private static final String NAMESPACE = "test"; + private static final String JWT_SECRET = "test-secret-key-test-secret-key-32-bytes"; + private static final AtomicLong CERTIFICATE_SERIAL = new AtomicLong(1); + private static final String ACQUIRE_METHOD = + WorldCanonicalInitialAdmissionHoldServiceGrpc.getAcquireCanonicalInitialAdmissionHoldMethod() + .getFullMethodName(); + private static final String IDENTITY_READ_METHOD = + WorldCanonicalInitialAdmissionHoldServiceGrpc + .getReadCanonicalInitialAdmissionHoldIdentityMethod() + .getFullMethodName(); + private static final String LIFECYCLE_READ_METHOD = + WorldCanonicalInstanceLifecycleReadServiceGrpc.getReadWorldCanonicalInstanceLifecycleMethod() + .getFullMethodName(); + private static final String TERMINAL_METHOD = + WorldCanonicalInitialAdmissionHoldTerminalServiceGrpc + .getFinalizeCanonicalInitialAdmissionHoldMethod() + .getFullMethodName(); + private static TestPki pki; + + private final WorldCanonicalInitialAdmissionHoldRepository holdRepository = + mock(WorldCanonicalInitialAdmissionHoldRepository.class); + private final WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository = + mock(WorldCanonicalInstanceLifecycleReadRepository.class); + private final WorldCanonicalInitialAdmissionHoldFinalizationService finalizationService = + mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + private final PingService pingService = mock(PingService.class); + private final RoomService roomService = mock(RoomService.class); + private final WorldInstanceActivationService activationService = + mock(WorldInstanceActivationService.class); + private final WorldDraftDesignDigestService draftDesignDigestService = + mock(WorldDraftDesignDigestService.class); + private final WorldDesignMutationService mutationService = mock(WorldDesignMutationService.class); + private final WorldUpgradeValidationService validationService = + mock(WorldUpgradeValidationService.class); + private final GameplaySessionAttestationService attestationService = + mock(GameplaySessionAttestationService.class); + private final InitialAdmissionBindHoldService bindHoldService = + mock(InitialAdmissionBindHoldService.class); + + private Server server; + + @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=World Canonical Admission Test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate(caName, caKeyPair.getPublic(), caName, caKeyPair.getPrivate(), true, null); + pki = + new TestPki( + caCertificate, + issueLeaf( + caName, + caKeyPair.getPrivate(), + List.of(workloadUri(NAMESPACE, "world-management-service"))), + issueLeaf( + caName, + caKeyPair.getPrivate(), + List.of(workloadUri(NAMESPACE, "game-session-service"))), + issueLeaf( + caName, caKeyPair.getPrivate(), List.of(workloadUri(NAMESPACE, "account-service"))), + issueLeaf( + caName, + caKeyPair.getPrivate(), + List.of(workloadUri("other-test", "game-session-service"))), + issueLeaf(caName, caKeyPair.getPrivate(), List.of()), + issueLeaf( + caName, + caKeyPair.getPrivate(), + List.of( + workloadUri(NAMESPACE, "game-session-service"), + workloadUri(NAMESPACE, "account-service")))); + } + + @BeforeEach + void startPhysicalReceiver() throws Exception { + var holdService = new WorldCanonicalInitialAdmissionHoldGrpcService(holdRepository, NAMESPACE); + var lifecycleService = + new WorldCanonicalInstanceLifecycleReadGrpcService(lifecycleRepository, NAMESPACE); + var terminalService = + new WorldCanonicalInitialAdmissionHoldTerminalGrpcService(finalizationService, NAMESPACE); + var legacyMutationService = + new WorldManagementGrpcService( + pingService, + roomService, + activationService, + draftDesignDigestService, + mutationService, + validationService, + attestationService, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry(), + new ObjectMapper(), + new PublicationReadGuard(NAMESPACE)); + legacyMutationService.configureInitialAdmissionBindHoldBoundary(bindHoldService, NAMESPACE); + + var authInterceptor = + new AuthTokenInterceptor( + new JwtUtil(JWT_SECRET, 60_000L), publicMethods("application.yml")); + var peerInterceptor = new GrpcPeerIdentityInterceptor(); + 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(ServerInterceptors.intercept(holdService, authInterceptor, peerInterceptor)) + .addService( + ServerInterceptors.intercept(lifecycleService, authInterceptor, peerInterceptor)) + .addService( + ServerInterceptors.intercept(terminalService, authInterceptor, peerInterceptor)) + .addService( + ServerInterceptors.intercept( + legacyMutationService, authInterceptor, peerInterceptor)) + .build() + .start(); + } + + @AfterEach + void stopPhysicalReceiver() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void exactSameNamespaceGameSessionCertificateReachesAllFourHandlersWithoutBearer() + throws Exception { + ManagedChannel channel = channel(pki.gameSessionClient()); + try { + assertInvalidArgument( + () -> + holdStub(channel) + .acquireCanonicalInitialAdmissionHold( + AcquireCanonicalInitialAdmissionHoldRequest.getDefaultInstance())); + assertInvalidArgument( + () -> + holdStub(channel) + .readCanonicalInitialAdmissionHoldIdentity( + ReadCanonicalInitialAdmissionHoldIdentityRequest.getDefaultInstance())); + assertInvalidArgument( + () -> + lifecycleStub(channel) + .readWorldCanonicalInstanceLifecycle( + ReadWorldCanonicalInstanceLifecycleRequest.getDefaultInstance())); + assertInvalidArgument( + () -> + terminalStub(channel) + .finalizeCanonicalInitialAdmissionHold( + FinalizeCanonicalInitialAdmissionHoldRequest.getDefaultInstance())); + } finally { + stopChannel(channel); + } + verifyNoOwnerCalls(); + } + + @Test + void wrongServiceNamespaceMissingAndAmbiguousWorkloadIdentitiesAreDeniedBeforeOwnerAccess() + throws Exception { + assertAllProtectedMethodsDenied(pki.accountClient()); + assertAllProtectedMethodsDenied(pki.foreignNamespaceGameSessionClient()); + assertAllProtectedMethodsDenied(pki.sharedLegacyClient()); + assertAllProtectedMethodsDenied(pki.ambiguousWorkloadClient()); + verifyNoOwnerCalls(); + } + + @Test + void clientWithoutCertificateCannotReachProtectedHandlerOrOwner() throws Exception { + ManagedChannel channel = channelWithoutCertificate(); + Throwable failure = null; + try { + holdStub(channel) + .acquireCanonicalInitialAdmissionHold( + AcquireCanonicalInitialAdmissionHoldRequest.getDefaultInstance()); + } catch (Throwable transportFailure) { + failure = transportFailure; + } finally { + stopChannel(channel); + } + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE); + verifyNoOwnerCalls(); + } + + @Test + void unrelatedWorldMutationMethodStillRequiresBearerAuthentication() throws Exception { + assertThat(publicMethods("application.yml")) + .containsExactlyInAnyOrder( + "world_management.v1.WorldManagementService/Ping", + "world_management.v1.WorldManagementService/GetDraftDesignDigest", + "world_management.v1.WorldAuthoredSourceIntakeService/IntakeAuthoredWorldSource", + "world_management.v1.WorldAuthoredSourceIntakeService/ReadAuthoredWorldSourceIntake", + ACQUIRE_METHOD, + IDENTITY_READ_METHOD, + LIFECYCLE_READ_METHOD, + TERMINAL_METHOD); + assertThat(publicMethods("application.yml")) + .doesNotContain( + WorldManagementServiceGrpc.getApplyWorldDesignMutationMethod().getFullMethodName()); + + ManagedChannel channel = channel(pki.gameSessionClient()); + Throwable failure = null; + try { + WorldManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .applyWorldDesignMutation( + net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationRequest + .getDefaultInstance()); + } catch (Throwable transportFailure) { + failure = transportFailure; + } finally { + stopChannel(channel); + } + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(Status.fromThrowable(failure).getDescription()).isEqualTo("Missing token"); + verifyNoOwnerCalls(); + } + + private void assertAllProtectedMethodsDenied(TestCertificate certificate) throws Exception { + ManagedChannel channel = channel(certificate); + try { + assertPermissionDenied( + () -> + holdStub(channel) + .acquireCanonicalInitialAdmissionHold( + AcquireCanonicalInitialAdmissionHoldRequest.getDefaultInstance())); + assertPermissionDenied( + () -> + holdStub(channel) + .readCanonicalInitialAdmissionHoldIdentity( + ReadCanonicalInitialAdmissionHoldIdentityRequest.getDefaultInstance())); + assertPermissionDenied( + () -> + lifecycleStub(channel) + .readWorldCanonicalInstanceLifecycle( + ReadWorldCanonicalInstanceLifecycleRequest.getDefaultInstance())); + assertPermissionDenied( + () -> + terminalStub(channel) + .finalizeCanonicalInitialAdmissionHold( + FinalizeCanonicalInitialAdmissionHoldRequest.getDefaultInstance())); + } finally { + stopChannel(channel); + } + } + + private WorldCanonicalInitialAdmissionHoldServiceGrpc + .WorldCanonicalInitialAdmissionHoldServiceBlockingStub + holdStub(ManagedChannel channel) { + return WorldCanonicalInitialAdmissionHoldServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private WorldCanonicalInstanceLifecycleReadServiceGrpc + .WorldCanonicalInstanceLifecycleReadServiceBlockingStub + lifecycleStub(ManagedChannel channel) { + return WorldCanonicalInstanceLifecycleReadServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private WorldCanonicalInitialAdmissionHoldTerminalServiceGrpc + .WorldCanonicalInitialAdmissionHoldTerminalServiceBlockingStub + terminalStub(ManagedChannel channel) { + return WorldCanonicalInitialAdmissionHoldTerminalServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private ManagedChannel channel(TestCertificate clientCertificate) throws Exception { + return NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager(clientCertificate.privateKey(), clientCertificate.certificate()) + .build()) + .build(); + } + + private ManagedChannel channelWithoutCertificate() throws Exception { + return NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .sslContext(GrpcSslContexts.forClient().trustManager(pki.caCertificate()).build()) + .build(); + } + + private static void assertInvalidArgument(Runnable rpc) { + assertStatus(rpc, Status.Code.INVALID_ARGUMENT); + } + + private static void assertPermissionDenied(Runnable rpc) { + assertStatus(rpc, Status.Code.PERMISSION_DENIED); + } + + private static void assertStatus(Runnable rpc, Status.Code expected) { + Throwable failure = null; + try { + rpc.run(); + } catch (Throwable rpcFailure) { + failure = rpcFailure; + } + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected); + } + + private static Set publicMethods(String resourceName) throws Exception { + 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 void verifyNoOwnerCalls() { + verifyNoInteractions( + holdRepository, + lifecycleRepository, + finalizationService, + pingService, + roomService, + activationService, + draftDesignDigestService, + mutationService, + validationService, + attestationService, + bindHoldService); + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static String workloadUri(String namespace, String serviceName) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + serviceName; + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caPrivateKey, List workloadUris) throws Exception { + KeyPair keyPair = newRsaKeyPair(); + X500Name subject = new X500Name("CN=FireMUD Test Workload, O=FireMUD Test"); + List subjectAltNames = new ArrayList<>(); + workloadUris.forEach( + uri -> subjectAltNames.add(new GeneralName(GeneralName.uniformResourceIdentifier, uri))); + subjectAltNames.add(new GeneralName(GeneralName.dNSName, "localhost")); + subjectAltNames.add(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); + X509Certificate certificate = + issueCertificate( + subject, + keyPair.getPublic(), + caName, + caPrivateKey, + false, + new GeneralNames(subjectAltNames.toArray(GeneralName[]::new))); + 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 TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate worldServer, + TestCertificate gameSessionClient, + TestCertificate accountClient, + TestCertificate foreignNamespaceGameSessionClient, + TestCertificate sharedLegacyClient, + TestCertificate ambiguousWorkloadClient) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationServiceTest.java new file mode 100644 index 0000000000..f15380dc96 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationServiceTest.java @@ -0,0 +1,142 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationService; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInitialPlayerLocationServiceTest { + @Test + void defaultServiceDeniesPlacementBeforeRepositoryAccess() { + var repository = mock(WorldCanonicalInitialPlayerLocationRepository.class); + var service = new WorldCanonicalInitialPlayerLocationService(repository); + + assertThatThrownBy(() -> service.place(request())) + .isInstanceOf(WorldCanonicalInitialPlayerLocationService.PlacementDeniedException.class) + .hasMessageContaining("authenticated current Entity assignment"); + + verify(repository, never()) + .place(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + } + + @Test + void currentHeldAuthorityIsRequiredAndReleasedOnEveryRetry() { + var repository = mock(WorldCanonicalInitialPlayerLocationRepository.class); + var request = request(); + var result = WorldCanonicalInitialPlayerLocation.Result.conflict(request, "TEST_CONFLICT"); + when(repository.place( + org.mockito.ArgumentMatchers.eq(request), org.mockito.ArgumentMatchers.any())) + .thenReturn(result); + AtomicInteger checks = new AtomicInteger(); + AtomicInteger closes = new AtomicInteger(); + var service = + new WorldCanonicalInitialPlayerLocationService( + repository, + ignored -> + new WorldCanonicalInitialPlayerLocationService.HeldPlacementAuthority() { + private boolean held = true; + + @Override + public void requireHeld() { + if (!held) throw new IllegalStateException("authority was released"); + checks.incrementAndGet(); + } + + @Override + public void close() { + held = false; + closes.incrementAndGet(); + } + }); + + service.place(request); + service.place(request); + + verify(repository, org.mockito.Mockito.times(2)) + .place(org.mockito.ArgumentMatchers.eq(request), org.mockito.ArgumentMatchers.any()); + org.assertj.core.api.Assertions.assertThat(checks).hasValue(4); + org.assertj.core.api.Assertions.assertThat(closes).hasValue(2); + } + + private static WorldCanonicalInitialPlayerLocation.Request request() { + UUID tenant = uuid("10000000-0000-4000-8000-000000000001"); + UUID instance = uuid("20000000-0000-4000-8000-000000000001"); + UUID namespace = uuid("30000000-0000-4000-8000-000000000001"); + var lifecycleRequest = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(lifecycleRequest.canonicalTenantId()).thenReturn(tenant); + when(lifecycleRequest.worldSlug()).thenReturn("starter-world"); + when(lifecycleRequest.canonicalGameInstanceId()).thenReturn(instance); + when(lifecycleRequest.playableStateNamespaceId()).thenReturn(namespace); + when(lifecycleRequest.playableStateScope()).thenReturn("SHARED"); + when(lifecycleRequest.canonicalVersionId()) + .thenReturn(uuid("70000000-0000-4000-8000-000000000001")); + var lifecycle = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(lifecycle.lifecycleStatus()).thenReturn("ACTIVE"); + when(lifecycle.request()).thenReturn(lifecycleRequest); + var room = + new net.firedevops.firemud.common.world.RoomTemplateRef( + tenant, + uuid("70000000-0000-4000-8000-000000000001"), + uuid("80000000-0000-4000-8000-000000000001")); + when(lifecycle.startLocation()).thenReturn(room); + when(lifecycle.runtimeRoomInstanceId()).thenReturn(23L); + when(lifecycle.canonicalBytes()) + .thenReturn( + ("{\"schema\":\"world-canonical-instance-lifecycle-evidence/v1\"," + + "\"lifecycleStatus\":\"ACTIVE\",\"lifecycleEpoch\":\"1\",\"request\":{" + + "\"readRequestId\":\"b0000000-0000-4000-8000-000000000001\"," + + "\"canonicalTenantId\":\"" + + tenant + + "\",\"canonicalVersionId\":\"70000000-0000-4000-8000-000000000001\"," + + "\"worldSlug\":\"starter-world\",\"canonicalGameInstanceId\":\"" + + instance + + "\"," + + "\"playableStateNamespaceId\":\"" + + namespace + + "\",\"playableStateScope\":\"SHARED\"}," + + "\"startLocation\":{\"tenantId\":\"" + + tenant + + "\"," + + "\"versionId\":\"70000000-0000-4000-8000-000000000001\"," + + "\"roomTemplateId\":\"80000000-0000-4000-8000-000000000001\"}," + + "\"runtimeRoomInstanceId\":\"23\"}") + .getBytes(StandardCharsets.UTF_8)); + return new WorldCanonicalInitialPlayerLocation.Request( + uuid("40000000-0000-4000-8000-000000000001"), + tenant, + uuid("50000000-0000-4000-8000-000000000001"), + "starter-world", + instance, + namespace, + "SHARED", + uuid("60000000-0000-4000-8000-000000000001"), + uuid("70000000-0000-4000-8000-000000000001"), + uuid("80000000-0000-4000-8000-000000000001"), + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + uuid("90000000-0000-4000-8000-000000000001"), + uuid("a0000000-0000-4000-8000-000000000001"), + "initial-request", + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + 1, + "owner-proof", + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", + "pointer-audit", + 1, + WorldCanonicalInitialPlayerLocation.InitialAdmissionOrigin.NO_PRIOR_POINTER, + lifecycle); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationGrpcServiceTest.java new file mode 100644 index 0000000000..b62fdb37c9 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationGrpcServiceTest.java @@ -0,0 +1,420 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; +import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceResponse; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInstanceActivationGrpcServiceTest { + private static final UUID ACTIVATION_ID = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID OTHER_ACTIVATION_ID = + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + @Test + void rejectsMissingWrongOrWrongNamespacePeerBeforeDecodingOrOwnerAccess() { + var activationService = mock(WorldCanonicalInstanceActivationService.class); + var grpc = new WorldCanonicalInstanceActivationGrpcService(activationService, "test"); + var malformed = request("not-a-uuid", new byte[] {1}); + + Collector missing = call(grpc, malformed, null); + Collector wrongService = call(grpc, malformed, peer("account-service", "test")); + Collector wrongPeerNamespace = call(grpc, malformed, peer("game-session-service", "other")); + + assertThat(missing.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongService.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongPeerNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(activationService); + } + + @Test + void rejectsEndUserContextBeforeDecodingOrOwnerAccess() { + var activationService = mock(WorldCanonicalInstanceActivationService.class); + var grpc = new WorldCanonicalInstanceActivationGrpcService(activationService, "test"); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Collector result; + try { + result = + call(grpc, request("not-a-uuid", new byte[] {1}), peer("game-session-service", "test")); + } finally { + SessionContext.clear(); + } + + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(activationService); + } + + @Test + void rejectsAmbientTransactionOrSynchronizationBeforeDecodingOrOwnerAccess() { + var activationService = mock(WorldCanonicalInstanceActivationService.class); + var grpc = new WorldCanonicalInstanceActivationGrpcService(activationService, "test"); + var malformed = request("not-a-uuid", new byte[] {1}); + + TransactionSynchronizationManager.setActualTransactionActive(true); + Collector transactionResult; + try { + transactionResult = call(grpc, malformed, peer("game-session-service", "test")); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + Collector synchronizationResult; + try { + synchronizationResult = call(grpc, malformed, peer("game-session-service", "test")); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + + assertThat(transactionResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(synchronizationResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(activationService); + } + + @Test + void rejectsUnknownMalformedAndNoncanonicalRequestBeforeOwnerAccess() { + var activationService = mock(WorldCanonicalInstanceActivationService.class); + var grpc = new WorldCanonicalInstanceActivationGrpcService(activationService, "test"); + var unknown = + request(ACTIVATION_ID.toString(), new byte[] {1}).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + Collector unknownField = call(grpc, unknown, peer("game-session-service", "test")); + Collector malformedEvidence = + call( + grpc, + request(ACTIVATION_ID.toString(), "not-json".getBytes(StandardCharsets.UTF_8)), + peer("game-session-service", "test")); + Collector uppercaseId = + call( + grpc, + request(ACTIVATION_ID.toString().toUpperCase(), new byte[] {1}), + peer("game-session-service", "test")); + + assertThat(unknownField.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(malformedEvidence.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(uppercaseId.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(activationService); + } + + @Test + void rejectsEvidenceFromAnotherNamespaceBeforeOwnerAccess() { + var activationService = mock(WorldCanonicalInstanceActivationService.class); + var grpc = new WorldCanonicalInstanceActivationGrpcService(activationService, "test"); + Fixture otherNamespace = fixture("other", "11111111-1111-4111-8111-111111111111", "source-a"); + try (MockedStatic parser = + mockStatic(WorldCanonicalInstanceLifecycleEvidence.class)) { + parser + .when(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(otherNamespace.bytes)) + .thenReturn(otherNamespace.preparing); + + Collector result = + call( + grpc, + request(ACTIVATION_ID.toString(), otherNamespace.bytes), + peer("game-session-service", "test")); + + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(activationService); + } + } + + @Test + void defaultVerifierDeniesNewOperationWithoutOwnerMutation() { + var repository = mock(WorldCanonicalInstanceActivationRepository.class); + var actualService = new WorldCanonicalInstanceActivationService(repository); + var grpc = new WorldCanonicalInstanceActivationGrpcService(actualService, "test"); + Fixture preparing = fixture("test", "11111111-1111-4111-8111-111111111111", "source-a"); + when(repository.readResult(any())).thenReturn(Optional.empty()); + + try (MockedStatic parser = + mockStatic(WorldCanonicalInstanceLifecycleEvidence.class)) { + parser + .when(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(preparing.bytes)) + .thenReturn(preparing.preparing); + + Collector result = + call( + grpc, + request(ACTIVATION_ID.toString(), preparing.bytes), + peer("game-session-service", "test")); + + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + ArgumentCaptor captor = + ArgumentCaptor.forClass(WorldCanonicalInstanceActivation.Request.class); + verify(repository).readResult(captor.capture()); + assertThat(captor.getValue().activationRequestId()).isEqualTo(ACTIVATION_ID); + assertThat(captor.getValue().preparingEvidenceBytes()).containsExactly(preparing.bytes); + verify(repository, never()).activate(any(), any()); + } + } + + @Test + void exactRetryWithNewReadCorrelationReturnsOriginalImmutableResultAndStableId() { + var repository = mock(WorldCanonicalInstanceActivationRepository.class); + Fixture original = fixture("test", "11111111-1111-4111-8111-111111111111", "source-a"); + Fixture retry = fixture("test", "22222222-2222-4222-8222-222222222222", "source-a"); + var originalRequest = + new WorldCanonicalInstanceActivation.Request(ACTIVATION_ID, original.preparing); + var retryRequest = new WorldCanonicalInstanceActivation.Request(ACTIVATION_ID, retry.preparing); + var active = lifecycleEvidence(original.lifecycleRequest, "ACTIVE", 4L, 1L, "active-result"); + var originalResult = + new WorldCanonicalInstanceActivation.Result( + originalRequest, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, active); + when(repository.readResult(any())).thenReturn(Optional.of(originalResult)); + var actualService = new WorldCanonicalInstanceActivationService(repository); + var grpc = new WorldCanonicalInstanceActivationGrpcService(actualService, "test"); + + try (MockedStatic parser = + mockStatic(WorldCanonicalInstanceLifecycleEvidence.class)) { + parser + .when(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(original.bytes)) + .thenReturn(original.preparing); + parser + .when(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(retry.bytes)) + .thenReturn(retry.preparing); + + Collector response = + call( + grpc, + request(ACTIVATION_ID.toString(), retry.bytes), + peer("game-session-service", "test")); + + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value.getActivationRequestId()).isEqualTo(ACTIVATION_ID.toString()); + assertThat(response.value.getCanonicalResultBytes().toByteArray()) + .containsExactly(originalResult.canonicalBytes()); + ArgumentCaptor captor = + ArgumentCaptor.forClass(WorldCanonicalInstanceActivation.Request.class); + verify(repository).readResult(captor.capture()); + assertThat(captor.getValue().canonicalRequestBytes()) + .containsExactly(retryRequest.canonicalRequestBytes()); + verify(repository, never()).activate(any(), any()); + } + } + + @Test + void rejectsReturnedResultForChangedOperationIdentity() { + var activationService = mock(WorldCanonicalInstanceActivationService.class); + Fixture requested = fixture("test", "11111111-1111-4111-8111-111111111111", "source-a"); + Fixture changed = fixture("test", "11111111-1111-4111-8111-111111111111", "source-b"); + var changedRequest = + new WorldCanonicalInstanceActivation.Request(OTHER_ACTIVATION_ID, changed.preparing); + var changedResult = + new WorldCanonicalInstanceActivation.Result( + changedRequest, + WorldCanonicalInstanceActivation.Outcome.ABORTED, + "PRECONDITION_FAILED", + changed.preparing); + when(activationService.activate(any())).thenReturn(changedResult); + var grpc = new WorldCanonicalInstanceActivationGrpcService(activationService, "test"); + + try (MockedStatic parser = + mockStatic(WorldCanonicalInstanceLifecycleEvidence.class)) { + parser + .when(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(requested.bytes)) + .thenReturn(requested.preparing); + + Collector response = + call( + grpc, + request(ACTIVATION_ID.toString(), requested.bytes), + peer("game-session-service", "test")); + + assertThat(response.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(response.value).isNull(); + verify(activationService).activate(any()); + } + } + + @Test + void mapsTransientStorageToUnavailableAndPermanentStorageToInternal() { + Fixture preparing = fixture("test", "11111111-1111-4111-8111-111111111111", "source-a"); + var transientService = mock(WorldCanonicalInstanceActivationService.class); + when(transientService.activate(any())) + .thenThrow(new TransientDataAccessException("temporary store issue") {}); + var permanentService = mock(WorldCanonicalInstanceActivationService.class); + when(permanentService.activate(any())) + .thenThrow( + new DataAccessException("permanent store issue", new SQLException("bad schema")) {}); + var transientGrpc = new WorldCanonicalInstanceActivationGrpcService(transientService, "test"); + var permanentGrpc = new WorldCanonicalInstanceActivationGrpcService(permanentService, "test"); + + try (MockedStatic parser = + mockStatic(WorldCanonicalInstanceLifecycleEvidence.class)) { + parser + .when(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(preparing.bytes)) + .thenReturn(preparing.preparing); + + Collector transientResult = + call( + transientGrpc, + request(ACTIVATION_ID.toString(), preparing.bytes), + peer("game-session-service", "test")); + Collector permanentResult = + call( + permanentGrpc, + request(ACTIVATION_ID.toString(), preparing.bytes), + peer("game-session-service", "test")); + + assertThat(transientResult.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(permanentResult.error).isEqualTo(Status.Code.INTERNAL); + } + } + + @Test + void mapsChangedOperationIdentityToIdempotencyConflict() { + Fixture preparing = fixture("test", "11111111-1111-4111-8111-111111111111", "source-a"); + var activationService = mock(WorldCanonicalInstanceActivationService.class); + when(activationService.activate(any())) + .thenThrow( + new WorldCanonicalInstanceActivationRepository.ActivationConflictException( + "request identity changed")); + var grpc = new WorldCanonicalInstanceActivationGrpcService(activationService, "test"); + + try (MockedStatic parser = + mockStatic(WorldCanonicalInstanceLifecycleEvidence.class)) { + parser + .when(() -> WorldCanonicalInstanceLifecycleEvidence.fromStored(preparing.bytes)) + .thenReturn(preparing.preparing); + + Collector response = + call( + grpc, + request(ACTIVATION_ID.toString(), preparing.bytes), + peer("game-session-service", "test")); + + assertThat(response.error).isEqualTo(Status.Code.ALREADY_EXISTS); + verify(activationService).activate(any()); + } + } + + private static Fixture fixture(String namespace, String readId, String binding) { + byte[] bytes = + ("{\"request\":{\"readRequestId\":\"" + + readId + + "\",\"targetNamespace\":\"" + + namespace + + "\",\"binding\":\"" + + binding + + "\"}}") + .getBytes(StandardCharsets.UTF_8); + var lifecycleRequest = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(lifecycleRequest.targetNamespace()).thenReturn(namespace); + var preparing = lifecycleEvidence(lifecycleRequest, "PREPARING", 3L, 0L, readId + binding); + when(preparing.canonicalBytes()).thenReturn(bytes); + return new Fixture(bytes, lifecycleRequest, preparing); + } + + private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence( + WorldCanonicalInstanceLifecycleEvidence.Request request, + String state, + long epoch, + long rowVersion, + String representation) { + var evidence = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(evidence.request()).thenReturn(request); + when(evidence.lifecycleStatus()).thenReturn(state); + when(evidence.lifecycleEpoch()).thenReturn(epoch); + when(evidence.rowVersion()).thenReturn(rowVersion); + when(evidence.canonicalBytes()) + .thenReturn( + ("{\"request\":{\"representation\":\"" + representation + "\"}}") + .getBytes(StandardCharsets.UTF_8)); + return evidence; + } + + private static ActivateCanonicalWorldInstanceRequest request( + String activationId, byte[] evidence) { + return ActivateCanonicalWorldInstanceRequest.newBuilder() + .setActivationRequestId(activationId) + .setPreparingLifecycleEvidenceBytes(ByteString.copyFrom(evidence)) + .build(); + } + + private static Collector call( + WorldCanonicalInstanceActivationGrpcService service, + ActivateCanonicalWorldInstanceRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector(); + Context context = + peer == null + ? Context.current() + : Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.activateCanonicalWorldInstance(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private record Fixture( + byte[] bytes, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, + WorldCanonicalInstanceLifecycleEvidence preparing) {} + + private static final class Collector + implements StreamObserver { + private ActivateCanonicalWorldInstanceResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ActivateCanonicalWorldInstanceResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + assertThat(completed).isFalse(); + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java new file mode 100644 index 0000000000..2e741f40bf --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java @@ -0,0 +1,80 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInstanceActivationRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final WorldCanonicalInstanceLifecycleReadRepository lifecycle = + mock(WorldCanonicalInstanceLifecycleReadRepository.class); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void immutableResultReadRejectsAmbientTransactionBeforeRepositoryOrDatabaseUse() { + var repository = new WorldCanonicalInstanceActivationRepository(dsl, manager, lifecycle); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.readResult(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not join an ambient transaction"); + + verifyNoInteractions(dsl, manager, lifecycle); + } + + @Test + void activationRejectsAmbientTransactionBeforeOpeningItsOwnerCas() { + var repository = new WorldCanonicalInstanceActivationRepository(dsl, manager, lifecycle); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + repository.activate( + request(), + new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() {} + + public void close() {} + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not join an ambient transaction"); + + verifyNoInteractions(dsl, manager, lifecycle); + } + + private static WorldCanonicalInstanceActivation.Request request() { + var lifecycleRequest = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(lifecycleRequest.canonicalGameInstanceId()) + .thenReturn(UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + var preparing = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(preparing.request()).thenReturn(lifecycleRequest); + when(preparing.lifecycleStatus()).thenReturn("PREPARING"); + when(preparing.lifecycleEpoch()).thenReturn(1L); + when(preparing.rowVersion()).thenReturn(0L); + when(preparing.canonicalBytes()) + .thenReturn( + ("{\"request\":{\"readRequestId\":\"11111111-1111-4111-8111-111111111111\"}}") + .getBytes(StandardCharsets.UTF_8)); + return new WorldCanonicalInstanceActivation.Request( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), preparing); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java new file mode 100644 index 0000000000..be148c3177 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java @@ -0,0 +1,102 @@ +package unit.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.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInstanceActivationServiceTest { + private static final UUID ACTIVATION_ID = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + @Test + void defaultVerifierDeniesNewOperationAfterReadOnlyLedgerMiss() { + var repository = mock(WorldCanonicalInstanceActivationRepository.class); + var request = request(); + when(repository.readResult(request)).thenReturn(Optional.empty()); + var service = new WorldCanonicalInstanceActivationService(repository); + + assertThatThrownBy(() -> service.activate(request)) + .isInstanceOf(WorldCanonicalInstanceActivationService.ActivationDeniedException.class) + .hasMessageContaining("no authenticated current source/release"); + + verify(repository).readResult(request); + verify(repository, never()).activate(eq(request), any()); + } + + @Test + void exactPriorResultReplaysWithoutConsultingCurrentAuthority() { + var repository = mock(WorldCanonicalInstanceActivationRepository.class); + var request = request(); + var result = mock(WorldCanonicalInstanceActivation.Result.class); + when(repository.readResult(request)).thenReturn(Optional.of(result)); + var service = + new WorldCanonicalInstanceActivationService( + repository, + ignored -> { + throw new AssertionError("prior immutable result must bypass current authority"); + }); + + assertThat(service.activate(request)).isSameAs(result); + + verify(repository, never()).activate(eq(request), any()); + } + + @Test + void aNewOperationChecksAndHoldsAuthorityOutsideTheOwnerTransaction() { + var repository = mock(WorldCanonicalInstanceActivationRepository.class); + var request = request(); + var result = mock(WorldCanonicalInstanceActivation.Result.class); + var closed = new java.util.concurrent.atomic.AtomicBoolean(); + var service = + new WorldCanonicalInstanceActivationService( + repository, + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() { + assertThat(closed.get()).isFalse(); + } + + public void close() { + closed.set(true); + } + }; + }); + when(repository.readResult(request)).thenReturn(Optional.empty()); + when(repository.activate(eq(request), any())).thenReturn(result); + + assertThat(service.activate(request)).isSameAs(result); + assertThat(closed.get()).isTrue(); + verify(repository).activate(eq(request), any()); + } + + private static WorldCanonicalInstanceActivation.Request request() { + var lifecycleRequest = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(lifecycleRequest.canonicalGameInstanceId()) + .thenReturn(UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + var preparing = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(preparing.request()).thenReturn(lifecycleRequest); + when(preparing.lifecycleStatus()).thenReturn("PREPARING"); + when(preparing.lifecycleEpoch()).thenReturn(1L); + when(preparing.rowVersion()).thenReturn(0L); + when(preparing.canonicalBytes()) + .thenReturn( + ("{\"request\":{\"readRequestId\":\"11111111-1111-4111-8111-111111111111\"}}") + .getBytes(StandardCharsets.UTF_8)); + return new WorldCanonicalInstanceActivation.Request(ACTIVATION_ID, preparing); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java new file mode 100644 index 0000000000..3bff8b942a --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.sql.Connection; +import java.util.UUID; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInstanceAssociationTest { + private final DSLContext dsl = mock(DSLContext.class); + private final WorldCompleteLaunchBindingRepository launchBindings = + mock(WorldCompleteLaunchBindingRepository.class); + private final WorldAuthoredSourceIntakeRepository sourceIntakes = + mock(WorldAuthoredSourceIntakeRepository.class); + private final WorldAuthoredVersionIdentityRepository versionIdentities = + mock(WorldAuthoredVersionIdentityRepository.class); + private final WorldCanonicalInstanceAssociationRepository repository = + new WorldCanonicalInstanceAssociationRepository( + dsl, launchBindings, sourceIntakes, versionIdentities); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void ownerWriteRequiresAnActiveTransactionBeforeAnyRepositoryAccess() { + assertThatThrownBy(() -> repository.retainClaimInOwnerTransaction(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active World owner transaction"); + + verifyNoInteractions(dsl, launchBindings, sourceIntakes, versionIdentities); + } + + @Test + void ownerWriteRejectsReadOnlyAndNonReadCommittedTransactionsBeforeOwnerAccess() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + + assertThatThrownBy(() -> repository.retainClaimInOwnerTransaction(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + + assertThatThrownBy(() -> repository.retainClaimInOwnerTransaction(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ COMMITTED isolation"); + + verifyNoInteractions(dsl, launchBindings, sourceIntakes, versionIdentities); + } + + @Test + void committedOwnerReadMustRunOutsideAnyTransactionAndRequiresNonNilIdentity() { + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.readOwnerAssociation(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent committed owner read"); + + TransactionSynchronizationManager.clear(); + assertThatThrownBy(() -> repository.readOwnerAssociation(new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + + verifyNoInteractions(dsl, launchBindings, sourceIntakes, versionIdentities); + } + + @Test + void canonicalIdentityRequiresExplicitPublicProductionClassification() { + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + UUID.randomUUID(), + "firemud", + UUID.randomUUID(), + "fixture-world", + UUID.randomUUID(), + "SHARED", + false, + "synthetic-control-request")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("explicit public-production evidence"); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java new file mode 100644 index 0000000000..0857223513 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java @@ -0,0 +1,187 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInstanceLifecycleReadGrpcServiceTest { + @Test + void rejectsActualOrSynchronizationTransactionBeforeParsingOrOwnerAccess() { + var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); + var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); + var malformed = ReadWorldCanonicalInstanceLifecycleRequest.getDefaultInstance(); + Collector actual; + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + actual = call(service, malformed, peer("game-session-service", "test")); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + Collector synchronization; + TransactionSynchronizationManager.initSynchronization(); + try { + synchronization = call(service, malformed, peer("game-session-service", "test")); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(actual.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(synchronization.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(repository); + } + + @Test + void rejectsWrongServiceOrNamespaceBeforeDecodingAndStorageAccess() { + var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); + var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); + var malformed = + ReadWorldCanonicalInstanceLifecycleRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFromUtf8("not-json")) + .build(); + + Collector wrongService = call(service, malformed, peer("account-service", "test")); + Collector wrongNamespace = call(service, malformed, peer("game-session-service", "other")); + Collector wrongRequestNamespace = + call( + service, + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request("other")), + peer("game-session-service", "test")); + assertThat(wrongService.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongRequestNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsAuthenticatedEndUserContextBeforeDecodingOrStorageAccess() { + var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); + var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Collector result; + try { + result = + call( + service, + ReadWorldCanonicalInstanceLifecycleRequest.getDefaultInstance(), + peer("game-session-service", "test")); + } finally { + SessionContext.clear(); + } + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void exactSameNamespaceGameSessionPeerReachesOnlyExactLifecycleRequest() { + var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); + var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); + var read = request("test"); + when(repository.read(read)).thenReturn(Optional.empty()); + + Collector result = + call( + service, + WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), + peer("game-session-service", "test")); + + assertThat(result.error).isEqualTo(Status.Code.NOT_FOUND); + verify(repository).read(read); + } + + @Test + void authenticatedPeerWithMalformedRequestFailsBeforeStorageAccess() { + var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); + var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); + var malformed = + ReadWorldCanonicalInstanceLifecycleRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFromUtf8("not-json")) + .build(); + + Collector result = call(service, malformed, peer("game-session-service", "test")); + + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + private static Collector call( + WorldCanonicalInstanceLifecycleReadGrpcService service, + ReadWorldCanonicalInstanceLifecycleRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readWorldCanonicalInstanceLifecycle(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request request(String namespace) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + namespace, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "starter-world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "SHARED", + true, + "control-request", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static final class Collector + implements StreamObserver { + private ReadWorldCanonicalInstanceLifecycleResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadWorldCanonicalInstanceLifecycleResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + assertThat(completed).isFalse(); + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java new file mode 100644 index 0000000000..6fed725aeb --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java @@ -0,0 +1,54 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInstanceLifecycleReadRepositoryTest { + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void rejectsAmbientTransactionBeforeOpeningIndependentOwnerSnapshot() { + var dsl = mock(DSLContext.class); + var manager = mock(PlatformTransactionManager.class); + var association = mock(WorldCanonicalInstanceAssociationRepository.class); + var repository = new WorldCanonicalInstanceLifecycleReadRepository(dsl, manager, association); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.read(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not join an ambient transaction"); + verifyNoInteractions(dsl, manager, association); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request request() { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + "test", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "starter-world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "SHARED", + true, + "control-request", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java new file mode 100644 index 0000000000..9fe9669457 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java @@ -0,0 +1,389 @@ +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.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Component-only assembly boundary proofs; mocked owner/client results are not producer proof. */ +class WorldCanonicalInstancePreparationAssemblyServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = UUID.randomUUID(); + private static final UUID INSTANCE_ID = UUID.randomUUID(); + private static final UUID BINDING_TENANT_ID = UUID.randomUUID(); + private static final UUID BINDING_SOURCE_OPERATION_ID = UUID.randomUUID(); + private static final UUID BINDING_VERSION_ID = UUID.randomUUID(); + private static final String BINDING_COMMIT_ID = UUID.randomUUID().toString(); + private static final String CONTROL_REQUEST_ID = "control-request"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void selectorIsMinimalAndReadsUseOnlyTheConfiguredNamespace() { + var launchBindings = mock(WorldCompleteLaunchBindingRepository.class); + var sourceIntakes = mock(WorldAuthoredSourceIntakeRepository.class); + var versionIdentities = mock(WorldAuthoredVersionIdentityRepository.class); + var frozenTopologies = mock(WorldCanonicalFrozenTopologyRepository.class); + var gameSession = mock(CanonicalGameInstanceLaunchAssociationClient.class); + var gameDesign = mock(AuthoredWorldLaunchDescriptorClient.class); + when(launchBindings.read(NAMESPACE, TENANT_ID, CONTROL_REQUEST_ID)) + .thenReturn(Optional.empty()); + var service = + new WorldCanonicalInstancePreparationAssemblyService( + NAMESPACE, + launchBindings, + sourceIntakes, + versionIdentities, + frozenTopologies, + gameSession, + gameDesign); + var selector = + new WorldCanonicalInstancePreparationAssemblyService.Selector( + TENANT_ID, INSTANCE_ID, CONTROL_REQUEST_ID); + + assertThatThrownBy(() -> service.assemble(selector)) + .isInstanceOf( + WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) + .hasMessageContaining("No committed World complete launch binding"); + + verify(launchBindings).read(NAMESPACE, TENANT_ID, CONTROL_REQUEST_ID); + verifyNoInteractions( + sourceIntakes, versionIdentities, frozenTopologies, gameSession, gameDesign); + assertThatThrownBy( + () -> + new WorldCanonicalInstancePreparationAssemblyService( + "not a namespace", + launchBindings, + sourceIntakes, + versionIdentities, + frozenTopologies, + gameSession, + gameDesign)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + } + + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeAnyOwnerOrRemoteRead() { + var launchBindings = mock(WorldCompleteLaunchBindingRepository.class); + var sourceIntakes = mock(WorldAuthoredSourceIntakeRepository.class); + var versionIdentities = mock(WorldAuthoredVersionIdentityRepository.class); + var frozenTopologies = mock(WorldCanonicalFrozenTopologyRepository.class); + var gameSession = mock(CanonicalGameInstanceLaunchAssociationClient.class); + var gameDesign = mock(AuthoredWorldLaunchDescriptorClient.class); + var service = + new WorldCanonicalInstancePreparationAssemblyService( + NAMESPACE, + launchBindings, + sourceIntakes, + versionIdentities, + frozenTopologies, + gameSession, + gameDesign); + var selector = + new WorldCanonicalInstancePreparationAssemblyService.Selector( + TENANT_ID, INSTANCE_ID, CONTROL_REQUEST_ID); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> service.assemble(selector)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent committed reads"); + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> service.assemble(selector)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent committed reads"); + + verifyNoInteractions( + launchBindings, + sourceIntakes, + versionIdentities, + frozenTopologies, + gameSession, + gameDesign); + } + + @Test + void rejectsLegacyReleaseWithoutStoredTypedWorldSelectorBeforeRemoteReads() { + var launchBindings = mock(WorldCompleteLaunchBindingRepository.class); + var sourceIntakes = mock(WorldAuthoredSourceIntakeRepository.class); + var versionIdentities = mock(WorldAuthoredVersionIdentityRepository.class); + var frozenTopologies = mock(WorldCanonicalFrozenTopologyRepository.class); + var gameSession = mock(CanonicalGameInstanceLaunchAssociationClient.class); + var gameDesign = mock(AuthoredWorldLaunchDescriptorClient.class); + var pair = binding('a'); + var descriptor = pair.descriptor(); + var intakeRequestId = UUID.randomUUID(); + var source = mock(WorldAuthoredSourceIntakeReceipt.class); + when(source.targetNamespace()).thenReturn(NAMESPACE); + when(source.intakeRequestId()).thenReturn(intakeRequestId); + when(source.canonicalTenantId()).thenReturn(descriptor.canonicalTenantId()); + when(source.worldSlug()).thenReturn(descriptor.worldSlug()); + when(source.sourceOperationId()).thenReturn(descriptor.authoredWorldSourceOperationId()); + when(source.sourceEvidenceDigest()).thenReturn(descriptor.authoredWorldSourceEvidenceDigest()); + when(source.operationId()).thenReturn(UUID.randomUUID()); + when(source.localTenantKey()).thenReturn(41L); + when(source.receiptDigest()).thenReturn("sha256:" + "3".repeat(64)); + when(source.requestDigest()).thenReturn("sha256:" + "4".repeat(64)); + var launchBinding = + new WorldCompleteLaunchBindingReceipt( + 1, + UUID.randomUUID(), + NAMESPACE, + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + descriptor.controlPlaneRequestId(), + source, + pair); + var stored = + new WorldCompleteLaunchBindingRepository.StoredBinding( + launchBinding.operationId(), + NAMESPACE, + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + descriptor.controlPlaneRequestId(), + source.operationId(), + intakeRequestId, + source.localTenantKey(), + source.sourceOperationId(), + source.sourceEvidenceDigest(), + source.receiptDigest(), + descriptor.requestDigest(), + descriptor.resultDigest(), + pair.releaseAttestation().evidenceDigest(), + pair); + when(launchBindings.read( + NAMESPACE, descriptor.canonicalTenantId(), descriptor.controlPlaneRequestId())) + .thenReturn(Optional.of(stored)); + when(sourceIntakes.read(NAMESPACE, intakeRequestId)).thenReturn(Optional.of(source)); + when(launchBindings.toReceipt(stored, source)).thenReturn(launchBinding); + var service = + new WorldCanonicalInstancePreparationAssemblyService( + NAMESPACE, + launchBindings, + sourceIntakes, + versionIdentities, + frozenTopologies, + gameSession, + gameDesign); + var selector = + new WorldCanonicalInstancePreparationAssemblyService.Selector( + descriptor.canonicalTenantId(), INSTANCE_ID, descriptor.controlPlaneRequestId()); + + assertThatThrownBy(() -> service.assemble(selector)) + .isInstanceOf( + WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) + .hasMessageContaining("stored v2 release selector"); + verifyNoInteractions(versionIdentities, frozenTopologies, gameSession, gameDesign); + } + + @Test + void acceptsOnlyTheExactGameSessionSelectorAndCompleteStoredPair() { + var stored = binding('a'); + var request = gameSessionRequest(stored, INSTANCE_ID); + var matching = gameSessionResult(request, stored); + + WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( + request, matching, stored); + var worldEvidence = + WorldCanonicalInstancePreparationAssemblyService.associationToWorldEvidence( + request, matching); + assertThat(worldEvidence.currentGameSessionStatus()).isEqualTo("RUNNING"); + assertThat(worldEvidence.currentGameSessionRowVersion()).isEqualTo(17L); + assertThat(worldEvidence.canonicalGameInstanceId()).isEqualTo(INSTANCE_ID); + assertThat(worldEvidence.playableStateScope()).isEqualTo("SHARED"); + assertThat(worldEvidence.publicProduction()).isTrue(); + + var changedInstanceRequest = gameSessionRequest(stored, UUID.randomUUID()); + var changedInstanceResult = gameSessionResult(changedInstanceRequest, stored); + assertThatThrownBy( + () -> + WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( + request, changedInstanceResult, stored)) + .isInstanceOf( + WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) + .hasMessageContaining("Game Session association differs"); + + var changedPair = binding('b'); + var changedPairRequest = gameSessionRequest(changedPair, INSTANCE_ID); + var changedPairResult = gameSessionResult(changedPairRequest, changedPair); + assertThatThrownBy( + () -> + WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( + request, changedPairResult, stored)) + .isInstanceOf( + WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) + .hasMessageContaining("Game Session association differs"); + } + + @Test + void rejectsNonSharedOrNonProductionGameSessionReadProjection() { + var stored = binding('a'); + var request = gameSessionRequest(stored, INSTANCE_ID); + var invalid = mock(CanonicalGameInstanceLaunchAssociationReadEvidence.Result.class); + when(invalid.request()).thenReturn(request); + when(invalid.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.ISOLATED); + when(invalid.publicProduction()).thenReturn(true); + when(invalid.launchBindingEvidence()).thenReturn(stored); + + assertThatThrownBy( + () -> + WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( + request, invalid, stored)) + .isInstanceOf( + WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) + .hasMessageContaining("Game Session association differs"); + + when(invalid.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(invalid.publicProduction()).thenReturn(false); + assertThatThrownBy( + () -> + WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( + request, invalid, stored)) + .isInstanceOf( + WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) + .hasMessageContaining("Game Session association differs"); + } + + @Test + void independentlyAuthenticatedGameDesignPairMustMatchEveryStoredEvidenceField() { + var stored = binding('a'); + WorldCanonicalInstancePreparationAssemblyService.requireSameCompletePair(stored, binding('a')); + + assertThatThrownBy( + () -> + WorldCanonicalInstancePreparationAssemblyService.requireSameCompletePair( + stored, binding('b'))) + .isInstanceOf( + WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) + .hasMessageContaining("Authenticated Game Design complete launch pair differs"); + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request gameSessionRequest( + CompleteLaunchBindingEvidence binding, UUID instanceId) { + var descriptor = binding.descriptor(); + var release = binding.releaseAttestation(); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + instanceId, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Result gameSessionResult( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request, + CompleteLaunchBindingEvidence binding) { + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + request, + UUID.randomUUID(), + RealmEntryPolicy.StateScope.SHARED, + true, + CurrentGameInstanceStatus.RUNNING, + 17L, + binding); + } + + private static CompleteLaunchBindingEvidence binding(char digestCharacter) { + UUID sourceOperationId = BINDING_SOURCE_OPERATION_ID; + UUID tenantId = BINDING_TENANT_ID; + String worldSlug = "assembly-world"; + String controlPlaneRequestId = "assembly-control"; + String sourceDigest = "sha256:" + "f".repeat(64); + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + tenantId, + worldSlug, + sourceOperationId, + sourceDigest, + 71L, + false, + null, + false, + null, + false, + null, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor-assembly", + 83L, + false, + null, + "{}", + "generation-assembly", + 9L, + 89L, + "release-assembly", + false, + null); + String commitId = BINDING_COMMIT_ID; + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + commitId, + String.valueOf(digestCharacter).repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "1".repeat(64) : null)) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + tenantId, + BINDING_VERSION_ID, + worldSlug, + sourceOperationId, + sourceDigest, + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:assembly", + commitId, + participants, + "sha256:" + "2".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, release); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcServiceTest.java new file mode 100644 index 0000000000..5781103a89 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcServiceTest.java @@ -0,0 +1,566 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationGrpcCodec; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation.GameSessionReadEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation.GameSessionReadRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Result; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationAssemblyService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingService; +import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Component-only adapter tests; mocked producer and storage results are not PostgreSQL proof. */ +class WorldCanonicalInstancePreparationGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID INSTANCE_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID PLAYABLE_NAMESPACE_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID READ_ID = uuid("11111111-1111-4111-8111-111111111111"); + private static final String CONTROL_REQUEST_ID = "control-request"; + private static final String DESCRIPTOR_ID = "launch-descriptor"; + private static final String REQUEST_DIGEST = "sha256:" + "a".repeat(64); + private static final String RESULT_DIGEST = "sha256:" + "b".repeat(64); + private static final String RELEASE_DIGEST = "sha256:" + "c".repeat(64); + + @AfterEach + void clearAmbientState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsWrongServiceNamespaceAndMissingPeerBeforeAnyComponentInteraction() { + Harness harness = new Harness("STARTING"); + var request = request(harness.selector); + + assertThat(call(harness.service, request, peer("account-service", NAMESPACE)).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(harness.service, request, peer("game-session-service", "other")).error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(harness.service, request, null).error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions( + harness.launchBinding, + harness.assembly, + harness.preparation, + harness.preparationRepository, + harness.lifecycleRepository); + } + + @Test + void rejectsOuterWorkloadNamespaceAndEndUserContextBeforeOwnerCalls() { + Harness harness = new Harness("STARTING"); + var wrongNamespace = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + READ_ID, + "other", + TENANT_ID, + "starter-world", + INSTANCE_ID, + CONTROL_REQUEST_ID, + DESCRIPTOR_ID, + REQUEST_DIGEST, + RESULT_DIGEST, + RELEASE_DIGEST); + assertThat( + call(harness.service, request(wrongNamespace), peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("66666666-6666-4666-8666-666666666666", List.of(), Map.of()); + Collector endUser; + try { + endUser = + call( + harness.service, + PrepareCanonicalWorldInstanceRequest.getDefaultInstance(), + peer("game-session-service", NAMESPACE)); + } finally { + SessionContext.clear(); + } + assertThat(endUser.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions( + harness.launchBinding, + harness.assembly, + harness.preparation, + harness.preparationRepository, + harness.lifecycleRepository); + } + + @Test + void rejectsAmbientTransactionBeforeBindingAssemblyOrStorage() { + Harness harness = new Harness("STARTING"); + TransactionSynchronizationManager.setActualTransactionActive(true); + + Collector result = + call(harness.service, request(harness.selector), peer("game-session-service", NAMESPACE)); + + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions( + harness.launchBinding, + harness.assembly, + harness.preparation, + harness.preparationRepository, + harness.lifecycleRepository); + } + + @Test + void invalidClosedSelectorFailsBeforeOwnerCalls() { + Harness harness = new Harness("STARTING"); + + Collector result = + call( + harness.service, + PrepareCanonicalWorldInstanceRequest.getDefaultInstance(), + peer("game-session-service", NAMESPACE)); + + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions( + harness.launchBinding, + harness.assembly, + harness.preparation, + harness.preparationRepository, + harness.lifecycleRepository); + } + + @Test + void unknownCommittedLaunchBindingFailsClosedBeforeAssembly() { + Harness harness = new Harness("STARTING"); + when(harness.launchBinding.bindCommittedLaunch(harness.selector)) + .thenThrow( + new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "private missing binding detail")); + + Collector result = + call(harness.service, request(harness.selector), peer("game-session-service", NAMESPACE)); + + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(result.description).doesNotContain("private missing binding detail"); + verify(harness.launchBinding).bindCommittedLaunch(harness.selector); + verifyNoInteractions( + harness.assembly, + harness.preparation, + harness.preparationRepository, + harness.lifecycleRepository); + } + + @Test + void unavailableOwnerRpcIsSanitizedAndMappedToUnavailable() { + Harness harness = new Harness("STARTING"); + when(harness.launchBinding.bindCommittedLaunch(harness.selector)) + .thenThrow( + Status.UNAVAILABLE.withDescription("private remote detail").asRuntimeException()); + + Collector result = + call(harness.service, request(harness.selector), peer("game-session-service", NAMESPACE)); + + assertThat(result.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(result.description).doesNotContain("private remote detail"); + verifyNoInteractions( + harness.assembly, + harness.preparation, + harness.preparationRepository, + harness.lifecycleRepository); + } + + @Test + void changedAssembledTupleFailsBeforePreparation() { + Harness harness = new Harness("STARTING"); + when(harness.innerRequest.expectedDescriptorResultDigest()) + .thenReturn("sha256:" + "d".repeat(64)); + + Collector result = + call(harness.service, request(harness.selector), peer("game-session-service", NAMESPACE)); + + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verify(harness.launchBinding).bindCommittedLaunch(harness.selector); + verify(harness.assembly) + .assemble( + new WorldCanonicalInstancePreparationAssemblyService.Selector( + TENANT_ID, INSTANCE_ID, CONTROL_REQUEST_ID)); + verifyNoInteractions( + harness.preparation, harness.preparationRepository, harness.lifecycleRepository); + } + + @Test + void freshNonStartingSessionIsDeniedButAnExactHistoricalRetryStillCallsPrepare() { + Harness fresh = new Harness("RUNNING"); + when(fresh.preparationRepository.readOwnerPreparation(fresh.input)) + .thenReturn(Optional.empty()); + Collector freshResult = + call(fresh.service, request(fresh.selector), peer("game-session-service", NAMESPACE)); + assertThat(freshResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(fresh.preparation, fresh.lifecycleRepository); + + Harness retry = new Harness("RUNNING"); + when(retry.preparationRepository.readOwnerPreparation(retry.input)) + .thenReturn(Optional.of(retry.prepared)); + when(retry.preparation.prepare(retry.input)) + .thenThrow( + new WorldCanonicalInstancePreparationService.PreparationDeniedException( + "held proof denied")); + + Collector retryResult = + call(retry.service, request(retry.selector), peer("game-session-service", NAMESPACE)); + + assertThat(retryResult.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verify(retry.preparation).prepare(retry.input); + verifyNoInteractions(retry.lifecycleRepository); + } + + @Test + void productionDefaultVerifierDeniesWithoutLifecycleSuccessAndNullPrepareResultIsRejected() { + Harness defaultDenied = new Harness("STARTING"); + var productionDefault = + new WorldCanonicalInstancePreparationService(defaultDenied.preparationRepository); + defaultDenied.replacePreparationService(productionDefault); + + Collector denied = + call( + defaultDenied.service, + request(defaultDenied.selector), + peer("game-session-service", NAMESPACE)); + + assertThat(denied.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verify(defaultDenied.preparationRepository).readOwnerPreparation(defaultDenied.input); + verifyNoInteractions(defaultDenied.lifecycleRepository); + + Harness noResult = new Harness("STARTING"); + when(noResult.preparation.prepare(noResult.input)).thenReturn(null); + + Collector absent = + call(noResult.service, request(noResult.selector), peer("game-session-service", NAMESPACE)); + + assertThat(absent.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verify(noResult.preparation).prepare(noResult.input); + verifyNoInteractions(noResult.lifecycleRepository); + } + + @Test + void bindsBeforeAssemblyThenRequiresExactMaterializationAndIndependentLifecycleReadback() { + Harness harness = new Harness("STARTING"); + var responseLifecycleBytes = + "canonical lifecycle bytes".getBytes(java.nio.charset.StandardCharsets.UTF_8); + when(harness.lifecycle.canonicalBytes()).thenReturn(responseLifecycleBytes); + + Collector result = + call(harness.service, request(harness.selector), peer("game-session-service", NAMESPACE)); + + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.value).isNotNull(); + assertThat(result.value.hasRequest()).isTrue(); + assertThat(result.value.getRequest()).isEqualTo(request(harness.selector)); + assertThat(result.value.hasLifecycle()).isTrue(); + assertThat(result.value.getLifecycle().getCanonicalResponseBytes().toByteArray()) + .containsExactly(responseLifecycleBytes); + assertThat(harness.lifecycleRequest.readRequestId()) + .isEqualTo(harness.selector.readRequestId()) + .isNotEqualTo(harness.innerRequest.readRequestId()); + var ordered = inOrder(harness.launchBinding, harness.assembly); + ordered.verify(harness.launchBinding).bindCommittedLaunch(harness.selector); + ordered + .verify(harness.assembly) + .assemble( + new WorldCanonicalInstancePreparationAssemblyService.Selector( + TENANT_ID, INSTANCE_ID, CONTROL_REQUEST_ID)); + verify(harness.preparationRepository).readOwnerPreparation(harness.input); + verify(harness.preparation).prepare(harness.input); + verify(harness.lifecycleRepository).read(harness.lifecycleRequest); + } + + @Test + void missingOrInconsistentIndependentLifecycleEvidenceIsRejected() { + Harness missing = new Harness("STARTING"); + when(missing.lifecycleRepository.read(missing.lifecycleRequest)).thenReturn(Optional.empty()); + Collector missingResult = + call(missing.service, request(missing.selector), peer("game-session-service", NAMESPACE)); + assertThat(missingResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + + Harness inconsistent = new Harness("STARTING"); + when(inconsistent.lifecycle.captureId()).thenReturn(UUID.randomUUID()); + Collector inconsistentResult = + call( + inconsistent.service, + request(inconsistent.selector), + peer("game-session-service", NAMESPACE)); + assertThat(inconsistentResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verify(missing.preparation).prepare(missing.input); + verify(inconsistent.preparation).prepare(inconsistent.input); + } + + private static PrepareCanonicalWorldInstanceRequest request( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector) { + return CanonicalWorldInstancePreparationGrpcCodec.toRequest(selector); + } + + private static Collector call( + WorldCanonicalInstancePreparationGrpcService service, + PrepareCanonicalWorldInstanceRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector(); + Context context = + peer == null ? Context.ROOT : Context.ROOT.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.prepareCanonicalWorldInstance(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Harness { + private final CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + READ_ID, + NAMESPACE, + TENANT_ID, + "starter-world", + INSTANCE_ID, + CONTROL_REQUEST_ID, + DESCRIPTOR_ID, + REQUEST_DIGEST, + RESULT_DIGEST, + RELEASE_DIGEST); + private final WorldCompleteLaunchBindingService launchBinding = + mock(WorldCompleteLaunchBindingService.class); + private final WorldCanonicalInstancePreparationAssemblyService assembly = + mock(WorldCanonicalInstancePreparationAssemblyService.class); + private WorldCanonicalInstancePreparationService preparation = + mock(WorldCanonicalInstancePreparationService.class); + private final WorldCanonicalInstancePreparationRepository preparationRepository = + mock(WorldCanonicalInstancePreparationRepository.class); + private final WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository = + mock(WorldCanonicalInstanceLifecycleReadRepository.class); + private final GameSessionReadRequest innerRequest = mock(GameSessionReadRequest.class); + private final GameSessionReadEvidence gameSession = mock(GameSessionReadEvidence.class); + private final AuthoredWorldLaunchDescriptorEvidence descriptor = + mock(AuthoredWorldLaunchDescriptorEvidence.class); + private final AuthoredWorldReleaseAttestationEvidence release = + mock(AuthoredWorldReleaseAttestationEvidence.class); + private final CompleteLaunchBindingEvidence pair = mock(CompleteLaunchBindingEvidence.class); + private final WorldCompleteLaunchBindingReceipt binding = + mock(WorldCompleteLaunchBindingReceipt.class); + private final WorldAuthoredVersionIdentityReceipt versionIdentity = + mock(WorldAuthoredVersionIdentityReceipt.class); + private final WorldCanonicalInstanceAssociation.CanonicalIdentity identity = + mock(WorldCanonicalInstanceAssociation.CanonicalIdentity.class); + private final WorldCanonicalInstanceTopologyPlan topologyPlan = + mock(WorldCanonicalInstanceTopologyPlan.class); + private final WorldCanonicalFrozenTopology.Request frozenSource = + mock(WorldCanonicalFrozenTopology.Request.class); + private final Input input = mock(Input.class); + private final Result prepared = mock(Result.class); + private final WorldCanonicalInstanceAssociation association = + mock(WorldCanonicalInstanceAssociation.class); + private final RoomTemplateRef startLocation = + new RoomTemplateRef(TENANT_ID, VERSION_ID, uuid("77777777-7777-4777-8777-777777777777")); + private final UUID captureId = uuid("88888888-8888-4888-8888-888888888888"); + private final String graphSha256 = "e".repeat(64); + private final String inputDigest = "sha256:" + "f".repeat(64); + private final Request lifecycleRequest; + private final WorldCanonicalInstanceLifecycleEvidence lifecycle = + mock(WorldCanonicalInstanceLifecycleEvidence.class); + private WorldCanonicalInstancePreparationGrpcService service; + + private Harness(String currentStatus) { + UUID internalReadId = uuid("99999999-9999-4999-8999-999999999999"); + when(innerRequest.readRequestId()).thenReturn(internalReadId); + when(innerRequest.targetNamespace()).thenReturn(NAMESPACE); + when(innerRequest.canonicalTenantId()).thenReturn(TENANT_ID); + when(innerRequest.worldSlug()).thenReturn("starter-world"); + when(innerRequest.canonicalGameInstanceId()).thenReturn(INSTANCE_ID); + when(innerRequest.controlPlaneRequestId()).thenReturn(CONTROL_REQUEST_ID); + when(innerRequest.launchDescriptorId()).thenReturn(DESCRIPTOR_ID); + when(innerRequest.expectedDescriptorRequestDigest()).thenReturn(REQUEST_DIGEST); + when(innerRequest.expectedDescriptorResultDigest()).thenReturn(RESULT_DIGEST); + when(innerRequest.expectedReleaseAttestationEvidenceDigest()).thenReturn(RELEASE_DIGEST); + + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(descriptor.canonicalTenantId()).thenReturn(TENANT_ID); + when(descriptor.worldSlug()).thenReturn("starter-world"); + when(descriptor.controlPlaneRequestId()).thenReturn(CONTROL_REQUEST_ID); + when(descriptor.launchDescriptorId()).thenReturn(DESCRIPTOR_ID); + when(descriptor.requestDigest()).thenReturn(REQUEST_DIGEST); + when(descriptor.resultDigest()).thenReturn(RESULT_DIGEST); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.descriptorResultDigest()).thenReturn(RESULT_DIGEST); + when(release.canonicalTenantId()).thenReturn(TENANT_ID); + when(release.canonicalVersionId()).thenReturn(VERSION_ID); + when(release.worldSlug()).thenReturn("starter-world"); + when(release.launchDescriptorId()).thenReturn(DESCRIPTOR_ID); + when(release.evidenceDigest()).thenReturn(RELEASE_DIGEST); + when(pair.descriptor()).thenReturn(descriptor); + when(pair.releaseAttestation()).thenReturn(release); + + when(gameSession.readRequestId()).thenReturn(internalReadId); + when(gameSession.targetNamespace()).thenReturn(NAMESPACE); + when(gameSession.canonicalTenantId()).thenReturn(TENANT_ID); + when(gameSession.worldSlug()).thenReturn("starter-world"); + when(gameSession.canonicalGameInstanceId()).thenReturn(INSTANCE_ID); + when(gameSession.controlPlaneRequestId()).thenReturn(CONTROL_REQUEST_ID); + when(gameSession.launchDescriptorId()).thenReturn(DESCRIPTOR_ID); + when(gameSession.descriptorRequestDigest()).thenReturn(REQUEST_DIGEST); + when(gameSession.descriptorResultDigest()).thenReturn(RESULT_DIGEST); + when(gameSession.releaseAttestationEvidenceDigest()).thenReturn(RELEASE_DIGEST); + when(gameSession.playableStateNamespaceId()).thenReturn(PLAYABLE_NAMESPACE_ID); + when(gameSession.playableStateScope()).thenReturn("SHARED"); + when(gameSession.publicProduction()).thenReturn(true); + when(gameSession.currentGameSessionStatus()).thenReturn(currentStatus); + when(gameSession.descriptor()).thenReturn(descriptor); + when(gameSession.releaseAttestation()).thenReturn(release); + when(gameSession.canonicalIdentity()).thenReturn(identity); + + when(binding.targetNamespace()).thenReturn(NAMESPACE); + when(binding.canonicalTenantId()).thenReturn(TENANT_ID); + when(binding.worldSlug()).thenReturn("starter-world"); + when(binding.controlPlaneRequestId()).thenReturn(CONTROL_REQUEST_ID); + when(binding.evidence()).thenReturn(pair); + when(binding.descriptor()).thenReturn(descriptor); + when(input.gameSessionReadRequest()).thenReturn(innerRequest); + when(input.gameSessionReadEvidence()).thenReturn(gameSession); + when(input.completeLaunchBinding()).thenReturn(binding); + when(input.versionIdentity()).thenReturn(versionIdentity); + when(input.topologyPlan()).thenReturn(topologyPlan); + when(input.captureId()).thenReturn(captureId); + // The production default verifier checks generation intent before denying due to missing + // authenticated held producer authority. This synthetic source is not producer or PG proof. + when(topologyPlan.sourceBinding()).thenReturn(frozenSource); + when(topologyPlan.generationRules()).thenReturn(List.of()); + when(topologyPlan.spawnBindings()).thenReturn(List.of()); + when(launchBinding.bindCommittedLaunch(selector)).thenReturn(binding); + when(assembly.assemble( + new WorldCanonicalInstancePreparationAssemblyService.Selector( + TENANT_ID, INSTANCE_ID, CONTROL_REQUEST_ID))) + .thenReturn(input); + + when(prepared.association()).thenReturn(association); + when(prepared.captureId()).thenReturn(captureId); + when(prepared.graphSha256()).thenReturn(graphSha256); + when(prepared.inputDigest()).thenReturn(inputDigest); + when(prepared.startLocation()).thenReturn(startLocation); + when(prepared.runtimeRoomInstanceId()).thenReturn(9L); + when(prepared.storageStatus()).thenReturn("MATERIALIZED_UNVERIFIED"); + when(association.identity()).thenReturn(identity); + when(association.completeLaunchBinding()).thenReturn(binding); + when(association.versionIdentity()).thenReturn(versionIdentity); + when(preparationRepository.readOwnerPreparation(input)).thenReturn(Optional.empty()); + when(preparation.prepare(input)).thenReturn(prepared); + + lifecycleRequest = + new Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + READ_ID, + NAMESPACE, + TENANT_ID, + "starter-world", + INSTANCE_ID, + PLAYABLE_NAMESPACE_ID, + "SHARED", + true, + CONTROL_REQUEST_ID, + VERSION_ID, + REQUEST_DIGEST, + RESULT_DIGEST, + RELEASE_DIGEST); + when(lifecycle.request()).thenReturn(lifecycleRequest); + when(lifecycle.launchBinding()).thenReturn(pair); + when(lifecycle.captureId()).thenReturn(captureId); + when(lifecycle.graphSha256()).thenReturn(graphSha256); + when(lifecycle.preparationInputDigest()).thenReturn(inputDigest); + when(lifecycle.startLocation()).thenReturn(startLocation); + when(lifecycle.runtimeRoomInstanceId()).thenReturn(9L); + when(lifecycleRepository.read(lifecycleRequest)).thenReturn(Optional.of(lifecycle)); + + service = createService(); + } + + private void replacePreparationService(WorldCanonicalInstancePreparationService replacement) { + preparation = replacement; + service = createService(); + } + + private WorldCanonicalInstancePreparationGrpcService createService() { + return new WorldCanonicalInstancePreparationGrpcService( + launchBinding, + assembly, + preparation, + preparationRepository, + lifecycleRepository, + NAMESPACE); + } + } + + private static final class Collector + implements StreamObserver { + private PrepareCanonicalWorldInstanceResponse value; + private Status.Code error; + private String description; + private boolean completed; + + @Override + public void onNext(PrepareCanonicalWorldInstanceResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + assertThat(completed).isFalse(); + error = Status.fromThrowable(failure).getCode(); + description = Status.fromThrowable(failure).getDescription(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java new file mode 100644 index 0000000000..88521ed104 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java @@ -0,0 +1,670 @@ +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.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.util.JsonFormat; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalFrozenTopology.Request; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DuplicateKeyException; + +class WorldCanonicalInstancePreparationTest { + @Test + void exactReleaseGraphJoinAcceptsMatchingCheckpointAndDistinctPublishedEpoch() throws Exception { + var fixture = releaseGraphFixture(); + WorldCanonicalInstancePreparation.requireExactReleaseGraph(fixture.release(), fixture.plan()); + assertThat(fixture.release().versionStateEpoch()) + .isGreaterThan(fixture.plan().sourceBinding().freeze().versionStateEpoch()); + } + + @Test + void exactReleaseGraphJoinRejectsChangedCommitDigestSchemaVersionAndWorkflow() throws Exception { + var fixture = releaseGraphFixture(); + var source = fixture.plan().sourceBinding(); + var freeze = source.freeze(); + for (var changed : + List.of( + releaseFor( + source, + UUID.randomUUID(), + freeze.appliedCommitId(), + freeze.contentDigest(), + freeze.publishWorkflowId()), + releaseFor( + source, + freeze.canonicalVersionId(), + UUID.randomUUID().toString(), + freeze.contentDigest(), + freeze.publishWorkflowId()), + releaseFor( + source, + freeze.canonicalVersionId(), + freeze.appliedCommitId(), + "6".repeat(64), + freeze.publishWorkflowId()), + releaseFor( + source, + freeze.canonicalVersionId(), + freeze.appliedCommitId(), + freeze.contentDigest(), + "another-workflow"))) { + assertThatThrownBy( + () -> + WorldCanonicalInstancePreparation.requireExactReleaseGraph( + changed, fixture.plan())) + .isInstanceOf(IllegalArgumentException.class); + } + var changedSchema = + new CaptureRequest( + freeze.targetNamespace(), + freeze.canonicalTenantId(), + freeze.canonicalVersionId(), + freeze.intakeRequestId(), + freeze.publicationFence(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + freeze.contentDigest(), + 2, + freeze.suppliedOwnedAffectedTuples()); + when(fixture.plan().sourceBinding()).thenReturn(new Request(source.plan(), changedSchema)); + assertThatThrownBy( + () -> + WorldCanonicalInstancePreparation.requireExactReleaseGraph( + fixture.release(), fixture.plan())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("World participant differs"); + } + + private record ReleaseGraphFixture( + AuthoredWorldReleaseAttestationEvidence release, WorldCanonicalInstanceTopologyPlan plan) {} + + private static ReleaseGraphFixture releaseGraphFixture() throws Exception { + UUID tenant = UUID.randomUUID(); + UUID version = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + UUID revision = UUID.randomUUID(); + UUID region = UUID.randomUUID(); + var owner = ownerBinding(tenant, version); + var binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 41L, "gd-tenant", 42L, "gd-tenant", "NEW_GAME_ROW"), + UUID.randomUUID(), + commit, + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + revision, + Owner.WORLD_MANAGEMENT, + JsonFormat.printer() + .print(regionMutation(commit, revision, region, "Region")))), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + region.toString(), + "AGGREGATE", + region.toString(), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + region.toString(), + "REGION_SUBTREE", + region.toString(), + "0"))); + var freeze = freezeRequest(owner, binding); + var source = new Request(WorldDraftTopologyCommitPlan.create(binding, owner), freeze); + var plan = mock(WorldCanonicalInstanceTopologyPlan.class); + when(plan.sourceBinding()).thenReturn(source); + when(plan.tenantId()).thenReturn(tenant); + when(plan.versionId()).thenReturn(version); + return new ReleaseGraphFixture( + releaseFor( + source, version, commit.toString(), freeze.contentDigest(), freeze.publishWorkflowId()), + plan); + } + + private static AuthoredWorldReleaseAttestationEvidence releaseFor( + Request source, UUID version, String commit, String worldDigest, String workflow) { + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(source.plan().ownerBinding().gameDesignVersionId()), + false, + null, + commit, + "WORLD_MANAGEMENT".equals(owner) ? worldDigest : "a".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "b".repeat(64) : null)) + .toList(); + return AuthoredWorldReleaseAttestationEvidence.create( + source.freeze().targetNamespace(), + "sha256:" + "1".repeat(64), + source.freeze().canonicalTenantId(), + version, + "synthetic-world", + UUID.randomUUID(), + "sha256:" + "2".repeat(64), + "descriptor", + "release", + 8L, + workflow, + commit, + participants, + "sha256:" + "3".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + "generation"); + } + + @Test + void translatesV35DifferentPreparationConflictAndPreservesCause() { + DuplicateKeyException databaseFailure = + duplicateKeyFailure( + "23505", "Canonical gameInstanceId is already bound to a different preparation"); + + RuntimeException translated = + WorldCanonicalInstancePreparationRepository.translateCanonicalPreparationConflict( + databaseFailure); + + assertThat(translated) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class); + assertThat(translated.getCause()).isSameAs(databaseFailure); + } + + @Test + void translatesV35ReservedIdentityConflictAndPreservesCause() { + DuplicateKeyException databaseFailure = + duplicateKeyFailure( + "23505", + "ERROR: Canonical game instance or request identity is already reserved\n Where: owner function"); + + RuntimeException translated = + WorldCanonicalInstancePreparationRepository.translateCanonicalPreparationConflict( + databaseFailure); + + assertThat(translated) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class); + assertThat(translated.getCause()).isSameAs(databaseFailure); + } + + @Test + void preservesUnrelatedDuplicateKeyFailures() { + DuplicateKeyException wrongSqlState = + duplicateKeyFailure( + "23503", "Canonical game instance or request identity is already reserved"); + DuplicateKeyException unrelatedUniqueViolation = + duplicateKeyFailure("23505", "Unexpected unique constraint violation"); + DuplicateKeyException unrelatedViolationWithMatchingDetail = + duplicateKeyFailure( + "23505", + "ERROR: duplicate key violates a different constraint\nDetail: Canonical game instance or request identity is already reserved"); + + assertThat( + WorldCanonicalInstancePreparationRepository.translateCanonicalPreparationConflict( + wrongSqlState)) + .isSameAs(wrongSqlState); + assertThat( + WorldCanonicalInstancePreparationRepository.translateCanonicalPreparationConflict( + unrelatedUniqueViolation)) + .isSameAs(unrelatedUniqueViolation); + assertThat( + WorldCanonicalInstancePreparationRepository.translateCanonicalPreparationConflict( + unrelatedViolationWithMatchingDetail)) + .isSameAs(unrelatedViolationWithMatchingDetail); + } + + @Test + void defaultServiceDeniesBeforeRepositoryAccess() { + WorldCanonicalInstancePreparationRepository repository = + mock(WorldCanonicalInstancePreparationRepository.class); + WorldCanonicalInstancePreparation.Input input = + mock(WorldCanonicalInstancePreparation.Input.class); + WorldCanonicalInstanceTopologyPlan plan = mock(WorldCanonicalInstanceTopologyPlan.class); + when(input.topologyPlan()).thenReturn(plan); + when(plan.generationRules()).thenReturn(List.of()); + when(plan.spawnBindings()).thenReturn(List.of()); + + assertThatThrownBy( + () -> new WorldCanonicalInstancePreparationService(repository).prepare(input)) + .isInstanceOf(WorldCanonicalInstancePreparationService.PreparationDeniedException.class) + .hasMessageContaining("no authenticated source/release terminal verifier"); + + verifyNoInteractions(repository); + } + + private static DuplicateKeyException duplicateKeyFailure(String sqlState, String message) { + return new DuplicateKeyException( + "Database rejected canonical preparation", new SQLException(message, sqlState)); + } + + @Test + void requiredGenerationIntentFailsClosedBeforeAnyPreparation() { + WorldCanonicalInstanceTopologyPlan plan = mock(WorldCanonicalInstanceTopologyPlan.class); + when(plan.generationRules()) + .thenReturn(List.of(mock(WorldCanonicalInstanceTopologyPlan.GenerationRuleIntent.class))); + when(plan.spawnBindings()).thenReturn(List.of()); + + assertThatThrownBy(() -> WorldCanonicalInstancePreparation.requireGenerationFree(plan)) + .isInstanceOf(WorldCanonicalInstancePreparation.GenerationIntentNotSupportedException.class) + .hasMessageContaining("configured generation or spawn intent"); + } + + @Test + void requiredSpawnIntentFailsClosedBeforeAnyPreparation() { + WorldCanonicalInstanceTopologyPlan plan = mock(WorldCanonicalInstanceTopologyPlan.class); + when(plan.generationRules()).thenReturn(List.of()); + when(plan.spawnBindings()) + .thenReturn(List.of(mock(WorldCanonicalInstanceTopologyPlan.SpawnBindingIntent.class))); + + assertThatThrownBy(() -> WorldCanonicalInstancePreparation.requireGenerationFree(plan)) + .isInstanceOf(WorldCanonicalInstancePreparation.GenerationIntentNotSupportedException.class) + .hasMessageContaining("configured generation or spawn intent"); + } + + @Test + void separatelyReconstructedFrozenSourceMatchesEveryValueButChangedPayloadIsDenied() + throws Exception { + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + UUID revisionId = UUID.randomUUID(); + UUID regionId = UUID.randomUUID(); + UUID secondRevisionId = UUID.randomUUID(); + UUID secondRegionId = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenantId, versionId, 41L, "gd-tenant", 42L, "gd-tenant", "NEW_GAME_ROW"); + var originalMutation = regionMutation(commitId, revisionId, regionId, "Original region"); + var secondMutation = + regionMutation(commitId, secondRevisionId, secondRegionId, "Second region"); + DraftCommitBinding binding = + draftBinding( + target, + requestId, + commitId, + revisionId, + regionId, + originalMutation, + secondRevisionId, + secondRegionId, + secondMutation); + OwnerBinding owner = ownerBinding(tenantId, versionId); + CaptureRequest freeze = freezeRequest(owner, binding); + WorldDraftTopologyInputGraph graph = + topologyGraph( + tenantId, + versionId, + revisionId, + regionId, + originalMutation, + secondRevisionId, + secondRegionId, + secondMutation); + Request supplied = sourceRequest(binding, owner, freeze, graph); + + DraftCommitBinding reconstructedBinding = + DraftCommitBinding.fromStored(binding.canonicalJson(), binding.digest()); + Request reconstructed = + sourceRequest( + reconstructedBinding, + copyOwnerBinding(owner), + copyFreezeRequest(freeze), + topologyGraph( + tenantId, + versionId, + revisionId, + regionId, + originalMutation, + secondRevisionId, + secondRegionId, + secondMutation)); + + assertThat(reconstructed).isNotEqualTo(supplied); + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, supplied)) + .isTrue(); + + var changedMutation = regionMutation(commitId, revisionId, regionId, "Changed region"); + Request changedSource = + sourceRequest( + draftBinding( + target, + requestId, + commitId, + revisionId, + regionId, + changedMutation, + secondRevisionId, + secondRegionId, + secondMutation), + owner, + freeze, + topologyGraph( + tenantId, + versionId, + revisionId, + regionId, + changedMutation, + secondRevisionId, + secondRegionId, + secondMutation)); + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, changedSource)) + .isFalse(); + + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, requestWithFreeze(supplied, withChangedAffectedTuple(freeze)))) + .isFalse(); + + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, + sourceRequest(binding, withChangedOwnerEvidence(owner), freeze, graph))) + .isFalse(); + + var changedGraphMutation = + regionMutation(commitId, revisionId, regionId, "Graph-only payload change"); + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, + sourceRequest( + binding, + owner, + freeze, + topologyGraph( + tenantId, + versionId, + revisionId, + regionId, + changedGraphMutation, + secondRevisionId, + secondRegionId, + secondMutation)))) + .isFalse(); + + assertThat( + WorldCanonicalInstancePreparationRepository.matchesCompleteFrozenSource( + reconstructed, sourceRequest(binding, owner, freeze, reverseTopologyGraph(graph)))) + .isFalse(); + } + + private static DraftCommitBinding draftBinding( + DraftCommitBinding.TargetProof target, + UUID requestId, + UUID commitId, + UUID revisionId, + UUID regionId, + WorldDesignMutationRevision mutation, + UUID secondRevisionId, + UUID secondRegionId, + WorldDesignMutationRevision secondMutation) + throws Exception { + return DraftCommitBinding.create( + target, + requestId, + commitId, + "base-commit", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", revisionId, Owner.WORLD_MANAGEMENT, JsonFormat.printer().print(mutation)), + new DraftCommitBinding.RevisionPayload( + "1", + secondRevisionId, + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().print(secondMutation))), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + regionId.toString(), + "AGGREGATE", + regionId.toString(), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + regionId.toString(), + "REGION_SUBTREE", + regionId.toString(), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + secondRegionId.toString(), + "AGGREGATE", + secondRegionId.toString(), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + secondRegionId.toString(), + "REGION_SUBTREE", + secondRegionId.toString(), + "0"))); + } + + private static WorldDesignMutationRevision regionMutation( + UUID commitId, UUID revisionId, UUID regionId, String name) { + return WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revisionId.toString()) + .setCommitId(commitId.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setAggregateId(regionId.toString()) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(regionId.toString()) + .setScopeMutationPolicy( + WorldDesignScopeMutationPolicy.WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED) + .setRegion(RegionDesignMutation.newBuilder().setName(name)) + .build(); + } + + private static WorldDraftTopologyInputGraph topologyGraph( + UUID tenantId, + UUID versionId, + UUID revisionId, + UUID regionId, + WorldDesignMutationRevision mutation, + UUID secondRevisionId, + UUID secondRegionId, + WorldDesignMutationRevision secondMutation) { + return new WorldDraftTopologyInputGraph( + tenantId, + versionId, + List.of( + new WorldDraftTopologyInputGraph.Node( + "0", revisionId, regionId, regionId, mutation, null), + new WorldDraftTopologyInputGraph.Node( + "1", secondRevisionId, secondRegionId, secondRegionId, secondMutation, null)), + null); + } + + private static WorldDraftTopologyInputGraph reverseTopologyGraph( + WorldDraftTopologyInputGraph graph) { + return new WorldDraftTopologyInputGraph( + graph.tenantId(), + graph.versionId(), + List.of(graph.nodes().get(1), graph.nodes().get(0)), + graph.freshGraphDeclaration().orElse(null)); + } + + private static OwnerBinding ownerBinding(UUID tenantId, UUID versionId) { + return new OwnerBinding( + "firemud", + tenantId, + versionId, + UUID.randomUUID(), + 41L, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "1".repeat(64), + UUID.randomUUID(), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + } + + private static CaptureRequest freezeRequest(OwnerBinding owner, DraftCommitBinding binding) { + return new CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + UUID.randomUUID(), + "publication-request", + "4".repeat(64), + 7L, + PublicationDigestRequestBinding.full( + owner.canonicalTenantId().toString(), + Long.toString(owner.gameDesignVersionId()), + "publication-request") + .derivedWorkflowIdentity(), + binding.commitId().toString(), + "5".repeat(64), + 3, + binding.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList()); + } + + private static CaptureRequest copyFreezeRequest(CaptureRequest source) { + return new CaptureRequest( + source.targetNamespace(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.intakeRequestId(), + source.publicationFence(), + source.publicationRequestId(), + source.requestDigest(), + source.versionStateEpoch(), + source.publishWorkflowId(), + source.appliedCommitId(), + source.contentDigest(), + source.digestSchemaVersion(), + List.copyOf(source.suppliedOwnedAffectedTuples())); + } + + private static CaptureRequest withChangedAffectedTuple(CaptureRequest source) { + List tuples = new ArrayList<>(source.suppliedOwnedAffectedTuples()); + OwnedAffectedTuple first = tuples.get(0); + tuples.set( + 0, + new OwnedAffectedTuple( + first.owner(), + first.aggregateType(), + first.aggregateId(), + first.scopeType(), + first.scopeId(), + "1")); + return new CaptureRequest( + source.targetNamespace(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.intakeRequestId(), + source.publicationFence(), + source.publicationRequestId(), + source.requestDigest(), + source.versionStateEpoch(), + source.publishWorkflowId(), + source.appliedCommitId(), + source.contentDigest(), + source.digestSchemaVersion(), + tuples); + } + + private static OwnerBinding copyOwnerBinding(OwnerBinding source) { + return new OwnerBinding( + source.targetNamespace(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.versionIdentityOperationId(), + source.gameDesignVersionId(), + source.intakeRequestId(), + source.intakeOperationId(), + source.intakeRequestDigest(), + source.sourceOperationId(), + source.sourceEvidenceDigest(), + source.intakeReceiptDigest()); + } + + private static OwnerBinding withChangedOwnerEvidence(OwnerBinding source) { + return new OwnerBinding( + source.targetNamespace(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.versionIdentityOperationId(), + source.gameDesignVersionId(), + source.intakeRequestId(), + source.intakeOperationId(), + source.intakeRequestDigest(), + source.sourceOperationId(), + "sha256:" + "8".repeat(64), + source.intakeReceiptDigest()); + } + + private static Request requestWithFreeze(Request source, CaptureRequest freeze) { + Request request = mock(Request.class); + when(request.plan()).thenReturn(source.plan()); + when(request.freeze()).thenReturn(freeze); + return request; + } + + private static Request sourceRequest( + DraftCommitBinding binding, + OwnerBinding owner, + CaptureRequest freeze, + WorldDraftTopologyInputGraph graph) { + WorldDraftTopologyCommitPlan plan = mock(WorldDraftTopologyCommitPlan.class); + when(plan.binding()).thenReturn(binding); + when(plan.ownerBinding()).thenReturn(owner); + when(plan.graph()).thenReturn(graph); + return new Request(plan, freeze); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlanTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlanTest.java new file mode 100644 index 0000000000..8b1e9ab387 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlanTest.java @@ -0,0 +1,650 @@ +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.Mockito.mock; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Row; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Template; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.Entry; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.GenerationRuleIntent; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.SpawnBindingIntent; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.junit.jupiter.api.Test; + +/** + * These fixtures exercise the pure projection with synthetic frozen component values. They do not + * establish authenticated publication, persisted capture, release evidence, or instance writes. + */ +class WorldCanonicalInstanceTopologyPlanTest { + private static final UUID TENANT = uuid(1); + private static final UUID VERSION = uuid(2); + private static final UUID COMMIT = uuid(3); + private static final UUID REGION_A = uuid(10); + private static final UUID REGION_B = uuid(11); + private static final UUID ZONE_A1 = uuid(20); + private static final UUID ZONE_A2 = uuid(21); + private static final UUID ZONE_B = uuid(22); + private static final UUID ROOM_A1 = uuid(30); + private static final UUID ROOM_A2 = uuid(31); + private static final UUID ROOM_B = uuid(32); + private static final UUID EXIT_A = uuid(40); + private static final UUID RULE_A = uuid(50); + private static final UUID RULE_B = uuid(51); + private static final UUID SPAWN_A = uuid(60); + private static final UUID SPAWN_B = uuid(61); + private static final UUID ENTITY_ITEM = uuid(70); + private static final UUID ENTITY_NPC = uuid(71); + private static final byte[] GRAPH_BYTES = + "synthetic graph bytes".getBytes(StandardCharsets.UTF_8); + private static final byte[] STORAGE_BYTES = + "synthetic storage result".getBytes(StandardCharsets.UTF_8); + private static final byte[] RESULT_BYTES = + "synthetic capture result".getBytes(StandardCharsets.UTF_8); + + @Test + void projectsEveryFamilyWithAuthoredParentLinksAndExactRequiredIntents() throws Exception { + Fixture fixture = fixture(); + var projected = WorldCanonicalInstanceTopologyPlan.create(fixture.source()); + + assertThat(projected.regions()).hasSize(2); + assertThat(projected.zones()).hasSize(3); + assertThat(projected.rooms()).hasSize(3); + assertThat(projected.roomExits()).hasSize(1); + assertThat(projected.generationRules()).hasSize(2); + assertThat(projected.spawnBindings()).hasSize(2); + assertThat(projected.roomExits().getFirst().fromRoom()) + .isEqualTo(new Template(Family.ROOM, ROOM_A1)); + assertThat(projected.roomExits().getFirst().toRoom()) + .isEqualTo(new Template(Family.ROOM, ROOM_A2)); + assertThat(projected.roomExits().getFirst().source().identity()) + .isEqualTo(new Template(Family.ROOM_EXIT, EXIT_A)); + assertThat(projected.zones()) + .filteredOn(zone -> zone.identity().templateId().equals(ZONE_B)) + .singleElement() + .satisfies( + zone -> assertThat(zone.region()).isEqualTo(new Template(Family.REGION, REGION_B))); + assertThat(projected.rooms()) + .filteredOn(room -> room.identity().templateId().equals(ROOM_B)) + .singleElement() + .satisfies(room -> assertThat(room.zone()).isEqualTo(new Template(Family.ZONE, ZONE_B))); + + assertThat(projected.generationRules()) + .extracting(GenerationRuleIntent::requiredIntent) + .containsExactly( + GenerationRuleDesignMutation.newBuilder() + .setName("weather-profile") + .setValue("{ \"locale\" : \"Café\" }") + .build(), + GenerationRuleDesignMutation.newBuilder() + .setName("room-density") + .setValue("sparse") + .build()); + assertThat(projected.spawnBindings()) + .extracting(SpawnBindingIntent::requiredIntent) + .containsExactly( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(ROOM_A1.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM) + .setEntityTemplateId(ENTITY_ITEM.toString()) + .setSpawnCount(0) + .setRespawnDelaySeconds(300) + .build(), + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(ROOM_B.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(ENTITY_NPC.toString()) + .setSpawnCount(4) + .setRespawnDelaySeconds(60) + .build()); + assertThat( + projected + .spawnBindings() + .getFirst() + .source() + .content() + .getWorldEntitySpawnBinding() + .getSpawnCount()) + .isEqualTo(1); + assertThat(projected.spawnBindings().getFirst().entityReference().kind()) + .isEqualTo(EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM); + assertThat(projected.spawnBindings().getFirst().entityReference().tenantId()).isEqualTo(TENANT); + assertThat(projected.spawnBindings().getFirst().entityReference().versionId()) + .isEqualTo(VERSION); + assertThat(projected.spawnBindings().getFirst().entityReference().templateId()) + .isEqualTo(ENTITY_ITEM); + } + + @Test + void keepsSourceBindingPayloadBytesAndOrderingAcrossDeterministicRetries() throws Exception { + Fixture fixture = fixture(); + var first = WorldCanonicalInstanceTopologyPlan.create(fixture.source()); + var retry = WorldCanonicalInstanceTopologyPlan.create(fixture.source()); + + assertThat(first.captureId()).isEqualTo(uuid(100)); + assertThat(fixture.source().status()).isEqualTo(WorldCanonicalFrozenTopology.STATUS); + assertThat(first.sourceBinding()).isSameAs(fixture.source().request()); + assertThat(first.entries()).containsExactlyElementsOf(retry.entries()); + assertThat(first.entries()) + .extracting(Entry::identity) + .containsExactlyElementsOf(fixture.rows().stream().map(Row::template).toList()); + assertThat(fixture.source().graphBytes()).isEqualTo(GRAPH_BYTES); + assertThat(fixture.source().storageResultBytes()).isEqualTo(STORAGE_BYTES); + assertThat(fixture.source().resultBytes()).isEqualTo(RESULT_BYTES); + for (Entry entry : first.entries()) { + String exactPayload = + fixture.plan().binding().revisions().stream() + .filter( + revision -> + revision + .revisionId() + .equals( + uuidFrom(entry.source().authoredRevision().getLogicalRevisionId()))) + .findFirst() + .orElseThrow() + .payload(); + assertThat(entry.source().inputPayload()).isEqualTo(exactPayload); + assertThat(entry.source().inputPayloadBytes()) + .isEqualTo(exactPayload.getBytes(StandardCharsets.UTF_8)); + } + + var authoredRoom = + first.rooms().stream() + .filter(room -> room.identity().templateId().equals(ROOM_A1)) + .findFirst() + .orElseThrow(); + String expectedLocalizedName = "{ \"en-US\" : \"Café 🐉\", \"ja\" : \"雪\" }"; + String expectedLocalizedDescription = "{\"en-US\":\"A quiet room\"}"; + assertThat(authoredRoom.content().getNameLocalizedVariantsJson()) + .isEqualTo(expectedLocalizedName); + assertThat(authoredRoom.content().getDescriptionLocalizedVariantsJson()) + .isEqualTo(expectedLocalizedDescription); + assertThat(authoredRoom.source().authoredRevision().getRoom().getNameLocalizedVariantsJson()) + .isEqualTo(expectedLocalizedName); + } + + @Test + void rejectsMissingDuplicateAndTypeConfusedFrozenRows() throws Exception { + Fixture fixture = fixture(); + + List missingRegion = new ArrayList<>(fixture.rows()); + missingRegion.removeIf(row -> row.template().equals(new Template(Family.REGION, REGION_B))); + assertThatThrownBy( + () -> + WorldCanonicalInstanceTopologyPlan.create( + withRows(fixture, missingRegion).source())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("omits or adds"); + + List duplicated = new ArrayList<>(fixture.rows()); + duplicated.set(1, fixture.rows().getFirst()); + assertThatThrownBy( + () -> WorldCanonicalInstanceTopologyPlan.create(withRows(fixture, duplicated).source())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing, duplicated"); + + List typeConfused = new ArrayList<>(fixture.rows()); + Row zone = findRow(typeConfused, Family.ZONE, ZONE_A1); + int index = typeConfused.indexOf(zone); + typeConfused.set( + index, + new Row( + new Template(Family.REGION, ZONE_A1), + zone.mappingKey(), + zone.privateRowKey(), + zone.authored(), + zone.content())); + assertThatThrownBy( + () -> + WorldCanonicalInstanceTopologyPlan.create(withRows(fixture, typeConfused).source())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("confuses authored family"); + + List missingRoomReference = new ArrayList<>(fixture.rows()); + Row exit = findRow(missingRoomReference, Family.ROOM_EXIT, EXIT_A); + int exitIndex = missingRoomReference.indexOf(exit); + var badExitContent = + exit.content().toBuilder() + .setRoomExit(exit.content().getRoomExit().toBuilder().setToRoomId(uuid(999).toString())) + .build(); + missingRoomReference.set( + exitIndex, + new Row( + exit.template(), + exit.mappingKey(), + exit.privateRowKey(), + exit.authored(), + badExitContent)); + assertThatThrownBy( + () -> + WorldCanonicalInstanceTopologyPlan.create( + withRows(fixture, missingRoomReference).source())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Frozen content differs"); + } + + @Test + void sourceCommitPlanRejectsCrossRegionExitOutsideItsDeclaredSubtree() { + List mutations = mutations(); + for (int index = 0; index < mutations.size(); index++) { + var mutation = mutations.get(index); + if (UUID.fromString(mutation.getAggregateId()).equals(EXIT_A)) { + mutations.set( + index, + mutation.toBuilder() + .setRoomExit(mutation.getRoomExit().toBuilder().setToRoomId(ROOM_B.toString())) + .build()); + } + } + + assertThatThrownBy(() -> createPlan(mutations)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("outside declared scope"); + } + + private static Fixture fixture() throws Exception { + WorldDraftTopologyCommitPlan plan = createPlan(mutations()); + WorldCanonicalAuthoredGraph graph = graph(plan); + var request = new WorldCanonicalFrozenTopology.Request(plan, freeze(plan)); + WorldCanonicalFrozenTopology source = + new WorldCanonicalFrozenTopology( + uuid(100), + request, + mock(WorldAuthoredVersionIdentityReceipt.class), + graph, + GRAPH_BYTES, + STORAGE_BYTES, + RESULT_BYTES); + return new Fixture(source, plan, graph.rows()); + } + + private static Fixture withRows(Fixture original, List rows) { + WorldCanonicalAuthoredGraph graph = + new WorldCanonicalAuthoredGraph(TENANT, VERSION, 9001, 9002, rows); + WorldCanonicalFrozenTopology source = + new WorldCanonicalFrozenTopology( + original.source().captureId(), + original.source().request(), + mock(WorldAuthoredVersionIdentityReceipt.class), + graph, + GRAPH_BYTES, + STORAGE_BYTES, + RESULT_BYTES); + return new Fixture(source, original.plan(), rows); + } + + private static WorldDraftTopologyCommitPlan createPlan( + List mutations) throws InvalidProtocolBufferException { + List revisions = new ArrayList<>(); + List affected = new ArrayList<>(); + for (int index = 0; index < mutations.size(); index++) { + var mutation = mutations.get(index); + UUID revisionId = UUID.fromString(mutation.getLogicalRevisionId()); + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(index), + revisionId, + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(mutation))); + String aggregate = + mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + String scope = mutation.getScopeType().name().replace("WORLD_DESIGN_SCOPE_TYPE_", ""); + affected.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + aggregate, + mutation.getAggregateId(), + "AGGREGATE", + mutation.getAggregateId(), + "0")); + affected.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + aggregate, + mutation.getAggregateId(), + scope, + mutation.getScopeId(), + "0")); + } + DraftCommitBinding binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 41, "gd-tenant-41", 51, "gd-tenant-41", "NEW_GAME_ROW"), + uuid(80), + COMMIT, + "base-commit", + revisions, + affected); + return WorldDraftTopologyCommitPlan.create(binding, ownerBinding()); + } + + private static OwnerBinding ownerBinding() { + return new OwnerBinding( + "firemud", + TENANT, + VERSION, + uuid(81), + 41, + uuid(82), + uuid(83), + "sha256:" + "a".repeat(64), + uuid(84), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + } + + private static CaptureRequest freeze(WorldDraftTopologyCommitPlan plan) { + var owner = plan.ownerBinding(); + List affected = + plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + String publicationRequestId = "publication-request"; + return new CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + uuid(85), + publicationRequestId, + "d".repeat(64), + 7, + PublicationDigestRequestBinding.full( + TENANT.toString(), Long.toString(owner.gameDesignVersionId()), publicationRequestId) + .derivedWorkflowIdentity(), + plan.binding().commitId().toString(), + "e".repeat(64), + 3, + affected); + } + + private static WorldCanonicalAuthoredGraph graph(WorldDraftTopologyCommitPlan plan) { + List rows = new ArrayList<>(); + long key = 1; + for (var node : plan.graph().nodes()) { + Family family = family(node.mutation().getAggregateType()); + rows.add( + new Row( + new Template(family, node.templateId()), + key, + key + 1000, + node, + storageContent(node.mutation()))); + key++; + } + return new WorldCanonicalAuthoredGraph(TENANT, VERSION, 9001, 9002, rows); + } + + private static WorldDesignMutationRevision storageContent(WorldDesignMutationRevision mutation) { + return switch (mutation.getAggregateType()) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> + mutation.getRegion().getSpacingMultiplier() == 0 + ? mutation.toBuilder() + .setRegion(mutation.getRegion().toBuilder().setSpacingMultiplier(1.0)) + .build() + : mutation; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> + mutation.getRoomExit().getCost() == 0 + ? mutation.toBuilder() + .setRoomExit(mutation.getRoomExit().toBuilder().setCost(1)) + .build() + : mutation; + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> + mutation.getWorldEntitySpawnBinding().getSpawnCount() == 0 + ? mutation.toBuilder() + .setWorldEntitySpawnBinding( + mutation.getWorldEntitySpawnBinding().toBuilder().setSpawnCount(1)) + .build() + : mutation; + default -> mutation; + }; + } + + private static List mutations() { + String localizedName = "{ \"en-US\" : \"Café 🐉\", \"ja\" : \"雪\" }"; + String localizedDescription = "{\"en-US\":\"A quiet room\"}"; + List rows = new ArrayList<>(); + rows.add( + base( + 1, + REGION_A, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("Northern Reach") + .setWeather("snow") + .setGeneratorParams("{ \"seed\" : 17 }") + .setSpacingMultiplier(0)) + .build()); + rows.add( + base( + 2, + ZONE_A1, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setZone( + ZoneDesignMutation.newBuilder().setName("Harbor").setRegionId(REGION_A.toString())) + .build()); + rows.add( + base( + 3, + ROOM_A1, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("Quay") + .setDescription("Stone steps descend to the water.") + .setZoneId(ZONE_A1.toString()) + .setNameLocalizedVariantsJson(localizedName) + .setDescriptionLocalizedVariantsJson(localizedDescription)) + .build()); + rows.add( + base( + 4, + REGION_B, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_B) + .setRegion( + RegionDesignMutation.newBuilder().setName("Southern Reach").setWeather("clear")) + .build()); + rows.add( + base( + 5, + ZONE_B, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_B) + .setZone( + ZoneDesignMutation.newBuilder().setName("Lowland").setRegionId(REGION_B.toString())) + .build()); + rows.add( + base( + 6, + ROOM_B, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_B) + .setRoom(RoomDesignMutation.newBuilder().setName("Ford").setZoneId(ZONE_B.toString())) + .build()); + rows.add( + base( + 7, + ZONE_A2, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("Cliffside") + .setRegionId(REGION_A.toString())) + .build()); + rows.add( + base( + 8, + ROOM_A2, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setRoom( + RoomDesignMutation.newBuilder().setName("Beacon").setZoneId(ZONE_A2.toString())) + .build()); + rows.add( + base( + 9, + EXIT_A, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(ROOM_A1.toString()) + .setToRoomId(ROOM_A2.toString()) + .setDirection("east") + .setCost(0)) + .build()); + rows.add( + base( + 10, + RULE_A, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder() + .setName("weather-profile") + .setValue("{ \"locale\" : \"Café\" }")) + .build()); + rows.add( + base( + 11, + RULE_B, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE, + ZONE_B) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder() + .setName("room-density") + .setValue("sparse")) + .build()); + rows.add( + base( + 12, + SPAWN_A, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + REGION_A) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(ROOM_A1.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM) + .setEntityTemplateId(ENTITY_ITEM.toString()) + .setSpawnCount(0) + .setRespawnDelaySeconds(300)) + .build()); + rows.add( + base( + 13, + SPAWN_B, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE, + ZONE_B) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(ROOM_B.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(ENTITY_NPC.toString()) + .setSpawnCount(4) + .setRespawnDelaySeconds(60)) + .build()); + return rows; + } + + private static WorldDesignMutationRevision.Builder base( + int revision, + UUID identity, + WorldDesignAggregateType aggregate, + WorldDesignScopeType scopeType, + UUID scopeId) { + return WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(uuid(200 + revision).toString()) + .setCommitId(COMMIT.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(aggregate) + .setAggregateId(identity.toString()) + .setScopeType(scopeType) + .setScopeId(scopeId.toString()); + } + + private static Row findRow(List rows, Family family, UUID identity) { + return rows.stream() + .filter(row -> row.template().equals(new Template(family, identity))) + .findFirst() + .orElseThrow(); + } + + private static Family family(WorldDesignAggregateType aggregate) { + return switch (aggregate) { + case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> Family.REGION; + case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> Family.ZONE; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> Family.ROOM; + case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> Family.ROOM_EXIT; + case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> Family.GENERATION_RULE; + case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> + Family.WORLD_ENTITY_SPAWN_BINDING; + default -> throw new IllegalArgumentException("Unexpected test family"); + }; + } + + private static UUID uuidFrom(String value) { + return UUID.fromString(value); + } + + private static UUID uuid(int value) { + return UUID.fromString("00000000-0000-4000-8000-%012d".formatted(value)); + } + + private record Fixture( + WorldCanonicalFrozenTopology source, WorldDraftTopologyCommitPlan plan, List rows) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcServiceTest.java new file mode 100644 index 0000000000..da49a4a55f --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldGrpcServiceTest.java @@ -0,0 +1,308 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldService; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalPlayerAdmissionHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalPlayerAdmissionHoldResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Adapter-only mocked service/lifecycle fixtures; not authenticated transport or database proof. + */ +class WorldCanonicalPlayerAdmissionHoldGrpcServiceTest { + private final WorldCanonicalPlayerAdmissionHoldService service = + mock(WorldCanonicalPlayerAdmissionHoldService.class); + private final WorldCanonicalPlayerAdmissionHoldGrpcService adapter = + new WorldCanonicalPlayerAdmissionHoldGrpcService(service, "firemud"); + + @AfterEach + void clearContext() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) + TransactionSynchronizationManager.clearSynchronization(); + } + + @Test + void wrongPeerAndEndUserContextDenyBeforeAnyPrimitiveParsingOrOwnerAccess() { + for (String peer : + java.util.List.of( + "spiffe://firemud/ns/firemud/sa/game-session-service", + "spiffe://firemud/ns/other/sa/account-service")) { + peer(peer) + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(null, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(null, read); + assertThat(read.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + }); + } + SessionContext.setContext( + WorldCanonicalPlayerAdmissionHoldTest.ACCOUNT, java.util.List.of(), java.util.Map.of()); + account() + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(null, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(null, read); + assertThat(read.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + }); + verifyNoInteractions(service); + } + + @Test + void ambientTransactionAndSynchronizationDenyBeforeDecode() { + account() + .run( + () -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(null, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(null, read); + assertThat(read.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + }); + verifyNoInteractions(service); + } + + @Test + void acquireAndReadEchoFreshCorrelationAndExactOriginalBindingWithSeparateOuterDigest() { + var request = request(); + var held = mockedLifecycleHold(request); + when(service.acquire( + request.getOriginalLeaseJson().toStringUtf8(), + request.getOriginalLeaseSha256(), + 7L, + 8L)) + .thenReturn(held); + when(service.read( + request.getOriginalLeaseJson().toStringUtf8(), + request.getOriginalLeaseSha256(), + 7L, + 8L)) + .thenReturn(Optional.of(held)); + account() + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(request, acquire); + assertThat(acquire.error).isNull(); + assertThat(acquire.completed).isTrue(); + assertThat(acquire.value.getRequestId()).isEqualTo(request.getRequestId()); + assertThat(acquire.value.getOriginalLeaseSha256()) + .isEqualTo(request.getOriginalLeaseSha256()); + assertThat(acquire.value.getHoldEvidenceJson().toByteArray()) + .containsExactly(held.canonicalBytes()); + assertThat(acquire.value.getHoldEvidenceSha256()).isEqualTo(held.sha256()); + String readCorrelation = UUID.randomUUID().toString(); + var readRequest = + readRequest(request).toBuilder().setRequestId(readCorrelation).build(); + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(readRequest, read); + assertThat(read.error).isNull(); + assertThat(read.completed).isTrue(); + assertThat(read.value.getRequestId()).isEqualTo(readCorrelation); + assertThat(read.value.getOriginalLeaseSha256()) + .isEqualTo(request.getOriginalLeaseSha256()); + assertThat(read.value.getHoldEvidenceJson()) + .isEqualTo(acquire.value.getHoldEvidenceJson()); + assertThat(read.value.getHoldEvidenceSha256()) + .isEqualTo(acquire.value.getHoldEvidenceSha256()); + }); + } + + @Test + void missingReadIsUnresolvedAndNeverAnAbsenceOrReleaseProof() { + when(service.read(anyString(), anyString(), anyLong(), anyLong())).thenReturn(Optional.empty()); + account() + .run( + () -> { + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(readRequest(request()), read); + assertThat(read.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(read.value).isNull(); + assertThat(read.completed).isFalse(); + }); + } + + @Test + void malformedUnknownAndNoncanonicalPrimitivesDenyWithoutOwnerCalls() { + var original = request(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var changed : + java.util.List.of( + original.toBuilder().setRequestId("invalid").build(), + original.toBuilder().setExpectedLifecycleEpoch("07").build(), + original.toBuilder().setExpectedRowVersion("9223372036854775808").build(), + original.toBuilder().setOriginalLeaseSha256("b".repeat(64)).build(), + original.toBuilder() + .setOriginalLeaseJson(ByteString.copyFrom(new byte[] {(byte) 0xc3, 0x28})) + .build(), + original.toBuilder() + .setOriginalLeaseJson( + ByteString.copyFrom( + new byte + [net.firedevops.firemud.common.account.admission + .AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + + 1])) + .build(), + original.toBuilder().setUnknownFields(unknown).build())) { + account() + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(changed, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.INVALID_ARGUMENT); + }); + } + var unknownRead = readRequest(original).toBuilder().setUnknownFields(unknown).build(); + account() + .run( + () -> { + var read = new Collector(); + adapter.readCanonicalPlayerAdmissionHold(unknownRead, read); + assertThat(read.code()).isEqualTo(Status.Code.INVALID_ARGUMENT); + }); + verifyNoInteractions(service); + } + + @Test + void changedOwnerBindingOrWorldScopeCannotProduceResponse() { + var request = request(); + var held = mockedLifecycleHold(request); + var lease = WorldCanonicalPlayerAdmissionHoldTest.lease(); + var changedCarrier = new java.util.LinkedHashMap<>(lease.carrier()); + changedCarrier.put("leaseFence", "2"); + var changedLease = + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + .fromCarrier(changedCarrier); + var changed = + new WorldCanonicalPlayerAdmissionHoldEvidence( + held.holdId(), + held.holdFence(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request(changedLease, 7L, 8L), + held.worldEvidence()); + when(service.acquire(anyString(), anyString(), anyLong(), anyLong())).thenReturn(changed); + account() + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(request, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(acquire.value).isNull(); + }); + when(service.acquire(anyString(), anyString(), anyLong(), anyLong())).thenReturn(held); + when(held.worldEvidence().request().worldSlug()).thenReturn("substituted-world"); + account() + .run( + () -> { + var acquire = new Collector(); + adapter.acquireCanonicalPlayerAdmissionHold(request, acquire); + assertThat(acquire.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(acquire.value).isNull(); + }); + } + + private static AcquireCanonicalPlayerAdmissionHoldRequest request() { + var lease = WorldCanonicalPlayerAdmissionHoldTest.lease(); + return AcquireCanonicalPlayerAdmissionHoldRequest.newBuilder() + .setRequestId(UUID.randomUUID().toString()) + .setOriginalLeaseJson(ByteString.copyFromUtf8(lease.canonicalJson())) + .setOriginalLeaseSha256(lease.sha256()) + .setExpectedLifecycleEpoch("7") + .setExpectedRowVersion("8") + .build(); + } + + private static ReadCanonicalPlayerAdmissionHoldRequest readRequest( + AcquireCanonicalPlayerAdmissionHoldRequest request) { + return ReadCanonicalPlayerAdmissionHoldRequest.newBuilder() + .setRequestId(request.getRequestId()) + .setOriginalLeaseJson(request.getOriginalLeaseJson()) + .setOriginalLeaseSha256(request.getOriginalLeaseSha256()) + .setExpectedLifecycleEpoch(request.getExpectedLifecycleEpoch()) + .setExpectedRowVersion(request.getExpectedRowVersion()) + .build(); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence mockedLifecycleHold( + AcquireCanonicalPlayerAdmissionHoldRequest request) { + var lease = + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + .parseCanonical(request.getOriginalLeaseJson().toStringUtf8()); + var world = WorldCanonicalPlayerAdmissionHoldTest.evidence(); + // Opaque mocked lifecycle bytes test adapter serialization only. The Common test uses real + // complete nested codecs and independently verifies their canonical roundtrip. + when(world.canonicalBytes()) + .thenReturn("mocked lifecycle bytes".getBytes(StandardCharsets.UTF_8)); + return new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease, 7L, 8L), + world); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } + + private static Context account() { + return peer("spiffe://firemud/ns/firemud/sa/account-service"); + } + + private static final class Collector implements StreamObserver { + private T value; + private Status error; + private boolean completed; + + public void onNext(T response) { + value = response; + } + + public void onError(Throwable failure) { + error = Status.fromThrowable(failure); + } + + public void onCompleted() { + completed = true; + } + + private Status.Code code() { + return error.getCode(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java new file mode 100644 index 0000000000..b2590d6eb5 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldRepositoryTest.java @@ -0,0 +1,110 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldRepository; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalPlayerAdmissionHoldRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final WorldCanonicalInstanceAssociationRepository associations = + mock(WorldCanonicalInstanceAssociationRepository.class); + private final WorldCanonicalInstanceLifecycleReadRepository lifecycle = + mock(WorldCanonicalInstanceLifecycleReadRepository.class); + private final WorldCanonicalPlayerAdmissionHoldRepository repository = + new WorldCanonicalPlayerAdmissionHoldRepository( + dsl, manager, "firemud", associations, lifecycle); + + @AfterEach + void clearAmbientTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void directRepositoryAccessStillRequiresTheAuthenticatedAccountPeer() { + assertThatThrownBy(() -> repository.acquire(request())).isInstanceOf(SecurityException.class); + assertThatThrownBy(() -> repository.read(request())).isInstanceOf(SecurityException.class); + verifyNoInteractions(dsl, manager, associations, lifecycle); + } + + @Test + void accountWorkloadWithAuthenticatedEndUserContextCannotReachOwnerTransactionOrSql() { + SessionContext.setContext( + WorldCanonicalPlayerAdmissionHoldTest.ACCOUNT, java.util.List.of(), java.util.Map.of()); + try { + account() + .run( + () -> { + assertThatThrownBy(() -> repository.acquire(request())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy(() -> repository.read(request())) + .isInstanceOf(SecurityException.class); + }); + verifyNoInteractions(dsl, manager, associations, lifecycle); + } finally { + SessionContext.clear(); + } + } + + @Test + void authenticatedCallerCannotJoinAnAmbientTransactionForAcquireOrRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + account() + .run( + () -> { + assertThatThrownBy(() -> repository.acquire(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient"); + assertThatThrownBy(() -> repository.read(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient"); + }); + verifyNoInteractions(dsl, manager, associations, lifecycle); + } + + @Test + void substitutedNamespaceDeniesBeforeOpeningSqlTransaction() { + var carrier = WorldCanonicalPlayerAdmissionHoldTest.carrier(); + carrier.put("targetNamespace", "other"); + carrier.put("callerWorkload", "spiffe://firemud/ns/other/sa/game-session-service"); + var changed = + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence + .fromCarrier(carrier), + 7L, + 8L); + account() + .run( + () -> + assertThatThrownBy(() -> repository.acquire(changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("namespace")); + verifyNoInteractions(dsl, manager, associations, lifecycle); + } + + private static WorldCanonicalPlayerAdmissionHoldEvidence.Request request() { + return new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + WorldCanonicalPlayerAdmissionHoldTest.lease(), 7L, 8L); + } + + private static Context account() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/account-service") + .orElseThrow()); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java new file mode 100644 index 0000000000..f436211d11 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldServiceTest.java @@ -0,0 +1,122 @@ +package unit.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.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerAdmissionHoldService; +import org.junit.jupiter.api.Test; + +class WorldCanonicalPlayerAdmissionHoldServiceTest { + private final WorldCanonicalPlayerAdmissionHoldRepository repository = + mock(WorldCanonicalPlayerAdmissionHoldRepository.class); + private final WorldCanonicalPlayerAdmissionHoldService service = + new WorldCanonicalPlayerAdmissionHoldService(repository, "firemud"); + + @Test + void unauthenticatedOrWrongPeerDeniesBeforeDecodeOrOwnerAccess() { + assertThatThrownBy(() -> service.acquire(null, null, 0, 0)) + .isInstanceOf(SecurityException.class); + for (String uri : + java.util.List.of( + "spiffe://firemud/ns/firemud/sa/game-session-service", + "spiffe://firemud/ns/other/sa/account-service")) { + peer(uri) + .run( + () -> + assertThatThrownBy(() -> service.read(null, null, 0, 0)) + .isInstanceOf(SecurityException.class)); + } + verifyNoInteractions(repository); + } + + @Test + void accountWorkloadWithAuthenticatedEndUserContextDeniesBeforeDecodeOrOwnerAccess() { + SessionContext.setContext( + WorldCanonicalPlayerAdmissionHoldTest.ACCOUNT, java.util.List.of(), java.util.Map.of()); + try { + account() + .run( + () -> { + assertThatThrownBy(() -> service.acquire(null, null, 0, 0)) + .isInstanceOf(SecurityException.class); + assertThatThrownBy(() -> service.read(null, null, 0, 0)) + .isInstanceOf(SecurityException.class); + assertThatThrownBy(service::release).isInstanceOf(SecurityException.class); + }); + verifyNoInteractions(repository); + } finally { + SessionContext.clear(); + } + } + + @Test + void exactAccountProducerPassesOriginalLeaseWithoutChangingIdentity() { + var lease = WorldCanonicalPlayerAdmissionHoldTest.lease(); + var request = new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease, 7L, 8L); + var retained = + new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + request, + WorldCanonicalPlayerAdmissionHoldTest.evidence()); + when(repository.acquire(request)).thenReturn(retained); + when(repository.read(request)).thenReturn(Optional.of(retained)); + account() + .run( + () -> { + assertThat(service.acquire(lease.canonicalJson(), lease.sha256(), 7L, 8L)) + .isSameAs(retained); + assertThat(service.read(lease.canonicalJson(), lease.sha256(), 7L, 8L)) + .contains(retained); + }); + verify(repository).acquire(request); + verify(repository).read(request); + } + + @Test + void changedDigestOrNonCanonicalBytesDenyWithoutSql() { + var lease = WorldCanonicalPlayerAdmissionHoldTest.lease(); + account() + .run( + () -> { + assertThatThrownBy( + () -> service.acquire(lease.canonicalJson(), "b".repeat(64), 7L, 8L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> service.acquire(" " + lease.canonicalJson(), lease.sha256(), 7L, 8L)) + .isInstanceOf(IllegalArgumentException.class); + }); + verifyNoInteractions(repository); + } + + @Test + void releaseHasNoAcceptingPathEvenForAuthenticatedAccount() { + account() + .run( + () -> + assertThatThrownBy(service::release) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account terminal AND Game Session")); + verifyNoInteractions(repository); + } + + private static Context account() { + return peer("spiffe://firemud/ns/firemud/sa/account-service"); + } + + private static Context peer(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java new file mode 100644 index 0000000000..b067211b6c --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerAdmissionHoldTest.java @@ -0,0 +1,223 @@ +package unit.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.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalPlayerAdmissionHoldEvidence; +import org.junit.jupiter.api.Test; + +class WorldCanonicalPlayerAdmissionHoldTest { + static final String ID = "11111111-1111-4111-8111-111111111111"; + static final String ACCOUNT = "22222222-2222-4222-8222-222222222222"; + + @Test + void originalLeaseDefinesRetryIdentityWithoutRemintingOrRenewal() { + var lease = lease(); + var original = new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease, 7L, 8L); + var exact = + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + AccountGameplayAdmissionLeaseEvidence.parseCanonical(lease.canonicalJson()), 7L, 8L); + assertThat(original.sameBinding(exact)).isTrue(); + assertThat( + original.sameBinding( + new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease, 8L, 8L))) + .isFalse(); + var changed = carrier(); + changed.put("leaseFence", "2"); + assertThat( + original.sameBinding( + new WorldCanonicalPlayerAdmissionHoldEvidence.Request( + AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed), 7L, 8L))) + .isFalse(); + } + + @Test + void donorDelegationBoundsRemainExactWithoutWideningTheOriginalCarrier() { + var carrier = carrier(); + var tuple = new LinkedHashMap<>((Map) carrier.get("authorityTuple")); + tuple.put("issuerAuthGeneration", "9007199254740993"); + carrier.put("authorityTuple", tuple); + var exact = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + assertThat(exact.canonicalJson()).contains("9007199254740993"); + tuple.put("issuerAuthGeneration", "9223372036854775808"); + assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void worldLifecycleEpochRemainsSeparateFromLeaseRegionEpoch() { + var request = new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease(), 7L, 8L); + var evidence = evidence(); + var hold = + new WorldCanonicalPlayerAdmissionHoldEvidence( + UUID.randomUUID(), UUID.randomUUID(), request, evidence); + assertThat(hold.worldEvidence().lifecycleEpoch()).isEqualTo(7L); + assertThat(hold.diagnosticExpiresAtMillis()) + .isEqualTo(Long.parseLong((String) request.lease().carrier().get("expiresAt"))); + when(evidence.lifecycleEpoch()).thenReturn(9L); + assertThatThrownBy(() -> request.requireExactActiveWorld(evidence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact expected ACTIVE"); + } + + @Test + void inactiveMembershipAndIsolatedScopeAreNotRepairable() { + var changed = carrier(); + changed.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "INACTIVE", + "membershipVersion", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + "1")); + var inactiveLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); + assertThatThrownBy( + () -> new WorldCanonicalPlayerAdmissionHoldEvidence.Request(inactiveLease, 7L, 8L)) + .isInstanceOf(IllegalArgumentException.class); + changed = carrier(); + var scope = new LinkedHashMap<>(scope(changed)); + scope.put("playableStateScope", "ISOLATED"); + changed.put("bindingScope", scope); + var isolated = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changed); + assertThatThrownBy( + () -> new WorldCanonicalPlayerAdmissionHoldEvidence.Request(isolated, 7L, 8L)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void substitutedWorldTenantOrNonActiveTupleIsDenied() { + var request = new WorldCanonicalPlayerAdmissionHoldEvidence.Request(lease(), 7L, 8L); + var evidence = evidence(); + when(evidence.request().canonicalTenantId()).thenReturn(UUID.fromString(ACCOUNT)); + var substituted = evidence; + assertThatThrownBy(() -> request.requireExactActiveWorld(substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical World scope"); + evidence = evidence(); + when(evidence.lifecycleStatus()).thenReturn("TERMINATING"); + var inactive = evidence; + assertThatThrownBy(() -> request.requireExactActiveWorld(inactive)) + .isInstanceOf(IllegalArgumentException.class); + } + + static WorldCanonicalInstanceLifecycleEvidence evidence() { + var selector = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); + when(selector.targetNamespace()).thenReturn("firemud"); + when(selector.canonicalTenantId()).thenReturn(UUID.fromString(ID)); + when(selector.worldSlug()).thenReturn("world"); + when(selector.canonicalGameInstanceId()).thenReturn(UUID.fromString(ID)); + when(selector.playableStateNamespaceId()).thenReturn(UUID.fromString(ID)); + when(selector.playableStateScope()).thenReturn("SHARED"); + when(selector.publicProduction()).thenReturn(true); + var evidence = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(evidence.request()).thenReturn(selector); + when(evidence.lifecycleStatus()).thenReturn("ACTIVE"); + when(evidence.lifecycleEpoch()).thenReturn(7L); + when(evidence.rowVersion()).thenReturn(8L); + return evidence; + } + + static AccountGameplayAdmissionLeaseEvidence lease() { + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier()); + } + + /** Synthetic lease shape only: no Account authentication, sources, or terminal proof. */ + static Map carrier() { + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", "firemud"); + value.put("callerWorkload", "spiffe://firemud/ns/firemud/sa/game-session-service"); + value.put("requestId", ID); + value.put("leaseId", ACCOUNT); + value.put("leaseFence", "1"); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "tenantId", + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, ID); + scope.put("accountId", ACCOUNT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "9007199254740993"); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + Map.of(ID, "1"), + "privateRealmGrantVersions", + List.of())); + value.put("issuanceFence", "1"); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(ID, "1"), + "membershipAuthorityGeneration", + "1")); + value.put( + "outboxCheckpoints", + List.of( + checkpoint("account/" + ACCOUNT, "0"), + checkpoint("issuer/firemud-account-service", "0"), + checkpoint("membership/" + ACCOUNT + "/" + ID, "1"), checkpoint("tenant/" + ID, "1"))); + long now = System.currentTimeMillis(); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", ACCOUNT), + Map.entry("operationId", ID), + Map.entry("issuanceRequestId", ID), + Map.entry("tokenJti", ID), + Map.entry("tokenSHA256", "a".repeat(64)), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", "1"), + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("issuedAt", Long.toString(now / 1000)), + Map.entry("notBefore", Long.toString(now / 1000)), + Map.entry("expiresAt", Long.toString(now / 1000 + 300)))); + value.put("evaluatedAt", Long.toString(now)); + value.put("expiresAt", Long.toString(now + 15000)); + return value; + } + + @SuppressWarnings("unchecked") + static Map scope(Map carrier) { + return (Map) carrier.get("bindingScope"); + } + + private static Map checkpoint(String suffix, String sequence) { + return Map.of( + "outboxStreamKey", "account:auth-authority:v1:" + suffix, "outboxSequence", sequence); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java new file mode 100644 index 0000000000..18cf8d7f90 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java @@ -0,0 +1,1301 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalCurrentPlayerLocationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalCurrentPlayerLocationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerLocationGrpcService; +import net.firedevops.firemud.worldmanagement.v1.PlaceCanonicalInitialPlayerLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.PlaceCanonicalInitialPlayerLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalCurrentPlayerLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalCurrentPlayerLocationResponse; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalPlayerLocationGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final UUID OPERATION_ID = uuid("a0000000-0000-4000-8000-000000000001"); + private static final UUID OTHER_OPERATION_ID = uuid("10000000-0000-4000-8000-000000000002"); + private static final UUID REGION_INSTANCE_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID OPERATIONAL_REGION_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + @Test + void rejectsMissingWrongOrWrongNamespacePeerBeforeParsingOrOwnerAccess() throws Exception { + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + var grpc = service(placementService, currentService); + var malformed = placeRequest(new byte[] {1}, new byte[] {1}); + var malformedRead = readRequest("not-a-uuid", new byte[] {1}, new byte[] {1}); + + Collector missing = + callPlace(grpc, malformed, null); + Collector wrongService = + callPlace(grpc, malformed, peer("account-service", NAMESPACE)); + Collector wrongNamespace = + callPlace(grpc, malformed, peer("game-session-service", "other")); + Collector readWrongService = + callRead(grpc, malformedRead, peer("account-service", NAMESPACE)); + + assertThat(missing.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongService.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(readWrongService.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(placementService, currentService); + } + + @Test + void rejectsAuthenticatedEndUserContextBeforeParsingOrOwnerAccess() throws Exception { + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + var grpc = service(placementService, currentService); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Collector placeResult; + Collector readResult; + try { + placeResult = + callPlace( + grpc, + placeRequest(new byte[] {1}, new byte[] {1}), + peer("game-session-service", NAMESPACE)); + readResult = + callRead( + grpc, + readRequest("not-a-uuid", new byte[] {1}, new byte[] {1}), + peer("game-session-service", NAMESPACE)); + } finally { + SessionContext.clear(); + } + + assertThat(placeResult.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(readResult.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(placementService, currentService); + } + + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeParsingOrOwnerAccess() { + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + var grpc = service(placementService, currentService); + var malformedPlace = placeRequest(new byte[] {1}, new byte[] {1}); + var malformedRead = readRequest("not-a-uuid", new byte[] {1}, new byte[] {1}); + + TransactionSynchronizationManager.setActualTransactionActive(true); + Collector transactionPlace; + try { + transactionPlace = callPlace(grpc, malformedPlace, peer("game-session-service", NAMESPACE)); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + Collector synchronizationRead; + try { + synchronizationRead = callRead(grpc, malformedRead, peer("game-session-service", NAMESPACE)); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + + assertThat(transactionPlace.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(synchronizationRead.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(placementService, currentService); + } + + @Test + void rejectsUnknownEmptyMalformedAndNamespaceSubstitutedEvidenceBeforeOwnerAccess() + throws Exception { + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + var grpc = service(placementService, currentService); + var fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + var unknownPlace = + placeRequest(fixture.request().canonicalRequestBytes(), fixture.originalLifecycleBytes()) + .toBuilder() + .setUnknownFields(unknownField()) + .build(); + var unknownRead = + readRequest( + fixture.readRequestId().toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()) + .toBuilder() + .setUnknownFields(unknownField()) + .build(); + + assertThat(callPlace(grpc, unknownPlace, peer("game-session-service", NAMESPACE)).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callPlace( + grpc, + placeRequest(new byte[0], fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callPlace( + grpc, + placeRequest(fixture.request().canonicalRequestBytes(), new byte[0]), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callPlace( + grpc, + placeRequest(new byte[] {1}, fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + String canonicalPlacementRequest = + new String(fixture.request().canonicalRequestBytes(), StandardCharsets.UTF_8); + assertThat( + callPlace( + grpc, + placeRequest( + canonicalPlacementRequest + .replace(OPERATION_ID.toString(), NIL_UUID.toString()) + .getBytes(StandardCharsets.UTF_8), + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callPlace( + grpc, + placeRequest( + canonicalPlacementRequest + .replace(OPERATION_ID.toString(), OPERATION_ID.toString().toUpperCase()) + .getBytes(StandardCharsets.UTF_8), + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(callRead(grpc, unknownRead, peer("game-session-service", NAMESPACE)).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callRead( + grpc, + readRequest( + fixture.readRequestId().toString(), + new byte[0], + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callRead( + grpc, + readRequest( + fixture.readRequestId().toString(), + fixture.request().canonicalRequestBytes(), + new byte[0]), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callRead( + grpc, + readRequest( + fixture.readRequestId().toString(), + new byte[] {1}, + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callRead( + grpc, + readRequest( + NIL_UUID.toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callRead( + grpc, + readRequest( + fixture.readRequestId().toString().toUpperCase(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + callRead( + grpc, + readRequest( + "not-a-uuid", + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + Fixture reusedOperationId = fixture(NAMESPACE, OPERATION_ID.toString()); + assertThat( + callRead( + grpc, + readRequest( + OPERATION_ID.toString(), + reusedOperationId.request().canonicalRequestBytes(), + reusedOperationId.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + Fixture otherNamespace = fixture("other", "b0000000-0000-4000-8000-000000000002"); + assertThat( + callPlace( + grpc, + placeRequest( + otherNamespace.request().canonicalRequestBytes(), + otherNamespace.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + callRead( + grpc, + readRequest( + otherNamespace.readRequestId().toString(), + otherNamespace.request().canonicalRequestBytes(), + otherNamespace.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)) + .error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(placementService, currentService); + } + + @Test + void rejectsReadCorrelationThatDoesNotMatchFullCurrentLifecycleEvidence() throws Exception { + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + var grpc = service(placementService, currentService); + var fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + + Collector result = + callRead( + grpc, + readRequest( + "b0000000-0000-4000-8000-000000000002", + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)); + + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(placementService, currentService); + } + + @Test + void defaultPlacementAndCurrentLocationVerifiersDenyOwnerAccess() throws Exception { + var placementRepository = mock(WorldCanonicalInitialPlayerLocationRepository.class); + var currentRepository = mock(WorldCanonicalCurrentPlayerLocationRepository.class); + var placementService = new WorldCanonicalInitialPlayerLocationService(placementRepository); + var currentService = new WorldCanonicalCurrentPlayerLocationService(currentRepository); + var grpc = service(placementService, currentService); + var fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + + Collector placeResult = + callPlace( + grpc, + placeRequest( + fixture.request().canonicalRequestBytes(), fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)); + Collector readResult = + callRead( + grpc, + readRequest( + fixture.readRequestId().toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)); + + assertThat(placeResult.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(readResult.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verify(placementRepository, never()).place(any(), any()); + verify(currentRepository, never()).read(any(), any()); + } + + @Test + void exactPlacementRetryWithFreshLifecycleReadIdReturnsOriginalImmutableResult() + throws Exception { + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + var grpc = service(placementService, currentService); + Fixture original = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + Fixture retry = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000002"); + assertThat(retry.request().canonicalRequestBytes()) + .containsExactly(original.request().canonicalRequestBytes()); + var stored = + WorldCanonicalInitialPlayerLocation.Result.applied( + original.request(), + original.lifecycleEvidence().startLocation(), + original.lifecycleEvidence().runtimeRoomInstanceId()); + var exactRetryResult = + WorldCanonicalInitialPlayerLocation.Result.fromStored( + retry.request(), stored.canonicalBytes()); + when(placementService.place(any())).thenReturn(exactRetryResult); + + Collector response = + callPlace( + grpc, + placeRequest(retry.request().canonicalRequestBytes(), retry.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)); + + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.value.getCanonicalResultBytes().toByteArray()) + .containsExactly(stored.canonicalBytes()); + ArgumentCaptor captor = + ArgumentCaptor.forClass(WorldCanonicalInitialPlayerLocation.Request.class); + verify(placementService).place(captor.capture()); + assertThat(captor.getValue().originalLifecycleEvidenceBytes()) + .containsExactly(retry.originalLifecycleBytes()); + } + + @Test + void rejectsPlacementConflictAndMapsStorageFailures() throws Exception { + Fixture fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + var conflictService = mock(WorldCanonicalInitialPlayerLocationService.class); + when(conflictService.place(any())) + .thenReturn( + WorldCanonicalInitialPlayerLocation.Result.conflict( + fixture.request(), "ACTOR_CONFLICT")); + var transientService = mock(WorldCanonicalInitialPlayerLocationService.class); + when(transientService.place(any())) + .thenThrow(new TransientDataAccessException("temporary store issue") {}); + var permanentService = mock(WorldCanonicalInitialPlayerLocationService.class); + when(permanentService.place(any())) + .thenThrow( + new DataAccessException("permanent store issue", new SQLException("bad schema")) {}); + var unknownService = mock(WorldCanonicalInitialPlayerLocationService.class); + when(unknownService.place(any())).thenThrow(new IllegalStateException("unexpected failure")); + + var conflict = + callPlace( + service(conflictService, mock(WorldCanonicalCurrentPlayerLocationService.class)), + placeRequest( + fixture.request().canonicalRequestBytes(), fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)); + var unavailable = + callPlace( + service(transientService, mock(WorldCanonicalCurrentPlayerLocationService.class)), + placeRequest( + fixture.request().canonicalRequestBytes(), fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)); + var internal = + callPlace( + service(permanentService, mock(WorldCanonicalCurrentPlayerLocationService.class)), + placeRequest( + fixture.request().canonicalRequestBytes(), fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)); + var unknown = + callPlace( + service(unknownService, mock(WorldCanonicalCurrentPlayerLocationService.class)), + placeRequest( + fixture.request().canonicalRequestBytes(), fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)); + + assertThat(conflict.error).isEqualTo(Status.Code.ALREADY_EXISTS); + assertThat(unavailable.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(internal.error).isEqualTo(Status.Code.INTERNAL); + assertThat(unknown.error).isEqualTo(Status.Code.INTERNAL); + } + + @Test + void foundLocationReturnsExactLifecycleResultProofAndDistinctRegionUuids() throws Exception { + var fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + Fixture originalPlacement = fixture(NAMESPACE, "c0000000-0000-4000-8000-000000000001"); + var immutableResult = + WorldCanonicalInitialPlayerLocation.Result.applied( + originalPlacement.request(), + originalPlacement.lifecycleEvidence().startLocation(), + originalPlacement.lifecycleEvidence().runtimeRoomInstanceId()); + var retainedResult = + WorldCanonicalInitialPlayerLocation.Result.fromStored( + fixture.request(), immutableResult.canonicalBytes()); + var current = + currentLocation(fixture, originalPlacement.originalLifecycleBytes(), retainedResult); + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + when(currentService.read(any())).thenReturn(Optional.of(current)); + var grpc = service(placementService, currentService); + + Collector response = + callRead( + grpc, + readRequest( + fixture.readRequestId().toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)); + + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value.getReadRequestId()).isEqualTo(fixture.readRequestId().toString()); + assertThat(response.value.getPlacementOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.value.getPlacementRequestDigest()) + .isEqualTo(fixture.request().requestDigest()); + assertThat(response.value.getCurrentLifecycleEvidenceBytes().toByteArray()) + .containsExactly(fixture.originalLifecycleBytes()); + assertThat(response.value.getImmutablePlacementResultBytes().toByteArray()) + .containsExactly(immutableResult.canonicalBytes()); + assertThat(response.value.getOriginalPlacementLifecycleEvidenceBytes().toByteArray()) + .containsExactly(originalPlacement.originalLifecycleBytes()); + assertThat(response.value.getRegionInstanceId()).isEqualTo(REGION_INSTANCE_ID.toString()); + assertThat(response.value.getOperationalRegionId()).isEqualTo(OPERATIONAL_REGION_ID.toString()); + verify(currentService).read(any()); + verifyNoInteractions(placementService); + } + + @Test + void emptyCurrentPlacementMapsToNotFound() throws Exception { + var fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + when(currentService.read(any())).thenReturn(Optional.empty()); + var grpc = service(mock(WorldCanonicalInitialPlayerLocationService.class), currentService); + + Collector response = + callRead( + grpc, + readRequest( + fixture.readRequestId().toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)); + + assertThat(response.error).isEqualTo(Status.Code.NOT_FOUND); + } + + @Test + void substitutedReturnedBindingResultOrRegionEvidenceFailsClosed() throws Exception { + Fixture fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + Fixture original = fixture(NAMESPACE, "c0000000-0000-4000-8000-000000000001"); + var immutableResult = + WorldCanonicalInitialPlayerLocation.Result.applied( + original.request(), + original.lifecycleEvidence().startLocation(), + original.lifecycleEvidence().runtimeRoomInstanceId()); + var validResult = + WorldCanonicalInitialPlayerLocation.Result.fromStored( + fixture.request(), immutableResult.canonicalBytes()); + var changedBindingRequest = placementRequestWithOperation(fixture, OTHER_OPERATION_ID); + var changedBindingResult = + WorldCanonicalInitialPlayerLocation.Result.applied( + changedBindingRequest, + changedBindingRequest.activeLifecycleEvidence().startLocation(), + changedBindingRequest.activeLifecycleEvidence().runtimeRoomInstanceId()); + var changedBindingLocation = + currentLocation( + fixture, + original.originalLifecycleBytes(), + changedBindingResult, + changedBindingRequest); + var bindingError = readForgedCurrent(fixture, changedBindingLocation); + + var substitutedResult = + mock(WorldCanonicalCurrentPlayerLocationRepository.CurrentLocation.class); + var changedResult = + WorldCanonicalInitialPlayerLocation.Result.applied( + placementRequestWithOperation(fixture, OTHER_OPERATION_ID), + fixture.lifecycleEvidence().startLocation(), + fixture.lifecycleEvidence().runtimeRoomInstanceId()); + stubCurrentLocation( + substitutedResult, fixture, original.originalLifecycleBytes(), changedResult); + var resultError = readForgedCurrent(fixture, substitutedResult); + + var substitutedRegion = + mock(WorldCanonicalCurrentPlayerLocationRepository.CurrentLocation.class); + stubCurrentLocation(substitutedRegion, fixture, original.originalLifecycleBytes(), validResult); + when(substitutedRegion.operationalRegionId()).thenReturn(REGION_INSTANCE_ID); + var regionError = readForgedCurrent(fixture, substitutedRegion); + + assertThat(bindingError).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(resultError).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(regionError).isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + @Test + void mapsCurrentLocationStorageFailureAndUnknownFailure() throws Exception { + var fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + var transientService = mock(WorldCanonicalCurrentPlayerLocationService.class); + when(transientService.read(any())) + .thenThrow(new TransientDataAccessException("temporary store issue") {}); + var permanentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + when(permanentService.read(any())) + .thenThrow( + new DataAccessException("permanent store issue", new SQLException("bad schema")) {}); + var unknownService = mock(WorldCanonicalCurrentPlayerLocationService.class); + when(unknownService.read(any())).thenThrow(new IllegalStateException("unexpected failure")); + + var request = + readRequest( + fixture.readRequestId().toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()); + var unavailable = + callRead( + service(mock(WorldCanonicalInitialPlayerLocationService.class), transientService), + request, + peer("game-session-service", NAMESPACE)); + var internal = + callRead( + service(mock(WorldCanonicalInitialPlayerLocationService.class), permanentService), + request, + peer("game-session-service", NAMESPACE)); + var unknown = + callRead( + service(mock(WorldCanonicalInitialPlayerLocationService.class), unknownService), + request, + peer("game-session-service", NAMESPACE)); + + assertThat(unavailable.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(internal.error).isEqualTo(Status.Code.INTERNAL); + assertThat(unknown.error).isEqualTo(Status.Code.INTERNAL); + } + + private static Status.Code readForgedCurrent( + Fixture fixture, WorldCanonicalCurrentPlayerLocationRepository.CurrentLocation location) { + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + when(currentService.read(any())).thenReturn(Optional.of(location)); + var isolated = service(mock(WorldCanonicalInitialPlayerLocationService.class), currentService); + Collector result = + callRead( + isolated, + readRequest( + fixture.readRequestId().toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("game-session-service", NAMESPACE)); + return result.error; + } + + private static WorldCanonicalCurrentPlayerLocationRepository.CurrentLocation currentLocation( + Fixture currentFixture, + byte[] originalPlacementLifecycleBytes, + WorldCanonicalInitialPlayerLocation.Result placementResult) { + return currentLocation( + currentFixture, originalPlacementLifecycleBytes, placementResult, currentFixture.request()); + } + + private static WorldCanonicalCurrentPlayerLocationRepository.CurrentLocation currentLocation( + Fixture currentFixture, + byte[] originalPlacementLifecycleBytes, + WorldCanonicalInitialPlayerLocation.Result placementResult, + WorldCanonicalInitialPlayerLocation.Request binding) { + return new WorldCanonicalCurrentPlayerLocationRepository.CurrentLocation( + binding, + currentFixture.lifecycleEvidence(), + 101L, + currentFixture.lifecycleEvidence().startLocation(), + currentFixture.lifecycleEvidence().runtimeRoomInstanceId(), + 202L, + REGION_INSTANCE_ID, + OPERATIONAL_REGION_ID, + placementResult, + originalPlacementLifecycleBytes); + } + + private static WorldCanonicalInitialPlayerLocation.Request placementRequestWithOperation( + Fixture fixture, UUID operationId) { + return placementRequest(fixture.lifecycleEvidence(), operationId); + } + + private static void stubCurrentLocation( + WorldCanonicalCurrentPlayerLocationRepository.CurrentLocation location, + Fixture fixture, + byte[] originalPlacementLifecycleBytes, + WorldCanonicalInitialPlayerLocation.Result result) { + when(location.binding()).thenReturn(fixture.request()); + when(location.currentLifecycleEvidence()).thenReturn(fixture.lifecycleEvidence()); + when(location.startLocation()).thenReturn(fixture.lifecycleEvidence().startLocation()); + when(location.runtimeRoomInstanceId()) + .thenReturn(fixture.lifecycleEvidence().runtimeRoomInstanceId()); + when(location.canonicalRegionInstanceId()).thenReturn(REGION_INSTANCE_ID); + when(location.operationalRegionId()).thenReturn(OPERATIONAL_REGION_ID); + when(location.placementResult()).thenReturn(result); + when(location.originalLifecycleEvidenceBytes()).thenReturn(originalPlacementLifecycleBytes); + } + + private static WorldCanonicalPlayerLocationGrpcService service( + WorldCanonicalInitialPlayerLocationService placementService, + WorldCanonicalCurrentPlayerLocationService currentService) { + return new WorldCanonicalPlayerLocationGrpcService(placementService, currentService, NAMESPACE); + } + + private static PlaceCanonicalInitialPlayerLocationRequest placeRequest( + byte[] canonicalRequestBytes, byte[] lifecycleEvidenceBytes) { + return PlaceCanonicalInitialPlayerLocationRequest.newBuilder() + .setCanonicalRequestBytes(ByteString.copyFrom(canonicalRequestBytes)) + .setOriginalLifecycleEvidenceBytes(ByteString.copyFrom(lifecycleEvidenceBytes)) + .build(); + } + + private static ReadCanonicalCurrentPlayerLocationRequest readRequest( + String readRequestId, byte[] canonicalRequestBytes, byte[] lifecycleEvidenceBytes) { + return ReadCanonicalCurrentPlayerLocationRequest.newBuilder() + .setReadRequestId(readRequestId) + .setCanonicalPlacementRequestBytes(ByteString.copyFrom(canonicalRequestBytes)) + .setOriginalLifecycleEvidenceBytes(ByteString.copyFrom(lifecycleEvidenceBytes)) + .build(); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static Collector callPlace( + WorldCanonicalPlayerLocationGrpcService service, + PlaceCanonicalInitialPlayerLocationRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector<>(); + Context context = + peer == null + ? Context.current() + : Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.placeCanonicalInitialPlayerLocation(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static Collector callRead( + WorldCanonicalPlayerLocationGrpcService service, + ReadCanonicalCurrentPlayerLocationRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector<>(); + Context context = + peer == null + ? Context.current() + : Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readCanonicalCurrentPlayerLocation(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static Fixture fixture(String namespace, String readRequestId) throws Exception { + var lifecycleEvidence = lifecycleEvidence(namespace, readRequestId); + var request = placementRequest(lifecycleEvidence, OPERATION_ID); + return new Fixture( + request, + lifecycleEvidence, + lifecycleEvidence.canonicalBytes(), + lifecycleEvidence.request().readRequestId()); + } + + private static WorldCanonicalInitialPlayerLocation.Request placementRequest( + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence, UUID operationId) { + UUID tenant = lifecycleEvidence.request().canonicalTenantId(); + return new WorldCanonicalInitialPlayerLocation.Request( + operationId, + tenant, + lifecycleEvidence.request().canonicalVersionId(), + lifecycleEvidence.request().worldSlug(), + lifecycleEvidence.request().canonicalGameInstanceId(), + lifecycleEvidence.request().playableStateNamespaceId(), + lifecycleEvidence.request().playableStateScope(), + uuid("60000000-0000-4000-8000-000000000001"), + uuid("70000000-0000-4000-8000-000000000001"), + uuid("80000000-0000-4000-8000-000000000001"), + "a".repeat(64), + uuid("90000000-0000-4000-8000-000000000001"), + uuid("a0000000-0000-4000-8000-000000000001"), + "initial-request", + "b".repeat(64), + 1, + "owner-proof", + "c".repeat(64), + "pointer-audit", + 1, + WorldCanonicalInitialPlayerLocation.InitialAdmissionOrigin.NO_PRIOR_POINTER, + lifecycleEvidence); + } + + private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence( + String namespace, String readRequestId) throws Exception { + WorldPublishedStartLocationEvidence selector = publishedSelector(namespace); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + var binding = new CompleteLaunchBindingEvidence(descriptor, release); + var selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + uuid(readRequestId), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + selectorReceipt.startLocation(), + 1042L, + "ACTIVE", + 3L, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64), + java.util.Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + + private static WorldPublishedStartLocationEvidence publishedSelector(String namespace) + throws Exception { + DraftCommitBinding draft = freshGraphBinding(); + byte[] accountBytes = accountBinding(draft); + var terminalRequest = + new WorldDraftTerminalReadEvidence.Request( + 1, namespace, uuid("33333333-3333-4333-8333-333333333333"), accountBytes); + var account = terminalRequest.accountBinding(); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var selectorRequest = + new WorldPublishedStartLocationEvidence.Request( + namespace, + account.tenantId(), + account.versionId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + byte[] appliedBytes = appliedResult(terminalRequest, draft); + byte[] receiptBytes = receiptBytes(terminalRequest, draft, appliedBytes); + // Construction validates the complete original Account binding, APPLIED receipt, operation + // identity, exact World affected set, and selector bytes. + return new WorldPublishedStartLocationEvidence( + selectorRequest, receiptBytes, accountBytes, appliedBytes); + } + + private static DraftCommitBinding freshGraphBinding() throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", + "11111111-1111-4111-8111-111111111111", + "versionId", + "22222222-2222-4222-8222-222222222222", + "startLocation", + Map.of( + "tenantId", "11111111-1111-4111-8111-111111111111", + "versionId", "22222222-2222-4222-8222-222222222222", + "roomTemplateId", "77777777-7777-4777-8777-777777777777"), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + UUID tenantId = uuid("11111111-1111-4111-8111-111111111111"); + UUID versionId = uuid("22222222-2222-4222-8222-222222222222"); + UUID commitId = uuid("55555555-5555-4555-8555-555555555555"); + UUID regionId = uuid("88888888-8888-4888-8888-888888888888"); + UUID zoneId = uuid("99999999-9999-4999-8999-999999999999"); + UUID roomId = uuid("77777777-7777-4777-8777-777777777777"); + UUID regionRevision = uuid("12345678-1234-4234-8234-123456789001"); + UUID zoneRevision = uuid("12345678-1234-4234-8234-123456789002"); + UUID roomRevision = uuid("12345678-1234-4234-8234-123456789003"); + return DraftCommitBinding.create( + new TargetProof(tenantId, versionId, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + uuid("44444444-4444-4444-8444-444444444444"), + commitId, + "base-1", + List.of( + new RevisionPayload( + "0", + regionRevision, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + regionRevision, + commitId, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + regionId, + declaration)), + new RevisionPayload( + "1", + zoneRevision, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + zoneRevision, commitId, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", zoneId, null)), + new RevisionPayload( + "2", + roomRevision, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + roomRevision, commitId, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", roomId, null))), + List.of( + affected("REGION", regionId, "REGION_SUBTREE", regionId), + affected("ZONE", zoneId, "REGION_SUBTREE", regionId), + affected("ROOM", roomId, "ZONE_SUBTREE", zoneId)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static String worldRevisionPayload( + UUID revisionId, UUID commitId, String family, UUID templateId, String declaration) + throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", commitId.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static byte[] appliedResult( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var account = request.accountBinding(); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = graphBytes(request, draft); + String graphDigest = sha256(graph); + var result = new java.util.LinkedHashMap(); + result.put("schema", "world-draft-graph-applied/v2"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + var receipt = receiptJson(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", unit.aggregateType(), + "aggregateId", unit.aggregateId(), + "scopeType", unit.scopeType(), + "scopeId", unit.scopeId(), + "expectedEpoch", unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + byte[] resultBytes = canonical(JSON.valueToTree(result)); + var readback = + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + resultBytes); + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec.toResponse( + request, Optional.of(readback))); + return resultBytes; + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put( + "version_identity_operation_id", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private static byte[] receiptBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, byte[] appliedBytes) + throws Exception { + var applied = JSON.readTree(appliedBytes); + return Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + } + + private static tools.jackson.databind.node.ObjectNode receiptJson( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + UUID tenant = uuid("11111111-1111-4111-8111-111111111111"); + UUID version = uuid("22222222-2222-4222-8222-222222222222"); + UUID room = uuid("77777777-7777-4777-8777-777777777777"); + String accountDigest = sha256(request.originalAccountBinding()); + String digest = + startLocationReceiptDigest( + request.targetNamespace(), + account, + accountDigest, + draft.digest(), + tenant, + version, + room, + graphDigest); + var value = new java.util.LinkedHashMap(); + value.put("schema", "world-draft-start-location-receipt/v1"); + value.put("targetNamespace", request.targetNamespace()); + value.put("operationId", account.operationId().toString()); + value.put("requestId", account.requestId().toString()); + value.put("commitId", account.commitId().toString()); + value.put("authorizationFenceId", account.fenceId().toString()); + value.put("accountBindingDigest", accountDigest); + value.put("bindingDigest", draft.digest()); + value.put( + "startLocation", + Map.of( + "tenantId", + tenant.toString(), + "versionId", + version.toString(), + "roomTemplateId", + room.toString())); + value.put("graphDigest", graphDigest); + value.put("receiptDigest", digest); + return (tools.jackson.databind.node.ObjectNode) JSON.valueToTree(value); + } + + private static String startLocationReceiptDigest( + String targetNamespace, + DraftAuthorizationFenceBinding account, + String accountBindingDigest, + String bindingDigest, + UUID tenantId, + UUID versionId, + UUID roomTemplateId, + String graphDigest) + throws Exception { + var framed = new ByteArrayOutputStream(); + for (String value : + List.of( + "world-draft-start-location-receipt/v1", + targetNamespace, + account.operationId().toString(), + account.requestId().toString(), + account.commitId().toString(), + account.fenceId().toString(), + accountBindingDigest, + bindingDigest, + tenantId.toString(), + versionId.toString(), + roomTemplateId.toString(), + graphDigest)) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + return sha256(framed.toByteArray()); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private static final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + WorldCanonicalInitialPlayerLocation.Request request, + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence, + byte[] originalLifecycleBytes, + UUID readRequestId) {} + + private static final class Collector implements StreamObserver { + private T value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(T response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + assertThat(completed).isFalse(); + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java new file mode 100644 index 0000000000..9a8c7b41a7 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java @@ -0,0 +1,1351 @@ +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.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCompleteLaunchBindingServiceTest { + private static final String NAMESPACE = "firemud"; + 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 INTAKE_REQUEST = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID INTAKE_OPERATION = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID BINDING_OPERATION = + UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final UUID VERSION = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID OTHER_CANONICAL_VERSION = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID CURRENT_READ_ID = + UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final UUID ADVANCED_READ_ID = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID OTHER_READ_ID = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID OTHER_SOURCE_OPERATION = + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID OTHER_REGISTRATION_REQUEST = + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final String WORLD = "violet-wilds"; + private static final String CONTROL_PLANE_REQUEST = "world-launch-request-41"; + + private final AuthoredWorldLaunchDescriptorClient client = + mock(AuthoredWorldLaunchDescriptorClient.class); + private final AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + private final CanonicalGameInstanceLaunchAssociationClient gameSessionClient = + mock(CanonicalGameInstanceLaunchAssociationClient.class); + private final WorldCompleteLaunchBindingRepository repository = + mock(WorldCompleteLaunchBindingRepository.class); + private final WorldAuthoredSourceIntakeRepository sourceRepository = + mock(WorldAuthoredSourceIntakeRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final WorldCompleteLaunchBindingService service = + new WorldCompleteLaunchBindingService( + client, repository, sourceRepository, transactionManager, NAMESPACE, versionStateClient); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void committedLaunchRequiresSameNamespaceGameSessionWithoutEndUserContextBeforeAccess() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + WorldCompleteLaunchBindingService committedService = committedLaunchService(); + + assertThatThrownBy( + () -> withoutPeer(() -> committedService.bindCommittedLaunch(fixture.request()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> committedService.bindCommittedLaunch(fixture.request()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-session-service"), + () -> committedService.bindCommittedLaunch(fixture.request()))) + .isInstanceOf(SecurityException.class); + + SessionContext.setContext( + "99999999-9999-4999-8999-999999999999", List.of(), java.util.Map.of()); + assertThatThrownBy( + () -> withGameSession(() -> committedService.bindCommittedLaunch(fixture.request()))) + .isInstanceOf(SecurityException.class); + + var wrongNamespaceRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + fixture.request().readRequestId(), + "other", + fixture.request().canonicalTenantId(), + fixture.request().worldSlug(), + fixture.request().gameInstanceUuid(), + fixture.request().controlPlaneRequestId(), + fixture.request().launchDescriptorId(), + fixture.request().expectedDescriptorRequestDigest(), + fixture.request().expectedDescriptorResultDigest(), + fixture.request().expectedReleaseAttestationEvidenceDigest()); + SessionContext.clear(); + assertThatThrownBy( + () -> + withGameSession(() -> committedService.bindCommittedLaunch(wrongNamespaceRequest))) + .isInstanceOf(SecurityException.class); + verifyNoInteractions(client, gameSessionClient, repository, sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchFailsClosedWhenGameSessionClientWasNotConfigured() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + + assertThatThrownBy(() -> withGameSession(() -> service.bindCommittedLaunch(fixture.request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no configured Game Session owner reader"); + verifyNoInteractions(client, gameSessionClient, repository, sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRefusesAmbientTransactionBeforeRemoteOrOwnerAccess() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside ambient transactions"); + verifyNoInteractions(client, gameSessionClient, repository, sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRejectsChangedDigestAndV1ReleaseBeforeWorldOwnerWrite() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence v1Binding = evidence(source); + var wrongDigestRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + NAMESPACE, + TENANT, + WORLD, + UUID.fromString("abababab-abab-4bab-8bab-abababababab"), + CONTROL_PLANE_REQUEST, + v1Binding.descriptor().launchDescriptorId(), + v1Binding.descriptor().requestDigest(), + digest('a'), + v1Binding.releaseAttestation().evidenceDigest()); + WorldCompleteLaunchBindingService committedService = committedLaunchService(); + when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(v1Binding); + + assertThatThrownBy( + () -> withGameSession(() -> committedService.bindCommittedLaunch(wrongDigestRequest))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + + var v1Request = committedAssociationRequest(v1Binding); + assertThatThrownBy(() -> withGameSession(() -> committedService.bindCommittedLaunch(v1Request))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("release attestation v2"); + verify(gameSessionClient, never()).read(any()); + verifyNoInteractions(repository, sourceRepository); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRejectsGameSessionPairThatDiffersFromGameDesignBeforeSourceOrWrite() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + CompleteLaunchBindingEvidence otherPair = + committedPair(fixture.evidence().descriptor(), digest('8')); + CanonicalGameInstanceLaunchAssociationReadEvidence.Result mismatchedAssociation = + mock(CanonicalGameInstanceLaunchAssociationReadEvidence.Result.class); + when(mismatchedAssociation.request()).thenReturn(fixture.request()); + when(mismatchedAssociation.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(mismatchedAssociation.publicProduction()).thenReturn(true); + when(mismatchedAssociation.launchBindingEvidence()).thenReturn(otherPair); + when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(fixture.evidence()); + when(gameSessionClient.read(fixture.request())).thenReturn(mismatchedAssociation); + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf( + WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class); + verify(sourceRepository, never()).readBySource(any(), any(), any(), any(), any()); + verifyNoInteractions(repository); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void exactCommittedLaunchRetryUsesTheOriginalPairWithoutAnotherOwnerWrite() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + WorldCompleteLaunchBindingService committedService = committedLaunchService(); + stubCommittedLaunchReads(fixture); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(fixture.stored())); + when(repository.toReceipt(fixture.stored(), fixture.sourceReceipt())) + .thenReturn(fixture.receipt()); + + WorldCompleteLaunchBindingReceipt result = + withGameSession(() -> committedService.bindCommittedLaunch(fixture.request())); + + assertThat(result).isSameAs(fixture.receipt()); + verify(client).getComplete(any(GetLaunchDescriptorRequest.class)); + verify(gameSessionClient).read(fixture.request()); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRetryRejectsAChangedRetainedReleasePairWithoutReplacement() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + CompleteLaunchBindingEvidence changedPair = + committedPair( + fixture.evidence().descriptor(), + fixture.request().expectedReleaseAttestationEvidenceDigest()); + WorldCompleteLaunchBindingRepository.StoredBinding changedStored = + stored(fixture.sourceReceipt(), changedPair); + stubCommittedLaunchReads(fixture); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(changedStored)); + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + verify(repository, never()).acceptFresh(any(), any(), any()); + verify(repository, never()).toReceipt(any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRequiresExactSourceIntakeBeforeWorldBindingOwnerAccess() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + stubCommittedLaunchReads(fixture); + when(sourceRepository.readBySource( + NAMESPACE, + TENANT, + WORLD, + SOURCE_OPERATION, + fixture.sourceReceipt().sourceEvidenceDigest())) + .thenReturn(Optional.empty()); + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("no exact committed World source intake"); + verifyNoInteractions(repository); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedLaunchRetainsThenIndependentlyReadsBackTheExactPairInFreshOwnerTransaction() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + WorldCompleteLaunchBindingService committedService = committedLaunchService(); + stubCommittedLaunchReads(fixture); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(fixture.stored())); + when(repository.acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence())) + .thenReturn(fixture.receipt()); + when(repository.toReceipt(fixture.stored(), fixture.sourceReceipt())) + .thenReturn(fixture.receipt()); + + WorldCompleteLaunchBindingReceipt result = + withGameSession(() -> committedService.bindCommittedLaunch(fixture.request())); + + assertThat(result).isSameAs(fixture.receipt()); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + ArgumentCaptor descriptorRead = + ArgumentCaptor.forClass(GetLaunchDescriptorRequest.class); + verify(client).getComplete(descriptorRead.capture()); + assertThat(descriptorRead.getValue().getRequestId()) + .isNotEqualTo(fixture.request().readRequestId().toString()); + assertThat(descriptorRead.getValue().getCanonicalTenantId()).isEqualTo(TENANT.toString()); + assertThat(descriptorRead.getValue().getWorldSlug()).isEqualTo(WORLD); + assertThat(descriptorRead.getValue().getControlPlaneRequestId()) + .isEqualTo(CONTROL_PLANE_REQUEST); + assertThat(descriptorRead.getValue().getExpectedRequestDigest()) + .isEqualTo(fixture.request().expectedDescriptorRequestDigest()); + assertThat(descriptorRead.getValue().getExpectedResultDigest()) + .isEqualTo(fixture.request().expectedDescriptorResultDigest()); + InOrder committedReadOrder = inOrder(client, gameSessionClient, sourceRepository, repository); + committedReadOrder.verify(client).getComplete(any(GetLaunchDescriptorRequest.class)); + committedReadOrder.verify(gameSessionClient).read(fixture.request()); + committedReadOrder + .verify(sourceRepository) + .readBySource( + NAMESPACE, + TENANT, + WORLD, + SOURCE_OPERATION, + fixture.sourceReceipt().sourceEvidenceDigest()); + committedReadOrder.verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + committedReadOrder + .verify(repository) + .acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence()); + committedReadOrder.verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + committedReadOrder + .verify(sourceRepository) + .readBySource( + NAMESPACE, + TENANT, + WORLD, + SOURCE_OPERATION, + fixture.sourceReceipt().sourceEvidenceDigest()); + committedReadOrder.verify(repository).toReceipt(fixture.stored(), fixture.sourceReceipt()); + verify(gameSessionClient).read(fixture.request()); + verify(repository).acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence()); + verify(repository).toReceipt(fixture.stored(), fixture.sourceReceipt()); + } + + @Test + void committedLaunchRecoversLostCommitAcknowledgmentOnlyForTheSamePair() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + stubCommittedLaunchReads(fixture); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(fixture.stored())); + when(repository.acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence())) + .thenReturn(fixture.receipt()); + when(repository.toReceipt(fixture.stored(), fixture.sourceReceipt())) + .thenReturn(fixture.receipt()); + transactionManager.loseCommitAcknowledgment = true; + + WorldCompleteLaunchBindingReceipt recovered = + withGameSession(() -> committedLaunchService().bindCommittedLaunch(fixture.request())); + + assertThat(recovered).isSameAs(fixture.receipt()); + verify(repository).acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence()); + verify(repository).toReceipt(fixture.stored(), fixture.sourceReceipt()); + assertThat(transactionManager.commitFailureThrown).isTrue(); + } + + @Test + void committedLaunchRejectsChangedPairDuringLostCommitAcknowledgmentRecovery() { + CommittedLaunchFixture fixture = committedLaunchFixture(); + CompleteLaunchBindingEvidence changedPair = + committedPair( + fixture.evidence().descriptor(), + fixture.request().expectedReleaseAttestationEvidenceDigest()); + WorldCompleteLaunchBindingRepository.StoredBinding changedStored = + stored(fixture.sourceReceipt(), changedPair); + stubCommittedLaunchReads(fixture); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(changedStored)); + when(repository.acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence())) + .thenReturn(fixture.receipt()); + transactionManager.loseCommitAcknowledgment = true; + + assertThatThrownBy( + () -> + withGameSession( + () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + verify(repository).acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence()); + verify(repository, never()).toReceipt(any(), any()); + assertThat(transactionManager.commitFailureThrown).isTrue(); + } + + @Test + void requiresExactSameNamespaceGameSessionPeerBeforeOwnerOrGameDesignAccess() { + GetRequest request = request(evidence(source())); + + assertThatThrownBy(() -> withoutPeer(() -> service.bind(request))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> withPeer(peer(NAMESPACE, "game-design-service"), () -> service.bind(request))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> withPeer(peer("other", "game-session-service"), () -> service.bind(request))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> withoutPeer(() -> service.readCurrentVersionState(request, CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> service.readCurrentVersionState(request, CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-session-service"), + () -> service.readCurrentVersionState(request, CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + AuthoredWorldLaunchDescriptorEvidence.Request original = request.expectedRequest(); + AuthoredWorldLaunchDescriptorEvidence.Request wrongNamespace = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "other", + original.controlPlaneRequestId(), + original.canonicalTenantId(), + original.worldSlug(), + original.authoredWorldSourceOperationId(), + original.authoredWorldSourceEvidenceDigest(), + original.gameTemplateId(), + original.requestedScriptPatchVersionPresent(), + original.requestedScriptPatchVersion(), + original.sourceVersionIdPresent(), + original.sourceVersionId(), + original.targetVersionIdPresent(), + original.targetVersionId(), + original.requestedRuntimeFlagsJsonPresent(), + original.requestedRuntimeFlagsJson()); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.bind( + new GetRequest(UUID.randomUUID(), wrongNamespace, digest('a'))))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + new GetRequest(UUID.randomUUID(), wrongNamespace, digest('a')), + CURRENT_READ_ID))) + .isInstanceOf(SecurityException.class); + verifyNoInteractions(client, versionStateClient, repository, sourceRepository); + } + + @Test + void retainsCompletePairThenIndependentlyReadsBackTheSameOwnerReceipt() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + GetRequest request = request(evidence); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(stored)); + when(client.getComplete(any())).thenReturn(evidence); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.acceptFresh(NAMESPACE, sourceReceipt, evidence)).thenReturn(receipt); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + + WorldCompleteLaunchBindingReceipt result = withGameSession(() -> service.bind(request)); + + assertThat(result).isEqualTo(receipt); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + verify(client).getComplete(any()); + verify(repository).acceptFresh(NAMESPACE, sourceReceipt, evidence); + verify(repository).toReceipt(stored, sourceReceipt); + } + + @Test + void exactRetryReadsTheStoredPairBeforeLocalSourceAndDoesNotCallGameDesign() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + GetRequest request = request(evidence); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.of(stored)); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + + WorldCompleteLaunchBindingReceipt result = withGameSession(() -> service.bind(request)); + + assertThat(result).isEqualTo(receipt); + verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + verify(client, never()).getComplete(any()); + verify(repository, never()).acceptFresh(any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedExpectedResultConflictsBeforeSourceLookupOrGameDesign() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.of(stored)); + GetRequest changed = + new GetRequest(UUID.randomUUID(), evidence.descriptor().request(), digest('b')); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(changed))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + verifyNoInteractions(client, sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void missingOrSwappedCompletePairCannotReachWorldPersistence() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence expectedEvidence = evidence(source); + CompleteLaunchBindingEvidence otherEvidence = + evidence(source, "another-world-launch-request", 42L); + assertThatThrownBy( + () -> + new CompleteLaunchBindingEvidence( + expectedEvidence.descriptor(), otherEvidence.releaseAttestation())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new CompleteLaunchBindingEvidence(null, null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> new CompleteLaunchBindingEvidence(expectedEvidence.descriptor(), null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> new CompleteLaunchBindingEvidence(null, expectedEvidence.releaseAttestation())) + .isInstanceOf(NullPointerException.class); + + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.empty()); + when(client.getComplete(any())).thenReturn(null); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(request(expectedEvidence)))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("no complete launch binding"); + verify(repository, never()).acceptFresh(any(), any(), any()); + verifyNoInteractions(sourceRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void refusesAmbientTransactionBeforeReadingOrCallingGameDesign() { + CompleteLaunchBindingEvidence evidence = evidence(source()); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> withGameSession(() -> service.bind(request(evidence)))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(evidence), CURRENT_READ_ID))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(client, versionStateClient, repository, sourceRepository); + } + + @Test + void recoversACommitAcknowledgmentLossByReadingTheSameOwnerOperation() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + CompleteLaunchBindingEvidence evidence = evidence(source); + GetRequest request = request(evidence); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + AtomicReference committed = + new AtomicReference<>(); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) + .thenAnswer( + invocation -> { + WorldCompleteLaunchBindingRepository.StoredBinding value = committed.get(); + return value == null ? Optional.empty() : Optional.of(value); + }); + when(client.getComplete(any())).thenReturn(evidence); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.acceptFresh(NAMESPACE, sourceReceipt, evidence)) + .thenAnswer( + invocation -> { + committed.set(stored); + return receipt; + }); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + transactionManager.loseCommitAcknowledgment = true; + + WorldCompleteLaunchBindingReceipt recovered = withGameSession(() -> service.bind(request)); + + assertThat(recovered.operationId()).isEqualTo(receipt.operationId()); + assertThat(recovered.evidence()).isEqualTo(evidence); + verify(client).getComplete(any()); + verify(repository).acceptFresh(NAMESPACE, sourceReceipt, evidence); + assertThat(transactionManager.commitFailureThrown).isTrue(); + } + + @Test + void readsPublishedCurrentVersionFromTheCommittedPairAndDescriptorVersionId() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + WorldCompleteLaunchBindingReceipt original = stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence current = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(current); + + AuthoredWorldVersionStateEvidence result = + withGameSession(() -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID)); + + assertThat(result).isEqualTo(current); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(AuthoredWorldVersionStateEvidence.Request.class); + InOrder readOrder = inOrder(repository, sourceRepository, versionStateClient); + readOrder.verify(repository).read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST); + readOrder + .verify(sourceRepository) + .readBySource(NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()); + readOrder.verify(repository).toReceipt(any(), any()); + readOrder.verify(versionStateClient).read(requestCaptor.capture()); + AuthoredWorldVersionStateEvidence.Request currentRequest = requestCaptor.getValue(); + assertThat(currentRequest.targetNamespace()).isEqualTo(original.targetNamespace()); + assertThat(currentRequest.canonicalTenantId()).isEqualTo(original.canonicalTenantId()); + assertThat(currentRequest.worldSlug()).isEqualTo(original.worldSlug()); + assertThat(currentRequest.sourceOperationId()).isEqualTo(SOURCE_OPERATION); + assertThat(currentRequest.expectedSourceEvidenceDigest()).isEqualTo(source.evidenceDigest()); + assertThat(currentRequest.versionId()).isEqualTo(binding.descriptor().versionId()); + assertThat(currentRequest.versionId()) + .isNotEqualTo(original.sourceIntakeReceipt().localTenantKey()); + assertThat(currentRequest.readRequestId()).isEqualTo(CURRENT_READ_ID); + assertThat(original.evidence()).isEqualTo(binding); + assertThat(original.operationId()).isEqualTo(BINDING_OPERATION); + assertThat(transactionManager.startedWith).isNull(); + verify(client, never()).getComplete(any()); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void acceptsActiveCurrentVersionAtTheDescriptorEpoch() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence current = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(current); + + AuthoredWorldVersionStateEvidence result = + withGameSession(() -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID)); + + assertThat(result).isEqualTo(current); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void repeatedCurrentReadsObserveVersionAdvanceAndRejectTheStaleDescriptorPair() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + WorldCompleteLaunchBindingReceipt original = stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence first = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence advanced = + currentVersionState( + source, + ADVANCED_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + binding.descriptor().versionStateEpoch() + 1); + when(versionStateClient.read(any())).thenReturn(first, advanced); + + AuthoredWorldVersionStateEvidence firstRead = + withGameSession(() -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID)); + assertThat(firstRead).isEqualTo(first); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), ADVANCED_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("epoch differs"); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(AuthoredWorldVersionStateEvidence.Request.class); + verify(versionStateClient, times(2)).read(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()) + .extracting(AuthoredWorldVersionStateEvidence.Request::readRequestId) + .containsExactly(CURRENT_READ_ID, ADVANCED_READ_ID); + assertThat(original.evidence()).isEqualTo(binding); + assertThat(original.operationId()).isEqualTo(BINDING_OPERATION); + verify(client, never()).getComplete(any()); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsCurrentEvidenceForAnotherAuthoredSource() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + AuthoredWorldSourceEvidence otherSource = + source("other-world", OTHER_REGISTRATION_REQUEST, OTHER_SOURCE_OPERATION); + AuthoredWorldVersionStateEvidence swappedSource = + currentVersionState( + otherSource, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(swappedSource); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsAChangedVersionSelectorInCurrentOwnerEvidence() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence swappedSelector = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId() + 1, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(swappedSelector); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("exact committed World source"); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsCurrentEvidenceWithCanonicalVersionUuidDifferentFromReleaseAttestation() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + UUID committedCanonicalVersionId = binding.releaseAttestation().canonicalVersionId(); + AuthoredWorldVersionStateEvidence expected = + currentVersionState( + source, + committedCanonicalVersionId, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + AuthoredWorldVersionStateEvidence substituted = + currentVersionState( + source, + OTHER_CANONICAL_VERSION, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + binding.descriptor().versionStateEpoch()); + assertThat(substituted.request()).isEqualTo(expected.request()); + assertThat(substituted.sourceEvidence()).isEqualTo(expected.sourceEvidence()); + assertThat(substituted.versionState()).isEqualTo(expected.versionState()); + assertThat(substituted.versionStateEpoch()).isEqualTo(expected.versionStateEpoch()); + assertThat(substituted.canonicalVersionId()).isNotEqualTo(committedCanonicalVersionId); + when(versionStateClient.read(any())).thenReturn(substituted); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("canonical version UUID differs"); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void changedBindingRequestIsRejectedBeforeReadingCurrentOwnerEvidence() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + GetRequest substituted = + new GetRequest(UUID.randomUUID(), binding.descriptor().request(), digest('b')); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(substituted, CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); + verifyNoInteractions(versionStateClient); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void requiresAnAlreadyCommittedPairWithoutRegisteringOne() { + CompleteLaunchBindingEvidence binding = evidence(source()); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.empty()); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("requires a committed launch binding"); + verifyNoInteractions(client, versionStateClient, sourceRepository); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void deniesDraftRetiredAndUnavailableCurrentVersionEvidenceWithoutChangingThePair() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + WorldCompleteLaunchBindingReceipt original = stubCommittedBinding(source, binding); + AuthoredWorldVersionStateEvidence draft = + currentVersionState( + source, + CURRENT_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(draft); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("not PUBLISHED or ACTIVE"); + + AuthoredWorldVersionStateEvidence retired = + currentVersionState( + source, + OTHER_READ_ID, + binding.descriptor().versionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_RETIRED, + binding.descriptor().versionStateEpoch()); + when(versionStateClient.read(any())).thenReturn(retired); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), OTHER_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("not PUBLISHED or ACTIVE"); + + when(versionStateClient.read(any())) + .thenThrow(new IllegalStateException("Game Design is unavailable")); + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), ADVANCED_READ_ID))) + .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) + .hasMessageContaining("unavailable or invalid"); + assertThat(original.evidence()).isEqualTo(binding); + verify(repository, never()).acceptFresh(any(), any(), any()); + } + + @Test + void rejectsReadCorrelationIdsReusedFromSourceOrRegistration() { + AuthoredWorldSourceEvidence source = source(); + CompleteLaunchBindingEvidence binding = evidence(source); + stubCommittedBinding(source, binding); + + assertThatThrownBy( + () -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), SOURCE_OPERATION))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("separate from source and registration IDs"); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + request(binding), source.registrationRequestId()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("separate from source and registration IDs"); + assertThatThrownBy( + () -> + withGameSession( + () -> + service.readCurrentVersionState( + request(binding), request(binding).requestId()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("separate from source and registration IDs"); + verifyNoInteractions(versionStateClient); + } + + private WorldCompleteLaunchBindingService committedLaunchService() { + return new WorldCompleteLaunchBindingService( + client, + repository, + sourceRepository, + transactionManager, + NAMESPACE, + versionStateClient, + gameSessionClient); + } + + private void stubCommittedLaunchReads(CommittedLaunchFixture fixture) { + when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(fixture.evidence()); + when(gameSessionClient.read(fixture.request())).thenReturn(fixture.associationResult()); + when(sourceRepository.readBySource( + NAMESPACE, + TENANT, + WORLD, + SOURCE_OPERATION, + fixture.sourceReceipt().sourceEvidenceDigest())) + .thenReturn(Optional.of(fixture.sourceReceipt())); + } + + private static CommittedLaunchFixture committedLaunchFixture() { + AuthoredWorldSourceEvidence source = source(); + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + AuthoredWorldLaunchDescriptorEvidence descriptor = evidence(source).descriptor(); + CompleteLaunchBindingEvidence pair = committedPair(descriptor, digest('7')); + var request = committedAssociationRequest(pair); + var associationResult = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + request, + UUID.fromString("abababab-abab-4bab-8bab-abababababab"), + RealmEntryPolicy.StateScope.SHARED, + true, + CurrentGameInstanceStatus.RUNNING, + 7L, + pair); + WorldCompleteLaunchBindingReceipt receipt = mock(WorldCompleteLaunchBindingReceipt.class); + when(receipt.targetNamespace()).thenReturn(NAMESPACE); + when(receipt.canonicalTenantId()).thenReturn(TENANT); + when(receipt.worldSlug()).thenReturn(WORLD); + when(receipt.controlPlaneRequestId()).thenReturn(CONTROL_PLANE_REQUEST); + when(receipt.sourceIntakeReceipt()).thenReturn(sourceReceipt); + when(receipt.evidence()).thenReturn(pair); + when(receipt.descriptor()).thenReturn(descriptor); + + WorldCompleteLaunchBindingRepository.StoredBinding stored = + new WorldCompleteLaunchBindingRepository.StoredBinding( + BINDING_OPERATION, + NAMESPACE, + TENANT, + WORLD, + CONTROL_PLANE_REQUEST, + sourceReceipt.operationId(), + sourceReceipt.intakeRequestId(), + sourceReceipt.localTenantKey(), + sourceReceipt.sourceOperationId(), + sourceReceipt.sourceEvidenceDigest(), + sourceReceipt.receiptDigest(), + descriptor.requestDigest(), + descriptor.resultDigest(), + pair.releaseAttestation().evidenceDigest(), + pair); + return new CommittedLaunchFixture( + source, sourceReceipt, pair, request, associationResult, stored, receipt); + } + + private static WorldCompleteLaunchBindingRepository.StoredBinding stored( + WorldAuthoredSourceIntakeReceipt sourceReceipt, CompleteLaunchBindingEvidence pair) { + AuthoredWorldLaunchDescriptorEvidence descriptor = pair.descriptor(); + return new WorldCompleteLaunchBindingRepository.StoredBinding( + BINDING_OPERATION, + NAMESPACE, + TENANT, + WORLD, + CONTROL_PLANE_REQUEST, + sourceReceipt.operationId(), + sourceReceipt.intakeRequestId(), + sourceReceipt.localTenantKey(), + sourceReceipt.sourceOperationId(), + sourceReceipt.sourceEvidenceDigest(), + sourceReceipt.receiptDigest(), + descriptor.requestDigest(), + descriptor.resultDigest(), + pair.releaseAttestation().evidenceDigest(), + pair); + } + + // The closed pair is mocked in these component tests; this is not authenticated owner-storage + // proof. + private static CompleteLaunchBindingEvidence committedPair( + AuthoredWorldLaunchDescriptorEvidence descriptor, String releaseEvidenceDigest) { + AuthoredWorldReleaseAttestationEvidence release = + mock(AuthoredWorldReleaseAttestationEvidence.class); + WorldPublishedStartLocationEvidence selector = mock(WorldPublishedStartLocationEvidence.class); + WorldPublishedStartLocationEvidence.Request selectorRequest = + mock(WorldPublishedStartLocationEvidence.Request.class); + when(selector.request()).thenReturn(selectorRequest); + when(selectorRequest.intakeRequestId()).thenReturn(INTAKE_REQUEST); + when(release.schemaVersion()) + .thenReturn(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + when(release.evidenceDigest()).thenReturn(releaseEvidenceDigest); + when(release.worldStartLocationEvidence()).thenReturn(selector); + CompleteLaunchBindingEvidence pair = mock(CompleteLaunchBindingEvidence.class); + when(pair.descriptor()).thenReturn(descriptor); + when(pair.releaseAttestation()).thenReturn(release); + return pair; + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request + committedAssociationRequest(CompleteLaunchBindingEvidence evidence) { + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + NAMESPACE, + evidence.descriptor().canonicalTenantId(), + evidence.descriptor().worldSlug(), + UUID.fromString("abababab-abab-4bab-8bab-abababababab"), + evidence.descriptor().controlPlaneRequestId(), + evidence.descriptor().launchDescriptorId(), + evidence.descriptor().requestDigest(), + evidence.descriptor().resultDigest(), + evidence.releaseAttestation().evidenceDigest()); + } + + private record CommittedLaunchFixture( + AuthoredWorldSourceEvidence source, + WorldAuthoredSourceIntakeReceipt sourceReceipt, + CompleteLaunchBindingEvidence evidence, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request, + CanonicalGameInstanceLaunchAssociationReadEvidence.Result associationResult, + WorldCompleteLaunchBindingRepository.StoredBinding stored, + WorldCompleteLaunchBindingReceipt receipt) {} + + private WorldCompleteLaunchBindingReceipt stubCommittedBinding( + AuthoredWorldSourceEvidence source, CompleteLaunchBindingEvidence evidence) { + WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(source); + WorldCompleteLaunchBindingReceipt receipt = bindingReceipt(sourceReceipt, evidence); + WorldCompleteLaunchBindingRepository.StoredBinding stored = stored(receipt); + when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.of(stored)); + when(sourceRepository.readBySource( + NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) + .thenReturn(Optional.of(sourceReceipt)); + when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); + return receipt; + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID readId, + long versionId, + VersionLifecycleState state, + long epoch) { + return currentVersionState(source, VERSION, readId, versionId, state, epoch); + } + + private static AuthoredWorldVersionStateEvidence currentVersionState( + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + UUID readId, + long versionId, + VersionLifecycleState state, + long epoch) { + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + source.targetNamespace(), + readId, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + versionId); + return AuthoredWorldVersionStateEvidence.create( + request, source, canonicalVersionId, state, epoch); + } + + private static WorldCompleteLaunchBindingRepository.StoredBinding stored( + WorldCompleteLaunchBindingReceipt receipt) { + AuthoredWorldLaunchDescriptorEvidence descriptor = receipt.descriptor(); + return new WorldCompleteLaunchBindingRepository.StoredBinding( + receipt.operationId(), + receipt.targetNamespace(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.controlPlaneRequestId(), + receipt.sourceIntakeReceipt().operationId(), + receipt.sourceIntakeReceipt().intakeRequestId(), + receipt.sourceIntakeReceipt().localTenantKey(), + receipt.sourceIntakeReceipt().sourceOperationId(), + receipt.sourceIntakeReceipt().sourceEvidenceDigest(), + receipt.sourceIntakeReceipt().receiptDigest(), + descriptor.requestDigest(), + descriptor.resultDigest(), + receipt.evidence().releaseAttestation().evidenceDigest(), + receipt.evidence()); + } + + private static WorldCompleteLaunchBindingReceipt bindingReceipt( + WorldAuthoredSourceIntakeReceipt sourceReceipt, CompleteLaunchBindingEvidence evidence) { + return new WorldCompleteLaunchBindingReceipt( + 1, + BINDING_OPERATION, + NAMESPACE, + TENANT, + WORLD, + CONTROL_PLANE_REQUEST, + sourceReceipt, + evidence); + } + + private static GetRequest request(CompleteLaunchBindingEvidence evidence) { + return new GetRequest( + UUID.fromString("66666666-6666-4666-8666-666666666666"), + evidence.descriptor().request(), + evidence.descriptor().resultDigest()); + } + + private static CompleteLaunchBindingEvidence evidence(AuthoredWorldSourceEvidence source) { + return evidence(source, CONTROL_PLANE_REQUEST, 41L); + } + + private static CompleteLaunchBindingEvidence evidence( + AuthoredWorldSourceEvidence source, String controlPlaneRequestId, long gameTemplateId) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "launch-descriptor-" + gameTemplateId, + 42L, + false, + null, + "{}", + "generation-config-41", + 7L, + 51L, + "release-bundle-51", + false, + null); + String commitId = "commit-41"; + List participants = + List.of( + participant("WORLD_MANAGEMENT", 3, "a", false), + participant("ENTITY_MANAGEMENT", 2, "b", false), + participant("GAME_LOGIC", 1, "c", true), + participant("AUTOMATION_SCRIPTING", 5, "d", false), + participant("GAME_DESIGN_CONTROL_PLANE", 1, "e", false)); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT, + VERSION, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:owner:launch-41", + commitId, + participants, + digest('f'), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } + + private static AuthoredWorldReleaseAttestationEvidence.Participant participant( + String owner, int schema, String contentHex, boolean hasAbilityDigest) { + return new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "42", + false, + null, + "commit-41", + contentHex.repeat(64), + schema, + hasAbilityDigest, + hasAbilityDigest ? digest('c') : null); + } + + private static WorldAuthoredSourceIntakeReceipt sourceReceipt( + AuthoredWorldSourceEvidence source) { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + return new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + INTAKE_OPERATION, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, INTAKE_OPERATION, requestDigest, source, 90_041L), + 90_041L, + source); + } + + private static AuthoredWorldSourceEvidence source() { + return source(WORLD, UUID.fromString("11111111-1111-4111-8111-111111111111"), SOURCE_OPERATION); + } + + private static AuthoredWorldSourceEvidence source( + String worldSlug, UUID registrationRequest, UUID sourceOperation) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequest, TENANT, "north-star", worldSlug, "Café 🐉"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequest, + sourceOperation, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequest, + sourceOperation, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Café 🐉", + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + + 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 withGameSession(Supplier action) { + return withPeer(peer(NAMESPACE, "game-session-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; + private boolean loseCommitAcknowledgment; + private boolean commitFailureThrown; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + if (loseCommitAcknowledgment) { + loseCommitAcknowledgment = false; + commitFailureThrown = true; + throw new IllegalStateException("simulated lost commit acknowledgment"); + } + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java new file mode 100644 index 0000000000..57874f0549 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java @@ -0,0 +1,232 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.junit.jupiter.api.Test; + +class WorldDesignPublicationFenceEvidenceTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID INTAKE_OPERATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID VERSION_IDENTITY_OPERATION_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String INTAKE_REQUEST_DIGEST = "sha256:" + "1".repeat(64); + private static final String SOURCE_EVIDENCE_DIGEST = "sha256:" + "a".repeat(64); + private static final String INTAKE_RECEIPT_DIGEST = "sha256:" + "2".repeat(64); + private static final String FULL_REQUEST_DIGEST = "f".repeat(64); + private static final String CONTENT_DIGEST = "b".repeat(64); + private static final long GAME_DESIGN_VERSION_ID = 9_000_000_042L; + + @Test + void bindsFullVersionToTheCanonicalPublicationDigestRequestGrammar() { + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full( + TENANT_ID.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7"); + WorldDesignPublicationFenceEvidence evidence = + evidence("request-7", FULL_REQUEST_DIGEST, binding.derivedWorkflowIdentity()); + + assertThat(evidence.publicationBinding()).usingRecursiveComparison().isEqualTo(binding); + assertThat(evidence.publicationBinding().scopeKindValue()).isEqualTo("FULL_VERSION"); + assertThat(evidence.publicationBinding().versionId()) + .isEqualTo(Long.toString(GAME_DESIGN_VERSION_ID)); + assertThat(evidence.publicationBinding().baseVersionId()).isEmpty(); + assertThat(evidence.publicationBinding().scriptPatchVersion()).isEmpty(); + assertThat(evidence.requestDigest()).isEqualTo(FULL_REQUEST_DIGEST); + assertThat(evidence.requestDigest()).isNotEqualTo(binding.requestDigest()); + assertThat(evidence.publishWorkflowId()) + .isEqualTo("publish:" + TENANT_ID + ":publish-request:request-7"); + assertThat(evidence.gameDesignVersionId()).isEqualTo(GAME_DESIGN_VERSION_ID); + assertThat(evidence.canonicalVersionId()).isEqualTo(CANONICAL_VERSION_ID); + assertThat(evidence.versionIdentityOperationId()).isEqualTo(VERSION_IDENTITY_OPERATION_ID); + assertThat(evidence.ownerBinding().intakeRequestDigest()).isEqualTo(INTAKE_REQUEST_DIGEST); + } + + @Test + void rejectsChangedOrOmittedRequestAndWorkflowBindings() { + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full( + TENANT_ID.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7"); + + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", binding.requestDigest(), "publish:wrong")); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", null, binding.derivedWorkflowIdentity())); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", "F".repeat(64), binding.derivedWorkflowIdentity())); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", binding.requestDigest(), null)); + } + + @Test + void rejectsMalformedScopeAndAuthoredSourceIdentifiers() { + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", validDigest(), validWorkflow(), 0, 1L)); + assertThatIllegalArgumentException() + .isThrownBy(() -> evidence("request-7", validDigest(), validWorkflow(), 42, 0L)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "FireMUD", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + 42, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + GAME_DESIGN_VERSION_ID, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST.substring("sha256:".length()), + "request-7", + validDigest(), + 9, + validWorkflow())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + new UUID(0L, 0L), + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + 42, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + 42, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + "a".repeat(64), + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + GAME_DESIGN_VERSION_ID, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST.substring("sha256:".length()), + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); + } + + @Test + void checkpointRequiresACompleteCanonicalDigestTuple() { + var checkpoint = + new WorldDesignPublicationFenceEvidence.Checkpoint("version:42", CONTENT_DIGEST, 2); + + assertThat(checkpoint.appliedCommitId()).isEqualTo("version:42"); + assertThat(checkpoint.contentDigest()).isEqualTo(CONTENT_DIGEST); + assertThat(checkpoint.digestSchemaVersion()).isPositive(); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new WorldDesignPublicationFenceEvidence.Checkpoint("", CONTENT_DIGEST, 2)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> new WorldDesignPublicationFenceEvidence.Checkpoint(" \t", CONTENT_DIGEST, 2)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "version:42", "B".repeat(64), 2)); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "version:42", CONTENT_DIGEST, 0)); + } + + private static WorldDesignPublicationFenceEvidence evidence( + String requestId, String digest, String workflowId) { + return evidence(requestId, digest, workflowId, GAME_DESIGN_VERSION_ID, 9L); + } + + private static WorldDesignPublicationFenceEvidence evidence( + String requestId, String digest, String workflowId, long versionId, long epoch) { + return new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + versionId, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + requestId, + digest, + epoch, + workflowId); + } + + private static String validDigest() { + return FULL_REQUEST_DIGEST; + } + + private static String validWorkflow() { + return PublicationDigestRequestBinding.full( + TENANT_ID.toString(), Long.toString(GAME_DESIGN_VERSION_ID), "request-7") + .derivedWorkflowIdentity(); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationServiceTest.java new file mode 100644 index 0000000000..cd8bb0bf94 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationServiceTest.java @@ -0,0 +1,110 @@ +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.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldDraftGraphApplicationServiceTest { + private final WorldDraftGraphApplicationRepository repository = + mock(WorldDraftGraphApplicationRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final WorldDraftGraphApplication application = mock(WorldDraftGraphApplication.class); + private final WorldDraftTerminalOperation operation = mock(WorldDraftTerminalOperation.class); + private final WorldDraftGraphApplicationService.CommitOrderVerifier verifier = + mock(WorldDraftGraphApplicationService.CommitOrderVerifier.class); + + @AfterEach + void clearTransactionFixture() { + TransactionSynchronizationManager.clear(); + } + + @Test + void defaultDenialPerformsOnlyCommittedLookupAndStartsNoWriterTransaction() { + when(application.operation()).thenReturn(operation); + when(repository.readCommitted(application)).thenReturn(Optional.empty()); + var service = new WorldDraftGraphApplicationService(repository, manager); + assertThatThrownBy(() -> service.apply(application)) + .hasMessageContaining("COMMIT_ORDER producer is unavailable"); + verifyNoInteractions(manager); + } + + @Test + void callerTransactionDeniesBeforeAnyAuthorityOrStorageAccess() { + TransactionSynchronizationManager.setActualTransactionActive(true); + var service = new WorldDraftGraphApplicationService(repository, manager, verifier); + assertThatThrownBy(() -> service.apply(application)) + .hasMessageContaining("no active caller transaction"); + verifyNoInteractions(repository, manager, verifier); + } + + @Test + void immutableExactRetryRequiresNeitherFreshPermissionNorWriterTransaction() { + var result = mock(WorldDraftGraphAppliedResult.class); + when(repository.readCommitted(application)).thenReturn(Optional.of(result)); + assertThat( + new WorldDraftGraphApplicationService(repository, manager, verifier).apply(application)) + .isSameAs(result); + verifyNoInteractions(manager, verifier); + } + + @Test + void changedOriginalProofDeniesBeforeWriterTransaction() { + when(application.operation()).thenReturn(operation); + when(operation.canonicalBytes()).thenReturn(new byte[] {1}); + when(operation.accountBindingBytes()).thenReturn(new byte[] {2}); + var proof = new WorldDraftGraphApplicationService.CommitOrderProof(operation); + when(operation.accountBindingBytes()).thenReturn(new byte[] {3}); + when(repository.readCommitted(application)).thenReturn(Optional.empty()); + when(verifier.verifyHeldOriginalCommitOrder(operation)).thenReturn(proof); + assertThatThrownBy( + () -> + new WorldDraftGraphApplicationService(repository, manager, verifier) + .apply(application)) + .hasMessageContaining("proof differs from original complete operation"); + verifyNoInteractions(manager); + } + + @Test + void stipulatedAuthorityPrecedesDedicatedTransactionAndLateFailureRollsBack() { + // Component sequencing only: this fixture is not an authenticated Account producer. + when(application.operation()).thenReturn(operation); + when(operation.canonicalBytes()).thenReturn(new byte[] {1}); + when(operation.accountBindingBytes()).thenReturn(new byte[] {2}); + var proof = new WorldDraftGraphApplicationService.CommitOrderProof(operation); + when(repository.readCommitted(application)).thenReturn(Optional.empty()); + when(verifier.verifyHeldOriginalCommitOrder(operation)).thenReturn(proof); + var status = mock(TransactionStatus.class); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.apply(application, proof)).thenThrow(new IllegalStateException("late failure")); + assertThatThrownBy( + () -> + new WorldDraftGraphApplicationService(repository, manager, verifier) + .apply(application)) + .hasMessage("late failure"); + var order = inOrder(repository, verifier, manager); + order.verify(repository).readCommitted(application); + order.verify(verifier).verifyHeldOriginalCommitOrder(operation); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + order.verify(manager).getTransaction(definition.capture()); + order.verify(repository).apply(application, proof); + order.verify(manager).rollback(status); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().isReadOnly()).isFalse(); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidenceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidenceTest.java new file mode 100644 index 0000000000..03ee2b01db --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitEvidenceTest.java @@ -0,0 +1,42 @@ +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.Mockito.mock; + +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +class WorldDraftRegionCommitEvidenceTest { + @Test + void graphAndResultBytesAreDefensiveAndRemainExplicitlyUnverifiedPermission() { + byte[] graph = {1, 2}; + byte[] result = {3, 4}; + DraftCommitBinding binding = mock(DraftCommitBinding.class); + WorldDesignPublicationFenceEvidence.OwnerBinding owner = + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class); + WorldDraftRegionCommitEvidence evidence = + new WorldDraftRegionCommitEvidence(binding, owner, graph, result); + graph[0] = 9; + result[0] = 9; + evidence.graphBytes()[0] = 8; + evidence.resultBytes()[0] = 8; + assertThat(evidence.graphBytes()).containsExactly((byte) 1, (byte) 2); + assertThat(evidence.resultBytes()).containsExactly((byte) 3, (byte) 4); + assertThat(evidence.binding()).isSameAs(binding); + assertThat(evidence.ownerBinding()).isSameAs(owner); + assertThat(evidence.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + } + + @Test + void incompleteEvidenceCannotBeReturnedAsSuccessfulComponentStorage() { + assertThatThrownBy( + () -> + new WorldDraftRegionCommitEvidence( + mock(DraftCommitBinding.class), + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class), + new byte[0], + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlanTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlanTest.java new file mode 100644 index 0000000000..a68f3e5b90 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPlanTest.java @@ -0,0 +1,540 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan.RegionRevision; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldGenerationSubtreeDesignMutation; +import org.junit.jupiter.api.Test; + +class WorldDraftRegionCommitPlanTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final long GAME_DESIGN_VERSION_ID = 9_000_000_042L; + private static final String PREFIXED_DIGEST = "sha256:" + "a".repeat(64); + private static final String OTHER_OWNER_PAYLOAD = "not decoded by the World plan"; + + @Test + void acceptsOrderedMultiRegionSubsetAndPreservesMixedOwnerBinding() { + UUID firstRevision = uuid(5); + UUID secondRevision = uuid(6); + DraftCommitBinding binding = + binding( + List.of( + otherRevision("0"), + worldRevision("1", firstRevision, regionJson(firstRevision, COMMIT_ID, "7", 2, 4)), + worldRevision( + "2", secondRevision, regionJson(secondRevision, COMMIT_ID, "19", 8, 3))), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), + worldUnit("7", "REGION_SUBTREE", "7", 4), + worldUnit("19", "AGGREGATE", "19", 8), + worldUnit("19", "REGION_SUBTREE", "19", 3), + otherUnit())); + + WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding = ownerBinding(); + WorldDraftRegionCommitPlan plan = WorldDraftRegionCommitPlan.create(binding, ownerBinding); + + assertThat(plan.binding()).isSameAs(binding); + assertThat(plan.ownerBinding()).isSameAs(ownerBinding); + assertThat(plan.binding().requestId()).isEqualTo(REQUEST_ID); + assertThat(plan.binding().baseCommitId()).isEqualTo("base-commit-17"); + assertThat(plan.regionRevisions()) + .extracting(RegionRevision::revisionOrder) + .containsExactly("1", "2"); + assertThat(plan.regionRevisions()) + .extracting(revision -> revision.mutation().getAggregateId()) + .containsExactly("7", "19"); + assertThat(plan.regionRevisions().get(0).mutation().getExpectedDraftRevisionEpoch()) + .isEqualTo(2); + assertThat(plan.regionRevisions().get(0).mutation().getExpectedDraftScopeRevisionEpoch()) + .isEqualTo(4); + assertThat(plan.regionRevisions().get(1).mutation().getExpectedDraftRevisionEpoch()) + .isEqualTo(8); + assertThat(plan.regionRevisions().get(1).mutation().getExpectedDraftScopeRevisionEpoch()) + .isEqualTo(3); + } + + @Test + void rejectsMissingContainingScopeAndAdditionalOrMismatchedWorldTuples() { + UUID revisionId = uuid(5); + String payload = regionJson(revisionId, COMMIT_ID, "7", 2, 4); + List revisions = + List.of(worldRevision("0", revisionId, payload)); + + assertPlanRejected(binding(revisions, List.of(worldUnit("7", "AGGREGATE", "7", 2)))); + assertPlanRejected( + binding( + revisions, + List.of( + worldUnit("7", "AGGREGATE", "7", 2), + worldUnit("7", "REGION_SUBTREE", "7", 4), + worldUnit("7", "ZONE_SUBTREE", "7", 4)))); + assertPlanRejected( + binding( + revisions, + List.of( + worldUnit("7", "AGGREGATE", "7", 3), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + assertPlanRejected( + binding( + revisions, + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 5)))); + } + + @Test + void rejectsChangedTargetAndProtoCommitOrRevisionIdentity() { + UUID revisionId = uuid(5); + List revisions = + List.of(worldRevision("0", revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4))); + List units = + List.of(worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)); + DraftCommitBinding valid = binding(revisions, units); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + WorldDraftRegionCommitPlan.create( + valid, + ownerBinding( + TENANT_ID, + UUID.fromString("55555555-5555-4555-8555-555555555555"), + GAME_DESIGN_VERSION_ID))); + assertPlanRejected( + binding( + List.of(worldRevision("0", revisionId, regionJson(revisionId, uuid(9), "7", 2, 4))), + units)); + assertPlanRejected( + binding( + List.of(worldRevision("0", revisionId, regionJson(uuid(10), COMMIT_ID, "7", 2, 4))), + units)); + } + + @Test + void comparesOnlyTheSharedCanonicalTargetAndGameDesignVersionSelector() { + UUID revisionId = uuid(5); + List revisions = + List.of(worldRevision("0", revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4))); + List units = + List.of(worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)); + + DraftCommitBinding differentTenant = + binding(targetProof(uuid(50), VERSION_ID, GAME_DESIGN_VERSION_ID), revisions, units); + DraftCommitBinding differentGameDesignVersion = + binding(targetProof(TENANT_ID, VERSION_ID, GAME_DESIGN_VERSION_ID + 1L), revisions, units); + + assertPlanRejected(differentTenant, ownerBinding()); + assertPlanRejected(differentGameDesignVersion, ownerBinding()); + assertPlanRejected( + binding(revisions, units), + ownerBinding(TENANT_ID, VERSION_ID, GAME_DESIGN_VERSION_ID + 1L)); + } + + @Test + void rejectsUnknownPayloadFieldsAndMalformedTypedJson() { + UUID revisionId = uuid(5); + String valid = regionJson(revisionId, COMMIT_ID, "7", 2, 4); + String withUnknownField = valid.substring(0, valid.length() - 1) + ",\"unrecognized\":true}"; + + assertPlanRejected( + binding( + List.of(worldRevision("0", revisionId, withUnknownField)), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + assertPlanRejected( + binding( + List.of(worldRevision("0", revisionId, "{")), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + } + + @Test + void rejectsNoncanonicalOrOutOfRangeRegionIdsAndMismatchedScopeIds() { + UUID revisionId = uuid(5); + for (String id : List.of("0", "01", "+7", " 7", "9223372036854775808")) { + assertPlanRejected( + binding( + List.of(worldRevision("0", revisionId, regionJson(revisionId, COMMIT_ID, id, 2, 4))), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + } + assertPlanRejected( + binding( + List.of( + worldRevision("0", revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4, "8"))), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + } + + @Test + void rejectsNegativeMaxAndBindingMismatchedEpochs() { + UUID revisionId = uuid(5); + assertPlanRejected( + planBinding(revisionId, regionJson(revisionId, COMMIT_ID, "7", -1, 4), 0, 4)); + assertPlanRejected( + planBinding( + revisionId, + regionJson(revisionId, COMMIT_ID, "7", Long.MAX_VALUE, 4), + Long.MAX_VALUE, + 4)); + assertPlanRejected( + planBinding(revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, -1), 2, 0)); + assertPlanRejected( + planBinding( + revisionId, + regionJson(revisionId, COMMIT_ID, "7", 2, Long.MAX_VALUE), + 2, + Long.MAX_VALUE)); + assertPlanRejected(planBinding(revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4), 3, 4)); + + WorldDraftRegionCommitPlan plan = + WorldDraftRegionCommitPlan.create( + planBinding( + revisionId, + regionJson(revisionId, COMMIT_ID, "7", Long.MAX_VALUE - 1, 4), + Long.MAX_VALUE - 1, + 4), + ownerBinding()); + assertThat(plan.regionRevisions().getFirst().mutation().getExpectedDraftRevisionEpoch()) + .isEqualTo(Long.MAX_VALUE - 1); + } + + @Test + void rejectsDuplicateRegionMutationsAndUnsupportedCreateDeleteReplacementOrGenerationShapes() { + UUID firstRevision = uuid(5); + UUID secondRevision = uuid(6); + assertPlanRejected( + binding( + List.of( + worldRevision("0", firstRevision, regionJson(firstRevision, COMMIT_ID, "7", 2, 4)), + worldRevision( + "1", secondRevision, regionJson(secondRevision, COMMIT_ID, "7", 2, 4))), + List.of( + worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4)))); + assertPlanRejected( + planBinding(firstRevision, regionJson(firstRevision, COMMIT_ID, "", 2, 4), 2, 4)); + assertPlanRejected( + planBinding( + firstRevision, + json( + regionRevision(firstRevision, COMMIT_ID, "7", 2, 4).toBuilder() + .setOperation( + WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_DELETE) + .build()), + 2, + 4)); + assertPlanRejected( + planBinding( + firstRevision, + json( + regionRevision(firstRevision, COMMIT_ID, "7", 2, 4).toBuilder() + .setOperation( + WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UNSPECIFIED) + .build()), + 2, + 4)); + assertPlanRejected( + planBinding( + firstRevision, + json( + regionRevision(firstRevision, COMMIT_ID, "7", 2, 4).toBuilder() + .setScopeMutationPolicy( + WorldDesignScopeMutationPolicy + .WORLD_DESIGN_SCOPE_MUTATION_POLICY_REPLACE_SCOPE) + .build()), + 2, + 4)); + assertPlanRejected( + planBinding( + firstRevision, + json( + regionRevision(firstRevision, COMMIT_ID, "7", 2, 4).toBuilder() + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_NEW_EMPTY_REGION) + .build()), + 2, + 4)); + assertPlanRejected( + planBinding( + firstRevision, + json( + WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(firstRevision.toString()) + .setCommitId(COMMIT_ID.toString()) + .setOperation( + WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType( + WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_GENERATION_SUBTREE) + .setAggregateId("7") + .setExpectedDraftRevisionEpoch(2) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId("7") + .setExpectedDraftScopeRevisionEpoch(4) + .setWorldGenerationSubtree( + WorldGenerationSubtreeDesignMutation.getDefaultInstance()) + .build()), + 2, + 4)); + } + + @Test + void rejectsBlankNameNonfiniteOrNegativeSpacingAndNonRegionPayload() { + UUID revisionId = uuid(5); + for (double spacing : List.of(Double.NaN, Double.POSITIVE_INFINITY, -0.5d)) { + assertPlanRejected( + planBinding( + revisionId, + json( + regionRevision(revisionId, COMMIT_ID, "7", 2, 4).toBuilder() + .setRegion( + RegionDesignMutation.newBuilder() + .setName("North") + .setSpacingMultiplier(spacing)) + .build()), + 2, + 4)); + } + assertPlanRejected( + planBinding( + revisionId, + json( + regionRevision(revisionId, COMMIT_ID, "7", 2, 4).toBuilder() + .setRegion( + RegionDesignMutation.newBuilder().setName(" ").setSpacingMultiplier(1.0d)) + .build()), + 2, + 4)); + assertPlanRejected( + planBinding( + revisionId, + json( + regionRevision(revisionId, COMMIT_ID, "7", 2, 4).toBuilder().clearRegion().build()), + 2, + 4)); + } + + @Test + void preservesZeroSpacingForTheExistingWorldDefaultRule() { + UUID revisionId = uuid(5); + String payload = + json( + regionRevision(revisionId, COMMIT_ID, "7", 2, 4).toBuilder() + .setRegion(RegionDesignMutation.newBuilder().setName("Northern Reach")) + .build()); + DraftCommitBinding binding = + binding( + List.of(worldRevision("0", revisionId, payload)), + List.of(worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4))); + + WorldDraftRegionCommitPlan plan = WorldDraftRegionCommitPlan.create(binding, ownerBinding()); + + assertThat(plan.regionRevisions().getFirst().mutation().getRegion().getSpacingMultiplier()) + .isZero(); + assertThat(plan.binding().revisions().getFirst().payload()).isEqualTo(payload); + } + + @Test + void sharedBindingRejectsDuplicateAffectedWorldTuples() { + UUID revisionId = uuid(5); + List units = + List.of( + worldUnit("7", "AGGREGATE", "7", 2), + worldUnit("7", "AGGREGATE", "7", 2), + worldUnit("7", "REGION_SUBTREE", "7", 4)); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> + binding( + List.of( + worldRevision( + "0", revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4))), + units)); + } + + @Test + void planCollectionsAreDefensiveAndKeepTheExactSharedBaseAndRequest() { + UUID revisionId = uuid(5); + ArrayList supplied = + new ArrayList<>( + List.of(worldRevision("0", revisionId, regionJson(revisionId, COMMIT_ID, "7", 2, 4)))); + DraftCommitBinding binding = + binding( + supplied, + List.of(worldUnit("7", "AGGREGATE", "7", 2), worldUnit("7", "REGION_SUBTREE", "7", 4))); + supplied.clear(); + WorldDraftRegionCommitPlan plan = WorldDraftRegionCommitPlan.create(binding, ownerBinding()); + + assertThat(plan.binding().requestId()).isEqualTo(REQUEST_ID); + assertThat(plan.binding().baseCommitId()).isEqualTo("base-commit-17"); + assertThat(plan.regionRevisions()).hasSize(1); + assertThatThrownBy(() -> plan.regionRevisions().add(plan.regionRevisions().getFirst())) + .isInstanceOf(UnsupportedOperationException.class); + } + + private static DraftCommitBinding planBinding( + UUID revisionId, String payload, long aggregateEpoch, long scopeEpoch) { + return binding( + List.of(worldRevision("0", revisionId, payload)), + List.of( + worldUnit("7", "AGGREGATE", "7", aggregateEpoch), + worldUnit("7", "REGION_SUBTREE", "7", scopeEpoch))); + } + + private static DraftCommitBinding binding( + List revisions, List units) { + return binding(targetProof(TENANT_ID, VERSION_ID, GAME_DESIGN_VERSION_ID), revisions, units); + } + + private static DraftCommitBinding binding( + DraftCommitBinding.TargetProof target, + List revisions, + List units) { + return DraftCommitBinding.create( + target, REQUEST_ID, COMMIT_ID, "base-commit-17", revisions, units); + } + + private static DraftCommitBinding.TargetProof targetProof( + UUID tenantId, UUID versionId, long gameDesignVersionRowId) { + return new DraftCommitBinding.TargetProof( + tenantId, + versionId, + gameDesignVersionRowId, + "tenant-123", + 1001L, + "tenant-123", + "NEW_GAME_ROW"); + } + + private static DraftCommitBinding.RevisionPayload worldRevision( + String order, UUID revisionId, String payload) { + return new DraftCommitBinding.RevisionPayload( + order, revisionId, Owner.WORLD_MANAGEMENT, payload); + } + + private static DraftCommitBinding.RevisionPayload otherRevision(String order) { + return new DraftCommitBinding.RevisionPayload( + order, uuid(30), Owner.GAME_LOGIC, OTHER_OWNER_PAYLOAD); + } + + private static AffectedUnit worldUnit( + String aggregateId, String scopeType, String scopeId, long expectedEpoch) { + return new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + aggregateId, + scopeType, + scopeId, + Long.toString(expectedEpoch)); + } + + private static AffectedUnit otherUnit() { + return new AffectedUnit( + Owner.GAME_LOGIC, "ABILITY", "ability-77", "AGGREGATE", "ability-77", "0"); + } + + private static WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding() { + return ownerBinding(TENANT_ID, VERSION_ID, GAME_DESIGN_VERSION_ID); + } + + private static WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding( + UUID tenantId, UUID versionId, long gameDesignVersionId) { + return new WorldDesignPublicationFenceEvidence.OwnerBinding( + "firemud", + tenantId, + versionId, + uuid(40), + gameDesignVersionId, + uuid(41), + uuid(42), + PREFIXED_DIGEST, + uuid(43), + PREFIXED_DIGEST, + PREFIXED_DIGEST); + } + + private static String regionJson( + UUID revisionId, UUID commitId, String regionId, long aggregateEpoch, long scopeEpoch) { + return regionJson(revisionId, commitId, regionId, aggregateEpoch, scopeEpoch, regionId); + } + + private static String regionJson( + UUID revisionId, + UUID commitId, + String regionId, + long aggregateEpoch, + long scopeEpoch, + String scopeId) { + return json( + regionRevision(revisionId, commitId, regionId, aggregateEpoch, scopeEpoch, scopeId)); + } + + private static WorldDesignMutationRevision regionRevision( + UUID revisionId, UUID commitId, String regionId, long aggregateEpoch, long scopeEpoch) { + return regionRevision(revisionId, commitId, regionId, aggregateEpoch, scopeEpoch, regionId); + } + + private static WorldDesignMutationRevision regionRevision( + UUID revisionId, + UUID commitId, + String regionId, + long aggregateEpoch, + long scopeEpoch, + String scopeId) { + return WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revisionId.toString()) + .setCommitId(commitId.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setAggregateId(regionId) + .setExpectedDraftRevisionEpoch(aggregateEpoch) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(scopeId) + .setExpectedDraftScopeRevisionEpoch(scopeEpoch) + .setRegion( + RegionDesignMutation.newBuilder().setName("Northern Reach").setSpacingMultiplier(1.25d)) + .build(); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException( + "Test mutation could not be rendered as protobuf JSON", exception); + } + } + + private static void assertPlanRejected(DraftCommitBinding binding) { + assertPlanRejected(binding, ownerBinding()); + } + + private static void assertPlanRejected( + DraftCommitBinding binding, WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding) { + assertThatIllegalArgumentException() + .isThrownBy(() -> WorldDraftRegionCommitPlan.create(binding, ownerBinding)); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-0000-4000-8000-%012d", value, value)); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java new file mode 100644 index 0000000000..478cc91384 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitRepositoryTest.java @@ -0,0 +1,102 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +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 java.sql.Connection; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.ResultQuery; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +class WorldDraftRegionCommitRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final WorldDesignPublicationFenceRepository fence = + mock(WorldDesignPublicationFenceRepository.class); + private final ObjectMapper mapper = mock(ObjectMapper.class); + private final WorldDraftRegionCommitRepository repository = + new WorldDraftRegionCommitRepository(dsl, fence, mapper); + private final WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + + @AfterEach + void clearTransactionFixture() { + TransactionSynchronizationManager.clear(); + } + + @Test + void absentTransactionCannotResolveOrTouchHistory() { + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } + + @Test + void readOnlyTransactionCannotResolveOrTouchHistory() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } + + @Test + void repeatableReadCannotUseReadCommittedReplayAndOwnerLockOrdering() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_REPEATABLE_READ); + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } + + @Test + void committedReadbackRejectsActiveCallerBeforeStorageOrSourceResolution() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repository.readCommitted(plan)) + .hasMessageContaining("no active caller transaction"); + verifyNoInteractions(dsl, fence, mapper, plan); + } + + @Test + @SuppressWarnings("unchecked") + void missingCommittedOperationIsUnknownWithoutOwnerClaimOrMutation() { + DraftCommitBinding binding = mock(DraftCommitBinding.class); + WorldDesignPublicationFenceEvidence.OwnerBinding owner = + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class); + ResultQuery query = mock(ResultQuery.class); + Result rows = mock(Result.class); + when(plan.binding()).thenReturn(binding); + when(plan.ownerBinding()).thenReturn(owner); + when(binding.requestId()).thenReturn(UUID.randomUUID()); + when(binding.commitId()).thenReturn(UUID.randomUUID()); + when(mapper.writeValueAsString(owner)).thenReturn("synthetic-owner-json"); + when(dsl.resultQuery(anyString(), any(Object[].class))).thenReturn(query); + when(query.fetch()).thenReturn(rows); + when(rows.isEmpty()).thenReturn(true); + assertThat(repository.readCommitted(plan)).isEmpty(); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(dsl).resultQuery(sql.capture(), any(Object[].class)); + assertThat(sql.getValue()) + .startsWith("SELECT ") + .doesNotContain("FOR UPDATE", "INSERT ", "UPDATE ", "DELETE "); + verify(query).fetch(); + verifyNoMoreInteractions(dsl, query); + verifyNoInteractions(fence); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java new file mode 100644 index 0000000000..64de374f9a --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitServiceTest.java @@ -0,0 +1,121 @@ +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.inOrder; +import static org.mockito.Mockito.mock; +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 java.util.Optional; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldDraftRegionCommitServiceTest { + private final WorldDraftRegionCommitRepository repository = + mock(WorldDraftRegionCommitRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final WorldDraftRegionCommitService.PermissionVerifier verifier = + mock(WorldDraftRegionCommitService.PermissionVerifier.class); + private final WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + + @AfterEach + void clearTransactionFixture() { + TransactionSynchronizationManager.clear(); + } + + @Test + void defaultDenialCannotStartTransactionOrAccessOwnerStorage() { + WorldDraftRegionCommitService service = new WorldDraftRegionCommitService(repository, manager); + assertThatThrownBy(() -> service.store(plan)).hasMessageContaining("permission is unavailable"); + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsCallerTransactionBeforeVerifierCouldMakeAnExternalCall() { + TransactionSynchronizationManager.setActualTransactionActive(true); + WorldDraftRegionCommitService service = + new WorldDraftRegionCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.store(plan)).hasMessageContaining("existing transaction"); + verifyNoInteractions(verifier, repository, manager); + } + + @Test + void syntheticVerifierPrecedesDedicatedWritableReadCommittedTransactionAndCommit() { + // This sequencing fixture is not authenticated Account ordering or fence release proof. + TransactionStatus status = mock(TransactionStatus.class); + WorldDraftRegionCommitEvidence evidence = mock(WorldDraftRegionCommitEvidence.class); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.store(plan)).thenReturn(evidence); + WorldDraftRegionCommitService service = + new WorldDraftRegionCommitService(repository, manager, verifier); + assertThat(service.store(plan)).isSameAs(evidence); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + InOrder order = inOrder(verifier, manager, repository); + order.verify(verifier).verify(plan); + order.verify(manager).getTransaction(definition.capture()); + order.verify(repository).store(plan); + order.verify(manager).commit(status); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().isReadOnly()).isFalse(); + } + + @Test + void localFailureRollsBackWithoutReturningStorageEvidence() { + TransactionStatus status = mock(TransactionStatus.class); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.store(plan)).thenThrow(new IllegalStateException("late tuple conflict")); + WorldDraftRegionCommitService service = + new WorldDraftRegionCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.store(plan)).hasMessage("late tuple conflict"); + InOrder order = inOrder(manager, repository); + order.verify(manager).getTransaction(any()); + order.verify(repository).store(plan); + order.verify(manager).rollback(status); + } + + @Test + void committedReadbackReturnsOriginalEvidenceWithoutVerifierOrTransactionInteractions() { + WorldDraftRegionCommitEvidence evidence = mock(WorldDraftRegionCommitEvidence.class); + when(repository.readCommitted(plan)).thenReturn(Optional.of(evidence)); + WorldDraftRegionCommitService service = + new WorldDraftRegionCommitService(repository, manager, verifier); + assertThat(service.readCommitted(plan)).containsSame(evidence); + verify(repository).readCommitted(plan); + verifyNoMoreInteractions(repository); + verifyNoInteractions(verifier, manager); + } + + @Test + void missingCommittedReadbackRemainsUnknownWithoutAttemptingDeniedWriter() { + when(repository.readCommitted(plan)).thenReturn(Optional.empty()); + WorldDraftRegionCommitService service = new WorldDraftRegionCommitService(repository, manager); + assertThat(service.readCommitted(plan)).isEmpty(); + verify(repository).readCommitted(plan); + verifyNoMoreInteractions(repository); + verifyNoInteractions(verifier, manager); + } + + @Test + void committedReadbackRejectsActiveCallerBeforeAnyCollaboratorInteraction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + WorldDraftRegionCommitService service = + new WorldDraftRegionCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.readCommitted(plan)) + .hasMessageContaining("no active caller transaction"); + verifyNoInteractions(repository, verifier, manager, plan); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStagerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStagerTest.java new file mode 100644 index 0000000000..697b29635b --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionGraphStagerTest.java @@ -0,0 +1,366 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraph; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionGraphStager; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.junit.jupiter.api.Test; + +class WorldDraftRegionGraphStagerTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final long GAME_DESIGN_VERSION_ID = 9_000_000_042L; + private static final String PREFIXED_DIGEST = "sha256:" + "a".repeat(64); + private static final long LARGE_REGION_ID = 9_223_372_036_854_775_806L; + + @Test + void stagesOrderedExistingRegionsAndPreservesBindingRowsAndUntouchedFamilies() { + RegionSpec first = + new RegionSpec( + LARGE_REGION_ID, + uuid(5), + RegionDesignMutation.newBuilder() + .setName("Updated North") + .setWeather("rain") + .setShardId(3) + .setGenerationSeed(Long.MAX_VALUE) + .setGeneratorType("cave") + .setGeneratorParams("density=4") + .setSpacingMultiplier(0.0d) + .build(), + Long.MAX_VALUE - 1L, + Long.MAX_VALUE - 2L); + RegionSpec second = + new RegionSpec( + 19L, + uuid(6), + RegionDesignMutation.newBuilder() + .setName("Updated South") + .setWeather(" ") + .setShardId(0) + .setGenerationSeed(Long.MIN_VALUE) + .setGeneratorType(" ") + .setGeneratorParams("\t") + .setSpacingMultiplier(2.5d) + .build(), + 7, + 9); + WorldDraftRegionCommitPlan plan = plan(first, second); + WorldAuthoredGraph priorGraph = + graph( + List.of( + region(99L, "Untouched", "clear", "old", "old params", 10L, 1.5d), + region(LARGE_REGION_ID, "Old North", "snow", "old", "old params", 11L, 0.75d), + region(19L, "Old South", "sun", "old", "old params", 12L, 3.0d)), + List.of(row(101L)), + List.of(row(201L)), + List.of(row(301L)), + List.of(row(401L)), + List.of(row(501L))); + + WorldDraftRegionGraphStager.UnverifiedStagedContent staged = + new WorldDraftRegionGraphStager().stage(plan, priorGraph); + + assertThat(staged.binding()).isSameAs(plan.binding()); + assertThat(staged.ownerBinding()).isSameAs(plan.ownerBinding()); + assertThat(staged.binding().baseCommitId()) + .isEqualTo("base-commit-from-an-older-disjoint-snapshot"); + assertThat(staged.binding().affectedUnits(Owner.WORLD_MANAGEMENT)) + .extracting(AffectedUnit::expectedEpoch) + .contains("9223372036854775806", "9223372036854775805"); + assertThat(plan.regionRevisions()) + .extracting(revision -> revision.revisionOrder()) + .containsExactly("0", "2"); + assertThat(staged.graph().regions()) + .extracting(row -> row.get("id")) + .containsExactly(99L, LARGE_REGION_ID, 19L); + assertThat(staged.graph().regions().get(0)).containsEntry("name", "Untouched"); + assertThat(staged.graph().regions().get(1)) + .containsEntry("id", LARGE_REGION_ID) + .containsEntry("shardId", 3) + .containsEntry("name", "Updated North") + .containsEntry("weather", "rain") + .containsEntry("generationSeed", Long.MAX_VALUE) + .containsEntry("generatorType", "cave") + .containsEntry("generatorParams", "density=4") + .containsEntry("spacingMultiplier", 1.0d); + assertThat(staged.graph().regions().get(2)) + .containsEntry("id", 19L) + .containsEntry("name", "Updated South") + .containsEntry("weather", null) + .containsEntry("generationSeed", Long.MIN_VALUE) + .containsEntry("generatorType", null) + .containsEntry("generatorParams", null) + .containsEntry("spacingMultiplier", 2.5d); + assertThat(staged.graph().zones()).containsExactlyElementsOf(priorGraph.zones()); + assertThat(staged.graph().rooms()).containsExactlyElementsOf(priorGraph.rooms()); + assertThat(staged.graph().roomExits()).containsExactlyElementsOf(priorGraph.roomExits()); + assertThat(staged.graph().generationRules()) + .containsExactlyElementsOf(priorGraph.generationRules()); + assertThat(staged.graph().spawnBindings()) + .containsExactlyElementsOf(priorGraph.spawnBindings()); + assertThat(priorGraph.regions().get(1)).containsEntry("name", "Old North"); + } + + @Test + void rejectsUnsupportedMissingDuplicateInconsistentAndInvalidTargetsWithoutPartialOutput() { + RegionSpec first = validSpec(LARGE_REGION_ID, uuid(5)); + RegionSpec missing = validSpec(19L, uuid(6)); + WorldDraftRegionCommitPlan twoRegionPlan = plan(first, missing); + WorldAuthoredGraph missingSecondTarget = + graph(List.of(region(LARGE_REGION_ID, "Old North", null, null, null, 12L, 1.0d))); + + assertThatIllegalArgumentException() + .isThrownBy( + () -> new WorldDraftRegionGraphStager().stage(twoRegionPlan, missingSecondTarget)); + assertThat(missingSecondTarget.regions()).hasSize(1); + assertThat(missingSecondTarget.regions().getFirst()).containsEntry("name", "Old North"); + + WorldDraftRegionCommitPlan oneRegionPlan = plan(first); + WorldAuthoredGraph duplicateTargets = + graph( + List.of( + region(LARGE_REGION_ID, "North A", null, null, null, 1L, 1.0d), + region(LARGE_REGION_ID, "North B", null, null, null, 2L, 1.0d))); + assertThatIllegalArgumentException() + .isThrownBy(() -> new WorldDraftRegionGraphStager().stage(oneRegionPlan, duplicateTargets)); + + Map inconsistentRegion = + region(LARGE_REGION_ID, "North", null, null, null, 1L, 1.0d); + inconsistentRegion.put("id", (int) LARGE_REGION_ID); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDraftRegionGraphStager() + .stage(oneRegionPlan, graph(List.of(inconsistentRegion)))); + + Map missingField = region(LARGE_REGION_ID, "North", null, null, null, 1L, 1.0d); + missingField.remove("weather"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDraftRegionGraphStager() + .stage(oneRegionPlan, graph(List.of(missingField)))); + + Map extraField = region(LARGE_REGION_ID, "North", null, null, null, 1L, 1.0d); + extraField.put("unrecognized", "value"); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDraftRegionGraphStager().stage(oneRegionPlan, graph(List.of(extraField)))); + + RegionSpec negativeShard = + new RegionSpec( + LARGE_REGION_ID, + uuid(7), + RegionDesignMutation.newBuilder().setName("Bad shard").setShardId(-1).build(), + 1, + 1); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + new WorldDraftRegionGraphStager() + .stage( + plan(negativeShard), + graph( + List.of( + region(LARGE_REGION_ID, "North", null, null, null, 1L, 1.0d))))); + + RegionSpec nonfiniteSpacing = + new RegionSpec( + LARGE_REGION_ID, + uuid(8), + RegionDesignMutation.newBuilder() + .setName("Bad spacing") + .setSpacingMultiplier(Double.NaN) + .build(), + 1, + 1); + assertThatIllegalArgumentException().isThrownBy(() -> plan(nonfiniteSpacing)); + + WorldDesignMutationRevision unsupportedMutation = + mutation(first, WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_DELETE); + assertThatIllegalArgumentException() + .isThrownBy(() -> planWithMutations(List.of(unsupportedMutation), List.of(first))); + } + + private static WorldDraftRegionCommitPlan plan(RegionSpec... specs) { + List mutations = new ArrayList<>(); + for (RegionSpec spec : specs) { + mutations.add( + mutation(spec, WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT)); + } + return planWithMutations(mutations, List.of(specs)); + } + + private static WorldDraftRegionCommitPlan planWithMutations( + List worldMutations, List specs) { + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + int revisionOrder = 0; + for (int index = 0; index < worldMutations.size(); index++) { + WorldDesignMutationRevision mutation = worldMutations.get(index); + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisionOrder++), + UUID.fromString(mutation.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + json(mutation))); + RegionSpec spec = specs.get(index); + units.add(worldUnit(Long.toString(spec.regionId()), "AGGREGATE", spec.aggregateEpoch())); + units.add(worldUnit(Long.toString(spec.regionId()), "REGION_SUBTREE", spec.scopeEpoch())); + if (index == 0) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisionOrder++), + uuid(30), + Owner.GAME_LOGIC, + "opaque game logic revision")); + units.add( + new AffectedUnit( + Owner.GAME_LOGIC, "ABILITY", "ability-17", "AGGREGATE", "ability-17", "2")); + } + } + DraftCommitBinding binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT_ID, + VERSION_ID, + GAME_DESIGN_VERSION_ID, + "tenant-123", + 1001L, + "tenant-123", + "NEW_GAME_ROW"), + REQUEST_ID, + COMMIT_ID, + "base-commit-from-an-older-disjoint-snapshot", + revisions, + units); + return WorldDraftRegionCommitPlan.create(binding, ownerBinding()); + } + + private static WorldDesignMutationRevision mutation( + RegionSpec spec, WorldDesignMutationOperation operation) { + return WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(spec.revisionId().toString()) + .setCommitId(COMMIT_ID.toString()) + .setOperation(operation) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setAggregateId(Long.toString(spec.regionId())) + .setExpectedDraftRevisionEpoch(spec.aggregateEpoch()) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(Long.toString(spec.regionId())) + .setExpectedDraftScopeRevisionEpoch(spec.scopeEpoch()) + .setRegion(spec.payload()) + .build(); + } + + private static RegionSpec validSpec(long id, UUID revisionId) { + return new RegionSpec( + id, + revisionId, + RegionDesignMutation.newBuilder().setName("Updated").setSpacingMultiplier(1.0d).build(), + 1, + 1); + } + + private static WorldAuthoredGraph graph(List> regions) { + return graph(regions, List.of(), List.of(), List.of(), List.of(), List.of()); + } + + private static WorldAuthoredGraph graph( + List> regions, + List> zones, + List> rooms, + List> roomExits, + List> generationRules, + List> spawnBindings) { + return new WorldAuthoredGraph(regions, zones, rooms, roomExits, generationRules, spawnBindings); + } + + private static Map region( + long id, + String name, + String weather, + String generatorType, + String generatorParams, + long generationSeed, + double spacingMultiplier) { + LinkedHashMap row = new LinkedHashMap<>(); + row.put("id", id); + row.put("shardId", 0); + row.put("name", name); + row.put("weather", weather); + row.put("generationSeed", generationSeed); + row.put("generatorType", generatorType); + row.put("generatorParams", generatorParams); + row.put("spacingMultiplier", spacingMultiplier); + return row; + } + + private static Map row(long id) { + LinkedHashMap row = new LinkedHashMap<>(); + row.put("id", id); + return row; + } + + private static AffectedUnit worldUnit(String id, String scopeType, long epoch) { + return new AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", id, scopeType, id, Long.toString(epoch)); + } + + private static WorldDesignPublicationFenceEvidence.OwnerBinding ownerBinding() { + return new WorldDesignPublicationFenceEvidence.OwnerBinding( + "firemud", + TENANT_ID, + VERSION_ID, + uuid(40), + GAME_DESIGN_VERSION_ID, + uuid(41), + uuid(42), + PREFIXED_DIGEST, + uuid(43), + PREFIXED_DIGEST, + PREFIXED_DIGEST); + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().print(mutation); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException( + "Test World revision could not be rendered as JSON", exception); + } + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-0000-4000-8000-%012d", value, value)); + } + + private record RegionSpec( + long regionId, + UUID revisionId, + RegionDesignMutation payload, + long aggregateEpoch, + long scopeEpoch) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingServiceTest.java new file mode 100644 index 0000000000..f5581f163e --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionStagingServiceTest.java @@ -0,0 +1,142 @@ +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.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.OpenOwner; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.InOrder; + +class WorldDraftRegionStagingServiceTest { + private final WorldDesignPublicationFenceRepository fence = + mock(WorldDesignPublicationFenceRepository.class); + private final WorldAuthoredGraphReader reader = mock(WorldAuthoredGraphReader.class); + private final WorldDraftRegionGraphStager stager = mock(WorldDraftRegionGraphStager.class); + private final WorldDraftRegionStagingService service = + new WorldDraftRegionStagingService(fence, reader, stager); + + @Test + void resolvesExactOwnerBeforeReadingServerPrivateKeysAndInvokingExistingStager() { + // Synthetic unit prerequisites: these doubles prove sequencing, not authenticated intake. + WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + OwnerBinding binding = ownerBinding(); + WorldAuthoredSourceIntakeReceipt receipt = mock(WorldAuthoredSourceIntakeReceipt.class); + bindSyntheticSource(plan, receipt); + when(receipt.localTenantKey()).thenReturn(123L); + when(plan.ownerBinding()).thenReturn(binding); + when(fence.lockOpenAndResolve(binding)).thenReturn(new OpenOwner(binding, receipt, 456L)); + WorldAuthoredGraph graph = + new WorldAuthoredGraph(List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + when(reader.readAndValidateGraph(123L, 456L)).thenReturn(graph); + WorldDraftRegionGraphStager.UnverifiedStagedContent content = + new WorldDraftRegionGraphStager.UnverifiedStagedContent(plan.binding(), binding, graph); + when(stager.stage(plan, graph)).thenReturn(content); + + assertThat(service.stage(plan)).isSameAs(content); + InOrder order = inOrder(fence, reader, stager); + order.verify(fence).lockOpenAndResolve(binding); + order.verify(reader).readAndValidateGraph(123L, 456L); + order.verify(stager).stage(plan, graph); + order.verifyNoMoreInteractions(); + assertThat(binding.gameDesignVersionId()).isNotEqualTo(456L); + } + + @Test + void rejectsClosedOwnerBeforeAnyGraphReadOrStaging() { + WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + OwnerBinding binding = ownerBinding(); + when(plan.ownerBinding()).thenReturn(binding); + when(fence.lockOpenAndResolve(binding)) + .thenThrow(new WorldDesignPublicationFenceRepository.ConflictException("not OPEN")); + + assertThatThrownBy(() -> service.stage(plan)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + verifyNoInteractions(reader, stager); + } + + @Test + void incompletePriorGraphCannotReachStager() { + WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + OwnerBinding binding = ownerBinding(); + WorldAuthoredSourceIntakeReceipt receipt = mock(WorldAuthoredSourceIntakeReceipt.class); + bindSyntheticSource(plan, receipt); + when(receipt.localTenantKey()).thenReturn(123L); + when(plan.ownerBinding()).thenReturn(binding); + when(fence.lockOpenAndResolve(binding)).thenReturn(new OpenOwner(binding, receipt, 456L)); + when(reader.readAndValidateGraph(123L, 456L)) + .thenThrow(new WorldAuthoredGraphSnapshotRepository.SnapshotConflictException("bad graph")); + + assertThatThrownBy(() -> service.stage(plan)) + .isInstanceOf(WorldAuthoredGraphSnapshotRepository.SnapshotConflictException.class); + verifyNoInteractions(stager); + } + + @ParameterizedTest + @ValueSource(strings = {"sourceGameRowId", "sourceGameTenantKey", "sourceProvenanceKind"}) + void rejectsEachChangedSourceFieldBeforeAnyGraphReadOrStaging(String changedField) { + WorldDraftRegionCommitPlan plan = mock(WorldDraftRegionCommitPlan.class); + OwnerBinding binding = ownerBinding(); + WorldAuthoredSourceIntakeReceipt receipt = mock(WorldAuthoredSourceIntakeReceipt.class); + TargetProof target = bindSyntheticSource(plan, receipt); + when(plan.ownerBinding()).thenReturn(binding); + when(fence.lockOpenAndResolve(binding)).thenReturn(new OpenOwner(binding, receipt, 456L)); + switch (changedField) { + case "sourceGameRowId" -> when(target.sourceGameRowId()).thenReturn(999L); + case "sourceGameTenantKey" -> + when(target.sourceGameTenantKey()).thenReturn("changed-source-key"); + case "sourceProvenanceKind" -> + when(target.sourceProvenanceKind()).thenReturn("changed-provenance"); + default -> throw new IllegalArgumentException("Unexpected synthetic negative field"); + } + + assertThatThrownBy(() -> service.stage(plan)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("source provenance"); + verifyNoInteractions(reader, stager); + } + + private static TargetProof bindSyntheticSource( + WorldDraftRegionCommitPlan plan, WorldAuthoredSourceIntakeReceipt receipt) { + // Complete compared provenance is stipulated here; these doubles do not prove authentication. + DraftCommitBinding binding = mock(DraftCommitBinding.class); + TargetProof target = mock(TargetProof.class); + AuthoredWorldSourceEvidence source = mock(AuthoredWorldSourceEvidence.class); + when(plan.binding()).thenReturn(binding); + when(binding.target()).thenReturn(target); + when(receipt.source()).thenReturn(source); + when(target.sourceGameRowId()).thenReturn(789L); + when(target.sourceGameTenantKey()).thenReturn("gd-row-789"); + when(target.sourceProvenanceKind()).thenReturn("NEW_GAME_ROW"); + when(source.sourceGameRowId()).thenReturn(789L); + when(source.sourceGameTenantKey()).thenReturn("gd-row-789"); + when(source.provenanceKind()).thenReturn("NEW_GAME_ROW"); + return target; + } + + private static OwnerBinding ownerBinding() { + return new OwnerBinding( + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + 987_654L, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + UUID.randomUUID(), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptTest.java new file mode 100644 index 0000000000..b1599785f3 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceiptTest.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.UUID; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import org.junit.jupiter.api.Test; + +class WorldDraftStartLocationReceiptTest { + @Test + void normalConstructionRetainsConstructorValuesAndSharedCanonicalBytes() { + var evidence = + WorldDraftStartLocationEvidence.create( + "test", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + "sha256:" + "0".repeat(64), + "sha256:" + "1".repeat(64), + new RoomTemplateRef( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + uuid("77777777-7777-4777-8777-777777777777")), + "sha256:" + "2".repeat(64)); + + var receipt = + new WorldDraftStartLocationReceipt( + evidence.targetNamespace(), + evidence.operationId(), + evidence.requestId(), + evidence.commitId(), + evidence.authorizationFenceId(), + evidence.accountBindingDigest(), + evidence.bindingDigest(), + evidence.startLocation(), + evidence.graphDigest(), + evidence.receiptDigest()); + + assertThat(receipt.canonicalBytes()).containsExactly(evidence.canonicalBytes()); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeTest.java new file mode 100644 index 0000000000..2f80d78869 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeTest.java @@ -0,0 +1,240 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOperation; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcome; +import org.junit.jupiter.api.Test; + +class WorldDraftTerminalOutcomeTest { + @Test + void operationRetainsAndStrictlyCrossChecksTheCompleteV57AccountBinding() { + Ids ids = ids(); + DraftCommitBinding binding = binding(ids); + byte[] accountBytes = accountBinding(binding, ids).canonicalBytes(); + WorldDraftTerminalOperation operation = operation(binding, accountBytes, ids); + + assertThat(operation.accountBindingBytes()).containsExactly(accountBytes); + assertThat(operation.accountBindingDigest()).isEqualTo(digest(accountBytes)); + assertThat(operation.canonicalBytes()).contains(accountBytes); + assertThat(operation.binding()).isEqualTo(binding); + } + + @Test + void changedOperationFenceTargetOrGameDesignBytesCannotReuseTheAccountBinding() { + Ids ids = ids(); + DraftCommitBinding binding = binding(ids); + byte[] accountBytes = accountBinding(binding, ids).canonicalBytes(); + + assertThatThrownBy( + () -> + operation( + binding, + accountBytes, + new Ids( + UUID.randomUUID(), ids.request(), ids.commit(), ids.fence(), ids.actor()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("V57 Account binding"); + assertThatThrownBy( + () -> + operation( + binding, + accountBytes, + new Ids( + ids.operation(), + ids.request(), + ids.commit(), + UUID.randomUUID(), + ids.actor()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("V57 Account binding"); + assertThatThrownBy( + () -> + new WorldDraftTerminalOperation( + ids.operation(), + ids.request(), + ids.commit(), + ids.fence(), + UUID.randomUUID(), + binding.target().canonicalVersionId(), + binding, + ownerBinding(binding), + accountBytes)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete Draft binding"); + } + + @Test + void abortEvidenceRequiresEveryExactWorldEpochAndRejectsSubstitutionOrMalformedFrames() { + Ids ids = ids(); + DraftCommitBinding binding = binding(ids); + WorldDraftTerminalOperation operation = + operation(binding, accountBinding(binding, ids).canonicalBytes(), ids); + List units = binding.affectedUnits(Owner.WORLD_MANAGEMENT); + var observed = + units.stream() + .map(unit -> new WorldDraftTerminalOutcome.ObservedEpoch(unit, unit.expectedEpoch())) + .toList(); + WorldDraftTerminalOutcome outcome = + WorldDraftTerminalOutcome.create( + operation, observed, java.time.OffsetDateTime.parse("2026-01-01T00:00:00Z")); + WorldDraftTerminalOutcome replay = + WorldDraftTerminalOutcome.fromStored( + operation, outcome.canonicalBytes(), outcome.digest(), outcome.recordedAt()); + + assertThat(replay.canonicalBytes()).containsExactly(outcome.canonicalBytes()); + assertThat(replay.digest()).isEqualTo(outcome.digest()); + assertThat(replay.observedEpochs()).isEqualTo(observed); + assertThatThrownBy( + () -> + WorldDraftTerminalOutcome.create( + operation, observed.subList(0, 1), outcome.recordedAt())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete affected set"); + assertThatThrownBy( + () -> + WorldDraftTerminalOutcome.fromStored( + operation, + outcome.canonicalBytes(), + digest("substituted".getBytes(StandardCharsets.UTF_8)), + outcome.recordedAt())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not exact canonical evidence"); + byte[] trailing = + java.util.Arrays.copyOf(outcome.canonicalBytes(), outcome.canonicalBytes().length + 1); + assertThatThrownBy( + () -> + WorldDraftTerminalOutcome.fromStored( + operation, trailing, outcome.digest(), outcome.recordedAt())) + .isInstanceOf(IllegalArgumentException.class); + } + + private WorldDraftTerminalOperation operation( + DraftCommitBinding binding, byte[] accountBytes, Ids ids) { + return new WorldDraftTerminalOperation( + ids.operation(), + ids.request(), + ids.commit(), + ids.fence(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding, + ownerBinding(binding), + accountBytes); + } + + private DraftAuthorizationFenceBinding accountBinding(DraftCommitBinding binding, Ids ids) { + return new DraftAuthorizationFenceBinding( + ids.operation(), + ids.request(), + ids.commit(), + ids.fence(), + ids.actor(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.baseCommitId(), + "0", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of( + new SourceEvidence( + SourceKind.TENANT, + binding.target().canonicalTenantId().toString(), + null, + "1", + null, + null, + new byte[] {1, 2, 3}))); + } + + private DraftCommitBinding binding(Ids ids) { + UUID tenant = UUID.randomUUID(); + UUID version = UUID.randomUUID(); + UUID aggregate = UUID.randomUUID(); + UUID worldRevision = UUID.randomUUID(); + UUID gdRevision = UUID.randomUUID(); + TargetProof target = + new TargetProof(tenant, version, 11, "gd-tenant", 12, "gd-tenant", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + ids.request(), + ids.commit(), + "base-commit", + List.of( + new RevisionPayload("0", worldRevision, Owner.WORLD_MANAGEMENT, "world mutation"), + new RevisionPayload("1", gdRevision, Owner.GAME_DESIGN_CONTROL_PLANE, "game mutation")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + aggregate.toString(), + "AGGREGATE", + aggregate.toString(), + "0"), + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + aggregate.toString(), + "REGION_SUBTREE", + aggregate.toString(), + "0"), + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "VERSION", + version.toString(), + "AGGREGATE", + version.toString(), + "0"))); + } + + private OwnerBinding ownerBinding(DraftCommitBinding binding) { + return new OwnerBinding( + "firemud", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + UUID.randomUUID(), + binding.target().gameDesignVersionRowId(), + UUID.randomUUID(), + UUID.randomUUID(), + digest(new byte[] {1}), + UUID.randomUUID(), + digest(new byte[] {2}), + digest(new byte[] {3})); + } + + private Ids ids() { + return new Ids( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID()); + } + + private String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record Ids(UUID operation, UUID request, UUID commit, UUID fence, UUID actor) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalReadGrpcServiceTest.java new file mode 100644 index 0000000000..b8a87d3fc1 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalReadGrpcServiceTest.java @@ -0,0 +1,273 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphAppliedResult; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcome; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcomeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldDraftTerminalOutcomeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldDraftTerminalReadStatus; +import org.junit.jupiter.api.Test; + +class WorldDraftTerminalReadGrpcServiceTest { + private final WorldDraftGraphApplicationRepository applications = + mock(WorldDraftGraphApplicationRepository.class); + + @Test + void rejectsMissingOrSubstitutedAccountPeerBeforeDecodingOrQuerying() { + WorldDraftTerminalOutcomeRepository repository = + mock(WorldDraftTerminalOutcomeRepository.class); + var service = new WorldDraftTerminalReadGrpcService(repository, applications, "test"); + ReadWorldDraftTerminalOutcomeRequest malformed = + ReadWorldDraftTerminalOutcomeRequest.newBuilder().setSchemaVersion(-1).build(); + + Collector missingPeer = new Collector(); + service.readWorldDraftTerminalOutcome(malformed, missingPeer); + assertThat(Status.fromThrowable(missingPeer.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + Collector wrongPeer = new Collector(); + Context context = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("world-management-service", "test")); + Context previous = context.attach(); + try { + service.readWorldDraftTerminalOutcome(malformed, wrongPeer); + } finally { + context.detach(previous); + } + assertThat(Status.fromThrowable(wrongPeer.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository, applications); + } + + @Test + void authenticatesThenReturnsUnknownForMissingTerminalRowWithoutInventingAbort() { + WorldDraftTerminalOutcomeRepository repository = + mock(WorldDraftTerminalOutcomeRepository.class); + var request = WorldDraftTerminalReadEvidence.Request.create("test", accountBinding()); + when(repository.readDefinitiveAbort(eq("test"), any(byte[].class))) + .thenReturn(Optional.empty()); + var service = new WorldDraftTerminalReadGrpcService(repository, applications, "test"); + Collector response = new Collector(); + Context context = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("account-service", "test")); + Context previous = context.attach(); + try { + service.readWorldDraftTerminalOutcome( + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec.toRequest( + request), + response); + } finally { + context.detach(previous); + } + + verify(repository).readDefinitiveAbort(eq("test"), any(byte[].class)); + verify(applications).readCommitted(eq("test"), any(byte[].class)); + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value.getStatus()) + .isEqualTo(WorldDraftTerminalReadStatus.WORLD_DRAFT_TERMINAL_READ_STATUS_UNKNOWN); + assertThat(response.value.getOwnerReadbackBytes()).isEmpty(); + } + + @Test + void trustedAccountPeerGetsUnavailableWhenJooqTerminalReadFails() { + WorldDraftTerminalOutcomeRepository repository = + mock(WorldDraftTerminalOutcomeRepository.class); + var request = WorldDraftTerminalReadEvidence.Request.create("test", accountBinding()); + when(repository.readDefinitiveAbort(eq("test"), any(byte[].class))) + .thenThrow(new org.jooq.exception.DataAccessException("database unavailable")); + var service = new WorldDraftTerminalReadGrpcService(repository, applications, "test"); + Collector response = new Collector(); + Context context = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("account-service", "test")); + Context previous = context.attach(); + try { + service.readWorldDraftTerminalOutcome( + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec.toRequest( + request), + response); + } finally { + context.detach(previous); + } + + verify(repository).readDefinitiveAbort(eq("test"), any(byte[].class)); + assertThat(Status.fromThrowable(response.error).getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + @Test + void conflictingCommittedAndAbortReceiptsReturnFailedPreconditionInsteadOfChoosingOne() { + var repository = mock(WorldDraftTerminalOutcomeRepository.class); + var request = WorldDraftTerminalReadEvidence.Request.create("test", accountBinding()); + var committed = mock(WorldDraftGraphAppliedResult.class); + when(repository.readDefinitiveAbort(eq("test"), any(byte[].class))) + .thenReturn(Optional.of(mock(WorldDraftTerminalOutcome.class))); + when(applications.readCommitted(eq("test"), any(byte[].class))) + .thenReturn(Optional.of(committed)); + var service = new WorldDraftTerminalReadGrpcService(repository, applications, "test"); + Collector response = callAsAccount(service, request); + assertThat(Status.fromThrowable(response.error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(response.value).isNull(); + verifyNoInteractions(committed); + } + + @Test + void substitutedCommittedOwnerReadbackFailsClosedAfterAuthenticatedOwnerReads() { + var repository = mock(WorldDraftTerminalOutcomeRepository.class); + var request = WorldDraftTerminalReadEvidence.Request.create("test", accountBinding()); + var committed = mock(WorldDraftGraphAppliedResult.class); + var binding = request.accountBinding(); + when(repository.readDefinitiveAbort(eq("test"), any(byte[].class))) + .thenReturn(Optional.empty()); + when(applications.readCommitted(eq("test"), any(byte[].class))) + .thenReturn(Optional.of(committed)); + when(committed.ownerReadback()) + .thenReturn( + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {1})); + var response = + callAsAccount( + new WorldDraftTerminalReadGrpcService(repository, applications, "test"), request); + assertThat(Status.fromThrowable(response.error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(response.value).isNull(); + } + + private static Collector callAsAccount( + WorldDraftTerminalReadGrpcService service, WorldDraftTerminalReadEvidence.Request request) { + Collector response = new Collector(); + var context = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("account-service", "test")); + var previous = context.attach(); + try { + service.readWorldDraftTerminalOutcome( + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec.toRequest( + request), + response); + } finally { + context.detach(previous); + } + return response; + } + + private static byte[] accountBinding() { + UUID tenant = uuid("11111111-1111-4111-8111-111111111111"); + UUID version = uuid("22222222-2222-4222-8222-222222222222"); + UUID request = uuid("44444444-4444-4444-8444-444444444444"); + UUID commit = uuid("55555555-5555-4555-8555-555555555555"); + DraftCommitBinding draft = + DraftCommitBinding.create( + new TargetProof(tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request, + commit, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + tenant, + version, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + null, + "1", + null, + null, + new byte[] {1}))) + .canonicalBytes(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Collector + implements StreamObserver { + private ReadWorldDraftTerminalOutcomeResponse value; + private Throwable error; + private boolean completed; + + @Override + public void onNext(ReadWorldDraftTerminalOutcomeResponse response) { + value = response; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The test recorder retains the original throwable for assertion.") + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidenceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidenceTest.java new file mode 100644 index 0000000000..091f18dad8 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidenceTest.java @@ -0,0 +1,42 @@ +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.Mockito.mock; + +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +class WorldDraftTopologyCommitEvidenceTest { + @Test + void graphAndResultBytesAreDefensiveAndRemainExplicitlyUnverifiedPermission() { + byte[] graph = {1, 2}; + byte[] result = {3, 4}; + DraftCommitBinding binding = mock(DraftCommitBinding.class); + WorldDesignPublicationFenceEvidence.OwnerBinding owner = + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class); + WorldDraftTopologyCommitEvidence evidence = + new WorldDraftTopologyCommitEvidence(binding, owner, graph, result); + graph[0] = 9; + result[0] = 9; + evidence.graphBytes()[0] = 8; + evidence.resultBytes()[0] = 8; + assertThat(evidence.graphBytes()).containsExactly((byte) 1, (byte) 2); + assertThat(evidence.resultBytes()).containsExactly((byte) 3, (byte) 4); + assertThat(evidence.binding()).isSameAs(binding); + assertThat(evidence.ownerBinding()).isSameAs(owner); + assertThat(evidence.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + } + + @Test + void incompleteEvidenceCannotBeReturnedAsSuccessfulComponentStorage() { + assertThatThrownBy( + () -> + new WorldDraftTopologyCommitEvidence( + mock(DraftCommitBinding.class), + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class), + new byte[0], + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java new file mode 100644 index 0000000000..830ce50acd --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java @@ -0,0 +1,870 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.function.UnaryOperator; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyCommitPlan; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.WorldGenerationSubtreeDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.junit.jupiter.api.Test; + +class WorldDraftTopologyCommitPlanTest { + private static final UUID TENANT = id(1); + private static final UUID VERSION = id(2); + private static final UUID COMMIT = id(3); + private static final UUID REGION = id(10); + private static final UUID ZONE = id(11); + private static final UUID ROOM = id(12); + private static final UUID OTHER_ROOM = id(13); + private static final UUID ENTITY = id(30); + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + void preservesCompleteMixedOwnerBindingAllFamiliesAndEveryPayloadField() { + List mutations = fresh(); + DraftCommitBinding binding = binding(mutations); + OwnerBinding owner = owner(); + var plan = WorldDraftTopologyCommitPlan.create(binding, owner); + + assertThat(plan.binding()).isSameAs(binding); + assertThat(plan.ownerBinding()).isSameAs(owner); + assertThat(plan.graph().tenantId()).isEqualTo(TENANT); + assertThat(plan.graph().versionId()).isEqualTo(VERSION); + assertThat(WorldDraftTopologyInputGraph.STATUS).isEqualTo("PURE_UNVERIFIED"); + assertThat(plan.graph().nodes()) + .extracting(WorldDraftTopologyInputGraph.Node::mutation) + .containsExactlyElementsOf(mutations); + assertThat(plan.graph().nodes()) + .extracting(WorldDraftTopologyInputGraph.Node::revisionOrder) + .containsExactly("1", "2", "3", "4", "5", "6", "7"); + assertThat(plan.graph().family(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM)) + .hasSize(2); + assertThat(plan.graph().nodes().getFirst().mutation().getRegion().getSpacingMultiplier()) + .isZero(); + var reference = plan.graph().nodes().getLast().entityReference(); + assertThat(reference.kind()) + .isEqualTo(EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC); + assertThat(reference.tenantId()).isEqualTo(TENANT); + assertThat(reference.versionId()).isEqualTo(VERSION); + assertThat(reference.templateId()).isEqualTo(ENTITY); + assertThat(plan.binding().baseCommitId()).isEqualTo("reviewed-base"); + assertThat(plan.binding().revisions().getFirst().payload()) + .isEqualTo("other-owner-byte-string"); + assertThatThrownBy(() -> plan.graph().nodes().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + plan.graph() + .family(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void acceptsOutOfParentOrderWithoutChangingCanonicalRevisionOrder() { + List mutations = fresh(); + List reversed = new ArrayList<>(mutations.reversed()); + var plan = WorldDraftTopologyCommitPlan.create(binding(reversed), owner()); + assertThat(plan.graph().nodes()) + .extracting(WorldDraftTopologyInputGraph.Node::mutation) + .containsExactlyElementsOf(reversed); + } + + @Test + void preservesZeroExitCostAndSpawnCountForTheExistingOwnerDefaults() { + var mutations = fresh(); + mutations.set( + 4, + mutations.get(4).toBuilder() + .setRoomExit(mutations.get(4).getRoomExit().toBuilder().setCost(0)) + .build()); + mutations.set( + 6, + mutations.get(6).toBuilder() + .setWorldEntitySpawnBinding( + mutations.get(6).getWorldEntitySpawnBinding().toBuilder().setSpawnCount(0)) + .build()); + var original = binding(mutations); + var plan = WorldDraftTopologyCommitPlan.create(original, owner()); + assertThat(plan.binding()).isSameAs(original); + assertThat(plan.graph().nodes().get(4).mutation().getRoomExit().getCost()).isZero(); + assertThat(plan.graph().nodes().get(6).mutation().getWorldEntitySpawnBinding().getSpawnCount()) + .isZero(); + assertThat(plan.graph().nodes()) + .extracting(WorldDraftTopologyInputGraph.Node::mutation) + .containsExactlyElementsOf(mutations); + assertThat(plan.binding().canonicalBytes()).isEqualTo(original.canonicalBytes()); + } + + @Test + void completeDeclarationPreservesTypedStartRoomAndExplicitZeroOptionalFamilies() { + List mutations = new ArrayList<>(fresh().subList(0, 3)); + var plan = WorldDraftTopologyCommitPlan.create(binding(mutations), owner()); + var declaration = plan.graph().freshGraphDeclaration().orElseThrow(); + + assertThat(declaration.tenantId()).isEqualTo(TENANT); + assertThat(declaration.versionId()).isEqualTo(VERSION); + assertThat(declaration.startLocation()) + .isEqualTo(new net.firedevops.firemud.common.world.RoomTemplateRef(TENANT, VERSION, ROOM)); + assertThat(declaration.familyCounts()) + .extracting(WorldDraftTopologyInputGraph.FamilyCount::count) + .containsExactly(1, 1, 1, 0, 0, 0); + assertThat(plan.graph().nodes()) + .extracting(node -> node.mutation().getAggregateType()) + .containsExactly( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM); + } + + @Test + void rejectsAbsentZeroCountDuplicateDeclarationAndChangedSelectorIdentity() { + List mutations = new ArrayList<>(fresh().subList(0, 3)); + DraftCommitBinding binding = binding(mutations); + rejected( + changeDeclaration( + binding, + declaration -> + declaration.setFamilyCounts( + 3, declaration.getFamilyCounts(3).toBuilder().clearCount().build()))); + rejected( + changeDeclaration( + binding, + declaration -> + declaration.setFamilyCounts( + 0, declaration.getFamilyCounts(0).toBuilder().setCount(2).build()))); + rejected( + changeDeclaration( + binding, + declaration -> { + var first = declaration.getFamilyCounts(0); + var second = declaration.getFamilyCounts(1); + return declaration.setFamilyCounts(0, second).setFamilyCounts(1, first); + })); + rejected(changeDeclaration(binding, declaration -> declaration.setTenantId(id(99).toString()))); + rejected( + changeDeclaration( + binding, + declaration -> + declaration.setStartLocation( + declaration.getStartLocation().toBuilder().setVersionId(id(99).toString())))); + rejected( + changeDeclaration( + binding, + declaration -> + declaration.setStartLocation( + declaration.getStartLocation().toBuilder().setTenantId(id(99).toString())))); + rejected(changeDeclaration(binding, WorldFreshGraphDeclaration.Builder::clearStartLocation)); + rejected( + changeDeclaration( + binding, + declaration -> + declaration.setStartLocation( + declaration.getStartLocation().toBuilder() + .setRoomTemplateId(id(99).toString())))); + rejected( + changeDeclaration( + binding, + declaration -> + declaration.setStartLocation( + declaration.getStartLocation().toBuilder() + .setRoomTemplateId(ZONE.toString())))); + rejected( + changeDeclaration( + binding, + declaration -> + declaration.setStartLocation( + declaration.getStartLocation().toBuilder() + .setRoomTemplateId("00000000-0000-0000-0000-000000000000")))); + + List duplicate = new ArrayList<>(binding.revisions()); + var roomRevision = duplicate.get(3); + try { + var roomMutation = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(roomRevision.payload(), roomMutation); + duplicate.set( + 3, + new DraftCommitBinding.RevisionPayload( + roomRevision.revisionOrder(), + roomRevision.revisionId(), + roomRevision.owner(), + JsonFormat.printer() + .print( + roomMutation.setFreshGraphDeclaration(bindingDeclaration(binding)).build()))); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException(exception); + } + rejected(copy(binding, duplicate)); + } + + @Test + void validatesZoneSubtreeAcrossAllDependentFamiliesAndDeniesNoWorldInput() { + var mutations = fresh(); + for (int index = 1; index < mutations.size(); index++) { + mutations.set( + index, + mutations.get(index).toBuilder() + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE) + .setScopeId(ZONE.toString()) + .build()); + } + var graph = WorldDraftTopologyCommitPlan.create(binding(mutations), owner()).graph(); + assertThat(graph.nodes().subList(1, graph.nodes().size())) + .extracting(WorldDraftTopologyInputGraph.Node::scopeId) + .containsOnly(ZONE); + rejected(binding(List.of())); + } + + @Test + void sameUuidInDifferentFamiliesResolvesOnlyThroughItsTypedParentReference() { + var mutations = fresh(); + mutations.set(1, mutations.get(1).toBuilder().setAggregateId(REGION.toString()).build()); + for (int index : List.of(2, 3)) { + mutations.set( + index, + mutations.get(index).toBuilder() + .setRoom(mutations.get(index).getRoom().toBuilder().setZoneId(REGION.toString())) + .build()); + } + var graph = WorldDraftTopologyCommitPlan.create(binding(mutations), owner()).graph(); + assertThat( + graph + .family(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .getFirst() + .templateId()) + .isEqualTo(REGION); + assertThat( + graph + .family(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .getFirst() + .templateId()) + .isEqualTo(REGION); + mutations.remove(1); + // The remaining REGION with that UUID cannot satisfy a typed ZONE parent reference. + rejected(binding(mutations)); + } + + @Test + void rejectsMissingAdditionalOrChangedDerivedScopeTuple() { + var mutations = fresh(); + List units = units(mutations); + units.removeLast(); + rejected(binding(mutations, units)); + units = units(mutations); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, "ROOM", ROOM.toString(), "ZONE_SUBTREE", ZONE.toString(), "0")); + rejected(binding(mutations, units)); + units = units(mutations); + AffectedUnit prior = units.get(1); + units.set( + 1, + new AffectedUnit( + prior.owner(), + prior.aggregateType(), + prior.aggregateId(), + prior.scopeType(), + prior.scopeId(), + "1")); + rejected(binding(mutations, units)); + } + + @Test + void rejectsEveryNumericNilUppercaseShortenedAndWhitespaceReference() { + for (String bad : + List.of( + "12", + "00000000-0000-0000-0000-000000000000", + "ABCDEFAB-0000-4000-8000-000000000001", + "1-0-4000-8000-1")) { + rejected(change(2, b -> b.setAggregateId(bad))); + rejected(change(1, b -> b.setScopeId(bad))); + rejected(change(1, b -> b.setZone(b.getZone().toBuilder().setRegionId(bad)))); + rejected(change(2, b -> b.setRoom(b.getRoom().toBuilder().setZoneId(bad)))); + rejected(change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setFromRoomId(bad)))); + rejected(change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setToRoomId(bad)))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder().setRoomId(bad)))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder().setEntityTemplateId(bad)))); + } + assertThatIllegalArgumentException() + .isThrownBy(() -> change(2, b -> b.setAggregateId(" " + ROOM))); + } + + @Test + void rejectsMissingAndWrongFamilyParentsOrScopeInsteadOfGuessingExistingRows() { + rejected(change(1, b -> b.setZone(b.getZone().toBuilder().setRegionId(id(99).toString())))); + rejected(change(2, b -> b.setRoom(b.getRoom().toBuilder().setZoneId(REGION.toString())))); + rejected( + change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setToRoomId(id(99).toString())))); + rejected(change(5, b -> b.setScopeId(ROOM.toString()))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder().setRoomId(id(99).toString())))); + List mutations = fresh(); + mutations.removeFirst(); + rejected(binding(mutations)); + } + + @Test + void requiresBothExitEndpointsWithinDeclaredZoneButSupportsTheirCommonRegion() { + List mutations = fresh(); + UUID secondZone = id(40); + mutations.add( + base(40, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("Other zone") + .setRegionId(REGION.toString())) + .build()); + mutations.set( + 3, + mutations.get(3).toBuilder() + .setRoom(mutations.get(3).getRoom().toBuilder().setZoneId(secondZone.toString())) + .build()); + assertThat(WorldDraftTopologyCommitPlan.create(binding(mutations), owner()).graph().nodes()) + .hasSize(8); + mutations.set( + 4, + mutations.get(4).toBuilder() + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE) + .setScopeId(ZONE.toString()) + .build()); + rejected(binding(mutations)); + } + + @Test + void rejectsCrossRegionExitAndMismatchedAncestry() { + List mutations = fresh(); + UUID otherRegion = id(41); + UUID otherZone = id(42); + mutations.add( + base(41, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setScopeId(otherRegion.toString()) + .setRegion(RegionDesignMutation.newBuilder().setName("South")) + .build()); + mutations.add( + base(42, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setScopeId(otherRegion.toString()) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("South zone") + .setRegionId(otherRegion.toString())) + .build()); + mutations.set( + 3, + mutations.get(3).toBuilder() + .setScopeId(otherRegion.toString()) + .setRoom(mutations.get(3).getRoom().toBuilder().setZoneId(otherZone.toString())) + .build()); + rejected(binding(mutations)); + rejected( + change( + 0, + b -> + b.setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE) + .setScopeId(ZONE.toString()))); + rejected( + change( + 1, + b -> + b.setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE) + .setScopeId(ROOM.toString()))); + } + + @Test + void rejectsDuplicateIdsRuleKeysSpawnKeysAndExitDirections() { + List mutations = fresh(); + mutations.add(mutations.get(2).toBuilder().setLogicalRevisionId(id(500).toString()).build()); + rejected(binding(mutations)); + for (int index : List.of(4, 5, 6)) { + mutations = fresh(); + mutations.add( + mutations.get(index).toBuilder() + .setAggregateId(id(60 + index).toString()) + .setLogicalRevisionId(id(600 + index).toString()) + .build()); + rejected(binding(mutations)); + } + mutations = fresh(); + mutations.set(2, mutations.get(2).toBuilder().setAggregateId(ZONE.toString()).build()); + rejected(binding(mutations)); + } + + @Test + void rejectsUnsupportedOperationsPoliciesFamiliesAndFreshNonzeroEpochs() { + rejected( + change( + 0, + b -> + b.setOperation( + WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_DELETE))); + rejected( + change( + 0, b -> b.setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_NEW_EMPTY_REGION))); + rejected( + change( + 0, + b -> + b.setScopeMutationPolicy( + WorldDesignScopeMutationPolicy + .WORLD_DESIGN_SCOPE_MUTATION_POLICY_REPLACE_SCOPE))); + rejected(change(0, b -> b.setExpectedDraftRevisionEpoch(1))); + rejected(change(0, b -> b.setExpectedDraftScopeRevisionEpoch(Long.MAX_VALUE))); + rejected(change(0, b -> b.setExpectedDraftRevisionEpoch(-1))); + rejected( + change( + 0, + b -> + b.setAggregateType( + WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_GENERATION_SUBTREE) + .setWorldGenerationSubtree( + WorldGenerationSubtreeDesignMutation.getDefaultInstance()))); + rejected(change(0, WorldDesignMutationRevision.Builder::clearRegion)); + rejected( + change( + 0, b -> b.setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM))); + } + + @Test + void rejectsInvalidRequiredPayloadRangesAndNonfiniteValues() { + for (double value : + List.of(Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, -1.0)) { + rejected(change(0, b -> b.setRegion(b.getRegion().toBuilder().setSpacingMultiplier(value)))); + } + rejected(change(0, b -> b.setRegion(b.getRegion().toBuilder().setShardId(-1)))); + rejected(change(0, b -> b.setRegion(b.getRegion().toBuilder().setName(" ")))); + rejected(change(0, b -> b.setRegion(b.getRegion().toBuilder().setWeather("x".repeat(51))))); + rejected( + change(0, b -> b.setRegion(b.getRegion().toBuilder().setGeneratorType("x".repeat(51))))); + rejected(change(1, b -> b.setZone(b.getZone().toBuilder().setName("x".repeat(101))))); + rejected(change(2, b -> b.setRoom(b.getRoom().toBuilder().setName("")))); + rejected(change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setCost(-1)))); + rejected(change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setDirection("")))); + rejected( + change(4, b -> b.setRoomExit(b.getRoomExit().toBuilder().setDirection("x".repeat(33))))); + rejected(change(5, b -> b.setGenerationRule(b.getGenerationRule().toBuilder().setName("")))); + rejected( + change( + 5, + b -> b.setGenerationRule(b.getGenerationRule().toBuilder().setValue("x".repeat(256))))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder().setSpawnCount(-1)))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder().setRespawnDelaySeconds(-1)))); + rejected( + change( + 6, + b -> + b.setWorldEntitySpawnBinding( + b.getWorldEntitySpawnBinding().toBuilder() + .setEntityTemplateType( + EntityTemplateReferenceType + .ENTITY_TEMPLATE_REFERENCE_TYPE_UNSPECIFIED)))); + } + + @Test + void rejectsMalformedDuplicateUnknownAndTrailingJsonWithoutDroppingFields() { + for (String bad : + List.of( + "{", + "null", + "[]", + " ", + "{} {}", + "{\"commitId\":\"one\",\"commitId\":\"two\"}", + "{\"unknown\":true}")) { + var good = binding(fresh()); + var revisions = new ArrayList<>(good.revisions()); + var prior = revisions.get(1); + revisions.set( + 1, + new DraftCommitBinding.RevisionPayload( + prior.revisionOrder(), prior.revisionId(), prior.owner(), bad)); + rejected( + DraftCommitBinding.create( + good.target(), + good.requestId(), + good.commitId(), + good.baseCommitId(), + revisions, + good.affectedUnits())); + } + } + + @Test + void rejectsChangedTargetCommitRevisionAndRetainedSourceWhileKeepingOwnerEvidenceUnauthenticated() + throws InvalidProtocolBufferException { + rejected(change(0, b -> b.setCommitId(id(99).toString()))); + var good = binding(fresh()); + var changedIdentity = new ArrayList<>(good.revisions()); + var firstWorld = changedIdentity.get(1); + changedIdentity.set( + 1, + new DraftCommitBinding.RevisionPayload( + firstWorld.revisionOrder(), + firstWorld.revisionId(), + firstWorld.owner(), + JsonFormat.printer() + .print( + fresh().getFirst().toBuilder() + .setLogicalRevisionId(id(99).toString()) + .build()))); + rejected( + DraftCommitBinding.create( + good.target(), + good.requestId(), + good.commitId(), + good.baseCommitId(), + changedIdentity, + good.affectedUnits())); + var target = good.target(); + for (DraftCommitBinding.TargetProof changed : + List.of( + new DraftCommitBinding.TargetProof( + id(99), VERSION, 901, "source-key", 801, "source-key", "NEW_GAME_ROW"), + new DraftCommitBinding.TargetProof( + TENANT, id(99), 901, "source-key", 801, "source-key", "NEW_GAME_ROW"), + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 902, "source-key", 801, "source-key", "NEW_GAME_ROW"), + new DraftCommitBinding.TargetProof( + TENANT, + VERSION, + target.gameDesignVersionRowId(), + "source-key", + 801, + "source-key", + "RETAINED_GAME_V30"))) { + rejected( + DraftCommitBinding.create( + changed, + good.requestId(), + good.commitId(), + good.baseCommitId(), + good.revisions(), + good.affectedUnits())); + } + var revisions = new ArrayList<>(good.revisions()); + var prior = revisions.get(2); + revisions.set( + 2, + new DraftCommitBinding.RevisionPayload( + prior.revisionOrder(), revisions.get(1).revisionId(), prior.owner(), prior.payload())); + assertThatIllegalArgumentException() + .isThrownBy( + () -> + DraftCommitBinding.create( + good.target(), + good.requestId(), + good.commitId(), + good.baseCommitId(), + revisions, + good.affectedUnits())); + } + + private static List fresh() { + return new ArrayList<>( + List.of( + base(10, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("North") + .setWeather("snow") + .setShardId(2) + .setGenerationSeed(Long.MIN_VALUE) + .setGeneratorType("Dungeon") + .setGeneratorParams("{\"seed\":1}")) + .build(), + base(11, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("Cavern") + .setRegionId(REGION.toString())) + .build(), + base(12, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("Hall") + .setDescription("Original text") + .setZoneId(ZONE.toString()) + .setNameLocalizedVariantsJson("{\"fr\":\"Salle\"}") + .setDescriptionLocalizedVariantsJson("{\"fr\":\"Texte\"}")) + .build(), + base(13, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom(RoomDesignMutation.newBuilder().setName("Gate").setZoneId(ZONE.toString())) + .build(), + base(14, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT) + .setRoomExit( + RoomExitDesignMutation.newBuilder() + .setFromRoomId(ROOM.toString()) + .setToRoomId(OTHER_ROOM.toString()) + .setDirection("NORTH") + .setCost(2)) + .build(), + base(15, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder().setName("density").setValue("sparse")) + .build(), + base( + 16, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(ROOM.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(ENTITY.toString()) + .setSpawnCount(3) + .setRespawnDelaySeconds(90)) + .build())); + } + + private static WorldDesignMutationRevision.Builder base( + int number, WorldDesignAggregateType kind) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(COMMIT.toString()) + .setLogicalRevisionId(id(100 + number).toString()) + .setAggregateId(id(number).toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(kind) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(REGION.toString()); + } + + private static DraftCommitBinding change( + int index, UnaryOperator change) { + List mutations = fresh(); + mutations.set(index, change.apply(mutations.get(index).toBuilder()).build()); + return binding(mutations); + } + + private static DraftCommitBinding binding(List mutations) { + return binding(mutations, units(mutations)); + } + + private static DraftCommitBinding binding( + List mutations, List units) { + if (!mutations.isEmpty()) { + var first = mutations.getFirst(); + mutations.set(0, first.toBuilder().setFreshGraphDeclaration(declaration(mutations)).build()); + } + List revisions = new ArrayList<>(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", id(700), Owner.GAME_LOGIC, "other-owner-byte-string")); + for (int index = 0; index < mutations.size(); index++) { + var mutation = mutations.get(index); + UUID revision = UUID.fromString(mutation.getLogicalRevisionId()); + try { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(index + 1), + revision, + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().print(mutation))); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException(exception); + } + } + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 901, "source-key", 801, "source-key", "NEW_GAME_ROW"), + id(4), + COMMIT, + "reviewed-base", + revisions, + units); + } + + private static WorldFreshGraphDeclaration declaration( + List mutations) { + return WorldFreshGraphDeclaration.newBuilder() + .setTenantId(TENANT.toString()) + .setVersionId(VERSION.toString()) + .setStartLocation( + net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef.newBuilder() + .setTenantId(TENANT.toString()) + .setVersionId(VERSION.toString()) + .setRoomTemplateId(ROOM.toString())) + .addFamilyCounts( + count(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION)) + .addFamilyCounts( + count(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE)) + .addFamilyCounts( + count(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM)) + .addFamilyCounts( + count(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT)) + .addFamilyCounts( + count(mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE)) + .addFamilyCounts( + count( + mutations, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) + .build(); + } + + private static WorldFreshGraphFamilyCount count( + List mutations, WorldDesignAggregateType family) { + int count = + (int) mutations.stream().filter(mutation -> mutation.getAggregateType() == family).count(); + return WorldFreshGraphFamilyCount.newBuilder().setFamily(family).setCount(count).build(); + } + + private static DraftCommitBinding changeDeclaration( + DraftCommitBinding binding, UnaryOperator change) { + List revisions = new ArrayList<>(binding.revisions()); + for (int index = 0; index < revisions.size(); index++) { + var revision = revisions.get(index); + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + continue; + } + try { + var mutation = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(revision.payload(), mutation); + if (!mutation.hasFreshGraphDeclaration()) { + continue; + } + revisions.set( + index, + new DraftCommitBinding.RevisionPayload( + revision.revisionOrder(), + revision.revisionId(), + revision.owner(), + JsonFormat.printer() + .print( + mutation + .setFreshGraphDeclaration( + change + .apply(mutation.getFreshGraphDeclaration().toBuilder()) + .build()) + .build()))); + return copy(binding, revisions); + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException(exception); + } + } + throw new IllegalArgumentException("Test binding has no fresh graph declaration"); + } + + private static WorldFreshGraphDeclaration bindingDeclaration(DraftCommitBinding binding) { + for (var revision : binding.revisions()) { + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + continue; + } + try { + var mutation = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(revision.payload(), mutation); + if (mutation.hasFreshGraphDeclaration()) { + return mutation.getFreshGraphDeclaration(); + } + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException(exception); + } + } + throw new IllegalArgumentException("Test binding has no fresh graph declaration"); + } + + private static DraftCommitBinding copy( + DraftCommitBinding original, List revisions) { + return DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + revisions, + original.affectedUnits()); + } + + private static List units(List mutations) { + List units = new ArrayList<>(); + units.add(new AffectedUnit(Owner.GAME_LOGIC, "ABILITY", "other", "AGGREGATE", "other", "0")); + // Deduplicate duplicate-object inputs so the owner plan, rather than this fixture, rejects + // them. + for (var mutation : mutations) { + String type = mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + AffectedUnit aggregate = + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + type, + mutation.getAggregateId(), + "AGGREGATE", + mutation.getAggregateId(), + "0"); + AffectedUnit scope = + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + type, + mutation.getAggregateId(), + mutation.getScopeType().name().replace("WORLD_DESIGN_SCOPE_TYPE_", ""), + mutation.getScopeId(), + "0"); + if (!units.contains(aggregate)) { + units.add(aggregate); + } + if (!units.contains(scope)) { + units.add(scope); + } + } + return units; + } + + private static OwnerBinding owner() { + return new OwnerBinding( + "firemud", TENANT, VERSION, id(50), 901, id(51), id(52), DIGEST, id(53), DIGEST, DIGEST); + } + + private static void rejected(DraftCommitBinding binding) { + assertThatIllegalArgumentException() + .isThrownBy(() -> WorldDraftTopologyCommitPlan.create(binding, owner())); + } + + private static UUID id(int number) { + return UUID.fromString(String.format("%08d-0000-4000-8000-%012d", number, number)); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepositoryTest.java new file mode 100644 index 0000000000..6a3ae08531 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepositoryTest.java @@ -0,0 +1,161 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +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.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import java.sql.Connection; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.ResultQuery; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +class WorldDraftTopologyCommitRepositoryTest { + private final DSLContext dsl = mock(DSLContext.class); + private final WorldDesignPublicationFenceRepository fence = + mock(WorldDesignPublicationFenceRepository.class); + private final ObjectMapper mapper = mock(ObjectMapper.class); + private final WorldDraftTopologyCommitRepository repository = + new WorldDraftTopologyCommitRepository(dsl, fence, mapper); + private final WorldDraftTopologyCommitPlan plan = mock(WorldDraftTopologyCommitPlan.class); + + @AfterEach + void clearTransactionFixture() { + TransactionSynchronizationManager.clear(); + } + + @Test + void absentTransactionCannotResolveOrTouchHistory() { + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } + + @Test + void readOnlyTransactionCannotResolveOrTouchHistory() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } + + @Test + void repeatableReadCannotUseReadCommittedReplayAndOwnerLockOrdering() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_REPEATABLE_READ); + assertThatThrownBy(() -> repository.store(plan)) + .hasMessageContaining("writable READ COMMITTED"); + verifyNoInteractions(dsl, fence, plan); + } + + @Test + void committedReadbackRejectsActiveCallerBeforeStorageOrSourceResolution() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> repository.readCommitted(plan)) + .hasMessageContaining("no active caller transaction"); + verifyNoInteractions(dsl, fence, mapper, plan); + } + + @Test + @SuppressWarnings("unchecked") + void missingCommittedOperationIsUnknownWithoutOwnerClaimOrMutation() { + DraftCommitBinding binding = mock(DraftCommitBinding.class); + WorldDesignPublicationFenceEvidence.OwnerBinding owner = + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class); + ResultQuery query = mock(ResultQuery.class); + Result rows = mock(Result.class); + when(plan.binding()).thenReturn(binding); + when(plan.ownerBinding()).thenReturn(owner); + when(binding.requestId()).thenReturn(UUID.randomUUID()); + when(binding.commitId()).thenReturn(UUID.randomUUID()); + when(mapper.writeValueAsString(owner)).thenReturn("synthetic-owner-json"); + when(dsl.resultQuery(anyString(), any(Object[].class))).thenReturn(query); + when(query.fetch()).thenReturn(rows); + when(rows.isEmpty()).thenReturn(true); + assertThat(repository.readCommitted(plan)).isEmpty(); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(dsl).resultQuery(sql.capture(), any(Object[].class)); + assertThat(sql.getValue()) + .startsWith("SELECT ") + .doesNotContain("FOR UPDATE", "INSERT ", "UPDATE ", "DELETE "); + verify(query).fetch(); + verifyNoMoreInteractions(dsl, query); + verifyNoInteractions(fence); + } + + @Test + void typedProjectionNormalizesParsedSpellingsWithoutReadingOrReplacingRawBinding() + throws InvalidProtocolBufferException { + UUID template = UUID.randomUUID(); + UUID revision = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + var mutation = + WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revision.toString()) + .setCommitId(commit.toString()) + .setAggregateId(template.toString()) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(template.toString()) + .setRegion(RegionDesignMutation.newBuilder().setName("region")) + .build(); + String original = + JsonFormat.printer() + .preservingProtoFieldNames() + .printingEnumsAsInts() + .omittingInsignificantWhitespace() + .print(mutation); + var parsed = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(original, parsed); + var graph = + new WorldDraftTopologyInputGraph( + UUID.randomUUID(), + UUID.randomUUID(), + List.of( + new WorldDraftTopologyInputGraph.Node( + "4", revision, template, template, parsed.build(), null)), + null); + when(plan.graph()).thenReturn(graph); + var projection = repository.executionRevisions(plan); + assertThat(projection).hasSize(1); + var execution = projection.getFirst(); + assertThat(execution.revisionId()).isEqualTo(revision); + assertThat(execution.revisionOrder()).isEqualTo("4"); + assertThat(execution.owner()).isEqualTo(DraftCommitBinding.Owner.WORLD_MANAGEMENT); + assertThat(original).contains("\"aggregate_type\":"); + assertThat(execution.payload()) + .contains("\"aggregateType\":\"WORLD_DESIGN_AGGREGATE_TYPE_REGION\"") + .isNotEqualTo(original); + var decoded = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(execution.payload(), decoded); + assertThat(decoded.build()).isEqualTo(mutation); + assertThat(decoded.getRegion().getSpacingMultiplier()).isZero(); + verifyNoInteractions(dsl, fence, mapper); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitServiceTest.java new file mode 100644 index 0000000000..ce82ebe9c5 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitServiceTest.java @@ -0,0 +1,123 @@ +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.inOrder; +import static org.mockito.Mockito.mock; +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 java.util.Optional; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldDraftTopologyCommitServiceTest { + private final WorldDraftTopologyCommitRepository repository = + mock(WorldDraftTopologyCommitRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final WorldDraftTopologyCommitService.PermissionVerifier verifier = + mock(WorldDraftTopologyCommitService.PermissionVerifier.class); + private final WorldDraftTopologyCommitPlan plan = mock(WorldDraftTopologyCommitPlan.class); + + @AfterEach + void clearTransactionFixture() { + TransactionSynchronizationManager.clear(); + } + + @Test + void defaultDenialCannotStartTransactionOrAccessOwnerStorage() { + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager); + assertThatThrownBy(() -> service.store(plan)).hasMessageContaining("permission is unavailable"); + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsCallerTransactionBeforeVerifierCouldMakeAnExternalCall() { + TransactionSynchronizationManager.setActualTransactionActive(true); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.store(plan)).hasMessageContaining("existing transaction"); + verifyNoInteractions(verifier, repository, manager); + } + + @Test + void syntheticVerifierPrecedesDedicatedWritableReadCommittedTransactionAndCommit() { + // This sequencing fixture is not authenticated Account ordering or fence release proof. + TransactionStatus status = mock(TransactionStatus.class); + WorldDraftTopologyCommitEvidence evidence = mock(WorldDraftTopologyCommitEvidence.class); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.store(plan)).thenReturn(evidence); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager, verifier); + assertThat(service.store(plan)).isSameAs(evidence); + ArgumentCaptor definition = + ArgumentCaptor.forClass(TransactionDefinition.class); + InOrder order = inOrder(verifier, manager, repository); + order.verify(verifier).verify(plan); + order.verify(manager).getTransaction(definition.capture()); + order.verify(repository).store(plan); + order.verify(manager).commit(status); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().isReadOnly()).isFalse(); + } + + @Test + void localFailureRollsBackWithoutReturningStorageEvidence() { + TransactionStatus status = mock(TransactionStatus.class); + when(manager.getTransaction(any())).thenReturn(status); + when(repository.store(plan)).thenThrow(new IllegalStateException("late tuple conflict")); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.store(plan)).hasMessage("late tuple conflict"); + InOrder order = inOrder(manager, repository); + order.verify(manager).getTransaction(any()); + order.verify(repository).store(plan); + order.verify(manager).rollback(status); + } + + @Test + void committedReadbackReturnsOriginalEvidenceWithoutVerifierOrTransactionInteractions() { + WorldDraftTopologyCommitEvidence evidence = mock(WorldDraftTopologyCommitEvidence.class); + when(repository.readCommitted(plan)).thenReturn(Optional.of(evidence)); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager, verifier); + assertThat(service.readCommitted(plan)).containsSame(evidence); + verify(repository).readCommitted(plan); + verifyNoMoreInteractions(repository); + verifyNoInteractions(verifier, manager); + } + + @Test + void missingCommittedReadbackRemainsUnknownWithoutAttemptingDeniedWriter() { + when(repository.readCommitted(plan)).thenReturn(Optional.empty()); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager); + assertThat(service.readCommitted(plan)).isEmpty(); + verify(repository).readCommitted(plan); + verifyNoMoreInteractions(repository); + verifyNoInteractions(verifier, manager); + } + + @Test + void committedReadbackRejectsActiveCallerBeforeAnyCollaboratorInteraction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + WorldDraftTopologyCommitService service = + new WorldDraftTopologyCommitService(repository, manager, verifier); + assertThatThrownBy(() -> service.readCommitted(plan)) + .hasMessageContaining("no active caller transaction"); + verifyNoInteractions(repository, verifier, manager, plan); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalServiceTest.java new file mode 100644 index 0000000000..bccd2c31bf --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalServiceTest.java @@ -0,0 +1,22 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalService; +import org.junit.jupiter.api.Test; + +class WorldPublicationTerminalServiceTest { + @Test + void productionDefaultDeniesOpaqueEvidenceBeforeDecodeOrOwnerStorage() { + var repository = mock(WorldPublicationTerminalRepository.class); + var service = new WorldPublicationTerminalService(repository); + + assertThatThrownBy(() -> service.complete(new byte[0], new byte[0])) + .isInstanceOf(WorldPublicationTerminalService.TerminalDeniedException.class) + .hasMessageContaining("no authenticated exact Game Design producer verifier"); + verifyNoInteractions(repository); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSourceSnapshotReadTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSourceSnapshotReadTest.java new file mode 100644 index 0000000000..27e7414f2a --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSourceSnapshotReadTest.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +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.when; + +import java.sql.Connection; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +class WorldPublishedSourceSnapshotReadTest { + private final DSLContext dsl = mock(DSLContext.class); + private final WorldCanonicalFrozenTopologyRepository frozen = + new WorldCanonicalFrozenTopologyRepository( + dsl, + mock(WorldAuthoredGraphSnapshotRepository.class), + mock(WorldDraftTopologyCommitRepository.class), + mock(net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.class)); + private final WorldDraftGraphApplicationRepository applications = + new WorldDraftGraphApplicationRepository( + dsl, mock(WorldDesignPublicationFenceRepository.class), mock(ObjectMapper.class)); + private final WorldPublishedStartLocationRepository published = + new WorldPublishedStartLocationRepository(dsl, frozen, applications); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void allOwnedSnapshotSeamsRejectMissingTransaction() { + assertThatThrownBy(() -> frozen.readInOwnedSnapshot(null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> applications.readInOwnedSnapshot("test", new byte[0])) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> published.readInOwnedSnapshot(null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + } + + @Test + void allOwnedSnapshotSeamsRejectWritableTransactions() { + setTransaction(false, Connection.TRANSACTION_REPEATABLE_READ); + assertSnapshotSeamsReject(); + } + + @Test + void allOwnedSnapshotSeamsRejectWrongTransactionIsolation() { + setTransaction(true, Connection.TRANSACTION_READ_COMMITTED); + assertSnapshotSeamsReject(); + } + + @Test + void allOwnedSnapshotSeamsRejectWrongActualJdbcIsolation() { + setTransaction(true, Connection.TRANSACTION_REPEATABLE_READ); + when(dsl.connectionResult(any())).thenReturn(Connection.TRANSACTION_READ_COMMITTED); + assertSnapshotSeamsReject(); + } + + @Test + void existingCommittedApisContinueRejectingAmbientTransactions() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> frozen.readCommitted((WorldAuthoredGraphSnapshot.CaptureRequest) null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> applications.readCommitted("test", new byte[0])) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> published.readCommitted(null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + } + + private void assertSnapshotSeamsReject() { + assertThatThrownBy(() -> frozen.readInOwnedSnapshot(null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> applications.readInOwnedSnapshot("test", new byte[0])) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + assertThatThrownBy(() -> published.readInOwnedSnapshot(null)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + } + + private static void setTransaction(boolean readOnly, int isolation) { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(isolation); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcServiceTest.java new file mode 100644 index 0000000000..31dd458ef4 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadGrpcServiceTest.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsResponse; +import org.junit.jupiter.api.Test; + +class WorldPublishedSpawnRequirementsReadGrpcServiceTest { + @Test + void mapsOwnerFailureToBoundedStatusWithoutReturningInternalDetails() { + var owner = mock(WorldPublishedSpawnRequirementsReadOwner.class); + when(owner.read(any())) + .thenThrow( + new WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException( + Status.Code.FAILED_PRECONDITION, "secret database row detail")); + var service = new WorldPublishedSpawnRequirementsReadGrpcService(owner); + var observer = new Collector(); + + service.readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest.newBuilder().build(), observer); + + assertThat(observer.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.description) + .isEqualTo("Published World source evidence is incomplete or inconsistent"); + assertThat(observer.description).doesNotContain("secret database row detail"); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + + @Test + void unexpectedOwnerFailureReturnsRedactedInternalAndNeverMasksObserverDelivery() { + var owner = mock(WorldPublishedSpawnRequirementsReadOwner.class); + when(owner.read(any())).thenThrow(new IllegalStateException("private exception detail")); + var service = new WorldPublishedSpawnRequirementsReadGrpcService(owner); + var observer = new Collector(); + + service.readWorldPublishedSpawnRequirements( + ReadWorldPublishedSpawnRequirementsRequest.newBuilder().build(), observer); + + assertThat(observer.error).isEqualTo(Status.Code.INTERNAL); + assertThat(observer.description).isEqualTo("Published World source read failed"); + assertThat(observer.description).doesNotContain("private exception detail"); + } + + private static final class Collector + implements StreamObserver { + private ReadWorldPublishedSpawnRequirementsResponse value; + private Status.Code error; + private String description; + private boolean completed; + + @Override + public void onNext(ReadWorldPublishedSpawnRequirementsResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + description = Status.fromThrowable(failure).getDescription(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java new file mode 100644 index 0000000000..9accb19a81 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java @@ -0,0 +1,476 @@ +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.EntityTemplateReference; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.FamilyCount; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.GenerationRequirement; +import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence.SpawnRequirement; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Template; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.GenerationRuleIntent; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.SourceRow; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan.SpawnBindingIntent; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.FreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedSpawnRequirementsRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldPublishedSpawnRequirementsReadOwnerTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_ID = uuid(1); + private static final UUID TENANT = uuid(2); + private static final UUID VERSION = uuid(3); + private final AuthoredWorldLaunchDescriptorClient gameDesign = + mock(AuthoredWorldLaunchDescriptorClient.class); + private final WorldPublishedStartLocationRepository published = + mock(WorldPublishedStartLocationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + + @AfterEach + void clearThreadState() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void rejectsWrongPeerAndEndUserBeforeRequestDecodingOrOwnerAccess() { + var malformed = + ReadWorldPublishedSpawnRequirementsRequest.newBuilder().setSchemaVersion(-1).build(); + for (GrpcPeerIdentity identity : + List.of( + peer("game-design-service", NAMESPACE), peer("entity-management-service", "other"))) { + try (var ignored = attach(identity)) { + assertThatThrownBy(() -> owner().read(malformed)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) + failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + } + SessionContext.setContext(TENANT.toString(), List.of(), java.util.Map.of()); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(malformed)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + verifyNoInteractions(gameDesign, published, transactions); + } + + @Test + void ambientTransactionIsRejectedBeforeDecodingOrGameDesignRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy( + () -> + owner() + .read( + ReadWorldPublishedSpawnRequirementsRequest.newBuilder() + .setSchemaVersion(-1) + .build())) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + verifyNoInteractions(gameDesign, published, transactions); + } + + @Test + void requestNamespaceMustMatchConfiguredOwnerBeforeGameDesignRead() { + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wireRequest("other"))) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + verifyNoInteractions(gameDesign, published, transactions); + } + + @Test + void unavailableGameDesignReadNeverOpensWorldSnapshot() { + var wire = wireRequest(NAMESPACE); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + var owner = owner(); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner.read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.UNAVAILABLE)); + } + verify(gameDesign).getComplete(any(GetLaunchDescriptorRequest.class)); + verifyNoInteractions(published, transactions); + } + + @Test + void changedReleaseAttestationDigestFailsBeforeWorldRead() { + var wire = wireRequest(NAMESPACE); + var pair = mock(CompleteLaunchBindingEvidence.class); + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(pair); + when(pair.descriptor()).thenReturn(descriptor); + when(pair.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.evidenceDigest()).thenReturn("sha256:" + "f".repeat(64)); + when(release.schemaVersion()) + .thenReturn(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + when(release.worldStartLocationEvidence()) + .thenReturn(mock(WorldPublishedStartLocationEvidence.class)); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + verifyNoInteractions(published, transactions); + } + + @Test + void malformedFrozenSourceFailsClosedAfterTheOwnedRead() { + var wire = wireRequest(NAMESPACE); + var selector = mock(WorldPublishedStartLocationEvidence.class); + when(selector.request()).thenReturn(selectorRequest()); + var pair = mock(CompleteLaunchBindingEvidence.class); + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + when(gameDesign.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(pair); + when(pair.descriptor()).thenReturn(descriptor); + when(pair.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.evidenceDigest()).thenReturn(wire.getExpectedReleaseAttestationDigest()); + when(release.schemaVersion()) + .thenReturn(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + when(release.worldStartLocationEvidence()).thenReturn(selector); + + var source = mock(WorldPublishedStartLocationSource.class); + var frozen = mock(WorldCanonicalFrozenTopology.class); + when(source.frozenTopology()).thenReturn(frozen); + when(frozen.status()).thenReturn("CHANGED"); + when(published.readInOwnedSnapshot(any())).thenReturn(Optional.of(source)); + try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { + assertThatThrownBy(() -> owner().read(wire)) + .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) + .satisfies( + failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + verify(published).readInOwnedSnapshot(any()); + } + + @Test + void projectsOriginalIntentFieldsAndExplicitFamilyCountsInRevisionOrder() { + UUID spawnRevision = uuid(20); + UUID generationRevision = uuid(21); + UUID secondSpawnRevision = uuid(22); + UUID spawnId = uuid(30); + UUID ruleId = uuid(31); + UUID secondSpawnId = uuid(32); + UUID roomId = uuid(40); + UUID entityId = uuid(41); + UUID secondRoomId = uuid(42); + UUID secondEntityId = uuid(43); + var spawnMutation = + base( + spawnRevision, + spawnId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE, + uuid(50)) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(roomId.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC) + .setEntityTemplateId(entityId.toString()) + .setSpawnCount(0) + .setRespawnDelaySeconds(77)) + .build(); + var generationMutation = + base( + generationRevision, + ruleId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE, + uuid(51)) + .setGenerationRule( + GenerationRuleDesignMutation.newBuilder() + .setName("authored-name") + .setValue("unchanged-value")) + .build(); + var secondSpawnMutation = + base( + secondSpawnRevision, + secondSpawnId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_ZONE_SUBTREE, + uuid(52)) + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(secondRoomId.toString()) + .setEntityTemplateType( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM) + .setEntityTemplateId(secondEntityId.toString()) + .setSpawnCount(4) + .setRespawnDelaySeconds(9)) + .build(); + var entityRef = + new WorldDraftTopologyInputGraph.EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC, + TENANT, + VERSION, + entityId); + var spawn = + new SpawnBindingIntent( + source(Family.WORLD_ENTITY_SPAWN_BINDING, spawnId, spawnMutation), + new Template(Family.ROOM, roomId), + new WorldDraftTopologyInputGraph.EntityTemplateReference( + entityRef.kind(), + entityRef.tenantId(), + entityRef.versionId(), + entityRef.templateId()), + spawnMutation.getWorldEntitySpawnBinding()); + var generation = + new GenerationRuleIntent( + source(Family.GENERATION_RULE, ruleId, generationMutation), + new Template(Family.ZONE, uuid(51)), + generationMutation.getGenerationRule()); + var secondSpawn = + new SpawnBindingIntent( + source(Family.WORLD_ENTITY_SPAWN_BINDING, secondSpawnId, secondSpawnMutation), + new Template(Family.ROOM, secondRoomId), + new WorldDraftTopologyInputGraph.EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + TENANT, + VERSION, + secondEntityId), + secondSpawnMutation.getWorldEntitySpawnBinding()); + var topology = mock(WorldCanonicalInstanceTopologyPlan.class); + when(topology.spawnBindings()).thenReturn(List.of(spawn, secondSpawn)); + when(topology.generationRules()).thenReturn(List.of(generation)); + when(topology.tenantId()).thenReturn(TENANT); + when(topology.versionId()).thenReturn(VERSION); + var declaration = + new FreshGraphDeclaration( + TENANT, + VERSION, + new RoomTemplateRef(TENANT, VERSION, roomId), + List.of( + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, 0), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, 1), + new WorldDraftTopologyInputGraph.FamilyCount( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING, + 2))); + var graph = + new WorldDraftTopologyInputGraph( + TENANT, + VERSION, + List.of( + new Node("0", spawnRevision, spawnId, uuid(50), spawnMutation, entityRef), + new Node("1", generationRevision, ruleId, uuid(51), generationMutation, null), + new Node( + "2", + secondSpawnRevision, + secondSpawnId, + uuid(52), + secondSpawnMutation, + new WorldDraftTopologyInputGraph.EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + TENANT, + VERSION, + secondEntityId))), + declaration); + + var projection = WorldPublishedSpawnRequirementsReadOwner.projectRequirements(graph, topology); + + assertThat(projection.familyCounts()) + .extracting(FamilyCount::count) + .containsExactly(0, 0, 0, 0, 1, 2); + assertThat(projection.spawnRequirements()) + .containsExactly( + new SpawnRequirement( + "0", + spawnRevision, + spawnId, + new RoomTemplateRef(TENANT, VERSION, roomId), + new EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC, + TENANT, + VERSION, + entityId), + 0, + 77), + new SpawnRequirement( + "2", + secondSpawnRevision, + secondSpawnId, + new RoomTemplateRef(TENANT, VERSION, secondRoomId), + new EntityTemplateReference( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + TENANT, + VERSION, + secondEntityId), + 4, + 9)); + assertThat(projection.generationRequirements()) + .containsExactly( + new GenerationRequirement( + "1", + generationRevision, + ruleId, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + uuid(51), + "authored-name", + "unchanged-value")); + } + + private WorldPublishedSpawnRequirementsReadOwner owner() { + return new WorldPublishedSpawnRequirementsReadOwner( + NAMESPACE, gameDesign, published, transactions); + } + + private static ReadWorldPublishedSpawnRequirementsRequest wireRequest(String namespace) { + var binding = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_ID.toString()) + .setCanonicalTenantId(TENANT.toString()) + .setWorldSlug("world") + .setControlPlaneRequestId("control-plane-request") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .build(); + return ReadWorldPublishedSpawnRequirementsRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(namespace) + .setReadRequestId(READ_ID.toString()) + .setLaunchBindingRequest(binding) + .setExpectedReleaseAttestationDigest("sha256:" + "c".repeat(64)) + .build(); + } + + private static WorldPublishedStartLocationEvidence.Request selectorRequest() { + return new WorldPublishedStartLocationEvidence.Request( + NAMESPACE, + TENANT, + VERSION, + uuid(4), + uuid(5), + "publication", + "d".repeat(64), + 6, + "workflow", + uuid(6).toString(), + "e".repeat(64), + 3, + List.of()); + } + + private static WorldDesignMutationRevision.Builder base( + UUID revision, + UUID aggregateId, + WorldDesignAggregateType aggregate, + WorldDesignScopeType scopeType, + UUID scopeId) { + return WorldDesignMutationRevision.newBuilder() + .setLogicalRevisionId(revision.toString()) + .setCommitId(uuid(7).toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(aggregate) + .setAggregateId(aggregateId.toString()) + .setScopeType(scopeType) + .setScopeId(scopeId.toString()); + } + + private static SourceRow source(Family family, UUID id, WorldDesignMutationRevision revision) { + return new SourceRow(new Template(family, id), revision, revision, "original-payload"); + } + + private static UUID uuid(int value) { + return UUID.fromString("00000000-0000-4000-8000-%012d".formatted(value)); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static ContextScope attach(GrpcPeerIdentity peer) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + return new ContextScope(context.attach()); + } + + private record ContextScope(Context previous) implements AutoCloseable { + @Override + public void close() { + Context.current().detach(previous); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcServiceTest.java new file mode 100644 index 0000000000..3369c919d2 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcServiceTest.java @@ -0,0 +1,159 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublishedStartLocationReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublishedStartLocationRepository; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import org.junit.jupiter.api.Test; + +class WorldPublishedStartLocationReadGrpcServiceTest { + @Test + void rejectsMissingOrSubstitutedPeerBeforeDecodingOrStorageAccess() { + var repository = mock(WorldPublishedStartLocationRepository.class); + var service = new WorldPublishedStartLocationReadGrpcService(repository, "test"); + var malformed = + ReadWorldPublishedStartLocationRequest.newBuilder().setSchemaVersion(-1).build(); + + Collector missing = new Collector(); + service.readWorldPublishedStartLocation(malformed, missing); + assertThat(missing.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + Collector wrongService = new Collector(); + Context context = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("account-service", "test")); + Context previous = context.attach(); + try { + service.readWorldPublishedStartLocation(malformed, wrongService); + } finally { + context.detach(previous); + } + assertThat(wrongService.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsAuthenticatedEndUserContextEvenWithCorrectWorkloadPeerBeforeDecoding() { + var repository = mock(WorldPublishedStartLocationRepository.class); + var service = new WorldPublishedStartLocationReadGrpcService(repository, "test"); + Collector response = new Collector(); + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Context context = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("game-design-service", "test")); + Context previous = context.attach(); + try { + service.readWorldPublishedStartLocation( + ReadWorldPublishedStartLocationRequest.newBuilder().setSchemaVersion(-1).build(), + response); + } finally { + context.detach(previous); + SessionContext.clear(); + } + assertThat(response.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void wrongNamespaceIsDeniedBeforeOwnerRead() { + var repository = mock(WorldPublishedStartLocationRepository.class); + var service = new WorldPublishedStartLocationReadGrpcService(repository, "test"); + Collector result = callAsGameDesign(service, request("other")); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void missingSelectionAndConflictingSelectionFailClosed() { + var repository = mock(WorldPublishedStartLocationRepository.class); + var service = new WorldPublishedStartLocationReadGrpcService(repository, "test"); + var request = request("test"); + when(repository.readCommitted(any())) + .thenReturn(Optional.empty()) + .thenThrow(new ConflictException("changed frozen selection")); + + Collector missing = callAsGameDesign(service, request); + assertThat(missing.error).isEqualTo(Status.Code.NOT_FOUND); + Collector changed = callAsGameDesign(service, request); + assertThat(changed.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verify(repository, org.mockito.Mockito.times(2)).readCommitted(any()); + } + + private static Collector callAsGameDesign( + WorldPublishedStartLocationReadGrpcService service, + ReadWorldPublishedStartLocationRequest request) { + Collector response = new Collector(); + Context context = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("game-design-service", "test")); + Context previous = context.attach(); + try { + service.readWorldPublishedStartLocation(request, response); + } finally { + context.detach(previous); + } + return response; + } + + private static ReadWorldPublishedStartLocationRequest request(String namespace) { + return ReadWorldPublishedStartLocationRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(namespace) + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .setCanonicalVersionId("22222222-2222-4222-8222-222222222222") + .setIntakeRequestId("33333333-3333-4333-8333-333333333333") + .setPublicationFence("44444444-4444-4444-8444-444444444444") + .setPublicationRequestId("publication-request") + .setRequestDigest("a".repeat(64)) + .setVersionStateEpoch(5L) + .setPublishWorkflowId("publish-workflow") + .setAppliedCommitId("55555555-5555-4555-8555-555555555555") + .setContentDigest("b".repeat(64)) + .setDigestSchemaVersion(3) + .build(); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static final class Collector + implements StreamObserver { + private ReadWorldPublishedStartLocationResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadWorldPublishedStartLocationResponse next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + assertThat(value).isNull(); + assertThat(completed).isFalse(); + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadServiceTest.java new file mode 100644 index 0000000000..cca42a44e3 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldSynchronizedDraftTopologyReadServiceTest.java @@ -0,0 +1,149 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityClient; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class WorldSynchronizedDraftTopologyReadServiceTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID READ_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + + @Test + void propagatesWorldDenialWhenAppliedOutputCannotBeBoundToGraph() { + DraftSynchronizedVisibilityClient client = mock(DraftSynchronizedVisibilityClient.class); + WorldDraftTopologyCommitRepository repository = mock(WorldDraftTopologyCommitRepository.class); + var request = request(READ_ID); + var evidence = evidence(request); + when(client.read(request)).thenReturn(evidence); + when(repository.readSynchronized(evidence)) + .thenThrow( + new WorldDesignPublicationFenceRepository.ConflictException( + "World synchronized graph selection has no canonical World APPLIED-result carrier " + + "bound to the retained graph")); + + assertThatThrownBy( + () -> new WorldSynchronizedDraftTopologyReadService(client, repository).read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no canonical World APPLIED-result carrier"); + verify(repository).readSynchronized(evidence); + } + + @Test + void deniesChangedReadEchoAndUnavailableVisibilityBeforeLocalGraphLookup() { + DraftSynchronizedVisibilityClient client = mock(DraftSynchronizedVisibilityClient.class); + WorldDraftTopologyCommitRepository repository = mock(WorldDraftTopologyCommitRepository.class); + var request = request(READ_ID); + when(client.read(request)) + .thenReturn(evidence(request(uuid("88888888-8888-4888-8888-888888888888")))); + + assertThatThrownBy( + () -> new WorldSynchronizedDraftTopologyReadService(client, repository).read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed the exact read target"); + verifyNoInteractions(repository); + + when(client.read(request)) + .thenThrow( + Status.UNAVAILABLE.withDescription("no synchronized fence").asRuntimeException()); + assertThatThrownBy( + () -> new WorldSynchronizedDraftTopologyReadService(client, repository).read(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + verifyNoInteractions(repository); + } + + private static DraftSynchronizedVisibilityEvidence evidence( + DraftSynchronizedVisibilityEvidence.Request request) { + DraftCommitBinding binding = + DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-source-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + Map epoch = new LinkedHashMap<>(); + epoch.put("aggregateType", "WORLD_TEMPLATE"); + epoch.put("aggregateId", "world-1"); + epoch.put("scopeType", "ROOM_SCOPE"); + epoch.put("scopeId", "room-1"); + epoch.put("expectedEpoch", "0"); + epoch.put("resultingEpoch", "1"); + Map owner = new LinkedHashMap<>(); + owner.put("owner", "WORLD_MANAGEMENT"); + owner.put("status", "APPLIED"); + owner.put("commitId", COMMIT_ID.toString()); + owner.put("bindingDigest", binding.digest()); + owner.put("resultIdentity", "world-result"); + owner.put( + "resultBytesBase64", + Base64.getEncoder().encodeToString("result".getBytes(StandardCharsets.UTF_8))); + owner.put("appliedEpochs", List.of(epoch)); + String vector = canonical(new ObjectMapper().writeValueAsString(List.of(owner))); + return new DraftSynchronizedVisibilityEvidence( + request, + binding, + "SYNCHRONIZED", + new DraftSynchronizedVisibilityEvidence.Fence( + REQUEST_ID, + COMMIT_ID, + binding.digest(), + vector, + OffsetDateTime.parse("2026-10-06T00:00:00Z"))); + } + + private static DraftSynchronizedVisibilityEvidence.Request request(UUID readId) { + return new DraftSynchronizedVisibilityEvidence.Request(1, "test", readId, target()); + } + + private static TargetProof target() { + return new TargetProof(TENANT, VERSION, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + } + + private static String canonical(String json) { + try { + return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + } catch (java.io.IOException exception) { + throw new AssertionError(exception); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts index 4894fe1e4e..c8a0d7284e 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -10,6 +10,9 @@ project(":common-data-runtime").projectDir = File("services/common-data-runtime" include("common-platform-core") project(":common-platform-core").projectDir = File("services/common-platform-core") +include("common-redis-contracts") +project(":common-redis-contracts").projectDir = File("services/common-redis-contracts") + include("common-saga") project(":common-saga").projectDir = File("services/common-saga") From 36ca4ec7d7cfb00a8496bc7c598d9614f16fab6e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:28:45 +1300 Subject: [PATCH 002/129] test: preserve denied runtime gates in imported World proof --- .../WorldCanonicalInitialAdmissionMtlsTest.java | 15 +++++---------- .../tenant/WorldDraftTopologyCommitPlanTest.java | 2 +- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java index 391426e176..bd1950559e 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java @@ -98,6 +98,9 @@ class WorldCanonicalInitialAdmissionMtlsTest { WorldCanonicalInitialAdmissionHoldTerminalServiceGrpc .getFinalizeCanonicalInitialAdmissionHoldMethod() .getFullMethodName(); + // Fixture-only opt-in lets the physical receiver reach the mock-backed workload-identity gates. + private static final Set PHYSICAL_RECEIVER_PUBLIC_METHODS = + Set.of(ACQUIRE_METHOD, IDENTITY_READ_METHOD, LIFECYCLE_READ_METHOD, TERMINAL_METHOD); private static TestPki pki; private final WorldCanonicalInitialAdmissionHoldRepository holdRepository = @@ -180,7 +183,7 @@ void startPhysicalReceiver() throws Exception { var authInterceptor = new AuthTokenInterceptor( - new JwtUtil(JWT_SECRET, 60_000L), publicMethods("application.yml")); + new JwtUtil(JWT_SECRET, 60_000L), PHYSICAL_RECEIVER_PUBLIC_METHODS); var peerInterceptor = new GrpcPeerIdentityInterceptor(); server = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) @@ -274,15 +277,7 @@ void clientWithoutCertificateCannotReachProtectedHandlerOrOwner() throws Excepti @Test void unrelatedWorldMutationMethodStillRequiresBearerAuthentication() throws Exception { assertThat(publicMethods("application.yml")) - .containsExactlyInAnyOrder( - "world_management.v1.WorldManagementService/Ping", - "world_management.v1.WorldManagementService/GetDraftDesignDigest", - "world_management.v1.WorldAuthoredSourceIntakeService/IntakeAuthoredWorldSource", - "world_management.v1.WorldAuthoredSourceIntakeService/ReadAuthoredWorldSourceIntake", - ACQUIRE_METHOD, - IDENTITY_READ_METHOD, - LIFECYCLE_READ_METHOD, - TERMINAL_METHOD); + .containsExactly("world_management.v1.WorldManagementService/Ping"); assertThat(publicMethods("application.yml")) .doesNotContain( WorldManagementServiceGrpc.getApplyWorldDesignMutationMethod().getFullMethodName()); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java index 830ce50acd..36990573da 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java @@ -580,7 +580,7 @@ TENANT, id(99), 901, "source-key", 801, "source-key", "NEW_GAME_ROW"), "source-key", 801, "source-key", - "RETAINED_GAME_V30"))) { + "RETAINED_GAME_V29"))) { rejected( DraftCommitBinding.create( changed, From d84d2a9e55c86907ad3048f82f3675b13b5fe3e6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 21:34:54 +1300 Subject: [PATCH 003/129] Compose required Account creator sources and repair construction guards --- .../world-management-service/api-contracts.md | 5 +- .../player-access-and-session.md | 2 +- services/account-service/build.gradle.kts | 1 + .../creatorparty/CreatorPartyEncoding.java | 108 ++ .../IndividualCreatorPartyRepository.java | 412 +++++++ .../IndividualCreatorPartySource.java | 52 + .../AccountTenantCreationBootstrapResult.java | 49 + .../AccountHostedTermsService.java | 1075 +++++++++++++++++ .../HostedTermsCatalogVersion.java | 144 +++ .../hostedterms/HostedTermsEncoding.java | 248 ++++ .../HostedTermsEnvironmentBinding.java | 147 +++ ...HostedTermsEnvironmentBindingEncoding.java | 87 ++ ...stedTermsEnvironmentBindingRepository.java | 418 +++++++ .../hostedterms/HostedTermsRepository.java | 547 +++++++++ .../IndividualHostedTermsAcceptance.java | 105 ++ ...eplayAdmissionCommitConfirmationOwner.java | 7 +- .../repository/AccountRepository.java | 24 + .../AccountTenantCreationBootstrapDigest.java | 251 ++++ ...tCreationBootstrapOperationRepository.java | 573 +++++++++ .../AccountTenantMembershipRepository.java | 89 ++ .../AccountCreatorMembershipSourceReader.java | 568 +++++++++ ...countMembershipAuthorityEventProducer.java | 289 +++++ ...tCreationBootstrapAuthorizationSource.java | 20 + ...AccountTenantCreationBootstrapService.java | 792 ++++++++++++ ...V94__account_tenant_creation_bootstrap.sql | 189 +++ .../V95__individual_creator_party_sources.sql | 153 +++ ...count_hosted_terms_acceptance_workflow.sql | 383 ++++++ ...count_hosted_terms_environment_binding.sql | 288 +++++ ...otstrapServicePostgresIntegrationTest.java | 832 +++++++++++++ ...alCreatorPartyPostgresIntegrationTest.java | 721 +++++++++++ ...untHostedTermsPostgresIntegrationTest.java | 722 +++++++++++ ...ronmentBindingPostgresIntegrationTest.java | 646 ++++++++++ ...rceEvidencePersistenceIntegrationTest.java | 219 ++-- ...stJoinAuthorityStorageIntegrationTest.java | 4 +- .../AccountRepositoryIntegrationTest.java | 242 ++-- ...tionRepositoryPostgresIntegrationTest.java | 469 +++++++ .../CreatorPartyEncodingTest.java | 113 ++ .../IndividualCreatorPartyRepositoryTest.java | 384 ++++++ .../AccountHostedTermsServiceTest.java | 567 +++++++++ .../HostedTermsEnvironmentBindingTest.java | 307 +++++ ...yAdmissionCommitConfirmationOwnerTest.java | 11 +- .../repository/AccountRepositoryTest.java | 62 + ...ountTenantCreationBootstrapDigestTest.java | 187 +++ ...ountCreatorMembershipSourceReaderTest.java | 116 ++ ...untTenantCreationBootstrapServiceTest.java | 138 +++ ...eMembershipAuthorityEvidenceValidator.java | 685 +++++++++++ .../tenant/FreshTenantCreatorDigest.java | 103 ++ .../tenant/FreshTenantCreatorEvidence.java | 54 + ...bershipAuthorityEvidenceValidatorTest.java | 924 ++++++++++++++ .../tenant/FreshTenantCreatorDigestTest.java | 82 ++ .../FreshTenantCreatorEvidenceTest.java | 153 +++ .../V54__immutable_command_source.sql | 2 +- .../impl/WorldManagementGrpcService.java | 265 ++-- .../impl/WorldManagementGrpcServiceTest.java | 509 +++++--- ...orldCanonicalInitialAdmissionMtlsTest.java | 82 +- 55 files changed, 15065 insertions(+), 560 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartySource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountTenantCreationBootstrapResult.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsCatalogVersion.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBinding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/IndividualHostedTermsAcceptance.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java create mode 100644 services/account-service/src/main/resources/db/migration/V94__account_tenant_creation_bootstrap.sql create mode 100644 services/account-service/src/main/resources/db/migration/V95__individual_creator_party_sources.sql create mode 100644 services/account-service/src/main/resources/db/migration/V96__account_hosted_terms_acceptance_workflow.sql create mode 100644 services/account-service/src/main/resources/db/migration/V97__account_hosted_terms_environment_binding.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncodingTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigestTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 340b01d865..8d3c6b3c98 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -7,8 +7,9 @@ This API contract is target-state canonical; implementation coverage is partial - The current World Management gameplay bridge serializes runtime room ids as `R-` and rejects scoped decimal `roomInstanceId` values such as `1021`. That storage-derived encoding is not the canonical target identity defined by the [Identifier Glossary](../../system-architecture-identifier-glossary.md). - The bridge, cross-service callers, examples, and focused proof have not migrated together to the scoped decimal `roomInstanceId` contract. The checked-in proof still exercises the legacy encoding. - The typed `ApplyRoomAmbientStatePatch` contract below is target-state: the current service has no complete handler or durable operation/digest-bound guard, so player-significant ambient mutations remain on the fenced Game Session admission/reconciliation path and are not direct table writes. -- `GetDraftDesignDigest` currently has only shared bearer parsing and no owner/method authorization or exact Game Design publication binding. The current `GetDraftDesignDigestRequest` proto carries only `tenant_id` plus a `oneof` `version_id`/`script_patch_version`; neither the proto nor handler carries or validates the target `publishRequestId`, derived workflow identity, or canonical `requestDigest`, and no wrong-workload, cross-tenant, or exact-replay proof exists. The target exact Game Design workload, tenant/scope/request/workflow/digest context and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). -- 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. +- `GetDraftDesignDigest` checks the exact Game Design workload/method boundary and validates the typed tenant/version, publication request, derived workflow identity and request digest before returning owner-matching scope. Missing authorization configuration denies the read. This read binding is not Account authoring authorization, release attestation or proof of the complete publication transaction. The canonical owner remains [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). +- The registered `ApplyWorldDesignMutation` handler fails closed before parsing or owner mutation until current Account commit authorization is verified. This denial does not implement the positive authenticated Game Design/Account commit boundary or repair the separate legacy REST generation-rule gap. +- The registered `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, `FailPreparedWorldInstance` and `TerminateWorldInstance` handlers allow only verified same-namespace Game Session workload identity before request parsing or owner calls. Missing configuration, missing peer identity and other workloads are denied; shared bearer claims do not substitute. Other pre-admission consumers are not currently allowlisted. This caller guard does not supply the remaining canonical preparation, activation, cleanup or admission proofs. - 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. ## gRPC APIs diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index d2a3e2d406..7d8fa61333 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -16,7 +16,7 @@ Internal Account-carrier typing is prepared in Game Session, while current produ Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. -Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). It is outside player-admission and session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. +Official-hosted creator-content acceptance is partial, not an enabled workflow; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). The near-front construction carries Account-owned creator bootstrap, individual-party source, hosted-terms acceptance and environment-binding storage in forward migrations V94–V97, with focused unit and PostgreSQL test definitions. The hosted-terms owners remain unregistered; new creator bootstrap remains denied without its current Account authorization/source participant. Live legal publication, trusted environment publication, current credential/source capture, participant settlement and commit-bound World authorization remain open. Source-stage PostgreSQL proof does not establish proof of this receiving composition, enable authoring, or supply player-admission/session authority. Future managed creator commerce remains outside player access and session authority; its canonical boundary is [ADR 0179](../../architecture/decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); no marketplace or purchase-entitlement implementation is present. Account runtime admission reads remain a security/proof blocker: both `GetTenantMembershipForRuntime` and `GetTenantEntitlementsForRuntime` are currently configured as public gRPC methods, and handlers accept caller-selected identifiers without exact Game Session/World Management workload or tenant binding. The target internal-workload boundary and required negative proof are canonical in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md) and the [authorization route matrix](../../architecture/system-architecture-authz-route-matrix.md). diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index d1f200b19c..88999a5ba1 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -14,6 +14,7 @@ firemudJooq { dependencies { testCompileOnly(libs.spotbugs.annotations) + add("integrationTestCompileOnly", libs.spotbugs.annotations) implementation(project(":common-redis-contracts")) implementation("com.fasterxml.jackson.core:jackson-databind") implementation(libs.spring.boot.starter.mail) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java new file mode 100644 index 0000000000..f0e3fb957b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java @@ -0,0 +1,108 @@ +package net.firedevops.firemud.accountservice.creatorparty; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import tools.jackson.databind.json.JsonMapper; + +/** Closed canonical encodings; every identity, reference and independent version is bound. */ +public final class CreatorPartyEncoding { + private CreatorPartyEncoding() {} + + public static byte[] party(IndividualCreatorPartySource source) { + Objects.requireNonNull(source); + Map fields = new LinkedHashMap<>(); + fields.put("schema", "account-individual-creator-party-source/v1"); + fields.put("creatorPartyId", source.creatorPartyId().toString()); + fields.put("accountId", source.accountId().toString()); + fields.put("verificationStatus", source.verificationStatus().name()); + fields.put("identityVersion", Long.toString(source.identityVersion())); + fields.put("policyReference", source.policyReference()); + fields.put("policyVersion", decimal(source.policyVersion())); + fields.put("verificationEvidenceReference", source.verificationEvidenceReference()); + fields.put("verificationEvidenceVersion", decimal(source.verificationEvidenceVersion())); + fields.put("sourceVersion", Long.toString(source.sourceVersion())); + return canonical(fields); + } + + public static byte[] request( + UUID requestId, FreshTenantCreatorEvidence creation, IndividualCreatorPartySource party) { + requireUuid(requestId); + Objects.requireNonNull(creation); + Objects.requireNonNull(party); + if (!creation.initiatingAccountId().equals(party.accountId())) { + throw new IllegalArgumentException("Creator must bind their own individual party"); + } + return canonical( + Map.of( + "schema", + "account-fresh-creator-party-association-request/v1", + "requestId", + requestId.toString(), + "creatorEvidence", + new String(creation(creation), StandardCharsets.UTF_8), + "individualPartySource", + new String(party(party), StandardCharsets.UTF_8))); + } + + public static byte[] result(UUID historyId, byte[] request) { + requireUuid(historyId); + Objects.requireNonNull(request); + if (request.length == 0) { + throw new IllegalArgumentException("Exact original request is required"); + } + return canonical( + Map.of( + "schema", + "account-fresh-creator-party-association-result/v1", + "historyId", + historyId.toString(), + "associationSourceVersion", + "1", + "request", + new String(request, StandardCharsets.UTF_8))); + } + + public static byte[] creation(FreshTenantCreatorEvidence evidence) { + return AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); + } + + public static String digest(byte[] bytes) { + Objects.requireNonNull(bytes); + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is required", exception); + } + } + + static void requireUuid(UUID uuid) { + if (uuid == null || uuid.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Canonical nonnil identity is required"); + } + } + + private static String decimal(Long value) { + return value == null ? null : value.toString(); + } + + private static byte[] canonical(Map fields) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(fields)); + } catch (IOException exception) { + throw new IllegalArgumentException( + "Creator-party evidence cannot be canonically encoded", exception); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java new file mode 100644 index 0000000000..c8bc8618f1 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java @@ -0,0 +1,412 @@ +package net.firedevops.firemud.accountservice.creatorparty; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered owner-local persistence prerequisite, not an authenticated association producer. + * + *

No provisioning method is provided. A future protected producer must authenticate the Account, + * independently obtain exact Game Design committed readback and approved individual verification, + * and participate in current source ordering before invoking this storage primitive. Supplied DTOs + * and a V64 receipt alone do not authenticate a caller. These immutable initial sources cannot yet + * participate in revocation/terms ordering; hosted authoring currentness remains denied. + */ +public final class IndividualCreatorPartyRepository { + private final DSLContext dsl; + private final FreshTenantIdentityAssociationRepository freshTenants; + private final AccountTenantCreationBootstrapOperationRepository bootstraps; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner transaction collaborators are retained privately and never exposed.") + public IndividualCreatorPartyRepository( + DSLContext dsl, + FreshTenantIdentityAssociationRepository freshTenants, + AccountTenantCreationBootstrapOperationRepository bootstraps) { + this.dsl = Objects.requireNonNull(dsl); + this.freshTenants = Objects.requireNonNull(freshTenants); + this.bootstraps = Objects.requireNonNull(bootstraps); + } + + /** Reads complete exact source bytes; local VERIFIED status is not legal provisioning proof. */ + public IndividualCreatorPartySource readIndividualSource(UUID partyId, UUID accountId) { + requireTransaction(); + CreatorPartyEncoding.requireUuid(partyId); + CreatorPartyEncoding.requireUuid(accountId); + Record row = + dsl.fetchOne( + "SELECT * FROM account_individual_creator_party_sources " + + "WHERE creator_party_id = ? FOR UPDATE", + partyId); + if (row == null) { + throw new IllegalStateException("Individual party source is absent"); + } + IndividualCreatorPartySource source = + new IndividualCreatorPartySource( + row.get("creator_party_id", UUID.class), + row.get("account_uuid", UUID.class), + VerificationStatus.valueOf(row.get("verification_status", String.class)), + row.get("identity_version", Long.class), + row.get("policy_reference", String.class), + row.get("policy_version", Long.class), + row.get("verification_evidence_reference", String.class), + row.get("verification_evidence_version", Long.class), + row.get("source_version", Long.class)); + byte[] payload = CreatorPartyEncoding.party(source); + if (!accountId.equals(source.accountId()) + || !Arrays.equals(payload, row.get("source_payload", byte[].class)) + || !CreatorPartyEncoding.digest(payload).equals(row.get("source_digest", String.class))) { + throw new IllegalStateException( + "Individual party source identity or exact evidence conflicts"); + } + return source; + } + + /** + * Stores an exact initial association under caller-owned Account transaction. The supplied + * qualification must match persisted V64 and fresh provenance, but this method authenticates no + * caller and is deliberately not registered or exposed. No record is inserted on negative paths. + */ + public AssociationReceipt associateFresh( + UUID requestId, + FreshTenantCreatorEvidence creator, + IndividualCreatorPartySource expectedParty) { + requireTransaction(); + byte[] request = CreatorPartyEncoding.request(requestId, creator, expectedParty); + UUID tenantId = creator.creationEvidence().canonicalTenantId(); + lockTenant(tenantId); + Record prior = operation(requestId); + if (prior != null) { + if (!Arrays.equals(request, prior.get("request_payload", byte[].class))) { + throw new AssociationConflictException("Association request identity changed its binding"); + } + return verifyReceipt(prior, requestId, creator, expectedParty); + } + requireFreshCreation(creator); + IndividualCreatorPartySource current = + readIndividualSource(expectedParty.creatorPartyId(), creator.initiatingAccountId()); + if (!current.equals(expectedParty) || !current.locallyVerified()) { + throw new IllegalStateException( + "Exact independently verified own individual source is absent"); + } + if (historyCount(tenantId) != 0 + || dsl.fetchOne( + "SELECT request_id FROM account_fresh_creator_party_association_operations " + + "WHERE tenant_uuid = ?", + tenantId) + != null) { + throw new AssociationConflictException( + "Tenant has prior creator-party association or history"); + } + UUID historyId = UUID.randomUUID(); + byte[] result = CreatorPartyEncoding.result(historyId, request); + String resultDigest = CreatorPartyEncoding.digest(result); + dsl.execute( + "INSERT INTO account_tenant_creator_party_history " + + "(history_id, tenant_uuid, origin, creator_party_id, source_version, " + + "evidence_payload, evidence_digest) VALUES (?, ?, 'FRESH_INITIAL', ?, 1, ?, ?)", + historyId, + tenantId, + current.creatorPartyId(), + result, + resultDigest); + dsl.execute( + "INSERT INTO account_fresh_creator_party_association_operations " + + "(request_id, tenant_uuid, initiating_account_uuid, creator_party_id, " + + "creation_operation_id, creator_evidence_payload, party_source_payload, " + + "request_payload, request_digest, history_id, result_payload, result_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + requestId, + tenantId, + creator.initiatingAccountId(), + current.creatorPartyId(), + creator.creationEvidence().operationId(), + CreatorPartyEncoding.creation(creator), + CreatorPartyEncoding.party(current), + request, + CreatorPartyEncoding.digest(request), + historyId, + result, + resultDigest); + return verifyReceipt(operation(requestId), requestId, creator, current); + } + + /** + * Exact local initial association readback; later retained/tombstone state denies this reader. + */ + public AssociationReceipt readInitialAssociation( + UUID requestId, + FreshTenantCreatorEvidence creator, + IndividualCreatorPartySource expectedParty) { + requireTransaction(); + lockTenant(creator.creationEvidence().canonicalTenantId()); + requireFreshCreation(creator); + IndividualCreatorPartySource source = + readIndividualSource(expectedParty.creatorPartyId(), creator.initiatingAccountId()); + if (!source.equals(expectedParty) || !source.locallyVerified()) { + throw new IllegalStateException("Current exact individual source is unavailable"); + } + AssociationReceipt receipt = verifyReceipt(operation(requestId), requestId, creator, source); + if (historyCount(receipt.tenantId()) != 1) { + throw new IllegalStateException( + "Initial association reader cannot resolve later party history"); + } + return receipt; + } + + /** + * Resolves the one persisted fresh initial association from its canonical tenant scope. + * + *

The initiating Account, original creator qualification, association operation, and party are + * all derived from owner rows. The canonical tenant claim serializes an absent-row read with the + * initial-association writer; no caller-selected party or operation can redirect the readback. + * This is immutable source evidence only and grants no caller, content, or gameplay permission. A + * composing source read acquires this tenant fence before the bootstrap and Account-source locks + * to preserve the initial-association writer's lock order. + */ + public InitialAssociationReadback readExistingInitialAssociation(UUID tenantUuid) { + requireTransaction(); + CreatorPartyEncoding.requireUuid(tenantUuid); + lockTenant(tenantUuid); + + FreshTenantCreationEvidence creation = + freshTenants + .read(tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Exact fresh tenant creation source is absent")); + UUID bootstrapRequestId = + bootstraps + .findRequestIdByTenantForUpdate(tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Committed creator-bootstrap receipt is absent")); + StoredOperation bootstrap = + bootstraps + .findForUpdate(bootstrapRequestId) + .orElseThrow( + () -> new IllegalStateException("Committed creator-bootstrap receipt is absent")); + if (!"COMMITTED".equals(bootstrap.status()) + || !bootstrapRequestId.equals(bootstrap.requestId()) + || !bootstrapRequestId.equals(bootstrap.accountAuthorizationOperationId()) + || !tenantUuid.equals(bootstrap.tenantUuid()) + || !creation.creationRequestId().equals(bootstrap.creationRequestId()) + || !creation.operationId().equals(bootstrap.creationOperationId())) { + throw new IllegalStateException( + "Committed creator-bootstrap receipt differs from exact fresh tenant provenance"); + } + + FreshTenantCreatorEvidence creator = + new FreshTenantCreatorEvidence( + 1, + creation, + bootstrap.initiatingAccountUuid(), + bootstrap.accountAuthorizationOperationId(), + bootstrap.accountAuthorizationDigest(), + bootstrap.creatorEvidenceDigest()); + // Re-read the persisted bootstrap through the existing exact creator-evidence verifier. This + // also binds the original creator payload and authorization digest to the fresh association. + requireFreshCreation(creator); + + Record association = + dsl.fetchOne( + "SELECT * FROM account_fresh_creator_party_association_operations " + + "WHERE tenant_uuid = ? FOR UPDATE", + tenantUuid); + if (association == null) { + throw new IllegalStateException( + "Immutable fresh initial creator-party association is absent"); + } + UUID associationRequestId = association.get("request_id", UUID.class); + UUID partyId = association.get("creator_party_id", UUID.class); + if (associationRequestId == null || partyId == null) { + throw new IllegalStateException( + "Immutable fresh initial creator-party association identity is incomplete"); + } + + IndividualCreatorPartySource party = + readIndividualSource(partyId, creator.initiatingAccountId()); + if (!party.locallyVerified()) { + throw new IllegalStateException( + "Fresh initial association does not identify its own verified individual party"); + } + AssociationReceipt receipt = readInitialAssociation(associationRequestId, creator, party); + if (!tenantUuid.equals(receipt.tenantId()) + || !partyId.equals(receipt.creatorPartyId()) + || !associationRequestId.equals(receipt.requestId())) { + throw new IllegalStateException( + "Exact initial association readback differs from its persisted tenant row"); + } + return new InitialAssociationReadback(creator, receipt, party); + } + + /** This slice never provides commit-bound party/terms authorization. */ + public void requireHostedAuthoringCurrentness() { + throw new IllegalStateException( + "Authenticated caller, approved provisioning, party source ordering and hosted terms are unavailable"); + } + + private void lockTenant(UUID tenantId) { + CreatorPartyEncoding.requireUuid(tenantId); + Record isolation = dsl.fetchOne("SHOW transaction_isolation"); + if (isolation == null) { + throw new IllegalStateException("Account transaction isolation readback is unavailable"); + } + if (!"read committed".equals(isolation.get(0, String.class))) { + throw new IllegalStateException( + "Initial party association requires READ COMMITTED owner transaction"); + } + Record claim = + dsl.fetchOne( + "SELECT identity_kind FROM account_canonical_tenant_identity_claims " + + "WHERE canonical_tenant_id = ? FOR UPDATE", + tenantId); + if (claim == null || !"FRESH_GAME_DESIGN".equals(claim.get("identity_kind", String.class))) { + throw new IllegalStateException("Fresh canonical tenant provenance is absent"); + } + } + + private void requireFreshCreation(FreshTenantCreatorEvidence creator) { + if (!freshTenants + .read(creator.creationEvidence().canonicalTenantId()) + .filter(creator.creationEvidence()::equals) + .isPresent()) { + throw new IllegalStateException("Exact committed fresh tenant provenance is absent"); + } + StoredOperation bootstrap = + bootstraps + .findForUpdate(creator.accountAuthorizationOperationId()) + .orElseThrow( + () -> new IllegalStateException("Persisted creator qualification is absent")); + if (!"COMMITTED".equals(bootstrap.status()) + || !creator.initiatingAccountId().equals(bootstrap.initiatingAccountUuid()) + || !creator.creationEvidence().canonicalTenantId().equals(bootstrap.tenantUuid()) + || !creator.creationEvidence().creationRequestId().equals(bootstrap.creationRequestId()) + || !creator.creationEvidence().operationId().equals(bootstrap.creationOperationId()) + || !creator + .accountAuthorizationOperationId() + .equals(bootstrap.accountAuthorizationOperationId()) + || !creator.accountAuthorizationDigest().equals(bootstrap.accountAuthorizationDigest()) + || !creator.evidenceDigest().equals(bootstrap.creatorEvidenceDigest()) + || !Arrays.equals( + CreatorPartyEncoding.creation(creator), bootstrap.creatorEvidencePayload())) { + throw new IllegalStateException("Persisted committed creator qualification conflicts"); + } + } + + private Record operation(UUID requestId) { + CreatorPartyEncoding.requireUuid(requestId); + return dsl.fetchOne( + "SELECT * FROM account_fresh_creator_party_association_operations WHERE request_id = ?", + requestId); + } + + private long historyCount(UUID tenantId) { + Record history = + dsl.fetchOne( + "SELECT count(*) AS count FROM account_tenant_creator_party_history WHERE tenant_uuid = ?", + tenantId); + if (history == null) { + throw new IllegalStateException("Creator-party history count readback is unavailable"); + } + Long count = history.get("count", Long.class); + if (count == null || count < 0) { + throw new IllegalStateException("Creator-party history count is incomplete or invalid"); + } + return count; + } + + private AssociationReceipt verifyReceipt( + Record row, + UUID requestId, + FreshTenantCreatorEvidence creator, + IndividualCreatorPartySource party) { + if (row == null) { + throw new IllegalStateException("Immutable association receipt is absent"); + } + UUID historyId = row.get("history_id", UUID.class); + byte[] request = CreatorPartyEncoding.request(requestId, creator, party); + byte[] result = CreatorPartyEncoding.result(historyId, request); + UUID tenantId = creator.creationEvidence().canonicalTenantId(); + String resultDigest = CreatorPartyEncoding.digest(result); + Record history = + dsl.fetchOne( + "SELECT * FROM account_tenant_creator_party_history WHERE history_id = ?", historyId); + if (!requestId.equals(row.get("request_id", UUID.class)) + || !tenantId.equals(row.get("tenant_uuid", UUID.class)) + || !creator.initiatingAccountId().equals(row.get("initiating_account_uuid", UUID.class)) + || !party.creatorPartyId().equals(row.get("creator_party_id", UUID.class)) + || !creator + .creationEvidence() + .operationId() + .equals(row.get("creation_operation_id", UUID.class)) + || !Arrays.equals( + CreatorPartyEncoding.creation(creator), + row.get("creator_evidence_payload", byte[].class)) + || !Arrays.equals( + CreatorPartyEncoding.party(party), row.get("party_source_payload", byte[].class)) + || !Arrays.equals(request, row.get("request_payload", byte[].class)) + || !CreatorPartyEncoding.digest(request).equals(row.get("request_digest", String.class)) + || !Arrays.equals(result, row.get("result_payload", byte[].class)) + || !resultDigest.equals(row.get("result_digest", String.class)) + || row.get("committed_at") == null + || history == null + || !"FRESH_INITIAL".equals(history.get("origin", String.class)) + || !tenantId.equals(history.get("tenant_uuid", UUID.class)) + || !party.creatorPartyId().equals(history.get("creator_party_id", UUID.class)) + || !Long.valueOf(1).equals(history.get("source_version", Long.class)) + || !Arrays.equals(result, history.get("evidence_payload", byte[].class)) + || !resultDigest.equals(history.get("evidence_digest", String.class))) { + throw new IllegalStateException( + "Immutable association readback is incomplete or contradictory"); + } + return new AssociationReceipt( + requestId, tenantId, party.creatorPartyId(), historyId, resultDigest); + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Caller-owned writable Account transaction is required"); + } + } + + /** Historical immutable result only; grants no caller, content or gameplay permission. */ + public record AssociationReceipt( + UUID requestId, UUID tenantId, UUID creatorPartyId, UUID historyId, String resultDigest) {} + + /** Owner-derived fresh creator qualification, association receipt, and current party source. */ + public record InitialAssociationReadback( + FreshTenantCreatorEvidence creatorEvidence, + AssociationReceipt receipt, + IndividualCreatorPartySource partySource) { + public InitialAssociationReadback { + Objects.requireNonNull(creatorEvidence); + Objects.requireNonNull(receipt); + Objects.requireNonNull(partySource); + if (!creatorEvidence.creationEvidence().canonicalTenantId().equals(receipt.tenantId()) + || !creatorEvidence.initiatingAccountId().equals(partySource.accountId()) + || !receipt.creatorPartyId().equals(partySource.creatorPartyId()) + || !partySource.locallyVerified()) { + throw new IllegalArgumentException( + "Initial association readback must retain exact fresh creator and own-party identity"); + } + } + } + + public static final class AssociationConflictException extends IllegalStateException { + public AssociationConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartySource.java new file mode 100644 index 0000000000..847641abe9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartySource.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.accountservice.creatorparty; + +import java.util.UUID; + +/** Opaque owner evidence, not legal identity facts or a caller-supplied verification decision. */ +public record IndividualCreatorPartySource( + UUID creatorPartyId, + UUID accountId, + VerificationStatus verificationStatus, + long identityVersion, + String policyReference, + Long policyVersion, + String verificationEvidenceReference, + Long verificationEvidenceVersion, + long sourceVersion) { + public enum VerificationStatus { + UNVERIFIED, + VERIFIED, + UNSUPPORTED + } + + public IndividualCreatorPartySource { + CreatorPartyEncoding.requireUuid(creatorPartyId); + CreatorPartyEncoding.requireUuid(accountId); + java.util.Objects.requireNonNull(verificationStatus); + if (identityVersion <= 0 || sourceVersion != 1) { + throw new IllegalArgumentException( + "Only a positive identity and initial source are supported"); + } + requireReference(policyReference, policyVersion); + requireReference(verificationEvidenceReference, verificationEvidenceVersion); + if (verificationStatus == VerificationStatus.VERIFIED + && (policyReference == null || verificationEvidenceReference == null)) { + throw new IllegalArgumentException("Verified individual requires exact policy and evidence"); + } + } + + public boolean locallyVerified() { + return verificationStatus == VerificationStatus.VERIFIED; + } + + private static void requireReference(String reference, Long version) { + if ((reference == null) != (version == null) + || (reference != null + && (reference.isBlank() || reference.length() > 512 || version <= 0))) { + throw new IllegalArgumentException("Opaque reference requires its exact positive version"); + } + if (reference != null) { + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.utf8ByteLength(reference); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountTenantCreationBootstrapResult.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountTenantCreationBootstrapResult.java new file mode 100644 index 0000000000..467461750d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountTenantCreationBootstrapResult.java @@ -0,0 +1,49 @@ +package net.firedevops.firemud.accountservice.dto; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** Immutable historical Account owner result for one source-bound creator membership bootstrap. */ +public record AccountTenantCreationBootstrapResult( + UUID operationId, + String requestDigest, + UUID initiatingAccountUuid, + UUID tenantUuid, + String creatorEvidenceDigest, + String sourceSnapshotDigest, + Map membershipVersion, + String membershipAuthorityGeneration, + List roles, + boolean gameplayAdmissionAllowed, + String eventStreamKey, + String eventRequestId, + long eventSequence, + String eventId, + String eventDigest, + UUID auditEventId, + String auditEventType, + String auditPayloadDigest, + String resultDigest) { + public AccountTenantCreationBootstrapResult { + if (operationId == null + || initiatingAccountUuid == null + || tenantUuid == null + || membershipVersion == null + || membershipAuthorityGeneration == null + || roles == null + || eventStreamKey == null + || eventRequestId == null + || eventSequence <= 0L + || eventId == null + || eventDigest == null + || auditEventId == null + || auditEventType == null + || auditPayloadDigest == null + || resultDigest == null) { + throw new IllegalArgumentException("Committed creator-bootstrap result is incomplete"); + } + membershipVersion = Map.copyOf(membershipVersion); + roles = List.copyOf(roles); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java new file mode 100644 index 0000000000..200b8cdd35 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java @@ -0,0 +1,1075 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Account owner workflow for hosted terms publication, individual acceptance and + * currentness. Its typed collaborators are trusted-owner boundaries, not caller DTO authority. + * + *

This does not prove live legal publication or identity verification, add a route/bean, or + * authorize Game Design commits. Currentness includes any disclosed future effective deadline; the + * commit consumer must recheck that deadline at its own linearization point. + */ +public final class AccountHostedTermsService { + private final HostedTermsRepository repository; + private final IndividualCreatorPartyRepository individualParties; + private final DraftAuthorizationFenceRepository draftFences; + private final OperatorPublicationAuthority publicationAuthority; + private final IndividualAcceptanceAuthority acceptanceAuthority; + private final HostedTermsEnvironmentBindingRepository environmentBindings; + private final EnvironmentBindingPublicationAuthority environmentBindingPublicationAuthority; + private final CurrentEnvironmentBoundaryAuthority currentEnvironmentBoundaryAuthority; + private final TransactionTemplate ownerTransaction; + + public AccountHostedTermsService( + PlatformTransactionManager transactionManager, + HostedTermsRepository repository, + IndividualCreatorPartyRepository individualParties, + DraftAuthorizationFenceRepository draftFences, + OperatorPublicationAuthority publicationAuthority, + IndividualAcceptanceAuthority acceptanceAuthority) { + this( + transactionManager, + repository, + individualParties, + draftFences, + publicationAuthority, + acceptanceAuthority, + null, + null, + null); + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Trusted owner collaborators are retained privately and never exposed.") + public AccountHostedTermsService( + PlatformTransactionManager transactionManager, + HostedTermsRepository repository, + IndividualCreatorPartyRepository individualParties, + DraftAuthorizationFenceRepository draftFences, + OperatorPublicationAuthority publicationAuthority, + IndividualAcceptanceAuthority acceptanceAuthority, + HostedTermsEnvironmentBindingRepository environmentBindings, + EnvironmentBindingPublicationAuthority environmentBindingPublicationAuthority, + CurrentEnvironmentBoundaryAuthority currentEnvironmentBoundaryAuthority) { + this.repository = Objects.requireNonNull(repository); + this.individualParties = Objects.requireNonNull(individualParties); + this.draftFences = Objects.requireNonNull(draftFences); + this.publicationAuthority = Objects.requireNonNull(publicationAuthority); + this.acceptanceAuthority = Objects.requireNonNull(acceptanceAuthority); + this.environmentBindings = environmentBindings; + this.environmentBindingPublicationAuthority = environmentBindingPublicationAuthority; + this.currentEnvironmentBoundaryAuthority = currentEnvironmentBoundaryAuthority; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + } + + /** Resolves publication solely from the trusted operator owner before opening an Account tx. */ + public PublicationResult publish(UUID requestId) { + HostedTermsEncoding.requireUuid(requestId, "publication request"); + PublicationEvidence evidence = + Objects.requireNonNull( + publicationAuthority.resolve(requestId), "operator publication evidence"); + byte[] requestPayload = HostedTermsEncoding.publication(requestId, evidence); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> publishInTransaction(requestId, evidence, requestPayload)), + "Account publication transaction result"); + } + + /** + * Resolves the authenticated environment-owner handoff before opening the Account transaction, + * then exact-validates its catalog and predecessor while holding owner-local locks. + */ + public EnvironmentBindingPublicationResult publishEnvironmentBinding(UUID requestId) { + requireEnvironmentBindingPublicationAuthority(); + HostedTermsEncoding.requireUuid(requestId, "environment binding publication request"); + HostedTermsEnvironmentBinding.PublicationEvidence evidence = + Objects.requireNonNull( + environmentBindingPublicationAuthority.resolve(requestId), + "authenticated environment-owner publication evidence"); + byte[] requestPayload = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> publishEnvironmentBindingInTransaction(requestId, evidence, requestPayload)), + "Account environment binding publication result"); + } + + /** Resumes only the exact durable environment-binding publication and source-change intent. */ + public EnvironmentBindingPublicationResult resumeEnvironmentBinding(UUID requestId) { + requireEnvironmentBindingRepository(); + HostedTermsEncoding.requireUuid(requestId, "environment binding publication request"); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> { + HostedTermsEnvironmentBindingRepository.PublicationOperation operation = + environmentBindings + .readPublication(requestId, true) + .orElseThrow( + () -> + new IllegalArgumentException( + "Original environment binding publication is absent")); + return advanceEnvironmentBinding(operation); + }), + "Account environment binding recovery result"); + } + + /** + * Derives the official environment boundary from a trusted owner collaborator, then reads the + * exact binding, current catalog, verified individual party and acceptance in one Account + * READ_COMMITTED owner transaction. The result is currentness/source evidence, not permission. + */ + public EnvironmentBoundCurrentness requireCurrentnessForCurrentEnvironment(UUID creatorPartyId) { + requireCurrentEnvironmentBoundaryAuthority(); + HostedTermsEncoding.requireUuid(creatorPartyId, "creator party"); + HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment = + Objects.requireNonNull( + currentEnvironmentBoundaryAuthority.currentBoundary(), + "authenticated current environment boundary"); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> currentnessForEnvironmentInTransaction(environment, creatorPartyId)), + "Account environment-bound currentness result"); + } + + /** Recovery uses the already durable exact publication and never remints operator evidence. */ + public PublicationResult resumePublication(UUID requestId) { + HostedTermsEncoding.requireUuid(requestId, "publication request"); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> { + HostedTermsRepository.PublicationOperation operation = + repository + .readPublication(requestId, true) + .orElseThrow( + () -> + new IllegalArgumentException( + "Original publication request is absent")); + return advancePublication(operation, null); + }), + "Account publication recovery result"); + } + + /** + * Records only a trusted upstream-authenticated individual's exact affirmative UI/action + * evidence. The accepting account/party comes from that collaborator, then Account independently + * reads and locks the persisted local VERIFIED party source. + */ + public IndividualHostedTermsAcceptance accept(UUID actionRequestId) { + HostedTermsEncoding.requireUuid(actionRequestId, "acceptance action request"); + AcceptanceAction action = + Objects.requireNonNull( + acceptanceAuthority.resolve(actionRequestId), "authenticated individual action"); + if (!actionRequestId.equals(action.actionRequestId())) { + throw new IllegalArgumentException( + "Trusted acceptance action has a changed request identity"); + } + if (!action.affirmative()) { + throw new IllegalArgumentException("Affirmative hosted-terms acceptance is required"); + } + byte[] actionBytes = HostedTermsEncoding.affirmativeAction(action); + return Objects.requireNonNull( + ownerTransaction.execute(ignored -> acceptInTransaction(action, actionBytes)), + "Account acceptance transaction result"); + } + + /** + * Fresh Account evidence for one hosted scope and party. A scheduled deadline is included even + * before it is due; at/after it, old terms are denied even if a source-change fence is + * unresolved. + */ + public CurrentnessEvidence requireCurrentness(UUID hostedScopeId, UUID creatorPartyId) { + HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope"); + HostedTermsEncoding.requireUuid(creatorPartyId, "creator party"); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> currentnessInTransaction(hostedScopeId, creatorPartyId)), + "Account hosted terms currentness result"); + } + + private EnvironmentBindingPublicationResult publishEnvironmentBindingInTransaction( + UUID requestId, + HostedTermsEnvironmentBinding.PublicationEvidence evidence, + byte[] requestPayload) { + environmentBindings.ensureHead(evidence.environmentBoundary()); + var operation = + environmentBindings.claimPublication( + requestId, evidence.environmentBoundary(), requestPayload); + if (operation.status() == HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED) { + return environmentBindingResult(operation, environmentBindings.readCandidate(operation)); + } + if (operation.status() + == HostedTermsEnvironmentBindingRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT) { + if (!Arrays.equals(operation.requestPayload(), requestPayload)) { + throw new IllegalArgumentException("Binding retry differs from exact owner publication"); + } + return advanceEnvironmentBinding(operation); + } + + HostedTermsEnvironmentBindingRepository.HeadSnapshot head = + environmentBindings.lockHead(evidence.environmentBoundary()); + if (head.unsettledPublication() != null + && !head.unsettledPublication().requestId().equals(requestId)) { + throw new IllegalStateException("Another environment binding change is pending"); + } + HostedTermsEnvironmentBinding predecessor = head.current(); + if (!Objects.equals( + evidence.predecessorBindingId(), predecessor == null ? null : predecessor.bindingId()) + || !Objects.equals( + evidence.predecessorSourceVersion(), + predecessor == null ? null : predecessor.sourceVersion())) { + throw new IllegalArgumentException( + "Authenticated environment publication does not extend exact current binding"); + } + Map catalogScopes = + lockBindingCatalogScopes(predecessor, evidence.hostedScopeId()); + if (predecessor != null && catalogScopes.get(predecessor.hostedScopeId()).current() == null) { + throw new IllegalStateException("Prior environment binding catalog source is unavailable"); + } + HostedTermsRepository.ScopeSnapshot targetScope = catalogScopes.get(evidence.hostedScopeId()); + HostedTermsCatalogVersion targetCatalog = targetScope.current(); + requireExactBindingCatalog(evidence, targetCatalog, targetScope.databaseNow()); + + HostedTermsEnvironmentBinding candidate = + environmentBindings.insertCandidate(UUID.randomUUID(), requestId, evidence, predecessor); + DraftAuthorizationFenceRepository.SourceChange change = + predecessor == null + ? null + : bindingSourceChange(requestId, predecessor, catalogScopes, candidate); + if (change != null) { + boolean settled = draftFences.requestSourceChange(change); + if (!settled || !draftFences.sourceMutationPermitted(change)) { + environmentBindings.markOwnerSettlementPending( + requestId, candidate, change.canonicalBytes()); + return environmentBindingResult( + HostedTermsEnvironmentBindingRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT, + candidate); + } + environmentBindings.completePublication( + requestId, candidate, change.canonicalBytes(), predecessor); + draftFences.markSourceCommitted(change); + return environmentBindingResult( + HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED, candidate); + } + environmentBindings.completePublication(requestId, candidate, null, null); + return environmentBindingResult( + HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED, candidate); + } + + private EnvironmentBindingPublicationResult advanceEnvironmentBinding( + HostedTermsEnvironmentBindingRepository.PublicationOperation operation) { + if (operation.status() == HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED) { + return environmentBindingResult(operation, environmentBindings.readCandidate(operation)); + } + if (operation.status() == HostedTermsEnvironmentBindingRepository.PublicationStatus.RECEIVED) { + throw new IllegalStateException( + "Binding publication intent is incomplete; retry the original trusted request"); + } + if (operation.sourceChangeBinding() == null) { + throw new IllegalStateException("Pending binding lacks its durable source-change intent"); + } + HostedTermsEnvironmentBindingRepository.HeadSnapshot head = + environmentBindings.lockHead(operation.environmentBoundary()); + HostedTermsEnvironmentBinding candidate = environmentBindings.readCandidate(operation); + HostedTermsEnvironmentBinding predecessor = head.current(); + if (head.unsettledPublication() == null + || !head.unsettledPublication().requestId().equals(operation.requestId()) + || !Objects.equals( + candidate.predecessorBindingId(), predecessor == null ? null : predecessor.bindingId()) + || !Objects.equals( + candidate.predecessorSourceVersion(), + predecessor == null ? null : predecessor.sourceVersion())) { + throw new IllegalStateException("Pending binding no longer matches exact environment head"); + } + HostedTermsRepository.ScopeSnapshot targetScope = + repository.lockScope(candidate.hostedScopeId()); + requireBindingCatalog(candidate, targetScope.current(), targetScope.databaseNow()); + DraftAuthorizationFenceRepository.SourceChange change = + DraftAuthorizationFenceRepository.SourceChange.fromStored(operation.sourceChangeBinding()); + boolean settled = draftFences.requestSourceChange(change); + if (!settled || !draftFences.sourceMutationPermitted(change)) { + return environmentBindingResult( + HostedTermsEnvironmentBindingRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT, + candidate); + } + environmentBindings.completePublication( + operation.requestId(), candidate, change.canonicalBytes(), predecessor); + draftFences.markSourceCommitted(change); + return environmentBindingResult( + HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED, candidate); + } + + private Map lockBindingCatalogScopes( + HostedTermsEnvironmentBinding predecessor, UUID targetScopeId) { + Map snapshots = new LinkedHashMap<>(); + java.util.stream.Stream.of( + predecessor == null ? targetScopeId : predecessor.hostedScopeId(), targetScopeId) + .distinct() + .sorted(Comparator.comparing(UUID::toString)) + .forEach(scopeId -> snapshots.put(scopeId, repository.lockScope(scopeId))); + return Map.copyOf(snapshots); + } + + private DraftAuthorizationFenceRepository.SourceChange bindingSourceChange( + UUID changeId, + HostedTermsEnvironmentBinding predecessor, + Map catalogScopes, + HostedTermsEnvironmentBinding candidate) { + Map sources = new LinkedHashMap<>(); + SourceEvidence bindingSource = predecessor.sourceEvidence(); + sources.put(bindingSource.key(), bindingSource); + catalogScopes.values().stream() + .map(HostedTermsRepository.ScopeSnapshot::current) + .filter(Objects::nonNull) + .map(this::catalogSourceEvidence) + .forEach(source -> sources.put(source.key(), source)); + return new DraftAuthorizationFenceRepository.SourceChange( + changeId, + List.copyOf(sources.values()), + HostedTermsEnvironmentBindingEncoding.receipt(candidate)); + } + + private SourceEvidence catalogSourceEvidence(HostedTermsCatalogVersion catalog) { + return new SourceEvidence( + SourceKind.HOSTED_TERMS, + catalog.hostedScopeId().toString(), + Long.toString(catalog.materialGeneration()), + Long.toString(catalog.sourceVersion()), + null, + null, + HostedTermsEncoding.catalog(catalog)); + } + + private void requireExactBindingCatalog( + HostedTermsEnvironmentBinding.PublicationEvidence evidence, + HostedTermsCatalogVersion current, + OffsetDateTime databaseNow) { + if (current == null || current.effectiveAt().isAfter(databaseNow.toInstant())) { + throw new IllegalStateException("Environment binding requires a current due terms catalog"); + } + if (!current.versionId().equals(evidence.catalogVersionId()) + || !current.hostedScopeId().equals(evidence.hostedScopeId()) + || current.sourceVersion() != evidence.catalogSourceVersion() + || !current.operatorLegalIdentity().equals(evidence.operatorLegalIdentity()) + || current.operatorIdentityVersion() != evidence.operatorIdentityVersion()) { + throw new IllegalArgumentException( + "Environment publication differs from exact current catalog and legal operator"); + } + } + + private void requireBindingCatalog( + HostedTermsEnvironmentBinding binding, + HostedTermsCatalogVersion current, + OffsetDateTime databaseNow) { + if (current == null || current.effectiveAt().isAfter(databaseNow.toInstant())) { + throw new IllegalStateException("Environment binding catalog is not currently operative"); + } + if (!current.versionId().equals(binding.catalogVersionId()) + || !current.hostedScopeId().equals(binding.hostedScopeId()) + || current.sourceVersion() != binding.catalogSourceVersion() + || !current.operatorLegalIdentity().equals(binding.operatorLegalIdentity()) + || current.operatorIdentityVersion() != binding.operatorIdentityVersion()) { + throw new IllegalStateException("Environment binding points at changed catalog authority"); + } + } + + private EnvironmentBoundCurrentness currentnessForEnvironmentInTransaction( + HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment, UUID creatorPartyId) { + HostedTermsEnvironmentBindingRepository.HeadSnapshot head = + environmentBindings.lockHead(environment.environmentBoundary()); + if (head.unsettledPublication() != null) { + throw new IllegalStateException("Environment binding source change is unresolved"); + } + HostedTermsEnvironmentBinding binding = head.current(); + if (binding == null) { + throw new IllegalStateException( + "No authenticated environment-to-hosted-scope binding exists"); + } + CurrentnessEvidence terms = currentnessInTransaction(binding.hostedScopeId(), creatorPartyId); + HostedTermsRepository.ScopeSnapshot lockedScope = repository.lockScope(binding.hostedScopeId()); + HostedTermsCatalogVersion catalog = lockedScope.current(); + requireBindingCatalog(binding, catalog, lockedScope.databaseNow()); + if (!catalog.versionId().equals(terms.currentVersionId())) { + throw new IllegalStateException("Currentness and locked catalog readback differ"); + } + IndividualCreatorPartySource party = + individualParties.readIndividualSource(terms.creatorPartyId(), terms.accountId()); + if (!party.locallyVerified()) { + throw new IllegalStateException( + "Current individual party source is unavailable or unverified"); + } + IndividualHostedTermsAcceptance acceptance = + repository + .readCurrentAcceptance(terms.creatorPartyId(), binding.hostedScopeId(), catalog) + .orElseThrow( + () -> new IllegalStateException("Current affirmative acceptance is unavailable")); + if (!acceptance.evidenceId().equals(terms.acceptanceEvidenceId())) { + throw new IllegalStateException("Current acceptance readback changed during capture"); + } + byte[] exactTermsSource = + HostedTermsEncoding.currentnessSource(catalog, acceptance, terms.disclosedDeadline()); + if (!Arrays.equals(exactTermsSource, terms.exactCurrentnessSource())) { + throw new IllegalStateException( + "Currentness source differs from exact locked acceptance and deadline evidence"); + } + SourceEvidence partySource = + new SourceEvidence( + SourceKind.CREATOR_PARTY, + party.creatorPartyId().toString(), + Long.toString(party.identityVersion()), + Long.toString(party.sourceVersion()), + null, + null, + CreatorPartyEncoding.party(party)); + SourceEvidence termsSource = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + catalog.hostedScopeId().toString(), + Long.toString(catalog.materialGeneration()), + Long.toString(catalog.sourceVersion()), + null, + null, + exactTermsSource); + List sources = + java.util.stream.Stream.of(binding.sourceEvidence(), termsSource, partySource) + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + return new EnvironmentBoundCurrentness(environment, binding, terms, sources); + } + + private EnvironmentBindingPublicationResult environmentBindingResult( + HostedTermsEnvironmentBindingRepository.PublicationOperation operation, + HostedTermsEnvironmentBinding candidate) { + return environmentBindingResult(operation.status(), candidate); + } + + private EnvironmentBindingPublicationResult environmentBindingResult( + HostedTermsEnvironmentBindingRepository.PublicationStatus status, + HostedTermsEnvironmentBinding candidate) { + return new EnvironmentBindingPublicationResult( + status, candidate, HostedTermsEnvironmentBindingEncoding.receipt(candidate)); + } + + private void requireEnvironmentBindingRepository() { + if (environmentBindings == null) { + throw new IllegalStateException("Account environment-binding persistence is unavailable"); + } + } + + private void requireEnvironmentBindingPublicationAuthority() { + requireEnvironmentBindingRepository(); + if (environmentBindingPublicationAuthority == null) { + throw new IllegalStateException( + "Authenticated environment publication authority is unavailable"); + } + } + + private void requireCurrentEnvironmentBoundaryAuthority() { + requireEnvironmentBindingRepository(); + if (currentEnvironmentBoundaryAuthority == null) { + throw new IllegalStateException("Authenticated current environment boundary is unavailable"); + } + } + + private PublicationResult publishInTransaction( + UUID requestId, PublicationEvidence evidence, byte[] requestPayload) { + repository.ensureScope(evidence.hostedScopeId()); + HostedTermsRepository.PublicationOperation operation = + repository.claimPublication(requestId, evidence.hostedScopeId(), requestPayload); + if (operation.status() != HostedTermsRepository.PublicationStatus.RECEIVED) { + return advancePublication(operation, evidence); + } + HostedTermsRepository.ScopeSnapshot scope = repository.lockScope(evidence.hostedScopeId()); + if (scope.unsettledPublication() != null + && !scope.unsettledPublication().requestId().equals(requestId)) { + throw new IllegalStateException("Another hosted terms publication is scheduled or pending"); + } + HostedTermsCatalogVersion candidate = candidate(evidence, scope.current()); + repository.insertCandidate(candidate); + if (candidate.effectiveAt().isAfter(scope.databaseNow().toInstant())) { + repository.markScheduled(requestId, candidate); + return result(HostedTermsRepository.PublicationStatus.SCHEDULED, candidate); + } + return activate(operation, candidate, scope.current(), null, scope.databaseNow()); + } + + private PublicationResult advancePublication( + HostedTermsRepository.PublicationOperation operation, PublicationEvidence suppliedEvidence) { + if (operation.status() == HostedTermsRepository.PublicationStatus.COMMITTED) { + return result(operation, repository.readCandidate(operation)); + } + if (operation.status() == HostedTermsRepository.PublicationStatus.RECEIVED) { + throw new IllegalStateException( + "Publication intent is incomplete; retry the original trusted publication request"); + } + if (suppliedEvidence != null) { + byte[] supplied = HostedTermsEncoding.publication(operation.requestId(), suppliedEvidence); + if (!Arrays.equals(operation.requestPayload(), supplied)) { + throw new IllegalArgumentException( + "Publication request identity conflicts with exact prior intent"); + } + } + HostedTermsRepository.ScopeSnapshot scope = repository.lockScope(operation.hostedScopeId()); + HostedTermsCatalogVersion candidate = repository.readCandidate(operation); + if (candidate.effectiveAt().isAfter(scope.databaseNow().toInstant())) { + if (operation.status() != HostedTermsRepository.PublicationStatus.SCHEDULED) { + throw new IllegalStateException( + "Owner-pending publication cannot precede its effective date"); + } + return result(operation, candidate); + } + if (operation.status() == HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT) { + DraftAuthorizationFenceRepository.SourceChange change = + DraftAuthorizationFenceRepository.SourceChange.fromStored( + operation.sourceChangeBinding()); + boolean settled = draftFences.requestSourceChange(change); + if (!settled || !draftFences.sourceMutationPermitted(change)) { + return result(operation, candidate); + } + repository.completePublication( + operation.requestId(), + candidate, + HostedTermsEncoding.catalog(candidate), + change.canonicalBytes()); + draftFences.markSourceCommitted(change); + return result(HostedTermsRepository.PublicationStatus.COMMITTED, candidate); + } + return activate(operation, candidate, scope.current(), null, scope.databaseNow()); + } + + private PublicationResult activate( + HostedTermsRepository.PublicationOperation operation, + HostedTermsCatalogVersion candidate, + HostedTermsCatalogVersion current, + byte[] priorChangeBinding, + OffsetDateTime databaseNow) { + if (candidate.effectiveAt().isAfter(databaseNow.toInstant())) { + throw new IllegalStateException("A future catalog version cannot become operative early"); + } + byte[] changeBinding = priorChangeBinding; + if (current != null) { + DraftAuthorizationFenceRepository.SourceChange change = + changeBinding == null + ? sourceChange(operation.requestId(), current, candidate) + : DraftAuthorizationFenceRepository.SourceChange.fromStored(changeBinding); + if (changeBinding == null) { + changeBinding = change.canonicalBytes(); + } + boolean settled = draftFences.requestSourceChange(change); + if (!settled || !draftFences.sourceMutationPermitted(change)) { + if (operation.status() + != HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT) { + repository.markOwnerSettlementPending(operation.requestId(), candidate, changeBinding); + } + return result(HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT, candidate); + } + if (operation.status() == HostedTermsRepository.PublicationStatus.RECEIVED) { + repository.markScheduled(operation.requestId(), candidate); + } + repository.completePublication( + operation.requestId(), candidate, HostedTermsEncoding.catalog(candidate), changeBinding); + draftFences.markSourceCommitted(change); + return result(HostedTermsRepository.PublicationStatus.COMMITTED, candidate); + } + if (operation.status() == HostedTermsRepository.PublicationStatus.RECEIVED) { + repository.markScheduled(operation.requestId(), candidate); + } + repository.completePublication( + operation.requestId(), candidate, HostedTermsEncoding.catalog(candidate), null); + return result(HostedTermsRepository.PublicationStatus.COMMITTED, candidate); + } + + private HostedTermsCatalogVersion candidate( + PublicationEvidence evidence, HostedTermsCatalogVersion predecessor) { + HostedTermsCatalogVersion.Materiality materiality = + predecessor == null + ? HostedTermsCatalogVersion.Materiality.INITIAL + : evidence.materiality(); + if (predecessor == null + && evidence.materiality() != HostedTermsCatalogVersion.Materiality.INITIAL) { + throw new IllegalArgumentException( + "Initial catalog birth must not claim a prior materiality change"); + } + if (predecessor != null + && evidence.materiality() == HostedTermsCatalogVersion.Materiality.INITIAL) { + throw new IllegalArgumentException( + "A catalog update requires an audited materiality classification"); + } + boolean operatorChanged = + predecessor != null + && (!predecessor.operatorLegalIdentity().equals(evidence.operatorLegalIdentity()) + || predecessor.operatorIdentityVersion() != evidence.operatorIdentityVersion()); + if (operatorChanged && materiality != HostedTermsCatalogVersion.Materiality.MATERIAL) { + throw new IllegalArgumentException( + "Operator identity change requires material classification"); + } + long sourceVersion = predecessor == null ? 1 : Math.addExact(predecessor.sourceVersion(), 1); + long generation = + predecessor == null + ? 1 + : Math.addExact( + predecessor.materialGeneration(), + materiality == HostedTermsCatalogVersion.Materiality.MATERIAL ? 1 : 0); + UUID versionId = UUID.randomUUID(); + return new HostedTermsCatalogVersion( + versionId, + evidence.hostedScopeId(), + predecessor == null ? null : predecessor.versionId(), + evidence.operatorLegalIdentity(), + evidence.operatorIdentityVersion(), + evidence.documentBytes(), + HostedTermsEncoding.digest(evidence.documentBytes()), + sourceVersion, + generation, + materiality, + evidence.materialityEvidenceReference(), + evidence.materialityEvidenceVersion(), + evidence.publicationEvidenceReference(), + evidence.publicationEvidenceVersion(), + evidence.noticeEvidenceReference(), + evidence.noticeEvidenceVersion(), + evidence.effectiveAt()); + } + + private IndividualHostedTermsAcceptance acceptInTransaction( + AcceptanceAction action, byte[] actionBytes) { + IndividualHostedTermsAcceptance prior = + repository.readAcceptanceByRequest(action.actionRequestId()).orElse(null); + if (prior != null) { + if (!prior.accountId().equals(action.accountId()) + || !prior.creatorPartyId().equals(action.creatorPartyId()) + || !prior.hostedScopeId().equals(action.hostedScopeId()) + || !prior.termsVersionId().equals(action.shownVersionId()) + || !prior.documentDigest().equals(action.shownDocumentDigest()) + || !prior.operatorLegalIdentity().equals(action.shownOperatorLegalIdentity()) + || prior.operatorIdentityVersion() != action.shownOperatorIdentityVersion() + || !Arrays.equals(prior.affirmativeActionEvidence(), actionBytes)) { + throw new IllegalArgumentException( + "Acceptance request identity conflicts with prior evidence"); + } + return prior; + } + IndividualCreatorPartySource party = + individualParties.readIndividualSource(action.creatorPartyId(), action.accountId()); + requireOwnVerifiedIndividual(action, party); + HostedTermsRepository.ScopeSnapshot scope = repository.lockScope(action.hostedScopeId()); + HostedTermsCatalogVersion shown = + repository.readCatalog(action.hostedScopeId(), action.shownVersionId()); + if (!action.shownVersionId().equals(shown.versionId()) + || !action.hostedScopeId().equals(shown.hostedScopeId()) + || !action.shownDocumentDigest().equals(shown.documentDigest()) + || !action.shownOperatorLegalIdentity().equals(shown.operatorLegalIdentity()) + || action.shownOperatorIdentityVersion() != shown.operatorIdentityVersion()) { + throw new IllegalArgumentException( + "Affirmative action differs from exact shown catalog version"); + } + boolean current = + scope.current() != null && scope.current().versionId().equals(shown.versionId()); + boolean scheduled = + scope.unsettledPublication() != null + && Objects.equals(scope.unsettledPublication().candidateVersionId(), shown.versionId()); + if (!current && !scheduled) { + throw new IllegalStateException( + "Shown hosted terms version is neither operative nor scheduled"); + } + IndividualHostedTermsAcceptance accepted = + repository.insertAcceptance(UUID.randomUUID(), action, party, shown, actionBytes); + return accepted; + } + + private CurrentnessEvidence currentnessInTransaction(UUID scopeId, UUID partyId) { + UUID accountId = repository.lockPartyAccount(partyId); + IndividualCreatorPartySource party = individualParties.readIndividualSource(partyId, accountId); + if (!party.locallyVerified()) { + throw new IllegalStateException( + "Current individual identity evidence is unavailable or unverified"); + } + HostedTermsRepository.ScopeSnapshot scope = repository.lockScope(scopeId); + HostedTermsCatalogVersion current = scope.current(); + if (current == null || current.effectiveAt().isAfter(scope.databaseNow().toInstant())) { + throw new IllegalStateException("No operative hosted terms version is available"); + } + Instant validUntil = null; + HostedTermsCatalogVersion disclosedDeadline = null; + HostedTermsRepository.PublicationOperation pending = scope.unsettledPublication(); + if (pending != null) { + HostedTermsCatalogVersion next = repository.readCandidate(pending); + validUntil = next.effectiveAt(); + disclosedDeadline = next; + if (pending.status() == HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT + || !next.effectiveAt().isAfter(scope.databaseNow().toInstant())) { + throw new IllegalStateException( + "Disclosed hosted-terms effective date has arrived; currentness is unavailable until owner settlement"); + } + } + IndividualHostedTermsAcceptance acceptance = + repository + .readCurrentAcceptance(partyId, scopeId, current) + .orElseThrow( + () -> + new IllegalStateException( + "No current affirmative party-wide hosted terms acceptance")); + byte[] currentParty = HostedTermsEncoding.individualParty(party); + if (!acceptance.accountId().equals(accountId) + || !acceptance.creatorPartyId().equals(partyId) + || !acceptance.hostedScopeId().equals(scopeId) + || !Arrays.equals(acceptance.individualPartySource(), currentParty) + || !CreatorPartyEncoding.digest(currentParty) + .equals(acceptance.individualPartySourceDigest()) + || acceptance.materialGeneration() != current.materialGeneration() + || !acceptance.operatorLegalIdentity().equals(current.operatorLegalIdentity()) + || acceptance.operatorIdentityVersion() != current.operatorIdentityVersion()) { + throw new IllegalStateException( + "Acceptance or individual identity source is stale or changed"); + } + byte[] exactCurrentnessSource = + HostedTermsEncoding.currentnessSource(current, acceptance, disclosedDeadline); + return new CurrentnessEvidence( + scopeId, + partyId, + accountId, + current.versionId(), + current.documentDigest(), + current.operatorLegalIdentity(), + current.operatorIdentityVersion(), + current.sourceVersion(), + current.materialGeneration(), + acceptance.evidenceId(), + acceptance.termsVersionId(), + acceptance.documentDigest(), + validUntil, + disclosedDeadline, + exactCurrentnessSource); + } + + private void requireOwnVerifiedIndividual( + AcceptanceAction action, IndividualCreatorPartySource party) { + if (!party.creatorPartyId().equals(action.creatorPartyId()) + || !party.accountId().equals(action.accountId()) + || party.verificationStatus() != VerificationStatus.VERIFIED) { + throw new IllegalStateException( + "Only the authenticated owner of their own locally verified individual party may accept"); + } + } + + private DraftAuthorizationFenceRepository.SourceChange sourceChange( + UUID changeId, HostedTermsCatalogVersion prior, HostedTermsCatalogVersion next) { + SourceEvidence source = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + prior.hostedScopeId().toString(), + Long.toString(prior.materialGeneration()), + Long.toString(prior.sourceVersion()), + null, + null, + HostedTermsEncoding.catalog(prior)); + return new DraftAuthorizationFenceRepository.SourceChange( + changeId, List.of(source), HostedTermsEncoding.catalog(next)); + } + + private PublicationResult result( + HostedTermsRepository.PublicationStatus status, HostedTermsCatalogVersion candidate) { + return new PublicationResult(status, candidate, HostedTermsEncoding.catalog(candidate)); + } + + private PublicationResult result( + HostedTermsRepository.PublicationOperation operation, HostedTermsCatalogVersion candidate) { + return result(operation.status(), candidate); + } + + public interface OperatorPublicationAuthority { + PublicationEvidence resolve(UUID stableRequestId); + } + + public interface IndividualAcceptanceAuthority { + AcceptanceAction resolve(UUID stableActionRequestId); + } + + /** Authenticated owner handoff; the result is obtained before any Account DB lock is taken. */ + public interface EnvironmentBindingPublicationAuthority { + HostedTermsEnvironmentBinding.PublicationEvidence resolve(UUID stableRequestId); + } + + /** Current official boundary source; no boundary identifier is accepted from the caller. */ + public interface CurrentEnvironmentBoundaryAuthority { + HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary currentBoundary(); + } + + /** Typed result of an independently trusted operator publication/audit owner. */ + public record PublicationEvidence( + UUID hostedScopeId, + String operatorLegalIdentity, + long operatorIdentityVersion, + byte[] documentBytes, + HostedTermsCatalogVersion.Materiality materiality, + String materialityEvidenceReference, + Long materialityEvidenceVersion, + String publicationEvidenceReference, + long publicationEvidenceVersion, + String noticeEvidenceReference, + long noticeEvidenceVersion, + Instant effectiveAt) { + public PublicationEvidence { + HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope"); + operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048); + if (operatorIdentityVersion <= 0) { + throw new IllegalArgumentException("Positive exact operator identity version required"); + } + documentBytes = HostedTermsEncoding.requireDocument(documentBytes); + Objects.requireNonNull(materiality, "audited materiality classification is required"); + if (materiality == HostedTermsCatalogVersion.Materiality.INITIAL) { + if (materialityEvidenceReference != null || materialityEvidenceVersion != null) { + throw new IllegalArgumentException( + "Initial catalog birth has no fabricated materiality predecessor"); + } + } else { + materialityEvidenceReference = + HostedTermsEncoding.requireText(materialityEvidenceReference, 512); + if (materialityEvidenceVersion == null || materialityEvidenceVersion <= 0) { + throw new IllegalArgumentException( + "Audited materiality evidence requires a positive version"); + } + } + publicationEvidenceReference = + HostedTermsEncoding.requireText(publicationEvidenceReference, 512); + noticeEvidenceReference = HostedTermsEncoding.requireText(noticeEvidenceReference, 512); + if (publicationEvidenceVersion <= 0 || noticeEvidenceVersion <= 0) { + throw new IllegalArgumentException( + "Publication and notice evidence versions must be positive"); + } + Objects.requireNonNull(effectiveAt, "explicit disclosed effective instant is required"); + if (effectiveAt.getNano() % 1_000 != 0) { + throw new IllegalArgumentException( + "Disclosed effective instant must preserve PostgreSQL microsecond precision"); + } + } + + @Override + public byte[] documentBytes() { + return documentBytes.clone(); + } + } + + /** Typed action returned only by an authenticated individual-action owner. */ + public record AcceptanceAction( + UUID actionRequestId, + boolean affirmative, + UUID accountId, + UUID creatorPartyId, + UUID hostedScopeId, + UUID shownVersionId, + String shownDocumentDigest, + String shownOperatorLegalIdentity, + long shownOperatorIdentityVersion, + String authenticatedActionReference, + long authenticatedActionVersion, + OffsetDateTime actionCreatedAt) { + public AcceptanceAction { + HostedTermsEncoding.requireUuid(actionRequestId, "acceptance action request"); + HostedTermsEncoding.requireUuid(accountId, "authenticated Account"); + HostedTermsEncoding.requireUuid(creatorPartyId, "authenticated creator party"); + HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope"); + HostedTermsEncoding.requireUuid(shownVersionId, "shown catalog version"); + shownDocumentDigest = HostedTermsEncoding.requireDigest(shownDocumentDigest); + shownOperatorLegalIdentity = + HostedTermsEncoding.requireText(shownOperatorLegalIdentity, 2048); + if (shownOperatorIdentityVersion <= 0 || authenticatedActionVersion <= 0) { + throw new IllegalArgumentException( + "Positive shown operator and action evidence versions required"); + } + authenticatedActionReference = + HostedTermsEncoding.requireText(authenticatedActionReference, 512); + Objects.requireNonNull(actionCreatedAt, "trusted action evidence time is required"); + } + } + + public record PublicationResult( + HostedTermsRepository.PublicationStatus status, + HostedTermsCatalogVersion candidate, + byte[] exactCandidateEvidence) { + public PublicationResult { + Objects.requireNonNull(status); + Objects.requireNonNull(candidate); + exactCandidateEvidence = HostedTermsEncoding.requireBytes(exactCandidateEvidence); + if (!Arrays.equals(exactCandidateEvidence, HostedTermsEncoding.catalog(candidate))) { + throw new IllegalArgumentException( + "Publication result differs from exact immutable catalog"); + } + } + + @Override + public byte[] exactCandidateEvidence() { + return exactCandidateEvidence.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof PublicationResult that + && status == that.status + && candidate.equals(that.candidate) + && Arrays.equals(exactCandidateEvidence, that.exactCandidateEvidence); + } + + @Override + public int hashCode() { + return Objects.hash(status, candidate, Arrays.hashCode(exactCandidateEvidence)); + } + } + + /** Immutable binding receipt result; PENDING_OWNER_SETTLEMENT is never current permission. */ + public record EnvironmentBindingPublicationResult( + HostedTermsEnvironmentBindingRepository.PublicationStatus status, + HostedTermsEnvironmentBinding candidate, + byte[] exactReceipt) { + public EnvironmentBindingPublicationResult { + Objects.requireNonNull(status); + Objects.requireNonNull(candidate); + exactReceipt = HostedTermsEncoding.requireBytes(exactReceipt); + if (!Arrays.equals(exactReceipt, HostedTermsEnvironmentBindingEncoding.receipt(candidate))) { + throw new IllegalArgumentException("Binding result differs from exact immutable receipt"); + } + } + + @Override + public byte[] exactReceipt() { + return exactReceipt.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof EnvironmentBindingPublicationResult that + && status == that.status + && candidate.equals(that.candidate) + && Arrays.equals(exactReceipt, that.exactReceipt); + } + + @Override + public int hashCode() { + return Objects.hash(status, candidate, Arrays.hashCode(exactReceipt)); + } + } + + /** Combined currentness and exact independent source vector; not a Game Design commit token. */ + public record EnvironmentBoundCurrentness( + HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment, + HostedTermsEnvironmentBinding binding, + CurrentnessEvidence terms, + List sourceEvidence) { + public EnvironmentBoundCurrentness { + Objects.requireNonNull(environment); + Objects.requireNonNull(binding); + Objects.requireNonNull(terms); + sourceEvidence = + List.copyOf(Objects.requireNonNull(sourceEvidence)).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (!environment.environmentBoundary().equals(binding.environmentBoundary()) + || !terms.hostedScopeId().equals(binding.hostedScopeId()) + || !terms.currentVersionId().equals(binding.catalogVersionId()) + || terms.sourceVersion() != binding.catalogSourceVersion() + || !terms.operatorLegalIdentity().equals(binding.operatorLegalIdentity()) + || terms.operatorIdentityVersion() != binding.operatorIdentityVersion()) { + throw new IllegalArgumentException( + "Environment binding, current catalog and party acceptance do not agree"); + } + if (sourceEvidence.size() != 3 + || sourceEvidence.stream().map(SourceEvidence::key).distinct().count() != 3 + || sourceEvidence.stream() + .noneMatch( + source -> + source.key().equals(binding.sourceEvidence().key()) + && Arrays.equals( + source.canonicalBytes(), binding.sourceEvidence().canonicalBytes())) + || sourceEvidence.stream() + .noneMatch( + source -> + source.kind() == SourceKind.HOSTED_TERMS + && source.scopeId().equals(terms.hostedScopeId().toString()) + && Objects.equals( + source.generation(), Long.toString(terms.materialGeneration())) + && source.sourceVersion().equals(Long.toString(terms.sourceVersion())) + && Arrays.equals(source.evidence(), terms.exactCurrentnessSource())) + || sourceEvidence.stream() + .noneMatch( + source -> + source.kind() == SourceKind.CREATOR_PARTY + && source.scopeId().equals(terms.creatorPartyId().toString()) + && source.generation() != null + && source.sourceVersion() != null)) { + throw new IllegalArgumentException( + "Bound currentness must retain exact binding, catalog/acceptance and party sources"); + } + } + + public List sourceEvidence() { + return List.copyOf(sourceEvidence); + } + } + + /** Not an owner commit token; deadline must be rechecked at consumer commit linearization. */ + public record CurrentnessEvidence( + UUID hostedScopeId, + UUID creatorPartyId, + UUID accountId, + UUID currentVersionId, + String currentDocumentDigest, + String operatorLegalIdentity, + long operatorIdentityVersion, + long sourceVersion, + long materialGeneration, + UUID acceptanceEvidenceId, + UUID acceptedVersionId, + String acceptedDocumentDigest, + Instant validUntil, + HostedTermsCatalogVersion disclosedDeadline, + byte[] exactCurrentnessSource) { + public CurrentnessEvidence { + HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope"); + HostedTermsEncoding.requireUuid(creatorPartyId, "creator party"); + HostedTermsEncoding.requireUuid(accountId, "party-owning Account"); + HostedTermsEncoding.requireUuid(currentVersionId, "current terms version"); + currentDocumentDigest = HostedTermsEncoding.requireDigest(currentDocumentDigest); + operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048); + HostedTermsEncoding.requireUuid(acceptanceEvidenceId, "acceptance evidence"); + HostedTermsEncoding.requireUuid(acceptedVersionId, "accepted terms version"); + acceptedDocumentDigest = HostedTermsEncoding.requireDigest(acceptedDocumentDigest); + exactCurrentnessSource = HostedTermsEncoding.requireBytes(exactCurrentnessSource); + if (operatorIdentityVersion <= 0 || sourceVersion <= 0 || materialGeneration <= 0) { + throw new IllegalArgumentException("Positive current hosted terms source required"); + } + if ((validUntil == null) != (disclosedDeadline == null) + || (disclosedDeadline != null + && (!validUntil.equals(disclosedDeadline.effectiveAt()) + || !disclosedDeadline.hostedScopeId().equals(hostedScopeId)))) { + throw new IllegalArgumentException( + "Disclosed deadline time and exact immutable catalog evidence must agree"); + } + } + + @Override + public byte[] exactCurrentnessSource() { + return exactCurrentnessSource.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsCatalogVersion.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsCatalogVersion.java new file mode 100644 index 0000000000..0523a33f6e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsCatalogVersion.java @@ -0,0 +1,144 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; + +/** + * Immutable Account-owned document and source version; publication is not proof of legal review. + */ +public record HostedTermsCatalogVersion( + UUID versionId, + UUID hostedScopeId, + UUID predecessorVersionId, + String operatorLegalIdentity, + long operatorIdentityVersion, + byte[] documentBytes, + String documentDigest, + long sourceVersion, + long materialGeneration, + Materiality materiality, + String materialityEvidenceReference, + Long materialityEvidenceVersion, + String publicationEvidenceReference, + long publicationEvidenceVersion, + String noticeEvidenceReference, + long noticeEvidenceVersion, + Instant effectiveAt) { + + public enum Materiality { + INITIAL, + MATERIAL, + NONMATERIAL + } + + public HostedTermsCatalogVersion { + HostedTermsEncoding.requireUuid(versionId, "terms version"); + HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope"); + if (predecessorVersionId != null) { + HostedTermsEncoding.requireUuid(predecessorVersionId, "predecessor version"); + } + operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048); + if (operatorIdentityVersion <= 0 || sourceVersion <= 0 || materialGeneration <= 0) { + throw new IllegalArgumentException( + "Positive independent source and identity versions required"); + } + documentBytes = HostedTermsEncoding.requireDocument(documentBytes); + documentDigest = HostedTermsEncoding.requireDigest(documentDigest); + if (!HostedTermsEncoding.digest(documentBytes).equals(documentDigest)) { + throw new IllegalArgumentException( + "Document digest must bind the exact stored document bytes"); + } + Objects.requireNonNull(materiality, "materiality classification is required"); + Objects.requireNonNull(effectiveAt, "disclosed effective instant is required"); + if (effectiveAt.getNano() % 1_000 != 0) { + throw new IllegalArgumentException( + "Effective instant must preserve PostgreSQL microsecond precision"); + } + publicationEvidenceReference = + HostedTermsEncoding.requireText(publicationEvidenceReference, 512); + if (publicationEvidenceVersion <= 0) { + throw new IllegalArgumentException("Positive publication evidence version required"); + } + noticeEvidenceReference = HostedTermsEncoding.requireText(noticeEvidenceReference, 512); + if (noticeEvidenceVersion <= 0) { + throw new IllegalArgumentException("Positive disclosed-notice evidence version required"); + } + if (predecessorVersionId == null) { + if (materiality != Materiality.INITIAL + || sourceVersion != 1 + || materialGeneration != 1 + || materialityEvidenceReference != null + || materialityEvidenceVersion != null) { + throw new IllegalArgumentException( + "Initial catalog birth cannot fabricate predecessor state"); + } + } else { + materialityEvidenceReference = + HostedTermsEncoding.requireText(materialityEvidenceReference, 512); + if (materialityEvidenceVersion == null + || materialityEvidenceVersion <= 0 + || materiality == Materiality.INITIAL) { + throw new IllegalArgumentException("Audited materiality classification is required"); + } + } + } + + @Override + public byte[] documentBytes() { + return documentBytes.clone(); + } + + public boolean hasOperatorIdentityOf(HostedTermsCatalogVersion other) { + return other != null + && operatorIdentityVersion == other.operatorIdentityVersion + && operatorLegalIdentity.equals(other.operatorLegalIdentity); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof HostedTermsCatalogVersion that)) { + return false; + } + return versionId.equals(that.versionId) + && hostedScopeId.equals(that.hostedScopeId) + && Objects.equals(predecessorVersionId, that.predecessorVersionId) + && operatorLegalIdentity.equals(that.operatorLegalIdentity) + && operatorIdentityVersion == that.operatorIdentityVersion + && Arrays.equals(documentBytes, that.documentBytes) + && documentDigest.equals(that.documentDigest) + && sourceVersion == that.sourceVersion + && materialGeneration == that.materialGeneration + && materiality == that.materiality + && Objects.equals(materialityEvidenceReference, that.materialityEvidenceReference) + && Objects.equals(materialityEvidenceVersion, that.materialityEvidenceVersion) + && publicationEvidenceReference.equals(that.publicationEvidenceReference) + && publicationEvidenceVersion == that.publicationEvidenceVersion + && noticeEvidenceReference.equals(that.noticeEvidenceReference) + && noticeEvidenceVersion == that.noticeEvidenceVersion + && effectiveAt.equals(that.effectiveAt); + } + + @Override + public int hashCode() { + return Objects.hash( + versionId, + hostedScopeId, + predecessorVersionId, + operatorLegalIdentity, + operatorIdentityVersion, + Arrays.hashCode(documentBytes), + documentDigest, + sourceVersion, + materialGeneration, + materiality, + materialityEvidenceReference, + materialityEvidenceVersion, + publicationEvidenceReference, + publicationEvidenceVersion, + noticeEvidenceReference, + noticeEvidenceVersion, + effectiveAt); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java new file mode 100644 index 0000000000..c74a8d55c4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java @@ -0,0 +1,248 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Exact closed encodings for Account-owned hosted terms, publication requests and acceptance. */ +public final class HostedTermsEncoding { + private HostedTermsEncoding() {} + + public static byte[] publication( + UUID requestId, AccountHostedTermsService.PublicationEvidence publication) { + requireUuid(requestId, "publication request"); + Objects.requireNonNull(publication); + Map fields = new LinkedHashMap<>(); + fields.put("schema", "account-hosted-terms-publication/v1"); + fields.put("requestId", requestId.toString()); + fields.put("hostedScopeId", publication.hostedScopeId().toString()); + fields.put("operatorLegalIdentity", publication.operatorLegalIdentity()); + fields.put("operatorIdentityVersion", Long.toString(publication.operatorIdentityVersion())); + fields.put("document", Base64.getEncoder().encodeToString(publication.documentBytes())); + fields.put("documentDigest", digest(publication.documentBytes())); + fields.put("materiality", publication.materiality().name()); + fields.put("materialityEvidenceReference", publication.materialityEvidenceReference()); + fields.put( + "materialityEvidenceVersion", + publication.materialityEvidenceVersion() == null + ? null + : publication.materialityEvidenceVersion().toString()); + fields.put("publicationEvidenceReference", publication.publicationEvidenceReference()); + fields.put( + "publicationEvidenceVersion", Long.toString(publication.publicationEvidenceVersion())); + fields.put("noticeEvidenceReference", publication.noticeEvidenceReference()); + fields.put("noticeEvidenceVersion", Long.toString(publication.noticeEvidenceVersion())); + fields.put("effectiveAt", publication.effectiveAt().toString()); + return canonical(fields); + } + + public static byte[] catalog(HostedTermsCatalogVersion version) { + Objects.requireNonNull(version); + Map fields = new LinkedHashMap<>(); + fields.put("schema", "account-hosted-terms-catalog-version/v1"); + fields.put("versionId", version.versionId().toString()); + fields.put("hostedScopeId", version.hostedScopeId().toString()); + fields.put( + "predecessorVersionId", + version.predecessorVersionId() == null ? null : version.predecessorVersionId().toString()); + fields.put("operatorLegalIdentity", version.operatorLegalIdentity()); + fields.put("operatorIdentityVersion", Long.toString(version.operatorIdentityVersion())); + fields.put("document", Base64.getEncoder().encodeToString(version.documentBytes())); + fields.put("documentDigest", version.documentDigest()); + fields.put("sourceVersion", Long.toString(version.sourceVersion())); + fields.put("materialGeneration", Long.toString(version.materialGeneration())); + fields.put("materiality", version.materiality().name()); + fields.put("materialityEvidenceReference", version.materialityEvidenceReference()); + fields.put( + "materialityEvidenceVersion", + version.materialityEvidenceVersion() == null + ? null + : version.materialityEvidenceVersion().toString()); + fields.put("publicationEvidenceReference", version.publicationEvidenceReference()); + fields.put("publicationEvidenceVersion", Long.toString(version.publicationEvidenceVersion())); + fields.put("noticeEvidenceReference", version.noticeEvidenceReference()); + fields.put("noticeEvidenceVersion", Long.toString(version.noticeEvidenceVersion())); + fields.put("effectiveAt", version.effectiveAt().toString()); + return canonical(fields); + } + + public static byte[] individualParty(IndividualCreatorPartySource source) { + return CreatorPartyEncoding.party(Objects.requireNonNull(source)); + } + + public static byte[] affirmativeAction(AccountHostedTermsService.AcceptanceAction action) { + Objects.requireNonNull(action); + Map fields = new LinkedHashMap<>(); + fields.put("schema", "account-hosted-terms-affirmative-action/v1"); + fields.put("actionRequestId", action.actionRequestId().toString()); + fields.put("affirmative", Boolean.toString(action.affirmative())); + fields.put("accountId", action.accountId().toString()); + fields.put("creatorPartyId", action.creatorPartyId().toString()); + fields.put("hostedScopeId", action.hostedScopeId().toString()); + fields.put("shownVersionId", action.shownVersionId().toString()); + fields.put("shownDocumentDigest", action.shownDocumentDigest()); + fields.put("shownOperatorLegalIdentity", action.shownOperatorLegalIdentity()); + fields.put( + "shownOperatorIdentityVersion", Long.toString(action.shownOperatorIdentityVersion())); + fields.put("authenticatedActionReference", action.authenticatedActionReference()); + fields.put("authenticatedActionVersion", Long.toString(action.authenticatedActionVersion())); + fields.put("createdAt", action.actionCreatedAt().toString()); + return canonical(fields); + } + + public static byte[] acceptance(IndividualHostedTermsAcceptance acceptance) { + Objects.requireNonNull(acceptance); + Map fields = new LinkedHashMap<>(); + fields.put("schema", "account-individual-hosted-terms-acceptance/v1"); + fields.put("evidenceId", acceptance.evidenceId().toString()); + fields.put("actionRequestId", acceptance.actionRequestId().toString()); + fields.put("creatorPartyId", acceptance.creatorPartyId().toString()); + fields.put("accountId", acceptance.accountId().toString()); + fields.put("hostedScopeId", acceptance.hostedScopeId().toString()); + fields.put("termsVersionId", acceptance.termsVersionId().toString()); + fields.put("documentDigest", acceptance.documentDigest()); + fields.put("operatorLegalIdentity", acceptance.operatorLegalIdentity()); + fields.put("operatorIdentityVersion", Long.toString(acceptance.operatorIdentityVersion())); + fields.put("sourceVersion", Long.toString(acceptance.sourceVersion())); + fields.put("materialGeneration", Long.toString(acceptance.materialGeneration())); + fields.put( + "individualPartySource", + Base64.getEncoder().encodeToString(acceptance.individualPartySource())); + fields.put("individualPartySourceDigest", acceptance.individualPartySourceDigest()); + fields.put( + "affirmativeActionEvidence", + Base64.getEncoder().encodeToString(acceptance.affirmativeActionEvidence())); + fields.put("affirmativeActionDigest", acceptance.affirmativeActionDigest()); + fields.put("acceptedAt", acceptance.acceptedAt().toString()); + return canonical(fields); + } + + /** Exact hosted source bytes include the catalog head and the affirmative acceptance receipt. */ + public static byte[] currentnessSource( + HostedTermsCatalogVersion catalog, IndividualHostedTermsAcceptance acceptance) { + return currentnessSource(catalog, acceptance, null); + } + + /** + * Exact currentness source also retains any disclosed future catalog and its immutable deadline. + */ + public static byte[] currentnessSource( + HostedTermsCatalogVersion catalog, + IndividualHostedTermsAcceptance acceptance, + HostedTermsCatalogVersion disclosedDeadline) { + Objects.requireNonNull(catalog); + Objects.requireNonNull(acceptance); + if (!catalog.hostedScopeId().equals(acceptance.hostedScopeId()) + || catalog.materialGeneration() != acceptance.materialGeneration() + || !catalog.operatorLegalIdentity().equals(acceptance.operatorLegalIdentity()) + || catalog.operatorIdentityVersion() != acceptance.operatorIdentityVersion()) { + throw new IllegalArgumentException( + "Currentness source requires one exact catalog and affirmative acceptance"); + } + if (disclosedDeadline != null) { + long expectedGeneration = + Math.addExact( + catalog.materialGeneration(), + disclosedDeadline.materiality() == HostedTermsCatalogVersion.Materiality.MATERIAL + ? 1 + : 0); + if (!catalog.hostedScopeId().equals(disclosedDeadline.hostedScopeId()) + || !Objects.equals(disclosedDeadline.predecessorVersionId(), catalog.versionId()) + || disclosedDeadline.sourceVersion() != Math.addExact(catalog.sourceVersion(), 1) + || disclosedDeadline.materialGeneration() != expectedGeneration + || (disclosedDeadline.materiality() != HostedTermsCatalogVersion.Materiality.MATERIAL + && !disclosedDeadline.hasOperatorIdentityOf(catalog)) + || !disclosedDeadline.effectiveAt().isAfter(catalog.effectiveAt())) { + throw new IllegalArgumentException( + "Disclosed deadline must be the exact immutable next catalog version"); + } + } + byte[] catalogBytes = catalog(catalog); + byte[] acceptanceBytes = acceptance(acceptance); + Map fields = new LinkedHashMap<>(); + fields.put("schema", "account-hosted-terms-currentness-source/v2"); + fields.put("hostedScopeId", catalog.hostedScopeId().toString()); + fields.put("catalog", Base64.getEncoder().encodeToString(catalogBytes)); + fields.put("catalogDigest", digest(catalogBytes)); + fields.put("acceptance", Base64.getEncoder().encodeToString(acceptanceBytes)); + fields.put("acceptanceDigest", digest(acceptanceBytes)); + byte[] deadlineBytes = disclosedDeadline == null ? null : catalog(disclosedDeadline); + fields.put( + "disclosedDeadlineCatalog", + deadlineBytes == null ? null : Base64.getEncoder().encodeToString(deadlineBytes)); + fields.put( + "disclosedDeadlineCatalogDigest", deadlineBytes == null ? null : digest(deadlineBytes)); + return canonical(fields); + } + + public static String digest(byte[] bytes) { + Objects.requireNonNull(bytes); + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is required", impossible); + } + } + + public static UUID requireUuid(UUID value, String description) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical nonnil " + description + " UUID is required"); + } + return value; + } + + public static byte[] requireDocument(byte[] value) { + return requireBytes(value); + } + + public static byte[] requireBytes(byte[] value) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException("Nonempty exact evidence bytes are required"); + } + return value.clone(); + } + + public static String requireText(String value, int maxUtf8Bytes) { + if (value == null + || value.isBlank() + || value.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes) { + throw new IllegalArgumentException("Required exact reference or identity text is invalid"); + } + return value; + } + + public static String requireDigest(String value) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical SHA-256 digest is required"); + } + return value; + } + + public static long requirePositive(long value, String description) { + if (value <= 0) { + throw new IllegalArgumentException("Positive " + description + " is required"); + } + return value; + } + + private static byte[] canonical(Map fields) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(fields)); + } catch (IOException failure) { + throw new IllegalArgumentException("Hosted-terms evidence cannot be encoded", failure); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBinding.java new file mode 100644 index 0000000000..c00e5507fd --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBinding.java @@ -0,0 +1,147 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; + +/** + * Immutable Account receipt binding one canonical environment boundary to an exact hosted terms + * source. This is owner evidence only; it does not establish production publisher custody. + */ +public record HostedTermsEnvironmentBinding( + UUID bindingId, + UUID publicationRequestId, + String environmentBoundary, + UUID hostedScopeId, + String operatorLegalIdentity, + long operatorIdentityVersion, + UUID catalogVersionId, + long catalogSourceVersion, + String authenticatedPublisherIdentity, + String publicationEventIdentity, + String publicationEvidenceDigest, + UUID predecessorBindingId, + Long predecessorSourceVersion, + long sourceVersion) { + + public HostedTermsEnvironmentBinding { + HostedTermsEncoding.requireUuid(bindingId, "environment-binding receipt"); + HostedTermsEncoding.requireUuid( + publicationRequestId, "environment-binding publication request"); + environmentBoundary = requireBoundary(environmentBoundary); + HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope"); + operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048); + HostedTermsEncoding.requirePositive(operatorIdentityVersion, "operator identity version"); + HostedTermsEncoding.requireUuid(catalogVersionId, "catalog version"); + HostedTermsEncoding.requirePositive(catalogSourceVersion, "catalog source version"); + authenticatedPublisherIdentity = + HostedTermsEncoding.requireText(authenticatedPublisherIdentity, 512); + publicationEventIdentity = HostedTermsEncoding.requireText(publicationEventIdentity, 512); + publicationEvidenceDigest = HostedTermsEncoding.requireDigest(publicationEvidenceDigest); + if ((predecessorBindingId == null) != (predecessorSourceVersion == null)) { + throw new IllegalArgumentException( + "Binding predecessor identity and source version must be present together"); + } + if (predecessorBindingId == null) { + if (sourceVersion != 1) { + throw new IllegalArgumentException( + "Initial environment binding cannot fabricate a predecessor source"); + } + } else { + HostedTermsEncoding.requireUuid(predecessorBindingId, "predecessor binding"); + HostedTermsEncoding.requirePositive(predecessorSourceVersion, "predecessor source version"); + if (sourceVersion != Math.addExact(predecessorSourceVersion, 1)) { + throw new IllegalArgumentException( + "Environment binding source must advance from its exact predecessor"); + } + } + HostedTermsEncoding.requirePositive(sourceVersion, "environment binding source version"); + } + + /** + * Exact independent fence key for this environment mapping. Its namespace is disjoint from the + * UUID hosted-scope key; its sourceVersion is the binding counter, not catalog materiality. + */ + public String sourceScopeId() { + return "environment-boundary/" + environmentBoundary; + } + + public SourceEvidence sourceEvidence() { + byte[] bytes = HostedTermsEnvironmentBindingEncoding.receipt(this); + return new SourceEvidence( + SourceKind.HOSTED_TERMS, + sourceScopeId(), + null, + Long.toString(sourceVersion), + null, + null, + bytes); + } + + /** + * Exact result supplied by the trusted environment/secrets owner outside the Account transaction. + * The Account workflow separately checks it against the current local catalog and binding head. + */ + public record PublicationEvidence( + String environmentBoundary, + UUID hostedScopeId, + String operatorLegalIdentity, + long operatorIdentityVersion, + UUID catalogVersionId, + long catalogSourceVersion, + String authenticatedPublisherIdentity, + String publicationEventIdentity, + UUID predecessorBindingId, + Long predecessorSourceVersion) { + public PublicationEvidence { + environmentBoundary = requireBoundary(environmentBoundary); + HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope"); + operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048); + HostedTermsEncoding.requirePositive(operatorIdentityVersion, "operator identity version"); + HostedTermsEncoding.requireUuid(catalogVersionId, "catalog version"); + HostedTermsEncoding.requirePositive(catalogSourceVersion, "catalog source version"); + authenticatedPublisherIdentity = + HostedTermsEncoding.requireText(authenticatedPublisherIdentity, 512); + publicationEventIdentity = HostedTermsEncoding.requireText(publicationEventIdentity, 512); + if ((predecessorBindingId == null) != (predecessorSourceVersion == null)) { + throw new IllegalArgumentException( + "Binding predecessor identity and source version must be present together"); + } + if (predecessorBindingId != null) { + HostedTermsEncoding.requireUuid(predecessorBindingId, "predecessor binding"); + HostedTermsEncoding.requirePositive(predecessorSourceVersion, "predecessor source version"); + } + } + } + + /** + * Fresh canonical environment-boundary observation supplied by the trusted environment owner; + * callers do not select a boundary UUID or name. + */ + public record CurrentEnvironmentBoundary( + String environmentBoundary, + String authenticatedOwnerIdentity, + String observationEventIdentity, + byte[] exactOwnerEvidence, + String ownerEvidenceDigest) { + public CurrentEnvironmentBoundary { + environmentBoundary = requireBoundary(environmentBoundary); + authenticatedOwnerIdentity = HostedTermsEncoding.requireText(authenticatedOwnerIdentity, 512); + observationEventIdentity = HostedTermsEncoding.requireText(observationEventIdentity, 512); + exactOwnerEvidence = HostedTermsEncoding.requireBytes(exactOwnerEvidence); + ownerEvidenceDigest = HostedTermsEncoding.requireDigest(ownerEvidenceDigest); + if (!HostedTermsEncoding.digest(exactOwnerEvidence).equals(ownerEvidenceDigest)) { + throw new IllegalArgumentException("Environment-owner evidence digest conflicts"); + } + } + + @Override + public byte[] exactOwnerEvidence() { + return exactOwnerEvidence.clone(); + } + } + + private static String requireBoundary(String value) { + return HostedTermsEncoding.requireText(value, 512); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java new file mode 100644 index 0000000000..c46c2052c4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Closed canonical encodings for trusted environment-owner binding publications and receipts. */ +public final class HostedTermsEnvironmentBindingEncoding { + private HostedTermsEnvironmentBindingEncoding() {} + + public static byte[] publication( + UUID requestId, HostedTermsEnvironmentBinding.PublicationEvidence evidence) { + HostedTermsEncoding.requireUuid(requestId, "environment binding publication request"); + Objects.requireNonNull(evidence); + Map fields = new LinkedHashMap<>(); + fields.put("schema", "account-hosted-terms-environment-binding-publication/v1"); + fields.put("requestId", requestId.toString()); + fields.put("environmentBoundary", evidence.environmentBoundary()); + fields.put("hostedScopeId", evidence.hostedScopeId().toString()); + fields.put("operatorLegalIdentity", evidence.operatorLegalIdentity()); + fields.put("operatorIdentityVersion", Long.toString(evidence.operatorIdentityVersion())); + fields.put("catalogVersionId", evidence.catalogVersionId().toString()); + fields.put("catalogSourceVersion", Long.toString(evidence.catalogSourceVersion())); + fields.put("authenticatedPublisherIdentity", evidence.authenticatedPublisherIdentity()); + fields.put("publicationEventIdentity", evidence.publicationEventIdentity()); + fields.put( + "predecessorBindingId", + evidence.predecessorBindingId() == null + ? null + : evidence.predecessorBindingId().toString()); + fields.put( + "predecessorSourceVersion", + evidence.predecessorSourceVersion() == null + ? null + : Long.toString(evidence.predecessorSourceVersion())); + return canonical(fields); + } + + public static byte[] receipt(HostedTermsEnvironmentBinding binding) { + Objects.requireNonNull(binding); + Map fields = new LinkedHashMap<>(); + fields.put("schema", "account-hosted-terms-environment-binding-receipt/v1"); + fields.put("bindingId", binding.bindingId().toString()); + fields.put("publicationRequestId", binding.publicationRequestId().toString()); + fields.put("environmentBoundary", binding.environmentBoundary()); + fields.put("hostedScopeId", binding.hostedScopeId().toString()); + fields.put("operatorLegalIdentity", binding.operatorLegalIdentity()); + fields.put("operatorIdentityVersion", Long.toString(binding.operatorIdentityVersion())); + fields.put("catalogVersionId", binding.catalogVersionId().toString()); + fields.put("catalogSourceVersion", Long.toString(binding.catalogSourceVersion())); + fields.put("authenticatedPublisherIdentity", binding.authenticatedPublisherIdentity()); + fields.put("publicationEventIdentity", binding.publicationEventIdentity()); + fields.put("publicationEvidenceDigest", binding.publicationEvidenceDigest()); + fields.put( + "predecessorBindingId", + binding.predecessorBindingId() == null ? null : binding.predecessorBindingId().toString()); + fields.put( + "predecessorSourceVersion", + binding.predecessorSourceVersion() == null + ? null + : Long.toString(binding.predecessorSourceVersion())); + fields.put("sourceVersion", Long.toString(binding.sourceVersion())); + return canonical(fields); + } + + public static String publicationDigest( + UUID requestId, HostedTermsEnvironmentBinding.PublicationEvidence evidence) { + return HostedTermsEncoding.digest(publication(requestId, evidence)); + } + + public static String receiptDigest(HostedTermsEnvironmentBinding binding) { + return HostedTermsEncoding.digest(receipt(binding)); + } + + private static byte[] canonical(Map fields) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(fields)); + } catch (IOException failure) { + throw new IllegalArgumentException("Environment-binding evidence cannot be encoded", failure); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java new file mode 100644 index 0000000000..27d949819c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java @@ -0,0 +1,418 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding.PublicationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local immutable binding receipt/head and exact retry storage. */ +public final class HostedTermsEnvironmentBindingRepository { + private static final String HEADS = "account_hosted_terms_environment_binding_heads"; + private static final String BINDINGS = "account_hosted_terms_environment_bindings"; + private static final String PUBLICATIONS = + "account_hosted_terms_environment_binding_publications"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner DSLContext is retained privately and never exposed.") + public HostedTermsEnvironmentBindingRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public enum PublicationStatus { + RECEIVED, + PENDING_OWNER_SETTLEMENT, + COMMITTED + } + + public record PublicationOperation( + UUID requestId, + String environmentBoundary, + byte[] requestPayload, + String requestDigest, + PublicationStatus status, + UUID candidateBindingId, + byte[] sourceChangeBinding, + byte[] resultPayload, + String resultDigest) { + public PublicationOperation { + requestPayload = requestPayload.clone(); + sourceChangeBinding = sourceChangeBinding == null ? null : sourceChangeBinding.clone(); + resultPayload = resultPayload == null ? null : resultPayload.clone(); + } + + @Override + public byte[] requestPayload() { + return requestPayload.clone(); + } + + @Override + public byte[] sourceChangeBinding() { + return sourceChangeBinding == null ? null : sourceChangeBinding.clone(); + } + + @Override + public byte[] resultPayload() { + return resultPayload == null ? null : resultPayload.clone(); + } + } + + public record HeadSnapshot( + String environmentBoundary, + HostedTermsEnvironmentBinding current, + PublicationOperation unsettledPublication) {} + + /** Creates only an empty serialization row; it does not invent a binding baseline. */ + public void ensureHead(String environmentBoundary) { + requireWriteTransaction(); + String boundary = requireBoundary(environmentBoundary); + dsl.execute( + "INSERT INTO " + HEADS + " (environment_boundary) VALUES (?) ON CONFLICT DO NOTHING", + boundary); + } + + /** Stable publication request identity binds every owner-authenticated field and predecessor. */ + public PublicationOperation claimPublication( + UUID requestId, String environmentBoundary, byte[] exactRequestPayload) { + requireWriteTransaction(); + HostedTermsEncoding.requireUuid(requestId, "environment binding publication request"); + String boundary = requireBoundary(environmentBoundary); + byte[] request = HostedTermsEncoding.requireBytes(exactRequestPayload); + String digest = HostedTermsEncoding.digest(request); + dsl.execute( + "INSERT INTO " + + PUBLICATIONS + + " (request_id, environment_boundary, request_payload, request_digest, status) " + + "VALUES (?, ?, ?, ?, 'RECEIVED') ON CONFLICT (request_id) DO NOTHING", + requestId, + boundary, + request, + digest); + PublicationOperation stored = + readPublication(requestId, true) + .orElseThrow( + () -> new IllegalStateException("Binding publication intent readback is absent")); + if (!stored.environmentBoundary().equals(boundary) + || !Arrays.equals(stored.requestPayload(), request) + || !stored.requestDigest().equals(digest)) { + throw new IllegalArgumentException( + "Environment binding request identity conflicts with exact prior evidence"); + } + return stored; + } + + /** Locks the canonical environment head before catalog and Draft source participation locks. */ + public HeadSnapshot lockHead(String environmentBoundary) { + requireWriteTransaction(); + String boundary = requireBoundary(environmentBoundary); + Record head = + dsl.fetchOne( + "SELECT * FROM " + HEADS + " WHERE environment_boundary = ? FOR UPDATE", boundary); + if (head == null) { + throw new IllegalStateException("Environment binding head is unavailable"); + } + UUID bindingId = head.get("current_binding_id", UUID.class); + Long sourceVersion = head.get("current_source_version", Long.class); + if ((bindingId == null) != (sourceVersion == null)) { + throw new IllegalStateException("Environment binding head is incomplete"); + } + HostedTermsEnvironmentBinding current = + bindingId == null ? null : readBinding(boundary, bindingId); + if (current != null && current.sourceVersion() != sourceVersion) { + throw new IllegalStateException("Environment binding head differs from immutable history"); + } + return new HeadSnapshot(boundary, current, readUnsettledPublication(boundary).orElse(null)); + } + + public Optional readPublication(UUID requestId, boolean forUpdate) { + requireTransaction(); + HostedTermsEncoding.requireUuid(requestId, "environment binding publication request"); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + PUBLICATIONS + + " WHERE request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + requestId); + return row == null ? Optional.empty() : Optional.of(publication(row)); + } + + public Optional readUnsettledPublication(String environmentBoundary) { + requireTransaction(); + String boundary = requireBoundary(environmentBoundary); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + PUBLICATIONS + + " WHERE environment_boundary = ? AND status IN ('RECEIVED', 'PENDING_OWNER_SETTLEMENT')" + + " ORDER BY requested_at, request_id LIMIT 1", + boundary); + return row == null ? Optional.empty() : Optional.of(publication(row)); + } + + public HostedTermsEnvironmentBinding readCandidate(PublicationOperation operation) { + requireTransaction(); + Objects.requireNonNull(operation); + if (operation.candidateBindingId() == null) { + throw new IllegalStateException("Environment binding candidate is absent"); + } + return readBinding(operation.environmentBoundary(), operation.candidateBindingId()); + } + + public HostedTermsEnvironmentBinding readBinding(String environmentBoundary, UUID bindingId) { + requireTransaction(); + String boundary = requireBoundary(environmentBoundary); + HostedTermsEncoding.requireUuid(bindingId, "environment binding receipt"); + Record row = + dsl.fetchOne( + "SELECT * FROM " + BINDINGS + " WHERE environment_boundary = ? AND binding_id = ?", + boundary, + bindingId); + if (row == null) { + throw new IllegalStateException("Exact environment binding receipt is unavailable"); + } + HostedTermsEnvironmentBinding binding = binding(row); + byte[] payload = HostedTermsEnvironmentBindingEncoding.receipt(binding); + if (!Arrays.equals(payload, row.get("binding_payload", byte[].class)) + || !HostedTermsEncoding.digest(payload).equals(row.get("binding_digest", String.class))) { + throw new IllegalStateException("Environment binding payload or digest conflicts"); + } + return binding; + } + + /** Candidate insertion follows the exact current head, and SQL independently enforces it. */ + public HostedTermsEnvironmentBinding insertCandidate( + UUID bindingId, + UUID requestId, + PublicationEvidence evidence, + HostedTermsEnvironmentBinding predecessor) { + requireWriteTransaction(); + HostedTermsEncoding.requireUuid(bindingId, "environment binding receipt"); + HostedTermsEncoding.requireUuid(requestId, "environment binding publication request"); + Objects.requireNonNull(evidence); + if (!Objects.equals( + evidence.predecessorBindingId(), predecessor == null ? null : predecessor.bindingId()) + || !Objects.equals( + evidence.predecessorSourceVersion(), + predecessor == null ? null : predecessor.sourceVersion())) { + throw new IllegalArgumentException( + "Candidate must extend the exact authenticated environment predecessor"); + } + byte[] request = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence); + long version = predecessor == null ? 1 : Math.addExact(predecessor.sourceVersion(), 1); + HostedTermsEnvironmentBinding binding = + new HostedTermsEnvironmentBinding( + bindingId, + requestId, + evidence.environmentBoundary(), + evidence.hostedScopeId(), + evidence.operatorLegalIdentity(), + evidence.operatorIdentityVersion(), + evidence.catalogVersionId(), + evidence.catalogSourceVersion(), + evidence.authenticatedPublisherIdentity(), + evidence.publicationEventIdentity(), + HostedTermsEncoding.digest(request), + predecessor == null ? null : predecessor.bindingId(), + predecessor == null ? null : predecessor.sourceVersion(), + version); + byte[] payload = HostedTermsEnvironmentBindingEncoding.receipt(binding); + dsl.execute( + "INSERT INTO " + + BINDINGS + + " (binding_id, publication_request_id, environment_boundary, hosted_scope_id, operator_legal_identity, " + + "operator_identity_version, catalog_version_id, catalog_source_version, " + + "authenticated_publisher_identity, publication_event_identity, " + + "publication_evidence_digest, predecessor_binding_id, predecessor_source_version, " + + "source_version, binding_payload, binding_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.bindingId(), + binding.publicationRequestId(), + binding.environmentBoundary(), + binding.hostedScopeId(), + binding.operatorLegalIdentity(), + binding.operatorIdentityVersion(), + binding.catalogVersionId(), + binding.catalogSourceVersion(), + binding.authenticatedPublisherIdentity(), + binding.publicationEventIdentity(), + binding.publicationEvidenceDigest(), + binding.predecessorBindingId(), + binding.predecessorSourceVersion(), + binding.sourceVersion(), + payload, + HostedTermsEncoding.digest(payload)); + return readBinding(binding.environmentBoundary(), binding.bindingId()); + } + + public void markOwnerSettlementPending( + UUID requestId, HostedTermsEnvironmentBinding candidate, byte[] sourceChangeBinding) { + transitionPublication( + requestId, + candidate, + "PENDING_OWNER_SETTLEMENT", + HostedTermsEncoding.requireBytes(sourceChangeBinding)); + } + + private void transitionPublication( + UUID requestId, + HostedTermsEnvironmentBinding candidate, + String status, + byte[] sourceChangeBinding) { + requireWriteTransaction(); + Objects.requireNonNull(candidate); + int updated = + dsl.execute( + "UPDATE " + + PUBLICATIONS + + " SET candidate_binding_id = ?, source_change_binding = ?, status = ?" + + " WHERE request_id = ? AND status = 'RECEIVED'", + candidate.bindingId(), + sourceChangeBinding, + status, + requestId); + if (updated != 1) { + PublicationOperation prior = + readPublication(requestId, true) + .orElseThrow(() -> new IllegalStateException("Binding publication disappeared")); + if (!Objects.equals(prior.candidateBindingId(), candidate.bindingId()) + || prior.status() != PublicationStatus.valueOf(status) + || !Arrays.equals(prior.sourceChangeBinding(), sourceChangeBinding)) { + throw new IllegalStateException("Binding publication transition differs from intent"); + } + } + } + + /** Commits the head and exact result in the same transaction as Draft source settlement. */ + public void completePublication( + UUID requestId, + HostedTermsEnvironmentBinding candidate, + byte[] sourceChangeBinding, + HostedTermsEnvironmentBinding predecessor) { + requireWriteTransaction(); + Objects.requireNonNull(candidate); + byte[] payload = HostedTermsEnvironmentBindingEncoding.receipt(candidate); + int operationUpdated = + dsl.execute( + "UPDATE " + + PUBLICATIONS + + " SET candidate_binding_id = ?, source_change_binding = ?, status = 'COMMITTED', " + + "result_payload = ?, result_digest = ?, committed_at = clock_timestamp() " + + "WHERE request_id = ? AND status IN ('RECEIVED', 'PENDING_OWNER_SETTLEMENT')", + candidate.bindingId(), + sourceChangeBinding, + payload, + HostedTermsEncoding.digest(payload), + requestId); + if (operationUpdated != 1) { + throw new IllegalStateException("Binding publication did not commit exactly once"); + } + int headUpdated = + dsl.execute( + "UPDATE " + + HEADS + + " SET current_binding_id = ?, current_source_version = ? " + + "WHERE environment_boundary = ? AND current_binding_id IS NOT DISTINCT FROM ? " + + "AND current_source_version IS NOT DISTINCT FROM ?", + candidate.bindingId(), + candidate.sourceVersion(), + candidate.environmentBoundary(), + predecessor == null ? null : predecessor.bindingId(), + predecessor == null ? null : predecessor.sourceVersion()); + if (headUpdated != 1) { + throw new IllegalStateException("Environment binding head changed from exact predecessor"); + } + } + + private PublicationOperation publication(Record row) { + byte[] request = row.get("request_payload", byte[].class); + String digest = row.get("request_digest", String.class); + if (!HostedTermsEncoding.digest(request).equals(digest)) { + throw new IllegalStateException("Stored binding publication request digest conflicts"); + } + PublicationOperation operation = + new PublicationOperation( + row.get("request_id", UUID.class), + row.get("environment_boundary", String.class), + request, + digest, + PublicationStatus.valueOf(row.get("status", String.class)), + row.get("candidate_binding_id", UUID.class), + row.get("source_change_binding", byte[].class), + row.get("result_payload", byte[].class), + row.get("result_digest", String.class)); + if ((operation.candidateBindingId() == null) + != (operation.status() == PublicationStatus.RECEIVED)) { + throw new IllegalStateException("Stored binding publication candidate state conflicts"); + } + if (operation.status() == PublicationStatus.COMMITTED) { + HostedTermsEnvironmentBinding result = readCandidate(operation); + if (!Arrays.equals( + operation.resultPayload(), HostedTermsEnvironmentBindingEncoding.receipt(result)) + || !HostedTermsEncoding.digest(operation.resultPayload()) + .equals(operation.resultDigest())) { + throw new IllegalStateException("Stored binding publication result conflicts"); + } + } + return operation; + } + + private HostedTermsEnvironmentBinding binding(Record row) { + HostedTermsEnvironmentBinding binding = + new HostedTermsEnvironmentBinding( + row.get("binding_id", UUID.class), + row.get("publication_request_id", UUID.class), + row.get("environment_boundary", String.class), + row.get("hosted_scope_id", UUID.class), + row.get("operator_legal_identity", String.class), + row.get("operator_identity_version", Long.class), + row.get("catalog_version_id", UUID.class), + row.get("catalog_source_version", Long.class), + row.get("authenticated_publisher_identity", String.class), + row.get("publication_event_identity", String.class), + row.get("publication_evidence_digest", String.class), + row.get("predecessor_binding_id", UUID.class), + row.get("predecessor_source_version", Long.class), + row.get("source_version", Long.class)); + if (!binding.environmentBoundary().equals(row.get("environment_boundary", String.class)) + || !binding.hostedScopeId().equals(row.get("hosted_scope_id", UUID.class)) + || !Objects.equals( + binding.predecessorBindingId(), row.get("predecessor_binding_id", UUID.class))) { + throw new IllegalStateException("Environment binding columns conflict with exact receipt"); + } + return binding; + } + + private static String requireBoundary(String boundary) { + return HostedTermsEncoding.requireText(boundary, 512); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Environment binding repository requires an owner transaction"); + } + } + + private void requireWriteTransaction() { + requireTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable owner transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable READ_COMMITTED Account transaction required"); + } + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java new file mode 100644 index 0000000000..7e13ce38a8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java @@ -0,0 +1,547 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local PostgreSQL persistence; it authenticates no publisher, signer or legal evidence. */ +public final class HostedTermsRepository { + private static final String SCOPES = "account_hosted_terms_scopes"; + private static final String VERSIONS = "account_hosted_terms_catalog_versions"; + private static final String PUBLICATIONS = "account_hosted_terms_publication_operations"; + private static final String ACCEPTANCES = "account_individual_hosted_terms_acceptances"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The owner DSLContext is retained privately and never exposed.") + public HostedTermsRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public enum PublicationStatus { + RECEIVED, + SCHEDULED, + PENDING_OWNER_SETTLEMENT, + COMMITTED + } + + public record PublicationOperation( + UUID requestId, + UUID hostedScopeId, + byte[] requestPayload, + String requestDigest, + PublicationStatus status, + UUID candidateVersionId, + byte[] sourceChangeBinding, + byte[] resultPayload, + String resultDigest, + OffsetDateTime committedAt) { + public PublicationOperation { + requestPayload = requestPayload.clone(); + sourceChangeBinding = sourceChangeBinding == null ? null : sourceChangeBinding.clone(); + resultPayload = resultPayload == null ? null : resultPayload.clone(); + } + + @Override + public byte[] requestPayload() { + return requestPayload.clone(); + } + + @Override + public byte[] sourceChangeBinding() { + return sourceChangeBinding == null ? null : sourceChangeBinding.clone(); + } + + @Override + public byte[] resultPayload() { + return resultPayload == null ? null : resultPayload.clone(); + } + } + + public record ScopeSnapshot( + UUID hostedScopeId, + HostedTermsCatalogVersion current, + OffsetDateTime databaseNow, + PublicationOperation unsettledPublication) {} + + /** Creates only an empty serialization row; it never seeds a catalog/source baseline. */ + public void ensureScope(UUID scopeId) { + requireWriteTransaction(); + HostedTermsEncoding.requireUuid(scopeId, "hosted scope"); + dsl.execute( + "INSERT INTO " + SCOPES + " (hosted_scope_id) VALUES (?) ON CONFLICT DO NOTHING", scopeId); + } + + /** Claims a stable request identity before scope locking, then returns its immutable intent. */ + public PublicationOperation claimPublication( + UUID requestId, UUID scopeId, byte[] requestPayload) { + requireWriteTransaction(); + HostedTermsEncoding.requireUuid(requestId, "publication request"); + HostedTermsEncoding.requireUuid(scopeId, "hosted scope"); + byte[] bytes = HostedTermsEncoding.requireBytes(requestPayload); + String digest = HostedTermsEncoding.digest(bytes); + dsl.execute( + "INSERT INTO " + + PUBLICATIONS + + " (request_id, hosted_scope_id, request_payload, request_digest, status)" + + " VALUES (?, ?, ?, ?, 'RECEIVED') ON CONFLICT (request_id) DO NOTHING", + requestId, + scopeId, + bytes, + digest); + PublicationOperation operation = + readPublication(requestId, true) + .orElseThrow( + () -> new IllegalStateException("Publication request readback is unavailable")); + if (!operation.hostedScopeId().equals(scopeId) + || !Arrays.equals(operation.requestPayload(), bytes) + || !operation.requestDigest().equals(digest)) { + throw new IllegalArgumentException( + "Publication request identity conflicts with prior evidence"); + } + return operation; + } + + /** Locks the canonical hosted-scope source before any sorted Draft-fence participation. */ + public ScopeSnapshot lockScope(UUID scopeId) { + requireWriteTransaction(); + HostedTermsEncoding.requireUuid(scopeId, "hosted scope"); + Record scope = + dsl.fetchOne("SELECT * FROM " + SCOPES + " WHERE hosted_scope_id = ? FOR UPDATE", scopeId); + if (scope == null) { + throw new IllegalStateException("Hosted terms scope serialization row is unavailable"); + } + UUID currentId = scope.get("current_version_id", UUID.class); + Long sourceVersion = scope.get("current_source_version", Long.class); + Long generation = scope.get("current_material_generation", Long.class); + if ((currentId == null) != (sourceVersion == null) + || (currentId == null) != (generation == null)) { + throw new IllegalStateException("Hosted terms current source is incomplete"); + } + HostedTermsCatalogVersion current = currentId == null ? null : readCatalog(scopeId, currentId); + if (current != null + && (current.sourceVersion() != sourceVersion + || current.materialGeneration() != generation)) { + throw new IllegalStateException( + "Hosted terms scope head differs from immutable catalog evidence"); + } + OffsetDateTime now = databaseNow(); + PublicationOperation pending = readUnsettledPublication(scopeId).orElse(null); + return new ScopeSnapshot(scopeId, current, now, pending); + } + + public Optional readPublication(UUID requestId, boolean forUpdate) { + requireTransaction(); + HostedTermsEncoding.requireUuid(requestId, "publication request"); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + PUBLICATIONS + + " WHERE request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + requestId); + return row == null ? Optional.empty() : Optional.of(publication(row)); + } + + public Optional readUnsettledPublication(UUID scopeId) { + requireTransaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + PUBLICATIONS + + " WHERE hosted_scope_id = ? AND status IN ('SCHEDULED', 'PENDING_OWNER_SETTLEMENT')" + + " ORDER BY requested_at, request_id LIMIT 1", + scopeId); + return row == null ? Optional.empty() : Optional.of(publication(row)); + } + + public HostedTermsCatalogVersion readCandidate(PublicationOperation operation) { + requireTransaction(); + Objects.requireNonNull(operation); + if (operation.candidateVersionId() == null) { + throw new IllegalStateException("Publication candidate is absent"); + } + return readCatalog(operation.hostedScopeId(), operation.candidateVersionId()); + } + + public HostedTermsCatalogVersion readCatalog(UUID scopeId, UUID versionId) { + requireTransaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM " + VERSIONS + " WHERE hosted_scope_id = ? AND version_id = ?", + scopeId, + versionId); + if (row == null) { + throw new IllegalStateException("Exact hosted terms catalog version is unavailable"); + } + HostedTermsCatalogVersion version = catalog(row); + byte[] payload = HostedTermsEncoding.catalog(version); + if (!Arrays.equals(payload, row.get("version_payload", byte[].class)) + || !HostedTermsEncoding.digest(payload).equals(row.get("version_digest", String.class))) { + throw new IllegalStateException( + "Hosted terms catalog payload or digest conflicts with exact columns"); + } + return version; + } + + public void insertCandidate(HostedTermsCatalogVersion candidate) { + requireWriteTransaction(); + Objects.requireNonNull(candidate); + byte[] payload = HostedTermsEncoding.catalog(candidate); + dsl.execute( + "INSERT INTO " + + VERSIONS + + " (version_id, hosted_scope_id, predecessor_version_id, operator_legal_identity, " + + "operator_identity_version, document_bytes, document_digest, source_version, " + + "material_generation, materiality, materiality_evidence_reference, " + + "materiality_evidence_version, publication_evidence_reference, " + + "publication_evidence_version, notice_evidence_reference, notice_evidence_version, " + + "effective_at, version_payload, version_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, ?, ?)", + candidate.versionId(), + candidate.hostedScopeId(), + candidate.predecessorVersionId(), + candidate.operatorLegalIdentity(), + candidate.operatorIdentityVersion(), + candidate.documentBytes(), + candidate.documentDigest(), + candidate.sourceVersion(), + candidate.materialGeneration(), + candidate.materiality().name(), + candidate.materialityEvidenceReference(), + candidate.materialityEvidenceVersion(), + candidate.publicationEvidenceReference(), + candidate.publicationEvidenceVersion(), + candidate.noticeEvidenceReference(), + candidate.noticeEvidenceVersion(), + OffsetDateTime.ofInstant(candidate.effectiveAt(), java.time.ZoneOffset.UTC), + payload, + HostedTermsEncoding.digest(payload)); + } + + public void markScheduled(UUID requestId, HostedTermsCatalogVersion candidate) { + transitionPublication(requestId, candidate, "SCHEDULED", null); + } + + public void markOwnerSettlementPending( + UUID requestId, HostedTermsCatalogVersion candidate, byte[] sourceChangeBinding) { + transitionPublication( + requestId, + candidate, + "PENDING_OWNER_SETTLEMENT", + HostedTermsEncoding.requireBytes(sourceChangeBinding)); + } + + private void transitionPublication( + UUID requestId, + HostedTermsCatalogVersion candidate, + String status, + byte[] sourceChangeBinding) { + requireWriteTransaction(); + Objects.requireNonNull(candidate); + int updated = + dsl.execute( + "UPDATE " + + PUBLICATIONS + + " SET candidate_version_id = ?, source_change_binding = ?, status = ?" + + " WHERE request_id = ? AND status IN ('RECEIVED', 'SCHEDULED')", + candidate.versionId(), + sourceChangeBinding, + status, + requestId); + if (updated != 1) { + PublicationOperation prior = + readPublication(requestId, true) + .orElseThrow(() -> new IllegalStateException("Publication intent disappeared")); + if (!Objects.equals(prior.candidateVersionId(), candidate.versionId()) + || prior.status() != PublicationStatus.valueOf(status) + || !Arrays.equals(prior.sourceChangeBinding(), sourceChangeBinding)) { + throw new IllegalStateException( + "Publication candidate transition differs from exact intent"); + } + } + } + + /** Advances operative head only after effectiveAt and every required owner terminal result. */ + public void completePublication( + UUID requestId, + HostedTermsCatalogVersion candidate, + byte[] resultPayload, + byte[] sourceChangeBinding) { + requireWriteTransaction(); + Objects.requireNonNull(candidate); + byte[] result = HostedTermsEncoding.requireBytes(resultPayload); + if (!Arrays.equals(result, HostedTermsEncoding.catalog(candidate))) { + throw new IllegalArgumentException( + "Publication result must be exact candidate catalog bytes"); + } + int headUpdated = + dsl.execute( + "UPDATE " + + SCOPES + + " SET current_version_id = ?, current_source_version = ?, " + + "current_material_generation = ? WHERE hosted_scope_id = ? " + + "AND current_version_id IS NOT DISTINCT FROM ? " + + "AND current_source_version IS NOT DISTINCT FROM ? " + + "AND current_material_generation IS NOT DISTINCT FROM ?", + candidate.versionId(), + candidate.sourceVersion(), + candidate.materialGeneration(), + candidate.hostedScopeId(), + candidate.predecessorVersionId(), + candidate.predecessorVersionId() == null ? null : candidate.sourceVersion() - 1, + candidate.predecessorVersionId() == null + ? null + : candidate.materialGeneration() + - (candidate.materiality() == HostedTermsCatalogVersion.Materiality.MATERIAL + ? 1 + : 0)); + if (headUpdated != 1) { + throw new IllegalStateException("Hosted terms operative head changed from exact predecessor"); + } + int operationUpdated = + dsl.execute( + "UPDATE " + + PUBLICATIONS + + " SET candidate_version_id = ?, source_change_binding = ?, status = 'COMMITTED', " + + "result_payload = ?, result_digest = ?, committed_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ? AND status IN ('RECEIVED', 'SCHEDULED', 'PENDING_OWNER_SETTLEMENT')", + candidate.versionId(), + sourceChangeBinding, + result, + HostedTermsEncoding.digest(result), + requestId); + if (operationUpdated != 1) { + throw new IllegalStateException("Publication operation did not commit exactly once"); + } + } + + public UUID lockPartyAccount(UUID creatorPartyId) { + requireWriteTransaction(); + HostedTermsEncoding.requireUuid(creatorPartyId, "creator party"); + Record row = + dsl.fetchOne( + "SELECT account_uuid FROM account_individual_creator_party_sources " + + "WHERE creator_party_id = ? FOR UPDATE", + creatorPartyId); + if (row == null) { + throw new IllegalStateException("Current individual creator party source is unavailable"); + } + UUID accountId = row.get("account_uuid", UUID.class); + return HostedTermsEncoding.requireUuid(accountId, "party-owning Account"); + } + + public Optional readAcceptanceByRequest(UUID actionRequestId) { + requireTransaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM " + ACCEPTANCES + " WHERE action_request_id = ?", actionRequestId); + return row == null ? Optional.empty() : Optional.of(acceptance(row)); + } + + /** Latest acceptance on the active catalog ancestry for this party and material generation. */ + public Optional readCurrentAcceptance( + UUID creatorPartyId, UUID hostedScopeId, HostedTermsCatalogVersion current) { + requireTransaction(); + Record row = + dsl.fetchOne( + "WITH RECURSIVE active_terms(version_id, predecessor_version_id) AS (" + + " SELECT version_id, predecessor_version_id FROM " + + VERSIONS + + " WHERE hosted_scope_id = ? AND version_id = ?" + + " UNION ALL SELECT prior.version_id, prior.predecessor_version_id FROM " + + VERSIONS + + " prior JOIN active_terms active ON prior.version_id = active.predecessor_version_id" + + " WHERE prior.hosted_scope_id = ?)" + + " SELECT acceptance.* FROM " + + ACCEPTANCES + + " acceptance JOIN active_terms active ON active.version_id = acceptance.terms_version_id" + + " WHERE acceptance.creator_party_id = ? AND acceptance.hosted_scope_id = ?" + + " AND acceptance.material_generation = ? AND acceptance.operator_legal_identity = ?" + + " AND acceptance.operator_identity_version = ?" + + " ORDER BY acceptance.accepted_at DESC, acceptance.evidence_id LIMIT 1", + hostedScopeId, + current.versionId(), + hostedScopeId, + creatorPartyId, + hostedScopeId, + current.materialGeneration(), + current.operatorLegalIdentity(), + current.operatorIdentityVersion()); + return row == null ? Optional.empty() : Optional.of(acceptance(row)); + } + + /** Inserts acceptance from owner-read sources; accepted_at is assigned by PostgreSQL. */ + public IndividualHostedTermsAcceptance insertAcceptance( + UUID evidenceId, + AccountHostedTermsService.AcceptanceAction action, + IndividualCreatorPartySource party, + HostedTermsCatalogVersion shownVersion, + byte[] actionEvidence) { + requireWriteTransaction(); + HostedTermsEncoding.requireUuid(evidenceId, "acceptance evidence"); + Objects.requireNonNull(action); + Objects.requireNonNull(party); + Objects.requireNonNull(shownVersion); + byte[] sourceBytes = HostedTermsEncoding.individualParty(party); + byte[] actionBytes = HostedTermsEncoding.requireBytes(actionEvidence); + dsl.execute( + "INSERT INTO " + + ACCEPTANCES + + " (evidence_id, action_request_id, creator_party_id, account_uuid, hosted_scope_id, " + + "terms_version_id, document_digest, operator_legal_identity, operator_identity_version, " + + "source_version, material_generation, individual_party_source, " + + "individual_party_source_digest, affirmative_action_evidence, affirmative_action_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (action_request_id) DO NOTHING", + evidenceId, + action.actionRequestId(), + party.creatorPartyId(), + party.accountId(), + shownVersion.hostedScopeId(), + shownVersion.versionId(), + shownVersion.documentDigest(), + shownVersion.operatorLegalIdentity(), + shownVersion.operatorIdentityVersion(), + shownVersion.sourceVersion(), + shownVersion.materialGeneration(), + sourceBytes, + HostedTermsEncoding.digest(sourceBytes), + actionBytes, + HostedTermsEncoding.digest(actionBytes)); + IndividualHostedTermsAcceptance stored = + readAcceptanceByRequest(action.actionRequestId()) + .orElseThrow(() -> new IllegalStateException("Affirmative acceptance did not persist")); + if (!stored.creatorPartyId().equals(party.creatorPartyId()) + || !stored.accountId().equals(party.accountId()) + || !stored.hostedScopeId().equals(shownVersion.hostedScopeId()) + || !stored.termsVersionId().equals(shownVersion.versionId()) + || !stored.documentDigest().equals(shownVersion.documentDigest()) + || !stored.operatorLegalIdentity().equals(shownVersion.operatorLegalIdentity()) + || stored.operatorIdentityVersion() != shownVersion.operatorIdentityVersion() + || stored.sourceVersion() != shownVersion.sourceVersion() + || stored.materialGeneration() != shownVersion.materialGeneration() + || !Arrays.equals(stored.individualPartySource(), sourceBytes) + || !stored.individualPartySourceDigest().equals(HostedTermsEncoding.digest(sourceBytes)) + || !Arrays.equals(stored.affirmativeActionEvidence(), actionBytes) + || !stored.affirmativeActionDigest().equals(HostedTermsEncoding.digest(actionBytes))) { + throw new IllegalArgumentException( + "Acceptance request identity conflicts with stored evidence"); + } + return stored; + } + + private OffsetDateTime databaseNow() { + // Transaction timestamp can predate a row-lock wait and incorrectly grandfather an expired + // terms version. Sample PostgreSQL wall time only after the source locks are held. + Record row = dsl.fetchOne("SELECT clock_timestamp() AS database_now"); + if (row == null || row.get("database_now", OffsetDateTime.class) == null) { + throw new IllegalStateException("Account database time is unavailable"); + } + return row.get("database_now", OffsetDateTime.class); + } + + private PublicationOperation publication(Record row) { + byte[] request = row.get("request_payload", byte[].class); + String requestDigest = row.get("request_digest", String.class); + if (!HostedTermsEncoding.digest(request).equals(requestDigest)) { + throw new IllegalStateException("Stored publication request digest conflicts"); + } + PublicationOperation operation = + new PublicationOperation( + row.get("request_id", UUID.class), + row.get("hosted_scope_id", UUID.class), + request, + requestDigest, + PublicationStatus.valueOf(row.get("status", String.class)), + row.get("candidate_version_id", UUID.class), + row.get("source_change_binding", byte[].class), + row.get("result_payload", byte[].class), + row.get("result_digest", String.class), + row.get("committed_at", OffsetDateTime.class)); + if (operation.status() == PublicationStatus.COMMITTED) { + HostedTermsCatalogVersion candidate = readCandidate(operation); + if (!Arrays.equals(operation.resultPayload(), HostedTermsEncoding.catalog(candidate)) + || !HostedTermsEncoding.digest(operation.resultPayload()) + .equals(operation.resultDigest())) { + throw new IllegalStateException( + "Committed publication result differs from immutable catalog"); + } + } + return operation; + } + + private HostedTermsCatalogVersion catalog(Record row) { + HostedTermsCatalogVersion version = + new HostedTermsCatalogVersion( + row.get("version_id", UUID.class), + row.get("hosted_scope_id", UUID.class), + row.get("predecessor_version_id", UUID.class), + row.get("operator_legal_identity", String.class), + row.get("operator_identity_version", Long.class), + row.get("document_bytes", byte[].class), + row.get("document_digest", String.class), + row.get("source_version", Long.class), + row.get("material_generation", Long.class), + HostedTermsCatalogVersion.Materiality.valueOf(row.get("materiality", String.class)), + row.get("materiality_evidence_reference", String.class), + row.get("materiality_evidence_version", Long.class), + row.get("publication_evidence_reference", String.class), + row.get("publication_evidence_version", Long.class), + row.get("notice_evidence_reference", String.class), + row.get("notice_evidence_version", Long.class), + row.get("effective_at", OffsetDateTime.class).toInstant()); + return version; + } + + private IndividualHostedTermsAcceptance acceptance(Record row) { + IndividualHostedTermsAcceptance acceptance = + new IndividualHostedTermsAcceptance( + row.get("evidence_id", UUID.class), + row.get("action_request_id", UUID.class), + row.get("creator_party_id", UUID.class), + row.get("account_uuid", UUID.class), + row.get("hosted_scope_id", UUID.class), + row.get("terms_version_id", UUID.class), + row.get("document_digest", String.class), + row.get("operator_legal_identity", String.class), + row.get("operator_identity_version", Long.class), + row.get("source_version", Long.class), + row.get("material_generation", Long.class), + row.get("individual_party_source", byte[].class), + row.get("individual_party_source_digest", String.class), + row.get("affirmative_action_evidence", byte[].class), + row.get("affirmative_action_digest", String.class), + row.get("accepted_at", OffsetDateTime.class)); + if (!Arrays.equals( + acceptance.affirmativeActionEvidence(), + row.get("affirmative_action_evidence", byte[].class)) + || !HostedTermsEncoding.digest(acceptance.individualPartySource()) + .equals(row.get("individual_party_source_digest", String.class))) { + throw new IllegalStateException("Stored acceptance evidence digest conflicts"); + } + return acceptance; + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Hosted terms repository requires an owner transaction"); + } + } + + private void requireWriteTransaction() { + requireTransaction(); + Record isolation = dsl.fetchOne("SHOW transaction_isolation"); + if (isolation == null || !"read committed".equals(isolation.get(0, String.class))) { + throw new IllegalStateException("Hosted terms owner writes require READ COMMITTED isolation"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/IndividualHostedTermsAcceptance.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/IndividualHostedTermsAcceptance.java new file mode 100644 index 0000000000..69dfc6df53 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/IndividualHostedTermsAcceptance.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; + +/** + * Append-only party-wide affirmative acceptance with the exact local individual source captured. + */ +public record IndividualHostedTermsAcceptance( + UUID evidenceId, + UUID actionRequestId, + UUID creatorPartyId, + UUID accountId, + UUID hostedScopeId, + UUID termsVersionId, + String documentDigest, + String operatorLegalIdentity, + long operatorIdentityVersion, + long sourceVersion, + long materialGeneration, + byte[] individualPartySource, + String individualPartySourceDigest, + byte[] affirmativeActionEvidence, + String affirmativeActionDigest, + OffsetDateTime acceptedAt) { + + public IndividualHostedTermsAcceptance { + HostedTermsEncoding.requireUuid(evidenceId, "acceptance evidence"); + HostedTermsEncoding.requireUuid(actionRequestId, "acceptance action request"); + HostedTermsEncoding.requireUuid(creatorPartyId, "creator party"); + HostedTermsEncoding.requireUuid(accountId, "accepting Account"); + HostedTermsEncoding.requireUuid(hostedScopeId, "hosted scope"); + HostedTermsEncoding.requireUuid(termsVersionId, "accepted terms version"); + documentDigest = HostedTermsEncoding.requireDigest(documentDigest); + operatorLegalIdentity = HostedTermsEncoding.requireText(operatorLegalIdentity, 2048); + if (operatorIdentityVersion <= 0 || sourceVersion <= 0 || materialGeneration <= 0) { + throw new IllegalArgumentException("Positive operator and currentness versions required"); + } + individualPartySource = HostedTermsEncoding.requireBytes(individualPartySource); + individualPartySourceDigest = HostedTermsEncoding.requireDigest(individualPartySourceDigest); + affirmativeActionEvidence = HostedTermsEncoding.requireBytes(affirmativeActionEvidence); + affirmativeActionDigest = HostedTermsEncoding.requireDigest(affirmativeActionDigest); + Objects.requireNonNull(acceptedAt, "database acceptance time is required"); + if (!HostedTermsEncoding.digest(individualPartySource).equals(individualPartySourceDigest) + || !HostedTermsEncoding.digest(affirmativeActionEvidence).equals(affirmativeActionDigest)) { + throw new IllegalArgumentException("Acceptance evidence digest does not match exact bytes"); + } + } + + @Override + public byte[] individualPartySource() { + return individualPartySource.clone(); + } + + @Override + public byte[] affirmativeActionEvidence() { + return affirmativeActionEvidence.clone(); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof IndividualHostedTermsAcceptance that)) { + return false; + } + return evidenceId.equals(that.evidenceId) + && actionRequestId.equals(that.actionRequestId) + && creatorPartyId.equals(that.creatorPartyId) + && accountId.equals(that.accountId) + && hostedScopeId.equals(that.hostedScopeId) + && termsVersionId.equals(that.termsVersionId) + && documentDigest.equals(that.documentDigest) + && operatorLegalIdentity.equals(that.operatorLegalIdentity) + && operatorIdentityVersion == that.operatorIdentityVersion + && sourceVersion == that.sourceVersion + && materialGeneration == that.materialGeneration + && Arrays.equals(individualPartySource, that.individualPartySource) + && individualPartySourceDigest.equals(that.individualPartySourceDigest) + && Arrays.equals(affirmativeActionEvidence, that.affirmativeActionEvidence) + && affirmativeActionDigest.equals(that.affirmativeActionDigest) + && acceptedAt.equals(that.acceptedAt); + } + + @Override + public int hashCode() { + return Objects.hash( + evidenceId, + actionRequestId, + creatorPartyId, + accountId, + hostedScopeId, + termsVersionId, + documentDigest, + operatorLegalIdentity, + operatorIdentityVersion, + sourceVersion, + materialGeneration, + Arrays.hashCode(individualPartySource), + individualPartySourceDigest, + Arrays.hashCode(affirmativeActionEvidence), + affirmativeActionDigest, + acceptedAt); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java index a6e844ffce..d7563191da 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java @@ -43,7 +43,7 @@ public AccountGameplayAdmissionCommitConfirmation confirm( try { return Objects.requireNonNull(executor.confirm(identity.evidence(), identity.decisionId())); } catch (RuntimeException failure) { - throw unavailable(); + throw unavailable(failure); } } @@ -55,7 +55,7 @@ public AccountGameplayAdmissionCommitConfirmation read( try { return Objects.requireNonNull(executor.read(identity.evidence(), identity.decisionId())); } catch (RuntimeException failure) { - throw unavailable(); + throw unavailable(failure); } } @@ -114,9 +114,10 @@ private static io.grpc.StatusRuntimeException invalidRequest() { .asRuntimeException(); } - private static io.grpc.StatusRuntimeException unavailable() { + private static io.grpc.StatusRuntimeException unavailable(RuntimeException failure) { return Status.UNAVAILABLE .withDescription("Durable Account admission commit confirmation unavailable") + .withCause(failure) .asRuntimeException(); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java index b60da32522..b6158a671b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java @@ -16,7 +16,9 @@ import net.firedevops.firemud.common.account.authority.AccountAuthoritySourceEventV1Codec.AccountState; import org.jooq.DSLContext; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; @Repository public class AccountRepository { @@ -70,6 +72,20 @@ public Optional findByAccountUuid(UUID accountUuid) { .fetchOne(this::toEntity)); } + /** Locks one exact Account UUID before an owner-local authority mutation. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByAccountUuidForUpdate(UUID accountUuid) { + if (accountUuid == null || accountUuid.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("A non-nil Account UUID is required"); + } + requireWritableOwnerTransaction(); + return Optional.ofNullable( + dsl.selectFrom(ACCOUNTS) + .where(ACCOUNTS.ACCOUNT_UUID.eq(accountUuid)) + .forUpdate() + .fetchOne(this::toEntity)); + } + public Optional findByUsername(String username) { return Optional.ofNullable( dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.USERNAME.eq(username)).fetchOne(this::toEntity)); @@ -229,6 +245,14 @@ private String normalizedLoginAuthModes(Account entity) { return AccountLoginAuthModes.normalize(entity.getLoginAuthModes()); } + private static void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Account UUID lock requires an active writable owner transaction"); + } + } + private static AccountAuthorityState authorityState(AccountsRecord record) { return new AccountAuthorityState( record.getPasswordHash(), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java new file mode 100644 index 0000000000..e17c784be8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java @@ -0,0 +1,251 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.PrivateRealmGrantVersion; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; + +/** Canonical complete-map encodings and digests for immutable creator-bootstrap owner evidence. */ +public final class AccountTenantCreationBootstrapDigest { + private static final String REQUEST_DOMAIN = + "firemud/account/tenant-creation-bootstrap/request/v1"; + private static final String RESULT_DOMAIN = "firemud/account/tenant-creation-bootstrap/result/v1"; + + private AccountTenantCreationBootstrapDigest() {} + + public static byte[] creatorEvidencePayload(FreshTenantCreatorEvidence evidence) { + Objects.requireNonNull(evidence, "creator evidence is required"); + Map creator = new LinkedHashMap<>(); + creator.put("schemaVersion", Integer.toString(evidence.schemaVersion())); + creator.put("creationEvidence", creationEvidenceMap(evidence.creationEvidence())); + creator.put("initiatingAccountId", evidence.initiatingAccountId().toString()); + creator.put( + "accountAuthorizationOperationId", evidence.accountAuthorizationOperationId().toString()); + creator.put("accountAuthorizationDigest", evidence.accountAuthorizationDigest()); + creator.put("evidenceDigest", evidence.evidenceDigest()); + return canonicalJson(creator); + } + + public static byte[] sourceSnapshotPayload(NeverJoinedMembershipSnapshot snapshot) { + Objects.requireNonNull(snapshot, "Account baseline snapshot is required"); + Map source = new LinkedHashMap<>(); + source.put("accountId", snapshot.accountId()); + source.put("tenantId", snapshot.tenantId()); + source.put("membershipExists", snapshot.membershipExists()); + source.put("membershipLifecycleState", snapshot.membershipLifecycleState()); + source.put("gameplayAdmissionAllowed", snapshot.gameplayAdmissionAllowed()); + source.put("roles", snapshot.roles()); + source.put("membershipVersion", snapshot.membershipVersion()); + source.put("membershipAuthorityGeneration", snapshot.membershipAuthorityGeneration()); + source.put("authorityTuple", authorityTupleMap(snapshot.authorityTuple())); + source.put("issuanceFence", snapshot.issuanceFence()); + source.put("evaluatedAt", snapshot.evaluatedAt().toString()); + source.put("outboxStreamKey", snapshot.outboxStreamKey()); + source.put( + "outboxCheckpoints", + snapshot.outboxCheckpoints().stream() + .map( + checkpoint -> + Map.of( + "outboxStreamKey", checkpoint.outboxStreamKey(), + "outboxSequence", checkpoint.outboxSequence())) + .toList()); + source.put( + "outboxSourceEvidence", + snapshot.outboxSourceEvidence().stream() + .map( + evidence -> + Map.of( + "outboxStreamKey", evidence.outboxStreamKey(), + "outboxSequence", evidence.outboxSequence(), + "eventId", evidence.eventId(), + "eventDigest", evidence.eventDigest(), + "canonicalEventJson", evidence.canonicalEventJson())) + .toList()); + return canonicalJson(source); + } + + public static byte[] requestPayload(byte[] creatorEvidencePayload, byte[] sourceSnapshotPayload) { + return frameBytes( + REQUEST_DOMAIN.getBytes(StandardCharsets.UTF_8), + creatorEvidencePayload, + sourceSnapshotPayload); + } + + public static byte[] resultPayload( + String requestId, + String requestDigest, + String sourceSnapshotDigest, + UUID tenantUuid, + Map membershipVersion, + String membershipAuthorityGeneration, + String eventStreamKey, + String eventRequestId, + long eventSequence, + String eventId, + String eventDigest, + byte[] eventPayload, + UUID auditEventId, + String auditEventType, + String auditOccurredAt, + String auditPayloadDigest, + byte[] auditPayload, + byte[] creatorEvidencePayload, + byte[] sourceSnapshotPayload) { + Objects.requireNonNull(tenantUuid, "result tenant UUID is required"); + Objects.requireNonNull(membershipVersion, "result membership-version map is required"); + String tenantKey = tenantUuid.toString(); + if (membershipVersion.size() != 1 || !membershipVersion.containsKey(tenantKey)) { + throw new IllegalArgumentException( + "Creator-bootstrap result requires exactly its tenant membership-version entry"); + } + String version = membershipVersion.get(tenantKey); + try { + if (version == null + || !Long.toString(Long.parseLong(version)).equals(version) + || Long.parseLong(version) <= 0L) { + throw new IllegalArgumentException("Creator-bootstrap membership version is invalid"); + } + } catch (NumberFormatException failure) { + throw new IllegalArgumentException( + "Creator-bootstrap membership version is invalid", failure); + } + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", "account-tenant-creation-bootstrap-result/v1"); + result.put("requestId", requestId); + result.put("requestDigest", requestDigest); + result.put("sourceSnapshotDigest", sourceSnapshotDigest); + result.put("membershipVersion", membershipVersion); + result.put("membershipAuthorityGeneration", membershipAuthorityGeneration); + result.put("eventStreamKey", eventStreamKey); + result.put("eventRequestId", eventRequestId); + result.put("eventSequence", Long.toString(eventSequence)); + result.put("eventId", eventId); + result.put("eventDigest", eventDigest); + result.put("eventPayload", Base64.getEncoder().encodeToString(eventPayload)); + result.put("auditEventId", auditEventId.toString()); + result.put("auditEventType", auditEventType); + result.put("auditOccurredAt", auditOccurredAt); + result.put("auditPayloadDigest", auditPayloadDigest); + result.put("auditPayload", Base64.getEncoder().encodeToString(auditPayload)); + result.put("creatorEvidence", Base64.getEncoder().encodeToString(creatorEvidencePayload)); + result.put("sourceSnapshot", Base64.getEncoder().encodeToString(sourceSnapshotPayload)); + return frameBytes(RESULT_DOMAIN.getBytes(StandardCharsets.UTF_8), canonicalJson(result)); + } + + public static String sha256(byte[] payload) { + Objects.requireNonNull(payload, "digest payload is required"); + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + public static byte[] authorityTuplePayload(AuthorityTuple tuple) { + return canonicalJson(authorityTupleMap(tuple)); + } + + public static Map authorityTupleMap(AuthorityTuple tuple) { + Objects.requireNonNull(tuple, "authority tuple is required"); + Map result = new LinkedHashMap<>(); + result.put("issuerAuthGeneration", tuple.issuerAuthGeneration()); + result.put("accountAuthorityGeneration", tuple.accountAuthorityGeneration()); + result.put("tenantAuthorityGeneration", tuple.tenantAuthorityGeneration()); + result.put("membershipAuthorityGeneration", tuple.membershipAuthorityGeneration()); + result.put( + "privateRealmGrantVersions", + tuple.privateRealmGrantVersions().stream() + .map(AccountTenantCreationBootstrapDigest::grantMap) + .toList()); + tuple + .accountSecurityCutoff() + .ifPresent(cutoff -> result.put("accountSecurityCutoff", cutoffMap(cutoff))); + tuple + .tenantBillingCutoff() + .ifPresent( + cutoffs -> { + Map encodedCutoffs = new LinkedHashMap<>(); + cutoffs.forEach( + (tenantId, cutoff) -> encodedCutoffs.put(tenantId, cutoffMap(cutoff))); + result.put("tenantBillingCutoff", encodedCutoffs); + }); + return result; + } + + private static Map creationEvidenceMap(FreshTenantCreationEvidence evidence) { + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", Integer.toString(evidence.schemaVersion())); + result.put("targetNamespace", evidence.targetNamespace()); + result.put("creationRequestId", evidence.creationRequestId().toString()); + result.put("operationId", evidence.operationId().toString()); + result.put("requestDigest", evidence.requestDigest()); + result.put("canonicalTenantId", evidence.canonicalTenantId().toString()); + result.put("sourceGameRowId", Long.toString(evidence.sourceGameRowId())); + result.put("sourceGameTenantKey", evidence.sourceGameTenantKey()); + result.put("provenanceKind", evidence.provenanceKind()); + result.put("evidenceDigest", evidence.evidenceDigest()); + return result; + } + + private static Map grantMap(PrivateRealmGrantVersion grant) { + return Map.of( + "tenantId", grant.tenantId(), + "worldSlug", grant.worldSlug(), + "realmSlug", grant.realmSlug(), + "playtestLifecycleId", grant.playtestLifecycleId(), + "grantVersion", grant.grantVersion()); + } + + private static Map cutoffMap(AccountSecurityCutoff cutoff) { + return Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()); + } + + private static Map cutoffMap(TenantBillingCutoff cutoff) { + return Map.of( + "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(), + "tenantBillingSequence", cutoff.tenantBillingSequence(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8( + tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(value)); + } catch (IOException | RuntimeException failure) { + throw new IllegalStateException( + "Creator-bootstrap canonical JSON serialization failed", failure); + } + } + + private static byte[] frameBytes(byte[]... values) { + ByteArrayOutputStream framed = new ByteArrayOutputStream(); + for (byte[] value : values) { + Objects.requireNonNull(value, "framed value is required"); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); + framed.writeBytes(value); + } + return framed.toByteArray(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java new file mode 100644 index 0000000000..f2912cbdcf --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepository.java @@ -0,0 +1,573 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountTenantCreationBootstrapResult; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Immutable Account owner request, source snapshot, and result receipt for creator bootstrap. */ +@Repository +public class AccountTenantCreationBootstrapOperationRepository { + private static final String TABLE = "account_tenant_creation_bootstrap_operations"; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring transaction proxy requires a non-final class; constructor only validates its internal collaborator and publishes no partial instance.") + public AccountTenantCreationBootstrapOperationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** Claims one source and baseline, or returns its exact immutable original result. */ + @Transactional(propagation = Propagation.MANDATORY) + public Claim claim( + FreshTenantCreatorEvidence evidence, + byte[] creatorEvidencePayload, + byte[] sourceSnapshotPayload, + String sourceSnapshotDigest, + byte[] requestPayload, + String requestDigest, + long baselineMembershipVersion, + long baselineMembershipAuthorityGeneration) { + requireWriteTransaction(); + Objects.requireNonNull(evidence, "creator evidence is required"); + requireBytes(creatorEvidencePayload, "creator evidence payload"); + requireBytes(sourceSnapshotPayload, "Account source snapshot payload"); + requireBytes(requestPayload, "creator-bootstrap request payload"); + requireDigest(sourceSnapshotDigest, "source snapshot digest"); + requireDigest(requestDigest, "request digest"); + if (baselineMembershipVersion <= 0L || baselineMembershipAuthorityGeneration <= 0L) { + throw new IllegalArgumentException("Creator-bootstrap baseline counters must be positive"); + } + var creation = evidence.creationEvidence(); + UUID requestId = evidence.accountAuthorizationOperationId(); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, schema_version, initiating_account_uuid, tenant_uuid, " + + "creation_request_id, creation_operation_id, account_authorization_operation_id, " + + "account_authorization_digest, creator_evidence_digest, creator_evidence_payload, " + + "source_snapshot_payload, source_snapshot_digest, request_payload, request_digest, " + + "baseline_membership_version, baseline_membership_authority_generation, " + + "baseline_event_sequence, status) " + + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'IN_PROGRESS') " + + "ON CONFLICT DO NOTHING", + requestId, + evidence.initiatingAccountId(), + creation.canonicalTenantId(), + creation.creationRequestId(), + creation.operationId(), + evidence.accountAuthorizationOperationId(), + evidence.accountAuthorizationDigest(), + evidence.evidenceDigest(), + creatorEvidencePayload, + sourceSnapshotPayload, + sourceSnapshotDigest, + requestPayload, + requestDigest, + baselineMembershipVersion, + baselineMembershipAuthorityGeneration); + if (inserted == 1) { + StoredOperation stored = + findForUpdate(requestId) + .orElseThrow( + () -> new IllegalStateException("Claimed creator-bootstrap operation is absent")); + requireSameInput( + stored, + evidence, + creatorEvidencePayload, + sourceSnapshotPayload, + sourceSnapshotDigest, + requestPayload, + requestDigest, + baselineMembershipVersion, + baselineMembershipAuthorityGeneration); + if (!"IN_PROGRESS".equals(stored.status())) { + throw new IllegalStateException("New creator-bootstrap claim is not in progress"); + } + return new Claim(true, stored); + } + if (inserted != 0) { + throw new IllegalStateException("Creator-bootstrap operation claim was ambiguous"); + } + + Optional sameRequest = findForUpdate(requestId); + if (sameRequest.isPresent()) { + StoredOperation stored = sameRequest.orElseThrow(); + requireSameInput( + stored, + evidence, + creatorEvidencePayload, + sourceSnapshotPayload, + sourceSnapshotDigest, + requestPayload, + requestDigest, + baselineMembershipVersion, + baselineMembershipAuthorityGeneration); + if (!"COMMITTED".equals(stored.status())) { + throw new IllegalStateException( + "Incomplete creator-bootstrap operation cannot be replayed"); + } + return new Claim(false, stored); + } + + Optional tenantOperation = findRequestIdByTenantForUpdate(creation.canonicalTenantId()); + if (tenantOperation.isPresent()) { + throw new OperationConflictException( + "Fresh tenant already has a different immutable creator-bootstrap operation"); + } + throw new IllegalStateException("Conflicting creator-bootstrap operation claim disappeared"); + } + + /** Returns one request under its row lock for exact retry verification. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findForUpdate(UUID requestId) { + requireWriteTransaction(); + Objects.requireNonNull(requestId, "creator-bootstrap request ID is required"); + Record row = + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ? FOR UPDATE", requestId); + return row == null ? Optional.empty() : Optional.of(toStoredOperation(row)); + } + + /** Locks the tenant's unique original creator operation when a request ID differs. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findRequestIdByTenantForUpdate(UUID tenantUuid) { + requireWriteTransaction(); + Objects.requireNonNull(tenantUuid, "tenant UUID is required"); + Record row = + dsl.fetchOne( + "SELECT request_id FROM " + TABLE + " WHERE tenant_uuid = ? FOR UPDATE", tenantUuid); + return row == null ? Optional.empty() : Optional.of(row.get("request_id", UUID.class)); + } + + /** + * Requires no older Account membership receipt or operation history for this exact UUID pair. The + * caller already holds the initiator Account row fence and the Account authority snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void assertNoContradictoryMembershipHistory(UUID accountUuid, UUID tenantUuid) { + requireWriteTransaction(); + boolean priorJoinOperation = + exists( + "SELECT EXISTS (SELECT 1 FROM account_join_operations " + + "WHERE account_uuid = ? AND tenant_uuid = ?)", + accountUuid, + tenantUuid); + if (priorJoinOperation) { + throw new IllegalStateException( + "Fresh creator membership pair has contradictory retained Account JOIN history"); + } + } + + /** Completes the exact claim with the membership event, audit, and immutable result receipt. */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredOperation complete(UUID requestId, Completion completion) { + requireWriteTransaction(); + Objects.requireNonNull(requestId, "creator-bootstrap request ID is required"); + Objects.requireNonNull(completion, "creator-bootstrap completion is required"); + int updated = + dsl.execute( + "UPDATE " + + TABLE + + " SET membership_id = ?, membership_version = ?, " + + "membership_authority_generation = ?, membership_lifecycle_state = ?, " + + "gameplay_admission_allowed = ?, membership_roles_payload = ?, " + + "event_stream_key = ?, event_request_id = ?, event_sequence = ?, event_id = ?, " + + "event_digest = ?, caller_bound_authority_invalidated = ?, event_payload = ?, " + + "audit_event_id = ?, audit_event_type = ?, audit_occurred_at = CAST(? AS TIMESTAMPTZ), " + + "audit_payload_digest = ?, audit_payload = ?, result_payload = ?, result_digest = ?, " + + "status = 'COMMITTED' WHERE request_id = ? AND status = 'IN_PROGRESS'", + completion.membershipId(), + completion.membershipVersion(), + completion.membershipAuthorityGeneration(), + completion.membershipLifecycleState(), + completion.gameplayAdmissionAllowed(), + completion.membershipRolesPayload(), + completion.eventStreamKey(), + completion.eventRequestId(), + completion.eventSequence(), + completion.eventId(), + completion.eventDigest(), + completion.callerBoundAuthorityInvalidated(), + completion.eventPayload(), + completion.auditEventId(), + completion.auditEventType(), + OffsetDateTime.ofInstant(completion.auditOccurredAt(), ZoneOffset.UTC).toString(), + completion.auditPayloadDigest(), + completion.auditPayload(), + completion.resultPayload(), + completion.resultDigest(), + requestId); + if (updated != 1) { + throw new IllegalStateException("Creator-bootstrap operation was not completed exactly once"); + } + StoredOperation stored = + findForUpdate(requestId) + .orElseThrow( + () -> new IllegalStateException("Completed creator-bootstrap receipt is absent")); + if (!"COMMITTED".equals(stored.status()) + || stored.membershipId() != completion.membershipId() + || stored.membershipVersion() != completion.membershipVersion() + || stored.membershipAuthorityGeneration() != completion.membershipAuthorityGeneration() + || !completion.membershipLifecycleState().equals(stored.membershipLifecycleState()) + || !Boolean.valueOf(completion.gameplayAdmissionAllowed()) + .equals(stored.gameplayAdmissionAllowed()) + || !Arrays.equals(stored.membershipRolesPayload(), completion.membershipRolesPayload()) + || !stored.eventStreamKey().equals(completion.eventStreamKey()) + || !stored.eventRequestId().equals(completion.eventRequestId()) + || stored.eventSequence() != completion.eventSequence() + || !stored.eventId().equals(completion.eventId()) + || !stored.eventDigest().equals(completion.eventDigest()) + || !Arrays.equals(stored.eventPayload(), completion.eventPayload()) + || !stored.auditEventId().equals(completion.auditEventId()) + || !stored.auditEventType().equals(completion.auditEventType()) + || !stored.auditOccurredAt().equals(completion.auditOccurredAt()) + || !stored.auditPayloadDigest().equals(completion.auditPayloadDigest()) + || !Arrays.equals(stored.auditPayload(), completion.auditPayload()) + || !Arrays.equals(stored.resultPayload(), completion.resultPayload()) + || !stored.resultDigest().equals(completion.resultDigest())) { + throw new IllegalStateException("Creator-bootstrap committed receipt readback differs"); + } + return stored; + } + + private boolean exists(String query, Object... bindings) { + Record result = dsl.fetchOne(query, bindings); + return result != null && Boolean.TRUE.equals(result.get(0, Boolean.class)); + } + + private static void requireSameInput( + StoredOperation stored, + FreshTenantCreatorEvidence evidence, + byte[] creatorEvidencePayload, + byte[] sourceSnapshotPayload, + String sourceSnapshotDigest, + byte[] requestPayload, + String requestDigest, + long baselineMembershipVersion, + long baselineMembershipAuthorityGeneration) { + var creation = evidence.creationEvidence(); + if (!stored.requestId().equals(evidence.accountAuthorizationOperationId()) + || !stored.initiatingAccountUuid().equals(evidence.initiatingAccountId()) + || !stored.tenantUuid().equals(creation.canonicalTenantId()) + || !stored.creationRequestId().equals(creation.creationRequestId()) + || !stored.creationOperationId().equals(creation.operationId()) + || !stored + .accountAuthorizationOperationId() + .equals(evidence.accountAuthorizationOperationId()) + || !stored.accountAuthorizationDigest().equals(evidence.accountAuthorizationDigest()) + || !stored.creatorEvidenceDigest().equals(evidence.evidenceDigest()) + || !Arrays.equals(stored.creatorEvidencePayload(), creatorEvidencePayload) + || !Arrays.equals(stored.sourceSnapshotPayload(), sourceSnapshotPayload) + || !stored.sourceSnapshotDigest().equals(sourceSnapshotDigest) + || !Arrays.equals(stored.requestPayload(), requestPayload) + || !stored.requestDigest().equals(requestDigest) + || stored.baselineMembershipVersion() != baselineMembershipVersion + || stored.baselineMembershipAuthorityGeneration() != baselineMembershipAuthorityGeneration + || stored.baselineEventSequence() != 0L) { + throw new OperationConflictException( + "Creator-bootstrap operation ID was reused with changed source or Account snapshot"); + } + } + + private static StoredOperation toStoredOperation(Record row) { + return new StoredOperation( + required(row.get("request_id", UUID.class), "request ID"), + required(row.get("initiating_account_uuid", UUID.class), "initiating Account UUID"), + required(row.get("tenant_uuid", UUID.class), "tenant UUID"), + required(row.get("creation_request_id", UUID.class), "creation request ID"), + required(row.get("creation_operation_id", UUID.class), "creation operation ID"), + required( + row.get("account_authorization_operation_id", UUID.class), + "Account authorization operation ID"), + required( + row.get("account_authorization_digest", String.class), "Account authorization digest"), + required(row.get("creator_evidence_digest", String.class), "creator evidence digest"), + required(row.get("creator_evidence_payload", byte[].class), "creator evidence payload"), + required(row.get("source_snapshot_payload", byte[].class), "source snapshot payload"), + required(row.get("source_snapshot_digest", String.class), "source snapshot digest"), + required(row.get("request_payload", byte[].class), "request payload"), + required(row.get("request_digest", String.class), "request digest"), + required(row.get("baseline_membership_version", Long.class), "baseline membership version"), + required( + row.get("baseline_membership_authority_generation", Long.class), + "baseline membership authority generation"), + required(row.get("baseline_event_sequence", Long.class), "baseline event sequence"), + required(row.get("status", String.class), "operation status"), + row.get("membership_id", Long.class), + row.get("membership_version", Long.class), + row.get("membership_authority_generation", Long.class), + row.get("membership_lifecycle_state", String.class), + row.get("gameplay_admission_allowed", Boolean.class), + row.get("membership_roles_payload", byte[].class), + row.get("event_stream_key", String.class), + row.get("event_request_id", String.class), + row.get("event_sequence", Long.class), + row.get("event_id", String.class), + row.get("event_digest", String.class), + row.get("caller_bound_authority_invalidated", Boolean.class), + row.get("event_payload", byte[].class), + row.get("audit_event_id", UUID.class), + row.get("audit_event_type", String.class), + toInstant(row.get("audit_occurred_at", OffsetDateTime.class)), + row.get("audit_payload_digest", String.class), + row.get("audit_payload", byte[].class), + row.get("result_payload", byte[].class), + row.get("result_digest", String.class), + toInstant(row.get("committed_at", OffsetDateTime.class))); + } + + private static T required(T value, String label) { + if (value == null) { + throw new IllegalStateException("Creator-bootstrap stored " + label + " is absent"); + } + return value; + } + + private static Instant toInstant(OffsetDateTime value) { + return value == null ? null : value.toInstant(); + } + + private static void requireBytes(byte[] value, String label) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException("Creator-bootstrap " + label + " is required"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Creator-bootstrap " + label + " is malformed"); + } + } + + private static void requireWriteTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Creator-bootstrap owner operation requires a write transaction"); + } + } + + public record Claim(boolean claimed, StoredOperation operation) { + public Claim { + Objects.requireNonNull(operation, "claimed creator-bootstrap operation is required"); + } + } + + public record Completion( + long membershipId, + long membershipVersion, + long membershipAuthorityGeneration, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + byte[] membershipRolesPayload, + String eventStreamKey, + String eventRequestId, + long eventSequence, + String eventId, + String eventDigest, + boolean callerBoundAuthorityInvalidated, + byte[] eventPayload, + UUID auditEventId, + String auditEventType, + Instant auditOccurredAt, + String auditPayloadDigest, + byte[] auditPayload, + byte[] resultPayload, + String resultDigest) { + public Completion { + if (membershipId <= 0L + || membershipVersion <= 0L + || membershipAuthorityGeneration <= 0L + || membershipLifecycleState == null + || membershipRolesPayload == null + || eventStreamKey == null + || eventRequestId == null + || eventSequence <= 0L + || eventId == null + || eventDigest == null + || eventPayload == null + || auditEventId == null + || auditEventType == null + || auditOccurredAt == null + || auditPayloadDigest == null + || auditPayload == null + || resultPayload == null + || resultDigest == null) { + throw new IllegalArgumentException("Creator-bootstrap completion evidence is incomplete"); + } + membershipRolesPayload = membershipRolesPayload.clone(); + eventPayload = eventPayload.clone(); + auditPayload = auditPayload.clone(); + resultPayload = resultPayload.clone(); + } + + @Override + public byte[] membershipRolesPayload() { + return membershipRolesPayload.clone(); + } + + @Override + public byte[] eventPayload() { + return eventPayload.clone(); + } + + @Override + public byte[] auditPayload() { + return auditPayload.clone(); + } + + @Override + public byte[] resultPayload() { + return resultPayload.clone(); + } + } + + public record StoredOperation( + UUID requestId, + UUID initiatingAccountUuid, + UUID tenantUuid, + UUID creationRequestId, + UUID creationOperationId, + UUID accountAuthorizationOperationId, + String accountAuthorizationDigest, + String creatorEvidenceDigest, + byte[] creatorEvidencePayload, + byte[] sourceSnapshotPayload, + String sourceSnapshotDigest, + byte[] requestPayload, + String requestDigest, + long baselineMembershipVersion, + long baselineMembershipAuthorityGeneration, + long baselineEventSequence, + String status, + Long membershipId, + Long membershipVersion, + Long membershipAuthorityGeneration, + String membershipLifecycleState, + Boolean gameplayAdmissionAllowed, + byte[] membershipRolesPayload, + String eventStreamKey, + String eventRequestId, + Long eventSequence, + String eventId, + String eventDigest, + Boolean callerBoundAuthorityInvalidated, + byte[] eventPayload, + UUID auditEventId, + String auditEventType, + Instant auditOccurredAt, + String auditPayloadDigest, + byte[] auditPayload, + byte[] resultPayload, + String resultDigest, + Instant committedAt) { + public StoredOperation { + creatorEvidencePayload = cloneBytes(creatorEvidencePayload); + sourceSnapshotPayload = cloneBytes(sourceSnapshotPayload); + requestPayload = cloneBytes(requestPayload); + membershipRolesPayload = cloneBytes(membershipRolesPayload); + eventPayload = cloneBytes(eventPayload); + auditPayload = cloneBytes(auditPayload); + resultPayload = cloneBytes(resultPayload); + } + + @Override + public byte[] creatorEvidencePayload() { + return cloneBytes(creatorEvidencePayload); + } + + @Override + public byte[] sourceSnapshotPayload() { + return cloneBytes(sourceSnapshotPayload); + } + + @Override + public byte[] requestPayload() { + return cloneBytes(requestPayload); + } + + @Override + public byte[] membershipRolesPayload() { + return cloneBytes(membershipRolesPayload); + } + + @Override + public byte[] eventPayload() { + return cloneBytes(eventPayload); + } + + @Override + public byte[] auditPayload() { + return cloneBytes(auditPayload); + } + + @Override + public byte[] resultPayload() { + return cloneBytes(resultPayload); + } + + public AccountTenantCreationBootstrapResult result() { + if (!"COMMITTED".equals(status) + || membershipVersion == null + || membershipAuthorityGeneration == null + || eventSequence == null + || eventStreamKey == null + || eventRequestId == null + || eventId == null + || eventDigest == null + || auditEventId == null + || auditEventType == null + || auditPayloadDigest == null + || resultDigest == null) { + throw new IllegalStateException("Incomplete creator-bootstrap result is not replayable"); + } + return new AccountTenantCreationBootstrapResult( + requestId, + requestDigest, + initiatingAccountUuid, + tenantUuid, + creatorEvidenceDigest, + sourceSnapshotDigest, + java.util.Map.of(tenantUuid.toString(), Long.toString(membershipVersion)), + Long.toString(membershipAuthorityGeneration), + List.of("tenantAdmin"), + false, + eventStreamKey, + eventRequestId, + eventSequence, + eventId, + eventDigest, + auditEventId, + auditEventType, + auditPayloadDigest, + resultDigest); + } + + private static byte[] cloneBytes(byte[] bytes) { + return bytes == null ? null : bytes.clone(); + } + } + + public static final class OperationConflictException extends IllegalStateException { + public OperationConflictException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java index 8ece8ba979..6618c17601 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepository.java @@ -294,6 +294,95 @@ public AccountTenantMembership createFreshMembershipForJoin(UUID accountUuid, UU return readback; } + /** Account-fenced absence enrollment for the fresh creator owner; creates no membership. */ + @Transactional(propagation = Propagation.MANDATORY) + public PairAuthority prepareFreshCreatorAbsence(UUID accountUuid, UUID tenantUuid) { + requireOwnerWriteTransaction(); + Account account = lockCanonicalAccountByUuid(accountUuid); + VerifiedTenantProvenance provenance = readFreshProvenance(tenantUuid); + if (readCanonicalRow(account.getId(), tenantUuid, true) != null) { + throw new IllegalStateException("Fresh creator membership is not absent"); + } + Record retainedRoleHistoryCheck = + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM account_tenant_membership_role_snapshots roles " + + "JOIN account_tenant_membership member ON member.id = roles.membership_id " + + "WHERE member.account_id = ? AND member.tenant_uuid = ?)", + account.getId(), + tenantUuid); + if (retainedRoleHistoryCheck == null) { + throw new IllegalStateException("Fresh creator role history check is absent"); + } + if (!Boolean.FALSE.equals(retainedRoleHistoryCheck.get(0, Boolean.class))) { + throw new IllegalStateException("Fresh creator pair has retained role history"); + } + return pairAuthorityRepository.enrollAbsence(accountUuid, tenantUuid, provenance); + } + + /** Exact UUID source row, including a creator write awaiting its same-transaction event. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCanonicalMembershipForUpdate( + UUID accountUuid, UUID tenantUuid) { + requireOwnerWriteTransaction(); + requireCanonicalUuid(tenantUuid, "tenant UUID"); + Account account = lockCanonicalAccountByUuid(accountUuid); + VerifiedTenantProvenance provenance = readFreshProvenance(tenantUuid); + Record row = readCanonicalRow(account.getId(), tenantUuid, true); + if (row == null) return Optional.empty(); + AccountTenantMembership membership = toCanonicalEntity(row, account); + requireFreshMembershipIdentity(membership, account, tenantUuid, provenance); + return Optional.of(membership); + } + + /** Creates only the exact first control-only creator row from its durable absence pair. */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountTenantMembership createFreshCreatorMembership(UUID accountUuid, UUID tenantUuid) { + requireOwnerWriteTransaction(); + Account account = lockCanonicalAccountByUuid(accountUuid); + VerifiedTenantProvenance provenance = readFreshProvenance(tenantUuid); + if (readCanonicalRow(account.getId(), tenantUuid, true) != null) { + throw new IllegalStateException("Creator bootstrap cannot overwrite membership"); + } + PairAuthority baseline = + pairAuthorityRepository + .readForUpdate(accountUuid, tenantUuid) + .orElseThrow(() -> new IllegalStateException("Creator absence pair is absent")); + if (!new PairAuthority( + accountUuid, tenantUuid, provenance, false, 1L, 1L, 0L, null, null, false) + .equals(baseline)) { + throw new IllegalStateException("Creator pair differs from its exact absence baseline"); + } + Long id = + dsl.resultQuery( + "INSERT INTO account_tenant_membership (account_id, tenant_id, tenant_uuid, " + + "tenant_provenance_kind, tenant_source_operation_id, tenant_provenance_digest, " + + "gameplay_admission_allowed, lifecycle_state, membership_version, " + + "membership_authority_generation, authority_provenance) " + + "VALUES (?, NULL, ?, ?, ?, ?, FALSE, 'ACTIVE', 2, 1, 'TENANT_CREATION') RETURNING id", + account.getId(), + tenantUuid, + provenance.kind().name(), + provenance.sourceOperationId(), + provenance.digest()) + .fetchOne(0, Long.class); + AccountTenantMembership result = + findCanonicalMembershipForUpdate(accountUuid, tenantUuid) + .orElseThrow(() -> new IllegalStateException("Creator membership readback is absent")); + if (id == null + || id <= 0L + || !id.equals(result.getId()) + || result.getMembershipVersion() != 2L + || result.getMembershipAuthorityGeneration() != 1L + || result.isGameplayAdmissionAllowed() + || !"ACTIVE".equals(result.getLifecycleState()) + || !"TENANT_CREATION".equals(result.getAuthorityProvenance()) + || !Optional.of(baseline) + .equals(pairAuthorityRepository.readForUpdate(accountUuid, tenantUuid))) { + throw new IllegalStateException("Creator membership readback differs from its write"); + } + return result; + } + public boolean existsByAccountIdAndTenantId(Long accountId, Long tenantId) { requirePositiveNumericTenantId(tenantId); return dsl.fetchExists( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java new file mode 100644 index 0000000000..12f020dfb5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java @@ -0,0 +1,568 @@ +package net.firedevops.firemud.accountservice.service; + +import static net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.validatorSnapshot; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account-owned creator source composition; supplies no caller, authoring or gameplay authority. + */ +@Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected Account repositories are internal transaction collaborators.") +public class AccountCreatorMembershipSourceReader { + private static final String ISSUER = "firemud-account-service"; + private final AccountRepository accountRepository; + private final AccountJoinOperationRepository joinOperationRepository; + private final AccountTenantMembershipRepository membershipRepository; + private final AccountMembershipPairAuthorityRepository pairAuthorityRepository; + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; + private final FreshTenantIdentityAssociationRepository freshTenantIdentityAssociationRepository; + private final AccountAuthorityGenerationRepository authorityGenerationRepository; + private final AccountAuthorityOutboxRepository authorityOutboxRepository; + private final AccountAuthoritySourceEvidenceRepository sourceEvidenceRepository; + private final AccountTenantCreationBootstrapOperationRepository bootstrapOperations; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring proxies the non-final owner reader; constructor validates private collaborators.") + public AccountCreatorMembershipSourceReader( + AccountRepository accounts, + AccountJoinOperationRepository joins, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository pairs, + AccountTenantMembershipRoleSnapshotRepository roles, + FreshTenantIdentityAssociationRepository fresh, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox, + AccountAuthoritySourceEvidenceRepository sources, + AccountTenantCreationBootstrapOperationRepository bootstrapOperations) { + this.accountRepository = Objects.requireNonNull(accounts); + this.joinOperationRepository = Objects.requireNonNull(joins); + this.membershipRepository = Objects.requireNonNull(memberships); + this.pairAuthorityRepository = Objects.requireNonNull(pairs); + this.roleSnapshotRepository = Objects.requireNonNull(roles); + this.freshTenantIdentityAssociationRepository = Objects.requireNonNull(fresh); + this.authorityGenerationRepository = Objects.requireNonNull(generations); + this.authorityOutboxRepository = Objects.requireNonNull(outbox); + this.sourceEvidenceRepository = Objects.requireNonNull(sources); + this.bootstrapOperations = Objects.requireNonNull(bootstrapOperations); + } + + /** Explicit owner enrollment/readback, never an absent-row authority inference. */ + @Transactional(propagation = Propagation.MANDATORY) + public NeverJoinedMembershipSnapshot readFreshNeverJoinedMembershipSnapshot( + UUID accountUuid, UUID tenantUuid) { + requireWritableOwnerTransaction(); + requireCanonicalUuidInput(accountUuid, "Account UUID"); + requireCanonicalUuidInput(tenantUuid, "tenant UUID"); + Account account = + accountRepository + .findByAccountUuidForUpdate(accountUuid) + .orElseThrow(() -> new IllegalStateException("Fresh Account source is absent")); + requirePersistedAccountIdentity(account, accountUuid); + FreshTenantCreationEvidence creation = + freshTenantIdentityAssociationRepository + .read(tenantUuid) + .orElseThrow(() -> new IllegalStateException("Fresh tenant source is absent")); + CompositeSnapshot upstream = + authorityGenerationRepository.readCompositeSnapshot( + ISSUER, accountUuid, List.of(tenantUuid), List.of()); + readCurrentUpstreamSourceEvidence(accountUuid, tenantUuid, upstream); + bootstrapOperations.assertNoContradictoryMembershipHistory(accountUuid, tenantUuid); + String stream = membershipStreamKey(accountUuid, tenantUuid); + if (authorityOutboxRepository.readCheckpoint(stream).isPresent()) { + throw new IllegalStateException("Fresh creator membership has committed event history"); + } + ScopeState generation = + authorityGenerationRepository.initialize( + AuthorityScope.membership(accountUuid, tenantUuid)); + if (generation.generation() != 1L || generation.sourceVersion() != 1L) { + throw new IllegalStateException("Fresh creator membership generation is not pristine"); + } + PairAuthority pair = membershipRepository.prepareFreshCreatorAbsence(accountUuid, tenantUuid); + VerifiedTenantProvenance provenance = freshTenantProvenance(creation); + if (!new PairAuthority( + accountUuid, tenantUuid, provenance, false, 1L, 1L, 0L, null, null, false) + .equals(pair)) { + throw new IllegalStateException("Fresh creator pair baseline differs"); + } + CompositeSnapshot authority = readSnapshot(accountUuid, tenantUuid); + requireMatchingFence(authority, only(authority.memberships(), "membership"), accountUuid); + CurrentSourceEvidence sources = + readCurrentUpstreamSourceEvidence(accountUuid, tenantUuid, authority); + List checkpoints = new ArrayList<>(sources.checkpoints()); + checkpoints.add(new OutboxCheckpointEntry(stream, "0")); + requireUnchangedAccountIdentity(account, accountUuid); + if (!Optional.of(creation).equals(freshTenantIdentityAssociationRepository.read(tenantUuid)) + || authorityOutboxRepository.readCheckpoint(stream).isPresent()) { + throw new IllegalStateException("Fresh creator source changed during capture"); + } + return new NeverJoinedMembershipSnapshot( + accountUuid.toString(), + tenantUuid.toString(), + Map.of(tenantUuid.toString(), "1"), + "1", + currentAuthorityTuple(tenantUuid, authority, sources), + decimal(authority.issuanceFence().value()), + Instant.now(), + stream, + orderedCheckpoints(checkpoints), + sources.sourceEvidence()); + } + + @Transactional(propagation = Propagation.MANDATORY) + CreatorControlCaptureSources readExistingCreatorControlCaptureSources( + UUID accountUuid, UUID tenantUuid, Supplier verifiedOriginalReceipt) { + requireWritableOwnerTransaction(); + requireCanonicalUuidInput(accountUuid, "Account UUID"); + requireCanonicalUuidInput(tenantUuid, "tenant UUID"); + Account account = + accountRepository + .findByAccountUuid(accountUuid) + .orElseThrow(() -> new IllegalStateException("Creator Account source is absent")); + requirePersistedAccountIdentity(account, accountUuid); + joinOperationRepository.lockAccount(account.getId()); + CompositeSnapshot authority = readSnapshot(accountUuid, tenantUuid); + CurrentSourceEvidence upstream = + readCurrentUpstreamSourceEvidence(accountUuid, tenantUuid, authority); + FreshTenantCreationEvidence creation = + freshTenantIdentityAssociationRepository + .read(tenantUuid) + .orElseThrow(() -> new IllegalStateException("Creator fresh tenant source is absent")); + var receipt = Objects.requireNonNull(verifiedOriginalReceipt.get()); + var provenance = freshTenantProvenance(creation); + Identity identity = new Identity(account.getId(), null, accountUuid, tenantUuid, provenance); + PairAuthority pair = + pairAuthorityRepository + .readForUpdate(accountUuid, tenantUuid) + .orElseThrow(() -> new IllegalStateException("Creator pair source is absent")); + AccountTenantMembership membership = + membershipRepository + .findCanonicalMembershipForUpdate(accountUuid, tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Creator control membership source is absent")); + if (membership.getAccount() == null) { + throw new IllegalStateException("Creator control membership Account is absent"); + } + requirePersistedAccountIdentity(membership.getAccount(), accountUuid); + ScopeState memberSource = only(authority.memberships(), "membership"); + requireMatchingFence(authority, memberSource, accountUuid); + if (!"COMMITTED".equals(receipt.status()) + || !accountUuid.equals(receipt.initiatingAccountUuid()) + || !tenantUuid.equals(receipt.tenantUuid()) + || !creation.operationId().equals(receipt.creationOperationId()) + || !creation.creationRequestId().equals(receipt.creationRequestId()) + || !Objects.equals(account.getId(), membership.getAccount().getId()) + || !tenantUuid.equals(membership.getTenantUuid()) + || membership.getTenantId() != null + || !provenance.kind().name().equals(membership.getTenantProvenanceKind()) + || !provenance.sourceOperationId().equals(membership.getTenantSourceOperationId()) + || !provenance.digest().equals(membership.getTenantProvenanceDigest()) + || !"TENANT_CREATION".equals(membership.getAuthorityProvenance()) + || !"ACTIVE".equals(membership.getLifecycleState()) + || membership.isGameplayAdmissionAllowed() + || !Objects.equals(receipt.membershipId(), membership.getId()) + || !Objects.equals(receipt.membershipVersion(), membership.getMembershipVersion()) + || !Objects.equals( + receipt.membershipAuthorityGeneration(), membership.getMembershipAuthorityGeneration()) + || receipt.baselineEventSequence() != 0L + || membership.getMembershipVersion() + != Math.incrementExact(receipt.baselineMembershipVersion()) + || membership.getMembershipAuthorityGeneration() + != receipt.baselineMembershipAuthorityGeneration() + || memberSource.generation() != membership.getMembershipAuthorityGeneration()) { + throw new IllegalStateException( + "Creator control membership differs from its exact bootstrap source"); + } + RoleSnapshot roles = + roleSnapshotRepository + .findForCanonicalUpdate( + accountUuid, + tenantUuid, + provenance, + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(() -> new IllegalStateException("Creator control role source is absent")); + if (!List.of("tenantAdmin").equals(roles.roles()) + || roles.accountId() != account.getId() + || roles.tenantId() != null + || !accountUuid.equals(roles.accountUuid()) + || !tenantUuid.equals(roles.tenantUuid()) + || !provenance.equals(roles.tenantProvenance()) + || roles.membershipId() != membership.getId() + || roles.snapshotVersion() != membership.getMembershipVersion() + || !Arrays.equals( + receipt.membershipRolesPayload(), + "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8))) { + throw new IllegalStateException( + "Creator control roles differ from the exact bootstrap receipt"); + } + String stream = membershipStreamKey(identity); + Checkpoint checkpoint = + authorityOutboxRepository + .readCheckpoint(stream) + .orElseThrow( + () -> new IllegalStateException("Creator current event checkpoint is absent")); + Event event = + authorityOutboxRepository + .findEvent(stream, checkpoint.outboxSequence()) + .orElseThrow(() -> new IllegalStateException("Creator current event source is absent")); + MembershipEvent verified = verifyStoredEvent(event, identity, receipt.eventRequestId()); + if (checkpoint.outboxSequence() != 1L + || !checkpointMatches(checkpoint, event) + || !stream.equals(receipt.eventStreamKey()) + || !Objects.equals(receipt.eventSequence(), 1L) + || !event.eventId().equals(receipt.eventId()) + || !event.eventDigest().equals(receipt.eventDigest()) + || !Arrays.equals(event.payload(), receipt.eventPayload()) + || !pair.equals( + new PairAuthority( + accountUuid, + tenantUuid, + provenance, + true, + membership.getMembershipVersion(), + membership.getMembershipAuthorityGeneration(), + 1L, + event.eventId(), + event.eventDigest(), + false))) { + throw new IllegalStateException( + "Creator control event or pair differs from the bootstrap receipt"); + } + List checkpoints = new ArrayList<>(upstream.checkpoints()); + checkpoints.add(new OutboxCheckpointEntry(stream, "1")); + List sources = new ArrayList<>(upstream.sourceEvidence()); + sources.add(sourceEvidence(checkpoint, event)); + AuthorityTuple tuple = currentAuthorityTuple(tenantUuid, authority, upstream); + Map version = + Map.of(tenantUuid.toString(), Long.toString(membership.getMembershipVersion())); + var boundEvent = + RuntimeMembershipAuthorityEvidenceValidator.validate( + validatorSnapshot( + accountUuid.toString(), + tenantUuid.toString(), + true, + "ACTIVE", + false, + version, + Long.toString(memberSource.generation()), + List.of("tenantAdmin"), + tuple, + decimal(authority.issuanceFence().value()), + orderedCheckpoints(checkpoints), + orderedSourceEvidence(sources))); + if (boundEvent.isEmpty() + || !verified.canonicalJson().equals(boundEvent.orElseThrow().canonicalJson()) + || verified.callerBoundAuthorityInvalidated()) { + throw new IllegalStateException( + "Creator control event does not bind the current source capture"); + } + requireUnchangedAccountIdentity(account, accountUuid); + if (!Optional.of(creation).equals(freshTenantIdentityAssociationRepository.read(tenantUuid))) { + throw new IllegalStateException("Creator fresh tenant source changed during capture"); + } + return new CreatorControlCaptureSources( + accountUuid, + tenantUuid, + authority, + version, + tuple, + decimal(authority.issuanceFence().value()), + pair, + roles, + creation, + receipt, + verified, + orderedCheckpoints(checkpoints), + orderedSourceEvidence(sources), + Instant.now()); + } + + private CurrentSourceEvidence readCurrentUpstreamSourceEvidence( + UUID accountUuid, UUID tenantUuid, CompositeSnapshot authority) { + IssuerAccountSourceSnapshot source = + sourceEvidenceRepository.readCurrentIssuerAccountSources(ISSUER, accountUuid); + ScopeState tenant = only(authority.tenants(), "tenant"); + Account account = accountRepository.findByAccountUuid(accountUuid).orElseThrow(); + requirePersistedAccountIdentity(account, accountUuid); + if (!AuthorityScope.issuer(ISSUER).equals(authority.issuer().scope()) + || !AuthorityScope.account(accountUuid).equals(authority.account().scope()) + || !AuthorityScope.tenant(tenantUuid).equals(tenant.scope()) + || !authority.issuanceFence().equals(source.issuanceFence()) + || !authority.issuanceFence().equals(authority.account().issuanceFence()) + || !accountUuid.equals(authority.issuanceFence().accountId()) + || source.account().accountSourceNumericId() == null + || !Objects.equals(source.account().accountSourceNumericId(), account.getId()) + || source.issuer().generation() != authority.issuer().generation() + || source.issuer().sourceVersion() != authority.issuer().sourceVersion() + || source.account().generation() != authority.account().generation() + || source.account().sourceVersion() != authority.account().sourceVersion() + || tenant.generation() != 1L + || tenant.sourceVersion() != 1L + || authorityOutboxRepository + .readCheckpoint( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantUuid) + .isPresent()) { + throw new IllegalStateException( + "Current creator upstream sources are unavailable or mismatched"); + } + // The source repository proves complete retained histories and exact live Account state; + // these projections additionally validate their current closed source-event schemas. + net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + FreshTenantCreationEvidence fresh = + freshTenantIdentityAssociationRepository + .read(tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Current fresh tenant provenance is absent")); + if (!tenantUuid.equals(fresh.canonicalTenantId())) { + throw new IllegalStateException("Current fresh tenant provenance differs"); + } + List checkpoints = new ArrayList<>(); + List sources = new ArrayList<>(); + for (var current : List.of(source.issuer(), source.account())) { + var checkpoint = current.checkpoint(); + checkpoints.add( + new OutboxCheckpointEntry( + checkpoint.outboxStreamKey(), Long.toString(checkpoint.sequence()))); + if (checkpoint.sequence() > 0L) { + Checkpoint stored = + authorityOutboxRepository.readCheckpoint(checkpoint.outboxStreamKey()).orElseThrow(); + Event event = + authorityOutboxRepository + .findEvent(checkpoint.outboxStreamKey(), checkpoint.sequence()) + .orElseThrow(); + if (stored.outboxSequence() != checkpoint.sequence() + || !checkpoint.sourceEventId().orElseThrow().equals(stored.sourceEventId()) + || !checkpoint.sourceEventDigest().orElseThrow().equals(stored.sourceEventDigest())) { + throw new IllegalStateException("Current source checkpoint differs from owner proof"); + } + sources.add(sourceEvidence(stored, event)); + } + } + checkpoints.add( + new OutboxCheckpointEntry( + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + "tenant/" + tenantUuid, "0")); + return new CurrentSourceEvidence( + orderedCheckpoints(checkpoints), + orderedSourceEvidence(sources), + source + .account() + .accountSecurityCutoff() + .map( + c -> + new MembershipAuthorityEventV1Codec.AccountSecurityCutoff( + c.accountAuthorityGeneration(), c.outboxStreamKey(), c.outboxSequence()))); + } + + private CompositeSnapshot readSnapshot(UUID accountUuid, UUID tenantUuid) { + return authorityGenerationRepository.readCompositeSnapshot( + ISSUER, accountUuid, List.of(tenantUuid), List.of(tenantUuid)); + } + + private static AuthorityTuple currentAuthorityTuple( + UUID tenantUuid, CompositeSnapshot authority, CurrentSourceEvidence sources) { + return new AuthorityTuple( + decimal(authority.issuer().generation()), + decimal(authority.account().generation()), + Map.of(tenantUuid.toString(), decimal(only(authority.tenants(), "tenant").generation())), + Map.of( + tenantUuid.toString(), + decimal(only(authority.memberships(), "membership").generation())), + List.of(), + sources.accountSecurityCutoff(), + Optional.empty()); + } + + private static void requireMatchingFence( + CompositeSnapshot authority, ScopeState member, UUID accountUuid) { + if (!AuthorityScope.membership( + accountUuid, only(authority.tenants(), "tenant").scope().tenantId()) + .equals(member.scope()) + || !accountUuid.equals(authority.issuanceFence().accountId()) + || !authority.issuanceFence().equals(authority.account().issuanceFence()) + || !authority.issuanceFence().equals(member.issuanceFence())) { + throw new IllegalStateException("Creator membership source fence differs"); + } + } + + private static MembershipEvent verifyStoredEvent( + Event event, Identity identity, String requestId) { + MembershipEvent verified = + MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); + if (!requestId.equals(event.requestId()) + || !requestId.equals(verified.requestId()) + || !membershipStreamKey(identity).equals(event.outboxStreamKey()) + || !event.outboxStreamKey().equals(verified.outboxStreamKey()) + || event.outboxSequence() != 1L + || !"1".equals(verified.outboxSequence()) + || !event.eventId().equals(verified.eventId()) + || !event.eventDigest().equals(verified.eventDigest()) + || !UUID.nameUUIDFromBytes( + (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + requestId) + .getBytes(StandardCharsets.UTF_8)) + .toString() + .equals(verified.eventId()) + || !identity.accountUuid().toString().equals(verified.accountId()) + || !identity.tenantUuid().toString().equals(verified.tenantId()) + || !Arrays.equals(event.payload(), verified.canonicalJsonUtf8())) { + throw new IllegalStateException("Creator event differs from its immutable source columns"); + } + return verified; + } + + private static boolean checkpointMatches(Checkpoint c, Event e) { + return c.outboxStreamKey().equals(e.outboxStreamKey()) + && c.outboxSequence() == e.outboxSequence() + && c.sourceEventId().equals(e.eventId()) + && c.sourceEventDigest().equals(e.eventDigest()); + } + + private static OutboxSourceEvidence sourceEvidence(Checkpoint c, Event e) { + if (!checkpointMatches(c, e)) + throw new IllegalStateException("Creator checkpoint differs from event"); + return new OutboxSourceEvidence( + c.outboxStreamKey(), + Long.toString(c.outboxSequence()), + e.eventId(), + e.eventDigest(), + new String(e.payload(), StandardCharsets.UTF_8)); + } + + private static List orderedCheckpoints( + List values) { + return values.stream() + .sorted(Comparator.comparing(OutboxCheckpointEntry::outboxStreamKey)) + .toList(); + } + + private static List orderedSourceEvidence( + List values) { + return values.stream() + .sorted(Comparator.comparing(OutboxSourceEvidence::outboxStreamKey)) + .toList(); + } + + private static ScopeState only(List values, String label) { + if (values.size() != 1) + throw new IllegalStateException("Expected exactly one " + label + " source"); + return values.getFirst(); + } + + private static VerifiedTenantProvenance freshTenantProvenance(FreshTenantCreationEvidence fresh) { + return new VerifiedTenantProvenance( + null, TenantProvenanceKind.FRESH_GAME_DESIGN, fresh.operationId(), fresh.evidenceDigest()); + } + + private static void requireCanonicalUuidInput(UUID uuid, String label) { + if (uuid == null || new UUID(0L, 0L).equals(uuid)) + throw new IllegalArgumentException(label + " must be non-nil"); + } + + private static void requirePersistedAccountIdentity(Account account, UUID uuid) { + if (account == null + || account.getId() == null + || account.getId() <= 0L + || !uuid.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() != AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT + || !account.getId().equals(account.getAccountUuidSourceNumericId())) { + throw new IllegalStateException("Creator Account source identity differs"); + } + } + + private void requireUnchangedAccountIdentity(Account before, UUID uuid) { + Account after = accountRepository.findByAccountUuid(uuid).orElseThrow(); + requirePersistedAccountIdentity(after, uuid); + if (!before.getId().equals(after.getId())) + throw new IllegalStateException("Creator Account identity changed"); + } + + private static String decimal(long value) { + if (value <= 0L) throw new IllegalStateException("Creator source counters must be positive"); + return Long.toString(value); + } + + private static String membershipStreamKey(Identity identity) { + return membershipStreamKey(identity.accountUuid(), identity.tenantUuid()); + } + + private static String membershipStreamKey(UUID account, UUID tenant) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + account + + "/" + + tenant; + } + + private static void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Creator source capture requires a writable Account owner transaction"); + } + } + + private record Identity( + long accountId, + Long legacyTenantId, + UUID accountUuid, + UUID tenantUuid, + VerifiedTenantProvenance provenance) {} + + private record CurrentSourceEvidence( + List checkpoints, + List sourceEvidence, + Optional accountSecurityCutoff) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index b5bd710108..87d7b8dbac 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -2,7 +2,10 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -32,11 +35,16 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -50,6 +58,10 @@ public class AccountMembershipAuthorityEventProducer { private static final String ACCOUNT_JWT_ISSUER = "firemud-account-service"; private static final int MAX_REQUEST_ID_LENGTH = 128; private static final int MAX_CALLER_BINDING_LENGTH = 128; + private static final Comparator OUTBOX_CHECKPOINT_ORDER = + Comparator.comparing( + OutboxCheckpointEntry::outboxStreamKey, + AccountMembershipAuthorityEventProducer::compareUnsignedUtf8); private final AccountJoinOperationRepository joinOperationRepository; private final AccountRepository accountRepository; @@ -716,6 +728,283 @@ private static void requireBoundedText(String value, String label, int maxCodePo } } + public record OutboxCheckpointEntry(String outboxStreamKey, String outboxSequence) { + public OutboxCheckpointEntry { + Objects.requireNonNull(outboxStreamKey, "authority outbox stream key is required"); + Objects.requireNonNull(outboxSequence, "authority outbox sequence is required"); + if (!outboxStreamKey.startsWith(MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX) + || !isNonnegativeCanonicalDecimal(outboxSequence)) { + throw new IllegalArgumentException("Account authority checkpoint is not canonical"); + } + } + } + + /** Positive committed source-event identity kept outside the two-field checkpoint carrier. */ + public record OutboxSourceEvidence( + String outboxStreamKey, + String outboxSequence, + String eventId, + String eventDigest, + String canonicalEventJson) { + public OutboxSourceEvidence { + Objects.requireNonNull(outboxStreamKey, "authority outbox stream key is required"); + Objects.requireNonNull(outboxSequence, "authority outbox sequence is required"); + if (eventId == null || eventId.isBlank()) { + throw new IllegalArgumentException("source event ID is required"); + } + Objects.requireNonNull(eventDigest, "source event digest is required"); + Objects.requireNonNull(canonicalEventJson, "canonical source event JSON is required"); + if (!outboxStreamKey.startsWith(MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX) + || !isPositiveCanonicalDecimal(outboxSequence) + || !eventDigest.matches("sha256:[0-9a-f]{64}") + || !canonicalEventJson.startsWith("{") + || !canonicalEventJson.endsWith("}")) { + throw new IllegalArgumentException( + "Account authority source event evidence is not canonical"); + } + } + } + + /** + * Local V36 absence evidence with an exact one-tenant membership-version map. The sequence-zero + * checkpoints carry no source event identity or digest and never authorize gameplay. + */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The constructor stores immutable Map.copyOf and List.copyOf values.") + public record NeverJoinedMembershipSnapshot( + String accountId, + String tenantId, + Map membershipVersion, + String membershipAuthorityGeneration, + AuthorityTuple authorityTuple, + String issuanceFence, + Instant evaluatedAt, + String outboxStreamKey, + List outboxCheckpoints, + List outboxSourceEvidence) { + public NeverJoinedMembershipSnapshot { + accountId = requireCanonicalUuid(accountId, "canonical Account UUID"); + tenantId = requireCanonicalUuid(tenantId, "canonical tenant UUID"); + membershipVersion = + requireExactPositiveVersionMap(membershipVersion, tenantId, "membership version"); + membershipAuthorityGeneration = + requirePositiveCanonicalDecimal( + membershipAuthorityGeneration, "membership authority generation"); + Objects.requireNonNull(authorityTuple, "complete authority tuple is required"); + issuanceFence = requirePositiveCanonicalDecimal(issuanceFence, "Account issuance fence"); + Objects.requireNonNull(evaluatedAt, "Account evaluation time is required"); + outboxStreamKey = + Objects.requireNonNull(outboxStreamKey, "membership stream key is required"); + outboxCheckpoints = requireOrderedCheckpointSet(outboxCheckpoints); + outboxSourceEvidence = List.copyOf(outboxSourceEvidence); + + if (!"1".equals(membershipAuthorityGeneration) + || !membershipAuthorityGeneration.equals( + authorityTuple.membershipAuthorityGeneration().get(tenantId)) + || !"1".equals(membershipVersion.get(tenantId)) + || !authorityTuple.privateRealmGrantVersions().isEmpty() + || authorityTuple.tenantBillingCutoff().isPresent()) { + throw new IllegalArgumentException( + "Never-joined Account authority tuple is incomplete or mismatched"); + } + + String expectedStreamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountId + + "/" + + tenantId; + if (!expectedStreamKey.equals(outboxStreamKey)) { + throw new IllegalArgumentException( + "Never-joined Account membership stream key is not canonical"); + } + List membershipCheckpoints = + outboxCheckpoints.stream() + .filter(checkpoint -> checkpoint.outboxStreamKey().equals(expectedStreamKey)) + .toList(); + if (membershipCheckpoints.size() != 1 + || !"0".equals(membershipCheckpoints.getFirst().outboxSequence())) { + throw new IllegalArgumentException( + "Never-joined Account snapshot must retain a sequence-zero membership checkpoint"); + } + if (RuntimeMembershipAuthorityEvidenceValidator.validate( + validatorSnapshot( + accountId, + tenantId, + false, + "MISSING", + false, + membershipVersion, + membershipAuthorityGeneration, + List.of(), + authorityTuple, + issuanceFence, + outboxCheckpoints, + outboxSourceEvidence)) + .isPresent()) { + throw new IllegalArgumentException( + "Never-joined Account snapshot cannot contain a membership event"); + } + } + + public boolean membershipExists() { + return false; + } + + public String membershipLifecycleState() { + return "MISSING"; + } + + public List roles() { + return List.of(); + } + + public boolean gameplayAdmissionAllowed() { + return false; + } + } + + /** Existing control-only source evidence, never a runtime admission or authoring permission. */ + public record CreatorControlCaptureSources( + UUID accountUuid, + UUID tenantUuid, + CompositeSnapshot authoritySnapshot, + Map membershipVersion, + AuthorityTuple authorityTuple, + String issuanceFence, + PairAuthority pairSource, + RoleSnapshot roleSource, + FreshTenantCreationEvidence creationSource, + StoredOperation bootstrapReceipt, + MembershipEvent sourceEvent, + List outboxCheckpoints, + List outboxSourceEvidence, + Instant evaluatedAt) { + public CreatorControlCaptureSources { + membershipVersion = Map.copyOf(membershipVersion); + outboxCheckpoints = List.copyOf(outboxCheckpoints); + outboxSourceEvidence = List.copyOf(outboxSourceEvidence); + } + } + + private static String requireCanonicalUuid(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + try { + if (!UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical lowercase UUID"); + } + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(field + " must be a canonical lowercase UUID", exception); + } + return value; + } + + private static String requirePositiveCanonicalDecimal(String value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (!isPositiveCanonicalDecimal(value)) { + throw new IllegalArgumentException( + field + " must be a positive canonical unsigned decimal string"); + } + return value; + } + + private static boolean isPositiveCanonicalDecimal(String value) { + return value != null && value.matches("[1-9][0-9]*"); + } + + private static boolean isNonnegativeCanonicalDecimal(String value) { + return value != null && value.matches("0|[1-9][0-9]*"); + } + + private static Map requireExactPositiveVersionMap( + Map value, String tenantId, String field) { + Objects.requireNonNull(value, field + " map is required"); + if (value.size() != 1 + || !value.containsKey(tenantId) + || !isPositiveCanonicalDecimal(value.get(tenantId))) { + throw new IllegalArgumentException(field + " must be a positive canonical one-tenant map"); + } + return Map.copyOf(value); + } + + private static List requireOrderedCheckpointSet( + List checkpoints) { + Objects.requireNonNull(checkpoints, "Account authority checkpoints are required"); + List copy = List.copyOf(checkpoints); + ArrayList ordered = new ArrayList<>(copy); + ordered.sort(OUTBOX_CHECKPOINT_ORDER); + if (!copy.equals(ordered)) { + throw new IllegalArgumentException( + "Account authority checkpoints must use canonical stream-key order"); + } + for (int index = 1; index < copy.size(); index++) { + if (copy.get(index - 1).outboxStreamKey().equals(copy.get(index).outboxStreamKey())) { + throw new IllegalArgumentException( + "Account authority checkpoint stream keys must be unique"); + } + } + return copy; + } + + static Snapshot validatorSnapshot( + String accountId, + String tenantId, + boolean membershipExists, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + Map membershipVersion, + String membershipAuthorityGeneration, + List roles, + AuthorityTuple authorityTuple, + String issuanceFence, + List checkpoints, + List sourceEvidence) { + return new Snapshot( + ACCOUNT_JWT_ISSUER, + accountId, + tenantId, + membershipExists, + membershipLifecycleState, + gameplayAdmissionAllowed, + membershipVersion, + membershipAuthorityGeneration, + roles, + authorityTuple, + issuanceFence, + checkpoints.stream() + .map( + checkpoint -> + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + checkpoint.outboxStreamKey(), checkpoint.outboxSequence())) + .toList(), + sourceEvidence.stream() + .map( + source -> + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + source.outboxStreamKey(), + source.outboxSequence(), + source.eventId(), + source.eventDigest(), + source.canonicalEventJson())) + .toList()); + } + + private static int compareUnsignedUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int comparison = + Integer.compare( + Byte.toUnsignedInt(leftBytes[index]), Byte.toUnsignedInt(rightBytes[index])); + if (comparison != 0) { + return comparison; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + private static void requireWritableOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java new file mode 100644 index 0000000000..43ad8d45e4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapAuthorizationSource.java @@ -0,0 +1,20 @@ +package net.firedevops.firemud.accountservice.service; + +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.dto.AccountTenantCreationBootstrapResult; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; + +/** + * Account-owned authorization/source participant required for a new creator bootstrap commit. + * + *

The implementation must authenticate the initiating Account and exact source operation, verify + * the current Account authorization named by the creator evidence, and hold or participate in that + * source's commit fence until {@code mutationWhileCurrent} returns and the enclosing Account + * transaction commits. The immutable DTO alone is never authorization. No production implementation + * is registered by this storage slice, so new creator bootstrap attempts are default-denied. + */ +public interface AccountTenantCreationBootstrapAuthorizationSource { + AccountTenantCreationBootstrapResult withCurrentAuthorizationAndSourceParticipation( + FreshTenantCreatorEvidence evidence, + Supplier mutationWhileCurrent); +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java new file mode 100644 index 0000000000..1dc443a273 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java @@ -0,0 +1,792 @@ +package net.firedevops.firemud.accountservice.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.dto.AccountAuditEnvelope; +import net.firedevops.firemud.accountservice.dto.AccountAuditTenantIdentity; +import net.firedevops.firemud.accountservice.dto.AccountTenantCreationBootstrapResult; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Checkpoint; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.Event; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository.EventEvidence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairTransition; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Claim; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned atomic membership bootstrap for an exact fresh tenant creator operation. + * + *

This service is intentionally not exposed by REST or gRPC. A new commit requires a separately + * registered current Account authorization/source participant; no such production participant is + * registered by this slice, so new bootstrap attempts remain default-denied. + */ +@Service +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account repositories and source participants are internal collaborators.") +public class AccountTenantCreationBootstrapService { + public static final String AUDIT_EVENT_TYPE = "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED"; + private static final String ROLE_SNAPSHOT_JSON = "[\"tenantAdmin\"]"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final AccountRepository accountRepository; + private final FreshTenantIdentityAssociationRepository tenantAssociationRepository; + private final AccountCreatorMembershipSourceReader creatorSourceReader; + private final AccountMembershipPairAuthorityRepository pairAuthorityRepository; + private final AccountTenantMembershipRepository membershipRepository; + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; + private final AccountAuthorityOutboxRepository authorityOutboxRepository; + private final AccountAuditOutboxRepository auditOutboxRepository; + private final AccountTenantCreationBootstrapOperationRepository operationRepository; + private final ObjectProvider + authorizationSourceProvider; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Spring transaction proxy requires a non-final class; constructor only validates its internal collaborators and publishes no partial instance.") + public AccountTenantCreationBootstrapService( + AccountRepository accountRepository, + FreshTenantIdentityAssociationRepository tenantAssociationRepository, + AccountCreatorMembershipSourceReader creatorSourceReader, + AccountMembershipPairAuthorityRepository pairAuthorityRepository, + AccountTenantMembershipRepository membershipRepository, + AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository, + AccountAuthorityOutboxRepository authorityOutboxRepository, + AccountAuditOutboxRepository auditOutboxRepository, + AccountTenantCreationBootstrapOperationRepository operationRepository, + ObjectProvider + authorizationSourceProvider) { + this.accountRepository = Objects.requireNonNull(accountRepository); + this.tenantAssociationRepository = Objects.requireNonNull(tenantAssociationRepository); + this.creatorSourceReader = Objects.requireNonNull(creatorSourceReader); + this.pairAuthorityRepository = Objects.requireNonNull(pairAuthorityRepository); + this.membershipRepository = Objects.requireNonNull(membershipRepository); + this.roleSnapshotRepository = Objects.requireNonNull(roleSnapshotRepository); + this.authorityOutboxRepository = Objects.requireNonNull(authorityOutboxRepository); + this.auditOutboxRepository = Objects.requireNonNull(auditOutboxRepository); + this.operationRepository = Objects.requireNonNull(operationRepository); + this.authorizationSourceProvider = Objects.requireNonNull(authorizationSourceProvider); + } + + /** + * Replays only an exact committed historical result, or runs a new commit under a current-source + * participant. The creator evidence value itself is data and does not authorize this method. + */ + @Transactional + public AccountTenantCreationBootstrapResult bootstrap(FreshTenantCreatorEvidence evidence) { + requireWritableOwnerTransaction(); + Objects.requireNonNull(evidence, "Authenticated creator evidence is required"); + UUID creatorUuid = evidence.initiatingAccountId(); + UUID tenantUuid = evidence.creationEvidence().canonicalTenantId(); + Account creator = + accountRepository + .findByAccountUuidForUpdate(creatorUuid) + .orElseThrow(() -> new IllegalStateException("Creator Account row is absent")); + requireAccountIdentity(creator, creatorUuid); + + UUID requestId = evidence.accountAuthorizationOperationId(); + Optional original = operationRepository.findForUpdate(requestId); + if (original.isPresent()) { + return replayExactOriginal(evidence, original.orElseThrow()); + } + Optional tenantOperation = operationRepository.findRequestIdByTenantForUpdate(tenantUuid); + if (tenantOperation.isPresent()) { + throw new AccountTenantCreationBootstrapOperationRepository.OperationConflictException( + "Fresh tenant already has a different immutable creator-bootstrap operation"); + } + + AccountTenantCreationBootstrapAuthorizationSource currentSource = + authorizationSourceProvider.getIfAvailable(); + if (currentSource == null) { + throw new IllegalStateException( + "No current Account creator-authorization/source participant is registered"); + } + AtomicBoolean callbackRan = new AtomicBoolean(); + AtomicReference committed = new AtomicReference<>(); + AccountTenantCreationBootstrapResult returned = + currentSource.withCurrentAuthorizationAndSourceParticipation( + evidence, + () -> { + if (!callbackRan.compareAndSet(false, true)) { + throw new IllegalStateException( + "Account creator authorization/source participant repeated its commit callback"); + } + AccountTenantCreationBootstrapResult result = commitNew(evidence, creator); + committed.set(result); + return result; + }); + if (!callbackRan.get() || returned == null || !returned.equals(committed.get())) { + throw new IllegalStateException( + "Account creator authorization/source participant did not preserve the owner result"); + } + return returned; + } + + /** + * Reads an already committed creator-control source under the existing Account/source locks. This + * immutable source capture authenticates no caller and grants no authoring or gameplay + * permission. Historical receipt recovery is verified separately from current source equality. + */ + @Transactional(propagation = org.springframework.transaction.annotation.Propagation.MANDATORY) + public AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources + readExistingCreatorControlCaptureSources(UUID accountUuid, UUID tenantUuid) { + requireWritableOwnerTransaction(); + return creatorSourceReader.readExistingCreatorControlCaptureSources( + accountUuid, + tenantUuid, + () -> { + UUID requestId = + operationRepository + .findRequestIdByTenantForUpdate(tenantUuid) + .orElseThrow( + () -> + new IllegalStateException( + "Committed creator-bootstrap operation is absent")); + StoredOperation operation = + operationRepository + .findForUpdate(requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Committed creator-bootstrap receipt is absent")); + FreshTenantCreationEvidence creation = + tenantAssociationRepository + .read(tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Creator fresh tenant source is absent")); + if (!accountUuid.equals(operation.initiatingAccountUuid())) { + throw new IllegalStateException("Creator-bootstrap receipt belongs to another Account"); + } + FreshTenantCreatorEvidence evidence = + new FreshTenantCreatorEvidence( + 1, + creation, + accountUuid, + operation.accountAuthorizationOperationId(), + operation.accountAuthorizationDigest(), + operation.creatorEvidenceDigest()); + replayExactOriginal(evidence, operation); + operationRepository.assertNoContradictoryMembershipHistory(accountUuid, tenantUuid); + return operation; + }); + } + + private AccountTenantCreationBootstrapResult commitNew( + FreshTenantCreatorEvidence evidence, Account creator) { + requireWritableOwnerTransaction(); + UUID creatorUuid = evidence.initiatingAccountId(); + UUID tenantUuid = evidence.creationEvidence().canonicalTenantId(); + FreshTenantCreationEvidence associated = + tenantAssociationRepository + .read(tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Fresh Game Design tenant source is absent")); + if (!associated.equals(evidence.creationEvidence())) { + throw new IllegalStateException( + "Fresh Game Design tenant source differs from creator qualification evidence"); + } + + AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot baseline = + creatorSourceReader.readFreshNeverJoinedMembershipSnapshot(creatorUuid, tenantUuid); + if (!creatorUuid.toString().equals(baseline.accountId()) + || !tenantUuid.toString().equals(baseline.tenantId()) + || baseline.membershipExists() + || !"MISSING".equals(baseline.membershipLifecycleState()) + || baseline.gameplayAdmissionAllowed() + || !List.of( + new AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry( + baseline.outboxStreamKey(), "0")) + .equals( + baseline.outboxCheckpoints().stream() + .filter( + checkpoint -> + checkpoint.outboxStreamKey().equals(baseline.outboxStreamKey())) + .toList())) { + throw new IllegalStateException( + "Creator bootstrap baseline is not exact sequence-zero absence"); + } + + operationRepository.assertNoContradictoryMembershipHistory(creatorUuid, tenantUuid); + VerifiedTenantProvenance provenance = freshProvenance(associated); + PairAuthority priorPair = + pairAuthorityRepository + .readForUpdate(creatorUuid, tenantUuid) + .orElseThrow( + () -> new IllegalStateException("Positive creator membership baseline is absent")); + long baselineVersion = + positiveLong(baseline.membershipVersion().get(tenantUuid.toString()), "membership version"); + long baselineGeneration = + positiveLong(baseline.membershipAuthorityGeneration(), "membership authority generation"); + if (!priorPair.accountUuid().equals(creatorUuid) + || !priorPair.tenantUuid().equals(tenantUuid) + || !priorPair.provenance().equals(provenance) + || priorPair.membershipExists() + || priorPair.membershipVersion() != baselineVersion + || priorPair.membershipAuthorityGeneration() != baselineGeneration + || priorPair.eventSequence() != 0L + || priorPair.eventId() != null + || priorPair.eventDigest() != null + || priorPair.lastTransitionInvalidated()) { + throw new IllegalStateException("Creator pair differs from its same-fence positive baseline"); + } + + byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); + byte[] sourcePayload = AccountTenantCreationBootstrapDigest.sourceSnapshotPayload(baseline); + String sourceDigest = AccountTenantCreationBootstrapDigest.sha256(sourcePayload); + byte[] requestPayload = + AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload); + String requestDigest = AccountTenantCreationBootstrapDigest.sha256(requestPayload); + Claim claim = + operationRepository.claim( + evidence, + creatorPayload, + sourcePayload, + sourceDigest, + requestPayload, + requestDigest, + baselineVersion, + baselineGeneration); + if (!claim.claimed()) { + return replayExactOriginal(evidence, claim.operation()); + } + + long newVersion = increment(baselineVersion, "membership version"); + AccountTenantMembership persisted = + membershipRepository.createFreshCreatorMembership(creatorUuid, tenantUuid); + RoleSnapshot roles = + roleSnapshotRepository.replaceCanonical( + persisted, creatorUuid, tenantUuid, provenance, newVersion, List.of("tenantAdmin")); + if (!roles.roles().equals(List.of("tenantAdmin"))) { + throw new IllegalStateException("Creator membership role readback is not tenantAdmin-only"); + } + + String requestId = evidence.accountAuthorizationOperationId().toString(); + String streamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + creatorUuid + + "/" + + tenantUuid; + if (authorityOutboxRepository.readCheckpoint(streamKey).isPresent()) { + throw new IllegalStateException( + "Creator membership stream acquired history before bootstrap"); + } + String eventId = + UUID.nameUUIDFromBytes( + (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + requestId) + .getBytes(StandardCharsets.UTF_8)) + .toString(); + MembershipEvent[] candidate = new MembershipEvent[1]; + Event event = + authorityOutboxRepository.append( + streamKey, + requestId, + sequence -> { + if (sequence != 1L) { + throw new IllegalStateException( + "First creator membership event must use sequence one"); + } + MembershipEvent sealed = + MembershipAuthorityEventV1Codec.seal( + eventPreimage( + baseline, + creatorUuid, + tenantUuid, + newVersion, + baselineGeneration, + streamKey, + requestId, + eventId)); + candidate[0] = sealed; + return new EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + MembershipEvent expectedEvent = candidate[0]; + Event eventReadback = + authorityOutboxRepository + .findEvent(streamKey, requestId) + .orElseThrow( + () -> new IllegalStateException("Creator membership event readback is absent")); + Checkpoint checkpoint = + authorityOutboxRepository + .readCheckpoint(streamKey) + .orElseThrow( + () -> new IllegalStateException("Creator membership checkpoint is absent")); + MembershipEvent verifiedEvent = + MembershipAuthorityEventV1Codec.verify( + new String(eventReadback.payload(), StandardCharsets.UTF_8)); + if (expectedEvent == null + || !event.equals(eventReadback) + || !checkpoint.outboxStreamKey().equals(streamKey) + || checkpoint.outboxSequence() != 1L + || !checkpoint.sourceEventId().equals(event.eventId()) + || !checkpoint.sourceEventDigest().equals(event.eventDigest()) + || !verifiedEvent.canonicalJson().equals(expectedEvent.canonicalJson()) + || !verifiedEvent.roles().equals(List.of("tenantAdmin")) + || verifiedEvent.gameplayAdmissionAllowed() + || verifiedEvent.callerBoundAuthorityInvalidated() + || !Long.toString(newVersion) + .equals(verifiedEvent.membershipVersion().get(tenantUuid.toString()))) { + throw new IllegalStateException("Creator membership event or checkpoint readback differs"); + } + + PairAuthority advanced = + pairAuthorityRepository.commitTransition( + priorPair, new PairTransition(true, 1L, event.eventId(), event.eventDigest(), false)); + if (!advanced.membershipExists() + || advanced.membershipVersion() != newVersion + || advanced.membershipAuthorityGeneration() != baselineGeneration + || advanced.eventSequence() != 1L + || !event.eventId().equals(advanced.eventId()) + || !event.eventDigest().equals(advanced.eventDigest()) + || advanced.lastTransitionInvalidated()) { + throw new IllegalStateException("Creator membership pair transition readback differs"); + } + + byte[] rolesPayload = ROLE_SNAPSHOT_JSON.getBytes(StandardCharsets.UTF_8); + UUID auditEventId = + UUID.nameUUIDFromBytes( + ("account-tenant-creation-bootstrap-audit/v1:" + requestId) + .getBytes(StandardCharsets.UTF_8)); + byte[] auditPayload = + auditPayload( + evidence, + requestDigest, + sourceDigest, + newVersion, + baselineGeneration, + event, + checkpoint); + String auditText = new String(auditPayload, StandardCharsets.UTF_8); + AccountAuditEnvelope audit = + auditOutboxRepository.appendCanonicalTenant( + auditEventId, tenantUuid.toString(), AUDIT_EVENT_TYPE, auditText); + byte[] resultPayload = + AccountTenantCreationBootstrapDigest.resultPayload( + requestId, + requestDigest, + sourceDigest, + tenantUuid, + verifiedEvent.membershipVersion(), + Long.toString(baselineGeneration), + streamKey, + requestId, + checkpoint.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.payload(), + audit.auditEventId(), + audit.eventType(), + audit.occurredAt().toString(), + audit.payloadDigest(), + audit.payload().getBytes(StandardCharsets.UTF_8), + creatorPayload, + sourcePayload); + String resultDigest = AccountTenantCreationBootstrapDigest.sha256(resultPayload); + StoredOperation completed = + operationRepository.complete( + evidence.accountAuthorizationOperationId(), + new Completion( + persisted.getId(), + newVersion, + baselineGeneration, + "ACTIVE", + false, + rolesPayload, + streamKey, + requestId, + checkpoint.outboxSequence(), + event.eventId(), + event.eventDigest(), + false, + event.payload(), + audit.auditEventId(), + audit.eventType(), + audit.occurredAt(), + audit.payloadDigest(), + audit.payload().getBytes(StandardCharsets.UTF_8), + resultPayload, + resultDigest)); + + verifyCommittedReadback(completed, persisted, roles, advanced, event, audit); + return completed.result(); + } + + private AccountTenantCreationBootstrapResult replayExactOriginal( + FreshTenantCreatorEvidence evidence, StoredOperation operation) { + byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); + if (!operation.requestId().equals(evidence.accountAuthorizationOperationId()) + || !operation.initiatingAccountUuid().equals(evidence.initiatingAccountId()) + || !operation.tenantUuid().equals(evidence.creationEvidence().canonicalTenantId()) + || !Arrays.equals(operation.creatorEvidencePayload(), creatorPayload) + || !operation.creatorEvidenceDigest().equals(evidence.evidenceDigest()) + || !operation.creationOperationId().equals(evidence.creationEvidence().operationId()) + || !operation.creationRequestId().equals(evidence.creationEvidence().creationRequestId()) + || !operation + .accountAuthorizationOperationId() + .equals(evidence.accountAuthorizationOperationId()) + || !operation.accountAuthorizationDigest().equals(evidence.accountAuthorizationDigest())) { + throw new AccountTenantCreationBootstrapOperationRepository.OperationConflictException( + "Creator-bootstrap operation ID was reused with changed creator or authorization source"); + } + requireCommittedOperation(operation); + byte[] sourcePayload = operation.sourceSnapshotPayload(); + byte[] requestPayload = + AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload); + if (!AccountTenantCreationBootstrapDigest.sha256(sourcePayload) + .equals(operation.sourceSnapshotDigest()) + || !Arrays.equals(requestPayload, operation.requestPayload()) + || !AccountTenantCreationBootstrapDigest.sha256(requestPayload) + .equals(operation.requestDigest()) + || !AccountTenantCreationBootstrapDigest.sha256(operation.resultPayload()) + .equals(operation.resultDigest())) { + throw new IllegalStateException( + "Creator-bootstrap immutable source or result digest differs"); + } + + MembershipEvent event = + MembershipAuthorityEventV1Codec.verify( + new String(operation.eventPayload(), StandardCharsets.UTF_8)); + String expectedStream = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + evidence.initiatingAccountId() + + "/" + + evidence.creationEvidence().canonicalTenantId(); + if (!expectedStream.equals(operation.eventStreamKey()) + || !operation.requestId().toString().equals(operation.eventRequestId()) + || operation.eventSequence() != 1L + || !event.outboxStreamKey().equals(operation.eventStreamKey()) + || !event.requestId().equals(operation.eventRequestId()) + || !event.eventId().equals(operation.eventId()) + || !event.eventDigest().equals(operation.eventDigest()) + || !"ACTIVE".equals(event.membershipLifecycleState()) + || event.gameplayAdmissionAllowed() + || event.callerBoundAuthorityInvalidated() + || !event.roles().equals(List.of("tenantAdmin")) + || !Map.of(operation.tenantUuid().toString(), Long.toString(operation.membershipVersion())) + .equals(event.membershipVersion())) { + throw new IllegalStateException("Creator-bootstrap historical event receipt is inconsistent"); + } + Event originalEvent = + authorityOutboxRepository + .findEvent(operation.eventStreamKey(), operation.eventRequestId()) + .orElseThrow(() -> new IllegalStateException("Original creator event is absent")); + if (originalEvent.outboxSequence() != operation.eventSequence() + || !originalEvent.eventId().equals(operation.eventId()) + || !originalEvent.eventDigest().equals(operation.eventDigest()) + || !Arrays.equals(originalEvent.payload(), operation.eventPayload())) { + throw new IllegalStateException("Original creator event readback differs from its receipt"); + } + + AccountAuditEnvelope expectedAudit = auditEnvelope(operation); + AccountAuditEnvelope actualAudit = + auditOutboxRepository + .findExactCanonicalTenantEnvelopeForUpdate(expectedAudit) + .orElseThrow( + () -> new IllegalStateException("Original creator audit envelope is absent")); + if (!actualAudit.equals(expectedAudit)) { + throw new IllegalStateException("Original creator audit envelope differs from its receipt"); + } + byte[] expectedResultPayload = + AccountTenantCreationBootstrapDigest.resultPayload( + operation.requestId().toString(), + operation.requestDigest(), + operation.sourceSnapshotDigest(), + operation.tenantUuid(), + event.membershipVersion(), + Long.toString(operation.membershipAuthorityGeneration()), + operation.eventStreamKey(), + operation.eventRequestId(), + operation.eventSequence(), + operation.eventId(), + operation.eventDigest(), + operation.eventPayload(), + operation.auditEventId(), + operation.auditEventType(), + operation.auditOccurredAt().toString(), + operation.auditPayloadDigest(), + operation.auditPayload(), + operation.creatorEvidencePayload(), + operation.sourceSnapshotPayload()); + if (!Arrays.equals(expectedResultPayload, operation.resultPayload())) { + throw new IllegalStateException("Creator-bootstrap historical result bytes differ"); + } + // This is immutable historical recovery. It intentionally does not read or rewrite current + // membership, roles, pair authority, or later JOIN state. + return operation.result(); + } + + private void verifyCommittedReadback( + StoredOperation completed, + AccountTenantMembership expectedMembership, + RoleSnapshot expectedRoles, + PairAuthority expectedPair, + Event expectedEvent, + AccountAuditEnvelope expectedAudit) { + AccountTenantMembership membership = + membershipRepository + .findCanonicalMembershipForUpdate(expectedPair.accountUuid(), expectedPair.tenantUuid()) + .orElseThrow(() -> new IllegalStateException("Creator membership readback is absent")); + RoleSnapshot roles = + roleSnapshotRepository + .findForCanonicalUpdate( + expectedPair.accountUuid(), + expectedPair.tenantUuid(), + expectedPair.provenance(), + expectedMembership.getId(), + expectedMembership.getMembershipVersion()) + .orElseThrow( + () -> new IllegalStateException("Creator role snapshot readback is absent")); + PairAuthority pair = + pairAuthorityRepository + .readForUpdate(expectedPair.accountUuid(), expectedPair.tenantUuid()) + .orElseThrow( + () -> new IllegalStateException("Creator pair authority readback is absent")); + Event event = + authorityOutboxRepository + .findEvent(expectedEvent.outboxStreamKey(), expectedEvent.requestId()) + .orElseThrow(() -> new IllegalStateException("Creator event readback is absent")); + MembershipEvent eventSnapshot = + MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); + AccountTenantCreationBootstrapResult result = completed.result(); + AccountAuditEnvelope audit = + auditOutboxRepository + .findExactCanonicalTenantEnvelopeForUpdate(expectedAudit) + .orElseThrow(() -> new IllegalStateException("Creator audit readback is absent")); + StoredOperation receipt = + operationRepository + .findForUpdate(completed.requestId()) + .orElseThrow(() -> new IllegalStateException("Creator operation receipt is absent")); + if (!sameMembership(expectedMembership, membership) + || !expectedRoles.equals(roles) + || !expectedPair.equals(pair) + || !expectedEvent.equals(event) + || !expectedAudit.equals(audit) + || !result.membershipVersion().equals(eventSnapshot.membershipVersion()) + || !Map.of( + expectedPair.tenantUuid().toString(), + Long.toString(expectedMembership.getMembershipVersion())) + .equals(result.membershipVersion()) + || !"COMMITTED".equals(receipt.status()) + || !completed.resultDigest().equals(receipt.resultDigest()) + || !Arrays.equals(completed.resultPayload(), receipt.resultPayload()) + || !Arrays.equals(completed.eventPayload(), receipt.eventPayload()) + || !Arrays.equals(completed.auditPayload(), receipt.auditPayload())) { + throw new IllegalStateException( + "Creator membership, roles, pair, event, audit, or receipt readback differs"); + } + } + + private Map eventPreimage( + AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot baseline, + UUID creatorUuid, + UUID tenantUuid, + long membershipVersion, + long membershipGeneration, + String streamKey, + String requestId, + String eventId) { + Map event = new LinkedHashMap<>(); + event.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + event.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + event.put("eventId", eventId); + event.put("requestId", requestId); + event.put("outboxStreamKey", streamKey); + event.put("outboxSequence", "1"); + event.put("sourceScope", "membership/" + creatorUuid + "/" + tenantUuid); + event.put("accountId", creatorUuid.toString()); + event.put("tenantId", tenantUuid.toString()); + event.put("membershipExists", true); + event.put("membershipLifecycleState", "ACTIVE"); + event.put("membershipVersion", Map.of(tenantUuid.toString(), Long.toString(membershipVersion))); + event.put("membershipAuthorityGeneration", Long.toString(membershipGeneration)); + event.put( + "authorityTuple", + AccountTenantCreationBootstrapDigest.authorityTupleMap(baseline.authorityTuple())); + event.put("issuanceFence", baseline.issuanceFence()); + event.put("roles", List.of("tenantAdmin")); + event.put("gameplayAdmissionAllowed", false); + event.put("callerBoundAuthorityInvalidated", false); + return event; + } + + private byte[] auditPayload( + FreshTenantCreatorEvidence evidence, + String requestDigest, + String sourceSnapshotDigest, + long membershipVersion, + long membershipGeneration, + Event event, + Checkpoint checkpoint) { + Map payload = new LinkedHashMap<>(); + payload.put("schemaVersion", "account-tenant-creation-bootstrap-audit/v1"); + payload.put("requestId", evidence.accountAuthorizationOperationId().toString()); + payload.put("requestDigest", requestDigest); + payload.put("initiatingAccountUuid", evidence.initiatingAccountId().toString()); + payload.put("tenantUuid", evidence.creationEvidence().canonicalTenantId().toString()); + payload.put("creationRequestId", evidence.creationEvidence().creationRequestId().toString()); + payload.put("creationOperationId", evidence.creationEvidence().operationId().toString()); + payload.put("creationRequestDigest", evidence.creationEvidence().requestDigest()); + payload.put("creationEvidenceDigest", evidence.creationEvidence().evidenceDigest()); + payload.put( + "accountAuthorizationOperationId", evidence.accountAuthorizationOperationId().toString()); + payload.put("accountAuthorizationDigest", evidence.accountAuthorizationDigest()); + payload.put("creatorEvidenceDigest", evidence.evidenceDigest()); + payload.put("sourceSnapshotDigest", sourceSnapshotDigest); + payload.put( + "membershipVersion", + Map.of( + evidence.creationEvidence().canonicalTenantId().toString(), + Long.toString(membershipVersion))); + payload.put("membershipAuthorityGeneration", Long.toString(membershipGeneration)); + payload.put("outboxStreamKey", checkpoint.outboxStreamKey()); + payload.put("outboxSequence", Long.toString(checkpoint.outboxSequence())); + payload.put("eventId", event.eventId()); + payload.put("eventDigest", event.eventDigest()); + payload.put("callerBoundAuthorityInvalidated", false); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(payload)); + } catch (IOException | RuntimeException failure) { + throw new IllegalStateException("Creator-bootstrap audit serialization failed", failure); + } + } + + private AccountAuditEnvelope auditEnvelope(StoredOperation operation) { + return new AccountAuditEnvelope( + operation.auditEventId(), + "tenant", + AccountAuditTenantIdentity.canonicalTenantV2(operation.tenantUuid().toString()), + "account-service", + operation.auditEventType(), + operation.auditOccurredAt(), + 1, + 1, + operation.auditPayloadDigest(), + new String(operation.auditPayload(), StandardCharsets.UTF_8)); + } + + private static VerifiedTenantProvenance freshProvenance(FreshTenantCreationEvidence source) { + return new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest()); + } + + private static void requireCommittedOperation(StoredOperation operation) { + if (!"COMMITTED".equals(operation.status()) + || operation.membershipId() == null + || operation.membershipVersion() == null + || operation.membershipAuthorityGeneration() == null + || !"ACTIVE".equals(operation.membershipLifecycleState()) + || !Boolean.FALSE.equals(operation.gameplayAdmissionAllowed()) + || !Boolean.FALSE.equals(operation.callerBoundAuthorityInvalidated()) + || operation.membershipRolesPayload() == null + || operation.eventPayload() == null + || operation.auditPayload() == null + || operation.resultPayload() == null + || operation.resultDigest() == null + || operation.committedAt() == null) { + throw new IllegalStateException("Incomplete creator-bootstrap operation cannot be replayed"); + } + } + + private static boolean sameMembership( + AccountTenantMembership expected, AccountTenantMembership actual) { + return Objects.equals(expected.getId(), actual.getId()) + && Objects.equals( + expected.getAccount().getAccountUuid(), actual.getAccount().getAccountUuid()) + && Objects.equals(expected.getTenantUuid(), actual.getTenantUuid()) + && Objects.equals(expected.getTenantId(), actual.getTenantId()) + && Objects.equals(expected.getTenantProvenanceKind(), actual.getTenantProvenanceKind()) + && Objects.equals( + expected.getTenantSourceOperationId(), actual.getTenantSourceOperationId()) + && Objects.equals(expected.getTenantProvenanceDigest(), actual.getTenantProvenanceDigest()) + && Objects.equals(expected.getLifecycleState(), actual.getLifecycleState()) + && expected.isGameplayAdmissionAllowed() == actual.isGameplayAdmissionAllowed() + && expected.getMembershipVersion() == actual.getMembershipVersion() + && expected.getMembershipAuthorityGeneration() == actual.getMembershipAuthorityGeneration() + && Objects.equals(expected.getAuthorityProvenance(), actual.getAuthorityProvenance()); + } + + private static void requireAccountIdentity(Account account, UUID expectedUuid) { + if (account.getId() == null + || account.getId() <= 0L + || !expectedUuid.equals(account.getAccountUuid()) + || account.getAccountUuidProvenance() == null + || account.getAccountUuidSourceNumericId() == null + || !account.getId().equals(account.getAccountUuidSourceNumericId())) { + throw new IllegalStateException( + "Creator Account UUID provenance is incomplete or mismatched"); + } + } + + private static long positiveLong(String value, String label) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new IllegalStateException("Creator-bootstrap " + label + " is not a positive decimal"); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L) { + throw new IllegalStateException("Creator-bootstrap " + label + " is not positive"); + } + return parsed; + } catch (NumberFormatException overflow) { + throw new IllegalStateException( + "Creator-bootstrap " + label + " exceeds Account BIGINT", overflow); + } + } + + private static long increment(long value, String label) { + try { + return Math.addExact(value, 1L); + } catch (ArithmeticException overflow) { + throw new IllegalStateException("Account " + label + " is exhausted", overflow); + } + } + + private static void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Creator bootstrap requires a writable Account transaction"); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V94__account_tenant_creation_bootstrap.sql b/services/account-service/src/main/resources/db/migration/V94__account_tenant_creation_bootstrap.sql new file mode 100644 index 0000000000..662c0252a7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V94__account_tenant_creation_bootstrap.sql @@ -0,0 +1,189 @@ +-- One immutable owner receipt for the first control-only Account membership created +-- from an exact, authenticated Game Design tenant-creation source. This storage does +-- not provide authentication or expose a mutation route. +CREATE TABLE account_tenant_creation_bootstrap_operations ( + request_id UUID PRIMARY KEY, + schema_version SMALLINT NOT NULL CHECK (schema_version = 1), + initiating_account_uuid UUID NOT NULL REFERENCES accounts (account_uuid), + tenant_uuid UUID NOT NULL, + creation_request_id UUID NOT NULL, + creation_operation_id UUID NOT NULL, + account_authorization_operation_id UUID NOT NULL, + account_authorization_digest VARCHAR(71) NOT NULL + CHECK (account_authorization_digest ~ '^sha256:[0-9a-f]{64}$'), + creator_evidence_digest VARCHAR(71) NOT NULL + CHECK (creator_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + creator_evidence_payload BYTEA NOT NULL, + source_snapshot_payload BYTEA NOT NULL, + source_snapshot_digest VARCHAR(71) NOT NULL + CHECK (source_snapshot_digest ~ '^sha256:[0-9a-f]{64}$'), + request_payload BYTEA NOT NULL, + request_digest VARCHAR(71) NOT NULL + CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + baseline_membership_version BIGINT NOT NULL CHECK (baseline_membership_version > 0), + baseline_membership_authority_generation BIGINT NOT NULL + CHECK (baseline_membership_authority_generation > 0), + baseline_event_sequence BIGINT NOT NULL CHECK (baseline_event_sequence = 0), + membership_id BIGINT, + membership_version BIGINT, + membership_authority_generation BIGINT, + membership_lifecycle_state VARCHAR(16), + gameplay_admission_allowed BOOLEAN, + membership_roles_payload BYTEA, + event_stream_key VARCHAR(256), + event_request_id VARCHAR(128), + event_sequence BIGINT, + event_id VARCHAR(512), + event_digest VARCHAR(71), + caller_bound_authority_invalidated BOOLEAN, + event_payload BYTEA, + audit_event_id UUID, + audit_event_type VARCHAR(80), + audit_occurred_at TIMESTAMPTZ, + audit_payload_digest VARCHAR(71), + audit_payload BYTEA, + result_payload BYTEA, + result_digest VARCHAR(71), + status VARCHAR(16) NOT NULL CHECK (status IN ('IN_PROGRESS', 'COMMITTED')), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + CONSTRAINT account_tenant_creation_bootstrap_authorization_identity_check + CHECK (request_id = account_authorization_operation_id), + CONSTRAINT account_tenant_creation_bootstrap_creator_tenant_uq + UNIQUE (tenant_uuid), + CONSTRAINT account_tenant_creation_bootstrap_creation_operation_uq + UNIQUE (creation_operation_id), + CONSTRAINT account_tenant_creation_bootstrap_membership_state_check + CHECK (membership_lifecycle_state IS NULL OR membership_lifecycle_state = 'ACTIVE'), + CONSTRAINT account_tenant_creation_bootstrap_admission_check + CHECK (gameplay_admission_allowed IS NULL OR gameplay_admission_allowed = FALSE), + CONSTRAINT account_tenant_creation_bootstrap_generation_check + CHECK (membership_authority_generation IS NULL OR + membership_authority_generation = baseline_membership_authority_generation), + CONSTRAINT account_tenant_creation_bootstrap_event_check + CHECK (event_sequence IS NULL OR event_sequence = 1), + CONSTRAINT account_tenant_creation_bootstrap_event_scope_check + CHECK (event_stream_key IS NULL OR event_stream_key = + 'account:auth-authority:v1:membership/' || initiating_account_uuid::TEXT || '/' || tenant_uuid::TEXT), + CONSTRAINT account_tenant_creation_bootstrap_event_request_check + CHECK (event_request_id IS NULL OR event_request_id = request_id::TEXT), + CONSTRAINT account_tenant_creation_bootstrap_invalidation_check + CHECK (caller_bound_authority_invalidated IS NULL OR caller_bound_authority_invalidated = FALSE), + CONSTRAINT account_tenant_creation_bootstrap_completion_shape CHECK ( + (status = 'IN_PROGRESS' + AND membership_id IS NULL AND membership_version IS NULL + AND membership_authority_generation IS NULL AND membership_lifecycle_state IS NULL + AND gameplay_admission_allowed IS NULL AND membership_roles_payload IS NULL + AND event_stream_key IS NULL AND event_request_id IS NULL AND event_sequence IS NULL + AND event_id IS NULL AND event_digest IS NULL + AND caller_bound_authority_invalidated IS NULL AND event_payload IS NULL + AND audit_event_id IS NULL AND audit_event_type IS NULL AND audit_occurred_at IS NULL + AND audit_payload_digest IS NULL AND audit_payload IS NULL + AND result_payload IS NULL AND result_digest IS NULL AND committed_at IS NULL) + OR (status = 'COMMITTED' + AND membership_id IS NOT NULL AND membership_id > 0 + AND membership_version = baseline_membership_version + 1 + AND membership_authority_generation = baseline_membership_authority_generation + AND membership_lifecycle_state = 'ACTIVE' + AND gameplay_admission_allowed = FALSE + AND membership_roles_payload = convert_to('["tenantAdmin"]', 'UTF8') + AND event_stream_key IS NOT NULL AND event_request_id IS NOT NULL + AND event_sequence = 1 AND event_id IS NOT NULL AND length(btrim(event_id)) > 0 + AND event_digest IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND caller_bound_authority_invalidated = FALSE AND event_payload IS NOT NULL + AND audit_event_id IS NOT NULL AND audit_event_type = 'ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED' + AND audit_occurred_at IS NOT NULL + AND audit_payload_digest IS NOT NULL AND audit_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND audit_payload IS NOT NULL + AND result_payload IS NOT NULL AND result_digest IS NOT NULL + AND result_digest ~ '^sha256:[0-9a-f]{64}$' AND committed_at IS NOT NULL)) +); + +CREATE INDEX account_tenant_creation_bootstrap_creator_idx + ON account_tenant_creation_bootstrap_operations + (initiating_account_uuid, tenant_uuid, request_id); + +-- [jooq ignore start] +CREATE FUNCTION account_tenant_creation_bootstrap_update_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.schema_version IS DISTINCT FROM OLD.schema_version + OR NEW.initiating_account_uuid IS DISTINCT FROM OLD.initiating_account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.creation_request_id IS DISTINCT FROM OLD.creation_request_id + OR NEW.creation_operation_id IS DISTINCT FROM OLD.creation_operation_id + OR NEW.account_authorization_operation_id IS DISTINCT FROM OLD.account_authorization_operation_id + OR NEW.account_authorization_digest IS DISTINCT FROM OLD.account_authorization_digest + OR NEW.creator_evidence_digest IS DISTINCT FROM OLD.creator_evidence_digest + OR NEW.creator_evidence_payload IS DISTINCT FROM OLD.creator_evidence_payload + OR NEW.source_snapshot_payload IS DISTINCT FROM OLD.source_snapshot_payload + OR NEW.source_snapshot_digest IS DISTINCT FROM OLD.source_snapshot_digest + OR NEW.request_payload IS DISTINCT FROM OLD.request_payload + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.baseline_membership_version IS DISTINCT FROM OLD.baseline_membership_version + OR NEW.baseline_membership_authority_generation IS DISTINCT FROM OLD.baseline_membership_authority_generation + OR NEW.baseline_event_sequence IS DISTINCT FROM OLD.baseline_event_sequence + OR NEW.created_at IS DISTINCT FROM OLD.created_at + OR OLD.status <> 'IN_PROGRESS' + OR NEW.status <> 'COMMITTED' THEN + RAISE EXCEPTION 'Account creator-bootstrap request is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'account_tenant_creation_bootstrap_identity_immutable'; + END IF; + NEW.committed_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_creation_bootstrap_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.status <> 'IN_PROGRESS' + OR NEW.membership_id IS NOT NULL OR NEW.membership_version IS NOT NULL + OR NEW.membership_authority_generation IS NOT NULL + OR NEW.membership_lifecycle_state IS NOT NULL OR NEW.gameplay_admission_allowed IS NOT NULL + OR NEW.membership_roles_payload IS NOT NULL + OR NEW.event_stream_key IS NOT NULL OR NEW.event_request_id IS NOT NULL + OR NEW.event_sequence IS NOT NULL OR NEW.event_id IS NOT NULL OR NEW.event_digest IS NOT NULL + OR NEW.caller_bound_authority_invalidated IS NOT NULL OR NEW.event_payload IS NOT NULL + OR NEW.audit_event_id IS NOT NULL OR NEW.audit_event_type IS NOT NULL + OR NEW.audit_occurred_at IS NOT NULL OR NEW.audit_payload_digest IS NOT NULL + OR NEW.audit_payload IS NOT NULL OR NEW.result_payload IS NOT NULL + OR NEW.result_digest IS NOT NULL OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Account creator-bootstrap operation must begin without a result' + USING ERRCODE = '23514', + CONSTRAINT = 'account_tenant_creation_bootstrap_initial_state'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_tenant_creation_bootstrap_no_delete() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account creator-bootstrap history cannot be deleted' + USING ERRCODE = '23514', + CONSTRAINT = 'account_tenant_creation_bootstrap_no_delete'; + RETURN OLD; +END; +$$; + +CREATE TRIGGER account_tenant_creation_bootstrap_insert + BEFORE INSERT ON account_tenant_creation_bootstrap_operations + FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_bootstrap_insert_guard(); + +CREATE TRIGGER account_tenant_creation_bootstrap_update + BEFORE UPDATE ON account_tenant_creation_bootstrap_operations + FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_bootstrap_update_guard(); + +CREATE TRIGGER account_tenant_creation_bootstrap_delete + BEFORE DELETE ON account_tenant_creation_bootstrap_operations + FOR EACH ROW EXECUTE FUNCTION account_tenant_creation_bootstrap_no_delete(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V95__individual_creator_party_sources.sql b/services/account-service/src/main/resources/db/migration/V95__individual_creator_party_sources.sql new file mode 100644 index 0000000000..d717b24762 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V95__individual_creator_party_sources.sql @@ -0,0 +1,153 @@ +-- Owner-local preparation only: no party provisioning, authenticated caller producer, +-- hosted terms, source revocation writer or runtime activation is supplied here. +CREATE TABLE account_individual_creator_party_sources ( + creator_party_id UUID PRIMARY KEY CHECK (creator_party_id <> '00000000-0000-0000-0000-000000000000'), + account_uuid UUID NOT NULL REFERENCES accounts (account_uuid), + verification_status VARCHAR(16) NOT NULL + CHECK (verification_status IN ('UNVERIFIED', 'VERIFIED', 'UNSUPPORTED')), + identity_version BIGINT NOT NULL CHECK (identity_version > 0), + policy_reference VARCHAR(512), + policy_version BIGINT, + verification_evidence_reference VARCHAR(512), + verification_evidence_version BIGINT, + source_version BIGINT NOT NULL CHECK (source_version = 1), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) > 0), + source_digest VARCHAR(71) NOT NULL CHECK (source_digest ~ '^sha256:[0-9a-f]{64}$'), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (policy_reference IS NULL OR length(btrim(policy_reference)) > 0), + CHECK (verification_evidence_reference IS NULL OR length(btrim(verification_evidence_reference)) > 0), + CHECK ((policy_reference IS NULL) = (policy_version IS NULL)), + CHECK ((verification_evidence_reference IS NULL) = (verification_evidence_version IS NULL)), + CHECK (policy_version IS NULL OR policy_version > 0), + CHECK (verification_evidence_version IS NULL OR verification_evidence_version > 0), + CHECK (verification_status <> 'VERIFIED' OR + (policy_reference IS NOT NULL AND verification_evidence_reference IS NOT NULL)), + UNIQUE (creator_party_id, account_uuid) +); + +-- All history counts as prior state. Retained/tombstoned evidence cannot be reset to fresh. +-- This migration intentionally enrolls no existing tenant or party. +CREATE TABLE account_tenant_creator_party_history ( + history_id UUID PRIMARY KEY CHECK (history_id <> '00000000-0000-0000-0000-000000000000'), + tenant_uuid UUID NOT NULL, + origin VARCHAR(24) NOT NULL CHECK (origin IN ('FRESH_INITIAL', 'RETAINED', 'TOMBSTONE')), + creator_party_id UUID REFERENCES account_individual_creator_party_sources (creator_party_id), + source_version BIGINT NOT NULL CHECK (source_version > 0), + evidence_payload BYTEA NOT NULL CHECK (octet_length(evidence_payload) > 0), + evidence_digest VARCHAR(71) NOT NULL CHECK (evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (tenant_uuid, source_version), + CHECK (origin <> 'FRESH_INITIAL' OR (creator_party_id IS NOT NULL AND source_version = 1)) +); + +CREATE TABLE account_fresh_creator_party_association_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'), + tenant_uuid UUID NOT NULL UNIQUE REFERENCES account_canonical_tenant_identity_claims (canonical_tenant_id), + initiating_account_uuid UUID NOT NULL REFERENCES accounts (account_uuid), + creator_party_id UUID NOT NULL, + creation_operation_id UUID NOT NULL UNIQUE, + creator_evidence_payload BYTEA NOT NULL CHECK (octet_length(creator_evidence_payload) > 0), + party_source_payload BYTEA NOT NULL CHECK (octet_length(party_source_payload) > 0), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + history_id UUID NOT NULL UNIQUE REFERENCES account_tenant_creator_party_history (history_id), + result_payload BYTEA NOT NULL CHECK (octet_length(result_payload) > 0), + result_digest VARCHAR(71) NOT NULL CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'), + committed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (creator_party_id, initiating_account_uuid) + REFERENCES account_individual_creator_party_sources (creator_party_id, account_uuid) +); + +-- [jooq ignore start] +CREATE FUNCTION account_creator_party_immutable_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Account creator-party source/history/receipt is immutable'; +END; +$$; +CREATE TRIGGER account_individual_creator_party_immutable + BEFORE UPDATE OR DELETE ON account_individual_creator_party_sources + FOR EACH ROW EXECUTE FUNCTION account_creator_party_immutable_guard(); +CREATE TRIGGER account_creator_party_history_immutable + BEFORE UPDATE OR DELETE ON account_tenant_creator_party_history + FOR EACH ROW EXECUTE FUNCTION account_creator_party_immutable_guard(); +CREATE TRIGGER account_creator_party_operation_immutable + BEFORE UPDATE OR DELETE ON account_fresh_creator_party_association_operations + FOR EACH ROW EXECUTE FUNCTION account_creator_party_immutable_guard(); + +CREATE FUNCTION account_creator_party_history_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + -- All future history writers must use this same canonical tenant serialization. + -- An older repeatable snapshot cannot prove history absence after waiting for this lock. + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Creator-party history requires READ COMMITTED owner transaction'; + END IF; + PERFORM 1 FROM account_canonical_tenant_identity_claims + WHERE canonical_tenant_id = NEW.tenant_uuid FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Creator-party history requires existing canonical tenant provenance'; + END IF; + IF NEW.origin = 'FRESH_INITIAL' AND EXISTS ( + SELECT 1 FROM account_tenant_creator_party_history WHERE tenant_uuid = NEW.tenant_uuid) THEN + RAISE EXCEPTION 'Fresh association cannot replace prior creator-party history'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_creator_party_history_insert + BEFORE INSERT ON account_tenant_creator_party_history + FOR EACH ROW EXECUTE FUNCTION account_creator_party_history_insert_guard(); + +CREATE FUNCTION account_creator_party_initial_receipt_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + history account_tenant_creator_party_history%ROWTYPE; + receipt account_fresh_creator_party_association_operations%ROWTYPE; +BEGIN + IF TG_TABLE_NAME = 'account_tenant_creator_party_history' THEN + history := NEW; + IF history.origin <> 'FRESH_INITIAL' THEN RETURN NEW; END IF; + SELECT * INTO receipt FROM account_fresh_creator_party_association_operations + WHERE history_id = history.history_id; + ELSE + receipt := NEW; + SELECT * INTO history FROM account_tenant_creator_party_history + WHERE history_id = receipt.history_id; + END IF; + IF receipt.request_id IS NULL OR history.history_id IS NULL + OR history.origin <> 'FRESH_INITIAL' + OR history.tenant_uuid <> receipt.tenant_uuid + OR history.creator_party_id <> receipt.creator_party_id + OR history.evidence_payload <> receipt.result_payload + OR history.evidence_digest <> receipt.result_digest + OR (SELECT count(*) FROM account_tenant_creator_party_history + WHERE tenant_uuid = receipt.tenant_uuid) <> 1 THEN + RAISE EXCEPTION 'Fresh creator-party history requires exact immutable owner receipt'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM account_individual_creator_party_sources party + WHERE party.creator_party_id = receipt.creator_party_id + AND party.account_uuid = receipt.initiating_account_uuid + AND party.verification_status = 'VERIFIED' + AND party.source_payload = receipt.party_source_payload) + OR NOT EXISTS ( + SELECT 1 FROM account_tenant_creation_bootstrap_operations bootstrap + JOIN account_fresh_tenant_identity_associations fresh + ON fresh.canonical_tenant_id = bootstrap.tenant_uuid + WHERE bootstrap.status = 'COMMITTED' + AND bootstrap.tenant_uuid = receipt.tenant_uuid + AND bootstrap.initiating_account_uuid = receipt.initiating_account_uuid + AND bootstrap.creation_operation_id = receipt.creation_operation_id + AND fresh.operation_id = receipt.creation_operation_id + AND fresh.creation_request_id = bootstrap.creation_request_id + AND bootstrap.creator_evidence_payload = receipt.creator_evidence_payload) THEN + RAISE EXCEPTION 'Fresh creator-party receipt requires exact persisted individual and creator sources'; + END IF; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER account_creator_party_initial_history_receipt + AFTER INSERT ON account_tenant_creator_party_history DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_creator_party_initial_receipt_guard(); +CREATE CONSTRAINT TRIGGER account_creator_party_initial_operation_receipt + AFTER INSERT ON account_fresh_creator_party_association_operations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_creator_party_initial_receipt_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V96__account_hosted_terms_acceptance_workflow.sql b/services/account-service/src/main/resources/db/migration/V96__account_hosted_terms_acceptance_workflow.sql new file mode 100644 index 0000000000..bf01e873c1 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V96__account_hosted_terms_acceptance_workflow.sql @@ -0,0 +1,383 @@ +-- Account-owned immutable hosted terms and individual affirmative acceptance workflow. +-- This schema is deliberately unregistered: it creates no production route, bean or live legal +-- publication. Existing Accounts and creator parties are not enrolled or backfilled. +CREATE TABLE account_hosted_terms_scopes ( + hosted_scope_id UUID PRIMARY KEY CHECK (hosted_scope_id <> '00000000-0000-0000-0000-000000000000'), + current_version_id UUID, + current_source_version BIGINT, + current_material_generation BIGINT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK ((current_version_id IS NULL) = (current_source_version IS NULL)), + CHECK ((current_version_id IS NULL) = (current_material_generation IS NULL)), + CHECK (current_source_version IS NULL OR current_source_version > 0), + CHECK (current_material_generation IS NULL OR current_material_generation > 0) +); + +CREATE TABLE account_hosted_terms_catalog_versions ( + version_id UUID PRIMARY KEY CHECK (version_id <> '00000000-0000-0000-0000-000000000000'), + hosted_scope_id UUID NOT NULL REFERENCES account_hosted_terms_scopes (hosted_scope_id), + predecessor_version_id UUID, + operator_legal_identity VARCHAR(2048) NOT NULL CHECK (length(btrim(operator_legal_identity)) > 0), + operator_identity_version BIGINT NOT NULL CHECK (operator_identity_version > 0), + document_bytes BYTEA NOT NULL CHECK (octet_length(document_bytes) > 0), + document_digest VARCHAR(71) NOT NULL CHECK (document_digest ~ '^sha256:[0-9a-f]{64}$'), + source_version BIGINT NOT NULL CHECK (source_version > 0), + material_generation BIGINT NOT NULL CHECK (material_generation > 0), + materiality VARCHAR(16) NOT NULL CHECK (materiality IN ('INITIAL', 'MATERIAL', 'NONMATERIAL')), + materiality_evidence_reference VARCHAR(512), + materiality_evidence_version BIGINT, + publication_evidence_reference VARCHAR(512) NOT NULL CHECK (length(btrim(publication_evidence_reference)) > 0), + publication_evidence_version BIGINT NOT NULL CHECK (publication_evidence_version > 0), + notice_evidence_reference VARCHAR(512) NOT NULL CHECK (length(btrim(notice_evidence_reference)) > 0), + notice_evidence_version BIGINT NOT NULL CHECK (notice_evidence_version > 0), + effective_at TIMESTAMPTZ NOT NULL, + version_payload BYTEA NOT NULL CHECK (octet_length(version_payload) > 0), + version_digest VARCHAR(71) NOT NULL CHECK (version_digest ~ '^sha256:[0-9a-f]{64}$'), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (hosted_scope_id, source_version), + UNIQUE (hosted_scope_id, version_id), + FOREIGN KEY (hosted_scope_id, predecessor_version_id) + REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, version_id), + CHECK ((predecessor_version_id IS NULL AND materiality = 'INITIAL' + AND source_version = 1 AND material_generation = 1 + AND materiality_evidence_reference IS NULL AND materiality_evidence_version IS NULL) + OR (predecessor_version_id IS NOT NULL AND materiality IN ('MATERIAL', 'NONMATERIAL') + AND materiality_evidence_reference IS NOT NULL + AND length(btrim(materiality_evidence_reference)) > 0 + AND materiality_evidence_version > 0)), + CHECK ((materiality_evidence_reference IS NULL) = (materiality_evidence_version IS NULL)), + CHECK (document_digest = 'sha256:' || encode(sha256(document_bytes), 'hex')), + CHECK (version_digest = 'sha256:' || encode(sha256(version_payload), 'hex')) +); + +ALTER TABLE account_hosted_terms_scopes + ADD CONSTRAINT account_hosted_terms_current_version_fk + FOREIGN KEY (hosted_scope_id, current_version_id) + REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, version_id); + +CREATE TABLE account_hosted_terms_publication_operations ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'), + hosted_scope_id UUID NOT NULL REFERENCES account_hosted_terms_scopes (hosted_scope_id), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + status VARCHAR(32) NOT NULL CHECK (status IN ('RECEIVED', 'SCHEDULED', 'PENDING_OWNER_SETTLEMENT', 'COMMITTED')), + candidate_version_id UUID, + source_change_binding BYTEA, + result_payload BYTEA, + result_digest VARCHAR(71), + requested_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + UNIQUE (request_id, hosted_scope_id), + UNIQUE (candidate_version_id), + FOREIGN KEY (hosted_scope_id, candidate_version_id) + REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, version_id), + CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')), + CHECK ((candidate_version_id IS NULL) = (status = 'RECEIVED')), + CHECK (status <> 'PENDING_OWNER_SETTLEMENT' OR source_change_binding IS NOT NULL), + CHECK ((status = 'COMMITTED') = (result_payload IS NOT NULL)), + CHECK ((result_payload IS NULL) = (result_digest IS NULL)), + CHECK ((result_digest IS NULL) = (committed_at IS NULL)), + CHECK (result_digest IS NULL OR result_digest = 'sha256:' || encode(sha256(result_payload), 'hex')) +); + +-- One pending/scheduled candidate per hosted scope preserves an unambiguous next independent +-- source version. A due candidate remains durable even while owner settlement is unresolved. +CREATE UNIQUE INDEX account_hosted_terms_one_unsettled_publication + ON account_hosted_terms_publication_operations (hosted_scope_id) + WHERE status IN ('SCHEDULED', 'PENDING_OWNER_SETTLEMENT'); + +CREATE TABLE account_individual_hosted_terms_acceptances ( + evidence_id UUID PRIMARY KEY CHECK (evidence_id <> '00000000-0000-0000-0000-000000000000'), + action_request_id UUID NOT NULL UNIQUE CHECK (action_request_id <> '00000000-0000-0000-0000-000000000000'), + creator_party_id UUID NOT NULL, + account_uuid UUID NOT NULL REFERENCES accounts (account_uuid), + hosted_scope_id UUID NOT NULL, + terms_version_id UUID NOT NULL, + document_digest VARCHAR(71) NOT NULL CHECK (document_digest ~ '^sha256:[0-9a-f]{64}$'), + operator_legal_identity VARCHAR(2048) NOT NULL CHECK (length(btrim(operator_legal_identity)) > 0), + operator_identity_version BIGINT NOT NULL CHECK (operator_identity_version > 0), + source_version BIGINT NOT NULL CHECK (source_version > 0), + material_generation BIGINT NOT NULL CHECK (material_generation > 0), + individual_party_source BYTEA NOT NULL CHECK (octet_length(individual_party_source) > 0), + individual_party_source_digest VARCHAR(71) NOT NULL CHECK (individual_party_source_digest ~ '^sha256:[0-9a-f]{64}$'), + affirmative_action_evidence BYTEA NOT NULL CHECK (octet_length(affirmative_action_evidence) > 0), + affirmative_action_digest VARCHAR(71) NOT NULL CHECK (affirmative_action_digest ~ '^sha256:[0-9a-f]{64}$'), + accepted_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (creator_party_id, account_uuid) + REFERENCES account_individual_creator_party_sources (creator_party_id, account_uuid), + FOREIGN KEY (hosted_scope_id, terms_version_id) + REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, version_id), + CHECK (individual_party_source_digest = 'sha256:' || encode(sha256(individual_party_source), 'hex')), + CHECK (affirmative_action_digest = 'sha256:' || encode(sha256(affirmative_action_evidence), 'hex')) +); + +CREATE INDEX account_individual_hosted_terms_current_acceptance + ON account_individual_hosted_terms_acceptances + (creator_party_id, hosted_scope_id, accepted_at DESC, evidence_id); + +-- [jooq ignore start] +CREATE FUNCTION account_hosted_terms_immutable_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Account hosted terms catalog and acceptance evidence is immutable'; +END; +$$; +CREATE TRIGGER account_hosted_terms_catalog_immutable + BEFORE UPDATE OR DELETE ON account_hosted_terms_catalog_versions + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_immutable_guard(); +CREATE TRIGGER account_hosted_terms_acceptance_immutable + BEFORE UPDATE OR DELETE ON account_individual_hosted_terms_acceptances + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_immutable_guard(); + +CREATE FUNCTION account_hosted_terms_version_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE prior account_hosted_terms_catalog_versions%ROWTYPE; +DECLARE scope account_hosted_terms_scopes%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Hosted terms versions are append-only'; + END IF; + SELECT * INTO scope FROM account_hosted_terms_scopes + WHERE hosted_scope_id = NEW.hosted_scope_id FOR UPDATE; + IF scope.hosted_scope_id IS NULL THEN + RAISE EXCEPTION 'Hosted terms version requires canonical scope lock'; + END IF; + IF NEW.predecessor_version_id IS NULL THEN + IF EXISTS (SELECT 1 FROM account_hosted_terms_catalog_versions + WHERE hosted_scope_id = NEW.hosted_scope_id) + OR scope.current_version_id IS NOT NULL THEN + RAISE EXCEPTION 'Initial hosted terms cannot replace prior source state'; + END IF; + RETURN NEW; + END IF; + IF scope.current_version_id IS DISTINCT FROM NEW.predecessor_version_id + OR EXISTS (SELECT 1 FROM account_hosted_terms_catalog_versions + WHERE hosted_scope_id = NEW.hosted_scope_id + AND predecessor_version_id = NEW.predecessor_version_id) THEN + RAISE EXCEPTION 'Hosted terms candidate must extend the sole current predecessor'; + END IF; + SELECT * INTO prior FROM account_hosted_terms_catalog_versions + WHERE hosted_scope_id = NEW.hosted_scope_id + AND version_id = NEW.predecessor_version_id; + IF prior.version_id IS NULL OR NEW.source_version <> prior.source_version + 1 THEN + RAISE EXCEPTION 'Hosted terms source version must advance from exact predecessor'; + END IF; + IF NEW.operator_legal_identity <> prior.operator_legal_identity + OR NEW.operator_identity_version <> prior.operator_identity_version THEN + IF NEW.materiality <> 'MATERIAL' + OR NEW.material_generation <> prior.material_generation + 1 THEN + RAISE EXCEPTION 'Operator identity change requires material acceptance-generation advance'; + END IF; + ELSIF NEW.materiality = 'MATERIAL' THEN + IF NEW.material_generation <> prior.material_generation + 1 THEN + RAISE EXCEPTION 'Material terms must advance acceptance generation exactly once'; + END IF; + ELSIF NEW.materiality = 'NONMATERIAL' THEN + IF NEW.material_generation <> prior.material_generation THEN + RAISE EXCEPTION 'Nonmaterial terms must preserve acceptance generation'; + END IF; + ELSE + RAISE EXCEPTION 'Only audited materiality classifications may follow a predecessor'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_hosted_terms_version_insert + BEFORE INSERT ON account_hosted_terms_catalog_versions + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_version_insert_guard(); + +CREATE FUNCTION account_hosted_terms_scope_head_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE next_version account_hosted_terms_catalog_versions%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Hosted terms source scope cannot be deleted'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.current_version_id IS NOT NULL + OR NEW.current_source_version IS NOT NULL + OR NEW.current_material_generation IS NOT NULL THEN + RAISE EXCEPTION 'New hosted terms scope cannot fabricate a prior current source'; + END IF; + RETURN NEW; + END IF; + IF NEW.hosted_scope_id <> OLD.hosted_scope_id + OR NEW.current_version_id IS NULL + OR NEW.current_source_version IS NULL + OR NEW.current_material_generation IS NULL THEN + RAISE EXCEPTION 'Hosted terms head update must retain canonical scope and positive source'; + END IF; + SELECT * INTO next_version FROM account_hosted_terms_catalog_versions + WHERE hosted_scope_id = NEW.hosted_scope_id AND version_id = NEW.current_version_id; + IF next_version.version_id IS NULL + OR next_version.source_version <> NEW.current_source_version + OR next_version.material_generation <> NEW.current_material_generation + OR next_version.effective_at > clock_timestamp() THEN + RAISE EXCEPTION 'Only an exact due catalog version may become operative'; + END IF; + IF NOT EXISTS (SELECT 1 FROM account_hosted_terms_publication_operations publication + WHERE publication.hosted_scope_id = NEW.hosted_scope_id + AND publication.candidate_version_id = NEW.current_version_id + AND publication.status IN ('SCHEDULED', 'PENDING_OWNER_SETTLEMENT')) THEN + RAISE EXCEPTION 'Operative terms must match a durable Account publication intent'; + END IF; + IF OLD.current_version_id IS NULL THEN + IF next_version.predecessor_version_id IS NOT NULL + OR next_version.source_version <> 1 OR next_version.material_generation <> 1 THEN + RAISE EXCEPTION 'Initial operative source cannot invent predecessor state'; + END IF; + ELSE + IF next_version.predecessor_version_id <> OLD.current_version_id + OR next_version.source_version <> OLD.current_source_version + 1 THEN + RAISE EXCEPTION 'Operative terms must advance from the exact prior head'; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_hosted_terms_scope_head + BEFORE INSERT OR UPDATE OR DELETE ON account_hosted_terms_scopes + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_scope_head_guard(); + +CREATE FUNCTION account_hosted_terms_scope_head_complete_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'UPDATE' AND NEW.current_version_id IS DISTINCT FROM OLD.current_version_id + AND NOT EXISTS (SELECT 1 FROM account_hosted_terms_publication_operations publication + WHERE publication.hosted_scope_id = NEW.hosted_scope_id + AND publication.candidate_version_id = NEW.current_version_id + AND publication.status = 'COMMITTED') THEN + RAISE EXCEPTION 'Operative catalog head requires committed publication readback'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_hosted_terms_scope_head_complete + AFTER UPDATE ON account_hosted_terms_scopes DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_scope_head_complete_guard(); + +CREATE FUNCTION account_hosted_terms_publication_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Hosted terms publication request history cannot be deleted'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'RECEIVED' OR NEW.candidate_version_id IS NOT NULL + OR NEW.source_change_binding IS NOT NULL OR NEW.result_payload IS NOT NULL THEN + RAISE EXCEPTION 'Publication operation must begin as exact received intent'; + END IF; + RETURN NEW; + END IF; + IF NEW.request_id <> OLD.request_id OR NEW.hosted_scope_id <> OLD.hosted_scope_id + OR NEW.request_payload <> OLD.request_payload OR NEW.request_digest <> OLD.request_digest + OR (OLD.candidate_version_id IS NOT NULL + AND NEW.candidate_version_id IS DISTINCT FROM OLD.candidate_version_id) + OR (OLD.source_change_binding IS NOT NULL + AND NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding) + OR OLD.status = 'COMMITTED' THEN + RAISE EXCEPTION 'Publication request identity and candidate are immutable'; + END IF; + IF NOT ((OLD.status = 'RECEIVED' AND NEW.status IN ('SCHEDULED', 'PENDING_OWNER_SETTLEMENT', 'COMMITTED')) + OR (OLD.status = 'SCHEDULED' AND NEW.status IN ('PENDING_OWNER_SETTLEMENT', 'COMMITTED')) + OR (OLD.status = 'PENDING_OWNER_SETTLEMENT' AND NEW.status = 'COMMITTED')) THEN + RAISE EXCEPTION 'Invalid hosted terms publication transition'; + END IF; + IF NEW.status = 'COMMITTED' THEN + IF NEW.candidate_version_id IS NULL OR NEW.result_payload IS NULL + OR NEW.result_digest IS NULL OR NEW.committed_at IS NULL + OR NOT EXISTS (SELECT 1 FROM account_hosted_terms_scopes scope + WHERE scope.hosted_scope_id = NEW.hosted_scope_id + AND scope.current_version_id = NEW.candidate_version_id) + OR NOT EXISTS (SELECT 1 FROM account_hosted_terms_catalog_versions version + WHERE version.hosted_scope_id = NEW.hosted_scope_id + AND version.version_id = NEW.candidate_version_id + AND version.version_payload = NEW.result_payload) THEN + RAISE EXCEPTION 'Committed publication requires exact operative catalog readback'; + END IF; + ELSIF NEW.result_payload IS NOT NULL OR NEW.result_digest IS NOT NULL OR NEW.committed_at IS NOT NULL THEN + RAISE EXCEPTION 'Unsettled publication cannot have a committed result'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_hosted_terms_publication_immutable + BEFORE INSERT OR UPDATE OR DELETE ON account_hosted_terms_publication_operations + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_publication_guard(); + +CREATE FUNCTION account_hosted_terms_publication_fence_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE predecessor UUID; +BEGIN + IF NEW.status = 'COMMITTED' THEN + SELECT predecessor_version_id INTO predecessor + FROM account_hosted_terms_catalog_versions + WHERE hosted_scope_id = NEW.hosted_scope_id + AND version_id = NEW.candidate_version_id; + IF predecessor IS NOT NULL AND (NEW.source_change_binding IS NULL OR NOT EXISTS ( + SELECT 1 FROM account_draft_authorization_source_changes change + JOIN account_draft_authorization_changed_scopes changed USING (change_id) + WHERE change.change_id = NEW.request_id + AND change.binding = NEW.source_change_binding + AND change.status = 'SOURCE_COMMITTED' + AND changed.source_key = 'HOSTED_TERMS:' || NEW.hosted_scope_id::TEXT)) THEN + RAISE EXCEPTION 'Updated hosted terms require fully settled exact Draft source change'; + END IF; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_hosted_terms_publication_fence_complete + AFTER INSERT OR UPDATE ON account_hosted_terms_publication_operations + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_publication_fence_complete_guard(); + +CREATE FUNCTION account_hosted_terms_acceptance_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE source account_individual_creator_party_sources%ROWTYPE; +DECLARE terms account_hosted_terms_catalog_versions%ROWTYPE; +DECLARE scope account_hosted_terms_scopes%ROWTYPE; +DECLARE action JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Hosted terms acceptances are append-only'; + END IF; + SELECT * INTO source FROM account_individual_creator_party_sources + WHERE creator_party_id = NEW.creator_party_id AND account_uuid = NEW.account_uuid FOR UPDATE; + SELECT * INTO terms FROM account_hosted_terms_catalog_versions + WHERE hosted_scope_id = NEW.hosted_scope_id AND version_id = NEW.terms_version_id; + SELECT * INTO scope FROM account_hosted_terms_scopes + WHERE hosted_scope_id = NEW.hosted_scope_id FOR UPDATE; + action := convert_from(NEW.affirmative_action_evidence, 'UTF8')::JSONB; + IF source.creator_party_id IS NULL OR source.verification_status <> 'VERIFIED' + OR source.source_payload <> NEW.individual_party_source + OR terms.version_id IS NULL + OR terms.document_digest <> NEW.document_digest + OR terms.operator_legal_identity <> NEW.operator_legal_identity + OR terms.operator_identity_version <> NEW.operator_identity_version + OR terms.source_version <> NEW.source_version + OR terms.material_generation <> NEW.material_generation + OR NEW.accepted_at IS DISTINCT FROM CURRENT_TIMESTAMP + OR action->>'schema' IS DISTINCT FROM 'account-hosted-terms-affirmative-action/v1' + OR action->>'actionRequestId' IS DISTINCT FROM NEW.action_request_id::TEXT + OR action->>'affirmative' IS DISTINCT FROM 'true' + OR action->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR action->>'creatorPartyId' IS DISTINCT FROM NEW.creator_party_id::TEXT + OR action->>'hostedScopeId' IS DISTINCT FROM NEW.hosted_scope_id::TEXT + OR action->>'shownVersionId' IS DISTINCT FROM NEW.terms_version_id::TEXT + OR action->>'shownDocumentDigest' IS DISTINCT FROM NEW.document_digest + OR action->>'shownOperatorLegalIdentity' IS DISTINCT FROM NEW.operator_legal_identity + OR action->>'shownOperatorIdentityVersion' IS DISTINCT FROM NEW.operator_identity_version::TEXT + OR (scope.current_version_id IS DISTINCT FROM NEW.terms_version_id + AND NOT EXISTS (SELECT 1 FROM account_hosted_terms_publication_operations publication + WHERE publication.hosted_scope_id = NEW.hosted_scope_id + AND publication.candidate_version_id = NEW.terms_version_id + AND publication.status IN ('SCHEDULED', 'PENDING_OWNER_SETTLEMENT'))) THEN + RAISE EXCEPTION 'Acceptance must bind exact locally verified party and shown catalog evidence'; + END IF; + -- Acceptance may be recorded in advance for one disclosed scheduled version. It remains + -- append-only and is not current until that exact version is on the operative ancestry. + IF scope.current_version_id IS NULL AND terms.predecessor_version_id IS NOT NULL THEN + RAISE EXCEPTION 'Hosted terms acceptance requires an existing operative source'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_hosted_terms_acceptance_insert + BEFORE INSERT OR UPDATE OR DELETE ON account_individual_hosted_terms_acceptances + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_acceptance_insert_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V97__account_hosted_terms_environment_binding.sql b/services/account-service/src/main/resources/db/migration/V97__account_hosted_terms_environment_binding.sql new file mode 100644 index 0000000000..35c21bb8a9 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V97__account_hosted_terms_environment_binding.sql @@ -0,0 +1,288 @@ +-- Account-owned immutable selection of the official hosted-terms source for one existing +-- environment boundary. The environment identity itself comes from the authenticated owner; this +-- migration creates no environment registry, backfill, route, bean, or production publisher. +CREATE TABLE account_hosted_terms_environment_binding_heads ( + environment_boundary VARCHAR(512) PRIMARY KEY + CHECK (length(btrim(environment_boundary)) > 0), + current_binding_id UUID, + current_source_version BIGINT, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK ((current_binding_id IS NULL) = (current_source_version IS NULL)), + CHECK (current_source_version IS NULL OR current_source_version > 0) +); + +CREATE TABLE account_hosted_terms_environment_bindings ( + binding_id UUID PRIMARY KEY CHECK (binding_id <> '00000000-0000-0000-0000-000000000000'), + publication_request_id UUID NOT NULL UNIQUE + CHECK (publication_request_id <> '00000000-0000-0000-0000-000000000000'), + environment_boundary VARCHAR(512) NOT NULL + REFERENCES account_hosted_terms_environment_binding_heads (environment_boundary), + hosted_scope_id UUID NOT NULL REFERENCES account_hosted_terms_scopes (hosted_scope_id), + operator_legal_identity VARCHAR(2048) NOT NULL + CHECK (length(btrim(operator_legal_identity)) > 0), + operator_identity_version BIGINT NOT NULL CHECK (operator_identity_version > 0), + catalog_version_id UUID NOT NULL, + catalog_source_version BIGINT NOT NULL CHECK (catalog_source_version > 0), + authenticated_publisher_identity VARCHAR(512) NOT NULL + CHECK (length(btrim(authenticated_publisher_identity)) > 0), + publication_event_identity VARCHAR(512) NOT NULL + CHECK (length(btrim(publication_event_identity)) > 0), + publication_evidence_digest VARCHAR(71) NOT NULL + CHECK (publication_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + predecessor_binding_id UUID, + predecessor_source_version BIGINT, + source_version BIGINT NOT NULL CHECK (source_version > 0), + binding_payload BYTEA NOT NULL CHECK (octet_length(binding_payload) > 0), + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (environment_boundary, binding_id), + UNIQUE (environment_boundary, source_version), + FOREIGN KEY (environment_boundary, predecessor_binding_id) + REFERENCES account_hosted_terms_environment_bindings (environment_boundary, binding_id), + FOREIGN KEY (hosted_scope_id, catalog_version_id) + REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, version_id), + FOREIGN KEY (hosted_scope_id, catalog_source_version) + REFERENCES account_hosted_terms_catalog_versions (hosted_scope_id, source_version), + CHECK ((predecessor_binding_id IS NULL) = (predecessor_source_version IS NULL)), + CHECK ((predecessor_binding_id IS NULL AND source_version = 1 + AND predecessor_source_version IS NULL) + OR (predecessor_binding_id IS NOT NULL AND predecessor_source_version > 0 + AND source_version = predecessor_source_version + 1)), + CHECK (binding_digest = 'sha256:' || encode(sha256(binding_payload), 'hex')) +); + +ALTER TABLE account_hosted_terms_environment_binding_heads + ADD CONSTRAINT account_hosted_terms_environment_binding_current_fk + FOREIGN KEY (environment_boundary, current_binding_id) + REFERENCES account_hosted_terms_environment_bindings (environment_boundary, binding_id) + DEFERRABLE INITIALLY DEFERRED; + +CREATE TABLE account_hosted_terms_environment_binding_publications ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'), + environment_boundary VARCHAR(512) NOT NULL + REFERENCES account_hosted_terms_environment_binding_heads (environment_boundary), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0), + request_digest VARCHAR(71) NOT NULL CHECK (request_digest ~ '^sha256:[0-9a-f]{64}$'), + status VARCHAR(32) NOT NULL + CHECK (status IN ('RECEIVED', 'PENDING_OWNER_SETTLEMENT', 'COMMITTED')), + candidate_binding_id UUID, + source_change_binding BYTEA, + result_payload BYTEA, + result_digest VARCHAR(71), + requested_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + UNIQUE (request_id, environment_boundary), + UNIQUE (candidate_binding_id), + FOREIGN KEY (environment_boundary, candidate_binding_id) + REFERENCES account_hosted_terms_environment_bindings (environment_boundary, binding_id), + CHECK (request_digest = 'sha256:' || encode(sha256(request_payload), 'hex')), + CHECK ((candidate_binding_id IS NULL) = (status = 'RECEIVED')), + CHECK (status <> 'PENDING_OWNER_SETTLEMENT' OR source_change_binding IS NOT NULL), + CHECK ((status = 'COMMITTED') = (result_payload IS NOT NULL)), + CHECK ((result_payload IS NULL) = (result_digest IS NULL)), + CHECK ((result_digest IS NULL) = (committed_at IS NULL)), + CHECK (result_digest IS NULL OR result_digest = 'sha256:' || encode(sha256(result_payload), 'hex')) +); + +ALTER TABLE account_hosted_terms_environment_bindings + ADD CONSTRAINT account_hosted_terms_environment_binding_publication_fk + FOREIGN KEY (publication_request_id, environment_boundary) + REFERENCES account_hosted_terms_environment_binding_publications + (request_id, environment_boundary) + DEFERRABLE INITIALLY DEFERRED; + +CREATE UNIQUE INDEX account_hosted_terms_environment_one_unsettled_binding + ON account_hosted_terms_environment_binding_publications (environment_boundary) + WHERE status = 'PENDING_OWNER_SETTLEMENT'; + +-- [jooq ignore start] +CREATE FUNCTION account_hosted_terms_environment_binding_immutable_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Environment binding receipt history is immutable'; +END; +$$; +CREATE TRIGGER account_hosted_terms_environment_binding_immutable + BEFORE UPDATE OR DELETE ON account_hosted_terms_environment_bindings + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_immutable_guard(); + +CREATE FUNCTION account_hosted_terms_environment_binding_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE head account_hosted_terms_environment_binding_heads%ROWTYPE; +DECLARE terms account_hosted_terms_catalog_versions%ROWTYPE; +DECLARE scope account_hosted_terms_scopes%ROWTYPE; +DECLARE publication account_hosted_terms_environment_binding_publications%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Environment binding receipts are append-only'; + END IF; + SELECT * INTO head FROM account_hosted_terms_environment_binding_heads + WHERE environment_boundary = NEW.environment_boundary FOR UPDATE; + IF head.environment_boundary IS NULL THEN + RAISE EXCEPTION 'Environment binding receipt requires canonical environment head lock'; + END IF; + SELECT * INTO publication FROM account_hosted_terms_environment_binding_publications + WHERE request_id = NEW.publication_request_id FOR UPDATE; + IF publication.request_id IS NULL OR publication.environment_boundary <> NEW.environment_boundary + OR publication.status <> 'RECEIVED' + OR publication.request_digest <> NEW.publication_evidence_digest THEN + RAISE EXCEPTION 'Binding receipt requires exact trusted publication intent'; + END IF; + IF head.current_binding_id IS NULL THEN + IF NEW.predecessor_binding_id IS NOT NULL OR NEW.predecessor_source_version IS NOT NULL + OR NEW.source_version <> 1 + OR EXISTS (SELECT 1 FROM account_hosted_terms_environment_bindings + WHERE environment_boundary = NEW.environment_boundary) THEN + RAISE EXCEPTION 'Initial environment binding cannot fabricate predecessor state'; + END IF; + ELSE + IF head.current_binding_id IS DISTINCT FROM NEW.predecessor_binding_id + OR head.current_source_version IS DISTINCT FROM NEW.predecessor_source_version + OR NEW.source_version <> head.current_source_version + 1 + OR EXISTS (SELECT 1 FROM account_hosted_terms_environment_bindings + WHERE environment_boundary = NEW.environment_boundary + AND predecessor_binding_id = head.current_binding_id) THEN + RAISE EXCEPTION 'Environment binding must extend the exact current predecessor'; + END IF; + END IF; + SELECT * INTO scope FROM account_hosted_terms_scopes + WHERE hosted_scope_id = NEW.hosted_scope_id FOR UPDATE; + SELECT * INTO terms FROM account_hosted_terms_catalog_versions + WHERE hosted_scope_id = NEW.hosted_scope_id AND version_id = NEW.catalog_version_id; + IF scope.current_version_id IS DISTINCT FROM NEW.catalog_version_id + OR scope.current_source_version IS DISTINCT FROM NEW.catalog_source_version + OR terms.version_id IS NULL OR terms.source_version <> NEW.catalog_source_version + OR terms.operator_legal_identity <> NEW.operator_legal_identity + OR terms.operator_identity_version <> NEW.operator_identity_version + OR terms.effective_at > clock_timestamp() THEN + RAISE EXCEPTION 'Binding must name exact current due catalog and legal operator'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_hosted_terms_environment_binding_insert + BEFORE INSERT ON account_hosted_terms_environment_bindings + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_insert_guard(); + +CREATE FUNCTION account_hosted_terms_environment_binding_head_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE next_binding account_hosted_terms_environment_bindings%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Environment binding head cannot be deleted'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.current_binding_id IS NOT NULL OR NEW.current_source_version IS NOT NULL THEN + RAISE EXCEPTION 'New environment binding head cannot fabricate prior source'; + END IF; + RETURN NEW; + END IF; + IF NEW.environment_boundary <> OLD.environment_boundary OR NEW.current_binding_id IS NULL + OR NEW.current_source_version IS NULL THEN + RAISE EXCEPTION 'Environment binding head update must retain boundary and positive source'; + END IF; + SELECT * INTO next_binding FROM account_hosted_terms_environment_bindings + WHERE environment_boundary = NEW.environment_boundary + AND binding_id = NEW.current_binding_id; + IF next_binding.binding_id IS NULL OR next_binding.source_version <> NEW.current_source_version + OR NOT EXISTS (SELECT 1 FROM account_hosted_terms_environment_binding_publications publication + WHERE publication.request_id = next_binding.publication_request_id + AND publication.environment_boundary = NEW.environment_boundary + AND publication.candidate_binding_id = NEW.current_binding_id + AND publication.status = 'COMMITTED') THEN + RAISE EXCEPTION 'Environment binding head must match exact publication candidate'; + END IF; + IF OLD.current_binding_id IS NULL THEN + IF next_binding.predecessor_binding_id IS NOT NULL OR next_binding.source_version <> 1 THEN + RAISE EXCEPTION 'Initial environment binding head cannot invent a predecessor'; + END IF; + ELSIF next_binding.predecessor_binding_id <> OLD.current_binding_id + OR next_binding.source_version <> OLD.current_source_version + 1 THEN + RAISE EXCEPTION 'Environment binding head must advance from its exact predecessor'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_hosted_terms_environment_binding_head + BEFORE INSERT OR UPDATE OR DELETE ON account_hosted_terms_environment_binding_heads + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_head_guard(); + +CREATE FUNCTION account_hosted_terms_environment_binding_publication_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE candidate account_hosted_terms_environment_bindings%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Environment binding publication history cannot be deleted'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'RECEIVED' OR NEW.candidate_binding_id IS NOT NULL + OR NEW.source_change_binding IS NOT NULL OR NEW.result_payload IS NOT NULL THEN + RAISE EXCEPTION 'Binding publication must begin as exact received intent'; + END IF; + RETURN NEW; + END IF; + IF NEW.request_id <> OLD.request_id OR NEW.environment_boundary <> OLD.environment_boundary + OR NEW.request_payload <> OLD.request_payload OR NEW.request_digest <> OLD.request_digest + OR NEW.requested_at <> OLD.requested_at THEN + RAISE EXCEPTION 'Binding publication request intent is immutable'; + END IF; + IF OLD.status = 'COMMITTED' THEN + RAISE EXCEPTION 'Committed binding publication result is immutable'; + END IF; + IF NOT ((OLD.status = 'RECEIVED' AND NEW.status IN ('PENDING_OWNER_SETTLEMENT', 'COMMITTED')) + OR (OLD.status = 'PENDING_OWNER_SETTLEMENT' AND NEW.status = 'COMMITTED')) THEN + RAISE EXCEPTION 'Invalid binding publication transition'; + END IF; + IF NEW.candidate_binding_id IS NULL THEN + RAISE EXCEPTION 'Binding publication transition requires exact candidate'; + END IF; + IF OLD.status = 'PENDING_OWNER_SETTLEMENT' + AND (NEW.candidate_binding_id IS DISTINCT FROM OLD.candidate_binding_id + OR NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding) THEN + RAISE EXCEPTION 'Pending binding publication cannot replace its immutable candidate'; + END IF; + IF NEW.status = 'PENDING_OWNER_SETTLEMENT' AND NEW.source_change_binding IS NULL THEN + RAISE EXCEPTION 'Pending binding publication requires durable source-change intent'; + END IF; + IF NEW.status IN ('PENDING_OWNER_SETTLEMENT', 'COMMITTED') THEN + SELECT * INTO candidate FROM account_hosted_terms_environment_bindings + WHERE environment_boundary = NEW.environment_boundary + AND binding_id = NEW.candidate_binding_id; + IF candidate.binding_id IS NULL OR candidate.publication_request_id <> NEW.request_id + OR ((candidate.predecessor_binding_id IS NOT NULL) + <> (NEW.source_change_binding IS NOT NULL)) THEN + RAISE EXCEPTION 'Binding operation must retain its exact predecessor source change'; + END IF; + END IF; + IF NEW.status = 'COMMITTED' THEN + IF NEW.result_payload <> candidate.binding_payload + OR NEW.result_digest <> candidate.binding_digest + OR NEW.committed_at IS NULL THEN + RAISE EXCEPTION 'Committed binding result must read back exact candidate and fence intent'; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_hosted_terms_environment_binding_publication + BEFORE INSERT OR UPDATE OR DELETE ON account_hosted_terms_environment_binding_publications + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_publication_guard(); + +CREATE FUNCTION account_hosted_terms_environment_binding_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'UPDATE' AND NEW.current_binding_id IS DISTINCT FROM OLD.current_binding_id + AND NOT EXISTS (SELECT 1 FROM account_hosted_terms_environment_binding_publications publication + WHERE publication.environment_boundary = NEW.environment_boundary + AND publication.candidate_binding_id = NEW.current_binding_id + AND publication.status = 'COMMITTED') THEN + RAISE EXCEPTION 'Environment binding head requires committed exact publication result'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_hosted_terms_environment_binding_complete + AFTER UPDATE ON account_hosted_terms_environment_binding_heads + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_complete_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java new file mode 100644 index 0000000000..b9f5aa8995 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java @@ -0,0 +1,832 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.locks.ReentrantLock; +import net.firedevops.firemud.accountservice.dto.AccountTenantCreationBootstrapResult; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Account transaction-composition proof using a synthetic current-source participant. The + * participant is test-only and does not establish production authentication or authorization. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountTenantCreationBootstrapServicePostgresIntegrationTest { + private static final String TEST_NAMESPACE = "creator-bootstrap-proof"; + private static final String AUDIT_EVENT_TYPE = "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED"; + private static final String SCHEMA_PREFIX = "creator_bootstrap_service_"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void commitIsControlOnlyAndHistoricalRetryDoesNotOverwriteLaterMembershipAdvance() { + Fixture fixture = fixture(false); + AccountTenantCreationBootstrapResult original = bootstrap(fixture); + assertThat(original.membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(original.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(original.roles()).containsExactly("tenantAdmin"); + assertThat(original.gameplayAdmissionAllowed()).isFalse(); + String streamKey = membershipStreamKey(fixture.accountUuid(), fixture.tenantUuid()); + AccountAuthorityOutboxRepository.Event originalOutboxEvent = + inTransaction( + fixture, + () -> + fixture + .outbox() + .findEvent( + streamKey, fixture.evidence().accountAuthorizationOperationId().toString()) + .orElseThrow()); + MembershipEvent originalEvent = + MembershipAuthorityEventV1Codec.verify( + new String(originalOutboxEvent.payload(), StandardCharsets.UTF_8)); + assertThat(originalEvent.outboxSequence()).isEqualTo("1"); + assertThat(originalEvent.membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(originalEvent.membershipVersion()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "2")); + assertThat(originalEvent.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(originalEvent.authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(originalEvent.authorityTuple().accountAuthorityGeneration()).isEqualTo("1"); + assertThat(originalEvent.authorityTuple().tenantAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(originalEvent.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(fixture.tenantUuid().toString(), "1")); + assertThat(originalEvent.authorityTuple().privateRealmGrantVersions()).isEmpty(); + assertThat(originalEvent.authorityTuple().accountSecurityCutoff()).isEmpty(); + assertThat(originalEvent.authorityTuple().tenantBillingCutoff()).isEmpty(); + assertThat(originalEvent.roles()).containsExactly("tenantAdmin"); + assertThat(originalEvent.gameplayAdmissionAllowed()).isFalse(); + assertThat(originalEvent.callerBoundAuthorityInvalidated()).isFalse(); + assertThat(originalOutboxEvent.outboxSequence()).isEqualTo(1L); + assertThat(originalOutboxEvent.eventId()).isEqualTo(originalEvent.eventId()); + assertThat(originalOutboxEvent.eventDigest()).isEqualTo(originalEvent.eventDigest()); + + AccountTenantMembership committedMembership = + inTransaction( + fixture, + () -> + fixture + .memberships() + .findCanonicalMembershipForUpdate(fixture.accountUuid(), fixture.tenantUuid()) + .orElseThrow()); + assertThat(committedMembership.getLifecycleState()).isEqualTo("ACTIVE"); + assertThat(committedMembership.getMembershipVersion()).isEqualTo(2L); + assertThat(committedMembership.getMembershipAuthorityGeneration()).isEqualTo(1L); + assertThat(committedMembership.isGameplayAdmissionAllowed()).isFalse(); + assertThat( + countQuery( + fixture.setupDsl(), + "SELECT count(*) FROM account_audit_outbox " + + "WHERE audit_event_id = ? AND event_type = ?", + auditEventId(fixture.evidence().accountAuthorizationOperationId()), + AUDIT_EVENT_TYPE)) + .isEqualTo(1L); + StoredOperation receipt = + inTransaction( + fixture, + () -> + fixture + .operationRepository() + .findForUpdate(fixture.evidence().accountAuthorizationOperationId()) + .orElseThrow()); + assertThat(receipt.status()).isEqualTo("COMMITTED"); + assertThat(receipt.result()).isEqualTo(original); + PairAuthority initialPair = + inTransaction( + fixture, + () -> + fixture + .pairAuthority() + .readForUpdate(fixture.accountUuid(), fixture.tenantUuid()) + .orElseThrow()); + assertThat(initialPair.membershipExists()).isTrue(); + assertThat(initialPair.membershipVersion()).isEqualTo(2L); + assertThat(initialPair.membershipAuthorityGeneration()).isEqualTo(1L); + assertThat(initialPair.eventSequence()).isEqualTo(1L); + assertThat(initialPair.lastTransitionInvalidated()).isFalse(); + + advanceMembershipForLaterJoin(fixture, originalEvent); + AccountTenantCreationBootstrapResult replay = bootstrap(fixture); + assertThat(replay).isEqualTo(original); + + CurrentState current = currentState(fixture); + assertThat(current.membership().getMembershipVersion()).isEqualTo(3L); + assertThat(current.membership().getMembershipAuthorityGeneration()).isEqualTo(1L); + assertThat(current.membership().isGameplayAdmissionAllowed()).isTrue(); + assertThat(current.roles()).containsExactly("player", "tenantAdmin"); + assertThat(current.pair().membershipVersion()).isEqualTo(3L); + assertThat(current.pair().eventSequence()).isEqualTo(2L); + } + + @Test + void lateReceiptFailureRollsBackMembershipRolesPairEventAuditAndClaimTogether() { + Fixture fixture = fixture(true); + assertThatThrownBy(() -> bootstrap(fixture)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("injected after Account audit append"); + + String streamKey = membershipStreamKey(fixture.accountUuid(), fixture.tenantUuid()); + UUID auditId = auditEventId(fixture.evidence().accountAuthorizationOperationId()); + assertThat( + count( + fixture.setupDsl(), + "account_tenant_membership", + "tenant_uuid", + fixture.tenantUuid())) + .isEqualTo(0L); + assertThat( + countQuery( + fixture.setupDsl(), + "SELECT count(*) FROM account_tenant_membership_role_snapshots s " + + "JOIN account_tenant_membership m ON m.id = s.membership_id " + + "WHERE m.tenant_uuid = ?", + fixture.tenantUuid())) + .isEqualTo(0L); + assertThat( + countQuery( + fixture.setupDsl(), + "SELECT count(*) FROM account_membership_pair_authority " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid())) + .isEqualTo(0L); + assertThat( + countQuery( + fixture.setupDsl(), + "SELECT count(*) FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = ?", + streamKey)) + .isEqualTo(0L); + assertThat( + countQuery( + fixture.setupDsl(), + "SELECT count(*) FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + streamKey)) + .isEqualTo(0L); + assertThat( + countQuery( + fixture.setupDsl(), + "SELECT count(*) FROM account_audit_outbox " + + "WHERE audit_event_id = ? AND event_type = ?", + auditId, + AUDIT_EVENT_TYPE)) + .isEqualTo(0L); + assertThat( + countQuery( + fixture.setupDsl(), + "SELECT count(*) FROM account_tenant_creation_bootstrap_operations " + + "WHERE request_id = ?", + fixture.evidence().accountAuthorizationOperationId())) + .isEqualTo(0L); + assertThat( + countQuery( + fixture.setupDsl(), + "SELECT count(*) FROM account_authority_generations " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ?", + fixture.accountUuid(), + fixture.tenantUuid())) + .isEqualTo(0L); + } + + @Test + void committedCreatorControlCaptureRetainsExactSourcesWithoutGameplayAdmission() { + Fixture f = fixture(false); + AccountTenantCreationBootstrapResult committed = bootstrap(f); + var capture = + inTransaction( + f, + () -> + f.service() + .readExistingCreatorControlCaptureSources(f.accountUuid(), f.tenantUuid())); + assertThat(capture.accountUuid()).isEqualTo(f.accountUuid()); + assertThat(capture.tenantUuid()).isEqualTo(f.tenantUuid()); + assertThat(capture.membershipVersion()).isEqualTo(committed.membershipVersion()); + assertThat(capture.roleSource().roles()).containsExactly("tenantAdmin"); + assertThat(capture.roleSource().tenantProvenance().sourceOperationId()) + .isEqualTo(f.evidence().creationEvidence().operationId()); + assertThat(capture.creationSource()).isEqualTo(f.evidence().creationEvidence()); + assertThat(capture.bootstrapReceipt().result()).isEqualTo(committed); + assertThat(capture.pairSource()) + .isEqualTo( + inTransaction( + f, + () -> + f.pairAuthority() + .readForUpdate(f.accountUuid(), f.tenantUuid()) + .orElseThrow())); + assertThat(capture.sourceEvent().membershipLifecycleState()).isEqualTo("ACTIVE"); + assertThat(capture.sourceEvent().gameplayAdmissionAllowed()).isFalse(); + assertThat(capture.sourceEvent().roles()).containsExactly("tenantAdmin"); + assertThat(capture.sourceEvent().eventId()).isEqualTo(committed.eventId()); + assertThat(capture.sourceEvent().eventDigest()).isEqualTo(committed.eventDigest()); + assertThat(capture.sourceEvent().membershipVersion()).isEqualTo(capture.membershipVersion()); + assertThat(capture.authorityTuple().membershipAuthorityGeneration()) + .isEqualTo(Map.of(f.tenantUuid().toString(), "1")); + assertThat(capture.issuanceFence()) + .isEqualTo(Long.toString(capture.authoritySnapshot().issuanceFence().value())); + assertThat(capture.outboxCheckpoints()).hasSize(4); + assertThat(capture.outboxSourceEvidence()).hasSize(1); + assertThat(capture.outboxSourceEvidence().getFirst().eventDigest()) + .isEqualTo(committed.eventDigest()); + assertThat(currentState(f).membership().isGameplayAdmissionAllowed()).isFalse(); + } + + @Test + void creatorControlCaptureDeniesLaterJoinedMembershipWithoutRewritingOriginalReceipt() { + Fixture f = fixture(false); + var committed = bootstrap(f); + MembershipEvent event = + inTransaction( + f, + () -> + MembershipAuthorityEventV1Codec.verify( + new String( + f.outbox() + .findEvent( + membershipStreamKey(f.accountUuid(), f.tenantUuid()), + committed.eventRequestId()) + .orElseThrow() + .payload(), + StandardCharsets.UTF_8))); + advanceMembershipForLaterJoin(f, event); + assertThatThrownBy( + () -> + inTransaction( + f, + () -> + f.service() + .readExistingCreatorControlCaptureSources( + f.accountUuid(), f.tenantUuid()))) + .isInstanceOf(IllegalStateException.class); + assertThat(currentState(f).membership().getMembershipVersion()).isEqualTo(3L); + assertThat( + inTransaction( + f, + () -> + f.operationRepository() + .findForUpdate(committed.operationId()) + .orElseThrow() + .result())) + .isEqualTo(committed); + } + + @Test + void creatorControlCaptureDeniesMissingCommittedReceiptReadbackRatherThanInferringFromRoles() { + Fixture f = fixture(false); + var committed = bootstrap(f); + // A synthetic unavailable owner read overlays the real committed database fixture. + doReturn(Optional.empty()).when(f.operationRepository()).findForUpdate(committed.operationId()); + assertThatThrownBy( + () -> + inTransaction( + f, + () -> + f.service() + .readExistingCreatorControlCaptureSources( + f.accountUuid(), f.tenantUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("receipt is absent"); + assertThat(currentState(f).roles()).containsExactly("tenantAdmin"); + assertThat(currentState(f).membership().isGameplayAdmissionAllowed()).isFalse(); + } + + @Test + void creatorControlCaptureDeniesCorruptedOriginalReceiptBytes() { + Fixture f = fixture(false); + var committed = bootstrap(f); + StoredOperation original = + inTransaction( + f, () -> f.operationRepository().findForUpdate(committed.operationId()).orElseThrow()); + StoredOperation corrupt = spy(original); + doReturn(new byte[] {1}).when(corrupt).creatorEvidencePayload(); + // Keep production immutability guards intact; inject corrupt read evidence, not SQL rewrites. + doReturn(Optional.of(corrupt)) + .when(f.operationRepository()) + .findForUpdate(committed.operationId()); + assertThatThrownBy( + () -> + inTransaction( + f, + () -> + f.service() + .readExistingCreatorControlCaptureSources( + f.accountUuid(), f.tenantUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed creator"); + assertThat(currentState(f).membership().isGameplayAdmissionAllowed()).isFalse(); + } + + @Test + void creatorControlCaptureDoesNotCreateMissingMembershipOrReceiptHistory() { + Fixture f = fixture(false); + assertThatThrownBy( + () -> + inTransaction( + f, + () -> + f.service() + .readExistingCreatorControlCaptureSources( + f.accountUuid(), f.tenantUuid()))) + .isInstanceOf(IllegalStateException.class); + assertThat( + inTransaction( + f, + () -> + f.memberships() + .findCanonicalMembershipForUpdate(f.accountUuid(), f.tenantUuid()))) + .isEmpty(); + assertThat( + inTransaction( + f, () -> f.operationRepository().findRequestIdByTenantForUpdate(f.tenantUuid()))) + .isEmpty(); + } + + @Test + void creatorCaptureRejectsGenericAccountSaveWithoutRewritingBootstrapEventOrReceipt() { + Fixture f = fixture(false); + var committed = bootstrap(f); + StoredOperation originalReceipt = + inTransaction( + f, () -> f.operationRepository().findForUpdate(committed.operationId()).orElseThrow()); + AccountAuthorityOutboxRepository.Event originalBootstrapEvent = + inTransaction( + f, + () -> + f.outbox() + .findEvent(originalReceipt.eventStreamKey(), originalReceipt.eventRequestId()) + .orElseThrow()); + assertThat(originalBootstrapEvent.payload()).containsExactly(originalReceipt.eventPayload()); + inTransaction( + f, + () -> { + AccountRepository accounts = new AccountRepository(f.setupDsl()); + Account account = accounts.findByAccountUuidForUpdate(f.accountUuid()).orElseThrow(); + account.setRole("admin"); + accounts.save(account); + return null; + }); + assertThatThrownBy( + () -> + inTransaction( + f, + () -> + f.service() + .readExistingCreatorControlCaptureSources( + f.accountUuid(), f.tenantUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event schema is unsupported"); + + StoredOperation receiptAfterRejectedCapture = + inTransaction( + f, () -> f.operationRepository().findForUpdate(committed.operationId()).orElseThrow()); + AccountAuthorityOutboxRepository.Event bootstrapEventAfterRejectedCapture = + inTransaction( + f, + () -> + f.outbox() + .findEvent(originalReceipt.eventStreamKey(), originalReceipt.eventRequestId()) + .orElseThrow()); + assertThat(receiptAfterRejectedCapture).usingRecursiveComparison().isEqualTo(originalReceipt); + assertThat(bootstrapEventAfterRejectedCapture).isEqualTo(originalBootstrapEvent); + MembershipEvent originalEvent = + MembershipAuthorityEventV1Codec.verify( + new String(originalBootstrapEvent.payload(), StandardCharsets.UTF_8)); + assertThat(originalEvent.eventDigest()).isEqualTo(committed.eventDigest()); + assertThat(originalEvent.gameplayAdmissionAllowed()).isFalse(); + } + + private static AccountTenantCreationBootstrapResult bootstrap(Fixture fixture) { + return fixture.transaction().execute(status -> fixture.service().bootstrap(fixture.evidence())); + } + + private static void advanceMembershipForLaterJoin( + Fixture fixture, MembershipEvent originalEvent) { + inTransaction( + fixture, + () -> { + VerifiedTenantProvenance provenance = provenance(fixture.evidence().creationEvidence()); + AccountTenantMembership membership = + fixture + .memberships() + .findCanonicalMembershipForUpdate(fixture.accountUuid(), fixture.tenantUuid()) + .orElseThrow(); + membership.setLifecycleState("ACTIVE"); + membership.setGameplayAdmissionAllowed(true); + membership.setMembershipVersion(3L); + membership.setMembershipAuthorityGeneration(1L); + membership.setAuthorityProvenance("EXPLICIT_JOIN"); + // Model a later committed owner state directly in this isolated schema. The target + // first-JOIN producer intentionally has no creator-to-player transition entrypoint. + fixture + .setupDsl() + .execute( + "UPDATE account_tenant_membership SET gameplay_admission_allowed = TRUE, " + + "membership_version = 3, authority_provenance = 'EXPLICIT_JOIN' WHERE id = ?", + membership.getId()); + AccountTenantMembership persisted = + fixture + .memberships() + .findCanonicalMembershipForUpdate(fixture.accountUuid(), fixture.tenantUuid()) + .orElseThrow(); + fixture + .roles() + .replaceCanonical( + persisted, + fixture.accountUuid(), + fixture.tenantUuid(), + provenance, + 3L, + List.of("player", "tenantAdmin")); + + PairAuthority priorPair = + fixture + .pairAuthority() + .readForUpdate(fixture.accountUuid(), fixture.tenantUuid()) + .orElseThrow(); + String requestId = UUID.randomUUID().toString(); + String eventId = + UUID.nameUUIDFromBytes( + (MembershipAuthorityEventV1Codec.SCHEMA_VERSION + ":" + requestId) + .getBytes(StandardCharsets.UTF_8)) + .toString(); + String streamKey = membershipStreamKey(fixture.accountUuid(), fixture.tenantUuid()); + Map preimage = new LinkedHashMap<>(); + preimage.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + preimage.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + preimage.put("eventId", eventId); + preimage.put("requestId", requestId); + preimage.put("outboxStreamKey", streamKey); + preimage.put("outboxSequence", "2"); + preimage.put( + "sourceScope", "membership/" + fixture.accountUuid() + "/" + fixture.tenantUuid()); + preimage.put("accountId", fixture.accountUuid().toString()); + preimage.put("tenantId", fixture.tenantUuid().toString()); + preimage.put("membershipExists", true); + preimage.put("membershipLifecycleState", "ACTIVE"); + preimage.put("membershipVersion", Map.of(fixture.tenantUuid().toString(), "3")); + preimage.put("membershipAuthorityGeneration", "1"); + preimage.put( + "authorityTuple", + AccountTenantCreationBootstrapDigest.authorityTupleMap( + originalEvent.authorityTuple())); + preimage.put("issuanceFence", originalEvent.issuanceFence()); + preimage.put("roles", List.of("player", "tenantAdmin")); + preimage.put("gameplayAdmissionAllowed", true); + preimage.put("callerBoundAuthorityInvalidated", false); + MembershipEvent laterEvent = MembershipAuthorityEventV1Codec.seal(preimage); + AccountAuthorityOutboxRepository.Event laterOutboxEvent = + fixture + .outbox() + .append( + streamKey, + requestId, + sequence -> { + if (sequence != 2L) { + throw new IllegalStateException( + "Later membership event sequence differs"); + } + return new AccountAuthorityOutboxRepository.EventEvidence( + laterEvent.eventId(), + laterEvent.eventDigest(), + laterEvent.canonicalJsonUtf8()); + }); + fixture + .setupDsl() + .execute( + "UPDATE account_membership_pair_authority SET membership_version = 3, " + + "last_event_sequence = 2, last_event_id = ?, last_event_digest = ? " + + "WHERE account_uuid = ? AND tenant_uuid = ? AND membership_version = ?", + laterOutboxEvent.eventId(), + laterOutboxEvent.eventDigest(), + fixture.accountUuid(), + fixture.tenantUuid(), + priorPair.membershipVersion()); + return null; + }); + } + + private static CurrentState currentState(Fixture fixture) { + return inTransaction( + fixture, + () -> { + AccountTenantMembership membership = + fixture + .memberships() + .findCanonicalMembershipForUpdate(fixture.accountUuid(), fixture.tenantUuid()) + .orElseThrow(); + VerifiedTenantProvenance provenance = provenance(fixture.evidence().creationEvidence()); + var roles = + fixture + .roles() + .findForCanonicalUpdate( + fixture.accountUuid(), + fixture.tenantUuid(), + provenance, + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(); + PairAuthority pair = + fixture + .pairAuthority() + .readForUpdate(fixture.accountUuid(), fixture.tenantUuid()) + .orElseThrow(); + return new CurrentState(membership, roles.roles(), pair); + }); + } + + private static Fixture fixture(boolean failAfterAudit) { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext txDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + + String suffix = UUID.randomUUID().toString().replace("-", ""); + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(txDsl); + AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(txDsl); + AccountAuthoritySourceEvidenceRepository sources = + new AccountAuthoritySourceEvidenceRepository(txDsl, generations, outbox); + AccountRepository accounts = new AccountRepository(txDsl, sources); + Account inserted = + transaction.execute( + status -> { + Account candidate = new Account(); + candidate.setUsername("creator-bootstrap-" + suffix.substring(0, 16)); + candidate.setEmail("creator-bootstrap-" + suffix + "@example.test"); + candidate.setPasswordHash("test-hash"); + return accounts.save(candidate); + }); + UUID accountUuid = java.util.Objects.requireNonNull(inserted).getAccountUuid(); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantIdentityAssociationRepository fresh = + new FreshTenantIdentityAssociationRepository(txDsl, TEST_NAMESPACE); + AccountMembershipPairAuthorityRepository pairs = + new AccountMembershipPairAuthorityRepository(txDsl); + AccountTenantMembershipRepository memberships = + new AccountTenantMembershipRepository(txDsl, accounts, fresh, pairs); + AccountTenantMembershipRoleSnapshotRepository roles = + new AccountTenantMembershipRoleSnapshotRepository(txDsl); + AccountAuditOutboxRepository audit = new AccountAuditOutboxRepository(txDsl); + AccountJoinOperationRepository joinOperations = new AccountJoinOperationRepository(txDsl); + AccountTenantCreationBootstrapOperationRepository operationRepository = + spy( + failAfterAudit + ? new FailingAfterAuditOperationRepository(txDsl) + : new AccountTenantCreationBootstrapOperationRepository(txDsl)); + AccountCreatorMembershipSourceReader producer = + new AccountCreatorMembershipSourceReader( + accounts, + joinOperations, + memberships, + pairs, + roles, + fresh, + generations, + outbox, + sources, + operationRepository); + + FreshTenantCreatorEvidence evidence = creatorEvidence(accountUuid, tenantUuid); + transaction.executeWithoutResult( + status -> { + fresh.importVerified(evidence.creationEvidence()); + generations.initializeTenantIfAbsent(tenantUuid); + }); + + AccountTenantCreationBootstrapAuthorizationSource syntheticParticipant = + syntheticParticipant(evidence); + @SuppressWarnings("unchecked") + ObjectProvider provider = + mock(ObjectProvider.class); + when(provider.getIfAvailable()).thenReturn(syntheticParticipant); + AccountTenantCreationBootstrapService service = + new AccountTenantCreationBootstrapService( + accounts, + fresh, + producer, + pairs, + memberships, + roles, + outbox, + audit, + operationRepository, + provider); + return new Fixture( + txDsl, + transaction, + accountUuid, + tenantUuid, + evidence, + service, + memberships, + roles, + pairs, + outbox, + operationRepository, + producer); + } + + private static FreshTenantCreatorEvidence creatorEvidence(UUID accountUuid, UUID tenantUuid) { + UUID creationRequestId = UUID.randomUUID(); + UUID creationOperationId = UUID.randomUUID(); + UUID authorizationOperationId = UUID.randomUUID(); + String tenantKey = "creator-game-row-17"; + String requestDigest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, creationRequestId, tenantKey, "Creator fixture", null); + FreshTenantCreationEvidence creation = + new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + creationRequestId, + creationOperationId, + requestDigest, + tenantUuid, + 17L, + tenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + creationRequestId, + creationOperationId, + requestDigest, + tenantUuid, + 17L, + tenantKey, + "NEW_GAME_ROW")); + String authorizationDigest = "sha256:" + "8".repeat(64); + return new FreshTenantCreatorEvidence( + 1, + creation, + accountUuid, + authorizationOperationId, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, accountUuid, authorizationOperationId, authorizationDigest)); + } + + private static AccountTenantCreationBootstrapAuthorizationSource syntheticParticipant( + FreshTenantCreatorEvidence expectedEvidence) { + ReentrantLock syntheticSourceFence = new ReentrantLock(); + return (supplied, mutation) -> { + if (!expectedEvidence.equals(supplied)) { + throw new IllegalStateException("Synthetic component fixture source differs"); + } + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Synthetic source participant requires the outer Account transaction"); + } + syntheticSourceFence.lock(); + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCompletion(int status) { + syntheticSourceFence.unlock(); + } + }); + AccountTenantCreationBootstrapResult result = mutation.get(); + if (!syntheticSourceFence.isHeldByCurrentThread()) { + throw new IllegalStateException( + "Synthetic source participant released its fence before Account completion"); + } + return result; + }; + } + + private static VerifiedTenantProvenance provenance(FreshTenantCreationEvidence source) { + return new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest()); + } + + private static String membershipStreamKey(UUID accountUuid, UUID tenantUuid) { + return MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountUuid + + "/" + + tenantUuid; + } + + private static UUID auditEventId(UUID authorizationOperationId) { + return UUID.nameUUIDFromBytes( + ("account-tenant-creation-bootstrap-audit/v1:" + authorizationOperationId) + .getBytes(StandardCharsets.UTF_8)); + } + + private static long count(DSLContext dsl, String table, String column, UUID value) { + return countQuery(dsl, "SELECT count(*) FROM " + table + " WHERE " + column + " = ?", value); + } + + private static long countQuery(DSLContext dsl, String query, Object... bindings) { + return java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull( + dsl.fetchOne(query, bindings), "Count query returned no row") + .get(0, Long.class), + "Count query returned no value"); + } + + private static T inTransaction(Fixture fixture, java.util.function.Supplier work) { + return fixture.transaction().execute(status -> work.get()); + } + + private record CurrentState( + AccountTenantMembership membership, List roles, PairAuthority pair) {} + + private record Fixture( + DSLContext setupDsl, + TransactionTemplate transaction, + UUID accountUuid, + UUID tenantUuid, + FreshTenantCreatorEvidence evidence, + AccountTenantCreationBootstrapService service, + AccountTenantMembershipRepository memberships, + AccountTenantMembershipRoleSnapshotRepository roles, + AccountMembershipPairAuthorityRepository pairAuthority, + AccountAuthorityOutboxRepository outbox, + AccountTenantCreationBootstrapOperationRepository operationRepository, + AccountCreatorMembershipSourceReader producer) {} + + private static final class FailingAfterAuditOperationRepository + extends AccountTenantCreationBootstrapOperationRepository { + private FailingAfterAuditOperationRepository(DSLContext dsl) { + super(dsl); + } + + @Override + public StoredOperation complete(UUID requestId, Completion completion) { + throw new IllegalStateException("injected after Account audit append"); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java new file mode 100644 index 0000000000..bbd9c15495 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java @@ -0,0 +1,721 @@ +package integration.net.firedevops.firemud.accountservice.creatorparty; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.Map; +import java.util.Objects; +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 java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.AssociationConflictException; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.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; + +/** + * Real owner-row and PostgreSQL guard definitions. Verification/policy and original V64 creation + * qualification are explicit SQL fixtures, not authentication, legal provisioning or launch proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class IndividualCreatorPartyPostgresIntegrationTest { + private static final String NAMESPACE = "creator-party-proof"; + private static final String DIGEST = "sha256:" + "1".repeat(64); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void migrationPreservesExistingAccountAndMembershipAndEnrollsNoParty() throws Exception { + // V74 is this source tree's last existing migration before V78; V77 is reserved elsewhere + // and is not a historical schema that this candidate can execute or prove. + Database db = database("74"); + UUID account = insertAccount(db); + long accountKey = + Objects.requireNonNull( + Objects.requireNonNull( + db.dsl().fetchOne("SELECT id FROM accounts WHERE account_uuid = ?", account), + "Persisted baseline Account row is missing") + .get("id", Long.class), + "Persisted baseline Account key is missing"); + Map accountBefore = + Objects.requireNonNull( + db.dsl().fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", account), + "Baseline Account row is missing") + .intoMap(); + db.dsl() + .execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, 42, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED')", + accountKey); + Map before = + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT * FROM account_tenant_membership WHERE account_id = ?", accountKey), + "Baseline membership row is missing") + .intoMap(); + migrate(db, "78"); + assertThat( + Objects.requireNonNull( + db.dsl().fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", account), + "Preserved Account row is missing after migration") + .intoMap()) + .isEqualTo(accountBefore); + assertThat( + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT * FROM account_tenant_membership WHERE account_id = ?", + accountKey), + "Preserved membership row is missing after migration") + .intoMap()) + .isEqualTo(before); + assertThat(count(db, "account_individual_creator_party_sources")).isZero(); + assertThat(count(db, "account_tenant_creator_party_history")).isZero(); + assertThat(count(db, "account_fresh_creator_party_association_operations")).isZero(); + } + + @Test + void committedAssociationReadsExactSourcesAndRetriesWithoutAnotherResult() throws Exception { + Fixture fixture = fixture(); + UUID request = UUID.randomUUID(); + var original = + tx( + fixture.db(), + () -> fixture.owner().associateFresh(request, fixture.creator(), fixture.party())); + assertThat( + tx( + fixture.db(), + () -> + fixture + .owner() + .readInitialAssociation(request, fixture.creator(), fixture.party()))) + .isEqualTo(original); + assertThat( + tx( + fixture.db(), + () -> fixture.owner().associateFresh(request, fixture.creator(), fixture.party()))) + .isEqualTo(original); + assertThat(count(fixture.db(), "account_tenant_creator_party_history")).isEqualTo(1); + assertThat(count(fixture.db(), "account_fresh_creator_party_association_operations")) + .isEqualTo(1); + assertThatThrownBy(() -> fixture.owner().requireHostedAuthoringCurrentness()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("hosted terms"); + } + + @Test + void changedPartyCreationAndOperationCannotRewriteAnOriginal() throws Exception { + Fixture fixture = fixture(); + UUID request = UUID.randomUUID(); + tx( + fixture.db(), + () -> fixture.owner().associateFresh(request, fixture.creator(), fixture.party())); + IndividualCreatorPartySource other = + party(fixture.creator().initiatingAccountId(), VerificationStatus.VERIFIED); + insertParty(fixture.db(), other); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> fixture.owner().associateFresh(request, fixture.creator(), other))) + .isInstanceOf(AssociationConflictException.class); + FreshTenantCreatorEvidence changed = + qualification( + fixture.creator().creationEvidence(), + fixture.creator().initiatingAccountId(), + UUID.randomUUID()); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> fixture.owner().associateFresh(request, changed, fixture.party()))) + .isInstanceOf(AssociationConflictException.class); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> + fixture + .owner() + .associateFresh(UUID.randomUUID(), fixture.creator(), fixture.party()))) + .isInstanceOf(AssociationConflictException.class); + assertThat(count(fixture.db(), "account_tenant_creator_party_history")).isEqualTo(1); + } + + @Test + void unverifiedMissingPolicyForeignPartyAndMissingCreatorProofWriteNothing() throws Exception { + Fixture fixture = fixture(); + IndividualCreatorPartySource unverified = + party(fixture.creator().initiatingAccountId(), VerificationStatus.UNVERIFIED); + insertParty(fixture.db(), unverified); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> + fixture + .owner() + .associateFresh(UUID.randomUUID(), fixture.creator(), unverified))) + .isInstanceOf(IllegalStateException.class); + IndividualCreatorPartySource unsupported = + party(fixture.creator().initiatingAccountId(), VerificationStatus.UNSUPPORTED); + insertParty(fixture.db(), unsupported); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> + fixture + .owner() + .associateFresh(UUID.randomUUID(), fixture.creator(), unsupported))) + .isInstanceOf(IllegalStateException.class); + IndividualCreatorPartySource foreign = + party(insertAccount(fixture.db()), VerificationStatus.VERIFIED); + insertParty(fixture.db(), foreign); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> + fixture + .owner() + .associateFresh(UUID.randomUUID(), fixture.creator(), foreign))) + .isInstanceOf(IllegalArgumentException.class); + FreshTenantCreatorEvidence absent = + qualification( + fixture.creator().creationEvidence(), + fixture.creator().initiatingAccountId(), + UUID.randomUUID()); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> + fixture.owner().associateFresh(UUID.randomUUID(), absent, fixture.party()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("qualification is absent"); + IndividualCreatorPartySource missing = + party(fixture.creator().initiatingAccountId(), VerificationStatus.VERIFIED); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> + fixture + .owner() + .associateFresh(UUID.randomUUID(), fixture.creator(), missing))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source is absent"); + IndividualCreatorPartySource changedProof = + new IndividualCreatorPartySource( + fixture.party().creatorPartyId(), + fixture.party().accountId(), + VerificationStatus.VERIFIED, + 1, + "fixture-approved-policy", + 2L, + "fixture-verified-evidence", + 1L, + 1); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> + fixture + .owner() + .associateFresh(UUID.randomUUID(), fixture.creator(), changedProof))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source is absent"); + assertThat(count(fixture.db(), "account_tenant_creator_party_history")).isZero(); + assertThat(count(fixture.db(), "account_fresh_creator_party_association_operations")).isZero(); + } + + @Test + void priorRetainedAndTombstonedHistoryCannotBeTreatedAsAbsent() throws Exception { + for (String origin : new String[] {"RETAINED", "TOMBSTONE"}) { + Fixture fixture = fixture(); + insertHistory(fixture, origin, 1); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> + fixture + .owner() + .associateFresh( + UUID.randomUUID(), fixture.creator(), fixture.party()))) + .isInstanceOf(AssociationConflictException.class); + assertThat(count(fixture.db(), "account_tenant_creator_party_history")).isEqualTo(1); + assertThat(count(fixture.db(), "account_fresh_creator_party_association_operations")) + .isZero(); + } + } + + @Test + void historicalReplaySurvivesLaterTombstoneButCurrentInitialReadDenies() throws Exception { + Fixture fixture = fixture(); + UUID request = UUID.randomUUID(); + var original = + tx( + fixture.db(), + () -> fixture.owner().associateFresh(request, fixture.creator(), fixture.party())); + insertHistory(fixture, "TOMBSTONE", 2); + assertThat( + tx( + fixture.db(), + () -> fixture.owner().associateFresh(request, fixture.creator(), fixture.party()))) + .isEqualTo(original); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> + fixture + .owner() + .readInitialAssociation(request, fixture.creator(), fixture.party()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("later party history"); + } + + @Test + void concurrentFirstAssociationsHaveOneCommittedWinner() throws Exception { + Fixture fixture = fixture(); + IndividualCreatorPartySource secondParty = + party(fixture.creator().initiatingAccountId(), VerificationStatus.VERIFIED); + insertParty(fixture.db(), secondParty); + CountDownLatch locked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + AtomicInteger secondPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future winner = + executor.submit( + () -> + tx( + fixture.db(), + () -> { + fixture + .db() + .dsl() + .fetchOne( + "SELECT canonical_tenant_id FROM account_canonical_tenant_identity_claims WHERE canonical_tenant_id = ? FOR UPDATE", + fixture.creator().creationEvidence().canonicalTenantId()); + locked.countDown(); + await(release); + return fixture + .owner() + .associateFresh(UUID.randomUUID(), fixture.creator(), fixture.party()); + })); + assertThat(locked.await(10, TimeUnit.SECONDS)).isTrue(); + Future loser = + executor.submit( + () -> { + return tx( + fixture.db(), + () -> { + secondPid.set( + Objects.requireNonNull( + Objects.requireNonNull( + fixture.db().dsl().fetchOne("SELECT pg_backend_pid()"), + "Competing fresh backend identity readback is missing") + .get(0, Integer.class), + "Competing fresh backend PID is missing")); + secondStarted.countDown(); + return fixture + .owner() + .associateFresh(UUID.randomUUID(), fixture.creator(), secondParty); + }); + }); + assertThat(secondStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertDatabaseLockWait(fixture.db(), secondPid.get()); + release.countDown(); + winner.get(10, TimeUnit.SECONDS); + assertThatThrownBy(() -> loser.get(10, TimeUnit.SECONDS)) + .hasCauseInstanceOf(AssociationConflictException.class); + assertThat(count(fixture.db(), "account_fresh_creator_party_association_operations")) + .isEqualTo(1); + assertThat(count(fixture.db(), "account_tenant_creator_party_history")).isEqualTo(1); + } finally { + release.countDown(); + executor.shutdownNow(); + } + } + + @Test + void retainedHistoryCommitWinsAgainstWaitingFreshAssociation() throws Exception { + Fixture fixture = fixture(); + CountDownLatch retainedInserted = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch freshStarted = new CountDownLatch(1); + AtomicInteger freshPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future retained = + executor.submit( + () -> + tx( + fixture.db(), + () -> { + insertHistory(fixture, "RETAINED", 1); + retainedInserted.countDown(); + await(release); + return null; + })); + assertThat(retainedInserted.await(10, TimeUnit.SECONDS)).isTrue(); + Future fresh = + executor.submit( + () -> + tx( + fixture.db(), + () -> { + freshPid.set( + Objects.requireNonNull( + Objects.requireNonNull( + fixture.db().dsl().fetchOne("SELECT pg_backend_pid()"), + "Waiting fresh backend identity readback is missing") + .get(0, Integer.class), + "Waiting fresh backend PID is missing")); + freshStarted.countDown(); + return fixture + .owner() + .associateFresh(UUID.randomUUID(), fixture.creator(), fixture.party()); + })); + assertThat(freshStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertDatabaseLockWait(fixture.db(), freshPid.get()); + release.countDown(); + retained.get(10, TimeUnit.SECONDS); + assertThatThrownBy(() -> fresh.get(10, TimeUnit.SECONDS)) + .hasCauseInstanceOf(AssociationConflictException.class); + assertThat(count(fixture.db(), "account_tenant_creator_party_history")).isEqualTo(1); + assertThat(count(fixture.db(), "account_fresh_creator_party_association_operations")) + .isZero(); + } finally { + release.countDown(); + executor.shutdownNow(); + } + } + + @Test + void commitBoundaryRejectsHistoryAddedAfterInitialAssociationInSameTransaction() + throws Exception { + Fixture fixture = fixture(); + assertThatThrownBy( + () -> + tx( + fixture.db(), + () -> { + fixture + .owner() + .associateFresh(UUID.randomUUID(), fixture.creator(), fixture.party()); + insertHistory(fixture, "RETAINED", 2); + return null; + })) + .hasStackTraceContaining("exact immutable owner receipt"); + assertThat(count(fixture.db(), "account_tenant_creator_party_history")).isZero(); + assertThat(count(fixture.db(), "account_fresh_creator_party_association_operations")).isZero(); + } + + @Test + void databaseRejectsSourceAndReceiptRewritesAndOrphanInitialHistory() throws Exception { + Fixture fixture = fixture(); + UUID request = UUID.randomUUID(); + tx( + fixture.db(), + () -> fixture.owner().associateFresh(request, fixture.creator(), fixture.party())); + assertThatThrownBy( + () -> + fixture + .db() + .dsl() + .execute( + "UPDATE account_individual_creator_party_sources SET verification_status = 'UNVERIFIED' WHERE creator_party_id = ?", + fixture.party().creatorPartyId())) + .hasMessageContaining("immutable"); + assertThatThrownBy( + () -> + fixture + .db() + .dsl() + .execute( + "DELETE FROM account_fresh_creator_party_association_operations WHERE request_id = ?", + request)) + .hasMessageContaining("immutable"); + Fixture empty = fixture(); + assertThatThrownBy( + () -> + tx( + empty.db(), + () -> { + empty + .db() + .dsl() + .execute( + "INSERT INTO account_tenant_creator_party_history (history_id, tenant_uuid, origin, creator_party_id, source_version, evidence_payload, evidence_digest) VALUES (?, ?, 'FRESH_INITIAL', ?, 1, ?, ?)", + UUID.randomUUID(), + empty.creator().creationEvidence().canonicalTenantId(), + empty.party().creatorPartyId(), + new byte[] {1}, + DIGEST); + return null; + })) + .hasStackTraceContaining("exact immutable owner receipt"); + assertThat(count(empty.db(), "account_tenant_creator_party_history")).isZero(); + } + + private static Fixture fixture() throws Exception { + Database db = database("78"); + UUID account = insertAccount(db); + UUID request = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + UUID tenant = UUID.randomUUID(); + FreshTenantCreationEvidence creation = + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + request, + operation, + DIGEST, + tenant, + 1, + "party-game", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, request, operation, DIGEST, tenant, 1, "party-game", "NEW_GAME_ROW")); + FreshTenantCreatorEvidence creator = qualification(creation, account, UUID.randomUUID()); + FreshTenantIdentityAssociationRepository fresh = + new FreshTenantIdentityAssociationRepository(db.dsl(), NAMESPACE); + tx(db, () -> fresh.importVerified(creation)); + insertBootstrapFixture(db, creator); + IndividualCreatorPartySource party = party(account, VerificationStatus.VERIFIED); + insertParty(db, party); + return new Fixture( + db, + creator, + party, + new IndividualCreatorPartyRepository( + db.dsl(), fresh, new AccountTenantCreationBootstrapOperationRepository(db.dsl()))); + } + + private static FreshTenantCreatorEvidence qualification( + FreshTenantCreationEvidence creation, UUID account, UUID authorization) { + return new FreshTenantCreatorEvidence( + 1, + creation, + account, + authorization, + DIGEST, + FreshTenantCreatorDigest.evidenceDigest(1, creation, account, authorization, DIGEST)); + } + + private static IndividualCreatorPartySource party(UUID account, VerificationStatus status) { + return new IndividualCreatorPartySource( + UUID.randomUUID(), + account, + status, + 1, + status == VerificationStatus.VERIFIED ? "fixture-approved-policy" : null, + status == VerificationStatus.VERIFIED ? 1L : null, + status == VerificationStatus.VERIFIED ? "fixture-verified-evidence" : null, + status == VerificationStatus.VERIFIED ? 1L : null, + 1); + } + + private static void insertParty(Database db, IndividualCreatorPartySource party) { + byte[] payload = CreatorPartyEncoding.party(party); + db.dsl() + .execute( + "INSERT INTO account_individual_creator_party_sources (creator_party_id, account_uuid, verification_status, identity_version, policy_reference, policy_version, verification_evidence_reference, verification_evidence_version, source_version, source_payload, source_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + payload, + CreatorPartyEncoding.digest(payload)); + } + + private static void insertHistory(Fixture fixture, String origin, long version) { + fixture + .db() + .dsl() + .execute( + "INSERT INTO account_tenant_creator_party_history (history_id, tenant_uuid, origin, source_version, evidence_payload, evidence_digest) VALUES (?, ?, ?, ?, ?, ?)", + UUID.randomUUID(), + fixture.creator().creationEvidence().canonicalTenantId(), + origin, + version, + new byte[] {1}, + DIGEST); + } + + private static void insertBootstrapFixture(Database db, FreshTenantCreatorEvidence creator) { + // Stipulated original qualification, using the real guarded V64 lifecycle; no guard is + // disabled. + var creation = creator.creationEvidence(); + UUID authorization = creator.accountAuthorizationOperationId(); + db.dsl() + .execute( + "INSERT INTO account_tenant_creation_bootstrap_operations (request_id, schema_version, initiating_account_uuid, tenant_uuid, creation_request_id, creation_operation_id, account_authorization_operation_id, account_authorization_digest, creator_evidence_digest, creator_evidence_payload, source_snapshot_payload, source_snapshot_digest, request_payload, request_digest, baseline_membership_version, baseline_membership_authority_generation, baseline_event_sequence, status) VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 0, 'IN_PROGRESS')", + authorization, + creator.initiatingAccountId(), + creation.canonicalTenantId(), + creation.creationRequestId(), + creation.operationId(), + authorization, + DIGEST, + creator.evidenceDigest(), + CreatorPartyEncoding.creation(creator), + new byte[] {1}, + DIGEST, + new byte[] {1}, + DIGEST); + db.dsl() + .execute( + "UPDATE account_tenant_creation_bootstrap_operations SET membership_id = 1, membership_version = 2, membership_authority_generation = 1, membership_lifecycle_state = 'ACTIVE', gameplay_admission_allowed = FALSE, membership_roles_payload = convert_to('[\"tenantAdmin\"]', 'UTF8'), event_stream_key = ?, event_request_id = ?, event_sequence = 1, event_id = 'fixture-event', event_digest = ?, event_payload = ?, caller_bound_authority_invalidated = FALSE, audit_event_id = ?, audit_event_type = 'ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED', audit_occurred_at = CURRENT_TIMESTAMP, audit_payload_digest = ?, audit_payload = ?, result_payload = ?, result_digest = ?, status = 'COMMITTED' WHERE request_id = ?", + "account:auth-authority:v1:membership/" + + creator.initiatingAccountId() + + "/" + + creation.canonicalTenantId(), + authorization.toString(), + DIGEST, + new byte[] {1}, + UUID.randomUUID(), + DIGEST, + new byte[] {1}, + new byte[] {1}, + DIGEST, + authorization); + } + + private static UUID insertAccount(Database db) { + UUID account = UUID.randomUUID(); + db.dsl() + .execute( + "INSERT INTO accounts (account_uuid, username, email, password_hash) VALUES (?, ?, ?, 'fixture-hash')", + account, + "party-" + account.toString().substring(0, 8), + account + "@example.com"); + return account; + } + + private static Database database(String target) throws Exception { + String schema = "creator_party_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema, + postgres.getUsername(), + postgres.getPassword()); + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + schema); + } + Database db = + new Database( + schema, + source, + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), + new TransactionTemplate(new DataSourceTransactionManager(source))); + migrate(db, target); + return db; + } + + private static void migrate(Database db, String target) { + Flyway.configure() + .dataSource(db.source()) + .schemas(db.schema()) + .defaultSchema(db.schema()) + .placeholders(Map.of("serviceSchema", db.schema())) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + } + + private static long count(Database db, String table) { + return Objects.requireNonNull( + Objects.requireNonNull( + db.dsl().fetchOne("SELECT count(*) AS count FROM " + table), + "Owner table count readback is missing") + .get("count", Long.class), + "Owner table count is missing"); + } + + private static T tx(Database db, Supplier work) { + return db.transactions().execute(status -> work.get()); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Database interleaving was not released"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Database interleaving was interrupted", exception); + } + } + + private static void assertDatabaseLockWait(Database db, int pid) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + var activity = + db.dsl().fetchOne("SELECT wait_event_type FROM pg_stat_activity WHERE pid = ?", pid); + if (activity != null && "Lock".equals(activity.get("wait_event_type", String.class))) { + return; + } + Thread.sleep(25); + } + throw new AssertionError("Second connection did not wait on the canonical tenant owner row"); + } + + private record Database( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + TransactionTemplate transactions) {} + + private record Fixture( + Database db, + FreshTenantCreatorEvidence creator, + IndividualCreatorPartySource party, + IndividualCreatorPartyRepository owner) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java new file mode 100644 index 0000000000..1c532676de --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java @@ -0,0 +1,722 @@ +package integration.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.sql.Statement; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL workflow proof. Operator publication and authenticated identity rows are explicit + * test-only upstream fixtures; these tests do not prove live legal publication or identity. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountHostedTermsPostgresIntegrationTest { + private static final String TEST_NAMESPACE = "account-hosted-terms-isolated-test"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void migrationRetainsExistingPartyAndBackfillsNoCatalogOrAcceptance() throws Exception { + Database db = database("81"); + UUID accountId = insertAccount(db); + IndividualCreatorPartySource party = + party(UUID.randomUUID(), accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map accountBefore = + Objects.requireNonNull( + db.dsl().fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", accountId)) + .intoMap(); + Map partyBefore = + new HashMap<>( + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT * FROM account_individual_creator_party_sources WHERE creator_party_id = ?", + party.creatorPartyId())) + .intoMap()); + byte[] partySourceBefore = (byte[]) partyBefore.remove("source_payload"); + + migrate(db, "94"); + + assertThat( + Objects.requireNonNull( + db.dsl().fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", accountId)) + .intoMap()) + .isEqualTo(accountBefore); + Map partyAfter = + new HashMap<>( + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT * FROM account_individual_creator_party_sources WHERE creator_party_id = ?", + party.creatorPartyId())) + .intoMap()); + byte[] partySourceAfter = (byte[]) partyAfter.remove("source_payload"); + assertThat(partyAfter).isEqualTo(partyBefore); + assertThat(partySourceAfter).containsExactly(partySourceBefore); + assertThat(count(db, "account_hosted_terms_scopes")).isZero(); + assertThat(count(db, "account_hosted_terms_catalog_versions")).isZero(); + assertThat(count(db, "account_hosted_terms_publication_operations")).isZero(); + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isZero(); + } + + @Test + void realServicePublishesAffirmativelyAcceptsReadsBackAndAdvancesMateriality() throws Exception { + Database db = database("94"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + AccountHostedTermsService service = service(db, publications, actions); + + UUID firstRequest = UUID.randomUUID(); + byte[] originalDocument = new byte[] {0, 1, 2, (byte) 0xff, 13, 10}; + publications.put( + firstRequest, + publication( + scopeId, + originalDocument, + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(5))); + AccountHostedTermsService.PublicationResult first = service.publish(firstRequest); + assertThat(first.status()).isEqualTo(HostedTermsRepository.PublicationStatus.COMMITTED); + assertThat(first.candidate().documentBytes()).containsExactly(originalDocument); + assertThat(first.candidate().documentDigest()) + .isEqualTo(HostedTermsEncoding.digest(originalDocument)); + assertThat(service.publish(firstRequest)).isEqualTo(first); // lost-result exact recovery + publications.put( + firstRequest, + publication( + scopeId, + "changed request payload".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(5))); + assertThatThrownBy(() -> service.publish(firstRequest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + publications.put( + firstRequest, + publication( + scopeId, + originalDocument, + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + first.candidate().effectiveAt())); + assertThat(count(db, "account_hosted_terms_catalog_versions")).isEqualTo(1); + + UUID firstActionId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction firstAction = + action(firstActionId, accountId, partyId, scopeId, first.candidate(), true); + actions.put(firstActionId, firstAction); + var accepted = service.accept(firstActionId); + assertThat(accepted.evidenceId()).isNotNull(); + assertThat(accepted.termsVersionId()).isEqualTo(first.candidate().versionId()); + assertThat(accepted.acceptedAt()).isNotNull(); // generated by PostgreSQL, not the caller action + assertThat(service.accept(firstActionId)).isEqualTo(accepted); + actions.put( + firstActionId, + new AccountHostedTermsService.AcceptanceAction( + firstAction.actionRequestId(), + true, + firstAction.accountId(), + firstAction.creatorPartyId(), + firstAction.hostedScopeId(), + firstAction.shownVersionId(), + HostedTermsEncoding.digest("changed shown document".getBytes()), + firstAction.shownOperatorLegalIdentity(), + firstAction.shownOperatorIdentityVersion(), + firstAction.authenticatedActionReference(), + firstAction.authenticatedActionVersion(), + firstAction.actionCreatedAt())); + assertThatThrownBy(() -> service.accept(firstActionId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isEqualTo(1); + var current = service.requireCurrentness(scopeId, partyId); + assertThat(current.acceptanceEvidenceId()).isEqualTo(accepted.evidenceId()); + assertThat(current.materialGeneration()).isEqualTo(1); + + UUID secondRequest = UUID.randomUUID(); + publications.put( + secondRequest, + publication( + scopeId, + "material-v2".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.MATERIAL, + now().minusSeconds(3))); + AccountHostedTermsService.PublicationResult material = service.publish(secondRequest); + assertThat(material.candidate().sourceVersion()).isEqualTo(2); + assertThat(material.candidate().materialGeneration()).isEqualTo(2); + assertThatThrownBy(() -> service.requireCurrentness(scopeId, partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("affirmative party-wide"); + + UUID secondActionId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction secondAction = + action(secondActionId, accountId, partyId, scopeId, material.candidate(), true); + actions.put(secondActionId, secondAction); + var reaccepted = service.accept(secondActionId); + assertThat(service.requireCurrentness(scopeId, partyId).acceptanceEvidenceId()) + .isEqualTo(reaccepted.evidenceId()); + + UUID thirdRequest = UUID.randomUUID(); + publications.put( + thirdRequest, + publication( + scopeId, + "nonmaterial-v3".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + now().minusSeconds(2))); + AccountHostedTermsService.PublicationResult nonmaterial = service.publish(thirdRequest); + assertThat(nonmaterial.candidate().sourceVersion()).isEqualTo(3); + assertThat(nonmaterial.candidate().materialGeneration()).isEqualTo(2); + assertThat(service.requireCurrentness(scopeId, partyId).acceptanceEvidenceId()) + .isEqualTo(reaccepted.evidenceId()); // prior exact acceptance remains in active ancestry + + UUID operatorChangeRequest = UUID.randomUUID(); + publications.put( + operatorChangeRequest, + publication( + scopeId, + "operator-change-v4".getBytes(), + "Replacement Test Operator", + 2, + HostedTermsCatalogVersion.Materiality.MATERIAL, + now().minusSeconds(1))); + AccountHostedTermsService.PublicationResult operatorChange = + service.publish(operatorChangeRequest); + assertThat(operatorChange.candidate().sourceVersion()).isEqualTo(4); + assertThat(operatorChange.candidate().materialGeneration()).isEqualTo(3); + assertThat(operatorChange.candidate().operatorLegalIdentity()) + .isEqualTo("Replacement Test Operator"); + assertThatThrownBy(() -> service.requireCurrentness(scopeId, partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("affirmative party-wide"); + } + + @Test + void acceptanceRejectsWrongSignerNegativeActionChangedShownTermsAndUnavailableIdentity() + throws Exception { + Database db = database("94"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + AccountHostedTermsService service = service(db, publications, actions); + UUID publicationId = UUID.randomUUID(); + publications.put( + publicationId, + publication( + scopeId, + "test-terms".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(1))); + HostedTermsCatalogVersion terms = service.publish(publicationId).candidate(); + + UUID negativeId = UUID.randomUUID(); + actions.put(negativeId, action(negativeId, accountId, partyId, scopeId, terms, false)); + assertThatThrownBy(() -> service.accept(negativeId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Affirmative"); + + UUID wrongAccountId = UUID.randomUUID(); + UUID wrongSignerId = UUID.randomUUID(); + actions.put( + wrongSignerId, action(wrongSignerId, wrongAccountId, partyId, scopeId, terms, true)); + assertThatThrownBy(() -> service.accept(wrongSignerId)) + .isInstanceOf(IllegalStateException.class); + + UUID wrongPartyId = UUID.randomUUID(); + actions.put( + wrongPartyId, action(wrongPartyId, accountId, UUID.randomUUID(), scopeId, terms, true)); + assertThatThrownBy(() -> service.accept(wrongPartyId)) + .isInstanceOf(IllegalStateException.class); + + UUID mismatchId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction correct = + action(mismatchId, accountId, partyId, scopeId, terms, true); + actions.put( + mismatchId, + new AccountHostedTermsService.AcceptanceAction( + correct.actionRequestId(), + true, + correct.accountId(), + correct.creatorPartyId(), + correct.hostedScopeId(), + correct.shownVersionId(), + HostedTermsEncoding.digest("different document".getBytes()), + correct.shownOperatorLegalIdentity(), + correct.shownOperatorIdentityVersion(), + correct.authenticatedActionReference(), + correct.authenticatedActionVersion(), + correct.actionCreatedAt())); + assertThatThrownBy(() -> service.accept(mismatchId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isZero(); + } + + @Test + void futureTermsCarryDeadlineWithoutFreezingPriorTermsEarly() throws Exception { + Database db = database("94"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + AccountHostedTermsService service = service(db, publications, actions); + UUID initialRequest = UUID.randomUUID(); + publications.put( + initialRequest, + publication( + scopeId, + "test-terms-v1".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(1))); + HostedTermsCatalogVersion initial = service.publish(initialRequest).candidate(); + UUID actionId = UUID.randomUUID(); + actions.put(actionId, action(actionId, accountId, partyId, scopeId, initial, true)); + var accepted = service.accept(actionId); + + UUID futureRequest = UUID.randomUUID(); + Instant deadline = databaseNow(db).plusSeconds(5).truncatedTo(ChronoUnit.MICROS); + publications.put( + futureRequest, + publication( + scopeId, + "test-terms-v2".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.MATERIAL, + deadline)); + AccountHostedTermsService.PublicationResult scheduled = service.publish(futureRequest); + assertThat(scheduled.status()).isEqualTo(HostedTermsRepository.PublicationStatus.SCHEDULED); + UUID advanceAcceptanceId = UUID.randomUUID(); + AccountHostedTermsService.AcceptanceAction advanceAcceptance = + action(advanceAcceptanceId, accountId, partyId, scopeId, scheduled.candidate(), true); + actions.put(advanceAcceptanceId, advanceAcceptance); + var acceptedInAdvance = service.accept(advanceAcceptanceId); + assertThat(acceptedInAdvance.termsVersionId()).isEqualTo(scheduled.candidate().versionId()); + var beforeDeadline = service.requireCurrentness(scopeId, partyId); + assertThat(beforeDeadline.acceptanceEvidenceId()).isEqualTo(accepted.evidenceId()); + assertThat(beforeDeadline.validUntil()).isEqualTo(deadline); + assertThat(count(db, "account_individual_hosted_terms_acceptances")).isEqualTo(2); + assertThat(service.resumePublication(futureRequest).status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.SCHEDULED); + + assertThat( + currentnessBlockedAcrossEffectiveDateIsDenied(db, service, scopeId, partyId, deadline)) + .isTrue(); + } + + private static boolean currentnessBlockedAcrossEffectiveDateIsDenied( + Database db, AccountHostedTermsService service, UUID scopeId, UUID partyId, Instant deadline) + throws Exception { + CountDownLatch scopeLocked = new CountDownLatch(1); + CountDownLatch releaseScope = new CountDownLatch(1); + AtomicInteger blockerPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + Future blocker = + executor.submit( + () -> + db.transactions() + .executeWithoutResult( + ignored -> { + blockerPid.set( + Objects.requireNonNull( + db.dsl().fetchOne("SELECT pg_backend_pid() AS pid")) + .get("pid", Integer.class)); + db.dsl() + .fetchOne( + "SELECT hosted_scope_id FROM account_hosted_terms_scopes " + + "WHERE hosted_scope_id = ? FOR UPDATE", + scopeId); + scopeLocked.countDown(); + awaitLatch(releaseScope, "Hosted scope blocker was not released"); + })); + try { + assertThat(scopeLocked.await(5, TimeUnit.SECONDS)).isTrue(); + Future waiter = + executor.submit(() -> service.requireCurrentness(scopeId, partyId)); + Record waiting = awaitHostedScopeLockWait(db, blockerPid.get(), deadline); + assertThat(waiting.get("query_start", OffsetDateTime.class).toInstant()) + .as("currentness lock wait must begin before the disclosed effective date") + .isBefore(deadline); + + awaitDatabaseTime(db, deadline); + releaseScope.countDown(); + try { + waiter.get(5, TimeUnit.SECONDS); + throw new AssertionError("Currentness returned after the disclosed terms deadline"); + } catch (ExecutionException failure) { + assertThat(failure.getCause()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("effective date has arrived"); + } + blocker.get(5, TimeUnit.SECONDS); + return true; + } finally { + releaseScope.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static Record awaitHostedScopeLockWait(Database db, int blockerPid, Instant deadline) + throws InterruptedException { + long timeoutAt = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < timeoutAt) { + Record waiting = + db.dsl() + .fetchOne( + "SELECT waiting.pid, waiting.query_start, waiting.xact_start " + + "FROM pg_stat_activity waiting " + + "WHERE waiting.wait_event_type = 'Lock' " + + "AND waiting.query ILIKE '%account_hosted_terms_scopes%' " + + "AND waiting.query ILIKE '%for update%' " + + "AND ? = ANY(pg_blocking_pids(waiting.pid)) LIMIT 1", + blockerPid); + if (waiting != null) { + assertThat(waiting.get("xact_start", OffsetDateTime.class).toInstant()) + .as("currentness transaction must also have begun before the deadline") + .isBefore(deadline); + return waiting; + } + Thread.sleep(10L); + } + throw new AssertionError("Currentness did not reach the hosted-scope lock wait"); + } + + private static void awaitDatabaseTime(Database db, Instant deadline) throws InterruptedException { + long timeoutAt = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < timeoutAt) { + Instant databaseTime = databaseNow(db); + if (!databaseTime.isBefore(deadline)) { + return; + } + Thread.sleep(10L); + } + throw new AssertionError("PostgreSQL clock did not reach the disclosed effective date"); + } + + private static Instant databaseNow(Database db) { + return Objects.requireNonNull(db.dsl().fetchOne("SELECT clock_timestamp() AS database_now")) + .get("database_now", OffsetDateTime.class) + .toInstant(); + } + + private static void awaitLatch(CountDownLatch latch, String message) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException(message); + } + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(message, failure); + } + } + + @Test + void ownerTransactionRollbackRemovesUncommittedCatalogAndPublicationIntent() throws Exception { + Database db = database("94"); + HostedTermsRepository repository = new HostedTermsRepository(db.dsl()); + UUID scopeId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + byte[] request = "test-only publication".getBytes(); + HostedTermsCatalogVersion candidate = + catalogCandidate( + scopeId, + "test-only terms".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(1), + UUID.randomUUID()); + + assertThatThrownBy( + () -> + tx( + db, + () -> + db.transactions() + .executeWithoutResult( + status -> { + repository.ensureScope(scopeId); + repository.claimPublication(requestId, scopeId, request); + repository.lockScope(scopeId); + repository.insertCandidate(candidate); + throw new IllegalStateException("test-only rollback"); + }))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("rollback"); + + assertThat(count(db, "account_hosted_terms_scopes")).isZero(); + assertThat(count(db, "account_hosted_terms_catalog_versions")).isZero(); + assertThat(count(db, "account_hosted_terms_publication_operations")).isZero(); + } + + private static AccountHostedTermsService service( + Database db, + Map publications, + Map actions) { + IndividualCreatorPartyRepository individualParties = + new IndividualCreatorPartyRepository( + db.dsl(), + new FreshTenantIdentityAssociationRepository(db.dsl(), TEST_NAMESPACE), + new AccountTenantCreationBootstrapOperationRepository(db.dsl())); + return new AccountHostedTermsService( + db.transactionManager(), + new HostedTermsRepository(db.dsl()), + individualParties, + new DraftAuthorizationFenceRepository(db.dsl()), + requestId -> + Objects.requireNonNull(publications.get(requestId), "test-only operator fixture"), + actionId -> + Objects.requireNonNull(actions.get(actionId), "test-only identity/action fixture")); + } + + private static AccountHostedTermsService.PublicationEvidence publication( + UUID scope, + byte[] document, + String operator, + long operatorVersion, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt) { + return new AccountHostedTermsService.PublicationEvidence( + scope, + operator, + operatorVersion, + document, + materiality, + materiality == HostedTermsCatalogVersion.Materiality.INITIAL + ? null + : "test-only-materiality", + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : 1L, + "test-only-publication-evidence", + 1, + "test-only-notice-evidence", + 1, + effectiveAt.truncatedTo(ChronoUnit.MICROS)); + } + + private static HostedTermsCatalogVersion catalogCandidate( + UUID scope, + byte[] document, + String operator, + long operatorVersion, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt, + UUID versionId) { + return new HostedTermsCatalogVersion( + versionId, + scope, + null, + operator, + operatorVersion, + document, + HostedTermsEncoding.digest(document), + 1, + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-only-publication-evidence", + 1, + "test-only-notice-evidence", + 1, + effectiveAt.truncatedTo(ChronoUnit.MICROS)); + } + + private static AccountHostedTermsService.AcceptanceAction action( + UUID actionId, + UUID accountId, + UUID partyId, + UUID scopeId, + HostedTermsCatalogVersion terms, + boolean affirmative) { + return new AccountHostedTermsService.AcceptanceAction( + actionId, + affirmative, + accountId, + partyId, + scopeId, + terms.versionId(), + terms.documentDigest(), + terms.operatorLegalIdentity(), + terms.operatorIdentityVersion(), + "test-only-authenticated-action", + 1, + OffsetDateTime.ofInstant(now(), ZoneOffset.UTC)); + } + + private static IndividualCreatorPartySource party( + UUID partyId, UUID accountId, long identityVersion, String evidenceRef) { + return new IndividualCreatorPartySource( + partyId, + accountId, + VerificationStatus.VERIFIED, + identityVersion, + "test-only-verification-policy", + 1L, + evidenceRef, + 1L, + 1); + } + + private static void insertParty(Database db, IndividualCreatorPartySource party) { + byte[] source = CreatorPartyEncoding.party(party); + db.dsl() + .execute( + "INSERT INTO account_individual_creator_party_sources " + + "(creator_party_id, account_uuid, verification_status, identity_version, " + + "policy_reference, policy_version, verification_evidence_reference, " + + "verification_evidence_version, source_version, source_payload, source_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + source, + CreatorPartyEncoding.digest(source)); + } + + private static UUID insertAccount(Database db) { + UUID accountId = UUID.randomUUID(); + db.dsl() + .execute( + "INSERT INTO accounts (account_uuid, username, email, password_hash) " + + "VALUES (?, ?, ?, 'test-only-password-hash')", + accountId, + "hosted-" + accountId.toString().substring(0, 8), + accountId + "@example.test"); + return accountId; + } + + private static Instant now() { + return Instant.now().truncatedTo(ChronoUnit.MICROS); + } + + private static long count(Database db, String table) { + return Objects.requireNonNull( + Objects.requireNonNull(db.dsl().fetchOne("SELECT count(*) AS count FROM " + table)) + .get("count", Long.class)); + } + + private static Database database(String target) throws Exception { + String schema = "hosted_terms_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema, + postgres.getUsername(), + postgres.getPassword()); + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + schema); + } + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(source); + Database db = + new Database( + schema, + source, + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), + transactionManager, + new TransactionTemplate(transactionManager)); + migrate(db, target); + return db; + } + + private static void migrate(Database db, String target) { + Flyway.configure() + .dataSource(db.source()) + .schemas(db.schema()) + .defaultSchema(db.schema()) + .placeholders(Map.of("serviceSchema", db.schema())) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + } + + private static void tx(Database db, Runnable work) { + db.transactions().executeWithoutResult(status -> work.run()); + } + + private record Database( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactions) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java new file mode 100644 index 0000000000..917e44db0e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java @@ -0,0 +1,646 @@ +package integration.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.Statement; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +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.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof with explicitly test-only environment publisher and identity authorities. */ +@Testcontainers(disabledWithoutDocker = true) +class HostedTermsEnvironmentBindingPostgresIntegrationTest { + private static final String TEST_NAMESPACE = "hosted-terms-binding-isolated-test"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersions() + throws Exception { + Database db = database("95"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + AtomicReference boundary = + new AtomicReference<>(currentBoundary("production")); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary); + + assertThat(count(db, "account_hosted_terms_environment_binding_heads")).isZero(); + assertThat(count(db, "account_hosted_terms_environment_bindings")).isZero(); + assertThat(count(db, "account_hosted_terms_environment_binding_publications")).isZero(); + + UUID firstTermsRequest = UUID.randomUUID(); + catalogPublications.put( + firstTermsRequest, + publication( + scopeId, + "test-only terms version one".getBytes(), + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(10))); + HostedTermsCatalogVersion firstCatalog = service.publish(firstTermsRequest).candidate(); + UUID acceptanceRequest = UUID.randomUUID(); + actions.put(acceptanceRequest, action(acceptanceRequest, accountId, partyId, firstCatalog)); + var acceptance = service.accept(acceptanceRequest); + + UUID firstBindingRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence firstBindingEvidence = + bindingEvidence("production", firstCatalog, null, null, "test-only-publisher-v1"); + bindingPublications.put(firstBindingRequest, firstBindingEvidence); + var firstBinding = service.publishEnvironmentBinding(firstBindingRequest); + assertThat(firstBinding.status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + assertThat(firstBinding.candidate().sourceVersion()).isOne(); + assertThat(firstBinding.exactReceipt()) + .containsExactly(HostedTermsEnvironmentBindingEncoding.receipt(firstBinding.candidate())); + assertThat(service.publishEnvironmentBinding(firstBindingRequest)).isEqualTo(firstBinding); + assertThat( + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT current_binding_id FROM account_hosted_terms_environment_binding_heads " + + "WHERE environment_boundary = 'production'")) + .get("current_binding_id", UUID.class)) + .isEqualTo(firstBinding.candidate().bindingId()); + + HostedTermsEnvironmentBinding.PublicationEvidence changedRetry = + bindingEvidence("production", firstCatalog, null, null, "changed-test-publisher"); + bindingPublications.put(firstBindingRequest, changedRetry); + assertThatThrownBy(() -> service.publishEnvironmentBinding(firstBindingRequest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + bindingPublications.put(firstBindingRequest, firstBindingEvidence); + + var current = service.requireCurrentnessForCurrentEnvironment(partyId); + assertThat(current.environment().environmentBoundary()).isEqualTo("production"); + assertThat(current.binding()).isEqualTo(firstBinding.candidate()); + assertThat(current.terms().acceptanceEvidenceId()).isEqualTo(acceptance.evidenceId()); + assertThat(current.sourceEvidence()).hasSize(3); + assertThat(current.sourceEvidence()) + .anySatisfy( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.scopeId()).isEqualTo("environment-boundary/production"); + assertThat(source.generation()).isNull(); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(source.evidence()) + .containsExactly( + HostedTermsEnvironmentBindingEncoding.receipt(firstBinding.candidate())); + }) + .anySatisfy( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.scopeId()).isEqualTo(scopeId.toString()); + assertThat(source.generation()).isEqualTo("1"); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(new String(source.evidence(), StandardCharsets.UTF_8)) + .contains("account-hosted-terms-currentness-source/v2") + .contains(HostedTermsEncoding.digest(HostedTermsEncoding.acceptance(acceptance))); + }) + .anySatisfy( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.CREATOR_PARTY); + assertThat(source.scopeId()).isEqualTo(partyId.toString()); + assertThat(source.generation()).isEqualTo("1"); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(source.evidence()).containsExactly(CreatorPartyEncoding.party(party)); + }); + + UUID nextTermsRequest = UUID.randomUUID(); + catalogPublications.put( + nextTermsRequest, + publication( + scopeId, + "test-only nonmaterial terms version two".getBytes(), + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + now().minusSeconds(5))); + HostedTermsCatalogVersion secondCatalog = service.publish(nextTermsRequest).candidate(); + assertThat(secondCatalog.sourceVersion()).isEqualTo(2); + assertThat(secondCatalog.materialGeneration()).isEqualTo(1); + assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed catalog authority"); + + UUID secondBindingRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence secondBindingEvidence = + bindingEvidence( + "production", + secondCatalog, + firstBinding.candidate().bindingId(), + firstBinding.candidate().sourceVersion(), + "test-only-publisher-v2"); + bindingPublications.put(secondBindingRequest, secondBindingEvidence); + var secondBinding = service.publishEnvironmentBinding(secondBindingRequest); + assertThat(secondBinding.status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + assertThat(secondBinding.candidate().sourceVersion()).isEqualTo(2); + assertThat(secondBinding.candidate().catalogSourceVersion()).isEqualTo(2); + assertThat(secondBinding.candidate().predecessorBindingId()) + .isEqualTo(firstBinding.candidate().bindingId()); + assertThat(service.publishEnvironmentBinding(secondBindingRequest)).isEqualTo(secondBinding); + HostedTermsEnvironmentBindingRepository bindingRepository = + new HostedTermsEnvironmentBindingRepository(db.dsl()); + assertThat(count(db, "account_hosted_terms_environment_bindings")).isEqualTo(2); + HostedTermsEnvironmentBinding retainedBinding = + db.transactions() + .execute( + ignored -> + bindingRepository.readBinding( + "production", firstBinding.candidate().bindingId())); + assertThat(retainedBinding).isEqualTo(firstBinding.candidate()); + assertThat(service.requireCurrentnessForCurrentEnvironment(partyId).binding()) + .isEqualTo(secondBinding.candidate()); + + boundary.set(currentBoundary("unbound-test-environment")); + assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("head is unavailable"); + } + + @Test + void bindingUpdateWaitsForExactTerminalSettlementOfAffectedDraftOperation() throws Exception { + Database db = database("95"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + AtomicReference boundary = + new AtomicReference<>(currentBoundary("settlement-test-environment")); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary); + + UUID termsRequest = UUID.randomUUID(); + catalogPublications.put( + termsRequest, + publication( + scopeId, + "test-only terms for settlement proof".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.INITIAL, + now().minusSeconds(10))); + HostedTermsCatalogVersion catalog = service.publish(termsRequest).candidate(); + UUID acceptanceRequest = UUID.randomUUID(); + actions.put(acceptanceRequest, action(acceptanceRequest, accountId, partyId, catalog)); + service.accept(acceptanceRequest); + + UUID firstRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence firstEvidence = + bindingEvidence( + "settlement-test-environment", catalog, null, null, "test-only-publisher-v1"); + bindingPublications.put(firstRequest, firstEvidence); + var first = service.publishEnvironmentBinding(firstRequest); + var captured = service.requireCurrentnessForCurrentEnvironment(partyId); + + // This is an explicit isolated-test fence fixture, not proof of the missing authenticated + // Draft producer. The Account binding update still uses the real PostgreSQL owner/fence repos. + DraftAuthorizationFenceBinding pendingDraft = + testDraftBinding(accountId, captured.sourceEvidence()); + var draftFences = new DraftAuthorizationFenceRepository(db.dsl()); + tx(db, () -> draftFences.reserve(pendingDraft)); + + UUID secondRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence secondEvidence = + bindingEvidence( + "settlement-test-environment", + catalog, + first.candidate().bindingId(), + first.candidate().sourceVersion(), + "test-only-publisher-v2"); + bindingPublications.put(secondRequest, secondEvidence); + var pendingBinding = service.publishEnvironmentBinding(secondRequest); + assertThat(pendingBinding.status()) + .isEqualTo( + HostedTermsEnvironmentBindingRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT); + assertThat(pendingBinding.candidate().sourceVersion()).isEqualTo(2); + assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source change is unresolved"); + String pendingDraftOrdering = + db.transactions().execute(ignored -> draftFences.read(pendingDraft).ordering().name()); + assertThat(pendingDraftOrdering).isEqualTo("REVOKE_ORDER"); + DraftAuthorizationFenceRepository.Settlement pendingSettlement = + db.transactions().execute(ignored -> draftFences.readSettlement(pendingDraft)); + assertThat(pendingSettlement).isEqualTo(DraftAuthorizationFenceRepository.Settlement.PENDING); + + // Explicitly simulated terminal abort evidence satisfies both original required owners. + tx( + db, + () -> { + draftFences.recordOwnerReadback( + pendingDraft, testReadback(pendingDraft, Owner.WORLD, new byte[] {1})); + draftFences.recordOwnerReadback( + pendingDraft, testReadback(pendingDraft, Owner.GAME_DESIGN, new byte[] {2})); + }); + assertThat(service.resumeEnvironmentBinding(secondRequest).status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + DraftAuthorizationFenceRepository.Settlement completedSettlement = + db.transactions().execute(ignored -> draftFences.readSettlement(pendingDraft)); + assertThat(completedSettlement) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.FAILED_NONPUBLICATION); + assertThat(service.requireCurrentnessForCurrentEnvironment(partyId).binding().sourceVersion()) + .isEqualTo(2); + } + + @Test + void boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline() throws Exception { + Database db = database("95"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + AtomicReference boundary = + new AtomicReference<>(currentBoundary("deadline-test-environment")); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary); + + UUID initialRequest = UUID.randomUUID(); + catalogPublications.put( + initialRequest, + publication( + scopeId, + "test-only current terms".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.INITIAL, + databaseNow(db).minusSeconds(10))); + HostedTermsCatalogVersion currentCatalog = service.publish(initialRequest).candidate(); + UUID acceptanceRequest = UUID.randomUUID(); + actions.put(acceptanceRequest, action(acceptanceRequest, accountId, partyId, currentCatalog)); + var acceptance = service.accept(acceptanceRequest); + + UUID bindingRequest = UUID.randomUUID(); + bindingPublications.put( + bindingRequest, + bindingEvidence( + "deadline-test-environment", currentCatalog, null, null, "test-only-publisher")); + service.publishEnvironmentBinding(bindingRequest); + + Instant deadline = databaseNow(db).plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.MICROS); + UUID scheduledRequest = UUID.randomUUID(); + catalogPublications.put( + scheduledRequest, + publication( + scopeId, + "test-only scheduled terms".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.MATERIAL, + deadline)); + HostedTermsCatalogVersion scheduled = service.publish(scheduledRequest).candidate(); + + var currentness = service.requireCurrentnessForCurrentEnvironment(partyId); + assertThat(currentness.terms().acceptanceEvidenceId()).isEqualTo(acceptance.evidenceId()); + assertThat(currentness.terms().validUntil()).isEqualTo(scheduled.effectiveAt()); + assertThat(currentness.terms().disclosedDeadline()).isEqualTo(scheduled); + byte[] exactTermsSource = + HostedTermsEncoding.currentnessSource(currentCatalog, acceptance, scheduled); + assertThat(currentness.terms().exactCurrentnessSource()).containsExactly(exactTermsSource); + assertThat(currentness.sourceEvidence()) + .filteredOn(source -> source.scopeId().equals(scopeId.toString())) + .singleElement() + .satisfies( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.generation()).isEqualTo("1"); + assertThat(source.sourceVersion()).isEqualTo("1"); + assertThat(source.evidence()).containsExactly(exactTermsSource); + assertThat(new String(source.evidence(), StandardCharsets.UTF_8)) + .contains(HostedTermsEncoding.digest(HostedTermsEncoding.catalog(scheduled))); + }); + } + + private static DraftAuthorizationFenceBinding testDraftBinding( + UUID actorAccountId, List sources) { + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof(tenantId, versionId, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + requestId, + commitId, + "opaque/base:1", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-only")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "test-region", + "aggregate", + "test-region", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + requestId, + commitId, + UUID.randomUUID(), + actorAccountId, + tenantId, + versionId, + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + sources) + .withRequiredOwners(); + } + + private static OwnerReadback testReadback( + DraftAuthorizationFenceBinding binding, Owner owner, byte[] exactTestResult) { + return new OwnerReadback( + owner, + Outcome.DEFINITIVELY_ABORTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + exactTestResult); + } + + private static AccountHostedTermsService service( + Database db, + Map catalogPublications, + Map actions, + Map bindingPublications, + AtomicReference boundary) { + IndividualCreatorPartyRepository parties = + new IndividualCreatorPartyRepository( + db.dsl(), + new FreshTenantIdentityAssociationRepository(db.dsl(), TEST_NAMESPACE), + new AccountTenantCreationBootstrapOperationRepository(db.dsl())); + return new AccountHostedTermsService( + db.transactionManager(), + new HostedTermsRepository(db.dsl()), + parties, + new DraftAuthorizationFenceRepository(db.dsl()), + request -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull( + catalogPublications.get(request), "test-only catalog fixture"); + }, + request -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull( + actions.get(request), "test-only affirmative action fixture"); + }, + new HostedTermsEnvironmentBindingRepository(db.dsl()), + request -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull( + bindingPublications.get(request), "test-only owner fixture"); + }, + () -> { + assertOutsideOwnerTransaction(); + return Objects.requireNonNull(boundary.get()); + }); + } + + private static void assertOutsideOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Owner authority must be resolved outside Account locks"); + } + } + + private static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary currentBoundary( + String boundary) { + byte[] ownerEvidence = ("test-only-boundary:" + boundary).getBytes(); + return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + boundary, + "test-only-environment-owner/" + boundary, + "test-only-current-boundary-observation/" + boundary, + ownerEvidence, + HostedTermsEncoding.digest(ownerEvidence)); + } + + private static HostedTermsEnvironmentBinding.PublicationEvidence bindingEvidence( + String boundary, + HostedTermsCatalogVersion catalog, + UUID predecessorBindingId, + Long predecessorSourceVersion, + String publisher) { + return new HostedTermsEnvironmentBinding.PublicationEvidence( + boundary, + catalog.hostedScopeId(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + catalog.versionId(), + catalog.sourceVersion(), + publisher, + "test-only-publication-event/" + UUID.randomUUID(), + predecessorBindingId, + predecessorSourceVersion); + } + + private static AccountHostedTermsService.PublicationEvidence publication( + UUID scope, + byte[] document, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt) { + return new AccountHostedTermsService.PublicationEvidence( + scope, + "Test Operator Legal Name", + 1, + document, + materiality, + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : "test-materiality", + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : 1L, + "test-only-legal-publication", + 1, + "test-only-notice", + 1, + effectiveAt.truncatedTo(ChronoUnit.MICROS)); + } + + private static AccountHostedTermsService.AcceptanceAction action( + UUID requestId, UUID accountId, UUID partyId, HostedTermsCatalogVersion catalog) { + return new AccountHostedTermsService.AcceptanceAction( + requestId, + true, + accountId, + partyId, + catalog.hostedScopeId(), + catalog.versionId(), + catalog.documentDigest(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + "test-only-authenticated-individual-action", + 1, + OffsetDateTime.ofInstant(now(), ZoneOffset.UTC)); + } + + private static IndividualCreatorPartySource party(UUID partyId, UUID accountId) { + return new IndividualCreatorPartySource( + partyId, + accountId, + VerificationStatus.VERIFIED, + 1, + "test-only-identity-policy", + 1L, + "test-only-verified-identity-evidence", + 1L, + 1); + } + + private static void insertParty(Database db, IndividualCreatorPartySource party) { + byte[] payload = CreatorPartyEncoding.party(party); + db.dsl() + .execute( + "INSERT INTO account_individual_creator_party_sources " + + "(creator_party_id, account_uuid, verification_status, identity_version, " + + "policy_reference, policy_version, verification_evidence_reference, " + + "verification_evidence_version, source_version, source_payload, source_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + payload, + CreatorPartyEncoding.digest(payload)); + } + + private static UUID insertAccount(Database db) { + UUID id = UUID.randomUUID(); + db.dsl() + .execute( + "INSERT INTO accounts (account_uuid, username, email, password_hash) " + + "VALUES (?, ?, ?, 'test-only-password-hash')", + id, + "hosted-binding-" + id.toString().substring(0, 8), + id + "@example.test"); + return id; + } + + private static Instant now() { + return Instant.now().truncatedTo(ChronoUnit.MICROS); + } + + private static Instant databaseNow(Database db) { + return Objects.requireNonNull(db.dsl().fetchOne("SELECT clock_timestamp() AS database_now")) + .get("database_now", OffsetDateTime.class) + .toInstant() + .truncatedTo(ChronoUnit.MICROS); + } + + private static long count(Database db, String table) { + return Objects.requireNonNull(db.dsl().fetchOne("SELECT count(*) AS count FROM " + table)) + .get("count", Long.class); + } + + private static Database database(String target) throws Exception { + String schema = "terms_binding_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema, + postgres.getUsername(), + postgres.getPassword()); + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + schema); + } + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(source); + Database db = + new Database( + schema, + source, + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), + transactionManager, + new TransactionTemplate(transactionManager)); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + return db; + } + + private static void tx(Database db, Runnable work) { + db.transactions().executeWithoutResult(ignored -> work.run()); + } + + private record Database( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactions) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java index 45ad6ec7b0..0d46717f09 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java @@ -4,8 +4,9 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; import java.util.Objects; -import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; @@ -172,7 +173,8 @@ void preV40RetainedPasswordResetFailsTypedAndRollsBackWithoutInventingSource() { } @Test - void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws Exception { + void freshAccountBaselineIsValidButGenericSaveHistoryCannotAuthorizeSecurityCurrentness() + throws Exception { TestContext context = newTestContext(); DSLContext dsl = context.dsl(); TransactionTemplate transaction = context.transaction(); @@ -228,29 +230,17 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws account.setEmailVerified(true); transaction.executeWithoutResult(status -> accounts.save(account)); - var changed = - transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); - assertThat(changed.account().generation()).isEqualTo(3L); - assertThat(changed.account().sourceVersion()).isEqualTo(3L); - assertThat(changed.account().issuanceFence().value()).isEqualTo(3L); - assertThat(changed.account().checkpoint().sequence()).isEqualTo(2L); - assertThat(changed.account().accountSecurityCutoff()).isPresent(); - assertThat(changed.account().accountSecurityCutoff().orElseThrow().accountAuthorityGeneration()) - .isEqualTo("3"); - assertThat(changed.account().accountSecurityCutoff().orElseThrow().outboxSequence()) - .isEqualTo("2"); + String streamKey = + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + + "account/" + + account.getAccountUuid(); AccountEvent passwordReset = (AccountEvent) AccountAuthoritySourceEventV1Codec.verify( new String( transaction.execute( - status -> - outbox - .findEvent(changed.account().checkpoint().outboxStreamKey(), 1L) - .orElseThrow() - .payload()), - java.nio.charset.StandardCharsets.UTF_8)); + status -> outbox.findEvent(streamKey, 1L).orElseThrow().payload()), + StandardCharsets.UTF_8)); assertThat(passwordReset.mutationKinds()).containsExactly("PASSWORD_RESET"); assertThat(passwordReset.canonicalJson()).doesNotContain("changed-password-hash-not-for-event"); AccountEvent latest = @@ -258,15 +248,17 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws AccountAuthoritySourceEventV1Codec.verify( new String( transaction.execute( - status -> - outbox - .findEvent(changed.account().checkpoint().outboxStreamKey(), 2L) - .orElseThrow() - .payload()), - java.nio.charset.StandardCharsets.UTF_8)); + status -> outbox.findEvent(streamKey, 2L).orElseThrow().payload()), + StandardCharsets.UTF_8)); assertThat(latest.mutationKinds()).containsExactly("EMAIL_LOGIN_ELIGIBILITY_CHANGED"); - assertThat(latest.accountSecurityCutoff().outboxSequence()).isEqualTo("2"); assertThat(latest.canonicalJson()).doesNotContain("changed-password-hash-not-for-event"); + assertThatThrownBy( + () -> + transaction.execute( + status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event schema is unsupported"); Account rollbackAttempt = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); rollbackAttempt.setPasswordHash("rollback-only-password-hash"); @@ -279,30 +271,54 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("force Account source event rollback"); - var afterRollback = - transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); + assertThat(accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow().getPasswordHash()) + .isEqualTo("changed-password-hash-not-for-event"); + var rolledBackEvent = transaction.execute(status -> outbox.findEvent(streamKey, 3L)); + assertThat(rolledBackEvent).isEmpty(); assertThat( accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow().getLifecycleState()) .isEqualTo(AccountLifecycleState.ACTIVE); - assertThat(afterRollback.account().generation()).isEqualTo(3L); - assertThat(afterRollback.account().issuanceFence().value()).isEqualTo(3L); - assertThat(afterRollback.account().checkpoint().sequence()).isEqualTo(2L); - assertThat(afterRollback.account().accountSecurityCutoff().orElseThrow().outboxSequence()) - .isEqualTo("2"); - Optional rolledBackEvent = - transaction.execute( - status -> outbox.findEvent(changed.account().checkpoint().outboxStreamKey(), 3L)); - assertThat(rolledBackEvent).isEmpty(); + assertThatThrownBy( + () -> + transaction.execute( + status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event schema is unsupported"); Account lifecycleUpdate = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); lifecycleUpdate.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); + var accountBeforeLifecycleRejection = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM accounts WHERE account_uuid = ?", account.getAccountUuid()), + "expected Account before lifecycle rejection") + .intoMap(); + var generationsBeforeLifecycleRejection = + dsl.fetch( + "SELECT * FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + account.getAccountUuid()) + .intoMaps(); + var fencesBeforeLifecycleRejection = + dsl.fetch( + "SELECT * FROM account_authority_issuance_fences WHERE account_uuid = ?", + account.getAccountUuid()) + .intoMaps(); + var sourceRowsBeforeLifecycleRejection = + dsl.fetch( + "SELECT * FROM account_authority_source_records WHERE account_uuid = ?", + account.getAccountUuid()) + .intoMaps(); + var outboxRowsBeforeLifecycleRejection = + dsl.fetch( + "SELECT * FROM account_authority_outbox_events WHERE outbox_stream_key = ? " + + "ORDER BY outbox_sequence", + streamKey) + .intoMaps(); assertThatThrownBy( () -> transaction.executeWithoutResult(status -> accounts.save(lifecycleUpdate))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("lifecycle changes are unavailable"); - var afterLifecycleUpdate = - transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); Account persistedAfterLifecycleRejection = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); assertThat(persistedAfterLifecycleRejection.getLifecycleState()) @@ -311,15 +327,48 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws .isEqualTo(account.getPasswordHash()); assertThat(lifecycleUpdate.getLifecycleState()) .isEqualTo(AccountLifecycleState.SECURITY_LOCKED); - assertThat(afterLifecycleUpdate.account().generation()).isEqualTo(3L); - assertThat(afterLifecycleUpdate.account().issuanceFence().value()).isEqualTo(3L); - assertThat(afterLifecycleUpdate.account().checkpoint().sequence()).isEqualTo(2L); - var absentLifecycleEvent = - transaction.execute( - status -> - outbox.findEvent( - afterLifecycleUpdate.account().checkpoint().outboxStreamKey(), 3L)); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM accounts WHERE account_uuid = ?", account.getAccountUuid()), + "expected Account after lifecycle rejection") + .intoMap()) + .isEqualTo(accountBeforeLifecycleRejection); + assertThat( + dsl.fetch( + "SELECT * FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + account.getAccountUuid()) + .intoMaps()) + .isEqualTo(generationsBeforeLifecycleRejection); + assertThat( + dsl.fetch( + "SELECT * FROM account_authority_issuance_fences WHERE account_uuid = ?", + account.getAccountUuid()) + .intoMaps()) + .isEqualTo(fencesBeforeLifecycleRejection); + assertThat( + dsl.fetch( + "SELECT * FROM account_authority_source_records WHERE account_uuid = ?", + account.getAccountUuid()) + .intoMaps()) + .isEqualTo(sourceRowsBeforeLifecycleRejection); + assertOutboxRowsEqual( + outboxRowsBeforeLifecycleRejection, + dsl.fetch( + "SELECT * FROM account_authority_outbox_events WHERE outbox_stream_key = ? " + + "ORDER BY outbox_sequence", + streamKey) + .intoMaps()); + var absentLifecycleEvent = transaction.execute(status -> outbox.findEvent(streamKey, 3L)); assertThat(absentLifecycleEvent).isEmpty(); + assertThatThrownBy( + () -> + transaction.execute( + status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event schema is unsupported"); assertThatThrownBy(() -> accounts.delete(account)) .isInstanceOf(IllegalStateException.class) @@ -335,8 +384,28 @@ void freshAccountBaselineAndSecurityMutationsCommitExactSourceEvidence() throws assertThat(accounts.findByAccountUuid(account.getAccountUuid())).isPresent(); } + private static void assertOutboxRowsEqual( + List> expected, List> actual) { + assertThat(actual).hasSize(expected.size()); + for (int index = 0; index < expected.size(); index++) { + Map expectedRow = expected.get(index); + Map actualRow = actual.get(index); + assertThat(actualRow.keySet()).isEqualTo(expectedRow.keySet()); + for (Map.Entry entry : expectedRow.entrySet()) { + String field = entry.getKey(); + Object expectedValue = entry.getValue(); + Object actualValue = actualRow.get(field); + if ("payload".equals(field)) { + assertThat((byte[]) actualValue).containsExactly((byte[]) expectedValue); + } else { + assertThat(actualValue).isEqualTo(expectedValue); + } + } + } + } + @Test - void freshAccountWithNullGlobalRoleCanCommitSecurityMutationSourceEvent() { + void genericSaveHistoryWithNullGlobalRoleDoesNotAuthorizeCanonicalCurrentness() { TestContext context = newTestContext(); DSLContext dsl = context.dsl(); TransactionTemplate transaction = context.transaction(); @@ -357,16 +426,12 @@ void freshAccountWithNullGlobalRoleCanCommitSecurityMutationSourceEvent() { account.setPasswordHash("changed-null-role-account-password-hash"); transaction.executeWithoutResult(status -> accounts.save(account)); - var changed = - transaction.execute( - status -> sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid())); - assertThat(changed.account().checkpoint().sequence()).isEqualTo(1L); + String streamKey = + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + + "account/" + + account.getAccountUuid(); AccountAuthorityOutboxRepository.Event storedEvent = - transaction.execute( - status -> - outbox - .findEvent(changed.account().checkpoint().outboxStreamKey(), 1L) - .orElseThrow()); + transaction.execute(status -> outbox.findEvent(streamKey, 1L).orElseThrow()); AccountEvent event = (AccountEvent) AccountAuthoritySourceEventV1Codec.verify( @@ -376,6 +441,13 @@ void freshAccountWithNullGlobalRoleCanCommitSecurityMutationSourceEvent() { assertThat(event.accountState().globalRole()).isNull(); assertThat(event.canonicalJson()).contains("\"globalRole\":null"); assertThat(event.canonicalJson()).doesNotContain("changed-null-role-account-password-hash"); + assertThatThrownBy( + () -> + transaction.execute( + status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event schema is unsupported"); } @Test @@ -535,32 +607,23 @@ void concurrentAccountMutationAndAuthorityReadUseAccountRowBeforeGenerationLocks awaitLockWait(dsl, readerPid, writerPid); releaseWriter.countDown(); writer.get(45, TimeUnit.SECONDS); - var readback = snapshot.get(45, TimeUnit.SECONDS); - assertThat(readback.account().generation()).isEqualTo(2L); - assertThat(readback.account().sourceVersion()).isEqualTo(2L); - assertThat(readback.account().issuanceFence().value()).isEqualTo(2L); - assertThat(readback.account().issuanceFence().sourceVersion()).isEqualTo(2L); - assertThat(readback.account().checkpoint().sequence()).isEqualTo(1L); + assertThatThrownBy(() -> snapshot.get(45, TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasRootCauseMessage("Account source event schema is unsupported"); + String streamKey = + AccountAuthoritySourceEventV1Codec.EVENT_STREAM_PREFIX + + "account/" + + account.getAccountUuid(); AccountAuthorityOutboxRepository.Event committedEvent = - transaction.execute( - status -> - outbox - .findEvent(readback.account().checkpoint().outboxStreamKey(), 1L) - .orElseThrow()); - assertThat(committedEvent.eventId()) - .isEqualTo(readback.account().checkpoint().sourceEventId().orElseThrow()); - assertThat(committedEvent.eventDigest()) - .isEqualTo(readback.account().checkpoint().sourceEventDigest().orElseThrow()); + transaction.execute(status -> outbox.findEvent(streamKey, 1L).orElseThrow()); AccountEvent event = (AccountEvent) AccountAuthoritySourceEventV1Codec.verify( new String(committedEvent.payload(), StandardCharsets.UTF_8)); assertThat(event.accountId()).isEqualTo(account.getAccountUuid().toString()); assertThat(event.outboxSequence()).isEqualTo("1"); - assertThat(event.accountAuthorityGeneration()).isEqualTo("2"); - assertThat(event.sourceVersion()).isEqualTo("2"); - assertThat(event.issuanceFence()).isEqualTo("2"); assertThat(event.mutationKinds()).containsExactly("PASSWORD_RESET"); + assertThat(event.canonicalJson()).doesNotContain("lock-order-updated-hash"); } finally { startLockPhase.countDown(); releaseWriter.countDown(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java index 29c8966353..344a1c8da6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java @@ -80,7 +80,7 @@ void appendsContiguousPerStreamAndReplaysOnlyExactRequestEvidence() { AccountAuthorityOutboxRepository repository = context.repository(); TransactionTemplate transaction = context.transaction(); String stream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); - String unrelated = "account:auth-authority:v1:tenant/" + UUID.randomUUID(); + String unrelated = membershipStream(UUID.randomUUID(), UUID.randomUUID()); assertThat(inTransaction(transaction, () -> repository.readCheckpoint(stream))).isEmpty(); @@ -338,7 +338,7 @@ void missingHeadWithNoExactHistoryIsEmptyDespiteAnotherStreamsRetainedEvent() { TransactionTemplate transaction = context.transaction(); DSLContext dsl = context.dsl(); String missingStream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); - String retainedStream = "account:auth-authority:v1:tenant/" + UUID.randomUUID(); + String retainedStream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); byte[] retainedPayload = new byte[] {4, 5, 6}; Event retained = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index f00f397145..3e6670d172 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -20,6 +20,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; import net.firedevops.firemud.accountservice.dto.AccountAuditDigest; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.dto.RealmAccessGrantRequest; @@ -699,6 +700,37 @@ private Account saveInTransaction(Account account) { .execute(status -> repository.save(account))); } + /** + * Test-only lifecycle row shaping in a rolled-back transaction; this is not proof of a production + * lifecycle transition. + */ + private void withTestOnlyPersistedLifecycle( + AccountLifecycleState lifecycleState, Consumer assertions) { + new TransactionTemplate(new DataSourceTransactionManager(dataSource)) + .executeWithoutResult( + status -> { + Account persisted = + account("original", "original@example.com", AccountLifecycleState.ACTIVE); + persisted.setPasswordHash("original-password-hash"); + Account saved = repository.save(persisted); + if (lifecycleState != AccountLifecycleState.ACTIVE) { + // This row image exists only for generic-save assertions and is always rolled back. + int updatedRows = + dsl.execute( + "UPDATE accounts SET lifecycle_state = ? WHERE id = ?", + lifecycleState.storageValue(), + saved.getId()); + if (updatedRows != 1) { + throw new IllegalStateException( + "Test-only lifecycle row shaping did not update one Account"); + } + saved.setLifecycleState(lifecycleState); + } + assertions.accept(saved); + status.setRollbackOnly(); + }); + } + @Test void connectScopeRepositoryRetainsCanonicalRealmUuidAndDetectsTampering() { JdbcTemplate jdbc = new JdbcTemplate(dataSource); @@ -928,116 +960,120 @@ private static VerifiedJoinScope joinScope( @EnumSource(AccountLifecycleState.class) void genericUpdateRejectsLifecycleChangeWithoutMutatingAccountOrAuthorityEvidence( AccountLifecycleState lifecycleState) { - Account persisted = account("original", "original@example.com", lifecycleState); - persisted.setPasswordHash("original-password-hash"); - Account saved = saveInTransaction(persisted); - UUID accountUuid = saved.getAccountUuid(); - - AccountLifecycleState requestedLifecycleState = - lifecycleState == AccountLifecycleState.ACTIVE - ? AccountLifecycleState.SECURITY_LOCKED - : AccountLifecycleState.ACTIVE; - Account staleUpdate = account("updated", "updated@example.com", requestedLifecycleState); - staleUpdate.setPasswordHash("updated-password-hash"); - staleUpdate.setId(saved.getId()); - - String accountBefore = - jsonRow( - "SELECT jsonb_build_object('username', username, 'email', email, " - + "'password_hash', password_hash, 'lifecycle_state', lifecycle_state)::text " - + "FROM accounts WHERE id = ?", - saved.getId()); - String generationBefore = - jsonRow( - "SELECT to_jsonb(generation_row)::text FROM account_authority_generations " - + "AS generation_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", - accountUuid); - String fenceBefore = - jsonRow( - "SELECT to_jsonb(fence_row)::text FROM account_authority_issuance_fences " - + "AS fence_row WHERE account_uuid = ?", - accountUuid); - String checkpointBefore = - jsonRow( - "SELECT to_jsonb(source_row)::text FROM account_authority_source_records " - + "AS source_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", - accountUuid); - String outboxStreamBefore = - jsonRow( - "SELECT to_jsonb(stream_row)::text FROM account_authority_outbox_streams " - + "AS stream_row WHERE outbox_stream_key = ?", - "account:auth-authority:v1:account/" + accountUuid); - String outboxEventsBefore = - jsonRow( - "SELECT COALESCE(jsonb_agg(to_jsonb(event_row) ORDER BY outbox_sequence), " - + "'[]'::jsonb)::text FROM account_authority_outbox_events AS event_row " - + "WHERE outbox_stream_key = ?", - "account:auth-authority:v1:account/" + accountUuid); - - assertThatThrownBy(() -> saveInTransaction(staleUpdate)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Account lifecycle changes are unavailable through generic Account saves"); + withTestOnlyPersistedLifecycle( + lifecycleState, + saved -> { + UUID accountUuid = saved.getAccountUuid(); + + AccountLifecycleState requestedLifecycleState = + lifecycleState == AccountLifecycleState.ACTIVE + ? AccountLifecycleState.SECURITY_LOCKED + : AccountLifecycleState.ACTIVE; + Account staleUpdate = account("updated", "updated@example.com", requestedLifecycleState); + staleUpdate.setPasswordHash("updated-password-hash"); + staleUpdate.setId(saved.getId()); + + String accountBefore = + jsonRow( + "SELECT jsonb_build_object('username', username, 'email', email, " + + "'password_hash', password_hash, 'lifecycle_state', lifecycle_state)::text " + + "FROM accounts WHERE id = ?", + saved.getId()); + String generationBefore = + jsonRow( + "SELECT to_jsonb(generation_row)::text FROM account_authority_generations " + + "AS generation_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid); + String fenceBefore = + jsonRow( + "SELECT to_jsonb(fence_row)::text FROM account_authority_issuance_fences " + + "AS fence_row WHERE account_uuid = ?", + accountUuid); + String checkpointBefore = + jsonRow( + "SELECT to_jsonb(source_row)::text FROM account_authority_source_records " + + "AS source_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid); + String outboxStreamBefore = + jsonRow( + "SELECT to_jsonb(stream_row)::text FROM account_authority_outbox_streams " + + "AS stream_row WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + accountUuid); + String outboxEventsBefore = + jsonRow( + "SELECT COALESCE(jsonb_agg(to_jsonb(event_row) ORDER BY outbox_sequence), " + + "'[]'::jsonb)::text FROM account_authority_outbox_events AS event_row " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + accountUuid); + + assertThatThrownBy(() -> saveInTransaction(staleUpdate)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Account lifecycle changes are unavailable through generic Account saves"); - assertThat( - jsonRow( - "SELECT jsonb_build_object('username', username, 'email', email, " - + "'password_hash', password_hash, 'lifecycle_state', lifecycle_state)::text " - + "FROM accounts WHERE id = ?", - saved.getId())) - .isEqualTo(accountBefore); - assertThat( - jsonRow( - "SELECT to_jsonb(generation_row)::text FROM account_authority_generations " - + "AS generation_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", - accountUuid)) - .isEqualTo(generationBefore); - assertThat( - jsonRow( - "SELECT to_jsonb(fence_row)::text FROM account_authority_issuance_fences " - + "AS fence_row WHERE account_uuid = ?", - accountUuid)) - .isEqualTo(fenceBefore); - assertThat( - jsonRow( - "SELECT to_jsonb(source_row)::text FROM account_authority_source_records " - + "AS source_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", - accountUuid)) - .isEqualTo(checkpointBefore); - assertThat( - jsonRow( - "SELECT to_jsonb(stream_row)::text FROM account_authority_outbox_streams " - + "AS stream_row WHERE outbox_stream_key = ?", - "account:auth-authority:v1:account/" + accountUuid)) - .isEqualTo(outboxStreamBefore); - assertThat( - jsonRow( - "SELECT COALESCE(jsonb_agg(to_jsonb(event_row) ORDER BY outbox_sequence), " - + "'[]'::jsonb)::text FROM account_authority_outbox_events AS event_row " - + "WHERE outbox_stream_key = ?", - "account:auth-authority:v1:account/" + accountUuid)) - .isEqualTo(outboxEventsBefore); + assertThat( + jsonRow( + "SELECT jsonb_build_object('username', username, 'email', email, " + + "'password_hash', password_hash, 'lifecycle_state', lifecycle_state)::text " + + "FROM accounts WHERE id = ?", + saved.getId())) + .isEqualTo(accountBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(generation_row)::text FROM account_authority_generations " + + "AS generation_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid)) + .isEqualTo(generationBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(fence_row)::text FROM account_authority_issuance_fences " + + "AS fence_row WHERE account_uuid = ?", + accountUuid)) + .isEqualTo(fenceBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(source_row)::text FROM account_authority_source_records " + + "AS source_row WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid)) + .isEqualTo(checkpointBefore); + assertThat( + jsonRow( + "SELECT to_jsonb(stream_row)::text FROM account_authority_outbox_streams " + + "AS stream_row WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + accountUuid)) + .isEqualTo(outboxStreamBefore); + assertThat( + jsonRow( + "SELECT COALESCE(jsonb_agg(to_jsonb(event_row) ORDER BY outbox_sequence), " + + "'[]'::jsonb)::text FROM account_authority_outbox_events AS event_row " + + "WHERE outbox_stream_key = ?", + "account:auth-authority:v1:account/" + accountUuid)) + .isEqualTo(outboxEventsBefore); + }); } @ParameterizedTest @EnumSource(AccountLifecycleState.class) void genericUpdateAllowsOrdinaryChangesWhenLifecycleMatches( AccountLifecycleState lifecycleState) { - Account persisted = account("original", "original@example.com", lifecycleState); - Account saved = saveInTransaction(persisted); - UUID accountUuid = saved.getAccountUuid(); - - Account ordinaryUpdate = account("updated", " Updated@Example.COM ", lifecycleState); - ordinaryUpdate.setPasswordHash("updated-password-hash"); - ordinaryUpdate.setId(saved.getId()); - Account updated = saveInTransaction(ordinaryUpdate); - - Account loaded = repository.findById(saved.getId()).orElseThrow(); - assertThat(loaded.getUsername()).isEqualTo("updated"); - assertThat(loaded.getEmail()).isEqualTo("updated@example.com"); - assertThat(loaded.getPasswordHash()).isEqualTo("updated-password-hash"); - assertThat(loaded.getLifecycleState()).isEqualTo(lifecycleState); - assertThat(updated.getAccountUuid()).isEqualTo(accountUuid); - assertThat(updated.getLifecycleState()).isEqualTo(lifecycleState); + withTestOnlyPersistedLifecycle( + lifecycleState, + saved -> { + UUID accountUuid = saved.getAccountUuid(); + + Account ordinaryUpdate = account("updated", " Updated@Example.COM ", lifecycleState); + ordinaryUpdate.setPasswordHash("updated-password-hash"); + ordinaryUpdate.setId(saved.getId()); + Account updated = saveInTransaction(ordinaryUpdate); + + Account loaded = repository.findById(saved.getId()).orElseThrow(); + assertThat(loaded.getUsername()).isEqualTo("updated"); + assertThat(loaded.getEmail()).isEqualTo("updated@example.com"); + assertThat(loaded.getPasswordHash()).isEqualTo("updated-password-hash"); + assertThat(loaded.getLifecycleState()).isEqualTo(lifecycleState); + assertThat(updated.getAccountUuid()).isEqualTo(accountUuid); + assertThat(updated.getLifecycleState()).isEqualTo(lifecycleState); + }); } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..cee0527906 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest.java @@ -0,0 +1,469 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Claim; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.OperationConflictException; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.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; + +/** + * Database-only storage proof for immutable creator-bootstrap receipts; synthetic evidence here is + * not proof of authenticated Account authorization or a production source participant. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountTenantCreationBootstrapOperationRepositoryPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "creator_bootstrap_operation_"; + private static final String AUDIT_EVENT_TYPE = "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void exactImmutableInputReplaysOriginalReceiptAndChangedSnapshotConflicts() { + TestContext context = newTestContext(); + FreshTenantCreatorEvidence evidence = evidence(UUID.randomUUID()); + RequestInput input = input(evidence); + insertAccount(context.setupDsl(), evidence.initiatingAccountId()); + + StoredOperation committed = + inTransaction( + context.transaction(), + () -> { + Claim claim = claim(context.repository(), input); + assertThat(claim.claimed()).isTrue(); + return context + .repository() + .complete(evidence.accountAuthorizationOperationId(), completion(evidence)); + }); + + assertThat(committed.status()).isEqualTo("COMMITTED"); + assertThat(committed.result().roles()).containsExactly("tenantAdmin"); + assertThat(committed.result().gameplayAdmissionAllowed()).isFalse(); + StoredOperation retry = + inTransaction( + context.transaction(), + () -> { + Claim claim = claim(context.repository(), input); + assertThat(claim.claimed()).isFalse(); + return claim.operation(); + }); + assertThat(retry.result()).isEqualTo(committed.result()); + assertThat(retry.resultPayload()).containsExactly(committed.resultPayload()); + + byte[] changedSource = + "same authorization ID, changed Account snapshot".getBytes(StandardCharsets.UTF_8); + byte[] changedRequest = + AccountTenantCreationBootstrapDigest.requestPayload(input.creatorPayload(), changedSource); + String changedSourceDigest = AccountTenantCreationBootstrapDigest.sha256(changedSource); + String changedRequestDigest = AccountTenantCreationBootstrapDigest.sha256(changedRequest); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), + () -> + context + .repository() + .claim( + evidence, + input.creatorPayload(), + changedSource, + changedSourceDigest, + changedRequest, + changedRequestDigest, + 1L, + 1L))) + .isInstanceOf(OperationConflictException.class) + .hasMessageContaining("changed source or Account snapshot"); + + RequestInput changedAuthorization = + input(withAuthorizationDigest(evidence, "sha256:" + "9".repeat(64))); + assertThatThrownBy( + () -> + inTransaction( + context.transaction(), () -> claim(context.repository(), changedAuthorization))) + .isInstanceOf(OperationConflictException.class) + .hasMessageContaining("changed source or Account snapshot"); + + assertThatThrownBy( + () -> + context + .setupDsl() + .execute( + "UPDATE account_tenant_creation_bootstrap_operations " + + "SET source_snapshot_payload = ? WHERE request_id = ?", + changedSource, + evidence.accountAuthorizationOperationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + context + .setupDsl() + .execute( + "DELETE FROM account_tenant_creation_bootstrap_operations WHERE request_id = ?", + evidence.accountAuthorizationOperationId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + @Test + void claimedReceiptRollsBackWithItsAccountTransaction() { + TestContext context = newTestContext(); + FreshTenantCreatorEvidence evidence = evidence(UUID.randomUUID()); + RequestInput input = input(evidence); + insertAccount(context.setupDsl(), evidence.initiatingAccountId()); + + assertThatThrownBy( + () -> + context + .transaction() + .execute( + status -> { + claim(context.repository(), input); + context + .repository() + .complete( + evidence.accountAuthorizationOperationId(), completion(evidence)); + throw new IllegalStateException( + "injected after immutable receipt readback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("injected after immutable receipt readback"); + assertThat( + java.util.Objects.requireNonNull( + context + .setupDsl() + .fetchOne( + "SELECT count(*) FROM account_tenant_creation_bootstrap_operations " + + "WHERE request_id = ?", + evidence.accountAuthorizationOperationId()), + "Rollback count query returned no row") + .get(0, Long.class)) + .isEqualTo(0L); + } + + @Test + void concurrentExactClaimsConvergeOnOneCommittedReceipt() throws Exception { + TestContext context = newTestContext(); + FreshTenantCreatorEvidence evidence = evidence(UUID.randomUUID()); + RequestInput input = input(evidence); + insertAccount(context.setupDsl(), evidence.initiatingAccountId()); + ExecutorService workers = Executors.newFixedThreadPool(2); + CountDownLatch firstCommittedInsideTransaction = new CountDownLatch(1); + CountDownLatch releaseFirstTransaction = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + try { + Future first = + workers.submit( + () -> + context + .transaction() + .execute( + status -> { + Claim initial = claim(context.repository(), input); + if (!initial.claimed()) { + throw new IllegalStateException("First exact claim was not unique"); + } + context + .repository() + .complete( + evidence.accountAuthorizationOperationId(), + completion(evidence)); + firstCommittedInsideTransaction.countDown(); + await(releaseFirstTransaction); + return initial.claimed(); + })); + assertThat(firstCommittedInsideTransaction.await(10, TimeUnit.SECONDS)).isTrue(); + Future second = + workers.submit( + () -> { + secondStarted.countDown(); + return context + .transaction() + .execute(status -> claim(context.repository(), input).claimed()); + }); + assertThat(secondStarted.await(10, TimeUnit.SECONDS)).isTrue(); + releaseFirstTransaction.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS)).isTrue(); + assertThat(second.get(10, TimeUnit.SECONDS)).isFalse(); + assertThat( + java.util.Objects.requireNonNull( + context + .setupDsl() + .fetchOne( + "SELECT count(*) FROM account_tenant_creation_bootstrap_operations " + + "WHERE request_id = ? AND status = 'COMMITTED'", + evidence.accountAuthorizationOperationId()), + "Committed count query returned no row") + .get(0, Long.class)) + .isEqualTo(1L); + } finally { + releaseFirstTransaction.countDown(); + workers.shutdownNow(); + } + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext setupDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + dataSource, + setupDsl, + new AccountTenantCreationBootstrapOperationRepository(transactionDsl), + new TransactionTemplate(new DataSourceTransactionManager(dataSource))); + } + + private static UUID insertAccount(DSLContext dsl, UUID accountUuid) { + String suffix = UUID.randomUUID().toString().replace("-", ""); + return dsl.resultQuery( + "INSERT INTO accounts (account_uuid, username, email, password_hash) " + + "VALUES (?, ?, ?, ?) RETURNING account_uuid", + accountUuid, + "creator_" + suffix.substring(0, 12), + suffix + "@example.test", + "test-hash") + .fetchOne(0, UUID.class); + } + + private static RequestInput input(FreshTenantCreatorEvidence evidence) { + byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); + byte[] sourcePayload = + AccountTenantCreationBootstrapDigest.sourceSnapshotPayload( + snapshot( + evidence.initiatingAccountId(), evidence.creationEvidence().canonicalTenantId())); + String sourceDigest = AccountTenantCreationBootstrapDigest.sha256(sourcePayload); + byte[] requestPayload = + AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload); + return new RequestInput( + evidence, + creatorPayload, + sourcePayload, + sourceDigest, + requestPayload, + AccountTenantCreationBootstrapDigest.sha256(requestPayload)); + } + + private static Claim claim( + AccountTenantCreationBootstrapOperationRepository repository, RequestInput input) { + return repository.claim( + input.evidence(), + input.creatorPayload(), + input.sourcePayload(), + input.sourceDigest(), + input.requestPayload(), + input.requestDigest(), + 1L, + 1L); + } + + private static Completion completion(FreshTenantCreatorEvidence evidence) { + UUID tenantUuid = evidence.creationEvidence().canonicalTenantId(); + String requestId = evidence.accountAuthorizationOperationId().toString(); + String stream = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + evidence.initiatingAccountId() + + "/" + + tenantUuid; + byte[] event = + "synthetic event bytes for repository storage proof".getBytes(StandardCharsets.UTF_8); + byte[] audit = + "synthetic audit bytes for repository storage proof".getBytes(StandardCharsets.UTF_8); + byte[] result = "synthetic immutable result bytes".getBytes(StandardCharsets.UTF_8); + return new Completion( + 51L, + 2L, + 1L, + "ACTIVE", + false, + "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8), + stream, + requestId, + 1L, + "creator-bootstrap-event-1", + digest(1), + false, + event, + UUID.randomUUID(), + AUDIT_EVENT_TYPE, + Instant.parse("2026-10-02T00:00:00Z"), + digest(2), + audit, + result, + AccountTenantCreationBootstrapDigest.sha256(result)); + } + + private static NeverJoinedMembershipSnapshot snapshot(UUID accountUuid, UUID tenantUuid) { + String account = accountUuid.toString(); + String tenant = tenantUuid.toString(); + String stream = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + account + + "/" + + tenant; + return new NeverJoinedMembershipSnapshot( + account, + tenant, + Map.of(tenant, "1"), + "1", + new AuthorityTuple( + "1", + "1", + Map.of(tenant, "1"), + Map.of(tenant, "1"), + List.of(), + Optional.empty(), + Optional.empty()), + "1", + Instant.parse("2026-10-01T00:00:00Z"), + stream, + List.of( + new OutboxCheckpointEntry("account:auth-authority:v1:account/" + account, "0"), + new OutboxCheckpointEntry( + "account:auth-authority:v1:issuer/firemud-account-service", "0"), + new OutboxCheckpointEntry(stream, "0"), + new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + tenant, "0")), + List.of()); + } + + private static FreshTenantCreatorEvidence evidence(UUID creatorUuid) { + UUID tenantUuid = UUID.randomUUID(); + UUID creationRequestId = UUID.randomUUID(); + UUID creationOperationId = UUID.randomUUID(); + UUID authorizationOperationId = UUID.randomUUID(); + String namespace = "firemud-test"; + String tenantKey = "repository-proof-17"; + String requestDigest = + GameTenantCreationDigest.requestDigest( + namespace, creationRequestId, tenantKey, "Example", null); + FreshTenantCreationEvidence creation = + new FreshTenantCreationEvidence( + 1, + namespace, + creationRequestId, + creationOperationId, + requestDigest, + tenantUuid, + 17L, + tenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + namespace, + creationRequestId, + creationOperationId, + requestDigest, + tenantUuid, + 17L, + tenantKey, + "NEW_GAME_ROW")); + String authorizationDigest = "sha256:" + "7".repeat(64); + return new FreshTenantCreatorEvidence( + 1, + creation, + creatorUuid, + authorizationOperationId, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, creatorUuid, authorizationOperationId, authorizationDigest)); + } + + private static FreshTenantCreatorEvidence withAuthorizationDigest( + FreshTenantCreatorEvidence original, String authorizationDigest) { + return new FreshTenantCreatorEvidence( + 1, + original.creationEvidence(), + original.initiatingAccountId(), + original.accountAuthorizationOperationId(), + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, + original.creationEvidence(), + original.initiatingAccountId(), + original.accountAuthorizationOperationId(), + authorizationDigest)); + } + + private static String digest(int marker) { + return "sha256:" + Integer.toHexString(marker).repeat(64).substring(0, 64); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent exact-claim proof timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent exact-claim proof was interrupted", interrupted); + } + } + + private static T inTransaction( + TransactionTemplate transaction, java.util.function.Supplier work) { + return transaction.execute(status -> work.get()); + } + + private record RequestInput( + FreshTenantCreatorEvidence evidence, + byte[] creatorPayload, + byte[] sourcePayload, + String sourceDigest, + byte[] requestPayload, + String requestDigest) {} + + private record TestContext( + DataSource dataSource, + DSLContext setupDsl, + AccountTenantCreationBootstrapOperationRepository repository, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncodingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncodingTest.java new file mode 100644 index 0000000000..307ecb6539 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncodingTest.java @@ -0,0 +1,113 @@ +package unit.net.firedevops.firemud.accountservice.creatorparty; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +class CreatorPartyEncodingTest { + @Test + void exactEncodingBindsReferencesVersionsAndOriginalCreation() { + UUID account = UUID.randomUUID(); + UUID partyId = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, account, "verified-evidence", 1L); + FreshTenantCreatorEvidence creator = creator(account); + byte[] original = CreatorPartyEncoding.request(request, creator, party); + assertThat(CreatorPartyEncoding.request(request, creator, party)).isEqualTo(original); + assertThat(CreatorPartyEncoding.digest(original)).matches("sha256:[0-9a-f]{64}"); + assertThat(CreatorPartyEncoding.request(request, creator, party(partyId, account, "other", 1L))) + .isNotEqualTo(original); + assertThat( + CreatorPartyEncoding.request( + request, creator, party(partyId, account, "verified-evidence", 2L))) + .isNotEqualTo(original); + assertThat(CreatorPartyEncoding.request(request, creator(account), party)) + .isNotEqualTo(original); + } + + @Test + void missingPolicyUnsupportedVersionsAndForeignIndividualDoNotBecomeAuthority() { + UUID account = UUID.randomUUID(); + UUID partyId = UUID.randomUUID(); + assertThatThrownBy( + () -> + new IndividualCreatorPartySource( + partyId, + account, + VerificationStatus.VERIFIED, + 1, + null, + null, + "evidence", + 1L, + 1)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> party(partyId, account, "evidence", 0L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> party(new UUID(0, 0), account, "evidence", 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CreatorPartyEncoding.request( + UUID.randomUUID(), + creator(account), + party(partyId, UUID.randomUUID(), "evidence", 1L))) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + new IndividualCreatorPartySource( + partyId, account, VerificationStatus.UNSUPPORTED, 1, null, null, null, null, 1) + .locallyVerified()) + .isFalse(); + } + + private static IndividualCreatorPartySource party( + UUID party, UUID account, String evidence, long version) { + return new IndividualCreatorPartySource( + party, + account, + VerificationStatus.VERIFIED, + 1, + "approved-policy", + 1L, + evidence, + version, + 1); + } + + private static FreshTenantCreatorEvidence creator(UUID account) { + UUID request = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + UUID tenant = UUID.randomUUID(); + String digest = "sha256:" + "1".repeat(64); + FreshTenantCreationEvidence creation = + new FreshTenantCreationEvidence( + 1, + "firemud-test", + request, + operation, + digest, + tenant, + 1, + "game-key", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "firemud-test", request, operation, digest, tenant, 1, "game-key", "NEW_GAME_ROW")); + UUID authorization = UUID.randomUUID(); + return new FreshTenantCreatorEvidence( + 1, + creation, + account, + authorization, + digest, + FreshTenantCreatorDigest.evidenceDigest(1, creation, account, authorization, digest)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java new file mode 100644 index 0000000000..0367e93183 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java @@ -0,0 +1,384 @@ +package unit.net.firedevops.firemud.accountservice.creatorparty; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.InitialAssociationReadback; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mock-backed owner-boundary predicates only; this is not PostgreSQL lock or trigger proof. */ +class IndividualCreatorPartyRepositoryTest { + @AfterEach + void clearTransactionMarkers() { + TransactionSynchronizationManager.clear(); + } + + @Test + void derivesAndVerifiesTheExactFreshInitialAssociationFromTenantOwnerRows() { + Fixture fixture = new Fixture(); + + InitialAssociationReadback readback = fixture.read(); + + assertThat(readback.creatorEvidence()).isEqualTo(fixture.creatorEvidence); + assertThat(readback.receipt()) + .isEqualTo( + new IndividualCreatorPartyRepository.AssociationReceipt( + fixture.associationRequestId, + fixture.tenantId, + fixture.party.creatorPartyId(), + fixture.historyId, + CreatorPartyEncoding.digest(fixture.resultPayload))); + assertThat(readback.partySource()).isEqualTo(fixture.party); + fixture.assertNoWrites(); + } + + @Test + void missingAssociationFailsWithoutCreatingAReceiptOrHistory() { + Fixture fixture = new Fixture(); + fixture.associationByTenant = null; + + fixture.rejects(); + } + + @Test + void incompleteBootstrapAndAssociationIdentitiesFailClosed() { + Fixture uncommittedBootstrap = new Fixture(); + uncommittedBootstrap.bootstrap = uncommittedBootstrap.withStatus("IN_PROGRESS"); + uncommittedBootstrap.whenBootstrapRead(); + uncommittedBootstrap.rejects(); + + Fixture malformedAssociation = new Fixture(); + malformedAssociation.associationByTenantFields.remove("creator_party_id"); + malformedAssociation.rejects(); + } + + @Test + void foreignInitiatorOrPartyCannotBeReadAsTheFreshCreatorAssociation() { + Fixture foreignInitiator = new Fixture(); + foreignInitiator.associationByRequestFields.put("initiating_account_uuid", UUID.randomUUID()); + foreignInitiator.associationByTenantFields.put( + "initiating_account_uuid", + foreignInitiator.associationByRequestFields.get("initiating_account_uuid")); + foreignInitiator.rejects(); + + Fixture foreignParty = new Fixture(); + foreignParty.partyFields.put("account_uuid", UUID.randomUUID()); + foreignParty.rejects(); + } + + @Test + void changedPartyBytesOrReceiptHistoryFailClosed() { + Fixture changedParty = new Fixture(); + changedParty.partyFields.put("source_payload", new byte[] {8, 8}); + changedParty.rejects(); + + Fixture changedReceipt = new Fixture(); + changedReceipt.associationByRequestFields.put("result_digest", "sha256:" + "f".repeat(64)); + changedReceipt.rejects(); + } + + @Test + void retainedOrTombstonedHistoryCannotBeReinterpretedAsInitialAssociation() { + Fixture retained = new Fixture(); + retained.historyFields.put("origin", "RETAINED"); + retained.rejects(); + + Fixture tombstoned = new Fixture(); + tombstoned.historyFields.put("origin", "TOMBSTONE"); + tombstoned.rejects(); + + Fixture multipleHistory = new Fixture(); + multipleHistory.historyCountFields.put("count", 2L); + multipleHistory.rejects(); + } + + private static final class Fixture { + private final DSLContext dsl = mock(DSLContext.class); + private final FreshTenantIdentityAssociationRepository freshTenants = + mock(FreshTenantIdentityAssociationRepository.class); + private final AccountTenantCreationBootstrapOperationRepository bootstraps = + mock(AccountTenantCreationBootstrapOperationRepository.class); + private final UUID accountId = UUID.randomUUID(); + private final UUID tenantId = UUID.randomUUID(); + private final UUID creatorBootstrapRequestId = UUID.randomUUID(); + private final UUID associationRequestId = UUID.randomUUID(); + private final UUID historyId = UUID.randomUUID(); + private final UUID creationRequestId = UUID.randomUUID(); + private final UUID creationOperationId = UUID.randomUUID(); + private final UUID accountAuthorizationOperationId = creatorBootstrapRequestId; + private final String accountAuthorizationDigest = sha256('a'); + private final FreshTenantCreationEvidence creation = creation(); + private final FreshTenantCreatorEvidence creatorEvidence = creatorEvidence(); + private final IndividualCreatorPartySource party = party(); + private final byte[] requestPayload = + CreatorPartyEncoding.request(associationRequestId, creatorEvidence, party); + private final byte[] resultPayload = CreatorPartyEncoding.result(historyId, requestPayload); + private final Map associationByTenantFields = new HashMap<>(); + private final Map associationByRequestFields = new HashMap<>(); + private final Map partyFields = new HashMap<>(); + private final Map historyFields = new HashMap<>(); + private final Map historyCountFields = new HashMap<>(); + private StoredOperation bootstrap; + private StoredOperation currentBootstrap; + private Record associationByTenant; + private final IndividualCreatorPartyRepository repository; + + private Fixture() { + bootstrap = bootstrap("COMMITTED"); + currentBootstrap = bootstrap; + associationByTenantFields.put("request_id", associationRequestId); + associationByTenantFields.put("tenant_uuid", tenantId); + associationByTenantFields.put("initiating_account_uuid", accountId); + associationByTenantFields.put("creator_party_id", party.creatorPartyId()); + associationByTenantFields.put("creation_operation_id", creationOperationId); + + associationByRequestFields.put("request_id", associationRequestId); + associationByRequestFields.put("tenant_uuid", tenantId); + associationByRequestFields.put("initiating_account_uuid", accountId); + associationByRequestFields.put("creator_party_id", party.creatorPartyId()); + associationByRequestFields.put("creation_operation_id", creationOperationId); + associationByRequestFields.put( + "creator_evidence_payload", CreatorPartyEncoding.creation(creatorEvidence)); + associationByRequestFields.put("party_source_payload", CreatorPartyEncoding.party(party)); + associationByRequestFields.put("request_payload", requestPayload); + associationByRequestFields.put("request_digest", CreatorPartyEncoding.digest(requestPayload)); + associationByRequestFields.put("history_id", historyId); + associationByRequestFields.put("result_payload", resultPayload); + associationByRequestFields.put("result_digest", CreatorPartyEncoding.digest(resultPayload)); + associationByRequestFields.put( + "committed_at", OffsetDateTime.ofInstant(Instant.EPOCH, ZoneOffset.UTC)); + + partyFields.put("creator_party_id", party.creatorPartyId()); + partyFields.put("account_uuid", accountId); + partyFields.put("verification_status", VerificationStatus.VERIFIED.name()); + partyFields.put("identity_version", party.identityVersion()); + partyFields.put("policy_reference", party.policyReference()); + partyFields.put("policy_version", party.policyVersion()); + partyFields.put("verification_evidence_reference", party.verificationEvidenceReference()); + partyFields.put("verification_evidence_version", party.verificationEvidenceVersion()); + partyFields.put("source_version", party.sourceVersion()); + partyFields.put("source_payload", CreatorPartyEncoding.party(party)); + partyFields.put( + "source_digest", CreatorPartyEncoding.digest(CreatorPartyEncoding.party(party))); + + historyFields.put("history_id", historyId); + historyFields.put("origin", "FRESH_INITIAL"); + historyFields.put("tenant_uuid", tenantId); + historyFields.put("creator_party_id", party.creatorPartyId()); + historyFields.put("source_version", 1L); + historyFields.put("evidence_payload", resultPayload); + historyFields.put("evidence_digest", CreatorPartyEncoding.digest(resultPayload)); + historyCountFields.put("count", 1L); + + associationByTenant = row(associationByTenantFields); + when(freshTenants.read(tenantId)).thenReturn(Optional.of(creation)); + when(bootstraps.findRequestIdByTenantForUpdate(tenantId)) + .thenReturn(Optional.of(creatorBootstrapRequestId)); + when(bootstraps.findForUpdate(creatorBootstrapRequestId)) + .thenAnswer(ignored -> Optional.of(currentBootstrap)); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenAnswer(this::fetch); + when(dsl.fetchOne(anyString())).thenAnswer(this::fetch); + repository = new IndividualCreatorPartyRepository(dsl, freshTenants, bootstraps); + } + + private InitialAssociationReadback read() { + beginWritableTransaction(); + try { + return repository.readExistingInitialAssociation(tenantId); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private void rejects() { + beginWritableTransaction(); + try { + assertThatThrownBy(() -> repository.readExistingInitialAssociation(tenantId)) + .isInstanceOf(IllegalStateException.class); + assertNoWrites(); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private void assertNoWrites() { + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + private void whenBootstrapRead() { + currentBootstrap = bootstrap; + when(bootstraps.findForUpdate(creatorBootstrapRequestId)) + .thenAnswer(ignored -> Optional.of(currentBootstrap)); + } + + private StoredOperation withStatus(String status) { + return bootstrap(status); + } + + private Object fetch(org.mockito.invocation.InvocationOnMock invocation) { + String sql = invocation.getArgument(0); + if (sql.equals("SHOW transaction_isolation")) { + Record isolation = mock(Record.class); + when(isolation.get(0, String.class)).thenReturn("read committed"); + return isolation; + } + if (sql.contains("account_canonical_tenant_identity_claims")) { + return row(Map.of("identity_kind", "FRESH_GAME_DESIGN")); + } + if (sql.contains("WHERE tenant_uuid = ? FOR UPDATE")) { + return associationByTenant; + } + if (sql.contains("account_individual_creator_party_sources")) { + return row(partyFields); + } + if (sql.contains("WHERE request_id = ?")) { + return row(associationByRequestFields); + } + if (sql.contains("SELECT count(*) AS count FROM account_tenant_creator_party_history")) { + return row(historyCountFields); + } + if (sql.contains("account_tenant_creator_party_history WHERE history_id = ?")) { + return row(historyFields); + } + throw new AssertionError("Unexpected repository SQL: " + sql); + } + + private FreshTenantCreationEvidence creation() { + String requestDigest = sha256('c'); + return new FreshTenantCreationEvidence( + 1, + "firemud-test", + creationRequestId, + creationOperationId, + requestDigest, + tenantId, + 1, + "test-game", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "firemud-test", + creationRequestId, + creationOperationId, + requestDigest, + tenantId, + 1, + "test-game", + "NEW_GAME_ROW")); + } + + private FreshTenantCreatorEvidence creatorEvidence() { + return new FreshTenantCreatorEvidence( + 1, + creation, + accountId, + accountAuthorizationOperationId, + accountAuthorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, accountId, accountAuthorizationOperationId, accountAuthorizationDigest)); + } + + private IndividualCreatorPartySource party() { + return new IndividualCreatorPartySource( + UUID.randomUUID(), + accountId, + VerificationStatus.VERIFIED, + 1, + "test-policy", + 1L, + "test-individual-verification", + 1L, + 1); + } + + private StoredOperation bootstrap(String status) { + return new StoredOperation( + creatorBootstrapRequestId, + accountId, + tenantId, + creationRequestId, + creationOperationId, + accountAuthorizationOperationId, + accountAuthorizationDigest, + creatorEvidence.evidenceDigest(), + CreatorPartyEncoding.creation(creatorEvidence), + new byte[] {1}, + sha256('s'), + new byte[] {2}, + sha256('r'), + 1L, + 1L, + 0L, + status, + 1L, + 2L, + 1L, + "ACTIVE", + false, + "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8), + "account:auth-authority:v1:membership/" + accountId + "/" + tenantId, + UUID.randomUUID().toString(), + 1L, + "test-event", + sha256('e'), + false, + new byte[] {3}, + UUID.randomUUID(), + "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED", + Instant.EPOCH, + sha256('a'), + new byte[] {4}, + new byte[] {5}, + sha256('b'), + Instant.EPOCH); + } + } + + private static Record row(Map fields) { + Record record = mock(Record.class); + when(record.get(anyString())).thenAnswer(invocation -> fields.get(invocation.getArgument(0))); + doAnswer(invocation -> fields.get(invocation.getArgument(0))) + .when(record) + .get(anyString(), ArgumentMatchers.>any()); + return record; + } + + private static void beginWritableTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + private static String sha256(char repeated) { + return "sha256:" + String.valueOf(repeated).repeat(64); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java new file mode 100644 index 0000000000..44f8772a00 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java @@ -0,0 +1,567 @@ +package unit.net.firedevops.firemud.accountservice.hostedterms; + +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.when; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.hostedterms.IndividualHostedTermsAcceptance; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; + +/** + * Unit proof uses explicit typed upstream authority fixtures, not caller-supplied authority DTOs. + */ +class AccountHostedTermsServiceTest { + private static final Instant NOW = Instant.parse("2026-10-08T00:00:00Z"); + + @Test + void affirmativeAcceptancePersistsExactShownCatalogAndReturnsOriginalReceipt() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion terms = + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(60)); + AccountHostedTermsService.AcceptanceAction action = action(fixture, terms, true); + IndividualHostedTermsAcceptance expected = acceptance(action, party, terms); + fixture.acceptanceAuthority(action); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, terms, NOW, null)); + when(fixture.repository.readCatalog(fixture.scopeId, terms.versionId())).thenReturn(terms); + when(fixture.repository.readAcceptanceByRequest(action.actionRequestId())) + .thenReturn(Optional.empty()); + when(fixture.repository.insertAcceptance( + any(UUID.class), any(), any(), any(), any(byte[].class))) + .thenReturn(expected); + + assertThat(fixture.service.accept(action.actionRequestId())).isEqualTo(expected); + verify(fixture.repository) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void nonaffirmativeOrUnverifiedForeignPartyCannotWriteAcceptance() { + Fixture fixture = new Fixture(); + HostedTermsCatalogVersion terms = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + AccountHostedTermsService.AcceptanceAction no = action(fixture, terms, false); + fixture.acceptanceAuthority(no); + assertThatThrownBy(() -> fixture.service.accept(no.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Affirmative"); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + + AccountHostedTermsService.AcceptanceAction foreign = action(fixture, terms, true); + fixture.acceptanceAuthority(foreign); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party(fixture.partyId, UUID.randomUUID())); + assertThatThrownBy(() -> fixture.service.accept(foreign.actionRequestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("own locally verified"); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void changedShownDigestOperatorOrVersionIsDenied() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion stored = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + HostedTermsCatalogVersion other = terms(fixture.scopeId, null, 1, 1, "other-terms", NOW); + AccountHostedTermsService.AcceptanceAction action = action(fixture, stored, true); + fixture.acceptanceAuthority(action); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, stored, NOW, null)); + when(fixture.repository.readCatalog(fixture.scopeId, stored.versionId())).thenReturn(other); + + assertThatThrownBy(() -> fixture.service.accept(action.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void changedOperatorIdentityOrVersionCannotBeAcceptedAsTheShownTerms() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion terms = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + AccountHostedTermsService.AcceptanceAction base = action(fixture, terms, true); + AccountHostedTermsService.AcceptanceAction changedName = + new AccountHostedTermsService.AcceptanceAction( + base.actionRequestId(), + true, + base.accountId(), + base.creatorPartyId(), + base.hostedScopeId(), + base.shownVersionId(), + base.shownDocumentDigest(), + "Different Operator", + base.shownOperatorIdentityVersion(), + base.authenticatedActionReference(), + base.authenticatedActionVersion(), + base.actionCreatedAt()); + fixture.acceptanceAuthority(changedName); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, terms, NOW, null)); + when(fixture.repository.readCatalog(fixture.scopeId, terms.versionId())).thenReturn(terms); + when(fixture.repository.readAcceptanceByRequest(base.actionRequestId())) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> fixture.service.accept(base.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + + AccountHostedTermsService.AcceptanceAction changedVersion = + new AccountHostedTermsService.AcceptanceAction( + UUID.randomUUID(), + true, + base.accountId(), + base.creatorPartyId(), + base.hostedScopeId(), + base.shownVersionId(), + base.shownDocumentDigest(), + base.shownOperatorLegalIdentity(), + 2, + base.authenticatedActionReference(), + base.authenticatedActionVersion(), + base.actionCreatedAt()); + fixture.acceptanceAuthority(changedVersion); + when(fixture.repository.readAcceptanceByRequest(changedVersion.actionRequestId())) + .thenReturn(Optional.empty()); + assertThatThrownBy(() -> fixture.service.accept(changedVersion.actionRequestId())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("shown catalog"); + } + + @Test + void exactRetryRecoversOriginalEvidenceWithoutRewritingOrReplacingIt() { + Fixture fixture = new Fixture(); + HostedTermsCatalogVersion terms = terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW); + AccountHostedTermsService.AcceptanceAction action = action(fixture, terms, true); + IndividualHostedTermsAcceptance receipt = + acceptance(action, party(fixture.partyId, fixture.accountId), terms); + fixture.acceptanceAuthority(action); + when(fixture.repository.readAcceptanceByRequest(action.actionRequestId())) + .thenReturn(Optional.of(receipt)); + + assertThat(fixture.service.accept(action.actionRequestId())).isEqualTo(receipt); + verify(fixture.parties, never()).readIndividualSource(any(), any()); + verify(fixture.repository, never()) + .insertAcceptance(any(UUID.class), any(), any(), any(), any(byte[].class)); + } + + @Test + void materialityAdvancesOnlyItsIndependentGenerationAndNonmaterialityPreservesIt() { + Fixture material = new Fixture(); + HostedTermsCatalogVersion oldMaterial = + terms(material.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(1)); + HostedTermsRepository.PublicationOperation materialOperation = + operation( + material.requestId, + material.scopeId, + "intent", + HostedTermsRepository.PublicationStatus.RECEIVED); + when(material.repository.claimPublication(any(), any(), any())).thenReturn(materialOperation); + when(material.repository.lockScope(material.scopeId)) + .thenReturn(scope(material.scopeId, oldMaterial, NOW, null)); + when(material.fences.requestSourceChange(any())).thenReturn(true); + when(material.fences.sourceMutationPermitted(any())).thenReturn(true); + material.publicationAuthority( + publication( + material.scopeId, + "terms-v2", + HostedTermsCatalogVersion.Materiality.MATERIAL, + NOW.minusSeconds(1))); + AccountHostedTermsService.PublicationResult materialResult = + material.service.publish(material.requestId); + assertThat(materialResult.status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.COMMITTED); + assertThat(materialResult.candidate().sourceVersion()).isEqualTo(2); + assertThat(materialResult.candidate().materialGeneration()).isEqualTo(2); + + Fixture nonmaterial = new Fixture(); + HostedTermsCatalogVersion oldNonmaterial = + terms(nonmaterial.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(1)); + HostedTermsRepository.PublicationOperation nonmaterialOperation = + operation( + nonmaterial.requestId, + nonmaterial.scopeId, + "intent", + HostedTermsRepository.PublicationStatus.RECEIVED); + when(nonmaterial.repository.claimPublication(any(), any(), any())) + .thenReturn(nonmaterialOperation); + when(nonmaterial.repository.lockScope(nonmaterial.scopeId)) + .thenReturn(scope(nonmaterial.scopeId, oldNonmaterial, NOW, null)); + when(nonmaterial.fences.requestSourceChange(any())).thenReturn(true); + when(nonmaterial.fences.sourceMutationPermitted(any())).thenReturn(true); + nonmaterial.publicationAuthority( + publication( + nonmaterial.scopeId, + "terms-v2", + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + NOW.minusSeconds(1))); + AccountHostedTermsService.PublicationResult nonmaterialResult = + nonmaterial.service.publish(nonmaterial.requestId); + assertThat(nonmaterialResult.candidate().sourceVersion()).isEqualTo(2); + assertThat(nonmaterialResult.candidate().materialGeneration()).isEqualTo(1); + } + + @Test + void unresolvedOwnerSettlementKeepsPublicationPendingWithoutAdvancingCatalogHead() { + Fixture fixture = new Fixture(); + HostedTermsCatalogVersion current = + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(1)); + when(fixture.repository.claimPublication(any(), any(), any())) + .thenReturn( + operation( + fixture.requestId, + fixture.scopeId, + "intent", + HostedTermsRepository.PublicationStatus.RECEIVED)); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, current, NOW, null)); + when(fixture.fences.requestSourceChange(any())).thenReturn(false); + fixture.publicationAuthority( + publication( + fixture.scopeId, + "terms-v2", + HostedTermsCatalogVersion.Materiality.MATERIAL, + NOW.minusSeconds(1))); + + AccountHostedTermsService.PublicationResult result = fixture.service.publish(fixture.requestId); + assertThat(result.status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT); + verify(fixture.repository).markOwnerSettlementPending(any(), any(), any(byte[].class)); + verify(fixture.repository, never()).completePublication(any(), any(), any(), any()); + } + + @Test + void dueDisclosedDeadlineDeniesOldCurrentnessWhileSourceSettlementIsPending() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion current = + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(10)); + HostedTermsCatalogVersion next = + terms(fixture.scopeId, current.versionId(), 2, 2, "terms-v2", NOW.minusSeconds(1)); + HostedTermsRepository.PublicationOperation pending = + new HostedTermsRepository.PublicationOperation( + fixture.requestId, + fixture.scopeId, + new byte[] {1}, + HostedTermsEncoding.digest(new byte[] {1}), + HostedTermsRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT, + next.versionId(), + new byte[] {2}, + null, + null, + null); + when(fixture.repository.lockPartyAccount(fixture.partyId)).thenReturn(fixture.accountId); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, current, NOW, pending)); + when(fixture.repository.readCandidate(pending)).thenReturn(next); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("effective date has arrived"); + } + + @Test + void staleGenerationAndChangedOrUnavailableIdentityNeverReturnCurrentness() { + Fixture fixture = new Fixture(); + IndividualCreatorPartySource acceptedParty = party(fixture.partyId, fixture.accountId); + IndividualCreatorPartySource changedParty = + new IndividualCreatorPartySource( + fixture.partyId, + fixture.accountId, + VerificationStatus.VERIFIED, + 2, + "test-policy-v2", + 2L, + "test-verification-v2", + 2L, + 1); + HostedTermsCatalogVersion current = + terms(fixture.scopeId, UUID.randomUUID(), 2, 2, "terms-v2", NOW); + IndividualHostedTermsAcceptance stale = + acceptance( + action(fixture, terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW), true), + acceptedParty, + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW)); + IndividualHostedTermsAcceptance currentAcceptance = + acceptance(action(fixture, current, true), acceptedParty, current); + when(fixture.repository.lockPartyAccount(fixture.partyId)).thenReturn(fixture.accountId); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(acceptedParty, acceptedParty, changedParty) + .thenThrow(new IllegalStateException("source unavailable")); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, current, NOW, null)); + when(fixture.repository.readCurrentAcceptance(fixture.partyId, fixture.scopeId, current)) + .thenReturn(Optional.empty(), Optional.of(stale), Optional.of(currentAcceptance)); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No current affirmative"); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or changed"); + + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or changed"); + assertThatThrownBy(() -> fixture.service.requireCurrentness(fixture.scopeId, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source unavailable"); + } + + @Test + void catalogAndAcceptanceEncodingsBindExactBytesWithoutCallerTimeAuthority() { + Fixture fixture = new Fixture(); + byte[] document = new byte[] {0, 1, (byte) 0xff, 13, 10}; + HostedTermsCatalogVersion version = terms(fixture.scopeId, null, 1, 1, document, NOW); + byte[] original = version.documentBytes(); + original[0] = 9; + assertThat(version.documentBytes()).containsExactly(document); + assertThat(version.documentDigest()).isEqualTo(HostedTermsEncoding.digest(document)); + assertThat(HostedTermsEncoding.catalog(version)) + .isEqualTo(HostedTermsEncoding.catalog(version)); + assertThatThrownBy( + () -> + new HostedTermsCatalogVersion( + UUID.randomUUID(), + fixture.scopeId, + null, + "Test Operator", + 1, + document, + HostedTermsEncoding.digest("different".getBytes()), + 1, + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-publication", + 1, + "test-notice", + 1, + NOW)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Document digest"); + } + + private static HostedTermsRepository.ScopeSnapshot scope( + UUID id, + HostedTermsCatalogVersion current, + Instant now, + HostedTermsRepository.PublicationOperation pending) { + return new HostedTermsRepository.ScopeSnapshot( + id, current, OffsetDateTime.ofInstant(now, ZoneOffset.UTC), pending); + } + + private static HostedTermsRepository.PublicationOperation operation( + UUID requestId, + UUID scopeId, + String request, + HostedTermsRepository.PublicationStatus status) { + byte[] payload = request.getBytes(); + return new HostedTermsRepository.PublicationOperation( + requestId, + scopeId, + payload, + HostedTermsEncoding.digest(payload), + status, + null, + null, + null, + null, + null); + } + + private static HostedTermsCatalogVersion terms( + UUID scope, + UUID predecessor, + long source, + long generation, + String document, + Instant effectiveAt) { + return terms(scope, predecessor, source, generation, document.getBytes(), effectiveAt); + } + + private static HostedTermsCatalogVersion terms( + UUID scope, + UUID predecessor, + long source, + long generation, + byte[] document, + Instant effectiveAt) { + return new HostedTermsCatalogVersion( + UUID.randomUUID(), + scope, + predecessor, + "Test Operator", + 1, + document, + HostedTermsEncoding.digest(document), + source, + generation, + predecessor == null + ? HostedTermsCatalogVersion.Materiality.INITIAL + : generation == 2 + ? HostedTermsCatalogVersion.Materiality.MATERIAL + : HostedTermsCatalogVersion.Materiality.NONMATERIAL, + predecessor == null ? null : "test-materiality", + predecessor == null ? null : 1L, + "test-publication", + 1, + "test-notice", + 1, + effectiveAt); + } + + private static IndividualCreatorPartySource party(UUID partyId, UUID accountId) { + return new IndividualCreatorPartySource( + partyId, + accountId, + VerificationStatus.VERIFIED, + 1, + "test-policy", + 1L, + "test-verification", + 1L, + 1); + } + + private static AccountHostedTermsService.AcceptanceAction action( + Fixture fixture, HostedTermsCatalogVersion terms, boolean affirmative) { + return new AccountHostedTermsService.AcceptanceAction( + UUID.randomUUID(), + affirmative, + fixture.accountId, + fixture.partyId, + fixture.scopeId, + terms.versionId(), + terms.documentDigest(), + terms.operatorLegalIdentity(), + terms.operatorIdentityVersion(), + "test-authenticated-action", + 1, + OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC)); + } + + private static AccountHostedTermsService.PublicationEvidence publication( + UUID scope, + String document, + HostedTermsCatalogVersion.Materiality materiality, + Instant effectiveAt) { + return new AccountHostedTermsService.PublicationEvidence( + scope, + "Test Operator", + 1, + document.getBytes(), + materiality, + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : "test-materiality", + materiality == HostedTermsCatalogVersion.Materiality.INITIAL ? null : 1L, + "test-publication", + 1, + "test-notice", + 1, + effectiveAt); + } + + private static IndividualHostedTermsAcceptance acceptance( + AccountHostedTermsService.AcceptanceAction action, + IndividualCreatorPartySource party, + HostedTermsCatalogVersion terms) { + byte[] source = HostedTermsEncoding.individualParty(party); + byte[] actionBytes = HostedTermsEncoding.affirmativeAction(action); + return new IndividualHostedTermsAcceptance( + UUID.randomUUID(), + action.actionRequestId(), + party.creatorPartyId(), + party.accountId(), + terms.hostedScopeId(), + terms.versionId(), + terms.documentDigest(), + terms.operatorLegalIdentity(), + terms.operatorIdentityVersion(), + terms.sourceVersion(), + terms.materialGeneration(), + source, + HostedTermsEncoding.digest(source), + actionBytes, + HostedTermsEncoding.digest(actionBytes), + OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC)); + } + + private static final class Fixture { + private final UUID requestId = UUID.randomUUID(); + private final UUID scopeId = UUID.randomUUID(); + private final UUID accountId = UUID.randomUUID(); + private final UUID partyId = UUID.randomUUID(); + private final HostedTermsRepository repository = mock(HostedTermsRepository.class); + private final IndividualCreatorPartyRepository parties = + mock(IndividualCreatorPartyRepository.class); + private final DraftAuthorizationFenceRepository fences = + mock(DraftAuthorizationFenceRepository.class); + private final AccountHostedTermsService.OperatorPublicationAuthority publicationAuthority = + mock(AccountHostedTermsService.OperatorPublicationAuthority.class); + private final AccountHostedTermsService.IndividualAcceptanceAuthority acceptanceAuthority = + mock(AccountHostedTermsService.IndividualAcceptanceAuthority.class); + private final AccountHostedTermsService service = + new AccountHostedTermsService( + new NoopTransactionManager(), + repository, + parties, + fences, + publicationAuthority, + acceptanceAuthority); + + private void acceptanceAuthority(AccountHostedTermsService.AcceptanceAction action) { + when(acceptanceAuthority.resolve(action.actionRequestId())).thenReturn(action); + } + + private void publicationAuthority(AccountHostedTermsService.PublicationEvidence evidence) { + when(publicationAuthority.resolve(requestId)).thenReturn(evidence); + } + } + + private static final class NoopTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingTest.java new file mode 100644 index 0000000000..4080386540 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingTest.java @@ -0,0 +1,307 @@ +package unit.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding.PublicationEvidence; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingEncoding; +import net.firedevops.firemud.accountservice.hostedterms.IndividualHostedTermsAcceptance; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.junit.jupiter.api.Test; + +class HostedTermsEnvironmentBindingTest { + @Test + void canonicalPublicationBindsBoundaryScopeOperatorCatalogPublisherEventAndPredecessor() { + UUID requestId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + UUID catalogVersionId = UUID.randomUUID(); + UUID priorBinding = UUID.randomUUID(); + PublicationEvidence evidence = + new PublicationEvidence( + "official/production-cluster-a", + scopeId, + "Test Operator Legal Name", + 4, + catalogVersionId, + 9, + "environment-secrets-owner@production", + "deployment-ref:event-37:traffic-open-12", + priorBinding, + 2L); + + byte[] original = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence); + assertThat(HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence)) + .containsExactly(original); + assertThat(HostedTermsEnvironmentBindingEncoding.publicationDigest(requestId, evidence)) + .isEqualTo(HostedTermsEncoding.digest(original)); + + PublicationEvidence changed = + new PublicationEvidence( + evidence.environmentBoundary(), + evidence.hostedScopeId(), + evidence.operatorLegalIdentity(), + evidence.operatorIdentityVersion(), + evidence.catalogVersionId(), + evidence.catalogSourceVersion(), + evidence.authenticatedPublisherIdentity(), + evidence.publicationEventIdentity(), + UUID.randomUUID(), + evidence.predecessorSourceVersion()); + assertThat(HostedTermsEnvironmentBindingEncoding.publication(requestId, changed)) + .isNotEqualTo(original); + assertThat(HostedTermsEnvironmentBindingEncoding.publication(UUID.randomUUID(), evidence)) + .isNotEqualTo(original); + } + + @Test + void independentBindingCounterAndExactReceiptUseNamespacedHostedTermsSourceKey() { + UUID requestId = UUID.randomUUID(); + PublicationEvidence evidence = + new PublicationEvidence( + "production", + UUID.randomUUID(), + "Test Operator", + 1, + UUID.randomUUID(), + 7, + "test-only-environment-owner", + "test-only-publication-event-17", + UUID.randomUUID(), + 8L); + byte[] publication = HostedTermsEnvironmentBindingEncoding.publication(requestId, evidence); + HostedTermsEnvironmentBinding binding = + new HostedTermsEnvironmentBinding( + UUID.randomUUID(), + requestId, + evidence.environmentBoundary(), + evidence.hostedScopeId(), + evidence.operatorLegalIdentity(), + evidence.operatorIdentityVersion(), + evidence.catalogVersionId(), + evidence.catalogSourceVersion(), + evidence.authenticatedPublisherIdentity(), + evidence.publicationEventIdentity(), + HostedTermsEncoding.digest(publication), + evidence.predecessorBindingId(), + evidence.predecessorSourceVersion(), + 9); + + var source = binding.sourceEvidence(); + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.scopeId()).isEqualTo("environment-boundary/production"); + assertThat(source.key()).isEqualTo("HOSTED_TERMS:environment-boundary/production"); + assertThat(source.scopeId()).isNotEqualTo(binding.hostedScopeId().toString()); + assertThat(source.generation()).isNull(); + assertThat(source.sourceVersion()).isEqualTo("9"); + assertThat(source.evidence()) + .containsExactly(HostedTermsEnvironmentBindingEncoding.receipt(binding)); + assertThat(HostedTermsEnvironmentBindingEncoding.receiptDigest(binding)) + .isEqualTo(HostedTermsEncoding.digest(source.evidence())); + assertThat(binding.catalogSourceVersion()).isEqualTo(7); + assertThat(binding.sourceVersion()).isEqualTo(9); + } + + @Test + void initialBindingCannotInventPredecessorAndUpdatesAdvanceExactlyOnce() { + UUID requestId = UUID.randomUUID(); + UUID priorBinding = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + UUID catalogId = UUID.randomUUID(); + assertThatThrownBy( + () -> + new PublicationEvidence( + "production", + scopeId, + "Test Operator", + 1, + catalogId, + 1, + "test-owner", + "event-1", + null, + 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("present together"); + + assertThatThrownBy( + () -> + new HostedTermsEnvironmentBinding( + UUID.randomUUID(), + requestId, + "production", + scopeId, + "Test Operator", + 1, + catalogId, + 1, + "test-owner", + "event-2", + HostedTermsEncoding.digest(new byte[] {1}), + priorBinding, + 4L, + 7)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact predecessor"); + } + + @Test + void currentEnvironmentEvidenceRequiresExactOwnerDigest() { + byte[] evidence = new byte[] {1, 2, 3}; + var current = + new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + "staging", + "test-only-environment-owner", + "test-only-current-boundary-read-1", + evidence, + HostedTermsEncoding.digest(evidence)); + byte[] returned = current.exactOwnerEvidence(); + returned[0] = 9; + assertThat(current.exactOwnerEvidence()).containsExactly(evidence); + + assertThatThrownBy( + () -> + new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + "staging", + "test-only-environment-owner", + "test-only-current-boundary-read-2", + evidence, + HostedTermsEncoding.digest(new byte[] {8}))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest conflicts"); + } + + @Test + void currentnessSourceRetainsExactScheduledCatalogAndDisclosedDeadline() { + Instant currentAt = Instant.parse("2026-10-08T00:00:00Z"); + byte[] currentDocument = "current terms".getBytes(StandardCharsets.UTF_8); + HostedTermsCatalogVersion current = + new HostedTermsCatalogVersion( + UUID.randomUUID(), + UUID.randomUUID(), + null, + "Test Operator", + 1, + currentDocument, + HostedTermsEncoding.digest(currentDocument), + 1, + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "current-publication", + 1, + "current-notice", + 1, + currentAt); + byte[] partySource = new byte[] {11, 12}; + byte[] affirmativeAction = new byte[] {21, 22}; + IndividualHostedTermsAcceptance acceptance = + new IndividualHostedTermsAcceptance( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + current.hostedScopeId(), + current.versionId(), + current.documentDigest(), + current.operatorLegalIdentity(), + current.operatorIdentityVersion(), + current.sourceVersion(), + current.materialGeneration(), + partySource, + HostedTermsEncoding.digest(partySource), + affirmativeAction, + HostedTermsEncoding.digest(affirmativeAction), + OffsetDateTime.ofInstant(currentAt, ZoneOffset.UTC)); + + Instant disclosedAt = Instant.parse("2026-10-09T00:00:00Z"); + byte[] nextDocument = "scheduled terms".getBytes(StandardCharsets.UTF_8); + HostedTermsCatalogVersion deadline = + new HostedTermsCatalogVersion( + UUID.randomUUID(), + current.hostedScopeId(), + current.versionId(), + current.operatorLegalIdentity(), + current.operatorIdentityVersion(), + nextDocument, + HostedTermsEncoding.digest(nextDocument), + 2, + 1, + HostedTermsCatalogVersion.Materiality.NONMATERIAL, + "audited-nonmaterial-classification", + 1L, + "scheduled-publication", + 2, + "scheduled-notice", + 2, + disclosedAt); + + byte[] exactDeadline = HostedTermsEncoding.catalog(deadline); + byte[] source = HostedTermsEncoding.currentnessSource(current, acceptance, deadline); + String sourceJson = new String(source, StandardCharsets.UTF_8); + assertThat(sourceJson).contains("account-hosted-terms-currentness-source/v2"); + assertThat(sourceJson) + .contains(Base64.getEncoder().encodeToString(exactDeadline)) + .contains(HostedTermsEncoding.digest(exactDeadline)); + assertThat( + new String( + HostedTermsEncoding.currentnessSource(current, acceptance), StandardCharsets.UTF_8)) + .contains("\"disclosedDeadlineCatalog\":null") + .contains("\"disclosedDeadlineCatalogDigest\":null"); + + HostedTermsCatalogVersion changedDeadline = + new HostedTermsCatalogVersion( + deadline.versionId(), + deadline.hostedScopeId(), + deadline.predecessorVersionId(), + deadline.operatorLegalIdentity(), + deadline.operatorIdentityVersion(), + deadline.documentBytes(), + deadline.documentDigest(), + deadline.sourceVersion(), + deadline.materialGeneration(), + deadline.materiality(), + deadline.materialityEvidenceReference(), + deadline.materialityEvidenceVersion(), + deadline.publicationEvidenceReference(), + deadline.publicationEvidenceVersion(), + deadline.noticeEvidenceReference(), + deadline.noticeEvidenceVersion(), + disclosedAt.plusSeconds(1)); + assertThat(HostedTermsEncoding.currentnessSource(current, acceptance, changedDeadline)) + .isNotEqualTo(source); + + HostedTermsCatalogVersion changedOperator = + new HostedTermsCatalogVersion( + deadline.versionId(), + deadline.hostedScopeId(), + deadline.predecessorVersionId(), + "Different Operator", + deadline.operatorIdentityVersion(), + deadline.documentBytes(), + deadline.documentDigest(), + deadline.sourceVersion(), + deadline.materialGeneration(), + deadline.materiality(), + deadline.materialityEvidenceReference(), + deadline.materialityEvidenceVersion(), + deadline.publicationEvidenceReference(), + deadline.publicationEvidenceVersion(), + deadline.noticeEvidenceReference(), + deadline.noticeEvidenceVersion(), + deadline.effectiveAt()); + assertThatThrownBy( + () -> HostedTermsEncoding.currentnessSource(current, acceptance, changedOperator)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact immutable next catalog"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java index 8cd7a8c4d1..97ed6c08ac 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java @@ -59,7 +59,7 @@ void authenticatedConfirmationDelegatesOnlyToPhysicalReceiptExecutor() throws Ex } @Test - void dependencyUnavailableDescriptionAndTrailersAreReplacedWithBoundedOwnerFailure() { + void dependencyFailureRetainsLocalCauseWithBoundedOwnerStatusAndNoTrailers() { var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); UUID decision = UUID.randomUUID(); Metadata trailers = new Metadata(); @@ -73,12 +73,13 @@ void dependencyUnavailableDescriptionAndTrailersAreReplacedWithBoundedOwnerFailu when(executor.confirm(evidence, decision)).thenThrow(dependencyFailure); assertUnavailableIsRedacted( - () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + () -> peer().call(() -> owner.confirm(request(evidence, decision))), dependencyFailure); TransactionSynchronizationManager.clear(); org.mockito.Mockito.reset(executor); when(executor.read(evidence, decision)).thenThrow(dependencyFailure); - assertUnavailableIsRedacted(() -> peer().call(() -> owner.read(request(evidence, decision)))); + assertUnavailableIsRedacted( + () -> peer().call(() -> owner.read(request(evidence, decision))), dependencyFailure); } @Test @@ -222,7 +223,7 @@ private static void assertStatus( } private static void assertUnavailableIsRedacted( - org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, Throwable expectedCause) { assertThatThrownBy(action) .isInstanceOf(StatusRuntimeException.class) .satisfies( @@ -233,7 +234,7 @@ private static void assertUnavailableIsRedacted( assertThat(Status.fromThrowable(failure).getDescription()) .isEqualTo("Durable Account admission commit confirmation unavailable"); assertThat(statusFailure.getTrailers()).isNull(); - assertThat(statusFailure.getCause()).isNull(); + assertThat(statusFailure.getCause()).isSameAs(expectedCause); }); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java index b3d246fc37..41e2acf62b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java @@ -1,5 +1,6 @@ package unit.net.firedevops.firemud.accountservice.repository; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doReturn; @@ -9,6 +10,7 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.util.UUID; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.jooq.Tables; @@ -17,8 +19,68 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountRepositoryTest { + @Test + void uuidLockRejectsNullAndNilIdentityBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountRepository repository = new AccountRepository(dsl, sourceEvidence); + + assertThatThrownBy(() -> repository.findByAccountUuidForUpdate(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-nil Account UUID is required"); + assertThatThrownBy(() -> repository.findByAccountUuidForUpdate(new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-nil Account UUID is required"); + + verifyNoInteractions(dsl, sourceEvidence); + } + + @Test + void uuidLockRequiresWritableOwnerTransactionBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountRepository repository = new AccountRepository(dsl, sourceEvidence); + UUID accountUuid = UUID.randomUUID(); + boolean priorActive = TransactionSynchronizationManager.isActualTransactionActive(); + boolean priorReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + try { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + assertThatThrownBy(() -> repository.findByAccountUuidForUpdate(accountUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account UUID lock requires an active writable owner transaction"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.findByAccountUuidForUpdate(accountUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account UUID lock requires an active writable owner transaction"); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(priorReadOnly); + TransactionSynchronizationManager.setActualTransactionActive(priorActive); + } + + verifyNoInteractions(dsl, sourceEvidence); + } + + @Test + void uuidLockRequiresMandatoryOwnerTransactionPropagation() throws NoSuchMethodException { + Transactional transactional = + AccountRepository.class + .getMethod("findByAccountUuidForUpdate", UUID.class) + .getAnnotation(Transactional.class); + + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + } + @Test void hardDeletionFailsClosedWithoutSqlOrSourceEvidenceMutation() { DSLContext dsl = mock(DSLContext.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigestTest.java new file mode 100644 index 0000000000..d635015524 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigestTest.java @@ -0,0 +1,187 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.NeverJoinedMembershipSnapshot; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.Test; + +/** Digest proof covers original creator qualification plus the complete fenced Account snapshot. */ +class AccountTenantCreationBootstrapDigestTest { + @Test + void resultPayloadCarriesCompleteTenantBoundMembershipVersionMap() { + UUID tenantUuid = UUID.randomUUID(); + + byte[] result = resultPayload(tenantUuid, Map.of(tenantUuid.toString(), "2")); + + assertThat(resultJson(result)).contains("\"membershipVersion\":{\"" + tenantUuid + "\":\"2\"}"); + } + + @Test + void resultPayloadRejectsMissingExtraAndWrongTenantMembershipVersionEntries() { + UUID tenantUuid = UUID.randomUUID(); + UUID otherTenantUuid = UUID.randomUUID(); + + assertThatThrownBy(() -> resultPayload(tenantUuid, Map.of())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + resultPayload( + tenantUuid, + Map.of(tenantUuid.toString(), "2", otherTenantUuid.toString(), "3"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> resultPayload(tenantUuid, Map.of(otherTenantUuid.toString(), "2"))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requestIdentityChangesWithAccountSnapshotAndRetainsCompleteAuthorityMaps() { + UUID accountUuid = UUID.randomUUID(); + UUID tenantUuid = UUID.randomUUID(); + FreshTenantCreatorEvidence evidence = evidence(accountUuid, tenantUuid); + NeverJoinedMembershipSnapshot first = snapshot(accountUuid, tenantUuid, "3"); + NeverJoinedMembershipSnapshot laterFence = snapshot(accountUuid, tenantUuid, "4"); + + byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); + byte[] firstSource = AccountTenantCreationBootstrapDigest.sourceSnapshotPayload(first); + byte[] laterSource = AccountTenantCreationBootstrapDigest.sourceSnapshotPayload(laterFence); + Map tuple = + AccountTenantCreationBootstrapDigest.authorityTupleMap(first.authorityTuple()); + + assertThat(new String(creatorPayload, StandardCharsets.UTF_8)) + .contains(evidence.creationEvidence().sourceGameTenantKey()) + .contains(evidence.accountAuthorizationOperationId().toString()) + .contains(evidence.accountAuthorizationDigest()); + assertThat(firstSource).isNotEqualTo(laterSource); + assertThat(tuple) + .containsEntry("tenantAuthorityGeneration", Map.of(tenantUuid.toString(), "1")) + .containsEntry("membershipAuthorityGeneration", Map.of(tenantUuid.toString(), "1")); + assertThat(AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, firstSource)) + .isNotEqualTo( + AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, laterSource)); + } + + private static NeverJoinedMembershipSnapshot snapshot( + UUID accountUuid, UUID tenantUuid, String issuanceFence) { + String account = accountUuid.toString(); + String tenant = tenantUuid.toString(); + String stream = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + account + + "/" + + tenant; + AuthorityTuple tuple = + new AuthorityTuple( + "1", + "1", + Map.of(tenant, "1"), + Map.of(tenant, "1"), + List.of(), + Optional.empty(), + Optional.empty()); + return new NeverJoinedMembershipSnapshot( + account, + tenant, + Map.of(tenant, "1"), + "1", + tuple, + issuanceFence, + Instant.parse("2026-10-01T00:00:00Z"), + stream, + List.of( + new OutboxCheckpointEntry("account:auth-authority:v1:account/" + account, "0"), + new OutboxCheckpointEntry( + "account:auth-authority:v1:issuer/firemud-account-service", "0"), + new OutboxCheckpointEntry(stream, "0"), + new OutboxCheckpointEntry("account:auth-authority:v1:tenant/" + tenant, "0")), + List.of()); + } + + private static FreshTenantCreatorEvidence evidence(UUID accountUuid, UUID tenantUuid) { + UUID requestId = UUID.randomUUID(); + UUID creationOperationId = UUID.randomUUID(); + UUID authorizationOperationId = UUID.randomUUID(); + String namespace = "firemud-test"; + String tenantKey = "world-source-17"; + String requestDigest = + GameTenantCreationDigest.requestDigest(namespace, requestId, tenantKey, "Example", null); + FreshTenantCreationEvidence creation = + new FreshTenantCreationEvidence( + 1, + namespace, + requestId, + creationOperationId, + requestDigest, + tenantUuid, + 17L, + tenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + namespace, + requestId, + creationOperationId, + requestDigest, + tenantUuid, + 17L, + tenantKey, + "NEW_GAME_ROW")); + String authorizationDigest = "sha256:" + "6".repeat(64); + return new FreshTenantCreatorEvidence( + 1, + creation, + accountUuid, + authorizationOperationId, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, accountUuid, authorizationOperationId, authorizationDigest)); + } + + private static byte[] resultPayload(UUID tenantUuid, Map membershipVersion) { + return AccountTenantCreationBootstrapDigest.resultPayload( + "request-id", + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + tenantUuid, + membershipVersion, + "1", + "membership-stream", + "event-request-id", + 1L, + "event-id", + "sha256:" + "3".repeat(64), + new byte[] {1}, + UUID.randomUUID(), + "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED", + "2026-10-01T00:00:00Z", + "sha256:" + "4".repeat(64), + new byte[] {2}, + new byte[] {3}, + new byte[] {4}); + } + + private static String resultJson(byte[] payload) { + ByteBuffer buffer = ByteBuffer.wrap(payload); + int domainLength = buffer.getInt(); + buffer.position(buffer.position() + domainLength); + int resultLength = buffer.getInt(); + byte[] result = new byte[resultLength]; + buffer.get(result); + return new String(result, StandardCharsets.UTF_8); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java new file mode 100644 index 0000000000..018de0893d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +@ExtendWith(MockitoExtension.class) +class AccountCreatorMembershipSourceReaderTest { + @Mock private AccountRepository accounts; + @Mock private AccountJoinOperationRepository joins; + @Mock private AccountTenantMembershipRepository memberships; + @Mock private AccountMembershipPairAuthorityRepository pairs; + @Mock private AccountTenantMembershipRoleSnapshotRepository roles; + @Mock private FreshTenantIdentityAssociationRepository fresh; + @Mock private AccountAuthorityGenerationRepository generations; + @Mock private AccountAuthorityOutboxRepository outbox; + @Mock private AccountAuthoritySourceEvidenceRepository sources; + @Mock private AccountTenantCreationBootstrapOperationRepository operations; + @Mock private CompositeSnapshot upstream; + @InjectMocks private AccountCreatorMembershipSourceReader reader; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void requiresWritableOwnerTransactionBeforeReadingOrEnrollingAnything() { + assertThatThrownBy( + () -> + reader.readFreshNeverJoinedMembershipSnapshot(UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions( + accounts, + joins, + memberships, + pairs, + roles, + fresh, + generations, + outbox, + sources, + operations); + } + + @Test + void missingGenuineUpstreamSourcesCannotCreateAnAbsenceBaseline() { + UUID accountUuid = UUID.randomUUID(); + UUID tenantUuid = UUID.randomUUID(); + Account account = new Account(); + account.setId(17L); + account.setAccountUuid(accountUuid); + account.setAccountUuidSourceNumericId(17L); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + TransactionSynchronizationManager.setActualTransactionActive(true); + when(accounts.findByAccountUuidForUpdate(accountUuid)).thenReturn(Optional.of(account)); + when(fresh.read(tenantUuid)).thenReturn(Optional.of(creation(tenantUuid))); + when(generations.readCompositeSnapshot( + "firemud-account-service", accountUuid, List.of(tenantUuid), List.of())) + .thenReturn(upstream); + when(sources.readCurrentIssuerAccountSources("firemud-account-service", accountUuid)) + .thenThrow(new IllegalStateException("Genuine Account source baseline is unavailable")); + assertThatThrownBy(() -> reader.readFreshNeverJoinedMembershipSnapshot(accountUuid, tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source baseline is unavailable"); + verifyNoInteractions(memberships, pairs, roles, outbox, operations); + } + + private static FreshTenantCreationEvidence creation(UUID tenantUuid) { + UUID request = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + String namespace = "creator-source-proof"; + String key = "creator-game"; + String digest = + GameTenantCreationDigest.requestDigest(namespace, request, key, "Creator", null); + return new FreshTenantCreationEvidence( + 1, + namespace, + request, + operation, + digest, + tenantUuid, + 17L, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + namespace, request, operation, digest, tenantUuid, 17L, key, "NEW_GAME_ROW")); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapServiceTest.java new file mode 100644 index 0000000000..eccb88047b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapServiceTest.java @@ -0,0 +1,138 @@ +package net.firedevops.firemud.accountservice.service; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Focused proof that no DTO-only or unregistered source can activate creator membership. */ +@ExtendWith(MockitoExtension.class) +class AccountTenantCreationBootstrapServiceTest { + @Mock private AccountRepository accountRepository; + @Mock private FreshTenantIdentityAssociationRepository tenantAssociationRepository; + @Mock private AccountCreatorMembershipSourceReader creatorSourceReader; + @Mock private AccountMembershipPairAuthorityRepository pairAuthorityRepository; + @Mock private AccountTenantMembershipRepository membershipRepository; + @Mock private AccountTenantMembershipRoleSnapshotRepository roleSnapshotRepository; + @Mock private AccountAuthorityOutboxRepository authorityOutboxRepository; + @Mock private AccountAuditOutboxRepository auditOutboxRepository; + @Mock private AccountTenantCreationBootstrapOperationRepository operationRepository; + + @Mock + private ObjectProvider + authorizationSourceProvider; + + @InjectMocks private AccountTenantCreationBootstrapService service; + + @AfterEach + void clearSyntheticTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void exactCreatorDtoCannotCommitWithoutRegisteredCurrentAccountAuthorizationSource() { + FreshTenantCreatorEvidence evidence = evidence(); + Account creator = account(evidence.initiatingAccountId()); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + when(accountRepository.findByAccountUuidForUpdate(evidence.initiatingAccountId())) + .thenReturn(Optional.of(creator)); + when(operationRepository.findForUpdate(evidence.accountAuthorizationOperationId())) + .thenReturn(Optional.empty()); + when(operationRepository.findRequestIdByTenantForUpdate( + evidence.creationEvidence().canonicalTenantId())) + .thenReturn(Optional.empty()); + when(authorizationSourceProvider.getIfAvailable()).thenReturn(null); + + assertThatThrownBy(() -> service.bootstrap(evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No current Account creator-authorization/source participant"); + + verify(authorizationSourceProvider).getIfAvailable(); + verifyNoInteractions( + tenantAssociationRepository, + creatorSourceReader, + pairAuthorityRepository, + membershipRepository, + roleSnapshotRepository, + authorityOutboxRepository, + auditOutboxRepository); + } + + private static Account account(UUID accountUuid) { + Account account = new Account(); + account.setId(17L); + account.setAccountUuid(accountUuid); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(17L); + return account; + } + + private static FreshTenantCreatorEvidence evidence() { + UUID creatorUuid = UUID.randomUUID(); + UUID tenantUuid = UUID.randomUUID(); + UUID creationRequestId = UUID.randomUUID(); + UUID creationOperationId = UUID.randomUUID(); + UUID authorizationOperationId = UUID.randomUUID(); + String targetNamespace = "firemud-test"; + String tenantKey = "source-tenant-17"; + String requestDigest = + GameTenantCreationDigest.requestDigest( + targetNamespace, creationRequestId, tenantKey, "Example", null); + FreshTenantCreationEvidence creationEvidence = + new FreshTenantCreationEvidence( + 1, + targetNamespace, + creationRequestId, + creationOperationId, + requestDigest, + tenantUuid, + 17L, + tenantKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + targetNamespace, + creationRequestId, + creationOperationId, + requestDigest, + tenantUuid, + 17L, + tenantKey, + "NEW_GAME_ROW")); + String authorizationDigest = "sha256:" + "4".repeat(64); + return new FreshTenantCreatorEvidence( + 1, + creationEvidence, + creatorUuid, + authorizationOperationId, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creationEvidence, creatorUuid, authorizationOperationId, authorizationDigest)); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java new file mode 100644 index 0000000000..eb12b42d85 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java @@ -0,0 +1,685 @@ +package net.firedevops.firemud.common.account.authority; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; + +/** + * Validates the content and cross-binding of one current runtime membership evidence snapshot. + * + *

This does not authenticate the source or authorize gameplay admission. The membership event is + * immutable historical evidence; a caller supplies the separate current tuple, fence and + * checkpoints. Private-realm grant and tenant-billing tuple evidence are not supported by this + * candidate and are rejected until their source contracts are available. An empty result for a + * missing membership is only a local statement about the supplied snapshot, not proof that the + * account has never joined. + */ +public final class RuntimeMembershipAuthorityEvidenceValidator { + private static final String EVENT_STREAM_PREFIX = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final String NIL_UUID = "00000000-0000-0000-0000-000000000000"; + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]*)"); + private static final Set MEMBERSHIP_LIFECYCLES = Set.of("ACTIVE", "INACTIVE"); + + private RuntimeMembershipAuthorityEvidenceValidator() {} + + /** + * Verifies every supplied source event and binds the immutable membership event to the current + * recipient carrier. Returns empty only for a well-formed snapshot whose membership checkpoint is + * zero and whose current membership state is explicitly missing and nonadmitting. + * + * @throws IllegalArgumentException if the snapshot is malformed, incomplete, inconsistent, or + * contains unsupported authority evidence + */ + public static Optional validate(Snapshot evidence) { + Objects.requireNonNull(evidence, "evidence must not be null"); + + requireCanonicalUuid(evidence.accountId(), "accountId"); + requireCanonicalUuid(evidence.tenantId(), "tenantId"); + requireNonBlank(evidence.issuerId(), "issuerId"); + requirePositiveDecimal( + evidence.membershipAuthorityGeneration(), "membershipAuthorityGeneration"); + requirePositiveDecimal(evidence.issuanceFence(), "issuanceFence"); + requireExactTenantValue(evidence.membershipVersion(), evidence.tenantId(), "membershipVersion"); + + AuthorityTuple currentTuple = evidence.authorityTuple(); + requireTupleShape( + currentTuple, + evidence.accountId(), + evidence.tenantId(), + evidence.membershipAuthorityGeneration(), + "authorityTuple"); + + String issuerStream = EVENT_STREAM_PREFIX + "issuer/" + evidence.issuerId(); + String accountStream = EVENT_STREAM_PREFIX + "account/" + evidence.accountId(); + String tenantStream = EVENT_STREAM_PREFIX + "tenant/" + evidence.tenantId(); + String membershipStream = + EVENT_STREAM_PREFIX + "membership/" + evidence.accountId() + "/" + evidence.tenantId(); + List expectedStreams = + new ArrayList<>(List.of(issuerStream, accountStream, tenantStream, membershipStream)); + expectedStreams.sort(RuntimeMembershipAuthorityEvidenceValidator::compareUtf8); + + Map checkpoints = + validateCheckpoints(evidence.checkpoints(), expectedStreams); + Map sources = + validateSourceInventory(evidence.sourceEvidence(), checkpoints); + + verifyIssuerSource( + sources.get(issuerStream), + checkpoints.get(issuerStream), + evidence.issuerId(), + currentTuple.issuerAuthGeneration()); + AccountSource accountSource = + verifyAccountSource( + sources.get(accountStream), + checkpoints.get(accountStream), + evidence.accountId(), + currentTuple.accountAuthorityGeneration()); + verifyTenantSource( + sources.get(tenantStream), + checkpoints.get(tenantStream), + evidence.tenantId(), + currentTuple.tenantAuthorityGeneration().get(evidence.tenantId())); + + validateCurrentAccountCutoff( + currentTuple, accountSource, checkpoints.get(accountStream), accountStream); + + Checkpoint membershipCheckpoint = checkpoints.get(membershipStream); + if (membershipCheckpoint.outboxSequence().equals("0")) { + validateMissingMembership(evidence); + return Optional.empty(); + } + + MembershipEvent membershipEvent = + verifyMembershipSource( + sources.get(membershipStream), + membershipCheckpoint, + evidence.accountId(), + evidence.tenantId()); + validateMembershipCarrier(evidence, membershipEvent, currentTuple, accountSource); + + return Optional.of(membershipEvent); + } + + private static Map validateCheckpoints( + List supplied, List expectedStreams) { + if (supplied.size() != expectedStreams.size()) { + throw invalid("checkpoints", "must contain exactly the four authority streams"); + } + Map checkpoints = new HashMap<>(); + String previousStream = null; + for (Checkpoint checkpoint : supplied) { + if (!expectedStreams.contains(checkpoint.outboxStreamKey())) { + throw invalid("checkpoints", "contains an unexpected authority stream"); + } + if (previousStream != null + && compareUtf8(previousStream, checkpoint.outboxStreamKey()) >= 0) { + throw invalid("checkpoints", "must be sorted by stream key and contain no duplicates"); + } + if (checkpoints.putIfAbsent(checkpoint.outboxStreamKey(), checkpoint) != null) { + throw invalid("checkpoints", "contains a duplicate authority stream"); + } + requireNonNegativeDecimal(checkpoint.outboxSequence(), "checkpoint.outboxSequence"); + previousStream = checkpoint.outboxStreamKey(); + } + if (!checkpoints.keySet().equals(Set.copyOf(expectedStreams))) { + throw invalid("checkpoints", "must cover each expected authority stream exactly once"); + } + return Map.copyOf(checkpoints); + } + + private static Map validateSourceInventory( + List supplied, Map checkpoints) { + Map sources = new HashMap<>(); + String previousStream = null; + for (SourceEvidence source : supplied) { + if (previousStream != null && compareUtf8(previousStream, source.outboxStreamKey()) >= 0) { + throw invalid("sourceEvidence", "must be sorted by stream key and contain no duplicates"); + } + Checkpoint checkpoint = checkpoints.get(source.outboxStreamKey()); + if (checkpoint == null || checkpoint.outboxSequence().equals("0")) { + throw invalid("sourceEvidence", "contains evidence without a positive checkpoint"); + } + if (!checkpoint.outboxSequence().equals(source.outboxSequence())) { + throw invalid("sourceEvidence", "sequence must equal its exact current checkpoint"); + } + if (sources.putIfAbsent(source.outboxStreamKey(), source) != null) { + throw invalid("sourceEvidence", "contains a duplicate authority stream"); + } + previousStream = source.outboxStreamKey(); + } + + for (Checkpoint checkpoint : checkpoints.values()) { + boolean hasSource = sources.containsKey(checkpoint.outboxStreamKey()); + if (checkpoint.outboxSequence().equals("0") == hasSource) { + throw invalid( + "sourceEvidence", "must contain one source for each positive checkpoint only"); + } + } + return Map.copyOf(sources); + } + + private static void verifyIssuerSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedIssuerId, + String currentGeneration) { + if (checkpoint.outboxSequence().equals("0")) { + requireEquals("1", currentGeneration, "authorityTuple.issuerAuthGeneration baseline"); + return; + } + var verified = AccountAuthoritySourceEventV1Codec.verify(supplied.canonicalEventJson()); + if (!(verified instanceof AccountAuthoritySourceEventV1Codec.IssuerEvent event)) { + throw invalid("issuer source", "must use the current issuer owner schema"); + } + requireSourceIdentity( + supplied, + checkpoint, + event.eventId(), + event.eventDigest(), + event.canonicalJson(), + event.outboxSequence(), + event.outboxStreamKey()); + requireEquals(expectedIssuerId, event.issuerId(), "issuer source issuerId"); + requireEquals(currentGeneration, event.issuerAuthGeneration(), "current issuer generation"); + } + + private static void verifyTenantSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedTenantId, + String currentGeneration) { + if (checkpoint.outboxSequence().equals("0")) { + requireEquals("1", currentGeneration, "authorityTuple.tenantAuthorityGeneration baseline"); + return; + } + throw invalid( + "tenant source", "advanced tenant authority requires its supported owner source contract"); + } + + private static AccountSource verifyAccountSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedAccountId, + String currentGeneration) { + if (checkpoint.outboxSequence().equals("0")) { + requireEquals("1", currentGeneration, "authorityTuple.accountAuthorityGeneration baseline"); + return null; + } + + AccountSource event; + try { + var verified = AccountAuthoritySourceEventV1Codec.verify(supplied.canonicalEventJson()); + if (!(verified instanceof AccountAuthoritySourceEventV1Codec.AccountEvent account)) { + throw invalid("account source", "must be an Account event"); + } + event = + new AccountSource( + account.eventId(), + account.eventDigest(), + account.canonicalJson(), + account.outboxStreamKey(), + account.outboxSequence(), + account.accountId(), + account.accountAuthorityGeneration(), + account.accountSecurityCutoff().accountAuthorityGeneration(), + account.accountSecurityCutoff().outboxStreamKey(), + account.accountSecurityCutoff().outboxSequence()); + } catch (IllegalArgumentException currentSchemaMismatch) { + try { + var reset = PasswordResetAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + event = + new AccountSource( + reset.eventId(), + reset.eventDigest(), + reset.canonicalJson(), + reset.outboxStreamKey(), + reset.outboxSequence(), + reset.accountId(), + reset.accountAuthorityGeneration(), + reset.accountSecurityCutoff().accountAuthorityGeneration(), + reset.accountSecurityCutoff().outboxStreamKey(), + reset.accountSecurityCutoff().outboxSequence()); + } catch (IllegalArgumentException resetFailure) { + try { + var logout = AccountLogoutAllAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + event = + new AccountSource( + logout.eventId(), + logout.eventDigest(), + logout.canonicalJson(), + logout.outboxStreamKey(), + logout.outboxSequence(), + logout.accountId(), + logout.accountAuthorityGeneration(), + logout.accountSecurityCutoff().accountAuthorityGeneration(), + logout.accountSecurityCutoff().outboxStreamKey(), + logout.accountSecurityCutoff().outboxSequence()); + } catch (IllegalArgumentException logoutFailure) { + var security = + AccountSecurityStateAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + event = + new AccountSource( + security.eventId(), + security.eventDigest(), + security.canonicalJson(), + security.outboxStreamKey(), + security.outboxSequence(), + security.accountId(), + security.accountAuthorityGeneration(), + security.accountSecurityCutoff().accountAuthorityGeneration(), + security.accountSecurityCutoff().outboxStreamKey(), + security.accountSecurityCutoff().outboxSequence()); + } + } + } + requireSourceIdentity( + supplied, + checkpoint, + event.eventId(), + event.eventDigest(), + event.canonicalJson(), + event.outboxSequence(), + event.outboxStreamKey()); + requireEquals(expectedAccountId, event.accountId(), "account source accountId"); + requireEquals( + currentGeneration, event.accountAuthorityGeneration(), "current account generation"); + requireEquals( + event.accountAuthorityGeneration(), event.cutoffGeneration(), "account cutoff generation"); + requireEquals(event.outboxStreamKey(), event.cutoffStream(), "account cutoff stream key"); + requireEquals(event.outboxSequence(), event.cutoffSequence(), "account cutoff sequence"); + return event; + } + + private static MembershipEvent verifyMembershipSource( + SourceEvidence supplied, + Checkpoint checkpoint, + String expectedAccountId, + String expectedTenantId) { + MembershipEvent event = MembershipAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + requireSourceIdentity( + supplied, + checkpoint, + event.eventId(), + event.eventDigest(), + event.canonicalJson(), + event.outboxSequence(), + event.outboxStreamKey()); + requireEquals(expectedAccountId, event.accountId(), "membership source accountId"); + requireEquals(expectedTenantId, event.tenantId(), "membership source tenantId"); + return event; + } + + private static void requireSourceIdentity( + SourceEvidence supplied, + Checkpoint checkpoint, + String eventId, + String eventDigest, + String canonicalJson, + String eventSequence, + String eventStreamKey) { + requireEquals(checkpoint.outboxStreamKey(), eventStreamKey, "source event stream key"); + requireEquals( + checkpoint.outboxStreamKey(), supplied.outboxStreamKey(), "source carrier stream key"); + requireEquals( + checkpoint.outboxSequence(), supplied.outboxSequence(), "source carrier sequence"); + requireEquals(checkpoint.outboxSequence(), eventSequence, "source event sequence"); + requireEquals(eventId, supplied.eventId(), "source carrier eventId"); + requireEquals(eventDigest, supplied.eventDigest(), "source carrier eventDigest"); + requireEquals( + canonicalJson, supplied.canonicalEventJson(), "source carrier canonical event bytes"); + } + + private static void validateCurrentAccountCutoff( + AuthorityTuple tuple, + AccountSource source, + Checkpoint checkpoint, + String expectedAccountStream) { + Optional cutoff = tuple.accountSecurityCutoff(); + if (checkpoint.outboxSequence().equals("0")) { + if (cutoff.isPresent()) { + throw invalid( + "authorityTuple.accountSecurityCutoff", "must be absent at the account baseline"); + } + return; + } + if (cutoff.isEmpty() || source == null) { + throw invalid( + "authorityTuple.accountSecurityCutoff", "must bind the current account source event"); + } + AccountSecurityCutoff current = cutoff.orElseThrow(); + requireEquals( + tuple.accountAuthorityGeneration(), + current.accountAuthorityGeneration(), + "current account cutoff generation"); + requireEquals( + expectedAccountStream, current.outboxStreamKey(), "current account cutoff stream key"); + requireEquals( + checkpoint.outboxSequence(), current.outboxSequence(), "current account cutoff sequence"); + requireEquals( + source.cutoffGeneration(), + current.accountAuthorityGeneration(), + "current account cutoff source generation"); + requireEquals( + source.cutoffStream(), current.outboxStreamKey(), "current account cutoff source stream"); + requireEquals( + source.cutoffSequence(), + current.outboxSequence(), + "current account cutoff source sequence"); + } + + private static void validateMissingMembership(Snapshot evidence) { + if (evidence.membershipExists() + || !"MISSING".equals(evidence.membershipLifecycleState()) + || evidence.gameplayAdmissionAllowed() + || !evidence.roles().isEmpty()) { + throw invalid( + "membership", "zero checkpoint requires MISSING, absent, empty-role, nonadmitting state"); + } + // The absent-row representation still carries positive persisted defaults. This check is + // content validation only and cannot establish that a prior membership never existed. + requirePositiveDecimal( + evidence.membershipVersion().get(evidence.tenantId()), "membershipVersion"); + requirePositiveDecimal( + evidence.membershipAuthorityGeneration(), "membershipAuthorityGeneration"); + requirePositiveDecimal(evidence.issuanceFence(), "issuanceFence"); + } + + private static void validateMembershipCarrier( + Snapshot evidence, + MembershipEvent event, + AuthorityTuple currentTuple, + AccountSource currentAccountSource) { + if (!evidence.membershipExists()) { + throw invalid("membershipExists", "must be true for a positive membership checkpoint"); + } + if (!MEMBERSHIP_LIFECYCLES.contains(evidence.membershipLifecycleState())) { + throw invalid( + "membershipLifecycleState", "must be ACTIVE or INACTIVE for an existing membership"); + } + requireEquals( + event.membershipLifecycleState(), + evidence.membershipLifecycleState(), + "membershipLifecycleState"); + requireEquals( + event.gameplayAdmissionAllowed(), + evidence.gameplayAdmissionAllowed(), + "gameplayAdmissionAllowed"); + requireEquals(event.roles(), evidence.roles(), "roles"); + requireEquals(event.membershipVersion(), evidence.membershipVersion(), "membershipVersion"); + requireEquals( + event.membershipAuthorityGeneration(), + evidence.membershipAuthorityGeneration(), + "membershipAuthorityGeneration"); + requireEquals( + event.membershipAuthorityGeneration(), + currentTuple.membershipAuthorityGeneration().get(evidence.tenantId()), + "current membership authority generation"); + + AuthorityTuple eventTuple = event.authorityTuple(); + requireSupportedTupleExtensions(eventTuple, "membership source authorityTuple"); + requireAtMost( + eventTuple.issuerAuthGeneration(), + currentTuple.issuerAuthGeneration(), + "membership source issuerAuthGeneration"); + requireAtMost( + eventTuple.accountAuthorityGeneration(), + currentTuple.accountAuthorityGeneration(), + "membership source accountAuthorityGeneration"); + requireAtMost( + eventTuple.tenantAuthorityGeneration().get(evidence.tenantId()), + currentTuple.tenantAuthorityGeneration().get(evidence.tenantId()), + "membership source tenantAuthorityGeneration"); + requireAtMost( + event.issuanceFence(), evidence.issuanceFence(), "membership source issuanceFence"); + validateHistoricalAccountCutoff(eventTuple, currentTuple, currentAccountSource); + } + + private static void validateHistoricalAccountCutoff( + AuthorityTuple eventTuple, AuthorityTuple currentTuple, AccountSource currentAccountSource) { + Optional historicalCutoff = eventTuple.accountSecurityCutoff(); + Optional currentCutoff = currentTuple.accountSecurityCutoff(); + int accountGenerationOrder = + compareDecimal( + eventTuple.accountAuthorityGeneration(), currentTuple.accountAuthorityGeneration()); + if (accountGenerationOrder == 0) { + if (historicalCutoff.isPresent() != currentCutoff.isPresent()) { + throw invalid( + "membership source accountSecurityCutoff", + "must match cutoff presence at the same generation"); + } + if (historicalCutoff.isPresent() + && !historicalCutoff.orElseThrow().equals(currentCutoff.orElseThrow())) { + throw invalid( + "membership source accountSecurityCutoff", + "must equal the current cutoff at the same generation"); + } + } + if (historicalCutoff.isEmpty()) { + requireEquals( + "1", + eventTuple.accountAuthorityGeneration(), + "membership source accountAuthorityGeneration without a cutoff"); + return; + } + if (currentCutoff.isEmpty() || currentAccountSource == null) { + throw invalid( + "membership source accountSecurityCutoff", + "cannot exceed or outlive current account cutoff evidence"); + } + AccountSecurityCutoff historical = historicalCutoff.orElseThrow(); + AccountSecurityCutoff current = currentCutoff.orElseThrow(); + requireEquals( + current.outboxStreamKey(), + historical.outboxStreamKey(), + "historical account cutoff stream key"); + requireAtMost( + historical.accountAuthorityGeneration(), + current.accountAuthorityGeneration(), + "historical account cutoff generation"); + requireAtMost( + historical.outboxSequence(), + current.outboxSequence(), + "historical account cutoff sequence"); + } + + private static void requireTupleShape( + AuthorityTuple tuple, + String accountId, + String tenantId, + String membershipGeneration, + String path) { + requirePositiveDecimal(tuple.issuerAuthGeneration(), path + ".issuerAuthGeneration"); + requirePositiveDecimal( + tuple.accountAuthorityGeneration(), path + ".accountAuthorityGeneration"); + requireExactTenantValue( + tuple.tenantAuthorityGeneration(), tenantId, path + ".tenantAuthorityGeneration"); + requireExactTenantValue( + tuple.membershipAuthorityGeneration(), tenantId, path + ".membershipAuthorityGeneration"); + requireEquals( + membershipGeneration, + tuple.membershipAuthorityGeneration().get(tenantId), + path + ".membershipAuthorityGeneration"); + requireSupportedTupleExtensions(tuple, path); + tuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> { + requirePositiveDecimal( + cutoff.accountAuthorityGeneration(), + path + ".accountSecurityCutoff.accountAuthorityGeneration"); + requireEquals( + EVENT_STREAM_PREFIX + "account/" + accountId, + cutoff.outboxStreamKey(), + path + ".accountSecurityCutoff.outboxStreamKey"); + requirePositiveDecimal( + cutoff.outboxSequence(), path + ".accountSecurityCutoff.outboxSequence"); + requireEquals( + tuple.accountAuthorityGeneration(), + cutoff.accountAuthorityGeneration(), + path + ".accountSecurityCutoff.accountAuthorityGeneration"); + }); + } + + private static void requireSupportedTupleExtensions(AuthorityTuple tuple, String path) { + if (!tuple.privateRealmGrantVersions().isEmpty()) { + throw invalid(path + ".privateRealmGrantVersions", "is not supported by this candidate"); + } + if (tuple.tenantBillingCutoff().isPresent()) { + throw invalid(path + ".tenantBillingCutoff", "is not supported by this candidate"); + } + } + + private static void requireExactTenantValue( + Map values, String tenantId, String path) { + if (values.size() != 1 || !values.containsKey(tenantId)) { + throw invalid(path, "must contain exactly the current tenantId key"); + } + requirePositiveDecimal(values.get(tenantId), path + "." + tenantId); + } + + private static void requireCanonicalUuid(String value, String path) { + if (!UUID_PATTERN.matcher(value).matches() || NIL_UUID.equals(value)) { + throw invalid(path, "must be a canonical lowercase non-nil UUID"); + } + } + + private static void requireNonBlank(String value, String path) { + if (value.isBlank()) { + throw invalid(path, "must be nonblank"); + } + } + + private static void requirePositiveDecimal(String value, String path) { + if (!POSITIVE_DECIMAL.matcher(value).matches()) { + throw invalid(path, "must be a positive canonical decimal string"); + } + } + + private static void requireNonNegativeDecimal(String value, String path) { + if (!NON_NEGATIVE_DECIMAL.matcher(value).matches()) { + throw invalid(path, "must be a non-negative canonical decimal string"); + } + } + + private static void requireAtMost(String lowerOrEqual, String upper, String path) { + requirePositiveDecimal(lowerOrEqual, path); + requirePositiveDecimal(upper, path + " current"); + if (compareDecimal(lowerOrEqual, upper) > 0) { + throw invalid(path, "must not be ahead of current authority"); + } + } + + private static int compareDecimal(String left, String right) { + return new BigInteger(left).compareTo(new BigInteger(right)); + } + + private static int compareUtf8(String left, String right) { + byte[] leftBytes = left.getBytes(StandardCharsets.UTF_8); + byte[] rightBytes = right.getBytes(StandardCharsets.UTF_8); + int commonLength = Math.min(leftBytes.length, rightBytes.length); + for (int index = 0; index < commonLength; index++) { + int comparison = + Integer.compare( + Byte.toUnsignedInt(leftBytes[index]), Byte.toUnsignedInt(rightBytes[index])); + if (comparison != 0) { + return comparison; + } + } + return Integer.compare(leftBytes.length, rightBytes.length); + } + + private static void requireEquals(Object expected, Object actual, String path) { + if (!Objects.equals(expected, actual)) { + throw invalid(path, "does not match its bound evidence"); + } + } + + private static IllegalArgumentException invalid(String path, String message) { + return new IllegalArgumentException(path + " " + message); + } + + private record AccountSource( + String eventId, + String eventDigest, + String canonicalJson, + String outboxStreamKey, + String outboxSequence, + String accountId, + String accountAuthorityGeneration, + String cutoffGeneration, + String cutoffStream, + String cutoffSequence) {} + + /** Immutable sequence checkpoint for one exact Account authority stream. */ + public record Checkpoint(String outboxStreamKey, String outboxSequence) { + public Checkpoint { + Objects.requireNonNull(outboxStreamKey, "outboxStreamKey must not be null"); + Objects.requireNonNull(outboxSequence, "outboxSequence must not be null"); + } + } + + /** Immutable source-event carrier bound to its exact stream and checkpoint. */ + public record SourceEvidence( + String outboxStreamKey, + String outboxSequence, + String eventId, + String eventDigest, + String canonicalEventJson) { + public SourceEvidence { + Objects.requireNonNull(outboxStreamKey, "outboxStreamKey must not be null"); + Objects.requireNonNull(outboxSequence, "outboxSequence must not be null"); + Objects.requireNonNull(eventId, "eventId must not be null"); + Objects.requireNonNull(eventDigest, "eventDigest must not be null"); + Objects.requireNonNull(canonicalEventJson, "canonicalEventJson must not be null"); + } + } + + /** Immutable current recipient carrier plus the exact source evidence it claims to summarize. */ + public record Snapshot( + String issuerId, + String accountId, + String tenantId, + boolean membershipExists, + String membershipLifecycleState, + boolean gameplayAdmissionAllowed, + Map membershipVersion, + String membershipAuthorityGeneration, + List roles, + AuthorityTuple authorityTuple, + String issuanceFence, + List checkpoints, + List sourceEvidence) { + public Snapshot { + Objects.requireNonNull(issuerId, "issuerId must not be null"); + Objects.requireNonNull(accountId, "accountId must not be null"); + Objects.requireNonNull(tenantId, "tenantId must not be null"); + Objects.requireNonNull(membershipLifecycleState, "membershipLifecycleState must not be null"); + membershipVersion = + Map.copyOf( + Objects.requireNonNull(membershipVersion, "membershipVersion must not be null")); + Objects.requireNonNull( + membershipAuthorityGeneration, "membershipAuthorityGeneration must not be null"); + roles = List.copyOf(Objects.requireNonNull(roles, "roles must not be null")); + Objects.requireNonNull(authorityTuple, "authorityTuple must not be null"); + Objects.requireNonNull(issuanceFence, "issuanceFence must not be null"); + checkpoints = + List.copyOf(Objects.requireNonNull(checkpoints, "checkpoints must not be null")); + sourceEvidence = + List.copyOf(Objects.requireNonNull(sourceEvidence, "sourceEvidence must not be null")); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java new file mode 100644 index 0000000000..8a153c841e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigest.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.common.tenant; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; + +/** Canonical digest for the distinct Account-initiator qualification on fresh tenant creation. */ +public final class FreshTenantCreatorDigest { + private static final int SCHEMA_VERSION = 1; + private static final String QUALIFICATION_DOMAIN = "game-design-tenant-creator-qualification/v1"; + private static final String DIGEST_PREFIX = "sha256:"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private FreshTenantCreatorDigest() {} + + /** + * Digests every original creation-evidence field, then the initiating Account and Account-owned + * authorization identity/digest, using decimal-byte-length-prefixed UTF-8 segments. + */ + public static String evidenceDigest( + int schemaVersion, + FreshTenantCreationEvidence creationEvidence, + UUID initiatingAccountId, + UUID accountAuthorizationOperationId, + String accountAuthorizationDigest) { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported fresh tenant creator evidence version"); + } + Objects.requireNonNull(creationEvidence, "creationEvidence"); + requireNonNil(initiatingAccountId, "initiatingAccountId"); + requireNonNil(accountAuthorizationOperationId, "accountAuthorizationOperationId"); + if (!GameTenantCreationDigest.isDigest(accountAuthorizationDigest)) { + throw new IllegalArgumentException( + "accountAuthorizationDigest must be a lowercase SHA-256 digest"); + } + + return digest( + QUALIFICATION_DOMAIN, + Integer.toString(schemaVersion), + Integer.toString(creationEvidence.schemaVersion()), + creationEvidence.targetNamespace(), + creationEvidence.creationRequestId().toString(), + creationEvidence.operationId().toString(), + creationEvidence.requestDigest(), + creationEvidence.canonicalTenantId().toString(), + Long.toString(creationEvidence.sourceGameRowId()), + creationEvidence.sourceGameTenantKey(), + creationEvidence.provenanceKind(), + creationEvidence.evidenceDigest(), + initiatingAccountId.toString(), + accountAuthorizationOperationId.toString(), + accountAuthorizationDigest); + } + + 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"); + } + } + + private static String digest(String... segments) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + for (String segment : segments) { + byte[] bytes = encodeUtf8(segment); + byte[] length = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8); + preimage.writeBytes(length); + preimage.write(':'); + preimage.writeBytes(bytes); + } + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray()); + return DIGEST_PREFIX + HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static byte[] encodeUtf8(String value) { + Objects.requireNonNull(value, "digest segment"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Creator evidence must contain valid Unicode", exception); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java new file mode 100644 index 0000000000..ebdc4bc8a3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidence.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.common.tenant; + +import java.util.Objects; +import java.util.UUID; + +/** + * Immutable creator-qualification evidence bound to one exact fresh tenant source operation. + * + *

This record validates a closed digest-bound tuple. The Account UUID and authorization + * operation fields are data, not authenticated proof by themselves; the Account-owned producer must + * supply and protect their authority. + */ +public record FreshTenantCreatorEvidence( + int schemaVersion, + FreshTenantCreationEvidence creationEvidence, + UUID initiatingAccountId, + UUID accountAuthorizationOperationId, + String accountAuthorizationDigest, + String evidenceDigest) { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public FreshTenantCreatorEvidence { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported fresh tenant creator evidence version"); + } + Objects.requireNonNull(creationEvidence, "creationEvidence"); + requireNonNil(initiatingAccountId, "initiatingAccountId"); + requireNonNil(accountAuthorizationOperationId, "accountAuthorizationOperationId"); + if (!GameTenantCreationDigest.isDigest(accountAuthorizationDigest)) { + throw new IllegalArgumentException( + "accountAuthorizationDigest must be a lowercase SHA-256 digest"); + } + Objects.requireNonNull(evidenceDigest, "evidenceDigest"); + String expectedDigest = + FreshTenantCreatorDigest.evidenceDigest( + schemaVersion, + creationEvidence, + initiatingAccountId, + accountAuthorizationOperationId, + accountAuthorizationDigest); + if (!expectedDigest.equals(evidenceDigest)) { + throw new IllegalArgumentException( + "Creator evidence digest does not match the immutable qualification tuple"); + } + } + + 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/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java new file mode 100644 index 0000000000..d5a367346f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java @@ -0,0 +1,924 @@ +package net.firedevops.firemud.common.account.authority; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AccountSecurityCutoff; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Checkpoint; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence; +import org.junit.jupiter.api.Test; + +class RuntimeMembershipAuthorityEvidenceValidatorTest { + private static final String ISSUER_ID = "issuer-main"; + private static final String ACCOUNT_ID = "018f8f0a-1a6b-7b13-8d04-5f6e7d8c9b0a"; + private static final String TENANT_ID = "018f8f0a-2b7c-7a24-9c15-6a9b8c7d6e5f"; + private static final String STREAM_PREFIX = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX; + + @Test + void verifiesMembershipJoinThenUpstreamAdvancesWithoutRewritingItsHistoricalBytes() { + Fixture fixture = advancedFixture(false); + + Optional result = + RuntimeMembershipAuthorityEvidenceValidator.validate(fixture.snapshot()); + + assertThat(result).isPresent(); + assertThat(result.orElseThrow().canonicalJson()) + .isEqualTo(fixture.membershipEvent().canonicalJson()); + assertThat(result.orElseThrow().canonicalJson()) + .isEqualTo( + fixture.snapshot().sourceEvidence().stream() + .filter( + source -> + source + .outboxStreamKey() + .endsWith("membership/" + ACCOUNT_ID + "/" + TENANT_ID)) + .findFirst() + .orElseThrow() + .canonicalEventJson()); + assertThat(fixture.membershipEvent().authorityTuple().issuerAuthGeneration()).isEqualTo("1"); + assertThat(fixture.snapshot().authorityTuple().issuerAuthGeneration()) + .isEqualTo("9007199254740993"); + assertThat(fixture.membershipEvent().authorityTuple().accountAuthorityGeneration()) + .isEqualTo("1"); + assertThat(fixture.snapshot().authorityTuple().accountAuthorityGeneration()) + .isEqualTo("9007199254740999"); + } + + @Test + void acceptsFixedCountersAndTheDeclaredLogoutAllAccountEvent() { + Fixture fixture = fixedFixture(true); + + Optional result = + RuntimeMembershipAuthorityEvidenceValidator.validate(fixture.snapshot()); + assertThat(result).isPresent(); + assertThat(result.orElseThrow().canonicalJson()) + .isEqualTo(fixture.membershipEvent().canonicalJson()); + } + + @Test + void acceptsAnExplicitMissingNonadmittingMembershipWithPositiveBaselineValues() { + Snapshot missing = missingSnapshot(); + + assertThat(RuntimeMembershipAuthorityEvidenceValidator.validate(missing)).isEmpty(); + } + + @Test + void rejectsMissingStateThatClaimsAdmissionOrMembership() { + Snapshot baseline = missingSnapshot(); + Snapshot falselyAdmitting = + new Snapshot( + baseline.issuerId(), + baseline.accountId(), + baseline.tenantId(), + true, + "MISSING", + true, + baseline.membershipVersion(), + baseline.membershipAuthorityGeneration(), + List.of("player"), + baseline.authorityTuple(), + baseline.issuanceFence(), + baseline.checkpoints(), + baseline.sourceEvidence()); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(falselyAdmitting)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("zero checkpoint"); + } + + @Test + void rejectsCarrierMembershipValuesThatDifferFromTheImmutableEvent() { + Snapshot baseline = advancedFixture(false).snapshot(); + Snapshot mismatched = + new Snapshot( + baseline.issuerId(), + baseline.accountId(), + baseline.tenantId(), + baseline.membershipExists(), + "INACTIVE", + false, + baseline.membershipVersion(), + baseline.membershipAuthorityGeneration(), + baseline.roles(), + baseline.authorityTuple(), + baseline.issuanceFence(), + baseline.checkpoints(), + baseline.sourceEvidence()); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(mismatched)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("membershipLifecycleState"); + } + + @Test + void rejectsWellFormedMembershipEventsWhoseUpstreamGenerationOrFenceLeadsCurrent() { + Snapshot baseline = advancedFixture(false).snapshot(); + AuthorityTuple current = baseline.authorityTuple(); + String memberGeneration = current.membershipAuthorityGeneration().get(TENANT_ID); + String accountStream = STREAM_PREFIX + "account/" + ACCOUNT_ID; + String accountSequence = current.accountSecurityCutoff().orElseThrow().outboxSequence(); + + List aheadEvents = + List.of( + resealedMembership( + baseline, + tuple( + increment(current.issuerAuthGeneration()), + current.accountAuthorityGeneration(), + current.tenantAuthorityGeneration().get(TENANT_ID), + memberGeneration, + current.accountSecurityCutoff()), + baseline.issuanceFence()), + resealedMembership( + baseline, + tuple( + current.issuerAuthGeneration(), + increment(current.accountAuthorityGeneration()), + current.tenantAuthorityGeneration().get(TENANT_ID), + memberGeneration, + Optional.of( + new AccountSecurityCutoff( + increment(current.accountAuthorityGeneration()), + accountStream, + accountSequence))), + baseline.issuanceFence()), + resealedMembership( + baseline, + tuple( + current.issuerAuthGeneration(), + current.accountAuthorityGeneration(), + increment(current.tenantAuthorityGeneration().get(TENANT_ID)), + memberGeneration, + current.accountSecurityCutoff()), + baseline.issuanceFence()), + resealedMembership(baseline, current, increment(baseline.issuanceFence()))); + + for (MembershipEvent aheadEvent : aheadEvents) { + // Each case is a valid, freshly sealed event. The validator must reject its authority + // relationship to the current carrier, not its schema or digest. + assertThat(MembershipAuthorityEventV1Codec.verify(aheadEvent.canonicalJson()).eventDigest()) + .isEqualTo(aheadEvent.eventDigest()); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + withMembershipEvent(baseline, aheadEvent))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not be ahead"); + } + } + + @Test + void rejectsPositiveCheckpointsWithoutTheirSourceAndWrongSourceCheckpointSequences() { + Snapshot baseline = advancedFixture(false).snapshot(); + List missingIssuer = new ArrayList<>(baseline.sourceEvidence()); + missingIssuer.remove(sourceFor(baseline, "issuer/" + ISSUER_ID)); + + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + withSources(baseline, missingIssuer))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one source for each positive checkpoint"); + + String membershipStream = STREAM_PREFIX + "membership/" + ACCOUNT_ID + "/" + TENANT_ID; + Checkpoint original = + baseline.checkpoints().stream() + .filter(checkpoint -> checkpoint.outboxStreamKey().equals(membershipStream)) + .findFirst() + .orElseThrow(); + Snapshot wrongSequence = + withCheckpointSequence(baseline, membershipStream, increment(original.outboxSequence())); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(wrongSequence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sequence must equal its exact current checkpoint"); + } + + @Test + void rejectsExtraTenantAuthorityInTheCurrentCarrier() { + Snapshot baseline = advancedFixture(false).snapshot(); + AuthorityTuple current = baseline.authorityTuple(); + AuthorityTuple withExtraTenant = + new AuthorityTuple( + current.issuerAuthGeneration(), + current.accountAuthorityGeneration(), + Map.of( + TENANT_ID, + current.tenantAuthorityGeneration().get(TENANT_ID), + "00000001-0000-0000-0000-000000000000", + "1"), + current.membershipAuthorityGeneration(), + current.privateRealmGrantVersions(), + current.accountSecurityCutoff(), + current.tenantBillingCutoff()); + + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + withTuple(baseline, withExtraTenant))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenantAuthorityGeneration") + .hasMessageContaining("exactly the current tenantId key"); + } + + @Test + void validatesPositiveUpstreamEvidenceBeforeReturningAnEmptyMissingMembership() { + Snapshot baseline = advancedFixture(false).snapshot(); + Snapshot missing = missingMembershipWithUpstream(baseline, false, List.of()); + + assertThat(RuntimeMembershipAuthorityEvidenceValidator.validate(missing)).isEmpty(); + + Snapshot falselyAdmitting = missingMembershipWithUpstream(baseline, true, List.of("player")); + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(falselyAdmitting)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("zero checkpoint"); + } + + @Test + void acceptsEqualAndNonRegressingHistoricalAccountCutoffsButRejectsASequenceAhead() { + Snapshot baseline = advancedFixture(false).snapshot(); + AuthorityTuple current = baseline.authorityTuple(); + String memberGeneration = current.membershipAuthorityGeneration().get(TENANT_ID); + String currentAccountGeneration = current.accountAuthorityGeneration(); + AccountSecurityCutoff currentCutoff = current.accountSecurityCutoff().orElseThrow(); + + MembershipEvent equalCutoffEvent = + resealedMembership(baseline, current, baseline.issuanceFence()); + assertThat( + RuntimeMembershipAuthorityEvidenceValidator.validate( + withMembershipEvent(baseline, equalCutoffEvent))) + .isPresent(); + + String historicalGeneration = decrement(currentAccountGeneration); + String historicalSequence = decrement(currentCutoff.outboxSequence()); + AuthorityTuple historicalTuple = + tuple( + current.issuerAuthGeneration(), + historicalGeneration, + current.tenantAuthorityGeneration().get(TENANT_ID), + memberGeneration, + Optional.of( + new AccountSecurityCutoff( + historicalGeneration, currentCutoff.outboxStreamKey(), historicalSequence))); + MembershipEvent historicalEvent = + resealedMembership(baseline, historicalTuple, decrement(baseline.issuanceFence())); + assertThat( + RuntimeMembershipAuthorityEvidenceValidator.validate( + withMembershipEvent(baseline, historicalEvent))) + .isPresent(); + + AuthorityTuple regressedGenerationButAdvancedSequence = + tuple( + current.issuerAuthGeneration(), + historicalGeneration, + current.tenantAuthorityGeneration().get(TENANT_ID), + memberGeneration, + Optional.of( + new AccountSecurityCutoff( + historicalGeneration, + currentCutoff.outboxStreamKey(), + increment(currentCutoff.outboxSequence())))); + MembershipEvent aheadCutoffEvent = + resealedMembership( + baseline, regressedGenerationButAdvancedSequence, decrement(baseline.issuanceFence())); + assertThat( + MembershipAuthorityEventV1Codec.verify(aheadCutoffEvent.canonicalJson()).eventDigest()) + .isEqualTo(aheadCutoffEvent.eventDigest()); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + withMembershipEvent(baseline, aheadCutoffEvent))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("historical account cutoff sequence") + .hasMessageContaining("must not be ahead"); + } + + @Test + void rejectsChangedSourceEventBytesAndCarrierDigest() { + Snapshot baseline = advancedFixture(false).snapshot(); + SourceEvidence issuerSource = sourceFor(baseline, "issuer/" + ISSUER_ID); + List changedSources = new ArrayList<>(baseline.sourceEvidence()); + int issuerIndex = changedSources.indexOf(issuerSource); + changedSources.set( + issuerIndex, + new SourceEvidence( + issuerSource.outboxStreamKey(), + issuerSource.outboxSequence(), + issuerSource.eventId(), + issuerSource.eventDigest(), + issuerSource + .canonicalEventJson() + .replace( + "\"requestId\":\"issuer-event-", "\"requestId\":\"changed-issuer-event-"))); + Snapshot changedEvent = withSources(baseline, changedSources); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(changedEvent)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + + changedSources.set( + issuerIndex, + new SourceEvidence( + issuerSource.outboxStreamKey(), + issuerSource.outboxSequence(), + issuerSource.eventId(), + "sha256:" + "0".repeat(64), + issuerSource.canonicalEventJson())); + Snapshot changedCarrier = withSources(baseline, changedSources); + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(changedCarrier)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("eventDigest"); + } + + @Test + void rejectsACurrentAccountCutoffThatDoesNotBindTheSuppliedSource() { + Snapshot baseline = advancedFixture(false).snapshot(); + AuthorityTuple tuple = baseline.authorityTuple(); + AccountSecurityCutoff original = tuple.accountSecurityCutoff().orElseThrow(); + AuthorityTuple wrongCutoff = + tuple( + tuple.issuerAuthGeneration(), + tuple.accountAuthorityGeneration(), + tuple.tenantAuthorityGeneration().get(TENANT_ID), + tuple.membershipAuthorityGeneration().get(TENANT_ID), + Optional.of( + new AccountSecurityCutoff( + original.accountAuthorityGeneration(), + original.outboxStreamKey(), + increment(original.outboxSequence())))); + Snapshot mismatched = withTuple(baseline, wrongCutoff); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(mismatched)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("current account cutoff sequence"); + } + + @Test + void rejectsWrongScopeAndDuplicateSourceEvidence() { + Snapshot baseline = advancedFixture(false).snapshot(); + var wrongIssuerEvent = + AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + "issuer-wrong", + "issuer-wrong", + STREAM_PREFIX + "issuer/another-issuer", + "9007199254740992", + "another-issuer", + "9007199254740993", + "9007199254740993", + "ISSUER_SECURITY_CHANGE")); + SourceEvidence expectedIssuer = sourceFor(baseline, "issuer/" + ISSUER_ID); + List wrongScopeSources = new ArrayList<>(baseline.sourceEvidence()); + wrongScopeSources.set( + wrongScopeSources.indexOf(expectedIssuer), + new SourceEvidence( + expectedIssuer.outboxStreamKey(), + expectedIssuer.outboxSequence(), + wrongIssuerEvent.eventId(), + wrongIssuerEvent.eventDigest(), + wrongIssuerEvent.canonicalJson())); + Snapshot wrongScope = withSources(baseline, wrongScopeSources); + + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(wrongScope)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source event stream key"); + + List duplicateSources = new ArrayList<>(baseline.sourceEvidence()); + duplicateSources.add(0, duplicateSources.get(0)); + Snapshot duplicate = withSources(baseline, duplicateSources); + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(duplicate)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sourceEvidence"); + } + + @Test + void acceptsCurrentAccountRepositorySourceSchemaAndRejectsItsWrongSubject() { + Snapshot baseline = fixedFixture(false).snapshot(); + String stream = STREAM_PREFIX + "account/" + ACCOUNT_ID; + var account = + AccountAuthoritySourceEventV1Codec.sealAccount( + new AccountAuthoritySourceEventV1Codec.AccountPreimage( + "account-update", + "account-update", + stream, + "1", + ACCOUNT_ID, + "2", + "2", + "2", + "2", + List.of("GLOBAL_ROLE_CHANGED"), + new AccountAuthoritySourceEventV1Codec.AccountState( + true, List.of("PASSWORD"), "admin", "ACTIVE"))); + List sources = new ArrayList<>(baseline.sourceEvidence()); + sources.removeIf(source -> source.outboxStreamKey().equals(stream)); + sources.add( + new SourceEvidence( + stream, "1", account.eventId(), account.eventDigest(), account.canonicalJson())); + Snapshot current = withSources(baseline, sortedSources(sources)); + assertThat(RuntimeMembershipAuthorityEvidenceValidator.validate(current)).isPresent(); + + var different = + AccountAuthoritySourceEventV1Codec.sealAccount( + new AccountAuthoritySourceEventV1Codec.AccountPreimage( + "account-other", + "account-other", + STREAM_PREFIX + "account/" + TENANT_ID, + "1", + TENANT_ID, + "2", + "2", + "2", + "2", + List.of("GLOBAL_ROLE_CHANGED"), + new AccountAuthoritySourceEventV1Codec.AccountState( + true, List.of("PASSWORD"), "admin", "ACTIVE"))); + sources.removeIf(source -> source.outboxStreamKey().equals(stream)); + sources.add( + new SourceEvidence( + stream, "1", different.eventId(), different.eventDigest(), different.canonicalJson())); + assertThatThrownBy( + () -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + withSources(baseline, sortedSources(sources)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source event stream key"); + } + + @Test + void deniesTenantAdvancementWithoutItsSupportedOwnerSourceContract() { + Snapshot baseline = missingSnapshot(); + var checkpoints = + baseline.checkpoints().stream() + .map( + checkpoint -> + checkpoint.outboxStreamKey().equals(STREAM_PREFIX + "tenant/" + TENANT_ID) + ? new Checkpoint(checkpoint.outboxStreamKey(), "1") + : checkpoint) + .toList(); + var unsupported = + new Snapshot( + baseline.issuerId(), + baseline.accountId(), + baseline.tenantId(), + false, + "MISSING", + false, + baseline.membershipVersion(), + "1", + List.of(), + tuple("1", "1", "2", "1", Optional.empty()), + "1", + checkpoints, + List.of( + new SourceEvidence( + STREAM_PREFIX + "tenant/" + TENANT_ID, + "1", + "tenant-source", + "sha256:" + "1".repeat(64), + "{}"))); + assertThatThrownBy(() -> RuntimeMembershipAuthorityEvidenceValidator.validate(unsupported)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("advanced tenant authority"); + } + + private static Fixture advancedFixture(boolean logoutAll) { + String issuerGeneration = "9007199254740993"; + String accountGeneration = "9007199254740999"; + String tenantGeneration = "1"; + String membershipGeneration = "12"; + String issuerSequence = "9007199254740992"; + String accountSequence = "9007199254740998"; + String tenantSequence = "0"; + String membershipSequence = "9007199254740997"; + String membershipVersion = "9007199254740999"; + + AuthorityTuple joinTuple = tuple("1", "1", "1", membershipGeneration, Optional.empty()); + MembershipEvent joined = + membershipEvent( + membershipSequence, + membershipVersion, + membershipGeneration, + "9007199254740996", + joinTuple, + "ACTIVE", + List.of("player"), + true); + + var issuer = issuerEvent(issuerSequence, issuerGeneration); + AccountSourceFixture account = accountEvent(accountSequence, accountGeneration, logoutAll); + AuthorityTuple currentTuple = + tuple( + issuerGeneration, + accountGeneration, + tenantGeneration, + membershipGeneration, + Optional.of( + new AccountSecurityCutoff( + accountGeneration, STREAM_PREFIX + "account/" + ACCOUNT_ID, accountSequence))); + + List sources = + sortedSources(List.of(source(issuer), account.evidence(), source(joined))); + Snapshot snapshot = + snapshot( + true, + "ACTIVE", + true, + Map.of(TENANT_ID, membershipVersion), + membershipGeneration, + List.of("player"), + currentTuple, + "9007199254741000", + Map.of( + STREAM_PREFIX + "issuer/" + ISSUER_ID, issuerSequence, + STREAM_PREFIX + "account/" + ACCOUNT_ID, accountSequence, + STREAM_PREFIX + "tenant/" + TENANT_ID, tenantSequence, + STREAM_PREFIX + "membership/" + ACCOUNT_ID + "/" + TENANT_ID, membershipSequence), + sources); + return new Fixture(snapshot, joined); + } + + private static Fixture fixedFixture(boolean logoutAll) { + AuthorityTuple eventTuple = tuple("1", "1", "1", "2", Optional.empty()); + MembershipEvent member = + membershipEvent("1", "1", "2", "1", eventTuple, "ACTIVE", List.of("player"), true); + var issuer = issuerEvent("1", "2"); + AccountSourceFixture account = accountEvent("1", "2", logoutAll); + AuthorityTuple currentTuple = + tuple( + "2", + "2", + "1", + "2", + Optional.of( + new AccountSecurityCutoff("2", STREAM_PREFIX + "account/" + ACCOUNT_ID, "1"))); + Snapshot snapshot = + snapshot( + true, + "ACTIVE", + true, + Map.of(TENANT_ID, "1"), + "2", + List.of("player"), + currentTuple, + "2", + Map.of( + STREAM_PREFIX + "issuer/" + ISSUER_ID, "1", + STREAM_PREFIX + "account/" + ACCOUNT_ID, "1", + STREAM_PREFIX + "tenant/" + TENANT_ID, "0", + STREAM_PREFIX + "membership/" + ACCOUNT_ID + "/" + TENANT_ID, "1"), + sortedSources(List.of(source(issuer), account.evidence(), source(member)))); + return new Fixture(snapshot, member); + } + + private static Snapshot missingSnapshot() { + return snapshot( + false, + "MISSING", + false, + Map.of(TENANT_ID, "1"), + "1", + List.of(), + tuple("1", "1", "1", "1", Optional.empty()), + "1", + Map.of( + STREAM_PREFIX + "issuer/" + ISSUER_ID, "0", + STREAM_PREFIX + "account/" + ACCOUNT_ID, "0", + STREAM_PREFIX + "tenant/" + TENANT_ID, "0", + STREAM_PREFIX + "membership/" + ACCOUNT_ID + "/" + TENANT_ID, "0"), + List.of()); + } + + private static Snapshot missingMembershipWithUpstream( + Snapshot baseline, boolean admission, List roles) { + String membershipStream = + STREAM_PREFIX + "membership/" + baseline.accountId() + "/" + baseline.tenantId(); + List checkpoints = + baseline.checkpoints().stream() + .map( + checkpoint -> + checkpoint.outboxStreamKey().equals(membershipStream) + ? new Checkpoint(membershipStream, "0") + : checkpoint) + .toList(); + List upstreamSources = + baseline.sourceEvidence().stream() + .filter(source -> !source.outboxStreamKey().equals(membershipStream)) + .toList(); + return new Snapshot( + baseline.issuerId(), + baseline.accountId(), + baseline.tenantId(), + false, + "MISSING", + admission, + Map.of(baseline.tenantId(), "1"), + baseline.membershipAuthorityGeneration(), + roles, + baseline.authorityTuple(), + baseline.issuanceFence(), + checkpoints, + upstreamSources); + } + + private static Snapshot withCheckpointSequence( + Snapshot snapshot, String streamKey, String sequence) { + List checkpoints = + snapshot.checkpoints().stream() + .map( + checkpoint -> + checkpoint.outboxStreamKey().equals(streamKey) + ? new Checkpoint(streamKey, sequence) + : checkpoint) + .toList(); + return new Snapshot( + snapshot.issuerId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.membershipExists(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.roles(), + snapshot.authorityTuple(), + snapshot.issuanceFence(), + checkpoints, + snapshot.sourceEvidence()); + } + + private static Snapshot withMembershipEvent(Snapshot snapshot, MembershipEvent event) { + List sources = new ArrayList<>(snapshot.sourceEvidence()); + SourceEvidence original = + sourceFor(snapshot, "membership/" + snapshot.accountId() + "/" + snapshot.tenantId()); + sources.set(sources.indexOf(original), source(event)); + return withSources(snapshot, sortedSources(sources)); + } + + private static MembershipEvent resealedMembership( + Snapshot snapshot, AuthorityTuple tuple, String issuanceFence) { + SourceEvidence original = + sourceFor(snapshot, "membership/" + snapshot.accountId() + "/" + snapshot.tenantId()); + return membershipEvent( + original.outboxSequence(), + snapshot.membershipVersion().get(snapshot.tenantId()), + snapshot.membershipAuthorityGeneration(), + issuanceFence, + tuple, + snapshot.membershipLifecycleState(), + snapshot.roles(), + snapshot.gameplayAdmissionAllowed()); + } + + private static String increment(String decimal) { + return new BigInteger(decimal).add(BigInteger.ONE).toString(); + } + + private static String decrement(String decimal) { + return new BigInteger(decimal).subtract(BigInteger.ONE).toString(); + } + + private static Snapshot snapshot( + boolean membershipExists, + String lifecycle, + boolean admission, + Map membershipVersion, + String membershipGeneration, + List roles, + AuthorityTuple tuple, + String issuanceFence, + Map checkpointSequences, + List sources) { + List checkpoints = + checkpointSequences.entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(entry -> new Checkpoint(entry.getKey(), entry.getValue())) + .toList(); + return new Snapshot( + ISSUER_ID, + ACCOUNT_ID, + TENANT_ID, + membershipExists, + lifecycle, + admission, + membershipVersion, + membershipGeneration, + roles, + tuple, + issuanceFence, + checkpoints, + sources); + } + + private static AuthorityTuple tuple( + String issuerGeneration, + String accountGeneration, + String tenantGeneration, + String membershipGeneration, + Optional cutoff) { + return new AuthorityTuple( + issuerGeneration, + accountGeneration, + Map.of(TENANT_ID, tenantGeneration), + Map.of(TENANT_ID, membershipGeneration), + List.of(), + cutoff, + Optional.empty()); + } + + private static MembershipEvent membershipEvent( + String sequence, + String version, + String membershipGeneration, + String issuanceFence, + AuthorityTuple tuple, + String lifecycle, + List roles, + boolean admission) { + String scope = "membership/" + ACCOUNT_ID + "/" + TENANT_ID; + Map preimage = new HashMap<>(); + preimage.put("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION); + preimage.put("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE); + preimage.put("eventId", "membership-event-" + sequence); + preimage.put("requestId", "membership-request-" + sequence); + preimage.put("outboxStreamKey", STREAM_PREFIX + scope); + preimage.put("outboxSequence", sequence); + preimage.put("sourceScope", scope); + preimage.put("accountId", ACCOUNT_ID); + preimage.put("tenantId", TENANT_ID); + preimage.put("membershipExists", true); + preimage.put("membershipLifecycleState", lifecycle); + preimage.put("membershipVersion", Map.of(TENANT_ID, version)); + preimage.put("membershipAuthorityGeneration", membershipGeneration); + preimage.put("authorityTuple", tupleWire(tuple)); + preimage.put("issuanceFence", issuanceFence); + preimage.put("roles", roles); + preimage.put("gameplayAdmissionAllowed", admission); + preimage.put("callerBoundAuthorityInvalidated", true); + return MembershipAuthorityEventV1Codec.seal(preimage); + } + + private static Map tupleWire(AuthorityTuple tuple) { + Map wire = new HashMap<>(); + wire.put("issuerAuthGeneration", tuple.issuerAuthGeneration()); + wire.put("accountAuthorityGeneration", tuple.accountAuthorityGeneration()); + wire.put("tenantAuthorityGeneration", tuple.tenantAuthorityGeneration()); + wire.put("membershipAuthorityGeneration", tuple.membershipAuthorityGeneration()); + wire.put("privateRealmGrantVersions", tuple.privateRealmGrantVersions()); + tuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> + wire.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); + return wire; + } + + private static AccountAuthoritySourceEventV1Codec.IssuerEvent issuerEvent( + String sequence, String generation) { + return AccountAuthoritySourceEventV1Codec.sealIssuer( + new AccountAuthoritySourceEventV1Codec.IssuerPreimage( + "issuer-event-" + sequence, + "issuer-event-" + sequence, + STREAM_PREFIX + "issuer/" + ISSUER_ID, + sequence, + ISSUER_ID, + generation, + generation, + "ISSUER_SECURITY_CHANGE")); + } + + private static AccountSourceFixture accountEvent( + String sequence, String generation, boolean logoutAll) { + String stream = STREAM_PREFIX + "account/" + ACCOUNT_ID; + String requestId = + logoutAll ? "018f8f0a-3c8d-7b35-ad26-7b0c9d8e6f4a" : "reset-request-" + sequence; + Map preimage = new HashMap<>(); + preimage.put( + "schemaVersion", + logoutAll + ? AccountLogoutAllAuthorityEventV1Codec.SCHEMA_VERSION + : PasswordResetAuthorityEventV1Codec.SCHEMA_VERSION); + preimage.put( + "eventType", + logoutAll + ? AccountLogoutAllAuthorityEventV1Codec.EVENT_TYPE + : PasswordResetAuthorityEventV1Codec.EVENT_TYPE); + preimage.put( + "eventId", + logoutAll + ? AccountLogoutAllAuthorityEventV1Codec.EVENT_ID_PREFIX + requestId + : "password-reset-event-" + sequence); + preimage.put("requestId", requestId); + preimage.put("accountId", ACCOUNT_ID); + preimage.put("sourceScope", "account/" + ACCOUNT_ID); + preimage.put("outboxStreamKey", stream); + preimage.put("outboxSequence", sequence); + preimage.put("accountAuthorityGeneration", generation); + preimage.put("sourceVersion", "2"); + preimage.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", generation, + "outboxStreamKey", stream, + "outboxSequence", sequence)); + String canonical; + String eventId; + String digest; + if (logoutAll) { + var event = AccountLogoutAllAuthorityEventV1Codec.seal(preimage); + canonical = event.canonicalJson(); + eventId = event.eventId(); + digest = event.eventDigest(); + } else { + var event = PasswordResetAuthorityEventV1Codec.seal(preimage); + canonical = event.canonicalJson(); + eventId = event.eventId(); + digest = event.eventDigest(); + } + return new AccountSourceFixture( + new SourceEvidence(stream, sequence, eventId, digest, canonical)); + } + + private static SourceEvidence source(AccountAuthoritySourceEventV1Codec.IssuerEvent event) { + return new SourceEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.canonicalJson()); + } + + private static SourceEvidence source(MembershipEvent event) { + return new SourceEvidence( + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest(), + event.canonicalJson()); + } + + private static List sortedSources(List sources) { + return sources.stream().sorted(Comparator.comparing(SourceEvidence::outboxStreamKey)).toList(); + } + + private static SourceEvidence sourceFor(Snapshot snapshot, String scope) { + String expected = STREAM_PREFIX + scope; + return snapshot.sourceEvidence().stream() + .filter(source -> source.outboxStreamKey().equals(expected)) + .findFirst() + .orElseThrow(); + } + + private static Snapshot withSources(Snapshot snapshot, List sources) { + return new Snapshot( + snapshot.issuerId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.membershipExists(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.roles(), + snapshot.authorityTuple(), + snapshot.issuanceFence(), + snapshot.checkpoints(), + sources); + } + + private static Snapshot withTuple(Snapshot snapshot, AuthorityTuple tuple) { + return new Snapshot( + snapshot.issuerId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.membershipExists(), + snapshot.membershipLifecycleState(), + snapshot.gameplayAdmissionAllowed(), + snapshot.membershipVersion(), + snapshot.membershipAuthorityGeneration(), + snapshot.roles(), + tuple, + snapshot.issuanceFence(), + snapshot.checkpoints(), + snapshot.sourceEvidence()); + } + + private record AccountSourceFixture(SourceEvidence evidence) {} + + private record Fixture(Snapshot snapshot, MembershipEvent membershipEvent) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java new file mode 100644 index 0000000000..91ddb4f2b7 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java @@ -0,0 +1,82 @@ +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 FreshTenantCreatorDigestTest { + private static final UUID INITIATOR_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID AUTHORIZATION_OPERATION_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String AUTHORIZATION_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void exactTupleProducesStableCanonicalSha256Digest() { + FreshTenantCreationEvidence source = freshTenantEvidence(); + + String first = + FreshTenantCreatorDigest.evidenceDigest( + 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST); + String retry = + FreshTenantCreatorDigest.evidenceDigest( + 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST); + + assertThat(first).matches("sha256:[0-9a-f]{64}").isEqualTo(retry); + } + + @Test + void rejectsInvalidSchemaNilIdsAndNoncanonicalAccountDigest() { + FreshTenantCreationEvidence source = freshTenantEvidence(); + + assertThatThrownBy( + () -> + FreshTenantCreatorDigest.evidenceDigest( + 2, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + FreshTenantCreatorDigest.evidenceDigest( + 1, source, new UUID(0L, 0L), AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + FreshTenantCreatorDigest.evidenceDigest( + 1, source, INITIATOR_ID, new UUID(0L, 0L), AUTHORIZATION_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + FreshTenantCreatorDigest.evidenceDigest( + 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, "bad")) + .isInstanceOf(IllegalArgumentException.class); + } + + private static FreshTenantCreationEvidence freshTenantEvidence() { + UUID requestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID operationId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID tenantId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + String sourceKey = "new-game-owner-key"; + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", requestId, sourceKey, "World", null); + return new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + operationId, + requestDigest, + tenantId, + 42L, + sourceKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", + requestId, + operationId, + requestDigest, + tenantId, + 42L, + sourceKey, + "NEW_GAME_ROW")); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java new file mode 100644 index 0000000000..d72cfac8dd --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java @@ -0,0 +1,153 @@ +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 FreshTenantCreatorEvidenceTest { + private static final UUID INITIATOR_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID AUTHORIZATION_OPERATION_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final String AUTHORIZATION_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void acceptsExactCreatorQualificationWithoutChangingOriginalCreationEvidence() { + FreshTenantCreationEvidence source = freshTenantEvidence(); + String creatorDigest = + FreshTenantCreatorDigest.evidenceDigest( + 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST); + + FreshTenantCreatorEvidence qualification = + new FreshTenantCreatorEvidence( + 1, + source, + INITIATOR_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST, + creatorDigest); + + assertThat(qualification.creationEvidence()).isSameAs(source); + assertThat(qualification.initiatingAccountId()).isEqualTo(INITIATOR_ID); + assertThat(qualification.accountAuthorizationOperationId()) + .isEqualTo(AUTHORIZATION_OPERATION_ID); + assertThat(qualification.accountAuthorizationDigest()).isEqualTo(AUTHORIZATION_DIGEST); + assertThat(qualification.evidenceDigest()).isEqualTo(creatorDigest); + } + + @Test + void rejectsUnsupportedVersionNilIdentitiesMalformedAuthorizationDigestAndChangedBinding() { + FreshTenantCreationEvidence source = freshTenantEvidence(); + String digest = + FreshTenantCreatorDigest.evidenceDigest( + 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST); + + assertInvalid( + 2, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST, digest); + assertInvalid( + 1, source, new UUID(0L, 0L), AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST, digest); + assertInvalid(1, source, INITIATOR_ID, new UUID(0L, 0L), AUTHORIZATION_DIGEST, digest); + assertInvalid( + 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, "SHA256:" + "a".repeat(64), digest); + assertInvalid( + 1, + source, + INITIATOR_ID, + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST, + "sha256:" + "b".repeat(64)); + } + + @Test + void creatorDigestBindsEveryCreationReceiptAndAuthorizationIdentity() { + FreshTenantCreationEvidence source = freshTenantEvidence(); + String original = + FreshTenantCreatorDigest.evidenceDigest( + 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST); + + assertThat( + FreshTenantCreatorDigest.evidenceDigest( + 1, + source, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + AUTHORIZATION_OPERATION_ID, + AUTHORIZATION_DIGEST)) + .isNotEqualTo(original); + assertThat( + FreshTenantCreatorDigest.evidenceDigest( + 1, + source, + INITIATOR_ID, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + AUTHORIZATION_DIGEST)) + .isNotEqualTo(original); + assertThat( + FreshTenantCreatorDigest.evidenceDigest( + 1, source, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, "sha256:" + "b".repeat(64))) + .isNotEqualTo(original); + + FreshTenantCreationEvidence changedSource = + freshTenantEvidence( + UUID.fromString("88888888-8888-4888-8888-888888888888"), + source.sourceGameRowId() + 1, + source.sourceGameTenantKey()); + assertThat( + FreshTenantCreatorDigest.evidenceDigest( + 1, changedSource, INITIATOR_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST)) + .isNotEqualTo(original); + } + + private static void assertInvalid( + int schemaVersion, + FreshTenantCreationEvidence source, + UUID initiatingAccountId, + UUID authorizationOperationId, + String authorizationDigest, + String evidenceDigest) { + assertThatThrownBy( + () -> + new FreshTenantCreatorEvidence( + schemaVersion, + source, + initiatingAccountId, + authorizationOperationId, + authorizationDigest, + evidenceDigest)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static FreshTenantCreationEvidence freshTenantEvidence() { + return freshTenantEvidence( + UUID.fromString("33333333-3333-4333-8333-333333333333"), 42L, "new-game-owner-key"); + } + + private static FreshTenantCreationEvidence freshTenantEvidence( + UUID canonicalTenantId, long sourceRowId, String sourceKey) { + UUID requestId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID operationId = UUID.fromString("22222222-2222-4222-8222-222222222222"); + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", requestId, sourceKey, "World", null); + String sourceDigest = + GameTenantCreationDigest.evidenceDigest( + "prod", + requestId, + operationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW"); + return new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + operationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW", + sourceDigest); + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql b/services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql index c2c62ae98b..aee294ac4a 100644 --- a/services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql +++ b/services/game-design-service/src/main/resources/db/migration/V54__immutable_command_source.sql @@ -291,7 +291,7 @@ BEGIN OR (SELECT count(*) FROM jsonb_object_keys(revision_payload)) <> 4 OR revision_payload->>'operation' IS DISTINCT FROM NEW.operation_kind OR (SELECT count(*) FROM jsonb_object_keys(stored_operation)) - <> CASE WHEN NEW.operation_kind = 'UPSERT' THEN 6 ELSE 5 END + <> (CASE WHEN NEW.operation_kind = 'UPSERT' THEN 6 ELSE 5 END) OR stored_operation->>'revisionOrder' IS DISTINCT FROM NEW.revision_order::TEXT OR stored_operation->>'revisionId' IS DISTINCT FROM NEW.revision_id::TEXT OR stored_operation->>'commitId' IS DISTINCT FROM NEW.commit_id::TEXT diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java index 39566abf51..8b2c0d41fc 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java @@ -3,9 +3,10 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; -import java.util.List; import java.util.Optional; +import java.util.Set; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.GameplaySessionAttestationException; @@ -21,7 +22,6 @@ import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto.RoomExitSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RuntimeRoomDto; -import net.firedevops.firemud.worldmanagement.dto.WorldDesignMutationRequestDto; import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; import net.firedevops.firemud.worldmanagement.service.PingService; import net.firedevops.firemud.worldmanagement.service.RoomService; @@ -37,10 +37,6 @@ import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationResponse; import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse; -import net.firedevops.firemud.worldmanagement.v1.GeneratedRoomDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.GeneratedRoomExitDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.GeneratedWorldEntitySpawnBindingDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestRequest; import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestResponse; import net.firedevops.firemud.worldmanagement.v1.GetRoomRequest; @@ -54,9 +50,6 @@ import net.firedevops.firemud.worldmanagement.v1.PingResponse; import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse; -import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomExitSnapshot; import net.firedevops.firemud.worldmanagement.v1.RoomSnapshot; import net.firedevops.firemud.worldmanagement.v1.RuntimeRoom; @@ -65,13 +58,9 @@ import net.firedevops.firemud.worldmanagement.v1.UpgradeValidationResult; import net.firedevops.firemud.worldmanagement.v1.ValidateWorldUpgradeMappingsRequest; import net.firedevops.firemud.worldmanagement.v1.ValidateWorldUpgradeMappingsResponse; -import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; -import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; -import net.firedevops.firemud.worldmanagement.v1.WorldGenerationSubtreeDesignMutation; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; -import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -85,6 +74,13 @@ public class WorldManagementGrpcService extends WorldManagementServiceGrpc.WorldManagementServiceImplBase { private static final Logger logger = LoggerFactory.getLogger(WorldManagementGrpcService.class); + private static final Set GAME_SESSION_LIFECYCLE_METHODS = + Set.of( + WorldManagementServiceGrpc.getPrepareWorldInstanceMethod().getFullMethodName(), + WorldManagementServiceGrpc.getActivatePreparedWorldInstanceMethod().getFullMethodName(), + WorldManagementServiceGrpc.getFailPreparedWorldInstanceMethod().getFullMethodName(), + WorldManagementServiceGrpc.getTerminateWorldInstanceMethod().getFullMethodName()); + private static final String GAME_SESSION_SERVICE = "game-session-service"; private final PingService pingService; private final RoomService roomService; private final WorldInstanceActivationService worldInstanceActivationService; @@ -186,6 +182,8 @@ public void prepareWorldInstance( StreamObserver responseObserver) { PrepareWorldInstanceResponse.Builder builder = PrepareWorldInstanceResponse.newBuilder(); try { + requireGameSessionLifecycleCaller( + WorldManagementServiceGrpc.getPrepareWorldInstanceMethod().getFullMethodName()); var snapshot = worldInstanceActivationService.prepareWorldInstance( new PreparedWorldInstanceRequest( @@ -206,6 +204,10 @@ public void prepareWorldInstance( request.getVersionStateEpoch(), request.getRemapSetId().isBlank() ? null : request.getRemapSetId())); builder.setWorldInstance(toProto(snapshot)); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, logger, "PrepareWorldInstance", "PERMISSION_DENIED", ex.getMessage())); } catch (IllegalArgumentException ex) { builder.setError( GrpcAppErrors.error( @@ -225,6 +227,8 @@ public void activatePreparedWorldInstance( ActivatePreparedWorldInstanceResponse.Builder builder = ActivatePreparedWorldInstanceResponse.newBuilder(); try { + requireGameSessionLifecycleCaller( + WorldManagementServiceGrpc.getActivatePreparedWorldInstanceMethod().getFullMethodName()); var snapshot = worldInstanceActivationService.activatePreparedWorldInstance( RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), @@ -232,6 +236,14 @@ public void activatePreparedWorldInstance( request.getGameInstanceId(), "gameInstanceId"), request.getExpectedLifecycleEpoch()); builder.setWorldInstance(toProto(snapshot)); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ActivatePreparedWorldInstance", + "PERMISSION_DENIED", + ex.getMessage())); } catch (IllegalArgumentException ex) { builder.setError( GrpcAppErrors.error( @@ -256,6 +268,8 @@ public void failPreparedWorldInstance( FailPreparedWorldInstanceResponse.Builder builder = FailPreparedWorldInstanceResponse.newBuilder(); try { + requireGameSessionLifecycleCaller( + WorldManagementServiceGrpc.getFailPreparedWorldInstanceMethod().getFullMethodName()); var snapshot = worldInstanceActivationService.failPreparedWorldInstance( RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), @@ -264,6 +278,14 @@ public void failPreparedWorldInstance( request.getExpectedLifecycleEpoch(), request.getReason()); builder.setWorldInstance(toProto(snapshot)); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "FailPreparedWorldInstance", + "PERMISSION_DENIED", + ex.getMessage())); } catch (IllegalArgumentException ex) { builder.setError( GrpcAppErrors.error( @@ -370,6 +392,8 @@ public void terminateWorldInstance( StreamObserver responseObserver) { TerminateWorldInstanceResponse.Builder builder = TerminateWorldInstanceResponse.newBuilder(); try { + requireGameSessionLifecycleCaller( + WorldManagementServiceGrpc.getTerminateWorldInstanceMethod().getFullMethodName()); builder.setWorldInstance( toProto( worldInstanceActivationService.terminateWorldInstance( @@ -379,6 +403,14 @@ public void terminateWorldInstance( request.getExpectedLifecycleEpoch(), request.getTerminationRequestId(), request.getReason()))); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "TerminateWorldInstance", + "PERMISSION_DENIED", + ex.getMessage())); } catch (IllegalArgumentException ex) { builder.setError( GrpcAppErrors.error( @@ -474,6 +506,22 @@ private void requirePublicationRead() { PublicationReadGuard.WORLD_MANAGEMENT_DIGEST_METHOD); } + private void requireGameSessionLifecycleCaller(String fullMethodName) { + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + String trustedNamespace = + publicationReadGuard == null ? null : publicationReadGuard.trustedNamespace(); + if (!GAME_SESSION_LIFECYCLE_METHODS.contains(fullMethodName) + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || peerIdentity == null + || !peerIdentity.isService(GAME_SESSION_SERVICE) + || !peerIdentity.isInNamespace(trustedNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "World lifecycle RPC requires only the authenticated same-namespace Game Session " + + "workload peer identity"); + } + } + @Override @Timed(value = "worldGrpc.validateWorldUpgradeMappings") public void validateWorldUpgradeMappings( @@ -523,33 +571,13 @@ public void applyWorldDesignMutation( StreamObserver responseObserver) { ApplyWorldDesignMutationResponse.Builder builder = ApplyWorldDesignMutationResponse.newBuilder(); - try { - var result = worldDesignMutationService.applyMutation(toDto(request)); - builder - .setResult(toProtoMutationResult(result.result())) - .setTenantId(Long.toString(result.tenantId())) - .setVersionId(Long.toString(result.versionId())) - .setAggregateId(Long.toString(result.aggregateId())) - .setDraftRevisionEpoch(result.draftRevisionEpoch()); - if (result.draftScopeRevisionEpoch() != null) { - builder.setDraftScopeRevisionEpoch(result.draftScopeRevisionEpoch()); - } - } catch (NumberFormatException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, logger, "ApplyWorldDesignMutation", "INVALID_ARGUMENT", "invalid id")); - } catch (IllegalArgumentException ex) { - builder.setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ApplyWorldDesignMutation", - errorCodeFor(ex), - errorMessageFor(ex))); - } catch (Exception ex) { - builder.setError( - GrpcAppErrors.internal(meterRegistry, logger, "ApplyWorldDesignMutation", ex)); - } + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "ApplyWorldDesignMutation", + "FAILED_PRECONDITION", + "Canonical World Draft writes are unavailable until current Account commit authorization is verified.")); responseObserver.onNext(builder.build()); responseObserver.onCompleted(); } @@ -880,163 +908,6 @@ private String errorMessageFor(IllegalArgumentException ex) { return message; } - private WorldDesignMutationRequestDto toDto(ApplyWorldDesignMutationRequest request) { - return new WorldDesignMutationRequestDto( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getVersionId(), "versionId"), - request.getCommitId(), - request.getRevisionId(), - operationName(request), - aggregateTypeName(request), - request.getAggregateId(), - request.getExpectedDraftRevisionEpoch(), - request.getScopeType() - == net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType - .WORLD_DESIGN_SCOPE_TYPE_UNSPECIFIED - ? "" - : request.getScopeType().name().replace("WORLD_DESIGN_SCOPE_TYPE_", ""), - request.getScopeId(), - request.getExpectedDraftScopeRevisionEpoch(), - request.getScopeMutationPolicy() - == net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy - .WORLD_DESIGN_SCOPE_MUTATION_POLICY_UNSPECIFIED - ? "" - : request - .getScopeMutationPolicy() - .name() - .replace("WORLD_DESIGN_SCOPE_MUTATION_POLICY_", ""), - request.hasRegion() ? toDto(request.getRegion()) : null, - request.hasZone() ? toDto(request.getZone()) : null, - request.hasRoom() ? toDto(request.getRoom()) : null, - request.hasRoomExit() ? toDto(request.getRoomExit()) : null, - request.hasGenerationRule() ? toDto(request.getGenerationRule()) : null, - request.hasWorldEntitySpawnBinding() ? toDto(request.getWorldEntitySpawnBinding()) : null, - request.hasWorldGenerationSubtree() ? toDto(request.getWorldGenerationSubtree()) : null); - } - - private String operationName(ApplyWorldDesignMutationRequest request) { - return switch (request.getOperation()) { - case WORLD_DESIGN_MUTATION_OPERATION_UPSERT -> "UPSERT"; - case WORLD_DESIGN_MUTATION_OPERATION_DELETE -> "DELETE"; - default -> ""; - }; - } - - private String aggregateTypeName(ApplyWorldDesignMutationRequest request) { - return switch (request.getAggregateType()) { - case WORLD_DESIGN_AGGREGATE_TYPE_REGION -> "REGION"; - case WORLD_DESIGN_AGGREGATE_TYPE_ZONE -> "ZONE"; - case WORLD_DESIGN_AGGREGATE_TYPE_ROOM -> "ROOM"; - case WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT -> "ROOM_EXIT"; - case WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE -> "GENERATION_RULE"; - case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING -> "WORLD_ENTITY_SPAWN_BINDING"; - case WORLD_DESIGN_AGGREGATE_TYPE_WORLD_GENERATION_SUBTREE -> "WORLD_GENERATION_SUBTREE"; - default -> ""; - }; - } - - private WorldDesignMutationRequestDto.RegionMutationDto toDto(RegionDesignMutation mutation) { - return new WorldDesignMutationRequestDto.RegionMutationDto( - mutation.getName(), - mutation.getWeather(), - mutation.getShardId(), - mutation.getGenerationSeed(), - mutation.getGeneratorType(), - mutation.getGeneratorParams(), - mutation.getSpacingMultiplier()); - } - - private WorldDesignMutationRequestDto.ZoneMutationDto toDto(ZoneDesignMutation mutation) { - return new WorldDesignMutationRequestDto.ZoneMutationDto( - mutation.getName(), mutation.getRegionId()); - } - - private WorldDesignMutationRequestDto.RoomMutationDto toDto(RoomDesignMutation mutation) { - return new WorldDesignMutationRequestDto.RoomMutationDto( - mutation.getName(), - mutation.getDescription(), - mutation.getZoneId(), - mutation.getNameLocalizedVariantsJson(), - mutation.getDescriptionLocalizedVariantsJson()); - } - - private WorldDesignMutationRequestDto.RoomExitMutationDto toDto(RoomExitDesignMutation mutation) { - return new WorldDesignMutationRequestDto.RoomExitMutationDto( - mutation.getFromRoomId(), - mutation.getToRoomId(), - mutation.getDirection(), - mutation.getCost()); - } - - private WorldDesignMutationRequestDto.GenerationRuleMutationDto toDto( - GenerationRuleDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GenerationRuleMutationDto( - mutation.getName(), mutation.getValue()); - } - - private WorldDesignMutationRequestDto.WorldEntitySpawnBindingMutationDto toDto( - WorldEntitySpawnBindingDesignMutation mutation) { - return new WorldDesignMutationRequestDto.WorldEntitySpawnBindingMutationDto( - mutation.getRoomId(), - mutation.getEntityTemplateType().name().replace("ENTITY_TEMPLATE_REFERENCE_TYPE_", ""), - mutation.getEntityTemplateId(), - mutation.getSpawnCount(), - mutation.getRespawnDelaySeconds()); - } - - private WorldDesignMutationRequestDto.WorldGenerationSubtreeMutationDto toDto( - WorldGenerationSubtreeDesignMutation mutation) { - List generationRules = - mutation.getGenerationRulesList().stream().map(this::toDto).toList(); - List rooms = - mutation.getRoomsList().stream().map(this::toDto).toList(); - List roomExits = - mutation.getRoomExitsList().stream().map(this::toDto).toList(); - List spawnBindings = - mutation.getWorldEntitySpawnBindingsList().stream().map(this::toDto).toList(); - return new WorldDesignMutationRequestDto.WorldGenerationSubtreeMutationDto( - generationRules, rooms, roomExits, spawnBindings); - } - - private WorldDesignMutationRequestDto.GeneratedRoomMutationDto toDto( - GeneratedRoomDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GeneratedRoomMutationDto( - mutation.getClientRef(), - mutation.getName(), - mutation.getDescription(), - mutation.getZoneId(), - mutation.getNameLocalizedVariantsJson(), - mutation.getDescriptionLocalizedVariantsJson()); - } - - private WorldDesignMutationRequestDto.GeneratedRoomExitMutationDto toDto( - GeneratedRoomExitDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GeneratedRoomExitMutationDto( - mutation.getFromRoomRef(), - mutation.getToRoomRef(), - mutation.getDirection(), - mutation.getCost()); - } - - private WorldDesignMutationRequestDto.GeneratedWorldEntitySpawnBindingMutationDto toDto( - GeneratedWorldEntitySpawnBindingDesignMutation mutation) { - return new WorldDesignMutationRequestDto.GeneratedWorldEntitySpawnBindingMutationDto( - mutation.getRoomRef(), - mutation.getEntityTemplateType().name().replace("ENTITY_TEMPLATE_REFERENCE_TYPE_", ""), - mutation.getEntityTemplateId(), - mutation.getSpawnCount(), - mutation.getRespawnDelaySeconds()); - } - - private WorldDesignMutationResult toProtoMutationResult(String result) { - return switch (result) { - case "APPLIED" -> WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_APPLIED; - case "NO_OP_ALREADY_APPLIED" -> - WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_NO_OP_ALREADY_APPLIED; - default -> WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED; - }; - } - private UpgradeValidationResult toUpgradeValidationResult(String result) { return switch (result) { case "COMPATIBLE" -> UpgradeValidationResult.UPGRADE_VALIDATION_RESULT_COMPATIBLE; diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java index efe6e396fb..83b619f257 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java @@ -1,9 +1,11 @@ package net.firedevops.firemud.worldmanagement.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import io.grpc.Context; import io.grpc.stub.StreamObserver; @@ -23,7 +25,6 @@ import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldDto; import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RuntimeRoomDto; -import net.firedevops.firemud.worldmanagement.dto.WorldDesignMutationResultDto; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; import net.firedevops.firemud.worldmanagement.service.PingService; @@ -38,6 +39,8 @@ import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationRequest; import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationResponse; +import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestRequest; import net.firedevops.firemud.worldmanagement.v1.GetDraftDesignDigestResponse; import net.firedevops.firemud.worldmanagement.v1.GetRoomSnapshotRequest; @@ -47,12 +50,15 @@ import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.ValidateWorldUpgradeMappingsRequest; import net.firedevops.firemud.worldmanagement.v1.ValidateWorldUpgradeMappingsResponse; import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -79,14 +85,63 @@ private static void runAsGameDesign(Runnable action) { } private static GrpcPeerIdentity peer(String service) { + return peer(TEST_NAMESPACE, service); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { return new GrpcPeerIdentity( - "spiffe://firemud/ns/" + TEST_NAMESPACE + "/sa/" + service, TEST_NAMESPACE, service); + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); } private static void runWithPeer(GrpcPeerIdentity peer, Runnable action) { Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(action); } + private static PrepareWorldInstanceResponse invokePrepareWorldInstance( + WorldManagementGrpcService service, PrepareWorldInstanceRequest request) { + AtomicReference ref = new AtomicReference<>(); + service.prepareWorldInstance(request, responseObserver(ref)); + return ref.get(); + } + + private static ActivatePreparedWorldInstanceResponse invokeActivatePreparedWorldInstance( + WorldManagementGrpcService service, ActivatePreparedWorldInstanceRequest request) { + AtomicReference ref = new AtomicReference<>(); + service.activatePreparedWorldInstance(request, responseObserver(ref)); + return ref.get(); + } + + private static FailPreparedWorldInstanceResponse invokeFailPreparedWorldInstance( + WorldManagementGrpcService service, FailPreparedWorldInstanceRequest request) { + AtomicReference ref = new AtomicReference<>(); + service.failPreparedWorldInstance(request, responseObserver(ref)); + return ref.get(); + } + + private static TerminateWorldInstanceResponse invokeTerminateWorldInstance( + WorldManagementGrpcService service, TerminateWorldInstanceRequest request) { + AtomicReference ref = new AtomicReference<>(); + service.terminateWorldInstance(request, responseObserver(ref)); + return ref.get(); + } + + private static StreamObserver responseObserver(AtomicReference ref) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + throw new AssertionError("Lifecycle RPC failed", t); + } + + @Override + public void onCompleted() {} + }; + } + private static GetDraftDesignDigestResponse invokeDigest( WorldManagementGrpcService service, GetDraftDesignDigestRequest request) { AtomicReference ref = new AtomicReference<>(); @@ -587,112 +642,127 @@ void getDraftDesignDigestRejectsOwnerTenantMismatch() { } @Test - void applyWorldDesignMutationReturnsTypedResult() { - PingService pingService = Mockito.mock(PingService.class); - RoomService roomService = Mockito.mock(RoomService.class); - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); + void applyWorldDesignMutationFailsClosedForEveryCallerContext() { WorldDesignMutationService mutationService = Mockito.mock(WorldDesignMutationService.class); - MeterRegistry meterRegistry = new SimpleMeterRegistry(); - Mockito.when(mutationService.applyMutation(Mockito.any())) - .thenReturn(new WorldDesignMutationResultDto("APPLIED", 1L, 7L, 44L, 1L, null)); + WorldManagementGrpcService service = worldManagementService(mutationService); + ApplyWorldDesignMutationRequest request = worldDesignMutationRequest("1", "7", "44"); + + SessionContext.clear(); + assertMutationUnavailable(invokeWorldDesignMutation(service, request)); + SessionContext.setContext( "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); - WorldManagementGrpcService service = - new WorldManagementGrpcService( - pingService, - roomService, - Mockito.mock(WorldInstanceActivationService.class), - digestService, - mutationService, - Mockito.mock(WorldUpgradeValidationService.class), - Mockito.mock(GameplaySessionAttestationService.class), - meterRegistry, - new ObjectMapper(), - (PublicationReadGuard) null); + assertMutationUnavailable(invokeWorldDesignMutation(service, request)); + + for (String caller : + List.of( + "account-service", + "game-session-service", + "game-design-service", + "tcp-proxy-service")) { + SessionContext.setContext("test-account", List.of(), Map.of(), true, caller, "test-instance"); + runWithPeer( + peer(caller), + () -> assertMutationUnavailable(invokeWorldDesignMutation(service, request))); + } - AtomicReference ref = new AtomicReference<>(); - service.applyWorldDesignMutation( - ApplyWorldDesignMutationRequest.newBuilder() - .setTenantId("1") - .setVersionId("7") - .setCommitId("commit-1") - .setRevisionId("revision-1") - .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) - .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) - .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) - .setScopeId("44") - .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) - .build(), - new StreamObserver<>() { - @Override - public void onNext(ApplyWorldDesignMutationResponse value) { - ref.set(value); - } + SessionContext.clear(); + Mockito.verifyNoInteractions(mutationService); + } - @Override - public void onError(Throwable t) {} + @Test + void applyWorldDesignMutationFailsClosedBeforeParsingTargetIds() { + WorldDesignMutationService mutationService = Mockito.mock(WorldDesignMutationService.class); + WorldManagementGrpcService service = worldManagementService(mutationService); + SessionContext.clear(); + + String[][] targets = { + {"1", "7", "44"}, + { + "123e4567-e89b-12d3-a456-426614174000", + "123e4567-e89b-12d3-a456-426614174001", + "123e4567-e89b-12d3-a456-426614174002" + }, + {"tenant-x", "version-y", "scope-z"}, + {"", "0", "not-a-number"} + }; + for (String[] target : targets) { + assertMutationUnavailable( + invokeWorldDesignMutation( + service, worldDesignMutationRequest(target[0], target[1], target[2]))); + } - @Override - public void onCompleted() {} - }); + SessionContext.clear(); + Mockito.verifyNoInteractions(mutationService); + } - assertEquals( - WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_APPLIED, ref.get().getResult()); - assertEquals("44", ref.get().getAggregateId()); - assertEquals(1L, ref.get().getDraftRevisionEpoch()); + private static WorldManagementGrpcService worldManagementService( + WorldDesignMutationService mutationService) { + return new WorldManagementGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(RoomService.class), + Mockito.mock(WorldInstanceActivationService.class), + Mockito.mock(WorldDraftDesignDigestService.class), + mutationService, + Mockito.mock(WorldUpgradeValidationService.class), + Mockito.mock(GameplaySessionAttestationService.class), + new SimpleMeterRegistry(), + new ObjectMapper(), + (PublicationReadGuard) null); } - @Test - void applyWorldDesignMutationRejectsZeroVersionIdBeforeMutation() { - PingService pingService = Mockito.mock(PingService.class); - RoomService roomService = Mockito.mock(RoomService.class); - WorldDraftDesignDigestService digestService = Mockito.mock(WorldDraftDesignDigestService.class); - WorldDesignMutationService mutationService = Mockito.mock(WorldDesignMutationService.class); - MeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext( - "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); - WorldManagementGrpcService service = - new WorldManagementGrpcService( - pingService, - roomService, - Mockito.mock(WorldInstanceActivationService.class), - digestService, - mutationService, - Mockito.mock(WorldUpgradeValidationService.class), - Mockito.mock(GameplaySessionAttestationService.class), - meterRegistry, - new ObjectMapper(), - (PublicationReadGuard) null); + private static ApplyWorldDesignMutationRequest worldDesignMutationRequest( + String tenantId, String versionId, String scopeId) { + return ApplyWorldDesignMutationRequest.newBuilder() + .setTenantId(tenantId) + .setVersionId(versionId) + .setCommitId("commit-1") + .setRevisionId("revision-1") + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(scopeId) + .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) + .build(); + } - AtomicReference ref = new AtomicReference<>(); + private static ApplyWorldDesignMutationResponse invokeWorldDesignMutation( + WorldManagementGrpcService service, ApplyWorldDesignMutationRequest request) { + AtomicReference response = new AtomicReference<>(); service.applyWorldDesignMutation( - ApplyWorldDesignMutationRequest.newBuilder() - .setTenantId("1") - .setVersionId("0") - .setCommitId("commit-1") - .setRevisionId("revision-1") - .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) - .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) - .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) - .setScopeId("44") - .setRegion(RegionDesignMutation.newBuilder().setName("North").build()) - .build(), + request, new StreamObserver<>() { @Override public void onNext(ApplyWorldDesignMutationResponse value) { - ref.set(value); + response.set(value); } @Override - public void onError(Throwable t) {} + public void onError(Throwable throwable) { + throw new AssertionError("World mutation RPC failed", throwable); + } @Override public void onCompleted() {} }); + return response.get(); + } - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("versionId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(mutationService); + private static void assertMutationUnavailable(ApplyWorldDesignMutationResponse response) { + assertNotNull(response); + assertTrue(response.hasError()); + assertEquals("FAILED_PRECONDITION", response.getError().getCode()); + assertEquals( + "Canonical World Draft writes are unavailable until current Account " + + "commit authorization is verified.", + response.getError().getMessage()); + assertEquals( + WorldDesignMutationResult.WORLD_DESIGN_MUTATION_RESULT_UNSPECIFIED, response.getResult()); + assertEquals("", response.getTenantId()); + assertEquals("", response.getVersionId()); + assertEquals("", response.getAggregateId()); + assertEquals(0L, response.getDraftRevisionEpoch()); + assertEquals(0L, response.getDraftScopeRevisionEpoch()); } @Test @@ -703,8 +773,7 @@ void prepareWorldInstanceReturnsLifecycleSnapshot() { WorldInstanceActivationService activationService = Mockito.mock(WorldInstanceActivationService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext( - "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); + SessionContext.clear(); Mockito.when( activationService.prepareWorldInstance( Mockito.argThat( @@ -734,35 +803,27 @@ void prepareWorldInstanceReturnsLifecycleSnapshot() { Mockito.mock(GameplaySessionAttestationService.class), meterRegistry, new ObjectMapper(), - (PublicationReadGuard) null); + publicationReadGuard()); AtomicReference ref = new AtomicReference<>(); - service.prepareWorldInstance( - PrepareWorldInstanceRequest.newBuilder() - .setTenantId("1") - .setGameInstanceId("55") - .setGameTemplateId("7") - .setControlPlaneRequestId("cp-1") - .setLaunchDescriptorId("ld-1") - .setVersionId("11") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setReleaseBundleId("77") - .setPublishedReleaseBundleRef("prb:1:11:77") - .setVersionStateEpoch(4L) - .build(), - new StreamObserver<>() { - @Override - public void onNext(PrepareWorldInstanceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + runWithPeer( + peer("game-session-service"), + () -> + service.prepareWorldInstance( + PrepareWorldInstanceRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("55") + .setGameTemplateId("7") + .setControlPlaneRequestId("cp-1") + .setLaunchDescriptorId("ld-1") + .setVersionId("11") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setReleaseBundleId("77") + .setPublishedReleaseBundleRef("prb:1:11:77") + .setVersionStateEpoch(4L) + .build(), + responseObserver(ref))); assertEquals("55", ref.get().getWorldInstance().getGameInstanceId()); assertEquals(1L, ref.get().getWorldInstance().getLifecycleEpoch()); @@ -775,8 +836,7 @@ void prepareWorldInstanceRejectsZeroTenantId() { WorldInstanceActivationService activationService = Mockito.mock(WorldInstanceActivationService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext( - "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); + SessionContext.clear(); WorldManagementGrpcService service = new WorldManagementGrpcService( pingService, @@ -788,35 +848,27 @@ void prepareWorldInstanceRejectsZeroTenantId() { Mockito.mock(GameplaySessionAttestationService.class), meterRegistry, new ObjectMapper(), - (PublicationReadGuard) null); + publicationReadGuard()); AtomicReference ref = new AtomicReference<>(); - service.prepareWorldInstance( - PrepareWorldInstanceRequest.newBuilder() - .setTenantId("0") - .setGameInstanceId("55") - .setGameTemplateId("7") - .setControlPlaneRequestId("cp-1") - .setLaunchDescriptorId("ld-1") - .setVersionId("11") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setReleaseBundleId("77") - .setPublishedReleaseBundleRef("prb:1:11:77") - .setVersionStateEpoch(4L) - .build(), - new StreamObserver<>() { - @Override - public void onNext(PrepareWorldInstanceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + runWithPeer( + peer("game-session-service"), + () -> + service.prepareWorldInstance( + PrepareWorldInstanceRequest.newBuilder() + .setTenantId("0") + .setGameInstanceId("55") + .setGameTemplateId("7") + .setControlPlaneRequestId("cp-1") + .setLaunchDescriptorId("ld-1") + .setVersionId("11") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setReleaseBundleId("77") + .setPublishedReleaseBundleRef("prb:1:11:77") + .setVersionStateEpoch(4L) + .build(), + responseObserver(ref))); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); assertEquals("tenantId must be positive", ref.get().getError().getMessage()); @@ -830,8 +882,7 @@ void activatePreparedWorldInstanceRejectsMalformedGameInstanceId() { WorldInstanceActivationService activationService = Mockito.mock(WorldInstanceActivationService.class); MeterRegistry meterRegistry = new SimpleMeterRegistry(); - SessionContext.setContext( - "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); + SessionContext.clear(); WorldManagementGrpcService service = new WorldManagementGrpcService( pingService, @@ -843,33 +894,161 @@ void activatePreparedWorldInstanceRejectsMalformedGameInstanceId() { Mockito.mock(GameplaySessionAttestationService.class), meterRegistry, new ObjectMapper(), - (PublicationReadGuard) null); + publicationReadGuard()); AtomicReference ref = new AtomicReference<>(); - service.activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("1") - .setGameInstanceId("abc") - .setExpectedLifecycleEpoch(3L) - .build(), - new StreamObserver<>() { - @Override - public void onNext(ActivatePreparedWorldInstanceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + runWithPeer( + peer("game-session-service"), + () -> + service.activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("abc") + .setExpectedLifecycleEpoch(3L) + .build(), + responseObserver(ref))); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); assertEquals("gameInstanceId must be numeric", ref.get().getError().getMessage()); Mockito.verifyNoInteractions(activationService); } + @Test + void lifecycleMutationsRequireSameNamespaceGameSessionPeerBeforeParsingOrOwnerCalls() { + SessionContext.clear(); + WorldInstanceActivationService activationService = + Mockito.mock(WorldInstanceActivationService.class); + WorldManagementGrpcService configuredService = + lifecycleService(activationService, publicationReadGuard()); + + assertLifecycleEndpointsDenied(configuredService, null); + assertLifecycleEndpointsDenied(configuredService, peer("account-service")); + assertLifecycleEndpointsDenied(configuredService, peer("other-test", "game-session-service")); + + SessionContext.setContext( + "test-account", List.of(), Map.of(), true, "game-session-service", "test-instance"); + assertLifecycleEndpointsDenied(configuredService, peer("game-session-service")); + SessionContext.clear(); + + WorldManagementGrpcService missingNamespaceService = lifecycleService(activationService, null); + assertLifecycleEndpointsDenied(missingNamespaceService, peer("game-session-service")); + + Mockito.verifyNoInteractions(activationService); + SessionContext.clear(); + } + + @Test + void authorizedGameSessionPeerReachesAllLifecycleOwners() { + SessionContext.clear(); + WorldInstanceActivationService activationService = + Mockito.mock(WorldInstanceActivationService.class); + WorldInstanceLifecycleSnapshotDto snapshot = + new WorldInstanceLifecycleSnapshotDto( + 1L, 55L, 7L, "cp-1", "ld-1", 11L, 77L, "genrev-11", "prb:1:11:77", 4L, 2L, "ACTIVE"); + Mockito.when(activationService.activatePreparedWorldInstance(1L, 55L, 2L)).thenReturn(snapshot); + Mockito.when(activationService.failPreparedWorldInstance(1L, 55L, 2L, "reason")) + .thenReturn(snapshot); + Mockito.when(activationService.terminateWorldInstance(1L, 55L, 2L, "termination-1", "reason")) + .thenReturn(snapshot); + WorldManagementGrpcService service = + lifecycleService(activationService, publicationReadGuard()); + + AtomicReference activateResponse = + new AtomicReference<>(); + AtomicReference failResponse = new AtomicReference<>(); + AtomicReference terminateResponse = new AtomicReference<>(); + runWithPeer( + peer("game-session-service"), + () -> { + service.activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("55") + .setExpectedLifecycleEpoch(2L) + .build(), + responseObserver(activateResponse)); + service.failPreparedWorldInstance( + FailPreparedWorldInstanceRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("55") + .setExpectedLifecycleEpoch(2L) + .setReason("reason") + .build(), + responseObserver(failResponse)); + service.terminateWorldInstance( + TerminateWorldInstanceRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("55") + .setExpectedLifecycleEpoch(2L) + .setTerminationRequestId("termination-1") + .setReason("reason") + .build(), + responseObserver(terminateResponse)); + }); + + assertEquals( + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE, + activateResponse.get().getWorldInstance().getStatus()); + assertEquals( + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE, + failResponse.get().getWorldInstance().getStatus()); + assertEquals( + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE, + terminateResponse.get().getWorldInstance().getStatus()); + Mockito.verify(activationService).activatePreparedWorldInstance(1L, 55L, 2L); + Mockito.verify(activationService).failPreparedWorldInstance(1L, 55L, 2L, "reason"); + Mockito.verify(activationService) + .terminateWorldInstance(1L, 55L, 2L, "termination-1", "reason"); + SessionContext.clear(); + } + + private static WorldManagementGrpcService lifecycleService( + WorldInstanceActivationService activationService, PublicationReadGuard readGuard) { + return new WorldManagementGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(RoomService.class), + activationService, + Mockito.mock(WorldDraftDesignDigestService.class), + Mockito.mock(WorldDesignMutationService.class), + Mockito.mock(WorldUpgradeValidationService.class), + Mockito.mock(GameplaySessionAttestationService.class), + new SimpleMeterRegistry(), + new ObjectMapper(), + readGuard); + } + + private static void assertLifecycleEndpointsDenied( + WorldManagementGrpcService service, GrpcPeerIdentity caller) { + Runnable assertDenied = + () -> { + var prepare = + invokePrepareWorldInstance(service, PrepareWorldInstanceRequest.getDefaultInstance()); + var activate = + invokeActivatePreparedWorldInstance( + service, ActivatePreparedWorldInstanceRequest.getDefaultInstance()); + var fail = + invokeFailPreparedWorldInstance( + service, FailPreparedWorldInstanceRequest.getDefaultInstance()); + var terminate = + invokeTerminateWorldInstance( + service, TerminateWorldInstanceRequest.getDefaultInstance()); + + assertEquals("PERMISSION_DENIED", prepare.getError().getCode()); + assertFalse(prepare.hasWorldInstance()); + assertEquals("PERMISSION_DENIED", activate.getError().getCode()); + assertFalse(activate.hasWorldInstance()); + assertEquals("PERMISSION_DENIED", fail.getError().getCode()); + assertFalse(fail.hasWorldInstance()); + assertEquals("PERMISSION_DENIED", terminate.getError().getCode()); + assertFalse(terminate.hasWorldInstance()); + }; + if (caller == null) { + assertDenied.run(); + } else { + runWithPeer(caller, assertDenied); + } + } + @Test void validateWorldUpgradeMappingsReturnsCompatibilityPayload() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java index bd1950559e..9c90511b63 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionMtlsTest.java @@ -48,9 +48,13 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.FinalizeCanonicalInitialAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityRequest; import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldTerminalServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; @@ -79,7 +83,7 @@ import org.springframework.core.io.FileSystemResource; import tools.jackson.databind.ObjectMapper; -/** Physical socket proof for the exact-method-protected canonical first-admission handlers. */ +/** Physical socket proof for exact-method-protected lifecycle and first-admission handlers. */ class WorldCanonicalInitialAdmissionMtlsTest { private static final String NAMESPACE = "test"; private static final String JWT_SECRET = "test-secret-key-test-secret-key-32-bytes"; @@ -100,7 +104,15 @@ class WorldCanonicalInitialAdmissionMtlsTest { .getFullMethodName(); // Fixture-only opt-in lets the physical receiver reach the mock-backed workload-identity gates. private static final Set PHYSICAL_RECEIVER_PUBLIC_METHODS = - Set.of(ACQUIRE_METHOD, IDENTITY_READ_METHOD, LIFECYCLE_READ_METHOD, TERMINAL_METHOD); + Set.of( + ACQUIRE_METHOD, + IDENTITY_READ_METHOD, + LIFECYCLE_READ_METHOD, + TERMINAL_METHOD, + WorldManagementServiceGrpc.getPrepareWorldInstanceMethod().getFullMethodName(), + WorldManagementServiceGrpc.getActivatePreparedWorldInstanceMethod().getFullMethodName(), + WorldManagementServiceGrpc.getFailPreparedWorldInstanceMethod().getFullMethodName(), + WorldManagementServiceGrpc.getTerminateWorldInstanceMethod().getFullMethodName()); private static TestPki pki; private final WorldCanonicalInitialAdmissionHoldRepository holdRepository = @@ -216,7 +228,7 @@ void stopPhysicalReceiver() throws Exception { } @Test - void exactSameNamespaceGameSessionCertificateReachesAllFourHandlersWithoutBearer() + void exactSameNamespaceGameSessionCertificateReachesProtectedHandlersWithoutBearer() throws Exception { ManagedChannel channel = channel(pki.gameSessionClient()); try { @@ -240,6 +252,31 @@ void exactSameNamespaceGameSessionCertificateReachesAllFourHandlersWithoutBearer terminalStub(channel) .finalizeCanonicalInitialAdmissionHold( FinalizeCanonicalInitialAdmissionHoldRequest.getDefaultInstance())); + assertWorldLifecycleError( + worldManagementStub(channel) + .prepareWorldInstance(PrepareWorldInstanceRequest.getDefaultInstance()) + .getError() + .getCode(), + "INVALID_ARGUMENT"); + assertWorldLifecycleError( + worldManagementStub(channel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.getDefaultInstance()) + .getError() + .getCode(), + "INVALID_ARGUMENT"); + assertWorldLifecycleError( + worldManagementStub(channel) + .failPreparedWorldInstance(FailPreparedWorldInstanceRequest.getDefaultInstance()) + .getError() + .getCode(), + "INVALID_ARGUMENT"); + assertWorldLifecycleError( + worldManagementStub(channel) + .terminateWorldInstance(TerminateWorldInstanceRequest.getDefaultInstance()) + .getError() + .getCode(), + "INVALID_ARGUMENT"); } finally { stopChannel(channel); } @@ -324,6 +361,7 @@ private void assertAllProtectedMethodsDenied(TestCertificate certificate) throws terminalStub(channel) .finalizeCanonicalInitialAdmissionHold( FinalizeCanonicalInitialAdmissionHoldRequest.getDefaultInstance())); + assertWorldLifecyclePeerDenied(channel); } finally { stopChannel(channel); } @@ -350,6 +388,44 @@ private void assertAllProtectedMethodsDenied(TestCertificate certificate) throws .withDeadlineAfter(3, TimeUnit.SECONDS); } + private WorldManagementServiceGrpc.WorldManagementServiceBlockingStub worldManagementStub( + ManagedChannel channel) { + return WorldManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private void assertWorldLifecyclePeerDenied(ManagedChannel channel) { + assertWorldLifecycleError( + worldManagementStub(channel) + .prepareWorldInstance(PrepareWorldInstanceRequest.getDefaultInstance()) + .getError() + .getCode(), + "PERMISSION_DENIED"); + assertWorldLifecycleError( + worldManagementStub(channel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.getDefaultInstance()) + .getError() + .getCode(), + "PERMISSION_DENIED"); + assertWorldLifecycleError( + worldManagementStub(channel) + .failPreparedWorldInstance(FailPreparedWorldInstanceRequest.getDefaultInstance()) + .getError() + .getCode(), + "PERMISSION_DENIED"); + assertWorldLifecycleError( + worldManagementStub(channel) + .terminateWorldInstance(TerminateWorldInstanceRequest.getDefaultInstance()) + .getError() + .getCode(), + "PERMISSION_DENIED"); + } + + private static void assertWorldLifecycleError(String actual, String expected) { + assertThat(actual).isEqualTo(expected); + } + private ManagedChannel channel(TestCertificate clientCertificate) throws Exception { return NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) .sslContext( From c8f674c47eafe638d7c99da33b4a60f9b100dfb5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 21:55:07 +1300 Subject: [PATCH 004/129] Compose hosted terms currentness inside Account owner transactions --- .../AccountHostedTermsService.java | 57 ++++- ...ronmentBindingPostgresIntegrationTest.java | 54 +++++ .../AccountHostedTermsServiceTest.java | 225 ++++++++++++++++++ 3 files changed, 331 insertions(+), 5 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java index 200b8cdd35..712b530035 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; /** @@ -141,16 +142,62 @@ public EnvironmentBindingPublicationResult resumeEnvironmentBinding(UUID request * READ_COMMITTED owner transaction. The result is currentness/source evidence, not permission. */ public EnvironmentBoundCurrentness requireCurrentnessForCurrentEnvironment(UUID creatorPartyId) { - requireCurrentEnvironmentBoundaryAuthority(); HostedTermsEncoding.requireUuid(creatorPartyId, "creator party"); + CapturedEnvironmentBoundary captured = captureCurrentEnvironmentBoundary(); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> requireCurrentnessInOwnerTransaction(captured, creatorPartyId)), + "Account environment-bound currentness result"); + } + + /** + * Obtains the trusted environment observation before any Account transaction begins. This + * service-issued handle is source material only and cannot authorize a Draft mutation. + */ + public CapturedEnvironmentBoundary captureCurrentEnvironmentBoundary() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Current environment boundary must be captured outside an Account transaction"); + } + requireCurrentEnvironmentBoundaryAuthority(); HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment = Objects.requireNonNull( currentEnvironmentBoundaryAuthority.currentBoundary(), "authenticated current environment boundary"); - return Objects.requireNonNull( - ownerTransaction.execute( - ignored -> currentnessForEnvironmentInTransaction(environment, creatorPartyId)), - "Account environment-bound currentness result"); + return new CapturedEnvironmentBoundary(this, environment); + } + + /** + * Locks and rereads the persisted mapping, catalog, party, acceptance and deadline in the + * caller's writable READ_COMMITTED Account transaction. No external owner is called here; the + * returned evidence is not a commit token or proof of later external environment continuity. + */ + public EnvironmentBoundCurrentness requireCurrentnessInOwnerTransaction( + CapturedEnvironmentBoundary captured, UUID creatorPartyId) { + if (captured == null || captured.owner != this) { + throw new IllegalArgumentException("Current environment capture belongs to another owner"); + } + HostedTermsEncoding.requireUuid(creatorPartyId, "creator party"); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account owner transaction required"); + } + // lockHead performs the physical connection's writable READ_COMMITTED check before reading. + return currentnessForEnvironmentInTransaction(captured.environment, creatorPartyId); + } + + /** Opaque, immutable observation scoped to the issuing service instance. */ + public static final class CapturedEnvironmentBoundary { + private final AccountHostedTermsService owner; + private final HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment; + + private CapturedEnvironmentBoundary( + AccountHostedTermsService owner, + HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary environment) { + this.owner = owner; + this.environment = environment; + } } /** Recovery uses the already durable exact publication and never remints operator evidence. */ diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java index 917e44db0e..1e92f957c0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java @@ -49,6 +49,7 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; @@ -127,6 +128,35 @@ void realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersion bindingPublications.put(firstBindingRequest, firstBindingEvidence); var current = service.requireCurrentnessForCurrentEnvironment(partyId); + var capturedBoundary = service.captureCurrentEnvironmentBoundary(); + var sameSnapshot = + db.transactions() + .execute( + ignored -> service.requireCurrentnessInOwnerTransaction(capturedBoundary, partyId)); + assertThat(sameSnapshot.environment()).isEqualTo(current.environment()); + assertThat(sameSnapshot.binding()).isEqualTo(current.binding()); + assertThat(sameSnapshot.terms().acceptanceEvidenceId()) + .isEqualTo(current.terms().acceptanceEvidenceId()); + assertThat(sameSnapshot.terms().exactCurrentnessSource()) + .containsExactly(current.terms().exactCurrentnessSource()); + TransactionTemplate wrongIsolation = new TransactionTemplate(db.transactionManager()); + wrongIsolation.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + wrongIsolation.execute( + ignored -> + service.requireCurrentnessInOwnerTransaction(capturedBoundary, partyId))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + TransactionTemplate readOnly = new TransactionTemplate(db.transactionManager()); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute( + ignored -> + service.requireCurrentnessInOwnerTransaction(capturedBoundary, partyId))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); assertThat(current.environment().environmentBoundary()).isEqualTo("production"); assertThat(current.binding()).isEqualTo(firstBinding.candidate()); assertThat(current.terms().acceptanceEvidenceId()).isEqualTo(acceptance.evidenceId()); @@ -175,6 +205,15 @@ void realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersion assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(partyId)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("changed catalog authority"); + assertThatThrownBy( + () -> + db.transactions() + .execute( + ignored -> + service.requireCurrentnessInOwnerTransaction( + capturedBoundary, partyId))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed catalog authority"); UUID secondBindingRequest = UUID.randomUUID(); HostedTermsEnvironmentBinding.PublicationEvidence secondBindingEvidence = @@ -205,6 +244,13 @@ void realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersion assertThat(retainedBinding).isEqualTo(firstBinding.candidate()); assertThat(service.requireCurrentnessForCurrentEnvironment(partyId).binding()) .isEqualTo(secondBinding.candidate()); + assertThat( + db.transactions() + .execute( + ignored -> + service.requireCurrentnessInOwnerTransaction(capturedBoundary, partyId)) + .binding()) + .isEqualTo(secondBinding.candidate()); boundary.set(currentBoundary("unbound-test-environment")); assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(partyId)) @@ -337,6 +383,7 @@ void boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline() throws "deadline-test-environment", currentCatalog, null, null, "test-only-publisher")); service.publishEnvironmentBinding(bindingRequest); + var capturedBoundary = service.captureCurrentEnvironmentBoundary(); Instant deadline = databaseNow(db).plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.MICROS); UUID scheduledRequest = UUID.randomUUID(); catalogPublications.put( @@ -349,6 +396,13 @@ void boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline() throws HostedTermsCatalogVersion scheduled = service.publish(scheduledRequest).candidate(); var currentness = service.requireCurrentnessForCurrentEnvironment(partyId); + var sameTransactionCurrentness = + db.transactions() + .execute( + ignored -> service.requireCurrentnessInOwnerTransaction(capturedBoundary, partyId)); + assertThat(sameTransactionCurrentness.binding()).isEqualTo(currentness.binding()); + assertThat(sameTransactionCurrentness.terms().exactCurrentnessSource()) + .containsExactly(currentness.terms().exactCurrentnessSource()); assertThat(currentness.terms().acceptanceEvidenceId()).isEqualTo(acceptance.evidenceId()); assertThat(currentness.terms().validUntil()).isEqualTo(scheduled.effectiveAt()); assertThat(currentness.terms().disclosedDeadline()).isEqualTo(scheduled); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java index 44f8772a00..305a64da79 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsServiceTest.java @@ -14,19 +14,24 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingRepository; import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; import net.firedevops.firemud.accountservice.hostedterms.IndividualHostedTermsAcceptance; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import org.junit.jupiter.api.Test; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Unit proof uses explicit typed upstream authority fixtures, not caller-supplied authority DTOs. @@ -34,6 +39,211 @@ class AccountHostedTermsServiceTest { private static final Instant NOW = Instant.parse("2026-10-08T00:00:00Z"); + @Test + void environmentCaptureIsServiceIssuedOutsideTheOwnerTransaction() { + Fixture fixture = new Fixture(); + var boundaries = mock(AccountHostedTermsService.CurrentEnvironmentBoundaryAuthority.class); + var bindings = mock(HostedTermsEnvironmentBindingRepository.class); + AccountHostedTermsService service = fixture.environmentService(bindings, boundaries); + var current = currentBoundary("production"); + when(boundaries.currentBoundary()) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return current; + }); + + var captured = service.captureCurrentEnvironmentBoundary(); + assertThat(captured).isNotNull(); + verify(boundaries).currentBoundary(); + + boolean transactionWasActive = TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(service::captureCurrentEnvironmentBoundary) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an Account transaction"); + assertThatThrownBy(() -> service.requireCurrentnessForCurrentEnvironment(fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an Account transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(transactionWasActive); + } + // Both rejected calls precede an additional external boundary lookup. + verify(boundaries).currentBoundary(); + } + + @Test + void synchronizationOnlyContextCannotCaptureTheExternalEnvironment() { + Fixture fixture = new Fixture(); + var boundaries = mock(AccountHostedTermsService.CurrentEnvironmentBoundaryAuthority.class); + AccountHostedTermsService service = + fixture.environmentService(mock(HostedTermsEnvironmentBindingRepository.class), boundaries); + boolean synchronizationWasActive = TransactionSynchronizationManager.isSynchronizationActive(); + if (!synchronizationWasActive) { + TransactionSynchronizationManager.initSynchronization(); + } + try { + assertThatThrownBy(service::captureCurrentEnvironmentBoundary) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an Account transaction"); + } finally { + if (!synchronizationWasActive) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + verify(boundaries, never()).currentBoundary(); + } + + @Test + void capturedEnvironmentReadsTheSameLockedSourcesWithoutCallingTheProviderInsideTransaction() { + Fixture fixture = new Fixture(); + var boundaries = mock(AccountHostedTermsService.CurrentEnvironmentBoundaryAuthority.class); + var bindings = mock(HostedTermsEnvironmentBindingRepository.class); + AccountHostedTermsService service = fixture.environmentService(bindings, boundaries); + var environment = currentBoundary("production"); + when(boundaries.currentBoundary()) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return environment; + }); + var captured = service.captureCurrentEnvironmentBoundary(); + + IndividualCreatorPartySource party = party(fixture.partyId, fixture.accountId); + HostedTermsCatalogVersion catalog = + terms(fixture.scopeId, null, 1, 1, "terms-v1", NOW.minusSeconds(60)); + IndividualHostedTermsAcceptance acceptance = + acceptance(action(fixture, catalog, true), party, catalog); + byte[] publicationEvidence = "test-publication-evidence".getBytes(); + HostedTermsEnvironmentBinding binding = + new HostedTermsEnvironmentBinding( + UUID.randomUUID(), + UUID.randomUUID(), + "production", + fixture.scopeId, + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + catalog.versionId(), + catalog.sourceVersion(), + "test-environment-owner", + "test-publication-event", + HostedTermsEncoding.digest(publicationEvidence), + null, + null, + 1); + when(bindings.lockHead("production")) + .thenReturn( + new HostedTermsEnvironmentBindingRepository.HeadSnapshot("production", binding, null)); + when(fixture.repository.lockPartyAccount(fixture.partyId)).thenReturn(fixture.accountId); + when(fixture.parties.readIndividualSource(fixture.partyId, fixture.accountId)) + .thenReturn(party); + when(fixture.repository.lockScope(fixture.scopeId)) + .thenReturn(scope(fixture.scopeId, catalog, NOW, null)); + when(fixture.repository.readCurrentAcceptance(fixture.partyId, fixture.scopeId, catalog)) + .thenReturn(Optional.of(acceptance)); + + boolean transactionWasActive = TransactionSynchronizationManager.isActualTransactionActive(); + boolean transactionWasReadOnly = + TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + try { + var current = service.requireCurrentnessInOwnerTransaction(captured, fixture.partyId); + assertThat(current.environment()).isSameAs(environment); + assertThat(current.binding()).isSameAs(binding); + assertThat(current.terms().acceptanceEvidenceId()).isEqualTo(acceptance.evidenceId()); + assertThat(current.terms().exactCurrentnessSource()) + .containsExactly(HostedTermsEncoding.currentnessSource(catalog, acceptance, null)); + assertThat(current.sourceEvidence()).hasSize(3); + assertThat(current.sourceEvidence()) + .anySatisfy( + source -> { + assertThat(source.key()).isEqualTo(binding.sourceEvidence().key()); + assertThat(source.canonicalBytes()) + .containsExactly(binding.sourceEvidence().canonicalBytes()); + }) + .anySatisfy( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.HOSTED_TERMS); + assertThat(source.scopeId()).isEqualTo(fixture.scopeId.toString()); + assertThat(source.evidence()) + .containsExactly( + HostedTermsEncoding.currentnessSource(catalog, acceptance, null)); + }) + .anySatisfy( + source -> { + assertThat(source.kind()).isEqualTo(SourceKind.CREATOR_PARTY); + assertThat(source.scopeId()).isEqualTo(fixture.partyId.toString()); + assertThat(source.evidence()).containsExactly(CreatorPartyEncoding.party(party)); + }); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(transactionWasReadOnly); + TransactionSynchronizationManager.setActualTransactionActive(transactionWasActive); + } + verify(boundaries).currentBoundary(); + verify(bindings).lockHead("production"); + } + + @Test + void ownerCurrentnessRejectsMissingForeignAndNonwritableTransactionBeforeSourceRead() { + Fixture fixture = new Fixture(); + var boundaries = mock(AccountHostedTermsService.CurrentEnvironmentBoundaryAuthority.class); + var bindings = mock(HostedTermsEnvironmentBindingRepository.class); + AccountHostedTermsService service = fixture.environmentService(bindings, boundaries); + AccountHostedTermsService other = fixture.environmentService(bindings, boundaries); + when(boundaries.currentBoundary()).thenReturn(currentBoundary("production")); + var captured = service.captureCurrentEnvironmentBoundary(); + + assertThatThrownBy(() -> service.requireCurrentnessInOwnerTransaction(null, fixture.partyId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> other.requireCurrentnessInOwnerTransaction(captured, fixture.partyId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> service.requireCurrentnessInOwnerTransaction(captured, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + + boolean transactionWasActive = TransactionSynchronizationManager.isActualTransactionActive(); + boolean transactionWasReadOnly = + TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy( + () -> service.requireCurrentnessInOwnerTransaction(captured, fixture.partyId)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(transactionWasReadOnly); + TransactionSynchronizationManager.setActualTransactionActive(transactionWasActive); + } + verify(bindings, never()).lockHead(any()); + } + + @Test + void unavailableEnvironmentObservationCannotProduceACapture() { + Fixture fixture = new Fixture(); + var boundaries = mock(AccountHostedTermsService.CurrentEnvironmentBoundaryAuthority.class); + AccountHostedTermsService service = + fixture.environmentService(mock(HostedTermsEnvironmentBindingRepository.class), boundaries); + assertThatThrownBy(service::captureCurrentEnvironmentBoundary) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("authenticated current environment boundary"); + } + + private static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary currentBoundary( + String boundary) { + byte[] evidence = + ("test-boundary:" + boundary).getBytes(java.nio.charset.StandardCharsets.UTF_8); + return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + boundary, + "test-environment-owner", + "test-observation", + evidence, + HostedTermsEncoding.digest(evidence)); + } + @Test void affirmativeAcceptancePersistsExactShownCatalogAndReturnsOriginalReceipt() { Fixture fixture = new Fixture(); @@ -550,6 +760,21 @@ private void acceptanceAuthority(AccountHostedTermsService.AcceptanceAction acti private void publicationAuthority(AccountHostedTermsService.PublicationEvidence evidence) { when(publicationAuthority.resolve(requestId)).thenReturn(evidence); } + + private AccountHostedTermsService environmentService( + HostedTermsEnvironmentBindingRepository bindings, + AccountHostedTermsService.CurrentEnvironmentBoundaryAuthority boundaries) { + return new AccountHostedTermsService( + new NoopTransactionManager(), + repository, + parties, + fences, + publicationAuthority, + acceptanceAuthority, + bindings, + mock(AccountHostedTermsService.EnvironmentBindingPublicationAuthority.class), + boundaries); + } } private static final class NoopTransactionManager implements PlatformTransactionManager { From ed2fef4a0d581df4a513d6fb304866757f5be462 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 22:18:08 +1300 Subject: [PATCH 005/129] Repair composed owner migrations and publication transaction fences --- design/project-management/ai-observations.md | 6 + .../capability-allocation.md | 2 +- .../V98__creator_membership_provenance.sql | 11 ++ ...otstrapServicePostgresIntegrationTest.java | 69 ++++++++++++ ...alCreatorPartyPostgresIntegrationTest.java | 13 +-- ...untHostedTermsPostgresIntegrationTest.java | 12 +- ...ronmentBindingPostgresIntegrationTest.java | 6 +- .../gamedesign/entity/PublishAttempt.java | 1 + .../repository/PublishAttemptRepository.java | 103 ++++++++++++++---- .../impl/PublishAttemptServiceImpl.java | 3 +- ...erminalOutcomePostgresIntegrationTest.java | 39 ++++++- ...leaseCanonicalIdentityIntegrationTest.java | 2 +- ...emptServiceTransactionIntegrationTest.java | 102 +++++++++++++++++ 13 files changed, 327 insertions(+), 42 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V98__creator_membership_provenance.sql diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index cebc28b28f..e36ef26754 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -67,3 +67,9 @@ Entry format: - Context: The PR #3078 watcher initially counted the first 30 jobs as the full run; complete coverage showed 40 jobs, with 38 successful and two skipped. Required gates were green and the merge remained valid. - Observation: The run header also transiently reported queued while jobs progressed, then completed successfully; its cause remains unknown. Partial job pages and a transient header cannot establish a full-run count or terminal outcome. - Expected pattern: Fetch complete pagination, reconcile `total_count`, and verify unique job IDs before reporting full-run counts. Report required-job/gate proof separately from the terminal run header, without inferring the cause of inconsistent intermediate snapshots. + +- `2026-10-08`: Carry integration fixture targets with forward-renumbered migrations + - Context: PR #3105 preserved imported Account migration bytes under receiving V94–V97, but donor-era Flyway targets remained in three integration suites. Physical CI exposed 18 missing-relation failures despite successful local schema generation and compilation; local PostgreSQL cases had skipped. + - Observation: Comparing migration filenames and bytes alone does not preserve executable proof. Runtime fixture targets and historical before/after migration boundaries must follow the receiving sequence independently. Current repositories may also require tables newer than a deliberately historical fixture. + - Expected pattern: Compare explicit Flyway targets alongside every migration remap, preserving genuine historical-row setup and before/after assertions rather than merely advancing every fixture to latest. Inspect saved per-case HTML when uploaded XML or console exceptions omit the underlying SQL error. + - Current status: Exact receiving target corrections are in preparation; corrected PostgreSQL execution remains unproved. The separate creator-membership provenance constraint mismatch is not attributed to fixture numbering. diff --git a/design/project-management/implementation-tracking/capability-allocation.md b/design/project-management/implementation-tracking/capability-allocation.md index ec71db3fd4..ee5acdd8fd 100644 --- a/design/project-management/implementation-tracking/capability-allocation.md +++ b/design/project-management/implementation-tracking/capability-allocation.md @@ -21,7 +21,7 @@ The ten permanent implementation trackers are retained as the complete-product p | `AA-1.3` | [player-access-and-session.md](./player-access-and-session.md) | [shared-runtime-contracts-and-persistence.md](./shared-runtime-contracts-and-persistence.md); [platform-operations-and-delivery.md](./platform-operations-and-delivery.md) | Account Service owns credential, recovery, security-policy, and data-rights decisions; Shared Runtime supplies trust propagation and Platform Operations supplies operator and deployment controls. | | `AA-1.4` | [player-access-and-session.md](./player-access-and-session.md) | [shared-runtime-contracts-and-persistence.md](./shared-runtime-contracts-and-persistence.md) | Account Service owns subscriptions, purchases, donations, billing, and fees; Shared Runtime carries the local transaction and saga handoff without owning commerce. | | `AA-1.5` | [player-access-and-session.md](./player-access-and-session.md) | [realm-routing-and-playable-state.md](./realm-routing-and-playable-state.md); [game-authoring-publishing-and-activation.md](./game-authoring-publishing-and-activation.md) | Account Service is the canonical entitlement, quota, and hosting-eligibility authority; Realm Routing and Authoring/Activation consume those gates before admission or launch. | -| `AA-2.1` | [player-access-and-session.md](./player-access-and-session.md) | [realm-routing-and-playable-state.md](./realm-routing-and-playable-state.md); [player-experience-commands-and-communication.md](./player-experience-commands-and-communication.md) | Player Access owns account-authenticated gameplay login, character selection, and session binding; Realm Routing supplies admissible targets and Player Experience owns the command/presentation handoff. | +| `AA-2.1` | [player-access-and-session.md](./player-access-and-session.md) | [realm-routing-and-playable-state.md](./realm-routing-and-playable-state.md); [player-experience-commands-and-communication.md](./player-experience-commands-and-communication.md); [shared-runtime-contracts-and-persistence.md](./shared-runtime-contracts-and-persistence.md); [platform-operations-and-delivery.md](./platform-operations-and-delivery.md) | Player Access owns account-authenticated gameplay login, character selection, and session binding; Realm Routing supplies admissible targets, Player Experience owns the command/presentation handoff, Shared Runtime supplies persisted identity and trust primitives, and Platform Operations owns migration-driver packaging and trusted execution. | | `AA-2.2` | [player-access-and-session.md](./player-access-and-session.md) | [player-experience-commands-and-communication.md](./player-experience-commands-and-communication.md); [shared-runtime-contracts-and-persistence.md](./shared-runtime-contracts-and-persistence.md); [platform-operations-and-delivery.md](./platform-operations-and-delivery.md) | Player Access owns reconnect eligibility and continuity decisions; Player Experience renders transcript/redraw, Shared Runtime supports persistence, and Platform Operations owns edge rebind/transport behavior. | | `AA-2.3` | [player-access-and-session.md](./player-access-and-session.md) | [player-experience-commands-and-communication.md](./player-experience-commands-and-communication.md); [world-runtime-and-movement.md](./world-runtime-and-movement.md); [gameplay-rules-entities-and-effects.md](./gameplay-rules-entities-and-effects.md); [shared-runtime-contracts-and-persistence.md](./shared-runtime-contracts-and-persistence.md) | Player Access owns takeover, logout, idle expiry, and revocation state transitions; Player Experience presents lifecycle outcomes while World, Gameplay, and Shared Runtime perform cleanup and persistence handoffs. | | `AA-3.1` | [realm-routing-and-playable-state.md](./realm-routing-and-playable-state.md) | [player-access-and-session.md](./player-access-and-session.md); [player-experience-commands-and-communication.md](./player-experience-commands-and-communication.md) | Realm Routing owns the visible world/realm catalog and pointer-backed discovery; Account supplies caller-filtered membership data and Player Experience exposes the browse experience. | diff --git a/services/account-service/src/main/resources/db/migration/V98__creator_membership_provenance.sql b/services/account-service/src/main/resources/db/migration/V98__creator_membership_provenance.sql new file mode 100644 index 0000000000..bb724346c7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V98__creator_membership_provenance.sql @@ -0,0 +1,11 @@ +ALTER TABLE account_tenant_membership + DROP CONSTRAINT account_membership_provenance_check; + +ALTER TABLE account_tenant_membership + ADD CONSTRAINT account_membership_provenance_check + CHECK (authority_provenance IN ( + 'EXPLICIT_JOIN', + 'LEGACY_UNVERIFIED', + 'SEEDED_DEMO', + 'TENANT_CREATION' + )); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java index b9f5aa8995..0f1f0f4feb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreationBootstrapServicePostgresIntegrationTest.java @@ -72,6 +72,62 @@ class AccountTenantCreationBootstrapServicePostgresIntegrationTest { @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + @Test + void provenanceMigrationPreservesRetainedRowsAndRejectsUnknownValues() { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + migrateSchema(dataSource, schema, "97"); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + + UUID accountUuid = UUID.randomUUID(); + dsl.execute( + "INSERT INTO accounts (account_uuid, username, email, password_hash) " + + "VALUES (?, ?, ?, 'migration-fixture-hash')", + accountUuid, + "creator-migration-" + accountUuid.toString().substring(0, 8), + accountUuid + "@example.test"); + Long accountId = + java.util.Objects.requireNonNull( + dsl.fetchOne("SELECT id FROM accounts WHERE account_uuid = ?", accountUuid)) + .get("id", Long.class); + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, 42, FALSE, 'LEGACY_UNVERIFIED', 1, 1, 'LEGACY_UNVERIFIED'), " + + "(?, 43, FALSE, 'ACTIVE', 1, 1, 'SEEDED_DEMO'), " + + "(?, 44, TRUE, 'ACTIVE', 1, 1, 'EXPLICIT_JOIN')", + accountId, + accountId, + accountId); + List> retainedBefore = + dsl.fetch("SELECT * FROM account_tenant_membership ORDER BY tenant_id").intoMaps(); + + migrateSchema(dataSource, schema, "98"); + + assertThat(dsl.fetch("SELECT * FROM account_tenant_membership ORDER BY tenant_id").intoMaps()) + .containsExactlyElementsOf(retainedBefore); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO account_tenant_membership " + + "(account_id, tenant_id, gameplay_admission_allowed, lifecycle_state, " + + "membership_version, membership_authority_generation, authority_provenance) " + + "VALUES (?, 45, FALSE, 'ACTIVE', 1, 1, 'UNRECOGNIZED')", + accountId)) + .hasMessageContaining("account_membership_provenance_check"); + assertThat( + java.util.Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM account_tenant_membership")) + .get(0, Long.class)) + .isEqualTo(3L); + } + @Test void commitIsControlOnlyAndHistoricalRetryDoesNotOverwriteLaterMembershipAdvance() { Fixture fixture = fixture(false); @@ -695,6 +751,19 @@ private static Fixture fixture(boolean failAfterAudit) { producer); } + private static void migrateSchema( + DriverManagerDataSource dataSource, String schema, String target) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(target) + .load() + .migrate(); + } + private static FreshTenantCreatorEvidence creatorEvidence(UUID accountUuid, UUID tenantUuid) { UUID creationRequestId = UUID.randomUUID(); UUID creationOperationId = UUID.randomUUID(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java index bbd9c15495..4acdb991f1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java @@ -40,7 +40,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Real owner-row and PostgreSQL guard definitions. Verification/policy and original V64 creation + * Real owner-row and PostgreSQL guard definitions. Verification/policy and receiving V94 creation * qualification are explicit SQL fixtures, not authentication, legal provisioning or launch proof. */ @Testcontainers(disabledWithoutDocker = true) @@ -53,9 +53,8 @@ class IndividualCreatorPartyPostgresIntegrationTest { @Test void migrationPreservesExistingAccountAndMembershipAndEnrollsNoParty() throws Exception { - // V74 is this source tree's last existing migration before V78; V77 is reserved elsewhere - // and is not a historical schema that this candidate can execute or prove. - Database db = database("74"); + // V94 is the receiving tree's last existing migration before the V95 creator-party schema. + Database db = database("94"); UUID account = insertAccount(db); long accountKey = Objects.requireNonNull( @@ -83,7 +82,7 @@ void migrationPreservesExistingAccountAndMembershipAndEnrollsNoParty() throws Ex "SELECT * FROM account_tenant_membership WHERE account_id = ?", accountKey), "Baseline membership row is missing") .intoMap(); - migrate(db, "78"); + migrate(db, "95"); assertThat( Objects.requireNonNull( db.dsl().fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", account), @@ -495,7 +494,7 @@ void databaseRejectsSourceAndReceiptRewritesAndOrphanInitialHistory() throws Exc } private static Fixture fixture() throws Exception { - Database db = database("78"); + Database db = database("95"); UUID account = insertAccount(db); UUID request = UUID.randomUUID(); UUID operation = UUID.randomUUID(); @@ -585,7 +584,7 @@ private static void insertHistory(Fixture fixture, String origin, long version) } private static void insertBootstrapFixture(Database db, FreshTenantCreatorEvidence creator) { - // Stipulated original qualification, using the real guarded V64 lifecycle; no guard is + // Stipulated original qualification, using the real guarded V94 lifecycle; no guard is // disabled. var creation = creator.creationEvidence(); UUID authorization = creator.accountAuthorizationOperationId(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java index 1c532676de..8365fc14e4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java @@ -59,7 +59,7 @@ class AccountHostedTermsPostgresIntegrationTest { @Test void migrationRetainsExistingPartyAndBackfillsNoCatalogOrAcceptance() throws Exception { - Database db = database("81"); + Database db = database("95"); UUID accountId = insertAccount(db); IndividualCreatorPartySource party = party(UUID.randomUUID(), accountId, 1, "test-id-evidence-v1"); @@ -78,7 +78,7 @@ void migrationRetainsExistingPartyAndBackfillsNoCatalogOrAcceptance() throws Exc .intoMap()); byte[] partySourceBefore = (byte[]) partyBefore.remove("source_payload"); - migrate(db, "94"); + migrate(db, "96"); assertThat( Objects.requireNonNull( @@ -104,7 +104,7 @@ void migrationRetainsExistingPartyAndBackfillsNoCatalogOrAcceptance() throws Exc @Test void realServicePublishesAffirmativelyAcceptsReadsBackAndAdvancesMateriality() throws Exception { - Database db = database("94"); + Database db = database("96"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -251,7 +251,7 @@ void realServicePublishesAffirmativelyAcceptsReadsBackAndAdvancesMateriality() t @Test void acceptanceRejectsWrongSignerNegativeActionChangedShownTermsAndUnavailableIdentity() throws Exception { - Database db = database("94"); + Database db = database("96"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -318,7 +318,7 @@ void acceptanceRejectsWrongSignerNegativeActionChangedShownTermsAndUnavailableId @Test void futureTermsCarryDeadlineWithoutFreezingPriorTermsEarly() throws Exception { - Database db = database("94"); + Database db = database("96"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -482,7 +482,7 @@ private static void awaitLatch(CountDownLatch latch, String message) { @Test void ownerTransactionRollbackRemovesUncommittedCatalogAndPublicationIntent() throws Exception { - Database db = database("94"); + Database db = database("96"); HostedTermsRepository repository = new HostedTermsRepository(db.dsl()); UUID scopeId = UUID.randomUUID(); UUID requestId = UUID.randomUUID(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java index 1e92f957c0..86b05dc0d9 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java @@ -67,7 +67,7 @@ class HostedTermsEnvironmentBindingPostgresIntegrationTest { @Test void realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersions() throws Exception { - Database db = database("95"); + Database db = database("97"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -260,7 +260,7 @@ void realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersion @Test void bindingUpdateWaitsForExactTerminalSettlementOfAffectedDraftOperation() throws Exception { - Database db = database("95"); + Database db = database("97"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -348,7 +348,7 @@ void bindingUpdateWaitsForExactTerminalSettlementOfAffectedDraftOperation() thro @Test void boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline() throws Exception { - Database db = database("95"); + Database db = database("97"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java index ab51eeb0da..2e58f1dd11 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/PublishAttempt.java @@ -8,6 +8,7 @@ @Data public class PublishAttempt { private Long id; + private Long revision; private String tenantId; private String publishWorkflowId; private PublishType publishType; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java index 2776b9394d..d00a16b4b4 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java @@ -24,7 +24,10 @@ justification = "Injected DSLContext is an internal Spring collaborator.") public class PublishAttemptRepository { private static final Table PUBLISH_ATTEMPT_TABLE = DSL.table(DSL.name("publish_attempt")); + private static final Table AUTHORED_PUBLISH_SELECTION_TABLE = + DSL.table(DSL.name("game_design_authored_draft_publish_selection")); private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field REVISION = DSL.field(DSL.name("revision"), Long.class); private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); private static final Field PUBLISH_WORKFLOW_ID = DSL.field(DSL.name("publish_workflow_id"), String.class); @@ -48,6 +51,10 @@ public class PublishAttemptRepository { DSL.field(DSL.name("created_at"), Timestamp.class); private static final Field COMPLETED_AT = DSL.field(DSL.name("completed_at"), Timestamp.class); + private static final Field SELECTION_TENANT_ID = + DSL.field(DSL.name("game_design_version_tenant_key"), String.class); + private static final Field SELECTION_VERSION_ID = + DSL.field(DSL.name("game_design_version_row_id"), Long.class); private final DSLContext dsl; @@ -121,8 +128,9 @@ private void requireTerminalOperation(PublishAttempt attempt, String outcome) { * Installs a compatibility digest only once, and only on the exact legacy full-version row whose * identity was validated by the caller. * - *

The conditional update makes concurrent retries idempotent: the first writer installs the - * digest and later writers can only read the already-installed value. It deliberately does not + *

The conditional update makes concurrent retries idempotent: it advances the attempt revision + * and installs the digest only while the exact attempt remains pending, unselected, and + * digestless; later writers can only read the already-installed value. It deliberately does not * derive or replace a digest for any other attempt shape. */ public Optional backfillFullVersionRequestDigestIfAbsent( @@ -144,13 +152,40 @@ public Optional backfillFullVersionRequestDigestIfAbsent( .and(VERSION_NUMBER.eq(versionNumber)); dsl.update(PUBLISH_ATTEMPT_TABLE) .set(REQUEST_DIGEST, requestDigest) - .where(fullVersionAttemptIdentity.and(REQUEST_DIGEST.isNull())) + .set(REVISION, REVISION.add(1L)) + .where( + fullVersionAttemptIdentity + .and(STATUS.eq(PublishAttemptStatus.PENDING.name())) + .and(REQUEST_DIGEST.isNull()) + .and(REVISION.lt(Long.MAX_VALUE)) + .and( + DSL.notExists( + DSL.selectOne() + .from(AUTHORED_PUBLISH_SELECTION_TABLE) + .where( + SELECTION_TENANT_ID + .eq(tenantId) + .and(SELECTION_VERSION_ID.eq(versionId)))))) .execute(); - return Optional.ofNullable( + PublishAttempt exactAttempt = dsl.selectFrom(PUBLISH_ATTEMPT_TABLE) .where(fullVersionAttemptIdentity) .limit(1) - .fetchOne(this::toEntity)); + .fetchOne(this::toEntity); + if (exactAttempt == null) { + return Optional.empty(); + } + if (exactAttempt.getRequestDigest() != null) { + return Optional.of(exactAttempt); + } + if (exactAttempt.getStatus() != PublishAttemptStatus.PENDING + || isSelectedAttempt(tenantId, versionId)) { + return Optional.empty(); + } + if (Long.valueOf(Long.MAX_VALUE).equals(exactAttempt.getRevision())) { + throw new IllegalStateException("publish attempt revision exhausted"); + } + return Optional.empty(); } public PublishAttempt save(PublishAttempt attempt) { @@ -176,23 +211,46 @@ public PublishAttempt save(PublishAttempt attempt) { .fetchOne(); return toEntity(record); } - dsl.update(PUBLISH_ATTEMPT_TABLE) - .set(TENANT_ID, attempt.getTenantId()) - .set(PUBLISH_WORKFLOW_ID, attempt.getPublishWorkflowId()) - .set(PUBLISH_TYPE, attempt.getPublishType().name()) - .set(STATUS, attempt.getStatus().name()) - .set(VERSION_ID, attempt.getVersionId()) - .set(VERSION_NUMBER, attempt.getVersionNumber()) - .set(SCRIPT_PATCH_VERSION, attempt.getScriptPatchVersion()) - .set(BASE_VERSION_ID, attempt.getBaseVersionId()) - .set(REQUEST_DIGEST, attempt.getRequestDigest()) - .set(FAILURE_CODE, attempt.getFailureCode()) - .set(FAILURE_MESSAGE, attempt.getFailureMessage()) - .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) - .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) - .where(ID.eq(attempt.getId())) - .execute(); - return findByPublishWorkflowId(attempt.getPublishWorkflowId()).orElseThrow(); + Long expectedRevision = attempt.getRevision(); + if (attempt.getStatus() == null || expectedRevision == null || expectedRevision <= 0) { + throw new IllegalStateException("publish attempt is stale or terminal"); + } + if (expectedRevision == Long.MAX_VALUE) { + throw new IllegalStateException("publish attempt revision exhausted"); + } + Record updated = + dsl.update(PUBLISH_ATTEMPT_TABLE) + .set(TENANT_ID, attempt.getTenantId()) + .set(PUBLISH_WORKFLOW_ID, attempt.getPublishWorkflowId()) + .set(PUBLISH_TYPE, attempt.getPublishType().name()) + .set(STATUS, attempt.getStatus().name()) + .set(VERSION_ID, attempt.getVersionId()) + .set(VERSION_NUMBER, attempt.getVersionNumber()) + .set(SCRIPT_PATCH_VERSION, attempt.getScriptPatchVersion()) + .set(BASE_VERSION_ID, attempt.getBaseVersionId()) + .set(REQUEST_DIGEST, attempt.getRequestDigest()) + .set(FAILURE_CODE, attempt.getFailureCode()) + .set(FAILURE_MESSAGE, attempt.getFailureMessage()) + .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) + .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) + .set(REVISION, REVISION.add(1L)) + .where( + ID.eq(attempt.getId()) + .and(REVISION.eq(expectedRevision)) + .and(STATUS.eq(PublishAttemptStatus.PENDING.name()))) + .returning() + .fetchOne(); + if (updated == null) { + throw new IllegalStateException("publish attempt is stale or terminal"); + } + return toEntity(updated); + } + + private boolean isSelectedAttempt(String tenantId, Long versionId) { + return dsl.fetchExists( + DSL.selectOne() + .from(AUTHORED_PUBLISH_SELECTION_TABLE) + .where(SELECTION_TENANT_ID.eq(tenantId).and(SELECTION_VERSION_ID.eq(versionId)))); } private PublishAttempt toEntity(Record record) { @@ -201,6 +259,7 @@ private PublishAttempt toEntity(Record record) { } PublishAttempt attempt = new PublishAttempt(); attempt.setId(record.get(ID)); + attempt.setRevision(record.get(REVISION)); attempt.setTenantId(record.get(TENANT_ID)); attempt.setPublishWorkflowId(record.get(PUBLISH_WORKFLOW_ID)); String publishType = record.get(PUBLISH_TYPE); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java index 84185929fa..f4d6df9c29 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishAttemptServiceImpl.java @@ -17,6 +17,7 @@ import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.service.PublishAttemptService; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -46,7 +47,7 @@ public T executeScriptPatchTransaction(Supplier operation) { } @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) + @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED) public T executeFullVersionTransaction(Supplier operation) { try { return operation.get(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java index 8577af395e..9764d3174c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java @@ -397,7 +397,7 @@ void rollbackCannotLeaveFinalAbortTombstoneWithoutItsTerminalOutcome() { @Test void migrationDoesNotInventAccountOutcomesForRetainedStatusOnlyRows() { Fixture legacy = createFixture(MigrationVersion.fromVersion("45")); - TargetProof target = legacy.newTarget(); + TargetProof target = legacy.newHistoricalTarget(); DraftCommitBinding binding = binding(target); List outcomes = allAppliedOutcomes(binding); @@ -753,6 +753,43 @@ TargetProof newTarget() { savedVersion.getIdentitySourceProvenanceKind()); } + TargetProof newHistoricalTarget() { + String tenantKey = "d-" + UUID.randomUUID().toString().replace("-", ""); + Game game = new Game(); + game.setTenantId(tenantKey); + game.setName("Historical Game Design terminal evidence source"); + game.setDescription("V45 canonical Version owner fixture"); + Game savedGame = Objects.requireNonNull(transaction.execute(status -> games.save(game))); + UUID canonicalVersionId = UUID.randomUUID(); + org.jooq.Record savedVersion = + Objects.requireNonNull( + transaction.execute( + status -> + dsl.resultQuery( + "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind, version_number, version_state, " + + "version_state_epoch, script_patch_version, base_version_id, " + + "is_script_only, notes) SELECT g.tenant_id, ?, g.canonical_tenant_id, " + + "g.id, g.tenant_id, g.tenant_identity_provenance_kind, 1, 'DRAFT', " + + "1, NULL, NULL, FALSE, ? FROM game g WHERE g.id = ? RETURNING " + + "id, tenant_id, canonical_tenant_id, canonical_version_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind", + canonicalVersionId, + "V45 retained status-only migration fixture", + savedGame.getId()) + .fetchOne())); + return new TargetProof( + savedVersion.get("canonical_tenant_id", UUID.class), + savedVersion.get("canonical_version_id", UUID.class), + savedVersion.get("id", Long.class), + savedVersion.get("tenant_id", String.class), + savedVersion.get("identity_source_game_row_id", Long.class), + savedVersion.get("identity_source_game_tenant_key", String.class), + savedVersion.get("identity_source_provenance_kind", String.class)); + } + T inTransaction(Supplier action) { return transaction.execute(status -> action.get()); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 53367c29d4..fbe49693e8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -425,10 +425,10 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD assertThat(row.get(ARTIFACT_DIGESTS_JSON)).isNull(); }); - Version mappedVersion = saveVersion(fixture, game); migrate(fixture.dataSource(), fixture.schema(), null); assertThat(retainedTuple(fixture.dsl(), retainedBundleId)).isEqualTo(retainedTupleBeforeV38); assertThat(bundleXmin(fixture.dsl(), retainedBundleId)).isEqualTo(retainedXminBeforeV38); + Version mappedVersion = saveVersion(fixture, game); PublishedReleaseBundle mapped = fixture.releaseBundleRepository().save(bundle(game.getTenantId(), mappedVersion.getId())); Map mappedTupleBefore = releaseBundleTuple(fixture.dsl(), mapped.getId()); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 532f2479f9..07889b6463 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -187,6 +187,7 @@ void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() publishAttemptRepository.save(attempt); PublishAttempt savedAttempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); + assertThat(savedAttempt.getRevision()).isEqualTo(1L); PublishAttempt backfilled = publishAttemptRepository @@ -200,6 +201,18 @@ void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() .orElseThrow(); assertThat(backfilled.getRequestDigest()).isEqualTo("exact-identity-digest"); + assertThat(backfilled.getRevision()).isEqualTo(2L); + PublishAttempt retryReadback = + publishAttemptRepository + .backfillFullVersionRequestDigestIfAbsent( + savedAttempt.getId(), + tenantId, + publishWorkflowId, + savedVersion.getId(), + savedVersion.getVersionNumber(), + "exact-identity-digest") + .orElseThrow(); + assertThat(retryReadback.getRevision()).isEqualTo(2L); assertThat( publishAttemptRepository.backfillFullVersionRequestDigestIfAbsent( savedAttempt.getId(), @@ -212,6 +225,93 @@ void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() PublishAttempt storedAttempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); assertThat(storedAttempt.getRequestDigest()).isEqualTo("exact-identity-digest"); + + String terminalWorkflowId = "terminal-digest-backfill-denial-integration-test"; + PublishAttempt terminalAttempt = new PublishAttempt(); + terminalAttempt.setTenantId(tenantId); + terminalAttempt.setPublishWorkflowId(terminalWorkflowId); + terminalAttempt.setPublishType(PublishType.FULL_VERSION); + terminalAttempt.setVersionId(savedVersion.getId()); + terminalAttempt.setVersionNumber(savedVersion.getVersionNumber()); + publishAttemptRepository.save(terminalAttempt); + terminalAttempt = + publishAttemptRepository.findByPublishWorkflowId(terminalWorkflowId).orElseThrow(); + terminalAttempt.setStatus(PublishAttemptStatus.FAILED); + terminalAttempt.setFailureCode("fixture-terminal"); + terminalAttempt.setCompletedAt(LocalDateTime.now()); + terminalAttempt = publishAttemptRepository.save(terminalAttempt); + assertThat(terminalAttempt.getRevision()).isEqualTo(2L); + assertThat( + publishAttemptRepository.backfillFullVersionRequestDigestIfAbsent( + terminalAttempt.getId(), + tenantId, + terminalWorkflowId, + savedVersion.getId(), + savedVersion.getVersionNumber(), + "terminal-must-not-install-digest")) + .isEmpty(); + PublishAttempt retainedTerminalAttempt = + publishAttemptRepository.findByPublishWorkflowId(terminalWorkflowId).orElseThrow(); + assertThat(retainedTerminalAttempt.getRequestDigest()).isNull(); + assertThat(retainedTerminalAttempt.getRevision()).isEqualTo(2L); + } + + @Test + void publishAttemptSaveUsesRevisionCasAndRejectsStaleAndTerminalUpdates() { + String tenantId = "9005"; + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("publish-attempt-revision-proof-game"); + gameRepository.save(game); + + Version version = new Version(); + version.setTenantId(tenantId); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + Version savedVersion = versionRepository.save(version); + + PublishAttempt attempt = new PublishAttempt(); + attempt.setTenantId(tenantId); + attempt.setPublishWorkflowId("publish-attempt-revision-cas-integration-test"); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(savedVersion.getId()); + attempt.setVersionNumber(savedVersion.getVersionNumber()); + PublishAttempt inserted = publishAttemptRepository.save(attempt); + assertThat(inserted.getRevision()).isEqualTo(1L); + + PublishAttempt firstWriter = + publishAttemptRepository + .findByPublishWorkflowId(attempt.getPublishWorkflowId()) + .orElseThrow(); + PublishAttempt staleWriter = + publishAttemptRepository + .findByPublishWorkflowId(attempt.getPublishWorkflowId()) + .orElseThrow(); + firstWriter.setFailureMessage("first revision writer"); + firstWriter = publishAttemptRepository.save(firstWriter); + assertThat(firstWriter.getRevision()).isEqualTo(2L); + + staleWriter.setFailureMessage("stale revision writer"); + assertThatThrownBy(() -> publishAttemptRepository.save(staleWriter)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or terminal"); + PublishAttempt afterStaleWrite = + publishAttemptRepository + .findByPublishWorkflowId(attempt.getPublishWorkflowId()) + .orElseThrow(); + assertThat(afterStaleWrite.getRevision()).isEqualTo(2L); + assertThat(afterStaleWrite.getFailureMessage()).isEqualTo("first revision writer"); + + afterStaleWrite.setStatus(PublishAttemptStatus.FAILED); + afterStaleWrite.setFailureCode("terminal-revision-proof"); + afterStaleWrite.setCompletedAt(LocalDateTime.now()); + PublishAttempt terminal = publishAttemptRepository.save(afterStaleWrite); + assertThat(terminal.getRevision()).isEqualTo(3L); + terminal.setFailureMessage("terminal rows cannot be rewritten"); + assertThatThrownBy(() -> publishAttemptRepository.save(terminal)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or terminal"); } @Test @@ -269,6 +369,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth .orElseThrow(); assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.SUCCEEDED); + assertThat(attempt.getRevision()).isGreaterThan(1L); assertThat(attempt.getVersionId()).isEqualTo(publishedVersion.id()); assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.PUBLISHED); assertThat(bundle.getPublishWorkflowId()).isEqualTo(publishWorkflowId); @@ -419,6 +520,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( .as("asset export uses the candidate's persisted version number") .isEqualTo(candidateVersionNumber.get()); assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(attempt.getRevision()).isGreaterThan(1L); assertThat(attempt.getFailureMessage()).isEqualTo("forced finalization failure"); Version retainedCandidate = versionRepository.findByTenantIdAndId(tenantId, candidateVersionId.get()).orElseThrow(); From 7edc00417de9be3f4b1c6f592471c40d49eb8696 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 22:46:36 +1300 Subject: [PATCH 006/129] Compose existing Account creator sources in owner transaction --- .../microservices/account-service/README.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 +- .../AccountDraftSourceCompositionService.java | 224 +++++++++++ .../IndividualCreatorPartyRepository.java | 41 ++ ...ronmentBindingPostgresIntegrationTest.java | 321 ++++++++++++++- ...ountDraftSourceCompositionServiceTest.java | 375 ++++++++++++++++++ .../IndividualCreatorPartyRepositoryTest.java | 34 +- 7 files changed, 994 insertions(+), 5 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionServiceTest.java diff --git a/design/architecture/microservices/account-service/README.md b/design/architecture/microservices/account-service/README.md index 084cafc2a4..fe8f70dfc7 100644 --- a/design/architecture/microservices/account-service/README.md +++ b/design/architecture/microservices/account-service/README.md @@ -9,7 +9,7 @@ Manages user accounts and authentication for the platform. It stores profile dat - Provider-specific external identity linking is target-state only; no provider is advertised until its server-verified authorization, global subject uniqueness, recovery, unlink, and end-to-end login proof are complete. - The caller-asserted external-link persistence/service scaffold remains unsupported implementation drift, but its REST route is removed and the exact legacy public-edge path is denied. No provider integration is advertised or externally available. - Credential-bearing gameplay `Authenticate` and its verified-email challenge authenticate global Account identity without a tenant or membership prerequisite. The resulting private delegation token is account-scoped; Game Session retains any bootstrap tenant only as local transport context, and selected-target membership, grant, and entitlement remain separate `JOIN`/`PLAY` checks. -- Account is the target authority for the hosted Creator Party, identified operator and hosted-terms catalog, and acceptance/currentness evidence under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md); changed-term notice, decline, continuity, and lifecycle consequences are separately governed by [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These hosted-terms contracts are target-only: no current party/signer registry, terms catalog, acceptance or transfer API/storage, creator UI, or downstream write-gate proof exists, and organization support is not enabled. +- Account is the authority for the hosted Creator Party, identified operator and hosted-terms catalog, and acceptance/currentness evidence under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md); changed-term notice, decline, continuity, and lifecycle consequences are separately governed by [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Bounded individual-party, catalog, acceptance and environment-binding owner storage exists, but its presence does not enable a hosted service or authorized content writes. Production authority integration, transfer, organization support, creator UI and downstream commit-gate proof remain incomplete; the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md) records the implemented boundary and proof limits. - Future managed-creator-commerce financial/provider reconciliation and entitlement authority are a separate target-only boundary under [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md); it does not expand hosted-terms acceptance/currentness authority or enable marketplace commerce, and no marketplace route or payout workflow is enabled. ### Responsibilities 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 df5cae8a26..5e8e9ce393 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 @@ -10,7 +10,7 @@ This tracker consolidates Game Design authoring, settings, publication, release Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. -Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These links do not change current capability ratings or imply an operative hosted service. +Official-hosted creator-content acceptance remains partial under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Account's individual-party and hosted-terms repositories now retain exact catalog, affirmative-acceptance and environment-binding operations; `AccountHostedTermsService` can resolve the external environment observation before SQL work and reread locked currentness in a caller-owned writable `READ_COMMITTED` transaction. The service and its trusted publication, environment and affirmative-action participants remain unregistered; current creator authentication and original multi-owner commit enforcement are not supplied by these storage APIs. `HostedTermsEnvironmentBindingPostgresIntegrationTest` exercises explicitly test-only authorities, not a real agreement or operative hosted service. Composed-head PostgreSQL execution, live authority provisioning, creator UI, transfer and organization workflows remain separate proof or implementation gaps. These foundations do not upgrade the broader capability ratings or authorize content writes. ### Fresh-tenant identity prerequisite diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionService.java new file mode 100644 index 0000000000..d7a5c33684 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionService.java @@ -0,0 +1,224 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.InitialAssociationReadback; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.EnvironmentBoundCurrentness; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Account existing-source composition. No caller authentication, source provisioning, + * Draft reservation, commit order or owner mutation is provided. The caller retains its transaction + * through the intended local use; the returned observation cannot authorize a later commit. + */ +public final class AccountDraftSourceCompositionService { + private static final String ISSUER = "firemud-account-service"; + private final DSLContext dsl; + private final IndividualCreatorPartyRepository parties; + private final AccountTenantCreationBootstrapService memberships; + private final AccountHostedTermsService terms; + private final AccountAuthoritySourceEvidenceRepository upstream; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner transaction collaborators are retained privately.") + public AccountDraftSourceCompositionService( + DSLContext dsl, + IndividualCreatorPartyRepository parties, + AccountTenantCreationBootstrapService memberships, + AccountHostedTermsService terms, + AccountAuthoritySourceEvidenceRepository upstream) { + this.dsl = Objects.requireNonNull(dsl); + this.parties = Objects.requireNonNull(parties); + this.memberships = Objects.requireNonNull(memberships); + this.terms = Objects.requireNonNull(terms); + this.upstream = Objects.requireNonNull(upstream); + } + + /** The environment observation must have been obtained outside this owner transaction. */ + public ExistingSources readExistingSources( + CapturedEnvironmentBoundary environment, UUID canonicalTenantId) { + requireOwnerTransaction(); + Objects.requireNonNull(environment, "Owner-captured environment boundary required"); + if (canonicalTenantId == null || canonicalTenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical tenant UUID required"); + } + var scope = parties.lockExistingInitialAssociationScope(canonicalTenantId); + if (!canonicalTenantId.equals(scope.tenantId())) { + throw mismatch(); + } + var membership = + memberships.readExistingCreatorControlCaptureSources(scope.accountId(), canonicalTenantId); + if (!scope.accountId().equals(membership.accountUuid()) + || !canonicalTenantId.equals(membership.tenantUuid())) { + throw mismatch(); + } + // Preserve independently verified sequence-zero birth evidence as well as positive events. + var issuerAccount = upstream.readCurrentIssuerAccountSources(ISSUER, scope.accountId()); + requireUpstream(membership, issuerAccount); + var currentTerms = + terms.requireCurrentnessInOwnerTransaction(environment, scope.creatorPartyId()); + if (!scope.accountId().equals(currentTerms.terms().accountId()) + || !scope.creatorPartyId().equals(currentTerms.terms().creatorPartyId())) { + throw mismatch(); + } + var association = parties.readExistingInitialAssociation(canonicalTenantId); + var creator = association.creatorEvidence(); + var bootstrap = membership.bootstrapReceipt(); + if (!canonicalTenantId.equals(association.receipt().tenantId()) + || !scope.associationRequestId().equals(association.receipt().requestId()) + || !scope.creatorPartyId().equals(association.receipt().creatorPartyId()) + || !scope.accountId().equals(creator.initiatingAccountId()) + || !membership.creationSource().equals(creator.creationEvidence()) + || !creator.accountAuthorizationOperationId().equals(bootstrap.requestId()) + || !creator + .accountAuthorizationOperationId() + .equals(bootstrap.accountAuthorizationOperationId()) + || !creator.accountAuthorizationDigest().equals(bootstrap.accountAuthorizationDigest()) + || !creator.evidenceDigest().equals(bootstrap.creatorEvidenceDigest()) + || !Arrays.equals( + CreatorPartyEncoding.creation(creator), bootstrap.creatorEvidencePayload()) + || currentTerms.sourceEvidence().stream() + .filter(source -> source.kind() == SourceKind.CREATOR_PARTY) + .noneMatch( + source -> + source.scopeId().equals(association.partySource().creatorPartyId().toString()) + && Objects.equals( + source.generation(), + Long.toString(association.partySource().identityVersion())) + && source + .sourceVersion() + .equals(Long.toString(association.partySource().sourceVersion())) + && Arrays.equals( + source.evidence(), + CreatorPartyEncoding.party(association.partySource())))) { + throw mismatch(); + } + return new ExistingSources(membership, issuerAccount, association, currentTerms); + } + + private void requireUpstream( + CreatorControlCaptureSources membership, IssuerAccountSourceSnapshot source) { + var authority = membership.authoritySnapshot(); + if (!AuthorityScope.issuer(ISSUER).equals(source.issuer().scope()) + || !AuthorityScope.account(membership.accountUuid()).equals(source.account().scope()) + || !authority.issuanceFence().equals(source.issuanceFence()) + || !membership.issuanceFence().equals(Long.toString(source.issuanceFence().value()))) { + throw mismatch(); + } + requireSource( + membership, + authority.issuer(), + source.issuer(), + Objects.requireNonNull(source.canonicalIssuerProjection()).sourceEvent()); + requireSource( + membership, + authority.account(), + source.account(), + Objects.requireNonNull(source.canonicalAccountProjection()).sourceEvent()); + } + + private void requireSource( + CreatorControlCaptureSources membership, + ScopeState state, + CurrentSourceEvidence source, + Optional event) { + var checkpoint = source.checkpoint(); + var checkpoints = + membership.outboxCheckpoints().stream() + .filter(value -> value.outboxStreamKey().equals(checkpoint.outboxStreamKey())) + .toList(); + var events = + membership.outboxSourceEvidence().stream() + .filter(value -> value.outboxStreamKey().equals(checkpoint.outboxStreamKey())) + .toList(); + if (!state.scope().equals(source.scope()) + || state.generation() != source.generation() + || state.sourceVersion() != source.sourceVersion() + || !Objects.equals(state.issuanceFence(), source.issuanceFence()) + || checkpoints.size() != 1 + || !checkpoints.get(0).outboxSequence().equals(Long.toString(checkpoint.sequence())) + || (checkpoint.sequence() == 0L + ? !events.isEmpty() || event.isPresent() + : events.size() != 1 + || event.isEmpty() + || !events.get(0).outboxSequence().equals(Long.toString(checkpoint.sequence())) + || !events.get(0).eventId().equals(checkpoint.sourceEventId().orElseThrow()) + || !events.get(0).eventDigest().equals(checkpoint.sourceEventDigest().orElseThrow()) + || !events.get(0).canonicalEventJson().equals(event.orElseThrow()))) { + throw mismatch(); + } + } + + private void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable READ_COMMITTED Account transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable READ_COMMITTED Account transaction required"); + } + }); + } + + private static IllegalStateException mismatch() { + return new IllegalStateException( + "Existing Account creator source identities or currentness differ"); + } + + /** Immutable existing owner observations only; no authenticated actor or commit permission. */ + public static final class ExistingSources { + private final CreatorControlCaptureSources membership; + private final IssuerAccountSourceSnapshot issuerAccount; + private final InitialAssociationReadback association; + private final EnvironmentBoundCurrentness hostedTerms; + + private ExistingSources( + CreatorControlCaptureSources membership, + IssuerAccountSourceSnapshot issuerAccount, + InitialAssociationReadback association, + EnvironmentBoundCurrentness hostedTerms) { + this.membership = membership; + this.issuerAccount = issuerAccount; + this.association = association; + this.hostedTerms = hostedTerms; + } + + public CreatorControlCaptureSources membership() { + return membership; + } + + public IssuerAccountSourceSnapshot issuerAccount() { + return issuerAccount; + } + + public InitialAssociationReadback association() { + return association; + } + + public EnvironmentBoundCurrentness hostedTerms() { + return hostedTerms; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java index c8bc8618f1..329f1248be 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepository.java @@ -250,6 +250,47 @@ public InitialAssociationReadback readExistingInitialAssociation(UUID tenantUuid return new InitialAssociationReadback(creator, receipt, party); } + /** + * Locks only the canonical tenant claim and derives candidate identities from existing owner + * rows. Bootstrap and party locks are deliberately deferred so a composer can acquire Account + * sources and the environment head first. The complete association must subsequently be read back + * with {@link #readExistingInitialAssociation(UUID)} in this same transaction. + */ + public InitialAssociationScope lockExistingInitialAssociationScope(UUID tenantUuid) { + requireTransaction(); + lockTenant(tenantUuid); + Record association = + dsl.fetchOne( + "SELECT request_id, tenant_uuid, initiating_account_uuid, creator_party_id " + + "FROM account_fresh_creator_party_association_operations WHERE tenant_uuid = ?", + tenantUuid); + if (association == null) { + throw new IllegalStateException( + "Immutable fresh initial creator-party association is absent"); + } + InitialAssociationScope scope = + new InitialAssociationScope( + association.get("tenant_uuid", UUID.class), + association.get("request_id", UUID.class), + association.get("initiating_account_uuid", UUID.class), + association.get("creator_party_id", UUID.class)); + if (!tenantUuid.equals(scope.tenantId())) { + throw new IllegalStateException("Initial association scope differs from canonical tenant"); + } + return scope; + } + + /** Candidate persisted identities only; not authenticated caller or association proof. */ + public record InitialAssociationScope( + UUID tenantId, UUID associationRequestId, UUID accountId, UUID creatorPartyId) { + public InitialAssociationScope { + CreatorPartyEncoding.requireUuid(tenantId); + CreatorPartyEncoding.requireUuid(associationRequestId); + CreatorPartyEncoding.requireUuid(accountId); + CreatorPartyEncoding.requireUuid(creatorPartyId); + } + } + /** This slice never provides commit-bound party/terms authorization. */ public void requireHostedAuthoringCurrentness() { throw new IllegalStateException( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java index 86b05dc0d9..8ca006c193 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java @@ -2,6 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.awaitility.Awaitility.await; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; import java.nio.charset.StandardCharsets; import java.sql.Connection; @@ -15,6 +19,12 @@ import java.util.Map; import java.util.Objects; 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 java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; @@ -28,6 +38,7 @@ import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingEncoding; import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingRepository; import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.hostedterms.IndividualHostedTermsAcceptance; import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; @@ -393,7 +404,10 @@ void boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline() throws "test-only scheduled terms".getBytes(StandardCharsets.UTF_8), HostedTermsCatalogVersion.Materiality.MATERIAL, deadline)); - HostedTermsCatalogVersion scheduled = service.publish(scheduledRequest).candidate(); + var scheduledPublication = service.publish(scheduledRequest); + assertThat(scheduledPublication.status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.SCHEDULED); + HostedTermsCatalogVersion scheduled = scheduledPublication.candidate(); var currentness = service.requireCurrentnessForCurrentEnvironment(partyId); var sameTransactionCurrentness = @@ -423,6 +437,243 @@ void boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline() throws }); } + @Test + void capturedEnvironmentDoesNotExemptCurrentnessAfterScheduledDeadline() throws Exception { + Database db = database("97"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + AtomicReference boundary = + new AtomicReference<>(currentBoundary("expired-deadline-test-environment")); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary); + + UUID initialRequest = UUID.randomUUID(); + catalogPublications.put( + initialRequest, + publication( + scopeId, + "test-only current terms for deadline proof".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.INITIAL, + databaseNow(db).minusSeconds(10))); + HostedTermsCatalogVersion currentCatalog = service.publish(initialRequest).candidate(); + UUID acceptanceRequest = UUID.randomUUID(); + actions.put(acceptanceRequest, action(acceptanceRequest, accountId, partyId, currentCatalog)); + IndividualHostedTermsAcceptance acceptance = service.accept(acceptanceRequest); + + UUID bindingRequest = UUID.randomUUID(); + bindingPublications.put( + bindingRequest, + bindingEvidence( + "expired-deadline-test-environment", + currentCatalog, + null, + null, + "test-only-publisher")); + service.publishEnvironmentBinding(bindingRequest); + + var capturedBoundary = service.captureCurrentEnvironmentBoundary(); + Instant deadline = databaseNow(db).plus(5, ChronoUnit.SECONDS).truncatedTo(ChronoUnit.MICROS); + UUID scheduledRequest = UUID.randomUUID(); + catalogPublications.put( + scheduledRequest, + publication( + scopeId, + "test-only scheduled material terms".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.MATERIAL, + deadline)); + var scheduledPublication = service.publish(scheduledRequest); + assertThat(scheduledPublication.status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.SCHEDULED); + HostedTermsCatalogVersion scheduled = scheduledPublication.candidate(); + + var beforeDeadline = service.requireCurrentnessForCurrentEnvironment(partyId); + assertThat(beforeDeadline.binding().catalogVersionId()).isEqualTo(currentCatalog.versionId()); + assertThat(beforeDeadline.terms().acceptanceEvidenceId()).isEqualTo(acceptance.evidenceId()); + assertThat(beforeDeadline.terms().validUntil()).isEqualTo(deadline); + assertThat(beforeDeadline.terms().disclosedDeadline()).isEqualTo(scheduled); + var capturedCurrentnessBeforeDeadline = + db.transactions() + .execute( + ignored -> service.requireCurrentnessInOwnerTransaction(capturedBoundary, partyId)); + assertThat(capturedCurrentnessBeforeDeadline.terms().exactCurrentnessSource()) + .containsExactly(beforeDeadline.terms().exactCurrentnessSource()); + + assertThat(awaitDatabaseTimeAfter(db, deadline)).isAfter(deadline); + assertThatThrownBy( + () -> + db.transactions() + .execute( + ignored -> + service.requireCurrentnessInOwnerTransaction( + capturedBoundary, partyId))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("effective date has arrived"); + + HostedTermsRepository repository = new HostedTermsRepository(db.dsl()); + HostedTermsRepository.PublicationOperation persistedOperation = + db.transactions() + .execute(ignored -> repository.readPublication(scheduledRequest, false).orElseThrow()); + HostedTermsCatalogVersion persistedScheduled = + db.transactions().execute(ignored -> repository.readCandidate(persistedOperation)); + IndividualHostedTermsAcceptance persistedAcceptance = + db.transactions() + .execute( + ignored -> + repository + .readCurrentAcceptance(partyId, scopeId, currentCatalog) + .orElseThrow()); + HostedTermsRepository.ScopeSnapshot scopeAtDeadline = + db.transactions().execute(ignored -> repository.lockScope(scopeId)); + assertThat(persistedOperation.status()) + .isEqualTo(HostedTermsRepository.PublicationStatus.SCHEDULED); + assertThat(HostedTermsEncoding.catalog(persistedScheduled)) + .containsExactly(HostedTermsEncoding.catalog(scheduled)); + assertThat(persistedScheduled.effectiveAt()).isEqualTo(deadline); + assertThat(persistedAcceptance).isEqualTo(acceptance); + assertThat(scopeAtDeadline.current()).isEqualTo(currentCatalog); + assertThat(scopeAtDeadline.unsettledPublication().requestId()).isEqualTo(scheduledRequest); + } + + @Test + void environmentBindingPublisherWaitsUntilCallerOwnedCurrentnessTransactionEnds() + throws Exception { + Database db = database("97"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + AtomicReference boundary = + new AtomicReference<>(currentBoundary("locked-currentness-test-environment")); + AtomicBoolean capturePublisherBackendPid = new AtomicBoolean(); + AtomicReference publisherBackendPid = new AtomicReference<>(); + CountDownLatch publisherAtHeadLock = new CountDownLatch(1); + HostedTermsEnvironmentBindingRepository bindingRepository = + spy(new HostedTermsEnvironmentBindingRepository(db.dsl())); + doAnswer( + invocation -> { + if (capturePublisherBackendPid.compareAndSet(true, false)) { + publisherBackendPid.set(currentBackendPid(db)); + publisherAtHeadLock.countDown(); + } + return invocation.callRealMethod(); + }) + .when(bindingRepository) + .lockHead(anyString()); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary, bindingRepository); + + UUID termsRequest = UUID.randomUUID(); + catalogPublications.put( + termsRequest, + publication( + scopeId, + "test-only terms for owner lock proof".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.INITIAL, + databaseNow(db).minusSeconds(10))); + HostedTermsCatalogVersion catalog = service.publish(termsRequest).candidate(); + UUID acceptanceRequest = UUID.randomUUID(); + actions.put(acceptanceRequest, action(acceptanceRequest, accountId, partyId, catalog)); + IndividualHostedTermsAcceptance acceptance = service.accept(acceptanceRequest); + + UUID firstBindingRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence firstEvidence = + bindingEvidence( + "locked-currentness-test-environment", catalog, null, null, "test-only-publisher-v1"); + bindingPublications.put(firstBindingRequest, firstEvidence); + var firstBinding = service.publishEnvironmentBinding(firstBindingRequest); + assertThat(firstBinding.status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + + var capturedBoundary = service.captureCurrentEnvironmentBoundary(); + UUID secondBindingRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence secondEvidence = + bindingEvidence( + "locked-currentness-test-environment", + catalog, + firstBinding.candidate().bindingId(), + firstBinding.candidate().sourceVersion(), + "test-only-publisher-v2"); + bindingPublications.put(secondBindingRequest, secondEvidence); + + CountDownLatch currentnessLocksHeld = new CountDownLatch(1); + CountDownLatch releaseOwnerTransaction = new CountDownLatch(1); + AtomicReference ownerBackendPid = new AtomicReference<>(); + AtomicReference heldCurrentness = + new AtomicReference<>(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future ownerTransaction = + executor.submit( + () -> + db.transactions() + .executeWithoutResult( + ignored -> { + heldCurrentness.set( + service.requireCurrentnessInOwnerTransaction( + capturedBoundary, partyId)); + ownerBackendPid.set(currentBackendPid(db)); + currentnessLocksHeld.countDown(); + awaitLatch(releaseOwnerTransaction, "owner transaction release"); + })); + + awaitLatch(currentnessLocksHeld, "currentness locks acquisition"); + assertThat(heldCurrentness.get().binding()).isEqualTo(firstBinding.candidate()); + assertThat(heldCurrentness.get().terms().acceptanceEvidenceId()) + .isEqualTo(acceptance.evidenceId()); + + capturePublisherBackendPid.set(true); + Future publisher = + executor.submit(() -> service.publishEnvironmentBinding(secondBindingRequest)); + awaitLatch(publisherAtHeadLock, "publisher backend PID capture at environment head lock"); + int exactPublisherPid = Objects.requireNonNull(publisherBackendPid.get()); + awaitPublisherBlockedByOwner(db, ownerBackendPid.get(), exactPublisherPid); + assertThat(exactPublisherPid).isNotEqualTo(ownerBackendPid.get()); + assertThat(publisher.isDone()).isFalse(); + + releaseOwnerTransaction.countDown(); + ownerTransaction.get(10, TimeUnit.SECONDS); + var secondBinding = publisher.get(10, TimeUnit.SECONDS); + assertThat(secondBinding.status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + assertThat(secondBinding.candidate().sourceVersion()) + .isEqualTo(firstBinding.candidate().sourceVersion() + 1); + assertThat(secondBinding.candidate().predecessorBindingId()) + .isEqualTo(firstBinding.candidate().bindingId()); + assertThat(secondBinding.candidate().catalogVersionId()).isEqualTo(catalog.versionId()); + HostedTermsEnvironmentBinding currentBinding = + db.transactions() + .execute( + ignored -> + service + .requireCurrentnessInOwnerTransaction(capturedBoundary, partyId) + .binding()); + assertThat(currentBinding).isEqualTo(secondBinding.candidate()); + IndividualHostedTermsAcceptance currentAcceptance = + db.transactions() + .execute( + ignored -> + new HostedTermsRepository(db.dsl()) + .readCurrentAcceptance(partyId, scopeId, catalog) + .orElseThrow()); + assertThat(currentAcceptance).isEqualTo(acceptance); + } finally { + releaseOwnerTransaction.countDown(); + executor.shutdownNow(); + } + } + private static DraftAuthorizationFenceBinding testDraftBinding( UUID actorAccountId, List sources) { UUID tenantId = UUID.randomUUID(); @@ -485,6 +736,22 @@ private static AccountHostedTermsService service( Map actions, Map bindingPublications, AtomicReference boundary) { + return service( + db, + catalogPublications, + actions, + bindingPublications, + boundary, + new HostedTermsEnvironmentBindingRepository(db.dsl())); + } + + private static AccountHostedTermsService service( + Database db, + Map catalogPublications, + Map actions, + Map bindingPublications, + AtomicReference boundary, + HostedTermsEnvironmentBindingRepository bindingRepository) { IndividualCreatorPartyRepository parties = new IndividualCreatorPartyRepository( db.dsl(), @@ -505,7 +772,7 @@ private static AccountHostedTermsService service( return Objects.requireNonNull( actions.get(request), "test-only affirmative action fixture"); }, - new HostedTermsEnvironmentBindingRepository(db.dsl()), + bindingRepository, request -> { assertOutsideOwnerTransaction(); return Objects.requireNonNull( @@ -648,6 +915,56 @@ private static Instant databaseNow(Database db) { .truncatedTo(ChronoUnit.MICROS); } + private static Instant awaitDatabaseTimeAfter(Database db, Instant deadline) { + AtomicReference observed = new AtomicReference<>(); + await() + .atMost(15, TimeUnit.SECONDS) + .pollInterval(50, TimeUnit.MILLISECONDS) + .untilAsserted( + () -> { + Instant databaseInstant = databaseNow(db); + assertThat(databaseInstant).isAfter(deadline); + observed.set(databaseInstant); + }); + return Objects.requireNonNull(observed.get()); + } + + private static void awaitPublisherBlockedByOwner(Database db, int ownerPid, int publisherPid) { + await() + .atMost(10, TimeUnit.SECONDS) + .pollInterval(25, TimeUnit.MILLISECONDS) + .untilAsserted( + () -> { + var blockedSessions = + db.dsl() + .fetch( + "SELECT pid FROM pg_stat_activity " + + "WHERE pid = ? AND state = 'active' " + + "AND strpos(query, 'account_hosted_terms_environment_binding_heads') > 0 " + + "AND ? = ANY(pg_blocking_pids(pid))", + publisherPid, + ownerPid); + assertThat(blockedSessions).hasSize(1); + assertThat(blockedSessions.get(0).get("pid", Integer.class)).isEqualTo(publisherPid); + }); + } + + private static int currentBackendPid(Database db) { + return Objects.requireNonNull(db.dsl().fetchOne("SELECT pg_backend_pid() AS pid")) + .get("pid", Integer.class); + } + + private static void awaitLatch(CountDownLatch latch, String description) { + try { + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new AssertionError("Timed out waiting for " + description); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for " + description, exception); + } + } + private static long count(Database db, String table) { return Objects.requireNonNull(db.dsl().fetchOne("SELECT count(*) AS count FROM " + table)) .get("count", Long.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionServiceTest.java new file mode 100644 index 0000000000..72a32185f7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionServiceTest.java @@ -0,0 +1,375 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +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.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftSourceCompositionService; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.AssociationReceipt; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.InitialAssociationReadback; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.InitialAssociationScope; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CurrentnessEvidence; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.EnvironmentBoundCurrentness; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mock owner-boundary composition proof; physical lock contention requires PostgreSQL proof. */ +class AccountDraftSourceCompositionServiceTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void composesInOwnerOrderAndPreservesSequenceZeroBirthEvidence() throws Exception { + Fixture f = new Fixture(); + var capture = f.read(); + assertThat(capture.membership()).isSameAs(f.membership); + assertThat(capture.issuerAccount()).isSameAs(f.source); + assertThat(capture.association()).isEqualTo(f.association); + assertThat(capture.hostedTerms()).isSameAs(f.currentTerms); + var order = inOrder(f.parties, f.memberships, f.upstream, f.terms); + order.verify(f.parties).lockExistingInitialAssociationScope(f.tenant); + order.verify(f.memberships).readExistingCreatorControlCaptureSources(f.account, f.tenant); + order.verify(f.upstream).readCurrentIssuerAccountSources("firemud-account-service", f.account); + order.verify(f.terms).requireCurrentnessInOwnerTransaction(f.environment, f.partyId); + order.verify(f.parties).readExistingInitialAssociation(f.tenant); + order.verifyNoMoreInteractions(); + } + + @Test + void deniesMissingReadOnlyAutocommitAndWrongPhysicalIsolationBeforeSources() throws Exception { + Fixture f = new Fixture(); + assertThatThrownBy(() -> f.service.readExistingSources(f.environment, f.tenant)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> f.service.readExistingSources(f.environment, f.tenant)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + when(f.connection.getAutoCommit()).thenReturn(true); + f.rejects(); + when(f.connection.getAutoCommit()).thenReturn(false); + when(f.connection.isReadOnly()).thenReturn(true); + f.rejects(); + when(f.connection.isReadOnly()).thenReturn(false); + when(f.connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_REPEATABLE_READ); + f.rejects(); + verifyNoInteractions(f.parties, f.memberships, f.upstream, f.terms); + } + + @Test + void failedMembershipPrerequisiteCannotReachUpstreamTermsOrFinalReadback() throws Exception { + Fixture f = new Fixture(); + when(f.memberships.readExistingCreatorControlCaptureSources(f.account, f.tenant)) + .thenThrow(new IllegalStateException("Absent current membership")); + f.rejects(); + verifyNoInteractions(f.upstream, f.terms); + org.mockito.Mockito.verify(f.parties, org.mockito.Mockito.never()) + .readExistingInitialAssociation(any()); + } + + @Test + void changedAccountSourceAndIssuanceFenceDenyBeforeTerms() throws Exception { + Fixture changedSource = new Fixture(); + when(changedSource.issuer.generation()).thenReturn(2L); + changedSource.rejects(); + verifyNoInteractions(changedSource.terms); + Fixture changedFence = new Fixture(); + when(changedFence.source.issuanceFence()) + .thenReturn(new IssuanceFence(changedFence.account, 2L, 2L)); + changedFence.rejects(); + verifyNoInteractions(changedFence.terms); + } + + @Test + void foreignTermsOwnerDeniesBeforeAssociationReadback() throws Exception { + Fixture f = new Fixture(); + when(f.currentness.accountId()).thenReturn(UUID.randomUUID()); + f.rejects(); + org.mockito.Mockito.verify(f.parties, org.mockito.Mockito.never()) + .readExistingInitialAssociation(any()); + } + + @Test + void changedTenantDeniesBeforeUpstreamOrTerms() throws Exception { + Fixture f = new Fixture(); + when(f.membership.tenantUuid()).thenReturn(UUID.randomUUID()); + f.rejects(); + verifyNoInteractions(f.upstream, f.terms); + } + + @Test + void comparesCollaboratorPositiveEventBytesWithoutClaimingCodecOrProducerProof() + throws Exception { + // Synthetic collaborator event: equality proof only, not a valid owner-event codec fixture. + Fixture f = new Fixture(); + var authority = f.membership.authoritySnapshot(); + String stream = f.issuer.checkpoint().outboxStreamKey(); + String accountStream = f.accountSource.checkpoint().outboxStreamKey(); + String digest = "sha256:" + "b".repeat(64); + when(f.issuer.generation()).thenReturn(2L); + when(f.issuer.sourceVersion()).thenReturn(2L); + when(f.issuer.checkpoint()) + .thenReturn(new SourceCheckpoint(stream, 1L, Optional.of("event"), Optional.of(digest))); + when(f.membership.authoritySnapshot()) + .thenReturn( + new CompositeSnapshot( + new ScopeState(authority.issuer().scope(), 2L, 2L, null), + authority.account(), + authority.tenants(), + authority.memberships(), + authority.issuanceFence())); + when(f.membership.outboxCheckpoints()) + .thenReturn( + List.of( + new OutboxCheckpointEntry(stream, "1"), + new OutboxCheckpointEntry(accountStream, "0"))); + when(f.membership.outboxSourceEvidence()) + .thenReturn( + List.of(new OutboxSourceEvidence(stream, "1", "event", digest, "{\"fixture\":1}"))); + when(f.source.canonicalIssuerProjection().sourceEvent()) + .thenReturn(Optional.of("{\"fixture\":1}")); + assertThat(f.read().issuerAccount()).isSameAs(f.source); + when(f.source.canonicalIssuerProjection().sourceEvent()) + .thenReturn(Optional.of("{\"fixture\":2}")); + f.rejects(); + } + + @Test + void changedAssociationHistoryAndExactPartySourceDeny() throws Exception { + Fixture changedHistory = new Fixture(); + when(changedHistory.parties.readExistingInitialAssociation(changedHistory.tenant)) + .thenReturn( + new InitialAssociationReadback( + changedHistory.creator, + new AssociationReceipt( + UUID.randomUUID(), + changedHistory.tenant, + changedHistory.partyId, + UUID.randomUUID(), + "retained-history"), + changedHistory.party)); + changedHistory.rejects(); + Fixture changedParty = new Fixture(); + when(changedParty.currentTerms.sourceEvidence()) + .thenReturn( + List.of( + new SourceEvidence( + SourceKind.CREATOR_PARTY, + changedParty.partyId.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + changedParty.rejects(); + } + + private static final class Fixture { + private final UUID tenant = UUID.randomUUID(); + private final UUID account = UUID.randomUUID(); + private final UUID partyId = UUID.randomUUID(); + private final UUID request = UUID.randomUUID(); + private final UUID bootstrapId = UUID.randomUUID(); + private final DSLContext dsl = mock(DSLContext.class); + private final Connection connection = mock(Connection.class); + private final IndividualCreatorPartyRepository parties = + mock(IndividualCreatorPartyRepository.class); + private final AccountTenantCreationBootstrapService memberships = + mock(AccountTenantCreationBootstrapService.class); + private final AccountHostedTermsService terms = mock(AccountHostedTermsService.class); + private final AccountAuthoritySourceEvidenceRepository upstream = + mock(AccountAuthoritySourceEvidenceRepository.class); + private final CapturedEnvironmentBoundary environment = mock(CapturedEnvironmentBoundary.class); + private final CreatorControlCaptureSources membership = + mock(CreatorControlCaptureSources.class); + private final IssuerAccountSourceSnapshot source = mock(IssuerAccountSourceSnapshot.class); + private final CurrentSourceEvidence issuer = mock(CurrentSourceEvidence.class); + private final CurrentSourceEvidence accountSource = mock(CurrentSourceEvidence.class); + private final EnvironmentBoundCurrentness currentTerms = + mock(EnvironmentBoundCurrentness.class); + private final CurrentnessEvidence currentness = mock(CurrentnessEvidence.class); + private final IndividualCreatorPartySource party = + new IndividualCreatorPartySource( + partyId, + account, + VerificationStatus.VERIFIED, + 1L, + "policy", + 1L, + "verification", + 1L, + 1L); + private final FreshTenantCreatorEvidence creator; + private final InitialAssociationReadback association; + private final AccountDraftSourceCompositionService service; + + private Fixture() throws Exception { + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_READ_COMMITTED); + doAnswer( + invocation -> { + invocation.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + UUID creationRequest = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + String digest = + GameTenantCreationDigest.requestDigest("test", creationRequest, "game", "Game", null); + var creation = + new FreshTenantCreationEvidence( + 1, + "test", + creationRequest, + operation, + digest, + tenant, + 1L, + "game", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "test", creationRequest, operation, digest, tenant, 1L, "game", "NEW_GAME_ROW")); + String authDigest = "sha256:" + "a".repeat(64); + creator = + new FreshTenantCreatorEvidence( + 1, + creation, + account, + bootstrapId, + authDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, account, bootstrapId, authDigest)); + association = + new InitialAssociationReadback( + creator, + new AssociationReceipt(request, tenant, partyId, UUID.randomUUID(), "history"), + party); + when(parties.lockExistingInitialAssociationScope(tenant)) + .thenReturn(new InitialAssociationScope(tenant, request, account, partyId)); + when(parties.readExistingInitialAssociation(tenant)).thenReturn(association); + when(memberships.readExistingCreatorControlCaptureSources(account, tenant)) + .thenReturn(membership); + when(membership.accountUuid()).thenReturn(account); + when(membership.tenantUuid()).thenReturn(tenant); + when(membership.creationSource()).thenReturn(creation); + var bootstrap = mock(StoredOperation.class); + when(membership.bootstrapReceipt()).thenReturn(bootstrap); + when(bootstrap.requestId()).thenReturn(bootstrapId); + when(bootstrap.accountAuthorizationOperationId()).thenReturn(bootstrapId); + when(bootstrap.accountAuthorizationDigest()).thenReturn(authDigest); + when(bootstrap.creatorEvidenceDigest()).thenReturn(creator.evidenceDigest()); + when(bootstrap.creatorEvidencePayload()).thenReturn(CreatorPartyEncoding.creation(creator)); + var fence = new IssuanceFence(account, 1L, 1L); + var issuerScope = AuthorityScope.issuer("firemud-account-service"); + var accountScope = AuthorityScope.account(account); + when(membership.authoritySnapshot()) + .thenReturn( + new CompositeSnapshot( + new ScopeState(issuerScope, 1L, 1L, null), + new ScopeState(accountScope, 1L, 1L, fence), + List.of(), + List.of(), + fence)); + when(membership.issuanceFence()).thenReturn("1"); + when(source.issuanceFence()).thenReturn(fence); + when(source.issuer()).thenReturn(issuer); + when(source.account()).thenReturn(accountSource); + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + String accountStream = "account:auth-authority:v1:account/" + account; + configureSource(issuer, issuerScope, null, issuerStream); + configureSource(accountSource, accountScope, fence, accountStream); + when(membership.outboxCheckpoints()) + .thenReturn( + List.of( + new OutboxCheckpointEntry(issuerStream, "0"), + new OutboxCheckpointEntry(accountStream, "0"))); + when(membership.outboxSourceEvidence()).thenReturn(List.of()); + var issuerProjection = mock(IssuerGenerationProjection.class); + var accountProjection = mock(AccountGenerationProjection.class); + when(issuerProjection.sourceEvent()).thenReturn(Optional.empty()); + when(accountProjection.sourceEvent()).thenReturn(Optional.empty()); + when(source.canonicalIssuerProjection()).thenReturn(issuerProjection); + when(source.canonicalAccountProjection()).thenReturn(accountProjection); + when(upstream.readCurrentIssuerAccountSources("firemud-account-service", account)) + .thenReturn(source); + when(terms.requireCurrentnessInOwnerTransaction(environment, partyId)) + .thenReturn(currentTerms); + when(currentTerms.terms()).thenReturn(currentness); + when(currentness.accountId()).thenReturn(account); + when(currentness.creatorPartyId()).thenReturn(partyId); + when(currentTerms.sourceEvidence()) + .thenReturn( + List.of( + new SourceEvidence( + SourceKind.CREATOR_PARTY, + partyId.toString(), + "1", + "1", + null, + null, + CreatorPartyEncoding.party(party)))); + service = + new AccountDraftSourceCompositionService(dsl, parties, memberships, terms, upstream); + } + + private void configureSource( + CurrentSourceEvidence value, AuthorityScope scope, IssuanceFence fence, String stream) { + when(value.scope()).thenReturn(scope); + when(value.generation()).thenReturn(1L); + when(value.sourceVersion()).thenReturn(1L); + when(value.issuanceFence()).thenReturn(fence); + when(value.checkpoint()) + .thenReturn(new SourceCheckpoint(stream, 0L, Optional.empty(), Optional.empty())); + } + + private AccountDraftSourceCompositionService.ExistingSources read() { + TransactionSynchronizationManager.setActualTransactionActive(true); + return service.readExistingSources(environment, tenant); + } + + private void rejects() { + assertThatThrownBy(this::read).isInstanceOf(IllegalStateException.class); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java index 0367e93183..5d5abc9c43 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyRepositoryTest.java @@ -8,6 +8,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; @@ -44,6 +45,36 @@ void clearTransactionMarkers() { TransactionSynchronizationManager.clear(); } + @Test + void preparationLocksOnlyTenantAndDerivesExistingCandidateIdentities() { + Fixture fixture = new Fixture(); + beginWritableTransaction(); + var scope = fixture.repository.lockExistingInitialAssociationScope(fixture.tenantId); + assertThat(scope.accountId()).isEqualTo(fixture.accountId); + assertThat(scope.creatorPartyId()).isEqualTo(fixture.party.creatorPartyId()); + assertThat(scope.associationRequestId()).isEqualTo(fixture.associationRequestId); + verifyNoInteractions(fixture.bootstraps, fixture.freshTenants); + verify(fixture.dsl, never()) + .fetchOne( + org.mockito.ArgumentMatchers.contains("account_individual_creator_party_sources"), + any(Object[].class)); + fixture.assertNoWrites(); + } + + @Test + void preparationRejectsMissingIdentityAndAbsentTransaction() { + Fixture fixture = new Fixture(); + assertThatThrownBy( + () -> fixture.repository.lockExistingInitialAssociationScope(fixture.tenantId)) + .isInstanceOf(IllegalStateException.class); + beginWritableTransaction(); + fixture.associationByTenantFields.remove("initiating_account_uuid"); + assertThatThrownBy( + () -> fixture.repository.lockExistingInitialAssociationScope(fixture.tenantId)) + .isInstanceOf(RuntimeException.class); + verifyNoInteractions(fixture.bootstraps, fixture.freshTenants); + } + @Test void derivesAndVerifiesTheExactFreshInitialAssociationFromTenantOwnerRows() { Fixture fixture = new Fixture(); @@ -256,7 +287,8 @@ private Object fetch(org.mockito.invocation.InvocationOnMock invocation) { if (sql.contains("account_canonical_tenant_identity_claims")) { return row(Map.of("identity_kind", "FRESH_GAME_DESIGN")); } - if (sql.contains("WHERE tenant_uuid = ? FOR UPDATE")) { + if (sql.contains("account_fresh_creator_party_association_operations") + && sql.contains("WHERE tenant_uuid = ?")) { return associationByTenant; } if (sql.contains("account_individual_creator_party_sources")) { From 6aaa754bfbf0356245eb0f24055d181b2ba0630b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 22:55:47 +1300 Subject: [PATCH 007/129] Define real Account creator source composition PostgreSQL proof --- .../account-service/api-contracts.md | 2 +- ...rceCompositionPostgresIntegrationTest.java | 537 ++++++++++++++++++ 2 files changed, 538 insertions(+), 1 deletion(-) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionPostgresIntegrationTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 2c67546689..89fde149b4 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ Current explicit JOIN status: the local `/auth/bootstrap/join` controller and op Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. -The hosted Creator Party, terms catalog, acceptance/currentness evidence, and changed-term lifecycle are target-only. No current Account route, proto/schema, storage, signer/transfer operation, creator UI, or focused proof implements them; Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. +Bounded hosted Creator Party, terms-catalog, acceptance/currentness and environment-binding owner storage exists, but no registered hosted-terms API or complete creator-authorized commit path is enabled. The [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md) records the implemented boundary and remaining proof. Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionPostgresIntegrationTest.java new file mode 100644 index 0000000000..6a8151f4c0 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionPostgresIntegrationTest.java @@ -0,0 +1,537 @@ +package integration.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftSourceCompositionService; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftSourceCompositionService.ExistingSources; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronization; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Account owner-row composition and transaction fences. External Game Design creation, + * bootstrap authority, individual verification, legal publication, affirmative action and + * environment observations are explicitly test-only fixtures, not production authorization. No + * owner repository, membership reader, event codec or source readback is mocked. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountDraftSourceCompositionPostgresIntegrationTest { + private static final String NAMESPACE = "draft-source-composition-proof"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void composesRealSourcesAndRereadsTheSameExactExistingEvidence() { + Fixture f = new Fixture(true, true); + CapturedEnvironmentBoundary environment = f.terms.captureCurrentEnvironmentBoundary(); + ExistingSources first = f.tx(() -> f.composer.readExistingSources(environment, f.tenant)); + ExistingSources second = f.tx(() -> f.composer.readExistingSources(environment, f.tenant)); + + assertThat(first.membership().accountUuid()).isEqualTo(f.account); + assertThat(first.membership().tenantUuid()).isEqualTo(f.tenant); + assertThat(first.membership().roleSource().roles()).containsExactly("tenantAdmin"); + assertThat(first.membership().sourceEvent().gameplayAdmissionAllowed()).isFalse(); + assertThat(first.membership().sourceEvent().membershipVersion()) + .isEqualTo(Map.of(f.tenant.toString(), "2")); + assertThat(first.issuerAccount().issuer().checkpoint().sequence()).isZero(); + assertThat(first.issuerAccount().account().checkpoint().sequence()).isZero(); + assertThat(first.issuerAccount().account().accountRepositoryInsertTransactionId()).isPositive(); + assertThat(first.issuerAccount().canonicalAccountProjection().sourceEvent()).isEmpty(); + assertThat(first.issuerAccount().canonicalIssuerProjection().sourceEvent()).isEmpty(); + assertThat(first.membership().issuanceFence()) + .isEqualTo(Long.toString(first.issuerAccount().issuanceFence().value())); + var event = + MembershipAuthorityEventV1Codec.verify(first.membership().sourceEvent().canonicalJson()); + assertThat(event.canonicalJson()).isEqualTo(first.membership().sourceEvent().canonicalJson()); + assertThat(first.association().creatorEvidence()).isEqualTo(f.creator); + assertThat(first.association().partySource()).isEqualTo(f.party); + assertThat(first.hostedTerms().terms().accountId()).isEqualTo(f.account); + assertThat(first.hostedTerms().terms().creatorPartyId()).isEqualTo(f.party.creatorPartyId()); + assertThat(first.hostedTerms().sourceEvidence()).hasSize(3); + + assertThat(second.membership()) + .usingRecursiveComparison() + .ignoringFields("evaluatedAt") + .isEqualTo(first.membership()); + assertThat(second.issuerAccount()).isEqualTo(first.issuerAccount()); + assertThat(second.association()).isEqualTo(first.association()); + assertThat(second.hostedTerms()).usingRecursiveComparison().isEqualTo(first.hostedTerms()); + assertThat(f.count("account_tenant_creator_party_history")).isOne(); + assertThat(f.count("account_fresh_creator_party_association_operations")).isOne(); + assertThat(f.count("account_draft_authorization_fences")).isZero(); + } + + @Test + void missingAssociationAndAcceptanceDenyWithoutCreatingSourcesOrDraftFences() { + Fixture absentAssociation = new Fixture(false, true); + var associationEnvironment = absentAssociation.terms.captureCurrentEnvironmentBoundary(); + assertThatThrownBy( + () -> + absentAssociation.tx( + () -> + absentAssociation.composer.readExistingSources( + associationEnvironment, absentAssociation.tenant))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("association is absent"); + assertThat(absentAssociation.count("account_tenant_creator_party_history")).isZero(); + assertThat(absentAssociation.count("account_fresh_creator_party_association_operations")) + .isZero(); + + Fixture absentAcceptance = new Fixture(true, false); + var acceptanceEnvironment = absentAcceptance.terms.captureCurrentEnvironmentBoundary(); + assertThatThrownBy( + () -> + absentAcceptance.tx( + () -> + absentAcceptance.composer.readExistingSources( + acceptanceEnvironment, absentAcceptance.tenant))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("affirmative"); + assertThat(absentAcceptance.count("account_draft_authorization_fences")).isZero(); + assertThat(absentAcceptance.count("account_tenant_creator_party_history")).isOne(); + } + + @Test + void differentCurrentEnvironmentAndUnsupportedChangedAccountSourceDenyExactReread() { + Fixture f = new Fixture(true, true); + var originalEnvironment = f.terms.captureCurrentEnvironmentBoundary(); + var original = f.tx(() -> f.composer.readExistingSources(originalEnvironment, f.tenant)); + f.boundary.set(testBoundary("different-test-environment")); + var differentEnvironment = f.terms.captureCurrentEnvironmentBoundary(); + assertThatThrownBy( + () -> f.tx(() -> f.composer.readExistingSources(differentEnvironment, f.tenant))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("binding head is unavailable"); + + // The existing generic-save owner emits legacy Account events. Its real generation/fence + // advance must be denied by the closed creator-source reader, not relabeled as current proof. + f.tx( + () -> { + Account account = f.accounts.findByAccountUuidForUpdate(f.account).orElseThrow(); + account.setRole("admin"); + f.accounts.save(account); + return null; + }); + assertThat( + Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT generation FROM account_authority_generations WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + f.account)) + .get("generation", Long.class)) + .isGreaterThan(original.issuerAccount().account().generation()); + assertThatThrownBy( + () -> f.tx(() -> f.composer.readExistingSources(originalEnvironment, f.tenant))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account source event schema is unsupported"); + byte[] retainedCreatorPayload = + f.tx( + () -> + f.operations + .findForUpdate(f.creator.accountAuthorizationOperationId()) + .orElseThrow() + .creatorEvidencePayload()); + assertThat(retainedCreatorPayload) + .containsExactly(original.membership().bootstrapReceipt().creatorEvidencePayload()); + assertThat(f.count("account_draft_authorization_fences")).isZero(); + } + + @Test + void physicalTransactionFencesRejectBeforeReadingAndAccountLockLivesUntilCompletion() { + Fixture f = new Fixture(true, true); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + assertThatThrownBy(() -> f.composer.readExistingSources(environment, f.tenant)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + TransactionTemplate repeatable = new TransactionTemplate(f.manager); + repeatable.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + repeatable.execute( + ignored -> f.composer.readExistingSources(environment, f.tenant))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + TransactionTemplate readOnly = new TransactionTemplate(f.manager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute(ignored -> f.composer.readExistingSources(environment, f.tenant))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + + f.tx( + () -> { + f.composer.readExistingSources(environment, f.tenant); + f.composer.readExistingSources(environment, f.tenant); + assertThatThrownBy(() -> lockAccountOnIndependentConnection(f)) + .isInstanceOf(SQLException.class) + .satisfies( + failure -> assertThat(((SQLException) failure).getSQLState()).isEqualTo("55P03")); + return null; + }); + org.assertj.core.api.Assertions.assertThatCode(() -> lockAccountOnIndependentConnection(f)) + .doesNotThrowAnyException(); + } + + private static void lockAccountOnIndependentConnection(Fixture f) throws SQLException { + try (Connection connection = f.dataSource.getConnection()) { + connection.setAutoCommit(false); + try (Statement statement = connection.createStatement()) { + statement.execute("SET LOCAL lock_timeout = '200ms'"); + try (var query = + connection.prepareStatement( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE")) { + query.setObject(1, f.account); + try (var rows = query.executeQuery()) { + assertThat(rows.next()).isTrue(); + } + } + } finally { + connection.rollback(); + } + } + } + + private static final class Fixture { + private final DriverManagerDataSource dataSource; + private final DataSourceTransactionManager manager; + private final TransactionTemplate transactions; + private final DSLContext dsl; + private final AccountRepository accounts; + private final AccountTenantCreationBootstrapOperationRepository operations; + private final UUID account; + private final UUID tenant = UUID.randomUUID(); + private final FreshTenantCreatorEvidence creator; + private final IndividualCreatorPartySource party; + private final AtomicReference + boundary = new AtomicReference<>(testBoundary("test-production")); + private final AccountHostedTermsService terms; + private final AccountDraftSourceCompositionService composer; + + private Fixture(boolean associate, boolean accept) { + String schema = "draft_source_" + UUID.randomUUID().toString().replace("-", ""); + dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + manager = new DataSourceTransactionManager(dataSource); + transactions = new TransactionTemplate(manager); + transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sources = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + accounts = new AccountRepository(dsl, sources); + account = + tx( + () -> { + Account candidate = new Account(); + String suffix = UUID.randomUUID().toString(); + candidate.setUsername("draft-" + suffix); + candidate.setEmail("draft-" + suffix + "@example.test"); + candidate.setPasswordHash("test-only-hash"); + return accounts.save(candidate).getAccountUuid(); + }); + creator = testCreation(account, tenant); + var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + tx( + () -> { + fresh.importVerified(creator.creationEvidence()); + generations.initializeTenantIfAbsent(tenant); + return null; + }); + var pairs = new AccountMembershipPairAuthorityRepository(dsl); + var memberships = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + operations = new AccountTenantCreationBootstrapOperationRepository(dsl); + var sourceReader = + new AccountCreatorMembershipSourceReader( + accounts, + new AccountJoinOperationRepository(dsl), + memberships, + pairs, + roles, + fresh, + generations, + outbox, + sources, + operations); + var beans = new StaticListableBeanFactory(); + beans.addBean("testOnlyBootstrapAuthority", testBootstrapParticipant(creator)); + var bootstrap = + new AccountTenantCreationBootstrapService( + accounts, + fresh, + sourceReader, + pairs, + memberships, + roles, + outbox, + new AccountAuditOutboxRepository(dsl), + operations, + beans.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class)); + tx(() -> bootstrap.bootstrap(creator)); + party = + new IndividualCreatorPartySource( + UUID.randomUUID(), + account, + VerificationStatus.VERIFIED, + 1L, + "test-only-policy", + 1L, + "test-only-individual-verification", + 1L, + 1L); + insertTestParty(dsl, party); + var parties = new IndividualCreatorPartyRepository(dsl, fresh, operations); + if (associate) { + tx(() -> parties.associateFresh(UUID.randomUUID(), creator, party)); + } + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindings = new HashMap<>(); + terms = + new AccountHostedTermsService( + manager, + new HostedTermsRepository(dsl), + parties, + new DraftAuthorizationFenceRepository(dsl), + request -> externalTestFixture(publications, request), + request -> externalTestFixture(actions, request), + new HostedTermsEnvironmentBindingRepository(dsl), + request -> externalTestFixture(bindings, request), + () -> { + requireOutsideTransaction(); + return boundary.get(); + }); + UUID publication = UUID.randomUUID(); + publications.put( + publication, + new AccountHostedTermsService.PublicationEvidence( + UUID.randomUUID(), + "Test-only Operator Legal Name", + 1L, + "Test-only terms".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-only-publication-audit", + 1L, + "test-only-notice", + 1L, + Instant.now().minusSeconds(30).truncatedTo(ChronoUnit.MICROS))); + var catalog = terms.publish(publication).candidate(); + if (accept) { + UUID action = UUID.randomUUID(); + actions.put( + action, + new AccountHostedTermsService.AcceptanceAction( + action, + true, + account, + party.creatorPartyId(), + catalog.hostedScopeId(), + catalog.versionId(), + catalog.documentDigest(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + "test-only-affirmative-individual-action", + 1L, + OffsetDateTime.now(ZoneOffset.UTC))); + terms.accept(action); + } + UUID binding = UUID.randomUUID(); + bindings.put( + binding, + new HostedTermsEnvironmentBinding.PublicationEvidence( + "test-production", + catalog.hostedScopeId(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + catalog.versionId(), + catalog.sourceVersion(), + "test-only-environment-publisher", + "test-only-environment-publication/" + binding, + null, + null)); + terms.publishEnvironmentBinding(binding); + composer = new AccountDraftSourceCompositionService(dsl, parties, bootstrap, terms, sources); + } + + private T tx(Supplier work) { + return transactions.execute(ignored -> work.get()); + } + + private long count(String table) { + return Objects.requireNonNull(dsl.fetchOne("SELECT count(*) FROM " + table)) + .get(0, Long.class); + } + } + + private static AccountTenantCreationBootstrapAuthorizationSource testBootstrapParticipant( + FreshTenantCreatorEvidence expected) { + ReentrantLock testOnlyFence = new ReentrantLock(); + return (actual, mutation) -> { + if (!expected.equals(actual) + || !TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Test-only bootstrap source requires exact evidence and owner transaction"); + } + testOnlyFence.lock(); + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCompletion(int status) { + testOnlyFence.unlock(); + } + }); + return mutation.get(); + }; + } + + private static FreshTenantCreatorEvidence testCreation(UUID account, UUID tenant) { + UUID request = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + UUID authorization = UUID.randomUUID(); + String key = "test-game-row-17"; + String digest = + GameTenantCreationDigest.requestDigest(NAMESPACE, request, key, "Test game", null); + var creation = + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + request, + operation, + digest, + tenant, + 17L, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); + String authorizationDigest = "sha256:" + "8".repeat(64); + return new FreshTenantCreatorEvidence( + 1, + creation, + account, + authorization, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, account, authorization, authorizationDigest)); + } + + private static void insertTestParty(DSLContext dsl, IndividualCreatorPartySource party) { + byte[] bytes = CreatorPartyEncoding.party(party); + dsl.execute( + "INSERT INTO account_individual_creator_party_sources " + + "(creator_party_id, account_uuid, verification_status, identity_version, policy_reference, " + + "policy_version, verification_evidence_reference, verification_evidence_version, " + + "source_version, source_payload, source_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + bytes, + CreatorPartyEncoding.digest(bytes)); + } + + private static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary testBoundary( + String name) { + byte[] bytes = ("test-only-environment-observation/" + name).getBytes(StandardCharsets.UTF_8); + return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + name, + "test-only-environment-owner", + "test-only-observation/" + name, + bytes, + HostedTermsEncoding.digest(bytes)); + } + + private static T externalTestFixture(Map fixtures, UUID request) { + requireOutsideTransaction(); + return Objects.requireNonNull( + fixtures.get(request), "Exact test-only external fixture required"); + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Test-only external source must be resolved outside Account locks"); + } + } +} From 66774f1d0098c96992a2da052ac1ffac6f7382cb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 23:17:33 +1300 Subject: [PATCH 008/129] Correct owner PostgreSQL result handling and contention proof --- ...ronmentBindingPostgresIntegrationTest.java | 29 ++++++++-- .../repository/PublishAttemptRepository.java | 24 ++++++++- ...emptServiceTransactionIntegrationTest.java | 54 ++++++++++++++++--- 3 files changed, 94 insertions(+), 13 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java index 8ca006c193..481401cd77 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java @@ -558,19 +558,19 @@ void environmentBindingPublisherWaitsUntilCallerOwnedCurrentnessTransactionEnds( new AtomicReference<>(currentBoundary("locked-currentness-test-environment")); AtomicBoolean capturePublisherBackendPid = new AtomicBoolean(); AtomicReference publisherBackendPid = new AtomicReference<>(); - CountDownLatch publisherAtHeadLock = new CountDownLatch(1); + CountDownLatch publisherBeforeEnsureHead = new CountDownLatch(1); HostedTermsEnvironmentBindingRepository bindingRepository = spy(new HostedTermsEnvironmentBindingRepository(db.dsl())); doAnswer( invocation -> { if (capturePublisherBackendPid.compareAndSet(true, false)) { publisherBackendPid.set(currentBackendPid(db)); - publisherAtHeadLock.countDown(); + publisherBeforeEnsureHead.countDown(); } return invocation.callRealMethod(); }) .when(bindingRepository) - .lockHead(anyString()); + .ensureHead(anyString()); AccountHostedTermsService service = service(db, catalogPublications, actions, bindingPublications, boundary, bindingRepository); @@ -636,7 +636,7 @@ void environmentBindingPublisherWaitsUntilCallerOwnedCurrentnessTransactionEnds( capturePublisherBackendPid.set(true); Future publisher = executor.submit(() -> service.publishEnvironmentBinding(secondBindingRequest)); - awaitLatch(publisherAtHeadLock, "publisher backend PID capture at environment head lock"); + awaitPublisherPidCapture(publisherBeforeEnsureHead, publisher); int exactPublisherPid = Objects.requireNonNull(publisherBackendPid.get()); awaitPublisherBlockedByOwner(db, ownerBackendPid.get(), exactPublisherPid); assertThat(exactPublisherPid).isNotEqualTo(ownerBackendPid.get()); @@ -940,7 +940,6 @@ private static void awaitPublisherBlockedByOwner(Database db, int ownerPid, int .fetch( "SELECT pid FROM pg_stat_activity " + "WHERE pid = ? AND state = 'active' " - + "AND strpos(query, 'account_hosted_terms_environment_binding_heads') > 0 " + "AND ? = ANY(pg_blocking_pids(pid))", publisherPid, ownerPid); @@ -954,6 +953,26 @@ private static int currentBackendPid(Database db) { .get("pid", Integer.class); } + private static void awaitPublisherPidCapture(CountDownLatch capture, Future publisher) + throws Exception { + try { + if (capture.await(20, TimeUnit.SECONDS)) { + return; + } + try { + publisher.get(100, TimeUnit.MILLISECONDS); + } catch (java.util.concurrent.TimeoutException ignored) { + // The bounded capture timeout remains the failure; a completed Future's exception is + // surfaced by get instead of being hidden behind that timeout. + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw exception; + } + throw new AssertionError( + "Timed out waiting for publisher backend PID capture before ensureHead"); + } + private static void awaitLatch(CountDownLatch latch, String description) { try { if (!latch.await(20, TimeUnit.SECONDS)) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java index d00a16b4b4..6398910d75 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java @@ -55,6 +55,23 @@ public class PublishAttemptRepository { DSL.field(DSL.name("game_design_version_tenant_key"), String.class); private static final Field SELECTION_VERSION_ID = DSL.field(DSL.name("game_design_version_row_id"), Long.class); + private static final Field[] PUBLISH_ATTEMPT_RETURNING_FIELDS = { + ID, + REVISION, + TENANT_ID, + PUBLISH_WORKFLOW_ID, + PUBLISH_TYPE, + STATUS, + VERSION_ID, + VERSION_NUMBER, + SCRIPT_PATCH_VERSION, + BASE_VERSION_ID, + REQUEST_DIGEST, + FAILURE_CODE, + FAILURE_MESSAGE, + CREATED_AT, + COMPLETED_AT + }; private final DSLContext dsl; @@ -207,8 +224,11 @@ public PublishAttempt save(PublishAttempt attempt) { .set(FAILURE_MESSAGE, attempt.getFailureMessage()) .set(CREATED_AT, JooqPersistenceSupport.toTimestamp(createdAt)) .set(COMPLETED_AT, JooqPersistenceSupport.toTimestamp(attempt.getCompletedAt())) - .returning() + .returning(PUBLISH_ATTEMPT_RETURNING_FIELDS) .fetchOne(); + if (record == null) { + throw new IllegalStateException("publish attempt insert returned no row"); + } return toEntity(record); } Long expectedRevision = attempt.getRevision(); @@ -238,7 +258,7 @@ public PublishAttempt save(PublishAttempt attempt) { ID.eq(attempt.getId()) .and(REVISION.eq(expectedRevision)) .and(STATUS.eq(PublishAttemptStatus.PENDING.name()))) - .returning() + .returning(PUBLISH_ATTEMPT_RETURNING_FIELDS) .fetchOne(); if (updated == null) { throw new IllegalStateException("publish attempt is stale or terminal"); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 07889b6463..0881817d9c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -240,7 +240,10 @@ void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() terminalAttempt.setFailureCode("fixture-terminal"); terminalAttempt.setCompletedAt(LocalDateTime.now()); terminalAttempt = publishAttemptRepository.save(terminalAttempt); + assertThat(terminalAttempt.getId()).isNotNull(); assertThat(terminalAttempt.getRevision()).isEqualTo(2L); + assertThat(terminalAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(terminalAttempt.getFailureCode()).isEqualTo("fixture-terminal"); assertThat( publishAttemptRepository.backfillFullVersionRequestDigestIfAbsent( terminalAttempt.getId(), @@ -252,6 +255,9 @@ void fullVersionRequestDigestBackfillReturnsEmptyForMismatchedAttemptIdentity() .isEmpty(); PublishAttempt retainedTerminalAttempt = publishAttemptRepository.findByPublishWorkflowId(terminalWorkflowId).orElseThrow(); + assertThat(retainedTerminalAttempt.getId()).isEqualTo(terminalAttempt.getId()); + assertThat(retainedTerminalAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(retainedTerminalAttempt.getFailureCode()).isEqualTo("fixture-terminal"); assertThat(retainedTerminalAttempt.getRequestDigest()).isNull(); assertThat(retainedTerminalAttempt.getRevision()).isEqualTo(2L); } @@ -278,7 +284,22 @@ void publishAttemptSaveUsesRevisionCasAndRejectsStaleAndTerminalUpdates() { attempt.setVersionId(savedVersion.getId()); attempt.setVersionNumber(savedVersion.getVersionNumber()); PublishAttempt inserted = publishAttemptRepository.save(attempt); + assertThat(inserted).isNotNull(); + assertThat(inserted.getId()).isNotNull(); assertThat(inserted.getRevision()).isEqualTo(1L); + assertThat(inserted.getTenantId()).isEqualTo(tenantId); + assertThat(inserted.getPublishWorkflowId()).isEqualTo(attempt.getPublishWorkflowId()); + assertThat(inserted.getVersionId()).isEqualTo(savedVersion.getId()); + assertThat(inserted.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); + PublishAttempt insertedReadback = + publishAttemptRepository + .findByPublishWorkflowId(attempt.getPublishWorkflowId()) + .orElseThrow(); + assertThat(insertedReadback.getId()).isEqualTo(inserted.getId()); + assertThat(insertedReadback.getRevision()).isEqualTo(1L); + assertThat(insertedReadback.getTenantId()).isEqualTo(tenantId); + assertThat(insertedReadback.getVersionId()).isEqualTo(savedVersion.getId()); + assertThat(insertedReadback.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); PublishAttempt firstWriter = publishAttemptRepository @@ -290,7 +311,10 @@ void publishAttemptSaveUsesRevisionCasAndRejectsStaleAndTerminalUpdates() { .orElseThrow(); firstWriter.setFailureMessage("first revision writer"); firstWriter = publishAttemptRepository.save(firstWriter); + assertThat(firstWriter.getId()).isEqualTo(inserted.getId()); assertThat(firstWriter.getRevision()).isEqualTo(2L); + assertThat(firstWriter.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); + assertThat(firstWriter.getFailureMessage()).isEqualTo("first revision writer"); staleWriter.setFailureMessage("stale revision writer"); assertThatThrownBy(() -> publishAttemptRepository.save(staleWriter)) @@ -300,18 +324,35 @@ void publishAttemptSaveUsesRevisionCasAndRejectsStaleAndTerminalUpdates() { publishAttemptRepository .findByPublishWorkflowId(attempt.getPublishWorkflowId()) .orElseThrow(); + assertThat(afterStaleWrite.getId()).isEqualTo(inserted.getId()); assertThat(afterStaleWrite.getRevision()).isEqualTo(2L); + assertThat(afterStaleWrite.getStatus()).isEqualTo(PublishAttemptStatus.PENDING); assertThat(afterStaleWrite.getFailureMessage()).isEqualTo("first revision writer"); + assertThat(afterStaleWrite.getFailureCode()).isNull(); + assertThat(afterStaleWrite.getCompletedAt()).isNull(); afterStaleWrite.setStatus(PublishAttemptStatus.FAILED); afterStaleWrite.setFailureCode("terminal-revision-proof"); afterStaleWrite.setCompletedAt(LocalDateTime.now()); PublishAttempt terminal = publishAttemptRepository.save(afterStaleWrite); + assertThat(terminal.getId()).isEqualTo(inserted.getId()); assertThat(terminal.getRevision()).isEqualTo(3L); + assertThat(terminal.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(terminal.getFailureMessage()).isEqualTo("first revision writer"); + assertThat(terminal.getFailureCode()).isEqualTo("terminal-revision-proof"); terminal.setFailureMessage("terminal rows cannot be rewritten"); assertThatThrownBy(() -> publishAttemptRepository.save(terminal)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("stale or terminal"); + PublishAttempt afterTerminalWrite = + publishAttemptRepository + .findByPublishWorkflowId(attempt.getPublishWorkflowId()) + .orElseThrow(); + assertThat(afterTerminalWrite.getId()).isEqualTo(inserted.getId()); + assertThat(afterTerminalWrite.getRevision()).isEqualTo(3L); + assertThat(afterTerminalWrite.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); + assertThat(afterTerminalWrite.getFailureMessage()).isEqualTo("first revision writer"); + assertThat(afterTerminalWrite.getFailureCode()).isEqualTo("terminal-revision-proof"); } @Test @@ -347,9 +388,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth null, null)); }); - Mockito.when(assetExportService.exportAssets(tenantId, 1)) - .thenReturn( - new ExportedAssetManifest("transaction-proof-manifest", List.of("manifest.json"))); + Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(immutableEmptyManifest()); VersionDto publishedVersion = versionPublishCommandService.publishFullVersion( @@ -373,7 +412,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth assertThat(attempt.getVersionId()).isEqualTo(publishedVersion.id()); assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.PUBLISHED); assertThat(bundle.getPublishWorkflowId()).isEqualTo(publishWorkflowId); - assertThat(bundle.getManifestHash()).isEqualTo("transaction-proof-manifest"); + assertThat(bundle.getManifestHash()).isEqualTo("sha256:" + "a".repeat(64)); assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.PUBLISHED); } @@ -442,8 +481,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( .when(recordedParticipantDigestService) .assertMatchesRecordedDigests( Mockito.eq(tenantId), Mockito.eq(PublishType.FULL_VERSION), Mockito.anyList()); - ExportedAssetManifest exportedManifest = - new ExportedAssetManifest("post-export-finalization-manifest", List.of("manifest.json")); + ExportedAssetManifest exportedManifest = immutableEmptyManifest(); Mockito.when(assetExportService.exportAssets(Mockito.eq(tenantId), Mockito.anyInt())) .thenAnswer( invocation -> { @@ -550,4 +588,8 @@ private static String firstStackFrame(Throwable failure) { } return failure.getStackTrace()[0].toString(); } + + private static ExportedAssetManifest immutableEmptyManifest() { + return new ExportedAssetManifest("sha256:" + "a".repeat(64), 1, List.of(), List.of()); + } } From 552fa9bdca6541602dc95cc6835d4255cd82a440 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 23:38:03 +1300 Subject: [PATCH 009/129] Retain exact historical World placement outcome readback --- .../world-management-service/api-contracts.md | 11 + .../v1/world_canonical_player_location.proto | 30 ++ ...onicalInitialPlayerLocationRepository.java | 103 +++++++ ...CanonicalInitialPlayerLocationService.java | 16 + ...rldCanonicalPlayerLocationGrpcService.java | 192 ++++++++++++ ...aphApplicationPostgresIntegrationTest.java | 111 +++++++ ...nicalInitialPlayerLocationServiceTest.java | 24 ++ ...anonicalPlayerLocationGrpcServiceTest.java | 289 +++++++++++++++++- 8 files changed, 775 insertions(+), 1 deletion(-) diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 8d3c6b3c98..79084c5b1e 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -10,6 +10,7 @@ This API contract is target-state canonical; implementation coverage is partial - `GetDraftDesignDigest` checks the exact Game Design workload/method boundary and validates the typed tenant/version, publication request, derived workflow identity and request digest before returning owner-matching scope. Missing authorization configuration denies the read. This read binding is not Account authoring authorization, release attestation or proof of the complete publication transaction. The canonical owner remains [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). - The registered `ApplyWorldDesignMutation` handler fails closed before parsing or owner mutation until current Account commit authorization is verified. This denial does not implement the positive authenticated Game Design/Account commit boundary or repair the separate legacy REST generation-rule gap. - The registered `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, `FailPreparedWorldInstance` and `TerminateWorldInstance` handlers allow only verified same-namespace Game Session workload identity before request parsing or owner calls. Missing configuration, missing peer identity and other workloads are denied; shared bearer claims do not substitute. Other pre-admission consumers are not currently allowlisted. This caller guard does not supply the remaining canonical preparation, activation, cleanup or admission proofs. +- The standalone canonical initial-placement adapter now defines an Entity Management-only historical terminal-result read. Its proto and handler remain unregistered; the read supplies settlement evidence for the exact immutable placement operation, without admitting gameplay or directly mutating any hold. - 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. ## gRPC APIs @@ -30,6 +31,16 @@ This API contract is target-state canonical; implementation coverage is partial The gRPC contract for world operations is located in [../../../../protos/world-management/v1](../../../../protos/world-management/v1). Run `./gradlew generateProto` to regenerate sources after editing these files. +### Canonical initial-placement terminal readback + +`ReadCanonicalInitialPlayerLocationOutcome` is a narrow World-owned historical read for the standalone canonical placement operation. It is separate from `PlaceCanonicalInitialPlayerLocation` and `ReadCanonicalCurrentPlayerLocation`; it does not register or enable the standalone service at runtime. + +The caller supplies a fresh canonical non-nil `readRequestId`, the complete immutable canonical placement request bytes, and the original complete lifecycle evidence bytes bound to that request. World accepts the read only from the verified same-namespace `entity-management-service` workload with no authenticated end-user context. This peer check is the only caller authorization for this historical operation read; shared JWT or ambient caller context is not a fallback. The original lifecycle evidence is retained historical binding evidence, not fresh authorization. The read UUID is distinct from both the placement operation ID and the original lifecycle read correlation. + +World retrieves one immutable placement operation row in one owner-local read. It verifies the exact stored operation ID, canonical tenant/namespace/runtime columns, request digest and request bytes, normalized original lifecycle binding, result digest, canonical result bytes, and the stored outcome columns. It reconstructs the request and result from the stored original request, lifecycle, and result bytes, then returns the echoed read UUID, placement operation ID and request digest, exact immutable result bytes, and exact stored original lifecycle evidence bytes. + +Both durable `APPLIED` and durable `CONFLICT` are terminal operation results and are returned as evidence in a successful response. Entity owns applicability-hold settlement and must verify this authenticated outcome against its exact held operation and digest; World does not directly release that hold. An exact immutable `CONFLICT` proves only that this operation cannot later apply under the existing placement guards. `NOT_FOUND` means the operation is unknown or unresolved; it is not proof of abort and never releases an admission hold. Malformed or mismatched requests, corrupt stored rows, unavailable storage, and other read failures return no result and likewise do not authorize abort, hold release, or retry under a new placement identity. A timeout or diagnostic expiry is only a retry/reconciliation trigger and never releases the hold. The read does not call placement mutation, current-location verification, current lifecycle reads, or creator authorization, and remains valid after the World lifecycle advances beyond `ACTIVE`. Neither a terminal result nor missing or unavailable evidence authorizes gameplay admission, movement, or a new placement. + Call the `Ping` method with: ```bash diff --git a/protos/world-management/v1/world_canonical_player_location.proto b/protos/world-management/v1/world_canonical_player_location.proto index 87558c8ca2..caf9ceb3cc 100644 --- a/protos/world-management/v1/world_canonical_player_location.proto +++ b/protos/world-management/v1/world_canonical_player_location.proto @@ -10,6 +10,8 @@ option java_multiple_files = true; service WorldCanonicalPlayerLocationService { rpc PlaceCanonicalInitialPlayerLocation(PlaceCanonicalInitialPlayerLocationRequest) returns (PlaceCanonicalInitialPlayerLocationResponse); + rpc ReadCanonicalInitialPlayerLocationOutcome(ReadCanonicalInitialPlayerLocationOutcomeRequest) + returns (ReadCanonicalInitialPlayerLocationOutcomeResponse); rpc ReadCanonicalCurrentPlayerLocation(ReadCanonicalCurrentPlayerLocationRequest) returns (ReadCanonicalCurrentPlayerLocationResponse); } @@ -30,6 +32,34 @@ message PlaceCanonicalInitialPlayerLocationResponse { bytes canonical_result_bytes = 2; } +message ReadCanonicalInitialPlayerLocationOutcomeRequest { + // Fresh canonical non-nil UUID for this read correlation; it grants no gameplay authority. + string read_request_id = 1; + + // Complete closed canonical placement request bytes identifying the immutable operation. + bytes canonical_placement_request_bytes = 2; + + // Complete original ACTIVE lifecycle evidence retained with the placement operation. + bytes original_lifecycle_evidence_bytes = 3; +} + +message ReadCanonicalInitialPlayerLocationOutcomeResponse { + // Echo of the fresh read correlation UUID. + string read_request_id = 1; + + // Stable operation UUID of the immutable initial placement. + string placement_operation_id = 2; + + // Exact canonical digest of the immutable placement request. + string placement_request_digest = 3; + + // Exact immutable APPLIED or CONFLICT placement result bytes retained by World. + bytes immutable_placement_result_bytes = 4; + + // Exact complete original lifecycle evidence bytes retained with the operation. + bytes original_placement_lifecycle_evidence_bytes = 5; +} + message ReadCanonicalCurrentPlayerLocationRequest { // Fresh canonical non-nil UUID for this read correlation; it grants no gameplay authority. string read_request_id = 1; diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java index b2a02cf38e..83e74717b1 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java @@ -143,6 +143,82 @@ public WorldCanonicalInitialPlayerLocation.Result place( }); } + /** + * Reads only the immutable placement operation row. This historical settlement read deliberately + * does not consult current lifecycle, association, hold, location, or placement authority state. + */ + public Optional readTerminalOutcome( + WorldCanonicalInitialPlayerLocation.Request request) { + Objects.requireNonNull(request, "request"); + requireNoActiveTransaction(); + + // A single statement observes one atomic row version; the operation table's owner guard keeps + // the request, lifecycle proof, and result immutable after commit. + Record row = + dsl.fetchOne( + "SELECT canonical_tenant_id, playable_state_namespace_id, canonical_game_instance_id, " + + "operation_id, request_digest, request_bytes, original_lifecycle_evidence_bytes, " + + "outcome, conflict_code, result_bytes, result_digest " + + "FROM world_canonical_initial_player_location_operation WHERE operation_id = ?", + request.operationId()); + if (row == null) return Optional.empty(); + + try { + UUID operationId = row.get("operation_id", UUID.class); + UUID canonicalTenantId = row.get("canonical_tenant_id", UUID.class); + UUID playableStateNamespaceId = row.get("playable_state_namespace_id", UUID.class); + UUID canonicalGameInstanceId = row.get("canonical_game_instance_id", UUID.class); + String requestDigest = row.get("request_digest", String.class); + byte[] requestBytes = row.get("request_bytes", byte[].class); + byte[] originalLifecycleEvidenceBytes = + row.get("original_lifecycle_evidence_bytes", byte[].class); + String outcome = row.get("outcome", String.class); + String conflictCode = row.get("conflict_code", String.class); + byte[] resultBytes = row.get("result_bytes", byte[].class); + String resultDigest = row.get("result_digest", String.class); + if (requestBytes == null || originalLifecycleEvidenceBytes == null || resultBytes == null) { + throw terminalReadbackDenied("retained initial-location operation is incomplete"); + } + + WorldCanonicalInitialPlayerLocation.Request storedRequest = + WorldCanonicalInitialPlayerLocation.Request.fromStored( + requestBytes, originalLifecycleEvidenceBytes); + if (!request.operationId().equals(operationId) + || !request.operationId().equals(storedRequest.operationId()) + || !request.canonicalTenantId().equals(canonicalTenantId) + || !request.playableStateNamespaceId().equals(playableStateNamespaceId) + || !request.canonicalGameInstanceId().equals(canonicalGameInstanceId) + || !request.requestDigest().equals(requestDigest) + || !prefixedDigest(requestBytes).equals(requestDigest) + || !Arrays.equals(request.canonicalRequestBytes(), requestBytes) + || !Arrays.equals( + request.normalizedLifecycleEvidenceBytes(), + WorldCanonicalInitialPlayerLocation.normalizedLifecycleEvidenceBytes( + originalLifecycleEvidenceBytes))) { + throw terminalReadbackDenied( + "requested initial-location operation differs from its immutable World binding"); + } + + if (!prefixedDigest(resultBytes).equals(resultDigest)) { + throw terminalReadbackDenied("retained initial-location result digest is inconsistent"); + } + WorldCanonicalInitialPlayerLocation.Result result = + WorldCanonicalInitialPlayerLocation.Result.fromStored(storedRequest, resultBytes); + if (!result.outcome().name().equals(outcome) + || !Objects.equals(result.conflictCode(), conflictCode)) { + throw terminalReadbackDenied( + "retained initial-location result differs from its immutable outcome columns"); + } + return Optional.of(new TerminalReadback(result, originalLifecycleEvidenceBytes)); + } catch (RuntimeException inconsistent) { + if (inconsistent.getMessage() != null + && inconsistent.getMessage().startsWith("INITIAL_PLAYER_LOCATION_READBACK_DENIED:")) { + throw inconsistent; + } + throw terminalReadbackDenied("retained initial-location operation is invalid", inconsistent); + } + } + void requireAssociation( WorldCanonicalInitialPlayerLocation.Request request, WorldCanonicalInstanceLifecycleEvidence current, @@ -443,6 +519,15 @@ private static IllegalStateException denied(String message) { return new IllegalStateException("INITIAL_PLAYER_LOCATION_DENIED: " + message); } + private static IllegalStateException terminalReadbackDenied(String message) { + return new IllegalStateException("INITIAL_PLAYER_LOCATION_READBACK_DENIED: " + message); + } + + private static IllegalStateException terminalReadbackDenied( + String message, RuntimeException cause) { + return new IllegalStateException("INITIAL_PLAYER_LOCATION_READBACK_DENIED: " + message, cause); + } + private static IllegalArgumentException conflict(String message) { return new IllegalArgumentException("IDEMPOTENCY_CONFLICT: " + message); } @@ -459,4 +544,22 @@ private record StoredOperation( resultBytes = Arrays.copyOf(resultBytes, resultBytes.length); } } + + /** Exact immutable result plus the exact original lifecycle bytes retained beside it. */ + public record TerminalReadback( + WorldCanonicalInitialPlayerLocation.Result result, byte[] originalLifecycleEvidenceBytes) { + public TerminalReadback { + Objects.requireNonNull(result, "result"); + originalLifecycleEvidenceBytes = + Arrays.copyOf( + Objects.requireNonNull( + originalLifecycleEvidenceBytes, "originalLifecycleEvidenceBytes"), + originalLifecycleEvidenceBytes.length); + } + + @Override + public byte[] originalLifecycleEvidenceBytes() { + return Arrays.copyOf(originalLifecycleEvidenceBytes, originalLifecycleEvidenceBytes.length); + } + } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationService.java index 714bb4f4f5..66ecd57f6a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationService.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.worldmanagement.tenant; import java.util.Objects; +import java.util.Optional; import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -49,6 +50,21 @@ public WorldCanonicalInitialPlayerLocation.Result place( } } + /** + * Returns operation-specific historical settlement evidence without rechecking current placement + * authority or lifecycle state. Absence remains unresolved and never authorizes hold release. + */ + public Optional + readTerminalOutcome(WorldCanonicalInitialPlayerLocation.Request request) { + Objects.requireNonNull(request, "request"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World initial-placement outcome read requires an independent owner operation"); + } + return repository.readTerminalOutcome(request); + } + private static HeldPlacementAuthority denyByDefault( WorldCanonicalInitialPlayerLocation.Request request) { throw new PlacementDeniedException( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcService.java index 99fa77d580..67d26136a9 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcService.java @@ -14,6 +14,8 @@ import net.firedevops.firemud.worldmanagement.v1.PlaceCanonicalInitialPlayerLocationResponse; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalCurrentPlayerLocationRequest; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalCurrentPlayerLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialPlayerLocationOutcomeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialPlayerLocationOutcomeResponse; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalPlayerLocationServiceGrpc; import org.jooq.exception.DataAccessException; import org.springframework.dao.TransientDataAccessException; @@ -149,6 +151,104 @@ public void placeCanonicalInitialPlayerLocation( } } + @Override + public void readCanonicalInitialPlayerLocationOutcome( + ReadCanonicalInitialPlayerLocationOutcomeRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedEntityManagementPeer(responseObserver)) return; + if (hasAmbientTransaction()) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World placement outcome read requires an independent owner operation"); + return; + } + + ParsedTerminalOutcomeRequest parsed; + try { + parsed = parseTerminalOutcomeRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A complete canonical World placement outcome read request is required"); + return; + } + if (!trustedNamespace.equals( + parsed.placementRequest().activeLifecycleEvidence().request().targetNamespace())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World placement namespace must match the authenticated Entity Management peer"); + return; + } + + java.util.Optional readback; + try { + readback = placementService.readTerminalOutcome(parsed.placementRequest()); + } catch (TransientDataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Canonical World placement outcome storage is temporarily unavailable"); + return; + } catch (DataAccessException permanentStorageFailure) { + fail(responseObserver, Status.INTERNAL, "Canonical World placement outcome storage failed"); + return; + } catch (org.springframework.dao.DataAccessException permanentSpringStorageFailure) { + fail(responseObserver, Status.INTERNAL, "Canonical World placement outcome storage failed"); + return; + } catch (IllegalStateException inconsistent) { + if (hasPrefix(inconsistent, "INITIAL_PLAYER_LOCATION_READBACK_DENIED:")) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World placement outcome does not match its immutable request"); + } else { + fail(responseObserver, Status.INTERNAL, "Canonical World placement outcome read failed"); + } + return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.INTERNAL, "Canonical World placement outcome read failed"); + return; + } + + if (readback == null) { + fail( + responseObserver, + Status.INTERNAL, + "Canonical World placement outcome owner returned no read result"); + return; + } + if (readback.isEmpty()) { + fail( + responseObserver, + Status.NOT_FOUND, + "No immutable terminal placement outcome is recorded; this operation remains unresolved"); + return; + } + + try { + ValidatedTerminalOutcome validated = + validateTerminalOutcome(parsed, readback.orElseThrow(), trustedNamespace); + responseObserver.onNext( + ReadCanonicalInitialPlayerLocationOutcomeResponse.newBuilder() + .setReadRequestId(parsed.readRequestId().toString()) + .setPlacementOperationId(parsed.placementRequest().operationId().toString()) + .setPlacementRequestDigest(parsed.placementRequest().requestDigest()) + .setImmutablePlacementResultBytes(ByteString.copyFrom(validated.resultBytes())) + .setOriginalPlacementLifecycleEvidenceBytes( + ByteString.copyFrom(validated.originalLifecycleEvidenceBytes())) + .build()); + responseObserver.onCompleted(); + } catch (RuntimeException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World placement outcome does not match the requested operation"); + } + } + @Override public void readCanonicalCurrentPlayerLocation( ReadCanonicalCurrentPlayerLocationRequest request, @@ -296,6 +396,33 @@ private static ParsedCurrentLocationRequest parseCurrentLocationRequest( return new ParsedCurrentLocationRequest(readRequestId, placementRequest); } + private static ParsedTerminalOutcomeRequest parseTerminalOutcomeRequest( + ReadCanonicalInitialPlayerLocationOutcomeRequest request) { + Objects.requireNonNull(request, "request"); + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Unknown canonical World outcome read request fields"); + } + UUID readRequestId = parseCanonicalUuid(request.getReadRequestId()); + byte[] canonicalRequestBytes = request.getCanonicalPlacementRequestBytes().toByteArray(); + byte[] originalLifecycleEvidenceBytes = + request.getOriginalLifecycleEvidenceBytes().toByteArray(); + if (canonicalRequestBytes.length == 0 || originalLifecycleEvidenceBytes.length == 0) { + throw new IllegalArgumentException( + "Complete canonical World placement outcome evidence is required"); + } + WorldCanonicalInitialPlayerLocation.Request placementRequest = + WorldCanonicalInitialPlayerLocation.Request.fromStored( + canonicalRequestBytes, originalLifecycleEvidenceBytes); + UUID originalLifecycleReadId = + placementRequest.activeLifecycleEvidence().request().readRequestId(); + if (readRequestId.equals(placementRequest.operationId()) + || readRequestId.equals(originalLifecycleReadId)) { + throw new IllegalArgumentException( + "Outcome read correlation must be fresh relative to the placement and retained lifecycle proof"); + } + return new ParsedTerminalOutcomeRequest(readRequestId, placementRequest); + } + private static UUID parseCanonicalUuid(String value) { UUID parsed; try { @@ -390,6 +517,65 @@ private static ValidatedCurrentLocation validateCurrentLocation( currentEvidenceBytes, immutablePlacementResultBytes, originalLifecycleEvidenceBytes); } + private static ValidatedTerminalOutcome validateTerminalOutcome( + ParsedTerminalOutcomeRequest parsed, + WorldCanonicalInitialPlayerLocationRepository.TerminalReadback readback, + String trustedNamespace) { + WorldCanonicalInitialPlayerLocation.Request requested = parsed.placementRequest(); + WorldCanonicalInitialPlayerLocation.Result result = + Objects.requireNonNull(readback.result(), "terminalReadback.result"); + WorldCanonicalInitialPlayerLocation.Request resultRequest = + Objects.requireNonNull(result.request(), "terminalReadback.result.request"); + if (!requested.operationId().equals(resultRequest.operationId()) + || !requested.requestDigest().equals(result.requestDigest()) + || !Arrays.equals( + requested.canonicalRequestBytes(), resultRequest.canonicalRequestBytes())) { + throw new InvalidOwnerEvidenceException(); + } + + byte[] resultBytes = result.canonicalBytes(); + if (resultBytes.length == 0) throw new InvalidOwnerEvidenceException(); + WorldCanonicalInitialPlayerLocation.Result exactResult = + WorldCanonicalInitialPlayerLocation.Result.fromStored(requested, resultBytes); + if (exactResult.outcome() != WorldCanonicalInitialPlayerLocation.Outcome.APPLIED + && exactResult.outcome() != WorldCanonicalInitialPlayerLocation.Outcome.CONFLICT) { + throw new InvalidOwnerEvidenceException(); + } + + byte[] originalLifecycleEvidenceBytes = readback.originalLifecycleEvidenceBytes(); + if (originalLifecycleEvidenceBytes.length == 0) throw new InvalidOwnerEvidenceException(); + WorldCanonicalInitialPlayerLocation.Request storedRequest = + WorldCanonicalInitialPlayerLocation.Request.fromStored( + requested.canonicalRequestBytes(), originalLifecycleEvidenceBytes); + if (!trustedNamespace.equals( + storedRequest.activeLifecycleEvidence().request().targetNamespace()) + || parsed + .readRequestId() + .equals(storedRequest.activeLifecycleEvidence().request().readRequestId()) + || !Arrays.equals( + requested.normalizedLifecycleEvidenceBytes(), + storedRequest.normalizedLifecycleEvidenceBytes())) { + throw new InvalidOwnerEvidenceException(); + } + + return new ValidatedTerminalOutcome(resultBytes, originalLifecycleEvidenceBytes); + } + + private boolean requireAuthenticatedEntityManagementPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("entity-management-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Only the verified same-namespace Entity Management workload without end-user context is allowed"); + return false; + } + private boolean requireAuthenticatedGameSessionPeer(StreamObserver responseObserver) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer != null @@ -421,10 +607,16 @@ private static void fail(StreamObserver responseObserver, Status status, Stri private record ParsedCurrentLocationRequest( UUID readRequestId, WorldCanonicalInitialPlayerLocation.Request placementRequest) {} + private record ParsedTerminalOutcomeRequest( + UUID readRequestId, WorldCanonicalInitialPlayerLocation.Request placementRequest) {} + private record ValidatedCurrentLocation( byte[] currentLifecycleEvidenceBytes, byte[] placementResultBytes, byte[] originalPlacementLifecycleEvidenceBytes) {} + private record ValidatedTerminalOutcome( + byte[] resultBytes, byte[] originalLifecycleEvidenceBytes) {} + private static final class InvalidOwnerEvidenceException extends IllegalStateException {} } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 919e445ffc..92112fee24 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -2076,6 +2076,117 @@ void canonicalInitialPlayerLocationCommitsAndFreshCorrelationRetryReplaysOrigina assertOrigin(); } + @Test + void terminalInitialPlayerLocationReadbackReturnsStoredAppliedAndConflictAfterTermination() { + PlacementFixture fixture = initialPlayerLocationFixture(); + var applied = fixture.service().place(fixture.request()); + var secondRequest = + initialLocationRequest( + fixture, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "d".repeat(64), + fixture.activeEvidence()); + fixture.service().place(secondRequest); + var conflictRequest = + initialLocationRequest( + fixture, + UUID.randomUUID(), + fixture.request().characterId(), + secondRequest.entityAssignmentOperationId(), + secondRequest.entityAssignmentDigest(), + fixture.activeEvidence()); + var conflict = fixture.service().place(conflictRequest); + assertThat(conflict.outcome()).isEqualTo(WorldCanonicalInitialPlayerLocation.Outcome.CONFLICT); + + var missingRequest = + initialLocationRequest( + fixture, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "e".repeat(64), + fixture.activeEvidence()); + long operationsBeforeReads = + countInitialLocationOperations(fixture.request().canonicalGameInstanceId()); + String locationsBeforeReads = + initialLocationSnapshot(fixture.request().canonicalGameInstanceId()); + assertThat(fixture.repository().readTerminalOutcome(missingRequest)).isEmpty(); + + var privateKeys = fixture.lifecycle().materialized().association().worldPrepareFields(); + lifecycleCommandService.terminateWorldInstance( + privateKeys.privateTenantKey(), + privateKeys.privateGameInstanceKey(), + fixture.activeEvidence().lifecycleEpoch(), + "initial-placement-terminal-readback", + "terminal readback proof"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT status FROM world_instance WHERE id=?", + fixture.lifecycle().materialized().association().worldInstanceId())) + .get("status", String.class)) + .isEqualTo("TERMINATED"); + + var appliedRead = fixture.repository().readTerminalOutcome(fixture.request()).orElseThrow(); + var conflictRead = fixture.repository().readTerminalOutcome(conflictRequest).orElseThrow(); + assertThat(appliedRead.result().outcome()) + .isEqualTo(WorldCanonicalInitialPlayerLocation.Outcome.APPLIED); + assertThat(appliedRead.result().canonicalBytes()).containsExactly(applied.canonicalBytes()); + assertThat(appliedRead.originalLifecycleEvidenceBytes()) + .containsExactly(fixture.request().originalLifecycleEvidenceBytes()); + assertThat(conflictRead.result().outcome()) + .isEqualTo(WorldCanonicalInitialPlayerLocation.Outcome.CONFLICT); + assertThat(conflictRead.result().canonicalBytes()).containsExactly(conflict.canonicalBytes()); + assertThat(conflictRead.originalLifecycleEvidenceBytes()) + .containsExactly(conflictRequest.originalLifecycleEvidenceBytes()); + + var changedAssignment = + initialLocationRequest( + fixture, + fixture.request().operationId(), + fixture.request().characterId(), + fixture.request().entityAssignmentOperationId(), + "f".repeat(64), + fixture.activeEvidence()); + assertThatThrownBy(() -> fixture.repository().readTerminalOutcome(changedAssignment)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("immutable World binding"); + var changedRealm = + new WorldCanonicalInitialPlayerLocation.Request( + fixture.request().operationId(), + fixture.request().canonicalTenantId(), + UUID.randomUUID(), + fixture.request().worldSlug(), + fixture.request().canonicalGameInstanceId(), + fixture.request().playableStateNamespaceId(), + fixture.request().playableStateScope(), + fixture.request().canonicalAccountId(), + fixture.request().characterId(), + fixture.request().entityAssignmentOperationId(), + fixture.request().entityAssignmentDigest(), + fixture.request().initialAdmissionHoldId(), + fixture.request().initialAdmissionHoldFence(), + fixture.request().initialAdmissionRequestId(), + fixture.request().initialAdmissionRequestDigest(), + fixture.request().catalogRevision(), + fixture.request().initialAdmissionOwnerProofId(), + fixture.request().initialAdmissionOwnerProofDigest(), + fixture.request().pointerAuditId(), + fixture.request().pointerVersion(), + fixture.request().initialAdmissionOrigin(), + fixture.request().activeLifecycleEvidence()); + assertThatThrownBy(() -> fixture.repository().readTerminalOutcome(changedRealm)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("immutable World binding"); + assertThat(countInitialLocationOperations(fixture.request().canonicalGameInstanceId())) + .isEqualTo(operationsBeforeReads); + assertThat(initialLocationSnapshot(fixture.request().canonicalGameInstanceId())) + .isEqualTo(locationsBeforeReads); + assertOrigin(); + } + @Test void expectedClosedPlacementUsesExactNextPointerVersionFromStipulatedOwnerProof() { PlacementFixture fixture = initialPlayerLocationFixture(InitialAdmissionOrigin.EXPECT_CLOSED); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationServiceTest.java index f15380dc96..a742315b40 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationServiceTest.java @@ -7,6 +7,7 @@ import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; @@ -68,6 +69,29 @@ public void close() { org.assertj.core.api.Assertions.assertThat(closes).hasValue(2); } + @Test + void historicalOutcomeReadDoesNotInvokeCurrentPlacementAuthority() { + var repository = mock(WorldCanonicalInitialPlayerLocationRepository.class); + var request = request(); + when(repository.readTerminalOutcome(request)).thenReturn(Optional.empty()); + AtomicInteger verifierCalls = new AtomicInteger(); + var service = + new WorldCanonicalInitialPlayerLocationService( + repository, + ignored -> { + verifierCalls.incrementAndGet(); + throw new AssertionError( + "historical outcome read must not acquire placement authority"); + }); + + org.assertj.core.api.Assertions.assertThat(service.readTerminalOutcome(request)).isEmpty(); + + verify(repository).readTerminalOutcome(request); + verify(repository, never()) + .place(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.assertj.core.api.Assertions.assertThat(verifierCalls).hasValue(0); + } + private static WorldCanonicalInitialPlayerLocation.Request request() { UUID tenant = uuid("10000000-0000-4000-8000-000000000001"); UUID instance = uuid("20000000-0000-4000-8000-000000000001"); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java index 18cf8d7f90..0472b71b0a 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java @@ -50,6 +50,8 @@ import net.firedevops.firemud.worldmanagement.v1.PlaceCanonicalInitialPlayerLocationResponse; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalCurrentPlayerLocationRequest; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalCurrentPlayerLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialPlayerLocationOutcomeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialPlayerLocationOutcomeResponse; import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -60,6 +62,7 @@ class WorldCanonicalPlayerLocationGrpcServiceTest { private static final String NAMESPACE = "test"; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final UUID OPERATION_ID = uuid("a0000000-0000-4000-8000-000000000001"); + private static final UUID TERMINAL_READ_ID = uuid("d0000000-0000-4000-8000-000000000001"); private static final UUID OTHER_OPERATION_ID = uuid("10000000-0000-4000-8000-000000000002"); private static final UUID REGION_INSTANCE_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); private static final UUID OPERATIONAL_REGION_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); @@ -88,6 +91,103 @@ void rejectsMissingWrongOrWrongNamespacePeerBeforeParsingOrOwnerAccess() throws verifyNoInteractions(placementService, currentService); } + @Test + void terminalOutcomeReadRequiresExactSameNamespaceEntityPeerBeforeOwnerAccess() throws Exception { + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + var grpc = service(placementService, currentService); + var malformed = terminalOutcomeRequest("not-a-uuid", new byte[] {1}, new byte[] {1}); + + Collector missing = + callTerminalOutcome(grpc, malformed, null); + Collector wrongService = + callTerminalOutcome(grpc, malformed, peer("game-session-service", NAMESPACE)); + Collector wrongNamespace = + callTerminalOutcome(grpc, malformed, peer("entity-management-service", "other")); + + assertThat(missing.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongService.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(placementService, currentService); + } + + @Test + void terminalOutcomeReadRejectsEndUserContextAndAmbientTransactionsBeforeOwnerAccess() + throws Exception { + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + var grpc = service(placementService, currentService); + var malformed = terminalOutcomeRequest("not-a-uuid", new byte[] {1}, new byte[] {1}); + + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Collector callerContext; + try { + callerContext = + callTerminalOutcome(grpc, malformed, peer("entity-management-service", NAMESPACE)); + } finally { + SessionContext.clear(); + } + + TransactionSynchronizationManager.setActualTransactionActive(true); + Collector transaction; + try { + transaction = + callTerminalOutcome(grpc, malformed, peer("entity-management-service", NAMESPACE)); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + assertThat(callerContext.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(transaction.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(placementService, currentService); + } + + @Test + void terminalOutcomeReadRejectsMalformedOrReusedCorrelationBeforeOwnerAccess() throws Exception { + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + var grpc = service(placementService, currentService); + var fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + + var malformed = + callTerminalOutcome( + grpc, + terminalOutcomeRequest( + TERMINAL_READ_ID.toString(), new byte[] {1}, fixture.originalLifecycleBytes()), + peer("entity-management-service", NAMESPACE)); + var operationCorrelation = + callTerminalOutcome( + grpc, + terminalOutcomeRequest( + OPERATION_ID.toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("entity-management-service", NAMESPACE)); + var lifecycleCorrelation = + callTerminalOutcome( + grpc, + terminalOutcomeRequest( + fixture.readRequestId().toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("entity-management-service", NAMESPACE)); + var otherNamespace = fixture("other", "c0000000-0000-4000-8000-000000000001"); + var namespaceMismatch = + callTerminalOutcome( + grpc, + terminalOutcomeRequest( + TERMINAL_READ_ID.toString(), + otherNamespace.request().canonicalRequestBytes(), + otherNamespace.originalLifecycleBytes()), + peer("entity-management-service", NAMESPACE)); + + assertThat(malformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(operationCorrelation.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(lifecycleCorrelation.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(namespaceMismatch.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(placementService, currentService); + } + @Test void rejectsAuthenticatedEndUserContextBeforeParsingOrOwnerAccess() throws Exception { var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); @@ -447,6 +547,163 @@ void rejectsPlacementConflictAndMapsStorageFailures() throws Exception { assertThat(unknown.error).isEqualTo(Status.Code.INTERNAL); } + @Test + void terminalOutcomeReadReturnsExactAppliedBytesAndDoesNotConsultCurrentLocation() + throws Exception { + Fixture fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + var applied = + WorldCanonicalInitialPlayerLocation.Result.applied( + fixture.request(), + fixture.lifecycleEvidence().startLocation(), + fixture.lifecycleEvidence().runtimeRoomInstanceId()); + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + when(placementService.readTerminalOutcome(any())) + .thenReturn( + Optional.of( + new WorldCanonicalInitialPlayerLocationRepository.TerminalReadback( + applied, fixture.originalLifecycleBytes()))); + var grpc = service(placementService, currentService); + + Collector response = + callTerminalOutcome( + grpc, + terminalOutcomeRequest( + TERMINAL_READ_ID.toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("entity-management-service", NAMESPACE)); + + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value.getReadRequestId()).isEqualTo(TERMINAL_READ_ID.toString()); + assertThat(response.value.getPlacementOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.value.getPlacementRequestDigest()) + .isEqualTo(fixture.request().requestDigest()); + assertThat(response.value.getImmutablePlacementResultBytes().toByteArray()) + .containsExactly(applied.canonicalBytes()); + assertThat(response.value.getOriginalPlacementLifecycleEvidenceBytes().toByteArray()) + .containsExactly(fixture.originalLifecycleBytes()); + verify(placementService).readTerminalOutcome(any()); + verify(placementService, never()).place(any()); + verifyNoInteractions(currentService); + } + + @Test + void terminalOutcomeReadReturnsDurableConflictAsEvidenceInsteadOfGrpcConflict() throws Exception { + Fixture fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + var conflict = + WorldCanonicalInitialPlayerLocation.Result.conflict( + fixture.request(), "INITIAL_LOCATION_ALREADY_ASSIGNED"); + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + when(placementService.readTerminalOutcome(any())) + .thenReturn( + Optional.of( + new WorldCanonicalInitialPlayerLocationRepository.TerminalReadback( + conflict, fixture.originalLifecycleBytes()))); + var grpc = service(placementService, currentService); + + Collector response = + callTerminalOutcome( + grpc, + terminalOutcomeRequest( + TERMINAL_READ_ID.toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("entity-management-service", NAMESPACE)); + + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat( + WorldCanonicalInitialPlayerLocation.Result.fromStored( + fixture.request(), + response.value.getImmutablePlacementResultBytes().toByteArray()) + .outcome()) + .isEqualTo(WorldCanonicalInitialPlayerLocation.Outcome.CONFLICT); + assertThat(response.value.getImmutablePlacementResultBytes().toByteArray()) + .containsExactly(conflict.canonicalBytes()); + assertThat(response.value.getOriginalPlacementLifecycleEvidenceBytes().toByteArray()) + .containsExactly(fixture.originalLifecycleBytes()); + verify(placementService).readTerminalOutcome(any()); + verify(placementService, never()).place(any()); + verifyNoInteractions(currentService); + } + + @Test + void missingTerminalOutcomeRemainsNotFoundAndDoesNotInvokeMutationOrCurrentRead() + throws Exception { + Fixture fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + var placementService = mock(WorldCanonicalInitialPlayerLocationService.class); + var currentService = mock(WorldCanonicalCurrentPlayerLocationService.class); + when(placementService.readTerminalOutcome(any())).thenReturn(Optional.empty()); + var grpc = service(placementService, currentService); + + Collector response = + callTerminalOutcome( + grpc, + terminalOutcomeRequest( + TERMINAL_READ_ID.toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("entity-management-service", NAMESPACE)); + + assertThat(response.error).isEqualTo(Status.Code.NOT_FOUND); + assertThat(response.description).contains("remains unresolved"); + verify(placementService).readTerminalOutcome(any()); + verify(placementService, never()).place(any()); + verifyNoInteractions(currentService); + } + + @Test + void mismatchedOrCorruptTerminalResultFailsClosedWithoutReturningBytes() throws Exception { + Fixture fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); + var substitutedRequest = placementRequestWithOperation(fixture, OTHER_OPERATION_ID); + var substitutedResult = + WorldCanonicalInitialPlayerLocation.Result.applied( + substitutedRequest, + substitutedRequest.activeLifecycleEvidence().startLocation(), + substitutedRequest.activeLifecycleEvidence().runtimeRoomInstanceId()); + var mismatchedService = mock(WorldCanonicalInitialPlayerLocationService.class); + when(mismatchedService.readTerminalOutcome(any())) + .thenReturn( + Optional.of( + new WorldCanonicalInitialPlayerLocationRepository.TerminalReadback( + substitutedResult, fixture.originalLifecycleBytes()))); + var mismatched = + callTerminalOutcome( + service(mismatchedService, mock(WorldCanonicalCurrentPlayerLocationService.class)), + terminalOutcomeRequest( + TERMINAL_READ_ID.toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("entity-management-service", NAMESPACE)); + + var corruptResult = mock(WorldCanonicalInitialPlayerLocation.Result.class); + when(corruptResult.request()).thenReturn(fixture.request()); + when(corruptResult.requestDigest()).thenReturn(fixture.request().requestDigest()); + when(corruptResult.canonicalBytes()).thenReturn(new byte[] {1, 2, 3}); + var corruptService = mock(WorldCanonicalInitialPlayerLocationService.class); + when(corruptService.readTerminalOutcome(any())) + .thenReturn( + Optional.of( + new WorldCanonicalInitialPlayerLocationRepository.TerminalReadback( + corruptResult, fixture.originalLifecycleBytes()))); + var corrupt = + callTerminalOutcome( + service(corruptService, mock(WorldCanonicalCurrentPlayerLocationService.class)), + terminalOutcomeRequest( + TERMINAL_READ_ID.toString(), + fixture.request().canonicalRequestBytes(), + fixture.originalLifecycleBytes()), + peer("entity-management-service", NAMESPACE)); + + assertThat(mismatched.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(mismatched.value).isNull(); + assertThat(corrupt.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(corrupt.value).isNull(); + } + @Test void foundLocationReturnsExactLifecycleResultProofAndDistinctRegionUuids() throws Exception { var fixture = fixture(NAMESPACE, "b0000000-0000-4000-8000-000000000001"); @@ -685,6 +942,15 @@ private static ReadCanonicalCurrentPlayerLocationRequest readRequest( .build(); } + private static ReadCanonicalInitialPlayerLocationOutcomeRequest terminalOutcomeRequest( + String readRequestId, byte[] canonicalRequestBytes, byte[] lifecycleEvidenceBytes) { + return ReadCanonicalInitialPlayerLocationOutcomeRequest.newBuilder() + .setReadRequestId(readRequestId) + .setCanonicalPlacementRequestBytes(ByteString.copyFrom(canonicalRequestBytes)) + .setOriginalLifecycleEvidenceBytes(ByteString.copyFrom(lifecycleEvidenceBytes)) + .build(); + } + private static UnknownFieldSet unknownField() { return UnknownFieldSet.newBuilder() .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) @@ -727,6 +993,24 @@ private static Collector callRead( return response; } + private static Collector callTerminalOutcome( + WorldCanonicalPlayerLocationGrpcService service, + ReadCanonicalInitialPlayerLocationOutcomeRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector<>(); + Context context = + peer == null + ? Context.current() + : Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readCanonicalInitialPlayerLocationOutcome(request, response); + } finally { + context.detach(previous); + } + return response; + } + private static GrpcPeerIdentity peer(String service, String namespace) { return new GrpcPeerIdentity( "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); @@ -1279,6 +1563,7 @@ private record Fixture( private static final class Collector implements StreamObserver { private T value; private Status.Code error; + private String description; private boolean completed; @Override @@ -1290,7 +1575,9 @@ public void onNext(T response) { public void onError(Throwable failure) { assertThat(value).isNull(); assertThat(completed).isFalse(); - error = Status.fromThrowable(failure).getCode(); + Status status = Status.fromThrowable(failure); + error = status.getCode(); + description = status.getDescription(); } @Override From 1fd2da64ff5248d8c0aceb9b9ca86e7c61f0a46e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 8 Oct 2026 23:50:15 +1300 Subject: [PATCH 010/129] Bind publication to original selector and prove Account receipt failure semantics --- .../game-design-service/version-control.md | 2 + ...ame-authoring-publishing-and-activation.md | 2 + ...issionLeasePersistenceIntegrationTest.java | 223 +++++++++++++++++- .../WorldPublishedStartLocationClient.java | 52 ++++ .../VersionPublishCommandServiceImpl.java | 16 +- .../draft/IsolatedPublicationOwnerSetup.java | 7 +- ...leaseCanonicalIdentityIntegrationTest.java | 19 +- ...WorldPublishedStartLocationClientTest.java | 85 +++++++ .../VersionPublishCommandServiceImplTest.java | 93 +++++++- 9 files changed, 480 insertions(+), 19 deletions(-) create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/WorldPublishedStartLocationClient.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldPublishedStartLocationClientTest.java diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 921444e405..915670b3b4 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -6,6 +6,8 @@ Game Design is the canonical authored-history, publication-coordination, release ## Implementation Status +Full-version finalization now requires the exact original World selector evidence retained by its pending publication operation and passes it to the v2 release-bundle path; missing or changed evidence remains pending for reconciliation, not permission to recapture or abort. This local enforcement does not supply the missing authenticated creator/Account commit-order producer or enable the standalone selector transport. Current construction and executable proof limits are recorded in the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + External Git synchronization and canonical multi-branch merge semantics are not implemented. Current authoring uses Game Design-owned revision APIs with optimistic validation and ordered mutation calls, but `SaveRevision` does not provide deterministic replay: it lacks durable request/revision deduplication and can leave a World mutation committed without its corresponding Game Design revision when the later local save fails. ADR 0129's durable multi-owner coordinator, owner-local compare-and-swap application, synchronized commit fence, and proof that partially applied owner rows remain invisible to ordinary Draft reads are also not implemented. Current release-bundle schema and plugin publication/activation code incorrectly reuse Automation & Scripting's aggregate participant `contentDigest` where the dedicated Game Logic-owned `abilitySchemaDigest` is required; exact ability-schema compatibility therefore remains an implementation and proof gap. Plugin publication currently uses signed-only intake; [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md)'s approved unsigned provenance remains target-only. The plugin publication path now rejects terminal-state reuse: an uploaded `SUPERSEDED` or `REVOKED_DESIGN` row cannot be republished under the same `pluginVersionId`; target rollback still uses a new immutable plugin version and leaves the prior terminal row unchanged, while new-version rollback proof remains absent. Duplicate signed plugin `assetId` values are likewise not rejected before export and can produce ambiguous distribution-manifest keys; target intake rejects them deterministically before publication/export. The live World Management design handoff adds a separate lifecycle race: it checks Game Design's authoritative remote version state (`GetVersionState(...).versionState=DRAFT`) before its own transaction, but has no durable owner-local publication freeze or exact Game Design version-state epoch/fence in the mutation request. That remote state check is not proof that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). Migration V28 corrects the historical V13 default by retaining every affected row while moving only non-script-only rows whose exact V13 marker remains (`version_state=PUBLISHED`, `version_state_epoch=1`) and whose exact `(tenant_id, version_id)` `published_release_bundle` is absent to `FAILED`, incrementing the epoch and refreshing `updated_at`. Bundled full versions and script-only publication rows are untouched, and the marker predicate makes the correction idempotent. Validation follows the shared [Validation and Runtime Proof](../../../developer-workflows/validation-and-runtime-proof.md) workflow; PostgreSQL retained-row execution remains a required migration gate. This data correction is separate from the still-open `CompareAndSetVersionState` transition gap: the live path still accepts any non-null lifecycle state after its in-memory epoch check and does not enforce release-bundle/artifact or retirement guards. 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 5e8e9ce393..be77811ec3 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The current Gameplay-prerequisite construction remains non-activating. Full-version finalization now reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. The real backend control-ui issuance/current-actor source, complete Account source-writer fencing and callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Earlier construction CI executed all four Account source-composition, five environment-binding and 31 Draft authorization PostgreSQL cases successfully, while three Game Design canonical-release fixtures failed for missing policy source capture. Their receiving correction now freezes actual Game Design command/policy source snapshots before sealing; corrected physical execution remains required. These bounded changes do not upgrade the broader capability ratings below. + This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index 0c73f6f2ba..d938af3e49 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -32,6 +32,7 @@ import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseWireCodec; @@ -44,6 +45,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DelegatingDataSource; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -1183,7 +1185,7 @@ void lostReceiptCommitAcknowledgementDeniesThenRecoversOnlyThroughIndependentV90 } @Test - void receiptCommitFailureBeforePhysicalDelegateRollsBackWithoutReceiptOrIndependentRead() { + void receiptCommitFailureOrPriorWalDenialRollsBackWithoutReceiptOrIndependentRead() { var context = context(null); var original = pending(context, account(context)); UUID decision = UUID.randomUUID(); @@ -1204,10 +1206,16 @@ void receiptCommitFailureBeforePhysicalDelegateRollsBackWithoutReceiptOrIndepend .call(() -> owner.confirm(confirmationRequest(original, decision)))) .isInstanceOf(StatusRuntimeException.class) .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); - assertThat(trace.count("commit-attempt")).isEqualTo(1); + failure -> { + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + int commitAttempts = trace.count("commit-attempt"); + assertThat(commitAttempts).isBetween(0, 1); + if (commitAttempts == 0) assertGlobalWalCoverageFailure(failure); + else + assertCauseChainContainsMessage( + failure, "Test failed before physical receipt COMMIT"); + }); assertThat(trace.count("physical-commit")).isZero(); assertThat(trace.count("v90-read")).isZero(); assertThat( @@ -1937,6 +1945,54 @@ void lostOriginalAcknowledgementCannotCreateOriginalAckReceipt() { .isZero(); } + @Test + void originalAckReceiptCommitFailureBeforePhysicalDelegateRollsBackWithoutReadOrReceipt() { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var trace = new ReceiptCommitTrace(); + var receiptPhase = new AtomicBoolean(); + var dataSource = + originalAckReceiptDataSource( + context.dataSource(), trace, receiptPhase, ReceiptCommitFault.BEFORE_FIRST_COMMIT); + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(dataSource).execute(original, decision); + receiptPhase.set(true); + var committedOperation = operation(context, original).intoMap(); + var unchanged = storageSnapshot(context); + + assertThat(acknowledgement.evidence().canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(acknowledgement.evidence().sha256()).isEqualTo(original.sha256()); + assertThat(acknowledgement.decisionId()).isEqualTo(decision); + assertThat(acknowledgement.finalizationXid()) + .isEqualTo(committedOperation.get("finalization_xid")); + assertThat(acknowledgement.committedBeforeMs()).isPositive().isLessThan(expiresAt(original)); + assertThat(committedOperation.get("status")).isEqualTo("COMMITTED"); + assertThat(committedOperation.get("expires_at_ms")).isEqualTo(expiresAt(original)); + + var receiptExecutor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(dataSource); + assertThatThrownBy(() -> receiptExecutor.confirm(acknowledgement)) + .hasMessageContaining("Account receipt physical COMMIT unavailable") + .satisfies( + failure -> + assertCauseChainContainsMessage( + failure, "Test failed before physical receipt COMMIT")); + + assertThat(trace.count("original-physical-commit")).isEqualTo(1); + assertThat(trace.count("receipt-commit-attempt")).isEqualTo(1); + assertThat(trace.count("receipt-physical-commit")).isZero(); + assertThat(trace.count("receipt-readback-physical-commit")).isZero(); + assertThat(trace.count("receipt-exact-read")).isZero(); + assertThat(trace.count("receipt-durable-read")).isZero(); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isZero(); + assertThat(operation(context, original).intoMap()).isEqualTo(committedOperation); + assertThat(storageSnapshot(context)).isEqualTo(unchanged); + } + @Test void originalAckReceiptCreatedInCurrentTransactionIsNotDurableReadback() { var context = context(null); @@ -2096,6 +2152,107 @@ void originalAckReceiptRecoversExactOriginalProofAfterLostReceiptAcknowledgement assertThat(trace.count("original-physical-commit")).isEqualTo(1); } + @Test + void concurrentOriginalAckReceiptRecoveriesRetainExactProofBeforeAndAfterExpiry() + throws Exception { + var context = context(null); + var original = pending(context, account(context)); + UUID decision = UUID.randomUUID(); + var trace = new ReceiptCommitTrace(); + var receiptPhase = new AtomicBoolean(); + var dataSource = originalAckReceiptDataSource(context.dataSource(), trace, receiptPhase, true); + var originalExecutor = new AccountGameplayAdmissionOriginalCommitExecutor(dataSource); + var acknowledgement = originalExecutor.execute(original, decision); + receiptPhase.set(true); + var receiptExecutor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(dataSource); + + assertThatThrownBy(() -> receiptExecutor.confirm(acknowledgement)) + .hasMessageContaining("Account receipt physical COMMIT unavailable"); + assertThat(trace.count("original-physical-commit")).isEqualTo(1); + assertThat(trace.count("receipt-durable-read")).isZero(); + assertThat(databaseNow(context)).isLessThan(expiresAt(original)); + + var operationBeforeRecovery = operation(context, original).intoMap(); + var sourcesBeforeRecovery = storageSnapshot(context); + var receiptBeforeRecovery = originalAckReceiptRow(context, original).intoMap(); + var start = new CountDownLatch(1); + Callable duplicateRead = + () -> { + if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); + return retrySerialization(() -> receiptExecutor.read(original, decision)); + }; + + AccountGameplayAdmissionOriginalAckReceipt leftReceipt; + AccountGameplayAdmissionOriginalAckReceipt rightReceipt; + try (var executor = Executors.newFixedThreadPool(2)) { + var left = executor.submit(duplicateRead); + var right = executor.submit(duplicateRead); + start.countDown(); + leftReceipt = left.get(30, TimeUnit.SECONDS); + rightReceipt = right.get(30, TimeUnit.SECONDS); + } + + assertThat(databaseNow(context)).isLessThan(expiresAt(original)); + assertThat(rightReceipt).isEqualTo(leftReceipt); + assertThat(leftReceipt.operation().evidence().canonicalJson()) + .isEqualTo(original.canonicalJson()); + assertThat(leftReceipt.operation().evidence().sha256()).isEqualTo(original.sha256()); + assertThat(leftReceipt.operation().bindingDecisionId()).isEqualTo(decision); + assertThat(leftReceipt.requestId()).isEqualTo(requestId(original)); + assertThat(leftReceipt.accountId()) + .isEqualTo( + UUID.fromString( + (String) ((Map) original.carrier().get("bindingScope")).get("accountId"))); + assertThat(leftReceipt.leaseId()) + .isEqualTo(UUID.fromString((String) original.carrier().get("leaseId"))); + assertThat(leftReceipt.leaseFence()).isEqualTo(original.leaseFence().longValueExact()); + assertThat(leftReceipt.evidenceSha256()).isEqualTo(original.sha256()); + assertThat(leftReceipt.bindingDecisionId()).isEqualTo(decision); + assertThat(leftReceipt.expiresAtMs()).isEqualTo(expiresAt(original)); + assertThat(leftReceipt.committedBeforeMs()) + .isEqualTo(acknowledgement.committedBeforeMs()) + .isPositive() + .isLessThan(leftReceipt.expiresAtMs()); + assertThat(leftReceipt.finalizationXid()).isEqualTo(acknowledgement.finalizationXid()); + assertThat(leftReceipt.receiptXid()) + .isEqualTo((String) receiptBeforeRecovery.get("receipt_xid")); + assertThat(trace.count("original-physical-commit")).isEqualTo(1); + assertThat(trace.count("receipt-durable-read")).isGreaterThanOrEqualTo(2); + assertThat(trace.count("receipt-exact-read")).isZero(); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isEqualTo(1); + assertThat(originalAckReceiptRow(context, original).intoMap()).isEqualTo(receiptBeforeRecovery); + assertThat(operation(context, original).intoMap()).isEqualTo(operationBeforeRecovery); + assertThat(storageSnapshot(context)).isEqualTo(sourcesBeforeRecovery); + + // The V92 receipt is immutable historical proof; expiry does not restamp or renew it. + waitPastDeadline(context, original); + var recoveredAfterExpiry = receiptExecutor.read(original, decision); + assertThat(recoveredAfterExpiry).isEqualTo(leftReceipt); + assertThat(recoveredAfterExpiry.expiresAtMs()).isEqualTo(expiresAt(original)); + assertThat(recoveredAfterExpiry.committedBeforeMs()) + .isEqualTo(acknowledgement.committedBeforeMs()) + .isLessThan(expiresAt(original)); + assertThat(trace.count("original-physical-commit")).isEqualTo(1); + assertThat(trace.count("receipt-durable-read")).isGreaterThanOrEqualTo(3); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isEqualTo(1); + assertThat(originalAckReceiptRow(context, original).intoMap()).isEqualTo(receiptBeforeRecovery); + assertThat(operation(context, original).intoMap()).isEqualTo(operationBeforeRecovery); + assertThat(storageSnapshot(context)).isEqualTo(sourcesBeforeRecovery); + assertThatThrownBy(() -> originalExecutor.execute(original, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThat(trace.count("original-physical-commit")).isEqualTo(1); + assertThat(operation(context, original).intoMap()).isEqualTo(operationBeforeRecovery); + assertThat(storageSnapshot(context)).isEqualTo(sourcesBeforeRecovery); + } + private static Record confirm( Context context, AccountGameplayAdmissionLeaseEvidence original, UUID decision) { return Objects.requireNonNull( @@ -2150,16 +2307,16 @@ private static final class ReceiptCommitTrace { private final AtomicInteger commitAttempts = new AtomicInteger(); private final List events = new java.util.ArrayList<>(); - private void record(String kind, int connectionId) { + private synchronized void record(String kind, int connectionId) { events.add(new ReceiptCommitEvent(kind, connectionId)); } - private int count(String kind) { + private synchronized int count(String kind) { return (int) events.stream().filter(event -> event.kind().equals(kind)).count(); } - private List events() { - return events; + private synchronized List events() { + return List.copyOf(events); } } @@ -2224,6 +2381,20 @@ private static DataSource originalAckReceiptDataSource( ReceiptCommitTrace trace, AtomicBoolean receiptPhase, boolean loseFirstReceiptCommitAcknowledgement) { + return originalAckReceiptDataSource( + source, + trace, + receiptPhase, + loseFirstReceiptCommitAcknowledgement + ? ReceiptCommitFault.AFTER_FIRST_COMMIT + : ReceiptCommitFault.NONE); + } + + private static DataSource originalAckReceiptDataSource( + DataSource source, + ReceiptCommitTrace trace, + AtomicBoolean receiptPhase, + ReceiptCommitFault fault) { return new DelegatingDataSource(source) { @Override public Connection getConnection() throws SQLException { @@ -2251,13 +2422,15 @@ private Connection tracedConnection(Connection physical) { } int attempt = trace.commitAttempts.incrementAndGet(); trace.record("receipt-commit-attempt", connectionId); + if (attempt == 1 && fault == ReceiptCommitFault.BEFORE_FIRST_COMMIT) + throw new SQLException("Test failed before physical receipt COMMIT", "08006"); physical.commit(); trace.record( exactReadOnConnection.get() ? "receipt-readback-physical-commit" : "receipt-physical-commit", connectionId); - if (attempt == 1 && loseFirstReceiptCommitAcknowledgement) + if (attempt == 1 && fault == ReceiptCommitFault.AFTER_FIRST_COMMIT) throw new SQLException("Test lost physical receipt COMMIT response", "08006"); return null; } @@ -2343,6 +2516,36 @@ private static ReceiptCommitEvent firstEvent(ReceiptCommitTrace trace, String ki .orElseThrow(() -> new AssertionError("Missing receipt JDBC event: " + kind)); } + private static void assertGlobalWalCoverageFailure(Throwable failure) { + Throwable cause = failure; + while (cause != null) { + var serverError = + cause instanceof PSQLException postgresFailure + ? postgresFailure.getServerErrorMessage() + : null; + if (cause instanceof PSQLException postgresFailure + && serverError != null + && "account_admission_confirmation_wal_coverage".equals(serverError.getConstraint())) { + assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); + assertThat(postgresFailure.getMessage()) + .contains("Account admission confirmation WAL coverage unavailable"); + return; + } + cause = cause.getCause(); + } + throw new AssertionError( + "Expected the retained Account admission confirmation WAL coverage failure", failure); + } + + private static void assertCauseChainContainsMessage(Throwable failure, String expectedMessage) { + Throwable cause = failure; + while (cause != null) { + if (cause.getMessage() != null && cause.getMessage().contains(expectedMessage)) return; + cause = cause.getCause(); + } + throw new AssertionError("Expected cause chain to contain: " + expectedMessage, failure); + } + private static Record readConfirmation( Context context, AccountGameplayAdmissionLeaseEvidence original, UUID decision) { return Objects.requireNonNull( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/WorldPublishedStartLocationClient.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/WorldPublishedStartLocationClient.java new file mode 100644 index 0000000000..8daa29f4db --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/WorldPublishedStartLocationClient.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.gamedesign.client; + +import java.io.IOException; +import java.util.Objects; +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.world.WorldPublishedStartLocationEvidence; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Opt-in Game Design owner for the canonical reloading mTLS World selector client. Initial capture + * runs outside owner transactions; publication retries use the persisted operation evidence. This + * client does not authenticate a creator or establish Account COMMIT_ORDER. + */ +public final class WorldPublishedStartLocationClient implements AutoCloseable { + private final net.firedevops.firemud.common.world.WorldPublishedStartLocationClient transport; + + public WorldPublishedStartLocationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + this( + new net.firedevops.firemud.common.world.WorldPublishedStartLocationClient( + endpoints, tlsProperties, channelFactory, workloadNamespace)); + } + + WorldPublishedStartLocationClient( + net.firedevops.firemud.common.world.WorldPublishedStartLocationClient transport) { + this.transport = Objects.requireNonNull(transport); + } + + /** Explicit lifecycle initialization; no automatic feature activation or credential fallback. */ + public void init() throws IOException { + transport.init(); + } + + public WorldPublishedStartLocationEvidence read( + WorldPublishedStartLocationEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("World publication capture requires no owner transaction"); + } + return transport.read(Objects.requireNonNull(request)); + } + + @Override + public void close() throws IOException { + transport.close(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index e75f581c76..e4844d8f87 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -7,6 +7,7 @@ import java.util.Optional; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; @@ -300,6 +301,18 @@ private PublishWorkflowSnapshot finalizeFullVersion( "pending full-version attempt does not reference a draft version"); } + // The pending operation owns the original authenticated capture; never recapture on retry. + WorldPublishedStartLocationEvidence worldEvidence; + try { + worldEvidence = + Objects.requireNonNull( + publishAttemptRepository.requirePublicationPending(attempt), + "Original World publication evidence is required"); + } catch (RuntimeException unresolved) { + // Missing or changed original evidence is not proof that either owner can abort. + throw pendingReconciliation( + "original World publication evidence requires exact reconciliation", unresolved); + } VersionDto dto = versionMapper.toDto(version); publishAttemptService.recordFullVersionParticipantDigests( request.publishWorkflowId(), participantDigests); @@ -319,7 +332,8 @@ private PublishWorkflowSnapshot finalizeFullVersion( request.publishWorkflowId(), exportedManifest, generationConfigRevision, - participantDigests); + participantDigests, + worldEvidence); version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(version.getVersionStateEpoch() + 1L); version.setUpdatedAt(LocalDateTime.now()); diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index 1bc06dd84b..63a923a461 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -133,7 +133,12 @@ private static GameDesignPublicationOperation retain( attempt.setVersionNumber(versionRow.get(0, Integer.class)); attempt.setRequestDigest(selection.digest()); new PublishAttemptRepository(dsl).save(attempt); - new GameDesignPublicationOperationRepository(dsl).reserve(operation); + var publications = new GameDesignPublicationOperationRepository(dsl); + if (captureSources) { + publications.reserveSourceBacked(operation); + } else { + publications.reserve(operation); + } return operation; } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index fbe49693e8..bdf7f70b82 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; @@ -791,8 +792,8 @@ private WorldPublishedStartLocationEvidence selectorEvidence(Version version) th } /** - * ISOLATED upstream sources/freeze; synchronized selection and terminal GD rows are actual DB - * writes. + * ISOLATED upstream Account/World evidence; actual GD genesis, synchronized source snapshots, + * publication captures and terminal rows use the canonical owner repositories. */ private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation selectorOperation(Fixture fixture, Version version) { @@ -810,8 +811,18 @@ private WorldPublishedStartLocationEvidence selectorEvidence(Version version) th .execute( status -> { try { - return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.retain( - fixture.dsl(), target, version.getVersionStateEpoch()); + var operation = + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .retainSourceBacked(fixture.dsl(), target, version.getVersionStateEpoch()); + var capture = + new GameDesignPublicationOperationRepository(fixture.dsl()) + .readSourceCapture(operation) + .orElseThrow(); + assertThat(capture.policy().operation()).isEqualTo(operation); + assertThat(capture.policy().snapshot().binding()) + .isEqualTo(operation.account().input().selection().selectedCommit()); + assertThat(capture.command().operation()).isEqualTo(operation); + return operation; } catch (Exception failure) { throw new IllegalStateException(failure); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldPublishedStartLocationClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldPublishedStartLocationClientTest.java new file mode 100644 index 0000000000..1b401b6c46 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/WorldPublishedStartLocationClientTest.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.gamedesign.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +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.world.WorldPublishedStartLocationEvidence; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner adapter tests use explicit transport doubles; they do not prove a physical mTLS call. */ +class WorldPublishedStartLocationClientTest { + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void explicitTransportDoubleRetainsExactRequestEvidenceAndLifecycle() throws Exception { + var transport = + mock(net.firedevops.firemud.common.world.WorldPublishedStartLocationClient.class); + var request = mock(WorldPublishedStartLocationEvidence.Request.class); + var evidence = mock(WorldPublishedStartLocationEvidence.class); + when(transport.read(request)).thenReturn(evidence); + var client = new WorldPublishedStartLocationClient(transport); + + client.init(); + assertThat(client.read(request)).isSameAs(evidence); + client.close(); + + verify(transport).init(); + verify(transport).read(request); + verify(transport).close(); + } + + @Test + void refusesCaptureUnderOwnerTransactionOrSynchronization() { + var transport = + mock(net.firedevops.firemud.common.world.WorldPublishedStartLocationClient.class); + var request = mock(WorldPublishedStartLocationEvidence.Request.class); + var client = new WorldPublishedStartLocationClient(transport); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + verifyNoInteractions(transport); + } + + @Test + void propagatesUnavailableTransportDoubleWithoutEvidenceFallback() { + var transport = + mock(net.firedevops.firemud.common.world.WorldPublishedStartLocationClient.class); + var request = mock(WorldPublishedStartLocationEvidence.Request.class); + var failure = Status.UNAVAILABLE.asRuntimeException(); + when(transport.read(request)).thenThrow(failure); + assertThatThrownBy(() -> new WorldPublishedStartLocationClient(transport).read(request)) + .isSameAs(failure); + } + + @Test + void productionConstructorRejectsPlaintextBeforeOpeningChannel() { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(true); + var channels = mock(GrpcChannelFactory.class); + assertThatThrownBy( + () -> + new WorldPublishedStartLocationClient( + new ServiceEndpointsProperties(), tls, channels, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + verifyNoInteractions(channels); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 66a2b9a944..7c02d3093c 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -15,6 +16,7 @@ import java.util.List; import java.util.Optional; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; @@ -44,6 +46,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; import org.mockito.InOrder; import org.mockito.Mock; @@ -60,12 +63,17 @@ class VersionPublishCommandServiceImplTest { @Mock private VersionAssetArtifactService versionAssetArtifactService; @Mock private PublishedReleaseBundleService publishedReleaseBundleService; @Mock private RecordedParticipantDigestService recordedParticipantDigestService; + // Explicit repository/service double: owner storage and authenticated capture have separate + // proof. + @Mock private WorldPublishedStartLocationEvidence originalWorldEvidence; private VersionPublishCommandServiceImpl service; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); + when(publishAttemptRepository.requirePublicationPending(any(PublishAttempt.class))) + .thenReturn(originalWorldEvidence); when(publishedReleaseBundleService.findPublishedReleaseBundle( any(String.class), any(Long.class))) .thenReturn(Optional.empty()); @@ -184,7 +192,8 @@ void publishFullVersionUsesTenantScopedVersionSequence() { any(String.class), any(ExportedAssetManifest.class), any(String.class), - any(List.class))) + any(List.class), + same(originalWorldEvidence))) .thenReturn( new PublishedReleaseBundleDto( 1L, @@ -227,6 +236,24 @@ void publishFullVersionUsesTenantScopedVersionSequence() { assertEquals(8, dto.versionNumber()); assertEquals(VersionLifecycleState.PUBLISHED, dto.versionState()); assertEquals(2L, dto.versionStateEpoch()); + InOrder evidenceOrder = inOrder(publishAttemptRepository, publishedReleaseBundleService); + evidenceOrder.verify(publishAttemptRepository).requirePublicationPending(attempt); + evidenceOrder + .verify(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + same(originalWorldEvidence)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class)); verify(publishAttemptService) .createFullVersionAttempt(any(VersionDto.class), any(String.class), any(String.class)); verify(assetExportService).exportAssets("tenant-1", 8); @@ -433,7 +460,8 @@ void publishFullVersionDeletesExportedAssetsWhenAttestationWriteFails() { any(String.class), any(ExportedAssetManifest.class), any(String.class), - any(List.class)); + any(List.class), + same(originalWorldEvidence)); assertThrows( IllegalStateException.class, @@ -1008,7 +1036,8 @@ void postBundleFailureAfterRollbackMarksFailureAndCleansExportedAssets() { any(String.class), any(ExportedAssetManifest.class), any(String.class), - any(List.class))) + any(List.class), + same(originalWorldEvidence))) .thenReturn(bundle); when(publishedReleaseBundleService.findPublishedReleaseBundle("tenant-1", 10L)) .thenReturn(Optional.empty()); @@ -1234,6 +1263,64 @@ void failureMarkingCommitUncertaintyLeavesAttemptPendingAndDoesNotCleanAssets() .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void missingOrChangedOriginalWorldEvidenceCannotWriteBundle(boolean changed) { + String workflowId = "publish:tenant-1:publish-request:workflow-1"; + PublishAttempt attempt = fullAttempt(PublishAttemptStatus.PENDING, 10L, 1, workflowId); + Version version = fullVersion(10L, 1, VersionLifecycleState.DRAFT); + Game game = new Game(); + game.setId(1L); + game.setTenantId("tenant-1"); + when(gameRepository.findByTenantIdForUpdate("tenant-1")).thenReturn(game); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + when(versionRepository.findByTenantIdAndId("tenant-1", 10L)).thenReturn(Optional.of(version)); + when(publishGateService.collectFullVersionParticipantDigests( + any(VersionDto.class), any(String.class), any(String.class))) + .thenReturn(participantDigests()); + when(assetExportService.exportAssets("tenant-1", 1)) + .thenReturn(new ExportedAssetManifest("manifest-hash", List.of("manifest.json"))); + // Explicit owner repository double models unavailable or changed/sealed persisted evidence. + if (changed) { + when(publishAttemptRepository.requirePublicationPending(attempt)) + .thenThrow(new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED")); + } else { + when(publishAttemptRepository.requirePublicationPending(attempt)).thenReturn(null); + } + + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileFullVersionPublish( + new PublishWorkflowRequest("tenant-1", "notes", "workflow-1", workflowId))); + + assertEquals(VersionLifecycleState.DRAFT, version.getVersionState()); + verify(versionRepository, never()).save(any(Version.class)); + verify(versionAssetArtifactService, never()) + .markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + any(WorldPublishedStartLocationEvidence.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class)); + } + private PublishAttempt fullAttempt( PublishAttemptStatus status, long versionId, int versionNumber, String workflowId) { PublishAttempt attempt = new PublishAttempt(); From cb0910832ce61dcddc39d2d30c74dd24d24a6599 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 00:02:25 +1300 Subject: [PATCH 011/129] Prove historical World placement readback over exact workload mTLS --- ...orldCanonicalPlacementOutcomeMtlsTest.java | 399 ++++++++++++++++++ ...anonicalPlayerLocationGrpcServiceTest.java | 4 +- 2 files changed, 401 insertions(+), 2 deletions(-) create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlacementOutcomeMtlsTest.java diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlacementOutcomeMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlacementOutcomeMtlsTest.java new file mode 100644 index 0000000000..67b628dde3 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlacementOutcomeMtlsTest.java @@ -0,0 +1,399 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; +import io.grpc.Server; +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 java.math.BigInteger; +import java.net.InetSocketAddress; +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.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.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalCurrentPlayerLocationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialPlayerLocationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalPlayerLocationGrpcService; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialPlayerLocationOutcomeRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialPlayerLocationOutcomeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalPlayerLocationServiceGrpc; +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; + +/** Socket mTLS proof for terminal readback with a mocked owner, not database-to-socket proof. */ +class WorldCanonicalPlacementOutcomeMtlsTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_ID = uuid("c0000000-0000-4000-8000-000000000001"); + private static final AtomicLong SERIAL = new AtomicLong(1); + private static TestPki pki; + + private Server server; + private WorldCanonicalInitialPlayerLocationService owner; + + @BeforeAll + static void createTestPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair caKeys = newKeyPair(); + X500Name caName = new X500Name("CN=World Placement Outcome Test CA, O=FireMUD Test"); + X509Certificate ca = + issueCertificate(caName, caKeys.getPublic(), caName, caKeys.getPrivate(), true, null); + pki = + new TestPki( + ca, + issueLeaf( + caName, + caKeys.getPrivate(), + "world-management-service", + "spiffe://firemud/ns/test/sa/world-management-service"), + issueLeaf( + caName, + caKeys.getPrivate(), + "entity-management-service", + "spiffe://firemud/ns/test/sa/entity-management-service"), + issueLeaf( + caName, + caKeys.getPrivate(), + "game-session-service", + "spiffe://firemud/ns/test/sa/game-session-service"), + issueLeaf( + caName, + caKeys.getPrivate(), + "account-service", + "spiffe://firemud/ns/test/sa/account-service"), + issueLeaf( + caName, + caKeys.getPrivate(), + "other-namespace-entity", + "spiffe://firemud/ns/other/sa/entity-management-service"), + issueLeaf(caName, caKeys.getPrivate(), "no-workload-uri", null)); + } + + @AfterEach + void stopServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void sameNamespaceEntityCertificateReadsExactAppliedAndConflictEvidence() throws Exception { + Fixture appliedFixture = fixture("d0000000-0000-4000-8000-000000000001"); + Fixture conflictFixture = + withOperation( + fixture("e0000000-0000-4000-8000-000000000001"), + uuid("f0000000-0000-4000-8000-000000000001")); + var applied = + WorldCanonicalInitialPlayerLocation.Result.applied( + appliedFixture.request(), + appliedFixture.request().activeLifecycleEvidence().startLocation(), + appliedFixture.request().activeLifecycleEvidence().runtimeRoomInstanceId()); + var conflict = + WorldCanonicalInitialPlayerLocation.Result.conflict( + conflictFixture.request(), "INITIAL_LOCATION_ALREADY_ASSIGNED"); + startServer(); + when(owner.readTerminalOutcome(any())) + .thenReturn( + Optional.of( + new WorldCanonicalInitialPlayerLocationRepository.TerminalReadback( + applied, appliedFixture.originalLifecycleBytes())), + Optional.of( + new WorldCanonicalInitialPlayerLocationRepository.TerminalReadback( + conflict, conflictFixture.originalLifecycleBytes()))); + + ManagedChannel channel = channel(pki.entityClient()); + try { + var stub = + WorldCanonicalPlayerLocationServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + ReadCanonicalInitialPlayerLocationOutcomeResponse appliedResponse = + stub.readCanonicalInitialPlayerLocationOutcome(request(appliedFixture)); + ReadCanonicalInitialPlayerLocationOutcomeResponse conflictResponse = + stub.readCanonicalInitialPlayerLocationOutcome(request(conflictFixture)); + + assertEvidence(appliedResponse, appliedFixture, applied); + assertEvidence(conflictResponse, conflictFixture, conflict); + } finally { + stopChannel(channel); + } + verify(owner, times(2)).readTerminalOutcome(any()); + } + + @Test + void wrongWorkloadsAndWrongNamespaceAreDeniedBeforeOwnerInvocation() throws Exception { + Fixture fixture = fixture("d0000000-0000-4000-8000-000000000002"); + startServer(); + for (TestCertificate caller : + List.of(pki.gameSessionClient(), pki.accountClient(), pki.otherNamespaceEntityClient())) { + ManagedChannel channel = channel(caller); + try { + Throwable failure = + catchFailure( + () -> + WorldCanonicalPlayerLocationServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .readCanonicalInitialPlayerLocationOutcome(request(fixture))); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + } + verifyNoInteractions(owner); + } + + @Test + void missingOrUnidentifiedClientCertificateIsRejectedAtTheSocketBoundary() throws Exception { + Fixture fixture = fixture("d0000000-0000-4000-8000-000000000003"); + startServer(); + for (TestCertificate caller : new TestCertificate[] {null, pki.noWorkloadUriClient()}) { + ManagedChannel channel = channel(caller); + try { + Throwable failure = + catchFailure( + () -> + WorldCanonicalPlayerLocationServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .readCanonicalInitialPlayerLocationOutcome(request(fixture))); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(caller == null ? Status.Code.UNAVAILABLE : Status.Code.PERMISSION_DENIED); + } finally { + stopChannel(channel); + } + } + verifyNoInteractions(owner); + } + + private void startServer() throws Exception { + owner = mock(WorldCanonicalInitialPlayerLocationService.class); + var handler = + new WorldCanonicalPlayerLocationGrpcService( + owner, mock(WorldCanonicalCurrentPlayerLocationService.class), NAMESPACE); + 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( + io.grpc.ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private ManagedChannel channel(TestCertificate certificate) throws Exception { + var ssl = GrpcSslContexts.forClient().trustManager(pki.caCertificate()); + if (certificate != null) ssl.keyManager(certificate.privateKey(), certificate.certificate()); + return NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .sslContext(ssl.build()) + .build(); + } + + private static void stopChannel(ManagedChannel channel) throws InterruptedException { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + private static ReadCanonicalInitialPlayerLocationOutcomeRequest request(Fixture fixture) { + return ReadCanonicalInitialPlayerLocationOutcomeRequest.newBuilder() + .setReadRequestId(READ_ID.toString()) + .setCanonicalPlacementRequestBytes( + ByteString.copyFrom(fixture.request().canonicalRequestBytes())) + .setOriginalLifecycleEvidenceBytes(ByteString.copyFrom(fixture.originalLifecycleBytes())) + .build(); + } + + private static void assertEvidence( + ReadCanonicalInitialPlayerLocationOutcomeResponse response, + Fixture fixture, + WorldCanonicalInitialPlayerLocation.Result expected) { + assertThat(response.getReadRequestId()).isEqualTo(READ_ID.toString()); + assertThat(response.getPlacementOperationId()) + .isEqualTo(fixture.request().operationId().toString()); + assertThat(response.getPlacementRequestDigest()).isEqualTo(fixture.request().requestDigest()); + assertThat(response.getImmutablePlacementResultBytes().toByteArray()) + .containsExactly(expected.canonicalBytes()); + assertThat(response.getOriginalPlacementLifecycleEvidenceBytes().toByteArray()) + .containsExactly(fixture.originalLifecycleBytes()); + } + + /** Reuses the established complete canonical request fixture for positive socket requests. */ + private static Fixture fixture(String lifecycleReadId) throws Exception { + WorldCanonicalPlayerLocationGrpcServiceTest.Fixture canonicalFixture = + WorldCanonicalPlayerLocationGrpcServiceTest.fixture(NAMESPACE, lifecycleReadId); + return new Fixture(canonicalFixture.request(), canonicalFixture.originalLifecycleBytes()); + } + + private static Fixture withOperation(Fixture fixture, UUID operationId) { + var request = fixture.request(); + return new Fixture( + new WorldCanonicalInitialPlayerLocation.Request( + operationId, + request.canonicalTenantId(), + request.realmId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalAccountId(), + request.characterId(), + request.entityAssignmentOperationId(), + request.entityAssignmentDigest(), + request.initialAdmissionHoldId(), + request.initialAdmissionHoldFence(), + request.initialAdmissionRequestId(), + request.initialAdmissionRequestDigest(), + request.catalogRevision(), + request.initialAdmissionOwnerProofId(), + request.initialAdmissionOwnerProofDigest(), + request.pointerAuditId(), + request.pointerVersion(), + request.initialAdmissionOrigin(), + request.activeLifecycleEvidence()), + fixture.originalLifecycleBytes()); + } + + private static Throwable catchFailure(Runnable action) { + try { + action.run(); + return null; + } catch (Throwable failure) { + return failure; + } + } + + private static TestCertificate issueLeaf( + X500Name caName, PrivateKey caKey, String commonName, String workloadUri) throws Exception { + KeyPair keys = newKeyPair(); + GeneralName[] names = + 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") + }; + return new TestCertificate( + keys.getPrivate(), + issueCertificate( + new X500Name("CN=" + commonName + ", O=FireMUD Test"), + keys.getPublic(), + caName, + caKey, + false, + new GeneralNames(names))); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerKey, + boolean ca, + GeneralNames names) + throws Exception { + Instant now = Instant.now().minusSeconds(60); + var builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(SERIAL.getAndIncrement()), + Date.from(now), + Date.from(now.plusSeconds(14L * 24 * 60 * 60)), + 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, names); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerKey))); + } + + private static KeyPair newKeyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + WorldCanonicalInitialPlayerLocation.Request request, byte[] originalLifecycleBytes) {} + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate worldServer, + TestCertificate entityClient, + TestCertificate gameSessionClient, + TestCertificate accountClient, + TestCertificate otherNamespaceEntityClient, + TestCertificate noWorkloadUriClient) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java index 0472b71b0a..440f1e5626 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java @@ -1016,7 +1016,7 @@ private static GrpcPeerIdentity peer(String service, String namespace) { "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); } - private static Fixture fixture(String namespace, String readRequestId) throws Exception { + static Fixture fixture(String namespace, String readRequestId) throws Exception { var lifecycleEvidence = lifecycleEvidence(namespace, readRequestId); var request = placementRequest(lifecycleEvidence, OPERATION_ID); return new Fixture( @@ -1554,7 +1554,7 @@ private static UUID uuid(String value) { return UUID.fromString(value); } - private record Fixture( + record Fixture( WorldCanonicalInitialPlayerLocation.Request request, WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence, byte[] originalLifecycleBytes, From 5d3e93823b77d9eff625a1bf94088caf1b3b9538 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 00:08:45 +1300 Subject: [PATCH 012/129] Keep World historical readback proof on canonical owner paths --- .../world-runtime-and-movement.md | 2 ++ ...aphApplicationPostgresIntegrationTest.java | 27 +++++++------------ 2 files changed, 11 insertions(+), 18 deletions(-) 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..07a68d4469 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,8 @@ 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). +The unregistered [canonical initial-placement terminal read](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-placement-terminal-readback) returns exact historical operation evidence without current placement authorization. Its [socket mTLS proof](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlacementOutcomeMtlsTest.java) executes against the real handler and a mock owner; it is not database-to-socket or live settlement proof. The [PostgreSQL definition](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java) checks retained `APPLIED`/`CONFLICT` bytes and no mutation when new placement authority is denied; corrected physical execution remains pending. Physical readback after canonical termination remains an explicit World lifecycle/cleanup obligation: the legacy numeric-key termination writer is correctly rejected by the canonical execution-manifest guard and cannot manufacture that test state. Revisit the post-termination proof when the canonical owner transition and required cleanup acknowledgements are implemented; do not bypass the guard or infer termination from missing state. + ## 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/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 92112fee24..8c01a5006d 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -2077,7 +2077,7 @@ void canonicalInitialPlayerLocationCommitsAndFreshCorrelationRetryReplaysOrigina } @Test - void terminalInitialPlayerLocationReadbackReturnsStoredAppliedAndConflictAfterTermination() { + void terminalInitialPlayerLocationReadbackReturnsStoredResultsWithoutCurrentPlacementAuthority() { PlacementFixture fixture = initialPlayerLocationFixture(); var applied = fixture.service().place(fixture.request()); var secondRequest = @@ -2114,23 +2114,14 @@ void terminalInitialPlayerLocationReadbackReturnsStoredAppliedAndConflictAfterTe initialLocationSnapshot(fixture.request().canonicalGameInstanceId()); assertThat(fixture.repository().readTerminalOutcome(missingRequest)).isEmpty(); - var privateKeys = fixture.lifecycle().materialized().association().worldPrepareFields(); - lifecycleCommandService.terminateWorldInstance( - privateKeys.privateTenantKey(), - privateKeys.privateGameInstanceKey(), - fixture.activeEvidence().lifecycleEpoch(), - "initial-placement-terminal-readback", - "terminal readback proof"); - assertThat( - Objects.requireNonNull( - dsl.fetchOne( - "SELECT status FROM world_instance WHERE id=?", - fixture.lifecycle().materialized().association().worldInstanceId())) - .get("status", String.class)) - .isEqualTo("TERMINATED"); - - var appliedRead = fixture.repository().readTerminalOutcome(fixture.request()).orElseThrow(); - var conflictRead = fixture.repository().readTerminalOutcome(conflictRequest).orElseThrow(); + // The legacy termination writer is correctly denied for this canonical tenant. Do not bypass + // its execution-manifest guard to manufacture a terminal lifecycle. Physical post-termination + // proof remains open until the canonical termination/cleanup owner path exists. + var historicalReader = new WorldCanonicalInitialPlayerLocationService(fixture.repository()); + assertThatThrownBy(() -> historicalReader.place(fixture.request())) + .isInstanceOf(WorldCanonicalInitialPlayerLocationService.PlacementDeniedException.class); + var appliedRead = historicalReader.readTerminalOutcome(fixture.request()).orElseThrow(); + var conflictRead = historicalReader.readTerminalOutcome(conflictRequest).orElseThrow(); assertThat(appliedRead.result().outcome()) .isEqualTo(WorldCanonicalInitialPlayerLocation.Outcome.APPLIED); assertThat(appliedRead.result().canonicalBytes()).containsExactly(applied.canonicalBytes()); From 341a870e1aae4418904115263f5e88f21b510b48 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 00:27:38 +1300 Subject: [PATCH 013/129] Reserve and finalize the exact synchronized Draft publication --- .../game-design-service/version-control.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 + ...eDesignPublicationOperationRepository.java | 38 +++ .../SelectedDraftPublicationOwner.java | 227 +++++++++++++ .../repository/PublishAttemptRepository.java | 33 +- .../VersionPublishCommandServiceImpl.java | 102 ++++++ .../draft/IsolatedPublicationOwnerSetup.java | 119 ++++--- .../impl/PublishedWorldSelectorFixtures.java | 112 ++++-- ...emptServiceTransactionIntegrationTest.java | 320 +++++++++++++++--- 9 files changed, 829 insertions(+), 126 deletions(-) create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 915670b3b4..e92aebc03c 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -6,7 +6,7 @@ Game Design is the canonical authored-history, publication-coordination, release ## Implementation Status -Full-version finalization now requires the exact original World selector evidence retained by its pending publication operation and passes it to the v2 release-bundle path; missing or changed evidence remains pending for reconciliation, not permission to recapture or abort. This local enforcement does not supply the missing authenticated creator/Account commit-order producer or enable the standalone selector transport. Current construction and executable proof limits are recorded in the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +Full-version finalization now requires the exact original World selector evidence retained by its pending publication operation and passes it to the v2 release-bundle path; missing or changed evidence remains pending for reconciliation, not permission to recapture or abort. The unregistered `SelectedDraftPublicationOwner` reserves one existing synchronized Draft, using its exact immutable selection digest for the pending attempt and source-backed publication operation. Its backend finalization entry requires exact durable selection/operation readback and shares the existing finalization transaction; it does not allocate a replacement Draft or translate a legacy full-publish digest. Typed Account and World inputs are not authentication of their producers. This local enforcement does not supply the missing authenticated creator/Account commit-order producer or enable the standalone selector transport. Current construction and executable proof limits are recorded in the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). External Git synchronization and canonical multi-branch merge semantics are not implemented. Current authoring uses Game Design-owned revision APIs with optimistic validation and ordered mutation calls, but `SaveRevision` does not provide deterministic replay: it lacks durable request/revision deduplication and can leave a World mutation committed without its corresponding Game Design revision when the later local save fails. ADR 0129's durable multi-owner coordinator, owner-local compare-and-swap application, synchronized commit fence, and proof that partially applied owner rows remain invisible to ordinary Draft reads are also not implemented. Current release-bundle schema and plugin publication/activation code incorrectly reuse Automation & Scripting's aggregate participant `contentDigest` where the dedicated Game Logic-owned `abilitySchemaDigest` is required; exact ability-schema compatibility therefore remains an implementation and proof gap. Plugin publication currently uses signed-only intake; [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md)'s approved unsigned provenance remains target-only. The plugin publication path now rejects terminal-state reuse: an uploaded `SUPERSEDED` or `REVOKED_DESIGN` row cannot be republished under the same `pluginVersionId`; target rollback still uses a new immutable plugin version and leaves the prior terminal row unchanged, while new-version rollback proof remains absent. Duplicate signed plugin `assetId` values are likewise not rejected before export and can produce ambiguous distribution-manifest keys; target intake rejects them deterministically before publication/export. The live World Management design handoff adds a separate lifecycle race: it checks Game Design's authoritative remote version state (`GetVersionState(...).versionState=DRAFT`) before its own transaction, but has no durable owner-local publication freeze or exact Game Design version-state epoch/fence in the mutation request. That remote state check is not proof that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). 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 be77811ec3..a4f8264ab2 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 @@ -10,6 +10,8 @@ The current Gameplay-prerequisite construction remains non-activating. Full-vers This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. +The unregistered [selected-Draft owner](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java) uses the exact selection digest, existing synchronized Draft and source-backed operation in one writable `READ_COMMITTED` reservation. Its backend finalizer retains exact terminal publication/no-publication operation evidence with the attempt outcome. The [transaction proof definitions](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java) cover pending reservation replay, successful terminal replay, changed selection/Account-operation conflicts, missing-operation pending denial, and rollback with approved-remap candidate retention. Those database cases require corrected-head PostgreSQL execution. Fixtures apply the real Game Design policy/command source owner but stipulate external Account/World authority; neither the structured inputs nor these fixtures establish authenticated end-to-end production publication. Legacy new-Version publication remains insufficient for this canonical selected-Draft path, and no public or Temporal ingress is enabled by the backend entry. + Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. Official-hosted creator-content acceptance remains partial under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Account's individual-party and hosted-terms repositories now retain exact catalog, affirmative-acceptance and environment-binding operations; `AccountHostedTermsService` can resolve the external environment observation before SQL work and reread locked currentness in a caller-owned writable `READ_COMMITTED` transaction. The service and its trusted publication, environment and affirmative-action participants remain unregistered; current creator authentication and original multi-owner commit enforcement are not supplied by these storage APIs. `HostedTermsEnvironmentBindingPostgresIntegrationTest` exercises explicitly test-only authorities, not a real agreement or operative hosted service. Composed-head PostgreSQL execution, live authority provisioning, creator UI, transfer and organization workflows remain separate proof or implementation gaps. These foundations do not upgrade the broader capability ratings or authorize content writes. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java index 0714337e59..8de9790d60 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java @@ -7,6 +7,8 @@ import java.util.Optional; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -66,6 +68,42 @@ public GameDesignPublicationOperation requirePending( || !result.outcome().equals("PENDING")) { throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); } + requireExactSelection(operation); + return operation; + } + + /** Exact durable selection readback; canonical bytes alone do not authenticate its producer. */ + public void requireExactSelection(GameDesignPublicationOperation operation) { + Objects.requireNonNull(operation, "operation"); + var selected = operation.account().input().selection(); + var retained = + new AuthoredDraftPublishSelectionRepository(dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + selected.intent().canonicalTenantId(), + selected.intent().canonicalVersionId(), + selected.intent().publishRequestId()) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_SELECTION_UNAVAILABLE")) + .selection(); + if (!Arrays.equals(selected.canonicalBytes(), retained.canonicalBytes()) + || !selected.digest().equals(retained.digest())) { + throw new IllegalStateException("PUBLICATION_SELECTION_CHANGED"); + } + } + + /** Requires one exact operation and selection with the requested owner terminal state. */ + public GameDesignPublicationOperation requireOutcome( + String tenant, String workflow, long version, String digest, String outcome) { + var result = + read(workflow) + .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); + var operation = result.operation(); + if (!operation.tenantKey().equals(tenant) + || operation.versionId() != version + || !operation.selectionDigest().equals(digest) + || !Objects.equals(result.outcome(), outcome)) { + throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); + } + requireExactSelection(operation); return operation; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java new file mode 100644 index 0000000000..22e0167213 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java @@ -0,0 +1,227 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.entity.PublishAttempt; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; +import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; +import org.jooq.DSLContext; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Game Design owner entry for reserving publication of one existing synchronized + * Draft. It persists exact local selection/attempt/source state; supplied Account and World binding + * objects are structured evidence, not proof that either remote owner authenticated its producer. A + * production caller must obtain them from the authenticated Account publication producer and the + * protected World selector read. Isolated fixtures may supply synthetic values only to test this + * owner-local boundary. + */ +public final class SelectedDraftPublicationOwner { + private final GameRepository games; + private final VersionRepository versions; + private final AuthoredDraftPublishSelectionRepository selections; + private final PublishAttemptRepository attempts; + private final GameDesignPublicationOperationRepository operations; + + public SelectedDraftPublicationOwner(DSLContext dsl) { + Objects.requireNonNull(dsl, "dsl"); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + games = new GameRepository(dsl); + versions = new VersionRepository(dsl); + selections = new AuthoredDraftPublishSelectionRepository(dsl, coordinator); + attempts = new PublishAttemptRepository(dsl); + operations = new GameDesignPublicationOperationRepository(dsl); + } + + /** + * Retains a first or exact-replay selection and the original external publication inputs in one + * caller-owned writable READ_COMMITTED transaction. The immutable selection determines attempt + * identity; an old full-publish digest is never rewritten or upgraded here. + */ + public Reservation reserve( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(intent, "intent"); + Objects.requireNonNull(account, "account"); + Objects.requireNonNull(world, "world"); + + Version identityCandidate = + versions + .findByCanonicalTenantIdAndCanonicalVersionId( + intent.canonicalTenantId(), intent.canonicalVersionId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_VERSION_UNAVAILABLE")); + String tenantKey = identityCandidate.getTenantId(); + var game = games.findByTenantIdForUpdate(tenantKey); + if (game == null + || !intent.canonicalTenantId().equals(game.getCanonicalTenantId()) + || !intent.canonicalTenantId().equals(identityCandidate.getCanonicalTenantId())) { + throw new IllegalStateException("SELECTED_PUBLICATION_GAME_IDENTITY_CHANGED"); + } + + var selectionSnapshot = selections.reserve(intent); + var selection = selectionSnapshot.selection(); + var selectedBinding = account.input().selection(); + if (!Arrays.equals(selection.canonicalBytes(), selectedBinding.canonicalBytes()) + || !selection.digest().equals(selectedBinding.digest())) { + throw new IllegalStateException("SELECTED_PUBLICATION_SELECTION_CHANGED"); + } + + var operation = new GameDesignPublicationOperation(account, world); + String workflowId = + FiremudWorkflowIds.workflowId( + TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, + selection.target().gameDesignVersionTenantKey(), + "publish-request", + intent.publishRequestId()); + if (!workflowId.equals(operation.workflowId()) + || !selection.target().canonicalTenantId().equals(world.request().canonicalTenantId()) + || !selection.target().canonicalVersionId().equals(world.request().canonicalVersionId()) + || !intent.publishRequestId().equals(world.request().publicationRequestId()) + || !intent + .expectedVersionStateEpoch() + .equals(Long.toString(world.request().versionStateEpoch())) + || !selection + .selectedCommit() + .commitId() + .toString() + .equals(world.request().appliedCommitId()) + || !selection.digest().equals("sha256:" + world.request().requestDigest())) { + throw new IllegalStateException("SELECTED_PUBLICATION_OPERATION_BINDING_CHANGED"); + } + + if (!tenantKey.equals(selection.target().gameDesignVersionTenantKey())) { + throw new IllegalStateException("SELECTED_PUBLICATION_TENANT_KEY_CHANGED"); + } + Version version = + versions + .findByTenantIdAndIdForUpdate(tenantKey, selection.target().gameDesignVersionRowId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_VERSION_UNAVAILABLE")); + requireExactSelectedVersion(selection, version); + + PublishAttempt attempt = + attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElse(null); + if (attempt == null) { + attempt = new PublishAttempt(); + attempt.setTenantId(tenantKey); + attempt.setPublishWorkflowId(operation.workflowId()); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(version.getId()); + attempt.setVersionNumber(version.getVersionNumber()); + attempt.setRequestDigest(selection.digest()); + attempt = attempts.save(attempt); + } else { + requireExactSelectedAttempt(attempt, operation, version, selection.digest()); + if (attempt.getStatus() != PublishAttemptStatus.PENDING) { + throw new IllegalStateException("SELECTED_PUBLICATION_ATTEMPT_TERMINAL"); + } + } + + var capture = operations.reserveSourceBacked(operation); + var retained = + operations + .read(operation.workflowId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_READBACK_UNAVAILABLE")); + var retainedSelection = + selections + .read( + intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId()) + .orElseThrow( + () -> + new IllegalStateException( + "SELECTED_PUBLICATION_SELECTION_READBACK_UNAVAILABLE")) + .selection(); + if (!Arrays.equals(operation.canonicalBytes(), retained.operation().canonicalBytes()) + || !"PENDING".equals(retained.outcome()) + || !Arrays.equals(selection.canonicalBytes(), retainedSelection.canonicalBytes()) + || !capture.command().operation().equals(operation) + || !capture.policy().operation().equals(operation)) { + throw new IllegalStateException("SELECTED_PUBLICATION_RESERVATION_READBACK_CONFLICT"); + } + long attemptId = + Objects.requireNonNull(attempt.getId(), "reserved publication attempt must be persisted"); + return new Reservation(selection, operation, attemptId, capture); + } + + private static void requireExactSelectedVersion( + net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection selection, + Version version) { + var target = selection.target(); + var actualTarget = + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + if (!target.equals(actualTarget) + || version.getVersionState() != VersionLifecycleState.DRAFT + || version.isScriptOnly() + || version.getBaseVersionId() != null + || version.getScriptPatchVersion() != null + || !Long.toString(version.getVersionStateEpoch()) + .equals(selection.intent().expectedVersionStateEpoch())) { + throw new IllegalStateException("SELECTED_PUBLICATION_VERSION_CHANGED"); + } + } + + private static void requireExactSelectedAttempt( + PublishAttempt attempt, + GameDesignPublicationOperation operation, + Version version, + String selectionDigest) { + if (!Objects.equals(attempt.getTenantId(), operation.tenantKey()) + || !Objects.equals(attempt.getPublishWorkflowId(), operation.workflowId()) + || attempt.getPublishType() != PublishType.FULL_VERSION + || !Objects.equals(attempt.getVersionId(), version.getId()) + || attempt.getVersionNumber() != version.getVersionNumber() + || !Objects.equals(attempt.getRequestDigest(), selectionDigest)) { + throw new IllegalStateException("SELECTED_PUBLICATION_ATTEMPT_IDENTITY_CONFLICT"); + } + } + + private static void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Selected Draft publication reservation requires caller-owned writable READ_COMMITTED transaction"); + } + } + + public record Reservation( + net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection selection, + GameDesignPublicationOperation operation, + long attemptId, + GameDesignSourceRepository.Capture sourceCapture) { + public Reservation { + Objects.requireNonNull(selection); + Objects.requireNonNull(operation); + if (attemptId <= 0) { + throw new IllegalArgumentException("reserved publication attempt ID must be positive"); + } + Objects.requireNonNull(sourceCapture); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java index 6398910d75..d89272b811 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishAttemptRepository.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.model.PublishAttemptStatus; import net.firedevops.firemud.gamedesign.model.PublishType; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; import org.jooq.Condition; @@ -128,17 +129,31 @@ public void requirePublishedOperation(PublishAttempt attempt) { requireTerminalOperation(attempt, "PUBLISHED"); } + public void requireNoPublicationOperation(PublishAttempt attempt) { + requireTerminalOperation(attempt, "NO_PUBLICATION"); + } + private void requireTerminalOperation(PublishAttempt attempt, String outcome) { - var result = - new GameDesignPublicationOperationRepository(dsl) - .read(attempt.getPublishWorkflowId()) - .orElseThrow(() -> new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE")); - if (!outcome.equals(result.outcome()) - || !result.operation().selectionDigest().equals(attempt.getRequestDigest()) - || result.operation().versionId() != attempt.getVersionId() - || !result.operation().tenantKey().equals(attempt.getTenantId())) { - throw new IllegalStateException("PUBLICATION_OPERATION_SEALED_OR_CHANGED"); + requireSelectedPublicationReadback(attempt, outcome); + } + + /** Read-only exact operation/selection proof for callers outside the final owner transaction. */ + public GameDesignPublicationOperation requireSelectedPublicationReadback( + PublishAttempt attempt, String outcome) { + if (attempt == null + || attempt.getTenantId() == null + || attempt.getPublishWorkflowId() == null + || attempt.getVersionId() == null + || attempt.getRequestDigest() == null) { + throw new IllegalStateException("PUBLICATION_OPERATION_UNAVAILABLE"); } + return new GameDesignPublicationOperationRepository(dsl) + .requireOutcome( + attempt.getTenantId(), + attempt.getPublishWorkflowId(), + attempt.getVersionId(), + attempt.getRequestDigest(), + outcome); } /** diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index e4844d8f87..63d2782d72 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -40,6 +40,8 @@ value = "EI_EXPOSE_REP2", justification = "Injected collaborators remain internal service dependencies") public class VersionPublishCommandServiceImpl { + private static final java.util.regex.Pattern SELECTION_DIGEST = + java.util.regex.Pattern.compile("sha256:[0-9a-f]{64}"); private static final Logger logger = LoggingUtil.getLogger(VersionPublishCommandServiceImpl.class); @@ -218,6 +220,59 @@ public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowReques } } + /** + * Reconciles an already-reserved publication of one existing synchronized Draft. This backend + * entry does not allocate a Version or authenticate the retained Account/World evidence; it + * requires the exact durable selection and operation, and remains unregistered from creator RPC + * or Temporal ingress until their authenticated producers are connected. + */ + public PublishWorkflowSnapshot reconcileSelectedDraftFullVersionPublish( + String tenantId, + long selectedVersionId, + String notes, + String publishRequestId, + String publishWorkflowId) { + PublishWorkflowRequest request = + new PublishWorkflowRequest(tenantId, notes, publishRequestId, publishWorkflowId); + request = request.recoverMissingPublishRequestId(); + validateRequestIdentity(request); + PublishAttempt attempt = + publishAttemptRepository + .findByPublishWorkflowId(publishWorkflowId) + .orElseThrow( + () -> pendingReconciliation("selected Draft publication attempt is unavailable")); + if (!Objects.equals(attempt.getTenantId(), tenantId) + || !Objects.equals(attempt.getVersionId(), selectedVersionId) + || !isSelectionDigest(attempt.getRequestDigest())) { + throw pendingReconciliation("selected Draft publication identity is unavailable or changed"); + } + try { + requireExactSelectedPublication(attempt, request); + } catch (PendingReconciliationException unresolved) { + throw unresolved; + } catch (RuntimeException unresolved) { + throw pendingReconciliation( + "selected Draft publication requires exact operation reconciliation", unresolved); + } + return reconcileFullVersionPublish(request); + } + + /** User-facing semantics for the unregistered selected-Draft backend path. */ + public VersionDto publishSelectedDraftFullVersion( + String tenantId, + long selectedVersionId, + String notes, + String publishRequestId, + String publishWorkflowId) { + PublishWorkflowSnapshot snapshot = + reconcileSelectedDraftFullVersionPublish( + tenantId, selectedVersionId, notes, publishRequestId, publishWorkflowId); + if (!snapshot.isSucceeded()) { + throw publishFailure(snapshot.failureCode(), snapshot.failureMessage()); + } + return versionMapper.toDto(requireTenantVersion(tenantId, snapshot.versionId())); + } + private PublishAttempt reserveDraftAttempt(PublishWorkflowRequest request) { try { return publishAttemptService.executeFullVersionTransaction(() -> createDraftAttempt(request)); @@ -347,6 +402,7 @@ private PublishWorkflowSnapshot finalizeFullVersion( recordedParticipantDigestService.recordVerifiedDigests( dto.tenantId(), PublishType.FULL_VERSION, request.publishWorkflowId(), participantDigests); publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + publishAttemptRepository.sealPublication(attempt, true); return succeededSnapshot(attempt); } @@ -417,6 +473,9 @@ private void recordVerifiedAndSucceed( currentReadback.bundle().participantDigests()); if (current.getStatus() == PublishAttemptStatus.PENDING) { publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + if (isSelectionDigest(current.getRequestDigest())) { + publishAttemptRepository.sealPublication(current, true); + } } return null; }); @@ -491,6 +550,9 @@ private PublishWorkflowSnapshot failDefinitively( } publishAttemptService.markFullVersionFailed( request.publishWorkflowId(), failureCode, failureMessage); + if (isSelectionDigest(current.getRequestDigest())) { + publishAttemptRepository.sealPublication(current, false); + } // Approved launch remap sets may reference this failed candidate, so retain the row. return Boolean.TRUE; }); @@ -578,6 +640,10 @@ private PublishAttempt backfillLegacyFullVersionRequestDigest( private void validateFullVersionAttempt(PublishAttempt attempt, PublishWorkflowRequest request) { validateFullVersionAttemptIdentity(attempt, request); + if (isSelectionDigest(attempt.getRequestDigest())) { + requireExactSelectedPublication(attempt, request); + return; + } PublicationDigestRequestBinding binding = PublicationDigestRequestBinding.full( request.tenantId(), String.valueOf(attempt.getVersionId()), request.publishRequestId()); @@ -595,6 +661,10 @@ private void validateFullVersionAttempt(PublishAttempt attempt, PublishWorkflowR private void validateTerminalFullVersionAttempt( PublishAttempt attempt, PublishWorkflowRequest request) { validateFullVersionAttemptIdentity(attempt, request); + if (isSelectionDigest(attempt.getRequestDigest())) { + requireExactSelectedPublication(attempt, request); + return; + } if (attempt.getRequestDigest() == null) { // Legacy terminal attempts predate the digest column. Their canonical workflow identity, // persisted full-version scope, and exact release-bundle identity are the replay binding. @@ -609,6 +679,38 @@ private void validateTerminalFullVersionAttempt( } } + private void requireExactSelectedPublication( + PublishAttempt attempt, PublishWorkflowRequest request) { + try { + String expectedOutcome = + switch (attempt.getStatus()) { + case PENDING -> "PENDING"; + case SUCCEEDED -> "PUBLISHED"; + case FAILED -> "NO_PUBLICATION"; + }; + var operation = + publishAttemptRepository.requireSelectedPublicationReadback(attempt, expectedOutcome); + var selection = operation.account().input().selection(); + var intent = selection.intent(); + if (!Objects.equals(operation.tenantKey(), request.tenantId()) + || operation.versionId() != attempt.getVersionId() + || !Objects.equals(operation.workflowId(), request.publishWorkflowId()) + || !Objects.equals(intent.publishRequestId(), request.publishRequestId()) + || !Objects.equals(intent.notes(), request.notes())) { + throw new IllegalStateException("SELECTED_PUBLICATION_REQUEST_IDENTITY_CHANGED"); + } + } catch (PendingReconciliationException unresolved) { + throw unresolved; + } catch (RuntimeException unresolved) { + throw pendingReconciliation( + "selected Draft publication requires exact operation reconciliation", unresolved); + } + } + + private static boolean isSelectionDigest(String digest) { + return digest != null && SELECTION_DIGEST.matcher(digest).matches(); + } + private void validateFullVersionAttemptIdentity( PublishAttempt attempt, PublishWorkflowRequest request) { if (attempt == null diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index 63a923a461..09249e0ea3 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -14,7 +14,9 @@ import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; @@ -57,6 +59,19 @@ public static GameDesignPublicationOperation retainSourceBacked( return retain(dsl, target, draftEpoch, "ISOLATED remote owner transaction proof", true); } + public static GameDesignPublicationOperation retainSourceBacked( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + return retain(dsl, target, draftEpoch, notes, true); + } + + /** Creates actual synchronized source rows and selection, without any publication operation. */ + public static AuthoredDraftPublishSelectionRepository.SelectionSnapshot selectSourceBackedDraft( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + return prepareSelection(dsl, target, draftEpoch, notes, true).selection(); + } + private static GameDesignPublicationOperation retain( DSLContext dsl, DraftCommitBinding.TargetProof target, @@ -64,6 +79,47 @@ private static GameDesignPublicationOperation retain( String notes, boolean captureSources) throws Exception { + PreparedSelection prepared = prepareSelection(dsl, target, draftEpoch, notes, captureSources); + var selection = prepared.selection().selection(); + var intent = selection.intent(); + var operation = + IsolatedPublicationOperationFixtures.forSelection( + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + prepared.world()); + if (captureSources) { + operation = + new SelectedDraftPublicationOwner(dsl) + .reserve(intent, operation.account(), operation.world()) + .operation(); + } else { + var attempt = new PublishAttempt(); + attempt.setTenantId(target.gameDesignVersionTenantKey()); + attempt.setPublishWorkflowId(operation.workflowId()); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(target.gameDesignVersionRowId()); + var versionRow = + dsl.fetchOne( + "SELECT version_number FROM version WHERE id = ?", target.gameDesignVersionRowId()); + if (versionRow == null) { + throw new IllegalStateException("Selected authored Version row is absent"); + } + attempt.setVersionNumber(versionRow.get(0, Integer.class)); + attempt.setRequestDigest(selection.digest()); + new PublishAttemptRepository(dsl).save(attempt); + var publications = new GameDesignPublicationOperationRepository(dsl); + publications.reserve(operation); + } + return operation; + } + + private static PreparedSelection prepareSelection( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + boolean captureSources) + throws Exception { var seed = IsolatedPublicationOperationFixtures.fresh(target); var draft = seed.account().input().selection().selectedCommit(); var coordinator = new DraftCommitCoordinatorRepository(dsl); @@ -71,6 +127,11 @@ private static GameDesignPublicationOperation retain( // GD Draft-authorization operation or live Account authority issued by this helper. coordinator.claim(draft); coordinator.claimApplicationSlot(draft); + var ownerOutcomes = new java.util.ArrayList(); + if (captureSources) { + coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + ownerOutcomes.add(new GameDesignSourceRepository(dsl).apply(draft).ownerOutcome()); + } var epochs = draft.affectedUnits().stream() .map( @@ -94,54 +155,32 @@ private static GameDesignPublicationOperation retain( epochs); coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.WORLD_MANAGEMENT); coordinator.recordOwnerOutcome(draft, outcome); - var proof = new DraftCommitCoordinatorRepository.CoordinatorProof(draft, List.of(outcome)); + ownerOutcomes.add(outcome); + var proof = new DraftCommitCoordinatorRepository.CoordinatorProof(draft, ownerOutcomes); if (captureSources) { coordinator.advanceSourceVisibilityFence(draft, proof); } else { coordinator.advanceVisibilityFence(draft, proof); } coordinator.releaseApplicationSlot(draft); - var selection = - new AuthoredDraftPublishSelectionRepository(dsl, coordinator) - .reserve( - new AuthoredDraftPublishSelection.PublishIntent( - target.canonicalTenantId(), - target.canonicalVersionId(), - java.util.UUID.randomUUID().toString(), - Long.toString(draftEpoch), - notes, - draft.requestId(), - draft.commitId(), - draft.digest())) - .selection(); - var operation = - IsolatedPublicationOperationFixtures.forSelection( - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson(), selection.digest()), - seed.world()); - var attempt = new PublishAttempt(); - attempt.setTenantId(target.gameDesignVersionTenantKey()); - attempt.setPublishWorkflowId(operation.workflowId()); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setVersionId(target.gameDesignVersionRowId()); - var versionRow = - dsl.fetchOne( - "SELECT version_number FROM version WHERE id = ?", target.gameDesignVersionRowId()); - if (versionRow == null) { - throw new IllegalStateException("Selected authored Version row is absent"); - } - attempt.setVersionNumber(versionRow.get(0, Integer.class)); - attempt.setRequestDigest(selection.digest()); - new PublishAttemptRepository(dsl).save(attempt); - var publications = new GameDesignPublicationOperationRepository(dsl); - if (captureSources) { - publications.reserveSourceBacked(operation); - } else { - publications.reserve(operation); - } - return operation; + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + java.util.UUID.randomUUID().toString(), + Long.toString(draftEpoch), + notes, + draft.requestId(), + draft.commitId(), + draft.digest()); + var selection = new AuthoredDraftPublishSelectionRepository(dsl, coordinator).reserve(intent); + return new PreparedSelection(selection, seed.world()); } + private record PreparedSelection( + AuthoredDraftPublishSelectionRepository.SelectionSnapshot selection, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence world) {} + /** Storage fixture commit only; does not substitute for actual command finalization proof. */ public static PublishedReleaseBundle commitStorage( DSLContext dsl, diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java index 566327ef2d..54e173f5a4 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -232,6 +232,49 @@ private DraftCommitBinding freshGraphBinding() throws Exception { "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", "count", 0)))); + var revisions = policyRevisions(); + int worldRevisionOrder = revisions.size(); + revisions.add( + new RevisionPayload( + Integer.toString(worldRevisionOrder++), + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration))); + revisions.add( + new RevisionPayload( + Integer.toString(worldRevisionOrder++), + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null))); + revisions.add( + new RevisionPayload( + Integer.toString(worldRevisionOrder), + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))); + var affectedUnits = new java.util.ArrayList(); + affectedUnits.add( + new AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "REALM_ENTRY_POLICY_SET", + VERSION_ID.toString(), + "REALM_ENTRY_POLICY_SET", + "effective", + "0")); + affectedUnits.addAll( + List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList()); return DraftCommitBinding.create( new TargetProof( TENANT_ID, @@ -244,35 +287,46 @@ private DraftCommitBinding freshGraphBinding() throws Exception { REQUEST_ID, COMMIT_ID, "base-1", - List.of( - new RevisionPayload( - "0", - REGION_REVISION_ID, - DraftCommitBinding.Owner.WORLD_MANAGEMENT, - worldRevisionPayload( - REGION_REVISION_ID, - "WORLD_DESIGN_AGGREGATE_TYPE_REGION", - REGION_TEMPLATE_ID, - declaration)), - new RevisionPayload( - "1", - ZONE_REVISION_ID, - DraftCommitBinding.Owner.WORLD_MANAGEMENT, - worldRevisionPayload( - ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), - new RevisionPayload( - "2", - ROOM_REVISION_ID, - DraftCommitBinding.Owner.WORLD_MANAGEMENT, - worldRevisionPayload( - ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), - List.of( - affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), - affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), - affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) - .stream() - .flatMap(List::stream) - .toList()); + revisions, + affectedUnits); + } + + private List policyRevisions() throws Exception { + var revisions = new java.util.ArrayList(); + UUID revisionId = UUID.randomUUID(); + var policy = + Map.of( + "schemaVersion", + 1, + "worldSlug", + "starter-world", + "worldDisplayName", + "Starter World", + "realmSlug", + "realm-001", + "realmDisplayName", + "Realm 1", + "visible", + true, + "publicProduction", + true, + "stateScope", + "SHARED", + "entryPolicy", + "PRESEEDED_ONLY"); + String payload = + JSON.writeValueAsString( + Map.of( + "revisionKind", + "REALM_ENTRY_POLICY", + "logicalRevisionId", + revisionId.toString(), + "policy", + policy)); + revisions.add( + new RevisionPayload( + "0", revisionId, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, payload)); + return revisions; } private String worldRevisionPayload( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 0881817d9c..7f5ce3280c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -6,11 +6,16 @@ import java.time.LocalDateTime; import java.util.List; +import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; -import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; @@ -23,6 +28,8 @@ import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; @@ -30,11 +37,13 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -44,6 +53,9 @@ import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -86,6 +98,8 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private VersionAssetArtifactRepository versionAssetArtifactRepository; @Autowired private VersionRepository versionRepository; @Autowired private VersionTemplateRemapSetRepository templateRemapSetRepository; + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private AssetExportService assetExportService; @MockitoBean private PublishGateService publishGateService; @MockitoSpyBean private RecordedParticipantDigestService recordedParticipantDigestService; @@ -358,41 +372,65 @@ void publishAttemptSaveUsesRevisionCasAndRejectsStaleAndTerminalUpdates() { @Test void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogether() { String tenantId = "9002"; - String publishRequestId = "successful-reconcile-request"; - String publishWorkflowId = - FiremudWorkflowIds.workflowId( - TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, - tenantId, - "publish-request", - publishRequestId); Game game = new Game(); game.setTenantId(tenantId); game.setName("successful-transaction-proof-game"); gameRepository.save(game); + Version candidate = new Version(); + candidate.setTenantId(tenantId); + candidate.setVersionNumber(1); + candidate.setVersionState(VersionLifecycleState.DRAFT); + candidate.setVersionStateEpoch(1L); + candidate.setNotes("successful transaction proof"); + candidate = versionRepository.save(candidate); + var operation = reserveSelectedDraft(candidate, "successful transaction proof"); + var selection = + AuthoredDraftPublishSelection.fromStored( + operation.account().input().selection().canonicalJson(), + operation.account().input().selection().digest()); + var exactReservationRetry = + inOwnerTransaction( + () -> + new SelectedDraftPublicationOwner(dsl) + .reserve(selection.intent(), operation.account(), operation.world())); + assertThat(exactReservationRetry.selection()).isEqualTo(selection); + assertThat(exactReservationRetry.operation().canonicalBytes()) + .containsExactly(operation.canonicalBytes()); + assertThat(exactReservationRetry.attemptId()) + .isEqualTo( + publishAttemptRepository + .findByPublishWorkflowId(operation.workflowId()) + .orElseThrow() + .getId()); + String publishRequestId = operation.account().publishRequestId(); + String publishWorkflowId = operation.workflowId(); + var participantDigests = + PublishedWorldSelectorFixtures.participants(candidate.getId(), operation.world()); + Mockito.when( publishGateService.collectFullVersionParticipantDigests( Mockito.any(VersionDto.class), Mockito.eq(publishRequestId), Mockito.eq(publishWorkflowId))) - .thenAnswer( - invocation -> { - VersionDto version = invocation.getArgument(0); - return List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", - String.valueOf(version.id()), - "version:" + version.id(), - "transaction-proof-design-digest", - 1, - null, - null)); - }); + .thenReturn(participantDigests); Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(immutableEmptyManifest()); VersionDto publishedVersion = - versionPublishCommandService.publishFullVersion( - tenantId, "successful transaction proof", publishRequestId, publishWorkflowId); + versionPublishCommandService.publishSelectedDraftFullVersion( + tenantId, + candidate.getId(), + "successful transaction proof", + publishRequestId, + publishWorkflowId); + VersionDto terminalReplay = + versionPublishCommandService.publishSelectedDraftFullVersion( + tenantId, + candidate.getId(), + "successful transaction proof", + publishRequestId, + publishWorkflowId); + assertThat(terminalReplay.id()).isEqualTo(publishedVersion.id()); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); @@ -414,18 +452,163 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth assertThat(bundle.getPublishWorkflowId()).isEqualTo(publishWorkflowId); assertThat(bundle.getManifestHash()).isEqualTo("sha256:" + "a".repeat(64)); assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.PUBLISHED); + var terminalOperation = + new GameDesignPublicationOperationRepository(dsl).read(publishWorkflowId).orElseThrow(); + assertThat(terminalOperation.outcome()).isEqualTo("PUBLISHED"); + assertThat(terminalOperation.terminalEvidenceBytes()).isNotNull(); + publishAttemptRepository.requirePublishedOperation(attempt); + } + + @Test + void selectedDraftPublicationRemainsPendingWithoutItsOriginalOperation() throws Exception { + String tenantId = "9005"; + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("missing-original-operation-proof-game"); + gameRepository.save(game); + + Version candidate = new Version(); + candidate.setTenantId(tenantId); + candidate.setVersionNumber(1); + candidate.setVersionState(VersionLifecycleState.DRAFT); + candidate.setVersionStateEpoch(1L); + candidate.setNotes("missing original operation proof"); + candidate = versionRepository.save(candidate); + TargetProof target = targetProof(candidate); + long candidateId = candidate.getId(); + long candidateEpoch = candidate.getVersionStateEpoch(); + int candidateNumber = candidate.getVersionNumber(); + AtomicReference selectedRef = + new AtomicReference<>(); + AtomicReference workflowRef = new AtomicReference<>(); + inOwnerTransaction( + () -> { + try { + var selected = + IsolatedPublicationOwnerSetup.selectSourceBackedDraft( + dsl, target, candidateEpoch, "missing original operation proof"); + selectedRef.set(selected); + var intent = selected.selection().intent(); + String workflow = + FiremudWorkflowIds.workflowId( + TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, + target.gameDesignVersionTenantKey(), + "publish-request", + intent.publishRequestId()); + workflowRef.set(workflow); + PublishAttempt attempt = new PublishAttempt(); + attempt.setTenantId(target.gameDesignVersionTenantKey()); + attempt.setPublishWorkflowId(workflow); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(target.gameDesignVersionRowId()); + attempt.setVersionNumber(candidateNumber); + attempt.setRequestDigest(selected.selection().digest()); + publishAttemptRepository.save(attempt); + return null; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + var selection = selectedRef.get().selection(); + String workflow = workflowRef.get(); + + assertThatThrownBy( + () -> + versionPublishCommandService.publishSelectedDraftFullVersion( + tenantId, + candidateId, + "missing original operation proof", + selection.intent().publishRequestId(), + workflow)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("selected Draft publication requires exact operation reconciliation"); + assertThat(publishAttemptRepository.findByPublishWorkflowId(workflow).orElseThrow().getStatus()) + .isEqualTo(PublishAttemptStatus.PENDING); + assertThat( + versionRepository + .findByTenantIdAndId(tenantId, candidateId) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.DRAFT); + assertThat(publishedReleaseBundleRepository.findByTenantIdAndVersionId(tenantId, candidateId)) + .isEmpty(); + assertThat(versionAssetArtifactRepository.findByTenantIdAndVersionId(tenantId, candidateId)) + .isEmpty(); + assertThat(new GameDesignPublicationOperationRepository(dsl).read(workflow)).isEmpty(); + } + + @Test + void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence() { + String tenantId = "9006"; + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("changed-original-operation-proof-game"); + gameRepository.save(game); + + Version candidate = new Version(); + candidate.setTenantId(tenantId); + candidate.setVersionNumber(1); + candidate.setVersionState(VersionLifecycleState.DRAFT); + candidate.setVersionStateEpoch(1L); + candidate.setNotes("changed original operation proof"); + candidate = versionRepository.save(candidate); + var operation = reserveSelectedDraft(candidate, "changed original operation proof"); + var selection = + AuthoredDraftPublishSelection.fromStored( + operation.account().input().selection().canonicalJson(), + operation.account().input().selection().digest()); + + var changedIntent = + new AuthoredDraftPublishSelection.PublishIntent( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId(), + selection.intent().expectedVersionStateEpoch(), + selection.intent().notes() + " changed", + selection.intent().selectedCommitRequestId(), + selection.intent().selectedCommitId(), + selection.intent().selectedCommitDigest()); + assertThatThrownBy( + () -> + inOwnerTransaction( + () -> + new SelectedDraftPublicationOwner(dsl) + .reserve(changedIntent, operation.account(), operation.world()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed notes"); + + var changedAccount = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + operation.account().fenceId(), + operation.account().input(), + operation.account().sources()); + assertThatThrownBy( + () -> + inOwnerTransaction( + () -> + new SelectedDraftPublicationOwner(dsl) + .reserve(selection.intent(), changedAccount, operation.world()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + + var retained = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(); + assertThat(retained.outcome()).isEqualTo("PENDING"); + assertThat(retained.operation().canonicalBytes()).containsExactly(operation.canonicalBytes()); + assertThat( + publishAttemptRepository + .findByPublishWorkflowId(operation.workflowId()) + .orElseThrow() + .getStatus()) + .isEqualTo(PublishAttemptStatus.PENDING); } @Test void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet() { String tenantId = "9003"; - String publishRequestId = "failed-remap-request"; - String publishWorkflowId = - FiremudWorkflowIds.workflowId( - TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, - tenantId, - "publish-request", - publishRequestId); Game game = new Game(); game.setTenantId(tenantId); game.setName("failed-remap-proof-game"); @@ -439,8 +622,23 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( sourceVersion.setNotes("remap source"); sourceVersion = versionRepository.save(sourceVersion); long sourceVersionId = sourceVersion.getId(); + Version candidate = new Version(); + candidate.setTenantId(tenantId); + candidate.setVersionNumber(2); + candidate.setVersionState(VersionLifecycleState.DRAFT); + candidate.setVersionStateEpoch(1L); + candidate.setNotes("failed remap proof"); + candidate = versionRepository.save(candidate); AtomicReference candidateVersionId = new AtomicReference<>(); AtomicReference candidateVersionNumber = new AtomicReference<>(); + var operation = reserveSelectedDraft(candidate, "failed remap proof"); + String publishRequestId = operation.account().publishRequestId(); + String publishWorkflowId = operation.workflowId(); + long selectedCandidateVersionId = candidate.getId(); + candidateVersionId.set(selectedCandidateVersionId); + candidateVersionNumber.set(candidate.getVersionNumber()); + var participantDigests = + PublishedWorldSelectorFixtures.participants(candidate.getId(), operation.world()); AtomicReference exportedVersionNumber = new AtomicReference<>(); AtomicReference remapSetId = new AtomicReference<>(); AtomicReference recordedDigestFailure = new AtomicReference<>(); @@ -453,21 +651,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( Mockito.any(VersionDto.class), Mockito.eq(publishRequestId), Mockito.eq(publishWorkflowId))) - .thenAnswer( - invocation -> { - VersionDto candidate = invocation.getArgument(0); - candidateVersionId.set(candidate.id()); - candidateVersionNumber.set(candidate.versionNumber()); - return List.of( - new PublishParticipantDigestDto( - "GAME_DESIGN_CONTROL_PLANE", - String.valueOf(candidate.id()), - "version:" + candidate.id(), - "failed-remap-design-digest", - 1, - null, - null)); - }); + .thenReturn(participantDigests); Mockito.doAnswer( invocation -> { try { @@ -522,8 +706,12 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( Throwable publishFailure = catchThrowable( () -> - versionPublishCommandService.publishFullVersion( - tenantId, "failed remap proof", publishRequestId, publishWorkflowId)); + versionPublishCommandService.publishSelectedDraftFullVersion( + tenantId, + selectedCandidateVersionId, + "failed remap proof", + publishRequestId, + publishWorkflowId)); assertThat(publishFailure).isInstanceOf(RuntimeException.class); PublishAttempt attempt = @@ -580,6 +768,11 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( assertThat(retainedRemapSet.getApprovedAt()).isNotNull(); assertThat(retainedRemapSet.getSourceVersionId()).isEqualTo(sourceVersionId); assertThat(retainedRemapSet.getTargetVersionId()).isEqualTo(candidateVersionId.get()); + var terminalOperation = + new GameDesignPublicationOperationRepository(dsl).read(publishWorkflowId).orElseThrow(); + assertThat(terminalOperation.outcome()).isEqualTo("NO_PUBLICATION"); + assertThat(terminalOperation.terminalEvidenceBytes()).isNotNull(); + publishAttemptRepository.requireNoPublicationOperation(attempt); } private static String firstStackFrame(Throwable failure) { @@ -589,6 +782,39 @@ private static String firstStackFrame(Throwable failure) { return failure.getStackTrace()[0].toString(); } + private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation + reserveSelectedDraft(Version version, String notes) { + TargetProof target = targetProof(version); + return inOwnerTransaction( + () -> { + try { + // Account/World values produced by this helper are isolated external fixtures; the GD + // selection, command/policy source, attempt and publication reservation are real. + return IsolatedPublicationOwnerSetup.retainSourceBacked( + dsl, target, version.getVersionStateEpoch(), notes); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + + private static TargetProof targetProof(Version version) { + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + } + + private T inOwnerTransaction(java.util.function.Supplier action) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return transaction.execute(status -> action.get()); + } + private static ExportedAssetManifest immutableEmptyManifest() { return new ExportedAssetManifest("sha256:" + "a".repeat(64), 1, List.of(), List.of()); } From ed928219ee3428073910f1845eaa975e8814a30a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 01:26:52 +1300 Subject: [PATCH 014/129] Build bounded Account creator issuance and authenticated held-order proof --- .github/workflows/ci.yml | 9 + ...ount-owned-hosted-terms-acceptance-gate.md | 2 +- .../account-service/api-contracts.md | 2 +- ...ame-authoring-publishing-and-activation.md | 4 + .../v1/draft_commit_order_service.proto | 34 + .../AccountControlUiAuthority.java | 355 ++++++++++ ...ccountDraftCommitOrderReadGrpcService.java | 113 ++++ .../AccountDraftCommitOrderReadService.java | 128 ++++ .../DraftAuthorizationFenceRepository.java | 26 + ...ccountJwtSignerDesiredStateRepository.java | 79 +++ .../service/impl/AccountServiceImpl.java | 41 ++ .../session/AccountControlUiActorService.java | 248 +++++++ .../session/AccountControlUiCoordination.java | 268 ++++++++ .../AccountControlUiIssuanceRepository.java | 552 +++++++++++++++ .../AccountControlUiIssuanceService.java | 422 ++++++++++++ .../session/AccountControlUiKeyring.java | 47 ++ .../AccountControlUiRegistryContract.java | 45 ++ .../AccountControlUiResponseCryptography.java | 76 +++ .../session/AccountControlUiSignerOwner.java | 201 ++++++ .../session/AccountControlUiSigningSpec.java | 79 +++ .../AccountMountedJwtSignerBundle.java | 81 +++ ...unt_control_ui_owner_and_source_guards.sql | 258 +++++++ .../lua/account-control-ui-registry-cas.lua | 51 ++ ...lUiSourceGuardPostgresIntegrationTest.java | 314 +++++++++ ...ommitOrderReadPostgresIntegrationTest.java | 446 ++++++++++++ ...trolUiIssuancePostgresIntegrationTest.java | 396 +++++++++++ ...iOwnerWorkflowPostgresIntegrationTest.java | 634 ++++++++++++++++++ ...AuthenticationPostgresIntegrationTest.java | 331 +++++++++ .../AccountControlUiAuthorityTest.java | 106 +++ ...countDraftCommitOrderReadGrpcMtlsTest.java | 525 +++++++++++++++ ...ntDraftCommitOrderReadGrpcServiceTest.java | 145 ++++ ...ccountDraftCommitOrderReadServiceTest.java | 268 ++++++++ .../AccountControlUiCoordinationTest.java | 237 +++++++ .../AccountControlUiIssuanceWorkflowTest.java | 556 +++++++++++++++ ...untControlUiPrimaryAuthenticationTest.java | 143 ++++ ...ountControlUiResponseCryptographyTest.java | 102 +++ .../AccountControlUiSigningAndActorTest.java | 365 ++++++++++ .../authoring/DraftCommitOrderReadClient.java | 142 ++++ .../DraftCommitOrderReadEvidence.java | 92 +++ .../DraftCommitOrderReadGrpcCodec.java | 97 +++ .../DraftCommitOrderReadClientMtlsTest.java | 519 ++++++++++++++ .../DraftCommitOrderReadClientTest.java | 150 +++++ .../DraftCommitOrderReadGrpcCodecTest.java | 145 ++++ .../tenant/WorldDraftCommitOrderVerifier.java | 45 ++ .../WorldDraftCommitOrderVerifierTest.java | 184 +++++ 45 files changed, 9061 insertions(+), 2 deletions(-) create mode 100644 protos/account/v1/draft_commit_order_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiKeyring.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryContract.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptography.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningSpec.java create mode 100644 services/account-service/src/main/resources/db/migration/V99__account_control_ui_owner_and_source_guards.sql create mode 100644 services/account-service/src/main/resources/redis/lua/account-control-ui-registry-cas.lua create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcMtlsTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptographyTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodecTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifier.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifierTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1b8aa7a151..6c02b1552f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -995,6 +995,15 @@ jobs: ./gradlew :${{ matrix.module }}:check -PfullCheck echo "::endgroup::" + - name: 📤 Capture owner integration test XML + if: ${{ always() && contains(fromJSON('["account-service", "game-design-service", "world-management-service"]'), matrix.module) }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: owner-integration-xml-${{ matrix.module }}-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: services/${{ matrix.module }}/build/test-results/integrationTest/*.xml + if-no-files-found: warn + retention-days: 7 + - name: 📤 Capture Account Draft authorization fence PostgreSQL XML if: ${{ always() && matrix.module == 'account-service' }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 diff --git a/design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md b/design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md index 73871f1b5e..c16f41de5f 100644 --- a/design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md +++ b/design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -This decision is target state only. FireMUD currently has no hosted-creator-party registry, immutable hosted-terms catalog, individual or organization acceptance API/storage, signer-authority evidence, creator acceptance UI, Game Design hosted-content gate, durable party/evidence binding, creator-party transfer workflow, route-matrix coverage/proof for the gate, material-change reacceptance invalidation, or focused tests for these behaviors. The [Hosted Content Terms](../../../HOSTED_CONTENT_TERMS.md) file remains a pre-launch policy baseline and is not an operative contract. Until the organization path is implemented and legally reviewed, official hosting may enable only individuals aged 18 years or older acting in their own capacity and must reject organization acceptance rather than infer it. +The complete hosted creator gate remains target state. The unregistered Account owner workflow now has bounded individual creator-party storage, immutable terms publication and acceptance storage, environment binding, source-currentness checks and focused tests; these foundations do not prove operative legal publication, production identity verification, a registered creator acceptance API/UI, organization signer authority, creator-party transfer, or an authenticated end-to-end Game Design commit gate. Current capability and proof limits belong to [Account API implementation status](../microservices/account-service/api-contracts.md#implementation-status) and the [authoring implementation tracker](../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status), not to storage presence alone. The [Hosted Content Terms](../../../HOSTED_CONTENT_TERMS.md) file remains a pre-launch policy baseline and is not an operative contract. Until the organization path is implemented and legally reviewed, official hosting may enable only individuals aged 18 years or older acting in their own capacity and must reject organization acceptance rather than infer it. ## Decision Record diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 89fde149b4..b926faf323 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ Current explicit JOIN status: the local `/auth/bootstrap/join` controller and op Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. -Bounded hosted Creator Party, terms-catalog, acceptance/currentness and environment-binding owner storage exists, but no registered hosted-terms API or complete creator-authorized commit path is enabled. The [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md) records the implemented boundary and remaining proof. Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. +Bounded hosted Creator Party, terms-catalog, acceptance/currentness and environment-binding owner storage exists, but no registered hosted-terms API or complete creator-authorized commit path is enabled. The unregistered backend control-ui construction adds primary-authenticated issuance, exact protected recovery and a current-actor Draft ordering entry for one existing initial creator; neither that entry nor the standalone World-only held-order read enables a public route or supplies an authenticated end-to-end World commit by itself. Deadline-qualified authorizations remain denied without physical commit enforcement. The [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md) records the implemented boundary and remaining proof. Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. 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 a4f8264ab2..9cbbd70a2d 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 @@ -8,6 +8,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a The current Gameplay-prerequisite construction remains non-activating. Full-version finalization now reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. The real backend control-ui issuance/current-actor source, complete Account source-writer fencing and callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Earlier construction CI executed all four Account source-composition, five environment-binding and 31 Draft authorization PostgreSQL cases successfully, while three Game Design canonical-release fixtures failed for missing policy source capture. Their receiving correction now freezes actual Game Design command/policy source snapshots before sealing; corrected physical execution remains required. These bounded changes do not upgrade the broader capability ratings below. +The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. + +Creator issuance preserves the existing OTP failure budget by committing a primary-authentication denial's accounting before returning the credential error; successful OTP consumption still rolls back if subsequent preparation fails. Its real PostgreSQL definitions use the primary hook's Spring transaction interceptor, not only a direct method call. Positive issuance and original-signer rotation proof are additionally blocked by Account's current readiness owner: validator inventory is always incomplete, and a complete claim without protected per-validator evidence is quarantined. No real committed signer can be produced through that owner path yet; synthetic signer fixtures cannot close the original APPLIED/release prerequisite. The broader JWT capability remains owned by [Shared Runtime Contracts](./shared-runtime-contracts-and-persistence.md). + This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. The unregistered [selected-Draft owner](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java) uses the exact selection digest, existing synchronized Draft and source-backed operation in one writable `READ_COMMITTED` reservation. Its backend finalizer retains exact terminal publication/no-publication operation evidence with the attempt outcome. The [transaction proof definitions](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java) cover pending reservation replay, successful terminal replay, changed selection/Account-operation conflicts, missing-operation pending denial, and rollback with approved-remap candidate retention. Those database cases require corrected-head PostgreSQL execution. Fixtures apply the real Game Design policy/command source owner but stipulate external Account/World authority; neither the structured inputs nor these fixtures establish authenticated end-to-end production publication. Legacy new-Version publication remains insufficient for this canonical selected-Draft path, and no public or Temporal ingress is enabled by the backend entry. diff --git a/protos/account/v1/draft_commit_order_service.proto b/protos/account/v1/draft_commit_order_service.proto new file mode 100644 index 0000000000..75d585c526 --- /dev/null +++ b/protos/account/v1/draft_commit_order_service.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone exact held-COMMIT_ORDER read. It is intentionally not runtime-registered here. +service AccountDraftCommitOrderReadService { + rpc ReadHeldOriginalCommitOrder(ReadHeldOriginalCommitOrderRequest) + returns (ReadHeldOriginalCommitOrderResponse); +} + +message ReadHeldOriginalCommitOrderRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical original Account fence bytes; this is identity, not permission. + bytes original_account_binding = 4; +} + +enum HeldOriginalCommitOrderStatus { + HELD_ORIGINAL_COMMIT_ORDER_STATUS_UNSPECIFIED = 0; + HELD_ORIGINAL_COMMIT_ORDER_STATUS_HELD = 1; +} + +message ReadHeldOriginalCommitOrderResponse { + // The complete request tuple is echoed exactly. Only HELD is a successful response. + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_account_binding = 4; + HeldOriginalCommitOrderStatus status = 5; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java new file mode 100644 index 0000000000..1eccd236ae --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java @@ -0,0 +1,355 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Actual existing-source capture for one initial creator, in the caller's owner transaction. */ +public final class AccountControlUiAuthority { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final AccountDraftSourceCompositionService sources; + + public AccountControlUiAuthority(AccountDraftSourceCompositionService sources) { + this.sources = Objects.requireNonNull(sources); + } + + public Snapshot capture(UUID actor, UUID tenant, CapturedEnvironmentBoundary environment) { + var existing = sources.readExistingSources(environment, tenant); + requireNoApplicableDeadline(existing); + return snapshot(actor, tenant, existing); + } + + /** Discovers only the existing initial creator; primary authentication must still match it. */ + public Snapshot captureInitial(UUID tenant, CapturedEnvironmentBoundary environment) { + var existing = sources.readExistingSources(environment, tenant); + requireNoApplicableDeadline(existing); + return snapshot(existing.membership().accountUuid(), tenant, existing); + } + + private static void requireNoApplicableDeadline( + AccountDraftSourceCompositionService.ExistingSources existing) { + // Only the locked typed owner readback proves absence; opaque source bytes are not a lease. + var terms = Objects.requireNonNull(Objects.requireNonNull(existing.hostedTerms()).terms()); + if (terms.validUntil() != null || terms.disclosedDeadline() != null) { + throw new IllegalStateException( + "Deadline-qualified hosted terms cannot authorize this minimum commit producer"); + } + } + + private Snapshot snapshot( + UUID actor, UUID tenant, AccountDraftSourceCompositionService.ExistingSources existing) { + var member = existing.membership(); + if (!actor.equals(member.accountUuid()) + || !tenant.equals(member.tenantUuid()) + || !member.roleSource().roles().equals(List.of("tenantAdmin")) + || !member.pairSource().membershipExists() + || member.pairSource().lastTransitionInvalidated()) { + throw new IllegalStateException("Current authenticated initial creator authority required"); + } + var tuple = member.authorityTuple(); + var selected = java.util.Set.of(tenant.toString()); + if (!tuple.tenantAuthorityGeneration().keySet().equals(selected) + || !tuple.membershipAuthorityGeneration().keySet().equals(selected) + || !member.membershipVersion().keySet().equals(selected) + || member.authoritySnapshot().tenants().size() != 1 + || member.authoritySnapshot().memberships().size() != 1) { + throw new IllegalStateException("Exact single selected creator tenant authority required"); + } + Map authority = new LinkedHashMap<>(); + authority.put("issuerAuthGeneration", Long.parseLong(tuple.issuerAuthGeneration())); + authority.put("accountAuthorityGeneration", Long.parseLong(tuple.accountAuthorityGeneration())); + authority.put("tenantAuthorityGeneration", numeric(tuple.tenantAuthorityGeneration())); + authority.put("membershipAuthorityGeneration", numeric(tuple.membershipAuthorityGeneration())); + if (!tuple.privateRealmGrantVersions().isEmpty()) { + throw new IllegalStateException("Creator control does not acquire gameplay grants"); + } + authority.put("privateRealmGrantVersions", List.of()); + tuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> + authority.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + Long.parseLong(cutoff.accountAuthorityGeneration()), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + Long.parseLong(cutoff.outboxSequence())))); + tuple + .tenantBillingCutoff() + .ifPresent( + cutoffs -> { + Map values = new LinkedHashMap<>(); + cutoffs.forEach( + (id, cutoff) -> + values.put( + id, + Map.of( + "tenantAuthorityGeneration", + Long.parseLong(cutoff.tenantAuthorityGeneration()), + "tenantBillingSequence", + Long.parseLong(cutoff.tenantBillingSequence()), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + Long.parseLong(cutoff.outboxSequence())))); + authority.put("tenantBillingCutoff", Map.copyOf(values)); + }); + var upstream = existing.issuerAccount(); + byte[] issuer = upstream.canonicalIssuerProjection().toJson().getBytes(StandardCharsets.UTF_8); + byte[] account = + upstream.canonicalAccountProjection().toJson().getBytes(StandardCharsets.UTF_8); + byte[] membership = member.sourceEvent().canonicalJsonUtf8(); + var vector = new ArrayList(existing.hostedTerms().sourceEvidence()); + vector.add( + new SourceEvidence( + SourceKind.ISSUER, + "firemud-account-service", + Long.toString(upstream.issuer().generation()), + Long.toString(upstream.issuer().sourceVersion()), + upstream.issuer().checkpoint().outboxStreamKey(), + Long.toString(upstream.issuer().checkpoint().sequence()), + issuer)); + vector.add( + new SourceEvidence( + SourceKind.ACCOUNT, + actor.toString(), + Long.toString(upstream.account().generation()), + Long.toString(upstream.account().sourceVersion()), + upstream.account().checkpoint().outboxStreamKey(), + Long.toString(upstream.account().checkpoint().sequence()), + account)); + vector.add( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + actor.toString(), + Long.toString(upstream.account().generation()), + Long.toString(upstream.account().sourceVersion()), + upstream.account().checkpoint().outboxStreamKey(), + Long.toString(upstream.account().checkpoint().sequence()), + account)); + var tenantState = member.authoritySnapshot().tenants().getFirst(); + vector.add( + new SourceEvidence( + SourceKind.TENANT, + tenant.toString(), + Long.toString(tenantState.generation()), + Long.toString(tenantState.sourceVersion()), + null, + null, + canonical( + Map.of( + "creation", + member.creationSource(), + "checkpoints", + member.outboxCheckpoints(), + "events", + member.outboxSourceEvidence())))); + var membershipState = member.authoritySnapshot().memberships().getFirst(); + vector.add( + new SourceEvidence( + SourceKind.MEMBERSHIP, + actor + "/" + tenant, + Long.toString(membershipState.generation()), + Long.toString(membershipState.sourceVersion()), + null, + null, + canonical( + Map.of( + "event", + Base64.getEncoder().encodeToString(membership), + "membershipVersion", + member.membershipVersion(), + "roleSnapshotVersion", + member.roleSource().snapshotVersion(), + "roles", + member.roleSource().roles())))); + vector.sort(java.util.Comparator.comparing(SourceEvidence::key)); + byte[] evidence = + canonical( + Map.of( + "schemaVersion", + 1, + "accountId", + actor.toString(), + "tenantId", + tenant.toString(), + "sources", + vector.stream() + .map(value -> Base64.getEncoder().encodeToString(value.canonicalBytes())) + .toList())); + var checkpoints = + member.outboxCheckpoints().stream() + .map( + checkpoint -> { + Map value = new LinkedHashMap<>(); + value.put("outboxStreamKey", checkpoint.outboxStreamKey()); + value.put("outboxSequence", checkpoint.outboxSequence()); + member.outboxSourceEvidence().stream() + .filter(event -> event.outboxStreamKey().equals(checkpoint.outboxStreamKey())) + .findFirst() + .ifPresent( + event -> { + value.put("sourceEventId", event.eventId()); + value.put("sourceEventDigest", event.eventDigest()); + }); + return Map.copyOf(value); + }) + .toList(); + Map identity = + Map.of( + "sourceRowId", + upstream.account().accountSourceNumericId(), + "provenance", + upstream.account().accountUuidProvenance(), + "sourceNumericId", + upstream.account().accountSourceNumericId()); + return new Snapshot( + actor, + tenant, + Map.copyOf(authority), + numeric(member.membershipVersion()), + Long.parseLong(member.issuanceFence()), + List.copyOf(vector), + evidence, + checkpoints, + identity); + } + + private static Map numeric(Map values) { + Map result = new LinkedHashMap<>(); + values.forEach((key, value) -> result.put(key, Long.parseLong(value))); + return Map.copyOf(result); + } + + public static byte[] canonical(Object value) { + try { + String original = JSON.writeValueAsString(value); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(original); + var exactNumbers = + JsonMapper.builder() + .enable(tools.jackson.databind.DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) + .enable(tools.jackson.databind.DeserializationFeature.USE_BIG_INTEGER_FOR_INTS) + .build(); + if (!sameValues( + exactNumbers.readValue(original, Object.class), + exactNumbers.readValue(canonical, Object.class))) { + throw new IllegalArgumentException("Canonical numeric authority must remain exact"); + } + return canonical; + } catch (java.io.IOException | RuntimeException exception) { + throw new IllegalArgumentException("Canonical control-ui value required"); + } + } + + private static boolean sameValues(Object original, Object canonical) { + if (original instanceof Number left && canonical instanceof Number right) { + return new java.math.BigDecimal(left.toString()) + .compareTo(new java.math.BigDecimal(right.toString())) + == 0; + } + if (original instanceof Map left && canonical instanceof Map right) { + return left.keySet().equals(right.keySet()) + && left.entrySet().stream() + .allMatch(entry -> sameValues(entry.getValue(), right.get(entry.getKey()))); + } + if (original instanceof List left && canonical instanceof List right) { + if (left.size() != right.size()) { + return false; + } + for (int index = 0; index < left.size(); index++) { + if (!sameValues(left.get(index), right.get(index))) { + return false; + } + } + return true; + } + return java.util.Objects.equals(original, canonical); + } + + public static final class Snapshot { + private final UUID actor; + private final UUID tenant; + private final Map tuple; + private final Map membership; + private final long fence; + private final List vector; + private final byte[] evidence; + private final List> checkpoints; + private final Map identity; + + private Snapshot( + UUID actor, + UUID tenant, + Map tuple, + Map membership, + long fence, + List vector, + byte[] evidence, + List> checkpoints, + Map identity) { + this.actor = actor; + this.tenant = tenant; + this.tuple = Map.copyOf(tuple); + this.membership = Map.copyOf(membership); + this.fence = fence; + this.vector = List.copyOf(vector); + this.evidence = evidence.clone(); + this.checkpoints = List.copyOf(checkpoints); + this.identity = Map.copyOf(identity); + } + + public UUID actor() { + return actor; + } + + public UUID tenant() { + return tenant; + } + + public Map authorityTuple() { + return tuple; + } + + public Map membershipVersion() { + return membership; + } + + public long issuanceFence() { + return fence; + } + + public List sources() { + return vector; + } + + public byte[] evidence() { + return evidence.clone(); + } + + public List> outboxCheckpoints() { + return checkpoints; + } + + public Map accountIdentitySource() { + return identity; + } + + @Override + public String toString() { + return "AccountControlUiAuthority[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcService.java new file mode 100644 index 0000000000..2a30efd571 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcService.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountDraftCommitOrderReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderRequest; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderResponse; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Standalone Account gRPC endpoint; authentication precedes request decoding and owner reads. */ +public final class AccountDraftCommitOrderReadGrpcService + extends AccountDraftCommitOrderReadServiceGrpc.AccountDraftCommitOrderReadServiceImplBase { + private final AccountDraftCommitOrderReadService owner; + private final String trustedNamespace; + + public AccountDraftCommitOrderReadGrpcService( + AccountDraftCommitOrderReadService owner, String trustedNamespace) { + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readHeldOriginalCommitOrder( + ReadHeldOriginalCommitOrderRequest request, + StreamObserver observer) { + if (!requireAuthenticatedWorldPeer(observer)) return; + + final DraftCommitOrderReadEvidence.Request decoded; + try { + decoded = DraftCommitOrderReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical original Account COMMIT_ORDER read is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Account COMMIT_ORDER read namespace differs from its peer") + .asRuntimeException()); + return; + } + + final ReadHeldOriginalCommitOrderResponse response; + try { + owner.requireHeld(decoded); + response = DraftCommitOrderReadGrpcCodec.toHeldResponse(decoded); + } catch (StatusRuntimeException failure) { + observer.onError(sanitized(failure)); + return; + } catch (RuntimeException failure) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Account COMMIT_ORDER owner read is unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private boolean requireAuthenticatedWorldPeer(StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError( + Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException()); + return false; + } + String expected = "spiffe://firemud/ns/" + trustedNamespace + "/sa/world-management-service"; + if (expected.equals(peer.uri())) return true; + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World workload required") + .asRuntimeException()); + return false; + } + + private static StatusRuntimeException sanitized(StatusRuntimeException failure) { + return switch (Status.fromThrowable(failure).getCode()) { + case UNAUTHENTICATED -> + Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + case PERMISSION_DENIED -> + Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World workload required") + .asRuntimeException(); + case INVALID_ARGUMENT -> + Status.INVALID_ARGUMENT + .withDescription("Canonical COMMIT_ORDER read is required") + .asRuntimeException(); + case FAILED_PRECONDITION -> + Status.FAILED_PRECONDITION + .withDescription("Exact held original Account COMMIT_ORDER is unavailable") + .asRuntimeException(); + default -> + Status.UNAVAILABLE + .withDescription("Account COMMIT_ORDER owner read is unavailable") + .asRuntimeException(); + }; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java new file mode 100644 index 0000000000..f4d366ccd8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.dao.DataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered, read-only owner proof of the original Account COMMIT_ORDER while settlement is + * still PENDING. It neither creates authorization nor changes source/order/readback state. + */ +public final class AccountDraftCommitOrderReadService { + private final DraftAuthorizationFenceRepository repository; + private final String trustedNamespace; + private final TransactionTemplate ownerTransaction; + + public AccountDraftCommitOrderReadService( + DraftAuthorizationFenceRepository repository, + PlatformTransactionManager transactionManager, + String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Returns only after this owner transaction reads the exact retained operation, COMMIT_ORDER, and + * PENDING settlement. Absence, mismatch, reservation/revocation, or any settlement denies. + */ + public void requireHeld(DraftCommitOrderReadEvidence.Request request) { + requireAuthenticatedWorldPeer(); + Objects.requireNonNull(request, "request"); + if (!trustedNamespace.equals(request.targetNamespace())) { + throw denied("COMMIT_ORDER read namespace differs from the Account workload namespace"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Owned Account COMMIT_ORDER read transaction required") + .asRuntimeException(); + } + + DraftAuthorizationFenceBinding requested = + DraftAuthorizationFenceBinding.fromStored(request.originalAccountBinding()); + if (!Arrays.equals(request.originalAccountBinding(), requested.canonicalBytes())) { + throw invalid("Complete canonical original Account binding is required"); + } + try { + ownerTransaction.execute( + status -> { + DraftAuthorizationFenceBinding retained = + repository + .readOriginalBinding(requested.operationId()) + .orElseThrow(AccountDraftCommitOrderReadService::unheld); + if (!Arrays.equals(retained.canonicalBytes(), request.originalAccountBinding())) { + throw unheld(); + } + + var fence = repository.read(retained); + if (fence.ordering() != Ordering.COMMIT_ORDER + || !Arrays.equals(fence.binding(), request.originalAccountBinding())) { + throw unheld(); + } + Settlement settlement = repository.readSettlement(retained); + if (settlement != Settlement.PENDING) throw unheld(); + return null; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (DataAccessException | org.jooq.exception.DataAccessException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Account COMMIT_ORDER owner read is unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException inconsistent) { + // The request has already passed canonical decoding; this is corrupt or substituted storage. + throw unheld(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Account COMMIT_ORDER owner read is unavailable") + .asRuntimeException(); + } + } + + private void requireAuthenticatedWorldPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + String expected = "spiffe://firemud/ns/" + trustedNamespace + "/sa/world-management-service"; + if (!expected.equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World workload required") + .asRuntimeException(); + } + } + + private static StatusRuntimeException unheld() { + return Status.FAILED_PRECONDITION + .withDescription("Exact held original Account COMMIT_ORDER is unavailable") + .asRuntimeException(); + } + + private static StatusRuntimeException denied(String description) { + return Status.PERMISSION_DENIED.withDescription(description).asRuntimeException(); + } + + private static StatusRuntimeException invalid(String description) { + return Status.INVALID_ARGUMENT.withDescription(description).asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 18d376eecd..e3e5664dc7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -566,6 +566,32 @@ private SourceChangeAbortReason abortReason(String value) { return value == null ? null : SourceChangeAbortReason.valueOf(value); } + /** + * Rows-first creator producer acquisition: never wait on a source-first mutation while retaining + * Account/tenant/terms locks. Missing rows or contention must roll back the entire owner capture; + * neither condition is a terminal authorization outcome. V99 establishes real-source lock rows. + */ + public void lockProducerSourcesNowait(List sources) { + requireTransaction(); + if (sources == null || sources.isEmpty()) { + throw new IllegalArgumentException("Complete existing creator sources required"); + } + String previous = null; + for (SourceEvidence source : sources) { + if (previous != null && previous.compareTo(source.key()) >= 0) { + throw new IllegalArgumentException("Distinct sorted creator source vector required"); + } + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks" + + " WHERE source_key = ? FOR UPDATE NOWAIT", + source.key()) + == null) { + throw new IllegalStateException("Existing creator source lock row unavailable"); + } + previous = source.key(); + } + } + private void lockSources(List sources) { for (SourceEvidence source : sources) { dsl.execute( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java index 4f34b1140d..ed3dccfcaf 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java @@ -860,6 +860,85 @@ public Optional readCurrentCommittedSigner( ActiveJwksPromotionReceipt.fromStored(promotion))); } + /** + * Reads the original committed signer after ordinary rotation. This authenticates retained + * lifecycle provenance only; the caller must separately verify that the original public JWK is + * still accepted by the current protected JWKS source. No current-active equality is imposed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readOriginalCommittedSigner( + Binding expectedBinding, + TrustFence trust, + String currentApiBindingDigest, + String currentApiConfigRevision, + UUID promotionOperationId, + UUID generationOperationId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding); + Objects.requireNonNull(trust); + requireOperationId(promotionOperationId); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, currentApiBindingDigest, "current public API binding digest"); + requireMatch(CLUSTER_ID, currentApiConfigRevision, "current public API config revision"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) return Optional.empty(); + DesiredState current = decodeState(stateRow); + requireBinding(current, expectedBinding); + requireEnrollmentTrust(current, trust); + EnrollmentIdentity enrollment = current.enrollmentIdentity().orElseThrow(); + if (!enrollment.apiBindingDigest().equals(currentApiBindingDigest) + || !enrollment.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException("Protected Account JWKS API binding changed"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, false); + if (promotion == null) return Optional.empty(); + requireCurrentTrust(promotion, trust); + if (!"COMMITTED".equals(promotion.status()) + || !expectedBinding.equals(promotion.binding()) + || !generationOperationId.equals(promotion.generationOperationId()) + || !currentApiBindingDigest.equals(promotion.apiBindingDigest()) + || !currentApiConfigRevision.equals(promotion.apiConfigRevision())) { + throw new QuarantinedStateException("Original committed signer identity differs"); + } + StoredGenerationOperation generation = selectGenerationOperation(generationOperationId, false); + GenerationResult result = selectGenerationResult(generationOperationId, false); + if (generation == null || result == null) { + throw new QuarantinedStateException("Original committed signer generation is absent"); + } + requireCurrentTrust(generation, trust); + verifyPreparedGenerationMatches(promotion, generation, result); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException("Original committed signer resource receipts are absent"); + } + return Optional.of( + new OriginalCommittedSignerEvidence( + promotion.publicEvidence(), + result, + PrivatePromotionReceipt.fromStored(promotion), + ActiveJwksPromotionReceipt.fromStored(promotion))); + } + + /** Immutable historical owner readback, not an active-key or authenticated-actor grant. */ + public record OriginalCommittedSignerEvidence( + PromotionOperationEvidence promotion, + GenerationResult generationResult, + PrivatePromotionReceipt privateReceipt, + ActiveJwksPromotionReceipt publicReceipt) { + public OriginalCommittedSignerEvidence { + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + Objects.requireNonNull(privateReceipt); + Objects.requireNonNull(publicReceipt); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.generationOperationId().equals(generationResult.operationId()) + || !promotion.operationId().equals(privateReceipt.promotionOperationId()) + || !promotion.operationId().equals(publicReceipt.promotionOperationId())) { + throw new QuarantinedStateException("Original committed signer linkage is inconsistent"); + } + } + } + /** Persists the pinned materializer's read-only observation of the fixed pre-created Secret. */ @Transactional(propagation = Propagation.MANDATORY) public GenerationRequest recordSecretObservation( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 3f7d619493..be8abca607 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -1905,6 +1905,47 @@ private Optional findAccountForAuthentication(String usernameOrEmail) { return accountRepository.findByUsername(usernameOrEmail); } + /** + * Explicit internal control-ui owner hook. It performs real primary authentication and consumes + * the exact OTP in the caller's writable issuance transaction; it issues no token or session. The + * owner must catch primary credential denial inside that transaction so failed-attempt accounting + * commits, then report the denial outside it. Successful OTP consumption remains rollback-capable + * when later issuance preparation fails. + */ + @Transactional( + propagation = org.springframework.transaction.annotation.Propagation.MANDATORY, + noRollbackFor = AuthenticationException.class) + public ControlUiPrimaryIdentity authenticateControlUiPrimaryIdentity( + String email, String secret) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account issuance transaction required"); + } + PrimaryAuthentication result = authenticateAccountIdentity(email, secret, true); + result.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); + Account account = result.account(); + UUID accountUuid = UUID.fromString(accountMapper.toDto(account).id()); + return new ControlUiPrimaryIdentity(accountUuid); + } + + /** No external constructor: only successful Account primary authentication creates this proof. */ + public static final class ControlUiPrimaryIdentity { + private final UUID accountId; + + private ControlUiPrimaryIdentity(UUID accountId) { + this.accountId = accountId; + } + + public UUID accountId() { + return accountId; + } + + @Override + public String toString() { + return "ControlUiPrimaryIdentity[redacted]"; + } + } + private PrimaryAuthentication authenticateAccountIdentity( String username, String password, boolean allowEmailLoginOtp) { Optional accountOpt = findAccountForAuthentication(username); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java new file mode 100644 index 0000000000..ceaa10cf60 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -0,0 +1,248 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Genuine creator actor/currentness and same-transaction original Draft ordering; unregistered. */ +public final class AccountControlUiActorService { + private static final AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy POLICY = + new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy( + "account-internal-creator-draft", + "control-ui", + "control-ui", + "firemud-account-service", + "control-ui", + ControlUiJwtProfileValidator.REQUIRED_CLAIMS, + ControlUiJwtProfileValidator.OPTIONAL_CLAIMS, + 300, + 0, + 16384, + claims -> ControlUiJwtProfileValidator.validateClaims(claims, 1)); + private final AccountControlUiIssuanceRepository operations; + private final AccountControlUiAuthority authority; + private final AccountControlUiSignerOwner signers; + private final AccountControlUiCoordination registry; + private final AccountJwtJwksTrustedSource publicSource; + private final DraftAuthorizationFenceRepository fences; + private final TransactionTemplate transaction; + private final Clock clock; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Draft fence repository is an internal Account owner transaction collaborator.") + public AccountControlUiActorService( + AccountControlUiIssuanceRepository operations, + AccountControlUiAuthority authority, + AccountControlUiSignerOwner signers, + AccountControlUiCoordination registry, + AccountJwtJwksTrustedSource publicSource, + DraftAuthorizationFenceRepository fences, + PlatformTransactionManager transactions, + Clock clock) { + this.operations = Objects.requireNonNull(operations); + this.authority = Objects.requireNonNull(authority); + this.signers = Objects.requireNonNull(signers); + this.registry = Objects.requireNonNull(registry); + this.publicSource = Objects.requireNonNull(publicSource); + this.fences = Objects.requireNonNull(fences); + this.clock = Objects.requireNonNull(clock); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + public AuthenticatedActor authenticate( + String compactJwt, UUID selectedTenant, CapturedEnvironmentBoundary environment) { + return withCurrent( + compactJwt, + selectedTenant, + environment, + current -> + new AuthenticatedActor( + current.stored.accountId, + current.stored.tenantId, + current.stored.operationId, + current.stored.tokenHash)); + } + + /** No transport or World mutation: original Account reservation/order is the only effect. */ + public DraftAuthorizationFenceRepository.FenceSnapshot claimOriginalDraft( + String compactJwt, + DraftAuthorizationFenceBinding original, + CapturedEnvironmentBoundary environment) { + Objects.requireNonNull(original); + return withCurrent( + compactJwt, + original.tenantId(), + environment, + current -> { + if (!original.actorAccountId().equals(current.stored.accountId) + || !exactSources(original.sources(), current.source.sources())) { + throw denied(); + } + // Never wait for a source-first writer while retaining captured owner rows. + fences.lockProducerSourcesNowait(current.source.sources()); + fences.reserve(original); + return fences.claimCommitOrder(original); + }); + } + + private T withCurrent( + String compactJwt, + UUID selectedTenant, + CapturedEnvironmentBoundary environment, + Function action) { + outsideSql(); + var signed = verifySigned(compactJwt); + String tokenHash = + AccountControlUiIssuanceRepository.hash(compactJwt.getBytes(StandardCharsets.US_ASCII)); + byte[] exactRegistry = registry.readActive(tokenHash); + return transaction.execute( + ignored -> { + var stored = operations.findToken(tokenHash); + if (stored == null + || !selectedTenant.equals(stored.tenantId) + || !"COMMITTED".equals(stored.status) + || !Arrays.equals(stored.activeRegistry, exactRegistry) + || !Arrays.equals( + stored.claims, AccountControlUiAuthority.canonical(signed.claims.claims()))) { + throw denied(); + } + requireSignerIdentity(stored, signed); + signers.requireOriginal(stored.signerReceipt); + var current = authority.capture(stored.accountId, selectedTenant, environment); + if (!Arrays.equals(current.evidence(), stored.sources)) { + throw denied(); + } + var committed = operations.requireCommitted(stored); + if (!committed.tokenHash().equals(tokenHash)) { + throw denied(); + } + return action.apply(new Current(stored, current)); + }); + } + + /** Production asymmetric/profile verification, also used before any candidate is persisted. */ + SignedObservation verifySigned(String compactJwt) { + outsideSql(); + var pin = publicSource.sourceIdentity(); + var cache = new AccountPublicJwksCache(publicSource, pin, clock, Duration.ofSeconds(30)); + return new SignedObservation( + new AccountAsymmetricJwtVerifier(cache, clock).verify(compactJwt, POLICY), pin); + } + + void requireSignerIdentity( + AccountControlUiIssuanceRepository.Stored stored, SignedObservation observation) { + var signed = observation.claims; + var receipt = AccountControlUiIssuanceRepository.object(stored.signerReceipt); + var pin = observation.pin; + if (!signed.keyId().equals(receipt.get("kid")) + || !pin.environmentId().equals(receipt.get("environmentId")) + || !pin.clusterId().equals(receipt.get("clusterId")) + || !pin.clusterIncarnationUid().equals(receipt.get("clusterIncarnationUid")) + || !pin.namespace().equals(receipt.get("namespace")) + || !pin.namespaceUid().equals(receipt.get("namespaceUid")) + || !pin.configMapUid().equals(receipt.get("publicConfigMapUid")) + || !pin.bindingRevision().equals(receipt.get("apiConfigRevision")) + || !stored.accountId.toString().equals(signed.claims().get("sub")) + || !stored.accountId.toString().equals(signed.claims().get("accountId")) + || !stored.jti.toString().equals(signed.claims().get("jti")) + || !Map.of(stored.tenantId.toString(), List.of("tenantAdmin")) + .equals(signed.claims().get("scopedRoles")) + || signed.claims().containsKey("globalRoles")) { + throw denied(); + } + } + + private static boolean exactSources( + List first, + List second) { + if (first.size() != second.size()) { + return false; + } + for (int index = 0; index < first.size(); index++) { + if (!Arrays.equals(first.get(index).canonicalBytes(), second.get(index).canonicalBytes())) { + return false; + } + } + return true; + } + + private record Current( + AccountControlUiIssuanceRepository.Stored stored, + AccountControlUiAuthority.Snapshot source) {} + + static final class SignedObservation { + final AccountAsymmetricJwtVerifier.VerifiedClaims claims; + final AccountPublicJwksCache.SourceIdentity pin; + + private SignedObservation( + AccountAsymmetricJwtVerifier.VerifiedClaims claims, + AccountPublicJwksCache.SourceIdentity pin) { + this.claims = claims; + this.pin = pin; + } + } + + /** No externally callable constructor; workload possession or a claimed UUID cannot create it. */ + public static final class AuthenticatedActor { + private final UUID accountId, tenantId, issuanceOperationId; + private final String tokenHash; + + private AuthenticatedActor(UUID accountId, UUID tenantId, UUID operationId, String tokenHash) { + this.accountId = accountId; + this.tenantId = tenantId; + this.issuanceOperationId = operationId; + this.tokenHash = tokenHash; + } + + public UUID accountId() { + return accountId; + } + + public UUID tenantId() { + return tenantId; + } + + public UUID issuanceOperationId() { + return issuanceOperationId; + } + + public String tokenHash() { + return tokenHash; + } + + @Override + public String toString() { + return "AccountControlUiActorService.AuthenticatedActor[redacted]"; + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Signature/registry reads must precede owner SQL locks"); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Exact current authenticated initial creator required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java new file mode 100644 index 0000000000..56c4504f51 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java @@ -0,0 +1,268 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.AcknowledgementRequirements; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Actual private Coordination reader/CAS with exact catalog, ACL, physical connection and WAITAOF. + */ +public final class AccountControlUiCoordination { + private final AccountCoordinationPinnedConnectionProvider connections; + private final AcknowledgementRequirements acknowledgements; + private final RedisScriptCatalog catalog; + + public AccountControlUiCoordination( + AccountCoordinationPinnedConnectionProvider connections, + AcknowledgementRequirements acknowledgements, + RedisScriptCatalog catalog) { + this.connections = Objects.requireNonNull(connections); + this.acknowledgements = Objects.requireNonNull(acknowledgements); + this.catalog = Objects.requireNonNull(catalog); + } + + /** Read-only pinned GET and physical expiry; no repair or gameplay-profile interpretation. */ + public byte[] readActive(String tokenHash) { + outsideSql(); + return withConnection( + commands -> { + byte[] value = commands.get(key(tokenHash)); + if (value == null || value.length == 0 || value.length > 32768) { + throw denied(); + } + var record = AccountControlUiIssuanceRepository.object(value); + if (!"control-ui".equals(record.get("profile")) + || !"control-ui".equals(record.get("type")) + || !"control-ui".equals(record.get("audience")) + || !"active".equals(record.get("state")) + || !tokenHash.equals(record.get("tokenHash"))) { + throw denied(); + } + Object encodedExpiry = record.get("exp"); + if (!(encodedExpiry instanceof Number number) + || !number.toString().matches("[1-9][0-9]{0,18}")) { + throw denied(); + } + long exactExpiry = Math.multiplyExact(Long.parseLong(number.toString()), 1000L); + Long physicalExpiry = commands.pexpiretime(key(tokenHash)); + // This distinct minimum profile uses zero cleanup margin, never an inferred/renewed TTL. + if (physicalExpiry == null || physicalExpiry != exactExpiry) { + throw denied(); + } + return value.clone(); + }); + } + + /** Exact readback for the owner's protected delivery workflow. */ + public void requireExactActive(String tokenHash, byte[] exactActive, long expiryMillis) { + outsideSql(); + withConnection( + commands -> { + byte[] key = key(tokenHash); + if (!Arrays.equals(exactActive, commands.get(key))) { + throw denied(); + } + Long expiry = commands.pexpiretime(key); + if (expiry == null || expiry != expiryMillis) { + throw denied(); + } + return null; + }); + } + + /** Only package-local owner workflow may register a non-authorizing pending candidate. */ + Receipt registerPending(String tokenHash, byte[] exactPending, long expiryMillis) { + return cas(tokenHash, new byte[0], exactPending, expiryMillis); + } + + /** The private committed owner readback is mandatory; arbitrary byte callers cannot activate. */ + Receipt activate(AccountControlUiIssuanceRepository.Committed original) { + return cas( + original.tokenHash(), + original.pendingRegistry(), + original.activeRegistry(), + original.expiryMillis()); + } + + /** Durable owner intent is non-authorizing even if this external CAS cannot complete. */ + Receipt revoke(AccountControlUiIssuanceRepository.Stored original) { + outsideSql(); + byte[] replacement = AccountControlUiIssuanceRepository.revokedRegistry(original); + byte[] expected = + withConnection( + commands -> { + byte[] observed = commands.get(key(original.tokenHash)); + Long expiry = commands.pexpiretime(key(original.tokenHash)); + if (expiry == null + || expiry != original.expiryMillis() + || (!Arrays.equals(observed, original.pendingRegistry) + && !Arrays.equals(observed, original.activeRegistry) + && !Arrays.equals(observed, replacement))) { + throw denied(); + } + return observed; + }); + return cas(original.tokenHash, expected, replacement, original.expiryMillis()); + } + + private Receipt cas(String tokenHash, byte[] expected, byte[] replacement, long expiryMillis) { + outsideSql(); + if (expected == null + || replacement == null + || replacement.length == 0 + || replacement.length > 32768 + || expected.length > 32768 + || expiryMillis <= 0) { + throw denied(); + } + var descriptor = AccountControlUiRegistryContract.descriptor(); + if (!descriptor.equals(catalog.require(descriptor.scriptId()))) { + throw denied(); + } + byte[] source; + try (var stream = getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + if (stream == null) { + throw denied(); + } + source = stream.readNBytes(32769); + if (source.length == 0 + || source.length > 32768 + || !digest("SHA-256", source).equals(descriptor.sha256())) { + throw denied(); + } + } catch (java.io.IOException | RuntimeException failure) { + throw denied(); + } + return withConnection( + commands -> { + byte[] key = key(tokenHash); + String sha = commands.scriptLoad(source); + if (!digest("SHA-1", source).equals(sha)) { + throw denied(); + } + Long outcome = + commands.evalsha( + sha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + expected, + replacement, + Long.toString(expiryMillis).getBytes(StandardCharsets.US_ASCII)); + if (outcome == null || (outcome != 0L && outcome != 1L)) { + throw denied(); + } + List counts = + commands.dispatch( + WaitAof.INSTANCE, + new ArrayOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE) + .add(acknowledgements.requiredLocalAofCount()) + .add(acknowledgements.requiredReplicaAofCount()) + .add(acknowledgements.timeoutMillis())); + if (counts == null + || counts.size() != 2 + || !(counts.get(0) instanceof Long local) + || !(counts.get(1) instanceof Long replicas) + || local < acknowledgements.requiredLocalAofCount() + || replicas < acknowledgements.requiredReplicaAofCount()) { + throw denied(); + } + Long expiry = commands.pexpiretime(key); + if (!Arrays.equals(replacement, commands.get(key)) + || expiry == null + || expiry != expiryMillis) { + throw denied(); + } + return new Receipt( + tokenHash, + digest("SHA-256", replacement), + expiryMillis, + acknowledgements.requiredLocalAofCount(), + acknowledgements.requiredReplicaAofCount()); + }); + } + + private T withConnection( + java.util.function.Function, T> action) { + try (var connection = connections.openPinnedConnection()) { + if (connection == null + || !connection.isOpen() + || connection.getOptions() == null + || connection.getOptions().isAutoReconnect()) { + throw denied(); + } + var commands = connection.sync(); + if (!"account_coord_app".equals(commands.aclWhoami())) { + throw denied(); + } + return action.apply(commands); + } catch (RuntimeException failure) { + throw denied(); + } + } + + private static byte[] key(String tokenHash) { + if (tokenHash == null || !tokenHash.matches("[0-9a-f]{64}")) { + throw denied(); + } + return ("session:auth:token:" + tokenHash).getBytes(StandardCharsets.US_ASCII); + } + + static String digest(String algorithm, byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(value)); + } catch (java.security.NoSuchAlgorithmException | RuntimeException failure) { + throw denied(); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Coordination calls cannot retain owner SQL locks"); + } + } + + /** Non-authorizing receipt, constructible only after actual durable exact Redis readback. */ + static final class Receipt { + final String tokenHash; + final String recordDigest; + final long expiryMillis; + final long localAof; + final long replicas; + + private Receipt( + String tokenHash, String recordDigest, long expiryMillis, long localAof, long replicas) { + this.tokenHash = tokenHash; + this.recordDigest = recordDigest; + this.expiryMillis = expiryMillis; + this.localAof = localAof; + this.replicas = replicas; + } + } + + private enum WaitAof implements ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "WAITAOF".getBytes(StandardCharsets.US_ASCII); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Exact Account control-ui Coordination evidence unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java new file mode 100644 index 0000000000..6090b1c769 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java @@ -0,0 +1,552 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl.ControlUiPrimaryIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Genuine durable control-ui owner state. No caller-provided registry or evidence is accepted. */ +public final class AccountControlUiIssuanceRepository { + private static final String TABLE = "account_control_ui_issuance_operations"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private final DSLContext dsl; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Account transaction collaborator.") + public AccountControlUiIssuanceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + Stored findRequest(UUID requestId) { + requireTransaction(); + Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ?", requestId); + return row == null ? null : new Stored(row); + } + + Stored findToken(String tokenHash) { + requireTransaction(); + Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE token_hash = ?", tokenHash); + return row == null ? null : new Stored(row); + } + + Stored prepare( + UUID requestId, + String caller, + UUID callerContextId, + String macKeyId, + String digest, + ControlUiPrimaryIdentity authenticated, + AccountControlUiAuthority.Snapshot source, + AccountControlUiSignerOwner.Capture signer, + Instant issuedAt) { + requireTransaction(); + if (!authenticated.accountId().equals(source.actor())) { + throw denied(); + } + UUID operationId = UUID.randomUUID(); + UUID jti = UUID.randomUUID(); + Instant expiry = issuedAt.plusSeconds(300); + Instant recovery = issuedAt.plusSeconds(60); + var spec = + new AccountControlUiSigningSpec(operationId, requestId, jti, source, issuedAt, expiry); + var transaction = + dsl.fetchOne( + "SELECT pg_current_xact_id()::TEXT AS xid, nextval('account_control_ui_source_fence') AS fence"); + if (transaction == null) { + throw denied(); + } + String xid = transaction.get("xid", String.class); + Long fence = transaction.get("fence", Long.class); + if (xid == null || !xid.matches("[1-9][0-9]{0,19}") || fence == null || fence <= 0) { + throw denied(); + } + Map ref = + Map.of( + "bundleVersion", + "1", + "sourceVersion", + xid, + "sourceFence", + Long.toString(fence), + "linearization", + xid); + Map operation = + Map.of( + "operationId", + operationId.toString(), + "requestId", + requestId.toString(), + "requestDigest", + digest, + "callerWorkload", + caller, + "callerContextId", + callerContextId.toString(), + "accountId", + source.actor().toString()); + var bundle = new LinkedHashMap(); + bundle.put("schema", "account-auth-evidence-bundle/v1"); + bundle.put("bundleRef", ref); + bundle.put("snapshotIdentity", hash(source.evidence())); + bundle.put( + "evaluationIdentity", + hash( + AccountControlUiAuthority.canonical( + Map.of( + "operation", + operation, + "claims", + spec.claims(), + "bundleRef", + ref, + "snapshotIdentity", + hash(source.evidence()))))); + bundle.put("issuer", "firemud-account-service"); + bundle.put("profile", "control-ui"); + bundle.put("audience", "control-ui"); + bundle.put( + "scope", + Map.of( + "kind", + "TENANT", + "accountId", + source.actor().toString(), + "tenantIds", + java.util.List.of(source.tenant().toString()))); + bundle.put("operation", operation); + bundle.put( + "tokenIdentity", + Map.of( + "jti", + jti.toString(), + "tokenGeneration", + 1, + "iat", + issuedAt.getEpochSecond(), + "nbf", + issuedAt.getEpochSecond(), + "exp", + expiry.getEpochSecond())); + bundle.put("authorityTuple", source.authorityTuple()); + bundle.put("membershipVersion", source.membershipVersion()); + bundle.put("issuanceFence", source.issuanceFence()); + Map versions = new LinkedHashMap<>(); + source.sources().forEach(value -> versions.put(value.key(), value.sourceVersion())); + bundle.put("authoritySourceVersions", Map.copyOf(versions)); + bundle.put("accountIdentitySource", source.accountIdentitySource()); + bundle.put("outboxCheckpoints", source.outboxCheckpoints()); + bundle.put( + "roleEvidence", + Map.of( + "scopedRoles", + spec.claims().get("scopedRoles"), + "freshnessSource", + hash(source.evidence()))); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload," + + " caller_context_id, request_mac_key_id, request_digest, claims_payload, source_payload," + + " bundle_payload, signer_receipt, issued_at_epoch_second, expires_at_epoch_second," + + " recovery_expires_at, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PREPARED')" + + " ON CONFLICT (request_id) DO NOTHING", + requestId, + operationId, + jti, + source.actor(), + source.tenant(), + caller, + callerContextId, + macKeyId, + digest, + AccountControlUiAuthority.canonical(spec.claims()), + source.evidence(), + AccountControlUiAuthority.canonical(bundle), + signer.receipt(), + issuedAt.getEpochSecond(), + expiry.getEpochSecond(), + OffsetDateTime.ofInstant(recovery, java.time.ZoneOffset.UTC)); + Stored stored = findRequest(requestId); + if (inserted != 1 || stored == null || !operationId.equals(stored.operationId)) { + throw denied(); + } + // The complete fixed-width digest field permits both final registry sizes to be checked now, + // before any private signing or Coordination mutation. No placeholder is retained as evidence. + registry(stored, signer, "0".repeat(64), false); + registry(stored, signer, "0".repeat(64), true); + return stored; + } + + Stored bindCandidate( + Stored original, + String tokenHash, + byte[] envelope, + byte[] binding, + AccountControlUiSignerOwner.Capture signer) { + requireTransaction(); + Stored current = lockExact(original); + if (!Arrays.equals(current.signerReceipt, signer.receipt()) + || !"PREPARED".equals(current.status)) { + throw denied(); + } + byte[] pending = registry(current, signer, tokenHash, false); + byte[] active = registry(current, signer, tokenHash, true); + dsl.execute( + "INSERT INTO account_control_ui_response_envelopes" + + " (operation_id, encrypted_response, owner_binding, recovery_expires_at) VALUES (?, ?, ?, ?)", + current.operationId, + envelope, + binding, + OffsetDateTime.ofInstant(current.recoveryExpiry, java.time.ZoneOffset.UTC)); + if (dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'CANDIDATE', token_hash = ?, pending_registry = ?, active_registry = ?" + + " WHERE operation_id = ? AND status = 'PREPARED'", + tokenHash, + pending, + active, + current.operationId) + != 1) { + throw denied(); + } + return findRequest(current.requestId); + } + + Committed commit(Stored original, AccountControlUiCoordination.Receipt pending) { + requireTransaction(); + Stored current = lockExact(original); + if (!Objects.equals(current.tokenHash, pending.tokenHash) + || !hash(current.pendingRegistry).equals(pending.recordDigest) + || current.expiryMillis() != pending.expiryMillis + || !"CANDIDATE".equals(current.status)) { + throw denied(); + } + byte[] receipt = + AccountControlUiAuthority.canonical( + Map.of( + "schema", + "account-control-ui-pending-readback/v1", + "tokenHash", + pending.tokenHash, + "recordDigest", + pending.recordDigest, + "expiryMillis", + pending.expiryMillis, + "aclIdentity", + "account_coord_app", + "localAofCount", + pending.localAof, + "replicaAofCount", + pending.replicas)); + if (dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'COMMITTED', pending_receipt = ?, committed_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND status = 'CANDIDATE'", + receipt, + current.operationId) + != 1) { + throw denied(); + } + return requireCommitted(findRequest(current.requestId)); + } + + Committed requireCommitted(Stored original) { + Stored current = lockExact(original); + if (!"COMMITTED".equals(current.status)) { + throw denied(); + } + return new Committed(current); + } + + /** Durable non-authorizing intent precedes any external revocation; no source recapture. */ + Stored beginRecoveryFailure(Stored original) { + Stored current = lockExact(original); + if (java.util.List.of("FAILED", "REVOKING", "REVOKED").contains(current.status)) { + return current; + } + String next = current.tokenHash == null ? "FAILED" : "REVOKING"; + if (dsl.execute( + "UPDATE " + + TABLE + + " SET status = ?, recovery_failed_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND status = ?", + next, + current.operationId, + current.status) + != 1) { + throw denied(); + } + return findRequest(current.requestId); + } + + void finishRecoveryFailure(Stored original, AccountControlUiCoordination.Receipt receipt) { + Stored current = lockExact(original); + if (!"REVOKING".equals(current.status) + || !Objects.equals(current.tokenHash, receipt.tokenHash) + || !hash(revokedRegistry(current)).equals(receipt.recordDigest) + || current.expiryMillis() != receipt.expiryMillis) { + throw denied(); + } + byte[] evidence = + AccountControlUiAuthority.canonical( + Map.of( + "schema", + "account-control-ui-revoked-readback/v1", + "tokenHash", + receipt.tokenHash, + "recordDigest", + receipt.recordDigest, + "expiryMillis", + receipt.expiryMillis, + "aclIdentity", + "account_coord_app", + "localAofCount", + receipt.localAof, + "replicaAofCount", + receipt.replicas)); + if (dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'REVOKED', revocation_receipt = ?" + + " WHERE operation_id = ? AND status = 'REVOKING'", + evidence, + current.operationId) + != 1) { + throw denied(); + } + } + + static byte[] revokedRegistry(Stored original) { + if (!"REVOKING".equals(original.status)) { + throw denied(); + } + var record = new LinkedHashMap(object(original.pendingRegistry)); + record.put("state", "revoked"); + record.put("registryVersion", 3); + return AccountControlUiAuthority.canonical(record); + } + + Envelope envelope(Stored original) { + requireTransaction(); + Record value = + dsl.fetchOne( + "SELECT encrypted_response, owner_binding, recovery_expires_at" + + " FROM account_control_ui_response_envelopes WHERE operation_id = ?", + original.operationId); + if (value == null) { + return null; + } + if (!value + .get("recovery_expires_at", OffsetDateTime.class) + .toInstant() + .equals(original.recoveryExpiry)) { + return null; + } + return new Envelope( + value.get("encrypted_response", byte[].class), value.get("owner_binding", byte[].class)); + } + + private Stored lockExact(Stored original) { + requireTransaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE operation_id = ? FOR UPDATE", original.operationId); + if (row == null) { + throw denied(); + } + Stored current = new Stored(row); + if (!original.requestId.equals(current.requestId) + || !Arrays.equals(original.claims, current.claims) + || !Arrays.equals(original.sources, current.sources) + || !Arrays.equals(original.bundle, current.bundle) + || !Arrays.equals(original.signerReceipt, current.signerReceipt) + || !original.requestDigest.equals(current.requestDigest)) { + throw denied(); + } + return current; + } + + private static byte[] registry( + Stored value, AccountControlUiSignerOwner.Capture signer, String tokenHash, boolean active) { + var claims = object(value.claims); + var bundle = object(value.bundle); + var result = new LinkedHashMap(); + result.put("schemaVersion", 1); + result.put("registryVersion", active ? 2 : 1); + result.put("tokenHash", tokenHash); + result.put("kid", signer.kid()); + result.put("signerGeneration", signer.generation()); + result.put("issuer", "firemud-account-service"); + result.put("profile", "control-ui"); + result.put("type", "control-ui"); + result.put("audience", "control-ui"); + for (String field : + java.util.List.of( + "accountId", + "jti", + "iat", + "nbf", + "exp", + "tokenGeneration", + "authorityTuple", + "membershipVersion", + "issuanceFence")) { + result.put(field, claims.get(field)); + } + result.put("operationId", value.operationId.toString()); + result.put("requestId", value.requestId.toString()); + result.put("requestDigest", value.requestDigest); + result.put("state", active ? "active" : "pending"); + result.put("authoritySourceVersions", bundle.get("authoritySourceVersions")); + var reference = new LinkedHashMap(); + @SuppressWarnings("unchecked") + var bundleRef = (Map) bundle.get("bundleRef"); + reference.putAll(bundleRef); + reference.put("canonicalSha256", hash(value.bundle)); + result.put("authEvidenceBundle", Map.copyOf(reference)); + result.put("originalSignerReceiptDigest", hash(value.signerReceipt)); + byte[] bytes = AccountControlUiAuthority.canonical(result); + if (bytes.length > 32768) { + throw denied(); + } + return bytes; + } + + static Map object(byte[] bytes) { + try { + return JSON.readValue(new String(bytes, StandardCharsets.UTF_8), new TypeReference<>() {}); + } catch (RuntimeException failure) { + throw denied(); + } + } + + static String hash(byte[] bytes) { + return AccountControlUiCoordination.digest("SHA-256", bytes); + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw denied(); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw denied(); + } + }); + } + + static final class Stored { + final UUID requestId, operationId, jti, accountId, tenantId, callerContextId; + final String caller, requestMacKeyId, requestDigest, status, tokenHash; + final byte[] claims, sources, bundle, signerReceipt, pendingRegistry, activeRegistry; + final Instant issuedAt, expiresAt, recoveryExpiry; + + Stored(Record row) { + requestId = row.get("request_id", UUID.class); + operationId = row.get("operation_id", UUID.class); + jti = row.get("token_jti", UUID.class); + accountId = row.get("account_uuid", UUID.class); + tenantId = row.get("tenant_uuid", UUID.class); + callerContextId = row.get("caller_context_id", UUID.class); + caller = row.get("caller_workload", String.class); + requestMacKeyId = row.get("request_mac_key_id", String.class); + requestDigest = row.get("request_digest", String.class); + status = row.get("status", String.class); + tokenHash = row.get("token_hash", String.class); + claims = row.get("claims_payload", byte[].class); + sources = row.get("source_payload", byte[].class); + bundle = row.get("bundle_payload", byte[].class); + signerReceipt = row.get("signer_receipt", byte[].class); + pendingRegistry = row.get("pending_registry", byte[].class); + activeRegistry = row.get("active_registry", byte[].class); + issuedAt = Instant.ofEpochSecond(row.get("issued_at_epoch_second", Long.class)); + expiresAt = Instant.ofEpochSecond(row.get("expires_at_epoch_second", Long.class)); + recoveryExpiry = row.get("recovery_expires_at", OffsetDateTime.class).toInstant(); + } + + long expiryMillis() { + return expiresAt.toEpochMilli(); + } + + @Override + public String toString() { + return "AccountControlUiIssuanceRepository.Stored[redacted]"; + } + } + + public static final class Committed { + final Stored stored; + + private Committed(Stored stored) { + this.stored = stored; + } + + public String tokenHash() { + return stored.tokenHash; + } + + public byte[] pendingRegistry() { + return stored.pendingRegistry.clone(); + } + + public byte[] activeRegistry() { + return stored.activeRegistry.clone(); + } + + public long expiryMillis() { + return stored.expiryMillis(); + } + + @Override + public String toString() { + return "AccountControlUiIssuanceRepository.Committed[redacted]"; + } + } + + record Envelope(byte[] encrypted, byte[] binding) { + Envelope { + encrypted = encrypted.clone(); + binding = binding.clone(); + } + + @Override + public byte[] encrypted() { + return encrypted.clone(); + } + + @Override + public byte[] binding() { + return binding.clone(); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Exact Account control-ui issuance owner evidence required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java new file mode 100644 index 0000000000..7541f70084 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java @@ -0,0 +1,422 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.EmailCanonicalization; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Minimum genuine backend creator issuance/recovery, deliberately unregistered and unmounted. + * Primary credentials, existing owner sources and actual Coordination are all required. An + * independently protected exact peer binding supplies transport identity, never creator authority. + */ +public final class AccountControlUiIssuanceService { + private final AccountServiceImpl primaryAuthentication; + private final AccountControlUiIssuanceRepository operations; + private final AccountControlUiAuthority authority; + private final DraftAuthorizationFenceRepository fences; + private final AccountControlUiSignerOwner signers; + private final AccountControlUiResponseCryptography cryptography; + private final AccountControlUiCoordination registry; + private final AccountControlUiActorService actors; + private final TransactionTemplate transaction; + private final Clock clock; + private final String protectedCallerUri; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected primary authentication and Draft fence services remain internal Account owner collaborators.") + public AccountControlUiIssuanceService( + AccountServiceImpl primaryAuthentication, + AccountControlUiIssuanceRepository operations, + AccountControlUiAuthority authority, + DraftAuthorizationFenceRepository fences, + AccountControlUiSignerOwner signers, + AccountControlUiResponseCryptography cryptography, + AccountControlUiCoordination registry, + AccountControlUiActorService actors, + PlatformTransactionManager transactions, + Clock clock, + String independentlyProtectedCallerUri) { + this.primaryAuthentication = Objects.requireNonNull(primaryAuthentication); + this.operations = Objects.requireNonNull(operations); + this.authority = Objects.requireNonNull(authority); + this.fences = Objects.requireNonNull(fences); + this.signers = Objects.requireNonNull(signers); + this.cryptography = Objects.requireNonNull(cryptography); + this.registry = Objects.requireNonNull(registry); + this.actors = Objects.requireNonNull(actors); + this.clock = Objects.requireNonNull(clock); + protectedCallerUri = + GrpcPeerIdentity.parseUri(independentlyProtectedCallerUri) + .orElseThrow( + () -> new IllegalArgumentException("One protected exact issuer peer URI required")) + .uri(); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + public IssuedCredential issue(Request request, CapturedEnvironmentBoundary environment) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Control-ui workflow cannot inherit owner SQL locks"); + } + Objects.requireNonNull(request); + Objects.requireNonNull(environment); + var peer = GrpcPeerIdentity.current(); + if (peer == null || !protectedCallerUri.equals(peer.uri())) { + throw denied(); + } + String email = EmailCanonicalization.normalize(request.email); + byte[] exactRequest = + AccountControlUiAuthority.canonical( + Map.of( + "schema", + "account-control-ui-request/v1", + "requestId", + request.requestId.toString(), + "email", + email, + "secret", + request.secret, + "canonicalTenantId", + request.tenantId.toString(), + "callerWorkload", + peer.uri(), + "callerContextId", + request.callerContextId.toString())); + try { + InitialPreparation initial = + transaction.execute( + ignored -> { + var existing = operations.findRequest(request.requestId); + if (existing != null) { + requireRequest(existing, request, peer.uri(), exactRequest); + return new InitialPreparation(current(existing, environment), null); + } + // Preserve canonical tenant -> Account owner order before OTP/advisory + // authentication. + var source = authority.captureInitial(request.tenantId, environment); + fences.lockProducerSourcesNowait(source.sources()); + AccountServiceImpl.ControlUiPrimaryIdentity authenticated; + try { + authenticated = + primaryAuthentication.authenticateControlUiPrimaryIdentity( + email, request.secret); + } catch (AuthenticationException denial) { + // Only primary denial commits attempt accounting. No signer/issuance work + // follows. + return new InitialPreparation( + null, new PrimaryDenial(denial.getCode(), denial.getMessage())); + } + if (!source.actor().equals(authenticated.accountId())) { + throw denied(); + } + var signer = signers.captureCurrent(); + String macKey = cryptography.currentKeyId(); + String requestDigest = cryptography.requestDigest(macKey, exactRequest); + var stored = + operations.prepare( + request.requestId, + peer.uri(), + request.callerContextId, + macKey, + requestDigest, + authenticated, + source, + signer, + Instant.ofEpochSecond(clock.instant().getEpochSecond())); + return new InitialPreparation(new Prepared(stored, source, signer), null); + }); + if (initial == null) { + throw denied(); + } + if (initial.denial != null) { + throw new AuthenticationException(initial.denial.code, initial.denial.message); + } + Prepared preparation = Objects.requireNonNull(initial.prepared); + var original = preparation.stored; + if ("PREPARED".equals(original.status)) { + var spec = + new AccountControlUiSigningSpec( + original.operationId, + original.requestId, + original.jti, + preparation.source, + original.issuedAt, + original.expiresAt); + if (!Arrays.equals(original.claims, AccountControlUiAuthority.canonical(spec.claims()))) { + throw denied(); + } + signers.sign( + preparation.signer, + spec, + (tokenHash, credential) -> { + String compact = new String(credential, StandardCharsets.US_ASCII); + var signed = actors.verifySigned(compact); + actors.requireSignerIdentity(original, signed); + if (!Arrays.equals( + original.claims, AccountControlUiAuthority.canonical(signed.claims.claims()))) { + throw denied(); + } + byte[] binding = envelopeBinding(original, tokenHash); + byte[] encrypted = cryptography.seal(credential, binding, original.recoveryExpiry); + transaction.execute( + ignored -> { + var stillCurrent = current(original, environment); + operations.bindCandidate( + stillCurrent.stored, tokenHash, encrypted, binding, stillCurrent.signer); + return null; + }); + }); + } + var candidate = transaction.execute(ignored -> current(original, environment).stored); + if (candidate == null) { + throw denied(); + } + AccountControlUiIssuanceRepository.Committed committed; + if ("CANDIDATE".equals(candidate.status)) { + var pending = + registry.registerPending( + candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis()); + committed = + transaction.execute( + ignored -> { + var observed = current(candidate, environment); + return operations.commit(observed.stored, pending); + }); + } else if ("COMMITTED".equals(candidate.status)) { + committed = + transaction.execute( + ignored -> { + current(candidate, environment); + return operations.requireCommitted(candidate); + }); + } else { + throw denied(); + } + if (committed == null) { + throw denied(); + } + registry.activate(committed); + var envelope = + transaction.execute( + ignored -> { + current(committed.stored, environment); + return operations.envelope(committed.stored); + }); + if (envelope == null + || !Arrays.equals( + envelope.binding(), envelopeBinding(committed.stored, committed.tokenHash()))) { + throw new RecoveryLost(committed.stored); + } + byte[] credential; + try { + credential = + cryptography.open( + envelope.encrypted(), envelope.binding(), committed.stored.recoveryExpiry); + } catch (AccountResponseEnvelopeCryptography.IntegrityException + | AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException permanent) { + throw new RecoveryLost(committed.stored); + } + try { + if (!committed.tokenHash().equals(AccountControlUiIssuanceRepository.hash(credential))) { + throw new RecoveryLost(committed.stored); + } + var actor = + actors.authenticate( + new String(credential, StandardCharsets.US_ASCII), request.tenantId, environment); + if (!actor.accountId().equals(committed.stored.accountId) + || !actor.issuanceOperationId().equals(committed.stored.operationId)) { + throw denied(); + } + return new IssuedCredential( + credential, committed.stored.expiresAt, committed.stored.recoveryExpiry); + } finally { + Arrays.fill(credential, (byte) 0); + } + } catch (RecoveryLost permanent) { + // Caller conflicts and unavailable SQL/custody/Coordination never enter this path. + // Persist denial first; ambiguous/missing Redis evidence leaves REVOKING, never success. + var failed = + transaction.execute(ignored -> operations.beginRecoveryFailure(permanent.original)); + if (failed != null && "REVOKING".equals(failed.status)) { + var receipt = registry.revoke(failed); + transaction.execute( + ignored -> { + operations.finishRecoveryFailure(failed, receipt); + return null; + }); + } + throw denied(); + } finally { + Arrays.fill(exactRequest, (byte) 0); + } + } + + private void requireRequest( + AccountControlUiIssuanceRepository.Stored stored, + Request request, + String caller, + byte[] exactRequest) { + if (!stored.requestId.equals(request.requestId) + || !stored.tenantId.equals(request.tenantId) + || !stored.caller.equals(caller) + || !stored.callerContextId.equals(request.callerContextId) + || !stored.requestDigest.equals( + cryptography.requestDigest(stored.requestMacKeyId, exactRequest))) { + throw new IllegalArgumentException("Control-ui issuance idempotency conflict"); + } + } + + private Prepared current( + AccountControlUiIssuanceRepository.Stored original, CapturedEnvironmentBoundary environment) { + if (!clock.instant().isBefore(original.recoveryExpiry) + || java.util.List.of("FAILED", "REVOKING", "REVOKED").contains(original.status)) { + throw new RecoveryLost(original); + } + var source = authority.capture(original.accountId, original.tenantId, environment); + fences.lockProducerSourcesNowait(source.sources()); + if (!Arrays.equals(source.evidence(), original.sources)) { + throw denied(); + } + var signer = signers.requireOriginal(original.signerReceipt); + var stored = operations.findRequest(original.requestId); + if (stored == null + || !stored.operationId.equals(original.operationId) + || !Arrays.equals(stored.sources, original.sources) + || !Arrays.equals(stored.claims, original.claims) + || !Arrays.equals(stored.signerReceipt, original.signerReceipt)) { + throw denied(); + } + return new Prepared(stored, source, signer); + } + + private static byte[] envelopeBinding( + AccountControlUiIssuanceRepository.Stored original, String tokenHash) { + return AccountControlUiAuthority.canonical( + Map.ofEntries( + Map.entry("purpose", "account-control-ui-original-credential/v1"), + Map.entry("operationId", original.operationId.toString()), + Map.entry("requestId", original.requestId.toString()), + Map.entry("accountId", original.accountId.toString()), + Map.entry("tenantId", original.tenantId.toString()), + Map.entry("callerWorkload", original.caller), + Map.entry("callerContextId", original.callerContextId.toString()), + Map.entry("requestMacKeyId", original.requestMacKeyId), + Map.entry("requestDigest", original.requestDigest), + Map.entry("tokenHash", tokenHash), + Map.entry("claimsDigest", AccountControlUiIssuanceRepository.hash(original.claims)), + Map.entry("bundleDigest", AccountControlUiIssuanceRepository.hash(original.bundle)), + Map.entry( + "signerReceiptDigest", + AccountControlUiIssuanceRepository.hash(original.signerReceipt)), + Map.entry("recoveryExpiresAt", original.recoveryExpiry.toString()))); + } + + private record PrimaryDenial(String code, String message) { + private PrimaryDenial { + Objects.requireNonNull(code); + Objects.requireNonNull(message); + } + } + + private record InitialPreparation(Prepared prepared, PrimaryDenial denial) { + private InitialPreparation { + if ((prepared == null) == (denial == null)) { + throw new IllegalArgumentException( + "Exactly one initial creator preparation outcome required"); + } + } + } + + private record Prepared( + AccountControlUiIssuanceRepository.Stored stored, + AccountControlUiAuthority.Snapshot source, + AccountControlUiSignerOwner.Capture signer) {} + + /** + * Only permanent loss established against the original owner record, never dependency failure. + */ + private static final class RecoveryLost extends RuntimeException { + private final AccountControlUiIssuanceRepository.Stored original; + + private RecoveryLost(AccountControlUiIssuanceRepository.Stored original) { + super("Original protected control-ui recovery permanently unavailable"); + this.original = original; + } + } + + public record Request( + UUID requestId, String email, String secret, UUID tenantId, UUID callerContextId) { + public Request { + if (requestId == null + || email == null + || email.isBlank() + || email.length() > 254 + || secret == null + || secret.isEmpty() + || secret.length() > 1024 + || tenantId == null + || callerContextId == null) { + throw new IllegalArgumentException("Exact bounded issuer request required"); + } + } + + @Override + public String toString() { + return "AccountControlUiIssuanceService.Request[redacted]"; + } + } + + public static final class IssuedCredential implements AutoCloseable { + private final byte[] bytes; + private final Instant expiresAt, recoveryExpiresAt; + + private IssuedCredential(byte[] bytes, Instant expiresAt, Instant recoveryExpiresAt) { + this.bytes = bytes.clone(); + this.expiresAt = expiresAt; + this.recoveryExpiresAt = recoveryExpiresAt; + } + + public byte[] compactBytes() { + return bytes.clone(); + } + + public Instant expiresAt() { + return expiresAt; + } + + public Instant recoveryExpiresAt() { + return recoveryExpiresAt; + } + + @Override + public void close() { + Arrays.fill(bytes, (byte) 0); + } + + @Override + public String toString() { + return "AccountControlUiIssuanceService.IssuedCredential[redacted]"; + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Control-ui original issuance/current recovery unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiKeyring.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiKeyring.java new file mode 100644 index 0000000000..5c8f6d5621 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiKeyring.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.file.Path; +import java.time.Instant; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +/** + * Separate unpublished control-ui custody using the existing bounded mounted-ring parser. + * encryption/ and request-mac/ each contain an independent existing-format keyring. Neither + * defaults to or reads the gameplay response-envelope mount. + */ +public final class AccountControlUiKeyring { + private final AccountResponseEnvelopeKeyring encryption; + private final AccountResponseEnvelopeKeyring requestMac; + + public AccountControlUiKeyring(Path dedicatedRoot) { + if (dedicatedRoot == null || !dedicatedRoot.isAbsolute()) { + throw new IllegalArgumentException("Separate absolute control-ui custody root required"); + } + encryption = new AccountResponseEnvelopeKeyring(dedicatedRoot.resolve("encryption").toString()); + requestMac = + new AccountResponseEnvelopeKeyring(dedicatedRoot.resolve("request-mac").toString()); + } + + AccountResponseEnvelopeKeyring encryption() { + return encryption; + } + + String requestKeyId() { + return requestMac.readCurrent().activeKeyId(); + } + + SecretKey requestKey(String id, Instant now) { + byte[] bytes = requestMac.readCurrent().decryptionKey(id, now).secretKey().getEncoded(); + byte[] encryptionBytes = encryption.readCurrent().activeKey().secretKey().getEncoded(); + try { + if (java.util.Arrays.equals(bytes, encryptionBytes)) { + throw new IllegalStateException("Control-ui encryption and request-MAC keys must differ"); + } + return new SecretKeySpec(bytes, "HmacSHA256"); + } finally { + java.util.Arrays.fill(bytes, (byte) 0); + java.util.Arrays.fill(encryptionBytes, (byte) 0); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryContract.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryContract.java new file mode 100644 index 0000000000..470a592ebc --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryContract.java @@ -0,0 +1,45 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.*; + +/** Distinct owner descriptor; runtime catalog registration and ACL provisioning remain closed. */ +public final class AccountControlUiRegistryContract { + public static final String SCRIPT_ID = "account-control-ui-registry-cas.v1"; + public static final String RESOURCE = "redis/lua/account-control-ui-registry-cas.lua"; + + private AccountControlUiRegistryContract() {} + + public static RedisScriptDescriptor descriptor() { + return new RedisScriptDescriptor( + SCRIPT_ID, + RESOURCE, + "b2576b34ffba9c6ecc8ce8a7f7fd4372c655da5937b87a0fcefe62cf34b612e6", + "account-service", + "account_coord_app", + RedisRole.COORDINATION, + List.of(new KeySpec("tokenRecord", "session:auth:token:", HashTagDeclaration.NOT_REQUIRED)), + List.of( + new ArgumentSpec("expectedOriginalRecord"), + new ArgumentSpec("exactReplacementRecord"), + new ArgumentSpec("absoluteExpiryEpochMillis")), + ScriptCategory.SESSION_CAS, + List.of( + new OutcomeSpec("APPLIED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING), + new OutcomeSpec("EXACT_REASSERTED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING), + new OutcomeSpec( + "INVALID_ARGUMENTS", + OutcomeCategory.VALIDATION_FAILURE, + MutationEffect.NON_MUTATING), + new OutcomeSpec("EXPIRED", OutcomeCategory.STALE, MutationEffect.NON_MUTATING), + new OutcomeSpec("EXPIRY_MISMATCH", OutcomeCategory.STALE, MutationEffect.NON_MUTATING), + new OutcomeSpec("CONFLICT", OutcomeCategory.STALE, MutationEffect.NON_MUTATING)), + ResetSensitivity.CLUSTER, + LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, + "Missing or changed control-ui record denies; only original durable Account issuance may reconcile.", + CompatibilityLevel.REQUIRES_CLUSTER_RESET, + List.of(new SupportedCoexistence("v1", "v1")), + null); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptography.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptography.java new file mode 100644 index 0000000000..a3de42db00 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptography.java @@ -0,0 +1,76 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import javax.crypto.Mac; + +/** Distinct control-ui custody and purpose over the existing tested envelope primitive. */ +public final class AccountControlUiResponseCryptography { + private final AccountControlUiKeyring keys; + private final AccountResponseEnvelopeCryptography envelopes; + private final Clock clock; + + public AccountControlUiResponseCryptography(AccountControlUiKeyring keys, Clock clock) { + this.keys = Objects.requireNonNull(keys); + this.clock = Objects.requireNonNull(clock); + envelopes = + new AccountResponseEnvelopeCryptography( + keys.encryption(), clock, new java.security.SecureRandom()); + } + + String currentKeyId() { + return keys.requestKeyId(); + } + + String requestDigest(String keyId, byte[] exactRequest) { + if (exactRequest == null || exactRequest.length == 0 || exactRequest.length > 16384) { + throw new IllegalArgumentException("Bounded control-ui credential request required"); + } + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(keys.requestKey(keyId, clock.instant())); + mac.update("firemud/control-ui/credential-request/v1\0".getBytes(StandardCharsets.US_ASCII)); + return HexFormat.of().formatHex(mac.doFinal(exactRequest)); + } catch (java.security.GeneralSecurityException | RuntimeException exception) { + throw new IllegalStateException("Control-ui request MAC unavailable"); + } + } + + byte[] seal(byte[] credential, byte[] binding, Instant recoveryExpiry) { + return envelopes.encrypt(binding(binding), credential, recoveryExpiry).bytes(); + } + + byte[] open(byte[] envelope, byte[] binding, Instant recoveryExpiry) { + return envelopes.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope(envelope), + binding(binding), + recoveryExpiry); + } + + private static AccountResponseEnvelopeCryptography.Binding binding(byte[] exactOwnerBinding) { + try { + byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(exactOwnerBinding); + String identity = HexFormat.of().formatHex(digest); + // Labels identify cryptographic purpose, not a workload or authenticated actor. + return new AccountResponseEnvelopeCryptography.Binding( + "control-ui-issuance/v1", + identity, + digest, + "account-control-ui-custody", + identity, + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1, + "{}".getBytes(StandardCharsets.US_ASCII), + "{}".getBytes(StandardCharsets.US_ASCII), + exactOwnerBinding); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java new file mode 100644 index 0000000000..c982a8210a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java @@ -0,0 +1,201 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.Objects; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; + +/** Unregistered genuine committed-signer owner, separate from non-authorizing readiness probes. */ +public final class AccountControlUiSignerOwner { + private final AccountJwtSignerDesiredStateRepository repository; + private final AccountJwtSignerMaterializerTrustBinding trust; + private final AccountJwtJwksApiBinding api; + private final Path privateRoot; + private final Path publicRoot; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected signer repository is an internal Account owner transaction collaborator.") + public AccountControlUiSignerOwner( + AccountJwtSignerDesiredStateRepository repository, + AccountJwtSignerMaterializerTrustBinding trust, + AccountJwtJwksApiBinding api, + Path privateRoot, + Path publicRoot) { + this.repository = Objects.requireNonNull(repository); + this.trust = Objects.requireNonNull(trust); + this.api = Objects.requireNonNull(api); + this.privateRoot = Objects.requireNonNull(privateRoot); + this.publicRoot = Objects.requireNonNull(publicRoot); + if (!privateRoot.isAbsolute() || !publicRoot.isAbsolute()) { + throw new IllegalArgumentException("Protected Account signer roots required"); + } + } + + /** Reads existing real lifecycle receipts under their existing Account owner transaction. */ + public Capture captureCurrent() { + return capture(null); + } + + /** Original retained owner receipt, independently re-read rather than treated as caller proof. */ + public Capture requireOriginal(byte[] originalReceipt) { + var observed = capture(Objects.requireNonNull(originalReceipt)); + if (!java.util.Arrays.equals(originalReceipt, observed.receipt())) { + throw unavailable(); + } + return observed; + } + + private Capture capture(byte[] originalReceipt) { + var materializer = trust.current().orElseThrow(AccountControlUiSignerOwner::unavailable); + var publicApi = api.current(); + if (!materializer.environmentId().equals(publicApi.environmentId()) + || !materializer.clusterId().equals(publicApi.clusterId()) + || !materializer.namespace().equals(publicApi.namespace()) + || !materializer + .expectedClusterIncarnationUid() + .equals(publicApi.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(publicApi.expectedNamespaceUid())) { + throw unavailable(); + } + var binding = + new AccountJwtSignerDesiredStateRepository.Binding( + materializer.environmentId(), + materializer.clusterId(), + materializer.namespace(), + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + var fence = + new TrustFence( + materializer.expectedClusterIncarnationUid(), + materializer.expectedNamespaceUid(), + materializer.bindingDigest(), + materializer.configRevision()); + AccountJwtSignerDesiredStateRepository.GenerationResult generation; + AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence promotion; + AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt privateReceipt; + AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt publicReceipt; + if (originalReceipt == null) { + var evidence = + repository + .readCurrentCommittedSigner( + binding, fence, publicApi.bindingDigest(), publicApi.configRevision()) + .orElseThrow(AccountControlUiSignerOwner::unavailable); + generation = evidence.generationResult(); + promotion = evidence.promotion(); + privateReceipt = evidence.privateReceipt(); + publicReceipt = evidence.publicReceipt(); + } else { + var original = AccountControlUiIssuanceRepository.object(originalReceipt); + var evidence = + repository + .readOriginalCommittedSigner( + binding, + fence, + publicApi.bindingDigest(), + publicApi.configRevision(), + java.util.UUID.fromString((String) original.get("promotionOperationId")), + java.util.UUID.fromString((String) original.get("generationOperationId"))) + .orElseThrow(AccountControlUiSignerOwner::unavailable); + generation = evidence.generationResult(); + promotion = evidence.promotion(); + privateReceipt = evidence.privateReceipt(); + publicReceipt = evidence.publicReceipt(); + } + if (!binding.equals(promotion.binding()) + || !binding.equals(generation.binding()) + || !fence.equals(promotion.trustFence()) + || !fence.equals(generation.trustFence()) + || !promotion.targetGeneration().equals(generation.targetGeneration()) + || !promotion.targetKid().equals(generation.targetKid()) + || !"RS256".equals(promotion.targetAlgorithm()) + || !"RS256".equals(generation.targetAlgorithm()) + || !promotion.targetPublicKeyFingerprint().equals(generation.publicKeyFingerprint())) { + throw unavailable(); + } + var expected = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + generation.operationId().toString(), + generation.targetGeneration(), + generation.targetKid(), + generation.publicKeyFingerprint()); + var receipt = new LinkedHashMap(); + receipt.put("schema", "account-control-ui-committed-signer/v1"); + receipt.put("environmentId", binding.environmentId()); + receipt.put("clusterId", binding.clusterId()); + receipt.put("namespace", binding.namespace()); + receipt.put("clusterIncarnationUid", materializer.expectedClusterIncarnationUid()); + receipt.put("namespaceUid", materializer.expectedNamespaceUid()); + receipt.put("trustBindingDigest", materializer.bindingDigest()); + receipt.put("trustConfigRevision", materializer.configRevision()); + receipt.put("apiBindingDigest", publicApi.bindingDigest()); + receipt.put("apiConfigRevision", publicApi.configRevision()); + receipt.put("promotionOperationId", promotion.operationId().toString()); + receipt.put("promotionRequestDigest", promotion.requestDigest()); + receipt.put("generationOperationId", generation.operationId().toString()); + receipt.put("signerGeneration", generation.targetGeneration()); + receipt.put("kid", generation.targetKid()); + receipt.put("algorithm", generation.targetAlgorithm()); + receipt.put("publicKeyFingerprint", generation.publicKeyFingerprint()); + receipt.put("privateReceiptDigest", privateReceipt.receiptDigest()); + receipt.put("privateResourceVersion", privateReceipt.observedResourceVersion()); + receipt.put("publicReceiptDigest", publicReceipt.receiptDigest()); + receipt.put("publicResourceVersion", publicReceipt.observedResourceVersion()); + receipt.put("publicConfigMapUid", publicReceipt.configMapUid()); + receipt.put("publicDataDigest", publicReceipt.publicDataDigest()); + return new Capture(expected, AccountControlUiAuthority.canonical(receipt)); + } + + String sign( + Capture original, + AccountControlUiSigningSpec spec, + java.util.function.BiConsumer candidateConsumer) { + return AccountMountedJwtSignerBundle.signCommittedControlUiDigest( + privateRoot, + Path.of("current.key"), + publicRoot, + Path.of("jwks.json"), + original.expected, + spec, + candidateConsumer); + } + + public static final class Capture { + private final AccountMountedJwtSignerBundle.ExpectedIdentity expected; + private final byte[] receipt; + + private Capture(AccountMountedJwtSignerBundle.ExpectedIdentity expected, byte[] receipt) { + this.expected = expected; + this.receipt = receipt.clone(); + } + + public byte[] receipt() { + return receipt.clone(); + } + + public String kid() { + return expected.kid(); + } + + public String generation() { + return expected.generation(); + } + + @Override + public String toString() { + return "AccountControlUiSignerOwner.Capture[redacted]"; + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Existing committed control-ui signer unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningSpec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningSpec.java new file mode 100644 index 0000000000..c2c7cb5777 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningSpec.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Instant; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; + +/** One canonical initial creator's immutable signing input, never an authentication result. */ +final class AccountControlUiSigningSpec { + private final UUID operationId; + private final UUID requestId; + private final UUID jti; + private final Map claims; + + AccountControlUiSigningSpec( + UUID operationId, + UUID requestId, + UUID jti, + AccountControlUiAuthority.Snapshot source, + Instant issuedAt, + Instant expiresAt) { + if (operationId == null + || requestId == null + || jti == null + || source == null + || issuedAt == null + || expiresAt == null + || issuedAt.getNano() != 0 + || expiresAt.getNano() != 0 + || !expiresAt.isAfter(issuedAt) + || expiresAt.isAfter(issuedAt.plusSeconds(300))) { + throw new IllegalArgumentException("Exact bounded control-ui signing input required"); + } + this.operationId = operationId; + this.requestId = requestId; + this.jti = jti; + var values = new java.util.LinkedHashMap(); + values.put("iss", "firemud-account-service"); + values.put("aud", ControlUiJwtProfileValidator.AUDIENCE); + values.put("sub", source.actor().toString()); + values.put("accountId", source.actor().toString()); + values.put("jti", jti.toString()); + values.put("iat", issuedAt.getEpochSecond()); + values.put("nbf", issuedAt.getEpochSecond()); + values.put("exp", expiresAt.getEpochSecond()); + values.put("tokenGeneration", 1L); + values.put("authorityTuple", source.authorityTuple()); + values.put("membershipVersion", source.membershipVersion()); + values.put("issuanceFence", source.issuanceFence()); + values.put("scopedRoles", Map.of(source.tenant().toString(), java.util.List.of("tenantAdmin"))); + ControlUiJwtProfileValidator.validateClaims(values, 1); + if (AccountControlUiAuthority.canonical(values).length > 12288) { + throw new IllegalArgumentException("Control-ui claim encoding exceeds its finite ceiling"); + } + this.claims = Map.copyOf(values); + } + + UUID operationId() { + return operationId; + } + + UUID requestId() { + return requestId; + } + + UUID jti() { + return jti; + } + + Map claims() { + return claims; + } + + @Override + public String toString() { + return "AccountControlUiSigningSpec[redacted]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java index 2e1929da82..63a4980e0d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java @@ -341,6 +341,87 @@ static SignedDelegationDigest signCommittedGameplayDelegationDigest( } } + /** + * Distinct control-ui entry, available only to the Account owner. The owner must have retained + * genuine primary authentication and exact committed signer evidence before calling outside SQL + * locks. Mounted correspondence alone supplies neither authority nor permission to deliver. + */ + static String signCommittedControlUiDigest( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity, + AccountControlUiSigningSpec spec, + java.util.function.BiConsumer exactCandidateConsumer) { + Objects.requireNonNull(spec); + Objects.requireNonNull(exactCandidateConsumer); + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) { + throw new IllegalStateException("Control-ui signing must occur outside owner SQL locks"); + } + VerifiedMountedSigner mounted = + readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); + byte[] header = null; + byte[] claims = null; + byte[] input = null; + byte[] signature = null; + byte[] compact = null; + byte[] callback = null; + try { + ControlUiJwtProfileValidator.validateClaims(spec.claims(), 1); + header = + canonicalJsonBytes(Map.of("alg", ALGORITHM, "kid", expectedIdentity.kid(), "typ", "JWT")); + claims = canonicalJsonBytes(spec.claims()); + input = + joinCompactParts( + Base64.getUrlEncoder().withoutPadding().encode(header), + Base64.getUrlEncoder().withoutPadding().encode(claims), + null); + int signatureLength = (mounted.publicKey().getModulus().bitLength() + 7) / 8; + int encodedSignatureLength = (signatureLength * 8 + 5) / 6; + if (input.length + 1 + encodedSignatureLength > MAX_READINESS_COMPACT_JWT_BYTES) { + throw invalid(); + } + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(mounted.privateKey()); + signer.update(input); + signature = signer.sign(); + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(mounted.publicKey()); + verifier.update(input); + if (!verifier.verify(signature)) { + throw invalid(); + } + compact = + joinCompactParts( + Base64.getUrlEncoder().withoutPadding().encode(header), + Base64.getUrlEncoder().withoutPadding().encode(claims), + Base64.getUrlEncoder().withoutPadding().encode(signature)); + if (compact.length > MAX_READINESS_COMPACT_JWT_BYTES) { + throw invalid(); + } + String digest = sha256(compact); + callback = compact.clone(); + exactCandidateConsumer.accept(digest, callback); + if (!digest.equals(sha256(callback))) { + throw invalid(); + } + return digest; + } catch (Exception failure) { + // Never retain a credential in a callback exception chain. + throw invalid(); + } finally { + wipe(header); + wipe(claims); + wipe(input); + wipe(signature); + wipe(compact); + wipe(callback); + } + } + private static Map delegationClaims( AccountGameplayDelegationPendingIdentity identity, AccountAuthoritySnapshot authority) { if (!authority.accountId().equals(identity.accountId())) { diff --git a/services/account-service/src/main/resources/db/migration/V99__account_control_ui_owner_and_source_guards.sql b/services/account-service/src/main/resources/db/migration/V99__account_control_ui_owner_and_source_guards.sql new file mode 100644 index 0000000000..758957cbfa --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V99__account_control_ui_owner_and_source_guards.sql @@ -0,0 +1,258 @@ +-- Backend preparation only: no route, mounted secret, issuer bean or production activation. +-- Credentials belong only to the separate encrypted response table, never to owner evidence. +CREATE SEQUENCE account_control_ui_source_fence START WITH 1; +CREATE TABLE account_control_ui_issuance_operations ( + request_id UUID PRIMARY KEY, + operation_id UUID NOT NULL UNIQUE, + token_jti UUID NOT NULL UNIQUE, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + caller_workload VARCHAR(256) NOT NULL, + caller_context_id UUID NOT NULL, + request_mac_key_id VARCHAR(32) NOT NULL, + request_digest VARCHAR(64) NOT NULL CHECK (request_digest ~ '^[0-9a-f]{64}$'), + claims_payload BYTEA NOT NULL CHECK (octet_length(claims_payload) BETWEEN 1 AND 16384), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + bundle_payload BYTEA NOT NULL CHECK (octet_length(bundle_payload) BETWEEN 1 AND 131072), + signer_receipt BYTEA NOT NULL CHECK (octet_length(signer_receipt) BETWEEN 1 AND 65536), + issued_at_epoch_second BIGINT NOT NULL CHECK (issued_at_epoch_second > 0), + expires_at_epoch_second BIGINT NOT NULL, + recovery_expires_at TIMESTAMPTZ NOT NULL, + status VARCHAR(16) NOT NULL CHECK (status IN ('PREPARED', 'CANDIDATE', 'COMMITTED', 'FAILED', 'REVOKING', 'REVOKED')), + token_hash VARCHAR(64) UNIQUE CHECK (token_hash ~ '^[0-9a-f]{64}$'), + pending_registry BYTEA, + active_registry BYTEA, + pending_receipt BYTEA, + committed_at TIMESTAMPTZ, + recovery_failed_at TIMESTAMPTZ, + revocation_receipt BYTEA, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (expires_at_epoch_second > issued_at_epoch_second + AND expires_at_epoch_second <= issued_at_epoch_second + 300), + CHECK ((status IN ('PREPARED','FAILED') AND token_hash IS NULL AND pending_registry IS NULL + AND active_registry IS NULL AND pending_receipt IS NULL AND committed_at IS NULL) + OR (status = 'CANDIDATE' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL AND pending_receipt IS NULL AND committed_at IS NULL) + OR (status = 'COMMITTED' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL AND pending_receipt IS NOT NULL AND committed_at IS NOT NULL) + OR (status IN ('REVOKING','REVOKED') AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL + AND ((pending_receipt IS NULL AND committed_at IS NULL) + OR (pending_receipt IS NOT NULL AND committed_at IS NOT NULL)))), + CHECK ((status IN ('FAILED','REVOKING','REVOKED')) = (recovery_failed_at IS NOT NULL)), + CHECK ((status = 'REVOKED') = (revocation_receipt IS NOT NULL)) +); + +CREATE TABLE account_control_ui_response_envelopes ( + operation_id UUID PRIMARY KEY REFERENCES account_control_ui_issuance_operations(operation_id), + encrypted_response BYTEA NOT NULL CHECK (octet_length(encrypted_response) BETWEEN 1 AND 65536), + owner_binding BYTEA NOT NULL CHECK (octet_length(owner_binding) BETWEEN 1 AND 8192), + recovery_expires_at TIMESTAMPTZ NOT NULL +); + +-- [jooq ignore start] +ALTER TABLE account_control_ui_issuance_operations + ADD CONSTRAINT account_control_ui_recovery_expiry_bound CHECK ( + recovery_expires_at > to_timestamp(issued_at_epoch_second) + AND recovery_expires_at <= to_timestamp(issued_at_epoch_second + 60) + AND recovery_expires_at <= to_timestamp(expires_at_epoch_second)); + +CREATE FUNCTION account_control_ui_issuance_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Control-ui issuance evidence cannot be deleted' USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['status','token_hash','pending_registry','active_registry', + 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['status','token_hash','pending_registry','active_registry', + 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) + OR NOT ((OLD.status = 'PREPARED' AND NEW.status = 'CANDIDATE') + OR (OLD.status = 'CANDIDATE' AND NEW.status = 'COMMITTED') + OR (OLD.status = 'PREPARED' AND NEW.status = 'FAILED') + OR (OLD.status IN ('CANDIDATE','COMMITTED') AND NEW.status = 'REVOKING') + OR (OLD.status = 'REVOKING' AND NEW.status = 'REVOKED')) + OR (OLD.status <> 'PREPARED' AND + (NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.pending_registry IS DISTINCT FROM OLD.pending_registry + OR NEW.active_registry IS DISTINCT FROM OLD.active_registry)) + OR (NEW.status IN ('REVOKING','REVOKED') AND + (NEW.pending_receipt IS DISTINCT FROM OLD.pending_receipt + OR NEW.committed_at IS DISTINCT FROM OLD.committed_at)) + OR (OLD.status = 'REVOKING' AND NEW.recovery_failed_at IS DISTINCT FROM OLD.recovery_failed_at) THEN + RAISE EXCEPTION 'Control-ui original operation or candidate cannot change' USING ERRCODE = '23514'; + END IF; + IF NEW.status = 'COMMITTED' AND NOT EXISTS ( + SELECT 1 FROM account_control_ui_response_envelopes e + WHERE e.operation_id = NEW.operation_id AND e.recovery_expires_at = NEW.recovery_expires_at) THEN + RAISE EXCEPTION 'Protected original control-ui response is absent' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_control_ui_issuance_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_guard(); +CREATE TRIGGER account_control_ui_response_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_response_envelopes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_control_ui_issuance_no_truncate + BEFORE TRUNCATE ON account_control_ui_issuance_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_control_ui_response_no_truncate + BEFORE TRUNCATE ON account_control_ui_response_envelopes + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +-- Derive exact source keys from owner rows, not from caller assertions or broad tenant matching. +-- These keys identify serialization only and do not provision authority/baselines. +CREATE FUNCTION account_control_ui_source_keys(table_name TEXT, row_value JSONB) +RETURNS TEXT[] LANGUAGE plpgsql STABLE STRICT AS $$ +DECLARE + account_value TEXT := row_value->>'account_uuid'; + tenant_value TEXT := row_value->>'tenant_uuid'; + scope_kind TEXT; + member RECORD; +BEGIN + CASE table_name + WHEN 'accounts' THEN + RETURN ARRAY['ACCOUNT:' || account_value, 'GLOBAL_ROLES:' || account_value]; + WHEN 'account_authority_generations' THEN + scope_kind := row_value->>'scope_kind'; + IF scope_kind = 'ISSUER' THEN RETURN ARRAY['ISSUER:' || (row_value->>'issuer_id')]; END IF; + IF scope_kind = 'TENANT' THEN RETURN ARRAY['TENANT:' || tenant_value]; END IF; + IF scope_kind = 'MEMBERSHIP' THEN RETURN ARRAY['MEMBERSHIP:' || account_value || '/' || tenant_value]; END IF; + RETURN ARRAY['ACCOUNT:' || account_value, 'GLOBAL_ROLES:' || account_value]; + WHEN 'account_authority_issuance_fences' THEN + RETURN ARRAY['ACCOUNT:' || account_value, 'GLOBAL_ROLES:' || account_value]; + WHEN 'account_membership_pair_authority' THEN + RETURN ARRAY['MEMBERSHIP:' || account_value || '/' || tenant_value]; + WHEN 'account_tenant_membership' THEN + SELECT account_uuid::TEXT INTO account_value FROM accounts WHERE id = (row_value->>'account_id')::BIGINT; + IF tenant_value IS NULL THEN RETURN ARRAY[]::TEXT[]; END IF; + RETURN ARRAY['MEMBERSHIP:' || account_value || '/' || tenant_value]; + WHEN 'account_tenant_membership_role_snapshots', 'account_tenant_membership_role_snapshot_roles' THEN + SELECT a.account_uuid::TEXT AS account_uuid, m.tenant_uuid::TEXT AS tenant_uuid INTO member + FROM account_tenant_membership m JOIN accounts a ON a.id = m.account_id + WHERE m.id = (row_value->>'membership_id')::BIGINT; + IF member.tenant_uuid IS NULL THEN RETURN ARRAY[]::TEXT[]; END IF; + RETURN ARRAY['MEMBERSHIP:' || member.account_uuid || '/' || member.tenant_uuid]; + WHEN 'account_individual_creator_party_sources' THEN + RETURN ARRAY['CREATOR_PARTY:' || (row_value->>'creator_party_id')]; + WHEN 'account_tenant_creator_party_history' THEN + RETURN ARRAY['TENANT:' || tenant_value]; + WHEN 'account_hosted_terms_scopes' THEN + RETURN ARRAY['HOSTED_TERMS:' || (row_value->>'hosted_scope_id')]; + WHEN 'account_individual_hosted_terms_acceptances' THEN + -- Acceptance currentness is party-specific; another party in this catalog is unrelated. + RETURN ARRAY['CREATOR_PARTY:' || (row_value->>'creator_party_id')]; + WHEN 'account_hosted_terms_environment_binding_heads' THEN + RETURN ARRAY['HOSTED_TERMS:environment-boundary/' || (row_value->>'environment_boundary')]; + ELSE + RAISE EXCEPTION 'Unsupported creator source guard owner' USING ERRCODE = '23514'; + END CASE; +END; +$$; + +CREATE FUNCTION account_control_ui_hold_required_sources(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql AS $$ +DECLARE + source_key_value TEXT; + operation_value UUID; +BEGIN + FOR source_key_value IN SELECT value FROM + (SELECT DISTINCT value FROM unnest(source_keys) value WHERE value IS NOT NULL) exact_keys + ORDER BY account_publication_authorization_source_sort_key(value) LOOP + INSERT INTO account_draft_authorization_source_locks(source_key) + VALUES (source_key_value) ON CONFLICT DO NOTHING; + PERFORM source_key FROM account_draft_authorization_source_locks + WHERE source_key = source_key_value FOR UPDATE NOWAIT; + END LOOP; + FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_draft_authorization_sources s WHERE s.source_key = ANY(source_keys) + ORDER BY s.operation_id LOOP + PERFORM operation_id FROM account_draft_authorization_fences + WHERE operation_id = operation_value FOR UPDATE NOWAIT; + IF NOT account_draft_authorization_is_settled(operation_value) THEN + RAISE EXCEPTION 'Required creator source is held until every original owner settles' + USING ERRCODE = '55P03'; + END IF; + END LOOP; +END; +$$; + +CREATE FUNCTION account_control_ui_required_source_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + old_value JSONB; + new_value JSONB; + protected_columns TEXT[]; + source_keys TEXT[] := ARRAY[]::TEXT[]; +BEGIN + IF TG_OP = 'TRUNCATE' THEN + EXECUTE format('SELECT array_agg(k) FROM %I t CROSS JOIN LATERAL ' + || 'unnest(account_control_ui_source_keys(%L, to_jsonb(t))) k', TG_TABLE_NAME, TG_TABLE_NAME) + INTO source_keys; + PERFORM account_control_ui_hold_required_sources(COALESCE(source_keys, ARRAY[]::TEXT[])); + RETURN NULL; + END IF; + IF TG_OP <> 'INSERT' THEN old_value := to_jsonb(OLD); END IF; + IF TG_OP <> 'DELETE' THEN new_value := to_jsonb(NEW); END IF; + IF TG_TABLE_NAME = 'accounts' AND TG_OP = 'UPDATE' THEN + protected_columns := ARRAY['account_uuid','account_uuid_provenance','account_uuid_source_numeric_id', + 'password_hash','email_verified','login_auth_modes','role','lifecycle_state']; + IF NOT EXISTS (SELECT 1 FROM unnest(protected_columns) c + WHERE old_value->c IS DISTINCT FROM new_value->c) THEN RETURN NEW; END IF; + ELSIF TG_OP = 'UPDATE' AND (old_value - ARRAY['created_at','updated_at','recorded_at']) + IS NOT DISTINCT FROM (new_value - ARRAY['created_at','updated_at','recorded_at']) THEN + RETURN NEW; + END IF; + IF old_value IS NOT NULL THEN + source_keys := source_keys || account_control_ui_source_keys(TG_TABLE_NAME, old_value); + END IF; + IF new_value IS NOT NULL THEN + source_keys := source_keys || account_control_ui_source_keys(TG_TABLE_NAME, new_value); + END IF; + PERFORM account_control_ui_hold_required_sources(source_keys); + IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; +END; +$$; + +-- Backfill serialization rows from actual owner scopes only; no evidence or grant is backfilled. +DO $$ +DECLARE + table_value TEXT; + row_value JSONB; + source_key_value TEXT; +BEGIN + FOREACH table_value IN ARRAY ARRAY['accounts','account_authority_generations', + 'account_authority_issuance_fences','account_membership_pair_authority', + 'account_tenant_membership','account_tenant_membership_role_snapshots', + 'account_tenant_membership_role_snapshot_roles','account_individual_creator_party_sources', + 'account_tenant_creator_party_history','account_hosted_terms_scopes', + 'account_individual_hosted_terms_acceptances','account_hosted_terms_environment_binding_heads'] LOOP + FOR row_value IN EXECUTE format('SELECT to_jsonb(t) FROM %I t', table_value) LOOP + FOREACH source_key_value IN ARRAY account_control_ui_source_keys(table_value, row_value) LOOP + IF source_key_value IS NOT NULL THEN + INSERT INTO account_draft_authorization_source_locks(source_key) + VALUES(source_key_value) ON CONFLICT DO NOTHING; + END IF; + END LOOP; + END LOOP; + EXECUTE format('CREATE TRIGGER account_control_ui_required_source_guard ' + || 'BEFORE INSERT OR UPDATE OR DELETE ON %I FOR EACH ROW ' + || 'EXECUTE FUNCTION account_control_ui_required_source_guard()', table_value); + EXECUTE format('CREATE TRIGGER account_control_ui_required_source_truncate_guard ' + || 'BEFORE TRUNCATE ON %I FOR EACH STATEMENT ' + || 'EXECUTE FUNCTION account_control_ui_required_source_guard()', table_value); + END LOOP; + FOREACH table_value IN ARRAY ARRAY['account_draft_authorization_source_locks', + 'account_draft_authorization_fences','account_draft_authorization_sources', + 'account_draft_authorization_owner_readbacks','account_draft_authorization_source_changes', + 'account_draft_authorization_changed_scopes'] LOOP + EXECUTE format('CREATE TRIGGER account_control_ui_draft_no_truncate ' + || 'BEFORE TRUNCATE ON %I FOR EACH STATEMENT ' + || 'EXECUTE FUNCTION account_draft_authorization_immutable_guard()', table_value); + END LOOP; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/redis/lua/account-control-ui-registry-cas.lua b/services/account-service/src/main/resources/redis/lua/account-control-ui-registry-cas.lua new file mode 100644 index 0000000000..7831332361 --- /dev/null +++ b/services/account-service/src/main/resources/redis/lua/account-control-ui-registry-cas.lua @@ -0,0 +1,51 @@ +-- Account-owned control-ui only. The client separately proves owner COMMITTED before activation. +if #KEYS ~= 1 or #ARGV ~= 3 then return -1 end +local key, expected, replacement, expiry = KEYS[1], ARGV[1], ARGV[2], ARGV[3] +if not string.match(key, '^session:auth:token:[0-9a-f]+$') or #key ~= 83 + or #replacement == 0 or #replacement > 32768 or #expected > 32768 + or not string.match(expiry, '^[1-9][0-9]*$') or #expiry > 16 then return -1 end +local deadline = tonumber(expiry) +if not deadline or deadline > 9007199254740991 then return -1 end +local now = redis.call('TIME') +if deadline <= tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000) then return -2 end +local ok, nextRecord = pcall(cjson.decode, replacement) +if not ok or type(nextRecord) ~= 'table' or nextRecord.schemaVersion ~= 1 + or nextRecord.profile ~= 'control-ui' or nextRecord.type ~= 'control-ui' + or nextRecord.audience ~= 'control-ui' or nextRecord.issuer ~= 'firemud-account-service' + or nextRecord.tokenHash ~= string.sub(key, 20) + or nextRecord.globalRoles ~= nil or nextRecord.scopedRoles ~= nil + or nextRecord.exp * 1000 ~= deadline then return -1 end +local current = redis.call('GET', key) +if current == replacement then + if redis.call('PEXPIRETIME', key) ~= deadline then return -3 end + -- Reassert identical bytes/deadline on this physical connection so its WAITAOF covers retry. + redis.call('SET', key, replacement, 'PXAT', expiry) + return 0 +end +if expected == '' then + if current then return -4 end + if nextRecord.state ~= 'pending' or nextRecord.registryVersion ~= 1 then return -1 end +else + if not current or current ~= expected then return -4 end + if redis.call('PEXPIRETIME', key) ~= deadline then return -3 end + local priorOk, prior = pcall(cjson.decode, expected) + if not priorOk then return -1 end + local activation = prior.state == 'pending' and prior.registryVersion == 1 + and nextRecord.state == 'active' and nextRecord.registryVersion == 2 + local revocation = ((prior.state == 'pending' and prior.registryVersion == 1) + or (prior.state == 'active' and prior.registryVersion == 2)) + and nextRecord.state == 'revoked' and nextRecord.registryVersion == 3 + if not activation and not revocation then return -1 end + local function equal(a, b) + if type(a) ~= type(b) then return false end + if type(a) ~= 'table' then return a == b end + for k,v in pairs(a) do if not equal(v,b[k]) then return false end end + for k,_ in pairs(b) do if a[k] == nil then return false end end + return true + end + prior.state, prior.registryVersion = nil, nil + nextRecord.state, nextRecord.registryVersion = nil, nil + if not equal(prior,nextRecord) then return -1 end +end +redis.call('SET', key, replacement, 'PXAT', expiry) +return 1 diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java new file mode 100644 index 0000000000..176b7a3d3f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java @@ -0,0 +1,314 @@ +package integration.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real PostgreSQL raw-source and lock-order definitions. Complete external authenticated capture + * and terminal owner RPC readbacks are explicitly test-only stipulated fixtures, NOT production + * caller/source/World proof. These tests do not claim genuine issuance or COMMIT_ORDER provenance. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountControlUiSourceGuardPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void rawProtectedMutationCannotBypassOriginalFenceButNoOpAndUnrelatedAccountRemainWritable() { + Context c = context(); + var binding = binding(c); + c.tx( + () -> { + c.fences.reserve(binding); + c.fences.claimCommitOrder(binding); + return null; + }); + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", + "test-only-bypass", + binding.actorAccountId()))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("every original owner settles"); + c.tx( + () -> + c.dsl.execute( + "UPDATE accounts SET id = id WHERE account_uuid = ?", binding.actorAccountId())); + // Username/email are not captured Account security/role fields. Existing protections still + // apply. + c.tx( + () -> + c.dsl.execute( + "UPDATE accounts SET username = ? WHERE account_uuid = ?", + "test-noop-metadata-" + UUID.randomUUID(), + binding.actorAccountId())); + UUID unrelated = account(c); + changePassword(c, unrelated, "test-only-unrelated-account-change"); + var ordering = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT ordering FROM account_draft_authorization_fences WHERE operation_id = ?", + binding.operationId()), + "Original authorization fence readback required"); + assertThat(ordering.get("ordering", String.class)).isEqualTo("COMMIT_ORDER"); + } + + @Test + void exactAllOwnerSettlementUnblocksButOneOrMixedReadbackDoesNot() { + for (Outcome outcome : Outcome.values()) { + Context c = context(); + var binding = binding(c); + c.tx( + () -> { + c.fences.reserve(binding); + c.fences.claimCommitOrder(binding); + return null; + }); + terminal(c, binding, Owner.WORLD, outcome); + assertThatThrownBy(() -> changePassword(c, binding.actorAccountId(), "test-only-blocked")) + .isInstanceOf(DataAccessException.class); + terminal(c, binding, Owner.GAME_DESIGN, outcome); + changePassword(c, binding.actorAccountId(), "test-only-settled-change"); + var settlement = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT account_draft_authorization_is_settled(?) AS settled", + binding.operationId()), + "Exact owner settlement readback required"); + assertThat(settlement.get("settled", Boolean.class)).isTrue(); + } + Context c = context(); + var binding = binding(c); + c.tx( + () -> { + c.fences.reserve(binding); + c.fences.claimCommitOrder(binding); + return null; + }); + terminal(c, binding, Owner.WORLD, Outcome.COMMITTED); + terminal(c, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThatThrownBy(() -> changePassword(c, binding.actorAccountId(), "test-only-mixed-denied")) + .isInstanceOf(DataAccessException.class); + } + + @Test + void sourceFirstContentionRollsBackRowsFirstProducerWithoutWaitingOrTerminalReceipt() + throws Exception { + Context c = context(); + var binding = binding(c); + try (Connection writer = c.source.getConnection()) { + writer.setAutoCommit(false); + try (var statement = + writer.prepareStatement( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE")) { + statement.setString(1, binding.sources().getFirst().key()); + statement.executeQuery().close(); + } + Instant started = Instant.now(); + assertThatThrownBy( + () -> + c.tx( + () -> { + c.dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", + binding.actorAccountId()); + c.fences.lockProducerSourcesNowait(binding.sources()); + c.fences.reserve(binding); + return c.fences.claimCommitOrder(binding); + })) + .isInstanceOf(DataAccessException.class); + assertThat(Duration.between(started, Instant.now())).isLessThan(Duration.ofSeconds(2)); + assertThat(c.dsl.fetchCount(DSL.table("account_draft_authorization_fences"))).isZero(); + assertThat(c.dsl.fetchCount(DSL.table("account_draft_authorization_owner_readbacks"))) + .isZero(); + writer.rollback(); + } + c.tx( + () -> { + c.fences.lockProducerSourcesNowait(binding.sources()); + c.fences.reserve(binding); + return c.fences.claimCommitOrder(binding); + }); + assertThatThrownBy( + () -> changePassword(c, binding.actorAccountId(), "test-only-producer-first")) + .isInstanceOf(DataAccessException.class); + } + + @Test + void waitingAndRevokeIntentCanStillBeRecordedWhileActualMutationStaysDenied() { + Context c = context(); + var binding = binding(c); + c.tx(() -> c.fences.reserve(binding)); + var intent = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), binding.sources(), new byte[] {11}); + assertThat(c.tx(() -> c.fences.requestSourceChange(intent))).isFalse(); + assertThat(c.tx(() -> c.fences.read(binding)).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER); + assertThatThrownBy(() -> changePassword(c, binding.actorAccountId(), "test-only-before-aborts")) + .isInstanceOf(DataAccessException.class); + terminal(c, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + terminal(c, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThat(c.tx(() -> c.fences.sourceMutationPermitted(intent))).isTrue(); + changePassword(c, binding.actorAccountId(), "test-only-after-aborts"); + } + + private static void terminal( + Context c, DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { + c.tx( + () -> { + c.fences.recordOwnerReadback( + binding, + new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {7})); + return null; + }); + } + + private static void changePassword(Context c, UUID id, String hash) { + c.tx( + () -> { + Account account = new AccountRepository(c.dsl).findByAccountUuid(id).orElseThrow(); + account.setPasswordHash(hash); + return new AccountRepository(c.dsl).save(account); + }); + } + + private static UUID account(Context c) { + return c.tx( + () -> { + Account row = new Account(); + String suffix = UUID.randomUUID().toString(); + row.setUsername("test-" + suffix); + row.setEmail(suffix + "@example.test"); + row.setPasswordHash("test-only-hash"); + return new AccountRepository(c.dsl).save(row).getAccountUuid(); + }); + } + + private static DraftAuthorizationFenceBinding binding(Context c) { + UUID actor = account(c); + var complete = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "test-only-tenant-key", + 2, + "test-only-tenant-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "test-only/base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-only-world-payload")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "test-region", + "aggregate", + "test-region", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + actor, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + "test-only-source-fixture".getBytes(java.nio.charset.StandardCharsets.UTF_8)))); + } + + private static Context context() { + String schema = "control_ui_guard_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context(source, dsl, new DraftAuthorizationFenceRepository(dsl), transaction); + } + + private record Context( + DriverManagerDataSource source, + DSLContext dsl, + DraftAuthorizationFenceRepository fences, + TransactionTemplate transaction) { + T tx(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java new file mode 100644 index 0000000000..7430bd3ffa --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java @@ -0,0 +1,446 @@ +package integration.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadService; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Flyway/PostgreSQL owner-read proof over explicitly stipulated test-only original bindings. + * The database rows, separate Account owner transaction, immutable order/readback state, and V99 + * source guards are real. The creator/source capture and workload Context are test fixtures only; + * this proves neither authenticated creator issuance nor physical mTLS or a production caller. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountDraftCommitOrderReadPostgresIntegrationTest { + private static final String NAMESPACE = "held-order-proof"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void acceptsOnlyExactCommittedHeldOrderInSeparateWritableReadCommittedTransaction() + throws Exception { + Fixture fixture = fixture(); + DraftAuthorizationFenceBinding binding = binding(fixture); + fixture.tx( + () -> { + fixture.repository.reserve(binding); + fixture.repository.claimCommitOrder(binding); + return null; + }); + var before = snapshot(fixture); + assertThat(ordering(fixture, binding)).isEqualTo("COMMIT_ORDER"); + fixture.transactions.reset(); + + asWorld(() -> fixture.reader.requireHeld(request(binding))); + + assertThat(fixture.transactions.beginCount()).isOne(); + assertThat(fixture.transactions.lastDefinition().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(fixture.transactions.lastDefinition().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(fixture.transactions.lastDefinition().isReadOnly()).isFalse(); + assertThat(snapshot(fixture)).isEqualTo(before); + assertThat(fixture.tx(() -> fixture.repository.readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + + // V99's real source guard remains effective while this original owner result is unresolved. + String passwordBefore = accountPassword(fixture, binding.actorAccountId()); + assertThatThrownBy( + () -> + fixture.tx( + () -> { + fixture.dsl.execute( + "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", + "test-only-blocked-change", + binding.actorAccountId()); + return null; + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Required creator source is held"); + assertThat(accountPassword(fixture, binding.actorAccountId())).isEqualTo(passwordBefore); + assertThat(snapshot(fixture)).isEqualTo(before); + } + + @Test + void deniesReservedRevokedSettledChangedAndMissingBindings() { + for (ReadCase readCase : ReadCase.values()) { + Fixture fixture = fixture(); + DraftAuthorizationFenceBinding original = binding(fixture); + DraftAuthorizationFenceBinding requested = original; + switch (readCase) { + case RESERVED -> fixture.tx(() -> fixture.repository.reserve(original)); + case REVOKE_ORDER -> { + fixture.tx(() -> fixture.repository.reserve(original)); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), original.sources(), new byte[] {9}); + assertThat(fixture.tx(() -> fixture.repository.requestSourceChange(change))).isFalse(); + assertThat(ordering(fixture, original)).isEqualTo("REVOKE_ORDER"); + } + case SETTLED -> { + reserveAndCommitOrder(fixture, original); + recordReadback(fixture, original, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {1}); + recordReadback(fixture, original, Owner.WORLD, Outcome.COMMITTED, new byte[] {2}); + assertThat(fixture.tx(() -> fixture.repository.readSettlement(original))) + .isEqualTo(Settlement.COMMITTED); + } + case CHANGED_BINDING -> { + reserveAndCommitOrder(fixture, original); + requested = changedBinding(original); + } + case MISSING -> requested = binding(fixture); + } + + fixture.transactions.reset(); + DraftAuthorizationFenceBinding submitted = requested; + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asWorld(() -> fixture.reader.requireHeld(request(submitted)))); + assertThat(fixture.transactions.beginCount()).isOne(); + if (readCase != ReadCase.MISSING) { + assertThat( + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT binding FROM account_draft_authorization_fences WHERE operation_id = ?", + original.operationId())) + .get("binding", byte[].class)) + .containsExactly(original.canonicalBytes()); + } + } + } + + @Test + void rejectsMissingAndWrongWorkloadContextBeforeOpeningOwnerTransaction() { + Fixture fixture = fixture(); + DraftAuthorizationFenceBinding binding = binding(fixture); + reserveAndCommitOrder(fixture, binding); + var request = request(binding); + fixture.transactions.reset(); + + assertStatus(Status.Code.UNAUTHENTICATED, () -> fixture.reader.requireHeld(request)); + assertThat(fixture.transactions.beginCount()).isZero(); + for (String uri : + List.of( + "spiffe://firemud/ns/held-order-proof/sa/account-service", + "spiffe://firemud/ns/other/sa/world-management-service")) { + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> asPeer(uri, () -> fixture.reader.requireHeld(request))); + assertThat(fixture.transactions.beginCount()).isZero(); + } + } + + private static Fixture fixture() { + String schema = "held_order_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = new DriverManagerDataSource(); + source.setUrl(postgres.getJdbcUrl()); + source.setUsername(postgres.getUsername()); + source.setPassword(postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("latest") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + CountingTransactionManager transactions = + new CountingTransactionManager(new DataSourceTransactionManager(source)); + TransactionTemplate transaction = new TransactionTemplate(transactions); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + DraftAuthorizationFenceRepository repository = new DraftAuthorizationFenceRepository(dsl); + AccountDraftCommitOrderReadService reader = + new AccountDraftCommitOrderReadService(repository, transactions, NAMESPACE); + return new Fixture(dsl, repository, transactions, transaction, reader); + } + + private static DraftAuthorizationFenceBinding binding(Fixture fixture) { + UUID account = + fixture.tx( + () -> { + Account row = new Account(); + String suffix = UUID.randomUUID().toString(); + row.setUsername("held-order-" + suffix); + row.setEmail(suffix + "@example.test"); + row.setPasswordHash("test-only-original-hash"); + return new AccountRepository(fixture.dsl).save(row).getAccountUuid(); + }); + UUID tenant = UUID.randomUUID(); + UUID version = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof( + tenant, version, 17L, "test-tenant", 23L, "test-tenant", "NEW_GAME_ROW"), + request, + commit, + "test-base", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-change")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "REGION", + "test-region", + "AGGREGATE", + "test-region", + "0"))); + byte[] draftBytes = complete.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + request, + commit, + UUID.randomUUID(), + account, + tenant, + version, + complete.baseCommitId(), + "0", + draftBytes, + draftBytes, + complete.digest(), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + "1", + "1", + "test-account-stream/" + account, + "0", + new byte[] {7}))); + } + + private static DraftAuthorizationFenceBinding changedBinding( + DraftAuthorizationFenceBinding original) { + SourceEvidence source = original.sources().getFirst(); + return new DraftAuthorizationFenceBinding( + original.operationId(), + original.requestId(), + original.commitId(), + original.fenceId(), + original.actorAccountId(), + original.tenantId(), + original.versionId(), + original.baseCommitId(), + original.expectedDraftEpoch(), + original.gameDesignBinding(), + original.normalizedInput(), + original.inputDigest(), + List.of( + new SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + new byte[] {8})), + original.schemaVersion(), + original.requiredOwners()); + } + + private static void reserveAndCommitOrder( + Fixture fixture, DraftAuthorizationFenceBinding binding) { + fixture.tx( + () -> { + fixture.repository.reserve(binding); + fixture.repository.claimCommitOrder(binding); + return null; + }); + } + + private static void recordReadback( + Fixture fixture, + DraftAuthorizationFenceBinding binding, + Owner owner, + Outcome outcome, + byte[] result) { + OwnerReadback readback = + new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + result); + fixture.tx( + () -> { + fixture.repository.recordOwnerReadback(binding, readback); + return null; + }); + } + + private static DraftCommitOrderReadEvidence.Request request( + DraftAuthorizationFenceBinding binding) { + return DraftCommitOrderReadEvidence.Request.create(NAMESPACE, binding.canonicalBytes()); + } + + private static String ordering(Fixture fixture, DraftAuthorizationFenceBinding binding) { + return Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT ordering FROM account_draft_authorization_fences WHERE operation_id = ?", + binding.operationId())) + .get("ordering", String.class); + } + + private static String accountPassword(Fixture fixture, UUID accountId) { + return Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT password_hash FROM accounts WHERE account_uuid = ?", accountId)) + .get("password_hash", String.class); + } + + private static EvidenceSnapshot snapshot(Fixture fixture) { + return new EvidenceSnapshot( + fixture.dsl.fetch("SELECT * FROM account_draft_authorization_fences ORDER BY operation_id"), + fixture.dsl.fetch( + "SELECT * FROM account_draft_authorization_sources ORDER BY operation_id, source_key"), + fixture.dsl.fetch( + "SELECT * FROM account_draft_authorization_owner_readbacks ORDER BY operation_id, owner"), + fixture.dsl.fetch( + "SELECT * FROM account_draft_authorization_source_locks ORDER BY source_key")); + } + + private static void assertStatus(Status.Code expected, Runnable operation) { + assertThatThrownBy(operation::run) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(expected); + } + + private static void asWorld(Runnable operation) { + asPeer("spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", operation); + } + + private static void asPeer(String uri, Runnable operation) { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(uri).orElseThrow(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + operation.run(); + } finally { + context.detach(previous); + } + } + + private enum ReadCase { + RESERVED, + REVOKE_ORDER, + SETTLED, + CHANGED_BINDING, + MISSING + } + + private record EvidenceSnapshot( + List fences, + List sources, + List ownerReadbacks, + List sourceLocks) {} + + private record Fixture( + DSLContext dsl, + DraftAuthorizationFenceRepository repository, + CountingTransactionManager transactions, + TransactionTemplate transaction, + AccountDraftCommitOrderReadService reader) { + private T tx(Supplier work) { + return transaction.execute(status -> work.get()); + } + } + + /** + * Counts and records owner transaction definitions while delegating to real JDBC transactions. + */ + private static final class CountingTransactionManager implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private final AtomicInteger begins = new AtomicInteger(); + private volatile TransactionDefinition lastDefinition; + + private CountingTransactionManager(PlatformTransactionManager delegate) { + this.delegate = delegate; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + begins.incrementAndGet(); + lastDefinition = definition; + return delegate.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + delegate.commit(status); + } + + @Override + public void rollback(TransactionStatus status) { + delegate.rollback(status); + } + + private int beginCount() { + return begins.get(); + } + + private TransactionDefinition lastDefinition() { + return Objects.requireNonNull(lastDefinition); + } + + private void reset() { + begins.set(0); + lastDefinition = null; + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java new file mode 100644 index 0000000000..8d654aa506 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java @@ -0,0 +1,396 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl.ControlUiPrimaryIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.AcknowledgementRequirements; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Flyway/PostgreSQL owner storage proof only. Primary authentication, canonical authority, + * signer capture and Redis/TLS/WAITAOF are explicitly test-only doubles. The tenant source is a + * stipulated external Game Design fixture, not genuine owner provenance. No private proof + * constructor is bypassed: Coordination creates its receipt through its normal transport path. + * Opaque envelope fixture bytes prove retention, not AEAD, genuine issuance or physical Redis. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountControlUiIssuancePostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void originalPreparedCandidateCommittedAndLostResponseReadBackExactOwnerBytes() { + Context c = context(); + Fixture f = new Fixture(c); + var prepared = f.prepare(); + assertThat(prepared.status).isEqualTo("PREPARED"); + var candidate = f.candidate(prepared); + assertThat(candidate.status).isEqualTo("CANDIDATE"); + Transport transport = new Transport(candidate); + var pending = + transport.client.registerPending( + candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis()); + var committed = c.tx(() -> c.operations.commit(candidate, pending)); + assertThat(committed.stored.status).isEqualTo("COMMITTED"); + + // Discard the commit response and re-read through a fresh repository instance/transaction. + var reread = + c.tx(() -> new AccountControlUiIssuanceRepository(c.dsl).findRequest(prepared.requestId)); + var recovered = c.tx(() -> c.operations.requireCommitted(reread)); + assertOriginal(prepared, recovered.stored); + assertThat(recovered.tokenHash()).isEqualTo(candidate.tokenHash); + assertThat(recovered.pendingRegistry()).isEqualTo(candidate.pendingRegistry); + assertThat(recovered.activeRegistry()).isEqualTo(candidate.activeRegistry); + var envelope = + Objects.requireNonNull( + c.tx(() -> c.operations.envelope(reread)), + "Original protected response envelope readback required"); + assertThat(envelope.encrypted()).isEqualTo(f.encryptedResponse); + assertThat(envelope.binding()).isEqualTo(f.ownerBinding); + assertThat(c.dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))).isEqualTo(1); + assertThat(c.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isEqualTo(1); + } + + @Test + void changedOriginalAndDirectSqlByteOrTimingChangesCannotRewriteRetainedOperation() { + Context c = context(); + Fixture f = new Fixture(c); + var prepared = f.prepare(); + var candidate = f.candidate(prepared); + Transport transport = new Transport(candidate); + var pending = + transport.client.registerPending( + candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis()); + c.tx(() -> c.operations.commit(candidate, pending)); + var changedRow = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE request_id = ?", + prepared.requestId), + "Original issuance row required before changed-input definition"); + changedRow.set( + changedRow.field("claims_payload", byte[].class), bytes("test-only-changed-original")); + var changed = new AccountControlUiIssuanceRepository.Stored(changedRow); + assertThatThrownBy(() -> c.tx(() -> c.operations.requireCommitted(changed))) + .isInstanceOf(IllegalStateException.class); + for (String column : + List.of("claims_payload", "source_payload", "bundle_payload", "signer_receipt")) { + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "UPDATE account_control_ui_issuance_operations SET " + + column + + " = ? WHERE request_id = ?", + bytes("test-only-rewrite"), + prepared.requestId))) + .isInstanceOf(DataAccessException.class); + } + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "UPDATE account_control_ui_issuance_operations" + + " SET recovery_expires_at = recovery_expires_at + INTERVAL '1 second' WHERE request_id = ?", + prepared.requestId))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "UPDATE account_control_ui_response_envelopes" + + " SET encrypted_response = ? WHERE operation_id = ?", + bytes("test-only-envelope-rewrite"), + prepared.operationId))) + .isInstanceOf(DataAccessException.class); + // A new row cannot evade the actual PostgreSQL-specific recovery bound either. + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "INSERT INTO account_control_ui_issuance_operations" + + " (request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload, caller_context_id," + + " request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt," + + " issued_at_epoch_second, expires_at_epoch_second, recovery_expires_at, status)" + + " SELECT ?, ?, ?, account_uuid, tenant_uuid, caller_workload, caller_context_id, request_mac_key_id," + + " request_digest, claims_payload, source_payload, bundle_payload, signer_receipt, issued_at_epoch_second," + + " expires_at_epoch_second, to_timestamp(issued_at_epoch_second + 61), 'PREPARED'" + + " FROM account_control_ui_issuance_operations WHERE request_id = ?", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + prepared.requestId))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("account_control_ui_recovery_expiry_bound"); + assertOriginal(prepared, c.tx(() -> c.operations.findRequest(prepared.requestId))); + } + + @Test + void + durableRevokingDeniesCommittedRecoveryAndUnavailableExternalRevocationIsNotTerminalSuccess() { + Context c = context(); + Fixture f = new Fixture(c); + var prepared = f.prepare(); + var candidate = f.candidate(prepared); + Transport transport = new Transport(candidate); + var pending = + transport.client.registerPending( + candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis()); + var committed = c.tx(() -> c.operations.commit(candidate, pending)); + var revoking = c.tx(() -> c.operations.beginRecoveryFailure(committed.stored)); + assertThat(revoking.status).isEqualTo("REVOKING"); + assertThatThrownBy(() -> c.tx(() -> c.operations.requireCommitted(committed.stored))) + .isInstanceOf(IllegalStateException.class); + when(transport.commands.get(any(byte[].class))) + .thenThrow(new IllegalStateException("test-only transport unavailable")); + assertThatThrownBy(() -> transport.client.revoke(revoking)) + .isInstanceOf(IllegalStateException.class); + var held = c.tx(() -> c.operations.findRequest(prepared.requestId)); + assertThat(held.status).isEqualTo("REVOKING"); + assertOriginal(prepared, held); + var revocation = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT revocation_receipt FROM account_control_ui_issuance_operations WHERE request_id = ?", + prepared.requestId), + "Durable non-authorizing issuance row must remain present"); + assertThat(revocation.get("revocation_receipt")).isNull(); + assertThat(c.tx(() -> c.operations.beginRecoveryFailure(held)).status).isEqualTo("REVOKING"); + + byte[] revoked = AccountControlUiIssuanceRepository.revokedRegistry(held); + doReturn(held.pendingRegistry, revoked).when(transport.commands).get(any(byte[].class)); + var receipt = transport.client.revoke(held); + c.tx( + () -> { + c.operations.finishRecoveryFailure(held, receipt); + return null; + }); + assertThat(c.tx(() -> c.operations.findRequest(prepared.requestId)).status) + .isEqualTo("REVOKED"); + assertThatThrownBy(() -> c.tx(() -> c.operations.requireCommitted(committed.stored))) + .isInstanceOf(IllegalStateException.class); + } + + private static void assertOriginal( + AccountControlUiIssuanceRepository.Stored original, + AccountControlUiIssuanceRepository.Stored observed) { + assertThat(observed.operationId).isEqualTo(original.operationId); + assertThat(observed.requestId).isEqualTo(original.requestId); + assertThat(observed.jti).isEqualTo(original.jti); + assertThat(observed.claims).isEqualTo(original.claims); + assertThat(observed.sources).isEqualTo(original.sources); + assertThat(observed.bundle).isEqualTo(original.bundle); + assertThat(observed.signerReceipt).isEqualTo(original.signerReceipt); + assertThat(observed.issuedAt).isEqualTo(original.issuedAt); + assertThat(observed.expiresAt).isEqualTo(original.expiresAt); + assertThat(observed.recoveryExpiry).isEqualTo(original.recoveryExpiry); + } + + private static final class Fixture { + final Context c; + final UUID actor, tenant = UUID.randomUUID(), request = UUID.randomUUID(); + final ControlUiPrimaryIdentity primary = mock(ControlUiPrimaryIdentity.class); + final AccountControlUiAuthority.Snapshot authority = + mock(AccountControlUiAuthority.Snapshot.class); + final AccountControlUiSignerOwner.Capture signer = + mock(AccountControlUiSignerOwner.Capture.class); + final byte[] encryptedResponse = bytes("test-only-opaque-encrypted-response-double"); + final byte[] ownerBinding = bytes("test-only-exact-envelope-owner-binding"); + + Fixture(Context c) { + this.c = c; + actor = + c.tx( + () -> { + Account account = new Account(); + String suffix = UUID.randomUUID().toString(); + account.setUsername("control-ui-" + suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash("test-only-primary-hash"); + return new AccountRepository(c.dsl).save(account).getAccountUuid(); + }); + // Stipulated external creation evidence only; real source/claim triggers still execute. + c.tx( + () -> + c.dsl.execute( + "INSERT INTO account_fresh_tenant_identity_associations" + + " (schema_version, target_namespace, creation_request_id, operation_id, request_digest," + + " canonical_tenant_id, source_game_row_id, source_game_tenant_key, provenance_kind, evidence_digest)" + + " VALUES (1, 'test-control', ?, ?, ?, ?, 1, ?, 'NEW_GAME_ROW', ?)", + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + tenant, + tenant.toString(), + "sha256:" + "b".repeat(64))); + when(primary.accountId()).thenReturn(actor); + when(authority.actor()).thenReturn(actor); + when(authority.tenant()).thenReturn(tenant); + when(authority.authorityTuple()) + .thenReturn( + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 1L, + "tenantAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "membershipAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "privateRealmGrantVersions", + List.of())); + when(authority.membershipVersion()).thenReturn(Map.of(tenant.toString(), 1L)); + when(authority.issuanceFence()).thenReturn(1L); + when(authority.evidence()).thenReturn(bytes("test-only-source-evidence-double")); + when(authority.sources()) + .thenReturn( + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + bytes("test-only-account-source")))); + when(authority.accountIdentitySource()).thenReturn(Map.of("testOnly", true)); + when(authority.outboxCheckpoints()).thenReturn(List.of()); + when(signer.receipt()).thenReturn(bytes("test-only-signer-receipt-double")); + when(signer.kid()).thenReturn("test-control-kid"); + when(signer.generation()).thenReturn("1"); + } + + AccountControlUiIssuanceRepository.Stored prepare() { + return c.tx( + () -> + c.operations.prepare( + request, + "spiffe://test-only/control-ui", + UUID.randomUUID(), + "test-mac1", + "c".repeat(64), + primary, + authority, + signer, + Instant.ofEpochSecond(Instant.now().getEpochSecond()))); + } + + AccountControlUiIssuanceRepository.Stored candidate( + AccountControlUiIssuanceRepository.Stored original) { + return c.tx( + () -> + c.operations.bindCandidate( + original, "d".repeat(64), encryptedResponse, ownerBinding, signer)); + } + } + + /** No Redis process or TLS proof: only actual owner adapter/receipt construction with doubles. */ + private static final class Transport { + @SuppressWarnings("unchecked") + final RedisCommands commands = mock(RedisCommands.class); + + @SuppressWarnings("unchecked") + final StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + + final AccountControlUiCoordination client; + + Transport(AccountControlUiIssuanceRepository.Stored original) { + var descriptor = AccountControlUiRegistryContract.descriptor(); + var catalog = mock(RedisScriptCatalog.class); + when(catalog.require(AccountControlUiRegistryContract.SCRIPT_ID)).thenReturn(descriptor); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()) + .thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn("account_coord_app"); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer( + invocation -> + AccountControlUiCoordination.digest("SHA-1", invocation.getArgument(0))); + doReturn(1L) + .when(commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + doReturn(List.of(1L, 1L)).when(commands).dispatch(any(), any(), any()); + when(commands.pexpiretime(any(byte[].class))).thenReturn(original.expiryMillis()); + when(commands.get(any(byte[].class))).thenReturn(original.pendingRegistry); + client = + new AccountControlUiCoordination( + () -> connection, new AcknowledgementRequirements(1, 1, 1000), catalog); + } + } + + private static Context context() { + String schema = "control_ui_storage_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context(dsl, new AccountControlUiIssuanceRepository(dsl), transaction); + } + + private record Context( + DSLContext dsl, + AccountControlUiIssuanceRepository operations, + TransactionTemplate transaction) { + T tx(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java new file mode 100644 index 0000000000..d449f27fda --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java @@ -0,0 +1,634 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import de.mkammerer.argon2.Argon2Factory; +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftSourceCompositionService; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.mapper.AccountMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.AcknowledgementRequirements; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mapstruct.factory.Mappers; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Composed negative boundary, NOT successful issuer/end-to-end proof. Actual primary auth, + * canonical source composition/currentness, issuance service/repository and PostgreSQL transactions + * execute together. External creation/bootstrap, party verification, legal action/publication and + * environment observations are explicitly stipulated test-only fixtures. Real signer owner is + * deliberately unavailable: no fabricated committed signer, private Capture, registry receipt or + * successful issuance is manufactured. Missing custody/signing/Redis never become authority. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountControlUiOwnerWorkflowPostgresIntegrationTest { + private static final String NAMESPACE = "control-ui-owner-proof"; + private static final String CALLER = + "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; + private static final String OTP = "test-only-original-creator-otp"; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @TempDir Path temporary; + + @Test + void realSourceAndPrimaryCompositionRollsBackOtpWhenGenuineSignerIsUnavailable() { + Fixture f = new Fixture(temporary); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + var source = f.tx(() -> f.authority.captureInitial(f.tenant, environment)); + assertThat(source.actor()).isEqualTo(f.account.getAccountUuid()); + assertThat(source.tenant()).isEqualTo(f.tenant); + assertThat(source.sources()).hasSize(8); + var originalOtp = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); + try (var ignored = withPeer(CALLER)) { + assertThatThrownBy(() -> f.service.issue(f.request(OTP), environment)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Existing committed control-ui signer unavailable"); + assertThat(f.challenges.findByAccountId(f.account.getId())).contains(originalOtp); + // The same exact request can retry its original OTP after owner rollback, but cannot mint. + assertThatThrownBy(() -> f.service.issue(f.request(OTP), environment)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Existing committed control-ui signer unavailable"); + assertThatThrownBy(() -> f.service.issue(f.request("changed-secret"), environment)) + .isInstanceOf(AuthenticationException.class); + } + var afterDenial = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); + assertThat(afterDenial.getId()).isEqualTo(originalOtp.getId()); + assertThat(afterDenial.getCodeHash()).isEqualTo(originalOtp.getCodeHash()); + assertThat(afterDenial.getInvalidAttemptCount()).isEqualTo(1); + f.assertNoIssuance(); + } + + @Test + void invalidOtpBudgetPersistsThroughProxiedPrimaryDenialAndExhaustsExistingFiveAttemptLimit() { + Fixture f = new Fixture(temporary); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + var original = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); + try (var ignored = withPeer(CALLER)) { + for (int attempt = 1; attempt <= 5; attempt++) { + assertThatThrownBy(() -> f.service.issue(f.request("wrong-otp"), environment)) + .isInstanceOf(AuthenticationException.class); + if (attempt < 5) { + var retained = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); + assertThat(retained.getId()).isEqualTo(original.getId()); + assertThat(retained.getCodeHash()).isEqualTo(original.getCodeHash()); + assertThat(retained.getInvalidAttemptCount()).isEqualTo(attempt); + } else { + assertThat(f.challenges.findByAccountId(f.account.getId())).isEmpty(); + } + } + assertThatThrownBy(() -> f.service.issue(f.request(OTP), environment)) + .isInstanceOf(AuthenticationException.class); + } + f.assertNoIssuance(); + } + + @Test + void concurrentInvalidAttemptsBothCommitTheirOwnAccountingWithoutMinting() throws Exception { + Fixture f = new Fixture(temporary); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + java.util.concurrent.Callable attempt = + () -> { + try (var ignored = withPeer(CALLER)) { + ready.countDown(); + awaitLatch(start); + try { + f.service.issue(f.request("concurrent-wrong-otp"), environment); + throw new AssertionError("Invalid credential must not authenticate"); + } catch (AuthenticationException expected) { + return expected; + } + } + }; + var first = executor.submit(attempt); + var second = executor.submit(attempt); + awaitLatch(ready); + start.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS)).isNotNull(); + assertThat(second.get(10, TimeUnit.SECONDS)).isNotNull(); + assertThat( + f.challenges + .findByAccountId(f.account.getId()) + .orElseThrow() + .getInvalidAttemptCount()) + .isEqualTo(2); + f.assertNoIssuance(); + } finally { + start.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + + private static void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Expected concurrent credential attempt boundary"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted concurrent credential attempt boundary"); + } + } + + @Test + void changedProtectedCallerAndUnboundCurrentEnvironmentDenyWithoutConsumingOtp() { + Fixture f = new Fixture(temporary); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + var originalOtp = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); + try (var ignored = + withPeer("spiffe://firemud/ns/control-ui-owner-proof/sa/game-design-service")) { + assertThatThrownBy(() -> f.service.issue(f.request(OTP), environment)) + .isInstanceOf(IllegalStateException.class); + } + // Explicit test-only protected environment observation now identifies a different scope. + // The actual current owner binding repository has no matching publication; no fallback exists. + f.boundary.set(testBoundary("test-withdrawn")); + CapturedEnvironmentBoundary changed = f.terms.captureCurrentEnvironmentBoundary(); + try (var ignored = withPeer(CALLER)) { + assertThatThrownBy(() -> f.service.issue(f.request(OTP), changed)) + .isInstanceOf(RuntimeException.class); + } + assertThat(f.challenges.findByAccountId(f.account.getId())).contains(originalOtp); + f.assertNoIssuance(); + } + + private static final class Fixture { + final DSLContext dsl; + final TransactionTemplate transactions; + final Account account; + final UUID tenant = UUID.randomUUID(), + request = UUID.randomUUID(), + callerContext = UUID.randomUUID(); + final AtomicReference boundary = + new AtomicReference<>(testBoundary("test-production")); + final AtomicInteger coordinationCalls = new AtomicInteger(); + final AccountEmailLoginChallengeRepository challenges; + final AccountHostedTermsService terms; + final AccountControlUiAuthority authority; + final AccountControlUiIssuanceService service; + + Fixture(Path root) { + String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + var manager = new DataSourceTransactionManager(dataSource); + transactions = new TransactionTemplate(manager); + transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var accounts = new AccountRepository(dsl, sourceEvidence); + account = + tx( + () -> { + Account candidate = new Account(); + String suffix = UUID.randomUUID().toString(); + candidate.setUsername("owner-" + suffix); + candidate.setEmail(suffix + "@example.test"); + candidate.setPasswordHash(hash("test-only-disabled-password")); + candidate.setLoginAuthModes("EMAIL_OTP"); + return accounts.save(candidate); + }); + var creator = testCreation(account.getAccountUuid(), tenant); + var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + tx( + () -> { + fresh.importVerified(creator.creationEvidence()); + generations.initializeTenantIfAbsent(tenant); + return null; + }); + var pairs = new AccountMembershipPairAuthorityRepository(dsl); + var memberships = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var bootstrapOperations = new AccountTenantCreationBootstrapOperationRepository(dsl); + var reader = + new AccountCreatorMembershipSourceReader( + accounts, + new AccountJoinOperationRepository(dsl), + memberships, + pairs, + roles, + fresh, + generations, + outbox, + sourceEvidence, + bootstrapOperations); + var beans = new StaticListableBeanFactory(); + AccountTenantCreationBootstrapAuthorizationSource externalBootstrap = + (actual, mutation) -> { + if (!creator.equals(actual) + || !TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Exact test-only external bootstrap fixture required"); + } + return mutation.get(); + }; + beans.addBean("testOnlyBootstrapAuthority", externalBootstrap); + var bootstrap = + new AccountTenantCreationBootstrapService( + accounts, + fresh, + reader, + pairs, + memberships, + roles, + outbox, + new AccountAuditOutboxRepository(dsl), + bootstrapOperations, + beans.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class)); + tx(() -> bootstrap.bootstrap(creator)); + var party = + new IndividualCreatorPartySource( + UUID.randomUUID(), + account.getAccountUuid(), + VerificationStatus.VERIFIED, + 1L, + "test-only-policy", + 1L, + "test-only-verification", + 1L, + 1L); + insertTestParty(dsl, party); + var parties = new IndividualCreatorPartyRepository(dsl, fresh, bootstrapOperations); + tx(() -> parties.associateFresh(UUID.randomUUID(), creator, party)); + var fences = new DraftAuthorizationFenceRepository(dsl); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindings = new HashMap<>(); + terms = + new AccountHostedTermsService( + manager, + new HostedTermsRepository(dsl), + parties, + fences, + id -> externalFixture(publications, id), + id -> externalFixture(actions, id), + new HostedTermsEnvironmentBindingRepository(dsl), + id -> externalFixture(bindings, id), + () -> { + requireOutsideTransaction(); + return boundary.get(); + }); + UUID publication = UUID.randomUUID(); + publications.put( + publication, + new AccountHostedTermsService.PublicationEvidence( + UUID.randomUUID(), + "Test-only Operator", + 1L, + bytes("Test-only initial terms"), + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-only-publication-audit", + 1L, + "test-only-notice", + 1L, + Instant.now().minusSeconds(30).truncatedTo(ChronoUnit.MICROS))); + var catalog = terms.publish(publication).candidate(); + UUID action = UUID.randomUUID(); + actions.put( + action, + new AccountHostedTermsService.AcceptanceAction( + action, + true, + account.getAccountUuid(), + party.creatorPartyId(), + catalog.hostedScopeId(), + catalog.versionId(), + catalog.documentDigest(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + "test-only-affirmative-action", + 1L, + OffsetDateTime.now(ZoneOffset.UTC))); + terms.accept(action); + UUID binding = UUID.randomUUID(); + bindings.put( + binding, + new HostedTermsEnvironmentBinding.PublicationEvidence( + "test-production", + catalog.hostedScopeId(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + catalog.versionId(), + catalog.sourceVersion(), + "test-only-environment-publisher", + "test-only-environment-publication/" + binding, + null, + null)); + terms.publishEnvironmentBinding(binding); + authority = + new AccountControlUiAuthority( + new AccountDraftSourceCompositionService( + dsl, parties, bootstrap, terms, sourceEvidence)); + challenges = new AccountEmailLoginChallengeRepository(dsl); + tx( + () -> { + var challenge = new AccountEmailLoginChallenge(); + var now = LocalDateTime.now().withNano(0); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash(OTP)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); + var primary = + new AccountServiceImpl( + accounts, + null, + null, + null, + challenges, + null, + null, + Mappers.getMapper(AccountMapper.class), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + manager); + // Exercise the real MANDATORY interceptor: noRollbackFor must not poison the owner callback. + var primaryProxy = new ProxyFactory(primary); + primaryProxy.setProxyTargetClass(true); + primaryProxy.addAdvice( + new TransactionInterceptor(manager, new AnnotationTransactionAttributeSource())); + primary = (AccountServiceImpl) primaryProxy.getProxy(); + var signerRepository = new AccountJwtSignerDesiredStateRepository(dsl); + var trust = new AccountJwtSignerMaterializerTrustBinding(false, ""); + var api = new AccountJwtJwksApiBinding(); + var signer = + new AccountControlUiSignerOwner( + signerRepository, trust, api, root.resolve("private"), root.resolve("public")); + var operations = new AccountControlUiIssuanceRepository(dsl); + var crypto = + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(root.resolve("custody")), Clock.systemUTC()); + var registry = + new AccountControlUiCoordination( + () -> { + coordinationCalls.incrementAndGet(); + throw new IllegalStateException("No physical Redis fixture in this negative proof"); + }, + new AcknowledgementRequirements(1, 1, 1000), + RedisScriptCatalog.fromContributions(List.of())); + var publicSource = + new AccountJwtJwksTrustedSource( + new AccountJwtJwksConfigMapClient(api), + trust, + signerRepository, + new AccountJwtJwksPublicationRepository(dsl, signerRepository), + manager); + var actors = + new AccountControlUiActorService( + operations, + authority, + signer, + registry, + publicSource, + fences, + manager, + Clock.systemUTC()); + service = + new AccountControlUiIssuanceService( + primary, + operations, + authority, + fences, + signer, + crypto, + registry, + actors, + manager, + Clock.systemUTC(), + CALLER); + } + + AccountControlUiIssuanceService.Request request(String secret) { + return new AccountControlUiIssuanceService.Request( + request, account.getEmail(), secret, tenant, callerContext); + } + + T tx(Supplier action) { + return transactions.execute(ignored -> action.get()); + } + + void assertNoIssuance() { + assertThat(dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isZero(); + assertThat(coordinationCalls).hasValue(0); + } + } + + private static FreshTenantCreatorEvidence testCreation(UUID account, UUID tenant) { + UUID request = UUID.randomUUID(), + operation = UUID.randomUUID(), + authorization = UUID.randomUUID(); + String key = "test-only-game-row-17"; + String digest = + GameTenantCreationDigest.requestDigest(NAMESPACE, request, key, "Test game", null); + var creation = + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + request, + operation, + digest, + tenant, + 17L, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); + String authorizationDigest = "sha256:" + "8".repeat(64); + return new FreshTenantCreatorEvidence( + 1, + creation, + account, + authorization, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, account, authorization, authorizationDigest)); + } + + private static void insertTestParty(DSLContext dsl, IndividualCreatorPartySource party) { + byte[] source = CreatorPartyEncoding.party(party); + dsl.execute( + "INSERT INTO account_individual_creator_party_sources" + + " (creator_party_id, account_uuid, verification_status, identity_version, policy_reference, policy_version," + + " verification_evidence_reference, verification_evidence_version, source_version, source_payload, source_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + source, + CreatorPartyEncoding.digest(source)); + } + + private static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary testBoundary( + String name) { + byte[] source = bytes("test-only-environment-observation/" + name); + return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + name, + "test-only-environment-owner", + "test-only-observation/" + name, + source, + HostedTermsEncoding.digest(source)); + } + + private static T externalFixture(Map values, UUID request) { + requireOutsideTransaction(); + return Objects.requireNonNull( + values.get(request), "Exact test-only external evidence required"); + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "External fixture observation must precede Account owner locks"); + } + } + + private static PeerScope withPeer(String uri) { + var attached = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + return new PeerScope(attached.attach(), attached); + } + + private record PeerScope(Context previous, Context attached) implements AutoCloseable { + @Override + public void close() { + attached.detach(previous); + } + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String hash(String value) { + char[] secret = value.toCharArray(); + var argon = Argon2Factory.create(); + try { + return argon.hash(2, 4096, 1, secret); + } finally { + argon.wipeArray(secret); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java new file mode 100644 index 0000000000..48d768676d --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java @@ -0,0 +1,331 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import de.mkammerer.argon2.Argon2Factory; +import java.time.LocalDateTime; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.mapper.AccountMapper; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.mapstruct.factory.Mappers; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual primary authentication, persisted canonical identity mapping, OTP repositories and + * PostgreSQL transactions/locks. Unused AccountService collaborators are absent, following the + * existing owner integration construction pattern. Secrets and Accounts are test-only fixtures; + * this is not creator-source, signer, protected caller, original Draft or runtime issuance proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountControlUiPrimaryAuthenticationPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + private static final String PASSWORD = "test-only-primary-password"; + private static final String OTP = "test-only-email-otp"; + + @Test + void passwordAuthenticatesPersistedCanonicalUuidAndInvalidOrLockedAccountDoesNotMutate() { + Context c = context(); + Account account = c.account("PASSWORD"); + String before = c.accountBytes(account.getAccountUuid()); + UUID authenticated = + c.tx( + () -> + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD) + .accountId()); + assertThat(authenticated).isEqualTo(account.getAccountUuid()); + assertThat(account.getAccountUuidSourceNumericId()).isEqualTo(account.getId()); + assertThat(c.accountBytes(account.getAccountUuid())).isEqualTo(before); + assertThatThrownBy( + () -> + c.tx( + () -> + c.primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "wrong-secret"))) + .isInstanceOf(AuthenticationException.class); + assertThat(c.accountBytes(account.getAccountUuid())).isEqualTo(before); + c.tx( + () -> { + Account locked = c.accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); + locked.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); + return c.accounts.save(locked); + }); + String locked = c.accountBytes(account.getAccountUuid()); + assertThatThrownBy( + () -> + c.tx( + () -> + c.primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), PASSWORD))) + .isInstanceOf(AuthenticationException.class); + assertThat(c.accountBytes(account.getAccountUuid())).isEqualTo(locked); + assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); + } + + @Test + void exactOtpConsumptionParticipatesInOwnerRollbackAndCannotBeReplayedAfterCommit() { + Context c = context(); + Account account = c.account("EMAIL_OTP"); + AccountEmailLoginChallenge original = c.challenge(account); + assertThatThrownBy( + () -> + c.tx( + () -> + c.primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "wrong-otp"))) + .isInstanceOf(AuthenticationException.class); + assertThat(c.challenges.findByAccountId(account.getId())).contains(original); + c.transaction.executeWithoutResult( + status -> { + assertThat( + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) + .accountId()) + .isEqualTo(account.getAccountUuid()); + assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); + status.setRollbackOnly(); + }); + assertThat(c.challenges.findByAccountId(account.getId())).contains(original); + assertThat( + c.tx( + () -> + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) + .accountId())) + .isEqualTo(account.getAccountUuid()); + assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); + assertThatThrownBy( + () -> + c.tx(() -> c.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), OTP))) + .isInstanceOf(AuthenticationException.class); + assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); + } + + @Test + void concurrentOtpAttemptsSerializeOnActualPostgresOwnerLockAndOnlyOneAuthenticates() + throws Exception { + Context c = context(); + Account account = c.account("EMAIL_OTP"); + c.challenge(account); + var firstAuthenticated = new CountDownLatch(1); + var secondEntered = new CountDownLatch(1); + var releaseFirst = new CountDownLatch(1); + var firstPid = new AtomicInteger(); + var secondPid = new AtomicInteger(); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> + c.tx( + () -> { + firstPid.set(c.pid()); + UUID actor = + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) + .accountId(); + firstAuthenticated.countDown(); + awaitLatch(releaseFirst); + return actor; + })); + awaitLatch(firstAuthenticated); + var second = + executor.submit( + () -> + c.tx( + () -> { + secondPid.set(c.pid()); + secondEntered.countDown(); + return c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) + .accountId(); + })); + awaitLatch(secondEntered); + awaitBlocked(c, secondPid.get(), firstPid.get()); + assertThat(first.isDone()).isFalse(); + assertThat(second.isDone()).isFalse(); + releaseFirst.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS)).isEqualTo(account.getAccountUuid()); + assertThatThrownBy(() -> second.get(10, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(AuthenticationException.class); + assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + + private static void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Expected primary-auth transaction boundary"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted primary-auth transaction boundary"); + } + } + + private static void awaitBlocked(Context c, int waitingPid, int blockerPid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + var observed = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT ? = ANY(pg_blocking_pids(?)) AS blocked", blockerPid, waitingPid), + "Exact PostgreSQL blocking identity readback required"); + if (Boolean.TRUE.equals(observed.get("blocked", Boolean.class))) { + return; + } + Thread.onSpinWait(); + } + throw new IllegalStateException( + "Second OTP attempt did not block on first primary-auth transaction"); + } + + private static Context context() { + String schema = "control_ui_primary_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(source); + var transaction = new TransactionTemplate(manager); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var accounts = new AccountRepository(dsl); + var challenges = new AccountEmailLoginChallengeRepository(dsl); + var primary = + new AccountServiceImpl( + accounts, + null, + null, + null, + challenges, + null, + null, + Mappers.getMapper(AccountMapper.class), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + manager); + return new Context(dsl, accounts, challenges, primary, transaction); + } + + private record Context( + DSLContext dsl, + AccountRepository accounts, + AccountEmailLoginChallengeRepository challenges, + AccountServiceImpl primary, + TransactionTemplate transaction) { + T tx(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + + Account account(String modes) { + return tx( + () -> { + Account account = new Account(); + String suffix = UUID.randomUUID().toString(); + account.setUsername("primary-" + suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash(hash(PASSWORD)); + account.setLoginAuthModes(modes); + return accounts.save(account); + }); + } + + AccountEmailLoginChallenge challenge(Account account) { + return tx( + () -> { + var challenge = new AccountEmailLoginChallenge(); + var now = LocalDateTime.now().withNano(0); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash(OTP)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); + } + + int pid() { + return Objects.requireNonNull( + dsl.fetchOne("SELECT pg_backend_pid() AS pid"), + "Exact owner transaction backend required") + .get("pid", Integer.class); + } + + String accountBytes(UUID account) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(a)::TEXT AS exact FROM accounts a WHERE account_uuid = ?", + account), + "Persisted canonical Account readback required") + .get("exact", String.class); + } + } + + private static String hash(String secret) { + char[] chars = secret.toCharArray(); + var argon = Argon2Factory.create(); + try { + return argon.hash(2, 4096, 1, chars); + } finally { + argon.wipeArray(chars); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java new file mode 100644 index 0000000000..41a8fb5d01 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java @@ -0,0 +1,106 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftSourceCompositionService; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CurrentnessEvidence; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.EnvironmentBoundCurrentness; +import org.junit.jupiter.api.Test; + +class AccountControlUiAuthorityTest { + @Test + void explicitTypedNoDeadlineReadbackPermitsExistingCompositionToContinue() { + var sources = mock(AccountDraftSourceCompositionService.class); + var existing = mock(AccountDraftSourceCompositionService.ExistingSources.class); + var hosted = mock(EnvironmentBoundCurrentness.class); + var terms = mock(CurrentnessEvidence.class); + var environment = mock(CapturedEnvironmentBoundary.class); + UUID tenant = UUID.randomUUID(); + when(sources.readExistingSources(environment, tenant)).thenReturn(existing); + when(existing.hostedTerms()).thenReturn(hosted); + when(hosted.terms()).thenReturn(terms); + when(terms.validUntil()).thenReturn(null); + when(terms.disclosedDeadline()).thenReturn(null); + // Stop at the next stage: this is not a fabricated successful source/provenance fixture. + when(existing.membership()) + .thenThrow(new IllegalStateException("membership-stage-test-sentinel")); + var authority = new AccountControlUiAuthority(sources); + assertThatThrownBy(() -> authority.capture(UUID.randomUUID(), tenant, environment)) + .hasMessage("membership-stage-test-sentinel"); + assertThatThrownBy(() -> authority.captureInitial(tenant, environment)) + .hasMessage("membership-stage-test-sentinel"); + } + + @Test + void bothCapturePathsDenyDeadlineQualifiedOwnerReadbackBeforeMembershipOrSourceCapture() { + // Explicit owner service doubles: this tests the enforcement boundary, not source provenance. + var sources = mock(AccountDraftSourceCompositionService.class); + var existing = mock(AccountDraftSourceCompositionService.ExistingSources.class); + var hosted = mock(EnvironmentBoundCurrentness.class); + var terms = mock(CurrentnessEvidence.class); + var environment = mock(CapturedEnvironmentBoundary.class); + UUID tenant = UUID.randomUUID(); + when(sources.readExistingSources(environment, tenant)).thenReturn(existing); + when(existing.hostedTerms()).thenReturn(hosted); + when(hosted.terms()).thenReturn(terms); + when(terms.validUntil()).thenReturn(Instant.parse("2099-01-01T00:00:00Z")); + var authority = new AccountControlUiAuthority(sources); + + assertThatThrownBy(() -> authority.capture(UUID.randomUUID(), tenant, environment)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Deadline-qualified"); + assertThatThrownBy(() -> authority.captureInitial(tenant, environment)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Deadline-qualified"); + verify(existing, never()).membership(); + verify(hosted, never()).sourceEvidence(); + } + + @Test + void absentTypedOwnerCurrentnessCannotMasqueradeAsNoDeadline() { + var sources = mock(AccountDraftSourceCompositionService.class); + var existing = mock(AccountDraftSourceCompositionService.ExistingSources.class); + var hosted = mock(EnvironmentBoundCurrentness.class); + var environment = mock(CapturedEnvironmentBoundary.class); + UUID tenant = UUID.randomUUID(); + when(sources.readExistingSources(environment, tenant)).thenReturn(existing); + when(existing.hostedTerms()).thenReturn(hosted); + var authority = new AccountControlUiAuthority(sources); + assertThatThrownBy(() -> authority.capture(UUID.randomUUID(), tenant, environment)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> authority.captureInitial(tenant, environment)) + .isInstanceOf(NullPointerException.class); + verify(existing, never()).membership(); + } + + @Test + void canonicalizationPreservesExactlyRepresentableNestedCounters() { + var bytes = + AccountControlUiAuthority.canonical( + Map.of("tuple", List.of(Map.of("counter", 42L), Map.of("counter", 9007199254740992L)))); + assertThat(new String(bytes, StandardCharsets.UTF_8)).contains("9007199254740992", "42"); + } + + @Test + void canonicalizationRejectsArithmeticChangeInsteadOfIssuingRoundedAuthority() { + for (long counter : new long[] {9007199254740993L, Long.MAX_VALUE}) { + assertThatThrownBy( + () -> + AccountControlUiAuthority.canonical( + Map.of("tuple", List.of(Map.of("counter", counter))))) + .isInstanceOf(IllegalArgumentException.class); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcMtlsTest.java new file mode 100644 index 0000000000..082228ebaf --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcMtlsTest.java @@ -0,0 +1,525 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +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.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.ByteString; +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.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountDraftCommitOrderReadServiceGrpc; +import net.firedevops.firemud.account.v1.HeldOriginalCommitOrderStatus; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderRequest; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderResponse; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadService; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical loopback mTLS proof for the Account held-COMMIT_ORDER gRPC handler boundary. */ +class AccountDraftCommitOrderReadGrpcMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String OTHER_NAMESPACE_WORLD_URI = + "spiffe://firemud/ns/other-test/sa/world-management-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @TempDir static Path tempDirectory; + + private static TestPki pki; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @Test + void exactSameNamespaceWorldPeerReachesHeldOwnerAndGetsExactHeldResponse() throws Exception { + DraftCommitOrderReadEvidence.Request request = validRequest(); + TestOnlyHeldOwner owner = new TestOnlyHeldOwner(); + try (TransportServer server = startServer(owner); + ClientTransport client = newClient(server.port(), pki.worldClient())) { + ReadHeldOriginalCommitOrderResponse response = + client.read(DraftCommitOrderReadGrpcCodec.toRequest(request)); + + assertThat(response).isEqualTo(DraftCommitOrderReadGrpcCodec.toHeldResponse(request)); + assertThat(response.getStatus()) + .isEqualTo(HeldOriginalCommitOrderStatus.HELD_ORIGINAL_COMMIT_ORDER_STATUS_HELD); + assertThat(server.handlerCalls()).hasValue(1); + assertThat(owner.reads()).hasValue(1); + assertThat(owner.peerUri().get()).isEqualTo(WORLD_URI); + verify(owner.service()).requireHeld(request); + } + } + + @Test + void trustedWrongWorkloadAndNamespaceAreDeniedBeforeOwnerReads() throws Exception { + DraftCommitOrderReadEvidence.Request request = validRequest(); + for (TestIdentity identity : List.of(pki.wrongWorkloadClient(), pki.otherNamespaceClient())) { + TestOnlyHeldOwner owner = new TestOnlyHeldOwner(); + try (TransportServer server = startServer(owner); + ClientTransport client = newClient(server.port(), identity)) { + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> client.read(DraftCommitOrderReadGrpcCodec.toRequest(request))); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(1); + assertThat(owner.reads()).as(identity.alias()).hasValue(0); + verifyNoInteractions(owner.service()); + } + } + } + + @Test + void missingClientCertificateIsRejectedBeforeHandlerOrOwnerRead() throws Exception { + TestOnlyHeldOwner owner = new TestOnlyHeldOwner(); + try (TransportServer server = startServer(owner); + ClientTransport client = newClientWithoutIdentity(server.port())) { + assertThatThrownBy(() -> client.read(DraftCommitOrderReadGrpcCodec.toRequest(validRequest()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + + assertThat(server.handlerCalls()).hasValue(0); + assertThat(owner.reads()).hasValue(0); + verifyNoInteractions(owner.service()); + } + } + + @Test + void missingOrMalformedBindingFromExactWorldPeerFailsParsingWithoutHeldResponse() + throws Exception { + TestOnlyHeldOwner owner = new TestOnlyHeldOwner(); + try (TransportServer server = startServer(owner); + ClientTransport client = newClient(server.port(), pki.worldClient())) { + for (ReadHeldOriginalCommitOrderRequest malformed : malformedRequests()) { + assertStatus(Status.Code.INVALID_ARGUMENT, () -> client.read(malformed)); + } + + assertThat(server.handlerCalls()).hasValue(2); + assertThat(owner.reads()).hasValue(0); + verifyNoInteractions(owner.service()); + } + } + + private static DraftCommitOrderReadEvidence.Request validRequest() { + return AccountDraftCommitOrderReadServiceTest.request( + AccountDraftCommitOrderReadServiceTest.binding(1)); + } + + private static List malformedRequests() { + String readRequestId = "33333333-3333-4333-8333-333333333333"; + ReadHeldOriginalCommitOrderRequest missingBinding = + ReadHeldOriginalCommitOrderRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setReadRequestId(readRequestId) + .build(); + ReadHeldOriginalCommitOrderRequest malformedBinding = + missingBinding.toBuilder() + .setOriginalAccountBinding(ByteString.copyFrom(new byte[] {1})) + .build(); + return List.of(missingBinding, malformedBinding); + } + + private static void assertStatus( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable operation) { + assertThatThrownBy(operation) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(expected); + } + + private static TransportServer startServer(TestOnlyHeldOwner owner) throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + AccountDraftCommitOrderReadGrpcService service = + new AccountDraftCommitOrderReadGrpcService(owner.service(), NAMESPACE); + ServerInterceptor countHandlerCalls = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + handlerCalls.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.accountServer().privateKey(), pki.accountServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHandlerCalls, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new TransportServer(server, handlerCalls); + } + + private static ClientTransport newClient(int port, TestIdentity identity) throws Exception { + return newClient(port, pki.clientProperties(tempDirectory, identity)); + } + + private static ClientTransport newClientWithoutIdentity(int port) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCaCert(pki.caCertificatePem().toString()); + return newClient(port, tls); + } + + private static ClientTransport newClient(int port, CommonGrpcClientProperties tls) + throws Exception { + ManagedChannel channel = + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false); + return new ClientTransport(channel); + } + + /** Mockito owner used only to prove the production handler's transport and caller boundary. */ + private static final class TestOnlyHeldOwner { + private final AccountDraftCommitOrderReadService service = + mock(AccountDraftCommitOrderReadService.class); + private final AtomicInteger reads = new AtomicInteger(); + private final AtomicReference peerUri = new AtomicReference<>(); + + private TestOnlyHeldOwner() { + doAnswer( + invocation -> { + reads.incrementAndGet(); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + peerUri.set(peer == null ? null : peer.uri()); + return null; + }) + .when(service) + .requireHeld(any(DraftCommitOrderReadEvidence.Request.class)); + } + + private AccountDraftCommitOrderReadService service() { + return service; + } + + private AtomicInteger reads() { + return reads; + } + + private AtomicReference peerUri() { + return peerUri; + } + } + + private record TransportServer(Server server, AtomicInteger handlerCalls) + implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private AccountDraftCommitOrderReadServiceGrpc.AccountDraftCommitOrderReadServiceBlockingStub + stub() { + return AccountDraftCommitOrderReadServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS); + } + + private ReadHeldOriginalCommitOrderResponse read(ReadHeldOriginalCommitOrderRequest request) { + return stub().readHeldOriginalCommitOrder(request); + } + + @Override + public void close() throws InterruptedException { + assertThat(channel.shutdownNow()).isNotNull(); + if (!channel.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC client did not terminate"); + } + } + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + Path caCertificatePem, + TestIdentity accountServer, + TestIdentity worldClient, + TestIdentity wrongWorkloadClient, + TestIdentity otherNamespaceClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD Account COMMIT_ORDER test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + caFile, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "world-client", WORLD_URI, false), + issueIdentity( + directory, caStore, caFile, "wrong-workload-client", WRONG_WORKLOAD_URI, false), + issueIdentity( + directory, + caStore, + caFile, + "other-namespace-client", + OTHER_NAMESPACE_WORLD_URI, + false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve(identity.alias() + ".crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve(identity.alias() + ".key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(caFile.toString()); + tls.setPlaintext(false); + return tls; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String extendedKeyUsage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + ArrayList command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcServiceTest.java new file mode 100644 index 0000000000..37abaf28a7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcServiceTest.java @@ -0,0 +1,145 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import net.firedevops.firemud.account.v1.HeldOriginalCommitOrderStatus; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderRequest; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderResponse; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadService; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.FenceSnapshot; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; + +class AccountDraftCommitOrderReadGrpcServiceTest { + @Test + void authenticatesExactWorldPeerBeforeDecodingOrOwnerAccess() { + var repository = mock(DraftAuthorizationFenceRepository.class); + var manager = mock(PlatformTransactionManager.class); + var owner = new AccountDraftCommitOrderReadService(repository, manager, "test"); + var service = new AccountDraftCommitOrderReadGrpcService(owner, "test"); + var malformed = ReadHeldOriginalCommitOrderRequest.newBuilder().setSchemaVersion(-1).build(); + + Collector missing = new Collector(); + service.readHeldOriginalCommitOrder(malformed, missing); + assertThat(missing.errorStatus.getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + + for (String identity : + new String[] { + "spiffe://firemud/ns/test/sa/account-service", + "spiffe://firemud/ns/other/sa/world-management-service" + }) { + Collector wrong = new Collector(); + asPeer(identity, () -> service.readHeldOriginalCommitOrder(malformed, wrong)); + assertThat(wrong.errorStatus.getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + verifyNoInteractions(repository, manager); + } + + @Test + void authenticatedWorldPeerGetsHeldOnlyForExactPendingCommitOrder() { + var repository = mock(DraftAuthorizationFenceRepository.class); + var manager = mock(PlatformTransactionManager.class); + var transactionStatus = mock(TransactionStatus.class); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + var binding = AccountDraftCommitOrderReadServiceTest.binding(1); + when(repository.readOriginalBinding(binding.operationId())).thenReturn(Optional.of(binding)); + when(repository.read(binding)) + .thenReturn(new FenceSnapshot(Ordering.COMMIT_ORDER, binding.canonicalBytes(), null, null)); + when(repository.readSettlement(binding)).thenReturn(Settlement.PENDING); + var owner = new AccountDraftCommitOrderReadService(repository, manager, "test"); + var service = new AccountDraftCommitOrderReadGrpcService(owner, "test"); + var request = AccountDraftCommitOrderReadServiceTest.request(binding); + Collector result = new Collector(); + + asPeer( + "spiffe://firemud/ns/test/sa/world-management-service", + () -> + service.readHeldOriginalCommitOrder( + DraftCommitOrderReadGrpcCodec.toRequest(request), result)); + + assertThat(result.errorStatus).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.value.getStatus()) + .isEqualTo(HeldOriginalCommitOrderStatus.HELD_ORIGINAL_COMMIT_ORDER_STATUS_HELD); + assertThat(result.value.getOriginalAccountBinding().toByteArray()) + .containsExactly(binding.canonicalBytes()); + } + + @Test + void invalidCanonicalRequestAndUnheldOperationNeverProducePositiveResponse() { + var repository = mock(DraftAuthorizationFenceRepository.class); + var manager = mock(PlatformTransactionManager.class); + when(manager.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); + var service = + new AccountDraftCommitOrderReadGrpcService( + new AccountDraftCommitOrderReadService(repository, manager, "test"), "test"); + Collector malformed = new Collector(); + asPeer( + "spiffe://firemud/ns/test/sa/world-management-service", + () -> + service.readHeldOriginalCommitOrder( + ReadHeldOriginalCommitOrderRequest.getDefaultInstance(), malformed)); + assertThat(malformed.errorStatus.getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + + var binding = AccountDraftCommitOrderReadServiceTest.binding(1); + when(repository.readOriginalBinding(binding.operationId())).thenReturn(Optional.empty()); + Collector absent = new Collector(); + asPeer( + "spiffe://firemud/ns/test/sa/world-management-service", + () -> + service.readHeldOriginalCommitOrder( + DraftCommitOrderReadGrpcCodec.toRequest( + AccountDraftCommitOrderReadServiceTest.request(binding)), + absent)); + assertThat(absent.errorStatus.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(absent.value).isNull(); + } + + private static void asPeer(String uri, Runnable call) { + var peer = GrpcPeerIdentity.parseUri(uri).orElseThrow(); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var previous = context.attach(); + try { + call.run(); + } finally { + context.detach(previous); + } + } + + private static final class Collector + implements StreamObserver { + private ReadHeldOriginalCommitOrderResponse value; + private Status errorStatus; + private boolean completed; + + @Override + public void onNext(ReadHeldOriginalCommitOrderResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + errorStatus = Status.fromThrowable(failure); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadServiceTest.java new file mode 100644 index 0000000000..3851be893a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadServiceTest.java @@ -0,0 +1,268 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +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 io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadService; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.FenceSnapshot; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountDraftCommitOrderReadServiceTest { + private final DraftAuthorizationFenceRepository repository = + mock(DraftAuthorizationFenceRepository.class); + private final PlatformTransactionManager manager = mock(PlatformTransactionManager.class); + private final TransactionStatus transactionStatus = mock(TransactionStatus.class); + private final AccountDraftCommitOrderReadService service = + new AccountDraftCommitOrderReadService(repository, manager, "test"); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void acceptsOnlyExactHeldOriginalCommitOrderInOwnedWritableReadCommittedTransaction() { + var binding = binding(1); + var request = request(binding); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.readOriginalBinding(binding.operationId())).thenReturn(Optional.of(binding)); + when(repository.read(binding)) + .thenReturn(new FenceSnapshot(Ordering.COMMIT_ORDER, binding.canonicalBytes(), null, null)); + when(repository.readSettlement(binding)).thenReturn(Settlement.PENDING); + + asWorld(() -> service.requireHeld(request)); + + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(manager).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(manager).commit(transactionStatus); + verify(repository).readOriginalBinding(binding.operationId()); + verify(repository).read(binding); + verify(repository).readSettlement(binding); + } + + @Test + void deniesAbsentChangedReservedRevokedAndSettledOperationsWithoutChangingOwnerState() { + var original = binding(1); + var changed = binding(2); + var absentRepository = mock(DraftAuthorizationFenceRepository.class); + var absentManager = mock(PlatformTransactionManager.class); + when(absentManager.getTransaction(any())).thenReturn(transactionStatus); + when(absentRepository.readOriginalBinding(original.operationId())).thenReturn(Optional.empty()); + assertDenied( + new AccountDraftCommitOrderReadService(absentRepository, absentManager, "test"), + request(original)); + verify(absentRepository, never()).read(any()); + + var changedRepository = mock(DraftAuthorizationFenceRepository.class); + var changedManager = mock(PlatformTransactionManager.class); + when(changedManager.getTransaction(any())).thenReturn(transactionStatus); + when(changedRepository.readOriginalBinding(changed.operationId())) + .thenReturn(Optional.of(original)); + assertDenied( + new AccountDraftCommitOrderReadService(changedRepository, changedManager, "test"), + request(changed)); + verify(changedRepository, never()).read(any()); + + for (Ordering ordering : List.of(Ordering.RESERVED, Ordering.REVOKE_ORDER)) { + var fencedRepository = mock(DraftAuthorizationFenceRepository.class); + var fencedManager = mock(PlatformTransactionManager.class); + when(fencedManager.getTransaction(any())).thenReturn(transactionStatus); + when(fencedRepository.readOriginalBinding(original.operationId())) + .thenReturn(Optional.of(original)); + when(fencedRepository.read(original)) + .thenReturn( + new FenceSnapshot(ordering, original.canonicalBytes(), null, OffsetDateTime.now())); + assertDenied( + new AccountDraftCommitOrderReadService(fencedRepository, fencedManager, "test"), + request(original)); + verify(fencedRepository, never()).readSettlement(original); + } + + for (Settlement settlement : List.of(Settlement.COMMITTED, Settlement.FAILED_NONPUBLICATION)) { + var settledRepository = mock(DraftAuthorizationFenceRepository.class); + var settledManager = mock(PlatformTransactionManager.class); + when(settledManager.getTransaction(any())).thenReturn(transactionStatus); + when(settledRepository.readOriginalBinding(original.operationId())) + .thenReturn(Optional.of(original)); + when(settledRepository.read(original)) + .thenReturn( + new FenceSnapshot( + Ordering.COMMIT_ORDER, original.canonicalBytes(), null, OffsetDateTime.now())); + when(settledRepository.readSettlement(original)).thenReturn(settlement); + assertDenied( + new AccountDraftCommitOrderReadService(settledRepository, settledManager, "test"), + request(original)); + } + + verifyNoInteractions(repository); + } + + @Test + void rejectsMissingWrongWorkloadAndAmbientTransactionBeforeRepositoryOrOwnerTransaction() { + var binding = binding(1); + var request = request(binding); + assertStatus(Status.Code.UNAUTHENTICATED, () -> service.requireHeld(request)); + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "spiffe://firemud/ns/test/sa/account-service", () -> service.requireHeld(request))); + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "spiffe://firemud/ns/other/sa/world-management-service", + () -> service.requireHeld(request))); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> asWorld(() -> service.requireHeld(request))); + verifyNoInteractions(repository, manager); + } + + @Test + void rejectsTargetNamespaceSubstitutionAndUnavailableStorageFailClosed() { + var binding = binding(1); + var wrongNamespace = + new DraftCommitOrderReadEvidence.Request( + 1, + "other", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + binding.canonicalBytes()); + assertStatus( + Status.Code.PERMISSION_DENIED, () -> asWorld(() -> service.requireHeld(wrongNamespace))); + verifyNoInteractions(repository, manager); + + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.readOriginalBinding(binding.operationId())) + .thenThrow(new org.jooq.exception.DataAccessException("offline")); + assertStatus( + Status.Code.UNAVAILABLE, () -> asWorld(() -> service.requireHeld(request(binding)))); + } + + private static void assertDenied( + AccountDraftCommitOrderReadService target, DraftCommitOrderReadEvidence.Request request) { + assertStatus(Status.Code.FAILED_PRECONDITION, () -> asWorld(() -> target.requireHeld(request))); + } + + private static void assertStatus( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable call) { + assertThatThrownBy(call) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(expected); + } + + private static void asWorld(Runnable call) { + asPeer("spiffe://firemud/ns/test/sa/world-management-service", call); + } + + private static void asPeer(String uri, Runnable call) { + var peer = GrpcPeerIdentity.parseUri(uri).orElseThrow(); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var previous = context.attach(); + try { + call.run(); + } finally { + context.detach(previous); + } + } + + static DraftCommitOrderReadEvidence.Request request(DraftAuthorizationFenceBinding binding) { + return new DraftCommitOrderReadEvidence.Request( + 1, + "test", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + binding.canonicalBytes()); + } + + static DraftAuthorizationFenceBinding binding(long sourceGeneration) { + UUID tenant = uuid("11111111-1111-4111-8111-111111111111"); + UUID version = uuid("22222222-2222-4222-8222-222222222222"); + UUID request = uuid("44444444-4444-4444-8444-444444444444"); + UUID commit = uuid("55555555-5555-4555-8555-555555555555"); + DraftCommitBinding draft = + DraftCommitBinding.create( + new TargetProof(tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request, + commit, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + tenant, + version, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + null, + Long.toString(sourceGeneration), + null, + null, + new byte[] {1}))); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java new file mode 100644 index 0000000000..be9ea0bbf7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java @@ -0,0 +1,237 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.AcknowledgementRequirements; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit Redis/TLS/ACL/WAITAOF service doubles, not physical Redis or mTLS proof. */ +class AccountControlUiCoordinationTest { + private static final String HASH = "a".repeat(64); + private static final long EXPIRY = 1791467100000L; + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactRetryMetadataDeclaresPhysicalReassertionAsMutatingSuccess() { + var descriptor = AccountControlUiRegistryContract.descriptor(); + assertThat(descriptor.outcomes()) + .contains( + new RedisScriptDescriptor.OutcomeSpec( + "EXACT_REASSERTED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING)); + } + + @Test + void exactRetryStillRequiresSameConnectionWriteThenWaitAofThenExactReadback() throws Exception { + Fixture f = new Fixture(); + byte[] pending = record("pending"); + doReturn(0L) + .when(f.commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + when(f.commands.get(any(byte[].class))).thenReturn(pending); + var receipt = f.client.registerPending(HASH, pending, EXPIRY); + assertThat(receipt.tokenHash).isEqualTo(HASH); + assertThat(receipt.recordDigest).isEqualTo(AccountControlUiIssuanceRepository.hash(pending)); + var order = inOrder(f.commands); + order.verify(f.commands).aclWhoami(); + order.verify(f.commands).scriptLoad(any(byte[].class)); + order + .verify(f.commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + order.verify(f.commands).dispatch(any(), any(), any()); + order.verify(f.commands).pexpiretime(any(byte[].class)); + order.verify(f.commands).get(any(byte[].class)); + } + + @Test + void activeReadRequiresOriginalPhysicalExpiryAndNeverRepairs() throws Exception { + Fixture f = new Fixture(); + when(f.commands.get(any(byte[].class))).thenReturn(record("active")); + assertThat(f.client.readActive(HASH)).isEqualTo(record("active")); + for (Long invalid : new Long[] {null, -1L, -2L, EXPIRY + 1}) { + when(f.commands.pexpiretime(any(byte[].class))).thenReturn(invalid); + assertThatThrownBy(() -> f.client.readActive(HASH)).isInstanceOf(IllegalStateException.class); + } + } + + @Test + void recoveryRevocationKeepsOriginalFieldsAndRequiresDurableExactReadback() throws Exception { + for (String prior : List.of("pending", "active", "revoked")) { + Fixture f = new Fixture(); + var original = revoking(); + byte[] revoked = AccountControlUiIssuanceRepository.revokedRegistry(original); + var fields = AccountControlUiIssuanceRepository.object(revoked); + assertThat(fields.get("state")).isEqualTo("revoked"); + assertThat(fields.get("registryVersion")).isEqualTo(3); + assertThat(((Number) fields.get("exp")).longValue()).isEqualTo(EXPIRY / 1000); + when(f.commands.get(any(byte[].class))).thenReturn(record(prior)).thenReturn(revoked); + if (prior.equals("revoked")) { + doReturn(0L) + .when(f.commands) + .evalsha( + anyString(), + eq(ScriptOutputType.INTEGER), + any(byte[][].class), + any(byte[][].class)); + } + var receipt = f.client.revoke(original); + assertThat(receipt.recordDigest).isEqualTo(AccountControlUiIssuanceRepository.hash(revoked)); + assertThat(receipt.expiryMillis).isEqualTo(EXPIRY); + var order = inOrder(f.commands); + order.verify(f.commands).get(any(byte[].class)); + order.verify(f.commands).pexpiretime(any(byte[].class)); + order.verify(f.commands).scriptLoad(any(byte[].class)); + order + .verify(f.commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + order.verify(f.commands).dispatch(any(), any(), any()); + order.verify(f.commands).pexpiretime(any(byte[].class)); + order.verify(f.commands).get(any(byte[].class)); + } + } + + @Test + void missingChangedExpiredOrUnavailableRevocationNeverCountsAsSuccess() throws Exception { + for (byte[] observed : new byte[][] {null, record("other")}) { + Fixture f = new Fixture(); + when(f.commands.get(any(byte[].class))).thenReturn(observed); + assertThatThrownBy(() -> f.client.revoke(revoking())) + .isInstanceOf(IllegalStateException.class); + } + Fixture f = new Fixture(); + when(f.commands.get(any(byte[].class))).thenReturn(record("active")); + when(f.commands.pexpiretime(any(byte[].class))).thenReturn(-2L); + assertThatThrownBy(() -> f.client.revoke(revoking())).isInstanceOf(IllegalStateException.class); + when(f.commands.pexpiretime(any(byte[].class))).thenReturn(EXPIRY); + doReturn(-4L) + .when(f.commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + assertThatThrownBy(() -> f.client.revoke(revoking())).isInstanceOf(IllegalStateException.class); + } + + private static AccountControlUiIssuanceRepository.Stored revoking() { + // Explicit owner-record double only; not a committed producer or physical owner transaction. + Record row = mock(Record.class); + when(row.get("status", String.class)).thenReturn("REVOKING"); + when(row.get("token_hash", String.class)).thenReturn(HASH); + when(row.get("pending_registry", byte[].class)).thenReturn(record("pending")); + when(row.get("active_registry", byte[].class)).thenReturn(record("active")); + when(row.get("issued_at_epoch_second", Long.class)).thenReturn(EXPIRY / 1000 - 300); + when(row.get("expires_at_epoch_second", Long.class)).thenReturn(EXPIRY / 1000); + when(row.get("recovery_expires_at", OffsetDateTime.class)) + .thenReturn( + OffsetDateTime.ofInstant(Instant.ofEpochMilli(EXPIRY - 240000), ZoneOffset.UTC)); + return new AccountControlUiIssuanceRepository.Stored(row); + } + + @Test + void wrongRoleMissingRecordReconnectSqlAndAcknowledgementShortfallDeny() throws Exception { + Fixture f = new Fixture(); + when(f.commands.aclWhoami()).thenReturn("game_session_coord_app"); + assertThatThrownBy(() -> f.client.readActive(HASH)).isInstanceOf(IllegalStateException.class); + when(f.commands.aclWhoami()).thenReturn("account_coord_app"); + when(f.commands.get(any(byte[].class))).thenReturn(null); + assertThatThrownBy(() -> f.client.readActive(HASH)).isInstanceOf(IllegalStateException.class); + when(f.connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(true).build()); + assertThatThrownBy(() -> f.client.readActive(HASH)).isInstanceOf(IllegalStateException.class); + when(f.connection.getOptions()) + .thenReturn(ClientOptions.builder().autoReconnect(false).build()); + doReturn(List.of(1L, 0L)).when(f.commands).dispatch(any(), any(), any()); + assertThatThrownBy(() -> f.client.registerPending(HASH, record("pending"), EXPIRY)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> f.client.readActive(HASH)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SQL locks"); + } + + private static byte[] record(String state) { + // A service-double observation only, never an authenticated actor or canonical owner bundle. + return AccountControlUiAuthority.canonical( + Map.of( + "schemaVersion", + 1, + "registryVersion", + state.equals("active") ? 2 : state.equals("revoked") ? 3 : 1, + "profile", + "control-ui", + "type", + "control-ui", + "audience", + "control-ui", + "issuer", + "firemud-account-service", + "tokenHash", + HASH, + "state", + state, + "exp", + EXPIRY / 1000)); + } + + private static final class Fixture { + @SuppressWarnings("unchecked") + final StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + + @SuppressWarnings("unchecked") + final RedisCommands commands = mock(RedisCommands.class); + + final RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + final AccountControlUiCoordination client; + + Fixture() throws Exception { + var descriptor = AccountControlUiRegistryContract.descriptor(); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()) + .thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn("account_coord_app"); + when(catalog.require(AccountControlUiRegistryContract.SCRIPT_ID)).thenReturn(descriptor); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer( + invocation -> + AccountControlUiCoordination.digest("SHA-1", invocation.getArgument(0))); + doReturn(1L) + .when(commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + doReturn(List.of(1L, 1L)).when(commands).dispatch(any(), any(), any()); + when(commands.pexpiretime(any(byte[].class))).thenReturn(EXPIRY); + client = + new AccountControlUiCoordination( + () -> connection, new AcknowledgementRequirements(1, 1, 1000), catalog); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java new file mode 100644 index 0000000000..1f46b1d20c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java @@ -0,0 +1,556 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +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.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Exercises the real workflow orchestration with explicitly synthetic owner, storage, signer, + * registry, transaction, and peer doubles. These definitions prove call ordering and denial only; + * they do not prove real Account authority, SQL durability, signer custody, mTLS, or Redis state. + */ +class AccountControlUiIssuanceWorkflowTest { + private static final Instant NOW = Instant.parse("2026-10-08T11:00:00Z"); + private static final String ISSUER = "spiffe://firemud/ns/firemud/sa/logging-admin-service"; + private static final String OTHER = "spiffe://firemud/ns/firemud/sa/game-design-service"; + + @AfterEach + void clearContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void primaryDenialCommitsAccountingBeforeThrowingAndNeverStartsIssuancePreparation() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + var source = mock(AccountControlUiAuthority.Snapshot.class); + when(source.sources()).thenReturn(java.util.List.of()); + when(fixture.authority.captureInitial(fixture.tenant, fixture.environment)).thenReturn(source); + var denial = new AuthenticationException("AUTH_INVALID_CREDENTIALS", "Invalid credentials"); + when(fixture.primary.authenticateControlUiPrimaryIdentity( + "creator@example.test", "test-only-secret")) + .thenThrow(denial); + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(AuthenticationException.class) + .hasMessage(denial.getMessage()) + .satisfies( + error -> + assertThat(((AuthenticationException) error).getCode()) + .isEqualTo(denial.getCode())); + } + var order = inOrder(fixture.primary, fixture.transactions); + order + .verify(fixture.primary) + .authenticateControlUiPrimaryIdentity("creator@example.test", "test-only-secret"); + order.verify(fixture.transactions).commit(any()); + verify(fixture.transactions, never()).rollback(any()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + verifyNoInteractions(fixture.signers, fixture.cryptography, fixture.registry, fixture.actors); + verify(fixture.operations, never()) + .prepare(any(), anyString(), any(), anyString(), anyString(), any(), any(), any(), any()); + } + + @Test + void missingOrWrongProtectedPeerDeniesBeforeOwnerLookup() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + var request = fixture.request(fixture.tenant, fixture.context, "test-only-secret"); + + assertThatThrownBy(() -> fixture.service().issue(request, fixture.environment)) + .isInstanceOf(IllegalStateException.class); + try (var ignored = fixture.withPeer(OTHER)) { + assertThatThrownBy(() -> fixture.service().issue(request, fixture.environment)) + .isInstanceOf(IllegalStateException.class); + } + + verifyNoInteractions( + fixture.operations, + fixture.authority, + fixture.fences, + fixture.primary, + fixture.signers, + fixture.registry, + fixture.cryptography, + fixture.actors); + } + + @Test + void changedDigestTenantOrCallerContextConflictsWithoutTerminalizingOriginal() { + for (int changed = 0; changed < 5; changed++) { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + fixture.existing(changed == 4 ? OTHER : ISSUER); + var request = + switch (changed) { + case 0 -> fixture.request(fixture.tenant, fixture.context, "different-secret"); + case 1 -> fixture.request(UUID.randomUUID(), fixture.context, "test-only-secret"); + case 2 -> fixture.request(fixture.tenant, UUID.randomUUID(), "test-only-secret"); + default -> fixture.request(fixture.tenant, fixture.context, "test-only-secret"); + }; + if (changed == 0 || changed == 3) { + when(fixture.cryptography.requestDigest(anyString(), any(byte[].class))) + .thenReturn("changed-request-digest"); + } + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy(() -> fixture.service().issue(request, fixture.environment)) + .isInstanceOf(IllegalArgumentException.class); + } + verify(fixture.operations, never()).beginRecoveryFailure(any()); + verifyNoInteractions(fixture.registry, fixture.primary, fixture.signers); + } + } + + @Test + void currentSourceUnavailabilityDeniesWithoutMarkingOriginalTerminal() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + var original = fixture.existing(); + when(fixture.authority.capture(original.accountId, original.tenantId, fixture.environment)) + .thenThrow(new IllegalStateException("test-only source unavailable")); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(IllegalStateException.class); + } + + verify(fixture.operations, never()).beginRecoveryFailure(any()); + verifyNoInteractions(fixture.registry, fixture.primary); + } + + @Test + void committedRecoveryReturnsTheExactOriginalCredentialWithoutPrimaryAuthenticationOrSigning() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + byte[] exactCredential = "test-only-original-compact-jwt".getBytes(StandardCharsets.US_ASCII); + String tokenHash = AccountControlUiIssuanceRepository.hash(exactCredential); + var original = fixture.useOwnerRepository(tokenHash); + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + when(snapshot.evidence()).thenReturn(new byte[] {1}); + when(snapshot.sources()).thenReturn(java.util.List.of()); + when(fixture.authority.capture(fixture.account, fixture.tenant, fixture.environment)) + .thenReturn(snapshot); + when(fixture.signers.requireOriginal(any(byte[].class))) + .thenReturn(mock(AccountControlUiSignerOwner.Capture.class)); + var binding = fixture.envelopeBinding(original, tokenHash); + var envelope = new AccountControlUiIssuanceRepository.Envelope(new byte[] {9}, binding); + doAnswer(call -> envelope).when(fixture.operations).envelope(any()); + byte[] expectedCredential = exactCredential.clone(); + when(fixture.cryptography.open(any(byte[].class), any(byte[].class), any(Instant.class))) + .thenReturn(exactCredential); + var actor = mock(AccountControlUiActorService.AuthenticatedActor.class); + when(actor.accountId()).thenReturn(fixture.account); + when(actor.issuanceOperationId()).thenReturn(fixture.operationId); + when(fixture.actors.authenticate( + "test-only-original-compact-jwt", fixture.tenant, fixture.environment)) + .thenReturn(actor); + + try (var ignored = fixture.withPeer(ISSUER)) { + try (var issued = + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) { + org.assertj.core.api.Assertions.assertThat(issued.compactBytes()) + .containsExactly(expectedCredential); + org.assertj.core.api.Assertions.assertThat(issued.expiresAt()) + .isEqualTo(NOW.plusSeconds(300)); + } + } + org.assertj.core.api.Assertions.assertThat(exactCredential).containsOnly((byte) 0); + + verify(fixture.registry).activate(any(AccountControlUiIssuanceRepository.Committed.class)); + verify(fixture.primary, never()).authenticateControlUiPrimaryIdentity(anyString(), anyString()); + verify(fixture.signers, never()).sign(any(), any(), any()); + } + + @Test + void unavailableActiveRegistryReadbackDeniesWithoutTerminalizingCommittedOriginal() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + byte[] credential = "test-only-token".getBytes(StandardCharsets.US_ASCII); + String tokenHash = AccountControlUiIssuanceRepository.hash(credential); + var original = fixture.useOwnerRepository(tokenHash); + fixture.recoveryInputs(); + var envelope = + new AccountControlUiIssuanceRepository.Envelope( + new byte[] {9}, fixture.envelopeBinding(original, tokenHash)); + doAnswer(call -> envelope).when(fixture.operations).envelope(any()); + when(fixture.cryptography.open(any(byte[].class), any(byte[].class), any(Instant.class))) + .thenReturn(credential); + when(fixture.actors.authenticate(anyString(), any(), any())) + .thenThrow(new IllegalStateException("test-only active registry unavailable")); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(IllegalStateException.class); + } + + verify(fixture.operations, never()).beginRecoveryFailure(any()); + verify(fixture.registry).activate(any(AccountControlUiIssuanceRepository.Committed.class)); + org.assertj.core.api.Assertions.assertThat(original.status).isEqualTo("COMMITTED"); + } + + @Test + void missingOriginalEnvelopeCreatesRevokingIntentAndDoesNotClaimRevocationOnRegistryFailure() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + var original = fixture.useOwnerRepository("unused-token-hash"); + fixture.recoveryInputs(); + doAnswer(call -> null).when(fixture.operations).envelope(any()); + var revoking = fixture.stored("REVOKING", original.recoveryExpiry, original.tokenHash); + doAnswer(call -> revoking) + .when(fixture.operations) + .beginRecoveryFailure(argThat(actual -> sameOriginalRecord(original, actual))); + when(fixture.registry.revoke(revoking)) + .thenThrow(new IllegalStateException("test-only Coordination unavailable")); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(IllegalStateException.class); + } + + ArgumentCaptor originalCaptor = + ArgumentCaptor.forClass(AccountControlUiIssuanceRepository.Stored.class); + verify(fixture.operations).beginRecoveryFailure(originalCaptor.capture()); + assertThat(sameOriginalRecord(original, originalCaptor.getValue())).isTrue(); + verify(fixture.registry) + .revoke( + argThat( + actual -> + "REVOKING".equals(actual.status) + && original.tokenHash.equals(actual.tokenHash) + && original.operationId.equals(actual.operationId))); + verify(fixture.operations, never()).finishRecoveryFailure(any(), any()); + } + + @Test + void expiredOriginalPersistsRevokingIntentBeforeUnavailableRegistryAndNeverReturnsCredential() { + Fixture fixture = new Fixture(NOW.minusSeconds(1)); + var original = fixture.existing(); + var revoking = fixture.stored("REVOKING", original.recoveryExpiry, original.tokenHash); + when(fixture.operations.beginRecoveryFailure(original)).thenReturn(revoking); + when(fixture.registry.revoke(revoking)) + .thenThrow(new IllegalStateException("test-only Coordination unavailable")); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(IllegalStateException.class); + } + + verify(fixture.operations).beginRecoveryFailure(original); + verify(fixture.registry).revoke(revoking); + verify(fixture.operations, never()).finishRecoveryFailure(any(), any()); + verifyNoInteractions(fixture.primary, fixture.signers); + verify(fixture.cryptography, never()) + .open(any(byte[].class), any(byte[].class), any(Instant.class)); + verify(fixture.cryptography, never()) + .seal(any(byte[].class), any(byte[].class), any(Instant.class)); + } + + private static boolean sameOriginalRecord( + AccountControlUiIssuanceRepository.Stored expected, + AccountControlUiIssuanceRepository.Stored actual) { + return actual != null + && expected.requestId.equals(actual.requestId) + && expected.operationId.equals(actual.operationId) + && expected.jti.equals(actual.jti) + && expected.accountId.equals(actual.accountId) + && expected.tenantId.equals(actual.tenantId) + && expected.callerContextId.equals(actual.callerContextId) + && expected.caller.equals(actual.caller) + && expected.requestMacKeyId.equals(actual.requestMacKeyId) + && expected.requestDigest.equals(actual.requestDigest) + && expected.status.equals(actual.status) + && expected.tokenHash.equals(actual.tokenHash) + && java.util.Arrays.equals(expected.claims, actual.claims) + && java.util.Arrays.equals(expected.sources, actual.sources) + && java.util.Arrays.equals(expected.bundle, actual.bundle) + && java.util.Arrays.equals(expected.signerReceipt, actual.signerReceipt) + && java.util.Arrays.equals(expected.pendingRegistry, actual.pendingRegistry) + && java.util.Arrays.equals(expected.activeRegistry, actual.activeRegistry) + && expected.issuedAt.equals(actual.issuedAt) + && expected.expiresAt.equals(actual.expiresAt) + && expected.recoveryExpiry.equals(actual.recoveryExpiry); + } + + private static final class Fixture { + final UUID requestId = UUID.randomUUID(); + final UUID operationId = UUID.randomUUID(); + final UUID jti = UUID.randomUUID(); + final UUID account = UUID.randomUUID(); + final UUID tenant = UUID.randomUUID(); + final UUID context = UUID.randomUUID(); + final AccountServiceImpl primary = mock(AccountServiceImpl.class); + AccountControlUiIssuanceRepository operations = mock(AccountControlUiIssuanceRepository.class); + final AccountControlUiAuthority authority = mock(AccountControlUiAuthority.class); + final DraftAuthorizationFenceRepository fences = mock(DraftAuthorizationFenceRepository.class); + final AccountControlUiSignerOwner signers = mock(AccountControlUiSignerOwner.class); + final AccountControlUiResponseCryptography cryptography = + mock(AccountControlUiResponseCryptography.class); + final AccountControlUiCoordination registry = mock(AccountControlUiCoordination.class); + final AccountControlUiActorService actors = mock(AccountControlUiActorService.class); + final CapturedEnvironmentBoundary environment = mock(CapturedEnvironmentBoundary.class); + final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + AccountControlUiIssuanceService service; + Record ownerRow; + + Fixture(Instant recoveryExpiry) { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer( + call -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + }); + doAnswer( + call -> { + TransactionSynchronizationManager.clear(); + return null; + }) + .when(transactions) + .commit(any()); + doAnswer( + call -> { + TransactionSynchronizationManager.clear(); + return null; + }) + .when(transactions) + .rollback(any()); + this.recoveryExpiry = recoveryExpiry; + } + + AccountControlUiIssuanceService service() { + if (service == null) { + service = + new AccountControlUiIssuanceService( + primary, + operations, + authority, + fences, + signers, + cryptography, + registry, + actors, + transactions, + Clock.fixed(NOW, ZoneOffset.UTC), + ISSUER); + } + return service; + } + + final Instant recoveryExpiry; + + AccountControlUiIssuanceRepository.Stored existing() { + return existing(ISSUER); + } + + AccountControlUiIssuanceRepository.Stored existing(String caller) { + var stored = stored("COMMITTED", recoveryExpiry, "original-token-hash", caller); + when(operations.findRequest(requestId)).thenReturn(stored); + when(cryptography.requestDigest(anyString(), any(byte[].class))) + .thenReturn("original-request-digest"); + return stored; + } + + AccountControlUiIssuanceRepository.Stored useOwnerRepository(String tokenHash) { + var stored = stored("COMMITTED", recoveryExpiry, tokenHash); + var dsl = mock(DSLContext.class); + var connection = mock(java.sql.Connection.class); + try { + when(connection.getTransactionIsolation()) + .thenReturn(java.sql.Connection.TRANSACTION_READ_COMMITTED); + } catch (java.sql.SQLException failure) { + throw new AssertionError(failure); + } + doAnswer( + call -> { + call.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(org.jooq.ConnectionRunnable.class)); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenAnswer(call -> ownerRow); + operations = Mockito.spy(new AccountControlUiIssuanceRepository(dsl)); + doAnswer(call -> stored).when(operations).findRequest(requestId); + when(cryptography.requestDigest(anyString(), any(byte[].class))) + .thenReturn("original-request-digest"); + ownerRow = rowFor(stored, tokenHash); + return stored; + } + + void recoveryInputs() { + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + when(snapshot.evidence()).thenReturn(new byte[] {1}); + when(snapshot.sources()).thenReturn(java.util.List.of()); + when(authority.capture(account, tenant, environment)).thenReturn(snapshot); + when(signers.requireOriginal(any(byte[].class))) + .thenReturn(mock(AccountControlUiSignerOwner.Capture.class)); + } + + AccountControlUiIssuanceRepository.Stored stored( + String status, Instant expiry, String tokenHash) { + return stored(status, expiry, tokenHash, ISSUER); + } + + AccountControlUiIssuanceRepository.Stored stored( + String status, Instant expiry, String tokenHash, String caller) { + var values = new java.util.HashMap(); + values.put("request_id", requestId); + values.put("operation_id", operationId); + values.put("token_jti", jti); + values.put("account_uuid", account); + values.put("tenant_uuid", tenant); + values.put("caller_context_id", context); + values.put("caller_workload", caller); + values.put("request_mac_key_id", "test-only-mac-key"); + values.put("request_digest", "original-request-digest"); + values.put("status", status); + values.put("token_hash", tokenHash); + values.put( + "claims_payload", + AccountControlUiAuthority.canonical(java.util.Map.of("synthetic", true))); + values.put("source_payload", new byte[] {1}); + values.put("bundle_payload", new byte[] {2}); + values.put("signer_receipt", new byte[] {3}); + values.put("pending_registry", new byte[] {4}); + values.put("active_registry", new byte[] {5}); + values.put("issued_at_epoch_second", NOW.getEpochSecond()); + values.put("expires_at_epoch_second", NOW.plusSeconds(300).getEpochSecond()); + values.put("recovery_expires_at", OffsetDateTime.ofInstant(expiry, ZoneOffset.UTC)); + Record row = rowForValues(values); + return new AccountControlUiIssuanceRepository.Stored(row); + } + + Record rowFor(AccountControlUiIssuanceRepository.Stored stored, String tokenHash) { + var values = new java.util.HashMap(); + values.put("request_id", stored.requestId); + values.put("operation_id", stored.operationId); + values.put("token_jti", stored.jti); + values.put("account_uuid", stored.accountId); + values.put("tenant_uuid", stored.tenantId); + values.put("caller_context_id", stored.callerContextId); + values.put("caller_workload", stored.caller); + values.put("request_mac_key_id", stored.requestMacKeyId); + values.put("request_digest", stored.requestDigest); + values.put("status", stored.status); + values.put("token_hash", tokenHash); + values.put("claims_payload", stored.claims); + values.put("source_payload", stored.sources); + values.put("bundle_payload", stored.bundle); + values.put("signer_receipt", stored.signerReceipt); + values.put("pending_registry", stored.pendingRegistry); + values.put("active_registry", stored.activeRegistry); + values.put("issued_at_epoch_second", stored.issuedAt.getEpochSecond()); + values.put("expires_at_epoch_second", stored.expiresAt.getEpochSecond()); + values.put( + "recovery_expires_at", OffsetDateTime.ofInstant(stored.recoveryExpiry, ZoneOffset.UTC)); + return rowForValues(values); + } + + Record rowForValues(java.util.Map values) { + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(call -> values.get(call.getArgument(0))); + return row; + } + + byte[] envelopeBinding(AccountControlUiIssuanceRepository.Stored original, String tokenHash) { + return AccountControlUiAuthority.canonical( + java.util.Map.ofEntries( + java.util.Map.entry("purpose", "account-control-ui-original-credential/v1"), + java.util.Map.entry("operationId", original.operationId.toString()), + java.util.Map.entry("requestId", original.requestId.toString()), + java.util.Map.entry("accountId", original.accountId.toString()), + java.util.Map.entry("tenantId", original.tenantId.toString()), + java.util.Map.entry("callerWorkload", original.caller), + java.util.Map.entry("callerContextId", original.callerContextId.toString()), + java.util.Map.entry("requestMacKeyId", original.requestMacKeyId), + java.util.Map.entry("requestDigest", original.requestDigest), + java.util.Map.entry("tokenHash", tokenHash), + java.util.Map.entry( + "claimsDigest", AccountControlUiIssuanceRepository.hash(original.claims)), + java.util.Map.entry( + "bundleDigest", AccountControlUiIssuanceRepository.hash(original.bundle)), + java.util.Map.entry( + "signerReceiptDigest", + AccountControlUiIssuanceRepository.hash(original.signerReceipt)), + java.util.Map.entry("recoveryExpiresAt", original.recoveryExpiry.toString()))); + } + + AccountControlUiIssuanceService.Request request( + UUID requestTenant, UUID requestContext, String secret) { + return new AccountControlUiIssuanceService.Request( + requestId, "creator@example.test", secret, requestTenant, requestContext); + } + + PeerScope withPeer(String uri) { + var identity = GrpcPeerIdentity.parseUri(uri).orElseThrow(); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, identity); + return new PeerScope(context.attach(), context); + } + } + + private record PeerScope(Context previous, Context attached) implements AutoCloseable { + @Override + public void close() { + attached.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java new file mode 100644 index 0000000000..abe7077d54 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java @@ -0,0 +1,143 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import de.mkammerer.argon2.Argon2Factory; +import java.time.LocalDateTime; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountDto; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.mapper.AccountMapper; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Actual primary-auth secret verification; repositories/transaction markers are explicit doubles. + */ +@ExtendWith(MockitoExtension.class) +class AccountControlUiPrimaryAuthenticationTest { + @Mock AccountRepository accounts; + @Mock AccountEmailLoginChallengeRepository challenges; + @Mock AccountMapper mapper; + @Mock PlatformTransactionManager transactions; + @InjectMocks AccountServiceImpl primary; + Account account; + + @BeforeEach + void setup() { + account = new Account(); + account.setId(41L); + account.setAccountUuid(UUID.randomUUID()); + account.setEmail("creator@example.test"); + account.setUsername("test-creator"); + account.setLoginAuthModes("PASSWORD"); + account.setPasswordHash(hash("test-only-primary-secret")); + TransactionSynchronizationManager.setActualTransactionActive(true); + } + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void actualPasswordProducesCanonicalActorOnlyForEligibleAccount() { + when(accounts.findByEmail("creator@example.test")).thenReturn(Optional.of(account)); + when(mapper.toDto(account)) + .thenReturn( + new AccountDto( + account.getAccountUuid().toString(), + account.getUsername(), + account.getEmail(), + "USER", + false)); + var actor = + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret"); + assertThat(actor.accountId()).isEqualTo(account.getAccountUuid()); + assertThat(actor.toString()).doesNotContain("secret", account.getEmail()); + assertThatThrownBy( + () -> primary.authenticateControlUiPrimaryIdentity(account.getEmail(), "wrong-secret")) + .isInstanceOf(RuntimeException.class); + account.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); + assertThatThrownBy( + () -> + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret")) + .isInstanceOf(RuntimeException.class); + } + + @Test + void exactOtpIsConsumedAndFailedPasswordCannotConsumeIt() { + account.setLoginAuthModes("EMAIL_OTP"); + var otp = new AccountEmailLoginChallenge(); + otp.setId(3L); + otp.setAccountId(account.getId()); + otp.setCodeHash(hash("test-only-otp")); + otp.setExpiresAt(LocalDateTime.now().plusMinutes(1)); + when(accounts.findByEmail(account.getEmail())).thenReturn(Optional.of(account)); + when(challenges.findByAccountId(account.getId())).thenReturn(Optional.of(otp)); + assertThatThrownBy( + () -> primary.authenticateControlUiPrimaryIdentity(account.getEmail(), "wrong-secret")) + .isInstanceOf(RuntimeException.class); + verify(challenges, never()).delete(otp); + when(mapper.toDto(account)) + .thenReturn( + new AccountDto( + account.getAccountUuid().toString(), + account.getUsername(), + account.getEmail(), + "USER", + false)); + assertThat( + primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), "test-only-otp") + .accountId()) + .isEqualTo(account.getAccountUuid()); + verify(challenges).delete(otp); + } + + @Test + void missingAndReadOnlyTransactionDenyBeforeCredentialAccess() { + TransactionSynchronizationManager.clear(); + assertThatThrownBy( + () -> + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret")) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy( + () -> + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret")) + .isInstanceOf(IllegalStateException.class); + } + + private static String hash(String secret) { + char[] chars = secret.toCharArray(); + var argon = Argon2Factory.create(); + try { + return argon.hash(2, 4096, 1, chars); + } finally { + argon.wipeArray(chars); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptographyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptographyTest.java new file mode 100644 index 0000000000..393a76858a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptographyTest.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Test-only custody files; no production mount, registry or issuer provenance is asserted. */ +class AccountControlUiResponseCryptographyTest { + @TempDir Path temporary; + private static final Instant NOW = Instant.parse("2026-10-08T11:00:00Z"); + + @Test + void recoversOnlyOriginalBoundedBytesAndExactOwnerBinding() throws Exception { + custody("encryption", "enc1", 11); + custody("request-mac", "mac1", 29); + var crypto = crypto(NOW); + byte[] credential = bytes("test-only-credential-not-a-production-token"); + byte[] binding = bytes("test-only/exact-owner/request1/actor1/tenant1/fence1"); + byte[] sealed = crypto.seal(credential, binding, NOW.plusSeconds(60)); + for (int offset = 0; offset <= sealed.length - credential.length; offset++) { + assertThat( + Arrays.equals( + sealed, offset, offset + credential.length, credential, 0, credential.length)) + .as("Encrypted envelope must not contain contiguous plaintext at offset %s", offset) + .isFalse(); + } + assertThat(crypto.open(sealed, binding, NOW.plusSeconds(60))).isEqualTo(credential); + assertThatThrownBy(() -> crypto.open(sealed, bytes("different-owner"), NOW.plusSeconds(60))) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + assertThatThrownBy(() -> crypto.open(sealed, binding, NOW.plusSeconds(59))) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + assertThatThrownBy(() -> crypto(NOW.plusSeconds(60)).open(sealed, binding, NOW.plusSeconds(60))) + .isInstanceOf(AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException.class); + } + + @Test + void requestMacIsExactKeyedAndIndependentFromEncryptionCustody() throws Exception { + custody("encryption", "enc1", 11); + custody("request-mac", "mac1", 29); + var crypto = crypto(NOW); + assertThat(crypto.currentKeyId()).isEqualTo("mac1"); + String original = crypto.requestDigest("mac1", bytes("test-only-secret/actor/tenant/request")); + assertThat(original).matches("[0-9a-f]{64}"); + assertThat(crypto.requestDigest("mac1", bytes("test-only-secret/actor/tenant/request"))) + .isEqualTo(original); + assertThat(crypto.requestDigest("mac1", bytes("changed-secret/actor/tenant/request"))) + .isNotEqualTo(original); + custody("request-mac", "mac2", 31); + assertThat(crypto.requestDigest("mac2", bytes("test-only-secret/actor/tenant/request"))) + .isNotEqualTo(original); + assertThatThrownBy(() -> crypto.requestDigest("mac1", bytes("exact-request"))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void absentWithdrawnAndSharedPurposeMaterialFailClosed() throws Exception { + assertThatThrownBy(() -> crypto(NOW).currentKeyId()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + custody("encryption", "enc1", 11); + custody("request-mac", "mac1", 11); + assertThatThrownBy(() -> crypto(NOW).requestDigest("mac1", bytes("test-only-presentation"))) + .isInstanceOf(IllegalStateException.class); + custody("request-mac", "mac1", 29); + byte[] binding = bytes("test-only-owner"); + byte[] envelope = crypto(NOW).seal(bytes("test-only-credential"), binding, NOW.plusSeconds(60)); + Files.delete(temporary.resolve("encryption/keyring")); + assertThatThrownBy(() -> crypto(NOW).open(envelope, binding, NOW.plusSeconds(60))) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } + + private AccountControlUiResponseCryptography crypto(Instant now) { + return new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary), Clock.fixed(now, ZoneOffset.UTC)); + } + + private void custody(String purpose, String id, int value) throws Exception { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) value); + Path directory = Files.createDirectories(temporary.resolve(purpose)); + Files.writeString( + directory.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive " + + id + + " " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n"); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java new file mode 100644 index 0000000000..b6df08a194 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java @@ -0,0 +1,365 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +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.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Actual RSA/profile verification and mounted signing. Registry, Account source, historical signer + * and transaction collaborators below are EXPLICIT SERVICE DOUBLES. No production credential, + * original lifecycle provenance, SQL transaction or physical mTLS/Coordination proof is asserted. + */ +class AccountControlUiSigningAndActorTest { + private static final Instant NOW = Instant.parse("2026-10-08T11:00:00Z"); + private static KeyPair key; + @TempDir Path temporary; + + @BeforeAll + static void key() throws Exception { + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + key = generator.generateKeyPair(); + } + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void distinctMountedSignerProducesExactOriginalProfileAndWipesCallbackCredential() + throws Exception { + Fixture f = new Fixture(); + Path privateRoot = Files.createDirectory(temporary.resolve("private")); + Path publicRoot = Files.createDirectory(temporary.resolve("public")); + String fingerprint = + AccountControlUiIssuanceRepository.hash( + AccountControlUiAuthority.canonical( + Map.of("kty", "RSA", "n", f.modulus, "e", f.exponent))); + var expected = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + "test-control", + "test-cluster", + "test-control", + UUID.randomUUID().toString(), + "1", + "test-only-control", + fingerprint); + Files.write( + privateRoot.resolve("current.key"), + AccountControlUiAuthority.canonical( + Map.ofEntries( + Map.entry("version", 1), + Map.entry("environmentId", expected.environmentId()), + Map.entry("clusterId", expected.clusterId()), + Map.entry("namespace", expected.namespace()), + Map.entry("operationId", expected.operationId()), + Map.entry("generation", expected.generation()), + Map.entry("kid", expected.kid()), + Map.entry("algorithm", "RS256"), + Map.entry("privateKeyPkcs8", b64(key.getPrivate().getEncoded())), + Map.entry("publicKeyFingerprint", fingerprint)))); + Files.write(publicRoot.resolve("jwks.json"), f.jwks); + var spec = + new AccountControlUiSigningSpec( + f.operationId, f.requestId, f.jti, f.snapshot, NOW, NOW.plusSeconds(300)); + AtomicReference retained = new AtomicReference<>(); + AtomicReference callback = new AtomicReference<>(); + String digest = + AccountMountedJwtSignerBundle.signCommittedControlUiDigest( + privateRoot, + Path.of("current.key"), + publicRoot, + Path.of("jwks.json"), + expected, + spec, + (hash, bytes) -> { + callback.set(bytes); + retained.set(bytes.clone()); + assertThat(hash).isEqualTo(AccountControlUiIssuanceRepository.hash(bytes)); + }); + assertThat(callback.get()).containsOnly((byte) 0); + assertThat(digest).isEqualTo(AccountControlUiIssuanceRepository.hash(retained.get())); + var verified = f.actors.verifySigned(new String(retained.get(), StandardCharsets.US_ASCII)); + assertThat(verified.claims.claims()) + .containsEntry("accountId", f.actor.toString()) + .containsEntry("scopedRoles", Map.of(f.tenant.toString(), List.of("tenantAdmin"))); + assertThat(verified.claims.claims()) + .doesNotContainKeys("globalRoles", "tokenProfile", "tokenType"); + } + + @Test + void signedControlUiNeedsExactActiveOwnerAndIndependentCurrentCreatorSources() throws Exception { + Fixture f = new Fixture(); + String compact = f.sign(f.claims); + f.owner(compact); + var actor = f.actors.authenticate(compact, f.tenant, f.environment); + assertThat(actor.accountId()).isEqualTo(f.actor); + assertThat(actor.tenantId()).isEqualTo(f.tenant); + assertThat(actor.toString()) + .isEqualTo("AccountControlUiActorService.AuthenticatedActor[redacted]"); + assertThatThrownBy(() -> f.actors.authenticate(compact, UUID.randomUUID(), f.environment)) + .isInstanceOf(IllegalStateException.class); + when(f.snapshot.evidence()).thenReturn(new byte[] {99}); + assertThatThrownBy(() -> f.actors.authenticate(compact, f.tenant, f.environment)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void readinessGameplayForgedAndMissingRegistryCredentialsNeverCreateActor() throws Exception { + Fixture f = new Fixture(); + for (String audience : + List.of("account-service", "firemud-account-jwt-readiness", "player-bootstrap")) { + var wrong = new HashMap<>(f.claims); + wrong.put("aud", audience); + assertThatThrownBy(() -> f.actors.authenticate(f.sign(wrong), f.tenant, f.environment)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + } + String compact = f.sign(f.claims); + String forged = compact.substring(0, compact.lastIndexOf('.') + 1) + "A".repeat(512); + assertThatThrownBy(() -> f.actors.authenticate(forged, f.tenant, f.environment)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + when(f.registry.readActive(anyString())) + .thenThrow(new IllegalStateException("test-only missing/inactive registry")); + assertThatThrownBy(() -> f.actors.authenticate(compact, f.tenant, f.environment)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void spoofedSubjectDifferentInitialAssociationAndHistoricalSignerFailureDeny() throws Exception { + Fixture f = new Fixture(); + var wrong = new HashMap<>(f.claims); + wrong.put("sub", UUID.randomUUID().toString()); + assertThatThrownBy(() -> f.actors.authenticate(f.sign(wrong), f.tenant, f.environment)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + String compact = f.sign(f.claims); + f.owner(compact); + when(f.authority.capture(f.actor, f.tenant, f.environment)) + .thenThrow(new IllegalStateException("test-only changed initial association")); + assertThatThrownBy(() -> f.actors.authenticate(compact, f.tenant, f.environment)) + .isInstanceOf(IllegalStateException.class); + doReturn(f.snapshot).when(f.authority).capture(f.actor, f.tenant, f.environment); + when(f.signers.requireOriginal(any(byte[].class))) + .thenThrow(new IllegalStateException("test-only absent original receipt")); + assertThatThrownBy(() -> f.actors.authenticate(compact, f.tenant, f.environment)) + .isInstanceOf(IllegalStateException.class); + } + + private static final class Fixture { + final UUID actor = UUID.randomUUID(), tenant = UUID.randomUUID(), jti = UUID.randomUUID(); + final UUID operationId = UUID.randomUUID(), requestId = UUID.randomUUID(); + final String modulus = unsigned(((RSAPublicKey) key.getPublic()).getModulus()); + final String exponent = unsigned(((RSAPublicKey) key.getPublic()).getPublicExponent()); + final byte[] jwks = + AccountControlUiAuthority.canonical( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "kid", + "test-only-control", + "use", + "sig", + "alg", + "RS256", + "key_ops", + List.of("verify"), + "n", + modulus, + "e", + exponent)))); + final AccountControlUiAuthority.Snapshot snapshot = + mock(AccountControlUiAuthority.Snapshot.class); + final AccountControlUiAuthority authority = mock(AccountControlUiAuthority.class); + final AccountControlUiIssuanceRepository operations = + mock(AccountControlUiIssuanceRepository.class); + final AccountControlUiSignerOwner signers = mock(AccountControlUiSignerOwner.class); + final AccountControlUiCoordination registry = mock(AccountControlUiCoordination.class); + final CapturedEnvironmentBoundary environment = mock(CapturedEnvironmentBoundary.class); + final AccountJwtJwksTrustedSource source = mock(AccountJwtJwksTrustedSource.class); + final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + final AccountPublicJwksCache.SourceIdentity pin = + new AccountPublicJwksCache.SourceIdentity( + "test-control", + "test-cluster", + UUID.randomUUID().toString(), + "test-control", + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + "test-revision", + "https://test-api.example.test:6443", + "a".repeat(64)); + final AccountControlUiActorService actors; + final Map claims; + + Fixture() { + when(snapshot.actor()).thenReturn(actor); + when(snapshot.tenant()).thenReturn(tenant); + when(snapshot.authorityTuple()) + .thenReturn( + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 1L, + "tenantAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "membershipAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "privateRealmGrantVersions", + List.of())); + when(snapshot.membershipVersion()).thenReturn(Map.of(tenant.toString(), 2L)); + when(snapshot.issuanceFence()).thenReturn(1L); + when(snapshot.evidence()).thenReturn(new byte[] {7}); + claims = + new AccountControlUiSigningSpec( + operationId, requestId, jti, snapshot, NOW, NOW.plusSeconds(300)) + .claims(); + when(source.sourceIdentity()).thenReturn(pin); + when(source.load()).thenReturn(new AccountPublicJwksCache.PublicJwksSnapshot(pin, jwks)); + when(transactions.getTransaction(any())) + .thenAnswer( + ignored -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + }); + doAnswer( + ignored -> { + TransactionSynchronizationManager.clear(); + return null; + }) + .when(transactions) + .commit(any()); + doAnswer( + ignored -> { + TransactionSynchronizationManager.clear(); + return null; + }) + .when(transactions) + .rollback(any()); + actors = + new AccountControlUiActorService( + operations, + authority, + signers, + registry, + source, + mock(DraftAuthorizationFenceRepository.class), + transactions, + Clock.fixed(NOW, ZoneOffset.UTC)); + } + + void owner(String compact) { + String hash = + AccountControlUiIssuanceRepository.hash(compact.getBytes(StandardCharsets.US_ASCII)); + Map values = new HashMap<>(); + values.put("request_id", requestId); + values.put("operation_id", operationId); + values.put("token_jti", jti); + values.put("account_uuid", actor); + values.put("tenant_uuid", tenant); + values.put("caller_context_id", UUID.randomUUID()); + values.put("caller_workload", "test-only-peer"); + values.put("request_mac_key_id", "test-only-mac"); + values.put("request_digest", "a".repeat(64)); + values.put("status", "COMMITTED"); + values.put("token_hash", hash); + values.put("claims_payload", AccountControlUiAuthority.canonical(claims)); + values.put("source_payload", new byte[] {7}); + values.put("bundle_payload", new byte[] {8}); + values.put( + "signer_receipt", + AccountControlUiAuthority.canonical( + Map.ofEntries( + Map.entry("kid", "test-only-control"), + Map.entry("environmentId", pin.environmentId()), + Map.entry("clusterId", pin.clusterId()), + Map.entry("clusterIncarnationUid", pin.clusterIncarnationUid()), + Map.entry("namespace", pin.namespace()), + Map.entry("namespaceUid", pin.namespaceUid()), + Map.entry("publicConfigMapUid", pin.configMapUid()), + Map.entry("apiConfigRevision", pin.bindingRevision())))); + values.put("pending_registry", new byte[] {11}); + values.put("active_registry", new byte[] {12}); + values.put("issued_at_epoch_second", NOW.getEpochSecond()); + values.put("expires_at_epoch_second", NOW.plusSeconds(300).getEpochSecond()); + values.put( + "recovery_expires_at", OffsetDateTime.ofInstant(NOW.plusSeconds(60), ZoneOffset.UTC)); + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(invocation -> values.get(invocation.getArgument(0))); + var stored = new AccountControlUiIssuanceRepository.Stored(row); + when(operations.findToken(hash)).thenReturn(stored); + when(registry.readActive(hash)).thenReturn(new byte[] {12}); + when(authority.capture(actor, tenant, environment)).thenReturn(snapshot); + var committed = mock(AccountControlUiIssuanceRepository.Committed.class); + when(committed.tokenHash()).thenReturn(hash); + when(operations.requireCommitted(stored)).thenReturn(committed); + } + + String sign(Map value) throws Exception { + String input = + b64( + AccountControlUiAuthority.canonical( + Map.of("alg", "RS256", "kid", "test-only-control", "typ", "JWT"))) + + "." + + b64(AccountControlUiAuthority.canonical(value)); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(key.getPrivate()); + signer.update(input.getBytes(StandardCharsets.US_ASCII)); + return input + "." + b64(signer.sign()); + } + } + + private static String unsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + if (bytes[0] == 0) { + bytes = Arrays.copyOfRange(bytes, 1, bytes.length); + } + return b64(bytes); + } + + private static String b64(byte[] bytes) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClient.java new file mode 100644 index 0000000000..9f704999ce --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClient.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.common.authoring; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountDraftCommitOrderReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Explicit file-backed mTLS client for the exact same-namespace Account order read. */ +public final class DraftCommitOrderReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountDraftCommitOrderReadServiceGrpc.AccountDraftCommitOrderReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public DraftCommitOrderReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + DraftCommitOrderReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account COMMIT_ORDER read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account COMMIT_ORDER read stub unavailable"); + initialized = true; + } + + /** Returns a validated HELD result only after exact Account server mTLS identity verification. */ + public DraftCommitOrderReadEvidence read(DraftCommitOrderReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account COMMIT_ORDER read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readHeldOriginalCommitOrder(DraftCommitOrderReadGrpcCodec.toRequest(request)); + try { + return DraftCommitOrderReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Account returned invalid COMMIT_ORDER evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountDraftCommitOrderReadServiceGrpc.AccountDraftCommitOrderReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountDraftCommitOrderReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountDraftCommitOrderReadServiceGrpc.AccountDraftCommitOrderReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account COMMIT_ORDER read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Account COMMIT_ORDER read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account COMMIT_ORDER read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account COMMIT_ORDER read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account COMMIT_ORDER read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account COMMIT_ORDER read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadEvidence.java new file mode 100644 index 0000000000..b50d85b4ab --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadEvidence.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.common.authoring; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; + +/** + * Exact HELD read returned by the authenticated Account mTLS client. The value shape alone is not + * proof; callers obtain it from {@link DraftCommitOrderReadClient} after exact peer verification. + */ +public final class DraftCommitOrderReadEvidence { + private final Request request; + + DraftCommitOrderReadEvidence(Request request) { + this.request = Objects.requireNonNull(request, "request"); + } + + public Request request() { + return request; + } + + /** Complete original binding plus one stable request/response correlation identity. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] originalAccountBinding) { + public static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported Account COMMIT_ORDER read schema version"); + } + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace is required"); + } + if (readRequestId == null || NIL_UUID.equals(readRequestId)) { + throw new IllegalArgumentException("Non-nil read request identity is required"); + } + if (originalAccountBinding == null || originalAccountBinding.length == 0) { + throw new IllegalArgumentException("Complete original Account binding is required"); + } + originalAccountBinding = originalAccountBinding.clone(); + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + if (!Arrays.equals(originalAccountBinding, binding.canonicalBytes())) { + throw new IllegalArgumentException("Canonical original Account binding is required"); + } + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.requestId()) + || readRequestId.equals(binding.commitId()) + || readRequestId.equals(binding.fenceId())) { + throw new IllegalArgumentException( + "COMMIT_ORDER read requires a separate request identity"); + } + } + + public static Request create(String targetNamespace, byte[] originalAccountBinding) { + DraftAuthorizationFenceBinding binding = + DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.requestId()) + || readRequestId.equals(binding.commitId()) + || readRequestId.equals(binding.fenceId())); + return new Request(SCHEMA_VERSION, targetNamespace, readRequestId, originalAccountBinding); + } + + @Override + public byte[] originalAccountBinding() { + return originalAccountBinding.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals(originalAccountBinding, that.originalAccountBinding); + } + + @Override + public int hashCode() { + int result = Objects.hash(schemaVersion, targetNamespace, readRequestId); + return 31 * result + Arrays.hashCode(originalAccountBinding); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodec.java new file mode 100644 index 0000000000..32ea5b9bbd --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodec.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.common.authoring; + +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.HeldOriginalCommitOrderStatus; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderRequest; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderResponse; + +/** Closed wire mapping and exact request-echo validation for the Account held-order read. */ +public final class DraftCommitOrderReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private DraftCommitOrderReadGrpcCodec() {} + + public static ReadHeldOriginalCommitOrderRequest toRequest( + DraftCommitOrderReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadHeldOriginalCommitOrderRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())) + .build(); + } + + /** Decode only after the Account server has authenticated its exact same-namespace World peer. */ + public static DraftCommitOrderReadEvidence.Request fromRequest( + ReadHeldOriginalCommitOrderRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadHeldOriginalCommitOrderRequest"); + try { + return new DraftCommitOrderReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalUuid(request.getReadRequestId()), + request.getOriginalAccountBinding().toByteArray()); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Account COMMIT_ORDER read request is invalid", invalid); + } + } + + /** Account may emit HELD only after its owner transaction proves the retained exact state. */ + public static ReadHeldOriginalCommitOrderResponse toHeldResponse( + DraftCommitOrderReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadHeldOriginalCommitOrderResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(request.originalAccountBinding())) + .setStatus(HeldOriginalCommitOrderStatus.HELD_ORIGINAL_COMMIT_ORDER_STATUS_HELD) + .build(); + } + + /** Validate a positive response; all non-held states are represented by non-OK RPC failures. */ + public static DraftCommitOrderReadEvidence fromResponse( + DraftCommitOrderReadEvidence.Request request, ReadHeldOriginalCommitOrderResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadHeldOriginalCommitOrderResponse"); + if (response.getSchemaVersion() != request.schemaVersion() + || !response.getTargetNamespace().equals(request.targetNamespace()) + || !response.getReadRequestId().equals(request.readRequestId().toString()) + || !Arrays.equals( + response.getOriginalAccountBinding().toByteArray(), request.originalAccountBinding())) { + throw new IllegalArgumentException("Account response changed the exact COMMIT_ORDER read"); + } + if (response.getStatus() + != HeldOriginalCommitOrderStatus.HELD_ORIGINAL_COMMIT_ORDER_STATUS_HELD) { + throw new IllegalArgumentException("Account did not confirm held original COMMIT_ORDER"); + } + return new DraftCommitOrderReadEvidence(request); + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalUuid(String value) { + if (value == null) throw new IllegalArgumentException("Canonical read request UUID required"); + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil read request UUID required"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Canonical non-nil read request UUID required", invalid); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientMtlsTest.java new file mode 100644 index 0000000000..cf7ec43736 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientMtlsTest.java @@ -0,0 +1,519 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +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.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountDraftCommitOrderReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderRequest; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical loopback mTLS proof for the Account COMMIT_ORDER client transport only. */ +class DraftCommitOrderReadClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String OTHER_NAMESPACE_ACCOUNT_URI = + "spiffe://firemud/ns/other-test/sa/account-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @TempDir static Path tempDirectory; + + private static TestPki pki; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @Test + void exactAccountPeerReturnsTheExactHeldResponseOverPhysicalMtls() throws Exception { + DraftCommitOrderReadEvidence.Request request = DraftCommitOrderReadGrpcCodecTest.request(); + try (TransportServer server = startServer(pki.accountServer(), request); + DraftCommitOrderReadClient client = newClient(server.port())) { + client.init(); + + DraftCommitOrderReadEvidence actual = client.read(request); + + assertThat(actual.request()).isEqualTo(request); + assertThat(server.rpcStarts()).hasValue(1); + assertThat(server.ownerReads()).hasValue(1); + assertThat(server.clientPeerUri()).hasValue(WORLD_URI); + } + } + + @Test + void trustedWrongAccountWorkloadAndNamespaceCannotReachTheHeldOwner() throws Exception { + DraftCommitOrderReadEvidence.Request request = DraftCommitOrderReadGrpcCodecTest.request(); + for (TestIdentity identity : List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer())) { + try (TransportServer server = startServer(identity, request); + DraftCommitOrderReadClient client = newClient(server.port())) { + client.init(); + + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(server.rpcStarts()).as(identity.alias()).hasValue(0); + assertThat(server.ownerReads()).as(identity.alias()).hasValue(0); + assertThat(server.clientPeerUri().get()).isNull(); + } + } + } + + @Test + void requiresAClientCertificateAndRejectsPlaintextOrMissingCertificateConfiguration() + throws Exception { + DraftCommitOrderReadEvidence.Request request = DraftCommitOrderReadGrpcCodecTest.request(); + try (TransportServer server = startServer(pki.accountServer(), request)) { + CommonGrpcClientProperties noClientCertificate = new CommonGrpcClientProperties(); + noClientCertificate.setCaCert(pki.caCertificatePem().toString()); + ManagedChannel channel = + new GrpcChannelFactory() + .buildChannel("127.0.0.1:" + server.port(), 6565, noClientCertificate, false); + try { + assertThatThrownBy( + () -> + AccountDraftCommitOrderReadServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .readHeldOriginalCommitOrder( + DraftCommitOrderReadGrpcCodec.toRequest(request))) + .satisfies( + failure -> assertThat(isMissingClientCertificateHandshake(failure)).isTrue()); + assertThat(server.rpcStarts()).hasValue(0); + assertThat(server.ownerReads()).hasValue(0); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + CommonGrpcClientProperties plaintext = pki.clientProperties(tempDirectory, pki.worldClient()); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new DraftCommitOrderReadClient( + endpoints(server.port()), plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + CommonGrpcClientProperties missingCertificate = + pki.clientProperties(tempDirectory, pki.worldClient()); + missingCertificate.setCertChain(""); + assertThatThrownBy( + () -> + new DraftCommitOrderReadClient( + endpoints(server.port()), + missingCertificate, + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + } + } + + private static TransportServer startServer( + TestIdentity identity, DraftCommitOrderReadEvidence.Request expectedRequest) + throws Exception { + AtomicInteger rpcStarts = new AtomicInteger(); + AtomicInteger ownerReads = new AtomicInteger(); + AtomicReference clientPeerUri = new AtomicReference<>(); + var owner = new TestOnlyHeldOwnerService(expectedRequest, ownerReads, clientPeerUri); + ServerInterceptor countRpcStarts = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + rpcStarts.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + owner, countRpcStarts, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new TransportServer(server, rpcStarts, ownerReads, clientPeerUri); + } + + private static DraftCommitOrderReadClient newClient(int port) throws Exception { + return new DraftCommitOrderReadClient( + endpoints(port), + pki.clientProperties(tempDirectory, pki.worldClient()), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ServiceEndpointsProperties endpoints(int port) { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + return endpoints; + } + + private static boolean isMissingClientCertificateHandshake(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SSLException && cause.getMessage() != null) { + String message = cause.getMessage().toLowerCase(Locale.ROOT); + if (message.contains("certificate_required") + || message.contains("certificate required") + || message.contains("empty client certificate chain") + || message.contains("peer did not return a certificate")) { + return true; + } + } + } + return false; + } + + /** + * Returns HELD for transport proof only; this does not query or represent the Account producer. + */ + private static final class TestOnlyHeldOwnerService + extends AccountDraftCommitOrderReadServiceGrpc.AccountDraftCommitOrderReadServiceImplBase { + private final DraftCommitOrderReadEvidence.Request expectedRequest; + private final AtomicInteger ownerReads; + private final AtomicReference clientPeerUri; + + private TestOnlyHeldOwnerService( + DraftCommitOrderReadEvidence.Request expectedRequest, + AtomicInteger ownerReads, + AtomicReference clientPeerUri) { + this.expectedRequest = expectedRequest; + this.ownerReads = ownerReads; + this.clientPeerUri = clientPeerUri; + } + + @Override + public void readHeldOriginalCommitOrder( + ReadHeldOriginalCommitOrderRequest wire, + StreamObserver observer) { + ownerReads.incrementAndGet(); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null) { + clientPeerUri.set(peer.uri()); + } + DraftCommitOrderReadEvidence.Request decoded = + DraftCommitOrderReadGrpcCodec.fromRequest(wire); + if (peer == null || !WORLD_URI.equals(peer.uri())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Exact World test caller required") + .asRuntimeException()); + return; + } + if (!expectedRequest.equals(decoded)) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Unexpected test request") + .asRuntimeException()); + return; + } + observer.onNext(DraftCommitOrderReadGrpcCodec.toHeldResponse(decoded)); + observer.onCompleted(); + } + } + + private record TransportServer( + Server server, + AtomicInteger rpcStarts, + AtomicInteger ownerReads, + AtomicReference clientPeerUri) + implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account test server did not terminate"); + } + } + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + Path caCertificatePem, + TestIdentity accountServer, + TestIdentity wrongWorkloadServer, + TestIdentity otherNamespaceServer, + TestIdentity worldClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD COMMIT_ORDER test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + caFile, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-workload-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, + caStore, + caFile, + "other-namespace-server", + OTHER_NAMESPACE_ACCOUNT_URI, + true), + issueIdentity(directory, caStore, caFile, "world-client", WORLD_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve(identity.alias() + ".crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve(identity.alias() + ".key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String extendedKeyUsage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + ArrayList command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientTest.java new file mode 100644 index 0000000000..42100c4c7d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientTest.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.AbstractStub; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.account.v1.AccountDraftCommitOrderReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderResponse; +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.GrpcServerPeerIdentityCallCredentials; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class DraftCommitOrderReadClientTest { + @Test + void rejectsPlaintextWrongNamespaceAndUninitializedCallsBeforeTransport(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new DraftCommitOrderReadClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var client = + new DraftCommitOrderReadClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + try { + assertThatThrownBy(() -> client.read(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(request("test"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(factory); + } finally { + client.close(); + } + } + + @Test + void configuresExactAccountServerIdentityAndReturnsOnlyExactHeldResponse(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(factory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = new DraftCommitOrderReadClient(endpoints, tls(directory), factory, "test"); + try { + client.init(); + AbstractStub initialized = initializedStub(client); + assertThat(initialized.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(initialized.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + + var stub = + mock( + AccountDraftCommitOrderReadServiceGrpc.AccountDraftCommitOrderReadServiceBlockingStub + .class); + when(stub.withDeadlineAfter(eq(5L), eq(java.util.concurrent.TimeUnit.SECONDS))) + .thenReturn(stub); + setStub(client, stub); + var request = request("test"); + var held = DraftCommitOrderReadGrpcCodec.toHeldResponse(request); + when(stub.readHeldOriginalCommitOrder(any())).thenReturn(held); + + assertThat(client.read(request).request()).isEqualTo(request); + verify(stub).readHeldOriginalCommitOrder(any()); + + when(stub.readHeldOriginalCommitOrder(any())) + .thenReturn(held.toBuilder().setTargetNamespace("other").build()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid COMMIT_ORDER evidence"); + when(stub.readHeldOriginalCommitOrder(any())) + .thenReturn(ReadHeldOriginalCommitOrderResponse.getDefaultInstance()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid COMMIT_ORDER evidence"); + when(stub.readHeldOriginalCommitOrder(any())) + .thenThrow(Status.UNAVAILABLE.withDescription("offline").asRuntimeException()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + } finally { + client.close(); + } + } + + private static DraftCommitOrderReadEvidence.Request request(String namespace) { + return new DraftCommitOrderReadEvidence.Request( + 1, + namespace, + java.util.UUID.fromString("33333333-3333-4333-8333-333333333333"), + DraftCommitOrderReadGrpcCodecTest.accountBinding()); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return tls; + } + + private static AbstractStub initializedStub(DraftCommitOrderReadClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + private static void setStub( + DraftCommitOrderReadClient client, + AccountDraftCommitOrderReadServiceGrpc.AccountDraftCommitOrderReadServiceBlockingStub stub) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodecTest.java new file mode 100644 index 0000000000..06f5409436 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodecTest.java @@ -0,0 +1,145 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.HeldOriginalCommitOrderStatus; +import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; + +class DraftCommitOrderReadGrpcCodecTest { + @Test + void mapsTheCompleteCanonicalBindingAndStableReadIdentity() { + var request = request(); + + var decoded = + DraftCommitOrderReadGrpcCodec.fromRequest(DraftCommitOrderReadGrpcCodec.toRequest(request)); + var evidence = + DraftCommitOrderReadGrpcCodec.fromResponse( + request, DraftCommitOrderReadGrpcCodec.toHeldResponse(request)); + + assertThat(decoded).isEqualTo(request); + assertThat(evidence.request()).isEqualTo(request); + assertThat(decoded.originalAccountBinding()).containsExactly(request.originalAccountBinding()); + } + + @Test + void rejectsMalformedRequestsUnknownFieldsAndNonCanonicalReadIdentity() { + var request = DraftCommitOrderReadGrpcCodec.toRequest(request()); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatThrownBy( + () -> + DraftCommitOrderReadGrpcCodec.fromRequest( + request.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + DraftCommitOrderReadGrpcCodec.fromRequest( + request.toBuilder().setReadRequestId("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + DraftCommitOrderReadGrpcCodec.fromRequest( + request.toBuilder().setSchemaVersion(2).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsResponseSubstitutionUnknownFieldsAndNonHeldStatuses() { + var request = request(); + var held = DraftCommitOrderReadGrpcCodec.toHeldResponse(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + for (ReadHeldOriginalCommitOrderResponse changed : + List.of( + held.toBuilder().setTargetNamespace("other").build(), + held.toBuilder().setReadRequestId(UUID.randomUUID().toString()).build(), + held.toBuilder().setOriginalAccountBinding(ByteString.copyFrom(new byte[] {1})).build(), + held.toBuilder() + .setStatus( + HeldOriginalCommitOrderStatus.HELD_ORIGINAL_COMMIT_ORDER_STATUS_UNSPECIFIED) + .build(), + held.toBuilder().setUnknownFields(unknown).build())) { + assertThatThrownBy(() -> DraftCommitOrderReadGrpcCodec.fromResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + static DraftCommitOrderReadEvidence.Request request() { + byte[] binding = accountBinding(); + return new DraftCommitOrderReadEvidence.Request( + 1, "test", uuid("33333333-3333-4333-8333-333333333333"), binding); + } + + static byte[] accountBinding() { + UUID tenant = uuid("11111111-1111-4111-8111-111111111111"); + UUID version = uuid("22222222-2222-4222-8222-222222222222"); + UUID request = uuid("44444444-4444-4444-8444-444444444444"); + UUID commit = uuid("55555555-5555-4555-8555-555555555555"); + DraftCommitBinding draft = + DraftCommitBinding.create( + new TargetProof(tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request, + commit, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + tenant, + version, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + null, + "1", + null, + null, + new byte[] {1}))) + .canonicalBytes(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifier.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifier.java new file mode 100644 index 0000000000..1e15fc71b5 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifier.java @@ -0,0 +1,45 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadClient; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationService.CommitOrderProof; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationService.CommitOrderVerifier; + +/** + * Unregistered production-shaped adapter: derives the exact Account read from the original World + * operation and creates a World proof only after the mTLS client returns its validated HELD result. + * This reads retained ordering, not physical commit-time terms currentness. A later terms schedule + * can introduce a deadline after the original capture; runtime wiring remains denied until that + * source transition and the World physical commit are safely fenced. + */ +public final class WorldDraftCommitOrderVerifier implements CommitOrderVerifier { + private final DraftCommitOrderReadClient accountClient; + private final String workloadNamespace; + + public WorldDraftCommitOrderVerifier( + DraftCommitOrderReadClient accountClient, String workloadNamespace) { + this.accountClient = Objects.requireNonNull(accountClient, "accountClient"); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public CommitOrderProof verifyHeldOriginalCommitOrder(WorldDraftTerminalOperation operation) { + Objects.requireNonNull(operation, "operation"); + if (!workloadNamespace.equals(operation.ownerBinding().targetNamespace())) { + throw new ConflictException("Original World operation namespace differs from this workload"); + } + DraftCommitOrderReadEvidence.Request request = + DraftCommitOrderReadEvidence.Request.create( + workloadNamespace, operation.accountBindingBytes()); + DraftCommitOrderReadEvidence evidence = Objects.requireNonNull(accountClient.read(request)); + if (!request.equals(Objects.requireNonNull(evidence.request()))) { + throw new ConflictException("Account changed the exact original COMMIT_ORDER read request"); + } + return new CommitOrderProof(operation); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifierTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifierTest.java new file mode 100644 index 0000000000..123167bf71 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifierTest.java @@ -0,0 +1,184 @@ +package unit.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.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadClient; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadGrpcCodec; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftCommitOrderVerifier; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationService.CommitOrderProof; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOperation; +import org.junit.jupiter.api.Test; + +/** Synthetic client outcomes exercise the unregistered adapter only; they are not Account proof. */ +class WorldDraftCommitOrderVerifierTest { + @Test + void derivesExactOriginalBindingAndReturnsProofOnlyAfterClientHeldResponse() throws Exception { + var operation = operation("test"); + var client = mock(DraftCommitOrderReadClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + var request = (DraftCommitOrderReadEvidence.Request) invocation.getArgument(0); + return DraftCommitOrderReadGrpcCodec.fromResponse( + request, DraftCommitOrderReadGrpcCodec.toHeldResponse(request)); + }); + var verifier = new WorldDraftCommitOrderVerifier(client, "test"); + + CommitOrderProof proof = verifier.verifyHeldOriginalCommitOrder(operation); + + assertThat(proof).isNotNull(); + var request = org.mockito.ArgumentCaptor.forClass(DraftCommitOrderReadEvidence.Request.class); + verify(client).read(request.capture()); + assertThat(request.getValue().targetNamespace()).isEqualTo("test"); + assertThat(request.getValue().originalAccountBinding()) + .containsExactly(operation.accountBindingBytes()); + assertThat(request.getValue().readRequestId()) + .isNotIn( + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId()); + } + + @Test + void rejectsChangedReadRequestUnavailableClientAndWrongNamespaceWithoutProof() throws Exception { + var operation = operation("test"); + var client = mock(DraftCommitOrderReadClient.class); + var substituted = + DraftCommitOrderReadEvidence.Request.create("test", operation.accountBindingBytes()); + when(client.read(any())) + .thenReturn( + DraftCommitOrderReadGrpcCodec.fromResponse( + substituted, DraftCommitOrderReadGrpcCodec.toHeldResponse(substituted))); + var verifier = new WorldDraftCommitOrderVerifier(client, "test"); + assertThatThrownBy(() -> verifier.verifyHeldOriginalCommitOrder(operation)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("changed the exact original"); + + var offline = mock(DraftCommitOrderReadClient.class); + when(offline.read(any())).thenThrow(new IllegalStateException("Account unavailable")); + assertThatThrownBy( + () -> + new WorldDraftCommitOrderVerifier(offline, "test") + .verifyHeldOriginalCommitOrder(operation)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + + var namespaceClient = mock(DraftCommitOrderReadClient.class); + var otherNamespaceOperation = operation("other"); + assertThatThrownBy( + () -> + new WorldDraftCommitOrderVerifier(namespaceClient, "test") + .verifyHeldOriginalCommitOrder(otherNamespaceOperation)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("namespace"); + verify(namespaceClient, never()).read(any()); + } + + private static WorldDraftTerminalOperation operation(String namespace) throws Exception { + UUID tenant = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID version = UUID.fromString("22222222-2222-4222-8222-222222222222"); + UUID requestId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + UUID commitId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + UUID operationId = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID fenceId = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + DraftCommitBinding draft = + DraftCommitBinding.create( + new TargetProof(tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + requestId, + commitId, + "base-1", + List.of( + new RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "world"), + new RevisionPayload( + "1", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "design")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "REGION", + "region-1", + "AGGREGATE", + "region-1", + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "VERSION", + version.toString(), + "AGGREGATE", + version.toString(), + "0"))); + byte[] draftBytes = draft.canonicalBytes(); + byte[] accountBytes = + new DraftAuthorizationFenceBinding( + operationId, + requestId, + commitId, + fenceId, + UUID.randomUUID(), + tenant, + version, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + null, + "1", + null, + null, + new byte[] {1}))) + .canonicalBytes(); + var owner = + new OwnerBinding( + namespace, + tenant, + version, + UUID.randomUUID(), + 19L, + UUID.randomUUID(), + UUID.randomUUID(), + digest("intake"), + UUID.randomUUID(), + digest("source"), + digest("receipt")); + return new WorldDraftTerminalOperation( + operationId, requestId, commitId, fenceId, tenant, version, draft, owner, accountBytes); + } + + private static String digest(String value) throws Exception { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } +} From 30c1b7d7b0f11027c965035aa9a2ec672ee8550d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 01:56:43 +1300 Subject: [PATCH 015/129] Repair creator PostgreSQL bindings and canonical policy genesis proof --- .../account-service/api-contracts.md | 2 + .../account-service/runtime-and-data.md | 4 +- ...ame-authoring-publishing-and-activation.md | 2 +- .../AccountControlUiIssuanceRepository.java | 2 +- ...lUiSourceGuardPostgresIntegrationTest.java | 2 +- ...orizationFencePostgresIntegrationTest.java | 35 ++--- ...trolUiIssuancePostgresIntegrationTest.java | 2 + ...AuthenticationPostgresIntegrationTest.java | 20 +-- .../publication/RealmPolicyApplication.java | 6 +- ...emptServiceTransactionIntegrationTest.java | 2 +- .../RealmPolicyApplicationTest.java | 127 ++++++++++++++++++ .../mapper/GameInstanceMapper.java | 5 + .../mapper/GameInstanceMapperTest.java | 10 ++ 13 files changed, 179 insertions(+), 40 deletions(-) create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index b926faf323..ab3c239ffc 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -18,6 +18,8 @@ For official hosted deployments, Game Design owns creator content and must obtai Account owns the changed-hosted-terms technical contract. It classifies each proposed terms change as material or nonmaterial through audited operator/legal review. A material change classified under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) advances the monotonic material-acceptance generation and requires affirmative reacceptance; only a nonmaterial change may leave that generation unchanged. Account keeps operative and proposed versions distinct, gives reasonable notice through disclosed durable channels with a disclosed effective date, and records sufficient notice evidence. An explicit decline during the notice period records nonacceptance but does not end the previously accepted terms or freeze writes early. At the effective date, a declined or non-reaccepted material generation is stale; Account currentness fails closed and Game Design blocks each covered new content-bearing mutation before side effects. +For any elective, not-yet-disclosed exact terms-source change that introduces an effective date, Account must own an authenticated, durable prepare-before-disclose handoff bound to the exact predecessor, candidate, and effective instant. It must serialize every applicable deadline-introduction path, including an environment-binding change that can expose a scope's deadline, against original `COMMIT_ORDER` acquisition and owner settlement; a one-time pending-order preflight is insufficient. Refuse introduction of a new deadline while an original applicable commit order remains unresolved, and preserve that fence through dispatch authorization, external disclosure and exact durable readback. No database lock may be held across an RPC. Once disclosed, the effective instant is immutable; exact retries and recovery use the same handoff identity and authenticated durable readback, and a notice reference or caller-supplied timestamp alone is not proof. Ordinary authoring under the previously operative terms continues until the disclosed effective instant: do not freeze it early, defer or rewrite a disclosed date, or delay existing security or restriction powers. A currentness observation is not write authorization; consumers of deadline-qualified creator-write authority remain denied until physical commit-time currentness and the complete handoff's focused proof exist. + Until the disclosed effective date, the previously accepted terms remain operative. After currentness becomes stale, narrow prior-terms continuity may support reads of persisted Draft/history content, unchanged published or active delivery, and technically necessary caching, replication, backup, restart, repair, security, or moderation. It must not create a new creator-content side effect, version, or publication, expand reachability or audience, or grant a new right. Supported reads and downloads, including any controlled export the product supports, remain separate from lifecycle reduction and use their applicable authorization and audit boundaries. A controlled export uses its own authorization, audit, and [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) retention requirements and does not promise whole-game portability. Only unpublish, retire, removal, deletion, and account-closure requests are lifecycle-reducing operations; each must be narrowly authorized, audited, idempotent, and reducing-only, with no new creator-content payload, reachability expansion, or new version. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9e8bf02bec..cf4a5c646f 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -24,7 +24,7 @@ Account also performs a bounded sweep of public connect-scope evidence after its The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback applies the terminal retry checks when a terminal row is present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. An exact retry of a terminal JOIN replays its stored result only after the retained scope is still unexpired and current target/entitlement authority is available and matches the stored policy digest; expiry, unavailable authority, or changed policy fails closed without rewriting the terminal operation or membership. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. -Hosted Creator Party/operator identity, terms catalog, acceptance/currentness evidence, changed-term status, and future financial-reconciliation boundaries are target-only. No current party/signer or terms storage, acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved; the local retention/export treatment must follow [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) when the owner contract is implemented. Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. +Account has bounded owner-local storage for identified Creator Party/operator, terms catalog, acceptance/currentness evidence, and environment-binding/publication operations. These stores are not registered production authority and do not establish the authenticated notice handoff or physical World commit-time currentness boundary. No production acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved. The local retention/export treatment follows [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md); the normative contract is in [Account API Contracts](./api-contracts.md#account-owned-hosted-terms-and-creator-party), and implementation gaps are tracked in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current consumers still rely on only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and do not enforce the complete atomic-freshness contract or consume the emitted lifecycle/generation fields. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and character discovery require membership after applicable target and entitlement checks; on an eligible public-production target only absent membership may return non-actionable `JOIN_REQUIRED`, while existing membership with `gameplayAdmissionAllowed=false` is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` can still return non-actionable `JOIN_REQUIRED` for missing or present non-admitting membership before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. These flows do not create or restore membership. The Account-owned public-production `JOIN` writer is implemented locally with a v1 policy-bound digest and atomic membership, operation-outcome, and audit-outbox evidence. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Exact-final-head PostgreSQL runtime proof remains unavailable locally without Docker; no live PostgreSQL runtime proof or direct text-client end-to-end proof is claimed. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. @@ -67,7 +67,7 @@ The target capacity retry contract uses stable outer `(tenantId, requestId, admi - Target `external_account` records link a server-verified canonical `{provider, issuer, subject}` to one global platform account without tenant scope. The current tenant-scoped, caller-asserted row shape is implementation drift. - Tenant-bound billing tables such as `subscription` and tenant-bound `payment_transaction` records associate `accountId` with `tenantId` for hosted games and hosting plans. Account-scoped transactions, grants, and donations carry no fabricated `tenantId`. - Account-owned safety records persist separate `account_security_lock` and `platform_access_ban` revisions keyed by global `accountId` and category. Their current projection, monotonic enforcement epoch, idempotency/result records, source case/security-event identity, and safe notice support auth-generation and player-safe denial decisions without a Logging & Admin read. The complete schema/command implementation remains a target gap. -- Account-owned Creator Party, identified operator/terms versions, acceptance/currentness evidence, and future financial-reconciliation records are target-only. Each committed covered creator mutation records the local `tenantId`, exact `creatorPartyId`, `acceptanceEvidenceId`, and material-acceptance `generation` binding; Account remains sole owner of the party and terms catalogs, which Game Design must not copy. No current storage or focused proof implements this boundary; see [Account API Contracts](./api-contracts.md#account-owned-hosted-terms-and-creator-party). +- Account-owned Creator Party, identified operator/terms versions, acceptance/currentness evidence, and environment-binding/publication operations have bounded owner-local storage; future financial-reconciliation records remain target-only. Each committed covered creator mutation records the local `tenantId`, exact `creatorPartyId`, `acceptanceEvidenceId`, and material-acceptance `generation` binding; Account remains sole owner of the party and terms catalogs, which Game Design must not copy. Production authority and the prepare-before-disclose/physical World commit-time boundary remain unimplemented or unproved; see [Account API Contracts](./api-contracts.md#account-owned-hosted-terms-and-creator-party) and [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). - Durable purchased-product grants are reserved for deferred future commerce and are separate from raw payment attempts. A future tenant-bound one-time purchase would store bindings to `accountId`, `tenantId`, an optional Entity-resolvable actor reference `{tenantId, playableStateNamespaceId, characterId}`, and `productCode`; those association fields are not fulfillment-uniqueness inputs. The sole fulfillment uniqueness pair is the immutable `(purchase_operation_id, product_grant_key)` defined by [Stripe Integration Design](./stripe-integration.md). Server-derived `playableStateScope` travels as separately validated policy/routing/authorization evidence for that actor and active instance, not as a durable actor key or uniqueness dimension. `gameInstanceId` may be added only as an explicit replaceable runtime fence when the operation requires it. Account-scoped grants use Account-owned records without `tenantId`. No v1 hosting-billing PaymentIntent, donation, or receipt creates this entitlement. Applying an account-scoped grant to a tenant-scoped feature requires an explicit tenant binding or consumption record. Payment rows remain financial/provider evidence, not entitlement authority. Google, Discord, and Steam are optional provider-specific HTTPS integrations, not simultaneously promised launch capabilities. Initial delivery links a verified provider subject to an already authenticated global account; provider-first account creation is deferred. Provider email or display-name matches never merge accounts, every account retains Account-owned verified-email recovery and an ordinary login mode, and provider outage does not invalidate existing FireMUD sessions. 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 9cbbd70a2d..053767754d 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 @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a The current Gameplay-prerequisite construction remains non-activating. Full-version finalization now reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. The real backend control-ui issuance/current-actor source, complete Account source-writer fencing and callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Earlier construction CI executed all four Account source-composition, five environment-binding and 31 Draft authorization PostgreSQL cases successfully, while three Game Design canonical-release fixtures failed for missing policy source capture. Their receiving correction now freezes actual Game Design command/policy source snapshots before sealing; corrected physical execution remains required. These bounded changes do not upgrade the broader capability ratings below. -The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. +The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. At `ed928219ee3428073910f1845eaa975e8814a30a`, local validation is complete for the held-order/source-fencing batch, but physical PostgreSQL validation was skipped. No authenticated terms-notice producer/receiver, durable prepare-before-disclose handoff, or physical World deadline gate is implemented; there is no production disclosure/currentness path. Reconsider only after focused PostgreSQL proof covers both orderings of preparation versus original `COMMIT_ORDER` acquisition and settlement, every deadline-introduction path including environment binding, exact retry/restart/ambiguous-notice readback, and World commit-time denial at the disclosed instant without early ordinary-authoring freeze or date rewriting. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. Creator issuance preserves the existing OTP failure budget by committing a primary-authentication denial's accounting before returning the credential error; successful OTP consumption still rolls back if subsequent preparation fails. Its real PostgreSQL definitions use the primary hook's Spring transaction interceptor, not only a direct method call. Positive issuance and original-signer rotation proof are additionally blocked by Account's current readiness owner: validator inventory is always incomplete, and a complete claim without protected per-validator evidence is quarantined. No real committed signer can be produced through that owner path yet; synthetic signer fixtures cannot close the original APPLIED/release prerequisite. The broader JWT capability remains owned by [Shared Runtime Contracts](./shared-runtime-contracts-and-persistence.md). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java index 6090b1c769..6bb0e6cade 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java @@ -168,7 +168,7 @@ Stored prepare( + " (request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload," + " caller_context_id, request_mac_key_id, request_digest, claims_payload, source_payload," + " bundle_payload, signer_receipt, issued_at_epoch_second, expires_at_epoch_second," - + " recovery_expires_at, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PREPARED')" + + " recovery_expires_at, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')" + " ON CONFLICT (request_id) DO NOTHING", requestId, operationId, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java index 176b7a3d3f..f8e9b222f7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java @@ -76,7 +76,7 @@ void rawProtectedMutationCannotBypassOriginalFenceButNoOpAndUnrelatedAccountRema () -> c.dsl.execute( "UPDATE accounts SET username = ? WHERE account_uuid = ?", - "test-noop-metadata-" + UUID.randomUUID(), + "test-noop-metadata", binding.actorAccountId())); UUID unrelated = account(c); changePassword(c, unrelated, "test-only-unrelated-account-change"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java index 2f60946867..1a2a645c0a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -144,18 +144,7 @@ void producerLocksDeduplicatedAccountsInUuidOrderBeforeAnySourceLocks() throws E source(SourceKind.GLOBAL_ROLES, first), source(SourceKind.GLOBAL_ROLES, last)), new byte[] {12}); - tx( - context, - () -> { - for (SourceEvidence source : change.sources()) { - context - .dsl() - .execute( - "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", - source.key()); - } - return null; - }); + // Fresh Account authority initialization already creates these canonical source locks. CountDownLatch started = new CountDownLatch(1); AtomicInteger waitingPid = new AtomicInteger(); try (var executor = Executors.newSingleThreadExecutor()) { @@ -223,11 +212,6 @@ void scopeInsertVersionsAccountBeforeTheExistingParentLockingTrigger() throws Ex "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) VALUES (?, ?, 'WAITING')", change, new byte[] {12}); - context - .dsl() - .execute( - "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", - key); return null; }); CountDownLatch started = new CountDownLatch(1); @@ -1282,11 +1266,13 @@ void rawSqlCannotRecordOwnerProofWithMissingChangedOrExtraSourceParticipation() b.canonicalBytes()); if (sourceShape != 0) { String key = sourceShape == 2 ? source.key() + "/changed" : source.key(); - context - .dsl() - .execute( - "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", - key); + if (!key.equals(source.key())) { + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + key); + } context .dsl() .execute( @@ -1558,12 +1544,15 @@ void issuerSourceKeysPreserveLegacyAndUnicodeIdentityThroughExactByteBound() { assertThat(tx(context, () -> context.repository().requestSourceChange(change))).isFalse(); List exactKeys = binding.sources().stream().map(SourceEvidence::key).toList(); + List lockKeys = new java.util.ArrayList<>(exactKeys); + lockKeys.add("GLOBAL_ROLES:" + base.actorAccountId()); + lockKeys.add("ISSUER:firemud-account-service"); assertThat( context .dsl() .fetch("SELECT source_key FROM account_draft_authorization_source_locks") .getValues(0, String.class)) - .containsExactlyInAnyOrderElementsOf(exactKeys); + .containsExactlyInAnyOrderElementsOf(lockKeys); assertThat( context .dsl() diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java index 8d654aa506..97f266371c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java @@ -61,6 +61,8 @@ void originalPreparedCandidateCommittedAndLostResponseReadBackExactOwnerBytes() Fixture f = new Fixture(c); var prepared = f.prepare(); assertThat(prepared.status).isEqualTo("PREPARED"); + assertThat(prepared.expiresAt).isEqualTo(prepared.issuedAt.plusSeconds(300)); + assertThat(prepared.recoveryExpiry).isEqualTo(prepared.issuedAt.plusSeconds(60)); var candidate = f.candidate(prepared); assertThat(candidate.status).isEqualTo("CANDIDATE"); Transport transport = new Transport(candidate); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java index 48d768676d..057f760b39 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java @@ -73,22 +73,17 @@ void passwordAuthenticatesPersistedCanonicalUuidAndInvalidOrLockedAccountDoesNot account.getEmail(), "wrong-secret"))) .isInstanceOf(AuthenticationException.class); assertThat(c.accountBytes(account.getAccountUuid())).isEqualTo(before); - c.tx( - () -> { - Account locked = c.accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); - locked.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); - return c.accounts.save(locked); - }); - String locked = c.accountBytes(account.getAccountUuid()); + Account lockedAccount = c.account("PASSWORD", AccountLifecycleState.SECURITY_LOCKED); + String locked = c.accountBytes(lockedAccount.getAccountUuid()); assertThatThrownBy( () -> c.tx( () -> c.primary.authenticateControlUiPrimaryIdentity( - account.getEmail(), PASSWORD))) + lockedAccount.getEmail(), PASSWORD))) .isInstanceOf(AuthenticationException.class); - assertThat(c.accountBytes(account.getAccountUuid())).isEqualTo(locked); - assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); + assertThat(c.accountBytes(lockedAccount.getAccountUuid())).isEqualTo(locked); + assertThat(c.challenges.findByAccountId(lockedAccount.getId())).isEmpty(); } @Test @@ -275,6 +270,10 @@ T tx(Supplier action) { } Account account(String modes) { + return account(modes, AccountLifecycleState.ACTIVE); + } + + Account account(String modes, AccountLifecycleState lifecycleState) { return tx( () -> { Account account = new Account(); @@ -283,6 +282,7 @@ Account account(String modes) { account.setEmail(suffix + "@example.test"); account.setPasswordHash(hash(PASSWORD)); account.setLoginAuthModes(modes); + account.setLifecycleState(lifecycleState); return accounts.save(account); }); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java index edc8cc59da..cb62ef5bbc 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java @@ -2,6 +2,7 @@ import java.io.ByteArrayOutputStream; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; @@ -43,7 +44,10 @@ public byte[] canonicalBytes() { out, genesis == null ? new byte[0] : genesis.canonicalBytes()); DraftAuthorizationFenceBinding.frame(out, inheritedCommitId == null ? "false" : "true"); DraftAuthorizationFenceBinding.frame( - out, inheritedCommitId == null ? "" : inheritedCommitId.toString()); + out, + inheritedCommitId == null + ? new byte[0] + : inheritedCommitId.toString().getBytes(StandardCharsets.UTF_8)); DraftAuthorizationFenceBinding.frame(out, expectedEpoch); DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); return out.toByteArray(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 7f5ce3280c..711b3e5d12 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -461,7 +461,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth @Test void selectedDraftPublicationRemainsPendingWithoutItsOriginalOperation() throws Exception { - String tenantId = "9005"; + String tenantId = "9007"; Game game = new Game(); game.setTenantId(tenantId); game.setName("missing-original-operation-proof-game"); diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java new file mode 100644 index 0000000000..58bd89a9aa --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java @@ -0,0 +1,127 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; + +class RealmPolicyApplicationTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID GENESIS_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID INHERITED_COMMIT_ID = + UUID.fromString("77777777-7777-4777-8777-777777777777"); + + @Test + void absentInheritedCommitUsesDeterministicZeroLengthByteFrame() { + RealmPolicyApplication application = freshApplication(); + + byte[] expected = + frames( + text("game-design-realm-policy-application/v1"), + text("true"), + application.genesis().canonicalBytes(), + text("false"), + new byte[0], + text("0"), + application.snapshot().canonicalBytes()); + + byte[] canonicalBytes = application.canonicalBytes(); + assertThat(canonicalBytes).isEqualTo(expected); + assertThat(canonicalBytes).hasSize(expected.length); + assertThat(canonicalBytes).isEqualTo(application.canonicalBytes()); + } + + @Test + void presentInheritedCommitRetainsItsExistingUtf8Frame() { + RealmPolicyApplication application = + new RealmPolicyApplication(null, INHERITED_COMMIT_ID, "0", snapshot()); + + byte[] expected = + frames( + text("game-design-realm-policy-application/v1"), + text("false"), + new byte[0], + text("true"), + text(INHERITED_COMMIT_ID.toString()), + text("0"), + application.snapshot().canonicalBytes()); + + assertThat(application.canonicalBytes()).isEqualTo(expected); + } + + @Test + void missingBothGenesisAndInheritedCommitAndInvalidRequiredTextAreRejected() { + RealmPolicySnapshot snapshot = snapshot(); + + assertThatThrownBy(() -> new RealmPolicyApplication(null, null, "0", snapshot)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new RealmPolicyApplication(freshGenesis(), null, "invalid", snapshot())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static RealmPolicyApplication freshApplication() { + return new RealmPolicyApplication(freshGenesis(), null, "0", snapshot()); + } + + private static RealmPolicyGenesis freshGenesis() { + return new RealmPolicyGenesis(target(), GENESIS_ID, "17"); + } + + private static RealmPolicySnapshot snapshot() { + DraftCommitBinding binding = + DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-commit-0", + List.of(new RevisionPayload("0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION_ID.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + return new RealmPolicySnapshot(binding, "1", List.of()); + } + + private static TargetProof target() { + return new TargetProof( + TENANT_ID, VERSION_ID, 23L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + } + + private static byte[] frames(byte[]... values) { + var output = new ByteArrayOutputStream(); + try { + var data = new DataOutputStream(output); + for (byte[] value : values) { + data.writeInt(value.length); + data.write(value); + } + return output.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static byte[] text(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/mapper/GameInstanceMapper.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/mapper/GameInstanceMapper.java index 24d939a2ee..815b79b379 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/mapper/GameInstanceMapper.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/mapper/GameInstanceMapper.java @@ -20,5 +20,10 @@ public interface GameInstanceMapper { @Mapping(target = "scriptPatchPinnedReason", ignore = true) @Mapping(target = "scriptPatchPinnedControlPlaneRequestId", ignore = true) @Mapping(target = "rowVersion", ignore = true) + @Mapping(target = "runOwnedStartRequestId", ignore = true) + @Mapping(target = "runOwnedStartRequestDigest", ignore = true) + @Mapping(target = "runOwnedStartPublishedReleaseBundleRef", ignore = true) + @Mapping(target = "runOwnedStartPreparingEpoch", ignore = true) + @Mapping(target = "runOwnedStartActiveEpoch", ignore = true) GameInstance toEntity(GameInstanceDto dto); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/mapper/GameInstanceMapperTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/mapper/GameInstanceMapperTest.java index c0de0c3156..5ec9d3fe25 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/mapper/GameInstanceMapperTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/mapper/GameInstanceMapperTest.java @@ -33,7 +33,17 @@ void serverControlledScriptPatchBaseIsIgnoredOnEntityMappingAndExposedOnDtoMappi GameInstance mappedEntity = mapper.toEntity(dto); + assertThat(mappedEntity.getId()).isEqualTo(1L); + assertThat(mappedEntity.getTenantId()).isEqualTo(2L); + assertThat(mappedEntity.getRuntimeVersion()).isEqualTo("runtime-1"); + assertThat(mappedEntity.getScriptPinEpoch()).isNull(); + assertThat(mappedEntity.getScriptPatchPinnedControlPlaneRequestId()).isNull(); assertThat(mappedEntity.getScriptPatchBaseVersionId()).isNull(); + assertThat(mappedEntity.getRunOwnedStartRequestId()).isNull(); + assertThat(mappedEntity.getRunOwnedStartRequestDigest()).isNull(); + assertThat(mappedEntity.getRunOwnedStartPublishedReleaseBundleRef()).isNull(); + assertThat(mappedEntity.getRunOwnedStartPreparingEpoch()).isNull(); + assertThat(mappedEntity.getRunOwnedStartActiveEpoch()).isNull(); GameInstance persistedEntity = new GameInstance(); persistedEntity.setScriptPatchBaseVersionId(99L); From ca415c8eb33a31ef1838af31eb258f883fc73019 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 02:37:56 +1300 Subject: [PATCH 016/129] Add isolated per-Pod readiness and repair creator proof fixtures --- .../firemud/FiremudJooqConventionsPlugin.kt | 132 +- ...ystem-architecture-authz-route-matrix.yaml | 80 + design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 2 +- .../v1/jwt_readiness_pod_receiver.proto | 56 + .../account/v1/jwt_readiness_receiver.proto | 137 + .../account/v1/jwt_readiness_validation.proto | 81 + .../v1/jwt_signer_materialization.proto | 206 ++ .../v1/jwt_readiness_receiver.proto | 37 + services/account-service/build.gradle.kts | 1 + ...tJwtReadinessPodReceiverConfiguration.java | 123 + ...tJwtReadinessPodReceiverWorkloadGuard.java | 104 + ...JwtReadinessPrerequisiteConfiguration.java | 103 + ...ntJwtReadinessProbeOwnerConfiguration.java | 86 + ...ntJwtReadinessProbeOwnerWorkloadGuard.java | 100 + ...untJwtReadinessTransportConfiguration.java | 91 + ...ccountJwtSignerBootstrapConfiguration.java | 87 + .../AccountJwtValidatorInventoryBinding.java | 172 +- .../AccountJwtJwksPublicationRepository.java | 8 +- .../AccountJwtReadinessProbeRepository.java | 1709 ++++++++++++- ...ccountJwtSignerDesiredStateRepository.java | 40 +- ...ccountJwtValidatorInventoryRepository.java | 3 +- .../AccountJwtReadinessTlsInterceptor.java | 106 + ...ntJwtSignerMaterializerTlsInterceptor.java | 73 + ...untJwtReadinessPodReceiverGrpcService.java | 73 + ...ountJwtReadinessProbeOwnerGrpcService.java | 64 + ...ountJwtReadinessValidationGrpcService.java | 124 + ...ccountJwtSignerMaterializationService.java | 739 ++++++ .../AccountControlUiIssuanceRepository.java | 2 +- .../AccountJwtJwksPrepublicationService.java | 935 +++++++ ...wtReadinessGrpcReceiverInvocationPort.java | 502 ++++ ...tJwtReadinessPodLocalIdentityProvider.java | 275 ++ .../AccountJwtReadinessPodReceiverEngine.java | 142 ++ ...untJwtReadinessPodReceiverProtoMapper.java | 253 ++ .../AccountJwtReadinessPodTrustManager.java | 132 + .../AccountJwtReadinessProbeCrypto.java | 279 +++ ...ountJwtReadinessProbeOwnerProtoMapper.java | 216 ++ ...AccountJwtReadinessProbeOwnerSelector.java | 165 ++ .../AccountJwtReadinessProbeOwnerService.java | 62 + .../AccountJwtReadinessProbeService.java | 549 ++++ ...untJwtReadinessReceiverInvocationPort.java | 593 +++++ .../AccountJwtReadinessTransportOwner.java | 427 ++++ .../AccountJwtReadinessValidationService.java | 372 +++ .../AccountJwtSignerBootstrapCoordinator.java | 1115 +++++++++ .../AccountJwtValidatorInventorySource.java | 257 +- ..._account_jwt_readiness_per_pod_closure.sql | 777 ++++++ ...BootstrapConfigurationIntegrationTest.java | 71 + ...PublicationPersistenceIntegrationTest.java | 508 ++++ ...esiredStatePersistenceIntegrationTest.java | 1085 ++++++++ ...orInventoryPersistenceIntegrationTest.java | 259 ++ ...AuthenticationPostgresIntegrationTest.java | 81 +- ...dinessProbePersistenceIntegrationTest.java | 2216 +++++++++++++++++ ...ReadinessPodReceiverWorkloadGuardTest.java | 138 + ...eadinessPrerequisiteConfigurationTest.java | 119 + ...tReadinessProbeOwnerWorkloadGuardTest.java | 138 + ...tJwtReadinessTransportCompositionTest.java | 138 + ...wtReadinessTransportConfigurationTest.java | 269 ++ .../AccountJwtReadinessTrustBindingTest.java | 119 + ...ntJwtSignerBootstrapConfigurationTest.java | 21 + ...countJwtValidatorInventoryBindingTest.java | 293 +++ ...countJwtJwksPublicationRepositoryTest.java | 226 ++ ...ccountJwtReadinessProbeRepositoryTest.java | 133 + ...ntJwtSignerDesiredStateRepositoryTest.java | 748 ++++++ ...ntJwtValidatorInventoryRepositoryTest.java | 169 ++ ...AccountJwtReadinessTlsInterceptorTest.java | 169 ++ ...tSignerMaterializerTlsInterceptorTest.java | 212 ++ ...JwtSignerMaterializerTlsTransportTest.java | 483 ++++ ...JwtReadinessProbeOwnerGrpcServiceTest.java | 148 ++ ...JwtReadinessValidationGrpcServiceTest.java | 82 + ...ntJwtSignerMaterializationServiceTest.java | 1323 ++++++++++ ...countJwtJwksPrepublicationServiceTest.java | 731 ++++++ ...adinessGrpcReceiverInvocationPortTest.java | 751 ++++++ ...ReadinessPodLocalIdentityProviderTest.java | 170 ++ ...ountJwtReadinessPodReceiverEngineTest.java | 569 +++++ ...wtReadinessPodReceiverProtoMapperTest.java | 175 ++ ...JwtReadinessProbeOwnerProtoMapperTest.java | 118 + ...ountJwtReadinessProbeOwnerServiceTest.java | 158 ++ .../AccountJwtReadinessProbeServiceTest.java | 274 ++ ...AccountJwtReadinessTransportOwnerTest.java | 402 +++ ...ountJwtReadinessValidationServiceTest.java | 857 +++++++ ...ountJwtSignerBootstrapCoordinatorTest.java | 1226 +++++++++ ...ccountJwtValidatorInventorySourceTest.java | 828 ++++++ .../draft/IsolatedPublicationOwnerSetup.java | 2 +- .../IsolatedPublicationOperationFixtures.java | 2 +- ...onJwtReadinessProbeOwnerWorkloadGuard.java | 64 + ...sionJwtReadinessReceiverConfiguration.java | 117 + ...sionJwtReadinessLocalIdentityProvider.java | 50 + .../GameSessionJwtReadinessProbeCrypto.java | 226 ++ ...meSessionJwtReadinessProbeOwnerClient.java | 91 + ...SessionJwtReadinessProbeOwnerReadPort.java | 12 + ...essionJwtReadinessProtectedJwksSource.java | 150 ++ ...GameSessionJwtReadinessReceiverEngine.java | 130 + ...essionJwtReadinessReceiverProtoMapper.java | 342 +++ ...essionJwtReadinessReceiverGrpcService.java | 64 + ...tReadinessProbeOwnerWorkloadGuardTest.java | 86 + ...JwtReadinessReceiverConfigurationTest.java | 43 + ...ameSessionJwtReadinessProbeCryptoTest.java | 284 +++ ...SessionJwtReadinessReceiverEngineTest.java | 292 +++ ...onJwtReadinessReceiverProtoMapperTest.java | 153 ++ 99 files changed, 28945 insertions(+), 166 deletions(-) create mode 100644 protos/account/v1/jwt_readiness_pod_receiver.proto create mode 100644 protos/account/v1/jwt_readiness_receiver.proto create mode 100644 protos/account/v1/jwt_readiness_validation.proto create mode 100644 protos/account/v1/jwt_signer_materialization.proto create mode 100644 protos/game-session/v1/jwt_readiness_receiver.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverConfiguration.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverWorkloadGuard.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPrerequisiteConfiguration.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerConfiguration.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerWorkloadGuard.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportConfiguration.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfiguration.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptor.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptor.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessPodReceiverGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessValidationGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverEngine.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverProtoMapper.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodTrustManager.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeCrypto.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapper.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessTransportOwner.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessValidationService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java create mode 100644 services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfigurationIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationPersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStatePersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverWorkloadGuardTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPrerequisiteConfigurationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerWorkloadGuardTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportCompositionTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportConfigurationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBindingTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfigurationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBindingTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptorTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptorTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsTransportTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessValidationGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverEngineTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverProtoMapperTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessTransportOwnerTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessValidationServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinatorTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySourceTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessProbeOwnerWorkloadGuard.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfiguration.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessLocalIdentityProvider.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeCrypto.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerReadPort.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngine.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapper.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverGrpcService.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessProbeOwnerWorkloadGuardTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeCryptoTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngineTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapperTest.java diff --git a/buildSrc/src/main/kotlin/net/firedevops/firemud/FiremudJooqConventionsPlugin.kt b/buildSrc/src/main/kotlin/net/firedevops/firemud/FiremudJooqConventionsPlugin.kt index 2d2900cdb4..55abeb20ba 100644 --- a/buildSrc/src/main/kotlin/net/firedevops/firemud/FiremudJooqConventionsPlugin.kt +++ b/buildSrc/src/main/kotlin/net/firedevops/firemud/FiremudJooqConventionsPlugin.kt @@ -2,14 +2,18 @@ package net.firedevops.firemud import javax.inject.Inject import org.gradle.api.DefaultTask +import org.gradle.api.GradleException import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.api.file.DirectoryProperty import org.gradle.api.provider.Property import org.gradle.api.tasks.Input +import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.OutputFile +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.SourceSetContainer import org.gradle.api.tasks.JavaExec @@ -24,6 +28,8 @@ abstract class FiremudJooqExtension @Inject constructor(project: Project) { val includes: Property = project.objects.property(String::class.java) val migrationGlob: Property = project.objects.property(String::class.java) val outputDirectory: DirectoryProperty = project.objects.directoryProperty() + val accountInventoryMigrationProjection: Property = + project.objects.property(Boolean::class.java).convention(false) } abstract class WriteJooqConfigTask : DefaultTask() { @@ -39,6 +45,12 @@ abstract class WriteJooqConfigTask : DefaultTask() { @get:Input abstract val migrationGlob: Property + @get:Input + abstract val accountInventoryMigrationProjection: Property + + @get:Input + abstract val projectedScriptsPath: Property + @get:Input abstract val scriptsPath: Property @@ -60,7 +72,7 @@ abstract class WriteJooqConfigTask : DefaultTask() { scripts - ${scriptsPath.get()} + ${if (accountInventoryMigrationProjection.get()) projectedScriptsPath.get() else scriptsPath.get()} sort @@ -93,6 +105,103 @@ abstract class WriteJooqConfigTask : DefaultTask() { } } +abstract class PrepareAccountJooqMigrationProjectionTask : DefaultTask() { + @get:Input + abstract val projectionEnabled: Property + + @get:InputDirectory + @get:PathSensitive(PathSensitivity.RELATIVE) + abstract val sourceDirectory: DirectoryProperty + + @get:OutputDirectory + abstract val outputDirectory: DirectoryProperty + + @TaskAction + fun projectMigrations() { + val sourceRoot = sourceDirectory.get().asFile + val outputRoot = outputDirectory.get().asFile + if (!sourceRoot.isDirectory) { + throw GradleException("Account Flyway migration source directory is unavailable") + } + if (outputRoot.exists() && !outputRoot.deleteRecursively()) { + throw GradleException("Account jOOQ migration projection could not be refreshed") + } + if (!outputRoot.mkdirs() && !outputRoot.isDirectory) { + throw GradleException("Account jOOQ migration projection directory is unavailable") + } + + val migrations = sourceRoot.walkTopDown().filter { it.isFile }.toList() + if (migrations.none { it.name == INVENTORY_MIGRATION }) { + throw GradleException("Expected Account validator-inventory migration is missing") + } + migrations.forEach { source -> + val destination = outputRoot.resolve(source.relativeTo(sourceRoot).path) + if (!destination.parentFile.mkdirs() && !destination.parentFile.isDirectory) { + throw GradleException("Account jOOQ migration projection path is unavailable") + } + if (source.name == INVENTORY_MIGRATION) { + destination.writeBytes(projectInventoryMigration(source.readBytes())) + } else { + // Every other migration remains a byte-for-byte copy of Flyway's authority. + destination.writeBytes(source.readBytes()) + } + } + } + + private fun projectInventoryMigration(bytes: ByteArray): ByteArray { + val source = bytes.toString(Charsets.UTF_8) + if (!source.toByteArray(Charsets.UTF_8).contentEquals(bytes)) { + throw GradleException("Account validator-inventory migration is not valid UTF-8") + } + if (source.countOccurrences(IGNORE_END) != 1 + || source.countOccurrences(IGNORE_STOP) != 0 + || source.countOccurrences(INVENTORY_ALTER) != 1) { + throw GradleException("Account validator-inventory migration projection shape changed") + } + val projected = + source + .replace(IGNORE_END, IGNORE_STOP) + .replace(INVENTORY_ALTER, PROJECTED_INVENTORY_ALTERS) + return projected.toByteArray(Charsets.UTF_8) + } + + private fun String.countOccurrences(value: String): Int = split(value).size - 1 + + private companion object { + const val INVENTORY_MIGRATION = "V52__account_jwt_validator_inventory_snapshots.sql" + const val IGNORE_END = "-- [jooq ignore end]" + const val IGNORE_STOP = "-- [jooq ignore stop]" + const val INVENTORY_ALTER = + """ALTER TABLE account_jwt_readiness_probe_plans + ADD COLUMN inventory_snapshot_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_digest_check + CHECK (inventory_snapshot_digest IS NULL + OR inventory_snapshot_digest ~ '^[0-9a-f]{64}$'), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, + kubernetes_namespace, expected_cluster_incarnation_uid, expected_namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT;""" + const val PROJECTED_INVENTORY_ALTERS = + """ALTER TABLE account_jwt_readiness_probe_plans + ADD COLUMN inventory_snapshot_digest VARCHAR(64); +ALTER TABLE account_jwt_readiness_probe_plans + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_digest_check + CHECK (inventory_snapshot_digest IS NULL + OR inventory_snapshot_digest ~ '^[0-9a-f]{64}$'); +ALTER TABLE account_jwt_readiness_probe_plans + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, + kubernetes_namespace, expected_cluster_incarnation_uid, expected_namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT;""" + } +} + class FiremudJooqConventionsPlugin : Plugin { override fun apply(project: Project) = with(project) { plugins.withId("java") { @@ -113,6 +222,17 @@ class FiremudJooqConventionsPlugin : Plugin { migrationGlob.convention("src/main/resources/db/migration/*.sql") outputDirectory.convention(generatedDir) } + val migrationProjectionDirectory = + layout.buildDirectory.dir("tmp/jooq/account-migration-projection") + val migrationProjection = + tasks.register( + "projectAccountJooqMigrations" + ) { + projectionEnabled.set(extension.accountInventoryMigrationProjection) + sourceDirectory.set(layout.projectDirectory.dir("src/main/resources/db/migration")) + outputDirectory.set(migrationProjectionDirectory) + onlyIf { projectionEnabled.get() } + } val jooqCodegen = configurations.create("jooqCodegen") dependencies { @@ -135,6 +255,9 @@ class FiremudJooqConventionsPlugin : Plugin { includes.set(extension.includes) migrationGlob.set(extension.migrationGlob) scriptsPath.set(layout.projectDirectory.asFile.absolutePath + "/" + extension.migrationGlob.get()) + accountInventoryMigrationProjection.set(extension.accountInventoryMigrationProjection) + projectedScriptsPath.set( + migrationProjectionDirectory.map { "${it.asFile.absolutePath}/*.sql" }) outputDirectory.set(extension.outputDirectory) configFile.set(layout.buildDirectory.file("tmp/jooq/config.xml")) } @@ -143,9 +266,16 @@ class FiremudJooqConventionsPlugin : Plugin { group = "jooq" description = "Generate jOOQ sources from Flyway-owned SQL migrations." dependsOn(writeConfig) + dependsOn(migrationProjection) classpath = jooqCodegen mainClass.set("org.jooq.codegen.GenerationTool") inputs.files(fileTree(layout.projectDirectory.dir("src/main/resources/db/migration"))) + inputs.files( + extension.accountInventoryMigrationProjection.map { enabled -> + if (enabled) files(migrationProjectionDirectory) else files() + } + ) + inputs.file(writeConfig.flatMap { it.configFile }) outputs.dir(extension.outputDirectory) val configPath = writeConfig.flatMap { it.configFile }.map { it.asFile.absolutePath } doFirst { diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index a8f6ba0f5d..a6c07608cc 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -3871,6 +3871,86 @@ routes: end_user_token_required: false required_live_checks: [exact_attempt_tuple, committed_pointer_audit_binding, aborted_attempt_future_commit_fence] required_fields: [hold_id, hold_fence, tenant_id, realm_uuid, playable_state_namespace_uuid, playable_state_scope, game_instance_id, version_id, active_lifecycle_epoch, initial_admission_request_id, request_digest, expected_no_prior_pointer, expected_catalog_revision] + - service: account-service + route: GetCurrentReadinessProbeOwner + transport: grpc + classification: internal_workload + route_status: target_not_currently_routable + auth_path: exact_mtls_workload + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [game-session-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/game-session-service"] + end_user_token_required: false + - service: account-service + route: ReceiveReadinessProbe + transport: grpc + classification: internal_workload + route_status: target_not_currently_routable + auth_path: exact_mtls_workload + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [account-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/account-service"] + end_user_token_required: false + - service: account-service + route: IssueReadinessProbes + transport: grpc + classification: internal_workload + route_status: target_not_currently_routable + auth_path: exact_mtls_workload + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [account-jwt-readiness-harness] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/account-jwt-readiness-harness"] + end_user_token_required: false + - service: account-service + route: ValidateReadinessProbe + transport: grpc + classification: internal_workload + route_status: target_not_currently_routable + auth_path: exact_mtls_workload + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [account-jwt-readiness-harness] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/account-jwt-readiness-harness"] + end_user_token_required: false + - service: game-session-service + route: ReceiveReadinessProbe + transport: grpc + classification: internal_workload + route_status: target_not_currently_routable + auth_path: exact_mtls_workload + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [account-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/account-service"] + end_user_token_required: false - service: world-management-service route: AcquireInitialAdmissionBindHold transport: grpc diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index e36ef26754..24ae8c1b84 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -73,3 +73,9 @@ Entry format: - Observation: Comparing migration filenames and bytes alone does not preserve executable proof. Runtime fixture targets and historical before/after migration boundaries must follow the receiving sequence independently. Current repositories may also require tables newer than a deliberately historical fixture. - Expected pattern: Compare explicit Flyway targets alongside every migration remap, preserving genuine historical-row setup and before/after assertions rather than merely advancing every fixture to latest. Inspect saved per-case HTML when uploaded XML or console exceptions omit the underlying SQL error. - Current status: Exact receiving target corrections are in preparation; corrected PostgreSQL execution remains unproved. The separate creator-membership provenance constraint mismatch is not attributed to fixture numbering. + +- `2026-10-08`: Prove derived schema inputs when importing later migrations + - Context: Account schema generation passed before the per-Pod readiness migration, but the new constraint exposed a missing projected column that was already present in the real V52 Flyway migration. The committed donor carried a narrowly scoped jOOQ projection that had initially been omitted as unnecessary. + - Observation: Successful earlier generation did not prove the simulator had represented every migration. V52's ignore-marker spelling hid its later ALTER from jOOQ; the donor projection also split that compound ALTER for simulation. + - Expected pattern: Preserve required build-input transformations with an imported capability, compare the generated input against its canonical migration sources, and distinguish simulator omissions from production schema gaps. Do not remove database constraints or add duplicate runtime columns to conceal projection drift. + - Current status: The selective Account projection restores schema generation and changes only V52's derived input; Flyway sources remain unchanged. This proves code generation, not PostgreSQL migration execution or readiness activation. 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 053767754d..91a158efa0 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 @@ -10,7 +10,7 @@ The current Gameplay-prerequisite construction remains non-activating. Full-vers The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. At `ed928219ee3428073910f1845eaa975e8814a30a`, local validation is complete for the held-order/source-fencing batch, but physical PostgreSQL validation was skipped. No authenticated terms-notice producer/receiver, durable prepare-before-disclose handoff, or physical World deadline gate is implemented; there is no production disclosure/currentness path. Reconsider only after focused PostgreSQL proof covers both orderings of preparation versus original `COMMIT_ORDER` acquisition and settlement, every deadline-introduction path including environment binding, exact retry/restart/ambiguous-notice readback, and World commit-time denial at the disclosed instant without early ordinary-authoring freeze or date rewriting. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. -Creator issuance preserves the existing OTP failure budget by committing a primary-authentication denial's accounting before returning the credential error; successful OTP consumption still rolls back if subsequent preparation fails. Its real PostgreSQL definitions use the primary hook's Spring transaction interceptor, not only a direct method call. Positive issuance and original-signer rotation proof are additionally blocked by Account's current readiness owner: validator inventory is always incomplete, and a complete claim without protected per-validator evidence is quarantined. No real committed signer can be produced through that owner path yet; synthetic signer fixtures cannot close the original APPLIED/release prerequisite. The broader JWT capability remains owned by [Shared Runtime Contracts](./shared-runtime-contracts-and-persistence.md). +Creator issuance preserves the existing OTP failure budget by committing a primary-authentication denial's accounting before returning the credential error; successful OTP consumption still rolls back if subsequent preparation fails. Its real PostgreSQL definitions use the primary hook's Spring transaction interceptor, not only a direct method call. The construction now includes a selective Account per-Pod readiness/receipt closure and commit-bound signer coordinator, together with a default-inactive Game Session receiver using production cryptographic profile validation and exact Account owner readback. These sources do not establish a production signer: protected Game Session local identity, isolated route wiring, current inventory and mounted correspondence, physical PostgreSQL proof, and live convergence/promotion remain open. A complete claim without protected per-validator evidence remains quarantined; synthetic signer fixtures cannot close the original APPLIED/release prerequisite. Password and wrong-secret PostgreSQL proof is separate from restricted-account authentication: the latter has unit coverage, while an authentic owner lifecycle transition needed for its physical fixture remains unavailable. The broader JWT capability remains owned by [Shared Runtime Contracts](./shared-runtime-contracts-and-persistence.md). This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. diff --git a/protos/account/v1/jwt_readiness_pod_receiver.proto b/protos/account/v1/jwt_readiness_pod_receiver.proto new file mode 100644 index 0000000000..7ac3bf27eb --- /dev/null +++ b/protos/account/v1/jwt_readiness_pod_receiver.proto @@ -0,0 +1,56 @@ +syntax = "proto3"; + +package account.v1; + +import "account/v1/jwt_readiness_receiver.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Isolated Account-Pod receiver for one exact, non-authorizing pending-key probe. +service AccountJwtReadinessPodReceiverService { + rpc ReceiveReadinessProbe(ReceiveAccountJwtReadinessProbeRequest) + returns (ReceiveAccountJwtReadinessProbeResponse); +} + +message ReceiveAccountJwtReadinessProbeRequest { + int32 schema_version = 1; + ReadinessProbeCoordinates coordinates = 2; + string compact_jwt = 3; +} + +// Receiver-derived identity. Unlike the shared caller identity, the trust revision is opaque +// because Account's protected JWKS binding uses a string revision. +message AccountJwtPodReceiverIdentity { + string validator_id = 1; + string deployment_uid = 2; + string pod_uid = 3; + string pod_ip = 4; + string direct_pod_endpoint = 5; + string canonical_service_uri = 6; + string image = 7; + string verifier_config_sha256 = 8; + string applicability_matrix_digest = 9; + string source_inventory_revision = 10; + string source_inventory_digest = 11; + string server_leaf_spki_sha256 = 12; + AccountSourceIdentity account_jwks_source_identity = 13; + string jwks_trust_binding_revision = 14; +} + +message ReceiveAccountJwtReadinessProbeResponse { + enum ObservationOutcome { + OBSERVATION_OUTCOME_UNSPECIFIED = 0; + VERIFIED = 1; + INAPPLICABLE_REJECT = 2; + } + + int32 schema_version = 1; + ReadinessProbeCoordinates coordinates = 2; + string compact_token_sha256 = 3; + string verified_key_id = 4; + AccountJwtPodReceiverIdentity receiver_identity = 5; + AccountPodTargetBinding account_pod_target = 6; + int64 observed_at_epoch_seconds = 7; + ObservationOutcome outcome = 8; +} diff --git a/protos/account/v1/jwt_readiness_receiver.proto b/protos/account/v1/jwt_readiness_receiver.proto new file mode 100644 index 0000000000..1951c87ba6 --- /dev/null +++ b/protos/account/v1/jwt_readiness_receiver.proto @@ -0,0 +1,137 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Authenticated read-only owner lookup used by one isolated Game Session Pod receiver. +// The request contains a hash, never the transient compact JWT. +service AccountJwtReadinessProbeOwnerService { + rpc GetCurrentReadinessProbeOwner(GetCurrentReadinessProbeOwnerRequest) + returns (GetCurrentReadinessProbeOwnerResponse); +} + +message ReadinessProbeCoordinates { + enum ProbeKind { + PROBE_KIND_UNSPECIFIED = 0; + CANARY = 1; + REPRESENTATIVE = 2; + } + enum ExpectedOutcome { + EXPECTED_OUTCOME_UNSPECIFIED = 0; + ACCEPT = 1; + INAPPLICABLE_REJECT = 2; + } + enum ExpectedActiveState { + EXPECTED_ACTIVE_STATE_UNSPECIFIED = 0; + PRESENT = 1; + ABSENT = 2; + UNKNOWN = 3; + } + + string rotation_operation_id = 1; + string operation_digest = 2; + string plan_digest = 3; + int32 plan_version = 4; + int32 registry_version = 5; + string validator_id = 6; + string token_profile = 7; + string audience = 8; + ProbeKind probe_kind = 9; + ExpectedOutcome expected_outcome = 10; + string jti = 11; + int64 entry_version = 12; + string target_generation = 13; + string target_kid = 14; + ExpectedActiveState expected_active_state = 15; + string expected_active_generation = 16; + string expected_active_kid = 17; + int64 issued_at_epoch_seconds = 18; + int64 expires_at_epoch_seconds = 19; + int64 plan_expires_at_epoch_seconds = 20; +} + +message AccountSourceIdentity { + string environment_id = 1; + string cluster_id = 2; + string cluster_incarnation_uid = 3; + string namespace = 4; + string namespace_uid = 5; + string config_map_uid = 6; + string binding_revision = 7; + string api_server_origin = 8; + string serving_ca_sha256 = 9; +} + +// Caller-supplied protected local context. Account compares its target-relevant fields with its +// independent current inventory but must not echo this whole message as owner evidence. +message ReadinessReceiverLocalIdentity { + string validator_id = 1; + string deployment_uid = 2; + string pod_uid = 3; + string pod_ip = 4; + string direct_pod_endpoint = 5; + string canonical_service_uri = 6; + string image = 7; + string verifier_config_sha256 = 8; + string applicability_matrix_digest = 9; + string source_inventory_revision = 10; + string source_inventory_digest = 11; + string server_leaf_spki_sha256 = 12; + AccountSourceIdentity account_jwks_source_identity = 13; + int64 account_jwks_trust_config_revision = 14; +} + +// Account's current API/inventory source pins and Pod target. These are not Game Session's +// verifier-source inventory pins or its Account-JWKS trust-source identity. +message AccountPodTargetBinding { + string inventory_snapshot_digest = 1; + string environment_id = 2; + string cluster_id = 3; + string cluster_incarnation_uid = 4; + string namespace = 5; + string namespace_uid = 6; + string api_binding_revision = 7; + string api_binding_digest = 8; + string inventory_binding_revision = 9; + string inventory_binding_digest = 10; + string validator_id = 11; + string deployment_uid = 12; + string pod_uid = 13; + string pod_ip = 14; + string image = 15; + string verifier_config_sha256 = 16; + string applicability_matrix_digest = 17; + ReadinessProbeCoordinates.ExpectedOutcome expected_outcome = 18; + string direct_pod_endpoint = 19; + string canonical_service_uri = 20; + string server_leaf_spki_sha256 = 21; +} + +message GetCurrentReadinessProbeOwnerRequest { + int32 schema_version = 1; + ReadinessProbeCoordinates expected_coordinates = 2; + string compact_token_sha256 = 3; + ReadinessReceiverLocalIdentity protected_local_identity = 4; +} + +message GetCurrentReadinessProbeOwnerResponse { + enum ProbeState { + PROBE_STATE_UNSPECIFIED = 0; + ISSUED = 1; + VERIFIED = 2; + RETIRED = 3; + CLEANED = 4; + EXPIRED = 5; + ABORTED = 6; + } + + int32 schema_version = 1; + bool owner_record_found = 2; + ReadinessProbeCoordinates current_coordinates = 3; + string compact_token_sha256 = 4; + ProbeState current_state = 5; + AccountPodTargetBinding current_pod_target = 7; + reserved 6; +} diff --git a/protos/account/v1/jwt_readiness_validation.proto b/protos/account/v1/jwt_readiness_validation.proto new file mode 100644 index 0000000000..ee00a6d233 --- /dev/null +++ b/protos/account/v1/jwt_readiness_validation.proto @@ -0,0 +1,81 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Non-authorizing validation of one exact Account-owned pending-key readiness probe. This route +// is separately mTLS-pinned and remains absent unless its explicit opt-in is enabled. +service AccountJwtReadinessValidationService { + rpc IssueReadinessProbes(IssueReadinessProbesRequest) + returns (IssueReadinessProbesResponse); + rpc ValidateReadinessProbe(ValidateReadinessProbeRequest) + returns (ValidateReadinessProbeResponse); +} + +message IssueReadinessProbesRequest { + int32 schema_version = 1; +} + +message IssueReadinessProbesResponse { + message ActiveSignerFence { + string generation = 1; + string kid = 2; + } + + message Probe { + string validator_id = 1; + string token_profile = 2; + string audience = 3; + string probe_kind = 4; + string jti = 5; + string target_generation = 6; + string target_kid = 7; + int32 registry_version = 8; + int64 entry_version = 9; + int64 issued_at_epoch_seconds = 10; + int64 expires_at_epoch_seconds = 11; + string compact_token_sha256 = 12; + string compact_jwt = 13; + } + + int32 schema_version = 1; + string rotation_operation_id = 2; + string plan_digest = 3; + int32 plan_version = 4; + int64 planned_at_epoch_seconds = 5; + int64 not_before_epoch_seconds = 6; + int64 expires_at_epoch_seconds = 7; + string target_generation = 8; + string target_kid = 9; + ActiveSignerFence expected_active = 10; + repeated Probe probes = 11; + bool validator_inventory_complete = 12; +} + +message ValidateReadinessProbeRequest { + int32 schema_version = 1; + string rotation_operation_id = 2; + string validator_id = 3; + string token_profile = 4; + string audience = 5; + string probe_kind = 6; + string jti = 7; + string compact_jwt = 8; +} + +message ValidateReadinessProbeResponse { + enum Result { + RESULT_UNSPECIFIED = 0; + NON_AUTHORIZING_VERIFICATION_RECORDED = 1; + } + + int32 schema_version = 1; + Result result = 2; + int32 receipt_version = 3; + string receipt_sha256 = 4; + int64 observed_at_epoch_seconds = 5; + string validator_id = 6; + string validator_instance_id = 7; +} diff --git a/protos/account/v1/jwt_signer_materialization.proto b/protos/account/v1/jwt_signer_materialization.proto new file mode 100644 index 0000000000..12d647a48a --- /dev/null +++ b/protos/account/v1/jwt_signer_materialization.proto @@ -0,0 +1,206 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// This exact authenticated peer performs only fixed-name Secret observation, pending-slot key +// generation, and an operation-bound private-slot transition after Account durably authorizes a +// PREPARED promotion. Account alone prepares/commits/promotes the lifecycle and publishes JWKS. +service AccountJwtSignerMaterializationService { + rpc EnrollBootstrap(EnrollBootstrapRequest) returns (EnrollBootstrapResponse); + rpc GetCurrentGenerationRequest(GetCurrentGenerationRequestRequest) + returns (GetCurrentGenerationRequestResponse); + rpc RecordSecretObservation(RecordSecretObservationRequest) + returns (GetCurrentGenerationRequestResponse); + rpc RecordGenerationResult(RecordGenerationResultRequest) + returns (RecordGenerationResultResponse); + rpc GetCurrentPromotionRequest(GetCurrentPromotionRequestRequest) + returns (GetCurrentPromotionRequestResponse); + rpc RecordPrivatePromotionResult(RecordPrivatePromotionResultRequest) + returns (RecordPrivatePromotionResultResponse); +} + +// Selector-free, authenticated bootstrap enrollment. The acknowledgment contains only pinned +// identities and the fixed public ConfigMap observation; it carries no private material or +// lifecycle selection authority. +message EnrollBootstrapRequest { + int32 schema_version = 1; +} + +message EnrollBootstrapResponse { + int32 schema_version = 1; + string environment_id = 2; + string cluster_id = 3; + string namespace = 4; + string expected_cluster_incarnation_uid = 5; + string expected_namespace_uid = 6; + string materializer_trust_binding_digest = 7; + string materializer_trust_config_revision = 8; + string api_binding_digest = 9; + string api_config_revision = 10; + string api_server_url = 11; + string api_tls_server_name = 12; + string api_serving_ca_sha256 = 13; + string api_expected_username = 14; + string private_secret_name = 15; + string public_config_map_name = 16; + string public_config_map_uid = 17; + string public_config_map_resource_version = 18; + string public_config_map_snapshot_digest = 19; +} + +message ActiveSigner { + string generation = 1; + string kid = 2; +} + +message GetCurrentGenerationRequestRequest { + int32 schema_version = 1; +} + +message GetCurrentGenerationRequestResponse { + enum Phase { + PHASE_UNSPECIFIED = 0; + OBSERVE_PRIVATE_SECRET = 1; + GENERATE_PENDING = 2; + GENERATION_RECORDED = 3; + } + + int32 schema_version = 1; + Phase phase = 2; + string operation_id = 3; + string operation_digest = 4; + string generation_request_digest = 5; + string desired_state_version = 6; + string environment_id = 7; + string cluster_id = 8; + string namespace = 9; + string expected_cluster_incarnation_uid = 10; + string expected_namespace_uid = 11; + string trust_binding_digest = 12; + string trust_config_revision = 13; + string private_secret_name = 14; + string target_generation = 15; + string target_kid = 16; + string target_algorithm = 17; + string operation_action = 18; + repeated string allowed_private_slots = 19; + ActiveSigner expected_active = 20; + string secret_uid = 21; + string expected_secret_resource_version = 22; + string generation_receipt_digest = 23; + string public_key_fingerprint = 24; + string public_jwk_json = 25; + string observed_secret_resource_version = 26; + ActiveSigner expected_published_active = 27; +} + +message RecordSecretObservationRequest { + int32 schema_version = 1; + string operation_id = 2; + string operation_digest = 3; + string secret_uid = 4; + string observed_resource_version = 5; +} + +message RecordGenerationResultRequest { + int32 schema_version = 1; + string operation_id = 2; + string generation_request_digest = 3; + string secret_uid = 4; + string expected_prior_resource_version = 5; + string observed_resource_version = 6; + // Exactly one bounded public RSA JWK; private RSA members and arbitrary resource names are not + // part of this schema. Account validates and canonicalizes the JWK and derives its fingerprint. + string public_jwk_json = 7; +} + +message RecordGenerationResultResponse { + int32 schema_version = 1; + string operation_id = 2; + string operation_digest = 3; + string generation_request_digest = 4; + string generation_receipt_digest = 5; + string desired_state_version = 6; + string environment_id = 7; + string cluster_id = 8; + string namespace = 9; + string expected_cluster_incarnation_uid = 10; + string expected_namespace_uid = 11; + string trust_binding_digest = 12; + string trust_config_revision = 13; + string private_secret_name = 14; + string secret_uid = 15; + string expected_prior_resource_version = 16; + string observed_resource_version = 17; + string target_generation = 18; + string target_kid = 19; + string target_algorithm = 20; + string public_key_fingerprint = 21; + string public_jwk_json = 22; +} + +// Account-authorized fixed-Secret slot transition. This peer response contains public identity +// fences only; it never selects or publishes the Account-owned JWKS ConfigMap and never commits +// the Account lifecycle. +message GetCurrentPromotionRequestRequest { + int32 schema_version = 1; +} + +message GetCurrentPromotionRequestResponse { + int32 schema_version = 1; + string promotion_operation_id = 2; + string promotion_request_digest = 3; + string generation_operation_id = 4; + string generation_operation_digest = 5; + string generation_receipt_digest = 6; + string environment_id = 7; + string cluster_id = 8; + string namespace = 9; + string expected_cluster_incarnation_uid = 10; + string expected_namespace_uid = 11; + string trust_binding_digest = 12; + string trust_config_revision = 13; + string private_secret_name = 14; + string target_generation = 15; + string target_kid = 16; + string target_algorithm = 17; + string target_public_key_fingerprint = 18; + string expected_secret_uid = 19; + string expected_secret_resource_version = 20; + string expected_previous_generation = 21; + string expected_previous_kid = 22; + string expected_previous_public_key_fingerprint = 23; + repeated string allowed_private_slots = 24; + string operation_action = 25; +} + +message PromotionPublicKeyIdentity { + string generation = 1; + string kid = 2; + string public_key_fingerprint = 3; +} + +message RecordPrivatePromotionResultRequest { + int32 schema_version = 1; + string promotion_operation_id = 2; + string promotion_request_digest = 3; + string generation_operation_id = 4; + string generation_operation_digest = 5; + string secret_uid = 6; + string expected_prior_resource_version = 7; + string observed_resource_version = 8; + PromotionPublicKeyIdentity current = 9; + PromotionPublicKeyIdentity previous = 10; + repeated string resulting_slots = 11; +} + +message RecordPrivatePromotionResultResponse { + int32 schema_version = 1; + string promotion_operation_id = 2; + string generation_operation_id = 3; + string observed_resource_version = 4; + string public_receipt_digest = 5; +} diff --git a/protos/game-session/v1/jwt_readiness_receiver.proto b/protos/game-session/v1/jwt_readiness_receiver.proto new file mode 100644 index 0000000000..17b03ad694 --- /dev/null +++ b/protos/game-session/v1/jwt_readiness_receiver.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; + +package game_session.v1; + +import "account/v1/jwt_readiness_receiver.proto"; + +option java_package = "net.firedevops.firemud.gamesession.v1"; +option java_multiple_files = true; + +// Isolated non-authorizing JWT readiness verification on the exact Game Session Pod. +service GameSessionJwtReadinessReceiverService { + rpc ReceiveReadinessProbe(ReceiveReadinessProbeRequest) + returns (ReceiveReadinessProbeResponse); +} + +message ReceiveReadinessProbeRequest { + int32 schema_version = 1; + account.v1.ReadinessProbeCoordinates coordinates = 2; + string compact_jwt = 3; +} + +message ReceiveReadinessProbeResponse { + enum ObservationOutcome { + OBSERVATION_OUTCOME_UNSPECIFIED = 0; + VERIFIED = 1; + INAPPLICABLE_REJECT = 2; + } + + int32 schema_version = 1; + account.v1.ReadinessProbeCoordinates coordinates = 2; + string compact_token_sha256 = 3; + string verified_key_id = 4; + account.v1.ReadinessReceiverLocalIdentity receiver_identity = 5; + account.v1.AccountPodTargetBinding account_pod_target = 6; + int64 observed_at_epoch_seconds = 7; + ObservationOutcome outcome = 8; +} diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 88999a5ba1..30a8ee9034 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -10,6 +10,7 @@ plugins { firemudJooq { packageName.set("net.firedevops.firemud.accountservice.jooq") + accountInventoryMigrationProjection.set(true) } dependencies { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverConfiguration.java new file mode 100644 index 0000000000..0453b0bbef --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverConfiguration.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.accountservice.config; + +import java.time.Clock; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessPodLocalIdentityProvider; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessPodReceiverEngine; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessPodReceiverProtoMapper; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeCrypto; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Default-false composition of Account's actual isolated per-Pod JWT readiness receiver. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.account.jwt-readiness.pod-receiver", + name = "enabled", + havingValue = "true") +@Conditional( + AccountJwtReadinessPrerequisiteConfiguration.ProtectedReadinessConfigurationPresent.class) +@Lazy +public class AccountJwtReadinessPodReceiverConfiguration { + @Bean + @Lazy + @ConditionalOnMissingBean(AccountJwtValidatorInventoryBinding.class) + public AccountJwtValidatorInventoryBinding accountJwtPodReceiverInventoryBinding() { + return new AccountJwtValidatorInventoryBinding( + true, AccountJwtValidatorInventoryBinding.PROTECTED_BINDING_PATH.toString()); + } + + @Bean + @Lazy + @ConditionalOnMissingBean(AccountJwtValidatorInventorySource.class) + public AccountJwtValidatorInventorySource accountJwtPodReceiverInventorySource( + @Qualifier("accountJwtReadinessJwksApiBinding") AccountJwtJwksApiBinding apiBinding, + AccountJwtValidatorInventoryBinding inventoryBinding) { + return new AccountJwtValidatorInventorySource(apiBinding, inventoryBinding, Clock.systemUTC()); + } + + @Bean + @Lazy + @ConditionalOnMissingBean(AccountJwtReadinessProbeService.class) + public AccountJwtReadinessProbeService accountJwtPodReceiverProbeService( + AccountJwtReadinessProbeRepository repository, + AccountJwtValidatorInventorySource inventorySource, + PlatformTransactionManager transactionManager) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setReadOnly(false); + return new AccountJwtReadinessProbeService( + repository, transaction, Clock.systemUTC(), inventorySource); + } + + @Bean + @Lazy + public AccountJwtReadinessPodReceiverWorkloadGuard accountJwtPodReceiverWorkloadGuard( + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + @Qualifier("accountJwtReadinessJwksApiBinding") AccountJwtJwksApiBinding apiBinding, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new AccountJwtReadinessPodReceiverWorkloadGuard( + materializerTrustBinding, apiBinding, workloadNamespace); + } + + @Bean + @Lazy + public AccountJwtReadinessPodLocalIdentityProvider accountJwtPodLocalIdentityProvider( + AccountJwtValidatorInventorySource inventorySource, + @Qualifier("accountJwtReadinessTrustedJwksSource") + AccountJwtJwksTrustedSource trustedJwksSource, + SslBundles sslBundles) { + return new AccountJwtReadinessPodLocalIdentityProvider( + inventorySource, + trustedJwksSource, + sslBundles, + Clock.systemUTC(), + System.getenv("HOSTNAME")); + } + + @Bean + @Lazy + public AccountJwtReadinessPodReceiverProtoMapper accountJwtPodReceiverProtoMapper() { + return new AccountJwtReadinessPodReceiverProtoMapper(); + } + + @Bean + @Lazy + public AccountAsymmetricJwtVerifier accountJwtPodReceiverProductionVerifier( + @Qualifier("accountJwtReadinessTrustedJwksSource") + AccountJwtJwksTrustedSource trustedJwksSource) { + return AccountJwtReadinessProbeCrypto.createVerifier(trustedJwksSource, Clock.systemUTC()); + } + + @Bean + @Lazy + public AccountJwtReadinessPodReceiverEngine accountJwtPodReceiverEngine( + AccountJwtReadinessProbeService probeService, + AccountJwtReadinessPodReceiverWorkloadGuard workloadGuard, + AccountJwtReadinessPodLocalIdentityProvider localIdentityProvider, + AccountJwtReadinessPodReceiverProtoMapper protoMapper, + @Qualifier("accountJwtPodReceiverProductionVerifier") AccountAsymmetricJwtVerifier verifier, + @Value("${firemud.account.jwt-readiness.pod-receiver.max-control-ui-tenant-scopes}") + int maxControlUiTenantScopes) { + return new AccountJwtReadinessPodReceiverEngine( + probeService, + workloadGuard, + localIdentityProvider, + protoMapper, + verifier, + Clock.systemUTC(), + maxControlUiTenantScopes); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverWorkloadGuard.java new file mode 100644 index 0000000000..f0a5711d67 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverWorkloadGuard.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.accountservice.config; + +import java.util.Objects; +import java.util.Optional; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Exact method-local mTLS authorization for Account's own-Pod readiness receiver. */ +public final class AccountJwtReadinessPodReceiverWorkloadGuard { + private static final String ACCOUNT_SERVICE = "account-service"; + + private final Supplier> materializerBinding; + private final Supplier apiBinding; + private final String localWorkloadNamespace; + + public AccountJwtReadinessPodReceiverWorkloadGuard( + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksApiBinding apiBinding, + String localWorkloadNamespace) { + this( + () -> Objects.requireNonNull(materializerTrustBinding).current(), + () -> Objects.requireNonNull(apiBinding).current(), + localWorkloadNamespace); + } + + AccountJwtReadinessPodReceiverWorkloadGuard( + Supplier> materializerBinding, + Supplier apiBinding, + String localWorkloadNamespace) { + this.materializerBinding = Objects.requireNonNull(materializerBinding); + this.apiBinding = Objects.requireNonNull(apiBinding); + this.localWorkloadNamespace = localWorkloadNamespace == null ? "" : localWorkloadNamespace; + } + + /** Re-reads both protected Account bindings and requires the exact local Account SPIFFE peer. */ + public AuthenticatedCaller requireAccountReceiverCaller() { + Binding account = materializerBinding.get().orElseThrow(ReceiverCallerDeniedException::new); + AccountJwtJwksApiBinding.ParsedBinding api; + try { + api = apiBinding.get(); + } catch (RuntimeException unavailable) { + throw new ReceiverCallerDeniedException(); + } + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (api == null + || !sameProtectedAccountIdentity(account, api) + || !GrpcPeerIdentity.isValidNamespace(localWorkloadNamespace) + || !localWorkloadNamespace.equals(account.namespace()) + || peer == null + || !ACCOUNT_SERVICE.equals(peer.service()) + || !account.namespace().equals(peer.namespace()) + || !("spiffe://firemud/ns/" + account.namespace() + "/sa/" + ACCOUNT_SERVICE) + .equals(peer.uri()) + || hasSessionContext()) { + throw new ReceiverCallerDeniedException(); + } + return new AuthenticatedCaller(account, api); + } + + /** Rejects protected trust changes across token verification and owner reread. */ + public void requireUnchanged(AuthenticatedCaller before) { + Objects.requireNonNull(before, "Initial authenticated caller snapshot is required"); + AuthenticatedCaller after = requireAccountReceiverCaller(); + if (!before.accountBinding().equals(after.accountBinding()) + || !before.apiBinding().equals(after.apiBinding())) { + throw new ReceiverCallerDeniedException(); + } + } + + private static boolean sameProtectedAccountIdentity( + Binding account, AccountJwtJwksApiBinding.ParsedBinding api) { + return account.environmentId().equals(api.environmentId()) + && account.clusterId().equals(api.clusterId()) + && account.namespace().equals(api.namespace()) + && account.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + && account.expectedNamespaceUid().equals(api.expectedNamespaceUid()); + } + + private static boolean hasSessionContext() { + return SessionContext.getAccountId() != null + || !SessionContext.getGlobalRoles().isEmpty() + || !SessionContext.getScopedRolesMap().isEmpty() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null; + } + + /** Immutable protected trust snapshot captured only after the authenticated peer check. */ + public record AuthenticatedCaller( + Binding accountBinding, AccountJwtJwksApiBinding.ParsedBinding apiBinding) { + public AuthenticatedCaller { + Objects.requireNonNull(accountBinding); + Objects.requireNonNull(apiBinding); + } + } + + public static final class ReceiverCallerDeniedException extends SecurityException { + public ReceiverCallerDeniedException() { + super("Authenticated same-namespace Account workload is required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPrerequisiteConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPrerequisiteConfiguration.java new file mode 100644 index 0000000000..d84214ef9d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPrerequisiteConfiguration.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.accountservice.config; + +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Condition; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.core.env.Environment; +import org.springframework.core.type.AnnotatedTypeMetadata; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Default-inactive, readiness-only prerequisite graph for Account's protected public-JWKS reads. + * + *

This configuration checks explicit selection only. The protected API and materializer bindings + * remain responsible for validating their actual protected files whenever used. + */ +@Configuration(proxyBeanMethods = false) +@Conditional( + AccountJwtReadinessPrerequisiteConfiguration.ProtectedReadinessConfigurationPresent.class) +@Lazy +public class AccountJwtReadinessPrerequisiteConfiguration { + private static final String READINESS_VALIDATION_ENABLED = + "firemud.account.jwt-readiness.validation.enabled"; + private static final String READINESS_PROBE_OWNER_ENABLED = + "firemud.account.jwt-readiness.probe-owner.enabled"; + private static final String READINESS_POD_RECEIVER_ENABLED = + "firemud.account.jwt-readiness.pod-receiver.enabled"; + private static final String JWKS_API_ENABLED = "firemud.account.jwt-jwks-api.enabled"; + private static final String JWKS_API_BINDING = + "firemud.account.jwt-jwks-api.protected-binding-path"; + private static final String MATERIALIZATION_ENABLED = + "firemud.account.jwt-signer.materialization.enabled"; + private static final String MATERIALIZER_BINDING = + "firemud.account.jwt-signer.materialization.protected-binding-path"; + private static final String WORKLOAD_NAMESPACE = "firemud.grpc.workload-namespace"; + private static final String EXPECTED_JWKS_API_BINDING = + "/etc/firemud/account-jwt-api/binding.json"; + private static final String EXPECTED_MATERIALIZER_BINDING = + "/etc/firemud/account-jwt-materializer/binding.json"; + + @Bean(name = "accountJwtReadinessJwksApiBinding") + @Lazy + public AccountJwtJwksApiBinding accountJwtReadinessJwksApiBinding() { + return new AccountJwtJwksApiBinding(true, EXPECTED_JWKS_API_BINDING); + } + + @Bean(name = "accountJwtReadinessJwksConfigMapClient") + @Lazy + public AccountJwtJwksConfigMapClient accountJwtReadinessJwksConfigMapClient( + @Qualifier("accountJwtReadinessJwksApiBinding") AccountJwtJwksApiBinding apiBinding) { + return new AccountJwtJwksConfigMapClient(apiBinding); + } + + @Bean(name = "accountJwtReadinessTrustedJwksSource") + @Lazy + public AccountJwtJwksTrustedSource accountJwtReadinessTrustedJwksSource( + @Qualifier("accountJwtReadinessJwksConfigMapClient") + AccountJwtJwksConfigMapClient configMapClient, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + PlatformTransactionManager transactionManager) { + return new AccountJwtJwksTrustedSource( + configMapClient, + materializerTrustBinding, + desiredStateRepository, + publicationRepository, + transactionManager); + } + + /** Checks readiness selection and exact protected-binding paths, not protected file contents. */ + public static final class ProtectedReadinessConfigurationPresent implements Condition { + @Override + public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { + Environment environment = context.getEnvironment(); + boolean readinessEnabled = + explicitlyEnabled(environment, READINESS_VALIDATION_ENABLED) + || explicitlyEnabled(environment, READINESS_PROBE_OWNER_ENABLED) + || explicitlyEnabled(environment, READINESS_POD_RECEIVER_ENABLED); + if (!readinessEnabled + || !explicitlyEnabled(environment, JWKS_API_ENABLED) + || !EXPECTED_JWKS_API_BINDING.equals(environment.getProperty(JWKS_API_BINDING)) + || !explicitlyEnabled(environment, MATERIALIZATION_ENABLED) + || !EXPECTED_MATERIALIZER_BINDING.equals(environment.getProperty(MATERIALIZER_BINDING))) { + return false; + } + + return GrpcPeerIdentity.isValidNamespace(environment.getProperty(WORKLOAD_NAMESPACE)); + } + + private static boolean explicitlyEnabled(Environment environment, String property) { + return "true".equals(environment.getProperty(property)); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerConfiguration.java new file mode 100644 index 0000000000..8d4e15c1a5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerConfiguration.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.accountservice.config; + +import java.time.Clock; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerProtoMapper; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Default-false composition for the isolated exact-probe owner lookup RPC. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.account.jwt-readiness.probe-owner", + name = "enabled", + havingValue = "true") +@Conditional( + AccountJwtReadinessPrerequisiteConfiguration.ProtectedReadinessConfigurationPresent.class) +@Lazy +public class AccountJwtReadinessProbeOwnerConfiguration { + @Bean + @Lazy + @ConditionalOnMissingBean(AccountJwtValidatorInventoryBinding.class) + public AccountJwtValidatorInventoryBinding accountJwtValidatorInventoryBinding() { + return new AccountJwtValidatorInventoryBinding( + true, AccountJwtValidatorInventoryBinding.PROTECTED_BINDING_PATH.toString()); + } + + @Bean + @Lazy + @ConditionalOnMissingBean(AccountJwtValidatorInventorySource.class) + public AccountJwtValidatorInventorySource accountJwtValidatorInventorySource( + @Qualifier("accountJwtReadinessJwksApiBinding") AccountJwtJwksApiBinding apiBinding, + AccountJwtValidatorInventoryBinding inventoryBinding) { + return new AccountJwtValidatorInventorySource(apiBinding, inventoryBinding, Clock.systemUTC()); + } + + @Bean + @Lazy + @ConditionalOnMissingBean(AccountJwtReadinessProbeService.class) + public AccountJwtReadinessProbeService accountJwtReadinessProbeService( + AccountJwtReadinessProbeRepository repository, + AccountJwtValidatorInventorySource inventorySource, + PlatformTransactionManager transactionManager) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setReadOnly(false); + return new AccountJwtReadinessProbeService( + repository, transaction, Clock.systemUTC(), inventorySource); + } + + @Bean + @Lazy + public AccountJwtReadinessProbeOwnerProtoMapper accountJwtReadinessProbeOwnerProtoMapper() { + return new AccountJwtReadinessProbeOwnerProtoMapper(); + } + + @Bean + @Lazy + public AccountJwtReadinessProbeOwnerWorkloadGuard accountJwtReadinessProbeOwnerWorkloadGuard( + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + @Qualifier("accountJwtReadinessJwksApiBinding") AccountJwtJwksApiBinding apiBinding, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new AccountJwtReadinessProbeOwnerWorkloadGuard( + materializerTrustBinding, apiBinding, workloadNamespace); + } + + @Bean + @Lazy + public AccountJwtReadinessProbeOwnerService accountJwtReadinessProbeOwnerService( + AccountJwtReadinessProbeService probeService, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtReadinessProbeOwnerWorkloadGuard workloadGuard, + AccountJwtReadinessProbeOwnerProtoMapper protoMapper) { + return new AccountJwtReadinessProbeOwnerService( + probeService, materializerTrustBinding, workloadGuard, protoMapper); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerWorkloadGuard.java new file mode 100644 index 0000000000..2d3ecc6312 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerWorkloadGuard.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.accountservice.config; + +import java.util.Objects; +import java.util.Optional; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Exact method-local mTLS authorization for the read-only Game Session probe-owner lookup. */ +public final class AccountJwtReadinessProbeOwnerWorkloadGuard { + private static final String GAME_SESSION_SERVICE = "game-session-service"; + + private final Supplier> materializerBinding; + private final Supplier apiBinding; + private final String localWorkloadNamespace; + + public AccountJwtReadinessProbeOwnerWorkloadGuard( + AccountJwtSignerMaterializerTrustBinding materializerBinding, + AccountJwtJwksApiBinding apiBinding, + String localWorkloadNamespace) { + this( + () -> Objects.requireNonNull(materializerBinding).current(), + () -> Objects.requireNonNull(apiBinding).current(), + localWorkloadNamespace); + } + + AccountJwtReadinessProbeOwnerWorkloadGuard( + Supplier> materializerBinding, + Supplier apiBinding, + String localWorkloadNamespace) { + this.materializerBinding = Objects.requireNonNull(materializerBinding); + this.apiBinding = Objects.requireNonNull(apiBinding); + this.localWorkloadNamespace = localWorkloadNamespace == null ? "" : localWorkloadNamespace; + } + + /** + * Reads both protected Account bindings and checks them against local config and peer TLS SAN. + */ + public AuthenticatedCaller requireGameSessionOwnerReadCaller() { + Binding account = materializerBinding.get().orElseThrow(OwnerReadDeniedException::new); + AccountJwtJwksApiBinding.ParsedBinding api; + try { + api = apiBinding.get(); + } catch (RuntimeException unavailable) { + throw new OwnerReadDeniedException(); + } + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (api == null + || !sameProtectedAccountIdentity(account, api) + || !GrpcPeerIdentity.isValidNamespace(localWorkloadNamespace) + || !localWorkloadNamespace.equals(account.namespace()) + || peer == null + || !GAME_SESSION_SERVICE.equals(peer.service()) + || !account.namespace().equals(peer.namespace()) + || !("spiffe://firemud/ns/" + account.namespace() + "/sa/" + GAME_SESSION_SERVICE) + .equals(peer.uri()) + || hasSessionContext()) { + throw new OwnerReadDeniedException(); + } + return new AuthenticatedCaller(account); + } + + private static boolean sameProtectedAccountIdentity( + Binding account, AccountJwtJwksApiBinding.ParsedBinding api) { + return account.environmentId().equals(api.environmentId()) + && account.clusterId().equals(api.clusterId()) + && account.namespace().equals(api.namespace()) + && account.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + && account.expectedNamespaceUid().equals(api.expectedNamespaceUid()); + } + + private static boolean hasSessionContext() { + return SessionContext.getAccountId() != null + || !SessionContext.getGlobalRoles().isEmpty() + || !SessionContext.getScopedRolesMap().isEmpty() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null; + } + + /** Opaque binding snapshot returned only after the gRPC peer check passes. */ + public static final class AuthenticatedCaller { + private final Binding accountBinding; + + private AuthenticatedCaller(Binding accountBinding) { + this.accountBinding = accountBinding; + } + + public Binding accountBinding() { + return accountBinding; + } + } + + public static final class OwnerReadDeniedException extends SecurityException { + public OwnerReadDeniedException() { + super("Authenticated same-namespace Game Session workload is required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportConfiguration.java new file mode 100644 index 0000000000..a7df100760 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportConfiguration.java @@ -0,0 +1,91 @@ +package net.firedevops.firemud.accountservice.config; + +import java.time.Clock; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessGrpcReceiverInvocationPort; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessTransportOwner; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessValidationService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Explicit, default-inactive composition for the isolated JWT readiness RPCs. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.account.jwt-readiness.validation", + name = "enabled", + havingValue = "true") +@Conditional( + AccountJwtReadinessPrerequisiteConfiguration.ProtectedReadinessConfigurationPresent.class) +@Lazy +public class AccountJwtReadinessTransportConfiguration { + @Bean + @Lazy + @ConditionalOnMissingBean(AccountJwtValidatorInventoryBinding.class) + public AccountJwtValidatorInventoryBinding accountJwtValidatorInventoryBinding() { + return new AccountJwtValidatorInventoryBinding( + true, AccountJwtValidatorInventoryBinding.PROTECTED_BINDING_PATH.toString()); + } + + @Bean + @Lazy + @ConditionalOnMissingBean(AccountJwtValidatorInventorySource.class) + public AccountJwtValidatorInventorySource accountJwtValidatorInventorySource( + @Qualifier("accountJwtReadinessJwksApiBinding") AccountJwtJwksApiBinding apiBinding, + AccountJwtValidatorInventoryBinding inventoryBinding) { + return new AccountJwtValidatorInventorySource(apiBinding, inventoryBinding, Clock.systemUTC()); + } + + @Bean + @Lazy + @ConditionalOnMissingBean(AccountJwtReadinessReceiverInvocationPort.class) + public AccountJwtReadinessReceiverInvocationPort accountJwtReadinessReceiverInvocationPort( + ObjectProvider sslBundles, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + SslBundles configuredBundles = sslBundles.getIfAvailable(); + if (configuredBundles != null + && net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace( + workloadNamespace)) { + return new AccountJwtReadinessGrpcReceiverInvocationPort( + configuredBundles, workloadNamespace); + } + return AccountJwtReadinessReceiverInvocationPort.defaultDenied(); + } + + @Bean + @Lazy + @ConditionalOnMissingBean(AccountJwtReadinessProbeService.class) + public AccountJwtReadinessProbeService accountJwtReadinessProbeService( + AccountJwtReadinessProbeRepository repository, + AccountJwtValidatorInventorySource inventorySource, + PlatformTransactionManager transactionManager) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setReadOnly(false); + return new AccountJwtReadinessProbeService( + repository, transaction, Clock.systemUTC(), inventorySource); + } + + @Bean + @Lazy + public AccountJwtReadinessTransportOwner accountJwtReadinessTransportOwner( + AccountJwtReadinessProbeRepository repository, + AccountJwtReadinessProbeService probeProducer, + AccountJwtReadinessValidationService validationService, + AccountJwtReadinessReceiverInvocationPort receiverInvocationPort, + PlatformTransactionManager transactionManager) { + return new AccountJwtReadinessTransportOwner( + repository, probeProducer, validationService, transactionManager, receiverInvocationPort); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfiguration.java new file mode 100644 index 0000000000..955bfbeb86 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfiguration.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.accountservice.config; + +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksPrepublicationService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Qualifier; +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.context.annotation.Lazy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Default-inactive composition for explicit Account JWT signer bootstrap reconciliation. + * + *

The enabled property only makes the callable coordinator available; it does not run it. No + * startup runner, scheduler, or automatic signer activation is registered here. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.account.jwt-signer.bootstrap", + name = "enabled", + havingValue = "true") +public class AccountJwtSignerBootstrapConfiguration { + private static final String JWKS_API_BINDING_PATH = "/etc/firemud/account-jwt-api/binding.json"; + + @Bean + @Lazy + public AccountJwtJwksApiBinding accountJwtSignerBootstrapJwksApiBinding( + @Value("${firemud.account.jwt-jwks-api.enabled:false}") boolean enabled) { + return new AccountJwtJwksApiBinding(enabled, JWKS_API_BINDING_PATH); + } + + @Bean + @Lazy + public AccountJwtJwksConfigMapClient accountJwtSignerBootstrapJwksConfigMapClient( + @Qualifier("accountJwtSignerBootstrapJwksApiBinding") + AccountJwtJwksApiBinding accountJwtSignerBootstrapJwksApiBinding) { + return new AccountJwtJwksConfigMapClient(accountJwtSignerBootstrapJwksApiBinding); + } + + @Bean + @Lazy + public AccountJwtJwksPrepublicationService accountJwtSignerBootstrapPrepublicationService( + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + @Qualifier("accountJwtSignerBootstrapJwksConfigMapClient") + AccountJwtJwksConfigMapClient accountJwtSignerBootstrapJwksConfigMapClient, + PlatformTransactionManager transactionManager) { + return new AccountJwtJwksPrepublicationService( + desiredStateRepository, + publicationRepository, + materializerTrustBinding, + accountJwtSignerBootstrapJwksConfigMapClient, + transactionManager); + } + + @Bean + @Lazy + public AccountJwtSignerBootstrapCoordinator accountJwtSignerBootstrapCoordinator( + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + @Qualifier("accountJwtSignerBootstrapJwksConfigMapClient") + AccountJwtJwksConfigMapClient accountJwtSignerBootstrapJwksConfigMapClient, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtReadinessProbeRepository readinessProbeRepository, + ObjectProvider inventorySourceProvider, + @Qualifier("accountJwtSignerBootstrapPrepublicationService") + AccountJwtJwksPrepublicationService accountJwtSignerBootstrapPrepublicationService, + PlatformTransactionManager transactionManager) { + return new AccountJwtSignerBootstrapCoordinator( + materializerTrustBinding, + accountJwtSignerBootstrapJwksConfigMapClient, + desiredStateRepository, + accountJwtSignerBootstrapPrepublicationService, + readinessProbeRepository, + inventorySourceProvider, + new TransactionTemplate(transactionManager)); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java index 1afe45ef49..6f775620ee 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.accountservice.config; import java.io.IOException; +import java.net.Inet6Address; +import java.net.InetAddress; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.charset.CharacterCodingException; @@ -44,7 +46,7 @@ public final class AccountJwtValidatorInventoryBinding { public static final Path PROTECTED_BINDING_PATH = Path.of("/etc/firemud/account-jwt-api/validator-inventory.json"); private static final Path PROTECTED_ROOT = Path.of("/etc/firemud/account-jwt-api"); - private static final String VERSION = "account-jwt-validator-inventory-binding/v1"; + private static final String VERSION = "account-jwt-validator-inventory-binding/v2"; private static final String RUNTIME_CONFIG_ENV = "FIREMUD_JWT_VERIFIER_CONFIG"; private static final Set ROOT_FIELDS = Set.of( @@ -71,8 +73,13 @@ public final class AccountJwtValidatorInventoryBinding { "image", "jwksUri", "maxCacheAgeSeconds", - "profiles"); + "profiles", + "receiverServiceUri", + "receiverPort", + "receiverPods"); private static final Set PROFILE_FIELDS = Set.of("tokenProfile", "audience"); + private static final Set RECEIVER_POD_FIELDS = + Set.of("podUid", "podIp", "leafSpkiSha256"); private static final JsonMapper JSON = JsonMapper.builder() .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) @@ -92,6 +99,9 @@ public final class AccountJwtValidatorInventoryBinding { Pattern.compile("(?:[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?"); private static final Pattern PROFILE = Pattern.compile("[a-z][a-z0-9-]{0,63}"); private static final Pattern AUDIENCE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}"); + private static final Pattern RECEIVER_SERVICE_URI = + Pattern.compile( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); private final boolean enabled; private final String configuredPath; @@ -206,6 +216,9 @@ private static List parseValidators(JsonNode node) { List result = new ArrayList<>(); Set ids = new LinkedHashSet<>(); Set deployments = new LinkedHashSet<>(); + Set expectedPodUids = new LinkedHashSet<>(); + Set expectedPodIps = new LinkedHashSet<>(); + Set expectedPodSpkis = new LinkedHashSet<>(); for (JsonNode validator : node) { requireObjectFields(validator, VALIDATOR_FIELDS); String id = requiredText(validator, "validatorId", 63); @@ -229,6 +242,18 @@ private static List parseValidators(JsonNode node) { if (profiles.isEmpty()) { throw unavailable(); } + List receiverPods = + parseReceiverPods(validator.get("receiverPods"), replicas); + for (ReceiverPodPin pin : receiverPods) { + // Validator workloads are distinct expected instances in this closed LOGIN matrix. A + // shared leaf key would make the TLS peer prove only possession by either Pod, not the + // exact Pod UID selected by the owner-observed inventory. + if (!expectedPodUids.add(pin.podUid()) + || !expectedPodIps.add(pin.podIp()) + || !expectedPodSpkis.add(pin.leafSpkiSha256())) { + throw unavailable(); + } + } String runtimeConfig = canonicalRuntimeConfig(jwksUri, maximumCacheAge, profiles); if (runtimeConfig.getBytes(StandardCharsets.UTF_8).length > MAX_RUNTIME_CONFIG_BYTES) { throw unavailable(); @@ -245,11 +270,127 @@ private static List parseValidators(JsonNode node) { jwksUri, maximumCacheAge, profiles, - runtimeConfig)); + runtimeConfig, + canonicalReceiverServiceUri(requiredText(validator, "receiverServiceUri", 256)), + exactInt(validator.get("receiverPort"), 1, 65535), + receiverPods)); } return List.copyOf(result); } + private static List parseReceiverPods(JsonNode node, int replicas) { + if (node == null || !node.isArray() || node.size() != replicas || node.size() > 128) { + throw unavailable(); + } + List pins = new ArrayList<>(); + Set podUids = new LinkedHashSet<>(); + Set podIps = new LinkedHashSet<>(); + Set podSpkis = new LinkedHashSet<>(); + String previousUid = null; + for (JsonNode pod : node) { + requireObjectFields(pod, RECEIVER_POD_FIELDS); + String uid = canonicalUid(requiredText(pod, "podUid", 36)); + String ip = canonicalPodIp(requiredText(pod, "podIp", 45)); + String spki = requiredText(pod, "leafSpkiSha256", 64); + if (!SHA256.matcher(spki).matches() + || !podUids.add(uid) + || !podIps.add(ip) + || !podSpkis.add(spki) + || (previousUid != null && previousUid.compareTo(uid) >= 0)) { + throw unavailable(); + } + previousUid = uid; + pins.add(new ReceiverPodPin(uid, ip, spki)); + } + return List.copyOf(pins); + } + + private static String canonicalReceiverServiceUri(String value) { + if (!RECEIVER_SERVICE_URI.matcher(value).matches()) { + throw unavailable(); + } + return value; + } + + public static String canonicalPodIp(String value) { + if (value == null || value.isBlank() || value.indexOf('%') >= 0) { + throw unavailable(); + } + try { + if (value.indexOf(':') < 0) { + String[] components = value.split("\\.", -1); + if (components.length != 4) { + throw unavailable(); + } + for (String component : components) { + if (component.isEmpty() + || (component.length() > 1 && component.charAt(0) == '0') + || !component.matches("[0-9]{1,3}") + || Integer.parseInt(component) > 255) { + throw unavailable(); + } + } + if ("0.0.0.0".equals(value) || "255.255.255.255".equals(value)) { + throw unavailable(); + } + return value; + } + if (!value.matches("[0-9A-Fa-f:]+")) { + throw unavailable(); + } + InetAddress address = InetAddress.getByName(value); + if (!(address instanceof Inet6Address) + || !canonicalIpv6(address.getAddress()).equals(value)) { + throw unavailable(); + } + return value; + } catch (IOException | NumberFormatException failure) { + throw unavailable(); + } + } + + private static String canonicalIpv6(byte[] bytes) { + if (bytes.length != 16) { + throw unavailable(); + } + int[] groups = new int[8]; + for (int index = 0; index < groups.length; index++) { + groups[index] = + Byte.toUnsignedInt(bytes[index * 2]) << 8 | Byte.toUnsignedInt(bytes[index * 2 + 1]); + } + int bestStart = -1; + int bestLength = 1; + for (int index = 0; index < groups.length; ) { + if (groups[index] != 0) { + index++; + continue; + } + int end = index; + while (end < groups.length && groups[end] == 0) { + end++; + } + if (end - index > bestLength) { + bestStart = index; + bestLength = end - index; + } + index = end; + } + StringBuilder canonical = new StringBuilder(); + for (int index = 0; index < groups.length; ) { + if (index == bestStart) { + canonical.append("::"); + index += bestLength; + continue; + } + if (canonical.length() > 0 && canonical.charAt(canonical.length() - 1) != ':') { + canonical.append(':'); + } + canonical.append(Integer.toHexString(groups[index])); + index++; + } + return canonical.toString(); + } + private static Map parseSelector(JsonNode node) { if (node == null || !node.isObject() || node.isEmpty() || node.size() > 16) { throw unavailable(); @@ -603,6 +744,9 @@ public static final class ValidatorExpectation { private final int maxCacheAgeSeconds; private final List profiles; private final String canonicalRuntimeConfig; + private final String receiverServiceUri; + private final int receiverPort; + private final List receiverPods; private ValidatorExpectation( String validatorId, @@ -615,7 +759,10 @@ private ValidatorExpectation( String jwksUri, int maxCacheAgeSeconds, List profiles, - String canonicalRuntimeConfig) { + String canonicalRuntimeConfig, + String receiverServiceUri, + int receiverPort, + List receiverPods) { this.validatorId = validatorId; this.deploymentName = deploymentName; this.deploymentUid = deploymentUid; @@ -627,6 +774,9 @@ private ValidatorExpectation( this.maxCacheAgeSeconds = maxCacheAgeSeconds; this.profiles = List.copyOf(profiles); this.canonicalRuntimeConfig = canonicalRuntimeConfig; + this.receiverServiceUri = receiverServiceUri; + this.receiverPort = receiverPort; + this.receiverPods = List.copyOf(receiverPods); } public String validatorId() { @@ -672,7 +822,21 @@ public List profiles() { public String canonicalRuntimeConfig() { return canonicalRuntimeConfig; } + + public String receiverServiceUri() { + return receiverServiceUri; + } + + public int receiverPort() { + return receiverPort; + } + + public List receiverPods() { + return receiverPods; + } } + public record ReceiverPodPin(String podUid, String podIp, String leafSpkiSha256) {} + public record ProfileExpectation(String tokenProfile, String audience) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java index ea4954ad03..c76f1951e0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java @@ -181,7 +181,7 @@ public Optional readCurrentPublication(Binding binding, Tru * generation. Ordinary current-publication reads remain unavailable while PREPARED. */ @Transactional(propagation = Propagation.MANDATORY, readOnly = true) - public PreparedPublicationEvidence readPreparedPublicationForRecovery( + public PromotionPublicationEvidence readPreparedPublicationForRecovery( Binding binding, TrustFence trust) { requireAccountTransaction(); PreparedGenerationEvidence prepared = @@ -209,7 +209,7 @@ public PreparedPublicationEvidence readPreparedPublicationForRecovery( throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( "Prepared promotion no longer matches its immutable prepublication evidence"); } - return new PreparedPublicationEvidence(intent, receipt, mount); + return new PromotionPublicationEvidence(intent, receipt, mount); } /** @@ -1262,11 +1262,11 @@ public record PublicationEvidence( } } - public record PreparedPublicationEvidence( + public record PromotionPublicationEvidence( PrepublicationIntent intent, PublicationReceipt receipt, MountObservation mountedCorrespondence) { - public PreparedPublicationEvidence { + public PromotionPublicationEvidence { Objects.requireNonNull(intent); Objects.requireNonNull(receipt); Objects.requireNonNull(mountedCorrespondence); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java index 63fa47891e..716bbb12e0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; +import java.net.URI; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -14,6 +15,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.PeerIdentity; @@ -24,7 +26,16 @@ import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerSelector; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.PodTarget; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException; import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.SignedProbeDigest; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; @@ -39,6 +50,7 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; /** @@ -56,11 +68,15 @@ public class AccountJwtReadinessProbeRepository { public static final int MAX_VALIDATOR_CACHE_AGE_SECONDS = 300; public static final int PROBE_LIFETIME_SECONDS = 300; public static final int MAX_ENTRIES_PER_OPERATION = 256; + public static final int MAX_POD_RECEIPTS_PER_OPERATION = 256; public static final String INVENTORY_STATUS = "PARTIAL_UNCONFIRMED"; + public static final int INVENTORY_PLAN_VERSION = 2; private static final String PLAN_TABLE = "account_jwt_readiness_probe_plans"; private static final String ENTRY_TABLE = "account_jwt_readiness_probe_entries"; private static final String DELIVERY_CLAIM_TABLE = "account_jwt_readiness_delivery_claims"; + private static final String EXPECTED_POD_TABLE = "account_jwt_readiness_validator_pods"; + private static final String POD_RECEIPT_TABLE = "account_jwt_readiness_pod_receipts"; private static final String VALIDATOR_ID = "account-service"; private static final String CANARY_PROFILE = "account-jwt-readiness-canary"; private static final String CANARY_AUDIENCE = "firemud-account-jwt-readiness"; @@ -72,6 +88,11 @@ public class AccountJwtReadinessProbeRepository { private static final String REPRESENTATIVE_PROFILE = GameSessionAccountDelegationProfile.PROFILE; private static final String REPRESENTATIVE_AUDIENCE = GameSessionAccountDelegationProfile.AUDIENCE; + private static final List PRODUCTION_PROFILE_CASES = + List.of( + new ProfileCase(CONTROL_UI_PROFILE, CONTROL_UI_AUDIENCE), + new ProfileCase(PLAYER_BOOTSTRAP_PROFILE, PLAYER_BOOTSTRAP_AUDIENCE), + new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE)); private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); private static final JsonMapper JSON = JsonMapper.builder().build(); @@ -122,6 +143,38 @@ public ReadinessProbePlan planCurrent(Binding binding, TrustFence trust, Instant return planCurrent(binding, trust, plannedAt, Optional.empty()); } + /** + * Reads the exact current operation context before protected inventory I/O. The caller must + * return to an Account transaction and recheck this context before persisting or consuming the + * resulting snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ObservationContext readCurrentInventoryObservationContext( + Binding binding, TrustFence trust) { + requireAccountTransaction(); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + ReadinessProbePlan existing = selectPlan(current.request().operationId(), false); + if (existing != null) { + requirePlanMatchesCurrent(readbackPlan(existing, false), current); + } + return observationContext(current); + } + + /** Reads the selected context only while its exact current V2 inventory plan remains current. */ + @Transactional(propagation = Propagation.MANDATORY) + public ObservationContext readCurrentInventoryObservationContext( + Binding binding, TrustFence trust, UUID operationId) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION || !plan.validatorInventoryComplete()) { + throw new ReceiverUnavailableException(); + } + return observationContext(current); + } + /** * Creates a still-partial plan bound to the exact Account-owned immutable inventory snapshot. The * live inventory observation does not establish per-Pod acceptance or promotion evidence. @@ -159,15 +212,22 @@ private ReadinessProbePlan planCurrent( Optional snapshotDigest = Optional.empty(); if (inventorySnapshot.isPresent()) { InventorySnapshot snapshot = inventorySnapshot.orElseThrow(); + requireObservationContext(current, snapshot); requireInventorySnapshotWithinPlanWindow(snapshot, plannedEpoch); AccountJwtValidatorInventoryRepository.StoredSnapshot stored = inventoryRepository.persistOrReadback(snapshot, binding, trust); snapshotDigest = Optional.of(stored.digest()); } - ReadinessProbePlan candidate = newPlan(current, plannedEpoch, snapshotDigest); + ReadinessProbePlan candidate = + newPlan(current, plannedEpoch, inventorySnapshot, snapshotDigest); insertPlan(candidate); for (ProbeEntry entry : candidate.entries()) { - insertEntry(entry); + insertEntry(entry, candidate.planVersion()); + } + if (inventorySnapshot.isPresent()) { + for (ExpectedPod expectedPod : expectedPods(candidate, inventorySnapshot.orElseThrow())) { + insertExpectedPod(expectedPod); + } } ReadinessProbePlan readback = selectPlan(operationId, true); if (readback == null) { @@ -304,13 +364,23 @@ public DeliveryClaim requireCurrentDeliveryClaim( } /** - * Recovery-only read for the exact generation/publication currently owned by PREPARED state. The - * static applicability matrix and immutable Deployment inventory snapshot are not per-Pod - * acceptance evidence. These PARTIAL_UNCONFIRMED plans cannot satisfy promotion. + * Reads the exact current generation and public publication before PREPARED so the caller can + * authorize that same generation's preparation. The static applicability matrix and immutable + * Deployment inventory snapshot alone are not per-Pod acceptance evidence; partial plans cannot + * satisfy promotion. */ @Transactional(propagation = Propagation.MANDATORY) public Optional readCurrentPromotionPrerequisites( Binding binding, TrustFence trust, UUID rotationOperationId) { + return readCurrentPromotionPrerequisites(binding, trust, rotationOperationId, null); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPromotionPrerequisites( + Binding binding, + TrustFence trust, + UUID rotationOperationId, + InventorySnapshot liveInventory) { // This is a nonmutating proof read, but it joins the writable lifecycle transaction because // the existing owner evidence readers lock their rows to fence the adjacent PREPARED CAS. requireWritableAccountTransaction(); @@ -332,15 +402,36 @@ public Optional readCurrentPromotionPrerequisites( if (!stored.validatorInventoryComplete()) { return Optional.empty(); } - // The immutable inventory snapshot is not per-Pod acceptance evidence. Never upgrade the - // static matrix or receipt set into complete inventory proof. - throw new QuarantinedStateException( - "Readiness plan claims complete inventory without protected inventory evidence"); + if (stored.planVersion() != INVENTORY_PLAN_VERSION || liveInventory == null) { + return Optional.empty(); + } + requireLiveInventoryMatches(stored, binding, trust, liveInventory, observationContext(current)); + if (!hasCompletePodReceiptClosure(stored)) { + return Optional.empty(); + } + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication = + promotionPublicationEvidence(current.publication()); + return Optional.of( + new ReadinessPromotionProof( + stored, + current.result(), + publication, + "protected-validator-inventory:" + liveInventory.digest(), + liveInventory.digest())); } @Transactional(propagation = Propagation.MANDATORY) public Optional readPromotionProof( Binding binding, TrustFence trust, UUID rotationOperationId) { + return readPromotionProof(binding, trust, rotationOperationId, null); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readPromotionProof( + Binding binding, + TrustFence trust, + UUID rotationOperationId, + InventorySnapshot liveInventory) { // Recovery evidence is likewise a locked, nonmutating read inside the writable reconciliation // transaction; do not split these reads into an unlocked read-only snapshot. requireWritableAccountTransaction(); @@ -355,7 +446,7 @@ public Optional readPromotionProof( throw new StaleOperationException( "Readiness promotion proof does not match the exact PREPARED generation"); } - AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication = + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication = publicationRepository.readPreparedPublicationForRecovery(binding, trust); ReadinessProbePlan plan = selectPlan(rotationOperationId, false); if (plan == null) { @@ -369,10 +460,26 @@ public Optional readPromotionProof( if (!stored.validatorInventoryComplete()) { return Optional.empty(); } - // The immutable inventory snapshot is not per-Pod acceptance evidence. Never upgrade the - // static matrix or receipt set into complete inventory proof. - throw new QuarantinedStateException( - "Readiness plan claims complete inventory without protected inventory evidence"); + if (stored.planVersion() != INVENTORY_PLAN_VERSION || liveInventory == null) { + return Optional.empty(); + } + requireLiveInventoryMatches( + stored, + binding, + trust, + liveInventory, + observationContext( + generation.operationId(), generation.operationDigest(), stored.expectedFence())); + if (!hasCompletePodReceiptClosure(stored)) { + return Optional.empty(); + } + return Optional.of( + new ReadinessPromotionProof( + stored, + generation, + publication, + "protected-validator-inventory:" + liveInventory.digest(), + liveInventory.digest())); } private boolean readinessPlanOutOfWindow(ReadinessProbePlan plan) { @@ -420,6 +527,9 @@ public ProbeEntry readCurrentEntry( CurrentEvidence current = lockCurrentEvidence(binding, trust); requireCurrentOperation(current, operationId.toString()); ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != 1) { + throw new ReceiverUnavailableException(); + } ProbeEntry entry = selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); if (entry == null @@ -452,6 +562,9 @@ public ProbeEntry recordVerified( CurrentEvidence current = lockCurrentEvidence(binding, trust); requireCurrentOperation(current, operationId.toString()); ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != 1) { + throw new ReceiverUnavailableException(); + } ProbeEntry entry = selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); if (entry == null @@ -824,49 +937,32 @@ private ProbeEntry transitionTerminal(ProbeEntry entry, ProbeState target, Long private ReadinessProbePlan newPlan( CurrentEvidence current, long plannedAtEpochSecond, + Optional inventorySnapshot, Optional inventorySnapshotDigest) { long notBefore = add(plannedAtEpochSecond, MAX_VALIDATOR_CACHE_AGE_SECONDS); long expiresAt = add(notBefore, PROBE_LIFETIME_SECONDS); - String matrixJson = applicabilityMatrixJson(); + int planVersion = inventorySnapshot.isPresent() ? INVENTORY_PLAN_VERSION : 1; + boolean inventoryComplete = + inventorySnapshot + .map(AccountJwtReadinessProbeRepository::inventoryPlanComplete) + .orElse(false); + String matrixJson = + inventorySnapshot + .map(snapshot -> applicabilityMatrixJson(snapshot, inventoryComplete)) + .orElseGet(AccountJwtReadinessProbeRepository::applicabilityMatrixJson); String matrixDigest = sha256(matrixJson.getBytes(StandardCharsets.UTF_8)); List entries = - List.of( - newEntry( - current, - ProbeKind.CANARY, - CANARY_PROFILE, - CANARY_AUDIENCE, - notBefore, - expiresAt), - newEntry( - current, - ProbeKind.REPRESENTATIVE, - CONTROL_UI_PROFILE, - CONTROL_UI_AUDIENCE, - notBefore, - expiresAt), - newEntry( - current, - ProbeKind.REPRESENTATIVE, - PLAYER_BOOTSTRAP_PROFILE, - PLAYER_BOOTSTRAP_AUDIENCE, - notBefore, - expiresAt), - newEntry( - current, - ProbeKind.REPRESENTATIVE, - REPRESENTATIVE_PROFILE, - REPRESENTATIVE_AUDIENCE, - notBefore, - expiresAt)) - .stream() - .sorted(PROBE_ENTRY_ORDER) - .toList(); + (inventorySnapshot.isPresent() + ? inventoryEntries(current, inventorySnapshot.orElseThrow(), notBefore, expiresAt) + : legacyEntries(current, notBefore, expiresAt)) + .stream().sorted(PROBE_ENTRY_ORDER).toList(); String planDigest = planDigest( current, matrixJson, matrixDigest, + planVersion, + inventoryComplete, plannedAtEpochSecond, notBefore, expiresAt, @@ -878,18 +974,88 @@ private ReadinessProbePlan newPlan( current, matrixJson, matrixDigest, - false, + inventoryComplete, MAX_VALIDATOR_CACHE_AGE_SECONDS, plannedAtEpochSecond, notBefore, expiresAt, planDigest, boundEntries, - inventorySnapshotDigest); + inventorySnapshotDigest, + planVersion); + } + + private static List legacyEntries( + CurrentEvidence current, long notBefore, long expiresAt) { + return List.of( + newEntry( + current, + VALIDATOR_ID, + ProbeKind.CANARY, + CANARY_PROFILE, + CANARY_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + CONTROL_UI_PROFILE, + CONTROL_UI_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + PLAYER_BOOTSTRAP_PROFILE, + PLAYER_BOOTSTRAP_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + REPRESENTATIVE_PROFILE, + REPRESENTATIVE_AUDIENCE, + notBefore, + expiresAt)); + } + + private static List inventoryEntries( + CurrentEvidence current, InventorySnapshot snapshot, long notBefore, long expiresAt) { + List entries = new ArrayList<>(); + for (ValidatorObservation validator : snapshot.validators()) { + entries.add( + newEntry( + current, + validator.validatorId(), + ProbeKind.CANARY, + CANARY_PROFILE, + CANARY_AUDIENCE, + notBefore, + expiresAt)); + for (ProfileCase profile : PRODUCTION_PROFILE_CASES) { + entries.add( + newEntry( + current, + validator.validatorId(), + ProbeKind.REPRESENTATIVE, + profile.tokenProfile(), + profile.audience(), + notBefore, + expiresAt)); + } + } + if (entries.isEmpty() || entries.size() > MAX_ENTRIES_PER_OPERATION) { + throw new InventoryPlanConflictException(); + } + return List.copyOf(entries); } private static ProbeEntry newEntry( CurrentEvidence current, + String validatorId, ProbeKind kind, String profile, String audience, @@ -898,7 +1064,7 @@ private static ProbeEntry newEntry( return new ProbeEntry( current.request().operationId(), "0".repeat(64), - VALIDATOR_ID, + validatorId, profile, audience, kind, @@ -966,7 +1132,7 @@ private void insertPlan(ReadinessProbePlan plan) { fields.put("planned_at_epoch_seconds", plan.plannedAtEpochSecond()); fields.put("not_before_epoch_seconds", plan.notBeforeEpochSecond()); fields.put("expires_at_epoch_seconds", plan.expiresAtEpochSecond()); - fields.put("plan_version", 1); + fields.put("plan_version", plan.planVersion()); fields.put("plan_digest", plan.planDigest()); insertOne(dsl, PLAN_TABLE, fields); } @@ -1040,7 +1206,7 @@ private DeliveryClaim selectDeliveryClaim(UUID operationId, boolean lock) { return result; } - private void insertEntry(ProbeEntry entry) { + private void insertEntry(ProbeEntry entry, int planVersion) { Map fields = new LinkedHashMap<>(); fields.put("rotation_operation_id", entry.rotationOperationId()); fields.put("plan_digest", entry.planDigest()); @@ -1060,12 +1226,917 @@ private void insertEntry(ProbeEntry entry) { fields.put("planned_issued_at_epoch_seconds", entry.plannedIssuedAtEpochSecond()); fields.put("expires_at_epoch_seconds", entry.expiresAtEpochSecond()); fields.put("state", entry.state().name()); + fields.put("entry_plan_version", planVersion); fields.put("terminal_outcome", null); fields.put("signing_attempted_at_epoch_seconds", null); fields.put("compact_token_sha256", null); insertOne(dsl, ENTRY_TABLE, fields); } + private void insertExpectedPod(ExpectedPod expected) { + PodTarget target = expected.target(); + target.requireRoutablePodIdentity(); + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", expected.rotationOperationId()); + fields.put("plan_digest", expected.planDigest()); + fields.put("validator_id", expected.validatorId()); + fields.put("token_profile", expected.tokenProfile()); + fields.put("audience", expected.audience()); + fields.put("probe_kind", expected.probeKind().name()); + fields.put("jti", expected.jti()); + fields.put("inventory_snapshot_digest", target.inventorySnapshotDigest()); + fields.put("environment_id", target.environmentId()); + fields.put("cluster_id", target.clusterId()); + fields.put("cluster_incarnation_uid", UUID.fromString(target.clusterIncarnationUid())); + fields.put("kubernetes_namespace", target.namespace()); + fields.put("namespace_uid", UUID.fromString(target.namespaceUid())); + fields.put("api_binding_revision", target.apiBindingRevision()); + fields.put("api_binding_digest", target.apiBindingDigest()); + fields.put("inventory_binding_revision", target.inventoryBindingRevision()); + fields.put("inventory_binding_digest", target.inventoryBindingDigest()); + fields.put("deployment_uid", UUID.fromString(target.deploymentUid())); + fields.put("pod_uid", UUID.fromString(target.podUid())); + fields.put("pod_ip", target.podIp()); + fields.put("image", target.image()); + fields.put("verifier_config_sha256", target.verifierConfigSha256()); + fields.put("applicability_matrix_digest", target.applicabilityMatrixDigest()); + fields.put("expected_outcome", target.expectation().name()); + fields.put("exact_pod_endpoint", target.exactPodEndpoint().map(URI::toString).orElse(null)); + fields.put("canonical_service_uri", target.canonicalServiceUri().orElse(null)); + fields.put("expected_pod_leaf_spki_sha256", target.podLeafSpkiSha256().orElse(null)); + insertOne(dsl, EXPECTED_POD_TABLE, fields); + } + + /** Reads the immutable, exact per-Pod plan rows for one current V2 entry. */ + @Transactional(propagation = Propagation.MANDATORY) + public List readCurrentExpectedPods( + Binding binding, TrustFence trust, ProbeEntry expectedEntry) { + throw new ReceiverUnavailableException(); + } + + /** Reads exact expected Pod rows only after a fresh independent owner observation. */ + @Transactional(propagation = Propagation.MANDATORY) + public List readCurrentExpectedPods( + Binding binding, + TrustFence trust, + ProbeEntry expectedEntry, + InventorySnapshot liveInventory) { + requireAccountTransaction(); + Objects.requireNonNull(expectedEntry, "Exact readiness entry is required"); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedEntry.rotationOperationId().toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.planDigest().equals(expectedEntry.planDigest())) { + throw new ReceiverUnavailableException(); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + ProbeEntry stored = + selectEntry( + expectedEntry.rotationOperationId(), + expectedEntry.validatorId(), + expectedEntry.tokenProfile(), + expectedEntry.audience(), + expectedEntry.probeKind(), + true); + if (stored == null + || !stored.equals(expectedEntry) + || stored.state() != ProbeState.ISSUED + || stored.compactTokenSha256().isEmpty()) { + throw new StaleOperationException("Readiness receiver entry changed before invocation"); + } + plan.inventorySnapshotDigest() + .ifPresent(digest -> inventoryRepository.readRequired(digest, binding, trust)); + List expectedPods = selectExpectedPods(stored, true); + if (expectedPods.isEmpty() || expectedPods.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness V2 entry has no bounded expected Pod set"); + } + return expectedPods; + } + + /** + * Reads only the owner-retained coordinates and one Pod target for the authenticated V2 receiver + * lookup. The caller's tuple is a selector: every returned coordinate is projected from locked + * current owner rows, never copied from the request. + */ + @Transactional(propagation = Propagation.MANDATORY) + public OwnerProbeEvidence readCurrentProbeOwner( + Binding binding, + TrustFence trust, + AccountJwtReadinessProbeOwnerSelector selector, + InventorySnapshot liveInventory, + String authenticatedWorkloadNamespace) { + requireAccountTransaction(); + Objects.requireNonNull(selector, "Exact readiness probe selector is required"); + if (authenticatedWorkloadNamespace == null || authenticatedWorkloadNamespace.isBlank()) { + throw new ReceiverUnavailableException(); + } + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(selector.rotationOperationId())) { + throw new ReceiverUnavailableException(); + } + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.operationId().equals(selector.rotationOperationId()) + || !plan.operationDigest().equals(selector.operationDigest()) + || !plan.planDigest().equals(selector.planDigest()) + || plan.planVersion() != selector.planVersion() + || plan.expiresAtEpochSecond() != selector.planExpiresAtEpochSecond() + || !plan.targetGeneration().equals(selector.targetGeneration()) + || !plan.targetKid().equals(selector.targetKid()) + || !plan.expectedFence().durableActive().equals(selector.expectedActive()) + || !plan.expectedFence().publishedActive().equals(selector.expectedActive())) { + throw new ReceiverUnavailableException(); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + if (readinessPlanOutOfWindow(plan)) { + throw new ReceiverUnavailableException(); + } + + ProbeEntry entry = + selectEntry( + selector.rotationOperationId(), + selector.validatorId(), + selector.tokenProfile(), + selector.audience(), + selector.probeKind(), + true); + if (entry == null + || entry.state() != ProbeState.ISSUED + || entry.verificationReceipt().isPresent() + || !entry.rotationOperationId().equals(selector.rotationOperationId()) + || !entry.planDigest().equals(plan.planDigest()) + || !entry.jti().equals(selector.jti()) + || entry.registryVersion() != selector.registryVersion() + || entry.entryVersion() != selector.entryVersion() + || !entry.targetGeneration().equals(selector.targetGeneration()) + || !entry.targetKid().equals(selector.targetKid()) + || !entry.expectedActive().equals(selector.expectedActive()) + || entry.plannedIssuedAtEpochSecond() != selector.issuedAtEpochSecond() + || entry.expiresAtEpochSecond() != selector.expiresAtEpochSecond() + || !entry.compactTokenSha256().equals(Optional.of(selector.compactTokenSha256()))) { + throw new ReceiverUnavailableException(); + } + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null + || databaseNow < entry.plannedIssuedAtEpochSecond() + || databaseNow >= entry.expiresAtEpochSecond()) { + throw new ReceiverUnavailableException(); + } + + List expectedPods = selectExpectedPods(entry, true); + if (expectedPods.isEmpty() || expectedPods.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new ReceiverUnavailableException(); + } + List selectedPods = + expectedPods.stream() + .filter(value -> value.target().podUid().equals(selector.localIdentity().podUid())) + .toList(); + if (selectedPods.size() != 1) { + throw new ReceiverUnavailableException(); + } + ExpectedPod expectedPod = selectedPods.getFirst(); + PodTarget target = expectedPod.target(); + target.requireRoutablePodIdentity(); + AccountJwtReadinessProbeOwnerSelector.LocalIdentity local = selector.localIdentity(); + if (!target.validatorId().equals(selector.validatorId()) + || !expectedPod.rotationOperationId().equals(selector.rotationOperationId()) + || !expectedPod.planDigest().equals(plan.planDigest()) + || !expectedPod.jti().equals(entry.jti()) + || target.expectation() != selector.expectedOutcome() + || !target.namespace().equals(authenticatedWorkloadNamespace) + || !local.validatorId().equals(target.validatorId()) + || !local.deploymentUid().equals(target.deploymentUid()) + || !local.podUid().equals(target.podUid()) + || !local.podIp().equals(target.podIp()) + || !local.directPodEndpoint().equals(target.exactPodEndpoint().orElseThrow().toString()) + || !local.canonicalServiceUri().equals(target.canonicalServiceUri().orElseThrow()) + || !local.image().equals(target.image()) + || !local.verifierConfigSha256().equals(target.verifierConfigSha256()) + || !local.applicabilityMatrixDigest().equals(plan.applicabilityMatrixDigest()) + || !local.serverLeafSpkiSha256().equals(target.podLeafSpkiSha256().orElseThrow())) { + throw new ReceiverUnavailableException(); + } + return new OwnerProbeEvidence(plan, entry, expectedPod); + } + + /** + * Records one owner-authenticated production verifier result for one exact expected Pod. A + * logical entry remains ISSUED until every immutable expected Pod has a matching unique receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordPodAcceptance( + Binding binding, + TrustFence trust, + ProbeEntry expectedEntry, + ExpectedPod expectedPod, + AuthenticatedAcceptance acceptance, + InventorySnapshot liveInventory) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedEntry, "Exact readiness entry is required"); + Objects.requireNonNull(expectedPod, "Exact expected Pod row is required"); + Objects.requireNonNull(acceptance, "Owner-authenticated receiver result is required"); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedEntry.rotationOperationId().toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.planDigest().equals(expectedEntry.planDigest()) + || !expectedPod.rotationOperationId().equals(plan.operationId()) + || !expectedPod.planDigest().equals(plan.planDigest()) + || !expectedPod.validatorId().equals(expectedEntry.validatorId()) + || !expectedPod.tokenProfile().equals(expectedEntry.tokenProfile()) + || !expectedPod.audience().equals(expectedEntry.audience()) + || expectedPod.probeKind() != expectedEntry.probeKind() + || !expectedPod.jti().equals(expectedEntry.jti())) { + throw new StaleOperationException("Readiness Pod receipt is outside the exact current entry"); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + ProbeEntry entry = + selectEntry( + expectedEntry.rotationOperationId(), + expectedEntry.validatorId(), + expectedEntry.tokenProfile(), + expectedEntry.audience(), + expectedEntry.probeKind(), + true); + if (entry == null + || entry.compactTokenSha256().isEmpty() + || !entry.rotationOperationId().equals(expectedEntry.rotationOperationId()) + || !entry.planDigest().equals(expectedEntry.planDigest()) + || !entry.validatorId().equals(expectedEntry.validatorId()) + || !entry.tokenProfile().equals(expectedEntry.tokenProfile()) + || !entry.audience().equals(expectedEntry.audience()) + || entry.probeKind() != expectedEntry.probeKind() + || !entry.jti().equals(expectedEntry.jti()) + || !entry.targetGeneration().equals(expectedEntry.targetGeneration()) + || !entry.targetKid().equals(expectedEntry.targetKid()) + || !entry.expectedActive().equals(expectedEntry.expectedActive()) + || entry.registryVersion() != expectedEntry.registryVersion() + || entry.plannedIssuedAtEpochSecond() != expectedEntry.plannedIssuedAtEpochSecond() + || entry.expiresAtEpochSecond() != expectedEntry.expiresAtEpochSecond()) { + throw new AmbiguousDeliveryException("Readiness Pod receipt requires its exact ISSUED entry"); + } + boolean alreadyVerified = entry.state() == ProbeState.VERIFIED; + if ((!alreadyVerified && entry.state() != ProbeState.ISSUED) + || (!alreadyVerified && !entry.equals(expectedEntry)) + || (alreadyVerified + && (entry.entryVersion() <= 1L + || entry + .verificationReceipt() + .filter(value -> value.receiptVersion() == 2) + .isEmpty()))) { + throw new AmbiguousDeliveryException("Readiness Pod receipt requires its exact ISSUED entry"); + } + List expectedPods = selectExpectedPods(entry, true); + ExpectedPod persistedPod = + expectedPods.stream() + .filter(value -> value.target().podUid().equals(expectedPod.target().podUid())) + .findFirst() + .orElseThrow(ReceiverUnavailableException::new); + if (!persistedPod.equals(expectedPod)) { + throw new QuarantinedStateException("Readiness Pod target changed after its immutable plan"); + } + PodTarget target = persistedPod.target(); + target.requireRoutablePodIdentity(); + long observedAt = acceptance.observedAtEpochSecond(); + if (!acceptance.podUid().equals(target.podUid()) + || !acceptance + .actualPodEndpoint() + .equals(target.exactPodEndpoint().orElseThrow().toString()) + || !acceptance.image().equals(target.image()) + || !acceptance.verifierConfigSha256().equals(target.verifierConfigSha256()) + || !acceptance.actualServiceUri().equals(target.canonicalServiceUri().orElseThrow()) + || !acceptance.actualPeerSpkiSha256().equals(target.podLeafSpkiSha256().orElseThrow()) + || !acceptance.jti().equals(entry.jti()) + || !acceptance.compactTokenSha256().equals(entry.compactTokenSha256().orElseThrow()) + || acceptance.result() != target.expectation() + || !entry.targetKid().equals(acceptance.verifiedKid())) { + throw new IdempotencyConflictException( + "Authenticated receiver evidence differs from the exact protected Pod target"); + } + requireNotExpired(entry, observedAt); + if (observedAt < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + + PodReceipt candidate = + podReceipt( + entry, + persistedPod, + acceptance, + alreadyVerified ? entry.entryVersion() - 1L : entry.entryVersion()); + PodReceipt existing = selectPodReceipt(candidate, true); + if (alreadyVerified) { + List retainedReceipts = selectPodReceipts(entry, true); + ProbeEntry sourceEntry = sourceEntryForVerifiedClosure(entry); + VerificationReceipt recomputed = + podReceiptClosure(plan, sourceEntry, expectedPods, retainedReceipts); + if (existing == null + || !existing.equals(candidate) + || retainedReceipts.size() != expectedPods.size() + || entry.verificationReceipt().filter(recomputed::equals).isEmpty()) { + throw new IdempotencyConflictException( + "A completed readiness Pod receipt retry differs from its immutable evidence"); + } + return entry; + } + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "A per-Pod readiness receipt already exists with different evidence"); + } + } else { + insertPodReceipt(candidate); + PodReceipt readback = selectPodReceipt(candidate, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException("Readiness Pod receipt did not read back exactly"); + } + } + + List receipts = selectPodReceipts(entry, true); + if (receipts.size() != expectedPods.size()) { + if (receipts.size() > expectedPods.size()) { + throw new QuarantinedStateException("Readiness Pod receipt set exceeds its exact target"); + } + ProbeEntry partial = selectEntry(entry, true); + if (partial == null || partial.state() != ProbeState.ISSUED) { + throw new QuarantinedStateException("Partial per-Pod receipt changed its logical entry"); + } + return partial; + } + VerificationReceipt closure = podReceiptClosure(plan, entry, expectedPods, receipts); + long resultEntryVersion = Math.addExact(entry.entryVersion(), 1L); + VerificationReceipt finalReceipt = + new VerificationReceipt( + closure.receiptVersion(), + entry.entryVersion(), + resultEntryVersion, + closure.observedAtEpochSecond(), + closure.receiptSha256(), + closure.verifiedKid(), + closure.validatorInstanceId(), + closure.validatorBindingDigest(), + closure.validatorConfigRevision(), + closure.validatorPeerUri(), + closure.validatorPeerSpkiSha256(), + closure.podReceiptCount(), + closure.podReceiptClosureSha256()); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'VERIFIED', entry_version = ?, verification_receipt_version = ?, " + + "verification_source_entry_version = ?, verified_at_epoch_seconds = ?, " + + "verified_kid = ?, validator_instance_id = ?, validator_binding_digest = ?, " + + "validator_config_revision = ?, validator_peer_uri = ?, " + + "validator_peer_spki_sha256 = ?, verification_receipt_sha256 = ?, " + + "pod_receipt_count = ?, pod_receipt_closure_sha256 = ? " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND jti = ? AND plan_digest = ? " + + "AND entry_plan_version = 2 AND state = 'ISSUED' AND entry_version = ? " + + "AND target_generation = ? AND target_kid = ? AND compact_token_sha256 = ? " + + "AND verification_receipt_sha256 IS NULL " + + "AND CURRENT_TIMESTAMP >= to_timestamp(planned_issued_at_epoch_seconds) " + + "AND CURRENT_TIMESTAMP < to_timestamp(expires_at_epoch_seconds)", + finalReceipt.resultEntryVersion(), + finalReceipt.receiptVersion(), + finalReceipt.sourceEntryVersion(), + finalReceipt.observedAtEpochSecond(), + finalReceipt.verifiedKid(), + finalReceipt.validatorInstanceId(), + finalReceipt.validatorBindingDigest(), + finalReceipt.validatorConfigRevision(), + finalReceipt.validatorPeerUri(), + finalReceipt.validatorPeerSpkiSha256(), + finalReceipt.receiptSha256(), + finalReceipt.podReceiptCount(), + finalReceipt.podReceiptClosureSha256(), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name(), + entry.jti(), + entry.planDigest(), + entry.entryVersion(), + Long.parseLong(entry.targetGeneration()), + entry.targetKid(), + entry.compactTokenSha256().orElseThrow()); + if (changed != 1) { + throw new VersionConflictException("Readiness per-Pod closure lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != ProbeState.VERIFIED + || readback.entryVersion() != finalReceipt.resultEntryVersion() + || readback.verificationReceipt().filter(finalReceipt::equals).isEmpty()) { + throw new QuarantinedStateException("Readiness per-Pod closure did not read back exactly"); + } + return readback; + } + + private List selectExpectedPods(ProbeEntry entry, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + EXPECTED_POD_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? ORDER BY pod_uid" + + (lock ? " FOR KEY SHARE" : ""), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name()); + List expected = new ArrayList<>(rows.size()); + for (Record row : rows) { + String endpoint = row.get("exact_pod_endpoint", String.class); + expected.add( + new ExpectedPod( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("jti", UUID.class), + new PodTarget( + row.get("inventory_snapshot_digest", String.class), + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("cluster_incarnation_uid", UUID.class).toString(), + row.get("kubernetes_namespace", String.class), + row.get("namespace_uid", UUID.class).toString(), + row.get("api_binding_revision", String.class), + row.get("api_binding_digest", String.class), + row.get("inventory_binding_revision", String.class), + row.get("inventory_binding_digest", String.class), + row.get("validator_id", String.class), + row.get("deployment_uid", UUID.class).toString(), + row.get("pod_uid", UUID.class).toString(), + row.get("pod_ip", String.class), + row.get("image", String.class), + row.get("verifier_config_sha256", String.class), + row.get("applicability_matrix_digest", String.class), + ProbeExpectation.valueOf(row.get("expected_outcome", String.class)), + Optional.ofNullable(endpoint).map(URI::create), + Optional.ofNullable(row.get("canonical_service_uri", String.class)), + Optional.ofNullable(row.get("expected_pod_leaf_spki_sha256", String.class))))); + } + return List.copyOf(expected); + } + + private void requireLiveInventoryMatches( + ReadinessProbePlan plan, + Binding binding, + TrustFence trust, + InventorySnapshot liveInventory, + ObservationContext expectedContext) { + Objects.requireNonNull(liveInventory, "Fresh protected live inventory is required"); + requireFreshLiveInventory(liveInventory); + String expectedDigest = + plan.inventorySnapshotDigest().orElseThrow(ReceiverUnavailableException::new); + AccountJwtValidatorInventoryRepository.StoredSnapshot stored = + inventoryRepository.readRequired(expectedDigest, binding, trust); + if (liveInventory.observationContext().filter(expectedContext::equals).isEmpty() + || !expectedDigest.equals(liveInventory.digest()) + || !stored.digest().equals(liveInventory.digest()) + || !stored.environmentId().equals(liveInventory.environmentId()) + || !stored.clusterId().equals(liveInventory.clusterId()) + || !stored.clusterIncarnationUid().equals(liveInventory.clusterIncarnationUid()) + || !stored.namespace().equals(liveInventory.namespace()) + || !stored.namespaceUid().equals(liveInventory.namespaceUid()) + || !stored.apiBindingRevision().equals(liveInventory.apiBindingRevision()) + || !stored.apiBindingDigest().equals(liveInventory.apiBindingDigest()) + || !stored.inventoryBindingRevision().equals(liveInventory.inventoryBindingRevision()) + || !stored.inventoryBindingDigest().equals(liveInventory.inventoryBindingDigest()) + || !MessageDigest.isEqual(stored.canonicalBytes(), liveInventory.canonicalBytes())) { + throw new ReceiverUnavailableException(); + } + } + + private static void requireObservationContext( + CurrentEvidence current, InventorySnapshot snapshot) { + if (snapshot.observationContext().filter(observationContext(current)::equals).isEmpty()) { + throw new InventoryPlanConflictException(); + } + } + + private static ObservationContext observationContext(CurrentEvidence current) { + return observationContext( + current.request().operationId(), + current.request().operationDigest(), + new SignerFence(current.state().durableActive(), current.state().publishedActive())); + } + + private static ObservationContext observationContext( + UUID operationId, String operationDigest, SignerFence expectedFence) { + if (!expectedFence.durableActive().equals(expectedFence.publishedActive())) { + throw new StaleOperationException("JWT active signer fence changed during inventory proof"); + } + ObservationPurpose purpose = + expectedFence.durableActive().isEmpty() + ? ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES + : ObservationPurpose.STRICT_READY; + return new ObservationContext(purpose, operationId, operationDigest); + } + + private void requireFreshLiveInventory(InventorySnapshot snapshot) { + long observedAt = snapshot.observedAt().getEpochSecond(); + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null) { + throw new StorageUnavailableException("Account validator inventory clock is unavailable"); + } + if (observedAt <= 0L + || observedAt > databaseNow + || databaseNow - observedAt > MAX_VALIDATOR_CACHE_AGE_SECONDS) { + throw new ReceiverUnavailableException(); + } + } + + private boolean hasCompletePodReceiptClosure(ReadinessProbePlan plan) { + if (plan.planVersion() != INVENTORY_PLAN_VERSION || !plan.validatorInventoryComplete()) { + return false; + } + int totalReceipts = 0; + for (ProbeEntry entry : plan.entries()) { + if (entry.state() != ProbeState.VERIFIED) { + return false; + } + VerificationReceipt receipt = entry.verificationReceipt().orElseThrow(); + if (receipt.receiptVersion() != 2) { + throw new QuarantinedStateException( + "V2 readiness entry has no per-Pod verification closure receipt"); + } + List expectedPods = selectExpectedPods(entry, true); + List podReceipts = selectPodReceipts(entry, true); + if (expectedPods.isEmpty() || expectedPods.size() != receipt.podReceiptCount()) { + throw new QuarantinedStateException( + "V2 readiness receipt count differs from its exact expected Pod inventory"); + } + if (podReceipts.size() < expectedPods.size()) { + return false; + } + if (podReceipts.size() != expectedPods.size()) { + throw new QuarantinedStateException( + "V2 readiness receipt set exceeds its exact expected Pod inventory"); + } + ProbeEntry sourceEntry = sourceEntryForVerifiedClosure(entry); + VerificationReceipt recomputed = + podReceiptClosure(plan, sourceEntry, expectedPods, podReceipts); + if (!recomputed.equals(receipt)) { + throw new QuarantinedStateException( + "V2 readiness entry closure differs from retained per-Pod receipts"); + } + totalReceipts = Math.addExact(totalReceipts, podReceipts.size()); + if (totalReceipts > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness Pod receipt closure exceeds its bound"); + } + } + return totalReceipts > 0; + } + + private void insertPodReceipt(PodReceipt receipt) { + dsl.execute( + "INSERT INTO " + + POD_RECEIPT_TABLE + + " (rotation_operation_id, plan_digest, validator_id, token_profile, audience, " + + "probe_kind, pod_uid, receipt_version, jti, source_entry_version, " + + "compact_token_sha256, target_generation, target_kid, expected_active_generation, " + + "expected_active_kid, outcome, observed_pod_uid, observed_image, " + + "observed_verifier_config_sha256, verified_kid, receiver_endpoint, " + + "receiver_service_uri, receiver_peer_spki_sha256, observed_at_epoch_seconds, receipt_sha256) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) " + + "DO NOTHING", + receipt.rotationOperationId(), + receipt.planDigest(), + receipt.validatorId(), + receipt.tokenProfile(), + receipt.audience(), + receipt.probeKind().name(), + UUID.fromString(receipt.podUid()), + 1, + receipt.jti(), + receipt.sourceEntryVersion(), + receipt.compactTokenSha256(), + Long.parseLong(receipt.targetGeneration()), + receipt.targetKid(), + receipt.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null), + receipt.expectedActive().map(ActiveSigner::kid).orElse(null), + receipt.outcome().name(), + UUID.fromString(receipt.observedPodUid()), + receipt.image(), + receipt.verifierConfigSha256(), + receipt.verifiedKid(), + receipt.receiverEndpoint().toString(), + receipt.receiverServiceUri(), + receipt.receiverPeerSpkiSha256(), + receipt.observedAtEpochSecond(), + receipt.receiptSha256()); + } + + private PodReceipt selectPodReceipt(PodReceipt key, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + POD_RECEIPT_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND pod_uid = ?" + + (lock ? " FOR UPDATE" : ""), + key.rotationOperationId(), + key.validatorId(), + key.tokenProfile(), + key.audience(), + key.probeKind().name(), + UUID.fromString(key.podUid())); + return row == null ? null : decodePodReceipt(row); + } + + private List selectPodReceipts(ProbeEntry entry, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + POD_RECEIPT_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? ORDER BY pod_uid" + + (lock ? " FOR UPDATE" : ""), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name()); + List receipts = new ArrayList<>(rows.size()); + for (Record row : rows) { + receipts.add(decodePodReceipt(row)); + } + return List.copyOf(receipts); + } + + private static PodReceipt decodePodReceipt(Record row) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + PodReceipt receipt = + new PodReceipt( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("pod_uid", UUID.class).toString(), + row.get("jti", UUID.class), + row.get("source_entry_version", Long.class), + row.get("compact_token_sha256", String.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + decodeActive(activeGeneration, activeKid), + ProbeExpectation.valueOf(row.get("outcome", String.class)), + row.get("observed_pod_uid", UUID.class).toString(), + row.get("observed_image", String.class), + row.get("observed_verifier_config_sha256", String.class), + row.get("verified_kid", String.class), + URI.create(row.get("receiver_endpoint", String.class)), + row.get("receiver_service_uri", String.class), + row.get("receiver_peer_spki_sha256", String.class), + row.get("observed_at_epoch_seconds", Long.class), + row.get("receipt_sha256", String.class)); + if (!receipt.receiptSha256().equals(podReceiptDigest(receipt))) { + throw new QuarantinedStateException("Immutable per-Pod readiness receipt digest is invalid"); + } + return receipt; + } + + private static PodReceipt podReceipt( + ProbeEntry entry, + ExpectedPod expected, + AuthenticatedAcceptance acceptance, + long sourceEntryVersion) { + PodTarget target = expected.target(); + PodReceipt unsigned = + new PodReceipt( + entry.rotationOperationId(), + entry.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + target.podUid(), + entry.jti(), + sourceEntryVersion, + entry.compactTokenSha256().orElseThrow(), + entry.targetGeneration(), + entry.targetKid(), + entry.expectedActive(), + acceptance.result(), + acceptance.podUid(), + acceptance.image(), + acceptance.verifierConfigSha256(), + acceptance.verifiedKid(), + URI.create(acceptance.actualPodEndpoint()), + acceptance.actualServiceUri(), + acceptance.actualPeerSpkiSha256(), + acceptance.observedAtEpochSecond(), + "0".repeat(64)); + return new PodReceipt( + unsigned.rotationOperationId(), + unsigned.planDigest(), + unsigned.validatorId(), + unsigned.tokenProfile(), + unsigned.audience(), + unsigned.probeKind(), + unsigned.podUid(), + unsigned.jti(), + unsigned.sourceEntryVersion(), + unsigned.compactTokenSha256(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.expectedActive(), + unsigned.outcome(), + unsigned.observedPodUid(), + unsigned.image(), + unsigned.verifierConfigSha256(), + unsigned.verifiedKid(), + unsigned.receiverEndpoint(), + unsigned.receiverServiceUri(), + unsigned.receiverPeerSpkiSha256(), + unsigned.observedAtEpochSecond(), + podReceiptDigest(unsigned)); + } + + private static ProbeEntry sourceEntryForVerifiedClosure(ProbeEntry verified) { + VerificationReceipt receipt = verified.verificationReceipt().orElseThrow(); + if (receipt.receiptVersion() != 2 + || receipt.sourceEntryVersion() + 1L != verified.entryVersion()) { + throw new QuarantinedStateException("Verified per-Pod closure has an invalid source version"); + } + return new ProbeEntry( + verified.rotationOperationId(), + verified.planDigest(), + verified.validatorId(), + verified.tokenProfile(), + verified.audience(), + verified.probeKind(), + verified.jti(), + verified.targetGeneration(), + verified.targetKid(), + verified.expectedActive(), + verified.registryVersion(), + receipt.sourceEntryVersion(), + verified.plannedIssuedAtEpochSecond(), + verified.expiresAtEpochSecond(), + ProbeState.ISSUED, + Optional.empty(), + verified.signingAttemptedAtEpochSecond(), + verified.compactTokenSha256(), + Optional.empty()); + } + + private static String podReceiptDigest(PodReceipt receipt) { + Map value = new LinkedHashMap<>(); + value.put("domain", "account-jwt-readiness-per-pod-receipt/v1"); + value.put("rotationOperationId", receipt.rotationOperationId().toString()); + value.put("planDigest", receipt.planDigest()); + value.put("validatorId", receipt.validatorId()); + value.put("tokenProfile", receipt.tokenProfile()); + value.put("audience", receipt.audience()); + value.put("probeKind", receipt.probeKind().name()); + value.put("podUid", receipt.podUid()); + value.put("jti", receipt.jti().toString()); + value.put("sourceEntryVersion", receipt.sourceEntryVersion()); + value.put("compactTokenSha256", receipt.compactTokenSha256()); + value.put("targetGeneration", receipt.targetGeneration()); + value.put("targetKid", receipt.targetKid()); + value.put("expectedActive", activeMap(receipt.expectedActive())); + value.put("outcome", receipt.outcome().name()); + value.put("observedPodUid", receipt.observedPodUid()); + value.put("image", receipt.image()); + value.put("verifierConfigSha256", receipt.verifierConfigSha256()); + value.put("verifiedKid", receipt.verifiedKid()); + value.put("receiverEndpoint", receipt.receiverEndpoint().toString()); + value.put("receiverServiceUri", receipt.receiverServiceUri()); + value.put("receiverPeerSpkiSha256", receipt.receiverPeerSpkiSha256()); + value.put("observedAtEpochSecond", receipt.observedAtEpochSecond()); + return digest(value); + } + + private static VerificationReceipt podReceiptClosure( + ReadinessProbePlan plan, + ProbeEntry entry, + List expectedPods, + List receipts) { + Map expectedByUid = new LinkedHashMap<>(); + for (ExpectedPod expected : expectedPods) { + if (expectedByUid.putIfAbsent(expected.target().podUid(), expected) != null) { + throw new QuarantinedStateException("Readiness Pod plan contains duplicate Pod UIDs"); + } + } + Map receiptsByUid = new LinkedHashMap<>(); + for (PodReceipt receipt : receipts) { + ExpectedPod expected = expectedByUid.get(receipt.podUid()); + if (expected == null + || receiptsByUid.putIfAbsent(receipt.podUid(), receipt) != null + || !receipt.rotationOperationId().equals(entry.rotationOperationId()) + || !receipt.planDigest().equals(entry.planDigest()) + || !receipt.validatorId().equals(entry.validatorId()) + || !receipt.tokenProfile().equals(entry.tokenProfile()) + || !receipt.audience().equals(entry.audience()) + || receipt.probeKind() != entry.probeKind() + || !receipt.jti().equals(entry.jti()) + || receipt.sourceEntryVersion() != entry.entryVersion() + || !receipt.compactTokenSha256().equals(entry.compactTokenSha256().orElseThrow()) + || !receipt.targetGeneration().equals(entry.targetGeneration()) + || !receipt.targetKid().equals(entry.targetKid()) + || !receipt.expectedActive().equals(entry.expectedActive()) + || receipt.outcome() != expected.target().expectation() + || !receipt.observedPodUid().equals(expected.target().podUid()) + || !receipt.image().equals(expected.target().image()) + || !receipt.verifierConfigSha256().equals(expected.target().verifierConfigSha256()) + || !receipt.receiverEndpoint().equals(expected.target().exactPodEndpoint().orElseThrow()) + || !receipt + .receiverServiceUri() + .equals(expected.target().canonicalServiceUri().orElseThrow()) + || !receipt + .receiverPeerSpkiSha256() + .equals(expected.target().podLeafSpkiSha256().orElseThrow()) + || !receipt.receiptSha256().equals(podReceiptDigest(receipt))) { + throw new QuarantinedStateException( + "Readiness Pod receipt does not match its exact target"); + } + } + if (expectedByUid.size() != receiptsByUid.size() + || expectedByUid.isEmpty() + || expectedByUid.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness Pod receipt closure is incomplete"); + } + ProbeExpectation expectedOutcome = null; + List> closurePods = new ArrayList<>(); + List ordered = + expectedPods.stream() + .sorted(java.util.Comparator.comparing(value -> value.target().podUid())) + .toList(); + long observedAt = 0L; + for (ExpectedPod expected : ordered) { + PodTarget target = expected.target(); + PodReceipt receipt = receiptsByUid.get(target.podUid()); + if (receipt == null || (expectedOutcome != null && expectedOutcome != target.expectation())) { + throw new QuarantinedStateException("Readiness Pod expectations are not a closed matrix"); + } + expectedOutcome = target.expectation(); + observedAt = Math.max(observedAt, receipt.observedAtEpochSecond()); + Map pod = new LinkedHashMap<>(); + pod.put("podUid", target.podUid()); + pod.put("podIpEndpoint", target.exactPodEndpoint().orElseThrow().toString()); + pod.put("serviceUri", target.canonicalServiceUri().orElseThrow()); + pod.put("leafSpkiSha256", target.podLeafSpkiSha256().orElseThrow()); + pod.put("image", target.image()); + pod.put("verifierConfigSha256", target.verifierConfigSha256()); + pod.put("receiptSha256", receipt.receiptSha256()); + closurePods.add(pod); + } + ExpectedPod first = ordered.get(0); + PodTarget firstTarget = first.target(); + Map closure = new LinkedHashMap<>(); + closure.put("domain", "account-jwt-readiness-per-pod-closure/v1"); + closure.put("rotationOperationId", plan.operationId().toString()); + closure.put("planDigest", plan.planDigest()); + closure.put("applicabilityMatrixDigest", plan.applicabilityMatrixDigest()); + closure.put("inventorySnapshotDigest", plan.inventorySnapshotDigest().orElseThrow()); + closure.put("validatorId", entry.validatorId()); + closure.put("tokenProfile", entry.tokenProfile()); + closure.put("audience", entry.audience()); + closure.put("probeKind", entry.probeKind().name()); + closure.put("jti", entry.jti().toString()); + closure.put("sourceEntryVersion", entry.entryVersion()); + closure.put("compactTokenSha256", entry.compactTokenSha256().orElseThrow()); + closure.put("targetGeneration", entry.targetGeneration()); + closure.put("targetKid", entry.targetKid()); + closure.put("expectedActive", activeMap(entry.expectedActive())); + closure.put("pods", closurePods); + String closureSha256 = digest(closure); + return new VerificationReceipt( + 2, + entry.entryVersion(), + entry.entryVersion() + 1L, + observedAt, + closureSha256, + entry.targetKid(), + firstTarget.podUid(), + firstTarget.inventoryBindingDigest(), + firstTarget.inventoryBindingRevision(), + firstTarget.canonicalServiceUri().orElseThrow(), + firstTarget.podLeafSpkiSha256().orElseThrow(), + expectedPods.size(), + closureSha256); + } + private ReadinessProbePlan selectPlan(UUID operationId, boolean lock) { Record row = dsl.fetchOne( @@ -1114,13 +2185,10 @@ private List selectEntries(UUID operationId, boolean lock) { return List.copyOf(entries); } - // Keep the candidate's digest/equality order identical to the durable key order. If a future - // schema adds identity dimensions (for example Pod membership), append them to both this - // comparator and SELECT's ORDER BY; V1 plans retain their existing tuple and digest semantics. + // V1 digests bind the established canary/control/player/delegation profile order. V2 adds + // validator identity as the leading key; per-Pod requirements remain separately bound rows. private static final Comparator PROBE_ENTRY_ORDER = Comparator.comparing(ProbeEntry::validatorId) - // V1 plan digests bind the established tuple order. Keep it explicit and shared with - // durable readback while appending any future identity dimensions consistently. .thenComparingInt(entry -> profileOrder(entry.tokenProfile())) .thenComparing(ProbeEntry::audience) .thenComparing(entry -> entry.probeKind().name()); @@ -1206,6 +2274,8 @@ private VerificationReceipt decodeVerificationReceipt(Record row) { String peerUri = row.get("validator_peer_uri", String.class); String peerSpki = row.get("validator_peer_spki_sha256", String.class); String receiptSha256 = row.get("verification_receipt_sha256", String.class); + Short podReceiptCount = row.get("pod_receipt_count", Short.class); + String podReceiptClosureSha256 = row.get("pod_receipt_closure_sha256", String.class); if (version == null && sourceVersion == null && verifiedAt == null @@ -1215,13 +2285,14 @@ private VerificationReceipt decodeVerificationReceipt(Record row) { && configRevision == null && peerUri == null && peerSpki == null - && receiptSha256 == null) { + && receiptSha256 == null + && podReceiptCount == null + && podReceiptClosureSha256 == null) { return null; } if (version == null || sourceVersion == null || verifiedAt == null - || verifiedKid == null || validatorInstanceId == null || bindingDigest == null || configRevision == null @@ -1230,6 +2301,11 @@ private VerificationReceipt decodeVerificationReceipt(Record row) { || receiptSha256 == null) { throw new QuarantinedStateException("Readiness verification receipt is partial"); } + if ((version == 1 + && (verifiedKid == null || podReceiptCount != null || podReceiptClosureSha256 != null)) + || (version == 2 && (podReceiptCount == null || podReceiptClosureSha256 == null))) { + throw new QuarantinedStateException("Readiness verification receipt version is partial"); + } Long resultVersion = Math.addExact(sourceVersion, 1L); return new VerificationReceipt( version.intValue(), @@ -1242,7 +2318,9 @@ private VerificationReceipt decodeVerificationReceipt(Record row) { bindingDigest, configRevision, peerUri, - peerSpki); + peerSpki, + podReceiptCount == null ? 0 : podReceiptCount.intValue(), + podReceiptClosureSha256); } private ReadinessProbePlan decodePlan(Record row, List entries) { @@ -1325,21 +2403,112 @@ private void requirePlanMatchesCurrent(ReadinessProbePlan plan, CurrentEvidence || !plan.publicationIntentDigest().equals(intent.intentDigest()) || !plan.publicationReceiptDigest().equals(receipt.receiptDigest()) || !plan.mountedObservationDigest().equals(mount.observationDigest()) - || !plan.applicabilityMatrixJson().equals(applicabilityMatrixJson()) + || (plan.planVersion() == 1 + && !plan.applicabilityMatrixJson().equals(applicabilityMatrixJson())) || !plan.applicabilityMatrixDigest() .equals(sha256(plan.applicabilityMatrixJson().getBytes(StandardCharsets.UTF_8))) - || plan.validatorInventoryComplete() + || (plan.planVersion() == 1 && plan.validatorInventoryComplete()) + || (plan.planVersion() == INVENTORY_PLAN_VERSION && !matchesStoredV2Inventory(plan)) || !plan.planDigest().equals(planDigest(plan))) { throw new StaleOperationException( "Readiness probe plan no longer matches current Account evidence"); } } + private static AccountJwtJwksPublicationRepository.PromotionPublicationEvidence + promotionPublicationEvidence( + AccountJwtJwksPublicationRepository.PublicationEvidence publication) { + return new AccountJwtJwksPublicationRepository.PromotionPublicationEvidence( + publication.intent(), + publication.receipt().orElseThrow(() -> new MissingPublicationEvidenceException()), + publication + .mountedCorrespondence() + .orElseThrow(() -> new MissingPublicationEvidenceException())); + } + + private boolean matchesStoredV2Inventory(ReadinessProbePlan plan) { + String inventoryDigest = plan.inventorySnapshotDigest().orElse(null); + if (inventoryDigest == null) { + return false; + } + AccountJwtValidatorInventoryRepository.StoredSnapshot snapshot = + inventoryRepository.readRequired(inventoryDigest, plan.binding(), plan.trustFence()); + try { + JsonNode matrix = JSON.readTree(plan.applicabilityMatrixJson()); + JsonNode source = matrix == null ? null : matrix.get("source"); + if (matrix == null + || !matrix.isObject() + || !"2".equals(matrix.path("schemaVersion").asText()) + || !inventoryDigest.equals(matrix.path("inventorySnapshotDigest").asText()) + || source == null + || !snapshot.apiBindingRevision().equals(source.path("apiBindingRevision").asText()) + || !snapshot.apiBindingDigest().equals(source.path("apiBindingDigest").asText()) + || !snapshot + .inventoryBindingRevision() + .equals(source.path("inventoryBindingRevision").asText()) + || !snapshot + .inventoryBindingDigest() + .equals(source.path("inventoryBindingDigest").asText()) + || !snapshot.clusterIncarnationUid().equals(source.path("clusterIncarnationUid").asText()) + || !snapshot.namespace().equals(source.path("namespace").asText()) + || !snapshot.namespaceUid().equals(source.path("namespaceUid").asText()) + || !snapshot.environmentId().equals(source.path("environmentId").asText()) + || !snapshot.clusterId().equals(source.path("clusterId").asText())) { + return false; + } + JsonNode validators = matrix.get("validators"); + if (validators == null + || !validators.isArray() + || validators.isEmpty() + || validators.size() > 32) { + return false; + } + if (!plan.validatorInventoryComplete()) { + return "PARTIAL_UNCONFIRMED".equals(matrix.path("inventoryStatus").asText()); + } + if (!"PROTECTED_LIVE_COMPLETE".equals(matrix.path("inventoryStatus").asText()) + || validators.size() != 2) { + return false; + } + JsonNode accountProfiles = null; + JsonNode gameSessionProfiles = null; + for (JsonNode validator : validators) { + String validatorId = validator.path("validatorId").asText(); + if (VALIDATOR_ID.equals(validatorId)) { + accountProfiles = validator.get("applicableProfiles"); + } else if ("game-session-service".equals(validatorId)) { + gameSessionProfiles = validator.get("applicableProfiles"); + } else { + return false; + } + } + return hasExactProfiles(accountProfiles, PRODUCTION_PROFILE_CASES) + && hasExactProfiles( + gameSessionProfiles, + List.of(new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE))); + } catch (Exception failure) { + throw new QuarantinedStateException("V2 readiness inventory matrix cannot be read back"); + } + } + + private static boolean hasExactProfiles(JsonNode node, List expected) { + if (node == null || !node.isArray() || node.size() != expected.size()) { + return false; + } + Set actual = new java.util.HashSet<>(); + for (JsonNode profile : node) { + actual.add( + new ProfileCase( + profile.path("tokenProfile").asText(), profile.path("audience").asText())); + } + return actual.equals(Set.copyOf(expected)); + } + private static void requirePreparedPlanMatches( ReadinessProbePlan plan, GenerationResult generation, AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence promotion, - AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication) { + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication) { AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); AccountJwtJwksPublicationRepository.PublicationReceipt receipt = publication.receipt(); AccountJwtJwksPublicationRepository.MountObservation mount = @@ -1569,10 +2738,198 @@ static String applicabilityMatrixJson() { } } + private static String applicabilityMatrixJson( + InventorySnapshot snapshot, boolean inventoryComplete) { + List> validators = + snapshot.validators().stream() + .sorted(java.util.Comparator.comparing(ValidatorObservation::validatorId)) + .map( + validator -> { + List> applicable = + validator.profiles().stream() + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .sorted( + java.util.Comparator.comparing( + (Map value) -> + value.get("tokenProfile").toString()) + .thenComparing(value -> value.get("audience").toString())) + .toList(); + List> inapplicable = + PRODUCTION_PROFILE_CASES.stream() + .filter( + profile -> + validator.profiles().stream() + .noneMatch( + actual -> + actual.tokenProfile().equals(profile.tokenProfile()) + && actual.audience().equals(profile.audience()))) + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .toList(); + Map value = new LinkedHashMap<>(); + value.put("applicableProfiles", applicable); + value.put("deploymentUid", validator.deploymentUid()); + value.put("image", validator.image()); + value.put("podCount", validator.pods().size()); + value.put( + "pods", + validator.pods().stream() + .sorted(java.util.Comparator.comparing(PodObservation::uid)) + .map( + pod -> + Map.of( + "podUid", pod.uid(), + "podIp", pod.podIp(), + "exactPodEndpoint", pod.endpoint().toString(), + "canonicalServiceUri", pod.receiverServiceUri(), + "leafSpkiSha256", pod.leafSpkiSha256(), + "image", pod.image(), + "verifierConfigSha256", pod.verifierConfigSha256())) + .toList()); + value.put("inapplicableProfiles", inapplicable); + value.put("validatorId", validator.validatorId()); + value.put("verifierConfigSha256", validator.verifierConfigSha256()); + return value; + }) + .toList(); + Map source = new LinkedHashMap<>(); + source.put("apiBindingDigest", snapshot.apiBindingDigest()); + source.put("apiBindingRevision", snapshot.apiBindingRevision()); + source.put("clusterIncarnationUid", snapshot.clusterIncarnationUid()); + source.put("environmentId", snapshot.environmentId()); + source.put("inventoryBindingDigest", snapshot.inventoryBindingDigest()); + source.put("inventoryBindingRevision", snapshot.inventoryBindingRevision()); + source.put("namespace", snapshot.namespace()); + source.put("namespaceUid", snapshot.namespaceUid()); + Map matrix = new LinkedHashMap<>(); + matrix.put("inventoryStatus", inventoryComplete ? "PROTECTED_LIVE_COMPLETE" : INVENTORY_STATUS); + matrix.put("inventorySnapshotDigest", snapshot.digest()); + matrix.put( + "productionProfiles", + PRODUCTION_PROFILE_CASES.stream() + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .toList()); + matrix.put("schemaVersion", INVENTORY_PLAN_VERSION); + matrix.put("source", source); + matrix.put("validators", validators); + try { + String canonical = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(matrix)), + StandardCharsets.UTF_8); + if (canonical.getBytes(StandardCharsets.UTF_8).length > 8192) { + throw new InventoryPlanConflictException(); + } + return canonical; + } catch (IOException ex) { + throw new StorageUnavailableException( + "Readiness inventory applicability matrix cannot be canonicalized"); + } + } + + private static boolean inventoryPlanComplete(InventorySnapshot snapshot) { + Map> actual = new LinkedHashMap<>(); + for (ValidatorObservation validator : snapshot.validators()) { + Set profiles = new java.util.HashSet<>(); + for (var profile : validator.profiles()) { + ProfileCase candidate = new ProfileCase(profile.tokenProfile(), profile.audience()); + if (!PRODUCTION_PROFILE_CASES.contains(candidate) || !profiles.add(candidate)) { + return false; + } + } + if (validator.pods().isEmpty() + || actual.putIfAbsent(validator.validatorId(), profiles) != null) { + return false; + } + } + Set accountProfiles = actual.get(VALIDATOR_ID); + Set gameSessionProfiles = actual.get("game-session-service"); + return actual.keySet().equals(Set.of(VALIDATOR_ID, "game-session-service")) + && accountProfiles != null + && accountProfiles.equals(Set.copyOf(PRODUCTION_PROFILE_CASES)) + && gameSessionProfiles != null + && gameSessionProfiles.equals( + Set.of(new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE))); + } + + private static List expectedPods( + ReadinessProbePlan plan, InventorySnapshot snapshot) { + List expected = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ValidatorObservation validator = + snapshot.validators().stream() + .filter(value -> value.validatorId().equals(entry.validatorId())) + .findFirst() + .orElseThrow(InventoryPlanConflictException::new); + ProbeExpectation expectation = + entry.probeKind() == ProbeKind.CANARY + ? ProbeExpectation.ACCEPT + : validator.profiles().stream() + .anyMatch( + profile -> + profile.tokenProfile().equals(entry.tokenProfile()) + && profile.audience().equals(entry.audience())) + ? ProbeExpectation.ACCEPT + : ProbeExpectation.INAPPLICABLE_REJECT; + for (PodObservation pod : validator.pods()) { + PodTarget target = + new PodTarget( + snapshot.digest(), + snapshot.environmentId(), + snapshot.clusterId(), + snapshot.clusterIncarnationUid(), + snapshot.namespace(), + snapshot.namespaceUid(), + snapshot.apiBindingRevision(), + snapshot.apiBindingDigest(), + snapshot.inventoryBindingRevision(), + snapshot.inventoryBindingDigest(), + validator.validatorId(), + validator.deploymentUid(), + pod.uid(), + pod.podIp(), + pod.image(), + pod.verifierConfigSha256(), + plan.applicabilityMatrixDigest(), + expectation, + Optional.of(pod.endpoint()), + Optional.of(pod.receiverServiceUri()), + Optional.of(pod.leafSpkiSha256())); + expected.add( + new ExpectedPod( + plan.operationId(), + plan.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + entry.jti(), + target)); + } + } + if (expected.isEmpty() || expected.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new InventoryPlanConflictException(); + } + return List.copyOf(expected); + } + private static String planDigest( CurrentEvidence current, String matrixJson, String matrixDigest, + int planVersion, + boolean validatorInventoryComplete, long plannedAt, long notBefore, long expiresAt, @@ -1582,7 +2939,7 @@ private static String planDigest( GenerationRequest request = current.request(); GenerationResult result = current.result(); AccountJwtJwksPublicationRepository.PublicationEvidence publication = current.publication(); - preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v1"); + preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v" + planVersion); preimage.put("rotationOperationId", request.operationId().toString()); preimage.put("environmentId", request.binding().environmentId()); preimage.put("clusterId", request.binding().clusterId()); @@ -1611,7 +2968,10 @@ private static String planDigest( publication.mountedCorrespondence().orElseThrow().observationDigest()); preimage.put("applicabilityMatrixJson", matrixJson); preimage.put("applicabilityMatrixDigest", matrixDigest); - preimage.put("validatorInventoryComplete", false); + preimage.put("validatorInventoryComplete", validatorInventoryComplete); + if (planVersion != 1) { + preimage.put("planVersion", planVersion); + } inventorySnapshotDigest.ifPresent(digest -> preimage.put("inventorySnapshotDigest", digest)); preimage.put("maximumCacheAgeSeconds", MAX_VALIDATOR_CACHE_AGE_SECONDS); preimage.put("plannedAtEpochSecond", plannedAt); @@ -1630,7 +2990,7 @@ private static String planDigest(ReadinessProbePlan plan) { private static Map planDigestMap(ReadinessProbePlan plan) { Map preimage = new LinkedHashMap<>(); - preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v1"); + preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v" + plan.planVersion()); preimage.put("rotationOperationId", plan.operationId().toString()); preimage.put("environmentId", plan.binding().environmentId()); preimage.put("clusterId", plan.binding().clusterId()); @@ -1658,6 +3018,9 @@ private static Map planDigestMap(ReadinessProbePlan plan) { preimage.put("applicabilityMatrixJson", plan.applicabilityMatrixJson()); preimage.put("applicabilityMatrixDigest", plan.applicabilityMatrixDigest()); preimage.put("validatorInventoryComplete", plan.validatorInventoryComplete()); + if (plan.planVersion() != 1) { + preimage.put("planVersion", plan.planVersion()); + } plan.inventorySnapshotDigest() .ifPresent(digest -> preimage.put("inventorySnapshotDigest", digest)); preimage.put("maximumCacheAgeSeconds", plan.maximumCacheAgeSeconds()); @@ -1726,7 +3089,7 @@ private static String deliveryClaimDigest(DeliveryClaim claim) { private static String readinessPromotionDigest( ReadinessProbePlan plan, GenerationResult generation, - AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication, String inventoryEvidenceReference, String inventoryEvidenceDigest, List verifiedProbes) { @@ -1735,7 +3098,7 @@ private static String readinessPromotionDigest( preimage.put("plan", planDigestMap(plan)); preimage.put("planDigest", plan.planDigest()); preimage.put("generation", generationEvidenceMap(generation)); - preimage.put("publication", preparedPublicationEvidenceMap(publication)); + preimage.put("publication", promotionPublicationEvidenceMap(publication)); preimage.put("inventoryEvidenceReference", inventoryEvidenceReference); preimage.put("inventoryEvidenceDigest", inventoryEvidenceDigest); preimage.put( @@ -1778,8 +3141,8 @@ private static Map trustFenceMap(TrustFence trust) { "configRevision", trust.configRevision()); } - private static Map preparedPublicationEvidenceMap( - AccountJwtJwksPublicationRepository.PreparedPublicationEvidence evidence) { + private static Map promotionPublicationEvidenceMap( + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence evidence) { var intent = evidence.intent(); var receipt = evidence.receipt(); var mount = evidence.mountedCorrespondence(); @@ -1858,6 +3221,8 @@ private static Map verifiedProbeEvidenceMap(VerifiedProbeEvidenc receiptValue.put("validatorConfigRevision", receipt.validatorConfigRevision()); receiptValue.put("validatorPeerUri", receipt.validatorPeerUri()); receiptValue.put("validatorPeerSpkiSha256", receipt.validatorPeerSpkiSha256()); + receiptValue.put("podReceiptCount", receipt.podReceiptCount()); + receiptValue.put("podReceiptClosureSha256", receipt.podReceiptClosureSha256()); value.put("verificationReceipt", receiptValue); return value; } @@ -1900,6 +3265,23 @@ private static void requireOperationId(UUID operationId) { } } + private static String requireCanonicalKubeUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + String canonical = parsed.toString(); + if (!canonical.equals(value) + || parsed.equals(new UUID(0L, 0L)) + || parsed.version() < 1 + || parsed.version() > 8 + || parsed.variant() != 2) { + throw new IllegalArgumentException(); + } + return canonical; + } catch (RuntimeException invalid) { + throw new QuarantinedStateException(label + " is malformed"); + } + } + private static void requireAccountTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException("An owning Account transaction is required"); @@ -1927,6 +3309,115 @@ private record CurrentEvidence( GenerationResult result, AccountJwtJwksPublicationRepository.PublicationEvidence publication) {} + private record ProfileCase(String tokenProfile, String audience) {} + + /** Exact immutable per-Pod requirement for one logical registry entry. */ + public record ExpectedPod( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + PodTarget target) { + public ExpectedPod { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "expected Pod plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + Objects.requireNonNull(target); + if (jti.version() != 4 || jti.variant() != 2 || !validatorId.equals(target.validatorId())) { + throw new QuarantinedStateException("Expected readiness Pod binding is malformed"); + } + } + } + + /** Owner-derived current plan, ISSUED entry, and exact expected Pod; contains no JWT. */ + public record OwnerProbeEvidence( + ReadinessProbePlan plan, ProbeEntry entry, ExpectedPod expectedPod) { + public OwnerProbeEvidence { + Objects.requireNonNull(plan); + Objects.requireNonNull(entry); + Objects.requireNonNull(expectedPod); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || entry.state() != ProbeState.ISSUED + || !plan.operationId().equals(entry.rotationOperationId()) + || !plan.planDigest().equals(entry.planDigest()) + || !entry.rotationOperationId().equals(expectedPod.rotationOperationId()) + || !entry.planDigest().equals(expectedPod.planDigest()) + || !entry.jti().equals(expectedPod.jti())) { + throw new ReceiverUnavailableException(); + } + } + } + + /** Immutable digest-covered one-Pod verifier receipt; no token or private key material. */ + private record PodReceipt( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + String podUid, + UUID jti, + long sourceEntryVersion, + String compactTokenSha256, + String targetGeneration, + String targetKid, + Optional expectedActive, + ProbeExpectation outcome, + String observedPodUid, + String image, + String verifierConfigSha256, + String verifiedKid, + URI receiverEndpoint, + String receiverServiceUri, + String receiverPeerSpkiSha256, + long observedAtEpochSecond, + String receiptSha256) { + private PodReceipt { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "per-Pod readiness plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + requireCanonicalKubeUuid(podUid, "per-Pod readiness target UID"); + Objects.requireNonNull(jti); + if (jti.version() != 4 || jti.variant() != 2 || sourceEntryVersion <= 0L) { + throw new QuarantinedStateException("Per-Pod readiness receipt identity is malformed"); + } + requireDigest(compactTokenSha256, "per-Pod readiness token digest"); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + Objects.requireNonNull(outcome); + requireCanonicalKubeUuid(observedPodUid, "observed readiness Pod UID"); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new QuarantinedStateException("Per-Pod verifier image is not pinned"); + } + requireDigest(verifierConfigSha256, "per-Pod verifier config digest"); + if (verifiedKid == null || !verifiedKid.equals(targetKid)) { + throw new QuarantinedStateException("Per-Pod verifier outcome does not match its key ID"); + } + Objects.requireNonNull(receiverEndpoint); + requireDigest(receiverPeerSpkiSha256, "per-Pod receiver SPKI digest"); + if (receiverServiceUri == null + || !receiverServiceUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}") + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Per-Pod receiver identity is malformed"); + } + requireDigest(receiptSha256, "per-Pod readiness receipt digest"); + } + } + public enum ProbeState { PLANNED, ISSUED, @@ -2026,7 +3517,10 @@ public record ProbeEntry( } verificationReceipt.ifPresent( receipt -> { - if (!receipt.verifiedKid().equals(targetKid) + if ((receipt.receiptVersion() == 1 && !receipt.verifiedKid().equals(targetKid)) + || (receipt.receiptVersion() == 2 + && receipt.verifiedKid() != null + && !receipt.verifiedKid().equals(targetKid)) || receipt.resultEntryVersion() > entryVersion || receipt.sourceEntryVersion() + 1L != receipt.resultEntryVersion() || (state == ProbeState.VERIFIED && receipt.resultEntryVersion() != entryVersion)) { @@ -2107,23 +3601,67 @@ public record VerificationReceipt( String validatorBindingDigest, String validatorConfigRevision, String validatorPeerUri, - String validatorPeerSpkiSha256) { + String validatorPeerSpkiSha256, + int podReceiptCount, + String podReceiptClosureSha256) { + public VerificationReceipt( + int receiptVersion, + long sourceEntryVersion, + long resultEntryVersion, + long observedAtEpochSecond, + String receiptSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256) { + this( + receiptVersion, + sourceEntryVersion, + resultEntryVersion, + observedAtEpochSecond, + receiptSha256, + verifiedKid, + validatorInstanceId, + validatorBindingDigest, + validatorConfigRevision, + validatorPeerUri, + validatorPeerSpkiSha256, + 0, + null); + } + public VerificationReceipt { - if (receiptVersion != 1 + if ((receiptVersion != 1 && receiptVersion != 2) || sourceEntryVersion <= 0L || resultEntryVersion != sourceEntryVersion + 1L || observedAtEpochSecond <= 0L) { throw new QuarantinedStateException("Readiness verification receipt version is malformed"); } requireDigest(receiptSha256, "readiness verification receipt digest"); - requireKid(verifiedKid); + if (receiptVersion == 1) { + requireKid(verifiedKid); + if (podReceiptCount != 0 || podReceiptClosureSha256 != null) { + throw new QuarantinedStateException("Legacy receipt cannot carry per-Pod closure fields"); + } + } else { + requireKid(verifiedKid); + if (podReceiptCount <= 0 || podReceiptCount > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Per-Pod receipt closure count is malformed"); + } + requireDigest(podReceiptClosureSha256, "per-Pod receipt closure digest"); + if (!receiptSha256.equals(podReceiptClosureSha256)) { + throw new QuarantinedStateException("Per-Pod closure and verification digests differ"); + } + } if (validatorInstanceId == null || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") || validatorConfigRevision == null || !validatorConfigRevision.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") || validatorPeerUri == null || !validatorPeerUri.matches( - "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness")) { + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { throw new QuarantinedStateException("Readiness verification receipt identity is malformed"); } requireDigest(validatorBindingDigest, "validator trust binding digest"); @@ -2237,7 +3775,8 @@ public ReadinessProbePlan( || notBeforeEpochSecond < plannedAtEpochSecond + maximumCacheAgeSeconds || expiresAtEpochSecond <= notBeforeEpochSecond || expiresAtEpochSecond - notBeforeEpochSecond > PROBE_LIFETIME_SECONDS - || planVersion != 1 + || (planVersion != 1 && planVersion != INVENTORY_PLAN_VERSION) + || (planVersion == INVENTORY_PLAN_VERSION && inventorySnapshotDigest.isEmpty()) || entries.isEmpty() || entries.size() > MAX_ENTRIES_PER_OPERATION) { throw new QuarantinedStateException("Readiness probe plan is malformed"); @@ -2255,7 +3794,8 @@ private static ReadinessProbePlan fromCurrent( long expiresAt, String planDigest, List entries, - Optional inventorySnapshotDigest) { + Optional inventorySnapshotDigest, + int planVersion) { GenerationRequest request = current.request(); GenerationResult result = current.result(); var publication = current.publication(); @@ -2281,7 +3821,7 @@ private static ReadinessProbePlan fromCurrent( plannedAt, notBefore, expiresAt, - 1, + planVersion, planDigest, entries, inventorySnapshotDigest); @@ -2295,7 +3835,7 @@ private static ReadinessProbePlan fromCurrent( public static final class ReadinessPromotionProof { private final ReadinessProbePlan plan; private final GenerationResult generationResult; - private final AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication; + private final AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication; private final String inventoryEvidenceReference; private final String inventoryEvidenceDigest; private final List verifiedProbes; @@ -2304,7 +3844,7 @@ public static final class ReadinessPromotionProof { private ReadinessPromotionProof( ReadinessProbePlan plan, GenerationResult generationResult, - AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication, String inventoryEvidenceReference, String inventoryEvidenceDigest) { this.plan = Objects.requireNonNull(plan); @@ -2325,6 +3865,8 @@ private ReadinessPromotionProof( plan.entries().stream().map(VerifiedProbeEvidence::from).toList(); if (verifiedProbes.isEmpty() || verifiedProbes.size() > MAX_ENTRIES_PER_OPERATION + || plan.planVersion() != INVENTORY_PLAN_VERSION + || verifiedProbes.stream().anyMatch(probe -> probe.receipt().receiptVersion() != 2) || !plan.operationId().equals(generationResult.operationId()) || !plan.operationDigest().equals(generationResult.operationDigest()) || !plan.generationRequestDigest().equals(generationResult.generationRequestDigest()) @@ -2356,7 +3898,7 @@ public GenerationResult generationResult() { return generationResult; } - public AccountJwtJwksPublicationRepository.PreparedPublicationEvidence publication() { + public AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication() { return publication; } @@ -2413,7 +3955,10 @@ public record VerifiedProbeEvidence( || entryVersion <= 0L || plannedIssuedAtEpochSecond <= 0L || expiresAtEpochSecond <= plannedIssuedAtEpochSecond - || !targetKid.equals(receipt.verifiedKid()) + || (receipt.receiptVersion() == 1 && !targetKid.equals(receipt.verifiedKid())) + || (receipt.receiptVersion() == 2 + && receipt.verifiedKid() != null + && !targetKid.equals(receipt.verifiedKid())) || receipt.resultEntryVersion() != entryVersion) { throw new QuarantinedStateException( "Verified probe evidence does not match its immutable receipt"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java index ed3dccfcaf..e07e834015 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java @@ -421,16 +421,11 @@ public PrivatePromotionReceipt recordPrivatePromotionResult( DesiredState state = decodeState(stateRow); requireBinding(state, expectedBinding); requireEnrollmentTrust(state, trust); - if (!state.preparedOperationId().equals(Optional.of(observation.promotionOperationId())) - || state.generationOperationId().isPresent()) { - throw new StaleGenerationOperationException( - "Private promotion result does not target Account's current PREPARED operation"); - } StoredPromotion promotion = selectPromotion(observation.promotionOperationId(), true); - if (promotion == null || !"PREPARED".equals(promotion.status())) { - throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + if (promotion == null) { + throw new StaleGenerationOperationException( + "Private promotion result does not target an Account-owned operation"); } - requirePromotionMatchesState(promotion, state); requireCurrentTrust(promotion, trust); if (!promotion.requestDigest().equals(observation.promotionRequestDigest()) || !promotion.generationOperationId().equals(observation.generationOperationId()) @@ -452,6 +447,35 @@ public PrivatePromotionReceipt recordPrivatePromotionResult( verifyPreparedGenerationMatches(promotion, operation, result); requirePrivatePromotionObservation(promotion, observation); PrivatePromotionReceipt candidate = PrivatePromotionReceipt.from(promotion, observation); + + if ("COMMITTED".equals(promotion.status())) { + ActiveSigner target = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!promotion.binding().equals(expectedBinding) + || !promotion.requestDigest().equals(promotionRequestDigest(promotion)) + || state.preparedOperationId().isPresent() + || state.durableActive().filter(target::equals).isEmpty() + || state.publishedActive().filter(target::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() < promotion.expectedRecordVersion() + 2 + || promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null + || !candidate.receiptDigest().equals(promotion.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.privatePromotionObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Committed private promotion retry does not match current Account evidence"); + } + return candidate; + } + + if (!"PREPARED".equals(promotion.status()) + || !state.preparedOperationId().equals(Optional.of(observation.promotionOperationId())) + || state.generationOperationId().isPresent()) { + throw new StaleGenerationOperationException( + "Private promotion result does not target Account's current PREPARED operation"); + } + requirePromotionMatchesState(promotion, state); if (promotion.privatePromotionReceiptDigest() != null) { if (!candidate.receiptDigest().equals(promotion.privatePromotionReceiptDigest()) || !candidate diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java index e8b11ec12c..4c3558b831 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java @@ -141,6 +141,8 @@ private static String digest(byte[] bytes) { } private static void requireSameSnapshot(InventorySnapshot expected, StoredSnapshot actual) { + // A content digest can be observed again later. Keep the first persisted timestamp immutable; + // callers separately use the fresh observation's timestamp for the bounded freshness check. if (!expected.digest().equals(actual.digest()) || !expected.environmentId().equals(actual.environmentId()) || !expected.clusterId().equals(actual.clusterId()) @@ -151,7 +153,6 @@ private static void requireSameSnapshot(InventorySnapshot expected, StoredSnapsh || !expected.apiBindingDigest().equals(actual.apiBindingDigest()) || !expected.inventoryBindingRevision().equals(actual.inventoryBindingRevision()) || !expected.inventoryBindingDigest().equals(actual.inventoryBindingDigest()) - || !expected.observedAt().equals(actual.observedAt()) || !MessageDigest.isEqual(expected.canonicalBytes(), actual.canonicalBytes())) { throw new InventorySnapshotUnavailableException(); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptor.java new file mode 100644 index 0000000000..099d2f16e8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptor.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.accountservice.security; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import java.util.Optional; +import java.util.function.Supplier; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.PeerIdentity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** Independently pins the readiness-harness TLS caller for the readiness RPC alone. */ +@Component("accountJwtReadinessTlsInterceptor") +public final class AccountJwtReadinessTlsInterceptor implements ServerInterceptor { + private static final Context.Key AUTHENTICATED_CALLER = + Context.key("account-jwt-readiness-authenticated-caller"); + + private final Supplier> trustBindingProvider; + + @Autowired + public AccountJwtReadinessTlsInterceptor(AccountJwtReadinessTrustBinding trustBindingProvider) { + this(trustBindingProvider::current); + } + + AccountJwtReadinessTlsInterceptor(Supplier> trustBindingProvider) { + this.trustBindingProvider = trustBindingProvider; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Optional current = trustBindingProvider.get(); + if (current.isEmpty()) { + return deny(call); + } + Binding binding = current.orElseThrow(); + if (!binding.isCurrentAt(java.time.Instant.now().getEpochSecond())) { + return deny(call); + } + SSLSession sslSession = call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + if (sslSession == null) { + return deny(call); + } + + java.security.cert.Certificate[] peerCertificates; + try { + peerCertificates = sslSession.getPeerCertificates(); + } catch (SSLPeerUnverifiedException ex) { + return deny(call); + } + PeerIdentity peer; + try { + peer = AccountJwtReadinessTrustBinding.identifyPeer(peerCertificates); + } catch (RuntimeException rejectedIdentity) { + return deny(call); + } + if (!binding.matches(peer)) { + return deny(call); + } + + Context authenticated = + Context.current().withValue(AUTHENTICATED_CALLER, new AuthenticatedCaller(binding, peer)); + return Contexts.interceptCall(authenticated, call, headers, next); + } + + /** Returns only identity established by this interceptor; callers cannot construct the value. */ + public static AuthenticatedCaller authenticatedCaller() { + return AUTHENTICATED_CALLER.get(); + } + + private static ServerCall.Listener deny(ServerCall call) { + call.close( + Status.PERMISSION_DENIED.withDescription( + "Authenticated Account readiness harness is required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + + /** Non-forgeable in-process handle for the TLS identity captured on this RPC. */ + public static final class AuthenticatedCaller { + private final Binding binding; + private final PeerIdentity peer; + + private AuthenticatedCaller(Binding binding, PeerIdentity peer) { + this.binding = binding; + this.peer = peer; + } + + public Binding binding() { + return binding; + } + + public PeerIdentity peer() { + return peer; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptor.java new file mode 100644 index 0000000000..8c6bea6cd2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptor.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.accountservice.security; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import java.util.Optional; +import java.util.function.Supplier; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** Service-local certificate identity gate for only the JWT signer materialization RPCs. */ +@Component("accountJwtSignerMaterializerTlsInterceptor") +public final class AccountJwtSignerMaterializerTlsInterceptor implements ServerInterceptor { + private static final Context.Key AUTHENTICATED_BINDING = + Context.key("account-jwt-signer-materializer-trust-binding"); + + private final Supplier> trustBindingProvider; + + @Autowired + public AccountJwtSignerMaterializerTlsInterceptor( + AccountJwtSignerMaterializerTrustBinding trustBindingProvider) { + this(trustBindingProvider::current); + } + + AccountJwtSignerMaterializerTlsInterceptor(Supplier> trustBindingProvider) { + this.trustBindingProvider = trustBindingProvider; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Optional current = trustBindingProvider.get(); + if (current.isEmpty()) { + return deny(call, "JWT materializer trust binding is unavailable"); + } + SSLSession sslSession = call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + if (sslSession == null) { + return deny(call, "Authenticated JWT materializer workload is required"); + } + Binding binding = current.orElseThrow(); + java.security.cert.Certificate[] peerCertificates; + try { + peerCertificates = sslSession.getPeerCertificates(); + } catch (SSLPeerUnverifiedException ex) { + return deny(call, "Authenticated JWT materializer workload is required"); + } + if (!AccountJwtSignerMaterializerTrustBinding.matchesPeer(peerCertificates, binding)) { + return deny(call, "Authenticated JWT materializer workload is required"); + } + Context authenticated = Context.current().withValue(AUTHENTICATED_BINDING, binding); + return Contexts.interceptCall(authenticated, call, headers, next); + } + + /** The service re-reads protected configuration and rejects a changed snapshot before storage. */ + public static Binding authenticatedBinding() { + return AUTHENTICATED_BINDING.get(); + } + + private static ServerCall.Listener deny( + ServerCall call, String description) { + call.close(Status.PERMISSION_DENIED.withDescription(description), new Metadata()); + return new ServerCall.Listener<>() {}; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessPodReceiverGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessPodReceiverGrpcService.java new file mode 100644 index 0000000000..170697c4d0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessPodReceiverGrpcService.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.account.v1.AccountJwtReadinessPodReceiverServiceGrpc; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeRequest; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPodReceiverWorkloadGuard; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPrerequisiteConfiguration; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessPodLocalIdentityProvider; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessPodReceiverEngine; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessPodReceiverProtoMapper; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Lazy; +import org.springframework.grpc.server.service.GrpcService; + +/** Isolated default-inactive Account Pod verifier; does not share the V1 harness RPC or guard. */ +@GrpcService +@ConditionalOnProperty( + prefix = "firemud.account.jwt-readiness.pod-receiver", + name = "enabled", + havingValue = "true") +@Conditional( + AccountJwtReadinessPrerequisiteConfiguration.ProtectedReadinessConfigurationPresent.class) +@Lazy +public final class AccountJwtReadinessPodReceiverGrpcService + extends AccountJwtReadinessPodReceiverServiceGrpc + .AccountJwtReadinessPodReceiverServiceImplBase { + private static final String UNAVAILABLE = "Account Pod readiness receiver is unavailable"; + + private final AccountJwtReadinessPodReceiverEngine receiver; + + public AccountJwtReadinessPodReceiverGrpcService(AccountJwtReadinessPodReceiverEngine receiver) { + this.receiver = receiver; + } + + @Override + public void receiveReadinessProbe( + ReceiveAccountJwtReadinessProbeRequest request, + StreamObserver responseObserver) { + try { + responseObserver.onNext(receiver.receiveReadinessProbe(request)); + responseObserver.onCompleted(); + } catch (AccountJwtReadinessPodReceiverWorkloadGuard.ReceiverCallerDeniedException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Authorized Account workload is required") + .asRuntimeException()); + } catch (AccountJwtReadinessPodReceiverProtoMapper.InvalidReceiverRequestException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Account Pod readiness request is invalid") + .asRuntimeException()); + } catch (AccountAsymmetricJwtVerifier.VerificationException rejected) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Current pending-key probe was not verified") + .asRuntimeException()); + } catch (AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException + | AccountJwtReadinessPodLocalIdentityProvider.IdentityUnavailableException unavailable) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Current Account Pod probe evidence is unavailable") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE.withDescription(UNAVAILABLE).asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java new file mode 100644 index 0000000000..93cf4f4aa3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java @@ -0,0 +1,64 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.account.v1.AccountJwtReadinessProbeOwnerServiceGrpc; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPrerequisiteConfiguration; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerWorkloadGuard; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerProtoMapper; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Lazy; +import org.springframework.grpc.server.service.GrpcService; + +/** Isolated, default-inactive mTLS owner lookup; no bearer or readiness-harness route is reused. */ +@GrpcService +@ConditionalOnProperty( + prefix = "firemud.account.jwt-readiness.probe-owner", + name = "enabled", + havingValue = "true") +@Conditional( + AccountJwtReadinessPrerequisiteConfiguration.ProtectedReadinessConfigurationPresent.class) +@Lazy +public final class AccountJwtReadinessProbeOwnerGrpcService + extends AccountJwtReadinessProbeOwnerServiceGrpc.AccountJwtReadinessProbeOwnerServiceImplBase { + private static final String UNAVAILABLE = "Account readiness probe owner is unavailable"; + + private final AccountJwtReadinessProbeOwnerService owner; + + public AccountJwtReadinessProbeOwnerGrpcService(AccountJwtReadinessProbeOwnerService owner) { + this.owner = owner; + } + + @Override + public void getCurrentReadinessProbeOwner( + GetCurrentReadinessProbeOwnerRequest request, + StreamObserver responseObserver) { + try { + responseObserver.onNext(owner.getCurrentReadinessProbeOwner(request)); + responseObserver.onCompleted(); + } catch (AccountJwtReadinessProbeOwnerWorkloadGuard.OwnerReadDeniedException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Authorized Game Session workload is required") + .asRuntimeException()); + } catch (AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Readiness owner request is invalid") + .asRuntimeException()); + } catch (AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException unavailable) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Current readiness owner evidence is unavailable") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE.withDescription(UNAVAILABLE).asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessValidationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessValidationGrpcService.java new file mode 100644 index 0000000000..f56514d425 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessValidationGrpcService.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.account.v1.AccountJwtReadinessValidationServiceGrpc; +import net.firedevops.firemud.account.v1.IssueReadinessProbesRequest; +import net.firedevops.firemud.account.v1.IssueReadinessProbesResponse; +import net.firedevops.firemud.account.v1.ValidateReadinessProbeRequest; +import net.firedevops.firemud.account.v1.ValidateReadinessProbeResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPrerequisiteConfiguration; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.security.AccountJwtReadinessTlsInterceptor; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessTransportOwner; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessValidationService; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Lazy; +import org.springframework.grpc.server.service.GrpcService; + +/** Isolated, exact-mTLS transport for Account's non-authorizing JWT readiness probes. */ +@GrpcService( + interceptorNames = "accountJwtReadinessTlsInterceptor", + blendWithGlobalInterceptors = false) +@ConditionalOnProperty( + prefix = "firemud.account.jwt-readiness.validation", + name = "enabled", + havingValue = "true") +@Conditional( + AccountJwtReadinessPrerequisiteConfiguration.ProtectedReadinessConfigurationPresent.class) +@Lazy +public final class AccountJwtReadinessValidationGrpcService + extends AccountJwtReadinessValidationServiceGrpc.AccountJwtReadinessValidationServiceImplBase { + private static final String UNAVAILABLE = "Account JWT readiness service is unavailable"; + + private final AccountJwtReadinessTransportOwner owner; + + public AccountJwtReadinessValidationGrpcService(AccountJwtReadinessTransportOwner owner) { + this.owner = owner; + } + + @Override + public void issueReadinessProbes( + IssueReadinessProbesRequest request, + StreamObserver responseObserver) { + var authenticatedCaller = AccountJwtReadinessTlsInterceptor.authenticatedCaller(); + if (authenticatedCaller == null) { + deny(responseObserver); + return; + } + try { + responseObserver.onNext(owner.issue(request, authenticatedCaller)); + responseObserver.onCompleted(); + } catch (AccountJwtReadinessValidationService.InvalidReadinessRequestException invalid) { + invalid(responseObserver); + } catch (SecurityException denied) { + deny(responseObserver); + } catch (AccountJwtReadinessProbeRepository.CacheAgeNotElapsedException + | AccountJwtReadinessProbeRepository.DeliveryAlreadyClaimedException + | AccountJwtReadinessProbeRepository.ProbeExpiredException + | AccountJwtReadinessValidationService.ProbeNotIssuedException precondition) { + precondition(responseObserver); + } catch (AccountAsymmetricJwtVerifier.VerificationException + | AccountJwtReadinessProbeRepository.IdempotencyConflictException invalid) { + invalid(responseObserver); + } catch (RuntimeException unavailable) { + unavailable(responseObserver); + } + } + + @Override + public void validateReadinessProbe( + ValidateReadinessProbeRequest request, + StreamObserver responseObserver) { + var authenticatedCaller = AccountJwtReadinessTlsInterceptor.authenticatedCaller(); + if (authenticatedCaller == null) { + deny(responseObserver); + return; + } + try { + responseObserver.onNext(owner.validate(request, authenticatedCaller)); + responseObserver.onCompleted(); + } catch (AccountJwtReadinessValidationService.InvalidReadinessRequestException invalid) { + invalid(responseObserver); + } catch (SecurityException denied) { + deny(responseObserver); + } catch (AccountJwtReadinessProbeRepository.CacheAgeNotElapsedException + | AccountJwtReadinessProbeRepository.DeliveryAlreadyClaimedException + | AccountJwtReadinessProbeRepository.ProbeExpiredException + | AccountJwtReadinessValidationService.ProbeNotIssuedException precondition) { + precondition(responseObserver); + } catch (AccountAsymmetricJwtVerifier.VerificationException + | AccountJwtReadinessProbeRepository.IdempotencyConflictException invalid) { + invalid(responseObserver); + } catch (RuntimeException unavailable) { + unavailable(responseObserver); + } + } + + private static void invalid(StreamObserver observer) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Readiness request is invalid") + .asRuntimeException()); + } + + private static void deny(StreamObserver observer) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Authenticated Account readiness harness is required") + .asRuntimeException()); + } + + private static void precondition(StreamObserver observer) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Readiness probe is not currently eligible") + .asRuntimeException()); + } + + private static void unavailable(StreamObserver observer) { + observer.onError(Status.UNAVAILABLE.withDescription(UNAVAILABLE).asRuntimeException()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java new file mode 100644 index 0000000000..b94bc0762f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java @@ -0,0 +1,739 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountJwtSignerMaterializationServiceGrpc; +import net.firedevops.firemud.account.v1.ActiveSigner; +import net.firedevops.firemud.account.v1.EnrollBootstrapRequest; +import net.firedevops.firemud.account.v1.EnrollBootstrapResponse; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; +import net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity; +import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; +import net.firedevops.firemud.account.v1.RecordSecretObservationRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PublicKeyIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.BootstrapOperationException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.Stage; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import org.jooq.exception.DataAccessException; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Narrow Account-owned operation handoff to the interim mounted-key materializer. + * + *

The exact peer can read Account-selected fixed-Secret generation and PREPARED promotion + * operations, report readbacks, and submit public key identities. It cannot select an operation, + * environment, resource, generation, or {@code kid}; submit private material; publish JWKS; commit + * the Account signer lifecycle; sign tokens; or establish readiness. + */ +@GrpcService( + interceptorNames = "accountJwtSignerMaterializerTlsInterceptor", + blendWithGlobalInterceptors = false) +public class AccountJwtSignerMaterializationService + extends AccountJwtSignerMaterializationServiceGrpc + .AccountJwtSignerMaterializationServiceImplBase { + private final AccountJwtSignerDesiredStateRepository repository; + private final AccountJwtReadinessProbeRepository readinessRepository; + private final AccountJwtSignerMaterializerTrustBinding trustBindingProvider; + private final TransactionTemplate accountTransaction; + private final ObjectProvider bootstrapCoordinatorProvider; + private final ObjectProvider validatorInventorySourceProvider; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Spring injects the same owner repositories into this gRPC adapter so lifecycle validation and persistence share the Account authority and transaction boundary.") + @Autowired + public AccountJwtSignerMaterializationService( + AccountJwtSignerDesiredStateRepository repository, + AccountJwtReadinessProbeRepository readinessRepository, + AccountJwtSignerMaterializerTrustBinding trustBindingProvider, + PlatformTransactionManager transactionManager, + ObjectProvider bootstrapCoordinatorProvider, + ObjectProvider validatorInventorySourceProvider) { + this.repository = repository; + this.readinessRepository = readinessRepository; + this.trustBindingProvider = trustBindingProvider; + this.bootstrapCoordinatorProvider = bootstrapCoordinatorProvider; + this.validatorInventorySourceProvider = validatorInventorySourceProvider; + this.accountTransaction = new TransactionTemplate(transactionManager); + this.accountTransaction.setReadOnly(false); + } + + /** + * Retains the narrow unit-test construction path when optional bootstrap composition is absent. + */ + public AccountJwtSignerMaterializationService( + AccountJwtSignerDesiredStateRepository repository, + AccountJwtReadinessProbeRepository readinessRepository, + AccountJwtSignerMaterializerTrustBinding trustBindingProvider, + PlatformTransactionManager transactionManager) { + this(repository, readinessRepository, trustBindingProvider, transactionManager, null, null); + } + + @Override + public void enrollBootstrap( + EnrollBootstrapRequest request, StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + Binding binding = requireCurrentAuthenticatedBinding(); + AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator(); + if (coordinator == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Account JWT signer bootstrap is not enabled") + .asRuntimeException(); + } + AccountJwtSignerBootstrapCoordinator.EnrollmentAcknowledgement acknowledgement = + coordinator.enrollOnce(); + requireUnchangedTrustBinding(binding); + responseObserver.onNext(toEnrollmentResponse(acknowledgement)); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + @Override + public void getCurrentGenerationRequest( + GetCurrentGenerationRequestRequest request, + StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + Binding binding = requireCurrentAuthenticatedBinding(); + GenerationRequest current = + accountTransaction.execute( + status -> { + GenerationRequest requested = + repository.ensureCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + requireUnchangedTrustBinding(binding); + return requested; + }); + if (current == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "JWT signer generation request is unavailable"); + } + requireUnchangedTrustBinding(binding); + if (current.phase() == GenerationPhase.GENERATION_RECORDED) { + AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator(); + if (coordinator != null) { + var progress = coordinator.reconcileCurrentGenerationOnce(current.operationId()); + requireUnchangedTrustBinding(binding); + if (progress.stage() != Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Account signer generation is durable but publication or mount reconciliation is incomplete") + .asRuntimeException(); + } + } + } + responseObserver.onNext(toRequestResponse(current)); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + @Override + public void recordSecretObservation( + RecordSecretObservationRequest request, + StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + UUID operationId = parseOperationId(request.getOperationId()); + Binding binding = requireCurrentAuthenticatedBinding(); + GenerationRequest current = + accountTransaction.execute( + status -> { + GenerationRequest observed = + repository.recordSecretObservation( + binding.accountBinding(), + trustFence(binding), + operationId, + request.getOperationDigest(), + request.getSecretUid(), + request.getObservedResourceVersion()); + requireUnchangedTrustBinding(binding); + return observed; + }); + if (current == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "JWT signer Secret observation is unavailable"); + } + requireUnchangedTrustBinding(binding); + responseObserver.onNext(toRequestResponse(current)); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + @Override + public void recordGenerationResult( + RecordGenerationResultRequest request, + StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + UUID operationId = parseOperationId(request.getOperationId()); + Binding binding = requireCurrentAuthenticatedBinding(); + GenerationResult result = + accountTransaction.execute( + status -> { + GenerationResult persisted = + repository.recordGenerationResult( + binding.accountBinding(), + trustFence(binding), + operationId, + request.getGenerationRequestDigest(), + request.getSecretUid(), + request.getExpectedPriorResourceVersion(), + request.getObservedResourceVersion(), + request.getPublicJwkJson()); + requireUnchangedTrustBinding(binding); + return persisted; + }); + if (result == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "JWT signer generation receipt is unavailable"); + } + requireUnchangedTrustBinding(binding); + responseObserver.onNext(toResultResponse(result)); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + /** Returns only the exact Account PREPARED operation for fixed-Secret reconciliation. */ + @Override + public void getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest request, + StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + Binding binding = requireCurrentAuthenticatedBinding(); + requireValidatorInventorySourceAvailable(); + PreparedGenerationEvidence preparedForObservation; + try { + preparedForObservation = + accountTransaction.execute( + status -> + repository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding))); + } catch (AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException notPrepared) { + AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator(); + if (coordinator == null) { + throw new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Account has no complete owner-verified promotion proof"); + } + if (coordinator.prepareCurrentPromotionOnce().isEmpty()) { + if (ownerConfirmsNoPromotionReadyYet(binding)) { + throw new AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException(); + } + throw new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Account has no complete owner-verified promotion proof"); + } + preparedForObservation = + accountTransaction.execute( + status -> + repository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding))); + } + if (preparedForObservation == null) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared Account signer operation is unavailable"); + } + ObservationContext observationContext = observationContext(preparedForObservation); + // The first PREPARED attempt refreshed ConfigMap and mounted evidence, then sampled the + // protected inventory before its PREPARED transaction. Reobserve here for the dispatch fence; + // recovery of an existing PREPARED operation also gets this independent live recheck. + InventorySnapshot liveInventory = observeCurrentValidatorInventory(observationContext); + requireUnchangedTrustBinding(binding); + PreparedGenerationEvidence prepared = + accountTransaction.execute( + status -> { + PreparedGenerationEvidence current = + repository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding)); + if (!observationContext.equals(observationContext(current))) { + throw new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Prepared signer operation changed during validator inventory proof"); + } + boolean completeProof = + readinessRepository + .readPromotionProof( + binding.accountBinding(), + trustFence(binding), + current.promotion().generationOperationId(), + liveInventory) + .isPresent(); + if (!completeProof) { + throw new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Complete Account readiness proof is unavailable"); + } + PreparedGenerationEvidence evidence = + repository.readAndMarkPreparedPromotionDispatched( + binding.accountBinding(), trustFence(binding)); + requireUnchangedTrustBinding(binding); + return evidence; + }); + if (prepared == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "JWT signer promotion request is unavailable"); + } + requireUnchangedTrustBinding(binding); + responseObserver.onNext(toPromotionRequestResponse(prepared)); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + /** Records Account's public-identity-only readback of the exact fixed-Secret CAS. */ + @Override + public void recordPrivatePromotionResult( + RecordPrivatePromotionResultRequest request, + StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + if (request.hasCurrent() == false + || request.getCurrent().getUnknownFields().asMap().isEmpty() == false + || (request.hasPrevious() + && request.getPrevious().getUnknownFields().asMap().isEmpty() == false)) { + throw new IllegalArgumentException("Promotion result identity is malformed"); + } + UUID promotionOperationId = parseOperationId(request.getPromotionOperationId()); + UUID generationOperationId = parseOperationId(request.getGenerationOperationId()); + Binding binding = requireCurrentAuthenticatedBinding(); + PrivatePromotionObservation observation = + new PrivatePromotionObservation( + promotionOperationId, + request.getPromotionRequestDigest(), + generationOperationId, + request.getGenerationOperationDigest(), + request.getSecretUid(), + request.getExpectedPriorResourceVersion(), + request.getObservedResourceVersion(), + publicIdentity(request.getCurrent()), + request.hasPrevious() + ? java.util.Optional.of(publicIdentity(request.getPrevious())) + : java.util.Optional.empty(), + request.getResultingSlotsList()); + PrivatePromotionReceipt receipt = + accountTransaction.execute( + status -> { + PrivatePromotionReceipt persisted = + repository.recordPrivatePromotionResult( + binding.accountBinding(), trustFence(binding), observation); + requireUnchangedTrustBinding(binding); + return persisted; + }); + if (receipt == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "JWT signer private promotion receipt is unavailable"); + } + requireUnchangedTrustBinding(binding); + AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator(); + if (coordinator == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Account JWT signer reconciliation is not enabled") + .asRuntimeException(); + } + coordinator.reconcilePreparedPromotionOnce(observation, receipt); + requireUnchangedTrustBinding(binding); + responseObserver.onNext( + RecordPrivatePromotionResultResponse.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(receipt.promotionOperationId().toString()) + .setGenerationOperationId(receipt.generationOperationId().toString()) + .setObservedResourceVersion(receipt.observedResourceVersion()) + .setPublicReceiptDigest(receipt.receiptDigest()) + .build()); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + private Binding requireCurrentAuthenticatedBinding() { + Binding authenticated = AccountJwtSignerMaterializerTlsInterceptor.authenticatedBinding(); + Binding current = trustBindingProvider.current().orElse(null); + if (authenticated == null || current == null || !authenticated.equals(current)) { + throw Status.PERMISSION_DENIED + .withDescription("Authenticated JWT materializer workload is required") + .asRuntimeException(); + } + return current; + } + + private AccountJwtSignerBootstrapCoordinator currentBootstrapCoordinator() { + return bootstrapCoordinatorProvider == null + ? null + : bootstrapCoordinatorProvider.getIfAvailable(); + } + + private InventorySnapshot observeCurrentValidatorInventory( + ObservationContext observationContext) { + AccountJwtValidatorInventorySource source = currentValidatorInventorySource(); + try { + return source.observe(observationContext); + } catch (AccountJwtValidatorInventorySource.InventoryUnavailableException failure) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Protected live validator inventory is unavailable"); + } + } + + private static ObservationContext observationContext( + PreparedGenerationEvidence preparedGeneration) { + if (preparedGeneration == null) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared Account generation evidence is unavailable"); + } + var promotion = preparedGeneration.promotion(); + if (!promotion.expectedPreviousActive().equals(promotion.expectedPublishedActive())) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared Account active signer fence is inconsistent"); + } + return new ObservationContext( + promotion.expectedPreviousActive().isEmpty() + ? ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES + : ObservationPurpose.STRICT_READY, + promotion.generationOperationId(), + promotion.generationOperationDigest()); + } + + private void requireValidatorInventorySourceAvailable() { + if (currentValidatorInventorySource() == null) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Protected live validator inventory is unavailable"); + } + } + + private AccountJwtValidatorInventorySource currentValidatorInventorySource() { + return validatorInventorySourceProvider == null + ? null + : validatorInventorySourceProvider.getIfAvailable(); + } + + private void requireUnchangedTrustBinding(Binding expected) { + if (trustBindingProvider.current().filter(expected::equals).isEmpty()) { + throw Status.PERMISSION_DENIED + .withDescription("JWT materializer trust binding changed during the request") + .asRuntimeException(); + } + } + + private boolean ownerConfirmsNoPromotionReadyYet(Binding binding) { + requireUnchangedTrustBinding(binding); + DesiredState state = + accountTransaction.execute(status -> repository.read(binding.accountBinding())); + requireUnchangedTrustBinding(binding); + if (state == null || state.enrollmentIdentity().isEmpty()) { + return false; + } + EnrollmentIdentity enrollment = state.enrollmentIdentity().orElseThrow(); + TrustFence currentTrust = trustFence(binding); + if (!enrollment + .expectedClusterIncarnationUid() + .equals(currentTrust.expectedClusterIncarnationUid()) + || !enrollment.expectedNamespaceUid().equals(currentTrust.expectedNamespaceUid()) + || !enrollment.materializerTrustBindingDigest().equals(currentTrust.bindingDigest()) + || !enrollment.materializerTrustConfigRevision().equals(currentTrust.configRevision()) + || state.preparedOperationId().isPresent()) { + return false; + } + if (state.generationOperationId().isEmpty()) { + boolean unselectedInitialEnrollment = + state.recordVersion() == 1 + && state.durableActive().isEmpty() + && state.publishedActive().isEmpty(); + requireUnchangedTrustBinding(binding); + return unselectedInitialEnrollment; + } + GenerationRequest current = + accountTransaction.execute( + status -> + repository.readCurrentGenerationRequest(binding.accountBinding(), currentTrust)); + requireUnchangedTrustBinding(binding); + return current != null + && (current.phase() == GenerationPhase.OBSERVE_PRIVATE_SECRET + || current.phase() == GenerationPhase.GENERATE_PENDING); + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private static GetCurrentGenerationRequestResponse toRequestResponse(GenerationRequest request) { + GetCurrentGenerationRequestResponse.Builder response = + GetCurrentGenerationRequestResponse.newBuilder() + .setSchemaVersion(1) + .setPhase(toWirePhase(request.phase())) + .setOperationId(request.operationId().toString()) + .setOperationDigest(request.operationDigest()) + .setGenerationRequestDigest(request.generationRequestDigest()) + .setDesiredStateVersion(Long.toString(request.desiredStateVersion())) + .setEnvironmentId(request.binding().environmentId()) + .setClusterId(request.binding().clusterId()) + .setNamespace(request.binding().namespace()) + .setExpectedClusterIncarnationUid(request.trustFence().expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(request.trustFence().expectedNamespaceUid()) + .setTrustBindingDigest(request.trustFence().bindingDigest()) + .setTrustConfigRevision(request.trustFence().configRevision()) + .setPrivateSecretName(request.privateSecretName()) + .setTargetGeneration(request.targetGeneration()) + .setTargetKid(request.targetKid()) + .setTargetAlgorithm(request.targetAlgorithm()) + .setOperationAction(request.operationAction()) + .addAllAllowedPrivateSlots(request.allowedPrivateSlots()) + .setSecretUid(request.secretUid()) + .setExpectedSecretResourceVersion(request.expectedSecretResourceVersion()) + .setGenerationReceiptDigest(request.generationReceiptDigest()) + .setPublicKeyFingerprint(request.publicKeyFingerprint()) + .setPublicJwkJson(request.publicJwkJson()) + .setObservedSecretResourceVersion(request.observedSecretResourceVersion()); + request.expectedActive().ifPresent(active -> response.setExpectedActive(toWireActive(active))); + request + .expectedPublishedActive() + .ifPresent(active -> response.setExpectedPublishedActive(toWireActive(active))); + return response.build(); + } + + private static EnrollBootstrapResponse toEnrollmentResponse( + AccountJwtSignerBootstrapCoordinator.EnrollmentAcknowledgement acknowledgement) { + return EnrollBootstrapResponse.newBuilder() + .setSchemaVersion(1) + .setEnvironmentId(acknowledgement.environmentId()) + .setClusterId(acknowledgement.clusterId()) + .setNamespace(acknowledgement.namespace()) + .setExpectedClusterIncarnationUid(acknowledgement.expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(acknowledgement.expectedNamespaceUid()) + .setMaterializerTrustBindingDigest(acknowledgement.materializerTrustBindingDigest()) + .setMaterializerTrustConfigRevision(acknowledgement.materializerTrustConfigRevision()) + .setApiBindingDigest(acknowledgement.apiBindingDigest()) + .setApiConfigRevision(acknowledgement.apiConfigRevision()) + .setApiServerUrl(acknowledgement.apiServerUrl()) + .setApiTlsServerName(acknowledgement.apiTlsServerName()) + .setApiServingCaSha256(acknowledgement.apiServingCaSha256()) + .setApiExpectedUsername(acknowledgement.apiExpectedUsername()) + .setPrivateSecretName(acknowledgement.privateSecretName()) + .setPublicConfigMapName(acknowledgement.publicConfigMapName()) + .setPublicConfigMapUid(acknowledgement.publicConfigMapUid()) + .setPublicConfigMapResourceVersion(acknowledgement.publicConfigMapResourceVersion()) + .setPublicConfigMapSnapshotDigest(acknowledgement.publicConfigMapSnapshotDigest()) + .build(); + } + + private static ActiveSigner toWireActive( + AccountJwtSignerDesiredStateRepository.ActiveSigner active) { + return ActiveSigner.newBuilder() + .setGeneration(active.generation()) + .setKid(active.kid()) + .build(); + } + + private static GetCurrentGenerationRequestResponse.Phase toWirePhase(GenerationPhase phase) { + return switch (phase) { + case OBSERVE_PRIVATE_SECRET -> + GetCurrentGenerationRequestResponse.Phase.OBSERVE_PRIVATE_SECRET; + case GENERATE_PENDING -> GetCurrentGenerationRequestResponse.Phase.GENERATE_PENDING; + case GENERATION_RECORDED -> GetCurrentGenerationRequestResponse.Phase.GENERATION_RECORDED; + }; + } + + private static RecordGenerationResultResponse toResultResponse(GenerationResult result) { + return RecordGenerationResultResponse.newBuilder() + .setSchemaVersion(1) + .setOperationId(result.operationId().toString()) + .setOperationDigest(result.operationDigest()) + .setGenerationRequestDigest(result.generationRequestDigest()) + .setGenerationReceiptDigest(result.receiptDigest()) + .setDesiredStateVersion(Long.toString(result.desiredStateVersion())) + .setEnvironmentId(result.binding().environmentId()) + .setClusterId(result.binding().clusterId()) + .setNamespace(result.binding().namespace()) + .setExpectedClusterIncarnationUid(result.trustFence().expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(result.trustFence().expectedNamespaceUid()) + .setTrustBindingDigest(result.trustFence().bindingDigest()) + .setTrustConfigRevision(result.trustFence().configRevision()) + .setPrivateSecretName(result.privateSecretName()) + .setSecretUid(result.secretUid()) + .setExpectedPriorResourceVersion(result.expectedPriorResourceVersion()) + .setObservedResourceVersion(result.observedResourceVersion()) + .setTargetGeneration(result.targetGeneration()) + .setTargetKid(result.targetKid()) + .setTargetAlgorithm(result.targetAlgorithm()) + .setPublicKeyFingerprint(result.publicKeyFingerprint()) + .setPublicJwkJson(result.publicJwkJson()) + .build(); + } + + private static GetCurrentPromotionRequestResponse toPromotionRequestResponse( + PreparedGenerationEvidence prepared) { + var promotion = prepared.promotion(); + var generation = prepared.generationResult(); + GetCurrentPromotionRequestResponse.Builder response = + GetCurrentPromotionRequestResponse.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(promotion.operationId().toString()) + .setPromotionRequestDigest(promotion.requestDigest()) + .setGenerationOperationId(generation.operationId().toString()) + .setGenerationOperationDigest(generation.operationDigest()) + .setGenerationReceiptDigest(generation.receiptDigest()) + .setEnvironmentId(promotion.binding().environmentId()) + .setClusterId(promotion.binding().clusterId()) + .setNamespace(promotion.binding().namespace()) + .setExpectedClusterIncarnationUid( + promotion.trustFence().expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(promotion.trustFence().expectedNamespaceUid()) + .setTrustBindingDigest(promotion.trustFence().bindingDigest()) + .setTrustConfigRevision(promotion.trustFence().configRevision()) + .setPrivateSecretName(AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME) + .setTargetGeneration(promotion.targetGeneration()) + .setTargetKid(promotion.targetKid()) + .setTargetAlgorithm(promotion.targetAlgorithm()) + .setTargetPublicKeyFingerprint(promotion.targetPublicKeyFingerprint()) + .setExpectedSecretUid(promotion.secretUid()) + .setExpectedSecretResourceVersion(promotion.expectedPrivateResourceVersion()) + .setOperationAction("PROMOTE_PENDING") + .addAllowedPrivateSlots("current.key") + .addAllowedPrivateSlots("pending.key") + .addAllowedPrivateSlots("previous.key"); + promotion + .expectedPreviousActive() + .ifPresent( + previous -> { + response.setExpectedPreviousGeneration(previous.generation()); + response.setExpectedPreviousKid(previous.kid()); + response.setExpectedPreviousPublicKeyFingerprint( + promotion.expectedPreviousPublicKeyFingerprint().orElseThrow()); + }); + return response.build(); + } + + private static PublicKeyIdentity publicIdentity(PromotionPublicKeyIdentity identity) { + return new PublicKeyIdentity( + identity.getGeneration(), identity.getKid(), identity.getPublicKeyFingerprint()); + } + + private static void validateRequest(int schemaVersion, boolean unknownFieldsEmpty) { + if (schemaVersion != 1 || !unknownFieldsEmpty) { + throw Status.INVALID_ARGUMENT + .withDescription("Exact JWT materialization request schema is required") + .asRuntimeException(); + } + } + + private static UUID parseOperationId(String value) { + try { + UUID operationId = UUID.fromString(value); + if (operationId.version() != 4 || !operationId.toString().equals(value)) { + throw new IllegalArgumentException("UUIDv4 required"); + } + return operationId; + } catch (RuntimeException ex) { + throw Status.INVALID_ARGUMENT + .withDescription("JWT signer operation ID must be canonical UUIDv4") + .asRuntimeException(); + } + } + + private static Status statusFor(RuntimeException exception) { + if (exception instanceof StatusRuntimeException statusException) { + return statusException.getStatus(); + } + if (exception instanceof IllegalArgumentException) { + return Status.INVALID_ARGUMENT.withDescription("JWT materialization request is malformed"); + } + if (exception instanceof AccountJwtSignerDesiredStateRepository.IdempotencyConflictException) { + return Status.ALREADY_EXISTS.withDescription( + "JWT materialization operation or public result conflicts with retained Account evidence"); + } + if (exception instanceof BootstrapOperationException) { + return Status.FAILED_PRECONDITION.withDescription( + "Account JWT signer bootstrap enrollment is quarantined"); + } + if (exception instanceof AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException) { + return Status.NOT_FOUND.withDescription("No Account-authorized signer promotion is pending"); + } + if (exception instanceof AccountJwtSignerDesiredStateRepository.StorageUnavailableException + || exception instanceof DataAccessResourceFailureException + || hasConnectionFailure(exception)) { + return Status.UNAVAILABLE.withDescription( + "Account JWT materialization storage is unavailable"); + } + if (exception instanceof AccountJwtSignerDesiredStateRepository.MissingDesiredStateException + || exception + instanceof AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException + || exception + instanceof AccountJwtSignerDesiredStateRepository.MissingGenerationObservationException + || exception + instanceof AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException + || exception instanceof AccountJwtSignerDesiredStateRepository.BindingMismatchException + || exception instanceof AccountJwtSignerDesiredStateRepository.VersionConflictException + || exception instanceof AccountJwtSignerDesiredStateRepository.QuarantinedStateException + || exception + instanceof + AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException) { + return Status.FAILED_PRECONDITION.withDescription( + "No exact current Account JWT signer generation phase is available"); + } + if (exception instanceof DataAccessException) { + return Status.INTERNAL.withDescription( + "Account JWT generation evidence could not be recorded"); + } + return Status.INTERNAL.withDescription("Account JWT materialization could not be completed"); + } + + private static boolean hasConnectionFailure(Throwable failure) { + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current instanceof SQLException sqlException) { + String state = sqlException.getSQLState(); + if (state != null && state.startsWith("08")) { + return true; + } + } + } + return false; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java index 6bb0e6cade..e8c7c2a20e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java @@ -213,7 +213,7 @@ Stored bindCandidate( byte[] active = registry(current, signer, tokenHash, true); dsl.execute( "INSERT INTO account_control_ui_response_envelopes" - + " (operation_id, encrypted_response, owner_binding, recovery_expires_at) VALUES (?, ?, ?, ?)", + + " (operation_id, encrypted_response, owner_binding, recovery_expires_at) VALUES (?, ?, ?, ?::timestamptz)", current.operationId, envelope, binding, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java new file mode 100644 index 0000000000..17de38c401 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java @@ -0,0 +1,935 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.security.KeyFactory; +import java.security.spec.RSAPublicKeySpec; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.MountObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned producer for the public JWKS prepublication phase and local mounted correspondence + * observation. + * + *

It accepts no caller-selected operation, key identity, ConfigMap name, or public bytes. The + * only source key is the exact current Account generation receipt. Remote CAS is outside SQL + * transactions and is preceded by a durable immutable intent. Neither publication nor local + * correspondence establishes PREPARED, COMMITTED, issuance, cache convergence, probes, or + * readiness. + */ +public final class AccountJwtJwksPrepublicationService { + public static final int MAX_MOUNTED_MARKER_BYTES = 16 * 1024; + private static final String PRIVATE_MOUNT = "/var/run/secrets/firemud/jwt"; + private static final String PRIVATE_PENDING_BUNDLE = "pending.key"; + private static final String PRIVATE_ACTIVE_BUNDLE = "current.key"; + private static final String PUBLIC_MOUNT = "/var/run/secrets/firemud/jwks"; + private static final String PUBLIC_JWKS = "jwks.json"; + private static final String PUBLIC_MARKER = "jwt-generation.json"; + private static final int MAX_KEYS = 64; + private static final int MIN_RSA_BITS = 3_072; + private static final int MAX_RSA_BITS = 16_384; + private static final Set JWKS_ROOT_FIELDS = Set.of("keys"); + private static final Set JWK_FIELDS = + Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPublicationRepository publicationRepository; + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtJwksConfigMapClient configMapClient; + private final TransactionTemplate accountTransaction; + private final MountedProjection mountedProjection; + + /** Production instance uses only the fixed Account signer/JWKS mount paths. */ + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The production constructor intentionally fixes Account's protected private-signer and read-only public-JWKS mount roots.") + public AccountJwtJwksPrepublicationService( + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksConfigMapClient configMapClient, + PlatformTransactionManager transactionManager) { + this( + desiredStateRepository, + publicationRepository, + materializerTrustBinding, + configMapClient, + transactionManager, + new MountedProjection( + Path.of(PRIVATE_MOUNT), + Path.of(PRIVATE_PENDING_BUNDLE), + Path.of(PUBLIC_MOUNT), + Path.of(PUBLIC_JWKS), + Path.of(PUBLIC_MARKER))); + } + + AccountJwtJwksPrepublicationService( + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksConfigMapClient configMapClient, + PlatformTransactionManager transactionManager, + MountedProjection mountedProjection) { + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Desired-state repository is required"); + this.publicationRepository = + Objects.requireNonNull(publicationRepository, "JWKS publication repository is required"); + this.materializerTrustBinding = + Objects.requireNonNull( + materializerTrustBinding, "Protected materializer trust is required"); + this.configMapClient = + Objects.requireNonNull(configMapClient, "Protected ConfigMap client is required"); + this.accountTransaction = new TransactionTemplate(transactionManager); + this.accountTransaction.setReadOnly(false); + this.mountedProjection = Objects.requireNonNull(mountedProjection); + } + + /** + * Publishes exactly Account's current pending public JWK alongside all retained public keys. + * Exact retries reconcile a previously persisted intent; changed/stale ConfigMap data fail before + * another write. + */ + public PublicationReceipt prepublishCurrentGeneration() { + Binding binding = requireCurrentMaterializerBinding(); + BindingIdentity apiIdentity = requireMatchingApiIdentity(binding, configMapClient.identity()); + CurrentGeneration current = loadCurrentGeneration(binding, apiIdentity); + if (current.publication().isPresent()) { + PublicationEvidence evidence = current.publication().orElseThrow(); + PrepublicationIntent intent = evidence.intent(); + requireIntentApiIdentity(intent, apiIdentity); + ConfigMapSnapshot snapshot = configMapClient.observe(); + if (evidence.receipt().isPresent()) { + requirePublishedProjection(intent, snapshot); + requireUnchangedBindings(binding, apiIdentity); + return evidence.receipt().orElseThrow(); + } + requireRetrySnapshot(intent, snapshot); + return publishAndRecord(binding, apiIdentity, intent, snapshot); + } + + ConfigMapSnapshot snapshot = configMapClient.observe(); + String sourceJwks = snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY); + if (sourceJwks == null || sourceJwks.isBlank()) { + throw new PublicationRejectedException( + "Pre-created Account public JWKS ConfigMap has no bounded jwks.json value"); + } + String desiredJwks = appendPendingPublicKey(sourceJwks, current.result()); + String marker = generationMarker(current.result(), current.request(), apiIdentity); + PrepublicationIntent intent = + accountTransaction.execute( + status -> { + PrepublicationIntent persisted = + publicationRepository.recordPrepublicationIntent( + binding.accountBinding(), + trustFence(binding), + current.result(), + current.request(), + apiIdentity.bindingDigest(), + apiIdentity.configRevision(), + snapshot.uid(), + snapshot.resourceVersion(), + AccountJwtJwksPublicationRepository.snapshotDigest(snapshot.data()), + desiredJwks, + marker); + requireUnchangedBindings(binding, apiIdentity); + return persisted; + }); + if (intent == null) { + throw new PublicationRejectedException("Account JWT JWKS intent was not persisted"); + } + requireIntentApiIdentity(intent, apiIdentity); + requireRetrySnapshot(intent, snapshot); + return publishAndRecord(binding, apiIdentity, intent, snapshot); + } + + /** + * Observes exact mounted {@code pending.key}, {@code jwks.json}, and publication marker files. + * The operation must already have an exact persisted Account API readback receipt. + */ + public MountObservation observeCurrentMountedCorrespondence() { + Binding binding = requireCurrentMaterializerBinding(); + BindingIdentity apiIdentity = requireMatchingApiIdentity(binding, configMapClient.identity()); + CurrentGeneration current = loadCurrentGeneration(binding, apiIdentity); + PublicationEvidence evidence = + current + .publication() + .orElseThrow( + () -> + new PublicationRejectedException( + "Account JWT JWKS publication evidence is not available")); + PrepublicationIntent intent = evidence.intent(); + evidence + .receipt() + .orElseThrow( + () -> + new PublicationRejectedException("Account JWT JWKS API readback is not available")); + requireIntentApiIdentity(intent, apiIdentity); + + byte[] markerBytes = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.markerPath(), + MAX_MOUNTED_MARKER_BYTES); + byte[] jwksBytes = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES); + String marker = strictUtf8(markerBytes); + String mountedJwks = strictUtf8(jwksBytes); + if (!intent.generationMarkerJson().equals(marker) + || !intent.jwksJson().equals(mountedJwks) + || !intent + .publicDataDigest() + .equals(AccountJwtJwksPublicationRepository.publicDataDigest(mountedJwks, marker))) { + throw new PublicationRejectedException( + "Mounted Account public JWT projection does not match Account's exact publication"); + } + + AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + current.result().operationId().toString(), + current.result().targetGeneration(), + current.result().targetKid(), + current.result().publicKeyFingerprint()); + AccountMountedJwtSignerBundle.LocalObservation localObservation = + AccountMountedJwtSignerBundle.observeMounted( + mountedProjection.privateMountRoot(), + mountedProjection.pendingBundlePath(), + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + expectedIdentity); + + byte[] markerAfter = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.markerPath(), + MAX_MOUNTED_MARKER_BYTES); + byte[] jwksAfter = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES); + if (!Arrays.equals(markerBytes, markerAfter) || !Arrays.equals(jwksBytes, jwksAfter)) { + throw new PublicationRejectedException( + "Mounted Account public JWT projection changed during correspondence observation"); + } + MountObservation observation = + accountTransaction.execute( + status -> { + MountObservation persisted = + publicationRepository.recordMountedCorrespondence( + binding.accountBinding(), + trustFence(binding), + current.result().operationId(), + sha256(markerBytes), + AccountJwtJwksPublicationRepository.publicDataDigest(mountedJwks, marker), + localObservation.publicKeyFingerprint()); + requireUnchangedBindings(binding, apiIdentity); + return persisted; + }); + if (observation == null) { + throw new PublicationRejectedException( + "Mounted Account JWT correspondence was not persisted"); + } + Arrays.fill(markerBytes, (byte) 0); + Arrays.fill(jwksBytes, (byte) 0); + Arrays.fill(markerAfter, (byte) 0); + Arrays.fill(jwksAfter, (byte) 0); + return observation; + } + + /** + * Observes the exact Account PREPARED operation's current private key and public projection + * without mutating either resource. The protected fixed Secret may already have been promoted + * while the public ConfigMap remains PREPUBLISHED; after an ambiguous Account-owned CAS, the + * exact ACTIVE projection is also accepted for forward reconciliation. + */ + public ConfigMapSnapshot observePreparedCurrentKeyCorrespondence( + PromotionOperationEvidence promotion) { + Objects.requireNonNull(promotion, "Account PREPARED promotion is required"); + Binding binding = requireCurrentMaterializerBinding(); + BindingIdentity apiIdentity = requireMatchingApiIdentity(binding, configMapClient.identity()); + TrustFence trust = trustFence(binding); + if (!promotion.binding().equals(binding.accountBinding()) + || !promotion.trustFence().equals(trust) + || !promotion.apiBindingDigest().equals(apiIdentity.bindingDigest()) + || !promotion.apiConfigRevision().equals(apiIdentity.configRevision()) + || !"PREPARED".equals(promotion.status()) + || !promotion.privatePromotionDispatched() + || promotion.privatePromotionReceiptDigest().isEmpty() + || !promotion.expectedPreviousActive().equals(promotion.expectedPublishedActive())) { + throw new PublicationRejectedException( + "Prepared Account JWT operation no longer matches protected bindings"); + } + + var publication = + accountTransaction.execute( + status -> + publicationRepository.readPreparedPublicationForRecovery( + binding.accountBinding(), trust)); + if (publication == null + || !publication.intent().operationId().equals(promotion.generationOperationId()) + || !publication.intent().intentDigest().equals(promotion.prepublicationIntentDigest()) + || !publication.receipt().receiptDigest().equals(promotion.prepublicationReceiptDigest()) + || !publication.intent().configMapUid().equals(promotion.publicConfigMapUid()) + || !publication + .receipt() + .observedResourceVersion() + .equals(promotion.expectedPublicResourceVersion()) + || !publication.intent().jwksJson().equals(promotion.expectedPublicJwksJson())) { + throw new PublicationRejectedException( + "Prepared Account JWT operation has no exact public publication evidence"); + } + + ConfigMapSnapshot snapshot = configMapClient.observe(); + String mountedJwks = snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY); + String apiMarker = + snapshot.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY); + boolean prepublished = publication.intent().generationMarkerJson().equals(apiMarker); + boolean active = promotion.expectedActiveMarkerJson().equals(apiMarker); + if (!promotion.publicConfigMapUid().equals(snapshot.uid()) + || !promotion.expectedPublicJwksJson().equals(mountedJwks) + || (!prepublished && !active) + || (prepublished + && !promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion())) + || (active + && promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion()))) { + throw new PublicationRejectedException( + "Live Account public JWT projection is not the exact PREPARED or ACTIVE value"); + } + if (promotion.activeJwksReceiptDigest().isPresent()) { + if (!active + || !promotion + .activeJwksObservedResourceVersion() + .filter(snapshot.resourceVersion()::equals) + .isPresent() + || !promotion + .activeJwksPublicDataDigest() + .filter( + AccountJwtJwksPublicationRepository.publicDataDigest(mountedJwks, apiMarker) + ::equals) + .isPresent()) { + throw new PublicationRejectedException( + "Live Account ACTIVE JWT projection differs from its durable receipt"); + } + } + + byte[] markerBefore = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.markerPath(), + MAX_MOUNTED_MARKER_BYTES); + byte[] jwksBefore = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES); + byte[] markerAfter = null; + byte[] jwksAfter = null; + try { + if (!apiMarker.equals(strictUtf8(markerBefore)) + || !mountedJwks.equals(strictUtf8(jwksBefore))) { + throw new PublicationRejectedException( + "Mounted Account public JWT projection has not caught up to its exact API value"); + } + AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + promotion.generationOperationId().toString(), + promotion.targetGeneration(), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint()); + AccountMountedJwtSignerBundle.LocalObservation local = + AccountMountedJwtSignerBundle.observeMounted( + mountedProjection.privateMountRoot(), + Path.of(PRIVATE_ACTIVE_BUNDLE), + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + expectedIdentity); + if (!local.expectedIdentity().equals(expectedIdentity)) { + throw new PublicationRejectedException( + "Mounted Account current JWT key does not match the PREPARED operation"); + } + markerAfter = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.markerPath(), + MAX_MOUNTED_MARKER_BYTES); + jwksAfter = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES); + if (!Arrays.equals(markerBefore, markerAfter) || !Arrays.equals(jwksBefore, jwksAfter)) { + throw new PublicationRejectedException( + "Mounted Account public JWT projection changed during current-key correspondence"); + } + requireUnchangedBindings(binding, apiIdentity); + return snapshot; + } finally { + Arrays.fill(markerBefore, (byte) 0); + Arrays.fill(jwksBefore, (byte) 0); + if (markerAfter != null) { + Arrays.fill(markerAfter, (byte) 0); + } + if (jwksAfter != null) { + Arrays.fill(jwksAfter, (byte) 0); + } + } + } + + private PublicationReceipt publishAndRecord( + Binding binding, + BindingIdentity apiIdentity, + PrepublicationIntent intent, + ConfigMapSnapshot expectedSnapshot) { + requireUnchangedBindings(binding, apiIdentity); + Map desiredData = desiredData(intent); + ConfigMapSnapshot intentCasSnapshot = + new ConfigMapSnapshot( + intent.configMapUid(), intent.expectedResourceVersion(), expectedSnapshot.data()); + CasObservation observation = configMapClient.publish(intentCasSnapshot, desiredData); + if (!intent.configMapUid().equals(observation.uid()) + || !intent.expectedResourceVersion().equals(observation.priorResourceVersion()) + || !observation.publishedData().equals(desiredData) + || !desiredData.entrySet().stream() + .allMatch( + entry -> entry.getValue().equals(observation.readbackData().get(entry.getKey()))) + || intent.expectedResourceVersion().equals(observation.resourceVersion())) { + throw new PublicationRejectedException( + "Protected Account public JWKS client returned a non-exact readback"); + } + requireUnchangedBindings(binding, apiIdentity); + PublicationReceipt persisted = + accountTransaction.execute( + status -> { + PublicationReceipt receipt = + publicationRepository.recordPublicationReceipt( + binding.accountBinding(), + trustFence(binding), + intent.operationId(), + apiIdentity.bindingDigest(), + apiIdentity.configRevision(), + observation.uid(), + observation.resourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson()); + requireUnchangedBindings(binding, apiIdentity); + return receipt; + }); + if (persisted == null) { + throw new PublicationRejectedException("Account JWT JWKS API receipt was not persisted"); + } + return persisted; + } + + private CurrentGeneration loadCurrentGeneration(Binding binding, BindingIdentity apiIdentity) { + CurrentGeneration current = + accountTransaction.execute( + status -> { + GenerationResult result = + desiredStateRepository.readCurrentGenerationResult( + binding.accountBinding(), trustFence(binding)); + GenerationRequest request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + Optional publication = + publicationRepository.readCurrentPublication( + binding.accountBinding(), trustFence(binding)); + if (!result.binding().equals(binding.accountBinding()) + || !result.trustFence().equals(trustFence(binding)) + || !request.operationId().equals(result.operationId()) + || !request.generationReceiptDigest().equals(result.receiptDigest())) { + throw new PublicationRejectedException( + "Account JWT generation receipt does not match the current protected binding"); + } + requireUnchangedBindings(binding, apiIdentity); + return new CurrentGeneration(result, request, publication); + }); + if (current == null) { + throw new PublicationRejectedException("Current Account JWT generation is unavailable"); + } + return current; + } + + private Binding requireCurrentMaterializerBinding() { + Binding current = materializerTrustBinding.current().orElse(null); + if (current == null) { + throw new PublicationRejectedException( + "Protected Account JWT materializer binding is unavailable"); + } + return current; + } + + private static BindingIdentity requireMatchingApiIdentity( + Binding materializerBinding, BindingIdentity apiIdentity) { + if (apiIdentity == null + || !materializerBinding.environmentId().equals(apiIdentity.environmentId()) + || !materializerBinding.clusterId().equals(apiIdentity.clusterId()) + || !materializerBinding.namespace().equals(apiIdentity.namespace()) + || !materializerBinding + .expectedClusterIncarnationUid() + .equals(apiIdentity.expectedClusterIncarnationUid()) + || !materializerBinding.expectedNamespaceUid().equals(apiIdentity.expectedNamespaceUid()) + || apiIdentity.bindingDigest() == null + || apiIdentity.configRevision() == null) { + throw new PublicationRejectedException( + "Protected Account materializer and ConfigMap API bindings disagree"); + } + return apiIdentity; + } + + private void requireUnchangedBindings(Binding expected, BindingIdentity expectedApiIdentity) { + if (materializerTrustBinding.current().filter(expected::equals).isEmpty() + || !expectedApiIdentity.equals(configMapClient.identity())) { + throw new PublicationRejectedException( + "Protected Account JWT publication trust changed during the operation"); + } + } + + private static void requireIntentApiIdentity( + PrepublicationIntent intent, BindingIdentity apiIdentity) { + if (!intent.apiBindingDigest().equals(apiIdentity.bindingDigest()) + || !intent.apiConfigRevision().equals(apiIdentity.configRevision())) { + throw new PublicationRejectedException( + "Protected Account ConfigMap API trust changed for the current JWT operation"); + } + } + + private static void requirePublishedProjection( + PrepublicationIntent intent, ConfigMapSnapshot snapshot) { + if (!intent.configMapUid().equals(snapshot.uid()) + || !intent + .jwksJson() + .equals(snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY)) + || !intent + .generationMarkerJson() + .equals( + snapshot + .data() + .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY))) { + throw new PublicationRejectedException( + "Current public JWT ConfigMap no longer matches Account's immutable receipt"); + } + } + + private static void requireRetrySnapshot( + PrepublicationIntent intent, ConfigMapSnapshot snapshot) { + if (!intent.configMapUid().equals(snapshot.uid())) { + throw new PublicationRejectedException( + "Account public JWKS ConfigMap UID changed after intent creation"); + } + if (intent + .jwksJson() + .equals(snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY)) + && intent + .generationMarkerJson() + .equals( + snapshot + .data() + .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY))) { + return; + } + if (!intent.expectedResourceVersion().equals(snapshot.resourceVersion()) + || !intent + .expectedSnapshotDigest() + .equals(AccountJwtJwksPublicationRepository.snapshotDigest(snapshot.data()))) { + throw new PublicationRejectedException( + "Account public JWKS ConfigMap changed after immutable intent creation"); + } + } + + private static Map desiredData(PrepublicationIntent intent) { + Map data = new LinkedHashMap<>(); + data.put(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, intent.jwksJson()); + data.put( + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + intent.generationMarkerJson()); + return Map.copyOf(data); + } + + private static String appendPendingPublicKey(String sourceJwks, GenerationResult result) { + JsonNode root = parseStrictJson(sourceJwks, AccountJwtJwksPublicationRepository.MAX_JWKS_BYTES); + boolean supportedRoot = root.size() == JWKS_ROOT_FIELDS.size(); + for (Map.Entry field : root.properties()) { + supportedRoot &= JWKS_ROOT_FIELDS.contains(field.getKey()); + } + if (!supportedRoot) { + throw new PublicationRejectedException("Existing Account JWKS has an unsupported shape"); + } + JsonNode keys = root.get("keys"); + if (keys == null || !keys.isArray() || keys.size() >= MAX_KEYS) { + throw new PublicationRejectedException( + "Existing Account JWKS is missing or at its key limit"); + } + Set kids = new HashSet<>(); + List canonicalKeys = new ArrayList<>(keys.size() + 1); + for (JsonNode jwk : keys) { + validateRetainedJwk(jwk); + String kid = jwk.get("kid").textValue(); + if (!kids.add(kid) || kid.equals(result.targetKid())) { + throw new PublicationRejectedException( + "Existing Account JWKS has a duplicate or conflicting key identifier"); + } + canonicalKeys.add(canonicalJson(jwk.toString())); + } + JsonNode pending = parseStrictJson(result.publicJwkJson(), 8 * 1024); + validateRetainedJwk(pending); + if (!result.targetKid().equals(pending.get("kid").textValue()) + || !kids.add(result.targetKid())) { + throw new PublicationRejectedException( + "Account generation receipt has a conflicting public key identifier"); + } + canonicalKeys.add(canonicalJson(result.publicJwkJson())); + String jwks = "{\"keys\":[" + String.join(",", canonicalKeys) + "]}"; + if (jwks.getBytes(StandardCharsets.UTF_8).length + > AccountJwtJwksPublicationRepository.MAX_JWKS_BYTES) { + throw new PublicationRejectedException("Account public JWKS exceeds its storage bound"); + } + return jwks; + } + + private static void validateRetainedJwk(JsonNode jwk) { + if (jwk == null || !jwk.isObject() || jwk.size() < 6 || jwk.size() > 7) { + throw new PublicationRejectedException("Existing Account JWKS contains a malformed key"); + } + for (Map.Entry field : jwk.properties()) { + if (!JWK_FIELDS.contains(field.getKey())) { + throw new PublicationRejectedException( + "Existing Account JWKS contains an unsupported or private key field"); + } + } + String kty = requiredText(jwk, "kty", 8); + String use = requiredText(jwk, "use", 8); + String alg = requiredText(jwk, "alg", 8); + String kid = requiredText(jwk, "kid", 64); + String n = requiredText(jwk, "n", 4096); + String e = requiredText(jwk, "e", 16); + if (!"RSA".equals(kty) + || !"sig".equals(use) + || !"RS256".equals(alg) + || !KID.matcher(kid).matches()) { + throw new PublicationRejectedException("Existing Account JWKS contains an unsupported key"); + } + JsonNode keyOps = jwk.get("key_ops"); + if (keyOps != null + && (!keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue()))) { + throw new PublicationRejectedException("Existing Account JWKS key operations are malformed"); + } + byte[] modulus = decodeBase64Url(n, 2048); + byte[] exponent = decodeBase64Url(e, 8); + try { + if (modulus.length == 0 || modulus[0] == 0 || exponent.length == 0 || exponent[0] == 0) { + throw new PublicationRejectedException( + "Existing Account JWKS RSA parameters are malformed"); + } + BigInteger modulusValue = new BigInteger(1, modulus); + BigInteger exponentValue = new BigInteger(1, exponent); + if (modulusValue.bitLength() < MIN_RSA_BITS + || modulusValue.bitLength() > MAX_RSA_BITS + || !modulusValue.testBit(0) + || !BigInteger.valueOf(65_537).equals(exponentValue)) { + throw new PublicationRejectedException( + "Existing Account JWKS RSA parameters are unsupported"); + } + KeyFactory.getInstance("RSA") + .generatePublic(new RSAPublicKeySpec(modulusValue, exponentValue)); + } catch (Exception ex) { + if (ex instanceof PublicationRejectedException rejected) { + throw rejected; + } + throw new PublicationRejectedException("Existing Account JWKS RSA parameters are invalid"); + } finally { + Arrays.fill(modulus, (byte) 0); + Arrays.fill(exponent, (byte) 0); + } + } + + private static String generationMarker( + GenerationResult result, GenerationRequest request, BindingIdentity apiIdentity) { + Map marker = new LinkedHashMap<>(); + marker.put("schemaVersion", 1); + marker.put("phase", "PREPUBLISHED"); + marker.put("operationId", result.operationId().toString()); + marker.put("operationDigest", result.operationDigest()); + marker.put("generationRequestDigest", result.generationRequestDigest()); + marker.put("generationReceiptDigest", result.receiptDigest()); + Map binding = new LinkedHashMap<>(); + binding.put("environmentId", result.binding().environmentId()); + binding.put("clusterId", result.binding().clusterId()); + binding.put("namespace", result.binding().namespace()); + binding.put( + "expectedClusterIncarnationUid", result.trustFence().expectedClusterIncarnationUid()); + binding.put("expectedNamespaceUid", result.trustFence().expectedNamespaceUid()); + binding.put("trustBindingDigest", result.trustFence().bindingDigest()); + binding.put("trustConfigRevision", result.trustFence().configRevision()); + binding.put("apiBindingDigest", apiIdentity.bindingDigest()); + binding.put("apiConfigRevision", apiIdentity.configRevision()); + marker.put("binding", binding); + marker.put("publicConfigMap", Map.of("name", "jwt-jwks")); + marker.put("expectedDurableActive", activeMarker(request.expectedActive())); + marker.put("expectedPublishedActive", activeMarker(request.expectedPublishedActive())); + Map pending = new LinkedHashMap<>(); + pending.put("generation", result.targetGeneration()); + pending.put("kid", result.targetKid()); + pending.put("algorithm", result.targetAlgorithm()); + pending.put("publicKeyFingerprint", result.publicKeyFingerprint()); + marker.put("pending", pending); + return canonicalJson(marker); + } + + private static Map activeMarker( + Optional active) { + Map marker = new LinkedHashMap<>(); + marker.put("present", active.isPresent()); + active.ifPresent( + signer -> { + marker.put("generation", signer.generation()); + marker.put("kid", signer.kid()); + }); + return marker; + } + + private static JsonNode parseStrictJson(String json, int maxBytes) { + if (json == null || json.isBlank() || json.getBytes(StandardCharsets.UTF_8).length > maxBytes) { + throw new PublicationRejectedException("Account public JWT JSON is missing or oversized"); + } + try { + JsonNode node = STRICT_JSON.readTree(json); + if (node == null || !node.isObject()) { + throw new PublicationRejectedException("Account public JWT JSON has an unsupported shape"); + } + return node; + } catch (PublicationRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new PublicationRejectedException("Account public JWT JSON is malformed"); + } + } + + private static String requiredText(JsonNode object, String field, int maxLength) { + JsonNode value = object.get(field); + if (value == null + || !value.isTextual() + || value.textValue().isEmpty() + || value.textValue().length() > maxLength) { + throw new PublicationRejectedException("Existing Account JWKS key is malformed"); + } + return value.textValue(); + } + + private static byte[] decodeBase64Url(String value, int maxBytes) { + if (value == null + || value.isEmpty() + || value.contains("=") + || !value.matches("[A-Za-z0-9_-]+")) { + throw new PublicationRejectedException("Existing Account JWKS RSA parameters are malformed"); + } + try { + byte[] decoded = Base64.getUrlDecoder().decode(value); + if (decoded.length > maxBytes + || !Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(value)) { + Arrays.fill(decoded, (byte) 0); + throw new PublicationRejectedException( + "Existing Account JWKS RSA parameters are malformed"); + } + return decoded; + } catch (IllegalArgumentException ex) { + throw new PublicationRejectedException("Existing Account JWKS RSA parameters are malformed"); + } + } + + private static String canonicalJson(String json) { + try { + return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new PublicationRejectedException("Account public JWT JSON canonicalization failed"); + } + } + + private static String canonicalJson(Object value) { + try { + return canonicalJson(STRICT_JSON.writeValueAsString(value)); + } catch (Exception ex) { + throw new PublicationRejectedException("Account public JWT marker encoding failed"); + } + } + + private static byte[] readMountedFile(Path configuredRoot, Path relativePath, int maxBytes) { + try { + if (configuredRoot == null + || relativePath == null + || relativePath.isAbsolute() + || relativePath.normalize().startsWith("..")) { + throw new IOException("Mounted file path is invalid"); + } + Path root = configuredRoot.toRealPath(); + if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) { + throw new IOException("Mounted root is unavailable"); + } + Path unresolved = root.resolve(relativePath).normalize(); + if (!unresolved.startsWith(root)) { + throw new IOException("Mounted file escapes its projection"); + } + Path file = unresolved.toRealPath(); + if (!file.startsWith(root) || !Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) { + throw new IOException("Mounted file is unavailable"); + } + BasicFileAttributes before = + Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (before.size() <= 0 || before.size() > maxBytes) { + throw new IOException("Mounted file size is invalid"); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(file, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw new IOException("Mounted file changed while being read"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Mounted file changed while being read"); + } + } + BasicFileAttributes after = + Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime())) { + Arrays.fill(bytes, (byte) 0); + throw new IOException("Mounted file changed while being read"); + } + return bytes; + } catch (IOException | RuntimeException ex) { + throw new PublicationRejectedException( + "Mounted Account JWT public projection is unavailable or invalid"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw new PublicationRejectedException("Mounted Account JWT public projection is not UTF-8"); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private record CurrentGeneration( + GenerationResult result, + GenerationRequest request, + Optional publication) {} + + /** Fixed filesystem projections; production paths are not request inputs. */ + record MountedProjection( + Path privateMountRoot, + Path pendingBundlePath, + Path publicMountRoot, + Path jwksPath, + Path markerPath) { + MountedProjection { + Objects.requireNonNull(privateMountRoot); + Objects.requireNonNull(pendingBundlePath); + Objects.requireNonNull(publicMountRoot); + Objects.requireNonNull(jwksPath); + Objects.requireNonNull(markerPath); + if (pendingBundlePath.isAbsolute() + || jwksPath.isAbsolute() + || markerPath.isAbsolute() + || pendingBundlePath.normalize().startsWith("..") + || jwksPath.normalize().startsWith("..") + || markerPath.normalize().startsWith("..")) { + throw new IllegalArgumentException("JWT mounted projection paths must be relative"); + } + } + } + + /** Safe generic failure; never includes a key, ConfigMap response body, or mounted path. */ + public static final class PublicationRejectedException extends IllegalStateException { + public PublicationRejectedException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java new file mode 100644 index 0000000000..71b0e8aa0a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java @@ -0,0 +1,502 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.ManagedChannel; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.UnknownHostException; +import java.time.Clock; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; +import net.firedevops.firemud.account.v1.AccountJwtPodReceiverIdentity; +import net.firedevops.firemud.account.v1.AccountJwtReadinessPodReceiverServiceGrpc; +import net.firedevops.firemud.account.v1.AccountPodTargetBinding; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeRequest; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.Invocation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.PodTarget; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.gamesession.v1.GameSessionJwtReadinessReceiverServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeRequest; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeResponse; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; + +/** Exact direct-Pod mTLS client for Account and Game Session non-authorizing probe receivers. */ +public final class AccountJwtReadinessGrpcReceiverInvocationPort + extends AccountJwtReadinessReceiverInvocationPort { + private static final String TLS_BUNDLE_NAME = "firemud-grpc"; + private static final String GAME_SESSION_VALIDATOR = "game-session-service"; + private static final String ACCOUNT_VALIDATOR = "account-service"; + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final long SHUTDOWN_DEADLINE_SECONDS = 2L; + private final SslBundles sslBundles; + private final Clock clock; + + public AccountJwtReadinessGrpcReceiverInvocationPort( + SslBundles sslBundles, String workloadNamespace) { + this(sslBundles, workloadNamespace, Clock.systemUTC()); + } + + AccountJwtReadinessGrpcReceiverInvocationPort( + SslBundles sslBundles, String workloadNamespace, Clock clock) { + this.sslBundles = Objects.requireNonNull(sslBundles); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Account workload namespace is required"); + } + this.clock = Objects.requireNonNull(clock); + } + + @Override + public void requireAvailable() { + SslBundle bundle = configuredBundle(); + if (bundle.getManagers().getKeyManagerFactory() == null + || bundle.getManagers().getTrustManagerFactory() == null) { + throw new ReceiverUnavailableException(); + } + try { + X509TrustManager ignored = x509TrustManager(bundle.getManagers().getTrustManagerFactory()); + if (ignored.getAcceptedIssuers().length == 0) { + throw new ReceiverUnavailableException(); + } + } catch (RuntimeException failure) { + throw new ReceiverUnavailableException(); + } + } + + @Override + public AuthenticatedAcceptance invoke(Invocation invocation) { + Objects.requireNonNull(invocation, "readiness invocation is required"); + requireAvailable(); + if ((!GAME_SESSION_VALIDATOR.equals(invocation.validatorId()) + && !ACCOUNT_VALIDATOR.equals(invocation.validatorId())) + || !invocation.validatorId().equals(invocation.target().validatorId())) { + throw new ReceiverUnavailableException(); + } + + PodTarget target = invocation.target(); + target.requireRoutablePodIdentity(); + String expectedServiceUri = target.canonicalServiceUri().orElseThrow(); + if (!expectedServiceUri.equals(serviceUri(target.namespace(), target.validatorId()))) { + throw new ReceiverUnavailableException(); + } + URI endpoint = target.exactPodEndpoint().orElseThrow(); + InetAddress podAddress = numericPodAddress(target.podIp()); + if (!endpoint.getHost().equals(target.podIp()) + && !endpoint.getHost().equals("[" + target.podIp() + "]")) { + throw new ReceiverUnavailableException(); + } + if (clock.instant().getEpochSecond() > invocation.expiresAtEpochSecond()) { + throw new ReceiverUnavailableException(); + } + + SslBundle bundle = configuredBundle(); + AccountJwtReadinessPodTrustManager peerTrust = + new AccountJwtReadinessPodTrustManager( + x509TrustManager(bundle.getManagers().getTrustManagerFactory()), + expectedServiceUri, + target.podLeafSpkiSha256().orElseThrow()); + final SslContext sslContext; + try { + sslContext = + GrpcSslContexts.forClient() + .keyManager(bundle.getManagers().getKeyManagerFactory()) + .trustManager((TrustManager) peerTrust) + .build(); + } catch (SSLException | RuntimeException failure) { + throw new ReceiverUnavailableException(); + } + + ManagedChannel channel = + NettyChannelBuilder.forAddress(new InetSocketAddress(podAddress, endpoint.getPort())) + .sslContext(sslContext) + .disableRetry() + .build(); + AuthenticatedAcceptance acceptance; + try { + if (GAME_SESSION_VALIDATOR.equals(invocation.validatorId())) { + ReceiveReadinessProbeResponse response = + GameSessionJwtReadinessReceiverServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .receiveReadinessProbe( + ReceiveReadinessProbeRequest.newBuilder() + .setSchemaVersion(1) + .setCoordinates(coordinates(invocation)) + .setCompactJwt(invocation.compactJwt()) + .build()); + acceptance = + authenticatedResponse(invocation, observation(response), peerTrust.authenticatedPeer()); + } else { + ReceiveAccountJwtReadinessProbeResponse response = + AccountJwtReadinessPodReceiverServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .receiveReadinessProbe( + ReceiveAccountJwtReadinessProbeRequest.newBuilder() + .setSchemaVersion(1) + .setCoordinates(coordinates(invocation)) + .setCompactJwt(invocation.compactJwt()) + .build()); + acceptance = + authenticatedResponse(invocation, observation(response), peerTrust.authenticatedPeer()); + } + } finally { + channel.shutdownNow(); + try { + if (!channel.awaitTermination(SHUTDOWN_DEADLINE_SECONDS, TimeUnit.SECONDS)) { + throw new ReceiverUnavailableException(); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new ReceiverUnavailableException(); + } + } + + return acceptance; + } + + private AuthenticatedAcceptance authenticatedResponse( + Invocation invocation, + ReceiverObservation response, + AccountJwtReadinessPodTrustManager.AuthenticatedPeer peer) { + if (response.schemaVersion() != 1 + || response.unknownFields() + || !coordinates(invocation).equals(response.coordinates()) + || !invocation.compactTokenSha256().equals(response.compactTokenSha256()) + || !invocation.targetKid().equals(response.verifiedKeyId()) + || !response.hasReceiverIdentity() + || !targetBinding(invocation.target()).equals(response.accountPodTarget()) + || response.targetUnknownFields()) { + throw new ReceiverUnavailableException(); + } + + ProbeExpectation result = response.outcome(); + if (result != invocation.expectation()) { + throw new ReceiverUnavailableException(); + } + + if (response.identityUnknownFields() + || !invocation.validatorId().equals(response.validatorId()) + || !invocation.target().deploymentUid().equals(response.deploymentUid()) + || !invocation.target().podUid().equals(response.podUid()) + || !invocation.target().podIp().equals(response.podIp()) + || !invocation + .target() + .exactPodEndpoint() + .orElseThrow() + .toString() + .equals(response.directPodEndpoint()) + || !peer.serviceUri().equals(response.canonicalServiceUri()) + || !invocation.target().image().equals(response.image()) + || !invocation.target().verifierConfigSha256().equals(response.verifierConfigSha256()) + || !invocation + .target() + .applicabilityMatrixDigest() + .equals(response.applicabilityMatrixDigest()) + || !peer.spkiSha256().equals(response.serverLeafSpkiSha256()) + || !isCanonicalRevision(response.sourceInventoryRevision()) + || !isSha256(response.sourceInventoryDigest()) + || response.accountJwksSourceIdentity().isEmpty() + || !sourceIdentityMatchesTarget( + response.accountJwksSourceIdentity().orElseThrow(), invocation.target()) + || !response.trustBindingRevisionValid()) { + throw new ReceiverUnavailableException(); + } + + long observedAt = response.observedAtEpochSeconds(); + if (observedAt < invocation.issuedAtEpochSecond() + || observedAt > invocation.expiresAtEpochSecond() + || clock.instant().getEpochSecond() > invocation.expiresAtEpochSecond()) { + throw new ReceiverUnavailableException(); + } + + // The acceptance uses inventory values plus the actual handshake peer, never response echoes + // for the peer SAN/SPKI. The receiver's local inventory remains receiver-owned evidence. + return authenticatedAcceptance( + invocation.target().podUid(), + invocation.target().exactPodEndpoint().orElseThrow().toString(), + invocation.target().image(), + invocation.target().verifierConfigSha256(), + peer.serviceUri(), + peer.spkiSha256(), + invocation.jti(), + invocation.compactTokenSha256(), + response.verifiedKeyId(), + result, + observedAt); + } + + private static ReceiverObservation observation(ReceiveReadinessProbeResponse response) { + var identity = response.getReceiverIdentity(); + return new ReceiverObservation( + response.getSchemaVersion(), + !response.getUnknownFields().asMap().isEmpty() + || !response.getCoordinates().getUnknownFields().asMap().isEmpty(), + response.getCoordinates(), + response.getCompactTokenSha256(), + response.getVerifiedKeyId(), + response.hasReceiverIdentity(), + !identity.getUnknownFields().asMap().isEmpty() + || !identity.getAccountJwksSourceIdentity().getUnknownFields().asMap().isEmpty(), + identity.getValidatorId(), + identity.getDeploymentUid(), + identity.getPodUid(), + identity.getPodIp(), + identity.getDirectPodEndpoint(), + identity.getCanonicalServiceUri(), + identity.getImage(), + identity.getVerifierConfigSha256(), + identity.getApplicabilityMatrixDigest(), + identity.getSourceInventoryRevision(), + identity.getSourceInventoryDigest(), + identity.getServerLeafSpkiSha256(), + accountSourceIdentity(identity.getAccountJwksSourceIdentity()), + identity.getAccountJwksTrustConfigRevision() > 0L, + response.hasAccountPodTarget() + ? response.getAccountPodTarget() + : AccountPodTargetBinding.getDefaultInstance(), + !response.getAccountPodTarget().getUnknownFields().asMap().isEmpty(), + outcome(response.getOutcome()), + response.getObservedAtEpochSeconds()); + } + + private static ReceiverObservation observation(ReceiveAccountJwtReadinessProbeResponse response) { + AccountJwtPodReceiverIdentity identity = response.getReceiverIdentity(); + return new ReceiverObservation( + response.getSchemaVersion(), + !response.getUnknownFields().asMap().isEmpty() + || !response.getCoordinates().getUnknownFields().asMap().isEmpty(), + response.getCoordinates(), + response.getCompactTokenSha256(), + response.getVerifiedKeyId(), + response.hasReceiverIdentity(), + !identity.getUnknownFields().asMap().isEmpty() + || !identity.getAccountJwksSourceIdentity().getUnknownFields().asMap().isEmpty(), + identity.getValidatorId(), + identity.getDeploymentUid(), + identity.getPodUid(), + identity.getPodIp(), + identity.getDirectPodEndpoint(), + identity.getCanonicalServiceUri(), + identity.getImage(), + identity.getVerifierConfigSha256(), + identity.getApplicabilityMatrixDigest(), + identity.getSourceInventoryRevision(), + identity.getSourceInventoryDigest(), + identity.getServerLeafSpkiSha256(), + accountSourceIdentity(identity.getAccountJwksSourceIdentity()), + isCanonicalRevision(identity.getJwksTrustBindingRevision()), + response.hasAccountPodTarget() + ? response.getAccountPodTarget() + : AccountPodTargetBinding.getDefaultInstance(), + !response.getAccountPodTarget().getUnknownFields().asMap().isEmpty(), + outcome(response.getOutcome()), + response.getObservedAtEpochSeconds()); + } + + private static ProbeExpectation outcome( + ReceiveReadinessProbeResponse.ObservationOutcome outcome) { + return switch (outcome) { + case VERIFIED -> ProbeExpectation.ACCEPT; + case INAPPLICABLE_REJECT -> ProbeExpectation.INAPPLICABLE_REJECT; + default -> throw new ReceiverUnavailableException(); + }; + } + + private static ProbeExpectation outcome( + ReceiveAccountJwtReadinessProbeResponse.ObservationOutcome outcome) { + return switch (outcome) { + case VERIFIED -> ProbeExpectation.ACCEPT; + case INAPPLICABLE_REJECT -> ProbeExpectation.INAPPLICABLE_REJECT; + default -> throw new ReceiverUnavailableException(); + }; + } + + private SslBundle configuredBundle() { + try { + return Objects.requireNonNull(sslBundles.getBundle(TLS_BUNDLE_NAME)); + } catch (RuntimeException failure) { + throw new ReceiverUnavailableException(); + } + } + + private static X509TrustManager x509TrustManager(TrustManagerFactory factory) { + return Arrays.stream(factory.getTrustManagers()) + .filter(X509TrustManager.class::isInstance) + .map(X509TrustManager.class::cast) + .findFirst() + .orElseThrow(ReceiverUnavailableException::new); + } + + private static ReadinessProbeCoordinates coordinates(Invocation invocation) { + ReadinessProbeCoordinates.Builder coordinates = + ReadinessProbeCoordinates.newBuilder() + .setRotationOperationId(invocation.rotationOperationId().toString()) + .setOperationDigest(invocation.operationDigest()) + .setPlanDigest(invocation.planDigest()) + .setPlanVersion(invocation.planVersion()) + .setRegistryVersion(invocation.registryVersion()) + .setValidatorId(invocation.validatorId()) + .setTokenProfile(invocation.tokenProfile()) + .setAudience(invocation.audience()) + .setProbeKind( + invocation.probeKind() == ProbeKind.CANARY + ? ReadinessProbeCoordinates.ProbeKind.CANARY + : ReadinessProbeCoordinates.ProbeKind.REPRESENTATIVE) + .setExpectedOutcome( + invocation.expectation() == ProbeExpectation.ACCEPT + ? ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT + : ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT) + .setJti(invocation.jti().toString()) + .setEntryVersion(invocation.sourceEntryVersion()) + .setTargetGeneration(invocation.targetGeneration()) + .setTargetKid(invocation.targetKid()) + .setIssuedAtEpochSeconds(invocation.issuedAtEpochSecond()) + .setExpiresAtEpochSeconds(invocation.expiresAtEpochSecond()) + .setPlanExpiresAtEpochSeconds(invocation.planExpiresAtEpochSecond()); + if (invocation.expectedActiveGeneration().isPresent()) { + coordinates + .setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.PRESENT) + .setExpectedActiveGeneration(invocation.expectedActiveGeneration().orElseThrow()) + .setExpectedActiveKid(invocation.expectedActiveKid().orElseThrow()); + } else { + coordinates.setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.ABSENT); + } + return coordinates.build(); + } + + private static AccountPodTargetBinding targetBinding(PodTarget target) { + return AccountPodTargetBinding.newBuilder() + .setInventorySnapshotDigest(target.inventorySnapshotDigest()) + .setEnvironmentId(target.environmentId()) + .setClusterId(target.clusterId()) + .setClusterIncarnationUid(target.clusterIncarnationUid()) + .setNamespace(target.namespace()) + .setNamespaceUid(target.namespaceUid()) + .setApiBindingRevision(target.apiBindingRevision()) + .setApiBindingDigest(target.apiBindingDigest()) + .setInventoryBindingRevision(target.inventoryBindingRevision()) + .setInventoryBindingDigest(target.inventoryBindingDigest()) + .setValidatorId(target.validatorId()) + .setDeploymentUid(target.deploymentUid()) + .setPodUid(target.podUid()) + .setPodIp(target.podIp()) + .setImage(target.image()) + .setVerifierConfigSha256(target.verifierConfigSha256()) + .setApplicabilityMatrixDigest(target.applicabilityMatrixDigest()) + .setExpectedOutcome( + target.expectation() == ProbeExpectation.ACCEPT + ? ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT + : ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT) + .setDirectPodEndpoint(target.exactPodEndpoint().orElseThrow().toString()) + .setCanonicalServiceUri(target.canonicalServiceUri().orElseThrow()) + .setServerLeafSpkiSha256(target.podLeafSpkiSha256().orElseThrow()) + .build(); + } + + private static Optional accountSourceIdentity( + net.firedevops.firemud.account.v1.AccountSourceIdentity identity) { + try { + return Optional.of( + new SourceIdentity( + identity.getEnvironmentId(), + identity.getClusterId(), + identity.getClusterIncarnationUid(), + identity.getNamespace(), + identity.getNamespaceUid(), + identity.getConfigMapUid(), + identity.getBindingRevision(), + identity.getApiServerOrigin(), + identity.getServingCaSha256())); + } catch (IllegalArgumentException failure) { + return Optional.empty(); + } + } + + static boolean sourceIdentityMatchesTarget(SourceIdentity source, PodTarget target) { + return source.environmentId().equals(target.environmentId()) + && source.clusterId().equals(target.clusterId()) + && source.clusterIncarnationUid().equals(target.clusterIncarnationUid()) + && source.namespace().equals(target.namespace()) + && source.namespaceUid().equals(target.namespaceUid()); + } + + private static boolean isSha256(String value) { + return value != null && value.matches("[0-9a-f]{64}"); + } + + private static boolean isCanonicalRevision(String value) { + return value != null && value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + } + + private static String serviceUri(String namespace, String serviceAccount) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + serviceAccount; + } + + private static InetAddress numericPodAddress(String value) { + try { + if (!AccountJwtValidatorInventoryBinding.canonicalPodIp(value).equals(value)) { + throw new ReceiverUnavailableException(); + } + if (value.indexOf(':') >= 0) { + InetAddress address = InetAddress.getByName(value); + if (!(address instanceof Inet6Address)) { + throw new ReceiverUnavailableException(); + } + return address; + } + String[] octets = value.split("\\.", -1); + byte[] address = new byte[4]; + for (int index = 0; index < address.length; index++) { + address[index] = (byte) Integer.parseInt(octets[index]); + } + return InetAddress.getByAddress(address); + } catch (UnknownHostException failure) { + throw new ReceiverUnavailableException(); + } catch (RuntimeException failure) { + throw new ReceiverUnavailableException(); + } + } + + private record ReceiverObservation( + int schemaVersion, + boolean unknownFields, + ReadinessProbeCoordinates coordinates, + String compactTokenSha256, + String verifiedKeyId, + boolean hasReceiverIdentity, + boolean identityUnknownFields, + String validatorId, + String deploymentUid, + String podUid, + String podIp, + String directPodEndpoint, + String canonicalServiceUri, + String image, + String verifierConfigSha256, + String applicabilityMatrixDigest, + String sourceInventoryRevision, + String sourceInventoryDigest, + String serverLeafSpkiSha256, + Optional accountJwksSourceIdentity, + boolean trustBindingRevisionValid, + AccountPodTargetBinding accountPodTarget, + boolean targetUnknownFields, + ProbeExpectation outcome, + long observedAtEpochSeconds) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java new file mode 100644 index 0000000000..c69a0615db --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java @@ -0,0 +1,275 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.account.v1.AccountJwtPodReceiverIdentity; +import net.firedevops.firemud.account.v1.AccountSourceIdentity; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerSelector.LocalIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; + +/** + * Derives the local Account Pod identity only from protected live inventory, the active server + * certificate, and Account's protected JWKS source. No receiver-request identity is accepted. + */ +public final class AccountJwtReadinessPodLocalIdentityProvider { + private static final String ACCOUNT_VALIDATOR_ID = AccountJwtReadinessProbeCrypto.VALIDATOR_ID; + private static final String TLS_BUNDLE_NAME = "firemud-grpc"; + + private final AccountJwtValidatorInventorySource inventorySource; + private final AccountJwtJwksTrustedSource trustedJwksSource; + private final SslBundles sslBundles; + private final Clock clock; + private final String localPodName; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Spring-managed SslBundles is retained for live server-certificate reads.") + public AccountJwtReadinessPodLocalIdentityProvider( + AccountJwtValidatorInventorySource inventorySource, + AccountJwtJwksTrustedSource trustedJwksSource, + SslBundles sslBundles, + Clock clock, + String localPodName) { + this.inventorySource = Objects.requireNonNull(inventorySource); + this.trustedJwksSource = Objects.requireNonNull(trustedJwksSource); + this.sslBundles = Objects.requireNonNull(sslBundles); + this.clock = Objects.requireNonNull(clock); + this.localPodName = localPodName == null ? "" : localPodName.trim(); + } + + /** Re-reads every protected identity source and requires the actual local TLS leaf to match. */ + public LocalObservation observe(String applicabilityMatrixDigest) { + return observe(applicabilityMatrixDigest, null); + } + + /** + * Re-reads protected identity using only the current Account-owner-selected operation context. + */ + public LocalObservation observe( + String applicabilityMatrixDigest, ObservationContext observationContext) { + try { + InventorySnapshot inventory = + observationContext == null + ? inventorySource.observe() + : inventorySource.observe(observationContext); + ValidatorObservation validator = exactAccountValidator(inventory); + PodObservation pod = exactLocalPod(validator, inventory.namespace()); + SourceIdentity jwksSourceIdentity = readCurrentJwksSourceIdentity(); + requireSameAccountCluster(inventory, jwksSourceIdentity); + String actualLeafSpki = localServerLeafSpki(sslBundles, clock, pod.receiverServiceUri()); + if (!actualLeafSpki.equals(pod.leafSpkiSha256())) { + throw new IdentityUnavailableException(); + } + + LocalIdentity selectorIdentity = + new LocalIdentity( + validator.validatorId(), + validator.deploymentUid(), + pod.uid(), + pod.podIp(), + pod.endpoint().toString(), + pod.receiverServiceUri(), + pod.image(), + pod.verifierConfigSha256(), + applicabilityMatrixDigest, + inventory.inventoryBindingRevision(), + inventory.digest(), + actualLeafSpki); + AccountJwtPodReceiverIdentity wireIdentity = + AccountJwtPodReceiverIdentity.newBuilder() + .setValidatorId(validator.validatorId()) + .setDeploymentUid(validator.deploymentUid()) + .setPodUid(pod.uid()) + .setPodIp(pod.podIp()) + .setDirectPodEndpoint(pod.endpoint().toString()) + .setCanonicalServiceUri(pod.receiverServiceUri()) + .setImage(pod.image()) + .setVerifierConfigSha256(pod.verifierConfigSha256()) + .setApplicabilityMatrixDigest(applicabilityMatrixDigest) + .setSourceInventoryRevision(inventory.inventoryBindingRevision()) + .setSourceInventoryDigest(inventory.digest()) + .setServerLeafSpkiSha256(actualLeafSpki) + .setAccountJwksSourceIdentity(toProto(jwksSourceIdentity)) + .setJwksTrustBindingRevision(jwksSourceIdentity.bindingRevision()) + .build(); + return new LocalObservation(selectorIdentity, wireIdentity); + } catch (IdentityUnavailableException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw new IdentityUnavailableException(); + } + } + + private SourceIdentity readCurrentJwksSourceIdentity() { + PublicJwksSnapshot snapshot = trustedJwksSource.load(); + if (snapshot == null) { + throw new IdentityUnavailableException(); + } + byte[] bytes = snapshot.jwksBytes(); + if (bytes == null) { + throw new IdentityUnavailableException(); + } + try { + if (bytes.length == 0 || bytes.length > 256 * 1024) { + throw new IdentityUnavailableException(); + } + return snapshot.sourceIdentity(); + } finally { + java.util.Arrays.fill(bytes, (byte) 0); + } + } + + private ValidatorObservation exactAccountValidator(InventorySnapshot inventory) { + List matches = + inventory.validators().stream() + .filter(value -> ACCOUNT_VALIDATOR_ID.equals(value.validatorId())) + .toList(); + if (matches.size() != 1) { + throw new IdentityUnavailableException(); + } + ValidatorObservation validator = matches.getFirst(); + Set expectedProfiles = + AccountJwtReadinessProbeCrypto.representativeProfiles().values().stream() + .map(value -> new ProfileExpectation(value.profile(), value.audience())) + .collect(java.util.stream.Collectors.toUnmodifiableSet()); + if (!Set.copyOf(validator.profiles()).equals(expectedProfiles)) { + throw new IdentityUnavailableException(); + } + return validator; + } + + private PodObservation exactLocalPod(ValidatorObservation validator, String namespace) { + if (localPodName.isBlank()) { + throw new IdentityUnavailableException(); + } + List matches = + validator.pods().stream().filter(value -> localPodName.equals(value.name())).toList(); + if (matches.size() != 1) { + throw new IdentityUnavailableException(); + } + PodObservation pod = matches.getFirst(); + if (!validator.deploymentUid().equals(pod.ownerUid()) + || !validator.deploymentName().equals(pod.ownerName()) + || !validator.image().equals(pod.image()) + || !validator.verifierConfigSha256().equals(pod.verifierConfigSha256())) { + throw new IdentityUnavailableException(); + } + validateServiceIdentity(pod.receiverServiceUri(), namespace, validator); + return pod; + } + + private static void validateServiceIdentity( + String uri, String namespace, ValidatorObservation validator) { + if (uri == null + || !uri.equals("spiffe://firemud/ns/" + namespace + "/sa/" + ACCOUNT_VALIDATOR_ID) + || !uri.matches( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/account-service") + || !validator.validatorId().equals(ACCOUNT_VALIDATOR_ID)) { + throw new IdentityUnavailableException(); + } + } + + private static void requireSameAccountCluster( + InventorySnapshot inventory, SourceIdentity source) { + if (!inventory.environmentId().equals(source.environmentId()) + || !inventory.clusterId().equals(source.clusterId()) + || !inventory.clusterIncarnationUid().equals(source.clusterIncarnationUid()) + || !inventory.namespace().equals(source.namespace()) + || !inventory.namespaceUid().equals(source.namespaceUid())) { + throw new IdentityUnavailableException(); + } + } + + private static String localServerLeafSpki( + SslBundles sslBundles, Clock clock, String expectedServiceUri) { + try { + SslBundle bundle = Objects.requireNonNull(sslBundles.getBundle(TLS_BUNDLE_NAME)); + KeyStore keyStore = Objects.requireNonNull(bundle.getStores().getKeyStore()); + List leaves = new ArrayList<>(); + var aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (!keyStore.isKeyEntry(alias)) { + continue; + } + Certificate certificate = keyStore.getCertificate(alias); + if (!(certificate instanceof X509Certificate x509)) { + throw new IdentityUnavailableException(); + } + leaves.add(x509); + } + if (leaves.size() != 1) { + throw new IdentityUnavailableException(); + } + X509Certificate leaf = leaves.getFirst(); + leaf.checkValidity(java.util.Date.from(clock.instant())); + GrpcPeerIdentity peer = + GrpcPeerIdentity.fromCertificate(leaf).orElseThrow(IdentityUnavailableException::new); + if (!expectedServiceUri.equals(peer.uri())) { + throw new IdentityUnavailableException(); + } + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(leaf.getPublicKey().getEncoded())); + } catch (IdentityUnavailableException failure) { + throw failure; + } catch (Exception unavailable) { + throw new IdentityUnavailableException(); + } + } + + private static AccountSourceIdentity toProto(SourceIdentity source) { + return AccountSourceIdentity.newBuilder() + .setEnvironmentId(source.environmentId()) + .setClusterId(source.clusterId()) + .setClusterIncarnationUid(source.clusterIncarnationUid()) + .setNamespace(source.namespace()) + .setNamespaceUid(source.namespaceUid()) + .setConfigMapUid(source.configMapUid()) + .setBindingRevision(source.bindingRevision()) + .setApiServerOrigin(source.apiServerOrigin()) + .setServingCaSha256(source.servingCaSha256()) + .build(); + } + + public record LocalObservation( + LocalIdentity selectorIdentity, AccountJwtPodReceiverIdentity wireIdentity) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "AccountJwtPodReceiverIdentity is an immutable generated protobuf value.") + public LocalObservation { + Objects.requireNonNull(selectorIdentity); + Objects.requireNonNull(wireIdentity); + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "AccountJwtPodReceiverIdentity is an immutable generated protobuf value.") + public AccountJwtPodReceiverIdentity wireIdentity() { + return wireIdentity; + } + } + + public static final class IdentityUnavailableException extends RuntimeException { + public IdentityUnavailableException() { + super("Protected Account Pod receiver identity is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverEngine.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverEngine.java new file mode 100644 index 0000000000..d3c906ab96 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverEngine.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Clock; +import java.util.Objects; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeRequest; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPodReceiverWorkloadGuard; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPodReceiverWorkloadGuard.AuthenticatedCaller; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.OwnerProbeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessPodLocalIdentityProvider.LocalObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessPodReceiverProtoMapper.ParsedRequest; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** + * Account's actual per-Pod pending-key receiver. It verifies production JWT crypto and returns only + * an immutable non-authorizing observation; it never calls the V1 receipt-writing harness. + */ +public final class AccountJwtReadinessPodReceiverEngine { + private final AccountJwtReadinessProbeService probeService; + private final AccountJwtReadinessPodReceiverWorkloadGuard workloadGuard; + private final AccountJwtReadinessPodLocalIdentityProvider localIdentityProvider; + private final AccountJwtReadinessPodReceiverProtoMapper protoMapper; + private final AccountAsymmetricJwtVerifier verifier; + private final Clock clock; + private final int maxControlUiTenantScopes; + + public AccountJwtReadinessPodReceiverEngine( + AccountJwtReadinessProbeService probeService, + AccountJwtReadinessPodReceiverWorkloadGuard workloadGuard, + AccountJwtReadinessPodLocalIdentityProvider localIdentityProvider, + AccountJwtReadinessPodReceiverProtoMapper protoMapper, + AccountAsymmetricJwtVerifier verifier, + Clock clock, + int maxControlUiTenantScopes) { + this.probeService = Objects.requireNonNull(probeService); + this.workloadGuard = Objects.requireNonNull(workloadGuard); + this.localIdentityProvider = Objects.requireNonNull(localIdentityProvider); + this.protoMapper = Objects.requireNonNull(protoMapper); + this.verifier = Objects.requireNonNull(verifier); + this.clock = Objects.requireNonNull(clock); + if (maxControlUiTenantScopes <= 0 + || maxControlUiTenantScopes + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw new IllegalArgumentException("Account control-ui verifier scope bound is required"); + } + this.maxControlUiTenantScopes = maxControlUiTenantScopes; + } + + public ReceiveAccountJwtReadinessProbeResponse receiveReadinessProbe( + ReceiveAccountJwtReadinessProbeRequest request) { + AuthenticatedCaller caller = workloadGuard.requireAccountReceiverCaller(); + ParsedRequest parsed = protoMapper.parse(request); + Binding accountBinding = caller.accountBinding(); + TrustFence trustFence = AccountJwtReadinessValidationService.trustFence(accountBinding); + + // The persisted plan supplies the matrix digest; this is a read only and does not create or + // advance a plan, bootstrap state, a registry record, or any activation state. + ReadinessProbePlan currentPlan = + probeService.readCurrentPlan( + accountBinding.accountBinding(), trustFence, parsed.operationId()); + requirePlanCoordinates(parsed, currentPlan); + ObservationContext observationContext = + probeService.readCurrentInventoryObservationContext( + accountBinding.accountBinding(), trustFence, parsed.operationId()); + + LocalObservation localBefore = + localIdentityProvider.observe(currentPlan.applicabilityMatrixDigest(), observationContext); + var selector = protoMapper.toOwnerSelector(parsed, localBefore.selectorIdentity()); + OwnerProbeEvidence ownerBefore = + probeService.readCurrentProbeOwner( + accountBinding.accountBinding(), trustFence, selector, accountBinding.namespace()); + + // All Account profiles are applicable. Unsupported or mismatched audience/profile pairs are + // rejected by the closed request mapper and production verifier; none becomes typed success. + VerifiedClaims verified = + AccountJwtReadinessProbeCrypto.verify( + verifier, + parsed.compactJwt(), + AccountJwtReadinessProbeCrypto.expectedProbe( + selector.probeKind(), + selector.tokenProfile(), + selector.audience(), + selector.jti().toString(), + ownerBefore.entry().targetKid(), + ownerBefore.entry().plannedIssuedAtEpochSecond(), + ownerBefore.entry().expiresAtEpochSecond()), + maxControlUiTenantScopes); + + LocalObservation localAfter = + localIdentityProvider.observe(currentPlan.applicabilityMatrixDigest(), observationContext); + if (!localBefore.equals(localAfter)) { + throw new ReceiverUnavailableException(); + } + OwnerProbeEvidence ownerAfter = + probeService.readCurrentProbeOwner( + accountBinding.accountBinding(), trustFence, selector, accountBinding.namespace()); + if (!ownerBefore.equals(ownerAfter)) { + throw new ReceiverUnavailableException(); + } + workloadGuard.requireUnchanged(caller); + + long observedAt = nowEpochSecond(); + if (observedAt < ownerAfter.entry().plannedIssuedAtEpochSecond() + || observedAt >= ownerAfter.entry().expiresAtEpochSecond() + || !ownerAfter.entry().targetKid().equals(verified.keyId())) { + throw new ReceiverUnavailableException(); + } + return protoMapper.toResponse(parsed, verified.keyId(), localAfter, ownerAfter, observedAt); + } + + private static void requirePlanCoordinates(ParsedRequest request, ReadinessProbePlan plan) { + var coordinates = request.coordinates(); + if (plan == null + || !plan.operationId().equals(request.operationId()) + || !plan.operationDigest().equals(coordinates.getOperationDigest()) + || !plan.planDigest().equals(coordinates.getPlanDigest()) + || plan.planVersion() != coordinates.getPlanVersion() + || plan.expiresAtEpochSecond() != coordinates.getPlanExpiresAtEpochSeconds() + || !plan.targetGeneration().equals(coordinates.getTargetGeneration()) + || !plan.targetKid().equals(coordinates.getTargetKid()) + || !plan.expectedFence().durableActive().equals(request.expectedActive()) + || !plan.expectedFence().publishedActive().equals(request.expectedActive()) + || !plan.validatorInventoryComplete()) { + throw new ReceiverUnavailableException(); + } + } + + private long nowEpochSecond() { + long value = clock.instant().getEpochSecond(); + if (value <= 0L) { + throw new ReceiverUnavailableException(); + } + return value; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverProtoMapper.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverProtoMapper.java new file mode 100644 index 0000000000..2eef69038a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverProtoMapper.java @@ -0,0 +1,253 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.AccountPodTargetBinding; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeRequest; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeResponse; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.OwnerProbeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerSelector.LocalIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.PodTarget; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; + +/** Strict closed-schema mapper for Account's separate production Pod receiver RPC. */ +public final class AccountJwtReadinessPodReceiverProtoMapper { + private static final int SCHEMA_VERSION = 1; + private static final int MAX_COMPACT_TOKEN_BYTES = 16 * 1024; + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + + public ParsedRequest parse(ReceiveAccountJwtReadinessProbeRequest request) { + if (request == null + || request.getSchemaVersion() != SCHEMA_VERSION + || !request.getUnknownFields().asMap().isEmpty() + || !request.hasCoordinates() + || request.getCompactJwt().isEmpty() + || request.getCompactJwt().length() > MAX_COMPACT_TOKEN_BYTES + || !isAscii(request.getCompactJwt())) { + throw new InvalidReceiverRequestException(); + } + ReadinessProbeCoordinates coordinates = request.getCoordinates(); + if (!coordinates.getUnknownFields().asMap().isEmpty()) { + throw new InvalidReceiverRequestException(); + } + try { + ProbeKind probeKind = + switch (coordinates.getProbeKind()) { + case CANARY -> ProbeKind.CANARY; + case REPRESENTATIVE -> ProbeKind.REPRESENTATIVE; + case PROBE_KIND_UNSPECIFIED, UNRECOGNIZED -> throw new IllegalArgumentException(); + }; + if (!AccountJwtReadinessProbeCrypto.VALIDATOR_ID.equals(coordinates.getValidatorId()) + || coordinates.getExpectedOutcome() != ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) { + throw new IllegalArgumentException(); + } + if (probeKind == ProbeKind.CANARY) { + if (!AccountJwtReadinessProbeCrypto.CANARY_PROFILE.equals(coordinates.getTokenProfile()) + || !AccountJwtReadinessProbeCrypto.CANARY_AUDIENCE.equals(coordinates.getAudience())) { + throw new IllegalArgumentException(); + } + } else { + AccountJwtReadinessProbeCrypto.ProfileDescriptor profile = + AccountJwtReadinessProbeCrypto.representativeProfile(coordinates.getTokenProfile()); + if (profile == null || !profile.audience().equals(coordinates.getAudience())) { + throw new IllegalArgumentException(); + } + } + Optional expectedActive = + switch (coordinates.getExpectedActiveState()) { + case ABSENT -> { + if (!coordinates.getExpectedActiveGeneration().isEmpty() + || !coordinates.getExpectedActiveKid().isEmpty()) { + throw new IllegalArgumentException(); + } + yield Optional.empty(); + } + case PRESENT -> { + if (coordinates.getExpectedActiveGeneration().isEmpty() + || coordinates.getExpectedActiveKid().isEmpty()) { + throw new IllegalArgumentException(); + } + yield Optional.of( + new ActiveSigner( + coordinates.getExpectedActiveGeneration(), + coordinates.getExpectedActiveKid())); + } + case EXPECTED_ACTIVE_STATE_UNSPECIFIED, UNKNOWN, UNRECOGNIZED -> + throw new IllegalArgumentException(); + }; + UUID operationId = canonicalUuid(coordinates.getRotationOperationId()); + UUID jti = canonicalUuid(coordinates.getJti()); + requireCoordinateBounds(coordinates); + byte[] compactBytes = request.getCompactJwt().getBytes(StandardCharsets.US_ASCII); + try { + return new ParsedRequest( + coordinates, + operationId, + jti, + probeKind, + expectedActive, + request.getCompactJwt(), + sha256(compactBytes)); + } finally { + java.util.Arrays.fill(compactBytes, (byte) 0); + } + } catch (RuntimeException invalid) { + throw new InvalidReceiverRequestException(); + } + } + + public AccountJwtReadinessProbeOwnerSelector toOwnerSelector( + ParsedRequest request, LocalIdentity localIdentity) { + ReadinessProbeCoordinates coordinates = request.coordinates(); + return new AccountJwtReadinessProbeOwnerSelector( + request.operationId(), + coordinates.getOperationDigest(), + coordinates.getPlanDigest(), + coordinates.getPlanVersion(), + coordinates.getRegistryVersion(), + coordinates.getValidatorId(), + coordinates.getTokenProfile(), + coordinates.getAudience(), + request.probeKind(), + ProbeExpectation.ACCEPT, + request.jti(), + coordinates.getEntryVersion(), + coordinates.getTargetGeneration(), + coordinates.getTargetKid(), + request.expectedActive(), + coordinates.getIssuedAtEpochSeconds(), + coordinates.getExpiresAtEpochSeconds(), + coordinates.getPlanExpiresAtEpochSeconds(), + request.compactTokenSha256(), + localIdentity); + } + + public ReceiveAccountJwtReadinessProbeResponse toResponse( + ParsedRequest request, + String verifiedKeyId, + AccountJwtReadinessPodLocalIdentityProvider.LocalObservation local, + OwnerProbeEvidence owner, + long observedAtEpochSeconds) { + return ReceiveAccountJwtReadinessProbeResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setCoordinates(request.coordinates()) + .setCompactTokenSha256(request.compactTokenSha256()) + .setVerifiedKeyId(verifiedKeyId) + .setReceiverIdentity(local.wireIdentity()) + .setAccountPodTarget(toTarget(owner)) + .setObservedAtEpochSeconds(observedAtEpochSeconds) + .setOutcome(ReceiveAccountJwtReadinessProbeResponse.ObservationOutcome.VERIFIED) + .build(); + } + + private static AccountPodTargetBinding toTarget(OwnerProbeEvidence owner) { + PodTarget target = owner.expectedPod().target(); + return AccountPodTargetBinding.newBuilder() + .setInventorySnapshotDigest(target.inventorySnapshotDigest()) + .setEnvironmentId(target.environmentId()) + .setClusterId(target.clusterId()) + .setClusterIncarnationUid(target.clusterIncarnationUid()) + .setNamespace(target.namespace()) + .setNamespaceUid(target.namespaceUid()) + .setApiBindingRevision(target.apiBindingRevision()) + .setApiBindingDigest(target.apiBindingDigest()) + .setInventoryBindingRevision(target.inventoryBindingRevision()) + .setInventoryBindingDigest(target.inventoryBindingDigest()) + .setValidatorId(target.validatorId()) + .setDeploymentUid(target.deploymentUid()) + .setPodUid(target.podUid()) + .setPodIp(target.podIp()) + .setImage(target.image()) + .setVerifierConfigSha256(target.verifierConfigSha256()) + .setApplicabilityMatrixDigest(target.applicabilityMatrixDigest()) + .setExpectedOutcome( + target.expectation() == ProbeExpectation.ACCEPT + ? ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT + : ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT) + .setDirectPodEndpoint(target.exactPodEndpoint().orElseThrow().toString()) + .setCanonicalServiceUri(target.canonicalServiceUri().orElseThrow()) + .setServerLeafSpkiSha256(target.podLeafSpkiSha256().orElseThrow()) + .build(); + } + + private static UUID canonicalUuid(String value) { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value) || uuid.version() != 4 || uuid.variant() != 2) { + throw new IllegalArgumentException(); + } + return uuid; + } + + private static void requireCoordinateBounds(ReadinessProbeCoordinates coordinates) { + if (!DIGEST.matcher(coordinates.getOperationDigest()).matches() + || !DIGEST.matcher(coordinates.getPlanDigest()).matches() + || coordinates.getPlanVersion() != AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION + || coordinates.getRegistryVersion() != 1 + || coordinates.getEntryVersion() <= 0L + || !GENERATION.matcher(coordinates.getTargetGeneration()).matches() + || !KID.matcher(coordinates.getTargetKid()).matches() + || coordinates.getIssuedAtEpochSeconds() <= 0L + || coordinates.getExpiresAtEpochSeconds() <= coordinates.getIssuedAtEpochSeconds() + || coordinates.getExpiresAtEpochSeconds() - coordinates.getIssuedAtEpochSeconds() + > AccountJwtReadinessProbeRepository.PROBE_LIFETIME_SECONDS + || coordinates.getPlanExpiresAtEpochSeconds() <= 0L + || coordinates.getExpiresAtEpochSeconds() > coordinates.getPlanExpiresAtEpochSeconds()) { + throw new IllegalArgumentException(); + } + } + + private static boolean isAscii(String value) { + for (int index = 0; index < value.length(); index++) { + if (value.charAt(index) > 0x7f) { + return false; + } + } + return true; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception unavailable) { + throw new InvalidReceiverRequestException(); + } + } + + public record ParsedRequest( + ReadinessProbeCoordinates coordinates, + UUID operationId, + UUID jti, + ProbeKind probeKind, + Optional expectedActive, + String compactJwt, + String compactTokenSha256) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "ReadinessProbeCoordinates is an immutable generated protobuf value.") + public ParsedRequest {} + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "ReadinessProbeCoordinates is an immutable generated protobuf value.") + public ReadinessProbeCoordinates coordinates() { + return coordinates; + } + } + + public static final class InvalidReceiverRequestException extends IllegalArgumentException { + public InvalidReceiverRequestException() { + super("Account Pod readiness receiver request is invalid"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodTrustManager.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodTrustManager.java new file mode 100644 index 0000000000..0beef0ab8f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodTrustManager.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.net.Socket; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.HexFormat; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.X509ExtendedTrustManager; +import javax.net.ssl.X509TrustManager; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Adds an exact per-Pod URI-SAN and leaf-SPKI pin to Account's normal TLS trust decision. */ +final class AccountJwtReadinessPodTrustManager extends X509ExtendedTrustManager { + private final X509TrustManager delegate; + private final String expectedServiceUri; + private final String expectedSpkiSha256; + private final AtomicReference authenticatedPeer = new AtomicReference<>(); + + AccountJwtReadinessPodTrustManager( + X509TrustManager delegate, String expectedServiceUri, String expectedSpkiSha256) { + this.delegate = Objects.requireNonNull(delegate); + this.expectedServiceUri = Objects.requireNonNull(expectedServiceUri); + if (expectedSpkiSha256 == null || !expectedSpkiSha256.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Expected Pod leaf SPKI digest is invalid"); + } + GrpcPeerIdentity.parseUri(expectedServiceUri) + .filter(peer -> peer.uri().equals(expectedServiceUri)) + .orElseThrow(() -> new IllegalArgumentException("Expected Pod service URI is invalid")); + this.expectedSpkiSha256 = expectedSpkiSha256; + } + + AuthenticatedPeer authenticatedPeer() { + AuthenticatedPeer peer = authenticatedPeer.get(); + if (peer == null) { + throw new SecurityException("The pinned Pod TLS handshake did not complete"); + } + return peer; + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + delegate.checkClientTrusted(chain, authType); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + delegate.checkServerTrusted(chain, authType); + authenticateServerLeaf(chain); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) + throws CertificateException { + if (delegate instanceof X509ExtendedTrustManager extended) { + extended.checkClientTrusted(chain, authType, socket); + } else { + delegate.checkClientTrusted(chain, authType); + } + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) + throws CertificateException { + if (delegate instanceof X509ExtendedTrustManager extended) { + extended.checkServerTrusted(chain, authType, socket); + } else { + delegate.checkServerTrusted(chain, authType); + } + authenticateServerLeaf(chain); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) + throws CertificateException { + if (delegate instanceof X509ExtendedTrustManager extended) { + extended.checkClientTrusted(chain, authType, engine); + } else { + delegate.checkClientTrusted(chain, authType); + } + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) + throws CertificateException { + if (delegate instanceof X509ExtendedTrustManager extended) { + extended.checkServerTrusted(chain, authType, engine); + } else { + delegate.checkServerTrusted(chain, authType); + } + authenticateServerLeaf(chain); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + X509Certificate[] issuers = delegate.getAcceptedIssuers(); + return issuers == null ? new X509Certificate[0] : issuers.clone(); + } + + private void authenticateServerLeaf(X509Certificate[] chain) throws CertificateException { + if (chain == null || chain.length == 0 || chain[0] == null) { + throw new CertificateException("Pod TLS peer did not present a leaf certificate"); + } + X509Certificate leaf = chain[0]; + GrpcPeerIdentity identity = + GrpcPeerIdentity.fromCertificate(leaf) + .orElseThrow(() -> new CertificateException("Pod TLS peer URI SAN is invalid")); + if (!expectedServiceUri.equals(identity.uri())) { + throw new CertificateException("Pod TLS peer URI SAN differs from the exact target"); + } + final String spkiSha256; + try { + spkiSha256 = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(leaf.getPublicKey().getEncoded())); + } catch (NoSuchAlgorithmException exception) { + throw new CertificateException("SHA-256 is unavailable for Pod TLS peer pinning", exception); + } + if (!expectedSpkiSha256.equals(spkiSha256)) { + throw new CertificateException("Pod TLS peer SPKI differs from the exact target"); + } + authenticatedPeer.set(new AuthenticatedPeer(identity.uri(), spkiSha256)); + } + + record AuthenticatedPeer(String serviceUri, String spkiSha256) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeCrypto.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeCrypto.java new file mode 100644 index 0000000000..a9b70ba42f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeCrypto.java @@ -0,0 +1,279 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.math.BigDecimal; +import java.time.Clock; +import java.time.Duration; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; + +/** Shared pure policy and claim checks for Account's readiness probes. */ +public final class AccountJwtReadinessProbeCrypto { + static final String RESERVED_SUBJECT = "00000000-0000-4000-8000-000000000001"; + static final String ISSUER = "firemud-account-service"; + static final String CANARY_PROFILE = "account-jwt-readiness-canary"; + static final String CANARY_TYPE = "account_jwt_readiness_canary"; + static final String CANARY_AUDIENCE = "firemud-account-jwt-readiness"; + static final String VALIDATOR_ID = "account-service"; + + private static final int MAX_COMPACT_TOKEN_BYTES = 16 * 1024; + private static final long MAX_TOKEN_LIFETIME_SECONDS = 300L; + private static final long CLOCK_SKEW_SECONDS = 5L; + private static final Set CANARY_CLAIMS = + Set.of("iss", "sub", "jti", "aud", "iat", "nbf", "exp", "tokenProfile", "tokenType"); + private static final Set INITIAL_AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Map REPRESENTATIVE_PROFILES = + Map.of( + ControlUiJwtProfileValidator.PROFILE, + new ProfileDescriptor( + ControlUiJwtProfileValidator.PROFILE, + ControlUiJwtProfileValidator.AUDIENCE, + ControlUiJwtProfileValidator.TOKEN_TYPE, + ControlUiJwtProfileValidator.REQUIRED_CLAIMS, + ControlUiJwtProfileValidator.OPTIONAL_CLAIMS), + PlayerBootstrapJwtProfileValidator.PROFILE, + new ProfileDescriptor( + PlayerBootstrapJwtProfileValidator.PROFILE, + PlayerBootstrapJwtProfileValidator.AUDIENCE, + PlayerBootstrapJwtProfileValidator.TOKEN_TYPE, + PlayerBootstrapJwtProfileValidator.REQUIRED_CLAIMS, + PlayerBootstrapJwtProfileValidator.OPTIONAL_CLAIMS), + GameSessionAccountDelegationProfile.PROFILE, + new ProfileDescriptor( + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.AUDIENCE, + GameSessionAccountDelegationProfile.TYPE, + GameSessionAccountDelegationJwtProfileValidator.REQUIRED_CLAIMS, + GameSessionAccountDelegationJwtProfileValidator.OPTIONAL_CLAIMS)); + + private AccountJwtReadinessProbeCrypto() {} + + static Map representativeProfiles() { + return REPRESENTATIVE_PROFILES; + } + + static ProfileDescriptor representativeProfile(String profile) { + return REPRESENTATIVE_PROFILES.get(profile); + } + + static ExplicitRouteProfilePolicy policy( + ProbeKind kind, String profile, int maxControlUiTenantScopes) { + if (kind == ProbeKind.CANARY) { + return new ExplicitRouteProfilePolicy( + "account-jwt-readiness-canary", + CANARY_PROFILE, + CANARY_TYPE, + ISSUER, + CANARY_AUDIENCE, + CANARY_CLAIMS, + Set.of(), + MAX_TOKEN_LIFETIME_SECONDS, + CLOCK_SKEW_SECONDS, + MAX_COMPACT_TOKEN_BYTES, + AccountJwtReadinessProbeCrypto::validateCanaryShape); + } + ProfileDescriptor descriptor = REPRESENTATIVE_PROFILES.get(profile); + if (descriptor == null) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + return new ExplicitRouteProfilePolicy( + "account-jwt-readiness-" + descriptor.profile(), + descriptor.profile(), + descriptor.tokenType(), + ISSUER, + descriptor.audience(), + descriptor.requiredClaims(), + descriptor.optionalClaims(), + MAX_TOKEN_LIFETIME_SECONDS, + CLOCK_SKEW_SECONDS, + MAX_COMPACT_TOKEN_BYTES, + claims -> validateProfileShape(descriptor.profile(), claims, maxControlUiTenantScopes)); + } + + static VerifiedClaims verify( + AccountAsymmetricJwtVerifier verifier, + String compactJwt, + ExpectedProbe expected, + int maxControlUiTenantScopes) { + Objects.requireNonNull(verifier); + Objects.requireNonNull(expected); + VerifiedClaims verified = + verifier.verify( + compactJwt, + policy(expected.probeKind(), expected.tokenProfile(), maxControlUiTenantScopes)); + validateSignedClaims(verified, expected); + return verified; + } + + static ExpectedProbe expectedProbe( + ProbeKind kind, + String tokenProfile, + String audience, + String jti, + String targetKid, + long issuedAtEpochSecond, + long expiresAtEpochSecond) { + if (kind == ProbeKind.CANARY) { + if (!CANARY_PROFILE.equals(tokenProfile) || !CANARY_AUDIENCE.equals(audience)) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + } else { + ProfileDescriptor descriptor = REPRESENTATIVE_PROFILES.get(tokenProfile); + if (descriptor == null || !descriptor.audience().equals(audience)) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + } + return new ExpectedProbe( + kind, tokenProfile, audience, jti, targetKid, issuedAtEpochSecond, expiresAtEpochSecond); + } + + private static void validateSignedClaims(VerifiedClaims verified, ExpectedProbe expected) { + Map claims = verified.claims(); + boolean canary = expected.probeKind() == ProbeKind.CANARY; + ProfileDescriptor profile = + canary ? null : REPRESENTATIVE_PROFILES.get(expected.tokenProfile()); + if (profile == null && !canary) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + String expectedPolicyType = canary ? CANARY_TYPE : profile.tokenType(); + if (!verified.profile().equals(expected.tokenProfile()) + || !verified.tokenType().equals(expectedPolicyType) + || !verified.keyId().equals(expected.targetKid()) + || !ISSUER.equals(claims.get("iss")) + || !expected.audience().equals(claims.get("aud")) + || !RESERVED_SUBJECT.equals(claims.get("sub")) + || !expected.jti().equals(claims.get("jti")) + || exactLong(claims.get("iat")) != expected.issuedAtEpochSecond() + || exactLong(claims.get("nbf")) != expected.issuedAtEpochSecond() + || exactLong(claims.get("exp")) != expected.expiresAtEpochSecond()) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + if (canary) { + if (!CANARY_CLAIMS.equals(claims.keySet()) + || !CANARY_PROFILE.equals(claims.get("tokenProfile")) + || !CANARY_TYPE.equals(claims.get("tokenType"))) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + return; + } + if (!RESERVED_SUBJECT.equals(claims.get("accountId")) + || !exactOneCounter(claims.get("tokenGeneration"), profile) + || !exactOneCounter(claims.get("issuanceFence"), profile) + || !exactAuthorityTuple(claims.get("authorityTuple"), profile) + || !(claims.get("membershipVersion") instanceof Map membershipVersion) + || !membershipVersion.isEmpty() + || !noRoleClaims(claims) + || !noScopeClaims(profile, claims)) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + } + + private static void validateCanaryShape(Map claims) { + if (!CANARY_CLAIMS.equals(claims.keySet()) + || !ISSUER.equals(claims.get("iss")) + || !CANARY_PROFILE.equals(claims.get("tokenProfile")) + || !CANARY_TYPE.equals(claims.get("tokenType"))) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + } + + private static void validateProfileShape( + String profile, Map claims, int maxControlUiTenantScopes) { + switch (profile) { + case ControlUiJwtProfileValidator.PROFILE -> + ControlUiJwtProfileValidator.validateClaims(claims, maxControlUiTenantScopes); + case PlayerBootstrapJwtProfileValidator.PROFILE -> + PlayerBootstrapJwtProfileValidator.validateClaims(claims); + case GameSessionAccountDelegationProfile.PROFILE -> + GameSessionAccountDelegationJwtProfileValidator.validateClaims(claims); + default -> throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + } + + private static boolean noRoleClaims(Map claims) { + if (claims.containsKey("globalRoles")) { + return claims.get("globalRoles") instanceof java.util.List roles && roles.isEmpty(); + } + return true; + } + + private static boolean noScopeClaims(ProfileDescriptor profile, Map claims) { + if (profile.profile().equals(GameSessionAccountDelegationProfile.PROFILE) + && !claims.containsKey("scopedRoles")) { + return true; + } + return claims.get("scopedRoles") instanceof Map scopedRoles && scopedRoles.isEmpty(); + } + + private static boolean exactOneCounter(Object value, ProfileDescriptor profile) { + return GameSessionAccountDelegationProfile.PROFILE.equals(profile.profile()) + ? "1".equals(value) + : exactLong(value) == 1L; + } + + private static boolean exactAuthorityTuple(Object value, ProfileDescriptor profile) { + if (!(value instanceof Map tuple) + || !tuple.keySet().equals(INITIAL_AUTHORITY_TUPLE_FIELDS)) { + return false; + } + return exactOneCounter(tuple.get("issuerAuthGeneration"), profile) + && exactOneCounter(tuple.get("accountAuthorityGeneration"), profile) + && tuple.get("tenantAuthorityGeneration") instanceof Map tenantAuthority + && tenantAuthority.isEmpty() + && tuple.get("membershipAuthorityGeneration") instanceof Map membershipAuthority + && membershipAuthority.isEmpty() + && tuple.get("privateRealmGrantVersions") instanceof java.util.List grants + && grants.isEmpty(); + } + + private static long exactLong(Object value) { + if (!(value instanceof Number number)) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + try { + return new BigDecimal(number.toString()).longValueExact(); + } catch (ArithmeticException | NumberFormatException invalidNumber) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + } + + public static AccountAsymmetricJwtVerifier createVerifier( + AccountJwtJwksTrustedSource trustedSource, Clock clock) { + Objects.requireNonNull(trustedSource, "Protected Account JWKS source is required"); + var sourceIdentity = trustedSource.sourceIdentity(); + var cache = + new AccountPublicJwksCache(trustedSource, sourceIdentity, clock, Duration.ofSeconds(300)); + return new AccountAsymmetricJwtVerifier(cache, clock); + } + + record ProfileDescriptor( + String profile, + String audience, + String tokenType, + Set requiredClaims, + Set optionalClaims) {} + + record ExpectedProbe( + ProbeKind probeKind, + String tokenProfile, + String audience, + String jti, + String targetKid, + long issuedAtEpochSecond, + long expiresAtEpochSecond) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapper.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapper.java new file mode 100644 index 0000000000..2f58713901 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapper.java @@ -0,0 +1,216 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountPodTargetBinding; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.OwnerProbeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; + +/** Strict closed-wire mapper; caller-local Account JWKS pins are validated but never echoed. */ +public final class AccountJwtReadinessProbeOwnerProtoMapper { + private static final int SCHEMA_VERSION = 1; + + public AccountJwtReadinessProbeOwnerSelector parse(GetCurrentReadinessProbeOwnerRequest request) { + if (request == null + || request.getSchemaVersion() != SCHEMA_VERSION + || !request.getUnknownFields().asMap().isEmpty() + || !request.hasExpectedCoordinates() + || !request.hasProtectedLocalIdentity() + || request.getCompactTokenSha256().isEmpty()) { + throw new InvalidOwnerReadRequestException(); + } + ReadinessProbeCoordinates coordinates = request.getExpectedCoordinates(); + var local = request.getProtectedLocalIdentity(); + if (!coordinates.getUnknownFields().asMap().isEmpty() + || !local.getUnknownFields().asMap().isEmpty() + || !local.hasAccountJwksSourceIdentity() + || !local.getAccountJwksSourceIdentity().getUnknownFields().asMap().isEmpty()) { + throw new InvalidOwnerReadRequestException(); + } + try { + ProbeKind probeKind = + switch (coordinates.getProbeKind()) { + case CANARY -> ProbeKind.CANARY; + case REPRESENTATIVE -> ProbeKind.REPRESENTATIVE; + case PROBE_KIND_UNSPECIFIED, UNRECOGNIZED -> throw new IllegalArgumentException(); + }; + ProbeExpectation expectedOutcome = + switch (coordinates.getExpectedOutcome()) { + case ACCEPT -> ProbeExpectation.ACCEPT; + case INAPPLICABLE_REJECT -> ProbeExpectation.INAPPLICABLE_REJECT; + case EXPECTED_OUTCOME_UNSPECIFIED, UNRECOGNIZED -> throw new IllegalArgumentException(); + }; + var activeFence = + switch (coordinates.getExpectedActiveState()) { + case ABSENT -> { + if (!coordinates.getExpectedActiveGeneration().isEmpty() + || !coordinates.getExpectedActiveKid().isEmpty()) { + throw new IllegalArgumentException(); + } + yield java.util.Optional.empty(); + } + case PRESENT -> { + if (coordinates.getExpectedActiveGeneration().isEmpty() + || coordinates.getExpectedActiveKid().isEmpty()) { + throw new IllegalArgumentException(); + } + yield java.util.Optional.of( + new ActiveSigner( + coordinates.getExpectedActiveGeneration(), + coordinates.getExpectedActiveKid())); + } + case EXPECTED_ACTIVE_STATE_UNSPECIFIED, UNKNOWN, UNRECOGNIZED -> + throw new IllegalArgumentException(); + }; + var source = local.getAccountJwksSourceIdentity(); + // This is caller-local verifier-source context, not Account's Kubernetes inventory source. + // Validate its closed bounded form, but never treat it as Account evidence or echo it. + new SourceIdentity( + source.getEnvironmentId(), + source.getClusterId(), + source.getClusterIncarnationUid(), + source.getNamespace(), + source.getNamespaceUid(), + source.getConfigMapUid(), + source.getBindingRevision(), + source.getApiServerOrigin(), + source.getServingCaSha256()); + if (local.getAccountJwksTrustConfigRevision() <= 0L) { + throw new IllegalArgumentException(); + } + return new AccountJwtReadinessProbeOwnerSelector( + canonicalUuid(coordinates.getRotationOperationId()), + coordinates.getOperationDigest(), + coordinates.getPlanDigest(), + coordinates.getPlanVersion(), + coordinates.getRegistryVersion(), + coordinates.getValidatorId(), + coordinates.getTokenProfile(), + coordinates.getAudience(), + probeKind, + expectedOutcome, + canonicalUuid(coordinates.getJti()), + coordinates.getEntryVersion(), + coordinates.getTargetGeneration(), + coordinates.getTargetKid(), + activeFence, + coordinates.getIssuedAtEpochSeconds(), + coordinates.getExpiresAtEpochSeconds(), + coordinates.getPlanExpiresAtEpochSeconds(), + request.getCompactTokenSha256(), + new AccountJwtReadinessProbeOwnerSelector.LocalIdentity( + local.getValidatorId(), + local.getDeploymentUid(), + local.getPodUid(), + local.getPodIp(), + local.getDirectPodEndpoint(), + local.getCanonicalServiceUri(), + local.getImage(), + local.getVerifierConfigSha256(), + local.getApplicabilityMatrixDigest(), + local.getSourceInventoryRevision(), + local.getSourceInventoryDigest(), + local.getServerLeafSpkiSha256())); + } catch (RuntimeException invalid) { + throw new InvalidOwnerReadRequestException(); + } + } + + public GetCurrentReadinessProbeOwnerResponse toResponse(OwnerProbeEvidence evidence) { + ReadinessProbePlan plan = evidence.plan(); + ProbeEntry entry = evidence.entry(); + var target = evidence.expectedPod().target(); + ReadinessProbeCoordinates.Builder coordinates = + ReadinessProbeCoordinates.newBuilder() + .setRotationOperationId(plan.operationId().toString()) + .setOperationDigest(plan.operationDigest()) + .setPlanDigest(plan.planDigest()) + .setPlanVersion(plan.planVersion()) + .setRegistryVersion(entry.registryVersion()) + .setValidatorId(entry.validatorId()) + .setTokenProfile(entry.tokenProfile()) + .setAudience(entry.audience()) + .setProbeKind( + entry.probeKind() == ProbeKind.CANARY + ? ReadinessProbeCoordinates.ProbeKind.CANARY + : ReadinessProbeCoordinates.ProbeKind.REPRESENTATIVE) + .setExpectedOutcome( + target.expectation() == ProbeExpectation.ACCEPT + ? ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT + : ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT) + .setJti(entry.jti().toString()) + .setEntryVersion(entry.entryVersion()) + .setTargetGeneration(entry.targetGeneration()) + .setTargetKid(entry.targetKid()) + .setIssuedAtEpochSeconds(entry.plannedIssuedAtEpochSecond()) + .setExpiresAtEpochSeconds(entry.expiresAtEpochSecond()) + .setPlanExpiresAtEpochSeconds(plan.expiresAtEpochSecond()); + entry + .expectedActive() + .ifPresentOrElse( + active -> + coordinates + .setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.PRESENT) + .setExpectedActiveGeneration(active.generation()) + .setExpectedActiveKid(active.kid()), + () -> + coordinates.setExpectedActiveState( + ReadinessProbeCoordinates.ExpectedActiveState.ABSENT)); + AccountPodTargetBinding accountTarget = + AccountPodTargetBinding.newBuilder() + .setInventorySnapshotDigest(target.inventorySnapshotDigest()) + .setEnvironmentId(target.environmentId()) + .setClusterId(target.clusterId()) + .setClusterIncarnationUid(target.clusterIncarnationUid()) + .setNamespace(target.namespace()) + .setNamespaceUid(target.namespaceUid()) + .setApiBindingRevision(target.apiBindingRevision()) + .setApiBindingDigest(target.apiBindingDigest()) + .setInventoryBindingRevision(target.inventoryBindingRevision()) + .setInventoryBindingDigest(target.inventoryBindingDigest()) + .setValidatorId(target.validatorId()) + .setDeploymentUid(target.deploymentUid()) + .setPodUid(target.podUid()) + .setPodIp(target.podIp()) + .setImage(target.image()) + .setVerifierConfigSha256(target.verifierConfigSha256()) + .setApplicabilityMatrixDigest(target.applicabilityMatrixDigest()) + .setExpectedOutcome( + target.expectation() == ProbeExpectation.ACCEPT + ? ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT + : ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT) + .setDirectPodEndpoint(target.exactPodEndpoint().orElseThrow().toString()) + .setCanonicalServiceUri(target.canonicalServiceUri().orElseThrow()) + .setServerLeafSpkiSha256(target.podLeafSpkiSha256().orElseThrow()) + .build(); + return GetCurrentReadinessProbeOwnerResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setOwnerRecordFound(true) + .setCurrentCoordinates(coordinates) + .setCompactTokenSha256(entry.compactTokenSha256().orElseThrow()) + .setCurrentState(GetCurrentReadinessProbeOwnerResponse.ProbeState.ISSUED) + .setCurrentPodTarget(accountTarget) + .build(); + } + + private static UUID canonicalUuid(String value) { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException(); + } + return parsed; + } + + public static final class InvalidOwnerReadRequestException extends RuntimeException { + public InvalidOwnerReadRequestException() { + super("Readiness probe owner request is invalid"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java new file mode 100644 index 0000000000..3344965501 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.net.URI; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; + +/** Closed, bounded selector for an authenticated read of one current V2 readiness entry. */ +public record AccountJwtReadinessProbeOwnerSelector( + UUID rotationOperationId, + String operationDigest, + String planDigest, + int planVersion, + int registryVersion, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + ProbeExpectation expectedOutcome, + UUID jti, + long entryVersion, + String targetGeneration, + String targetKid, + Optional expectedActive, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + long planExpiresAtEpochSecond, + String compactTokenSha256, + LocalIdentity localIdentity) { + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,62}"); + private static final Pattern PROFILE = Pattern.compile("[a-z][a-z0-9-]{0,62}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + + public AccountJwtReadinessProbeOwnerSelector { + Objects.requireNonNull(rotationOperationId, "operation ID is required"); + if (rotationOperationId.version() != 4 || rotationOperationId.variant() != 2) { + throw new IllegalArgumentException("Canonical readiness operation UUIDv4 is required"); + } + requireDigest(operationDigest, "operation digest"); + requireDigest(planDigest, "plan digest"); + if (planVersion != AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION + || registryVersion != 1 + || entryVersion <= 0L) { + throw new IllegalArgumentException("Current V2 readiness coordinates are required"); + } + requireId(validatorId, "validator ID"); + requireProfile(tokenProfile); + requireProfile(audience); + Objects.requireNonNull(probeKind, "probe kind is required"); + Objects.requireNonNull(expectedOutcome, "expected outcome is required"); + Objects.requireNonNull(jti, "probe JTI is required"); + if (jti.version() != 4 || jti.variant() != 2) { + throw new IllegalArgumentException("Canonical readiness JTI is required"); + } + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive, "active fence state is required"); + if (issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || planExpiresAtEpochSecond <= 0L + || expiresAtEpochSecond > planExpiresAtEpochSecond) { + throw new IllegalArgumentException("Readiness probe time bounds are malformed"); + } + requireDigest(compactTokenSha256, "compact token digest"); + Objects.requireNonNull(localIdentity, "protected local identity is required"); + } + + public record LocalIdentity( + String validatorId, + String deploymentUid, + String podUid, + String podIp, + String directPodEndpoint, + String canonicalServiceUri, + String image, + String verifierConfigSha256, + String applicabilityMatrixDigest, + String sourceInventoryRevision, + String sourceInventoryDigest, + String serverLeafSpkiSha256) { + public LocalIdentity { + requireId(validatorId, "validator ID"); + requireCanonicalUuid(deploymentUid, "deployment UID"); + requireCanonicalUuid(podUid, "Pod UID"); + if (!net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding + .canonicalPodIp(podIp) + .equals(podIp)) { + throw new IllegalArgumentException("Pod IP is not canonical"); + } + requireText(directPodEndpoint, 256, "direct Pod endpoint"); + requireText(canonicalServiceUri, 256, "canonical service URI"); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Validator image must be digest-pinned"); + } + requireDigest(verifierConfigSha256, "verifier configuration digest"); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + if (sourceInventoryRevision == null || !REVISION.matcher(sourceInventoryRevision).matches()) { + throw new IllegalArgumentException("Receiver source inventory revision is malformed"); + } + requireDigest(sourceInventoryDigest, "receiver source inventory digest"); + requireDigest(serverLeafSpkiSha256, "receiver TLS SPKI digest"); + URI endpoint = URI.create(directPodEndpoint); + if (!endpoint.toString().equals(directPodEndpoint) + || !canonicalServiceUri.matches( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new IllegalArgumentException("Receiver endpoint or service identity is malformed"); + } + } + } + + private static void requireCanonicalUuid(String value, String label) { + if (value == null + || !value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}") + || !UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException(label + " is not canonical"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is malformed"); + } + } + + private static void requireId(String value, String label) { + if (value == null || !ID.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is malformed"); + } + } + + private static void requireProfile(String value) { + if (value == null || !PROFILE.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness profile or audience is malformed"); + } + } + + private static void requireKid(String value) { + if (value == null || !KID.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness target key ID is malformed"); + } + } + + private static void requireGeneration(String value) { + if (value == null || !GENERATION.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness target generation is malformed"); + } + } + + private static void requireText(String value, int maximum, String label) { + if (value == null + || value.isBlank() + || value.length() > maximum + || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(label + " is malformed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerService.java new file mode 100644 index 0000000000..46aa3295de --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerService.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Objects; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerWorkloadGuard; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerWorkloadGuard.AuthenticatedCaller; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException; + +/** Default-inactive read-only boundary for one exact current Game Session readiness probe. */ +public final class AccountJwtReadinessProbeOwnerService { + private static final String GAME_SESSION_VALIDATOR = "game-session-service"; + + private final AccountJwtReadinessProbeService probeService; + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtReadinessProbeOwnerWorkloadGuard workloadGuard; + private final AccountJwtReadinessProbeOwnerProtoMapper protoMapper; + + public AccountJwtReadinessProbeOwnerService( + AccountJwtReadinessProbeService probeService, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtReadinessProbeOwnerWorkloadGuard workloadGuard, + AccountJwtReadinessProbeOwnerProtoMapper protoMapper) { + this.probeService = Objects.requireNonNull(probeService); + this.materializerTrustBinding = Objects.requireNonNull(materializerTrustBinding); + this.workloadGuard = Objects.requireNonNull(workloadGuard); + this.protoMapper = Objects.requireNonNull(protoMapper); + } + + public GetCurrentReadinessProbeOwnerResponse getCurrentReadinessProbeOwner( + GetCurrentReadinessProbeOwnerRequest request) { + AuthenticatedCaller caller = workloadGuard.requireGameSessionOwnerReadCaller(); + AccountJwtReadinessProbeOwnerSelector selector = protoMapper.parse(request); + if (!GAME_SESSION_VALIDATOR.equals(selector.validatorId())) { + throw new AccountJwtReadinessProbeOwnerWorkloadGuard.OwnerReadDeniedException(); + } + var protectedAccountBinding = caller.accountBinding(); + TrustFence trustFence = + AccountJwtReadinessValidationService.trustFence(protectedAccountBinding); + var evidence = + probeService.readCurrentProbeOwner( + protectedAccountBinding.accountBinding(), + trustFence, + selector, + protectedAccountBinding.namespace()); + + // Do not return an observation tied to a protected binding that changed during the read. + var currentCaller = workloadGuard.requireGameSessionOwnerReadCaller(); + var latestBinding = + materializerTrustBinding.current().orElseThrow(ReceiverUnavailableException::new); + if (!protectedAccountBinding.equals(currentCaller.accountBinding()) + || !protectedAccountBinding.equals(latestBinding)) { + throw new ReceiverUnavailableException(); + } + if (!evidence.expectedPod().target().namespace().equals(protectedAccountBinding.namespace())) { + throw new ReceiverUnavailableException(); + } + return protoMapper.toResponse(evidence); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java new file mode 100644 index 0000000000..470b46922d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java @@ -0,0 +1,549 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.DeliveryClaim; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ExpectedPod; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.OwnerProbeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeState; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ExpectedIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.SignedProbeDigest; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Dormant, owner-internal producer for durable Account readiness-probe plans and constrained + * pending-key signatures. + * + *

This class is intentionally not a Spring component. Its per-invocation callback receives the + * exact compact probe only for the duration of the call; this producer persists only its hash. The + * caller must supply the already-persisted one-shot delivery claim. The separate readiness route + * may record an authenticated non-authorizing observation, but neither path can promote a signer. + */ +public final class AccountJwtReadinessProbeService { + private static final Path PRIVATE_MOUNT = privateSignerMount(); + + private static final Path PRIVATE_PENDING_BUNDLE = Path.of("pending.key"); + + private static final Path PUBLIC_MOUNT = publicJwksMount(); + + private static final Path PUBLIC_JWKS = Path.of("jwks.json"); + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The interim private signer projection is intentionally fixed to Account's protected read-only mount.") + private static Path privateSignerMount() { + return Path.of("/var/run/secrets/firemud/jwt"); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The public JWKS projection is intentionally fixed to Account's read-only validator-consumed mount.") + private static Path publicJwksMount() { + return Path.of("/var/run/secrets/firemud/jwks"); + } + + private final AccountJwtReadinessProbeRepository repository; + private final TransactionTemplate accountTransaction; + private final Clock clock; + private final AccountJwtValidatorInventorySource inventorySource; + private final Path privateMount; + private final Path privateBundle; + private final Path publicMount; + private final Path publicJwks; + + public AccountJwtReadinessProbeService( + AccountJwtReadinessProbeRepository repository, + TransactionTemplate accountTransaction, + Clock clock) { + this( + repository, + accountTransaction, + clock, + PRIVATE_MOUNT, + PRIVATE_PENDING_BUNDLE, + PUBLIC_MOUNT, + PUBLIC_JWKS); + } + + AccountJwtReadinessProbeService( + AccountJwtReadinessProbeRepository repository, + TransactionTemplate accountTransaction, + Clock clock, + Path privateMount, + Path privateBundle, + Path publicMount, + Path publicJwks) { + this( + repository, + accountTransaction, + clock, + privateMount, + privateBundle, + publicMount, + publicJwks, + null); + } + + public AccountJwtReadinessProbeService( + AccountJwtReadinessProbeRepository repository, + TransactionTemplate accountTransaction, + Clock clock, + AccountJwtValidatorInventorySource inventorySource) { + this( + repository, + accountTransaction, + clock, + PRIVATE_MOUNT, + PRIVATE_PENDING_BUNDLE, + PUBLIC_MOUNT, + PUBLIC_JWKS, + Objects.requireNonNull(inventorySource)); + } + + private AccountJwtReadinessProbeService( + AccountJwtReadinessProbeRepository repository, + TransactionTemplate accountTransaction, + Clock clock, + Path privateMount, + Path privateBundle, + Path publicMount, + Path publicJwks, + AccountJwtValidatorInventorySource inventorySource) { + this.repository = Objects.requireNonNull(repository); + this.accountTransaction = Objects.requireNonNull(accountTransaction); + this.clock = Objects.requireNonNull(clock); + this.privateMount = Objects.requireNonNull(privateMount); + this.privateBundle = Objects.requireNonNull(privateBundle); + this.publicMount = Objects.requireNonNull(publicMount); + this.publicJwks = Objects.requireNonNull(publicJwks); + this.inventorySource = inventorySource; + } + + /** Plans the current Account-selected generation operation; no signing occurs in this method. */ + public ReadinessProbePlan planCurrent(Binding binding, TrustFence trust) { + if (inventorySource == null) { + return inTransaction( + () -> repository.planCurrent(binding, trust, Instant.ofEpochSecond(nowEpochSecond()))); + } + ObservationContext observationContext = + inTransaction(() -> repository.readCurrentInventoryObservationContext(binding, trust)); + AccountJwtValidatorInventorySource.InventorySnapshot snapshot = + inventorySource.observe(observationContext); + return inTransaction( + () -> + repository.planCurrent( + binding, trust, Instant.ofEpochSecond(nowEpochSecond()), snapshot)); + } + + /** Rereads protected live inventory before opening the exact receiver target-read transaction. */ + public List readCurrentExpectedPods( + Binding binding, TrustFence trust, ProbeEntry entry) { + AccountJwtValidatorInventorySource.InventorySnapshot snapshot = + observeCurrentInventory(binding, trust, entry.rotationOperationId()); + return inTransaction(() -> repository.readCurrentExpectedPods(binding, trust, entry, snapshot)); + } + + /** + * Reads one exact V2 receiver owner row after observing protected Kubernetes inventory outside + * the short SQL transaction. + */ + public OwnerProbeEvidence readCurrentProbeOwner( + Binding binding, + TrustFence trust, + AccountJwtReadinessProbeOwnerSelector selector, + String authenticatedWorkloadNamespace) { + AccountJwtValidatorInventorySource.InventorySnapshot snapshot = + observeCurrentInventory(binding, trust, selector.rotationOperationId()); + if (!snapshot.namespace().equals(authenticatedWorkloadNamespace)) { + throw new AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException(); + } + return inTransaction( + () -> + repository.readCurrentProbeOwner( + binding, trust, selector, snapshot, authenticatedWorkloadNamespace)); + } + + /** Rereads protected live inventory before committing one immutable per-Pod receipt. */ + public ProbeEntry recordPodAcceptance( + Binding binding, + TrustFence trust, + ProbeEntry entry, + ExpectedPod expectedPod, + AuthenticatedAcceptance acceptance) { + AccountJwtValidatorInventorySource.InventorySnapshot snapshot = + observeCurrentInventory(binding, trust, entry.rotationOperationId()); + return inTransaction( + () -> + repository.recordPodAcceptance( + binding, trust, entry, expectedPod, acceptance, snapshot)); + } + + /** + * Fresh owner observation for promotion callers; never performs I/O while SQL rows are locked. + */ + public AccountJwtValidatorInventorySource.InventorySnapshot observeCurrentInventory() { + if (inventorySource == null) { + throw new AccountJwtValidatorInventorySource.InventoryUnavailableException(); + } + return inventorySource.observe(); + } + + /** Reads only an owner-derived current V2 operation context for the Pod-local receiver proof. */ + ObservationContext readCurrentInventoryObservationContext( + Binding binding, TrustFence trust, UUID operationId) { + return inTransaction( + () -> repository.readCurrentInventoryObservationContext(binding, trust, operationId)); + } + + private AccountJwtValidatorInventorySource.InventorySnapshot observeCurrentInventory( + Binding binding, TrustFence trust, UUID operationId) { + if (inventorySource == null) { + throw new AccountJwtValidatorInventorySource.InventoryUnavailableException(); + } + ObservationContext observationContext = + readCurrentInventoryObservationContext(binding, trust, operationId); + return inventorySource.observe(observationContext); + } + + /** Reads the exact durable operation and latest receipt state without creating evidence. */ + ReadinessProbePlan readCurrentPlan(Binding binding, TrustFence trust, UUID operationId) { + return inTransaction(() -> repository.readCurrentPlan(binding, trust, operationId)); + } + + /** + * Delivers each exact current planned probe once. The compact-token hash and ISSUED transition + * are durably read back before transient delivery, so an authenticated validator can consume the + * current entry synchronously. A persisted signing-attempt hash without ISSUED is ambiguous and + * causes same-operation quarantine rather than token remint or replay. + */ + List issueCurrentPlan( + Binding binding, + TrustFence trust, + UUID operationId, + DeliveryClaim claim, + OwnerInternalProbeDelivery delivery) { + ReadinessProbePlan plan = + inTransaction(() -> repository.readCurrentPlan(binding, trust, operationId)); + if (nowEpochSecond() < plan.notBeforeEpochSecond()) { + throw new AccountJwtReadinessProbeRepository.CacheAgeNotElapsedException(); + } + if (nowEpochSecond() >= plan.expiresAtEpochSecond()) { + return expireAndClean(binding, trust, operationId); + } + Objects.requireNonNull(claim, "Persisted one-shot delivery claim is required"); + Objects.requireNonNull(delivery, "Per-invocation internal delivery is required"); + DeliveryClaim persistedClaim = + inTransaction( + () -> + repository.requireCurrentDeliveryClaim( + binding, trust, plan, claim, Instant.ofEpochSecond(nowEpochSecond()))); + if (persistedClaim == null || !persistedClaim.equals(claim)) { + throw new AccountJwtReadinessProbeRepository.DeliveryAlreadyClaimedException(); + } + List output = new ArrayList<>(); + for (ProbeEntry planned : plan.entries()) { + ProbeEntry current = currentEntry(binding, trust, operationId, planned); + if (current.state() == ProbeState.ISSUED) { + output.add(current); + continue; + } + if (current.state() == ProbeState.PLANNED && current.compactTokenSha256().isPresent()) { + output.addAll(quarantineCurrent(binding, trust, operationId)); + break; + } + if (current.state() != ProbeState.PLANNED) { + output.add(current); + continue; + } + + long now = nowEpochSecond(); + if (now < current.plannedIssuedAtEpochSecond()) { + throw new AccountJwtReadinessProbeRepository.CacheAgeNotElapsedException(); + } + if (now >= current.expiresAtEpochSecond()) { + output.addAll(expireAndClean(binding, trust, operationId)); + break; + } + + ExpectedIdentity identity = + new ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + operationId.toString(), + current.targetGeneration(), + current.targetKid(), + plan.targetPublicKeyFingerprint()); + ReadinessProbeSigningSpec spec = + new ReadinessProbeSigningSpec( + current.validatorId(), + current.probeKind(), + current.tokenProfile(), + current.audience(), + current.jti(), + current.targetGeneration(), + current.targetKid(), + current.plannedIssuedAtEpochSecond(), + current.expiresAtEpochSecond()); + + SignedProbeDigest signed; + try { + signed = + AccountMountedJwtSignerBundle.signReadinessProbeDigest( + privateMount, + privateBundle, + publicMount, + publicJwks, + identity, + spec, + (digest, exactCompactJwt) -> { + try { + pinBeforeDelivery(binding, trust, digest); + ProbeEntry issued = + inTransaction( + () -> + repository.recordIssued( + binding, + trust, + digest, + Instant.ofEpochSecond(nowEpochSecond()))); + DeliveryMetadata metadata = DeliveryMetadata.from(plan, issued, digest); + delivery.deliver(metadata, exactCompactJwt); + if (!sha256(exactCompactJwt).equals(metadata.compactTokenSha256())) { + throw new IllegalStateException( + "Transient readiness probe bytes changed in delivery"); + } + } catch (RuntimeException ignored) { + abortAfterDeliveryFailure(binding, trust, operationId); + throw new DeliveryQuarantinedException(); + } + }); + } catch (DeliveryQuarantinedException ex) { + throw ex; + } + try { + ProbeEntry delivered = currentEntry(binding, trust, operationId, current); + if (!exactSignedReadback(plan, current, delivered, signed) + || (delivered.state() != ProbeState.ISSUED + && delivered.state() != ProbeState.VERIFIED)) { + throw new IllegalStateException("Readiness delivery result did not read back exactly"); + } + output.add(delivered); + } catch (RuntimeException ignored) { + abortAfterDeliveryFailure(binding, trust, operationId); + throw new DeliveryQuarantinedException(); + } + } + return List.copyOf(output); + } + + /** Aborts only the named current operation and retains hashes/evidence. */ + public List abortCurrentPlan(Binding binding, TrustFence trust, UUID operationId) { + return quarantineCurrent(binding, trust, operationId); + } + + /** Expires due entries and performs bounded cleanup for only the named operation. */ + public List expireAndClean(Binding binding, TrustFence trust, UUID operationId) { + return inTransaction( + () -> { + repository.expireCurrent( + binding, trust, operationId, Instant.ofEpochSecond(nowEpochSecond())); + return repository.cleanTerminalEntries( + operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION); + }); + } + + /** Bounded terminal cleanup never scans outside this explicit operation ID. */ + public List cleanTerminalEntries(UUID operationId) { + return inTransaction( + () -> + repository.cleanTerminalEntries( + operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION)); + } + + private void pinBeforeDelivery(Binding binding, TrustFence trust, SignedProbeDigest digest) { + try { + inTransaction( + () -> + repository.recordSigningAttempt( + binding, trust, digest, Instant.ofEpochSecond(nowEpochSecond()))); + } catch (RuntimeException failure) { + throw new SigningAttemptConflict(); + } + } + + private void abortAfterDeliveryFailure(Binding binding, TrustFence trust, UUID operationId) { + try { + quarantineCurrent(binding, trust, operationId); + } catch (RuntimeException ignored) { + // The durable pre-delivery hash remains a quarantine marker for same-operation recovery. + } + } + + private static boolean exactSignedReadback( + ReadinessProbePlan plan, ProbeEntry expected, ProbeEntry readback, SignedProbeDigest signed) { + long issuedEntryVersion = expected.entryVersion() + 2L; + long resultEntryVersion = + readback.state() == ProbeState.VERIFIED ? issuedEntryVersion + 1L : issuedEntryVersion; + return readback.rotationOperationId().equals(plan.operationId()) + && readback.planDigest().equals(plan.planDigest()) + && expected.planDigest().equals(plan.planDigest()) + && signed.operationId().equals(plan.operationId().toString()) + && readback.jti().equals(expected.jti()) + && signed.jti().equals(expected.jti()) + && readback.validatorId().equals(expected.validatorId()) + && signed.validatorId().equals(expected.validatorId()) + && readback.tokenProfile().equals(expected.tokenProfile()) + && signed.tokenProfile().equals(expected.tokenProfile()) + && readback.audience().equals(expected.audience()) + && signed.audience().equals(expected.audience()) + && readback.probeKind() == expected.probeKind() + && signed.probeKind() == expected.probeKind() + && readback.targetGeneration().equals(plan.targetGeneration()) + && signed.targetGeneration().equals(plan.targetGeneration()) + && readback.targetKid().equals(plan.targetKid()) + && signed.targetKid().equals(plan.targetKid()) + && signed.publicKeyFingerprint().equals(plan.targetPublicKeyFingerprint()) + && readback.plannedIssuedAtEpochSecond() == signed.issuedAtEpochSecond() + && readback.expiresAtEpochSecond() == signed.expiresAtEpochSecond() + && readback.signingAttemptedAtEpochSecond().isPresent() + && readback.entryVersion() == resultEntryVersion + && (readback.state() != ProbeState.VERIFIED + || readback + .verificationReceipt() + .filter( + receipt -> + receipt.sourceEntryVersion() == issuedEntryVersion + && receipt.resultEntryVersion() == resultEntryVersion) + .isPresent()) + && readback.compactTokenSha256().equals(java.util.Optional.of(signed.compactTokenSha256())); + } + + private List quarantineCurrent(Binding binding, TrustFence trust, UUID operationId) { + return inTransaction( + () -> { + repository.abortCurrent( + binding, trust, operationId, Instant.ofEpochSecond(nowEpochSecond())); + return repository.cleanTerminalEntries( + operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION); + }); + } + + private ProbeEntry currentEntry( + Binding binding, TrustFence trust, UUID operationId, ProbeEntry expected) { + ReadinessProbePlan plan = + inTransaction(() -> repository.readCurrentPlan(binding, trust, operationId)); + return plan.entries().stream() + .filter(entry -> entry.jti().equals(expected.jti())) + .findFirst() + .orElseThrow( + () -> + new AccountJwtReadinessProbeRepository.QuarantinedStateException( + "Readiness probe entry disappeared from its immutable plan")); + } + + private long nowEpochSecond() { + long value = clock.instant().getEpochSecond(); + if (value <= 0L) { + throw new IllegalStateException("Readiness producer clock is invalid"); + } + return value; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable"); + } + } + + private T inTransaction(java.util.function.Supplier operation) { + return accountTransaction.execute(status -> operation.get()); + } + + /** + * Per-invocation owner-internal sink. This is not a Spring component contract or an authority + * input; callback success is not validation evidence. Only an exact owner readback of a receipt + * independently recorded by the authenticated validator is. + */ + @FunctionalInterface + interface OwnerInternalProbeDelivery { + void deliver(DeliveryMetadata metadata, byte[] exactCompactJwt); + } + + /** Non-secret operation identity passed alongside the transient probe bytes. */ + public record DeliveryMetadata( + UUID operationId, + String planDigest, + int planVersion, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + String targetGeneration, + String targetKid, + Optional expectedActiveGeneration, + Optional expectedActiveKid, + int registryVersion, + long entryVersion, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256) { + private static DeliveryMetadata from( + ReadinessProbePlan plan, ProbeEntry entry, SignedProbeDigest digest) { + return new DeliveryMetadata( + plan.operationId(), + plan.planDigest(), + plan.planVersion(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + entry.jti(), + entry.targetGeneration(), + entry.targetKid(), + entry.expectedActive().map(value -> value.generation()), + entry.expectedActive().map(value -> value.kid()), + entry.registryVersion(), + entry.entryVersion(), + entry.plannedIssuedAtEpochSecond(), + entry.expiresAtEpochSecond(), + digest.compactTokenSha256()); + } + } + + private static final class SigningAttemptConflict extends IllegalStateException { + private SigningAttemptConflict() { + super("Readiness signing attempt could not be durably pinned"); + } + } + + private static final class DeliveryQuarantinedException extends IllegalStateException { + private DeliveryQuarantinedException() { + super("Readiness probe delivery was ambiguous; the operation was quarantined"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java new file mode 100644 index 0000000000..88acaea9a6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java @@ -0,0 +1,593 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; + +/** + * Account-owned internal invocation boundary for one exact validator Pod and one exact probe. + * + *

The production implementation must route to the observed Pod endpoint, verify the TLS peer + * against its protected Pod-specific pin while retaining the canonical service SAN, and return an + * {@link AuthenticatedAcceptance} only after validating the receiver's production-verifier result + * and local Pod identity. No RPC request or harness DTO is an implementation of this port. + */ +public abstract class AccountJwtReadinessReceiverInvocationPort { + private static final Pattern UUID_V4 = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern UUID_CANONICAL = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,62}"); + private static final Pattern SERVICE_URI = + Pattern.compile( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + + /** Invokes one Pod; implementations must fail closed if any target binding is unavailable. */ + public abstract AuthenticatedAcceptance invoke(Invocation invocation); + + /** Availability guard called before one-shot signing or delivery is durably claimed. */ + public abstract void requireAvailable(); + + /** No remote receiver or Pod-bound transport identity is currently composed. */ + public static AccountJwtReadinessReceiverInvocationPort defaultDenied() { + return new AccountJwtReadinessReceiverInvocationPort() { + @Override + public AuthenticatedAcceptance invoke(Invocation invocation) { + throw new ReceiverUnavailableException(); + } + + @Override + public void requireAvailable() { + throw new ReceiverUnavailableException(); + } + }; + } + + /** Owner-package factory for a response already authenticated by the real Pod-bound client. */ + static AuthenticatedAcceptance authenticatedAcceptance( + String podUid, + String actualPodEndpoint, + String image, + String verifierConfigSha256, + String actualServiceUri, + String actualPeerSpkiSha256, + UUID jti, + String compactTokenSha256, + String verifiedKid, + ProbeExpectation result, + long observedAtEpochSecond) { + return new AuthenticatedAcceptance( + podUid, + actualPodEndpoint, + image, + verifierConfigSha256, + actualServiceUri, + actualPeerSpkiSha256, + jti, + compactTokenSha256, + verifiedKid, + result, + observedAtEpochSecond); + } + + /** Exact, non-secret Pod target derived by Account from one protected inventory snapshot. */ + public record PodTarget( + String inventorySnapshotDigest, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + String validatorId, + String deploymentUid, + String podUid, + String podIp, + String image, + String verifierConfigSha256, + String applicabilityMatrixDigest, + ProbeExpectation expectation, + Optional exactPodEndpoint, + Optional canonicalServiceUri, + Optional podLeafSpkiSha256) { + public PodTarget { + requireDigest(inventorySnapshotDigest, "inventory snapshot digest"); + requireIdentity(environmentId, "environment ID"); + requireCluster(clusterId); + requireCanonicalUuid(clusterIncarnationUid, "cluster incarnation UID"); + requireIdentity(namespace, "Kubernetes namespace"); + requireCanonicalUuid(namespaceUid, "namespace UID"); + requireRevision(apiBindingRevision, "Kubernetes API binding revision"); + requireDigest(apiBindingDigest, "Kubernetes API binding digest"); + requireRevision(inventoryBindingRevision, "inventory binding revision"); + requireDigest(inventoryBindingDigest, "inventory binding digest"); + requireId(validatorId, "validator ID"); + requireCanonicalUuid(deploymentUid, "validator Deployment UID"); + requireCanonicalUuid(podUid, "validator Pod UID"); + if (!AccountJwtValidatorInventoryBinding.canonicalPodIp(podIp).equals(podIp)) { + throw new IllegalArgumentException("Protected validator Pod IP is not canonical"); + } + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Validator image must be pinned by digest"); + } + requireDigest(verifierConfigSha256, "verifier configuration digest"); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + Objects.requireNonNull(expectation, "probe expectation is required"); + exactPodEndpoint = Objects.requireNonNull(exactPodEndpoint); + canonicalServiceUri = Objects.requireNonNull(canonicalServiceUri); + podLeafSpkiSha256 = Objects.requireNonNull(podLeafSpkiSha256); + exactPodEndpoint.ifPresent(endpoint -> requirePodEndpoint(endpoint, podIp)); + canonicalServiceUri.ifPresent(AccountJwtReadinessReceiverInvocationPort::requireServiceUri); + podLeafSpkiSha256.ifPresent(value -> requireDigest(value, "Pod TLS leaf SPKI digest")); + } + + /** Missing addressing or a Pod-specific peer pin makes this target non-invocable. */ + public void requireRoutablePodIdentity() { + if (exactPodEndpoint.isEmpty() + || canonicalServiceUri.isEmpty() + || podLeafSpkiSha256.isEmpty()) { + throw new ReceiverUnavailableException(); + } + } + } + + /** One exact logical registry probe, including transient signed bytes but no signer authority. */ + public static final class Invocation { + private final UUID rotationOperationId; + private final String operationDigest; + private final String planDigest; + private final int planVersion; + private final long planExpiresAtEpochSecond; + private final String validatorId; + private final String tokenProfile; + private final String audience; + private final ProbeKind probeKind; + private final ProbeExpectation expectation; + private final int registryVersion; + private final long sourceEntryVersion; + private final UUID jti; + private final String compactJwt; + private final String compactTokenSha256; + private final String targetGeneration; + private final String targetKid; + private final Optional expectedActiveGeneration; + private final Optional expectedActiveKid; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final PodTarget target; + + Invocation( + UUID rotationOperationId, + String operationDigest, + String planDigest, + int planVersion, + long planExpiresAtEpochSecond, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + ProbeExpectation expectation, + int registryVersion, + long sourceEntryVersion, + UUID jti, + String compactJwt, + String compactTokenSha256, + String targetGeneration, + String targetKid, + Optional expectedActiveGeneration, + Optional expectedActiveKid, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + PodTarget target) { + this.rotationOperationId = Objects.requireNonNull(rotationOperationId); + requireUuid(rotationOperationId.toString(), "rotation operation ID"); + requireDigest(operationDigest, "generation operation digest"); + requireDigest(planDigest, "readiness plan digest"); + if (planVersion != AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION + || planExpiresAtEpochSecond <= 0L) { + throw new IllegalArgumentException("Exact V2 readiness plan coordinates are required"); + } + requireId(validatorId, "validator ID"); + if (tokenProfile == null || !tokenProfile.matches("[a-z][a-z0-9-]{0,127}")) { + throw new IllegalArgumentException("Token profile is malformed"); + } + if (audience == null || !audience.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("Token audience is malformed"); + } + this.operationDigest = operationDigest; + this.planDigest = planDigest; + this.planVersion = planVersion; + this.planExpiresAtEpochSecond = planExpiresAtEpochSecond; + this.validatorId = validatorId; + this.tokenProfile = tokenProfile; + this.audience = audience; + this.probeKind = Objects.requireNonNull(probeKind); + this.expectation = Objects.requireNonNull(expectation); + if (registryVersion != 1 || sourceEntryVersion <= 0L) { + throw new IllegalArgumentException("Readiness entry version is malformed"); + } + this.registryVersion = registryVersion; + this.sourceEntryVersion = sourceEntryVersion; + this.jti = Objects.requireNonNull(jti); + requireUuid(jti.toString(), "probe JTI"); + if (compactJwt == null + || compactJwt.isBlank() + || compactJwt.length() > 16 * 1024 + || !compactJwt.matches("[A-Za-z0-9_=-]+\\.[A-Za-z0-9_=-]+\\.[A-Za-z0-9_=-]+")) { + throw new IllegalArgumentException("Compact readiness token is malformed"); + } + requireDigest(compactTokenSha256, "compact readiness token digest"); + if (!compactTokenSha256.equals(sha256(compactJwt))) { + throw new IllegalArgumentException("Compact readiness token digest does not match bytes"); + } + this.compactJwt = compactJwt; + this.compactTokenSha256 = compactTokenSha256; + if (targetGeneration == null || !targetGeneration.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Target generation is malformed"); + } + if (targetKid == null || !targetKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Target key ID is malformed"); + } + this.targetGeneration = targetGeneration; + this.targetKid = targetKid; + this.expectedActiveGeneration = Objects.requireNonNull(expectedActiveGeneration); + this.expectedActiveKid = Objects.requireNonNull(expectedActiveKid); + if (expectedActiveGeneration.isPresent() != expectedActiveKid.isPresent()) { + throw new IllegalArgumentException("Expected active signer fence is partial"); + } + this.expectedActiveGeneration.ifPresent( + value -> { + if (!value.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Expected active generation is malformed"); + } + }); + this.expectedActiveKid.ifPresent( + value -> { + if (!value.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Expected active key ID is malformed"); + } + }); + if (issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond > planExpiresAtEpochSecond) { + throw new IllegalArgumentException("Readiness token lifetime is malformed"); + } + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + this.target = Objects.requireNonNull(target); + if (!validatorId.equals(target.validatorId())) { + throw new IllegalArgumentException("Readiness probe and Pod validator differ"); + } + } + + public UUID rotationOperationId() { + return rotationOperationId; + } + + public String operationDigest() { + return operationDigest; + } + + public String planDigest() { + return planDigest; + } + + public int planVersion() { + return planVersion; + } + + public long planExpiresAtEpochSecond() { + return planExpiresAtEpochSecond; + } + + public String validatorId() { + return validatorId; + } + + public String tokenProfile() { + return tokenProfile; + } + + public String audience() { + return audience; + } + + public ProbeKind probeKind() { + return probeKind; + } + + public ProbeExpectation expectation() { + return expectation; + } + + public int registryVersion() { + return registryVersion; + } + + public long sourceEntryVersion() { + return sourceEntryVersion; + } + + public UUID jti() { + return jti; + } + + public String compactJwt() { + return compactJwt; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + public String targetGeneration() { + return targetGeneration; + } + + public String targetKid() { + return targetKid; + } + + public Optional expectedActiveGeneration() { + return expectedActiveGeneration; + } + + public Optional expectedActiveKid() { + return expectedActiveKid; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public PodTarget target() { + return target; + } + + @Override + public String toString() { + return "AccountJwtReadinessReceiverInvocation[rotationOperationId=" + + rotationOperationId + + ", validatorId=" + + validatorId + + ", podUid=" + + target.podUid() + + ", jti=" + + jti + + ", tokenRedacted=true]"; + } + } + + public enum ProbeExpectation { + ACCEPT, + INAPPLICABLE_REJECT + } + + /** + * Internal result established by the Account-owned receiver client after mTLS and response + * identity checks. Its package-private constructor is not available to an RPC adapter/harness. + */ + public static final class AuthenticatedAcceptance { + private final String podUid; + private final String actualPodEndpoint; + private final String image; + private final String verifierConfigSha256; + private final String actualServiceUri; + private final String actualPeerSpkiSha256; + private final UUID jti; + private final String compactTokenSha256; + private final String verifiedKid; + private final ProbeExpectation result; + private final long observedAtEpochSecond; + + private AuthenticatedAcceptance( + String podUid, + String actualPodEndpoint, + String image, + String verifierConfigSha256, + String actualServiceUri, + String actualPeerSpkiSha256, + UUID jti, + String compactTokenSha256, + String verifiedKid, + ProbeExpectation result, + long observedAtEpochSecond) { + requireCanonicalUuid(podUid, "receiver-reported local Pod UID"); + requirePodEndpointShape(actualPodEndpoint); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Receiver image is not pinned by digest"); + } + requireDigest(verifierConfigSha256, "receiver verifier configuration digest"); + requireServiceUri(actualServiceUri); + requireDigest(actualPeerSpkiSha256, "authenticated peer SPKI digest"); + Objects.requireNonNull(jti); + requireUuid(jti.toString(), "receiver probe JTI"); + requireDigest(compactTokenSha256, "receiver compact token digest"); + if (verifiedKid == null || !verifiedKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Receiver verified key ID is malformed"); + } + this.result = Objects.requireNonNull(result); + if (observedAtEpochSecond <= 0L) { + throw new IllegalArgumentException("Receiver observation time is malformed"); + } + this.podUid = podUid; + this.actualPodEndpoint = actualPodEndpoint; + this.image = image; + this.verifierConfigSha256 = verifierConfigSha256; + this.actualServiceUri = actualServiceUri; + this.actualPeerSpkiSha256 = actualPeerSpkiSha256; + this.jti = jti; + this.compactTokenSha256 = compactTokenSha256; + this.verifiedKid = verifiedKid; + this.observedAtEpochSecond = observedAtEpochSecond; + } + + public String podUid() { + return podUid; + } + + public String actualPodEndpoint() { + return actualPodEndpoint; + } + + public String image() { + return image; + } + + public String verifierConfigSha256() { + return verifierConfigSha256; + } + + public String actualServiceUri() { + return actualServiceUri; + } + + public String actualPeerSpkiSha256() { + return actualPeerSpkiSha256; + } + + public UUID jti() { + return jti; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + public String verifiedKid() { + return verifiedKid; + } + + public ProbeExpectation result() { + return result; + } + + public long observedAtEpochSecond() { + return observedAtEpochSecond; + } + + @Override + public String toString() { + return "AccountJwtReadinessAuthenticatedAcceptance[podUid=" + + podUid + + ", jti=" + + jti + + ", tokenRedacted=true]"; + } + } + + public static final class ReceiverUnavailableException extends IllegalStateException { + public ReceiverUnavailableException() { + super("Account JWT readiness receiver transport is unavailable"); + } + } + + private static void requirePodEndpoint(URI endpoint, String podIp) { + String endpointHost = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + if (!"grpcs".equals(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() < 1 + || endpoint.getPort() > 65535 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null && !endpoint.getRawPath().isEmpty()) + || !endpoint.toString().equals("grpcs://" + endpointHost + ":" + endpoint.getPort())) { + throw new IllegalArgumentException("Exact Pod endpoint is malformed"); + } + } + + private static void requirePodEndpointShape(String value) { + try { + URI endpoint = URI.create(value); + if (!"grpcs".equals(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() < 1 + || endpoint.getPort() > 65535 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null && !endpoint.getRawPath().isEmpty())) { + throw new IllegalArgumentException("Observed Pod endpoint is malformed"); + } + } catch (RuntimeException failure) { + throw new IllegalArgumentException("Observed Pod endpoint is malformed", failure); + } + } + + private static void requireServiceUri(String value) { + if (value == null || !SERVICE_URI.matcher(value).matches()) { + throw new IllegalArgumentException("Canonical validator service SAN is malformed"); + } + } + + private static void requireDigest(String value, String name) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireUuid(String value, String name) { + if (value == null || !UUID_V4.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireCanonicalUuid(String value, String name) { + if (value == null || !UUID_CANONICAL.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireId(String value, String name) { + if (value == null || !ID.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireIdentity(String value, String name) { + if (value == null || !value.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireCluster(String value) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("cluster ID is malformed"); + } + } + + private static void requireRevision(String value, String name) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static String sha256(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.US_ASCII))); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 is unavailable", failure); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessTransportOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessTransportOwner.java new file mode 100644 index 0000000000..adfba130e2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessTransportOwner.java @@ -0,0 +1,427 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.IssueReadinessProbesRequest; +import net.firedevops.firemud.account.v1.IssueReadinessProbesResponse; +import net.firedevops.firemud.account.v1.ValidateReadinessProbeRequest; +import net.firedevops.firemud.account.v1.ValidateReadinessProbeResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.DeliveryClaim; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ExpectedPod; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeState; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.VerificationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtReadinessTlsInterceptor; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.Invocation; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Account-owned transport orchestration for one-shot, non-authorizing JWT readiness probes. */ +public final class AccountJwtReadinessTransportOwner { + private static final int SCHEMA_VERSION = 1; + private static final String VALIDATOR_ID = "account-service"; + private static final int MAX_COMPACT_TOKEN_BYTES = 16 * 1024; + + private final AccountJwtReadinessProbeRepository repository; + private final AccountJwtReadinessProbeService probeProducer; + private final AccountJwtReadinessValidationService validationService; + private final TransactionTemplate accountTransaction; + private final Clock clock; + private final AccountJwtReadinessReceiverInvocationPort receiverInvocationPort; + + public AccountJwtReadinessTransportOwner( + AccountJwtReadinessProbeRepository repository, + AccountJwtReadinessProbeService probeProducer, + AccountJwtReadinessValidationService validationService, + PlatformTransactionManager transactionManager) { + this( + repository, + probeProducer, + validationService, + writableTransaction(transactionManager), + Clock.systemUTC(), + AccountJwtReadinessReceiverInvocationPort.defaultDenied()); + } + + public AccountJwtReadinessTransportOwner( + AccountJwtReadinessProbeRepository repository, + AccountJwtReadinessProbeService probeProducer, + AccountJwtReadinessValidationService validationService, + PlatformTransactionManager transactionManager, + AccountJwtReadinessReceiverInvocationPort receiverInvocationPort) { + this( + repository, + probeProducer, + validationService, + writableTransaction(transactionManager), + Clock.systemUTC(), + receiverInvocationPort); + } + + AccountJwtReadinessTransportOwner( + AccountJwtReadinessProbeRepository repository, + AccountJwtReadinessProbeService probeProducer, + AccountJwtReadinessValidationService validationService, + TransactionTemplate accountTransaction, + Clock clock) { + this( + repository, + probeProducer, + validationService, + accountTransaction, + clock, + AccountJwtReadinessReceiverInvocationPort.defaultDenied()); + } + + AccountJwtReadinessTransportOwner( + AccountJwtReadinessProbeRepository repository, + AccountJwtReadinessProbeService probeProducer, + AccountJwtReadinessValidationService validationService, + TransactionTemplate accountTransaction, + Clock clock, + AccountJwtReadinessReceiverInvocationPort receiverInvocationPort) { + this.repository = Objects.requireNonNull(repository); + this.probeProducer = Objects.requireNonNull(probeProducer); + this.validationService = Objects.requireNonNull(validationService); + this.accountTransaction = Objects.requireNonNull(accountTransaction); + this.accountTransaction.setReadOnly(false); + this.clock = Objects.requireNonNull(clock); + this.receiverInvocationPort = Objects.requireNonNull(receiverInvocationPort); + } + + /** Plans and delivers one exact readiness batch after durably claiming its only delivery. */ + public IssueReadinessProbesResponse issue( + IssueReadinessProbesRequest request, + AccountJwtReadinessTlsInterceptor.AuthenticatedCaller authenticatedCaller) { + requireExactIssueRequest(request); + Binding readinessBinding = validationService.requireAuthenticatedBinding(authenticatedCaller); + var signerBinding = validationService.requireCurrentSignerBinding(readinessBinding); + validationService.requireBindingsUnchanged( + readinessBinding, signerBinding, authenticatedCaller); + + var binding = signerBinding.accountBinding(); + TrustFence trustFence = AccountJwtReadinessValidationService.trustFence(signerBinding); + ReadinessProbePlan plan = probeProducer.planCurrent(binding, trustFence); + if (plan.validatorInventoryComplete()) { + if (plan.planVersion() != AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION) { + throw new TransportUnavailableException(); + } + // Do not sign, claim, or transiently deliver a complete-fleet plan until the real Pod-bound + // receiver client is composed. The default implementation is explicitly unavailable. + receiverInvocationPort.requireAvailable(); + } + + // This is deliberately a separate short SQL transaction. No signer or file work occurs while + // the durable, irreversible one-shot claim is being committed. + Instant claimedAt = clock.instant(); + DeliveryClaim claim = + accountTransaction.execute( + status -> + repository.claimSingleDelivery( + binding, + trustFence, + plan, + readinessBinding, + authenticatedCaller.peer(), + claimedAt)); + if (claim == null) { + throw new TransportUnavailableException(); + } + + validationService.requireBindingsUnchanged( + readinessBinding, signerBinding, authenticatedCaller); + + Map transientProbes = new HashMap<>(); + List issuedEntries = + probeProducer.issueCurrentPlan( + binding, + trustFence, + plan.operationId(), + claim, + (metadata, exactCompactJwt) -> { + TransientProbe previous = + transientProbes.putIfAbsent( + metadata.jti(), new TransientProbe(metadata, compactJwt(exactCompactJwt))); + if (previous != null) { + throw new TransportUnavailableException(); + } + }); + + boolean perPodClosureComplete = false; + if (plan.validatorInventoryComplete()) { + invokeEveryExpectedPod(binding, trustFence, plan, issuedEntries, transientProbes); + ReadinessProbePlan latest = + probeProducer.readCurrentPlan(binding, trustFence, plan.operationId()); + perPodClosureComplete = exactPerPodClosure(plan, latest); + if (!perPodClosureComplete) { + throw new TransportUnavailableException(); + } + } + + validationService.requireBindingsUnchanged( + readinessBinding, signerBinding, authenticatedCaller); + return response(plan, issuedEntries, transientProbes, perPodClosureComplete); + } + + /** Records only the production verifier's exact, non-authorizing receipt. */ + public ValidateReadinessProbeResponse validate( + ValidateReadinessProbeRequest request, + AccountJwtReadinessTlsInterceptor.AuthenticatedCaller authenticatedCaller) { + if (request == null + || request.getSchemaVersion() != SCHEMA_VERSION + || !request.getUnknownFields().asMap().isEmpty()) { + throw new AccountJwtReadinessValidationService.InvalidReadinessRequestException(); + } + VerificationReceipt receipt = validationService.validate(request, authenticatedCaller); + return ValidateReadinessProbeResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setResult(ValidateReadinessProbeResponse.Result.NON_AUTHORIZING_VERIFICATION_RECORDED) + .setReceiptVersion(receipt.receiptVersion()) + .setReceiptSha256(receipt.receiptSha256()) + .setObservedAtEpochSeconds(receipt.observedAtEpochSecond()) + .setValidatorId(VALIDATOR_ID) + .setValidatorInstanceId(receipt.validatorInstanceId()) + .build(); + } + + private static void requireExactIssueRequest(IssueReadinessProbesRequest request) { + if (request == null + || request.getSchemaVersion() != SCHEMA_VERSION + || !request.getUnknownFields().asMap().isEmpty()) { + throw new AccountJwtReadinessValidationService.InvalidReadinessRequestException(); + } + } + + private static IssueReadinessProbesResponse response( + ReadinessProbePlan plan, + List issuedEntries, + Map transientProbes, + boolean perPodClosureComplete) { + if (plan.validatorInventoryComplete() != perPodClosureComplete + || issuedEntries.size() != plan.entries().size() + || transientProbes.size() != plan.entries().size()) { + throw new TransportUnavailableException(); + } + Map issuedByJti = new HashMap<>(); + for (ProbeEntry entry : issuedEntries) { + if (issuedByJti.putIfAbsent(entry.jti(), entry) != null) { + throw new TransportUnavailableException(); + } + } + + var response = + IssueReadinessProbesResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setRotationOperationId(plan.operationId().toString()) + .setPlanDigest(plan.planDigest()) + .setPlanVersion(plan.planVersion()) + .setPlannedAtEpochSeconds(plan.plannedAtEpochSecond()) + .setNotBeforeEpochSeconds(plan.notBeforeEpochSecond()) + .setExpiresAtEpochSeconds(plan.expiresAtEpochSecond()) + .setTargetGeneration(plan.targetGeneration()) + .setTargetKid(plan.targetKid()) + .setValidatorInventoryComplete(plan.validatorInventoryComplete()); + plan.expectedFence() + .durableActive() + .ifPresent( + active -> + response.setExpectedActive( + IssueReadinessProbesResponse.ActiveSignerFence.newBuilder() + .setGeneration(active.generation()) + .setKid(active.kid()) + .build())); + + for (ProbeEntry planned : plan.entries()) { + ProbeEntry issued = issuedByJti.get(planned.jti()); + TransientProbe transientProbe = transientProbes.get(planned.jti()); + if (issued == null + || transientProbe == null + || issued.state() != ProbeState.ISSUED + || !matchesPlanEntry(plan, planned, issued) + || !matchesDelivery(plan, issued, transientProbe.metadata()) + || !issued + .compactTokenSha256() + .equals(java.util.Optional.of(transientProbe.metadata().compactTokenSha256()))) { + throw new TransportUnavailableException(); + } + response.addProbes(toResponseProbe(issued, transientProbe)); + } + return response.build(); + } + + private void invokeEveryExpectedPod( + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .Binding + binding, + TrustFence trustFence, + ReadinessProbePlan plan, + List issuedEntries, + Map transientProbes) { + for (ProbeEntry entry : issuedEntries) { + TransientProbe transientProbe = transientProbes.get(entry.jti()); + if (transientProbe == null || entry.state() != ProbeState.ISSUED) { + throw new TransportUnavailableException(); + } + List targets = probeProducer.readCurrentExpectedPods(binding, trustFence, entry); + if (targets.isEmpty() + || targets.size() > AccountJwtReadinessProbeRepository.MAX_POD_RECEIPTS_PER_OPERATION) { + throw new TransportUnavailableException(); + } + for (ExpectedPod expectedPod : targets) { + var target = expectedPod.target(); + target.requireRoutablePodIdentity(); + Invocation invocation = + new Invocation( + plan.operationId(), + plan.operationDigest(), + plan.planDigest(), + plan.planVersion(), + plan.expiresAtEpochSecond(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + target.expectation(), + entry.registryVersion(), + entry.entryVersion(), + entry.jti(), + transientProbe.compactJwt(), + transientProbe.metadata().compactTokenSha256(), + entry.targetGeneration(), + entry.targetKid(), + entry.expectedActive().map(value -> value.generation()), + entry.expectedActive().map(value -> value.kid()), + entry.plannedIssuedAtEpochSecond(), + entry.expiresAtEpochSecond(), + target); + AuthenticatedAcceptance acceptance = receiverInvocationPort.invoke(invocation); + probeProducer.recordPodAcceptance(binding, trustFence, entry, expectedPod, acceptance); + } + } + } + + private static boolean exactPerPodClosure( + ReadinessProbePlan expected, ReadinessProbePlan actual) { + return actual != null + && actual.planVersion() == AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION + && actual.validatorInventoryComplete() + && actual.operationId().equals(expected.operationId()) + && actual.operationDigest().equals(expected.operationDigest()) + && actual.planDigest().equals(expected.planDigest()) + && actual.entries().size() == expected.entries().size() + && actual.entries().stream() + .allMatch( + entry -> + entry.state() == ProbeState.VERIFIED + && entry + .verificationReceipt() + .filter(receipt -> receipt.receiptVersion() == 2) + .filter( + receipt -> + receipt.podReceiptCount() > 0 + && receipt + .podReceiptClosureSha256() + .equals(receipt.receiptSha256())) + .isPresent()); + } + + private static boolean matchesPlanEntry( + ReadinessProbePlan plan, ProbeEntry planned, ProbeEntry issued) { + return issued.rotationOperationId().equals(plan.operationId()) + && issued.planDigest().equals(plan.planDigest()) + && issued.validatorId().equals(planned.validatorId()) + && issued.tokenProfile().equals(planned.tokenProfile()) + && issued.audience().equals(planned.audience()) + && issued.probeKind() == planned.probeKind() + && issued.jti().equals(planned.jti()) + && issued.targetGeneration().equals(plan.targetGeneration()) + && issued.targetKid().equals(plan.targetKid()) + && issued.expectedActive().equals(planned.expectedActive()) + && issued.registryVersion() == planned.registryVersion() + && issued.plannedIssuedAtEpochSecond() == planned.plannedIssuedAtEpochSecond() + && issued.expiresAtEpochSecond() == planned.expiresAtEpochSecond(); + } + + private static boolean matchesDelivery( + ReadinessProbePlan plan, + ProbeEntry issued, + AccountJwtReadinessProbeService.DeliveryMetadata metadata) { + return metadata.operationId().equals(issued.rotationOperationId()) + && metadata.planDigest().equals(issued.planDigest()) + && metadata.planVersion() == plan.planVersion() + && metadata.validatorId().equals(issued.validatorId()) + && metadata.tokenProfile().equals(issued.tokenProfile()) + && metadata.audience().equals(issued.audience()) + && metadata.probeKind() == issued.probeKind() + && metadata.jti().equals(issued.jti()) + && metadata.targetGeneration().equals(issued.targetGeneration()) + && metadata.targetKid().equals(issued.targetKid()) + && metadata.registryVersion() == issued.registryVersion() + && metadata.entryVersion() == issued.entryVersion() + && metadata.issuedAtEpochSecond() == issued.plannedIssuedAtEpochSecond() + && metadata.expiresAtEpochSecond() == issued.expiresAtEpochSecond() + && metadata + .expectedActiveGeneration() + .equals(issued.expectedActive().map(value -> value.generation())) + && metadata.expectedActiveKid().equals(issued.expectedActive().map(value -> value.kid())); + } + + private static IssueReadinessProbesResponse.Probe toResponseProbe( + ProbeEntry issued, TransientProbe transientProbe) { + var builder = + IssueReadinessProbesResponse.Probe.newBuilder() + .setValidatorId(issued.validatorId()) + .setTokenProfile(issued.tokenProfile()) + .setAudience(issued.audience()) + .setProbeKind(issued.probeKind().name()) + .setJti(issued.jti().toString()) + .setTargetGeneration(issued.targetGeneration()) + .setTargetKid(issued.targetKid()) + .setRegistryVersion(issued.registryVersion()) + .setEntryVersion(issued.entryVersion()) + .setIssuedAtEpochSeconds(issued.plannedIssuedAtEpochSecond()) + .setExpiresAtEpochSeconds(issued.expiresAtEpochSecond()) + .setCompactTokenSha256(transientProbe.metadata().compactTokenSha256()) + .setCompactJwt(transientProbe.compactJwt()); + return builder.build(); + } + + private static String compactJwt(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_COMPACT_TOKEN_BYTES) { + throw new TransportUnavailableException(); + } + for (byte value : bytes) { + if (value <= 0 || value > 0x7f) { + throw new TransportUnavailableException(); + } + } + return new String(bytes, StandardCharsets.US_ASCII); + } + + private static TransactionTemplate writableTransaction( + PlatformTransactionManager transactionManager) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setReadOnly(false); + return transaction; + } + + private record TransientProbe( + AccountJwtReadinessProbeService.DeliveryMetadata metadata, String compactJwt) {} + + public static final class TransportUnavailableException extends IllegalStateException { + public TransportUnavailableException() { + super("Account JWT readiness transport is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessValidationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessValidationService.java new file mode 100644 index 0000000000..b7c00e090f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessValidationService.java @@ -0,0 +1,372 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ValidateReadinessProbeRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.PeerIdentity; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.VerificationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.VerifiedProbeObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtReadinessTlsInterceptor; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Owner-internal, non-authorizing verification of one exact current Account readiness probe. + * + *

The only authenticated-caller value is created by the dedicated TLS interceptor. Both trust + * bindings are reread before recording the observation. This service creates no principal, + * SessionContext, authorization decision, application call, or fleet-completion evidence. + */ +@Service +@ConditionalOnProperty( + prefix = "firemud.account.jwt-readiness.validation", + name = "enabled", + havingValue = "true") +public final class AccountJwtReadinessValidationService { + private static final int SCHEMA_VERSION = 1; + private static final int MAX_COMPACT_TOKEN_BYTES = 16 * 1024; + private static final String CANARY_PROFILE = AccountJwtReadinessProbeCrypto.CANARY_PROFILE; + private static final String CANARY_AUDIENCE = AccountJwtReadinessProbeCrypto.CANARY_AUDIENCE; + private static final String VALIDATOR_ID = AccountJwtReadinessProbeCrypto.VALIDATOR_ID; + private static final Map + REPRESENTATIVE_PROFILES = AccountJwtReadinessProbeCrypto.representativeProfiles(); + + private final AccountJwtReadinessProbeRepository repository; + private final AccountJwtReadinessTrustBinding readinessTrustBinding; + private final AccountJwtSignerMaterializerTrustBinding signerTrustBinding; + private final AccountAsymmetricJwtVerifier verifier; + private final TransactionTemplate accountTransaction; + private final Clock clock; + private final int maxControlUiTenantScopes; + + @Autowired + public AccountJwtReadinessValidationService( + AccountJwtReadinessProbeRepository repository, + AccountJwtReadinessTrustBinding readinessTrustBinding, + AccountJwtSignerMaterializerTrustBinding signerTrustBinding, + AccountJwtJwksTrustedSource trustedJwksSource, + PlatformTransactionManager transactionManager, + @Value("${firemud.account.jwt-readiness.validation.max-control-ui-tenant-scopes}") + int maxControlUiTenantScopes) { + this( + repository, + readinessTrustBinding, + signerTrustBinding, + createVerifier(trustedJwksSource, Clock.systemUTC()), + new TransactionTemplate(transactionManager), + Clock.systemUTC(), + maxControlUiTenantScopes); + } + + AccountJwtReadinessValidationService( + AccountJwtReadinessProbeRepository repository, + AccountJwtReadinessTrustBinding readinessTrustBinding, + AccountJwtSignerMaterializerTrustBinding signerTrustBinding, + AccountAsymmetricJwtVerifier verifier, + TransactionTemplate accountTransaction, + Clock clock, + int maxControlUiTenantScopes) { + this.repository = Objects.requireNonNull(repository); + this.readinessTrustBinding = Objects.requireNonNull(readinessTrustBinding); + this.signerTrustBinding = Objects.requireNonNull(signerTrustBinding); + this.verifier = Objects.requireNonNull(verifier); + this.accountTransaction = Objects.requireNonNull(accountTransaction); + this.accountTransaction.setReadOnly(false); + this.clock = Objects.requireNonNull(clock); + if (maxControlUiTenantScopes <= 0 + || maxControlUiTenantScopes + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw new IllegalArgumentException( + "Control UI readiness tenant-scope bound is missing or transport-incompatible"); + } + this.maxControlUiTenantScopes = maxControlUiTenantScopes; + } + + /** Verifies the exact signed probe and persists only a non-authorizing receipt. */ + public VerificationReceipt validate( + ValidateReadinessProbeRequest request, + AccountJwtReadinessTlsInterceptor.AuthenticatedCaller authenticatedCaller) { + Objects.requireNonNull(request, "Readiness request is required"); + Binding readinessBinding = requireAuthenticatedBinding(authenticatedCaller); + RequestSelector selector = parseRequest(request); + var signerBinding = requireCurrentSignerBinding(readinessBinding); + AccountJwtReadinessProbeRepository.ProbeEntry current = + accountTransaction.execute( + status -> + repository.readCurrentEntry( + signerBinding.accountBinding(), + trustFence(signerBinding), + selector.operationId(), + selector.validatorId(), + selector.tokenProfile(), + selector.audience(), + selector.probeKind(), + selector.jti())); + if (current == null) { + throw new ValidationUnavailableException(); + } + long nowEpochSecond = nowEpochSecond(); + if (current.state() != AccountJwtReadinessProbeRepository.ProbeState.ISSUED + && current.state() != AccountJwtReadinessProbeRepository.ProbeState.VERIFIED) { + throw new ProbeNotIssuedException(); + } + if (nowEpochSecond < current.plannedIssuedAtEpochSecond()) { + throw new AccountJwtReadinessProbeRepository.CacheAgeNotElapsedException(); + } + if (nowEpochSecond >= current.expiresAtEpochSecond()) { + throw new AccountJwtReadinessProbeRepository.ProbeExpiredException(); + } + + String compactJwt = request.getCompactJwt(); + byte[] compactBytes = compactJwt.getBytes(StandardCharsets.US_ASCII); + String compactHash = sha256(compactBytes); + try { + if (!current.compactTokenSha256().equals(Optional.of(compactHash))) { + throw new AccountJwtReadinessProbeRepository.IdempotencyConflictException( + "Readiness probe differs from its owner-recorded issuance"); + } + VerifiedClaims verified = + AccountJwtReadinessProbeCrypto.verify( + verifier, + compactJwt, + AccountJwtReadinessProbeCrypto.expectedProbe( + selector.probeKind(), + selector.tokenProfile(), + selector.audience(), + selector.jti().toString(), + current.targetKid(), + current.plannedIssuedAtEpochSecond(), + current.expiresAtEpochSecond()), + maxControlUiTenantScopes); + + PeerIdentity peer = authenticatedCaller.peer(); + VerifiedProbeObservation observation = + new VerifiedProbeObservation( + compactHash, + verified.keyId(), + readinessBinding.validatorInstanceId(), + readinessBinding.bindingDigest(), + readinessBinding.configRevision(), + peer.uri(), + peer.spkiSha256(), + nowEpochSecond()); + return accountTransaction.execute( + status -> { + requireBindingsUnchanged(readinessBinding, signerBinding, authenticatedCaller); + VerificationReceipt result = + repository + .recordVerified( + signerBinding.accountBinding(), + trustFence(signerBinding), + selector.operationId(), + selector.validatorId(), + selector.tokenProfile(), + selector.audience(), + selector.probeKind(), + selector.jti(), + observation) + .verificationReceipt() + .orElseThrow(ValidationUnavailableException::new); + requireBindingsUnchanged(readinessBinding, signerBinding, authenticatedCaller); + return result; + }); + } finally { + java.util.Arrays.fill(compactBytes, (byte) 0); + } + } + + Binding requireAuthenticatedBinding( + AccountJwtReadinessTlsInterceptor.AuthenticatedCaller authenticatedCaller) { + if (authenticatedCaller == null) { + throw new ReadinessCallerRejectedException(); + } + Binding current = + readinessTrustBinding.current().orElseThrow(ReadinessCallerRejectedException::new); + if (!current.equals(authenticatedCaller.binding()) + || !current.isCurrentAt(nowEpochSecond()) + || !current.matches(authenticatedCaller.peer())) { + throw new ReadinessCallerRejectedException(); + } + return current; + } + + AccountJwtSignerMaterializerTrustBinding.Binding requireCurrentSignerBinding( + Binding readinessBinding) { + var signerBinding = + signerTrustBinding.current().orElseThrow(ValidationUnavailableException::new); + if (!readinessBinding.environmentId().equals(signerBinding.environmentId()) + || !readinessBinding.clusterId().equals(signerBinding.clusterId()) + || !readinessBinding.namespace().equals(signerBinding.namespace()) + || !readinessBinding + .expectedClusterIncarnationUid() + .equals(signerBinding.expectedClusterIncarnationUid()) + || !readinessBinding.expectedNamespaceUid().equals(signerBinding.expectedNamespaceUid())) { + throw new ReadinessCallerRejectedException(); + } + return signerBinding; + } + + void requireBindingsUnchanged( + Binding readinessBinding, + AccountJwtSignerMaterializerTrustBinding.Binding signerBinding, + AccountJwtReadinessTlsInterceptor.AuthenticatedCaller authenticatedCaller) { + Binding latestReadiness = + readinessTrustBinding.current().orElseThrow(ReadinessCallerRejectedException::new); + var latestSigner = + signerTrustBinding.current().orElseThrow(ValidationUnavailableException::new); + if (!readinessBinding.equals(latestReadiness) + || !signerBinding.equals(latestSigner) + || !latestReadiness.equals(authenticatedCaller.binding()) + || !latestReadiness.matches(authenticatedCaller.peer()) + || !latestReadiness.isCurrentAt(nowEpochSecond())) { + throw new ReadinessCallerRejectedException(); + } + requireCurrentSignerBinding(latestReadiness); + } + + private RequestSelector parseRequest(ValidateReadinessProbeRequest request) { + if (request.getSchemaVersion() != SCHEMA_VERSION + || !request.getUnknownFields().asMap().isEmpty() + || request.getCompactJwt().isEmpty() + || request.getCompactJwt().length() > MAX_COMPACT_TOKEN_BYTES + || !isAscii(request.getCompactJwt())) { + throw new InvalidReadinessRequestException(); + } + UUID operationId = canonicalUuid(request.getRotationOperationId()); + UUID jti = canonicalUuid(request.getJti()); + ProbeKind kind; + try { + kind = ProbeKind.valueOf(request.getProbeKind()); + } catch (RuntimeException invalidKind) { + throw new InvalidReadinessRequestException(); + } + String profile; + String audience; + if (kind == ProbeKind.CANARY) { + profile = CANARY_PROFILE; + audience = CANARY_AUDIENCE; + } else { + profile = request.getTokenProfile(); + AccountJwtReadinessProbeCrypto.ProfileDescriptor descriptor = + REPRESENTATIVE_PROFILES.get(profile); + if (descriptor == null) { + throw new InvalidReadinessRequestException(); + } + audience = descriptor.audience(); + } + if (!VALIDATOR_ID.equals(request.getValidatorId()) + || !profile.equals(request.getTokenProfile()) + || !audience.equals(request.getAudience())) { + throw new InvalidReadinessRequestException(); + } + return new RequestSelector( + operationId, + request.getValidatorId(), + request.getTokenProfile(), + request.getAudience(), + kind, + jti); + } + + private static UUID canonicalUuid(String value) { + try { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value) || uuid.version() != 4 || uuid.variant() != 2) { + throw new InvalidReadinessRequestException(); + } + return uuid; + } catch (RuntimeException invalidUuid) { + throw new InvalidReadinessRequestException(); + } + } + + private static boolean isAscii(String value) { + for (int index = 0; index < value.length(); index++) { + if (value.charAt(index) > 0x7f) { + return false; + } + } + return true; + } + + long nowEpochSecond() { + long value = clock.instant().getEpochSecond(); + if (value <= 0L) { + throw new ValidationUnavailableException(); + } + return value; + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException unavailable) { + throw new ValidationUnavailableException(); + } + } + + static TrustFence trustFence(AccountJwtSignerMaterializerTrustBinding.Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private static AccountAsymmetricJwtVerifier createVerifier( + AccountJwtJwksTrustedSource trustedSource, Clock clock) { + return AccountJwtReadinessProbeCrypto.createVerifier(trustedSource, clock); + } + + public static final class InvalidReadinessRequestException extends IllegalArgumentException { + public InvalidReadinessRequestException() { + super("Readiness validation request is invalid"); + } + } + + public static final class ReadinessCallerRejectedException extends SecurityException { + public ReadinessCallerRejectedException() { + super("Authenticated readiness caller is unavailable"); + } + } + + public static final class ProbeNotIssuedException extends IllegalStateException { + public ProbeNotIssuedException() { + super("Readiness probe is not owner-recorded as issued"); + } + } + + public static final class ValidationUnavailableException extends IllegalStateException { + public ValidationUnavailableException() { + super("Readiness validation evidence is unavailable"); + } + } + + private record RequestSelector( + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java new file mode 100644 index 0000000000..1278db60f7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java @@ -0,0 +1,1115 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedPromotion; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionPreparation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicit Account-owned enrollment and durable-generation reconciliation for interim JWT signer + * materialization. + * + *

This coordinator is not scheduled or run at application startup. Enrollment derives only from + * Account's protected materializer binding, protected JWKS API binding, and a live observation of + * the fixed public ConfigMap. Enrollment initializes the short Account state row without selecting + * a generation request. Durable-generation reconciliation reads only an already selected request. + * Those two bootstrap paths do not commit signer promotion or treat mounted correspondence as + * validator readiness; the separate prepared-promotion path below requires the private receipt and + * complete current readiness evidence before it owns the public ACTIVE CAS and durable commit. + */ +public final class AccountJwtSignerBootstrapCoordinator { + private static final String JWKS_DATA_KEY = AccountJwtJwksPublicationRepository.JWKS_DATA_KEY; + + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtJwksConfigMapClient configMapClient; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPrepublicationService prepublicationService; + private final AccountJwtReadinessProbeRepository readinessRepository; + private final ObjectProvider inventorySourceProvider; + private final TransactionTemplate accountTransaction; + + public AccountJwtSignerBootstrapCoordinator( + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksConfigMapClient configMapClient, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPrepublicationService prepublicationService, + TransactionTemplate accountTransaction) { + this( + materializerTrustBinding, + configMapClient, + desiredStateRepository, + prepublicationService, + null, + null, + accountTransaction); + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The Account readiness repository is a live Spring owner used for transactional proof reads.") + public AccountJwtSignerBootstrapCoordinator( + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksConfigMapClient configMapClient, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPrepublicationService prepublicationService, + AccountJwtReadinessProbeRepository readinessRepository, + ObjectProvider inventorySourceProvider, + TransactionTemplate accountTransaction) { + this.materializerTrustBinding = + Objects.requireNonNull( + materializerTrustBinding, "Protected materializer trust is required"); + this.configMapClient = + Objects.requireNonNull(configMapClient, "Protected JWKS client is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Account signer repository is required"); + this.prepublicationService = + Objects.requireNonNull(prepublicationService, "Account prepublication owner is required"); + this.readinessRepository = readinessRepository; + this.inventorySourceProvider = inventorySourceProvider; + this.accountTransaction = + Objects.requireNonNull(accountTransaction, "Account transaction template is required"); + this.accountTransaction.setReadOnly(false); + } + + /** + * Performs only the authenticated, finite enrollment step. It does not select a generation + * request, advance a signer phase, publish JWKS, or inspect mounted private material. + */ + public EnrollmentAcknowledgement enrollOnce() { + EnrollmentSources sources = captureEnrollmentSources(); + DesiredState initialized = initializeEnrollment(sources); + EnrollmentIdentity enrolled = + initialized + .enrollmentIdentity() + .orElseThrow( + () -> new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS)); + return acknowledgement(sources.materializerBinding(), sources.apiIdentity(), enrolled); + } + + /** + * Reconciles publication and mounted correspondence for the exact current generated receipt. The + * authenticated RPC owner calls this only after its short generation-read transaction has + * returned {@code GENERATION_RECORDED}; this method never creates a new operation. + */ + public BootstrapProgress reconcileCurrentGenerationOnce(UUID expectedOperationId) { + Objects.requireNonNull(expectedOperationId, "Expected generation operation is required"); + EnrollmentSources sources = captureEnrollmentSources(); + GenerationRequest request = readCurrentGenerationRequest(sources); + if (!expectedOperationId.equals(request.operationId()) + || request.phase() != GenerationPhase.GENERATION_RECORDED) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH); + } + return reconcileSelectedGeneration(sources, request); + } + + /** + * Enters PREPARED only for the exact current durable generation after refreshed publication, + * mounted correspondence, and owner-verified live validator closure. The materializer's + * authenticated promotion-request RPC is the only production caller. All API, filesystem, and + * Kubernetes reads finish before the short Account transaction that obtains the private proof and + * performs the owner CAS. + */ + public Optional prepareCurrentPromotionOnce() { + if (readinessRepository == null || inventorySourceProvider == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + EnrollmentSources sources = captureEnrollmentSources(); + DesiredState enrolled = readEnrollmentState(sources); + if (enrolled.generationOperationId().isEmpty()) { + requireUnselectedInitialEnrollment(enrolled, sources); + requireUnchangedProtectedBindings(sources); + return Optional.empty(); + } + GenerationRequest request = readCurrentGenerationRequest(sources); + if (request.phase() != GenerationPhase.GENERATION_RECORDED) { + if (request.phase() == GenerationPhase.OBSERVE_PRIVATE_SECRET + || request.phase() == GenerationPhase.GENERATE_PENDING) { + requireUnchangedProtectedBindings(sources); + return Optional.empty(); + } + throw new BootstrapOperationException(FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH); + } + + BootstrapProgress refreshed = reconcileSelectedGeneration(sources, request); + if (refreshed.stage() != Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE + || !refreshed.publicKeyPrepublished() + || !refreshed.mountedKeyCorrespondence()) { + return Optional.empty(); + } + + InventorySnapshot liveInventory = observeCurrentValidatorInventory(sources, request); + requireUnchangedProtectedBindings(sources); + PreparedPromotion prepared = + accountTransaction.execute( + status -> { + requireUnchangedProtectedBindings(sources); + var proof = + readinessRepository.readCurrentPromotionPrerequisites( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding()), + request.operationId(), + liveInventory); + if (proof.isEmpty()) { + return null; + } + ReadinessPromotionProof verifiedProof = proof.orElseThrow(); + DesiredState state = + desiredStateRepository.read(sources.materializerBinding().accountBinding()); + EnrollmentIdentity enrollment = + state + .enrollmentIdentity() + .orElseThrow( + () -> + new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS)); + var publication = verifiedProof.publication(); + PromotionPreparation preparation = + new PromotionPreparation( + verifiedProof.generationResult().operationId(), + verifiedProof.generationResult(), + enrollment, + publication.intent().apiBindingDigest(), + publication.intent().apiConfigRevision(), + publication.intent().configMapUid(), + publication.receipt().observedResourceVersion(), + publication.intent().intentDigest(), + publication.receipt().receiptDigest(), + publication.mountedCorrespondence().observationDigest(), + verifiedProof.plan().planDigest(), + verifiedProof.readinessEvidenceDigest(), + publication.intent().jwksJson()); + PreparedPromotion persisted = + desiredStateRepository.prepareCurrentGeneration( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding()), + preparation, + verifiedProof); + requireUnchangedProtectedBindings(sources); + return persisted; + }); + if (prepared == null) { + return Optional.empty(); + } + requireUnchangedProtectedBindings(sources); + if (!prepared.operationId().equals(request.operationId()) + || !"PREPARED".equals(prepared.status())) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + return Optional.of(prepared); + } + + /** + * Completes only the exact Account PREPARED operation whose authenticated private-slot receipt + * has already been recorded. Account owns the public ConfigMap ACTIVE CAS and terminal durable + * commit; this finite call is never started at boot or by a scheduler. + */ + public void reconcilePreparedPromotionOnce( + PrivatePromotionObservation observation, PrivatePromotionReceipt expectedReceipt) { + Objects.requireNonNull(observation, "Exact private promotion observation is required"); + Objects.requireNonNull(expectedReceipt, "Durable private promotion receipt is required"); + Binding binding = currentMaterializerBinding(); + BindingIdentity apiIdentity = currentApiIdentity(); + requireMatchingProtectedPins(binding, apiIdentity); + requireReceiptIdentity(observation, expectedReceipt); + + PromotionOwnerSnapshot start = + readPromotionOwnerSnapshot(binding, apiIdentity, observation, expectedReceipt); + requireUnchangedProtectedBindings(binding, apiIdentity); + if (!expectedReceipt.equals(start.privateReceipt())) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account private promotion receipt changed during reconciliation"); + } + if (start.committedEvidence() != null) { + return; + } + if (readinessRepository == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + + PreparedGenerationEvidence prepared = start.preparedEvidence(); + PromotionOperationEvidence promotion = prepared.promotion(); + ObservationContext context = observationContext(promotion); + InventorySnapshot beforeInventory = observePreparedInventory(context); + requireUnchangedProtectedBindings(binding, apiIdentity); + + ConfigMapSnapshot observedConfigMap = + prepublicationService.observePreparedCurrentKeyCorrespondence(promotion); + requireUnchangedProtectedBindings(binding, apiIdentity); + + readPreparedPromotionProof( + binding, apiIdentity, observation, expectedReceipt, promotion, beforeInventory); + requireUnchangedProtectedBindings(binding, apiIdentity); + requireExpectedPublicSnapshot(promotion, observedConfigMap); + requireUnchangedProtectedBindings(binding, apiIdentity); + + CasObservation activeReadback = + configMapClient.publishActiveProjection( + observedConfigMap, + promotion.expectedPublicResourceVersion(), + java.util.Map.of( + JWKS_DATA_KEY, + promotion.expectedPublicJwksJson(), + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + promotion.expectedActiveMarkerJson())); + requireExactActiveReadback(promotion, activeReadback); + requireUnchangedProtectedBindings(binding, apiIdentity); + + ActiveJwksPromotionObservation activeObservation = + new ActiveJwksPromotionObservation( + activeReadback.uid(), + activeReadback.priorResourceVersion(), + activeReadback.resourceVersion(), + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson()); + ActiveJwksPromotionReceipt activeReceipt = + accountTransaction.execute( + status -> { + PrivatePromotionReceipt currentPrivateReceipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trustFence(binding), observation); + if (!expectedReceipt.equals(currentPrivateReceipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Original private promotion receipt changed before ACTIVE readback recording"); + } + return desiredStateRepository.recordActiveJwksPromotionResult( + binding.accountBinding(), trustFence(binding), activeObservation); + }); + if (activeReceipt == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account ACTIVE JWKS receipt is unavailable"); + } + requireUnchangedProtectedBindings(binding, apiIdentity); + if (!activeReceipt.promotionOperationId().equals(promotion.operationId()) + || !activeReceipt.configMapUid().equals(promotion.publicConfigMapUid()) + || !activeReceipt.priorResourceVersion().equals(promotion.expectedPublicResourceVersion()) + || !activeReceipt.observedResourceVersion().equals(activeReadback.resourceVersion()) + || !activeReceipt + .publicDataDigest() + .equals( + AccountJwtJwksPublicationRepository.publicDataDigest( + promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson()))) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account ACTIVE JWKS receipt did not match its exact CAS readback"); + } + + PreparedGenerationEvidence afterActiveReceipt = + accountTransaction.execute( + status -> + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding))); + if (afterActiveReceipt == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Prepared Account promotion evidence is unavailable after ACTIVE readback"); + } + PromotionOperationEvidence promotionWithActiveReceipt = afterActiveReceipt.promotion(); + requirePromotionIdentity(promotion, promotionWithActiveReceipt, observation, expectedReceipt); + if (!promotionWithActiveReceipt + .activeJwksReceiptDigest() + .equals(Optional.of(activeReceipt.receiptDigest())) + || !promotionWithActiveReceipt + .activeJwksPublicDataDigest() + .equals(Optional.of(activeReceipt.publicDataDigest())) + || !promotionWithActiveReceipt + .activeJwksObservedResourceVersion() + .equals(Optional.of(activeReceipt.observedResourceVersion()))) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account ACTIVE JWKS receipt is not bound to the current PREPARED operation"); + } + requireUnchangedProtectedBindings(binding, apiIdentity); + + InventorySnapshot beforeCommitInventory = observePreparedInventory(context); + requireUnchangedProtectedBindings(binding, apiIdentity); + prepublicationService.observePreparedCurrentKeyCorrespondence(promotionWithActiveReceipt); + requireUnchangedProtectedBindings(binding, apiIdentity); + CommittedSignerEvidence committed = + commitPreparedPromotion( + binding, + apiIdentity, + observation, + expectedReceipt, + promotionWithActiveReceipt, + beforeCommitInventory); + requireUnchangedProtectedBindings(binding, apiIdentity); + if (committed == null + || !promotion.operationId().equals(committed.promotion().operationId()) + || !"COMMITTED".equals(committed.promotion().status())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account ACTIVE signer commit did not read back exactly"); + } + // The final commit obtains a separate readiness proof from the independent post-CAS inventory + // observation. + } + + private PromotionOwnerSnapshot readPromotionOwnerSnapshot( + Binding binding, + BindingIdentity apiIdentity, + PrivatePromotionObservation observation, + PrivatePromotionReceipt expectedReceipt) { + TrustFence trust = trustFence(binding); + PromotionOwnerSnapshot snapshot = + accountTransaction.execute( + status -> { + PrivatePromotionReceipt receipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trust, observation); + if (!expectedReceipt.equals(receipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Private promotion receipt changed before Account reconciliation"); + } + try { + PreparedGenerationEvidence prepared = + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trust); + requirePreparedReceipt(prepared, observation, receipt); + return new PromotionOwnerSnapshot(prepared, null, receipt); + } catch (AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException done) { + CommittedSignerEvidence committed = + desiredStateRepository + .readCurrentCommittedSigner( + binding.accountBinding(), + trust, + apiIdentity.bindingDigest(), + apiIdentity.configRevision()) + .orElseThrow( + () -> + new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Private promotion is neither PREPARED nor currently committed")); + if (!committed.privateReceipt().equals(receipt) + || !committed + .promotion() + .operationId() + .equals(observation.promotionOperationId())) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Committed private promotion retry differs from Account evidence"); + } + return new PromotionOwnerSnapshot(null, committed, receipt); + } + }); + if (snapshot == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account signer promotion evidence is unavailable"); + } + return snapshot; + } + + private ReadinessPromotionProof readPreparedPromotionProof( + Binding binding, + BindingIdentity apiIdentity, + PrivatePromotionObservation observation, + PrivatePromotionReceipt expectedReceipt, + PromotionOperationEvidence expectedPromotion, + InventorySnapshot liveInventory) { + TrustFence trust = trustFence(binding); + ReadinessPromotionProof proof = + accountTransaction.execute( + status -> { + PrivatePromotionReceipt receipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trust, observation); + if (!expectedReceipt.equals(receipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Private promotion receipt changed before ACTIVE publication"); + } + PreparedGenerationEvidence current = + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trust); + requireSamePreparedPromotion(current, expectedPromotion, observation, receipt); + return readinessRepository + .readPromotionProof( + binding.accountBinding(), + trust, + expectedPromotion.generationOperationId(), + liveInventory) + .orElseThrow( + () -> + new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Fresh complete Account readiness proof is unavailable")); + }); + if (proof == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account readiness proof is unavailable"); + } + requireUnchangedProtectedBindings(binding, apiIdentity); + return proof; + } + + private CommittedSignerEvidence commitPreparedPromotion( + Binding binding, + BindingIdentity apiIdentity, + PrivatePromotionObservation observation, + PrivatePromotionReceipt expectedReceipt, + PromotionOperationEvidence expectedPromotion, + InventorySnapshot liveInventory) { + TrustFence trust = trustFence(binding); + CommittedSignerEvidence committed = + accountTransaction.execute( + status -> { + PrivatePromotionReceipt receipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trust, observation); + if (!expectedReceipt.equals(receipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Original private promotion observation no longer matches Account evidence"); + } + PreparedGenerationEvidence current = + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trust); + requireSamePreparedPromotion(current, expectedPromotion, observation, receipt); + ReadinessPromotionProof proof = + readinessRepository + .readPromotionProof( + binding.accountBinding(), + trust, + expectedPromotion.generationOperationId(), + liveInventory) + .orElseThrow( + () -> + new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Post-CAS complete Account readiness proof is unavailable")); + return desiredStateRepository.commitPreparedPromotion( + binding.accountBinding(), trust, expectedPromotion.operationId(), proof); + }); + if (committed == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account signer promotion commit is unavailable"); + } + requireUnchangedProtectedBindings(binding, apiIdentity); + return committed; + } + + private InventorySnapshot observePreparedInventory(ObservationContext context) { + if (inventorySourceProvider == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + AccountJwtValidatorInventorySource source = inventorySourceProvider.getIfAvailable(); + if (source == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + try { + return source.observe(context); + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + } + + private static ObservationContext observationContext(PromotionOperationEvidence promotion) { + if (!promotion.expectedPreviousActive().equals(promotion.expectedPublishedActive())) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared Account active signer fence is inconsistent"); + } + return new ObservationContext( + promotion.expectedPreviousActive().isEmpty() + ? ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES + : ObservationPurpose.STRICT_READY, + promotion.generationOperationId(), + promotion.generationOperationDigest()); + } + + private static void requireReceiptIdentity( + PrivatePromotionObservation observation, PrivatePromotionReceipt receipt) { + if (!observation.promotionOperationId().equals(receipt.promotionOperationId()) + || !observation.generationOperationId().equals(receipt.generationOperationId()) + || !observation.observedResourceVersion().equals(receipt.observedResourceVersion())) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Private promotion result does not match the exact Account receipt"); + } + } + + private static void requirePreparedReceipt( + PreparedGenerationEvidence prepared, + PrivatePromotionObservation observation, + PrivatePromotionReceipt receipt) { + requireSamePreparedPromotion(prepared, prepared.promotion(), observation, receipt); + } + + private static void requireSamePreparedPromotion( + PreparedGenerationEvidence prepared, + PromotionOperationEvidence expected, + PrivatePromotionObservation observation, + PrivatePromotionReceipt receipt) { + PromotionOperationEvidence current = prepared.promotion(); + if (!current.equals(expected) + || !current.operationId().equals(observation.promotionOperationId()) + || !current.generationOperationId().equals(observation.generationOperationId()) + || !current.generationOperationDigest().equals(observation.generationOperationDigest()) + || !current.requestDigest().equals(observation.promotionRequestDigest()) + || !current.privatePromotionDispatched() + || !current.privatePromotionReceiptDigest().equals(Optional.of(receipt.receiptDigest()))) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Private promotion receipt does not match the exact current PREPARED operation"); + } + } + + private static void requirePromotionIdentity( + PromotionOperationEvidence expected, + PromotionOperationEvidence current, + PrivatePromotionObservation observation, + PrivatePromotionReceipt receipt) { + if (!current.operationId().equals(expected.operationId()) + || !current.requestDigest().equals(expected.requestDigest()) + || current.expectedRecordVersion() != expected.expectedRecordVersion() + || !current.binding().equals(expected.binding()) + || !current.expectedPreviousActive().equals(expected.expectedPreviousActive()) + || !current + .expectedPreviousPublicKeyFingerprint() + .equals(expected.expectedPreviousPublicKeyFingerprint()) + || !current.expectedPublishedActive().equals(expected.expectedPublishedActive()) + || !current.targetAlgorithm().equals(expected.targetAlgorithm()) + || !current.trustFence().equals(expected.trustFence()) + || !current.generationOperationId().equals(expected.generationOperationId()) + || !current.generationOperationDigest().equals(expected.generationOperationDigest()) + || !current.generationReceiptDigest().equals(expected.generationReceiptDigest()) + || !current.targetGeneration().equals(expected.targetGeneration()) + || !current.targetKid().equals(expected.targetKid()) + || !current.targetPublicKeyFingerprint().equals(expected.targetPublicKeyFingerprint()) + || !current.secretUid().equals(expected.secretUid()) + || !current + .expectedPrivateResourceVersion() + .equals(expected.expectedPrivateResourceVersion()) + || !current.apiBindingDigest().equals(expected.apiBindingDigest()) + || !current.apiConfigRevision().equals(expected.apiConfigRevision()) + || !current.publicConfigMapUid().equals(expected.publicConfigMapUid()) + || !current.expectedPublicResourceVersion().equals(expected.expectedPublicResourceVersion()) + || !current.prepublicationIntentDigest().equals(expected.prepublicationIntentDigest()) + || !current.prepublicationReceiptDigest().equals(expected.prepublicationReceiptDigest()) + || !current.mountedObservationDigest().equals(expected.mountedObservationDigest()) + || !current.readinessPlanDigest().equals(expected.readinessPlanDigest()) + || !current.readinessEvidenceDigest().equals(expected.readinessEvidenceDigest()) + || !current.expectedPublicJwksJson().equals(expected.expectedPublicJwksJson()) + || !current.expectedActiveMarkerJson().equals(expected.expectedActiveMarkerJson()) + || !"PREPARED".equals(current.status()) + || !current.operationId().equals(observation.promotionOperationId()) + || !current.generationOperationId().equals(observation.generationOperationId()) + || !current.privatePromotionDispatched() + || !current.privatePromotionReceiptDigest().equals(Optional.of(receipt.receiptDigest()))) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account PREPARED operation changed during ACTIVE publication"); + } + } + + private static void requireExpectedPublicSnapshot( + PromotionOperationEvidence promotion, ConfigMapSnapshot snapshot) { + String marker = + snapshot.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY); + boolean active = promotion.expectedActiveMarkerJson().equals(marker); + if (!promotion.publicConfigMapUid().equals(snapshot.uid()) + || !promotion.expectedPublicJwksJson().equals(snapshot.data().get(JWKS_DATA_KEY)) + || (!promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion()) + && !active) + || (promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion()) + && active)) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Account public ConfigMap changed before its exact ACTIVE CAS"); + } + } + + private static void requireExactActiveReadback( + PromotionOperationEvidence promotion, CasObservation observation) { + if (!promotion.publicConfigMapUid().equals(observation.uid()) + || !promotion.expectedPublicResourceVersion().equals(observation.priorResourceVersion()) + || !promotion + .expectedPublicJwksJson() + .equals(observation.publishedData().get(JWKS_DATA_KEY)) + || !promotion + .expectedActiveMarkerJson() + .equals( + observation + .publishedData() + .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY)) + || !promotion.expectedPublicJwksJson().equals(observation.readbackData().get(JWKS_DATA_KEY)) + || !promotion + .expectedActiveMarkerJson() + .equals( + observation + .readbackData() + .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY)) + || promotion.expectedPublicResourceVersion().equals(observation.resourceVersion())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account ACTIVE ConfigMap CAS did not return its exact immutable readback"); + } + } + + private InventorySnapshot observeCurrentValidatorInventory( + EnrollmentSources sources, GenerationRequest request) { + try { + AccountJwtValidatorInventorySource source = inventorySourceProvider.getIfAvailable(); + if (source == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + ObservationContext context = + accountTransaction.execute( + status -> { + requireUnchangedProtectedBindings(sources); + ObservationContext selected = + readinessRepository.readCurrentInventoryObservationContext( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding()), + request.operationId()); + requireUnchangedProtectedBindings(sources); + return selected; + }); + if (context == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + return source.observe(context); + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + } + + private BootstrapProgress reconcileSelectedGeneration( + EnrollmentSources sources, GenerationRequest request) { + try { + AccountJwtJwksPublicationRepository.PublicationReceipt publication = + prepublicationService.prepublishCurrentGeneration(); + requireUnchangedProtectedBindings(sources); + if (!request.operationId().equals(publication.operationId())) { + return progress( + Stage.PREPUBLICATION_BLOCKED, + request, + false, + false, + FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH); + } + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException ambiguousOrRejected) { + return progress( + Stage.PREPUBLICATION_BLOCKED, + request, + false, + false, + FailureCode.ACCOUNT_PREPUBLICATION_UNAVAILABLE); + } + + try { + AccountJwtJwksPublicationRepository.MountObservation mount = + prepublicationService.observeCurrentMountedCorrespondence(); + requireUnchangedProtectedBindings(sources); + if (!request.operationId().equals(mount.operationId())) { + return progress( + Stage.MOUNT_CORRESPONDENCE_BLOCKED, + request, + true, + false, + FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH); + } + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailableOrRejected) { + return progress( + Stage.MOUNT_CORRESPONDENCE_BLOCKED, + request, + true, + false, + FailureCode.ACCOUNT_MOUNT_CORRESPONDENCE_UNAVAILABLE); + } + + return progress( + Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE, + request, + true, + true, + FailureCode.VALIDATOR_ACCEPTANCE_INCOMPLETE); + } + + private DesiredState initializeEnrollment(EnrollmentSources sources) { + AccountJwtSignerDesiredStateRepository.Binding accountBinding = + sources.materializerBinding().accountBinding(); + try { + DesiredState initialized = + accountTransaction.execute( + status -> { + requireUnchangedProtectedBindings(sources); + DesiredState persisted = + desiredStateRepository.initialize(accountBinding, sources.enrollmentIdentity()); + requireUnchangedProtectedBindings(sources); + return persisted; + }); + if (initialized == null) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + requireUnchangedProtectedBindings(sources); + return initialized; + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + } + + private DesiredState readEnrollmentState(EnrollmentSources sources) { + AccountJwtSignerDesiredStateRepository.Binding accountBinding = + sources.materializerBinding().accountBinding(); + try { + Optional state = + accountTransaction.execute( + status -> { + requireUnchangedProtectedBindings(sources); + Optional current = + desiredStateRepository.readEnrollmentState(accountBinding); + requireUnchangedProtectedBindings(sources); + return current; + }); + if (state == null || state.isEmpty()) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + DesiredState current = state.orElseThrow(); + EnrollmentIdentity enrollment = + current + .enrollmentIdentity() + .orElseThrow( + () -> new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS)); + if (!enrollment.sameStablePins(sources.enrollmentIdentity())) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_MISMATCH); + } + requireUnchangedProtectedBindings(sources); + return current; + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + } + + private static void requireUnselectedInitialEnrollment( + DesiredState state, EnrollmentSources sources) { + if (state.recordVersion() != 1 + || state.durableActive().isPresent() + || state.publishedActive().isPresent() + || state.preparedOperationId().isPresent() + || state.generationOperationId().isPresent() + || state.enrollmentIdentity().isEmpty() + || !state.enrollmentIdentity().orElseThrow().sameStablePins(sources.enrollmentIdentity())) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + } + + private GenerationRequest readCurrentGenerationRequest(EnrollmentSources sources) { + AccountJwtSignerDesiredStateRepository.Binding accountBinding = + sources.materializerBinding().accountBinding(); + TrustFence trustFence = trustFence(sources.materializerBinding()); + try { + GenerationRequest request = + accountTransaction.execute( + status -> { + requireUnchangedProtectedBindings(sources); + GenerationRequest current = + desiredStateRepository.readCurrentGenerationRequest(accountBinding, trustFence); + requireUnchangedProtectedBindings(sources); + return current; + }); + if (request == null) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + requireUnchangedProtectedBindings(sources); + return request; + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + } + + private static EnrollmentAcknowledgement acknowledgement( + Binding materializer, + AccountJwtJwksConfigMapClient.BindingIdentity api, + EnrollmentIdentity enrollment) { + return new EnrollmentAcknowledgement( + materializer.environmentId(), + materializer.clusterId(), + materializer.namespace(), + enrollment.expectedClusterIncarnationUid(), + enrollment.expectedNamespaceUid(), + enrollment.materializerTrustBindingDigest(), + enrollment.materializerTrustConfigRevision(), + enrollment.apiBindingDigest(), + enrollment.apiConfigRevision(), + api.apiServerUrl(), + api.tlsServerName(), + api.servingCaSha256(), + api.expectedApiUsername(), + AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME, + AccountJwtSignerDesiredStateRepository.PUBLIC_JWKS_CONFIG_MAP_NAME, + enrollment.publicConfigMapUid(), + enrollment.publicConfigMapResourceVersion(), + enrollment.publicConfigMapSnapshotDigest()); + } + + private EnrollmentSources captureEnrollmentSources() { + Binding materializerBefore = currentMaterializerBinding(); + AccountJwtJwksConfigMapClient.BindingIdentity apiBefore = currentApiIdentity(); + requireMatchingProtectedPins(materializerBefore, apiBefore); + + AccountJwtJwksConfigMapClient.ConfigMapSnapshot publicConfigMap; + try { + publicConfigMap = Objects.requireNonNull(configMapClient.observe()); + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.PUBLIC_CONFIG_MAP_UNAVAILABLE); + } + + Binding materializerAfter = currentMaterializerBinding(); + AccountJwtJwksConfigMapClient.BindingIdentity apiAfter = currentApiIdentity(); + if (!materializerBefore.equals(materializerAfter) || !apiBefore.equals(apiAfter)) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_CHANGED); + } + requireMatchingProtectedPins(materializerAfter, apiAfter); + String initialJwks = publicConfigMap.data().get(JWKS_DATA_KEY); + if (initialJwks == null || initialJwks.isBlank()) { + throw new BootstrapOperationException(FailureCode.PUBLIC_CONFIG_MAP_INCOMPLETE); + } + + try { + EnrollmentIdentity enrollment = + new EnrollmentIdentity( + materializerAfter.expectedClusterIncarnationUid(), + materializerAfter.expectedNamespaceUid(), + materializerAfter.bindingDigest(), + materializerAfter.configRevision(), + apiAfter.bindingDigest(), + apiAfter.configRevision(), + publicConfigMap.uid(), + publicConfigMap.resourceVersion(), + AccountJwtJwksPublicationRepository.snapshotDigest(publicConfigMap.data())); + return new EnrollmentSources(materializerAfter, apiAfter, enrollment); + } catch (RuntimeException malformedSource) { + throw new BootstrapOperationException(FailureCode.PUBLIC_CONFIG_MAP_INCOMPLETE); + } + } + + private Binding currentMaterializerBinding() { + try { + return materializerTrustBinding + .current() + .orElseThrow( + () -> new BootstrapOperationException(FailureCode.PROTECTED_BINDING_UNAVAILABLE)); + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_UNAVAILABLE); + } + } + + private AccountJwtJwksConfigMapClient.BindingIdentity currentApiIdentity() { + try { + return Objects.requireNonNull(configMapClient.identity()); + } catch (RuntimeException unavailable) { + throw new BootstrapOperationException(FailureCode.PROTECTED_API_BINDING_UNAVAILABLE); + } + } + + private void requireUnchangedProtectedBindings(EnrollmentSources sources) { + Binding currentMaterializer = currentMaterializerBinding(); + AccountJwtJwksConfigMapClient.BindingIdentity currentApi = currentApiIdentity(); + if (!sources.materializerBinding().equals(currentMaterializer) + || !sources.apiIdentity().equals(currentApi)) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_CHANGED); + } + requireMatchingProtectedPins(currentMaterializer, currentApi); + } + + private void requireUnchangedProtectedBindings( + Binding expectedMaterializer, BindingIdentity expectedApiIdentity) { + Binding currentMaterializer = currentMaterializerBinding(); + BindingIdentity currentApi = currentApiIdentity(); + if (!expectedMaterializer.equals(currentMaterializer) + || !expectedApiIdentity.equals(currentApi)) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_CHANGED); + } + requireMatchingProtectedPins(currentMaterializer, currentApi); + } + + private static void requireMatchingProtectedPins( + Binding materializer, AccountJwtJwksConfigMapClient.BindingIdentity api) { + if (!materializer.environmentId().equals(api.environmentId()) + || !materializer.clusterId().equals(api.clusterId()) + || !materializer.namespace().equals(api.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid())) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_MISMATCH); + } + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private static BootstrapProgress progress( + Stage stage, + GenerationRequest request, + boolean prepublished, + boolean mountedCorrespondence, + FailureCode failure) { + boolean validatorAcceptanceComplete = false; + List blockers = List.of(failure); + if (stage == Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE) { + blockers = + List.of( + FailureCode.VALIDATOR_ACCEPTANCE_INCOMPLETE, + FailureCode.SIGNER_PROMOTION_NOT_ATTEMPTED); + } + return new BootstrapProgress( + stage, + EnrollmentSource.PROTECTED_BINDINGS_AND_LIVE_FIXED_JWKS_CONFIG_MAP, + true, + true, + request.operationId(), + request.phase(), + request.targetGeneration(), + request.targetKid(), + request.phase() == GenerationPhase.GENERATION_RECORDED, + prepublished, + mountedCorrespondence, + AccountJwtReadinessProbeRepository.INVENTORY_STATUS, + validatorAcceptanceComplete, + false, + false, + blockers); + } + + private record EnrollmentSources( + Binding materializerBinding, + AccountJwtJwksConfigMapClient.BindingIdentity apiIdentity, + EnrollmentIdentity enrollmentIdentity) {} + + private record PromotionOwnerSnapshot( + PreparedGenerationEvidence preparedEvidence, + CommittedSignerEvidence committedEvidence, + PrivatePromotionReceipt privateReceipt) {} + + /** Closed, non-secret identity acknowledgment for one idempotent durable enrollment. */ + public record EnrollmentAcknowledgement( + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String materializerTrustBindingDigest, + String materializerTrustConfigRevision, + String apiBindingDigest, + String apiConfigRevision, + String apiServerUrl, + String apiTlsServerName, + String apiServingCaSha256, + String apiExpectedUsername, + String privateSecretName, + String publicConfigMapName, + String publicConfigMapUid, + String publicConfigMapResourceVersion, + String publicConfigMapSnapshotDigest) {} + + public enum Stage { + PREPUBLICATION_BLOCKED, + MOUNT_CORRESPONDENCE_BLOCKED, + BLOCKED_FOR_VALIDATOR_ACCEPTANCE + } + + public enum EnrollmentSource { + PROTECTED_BINDINGS_AND_LIVE_FIXED_JWKS_CONFIG_MAP + } + + /** Non-secret progress; `false` readiness fields are deliberate until fleet proof exists. */ + public record BootstrapProgress( + Stage stage, + EnrollmentSource enrollmentSource, + boolean enrollmentInitialized, + boolean generationRequestSelected, + UUID operationId, + GenerationPhase generationPhase, + String targetGeneration, + String targetKid, + boolean generationReadbackComplete, + boolean publicKeyPrepublished, + boolean mountedKeyCorrespondence, + String validatorInventoryStatus, + boolean validatorAcceptanceComplete, + boolean signerPromotionCommitted, + boolean issuanceReady, + List blockers) { + public BootstrapProgress { + Objects.requireNonNull(stage); + Objects.requireNonNull(enrollmentSource); + Objects.requireNonNull(operationId); + Objects.requireNonNull(generationPhase); + Objects.requireNonNull(targetGeneration); + Objects.requireNonNull(targetKid); + Objects.requireNonNull(validatorInventoryStatus); + blockers = List.copyOf(blockers); + if (validatorAcceptanceComplete || signerPromotionCommitted || issuanceReady) { + throw new IllegalArgumentException( + "Signer bootstrap progress cannot claim validator acceptance, promotion, or readiness"); + } + if (!enrollmentInitialized || !generationRequestSelected) { + throw new IllegalArgumentException( + "Signer bootstrap progress requires completed Account enrollment and request selection"); + } + } + } + + public enum FailureCode { + PROTECTED_BINDING_UNAVAILABLE, + PROTECTED_API_BINDING_UNAVAILABLE, + PROTECTED_BINDING_MISMATCH, + PROTECTED_BINDING_CHANGED, + PUBLIC_CONFIG_MAP_UNAVAILABLE, + PUBLIC_CONFIG_MAP_INCOMPLETE, + SIGNER_PROMOTION_NOT_ATTEMPTED, + ACCOUNT_STATE_AMBIGUOUS, + ACCOUNT_OWNER_OPERATION_MISMATCH, + ACCOUNT_PREPUBLICATION_UNAVAILABLE, + ACCOUNT_MOUNT_CORRESPONDENCE_UNAVAILABLE, + VALIDATOR_INVENTORY_UNAVAILABLE, + VALIDATOR_ACCEPTANCE_INCOMPLETE + } + + public static final class BootstrapOperationException extends IllegalStateException { + private final FailureCode failureCode; + + public BootstrapOperationException(FailureCode failureCode) { + super("Account JWT signer bootstrap is quarantined: " + failureCode); + this.failureCode = Objects.requireNonNull(failureCode); + } + + public FailureCode failureCode() { + return failureCode; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java index 289c255116..a2a5d47715 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.service.session; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.CodingErrorAction; @@ -16,7 +17,9 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; +import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiOperation; @@ -25,6 +28,7 @@ import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding; import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProtectedInventory; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ReceiverPodPin; import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ValidatorExpectation; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import tools.jackson.core.StreamReadFeature; @@ -41,7 +45,7 @@ public final class AccountJwtValidatorInventorySource { private static final int MAX_PAGES = 16; private static final int MAX_PODS_PER_VALIDATOR = 128; private static final int MAX_CANONICAL_SNAPSHOT_BYTES = 4 * 1024 * 1024; - private static final String INVENTORY_DOMAIN = "firemud-account-validator-inventory/v1"; + private static final String INVENTORY_DOMAIN = "firemud-account-validator-inventory/v2"; private static final String SELF_REVIEW_REQUEST = "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}"; private static final String RUNTIME_CONFIG_ENV = "FIREMUD_JWT_VERIFIER_CONFIG"; @@ -49,6 +53,7 @@ public final class AccountJwtValidatorInventorySource { Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); private static final Pattern IMAGE_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern OPERATION_DIGEST = Pattern.compile("[0-9a-f]{64}"); private static final Pattern POD_TEMPLATE_HASH = Pattern.compile("[a-z0-9]{5,20}"); private static final JsonMapper JSON = JsonMapper.builder() @@ -78,8 +83,24 @@ public AccountJwtValidatorInventorySource( * or unpinned state is returned as one redacted failure; no Kubernetes response body is retained. */ public InventorySnapshot observe() { + return observeInternal(null); + } + + /** + * Produces an observation bound to an Account-selected durable generation operation. Only an + * initial operation with no durable or published active signer may enumerate non-ready Running + * Pods as candidates; those candidates still require the existing authenticated per-Pod probes + * before they can satisfy a promotion proof. + */ + public InventorySnapshot observe(ObservationContext observationContext) { + return observeInternal(Objects.requireNonNull(observationContext)); + } + + private InventorySnapshot observeInternal(ObservationContext observationContext) { ProtectedInventory expected = inventoryBinding.current().orElseThrow(InventoryUnavailableException::new); + boolean requireOrdinaryReady = + observationContext == null || observationContext.purpose().requiresOrdinaryReady(); try (ApiOperation operation = apiBinding.beginOperation()) { ParsedBinding api = operation.binding(); if (!expected.matchesApiBinding(api)) { @@ -88,15 +109,20 @@ public InventorySnapshot observe() { verifyApiIdentity(operation, expected); List observations = new ArrayList<>(); for (ValidatorExpectation validator : expected.validators()) { - DeploymentObservation beforeDeployment = readDeployment(operation, expected, validator); + DeploymentObservation beforeDeployment = + readDeployment(operation, expected, validator, requireOrdinaryReady); List beforePods = - readPods(operation, expected, validator, beforeDeployment); + readPods(operation, expected, validator, beforeDeployment, requireOrdinaryReady); List beforeReplicaSets = - readReplicaSets(operation, expected, validator, beforeDeployment, beforePods); - DeploymentObservation afterDeployment = readDeployment(operation, expected, validator); - List afterPods = readPods(operation, expected, validator, afterDeployment); + readReplicaSets( + operation, expected, validator, beforeDeployment, beforePods, requireOrdinaryReady); + DeploymentObservation afterDeployment = + readDeployment(operation, expected, validator, requireOrdinaryReady); + List afterPods = + readPods(operation, expected, validator, afterDeployment, requireOrdinaryReady); List afterReplicaSets = - readReplicaSets(operation, expected, validator, afterDeployment, afterPods); + readReplicaSets( + operation, expected, validator, afterDeployment, afterPods, requireOrdinaryReady); if (!beforeDeployment.equals(afterDeployment) || !beforePods.equals(afterPods) || !beforeReplicaSets.equals(afterReplicaSets)) { @@ -128,7 +154,7 @@ public InventorySnapshot observe() { if (observedAt == null || observedAt.isBefore(Instant.EPOCH)) { throw new InventoryUnavailableException(); } - return createSnapshot(expected, observations, observedAt); + return createSnapshot(expected, observations, observedAt, observationContext); } catch (InventoryUnavailableException failure) { throw failure; } catch (RuntimeException failure) { @@ -192,7 +218,10 @@ private static void verifyNamespace(ApiResponse response, String name, String ex } private static DeploymentObservation readDeployment( - ApiOperation operation, ProtectedInventory inventory, ValidatorExpectation expected) { + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + boolean requireOrdinaryReady) { ApiResponse response = operation.readValidatorDeployment(inventory, expected); if (response.statusCode() != 200) { throw new InventoryUnavailableException(); @@ -229,14 +258,24 @@ private static DeploymentObservation readDeployment( String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); long generation = positiveLong(metadata.get("generation")); int replicas = exactInt(spec.get("replicas"), 1, 128); + int readyReplicas = observedReplicaCount(status, "readyReplicas", !requireOrdinaryReady); + int updatedReplicas = exactInt(status.get("updatedReplicas"), 0, 128); + int availableReplicas = + observedReplicaCount(status, "availableReplicas", !requireOrdinaryReady); + int unavailableReplicas = + status.has("unavailableReplicas") && !status.get("unavailableReplicas").isNull() + ? exactInt(status.get("unavailableReplicas"), 0, 128) + : 0; if (replicas != expected.replicas() || positiveLong(status.get("observedGeneration")) != generation - || exactInt(status.get("readyReplicas"), 0, 128) != replicas - || exactInt(status.get("updatedReplicas"), 0, 128) != replicas - || exactInt(status.get("availableReplicas"), 0, 128) != replicas - || (status.has("unavailableReplicas") - && !status.get("unavailableReplicas").isNull() - && exactInt(status.get("unavailableReplicas"), 0, 128) != 0)) { + || readyReplicas > replicas + || updatedReplicas != replicas + || availableReplicas > readyReplicas + || unavailableReplicas > replicas + || (requireOrdinaryReady + && (readyReplicas != replicas + || availableReplicas != replicas + || unavailableReplicas != 0))) { throw new InventoryUnavailableException(); } ContainerConfig container = @@ -248,15 +287,31 @@ && exactInt(status.get("unavailableReplicas"), 0, 128) != 0)) { resourceVersion, generation, replicas, + readyReplicas, + availableReplicas, container.image(), container.runtimeConfigSha256()); } + private static int observedReplicaCount( + JsonNode status, String fieldName, boolean allowOmittedZero) { + if (!status.has(fieldName)) { + if (allowOmittedZero) { + // Kubernetes omits zero-valued optional status replica counts. This is safe only for the + // owner-bound initial candidate observation; strict readiness still requires both fields. + return 0; + } + throw new InventoryUnavailableException(); + } + return exactInt(status.get(fieldName), 0, 128); + } + private static List readPods( ApiOperation operation, ProtectedInventory inventory, ValidatorExpectation expected, - DeploymentObservation deployment) { + DeploymentObservation deployment, + boolean requireOrdinaryReady) { String continuation = null; String listResourceVersion = null; int pageCount = 0; @@ -291,7 +346,8 @@ private static List readPods( if (pods.size() >= MAX_PODS_PER_VALIDATOR) { throw new InventoryUnavailableException(); } - PodObservation pod = parsePod(item, inventory.namespace(), expected, deployment); + PodObservation pod = + parsePod(item, inventory.namespace(), expected, deployment, requireOrdinaryReady); if (!podUids.add(pod.uid()) || !podNames.add(pod.name())) { throw new InventoryUnavailableException(); } @@ -313,6 +369,12 @@ private static List readPods( throw new InventoryUnavailableException(); } pods.sort(Comparator.comparing(PodObservation::uid)); + List observedPodUids = pods.stream().map(PodObservation::uid).toList(); + List protectedPodUids = + expected.receiverPods().stream().map(ReceiverPodPin::podUid).sorted().toList(); + if (!observedPodUids.equals(protectedPodUids)) { + throw new InventoryUnavailableException(); + } return List.copyOf(pods); } @@ -320,7 +382,8 @@ private static PodObservation parsePod( JsonNode pod, String namespace, ValidatorExpectation expected, - DeploymentObservation deployment) { + DeploymentObservation deployment, + boolean requireOrdinaryReady) { if (pod == null || pod.isNull()) { throw new InventoryUnavailableException(); } @@ -340,6 +403,15 @@ private static PodObservation parsePod( } String name = dnsLabel(text(metadata.get("name"))); String uid = canonicalUid(text(metadata.get("uid"))); + String podIp = canonicalPodIp(text(status.get("podIP"))); + ReceiverPodPin receiverPin = + expected.receiverPods().stream() + .filter(pin -> pin.podUid().equals(uid)) + .findFirst() + .orElseThrow(InventoryUnavailableException::new); + if (!receiverPin.podIp().equals(podIp)) { + throw new InventoryUnavailableException(); + } String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); String templateHash = podTemplateHash(metadata.get("labels")); JsonNode owners = metadata.get("ownerReferences"); @@ -360,8 +432,9 @@ private static PodObservation parsePod( || !deployment.verifierConfigSha256().equals(container.runtimeConfigSha256())) { throw new InventoryUnavailableException(); } - verifyReadyCondition(status.get("conditions")); - verifyContainerReady(status.get("containerStatuses"), expected, deployment.image()); + verifyReadyCondition(status.get("conditions"), requireOrdinaryReady); + verifyContainerReady( + status.get("containerStatuses"), expected, deployment.image(), requireOrdinaryReady); return new PodObservation( name, uid, @@ -370,7 +443,11 @@ private static PodObservation parsePod( ownerUid, templateHash, deployment.image(), - deployment.verifierConfigSha256()); + deployment.verifierConfigSha256(), + podIp, + podEndpoint(podIp, expected.receiverPort()), + expected.receiverServiceUri(), + receiverPin.leafSpkiSha256()); } private static List readReplicaSets( @@ -378,7 +455,8 @@ private static List readReplicaSets( ProtectedInventory inventory, ValidatorExpectation expected, DeploymentObservation deployment, - List pods) { + List pods, + boolean requireOrdinaryReady) { Map observedOwners = new LinkedHashMap<>(); Map templateHashes = new LinkedHashMap<>(); for (PodObservation pod : pods) { @@ -403,7 +481,8 @@ private static List readReplicaSets( deployment, owner.getKey(), owner.getValue(), - templateHashes.get(owner.getKey()))); + templateHashes.get(owner.getKey()), + requireOrdinaryReady)); } observations.sort(Comparator.comparing(ReplicaSetObservation::uid)); return List.copyOf(observations); @@ -416,7 +495,8 @@ private static ReplicaSetObservation parseReplicaSet( DeploymentObservation deployment, String expectedName, String expectedUid, - String expectedTemplateHash) { + String expectedTemplateHash, + boolean requireOrdinaryReady) { JsonNode root = parseJson(responseBody); JsonNode metadata = root.get("metadata"); JsonNode spec = root.get("spec"); @@ -464,9 +544,11 @@ private static ReplicaSetObservation parseReplicaSet( String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); long generation = positiveLong(metadata.get("generation")); int replicas = exactInt(spec.get("replicas"), 1, 128); + int readyReplicas = observedReplicaCount(status, "readyReplicas", !requireOrdinaryReady); if (positiveLong(status.get("observedGeneration")) != generation - || exactInt(status.get("readyReplicas"), 0, 128) != replicas - || replicas != expected.replicas()) { + || readyReplicas > replicas + || replicas != expected.replicas() + || (requireOrdinaryReady && readyReplicas != replicas)) { throw new InventoryUnavailableException(); } ContainerConfig container = @@ -638,14 +720,18 @@ private static void rejectSigningSecretVolumes(JsonNode volumes) { } } - private static void verifyReadyCondition(JsonNode conditions) { + private static void verifyReadyCondition(JsonNode conditions, boolean requireOrdinaryReady) { if (conditions == null || !conditions.isArray() || conditions.size() > 64) { throw new InventoryUnavailableException(); } boolean ready = false; for (JsonNode condition : conditions) { if ("Ready".equals(text(condition.get("type")))) { - if (ready || !"True".equals(text(condition.get("status")))) { + String status = text(condition.get("status")); + if (ready || (!"True".equals(status) && !"False".equals(status))) { + throw new InventoryUnavailableException(); + } + if (requireOrdinaryReady && !"True".equals(status)) { throw new InventoryUnavailableException(); } ready = true; @@ -657,7 +743,10 @@ private static void verifyReadyCondition(JsonNode conditions) { } private static void verifyContainerReady( - JsonNode statuses, ValidatorExpectation expected, String expectedImage) { + JsonNode statuses, + ValidatorExpectation expected, + String expectedImage, + boolean requireOrdinaryReady) { if (statuses == null || !statuses.isArray() || statuses.isEmpty() || statuses.size() > 32) { throw new InventoryUnavailableException(); } @@ -673,22 +762,29 @@ private static void verifyContainerReady( String imageId = found == null ? null : text(found.get("imageID")); String digest = imageDigest(imageId); String expectedDigest = expected.image().substring(expected.image().lastIndexOf('@') + 1); + Boolean ready = found == null ? null : booleanValue(found.get("ready")); if (found == null - || !Boolean.TRUE.equals(booleanValue(found.get("ready"))) + || ready == null + || (requireOrdinaryReady && !ready) || !expectedDigest.equals(digest)) { throw new InventoryUnavailableException(); } } private static InventorySnapshot createSnapshot( - ProtectedInventory expected, List validators, Instant observedAt) { + ProtectedInventory expected, + List validators, + Instant observedAt, + ObservationContext observationContext) { List sorted = validators.stream() .sorted(Comparator.comparing(ValidatorObservation::validatorId)) .toList(); Map preimage = new LinkedHashMap<>(); preimage.put("domain", INVENTORY_DOMAIN); - preimage.put("observedAt", observedAt.toString()); + // Acquisition time is independently bounded freshness metadata, not inventory content. The + // v2 digest must remain stable across an unchanged later reread while retaining this time in + // the immutable snapshot row and in the in-memory observation. preimage.put("environmentId", expected.environmentId()); preimage.put("clusterId", expected.clusterId()); preimage.put("clusterIncarnationUid", expected.expectedClusterIncarnationUid()); @@ -698,6 +794,9 @@ private static InventorySnapshot createSnapshot( preimage.put("apiBindingDigest", expected.apiBindingDigest()); preimage.put("inventoryBindingRevision", expected.configRevision()); preimage.put("inventoryBindingDigest", expected.bindingDigest()); + if (observationContext != null) { + preimage.put("observationContext", observationContext.canonicalMap()); + } preimage.put( "validators", sorted.stream().map(AccountJwtValidatorInventorySource::validatorMap).toList()); @@ -718,6 +817,7 @@ private static InventorySnapshot createSnapshot( expected.configRevision(), expected.bindingDigest(), sorted, + Optional.ofNullable(observationContext), canonicalSnapshot, digest); } @@ -742,6 +842,8 @@ private static Map validatorMap(ValidatorObservation validator) .toList()); result.put( "pods", validator.pods().stream().map(AccountJwtValidatorInventorySource::podMap).toList()); + result.put("receiverServiceUri", validator.pods().getFirst().receiverServiceUri()); + result.put("receiverPort", validator.pods().getFirst().endpoint().getPort()); result.put( "replicaSets", validator.replicaSets().stream() @@ -765,15 +867,32 @@ private static Map replicaSetMap(ReplicaSetObservation replicaSe } private static Map podMap(PodObservation pod) { - return Map.of( - "name", pod.name(), - "uid", pod.uid(), - "resourceVersion", pod.resourceVersion(), - "ownerReplicaSetName", pod.ownerName(), - "ownerReplicaSetUid", pod.ownerUid(), - "podTemplateHash", pod.podTemplateHash(), - "image", pod.image(), - "verifierConfigSha256", pod.verifierConfigSha256()); + return Map.ofEntries( + Map.entry("name", pod.name()), + Map.entry("uid", pod.uid()), + Map.entry("resourceVersion", pod.resourceVersion()), + Map.entry("ownerReplicaSetName", pod.ownerName()), + Map.entry("ownerReplicaSetUid", pod.ownerUid()), + Map.entry("podTemplateHash", pod.podTemplateHash()), + Map.entry("image", pod.image()), + Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), + Map.entry("podIp", pod.podIp()), + Map.entry("exactPodEndpoint", pod.endpoint().toString()), + Map.entry("canonicalServiceUri", pod.receiverServiceUri()), + Map.entry("leafSpkiSha256", pod.leafSpkiSha256())); + } + + private static URI podEndpoint(String podIp, int port) { + String host = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + return URI.create("grpcs://" + host + ":" + port); + } + + private static String canonicalPodIp(String value) { + try { + return AccountJwtValidatorInventoryBinding.canonicalPodIp(value); + } catch (RuntimeException failure) { + throw new InventoryUnavailableException(); + } } private static boolean selectorMatches(JsonNode actual, Map expected) { @@ -924,6 +1043,8 @@ private record DeploymentObservation( String resourceVersion, long generation, int replicas, + int readyReplicas, + int availableReplicas, String image, String verifierConfigSha256) {} @@ -948,7 +1069,11 @@ public record PodObservation( String ownerUid, String podTemplateHash, String image, - String verifierConfigSha256) {} + String verifierConfigSha256, + String podIp, + URI endpoint, + String receiverServiceUri, + String leafSpkiSha256) {} public record ValidatorObservation( String validatorId, @@ -970,6 +1095,45 @@ public record ValidatorObservation( } } + /** + * Account-owner-derived context for one validator inventory acquisition. Bootstrap candidate + * observation is available only for the exact current operation whose active signer fence is + * absent; the repository re-derives and checks this context before consuming the snapshot. + */ + public record ObservationContext( + ObservationPurpose purpose, UUID operationId, String operationDigest) { + public ObservationContext { + Objects.requireNonNull(purpose, "Inventory observation purpose is required"); + Objects.requireNonNull(operationId, "Inventory observation operation is required"); + if (operationId.version() != 4 + || operationId.variant() != 2 + || operationDigest == null + || !OPERATION_DIGEST.matcher(operationDigest).matches()) { + throw new InventoryUnavailableException(); + } + } + + public boolean isInitialNoActiveSigner() { + return purpose == ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES; + } + + private Map canonicalMap() { + return Map.of( + "purpose", purpose.name(), + "operationId", operationId.toString(), + "operationDigest", operationDigest); + } + } + + public enum ObservationPurpose { + STRICT_READY, + INITIAL_NO_ACTIVE_SIGNER_CANDIDATES; + + private boolean requiresOrdinaryReady() { + return this == STRICT_READY; + } + } + public static final class InventorySnapshot { private final Instant observedAt; private final String environmentId; @@ -982,6 +1146,7 @@ public static final class InventorySnapshot { private final String inventoryBindingRevision; private final String inventoryBindingDigest; private final List validators; + private final Optional observationContext; private final byte[] canonicalBytes; private final String digest; @@ -997,6 +1162,7 @@ private InventorySnapshot( String inventoryBindingRevision, String inventoryBindingDigest, List validators, + Optional observationContext, byte[] canonicalBytes, String digest) { this.observedAt = Objects.requireNonNull(observedAt); @@ -1010,6 +1176,7 @@ private InventorySnapshot( this.inventoryBindingRevision = Objects.requireNonNull(inventoryBindingRevision); this.inventoryBindingDigest = Objects.requireNonNull(inventoryBindingDigest); this.validators = List.copyOf(validators); + this.observationContext = Objects.requireNonNull(observationContext); this.canonicalBytes = Objects.requireNonNull(canonicalBytes).clone(); this.digest = Objects.requireNonNull(digest); if (this.canonicalBytes.length == 0 @@ -1063,6 +1230,10 @@ public List validators() { return validators; } + public Optional observationContext() { + return observationContext; + } + public byte[] canonicalBytes() { return canonicalBytes.clone(); } @@ -1085,6 +1256,7 @@ public boolean equals(Object other) { && inventoryBindingRevision.equals(that.inventoryBindingRevision) && inventoryBindingDigest.equals(that.inventoryBindingDigest) && validators.equals(that.validators) + && observationContext.equals(that.observationContext) && java.util.Arrays.equals(canonicalBytes, that.canonicalBytes) && digest.equals(that.digest); } @@ -1104,6 +1276,7 @@ public int hashCode() { inventoryBindingRevision, inventoryBindingDigest, validators, + observationContext, digest) + java.util.Arrays.hashCode(canonicalBytes); } diff --git a/services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql b/services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql new file mode 100644 index 0000000000..c871d646f8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql @@ -0,0 +1,777 @@ +-- V2 readiness plans bind every protected live validator Pod and retain one immutable production +-- verification receipt per Pod and logical probe. Existing V1 plans and receipts remain retained +-- and partial; they are never rewritten into V2 closure evidence. + +ALTER TABLE account_jwt_readiness_probe_plans + DROP CONSTRAINT account_jwt_readiness_plan_window_check; + +ALTER TABLE account_jwt_readiness_probe_plans + ADD CONSTRAINT account_jwt_readiness_plan_window_check + CHECK (maximum_cache_age_seconds BETWEEN 1 AND 300 + AND planned_at_epoch_seconds > 0 + AND not_before_epoch_seconds >= planned_at_epoch_seconds + maximum_cache_age_seconds + AND expires_at_epoch_seconds > not_before_epoch_seconds + AND expires_at_epoch_seconds - not_before_epoch_seconds <= 300 + AND plan_version IN (1, 2) + AND (plan_version <> 2 OR inventory_snapshot_digest IS NOT NULL)); + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN entry_plan_version SMALLINT NOT NULL DEFAULT 1; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN pod_receipt_count SMALLINT; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN pod_receipt_closure_sha256 VARCHAR(64); + +ALTER TABLE account_jwt_readiness_probe_entries + DROP CONSTRAINT account_jwt_readiness_probe_evidence_check; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD CONSTRAINT account_jwt_readiness_probe_evidence_check + CHECK (plan_digest ~ '^[0-9a-f]{64}$' + AND registry_version = 1 + AND entry_plan_version IN (1, 2) + AND entry_version > 0 + AND planned_issued_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > planned_issued_at_epoch_seconds + AND (compact_token_sha256 IS NULL OR compact_token_sha256 ~ '^[0-9a-f]{64}$') + AND (signing_attempted_at_epoch_seconds IS NULL + OR (signing_attempted_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND signing_attempted_at_epoch_seconds < expires_at_epoch_seconds)) + AND ((compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL) + OR (compact_token_sha256 IS NOT NULL AND signing_attempted_at_epoch_seconds IS NOT NULL)) + AND (state NOT IN ('ISSUED', 'VERIFIED', 'RETIRED') OR compact_token_sha256 IS NOT NULL) + AND (verification_receipt_version IS NULL + OR (entry_plan_version = 1 AND verification_receipt_version = 1) + OR (entry_plan_version = 2 AND verification_receipt_version = 2)) + AND (verification_source_entry_version IS NULL OR verification_source_entry_version > 0) + AND (verified_at_epoch_seconds IS NULL + OR (verified_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND verified_at_epoch_seconds < expires_at_epoch_seconds)) + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND (validator_instance_id IS NULL + OR validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_binding_digest IS NULL OR validator_binding_digest ~ '^[0-9a-f]{64}$') + AND (validator_config_revision IS NULL + OR validator_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_peer_uri IS NULL + OR validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$') + AND (validator_peer_spki_sha256 IS NULL + OR validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$') + AND (verification_receipt_sha256 IS NULL + OR verification_receipt_sha256 ~ '^[0-9a-f]{64}$') + AND (pod_receipt_count IS NULL OR pod_receipt_count BETWEEN 1 AND 256) + AND (pod_receipt_closure_sha256 IS NULL + OR pod_receipt_closure_sha256 ~ '^[0-9a-f]{64}$') + AND ((verification_receipt_sha256 IS NULL + AND verification_receipt_version IS NULL + AND verification_source_entry_version IS NULL + AND verified_at_epoch_seconds IS NULL + AND verified_kid IS NULL + AND validator_instance_id IS NULL + AND validator_binding_digest IS NULL + AND validator_config_revision IS NULL + AND validator_peer_uri IS NULL + AND validator_peer_spki_sha256 IS NULL + AND pod_receipt_count IS NULL + AND pod_receipt_closure_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 1 + AND entry_plan_version = 1 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid IS NOT NULL + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL + AND pod_receipt_count IS NULL + AND pod_receipt_closure_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 2 + AND entry_plan_version = 2 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid = target_kid + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL + AND pod_receipt_count IS NOT NULL + AND pod_receipt_closure_sha256 = verification_receipt_sha256)) + AND (state NOT IN ('VERIFIED', 'RETIRED') OR verification_receipt_sha256 IS NOT NULL) + AND (state NOT IN ('PLANNED', 'ISSUED') OR verification_receipt_sha256 IS NULL)); + +CREATE TABLE account_jwt_readiness_validator_pods ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + jti UUID NOT NULL, + inventory_snapshot_digest VARCHAR(64) NOT NULL, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + cluster_incarnation_uid UUID NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + namespace_uid UUID NOT NULL, + api_binding_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + inventory_binding_revision VARCHAR(128) NOT NULL, + inventory_binding_digest VARCHAR(64) NOT NULL, + deployment_uid UUID NOT NULL, + pod_uid UUID NOT NULL, + pod_ip VARCHAR(45) NOT NULL, + image VARCHAR(512) NOT NULL, + verifier_config_sha256 VARCHAR(64) NOT NULL, + applicability_matrix_digest VARCHAR(64) NOT NULL, + expected_outcome VARCHAR(32) NOT NULL, + exact_pod_endpoint VARCHAR(512) NOT NULL, + canonical_service_uri VARCHAR(256) NOT NULL, + expected_pod_leaf_spki_sha256 VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid), + CONSTRAINT account_jwt_readiness_validator_pod_entry_fk + FOREIGN KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind) + REFERENCES account_jwt_readiness_probe_entries( + rotation_operation_id, validator_id, token_profile, audience, probe_kind) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_validator_pod_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_validator_pod_shape_check + CHECK (rotation_operation_id::text ~ + '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND plan_digest ~ '^[0-9a-f]{64}$' + AND inventory_snapshot_digest ~ '^[0-9a-f]{64}$' + AND validator_id ~ '^[a-z0-9][a-z0-9-]{0,62}$' + AND token_profile ~ '^[a-z0-9][a-z0-9-]{0,127}$' + AND audience ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND probe_kind IN ('CANARY', 'REPRESENTATIVE') + AND environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND api_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND inventory_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND inventory_binding_digest ~ '^[0-9a-f]{64}$' + AND deployment_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND pod_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND (pod_ip ~ '^(?:[0-9]{1,3}[.]){3}[0-9]{1,3}$' OR pod_ip ~ '^[0-9a-f:]+$') + AND image ~ '^[^[:space:]@]+@sha256:[0-9a-f]{64}$' + AND verifier_config_sha256 ~ '^[0-9a-f]{64}$' + AND applicability_matrix_digest ~ '^[0-9a-f]{64}$' + AND expected_outcome IN ('ACCEPT', 'INAPPLICABLE_REJECT') + AND exact_pod_endpoint ~ '^grpcs://[^/?#]+:[0-9]{1,5}$' + AND canonical_service_uri ~ + '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$' + AND expected_pod_leaf_spki_sha256 ~ '^[0-9a-f]{64}$') +); + +CREATE TABLE account_jwt_readiness_pod_receipts ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + pod_uid UUID NOT NULL, + receipt_version SMALLINT NOT NULL, + jti UUID NOT NULL, + source_entry_version BIGINT NOT NULL, + compact_token_sha256 VARCHAR(64) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + outcome VARCHAR(32) NOT NULL, + observed_pod_uid UUID NOT NULL, + observed_image VARCHAR(512) NOT NULL, + observed_verifier_config_sha256 VARCHAR(64) NOT NULL, + verified_kid VARCHAR(64), + receiver_endpoint VARCHAR(512) NOT NULL, + receiver_service_uri VARCHAR(256) NOT NULL, + receiver_peer_spki_sha256 VARCHAR(64) NOT NULL, + observed_at_epoch_seconds BIGINT NOT NULL, + receipt_sha256 VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid), + CONSTRAINT account_jwt_readiness_pod_receipt_target_fk + FOREIGN KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) + REFERENCES account_jwt_readiness_validator_pods( + rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_pod_receipt_shape_check + CHECK (receipt_version = 1 + AND source_entry_version > 0 + AND compact_token_sha256 ~ '^[0-9a-f]{64}$' + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid + AND outcome IN ('ACCEPT', 'INAPPLICABLE_REJECT') + AND observed_pod_uid = pod_uid + AND observed_image ~ '^[^[:space:]@]+@sha256:[0-9a-f]{64}$' + AND observed_verifier_config_sha256 ~ '^[0-9a-f]{64}$' + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND receiver_endpoint ~ '^grpcs://[^/?#]+:[0-9]{1,5}$' + AND receiver_service_uri ~ + '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$' + AND receiver_peer_spki_sha256 ~ '^[0-9a-f]{64}$' + AND observed_at_epoch_seconds > 0 + AND receipt_sha256 ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_readiness_plan_inventory_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + matrix jsonb; + account_profiles jsonb; + game_session_profiles jsonb; +BEGIN + matrix := NEW.applicability_matrix_json::jsonb; + IF NEW.plan_version = 1 THEN + IF NEW.validator_inventory_complete + OR matrix ->> 'inventoryStatus' <> 'PARTIAL_UNCONFIRMED' + OR matrix ->> 'schemaVersion' <> '1' + OR jsonb_array_length(matrix -> 'validators') <> 1 + OR matrix #>> '{validators,0,validatorId}' <> 'account-service' + OR jsonb_array_length(matrix #> '{validators,0,applicableProfiles}') <> 3 + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Legacy readiness plans remain explicitly partial and Account-only' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF NEW.plan_version <> 2 + OR NEW.inventory_snapshot_digest IS NULL + OR matrix ->> 'schemaVersion' <> '2' + OR matrix ->> 'inventorySnapshotDigest' IS DISTINCT FROM NEW.inventory_snapshot_digest + OR jsonb_array_length(matrix -> 'validators') < 1 + OR jsonb_array_length(matrix -> 'validators') > 32 + OR jsonb_array_length(matrix -> 'productionProfiles') <> 3 THEN + RAISE EXCEPTION 'Readiness V2 plan must bind its protected live snapshot and closed profile family' + USING ERRCODE = '23514'; + END IF; + IF NEW.validator_inventory_complete THEN + SELECT value -> 'applicableProfiles' INTO account_profiles + FROM jsonb_array_elements(matrix -> 'validators') AS validator(value) + WHERE value ->> 'validatorId' = 'account-service'; + SELECT value -> 'applicableProfiles' INTO game_session_profiles + FROM jsonb_array_elements(matrix -> 'validators') AS validator(value) + WHERE value ->> 'validatorId' = 'game-session-service'; + IF matrix ->> 'inventoryStatus' <> 'PROTECTED_LIVE_COMPLETE' + OR jsonb_array_length(matrix -> 'validators') <> 2 + OR account_profiles IS NULL + OR jsonb_array_length(account_profiles) <> 3 + OR NOT (account_profiles @> '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (account_profiles @> '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (account_profiles @> '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) + OR game_session_profiles IS NULL + OR jsonb_array_length(game_session_profiles) <> 1 + OR NOT (game_session_profiles @> '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Readiness V2 completion requires exact Account and Game Session profile inventory' + USING ERRCODE = '23514'; + END IF; + ELSIF matrix ->> 'inventoryStatus' <> 'PARTIAL_UNCONFIRMED' THEN + RAISE EXCEPTION 'Incomplete Readiness V2 inventory must remain explicitly partial' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_readiness_entry_plan_version_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; +BEGIN + IF TG_OP = 'UPDATE' AND NEW.entry_plan_version IS DISTINCT FROM OLD.entry_plan_version THEN + RAISE EXCEPTION 'Readiness entry schema version is immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND OR NEW.entry_plan_version IS DISTINCT FROM plan_row.plan_version THEN + RAISE EXCEPTION 'Readiness entry schema differs from its immutable plan' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_plan_version_binding + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_plan_version_guard(); + +DROP TRIGGER account_jwt_readiness_entry_lifecycle ON account_jwt_readiness_probe_entries; +CREATE TRIGGER account_jwt_readiness_entry_lifecycle_v1 + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW WHEN (NEW.entry_plan_version = 1) + EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); +CREATE TRIGGER account_jwt_readiness_entry_delete_guard + BEFORE DELETE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); + +CREATE FUNCTION account_jwt_readiness_expected_pod_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + entry_row account_jwt_readiness_probe_entries%ROWTYPE; + snapshot_json jsonb; + validator_json jsonb; + pod_json jsonb; + expected_outcome_value text; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Expected readiness Pod bindings are immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + SELECT * INTO entry_row + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + SELECT convert_from(canonical_snapshot, 'UTF8')::jsonb INTO snapshot_json + FROM account_jwt_validator_inventory_snapshots + WHERE snapshot_digest = NEW.inventory_snapshot_digest; + IF NOT FOUND OR plan_row.plan_version <> 2 OR entry_row.entry_plan_version <> 2 + OR entry_row.jti IS DISTINCT FROM NEW.jti + OR plan_row.inventory_snapshot_digest IS DISTINCT FROM NEW.inventory_snapshot_digest + OR plan_row.applicability_matrix_digest IS DISTINCT FROM NEW.applicability_matrix_digest + OR (plan_row.environment_id, plan_row.cluster_id, plan_row.kubernetes_namespace, + plan_row.expected_cluster_incarnation_uid, plan_row.expected_namespace_uid) + IS DISTINCT FROM (NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.cluster_incarnation_uid, NEW.namespace_uid) + OR NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'pods') AS pod(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND validator.value ->> 'deploymentUid' = NEW.deployment_uid::text + AND pod.value ->> 'uid' = NEW.pod_uid::text + AND pod.value ->> 'podIp' = NEW.pod_ip + AND pod.value ->> 'exactPodEndpoint' = NEW.exact_pod_endpoint + AND pod.value ->> 'canonicalServiceUri' = NEW.canonical_service_uri + AND pod.value ->> 'leafSpkiSha256' = NEW.expected_pod_leaf_spki_sha256 + AND pod.value ->> 'image' = NEW.image + AND pod.value ->> 'verifierConfigSha256' = NEW.verifier_config_sha256 + AND validator.value ->> 'image' = NEW.image + AND validator.value ->> 'verifierConfigSha256' = NEW.verifier_config_sha256) + OR (NEW.probe_kind = 'CANARY' AND NEW.expected_outcome <> 'ACCEPT') + OR (NEW.probe_kind = 'REPRESENTATIVE' AND ( + (NEW.expected_outcome = 'ACCEPT') IS DISTINCT FROM EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'profiles') AS profile(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND profile.value ->> 'tokenProfile' = NEW.token_profile + AND profile.value ->> 'audience' = NEW.audience))) THEN + RAISE EXCEPTION 'Expected readiness Pod differs from its exact protected inventory and entry' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_expected_pod_insert_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_validator_pods + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_expected_pod_guard(); + +CREATE FUNCTION account_jwt_readiness_pod_receipt_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + entry_row account_jwt_readiness_probe_entries%ROWTYPE; + pod_row account_jwt_readiness_validator_pods%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Readiness Pod verification receipts are immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + SELECT * INTO entry_row + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind + FOR UPDATE; + SELECT * INTO pod_row + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind + AND pod_uid = NEW.pod_uid + FOR KEY SHARE; + IF plan_row.plan_version <> 2 OR plan_row.validator_inventory_complete IS DISTINCT FROM TRUE + OR entry_row.entry_plan_version <> 2 OR entry_row.state <> 'ISSUED' + OR entry_row.jti IS DISTINCT FROM NEW.jti + OR entry_row.entry_version IS DISTINCT FROM NEW.source_entry_version + OR entry_row.compact_token_sha256 IS DISTINCT FROM NEW.compact_token_sha256 + OR entry_row.target_generation IS DISTINCT FROM NEW.target_generation + OR entry_row.target_kid IS DISTINCT FROM NEW.target_kid + OR entry_row.expected_active_generation IS DISTINCT FROM NEW.expected_active_generation + OR entry_row.expected_active_kid IS DISTINCT FROM NEW.expected_active_kid + OR pod_row.expected_outcome IS DISTINCT FROM NEW.outcome + OR pod_row.exact_pod_endpoint IS NULL + OR pod_row.exact_pod_endpoint IS DISTINCT FROM NEW.receiver_endpoint + OR pod_row.canonical_service_uri IS DISTINCT FROM NEW.receiver_service_uri + OR pod_row.expected_pod_leaf_spki_sha256 IS DISTINCT FROM NEW.receiver_peer_spki_sha256 + OR pod_row.pod_uid IS DISTINCT FROM NEW.observed_pod_uid + OR pod_row.image IS DISTINCT FROM NEW.observed_image + OR pod_row.verifier_config_sha256 IS DISTINCT FROM NEW.observed_verifier_config_sha256 + OR NEW.verified_kid IS DISTINCT FROM NEW.target_kid + OR NEW.observed_at_epoch_seconds < entry_row.planned_issued_at_epoch_seconds + OR NEW.observed_at_epoch_seconds >= entry_row.expires_at_epoch_seconds + OR NEW.observed_at_epoch_seconds > floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT + OR CURRENT_TIMESTAMP < to_timestamp(entry_row.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(entry_row.expires_at_epoch_seconds) THEN + RAISE EXCEPTION 'Readiness Pod receipt differs from exact current inventory, probe, or TLS identity' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_pod_receipt_insert_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_pod_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_pod_receipt_guard(); + +CREATE FUNCTION account_jwt_readiness_entry_v2_lifecycle_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + expected_pod_count integer; + receipt_count integer; +BEGIN + IF TG_OP = 'INSERT' THEN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND OR plan_row.plan_version <> 2 + OR NEW.state <> 'PLANNED' + OR NEW.entry_version <> 1 + OR NEW.registry_version <> 1 + OR NEW.terminal_outcome IS NOT NULL + OR NEW.compact_token_sha256 IS NOT NULL + OR NEW.signing_attempted_at_epoch_seconds IS NOT NULL + OR NEW.verification_receipt_sha256 IS NOT NULL + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM plan_row.not_before_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Readiness V2 entry differs from its immutable plan' + USING ERRCODE = '23514'; + END IF; + IF NEW.probe_kind = 'CANARY' THEN + IF NEW.token_profile <> 'account-jwt-readiness-canary' + OR NEW.audience <> 'firemud-account-jwt-readiness' + OR NOT EXISTS (SELECT 1 FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS v(value) + WHERE v.value ->> 'validatorId' = NEW.validator_id) THEN + RAISE EXCEPTION 'Readiness V2 canary entry is outside the closed validator set' + USING ERRCODE = '23514'; + END IF; + ELSIF NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS v(value) + CROSS JOIN LATERAL jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'productionProfiles') AS p(value) + WHERE v.value ->> 'validatorId' = NEW.validator_id + AND p.value ->> 'tokenProfile' = NEW.token_profile + AND p.value ->> 'audience' = NEW.audience) THEN + RAISE EXCEPTION 'Readiness V2 representative entry is outside its exact profile matrix' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT readiness evidence is retained' USING ERRCODE = '23514'; + END IF; + IF OLD.entry_plan_version <> 2 OR NEW.entry_plan_version <> 2 + OR NEW.rotation_operation_id IS DISTINCT FROM OLD.rotation_operation_id + OR NEW.plan_digest IS DISTINCT FROM OLD.plan_digest + OR NEW.validator_id IS DISTINCT FROM OLD.validator_id + OR NEW.token_profile IS DISTINCT FROM OLD.token_profile + OR NEW.audience IS DISTINCT FROM OLD.audience + OR NEW.probe_kind IS DISTINCT FROM OLD.probe_kind + OR NEW.jti IS DISTINCT FROM OLD.jti + OR NEW.target_generation IS DISTINCT FROM OLD.target_generation + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM OLD.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM OLD.expected_active_kid + OR NEW.registry_version IS DISTINCT FROM OLD.registry_version + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM OLD.planned_issued_at_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM OLD.expires_at_epoch_seconds + OR NEW.entry_version <> OLD.entry_version + 1 THEN + RAISE EXCEPTION 'Readiness V2 entry identity/version is immutable except for one exact transition' + USING ERRCODE = '23514'; + END IF; + IF OLD.state = 'PLANNED' AND NEW.state = 'PLANNED' + AND OLD.compact_token_sha256 IS NULL + AND NEW.compact_token_sha256 IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds >= OLD.planned_issued_at_epoch_seconds + AND NEW.signing_attempted_at_epoch_seconds < OLD.expires_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + IF OLD.state = 'PLANNED' AND NEW.state = 'ISSUED' + AND OLD.compact_token_sha256 IS NOT NULL + AND NEW.compact_token_sha256 = OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds = OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + IF OLD.state = 'ISSUED' AND NEW.state = 'VERIFIED' THEN + SELECT count(*) INTO expected_pod_count + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + SELECT count(*) INTO receipt_count + FROM account_jwt_readiness_pod_receipts + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + IF expected_pod_count <= 0 OR expected_pod_count <> receipt_count + OR NEW.verification_receipt_version IS DISTINCT FROM 2 + OR NEW.verification_source_entry_version IS DISTINCT FROM OLD.entry_version + OR NEW.verification_receipt_sha256 IS NULL + OR NEW.pod_receipt_count IS DISTINCT FROM expected_pod_count + OR NEW.pod_receipt_closure_sha256 IS DISTINCT FROM NEW.verification_receipt_sha256 + OR NEW.entry_version IS DISTINCT FROM OLD.entry_version + 1 + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.compact_token_sha256 IS DISTINCT FROM OLD.compact_token_sha256 + OR NEW.verified_at_epoch_seconds IS NULL + OR NEW.verified_at_epoch_seconds < OLD.planned_issued_at_epoch_seconds + OR NEW.verified_at_epoch_seconds >= OLD.expires_at_epoch_seconds + OR to_timestamp(NEW.verified_at_epoch_seconds) > CURRENT_TIMESTAMP + OR NEW.validator_instance_id IS NULL + OR NEW.validator_binding_digest IS NULL + OR NEW.validator_config_revision IS NULL + OR NEW.validator_peer_uri IS NULL + OR NEW.validator_peer_spki_sha256 IS NULL + OR CURRENT_TIMESTAMP < to_timestamp(OLD.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + OR NEW.terminal_outcome IS NOT NULL THEN + RAISE EXCEPTION 'Readiness V2 VERIFIED transition lacks complete exact per-Pod receipts' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'ABORTED' + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 + AND NEW.terminal_outcome = 'ABORTED' THEN + RETURN NEW; + END IF; + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'EXPIRED' + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 + AND NEW.terminal_outcome = 'EXPIRED' THEN + RETURN NEW; + END IF; + IF OLD.state IN ('ABORTED', 'EXPIRED') AND NEW.state = 'CLEANED' + AND NEW.terminal_outcome = OLD.terminal_outcome + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Account JWT readiness V2 lifecycle transition is unavailable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_lifecycle_v2 + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW WHEN (NEW.entry_plan_version = 2) + EXECUTE FUNCTION account_jwt_readiness_entry_v2_lifecycle_guard(); + +CREATE FUNCTION account_jwt_readiness_inventory_plan_closure_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + operation_id UUID; + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + snapshot_json jsonb; + expected_entry_count integer; + actual_entry_count integer; + expected_pod_count integer; + actual_pod_count integer; +BEGIN + operation_id := CASE WHEN TG_OP = 'DELETE' THEN OLD.rotation_operation_id ELSE NEW.rotation_operation_id END; + SELECT * INTO plan_row FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = operation_id; + IF NOT FOUND OR plan_row.plan_version <> 2 THEN + RETURN NULL; + END IF; + SELECT convert_from(canonical_snapshot, 'UTF8')::jsonb INTO snapshot_json + FROM account_jwt_validator_inventory_snapshots + WHERE snapshot_digest = plan_row.inventory_snapshot_digest; + IF snapshot_json IS NULL THEN + RAISE EXCEPTION 'Readiness V2 inventory snapshot is missing' USING ERRCODE = '23514'; + END IF; + SELECT count(*) * 4 INTO expected_entry_count + FROM jsonb_array_elements(snapshot_json -> 'validators'); + SELECT count(*) INTO actual_entry_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = operation_id AND plan_digest = plan_row.plan_digest; + SELECT COALESCE(sum(jsonb_array_length(validator.value -> 'pods') * 4), 0) + INTO expected_pod_count + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value); + SELECT count(*) INTO actual_pod_count + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = operation_id AND plan_digest = plan_row.plan_digest; + IF actual_entry_count <> expected_entry_count + OR actual_pod_count <> expected_pod_count + OR actual_entry_count > 256 OR actual_pod_count > 256 + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'productionProfiles') AS profile(value) + WHERE NOT EXISTS ( + SELECT 1 FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND entry.validator_id = validator.value ->> 'validatorId' + AND entry.token_profile = profile.value ->> 'tokenProfile' + AND entry.audience = profile.value ->> 'audience' + AND entry.probe_kind = 'REPRESENTATIVE')) + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + WHERE NOT EXISTS ( + SELECT 1 FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND entry.validator_id = validator.value ->> 'validatorId' + AND entry.token_profile = 'account-jwt-readiness-canary' + AND entry.audience = 'firemud-account-jwt-readiness' + AND entry.probe_kind = 'CANARY')) + OR EXISTS ( + SELECT 1 + FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND (SELECT count(*) FROM account_jwt_readiness_validator_pods target + WHERE target.rotation_operation_id = entry.rotation_operation_id + AND target.validator_id = entry.validator_id + AND target.token_profile = entry.token_profile + AND target.audience = entry.audience + AND target.probe_kind = entry.probe_kind) + <> (SELECT jsonb_array_length(validator.value -> 'pods') + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + WHERE validator.value ->> 'validatorId' = entry.validator_id)) THEN + RAISE EXCEPTION 'Readiness V2 plan is missing a validator entry or exact per-Pod inventory row' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_jwt_readiness_plan_v2_closure + AFTER INSERT ON account_jwt_readiness_probe_plans + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +CREATE CONSTRAINT TRIGGER account_jwt_readiness_entry_v2_closure + AFTER INSERT ON account_jwt_readiness_probe_entries + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +CREATE CONSTRAINT TRIGGER account_jwt_readiness_pod_v2_closure + AFTER INSERT ON account_jwt_readiness_validator_pods + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfigurationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfigurationIntegrationTest.java new file mode 100644 index 0000000000..972dcd6165 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfigurationIntegrationTest.java @@ -0,0 +1,71 @@ +package integration.net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerBootstrapConfiguration; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.BootstrapOperationException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.FailureCode; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.transaction.PlatformTransactionManager; + +class AccountJwtSignerBootstrapConfigurationIntegrationTest { + @Test + void enabledCompositionIsCallableButDoesNotReadTrustOrStartReconciliationAtContextStartup() { + AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + AccountJwtSignerDesiredStateRepository desiredStateRepository = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository publicationRepository = + mock(AccountJwtJwksPublicationRepository.class); + AccountJwtReadinessProbeRepository readinessProbeRepository = + mock(AccountJwtReadinessProbeRepository.class); + when(materializerTrust.current()).thenReturn(Optional.empty()); + + new ApplicationContextRunner() + .withUserConfiguration(AccountJwtSignerBootstrapConfiguration.class) + .withBean(AccountJwtSignerMaterializerTrustBinding.class, () -> materializerTrust) + .withBean(AccountJwtSignerDesiredStateRepository.class, () -> desiredStateRepository) + .withBean(AccountJwtJwksPublicationRepository.class, () -> publicationRepository) + .withBean(AccountJwtReadinessProbeRepository.class, () -> readinessProbeRepository) + .withBean(PlatformTransactionManager.class, () -> mock(PlatformTransactionManager.class)) + .withPropertyValues("firemud.account.jwt-signer.bootstrap.enabled=true") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(AccountJwtSignerBootstrapCoordinator.class); + verifyNoInteractions( + materializerTrust, + desiredStateRepository, + publicationRepository, + readinessProbeRepository); + + AccountJwtSignerBootstrapCoordinator coordinator = + context.getBean(AccountJwtSignerBootstrapCoordinator.class); + verifyNoInteractions( + materializerTrust, + desiredStateRepository, + publicationRepository, + readinessProbeRepository); + + assertThatThrownBy(coordinator::enrollOnce) + .isInstanceOf(BootstrapOperationException.class) + .extracting(failure -> ((BootstrapOperationException) failure).failureCode()) + .isEqualTo(FailureCode.PROTECTED_BINDING_UNAVAILABLE); + verify(materializerTrust).current(); + verifyNoInteractions( + desiredStateRepository, publicationRepository, readinessProbeRepository); + }); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationPersistenceIntegrationTest.java new file mode 100644 index 0000000000..f7d9d74e97 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationPersistenceIntegrationTest.java @@ -0,0 +1,508 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +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.DockerClientFactory; +import org.testcontainers.containers.PostgreSQLContainer; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtJwksPublicationPersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "jwt_jwks_publication_proof"; + private static final String EXTERNAL_POSTGRES_URL_ENV = + "FIREMUD_ACCOUNT_SIGNER_TEST_POSTGRES_URL"; + private static final Binding PROD_BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String SECRET_UID = "33333333-3333-4333-8333-333333333333"; + private static final String CONFIG_MAP_UID = "44444444-4444-4444-8444-444444444444"; + private static final String TRUST_DIGEST = "a".repeat(64); + private static final String TRUST_REVISION = "trust-r1"; + private static final String API_DIGEST = "b".repeat(64); + private static final String API_REVISION = "api-r1"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>("postgres:16-alpine"); + private static String testJdbcUrl; + private static String testJdbcUsername; + private static String testJdbcPassword; + private static boolean startedOwnedContainer; + + @BeforeAll + static void configureDatabase() { + String externalUrl = System.getenv(EXTERNAL_POSTGRES_URL_ENV); + if (externalUrl != null) { + testJdbcUrl = validateExternalLoopbackPostgresUrl(externalUrl); + testJdbcUsername = "postgres"; + testJdbcPassword = ""; + return; + } + Assumptions.assumeTrue( + DockerClientFactory.instance().isDockerAvailable(), + "PostgreSQL integration proof requires the explicit loopback tunnel or an available Docker daemon"); + postgres.start(); + startedOwnedContainer = true; + testJdbcUrl = postgres.getJdbcUrl(); + testJdbcUsername = postgres.getUsername(); + testJdbcPassword = postgres.getPassword(); + } + + @AfterAll + static void stopOwnedContainer() { + if (startedOwnedContainer) { + postgres.stop(); + } + } + + @Test + void exactIntentReadbackAndMountedObservationPersistAndRejectEveryMutationPath() + throws Exception { + TestContext context = newTestContext(); + AccountJwtSignerDesiredStateRepository desiredRepository = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + AccountJwtJwksPublicationRepository publicationRepository = + new AccountJwtJwksPublicationRepository(context.dsl(), desiredRepository); + String expectedSnapshotDigest = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", "{\"keys\":[]}", "unrelated.txt", "preserve")); + EnrollmentIdentity enrollment = + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + TRUST_DIGEST, + TRUST_REVISION, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest); + inTransaction(context, () -> desiredRepository.initialize(PROD_BINDING, enrollment)); + + GenerationRequest operation = + inTransaction( + context, () -> desiredRepository.ensureCurrentGenerationRequest(PROD_BINDING, trust())); + GenerationRequest observed = + inTransaction( + context, + () -> + desiredRepository.recordSecretObservation( + PROD_BINDING, + trust(), + operation.operationId(), + operation.operationDigest(), + SECRET_UID, + "12")); + PublicJwk jwk = publicJwk(operation.targetKid()); + GenerationResult result = + inTransaction( + context, + () -> + desiredRepository.recordGenerationResult( + PROD_BINDING, + trust(), + operation.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + "12", + "13", + jwk.json())); + + String retainedJwk = publicJwk("retained-key").jsonWithoutKeyOps(); + String desiredJwks = jwks(retainedJwk, result.publicJwkJson()); + String marker = marker(result, operation); + String invalidBindingMarker = + marker.replaceFirst("\"binding\":\\{[^{}]*}", "\"binding\":\"binding\""); + GenerationRequest currentRequest = + inTransaction( + context, () -> desiredRepository.readCurrentGenerationRequest(PROD_BINDING, trust())); + String invalidMarker = marker.replace("\"pending\":{", "\"pending\":{\"unexpected\":true,"); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + desiredJwks, + invalidMarker))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + desiredJwks, + invalidBindingMarker))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + jwks( + mutateJwk(retainedJwk, "key_ops", List.of("sign")), + result.publicJwkJson()), + marker))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + jwks( + mutateJwk(retainedJwk, "unexpected", "field"), + result.publicJwkJson()), + marker))) + .isInstanceOf(DataAccessException.class); + var intent = + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + desiredJwks, + marker)); + assertThat(intent.operationId()).isEqualTo(result.operationId()); + assertThat(intent.generationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(intent.publicKeyFingerprint()).isEqualTo(result.publicKeyFingerprint()); + assertThat(intent.jwksJson()).doesNotContain("privateKey", "\"d\""); + + var receipt = + inTransaction( + context, + () -> + publicationRepository.recordPublicationReceipt( + PROD_BINDING, + trust(), + result.operationId(), + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "42", + desiredJwks, + marker)); + assertThat(receipt.intentDigest()).isEqualTo(intent.intentDigest()); + assertThat(receipt.expectedResourceVersion()).isEqualTo("41"); + assertThat(receipt.observedResourceVersion()).isEqualTo("42"); + + var mountObservation = + inTransaction( + context, + () -> + publicationRepository.recordMountedCorrespondence( + PROD_BINDING, + trust(), + result.operationId(), + sha256(marker.getBytes(StandardCharsets.UTF_8)), + AccountJwtJwksPublicationRepository.publicDataDigest(desiredJwks, marker), + result.publicKeyFingerprint())); + assertThat(mountObservation.publicationReceiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(mountObservation.publicKeyFingerprint()).isEqualTo(result.publicKeyFingerprint()); + + assertThat(count(context, "account_jwt_jwks_prepublication_intents")).isEqualTo(1L); + assertThat(count(context, "account_jwt_jwks_publication_receipts")).isEqualTo(1L); + assertThat(count(context, "account_jwt_jwks_mount_observations")).isEqualTo(1L); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_jwks_prepublication_intents " + + "SET public_data_digest = ? WHERE operation_id = ?", + "f".repeat(64), + result.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "DELETE FROM account_jwt_jwks_publication_receipts " + + "WHERE operation_id = ?", + result.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> context.dsl().execute("TRUNCATE account_jwt_jwks_mount_observations"))) + .isInstanceOf(DataAccessException.class); + + assertThat(count(context, "account_jwt_jwks_prepublication_intents")).isEqualTo(1L); + assertThat(count(context, "account_jwt_jwks_publication_receipts")).isEqualTo(1L); + assertThat(count(context, "account_jwt_jwks_mount_observations")).isEqualTo(1L); + assertThat( + inTransaction( + context, () -> publicationRepository.readCurrentPublication(PROD_BINDING, trust()))) + .isPresent() + .get() + .satisfies( + evidence -> { + assertThat(evidence.intent()).isEqualTo(intent); + assertThat(evidence.receipt()).contains(receipt); + assertThat(evidence.mountedCorrespondence()).contains(mountObservation); + }); + } + + private static TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = testJdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(testJdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(testJdbcUsername); + dataSource.setPassword(testJdbcPassword); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + return new TestContext(new TransactionTemplate(transactionManager), dsl); + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static long count(TestContext context, String table) { + return java.util.Objects.requireNonNull( + context.dsl().resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class), + "COUNT query must return a scalar row"); + } + + private static TrustFence trust() { + return new TrustFence(CLUSTER_UID, NAMESPACE_UID, TRUST_DIGEST, TRUST_REVISION); + } + + private static String marker(GenerationResult result, GenerationRequest request) + throws Exception { + Map marker = new LinkedHashMap<>(); + marker.put("schemaVersion", 1); + marker.put("phase", "PREPUBLISHED"); + marker.put("operationId", result.operationId().toString()); + marker.put("operationDigest", result.operationDigest()); + marker.put("generationRequestDigest", result.generationRequestDigest()); + marker.put("generationReceiptDigest", result.receiptDigest()); + Map binding = new LinkedHashMap<>(); + binding.put("environmentId", result.binding().environmentId()); + binding.put("clusterId", result.binding().clusterId()); + binding.put("namespace", result.binding().namespace()); + binding.put( + "expectedClusterIncarnationUid", result.trustFence().expectedClusterIncarnationUid()); + binding.put("expectedNamespaceUid", result.trustFence().expectedNamespaceUid()); + binding.put("trustBindingDigest", result.trustFence().bindingDigest()); + binding.put("trustConfigRevision", result.trustFence().configRevision()); + binding.put("apiBindingDigest", API_DIGEST); + binding.put("apiConfigRevision", API_REVISION); + marker.put("binding", binding); + marker.put("publicConfigMap", Map.of("name", "jwt-jwks")); + marker.put("expectedDurableActive", Map.of("present", false)); + marker.put("expectedPublishedActive", Map.of("present", false)); + marker.put( + "pending", + Map.of( + "generation", + result.targetGeneration(), + "kid", + result.targetKid(), + "algorithm", + result.targetAlgorithm(), + "publicKeyFingerprint", + result.publicKeyFingerprint())); + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(marker)), + StandardCharsets.UTF_8); + } + + private static PublicJwk publicJwk(String kid) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + RSAPublicKey key = (RSAPublicKey) generator.generateKeyPair().getPublic(); + String modulus = encodeUnsigned(key.getModulus()); + String exponent = encodeUnsigned(key.getPublicExponent()); + Map jwk = new LinkedHashMap<>(); + jwk.put("alg", "RS256"); + jwk.put("e", exponent); + jwk.put("key_ops", List.of("verify")); + jwk.put("kid", kid); + jwk.put("kty", "RSA"); + jwk.put("n", modulus); + jwk.put("use", "sig"); + String json = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(jwk)), + StandardCharsets.UTF_8); + Map withoutKeyOps = new LinkedHashMap<>(jwk); + withoutKeyOps.remove("key_ops"); + String jsonWithoutKeyOps = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(withoutKeyOps)), + StandardCharsets.UTF_8); + String fingerprint = + sha256( + Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(Map.of("e", exponent, "kty", "RSA", "n", modulus)))); + return new PublicJwk(json, jsonWithoutKeyOps, fingerprint); + } + + private static String jwks(String retainedJwk, String targetJwk) { + return "{\"keys\":[" + retainedJwk + "," + targetJwk + "]}"; + } + + private static String mutateJwk(String jwkJson, String fieldName, Object value) { + try { + @SuppressWarnings("unchecked") + Map jwk = JSON.readValue(jwkJson, Map.class); + jwk.put(fieldName, value); + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(jwk)), + StandardCharsets.UTF_8); + } catch (Exception ex) { + throw new IllegalStateException("Test JWK could not be updated", ex); + } + } + + private static String encodeUnsigned(java.math.BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is required for the persistence fixture", ex); + } + } + + private static String validateExternalLoopbackPostgresUrl(String jdbcUrl) { + final URI uri; + try { + if (!jdbcUrl.startsWith("jdbc:")) { + throw new IllegalArgumentException("not a JDBC URL"); + } + uri = URI.create(jdbcUrl.substring("jdbc:".length())); + } catch (RuntimeException ex) { + throw new IllegalStateException( + EXTERNAL_POSTGRES_URL_ENV + " must target jdbc:postgresql://127.0.0.1:/postgres", + ex); + } + if (!"postgresql".equals(uri.getScheme()) + || !"127.0.0.1".equals(uri.getHost()) + || uri.getPort() < 1 + || uri.getPort() > 65_535 + || !"/postgres".equals(uri.getPath()) + || uri.getUserInfo() != null + || uri.getQuery() != null + || uri.getFragment() != null) { + throw new IllegalStateException( + EXTERNAL_POSTGRES_URL_ENV + " must target jdbc:postgresql://127.0.0.1:/postgres"); + } + return jdbcUrl; + } + + private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + + private record TestContext(TransactionTemplate transaction, DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStatePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStatePersistenceIntegrationTest.java new file mode 100644 index 0000000000..f35aa5b130 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStatePersistenceIntegrationTest.java @@ -0,0 +1,1085 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.math.BigInteger; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.PublicKey; +import java.security.interfaces.RSAPublicKey; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.Callable; +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 javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionPreparation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtSignerMaterializationService; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +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.DockerClientFactory; +import org.testcontainers.containers.PostgreSQLContainer; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtSignerDesiredStatePersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "jwt_signer_generation_proof"; + private static final String EXTERNAL_POSTGRES_URL_ENV = + "FIREMUD_ACCOUNT_SIGNER_TEST_POSTGRES_URL"; + private static final Binding PROD_BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String SECRET_UID = "33333333-3333-4333-8333-333333333333"; + private static final String TRUST_DIGEST = "b".repeat(64); + private static final String TRUST_REVISION = "trust-revision-1"; + private static final String MATERIALIZER_URI = + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + private static final byte[] PEER_SPKI = + "authenticated materializer integration key".getBytes(StandardCharsets.US_ASCII); + + private static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>("postgres:16-alpine"); + private static String testJdbcUrl; + private static String testJdbcUsername; + private static String testJdbcPassword; + private static boolean startedOwnedContainer; + + @Test + void v49RejectsPartialEnrollmentPinsDigestsAndResourceUid() throws Exception { + TestContext context = newTestContext(); + + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_desired_states " + + "(environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "enrollment_cluster_incarnation_uid) " + + "VALUES ('partial-pin', 'prod-cluster-1', 'firemud-prod', " + + "'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK', ?)", + UUID.fromString(CLUSTER_UID))) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_desired_states " + + "(environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "enrollment_cluster_incarnation_uid, enrollment_namespace_uid, " + + "enrollment_materializer_binding_digest, " + + "enrollment_materializer_config_revision, " + + "enrollment_api_config_revision, enrollment_public_config_map_uid, " + + "enrollment_public_config_map_resource_version, " + + "enrollment_public_config_map_snapshot_digest) " + + "VALUES ('partial-digest', 'prod-cluster-1', 'firemud-prod', " + + "'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK', ?, ?, ?, ?, ?, ?, ?, ?)", + UUID.fromString(CLUSTER_UID), + UUID.fromString(NAMESPACE_UID), + TRUST_DIGEST, + TRUST_REVISION, + "api-revision-1", + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "12", + "c".repeat(64))) + .isInstanceOf(DataAccessException.class); + + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_desired_states " + + "(environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "enrollment_cluster_incarnation_uid, enrollment_namespace_uid, " + + "enrollment_materializer_binding_digest, " + + "enrollment_materializer_config_revision, enrollment_api_binding_digest, " + + "enrollment_api_config_revision, enrollment_public_config_map_resource_version, " + + "enrollment_public_config_map_snapshot_digest) " + + "VALUES ('partial-resource-uid', 'prod-cluster-1', 'firemud-prod', " + + "'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK', ?, ?, ?, ?, ?, ?, ?, ?)", + UUID.fromString(CLUSTER_UID), + UUID.fromString(NAMESPACE_UID), + TRUST_DIGEST, + TRUST_REVISION, + "d".repeat(64), + "api-revision-1", + "12", + "c".repeat(64))) + .isInstanceOf(DataAccessException.class); + + AccountJwtSignerDesiredStateRepository repository = repository(context); + EnrollmentIdentity enrollment = enrollmentIdentity(); + inTransaction(context, () -> repository.initialize(PROD_BINDING, enrollment)); + GenerationRequest current = + inTransaction( + context, () -> repository.ensureCurrentGenerationRequest(PROD_BINDING, trust())); + + assertRejectedPartialPromotionInsert(context, current, "materializer_trust_binding_digest"); + assertRejectedPartialPromotionInsert(context, current, "api_config_revision"); + assertRejectedPartialPromotionInsert(context, current, "expected_public_config_map_uid"); + } + + @Test + void directPromotionCommitWithoutOwnerCreatedReadinessProofIsRejected() throws Exception { + TestContext context = newTestContext(); + AccountJwtSignerDesiredStateRepository repository = repository(context); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.commitPreparedPromotion( + PROD_BINDING, trust(), UUID.randomUUID(), null))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("readiness proof"); + assertThat(count(context, "account_jwt_signer_desired_states")).isZero(); + } + + @BeforeAll + static void configureDatabase() { + String externalUrl = System.getenv(EXTERNAL_POSTGRES_URL_ENV); + if (externalUrl != null) { + testJdbcUrl = validateExternalLoopbackPostgresUrl(externalUrl); + testJdbcUsername = "postgres"; + testJdbcPassword = ""; + return; + } + + Assumptions.assumeTrue( + DockerClientFactory.instance().isDockerAvailable(), + "PostgreSQL integration proof requires the explicit loopback tunnel or an available Docker daemon"); + postgres.start(); + startedOwnedContainer = true; + testJdbcUrl = postgres.getJdbcUrl(); + testJdbcUsername = postgres.getUsername(); + testJdbcPassword = postgres.getPassword(); + } + + @AfterAll + static void stopOwnedContainer() { + if (startedOwnedContainer) { + postgres.stop(); + } + } + + private static String validateExternalLoopbackPostgresUrl(String jdbcUrl) { + final URI uri; + try { + if (!jdbcUrl.startsWith("jdbc:")) { + throw new IllegalArgumentException("not a JDBC URL"); + } + uri = URI.create(jdbcUrl.substring("jdbc:".length())); + } catch (RuntimeException ex) { + throw new IllegalStateException( + EXTERNAL_POSTGRES_URL_ENV + " must be a loopback PostgreSQL JDBC URL", ex); + } + if (!"postgresql".equals(uri.getScheme()) + || !"127.0.0.1".equals(uri.getHost()) + || uri.getPort() < 1 + || uri.getPort() > 65535 + || !"/postgres".equals(uri.getPath()) + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null) { + throw new IllegalStateException( + EXTERNAL_POSTGRES_URL_ENV + " must target jdbc:postgresql://127.0.0.1:/postgres"); + } + return jdbcUrl; + } + + @Test + void explicitInitializationAndGenerationReceiptPersistOnlyNonSecretOwnerEvidence() + throws Exception { + TestContext context = newTestContext(); + AccountJwtSignerDesiredStateRepository repository = repository(context); + String resourceVersionAtMaximumLength = "r".repeat(256); + assertThat(count(context, "account_jwt_signer_desired_states")).isZero(); + + var state = + inTransaction(context, () -> repository.initialize(PROD_BINDING, enrollmentIdentity())); + assertThat(state.recordVersion()).isEqualTo(1); + assertThat(state.durableActive()).isEmpty(); + assertThat(state.publishedActive()).isEmpty(); + assertThat(state.generationOperationId()).isEmpty(); + assertThat(state.preparedOperationId()).isEmpty(); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> repository.read(binding("stage", "prod-cluster-1", "firemud-prod")))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.MissingDesiredStateException.class); + assertThat(count(context, "account_jwt_signer_desired_states")).isEqualTo(1L); + + GenerationRequest operation = + inTransaction( + context, () -> repository.ensureCurrentGenerationRequest(PROD_BINDING, trust())); + assertThat(operation.targetGeneration()).isEqualTo("1"); + assertThat(operation.targetKid()).startsWith("jwt-1-"); + assertThat(operation.phase()) + .isEqualTo(AccountJwtSignerDesiredStateRepository.GenerationPhase.OBSERVE_PRIVATE_SECRET); + assertThat(operation.publicKeyFingerprint()).isEmpty(); + assertThat(operation.publicJwkJson()).isEmpty(); + + GenerationRequest observation = + inTransaction( + context, + () -> + repository.recordSecretObservation( + PROD_BINDING, + trust(), + operation.operationId(), + operation.operationDigest(), + SECRET_UID, + resourceVersionAtMaximumLength)); + GenerationRequest observationRetry = + inTransaction( + context, + () -> + repository.recordSecretObservation( + PROD_BINDING, + trust(), + operation.operationId(), + operation.operationDigest(), + SECRET_UID, + resourceVersionAtMaximumLength)); + assertThat(observationRetry).isEqualTo(observation); + assertThat(observation.phase()) + .isEqualTo(AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATE_PENDING); + assertThat(observation.generationRequestDigest()).hasSize(64); + assertThat(observation.expectedSecretResourceVersion()) + .isEqualTo(resourceVersionAtMaximumLength); + assertThat(observation.secretUid()).isEqualTo(SECRET_UID); + + PublicJwk jwk = publicJwk(operation.targetKid()); + GenerationResult result = + inTransaction( + context, + () -> + repository.recordGenerationResult( + PROD_BINDING, + trust(), + operation.operationId(), + observation.generationRequestDigest(), + SECRET_UID, + resourceVersionAtMaximumLength, + "13", + jwk.json())); + GenerationResult exactRetry = + inTransaction( + context, + () -> + repository.recordGenerationResult( + PROD_BINDING, + trust(), + operation.operationId(), + observation.generationRequestDigest(), + SECRET_UID, + resourceVersionAtMaximumLength, + "13", + jwk.json())); + assertThat(exactRetry).isEqualTo(result); + assertThat(result.publicKeyFingerprint()).isEqualTo(jwk.fingerprint()); + assertThat(result.expectedPriorResourceVersion()).isEqualTo(resourceVersionAtMaximumLength); + assertThat(result.observedResourceVersion()).isEqualTo("13"); + assertThat(result.publicJwkJson()).doesNotContain("\"d\""); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.prepareCurrentGeneration( + PROD_BINDING, trust(), callerSuppliedPreparation(result), null))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Account-verified readiness proof is required"); + assertThat(count(context, "account_jwt_signer_generation_operations")).isEqualTo(1L); + assertThat(count(context, "account_jwt_signer_secret_observations")).isEqualTo(1L); + assertThat(count(context, "account_jwt_signer_generation_results")).isEqualTo(1L); + assertThat( + context + .dsl() + .resultQuery( + "SELECT record_version, generation_operation_id, prepared_operation_id, " + + "durable_active_generation, published_active_generation " + + "FROM account_jwt_signer_desired_states WHERE environment_id = 'prod'") + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("record_version", Long.class)).isEqualTo(2L); + assertThat(row.get("generation_operation_id", UUID.class)) + .isEqualTo(operation.operationId()); + assertThat(row.get("prepared_operation_id", UUID.class)).isNull(); + assertThat(row.get("durable_active_generation", Long.class)).isNull(); + assertThat(row.get("published_active_generation", Long.class)).isNull(); + }); + assertThat( + context + .dsl() + .resultQuery( + "SELECT custody_mode, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, private_secret_name, " + + "secret_uid, observed_resource_version, generation_request_digest " + + "FROM account_jwt_signer_secret_observations") + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("custody_mode", String.class)) + .isEqualTo("INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK"); + assertThat(row.get("expected_cluster_incarnation_uid", UUID.class)) + .isEqualTo(UUID.fromString(CLUSTER_UID)); + assertThat(row.get("expected_namespace_uid", UUID.class)) + .isEqualTo(UUID.fromString(NAMESPACE_UID)); + assertThat(row.get("trust_binding_digest", String.class)).isEqualTo(TRUST_DIGEST); + assertThat(row.get("trust_config_revision", String.class)).isEqualTo(TRUST_REVISION); + assertThat(row.get("private_secret_name", String.class)) + .isEqualTo("jwt-signing-keys"); + assertThat(row.get("secret_uid", UUID.class)).isEqualTo(UUID.fromString(SECRET_UID)); + assertThat(row.get("observed_resource_version", String.class)) + .isEqualTo(resourceVersionAtMaximumLength); + assertThat(row.get("generation_request_digest", String.class)) + .isEqualTo(observation.generationRequestDigest()); + }); + assertThat( + context + .dsl() + .resultQuery( + "SELECT expected_prior_resource_version, observed_resource_version, " + + "target_generation, target_kid, target_algorithm, public_key_fingerprint, " + + "public_jwk_json, receipt_digest FROM account_jwt_signer_generation_results") + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("expected_prior_resource_version", String.class)) + .isEqualTo(resourceVersionAtMaximumLength); + assertThat(row.get("observed_resource_version", String.class)).isEqualTo("13"); + assertThat(row.get("target_generation", Long.class)).isEqualTo(1L); + assertThat(row.get("target_kid", String.class)).isEqualTo(operation.targetKid()); + assertThat(row.get("target_algorithm", String.class)).isEqualTo("RS256"); + assertThat(row.get("public_key_fingerprint", String.class)) + .isEqualTo(jwk.fingerprint()); + assertThat(row.get("public_jwk_json", String.class)).isEqualTo(jwk.json()); + assertThat(row.get("receipt_digest", String.class)).isEqualTo(result.receiptDigest()); + }); + + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_secret_observations " + + "SELECT operation_id, environment_id, cluster_id, " + + "kubernetes_namespace, custody_mode, operation_digest_version, " + + "operation_digest, expected_record_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, private_secret_name, " + + "secret_uid, {0}, observation_digest_version, observation_digest, " + + "generation_request_digest FROM account_jwt_signer_secret_observations", + "r".repeat(257))) + .isInstanceOf(DataAccessException.class); + for (String invalidResourceVersion : List.of("r\n", "r\u0001")) { + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_secret_observations " + + "SELECT operation_id, environment_id, cluster_id, " + + "kubernetes_namespace, custody_mode, operation_digest_version, " + + "operation_digest, expected_record_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, private_secret_name, " + + "secret_uid, {0}, observation_digest_version, observation_digest, " + + "generation_request_digest FROM account_jwt_signer_secret_observations", + invalidResourceVersion)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("account_jwt_signer_observation_resource_version_check"); + } + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.recordSecretObservation( + PROD_BINDING, + trust(), + operation.operationId(), + operation.operationDigest(), + SECRET_UID, + "14"))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.recordGenerationResult( + PROD_BINDING, + trust(), + operation.operationId(), + observation.generationRequestDigest(), + SECRET_UID, + resourceVersionAtMaximumLength, + "14", + jwk.json()))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); + + assertThatThrownBy( + () -> + insertResult( + context, result, result.desiredStateVersion() + 1, result.receiptDigest())) + .isInstanceOf(DataAccessException.class); + assertThat(count(context, "account_jwt_signer_generation_results")).isEqualTo(1L); + + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_signer_generation_operations SET target_kid = 'changed' " + + "WHERE operation_id = ?", + operation.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "DELETE FROM account_jwt_signer_generation_operations WHERE operation_id = ?", + operation.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_signer_secret_observations SET trust_config_revision = 'changed' " + + "WHERE operation_id = ?", + operation.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "DELETE FROM account_jwt_signer_secret_observations WHERE operation_id = ?", + operation.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_signer_generation_results SET public_key_fingerprint = ? " + + "WHERE operation_id = ?", + "0".repeat(64), + operation.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "DELETE FROM account_jwt_signer_generation_results WHERE operation_id = ?", + operation.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> context.dsl().execute("TRUNCATE account_jwt_signer_generation_operations")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> context.dsl().execute("TRUNCATE account_jwt_signer_secret_observations")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> context.dsl().execute("TRUNCATE account_jwt_signer_generation_results")) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_signer_desired_states SET prepared_operation_id = ? " + + "WHERE environment_id = 'prod'", + UUID.randomUUID())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> context.dsl().execute("TRUNCATE account_jwt_signer_desired_states")) + .isInstanceOf(DataAccessException.class); + } + + @Test + void resultTriggerHoldsDesiredStateLockUntilAccountTransactionCommits() throws Exception { + TestContext context = newTestContext(); + AccountJwtSignerDesiredStateRepository repository = repository(context); + inTransaction(context, () -> repository.initialize(PROD_BINDING, enrollmentIdentity())); + GenerationRequest operation = + inTransaction( + context, () -> repository.ensureCurrentGenerationRequest(PROD_BINDING, trust())); + GenerationRequest observation = + inTransaction( + context, + () -> + repository.recordSecretObservation( + PROD_BINDING, + trust(), + operation.operationId(), + operation.operationDigest(), + SECRET_UID, + "12")); + PublicJwk jwk = publicJwk(operation.targetKid()); + CountDownLatch resultInserted = new CountDownLatch(1); + CountDownLatch allowCommit = new CountDownLatch(1); + CountDownLatch competingSelectStarted = new CountDownLatch(1); + CountDownLatch competingSelectCompleted = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future resultTransaction = + executor.submit( + () -> + context + .transaction() + .execute( + status -> { + repository.recordGenerationResult( + PROD_BINDING, + trust(), + operation.operationId(), + observation.generationRequestDigest(), + SECRET_UID, + "12", + "13", + jwk.json()); + resultInserted.countDown(); + await( + allowCommit, "JWT generation receipt transaction was not released"); + return null; + })); + assertThat(resultInserted.await(10, TimeUnit.SECONDS)).isTrue(); + Future competingTransaction = + executor.submit( + () -> + context + .transaction() + .execute( + status -> { + competingSelectStarted.countDown(); + context + .dsl() + .fetchOne( + "SELECT record_version FROM account_jwt_signer_desired_states " + + "WHERE environment_id = 'prod' FOR UPDATE"); + competingSelectCompleted.countDown(); + return null; + })); + assertThat(competingSelectStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(competingSelectCompleted.await(250, TimeUnit.MILLISECONDS)).isFalse(); + allowCommit.countDown(); + resultTransaction.get(10, TimeUnit.SECONDS); + competingTransaction.get(10, TimeUnit.SECONDS); + assertThat(competingSelectCompleted.getCount()).isZero(); + } finally { + allowCommit.countDown(); + executor.shutdownNow(); + executor.awaitTermination(10, TimeUnit.SECONDS); + } + } + + @Test + void changedProtectedTrustBeforeCommitRollsBackGenerationReceipt() throws Exception { + TestContext context = newTestContext(); + AccountJwtSignerDesiredStateRepository repository = repository(context); + String peerPin = sha256(PEER_SPKI); + AccountJwtSignerMaterializerTrustBinding.Binding initial = + materializerTrust(peerPin, TRUST_REVISION); + inTransaction( + context, + () -> + repository.initialize( + PROD_BINDING, + enrollmentIdentity(initial.bindingDigest(), initial.configRevision()))); + TrustFence initialTrust = + new TrustFence( + initial.expectedClusterIncarnationUid(), + initial.expectedNamespaceUid(), + initial.bindingDigest(), + initial.configRevision()); + GenerationRequest operation = + inTransaction( + context, () -> repository.ensureCurrentGenerationRequest(PROD_BINDING, initialTrust)); + GenerationRequest observation = + inTransaction( + context, + () -> + repository.recordSecretObservation( + PROD_BINDING, + initialTrust, + operation.operationId(), + operation.operationDigest(), + SECRET_UID, + "12")); + + AccountJwtSignerMaterializerTrustBinding provider = + mock(AccountJwtSignerMaterializerTrustBinding.class); + AccountJwtSignerMaterializerTrustBinding.Binding changed = + materializerTrust( + sha256("replacement peer key".getBytes(StandardCharsets.US_ASCII)), "revision-2"); + when(provider.current()) + .thenReturn(Optional.of(initial), Optional.of(initial), Optional.of(changed)); + AccountJwtSignerMaterializationService service = + new AccountJwtSignerMaterializationService( + repository, + new AccountJwtReadinessProbeRepository( + context.dsl(), + repository, + new AccountJwtJwksPublicationRepository(context.dsl(), repository)), + provider, + context.transactionManager()); + AccountJwtSignerMaterializerTlsInterceptor interceptor = + new AccountJwtSignerMaterializerTlsInterceptor(provider); + PublicJwk jwk = publicJwk(operation.targetKid()); + RecordGenerationResultRequest request = + RecordGenerationResultRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(operation.operationId().toString()) + .setGenerationRequestDigest(observation.generationRequestDigest()) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion("12") + .setObservedResourceVersion("13") + .setPublicJwkJson(jwk.json()) + .build(); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer(interceptor, service, request, response, PEER_SPKI); + + assertThat(response.error.type()).isEqualTo(StatusRuntimeException.class.getName()); + assertThat(response.error.code()).isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED); + assertThat(response.error.message()).contains("PERMISSION_DENIED"); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + verify(provider, times(3)).current(); + assertThat(count(context, "account_jwt_signer_generation_results")).isZero(); + assertThat(count(context, "account_jwt_signer_secret_observations")).isEqualTo(1L); + assertThat( + context + .dsl() + .resultQuery( + "SELECT record_version, generation_operation_id, prepared_operation_id " + + "FROM account_jwt_signer_desired_states WHERE environment_id = 'prod'") + .fetchOne()) + .satisfies( + row -> { + assertThat(row.get("record_version", Long.class)).isEqualTo(2L); + assertThat(row.get("generation_operation_id", UUID.class)) + .isEqualTo(operation.operationId()); + assertThat(row.get("prepared_operation_id", UUID.class)).isNull(); + }); + } + + private static AccountJwtSignerDesiredStateRepository repository(TestContext context) { + return new AccountJwtSignerDesiredStateRepository(context.dsl()); + } + + private static long count(TestContext context, String tableName) { + return java.util.Objects.requireNonNull( + context.dsl().resultQuery("SELECT COUNT(*) FROM " + tableName).fetchOne(0, Long.class), + "COUNT query must return a scalar row"); + } + + private static void assertRejectedPartialPromotionInsert( + TestContext context, GenerationRequest generation, String omittedLifecycleField) { + Map values = new LinkedHashMap<>(); + values.put("operation_id", UUID.randomUUID()); + values.put("environment_id", PROD_BINDING.environmentId()); + values.put("cluster_id", PROD_BINDING.clusterId()); + values.put("kubernetes_namespace", PROD_BINDING.namespace()); + values.put("custody_mode", PROD_BINDING.mode().value()); + values.put("request_digest_version", 1); + values.put("request_digest", "a".repeat(64)); + values.put("expected_record_version", generation.desiredStateVersion()); + values.put("target_generation", Long.parseLong(generation.targetGeneration())); + values.put("target_kid", generation.targetKid()); + values.put("target_algorithm", "RS256"); + values.put("target_public_key_fingerprint", "b".repeat(64)); + values.put("expected_private_secret_resource_version", "12"); + values.put("expected_public_jwks_resource_version", "13"); + values.put("operation_action", "PROMOTE_PENDING"); + values.put( + "allowed_private_slots_canonical_bytes", + "[\"current\",\"pending\",\"previous\"]".getBytes(StandardCharsets.US_ASCII)); + values.put("status", "PREPARED"); + values.put("generation_operation_id", generation.operationId()); + values.put("expected_cluster_incarnation_uid", UUID.fromString(CLUSTER_UID)); + values.put("expected_namespace_uid", UUID.fromString(NAMESPACE_UID)); + values.put("materializer_trust_binding_digest", TRUST_DIGEST); + values.put("materializer_trust_config_revision", TRUST_REVISION); + values.put("api_binding_digest", "d".repeat(64)); + values.put("api_config_revision", "api-revision-1"); + values.put("expected_private_secret_uid", UUID.fromString(SECRET_UID)); + values.put( + "expected_public_config_map_uid", UUID.fromString("44444444-4444-4444-8444-444444444444")); + values.put("prepublication_intent_digest", "a".repeat(64)); + values.put("prepublication_receipt_digest", "b".repeat(64)); + values.put("mounted_observation_digest", "c".repeat(64)); + values.put("readiness_plan_digest", "d".repeat(64)); + values.put("readiness_evidence_digest", "e".repeat(64)); + values.put("expected_public_jwks_json", "{\"keys\":[]}"); + values.put("expected_active_generation_marker_json", "{\"phase\":\"ACTIVE\"}"); + values.put(omittedLifecycleField, null); + + String columns = String.join(", ", values.keySet()); + String placeholders = String.join(", ", java.util.Collections.nCopies(values.size(), "?")); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_promotion_operations (" + + columns + + ") VALUES (" + + placeholders + + ")", + values.values().toArray())) + .isInstanceOf(DataAccessException.class); + } + + private static GenerationResult insertResult( + TestContext context, + GenerationResult result, + long desiredStateVersion, + String receiptDigest) { + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_generation_results " + + "(operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, desired_state_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, " + + "expected_prior_resource_version, observed_resource_version, target_generation, " + + "target_kid, target_algorithm, public_key_fingerprint, public_jwk_json, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'jwt-signing-keys', ?, ?, ?, ?, ?, " + + "'RS256', ?, ?, ?)", + result.operationId(), + result.binding().environmentId(), + result.binding().clusterId(), + result.binding().namespace(), + result.binding().mode().value(), + result.operationDigest(), + result.generationRequestDigest(), + desiredStateVersion, + UUID.fromString(result.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(result.trustFence().expectedNamespaceUid()), + result.trustFence().bindingDigest(), + result.trustFence().configRevision(), + UUID.fromString(result.secretUid()), + result.expectedPriorResourceVersion(), + result.observedResourceVersion(), + Long.parseLong(result.targetGeneration()), + result.targetKid(), + result.publicKeyFingerprint(), + result.publicJwkJson(), + receiptDigest); + return result; + } + + private static AccountJwtSignerDesiredStateRepository.TrustFence trust() { + return new TrustFence(CLUSTER_UID, NAMESPACE_UID, TRUST_DIGEST, TRUST_REVISION); + } + + private static EnrollmentIdentity enrollmentIdentity() { + return enrollmentIdentity(TRUST_DIGEST, TRUST_REVISION); + } + + private static EnrollmentIdentity enrollmentIdentity(String trustDigest, String trustRevision) { + return new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + trustDigest, + trustRevision, + "d".repeat(64), + "api-revision-1", + "44444444-4444-4444-8444-444444444444", + "12", + "e".repeat(64)); + } + + /** A bounded caller DTO paired with no owner proof; it is deliberately non-authorizing. */ + private static PromotionPreparation callerSuppliedPreparation(GenerationResult result) { + EnrollmentIdentity enrollment = enrollmentIdentity(); + return new PromotionPreparation( + result.operationId(), + result, + enrollment, + enrollment.apiBindingDigest(), + enrollment.apiConfigRevision(), + enrollment.publicConfigMapUid(), + "14", + "a".repeat(64), + "b".repeat(64), + "c".repeat(64), + "1".repeat(64), + "2".repeat(64), + "{\"keys\":[" + result.publicJwkJson() + "]}"); + } + + private static AccountJwtSignerMaterializerTrustBinding.Binding materializerTrust( + String pin, String revision) { + List pins = List.of(pin); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, + PROD_BINDING.environmentId(), + PROD_BINDING.clusterId(), + PROD_BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + pins); + return new AccountJwtSignerMaterializerTrustBinding.Binding( + PROD_BINDING.environmentId(), + PROD_BINDING.clusterId(), + PROD_BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + pins, + revision, + digest); + } + + private static Binding binding(String environment, String cluster, String namespace) { + return new Binding( + environment, cluster, namespace, CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + } + + private static PublicJwk publicJwk(String kid) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + RSAPublicKey key = (RSAPublicKey) generator.generateKeyPair().getPublic(); + String modulus = encodeUnsigned(key.getModulus()); + String exponent = encodeUnsigned(key.getPublicExponent()); + Map jwk = new LinkedHashMap<>(); + jwk.put("alg", "RS256"); + jwk.put("e", exponent); + jwk.put("key_ops", List.of("verify")); + jwk.put("kid", kid); + jwk.put("kty", "RSA"); + jwk.put("n", modulus); + jwk.put("use", "sig"); + String json = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(jwk)), + StandardCharsets.UTF_8); + String fingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder() + .build() + .writeValueAsString( + Map.of("e", exponent, "kty", "RSA", "n", modulus))))); + return new PublicJwk(json, fingerprint); + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return java.util.Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + private static void invokeWithAuthenticatedPeer( + AccountJwtSignerMaterializerTlsInterceptor interceptor, + AccountJwtSignerMaterializationService service, + RecordGenerationResultRequest request, + RecordingObserver response, + byte[] peerSpki) + throws Exception { + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + SSLSession sslSession = mock(SSLSession.class); + java.security.cert.X509Certificate certificate = mock(java.security.cert.X509Certificate.class); + PublicKey publicKey = mock(PublicKey.class); + when(publicKey.getEncoded()).thenReturn(peerSpki); + when(certificate.getPublicKey()).thenReturn(publicKey); + when(certificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, MATERIALIZER_URI))); + when(sslSession.getPeerCertificates()) + .thenReturn(new java.security.cert.Certificate[] {certificate}); + when(call.getAttributes()) + .thenReturn( + Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession).build()); + ServerCallHandler next = + (interceptedCall, headers) -> { + service.recordGenerationResult(request, response); + return new ServerCall.Listener<>() {}; + }; + interceptor.interceptCall(call, new Metadata(), next); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = testJdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(testJdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(testJdbcUsername); + dataSource.setPassword(testJdbcPassword); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + return new TestContext(new TransactionTemplate(transactionManager), transactionManager, dsl); + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static PublicJwk publicJwkFor(GenerationRequest request) throws Exception { + return publicJwk(request.targetKid()); + } + + private static String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static void await(CountDownLatch latch, String message) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException(message); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(message, ex); + } + } + + private static final class RecordingObserver implements StreamObserver { + private T value; + private ErrorDiagnostic error; + private boolean completed; + + @Override + public void onNext(T value) { + this.value = value; + } + + @Override + public void onError(Throwable error) { + this.error = + new ErrorDiagnostic( + error.getClass().getName(), + error instanceof StatusRuntimeException statusError + ? statusError.getStatus().getCode() + : null, + error.getMessage()); + } + + @Override + public void onCompleted() { + completed = true; + } + + private record ErrorDiagnostic(String type, io.grpc.Status.Code code, String message) {} + } + + private static List race(Callable left, Callable right) throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(2); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + try { + Future leftResult = executor.submit(awaitStart(left, ready, start)); + Future rightResult = executor.submit(awaitStart(right, ready, start)); + if (!ready.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("JWT signer persistence workers did not become ready"); + } + start.countDown(); + return List.of(leftResult.get(30, TimeUnit.SECONDS), rightResult.get(30, TimeUnit.SECONDS)); + } finally { + executor.shutdownNow(); + executor.awaitTermination(10, TimeUnit.SECONDS); + } + } + + private static Callable awaitStart( + Callable operation, CountDownLatch ready, CountDownLatch start) { + return () -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("JWT signer persistence race start was not released"); + } + return operation.call(); + }; + } + + private record PublicJwk(String json, String fingerprint) {} + + private record TestContext( + TransactionTemplate transaction, + DataSourceTransactionManager transactionManager, + DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java new file mode 100644 index 0000000000..a570e5c362 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java @@ -0,0 +1,259 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.repository.AccountJwtValidatorInventoryRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +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.DockerClientFactory; +import org.testcontainers.containers.PostgreSQLContainer; + +/** Persistence-component proof only; fixture bytes are not evidence of a live Kubernetes read. */ +class AccountJwtValidatorInventoryPersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "jwt_inv_snapshot_"; + private static final String EXTERNAL_POSTGRES_URL_ENV = + "FIREMUD_ACCOUNT_SIGNER_TEST_POSTGRES_URL"; + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>("postgres:16-alpine"); + + private static String jdbcUrl; + private static String username; + private static String password; + private static boolean startedOwnedContainer; + + @BeforeAll + static void configureDatabase() { + String externalUrl = System.getenv(EXTERNAL_POSTGRES_URL_ENV); + if (externalUrl != null) { + jdbcUrl = validateExternalLoopbackPostgresUrl(externalUrl); + username = "postgres"; + password = ""; + return; + } + Assumptions.assumeTrue( + DockerClientFactory.instance().isDockerAvailable(), + "PostgreSQL integration proof requires the explicit loopback tunnel or an available Docker daemon"); + postgres.start(); + startedOwnedContainer = true; + jdbcUrl = postgres.getJdbcUrl(); + username = postgres.getUsername(); + password = postgres.getPassword(); + } + + @AfterAll + static void stopOwnedContainer() { + if (startedOwnedContainer) { + postgres.stop(); + } + } + + @Test + void exactDigestRetryReadsBackImmutableCanonicalBytesAndRejectsMutation() throws Exception { + TestContext context = newTestContext(); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(context.dsl()); + InventorySnapshot candidate = snapshot(); + + var first = + inTransaction(context, () -> repository.persistOrReadback(candidate, BINDING, trust())); + var retry = + inTransaction(context, () -> repository.persistOrReadback(candidate, BINDING, trust())); + + assertThat(retry).isEqualTo(first); + assertThat( + context + .dsl() + .resultQuery("SELECT COUNT(*) FROM account_jwt_validator_inventory_snapshots") + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat(retry.canonicalBytes()).isEqualTo(candidate.canonicalBytes()); + assertThat(new String(retry.canonicalBytes(), StandardCharsets.UTF_8)) + .doesNotContain("privateKey"); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_validator_inventory_snapshots " + + "SET canonical_snapshot = ? WHERE snapshot_digest = ?", + "{}".getBytes(StandardCharsets.UTF_8), + retry.digest())) + .isInstanceOf(DataAccessException.class); + + long plansBeforeTruncate = count(context, "account_jwt_readiness_probe_plans"); + assertThatThrownBy( + () -> + context + .dsl() + .execute("TRUNCATE TABLE account_jwt_validator_inventory_snapshots CASCADE")) + .isInstanceOf(DataAccessException.class); + assertThat(count(context, "account_jwt_validator_inventory_snapshots")).isEqualTo(1L); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(plansBeforeTruncate); + } + + @Test + void differentBytesCannotReuseAStoredDigestAndWrongOwnerIdentityIsDenied() throws Exception { + TestContext context = newTestContext(); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(context.dsl()); + InventorySnapshot candidate = snapshot(); + inTransaction(context, () -> repository.persistOrReadback(candidate, BINDING, trust())); + Instant observedAt = candidate.observedAt(); + String environmentId = candidate.environmentId(); + String namespace = candidate.namespace(); + String apiBindingRevision = candidate.apiBindingRevision(); + String apiBindingDigest = candidate.apiBindingDigest(); + String inventoryBindingRevision = candidate.inventoryBindingRevision(); + String inventoryBindingDigest = candidate.inventoryBindingDigest(); + String digest = candidate.digest(); + byte[] canonicalBytes = candidate.canonicalBytes(); + + InventorySnapshot wrongIdentity = mock(InventorySnapshot.class); + when(wrongIdentity.observedAt()).thenReturn(observedAt); + when(wrongIdentity.environmentId()).thenReturn(environmentId); + when(wrongIdentity.clusterId()).thenReturn("other-cluster"); + when(wrongIdentity.clusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(wrongIdentity.namespace()).thenReturn(namespace); + when(wrongIdentity.namespaceUid()).thenReturn(NAMESPACE_UID); + when(wrongIdentity.apiBindingRevision()).thenReturn(apiBindingRevision); + when(wrongIdentity.apiBindingDigest()).thenReturn(apiBindingDigest); + when(wrongIdentity.inventoryBindingRevision()).thenReturn(inventoryBindingRevision); + when(wrongIdentity.inventoryBindingDigest()).thenReturn(inventoryBindingDigest); + when(wrongIdentity.digest()).thenReturn(digest); + when(wrongIdentity.canonicalBytes()).thenReturn(canonicalBytes); + + assertThatThrownBy( + () -> + inTransaction( + context, () -> repository.persistOrReadback(wrongIdentity, BINDING, trust()))) + .isInstanceOf( + AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) + .hasNoCause(); + } + + private static InventorySnapshot snapshot() throws Exception { + byte[] bytes = + ("{\"domain\":\"firemud-account-validator-inventory/v1\"," + + "\"environmentId\":\"prod\",\"clusterId\":\"prod-cluster-1\"," + + "\"clusterIncarnationUid\":\"" + + CLUSTER_UID + + "\"," + + "\"namespace\":\"firemud-prod\",\"namespaceUid\":\"" + + NAMESPACE_UID + + "\"}") + .getBytes(StandardCharsets.UTF_8); + InventorySnapshot snapshot = mock(InventorySnapshot.class); + when(snapshot.observedAt()).thenReturn(Instant.parse("2026-10-05T00:00:00Z")); + when(snapshot.environmentId()).thenReturn("prod"); + when(snapshot.clusterId()).thenReturn("prod-cluster-1"); + when(snapshot.clusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(snapshot.namespace()).thenReturn("firemud-prod"); + when(snapshot.namespaceUid()).thenReturn(NAMESPACE_UID); + when(snapshot.apiBindingRevision()).thenReturn("api-r1"); + when(snapshot.apiBindingDigest()).thenReturn("a".repeat(64)); + when(snapshot.inventoryBindingRevision()).thenReturn("inventory-r1"); + when(snapshot.inventoryBindingDigest()).thenReturn("b".repeat(64)); + when(snapshot.canonicalBytes()).thenReturn(bytes); + when(snapshot.digest()).thenReturn(sha256(bytes)); + return snapshot; + } + + private static String validateExternalLoopbackPostgresUrl(String value) { + final URI uri; + try { + if (!value.startsWith("jdbc:")) { + throw new IllegalArgumentException("not a JDBC URL"); + } + uri = URI.create(value.substring("jdbc:".length())); + } catch (RuntimeException failure) { + throw new IllegalStateException( + EXTERNAL_POSTGRES_URL_ENV + " must be a loopback JDBC URL", failure); + } + if (!"postgresql".equals(uri.getScheme()) + || !"127.0.0.1".equals(uri.getHost()) + || uri.getPort() < 1 + || uri.getPort() > 65535 + || !"/postgres".equals(uri.getPath()) + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null) { + throw new IllegalStateException( + EXTERNAL_POSTGRES_URL_ENV + " must target jdbc:postgresql://127.0.0.1:/postgres"); + } + return value; + } + + private static TestContext newTestContext() { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(username); + dataSource.setPassword(password); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + new TransactionTemplate(new DataSourceTransactionManager(dataSource)), dsl); + } + + private static T inTransaction(TestContext context, java.util.function.Supplier action) { + return context.transaction().execute(status -> action.get()); + } + + private static long count(TestContext context, String table) { + return java.util.Objects.requireNonNull( + context.dsl().resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class), + "COUNT query must return a scalar row"); + } + + private static TrustFence trust() { + return new TrustFence(CLUSTER_UID, NAMESPACE_UID, "c".repeat(64), "trust-r1"); + } + + private static String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private record TestContext(TransactionTemplate transaction, DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java index 057f760b39..094902e3ba 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java @@ -52,7 +52,7 @@ class AccountControlUiPrimaryAuthenticationPostgresIntegrationTest { private static final String OTP = "test-only-email-otp"; @Test - void passwordAuthenticatesPersistedCanonicalUuidAndInvalidOrLockedAccountDoesNotMutate() { + void passwordAuthenticatesPersistedCanonicalUuidAndWrongSecretDoesNotMutate() { Context c = context(); Account account = c.account("PASSWORD"); String before = c.accountBytes(account.getAccountUuid()); @@ -73,17 +73,29 @@ void passwordAuthenticatesPersistedCanonicalUuidAndInvalidOrLockedAccountDoesNot account.getEmail(), "wrong-secret"))) .isInstanceOf(AuthenticationException.class); assertThat(c.accountBytes(account.getAccountUuid())).isEqualTo(before); - Account lockedAccount = c.account("PASSWORD", AccountLifecycleState.SECURITY_LOCKED); - String locked = c.accountBytes(lockedAccount.getAccountUuid()); + } + + @Test + void freshSecurityLockedAccountCannotCompleteOwnerBirthAndLeavesNoRows() { + Context c = context(); + Account lockedAccount = c.accountCandidate("PASSWORD", AccountLifecycleState.SECURITY_LOCKED); assertThatThrownBy( () -> c.tx( - () -> - c.primary.authenticateControlUiPrimaryIdentity( - lockedAccount.getEmail(), PASSWORD))) - .isInstanceOf(AuthenticationException.class); - assertThat(c.accountBytes(lockedAccount.getAccountUuid())).isEqualTo(locked); - assertThat(c.challenges.findByAccountId(lockedAccount.getId())).isEmpty(); + () -> { + c.accounts.save(lockedAccount); + return null; + })) + .isInstanceOf( + net.firedevops.firemud.accountservice.repository + .AccountPlatformRestrictionBirthRepository.BirthSourceUnavailableException.class); + + UUID accountUuid = lockedAccount.getAccountUuid(); + assertThat(accountUuid).isNotNull(); + assertThat(c.accountRowCount(accountUuid)).isZero(); + assertThat(c.accountSourceRowCount(accountUuid)).isZero(); + assertThat(c.accountGenerationRowCount(accountUuid)).isZero(); + assertThat(c.restrictionBirthRowCount(accountUuid)).isZero(); } @Test @@ -274,17 +286,46 @@ Account account(String modes) { } Account account(String modes, AccountLifecycleState lifecycleState) { - return tx( - () -> { - Account account = new Account(); - String suffix = UUID.randomUUID().toString(); - account.setUsername("primary-" + suffix); - account.setEmail(suffix + "@example.test"); - account.setPasswordHash(hash(PASSWORD)); - account.setLoginAuthModes(modes); - account.setLifecycleState(lifecycleState); - return accounts.save(account); - }); + Account account = accountCandidate(modes, lifecycleState); + return tx(() -> accounts.save(account)); + } + + Account accountCandidate(String modes, AccountLifecycleState lifecycleState) { + Account account = new Account(); + String suffix = UUID.randomUUID().toString(); + account.setUsername("primary-" + suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash(hash(PASSWORD)); + account.setLoginAuthModes(modes); + account.setLifecycleState(lifecycleState); + return account; + } + + long accountRowCount(UUID accountUuid) { + return count("SELECT COUNT(*) FROM accounts WHERE account_uuid = ?", accountUuid); + } + + long accountSourceRowCount(UUID accountUuid) { + return count( + "SELECT COUNT(*) FROM account_authority_source_records WHERE account_uuid = ?", + accountUuid); + } + + long accountGenerationRowCount(UUID accountUuid) { + return count( + "SELECT COUNT(*) FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + accountUuid); + } + + long restrictionBirthRowCount(UUID accountUuid) { + return count( + "SELECT COUNT(*) FROM account_platform_restriction_births WHERE account_uuid = ?", + accountUuid); + } + + private long count(String query, UUID accountUuid) { + return Objects.requireNonNull(dsl.fetchOne(query, accountUuid)).get(0, Long.class); } AccountEmailLoginChallenge challenge(Account account) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java new file mode 100644 index 0000000000..a29c25931f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java @@ -0,0 +1,2216 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import java.math.BigInteger; +import java.net.URI; +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.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.ValidateReadinessProbeRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeState; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.VerificationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedPromotion; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PublicKeyIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtReadinessTlsInterceptor; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerSelector.LocalIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.postgresql.util.PSQLException; +import org.springframework.beans.factory.ObjectProvider; +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.DockerClientFactory; +import org.testcontainers.containers.PostgreSQLContainer; +import tools.jackson.databind.json.JsonMapper; + +/** Real-PostgreSQL proof of readiness planning, exact signing, verification, and quarantine. */ +class AccountJwtReadinessProbePersistenceIntegrationTest { + private static final Set VALIDATION_CONSTRAINT_ALLOWLIST = + Set.of( + "account_jwt_readiness_probe_state_check", "account_jwt_readiness_probe_evidence_check"); + private static final String SCHEMA_PREFIX = "jwt_readiness_probe_proof"; + private static final String EXTERNAL_POSTGRES_URL_ENV = + "FIREMUD_ACCOUNT_SIGNER_TEST_POSTGRES_URL"; + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String SECRET_UID = "33333333-3333-4333-8333-333333333333"; + private static final String CONFIG_MAP_UID = "44444444-4444-4444-8444-444444444444"; + private static final String TRUST_REVISION = "trust-r1"; + private static final String MATERIALIZER_URI = + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + private static final List MATERIALIZER_PINS = List.of("c".repeat(64)); + private static final String TRUST_DIGEST = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + TRUST_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + MATERIALIZER_PINS); + private static final String API_DIGEST = "b".repeat(64); + private static final String API_REVISION = "api-r1"; + private static final String INITIAL_CONFIG_MAP_RESOURCE_VERSION = "41"; + private static final Map INITIAL_CONFIG_MAP_DATA = + Map.of("jwks.json", "{\"keys\":[]}", "unrelated.txt", "preserve"); + private static final EnrollmentIdentity ENROLLMENT_IDENTITY = + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + TRUST_DIGEST, + TRUST_REVISION, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + INITIAL_CONFIG_MAP_RESOURCE_VERSION, + AccountJwtJwksPublicationRepository.snapshotDigest(INITIAL_CONFIG_MAP_DATA)); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>("postgres:16-alpine"); + + @TempDir Path tempDirectory; + + private static String testJdbcUrl; + private static String testJdbcUsername; + private static String testJdbcPassword; + private static volatile boolean startedOwnedContainer; + + @BeforeAll + static void configureDatabase() { + String externalUrl = System.getenv(EXTERNAL_POSTGRES_URL_ENV); + if (externalUrl != null) { + testJdbcUrl = validateExternalLoopbackPostgresUrl(externalUrl); + testJdbcUsername = "postgres"; + testJdbcPassword = ""; + return; + } + Assumptions.assumeTrue( + DockerClientFactory.instance().isDockerAvailable(), + "PostgreSQL proof requires the explicit loopback tunnel or an available Docker daemon"); + postgres.start(); + startedOwnedContainer = true; + testJdbcUrl = postgres.getJdbcUrl(); + testJdbcUsername = postgres.getUsername(); + testJdbcPassword = postgres.getPassword(); + } + + @AfterAll + static void stopOwnedContainer() { + if (startedOwnedContainer) { + postgres.stop(); + } + } + + @Test + void persistsFirstInstallPlanIssuesVerifiedReceiptsAndQuarantines() throws Exception { + TestContext context = newTestContext(); + AccountJwtSignerDesiredStateRepository desired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + AccountJwtJwksPublicationRepository publication = + new AccountJwtJwksPublicationRepository(context.dsl(), desired); + AccountJwtReadinessProbeRepository readiness = + new AccountJwtReadinessProbeRepository(context.dsl(), desired, publication); + TrustFence trust = trust(); + + inTransaction(context, () -> desired.initialize(BINDING, ENROLLMENT_IDENTITY)); + GenerationRequest requested = + inTransaction(context, () -> desired.ensureCurrentGenerationRequest(BINDING, trust)); + GenerationRequest observed = + inTransaction( + context, + () -> + desired.recordSecretObservation( + BINDING, + trust, + requested.operationId(), + requested.operationDigest(), + SECRET_UID, + "12")); + + KeyPair keyPair = generateRsa3072(); + PublicJwk targetJwk = publicJwk(requested.targetKid(), (RSAPublicKey) keyPair.getPublic()); + GenerationResult result = + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + trust, + requested.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + "12", + "13", + targetJwk.json())); + + KeyPair retainedPair = generateRsa3072(); + String retainedJwk = + publicJwk("retained-key", (RSAPublicKey) retainedPair.getPublic()).jsonWithoutKeyOps(); + String desiredJwks = jwks(retainedJwk, result.publicJwkJson()); + String marker = marker(result); + String expectedSnapshotDigest = + AccountJwtJwksPublicationRepository.snapshotDigest(INITIAL_CONFIG_MAP_DATA); + GenerationRequest currentRequest = + inTransaction(context, () -> desired.readCurrentGenerationRequest(BINDING, trust)); + var intent = + inTransaction( + context, + () -> + publication.recordPrepublicationIntent( + BINDING, + trust, + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + INITIAL_CONFIG_MAP_RESOURCE_VERSION, + expectedSnapshotDigest, + desiredJwks, + marker)); + var receipt = + inTransaction( + context, + () -> + publication.recordPublicationReceipt( + BINDING, + trust, + result.operationId(), + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "42", + desiredJwks, + marker)); + var mountObservation = + inTransaction( + context, + () -> + publication.recordMountedCorrespondence( + BINDING, + trust, + result.operationId(), + sha256(marker.getBytes(StandardCharsets.UTF_8)), + AccountJwtJwksPublicationRepository.publicDataDigest(desiredJwks, marker), + result.publicKeyFingerprint())); + assertThat(receipt.intentDigest()).isEqualTo(intent.intentDigest()); + assertThat(mountObservation.publicationReceiptDigest()).isEqualTo(receipt.receiptDigest()); + + long now = + java.util.Objects.requireNonNull( + context + .dsl() + .resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class), + "Database timestamp query must return a scalar row"); + // Controlled historical-plan fixture to reach the post-cache lifecycle without waiting in + // this persistence test. This is not evidence of a production 300-second cache convergence. + ReadinessProbePlan plan = + inTransaction( + context, () -> readiness.planCurrent(BINDING, trust, Instant.ofEpochSecond(now - 301))); + ReadinessProbePlan retry = + inTransaction( + context, () -> readiness.planCurrent(BINDING, trust, Instant.ofEpochSecond(now))); + assertThat(retry).isEqualTo(plan); + assertThat(retry.planDigest()).isEqualTo(plan.planDigest()); + assertThat(retry.entries()).containsExactlyElementsOf(plan.entries()); + assertThat(retry.entries()) + .extracting(ProbeEntry::tokenProfile) + .containsExactly( + "account-jwt-readiness-canary", + "control-ui", + "player-bootstrap", + "game-session-account-delegation"); + ReadinessProbePlan durableReadback = + inTransaction( + context, () -> readiness.readCurrentPlan(BINDING, trust, result.operationId())); + assertThat(durableReadback.planDigest()).isEqualTo(plan.planDigest()); + assertThat(durableReadback.entries()).containsExactlyElementsOf(plan.entries()); + assertThat(plan.expectedFence().durableActive()).isEmpty(); + assertThat(plan.expectedFence().publishedActive()).isEmpty(); + assertThat(plan.validatorInventoryComplete()).isFalse(); + assertThat(plan.planVersion()).isEqualTo(1); + assertThat(plan.inventorySnapshotDigest()).isEmpty(); + assertThat(plan.applicabilityMatrixJson()).contains("PARTIAL_UNCONFIRMED"); + assertThat(plan.applicabilityMatrixJson()).contains("game-session-account-delegation"); + assertThat(plan.maximumCacheAgeSeconds()).isEqualTo(300); + assertThat( + inTransaction( + context, + () -> + readiness.readCurrentPromotionPrerequisites( + BINDING, trust, result.operationId()))) + .isEmpty(); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> readiness.readPromotionProof(BINDING, trust, result.operationId()))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException.class); + assertThat(plan.entries()) + .hasSize(4) + .allSatisfy(entry -> assertThat(entry.state()).isEqualTo(ProbeState.PLANNED)); + assertThat(plan.entries()).extracting(ProbeEntry::jti).doesNotHaveDuplicates(); + + assertThat(count(context, "account_jwt_validator_inventory_snapshots")).isZero(); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(1L); + + Path privateMount = Files.createDirectory(tempDirectory.resolve("private-mount")); + Path publicMount = Files.createDirectory(tempDirectory.resolve("public-mount")); + Files.writeString( + privateMount.resolve("pending.key"), privateBundleJson(requested, result, keyPair)); + Files.writeString(publicMount.resolve("jwks.json"), desiredJwks); + TransactionTemplate accountTransaction = + new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); + int[] transientDeliveries = {0}; + String[] transientFailurePayload = {null}; + String[] safeDeliveryStage = {"NOT_STARTED"}; + String[] safeDeliveryProfile = {"NOT_STARTED"}; + String[] safeValidationFailure = {"NONE"}; + Map transientProbeBytes = new LinkedHashMap<>(); + AccountJwtReadinessProbeService earlyService = + new AccountJwtReadinessProbeService( + readiness, + accountTransaction, + Clock.fixed( + Instant.ofEpochSecond(plan.notBeforeEpochSecond() - 1), java.time.ZoneOffset.UTC), + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json")); + assertThatThrownBy( + () -> earlyService.issueCurrentPlan(BINDING, trust, result.operationId(), null, null)) + .isInstanceOf(AccountJwtReadinessProbeRepository.CacheAgeNotElapsedException.class); + assertThat( + inTransaction( + context, + () -> readiness.readCurrentPlan(BINDING, trust, result.operationId()).entries())) + .allSatisfy( + entry -> { + assertThat(entry.state()).isEqualTo(ProbeState.PLANNED); + assertThat(entry.compactTokenSha256()).isEmpty(); + }); + + // An application clock alone cannot force EXPIRED while PostgreSQL still considers a probe + // live. + AccountJwtReadinessProbeService futureClockService = + new AccountJwtReadinessProbeService( + readiness, + accountTransaction, + Clock.fixed( + Instant.ofEpochSecond(plan.expiresAtEpochSecond()), java.time.ZoneOffset.UTC), + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json")); + assertThatThrownBy( + () -> + futureClockService.issueCurrentPlan( + BINDING, trust, result.operationId(), null, null)) + .isInstanceOf(DataAccessException.class); + + ValidatorFixture validator = createValidatorFixture(context, readiness, desiredJwks); + var deliveryClaim = + raceForSingleDeliveryClaim( + context, + readiness, + trust, + plan, + validator.caller().binding(), + validator.caller().peer(), + now); + assertThat(count(context, "account_jwt_readiness_delivery_claims")).isEqualTo(1L); + AccountJwtReadinessProbeService service = + new AccountJwtReadinessProbeService( + readiness, + accountTransaction, + Clock.fixed(Instant.ofEpochSecond(now), java.time.ZoneOffset.UTC), + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json")); + AccountJwtReadinessProbeService.OwnerInternalProbeDelivery delivery = + (metadata, exactCompactJwt) -> { + transientDeliveries[0]++; + safeDeliveryStage[0] = "CALLBACK_REACHED"; + safeDeliveryProfile[0] = metadata.tokenProfile(); + assertThat(exactCompactJwt).isNotEmpty().hasSizeLessThan(16 * 1024); + assertThat(sha256(exactCompactJwt)).isEqualTo(metadata.compactTokenSha256()); + assertThat(transientProbeBytes.put(metadata.tokenProfile(), exactCompactJwt)).isNull(); + String compact = new String(exactCompactJwt, StandardCharsets.US_ASCII); + assertThat(compact.split("\\.", -1)).hasSize(3); + String[] segments = compact.split("\\.", -1); + String claims = + new String(Base64.getUrlDecoder().decode(segments[1]), StandardCharsets.UTF_8); + assertThat(claims).contains("\"sub\":\"00000000-0000-4000-8000-000000000001\""); + assertThat(claims).doesNotContain("\"globalRoles\""); + if (metadata.probeKind() == AccountMountedJwtSignerBundle.ProbeKind.CANARY) { + assertThat(metadata.audience()).isEqualTo("firemud-account-jwt-readiness"); + assertThat(claims) + .contains("\"tokenType\":\"account_jwt_readiness_canary\"") + .doesNotContain("tokenGeneration", "issuanceFence"); + } else if (metadata.tokenProfile().equals("control-ui")) { + assertThat(metadata.audience()).isEqualTo("control-ui"); + assertThat(claims) + .contains("\"scopedRoles\":{}", "\"tokenGeneration\":1", "\"issuanceFence\":1") + .contains("\"tenantAuthorityGeneration\":{}") + .contains("\"membershipAuthorityGeneration\":{}") + .contains("\"membershipVersion\":{}"); + } else if (metadata.tokenProfile().equals("player-bootstrap")) { + assertThat(metadata.audience()).isEqualTo("player-bootstrap"); + assertThat(claims) + .contains("\"scopedRoles\":{}", "\"tokenGeneration\":1", "\"issuanceFence\":1") + .contains("\"tenantAuthorityGeneration\":{}") + .contains("\"membershipAuthorityGeneration\":{}") + .contains("\"membershipVersion\":{}"); + } else { + assertThat(metadata.tokenProfile()).isEqualTo("game-session-account-delegation"); + assertThat(metadata.audience()).isEqualTo("account-service"); + assertThat(claims) + .contains("\"tokenGeneration\":\"1\"", "\"issuanceFence\":\"1\"") + .contains("\"issuerAuthGeneration\":\"1\"", "\"accountAuthorityGeneration\":\"1\"") + .contains("\"tenantAuthorityGeneration\":{}") + .contains("\"membershipAuthorityGeneration\":{}") + .contains("\"membershipVersion\":{}"); + } + ProbeEntry issuedBeforeCallback = + inTransaction( + context, + () -> + readiness.readCurrentPlan(BINDING, trust, result.operationId()).entries()) + .stream() + .filter(entry -> entry.jti().equals(metadata.jti())) + .findFirst() + .orElseThrow(); + assertThat(issuedBeforeCallback.state()).isEqualTo(ProbeState.ISSUED); + assertThat(issuedBeforeCallback.compactTokenSha256()) + .contains(metadata.compactTokenSha256()); + safeDeliveryStage[0] = "ISSUED_READBACK_CONFIRMED"; + VerificationReceipt verification; + safeDeliveryStage[0] = "VALIDATOR_VALIDATE"; + try { + verification = validator.validate(issuedBeforeCallback, exactCompactJwt); + } catch (RuntimeException validationFailure) { + safeValidationFailure[0] = safeValidationFailure(validationFailure); + throw validationFailure; + } + assertThat(verification.verifiedKid()).isEqualTo(issuedBeforeCallback.targetKid()); + assertThat(verification.validatorInstanceId()).isEqualTo(validator.validatorInstanceId()); + assertThat(verification.validatorBindingDigest()).isEqualTo(validator.readinessDigest()); + assertThat(verification.validatorConfigRevision()) + .isEqualTo(validator.readinessRevision()); + assertThat(verification.validatorPeerUri()).isEqualTo(validator.harnessUri()); + assertThat(verification.validatorPeerSpkiSha256()) + .isEqualTo(validator.harnessSpkiSha256()); + safeDeliveryStage[0] = "VALIDATOR_CRYPTO_PROFILE_CONFIRMED"; + ReadinessProbePlan verifiedPlan = + inTransaction( + context, () -> readiness.readCurrentPlan(BINDING, trust, result.operationId())); + ProbeEntry verifiedEntry = + verifiedPlan.entries().stream() + .filter(entry -> entry.jti().equals(metadata.jti())) + .findFirst() + .orElseThrow(); + assertThat(verifiedEntry.state()).isEqualTo(ProbeState.VERIFIED); + assertThat(verifiedEntry.verificationReceipt()).contains(verification); + assertThat(verification.sourceEntryVersion()) + .isEqualTo(issuedBeforeCallback.entryVersion()); + assertThat(verification.resultEntryVersion()).isEqualTo(verifiedEntry.entryVersion()); + assertThat(validator.validate(issuedBeforeCallback, exactCompactJwt)) + .isEqualTo(verification); + safeDeliveryStage[0] = "OWNER_RECEIPT_READBACK_CONFIRMED"; + if (metadata.tokenProfile().equals("game-session-account-delegation")) { + safeDeliveryStage[0] = "GSA_TRANSPORT_INTERRUPTION_ARMED"; + transientFailurePayload[0] = new String(exactCompactJwt, StandardCharsets.US_ASCII); + throw new IllegalStateException( + "controlled transport interruption after authenticated observation: " + + transientFailurePayload[0]); + } + }; + + assertThatThrownBy( + () -> + service.issueCurrentPlan( + BINDING, trust, result.operationId(), deliveryClaim, delivery)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Readiness probe delivery was ambiguous; the operation was quarantined") + .satisfies( + failure -> { + assertThat(failure.getCause()).isNull(); + assertThat(failure.getSuppressed()).isEmpty(); + assertThat(safeDeliveryStage[0]) + .as( + "Readiness delivery stage for profile %s (validator failure: %s)", + safeDeliveryProfile[0], safeValidationFailure[0]) + .isEqualTo("GSA_TRANSPORT_INTERRUPTION_ARMED"); + assertThat(transientFailurePayload[0]).isNotNull(); + assertThat(failure.toString().contains(transientFailurePayload[0])).isFalse(); + }); + assertThat(transientDeliveries[0]).isEqualTo(4); + List cleaned = + inTransaction( + context, + () -> readiness.readCurrentPlan(BINDING, trust, result.operationId()).entries()); + assertThat(cleaned) + .hasSize(4) + .allSatisfy( + entry -> { + assertThat(entry.state()).isEqualTo(ProbeState.CLEANED); + assertThat(entry.terminalOutcome()).contains("ABORTED"); + assertThat(entry.compactTokenSha256()).isPresent(); + assertThat(entry.verificationReceipt()).isPresent(); + }); + assertThat( + service.issueCurrentPlan(BINDING, trust, result.operationId(), deliveryClaim, delivery)) + .isEqualTo(cleaned); + assertThat(transientDeliveries[0]).isEqualTo(4); + assertThat(transientProbeBytes.values()) + .allSatisfy(bytes -> assertThat(bytes).containsOnly((byte) 0)); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_readiness_probe_entries SET state = 'VERIFIED', " + + "entry_version = entry_version + 1 WHERE rotation_operation_id = ?", + result.operationId()))) + .isInstanceOf(DataAccessException.class); + + assertThat(service.abortCurrentPlan(BINDING, trust, result.operationId())).isEmpty(); + List retainedCleaned = + inTransaction( + context, + () -> readiness.readCurrentPlan(BINDING, trust, result.operationId()).entries()); + assertThat(retainedCleaned) + .isEqualTo(cleaned) + .hasSize(4) + .allSatisfy( + entry -> { + assertThat(entry.state()).isEqualTo(ProbeState.CLEANED); + assertThat(entry.terminalOutcome()).contains("ABORTED"); + assertThat(entry.compactTokenSha256()).isPresent(); + assertThat(entry.verificationReceipt()).isPresent(); + }); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(1L); + assertThat(count(context, "account_jwt_readiness_probe_entries")).isEqualTo(4L); + assertThat(count(context, "account_jwt_readiness_delivery_claims")).isEqualTo(1L); + ReadinessProbePlan cleanedPlan = + inTransaction( + context, () -> readiness.readCurrentPlan(BINDING, trust, result.operationId())); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.claimSingleDelivery( + BINDING, + trust, + cleanedPlan, + validator.caller().binding(), + validator.caller().peer(), + Instant.ofEpochSecond(now)))) + .isInstanceOf(AccountJwtReadinessProbeRepository.DeliveryAlreadyClaimedException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.claimSingleDelivery( + BINDING, + trust, + plan, + validator.caller().binding(), + validator.caller().peer(), + Instant.ofEpochSecond(now)))) + .isInstanceOf(AccountJwtReadinessProbeRepository.StaleOperationException.class); + assertThat(columnNames(context, "account_jwt_readiness_probe_entries")) + .contains("compact_token_sha256") + .contains("verification_receipt_sha256", "validator_peer_spki_sha256") + .doesNotContain("compact_token", "token_bytes", "credential"); + } + + @Test + void persistsProtectedV2PodClosureAndRequiresFreshExactInventoryForPromotion() throws Exception { + // The package-private evidence factory below models the output of a trusted Pod-bound client + // only to exercise PostgreSQL closure constraints; this does not claim receiver transport or + // production verifier proof, which remains default-denied until real transport is wired. + TestContext context = newTestContext(); + AccountJwtSignerDesiredStateRepository desired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + AccountJwtJwksPublicationRepository publication = + new AccountJwtJwksPublicationRepository(context.dsl(), desired); + AccountJwtReadinessProbeRepository readiness = + new AccountJwtReadinessProbeRepository(context.dsl(), desired, publication); + TrustFence trust = trust(); + + inTransaction(context, () -> desired.initialize(BINDING, ENROLLMENT_IDENTITY)); + GenerationRequest requested = + inTransaction(context, () -> desired.ensureCurrentGenerationRequest(BINDING, trust)); + GenerationRequest observed = + inTransaction( + context, + () -> + desired.recordSecretObservation( + BINDING, + trust, + requested.operationId(), + requested.operationDigest(), + SECRET_UID, + "12")); + + KeyPair keyPair = generateRsa3072(); + PublicJwk targetJwk = publicJwk(requested.targetKid(), (RSAPublicKey) keyPair.getPublic()); + GenerationResult result = + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + trust, + requested.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + "12", + "13", + targetJwk.json())); + + KeyPair retainedPair = generateRsa3072(); + String retainedJwk = + publicJwk("retained-key", (RSAPublicKey) retainedPair.getPublic()).jsonWithoutKeyOps(); + String desiredJwks = jwks(retainedJwk, result.publicJwkJson()); + String marker = marker(result); + String expectedSnapshotDigest = + AccountJwtJwksPublicationRepository.snapshotDigest(INITIAL_CONFIG_MAP_DATA); + GenerationRequest currentRequest = + inTransaction(context, () -> desired.readCurrentGenerationRequest(BINDING, trust)); + var intent = + inTransaction( + context, + () -> + publication.recordPrepublicationIntent( + BINDING, + trust, + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + INITIAL_CONFIG_MAP_RESOURCE_VERSION, + expectedSnapshotDigest, + desiredJwks, + marker)); + var publicationReceipt = + inTransaction( + context, + () -> + publication.recordPublicationReceipt( + BINDING, + trust, + result.operationId(), + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "42", + desiredJwks, + marker)); + var mountedObservation = + inTransaction( + context, + () -> + publication.recordMountedCorrespondence( + BINDING, + trust, + result.operationId(), + sha256(marker.getBytes(StandardCharsets.UTF_8)), + AccountJwtJwksPublicationRepository.publicDataDigest(desiredJwks, marker), + result.publicKeyFingerprint())); + assertThat(publicationReceipt.intentDigest()).isEqualTo(intent.intentDigest()); + + ObservationContext initialObservationContext = + inTransaction( + context, () -> readiness.readCurrentInventoryObservationContext(BINDING, trust)); + assertThat(initialObservationContext.purpose()) + .isEqualTo(ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES); + assertThat(initialObservationContext.operationId()).isEqualTo(result.operationId()); + assertThat(initialObservationContext.operationDigest()).isEqualTo(result.operationDigest()); + + long now = + java.util.Objects.requireNonNull( + context + .dsl() + .resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class), + "Database timestamp query must return a scalar row"); + InventorySnapshot planObservation = + completeInventorySnapshot(Instant.ofEpochSecond(now - 300), initialObservationContext); + ObservationContext wrongPurposeContext = + new ObservationContext( + ObservationPurpose.STRICT_READY, + initialObservationContext.operationId(), + initialObservationContext.operationDigest()); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.planCurrent( + BINDING, + trust, + Instant.ofEpochSecond(now - 300), + completeInventorySnapshot( + Instant.ofEpochSecond(now - 300), wrongPurposeContext)))) + .isInstanceOf(AccountJwtReadinessProbeRepository.InventoryPlanConflictException.class); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isZero(); + ReadinessProbePlan plan = + inTransaction( + context, + () -> + readiness.planCurrent( + BINDING, trust, Instant.ofEpochSecond(now - 300), planObservation)); + InventorySnapshot refreshedObservation = + completeInventorySnapshot(Instant.ofEpochSecond(now), initialObservationContext); + assertThat(refreshedObservation.digest()).isEqualTo(planObservation.digest()); + assertThat(refreshedObservation.canonicalBytes()) + .containsExactly(planObservation.canonicalBytes()); + ReadinessProbePlan inventoryRetry = + inTransaction( + context, + () -> + readiness.planCurrent( + BINDING, trust, Instant.ofEpochSecond(now), refreshedObservation)); + assertThat(inventoryRetry).isEqualTo(plan); + assertThat(inventoryRetry.planDigest()).isEqualTo(plan.planDigest()); + assertThat(inventoryRetry.entries()).containsExactlyElementsOf(plan.entries()); + assertThat(inventoryRetry.entries()) + .extracting(ProbeEntry::validatorId) + .containsExactly( + "account-service", + "account-service", + "account-service", + "account-service", + "game-session-service", + "game-session-service", + "game-session-service", + "game-session-service"); + assertThat(inventoryRetry.entries()) + .extracting(ProbeEntry::tokenProfile) + .containsExactly( + "account-jwt-readiness-canary", + "control-ui", + "player-bootstrap", + "game-session-account-delegation", + "account-jwt-readiness-canary", + "control-ui", + "player-bootstrap", + "game-session-account-delegation"); + ReadinessProbePlan inventoryReadback = + inTransaction( + context, () -> readiness.readCurrentPlan(BINDING, trust, result.operationId())); + assertThat(inventoryReadback.planDigest()).isEqualTo(plan.planDigest()); + assertThat(inventoryReadback.entries()).containsExactlyElementsOf(plan.entries()); + assertThat(plan.planVersion()).isEqualTo(2); + assertThat(plan.validatorInventoryComplete()).isTrue(); + assertThat(plan.expectedFence().durableActive()).isEmpty(); + assertThat(plan.entries()).allSatisfy(entry -> assertThat(entry.expectedActive()).isEmpty()); + assertThat(plan.entries()) + .hasSize(8) + .allSatisfy(entry -> assertThat(entry.state()).isEqualTo(ProbeState.PLANNED)); + assertThat(plan.entries()).extracting(ProbeEntry::jti).doesNotHaveDuplicates(); + assertThat(count(context, "account_jwt_readiness_validator_pods")).isEqualTo(12L); + // The owner-bound cold-start candidate inventory plans exact Pod targets, but is not itself an + // availability or promotion proof: every Pod still needs its authenticated profile receipts. + assertThat( + inTransaction( + context, + () -> + readiness.readCurrentPromotionPrerequisites( + BINDING, trust, result.operationId()))) + .isEmpty(); + + Path privateMount = Files.createDirectory(tempDirectory.resolve("v2-private-mount")); + Path publicMount = Files.createDirectory(tempDirectory.resolve("v2-public-mount")); + Files.writeString( + privateMount.resolve("pending.key"), privateBundleJson(requested, result, keyPair)); + Files.writeString(publicMount.resolve("jwks.json"), desiredJwks); + TransactionTemplate accountTransaction = + new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); + ValidatorFixture validator = createValidatorFixture(context, readiness, desiredJwks); + var deliveryClaim = + raceForSingleDeliveryClaim( + context, + readiness, + trust, + plan, + validator.caller().binding(), + validator.caller().peer(), + now); + AccountJwtReadinessProbeService probeService = + new AccountJwtReadinessProbeService( + readiness, + accountTransaction, + Clock.fixed(Instant.ofEpochSecond(now), java.time.ZoneOffset.UTC), + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json")); + List issued = + probeService.issueCurrentPlan( + BINDING, + trust, + result.operationId(), + deliveryClaim, + (metadata, compactJwt) -> + assertThat(sha256(compactJwt)).isEqualTo(metadata.compactTokenSha256())); + assertThat(issued) + .hasSize(8) + .allSatisfy(entry -> assertThat(entry.state()).isEqualTo(ProbeState.ISSUED)); + + boolean racedOneReceipt = false; + boolean testedInapplicablePendingKid = false; + boolean testedCurrentProbeOwnerRead = false; + for (ProbeEntry entry : issued) { + List targets = + inTransaction( + context, + () -> readiness.readCurrentExpectedPods(BINDING, trust, entry, refreshedObservation)); + assertThat(targets).isNotEmpty(); + if (!testedCurrentProbeOwnerRead && entry.validatorId().equals("game-session-service")) { + var expectedPod = targets.getFirst(); + var selector = ownerSelector(plan, entry, expectedPod); + var ownerEvidence = + inTransaction( + context, + () -> + readiness.readCurrentProbeOwner( + BINDING, trust, selector, refreshedObservation, BINDING.namespace())); + assertThat(ownerEvidence.plan()).isEqualTo(plan); + assertThat(ownerEvidence.entry()).isEqualTo(entry); + assertThat(ownerEvidence.expectedPod()).isEqualTo(expectedPod); + var ownerResponse = + new AccountJwtReadinessProbeOwnerProtoMapper().toResponse(ownerEvidence); + assertThat(ownerResponse.getCurrentState()) + .isEqualTo( + net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse.ProbeState + .ISSUED); + assertThat(ownerResponse.getCompactTokenSha256()) + .isEqualTo(entry.compactTokenSha256().orElseThrow()); + assertThat(ownerResponse.getDescriptorForType().findFieldByName("compact_jwt")).isNull(); + + var wrongHash = ownerSelector(plan, entry, expectedPod, "0".repeat(64), null, null); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.readCurrentProbeOwner( + BINDING, + trust, + wrongHash, + refreshedObservation, + BINDING.namespace()))) + .isInstanceOf( + AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + var replacedPod = + ownerSelector( + plan, entry, expectedPod, null, null, "77777777-7777-4777-8777-777777777777"); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.readCurrentProbeOwner( + BINDING, + trust, + replacedPod, + refreshedObservation, + BINDING.namespace()))) + .isInstanceOf( + AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + var wrongPlanExpiry = + ownerSelector(plan, entry, expectedPod, null, plan.expiresAtEpochSecond() + 1L, null); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.readCurrentProbeOwner( + BINDING, + trust, + wrongPlanExpiry, + refreshedObservation, + BINDING.namespace()))) + .isInstanceOf( + AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + var wrongOperation = + ownerSelector( + plan, + entry, + expectedPod, + null, + null, + null, + UUID.fromString("88888888-8888-4888-8888-888888888888"), + null, + null); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.readCurrentProbeOwner( + BINDING, + trust, + wrongOperation, + refreshedObservation, + BINDING.namespace()))) + .isInstanceOf( + AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + var wrongKey = + ownerSelector(plan, entry, expectedPod, null, null, null, null, "different-key", null); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.readCurrentProbeOwner( + BINDING, + trust, + wrongKey, + refreshedObservation, + BINDING.namespace()))) + .isInstanceOf( + AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + var inventedActive = + ownerSelector( + plan, + entry, + expectedPod, + null, + null, + null, + null, + null, + Optional.of( + new AccountJwtSignerDesiredStateRepository.ActiveSigner("2", "old-key"))); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.readCurrentProbeOwner( + BINDING, + trust, + inventedActive, + refreshedObservation, + BINDING.namespace()))) + .isInstanceOf( + AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + InventorySnapshot changedInventory = + completeInventorySnapshot( + Instant.ofEpochSecond(now), "10.11.0.99", initialObservationContext); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.readCurrentProbeOwner( + BINDING, trust, selector, changedInventory, BINDING.namespace()))) + .isInstanceOf( + AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + InventorySnapshot swappedPodInventory = + completeInventorySnapshot( + Instant.ofEpochSecond(now), + "10.11.0.11", + initialObservationContext, + "aaaaaaaa-7777-4777-8777-777777777777"); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.readCurrentProbeOwner( + BINDING, + trust, + selector, + swappedPodInventory, + BINDING.namespace()))) + .isInstanceOf( + AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isZero(); + testedCurrentProbeOwnerRead = true; + } + for (AccountJwtReadinessProbeRepository.ExpectedPod target : targets) { + var acceptance = testAuthenticatedAcceptance(entry, target, now); + if (!testedInapplicablePendingKid + && target.target().expectation() + == AccountJwtReadinessReceiverInvocationPort.ProbeExpectation.INAPPLICABLE_REJECT) { + var wrongInapplicableKey = + testAuthenticatedAcceptance(entry, target, now, entry.targetKid() + "-wrong"); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.recordPodAcceptance( + BINDING, + trust, + entry, + target, + wrongInapplicableKey, + refreshedObservation))) + .isInstanceOf(AccountJwtReadinessProbeRepository.IdempotencyConflictException.class); + testedInapplicablePendingKid = true; + } + if (!racedOneReceipt) { + var wrongKey = + testAuthenticatedAcceptance(entry, target, now, entry.targetKid() + "-wrong"); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.recordPodAcceptance( + BINDING, trust, entry, target, wrongKey, refreshedObservation))) + .isInstanceOf(AccountJwtReadinessProbeRepository.IdempotencyConflictException.class); + var wrongEndpoint = + testAuthenticatedAcceptance( + entry, + target, + now, + entry.targetKid(), + "grpcs://192.0.2.1:" + + target.target().exactPodEndpoint().orElseThrow().getPort()); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.recordPodAcceptance( + BINDING, + trust, + entry, + target, + wrongEndpoint, + refreshedObservation))) + .isInstanceOf(AccountJwtReadinessProbeRepository.IdempotencyConflictException.class); + raceForPodAcceptance( + context, readiness, trust, entry, target, acceptance, refreshedObservation); + racedOneReceipt = true; + ReadinessProbePlan partial = + inTransaction( + context, () -> readiness.readCurrentPlan(BINDING, trust, result.operationId())); + ProbeEntry partialEntry = + partial.entries().stream() + .filter(candidate -> candidate.jti().equals(entry.jti())) + .findFirst() + .orElseThrow(); + assertThat(partialEntry.state()).isEqualTo(ProbeState.ISSUED); + assertThat(partialEntry.verificationReceipt()).isEmpty(); + InventorySnapshot changedPod = + completeInventorySnapshot( + Instant.ofEpochSecond(now), "10.11.0.99", initialObservationContext); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.recordPodAcceptance( + BINDING, trust, entry, target, acceptance, changedPod))) + .isInstanceOf( + AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + InventorySnapshot staleObservation = + completeInventorySnapshot( + Instant.ofEpochSecond(now - 301), initialObservationContext); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + readiness.recordPodAcceptance( + BINDING, trust, entry, target, acceptance, staleObservation))) + .isInstanceOf( + AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + assertThat( + inTransaction( + context, + () -> + readiness.readCurrentPromotionPrerequisites( + BINDING, trust, result.operationId(), refreshedObservation))) + .isEmpty(); + } else { + inTransaction( + context, + () -> + readiness.recordPodAcceptance( + BINDING, trust, entry, target, acceptance, refreshedObservation)); + } + } + } + assertThat(racedOneReceipt).isTrue(); + assertThat(testedInapplicablePendingKid).isTrue(); + assertThat(testedCurrentProbeOwnerRead).isTrue(); + + AccountJwtReadinessProbeRepository restartedReadiness = + new AccountJwtReadinessProbeRepository(context.dsl(), desired, publication); + ReadinessProbePlan completed = + inTransaction( + context, + () -> restartedReadiness.readCurrentPlan(BINDING, trust, result.operationId())); + assertThat(completed.entries()) + .hasSize(8) + .allSatisfy( + entry -> { + assertThat(entry.state()).isEqualTo(ProbeState.VERIFIED); + assertThat(entry.verificationReceipt()).isPresent(); + var closure = entry.verificationReceipt().orElseThrow(); + assertThat(closure.receiptVersion()).isEqualTo(2); + assertThat(closure.sourceEntryVersion() + 1L).isEqualTo(entry.entryVersion()); + }); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(12L); + assertThat( + java.util.Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT COUNT(*) FROM account_jwt_readiness_pod_receipts " + + "WHERE outcome = 'INAPPLICABLE_REJECT'")) + .get(0, Long.class)) + .isEqualTo(2L); + assertThat( + inTransaction( + context, + () -> + restartedReadiness.readCurrentPromotionPrerequisites( + BINDING, trust, result.operationId()))) + .isEmpty(); + long proofObservedAt = + java.util.Objects.requireNonNull( + context + .dsl() + .resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class), + "Database timestamp query must return a scalar row"); + InventorySnapshot proofInventory = + completeInventorySnapshot( + Instant.ofEpochSecond(proofObservedAt), initialObservationContext); + assertThat(proofInventory.digest()).isEqualTo(refreshedObservation.digest()); + var currentProof = + inTransaction( + context, + () -> + restartedReadiness.readCurrentPromotionPrerequisites( + BINDING, trust, result.operationId(), proofInventory)); + assertThat(currentProof).isPresent(); + assertThat(currentProof.orElseThrow().plan()).isEqualTo(completed); + assertThat(currentProof.orElseThrow().generationResult()).isEqualTo(result); + assertThat(currentProof.orElseThrow().publication().intent().operationId()) + .isEqualTo(result.operationId()); + assertThat(inTransaction(context, () -> desired.read(BINDING).preparedOperationId())).isEmpty(); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + restartedReadiness.readPromotionProof( + BINDING, trust, result.operationId()))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException.class); + + AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + AccountJwtSignerMaterializerTrustBinding.Binding materializerBinding = materializerBinding(); + when(materializerTrust.current()).thenReturn(Optional.of(materializerBinding)); + AccountJwtJwksConfigMapClient configMapClient = mock(AccountJwtJwksConfigMapClient.class); + AccountJwtJwksConfigMapClient.BindingIdentity apiIdentity = + new AccountJwtJwksConfigMapClient.BindingIdentity( + API_DIGEST, + API_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + "https://kubernetes.default.svc:6443/", + "kubernetes.default.svc", + "d".repeat(64), + "system:serviceaccount:firemud-prod:account-service"); + when(configMapClient.identity()).thenReturn(apiIdentity); + when(configMapClient.observe()) + .thenReturn( + new AccountJwtJwksConfigMapClient.ConfigMapSnapshot( + CONFIG_MAP_UID, "43", Map.of("jwks.json", desiredJwks))); + AccountJwtJwksPrepublicationService prepublication = + mock(AccountJwtJwksPrepublicationService.class); + when(prepublication.prepublishCurrentGeneration()).thenReturn(publicationReceipt); + when(prepublication.observeCurrentMountedCorrespondence()).thenReturn(mountedObservation); + AccountJwtValidatorInventorySource inventorySource = + mock(AccountJwtValidatorInventorySource.class); + @SuppressWarnings("unchecked") + ObjectProvider inventoryProvider = + mock(ObjectProvider.class); + when(inventoryProvider.getIfAvailable()).thenReturn(inventorySource); + TransactionTemplate coordinatorTransaction = + new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); + AccountJwtSignerBootstrapCoordinator coordinator = + new AccountJwtSignerBootstrapCoordinator( + materializerTrust, + configMapClient, + desired, + prepublication, + restartedReadiness, + inventoryProvider, + coordinatorTransaction); + + InventorySnapshot staleProofInventory = + completeInventorySnapshot( + Instant.ofEpochSecond(proofObservedAt - 301), initialObservationContext); + when(inventorySource.observe(initialObservationContext)).thenReturn(staleProofInventory); + assertThatThrownBy(coordinator::prepareCurrentPromotionOnce) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + assertThat(inTransaction(context, () -> desired.read(BINDING).preparedOperationId())).isEmpty(); + assertThat(count(context, "account_jwt_signer_promotion_operations")).isZero(); + + InventorySnapshot driftedProofInventory = + completeInventorySnapshot( + Instant.ofEpochSecond(proofObservedAt), "10.11.0.99", initialObservationContext); + when(inventorySource.observe(initialObservationContext)).thenReturn(driftedProofInventory); + assertThatThrownBy(coordinator::prepareCurrentPromotionOnce) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + assertThat(inTransaction(context, () -> desired.read(BINDING).preparedOperationId())).isEmpty(); + assertThat(count(context, "account_jwt_signer_promotion_operations")).isZero(); + + when(inventorySource.observe(initialObservationContext)).thenReturn(proofInventory); + Optional prepared = coordinator.prepareCurrentPromotionOnce(); + assertThat(prepared).isPresent(); + assertThat(prepared.orElseThrow().operationId()).isEqualTo(result.operationId()); + assertThat(prepared.orElseThrow().status()).isEqualTo("PREPARED"); + assertThat(inTransaction(context, () -> desired.read(BINDING).preparedOperationId())) + .contains(result.operationId()); + assertThat(count(context, "account_jwt_signer_promotion_operations")).isEqualTo(1L); + assertThat( + inTransaction( + context, + () -> + restartedReadiness.readPromotionProof( + BINDING, trust, result.operationId(), proofInventory))) + .isPresent(); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(12L); + + var preparedEvidence = + inTransaction(context, () -> desired.readPreparedGenerationForRecovery(BINDING, trust)); + var promotion = preparedEvidence.promotion(); + inTransaction(context, () -> desired.readAndMarkPreparedPromotionDispatched(BINDING, trust)); + PrivatePromotionObservation privateObservation = + new PrivatePromotionObservation( + promotion.operationId(), + promotion.requestDigest(), + promotion.generationOperationId(), + promotion.generationOperationDigest(), + promotion.secretUid(), + promotion.expectedPrivateResourceVersion(), + "14", + new PublicKeyIdentity( + promotion.targetGeneration(), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint()), + Optional.empty(), + List.of("current")); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + desired.commitPreparedPromotion( + BINDING, trust, promotion.operationId(), currentProof.orElseThrow()))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException.class) + .hasMessageContaining("exact private and public resource receipts"); + PrivatePromotionReceipt privateReceipt = + inTransaction( + context, + () -> desired.recordPrivatePromotionResult(BINDING, trust, privateObservation)); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + desired.commitPreparedPromotion( + BINDING, trust, promotion.operationId(), currentProof.orElseThrow()))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException.class) + .hasMessageContaining("exact private and public resource receipts"); + + var activeReceipt = + inTransaction( + context, + () -> + desired.recordActiveJwksPromotionResult( + BINDING, + trust, + new ActiveJwksPromotionObservation( + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + "45", + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson()))); + assertThat(activeReceipt.promotionOperationId()).isEqualTo(promotion.operationId()); + var freshProof = + inTransaction( + context, + () -> + restartedReadiness.readPromotionProof( + BINDING, trust, result.operationId(), proofInventory)) + .orElseThrow(); + var committed = + inTransaction( + context, + () -> + desired.commitPreparedPromotion( + BINDING, trust, promotion.operationId(), freshProof)); + assertThat(committed.promotion().status()).isEqualTo("COMMITTED"); + assertThat(committed.privateReceipt()).isEqualTo(privateReceipt); + assertThat(committed.publicReceipt()).isEqualTo(activeReceipt); + + assertThat( + inTransaction( + context, + () -> desired.recordPrivatePromotionResult(BINDING, trust, privateObservation))) + .isEqualTo(privateReceipt); + PrivatePromotionObservation changedReplay = + new PrivatePromotionObservation( + privateObservation.promotionOperationId(), + privateObservation.promotionRequestDigest(), + privateObservation.generationOperationId(), + privateObservation.generationOperationDigest(), + privateObservation.secretUid(), + privateObservation.expectedPriorResourceVersion(), + "15", + privateObservation.current(), + privateObservation.previous(), + privateObservation.resultingSlots()); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> desired.recordPrivatePromotionResult(BINDING, trust, changedReplay))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); + assertThat( + inTransaction( + context, + () -> + desired + .readCurrentCommittedSigner(BINDING, trust, API_DIGEST, API_REVISION) + .orElseThrow() + .promotion() + .operationId())) + .isEqualTo(promotion.operationId()); + } + + private static ValidatorFixture createValidatorFixture( + TestContext context, AccountJwtReadinessProbeRepository readiness, String desiredJwks) + throws Exception { + byte[] harnessSpki = "real-pg-readiness-harness-leaf-spki".getBytes(StandardCharsets.US_ASCII); + try { + String harnessSpkiSha256 = sha256(harnessSpki); + long bindingValidUntil = Instant.now().plusSeconds(3_600).getEpochSecond(); + String harnessUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"; + List harnessPins = List.of(harnessSpkiSha256); + String readinessRevision = "readiness-instance-r1"; + String validatorInstanceId = "account-validator-instance-7"; + String readinessDigest = + AccountJwtReadinessTrustBinding.computeBindingDigest( + readinessRevision, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + harnessUri, + harnessPins, + validatorInstanceId, + bindingValidUntil); + var readinessBinding = + new AccountJwtReadinessTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + harnessUri, + harnessPins, + readinessRevision, + "account-service", + validatorInstanceId, + bindingValidUntil, + readinessDigest); + String materializerDigest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + TRUST_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + MATERIALIZER_PINS); + var materializerBinding = + new AccountJwtSignerMaterializerTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + MATERIALIZER_PINS, + TRUST_REVISION, + materializerDigest); + + AccountJwtReadinessTrustBinding readinessTrust = mock(AccountJwtReadinessTrustBinding.class); + AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + when(readinessTrust.current()).thenReturn(Optional.of(readinessBinding)); + when(materializerTrust.current()).thenReturn(Optional.of(materializerBinding)); + + AccountPublicJwksCache.SourceIdentity sourceIdentity = + new AccountPublicJwksCache.SourceIdentity( + BINDING.environmentId(), + BINDING.clusterId(), + CLUSTER_UID, + BINDING.namespace(), + NAMESPACE_UID, + CONFIG_MAP_UID, + API_REVISION, + "https://kubernetes.example:6443", + "9".repeat(64)); + AccountJwtJwksTrustedSource trustedSource = mock(AccountJwtJwksTrustedSource.class); + when(trustedSource.sourceIdentity()).thenReturn(sourceIdentity); + when(trustedSource.load()) + .thenReturn( + new AccountPublicJwksCache.PublicJwksSnapshot( + sourceIdentity, desiredJwks.getBytes(StandardCharsets.UTF_8))); + DataSourceTransactionManager transactionManager = + new DataSourceTransactionManager(context.dataSource()); + AccountJwtReadinessValidationService validationService = + new AccountJwtReadinessValidationService( + readiness, readinessTrust, materializerTrust, trustedSource, transactionManager, 8); + AccountJwtReadinessTlsInterceptor.AuthenticatedCaller caller = + authenticatedHarnessCaller(readinessBinding, harnessSpki); + return new ValidatorFixture( + validationService, + caller, + validatorInstanceId, + readinessDigest, + readinessRevision, + harnessUri, + harnessSpkiSha256); + } finally { + java.util.Arrays.fill(harnessSpki, (byte) 0); + } + } + + private record ValidatorFixture( + AccountJwtReadinessValidationService service, + AccountJwtReadinessTlsInterceptor.AuthenticatedCaller caller, + String validatorInstanceId, + String readinessDigest, + String readinessRevision, + String harnessUri, + String harnessSpkiSha256) { + private VerificationReceipt validate(ProbeEntry entry, byte[] compactJwt) { + assertThat(sha256(compactJwt)).isEqualTo(entry.compactTokenSha256().orElseThrow()); + ValidateReadinessProbeRequest request = + ValidateReadinessProbeRequest.newBuilder() + .setSchemaVersion(1) + .setRotationOperationId(entry.rotationOperationId().toString()) + .setValidatorId(entry.validatorId()) + .setTokenProfile(entry.tokenProfile()) + .setAudience(entry.audience()) + .setProbeKind(entry.probeKind().name()) + .setJti(entry.jti().toString()) + .setCompactJwt(new String(compactJwt, StandardCharsets.US_ASCII)) + .build(); + return service.validate(request, caller); + } + } + + private static AccountJwtReadinessTlsInterceptor.AuthenticatedCaller authenticatedHarnessCaller( + AccountJwtReadinessTrustBinding.Binding binding, byte[] spki) throws Exception { + AccountJwtReadinessTrustBinding bindingProvider = mock(AccountJwtReadinessTrustBinding.class); + when(bindingProvider.current()).thenReturn(Optional.of(binding)); + AccountJwtReadinessTlsInterceptor interceptor = + new AccountJwtReadinessTlsInterceptor(bindingProvider); + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + @SuppressWarnings("unchecked") + ServerCallHandler next = mock(ServerCallHandler.class); + SSLSession session = mock(SSLSession.class); + java.security.cert.X509Certificate certificate = mock(java.security.cert.X509Certificate.class); + java.security.PublicKey publicKey = mock(java.security.PublicKey.class); + when(certificate.getPublicKey()).thenReturn(publicKey); + when(publicKey.getEncoded()).thenReturn(spki); + when(certificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, binding.expectedPeerUri()))); + when(session.getPeerCertificates()) + .thenReturn(new java.security.cert.Certificate[] {certificate}); + when(call.getAttributes()) + .thenReturn(Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build()); + AtomicReference captured = + new AtomicReference<>(); + when(next.startCall(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) + .thenAnswer( + invocation -> { + captured.set(AccountJwtReadinessTlsInterceptor.authenticatedCaller()); + return new ServerCall.Listener<>() {}; + }); + interceptor.interceptCall(call, new Metadata(), next); + return captured.get(); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + String separator = testJdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(testJdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(testJdbcUsername); + dataSource.setPassword(testJdbcPassword); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + return new TestContext(dataSource, new TransactionTemplate(transactionManager), dsl); + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static long count(TestContext context, String table) { + return java.util.Objects.requireNonNull( + context.dsl().resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class), + "COUNT query must return a scalar row"); + } + + private static AccountJwtReadinessProbeRepository.DeliveryClaim raceForSingleDeliveryClaim( + TestContext context, + AccountJwtReadinessProbeRepository readiness, + TrustFence trust, + ReadinessProbePlan plan, + AccountJwtReadinessTrustBinding.Binding readinessBinding, + AccountJwtReadinessTrustBinding.PeerIdentity peer, + long claimedAtEpochSecond) + throws Exception { + ExecutorService contenders = Executors.newFixedThreadPool(2); + CyclicBarrier start = new CyclicBarrier(2); + try { + List> attempts = + List.of( + contenders.submit( + () -> { + start.await(30, TimeUnit.SECONDS); + return inTransaction( + context, + () -> + readiness.claimSingleDelivery( + BINDING, + trust, + plan, + readinessBinding, + peer, + Instant.ofEpochSecond(claimedAtEpochSecond))); + }), + contenders.submit( + () -> { + start.await(30, TimeUnit.SECONDS); + return inTransaction( + context, + () -> + readiness.claimSingleDelivery( + BINDING, + trust, + plan, + readinessBinding, + peer, + Instant.ofEpochSecond(claimedAtEpochSecond))); + })); + AccountJwtReadinessProbeRepository.DeliveryClaim winner = null; + int rejected = 0; + for (Future attempt : attempts) { + try { + AccountJwtReadinessProbeRepository.DeliveryClaim claim = + attempt.get(30, TimeUnit.SECONDS); + assertThat(winner).isNull(); + winner = claim; + } catch (ExecutionException failure) { + assertThat(failure.getCause()) + .isInstanceOf( + AccountJwtReadinessProbeRepository.DeliveryAlreadyClaimedException.class); + rejected++; + } + } + assertThat(winner).isNotNull(); + assertThat(rejected).isEqualTo(1); + return winner; + } finally { + contenders.shutdownNow(); + assertThat(contenders.awaitTermination(30, TimeUnit.SECONDS)).isTrue(); + } + } + + private static void raceForPodAcceptance( + TestContext context, + AccountJwtReadinessProbeRepository readiness, + TrustFence trust, + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance acceptance, + InventorySnapshot currentInventory) + throws Exception { + ExecutorService contenders = Executors.newFixedThreadPool(2); + CyclicBarrier start = new CyclicBarrier(2); + try { + List> attempts = + List.of( + contenders.submit( + () -> { + start.await(30, TimeUnit.SECONDS); + return inTransaction( + context, + () -> + readiness.recordPodAcceptance( + BINDING, trust, entry, expectedPod, acceptance, currentInventory)); + }), + contenders.submit( + () -> { + start.await(30, TimeUnit.SECONDS); + return inTransaction( + context, + () -> + readiness.recordPodAcceptance( + BINDING, trust, entry, expectedPod, acceptance, currentInventory)); + })); + ProbeEntry first = attempts.getFirst().get(30, TimeUnit.SECONDS); + ProbeEntry second = attempts.getLast().get(30, TimeUnit.SECONDS); + assertThat(first).isEqualTo(second); + assertThat(first.state()).isEqualTo(ProbeState.ISSUED); + } finally { + contenders.shutdownNow(); + assertThat(contenders.awaitTermination(30, TimeUnit.SECONDS)).isTrue(); + } + } + + private static List columnNames(TestContext context, String table) { + return context + .dsl() + .resultQuery( + "SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() " + + "AND table_name = ? ORDER BY ordinal_position", + table) + .fetch() + .getValues("column_name", String.class); + } + + private static TrustFence trust() { + return new TrustFence(CLUSTER_UID, NAMESPACE_UID, TRUST_DIGEST, TRUST_REVISION); + } + + private static AccountJwtSignerMaterializerTrustBinding.Binding materializerBinding() { + return new AccountJwtSignerMaterializerTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + MATERIALIZER_PINS, + TRUST_REVISION, + TRUST_DIGEST); + } + + private static String marker(GenerationResult result) throws Exception { + Map marker = new LinkedHashMap<>(); + marker.put("schemaVersion", 1); + marker.put("phase", "PREPUBLISHED"); + marker.put("operationId", result.operationId().toString()); + marker.put("operationDigest", result.operationDigest()); + marker.put("generationRequestDigest", result.generationRequestDigest()); + marker.put("generationReceiptDigest", result.receiptDigest()); + Map binding = new LinkedHashMap<>(); + binding.put("environmentId", result.binding().environmentId()); + binding.put("clusterId", result.binding().clusterId()); + binding.put("namespace", result.binding().namespace()); + binding.put( + "expectedClusterIncarnationUid", result.trustFence().expectedClusterIncarnationUid()); + binding.put("expectedNamespaceUid", result.trustFence().expectedNamespaceUid()); + binding.put("trustBindingDigest", result.trustFence().bindingDigest()); + binding.put("trustConfigRevision", result.trustFence().configRevision()); + binding.put("apiBindingDigest", API_DIGEST); + binding.put("apiConfigRevision", API_REVISION); + marker.put("binding", binding); + marker.put("publicConfigMap", Map.of("name", "jwt-jwks")); + marker.put("expectedDurableActive", Map.of("present", false)); + marker.put("expectedPublishedActive", Map.of("present", false)); + marker.put( + "pending", + Map.of( + "generation", + result.targetGeneration(), + "kid", + result.targetKid(), + "algorithm", + result.targetAlgorithm(), + "publicKeyFingerprint", + result.publicKeyFingerprint())); + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(marker)), + StandardCharsets.UTF_8); + } + + private static String privateBundleJson( + GenerationRequest request, GenerationResult result, KeyPair pair) { + Map bundle = new LinkedHashMap<>(); + bundle.put("version", 1); + bundle.put("environmentId", request.binding().environmentId()); + bundle.put("clusterId", request.binding().clusterId()); + bundle.put("namespace", request.binding().namespace()); + bundle.put("operationId", request.operationId().toString()); + bundle.put("generation", result.targetGeneration()); + bundle.put("kid", result.targetKid()); + bundle.put("algorithm", "RS256"); + bundle.put( + "privateKeyPkcs8", + Base64.getUrlEncoder().withoutPadding().encodeToString(pair.getPrivate().getEncoded())); + bundle.put("publicKeyFingerprint", result.publicKeyFingerprint()); + return JSON.writeValueAsString(bundle); + } + + private static PublicJwk publicJwk(String kid, RSAPublicKey key) throws Exception { + String modulus = encodeUnsigned(key.getModulus()); + String exponent = encodeUnsigned(key.getPublicExponent()); + Map jwk = new LinkedHashMap<>(); + jwk.put("alg", "RS256"); + jwk.put("e", exponent); + jwk.put("key_ops", List.of("verify")); + jwk.put("kid", kid); + jwk.put("kty", "RSA"); + jwk.put("n", modulus); + jwk.put("use", "sig"); + String json = canonicalJson(jwk); + Map withoutKeyOps = new LinkedHashMap<>(jwk); + withoutKeyOps.remove("key_ops"); + String jsonWithoutKeyOps = canonicalJson(withoutKeyOps); + String fingerprint = + sha256( + Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(Map.of("e", exponent, "kty", "RSA", "n", modulus)))); + return new PublicJwk(json, jsonWithoutKeyOps, fingerprint); + } + + private static String canonicalJson(Map value) throws Exception { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } + + private static String jwks(String retainedJwk, String targetJwk) { + return "{\"keys\":[" + retainedJwk + "," + targetJwk + "]}"; + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + private static KeyPair generateRsa3072() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3_072); + return generator.generateKeyPair(); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is required for the persistence fixture", ex); + } + } + + private static AccountJwtReadinessProbeOwnerSelector ownerSelector( + ReadinessProbePlan plan, + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod) { + return ownerSelector(plan, entry, expectedPod, null, null, null); + } + + private static AccountJwtReadinessProbeOwnerSelector ownerSelector( + ReadinessProbePlan plan, + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + String tokenHashOverride, + Long planExpiryOverride, + String podUidOverride) { + return ownerSelector( + plan, + entry, + expectedPod, + tokenHashOverride, + planExpiryOverride, + podUidOverride, + null, + null, + null); + } + + private static AccountJwtReadinessProbeOwnerSelector ownerSelector( + ReadinessProbePlan plan, + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + String tokenHashOverride, + Long planExpiryOverride, + String podUidOverride, + UUID operationIdOverride, + String targetKidOverride, + Optional activeOverride) { + var target = expectedPod.target(); + LocalIdentity localIdentity = + new LocalIdentity( + target.validatorId(), + target.deploymentUid(), + podUidOverride == null ? target.podUid() : podUidOverride, + target.podIp(), + target.exactPodEndpoint().orElseThrow().toString(), + target.canonicalServiceUri().orElseThrow(), + target.image(), + target.verifierConfigSha256(), + target.applicabilityMatrixDigest(), + "game-session-source-r1", + "9".repeat(64), + target.podLeafSpkiSha256().orElseThrow()); + return new AccountJwtReadinessProbeOwnerSelector( + operationIdOverride == null ? plan.operationId() : operationIdOverride, + plan.operationDigest(), + plan.planDigest(), + plan.planVersion(), + entry.registryVersion(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + target.expectation(), + entry.jti(), + entry.entryVersion(), + entry.targetGeneration(), + targetKidOverride == null ? entry.targetKid() : targetKidOverride, + activeOverride == null ? entry.expectedActive() : activeOverride, + entry.plannedIssuedAtEpochSecond(), + entry.expiresAtEpochSecond(), + planExpiryOverride == null ? plan.expiresAtEpochSecond() : planExpiryOverride, + tokenHashOverride == null ? entry.compactTokenSha256().orElseThrow() : tokenHashOverride, + localIdentity); + } + + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, ObservationContext observationContext) { + return completeInventorySnapshot(observedAt, "10.11.0.11", observationContext); + } + + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, String firstAccountPodIp, ObservationContext observationContext) { + return completeInventorySnapshot( + observedAt, firstAccountPodIp, observationContext, "77777777-7777-4777-8777-777777777777"); + } + + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, + String firstAccountPodIp, + ObservationContext observationContext, + String firstAccountPodUid) { + String accountImage = "registry.example/account-validator@sha256:" + "1".repeat(64); + String gameSessionImage = "registry.example/game-session-validator@sha256:" + "3".repeat(64); + String accountConfigDigest = "2".repeat(64); + String gameSessionConfigDigest = "4".repeat(64); + String accountServiceUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator"; + String gameSessionServiceUri = "spiffe://firemud/ns/firemud-prod/sa/game-session-jwt-validator"; + List accountProfiles = + List.of( + new ProfileExpectation("control-ui", "control-ui"), + new ProfileExpectation("game-session-account-delegation", "account-service"), + new ProfileExpectation("player-bootstrap", "player-bootstrap")); + List gameSessionProfiles = + List.of(new ProfileExpectation("game-session-account-delegation", "account-service")); + List accountPods = + List.of( + inventoryPod( + "account-a", + firstAccountPodUid, + "account-rs", + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "acct1", + firstAccountPodIp, + 9443, + accountImage, + accountConfigDigest, + accountServiceUri, + "5".repeat(64)), + inventoryPod( + "account-b", + "88888888-8888-4888-8888-888888888888", + "account-rs", + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "acct1", + "10.11.0.12", + 9443, + accountImage, + accountConfigDigest, + accountServiceUri, + "6".repeat(64))); + List gameSessionPods = + List.of( + inventoryPod( + "game-session-a", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "game-session-rs", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "games", + "10.12.0.11", + 9444, + gameSessionImage, + gameSessionConfigDigest, + gameSessionServiceUri, + "7".repeat(64))); + List validators = + List.of( + new ValidatorObservation( + "account-service", + "account-service", + "66666666-6666-4666-8666-666666666666", + 1L, + "51", + 2, + accountImage, + accountConfigDigest, + 300, + accountProfiles, + accountPods, + List.of()), + new ValidatorObservation( + "game-session-service", + "game-session-service", + "99999999-9999-4999-8999-999999999999", + 1L, + "52", + 1, + gameSessionImage, + gameSessionConfigDigest, + 300, + gameSessionProfiles, + gameSessionPods, + List.of())); + List> validatorMaps = + List.of( + inventoryValidatorMap(validators.get(0), accountServiceUri, 9443), + inventoryValidatorMap(validators.get(1), gameSessionServiceUri, 9444)); + Map preimage = new LinkedHashMap<>(); + preimage.put("domain", "firemud-account-validator-inventory/v2"); + preimage.put("environmentId", BINDING.environmentId()); + preimage.put("clusterId", BINDING.clusterId()); + preimage.put("clusterIncarnationUid", CLUSTER_UID); + preimage.put("namespace", BINDING.namespace()); + preimage.put("namespaceUid", NAMESPACE_UID); + preimage.put("apiBindingRevision", API_REVISION); + preimage.put("apiBindingDigest", API_DIGEST); + preimage.put("inventoryBindingRevision", "inventory-r1"); + preimage.put("inventoryBindingDigest", "c".repeat(64)); + preimage.put( + "observationContext", + Map.of( + "purpose", observationContext.purpose().name(), + "operationId", observationContext.operationId().toString(), + "operationDigest", observationContext.operationDigest())); + preimage.put("validators", validatorMaps); + byte[] bytes; + try { + bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + } catch (Exception failure) { + throw new AssertionError(failure); + } + InventorySnapshot snapshot = mock(InventorySnapshot.class); + when(snapshot.observedAt()).thenReturn(observedAt); + when(snapshot.environmentId()).thenReturn(BINDING.environmentId()); + when(snapshot.clusterId()).thenReturn(BINDING.clusterId()); + when(snapshot.clusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(snapshot.namespace()).thenReturn(BINDING.namespace()); + when(snapshot.namespaceUid()).thenReturn(NAMESPACE_UID); + when(snapshot.apiBindingRevision()).thenReturn(API_REVISION); + when(snapshot.apiBindingDigest()).thenReturn(API_DIGEST); + when(snapshot.inventoryBindingRevision()).thenReturn("inventory-r1"); + when(snapshot.inventoryBindingDigest()).thenReturn("c".repeat(64)); + when(snapshot.observationContext()).thenReturn(Optional.of(observationContext)); + when(snapshot.validators()).thenReturn(validators); + when(snapshot.canonicalBytes()).thenReturn(bytes.clone()); + when(snapshot.digest()).thenReturn(sha256(bytes)); + return snapshot; + } + + private static PodObservation inventoryPod( + String name, + String uid, + String ownerName, + String ownerUid, + String podTemplateHash, + String podIp, + int receiverPort, + String image, + String configDigest, + String serviceUri, + String spkiDigest) { + String host = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + return new PodObservation( + name, + uid, + "11", + ownerName, + ownerUid, + podTemplateHash, + image, + configDigest, + podIp, + URI.create("grpcs://" + host + ":" + receiverPort), + serviceUri, + spkiDigest); + } + + private static Map inventoryValidatorMap( + ValidatorObservation validator, String serviceUri, int receiverPort) { + Map result = new LinkedHashMap<>(); + result.put("validatorId", validator.validatorId()); + result.put("deploymentName", validator.deploymentName()); + result.put("deploymentUid", validator.deploymentUid()); + result.put("deploymentGeneration", Long.toString(validator.deploymentGeneration())); + result.put("deploymentResourceVersion", validator.deploymentResourceVersion()); + result.put("replicas", Integer.toString(validator.replicas())); + result.put("image", validator.image()); + result.put("verifierConfigSha256", validator.verifierConfigSha256()); + result.put("maxCacheAgeSeconds", Integer.toString(validator.maxCacheAgeSeconds())); + result.put( + "profiles", + validator.profiles().stream() + .map( + profile -> + Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .toList()); + result.put( + "pods", + validator.pods().stream() + .map( + pod -> + Map.ofEntries( + Map.entry("name", pod.name()), + Map.entry("uid", pod.uid()), + Map.entry("resourceVersion", pod.resourceVersion()), + Map.entry("ownerReplicaSetName", pod.ownerName()), + Map.entry("ownerReplicaSetUid", pod.ownerUid()), + Map.entry("podTemplateHash", pod.podTemplateHash()), + Map.entry("image", pod.image()), + Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), + Map.entry("podIp", pod.podIp()), + Map.entry("exactPodEndpoint", pod.endpoint().toString()), + Map.entry("canonicalServiceUri", pod.receiverServiceUri()), + Map.entry("leafSpkiSha256", pod.leafSpkiSha256()))) + .toList()); + result.put("receiverServiceUri", serviceUri); + result.put("receiverPort", receiverPort); + result.put("replicaSets", List.of()); + return result; + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + long observedAtEpochSecond) { + return testAuthenticatedAcceptance( + entry, expectedPod, observedAtEpochSecond, entry.targetKid()); + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + long observedAtEpochSecond, + String verifiedKid) { + return testAuthenticatedAcceptance( + entry, + expectedPod, + observedAtEpochSecond, + verifiedKid, + expectedPod.target().exactPodEndpoint().orElseThrow().toString()); + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + long observedAtEpochSecond, + String verifiedKid, + String actualPodEndpoint) { + var target = expectedPod.target(); + return AccountJwtReadinessReceiverInvocationPort.authenticatedAcceptance( + target.podUid(), + actualPodEndpoint, + target.image(), + target.verifierConfigSha256(), + target.canonicalServiceUri().orElseThrow(), + target.podLeafSpkiSha256().orElseThrow(), + entry.jti(), + entry.compactTokenSha256().orElseThrow(), + verifiedKid, + target.expectation(), + observedAtEpochSecond); + } + + private static String safeValidationFailure(RuntimeException failure) { + String exceptionClass = + failure instanceof DataAccessException + ? "DataAccessException" + : failure instanceof IllegalStateException + ? "IllegalStateException" + : failure instanceof IllegalArgumentException + ? "IllegalArgumentException" + : "UNKNOWN"; + String sqlState = "UNKNOWN"; + String constraint = "UNKNOWN"; + Throwable current = failure; + for (int depth = 0; current != null && depth < 8; depth++, current = current.getCause()) { + if (current instanceof PSQLException postgresFailure) { + String candidateSqlState = postgresFailure.getSQLState(); + if (candidateSqlState != null && candidateSqlState.matches("[0-9A-Z]{5}")) { + sqlState = candidateSqlState; + } + var serverError = postgresFailure.getServerErrorMessage(); + String candidateConstraint = serverError == null ? null : serverError.getConstraint(); + if (candidateConstraint != null + && VALIDATION_CONSTRAINT_ALLOWLIST.contains(candidateConstraint)) { + constraint = candidateConstraint; + } + break; + } + } + return "class=" + exceptionClass + ";sqlstate=" + sqlState + ";constraint=" + constraint; + } + + private static String validateExternalLoopbackPostgresUrl(String jdbcUrl) { + final URI uri; + try { + if (!jdbcUrl.startsWith("jdbc:")) { + throw new IllegalArgumentException("not a JDBC URL"); + } + uri = URI.create(jdbcUrl.substring("jdbc:".length())); + } catch (RuntimeException ex) { + throw new IllegalStateException( + EXTERNAL_POSTGRES_URL_ENV + " must target jdbc:postgresql://127.0.0.1:/postgres", + ex); + } + if (!"postgresql".equals(uri.getScheme()) + || !"127.0.0.1".equals(uri.getHost()) + || uri.getPort() < 1 + || uri.getPort() > 65_535 + || !"/postgres".equals(uri.getPath()) + || uri.getUserInfo() != null + || uri.getQuery() != null + || uri.getFragment() != null) { + throw new IllegalStateException( + EXTERNAL_POSTGRES_URL_ENV + " must target jdbc:postgresql://127.0.0.1:/postgres"); + } + return jdbcUrl; + } + + private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + + private record TestContext( + DriverManagerDataSource dataSource, TransactionTemplate transaction, DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverWorkloadGuardTest.java new file mode 100644 index 0000000000..6b5c78ed6d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverWorkloadGuardTest.java @@ -0,0 +1,138 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import java.net.URI; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class AccountJwtReadinessPodReceiverWorkloadGuardTest { + private static final String NAMESPACE = "firemud-prod"; + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void requiresExactAccountPeerAndMatchingProtectedAccountBindings() { + var guard = guard(NAMESPACE); + assertThatThrownBy(guard::requireAccountReceiverCaller) + .isInstanceOf( + AccountJwtReadinessPodReceiverWorkloadGuard.ReceiverCallerDeniedException.class); + + withPeer( + peer("other", "account-service"), + () -> + assertThatThrownBy(guard::requireAccountReceiverCaller) + .isInstanceOf( + AccountJwtReadinessPodReceiverWorkloadGuard.ReceiverCallerDeniedException + .class)); + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> + assertThatThrownBy(guard::requireAccountReceiverCaller) + .isInstanceOf( + AccountJwtReadinessPodReceiverWorkloadGuard.ReceiverCallerDeniedException + .class)); + + withPeer( + peer(NAMESPACE, "account-service"), + () -> + assertThat(guard.requireAccountReceiverCaller().accountBinding().namespace()) + .isEqualTo(NAMESPACE)); + } + + @Test + void rejectsSessionContextAndProtectedTrustDriftAcrossVerification() { + Binding original = binding(NAMESPACE, "materializer-r1"); + AtomicReference current = new AtomicReference<>(original); + var guard = + new AccountJwtReadinessPodReceiverWorkloadGuard( + () -> Optional.of(current.get()), () -> apiBinding(NAMESPACE), NAMESPACE); + + withPeer( + peer(NAMESPACE, "account-service"), + () -> { + var caller = guard.requireAccountReceiverCaller(); + guard.requireUnchanged(caller); + current.set(binding(NAMESPACE, "materializer-r2")); + assertThatThrownBy(() -> guard.requireUnchanged(caller)) + .isInstanceOf( + AccountJwtReadinessPodReceiverWorkloadGuard.ReceiverCallerDeniedException.class); + + SessionContext.setContext("authenticated-account", List.of(), Map.of()); + assertThatThrownBy(guard::requireAccountReceiverCaller) + .isInstanceOf( + AccountJwtReadinessPodReceiverWorkloadGuard.ReceiverCallerDeniedException.class); + }); + } + + private static AccountJwtReadinessPodReceiverWorkloadGuard guard(String localNamespace) { + Binding binding = binding(NAMESPACE, "materializer-r1"); + return new AccountJwtReadinessPodReceiverWorkloadGuard( + () -> Optional.of(binding), () -> apiBinding(NAMESPACE), localNamespace); + } + + private static Binding binding(String namespace, String revision) { + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/jwt-signer-materializer"; + List pins = List.of("a".repeat(64)); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, "prod", "cluster-a", namespace, clusterUid, namespaceUid, expectedPeer, pins); + return new Binding( + "prod", + "cluster-a", + namespace, + clusterUid, + namespaceUid, + expectedPeer, + pins, + revision, + digest); + } + + private static AccountJwtJwksApiBinding.ParsedBinding apiBinding(String namespace) { + return new AccountJwtJwksApiBinding.ParsedBinding( + "api-r1", + "prod", + "cluster-a", + URI.create("https://kubernetes.example.test:6443"), + "kubernetes.example.test", + Path.of("protected").toAbsolutePath().resolve("ca.pem"), + "b".repeat(64), + Path.of("protected").toAbsolutePath().resolve("token"), + namespace, + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "system:serviceaccount:" + namespace + ":account-service", + "c".repeat(64)); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.ROOT.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPrerequisiteConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPrerequisiteConfigurationTest.java new file mode 100644 index 0000000000..18daf679be --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPrerequisiteConfigurationTest.java @@ -0,0 +1,119 @@ +package unit.net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPrerequisiteConfiguration; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.assertj.AssertableApplicationContext; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class AccountJwtReadinessPrerequisiteConfigurationTest { + private static final String[] VALID_PREREQUISITE_PROPERTIES = { + "firemud.account.jwt-readiness.validation.enabled=true", + "firemud.account.jwt-jwks-api.enabled=true", + "firemud.account.jwt-jwks-api.protected-binding-path=/etc/firemud/account-jwt-api/binding.json", + "firemud.account.jwt-signer.materialization.enabled=true", + "firemud.account.jwt-signer.materialization.protected-binding-path=/etc/firemud/account-jwt-materializer/binding.json", + "firemud.grpc.workload-namespace=firemud-prod" + }; + + private final ApplicationContextRunner contextRunner = + new ApplicationContextRunner() + .withUserConfiguration(AccountJwtReadinessPrerequisiteConfiguration.class); + + @Test + void prerequisiteGraphIsAbsentWithoutExplicitReadinessAndProtectedBindings() { + contextRunner + .withPropertyValues( + "firemud.account.jwt-jwks-api.enabled=true", + "firemud.account.jwt-jwks-api.protected-binding-path=/etc/firemud/account-jwt-api/binding.json", + "firemud.account.jwt-signer.materialization.enabled=true", + "firemud.account.jwt-signer.materialization.protected-binding-path=/etc/firemud/account-jwt-materializer/binding.json", + "firemud.grpc.workload-namespace=firemud-prod") + .run(AccountJwtReadinessPrerequisiteConfigurationTest::assertNoPrerequisiteBeans); + + contextRunner + .withPropertyValues("firemud.account.jwt-readiness.validation.enabled=true") + .run(AccountJwtReadinessPrerequisiteConfigurationTest::assertNoPrerequisiteBeans); + + contextRunner + .withPropertyValues( + "firemud.account.gameplay-canonical-login.readiness.enabled=true", + "firemud.account.jwt-jwks-api.enabled=true", + "firemud.account.jwt-jwks-api.protected-binding-path=/etc/firemud/account-jwt-api/binding.json", + "firemud.account.jwt-signer.materialization.enabled=true", + "firemud.account.jwt-signer.materialization.protected-binding-path=/etc/firemud/account-jwt-materializer/binding.json", + "firemud.grpc.workload-namespace=firemud-prod") + .run(AccountJwtReadinessPrerequisiteConfigurationTest::assertNoPrerequisiteBeans); + } + + @Test + void exactExplicitReadinessCompositionRegistersOnlyLazyProtectedPrerequisites() { + contextRunner + .withPropertyValues(VALID_PREREQUISITE_PROPERTIES) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertLazyBean(context, "accountJwtReadinessJwksApiBinding"); + assertLazyBean(context, "accountJwtReadinessJwksConfigMapClient"); + assertLazyBean(context, "accountJwtReadinessTrustedJwksSource"); + assertThat( + context + .getBeanFactory() + .containsSingleton("accountJwtReadinessJwksApiBinding")) + .isFalse(); + assertThat( + context + .getBeanFactory() + .containsSingleton("accountJwtReadinessJwksConfigMapClient")) + .isFalse(); + assertThat( + context + .getBeanFactory() + .containsSingleton("accountJwtReadinessTrustedJwksSource")) + .isFalse(); + }); + } + + @Test + void invalidNamespaceOrChangedBindingPathsKeepPrerequisitesUnavailable() { + contextRunner + .withPropertyValues( + VALID_PREREQUISITE_PROPERTIES[0], + VALID_PREREQUISITE_PROPERTIES[1], + VALID_PREREQUISITE_PROPERTIES[2], + VALID_PREREQUISITE_PROPERTIES[3], + VALID_PREREQUISITE_PROPERTIES[4], + "firemud.grpc.workload-namespace=INVALID_NAMESPACE") + .run(AccountJwtReadinessPrerequisiteConfigurationTest::assertNoPrerequisiteBeans); + + contextRunner + .withPropertyValues( + "firemud.account.jwt-readiness.pod-receiver.enabled=true", + "firemud.account.jwt-jwks-api.enabled=true", + "firemud.account.jwt-jwks-api.protected-binding-path=/tmp/other-binding.json", + "firemud.account.jwt-signer.materialization.enabled=true", + "firemud.account.jwt-signer.materialization.protected-binding-path=/etc/firemud/account-jwt-materializer/binding.json", + "firemud.grpc.workload-namespace=firemud-prod") + .run(AccountJwtReadinessPrerequisiteConfigurationTest::assertNoPrerequisiteBeans); + } + + private static void assertNoPrerequisiteBeans(AssertableApplicationContext context) { + assertThat(context).hasNotFailed(); + assertThat(context.getBeanFactory().containsBeanDefinition("accountJwtReadinessJwksApiBinding")) + .isFalse(); + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessJwksConfigMapClient")) + .isFalse(); + assertThat( + context.getBeanFactory().containsBeanDefinition("accountJwtReadinessTrustedJwksSource")) + .isFalse(); + } + + private static void assertLazyBean(AssertableApplicationContext context, String beanName) { + assertThat(context.getBeanFactory().containsBeanDefinition(beanName)).isTrue(); + assertThat(context.getBeanFactory().getBeanDefinition(beanName).isLazyInit()).isTrue(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerWorkloadGuardTest.java new file mode 100644 index 0000000000..d523ec312c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerWorkloadGuardTest.java @@ -0,0 +1,138 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import java.net.URI; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class AccountJwtReadinessProbeOwnerWorkloadGuardTest { + private static final String NAMESPACE = "firemud-prod"; + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void requiresExactGameSessionPeerAndNamespaceFromBothProtectedAndLocalBindings() { + var guard = guard(NAMESPACE); + + assertThatThrownBy(guard::requireGameSessionOwnerReadCaller) + .isInstanceOf(AccountJwtReadinessProbeOwnerWorkloadGuard.OwnerReadDeniedException.class); + + withPeer( + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", "other", "game-session-service"), + () -> + assertThatThrownBy(guard::requireGameSessionOwnerReadCaller) + .isInstanceOf( + AccountJwtReadinessProbeOwnerWorkloadGuard.OwnerReadDeniedException.class)); + + withPeer( + peer(NAMESPACE), + () -> + assertThat(guard.requireGameSessionOwnerReadCaller().accountBinding().namespace()) + .isEqualTo(NAMESPACE)); + } + + @Test + void rejectsDisabledMismatchedAndSessionContextCallers() { + var enabled = guard(NAMESPACE); + var disabled = + new AccountJwtReadinessProbeOwnerWorkloadGuard( + Optional::empty, () -> apiBinding(NAMESPACE), NAMESPACE); + withPeer( + peer(NAMESPACE), + () -> + assertThatThrownBy(disabled::requireGameSessionOwnerReadCaller) + .isInstanceOf( + AccountJwtReadinessProbeOwnerWorkloadGuard.OwnerReadDeniedException.class)); + + var localMismatch = guard("other"); + withPeer( + peer(NAMESPACE), + () -> + assertThatThrownBy(localMismatch::requireGameSessionOwnerReadCaller) + .isInstanceOf( + AccountJwtReadinessProbeOwnerWorkloadGuard.OwnerReadDeniedException.class)); + + withPeer( + peer(NAMESPACE), + () -> { + SessionContext.setContext("authenticated-account", List.of(), java.util.Map.of()); + assertThatThrownBy(enabled::requireGameSessionOwnerReadCaller) + .isInstanceOf( + AccountJwtReadinessProbeOwnerWorkloadGuard.OwnerReadDeniedException.class); + }); + } + + private static AccountJwtReadinessProbeOwnerWorkloadGuard guard(String localNamespace) { + Binding binding = binding(NAMESPACE); + return new AccountJwtReadinessProbeOwnerWorkloadGuard( + () -> Optional.of(binding), () -> apiBinding(NAMESPACE), localNamespace); + } + + private static Binding binding(String namespace) { + String revision = "materializer-r1"; + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/jwt-signer-materializer"; + List pins = List.of("a".repeat(64)); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, "prod", "cluster-a", namespace, clusterUid, namespaceUid, expectedPeer, pins); + return new Binding( + "prod", + "cluster-a", + namespace, + clusterUid, + namespaceUid, + expectedPeer, + pins, + revision, + digest); + } + + private static AccountJwtJwksApiBinding.ParsedBinding apiBinding(String namespace) { + return new AccountJwtJwksApiBinding.ParsedBinding( + "api-r1", + "prod", + "cluster-a", + URI.create("https://kubernetes.example.test:6443"), + "kubernetes.example.test", + Path.of("protected").toAbsolutePath().resolve("ca.pem"), + "b".repeat(64), + Path.of("protected").toAbsolutePath().resolve("token"), + namespace, + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "system:serviceaccount:" + namespace + ":account-service", + "c".repeat(64)); + } + + private static GrpcPeerIdentity peer(String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", + namespace, + "game-session-service"); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.ROOT.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportCompositionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportCompositionTest.java new file mode 100644 index 0000000000..36771d13b8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportCompositionTest.java @@ -0,0 +1,138 @@ +package unit.net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.account.v1.AccountJwtReadinessPodReceiverServiceGrpc; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPrerequisiteConfiguration; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerConfiguration; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTransportConfiguration; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessGrpcReceiverInvocationPort; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessTransportOwner; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import net.firedevops.firemud.gamesession.v1.GameSessionJwtReadinessReceiverServiceGrpc; +import org.junit.jupiter.api.Test; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class AccountJwtReadinessTransportCompositionTest { + private static final String[] PROTECTED_READINESS_PROPERTIES = { + "firemud.account.jwt-readiness.validation.max-control-ui-tenant-scopes=256", + "firemud.account.jwt-jwks-api.enabled=true", + "firemud.account.jwt-jwks-api.protected-binding-path=/etc/firemud/account-jwt-api/binding.json", + "firemud.account.jwt-signer.materialization.enabled=true", + "firemud.account.jwt-signer.materialization.protected-binding-path=/etc/firemud/account-jwt-materializer/binding.json" + }; + + @Test + void realInvocationPortRequiresSslBundleAndProtectedWorkloadNamespace() { + protectedTransportRunner() + .withPropertyValues(PROTECTED_READINESS_PROPERTIES) + .withPropertyValues( + "firemud.account.jwt-readiness.validation.enabled=true", + "firemud.grpc.workload-namespace=firemud-prod") + .withBean(SslBundles.class, () -> mock(SslBundles.class)) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(AccountJwtReadinessReceiverInvocationPort.class)) + .isExactlyInstanceOf(AccountJwtReadinessGrpcReceiverInvocationPort.class); + }); + + protectedTransportRunner() + .withPropertyValues(PROTECTED_READINESS_PROPERTIES) + .withPropertyValues( + "firemud.account.jwt-readiness.validation.enabled=true", + "firemud.grpc.workload-namespace=firemud-prod") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertDefaultDenied(context.getBean(AccountJwtReadinessReceiverInvocationPort.class)); + }); + + protectedTransportRunner() + .withPropertyValues(PROTECTED_READINESS_PROPERTIES) + .withPropertyValues("firemud.account.jwt-readiness.validation.enabled=true") + .withBean(SslBundles.class, () -> mock(SslBundles.class)) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessReceiverInvocationPort")) + .isFalse(); + }); + + protectedTransportRunner() + .withPropertyValues(PROTECTED_READINESS_PROPERTIES) + .withPropertyValues("firemud.grpc.workload-namespace=firemud-prod") + .withBean(SslBundles.class, () -> mock(SslBundles.class)) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessReceiverInvocationPort")) + .isFalse(); + }); + } + + @Test + void ownerReadAndCallerCompositionShareOneProbeGraphAndKeepReceiverApisDistinct() { + protectedTransportRunner() + .withUserConfiguration(AccountJwtReadinessProbeOwnerConfiguration.class) + .withPropertyValues(PROTECTED_READINESS_PROPERTIES) + .withPropertyValues( + "firemud.account.jwt-readiness.validation.enabled=true", + "firemud.account.jwt-readiness.probe-owner.enabled=true", + "firemud.grpc.workload-namespace=firemud-prod") + .withBean(SslBundles.class, () -> mock(SslBundles.class)) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBeansOfType(AccountJwtReadinessProbeService.class)).hasSize(1); + assertThat(context.getBeansOfType(AccountJwtValidatorInventorySource.class)) + .hasSize(1); + assertThat(context.getBean(AccountJwtReadinessReceiverInvocationPort.class)) + .isExactlyInstanceOf(AccountJwtReadinessGrpcReceiverInvocationPort.class); + assertThat(context.getBean(AccountJwtReadinessProbeOwnerService.class)).isNotNull(); + assertThat(context.getBean(AccountJwtReadinessTransportOwner.class)).isNotNull(); + }); + + assertThat( + AccountJwtReadinessPodReceiverServiceGrpc.getReceiveReadinessProbeMethod() + .getFullMethodName()) + .isEqualTo("account.v1.AccountJwtReadinessPodReceiverService/ReceiveReadinessProbe"); + assertThat( + GameSessionJwtReadinessReceiverServiceGrpc.getReceiveReadinessProbeMethod() + .getFullMethodName()) + .isEqualTo("game_session.v1.GameSessionJwtReadinessReceiverService/ReceiveReadinessProbe"); + assertThat( + AccountJwtReadinessPodReceiverServiceGrpc.getReceiveReadinessProbeMethod() + .getFullMethodName()) + .isNotEqualTo( + GameSessionJwtReadinessReceiverServiceGrpc.getReceiveReadinessProbeMethod() + .getFullMethodName()); + } + + private static ApplicationContextRunner protectedTransportRunner() { + return new ApplicationContextRunner() + .withUserConfiguration( + AccountJwtReadinessPrerequisiteConfiguration.class, + AccountJwtReadinessTransportConfiguration.class, + AccountJwtReadinessTestDependencies.class); + } + + private static void assertDefaultDenied(AccountJwtReadinessReceiverInvocationPort port) { + assertThat(port).isNotInstanceOf(AccountJwtReadinessGrpcReceiverInvocationPort.class); + assertThatThrownBy(port::requireAvailable) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class) + .hasNoCause(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportConfigurationTest.java new file mode 100644 index 0000000000..2ba503e1ca --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTransportConfigurationTest.java @@ -0,0 +1,269 @@ +package unit.net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPrerequisiteConfiguration; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerConfiguration; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTransportConfiguration; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessTransportOwner; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessValidationService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.assertj.AssertableApplicationContext; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.transaction.PlatformTransactionManager; + +class AccountJwtReadinessTransportConfigurationTest { + private final ApplicationContextRunner contextRunner = + new ApplicationContextRunner() + .withUserConfiguration( + AccountJwtReadinessPrerequisiteConfiguration.class, + AccountJwtReadinessTransportConfiguration.class); + + @Test + void readinessTransportIsAbsentWhenTheOptInIsMissingOrProtectedCompositionIsIncomplete() { + contextRunner.run( + context -> { + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessProbeService")) + .isFalse(); + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessTransportOwner")) + .isFalse(); + }); + + contextRunner + .withPropertyValues("firemud.account.jwt-readiness.validation.enabled=true") + .run( + context -> { + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessProbeService")) + .isFalse(); + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessTransportOwner")) + .isFalse(); + }); + } + + @Test + void probeOwnerCompositionIsIndependentlyDefaultDeniedAndExplicitlyOptIn() { + new ApplicationContextRunner() + .withUserConfiguration(AccountJwtReadinessProbeOwnerConfiguration.class) + .run( + context -> { + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessProbeOwnerService")) + .isFalse(); + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessProbeOwnerWorkloadGuard")) + .isFalse(); + }); + + new ApplicationContextRunner() + .withUserConfiguration( + AccountJwtReadinessPrerequisiteConfiguration.class, + AccountJwtReadinessProbeOwnerConfiguration.class) + .withPropertyValues( + "firemud.account.jwt-readiness.probe-owner.enabled=true", + "firemud.account.jwt-jwks-api.enabled=true", + "firemud.account.jwt-jwks-api.protected-binding-path=/etc/firemud/account-jwt-api/binding.json", + "firemud.account.jwt-signer.materialization.enabled=true", + "firemud.account.jwt-signer.materialization.protected-binding-path=/etc/firemud/account-jwt-materializer/binding.json", + "firemud.grpc.workload-namespace=firemud-prod") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessProbeOwnerService")) + .isTrue(); + assertThat( + context + .getBeanFactory() + .getBeanDefinition("accountJwtReadinessProbeOwnerService") + .isLazyInit()) + .isTrue(); + }); + } + + @Test + void completeExplicitReadinessCompositionInstantiatesLazyCallableOwnerGraphWithoutActivation() { + contextRunner + .withUserConfiguration(AccountJwtReadinessTestDependencies.class) + .withPropertyValues( + "firemud.account.jwt-readiness.validation.enabled=true", + "firemud.account.jwt-readiness.validation.max-control-ui-tenant-scopes=256", + "firemud.account.jwt-jwks-api.enabled=true", + "firemud.account.jwt-jwks-api.protected-binding-path=/etc/firemud/account-jwt-api/binding.json", + "firemud.account.jwt-signer.materialization.enabled=true", + "firemud.account.jwt-signer.materialization.protected-binding-path=/etc/firemud/account-jwt-materializer/binding.json", + "firemud.grpc.workload-namespace=firemud-prod") + .run( + context -> { + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessProbeService")) + .isTrue(); + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessTransportOwner")) + .isTrue(); + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtValidatorInventorySource")) + .isTrue(); + assertThat( + context + .getBeanFactory() + .containsBeanDefinition("accountJwtReadinessReceiverInvocationPort")) + .isTrue(); + assertThat( + context + .getBeanFactory() + .getBeanDefinition("accountJwtReadinessProbeService") + .isLazyInit()) + .isTrue(); + assertThat( + context + .getBeanFactory() + .getBeanDefinition("accountJwtReadinessTransportOwner") + .isLazyInit()) + .isTrue(); + + AccountJwtReadinessTestAssertions.assertActualGraphWithoutActivation(context); + }); + } +} + +@Configuration(proxyBeanMethods = false) +@Import(AccountJwtReadinessValidationService.class) +class AccountJwtReadinessTestDependencies { + private static final AccountPublicJwksCache.SourceIdentity SOURCE_IDENTITY = + new AccountPublicJwksCache.SourceIdentity( + "prod", + "prod-cluster-1", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "api-r1", + "https://kubernetes.example:6443", + "a".repeat(64)); + + @Bean + AccountJwtReadinessProbeRepository accountJwtReadinessProbeRepository() { + return mock(AccountJwtReadinessProbeRepository.class); + } + + @Bean + AccountJwtReadinessTrustBinding accountJwtReadinessTrustBinding() { + return mock(AccountJwtReadinessTrustBinding.class); + } + + @Bean + AccountJwtSignerMaterializerTrustBinding accountJwtSignerMaterializerTrustBinding() { + return mock(AccountJwtSignerMaterializerTrustBinding.class); + } + + @Bean + @Primary + AccountJwtJwksTrustedSource readinessTestTrustedJwksSource() { + AccountJwtJwksTrustedSource source = mock(AccountJwtJwksTrustedSource.class); + when(source.sourceIdentity()).thenReturn(SOURCE_IDENTITY); + return source; + } + + @Bean + PlatformTransactionManager readinessTestTransactionManager() { + return mock(PlatformTransactionManager.class); + } +} + +final class AccountJwtReadinessTestAssertions { + private AccountJwtReadinessTestAssertions() {} + + static void assertActualGraphWithoutActivation(AssertableApplicationContext context) { + var beanFactory = context.getBeanFactory(); + assertThat(beanFactory.containsSingleton("accountJwtReadinessProbeService")).isFalse(); + assertThat(beanFactory.containsSingleton("accountJwtReadinessTransportOwner")).isFalse(); + + assertThat(context.getBean(AccountJwtReadinessValidationService.class)) + .isExactlyInstanceOf(AccountJwtReadinessValidationService.class); + assertThat(context.getBean(AccountJwtReadinessProbeService.class)) + .isExactlyInstanceOf(AccountJwtReadinessProbeService.class); + assertThat(context.getBean(AccountJwtReadinessTransportOwner.class)) + .isExactlyInstanceOf(AccountJwtReadinessTransportOwner.class); + assertThatThrownBy( + () -> context.getBean(AccountJwtReadinessReceiverInvocationPort.class).invoke(null)) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class) + .hasNoCause(); + assertThatThrownBy( + () -> + context.getBean(AccountJwtReadinessReceiverInvocationPort.class).requireAvailable()) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class) + .hasNoCause(); + assertThat(context.getBean(AccountJwtValidatorInventorySource.class)) + .isExactlyInstanceOf(AccountJwtValidatorInventorySource.class); + + assertThat(beanFactory.containsSingleton("accountJwtReadinessProbeService")).isTrue(); + assertThat(beanFactory.containsSingleton("accountJwtReadinessTransportOwner")).isTrue(); + assertThat(beanFactory.containsSingleton("accountJwtReadinessJwksApiBinding")).isTrue(); + assertThat(beanFactory.containsSingleton("accountJwtReadinessJwksConfigMapClient")).isFalse(); + assertThat(beanFactory.containsSingleton("accountJwtReadinessTrustedJwksSource")).isFalse(); + assertThat( + beanFactory.containsSingleton( + "accountCanonicalGameplayLoginCoordinationConnectionProvider")) + .isFalse(); + assertThat(beanFactory.containsSingleton("accountCanonicalGameplayLoginRedisClient")).isFalse(); + assertThat(beanFactory.containsSingleton("accountCanonicalGameplayLoginSigner")).isFalse(); + + AccountJwtReadinessProbeRepository repository = + context.getBean(AccountJwtReadinessProbeRepository.class); + AccountJwtReadinessTrustBinding readinessTrustBinding = + context.getBean(AccountJwtReadinessTrustBinding.class); + AccountJwtSignerMaterializerTrustBinding signerTrustBinding = + context.getBean(AccountJwtSignerMaterializerTrustBinding.class); + AccountJwtJwksTrustedSource trustedJwksSource = + context.getBean(AccountJwtJwksTrustedSource.class); + PlatformTransactionManager transactionManager = + context.getBean(PlatformTransactionManager.class); + + verifyNoInteractions(repository, readinessTrustBinding, signerTrustBinding, transactionManager); + verify(trustedJwksSource, times(1)).sourceIdentity(); + verify(trustedJwksSource, never()).load(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBindingTest.java new file mode 100644 index 0000000000..270b9a6c9b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBindingTest.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.List; +import org.junit.jupiter.api.Test; + +class AccountJwtReadinessTrustBindingTest { + private static final long NOW = 1_800_000_000L; + + @Test + void missingOrDisabledConfigurationNeverCreatesReadinessTrust() { + assertThat(new AccountJwtReadinessTrustBinding(false, "/unused", Clock.systemUTC()).current()) + .isEmpty(); + assertThat(new AccountJwtReadinessTrustBinding(true, "", Clock.systemUTC()).current()) + .isEmpty(); + } + + @Test + void strictBindingPinsAccountRuntimeAndDedicatedHarnessIdentity() { + var binding = + AccountJwtReadinessTrustBinding.parseProtectedBytes( + protectedConfig(NOW + 60).getBytes(StandardCharsets.UTF_8), NOW); + + assertThat(binding.environmentId()).isEqualTo("prod"); + assertThat(binding.clusterId()).isEqualTo("prod-cluster-1"); + assertThat(binding.namespace()).isEqualTo("firemud-prod"); + assertThat(binding.expectedPeerUri()) + .isEqualTo("spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"); + assertThat(binding.validatorId()).isEqualTo("account-service"); + assertThat(binding.validatorInstanceId()).isEqualTo("account-validator-instance-7"); + assertThat(binding.validUntilEpochSecond()).isEqualTo(NOW + 60); + assertThat(binding.isCurrentAt(NOW)).isTrue(); + assertThat(binding.isCurrentAt(NOW + 60)).isFalse(); + } + + @Test + void missingExpiredDuplicateUnknownAndChangedIdentityBindingsAreRejected() { + String valid = protectedConfig(NOW + 60); + assertThatThrownBy( + () -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + valid.getBytes(StandardCharsets.UTF_8), NOW + 60)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + (valid + "validatorInstanceId=other\n").getBytes(StandardCharsets.UTF_8), NOW)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + (valid + "untrusted=true\n").getBytes(StandardCharsets.UTF_8), NOW)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + valid + .replace( + "validatorInstanceId=account-validator-instance-7", + "validatorInstanceId=other") + .getBytes(StandardCharsets.UTF_8), + NOW)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + valid.replace("enabled=true", "enabled=false").getBytes(StandardCharsets.UTF_8), + NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static String protectedConfig(long validUntil) { + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + String uri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"; + List pins = List.of("a".repeat(64)); + String digest = + AccountJwtReadinessTrustBinding.computeBindingDigest( + "revision-7", + "prod", + "prod-cluster-1", + "firemud-prod", + clusterUid, + namespaceUid, + uri, + pins, + "account-validator-instance-7", + validUntil); + return "enabled=true\n" + + "configRevision=revision-7\n" + + "environmentId=prod\n" + + "clusterId=prod-cluster-1\n" + + "namespace=firemud-prod\n" + + "expectedClusterIncarnationUid=" + + clusterUid + + "\n" + + "expectedNamespaceUid=" + + namespaceUid + + "\n" + + "expectedPeerUri=" + + uri + + "\n" + + "peerSpkiSha256Pins=" + + String.join(",", pins) + + "\n" + + "validatorId=account-service\n" + + "validatorInstanceId=account-validator-instance-7\n" + + "validUntilEpochSecond=" + + validUntil + + "\n" + + "bindingDigest=" + + digest + + "\n"; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfigurationTest.java new file mode 100644 index 0000000000..3f9313a4af --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerBootstrapConfigurationTest.java @@ -0,0 +1,21 @@ +package unit.net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import net.firedevops.firemud.accountservice.config.AccountJwtSignerBootstrapConfiguration; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class AccountJwtSignerBootstrapConfigurationTest { + @Test + void bootstrapCoordinatorIsNotComposedByDefault() { + new ApplicationContextRunner() + .withUserConfiguration(AccountJwtSignerBootstrapConfiguration.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(AccountJwtSignerBootstrapCoordinator.class); + }); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBindingTest.java new file mode 100644 index 0000000000..9a9907c304 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBindingTest.java @@ -0,0 +1,293 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProtectedInventory; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtValidatorInventoryBindingTest { + private static final String API_DIGEST = "a".repeat(64); + private static final String IMAGE = "registry.example/firemud/player@sha256:" + "b".repeat(64); + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String DEPLOYMENT_UID = "33333333-3333-4333-8333-333333333333"; + private static final String POD_UID_ONE = "44444444-4444-4444-8444-444444444444"; + private static final String POD_UID_TWO = "55555555-5555-4555-8555-555555555555"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void defaultBindingIsInactiveWithoutReadingFilesystem() { + assertThat(new AccountJwtValidatorInventoryBinding().current()).isEmpty(); + } + + @Test + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = "Canonical protected mount paths are fixed inputs for this binding proof") + void parsesOnlyCompletePinnedRs256ApplicabilityAndProducesCanonicalRuntimeConfig() { + ProtectedInventory inventory = + AccountJwtValidatorInventoryBinding.parseProtectedBytes(validBindingBytes()); + + assertThat(inventory.environmentId()).isEqualTo("test"); + assertThat(inventory.clusterId()).isEqualTo("cluster-test"); + assertThat(inventory.namespace()).isEqualTo("firemud-test"); + assertThat(inventory.expectedClusterIncarnationUid()).isEqualTo(CLUSTER_UID); + assertThat(inventory.expectedNamespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(inventory.validators()).hasSize(1); + var validator = inventory.validators().get(0); + assertThat(validator.deploymentUid()).isEqualTo(DEPLOYMENT_UID); + assertThat(validator.image()).isEqualTo(IMAGE); + assertThat(validator.receiverServiceUri()) + .isEqualTo("spiffe://firemud/ns/firemud-test/sa/player-service"); + assertThat(validator.receiverPort()).isEqualTo(8443); + assertThat(validator.receiverPods()).hasSize(2); + assertThat(validator.canonicalRuntimeConfig()) + .contains("\"algorithm\":\"RS256\"") + .contains("\"maxCacheAgeSeconds\":60") + .contains("\"jwksUri\":\"https://account-api.test/.well-known/jwks.json\""); + + ParsedBinding matchingApi = + new ParsedBinding( + "api-r1", + "test", + "cluster-test", + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + Path.of("/etc/firemud/account-jwt-api/serving-ca.pem"), + "c".repeat(64), + Path.of("/var/run/secrets/firemud/account-jwt-api-token/token"), + "firemud-test", + CLUSTER_UID, + NAMESPACE_UID, + "system:serviceaccount:firemud-test:account-service", + API_DIGEST); + assertThat(inventory.matchesApiBinding(matchingApi)).isTrue(); + assertThat(inventory.matchesApiBinding(null)).isFalse(); + } + + @Test + void rejectsDigestTamperingUnknownFieldsAndUnpinnedImage() throws Exception { + byte[] valid = validBindingBytes(); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + new String(valid, StandardCharsets.UTF_8) + .replace("cluster-test", "other-cluster") + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalStateException.class); + + Map withUnknown = parseMap(valid); + withUnknown.put("ambientTrust", true); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(withUnknown))) + .isInstanceOf(IllegalStateException.class); + + byte[] unpinnedImage = validBindingBytes("registry.example/firemud/player:latest"); + assertThatThrownBy(() -> AccountJwtValidatorInventoryBinding.parseProtectedBytes(unpinnedImage)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void rejectsNonHttpsOrNonCanonicalJwksUri() { + byte[] malformed = validBindingBytes("http://account-api.test/.well-known/jwks.json", IMAGE); + assertThatThrownBy(() -> AccountJwtValidatorInventoryBinding.parseProtectedBytes(malformed)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void rejectsUnsortedDuplicateAndNoncanonicalPodIdentityPins() throws Exception { + Map unsorted = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map validator = + (Map) ((List) unsorted.get("validators")).get(0); + List pins = (List) validator.get("receiverPods"); + validator.put("receiverPods", List.of(pins.get(1), pins.get(0))); + rebindDigest(unsorted); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(unsorted))) + .isInstanceOf(IllegalStateException.class); + + Map noncanonicalIp = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map noncanonicalValidator = + (Map) ((List) noncanonicalIp.get("validators")).get(0); + @SuppressWarnings("unchecked") + Map firstPin = + (Map) ((List) noncanonicalValidator.get("receiverPods")).get(0); + firstPin.put("podIp", "010.0.0.10"); + rebindDigest(noncanonicalIp); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(noncanonicalIp))) + .isInstanceOf(IllegalStateException.class); + + Map uppercaseSpki = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map uppercaseValidator = + (Map) ((List) uppercaseSpki.get("validators")).get(0); + @SuppressWarnings("unchecked") + Map secondPin = + (Map) ((List) uppercaseValidator.get("receiverPods")).get(1); + secondPin.put("leafSpkiSha256", "D".repeat(64)); + rebindDigest(uppercaseSpki); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(uppercaseSpki))) + .isInstanceOf(IllegalStateException.class); + + Map sharedPodKey = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map sharedKeyValidator = + (Map) ((List) sharedPodKey.get("validators")).get(0); + @SuppressWarnings("unchecked") + List> sharedKeyPins = + (List>) sharedKeyValidator.get("receiverPods"); + sharedKeyPins.get(1).put("leafSpkiSha256", sharedKeyPins.get(0).get("leafSpkiSha256")); + rebindDigest(sharedPodKey); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(sharedPodKey))) + .isInstanceOf(IllegalStateException.class); + + Map canonicalIpv6 = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map ipv6Validator = + (Map) ((List) canonicalIpv6.get("validators")).get(0); + @SuppressWarnings("unchecked") + Map ipv6Pin = + (Map) ((List) ipv6Validator.get("receiverPods")).get(0); + ipv6Pin.put("podIp", "2001:db8::1"); + rebindDigest(canonicalIpv6); + assertThat( + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(canonicalIpv6)) + .validators() + .get(0) + .receiverPods() + .get(0) + .podIp()) + .isEqualTo("2001:db8::1"); + + ipv6Pin.put("podIp", "2001:0db8:0:0:0:0:0:1"); + rebindDigest(canonicalIpv6); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(canonicalIpv6))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void rejectsOnePodLeafKeyPinnedToDifferentValidatorPods() throws Exception { + Map sharedIdentity = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map firstValidator = + (Map) ((List) sharedIdentity.get("validators")).get(0); + Map secondValidator = new LinkedHashMap<>(firstValidator); + secondValidator.put("validatorId", "other-service"); + secondValidator.put("deploymentName", "other-service"); + secondValidator.put("deploymentUid", "66666666-6666-4666-8666-666666666666"); + secondValidator.put("selector", Map.of("app", "other-service")); + secondValidator.put("containerName", "other-service"); + secondValidator.put("receiverServiceUri", "spiffe://firemud/ns/firemud-test/sa/other-service"); + @SuppressWarnings("unchecked") + List> firstPins = + (List>) firstValidator.get("receiverPods"); + Map otherFirstPin = new LinkedHashMap<>(firstPins.get(0)); + otherFirstPin.put("podUid", "77777777-7777-4777-8777-777777777777"); + otherFirstPin.put("podIp", "10.0.1.10"); + Map otherSecondPin = new LinkedHashMap<>(firstPins.get(1)); + otherSecondPin.put("podUid", "88888888-8888-4888-8888-888888888888"); + otherSecondPin.put("podIp", "10.0.1.11"); + secondValidator.put("receiverPods", List.of(otherFirstPin, otherSecondPin)); + sharedIdentity.put("validators", List.of(firstValidator, secondValidator)); + rebindDigest(sharedIdentity); + + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(sharedIdentity))) + .isInstanceOf(IllegalStateException.class); + } + + private static byte[] validBindingBytes() { + return validBindingBytes("https://account-api.test/.well-known/jwks.json", IMAGE); + } + + private static byte[] validBindingBytes(String image) { + return validBindingBytes("https://account-api.test/.well-known/jwks.json", image); + } + + private static byte[] validBindingBytes(String jwksUri, String image) { + Map profile = + Map.of("tokenProfile", "game-session-account-delegation", "audience", "account-service"); + Map validator = new LinkedHashMap<>(); + validator.put("validatorId", "player-service"); + validator.put("deploymentName", "player-service"); + validator.put("deploymentUid", DEPLOYMENT_UID); + validator.put("selector", Map.of("app", "player-service")); + validator.put("replicas", 2); + validator.put("containerName", "player-service"); + validator.put("image", image); + validator.put("jwksUri", jwksUri); + validator.put("maxCacheAgeSeconds", 60); + validator.put("profiles", List.of(profile)); + validator.put("receiverServiceUri", "spiffe://firemud/ns/firemud-test/sa/player-service"); + validator.put("receiverPort", 8443); + validator.put( + "receiverPods", + List.of( + Map.of("podUid", POD_UID_ONE, "podIp", "10.0.0.10", "leafSpkiSha256", "c".repeat(64)), + Map.of("podUid", POD_UID_TWO, "podIp", "10.0.0.11", "leafSpkiSha256", "d".repeat(64)))); + Map root = new LinkedHashMap<>(); + root.put("version", "account-jwt-validator-inventory-binding/v2"); + root.put("enabled", "true"); + root.put("configRevision", "inventory-r1"); + root.put("environmentId", "test"); + root.put("clusterId", "cluster-test"); + root.put("namespace", "firemud-test"); + root.put("expectedClusterIncarnationUid", CLUSTER_UID); + root.put("expectedNamespaceUid", NAMESPACE_UID); + root.put("apiBindingRevision", "api-r1"); + root.put("apiBindingDigest", API_DIGEST); + root.put("validators", List.of(validator)); + root.put("bindingDigest", "0".repeat(64)); + try { + JsonNode unsigned = JSON.readTree(JSON.writeValueAsBytes(root)); + root.put("bindingDigest", AccountJwtValidatorInventoryBinding.computeBindingDigest(unsigned)); + return JSON.writeValueAsBytes(root); + } catch (Exception failure) { + throw new AssertionError(failure); + } + } + + private static void rebindDigest(Map root) throws Exception { + root.put("bindingDigest", "0".repeat(64)); + JsonNode unsigned = JSON.readTree(JSON.writeValueAsBytes(root)); + root.put("bindingDigest", AccountJwtValidatorInventoryBinding.computeBindingDigest(unsigned)); + } + + @SuppressWarnings("unchecked") + private static Map parseMap(byte[] value) throws Exception { + JsonNode root = JSON.readTree(value); + return JSON.readValue(JSON.writeValueAsBytes(root), Map.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java new file mode 100644 index 0000000000..572598164b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java @@ -0,0 +1,226 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.MountObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJwtJwksPublicationRepositoryTest { + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "trust-r1"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String JWKS = "{\"keys\":[]}"; + private static final String MARKER = "{\"phase\":\"PREPUBLISHED\"}"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void currentReadsRemainMandatoryAccountTransactions() throws Exception { + assertMandatory("readCurrentIntent", Binding.class, TrustFence.class); + assertMandatory("readCurrentPublication", Binding.class, TrustFence.class); + assertMandatory( + "recordPrepublicationIntent", + Binding.class, + TrustFence.class, + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .GenerationResult.class, + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .GenerationRequest.class, + String.class, + String.class, + String.class, + String.class, + String.class, + String.class, + String.class); + } + + @Test + void publicationRepositoryRejectsCallsOutsideAnOwningAccountTransaction() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository repository = + new AccountJwtJwksPublicationRepository(dsl, desired); + + assertThatThrownBy(() -> repository.readCurrentIntent(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owning Account transaction"); + + verifyNoInteractions(dsl, desired); + } + + @Test + void snapshotAndPublicDataDigestsBindEveryObservedPublicByte() { + String first = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", JWKS, "other.txt", "preserve")); + String sameDifferentOrder = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("other.txt", "preserve", "jwks.json", JWKS)); + String changed = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", JWKS, "other.txt", "changed")); + + assertThat(first).hasSize(64).isEqualTo(sameDifferentOrder).isNotEqualTo(changed); + assertThat(AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER)) + .isNotEqualTo(AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER + " ")); + } + + @Test + void immutableEvidenceDigestsBindIntentReceiptAndMountedCorrespondence() { + PrepublicationIntent intent = intent(); + PublicationReceipt receipt = PublicationReceipt.create(intent, "42"); + MountObservation observation = MountObservation.create(intent, receipt); + + assertThat(intent.intentDigest()).isEqualTo(PrepublicationIntent.digest(intent)); + assertThat(receipt.receiptDigest()).isEqualTo(PublicationReceipt.digest(receipt)); + assertThat(observation.observationDigest()).isEqualTo(MountObservation.digest(observation)); + assertThat(observation.publicationReceiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(intent.jwksJson()).doesNotContain("privateKey", "\"d\""); + } + + @Test + void immutableEvidenceRejectsChangedDigestAndNonAdvancingRemoteReadback() { + PrepublicationIntent intent = intent(); + + assertThatThrownBy( + () -> + new PrepublicationIntent( + intent.operationId(), + intent.binding(), + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + intent.trustFence(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + intent.configMapName(), + intent.configMapUid(), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + intent.targetGeneration(), + intent.targetKid(), + intent.publicKeyFingerprint(), + intent.expectedDurableActive(), + intent.expectedPublishedActive(), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + "f".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intent digest"); + + assertThatThrownBy( + () -> + new PrepublicationIntent( + intent.operationId(), + intent.binding(), + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + intent.trustFence(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + intent.configMapName(), + intent.configMapUid(), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + intent.targetGeneration(), + intent.targetKid(), + intent.publicKeyFingerprint(), + intent.expectedDurableActive(), + intent.expectedPublishedActive(), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intent digest"); + + assertThatThrownBy(() -> PublicationReceipt.create(intent, intent.expectedResourceVersion())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("resourceVersion did not advance"); + } + + private static PrepublicationIntent intent() { + return PrepublicationIntent.create( + OPERATION_ID, + BINDING, + "b".repeat(64), + "c".repeat(64), + "d".repeat(64), + 2L, + TRUST, + "e".repeat(64), + "api-r1", + "jwt-jwks", + "44444444-4444-4444-8444-444444444444", + "41", + "f".repeat(64), + "1", + "jwt-1-test", + "9".repeat(64), + Optional.empty(), + Optional.empty(), + JWKS, + MARKER, + AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER), + sha256(MARKER)); + } + + private static String sha256(String value) { + try { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (Exception ex) { + throw new IllegalStateException(ex); + } + } + + private static void assertMandatory(String method, Class... parameterTypes) throws Exception { + Transactional transactional = + AccountJwtJwksPublicationRepository.class + .getMethod(method, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java new file mode 100644 index 0000000000..281daec872 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJwtReadinessProbeRepositoryTest { + private static final Binding BINDING = + new Binding( + "staging", "cluster-a", "firemud", CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "trust-r1"); + + @Test + void requiresAnOwningAccountTransactionBeforeReadingOtherAuthorities() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository publication = + mock(AccountJwtJwksPublicationRepository.class); + AccountJwtReadinessProbeRepository repository = + new AccountJwtReadinessProbeRepository(dsl, desired, publication); + + assertThatThrownBy(() -> repository.planCurrent(BINDING, TRUST, Instant.ofEpochSecond(10_000))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owning Account transaction"); + + verifyNoInteractions(dsl, desired, publication); + } + + @Test + void promotionProofReadsRequireWritableOwnerTransactionForLockedEvidence() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository publication = + mock(AccountJwtJwksPublicationRepository.class); + AccountJwtReadinessProbeRepository repository = + new AccountJwtReadinessProbeRepository(dsl, desired, publication); + UUID operationId = UUID.randomUUID(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy( + () -> repository.readCurrentPromotionPrerequisites(BINDING, TRUST, operationId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A writable Account transaction is required"); + assertThatThrownBy(() -> repository.readPromotionProof(BINDING, TRUST, operationId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A writable Account transaction is required"); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + verifyNoInteractions(dsl, desired, publication); + } + + @Test + void matrixIsCanonicalExplicitAndStillMarkedIncomplete() { + String matrix = AccountJwtReadinessProbeRepository.applicabilityMatrixJson(); + + assertThat(matrix) + .isEqualTo( + "{\"inventoryStatus\":\"PARTIAL_UNCONFIRMED\",\"schemaVersion\":1," + + "\"validators\":[{\"applicableProfiles\":[{\"audience\":\"control-ui\"," + + "\"tokenProfile\":\"control-ui\"},{\"audience\":\"player-bootstrap\"," + + "\"tokenProfile\":\"player-bootstrap\"},{\"audience\":\"account-service\"," + + "\"tokenProfile\":\"game-session-account-delegation\"}]," + + "\"validatorId\":\"account-service\"}]}"); + assertThat(matrix).doesNotContain("credential-authenticate-account"); + } + + @Test + void firstInstallFenceHasExactAbsentActiveAndPublishedPair() { + AccountJwtReadinessProbeRepository.SignerFence fence = + new AccountJwtReadinessProbeRepository.SignerFence(Optional.empty(), Optional.empty()); + + assertThat(fence.durableActive()).isEmpty(); + assertThat(fence.publishedActive()).isEmpty(); + assertThatThrownBy( + () -> + new AccountJwtReadinessProbeRepository.SignerFence( + Optional.empty(), + Optional.of( + new AccountJwtSignerDesiredStateRepository.ActiveSigner("1", "old-key")))) + .isInstanceOf(AccountJwtReadinessProbeRepository.QuarantinedStateException.class); + } + + @Test + void plannedFirstInstallEntryCarriesAnAbsentPreviousActiveFence() { + var entry = + new AccountJwtReadinessProbeRepository.ProbeEntry( + UUID.randomUUID(), + "a".repeat(64), + "account-service", + "game-session-account-delegation", + "account-service", + net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle + .ProbeKind.REPRESENTATIVE, + UUID.randomUUID(), + "1", + "first-key", + Optional.empty(), + 1, + 1, + 20_000, + 20_300, + AccountJwtReadinessProbeRepository.ProbeState.PLANNED, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); + + assertThat(entry.expectedActive()).isEmpty(); + assertThat(entry.state()).isEqualTo(AccountJwtReadinessProbeRepository.ProbeState.PLANNED); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java new file mode 100644 index 0000000000..cddf5dd5c5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java @@ -0,0 +1,748 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionPreparation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtSignerDesiredStateRepositoryTest { + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "binding-r1"); + private static final UUID SECRET_UID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final EnrollmentIdentity ENROLLMENT = + new EnrollmentIdentity( + TRUST.expectedClusterIncarnationUid(), + TRUST.expectedNamespaceUid(), + TRUST.bindingDigest(), + TRUST.configRevision(), + "b".repeat(64), + "api-r1", + "44444444-4444-4444-8444-444444444444", + "12", + "c".repeat(64)); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void durableGenerationEntryPointsRequireAnAccountTransaction() throws Exception { + assertMandatory("initialize", Binding.class, EnrollmentIdentity.class); + assertMandatory("read", Binding.class); + assertMandatory("ensureCurrentGenerationRequest", Binding.class, TrustFence.class); + assertMandatory("readCurrentGenerationRequest", Binding.class, TrustFence.class); + assertMandatory( + "recordSecretObservation", + Binding.class, + TrustFence.class, + UUID.class, + String.class, + String.class, + String.class); + assertMandatory( + "recordGenerationResult", + Binding.class, + TrustFence.class, + UUID.class, + String.class, + String.class, + String.class, + String.class, + String.class); + assertMandatoryWritable("readPreparedGenerationForRecovery", Binding.class, TrustFence.class); + assertMandatoryWritable( + "readAndMarkPreparedPromotionDispatched", Binding.class, TrustFence.class); + assertMandatoryWritable( + "readCurrentCommittedSigner", Binding.class, TrustFence.class, String.class, String.class); + assertMandatoryWritable( + "commitPreparedPromotion", + Binding.class, + TrustFence.class, + UUID.class, + ReadinessPromotionProof.class); + assertMandatoryWritable( + "prepareCurrentGeneration", + Binding.class, + TrustFence.class, + PromotionPreparation.class, + ReadinessPromotionProof.class); + } + + @Test + void promotionCommitRequiresOwnerCreatedReadinessProofBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + repository.commitPreparedPromotion( + BINDING, + TRUST, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + null))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("readiness proof"); + verifyNoInteractions(dsl); + } + + @Test + void lockedPromotionReadsRejectReadOnlyTransactionsBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy(() -> repository.readPreparedGenerationForRecovery(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); + assertThatThrownBy(() -> repository.readAndMarkPreparedPromotionDispatched(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void accountCreatesAndReplaysOnlyItsOwnBoundGenerationRequest() { + Conversation conversation = new Conversation(); + + GenerationRequest first = inWritableTransaction(conversation::ensureRequest); + GenerationRequest retry = inWritableTransaction(conversation::ensureRequest); + + assertThat(first).isEqualTo(retry); + assertThat(first.phase()).isEqualTo(GenerationPhase.OBSERVE_PRIVATE_SECRET); + assertThat(first.operationId().version()).isEqualTo(4); + assertThat(first.operationDigest()).hasSize(64); + assertThat(first.desiredStateVersion()).isEqualTo(2); + assertThat(first.targetGeneration()).isEqualTo("1"); + assertThat(first.targetKid()).startsWith("jwt-1-"); + assertThat(first.expectedActive()).isEmpty(); + assertThat(first.expectedPublishedActive()).isEmpty(); + assertThat(first.privateSecretName()).isEqualTo("jwt-signing-keys"); + assertThat(first.expectedSecretResourceVersion()).isEmpty(); + assertThat(first.publicKeyFingerprint()).isEmpty(); + assertThat(first.publicJwkJson()).isEmpty(); + assertThat(conversation.operationInsert).isNotNull(); + assertThat(conversation.executedStatements) + .anyMatch(sql -> sql.contains("account_jwt_signer_generation_operations")) + .anyMatch(sql -> sql.contains("generation_operation_id")) + .noneMatch(sql -> sql.contains("target_public_key_fingerprint")); + verify(conversation.dsl, times(2)).execute(anyString(), any(Object[].class)); + } + + @Test + void generationRequestDefensivelyCopiesItsValidatedPrivateSlots() { + Conversation conversation = new Conversation(); + GenerationRequest source = inWritableTransaction(conversation::ensureRequest); + List suppliedSlots = new ArrayList<>(source.allowedPrivateSlots()); + + GenerationRequest copied = + new GenerationRequest( + source.phase(), + source.operationId(), + source.operationDigest(), + source.generationRequestDigest(), + source.desiredStateVersion(), + source.binding(), + source.trustFence(), + source.privateSecretName(), + source.targetGeneration(), + source.targetKid(), + source.targetAlgorithm(), + source.operationAction(), + suppliedSlots, + source.expectedActive(), + source.expectedPublishedActive(), + source.secretUid(), + source.expectedSecretResourceVersion(), + source.generationReceiptDigest(), + source.publicKeyFingerprint(), + source.publicJwkJson(), + source.observedSecretResourceVersion()); + + suppliedSlots.clear(); + + assertThat(copied.allowedPrivateSlots()).containsExactly("pending"); + assertThatThrownBy(() -> copied.allowedPrivateSlots().add("current")) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void committedActiveSignerNeedsAnExplicitDurableRotationRequest() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + Map values = new HashMap<>(); + values.put("environment_id", BINDING.environmentId()); + values.put("cluster_id", BINDING.clusterId()); + values.put("kubernetes_namespace", BINDING.namespace()); + values.put("custody_mode", BINDING.mode().value()); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put( + "public_jwks_config_map_name", + AccountJwtSignerDesiredStateRepository.PUBLIC_JWKS_CONFIG_MAP_NAME); + values.put("record_version", 8L); + values.put("durable_active_generation", 4L); + values.put("durable_active_kid", "jwt-4-active"); + values.put("published_active_generation", 4L); + values.put("published_active_kid", "jwt-4-active"); + values.put("generation_operation_id", null); + values.put("prepared_operation_id", null); + values.put( + "enrollment_cluster_incarnation_uid", + UUID.fromString(TRUST.expectedClusterIncarnationUid())); + values.put("enrollment_namespace_uid", UUID.fromString(TRUST.expectedNamespaceUid())); + values.put("enrollment_materializer_binding_digest", TRUST.bindingDigest()); + values.put("enrollment_materializer_config_revision", TRUST.configRevision()); + values.put("enrollment_api_binding_digest", "b".repeat(64)); + values.put("enrollment_api_config_revision", "api-r1"); + values.put( + "enrollment_public_config_map_uid", + UUID.fromString("33333333-3333-4333-8333-333333333333")); + values.put("enrollment_public_config_map_resource_version", "12"); + values.put("enrollment_public_config_map_snapshot_digest", "c".repeat(64)); + Record activeState = record(values); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(activeState); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> repository.ensureCurrentGenerationRequest(BINDING, TRUST))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class) + .hasMessageContaining("durable rotation request"); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void secretObservationUnlocksOnlyTheExactGenerationFenceAndChangedReplayConflicts() { + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + GenerationRequest replay = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + + assertThat(pending.phase()).isEqualTo(GenerationPhase.GENERATE_PENDING); + assertThat(pending.generationRequestDigest()).hasSize(64); + assertThat(pending.secretUid()).isEqualTo(SECRET_UID.toString()); + assertThat(pending.expectedSecretResourceVersion()).isEqualTo("12"); + assertThat(pending.publicKeyFingerprint()).isEmpty(); + assertThat(replay).isEqualTo(pending); + int executedBeforeConflict = conversation.executedStatements.size(); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "changed-rv"))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); + assertThat(conversation.executedStatements).hasSize(executedBeforeConflict); + } + + @Test + void generationReceiptDerivesCanonicalRsaFingerprintAndRemainsNonPromoting() throws Exception { + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + PublicJwk jwk = publicJwk(operation.targetKid()); + + GenerationResult result = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + operation.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + GenerationResult replay = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + operation.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + + assertThat(result).isEqualTo(replay); + assertThat(result.publicKeyFingerprint()).isEqualTo(jwk.fingerprint()); + assertThat(result.expectedPriorResourceVersion()).isEqualTo("12"); + assertThat(result.observedResourceVersion()).isEqualTo("13"); + assertThat(result.publicJwkJson()).doesNotContain("\"d\""); + int executedBeforePromotionAttempt = conversation.executedStatements.size(); + PromotionPreparation callerSuppliedPreparation = + new PromotionPreparation( + result.operationId(), + result, + ENROLLMENT, + "b".repeat(64), + "api-r1", + "44444444-4444-4444-8444-444444444444", + "14", + "d".repeat(64), + "e".repeat(64), + "f".repeat(64), + "1".repeat(64), + "2".repeat(64), + "{\"keys\":[" + result.publicJwkJson() + "]}"); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.prepareCurrentGeneration( + BINDING, TRUST, callerSuppliedPreparation, null))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Account-verified readiness proof is required"); + assertThat(conversation.executedStatements).hasSize(executedBeforePromotionAttempt); + } + + @Test + void absentOperationAndWrongCurrentOperationFailBeforeAnyMutation() { + DSLContext emptyDsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository emptyRepository = + new AccountJwtSignerDesiredStateRepository(emptyDsl); + Record emptyState = stateRow(BINDING, 1, null, null, null, null, null); + when(emptyDsl.fetchOne(anyString(), any(Object[].class))).thenReturn(emptyState); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> emptyRepository.readCurrentGenerationRequest(BINDING, TRUST))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class); + verify(emptyDsl, never()).execute(anyString(), any(Object[].class)); + + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + UUID wrongOperation = UUID.fromString("55555555-5555-4555-8555-555555555555"); + int executedBeforeStaleCall = conversation.executedStatements.size(); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + wrongOperation, + operation.operationDigest(), + SECRET_UID.toString(), + "12"))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException.class); + assertThat(conversation.executedStatements).hasSize(executedBeforeStaleCall); + } + + @Test + void privateOrMalformedPublicJwkIsRejectedBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + repository.recordGenerationResult( + BINDING, + TRUST, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "a".repeat(64), + SECRET_UID.toString(), + "12", + "13", + "{\"d\":\"private\"}"))) + .isInstanceOf(IllegalArgumentException.class); + verify(dsl, never()).fetchOne(anyString(), any(Object[].class)); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void initializationStaysExplicitAndNonAuthorizing() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + Record initializedState = stateRow(BINDING, 1, null, null, null, null, null); + when(dsl.execute(anyString(), any(Object[].class))).thenReturn(1); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(initializedState); + + var state = inWritableTransaction(() -> repository.initialize(BINDING, ENROLLMENT)); + + assertThat(state.recordVersion()).isEqualTo(1); + assertThat(state.durableActive()).isEmpty(); + assertThat(state.publishedActive()).isEmpty(); + assertThat(state.generationOperationId()).isEmpty(); + assertThat(state.preparedOperationId()).isEmpty(); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bindings = ArgumentCaptor.forClass(Object[].class); + verify(dsl).execute(sql.capture(), bindings.capture()); + assertThat(sql.getValue()) + .contains("generation_operation_id") + .contains("prepared_operation_id"); + Object[] values = bindings.getValue(); + assertThat(values[4]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.expectedClusterIncarnationUid())); + assertThat(values[5]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.expectedNamespaceUid())); + assertThat(values[10]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.publicConfigMapUid())); + } + + private void assertMandatory(String methodName, Class... parameterTypes) + throws ReflectiveOperationException { + Transactional transactional = + AccountJwtSignerDesiredStateRepository.class + .getMethod(methodName, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + } + + private void assertMandatoryWritable(String methodName, Class... parameterTypes) + throws ReflectiveOperationException { + Transactional transactional = + AccountJwtSignerDesiredStateRepository.class + .getMethod(methodName, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat(transactional.readOnly()).isFalse(); + } + + private static Record stateRow( + Binding binding, + long version, + Long durableGeneration, + String durableKid, + Long publishedGeneration, + String publishedKid, + UUID generationOperationId) { + Map values = new HashMap<>(); + values.put("environment_id", binding.environmentId()); + values.put("cluster_id", binding.clusterId()); + values.put("kubernetes_namespace", binding.namespace()); + values.put("custody_mode", binding.mode().value()); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put( + "public_jwks_config_map_name", + AccountJwtSignerDesiredStateRepository.PUBLIC_JWKS_CONFIG_MAP_NAME); + values.put("record_version", version); + values.put("durable_active_generation", durableGeneration); + values.put("durable_active_kid", durableKid); + values.put("published_active_generation", publishedGeneration); + values.put("published_active_kid", publishedKid); + values.put("generation_operation_id", generationOperationId); + values.put("prepared_operation_id", null); + values.put( + "enrollment_cluster_incarnation_uid", + UUID.fromString(ENROLLMENT.expectedClusterIncarnationUid())); + values.put("enrollment_namespace_uid", UUID.fromString(ENROLLMENT.expectedNamespaceUid())); + values.put( + "enrollment_materializer_binding_digest", ENROLLMENT.materializerTrustBindingDigest()); + values.put( + "enrollment_materializer_config_revision", ENROLLMENT.materializerTrustConfigRevision()); + values.put("enrollment_api_binding_digest", ENROLLMENT.apiBindingDigest()); + values.put("enrollment_api_config_revision", ENROLLMENT.apiConfigRevision()); + values.put( + "enrollment_public_config_map_uid", UUID.fromString(ENROLLMENT.publicConfigMapUid())); + values.put( + "enrollment_public_config_map_resource_version", + ENROLLMENT.publicConfigMapResourceVersion()); + values.put( + "enrollment_public_config_map_snapshot_digest", ENROLLMENT.publicConfigMapSnapshotDigest()); + return record(values); + } + + private static Record generationOperationRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest_version", 1); + values.put("operation_digest", parameters[5]); + values.put("expected_record_version", parameters[6]); + values.put("expected_previous_generation", parameters[7]); + values.put("expected_previous_kid", parameters[8]); + values.put("expected_published_generation", parameters[9]); + values.put("expected_published_kid", parameters[10]); + values.put("target_generation", parameters[11]); + values.put("target_kid", parameters[12]); + values.put("target_algorithm", parameters[13]); + values.put("expected_cluster_incarnation_uid", parameters[14]); + values.put("expected_namespace_uid", parameters[15]); + values.put("trust_binding_digest", parameters[16]); + values.put("trust_config_revision", parameters[17]); + values.put("operation_action", "MATERIALIZE_PENDING"); + values.put("allowed_private_slots_canonical_bytes", parameters[18]); + return record(values); + } + + private static Record secretObservationRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest", parameters[5]); + values.put("expected_record_version", parameters[6]); + values.put("expected_cluster_incarnation_uid", parameters[7]); + values.put("expected_namespace_uid", parameters[8]); + values.put("trust_binding_digest", parameters[9]); + values.put("trust_config_revision", parameters[10]); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put("secret_uid", parameters[11]); + values.put("observed_resource_version", parameters[12]); + values.put("observation_digest", parameters[13]); + values.put("generation_request_digest", parameters[14]); + return record(values); + } + + private static Record generationResultRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest", parameters[5]); + values.put("generation_request_digest", parameters[6]); + values.put("desired_state_version", parameters[7]); + values.put("expected_cluster_incarnation_uid", parameters[8]); + values.put("expected_namespace_uid", parameters[9]); + values.put("trust_binding_digest", parameters[10]); + values.put("trust_config_revision", parameters[11]); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put("secret_uid", parameters[12]); + values.put("expected_prior_resource_version", parameters[13]); + values.put("observed_resource_version", parameters[14]); + values.put("target_generation", parameters[15]); + values.put("target_kid", parameters[16]); + values.put("target_algorithm", "RS256"); + values.put("public_key_fingerprint", parameters[17]); + values.put("public_jwk_json", parameters[18]); + values.put("receipt_digest", parameters[19]); + return record(values); + } + + private static PublicJwk publicJwk(String kid) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + RSAPublicKey key = (RSAPublicKey) generator.generateKeyPair().getPublic(); + String modulus = encodeUnsigned(key.getModulus()); + String exponent = encodeUnsigned(key.getPublicExponent()); + Map jwk = new java.util.TreeMap<>(); + jwk.put("alg", "RS256"); + jwk.put("e", exponent); + jwk.put("key_ops", List.of("verify")); + jwk.put("kid", kid); + jwk.put("kty", "RSA"); + jwk.put("n", modulus); + jwk.put("use", "sig"); + String json = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(jwk)), + StandardCharsets.UTF_8); + String fingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder() + .build() + .writeValueAsString( + Map.of("e", exponent, "kty", "RSA", "n", modulus))))); + return new PublicJwk(json, fingerprint); + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return java.util.Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static Record record(Map values) { + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(invocation -> values.get(invocation.getArgument(0))); + return row; + } + + private static T inWritableTransaction(java.util.function.Supplier operation) { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + try { + return operation.get(); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private record PublicJwk(String json, String fingerprint) {} + + private final class Conversation { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + private final List executedStatements = new java.util.ArrayList<>(); + private Object[] operationInsert; + private Object[] observationInsert; + private Object[] resultInsert; + private int stateReadCount; + + private Conversation() { + when(dsl.execute(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + Object[] arguments = invocation.getArguments(); + Object[] parameters = + arguments.length == 2 && arguments[1] instanceof Object[] bindings + ? bindings + : java.util.Arrays.copyOfRange(arguments, 1, arguments.length); + executedStatements.add(sql); + if (sql.contains("account_jwt_signer_generation_operations")) { + operationInsert = parameters.clone(); + } else if (sql.contains("account_jwt_signer_secret_observations")) { + observationInsert = parameters.clone(); + } else if (sql.contains("account_jwt_signer_generation_results")) { + resultInsert = parameters.clone(); + } + return 1; + }); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("account_jwt_signer_desired_states")) { + return stateReadCount++ == 0 + ? stateRow(BINDING, 1, null, null, null, null, null) + : stateRow( + BINDING, + 2, + null, + null, + null, + null, + operationInsert == null ? null : (UUID) operationInsert[0]); + } + if (sql.contains("account_jwt_signer_generation_operations")) { + return operationInsert == null ? null : generationOperationRow(operationInsert); + } + if (sql.contains("account_jwt_signer_generation_results")) { + return resultInsert == null ? null : generationResultRow(resultInsert); + } + if (sql.contains("account_jwt_signer_secret_observations")) { + return observationInsert == null ? null : secretObservationRow(observationInsert); + } + return null; + }); + } + + private GenerationRequest ensureRequest() { + return repository.ensureCurrentGenerationRequest(BINDING, TRUST); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepositoryTest.java new file mode 100644 index 0000000000..ba53cec177 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepositoryTest.java @@ -0,0 +1,169 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.HexFormat; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJwtValidatorInventoryRepositoryTest { + private static final Binding BINDING = + new Binding( + "staging", "cluster-a", "firemud", CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "trust-r1"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsUseOutsideAnOwningAccountTransactionWithoutDatabaseAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(dsl); + + assertThatThrownBy(() -> repository.persistOrReadback(snapshot("good"), BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owning Account transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsReadOnlyTransactionBeforeAnyInsert() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy(() -> repository.persistOrReadback(snapshot("good"), BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A writable Account transaction is required"); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsWrongClusterNamespaceOrIncarnationBeforeInsert() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy( + () -> repository.persistOrReadback(snapshot("other-cluster"), BINDING, TRUST)) + .isInstanceOf( + AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) + .hasNoCause(); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsCanonicalSnapshotBytesWhoseDigestDoesNotMatchBeforeInsert() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + InventorySnapshot candidate = snapshot("cluster-a"); + when(candidate.canonicalBytes()) + .thenReturn("{\"tampered\":true}".getBytes(StandardCharsets.UTF_8)); + + assertThatThrownBy(() -> repository.persistOrReadback(candidate, BINDING, TRUST)) + .isInstanceOf( + AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) + .hasNoCause(); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsSnapshotDigestMismatchAndReturnsDefensiveByteCopies() { + byte[] bytes = "{\"domain\":\"test\"}".getBytes(StandardCharsets.UTF_8); + String digest = sha256(bytes); + AccountJwtValidatorInventoryRepository.StoredSnapshot snapshot = + new AccountJwtValidatorInventoryRepository.StoredSnapshot( + digest, + "staging", + "cluster-a", + TRUST.expectedClusterIncarnationUid(), + "firemud", + TRUST.expectedNamespaceUid(), + "api-r1", + "b".repeat(64), + "inventory-r1", + "c".repeat(64), + Instant.parse("2026-10-05T00:00:00Z"), + bytes); + byte[] returned = snapshot.canonicalBytes(); + returned[2] = 'x'; + + assertThat(snapshot.canonicalBytes()).isEqualTo(bytes); + assertThatThrownBy( + () -> + new AccountJwtValidatorInventoryRepository.StoredSnapshot( + "d".repeat(64), + "staging", + "cluster-a", + TRUST.expectedClusterIncarnationUid(), + "firemud", + TRUST.expectedNamespaceUid(), + "api-r1", + "b".repeat(64), + "inventory-r1", + "c".repeat(64), + Instant.parse("2026-10-05T00:00:00Z"), + bytes)) + .isInstanceOf( + AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) + .hasNoCause(); + } + + private static InventorySnapshot snapshot(String clusterId) { + byte[] bytes = "{\"domain\":\"inventory\"}".getBytes(StandardCharsets.UTF_8); + InventorySnapshot snapshot = mock(InventorySnapshot.class); + when(snapshot.observedAt()).thenReturn(Instant.parse("2026-10-05T00:00:00Z")); + when(snapshot.environmentId()).thenReturn("staging"); + when(snapshot.clusterId()).thenReturn(clusterId); + when(snapshot.clusterIncarnationUid()).thenReturn(TRUST.expectedClusterIncarnationUid()); + when(snapshot.namespace()).thenReturn("firemud"); + when(snapshot.namespaceUid()).thenReturn(TRUST.expectedNamespaceUid()); + when(snapshot.apiBindingRevision()).thenReturn("api-r1"); + when(snapshot.apiBindingDigest()).thenReturn("b".repeat(64)); + when(snapshot.inventoryBindingRevision()).thenReturn("inventory-r1"); + when(snapshot.inventoryBindingDigest()).thenReturn("c".repeat(64)); + when(snapshot.canonicalBytes()).thenReturn(bytes); + when(snapshot.digest()).thenReturn(sha256(bytes)); + return snapshot; + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (Exception failure) { + throw new AssertionError(failure); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptorTest.java new file mode 100644 index 0000000000..8b2627ec38 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtReadinessTlsInterceptorTest.java @@ -0,0 +1,169 @@ +package net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class AccountJwtReadinessTlsInterceptorTest { + private static final String URI = + "spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"; + private static final byte[] MATCHING_SPKI = + "readiness harness leaf key".getBytes(StandardCharsets.US_ASCII); + + @Test + void absentTlsOrProtectedBindingIsDeniedBeforeTheHandler() { + Binding binding = binding(sha256(MATCHING_SPKI), "revision-1"); + assertDenied( + new AccountJwtReadinessTlsInterceptor(() -> Optional.of(binding)), Attributes.EMPTY); + assertDenied(new AccountJwtReadinessTlsInterceptor(Optional::empty), Attributes.EMPTY); + } + + @Test + void exactHarnessUriAndConfiguredSpkiPinEstablishOnlyAnInternalCallerContext() throws Exception { + Binding binding = binding(sha256(MATCHING_SPKI), "revision-1"); + AccountJwtReadinessTlsInterceptor interceptor = + new AccountJwtReadinessTlsInterceptor(() -> Optional.of(binding)); + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + @SuppressWarnings("unchecked") + ServerCallHandler next = mock(ServerCallHandler.class); + SSLSession session = mock(SSLSession.class); + java.security.cert.Certificate peer = cert(URI); + when(session.getPeerCertificates()).thenReturn(new java.security.cert.Certificate[] {peer}); + when(call.getAttributes()) + .thenReturn(Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build()); + AtomicReference captured = + new AtomicReference<>(); + ServerCall.Listener listener = + new ServerCall.Listener<>() { + @Override + public void onMessage(String message) { + captured.set(AccountJwtReadinessTlsInterceptor.authenticatedCaller()); + } + }; + when(next.startCall(any(), any())) + .thenAnswer( + invocation -> { + assertThat(AccountJwtReadinessTlsInterceptor.authenticatedCaller()).isNotNull(); + return listener; + }); + + ServerCall.Listener wrapped = interceptor.interceptCall(call, new Metadata(), next); + wrapped.onMessage("request"); + + assertThat(captured.get()).isNotNull(); + assertThat(captured.get().binding()).isEqualTo(binding); + assertThat(captured.get().peer().uri()).isEqualTo(URI); + assertThat(captured.get().peer().spkiSha256()).isEqualTo(sha256(MATCHING_SPKI)); + verify(call, never()).close(any(), any()); + } + + @Test + void wrongUriOrSpkiCannotUseHeaderOrRequestIdentityAsFallback() throws Exception { + Binding binding = binding(sha256(MATCHING_SPKI), "revision-1"); + assertDenied( + new AccountJwtReadinessTlsInterceptor(() -> Optional.of(binding)), + tlsAttributes(cert("spiffe://firemud/ns/other/sa/account-jwt-readiness-harness"))); + assertDenied( + new AccountJwtReadinessTlsInterceptor(() -> Optional.of(binding)), + tlsAttributes(cert(URI, "different readiness key".getBytes(StandardCharsets.US_ASCII)))); + } + + private static void assertDenied( + AccountJwtReadinessTlsInterceptor interceptor, Attributes attributes) { + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + @SuppressWarnings("unchecked") + ServerCallHandler next = mock(ServerCallHandler.class); + when(call.getAttributes()).thenReturn(attributes); + + interceptor.interceptCall(call, new Metadata(), next); + + ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); + verify(call).close(status.capture(), any(Metadata.class)); + assertThat(status.getValue().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + verify(next, never()).startCall(any(), any()); + } + + private static Attributes tlsAttributes(java.security.cert.Certificate peer) throws Exception { + SSLSession session = mock(SSLSession.class); + when(session.getPeerCertificates()).thenReturn(new java.security.cert.Certificate[] {peer}); + return Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build(); + } + + private static Binding binding(String pin, String revision) { + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + List pins = List.of(pin); + String digest = + AccountJwtReadinessTrustBinding.computeBindingDigest( + revision, + "prod", + "prod-cluster-1", + "firemud-prod", + clusterUid, + namespaceUid, + URI, + pins, + "account-validator-instance-7", + 1_900_000_000L); + return new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + clusterUid, + namespaceUid, + URI, + pins, + revision, + "account-service", + "account-validator-instance-7", + 1_900_000_000L, + digest); + } + + private static java.security.cert.Certificate cert(String uri) throws Exception { + return cert(uri, MATCHING_SPKI); + } + + private static java.security.cert.Certificate cert(String uri, byte[] spki) throws Exception { + java.security.cert.X509Certificate certificate = mock(java.security.cert.X509Certificate.class); + java.security.PublicKey publicKey = mock(java.security.PublicKey.class); + when(certificate.getPublicKey()).thenReturn(publicKey); + when(publicKey.getEncoded()).thenReturn(spki); + List> alternativeNames = new ArrayList<>(); + alternativeNames.add(List.of(6, uri)); + when(certificate.getSubjectAlternativeNames()).thenReturn(alternativeNames); + return certificate; + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new AssertionError(ex); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptorTest.java new file mode 100644 index 0000000000..aadb56046c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptorTest.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class AccountJwtSignerMaterializerTlsInterceptorTest { + private static final String URI = "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + private static final byte[] MATCHING_SPKI = + "materializer leaf key".getBytes(StandardCharsets.US_ASCII); + + @Test + void noTlsOrHeaderOnlyIdentityIsDeniedBeforeTheServiceHandler() { + Binding binding = binding("a".repeat(64), "revision-1", "firemud-prod"); + AccountJwtSignerMaterializerTlsInterceptor interceptor = + new AccountJwtSignerMaterializerTlsInterceptor(() -> Optional.of(binding)); + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + @SuppressWarnings("unchecked") + ServerCallHandler next = mock(ServerCallHandler.class); + when(call.getAttributes()).thenReturn(Attributes.EMPTY); + Metadata headers = new Metadata(); + headers.put( + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), "Bearer header-only"); + + interceptor.interceptCall(call, headers, next); + + ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); + verify(call).close(status.capture(), any(Metadata.class)); + assertThat(status.getValue().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + verify(next, never()).startCall(any(), any()); + } + + @Test + void absentDisabledOrWithdrawnProtectedBindingDeniesAccess() { + AccountJwtSignerMaterializerTrustBinding disabled = + new AccountJwtSignerMaterializerTrustBinding(false, "/absent"); + AccountJwtSignerMaterializerTlsInterceptor noBindingInterceptor = + new AccountJwtSignerMaterializerTlsInterceptor(disabled); + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + @SuppressWarnings("unchecked") + ServerCallHandler next = mock(ServerCallHandler.class); + + noBindingInterceptor.interceptCall(call, new Metadata(), next); + + ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); + verify(call).close(status.capture(), any(Metadata.class)); + assertThat(status.getValue().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + verify(next, never()).startCall(any(), any()); + } + + @Test + void exactUriAndOneConfiguredLeafSpkiPinAreRequired() throws Exception { + String pin = sha256(MATCHING_SPKI); + Binding binding = binding(pin, "revision-1", "firemud-prod"); + + assertThat( + AccountJwtSignerMaterializerTrustBinding.matchesPeer( + new java.security.cert.Certificate[] {certificate(URI, MATCHING_SPKI)}, binding)) + .isTrue(); + assertThat( + AccountJwtSignerMaterializerTrustBinding.matchesPeer( + new java.security.cert.Certificate[] { + certificate("spiffe://firemud/ns/other/sa/jwt-signer-materializer", MATCHING_SPKI) + }, + binding)) + .isFalse(); + assertThat( + AccountJwtSignerMaterializerTrustBinding.matchesPeer( + new java.security.cert.Certificate[] { + certificate(URI, "different materializer key".getBytes(StandardCharsets.US_ASCII)) + }, + binding)) + .isFalse(); + assertThat( + AccountJwtSignerMaterializerTrustBinding.matchesPeer( + new java.security.cert.Certificate[] { + certificate(List.of(URI, URI), MATCHING_SPKI) + }, + binding)) + .isFalse(); + } + + @Test + void sameUriCertificateFailsAfterItsConfiguredKeyPinIsWithdrawn() throws Exception { + String oldPin = sha256(MATCHING_SPKI); + Binding oldBinding = binding(oldPin, "revision-1", "firemud-prod"); + Binding rotatedBinding = + binding( + sha256("replacement key".getBytes(StandardCharsets.US_ASCII)), + "revision-2", + "firemud-prod"); + java.security.cert.Certificate[] peer = {certificate(URI, MATCHING_SPKI)}; + + assertThat(AccountJwtSignerMaterializerTrustBinding.matchesPeer(peer, oldBinding)).isTrue(); + assertThat(AccountJwtSignerMaterializerTrustBinding.matchesPeer(peer, rotatedBinding)) + .isFalse(); + } + + @Test + void matchingTlsPeerReachesOnlyTheLocallyProtectedServiceContext() throws Exception { + Binding binding = binding(sha256(MATCHING_SPKI), "revision-1", "firemud-prod"); + AccountJwtSignerMaterializerTlsInterceptor interceptor = + new AccountJwtSignerMaterializerTlsInterceptor(() -> Optional.of(binding)); + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + @SuppressWarnings("unchecked") + ServerCallHandler next = mock(ServerCallHandler.class); + SSLSession session = mock(SSLSession.class); + java.security.cert.Certificate[] peerCertificates = {certificate(URI, MATCHING_SPKI)}; + when(session.getPeerCertificates()).thenReturn(peerCertificates); + when(call.getAttributes()) + .thenReturn(Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build()); + AtomicReference bindingDuringCallback = new AtomicReference<>(); + ServerCall.Listener listener = + new ServerCall.Listener<>() { + @Override + public void onMessage(String message) { + bindingDuringCallback.set( + AccountJwtSignerMaterializerTlsInterceptor.authenticatedBinding()); + } + }; + when(next.startCall(any(), any())) + .thenAnswer( + invocation -> { + assertThat(AccountJwtSignerMaterializerTlsInterceptor.authenticatedBinding()) + .isEqualTo(binding); + return listener; + }); + + ServerCall.Listener intercepted = interceptor.interceptCall(call, new Metadata(), next); + assertThat(intercepted).isNotSameAs(listener); + intercepted.onMessage("request"); + assertThat(bindingDuringCallback.get()).isEqualTo(binding); + assertThat(AccountJwtSignerMaterializerTlsInterceptor.authenticatedBinding()).isNull(); + verify(next).startCall(any(), any()); + verify(call, never()).close(any(), any()); + } + + private static Binding binding(String pin, String revision, String namespace) { + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + String expectedUri = "spiffe://firemud/ns/" + namespace + "/sa/jwt-signer-materializer"; + List pins = List.of(pin); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, + "prod", + "prod-cluster-1", + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins); + return new Binding( + "prod", + "prod-cluster-1", + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + revision, + digest); + } + + private static java.security.cert.Certificate certificate(String uri, byte[] publicKeyBytes) + throws Exception { + return certificate(List.of(uri), publicKeyBytes); + } + + private static java.security.cert.Certificate certificate( + List uris, byte[] publicKeyBytes) throws Exception { + java.security.cert.X509Certificate certificate = mock(java.security.cert.X509Certificate.class); + java.security.PublicKey publicKey = mock(java.security.PublicKey.class); + when(certificate.getPublicKey()).thenReturn(publicKey); + when(publicKey.getEncoded()).thenReturn(publicKeyBytes); + List> alternativeNames = new ArrayList<>(); + for (String uri : uris) { + alternativeNames.add(List.of(6, uri)); + } + when(certificate.getSubjectAlternativeNames()).thenReturn(alternativeNames); + return certificate; + } + + private static String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsTransportTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsTransportTest.java new file mode 100644 index 0000000000..11573435a7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsTransportTest.java @@ -0,0 +1,483 @@ +package net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.protobuf.StringValue; +import io.grpc.Attributes; +import io.grpc.CallOptions; +import io.grpc.ManagedChannel; +import io.grpc.MethodDescriptor; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.ServerTransportFilter; +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.SslContext; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.protobuf.ProtoUtils; +import io.grpc.stub.ClientCalls; +import io.grpc.stub.ServerCalls; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.test.TlsTestSupport; +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 loopback gRPC mTLS transport proof for Account's JWT materializer interceptor only. The + * test-only echo RPC does not prove Secret generation, database readiness, or live provisioning. + */ +class AccountJwtSignerMaterializerTlsTransportTest { + private static final String SERVICE_NAME = "firemud.account.v1.JwtSignerMaterializerTransport"; + private static final String EXPECTED_PEER_URI = + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + private static final String OTHER_PEER_URI = + "spiffe://firemud/ns/firemud-prod/sa/other-materializer"; + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final MethodDescriptor PROBE_METHOD = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(MethodDescriptor.generateFullMethodName(SERVICE_NAME, "Probe")) + .setRequestMarshaller(ProtoUtils.marshaller(StringValue.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(StringValue.getDefaultInstance())) + .build(); + + @TempDir private static Path temporaryDirectory; + + private static TestPki pki; + + private final List channels = new ArrayList<>(); + private final AtomicReference authenticatedBindingAtHandler = new AtomicReference<>(); + private final AtomicInteger handlerCalls = new AtomicInteger(); + private final AtomicInteger serverTransports = new AtomicInteger(); + + private Server server; + + @BeforeAll + static void generateEphemeralTestCertificates() throws Exception { + Path trustedDirectory = Files.createDirectories(temporaryDirectory.resolve("trusted-pki")); + TestAuthority trustedAuthority = createAuthority(trustedDirectory, "firemud-test-ca"); + TestCertificate serverCertificate = + issueLeaf( + trustedDirectory, + trustedAuthority, + "account-materializer-test-server", + "spiffe://firemud/ns/firemud-prod/sa/account-service", + true); + TestCertificate pinnedMaterializer = + issueLeaf( + trustedDirectory, + trustedAuthority, + "materializer-cluster-one", + EXPECTED_PEER_URI, + false); + TestCertificate sameUriOtherCluster = + issueLeaf( + trustedDirectory, + trustedAuthority, + "materializer-cluster-two", + EXPECTED_PEER_URI, + false); + TestCertificate wrongUri = + issueLeaf( + trustedDirectory, trustedAuthority, "wrong-materializer-uri", OTHER_PEER_URI, false); + + Path unknownDirectory = Files.createDirectories(temporaryDirectory.resolve("unknown-pki")); + TestAuthority unknownAuthority = createAuthority(unknownDirectory, "untrusted-test-ca"); + TestCertificate unknownCaMaterializer = + issueLeaf( + unknownDirectory, + unknownAuthority, + "unknown-ca-materializer", + EXPECTED_PEER_URI, + false); + + pki = + new TestPki( + trustedAuthority.certificate(), + serverCertificate, + pinnedMaterializer, + sameUriOtherCluster, + wrongUri, + unknownCaMaterializer); + } + + @AfterEach + void stopTransport() throws InterruptedException { + List terminatingChannels = + channels.stream().map(ManagedChannel::shutdownNow).toList(); + if (server != null) { + server.shutdownNow(); + } + for (ManagedChannel channel : terminatingChannels) { + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + if (server != null) { + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void pinnedCertificateReachesHandlerWithTheAuthenticatedBindingOverLoopbackMtls() + throws Exception { + Binding binding = binding("prod-cluster-one", pki.pinnedMaterializer(), "revision-1"); + startServer(() -> Optional.of(binding)); + ManagedChannel channel = channel(pki.pinnedMaterializer()); + + assertThat(invoke(channel).getValue()).isEqualTo("materializer transport probe"); + assertThat(authenticatedBindingAtHandler.get()).isEqualTo(binding); + assertThat(handlerCalls.get()).isEqualTo(1); + assertThat(serverTransports.get()).isEqualTo(1); + } + + @Test + void sameUriCertificateWithAnotherClustersKeyFailsTheIndependentSpkiPin() throws Exception { + Binding binding = binding("prod-cluster-one", pki.pinnedMaterializer(), "revision-1"); + startServer(() -> Optional.of(binding)); + ManagedChannel channel = channel(pki.sameUriOtherCluster()); + + assertPermissionDenied(() -> invoke(channel)); + assertThat(handlerCalls.get()).isZero(); + // The certificate chains to the server's trusted CA, so denial came from URI+SPKI binding. + assertThat(serverTransports.get()).isEqualTo(1); + } + + @Test + void wrongUriFailsEvenWhenTheProtectedBindingPinsThatCertificatesKey() throws Exception { + Binding binding = binding("prod-cluster-one", pki.wrongUri(), "revision-wrong-uri"); + startServer(() -> Optional.of(binding)); + ManagedChannel channel = channel(pki.wrongUri()); + + assertPermissionDenied(() -> invoke(channel)); + assertThat(handlerCalls.get()).isZero(); + assertThat(serverTransports.get()).isEqualTo(1); + } + + @Test + void absentClientCertificateIsRejectedByTheTlsHandshake() throws Exception { + Binding binding = binding("prod-cluster-one", pki.pinnedMaterializer(), "revision-1"); + startServer(() -> Optional.of(binding)); + ManagedChannel channel = channel(null); + + assertTlsHandshakeDenied(() -> invoke(channel)); + assertThat(handlerCalls.get()).isZero(); + } + + @Test + void clientCertificateFromAnUnknownCaIsRejectedByTheTlsHandshake() throws Exception { + Binding binding = binding("prod-cluster-one", pki.unknownCaMaterializer(), "revision-1"); + startServer(() -> Optional.of(binding)); + ManagedChannel channel = channel(pki.unknownCaMaterializer()); + + assertTlsHandshakeDenied(() -> invoke(channel)); + assertThat(handlerCalls.get()).isZero(); + } + + @Test + void trustWithdrawalDeniesTheNextRpcOnTheExistingTlsConnection() throws Exception { + Binding binding = binding("prod-cluster-one", pki.pinnedMaterializer(), "revision-1"); + AtomicReference> protectedBinding = + new AtomicReference<>(Optional.of(binding)); + startServer(protectedBinding::get); + ManagedChannel channel = channel(pki.pinnedMaterializer()); + + invoke(channel); + assertThat(handlerCalls.get()).isEqualTo(1); + assertThat(serverTransports.get()).isEqualTo(1); + + protectedBinding.set(Optional.empty()); + assertPermissionDenied(() -> invoke(channel)); + assertThat(handlerCalls.get()).isEqualTo(1); + assertThat(serverTransports.get()).isEqualTo(1); + } + + @Test + void changedClusterBindingDeniesTheOldPeerOnTheExistingTlsConnection() throws Exception { + Binding original = binding("prod-cluster-one", pki.pinnedMaterializer(), "revision-1"); + Binding changed = binding("prod-cluster-two", pki.sameUriOtherCluster(), "revision-2"); + AtomicReference> protectedBinding = + new AtomicReference<>(Optional.of(original)); + startServer(protectedBinding::get); + ManagedChannel channel = channel(pki.pinnedMaterializer()); + + invoke(channel); + assertThat(handlerCalls.get()).isEqualTo(1); + assertThat(serverTransports.get()).isEqualTo(1); + + protectedBinding.set(Optional.of(changed)); + assertPermissionDenied(() -> invoke(channel)); + assertThat(handlerCalls.get()).isEqualTo(1); + assertThat(serverTransports.get()).isEqualTo(1); + } + + private void startServer(Supplier> bindingProvider) throws Exception { + AccountJwtSignerMaterializerTlsInterceptor interceptor = + new AccountJwtSignerMaterializerTlsInterceptor(bindingProvider); + ServerServiceDefinition testOnlyHandler = + ServerServiceDefinition.builder(SERVICE_NAME) + .addMethod( + PROBE_METHOD, + ServerCalls.asyncUnaryCall( + (StringValue request, StreamObserver responseObserver) -> { + authenticatedBindingAtHandler.set( + AccountJwtSignerMaterializerTlsInterceptor.authenticatedBinding()); + handlerCalls.incrementAndGet(); + responseObserver.onNext(request); + responseObserver.onCompleted(); + })) + .build(); + SslContext tlsContext = + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.serverCertificate().certificate().toFile(), + pki.serverCertificate().privateKey().toFile())) + .trustManager(pki.trustedCa().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build(); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(tlsContext) + .addTransportFilter( + new ServerTransportFilter() { + @Override + public Attributes transportReady(Attributes attributes) { + serverTransports.incrementAndGet(); + return attributes; + } + }) + .addService(ServerInterceptors.intercept(testOnlyHandler, interceptor)) + .build() + .start(); + } + + private ManagedChannel channel(TestCertificate clientCertificate) throws Exception { + SslContextBuilder tlsBuilder = + GrpcSslContexts.forClient().trustManager(pki.trustedCa().toFile()); + if (clientCertificate != null) { + tlsBuilder.keyManager( + clientCertificate.certificate().toFile(), clientCertificate.privateKey().toFile()); + } + ManagedChannel channel = + NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", server.getPort())) + .sslContext(tlsBuilder.build()) + .build(); + channels.add(channel); + return channel; + } + + private static StringValue invoke(ManagedChannel channel) { + CallOptions options = CallOptions.DEFAULT.withDeadlineAfter(3, TimeUnit.SECONDS); + return ClientCalls.blockingUnaryCall( + channel, PROBE_METHOD, options, StringValue.of("materializer transport probe")); + } + + private static void assertPermissionDenied(Runnable rpc) { + Throwable failure = failureOf(rpc); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isFalse(); + } + + private static void assertTlsHandshakeDenied(Runnable rpc) { + Throwable failure = failureOf(rpc); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isNotEqualTo(Status.Code.DEADLINE_EXCEEDED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue(); + } + + private static Throwable failureOf(Runnable rpc) { + try { + rpc.run(); + return null; + } catch (Throwable failure) { + return failure; + } + } + + private static Binding binding(String clusterId, TestCertificate certificate, String revision) + throws Exception { + String pin = spkiSha256(certificate.certificate()); + List pins = List.of(pin); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, + "prod", + clusterId, + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + EXPECTED_PEER_URI, + pins); + return new Binding( + "prod", + clusterId, + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + EXPECTED_PEER_URI, + pins, + revision, + digest); + } + + private static String spkiSha256(Path certificatePath) throws Exception { + X509Certificate certificate; + try (InputStream input = Files.newInputStream(certificatePath)) { + certificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(certificate.getPublicKey().getEncoded())); + } + + private static TestAuthority createAuthority(Path directory, String commonName) throws Exception { + Path privateKey = directory.resolve(commonName + ".key"); + Path certificate = directory.resolve(commonName + ".crt"); + runOpenSsl( + directory, + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + privateKey.toString(), + "-out", + certificate.toString(), + "-subj", + "/CN=" + commonName, + "-days", + "2", + "-sha256", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign"); + return new TestAuthority(privateKey, certificate); + } + + private static TestCertificate issueLeaf( + Path directory, + TestAuthority authority, + String commonName, + String workloadUri, + boolean serverCertificate) + throws Exception { + Path privateKey = directory.resolve(commonName + ".key"); + Path request = directory.resolve(commonName + ".csr"); + Path certificate = directory.resolve(commonName + ".crt"); + Path extensions = directory.resolve(commonName + ".ext"); + String extendedKeyUsage = serverCertificate ? "serverAuth" : "clientAuth"; + Files.writeString( + extensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=" + + extendedKeyUsage + + "\n" + + "subjectAltName=URI:" + + workloadUri + + ",DNS:localhost,IP:127.0.0.1\n"); + runOpenSsl( + directory, + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + privateKey.toString(), + "-out", + request.toString(), + "-subj", + "/CN=" + commonName); + runOpenSsl( + directory, + "x509", + "-req", + "-in", + request.toString(), + "-CA", + authority.certificate().toString(), + "-CAkey", + authority.privateKey().toString(), + "-CAcreateserial", + "-out", + certificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + extensions.toString()); + return new TestCertificate(privateKey, certificate); + } + + private static void runOpenSsl(Path directory, String... arguments) throws Exception { + List command = new ArrayList<>(); + command.add("openssl"); + command.addAll(List.of(arguments)); + Process process; + try { + process = + new ProcessBuilder(command) + .directory(directory.toFile()) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + } catch (IOException exception) { + throw new IllegalStateException("OpenSSL is required for the ephemeral TLS test fixture"); + } + try { + if (!process.waitFor(20, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(2, TimeUnit.SECONDS); + throw new IllegalStateException("Ephemeral TLS fixture generation timed out"); + } + } catch (InterruptedException exception) { + process.destroyForcibly(); + Thread.currentThread().interrupt(); + throw new IllegalStateException("Ephemeral TLS fixture generation was interrupted"); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("Ephemeral TLS fixture generation failed"); + } + } + + private record TestAuthority(Path privateKey, Path certificate) {} + + private record TestCertificate(Path privateKey, Path certificate) {} + + private record TestPki( + Path trustedCa, + TestCertificate serverCertificate, + TestCertificate pinnedMaterializer, + TestCertificate sameUriOtherCluster, + TestCertificate wrongUri, + TestCertificate unknownCaMaterializer) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java new file mode 100644 index 0000000000..45554c3931 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java @@ -0,0 +1,148 @@ +package unit.net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerWorkloadGuard; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtReadinessProbeOwnerGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerProtoMapper; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeService; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.grpc.server.GlobalServerInterceptor; +import org.springframework.grpc.server.service.DefaultGrpcServiceConfigurer; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.grpc.server.service.GrpcServiceInfo; +import org.springframework.grpc.server.service.GrpcServiceSpec; + +class AccountJwtReadinessProbeOwnerGrpcServiceTest { + @Test + void ownerLookupIsIndependentlyDefaultDeniedAndUsesTheGlobalPeerIdentityInterceptor() { + GrpcService grpc = + AccountJwtReadinessProbeOwnerGrpcService.class.getAnnotation(GrpcService.class); + assertThat(grpc).isNotNull(); + assertThat(grpc.interceptorNames()).isEmpty(); + assertThat(grpc.interceptors()).isEmpty(); + + try (AnnotationConfigApplicationContext context = + new AnnotationConfigApplicationContext(GlobalPeerIdentityConfiguration.class)) { + DefaultGrpcServiceConfigurer configurer = new DefaultGrpcServiceConfigurer(context); + configurer.afterPropertiesSet(); + var service = + new AccountJwtReadinessProbeOwnerGrpcService( + mock(AccountJwtReadinessProbeOwnerService.class)); + var serviceDefinition = + configurer.configure(new GrpcServiceSpec(service, GrpcServiceInfo.from(grpc)), null); + var methodDefinition = serviceDefinition.getMethods().iterator().next(); + ServerCall serverCall = mock(ServerCall.class); + when(serverCall.getMethodDescriptor()).thenReturn(methodDefinition.getMethodDescriptor()); + methodDefinition.getServerCallHandler().startCall(serverCall, new Metadata()); + + assertThat(context.getBean(GlobalPeerIdentityMarker.class).invocations()).hasValue(1); + } + + ConditionalOnProperty condition = + AccountJwtReadinessProbeOwnerGrpcService.class.getAnnotation(ConditionalOnProperty.class); + assertThat(condition).isNotNull(); + assertThat(condition.prefix()).isEqualTo("firemud.account.jwt-readiness.probe-owner"); + assertThat(condition.name()).containsExactly("enabled"); + assertThat(condition.havingValue()).isEqualTo("true"); + assertThat(condition.matchIfMissing()).isFalse(); + } + + @Test + void missingProtectedAccountBindingDeniesBeforeInventoryOrSqlAccess() { + AccountJwtSignerMaterializerTrustBinding materializerBinding = + mock(AccountJwtSignerMaterializerTrustBinding.class); + when(materializerBinding.current()).thenReturn(Optional.empty()); + AccountJwtReadinessProbeService probeService = mock(AccountJwtReadinessProbeService.class); + var guard = + new AccountJwtReadinessProbeOwnerWorkloadGuard( + materializerBinding, mock(AccountJwtJwksApiBinding.class), "firemud-prod"); + var owner = + new AccountJwtReadinessProbeOwnerService( + probeService, + materializerBinding, + guard, + new AccountJwtReadinessProbeOwnerProtoMapper()); + var service = new AccountJwtReadinessProbeOwnerGrpcService(owner); + RecordingObserver response = new RecordingObserver(); + + service.getCurrentReadinessProbeOwner( + GetCurrentReadinessProbeOwnerRequest.newBuilder().setSchemaVersion(1).build(), response); + + assertThat(response.value.get()).isNull(); + assertThat(response.completed).isFalse(); + assertThat(Status.fromThrowable(response.failure.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(probeService); + } + + private static final class RecordingObserver + implements StreamObserver { + private final AtomicReference value = + new AtomicReference<>(); + private final AtomicReference failure = new AtomicReference<>(); + private boolean completed; + + @Override + public void onNext(GetCurrentReadinessProbeOwnerResponse response) { + value.set(response); + } + + @Override + public void onError(Throwable throwable) { + failure.set(throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + @Configuration(proxyBeanMethods = false) + static class GlobalPeerIdentityConfiguration { + @Bean + @GlobalServerInterceptor + GlobalPeerIdentityMarker globalPeerIdentityMarker() { + return new GlobalPeerIdentityMarker(); + } + } + + private static final class GlobalPeerIdentityMarker implements ServerInterceptor { + private final AtomicInteger invocations = new AtomicInteger(); + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + invocations.incrementAndGet(); + return next.startCall(call, headers); + } + + private AtomicInteger invocations() { + return invocations; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessValidationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessValidationGrpcServiceTest.java new file mode 100644 index 0000000000..8a005b848c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessValidationGrpcServiceTest.java @@ -0,0 +1,82 @@ +package unit.net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.IssueReadinessProbesRequest; +import net.firedevops.firemud.account.v1.IssueReadinessProbesResponse; +import net.firedevops.firemud.account.v1.ValidateReadinessProbeRequest; +import net.firedevops.firemud.account.v1.ValidateReadinessProbeResponse; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtReadinessValidationGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessTransportOwner; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.grpc.server.service.GrpcService; + +class AccountJwtReadinessValidationGrpcServiceTest { + @Test + void serviceBindsOnlyTheDedicatedReadinessTlsInterceptorAndRemainsOptIn() { + GrpcService grpc = + AccountJwtReadinessValidationGrpcService.class.getAnnotation(GrpcService.class); + assertThat(grpc).isNotNull(); + assertThat(grpc.interceptorNames()).containsExactly("accountJwtReadinessTlsInterceptor"); + assertThat(grpc.blendWithGlobalInterceptors()).isFalse(); + + ConditionalOnProperty condition = + AccountJwtReadinessValidationGrpcService.class.getAnnotation(ConditionalOnProperty.class); + assertThat(condition).isNotNull(); + assertThat(condition.prefix()).isEqualTo("firemud.account.jwt-readiness.validation"); + assertThat(condition.name()).containsExactly("enabled"); + assertThat(condition.havingValue()).isEqualTo("true"); + assertThat(condition.matchIfMissing()).isFalse(); + } + + @Test + void bothMethodsDenyMissingTlsContextBeforeOwnerAccess() { + AccountJwtReadinessTransportOwner owner = mock(AccountJwtReadinessTransportOwner.class); + var service = new AccountJwtReadinessValidationGrpcService(owner); + RecordingObserver issue = new RecordingObserver<>(); + RecordingObserver validate = new RecordingObserver<>(); + + service.issueReadinessProbes( + IssueReadinessProbesRequest.newBuilder().setSchemaVersion(1).build(), issue); + service.validateReadinessProbe( + ValidateReadinessProbeRequest.newBuilder().setSchemaVersion(1).build(), validate); + + assertDenied(issue); + assertDenied(validate); + verifyNoInteractions(owner); + } + + private static void assertDenied(RecordingObserver observer) { + assertThat(observer.value.get()).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(Status.fromThrowable(observer.failure.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + private static final class RecordingObserver implements StreamObserver { + private final AtomicReference value = new AtomicReference<>(); + private final AtomicReference failure = new AtomicReference<>(); + private boolean completed; + + @Override + public void onNext(T item) { + value.set(item); + } + + @Override + public void onError(Throwable throwable) { + failure.set(throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java new file mode 100644 index 0000000000..84e974f093 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java @@ -0,0 +1,1323 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.PublicKey; +import java.security.interfaces.RSAPublicKey; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.EnrollBootstrapRequest; +import net.firedevops.firemud.account.v1.EnrollBootstrapResponse; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; +import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; +import net.firedevops.firemud.account.v1.RecordSecretObservationRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedPromotion; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtSignerMaterializationServiceTest { + private static final UUID OPERATION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final String OPERATION_DIGEST = "a".repeat(64); + private static final String GENERATION_REQUEST_DIGEST = "b".repeat(64); + private static final String RECEIPT_DIGEST = "c".repeat(64); + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "33333333-3333-4333-8333-333333333333"; + private static final String SECRET_UID = "44444444-4444-4444-8444-444444444444"; + private static final String PEER_URI = + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + private static final byte[] PEER_SPKI = + "account materializer test public key".getBytes(StandardCharsets.US_ASCII); + + @Test + void bootstrapEnrollmentIsDisabledWithoutExplicitCompositionAndDoesNotTouchAccountState() + throws Exception { + Fixture fixture = fixture(); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.enrollBootstrap( + EnrollBootstrapRequest.newBuilder().setSchemaVersion(1).build(), response)); + + assertStatus(response.error, Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(fixture.repository, fixture.transactionManager); + } + + @Test + void authenticatedGetReturnsAccountSelectedReadOnlyObservationOperation() throws Exception { + Fixture fixture = fixture(); + GenerationRequest request = + generationRequest(fixture.binding, GenerationPhase.OBSERVE_PRIVATE_SECRET, "", "", null); + when(fixture.repository.ensureCurrentGenerationRequest( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenReturn(request); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.getCurrentGenerationRequest( + GetCurrentGenerationRequestRequest.newBuilder().setSchemaVersion(1).build(), + response)); + + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value.getPhase()) + .isEqualTo(GetCurrentGenerationRequestResponse.Phase.OBSERVE_PRIVATE_SECRET); + assertThat(response.value.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.value.getTargetGeneration()).isEqualTo("1"); + assertThat(response.value.getTargetKid()).startsWith("jwt-1-"); + assertThat(response.value.getPrivateSecretName()).isEqualTo("jwt-signing-keys"); + assertThat(response.value.getExpectedSecretResourceVersion()).isEmpty(); + assertThat(response.value.getPublicJwkJson()).isEmpty(); + verify(fixture.repository) + .ensureCurrentGenerationRequest( + accountBinding(fixture.binding), trustFence(fixture.binding)); + verify(fixture.transactionManager).commit(any(TransactionStatus.class)); + } + + @Test + void authenticatedObservationReturnsOnlyTheExactGenerationCasFence() throws Exception { + Fixture fixture = fixture(); + GenerationRequest pending = + generationRequest( + fixture.binding, GenerationPhase.GENERATE_PENDING, SECRET_UID, "12", null); + when(fixture.repository.recordSecretObservation( + eq(accountBinding(fixture.binding)), + eq(trustFence(fixture.binding)), + eq(OPERATION_ID), + eq(OPERATION_DIGEST), + eq(SECRET_UID), + eq("12"))) + .thenReturn(pending); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.recordSecretObservation( + RecordSecretObservationRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(OPERATION_ID.toString()) + .setOperationDigest(OPERATION_DIGEST) + .setSecretUid(SECRET_UID) + .setObservedResourceVersion("12") + .build(), + response)); + + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value.getPhase()) + .isEqualTo(GetCurrentGenerationRequestResponse.Phase.GENERATE_PENDING); + assertThat(response.value.getGenerationRequestDigest()).isEqualTo(GENERATION_REQUEST_DIGEST); + assertThat(response.value.getSecretUid()).isEqualTo(SECRET_UID); + assertThat(response.value.getExpectedSecretResourceVersion()).isEqualTo("12"); + assertThat(response.value.getPublicKeyFingerprint()).isEmpty(); + verify(fixture.repository) + .recordSecretObservation( + accountBinding(fixture.binding), + trustFence(fixture.binding), + OPERATION_ID, + OPERATION_DIGEST, + SECRET_UID, + "12"); + } + + @Test + void authenticatedGenerationResultReturnsAccountDerivedPublicOnlyReceipt() throws Exception { + Fixture fixture = fixture(); + PublicJwk jwk = publicJwk(targetKid()); + GenerationResult result = generationResult(fixture.binding, jwk); + when(fixture.repository.recordGenerationResult( + eq(accountBinding(fixture.binding)), + eq(trustFence(fixture.binding)), + eq(OPERATION_ID), + eq(GENERATION_REQUEST_DIGEST), + eq(SECRET_UID), + eq("12"), + eq("13"), + eq(jwk.json()))) + .thenReturn(result); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.recordGenerationResult( + RecordGenerationResultRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(OPERATION_ID.toString()) + .setGenerationRequestDigest(GENERATION_REQUEST_DIGEST) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion("12") + .setObservedResourceVersion("13") + .setPublicJwkJson(jwk.json()) + .build(), + response)); + + assertThat(response.error).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value.getGenerationReceiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(response.value.getExpectedPriorResourceVersion()).isEqualTo("12"); + assertThat(response.value.getObservedResourceVersion()).isEqualTo("13"); + assertThat(response.value.getTargetKid()).isEqualTo(targetKid()); + assertThat(response.value.getPublicKeyFingerprint()).isEqualTo(jwk.fingerprint()); + assertThat(response.value.getPublicJwkJson()).isEqualTo(jwk.json()); + assertThat(response.value.getPublicJwkJson()).doesNotContain("\"d\""); + verify(fixture.transactionManager).commit(any(TransactionStatus.class)); + } + + @Test + void privatePromotionReceiptRunsAccountCompletionAfterReceiptTransactionBeforeSuccess() + throws Exception { + Fixture fixture = fixture(); + AccountJwtSignerBootstrapCoordinator coordinator = + mock(AccountJwtSignerBootstrapCoordinator.class); + when(fixture.bootstrapCoordinatorProvider.getIfAvailable()).thenReturn(coordinator); + UUID promotionId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + PublicJwk jwk = publicJwk(targetKid()); + PrivatePromotionObservation observation = + new PrivatePromotionObservation( + promotionId, + "f".repeat(64), + OPERATION_ID, + OPERATION_DIGEST, + SECRET_UID, + "13", + "14", + new AccountJwtSignerDesiredStateRepository.PublicKeyIdentity( + "1", targetKid(), jwk.fingerprint()), + Optional.empty(), + List.of("current")); + PrivatePromotionReceipt receipt = + new PrivatePromotionReceipt(promotionId, OPERATION_ID, "14", "e".repeat(64)); + AtomicReference repositoryObservation = new AtomicReference<>(); + when(fixture.repository.recordPrivatePromotionResult( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)), eq(observation))) + .thenAnswer( + invocation -> { + repositoryObservation.set(invocation.getArgument(2)); + return receipt; + }); + AtomicBoolean receiptTransactionCommitted = new AtomicBoolean(); + doAnswer( + invocation -> { + receiptTransactionCommitted.set(true); + return null; + }) + .when(fixture.transactionManager) + .commit(any(TransactionStatus.class)); + AtomicBoolean reconciliationCompleted = new AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> { + assertThat(receiptTransactionCommitted.get()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(invocation.getArgument(0)) + .isSameAs(repositoryObservation.get()); + assertThat(invocation.getArgument(1)).isSameAs(receipt); + reconciliationCompleted.set(true); + return null; + }) + .when(coordinator) + .reconcilePreparedPromotionOnce(observation, receipt); + java.util.concurrent.atomic.AtomicReference delivered = + new java.util.concurrent.atomic.AtomicReference<>(); + AtomicBoolean completed = new AtomicBoolean(); + StreamObserver response = + new StreamObserver<>() { + @Override + public void onNext(RecordPrivatePromotionResultResponse value) { + assertThat(reconciliationCompleted.get()).isTrue(); + delivered.set(value); + } + + @Override + public void onError(Throwable error) { + throw new AssertionError("Private promotion unexpectedly failed", error); + } + + @Override + public void onCompleted() { + assertThat(reconciliationCompleted.get()).isTrue(); + completed.set(true); + } + }; + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.recordPrivatePromotionResult( + RecordPrivatePromotionResultRequest.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(promotionId.toString()) + .setPromotionRequestDigest("f".repeat(64)) + .setGenerationOperationId(OPERATION_ID.toString()) + .setGenerationOperationDigest(OPERATION_DIGEST) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion("13") + .setObservedResourceVersion("14") + .setCurrent( + net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity.newBuilder() + .setGeneration("1") + .setKid(targetKid()) + .setPublicKeyFingerprint(jwk.fingerprint())) + .addResultingSlots("current") + .build(), + response)); + + assertThat(completed).isTrue(); + assertThat(delivered.get().getPublicReceiptDigest()).isEqualTo(receipt.receiptDigest()); + verify(coordinator).reconcilePreparedPromotionOnce(observation, receipt); + } + + @Test + void promotionRequestCommitsStickyDispatchBeforeReturningMutationAuthority() throws Exception { + Fixture fixture = fixture(); + PublicJwk jwk = publicJwk(targetKid()); + PreparedGenerationEvidence prepared = preparedGenerationEvidence(fixture.binding, jwk); + AtomicBoolean dispatchRecorded = new AtomicBoolean(); + when(fixture.repository.readAndMarkPreparedPromotionDispatched( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenAnswer( + invocation -> { + dispatchRecorded.set(true); + return prepared; + }); + when(fixture.repository.readPreparedGenerationForRecovery( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenReturn(prepared); + when(fixture.readinessRepository.readPromotionProof( + eq(accountBinding(fixture.binding)), + eq(trustFence(fixture.binding)), + eq(OPERATION_ID), + same(fixture.inventorySnapshot))) + .thenReturn(Optional.of(mock(ReadinessPromotionProof.class))); + AtomicBoolean transactionCommitted = new AtomicBoolean(); + doAnswer( + invocation -> { + if (dispatchRecorded.get()) { + transactionCommitted.set(true); + } + return null; + }) + .when(fixture.transactionManager) + .commit(any(TransactionStatus.class)); + GetCurrentPromotionRequestResponse[] delivered = new GetCurrentPromotionRequestResponse[1]; + StreamObserver response = + new StreamObserver<>() { + @Override + public void onNext(GetCurrentPromotionRequestResponse value) { + assertThat(transactionCommitted.get()).isTrue(); + delivered[0] = value; + } + + @Override + public void onError(Throwable error) { + throw new AssertionError("Promotion request unexpectedly failed", error); + } + + @Override + public void onCompleted() { + assertThat(transactionCommitted.get()).isTrue(); + } + }; + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + response)); + + assertThat(delivered[0]).isNotNull(); + assertThat(delivered[0].getPromotionOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(delivered[0].getOperationAction()).isEqualTo("PROMOTE_PENDING"); + assertThat(delivered[0].getAllowedPrivateSlotsList()) + .containsExactly("current.key", "pending.key", "previous.key"); + verify(fixture.repository, times(2)) + .readPreparedGenerationForRecovery( + accountBinding(fixture.binding), trustFence(fixture.binding)); + verify(fixture.readinessRepository) + .readPromotionProof( + accountBinding(fixture.binding), + trustFence(fixture.binding), + OPERATION_ID, + fixture.inventorySnapshot); + InOrder ownerFlow = + inOrder( + fixture.transactionManager, + fixture.repository, + fixture.validatorInventorySource, + fixture.readinessRepository); + ownerFlow.verify(fixture.transactionManager).getTransaction(any()); + ownerFlow + .verify(fixture.repository) + .readPreparedGenerationForRecovery( + accountBinding(fixture.binding), trustFence(fixture.binding)); + ownerFlow.verify(fixture.transactionManager).commit(any(TransactionStatus.class)); + ownerFlow.verify(fixture.validatorInventorySource).observe(initialObservationContext()); + ownerFlow.verify(fixture.transactionManager).getTransaction(any()); + ownerFlow + .verify(fixture.repository) + .readPreparedGenerationForRecovery( + accountBinding(fixture.binding), trustFence(fixture.binding)); + ownerFlow + .verify(fixture.readinessRepository) + .readPromotionProof( + accountBinding(fixture.binding), + trustFence(fixture.binding), + OPERATION_ID, + fixture.inventorySnapshot); + ownerFlow + .verify(fixture.repository) + .readAndMarkPreparedPromotionDispatched( + accountBinding(fixture.binding), trustFence(fixture.binding)); + ownerFlow.verify(fixture.transactionManager).commit(any(TransactionStatus.class)); + verify(fixture.transactionManager, times(2)).commit(any(TransactionStatus.class)); + } + + @Test + void authenticatedPromotionPollFailsClosedWhenNoPreparedWorkHasNoBootstrapCoordinator() + throws Exception { + Fixture fixture = fixture(); + when(fixture.repository.readPreparedGenerationForRecovery( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenThrow(new AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException()); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + response)); + + assertStatus(response.error, Status.Code.FAILED_PRECONDITION); + assertThat(response.completed).isFalse(); + verify(fixture.transactionManager).rollback(any(TransactionStatus.class)); + verify(fixture.transactionManager, never()).commit(any(TransactionStatus.class)); + } + + @Test + void promotionPollDoesNotRecordDispatchWhenOwnerReadinessProofIsMissing() throws Exception { + Fixture fixture = fixture(); + PublicJwk jwk = publicJwk(targetKid()); + PreparedGenerationEvidence prepared = preparedGenerationEvidence(fixture.binding, jwk); + when(fixture.repository.readPreparedGenerationForRecovery( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenReturn(prepared); + when(fixture.readinessRepository.readPromotionProof( + eq(accountBinding(fixture.binding)), + eq(trustFence(fixture.binding)), + eq(OPERATION_ID), + same(fixture.inventorySnapshot))) + .thenReturn(Optional.empty()); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + response)); + + assertStatus(response.error, Status.Code.FAILED_PRECONDITION); + verify(fixture.repository, never()).readAndMarkPreparedPromotionDispatched(any(), any()); + InOrder ownerFlow = + inOrder( + fixture.transactionManager, + fixture.repository, + fixture.validatorInventorySource, + fixture.readinessRepository); + ownerFlow.verify(fixture.transactionManager).getTransaction(any()); + ownerFlow + .verify(fixture.repository) + .readPreparedGenerationForRecovery( + accountBinding(fixture.binding), trustFence(fixture.binding)); + ownerFlow.verify(fixture.transactionManager).commit(any(TransactionStatus.class)); + ownerFlow.verify(fixture.validatorInventorySource).observe(initialObservationContext()); + ownerFlow.verify(fixture.transactionManager).getTransaction(any()); + ownerFlow + .verify(fixture.repository) + .readPreparedGenerationForRecovery( + accountBinding(fixture.binding), trustFence(fixture.binding)); + ownerFlow + .verify(fixture.readinessRepository) + .readPromotionProof( + accountBinding(fixture.binding), + trustFence(fixture.binding), + OPERATION_ID, + fixture.inventorySnapshot); + ownerFlow.verify(fixture.transactionManager).rollback(any(TransactionStatus.class)); + verify(fixture.transactionManager, times(1)).commit(any(TransactionStatus.class)); + } + + @Test + void promotionRequestWithoutProtectedInventorySourceDoesNotOpenSqlOrDispatch() throws Exception { + Fixture fixture = fixture(); + when(fixture.validatorInventorySourceProvider.getIfAvailable()).thenReturn(null); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + response)); + + assertStatus(response.error, Status.Code.FAILED_PRECONDITION); + verifyNoInteractions( + fixture.repository, fixture.readinessRepository, fixture.transactionManager); + } + + @Test + void explicitPromotionRequestPreparesThroughCoordinatorThenRechecksBeforeDispatch() + throws Exception { + Fixture fixture = fixture(); + PublicJwk jwk = publicJwk(targetKid()); + PreparedGenerationEvidence prepared = preparedGenerationEvidence(fixture.binding, jwk); + AccountJwtSignerBootstrapCoordinator coordinator = + mock(AccountJwtSignerBootstrapCoordinator.class); + when(fixture.bootstrapCoordinatorProvider.getIfAvailable()).thenReturn(coordinator); + when(coordinator.prepareCurrentPromotionOnce()) + .thenReturn(Optional.of(new PreparedPromotion(OPERATION_ID, "c".repeat(64), "PREPARED"))); + when(fixture.repository.readPreparedGenerationForRecovery( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenThrow(new AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException()) + .thenReturn(prepared, prepared); + when(fixture.repository.readAndMarkPreparedPromotionDispatched( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenReturn(prepared); + when(fixture.readinessRepository.readPromotionProof( + eq(accountBinding(fixture.binding)), + eq(trustFence(fixture.binding)), + eq(OPERATION_ID), + same(fixture.inventorySnapshot))) + .thenReturn(Optional.of(mock(ReadinessPromotionProof.class))); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + response)); + + assertThat(response.error).isNull(); + assertThat(response.value.getPromotionOperationId()).isEqualTo(OPERATION_ID.toString()); + InOrder ownerFlow = + inOrder( + coordinator, + fixture.validatorInventorySource, + fixture.readinessRepository, + fixture.repository); + ownerFlow.verify(coordinator).prepareCurrentPromotionOnce(); + ownerFlow.verify(fixture.validatorInventorySource).observe(initialObservationContext()); + ownerFlow + .verify(fixture.readinessRepository) + .readPromotionProof( + accountBinding(fixture.binding), + trustFence(fixture.binding), + OPERATION_ID, + fixture.inventorySnapshot); + ownerFlow + .verify(fixture.repository) + .readAndMarkPreparedPromotionDispatched( + accountBinding(fixture.binding), trustFence(fixture.binding)); + verify(fixture.repository, times(3)) + .readPreparedGenerationForRecovery( + accountBinding(fixture.binding), trustFence(fixture.binding)); + } + + @Test + void incompleteCoordinatorProofDoesNotReobserveOrDispatch() throws Exception { + Fixture fixture = fixture(); + AccountJwtSignerBootstrapCoordinator coordinator = + mock(AccountJwtSignerBootstrapCoordinator.class); + when(fixture.bootstrapCoordinatorProvider.getIfAvailable()).thenReturn(coordinator); + when(fixture.repository.readPreparedGenerationForRecovery( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenThrow(new AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException()); + when(coordinator.prepareCurrentPromotionOnce()).thenReturn(Optional.empty()); + when(fixture.repository.read(accountBinding(fixture.binding))) + .thenReturn( + new DesiredState( + accountBinding(fixture.binding), + 2, + Optional.empty(), + Optional.empty(), + Optional.of(OPERATION_ID), + Optional.empty(), + Optional.of(enrollment(fixture.binding)))); + PublicJwk recordedJwk = publicJwk(targetKid()); + GenerationRequest recorded = + generationRequest( + fixture.binding, GenerationPhase.GENERATION_RECORDED, SECRET_UID, "12", recordedJwk); + when(fixture.repository.readCurrentGenerationRequest( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenReturn(recorded); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + response)); + + assertStatus(response.error, Status.Code.FAILED_PRECONDITION); + verify(coordinator).prepareCurrentPromotionOnce(); + verify(fixture.repository) + .readCurrentGenerationRequest(accountBinding(fixture.binding), trustFence(fixture.binding)); + verify(fixture.validatorInventorySource, never()).observe(any(ObservationContext.class)); + verify(fixture.repository, never()).readAndMarkPreparedPromotionDispatched(any(), any()); + verify(fixture.readinessRepository, never()).readPromotionProof(any(), any(), any(), any()); + } + + @Test + void initialEnrollmentWithoutGenerationReturnsNotFoundOnlyAfterCoordinatorConfirmsIt() + throws Exception { + Fixture fixture = fixture(); + AccountJwtSignerBootstrapCoordinator coordinator = + mock(AccountJwtSignerBootstrapCoordinator.class); + when(fixture.bootstrapCoordinatorProvider.getIfAvailable()).thenReturn(coordinator); + when(fixture.repository.readPreparedGenerationForRecovery( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenThrow(new AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException()); + when(coordinator.prepareCurrentPromotionOnce()).thenReturn(Optional.empty()); + DesiredState initial = + new DesiredState( + accountBinding(fixture.binding), + 1, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.of(enrollment(fixture.binding))); + when(fixture.repository.read(accountBinding(fixture.binding))).thenReturn(initial); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + response)); + + assertStatus(response.error, Status.Code.NOT_FOUND); + verify(coordinator).prepareCurrentPromotionOnce(); + verify(fixture.repository).read(accountBinding(fixture.binding)); + verify(fixture.repository, never()).readCurrentGenerationRequest(any(), any()); + verify(fixture.repository, never()).readAndMarkPreparedPromotionDispatched(any(), any()); + } + + @Test + void earlyGenerationPhaseReturnsNotFoundButRecordedGenerationKeepsPrerequisiteFailure() + throws Exception { + for (GenerationPhase phase : + List.of( + GenerationPhase.OBSERVE_PRIVATE_SECRET, + GenerationPhase.GENERATE_PENDING, + GenerationPhase.GENERATION_RECORDED)) { + Fixture fixture = fixture(); + AccountJwtSignerBootstrapCoordinator coordinator = + mock(AccountJwtSignerBootstrapCoordinator.class); + when(fixture.bootstrapCoordinatorProvider.getIfAvailable()).thenReturn(coordinator); + when(fixture.repository.readPreparedGenerationForRecovery( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenThrow(new AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException()); + when(coordinator.prepareCurrentPromotionOnce()).thenReturn(Optional.empty()); + when(fixture.repository.read(accountBinding(fixture.binding))) + .thenReturn( + new DesiredState( + accountBinding(fixture.binding), + 2, + Optional.empty(), + Optional.empty(), + Optional.of(OPERATION_ID), + Optional.empty(), + Optional.of(enrollment(fixture.binding)))); + boolean observedSecret = phase != GenerationPhase.OBSERVE_PRIVATE_SECRET; + PublicJwk recordedJwk = + phase == GenerationPhase.GENERATION_RECORDED ? publicJwk(targetKid()) : null; + GenerationRequest current = + generationRequest( + fixture.binding, + phase, + observedSecret ? SECRET_UID : "", + observedSecret ? "12" : "", + recordedJwk); + when(fixture.repository.readCurrentGenerationRequest( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenReturn(current); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + response)); + + assertStatus( + response.error, + phase == GenerationPhase.GENERATION_RECORDED + ? Status.Code.FAILED_PRECONDITION + : Status.Code.NOT_FOUND); + verify(fixture.repository) + .readCurrentGenerationRequest( + accountBinding(fixture.binding), trustFence(fixture.binding)); + verify(fixture.repository, never()).readAndMarkPreparedPromotionDispatched(any(), any()); + } + } + + @Test + void promotionRequestDoesNotDispatchWhenSnapshotBoundProofIsUnavailable() throws Exception { + Fixture fixture = fixture(); + PublicJwk jwk = publicJwk(targetKid()); + PreparedGenerationEvidence prepared = + preparedGenerationEvidence( + fixture.binding, jwk, Optional.of(new ActiveSigner("1", "old-active-key")), "2"); + when(fixture.repository.readPreparedGenerationForRecovery( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenReturn(prepared); + when(fixture.readinessRepository.readPromotionProof( + eq(accountBinding(fixture.binding)), + eq(trustFence(fixture.binding)), + eq(OPERATION_ID), + same(fixture.inventorySnapshot))) + .thenReturn(Optional.empty()); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + response)); + + assertStatus(response.error, Status.Code.FAILED_PRECONDITION); + verify(fixture.readinessRepository) + .readPromotionProof( + accountBinding(fixture.binding), + trustFence(fixture.binding), + OPERATION_ID, + fixture.inventorySnapshot); + verify(fixture.repository, never()).readAndMarkPreparedPromotionDispatched(any(), any()); + InOrder ownerFlow = + inOrder( + fixture.transactionManager, + fixture.repository, + fixture.validatorInventorySource, + fixture.readinessRepository); + ownerFlow.verify(fixture.transactionManager).getTransaction(any()); + ownerFlow + .verify(fixture.repository) + .readPreparedGenerationForRecovery( + accountBinding(fixture.binding), trustFence(fixture.binding)); + ownerFlow.verify(fixture.transactionManager).commit(any(TransactionStatus.class)); + ownerFlow.verify(fixture.validatorInventorySource).observe(strictObservationContext()); + ownerFlow.verify(fixture.transactionManager).getTransaction(any()); + ownerFlow + .verify(fixture.repository) + .readPreparedGenerationForRecovery( + accountBinding(fixture.binding), trustFence(fixture.binding)); + ownerFlow + .verify(fixture.readinessRepository) + .readPromotionProof( + accountBinding(fixture.binding), + trustFence(fixture.binding), + OPERATION_ID, + fixture.inventorySnapshot); + ownerFlow.verify(fixture.transactionManager).rollback(any(TransactionStatus.class)); + verify(fixture.transactionManager, times(1)).commit(any(TransactionStatus.class)); + } + + @Test + void promotionDispatchRejectsActiveFenceChangedAfterInitialCandidateObservation() + throws Exception { + Fixture fixture = fixture(); + PublicJwk jwk = publicJwk(targetKid()); + PreparedGenerationEvidence initial = preparedGenerationEvidence(fixture.binding, jwk); + PreparedGenerationEvidence active = + preparedGenerationEvidence( + fixture.binding, jwk, Optional.of(new ActiveSigner("1", "old-active-key")), "2"); + when(fixture.repository.readPreparedGenerationForRecovery( + eq(accountBinding(fixture.binding)), eq(trustFence(fixture.binding)))) + .thenReturn(initial, active); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + response)); + + assertStatus(response.error, Status.Code.FAILED_PRECONDITION); + verify(fixture.validatorInventorySource).observe(initialObservationContext()); + verify(fixture.readinessRepository, never()).readPromotionProof(any(), any(), any(), any()); + verify(fixture.repository, never()).readAndMarkPreparedPromotionDispatched(any(), any()); + } + + @Test + void serviceCallsWithoutInterceptorContextAreDeniedEvenWithBearerHeader() { + Fixture fixture = fixture(); + RecordingObserver response = new RecordingObserver<>(); + Metadata headers = new Metadata(); + headers.put( + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer caller-controlled-header"); + + fixture.service.getCurrentGenerationRequest( + GetCurrentGenerationRequestRequest.newBuilder().setSchemaVersion(1).build(), response); + + assertStatus(response.error, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(fixture.repository, fixture.transactionManager); + verify(fixture.trustBindingProvider).current(); + } + + @Test + void malformedSchemaFailsBeforeTrustLookupOrTransaction() { + Fixture fixture = fixture(); + RecordingObserver response = new RecordingObserver<>(); + + fixture.service.getCurrentGenerationRequest( + GetCurrentGenerationRequestRequest.getDefaultInstance(), response); + + assertStatus(response.error, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions( + fixture.repository, fixture.transactionManager, fixture.trustBindingProvider); + } + + @Test + void changedProtectedTrustBeforeCommitRollsBackSecretObservation() throws Exception { + Fixture fixture = fixture(); + Binding changedBinding = trustBinding("revision-2", sha256("replacement materializer key")); + when(fixture.trustBindingProvider.current()) + .thenReturn( + Optional.of(fixture.binding), + Optional.of(fixture.binding), + Optional.of(changedBinding)); + when(fixture.repository.recordSecretObservation(any(), any(), any(), any(), any(), any())) + .thenReturn( + generationRequest( + fixture.binding, GenerationPhase.GENERATE_PENDING, SECRET_UID, "12", null)); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.recordSecretObservation( + RecordSecretObservationRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(OPERATION_ID.toString()) + .setOperationDigest(OPERATION_DIGEST) + .setSecretUid(SECRET_UID) + .setObservedResourceVersion("12") + .build(), + response)); + + assertStatus(response.error, Status.Code.PERMISSION_DENIED); + assertThat(response.completed).isFalse(); + verify(fixture.repository).recordSecretObservation(any(), any(), any(), any(), any(), any()); + verify(fixture.transactionManager).rollback(any(TransactionStatus.class)); + verify(fixture.transactionManager, never()).commit(any(TransactionStatus.class)); + } + + @Test + void staleOperationAndConflictingReadbackFailClosed() throws Exception { + Fixture staleFixture = fixture(); + when(staleFixture.repository.recordSecretObservation(any(), any(), any(), any(), any(), any())) + .thenThrow( + new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "stale operation")); + RecordingObserver staleResponse = + new RecordingObserver<>(); + invokeWithAuthenticatedPeer( + staleFixture, + () -> staleFixture.service.recordSecretObservation(observationRequest(), staleResponse)); + assertStatus(staleResponse.error, Status.Code.FAILED_PRECONDITION); + verify(staleFixture.transactionManager).rollback(any(TransactionStatus.class)); + + Fixture conflictFixture = fixture(); + when(conflictFixture.repository.recordSecretObservation( + any(), any(), any(), any(), any(), any())) + .thenThrow( + new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "changed observation")); + RecordingObserver conflictResponse = + new RecordingObserver<>(); + invokeWithAuthenticatedPeer( + conflictFixture, + () -> + conflictFixture.service.recordSecretObservation( + observationRequest(), conflictResponse)); + assertStatus(conflictResponse.error, Status.Code.ALREADY_EXISTS); + verify(conflictFixture.transactionManager).rollback(any(TransactionStatus.class)); + } + + @Test + void exactOperationIdMustBeCanonicalUuidV4() throws Exception { + Fixture fixture = fixture(); + RecordingObserver response = new RecordingObserver<>(); + + invokeWithAuthenticatedPeer( + fixture, + () -> + fixture.service.recordSecretObservation( + RecordSecretObservationRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId("not-a-uuid") + .build(), + response)); + + assertStatus(response.error, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(fixture.repository, fixture.transactionManager); + } + + @SuppressWarnings("unchecked") + private static Fixture fixture() { + try { + Binding binding = trustBinding("revision-1", sha256(PEER_SPKI)); + AccountJwtSignerMaterializerTrustBinding trustBindingProvider = + mock(AccountJwtSignerMaterializerTrustBinding.class); + when(trustBindingProvider.current()).thenReturn(Optional.of(binding)); + AccountJwtSignerDesiredStateRepository repository = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtReadinessProbeRepository readinessRepository = + mock(AccountJwtReadinessProbeRepository.class); + ObjectProvider validatorInventorySourceProvider = + mock(ObjectProvider.class); + ObjectProvider bootstrapCoordinatorProvider = + mock(ObjectProvider.class); + AccountJwtValidatorInventorySource validatorInventorySource = + mock(AccountJwtValidatorInventorySource.class); + InventorySnapshot inventorySnapshot = mock(InventorySnapshot.class); + when(validatorInventorySourceProvider.getIfAvailable()).thenReturn(validatorInventorySource); + when(validatorInventorySource.observe(any(ObservationContext.class))) + .thenReturn(inventorySnapshot); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any())) + .thenAnswer(invocation -> new SimpleTransactionStatus()); + AccountJwtSignerMaterializationService service = + new AccountJwtSignerMaterializationService( + repository, + readinessRepository, + trustBindingProvider, + transactionManager, + bootstrapCoordinatorProvider, + validatorInventorySourceProvider); + AccountJwtSignerMaterializerTlsInterceptor interceptor = + new AccountJwtSignerMaterializerTlsInterceptor(trustBindingProvider); + return new Fixture( + binding, + trustBindingProvider, + repository, + readinessRepository, + bootstrapCoordinatorProvider, + validatorInventorySourceProvider, + validatorInventorySource, + inventorySnapshot, + transactionManager, + service, + interceptor); + } catch (Exception ex) { + throw new IllegalStateException("JWT materializer service test fixture failed", ex); + } + } + + private static Binding trustBinding(String revision, String pin) { + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, + "prod", + "prod-cluster-1", + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + PEER_URI, + List.of(pin)); + return new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + PEER_URI, + List.of(pin), + revision, + digest); + } + + private static AccountJwtSignerDesiredStateRepository.Binding accountBinding(Binding binding) { + return new AccountJwtSignerDesiredStateRepository.Binding( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private static GenerationRequest generationRequest( + Binding binding, + GenerationPhase phase, + String secretUid, + String resourceVersion, + PublicJwk jwk) { + String generationRequestDigest = + phase == GenerationPhase.OBSERVE_PRIVATE_SECRET ? "" : GENERATION_REQUEST_DIGEST; + boolean recorded = phase == GenerationPhase.GENERATION_RECORDED; + return new GenerationRequest( + phase, + OPERATION_ID, + OPERATION_DIGEST, + generationRequestDigest, + 2, + accountBinding(binding), + trustFence(binding), + "jwt-signing-keys", + "1", + targetKid(), + "RS256", + "MATERIALIZE_PENDING", + List.of("pending"), + Optional.empty(), + Optional.empty(), + secretUid, + resourceVersion, + recorded ? RECEIPT_DIGEST : "", + recorded ? jwk.fingerprint() : "", + recorded ? jwk.json() : "", + recorded ? "13" : ""); + } + + private static GenerationResult generationResult(Binding binding, PublicJwk jwk) { + return generationResult(binding, jwk, "1"); + } + + private static GenerationResult generationResult( + Binding binding, PublicJwk jwk, String targetGeneration) { + return new GenerationResult( + OPERATION_ID, + accountBinding(binding), + OPERATION_DIGEST, + GENERATION_REQUEST_DIGEST, + 2, + trustFence(binding), + "jwt-signing-keys", + SECRET_UID, + "12", + "13", + targetGeneration, + targetKid(), + "RS256", + jwk.fingerprint(), + jwk.json(), + RECEIPT_DIGEST); + } + + private static PreparedGenerationEvidence preparedGenerationEvidence( + Binding binding, PublicJwk jwk) { + return preparedGenerationEvidence(binding, jwk, Optional.empty(), "1"); + } + + private static EnrollmentIdentity enrollment(Binding binding) { + return new EnrollmentIdentity( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision(), + "e".repeat(64), + "api-revision-1", + "55555555-5555-4555-8555-555555555555", + "44", + "f".repeat(64)); + } + + private static PreparedGenerationEvidence preparedGenerationEvidence( + Binding binding, + PublicJwk jwk, + Optional expectedActive, + String targetGeneration) { + AccountJwtSignerDesiredStateRepository.Binding accountBinding = accountBinding(binding); + TrustFence trustFence = trustFence(binding); + EnrollmentIdentity enrollment = + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + OPERATION_DIGEST, + "revision-1", + "e".repeat(64), + "api-revision-1", + "55555555-5555-4555-8555-555555555555", + "44", + "f".repeat(64)); + DesiredState desiredState = + new DesiredState( + accountBinding, + 3, + expectedActive, + expectedActive, + Optional.empty(), + Optional.of(OPERATION_ID), + Optional.of(enrollment)); + PromotionOperationEvidence promotion = + new PromotionOperationEvidence( + OPERATION_ID, + "a".repeat(64), + 2, + accountBinding, + expectedActive, + expectedActive.map(ignored -> "6".repeat(64)), + expectedActive, + targetGeneration, + targetKid(), + "RS256", + jwk.fingerprint(), + trustFence, + OPERATION_ID, + OPERATION_DIGEST, + RECEIPT_DIGEST, + SECRET_UID, + "13", + "e".repeat(64), + "api-revision-1", + "55555555-5555-4555-8555-555555555555", + "44", + "1".repeat(64), + "2".repeat(64), + "3".repeat(64), + "4".repeat(64), + "5".repeat(64), + jwk.json(), + "{}", + "PREPARED", + false, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); + return new PreparedGenerationEvidence( + desiredState, promotion, generationResult(binding, jwk, targetGeneration)); + } + + private static ObservationContext initialObservationContext() { + return new ObservationContext( + ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES, OPERATION_ID, OPERATION_DIGEST); + } + + private static ObservationContext strictObservationContext() { + return new ObservationContext(ObservationPurpose.STRICT_READY, OPERATION_ID, OPERATION_DIGEST); + } + + private static RecordSecretObservationRequest observationRequest() { + return RecordSecretObservationRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(OPERATION_ID.toString()) + .setOperationDigest(OPERATION_DIGEST) + .setSecretUid(SECRET_UID) + .setObservedResourceVersion("12") + .build(); + } + + private static PublicJwk publicJwk(String kid) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + RSAPublicKey key = (RSAPublicKey) generator.generateKeyPair().getPublic(); + String modulus = encodeUnsigned(key.getModulus()); + String exponent = encodeUnsigned(key.getPublicExponent()); + Map jwk = new LinkedHashMap<>(); + jwk.put("alg", "RS256"); + jwk.put("e", exponent); + jwk.put("key_ops", List.of("verify")); + jwk.put("kid", kid); + jwk.put("kty", "RSA"); + jwk.put("n", modulus); + jwk.put("use", "sig"); + String json = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(jwk)), + StandardCharsets.UTF_8); + String fingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder() + .build() + .writeValueAsString( + Map.of("e", exponent, "kty", "RSA", "n", modulus))))); + return new PublicJwk(kid, json, fingerprint); + } + + private static String targetKid() { + return "jwt-1-" + OPERATION_ID.toString().substring(0, 12); + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return java.util.Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + private static void invokeWithAuthenticatedPeer(Fixture fixture, Runnable rpcInvocation) + throws Exception { + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + SSLSession sslSession = mock(SSLSession.class); + java.security.cert.X509Certificate certificate = mock(java.security.cert.X509Certificate.class); + PublicKey publicKey = mock(PublicKey.class); + when(publicKey.getEncoded()).thenReturn(PEER_SPKI); + when(certificate.getPublicKey()).thenReturn(publicKey); + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, PEER_URI))); + when(sslSession.getPeerCertificates()) + .thenReturn(new java.security.cert.Certificate[] {certificate}); + when(call.getAttributes()) + .thenReturn( + Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession).build()); + ServerCallHandler next = + (interceptedCall, headers) -> { + assertThat(AccountJwtSignerMaterializerTlsInterceptor.authenticatedBinding()) + .isEqualTo(fixture.binding); + rpcInvocation.run(); + return new ServerCall.Listener<>() {}; + }; + + fixture.interceptor.interceptCall(call, new Metadata(), next); + } + + private static String sha256(byte[] value) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static String sha256(String value) throws Exception { + return sha256(value.getBytes(StandardCharsets.US_ASCII)); + } + + private static void assertStatus(ErrorDiagnostic failure, Status.Code expected) { + assertThat(failure.exceptionType()).isEqualTo(StatusRuntimeException.class.getName()); + assertThat(failure.code()).isEqualTo(expected); + } + + private record ErrorDiagnostic(String exceptionType, Status.Code code) {} + + private record PublicJwk(String kid, String json, String fingerprint) {} + + private record Fixture( + Binding binding, + AccountJwtSignerMaterializerTrustBinding trustBindingProvider, + AccountJwtSignerDesiredStateRepository repository, + AccountJwtReadinessProbeRepository readinessRepository, + ObjectProvider bootstrapCoordinatorProvider, + ObjectProvider validatorInventorySourceProvider, + AccountJwtValidatorInventorySource validatorInventorySource, + InventorySnapshot inventorySnapshot, + PlatformTransactionManager transactionManager, + AccountJwtSignerMaterializationService service, + AccountJwtSignerMaterializerTlsInterceptor interceptor) {} + + private static final class RecordingObserver implements StreamObserver { + private T value; + private ErrorDiagnostic error; + private boolean completed; + + @Override + public void onNext(T value) { + this.value = value; + } + + @Override + public void onError(Throwable error) { + Status.Code code = + error instanceof StatusRuntimeException statusFailure + ? statusFailure.getStatus().getCode() + : Status.fromThrowable(error).getCode(); + this.error = new ErrorDiagnostic(error.getClass().getName(), code); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationServiceTest.java new file mode 100644 index 0000000000..37754d6592 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationServiceTest.java @@ -0,0 +1,731 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.MountObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PromotionPublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.Outcome; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtJwksPrepublicationServiceTest { + private static final UUID OPERATION_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String MATERIALIZER_URI = + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + private static final String OPERATION_DIGEST = "a".repeat(64); + private static final String REQUEST_DIGEST = "b".repeat(64); + private static final String RECEIPT_DIGEST = "c".repeat(64); + private static final String API_DIGEST = "d".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void currentGenerationIsPrepublishedWithRetainedKeysAndExactAccountReadbackOnly() + throws Exception { + Fixture fixture = fixture("{\"keys\":[]}", "41"); + fixture.stubCurrentGeneration(); + when(fixture.publicationRepository.readCurrentPublication( + eq(accountBinding()), eq(trustFence(fixture.binding)))) + .thenReturn(Optional.empty()); + when(fixture.client.observe()).thenReturn(fixture.snapshot); + when(fixture.client.publish(eq(fixture.snapshot), anyMap())) + .thenAnswer( + invocation -> { + Map desired = invocation.getArgument(1); + Map readback = new LinkedHashMap<>(desired); + readback.put("unrelated.txt", "preserved"); + return new CasObservation( + CONFIG_MAP_UID, "41", "42", desired, readback, Outcome.APPLIED); + }); + when(fixture.publicationRepository.recordPrepublicationIntent( + eq(accountBinding()), + eq(trustFence(fixture.binding)), + eq(fixture.result), + eq(fixture.request), + eq(API_DIGEST), + eq("api-r1"), + eq(CONFIG_MAP_UID), + eq("41"), + any(String.class), + any(String.class), + any(String.class))) + .thenAnswer( + invocation -> + intent( + fixture, + invocation.getArgument(9), + invocation.getArgument(10), + invocation.getArgument(7), + invocation.getArgument(8))); + when(fixture.publicationRepository.recordPublicationReceipt( + eq(accountBinding()), + eq(trustFence(fixture.binding)), + eq(OPERATION_ID), + eq(API_DIGEST), + eq("api-r1"), + eq(CONFIG_MAP_UID), + eq("42"), + any(String.class), + any(String.class))) + .thenAnswer( + invocation -> + PublicationReceipt.create( + intent( + fixture, + invocation.getArgument(7), + invocation.getArgument(8), + "41", + AccountJwtJwksPublicationRepository.snapshotDigest( + fixture.snapshot.data())), + invocation.getArgument(6))); + + PublicationReceipt receipt = fixture.service.prepublishCurrentGeneration(); + + assertThat(receipt.operationId()).isEqualTo(OPERATION_ID); + ArgumentCaptor jwksJson = ArgumentCaptor.forClass(String.class); + ArgumentCaptor generationMarkerJson = ArgumentCaptor.forClass(String.class); + verify(fixture.publicationRepository) + .recordPrepublicationIntent( + eq(accountBinding()), + eq(trustFence(fixture.binding)), + eq(fixture.result), + eq(fixture.request), + eq(API_DIGEST), + eq("api-r1"), + eq(CONFIG_MAP_UID), + eq("41"), + any(String.class), + jwksJson.capture(), + generationMarkerJson.capture()); + PrepublicationIntent expectedIntent = + intent( + fixture, + jwksJson.getValue(), + generationMarkerJson.getValue(), + "41", + AccountJwtJwksPublicationRepository.snapshotDigest(fixture.snapshot.data())); + assertThat(receipt.intentDigest()).isEqualTo(expectedIntent.intentDigest()); + assertThat(receipt.expectedResourceVersion()).isEqualTo("41"); + assertThat(receipt.observedResourceVersion()).isEqualTo("42"); + assertThat(receipt.publicDataDigest()) + .isEqualTo( + AccountJwtJwksPublicationRepository.publicDataDigest( + jwksJson.getValue(), generationMarkerJson.getValue())); + verify(fixture.client).publish(eq(fixture.snapshot), anyMap()); + verify(fixture.publicationRepository) + .recordPublicationReceipt( + eq(accountBinding()), + eq(trustFence(fixture.binding)), + eq(OPERATION_ID), + eq(API_DIGEST), + eq("api-r1"), + eq(CONFIG_MAP_UID), + eq("42"), + any(String.class), + any(String.class)); + verify(fixture.desiredRepository, never()).prepareCurrentGeneration(any(), any(), any(), any()); + assertThat(fixture.transactionManager.commits).isEqualTo(3); + assertThat(fixture.transactionManager.rollbacks).isZero(); + } + + @Test + void wrongApiClusterOrNamespaceBindingFailsBeforeCurrentStateOrRemoteAccess() throws Exception { + Fixture fixture = fixture("{\"keys\":[]}", "41"); + BindingIdentity wrongApi = + new BindingIdentity( + API_DIGEST, + "api-r1", + "prod", + "different-cluster", + "other-namespace", + CLUSTER_UID, + NAMESPACE_UID, + "https://api.example.test", + "api.example.test", + "f".repeat(64), + "system:serviceaccount:other-namespace:account-service"); + when(fixture.client.identity()).thenReturn(wrongApi); + + assertThatThrownBy(fixture.service::prepublishCurrentGeneration) + .isInstanceOf(AccountJwtJwksPrepublicationService.PublicationRejectedException.class) + .hasMessageContaining("bindings disagree"); + + verifyNoInteractions(fixture.desiredRepository, fixture.publicationRepository); + verify(fixture.client, never()).observe(); + verify(fixture.client, never()).publish(any(), anyMap()); + } + + @Test + void preparedCurrentKeyProofFailsClosedUntilProjectedSecretAndPublicFilesCatchUp( + @TempDir Path temporaryDirectory) throws Exception { + Fixture fixture = fixture("{\"keys\":[]}", "41"); + String desiredJwks = "{\"keys\":[" + fixture.result.publicJwkJson() + "]}"; + String prepublishedMarker = marker(); + PrepublicationIntent intent = + intent( + fixture, + desiredJwks, + prepublishedMarker, + "41", + AccountJwtJwksPublicationRepository.snapshotDigest(fixture.snapshot.data())); + PublicationReceipt receipt = PublicationReceipt.create(intent, "42"); + MountObservation mounted = MountObservation.create(intent, receipt); + when(fixture.publicationRepository.readPreparedPublicationForRecovery( + eq(accountBinding()), eq(trustFence(fixture.binding)))) + .thenReturn(new PromotionPublicationEvidence(intent, receipt, mounted)); + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + when(promotion.status()).thenReturn("PREPARED"); + when(promotion.privatePromotionDispatched()).thenReturn(true); + when(promotion.privatePromotionReceiptDigest()).thenReturn(Optional.of("8".repeat(64))); + when(promotion.expectedPreviousActive()).thenReturn(Optional.empty()); + when(promotion.expectedPublishedActive()).thenReturn(Optional.empty()); + when(promotion.binding()).thenReturn(accountBinding()); + when(promotion.trustFence()).thenReturn(trustFence(fixture.binding)); + when(promotion.apiBindingDigest()).thenReturn(API_DIGEST); + when(promotion.apiConfigRevision()).thenReturn("api-r1"); + when(promotion.generationOperationId()).thenReturn(OPERATION_ID); + when(promotion.prepublicationIntentDigest()).thenReturn(intent.intentDigest()); + when(promotion.prepublicationReceiptDigest()).thenReturn(receipt.receiptDigest()); + when(promotion.publicConfigMapUid()).thenReturn(CONFIG_MAP_UID); + when(promotion.expectedPublicResourceVersion()).thenReturn("42"); + when(promotion.expectedPublicJwksJson()).thenReturn(desiredJwks); + when(promotion.expectedActiveMarkerJson()).thenReturn("{\"phase\":\"ACTIVE\"}"); + when(promotion.activeJwksReceiptDigest()).thenReturn(Optional.empty()); + when(promotion.targetGeneration()).thenReturn(fixture.result.targetGeneration()); + when(promotion.targetKid()).thenReturn(fixture.result.targetKid()); + when(promotion.targetPublicKeyFingerprint()).thenReturn(fixture.result.publicKeyFingerprint()); + when(fixture.client.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "42", + Map.of( + "jwks.json", desiredJwks, + "jwt-generation.json", prepublishedMarker, + "unrelated.txt", "preserved"))); + + Path privateMount = Files.createDirectory(temporaryDirectory.resolve("private-mount")); + Path publicMount = Files.createDirectory(temporaryDirectory.resolve("public-mount")); + Files.writeString(publicMount.resolve("jwks.json"), desiredJwks, StandardCharsets.UTF_8); + Files.writeString( + publicMount.resolve("jwt-generation.json"), prepublishedMarker, StandardCharsets.UTF_8); + AccountJwtJwksPrepublicationService mountedService = + new AccountJwtJwksPrepublicationService( + fixture.desiredRepository, + fixture.publicationRepository, + fixture.trustBindingProvider, + fixture.client, + fixture.transactionManager, + new AccountJwtJwksPrepublicationService.MountedProjection( + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json"), + Path.of("jwt-generation.json"))); + + assertThatThrownBy(() -> mountedService.observePreparedCurrentKeyCorrespondence(promotion)) + .isInstanceOf(AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class); + + verify(fixture.client).observe(); + verify(fixture.client, never()).publish(any(), anyMap()); + } + + @Test + void withdrawnProtectedBindingBeforeTransactionCommitRollsBackWithoutRemoteWrite() + throws Exception { + Fixture fixture = fixture("{\"keys\":[]}", "41"); + Binding changed = trustBinding("trust-r2"); + when(fixture.trustBindingProvider.current()) + .thenReturn(Optional.of(fixture.binding), Optional.of(changed)); + fixture.stubCurrentGeneration(); + when(fixture.publicationRepository.readCurrentPublication( + eq(accountBinding()), eq(trustFence(fixture.binding)))) + .thenReturn(Optional.empty()); + + assertThatThrownBy(fixture.service::prepublishCurrentGeneration) + .isInstanceOf(AccountJwtJwksPrepublicationService.PublicationRejectedException.class) + .hasMessageContaining("trust changed"); + + assertThat(fixture.transactionManager.commits).isZero(); + assertThat(fixture.transactionManager.rollbacks).isEqualTo(1); + verify(fixture.client, never()).observe(); + verify(fixture.client, never()).publish(any(), anyMap()); + verify(fixture.publicationRepository, never()) + .recordPrepublicationIntent( + any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void malformedExistingJwksCannotCreateIntentOrReachConfigMapCas() throws Exception { + Fixture fixture = fixture("{\"keys\":[] , \"unexpected\":true}", "41"); + fixture.stubCurrentGeneration(); + when(fixture.publicationRepository.readCurrentPublication( + eq(accountBinding()), eq(trustFence(fixture.binding)))) + .thenReturn(Optional.empty()); + when(fixture.client.observe()).thenReturn(fixture.snapshot); + + assertThatThrownBy(fixture.service::prepublishCurrentGeneration) + .isInstanceOf(AccountJwtJwksPrepublicationService.PublicationRejectedException.class) + .hasMessageContaining("unsupported shape"); + + verify(fixture.publicationRepository, never()) + .recordPrepublicationIntent( + any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(fixture.client, never()).publish(any(), anyMap()); + } + + @Test + void existingIntentCannotOverwriteChangedSameNameConfigMap() throws Exception { + Fixture fixture = fixture("{\"keys\":[]}", "42"); + fixture.stubCurrentGeneration(); + PrepublicationIntent intent = + intent( + fixture, + "{\"keys\":[]}", + marker(), + "41", + AccountJwtJwksPublicationRepository.snapshotDigest(fixture.snapshot.data())); + when(fixture.publicationRepository.readCurrentPublication( + eq(accountBinding()), eq(trustFence(fixture.binding)))) + .thenReturn( + Optional.of(new PublicationEvidence(intent, Optional.empty(), Optional.empty()))); + when(fixture.client.observe()).thenReturn(fixture.snapshot); + + assertThatThrownBy(fixture.service::prepublishCurrentGeneration) + .isInstanceOf(AccountJwtJwksPrepublicationService.PublicationRejectedException.class) + .hasMessageContaining("changed after immutable intent"); + + verify(fixture.client, never()).publish(any(), anyMap()); + verify(fixture.publicationRepository, never()) + .recordPublicationReceipt(any(), any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void exactRemoteApplyWithoutReceiptIsRecoveredAgainstOriginalResourceVersion() throws Exception { + String desiredJwks = "{\"keys\":[]}"; + String marker = marker(); + Map advancedData = + Map.of( + "jwks.json", desiredJwks, + "jwt-generation.json", marker, + "unrelated.txt", "preserved"); + Fixture fixture = fixture(desiredJwks, "42"); + fixture.stubCurrentGeneration(); + PrepublicationIntent intent = + intent( + fixture, + desiredJwks, + marker, + "41", + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", "{\"keys\":[]}", "unrelated.txt", "preserved"))); + when(fixture.publicationRepository.readCurrentPublication( + eq(accountBinding()), eq(trustFence(fixture.binding)))) + .thenReturn( + Optional.of(new PublicationEvidence(intent, Optional.empty(), Optional.empty()))); + when(fixture.client.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "42", advancedData)); + Map desiredData = + Map.of("jwks.json", desiredJwks, "jwt-generation.json", marker); + when(fixture.client.publish( + eq(new ConfigMapSnapshot(CONFIG_MAP_UID, "41", advancedData)), eq(desiredData))) + .thenReturn( + new CasObservation( + CONFIG_MAP_UID, "41", "42", desiredData, advancedData, Outcome.EXACT_REPLAY)); + when(fixture.publicationRepository.recordPublicationReceipt( + eq(accountBinding()), + eq(trustFence(fixture.binding)), + eq(OPERATION_ID), + eq(API_DIGEST), + eq("api-r1"), + eq(CONFIG_MAP_UID), + eq("42"), + eq(desiredJwks), + eq(marker))) + .thenReturn( + PublicationReceipt.create( + intent( + fixture, + desiredJwks, + marker, + "41", + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", "{\"keys\":[]}", "unrelated.txt", "preserved"))), + "42")); + + PublicationReceipt receipt = fixture.service.prepublishCurrentGeneration(); + + assertThat(receipt.expectedResourceVersion()).isEqualTo("41"); + assertThat(receipt.observedResourceVersion()).isEqualTo("42"); + verify(fixture.client) + .publish(eq(new ConfigMapSnapshot(CONFIG_MAP_UID, "41", advancedData)), eq(desiredData)); + verify(fixture.publicationRepository, never()) + .recordPrepublicationIntent( + any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(fixture.publicationRepository) + .recordPublicationReceipt( + eq(accountBinding()), + eq(trustFence(fixture.binding)), + eq(OPERATION_ID), + eq(API_DIGEST), + eq("api-r1"), + eq(CONFIG_MAP_UID), + eq("42"), + eq(desiredJwks), + eq(marker)); + verify(fixture.desiredRepository, never()).prepareCurrentGeneration(any(), any(), any(), any()); + } + + @Test + void exactBytesAtUnadvancedOriginalResourceVersionDoNotCreateReceipt() throws Exception { + String desiredJwks = "{\"keys\":[]}"; + String marker = marker(); + Map unchangedData = + Map.of( + "jwks.json", desiredJwks, + "jwt-generation.json", marker, + "unrelated.txt", "preserved"); + Fixture fixture = fixture(desiredJwks, "41"); + fixture.stubCurrentGeneration(); + PrepublicationIntent intent = + intent( + fixture, + desiredJwks, + marker, + "41", + AccountJwtJwksPublicationRepository.snapshotDigest(fixture.snapshot.data())); + when(fixture.publicationRepository.readCurrentPublication( + eq(accountBinding()), eq(trustFence(fixture.binding)))) + .thenReturn( + Optional.of(new PublicationEvidence(intent, Optional.empty(), Optional.empty()))); + when(fixture.client.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "41", unchangedData)); + when(fixture.client.publish(any(), anyMap())) + .thenThrow(new AccountJwtJwksConfigMapClient.CasConflictException(CONFIG_MAP_UID, "41")); + + assertThatThrownBy(fixture.service::prepublishCurrentGeneration) + .isInstanceOf(AccountJwtJwksConfigMapClient.CasConflictException.class); + + verify(fixture.publicationRepository, never()) + .recordPrepublicationIntent( + any(), any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(fixture.publicationRepository, never()) + .recordPublicationReceipt(any(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(fixture.desiredRepository, never()).prepareCurrentGeneration(any(), any(), any(), any()); + } + + private static Fixture fixture(String jwks, String resourceVersion) throws Exception { + Binding binding = trustBinding("trust-r1"); + GenerationKeys keys = generationKeys(); + AccountJwtSignerDesiredStateRepository desiredRepository = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository publicationRepository = + mock(AccountJwtJwksPublicationRepository.class); + AccountJwtSignerMaterializerTrustBinding trustProvider = + mock(AccountJwtSignerMaterializerTrustBinding.class); + when(trustProvider.current()).thenReturn(Optional.of(binding)); + AccountJwtJwksConfigMapClient client = mock(AccountJwtJwksConfigMapClient.class); + when(client.identity()).thenReturn(apiIdentity()); + ConfigMapSnapshot snapshot = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + resourceVersion, + Map.of("jwks.json", jwks, "unrelated.txt", "preserved")); + RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + AccountJwtJwksPrepublicationService service = + new AccountJwtJwksPrepublicationService( + desiredRepository, + publicationRepository, + trustProvider, + client, + transactionManager, + new AccountJwtJwksPrepublicationService.MountedProjection( + java.nio.file.Path.of("/tmp/private"), + java.nio.file.Path.of("pending.key"), + java.nio.file.Path.of("/tmp/public"), + java.nio.file.Path.of("jwks.json"), + java.nio.file.Path.of("jwt-generation.json"))); + return new Fixture( + binding, + desiredRepository, + publicationRepository, + trustProvider, + client, + transactionManager, + service, + snapshot, + keys.result(), + keys.request()); + } + + private static void stubCurrentGeneration(Fixture fixture) { + when(fixture.desiredRepository.readCurrentGenerationResult( + eq(accountBinding()), eq(trustFence(fixture.binding)))) + .thenReturn(fixture.result); + when(fixture.desiredRepository.readCurrentGenerationRequest( + eq(accountBinding()), eq(trustFence(fixture.binding)))) + .thenReturn(fixture.request); + } + + private static PrepublicationIntent intent( + Fixture fixture, + String jwks, + String marker, + String expectedResourceVersion, + String expectedSnapshotDigest) + throws Exception { + return PrepublicationIntent.create( + OPERATION_ID, + accountBinding(), + fixture.result.operationDigest(), + fixture.result.generationRequestDigest(), + fixture.result.receiptDigest(), + fixture.result.desiredStateVersion(), + fixture.result.trustFence(), + API_DIGEST, + "api-r1", + "jwt-jwks", + CONFIG_MAP_UID, + expectedResourceVersion, + expectedSnapshotDigest, + fixture.result.targetGeneration(), + fixture.result.targetKid(), + fixture.result.publicKeyFingerprint(), + fixture.request.expectedActive(), + fixture.request.expectedPublishedActive(), + jwks, + marker, + AccountJwtJwksPublicationRepository.publicDataDigest(jwks, marker), + sha256(marker.getBytes(StandardCharsets.UTF_8))); + } + + private static String marker() { + return "{\"phase\":\"PREPUBLISHED\"}"; + } + + private static Binding trustBinding(String revision) { + String peerPin = "e".repeat(64); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, + "prod", + "prod-cluster-1", + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + List.of(peerPin)); + return new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + List.of(peerPin), + revision, + digest); + } + + private static BindingIdentity apiIdentity() { + return new BindingIdentity( + API_DIGEST, + "api-r1", + "prod", + "prod-cluster-1", + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + "https://api.firemud.test", + "api.firemud.test", + "f".repeat(64), + "system:serviceaccount:firemud-prod:account-service"); + } + + private static AccountJwtSignerDesiredStateRepository.Binding accountBinding() { + return new AccountJwtSignerDesiredStateRepository.Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private static GenerationKeys generationKeys() throws Exception { + UUID operationId = OPERATION_ID; + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + RSAPublicKey publicKey = (RSAPublicKey) generator.generateKeyPair().getPublic(); + String modulus = encodeUnsigned(publicKey.getModulus()); + String exponent = encodeUnsigned(publicKey.getPublicExponent()); + String kid = "jwt-1-444444444444"; + Map jwkMap = new LinkedHashMap<>(); + jwkMap.put("kty", "RSA"); + jwkMap.put("use", "sig"); + jwkMap.put("alg", "RS256"); + jwkMap.put("kid", kid); + jwkMap.put("key_ops", List.of("verify")); + jwkMap.put("n", modulus); + jwkMap.put("e", exponent); + String jwk = canonicalJson(jwkMap); + Map thumbprint = Map.of("e", exponent, "kty", "RSA", "n", modulus); + String fingerprint = + sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(thumbprint))); + Binding binding = trustBinding("trust-r1"); + AccountJwtSignerDesiredStateRepository.Binding accountBinding = accountBinding(); + TrustFence trustFence = trustFence(binding); + GenerationResult result = + new GenerationResult( + operationId, + accountBinding, + OPERATION_DIGEST, + REQUEST_DIGEST, + 2L, + trustFence, + "jwt-signing-keys", + "55555555-5555-4555-8555-555555555555", + "12", + "13", + "1", + kid, + "RS256", + fingerprint, + jwk, + RECEIPT_DIGEST); + GenerationRequest request = + new GenerationRequest( + GenerationPhase.GENERATION_RECORDED, + operationId, + OPERATION_DIGEST, + REQUEST_DIGEST, + 2L, + accountBinding, + trustFence, + "jwt-signing-keys", + "1", + kid, + "RS256", + "MATERIALIZE_PENDING", + List.of("pending"), + Optional.empty(), + Optional.empty(), + "55555555-5555-4555-8555-555555555555", + "12", + RECEIPT_DIGEST, + fingerprint, + jwk, + "13"); + return new GenerationKeys(result, request); + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + private static String canonicalJson(Object value) throws Exception { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } + + private static String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private record GenerationKeys(GenerationResult result, GenerationRequest request) {} + + private record Fixture( + Binding binding, + AccountJwtSignerDesiredStateRepository desiredRepository, + AccountJwtJwksPublicationRepository publicationRepository, + AccountJwtSignerMaterializerTrustBinding trustBindingProvider, + AccountJwtJwksConfigMapClient client, + RecordingTransactionManager transactionManager, + AccountJwtJwksPrepublicationService service, + ConfigMapSnapshot snapshot, + GenerationResult result, + GenerationRequest request) { + private void stubCurrentGeneration() { + AccountJwtJwksPrepublicationServiceTest.stubCurrentGeneration(this); + } + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private int commits; + private int rollbacks; + + @Override + public TransactionStatus getTransaction( + org.springframework.transaction.TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commits++; + } + + @Override + public void rollback(TransactionStatus status) { + rollbacks++; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java new file mode 100644 index 0000000000..22204bd2cf --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java @@ -0,0 +1,751 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Server; +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.SslContext; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountJwtReadinessPodReceiverServiceGrpc; +import net.firedevops.firemud.account.v1.AccountPodTargetBinding; +import net.firedevops.firemud.account.v1.AccountSourceIdentity; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeRequest; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeResponse; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.Invocation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.PodTarget; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.gamesession.v1.GameSessionJwtReadinessReceiverServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeRequest; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeResponse; +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.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.boot.ssl.SslManagerBundle; + +class AccountJwtReadinessGrpcReceiverInvocationPortTest { + private static final String PEER_URI = "spiffe://firemud/ns/firemud-prod/sa/game-session-service"; + private static final String OTHER_PEER_URI = + "spiffe://firemud/ns/firemud-prod/sa/account-service"; + private static final char[] KEY_PASSWORD = "test-only-password".toCharArray(); + + @TempDir private static Path temporaryDirectory; + + private static TestPki pki; + + private final AtomicInteger handlerCalls = new AtomicInteger(); + private Server server; + + @BeforeAll + static void createEphemeralTlsFixtures() throws Exception { + Path trustedDirectory = Files.createDirectories(temporaryDirectory.resolve("trusted")); + TestAuthority trusted = createAuthority(trustedDirectory, "account-readiness-test-ca"); + TestCertificate accountClient = + issueLeaf( + trustedDirectory, + trusted, + "account-client", + "spiffe://firemud/ns/firemud-prod/sa/account-service", + false); + TestCertificate pinnedServer = + issueLeaf(trustedDirectory, trusted, "game-session-pinned", PEER_URI, true); + TestCertificate sameSanDifferentKey = + issueLeaf(trustedDirectory, trusted, "game-session-other-key", PEER_URI, true); + TestCertificate wrongSan = + issueLeaf(trustedDirectory, trusted, "wrong-game-session-san", OTHER_PEER_URI, true); + TestCertificate accountServer = + issueLeaf( + trustedDirectory, + trusted, + "account-pod-receiver", + "spiffe://firemud/ns/firemud-prod/sa/account-service", + true); + + Path untrustedDirectory = Files.createDirectories(temporaryDirectory.resolve("untrusted")); + TestAuthority untrusted = createAuthority(untrustedDirectory, "untrusted-readiness-ca"); + TestCertificate untrustedServer = + issueLeaf(untrustedDirectory, untrusted, "untrusted-game-session", PEER_URI, true); + pki = + new TestPki( + trusted.certificate(), + accountClient, + pinnedServer, + sameSanDifferentKey, + wrongSan, + accountServer, + untrustedServer); + } + + @AfterEach + void stopServer() throws InterruptedException { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void wrongServerUriSanIsRejectedDuringTlsBeforeProbeRpcDispatch() throws Exception { + startServer(pki.wrongSan(), pki.trustedCa()); + assertProbeRejected( + invocation(pki.wrongSan(), server.getPort()), pki.accountClient(), pki.trustedCa()); + assertThat(handlerCalls.get()).isZero(); + } + + @Test + void sameUriWithWrongPodSpecificSpkiIsRejectedDuringTlsBeforeProbeRpcDispatch() throws Exception { + startServer(pki.pinnedServer(), pki.trustedCa()); + assertProbeRejected( + invocation(pki.sameSanDifferentKey(), server.getPort()), + pki.accountClient(), + pki.trustedCa()); + assertThat(handlerCalls.get()).isZero(); + } + + @Test + void untrustedServerCaIsRejectedBeforeProbeRpcDispatch() throws Exception { + startServer(pki.untrustedServer(), pki.trustedCa()); + assertProbeRejected( + invocation(pki.untrustedServer(), server.getPort()), pki.accountClient(), pki.trustedCa()); + assertThat(handlerCalls.get()).isZero(); + } + + @Test + void missingAccountClientCertificateIsRejectedByRequiredMtlsBeforeProbeRpcDispatch() + throws Exception { + startServer(pki.pinnedServer(), pki.trustedCa()); + assertProbeRejected(invocation(pki.pinnedServer(), server.getPort()), null, pki.trustedCa()); + assertThat(handlerCalls.get()).isZero(); + } + + @Test + void exactTlsPeerCanDispatchButMismatchedReceiverCoordinatesNeverBecomeAcceptance() + throws Exception { + startServer(pki.pinnedServer(), pki.trustedCa()); + assertThatThrownBy( + () -> + port(pki.accountClient(), pki.trustedCa()) + .invoke(invocation(pki.pinnedServer(), server.getPort()))) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + assertThat(handlerCalls.get()).isEqualTo(1); + } + + @Test + void accountPodTargetUsesSeparateReceiverRpcAndRejectsMismatchedCoordinates() throws Exception { + startAccountServer(pki.accountServer(), pki.trustedCa()); + assertThatThrownBy( + () -> + port(pki.accountClient(), pki.trustedCa()) + .invoke( + invocation( + pki.accountServer(), + server.getPort(), + "account-service", + "spiffe://firemud/ns/firemud-prod/sa/account-service"))) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + assertThat(handlerCalls.get()).isEqualTo(1); + } + + @Test + void validButDifferentAccountSourceClusterNamespaceOrNamespaceUidCannotMatchPodTarget() { + PodTarget target = protectedPodTarget(); + SourceIdentity matching = + sourceIdentity( + target, + target.clusterId(), + target.namespace(), + target.namespaceUid(), + "88888888-8888-4888-8888-888888888888", + "different-trust-binding-revision"); + + assertThat( + AccountJwtReadinessGrpcReceiverInvocationPort.sourceIdentityMatchesTarget( + matching, target)) + .isTrue(); + assertThat( + AccountJwtReadinessGrpcReceiverInvocationPort.sourceIdentityMatchesTarget( + sourceIdentity( + target, + "other-cluster", + target.namespace(), + target.namespaceUid(), + "88888888-8888-4888-8888-888888888888", + "different-trust-binding-revision"), + target)) + .isFalse(); + assertThat( + AccountJwtReadinessGrpcReceiverInvocationPort.sourceIdentityMatchesTarget( + sourceIdentity( + target, + target.clusterId(), + "other-namespace", + target.namespaceUid(), + "88888888-8888-4888-8888-888888888888", + "different-trust-binding-revision"), + target)) + .isFalse(); + assertThat( + AccountJwtReadinessGrpcReceiverInvocationPort.sourceIdentityMatchesTarget( + sourceIdentity( + target, + target.clusterId(), + target.namespace(), + "77777777-7777-4777-8777-777777777777", + "88888888-8888-4888-8888-888888888888", + "different-trust-binding-revision"), + target)) + .isFalse(); + } + + @Test + void loopbackMtlsInvocationRejectsStructurallyValidOtherAccountSourceCluster() throws Exception { + AtomicReference currentInvocation = new AtomicReference<>(); + startSourceIdentityServer(pki.pinnedServer(), pki.trustedCa(), currentInvocation, true); + Invocation invocation = invocation(pki.pinnedServer(), server.getPort()); + currentInvocation.set(invocation); + + assertThatThrownBy(() -> port(pki.accountClient(), pki.trustedCa()).invoke(invocation)) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + assertThat(handlerCalls.get()).isEqualTo(1); + } + + @Test + void matchingLoopbackMtlsResponseYieldsOnlyNonAuthorizingAcceptanceEvidence() throws Exception { + AtomicReference currentInvocation = new AtomicReference<>(); + startSourceIdentityServer(pki.pinnedServer(), pki.trustedCa(), currentInvocation, false); + Invocation invocation = invocation(pki.pinnedServer(), server.getPort()); + currentInvocation.set(invocation); + + var acceptance = port(pki.accountClient(), pki.trustedCa()).invoke(invocation); + + assertThat(acceptance.jti()).isEqualTo(invocation.jti()); + assertThat(acceptance.compactTokenSha256()).isEqualTo(invocation.compactTokenSha256()); + assertThat(acceptance.verifiedKid()).isEqualTo(invocation.targetKid()); + assertThat(acceptance.podUid()).isEqualTo(invocation.target().podUid()); + assertThat(acceptance.actualServiceUri()).isEqualTo(PEER_URI); + assertThat(acceptance.actualPeerSpkiSha256()) + .isEqualTo(invocation.target().podLeafSpkiSha256().orElseThrow()); + assertThat(acceptance.result()).isEqualTo(ProbeExpectation.ACCEPT); + assertThat(handlerCalls.get()).isEqualTo(1); + } + + private void startServer(TestCertificate serverCertificate, Path trustedCa) throws Exception { + SslContext tlsContext = + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.certificate().toFile(), + serverCertificate.privateKey().toFile())) + .trustManager(trustedCa.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build(); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(tlsContext) + .addService( + new GameSessionJwtReadinessReceiverServiceGrpc + .GameSessionJwtReadinessReceiverServiceImplBase() { + @Override + public void receiveReadinessProbe( + ReceiveReadinessProbeRequest request, + StreamObserver responseObserver) { + handlerCalls.incrementAndGet(); + responseObserver.onNext( + ReceiveReadinessProbeResponse.newBuilder() + .setSchemaVersion(1) + .setCoordinates( + request.getCoordinates().toBuilder() + .setOperationDigest("f".repeat(64))) + .setOutcome(ReceiveReadinessProbeResponse.ObservationOutcome.VERIFIED) + .build()); + responseObserver.onCompleted(); + } + }) + .build() + .start(); + } + + private void startAccountServer(TestCertificate serverCertificate, Path trustedCa) + throws Exception { + SslContext tlsContext = + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.certificate().toFile(), + serverCertificate.privateKey().toFile())) + .trustManager(trustedCa.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build(); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(tlsContext) + .addService( + new AccountJwtReadinessPodReceiverServiceGrpc + .AccountJwtReadinessPodReceiverServiceImplBase() { + @Override + public void receiveReadinessProbe( + ReceiveAccountJwtReadinessProbeRequest request, + StreamObserver responseObserver) { + handlerCalls.incrementAndGet(); + responseObserver.onNext( + ReceiveAccountJwtReadinessProbeResponse.newBuilder() + .setSchemaVersion(1) + .setCoordinates( + request.getCoordinates().toBuilder() + .setOperationDigest("f".repeat(64))) + .setOutcome( + ReceiveAccountJwtReadinessProbeResponse.ObservationOutcome.VERIFIED) + .build()); + responseObserver.onCompleted(); + } + }) + .build() + .start(); + } + + private void startSourceIdentityServer( + TestCertificate serverCertificate, + Path trustedCa, + AtomicReference currentInvocation, + boolean otherCluster) + throws Exception { + SslContext tlsContext = tlsContext(serverCertificate, trustedCa); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(tlsContext) + .addService( + new GameSessionJwtReadinessReceiverServiceGrpc + .GameSessionJwtReadinessReceiverServiceImplBase() { + @Override + public void receiveReadinessProbe( + ReceiveReadinessProbeRequest request, + StreamObserver responseObserver) { + handlerCalls.incrementAndGet(); + Invocation invocation = currentInvocation.get(); + PodTarget target = invocation.target(); + responseObserver.onNext( + ReceiveReadinessProbeResponse.newBuilder() + .setSchemaVersion(1) + .setCoordinates(request.getCoordinates()) + .setCompactTokenSha256(invocation.compactTokenSha256()) + .setVerifiedKeyId(invocation.targetKid()) + .setReceiverIdentity( + ReadinessReceiverLocalIdentity.newBuilder() + .setValidatorId(target.validatorId()) + .setDeploymentUid(target.deploymentUid()) + .setPodUid(target.podUid()) + .setPodIp(target.podIp()) + .setDirectPodEndpoint( + target.exactPodEndpoint().orElseThrow().toString()) + .setCanonicalServiceUri( + target.canonicalServiceUri().orElseThrow()) + .setImage(target.image()) + .setVerifierConfigSha256(target.verifierConfigSha256()) + .setApplicabilityMatrixDigest( + target.applicabilityMatrixDigest()) + .setSourceInventoryRevision("source-r1") + .setSourceInventoryDigest("8".repeat(64)) + .setServerLeafSpkiSha256( + target.podLeafSpkiSha256().orElseThrow()) + .setAccountJwksSourceIdentity( + AccountSourceIdentity.newBuilder() + .setEnvironmentId(target.environmentId()) + .setClusterId( + otherCluster ? "other-cluster" : target.clusterId()) + .setClusterIncarnationUid( + target.clusterIncarnationUid()) + .setNamespace(target.namespace()) + .setNamespaceUid(target.namespaceUid()) + .setConfigMapUid("88888888-8888-4888-8888-888888888888") + .setBindingRevision("unrelated-trust-revision") + .setApiServerOrigin("https://kubernetes.example:6443") + .setServingCaSha256("9".repeat(64))) + .setAccountJwksTrustConfigRevision(1L)) + .setAccountPodTarget(accountTargetBinding(target)) + .setObservedAtEpochSeconds(System.currentTimeMillis() / 1000) + .setOutcome(ReceiveReadinessProbeResponse.ObservationOutcome.VERIFIED) + .build()); + responseObserver.onCompleted(); + } + }) + .build() + .start(); + } + + private static SslContext tlsContext(TestCertificate serverCertificate, Path trustedCa) + throws Exception { + return GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverCertificate.certificate().toFile(), serverCertificate.privateKey().toFile())) + .trustManager(trustedCa.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build(); + } + + private static AccountPodTargetBinding accountTargetBinding(PodTarget target) { + return AccountPodTargetBinding.newBuilder() + .setInventorySnapshotDigest(target.inventorySnapshotDigest()) + .setEnvironmentId(target.environmentId()) + .setClusterId(target.clusterId()) + .setClusterIncarnationUid(target.clusterIncarnationUid()) + .setNamespace(target.namespace()) + .setNamespaceUid(target.namespaceUid()) + .setApiBindingRevision(target.apiBindingRevision()) + .setApiBindingDigest(target.apiBindingDigest()) + .setInventoryBindingRevision(target.inventoryBindingRevision()) + .setInventoryBindingDigest(target.inventoryBindingDigest()) + .setValidatorId(target.validatorId()) + .setDeploymentUid(target.deploymentUid()) + .setPodUid(target.podUid()) + .setPodIp(target.podIp()) + .setImage(target.image()) + .setVerifierConfigSha256(target.verifierConfigSha256()) + .setApplicabilityMatrixDigest(target.applicabilityMatrixDigest()) + .setExpectedOutcome(ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setDirectPodEndpoint(target.exactPodEndpoint().orElseThrow().toString()) + .setCanonicalServiceUri(target.canonicalServiceUri().orElseThrow()) + .setServerLeafSpkiSha256(target.podLeafSpkiSha256().orElseThrow()) + .build(); + } + + private static void assertProbeRejected( + Invocation invocation, TestCertificate accountClient, Path trustedCa) { + assertThatThrownBy(() -> port(accountClient, trustedCa).invoke(invocation)) + .isInstanceOf(RuntimeException.class); + } + + private static AccountJwtReadinessGrpcReceiverInvocationPort port( + TestCertificate accountClient, Path trustedCa) { + try { + KeyStore keyStore; + if (accountClient == null) { + keyStore = KeyStore.getInstance("PKCS12"); + keyStore.load(null, KEY_PASSWORD); + } else { + keyStore = keyStore(accountClient); + } + var keyManagerFactory = + javax.net.ssl.KeyManagerFactory.getInstance( + javax.net.ssl.KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keyStore, KEY_PASSWORD); + var trustManagerFactory = + javax.net.ssl.TrustManagerFactory.getInstance( + javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm()); + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + trustStore.setCertificateEntry("readiness-test-ca", readCertificate(trustedCa)); + trustManagerFactory.init(trustStore); + + SslBundles bundles = mock(SslBundles.class); + SslBundle bundle = mock(SslBundle.class); + SslManagerBundle managers = mock(SslManagerBundle.class); + when(bundles.getBundle("firemud-grpc")).thenReturn(bundle); + when(bundle.getManagers()).thenReturn(managers); + when(managers.getKeyManagerFactory()).thenReturn(keyManagerFactory); + when(managers.getTrustManagerFactory()).thenReturn(trustManagerFactory); + return new AccountJwtReadinessGrpcReceiverInvocationPort(bundles, "firemud-prod"); + } catch (Exception failure) { + throw new IllegalStateException("Could not assemble test-only Account TLS bundle", failure); + } + } + + private static Invocation invocation(TestCertificate expectedServer, int port) throws Exception { + return invocation(expectedServer, port, "game-session-service", PEER_URI); + } + + private static PodTarget protectedPodTarget() { + return new PodTarget( + "a".repeat(64), + "prod", + "prod-cluster-1", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "api-r1", + "b".repeat(64), + "inventory-r1", + "c".repeat(64), + "game-session-service", + "33333333-3333-4333-8333-333333333333", + "44444444-4444-4444-8444-444444444444", + "127.0.0.1", + "registry.example/firemud/game-session-service@sha256:" + "d".repeat(64), + "e".repeat(64), + "f".repeat(64), + ProbeExpectation.ACCEPT, + Optional.empty(), + Optional.empty(), + Optional.empty()); + } + + private static SourceIdentity sourceIdentity( + PodTarget target, + String clusterId, + String namespace, + String namespaceUid, + String configMapUid, + String bindingRevision) { + return new SourceIdentity( + target.environmentId(), + clusterId, + target.clusterIncarnationUid(), + namespace, + namespaceUid, + configMapUid, + bindingRevision, + "https://kubernetes.example:6443", + "9".repeat(64)); + } + + private static Invocation invocation( + TestCertificate expectedServer, int port, String validatorId, String expectedServiceUri) + throws Exception { + long now = System.currentTimeMillis() / 1000; + String podIp = "127.0.0.1"; + PodTarget target = + new PodTarget( + "a".repeat(64), + "prod", + "prod-cluster-1", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "api-r1", + "b".repeat(64), + "inventory-r1", + "c".repeat(64), + validatorId, + "33333333-3333-4333-8333-333333333333", + "44444444-4444-4444-8444-444444444444", + podIp, + "registry.example/firemud/" + validatorId + "@sha256:" + "d".repeat(64), + "e".repeat(64), + "f".repeat(64), + ProbeExpectation.ACCEPT, + Optional.of(java.net.URI.create("grpcs://" + podIp + ":" + port)), + Optional.of(expectedServiceUri), + Optional.of(spki(expectedServer.certificate()))); + String compact = "e30.eyJ4IjoxfQ.c2lnbmF0dXJl"; + return new Invocation( + UUID.fromString("55555555-5555-4555-8555-555555555555"), + "1".repeat(64), + "2".repeat(64), + AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION, + now + 120, + validatorId, + "canary", + "account-service", + ProbeKind.CANARY, + ProbeExpectation.ACCEPT, + 1, + 1L, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + compact, + sha256(compact), + "2", + "target-kid", + Optional.empty(), + Optional.empty(), + now - 1, + now + 60, + target); + } + + private static KeyStore keyStore(TestCertificate certificate) throws Exception { + Path privateKeyDirectory = + Objects.requireNonNull( + certificate.privateKey().getParent(), + "test certificate private-key directory is required"); + Path pkcs12 = privateKeyDirectory.resolve("account-client-" + UUID.randomUUID() + ".p12"); + Path pkcs12Directory = + Objects.requireNonNull(pkcs12.getParent(), "test client keystore directory is required"); + runOpenSsl( + pkcs12Directory, + "pkcs12", + "-export", + "-in", + certificate.certificate().toString(), + "-inkey", + certificate.privateKey().toString(), + "-certfile", + pki.trustedCa().toString(), + "-out", + pkcs12.toString(), + "-name", + "account-client", + "-passout", + "pass:" + new String(KEY_PASSWORD)); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream input = Files.newInputStream(pkcs12)) { + keyStore.load(input, KEY_PASSWORD); + } + return keyStore; + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (InputStream input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static String spki(Path certificatePath) throws Exception { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(readCertificate(certificatePath).getPublicKey().getEncoded())); + } + + private static String sha256(String value) throws Exception { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(java.nio.charset.StandardCharsets.US_ASCII))); + } + + private static TestAuthority createAuthority(Path directory, String commonName) throws Exception { + Path privateKey = directory.resolve(commonName + ".key"); + Path certificate = directory.resolve(commonName + ".crt"); + runOpenSsl( + directory, + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + privateKey.toString(), + "-out", + certificate.toString(), + "-subj", + "/CN=" + commonName, + "-days", + "2", + "-sha256", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign"); + return new TestAuthority(privateKey, certificate); + } + + private static TestCertificate issueLeaf( + Path directory, + TestAuthority authority, + String commonName, + String workloadUri, + boolean serverCertificate) + throws Exception { + Path privateKey = directory.resolve(commonName + ".key"); + Path request = directory.resolve(commonName + ".csr"); + Path certificate = directory.resolve(commonName + ".crt"); + Path extensions = directory.resolve(commonName + ".ext"); + Files.writeString( + extensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=" + + (serverCertificate ? "serverAuth" : "clientAuth") + + "\nsubjectAltName=URI:" + + workloadUri + + ",DNS:localhost,IP:127.0.0.1\n"); + runOpenSsl( + directory, + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + privateKey.toString(), + "-out", + request.toString(), + "-subj", + "/CN=" + commonName); + runOpenSsl( + directory, + "x509", + "-req", + "-in", + request.toString(), + "-CA", + authority.certificate().toString(), + "-CAkey", + authority.privateKey().toString(), + "-CAcreateserial", + "-out", + certificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + extensions.toString()); + return new TestCertificate(privateKey, certificate); + } + + private static void runOpenSsl(Path directory, String... arguments) throws Exception { + List command = new ArrayList<>(); + command.add("openssl"); + command.addAll(List.of(arguments)); + Process process; + try { + process = + new ProcessBuilder(command) + .directory(directory.toFile()) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + } catch (IOException exception) { + throw new IllegalStateException("OpenSSL is required for ephemeral TLS test fixtures"); + } + if (!process.waitFor(20, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(2, TimeUnit.SECONDS); + throw new IllegalStateException("Ephemeral TLS test fixture generation timed out"); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("Ephemeral TLS test fixture generation failed"); + } + } + + private record TestAuthority(Path privateKey, Path certificate) {} + + private record TestCertificate(Path privateKey, Path certificate) {} + + private record TestPki( + Path trustedCa, + TestCertificate accountClient, + TestCertificate pinnedServer, + TestCertificate sameSanDifferentKey, + TestCertificate wrongSan, + TestCertificate accountServer, + TestCertificate untrustedServer) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java new file mode 100644 index 0000000000..31b761fa9b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java @@ -0,0 +1,170 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Collections; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import org.junit.jupiter.api.Test; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.boot.ssl.SslStoreBundle; + +class AccountJwtReadinessPodLocalIdentityProviderTest { + private static final String URI_SAN = "spiffe://firemud/ns/firemud-prod/sa/account-service"; + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2030-06-01T00:10:00Z"), ZoneId.of("UTC")); + + @Test + void derivesLocalPodIdentityFromProtectedInventoryAndMatchingServerBundleLeaf() throws Exception { + Fixture fixture = new Fixture(false); + + var identity = fixture.provider.observe("c".repeat(64)); + + assertThat(identity.selectorIdentity().podUid()).isEqualTo(Fixture.POD_UID); + assertThat(identity.selectorIdentity().deploymentUid()).isEqualTo(Fixture.DEPLOYMENT_UID); + assertThat(identity.selectorIdentity().podIp()).isEqualTo("10.0.0.12"); + assertThat(identity.selectorIdentity().serverLeafSpkiSha256()).isEqualTo(fixture.leafSpki); + assertThat(identity.wireIdentity().getJwksTrustBindingRevision()).isEqualTo("api-r1"); + assertThat(identity.wireIdentity().getAccountJwksSourceIdentity().getConfigMapUid()) + .isEqualTo("55555555-5555-4555-8555-555555555555"); + } + + @Test + void localIdentityRereadUsesTheOwnerBoundInitialCandidateContext() throws Exception { + Fixture fixture = new Fixture(false); + ObservationContext context = + new ObservationContext( + ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "9".repeat(64)); + when(fixture.inventorySource.observe(context)).thenReturn(fixture.inventory); + + var identity = fixture.provider.observe("c".repeat(64), context); + + assertThat(identity.selectorIdentity().podUid()).isEqualTo(Fixture.POD_UID); + assertThat(identity.wireIdentity().getSourceInventoryDigest()).isEqualTo("d".repeat(64)); + org.mockito.Mockito.verify(fixture.inventorySource).observe(context); + } + + @Test + void refusesWhenActualSslBundleLeafDoesNotMatchProtectedPodPin() throws Exception { + Fixture fixture = new Fixture(true); + + assertThatThrownBy(() -> fixture.provider.observe("c".repeat(64))) + .isInstanceOf( + AccountJwtReadinessPodLocalIdentityProvider.IdentityUnavailableException.class); + } + + private static final class Fixture { + private static final String POD_UID = "33333333-3333-4333-8333-333333333333"; + private static final String DEPLOYMENT_UID = "44444444-4444-4444-8444-444444444444"; + private final byte[] encodedPublicKey = + "test server public key".getBytes(java.nio.charset.StandardCharsets.US_ASCII); + private final String leafSpki = sha256(encodedPublicKey); + private final AccountJwtValidatorInventorySource inventorySource = + mock(AccountJwtValidatorInventorySource.class); + private final InventorySnapshot inventory = mock(InventorySnapshot.class); + private final AccountJwtJwksTrustedSource trustedSource = + mock(AccountJwtJwksTrustedSource.class); + private final SslBundles sslBundles = mock(SslBundles.class); + private final AccountJwtReadinessPodLocalIdentityProvider provider; + + private Fixture(boolean mismatchProtectedLeafPin) throws Exception { + ValidatorObservation validator = mock(ValidatorObservation.class); + PodObservation pod = mock(PodObservation.class); + when(inventory.validators()).thenReturn(List.of(validator)); + when(inventory.environmentId()).thenReturn("prod"); + when(inventory.clusterId()).thenReturn("cluster-a"); + when(inventory.clusterIncarnationUid()).thenReturn("11111111-1111-4111-8111-111111111111"); + when(inventory.namespace()).thenReturn("firemud-prod"); + when(inventory.namespaceUid()).thenReturn("22222222-2222-4222-8222-222222222222"); + when(inventory.inventoryBindingRevision()).thenReturn("inventory-r1"); + when(inventory.digest()).thenReturn("d".repeat(64)); + when(validator.validatorId()).thenReturn("account-service"); + when(validator.deploymentName()).thenReturn("account-service"); + when(validator.deploymentUid()).thenReturn(DEPLOYMENT_UID); + when(validator.image()).thenReturn("registry.example/account@sha256:" + "a".repeat(64)); + when(validator.verifierConfigSha256()).thenReturn("b".repeat(64)); + when(validator.profiles()) + .thenReturn( + AccountJwtReadinessProbeCrypto.representativeProfiles().values().stream() + .map(value -> new ProfileExpectation(value.profile(), value.audience())) + .toList()); + when(validator.pods()).thenReturn(List.of(pod)); + when(pod.name()).thenReturn("account-0"); + when(pod.uid()).thenReturn(POD_UID); + when(pod.ownerName()).thenReturn("account-service"); + when(pod.ownerUid()).thenReturn(DEPLOYMENT_UID); + when(pod.podIp()).thenReturn("10.0.0.12"); + when(pod.endpoint()).thenReturn(URI.create("https://10.0.0.12:6565")); + when(pod.receiverServiceUri()).thenReturn(URI_SAN); + when(pod.image()).thenReturn("registry.example/account@sha256:" + "a".repeat(64)); + when(pod.verifierConfigSha256()).thenReturn("b".repeat(64)); + when(pod.leafSpkiSha256()).thenReturn(mismatchProtectedLeafPin ? "f".repeat(64) : leafSpki); + when(inventorySource.observe()).thenReturn(inventory); + + var sourceIdentity = + new AccountPublicJwksCache.SourceIdentity( + "prod", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "55555555-5555-4555-8555-555555555555", + "api-r1", + "https://kubernetes.example.test:6443", + "9".repeat(64)); + when(trustedSource.load()) + .thenReturn( + new AccountPublicJwksCache.PublicJwksSnapshot( + sourceIdentity, + "{\"keys\":[]}".getBytes(java.nio.charset.StandardCharsets.US_ASCII))); + + KeyStore keyStore = mock(KeyStore.class); + when(keyStore.aliases()).thenReturn(Collections.enumeration(List.of("account-server"))); + when(keyStore.isKeyEntry("account-server")).thenReturn(true); + X509Certificate certificate = mock(X509Certificate.class); + PublicKey publicKey = mock(PublicKey.class); + when(certificate.getPublicKey()).thenReturn(publicKey); + when(publicKey.getEncoded()).thenReturn(encodedPublicKey); + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, URI_SAN))); + when(keyStore.getCertificate("account-server")).thenReturn(certificate); + SslStoreBundle stores = mock(SslStoreBundle.class); + when(stores.getKeyStore()).thenReturn(keyStore); + SslBundle sslBundle = mock(SslBundle.class); + when(sslBundle.getStores()).thenReturn(stores); + when(sslBundles.getBundle("firemud-grpc")).thenReturn(sslBundle); + provider = + new AccountJwtReadinessPodLocalIdentityProvider( + inventorySource, trustedSource, sslBundles, CLOCK, "account-0"); + } + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (Exception unavailable) { + throw new AssertionError(unavailable); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverEngineTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverEngineTest.java new file mode 100644 index 0000000000..5df07bb91e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverEngineTest.java @@ -0,0 +1,569 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.RSAKeyGenParameterSpec; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountJwtPodReceiverIdentity; +import net.firedevops.firemud.account.v1.AccountSourceIdentity; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPodReceiverWorkloadGuard; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPodReceiverWorkloadGuard.AuthenticatedCaller; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.OwnerProbeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.SignerFence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessPodLocalIdentityProvider.LocalObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.PodTarget; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtReadinessPodReceiverEngineTest { + private static final Instant NOW = Instant.parse("2030-06-01T00:10:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneId.of("UTC")); + private static final String RESERVED_SUBJECT = "00000000-0000-4000-8000-000000000001"; + private static final String ACTIVE_KID = "active-key-6"; + private static final String PENDING_KID = "pending-key-7"; + private static final String MATRIX_DIGEST = "c".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void + verifiesAllAccountProfilesWithProductionCryptoAfterUnknownPendingKidRefreshAndOnlyReadsOwner() + throws Exception { + Fixture fixture = new Fixture(); + Map profiles = + Map.of( + "account-jwt-readiness-canary", + "firemud-account-jwt-readiness", + ControlUiJwtProfileValidator.PROFILE, + ControlUiJwtProfileValidator.AUDIENCE, + PlayerBootstrapJwtProfileValidator.PROFILE, + PlayerBootstrapJwtProfileValidator.AUDIENCE, + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.AUDIENCE); + + for (Map.Entry profile : profiles.entrySet()) { + ReceiveAccountJwtReadinessProbeRequest request = + fixture.request(profile.getKey(), profile.getValue()); + var response = fixture.engine.receiveReadinessProbe(request); + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getCoordinates()).isEqualTo(request.getCoordinates()); + assertThat(response.getCompactTokenSha256()).matches("[0-9a-f]{64}"); + assertThat(response.getVerifiedKeyId()).isEqualTo(PENDING_KID); + assertThat(response.getOutcome()) + .isEqualTo( + net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeResponse + .ObservationOutcome.VERIFIED); + assertThat(response.getReceiverIdentity().getPodUid()).isEqualTo(Fixture.POD_UID); + assertThat(response.getReceiverIdentity().getJwksTrustBindingRevision()) + .isEqualTo("account-api-r1"); + assertThat(response.getAccountPodTarget().getPodUid()).isEqualTo(Fixture.POD_UID); + assertThat(response.getObservedAtEpochSeconds()).isEqualTo(NOW.getEpochSecond()); + } + + verify(fixture.localIdentityProvider, times(2 * profiles.size())) + .observe(MATRIX_DIGEST, fixture.observationContext); + verify(fixture.probeService, times(2 * profiles.size())) + .readCurrentProbeOwner( + eq(fixture.accountBinding.accountBinding()), + any(TrustFence.class), + any(AccountJwtReadinessProbeOwnerSelector.class), + eq("firemud-prod")); + verify(fixture.probeService, times(profiles.size())) + .readCurrentPlan( + eq(fixture.accountBinding.accountBinding()), any(TrustFence.class), any(UUID.class)); + verify(fixture.probeService, times(profiles.size())) + .readCurrentInventoryObservationContext( + eq(fixture.accountBinding.accountBinding()), any(TrustFence.class), any(UUID.class)); + verifyNoMoreInteractions(fixture.probeService); + verify(fixture.workloadGuard, times(profiles.size())).requireUnchanged(fixture.caller); + } + + @Test + void signatureFailureDoesNotProduceReceiptOrAfterCryptoIdentityRead() throws Exception { + Fixture fixture = new Fixture(); + ReceiveAccountJwtReadinessProbeRequest valid = + fixture.request( + ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE); + String[] parts = valid.getCompactJwt().split("\\.", -1); + byte[] signature = Base64.getUrlDecoder().decode(parts[2]); + signature[0] ^= 0x01; + String tampered = parts[0] + "." + parts[1] + "." + encode(signature); + + assertThatThrownBy( + () -> + fixture.engine.receiveReadinessProbe( + valid.toBuilder().setCompactJwt(tampered).build())) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + + InOrder reads = inOrder(fixture.probeService, fixture.localIdentityProvider); + reads + .verify(fixture.probeService) + .readCurrentPlan( + eq(fixture.accountBinding.accountBinding()), + any(TrustFence.class), + eq(fixture.operationId)); + reads + .verify(fixture.probeService) + .readCurrentInventoryObservationContext( + eq(fixture.accountBinding.accountBinding()), + any(TrustFence.class), + eq(fixture.operationId)); + reads.verify(fixture.localIdentityProvider).observe(MATRIX_DIGEST, fixture.observationContext); + reads + .verify(fixture.probeService) + .readCurrentProbeOwner( + eq(fixture.accountBinding.accountBinding()), + any(TrustFence.class), + any(AccountJwtReadinessProbeOwnerSelector.class), + eq("firemud-prod")); + verifyNoMoreInteractions(fixture.probeService); + verifyNoMoreInteractions(fixture.localIdentityProvider); + } + + @Test + void absentPersistedPlanFailsBeforeIdentityOrReceiverOwnerRead() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.probeService.readCurrentPlan( + eq(fixture.accountBinding.accountBinding()), any(TrustFence.class), any(UUID.class))) + .thenThrow(new AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException()); + ReceiveAccountJwtReadinessProbeRequest request = + fixture.request( + ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE); + + assertThatThrownBy(() -> fixture.engine.receiveReadinessProbe(request)) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + + verify(fixture.localIdentityProvider, never()).observe(any(), any()); + verify(fixture.probeService).readCurrentPlan(any(), any(), any()); + verify(fixture.probeService, never()) + .readCurrentInventoryObservationContext(any(), any(), any()); + verify(fixture.probeService, never()).readCurrentProbeOwner(any(), any(), any(), any()); + verifyNoMoreInteractions(fixture.probeService); + } + + @Test + void ownerOrLocalIdentityDriftAfterCryptoRejectsWithoutSuccess() throws Exception { + Fixture ownerDrift = new Fixture(); + OwnerProbeEvidence changedEvidence = mock(OwnerProbeEvidence.class); + when(ownerDrift.probeService.readCurrentProbeOwner(any(), any(), any(), any())) + .thenReturn(ownerDrift.ownerEvidence, changedEvidence); + var request = + ownerDrift.request( + ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE); + assertThatThrownBy(() -> ownerDrift.engine.receiveReadinessProbe(request)) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + + Fixture localDrift = new Fixture(); + AccountJwtPodReceiverIdentity changedWireIdentity = + localDrift.localObservation.wireIdentity().toBuilder().setPodIp("10.0.0.13").build(); + when(localDrift.localIdentityProvider.observe(MATRIX_DIGEST, localDrift.observationContext)) + .thenReturn( + localDrift.localObservation, + new LocalObservation( + localDrift.localObservation.selectorIdentity(), changedWireIdentity)); + assertThatThrownBy( + () -> + localDrift.engine.receiveReadinessProbe( + localDrift.request( + ControlUiJwtProfileValidator.PROFILE, + ControlUiJwtProfileValidator.AUDIENCE))) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + } + + private static final class Fixture { + private final UUID operationId = UUID.randomUUID(); + private final UUID jti = UUID.randomUUID(); + private static final String POD_UID = "33333333-3333-4333-8333-333333333333"; + private static final String DEPLOYMENT_UID = "44444444-4444-4444-8444-444444444444"; + private final AccountJwtSignerMaterializerTrustBinding.Binding accountBinding = + accountBinding(); + private final AuthenticatedCaller caller = + new AuthenticatedCaller(accountBinding, apiBinding()); + private final AccountJwtReadinessProbeService probeService = + mock(AccountJwtReadinessProbeService.class); + private final AccountJwtReadinessPodReceiverWorkloadGuard workloadGuard = + mock(AccountJwtReadinessPodReceiverWorkloadGuard.class); + private final AccountJwtReadinessPodLocalIdentityProvider localIdentityProvider = + mock(AccountJwtReadinessPodLocalIdentityProvider.class); + private final ReadinessProbePlan plan = mock(ReadinessProbePlan.class); + private final ProbeEntry entry = mock(ProbeEntry.class); + private final OwnerProbeEvidence ownerEvidence = mock(OwnerProbeEvidence.class); + private final AccountJwtReadinessProbeOwnerSelector.LocalIdentity selectorIdentity = + localIdentity(); + private final LocalObservation localObservation = + new LocalObservation(selectorIdentity, wireIdentity()); + private final ObservationContext observationContext = + new ObservationContext( + ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES, operationId, "a".repeat(64)); + private final KeyPair pendingKey; + private final AccountAsymmetricJwtVerifier verifier; + private final AccountJwtReadinessPodReceiverEngine engine; + + private Fixture() throws Exception { + KeyPair active = rsa3072(); + pendingKey = rsa3072(); + AtomicReference jwks = + new AtomicReference<>(jwks(ACTIVE_KID, (RSAPublicKey) active.getPublic())); + AccountPublicJwksCache.SourceIdentity sourceIdentity = sourceIdentity(); + AccountPublicJwksCache cache = + new AccountPublicJwksCache( + () -> + new AccountPublicJwksCache.PublicJwksSnapshot( + sourceIdentity, jwks.get().getBytes(StandardCharsets.US_ASCII)), + sourceIdentity, + CLOCK, + Duration.ofSeconds(300)); + cache.keyFor(ACTIVE_KID); + jwks.set( + jwks( + ACTIVE_KID, + (RSAPublicKey) active.getPublic(), + PENDING_KID, + (RSAPublicKey) pendingKey.getPublic())); + verifier = new AccountAsymmetricJwtVerifier(cache, CLOCK); + + when(workloadGuard.requireAccountReceiverCaller()).thenReturn(caller); + when(localIdentityProvider.observe(MATRIX_DIGEST, observationContext)) + .thenReturn(localObservation, localObservation); + when(plan.operationId()).thenReturn(operationId); + when(plan.operationDigest()).thenReturn("a".repeat(64)); + when(plan.planDigest()).thenReturn("b".repeat(64)); + when(plan.planVersion()).thenReturn(2); + when(plan.expiresAtEpochSecond()).thenReturn(NOW.getEpochSecond() + 300); + when(plan.targetGeneration()).thenReturn("7"); + when(plan.targetKid()).thenReturn(PENDING_KID); + when(plan.expectedFence()).thenReturn(new SignerFence(Optional.empty(), Optional.empty())); + when(plan.validatorInventoryComplete()).thenReturn(true); + when(plan.applicabilityMatrixDigest()).thenReturn(MATRIX_DIGEST); + when(entry.targetKid()).thenReturn(PENDING_KID); + when(entry.plannedIssuedAtEpochSecond()).thenReturn(NOW.getEpochSecond() - 1); + when(entry.expiresAtEpochSecond()).thenReturn(NOW.getEpochSecond() + 299); + when(ownerEvidence.plan()).thenReturn(plan); + when(ownerEvidence.entry()).thenReturn(entry); + var expectedPod = mock(AccountJwtReadinessProbeRepository.ExpectedPod.class); + when(expectedPod.target()).thenReturn(podTarget()); + when(ownerEvidence.expectedPod()).thenReturn(expectedPod); + when(probeService.readCurrentPlan( + eq(accountBinding.accountBinding()), any(TrustFence.class), any(UUID.class))) + .thenReturn(plan); + when(probeService.readCurrentInventoryObservationContext( + eq(accountBinding.accountBinding()), any(TrustFence.class), eq(operationId))) + .thenReturn(observationContext); + when(probeService.readCurrentProbeOwner(any(), any(), any(), any())) + .thenReturn(ownerEvidence); + + engine = + new AccountJwtReadinessPodReceiverEngine( + probeService, + workloadGuard, + localIdentityProvider, + new AccountJwtReadinessPodReceiverProtoMapper(), + verifier, + CLOCK, + 8); + } + + private ReceiveAccountJwtReadinessProbeRequest request(String profile, String audience) + throws Exception { + boolean canary = "account-jwt-readiness-canary".equals(profile); + String compactJwt = token(profile, audience, canary, jti, PENDING_KID, pendingKey()); + ReadinessProbeCoordinates coordinates = + ReadinessProbeCoordinates.newBuilder() + .setRotationOperationId(operationId.toString()) + .setOperationDigest("a".repeat(64)) + .setPlanDigest("b".repeat(64)) + .setPlanVersion(2) + .setRegistryVersion(1) + .setValidatorId("account-service") + .setTokenProfile(profile) + .setAudience(audience) + .setProbeKind( + canary + ? ReadinessProbeCoordinates.ProbeKind.CANARY + : ReadinessProbeCoordinates.ProbeKind.REPRESENTATIVE) + .setExpectedOutcome(ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setJti(jti.toString()) + .setEntryVersion(4) + .setTargetGeneration("7") + .setTargetKid(PENDING_KID) + .setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.ABSENT) + .setIssuedAtEpochSeconds(NOW.getEpochSecond() - 1) + .setExpiresAtEpochSeconds(NOW.getEpochSecond() + 299) + .setPlanExpiresAtEpochSeconds(NOW.getEpochSecond() + 300) + .build(); + return ReceiveAccountJwtReadinessProbeRequest.newBuilder() + .setSchemaVersion(1) + .setCoordinates(coordinates) + .setCompactJwt(compactJwt) + .build(); + } + + private KeyPair pendingKey() { + // The trusted source serves only public keys; this is a signing-only fixture key. + return pendingKey; + } + + private AccountJwtReadinessProbeOwnerSelector.LocalIdentity localIdentity() { + return new AccountJwtReadinessProbeOwnerSelector.LocalIdentity( + "account-service", + DEPLOYMENT_UID, + POD_UID, + "10.0.0.12", + "grpcs://10.0.0.12:6565", + "spiffe://firemud/ns/firemud-prod/sa/account-service", + "registry.example/account@sha256:" + "a".repeat(64), + "b".repeat(64), + MATRIX_DIGEST, + "inventory-r1", + "d".repeat(64), + "e".repeat(64)); + } + + private AccountJwtPodReceiverIdentity wireIdentity() { + return AccountJwtPodReceiverIdentity.newBuilder() + .setValidatorId("account-service") + .setDeploymentUid(DEPLOYMENT_UID) + .setPodUid(POD_UID) + .setPodIp("10.0.0.12") + .setDirectPodEndpoint("grpcs://10.0.0.12:6565") + .setCanonicalServiceUri("spiffe://firemud/ns/firemud-prod/sa/account-service") + .setImage("registry.example/account@sha256:" + "a".repeat(64)) + .setVerifierConfigSha256("b".repeat(64)) + .setApplicabilityMatrixDigest(MATRIX_DIGEST) + .setSourceInventoryRevision("inventory-r1") + .setSourceInventoryDigest("d".repeat(64)) + .setServerLeafSpkiSha256("e".repeat(64)) + .setAccountJwksSourceIdentity( + AccountSourceIdentity.newBuilder() + .setEnvironmentId("prod") + .setClusterId("cluster-a") + .setClusterIncarnationUid("11111111-1111-4111-8111-111111111111") + .setNamespace("firemud-prod") + .setNamespaceUid("22222222-2222-4222-8222-222222222222") + .setConfigMapUid("55555555-5555-4555-8555-555555555555") + .setBindingRevision("account-api-r1") + .setApiServerOrigin("https://kubernetes.example.test:6443") + .setServingCaSha256("9".repeat(64))) + .setJwksTrustBindingRevision("account-api-r1") + .build(); + } + + private PodTarget podTarget() { + return new PodTarget( + "f".repeat(64), + "prod", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "api-r1", + "8".repeat(64), + "inventory-r1", + "d".repeat(64), + "account-service", + DEPLOYMENT_UID, + POD_UID, + "10.0.0.12", + "registry.example/account@sha256:" + "a".repeat(64), + "b".repeat(64), + MATRIX_DIGEST, + ProbeExpectation.ACCEPT, + Optional.of(URI.create("grpcs://10.0.0.12:6565")), + Optional.of("spiffe://firemud/ns/firemud-prod/sa/account-service"), + Optional.of("e".repeat(64))); + } + } + + private static AccountJwtSignerMaterializerTrustBinding.Binding accountBinding() { + String namespace = "firemud-prod"; + String revision = "trust-r1"; + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + String peer = "spiffe://firemud/ns/" + namespace + "/sa/jwt-signer-materializer"; + List pins = List.of("a".repeat(64)); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, "prod", "cluster-a", namespace, clusterUid, namespaceUid, peer, pins); + return new AccountJwtSignerMaterializerTrustBinding.Binding( + "prod", "cluster-a", namespace, clusterUid, namespaceUid, peer, pins, revision, digest); + } + + private static AccountJwtJwksApiBinding.ParsedBinding apiBinding() { + return new AccountJwtJwksApiBinding.ParsedBinding( + "api-r1", + "prod", + "cluster-a", + URI.create("https://kubernetes.example.test:6443"), + "kubernetes.example.test", + fixtureOnlyPath("serving-ca.pem"), + "9".repeat(64), + fixtureOnlyPath("bearer-token"), + "firemud-prod", + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "system:serviceaccount:firemud-prod:account-service", + "7".repeat(64)); + } + + private static Path fixtureOnlyPath(String name) { + // The guard fixture carries these parsed paths as identity only and never opens them. + return Path.of("protected").toAbsolutePath().resolve(name); + } + + private static AccountPublicJwksCache.SourceIdentity sourceIdentity() { + return new AccountPublicJwksCache.SourceIdentity( + "prod", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "55555555-5555-4555-8555-555555555555", + "account-api-r1", + "https://kubernetes.example.test:6443", + "9".repeat(64)); + } + + private static String token( + String profile, String audience, boolean canary, UUID jti, String kid, KeyPair keyPair) + throws Exception { + Map header = Map.of("alg", "RS256", "kid", kid, "typ", "JWT"); + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("sub", RESERVED_SUBJECT); + claims.put("jti", jti.toString()); + claims.put("aud", audience); + claims.put("iat", NOW.getEpochSecond() - 1L); + claims.put("nbf", NOW.getEpochSecond() - 1L); + claims.put("exp", NOW.getEpochSecond() + 299L); + if (canary) { + claims.put("tokenProfile", profile); + claims.put("tokenType", "account_jwt_readiness_canary"); + } else { + if (ControlUiJwtProfileValidator.PROFILE.equals(profile) + || PlayerBootstrapJwtProfileValidator.PROFILE.equals(profile)) { + claims.put("scopedRoles", Map.of()); + } + claims.put("accountId", RESERVED_SUBJECT); + boolean decimalCounters = GameSessionAccountDelegationProfile.PROFILE.equals(profile); + Object initialCounter = decimalCounters ? "1" : 1L; + claims.put("tokenGeneration", initialCounter); + claims.put("authorityTuple", authorityTuple(initialCounter)); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", initialCounter); + } + String signingInput = + encode(JSON.writeValueAsBytes(header)) + + "." + + encode(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(claims))); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keyPair.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return signingInput + "." + encode(signature.sign()); + } + + private static Map authorityTuple(Object generation) { + return Map.of( + "issuerAuthGeneration", generation, + "accountAuthorityGeneration", generation, + "tenantAuthorityGeneration", Map.of(), + "membershipAuthorityGeneration", Map.of(), + "privateRealmGrantVersions", List.of()); + } + + private static String jwks(String kid, RSAPublicKey key) { + return jwksEntries(Map.of(kid, key)); + } + + private static String jwks( + String firstKid, RSAPublicKey firstKey, String secondKid, RSAPublicKey secondKey) { + return jwksEntries(Map.of(firstKid, firstKey, secondKid, secondKey)); + } + + private static String jwksEntries(Map keys) { + StringBuilder json = new StringBuilder("{\"keys\":["); + boolean first = true; + for (Map.Entry entry : keys.entrySet()) { + if (!first) { + json.append(','); + } + first = false; + RSAPublicKey key = entry.getValue(); + json.append("{\"kty\":\"RSA\",\"kid\":\"") + .append(entry.getKey()) + .append("\",\"use\":\"sig\",\"alg\":\"RS256\",\"n\":\"") + .append(encode(unsigned(key.getModulus()))) + .append("\",\"e\":\"") + .append(encode(unsigned(key.getPublicExponent()))) + .append("\"}"); + } + return json.append("]}").toString(); + } + + private static KeyPair rsa3072() { + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(new RSAKeyGenParameterSpec(3_072, RSAKeyGenParameterSpec.F4)); + KeyPair key = generator.generateKeyPair(); + return key; + } catch (Exception failure) { + throw new AssertionError(failure); + } + } + + private static byte[] unsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + if (bytes.length > 1 && bytes[0] == 0) { + return java.util.Arrays.copyOfRange(bytes, 1, bytes.length); + } + return bytes; + } + + private static String encode(byte[] value) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverProtoMapperTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverProtoMapperTest.java new file mode 100644 index 0000000000..8579e2778f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodReceiverProtoMapperTest.java @@ -0,0 +1,175 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.account.v1.ReceiveAccountJwtReadinessProbeRequest; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerSelector.LocalIdentity; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import org.junit.jupiter.api.Test; + +class AccountJwtReadinessPodReceiverProtoMapperTest { + private final AccountJwtReadinessPodReceiverProtoMapper mapper = + new AccountJwtReadinessPodReceiverProtoMapper(); + + @Test + void acceptsOnlyTheCanaryAndThreeAccountProductionProfilesAsApplicable() { + Map profiles = + Map.of( + "account-jwt-readiness-canary", + "firemud-account-jwt-readiness", + ControlUiJwtProfileValidator.PROFILE, + ControlUiJwtProfileValidator.AUDIENCE, + PlayerBootstrapJwtProfileValidator.PROFILE, + PlayerBootstrapJwtProfileValidator.AUDIENCE, + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.AUDIENCE); + + for (Map.Entry profile : profiles.entrySet()) { + var parsed = mapper.parse(request(profile.getKey(), profile.getValue()).build()); + assertThat(parsed.coordinates().getExpectedOutcome()) + .isEqualTo(ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT); + assertThat(parsed.compactTokenSha256()).matches("[0-9a-f]{64}"); + assertThat(parsed.probeKind()) + .isEqualTo( + "account-jwt-readiness-canary".equals(profile.getKey()) + ? AccountMountedJwtSignerBundle.ProbeKind.CANARY + : AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE); + } + } + + @Test + void rejectsUnknownFieldsUnsupportedProfilesAndTypedInapplicableSuccess() { + var unknownRequest = + request(ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE) + .setUnknownFields(unknownFields()) + .build(); + assertInvalid(unknownRequest); + + var unknownCoordinates = + request(ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE) + .setCoordinates( + request(ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE) + .getCoordinates() + .toBuilder() + .setUnknownFields(unknownFields())) + .build(); + assertInvalid(unknownCoordinates); + + assertInvalid( + request(ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE) + .setCoordinates( + request(ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE) + .getCoordinates() + .toBuilder() + .setExpectedOutcome( + ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT)) + .build()); + assertInvalid( + request("account-login", "account-service") + .setCoordinates( + request("account-login", "account-service").getCoordinates().toBuilder() + .setExpectedOutcome(ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT)) + .build()); + } + + @Test + void rejectsMalformedCoordinatesAndUnboundedOrNonAsciiCompactTokens() { + assertInvalid( + request(ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE) + .setCoordinates( + request(ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE) + .getCoordinates() + .toBuilder() + .setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.UNKNOWN)) + .build()); + assertInvalid( + request(ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE) + .setCompactJwt("x".repeat(16 * 1024 + 1)) + .build()); + assertInvalid( + request(ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE) + .setCompactJwt("header.payload.é") + .build()); + } + + @Test + void derivesSelectorOnlyFromValidatedCoordinatesAndProtectedLocalIdentity() { + var parsed = + mapper.parse( + request(ControlUiJwtProfileValidator.PROFILE, ControlUiJwtProfileValidator.AUDIENCE) + .build()); + LocalIdentity identity = + new LocalIdentity( + "account-service", + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "10.0.0.12", + "https://10.0.0.12:6565", + "spiffe://firemud/ns/firemud-prod/sa/account-service", + "registry.example/account@sha256:" + "a".repeat(64), + "b".repeat(64), + "c".repeat(64), + "inventory-r1", + "d".repeat(64), + "e".repeat(64)); + + var selector = mapper.toOwnerSelector(parsed, identity); + + assertThat(selector.validatorId()).isEqualTo("account-service"); + assertThat(selector.expectedOutcome()) + .isEqualTo(AccountJwtReadinessReceiverInvocationPort.ProbeExpectation.ACCEPT); + assertThat(selector.localIdentity()).isEqualTo(identity); + } + + private static ReceiveAccountJwtReadinessProbeRequest.Builder request( + String profile, String audience) { + boolean canary = "account-jwt-readiness-canary".equals(profile); + ReadinessProbeCoordinates coordinates = + ReadinessProbeCoordinates.newBuilder() + .setRotationOperationId(UUID.randomUUID().toString()) + .setOperationDigest("a".repeat(64)) + .setPlanDigest("b".repeat(64)) + .setPlanVersion(2) + .setRegistryVersion(1) + .setValidatorId("account-service") + .setTokenProfile(profile) + .setAudience(audience) + .setProbeKind( + canary + ? ReadinessProbeCoordinates.ProbeKind.CANARY + : ReadinessProbeCoordinates.ProbeKind.REPRESENTATIVE) + .setExpectedOutcome(ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setJti(UUID.randomUUID().toString()) + .setEntryVersion(4) + .setTargetGeneration("7") + .setTargetKid("pending-key-7") + .setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.ABSENT) + .setIssuedAtEpochSeconds(1_900_000_000L) + .setExpiresAtEpochSeconds(1_900_000_120L) + .setPlanExpiresAtEpochSeconds(1_900_000_180L) + .build(); + return ReceiveAccountJwtReadinessProbeRequest.newBuilder() + .setSchemaVersion(1) + .setCoordinates(coordinates) + .setCompactJwt("header.payload.signature"); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private void assertInvalid(ReceiveAccountJwtReadinessProbeRequest request) { + assertThatThrownBy(() -> mapper.parse(request)) + .isInstanceOf( + AccountJwtReadinessPodReceiverProtoMapper.InvalidReceiverRequestException.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java new file mode 100644 index 0000000000..6a85233df2 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import net.firedevops.firemud.account.v1.AccountJwtReadinessProbeOwnerServiceGrpc; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import org.junit.jupiter.api.Test; + +class AccountJwtReadinessProbeOwnerProtoMapperTest { + private final AccountJwtReadinessProbeOwnerProtoMapper mapper = + new AccountJwtReadinessProbeOwnerProtoMapper(); + + @Test + void parsesClosedV2CoordinatesWithExplicitNoActiveSignerFence() { + var parsed = mapper.parse(request().build()); + + assertThat(parsed.planVersion()).isEqualTo(2); + assertThat(parsed.expectedActive()).isEmpty(); + assertThat(parsed.localIdentity().podUid()).isEqualTo("66666666-6666-4666-8666-666666666666"); + assertThat(parsed.compactTokenSha256()).isEqualTo("d".repeat(64)); + } + + @Test + void rejectsUnknownActiveStateAndUnknownNestedFields() { + var unknownState = + request() + .setExpectedCoordinates( + request().getExpectedCoordinates().toBuilder().setExpectedActiveStateValue(3)) + .build(); + assertThatThrownBy(() -> mapper.parse(unknownState)) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + var unknownLocal = + request() + .setProtectedLocalIdentity( + request().getProtectedLocalIdentity().toBuilder().setUnknownFields(unknown)) + .build(); + assertThatThrownBy(() -> mapper.parse(unknownLocal)) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + } + + @Test + void wireHasNoCompactJwtRequestOrResponseField() { + assertThat(GetCurrentReadinessProbeOwnerRequest.getDescriptor().findFieldByName("compact_jwt")) + .isNull(); + assertThat(GetCurrentReadinessProbeOwnerResponse.getDescriptor().findFieldByName("compact_jwt")) + .isNull(); + assertThat( + AccountJwtReadinessProbeOwnerServiceGrpc.getGetCurrentReadinessProbeOwnerMethod() + .getFullMethodName()) + .isEqualTo("account.v1.AccountJwtReadinessProbeOwnerService/GetCurrentReadinessProbeOwner"); + } + + private static GetCurrentReadinessProbeOwnerRequest.Builder request() { + var coordinates = + ReadinessProbeCoordinates.newBuilder() + .setRotationOperationId("33333333-3333-4333-8333-333333333333") + .setOperationDigest("b".repeat(64)) + .setPlanDigest("c".repeat(64)) + .setPlanVersion(2) + .setRegistryVersion(1) + .setValidatorId("game-session-service") + .setTokenProfile("game-session-account-delegation") + .setAudience("account-service") + .setProbeKind(ReadinessProbeCoordinates.ProbeKind.REPRESENTATIVE) + .setExpectedOutcome(ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setJti("44444444-4444-4444-8444-444444444444") + .setEntryVersion(2) + .setTargetGeneration("1") + .setTargetKid("pending-key") + .setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.ABSENT) + .setIssuedAtEpochSeconds(20_100) + .setExpiresAtEpochSeconds(20_300) + .setPlanExpiresAtEpochSeconds(20_300); + var source = + net.firedevops.firemud.account.v1.AccountSourceIdentity.newBuilder() + .setEnvironmentId("prod") + .setClusterId("cluster-a") + .setClusterIncarnationUid("11111111-1111-4111-8111-111111111111") + .setNamespace("firemud") + .setNamespaceUid("22222222-2222-4222-8222-222222222222") + .setConfigMapUid("77777777-7777-4777-8777-777777777777") + .setBindingRevision("source-r1") + .setApiServerOrigin("https://api.example.test:6443") + .setServingCaSha256("8".repeat(64)); + var local = + net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity.newBuilder() + .setValidatorId("game-session-service") + .setDeploymentUid("55555555-5555-4555-8555-555555555555") + .setPodUid("66666666-6666-4666-8666-666666666666") + .setPodIp("10.0.0.1") + .setDirectPodEndpoint("grpcs://10.0.0.1:9443") + .setCanonicalServiceUri("spiffe://firemud/ns/firemud/sa/game-session-jwt-validator") + .setImage("registry.example/validator@sha256:" + "e".repeat(64)) + .setVerifierConfigSha256("f".repeat(64)) + .setApplicabilityMatrixDigest("a".repeat(64)) + .setSourceInventoryRevision("gs-source-r1") + .setSourceInventoryDigest("9".repeat(64)) + .setServerLeafSpkiSha256("8".repeat(64)) + .setAccountJwksSourceIdentity(source) + .setAccountJwksTrustConfigRevision(4); + return GetCurrentReadinessProbeOwnerRequest.newBuilder() + .setSchemaVersion(1) + .setExpectedCoordinates(coordinates) + .setCompactTokenSha256("d".repeat(64)) + .setProtectedLocalIdentity(local); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerServiceTest.java new file mode 100644 index 0000000000..71462c1cbf --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerServiceTest.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.time.Clock; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.OwnerProbeEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerSelector.LocalIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountJwtReadinessProbeOwnerServiceTest { + private static final Binding BINDING = + new Binding( + "prod", "cluster-a", "firemud", CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "trust-r1"); + + @Test + void selectsOwnerContextThenObservesInventoryBeforeOpeningTheOwnerReadTransaction() { + List order = new ArrayList<>(); + AccountJwtReadinessProbeRepository repository = mock(AccountJwtReadinessProbeRepository.class); + AccountJwtValidatorInventorySource inventorySource = + mock(AccountJwtValidatorInventorySource.class); + InventorySnapshot snapshot = mock(InventorySnapshot.class); + when(snapshot.namespace()).thenReturn(BINDING.namespace()); + AccountJwtReadinessProbeOwnerSelector selector = selector(); + ObservationContext context = + new ObservationContext( + ObservationPurpose.STRICT_READY, selector.rotationOperationId(), "9".repeat(64)); + when(repository.readCurrentInventoryObservationContext( + eq(BINDING), eq(TRUST), eq(selector.rotationOperationId()))) + .thenAnswer( + ignored -> { + order.add("context"); + return context; + }); + when(inventorySource.observe(context)) + .thenAnswer( + ignored -> { + assertThat(order).containsExactly("transaction", "context", "commit"); + order.add("inventory"); + return snapshot; + }); + OwnerProbeEvidence evidence = mock(OwnerProbeEvidence.class); + when(repository.readCurrentProbeOwner( + eq(BINDING), eq(TRUST), eq(selector), eq(snapshot), eq(BINDING.namespace()))) + .thenAnswer( + ignored -> { + order.add("repository"); + assertThat(order) + .containsExactly( + "transaction", "context", "commit", "inventory", "transaction", "repository"); + return evidence; + }); + TransactionTemplate transaction = + new TransactionTemplate(new RecordingTransactionManager(order)); + AccountJwtReadinessProbeService service = + new AccountJwtReadinessProbeService( + repository, transaction, Clock.systemUTC(), inventorySource); + + assertThat(service.readCurrentProbeOwner(BINDING, TRUST, selector, BINDING.namespace())) + .isSameAs(evidence); + assertThat(order) + .containsExactly( + "transaction", "context", "commit", "inventory", "transaction", "repository", "commit"); + verify(repository) + .readCurrentInventoryObservationContext(BINDING, TRUST, selector.rotationOperationId()); + verify(inventorySource).observe(context); + verify(repository) + .readCurrentProbeOwner(BINDING, TRUST, selector, snapshot, BINDING.namespace()); + } + + private static AccountJwtReadinessProbeOwnerSelector selector() { + return new AccountJwtReadinessProbeOwnerSelector( + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "b".repeat(64), + "c".repeat(64), + 2, + 1, + "game-session-service", + "game-session-account-delegation", + "account-service", + ProbeKind.REPRESENTATIVE, + ProbeExpectation.ACCEPT, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + 2, + "1", + "pending-key", + Optional.empty(), + 20_100, + 20_300, + 20_300, + "d".repeat(64), + new LocalIdentity( + "game-session-service", + "55555555-5555-4555-8555-555555555555", + "66666666-6666-4666-8666-666666666666", + "10.0.0.1", + URI.create("grpcs://10.0.0.1:9443").toString(), + "spiffe://firemud/ns/firemud/sa/game-session-jwt-validator", + "registry.example/validator@sha256:" + "e".repeat(64), + "f".repeat(64), + "a".repeat(64), + "gs-r1", + "9".repeat(64), + "8".repeat(64))); + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private final List order; + + private RecordingTransactionManager(List order) { + this.order = order; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + order.add("transaction"); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + order.add("commit"); + } + + @Override + public void rollback(TransactionStatus status) { + throw new AssertionError("Unexpected transaction rollback"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeServiceTest.java new file mode 100644 index 0000000000..d3452a63f4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeServiceTest.java @@ -0,0 +1,274 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.DeliveryClaim; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeState; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.SignerFence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountJwtReadinessProbeServiceTest { + private static final Binding BINDING = + new Binding( + "staging", "cluster-a", "firemud", CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "trust-r1"); + + @Test + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = "Missing fixed paths prove retries never read mounted signing material") + void exactIssuedRetryReadsOnlyStoredEvidenceAndDoesNotRemintOrRedeliver() { + AccountJwtReadinessProbeRepository repository = mock(AccountJwtReadinessProbeRepository.class); + UUID operationId = UUID.randomUUID(); + UUID jti = UUID.randomUUID(); + long issuedAt = 20_300; + ProbeEntry issued = + new ProbeEntry( + operationId, + "b".repeat(64), + "account-service", + "game-session-account-delegation", + "account-service", + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + jti, + "1", + "first-key", + Optional.empty(), + 1, + 3, + issuedAt, + issuedAt + 180, + ProbeState.ISSUED, + Optional.empty(), + Optional.of(issuedAt), + Optional.of("c".repeat(64)), + Optional.empty()); + ReadinessProbePlan plan = + new ReadinessProbePlan( + operationId, + BINDING, + TRUST, + "d".repeat(64), + "e".repeat(64), + "f".repeat(64), + 2, + "1", + "first-key", + "a".repeat(64), + new SignerFence(Optional.empty(), Optional.empty()), + "1".repeat(64), + "2".repeat(64), + "3".repeat(64), + "{}", + "4".repeat(64), + false, + 300, + 20_000, + 20_300, + 20_600, + 1, + "5".repeat(64), + List.of(issued)); + when(repository.readCurrentPlan(BINDING, TRUST, operationId)).thenReturn(plan); + DeliveryClaim claim = deliveryClaim(plan); + when(repository.requireCurrentDeliveryClaim( + org.mockito.ArgumentMatchers.eq(BINDING), + org.mockito.ArgumentMatchers.eq(TRUST), + org.mockito.ArgumentMatchers.eq(plan), + org.mockito.ArgumentMatchers.eq(claim), + org.mockito.ArgumentMatchers.any())) + .thenReturn(claim); + AtomicInteger deliveries = new AtomicInteger(); + AccountJwtReadinessProbeService service = + new AccountJwtReadinessProbeService( + repository, + new TransactionTemplate(new NoopTransactionManager()), + Clock.fixed(Instant.ofEpochSecond(20_400), ZoneOffset.UTC), + Path.of("/missing/private"), + Path.of("pending.key"), + Path.of("/missing/public"), + Path.of("jwks.json")); + + List result = + service.issueCurrentPlan( + BINDING, TRUST, operationId, claim, (metadata, jwt) -> deliveries.incrementAndGet()); + + assertThat(result).containsExactly(issued); + assertThat(result.get(0).compactTokenSha256()).contains("c".repeat(64)); + assertThat(deliveries).hasValue(0); + verify(repository, org.mockito.Mockito.times(2)).readCurrentPlan(BINDING, TRUST, operationId); + verify(repository) + .requireCurrentDeliveryClaim( + BINDING, TRUST, plan, claim, java.time.Instant.ofEpochSecond(20_400)); + verifyNoMoreInteractions(repository); + } + + @Test + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = "Missing fixed paths prove retries never read mounted signing material") + void exactVerifiedRetryPreservesReceiptWithoutRemintOrRedelivery() { + AccountJwtReadinessProbeRepository repository = mock(AccountJwtReadinessProbeRepository.class); + UUID operationId = UUID.randomUUID(); + UUID jti = UUID.randomUUID(); + long issuedAt = 20_300; + String tokenHash = "c".repeat(64); + var receipt = + new AccountJwtReadinessProbeRepository.VerificationReceipt( + 1, + 3, + 4, + 20_400, + "6".repeat(64), + "first-key", + "account-validator-instance-7", + "7".repeat(64), + "readiness-r1", + "spiffe://firemud/ns/firemud/sa/account-jwt-readiness-harness", + "8".repeat(64)); + ProbeEntry verified = + new ProbeEntry( + operationId, + "b".repeat(64), + "account-service", + "game-session-account-delegation", + "account-service", + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + jti, + "1", + "first-key", + Optional.empty(), + 1, + 4, + issuedAt, + issuedAt + 180, + ProbeState.VERIFIED, + Optional.empty(), + Optional.of(issuedAt), + Optional.of(tokenHash), + Optional.of(receipt)); + ReadinessProbePlan plan = + new ReadinessProbePlan( + operationId, + BINDING, + TRUST, + "d".repeat(64), + "e".repeat(64), + "f".repeat(64), + 2, + "1", + "first-key", + "a".repeat(64), + new SignerFence(Optional.empty(), Optional.empty()), + "1".repeat(64), + "2".repeat(64), + "3".repeat(64), + "{}", + "4".repeat(64), + false, + 300, + 20_000, + 20_300, + 20_600, + 1, + "5".repeat(64), + List.of(verified)); + when(repository.readCurrentPlan(BINDING, TRUST, operationId)).thenReturn(plan); + DeliveryClaim claim = deliveryClaim(plan); + when(repository.requireCurrentDeliveryClaim( + org.mockito.ArgumentMatchers.eq(BINDING), + org.mockito.ArgumentMatchers.eq(TRUST), + org.mockito.ArgumentMatchers.eq(plan), + org.mockito.ArgumentMatchers.eq(claim), + org.mockito.ArgumentMatchers.any())) + .thenReturn(claim); + AtomicInteger deliveries = new AtomicInteger(); + AccountJwtReadinessProbeService service = + new AccountJwtReadinessProbeService( + repository, + new TransactionTemplate(new NoopTransactionManager()), + Clock.fixed(Instant.ofEpochSecond(20_400), ZoneOffset.UTC), + Path.of("/missing/private"), + Path.of("pending.key"), + Path.of("/missing/public"), + Path.of("jwks.json")); + + List result = + service.issueCurrentPlan( + BINDING, TRUST, operationId, claim, (metadata, jwt) -> deliveries.incrementAndGet()); + + assertThat(result).containsExactly(verified); + assertThat(result.get(0).verificationReceipt()).contains(receipt); + assertThat(deliveries).hasValue(0); + verify(repository, org.mockito.Mockito.times(2)).readCurrentPlan(BINDING, TRUST, operationId); + verify(repository) + .requireCurrentDeliveryClaim( + BINDING, TRUST, plan, claim, java.time.Instant.ofEpochSecond(20_400)); + verifyNoMoreInteractions(repository); + } + + private static final class NoopTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } + + private static DeliveryClaim deliveryClaim(ReadinessProbePlan plan) { + return new DeliveryClaim( + plan.operationId(), + plan.planDigest(), + TRUST.expectedClusterIncarnationUid(), + TRUST.expectedNamespaceUid(), + TRUST.bindingDigest(), + TRUST.configRevision(), + plan.targetGeneration(), + plan.targetKid(), + plan.expectedFence().durableActive(), + "9".repeat(64), + "readiness-r1", + plan.expiresAtEpochSecond() + 1, + "account-service", + "account-validator-instance-1", + "spiffe://firemud/ns/firemud/sa/account-jwt-readiness-harness", + "8".repeat(64), + plan.notBeforeEpochSecond(), + plan.expiresAtEpochSecond(), + "7".repeat(64)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessTransportOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessTransportOwnerTest.java new file mode 100644 index 0000000000..bdd842e63e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessTransportOwnerTest.java @@ -0,0 +1,402 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.account.v1.IssueReadinessProbesRequest; +import net.firedevops.firemud.account.v1.ValidateReadinessProbeRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.PeerIdentity; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.DeliveryClaim; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeState; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.SignerFence; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.VerificationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtReadinessTlsInterceptor; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountJwtReadinessTransportOwnerTest { + private static final Instant NOW = Instant.parse("2030-06-01T00:10:00Z"); + private static final UUID OPERATION_ID = UUID.randomUUID(); + private static final UUID JTI = UUID.randomUUID(); + private static final String PLAN_DIGEST = "a".repeat(64); + private static final String TOKEN_HASH = "c".repeat(64); + private static final String COMPACT_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ4In0.signature"; + private static final String VALIDATOR_URI = + "spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"; + + @Test + void unknownOrMissingSchemaIsRejectedBeforeAnyOwnerOrRepositoryAccess() { + Fixture fixture = new Fixture(false); + IssueReadinessProbesRequest unknown = + IssueReadinessProbesRequest.newBuilder() + .setSchemaVersion(1) + .mergeUnknownFields(unknownField()) + .build(); + IssueReadinessProbesRequest missing = IssueReadinessProbesRequest.getDefaultInstance(); + ValidateReadinessProbeRequest unknownValidation = + ValidateReadinessProbeRequest.newBuilder() + .setSchemaVersion(1) + .mergeUnknownFields(unknownField()) + .build(); + ValidateReadinessProbeRequest missingValidation = + ValidateReadinessProbeRequest.getDefaultInstance(); + + assertThatThrownBy(() -> fixture.owner.issue(unknown, fixture.caller)) + .isInstanceOf(AccountJwtReadinessValidationService.InvalidReadinessRequestException.class); + assertThatThrownBy(() -> fixture.owner.issue(missing, fixture.caller)) + .isInstanceOf(AccountJwtReadinessValidationService.InvalidReadinessRequestException.class); + assertThatThrownBy(() -> fixture.owner.validate(unknownValidation, fixture.caller)) + .isInstanceOf(AccountJwtReadinessValidationService.InvalidReadinessRequestException.class); + assertThatThrownBy(() -> fixture.owner.validate(missingValidation, fixture.caller)) + .isInstanceOf(AccountJwtReadinessValidationService.InvalidReadinessRequestException.class); + verifyNoInteractions(fixture.repository, fixture.producer, fixture.validation); + } + + @Test + void claimCommitsBeforeSigningAndResponseContainsOnlyReadBackIssuedProbes() { + Fixture fixture = new Fixture(false); + fixture.stubCurrentBindings(); + ReadinessProbePlan plan = fixture.plan(); + ProbeEntry planned = fixture.entry(ProbeState.PLANNED, 1, Optional.empty()); + ProbeEntry issued = fixture.entry(ProbeState.ISSUED, 3, Optional.of(TOKEN_HASH)); + when(plan.entries()).thenReturn(List.of(planned)); + when(fixture.producer.planCurrent(fixture.accountBinding, fixture.trustFence)).thenReturn(plan); + DeliveryClaim claim = mock(DeliveryClaim.class); + when(fixture.repository.claimSingleDelivery( + eq(fixture.accountBinding), + eq(fixture.trustFence), + eq(plan), + eq(fixture.readinessBinding), + eq(fixture.peer), + any(Instant.class))) + .thenReturn(claim); + + var metadata = + new AccountJwtReadinessProbeService.DeliveryMetadata( + OPERATION_ID, + PLAN_DIGEST, + 1, + "account-service", + "account-jwt-readiness-canary", + "firemud-account-jwt-readiness", + ProbeKind.CANARY, + JTI, + "2", + "pending-key-2", + Optional.empty(), + Optional.empty(), + 1, + 3, + 20_300, + 20_600, + TOKEN_HASH); + doAnswer( + invocation -> { + assertThat(fixture.transactions.committed).isTrue(); + AccountJwtReadinessProbeService.OwnerInternalProbeDelivery delivery = + invocation.getArgument(4); + delivery.deliver(metadata, COMPACT_JWT.getBytes(StandardCharsets.US_ASCII)); + return List.of(issued); + }) + .when(fixture.producer) + .issueCurrentPlan( + eq(fixture.accountBinding), + eq(fixture.trustFence), + eq(OPERATION_ID), + eq(claim), + any(AccountJwtReadinessProbeService.OwnerInternalProbeDelivery.class)); + + var response = fixture.owner.issue(validIssueRequest(), fixture.caller); + + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getRotationOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getPlanDigest()).isEqualTo(PLAN_DIGEST); + assertThat(response.getValidatorInventoryComplete()).isFalse(); + assertThat(response.getProbesCount()).isEqualTo(1); + assertThat(response.getProbes(0).getJti()).isEqualTo(JTI.toString()); + assertThat(response.getProbes(0).getCompactTokenSha256()).isEqualTo(TOKEN_HASH); + assertThat(response.getProbes(0).getCompactJwt()).isEqualTo(COMPACT_JWT); + verify(fixture.repository) + .claimSingleDelivery( + eq(fixture.accountBinding), + eq(fixture.trustFence), + eq(plan), + eq(fixture.readinessBinding), + eq(fixture.peer), + any(Instant.class)); + verify(fixture.producer) + .issueCurrentPlan( + eq(fixture.accountBinding), + eq(fixture.trustFence), + eq(OPERATION_ID), + eq(claim), + any(AccountJwtReadinessProbeService.OwnerInternalProbeDelivery.class)); + verifyNoMoreInteractions(fixture.repository); + } + + @Test + void uncertainClaimCommitNeverInvokesSignerOrCreatesAnotherAttempt() { + Fixture fixture = new Fixture(true); + fixture.stubCurrentBindings(); + ReadinessProbePlan plan = fixture.plan(); + when(fixture.producer.planCurrent(fixture.accountBinding, fixture.trustFence)).thenReturn(plan); + DeliveryClaim claim = mock(DeliveryClaim.class); + when(fixture.repository.claimSingleDelivery( + eq(fixture.accountBinding), + eq(fixture.trustFence), + eq(plan), + eq(fixture.readinessBinding), + eq(fixture.peer), + any(Instant.class))) + .thenReturn(claim); + + assertThatThrownBy(() -> fixture.owner.issue(validIssueRequest(), fixture.caller)) + .isInstanceOf(IllegalStateException.class); + + verify(fixture.producer).planCurrent(fixture.accountBinding, fixture.trustFence); + verify(fixture.producer, never()) + .issueCurrentPlan( + any(), + any(), + any(), + any(), + any(AccountJwtReadinessProbeService.OwnerInternalProbeDelivery.class)); + verify(fixture.repository) + .claimSingleDelivery( + eq(fixture.accountBinding), + eq(fixture.trustFence), + eq(plan), + eq(fixture.readinessBinding), + eq(fixture.peer), + any(Instant.class)); + } + + @Test + void claimReadbackFailureNeverInvokesSigner() { + Fixture fixture = new Fixture(false); + fixture.stubCurrentBindings(); + ReadinessProbePlan plan = fixture.plan(); + when(fixture.producer.planCurrent(fixture.accountBinding, fixture.trustFence)).thenReturn(plan); + when(fixture.repository.claimSingleDelivery( + eq(fixture.accountBinding), + eq(fixture.trustFence), + eq(plan), + eq(fixture.readinessBinding), + eq(fixture.peer), + any(Instant.class))) + .thenThrow(new AccountJwtReadinessProbeRepository.StorageUnavailableException("readback")); + + assertThatThrownBy(() -> fixture.owner.issue(validIssueRequest(), fixture.caller)) + .isInstanceOf(AccountJwtReadinessProbeRepository.StorageUnavailableException.class); + verify(fixture.producer, never()) + .issueCurrentPlan( + any(), + any(), + any(), + any(), + any(AccountJwtReadinessProbeService.OwnerInternalProbeDelivery.class)); + } + + @Test + void validateReturnsTheExactProductionReceiptWithoutInventingReadinessEvidence() { + Fixture fixture = new Fixture(false); + VerificationReceipt receipt = + new VerificationReceipt( + 1, + 3, + 4, + 20_400, + "d".repeat(64), + "pending-key-2", + "account-validator-instance-7", + "e".repeat(64), + "revision-7", + VALIDATOR_URI, + "f".repeat(64)); + ValidateReadinessProbeRequest request = + ValidateReadinessProbeRequest.newBuilder() + .setSchemaVersion(1) + .setRotationOperationId(OPERATION_ID.toString()) + .setValidatorId("account-service") + .setTokenProfile("account-jwt-readiness-canary") + .setAudience("firemud-account-jwt-readiness") + .setProbeKind("CANARY") + .setJti(JTI.toString()) + .setCompactJwt(COMPACT_JWT) + .build(); + when(fixture.validation.validate(request, fixture.caller)).thenReturn(receipt); + + var response = fixture.owner.validate(request, fixture.caller); + + assertThat(response.getResult()) + .isEqualTo( + net.firedevops.firemud.account.v1.ValidateReadinessProbeResponse.Result + .NON_AUTHORIZING_VERIFICATION_RECORDED); + assertThat(response.getReceiptVersion()).isEqualTo(receipt.receiptVersion()); + assertThat(response.getReceiptSha256()).isEqualTo(receipt.receiptSha256()); + assertThat(response.getObservedAtEpochSeconds()).isEqualTo(receipt.observedAtEpochSecond()); + assertThat(response.getValidatorInstanceId()).isEqualTo(receipt.validatorInstanceId()); + verify(fixture.validation).validate(request, fixture.caller); + verifyNoInteractions(fixture.repository, fixture.producer); + } + + private static IssueReadinessProbesRequest validIssueRequest() { + return IssueReadinessProbesRequest.newBuilder().setSchemaVersion(1).build(); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static final class Fixture { + private final AccountJwtReadinessProbeRepository repository = + mock(AccountJwtReadinessProbeRepository.class); + private final AccountJwtReadinessProbeService producer = + mock(AccountJwtReadinessProbeService.class); + private final AccountJwtReadinessValidationService validation = + mock(AccountJwtReadinessValidationService.class); + private final AccountJwtReadinessTlsInterceptor.AuthenticatedCaller caller = + mock(AccountJwtReadinessTlsInterceptor.AuthenticatedCaller.class); + private final AccountJwtReadinessTrustBinding.Binding readinessBinding = + mock(AccountJwtReadinessTrustBinding.Binding.class); + private final AccountJwtSignerMaterializerTrustBinding.Binding signerBinding = + mock(AccountJwtSignerMaterializerTrustBinding.Binding.class); + private final AccountJwtSignerDesiredStateRepository.Binding accountBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + AccountJwtSignerDesiredStateRepository.CustodyMode + .INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private final TrustFence trustFence = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "b".repeat(64), + "revision-7"); + private final PeerIdentity peer = new PeerIdentity(VALIDATOR_URI, "f".repeat(64)); + private final RecordingTransactionManager transactions; + private final AccountJwtReadinessTransportOwner owner; + + private Fixture(boolean failCommit) { + transactions = new RecordingTransactionManager(failCommit); + owner = + new AccountJwtReadinessTransportOwner( + repository, + producer, + validation, + new TransactionTemplate(transactions), + Clock.fixed(NOW, ZoneOffset.UTC)); + when(caller.peer()).thenReturn(peer); + when(validation.requireAuthenticatedBinding(caller)).thenReturn(readinessBinding); + when(validation.requireCurrentSignerBinding(readinessBinding)).thenReturn(signerBinding); + when(signerBinding.accountBinding()).thenReturn(accountBinding); + when(signerBinding.expectedClusterIncarnationUid()) + .thenReturn("11111111-1111-4111-8111-111111111111"); + when(signerBinding.expectedNamespaceUid()).thenReturn("22222222-2222-4222-8222-222222222222"); + when(signerBinding.bindingDigest()).thenReturn("b".repeat(64)); + when(signerBinding.configRevision()).thenReturn("revision-7"); + } + + private void stubCurrentBindings() { + org.mockito.Mockito.doNothing() + .when(validation) + .requireBindingsUnchanged(readinessBinding, signerBinding, caller); + } + + private ReadinessProbePlan plan() { + ReadinessProbePlan plan = mock(ReadinessProbePlan.class); + when(plan.operationId()).thenReturn(OPERATION_ID); + when(plan.planDigest()).thenReturn(PLAN_DIGEST); + when(plan.planVersion()).thenReturn(1); + when(plan.plannedAtEpochSecond()).thenReturn(20_000L); + when(plan.notBeforeEpochSecond()).thenReturn(20_300L); + when(plan.expiresAtEpochSecond()).thenReturn(20_600L); + when(plan.targetGeneration()).thenReturn("2"); + when(plan.targetKid()).thenReturn("pending-key-2"); + when(plan.validatorInventoryComplete()).thenReturn(false); + when(plan.expectedFence()).thenReturn(new SignerFence(Optional.empty(), Optional.empty())); + ProbeEntry plannedEntry = entry(ProbeState.PLANNED, 1, Optional.empty()); + when(plan.entries()).thenReturn(List.of(plannedEntry)); + return plan; + } + + private ProbeEntry entry(ProbeState state, long version, Optional tokenHash) { + ProbeEntry entry = mock(ProbeEntry.class); + when(entry.rotationOperationId()).thenReturn(OPERATION_ID); + when(entry.planDigest()).thenReturn(PLAN_DIGEST); + when(entry.validatorId()).thenReturn("account-service"); + when(entry.tokenProfile()).thenReturn("account-jwt-readiness-canary"); + when(entry.audience()).thenReturn("firemud-account-jwt-readiness"); + when(entry.probeKind()).thenReturn(ProbeKind.CANARY); + when(entry.jti()).thenReturn(JTI); + when(entry.targetGeneration()).thenReturn("2"); + when(entry.targetKid()).thenReturn("pending-key-2"); + when(entry.expectedActive()).thenReturn(Optional.empty()); + when(entry.registryVersion()).thenReturn(1); + when(entry.entryVersion()).thenReturn(version); + when(entry.plannedIssuedAtEpochSecond()).thenReturn(20_300L); + when(entry.expiresAtEpochSecond()).thenReturn(20_600L); + when(entry.state()).thenReturn(state); + when(entry.compactTokenSha256()).thenReturn(tokenHash); + return entry; + } + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private final boolean failCommit; + private final AtomicBoolean committed = new AtomicBoolean(); + + private RecordingTransactionManager(boolean failCommit) { + this.failCommit = failCommit; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + if (failCommit) { + throw new IllegalStateException("Commit outcome is uncertain"); + } + committed.set(true); + } + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessValidationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessValidationServiceTest.java new file mode 100644 index 0000000000..6fec28d106 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessValidationServiceTest.java @@ -0,0 +1,857 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.RSAKeyGenParameterSpec; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.ValidateReadinessProbeRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeState; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.VerificationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtReadinessTlsInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtReadinessValidationServiceTest { + private static final Instant NOW = Instant.parse("2030-06-01T00:10:00Z"); + private static final String HARNESS_URI = + "spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"; + private static final String MATERIALIZER_URI = + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + private static final String SPKI_TEXT = "mock authenticated readiness leaf key"; + private static final String KID = "pending-key-7"; + private static final String RESERVED_SUBJECT = "00000000-0000-4000-8000-000000000001"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Map REPRESENTATIVE_PROFILES = + Map.of( + ControlUiJwtProfileValidator.PROFILE, + ControlUiJwtProfileValidator.AUDIENCE, + PlayerBootstrapJwtProfileValidator.PROFILE, + PlayerBootstrapJwtProfileValidator.AUDIENCE, + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.AUDIENCE); + + @Test + void representativeUsesActualRs256VerifierAndRecordsOnlyTheExactNonAuthorizingReceipt() + throws Exception { + Fixture fixture = new Fixture(AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE); + VerificationReceipt result = fixture.service.validate(fixture.request, fixture.authenticated); + + assertThat(result).isEqualTo(fixture.receipt); + assertThat(result.receiptSha256()).matches("[0-9a-f]{64}"); + verify(fixture.repository) + .recordVerified( + eq(fixture.signerBinding.accountBinding()), + eq(fixture.trustFence), + eq(fixture.operationId), + eq("account-service"), + eq(GameSessionAccountDelegationProfile.PROFILE), + eq(GameSessionAccountDelegationProfile.AUDIENCE), + eq(AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE), + eq(fixture.jti), + any(AccountJwtReadinessProbeRepository.VerifiedProbeObservation.class)); + } + + @Test + void eachAccountProfileUsesItsExactAudienceAndCanonicalShapeValidator() throws Exception { + for (Map.Entry profile : REPRESENTATIVE_PROFILES.entrySet()) { + Fixture fixture = + new Fixture( + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + profile.getKey(), + profile.getValue()); + + VerificationReceipt result = fixture.service.validate(fixture.request, fixture.authenticated); + + assertThat(result).isEqualTo(fixture.receipt); + verify(fixture.repository) + .recordVerified( + eq(fixture.signerBinding.accountBinding()), + eq(fixture.trustFence), + eq(fixture.operationId), + eq("account-service"), + eq(profile.getKey()), + eq(profile.getValue()), + eq(AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE), + eq(fixture.jti), + any(AccountJwtReadinessProbeRepository.VerifiedProbeObservation.class)); + } + } + + @Test + void oppositeCounterWireTypesAreRejectedForEveryProfileWithoutRecording() throws Exception { + for (Map.Entry profile : REPRESENTATIVE_PROFILES.entrySet()) { + boolean decimalCounters = + GameSessionAccountDelegationProfile.PROFILE.equals(profile.getKey()); + Object oppositeCounter = decimalCounters ? 1L : "1"; + Fixture fixture = + new Fixture( + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + profile.getKey(), + profile.getValue(), + Map.of( + "tokenGeneration", + oppositeCounter, + "issuanceFence", + oppositeCounter, + "authorityTuple", + authorityTuple(oppositeCounter, oppositeCounter)), + false, + 8); + + assertRejectedWithoutRecording(fixture); + } + } + + @Test + void malformedProfileCountersAreRejectedBeforeRecording() throws Exception { + for (Map.Entry profile : REPRESENTATIVE_PROFILES.entrySet()) { + Object malformedCounter = + GameSessionAccountDelegationProfile.PROFILE.equals(profile.getKey()) ? "01" : 1.5d; + Fixture fixture = + new Fixture( + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + profile.getKey(), + profile.getValue(), + Map.of("tokenGeneration", malformedCounter), + false, + 8); + + assertRejectedWithoutRecording(fixture); + } + } + + @Test + void onlyExactInitialCountersAreAcceptedAfterSignedProfileVerification() throws Exception { + for (Map.Entry profile : REPRESENTATIVE_PROFILES.entrySet()) { + boolean decimalCounters = + GameSessionAccountDelegationProfile.PROFILE.equals(profile.getKey()); + Object nonInitialCounter = decimalCounters ? "2" : 2L; + for (Map nonInitialClaims : + List.>of( + Map.of("tokenGeneration", nonInitialCounter), + Map.of("issuanceFence", nonInitialCounter), + Map.of( + "authorityTuple", + authorityTuple(nonInitialCounter, decimalCounters ? "1" : 1L)))) { + Fixture fixture = + new Fixture( + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + profile.getKey(), + profile.getValue(), + nonInitialClaims, + false, + 8); + + assertRejectedWithoutRecording(fixture); + } + } + } + + @Test + void largeCanonicalDelegationCounterIsComparedWithoutNumericRounding() throws Exception { + String largeCounter = "9007199254740993"; + Fixture fixture = + new Fixture( + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.AUDIENCE, + Map.of( + "issuanceFence", largeCounter, "authorityTuple", authorityTuple(largeCounter, "1")), + false, + 8); + + assertRejectedWithoutRecording(fixture); + } + + @Test + void inapplicableAudienceIsRejectedBeforeReadingOwnerProbeState() throws Exception { + Fixture fixture = + new Fixture( + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + ControlUiJwtProfileValidator.PROFILE, + ControlUiJwtProfileValidator.AUDIENCE); + ValidateReadinessProbeRequest wrongAudience = + fixture.request.toBuilder() + .setAudience(PlayerBootstrapJwtProfileValidator.AUDIENCE) + .build(); + + assertThatThrownBy(() -> fixture.service.validate(wrongAudience, fixture.authenticated)) + .isInstanceOf(AccountJwtReadinessValidationService.InvalidReadinessRequestException.class); + verify(fixture.repository, never()) + .readCurrentEntry(any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void enabledValidationRejectsMissingOrTransportIncompatibleControlUiScopeCap() { + assertThatThrownBy( + () -> + new Fixture( + AccountMountedJwtSignerBundle.ProbeKind.CANARY, + "account-jwt-readiness-canary", + "firemud-account-jwt-readiness", + 0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("scope bound"); + assertThatThrownBy( + () -> + new Fixture( + AccountMountedJwtSignerBundle.ProbeKind.CANARY, + "account-jwt-readiness-canary", + "firemud-account-jwt-readiness", + GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES + 1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("scope bound"); + } + + @Test + void validationBeanIsOffByDefaultAndEnabledConstructionRequiresFiniteTransportSafeCap() { + validationContextRunner() + .run( + context -> + assertThat(context).doesNotHaveBean(AccountJwtReadinessValidationService.class)); + + validationContextRunner() + .withPropertyValues("firemud.account.jwt-readiness.validation.enabled=true") + .run(context -> assertThat(context).hasFailed()); + + for (String invalidCap : List.of("NaN", "Infinity", "-Infinity", "0", "4097")) { + validationContextRunner() + .withPropertyValues( + "firemud.account.jwt-readiness.validation.enabled=true", + "firemud.account.jwt-readiness.validation.max-control-ui-tenant-scopes=" + invalidCap) + .run(context -> assertThat(context).hasFailed()); + } + + for (int boundaryCap : + List.of(1, GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES)) { + validationContextRunner() + .withPropertyValues( + "firemud.account.jwt-readiness.validation.enabled=true", + "firemud.account.jwt-readiness.validation.max-control-ui-tenant-scopes=" + + boundaryCap) + .run( + context -> + assertThat(context) + .hasNotFailed() + .hasSingleBean(AccountJwtReadinessValidationService.class)); + } + } + + @Test + void dedicatedCanaryMustHaveReservedSubjectAndNoApplicationAuthorityClaims() throws Exception { + Fixture fixture = new Fixture(AccountMountedJwtSignerBundle.ProbeKind.CANARY); + + VerificationReceipt result = fixture.service.validate(fixture.request, fixture.authenticated); + + assertThat(result).isEqualTo(fixture.receipt); + verify(fixture.repository) + .recordVerified( + any(), + any(), + eq(fixture.operationId), + eq("account-service"), + eq("account-jwt-readiness-canary"), + eq("firemud-account-jwt-readiness"), + eq(AccountMountedJwtSignerBundle.ProbeKind.CANARY), + eq(fixture.jti), + any(AccountJwtReadinessProbeRepository.VerifiedProbeObservation.class)); + } + + @Test + void signatureFailureAndUnexpectedAuthorityClaimNeverRecordVerification() throws Exception { + Fixture tampered = new Fixture(AccountMountedJwtSignerBundle.ProbeKind.CANARY, Map.of(), true); + assertThatThrownBy(() -> tampered.service.validate(tampered.request, tampered.authenticated)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + verify(tampered.repository, never()) + .recordVerified(any(), any(), any(), any(), any(), any(), any(), any(), any()); + + Fixture withRoles = + new Fixture( + AccountMountedJwtSignerBundle.ProbeKind.CANARY, Map.of("roles", List.of("ADMIN"))); + assertThatThrownBy(() -> withRoles.service.validate(withRoles.request, withRoles.authenticated)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + verify(withRoles.repository, never()) + .recordVerified(any(), any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void noTlsInterceptorContextCannotBeSuppliedByRequestOrDirectServiceCall() throws Exception { + Fixture fixture = new Fixture(AccountMountedJwtSignerBundle.ProbeKind.CANARY); + + assertThatThrownBy(() -> fixture.service.validate(fixture.request, null)) + .isInstanceOf(AccountJwtReadinessValidationService.ReadinessCallerRejectedException.class); + verify(fixture.repository, never()) + .readCurrentEntry(any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void changedProtectedHarnessBindingBetweenReadAndReceiptRefusesVerification() throws Exception { + Fixture fixture = new Fixture(AccountMountedJwtSignerBundle.ProbeKind.CANARY); + Binding rotatedBinding = readinessBinding(sha256(fixture.spki), "readiness-r2"); + when(fixture.readinessProvider.current()) + .thenReturn(Optional.of(fixture.readinessBinding), Optional.of(rotatedBinding)); + + assertThatThrownBy(() -> fixture.service.validate(fixture.request, fixture.authenticated)) + .isInstanceOf(AccountJwtReadinessValidationService.ReadinessCallerRejectedException.class); + verify(fixture.repository, never()) + .recordVerified(any(), any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void unknownRequestFieldsAndOversizedTokensAreRejectedBeforeOwnerStateReads() throws Exception { + Fixture fixture = new Fixture(AccountMountedJwtSignerBundle.ProbeKind.CANARY); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + ValidateReadinessProbeRequest unknownFieldRequest = + fixture.request.toBuilder().setUnknownFields(unknown).build(); + + assertThatThrownBy(() -> fixture.service.validate(unknownFieldRequest, fixture.authenticated)) + .isInstanceOf(AccountJwtReadinessValidationService.InvalidReadinessRequestException.class); + ValidateReadinessProbeRequest oversized = + fixture.request.toBuilder().setCompactJwt("x".repeat(16 * 1024 + 1)).build(); + assertThatThrownBy(() -> fixture.service.validate(oversized, fixture.authenticated)) + .isInstanceOf(AccountJwtReadinessValidationService.InvalidReadinessRequestException.class); + verify(fixture.repository, never()) + .readCurrentEntry(any(), any(), any(), any(), any(), any(), any(), any()); + } + + private static final class Fixture { + private final AccountJwtReadinessProbeRepository repository = + mock(AccountJwtReadinessProbeRepository.class); + private final AccountJwtReadinessTrustBinding readinessProvider; + private final UUID operationId = UUID.randomUUID(); + private final UUID jti = UUID.randomUUID(); + private final long issuedAt = NOW.getEpochSecond() - 1L; + private final long expiresAt = NOW.getEpochSecond() + 299L; + private final KeyPair keyPair = rsa3072(); + private final byte[] spki = SPKI_TEXT.getBytes(StandardCharsets.US_ASCII); + private final Binding readinessBinding = readinessBinding(sha256(spki)); + private final AccountJwtSignerMaterializerTrustBinding.Binding signerBinding = signerBinding(); + private final TrustFence trustFence = + new TrustFence( + signerBinding.expectedClusterIncarnationUid(), + signerBinding.expectedNamespaceUid(), + signerBinding.bindingDigest(), + signerBinding.configRevision()); + private final String compactJwt; + private final AccountJwtReadinessValidationService service; + private final AccountJwtReadinessTlsInterceptor.AuthenticatedCaller authenticated; + private final ValidateReadinessProbeRequest request; + private final VerificationReceipt receipt; + private final ProbeEntry issued; + private final ProbeEntry verified; + + private Fixture(AccountMountedJwtSignerBundle.ProbeKind kind) throws Exception { + this( + kind, + kind == AccountMountedJwtSignerBundle.ProbeKind.CANARY + ? "account-jwt-readiness-canary" + : GameSessionAccountDelegationProfile.PROFILE, + kind == AccountMountedJwtSignerBundle.ProbeKind.CANARY + ? "firemud-account-jwt-readiness" + : GameSessionAccountDelegationProfile.AUDIENCE, + Map.of(), + false); + } + + private Fixture(AccountMountedJwtSignerBundle.ProbeKind kind, Map extras) + throws Exception { + this( + kind, + kind == AccountMountedJwtSignerBundle.ProbeKind.CANARY + ? "account-jwt-readiness-canary" + : GameSessionAccountDelegationProfile.PROFILE, + kind == AccountMountedJwtSignerBundle.ProbeKind.CANARY + ? "firemud-account-jwt-readiness" + : GameSessionAccountDelegationProfile.AUDIENCE, + extras, + false); + } + + private Fixture( + AccountMountedJwtSignerBundle.ProbeKind kind, + Map extras, + boolean invalidSignature) + throws Exception { + this( + kind, + kind == AccountMountedJwtSignerBundle.ProbeKind.CANARY + ? "account-jwt-readiness-canary" + : GameSessionAccountDelegationProfile.PROFILE, + kind == AccountMountedJwtSignerBundle.ProbeKind.CANARY + ? "firemud-account-jwt-readiness" + : GameSessionAccountDelegationProfile.AUDIENCE, + extras, + invalidSignature); + } + + private Fixture(AccountMountedJwtSignerBundle.ProbeKind kind, String profile, String audience) + throws Exception { + this(kind, profile, audience, Map.of(), false, 8); + } + + private Fixture( + AccountMountedJwtSignerBundle.ProbeKind kind, + String profile, + String audience, + int maxControlUiTenantScopes) + throws Exception { + this(kind, profile, audience, Map.of(), false, maxControlUiTenantScopes); + } + + private Fixture( + AccountMountedJwtSignerBundle.ProbeKind kind, + String profile, + String audience, + Map extras, + boolean invalidSignature) + throws Exception { + this(kind, profile, audience, extras, invalidSignature, 8); + } + + private Fixture( + AccountMountedJwtSignerBundle.ProbeKind kind, + String profile, + String audience, + Map extras, + boolean invalidSignature, + int maxControlUiTenantScopes) + throws Exception { + String signedToken = createToken(kind, profile, audience, extras, jti, keyPair); + this.compactJwt = invalidSignature ? corruptSignature(signedToken) : signedToken; + this.issued = + entry(kind, profile, audience, sha256(compactJwt.getBytes(StandardCharsets.US_ASCII))); + this.receipt = + new VerificationReceipt( + 1, + 4, + 5, + NOW.getEpochSecond(), + "e".repeat(64), + KID, + readinessBinding.validatorInstanceId(), + readinessBinding.bindingDigest(), + readinessBinding.configRevision(), + HARNESS_URI, + sha256(spki)); + this.verified = + new ProbeEntry( + operationId, + "b".repeat(64), + "account-service", + profile, + audience, + kind, + jti, + "7", + KID, + Optional.empty(), + 1, + 5, + issuedAt, + expiresAt, + ProbeState.VERIFIED, + Optional.empty(), + Optional.of(issuedAt), + Optional.of(sha256(compactJwt.getBytes(StandardCharsets.US_ASCII))), + Optional.of(receipt)); + readinessProvider = mock(AccountJwtReadinessTrustBinding.class); + AccountJwtSignerMaterializerTrustBinding signerProvider = + mock(AccountJwtSignerMaterializerTrustBinding.class); + when(readinessProvider.current()).thenReturn(Optional.of(readinessBinding)); + when(signerProvider.current()).thenReturn(Optional.of(signerBinding)); + when(repository.readCurrentEntry(any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(issued); + when(repository.recordVerified(any(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(verified); + AccountPublicJwksCache.SourceIdentity sourceIdentity = sourceIdentity(); + String jwks = jwks(KID, (RSAPublicKey) keyPair.getPublic()); + AccountPublicJwksCache cache = + new AccountPublicJwksCache( + () -> + new AccountPublicJwksCache.PublicJwksSnapshot( + sourceIdentity, jwks.getBytes(StandardCharsets.UTF_8)), + sourceIdentity, + Clock.fixed(NOW, ZoneId.of("UTC")), + Duration.ofMinutes(5)); + AccountAsymmetricJwtVerifier verifier = + new AccountAsymmetricJwtVerifier(cache, Clock.fixed(NOW, ZoneId.of("UTC"))); + service = + new AccountJwtReadinessValidationService( + repository, + readinessProvider, + signerProvider, + verifier, + new TransactionTemplate(new NoopTransactionManager()), + Clock.fixed(NOW, ZoneId.of("UTC")), + maxControlUiTenantScopes); + authenticated = authenticatedCaller(readinessBinding, spki); + request = + ValidateReadinessProbeRequest.newBuilder() + .setSchemaVersion(1) + .setRotationOperationId(operationId.toString()) + .setValidatorId("account-service") + .setTokenProfile(profile) + .setAudience(audience) + .setProbeKind(kind.name()) + .setJti(jti.toString()) + .setCompactJwt(compactJwt) + .build(); + } + + private ProbeEntry entry( + AccountMountedJwtSignerBundle.ProbeKind kind, + String profile, + String audience, + String tokenHash) { + return new ProbeEntry( + operationId, + "b".repeat(64), + "account-service", + profile, + audience, + kind, + jti, + "7", + KID, + Optional.empty(), + 1, + 4, + issuedAt, + expiresAt, + ProbeState.ISSUED, + Optional.empty(), + Optional.of(issuedAt), + Optional.of(tokenHash), + Optional.empty()); + } + } + + private static ApplicationContextRunner validationContextRunner() { + AccountJwtJwksTrustedSource trustedSource = mock(AccountJwtJwksTrustedSource.class); + when(trustedSource.sourceIdentity()) + .thenReturn( + new AccountPublicJwksCache.SourceIdentity( + "prod", + "prod-cluster-1", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "api-r1", + "https://kubernetes.example:6443", + "a".repeat(64))); + return new ApplicationContextRunner() + .withUserConfiguration(ReadinessValidationContext.class) + .withBean( + AccountJwtReadinessProbeRepository.class, + () -> mock(AccountJwtReadinessProbeRepository.class)) + .withBean( + AccountJwtReadinessTrustBinding.class, + () -> new AccountJwtReadinessTrustBinding(false, "")) + .withBean( + AccountJwtSignerMaterializerTrustBinding.class, + () -> new AccountJwtSignerMaterializerTrustBinding(false, "")) + .withBean(AccountJwtJwksTrustedSource.class, () -> trustedSource) + .withBean(PlatformTransactionManager.class, NoopTransactionManager::new); + } + + @Configuration(proxyBeanMethods = false) + @Import(AccountJwtReadinessValidationService.class) + static class ReadinessValidationContext {} + + private static Binding readinessBinding(String pin) { + return readinessBinding(pin, "readiness-r1"); + } + + private static Binding readinessBinding(String pin, String revision) { + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + List pins = List.of(pin); + String digest = + AccountJwtReadinessTrustBinding.computeBindingDigest( + revision, + "prod", + "prod-cluster-1", + "firemud-prod", + clusterUid, + namespaceUid, + HARNESS_URI, + pins, + "account-validator-instance-7", + NOW.getEpochSecond() + 600L); + return new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + clusterUid, + namespaceUid, + HARNESS_URI, + pins, + revision, + "account-service", + "account-validator-instance-7", + NOW.getEpochSecond() + 600L, + digest); + } + + private static AccountJwtSignerMaterializerTrustBinding.Binding signerBinding() { + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + List pins = List.of("a".repeat(64)); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + "trust-r1", + "prod", + "prod-cluster-1", + "firemud-prod", + clusterUid, + namespaceUid, + MATERIALIZER_URI, + pins); + return new AccountJwtSignerMaterializerTrustBinding.Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + clusterUid, + namespaceUid, + MATERIALIZER_URI, + pins, + "trust-r1", + digest); + } + + private static AccountPublicJwksCache.SourceIdentity sourceIdentity() { + return new AccountPublicJwksCache.SourceIdentity( + "prod", + "prod-cluster-1", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "account-api-r1", + "https://kubernetes.example:6443", + "9".repeat(64)); + } + + private static AccountJwtReadinessTlsInterceptor.AuthenticatedCaller authenticatedCaller( + Binding binding, byte[] spki) throws Exception { + AccountJwtReadinessTrustBinding trustBinding = mock(AccountJwtReadinessTrustBinding.class); + when(trustBinding.current()).thenReturn(Optional.of(binding)); + AccountJwtReadinessTlsInterceptor interceptor = + new AccountJwtReadinessTlsInterceptor(trustBinding); + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + @SuppressWarnings("unchecked") + ServerCallHandler next = mock(ServerCallHandler.class); + SSLSession session = mock(SSLSession.class); + java.security.cert.X509Certificate certificate = mock(java.security.cert.X509Certificate.class); + java.security.PublicKey publicKey = mock(java.security.PublicKey.class); + when(certificate.getPublicKey()).thenReturn(publicKey); + when(publicKey.getEncoded()).thenReturn(spki); + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, HARNESS_URI))); + when(session.getPeerCertificates()) + .thenReturn(new java.security.cert.Certificate[] {certificate}); + when(call.getAttributes()) + .thenReturn(Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build()); + AtomicReference result = + new AtomicReference<>(); + when(next.startCall(any(), any())) + .thenAnswer( + invocation -> { + result.set(AccountJwtReadinessTlsInterceptor.authenticatedCaller()); + return new ServerCall.Listener<>() {}; + }); + interceptor.interceptCall(call, new Metadata(), next); + return result.get(); + } + + private static Map authorityTuple( + Object issuerAuthGeneration, Object accountAuthorityGeneration) { + return Map.of( + "issuerAuthGeneration", + issuerAuthGeneration, + "accountAuthorityGeneration", + accountAuthorityGeneration, + "tenantAuthorityGeneration", + Map.of(), + "membershipAuthorityGeneration", + Map.of(), + "privateRealmGrantVersions", + List.of()); + } + + private static void assertRejectedWithoutRecording(Fixture fixture) { + assertThatThrownBy(() -> fixture.service.validate(fixture.request, fixture.authenticated)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + verify(fixture.repository, never()) + .recordVerified(any(), any(), any(), any(), any(), any(), any(), any(), any()); + } + + private static String createToken( + AccountMountedJwtSignerBundle.ProbeKind kind, + String profile, + String audience, + Map extraClaims, + UUID jti, + KeyPair keyPair) + throws Exception { + Map header = Map.of("alg", "RS256", "kid", KID, "typ", "JWT"); + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("sub", RESERVED_SUBJECT); + claims.put("jti", jti.toString()); + claims.put("aud", audience); + claims.put("iat", NOW.getEpochSecond() - 1L); + claims.put("nbf", NOW.getEpochSecond() - 1L); + claims.put("exp", NOW.getEpochSecond() + 299L); + if (kind == AccountMountedJwtSignerBundle.ProbeKind.CANARY) { + claims.put("tokenProfile", profile); + claims.put("tokenType", "account_jwt_readiness_canary"); + } else { + if (ControlUiJwtProfileValidator.PROFILE.equals(profile) + || PlayerBootstrapJwtProfileValidator.PROFILE.equals(profile)) { + claims.put("scopedRoles", Map.of()); + } + claims.put("accountId", RESERVED_SUBJECT); + boolean decimalCounters = GameSessionAccountDelegationProfile.PROFILE.equals(profile); + Object initialCounter = decimalCounters ? "1" : 1L; + claims.put("tokenGeneration", initialCounter); + claims.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", initialCounter, + "accountAuthorityGeneration", initialCounter, + "tenantAuthorityGeneration", Map.of(), + "membershipAuthorityGeneration", Map.of(), + "privateRealmGrantVersions", List.of())); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", initialCounter); + } + claims.putAll(extraClaims); + String signingInput = + encode(JSON.writeValueAsBytes(header)) + + "." + + encode(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(claims))); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keyPair.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return signingInput + "." + encode(signature.sign()); + } + + private static String corruptSignature(String compactJwt) { + String[] parts = compactJwt.split("\\.", -1); + byte[] signature = Base64.getUrlDecoder().decode(parts[2]); + signature[0] ^= 0x01; + return parts[0] + "." + parts[1] + "." + encode(signature); + } + + private static String jwks(String kid, RSAPublicKey key) { + String n = encode(unsigned(key.getModulus())); + String e = encode(unsigned(key.getPublicExponent())); + return "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"" + + kid + + "\",\"use\":\"sig\",\"alg\":\"RS256\",\"n\":\"" + + n + + "\",\"e\":\"" + + e + + "\"}]}"; + } + + private static KeyPair rsa3072() { + try { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(new RSAKeyGenParameterSpec(3_072, RSAKeyGenParameterSpec.F4)); + return generator.generateKeyPair(); + } catch (Exception ex) { + throw new AssertionError(ex); + } + } + + private static byte[] unsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + if (bytes.length > 1 && bytes[0] == 0) { + return java.util.Arrays.copyOfRange(bytes, 1, bytes.length); + } + return bytes; + } + + private static String encode(byte[] value) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (Exception ex) { + throw new AssertionError(ex); + } + } + + private static final class NoopTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinatorTest.java new file mode 100644 index 0000000000..0a2ee8dd64 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinatorTest.java @@ -0,0 +1,1226 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedPromotion; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionPreparation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksPrepublicationService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.BootstrapOperationException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.BootstrapProgress; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.FailureCode; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.Stage; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountJwtSignerBootstrapCoordinatorTest { + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String MATERIALIZER_URI = + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + private static final String API_DIGEST = "d".repeat(64); + private static final String API_REVISION = "api-revision-1"; + private static final String PUBLIC_JWKS = "{\"keys\":[]}"; + + @Test + void repeatedEnrollmentReturnsOnlyExactPinsWithoutSelectingAGeneration() { + Fixture fixture = fixture(GenerationPhase.OBSERVE_PRIVATE_SECRET); + ConfigMapSnapshot changedSnapshot = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "42", + Map.of(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, "{\"keys\":[{}]}")); + when(fixture.client().observe()).thenReturn(fixture.snapshot(), changedSnapshot); + + var first = fixture.coordinator().enrollOnce(); + var retry = fixture.coordinator().enrollOnce(); + + assertThat(first).isEqualTo(retry); + assertThat(first.environmentId()).isEqualTo("prod"); + assertThat(first.clusterId()).isEqualTo("prod-cluster-1"); + assertThat(first.namespace()).isEqualTo("firemud-prod"); + assertThat(first.expectedClusterIncarnationUid()).isEqualTo(CLUSTER_UID); + assertThat(first.expectedNamespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(first.materializerTrustBindingDigest()).isEqualTo(fixture.binding().bindingDigest()); + assertThat(first.materializerTrustConfigRevision()) + .isEqualTo(fixture.binding().configRevision()); + assertThat(first.apiBindingDigest()).isEqualTo(API_DIGEST); + assertThat(first.apiConfigRevision()).isEqualTo(API_REVISION); + assertThat(first.apiServerUrl()).isEqualTo("https://kubernetes.default.svc:6443/"); + assertThat(first.apiTlsServerName()).isEqualTo("kubernetes.default.svc"); + assertThat(first.apiServingCaSha256()).isEqualTo("b".repeat(64)); + assertThat(first.apiExpectedUsername()) + .isEqualTo("system:serviceaccount:firemud-prod:account-service"); + assertThat(first.publicConfigMapName()).isEqualTo("jwt-jwks"); + assertThat(first.publicConfigMapUid()).isEqualTo(CONFIG_MAP_UID); + assertThat(first.publicConfigMapResourceVersion()).isEqualTo("41"); + assertThat(first.publicConfigMapSnapshotDigest()) + .isEqualTo( + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, PUBLIC_JWKS))); + + ArgumentCaptor enrollment = + ArgumentCaptor.forClass(EnrollmentIdentity.class); + verify(fixture.repository(), times(2)) + .initialize(eq(fixture.binding().accountBinding()), enrollment.capture()); + assertThat(enrollment.getAllValues()) + .allSatisfy( + value -> { + assertThat(value.expectedClusterIncarnationUid()).isEqualTo(CLUSTER_UID); + assertThat(value.expectedNamespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(value.materializerTrustBindingDigest()) + .isEqualTo(fixture.binding().bindingDigest()); + assertThat(value.materializerTrustConfigRevision()) + .isEqualTo(fixture.binding().configRevision()); + assertThat(value.apiBindingDigest()).isEqualTo(API_DIGEST); + assertThat(value.apiConfigRevision()).isEqualTo(API_REVISION); + assertThat(value.publicConfigMapUid()).isEqualTo(CONFIG_MAP_UID); + }); + assertThat(enrollment.getAllValues().get(0).publicConfigMapResourceVersion()).isEqualTo("41"); + assertThat(enrollment.getAllValues().get(1).publicConfigMapResourceVersion()).isEqualTo("42"); + assertThat(enrollment.getAllValues().get(0).publicConfigMapSnapshotDigest()) + .isEqualTo( + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, PUBLIC_JWKS))); + assertThat(enrollment.getAllValues().get(1).publicConfigMapSnapshotDigest()) + .isEqualTo( + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, "{\"keys\":[{}]}"))); + assertThat(first.publicConfigMapResourceVersion()).isEqualTo("41"); + assertThat(retry.publicConfigMapResourceVersion()).isEqualTo("41"); + verify(fixture.repository(), never()).ensureCurrentGenerationRequest(any(), any()); + verify(fixture.repository(), never()).readCurrentGenerationRequest(any(), any()); + verify(fixture.prepublication(), never()).prepublishCurrentGeneration(); + verify(fixture.prepublication(), never()).observeCurrentMountedCorrespondence(); + } + + @Test + void rejectsMismatchedProtectedBindingsBeforeEnrollmentOrRemoteObservation() { + Fixture fixture = fixture(GenerationPhase.OBSERVE_PRIVATE_SECRET); + when(fixture.client().identity()) + .thenReturn( + new BindingIdentity( + API_DIGEST, + API_REVISION, + "prod", + "different-cluster", + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + "https://kubernetes.default.svc:6443/", + "kubernetes.default.svc", + "a".repeat(64), + "system:serviceaccount:firemud-prod:account-service")); + + assertThatThrownBy(fixture.coordinator()::enrollOnce) + .isInstanceOf(BootstrapOperationException.class) + .extracting(failure -> ((BootstrapOperationException) failure).failureCode()) + .isEqualTo(FailureCode.PROTECTED_BINDING_MISMATCH); + + verify(fixture.client(), never()).observe(); + verifyNoInteractions(fixture.repository(), fixture.prepublication()); + } + + @Test + void ambiguousLiveConfigMapObservationDoesNotInitializeOrSelectLifecycleState() { + Fixture fixture = fixture(GenerationPhase.OBSERVE_PRIVATE_SECRET); + when(fixture.client().observe()) + .thenThrow(new AccountJwtJwksConfigMapClient.UncertainOutcomeException()); + + assertThatThrownBy(fixture.coordinator()::enrollOnce) + .isInstanceOf(BootstrapOperationException.class) + .extracting(failure -> ((BootstrapOperationException) failure).failureCode()) + .isEqualTo(FailureCode.PUBLIC_CONFIG_MAP_UNAVAILABLE); + + verifyNoInteractions(fixture.repository(), fixture.prepublication()); + } + + @Test + void accountStateAmbiguityDoesNotSelectOrPublishGeneration() { + Fixture fixture = fixture(GenerationPhase.OBSERVE_PRIVATE_SECRET); + when(fixture + .repository() + .initialize(eq(fixture.binding().accountBinding()), any(EnrollmentIdentity.class))) + .thenThrow( + new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "test ambiguity")); + + assertThatThrownBy(fixture.coordinator()::enrollOnce) + .isInstanceOf(BootstrapOperationException.class) + .extracting(failure -> ((BootstrapOperationException) failure).failureCode()) + .isEqualTo(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + + verify(fixture.repository(), never()).ensureCurrentGenerationRequest(any(), any()); + verify(fixture.repository(), never()).readCurrentGenerationRequest(any(), any()); + verifyNoInteractions(fixture.prepublication()); + } + + @Test + void materializerTrustIsRecheckedBeforeTheEnrollmentTransactionCompletes() { + Fixture fixture = fixture(GenerationPhase.OBSERVE_PRIVATE_SECRET); + Binding changedBinding = materializerBinding("trust-revision-2"); + when(fixture.materializerTrust().current()) + .thenReturn( + Optional.of(fixture.binding()), + Optional.of(fixture.binding()), + Optional.of(fixture.binding()), + Optional.of(changedBinding)); + + assertThatThrownBy(fixture.coordinator()::enrollOnce) + .isInstanceOf(BootstrapOperationException.class) + .extracting(failure -> ((BootstrapOperationException) failure).failureCode()) + .isEqualTo(FailureCode.PROTECTED_BINDING_CHANGED); + + verify(fixture.repository()) + .initialize(eq(fixture.binding().accountBinding()), any(EnrollmentIdentity.class)); + verify(fixture.repository(), never()).ensureCurrentGenerationRequest(any(), any()); + verify(fixture.repository(), never()).readCurrentGenerationRequest(any(), any()); + verifyNoInteractions(fixture.prepublication()); + } + + @Test + void validatorAcceptanceRemainsAnExplicitBlockerAfterPublicationAndMountCorrespondence() { + AtomicBoolean insideTransaction = new AtomicBoolean(); + Fixture fixture = fixture(GenerationPhase.GENERATION_RECORDED, insideTransaction); + UUID operationId = fixture.request().operationId(); + var publication = mock(AccountJwtJwksPublicationRepository.PublicationReceipt.class); + var mounted = mock(AccountJwtJwksPublicationRepository.MountObservation.class); + when(publication.operationId()).thenReturn(operationId); + when(mounted.operationId()).thenReturn(operationId); + when(fixture + .repository() + .readCurrentGenerationRequest( + eq(fixture.binding().accountBinding()), eq(trustFence(fixture.binding())))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(insideTransaction.get()).isTrue(); + return fixture.request(); + }); + when(fixture.prepublication().prepublishCurrentGeneration()) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(insideTransaction.get()).isFalse(); + return publication; + }); + when(fixture.prepublication().observeCurrentMountedCorrespondence()) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(insideTransaction.get()).isFalse(); + return mounted; + }); + + BootstrapProgress progress = + fixture.coordinator().reconcileCurrentGenerationOnce(fixture.request().operationId()); + + assertThat(progress.stage()).isEqualTo(Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE); + assertThat(progress.generationReadbackComplete()).isTrue(); + assertThat(progress.publicKeyPrepublished()).isTrue(); + assertThat(progress.mountedKeyCorrespondence()).isTrue(); + assertThat(progress.validatorInventoryStatus()).isEqualTo("PARTIAL_UNCONFIRMED"); + assertThat(progress.validatorAcceptanceComplete()).isFalse(); + assertThat(progress.signerPromotionCommitted()).isFalse(); + assertThat(progress.issuanceReady()).isFalse(); + assertThat(progress.blockers()) + .containsExactly( + FailureCode.VALIDATOR_ACCEPTANCE_INCOMPLETE, + FailureCode.SIGNER_PROMOTION_NOT_ATTEMPTED); + verify(fixture.repository(), never()).initialize(any(), any()); + verify(fixture.repository(), never()).ensureCurrentGenerationRequest(any(), any()); + } + + @Test + void remoteConfigMapReadOccursOutsideAccountTransaction() { + AtomicBoolean insideTransaction = new AtomicBoolean(); + Fixture fixture = fixture(GenerationPhase.OBSERVE_PRIVATE_SECRET, insideTransaction); + when(fixture.client().observe()) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(insideTransaction.get()).isFalse(); + return fixture.snapshot(); + }); + + fixture.coordinator().enrollOnce(); + + assertThat(insideTransaction.get()).isFalse(); + } + + @Test + void emptyInitialEnrollmentIsNoPromotionUntilAccountSelectsGeneration() { + Fixture fixture = fixture(GenerationPhase.OBSERVE_PRIVATE_SECRET); + DesiredState initial = + new DesiredState( + fixture.binding().accountBinding(), + 1, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.of(enrollment(fixture.binding()))); + when(fixture.repository().readEnrollmentState(fixture.binding().accountBinding())) + .thenReturn(Optional.of(initial)); + + assertThat(fixture.coordinator().prepareCurrentPromotionOnce()).isEmpty(); + + verify(fixture.repository()).readEnrollmentState(fixture.binding().accountBinding()); + verify(fixture.repository(), never()).readCurrentGenerationRequest(any(), any()); + verify(fixture.prepublication(), never()).prepublishCurrentGeneration(); + verify(fixture.inventorySource(), never()).observe(any()); + } + + @Test + void validEarlyGenerationPhasesHaveNoPromotionUntilGenerationIsRecorded() { + for (GenerationPhase phase : + List.of(GenerationPhase.OBSERVE_PRIVATE_SECRET, GenerationPhase.GENERATE_PENDING)) { + AtomicBoolean insideTransaction = new AtomicBoolean(); + Fixture fixture = fixture(phase, insideTransaction); + stubCurrentGenerationRequest(fixture, insideTransaction); + + assertThat(fixture.coordinator().prepareCurrentPromotionOnce()).isEmpty(); + + verify(fixture.repository()) + .readCurrentGenerationRequest( + fixture.binding().accountBinding(), trustFence(fixture.binding())); + verify(fixture.prepublication(), never()).prepublishCurrentGeneration(); + verify(fixture.inventorySource(), never()).observe(any()); + } + } + + @Test + void missingEnrollmentReadbackIsQuarantinedRatherThanTreatedAsNoPromotion() { + Fixture fixture = fixture(GenerationPhase.OBSERVE_PRIVATE_SECRET); + when(fixture.repository().readEnrollmentState(fixture.binding().accountBinding())) + .thenReturn(Optional.empty()); + + assertThatThrownBy(fixture.coordinator()::prepareCurrentPromotionOnce) + .isInstanceOf(BootstrapOperationException.class) + .extracting(failure -> ((BootstrapOperationException) failure).failureCode()) + .isEqualTo(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + + verify(fixture.repository(), never()).readCurrentGenerationRequest(any(), any()); + verify(fixture.prepublication(), never()).prepublishCurrentGeneration(); + + Fixture faulted = fixture(GenerationPhase.OBSERVE_PRIVATE_SECRET); + when(faulted.repository().readEnrollmentState(faulted.binding().accountBinding())) + .thenThrow( + new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "test owner read failure")); + assertThatThrownBy(faulted.coordinator()::prepareCurrentPromotionOnce) + .isInstanceOf(BootstrapOperationException.class) + .extracting(failure -> ((BootstrapOperationException) failure).failureCode()) + .isEqualTo(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + verify(faulted.repository(), never()).readCurrentGenerationRequest(any(), any()); + } + + @Test + void unavailableReadinessOwnerIsNotReportedAsNoPromotion() { + Fixture fixture = fixture(GenerationPhase.OBSERVE_PRIVATE_SECRET); + AccountJwtSignerBootstrapCoordinator withoutReadinessOwner = + new AccountJwtSignerBootstrapCoordinator( + fixture.materializerTrust(), + fixture.client(), + fixture.repository(), + fixture.prepublication(), + new TransactionTemplate(new InertTransactionManager(new AtomicBoolean()))); + + assertThatThrownBy(withoutReadinessOwner::prepareCurrentPromotionOnce) + .isInstanceOf(BootstrapOperationException.class) + .extracting(failure -> ((BootstrapOperationException) failure).failureCode()) + .isEqualTo(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + + verifyNoInteractions(fixture.client(), fixture.repository(), fixture.prepublication()); + } + + @Test + void partialReadinessNeverEntersPreparedAndRefreshesExternalEvidenceBeforeSql() { + AtomicBoolean insideTransaction = new AtomicBoolean(); + Fixture fixture = fixture(GenerationPhase.GENERATION_RECORDED, insideTransaction); + UUID operationId = fixture.request().operationId(); + stubCurrentGenerationRequest(fixture, insideTransaction); + stubPublicationAndMountRefresh(fixture, insideTransaction); + ObservationContext context = initialObservationContext(fixture.request()); + when(fixture + .readinessRepository() + .readCurrentInventoryObservationContext( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(operationId))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(insideTransaction.get()).isTrue(); + return context; + }); + when(fixture.inventorySource().observe(context)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(insideTransaction.get()).isFalse(); + return fixture.inventorySnapshot(); + }); + when(fixture + .readinessRepository() + .readCurrentPromotionPrerequisites( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(operationId), + eq(fixture.inventorySnapshot()))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(insideTransaction.get()).isTrue(); + return Optional.empty(); + }); + + assertThat(fixture.coordinator().prepareCurrentPromotionOnce()).isEmpty(); + + verify(fixture.prepublication()).prepublishCurrentGeneration(); + verify(fixture.prepublication()).observeCurrentMountedCorrespondence(); + verify(fixture.readinessRepository()) + .readCurrentInventoryObservationContext( + fixture.binding().accountBinding(), trustFence(fixture.binding()), operationId); + verify(fixture.inventorySource()).observe(context); + verify(fixture.repository(), never()).prepareCurrentGeneration(any(), any(), any(), any()); + assertThat(insideTransaction.get()).isFalse(); + } + + @Test + void concurrentActiveSignerInvalidatesInitialCandidateContextBeforePreparation() { + AtomicBoolean insideTransaction = new AtomicBoolean(); + Fixture fixture = fixture(GenerationPhase.GENERATION_RECORDED, insideTransaction); + UUID operationId = fixture.request().operationId(); + stubCurrentGenerationRequest(fixture, insideTransaction); + stubPublicationAndMountRefresh(fixture, insideTransaction); + ObservationContext initialContext = initialObservationContext(fixture.request()); + when(fixture + .readinessRepository() + .readCurrentInventoryObservationContext( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(operationId))) + .thenReturn(initialContext); + when(fixture.inventorySource().observe(initialContext)).thenReturn(fixture.inventorySnapshot()); + when(fixture + .readinessRepository() + .readCurrentPromotionPrerequisites( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(operationId), + eq(fixture.inventorySnapshot()))) + .thenThrow( + new net.firedevops.firemud.accountservice.service.session + .AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException()); + + assertThatThrownBy(fixture.coordinator()::prepareCurrentPromotionOnce) + .isInstanceOf( + net.firedevops.firemud.accountservice.service.session + .AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + + verify(fixture.inventorySource()).observe(initialContext); + verify(fixture.repository(), never()).prepareCurrentGeneration(any(), any(), any(), any()); + assertThat(insideTransaction.get()).isFalse(); + } + + @Test + void completeOwnerProofPreparesOnlyItsExactCurrentGenerationOnce() { + AtomicBoolean insideTransaction = new AtomicBoolean(); + Fixture fixture = fixture(GenerationPhase.GENERATION_RECORDED, insideTransaction); + UUID operationId = fixture.request().operationId(); + stubCurrentGenerationRequest(fixture, insideTransaction); + stubPublicationAndMountRefresh(fixture, insideTransaction); + ObservationContext context = initialObservationContext(fixture.request()); + when(fixture + .readinessRepository() + .readCurrentInventoryObservationContext( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(operationId))) + .thenReturn(context); + when(fixture.inventorySource().observe(context)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(insideTransaction.get()).isFalse(); + return fixture.inventorySnapshot(); + }); + + ReadinessPromotionProof proof = mock(ReadinessPromotionProof.class); + GenerationResult generation = mock(GenerationResult.class); + when(generation.operationId()).thenReturn(operationId); + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication = + mock(AccountJwtJwksPublicationRepository.PromotionPublicationEvidence.class); + var intent = mock(AccountJwtJwksPublicationRepository.PrepublicationIntent.class); + var receipt = mock(AccountJwtJwksPublicationRepository.PublicationReceipt.class); + var mounted = mock(AccountJwtJwksPublicationRepository.MountObservation.class); + when(intent.apiBindingDigest()).thenReturn(API_DIGEST); + when(intent.apiConfigRevision()).thenReturn(API_REVISION); + when(intent.configMapUid()).thenReturn(CONFIG_MAP_UID); + when(intent.intentDigest()).thenReturn("1".repeat(64)); + when(intent.jwksJson()).thenReturn(PUBLIC_JWKS); + when(receipt.observedResourceVersion()).thenReturn("42"); + when(receipt.receiptDigest()).thenReturn("2".repeat(64)); + when(mounted.observationDigest()).thenReturn("3".repeat(64)); + when(publication.intent()).thenReturn(intent); + when(publication.receipt()).thenReturn(receipt); + when(publication.mountedCorrespondence()).thenReturn(mounted); + var plan = mock(AccountJwtReadinessProbeRepository.ReadinessProbePlan.class); + when(plan.planDigest()).thenReturn("4".repeat(64)); + when(proof.generationResult()).thenReturn(generation); + when(proof.publication()).thenReturn(publication); + when(proof.plan()).thenReturn(plan); + when(proof.readinessEvidenceDigest()).thenReturn("5".repeat(64)); + when(fixture + .readinessRepository() + .readCurrentPromotionPrerequisites( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(operationId), + eq(fixture.inventorySnapshot()))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(insideTransaction.get()).isTrue(); + return Optional.of(proof); + }); + EnrollmentIdentity enrollment = enrollment(fixture.binding()); + when(fixture.repository().read(fixture.binding().accountBinding())) + .thenReturn( + new DesiredState( + fixture.binding().accountBinding(), + 2, + Optional.empty(), + Optional.empty(), + Optional.of(operationId), + Optional.empty(), + Optional.of(enrollment))); + PreparedPromotion prepared = new PreparedPromotion(operationId, "6".repeat(64), "PREPARED"); + when(fixture + .repository() + .prepareCurrentGeneration( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + any(PromotionPreparation.class), + eq(proof))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(insideTransaction.get()).isTrue(); + return prepared; + }); + + assertThat(fixture.coordinator().prepareCurrentPromotionOnce()).contains(prepared); + + ArgumentCaptor preparation = + ArgumentCaptor.forClass(PromotionPreparation.class); + verify(fixture.repository(), times(1)) + .prepareCurrentGeneration( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + preparation.capture(), + eq(proof)); + assertThat(preparation.getValue().generationOperationId()).isEqualTo(operationId); + assertThat(preparation.getValue().generationResult()).isSameAs(generation); + assertThat(preparation.getValue().enrollmentIdentity()).isEqualTo(enrollment); + assertThat(preparation.getValue().readinessPlanDigest()).isEqualTo("4".repeat(64)); + assertThat(preparation.getValue().readinessEvidenceDigest()).isEqualTo("5".repeat(64)); + assertThat(insideTransaction.get()).isFalse(); + } + + @Test + void missingInventorySourceFailsClosedWithoutPreparation() { + AtomicBoolean insideTransaction = new AtomicBoolean(); + Fixture fixture = fixture(GenerationPhase.GENERATION_RECORDED, insideTransaction); + when(fixture.inventorySourceProvider().getIfAvailable()).thenReturn(null); + stubCurrentGenerationRequest(fixture, insideTransaction); + stubPublicationAndMountRefresh(fixture, insideTransaction); + + assertThatThrownBy(fixture.coordinator()::prepareCurrentPromotionOnce) + .isInstanceOf(BootstrapOperationException.class) + .extracting(failure -> ((BootstrapOperationException) failure).failureCode()) + .isEqualTo(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + + verify(fixture.repository(), never()).prepareCurrentGeneration(any(), any(), any(), any()); + } + + @Test + void preparedPromotionDoesNotPublishOrCommitWithoutFreshCompleteReadinessProof() { + AtomicBoolean insideTransaction = new AtomicBoolean(); + Fixture fixture = fixture(GenerationPhase.GENERATION_RECORDED, insideTransaction); + UUID promotionId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + UUID generationOperationId = fixture.request().operationId(); + String generationOperationDigest = fixture.request().operationDigest(); + PrivatePromotionObservation observation = + new PrivatePromotionObservation( + promotionId, + "f".repeat(64), + generationOperationId, + generationOperationDigest, + "44444444-4444-4444-8444-444444444444", + "13", + "14", + new AccountJwtSignerDesiredStateRepository.PublicKeyIdentity( + "1", "test-kid", "9".repeat(64)), + Optional.empty(), + List.of("current")); + PrivatePromotionReceipt privateReceipt = + new PrivatePromotionReceipt(promotionId, generationOperationId, "14", "8".repeat(64)); + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + when(promotion.status()).thenReturn("PREPARED"); + when(promotion.operationId()).thenReturn(promotionId); + when(promotion.requestDigest()).thenReturn("f".repeat(64)); + when(promotion.generationOperationId()).thenReturn(generationOperationId); + when(promotion.generationOperationDigest()).thenReturn(generationOperationDigest); + when(promotion.expectedPreviousActive()).thenReturn(Optional.empty()); + when(promotion.expectedPublishedActive()).thenReturn(Optional.empty()); + when(promotion.privatePromotionDispatched()).thenReturn(true); + when(promotion.privatePromotionReceiptDigest()) + .thenReturn(Optional.of(privateReceipt.receiptDigest())); + PreparedGenerationEvidence prepared = mock(PreparedGenerationEvidence.class); + when(prepared.promotion()).thenReturn(promotion); + when(fixture + .repository() + .recordPrivatePromotionResult( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(observation))) + .thenReturn(privateReceipt); + when(fixture + .repository() + .readPreparedGenerationForRecovery( + eq(fixture.binding().accountBinding()), eq(trustFence(fixture.binding())))) + .thenReturn(prepared); + ObservationContext context = + initialObservationContext(generationOperationId, generationOperationDigest); + when(fixture.inventorySource().observe(context)) + .thenAnswer( + invocation -> { + assertThat(insideTransaction.get()).isFalse(); + return fixture.inventorySnapshot(); + }); + when(fixture.prepublication().observePreparedCurrentKeyCorrespondence(promotion)) + .thenAnswer( + invocation -> { + assertThat(insideTransaction.get()).isFalse(); + return fixture.snapshot(); + }); + when(fixture + .readinessRepository() + .readPromotionProof( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(generationOperationId), + same(fixture.inventorySnapshot()))) + .thenReturn(Optional.empty()); + + assertThatThrownBy( + () -> fixture.coordinator().reconcilePreparedPromotionOnce(observation, privateReceipt)) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException.class) + .hasMessageContaining("Fresh complete Account readiness proof is unavailable"); + + verify(fixture.client(), never()).publishActiveProjection(any(), any(), any()); + verify(fixture.repository(), never()).recordActiveJwksPromotionResult(any(), any(), any()); + verify(fixture.repository(), never()).commitPreparedPromotion(any(), any(), any(), any()); + assertThat(insideTransaction.get()).isFalse(); + } + + @Test + void exactCommittedPrivateReceiptReplayDoesNotRepeatExternalMutation() { + Fixture fixture = fixture(GenerationPhase.GENERATION_RECORDED); + UUID promotionId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + PrivatePromotionObservation observation = + new PrivatePromotionObservation( + promotionId, + "f".repeat(64), + fixture.request().operationId(), + fixture.request().operationDigest(), + "44444444-4444-4444-8444-444444444444", + "13", + "14", + new AccountJwtSignerDesiredStateRepository.PublicKeyIdentity( + "1", "test-kid", "9".repeat(64)), + Optional.empty(), + List.of("current")); + PrivatePromotionReceipt receipt = + new PrivatePromotionReceipt( + promotionId, fixture.request().operationId(), "14", "8".repeat(64)); + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + when(promotion.operationId()).thenReturn(promotionId); + CommittedSignerEvidence committed = mock(CommittedSignerEvidence.class); + when(committed.privateReceipt()).thenReturn(receipt); + when(committed.promotion()).thenReturn(promotion); + when(fixture + .repository() + .recordPrivatePromotionResult( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(observation))) + .thenReturn(receipt); + when(fixture + .repository() + .readPreparedGenerationForRecovery( + eq(fixture.binding().accountBinding()), eq(trustFence(fixture.binding())))) + .thenThrow(new AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException()); + when(fixture + .repository() + .readCurrentCommittedSigner( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(API_DIGEST), + eq(API_REVISION))) + .thenReturn(Optional.of(committed)); + + fixture.coordinator().reconcilePreparedPromotionOnce(observation, receipt); + + verify(fixture.repository()) + .readCurrentCommittedSigner( + fixture.binding().accountBinding(), + trustFence(fixture.binding()), + API_DIGEST, + API_REVISION); + verify(fixture.inventorySourceProvider(), never()).getIfAvailable(); + verifyNoInteractions(fixture.prepublication()); + verify(fixture.client(), never()).publishActiveProjection(any(), any(), any()); + verify(fixture.repository(), never()).recordActiveJwksPromotionResult(any(), any(), any()); + verify(fixture.repository(), never()).commitPreparedPromotion(any(), any(), any(), any()); + } + + @Test + void preparedPromotionCasAndCommitAreSeparatedByIndependentProofTransactions() { + AtomicBoolean insideTransaction = new AtomicBoolean(); + Fixture fixture = fixture(GenerationPhase.GENERATION_RECORDED, insideTransaction); + UUID promotionId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + UUID generationOperationId = fixture.request().operationId(); + String generationOperationDigest = fixture.request().operationDigest(); + PrivatePromotionObservation observation = + new PrivatePromotionObservation( + promotionId, + "f".repeat(64), + generationOperationId, + generationOperationDigest, + "44444444-4444-4444-8444-444444444444", + "13", + "14", + new AccountJwtSignerDesiredStateRepository.PublicKeyIdentity( + "1", "test-kid", "9".repeat(64)), + Optional.empty(), + List.of("current")); + PrivatePromotionReceipt privateReceipt = + new PrivatePromotionReceipt(promotionId, generationOperationId, "14", "8".repeat(64)); + PromotionOperationEvidence beforeCas = + promotionEvidence(fixture, promotionId, privateReceipt, Optional.empty()); + String activeMarker = "{\"phase\":\"ACTIVE\"}"; + ActiveJwksPromotionReceipt activeReceipt = + new ActiveJwksPromotionReceipt( + promotionId, + CONFIG_MAP_UID, + "42", + "43", + AccountJwtJwksPublicationRepository.publicDataDigest(PUBLIC_JWKS, activeMarker), + "6".repeat(64)); + PromotionOperationEvidence afterCas = + promotionEvidence(fixture, promotionId, privateReceipt, Optional.of(activeReceipt)); + PreparedGenerationEvidence preparedBefore = mock(PreparedGenerationEvidence.class); + when(preparedBefore.promotion()).thenReturn(beforeCas); + PreparedGenerationEvidence preparedAfter = mock(PreparedGenerationEvidence.class); + when(preparedAfter.promotion()).thenReturn(afterCas); + when(fixture + .repository() + .recordPrivatePromotionResult( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(observation))) + .thenReturn(privateReceipt); + when(fixture + .repository() + .readPreparedGenerationForRecovery( + eq(fixture.binding().accountBinding()), eq(trustFence(fixture.binding())))) + .thenReturn(preparedBefore, preparedBefore, preparedAfter, preparedAfter); + ObservationContext context = + new ObservationContext( + ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES, + generationOperationId, + generationOperationDigest); + InventorySnapshot inventory = fixture.inventorySnapshot(); + AtomicBoolean activeCasReturned = new AtomicBoolean(); + AtomicBoolean activeReceiptRecorded = new AtomicBoolean(); + java.util.concurrent.atomic.AtomicInteger inventoryReads = + new java.util.concurrent.atomic.AtomicInteger(); + java.util.concurrent.atomic.AtomicInteger proofReads = + new java.util.concurrent.atomic.AtomicInteger(); + when(fixture.inventorySource().observe(context)) + .thenAnswer( + invocation -> { + assertThat(insideTransaction.get()).isFalse(); + inventoryReads.incrementAndGet(); + return inventory; + }); + String prepublishedMarker = "{\"phase\":\"PREPUBLISHED\"}"; + ConfigMapSnapshot beforeSnapshot = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "42", + Map.of( + "jwks.json", PUBLIC_JWKS, + "jwt-generation.json", prepublishedMarker, + "unrelated.txt", "preserved")); + ConfigMapSnapshot afterSnapshot = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + "jwks.json", PUBLIC_JWKS, + "jwt-generation.json", activeMarker, + "unrelated.txt", "preserved")); + when(fixture.prepublication().observePreparedCurrentKeyCorrespondence(beforeCas)) + .thenReturn(beforeSnapshot); + when(fixture.prepublication().observePreparedCurrentKeyCorrespondence(afterCas)) + .thenReturn(afterSnapshot); + when(fixture.client().publishActiveProjection(eq(beforeSnapshot), eq("42"), any())) + .thenAnswer( + invocation -> { + assertThat(insideTransaction.get()).isFalse(); + assertThat(inventoryReads.get()).isEqualTo(1); + assertThat(proofReads.get()).isEqualTo(1); + activeCasReturned.set(true); + return new CasObservation( + CONFIG_MAP_UID, + "42", + "43", + Map.of("jwks.json", PUBLIC_JWKS, "jwt-generation.json", activeMarker), + afterSnapshot.data(), + AccountJwtJwksConfigMapClient.Outcome.APPLIED); + }); + when(fixture.repository().recordActiveJwksPromotionResult(any(), any(), any())) + .thenAnswer( + invocation -> { + assertThat(insideTransaction.get()).isTrue(); + assertThat(activeCasReturned.get()).isTrue(); + activeReceiptRecorded.set(true); + return activeReceipt; + }); + when(fixture + .readinessRepository() + .readPromotionProof( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(generationOperationId), + same(inventory))) + .thenAnswer( + invocation -> { + assertThat(insideTransaction.get()).isTrue(); + proofReads.incrementAndGet(); + return Optional.of(mock(ReadinessPromotionProof.class)); + }); + CommittedSignerEvidence committed = mock(CommittedSignerEvidence.class); + PromotionOperationEvidence committedOperation = mock(PromotionOperationEvidence.class); + when(committedOperation.operationId()).thenReturn(promotionId); + when(committedOperation.status()).thenReturn("COMMITTED"); + when(committed.promotion()).thenReturn(committedOperation); + when(fixture + .repository() + .commitPreparedPromotion( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(promotionId), + any(ReadinessPromotionProof.class))) + .thenAnswer( + invocation -> { + assertThat(insideTransaction.get()).isTrue(); + assertThat(activeReceiptRecorded.get()).isTrue(); + assertThat(inventoryReads.get()).isEqualTo(2); + assertThat(proofReads.get()).isEqualTo(2); + return committed; + }); + + fixture.coordinator().reconcilePreparedPromotionOnce(observation, privateReceipt); + + assertThat(activeCasReturned.get()).isTrue(); + assertThat(activeReceiptRecorded.get()).isTrue(); + assertThat(inventoryReads.get()).isEqualTo(2); + assertThat(proofReads.get()).isEqualTo(2); + verify(fixture.client()).publishActiveProjection(eq(beforeSnapshot), eq("42"), any()); + verify(fixture.repository()).recordActiveJwksPromotionResult(any(), any(), any()); + verify(fixture.repository()) + .commitPreparedPromotion( + eq(fixture.binding().accountBinding()), + eq(trustFence(fixture.binding())), + eq(promotionId), + any(ReadinessPromotionProof.class)); + } + + private static PromotionOperationEvidence promotionEvidence( + Fixture fixture, + UUID promotionId, + PrivatePromotionReceipt privateReceipt, + Optional activeReceipt) { + return new PromotionOperationEvidence( + promotionId, + "f".repeat(64), + 2, + fixture.binding().accountBinding(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + "1", + "test-kid", + "RS256", + "9".repeat(64), + trustFence(fixture.binding()), + fixture.request().operationId(), + fixture.request().operationDigest(), + "a".repeat(64), + "44444444-4444-4444-8444-444444444444", + "13", + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "42", + "1".repeat(64), + "2".repeat(64), + "3".repeat(64), + "4".repeat(64), + "5".repeat(64), + PUBLIC_JWKS, + "{\"phase\":\"ACTIVE\"}", + "PREPARED", + true, + Optional.of(privateReceipt.observedResourceVersion()), + Optional.of(privateReceipt.receiptDigest()), + activeReceipt.map(ActiveJwksPromotionReceipt::observedResourceVersion), + activeReceipt.map(ActiveJwksPromotionReceipt::publicDataDigest), + activeReceipt.map(ActiveJwksPromotionReceipt::receiptDigest)); + } + + private static Fixture fixture(GenerationPhase phase) { + return fixture(phase, new AtomicBoolean()); + } + + private static Fixture fixture(GenerationPhase phase, AtomicBoolean insideTransaction) { + AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + AccountJwtJwksConfigMapClient client = mock(AccountJwtJwksConfigMapClient.class); + AccountJwtSignerDesiredStateRepository repository = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPrepublicationService prepublication = + mock(AccountJwtJwksPrepublicationService.class); + AccountJwtReadinessProbeRepository readinessRepository = + mock(AccountJwtReadinessProbeRepository.class); + AccountJwtValidatorInventorySource inventorySource = + mock(AccountJwtValidatorInventorySource.class); + InventorySnapshot inventorySnapshot = mock(InventorySnapshot.class); + @SuppressWarnings("unchecked") + ObjectProvider inventorySourceProvider = + mock(ObjectProvider.class); + when(inventorySourceProvider.getIfAvailable()).thenReturn(inventorySource); + Binding binding = materializerBinding(); + BindingIdentity apiIdentity = apiIdentity(); + ConfigMapSnapshot snapshot = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "41", + Map.of(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, PUBLIC_JWKS)); + GenerationRequest request = request(binding, phase); + DesiredState enrollmentState = + new DesiredState( + binding.accountBinding(), + 2, + Optional.empty(), + Optional.empty(), + Optional.of(request.operationId()), + Optional.empty(), + Optional.of(enrollment(binding))); + when(materializerTrust.current()).thenReturn(Optional.of(binding)); + when(client.identity()).thenReturn(apiIdentity); + when(client.observe()).thenReturn(snapshot); + when(repository.readEnrollmentState(binding.accountBinding())) + .thenReturn(Optional.of(enrollmentState)); + AtomicReference persistedEnrollment = new AtomicReference<>(); + when(repository.initialize(eq(binding.accountBinding()), any(EnrollmentIdentity.class))) + .thenAnswer( + invocation -> { + EnrollmentIdentity requested = invocation.getArgument(1); + EnrollmentIdentity persisted = + persistedEnrollment.updateAndGet( + current -> current == null ? requested : current); + return new DesiredState( + binding.accountBinding(), + 1, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.of(persisted)); + }); + TransactionTemplate transaction = + new TransactionTemplate(new InertTransactionManager(insideTransaction)); + AccountJwtSignerBootstrapCoordinator coordinator = + new AccountJwtSignerBootstrapCoordinator( + materializerTrust, + client, + repository, + prepublication, + readinessRepository, + inventorySourceProvider, + transaction); + return new Fixture( + coordinator, + materializerTrust, + client, + repository, + prepublication, + readinessRepository, + inventorySource, + inventorySnapshot, + inventorySourceProvider, + binding, + request, + snapshot); + } + + private static Binding materializerBinding() { + return materializerBinding("trust-revision-1"); + } + + private static Binding materializerBinding(String revision) { + List pins = List.of("a".repeat(64)); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, + "prod", + "prod-cluster-1", + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + pins); + return new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + pins, + revision, + digest); + } + + private static BindingIdentity apiIdentity() { + return new BindingIdentity( + API_DIGEST, + API_REVISION, + "prod", + "prod-cluster-1", + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + "https://kubernetes.default.svc:6443/", + "kubernetes.default.svc", + "b".repeat(64), + "system:serviceaccount:firemud-prod:account-service"); + } + + private static EnrollmentIdentity enrollment(Binding binding) { + return new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + binding.bindingDigest(), + binding.configRevision(), + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, PUBLIC_JWKS))); + } + + private static void stubCurrentGenerationRequest( + Fixture fixture, AtomicBoolean insideTransaction) { + when(fixture + .repository() + .readCurrentGenerationRequest( + eq(fixture.binding().accountBinding()), eq(trustFence(fixture.binding())))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(insideTransaction.get()).isTrue(); + return fixture.request(); + }); + } + + private static void stubPublicationAndMountRefresh( + Fixture fixture, AtomicBoolean insideTransaction) { + var operationId = fixture.request().operationId(); + var publication = mock(AccountJwtJwksPublicationRepository.PublicationReceipt.class); + var mounted = mock(AccountJwtJwksPublicationRepository.MountObservation.class); + when(publication.operationId()).thenReturn(operationId); + when(mounted.operationId()).thenReturn(operationId); + when(fixture.prepublication().prepublishCurrentGeneration()) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(insideTransaction.get()).isFalse(); + return publication; + }); + when(fixture.prepublication().observeCurrentMountedCorrespondence()) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(insideTransaction.get()).isFalse(); + return mounted; + }); + } + + private static GenerationRequest request(Binding binding, GenerationPhase phase) { + if (phase == GenerationPhase.GENERATION_RECORDED) { + GenerationRequest recorded = mock(GenerationRequest.class); + when(recorded.phase()).thenReturn(phase); + when(recorded.operationId()) + .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); + when(recorded.operationDigest()).thenReturn("c".repeat(64)); + when(recorded.targetGeneration()).thenReturn("1"); + when(recorded.targetKid()).thenReturn("test-kid"); + return recorded; + } + return new GenerationRequest( + phase, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "c".repeat(64), + phase == GenerationPhase.GENERATE_PENDING ? "d".repeat(64) : "", + 2, + binding.accountBinding(), + trustFence(binding), + "jwt-signing-keys", + "1", + "test-kid", + "RS256", + "MATERIALIZE_PENDING", + List.of("pending"), + Optional.empty(), + Optional.empty(), + phase == GenerationPhase.GENERATE_PENDING ? "55555555-5555-4555-8555-555555555555" : "", + phase == GenerationPhase.GENERATE_PENDING ? "12" : "", + "", + "", + "", + ""); + } + + private static ObservationContext initialObservationContext( + UUID operationId, String operationDigest) { + return new ObservationContext( + ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES, operationId, operationDigest); + } + + private static ObservationContext initialObservationContext(GenerationRequest request) { + return initialObservationContext(request.operationId(), request.operationDigest()); + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private record Fixture( + AccountJwtSignerBootstrapCoordinator coordinator, + AccountJwtSignerMaterializerTrustBinding materializerTrust, + AccountJwtJwksConfigMapClient client, + AccountJwtSignerDesiredStateRepository repository, + AccountJwtJwksPrepublicationService prepublication, + AccountJwtReadinessProbeRepository readinessRepository, + AccountJwtValidatorInventorySource inventorySource, + InventorySnapshot inventorySnapshot, + ObjectProvider inventorySourceProvider, + Binding binding, + GenerationRequest request, + ConfigMapSnapshot snapshot) {} + + private static final class InertTransactionManager extends AbstractPlatformTransactionManager { + private final AtomicBoolean active; + + private InertTransactionManager(AtomicBoolean active) { + this.active = active; + } + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected boolean isExistingTransaction(Object transaction) { + return false; + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + active.set(true); + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + active.set(false); + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + active.set(false); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySourceTest.java new file mode 100644 index 0000000000..91ff7c8076 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySourceTest.java @@ -0,0 +1,828 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiOperation; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProtectedInventory; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ValidatorExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventoryUnavailableException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtValidatorInventorySourceTest { + private static final String ENVIRONMENT = "test"; + private static final String CLUSTER = "cluster-test"; + private static final String NAMESPACE = "firemud-test"; + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String DEPLOYMENT_UID = "33333333-3333-4333-8333-333333333333"; + private static final String REPLICA_SET_UID = "44444444-4444-4444-8444-444444444444"; + private static final String POD_UID = "55555555-5555-4555-8555-555555555555"; + private static final String POD_IP = "10.10.0.15"; + private static final String POD_SPKI = "e".repeat(64); + private static final String POD_TEMPLATE_HASH = "abcde12345"; + private static final String API_DIGEST = "a".repeat(64); + private static final String IMAGE_DIGEST = "d".repeat(64); + private static final String IMAGE = "registry.example/firemud/player@sha256:" + IMAGE_DIGEST; + private static final String EXPECTED_USERNAME = + "system:serviceaccount:" + NAMESPACE + ":account-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-10-05T00:00:00Z"), ZoneOffset.UTC); + + @Test + void defaultBindingsRemainInactiveAndUnavailable() { + AccountJwtValidatorInventorySource source = + new AccountJwtValidatorInventorySource( + new AccountJwtJwksApiBinding(), new AccountJwtValidatorInventoryBinding(), CLOCK); + + assertThatThrownBy(source::observe) + .isInstanceOf(InventoryUnavailableException.class) + .hasNoCause(); + } + + @Test + void returnsOnlyStableActualPodAndDeploymentIdentitiesAsNonAuthorizingEvidence() + throws Exception { + Fixture fixture = new Fixture(); + + InventorySnapshot snapshot = fixture.source.observe(); + + assertThat(snapshot.environmentId()).isEqualTo(ENVIRONMENT); + assertThat(snapshot.clusterIncarnationUid()).isEqualTo(CLUSTER_UID); + assertThat(snapshot.namespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(snapshot.validators()).hasSize(1); + assertThat(snapshot.validators().get(0).deploymentUid()).isEqualTo(DEPLOYMENT_UID); + assertThat(snapshot.validators().get(0).pods()) + .extracting(AccountJwtValidatorInventorySource.PodObservation::uid) + .containsExactly(POD_UID); + assertThat(snapshot.validators().get(0).pods().get(0).ownerUid()).isEqualTo(REPLICA_SET_UID); + assertThat(snapshot.validators().get(0).pods().get(0).podIp()).isEqualTo(POD_IP); + assertThat(snapshot.validators().get(0).pods().get(0).endpoint()) + .isEqualTo(URI.create("grpcs://10.10.0.15:8443")); + assertThat(snapshot.validators().get(0).pods().get(0).receiverServiceUri()) + .isEqualTo("spiffe://firemud/ns/firemud-test/sa/player-service"); + assertThat(snapshot.validators().get(0).pods().get(0).leafSpkiSha256()).isEqualTo(POD_SPKI); + assertThat(snapshot.validators().get(0).replicaSets()) + .singleElement() + .satisfies( + replicaSet -> { + assertThat(replicaSet.ownerDeploymentName()).isEqualTo("player-service"); + assertThat(replicaSet.ownerDeploymentUid()).isEqualTo(DEPLOYMENT_UID); + }); + assertThat(snapshot.digest()).matches("[0-9a-f]{64}"); + assertThat(new String(snapshot.canonicalBytes(), StandardCharsets.UTF_8)) + .contains("ownerDeploymentUid", DEPLOYMENT_UID, "podTemplateHash", POD_TEMPLATE_HASH) + .doesNotContain("observedAt"); + } + + @Test + void unchangedProtectedInventoryKeepsContentDigestAcrossLaterObservation() throws Exception { + Fixture fixture = new Fixture(); + InventorySnapshot first = fixture.source.observe(); + InventorySnapshot later = + new AccountJwtValidatorInventorySource( + fixture.apiBinding, + fixture.inventoryBinding, + Clock.offset(CLOCK, Duration.ofSeconds(10))) + .observe(); + + assertThat(later.observedAt()).isAfter(first.observedAt()); + assertThat(later.digest()).isEqualTo(first.digest()); + assertThat(later.canonicalBytes()).containsExactly(first.canonicalBytes()); + } + + @Test + void initialOperationCanEnumerateExactRunningCandidatesBeforeKubernetesReadiness() + throws Exception { + Fixture fixture = new Fixture(); + fixture.stubNotReadyCandidates(); + ObservationContext context = initialObservationContext(); + + InventorySnapshot snapshot = fixture.source.observe(context); + + assertThat(snapshot.observationContext()).contains(context); + assertThat(snapshot.validators()) + .singleElement() + .satisfies( + validator -> { + assertThat(validator.pods()) + .extracting(AccountJwtValidatorInventorySource.PodObservation::uid) + .containsExactly(POD_UID); + assertThat(validator.image()).isEqualTo(IMAGE); + assertThat(validator.verifierConfigSha256()).isNotBlank(); + }); + assertThat(new String(snapshot.canonicalBytes(), StandardCharsets.UTF_8)) + .contains( + "INITIAL_NO_ACTIVE_SIGNER_CANDIDATES", + context.operationId().toString(), + context.operationDigest()) + .doesNotContain("ordinaryReady"); + } + + @Test + void nonReadyCandidatesRemainUnavailableForNormalRotationAndUnboundObservation() + throws Exception { + Fixture fixture = new Fixture(); + fixture.stubNotReadyCandidates(); + + assertUnavailable(fixture); + assertThatThrownBy( + () -> + fixture.source.observe( + new ObservationContext( + ObservationPurpose.STRICT_READY, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "9".repeat(64)))) + .isInstanceOf(InventoryUnavailableException.class) + .hasNoCause(); + } + + @Test + void initialCandidateInventoryStillRejectsMissingOrSwappedPinnedPods() throws Exception { + ObservationContext context = initialObservationContext(); + Fixture missing = new Fixture(); + missing.stubNotReadyCandidates(); + when(missing.operation.listValidatorPods( + same(missing.inventory), same(missing.validator), isNull())) + .thenReturn( + new ApiResponse( + 200, + jsonBytes( + Map.of( + "apiVersion", + "v1", + "kind", + "PodList", + "metadata", + Map.of("resourceVersion", "20", "continue", ""), + "items", + List.of())))); + + Fixture swapped = new Fixture(); + swapped.stubNotReadyCandidates(); + when(swapped.operation.listValidatorPods( + same(swapped.inventory), same(swapped.validator), isNull())) + .thenReturn( + new ApiResponse( + 200, podListJson(POD_IP, "66666666-6666-4666-8666-666666666666", false))); + + assertBootstrapUnavailable(missing, context); + assertBootstrapUnavailable(swapped, context); + } + + @Test + void deniesUnexpectedAuthenticatedPrincipalAndNamespaceIncarnation() throws Exception { + Fixture wrongPrincipal = new Fixture(); + wrongPrincipal.stubSelfReview("system:serviceaccount:" + NAMESPACE + ":other"); + assertUnavailable(wrongPrincipal); + verify(wrongPrincipal.operation, times(0)) + .readValidatorDeployment(same(wrongPrincipal.inventory), same(wrongPrincipal.validator)); + + Fixture wrongNamespace = new Fixture(); + wrongNamespace.stubTargetNamespace("99999999-9999-4999-8999-999999999999"); + assertUnavailable(wrongNamespace); + verify(wrongNamespace.operation, times(0)).readValidatorDeployment(any(), any()); + } + + @Test + void deniesLegacyHmacRuntimeAndPartialDeploymentRollout() throws Exception { + Fixture legacy = new Fixture(); + legacy.stubDeployment(new ApiResponse(200, deploymentJson("10", 1, 1, 1, true))); + assertUnavailable(legacy); + + Fixture partial = new Fixture(); + partial.stubDeployment(new ApiResponse(200, deploymentJson("10", 1, 1, 0, false))); + assertUnavailable(partial); + } + + @Test + void rejectsNullPodListEntriesAsUnavailableInventory() throws Exception { + Fixture fixture = new Fixture(); + byte[] nullPodList = + jsonBytes( + Map.of( + "apiVersion", + "v1", + "kind", + "PodList", + "metadata", + Map.of("resourceVersion", "20"), + "items", + java.util.Collections.singletonList(null))); + when(fixture.operation.listValidatorPods( + same(fixture.inventory), same(fixture.validator), isNull())) + .thenReturn(new ApiResponse(200, nullPodList)); + + assertUnavailable(fixture); + } + + @Test + void deniesADeploymentThatChangesBetweenTheTwoInventoryReads() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.operation.readValidatorDeployment( + same(fixture.inventory), same(fixture.validator))) + .thenReturn( + new ApiResponse(200, deploymentJson("10", 1, 1, 1, false)), + new ApiResponse(200, deploymentJson("11", 2, 2, 1, false))); + + assertUnavailable(fixture); + } + + @Test + void deniesPodAddressThatDiffersFromTheProtectedPodBoundTlsPin() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.operation.listValidatorPods( + same(fixture.inventory), same(fixture.validator), isNull())) + .thenReturn(new ApiResponse(200, podListJson("10.10.0.16"))); + + assertUnavailable(fixture); + } + + @Test + void deniesLivePodUidMissingFromTheProtectedReceiverIdentityMap() throws Exception { + Fixture fixture = + new Fixture( + validInventoryBytes( + "66666666-6666-4666-8666-666666666666", + POD_IP, + POD_SPKI, + IMAGE, + "https://account-api.test/.well-known/jwks.json", + "inventory-r1")); + + assertUnavailable(fixture); + } + + @Test + void changedProtectedPodKeyOrBindingRevisionChangesInventoryContentIdentity() throws Exception { + InventorySnapshot original = new Fixture().source.observe(); + InventorySnapshot changed = + new Fixture( + validInventoryBytes( + POD_UID, + POD_IP, + "f".repeat(64), + IMAGE, + "https://account-api.test/.well-known/jwks.json", + "inventory-r1")) + .source.observe(); + InventorySnapshot changedSourceRevision = + new Fixture( + validInventoryBytes( + POD_UID, + POD_IP, + POD_SPKI, + IMAGE, + "https://account-api.test/.well-known/jwks.json", + "inventory-r2")) + .source.observe(); + + assertThat(changed.digest()).isNotEqualTo(original.digest()); + assertThat(changedSourceRevision.digest()).isNotEqualTo(original.digest()); + } + + @Test + void deniesLiveImageOrVerifierConfigurationThatDriftsFromProtectedInventory() throws Exception { + Fixture changedImage = + new Fixture( + validInventoryBytes( + POD_UID, + POD_IP, + POD_SPKI, + "registry.example/firemud/player@sha256:" + "f".repeat(64), + "https://account-api.test/.well-known/jwks.json", + "inventory-r2")); + Fixture changedConfig = + new Fixture( + validInventoryBytes( + POD_UID, + POD_IP, + POD_SPKI, + IMAGE, + "https://replacement-api.test/.well-known/jwks.json", + "inventory-r2")); + + assertUnavailable(changedImage); + assertUnavailable(changedConfig); + } + + @Test + void deniesReplicaSetOwnedByDifferentDeploymentEvenWhenPodOwnerMatches() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.operation.readValidatorReplicaSet( + same(fixture.inventory), same(fixture.validator), eq("player-service-abcde"))) + .thenReturn( + new ApiResponse( + 200, + replicaSetJson( + "40", + "44444444-4444-4444-8444-444444444444", + "other-service", + "99999999-9999-4999-8999-999999999999"))); + + assertUnavailable(fixture); + } + + @Test + void deniesReplicaSetUidReplacementOrOwnershipChangeBetweenInventoryReads() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.operation.readValidatorReplicaSet( + same(fixture.inventory), same(fixture.validator), eq("player-service-abcde"))) + .thenReturn( + new ApiResponse( + 200, replicaSetJson("40", REPLICA_SET_UID, "player-service", DEPLOYMENT_UID)), + new ApiResponse( + 200, + replicaSetJson( + "41", + "66666666-6666-4666-8666-666666666666", + "player-service", + DEPLOYMENT_UID))); + + assertUnavailable(fixture); + } + + @Test + void deniesADeploymentPodListWhosePaginationNeverCompletes() throws Exception { + Fixture fixture = new Fixture(); + byte[] unfinishedPage = + jsonBytes( + Map.of( + "apiVersion", + "v1", + "kind", + "PodList", + "metadata", + Map.of("resourceVersion", "20", "continue", "next-page"), + "items", + List.of())); + when(fixture.operation.listValidatorPods( + same(fixture.inventory), same(fixture.validator), any())) + .thenReturn(new ApiResponse(200, unfinishedPage)); + + assertUnavailable(fixture); + + verify(fixture.operation, times(16)) + .listValidatorPods(same(fixture.inventory), same(fixture.validator), any()); + } + + private static void assertUnavailable(Fixture fixture) { + assertThatThrownBy(fixture.source::observe) + .isInstanceOf(InventoryUnavailableException.class) + .hasNoCause(); + } + + private static void assertBootstrapUnavailable(Fixture fixture, ObservationContext context) { + assertThatThrownBy(() -> fixture.source.observe(context)) + .isInstanceOf(InventoryUnavailableException.class) + .hasNoCause(); + } + + private static ObservationContext initialObservationContext() { + return new ObservationContext( + ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "9".repeat(64)); + } + + private static byte[] deploymentJson( + String resourceVersion, + int generation, + int observedGeneration, + int readyReplicas, + boolean legacyHmac) + throws Exception { + return deploymentJson( + resourceVersion, generation, observedGeneration, readyReplicas, legacyHmac, false); + } + + private static byte[] deploymentJson( + String resourceVersion, + int generation, + int observedGeneration, + int readyReplicas, + boolean legacyHmac, + boolean omitZeroReadinessCounts) + throws Exception { + List> env = new ArrayList<>(); + env.add(Map.of("name", "FIREMUD_JWT_VERIFIER_CONFIG", "value", runtimeConfig())); + if (legacyHmac) { + env.add(Map.of("name", "FIREMUD_AUTH_JWT_SECRET", "value", "not-retained")); + } + Map container = + Map.of("name", "player-service", "image", IMAGE, "env", env, "volumeMounts", List.of()); + Map template = + Map.of( + "metadata", Map.of("labels", Map.of("app", "player-service")), + "spec", Map.of("containers", List.of(container), "volumes", List.of())); + Map spec = + Map.of( + "replicas", + 1, + "selector", + Map.of("matchLabels", Map.of("app", "player-service")), + "template", + template); + Map status = new LinkedHashMap<>(); + status.put("observedGeneration", observedGeneration); + if (!omitZeroReadinessCounts || readyReplicas != 0) { + status.put("readyReplicas", readyReplicas); + } + status.put("updatedReplicas", 1); + if (!omitZeroReadinessCounts || readyReplicas != 0) { + status.put("availableReplicas", readyReplicas); + } + return jsonBytes( + Map.of( + "apiVersion", + "apps/v1", + "kind", + "Deployment", + "metadata", + Map.of( + "name", "player-service", + "namespace", NAMESPACE, + "uid", DEPLOYMENT_UID, + "resourceVersion", resourceVersion, + "generation", generation), + "spec", + spec, + "status", + status)); + } + + private static byte[] podListJson() throws Exception { + return podListJson(POD_IP); + } + + private static byte[] podListJson(String podIp) throws Exception { + return podListJson(podIp, POD_UID, true); + } + + private static byte[] podListJson(String podIp, String podUid, boolean ready) throws Exception { + Map container = + Map.of( + "name", + "player-service", + "image", + IMAGE, + "env", + List.of(Map.of("name", "FIREMUD_JWT_VERIFIER_CONFIG", "value", runtimeConfig())), + "volumeMounts", + List.of()); + Map pod = + Map.of( + "apiVersion", "v1", + "kind", "Pod", + "metadata", + Map.of( + "name", + "player-service-abcde-12345", + "namespace", + NAMESPACE, + "uid", + podUid, + "resourceVersion", + "30", + "labels", + Map.of("app", "player-service", "pod-template-hash", POD_TEMPLATE_HASH), + "ownerReferences", + List.of( + Map.of( + "apiVersion", "apps/v1", + "kind", "ReplicaSet", + "name", "player-service-abcde", + "uid", REPLICA_SET_UID, + "controller", true))), + "spec", Map.of("containers", List.of(container), "volumes", List.of()), + "status", + Map.of( + "phase", + "Running", + "podIP", + podIp, + "conditions", + List.of(Map.of("type", "Ready", "status", ready ? "True" : "False")), + "containerStatuses", + List.of( + Map.of( + "name", + "player-service", + "ready", + ready, + "imageID", + "docker-pullable://registry.example/player@sha256:" + IMAGE_DIGEST)))); + return jsonBytes( + Map.of( + "apiVersion", + "v1", + "kind", + "PodList", + "metadata", + Map.of("resourceVersion", "20", "continue", ""), + "items", + List.of(pod))); + } + + private static byte[] replicaSetJson( + String resourceVersion, String uid, String ownerName, String ownerUid) throws Exception { + return replicaSetJson(resourceVersion, uid, ownerName, ownerUid, 1); + } + + private static byte[] replicaSetJson( + String resourceVersion, String uid, String ownerName, String ownerUid, int readyReplicas) + throws Exception { + return replicaSetJson(resourceVersion, uid, ownerName, ownerUid, readyReplicas, false); + } + + private static byte[] replicaSetJson( + String resourceVersion, + String uid, + String ownerName, + String ownerUid, + int readyReplicas, + boolean omitZeroReadyReplicas) + throws Exception { + Map container = + Map.of( + "name", + "player-service", + "image", + IMAGE, + "env", + List.of(Map.of("name", "FIREMUD_JWT_VERIFIER_CONFIG", "value", runtimeConfig())), + "volumeMounts", + List.of()); + Map status = new LinkedHashMap<>(); + status.put("observedGeneration", 1); + if (!omitZeroReadyReplicas || readyReplicas != 0) { + status.put("readyReplicas", readyReplicas); + } + return jsonBytes( + Map.of( + "apiVersion", + "apps/v1", + "kind", + "ReplicaSet", + "metadata", + Map.of( + "name", + "player-service-abcde", + "namespace", + NAMESPACE, + "uid", + uid, + "resourceVersion", + resourceVersion, + "generation", + 1, + "ownerReferences", + List.of( + Map.of( + "apiVersion", + "apps/v1", + "kind", + "Deployment", + "name", + ownerName, + "uid", + ownerUid, + "controller", + true))), + "spec", + Map.of( + "replicas", 1, + "selector", + Map.of( + "matchLabels", + Map.of("app", "player-service", "pod-template-hash", POD_TEMPLATE_HASH)), + "template", + Map.of( + "metadata", + Map.of( + "labels", + Map.of( + "app", + "player-service", + "pod-template-hash", + POD_TEMPLATE_HASH)), + "spec", Map.of("containers", List.of(container), "volumes", List.of()))), + "status", + status)); + } + + private static String runtimeConfig() { + return AccountJwtValidatorInventoryBinding.parseProtectedBytes(validInventoryBytes()) + .validators() + .get(0) + .canonicalRuntimeConfig(); + } + + private static byte[] validInventoryBytes() { + return validInventoryBytes( + POD_UID, + POD_IP, + POD_SPKI, + IMAGE, + "https://account-api.test/.well-known/jwks.json", + "inventory-r1"); + } + + private static byte[] validInventoryBytes( + String podUid, + String podIp, + String podSpki, + String image, + String jwksUri, + String configRevision) { + Map validator = new LinkedHashMap<>(); + validator.put("validatorId", "player-service"); + validator.put("deploymentName", "player-service"); + validator.put("deploymentUid", DEPLOYMENT_UID); + validator.put("selector", Map.of("app", "player-service")); + validator.put("replicas", 1); + validator.put("containerName", "player-service"); + validator.put("image", image); + validator.put("jwksUri", jwksUri); + validator.put("maxCacheAgeSeconds", 60); + validator.put( + "profiles", + List.of( + Map.of( + "tokenProfile", "game-session-account-delegation", + "audience", "account-service"))); + validator.put("receiverServiceUri", "spiffe://firemud/ns/firemud-test/sa/player-service"); + validator.put("receiverPort", 8443); + validator.put( + "receiverPods", + List.of(Map.of("podUid", podUid, "podIp", podIp, "leafSpkiSha256", podSpki))); + Map root = new LinkedHashMap<>(); + root.put("version", "account-jwt-validator-inventory-binding/v2"); + root.put("enabled", "true"); + root.put("configRevision", configRevision); + root.put("environmentId", ENVIRONMENT); + root.put("clusterId", CLUSTER); + root.put("namespace", NAMESPACE); + root.put("expectedClusterIncarnationUid", CLUSTER_UID); + root.put("expectedNamespaceUid", NAMESPACE_UID); + root.put("apiBindingRevision", "api-r1"); + root.put("apiBindingDigest", API_DIGEST); + root.put("validators", List.of(validator)); + root.put("bindingDigest", "0".repeat(64)); + try { + var unsigned = JSON.readTree(JSON.writeValueAsBytes(root)); + root.put("bindingDigest", AccountJwtValidatorInventoryBinding.computeBindingDigest(unsigned)); + return JSON.writeValueAsBytes(root); + } catch (Exception failure) { + throw new AssertionError(failure); + } + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = "Canonical protected paths are fixed test binding inputs") + private static ParsedBinding apiBinding() { + return new ParsedBinding( + "api-r1", + ENVIRONMENT, + CLUSTER, + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + Path.of("/etc/firemud/account-jwt-api/serving-ca.pem"), + "c".repeat(64), + Path.of("/var/run/secrets/firemud/account-jwt-api-token/token"), + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + EXPECTED_USERNAME, + API_DIGEST); + } + + private static byte[] jsonBytes(Object value) { + try { + return JSON.writeValueAsBytes(value); + } catch (Exception failure) { + throw new AssertionError(failure); + } + } + + private static byte[] namespaceJson(String namespace, String uid) { + return jsonBytes( + Map.of( + "apiVersion", + "v1", + "kind", + "Namespace", + "metadata", + Map.of("name", namespace, "uid", uid), + "status", + Map.of("phase", "Active"))); + } + + private static byte[] selfReviewJson(String username) { + return jsonBytes( + Map.of( + "apiVersion", "authentication.k8s.io/v1", + "kind", "SelfSubjectReview", + "status", Map.of("userInfo", Map.of("username", username)))); + } + + private static final class Fixture { + private final AccountJwtJwksApiBinding apiBinding = mock(AccountJwtJwksApiBinding.class); + private final AccountJwtValidatorInventoryBinding inventoryBinding = + mock(AccountJwtValidatorInventoryBinding.class); + private final ApiOperation operation = mock(ApiOperation.class); + private final ProtectedInventory inventory; + private final ValidatorExpectation validator; + private final AccountJwtValidatorInventorySource source; + + private Fixture() throws Exception { + this(validInventoryBytes()); + } + + private Fixture(byte[] inventoryBytes) throws Exception { + inventory = AccountJwtValidatorInventoryBinding.parseProtectedBytes(inventoryBytes); + validator = inventory.validators().get(0); + when(apiBinding.beginOperation()).thenReturn(operation); + when(operation.binding()).thenReturn(apiBinding()); + when(inventoryBinding.current()).thenReturn(Optional.of(inventory)); + when(operation.send(eq(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL), any(byte[].class))) + .thenReturn(new ApiResponse(201, selfReviewJson(EXPECTED_USERNAME))); + when(operation.send(ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null)) + .thenReturn(new ApiResponse(200, namespaceJson("kube-system", CLUSTER_UID))); + when(operation.send(ApiCall.READ_TARGET_NAMESPACE, null)) + .thenReturn(new ApiResponse(200, namespaceJson(NAMESPACE, NAMESPACE_UID))); + ApiResponse deployment = new ApiResponse(200, deploymentJson("10", 1, 1, 1, false)); + ApiResponse pods = new ApiResponse(200, podListJson()); + when(operation.readValidatorDeployment(same(inventory), same(validator))) + .thenReturn(deployment); + when(operation.listValidatorPods(same(inventory), same(validator), isNull())) + .thenReturn(pods); + when(operation.readValidatorReplicaSet( + same(inventory), same(validator), eq("player-service-abcde"))) + .thenReturn( + new ApiResponse( + 200, replicaSetJson("40", REPLICA_SET_UID, "player-service", DEPLOYMENT_UID))); + source = new AccountJwtValidatorInventorySource(apiBinding, inventoryBinding, CLOCK); + } + + private void stubSelfReview(String username) { + when(operation.send(eq(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL), any(byte[].class))) + .thenReturn(new ApiResponse(201, selfReviewJson(username))); + } + + private void stubTargetNamespace(String uid) { + when(operation.send(ApiCall.READ_TARGET_NAMESPACE, null)) + .thenReturn(new ApiResponse(200, namespaceJson(NAMESPACE, uid))); + } + + private void stubDeployment(ApiResponse response) { + when(operation.readValidatorDeployment(same(inventory), same(validator))) + .thenReturn(response); + } + + private void stubNotReadyCandidates() throws Exception { + stubDeployment(new ApiResponse(200, deploymentJson("10", 1, 1, 0, false, true))); + when(operation.listValidatorPods(same(inventory), same(validator), isNull())) + .thenReturn(new ApiResponse(200, podListJson(POD_IP, POD_UID, false))); + when(operation.readValidatorReplicaSet( + same(inventory), same(validator), eq("player-service-abcde"))) + .thenReturn( + new ApiResponse( + 200, + replicaSetJson( + "40", REPLICA_SET_UID, "player-service", DEPLOYMENT_UID, 0, true))); + } + } +} diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index 09249e0ea3..658ca9cb1d 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -133,7 +133,7 @@ private static PreparedSelection prepareSelection( ownerOutcomes.add(new GameDesignSourceRepository(dsl).apply(draft).ownerOutcome()); } var epochs = - draft.affectedUnits().stream() + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() .map( unit -> new DraftCommitCoordinatorRepository.AppliedEpoch( diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java index 967d8e48fa..b501f5ae9f 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -36,7 +36,7 @@ public static GameDesignPublicationOperation fresh(DraftCommitBinding.TargetProo new String(originalDraftAccount.gameDesignBinding(), StandardCharsets.UTF_8), originalDraftAccount.inputDigest()); var appliedEpochs = - draft.affectedUnits().stream() + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() .map( unit -> Map.of( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessProbeOwnerWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessProbeOwnerWorkloadGuard.java new file mode 100644 index 0000000000..7f0cf2a62f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessProbeOwnerWorkloadGuard.java @@ -0,0 +1,64 @@ +package net.firedevops.firemud.gamesession.config; + +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Exact same-namespace Account mTLS guard for the isolated Game Session Pod receiver. */ +public final class GameSessionJwtReadinessProbeOwnerWorkloadGuard { + private static final String ACCOUNT_SERVICE = "account-service"; + private static final String METHOD_NAME = + "game_session.v1.GameSessionJwtReadinessReceiverService/ReceiveReadinessProbe"; + + private final String trustedNamespace; + + public GameSessionJwtReadinessProbeOwnerWorkloadGuard(String trustedNamespace) { + this.trustedNamespace = trustedNamespace == null ? "" : trustedNamespace.trim(); + } + + /** Requires the exact Account workload peer and an otherwise empty application auth context. */ + public AuthenticatedCaller requireAccountReceiverCaller(String fullMethodName) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!METHOD_NAME.equals(fullMethodName) + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || peer == null + || !ACCOUNT_SERVICE.equals(peer.service()) + || !trustedNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + trustedNamespace + "/sa/" + ACCOUNT_SERVICE) + .equals(peer.uri()) + || hasSessionContext()) { + throw new ReceiverCallerDeniedException(); + } + return new AuthenticatedCaller(peer); + } + + /** Rejects peer or application-context drift across the crypto and owner-read sequence. */ + public void requireUnchanged(AuthenticatedCaller before, String fullMethodName) { + Objects.requireNonNull(before, "Initial authenticated caller is required"); + AuthenticatedCaller after = requireAccountReceiverCaller(fullMethodName); + if (!before.peer().equals(after.peer())) { + throw new ReceiverCallerDeniedException(); + } + } + + private static boolean hasSessionContext() { + return SessionContext.getAccountId() != null + || !SessionContext.getGlobalRoles().isEmpty() + || !SessionContext.getScopedRolesMap().isEmpty() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null; + } + + public record AuthenticatedCaller(GrpcPeerIdentity peer) { + public AuthenticatedCaller { + Objects.requireNonNull(peer); + } + } + + public static final class ReceiverCallerDeniedException extends SecurityException { + public ReceiverCallerDeniedException() { + super("Authenticated same-namespace Account workload is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfiguration.java new file mode 100644 index 0000000000..4a35de823c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfiguration.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.gamesession.config; + +import java.time.Clock; +import java.time.Duration; +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.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessLocalIdentityProvider; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProbeCrypto; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProbeOwnerClient; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProbeOwnerReadPort; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProtectedJwksSource; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverEngine; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverProtoMapper; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; + +/** + * Explicit default-off composition; absence of protected Pod identity leaves the route + * unregistered. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.game-session.jwt-readiness.receiver", + name = "enabled", + havingValue = "true") +@ConditionalOnBean(GameSessionJwtReadinessLocalIdentityProvider.class) +@Lazy +public class GameSessionJwtReadinessReceiverConfiguration { + @Bean + @Lazy + public GameSessionJwtReadinessProtectedJwksSource gameSessionJwtReadinessPublicJwksSource( + GameSessionJwtReadinessLocalIdentityProvider localIdentityProvider) { + return new GameSessionJwtReadinessProtectedJwksSource(localIdentityProvider); + } + + @Bean + @Lazy + public AccountPublicJwksCache gameSessionJwtReadinessPublicJwksCache( + GameSessionJwtReadinessProtectedJwksSource trustedJwksSource, + GameSessionJwtReadinessLocalIdentityProvider localIdentityProvider) { + return new AccountPublicJwksCache( + trustedJwksSource, + localIdentityProvider.observe().jwksSourceIdentity(), + Clock.systemUTC(), + Duration.ofSeconds(300)); + } + + @Bean + @Lazy + public AccountAsymmetricJwtVerifier gameSessionJwtReadinessProductionVerifier( + @Qualifier("gameSessionJwtReadinessPublicJwksCache") + AccountPublicJwksCache gameSessionJwtReadinessPublicJwksCache) { + return new AccountAsymmetricJwtVerifier( + gameSessionJwtReadinessPublicJwksCache, Clock.systemUTC()); + } + + @Bean + @Lazy + public GameSessionJwtReadinessProbeCrypto gameSessionJwtReadinessProbeCrypto( + @Qualifier("gameSessionJwtReadinessProductionVerifier") + AccountAsymmetricJwtVerifier gameSessionJwtReadinessProductionVerifier, + @Value("${firemud.game-session.jwt-readiness.receiver.max-control-ui-tenant-scopes}") + int maxControlUiTenantScopes) { + return new GameSessionJwtReadinessProbeCrypto( + gameSessionJwtReadinessProductionVerifier, maxControlUiTenantScopes); + } + + @Bean + @Lazy + public GameSessionJwtReadinessProbeOwnerReadPort gameSessionJwtReadinessProbeOwnerReadPort( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new GameSessionJwtReadinessProbeOwnerClient( + endpoints, tlsProperties, channelFactory, workloadNamespace); + } + + @Bean + @Lazy + public GameSessionJwtReadinessProbeOwnerWorkloadGuard + gameSessionJwtReadinessProbeOwnerWorkloadGuard( + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new GameSessionJwtReadinessProbeOwnerWorkloadGuard(workloadNamespace); + } + + @Bean + @Lazy + public GameSessionJwtReadinessReceiverProtoMapper gameSessionJwtReadinessReceiverProtoMapper() { + return new GameSessionJwtReadinessReceiverProtoMapper(); + } + + @Bean + @Lazy + public GameSessionJwtReadinessReceiverEngine gameSessionJwtReadinessReceiverEngine( + GameSessionJwtReadinessProbeOwnerWorkloadGuard workloadGuard, + GameSessionJwtReadinessLocalIdentityProvider localIdentityProvider, + GameSessionJwtReadinessProbeOwnerReadPort ownerReadPort, + GameSessionJwtReadinessReceiverProtoMapper protoMapper, + @Qualifier("gameSessionJwtReadinessProbeCrypto") GameSessionJwtReadinessProbeCrypto crypto) { + return new GameSessionJwtReadinessReceiverEngine( + workloadGuard, + localIdentityProvider, + ownerReadPort, + protoMapper, + crypto, + Clock.systemUTC()); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessLocalIdentityProvider.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessLocalIdentityProvider.java new file mode 100644 index 0000000000..16a75451d9 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessLocalIdentityProvider.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSourceIdentity; +import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; + +/** + * Supplies receiver-local Pod and JWKS pins from protected runtime configuration, never a request. + */ +public interface GameSessionJwtReadinessLocalIdentityProvider { + LocalObservation observe(); + + record LocalObservation( + ReadinessReceiverLocalIdentity wireIdentity, SourceIdentity jwksSourceIdentity) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "ReadinessReceiverLocalIdentity is an immutable generated protobuf value.") + public LocalObservation { + Objects.requireNonNull(wireIdentity, "protected receiver identity is required"); + Objects.requireNonNull(jwksSourceIdentity, "protected JWKS source identity is required"); + if (!wireIdentity.hasAccountJwksSourceIdentity() + || !jwksSourceIdentity.equals(fromProto(wireIdentity.getAccountJwksSourceIdentity())) + || wireIdentity.getAccountJwksTrustConfigRevision() <= 0L) { + throw new IllegalArgumentException("Protected receiver JWKS identity is inconsistent"); + } + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "ReadinessReceiverLocalIdentity is an immutable generated protobuf value.") + public ReadinessReceiverLocalIdentity wireIdentity() { + return wireIdentity; + } + + private static SourceIdentity fromProto(AccountSourceIdentity value) { + return new SourceIdentity( + value.getEnvironmentId(), + value.getClusterId(), + value.getClusterIncarnationUid(), + value.getNamespace(), + value.getNamespaceUid(), + value.getConfigMapUid(), + value.getBindingRevision(), + value.getApiServerOrigin(), + value.getServingCaSha256()); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeCrypto.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeCrypto.java new file mode 100644 index 0000000000..c12231f547 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeCrypto.java @@ -0,0 +1,226 @@ +package net.firedevops.firemud.gamesession.service; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverProtoMapper.ParsedRequest; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeResponse; + +/** Production-profile cryptographic verification with a non-authorizing readiness result only. */ +public final class GameSessionJwtReadinessProbeCrypto { + private static final String ISSUER = "firemud-account-service"; + private static final String RESERVED_SUBJECT = "00000000-0000-4000-8000-000000000001"; + private static final String CANARY_TYPE = "account_jwt_readiness_canary"; + private static final Set CANARY_CLAIMS = + Set.of("iss", "sub", "jti", "aud", "iat", "nbf", "exp", "tokenProfile", "tokenType"); + private static final Set INITIAL_AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + + private final AccountAsymmetricJwtVerifier verifier; + private final int maxControlUiTenantScopes; + + public GameSessionJwtReadinessProbeCrypto( + AccountAsymmetricJwtVerifier verifier, int maxControlUiTenantScopes) { + this.verifier = java.util.Objects.requireNonNull(verifier); + if (maxControlUiTenantScopes <= 0 + || maxControlUiTenantScopes + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw new IllegalArgumentException("Control UI profile scope bound is invalid"); + } + this.maxControlUiTenantScopes = maxControlUiTenantScopes; + } + + /** + * Verifies signature, production profile shape, exact owner coordinates, and non-authorizing use. + */ + public VerifiedProbe verify(ParsedRequest request) { + ExplicitRouteProfilePolicy policy = policy(request); + VerifiedClaims claims = verifier.verify(request.compactJwt(), policy); + validateOwnerBoundProbe(request, claims); + ReceiveReadinessProbeResponse.ObservationOutcome outcome = + request.probeKind() == GameSessionJwtReadinessReceiverProtoMapper.ProbeKind.CANARY + || GameSessionAccountDelegationProfile.PROFILE.equals( + request.coordinates().getTokenProfile()) + ? ReceiveReadinessProbeResponse.ObservationOutcome.VERIFIED + : ReceiveReadinessProbeResponse.ObservationOutcome.INAPPLICABLE_REJECT; + var expectedOutcome = + outcome == ReceiveReadinessProbeResponse.ObservationOutcome.VERIFIED + ? net.firedevops.firemud.account.v1.ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT + : net.firedevops.firemud.account.v1.ReadinessProbeCoordinates.ExpectedOutcome + .INAPPLICABLE_REJECT; + if (request.expectedOutcome() != expectedOutcome) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + return new VerifiedProbe(claims.keyId(), outcome); + } + + private ExplicitRouteProfilePolicy policy(ParsedRequest request) { + if (request.probeKind() == GameSessionJwtReadinessReceiverProtoMapper.ProbeKind.CANARY) { + return new ExplicitRouteProfilePolicy( + "game-session-jwt-readiness-canary", + GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE, + CANARY_TYPE, + ISSUER, + GameSessionJwtReadinessReceiverProtoMapper.CANARY_AUDIENCE, + CANARY_CLAIMS, + Set.of(), + GameSessionJwtReadinessReceiverProtoMapper.MAX_PROBE_LIFETIME_SECONDS, + 5L, + GameSessionJwtReadinessReceiverProtoMapper.MAX_COMPACT_JWT_BYTES, + GameSessionJwtReadinessProbeCrypto::validateCanaryShape); + } + String profile = request.coordinates().getTokenProfile(); + return switch (profile) { + case ControlUiJwtProfileValidator.PROFILE -> + new ExplicitRouteProfilePolicy( + "game-session-jwt-readiness-control-ui", + ControlUiJwtProfileValidator.PROFILE, + ControlUiJwtProfileValidator.TOKEN_TYPE, + ISSUER, + ControlUiJwtProfileValidator.AUDIENCE, + ControlUiJwtProfileValidator.REQUIRED_CLAIMS, + ControlUiJwtProfileValidator.OPTIONAL_CLAIMS, + GameSessionJwtReadinessReceiverProtoMapper.MAX_PROBE_LIFETIME_SECONDS, + 5L, + GameSessionJwtReadinessReceiverProtoMapper.MAX_COMPACT_JWT_BYTES, + claims -> + ControlUiJwtProfileValidator.validateClaims(claims, maxControlUiTenantScopes)); + case PlayerBootstrapJwtProfileValidator.PROFILE -> + new ExplicitRouteProfilePolicy( + "game-session-jwt-readiness-player-bootstrap", + PlayerBootstrapJwtProfileValidator.PROFILE, + PlayerBootstrapJwtProfileValidator.TOKEN_TYPE, + ISSUER, + PlayerBootstrapJwtProfileValidator.AUDIENCE, + PlayerBootstrapJwtProfileValidator.REQUIRED_CLAIMS, + PlayerBootstrapJwtProfileValidator.OPTIONAL_CLAIMS, + GameSessionJwtReadinessReceiverProtoMapper.MAX_PROBE_LIFETIME_SECONDS, + 5L, + GameSessionJwtReadinessReceiverProtoMapper.MAX_COMPACT_JWT_BYTES, + PlayerBootstrapJwtProfileValidator::validateClaims); + case GameSessionAccountDelegationProfile.PROFILE -> + new ExplicitRouteProfilePolicy( + "game-session-jwt-readiness-game-session-account-delegation", + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.TYPE, + GameSessionAccountDelegationProfile.ISSUER, + GameSessionAccountDelegationProfile.AUDIENCE, + GameSessionAccountDelegationJwtProfileValidator.REQUIRED_CLAIMS, + GameSessionAccountDelegationJwtProfileValidator.OPTIONAL_CLAIMS, + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS, + 5L, + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES, + GameSessionAccountDelegationJwtProfileValidator::validateClaims); + default -> throw new AccountAsymmetricJwtVerifier.VerificationException(); + }; + } + + private static void validateCanaryShape(Map claims) { + if (!CANARY_CLAIMS.equals(claims.keySet()) + || !ISSUER.equals(claims.get("iss")) + || !GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE.equals( + claims.get("tokenProfile")) + || !CANARY_TYPE.equals(claims.get("tokenType"))) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + } + + private static void validateOwnerBoundProbe(ParsedRequest request, VerifiedClaims verified) { + Map claims = verified.claims(); + var coordinates = request.coordinates(); + boolean canary = + request.probeKind() == GameSessionJwtReadinessReceiverProtoMapper.ProbeKind.CANARY; + if (!verified.profile().equals(coordinates.getTokenProfile()) + || !verified.keyId().equals(coordinates.getTargetKid()) + || !ISSUER.equals(claims.get("iss")) + || !coordinates.getAudience().equals(claims.get("aud")) + || !RESERVED_SUBJECT.equals(claims.get("sub")) + || !request.jti().toString().equals(claims.get("jti")) + || exactLong(claims.get("iat")) != coordinates.getIssuedAtEpochSeconds() + || exactLong(claims.get("nbf")) != coordinates.getIssuedAtEpochSeconds() + || exactLong(claims.get("exp")) != coordinates.getExpiresAtEpochSeconds()) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + if (canary) { + if (!CANARY_CLAIMS.equals(claims.keySet())) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + return; + } + if (!RESERVED_SUBJECT.equals(claims.get("accountId")) + || !exactOneCounter(claims.get("tokenGeneration"), verified.profile()) + || !exactOneCounter(claims.get("issuanceFence"), verified.profile()) + || !exactAuthorityTuple(claims.get("authorityTuple"), verified.profile()) + || !(claims.get("membershipVersion") instanceof Map membershipVersion) + || !membershipVersion.isEmpty() + || !noRoles(claims) + || !noScopes(claims, verified.profile()) + || (GameSessionAccountDelegationProfile.PROFILE.equals(verified.profile()) + && claims.containsKey("tenantId"))) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + } + + private static boolean exactOneCounter(Object value, String profile) { + return GameSessionAccountDelegationProfile.PROFILE.equals(profile) + ? "1".equals(value) + : exactLong(value) == 1L; + } + + private static boolean exactAuthorityTuple(Object value, String profile) { + if (!(value instanceof Map tuple) + || !tuple.keySet().equals(INITIAL_AUTHORITY_TUPLE_FIELDS)) { + return false; + } + return exactOneCounter(tuple.get("issuerAuthGeneration"), profile) + && exactOneCounter(tuple.get("accountAuthorityGeneration"), profile) + && tuple.get("tenantAuthorityGeneration") instanceof Map tenantAuthority + && tenantAuthority.isEmpty() + && tuple.get("membershipAuthorityGeneration") instanceof Map membershipAuthority + && membershipAuthority.isEmpty() + && tuple.get("privateRealmGrantVersions") instanceof List grants + && grants.isEmpty(); + } + + private static boolean noRoles(Map claims) { + if (!claims.containsKey("globalRoles")) { + return true; + } + return claims.get("globalRoles") instanceof List roles && roles.isEmpty(); + } + + private static boolean noScopes(Map claims, String profile) { + if (GameSessionAccountDelegationProfile.PROFILE.equals(profile) + && !claims.containsKey("scopedRoles")) { + return true; + } + return claims.get("scopedRoles") instanceof Map scopes && scopes.isEmpty(); + } + + private static long exactLong(Object value) { + if (!(value instanceof Number number)) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + try { + return new BigDecimal(number.toString()).longValueExact(); + } catch (ArithmeticException | NumberFormatException invalid) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + } + + public record VerifiedProbe( + String keyId, ReceiveReadinessProbeResponse.ObservationOutcome outcome) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerClient.java new file mode 100644 index 0000000000..ea04851f0f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerClient.java @@ -0,0 +1,91 @@ +package net.firedevops.firemud.gamesession.service; + +import io.grpc.ClientInterceptors; +import io.grpc.ManagedChannel; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountJwtReadinessProbeOwnerServiceGrpc; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Direct mTLS-only client for the exact Account readiness owner read; attaches no bearer token. */ +public final class GameSessionJwtReadinessProbeOwnerClient + implements GameSessionJwtReadinessProbeOwnerReadPort { + private static final int DEFAULT_ACCOUNT_PORT = 6565; + private static final long DEADLINE_SECONDS = 5L; + private static final long SHUTDOWN_SECONDS = 2L; + + private final ServiceEndpointsProperties endpoints; + private final CommonGrpcClientProperties tlsProperties; + private final GrpcChannelFactory channelFactory; + private final String workloadNamespace; + + public GameSessionJwtReadinessProbeOwnerClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + this.endpoints = Objects.requireNonNull(endpoints).copy(); + this.tlsProperties = Objects.requireNonNull(tlsProperties).copy(); + this.channelFactory = Objects.requireNonNull(channelFactory); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || this.tlsProperties.isPlaintext() + || blank(this.tlsProperties.getCertChain()) + || blank(this.tlsProperties.getPrivateKey()) + || blank(this.tlsProperties.getCaCert())) { + throw new IllegalArgumentException("Protected Account mTLS client configuration is required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public GetCurrentReadinessProbeOwnerResponse readCurrent( + GetCurrentReadinessProbeOwnerRequest request) { + Objects.requireNonNull(request, "Current Account owner read request is required"); + ManagedChannel channel = null; + try { + String target = endpoints.getAccountService(); + if (blank(target)) { + target = "account-service:" + DEFAULT_ACCOUNT_PORT; + } + channel = channelFactory.buildChannel(target, DEFAULT_ACCOUNT_PORT, tlsProperties, false); + String expectedAccountUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + var accountChannel = + ClientInterceptors.intercept( + channel, new GrpcServerPeerIdentityClientInterceptor(expectedAccountUri)); + return AccountJwtReadinessProbeOwnerServiceGrpc.newBlockingStub(accountChannel) + .withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCurrentReadinessProbeOwner(request); + } catch (RuntimeException | javax.net.ssl.SSLException unavailable) { + throw new OwnerReadUnavailableException(); + } finally { + if (channel != null) { + channel.shutdownNow(); + try { + if (!channel.awaitTermination(SHUTDOWN_SECONDS, TimeUnit.SECONDS)) { + throw new OwnerReadUnavailableException(); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new OwnerReadUnavailableException(); + } + } + } + } + + private static boolean blank(String value) { + return value == null || value.isBlank(); + } + + public static final class OwnerReadUnavailableException extends RuntimeException { + public OwnerReadUnavailableException() { + super("Current Account readiness owner evidence is unavailable"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerReadPort.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerReadPort.java new file mode 100644 index 0000000000..e07deaa6e3 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerReadPort.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; + +/** + * Authenticated, read-only Account owner lookup; request contains the token hash, never the JWT. + */ +@FunctionalInterface +public interface GameSessionJwtReadinessProbeOwnerReadPort { + GetCurrentReadinessProbeOwnerResponse readCurrent(GetCurrentReadinessProbeOwnerRequest request); +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java new file mode 100644 index 0000000000..7a24ec1700 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.TrustedPublicJwksSource; + +/** + * Reads only Account's fixed projected public JWKS; it never discovers keys or uses classpath data. + */ +public final class GameSessionJwtReadinessProtectedJwksSource implements TrustedPublicJwksSource { + public static final Path JWKS_PATH = fixedJwksPath(); + + private static final Path JWKS_DIRECTORY = + Objects.requireNonNull( + JWKS_PATH.getParent(), "The fixed Account JWKS path must have a parent"); + private static final Path DATA_LINK = JWKS_DIRECTORY.resolve("..data"); + private static final int MAX_FILE_BYTES = AccountPublicJwksCache.MAX_JWKS_BYTES; + + private final GameSessionJwtReadinessLocalIdentityProvider identityProvider; + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The Account public JWKS is intentionally fixed to this read-only projected path; alternate paths would permit trust-source substitution.") + private static Path fixedJwksPath() { + return Path.of("/var/run/secrets/firemud/jwks/jwks.json"); + } + + public GameSessionJwtReadinessProtectedJwksSource( + GameSessionJwtReadinessLocalIdentityProvider identityProvider) { + this.identityProvider = Objects.requireNonNull(identityProvider); + } + + @Override + public PublicJwksSnapshot load() { + try { + GameSessionJwtReadinessLocalIdentityProvider.LocalObservation before = + Objects.requireNonNull(identityProvider.observe()); + byte[] bytes = readProjectedFile(); + try { + GameSessionJwtReadinessLocalIdentityProvider.LocalObservation after = + Objects.requireNonNull(identityProvider.observe()); + if (!before.equals(after)) { + throw unavailable(); + } + return new PublicJwksSnapshot(before.jwksSourceIdentity(), bytes); + } finally { + java.util.Arrays.fill(bytes, (byte) 0); + } + } catch (SourceUnavailableException unavailable) { + throw unavailable; + } catch (RuntimeException | IOException unavailable) { + throw unavailable(); + } + } + + private static byte[] readProjectedFile() throws IOException { + Path normalizedDirectory = JWKS_DIRECTORY.toAbsolutePath().normalize(); + if (!normalizedDirectory.equals(JWKS_DIRECTORY) + || Files.isSymbolicLink(JWKS_DIRECTORY) + || !Files.isSymbolicLink(DATA_LINK) + || !Files.isSymbolicLink(JWKS_PATH) + || !Path.of("..data/jwks.json").equals(Files.readSymbolicLink(JWKS_PATH))) { + throw unavailable(); + } + Path dataVersion = Files.readSymbolicLink(DATA_LINK); + if (dataVersion.isAbsolute() + || dataVersion.getNameCount() != 1 + || !dataVersion.toString().matches("\\.\\.[A-Za-z0-9._-]{1,128}")) { + throw unavailable(); + } + Path trustedDirectory = JWKS_DIRECTORY.toRealPath(LinkOption.NOFOLLOW_LINKS); + verifyRootOwnedReadOnly(trustedDirectory, true); + Path dataTarget = DATA_LINK.toRealPath(); + Path dataTargetParent = dataTarget.getParent(); + if (dataTargetParent == null + || !dataTargetParent.equals(trustedDirectory) + || !Files.isDirectory(dataTarget, LinkOption.NOFOLLOW_LINKS)) { + throw unavailable(); + } + verifyRootOwnedReadOnly(dataTarget, true); + Path file = dataTarget.resolve("jwks.json"); + BasicFileAttributes before = + Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0L || before.size() > MAX_FILE_BYTES) { + throw unavailable(); + } + verifyRootOwnedReadOnly(file, false); + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(file, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw unavailable(); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw unavailable(); + } + } + BasicFileAttributes after = + Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime()) + || !dataVersion.equals(Files.readSymbolicLink(DATA_LINK)) + || !dataTarget.equals(DATA_LINK.toRealPath()) + || !Path.of("..data/jwks.json").equals(Files.readSymbolicLink(JWKS_PATH))) { + java.util.Arrays.fill(bytes, (byte) 0); + throw unavailable(); + } + verifyRootOwnedReadOnly(file, false); + return bytes; + } + + private static void verifyRootOwnedReadOnly(Path path, boolean directory) throws IOException { + BasicFileAttributes attributes = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if ((directory && !attributes.isDirectory()) || (!directory && !attributes.isRegularFile())) { + throw unavailable(); + } + Object owner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set mode = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + if (!(owner instanceof Number uid) + || uid.longValue() != 0L + || mode.contains(PosixFilePermission.OWNER_WRITE) + || mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE)) { + throw unavailable(); + } + } + + private static SourceUnavailableException unavailable() { + return new SourceUnavailableException(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngine.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngine.java new file mode 100644 index 0000000000..ad283feb8f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngine.java @@ -0,0 +1,130 @@ +package net.firedevops.firemud.gamesession.service; + +import java.time.Clock; +import java.util.Objects; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.gamesession.config.GameSessionJwtReadinessProbeOwnerWorkloadGuard; +import net.firedevops.firemud.gamesession.config.GameSessionJwtReadinessProbeOwnerWorkloadGuard.AuthenticatedCaller; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessLocalIdentityProvider.LocalObservation; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverProtoMapper.OwnerEvidence; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverProtoMapper.ParsedRequest; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeRequest; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeResponse; + +/** Exact Account owner-read, production verification, and immutable Pod readback sequence. */ +public final class GameSessionJwtReadinessReceiverEngine { + public static final String FULL_METHOD_NAME = + "game_session.v1.GameSessionJwtReadinessReceiverService/ReceiveReadinessProbe"; + + private final GameSessionJwtReadinessProbeOwnerWorkloadGuard workloadGuard; + private final GameSessionJwtReadinessLocalIdentityProvider localIdentityProvider; + private final GameSessionJwtReadinessProbeOwnerReadPort ownerReadPort; + private final GameSessionJwtReadinessReceiverProtoMapper protoMapper; + private final GameSessionJwtReadinessProbeCrypto crypto; + private final Clock clock; + + public GameSessionJwtReadinessReceiverEngine( + GameSessionJwtReadinessProbeOwnerWorkloadGuard workloadGuard, + GameSessionJwtReadinessLocalIdentityProvider localIdentityProvider, + GameSessionJwtReadinessProbeOwnerReadPort ownerReadPort, + GameSessionJwtReadinessReceiverProtoMapper protoMapper, + GameSessionJwtReadinessProbeCrypto crypto, + Clock clock) { + this.workloadGuard = Objects.requireNonNull(workloadGuard); + this.localIdentityProvider = Objects.requireNonNull(localIdentityProvider); + this.ownerReadPort = Objects.requireNonNull(ownerReadPort); + this.protoMapper = Objects.requireNonNull(protoMapper); + this.crypto = Objects.requireNonNull(crypto); + this.clock = Objects.requireNonNull(clock); + } + + public ReceiveReadinessProbeResponse receiveReadinessProbe(ReceiveReadinessProbeRequest request) { + AuthenticatedCaller caller = workloadGuard.requireAccountReceiverCaller(FULL_METHOD_NAME); + ParsedRequest parsed = protoMapper.parse(request); + + // The compact token is hashed but not decoded or verified until the exact Account owner read. + LocalObservation localBefore = observeLocalIdentity(caller.peer().namespace()); + ReadinessReceiverLocalIdentity protectedIdentity = localBefore.wireIdentity(); + var ownerRequest = protoMapper.ownerReadRequest(parsed, protectedIdentity); + GetCurrentReadinessProbeOwnerResponse ownerResponseBefore = + ownerReadPort.readCurrent(ownerRequest); + OwnerEvidence ownerBefore = + protoMapper.requireCurrentOwner(parsed, protectedIdentity, ownerResponseBefore); + + GameSessionJwtReadinessProbeCrypto.VerifiedProbe verified = crypto.verify(parsed); + ReceiveReadinessProbeResponse.ObservationOutcome expectedObservation = + parsed.expectedOutcome() + == net.firedevops.firemud.account.v1.ReadinessProbeCoordinates.ExpectedOutcome + .ACCEPT + ? ReceiveReadinessProbeResponse.ObservationOutcome.VERIFIED + : ReceiveReadinessProbeResponse.ObservationOutcome.INAPPLICABLE_REJECT; + if (verified.outcome() != expectedObservation) { + throw new AccountAsymmetricJwtVerifier.VerificationException(); + } + + LocalObservation localAfter = observeLocalIdentity(caller.peer().namespace()); + GetCurrentReadinessProbeOwnerResponse ownerResponseAfter = + ownerReadPort.readCurrent(ownerRequest); + OwnerEvidence ownerAfter = + protoMapper.requireCurrentOwner(parsed, localAfter.wireIdentity(), ownerResponseAfter); + if (!localBefore.equals(localAfter) + || !ownerResponseBefore.equals(ownerResponseAfter) + || !ownerBefore.equals(ownerAfter)) { + throw new OwnerReadbackChangedException(); + } + workloadGuard.requireUnchanged(caller, FULL_METHOD_NAME); + + long observedAt = nowEpochSecond(); + return protoMapper.response( + parsed, + verified.keyId(), + localAfter.wireIdentity(), + ownerAfter, + observedAt, + verified.outcome()); + } + + private LocalObservation observeLocalIdentity(String authenticatedNamespace) { + try { + LocalObservation observation = Objects.requireNonNull(localIdentityProvider.observe()); + ReadinessReceiverLocalIdentity identity = observation.wireIdentity(); + if (!GameSessionJwtReadinessReceiverProtoMapper.GAME_SESSION_VALIDATOR.equals( + identity.getValidatorId()) + || !identity.getAccountJwksSourceIdentity().getNamespace().equals(authenticatedNamespace) + || !identity + .getCanonicalServiceUri() + .equals( + "spiffe://firemud/ns/" + + identity.getAccountJwksSourceIdentity().getNamespace() + + "/sa/game-session-service")) { + throw new IllegalStateException(); + } + return observation; + } catch (RuntimeException unavailable) { + throw new LocalIdentityUnavailableException(); + } + } + + private long nowEpochSecond() { + long now = clock.instant().getEpochSecond(); + return now > 0L ? now : throwUnavailable(); + } + + private static long throwUnavailable() { + throw new LocalIdentityUnavailableException(); + } + + public static final class OwnerReadbackChangedException extends RuntimeException { + public OwnerReadbackChangedException() { + super("Current readiness owner evidence changed during verification"); + } + } + + public static final class LocalIdentityUnavailableException extends RuntimeException { + public LocalIdentityUnavailableException() { + super("Protected Game Session readiness identity is unavailable"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapper.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapper.java new file mode 100644 index 0000000000..89323051d6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapper.java @@ -0,0 +1,342 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.AccountPodTargetBinding; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeRequest; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeResponse; + +/** + * Closed-wire parser and exact Account owner evidence matcher for the GS Pod readiness receiver. + */ +public final class GameSessionJwtReadinessReceiverProtoMapper { + public static final int SCHEMA_VERSION = 1; + public static final int CURRENT_PLAN_VERSION = 2; + public static final int CURRENT_REGISTRY_VERSION = 1; + public static final int MAX_COMPACT_JWT_BYTES = 16 * 1024; + public static final int MAX_PROBE_LIFETIME_SECONDS = 300; + public static final String CANARY_PROFILE = "account-jwt-readiness-canary"; + public static final String CANARY_AUDIENCE = "firemud-account-jwt-readiness"; + public static final String GAME_SESSION_VALIDATOR = "game-session-service"; + + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern PROFILE = Pattern.compile("[a-z][a-z0-9-]{0,62}"); + private static final java.util.Map REPRESENTATIVE_AUDIENCES = + java.util.Map.of( + "control-ui", "control-ui", + "player-bootstrap", "player-bootstrap", + "game-session-account-delegation", "account-service"); + + public ParsedRequest parse(ReceiveReadinessProbeRequest request) { + if (request == null + || request.getSchemaVersion() != SCHEMA_VERSION + || !request.getUnknownFields().asMap().isEmpty() + || !request.hasCoordinates() + || request.getCompactJwt().isEmpty() + || request.getCompactJwt().length() > MAX_COMPACT_JWT_BYTES + || !isAscii(request.getCompactJwt())) { + throw new InvalidReceiverRequestException(); + } + ReadinessProbeCoordinates coordinates = request.getCoordinates(); + if (!coordinates.getUnknownFields().asMap().isEmpty()) { + throw new InvalidReceiverRequestException(); + } + try { + ProbeKind probeKind = + switch (coordinates.getProbeKind()) { + case CANARY -> ProbeKind.CANARY; + case REPRESENTATIVE -> ProbeKind.REPRESENTATIVE; + case PROBE_KIND_UNSPECIFIED, UNRECOGNIZED -> throw new IllegalArgumentException(); + }; + ReadinessProbeCoordinates.ExpectedOutcome expectedOutcome = coordinates.getExpectedOutcome(); + if (!GAME_SESSION_VALIDATOR.equals(coordinates.getValidatorId())) { + throw new IllegalArgumentException(); + } + if (probeKind == ProbeKind.CANARY) { + if (!CANARY_PROFILE.equals(coordinates.getTokenProfile()) + || !CANARY_AUDIENCE.equals(coordinates.getAudience()) + || expectedOutcome != ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) { + throw new IllegalArgumentException(); + } + } else { + String audience = REPRESENTATIVE_AUDIENCES.get(coordinates.getTokenProfile()); + ReadinessProbeCoordinates.ExpectedOutcome outcome = + "game-session-account-delegation".equals(coordinates.getTokenProfile()) + ? ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT + : ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT; + if (audience == null + || !audience.equals(coordinates.getAudience()) + || expectedOutcome != outcome) { + throw new IllegalArgumentException(); + } + } + UUID operationId = canonicalUuid(coordinates.getRotationOperationId()); + UUID jti = canonicalUuid(coordinates.getJti()); + Optional expectedActive = parseActiveFence(coordinates); + requireCoordinates(coordinates); + byte[] compactBytes = request.getCompactJwt().getBytes(StandardCharsets.US_ASCII); + try { + return new ParsedRequest( + coordinates, + operationId, + jti, + probeKind, + expectedActive, + expectedOutcome, + request.getCompactJwt(), + sha256(compactBytes)); + } finally { + java.util.Arrays.fill(compactBytes, (byte) 0); + } + } catch (RuntimeException invalid) { + if (invalid instanceof InvalidReceiverRequestException receiverException) { + throw receiverException; + } + throw new InvalidReceiverRequestException(); + } + } + + public GetCurrentReadinessProbeOwnerRequest ownerReadRequest( + ParsedRequest request, ReadinessReceiverLocalIdentity localIdentity) { + if (localIdentity == null + || !localIdentity.getUnknownFields().asMap().isEmpty() + || !localIdentity.hasAccountJwksSourceIdentity() + || !localIdentity.getAccountJwksSourceIdentity().getUnknownFields().asMap().isEmpty()) { + throw new IdentityUnavailableException(); + } + return GetCurrentReadinessProbeOwnerRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setExpectedCoordinates(request.coordinates()) + .setCompactTokenSha256(request.compactTokenSha256()) + .setProtectedLocalIdentity(localIdentity) + .build(); + } + + public OwnerEvidence requireCurrentOwner( + ParsedRequest request, + ReadinessReceiverLocalIdentity localIdentity, + GetCurrentReadinessProbeOwnerResponse response) { + if (response == null + || response.getSchemaVersion() != SCHEMA_VERSION + || !response.getUnknownFields().asMap().isEmpty() + || !response.getOwnerRecordFound() + || !response.hasCurrentCoordinates() + || !response.hasCurrentPodTarget() + || response.getCurrentState() != GetCurrentReadinessProbeOwnerResponse.ProbeState.ISSUED + || !response.getCurrentCoordinates().getUnknownFields().asMap().isEmpty() + || !response.hasCurrentPodTarget() + || !response.getCurrentPodTarget().getUnknownFields().asMap().isEmpty() + || !request.coordinates().equals(response.getCurrentCoordinates()) + || !request.compactTokenSha256().equals(response.getCompactTokenSha256()) + || !DIGEST.matcher(response.getCompactTokenSha256()).matches()) { + throw new OwnerEvidenceUnavailableException(); + } + AccountPodTargetBinding target = response.getCurrentPodTarget(); + if (!GAME_SESSION_VALIDATOR.equals(target.getValidatorId()) + || !localIdentity.getValidatorId().equals(target.getValidatorId()) + || !localIdentity.getDeploymentUid().equals(target.getDeploymentUid()) + || !localIdentity.getPodUid().equals(target.getPodUid()) + || !localIdentity.getPodIp().equals(target.getPodIp()) + || !localIdentity.getDirectPodEndpoint().equals(target.getDirectPodEndpoint()) + || !localIdentity.getCanonicalServiceUri().equals(target.getCanonicalServiceUri()) + || !localIdentity.getImage().equals(target.getImage()) + || !localIdentity.getVerifierConfigSha256().equals(target.getVerifierConfigSha256()) + || !localIdentity + .getApplicabilityMatrixDigest() + .equals(target.getApplicabilityMatrixDigest()) + || !localIdentity.getServerLeafSpkiSha256().equals(target.getServerLeafSpkiSha256()) + || target.getExpectedOutcome() != request.expectedOutcome() + || !sourceIdentityMatchesTarget(localIdentity, target) + || !DIGEST.matcher(target.getInventorySnapshotDigest()).matches() + || !DIGEST.matcher(target.getApiBindingDigest()).matches() + || !DIGEST.matcher(target.getInventoryBindingDigest()).matches()) { + throw new OwnerEvidenceUnavailableException(); + } + return new OwnerEvidence(response, target); + } + + public ReceiveReadinessProbeResponse response( + ParsedRequest request, + String verifiedKeyId, + ReadinessReceiverLocalIdentity localIdentity, + OwnerEvidence owner, + long observedAtEpochSeconds, + ReceiveReadinessProbeResponse.ObservationOutcome outcome) { + if (!KID.matcher(verifiedKeyId).matches() + || !verifiedKeyId.equals(request.coordinates().getTargetKid()) + || observedAtEpochSeconds < request.coordinates().getIssuedAtEpochSeconds() + || observedAtEpochSeconds >= request.coordinates().getExpiresAtEpochSeconds() + || observedAtEpochSeconds >= request.coordinates().getPlanExpiresAtEpochSeconds()) { + throw new OwnerEvidenceUnavailableException(); + } + return ReceiveReadinessProbeResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setCoordinates(request.coordinates()) + .setCompactTokenSha256(request.compactTokenSha256()) + .setVerifiedKeyId(verifiedKeyId) + .setReceiverIdentity(localIdentity) + .setAccountPodTarget(owner.target()) + .setObservedAtEpochSeconds(observedAtEpochSeconds) + .setOutcome(outcome) + .build(); + } + + private static Optional parseActiveFence(ReadinessProbeCoordinates coordinates) { + return switch (coordinates.getExpectedActiveState()) { + case ABSENT -> { + if (!coordinates.getExpectedActiveGeneration().isEmpty() + || !coordinates.getExpectedActiveKid().isEmpty()) { + throw new IllegalArgumentException(); + } + yield Optional.empty(); + } + case PRESENT -> { + if (!GENERATION.matcher(coordinates.getExpectedActiveGeneration()).matches() + || !KID.matcher(coordinates.getExpectedActiveKid()).matches()) { + throw new IllegalArgumentException(); + } + yield Optional.of( + new ActiveFence( + coordinates.getExpectedActiveGeneration(), coordinates.getExpectedActiveKid())); + } + case EXPECTED_ACTIVE_STATE_UNSPECIFIED, UNKNOWN, UNRECOGNIZED -> + throw new IllegalArgumentException(); + }; + } + + private static void requireCoordinates(ReadinessProbeCoordinates value) { + if (!DIGEST.matcher(value.getOperationDigest()).matches() + || !DIGEST.matcher(value.getPlanDigest()).matches() + || value.getPlanVersion() != CURRENT_PLAN_VERSION + || value.getRegistryVersion() != CURRENT_REGISTRY_VERSION + || value.getEntryVersion() <= 0L + || !GENERATION.matcher(value.getTargetGeneration()).matches() + || !KID.matcher(value.getTargetKid()).matches() + || !PROFILE.matcher(value.getTokenProfile()).matches() + || !PROFILE.matcher(value.getAudience()).matches() + || value.getIssuedAtEpochSeconds() <= 0L + || value.getExpiresAtEpochSeconds() <= value.getIssuedAtEpochSeconds() + || value.getExpiresAtEpochSeconds() - value.getIssuedAtEpochSeconds() + > MAX_PROBE_LIFETIME_SECONDS + || value.getPlanExpiresAtEpochSeconds() < value.getExpiresAtEpochSeconds()) { + throw new IllegalArgumentException(); + } + } + + private static UUID canonicalUuid(String value) { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.version() != 4 || parsed.variant() != 2) { + throw new IllegalArgumentException(); + } + return parsed; + } + + private static boolean sourceIdentityMatchesTarget( + ReadinessReceiverLocalIdentity local, AccountPodTargetBinding target) { + var source = local.getAccountJwksSourceIdentity(); + return source.getEnvironmentId().equals(target.getEnvironmentId()) + && source.getClusterId().equals(target.getClusterId()) + && source.getClusterIncarnationUid().equals(target.getClusterIncarnationUid()) + && source.getNamespace().equals(target.getNamespace()) + && source.getNamespaceUid().equals(target.getNamespaceUid()); + } + + private static boolean isAscii(String value) { + for (int index = 0; index < value.length(); index++) { + if (value.charAt(index) > 0x7f) { + return false; + } + } + return true; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception unavailable) { + throw new InvalidReceiverRequestException(); + } + } + + public enum ProbeKind { + CANARY, + REPRESENTATIVE + } + + public record ActiveFence(String generation, String keyId) {} + + public record ParsedRequest( + ReadinessProbeCoordinates coordinates, + UUID operationId, + UUID jti, + ProbeKind probeKind, + Optional expectedActive, + ReadinessProbeCoordinates.ExpectedOutcome expectedOutcome, + String compactJwt, + String compactTokenSha256) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "ReadinessProbeCoordinates is an immutable generated protobuf value.") + public ParsedRequest {} + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "ReadinessProbeCoordinates is an immutable generated protobuf value.") + public ReadinessProbeCoordinates coordinates() { + return coordinates; + } + } + + public record OwnerEvidence( + GetCurrentReadinessProbeOwnerResponse response, AccountPodTargetBinding target) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "GetCurrentReadinessProbeOwnerResponse and AccountPodTargetBinding are immutable generated protobuf values.") + public OwnerEvidence {} + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "GetCurrentReadinessProbeOwnerResponse is an immutable generated protobuf value.") + public GetCurrentReadinessProbeOwnerResponse response() { + return response; + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "AccountPodTargetBinding is an immutable generated protobuf value.") + public AccountPodTargetBinding target() { + return target; + } + } + + public static final class InvalidReceiverRequestException extends IllegalArgumentException { + public InvalidReceiverRequestException() { + super("Game Session readiness receiver request is invalid"); + } + } + + public static final class IdentityUnavailableException extends RuntimeException { + public IdentityUnavailableException() { + super("Protected Game Session receiver identity is unavailable"); + } + } + + public static final class OwnerEvidenceUnavailableException extends RuntimeException { + public OwnerEvidenceUnavailableException() { + super("Current Account readiness owner evidence is unavailable"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverGrpcService.java new file mode 100644 index 0000000000..de63c35fea --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverGrpcService.java @@ -0,0 +1,64 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.gamesession.config.GameSessionJwtReadinessProbeOwnerWorkloadGuard; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverEngine; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverProtoMapper; +import net.firedevops.firemud.gamesession.v1.GameSessionJwtReadinessReceiverServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeRequest; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeResponse; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Lazy; +import org.springframework.grpc.server.service.GrpcService; + +/** Default-inactive, non-authorizing receiver for one exact Game Session Pod. */ +@GrpcService +@Lazy +@ConditionalOnProperty( + prefix = "firemud.game-session.jwt-readiness.receiver", + name = "enabled", + havingValue = "true") +@ConditionalOnBean(GameSessionJwtReadinessReceiverEngine.class) +public final class GameSessionJwtReadinessReceiverGrpcService + extends GameSessionJwtReadinessReceiverServiceGrpc + .GameSessionJwtReadinessReceiverServiceImplBase { + private static final String UNAVAILABLE = "Game Session readiness receiver is unavailable"; + + private final GameSessionJwtReadinessReceiverEngine receiver; + + public GameSessionJwtReadinessReceiverGrpcService( + GameSessionJwtReadinessReceiverEngine receiver) { + this.receiver = receiver; + } + + @Override + public void receiveReadinessProbe( + ReceiveReadinessProbeRequest request, + StreamObserver responseObserver) { + try { + responseObserver.onNext(receiver.receiveReadinessProbe(request)); + responseObserver.onCompleted(); + } catch (GameSessionJwtReadinessProbeOwnerWorkloadGuard.ReceiverCallerDeniedException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Authorized Account workload is required") + .asRuntimeException()); + } catch (GameSessionJwtReadinessReceiverProtoMapper.InvalidReceiverRequestException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Game Session readiness request is invalid") + .asRuntimeException()); + } catch (AccountAsymmetricJwtVerifier.VerificationException rejected) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Current Account readiness probe was not verified") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE.withDescription(UNAVAILABLE).asRuntimeException()); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessProbeOwnerWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessProbeOwnerWorkloadGuardTest.java new file mode 100644 index 0000000000..1d1482495f --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessProbeOwnerWorkloadGuardTest.java @@ -0,0 +1,86 @@ +package net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class GameSessionJwtReadinessProbeOwnerWorkloadGuardTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String METHOD = + "game_session.v1.GameSessionJwtReadinessReceiverService/ReceiveReadinessProbe"; + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void acceptsOnlyExactSameNamespaceAccountPeerForDedicatedMethod() { + var guard = new GameSessionJwtReadinessProbeOwnerWorkloadGuard(NAMESPACE); + + assertDenied(() -> guard.requireAccountReceiverCaller(METHOD)); + withPeer( + peer("other", "account-service"), + () -> assertDenied(() -> guard.requireAccountReceiverCaller(METHOD))); + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> assertDenied(() -> guard.requireAccountReceiverCaller(METHOD))); + withPeer( + peer(NAMESPACE, "account-service"), + () -> assertDenied(() -> guard.requireAccountReceiverCaller(METHOD + "Extra"))); + + withPeer( + peer(NAMESPACE, "account-service"), + () -> { + var caller = guard.requireAccountReceiverCaller(METHOD); + assertThat(caller.peer().uri()) + .isEqualTo("spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service"); + guard.requireUnchanged(caller, METHOD); + }); + } + + @Test + void rejectsApplicationSessionContextAndCallerDrift() { + var guard = new GameSessionJwtReadinessProbeOwnerWorkloadGuard(NAMESPACE); + withPeer( + peer(NAMESPACE, "account-service"), + () -> { + var caller = guard.requireAccountReceiverCaller(METHOD); + SessionContext.setContext("user-1", java.util.List.of(), java.util.Map.of()); + assertDenied(() -> guard.requireUnchanged(caller, METHOD)); + SessionContext.clear(); + }); + + var otherGuard = new GameSessionJwtReadinessProbeOwnerWorkloadGuard("other"); + withPeer( + peer(NAMESPACE, "account-service"), + () -> assertDenied(() -> otherGuard.requireAccountReceiverCaller(METHOD))); + } + + private static void assertDenied(Runnable invocation) { + assertThatThrownBy(invocation::run) + .isInstanceOf( + GameSessionJwtReadinessProbeOwnerWorkloadGuard.ReceiverCallerDeniedException.class); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.ROOT.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + SessionContext.clear(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java new file mode 100644 index 0000000000..a225218cc5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessLocalIdentityProvider; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverEngine; +import net.firedevops.firemud.gamesession.service.impl.GameSessionJwtReadinessReceiverGrpcService; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class GameSessionJwtReadinessReceiverConfigurationTest { + private static final String ENABLED = "firemud.game-session.jwt-readiness.receiver.enabled=true"; + + private final ApplicationContextRunner contextRunner = + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionJwtReadinessReceiverConfiguration.class, + GameSessionJwtReadinessReceiverGrpcService.class); + + @Test + void receiverAndCryptoCompositionRemainAbsentByDefault() { + contextRunner.run( + context -> { + assertThat(context) + .doesNotHaveBean(GameSessionJwtReadinessReceiverEngine.class) + .doesNotHaveBean(GameSessionJwtReadinessLocalIdentityProvider.class) + .doesNotHaveBean(GameSessionJwtReadinessReceiverGrpcService.class); + }); + } + + @Test + void explicitEnablementWithoutProtectedLocalIdentityStillLeavesReceiverUnregistered() { + contextRunner + .withPropertyValues(ENABLED) + .run( + context -> { + assertThat(context) + .doesNotHaveBean(GameSessionJwtReadinessReceiverEngine.class) + .doesNotHaveBean(GameSessionJwtReadinessLocalIdentityProvider.class) + .doesNotHaveBean(GameSessionJwtReadinessReceiverGrpcService.class); + }); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeCryptoTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeCryptoTest.java new file mode 100644 index 0000000000..11180e1178 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeCryptoTest.java @@ -0,0 +1,284 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.RSAKeyGenParameterSpec; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeResponse; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class GameSessionJwtReadinessProbeCryptoTest { + private static final Instant NOW = Instant.parse("2030-06-01T00:10:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneId.of("UTC")); + private static final String KID = "pending-key-7"; + private static final String RESERVED_SUBJECT = "00000000-0000-4000-8000-000000000001"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private KeyPair signingKey; + private GameSessionJwtReadinessProbeCrypto crypto; + private final GameSessionJwtReadinessReceiverProtoMapper mapper = + new GameSessionJwtReadinessReceiverProtoMapper(); + + @BeforeEach + void setUp() throws Exception { + signingKey = rsa3072(); + AccountPublicJwksCache.SourceIdentity source = sourceIdentity(); + String jwks = jwks(KID, (RSAPublicKey) signingKey.getPublic()); + AccountPublicJwksCache cache = + new AccountPublicJwksCache( + () -> + new AccountPublicJwksCache.PublicJwksSnapshot( + source, jwks.getBytes(StandardCharsets.US_ASCII)), + source, + CLOCK, + Duration.ofSeconds(300)); + crypto = + new GameSessionJwtReadinessProbeCrypto(new AccountAsymmetricJwtVerifier(cache, CLOCK), 8); + } + + @Test + void verifiesRealProductionDelegationAndCanaryTokensAsNonAuthorizingProofs() throws Exception { + for (String profile : + List.of( + GameSessionAccountDelegationProfile.PROFILE, + GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE)) { + ReadinessProbeCoordinates.ExpectedOutcome expected = + ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT; + UUID jti = UUID.randomUUID(); + var parsed = mapper.parse(request(profile, expected, signedToken(profile, jti), jti).build()); + + var verified = crypto.verify(parsed); + + assertThat(verified.keyId()).isEqualTo(KID); + assertThat(verified.outcome()) + .isEqualTo(ReceiveReadinessProbeResponse.ObservationOutcome.VERIFIED); + } + } + + @Test + void verifiesValidInapplicableProductionProfilesButReturnsOnlyInapplicableReject() + throws Exception { + for (String profile : + List.of(ControlUiJwtProfileValidator.PROFILE, PlayerBootstrapJwtProfileValidator.PROFILE)) { + UUID jti = UUID.randomUUID(); + var parsed = + mapper.parse( + request( + profile, + ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT, + signedToken(profile, jti), + jti) + .build()); + + var verified = crypto.verify(parsed); + + assertThat(verified.outcome()) + .isEqualTo(ReceiveReadinessProbeResponse.ObservationOutcome.INAPPLICABLE_REJECT); + } + } + + @Test + void rejectsSignatureOrExpectedOutcomeMismatch() throws Exception { + UUID jti = UUID.randomUUID(); + String valid = signedToken(GameSessionAccountDelegationProfile.PROFILE, jti); + String[] parts = valid.split("\\.", -1); + byte[] signature = Base64.getUrlDecoder().decode(parts[2]); + signature[0] ^= 1; + String tampered = parts[0] + "." + parts[1] + "." + encode(signature); + var tamperedProbe = + mapper.parse( + request( + GameSessionAccountDelegationProfile.PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT, + tampered, + jti) + .build()); + assertThatThrownBy(() -> crypto.verify(tamperedProbe)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + + var mismatchedProbe = + mapper.parse( + request( + GameSessionAccountDelegationProfile.PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT, + valid, + jti) + .build()); + var alteredExpectation = + new GameSessionJwtReadinessReceiverProtoMapper.ParsedRequest( + mismatchedProbe.coordinates(), + mismatchedProbe.operationId(), + mismatchedProbe.jti(), + mismatchedProbe.probeKind(), + mismatchedProbe.expectedActive(), + ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT, + mismatchedProbe.compactJwt(), + mismatchedProbe.compactTokenSha256()); + assertThatThrownBy(() -> crypto.verify(alteredExpectation)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + } + + private static net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeRequest.Builder request( + String profile, ReadinessProbeCoordinates.ExpectedOutcome outcome, String token, UUID jti) { + boolean canary = GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE.equals(profile); + String audience = + switch (profile) { + case GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE -> + GameSessionJwtReadinessReceiverProtoMapper.CANARY_AUDIENCE; + case ControlUiJwtProfileValidator.PROFILE -> ControlUiJwtProfileValidator.AUDIENCE; + case PlayerBootstrapJwtProfileValidator.PROFILE -> + PlayerBootstrapJwtProfileValidator.AUDIENCE; + default -> GameSessionAccountDelegationProfile.AUDIENCE; + }; + long issuedAt = NOW.getEpochSecond() - 1L; + ReadinessProbeCoordinates coordinates = + ReadinessProbeCoordinates.newBuilder() + .setRotationOperationId(UUID.randomUUID().toString()) + .setOperationDigest("a".repeat(64)) + .setPlanDigest("b".repeat(64)) + .setPlanVersion(2) + .setRegistryVersion(1) + .setValidatorId(GameSessionJwtReadinessReceiverProtoMapper.GAME_SESSION_VALIDATOR) + .setTokenProfile(profile) + .setAudience(audience) + .setProbeKind( + canary + ? ReadinessProbeCoordinates.ProbeKind.CANARY + : ReadinessProbeCoordinates.ProbeKind.REPRESENTATIVE) + .setExpectedOutcome(outcome) + .setJti(jti.toString()) + .setEntryVersion(1) + .setTargetGeneration("7") + .setTargetKid(KID) + .setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.ABSENT) + .setIssuedAtEpochSeconds(issuedAt) + .setExpiresAtEpochSeconds(issuedAt + 120L) + .setPlanExpiresAtEpochSeconds(issuedAt + 180L) + .build(); + return net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeRequest.newBuilder() + .setSchemaVersion(1) + .setCoordinates(coordinates) + .setCompactJwt(token); + } + + private String signedToken(String profile, UUID jti) throws Exception { + boolean canary = GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE.equals(profile); + String audience = + switch (profile) { + case GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE -> + GameSessionJwtReadinessReceiverProtoMapper.CANARY_AUDIENCE; + case ControlUiJwtProfileValidator.PROFILE -> ControlUiJwtProfileValidator.AUDIENCE; + case PlayerBootstrapJwtProfileValidator.PROFILE -> + PlayerBootstrapJwtProfileValidator.AUDIENCE; + default -> GameSessionAccountDelegationProfile.AUDIENCE; + }; + long issuedAt = NOW.getEpochSecond() - 1L; + long expiresAt = issuedAt + 120L; + Map header = Map.of("alg", "RS256", "kid", KID, "typ", "JWT"); + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("sub", RESERVED_SUBJECT); + claims.put("jti", jti.toString()); + claims.put("aud", audience); + claims.put("iat", issuedAt); + claims.put("nbf", issuedAt); + claims.put("exp", expiresAt); + if (canary) { + claims.put("tokenProfile", profile); + claims.put("tokenType", "account_jwt_readiness_canary"); + } else { + if (ControlUiJwtProfileValidator.PROFILE.equals(profile) + || PlayerBootstrapJwtProfileValidator.PROFILE.equals(profile)) { + claims.put("scopedRoles", Map.of()); + } + claims.put("accountId", RESERVED_SUBJECT); + boolean decimalCounters = GameSessionAccountDelegationProfile.PROFILE.equals(profile); + Object initial = decimalCounters ? "1" : 1L; + claims.put("tokenGeneration", initial); + claims.put("authorityTuple", authorityTuple(initial)); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", initial); + } + String signingInput = + encode(JSON.writeValueAsBytes(header)) + + "." + + encode(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(claims))); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(signingKey.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return signingInput + "." + encode(signature.sign()); + } + + private static Map authorityTuple(Object generation) { + return Map.of( + "issuerAuthGeneration", generation, + "accountAuthorityGeneration", generation, + "tenantAuthorityGeneration", Map.of(), + "membershipAuthorityGeneration", Map.of(), + "privateRealmGrantVersions", List.of()); + } + + private static AccountPublicJwksCache.SourceIdentity sourceIdentity() { + return new AccountPublicJwksCache.SourceIdentity( + "prod", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "55555555-5555-4555-8555-555555555555", + "account-api-r1", + "https://kubernetes.example.test:6443", + "9".repeat(64)); + } + + private static String jwks(String kid, RSAPublicKey key) { + return "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"" + + kid + + "\",\"use\":\"sig\",\"alg\":\"RS256\",\"n\":\"" + + encode(unsigned(key.getModulus())) + + "\",\"e\":\"" + + encode(unsigned(key.getPublicExponent())) + + "\"}]}"; + } + + private static KeyPair rsa3072() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(new RSAKeyGenParameterSpec(3_072, RSAKeyGenParameterSpec.F4)); + return generator.generateKeyPair(); + } + + private static byte[] unsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + return bytes.length > 1 && bytes[0] == 0 + ? java.util.Arrays.copyOfRange(bytes, 1, bytes.length) + : bytes; + } + + private static String encode(byte[] value) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngineTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngineTest.java new file mode 100644 index 0000000000..15e24471b4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngineTest.java @@ -0,0 +1,292 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountPodTargetBinding; +import net.firedevops.firemud.account.v1.AccountSourceIdentity; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.config.GameSessionJwtReadinessProbeOwnerWorkloadGuard; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessLocalIdentityProvider.LocalObservation; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeRequest; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; + +class GameSessionJwtReadinessReceiverEngineTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String METHOD = GameSessionJwtReadinessReceiverEngine.FULL_METHOD_NAME; + private static final String KID = "pending-key-7"; + private static final Instant NOW = Instant.parse("2030-06-01T00:10:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneId.of("UTC")); + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void ownerReadsBracketRealBoundaryAndReturnOnlyNonAuthorizingReceipt() { + Fixture fixture = new Fixture(); + fixture.stubVerifiedOutcome(ReceiveReadinessProbeResponse.ObservationOutcome.VERIFIED); + + ReceiveReadinessProbeResponse response = + withAccountPeer(() -> fixture.engine.receiveReadinessProbe(fixture.request)); + + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getCoordinates()).isEqualTo(fixture.request.getCoordinates()); + assertThat(response.getCompactTokenSha256()).matches("[0-9a-f]{64}"); + assertThat(response.getVerifiedKeyId()).isEqualTo(KID); + assertThat(response.getReceiverIdentity()).isEqualTo(fixture.local.wireIdentity()); + assertThat(response.getAccountPodTarget()).isEqualTo(fixture.target); + assertThat(response.getObservedAtEpochSeconds()).isEqualTo(NOW.getEpochSecond()); + assertThat(response.getOutcome()) + .isEqualTo(ReceiveReadinessProbeResponse.ObservationOutcome.VERIFIED); + assertThat(SessionContext.getAccountId()).isNull(); + assertThat(SessionContext.getGlobalRoles()).isEmpty(); + + ArgumentCaptor ownerRequest = + ArgumentCaptor.forClass(GetCurrentReadinessProbeOwnerRequest.class); + InOrder order = inOrder(fixture.localIdentityProvider, fixture.ownerReadPort, fixture.crypto); + order.verify(fixture.localIdentityProvider).observe(); + order.verify(fixture.ownerReadPort).readCurrent(ownerRequest.capture()); + order.verify(fixture.crypto).verify(any()); + order.verify(fixture.localIdentityProvider).observe(); + order.verify(fixture.ownerReadPort).readCurrent(ownerRequest.capture()); + verify(fixture.localIdentityProvider, times(2)).observe(); + verify(fixture.ownerReadPort, times(2)).readCurrent(any()); + assertThat(ownerRequest.getAllValues()).hasSize(2); + for (GetCurrentReadinessProbeOwnerRequest captured : ownerRequest.getAllValues()) { + assertThat(captured.getExpectedCoordinates()).isEqualTo(fixture.request.getCoordinates()); + assertThat(captured.getCompactTokenSha256()).isEqualTo(response.getCompactTokenSha256()); + assertThat(captured.getProtectedLocalIdentity()).isEqualTo(fixture.local.wireIdentity()); + assertThat(captured.getUnknownFields().asMap()).isEmpty(); + } + verifyNoMoreInteractions(fixture.localIdentityProvider, fixture.ownerReadPort, fixture.crypto); + } + + @Test + void cryptographicOutcomeMismatchDeniesWithoutSecondOwnerReadOrReceipt() { + Fixture fixture = new Fixture(); + fixture.stubVerifiedOutcome( + ReceiveReadinessProbeResponse.ObservationOutcome.INAPPLICABLE_REJECT); + + assertThatThrownBy( + () -> withAccountPeer(() -> fixture.engine.receiveReadinessProbe(fixture.request))) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + + verify(fixture.ownerReadPort, times(1)).readCurrent(any()); + verify(fixture.localIdentityProvider, times(1)).observe(); + verify(fixture.crypto).verify(any()); + verifyNoMoreInteractions(fixture.localIdentityProvider, fixture.ownerReadPort, fixture.crypto); + } + + @Test + void staleCurrentOwnerReadbackDeniesAfterCrypto() { + Fixture fixture = new Fixture(); + fixture.stubVerifiedOutcome(ReceiveReadinessProbeResponse.ObservationOutcome.VERIFIED); + AccountPodTargetBinding changedTarget = + fixture.target.toBuilder().setPodIp("10.0.0.99").build(); + when(fixture.ownerReadPort.readCurrent(any())) + .thenReturn( + fixture.ownerResponse, + fixture.ownerResponse.toBuilder().setCurrentPodTarget(changedTarget).build()); + + assertThatThrownBy( + () -> withAccountPeer(() -> fixture.engine.receiveReadinessProbe(fixture.request))) + .isInstanceOf( + GameSessionJwtReadinessReceiverProtoMapper.OwnerEvidenceUnavailableException.class); + + verify(fixture.ownerReadPort, times(2)).readCurrent(any()); + verify(fixture.localIdentityProvider, times(2)).observe(); + verify(fixture.crypto).verify(any()); + verifyNoMoreInteractions(fixture.localIdentityProvider, fixture.ownerReadPort, fixture.crypto); + } + + private static T withAccountPeer(java.util.concurrent.Callable action) { + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", + NAMESPACE, + "account-service"); + Context context = Context.ROOT.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.call(); + } catch (RuntimeException failure) { + throw failure; + } catch (Exception failure) { + throw new AssertionError(failure); + } finally { + context.detach(previous); + SessionContext.clear(); + } + } + + private static final class Fixture { + private final UUID operationId = UUID.randomUUID(); + private final UUID jti = UUID.randomUUID(); + private final GameSessionJwtReadinessLocalIdentityProvider localIdentityProvider = + mock(GameSessionJwtReadinessLocalIdentityProvider.class); + private final GameSessionJwtReadinessProbeOwnerReadPort ownerReadPort = + mock(GameSessionJwtReadinessProbeOwnerReadPort.class); + private final GameSessionJwtReadinessProbeCrypto crypto = + mock(GameSessionJwtReadinessProbeCrypto.class); + private final GameSessionJwtReadinessReceiverProtoMapper mapper = + new GameSessionJwtReadinessReceiverProtoMapper(); + private final AccountPublicJwksCache.SourceIdentity sourceIdentity = sourceIdentity(); + private final LocalObservation local = new LocalObservation(wireIdentity(), sourceIdentity); + private final ReadinessProbeCoordinates coordinates = coordinates(); + private final ReceiveReadinessProbeRequest request = + ReceiveReadinessProbeRequest.newBuilder() + .setSchemaVersion(1) + .setCoordinates(coordinates) + .setCompactJwt("header.payload.signature") + .build(); + private final AccountPodTargetBinding target = target(); + private final GetCurrentReadinessProbeOwnerResponse ownerResponse = ownerResponse(); + private final GameSessionJwtReadinessReceiverEngine engine = + new GameSessionJwtReadinessReceiverEngine( + new GameSessionJwtReadinessProbeOwnerWorkloadGuard(NAMESPACE), + localIdentityProvider, + ownerReadPort, + mapper, + crypto, + CLOCK); + + private Fixture() { + when(localIdentityProvider.observe()).thenReturn(local); + when(ownerReadPort.readCurrent(any())).thenReturn(ownerResponse); + } + + private void stubVerifiedOutcome(ReceiveReadinessProbeResponse.ObservationOutcome outcome) { + when(crypto.verify(any())) + .thenReturn(new GameSessionJwtReadinessProbeCrypto.VerifiedProbe(KID, outcome)); + } + + private ReadinessProbeCoordinates coordinates() { + long issuedAt = NOW.getEpochSecond() - 1L; + return ReadinessProbeCoordinates.newBuilder() + .setRotationOperationId(operationId.toString()) + .setOperationDigest("a".repeat(64)) + .setPlanDigest("b".repeat(64)) + .setPlanVersion(2) + .setRegistryVersion(1) + .setValidatorId(GameSessionJwtReadinessReceiverProtoMapper.GAME_SESSION_VALIDATOR) + .setTokenProfile("game-session-account-delegation") + .setAudience("account-service") + .setProbeKind(ReadinessProbeCoordinates.ProbeKind.REPRESENTATIVE) + .setExpectedOutcome(ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setJti(jti.toString()) + .setEntryVersion(4) + .setTargetGeneration("7") + .setTargetKid(KID) + .setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.ABSENT) + .setIssuedAtEpochSeconds(issuedAt) + .setExpiresAtEpochSeconds(issuedAt + 120L) + .setPlanExpiresAtEpochSeconds(issuedAt + 180L) + .build(); + } + + private static ReadinessReceiverLocalIdentity wireIdentity() { + return ReadinessReceiverLocalIdentity.newBuilder() + .setValidatorId("game-session-service") + .setDeploymentUid("33333333-3333-4333-8333-333333333333") + .setPodUid("44444444-4444-4444-8444-444444444444") + .setPodIp("10.0.0.12") + .setDirectPodEndpoint("grpcs://10.0.0.12:6565") + .setCanonicalServiceUri("spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service") + .setImage("registry.example/game-session@sha256:" + "a".repeat(64)) + .setVerifierConfigSha256("b".repeat(64)) + .setApplicabilityMatrixDigest("c".repeat(64)) + .setSourceInventoryRevision("inventory-r1") + .setSourceInventoryDigest("d".repeat(64)) + .setServerLeafSpkiSha256("e".repeat(64)) + .setAccountJwksSourceIdentity( + AccountSourceIdentity.newBuilder() + .setEnvironmentId("prod") + .setClusterId("cluster-a") + .setClusterIncarnationUid("11111111-1111-4111-8111-111111111111") + .setNamespace(NAMESPACE) + .setNamespaceUid("22222222-2222-4222-8222-222222222222") + .setConfigMapUid("55555555-5555-4555-8555-555555555555") + .setBindingRevision("account-api-r1") + .setApiServerOrigin("https://kubernetes.example.test:6443") + .setServingCaSha256("9".repeat(64))) + .setAccountJwksTrustConfigRevision(1L) + .build(); + } + + private static AccountPublicJwksCache.SourceIdentity sourceIdentity() { + return new AccountPublicJwksCache.SourceIdentity( + "prod", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + NAMESPACE, + "22222222-2222-4222-8222-222222222222", + "55555555-5555-4555-8555-555555555555", + "account-api-r1", + "https://kubernetes.example.test:6443", + "9".repeat(64)); + } + + private AccountPodTargetBinding target() { + return AccountPodTargetBinding.newBuilder() + .setInventorySnapshotDigest("f".repeat(64)) + .setEnvironmentId("prod") + .setClusterId("cluster-a") + .setClusterIncarnationUid("11111111-1111-4111-8111-111111111111") + .setNamespace(NAMESPACE) + .setNamespaceUid("22222222-2222-4222-8222-222222222222") + .setApiBindingRevision("api-r1") + .setApiBindingDigest("8".repeat(64)) + .setInventoryBindingRevision("inventory-r1") + .setInventoryBindingDigest("d".repeat(64)) + .setValidatorId("game-session-service") + .setDeploymentUid("33333333-3333-4333-8333-333333333333") + .setPodUid("44444444-4444-4444-8444-444444444444") + .setPodIp("10.0.0.12") + .setImage("registry.example/game-session@sha256:" + "a".repeat(64)) + .setVerifierConfigSha256("b".repeat(64)) + .setApplicabilityMatrixDigest("c".repeat(64)) + .setExpectedOutcome(ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setDirectPodEndpoint("grpcs://10.0.0.12:6565") + .setCanonicalServiceUri("spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service") + .setServerLeafSpkiSha256("e".repeat(64)) + .build(); + } + + private GetCurrentReadinessProbeOwnerResponse ownerResponse() { + var parsed = new GameSessionJwtReadinessReceiverProtoMapper().parse(request); + return GetCurrentReadinessProbeOwnerResponse.newBuilder() + .setSchemaVersion(1) + .setOwnerRecordFound(true) + .setCurrentCoordinates(coordinates) + .setCompactTokenSha256(parsed.compactTokenSha256()) + .setCurrentState(GetCurrentReadinessProbeOwnerResponse.ProbeState.ISSUED) + .setCurrentPodTarget(target) + .build(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapperTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapperTest.java new file mode 100644 index 0000000000..74b194d822 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapperTest.java @@ -0,0 +1,153 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeRequest; +import org.junit.jupiter.api.Test; + +class GameSessionJwtReadinessReceiverProtoMapperTest { + private final GameSessionJwtReadinessReceiverProtoMapper mapper = + new GameSessionJwtReadinessReceiverProtoMapper(); + + @Test + void acceptsOnlyTheCanaryAndProductionProfilesWithTypedExpectedOutcomes() { + Map outcomes = + Map.of( + GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT, + "game-session-account-delegation", + ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT, + ControlUiJwtProfileValidator.PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT, + PlayerBootstrapJwtProfileValidator.PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT); + + outcomes.forEach( + (profile, expectedOutcome) -> { + var parsed = mapper.parse(request(profile, expectedOutcome).build()); + assertThat(parsed.coordinates().getExpectedOutcome()).isEqualTo(expectedOutcome); + assertThat(parsed.expectedOutcome()).isEqualTo(expectedOutcome); + assertThat(parsed.compactTokenSha256()).matches("[0-9a-f]{64}"); + }); + } + + @Test + void rejectsUnknownFieldsUnsupportedProfilesAndOutcomeMismatch() { + assertInvalid( + request( + GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setUnknownFields(unknownFields()) + .build()); + assertInvalid( + request( + ControlUiJwtProfileValidator.PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT) + .setCoordinates( + request( + ControlUiJwtProfileValidator.PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT) + .getCoordinates() + .toBuilder() + .setUnknownFields(unknownFields())) + .build()); + assertInvalid( + request( + ControlUiJwtProfileValidator.PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .build()); + assertInvalid( + request("account-login", ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT).build()); + } + + @Test + void rejectsMalformedCoordinatesAndUnboundedOrNonAsciiTokens() { + assertInvalid( + request( + GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setCoordinates( + request( + GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .getCoordinates() + .toBuilder() + .setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.UNKNOWN)) + .build()); + assertInvalid( + request( + GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setCompactJwt( + "x".repeat(GameSessionJwtReadinessReceiverProtoMapper.MAX_COMPACT_JWT_BYTES + 1)) + .build()); + assertInvalid( + request( + GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE, + ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setCompactJwt("header.payload.é") + .build()); + } + + private static void assertInvalid(ReceiveReadinessProbeRequest request) { + assertThatThrownBy(() -> new GameSessionJwtReadinessReceiverProtoMapper().parse(request)) + .isInstanceOf( + GameSessionJwtReadinessReceiverProtoMapper.InvalidReceiverRequestException.class); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static ReceiveReadinessProbeRequest.Builder request( + String profile, ReadinessProbeCoordinates.ExpectedOutcome expectedOutcome) { + boolean canary = GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE.equals(profile); + String audience = + switch (profile) { + case GameSessionJwtReadinessReceiverProtoMapper.CANARY_PROFILE -> + GameSessionJwtReadinessReceiverProtoMapper.CANARY_AUDIENCE; + case ControlUiJwtProfileValidator.PROFILE -> ControlUiJwtProfileValidator.AUDIENCE; + case PlayerBootstrapJwtProfileValidator.PROFILE -> + PlayerBootstrapJwtProfileValidator.AUDIENCE; + case "game-session-account-delegation" -> "account-service"; + default -> "account-login"; + }; + ReadinessProbeCoordinates coordinates = + ReadinessProbeCoordinates.newBuilder() + .setRotationOperationId(UUID.randomUUID().toString()) + .setOperationDigest("a".repeat(64)) + .setPlanDigest("b".repeat(64)) + .setPlanVersion(GameSessionJwtReadinessReceiverProtoMapper.CURRENT_PLAN_VERSION) + .setRegistryVersion(GameSessionJwtReadinessReceiverProtoMapper.CURRENT_REGISTRY_VERSION) + .setValidatorId(GameSessionJwtReadinessReceiverProtoMapper.GAME_SESSION_VALIDATOR) + .setTokenProfile(profile) + .setAudience(audience) + .setProbeKind( + canary + ? ReadinessProbeCoordinates.ProbeKind.CANARY + : ReadinessProbeCoordinates.ProbeKind.REPRESENTATIVE) + .setExpectedOutcome(expectedOutcome) + .setJti(UUID.randomUUID().toString()) + .setEntryVersion(1) + .setTargetGeneration("7") + .setTargetKid("pending-key-7") + .setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.ABSENT) + .setIssuedAtEpochSeconds(1_900_000_000L) + .setExpiresAtEpochSeconds(1_900_000_120L) + .setPlanExpiresAtEpochSeconds(1_900_000_180L) + .build(); + return ReceiveReadinessProbeRequest.newBuilder() + .setSchemaVersion(GameSessionJwtReadinessReceiverProtoMapper.SCHEMA_VERSION) + .setCoordinates(coordinates) + .setCompactJwt("header.payload.signature"); + } +} From baf478833175e0fd3e8a11eeee469505065738d5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 03:41:06 +1300 Subject: [PATCH 017/129] fix readiness isolation and publication binding; preserve disclosure journal --- .../account-service/configuration.md | 2 + .../game-session-service/configuration.md | 6 + design/project-management/ai-observations.md | 13 + ...ame-authoring-publishing-and-activation.md | 6 +- .../DraftAuthorizationFenceRepository.java | 44 + ...inessIsolatedGrpcRoutingConfiguration.java | 48 + .../HostedTermsDisclosureHandoff.java | 275 ++++++ ...ostedTermsDisclosureHandoffRepository.java | 414 +++++++++ .../AccountJwtReadinessProbeRepository.java | 1 + ...untJwtReadinessPodReceiverGrpcService.java | 2 +- ...ountJwtReadinessProbeOwnerGrpcService.java | 2 +- ...wtReadinessGrpcReceiverInvocationPort.java | 45 +- ...tJwtReadinessPodLocalIdentityProvider.java | 17 +- ...count_hosted_terms_disclosure_handoffs.sql | 151 +++ ...closureHandoffPostgresIntegrationTest.java | 387 ++++++++ ...dinessProbePersistenceIntegrationTest.java | 3 + ...ntJwtReadinessIsolatedGrpcRoutingTest.java | 146 +++ ...tSignerMaterializationCompositionTest.java | 158 ++++ .../HostedTermsDisclosureHandoffTest.java | 217 +++++ ...JwtReadinessProbeOwnerGrpcServiceTest.java | 93 +- ...adinessGrpcReceiverInvocationPortTest.java | 75 +- ...ReadinessPodLocalIdentityProviderTest.java | 78 +- .../SelectedDraftPublicationOwner.java | 13 +- ...emptServiceTransactionIntegrationTest.java | 10 + .../game-session-service/build.gradle.kts | 1 + ...inessIsolatedGrpcRoutingConfiguration.java | 31 + ...essionJwtReadinessReceiverGrpcService.java | 2 +- ...tReadinessReceiverMtlsIntegrationTest.java | 856 ++++++++++++++++++ ...JwtReadinessReceiverConfigurationTest.java | 77 ++ 29 files changed, 3131 insertions(+), 42 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessIsolatedGrpcRoutingConfiguration.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoff.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V101__account_hosted_terms_disclosure_handoffs.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessIsolatedGrpcRoutingTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializationCompositionTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessIsolatedGrpcRoutingConfiguration.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index cfeb4f6035..d1c29d2d6f 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -22,6 +22,8 @@ In player-facing environments, the interim `jwt-signing-keys` private bundle is The configurable cleanup margin controls issued-token registry retention only. Gameplay continuity is a separate Game Session policy documented in [Reconnection](../../system-architecture-reconnection.md); Account configuration does not derive or widen that lifetime. +The isolated readiness prerequisite graph is separately selected by an explicit `firemud.account.jwt-readiness.validation.enabled`, `.probe-owner.enabled` or `.pod-receiver.enabled`. It also requires `firemud.account.jwt-jwks-api.enabled=true` with its `protected-binding-path` fixed to `/etc/firemud/account-jwt-api/binding.json`, `firemud.account.jwt-signer.materialization.enabled=true` with its `protected-binding-path` fixed to `/etc/firemud/account-jwt-materializer/binding.json`, and a valid `firemud.grpc.workload-namespace`. Selection only constructs the readiness-specific graph: protected-file validation, authenticated resource readback and signer/readiness proof are still mandatory, and it does not enable the unrelated LOGIN or credential composition. Current proof and delivery gaps remain in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). + ## Implementation Status The current runtime still uses the shared-HMAC compatibility profile for issuance and validation and has no asymmetric non-exportable signer delegation. Any Secret-backed asymmetric materialization is the explicit interim fallback/drift, not canonical target custody; the current preflight/manifests still treat signing paths and `jwt-signing-keys` mounts as shared workload configuration rather than enforcing Account as the sole private-material consumer, and the classpath fallback remains permitted when the configured JWKS file is absent. The runtime also retains the legacy creator-share percentage setting and provider-mutating code paths; they are unsupported implementation drift, not an accepted fee policy or product capability. These target-state requirements are not proof of current startup, custody, mount enforcement, or creator-commerce disablement; runtime, preflight, and manifest alignment is outside this documentation slice. diff --git a/design/architecture/microservices/game-session-service/configuration.md b/design/architecture/microservices/game-session-service/configuration.md index 00b02cf1d3..55b06173b2 100644 --- a/design/architecture/microservices/game-session-service/configuration.md +++ b/design/architecture/microservices/game-session-service/configuration.md @@ -23,6 +23,12 @@ TLS certificates are supplied via [`FIREMUD_GRPC_CERT_CHAIN_PATH`, `FIREMUD_GRPC | `FIREMUD_SERVICES_ENTITY_MANAGEMENT_SERVICE` | gRPC endpoint (`host:port`) for Entity Management Service | `entity-management-service:6565` | | `FIREMUD_CONFLICT_TTL_SECONDS` | TTL for conflict hotspot tracking in Redis | `300` | +### Isolated JWT Readiness Receiver + +The receiver composition for [ADR 0014](../../decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md) is default-inactive. `firemud.game-session.jwt-readiness.receiver.enabled=true` alone does not supply the required protected local identity provider or register a receiver. When selected with its prerequisites, the adapter explicitly extracts the TLS peer and excludes the global application bearer interceptor; the exact Account workload guard remains mandatory. The remaining producer, transport and activation proof belongs in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md), not in a configuration toggle. + +When constructing the isolated receiver, `firemud.game-session.jwt-readiness.receiver.max-control-ui-tenant-scopes` is required, and `firemud.grpc.workload-namespace` must identify the exact protected workload namespace. Its owner-read client uses the existing Account endpoint and gRPC mTLS configuration. The receiver reads only the fixed public projection `/var/run/secrets/firemud/jwks/jwks.json`; it has no private signing material, alternate-path discovery or classpath fallback. These local prerequisites do not authorize an application auth context, session or admission. + ## FireMUD Settings Domains The canonical per-key reference for the surfaced pre-`06` platform settings now lives in the generated artifacts below rather than being hand-maintained in this service doc: diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 24ae8c1b84..8ef0b60f95 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -79,3 +79,16 @@ Entry format: - Observation: Successful earlier generation did not prove the simulator had represented every migration. V52's ignore-marker spelling hid its later ALTER from jOOQ; the donor projection also split that compound ALTER for simulation. - Expected pattern: Preserve required build-input transformations with an imported capability, compare the generated input against its canonical migration sources, and distinguish simulator omissions from production schema gaps. Do not remove database constraints or add duplicate runtime columns to conceal projection drift. - Current status: The selective Account projection restores schema generation and changes only V52's derived input; Flyway sources remain unchanged. This proves code generation, not PostgreSQL migration execution or readiness activation. + +- `2026-10-08`: Distinguish public code identifiers from secrets in controller updates + - Context: A Document job update describing the public `AuthTokenInterceptor` class was rejected as resembling credential or raw secret material; the update contained no credential bytes. + - Observation: Rephrasing the surrounding authentication description allowed the same non-secret milestone to be recorded. The exact filter condition is unconfirmed and has been reported to the controller owner. + - Expected pattern: Secret detection should retain fail-closed protection while permitting public source identifiers and ordinary authentication diagnostics. Do not include secret material or disable the filter to publish a status update. + - Current status: The milestone is recorded using neutral wording; filter correction remains unproved. + - Outcome: The controller owner confirmed that the conservative guard rejects a value immediately following an authentication-scheme word, including inline code. Preserve the public identifier with wording such as “The global authentication handler is `AuthTokenInterceptor`”; no broader filter change is needed for this case. + +- `2026-10-08`: Verify framework interceptor isolation through actual composition + - Context: Readiness adapters selected an exact TLS peer interceptor and set Spring gRPC's `blendWithGlobalInterceptors=false`, but the composed service still invoked a global interceptor. + - Observation: Installed Spring gRPC 1.0.3 uses that flag to control sorting, not exclusion. Its supported server-factory filter removes global interceptors before explicitly selected interceptors are appended; a null-factory test cannot prove that filtering path. + - Expected pattern: Prove isolated and ordinary service composition with the production factory customization, preserving exact peer extraction and ordinary application authentication. Annotation assertions alone are insufficient. + - Current status: The composition test exposed the defect before publication of the routing correction. A bounded service-local factory filter and positive/negative proof are being integrated; deployed composition remains unproved. 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 91a158efa0..91fe59962d 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 @@ -8,9 +8,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a The current Gameplay-prerequisite construction remains non-activating. Full-version finalization now reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. The real backend control-ui issuance/current-actor source, complete Account source-writer fencing and callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Earlier construction CI executed all four Account source-composition, five environment-binding and 31 Draft authorization PostgreSQL cases successfully, while three Game Design canonical-release fixtures failed for missing policy source capture. Their receiving correction now freezes actual Game Design command/policy source snapshots before sealing; corrected physical execution remains required. These bounded changes do not upgrade the broader capability ratings below. -The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. At `ed928219ee3428073910f1845eaa975e8814a30a`, local validation is complete for the held-order/source-fencing batch, but physical PostgreSQL validation was skipped. No authenticated terms-notice producer/receiver, durable prepare-before-disclose handoff, or physical World deadline gate is implemented; there is no production disclosure/currentness path. Reconsider only after focused PostgreSQL proof covers both orderings of preparation versus original `COMMIT_ORDER` acquisition and settlement, every deadline-introduction path including environment binding, exact retry/restart/ambiguous-notice readback, and World commit-time denial at the disclosed instant without early ordinary-authoring freeze or date rewriting. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. +The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. At `ed928219ee3428073910f1845eaa975e8814a30a`, local validation is complete for the held-order/source-fencing batch, but physical PostgreSQL validation was skipped. The Account-owned disclosure journal now defines an immutable request, predecessor/candidate, effective instant, exact source vector and opaque authority binding, with exact dispatch/ambiguity/result readback. Its non-revoking preparation check refuses already-reserved or unsettled original operations under sorted source locks. This is only a storage foundation: handoff-aware capture/reserve/claim, both publication paths including environment binding, authenticated notice production/readback and the physical World deadline gate remain unimplemented or unproved. In particular, preparation-first serialization is not closed while later capture and ordering do not consult the journal; there is no production disclosure/currentness path. Reconsider only after focused PostgreSQL proof covers both orderings of preparation versus original `COMMIT_ORDER` acquisition and settlement, every deadline-introduction path including environment binding, exact retry/restart/ambiguous-notice readback, and World commit-time denial at the disclosed instant without early ordinary-authoring freeze or date rewriting. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. -Creator issuance preserves the existing OTP failure budget by committing a primary-authentication denial's accounting before returning the credential error; successful OTP consumption still rolls back if subsequent preparation fails. Its real PostgreSQL definitions use the primary hook's Spring transaction interceptor, not only a direct method call. The construction now includes a selective Account per-Pod readiness/receipt closure and commit-bound signer coordinator, together with a default-inactive Game Session receiver using production cryptographic profile validation and exact Account owner readback. These sources do not establish a production signer: protected Game Session local identity, isolated route wiring, current inventory and mounted correspondence, physical PostgreSQL proof, and live convergence/promotion remain open. A complete claim without protected per-validator evidence remains quarantined; synthetic signer fixtures cannot close the original APPLIED/release prerequisite. Password and wrong-secret PostgreSQL proof is separate from restricted-account authentication: the latter has unit coverage, while an authentic owner lifecycle transition needed for its physical fixture remains unavailable. The broader JWT capability remains owned by [Shared Runtime Contracts](./shared-runtime-contracts-and-persistence.md). +Creator issuance preserves the existing OTP failure budget by committing a primary-authentication denial's accounting before returning the credential error; successful OTP consumption still rolls back if subsequent preparation fails. Its real PostgreSQL definitions use the primary hook's Spring transaction interceptor, not only a direct method call. The construction now includes a selective Account per-Pod readiness/receipt closure and commit-bound signer coordinator, together with a default-inactive Game Session receiver using production cryptographic profile validation and exact Account owner readback. The isolated adapters explicitly select TLS peer extraction without the global application JWT interceptor. Six loopback mTLS cases executed without skips through the real Game Session verifier and owner-read client; their Account owner responses, protected local identity and public JWKS remain test fixtures. Annotation/default-registration checks and manual Netty transport proof do not prove deployed Spring composition or authentic inventory. These sources do not establish a production signer: protected Game Session local identity and input delivery, deployed isolated routing, current inventory and mounted correspondence, physical PostgreSQL proof, and live convergence/promotion remain open. The current inventory rejects shared receiver-Pod leaf-key pins, while the base Deployment uses the accepted workload-level certificate delivery. Unique replica SPKI is a code-selected strengthening, not an ADR 0038 prerequisite. The approved platform-owned alternative must establish authenticated control-plane Pod UID/direct numeric endpoint, protected routing and replacement-race checks around delivery and at promotion, plus a genuine protected local-identity producer; shared keys or receiver/environment UID alone are insufficient. That alternate attribution is not yet defined and proved, and the existing guard remains intact. A complete claim without protected per-validator evidence remains quarantined; synthetic signer fixtures cannot close the original APPLIED/release prerequisite. Password and wrong-secret PostgreSQL proof is separate from restricted-account authentication: the latter has unit coverage, while an authentic owner lifecycle transition needed for its physical fixture remains unavailable. The broader JWT capability remains owned by [Shared Runtime Contracts](./shared-runtime-contracts-and-persistence.md). + +The installed Spring gRPC routing correction uses service-local server-factory filters, not the interceptor annotation alone: isolated readiness services exclude global middleware and append the exact TLS peer extractor once, while ordinary services retain their global interception. Local composition and loopback tests pass; this does not establish protected deployment inputs or deployed routing. Construction CI exposed two producer defects: the readiness applicability matrix omitted its cluster ID, and selected publication derived its workflow from a private tenant key rather than the canonical UUID. Both have corrections and local regression assertions; corrected PostgreSQL execution remains required. The Account local receiver now joins Pod-to-ReplicaSet-to-Deployment explicitly, and direct numeric transport excludes configured proxies and checks the actual socket address before accepting a result. That post-RPC check does not prove prevention of dispatch or transparent routing substitution. These corrections do not supply the missing protected Game Session identity producer or platform enforcement. Separately, a World-local post-commit confirmation could prove an on-time original transaction, but rejecting a late confirmation cannot prevent an already-committed late write to normal topology. Already-disclosed deadline-bearing writes remain denied; true staging and the remaining physical deadline design are outside the current Gameplay prerequisite batch. Account-local transaction evidence cannot prove another database's durability. This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index e3e5664dc7..9d294e4479 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -231,6 +231,50 @@ public FenceSnapshot claimCommitOrder(DraftAuthorizationFenceBinding binding) { return snapshot(requireExact(readOperation(binding.operationId()), binding)); } + /** + * Serializes an exact disclosure preparation against existing Draft captures and owner + * settlement. The caller must persist its immutable handoff in this same transaction. This is + * deliberately a non-revoking check: it never changes RESERVED, COMMIT_ORDER, or REVOKE_ORDER, + * and it does not install a blanket block on ordinary authoring. + * + *

The lock order is the canonical sorted source-key vector followed by affected operation + * UUIDs in canonical order, matching capture, commit-order, source-change, and owner-readback + * paths. No lock obtained here may be held across an RPC. + */ + public void requireDisclosurePreparation(List exactSources) { + requireTransaction(); + List sources = + List.copyOf(Objects.requireNonNull(exactSources, "exact disclosure sources")).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Distinct exact disclosure source evidence required"); + } + for (SourceEvidence source : sources) { + if (source.key().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 512) { + throw new IllegalArgumentException( + "Disclosure source key exceeds the existing Account source-lock bound"); + } + } + lockSources(sources); + if (hasWaitingChange(sources)) { + throw new IllegalStateException("Applicable Account source change is unresolved"); + } + for (UUID operationId : affectedOperations(sources)) { + Record row = readOperation(operationId); + if (row == null) { + throw new IllegalStateException("Affected original Draft operation disappeared"); + } + DraftAuthorizationFenceBinding original = originalBinding(row); + Ordering ordering = Ordering.valueOf(row.get("ordering", String.class)); + if (ordering == Ordering.RESERVED || settlement(original, ordering) == Settlement.PENDING) { + throw new IllegalStateException( + "Disclosure deadline cannot pass an unsettled original Draft operation"); + } + } + } + /** * Commit this WAITING result even when false: rolling back would lose revocation intent. True * means settled or an exact SOURCE_COMMITTED replay; call sourceMutationPermitted before writing. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessIsolatedGrpcRoutingConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessIsolatedGrpcRoutingConfiguration.java new file mode 100644 index 0000000000..b864fb1470 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessIsolatedGrpcRoutingConfiguration.java @@ -0,0 +1,48 @@ +package net.firedevops.firemud.accountservice.config; + +import java.util.HashSet; +import java.util.Set; +import net.firedevops.firemud.account.v1.AccountJwtReadinessPodReceiverServiceGrpc; +import net.firedevops.firemud.account.v1.AccountJwtReadinessProbeOwnerServiceGrpc; +import net.firedevops.firemud.account.v1.AccountJwtSignerMaterializationServiceGrpc; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.grpc.server.DefaultGrpcServerFactory; + +/** Excludes global middleware only from explicitly selected isolated readiness adapters. */ +@Configuration(proxyBeanMethods = false) +public class AccountJwtReadinessIsolatedGrpcRoutingConfiguration { + @Bean + public GrpcServerFactoryCustomizer accountJwtReadinessIsolatedGrpcRoutingCustomizer( + @Value("${firemud.account.jwt-readiness.probe-owner.enabled:false}") boolean ownerEnabled, + @Value("${firemud.account.jwt-readiness.pod-receiver.enabled:false}") boolean receiverEnabled, + @Value("${firemud.account.jwt-signer.materialization.enabled:false}") + boolean materializationEnabled) { + Set isolatedServices = new HashSet<>(); + if (ownerEnabled) { + isolatedServices.add(AccountJwtReadinessProbeOwnerServiceGrpc.SERVICE_NAME); + } + if (receiverEnabled) { + isolatedServices.add(AccountJwtReadinessPodReceiverServiceGrpc.SERVICE_NAME); + } + if (materializationEnabled) { + isolatedServices.add(AccountJwtSignerMaterializationServiceGrpc.SERVICE_NAME); + } + Set selectedServices = Set.copyOf(isolatedServices); + return factory -> { + if (selectedServices.isEmpty()) { + return; + } + if (!(factory instanceof DefaultGrpcServerFactory supportedFactory)) { + throw new IllegalStateException( + "Isolated Account readiness requires interceptor filtering"); + } + // Spring gRPC 1.0 filters globals before appending each adapter's named TLS interceptor. + supportedFactory.setInterceptorFilter( + (interceptor, service) -> + !selectedServices.contains(service.getServiceDescriptor().getName())); + }; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoff.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoff.java new file mode 100644 index 0000000000..bb8c728000 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoff.java @@ -0,0 +1,275 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; + +/** + * Exact, immutable Account evidence prepared before an elective terms deadline is disclosed. This + * value is not an authorization decision: its opaque authority bytes must come from a future + * trusted Account verifier, and this class does not authenticate them. + */ +public record HostedTermsDisclosureHandoff( + UUID handoffId, + UUID requestId, + Kind kind, + String sourceKey, + String predecessorDigest, + String candidateDigest, + Instant effectiveAt, + List sources, + byte[] authenticatedAuthorityEvidence) { + public static final String SCHEMA = "account-hosted-terms-disclosure-handoff/v1"; + private static final int MAX_SOURCES = 128; + private static final int MAX_EVIDENCE_BYTES = 1_048_576; + + public enum Kind { + CATALOG, + ENVIRONMENT_BINDING + } + + public HostedTermsDisclosureHandoff { + HostedTermsEncoding.requireUuid(handoffId, "disclosure handoff"); + HostedTermsEncoding.requireUuid(requestId, "disclosure request"); + Objects.requireNonNull(kind, "disclosure handoff kind"); + String exactSourceKey = HostedTermsEncoding.requireText(sourceKey, 512); + sourceKey = exactSourceKey; + if (exactSourceKey.getBytes(StandardCharsets.UTF_8).length > 512) { + throw new IllegalArgumentException( + "Disclosure source key exceeds the Account lock-key bound"); + } + HostedTermsEncoding.requireDigest(predecessorDigest); + HostedTermsEncoding.requireDigest(candidateDigest); + Objects.requireNonNull(effectiveAt, "disclosed effective instant"); + if (effectiveAt.getNano() % 1_000 != 0) { + throw new IllegalArgumentException( + "Effective instant must preserve PostgreSQL microsecond precision"); + } + List exactSources = + Objects.requireNonNull(sources, "complete exact source vector").stream() + .map(Objects::requireNonNull) + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (exactSources.isEmpty() + || exactSources.size() > MAX_SOURCES + || exactSources.stream().map(SourceEvidence::key).distinct().count() != exactSources.size() + || exactSources.stream().noneMatch(source -> source.key().equals(exactSourceKey))) { + throw new IllegalArgumentException( + "Distinct complete sorted source evidence including the changed source is required"); + } + SourceEvidence changedSource = + exactSources.stream() + .filter(source -> source.key().equals(exactSourceKey)) + .findFirst() + .orElseThrow(); + if (changedSource.kind() != SourceKind.HOSTED_TERMS) { + throw new IllegalArgumentException("Disclosure source must be Account hosted terms evidence"); + } + if (kind == Kind.CATALOG) { + DraftAuthorizationFenceBinding.canonicalUuid(changedSource.scopeId()); + if (!sourceKey.equals("HOSTED_TERMS:" + changedSource.scopeId())) { + throw new IllegalArgumentException( + "Catalog disclosure source key must bind its exact scope"); + } + } else if (!changedSource.scopeId().startsWith("environment-boundary/")) { + throw new IllegalArgumentException( + "Environment-binding disclosure source must name its exact boundary"); + } + sources = List.copyOf(exactSources); + authenticatedAuthorityEvidence = + requireEvidence(authenticatedAuthorityEvidence, "authenticated authority evidence"); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + @Override + public byte[] authenticatedAuthorityEvidence() { + return authenticatedAuthorityEvidence.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof HostedTermsDisclosureHandoff that + && Arrays.equals(canonicalBytes(), that.canonicalBytes()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + /** Closed length-framed bytes; the caller-provided evidence is retained exactly, not trusted. */ + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, handoffId.toString()); + DraftAuthorizationFenceBinding.frame(output, requestId.toString()); + DraftAuthorizationFenceBinding.frame(output, kind.name()); + DraftAuthorizationFenceBinding.frame(output, sourceKey); + DraftAuthorizationFenceBinding.frame(output, predecessorDigest); + DraftAuthorizationFenceBinding.frame(output, candidateDigest); + DraftAuthorizationFenceBinding.frame(output, effectiveAt.toString()); + DraftAuthorizationFenceBinding.frame(output, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + DraftAuthorizationFenceBinding.frame(output, source.canonicalBytes()); + } + DraftAuthorizationFenceBinding.frame(output, authenticatedAuthorityEvidence); + return output.toByteArray(); + } + + /** Decodes only this exact immutable frame; it does not authenticate the authority bytes. */ + public static HostedTermsDisclosureHandoff fromStored(byte[] stored) { + DraftAuthorizationFenceBinding.FrameReader reader = + new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(SCHEMA); + UUID handoffId = canonicalUuid(reader.text()); + UUID requestId = canonicalUuid(reader.text()); + Kind kind = Kind.valueOf(reader.text()); + String sourceKey = reader.text(); + String predecessorDigest = reader.text(); + String candidateDigest = reader.text(); + String effectiveAtText = reader.text(); + String countText = reader.text(); + DraftAuthorizationFenceBinding.decimal(countText, false); + int count; + try { + count = Integer.parseInt(countText); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException("Stored source count is out of range", invalid); + } + if (count > MAX_SOURCES || count > reader.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Stored source vector is incomplete or too large"); + } + java.util.ArrayList sources = new java.util.ArrayList<>(); + for (int index = 0; index < count; index++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + byte[] authorityEvidence = reader.bytes(); + reader.requireEnd(); + final Instant effectiveAt; + try { + effectiveAt = Instant.parse(effectiveAtText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Stored effective instant is invalid", invalid); + } + HostedTermsDisclosureHandoff handoff = + new HostedTermsDisclosureHandoff( + handoffId, + requestId, + kind, + sourceKey, + predecessorDigest, + candidateDigest, + effectiveAt, + sources, + authorityEvidence); + if (!Arrays.equals(stored, handoff.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored disclosure handoff"); + } + return handoff; + } + + /** Exact authenticated owner result. The opaque evidence must be verified before construction. */ + public record DisclosureResult( + UUID handoffId, + UUID requestId, + String bindingDigest, + Outcome outcome, + byte[] authenticatedEvidence) { + private static final String RESULT_SCHEMA = "account-hosted-terms-disclosure-result/v1"; + + public DisclosureResult { + HostedTermsEncoding.requireUuid(handoffId, "disclosure handoff"); + HostedTermsEncoding.requireUuid(requestId, "disclosure request"); + HostedTermsEncoding.requireDigest(bindingDigest); + Objects.requireNonNull(outcome, "authenticated disclosure outcome"); + authenticatedEvidence = + requireEvidence(authenticatedEvidence, "authenticated result evidence"); + } + + @Override + public byte[] authenticatedEvidence() { + return authenticatedEvidence.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof DisclosureResult that + && Arrays.equals(canonicalBytes(), that.canonicalBytes()); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes()); + } + + public byte[] canonicalBytes() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, RESULT_SCHEMA); + DraftAuthorizationFenceBinding.frame(output, handoffId.toString()); + DraftAuthorizationFenceBinding.frame(output, requestId.toString()); + DraftAuthorizationFenceBinding.frame(output, bindingDigest); + DraftAuthorizationFenceBinding.frame(output, outcome.name()); + DraftAuthorizationFenceBinding.frame( + output, HostedTermsEncoding.digest(authenticatedEvidence)); + DraftAuthorizationFenceBinding.frame(output, authenticatedEvidence); + return output.toByteArray(); + } + + public static DisclosureResult fromStored(byte[] stored) { + DraftAuthorizationFenceBinding.FrameReader reader = + new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(RESULT_SCHEMA); + DisclosureResult result = + new DisclosureResult( + canonicalUuid(reader.text()), + canonicalUuid(reader.text()), + reader.text(), + Outcome.valueOf(reader.text()), + readEvidence(reader)); + reader.requireEnd(); + if (!Arrays.equals(stored, result.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical stored disclosure result"); + } + return result; + } + + private static byte[] readEvidence(DraftAuthorizationFenceBinding.FrameReader reader) { + String digest = reader.text(); + byte[] evidence = reader.bytes(); + if (!HostedTermsEncoding.digest(evidence).equals(digest)) { + throw new IllegalArgumentException("Stored disclosure result evidence digest conflicts"); + } + return evidence; + } + } + + public enum Outcome { + DISCLOSED, + DEFINITIVELY_NOT_DISCLOSED + } + + private static UUID canonicalUuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } + + private static byte[] requireEvidence(byte[] evidence, String description) { + byte[] exact = HostedTermsEncoding.requireBytes(evidence); + if (exact.length > MAX_EVIDENCE_BYTES) { + throw new IllegalArgumentException(description + " exceeds the durable evidence bound"); + } + return exact; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java new file mode 100644 index 0000000000..294d70911f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java @@ -0,0 +1,414 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.DisclosureResult; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Immutable Account-owned disclosure intent and exact owner-result journal. It performs no + * authentication and no RPC; only a future trusted Account verifier/dispatcher may supply the + * opaque authority and result bytes. Every write and source-fence check is one writable owner + * READ_COMMITTED transaction, which must finish before external dispatch. + */ +public final class HostedTermsDisclosureHandoffRepository { + private static final String HANDOFFS = "account_hosted_terms_disclosure_handoffs"; + private static final String SOURCES = "account_hosted_terms_disclosure_sources"; + private final DSLContext dsl; + private final DraftAuthorizationFenceRepository fenceRepository; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected owner persistence collaborators are retained privately and never exposed.") + public HostedTermsDisclosureHandoffRepository( + DSLContext dsl, DraftAuthorizationFenceRepository fenceRepository) { + this.dsl = Objects.requireNonNull(dsl); + this.fenceRepository = Objects.requireNonNull(fenceRepository); + } + + public enum Status { + PREPARED, + DISPATCH_AUTHORIZED, + AMBIGUOUS, + DISCLOSED, + DEFINITIVELY_NOT_DISCLOSED + } + + public record Snapshot( + HostedTermsDisclosureHandoff handoff, + Status status, + int dispatchAttempts, + Optional result, + OffsetDateTime createdAt, + OffsetDateTime resultRecordedAt) { + public Snapshot { + Objects.requireNonNull(handoff); + Objects.requireNonNull(status); + if (dispatchAttempts < 0) { + throw new IllegalArgumentException("Nonnegative dispatch attempt count required"); + } + result = Objects.requireNonNull(result); + Objects.requireNonNull(createdAt); + if (status == Status.DISCLOSED || status == Status.DEFINITIVELY_NOT_DISCLOSED) { + if (result.isEmpty() || resultRecordedAt == null) { + throw new IllegalArgumentException("Terminal status requires exact durable result"); + } + } else if (result.isPresent() || resultRecordedAt != null) { + throw new IllegalArgumentException("Nonterminal status cannot carry a result"); + } + } + } + + /** True only when this transaction durably authorized a new exact dispatch attempt. */ + public record DispatchPermit(Snapshot snapshot, boolean newlyAuthorized) { + public DispatchPermit { + Objects.requireNonNull(snapshot); + } + } + + /** + * Prepare the immutable exact source handoff. Existing exact identities are idempotent; a new + * identity first locks all sorted source keys, refuses unsettled original operations without + * modifying them, and writes the journal before those locks are released. + */ + public Snapshot prepare(HostedTermsDisclosureHandoff handoff) { + requireWriteTransaction(); + Objects.requireNonNull(handoff); + byte[] exactBinding = handoff.canonicalBytes(); + Record existing = findByIdentity(handoff.handoffId(), handoff.requestId()); + if (existing != null) { + return exactSnapshot(existing, handoff, exactBinding); + } + + fenceRepository.requireDisclosurePreparation(handoff.sources()); + dsl.execute( + "INSERT INTO " + + HANDOFFS + + " (handoff_id, request_id, kind, source_key, predecessor_digest, candidate_digest, " + + "effective_at, binding, binding_digest, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?, ?, 'PREPARED') " + + "ON CONFLICT DO NOTHING", + handoff.handoffId(), + handoff.requestId(), + handoff.kind().name(), + handoff.sourceKey(), + handoff.predecessorDigest(), + handoff.candidateDigest(), + java.time.OffsetDateTime.ofInstant(handoff.effectiveAt(), java.time.ZoneOffset.UTC), + exactBinding, + HostedTermsEncoding.digest(exactBinding)); + + Record row = findByIdentity(handoff.handoffId(), handoff.requestId()); + if (row == null) { + throw new IllegalStateException("Disclosure handoff durable readback is unavailable"); + } + Snapshot current = snapshot(row); + requireExactHandoffColumns(row, handoff, exactBinding); + if (current.status() == Status.PREPARED && current.dispatchAttempts() == 0) { + for (SourceEvidence source : handoff.sources()) { + byte[] evidence = source.canonicalBytes(); + dsl.execute( + "INSERT INTO " + + SOURCES + + " (handoff_id, source_key, source_evidence, source_evidence_digest) " + + "VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", + handoff.handoffId(), + source.key(), + evidence, + HostedTermsEncoding.digest(evidence)); + } + row = findByIdentity(handoff.handoffId(), handoff.requestId()); + if (row == null) { + throw new IllegalStateException("Disclosure handoff disappeared during source readback"); + } + } + return exactSnapshot(row, handoff, exactBinding); + } + + /** + * Durably authorizes one dispatch before the caller leaves the transaction. A pre-existing + * DISPATCH_AUTHORIZED row is recovered by readback, not by guessing that a previous RPC failed. + * An exact retry after explicit ambiguity may reauthorize the same stable request identity; the + * external receiver must deduplicate it. + */ + public DispatchPermit authorizeDispatch(HostedTermsDisclosureHandoff handoff) { + requireWriteTransaction(); + Objects.requireNonNull(handoff); + Record row = requireExactRow(handoff); + Status status = Status.valueOf(row.get("status", String.class)); + boolean newlyAuthorized = false; + if (status == Status.PREPARED || status == Status.AMBIGUOUS) { + int updated = + dsl.execute( + "UPDATE " + + HANDOFFS + + " SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = dispatch_attempts + 1 " + + "WHERE handoff_id = ? AND status = ?", + handoff.handoffId(), + status.name()); + if (updated != 1) { + throw new IllegalStateException("Disclosure dispatch authorization did not advance once"); + } + newlyAuthorized = true; + } + row = requireExactRow(handoff); + return new DispatchPermit(snapshot(row), newlyAuthorized); + } + + /** Records uncertainty only; absence, timeout, or an empty readback is never no-disclosure. */ + public Snapshot recordAmbiguous(HostedTermsDisclosureHandoff handoff) { + requireWriteTransaction(); + Objects.requireNonNull(handoff); + Record row = requireExactRow(handoff); + Status status = Status.valueOf(row.get("status", String.class)); + if (status == Status.DISPATCH_AUTHORIZED) { + int updated = + dsl.execute( + "UPDATE " + + HANDOFFS + + " SET status = 'AMBIGUOUS' WHERE handoff_id = ? AND status = 'DISPATCH_AUTHORIZED'", + handoff.handoffId()); + if (updated != 1) { + throw new IllegalStateException("Ambiguous disclosure outcome did not persist once"); + } + row = requireExactRow(handoff); + } else if (status != Status.AMBIGUOUS) { + throw new IllegalStateException("Only an authorized unresolved dispatch can be ambiguous"); + } + return snapshot(row); + } + + /** + * Stores immutable exact owner evidence after its authenticated verifier proves either outcome. + * The repository itself cannot authenticate the supplied evidence, and never infers a negative + * result from timeout, process restart, or a missing owner row. + */ + public Snapshot recordResult(HostedTermsDisclosureHandoff handoff, DisclosureResult result) { + requireWriteTransaction(); + Objects.requireNonNull(handoff); + Objects.requireNonNull(result); + Record row = requireExactRow(handoff); + byte[] resultBytes = result.canonicalBytes(); + String resultDigest = HostedTermsEncoding.digest(resultBytes); + requireResultBinding(handoff, result); + Status status = Status.valueOf(row.get("status", String.class)); + if (status == Status.DISCLOSED || status == Status.DEFINITIVELY_NOT_DISCLOSED) { + if (!Arrays.equals(resultBytes, row.get("result_payload", byte[].class))) { + throw new IllegalArgumentException("Changed terminal disclosure result evidence"); + } + return snapshot(row); + } + if (status != Status.DISPATCH_AUTHORIZED && status != Status.AMBIGUOUS) { + throw new IllegalStateException( + "A disclosure result requires durable dispatch authorization"); + } + Status terminal = + result.outcome() == Outcome.DISCLOSED + ? Status.DISCLOSED + : Status.DEFINITIVELY_NOT_DISCLOSED; + int updated = + dsl.execute( + "UPDATE " + + HANDOFFS + + " SET status = ?, result_outcome = ?, result_payload = ?, result_digest = ?, " + + "result_recorded_at = CURRENT_TIMESTAMP WHERE handoff_id = ? " + + "AND status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS')", + terminal.name(), + result.outcome().name(), + resultBytes, + resultDigest, + handoff.handoffId()); + if (updated != 1) { + Record prior = requireExactRow(handoff); + if (Status.valueOf(prior.get("status", String.class)) != terminal + || !Arrays.equals(resultBytes, prior.get("result_payload", byte[].class))) { + throw new IllegalStateException( + "Disclosure result did not persist as exact terminal readback"); + } + return snapshot(prior); + } + return snapshot(requireExactRow(handoff)); + } + + public Optional read(UUID handoffId) { + requireTransaction(); + HostedTermsEncoding.requireUuid(handoffId, "disclosure handoff"); + Record row = dsl.fetchOne("SELECT * FROM " + HANDOFFS + " WHERE handoff_id = ?", handoffId); + if (row == null) { + return Optional.empty(); + } + Snapshot snapshot = snapshot(row); + requireExactSourceRows(snapshot.handoff()); + return Optional.of(snapshot); + } + + private Record requireExactRow(HostedTermsDisclosureHandoff handoff) { + Record row = findByIdentity(handoff.handoffId(), handoff.requestId()); + if (row == null) { + throw new IllegalStateException("Exact disclosure handoff is unavailable"); + } + exactSnapshot(row, handoff, handoff.canonicalBytes()); + return row; + } + + private Record findByIdentity(UUID handoffId, UUID requestId) { + List rows = + dsl.fetch( + "SELECT * FROM " + HANDOFFS + " WHERE handoff_id = ? OR request_id = ? FOR UPDATE", + handoffId, + requestId); + if (rows.size() > 1) { + throw new IllegalStateException("Disclosure handoff and request identities conflict"); + } + return rows.isEmpty() ? null : rows.getFirst(); + } + + private Snapshot exactSnapshot( + Record row, HostedTermsDisclosureHandoff expected, byte[] expectedBinding) { + Snapshot snapshot = snapshot(row); + requireExactHandoffColumns(row, expected, expectedBinding); + requireExactSourceRows(expected); + return snapshot; + } + + private void requireExactHandoffColumns( + Record row, HostedTermsDisclosureHandoff expected, byte[] expectedBinding) { + if (!Arrays.equals(expectedBinding, row.get("binding", byte[].class)) + || !expected.handoffId().equals(row.get("handoff_id", UUID.class)) + || !expected.requestId().equals(row.get("request_id", UUID.class)) + || !expected.kind().name().equals(row.get("kind", String.class)) + || !expected.sourceKey().equals(row.get("source_key", String.class)) + || !expected.predecessorDigest().equals(row.get("predecessor_digest", String.class)) + || !expected.candidateDigest().equals(row.get("candidate_digest", String.class)) + || !expected.effectiveAt().equals(row.get("effective_at", OffsetDateTime.class).toInstant()) + || !HostedTermsEncoding.digest(expectedBinding) + .equals(row.get("binding_digest", String.class))) { + throw new IllegalArgumentException( + "Disclosure handoff identity conflicts with prior evidence"); + } + } + + private Snapshot snapshot(Record row) { + byte[] bindingBytes = row.get("binding", byte[].class); + String bindingDigest = HostedTermsEncoding.digest(bindingBytes); + if (!bindingDigest.equals(row.get("binding_digest", String.class))) { + throw new IllegalStateException( + "Disclosure handoff binding digest conflicts with exact bytes"); + } + HostedTermsDisclosureHandoff handoff = HostedTermsDisclosureHandoff.fromStored(bindingBytes); + if (!handoff.handoffId().equals(row.get("handoff_id", UUID.class)) + || !handoff.requestId().equals(row.get("request_id", UUID.class)) + || !handoff.kind().name().equals(row.get("kind", String.class)) + || !handoff.sourceKey().equals(row.get("source_key", String.class)) + || !handoff.predecessorDigest().equals(row.get("predecessor_digest", String.class)) + || !handoff.candidateDigest().equals(row.get("candidate_digest", String.class)) + || !handoff + .effectiveAt() + .equals(row.get("effective_at", OffsetDateTime.class).toInstant())) { + throw new IllegalStateException("Disclosure handoff columns conflict with exact binding"); + } + Status status = Status.valueOf(row.get("status", String.class)); + String resultOutcome = row.get("result_outcome", String.class); + byte[] resultPayload = row.get("result_payload", byte[].class); + String resultDigest = row.get("result_digest", String.class); + OffsetDateTime resultRecordedAt = row.get("result_recorded_at", OffsetDateTime.class); + Optional result = Optional.empty(); + if (resultPayload != null) { + if (resultDigest == null + || !HostedTermsEncoding.digest(resultPayload).equals(resultDigest) + || resultOutcome == null) { + throw new IllegalStateException("Disclosure result digest or outcome is incomplete"); + } + DisclosureResult decoded = DisclosureResult.fromStored(resultPayload); + requireResultBinding(handoff, decoded); + if (!decoded.outcome().name().equals(resultOutcome)) { + throw new IllegalStateException("Disclosure result outcome differs from exact evidence"); + } + if ((status == Status.DISCLOSED && decoded.outcome() != Outcome.DISCLOSED) + || (status == Status.DEFINITIVELY_NOT_DISCLOSED + && decoded.outcome() != Outcome.DEFINITIVELY_NOT_DISCLOSED)) { + throw new IllegalStateException("Terminal disclosure status differs from exact result"); + } + result = Optional.of(decoded); + } else if (resultOutcome != null || resultDigest != null || resultRecordedAt != null) { + throw new IllegalStateException("Partial disclosure result columns are not permitted"); + } + return new Snapshot( + handoff, + status, + row.get("dispatch_attempts", Integer.class), + result, + row.get("created_at", OffsetDateTime.class), + resultRecordedAt); + } + + private void requireExactSourceRows(HostedTermsDisclosureHandoff handoff) { + List rows = + dsl + .fetch( + "SELECT source_key, source_evidence, source_evidence_digest FROM " + + SOURCES + + " WHERE handoff_id = ?", + handoff.handoffId()) + .stream() + .sorted(Comparator.comparing(row -> row.get("source_key", String.class))) + .toList(); + if (rows.size() != handoff.sources().size()) { + throw new IllegalStateException("Disclosure handoff source participation is incomplete"); + } + for (int index = 0; index < rows.size(); index++) { + SourceEvidence expected = handoff.sources().get(index); + Record row = rows.get(index); + byte[] evidence = row.get("source_evidence", byte[].class); + if (!expected.key().equals(row.get("source_key", String.class)) + || !Arrays.equals(expected.canonicalBytes(), evidence) + || !HostedTermsEncoding.digest(evidence) + .equals(row.get("source_evidence_digest", String.class))) { + throw new IllegalStateException("Disclosure handoff source evidence differs from binding"); + } + } + } + + private void requireResultBinding(HostedTermsDisclosureHandoff handoff, DisclosureResult result) { + if (!handoff.handoffId().equals(result.handoffId()) + || !handoff.requestId().equals(result.requestId()) + || !HostedTermsEncoding.digest(handoff.canonicalBytes()).equals(result.bindingDigest())) { + throw new IllegalArgumentException("Disclosure result is not bound to the exact handoff"); + } + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Caller Account transaction required"); + } + } + + private void requireWriteTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable caller Account transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Transaction-bound writable READ_COMMITTED connection required"); + } + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java index 716bbb12e0..adc934c480 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java @@ -2803,6 +2803,7 @@ private static String applicabilityMatrixJson( source.put("apiBindingDigest", snapshot.apiBindingDigest()); source.put("apiBindingRevision", snapshot.apiBindingRevision()); source.put("clusterIncarnationUid", snapshot.clusterIncarnationUid()); + source.put("clusterId", snapshot.clusterId()); source.put("environmentId", snapshot.environmentId()); source.put("inventoryBindingDigest", snapshot.inventoryBindingDigest()); source.put("inventoryBindingRevision", snapshot.inventoryBindingRevision()); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessPodReceiverGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessPodReceiverGrpcService.java index 170697c4d0..00af150be8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessPodReceiverGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessPodReceiverGrpcService.java @@ -18,7 +18,7 @@ import org.springframework.grpc.server.service.GrpcService; /** Isolated default-inactive Account Pod verifier; does not share the V1 harness RPC or guard. */ -@GrpcService +@GrpcService(interceptorNames = "grpcPeerIdentityInterceptor", blendWithGlobalInterceptors = false) @ConditionalOnProperty( prefix = "firemud.account.jwt-readiness.pod-receiver", name = "enabled", diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java index 93cf4f4aa3..c64027e9f2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java @@ -16,7 +16,7 @@ import org.springframework.grpc.server.service.GrpcService; /** Isolated, default-inactive mTLS owner lookup; no bearer or readiness-harness route is reused. */ -@GrpcService +@GrpcService(interceptorNames = "grpcPeerIdentityInterceptor", blendWithGlobalInterceptors = false) @ConditionalOnProperty( prefix = "firemud.account.jwt-readiness.probe-owner", name = "enabled", diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java index 71b0e8aa0a..bff7b6e58f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java @@ -1,5 +1,8 @@ package net.firedevops.firemud.accountservice.service.session; +import io.grpc.Attributes; +import io.grpc.ClientTransportFilter; +import io.grpc.Grpc; import io.grpc.ManagedChannel; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; @@ -7,6 +10,7 @@ import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.SocketAddress; import java.net.URI; import java.net.UnknownHostException; import java.time.Clock; @@ -123,8 +127,20 @@ public AuthenticatedAcceptance invoke(Invocation invocation) { throw new ReceiverUnavailableException(); } + InetSocketAddress expectedRemoteAddress = new InetSocketAddress(podAddress, endpoint.getPort()); + RemoteAddressObservation remoteAddressObservation = new RemoteAddressObservation(); ManagedChannel channel = - NettyChannelBuilder.forAddress(new InetSocketAddress(podAddress, endpoint.getPort())) + NettyChannelBuilder.forAddress(expectedRemoteAddress) + .proxyDetector(address -> null) + .addTransportFilter( + new ClientTransportFilter() { + @Override + public Attributes transportReady(Attributes attributes) { + remoteAddressObservation.observe( + attributes.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)); + return attributes; + } + }) .sslContext(sslContext) .disableRetry() .build(); @@ -167,9 +183,36 @@ public AuthenticatedAcceptance invoke(Invocation invocation) { } } + if (!remoteAddressObservation.matches(expectedRemoteAddress)) { + throw new ReceiverUnavailableException(); + } + return acceptance; } + static final class RemoteAddressObservation { + private SocketAddress observedAddress; + private boolean inconsistent; + + synchronized void observe(SocketAddress address) { + if (address == null) { + inconsistent = true; + } else if (observedAddress == null) { + observedAddress = address; + } else if (!observedAddress.equals(address)) { + inconsistent = true; + } + } + + synchronized boolean matches(InetSocketAddress expected) { + return !inconsistent + && !expected.isUnresolved() + && observedAddress instanceof InetSocketAddress observed + && !observed.isUnresolved() + && observed.equals(expected); + } + } + private AuthenticatedAcceptance authenticatedResponse( Invocation invocation, ReceiverObservation response, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java index c69a0615db..b0959efa5e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ReplicaSetObservation; import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; @@ -166,8 +167,20 @@ private PodObservation exactLocalPod(ValidatorObservation validator, String name throw new IdentityUnavailableException(); } PodObservation pod = matches.getFirst(); - if (!validator.deploymentUid().equals(pod.ownerUid()) - || !validator.deploymentName().equals(pod.ownerName()) + List ownerReplicaSets = + validator.replicaSets().stream() + .filter( + value -> pod.ownerUid().equals(value.uid()) && pod.ownerName().equals(value.name())) + .toList(); + if (ownerReplicaSets.size() != 1) { + throw new IdentityUnavailableException(); + } + ReplicaSetObservation ownerReplicaSet = ownerReplicaSets.getFirst(); + if (!validator.deploymentUid().equals(ownerReplicaSet.ownerDeploymentUid()) + || !validator.deploymentName().equals(ownerReplicaSet.ownerDeploymentName()) + || !ownerReplicaSet.podTemplateHash().equals(pod.podTemplateHash()) + || !validator.image().equals(ownerReplicaSet.image()) + || !validator.verifierConfigSha256().equals(ownerReplicaSet.verifierConfigSha256()) || !validator.image().equals(pod.image()) || !validator.verifierConfigSha256().equals(pod.verifierConfigSha256())) { throw new IdentityUnavailableException(); diff --git a/services/account-service/src/main/resources/db/migration/V101__account_hosted_terms_disclosure_handoffs.sql b/services/account-service/src/main/resources/db/migration/V101__account_hosted_terms_disclosure_handoffs.sql new file mode 100644 index 0000000000..cc90a0c8f7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V101__account_hosted_terms_disclosure_handoffs.sql @@ -0,0 +1,151 @@ +-- Account-owned exact intent only. No legal authority verifier, dispatch RPC, or consumer is +-- enabled by this journal. +CREATE TABLE account_hosted_terms_disclosure_handoffs ( + handoff_id UUID PRIMARY KEY, + request_id UUID NOT NULL UNIQUE, + kind VARCHAR(32) NOT NULL CHECK (kind IN ('CATALOG', 'ENVIRONMENT_BINDING')), + source_key VARCHAR(512) NOT NULL CHECK (length(source_key) > 0 AND octet_length(source_key) <= 512), + predecessor_digest VARCHAR(71) NOT NULL CHECK (predecessor_digest ~ '^sha256:[0-9a-f]{64}$'), + candidate_digest VARCHAR(71) NOT NULL CHECK (candidate_digest ~ '^sha256:[0-9a-f]{64}$'), + effective_at TIMESTAMPTZ NOT NULL, + binding BYTEA NOT NULL CHECK (octet_length(binding) > 0), + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + status VARCHAR(32) NOT NULL + CHECK (status IN ('PREPARED', 'DISPATCH_AUTHORIZED', 'AMBIGUOUS', 'DISCLOSED', 'DEFINITIVELY_NOT_DISCLOSED')), + dispatch_attempts INTEGER NOT NULL DEFAULT 0 CHECK (dispatch_attempts >= 0), + result_outcome VARCHAR(32) CHECK (result_outcome IN ('DISCLOSED', 'DEFINITIVELY_NOT_DISCLOSED')), + result_payload BYTEA, + result_digest VARCHAR(71) CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + result_recorded_at TIMESTAMPTZ, + CHECK ( + (status = 'PREPARED' AND dispatch_attempts = 0 + AND result_outcome IS NULL AND result_payload IS NULL + AND result_digest IS NULL AND result_recorded_at IS NULL) + OR (status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS') AND dispatch_attempts > 0 + AND result_outcome IS NULL AND result_payload IS NULL + AND result_digest IS NULL AND result_recorded_at IS NULL) + OR (status = 'DISCLOSED' AND dispatch_attempts > 0 + AND result_outcome = 'DISCLOSED' AND result_payload IS NOT NULL + AND octet_length(result_payload) > 0 + AND result_digest IS NOT NULL AND result_recorded_at IS NOT NULL) + OR (status = 'DEFINITIVELY_NOT_DISCLOSED' AND dispatch_attempts > 0 + AND result_outcome = 'DEFINITIVELY_NOT_DISCLOSED' + AND result_payload IS NOT NULL AND octet_length(result_payload) > 0 + AND result_digest IS NOT NULL + AND result_recorded_at IS NOT NULL) + ) +); + +CREATE TABLE account_hosted_terms_disclosure_sources ( + handoff_id UUID NOT NULL REFERENCES account_hosted_terms_disclosure_handoffs(handoff_id), + source_key VARCHAR(512) NOT NULL + REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), + source_evidence_digest VARCHAR(71) NOT NULL + CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (handoff_id, source_key) +); +CREATE INDEX account_hosted_terms_disclosure_sources_by_key + ON account_hosted_terms_disclosure_sources(source_key, handoff_id); + +-- [jooq ignore start] +CREATE FUNCTION account_hosted_terms_disclosure_handoff_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Hosted terms disclosure handoff cannot be deleted' + USING ERRCODE = '23514'; + END IF; + IF NEW.handoff_id IS DISTINCT FROM OLD.handoff_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.kind IS DISTINCT FROM OLD.kind + OR NEW.source_key IS DISTINCT FROM OLD.source_key + OR NEW.predecessor_digest IS DISTINCT FROM OLD.predecessor_digest + OR NEW.candidate_digest IS DISTINCT FROM OLD.candidate_digest + OR NEW.effective_at IS DISTINCT FROM OLD.effective_at + OR NEW.binding IS DISTINCT FROM OLD.binding + OR NEW.binding_digest IS DISTINCT FROM OLD.binding_digest + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Hosted terms disclosure handoff binding is immutable' + USING ERRCODE = '23514'; + END IF; + + IF OLD.result_payload IS NOT NULL THEN + IF NEW.status IS DISTINCT FROM OLD.status + OR NEW.dispatch_attempts IS DISTINCT FROM OLD.dispatch_attempts + OR NEW.result_outcome IS DISTINCT FROM OLD.result_outcome + OR NEW.result_payload IS DISTINCT FROM OLD.result_payload + OR NEW.result_digest IS DISTINCT FROM OLD.result_digest + OR NEW.result_recorded_at IS DISTINCT FROM OLD.result_recorded_at THEN + RAISE EXCEPTION 'Hosted terms disclosure result is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED' + AND OLD.dispatch_attempts = 0 AND NEW.dispatch_attempts = 1 + AND NEW.result_outcome IS NULL AND NEW.result_payload IS NULL + AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL THEN + RETURN NEW; + ELSIF OLD.status = 'DISPATCH_AUTHORIZED' AND NEW.status = 'AMBIGUOUS' + AND NEW.dispatch_attempts = OLD.dispatch_attempts + AND NEW.result_outcome IS NULL AND NEW.result_payload IS NULL + AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL THEN + RETURN NEW; + ELSIF OLD.status = 'AMBIGUOUS' AND NEW.status = 'DISPATCH_AUTHORIZED' + AND NEW.dispatch_attempts = OLD.dispatch_attempts + 1 + AND NEW.result_outcome IS NULL AND NEW.result_payload IS NULL + AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL THEN + RETURN NEW; + ELSIF OLD.status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS') + AND NEW.status IN ('DISCLOSED', 'DEFINITIVELY_NOT_DISCLOSED') + AND NEW.dispatch_attempts = OLD.dispatch_attempts + AND NEW.result_payload IS NOT NULL AND octet_length(NEW.result_payload) > 0 + AND NEW.result_digest IS NOT NULL AND NEW.result_recorded_at IS NOT NULL + AND ((NEW.status = 'DISCLOSED' AND NEW.result_outcome = 'DISCLOSED') + OR (NEW.status = 'DEFINITIVELY_NOT_DISCLOSED' + AND NEW.result_outcome = 'DEFINITIVELY_NOT_DISCLOSED')) THEN + RETURN NEW; + END IF; + + RAISE EXCEPTION 'Invalid hosted terms disclosure handoff transition' + USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_hosted_terms_disclosure_immutable_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Hosted terms disclosure source evidence is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_hosted_terms_disclosure_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + phase TEXT; +BEGIN + SELECT status INTO phase + FROM account_hosted_terms_disclosure_handoffs + WHERE handoff_id = NEW.handoff_id FOR UPDATE; + IF phase IS DISTINCT FROM 'PREPARED' THEN + RAISE EXCEPTION 'Only a newly prepared handoff may acquire source evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_hosted_terms_disclosure_handoff_immutable + BEFORE UPDATE OR DELETE ON account_hosted_terms_disclosure_handoffs + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_disclosure_handoff_guard(); +CREATE TRIGGER account_hosted_terms_disclosure_sources_immutable + BEFORE UPDATE OR DELETE ON account_hosted_terms_disclosure_sources + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_disclosure_immutable_guard(); +CREATE TRIGGER account_hosted_terms_disclosure_sources_insert_phase + BEFORE INSERT ON account_hosted_terms_disclosure_sources + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_disclosure_source_insert_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java new file mode 100644 index 0000000000..e0cbca61bf --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java @@ -0,0 +1,387 @@ +package integration.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.Statement; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.DisclosureResult; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Kind; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Outcome; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoffRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoffRepository.Status; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Owner-store proof only. Authority and disclosure evidence below is explicitly test-only; this + * does not authenticate a publisher or implement an external dispatch/receipt owner. + */ +@Testcontainers(disabledWithoutDocker = true) +class HostedTermsDisclosureHandoffPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void exactRetryAmbiguityAndTerminalEvidenceAreDurableAndImmutable() throws Exception { + Database database = database(); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(database.dsl()); + HostedTermsDisclosureHandoffRepository journal = + new HostedTermsDisclosureHandoffRepository(database.dsl(), fences); + HostedTermsDisclosureHandoff handoff = handoff(source("journal")); + + var prepared = tx(database, () -> journal.prepare(handoff)); + assertThat(prepared.status()).isEqualTo(Status.PREPARED); + assertThat(prepared.dispatchAttempts()).isZero(); + var preparedRetry = tx(database, () -> journal.prepare(handoff)); + assertThat(preparedRetry.handoff().canonicalBytes()).containsExactly(handoff.canonicalBytes()); + assertThat(preparedRetry.status()).isEqualTo(Status.PREPARED); + + HostedTermsDisclosureHandoff conflict = + new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + handoff.requestId(), + handoff.kind(), + handoff.sourceKey(), + handoff.predecessorDigest(), + HostedTermsEncoding.digest(new byte[] {99}), + handoff.effectiveAt(), + handoff.sources(), + "test-only-conflicting-authority-bytes".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> tx(database, () -> journal.prepare(conflict))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + + var firstPermit = tx(database, () -> journal.authorizeDispatch(handoff)); + assertThat(firstPermit.newlyAuthorized()).isTrue(); + assertThat(firstPermit.snapshot().status()).isEqualTo(Status.DISPATCH_AUTHORIZED); + assertThat(firstPermit.snapshot().dispatchAttempts()).isEqualTo(1); + assertThat(firstPermit.snapshot().result()).isEmpty(); + var lostPermitRecovery = tx(database, () -> journal.authorizeDispatch(handoff)); + assertThat(lostPermitRecovery.newlyAuthorized()).isFalse(); + assertThat(lostPermitRecovery.snapshot().dispatchAttempts()).isEqualTo(1); + + assertThat(tx(database, () -> journal.recordAmbiguous(handoff)).status()) + .isEqualTo(Status.AMBIGUOUS); + var retryPermit = tx(database, () -> journal.authorizeDispatch(handoff)); + assertThat(retryPermit.newlyAuthorized()).isTrue(); + assertThat(retryPermit.snapshot().dispatchAttempts()).isEqualTo(2); + + DisclosureResult mismatchedBindingResult = + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + HostedTermsEncoding.digest(new byte[] {42}), + Outcome.DISCLOSED, + "test-only-mismatched-owner-readback".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> tx(database, () -> journal.recordResult(handoff, mismatchedBindingResult))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not bound to the exact handoff"); + var afterMismatchedBinding = tx(database, () -> journal.read(handoff.handoffId())); + assertThat(afterMismatchedBinding).isPresent(); + assertThat(afterMismatchedBinding.orElseThrow().status()).isEqualTo(Status.DISPATCH_AUTHORIZED); + assertThat(afterMismatchedBinding.orElseThrow().result()).isEmpty(); + + byte[] testOnlyOwnerReadback = + "test-only-authenticated-disclosure-receipt".getBytes(StandardCharsets.UTF_8); + DisclosureResult result = + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + HostedTermsEncoding.digest(handoff.canonicalBytes()), + Outcome.DISCLOSED, + testOnlyOwnerReadback); + var disclosed = tx(database, () -> journal.recordResult(handoff, result)); + assertThat(disclosed.status()).isEqualTo(Status.DISCLOSED); + assertThat(disclosed.result().orElseThrow().canonicalBytes()) + .containsExactly(result.canonicalBytes()); + var resultRetry = tx(database, () -> journal.recordResult(handoff, result)); + assertThat(resultRetry.result().orElseThrow().canonicalBytes()) + .containsExactly(result.canonicalBytes()); + Database restarted = reopen(database); + var restartedRead = + tx( + restarted, + () -> + new HostedTermsDisclosureHandoffRepository( + restarted.dsl(), new DraftAuthorizationFenceRepository(restarted.dsl())) + .read(handoff.handoffId())); + assertThat(restartedRead).isPresent(); + assertThat(restartedRead.orElseThrow().status()).isEqualTo(Status.DISCLOSED); + assertThat(restartedRead.orElseThrow().handoff().canonicalBytes()) + .containsExactly(handoff.canonicalBytes()); + + DisclosureResult changedResult = + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + HostedTermsEncoding.digest(handoff.canonicalBytes()), + Outcome.DISCLOSED, + "test-only-changed-owner-readback".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> tx(database, () -> journal.recordResult(handoff, changedResult))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed terminal"); + assertThatThrownBy( + () -> + tx( + database, + () -> { + database + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs " + + "SET result_payload = ? WHERE handoff_id = ?", + "test-only-overwrite".getBytes(StandardCharsets.UTF_8), + handoff.handoffId()); + return null; + })) + .isInstanceOf(DataAccessException.class); + + HostedTermsDisclosureHandoff noDisclosure = handoff(source("definitive-no-disclosure")); + tx(database, () -> journal.prepare(noDisclosure)); + assertThatThrownBy( + () -> + tx( + database, + () -> + journal.recordResult( + noDisclosure, + new DisclosureResult( + noDisclosure.handoffId(), + noDisclosure.requestId(), + HostedTermsEncoding.digest(noDisclosure.canonicalBytes()), + Outcome.DEFINITIVELY_NOT_DISCLOSED, + "test-only-premature-negative".getBytes(StandardCharsets.UTF_8))))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("dispatch authorization"); + tx(database, () -> journal.authorizeDispatch(noDisclosure)); + tx(database, () -> journal.recordAmbiguous(noDisclosure)); + DisclosureResult negativeResult = + new DisclosureResult( + noDisclosure.handoffId(), + noDisclosure.requestId(), + HostedTermsEncoding.digest(noDisclosure.canonicalBytes()), + Outcome.DEFINITIVELY_NOT_DISCLOSED, + "test-only-authenticated-definitive-no-disclosure".getBytes(StandardCharsets.UTF_8)); + var noDisclosureSnapshot = + tx(database, () -> journal.recordResult(noDisclosure, negativeResult)); + assertThat(noDisclosureSnapshot.status()).isEqualTo(Status.DEFINITIVELY_NOT_DISCLOSED); + assertThat(noDisclosureSnapshot.handoff().effectiveAt()).isEqualTo(noDisclosure.effectiveAt()); + assertThat(noDisclosureSnapshot.result().orElseThrow().canonicalBytes()) + .containsExactly(negativeResult.canonicalBytes()); + } + + @Test + void preparationRefusesReservedAndUnsettledCommitOrderWithoutRewritingEither() throws Exception { + Database database = database(); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(database.dsl()); + HostedTermsDisclosureHandoffRepository journal = + new HostedTermsDisclosureHandoffRepository(database.dsl(), fences); + SourceEvidence source = source("fenced-operation"); + DraftAuthorizationFenceBinding original = draftBinding(source); + HostedTermsDisclosureHandoff handoff = handoff(source); + + tx(database, () -> fences.reserve(original)); + assertThatThrownBy(() -> tx(database, () -> journal.prepare(handoff))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unsettled original Draft operation"); + assertThat(tx(database, () -> fences.read(original).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.RESERVED); + + tx(database, () -> fences.claimCommitOrder(original)); + assertThatThrownBy(() -> tx(database, () -> journal.prepare(handoff))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unsettled original Draft operation"); + assertThat(tx(database, () -> fences.read(original).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER); + + tx( + database, + () -> { + recordOwnerResult(fences, original, Owner.GAME_DESIGN); + return null; + }); + tx( + database, + () -> { + recordOwnerResult(fences, original, Owner.WORLD); + return null; + }); + var prepared = tx(database, () -> journal.prepare(handoff)); + assertThat(prepared.status()).isEqualTo(Status.PREPARED); + assertThat(tx(database, () -> fences.read(original).ordering())) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER); + } + + private static void recordOwnerResult( + DraftAuthorizationFenceRepository fences, + DraftAuthorizationFenceBinding binding, + Owner owner) { + fences.recordOwnerReadback( + binding, + new OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + "test-only-owner-result".getBytes(StandardCharsets.UTF_8))); + } + + private static SourceEvidence source(String scopeSuffix) { + return new SourceEvidence( + SourceKind.HOSTED_TERMS, + UUID.nameUUIDFromBytes(scopeSuffix.getBytes(StandardCharsets.UTF_8)).toString(), + null, + "7", + null, + null, + ("test-only-source-evidence-" + scopeSuffix).getBytes(StandardCharsets.UTF_8)); + } + + private static HostedTermsDisclosureHandoff handoff(SourceEvidence source) { + return new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + source.key(), + HostedTermsEncoding.digest("test-only-predecessor".getBytes(StandardCharsets.UTF_8)), + HostedTermsEncoding.digest("test-only-candidate".getBytes(StandardCharsets.UTF_8)), + Instant.parse("2026-10-08T00:00:00Z"), + List.of(source), + "test-only-authority-evidence".getBytes(StandardCharsets.UTF_8)); + } + + private static DraftAuthorizationFenceBinding draftBinding(SourceEvidence source) { + UUID actor = UUID.randomUUID(); + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "test-only-tenant-key", + 2, + "test-only-tenant-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "test-only-base-commit", + List.of( + new RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "payload")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + actor, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "1", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of(source)); + } + + private static Database database() throws Exception { + String schema = "terms_disclosure_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl() + + (postgres.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema, + postgres.getUsername(), + postgres.getPassword()); + try (Connection connection = source.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA " + schema); + } + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(source); + Database database = + new Database( + schema, + source, + DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), + transactionManager, + new TransactionTemplate(transactionManager)); + Flyway.configure() + .dataSource(database.source()) + .schemas(database.schema()) + .defaultSchema(database.schema()) + .placeholders(Map.of("serviceSchema", database.schema())) + .locations("classpath:db/migration") + .target("101") + .load() + .migrate(); + return database; + } + + private static Database reopen(Database original) { + DataSourceTransactionManager transactionManager = + new DataSourceTransactionManager(original.source()); + return new Database( + original.schema(), + original.source(), + DSL.using(new TransactionAwareDataSourceProxy(original.source()), SQLDialect.POSTGRES), + transactionManager, + new TransactionTemplate(transactionManager)); + } + + private static T tx(Database database, Supplier work) { + return database.transactions().execute(status -> work.get()); + } + + private record Database( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + PlatformTransactionManager transactionManager, + TransactionTemplate transactions) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java index a29c25931f..86474d316f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java @@ -785,6 +785,9 @@ void persistsProtectedV2PodClosureAndRequiresFreshExactInventoryForPromotion() t assertThat(inventoryReadback.entries()).containsExactlyElementsOf(plan.entries()); assertThat(plan.planVersion()).isEqualTo(2); assertThat(plan.validatorInventoryComplete()).isTrue(); + assertThat( + JSON.readTree(plan.applicabilityMatrixJson()).path("source").path("clusterId").asText()) + .isEqualTo(BINDING.clusterId()); assertThat(plan.expectedFence().durableActive()).isEmpty(); assertThat(plan.entries()).allSatisfy(entry -> assertThat(entry.expectedActive()).isEmpty()); assertThat(plan.entries()) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessIsolatedGrpcRoutingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessIsolatedGrpcRoutingTest.java new file mode 100644 index 0000000000..6faddd5a9c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessIsolatedGrpcRoutingTest.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import io.grpc.ServerInterceptor; +import io.grpc.ServerServiceDefinition; +import io.grpc.TlsServerCredentials; +import java.util.List; +import net.firedevops.firemud.account.v1.AccountJwtReadinessPodReceiverServiceGrpc; +import net.firedevops.firemud.account.v1.AccountJwtReadinessProbeOwnerServiceGrpc; +import net.firedevops.firemud.account.v1.AccountJwtSignerMaterializationServiceGrpc; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtReadinessPodReceiverGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtReadinessProbeOwnerGrpcService; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.ShadedNettyGrpcServerFactory; +import org.springframework.grpc.server.service.GrpcService; + +class AccountJwtReadinessIsolatedGrpcRoutingTest { + private final ApplicationContextRunner routingRunner = + new ApplicationContextRunner() + .withUserConfiguration(AccountJwtReadinessIsolatedGrpcRoutingConfiguration.class); + private final ApplicationContextRunner contextRunner = + new ApplicationContextRunner() + .withUserConfiguration( + AccountJwtReadinessProbeOwnerGrpcService.class, + AccountJwtReadinessPodReceiverGrpcService.class); + + @Test + void bothAdaptersUseOnlyThePeerIdentityInterceptor() { + assertIsolatedGrpcService(AccountJwtReadinessProbeOwnerGrpcService.class); + assertIsolatedGrpcService(AccountJwtReadinessPodReceiverGrpcService.class); + } + + @Test + void bothAdaptersRemainUnregisteredByDefault() { + contextRunner.run( + context -> + assertThat(context) + .doesNotHaveBean(AccountJwtReadinessProbeOwnerGrpcService.class) + .doesNotHaveBean(AccountJwtReadinessPodReceiverGrpcService.class)); + } + + @Test + void disabledRoutingLeavesExistingFactoryFilteringAndUnsupportedFactoriesAlone() { + routingRunner.run( + context -> { + var customizer = context.getBean(GrpcServerFactoryCustomizer.class); + var factory = factory(); + factory.setInterceptorFilter((interceptor, service) -> false); + customizer.customize(factory); + assertThat( + factory.supports(mock(ServerInterceptor.class), definition("ordinary.Service"))) + .isFalse(); + customizer.customize(mock(GrpcServerFactory.class)); + }); + } + + @Test + void eachFlagFiltersOnlyItsExactServiceAndEnabledRoutingRejectsUnsupportedFactories() { + for (boolean owner : List.of(false, true)) { + for (boolean receiver : List.of(false, true)) { + for (boolean materialization : List.of(false, true)) { + routingRunner + .withPropertyValues( + "firemud.account.jwt-readiness.probe-owner.enabled=" + owner, + "firemud.account.jwt-readiness.pod-receiver.enabled=" + receiver, + "firemud.account.jwt-signer.materialization.enabled=" + materialization) + .run( + context -> { + var customizer = context.getBean(GrpcServerFactoryCustomizer.class); + var factory = factory(); + customizer.customize(factory); + var interceptor = mock(ServerInterceptor.class); + assertThat( + factory.supports( + interceptor, + definition(AccountJwtReadinessProbeOwnerServiceGrpc.SERVICE_NAME))) + .isEqualTo(!owner); + assertThat( + factory.supports( + interceptor, + definition(AccountJwtReadinessPodReceiverServiceGrpc.SERVICE_NAME))) + .isEqualTo(!receiver); + assertThat( + factory.supports( + interceptor, + definition( + AccountJwtSignerMaterializationServiceGrpc.SERVICE_NAME))) + .isEqualTo(!materialization); + assertThat(factory.supports(interceptor, definition("ordinary.Service"))) + .isTrue(); + assertThat( + factory.supports( + interceptor, + definition( + AccountJwtReadinessProbeOwnerServiceGrpc.SERVICE_NAME + + "Extra"))) + .isTrue(); + assertThat( + factory.supports( + interceptor, + definition( + AccountJwtSignerMaterializationServiceGrpc.SERVICE_NAME + + "Extra"))) + .isTrue(); + if (owner || receiver || materialization) { + assertThatThrownBy(() -> customizer.customize(mock(GrpcServerFactory.class))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("interceptor filtering"); + } else { + customizer.customize(mock(GrpcServerFactory.class)); + } + }); + } + } + } + } + + private static ShadedNettyGrpcServerFactory factory() { + return new ShadedNettyGrpcServerFactory( + "127.0.0.1:0", List.of(), null, null, TlsServerCredentials.ClientAuth.REQUIRE); + } + + private static ServerServiceDefinition definition(String name) { + return ServerServiceDefinition.builder(name).build(); + } + + private static void assertIsolatedGrpcService(Class serviceType) { + GrpcService grpcService = serviceType.getAnnotation(GrpcService.class); + ConditionalOnProperty property = serviceType.getAnnotation(ConditionalOnProperty.class); + + assertThat(grpcService).isNotNull(); + assertThat(grpcService.interceptorNames()).containsExactly("grpcPeerIdentityInterceptor"); + assertThat(grpcService.blendWithGlobalInterceptors()).isFalse(); + assertThat(property).isNotNull(); + assertThat(property.name()).containsExactly("enabled"); + assertThat(property.havingValue()).isEqualTo("true"); + assertThat(property.matchIfMissing()).isFalse(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializationCompositionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializationCompositionTest.java new file mode 100644 index 0000000000..6751ef0aff --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializationCompositionTest.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerMethodDefinition; +import io.grpc.Status; +import io.grpc.TlsServerCredentials; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtSignerMaterializationService; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.MapPropertySource; +import org.springframework.grpc.server.GlobalServerInterceptor; +import org.springframework.grpc.server.ShadedNettyGrpcServerFactory; +import org.springframework.grpc.server.service.DefaultGrpcServiceConfigurer; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.grpc.server.service.GrpcServiceInfo; +import org.springframework.grpc.server.service.GrpcServiceSpec; +import org.springframework.transaction.PlatformTransactionManager; + +/** Exercises Spring's interceptor composition without starting a server or supplying a bearer. */ +class AccountJwtSignerMaterializationCompositionTest { + @Test + void missingProtectedBindingReachesTheExactTlsGuardForAllSixMethodsWithoutGlobalJwt() { + assertDeniedForEveryMethod(new AccountJwtSignerMaterializerTrustBinding(true, "")); + } + + @Test + void configuredProtectedBindingWithoutTlsPeerReachesTheExactGuardWithoutGlobalJwt() { + var bindingProvider = mock(AccountJwtSignerMaterializerTrustBinding.class); + var binding = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer", + List.of("a".repeat(64)), + "revision-1", + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + "revision-1", + "prod", + "prod-cluster-1", + "firemud-prod", + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer", + List.of("a".repeat(64)))); + when(bindingProvider.current()).thenReturn(Optional.of(binding)); + assertDeniedForEveryMethod(bindingProvider); + } + + private static void assertDeniedForEveryMethod( + AccountJwtSignerMaterializerTrustBinding bindingProvider) { + try (var context = new AnnotationConfigApplicationContext()) { + context + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "materialization-composition-test", + Map.of("firemud.account.jwt-signer.materialization.enabled", "true"))); + context.registerBean(AccountJwtSignerMaterializerTrustBinding.class, () -> bindingProvider); + context.register( + AccountJwtReadinessIsolatedGrpcRoutingConfiguration.class, MiddlewareConfiguration.class); + context.refresh(); + + var repository = mock(AccountJwtSignerDesiredStateRepository.class); + var readinessRepository = mock(AccountJwtReadinessProbeRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var service = + new AccountJwtSignerMaterializationService( + repository, readinessRepository, bindingProvider, transactions); + var annotation = + AccountJwtSignerMaterializationService.class.getAnnotation(GrpcService.class); + assertThat(annotation.interceptorNames()) + .containsExactly("accountJwtSignerMaterializerTlsInterceptor"); + var factory = + new ShadedNettyGrpcServerFactory( + "127.0.0.1:0", List.of(), null, null, TlsServerCredentials.ClientAuth.REQUIRE); + context.getBean(GrpcServerFactoryCustomizer.class).customize(factory); + var configurer = new DefaultGrpcServiceConfigurer(context); + configurer.afterPropertiesSet(); + var definition = + configurer.configure( + new GrpcServiceSpec(service, GrpcServiceInfo.from(annotation)), factory); + var tls = context.getBean(AccountJwtSignerMaterializerTlsInterceptor.class); + var jwt = context.getBean(AuthTokenInterceptor.class); + + assertThat(definition.getMethods()).hasSize(6); + for (var method : definition.getMethods()) { + clearInvocations(tls); + assertStartDenied(method, Status.Code.PERMISSION_DENIED); + verify(tls).interceptCall(any(), any(), any()); + verify(jwt, never()).interceptCall(any(), any(), any()); + } + verifyNoInteractions(repository, readinessRepository, transactions); + + var ordinary = + configurer.configure( + new GrpcServiceSpec(new AccountServiceGrpc.AccountServiceImplBase() {}, null), + factory); + assertStartDenied(ordinary.getMethods().iterator().next(), Status.Code.UNAUTHENTICATED); + verify(jwt).interceptCall(any(), any(), any()); + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static void assertStartDenied(ServerMethodDefinition method, Status.Code expected) { + ServerCall call = mock(ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(method.getMethodDescriptor()); + when(call.getAttributes()).thenReturn(Attributes.EMPTY); + method.getServerCallHandler().startCall(call, new Metadata()); + var status = ArgumentCaptor.forClass(Status.class); + verify(call).close(status.capture(), any(Metadata.class)); + assertThat(status.getValue().getCode()).isEqualTo(expected); + } + + @Configuration(proxyBeanMethods = false) + static class MiddlewareConfiguration { + @Bean + AccountJwtSignerMaterializerTlsInterceptor accountJwtSignerMaterializerTlsInterceptor( + AccountJwtSignerMaterializerTrustBinding bindingProvider) { + return spy(new AccountJwtSignerMaterializerTlsInterceptor(bindingProvider)); + } + + @Bean + @GlobalServerInterceptor + AuthTokenInterceptor authTokenInterceptor() { + return spy(new AuthTokenInterceptor(mock(JwtUtil.class))); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.java new file mode 100644 index 0000000000..9cf194dec4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.java @@ -0,0 +1,217 @@ +package unit.net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.DisclosureResult; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Kind; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Outcome; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.junit.jupiter.api.Test; + +class HostedTermsDisclosureHandoffTest { + @Test + void canonicalBindingSortsCompleteSourceVectorAndCopiesEveryArray() { + byte[] hostedEvidence = new byte[] {1, 2, 3}; + byte[] tenantEvidence = new byte[] {4, 5, 6}; + SourceEvidence hosted = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + UUID.randomUUID().toString(), + null, + "7", + null, + null, + hostedEvidence); + SourceEvidence tenant = + new SourceEvidence( + SourceKind.TENANT, UUID.randomUUID().toString(), "3", "8", null, null, tenantEvidence); + hostedEvidence[0] = 99; + tenantEvidence[0] = 99; + byte[] authorityBytes = "test-only-authority-evidence".getBytes(StandardCharsets.UTF_8); + HostedTermsDisclosureHandoff handoff = handoff(hosted, tenant, authorityBytes); + authorityBytes[0] = 99; + + assertThat(handoff.sources().stream().map(SourceEvidence::key).toList()) + .containsExactly(hosted.key(), tenant.key()); + assertThat(handoff.sources().getFirst().evidence()).containsExactly(1, 2, 3); + assertThat(handoff.authenticatedAuthorityEvidence()) + .containsExactly("test-only-authority-evidence".getBytes(StandardCharsets.UTF_8)); + + byte[] returned = handoff.authenticatedAuthorityEvidence(); + returned[0] = 88; + SourceEvidence returnedSource = handoff.sources().getFirst(); + byte[] returnedSourceBytes = returnedSource.evidence(); + returnedSourceBytes[0] = 77; + assertThat(handoff.authenticatedAuthorityEvidence()) + .containsExactly("test-only-authority-evidence".getBytes(StandardCharsets.UTF_8)); + assertThat(handoff.sources().getFirst().evidence()).containsExactly(1, 2, 3); + assertThat(HostedTermsDisclosureHandoff.fromStored(handoff.canonicalBytes()).canonicalBytes()) + .containsExactly(handoff.canonicalBytes()); + } + + @Test + void exactDigestBindsEveryDisclosureFieldAndRejectsChangedOrMalformedInputs() { + SourceEvidence source = hostedSource("source-v7"); + HostedTermsDisclosureHandoff original = + new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + source.key(), + HostedTermsEncoding.digest(new byte[] {1}), + HostedTermsEncoding.digest(new byte[] {2}), + Instant.parse("2026-10-08T00:00:00.123456Z"), + List.of(source), + "test-only-authority-evidence".getBytes(StandardCharsets.UTF_8)); + + String originalDigest = HostedTermsEncoding.digest(original.canonicalBytes()); + assertThat(originalDigest) + .isNotEqualTo(HostedTermsEncoding.digest(changed(original, "candidate").canonicalBytes())) + .isNotEqualTo(HostedTermsEncoding.digest(changed(original, "effectiveAt").canonicalBytes())) + .isNotEqualTo(HostedTermsEncoding.digest(changed(original, "requestId").canonicalBytes())) + .isNotEqualTo( + HostedTermsEncoding.digest(changed(original, "authorityEvidence").canonicalBytes())); + assertThatThrownBy( + () -> + new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + source.key(), + original.predecessorDigest(), + original.candidateDigest(), + Instant.parse("2026-10-08T00:00:00.123456789Z"), + List.of(source), + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("microsecond"); + assertThatThrownBy( + () -> + new HostedTermsDisclosureHandoff( + original.handoffId(), + original.requestId(), + original.kind(), + original.sourceKey(), + original.predecessorDigest(), + original.candidateDigest(), + original.effectiveAt(), + List.of(source, source), + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Distinct complete sorted source evidence"); + byte[] trailing = + java.util.Arrays.copyOf(original.canonicalBytes(), original.canonicalBytes().length + 1); + assertThatThrownBy(() -> HostedTermsDisclosureHandoff.fromStored(trailing)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void disclosureResultPreservesBindingDigestAndCopiesAuthenticatedBytes() { + SourceEvidence source = hostedSource("source-result"); + HostedTermsDisclosureHandoff handoff = handoff(source, null, new byte[] {9}); + byte[] evidence = "test-only-authenticated-owner-readback".getBytes(StandardCharsets.UTF_8); + DisclosureResult result = + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + HostedTermsEncoding.digest(handoff.canonicalBytes()), + Outcome.DISCLOSED, + evidence); + evidence[0] = 0; + + assertThat(result.authenticatedEvidence()) + .containsExactly("test-only-authenticated-owner-readback".getBytes(StandardCharsets.UTF_8)); + assertThat(DisclosureResult.fromStored(result.canonicalBytes()).canonicalBytes()) + .containsExactly(result.canonicalBytes()); + String changedBindingDigest = HostedTermsEncoding.digest(new byte[] {4}); + DisclosureResult changedBinding = + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + changedBindingDigest, + Outcome.DISCLOSED, + new byte[] {1}); + assertThat(changedBinding.bindingDigest()).isEqualTo(changedBindingDigest); + assertThat(changedBinding.canonicalBytes()).isNotEqualTo(result.canonicalBytes()); + } + + @Test + void environmentBindingUsesItsIndependentNamespacedHostedTermsSource() { + SourceEvidence boundary = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + "environment-boundary/production", + null, + "9", + null, + null, + new byte[] {6, 7}); + HostedTermsDisclosureHandoff handoff = + new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.ENVIRONMENT_BINDING, + boundary.key(), + HostedTermsEncoding.digest(new byte[] {4}), + HostedTermsEncoding.digest(new byte[] {5}), + Instant.parse("2026-10-08T00:00:00Z"), + List.of(boundary), + "test-only-authority-evidence".getBytes(StandardCharsets.UTF_8)); + assertThat(handoff.sourceKey()).isEqualTo("HOSTED_TERMS:environment-boundary/production"); + assertThat(HostedTermsDisclosureHandoff.fromStored(handoff.canonicalBytes()).kind()) + .isEqualTo(Kind.ENVIRONMENT_BINDING); + } + + private static HostedTermsDisclosureHandoff handoff( + SourceEvidence primary, SourceEvidence additional, byte[] authorityEvidence) { + return new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + primary.key(), + HostedTermsEncoding.digest(new byte[] {1}), + HostedTermsEncoding.digest(new byte[] {2}), + Instant.parse("2026-10-08T00:00:00.123456Z"), + additional == null ? List.of(primary) : List.of(additional, primary), + authorityEvidence); + } + + private static SourceEvidence hostedSource(String scope) { + return new SourceEvidence( + SourceKind.HOSTED_TERMS, + UUID.nameUUIDFromBytes(scope.getBytes(StandardCharsets.UTF_8)).toString(), + null, + "7", + null, + null, + new byte[] {3, 4, 5}); + } + + private static HostedTermsDisclosureHandoff changed( + HostedTermsDisclosureHandoff original, String field) { + return new HostedTermsDisclosureHandoff( + original.handoffId(), + field.equals("requestId") ? UUID.randomUUID() : original.requestId(), + original.kind(), + original.sourceKey(), + original.predecessorDigest(), + field.equals("candidate") + ? HostedTermsEncoding.digest(new byte[] {3}) + : original.candidateDigest(), + field.equals("effectiveAt") + ? original.effectiveAt().plusSeconds(1) + : original.effectiveAt(), + original.sources(), + field.equals("authorityEvidence") + ? new byte[] {42} + : original.authenticatedAuthorityEvidence()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java index 45554c3931..82289cf376 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java @@ -1,34 +1,52 @@ package unit.net.firedevops.firemud.accountservice.service.impl; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import io.grpc.Attributes; +import io.grpc.Grpc; import io.grpc.Metadata; import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; import io.grpc.Status; +import io.grpc.TlsServerCredentials; import io.grpc.stub.StreamObserver; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessIsolatedGrpcRoutingConfiguration; import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerWorkloadGuard; import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; import net.firedevops.firemud.accountservice.service.impl.AccountJwtReadinessProbeOwnerGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerProtoMapper; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerService; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.MapPropertySource; import org.springframework.grpc.server.GlobalServerInterceptor; +import org.springframework.grpc.server.ShadedNettyGrpcServerFactory; import org.springframework.grpc.server.service.DefaultGrpcServiceConfigurer; import org.springframework.grpc.server.service.GrpcService; import org.springframework.grpc.server.service.GrpcServiceInfo; @@ -36,27 +54,74 @@ class AccountJwtReadinessProbeOwnerGrpcServiceTest { @Test - void ownerLookupIsIndependentlyDefaultDeniedAndUsesTheGlobalPeerIdentityInterceptor() { + void ownerLookupIsIndependentlyDefaultDeniedAndUsesTheExactPeerIdentityInterceptor() + throws Exception { GrpcService grpc = AccountJwtReadinessProbeOwnerGrpcService.class.getAnnotation(GrpcService.class); assertThat(grpc).isNotNull(); - assertThat(grpc.interceptorNames()).isEmpty(); + assertThat(grpc.interceptorNames()).containsExactly("grpcPeerIdentityInterceptor"); assertThat(grpc.interceptors()).isEmpty(); - - try (AnnotationConfigApplicationContext context = - new AnnotationConfigApplicationContext(GlobalPeerIdentityConfiguration.class)) { + assertThat(grpc.blendWithGlobalInterceptors()).isFalse(); + + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { + context + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "isolated-readiness-test", + Map.of("firemud.account.jwt-readiness.probe-owner.enabled", "true"))); + context.register( + GlobalPeerIdentityConfiguration.class, + AccountJwtReadinessIsolatedGrpcRoutingConfiguration.class); + context.refresh(); DefaultGrpcServiceConfigurer configurer = new DefaultGrpcServiceConfigurer(context); configurer.afterPropertiesSet(); - var service = - new AccountJwtReadinessProbeOwnerGrpcService( - mock(AccountJwtReadinessProbeOwnerService.class)); + var factory = + new ShadedNettyGrpcServerFactory( + "127.0.0.1:0", List.of(), null, null, TlsServerCredentials.ClientAuth.REQUIRE); + context.getBean(GrpcServerFactoryCustomizer.class).customize(factory); + var owner = mock(AccountJwtReadinessProbeOwnerService.class); + AtomicReference observedPeer = new AtomicReference<>(); + doAnswer( + invocation -> { + observedPeer.set(GrpcPeerIdentity.current()); + return GetCurrentReadinessProbeOwnerResponse.getDefaultInstance(); + }) + .when(owner) + .getCurrentReadinessProbeOwner(org.mockito.ArgumentMatchers.any()); + var service = new AccountJwtReadinessProbeOwnerGrpcService(owner); var serviceDefinition = - configurer.configure(new GrpcServiceSpec(service, GrpcServiceInfo.from(grpc)), null); + configurer.configure(new GrpcServiceSpec(service, GrpcServiceInfo.from(grpc)), factory); var methodDefinition = serviceDefinition.getMethods().iterator().next(); ServerCall serverCall = mock(ServerCall.class); when(serverCall.getMethodDescriptor()).thenReturn(methodDefinition.getMethodDescriptor()); - methodDefinition.getServerCallHandler().startCall(serverCall, new Metadata()); - + String peerUri = "spiffe://firemud/ns/firemud-prod/sa/game-session-service"; + X509Certificate certificate = mock(X509Certificate.class); + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, peerUri))); + SSLSession sslSession = mock(SSLSession.class); + when(sslSession.getPeerCertificates()).thenReturn(new Certificate[] {certificate}); + when(serverCall.getAttributes()) + .thenReturn( + Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession).build()); + ServerCall.Listener listener = + methodDefinition.getServerCallHandler().startCall(serverCall, new Metadata()); + listener.onMessage(GetCurrentReadinessProbeOwnerRequest.getDefaultInstance()); + listener.onHalfClose(); + + assertThat(context.getBean(GlobalPeerIdentityMarker.class).invocations()).hasValue(0); + assertThat(observedPeer.get()).isEqualTo(GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); + verify(sslSession, times(1)).getPeerCertificates(); + + var ordinary = + configurer.configure( + new GrpcServiceSpec(new AccountServiceGrpc.AccountServiceImplBase() {}, null), + factory); + var ordinaryMethod = ordinary.getMethods().iterator().next(); + ServerCall ordinaryCall = mock(ServerCall.class); + when(ordinaryCall.getMethodDescriptor()).thenReturn(ordinaryMethod.getMethodDescriptor()); + when(ordinaryCall.getAttributes()).thenReturn(Attributes.EMPTY); + ordinaryMethod.getServerCallHandler().startCall(ordinaryCall, new Metadata()); assertThat(context.getBean(GlobalPeerIdentityMarker.class).invocations()).hasValue(1); } @@ -122,6 +187,12 @@ public void onCompleted() { @Configuration(proxyBeanMethods = false) static class GlobalPeerIdentityConfiguration { + @Bean + @GlobalServerInterceptor + GrpcPeerIdentityInterceptor grpcPeerIdentityInterceptor() { + return new GrpcPeerIdentityInterceptor(); + } + @Bean @GlobalServerInterceptor GlobalPeerIdentityMarker globalPeerIdentityMarker() { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java index 22204bd2cf..67d9922093 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java @@ -15,6 +15,10 @@ import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyStore; @@ -241,23 +245,70 @@ void loopbackMtlsInvocationRejectsStructurallyValidOtherAccountSourceCluster() t } @Test - void matchingLoopbackMtlsResponseYieldsOnlyNonAuthorizingAcceptanceEvidence() throws Exception { + void remoteAddressObservationRequiresOneExactResolvedSocket() { + InetSocketAddress expected = new InetSocketAddress("127.0.0.1", 43127); + InetSocketAddress other = new InetSocketAddress("127.0.0.2", 43127); + + var missing = new AccountJwtReadinessGrpcReceiverInvocationPort.RemoteAddressObservation(); + assertThat(missing.matches(expected)).isFalse(); + + var exact = new AccountJwtReadinessGrpcReceiverInvocationPort.RemoteAddressObservation(); + exact.observe(expected); + assertThat(exact.matches(expected)).isTrue(); + + var absentThenPresent = + new AccountJwtReadinessGrpcReceiverInvocationPort.RemoteAddressObservation(); + absentThenPresent.observe(null); + absentThenPresent.observe(expected); + assertThat(absentThenPresent.matches(expected)).isFalse(); + + var mismatched = new AccountJwtReadinessGrpcReceiverInvocationPort.RemoteAddressObservation(); + mismatched.observe(other); + assertThat(mismatched.matches(expected)).isFalse(); + + var changed = new AccountJwtReadinessGrpcReceiverInvocationPort.RemoteAddressObservation(); + changed.observe(expected); + changed.observe(other); + changed.observe(expected); + assertThat(changed.matches(expected)).isFalse(); + } + + @Test + void matchingLoopbackMtlsResponseUsesDirectSocketDespiteJvmProxySelector() throws Exception { AtomicReference currentInvocation = new AtomicReference<>(); startSourceIdentityServer(pki.pinnedServer(), pki.trustedCa(), currentInvocation, false); Invocation invocation = invocation(pki.pinnedServer(), server.getPort()); currentInvocation.set(invocation); - var acceptance = port(pki.accountClient(), pki.trustedCa()).invoke(invocation); - - assertThat(acceptance.jti()).isEqualTo(invocation.jti()); - assertThat(acceptance.compactTokenSha256()).isEqualTo(invocation.compactTokenSha256()); - assertThat(acceptance.verifiedKid()).isEqualTo(invocation.targetKid()); - assertThat(acceptance.podUid()).isEqualTo(invocation.target().podUid()); - assertThat(acceptance.actualServiceUri()).isEqualTo(PEER_URI); - assertThat(acceptance.actualPeerSpkiSha256()) - .isEqualTo(invocation.target().podLeafSpkiSha256().orElseThrow()); - assertThat(acceptance.result()).isEqualTo(ProbeExpectation.ACCEPT); - assertThat(handlerCalls.get()).isEqualTo(1); + ProxySelector previousProxySelector = ProxySelector.getDefault(); + AtomicInteger proxySelectorCalls = new AtomicInteger(); + ProxySelector.setDefault( + new ProxySelector() { + @Override + public List select(URI uri) { + proxySelectorCalls.incrementAndGet(); + return List.of(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 1))); + } + + @Override + public void connectFailed(URI uri, SocketAddress socketAddress, IOException failure) {} + }); + try { + var acceptance = port(pki.accountClient(), pki.trustedCa()).invoke(invocation); + + assertThat(acceptance.jti()).isEqualTo(invocation.jti()); + assertThat(acceptance.compactTokenSha256()).isEqualTo(invocation.compactTokenSha256()); + assertThat(acceptance.verifiedKid()).isEqualTo(invocation.targetKid()); + assertThat(acceptance.podUid()).isEqualTo(invocation.target().podUid()); + assertThat(acceptance.actualServiceUri()).isEqualTo(PEER_URI); + assertThat(acceptance.actualPeerSpkiSha256()) + .isEqualTo(invocation.target().podLeafSpkiSha256().orElseThrow()); + assertThat(acceptance.result()).isEqualTo(ProbeExpectation.ACCEPT); + assertThat(proxySelectorCalls).hasValue(0); + assertThat(handlerCalls.get()).isEqualTo(1); + } finally { + ProxySelector.setDefault(previousProxySelector); + } } private void startServer(TestCertificate serverCertificate, Path trustedCa) throws Exception { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java index 31b761fa9b..37b986e7f1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ReplicaSetObservation; import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; import net.firedevops.firemud.common.security.AccountPublicJwksCache; import org.junit.jupiter.api.Test; @@ -75,23 +76,83 @@ void refusesWhenActualSslBundleLeafDoesNotMatchProtectedPodPin() throws Exceptio AccountJwtReadinessPodLocalIdentityProvider.IdentityUnavailableException.class); } + @Test + void refusesWhenLocalPodHasNoMatchingReplicaSet() throws Exception { + Fixture fixture = new Fixture(false); + when(fixture.validator.replicaSets()).thenReturn(List.of()); + + assertIdentityUnavailable(fixture); + } + + @Test + void refusesWhenLocalPodOwnerUidDoesNotMatchReplicaSet() throws Exception { + Fixture fixture = new Fixture(false); + when(fixture.pod.ownerUid()).thenReturn("66666666-6666-4666-8666-666666666666"); + + assertIdentityUnavailable(fixture); + } + + @Test + void refusesWhenLocalPodOwnerNameDoesNotMatchReplicaSet() throws Exception { + Fixture fixture = new Fixture(false); + when(fixture.pod.ownerName()).thenReturn("different-replicaset"); + + assertIdentityUnavailable(fixture); + } + + @Test + void refusesWhenReplicaSetOwnerNamesWrongDeployment() throws Exception { + Fixture fixture = new Fixture(false); + when(fixture.replicaSet.ownerDeploymentUid()) + .thenReturn("66666666-6666-4666-8666-666666666666"); + + assertIdentityUnavailable(fixture); + } + + @Test + void refusesDuplicateMatchingReplicaSetObservations() throws Exception { + Fixture fixture = new Fixture(false); + when(fixture.validator.replicaSets()) + .thenReturn(List.of(fixture.replicaSet, fixture.replicaSet)); + + assertIdentityUnavailable(fixture); + } + + @Test + void refusesPodMockWhoseOwnerIsDeploymentInsteadOfReplicaSet() throws Exception { + Fixture fixture = new Fixture(false); + when(fixture.pod.ownerName()).thenReturn("account-service"); + when(fixture.pod.ownerUid()).thenReturn(Fixture.DEPLOYMENT_UID); + + assertIdentityUnavailable(fixture); + } + + private static void assertIdentityUnavailable(Fixture fixture) { + assertThatThrownBy(() -> fixture.provider.observe("c".repeat(64))) + .isInstanceOf( + AccountJwtReadinessPodLocalIdentityProvider.IdentityUnavailableException.class); + } + private static final class Fixture { private static final String POD_UID = "33333333-3333-4333-8333-333333333333"; private static final String DEPLOYMENT_UID = "44444444-4444-4444-8444-444444444444"; + private static final String REPLICA_SET_UID = "77777777-7777-4777-8777-777777777777"; + private static final String TEMPLATE_HASH = "account12345"; private final byte[] encodedPublicKey = "test server public key".getBytes(java.nio.charset.StandardCharsets.US_ASCII); private final String leafSpki = sha256(encodedPublicKey); private final AccountJwtValidatorInventorySource inventorySource = mock(AccountJwtValidatorInventorySource.class); private final InventorySnapshot inventory = mock(InventorySnapshot.class); + private final ValidatorObservation validator = mock(ValidatorObservation.class); + private final PodObservation pod = mock(PodObservation.class); + private final ReplicaSetObservation replicaSet = mock(ReplicaSetObservation.class); private final AccountJwtJwksTrustedSource trustedSource = mock(AccountJwtJwksTrustedSource.class); private final SslBundles sslBundles = mock(SslBundles.class); private final AccountJwtReadinessPodLocalIdentityProvider provider; private Fixture(boolean mismatchProtectedLeafPin) throws Exception { - ValidatorObservation validator = mock(ValidatorObservation.class); - PodObservation pod = mock(PodObservation.class); when(inventory.validators()).thenReturn(List.of(validator)); when(inventory.environmentId()).thenReturn("prod"); when(inventory.clusterId()).thenReturn("cluster-a"); @@ -111,16 +172,25 @@ private Fixture(boolean mismatchProtectedLeafPin) throws Exception { .map(value -> new ProfileExpectation(value.profile(), value.audience())) .toList()); when(validator.pods()).thenReturn(List.of(pod)); + when(validator.replicaSets()).thenReturn(List.of(replicaSet)); when(pod.name()).thenReturn("account-0"); when(pod.uid()).thenReturn(POD_UID); - when(pod.ownerName()).thenReturn("account-service"); - when(pod.ownerUid()).thenReturn(DEPLOYMENT_UID); + when(pod.ownerName()).thenReturn("account-service-abcde"); + when(pod.ownerUid()).thenReturn(REPLICA_SET_UID); + when(pod.podTemplateHash()).thenReturn(TEMPLATE_HASH); when(pod.podIp()).thenReturn("10.0.0.12"); when(pod.endpoint()).thenReturn(URI.create("https://10.0.0.12:6565")); when(pod.receiverServiceUri()).thenReturn(URI_SAN); when(pod.image()).thenReturn("registry.example/account@sha256:" + "a".repeat(64)); when(pod.verifierConfigSha256()).thenReturn("b".repeat(64)); when(pod.leafSpkiSha256()).thenReturn(mismatchProtectedLeafPin ? "f".repeat(64) : leafSpki); + when(replicaSet.name()).thenReturn("account-service-abcde"); + when(replicaSet.uid()).thenReturn(REPLICA_SET_UID); + when(replicaSet.ownerDeploymentName()).thenReturn("account-service"); + when(replicaSet.ownerDeploymentUid()).thenReturn(DEPLOYMENT_UID); + when(replicaSet.podTemplateHash()).thenReturn(TEMPLATE_HASH); + when(replicaSet.image()).thenReturn("registry.example/account@sha256:" + "a".repeat(64)); + when(replicaSet.verifierConfigSha256()).thenReturn("b".repeat(64)); when(inventorySource.observe()).thenReturn(inventory); var sourceIdentity = diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java index 22e0167213..75654ed088 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java @@ -3,7 +3,7 @@ import java.util.Arrays; import java.util.Objects; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; -import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; @@ -16,7 +16,6 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; -import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; import org.jooq.DSLContext; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -84,11 +83,11 @@ public Reservation reserve( var operation = new GameDesignPublicationOperation(account, world); String workflowId = - FiremudWorkflowIds.workflowId( - TemporalVersionPublishWorkflow.WORKFLOW_FAMILY, - selection.target().gameDesignVersionTenantKey(), - "publish-request", - intent.publishRequestId()); + PublicationDigestRequestBinding.full( + selection.target().canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity(); if (!workflowId.equals(operation.workflowId()) || !selection.target().canonicalTenantId().equals(world.request().canonicalTenantId()) || !selection.target().canonicalVersionId().equals(world.request().canonicalVersionId()) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 711b3e5d12..4bfab791bf 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -11,6 +11,7 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; @@ -385,6 +386,15 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth candidate.setNotes("successful transaction proof"); candidate = versionRepository.save(candidate); var operation = reserveSelectedDraft(candidate, "successful transaction proof"); + assertThat(candidate.getTenantId()).isEqualTo(tenantId); + assertThat(candidate.getTenantId()).isNotEqualTo(candidate.getCanonicalTenantId().toString()); + assertThat(operation.workflowId()) + .isEqualTo( + PublicationDigestRequestBinding.full( + candidate.getCanonicalTenantId().toString(), + Long.toString(candidate.getId()), + operation.account().publishRequestId()) + .derivedWorkflowIdentity()); var selection = AuthoredDraftPublishSelection.fromStored( operation.account().input().selection().canonicalJson(), diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 4fb2c0a154..60ba945a68 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -84,6 +84,7 @@ dependencies { testFixturesCompileOnly(libs.testcontainers.postgresql) testFixturesCompileOnly(libs.testcontainers) testImplementation(libs.grpc.inprocess) + testImplementation(libs.bouncycastle.pkix) testImplementation(testFixtures(project(":game-session-service"))) testImplementation(project(":game-logic-service")) } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessIsolatedGrpcRoutingConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessIsolatedGrpcRoutingConfiguration.java new file mode 100644 index 0000000000..2f1dfbbf39 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessIsolatedGrpcRoutingConfiguration.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.gamesession.v1.GameSessionJwtReadinessReceiverServiceGrpc; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.grpc.server.DefaultGrpcServerFactory; + +/** Keeps the selected readiness receiver separate from global application middleware. */ +@Configuration(proxyBeanMethods = false) +public class GameSessionJwtReadinessIsolatedGrpcRoutingConfiguration { + @Bean + public GrpcServerFactoryCustomizer gameSessionJwtReadinessIsolatedGrpcRoutingCustomizer( + @Value("${firemud.game-session.jwt-readiness.receiver.enabled:false}") boolean enabled) { + return factory -> { + if (!enabled) { + return; + } + if (!(factory instanceof DefaultGrpcServerFactory supportedFactory)) { + throw new IllegalStateException( + "Isolated Game Session readiness requires interceptor filtering"); + } + // Explicitly named peer extraction is appended after this global-interceptor filter. + supportedFactory.setInterceptorFilter( + (interceptor, service) -> + !GameSessionJwtReadinessReceiverServiceGrpc.SERVICE_NAME.equals( + service.getServiceDescriptor().getName())); + }; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverGrpcService.java index de63c35fea..1b8f3df456 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverGrpcService.java @@ -15,7 +15,7 @@ import org.springframework.grpc.server.service.GrpcService; /** Default-inactive, non-authorizing receiver for one exact Game Session Pod. */ -@GrpcService +@GrpcService(interceptorNames = "grpcPeerIdentityInterceptor", blendWithGlobalInterceptors = false) @Lazy @ConditionalOnProperty( prefix = "firemud.game-session.jwt-readiness.receiver", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java new file mode 100644 index 0000000000..02b0b6d1e7 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java @@ -0,0 +1,856 @@ +package integration.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Channel; +import io.grpc.ClientInterceptors; +import io.grpc.ForwardingServerCall; +import io.grpc.ManagedChannel; +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.StreamObserver; +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.Signature; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.RSAKeyGenParameterSpec; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Base64; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountJwtReadinessProbeOwnerServiceGrpc; +import net.firedevops.firemud.account.v1.AccountPodTargetBinding; +import net.firedevops.firemud.account.v1.AccountSourceIdentity; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.config.GameSessionJwtReadinessProbeOwnerWorkloadGuard; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessLocalIdentityProvider; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProbeCrypto; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProbeOwnerClient; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverEngine; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverProtoMapper; +import net.firedevops.firemud.gamesession.service.impl.GameSessionJwtReadinessReceiverGrpcService; +import net.firedevops.firemud.gamesession.v1.GameSessionJwtReadinessReceiverServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeRequest; +import net.firedevops.firemud.gamesession.v1.ReceiveReadinessProbeResponse; +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 tools.jackson.databind.json.JsonMapper; + +/** + * Loopback mTLS proof of the isolated Account-to-Pod boundary and the production verification + * sequence. The Account owner response and protected local identity are explicitly test fixtures; + * neither establishes live provenance, current inventory, or deployed workload identity. + */ +class GameSessionJwtReadinessReceiverMtlsIntegrationTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/firemud-prod/sa/account-service"; + private static final String GAME_SESSION_URI = + "spiffe://firemud/ns/firemud-prod/sa/game-session-service"; + private static final String OTHER_WORKLOAD_URI = + "spiffe://firemud/ns/firemud-prod/sa/game-design-service"; + private static final String KID = "pending-key-7"; + private static final String RESERVED_SUBJECT = "00000000-0000-4000-8000-000000000001"; + private static final String DEPLOYMENT_UID = "33333333-3333-4333-8333-333333333333"; + private static final String POD_UID = "44444444-4444-4444-8444-444444444444"; + private static final String CLUSTER_INCARNATION_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final Instant NOW = Instant.parse("2030-06-01T00:10:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneId.of("UTC")); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final AtomicInteger CERTIFICATE_SERIAL = new AtomicInteger(1); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private Server gameSessionServer; + private Server accountOwnerServer; + private TestIdentityFiles accountClientFiles; + private TestIdentityFiles gameSessionFiles; + private Path caCertificateFile; + private final AtomicReference ownerResponseMode = + new AtomicReference<>(OwnerResponseMode.EXACT); + private final AtomicInteger ownerReadCalls = new AtomicInteger(); + private final AtomicReference lastOwnerRequest = + new AtomicReference<>(); + private final AtomicReference ownerSawPeerUri = new AtomicReference<>(); + private final AtomicReference ownerTarget = new AtomicReference<>(); + private final AtomicReference + localObservation = new AtomicReference<>(); + private final AtomicBoolean responseHadNoApplicationAuthContext = new AtomicBoolean(); + private KeyPair signingKey; + private AccountPublicJwksCache.SourceIdentity jwksSourceIdentity; + private ReadinessReceiverLocalIdentity localIdentity; + private AccountPodTargetBinding exactOwnerTarget; + private ReceiveReadinessProbeRequest validRequest; + private String validCompactJwt; + + @BeforeAll + static void createTestCertificates() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair authority = rsaKeyPair(2048); + X500Name authorityName = new X500Name("CN=Game Session readiness test CA, O=FireMUD Test"); + X509Certificate caCertificate = + issueCertificate( + authorityName, + authority.getPublic(), + authorityName, + authority.getPrivate(), + true, + null); + pki = + new TestPki( + caCertificate, + issueLeaf(authorityName, authority.getPrivate(), ACCOUNT_URI), + issueLeaf(authorityName, authority.getPrivate(), GAME_SESSION_URI), + issueLeaf(authorityName, authority.getPrivate(), OTHER_WORKLOAD_URI), + issueLeaf(authorityName, authority.getPrivate(), null)); + } + + @BeforeEach + void startIsolatedTransports() throws Exception { + ownerResponseMode.set(OwnerResponseMode.EXACT); + ownerReadCalls.set(0); + lastOwnerRequest.set(null); + ownerSawPeerUri.set(null); + ownerTarget.set(null); + localObservation.set(null); + responseHadNoApplicationAuthContext.set(false); + + caCertificateFile = writePem("readiness-test-ca.crt", "CERTIFICATE", pki.caCertificate()); + accountClientFiles = writeIdentityFiles("account", pki.account()); + gameSessionFiles = writeIdentityFiles("game-session", pki.gameSession()); + accountOwnerServer = startAccountOwnerServer(); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + accountOwnerServer.getPort()); + GameSessionJwtReadinessProbeOwnerClient ownerClient = + new GameSessionJwtReadinessProbeOwnerClient( + endpoints, clientProperties(gameSessionFiles), new GrpcChannelFactory(), NAMESPACE); + + signingKey = rsaKeyPair(3072); + jwksSourceIdentity = sourceIdentity(); + String jwks = jwks(KID, (RSAPublicKey) signingKey.getPublic()); + AccountPublicJwksCache keyCache = + new AccountPublicJwksCache( + () -> + new AccountPublicJwksCache.PublicJwksSnapshot( + jwksSourceIdentity, jwks.getBytes(StandardCharsets.US_ASCII)), + jwksSourceIdentity, + CLOCK, + Duration.ofSeconds(300)); + GameSessionJwtReadinessProbeCrypto crypto = + new GameSessionJwtReadinessProbeCrypto( + new AccountAsymmetricJwtVerifier(keyCache, CLOCK), 8); + + GameSessionJwtReadinessReceiverProtoMapper mapper = + new GameSessionJwtReadinessReceiverProtoMapper(); + GameSessionJwtReadinessReceiverEngine engine = + new GameSessionJwtReadinessReceiverEngine( + new GameSessionJwtReadinessProbeOwnerWorkloadGuard(NAMESPACE), + localObservation::get, + ownerClient, + mapper, + crypto, + CLOCK); + var receiverService = new GameSessionJwtReadinessReceiverGrpcService(engine); + gameSessionServer = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(serverTlsContext(gameSessionFiles)) + .addService( + ServerInterceptors.intercept( + receiverService, + new GrpcPeerIdentityInterceptor(), + applicationAuthContextProbe())) + .build() + .start(); + + localIdentity = localIdentity(gameSessionServer.getPort()); + exactOwnerTarget = ownerTarget(localIdentity); + localObservation.set( + new GameSessionJwtReadinessLocalIdentityProvider.LocalObservation( + localIdentity, jwksSourceIdentity)); + ownerTarget.set(exactOwnerTarget); + UUID jti = UUID.randomUUID(); + long issuedAt = NOW.getEpochSecond() - 1L; + ReadinessProbeCoordinates coordinates = coordinates(jti, issuedAt); + validCompactJwt = signedDelegationToken(jti, issuedAt); + validRequest = request(validCompactJwt, coordinates); + + assertThat(accountClientFiles.certificate()).isEqualTo(pki.account().certificate()); + } + + @AfterEach + void stopTransportsAndClearContext() throws Exception { + SessionContext.clear(); + stopServer(gameSessionServer); + gameSessionServer = null; + stopServer(accountOwnerServer); + accountOwnerServer = null; + } + + @Test + void accountMtlsCallUsesProductionOwnerReadAndRealProfileVerificationWithoutAuthSideEffects() + throws Exception { + ReceiveReadinessProbeResponse response = receive(pki.account(), validRequest); + + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getCoordinates()).isEqualTo(validRequest.getCoordinates()); + assertThat(response.getCompactTokenSha256()).isEqualTo(sha256(validCompactJwt)); + assertThat(response.getVerifiedKeyId()).isEqualTo(KID); + assertThat(response.getReceiverIdentity()).isEqualTo(localIdentity); + assertThat(response.getAccountPodTarget()).isEqualTo(exactOwnerTarget); + assertThat(response.getObservedAtEpochSeconds()).isEqualTo(NOW.getEpochSecond()); + assertThat(response.getOutcome()) + .isEqualTo(ReceiveReadinessProbeResponse.ObservationOutcome.VERIFIED); + assertThat(ownerReadCalls).hasValue(2); + assertThat(ownerSawPeerUri).hasValue(GAME_SESSION_URI); + assertThat(lastOwnerRequest.get().getExpectedCoordinates()) + .isEqualTo(validRequest.getCoordinates()); + assertThat(lastOwnerRequest.get().getCompactTokenSha256()).isEqualTo(sha256(validCompactJwt)); + assertThat(lastOwnerRequest.get().getProtectedLocalIdentity()).isEqualTo(localIdentity); + assertThat(lastOwnerRequest.get().getUnknownFields().asMap()).isEmpty(); + assertThat(responseHadNoApplicationAuthContext).isTrue(); + assertThat(SessionContext.getAccountId()).isNull(); + assertThat(SessionContext.getGlobalRoles()).isEmpty(); + assertThat(SessionContext.getScopedRolesMap()).isEmpty(); + assertThat(SessionContext.isInternalService()).isFalse(); + assertThat(SessionContext.getServiceName()).isNull(); + assertThat(SessionContext.getServiceInstanceId()).isNull(); + } + + @Test + void wrongWorkloadAndMissingWorkloadIdentityAreDeniedBeforeOwnerRead() throws Exception { + for (TestCertificate caller : List.of(pki.wrongWorkload(), pki.missingWorkloadUri())) { + assertThatThrownBy(() -> receive(caller, validRequest)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(ownerReadCalls).hasValue(0); + } + } + + @Test + void mismatchedOwnerCoordinatesTokenHashAndPodTargetFailClosedBeforeReceipt() throws Exception { + ownerResponseMode.set(OwnerResponseMode.STALE_COORDINATES); + assertUnavailable(validRequest); + assertThat(ownerReadCalls).hasValue(1); + + ownerReadCalls.set(0); + ownerResponseMode.set(OwnerResponseMode.STALE_TOKEN_HASH); + assertUnavailable(validRequest); + assertThat(ownerReadCalls).hasValue(1); + + ownerReadCalls.set(0); + ownerResponseMode.set(OwnerResponseMode.WRONG_POD_TARGET); + assertUnavailable(validRequest); + assertThat(ownerReadCalls).hasValue(1); + } + + @Test + void changedOwnerEvidenceOnSecondReadDeniesAfterCryptographicVerification() throws Exception { + ownerResponseMode.set(OwnerResponseMode.CHANGED_AFTER_FIRST_READ); + + assertUnavailable(validRequest); + + assertThat(ownerReadCalls).hasValue(2); + assertThat(ownerSawPeerUri).hasValue(GAME_SESSION_URI); + } + + @Test + void validInapplicableProductionProfileReturnsOnlyItsNonAuthorizingNegativeObservation() + throws Exception { + UUID jti = UUID.randomUUID(); + long issuedAt = NOW.getEpochSecond() - 1L; + ReadinessProbeCoordinates coordinates = + validRequest.getCoordinates().toBuilder() + .setJti(jti.toString()) + .setTokenProfile("control-ui") + .setAudience("control-ui") + .setExpectedOutcome(ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT) + .setIssuedAtEpochSeconds(issuedAt) + .setExpiresAtEpochSeconds(issuedAt + 120L) + .setPlanExpiresAtEpochSeconds(issuedAt + 180L) + .build(); + ReceiveReadinessProbeResponse response = + receive(pki.account(), request(signedControlUiToken(jti, issuedAt), coordinates)); + + assertThat(response.getOutcome()) + .isEqualTo(ReceiveReadinessProbeResponse.ObservationOutcome.INAPPLICABLE_REJECT); + assertThat(response.getCoordinates()).isEqualTo(coordinates); + assertThat(response.getVerifiedKeyId()).isEqualTo(KID); + assertThat(ownerReadCalls).hasValue(2); + assertThat(responseHadNoApplicationAuthContext).isTrue(); + assertThat(SessionContext.getAccountId()).isNull(); + assertThat(SessionContext.getGlobalRoles()).isEmpty(); + assertThat(SessionContext.getScopedRolesMap()).isEmpty(); + } + + @Test + void wrongKeyAndTamperedSignatureAreRejectedByProductionVerifier() throws Exception { + ownerResponseMode.set(OwnerResponseMode.EXACT); + ReadinessProbeCoordinates wrongKeyCoordinates = + validRequest.getCoordinates().toBuilder().setTargetKid("pending-key-8").build(); + ReceiveReadinessProbeRequest wrongKeyRequest = request(validCompactJwt, wrongKeyCoordinates); + assertThatThrownBy(() -> receive(pki.account(), wrongKeyRequest)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(ownerReadCalls).hasValue(1); + + ownerReadCalls.set(0); + String tamperedJwt = tamperSignature(validCompactJwt); + ReceiveReadinessProbeRequest tamperedRequest = + request(tamperedJwt, validRequest.getCoordinates()); + assertThatThrownBy(() -> receive(pki.account(), tamperedRequest)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(ownerReadCalls).hasValue(1); + } + + private void assertUnavailable(ReceiveReadinessProbeRequest request) throws Exception { + assertThatThrownBy(() -> receive(pki.account(), request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + } + + private ReceiveReadinessProbeResponse receive( + TestCertificate caller, ReceiveReadinessProbeRequest request) throws Exception { + TestIdentityFiles callerFiles = + caller == pki.account() + ? accountClientFiles + : caller == pki.gameSession() + ? gameSessionFiles + : writeIdentityFiles("temporary-caller-" + ownerReadCalls.get(), caller); + ManagedChannel transport = + NettyChannelBuilder.forAddress("127.0.0.1", gameSessionServer.getPort()) + .sslContext(clientTlsContext(callerFiles)) + .build(); + Channel authenticatedServer = + ClientInterceptors.intercept( + transport, new GrpcServerPeerIdentityClientInterceptor(GAME_SESSION_URI)); + try { + return GameSessionJwtReadinessReceiverServiceGrpc.newBlockingStub(authenticatedServer) + .receiveReadinessProbe(request); + } finally { + transport.shutdownNow(); + assertThat(transport.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + private Server startAccountOwnerServer() throws Exception { + AccountJwtReadinessProbeOwnerServiceGrpc.AccountJwtReadinessProbeOwnerServiceImplBase service = + new AccountJwtReadinessProbeOwnerServiceGrpc + .AccountJwtReadinessProbeOwnerServiceImplBase() { + @Override + public void getCurrentReadinessProbeOwner( + GetCurrentReadinessProbeOwnerRequest request, + StreamObserver responseObserver) { + ownerReadCalls.incrementAndGet(); + lastOwnerRequest.set(request); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + ownerSawPeerUri.set(peer == null ? null : peer.uri()); + responseObserver.onNext( + ownerResponse(request, ownerResponseMode.get(), ownerReadCalls.get())); + responseObserver.onCompleted(); + } + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(serverTlsContext(writeIdentityFiles("account-server", pki.account()))) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GetCurrentReadinessProbeOwnerResponse ownerResponse( + GetCurrentReadinessProbeOwnerRequest request, OwnerResponseMode mode, int callNumber) { + var builder = + GetCurrentReadinessProbeOwnerResponse.newBuilder() + .setSchemaVersion(1) + .setOwnerRecordFound(true) + .setCurrentCoordinates(request.getExpectedCoordinates()) + .setCompactTokenSha256(request.getCompactTokenSha256()) + .setCurrentState(GetCurrentReadinessProbeOwnerResponse.ProbeState.ISSUED) + .setCurrentPodTarget( + ownerTarget.get().toBuilder() + .setExpectedOutcome(request.getExpectedCoordinates().getExpectedOutcome())); + return switch (mode) { + case EXACT -> builder.build(); + case STALE_COORDINATES -> + builder + .setCurrentCoordinates( + request.getExpectedCoordinates().toBuilder().setPlanDigest("0".repeat(64))) + .build(); + case STALE_TOKEN_HASH -> builder.setCompactTokenSha256("f".repeat(64)).build(); + case WRONG_POD_TARGET -> + builder + .setCurrentPodTarget( + ownerTarget.get().toBuilder() + .setPodIp("127.0.0.2") + .setDirectPodEndpoint("grpcs://127.0.0.2:" + endpointPort(ownerTarget.get()))) + .build(); + case CHANGED_AFTER_FIRST_READ -> + callNumber == 1 + ? builder.build() + : builder + .setCurrentState(GetCurrentReadinessProbeOwnerResponse.ProbeState.VERIFIED) + .build(); + }; + } + + private static int endpointPort(AccountPodTargetBinding target) { + return Integer.parseInt( + target + .getDirectPodEndpoint() + .substring(target.getDirectPodEndpoint().lastIndexOf(':') + 1)); + } + + private ServerInterceptor applicationAuthContextProbe() { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + io.grpc.Metadata headers, + ServerCallHandler next) { + ServerCall observingCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + responseHadNoApplicationAuthContext.set( + SessionContext.getAccountId() == null + && SessionContext.getGlobalRoles().isEmpty() + && SessionContext.getScopedRolesMap().isEmpty() + && !SessionContext.isInternalService() + && SessionContext.getServiceName() == null + && SessionContext.getServiceInstanceId() == null); + super.sendMessage(message); + } + }; + return next.startCall(observingCall, headers); + } + }; + } + + private ReadinessProbeCoordinates coordinates(UUID jti, long issuedAt) { + return ReadinessProbeCoordinates.newBuilder() + .setRotationOperationId(UUID.randomUUID().toString()) + .setOperationDigest("a".repeat(64)) + .setPlanDigest("b".repeat(64)) + .setPlanVersion(2) + .setRegistryVersion(1) + .setValidatorId(GameSessionJwtReadinessReceiverProtoMapper.GAME_SESSION_VALIDATOR) + .setTokenProfile(GameSessionAccountDelegationProfile.PROFILE) + .setAudience(GameSessionAccountDelegationProfile.AUDIENCE) + .setProbeKind(ReadinessProbeCoordinates.ProbeKind.REPRESENTATIVE) + .setExpectedOutcome(ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setJti(jti.toString()) + .setEntryVersion(4) + .setTargetGeneration("7") + .setTargetKid(KID) + .setExpectedActiveState(ReadinessProbeCoordinates.ExpectedActiveState.ABSENT) + .setIssuedAtEpochSeconds(issuedAt) + .setExpiresAtEpochSeconds(issuedAt + 120L) + .setPlanExpiresAtEpochSeconds(issuedAt + 180L) + .build(); + } + + private static ReceiveReadinessProbeRequest request( + String jwt, ReadinessProbeCoordinates coordinates) { + return ReceiveReadinessProbeRequest.newBuilder() + .setSchemaVersion(1) + .setCoordinates(coordinates) + .setCompactJwt(jwt) + .build(); + } + + private String signedDelegationToken(UUID jti, long issuedAt) throws Exception { + Map header = Map.of("alg", "RS256", "kid", KID, "typ", "JWT"); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(), + "membershipAuthorityGeneration", Map.of(), + "privateRealmGrantVersions", List.of()); + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("sub", RESERVED_SUBJECT); + claims.put("jti", jti.toString()); + claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + claims.put("iat", issuedAt); + claims.put("nbf", issuedAt); + claims.put("exp", issuedAt + 120L); + claims.put("accountId", RESERVED_SUBJECT); + claims.put("tokenGeneration", "1"); + claims.put("authorityTuple", authorityTuple); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", "1"); + return sign(header, claims); + } + + private String signedControlUiToken(UUID jti, long issuedAt) throws Exception { + Map header = Map.of("alg", "RS256", "kid", KID, "typ", "JWT"); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 1L, + "tenantAuthorityGeneration", Map.of(), + "membershipAuthorityGeneration", Map.of(), + "privateRealmGrantVersions", List.of()); + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("sub", RESERVED_SUBJECT); + claims.put("jti", jti.toString()); + claims.put("aud", "control-ui"); + claims.put("iat", issuedAt); + claims.put("nbf", issuedAt); + claims.put("exp", issuedAt + 120L); + claims.put("accountId", RESERVED_SUBJECT); + claims.put("tokenGeneration", 1L); + claims.put("authorityTuple", authorityTuple); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", 1L); + claims.put("scopedRoles", Map.of()); + return sign(header, claims); + } + + private String sign(Map header, Map claims) throws Exception { + String signingInput = + encode(JSON.writeValueAsBytes(header)) + + "." + + encode(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(claims))); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(signingKey.getPrivate()); + signer.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return signingInput + "." + encode(signer.sign()); + } + + private ReadinessReceiverLocalIdentity localIdentity(int port) throws Exception { + return ReadinessReceiverLocalIdentity.newBuilder() + .setValidatorId(GameSessionJwtReadinessReceiverProtoMapper.GAME_SESSION_VALIDATOR) + .setDeploymentUid(DEPLOYMENT_UID) + .setPodUid(POD_UID) + .setPodIp("127.0.0.1") + .setDirectPodEndpoint("grpcs://127.0.0.1:" + port) + .setCanonicalServiceUri(GAME_SESSION_URI) + .setImage("registry.example/firemud/game-session-service@sha256:" + "a".repeat(64)) + .setVerifierConfigSha256("b".repeat(64)) + .setApplicabilityMatrixDigest("c".repeat(64)) + .setSourceInventoryRevision("inventory-r1") + .setSourceInventoryDigest("d".repeat(64)) + .setServerLeafSpkiSha256(spkiSha256(pki.gameSession().certificate())) + .setAccountJwksSourceIdentity(sourceIdentityProto()) + .setAccountJwksTrustConfigRevision(1L) + .build(); + } + + private AccountPodTargetBinding ownerTarget(ReadinessReceiverLocalIdentity receiverIdentity) { + return AccountPodTargetBinding.newBuilder() + .setInventorySnapshotDigest("f".repeat(64)) + .setEnvironmentId("prod") + .setClusterId("cluster-a") + .setClusterIncarnationUid(CLUSTER_INCARNATION_UID) + .setNamespace(NAMESPACE) + .setNamespaceUid(NAMESPACE_UID) + .setApiBindingRevision("api-r1") + .setApiBindingDigest("8".repeat(64)) + .setInventoryBindingRevision("inventory-r1") + .setInventoryBindingDigest("d".repeat(64)) + .setValidatorId(receiverIdentity.getValidatorId()) + .setDeploymentUid(receiverIdentity.getDeploymentUid()) + .setPodUid(receiverIdentity.getPodUid()) + .setPodIp(receiverIdentity.getPodIp()) + .setImage(receiverIdentity.getImage()) + .setVerifierConfigSha256(receiverIdentity.getVerifierConfigSha256()) + .setApplicabilityMatrixDigest(receiverIdentity.getApplicabilityMatrixDigest()) + .setExpectedOutcome(ReadinessProbeCoordinates.ExpectedOutcome.ACCEPT) + .setDirectPodEndpoint(receiverIdentity.getDirectPodEndpoint()) + .setCanonicalServiceUri(receiverIdentity.getCanonicalServiceUri()) + .setServerLeafSpkiSha256(receiverIdentity.getServerLeafSpkiSha256()) + .build(); + } + + private AccountPublicJwksCache.SourceIdentity sourceIdentity() { + return new AccountPublicJwksCache.SourceIdentity( + "prod", + "cluster-a", + CLUSTER_INCARNATION_UID, + NAMESPACE, + NAMESPACE_UID, + "55555555-5555-4555-8555-555555555555", + "account-api-r1", + "https://kubernetes.example.test:6443", + "9".repeat(64)); + } + + private AccountSourceIdentity sourceIdentityProto() { + return AccountSourceIdentity.newBuilder() + .setEnvironmentId("prod") + .setClusterId("cluster-a") + .setClusterIncarnationUid(CLUSTER_INCARNATION_UID) + .setNamespace(NAMESPACE) + .setNamespaceUid(NAMESPACE_UID) + .setConfigMapUid("55555555-5555-4555-8555-555555555555") + .setBindingRevision("account-api-r1") + .setApiServerOrigin("https://kubernetes.example.test:6443") + .setServingCaSha256("9".repeat(64)) + .build(); + } + + private static String jwks(String kid, RSAPublicKey key) { + return "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"" + + kid + + "\",\"use\":\"sig\",\"alg\":\"RS256\",\"n\":\"" + + encode(unsigned(key.getModulus())) + + "\",\"e\":\"" + + encode(unsigned(key.getPublicExponent())) + + "\"}]}"; + } + + private static String tamperSignature(String jwt) { + String[] parts = jwt.split("\\.", -1); + byte[] signature = Base64.getUrlDecoder().decode(parts[2]); + signature[0] ^= 1; + return parts[0] + "." + parts[1] + "." + encode(signature); + } + + private static String sha256(String value) throws Exception { + return java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.US_ASCII))); + } + + private static String spkiSha256(X509Certificate certificate) throws Exception { + return java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(certificate.getPublicKey().getEncoded())); + } + + private static String encode(byte[] bytes) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private static byte[] unsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + return bytes.length > 1 && bytes[0] == 0 + ? java.util.Arrays.copyOfRange(bytes, 1, bytes.length) + : bytes; + } + + private static KeyPair rsaKeyPair(int bits) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(new RSAKeyGenParameterSpec(bits, RSAKeyGenParameterSpec.F4)); + return generator.generateKeyPair(); + } + + private static TestCertificate issueLeaf( + X500Name authorityName, PrivateKey authorityKey, String workloadUri) throws Exception { + KeyPair keys = rsaKeyPair(2048); + GeneralName[] names = + 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( + new X500Name("CN=FireMUD mTLS readiness test workload, O=FireMUD Test"), + keys.getPublic(), + authorityName, + authorityKey, + false, + new GeneralNames(names)); + return new TestCertificate(keys.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerKey, + boolean certificateAuthority, + GeneralNames subjectAltNames) + throws Exception { + Instant notBefore = Instant.now().minusSeconds(60); + var builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + Date.from(notBefore), + Date.from(notBefore.plusSeconds(14L * 24L * 60L * 60L)), + subject, + publicKey); + builder.addExtension( + Extension.basicConstraints, true, new BasicConstraints(certificateAuthority)); + if (certificateAuthority) { + 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(issuerKey))); + } + + private Path writePem(String name, String label, X509Certificate certificate) throws Exception { + return writePem(name, label, certificate.getEncoded()); + } + + private Path writePem(String name, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + tempDirectory.resolve(name), + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + private TestIdentityFiles writeIdentityFiles(String prefix, TestCertificate identity) + throws Exception { + Path certificate = writePem(prefix + ".crt", "CERTIFICATE", identity.certificate()); + Path privateKey = writePem(prefix + ".key", "PRIVATE KEY", identity.privateKey().getEncoded()); + return new TestIdentityFiles(certificate, privateKey, identity.certificate()); + } + + private CommonGrpcClientProperties clientProperties(TestIdentityFiles identity) { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(identity.certificateFile().toString()); + properties.setPrivateKey(identity.privateKeyFile().toString()); + properties.setCaCert(caCertificateFile.toString()); + return properties; + } + + private io.grpc.netty.shaded.io.netty.handler.ssl.SslContext serverTlsContext( + TestIdentityFiles identity) throws Exception { + return GrpcSslContexts.configure( + SslContextBuilder.forServer( + identity.certificateFile().toFile(), identity.privateKeyFile().toFile())) + .trustManager(caCertificateFile.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build(); + } + + private io.grpc.netty.shaded.io.netty.handler.ssl.SslContext clientTlsContext( + TestIdentityFiles identity) throws Exception { + return GrpcSslContexts.forClient() + .trustManager(caCertificateFile.toFile()) + .keyManager(identity.certificateFile().toFile(), identity.privateKeyFile().toFile()) + .build(); + } + + private static void stopServer(Server server) throws InterruptedException { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + private enum OwnerResponseMode { + EXACT, + STALE_COORDINATES, + STALE_TOKEN_HASH, + WRONG_POD_TARGET, + CHANGED_AFTER_FIRST_READ + } + + private record TestCertificate(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestIdentityFiles( + Path certificateFile, Path privateKeyFile, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestCertificate account, + TestCertificate gameSession, + TestCertificate wrongWorkload, + TestCertificate missingWorkloadUri) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java index a225218cc5..a7aaf556d6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java @@ -1,22 +1,47 @@ package net.firedevops.firemud.gamesession.config; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import io.grpc.ServerInterceptor; +import io.grpc.ServerServiceDefinition; +import io.grpc.TlsServerCredentials; +import java.util.List; import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessLocalIdentityProvider; import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverEngine; import net.firedevops.firemud.gamesession.service.impl.GameSessionJwtReadinessReceiverGrpcService; +import net.firedevops.firemud.gamesession.v1.GameSessionJwtReadinessReceiverServiceGrpc; import org.junit.jupiter.api.Test; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.ShadedNettyGrpcServerFactory; +import org.springframework.grpc.server.service.GrpcService; class GameSessionJwtReadinessReceiverConfigurationTest { private static final String ENABLED = "firemud.game-session.jwt-readiness.receiver.enabled=true"; + private final ApplicationContextRunner routingRunner = + new ApplicationContextRunner() + .withUserConfiguration(GameSessionJwtReadinessIsolatedGrpcRoutingConfiguration.class); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration( GameSessionJwtReadinessReceiverConfiguration.class, GameSessionJwtReadinessReceiverGrpcService.class); + @Test + void grpcAdapterUsesOnlyThePeerIdentityInterceptor() { + GrpcService grpcService = + GameSessionJwtReadinessReceiverGrpcService.class.getAnnotation(GrpcService.class); + + assertThat(grpcService).isNotNull(); + assertThat(grpcService.interceptorNames()).containsExactly("grpcPeerIdentityInterceptor"); + assertThat(grpcService.blendWithGlobalInterceptors()).isFalse(); + } + @Test void receiverAndCryptoCompositionRemainAbsentByDefault() { contextRunner.run( @@ -40,4 +65,56 @@ void explicitEnablementWithoutProtectedLocalIdentityStillLeavesReceiverUnregiste .doesNotHaveBean(GameSessionJwtReadinessReceiverGrpcService.class); }); } + + @Test + void disabledRoutingDoesNotAlterFilteringOrRequireSupportedFactory() { + routingRunner.run( + context -> { + var customizer = context.getBean(GrpcServerFactoryCustomizer.class); + var factory = factory(); + factory.setInterceptorFilter((interceptor, service) -> false); + customizer.customize(factory); + assertThat( + factory.supports(mock(ServerInterceptor.class), definition("ordinary.Service"))) + .isFalse(); + customizer.customize(mock(GrpcServerFactory.class)); + }); + } + + @Test + void selectedReceiverFiltersOnlyExactServiceAndRequiresSupportedFactory() { + routingRunner + .withPropertyValues(ENABLED) + .run( + context -> { + var customizer = context.getBean(GrpcServerFactoryCustomizer.class); + var factory = factory(); + customizer.customize(factory); + var interceptor = mock(ServerInterceptor.class); + assertThat( + factory.supports( + interceptor, + definition(GameSessionJwtReadinessReceiverServiceGrpc.SERVICE_NAME))) + .isFalse(); + assertThat(factory.supports(interceptor, definition("ordinary.Service"))).isTrue(); + assertThat( + factory.supports( + interceptor, + definition( + GameSessionJwtReadinessReceiverServiceGrpc.SERVICE_NAME + "Extra"))) + .isTrue(); + assertThatThrownBy(() -> customizer.customize(mock(GrpcServerFactory.class))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("interceptor filtering"); + }); + } + + private static ShadedNettyGrpcServerFactory factory() { + return new ShadedNettyGrpcServerFactory( + "127.0.0.1:0", List.of(), null, null, TlsServerCredentials.ClientAuth.REQUIRE); + } + + private static ServerServiceDefinition definition(String name) { + return ServerServiceDefinition.builder(name).build(); + } } From 5b8783b2eeafe8de606d4be8107ad0ef84bf8b89 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 04:36:10 +1300 Subject: [PATCH 018/129] Compose protected readiness identity and correct native publication guards --- .../environment-and-secrets-overview.md | 8 + .../account-service/configuration.md | 2 + .../game-session-service/configuration.md | 4 +- ...ystem-architecture-authz-route-matrix.yaml | 16 + ...em-architecture-jwt-and-token-contracts.md | 8 + ...ame-authoring-publishing-and-activation.md | 8 +- .../preview/validate-preview-artifact.py | 20 +- .../trust-bootstrap/bind-runtime-roles.sh | 67 +++ .../tests/hosted-gateway-bridge-contract.sh | 33 ++ .../tests/trust-bootstrap-rbac-contract.sh | 135 ++++- .../test_validate_preview_artifact.py | 78 +++ k8s/helm/firemud/templates/apps.yaml | 20 +- k8s/trust-bootstrap/deployment-admission.yaml | 184 ++++++ k8s/trust-bootstrap/deployment-rbac.yaml | 10 + .../account/v1/jwt_readiness_receiver.proto | 24 +- ...tJwtReadinessPodReceiverConfiguration.java | 6 +- ...ntJwtReadinessProbeOwnerConfiguration.java | 24 +- ...ountJwtReadinessProbeOwnerGrpcService.java | 37 +- ...wtReadinessGrpcReceiverInvocationPort.java | 17 +- ...tJwtReadinessPodLocalIdentityProvider.java | 60 +- ...ountJwtReadinessProbeOwnerProtoMapper.java | 90 ++- .../AccountJwtReadinessProbeService.java | 5 + ...ntJwtReadinessReceiverMetadataService.java | 415 +++++++++++++ ...ess_version_aware_delivery_claim_guard.sql | 84 +++ ...dinessProbePersistenceIntegrationTest.java | 43 ++ ...JwtReadinessProbeOwnerGrpcServiceTest.java | 55 +- ...adinessGrpcReceiverInvocationPortTest.java | 43 +- ...ReadinessPodLocalIdentityProviderTest.java | 54 +- ...JwtReadinessProbeOwnerProtoMapperTest.java | 91 ++- ...tReadinessReceiverMetadataServiceTest.java | 557 ++++++++++++++++++ .../security/ProtectedPodUidProjection.java | 278 +++++++++ .../ProtectedPodUidProjectionTest.java | 190 ++++++ .../VersionPublishCommandServiceImpl.java | 21 +- .../VersionPublishCommandServiceImplTest.java | 65 ++ ...sionJwtReadinessReceiverConfiguration.java | 20 +- ...sionJwtReadinessLocalIdentityProvider.java | 8 +- ...meSessionJwtReadinessProbeOwnerClient.java | 32 +- ...essionJwtReadinessProtectedJwksSource.java | 86 ++- ...adinessProtectedLocalIdentityProvider.java | 410 +++++++++++++ ...nJwtReadinessReceiverMetadataReadPort.java | 11 + ...tReadinessReceiverMtlsIntegrationTest.java | 89 ++- ...JwtReadinessReceiverConfigurationTest.java | 138 +++++ ...onJwtReadinessProtectedJwksSourceTest.java | 199 +++++++ ...essProtectedLocalIdentityProviderTest.java | 383 ++++++++++++ ...SessionJwtReadinessReceiverEngineTest.java | 16 +- 45 files changed, 4052 insertions(+), 92 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataService.java create mode 100644 services/account-service/src/main/resources/db/migration/V102__account_jwt_readiness_version_aware_delivery_claim_guard.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/security/ProtectedPodUidProjection.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedPodUidProjectionTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProvider.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverMetadataReadPort.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSourceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProviderTest.java diff --git a/design/architecture/infrastructure/environment-and-secrets-overview.md b/design/architecture/infrastructure/environment-and-secrets-overview.md index 6c162d5237..84118d2d17 100644 --- a/design/architecture/infrastructure/environment-and-secrets-overview.md +++ b/design/architecture/infrastructure/environment-and-secrets-overview.md @@ -149,6 +149,14 @@ Current implementation drift includes the runtime classpath JWKS fallback when t --- +### Hosted Readiness Pod Projection and Routing Boundary + +The attribution contract is owned by [JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md#protected-readiness-receiver-attribution). The bounded hosted implementation targets the protected `dev` and canonical `pr-N` runtime namespaces on the documented k3s Flannel VXLAN/kube-router platform; it is not proof for arbitrary CNI implementations or player-facing environments. The existing trusted bootstrap installs fail-closed native admission policies, and the trusted namespace manager must read back their exact content before granting runtime deployment roles. Runtime deployers must not be able to replace that policy authority. Policy matching must not depend on a removable opt-in Pod label. + +Account and Game Session receive the fixed kubelet downward-API UID projection read-only. The hosted Pod policy must reject host/network escape and protected receiver injection or projection substitution after mutating admission, including updates and ephemeral-container subresources. Existing workload TLS delivery remains unchanged. Kubelet AtomicWriter directories may retain root-owned `0755` permissions on a read-only mount; filesystem mode checks alone neither prove a read-only mount nor authenticate kubelet provenance. Base Kustomize sidecar/hostPath layouts do not inherit the hosted single-container proof. + +Local rendering, source-contract tests and socket fixtures are only preparatory evidence. Live API policy compilation/enforcement, trusted installation/readback, actual CNI direct routing and shared-key wrong-replica/replacement-race proof remain activation gates. Do not enable readiness promotion or remove a shared-SPKI denial from these static artifacts alone. + ## JWT Trust Model by Environment The canonical JWT profile, registry, authority-generation, outage, signing, and rotation contract is [JWT and Token Contracts](../system-architecture-jwt-and-token-contracts.md). The matrix below records only environment-local resource and readiness consequences: diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index d1c29d2d6f..5163eecbe8 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -24,6 +24,8 @@ The configurable cleanup margin controls issued-token registry retention only. G The isolated readiness prerequisite graph is separately selected by an explicit `firemud.account.jwt-readiness.validation.enabled`, `.probe-owner.enabled` or `.pod-receiver.enabled`. It also requires `firemud.account.jwt-jwks-api.enabled=true` with its `protected-binding-path` fixed to `/etc/firemud/account-jwt-api/binding.json`, `firemud.account.jwt-signer.materialization.enabled=true` with its `protected-binding-path` fixed to `/etc/firemud/account-jwt-materializer/binding.json`, and a valid `firemud.grpc.workload-namespace`. Selection only constructs the readiness-specific graph: protected-file validation, authenticated resource readback and signer/readiness proof are still mandatory, and it does not enable the unrelated LOGIN or credential composition. Current proof and delivery gaps remain in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). +The per-Pod receiver uses the fixed read-only kubelet UID projection at `/var/run/secrets/firemud/pod-identity/uid`; `HOSTNAME` and caller identity fields are not attribution sources. Its independent authenticated inventory join remains mandatory. The readiness-only metadata read for Game Session shares the exact isolated Game Session workload guard and cannot select an operation, create a plan or supply application authority. The canonical producer, source and routing requirements are in [Protected Readiness Receiver Attribution](../../system-architecture-jwt-and-token-contracts.md#protected-readiness-receiver-attribution); a mounted file or enabled property does not satisfy those proof gates. + ## Implementation Status The current runtime still uses the shared-HMAC compatibility profile for issuance and validation and has no asymmetric non-exportable signer delegation. Any Secret-backed asymmetric materialization is the explicit interim fallback/drift, not canonical target custody; the current preflight/manifests still treat signing paths and `jwt-signing-keys` mounts as shared workload configuration rather than enforcing Account as the sole private-material consumer, and the classpath fallback remains permitted when the configured JWKS file is absent. The runtime also retains the legacy creator-share percentage setting and provider-mutating code paths; they are unsupported implementation drift, not an accepted fee policy or product capability. These target-state requirements are not proof of current startup, custody, mount enforcement, or creator-commerce disablement; runtime, preflight, and manifest alignment is outside this documentation slice. diff --git a/design/architecture/microservices/game-session-service/configuration.md b/design/architecture/microservices/game-session-service/configuration.md index 55b06173b2..7c1fde6cba 100644 --- a/design/architecture/microservices/game-session-service/configuration.md +++ b/design/architecture/microservices/game-session-service/configuration.md @@ -25,9 +25,9 @@ TLS certificates are supplied via [`FIREMUD_GRPC_CERT_CHAIN_PATH`, `FIREMUD_GRPC ### Isolated JWT Readiness Receiver -The receiver composition for [ADR 0014](../../decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md) is default-inactive. `firemud.game-session.jwt-readiness.receiver.enabled=true` alone does not supply the required protected local identity provider or register a receiver. When selected with its prerequisites, the adapter explicitly extracts the TLS peer and excludes the global application bearer interceptor; the exact Account workload guard remains mandatory. The remaining producer, transport and activation proof belongs in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md), not in a configuration toggle. +The receiver composition for [ADR 0014](../../decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md) is default-inactive. Explicit enablement selects its protected local-identity producer only when Spring supplies TLS bundles; lazy bean registration is not proof that its inputs are available. Every identity read requires the fixed kubelet Pod UID projection, the exact local Game Session TLS leaf and Account-authenticated current receiver metadata. Missing or inconsistent inputs deny the read; no environment UID or fixture fallback exists. When selected with its prerequisites, the adapter explicitly extracts the TLS peer and excludes the global application bearer interceptor; the exact Account workload guard remains mandatory. The canonical attribution boundary is [Protected Readiness Receiver Attribution](../../system-architecture-jwt-and-token-contracts.md#protected-readiness-receiver-attribution). Remaining producer, transport and activation proof belongs in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md), not in a configuration toggle. -When constructing the isolated receiver, `firemud.game-session.jwt-readiness.receiver.max-control-ui-tenant-scopes` is required, and `firemud.grpc.workload-namespace` must identify the exact protected workload namespace. Its owner-read client uses the existing Account endpoint and gRPC mTLS configuration. The receiver reads only the fixed public projection `/var/run/secrets/firemud/jwks/jwks.json`; it has no private signing material, alternate-path discovery or classpath fallback. These local prerequisites do not authorize an application auth context, session or admission. +When constructing the isolated receiver, `firemud.game-session.jwt-readiness.receiver.max-control-ui-tenant-scopes` is required, and `firemud.grpc.workload-namespace` must identify the exact protected workload namespace. Its owner-read client uses the existing Account endpoint and gRPC mTLS configuration for both current receiver metadata and exact probe-owner readback. The UID projection is `/var/run/secrets/firemud/pod-identity/uid`. The receiver reads only the fixed public projection `/var/run/secrets/firemud/jwks/jwks.json`, whose bytes must match Account's authenticated public-JWKS digest and exact opaque trust-binding revision; it has no private signing material, alternate-path discovery or classpath fallback. These local prerequisites do not authorize an application auth context, session or admission. ## FireMUD Settings Domains diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index a6c07608cc..1b8132cad4 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -3871,6 +3871,22 @@ routes: end_user_token_required: false required_live_checks: [exact_attempt_tuple, committed_pointer_audit_binding, aborted_attempt_future_commit_fence] required_fields: [hold_id, hold_fence, tenant_id, realm_uuid, playable_state_namespace_uuid, playable_state_scope, game_instance_id, version_id, active_lifecycle_epoch, initial_admission_request_id, request_digest, expected_no_prior_pointer, expected_catalog_revision] + - service: account-service + route: GetCurrentReadinessReceiverMetadata + transport: grpc + classification: internal_workload + route_status: target_not_currently_routable + auth_path: exact_mtls_workload + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [game-session-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/game-session-service"] + end_user_token_required: false - service: account-service route: GetCurrentReadinessProbeOwner transport: grpc diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index add7da17bc..d229a83b8f 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -109,6 +109,14 @@ The registry lifecycle is `PLANNED -> ISSUED -> VERIFIED -> RETIRED -> CLEANED` This predicate is harness-only and non-authorizing. A request that fails any predicate, including an ordinary caller presenting a probe-shaped token or a harness request with a missing, extra, mismatched, expired, terminal, or cross-operation entry, is denied before normal authentication context is created, authorization is evaluated, or application side effects occur. A matching probe may proceed only through the production signature, claim, audience, algorithm, key-use, and JWKS validation code and is then unconditionally denied before authorization and side effects. A readiness entry never satisfies `session:auth:token:`, grants authentication context, or permits a normal registry-backed request to bypass its required record. This readiness-only exception does not apply to gameplay-connect, routine gameplay, bootstrap, control-plane, or any other application route; those paths retain their declared authentication contracts. +### Protected Readiness Receiver Attribution + +Readiness receiver attribution uses the existing workload mTLS identity together with a protected local Pod UID, not a new per-Pod certificate family. The local UID comes only from the kubelet's read-only downward-API projection at `/var/run/secrets/firemud/pod-identity/uid`. An environment variable, request field, receiver assertion, or shared workload certificate alone cannot establish which Pod executed a probe. Account independently authenticates current control-plane evidence for the exact Pod, its ReplicaSet-to-Deployment ownership, numeric endpoint, image and verifier configuration, and rechecks that evidence around delivery and before promotion. Missing, changed, ambiguous or substituted evidence denies; existing duplicate-SPKI protection must not be relaxed until the alternative attribution and its negative/race proof are complete. + +For Game Session's isolated receiver, Account supplies a readiness-only current metadata read authenticated to the exact Game Session workload. Account selects the durable current rotation operation and existing complete inventory plan; the caller cannot choose an operation, create a plan or substitute trust pins. The lookup binds the projected local Pod UID and actual local TLS leaf to Account's independently observed inventory, and returns the complete current receiver identity, applicability-matrix and inventory digests, Account public-JWKS source identity and exact public-document digest. Account rechecks the selected operation, plan, protected bindings, inventory and public source after external reads, without holding database locks across control-plane I/O. Game Session independently checks its projected UID and local TLS leaf before and after the lookup and matches its fixed public JWKS projection to that authenticated document digest. The trust-binding revision is the exact opaque revision from the protected source, not an invented numeric counter. The separate exact-probe owner read still binds the issued token hash, coordinates and current Pod target before and after cryptographic verification. Neither metadata nor a probe result creates authentication context, application authority, a session or admission. + +Direct delivery uses a fresh numeric Pod endpoint with proxy resolution and retries disabled, verifies the actual socket endpoint, and requires platform enforcement against listener/route substitution. A post-response address check alone is not proof that dispatch was safe. The protected platform boundary must exclude host networking, network-escape privileges, injected proxy/init/ephemeral containers and replacement races, and preserve the kubelet projection against shadowing or writable substitution. The trust assumptions include the authenticated Kubernetes control plane, kubelet, nodes/kernel, enforced CNI routing and the verified application image. Static manifests, local permission checks and loopback fixtures do not establish those assumptions or authorize promotion; live admission, routing and replacement-race proof remains required. Hosted implementation consequences and its narrower environment coverage belong in [Environment and Secrets](./infrastructure/environment-and-secrets-overview.md), while remaining implementation and proof belong in the owning trackers. + ## Token Validity and Revocation For registry-backed JWT profiles (`control-ui`, `player-bootstrap`, and receiver-specific private player-delegation profiles), token validity semantics are: 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 91fe59962d..88a19fe496 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 @@ -10,9 +10,13 @@ The current Gameplay-prerequisite construction remains non-activating. Full-vers The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. At `ed928219ee3428073910f1845eaa975e8814a30a`, local validation is complete for the held-order/source-fencing batch, but physical PostgreSQL validation was skipped. The Account-owned disclosure journal now defines an immutable request, predecessor/candidate, effective instant, exact source vector and opaque authority binding, with exact dispatch/ambiguity/result readback. Its non-revoking preparation check refuses already-reserved or unsettled original operations under sorted source locks. This is only a storage foundation: handoff-aware capture/reserve/claim, both publication paths including environment binding, authenticated notice production/readback and the physical World deadline gate remain unimplemented or unproved. In particular, preparation-first serialization is not closed while later capture and ordering do not consult the journal; there is no production disclosure/currentness path. Reconsider only after focused PostgreSQL proof covers both orderings of preparation versus original `COMMIT_ORDER` acquisition and settlement, every deadline-introduction path including environment binding, exact retry/restart/ambiguous-notice readback, and World commit-time denial at the disclosed instant without early ordinary-authoring freeze or date rewriting. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. -Creator issuance preserves the existing OTP failure budget by committing a primary-authentication denial's accounting before returning the credential error; successful OTP consumption still rolls back if subsequent preparation fails. Its real PostgreSQL definitions use the primary hook's Spring transaction interceptor, not only a direct method call. The construction now includes a selective Account per-Pod readiness/receipt closure and commit-bound signer coordinator, together with a default-inactive Game Session receiver using production cryptographic profile validation and exact Account owner readback. The isolated adapters explicitly select TLS peer extraction without the global application JWT interceptor. Six loopback mTLS cases executed without skips through the real Game Session verifier and owner-read client; their Account owner responses, protected local identity and public JWKS remain test fixtures. Annotation/default-registration checks and manual Netty transport proof do not prove deployed Spring composition or authentic inventory. These sources do not establish a production signer: protected Game Session local identity and input delivery, deployed isolated routing, current inventory and mounted correspondence, physical PostgreSQL proof, and live convergence/promotion remain open. The current inventory rejects shared receiver-Pod leaf-key pins, while the base Deployment uses the accepted workload-level certificate delivery. Unique replica SPKI is a code-selected strengthening, not an ADR 0038 prerequisite. The approved platform-owned alternative must establish authenticated control-plane Pod UID/direct numeric endpoint, protected routing and replacement-race checks around delivery and at promotion, plus a genuine protected local-identity producer; shared keys or receiver/environment UID alone are insufficient. That alternate attribution is not yet defined and proved, and the existing guard remains intact. A complete claim without protected per-validator evidence remains quarantined; synthetic signer fixtures cannot close the original APPLIED/release prerequisite. Password and wrong-secret PostgreSQL proof is separate from restricted-account authentication: the latter has unit coverage, while an authentic owner lifecycle transition needed for its physical fixture remains unavailable. The broader JWT capability remains owned by [Shared Runtime Contracts](./shared-runtime-contracts-and-persistence.md). +Creator issuance preserves the existing OTP failure budget by committing a primary-authentication denial's accounting before returning the credential error; successful OTP consumption still rolls back if subsequent preparation fails. Its real PostgreSQL definitions use the primary hook's Spring transaction interceptor, not only a direct method call. The construction includes a selective Account per-Pod readiness/receipt closure and commit-bound signer coordinator, together with a default-inactive Game Session receiver using production cryptographic profile validation and exact Account owner readback. Six loopback mTLS cases executed without skips through the real Game Session verifier and owner-read client; their Account owner responses, protected local identity and public JWKS remain test fixtures. These sources do not establish a production signer: protected input delivery, deployed isolated routing, current inventory and mounted correspondence, corrected PostgreSQL proof, and live convergence/promotion remain open. The current inventory rejects shared receiver-Pod leaf-key pins, while the base Deployment uses the accepted workload-level certificate delivery. Unique replica SPKI is a code-selected strengthening, not an ADR 0038 prerequisite; the approved alternative is described below but remains unproved. A complete claim without protected per-validator evidence remains quarantined; synthetic signer fixtures cannot close the original APPLIED/release prerequisite. Password and wrong-secret PostgreSQL proof is separate from restricted-account authentication: the latter has unit coverage, while an authentic owner lifecycle transition needed for its physical fixture remains unavailable. The broader JWT capability remains owned by [Shared Runtime Contracts](./shared-runtime-contracts-and-persistence.md). -The installed Spring gRPC routing correction uses service-local server-factory filters, not the interceptor annotation alone: isolated readiness services exclude global middleware and append the exact TLS peer extractor once, while ordinary services retain their global interception. Local composition and loopback tests pass; this does not establish protected deployment inputs or deployed routing. Construction CI exposed two producer defects: the readiness applicability matrix omitted its cluster ID, and selected publication derived its workflow from a private tenant key rather than the canonical UUID. Both have corrections and local regression assertions; corrected PostgreSQL execution remains required. The Account local receiver now joins Pod-to-ReplicaSet-to-Deployment explicitly, and direct numeric transport excludes configured proxies and checks the actual socket address before accepting a result. That post-RPC check does not prove prevention of dispatch or transparent routing substitution. These corrections do not supply the missing protected Game Session identity producer or platform enforcement. Separately, a World-local post-commit confirmation could prove an on-time original transaction, but rejecting a late confirmation cannot prevent an already-committed late write to normal topology. Already-disclosed deadline-bearing writes remain denied; true staging and the remaining physical deadline design are outside the current Gameplay prerequisite batch. Account-local transaction evidence cannot prove another database's durability. +The installed Spring gRPC routing correction uses service-local server-factory filters, not the interceptor annotation alone: isolated readiness and materializer services exclude global middleware and apply the exact TLS guard once, while ordinary services retain their global interception. Local composition and loopback tests pass; this does not establish protected deployment inputs or deployed routing. Earlier construction CI exposed omitted cluster identity in the readiness applicability matrix and private-key workflow derivation in the selected publication owner. Correcting those producers exposed the distinct downstream failures recorded below. The Account local receiver joins Pod-to-ReplicaSet-to-Deployment explicitly, and direct numeric transport excludes configured proxies and checks the actual socket address before accepting a result. That post-RPC check does not prove prevention of dispatch or transparent routing substitution. Separately, a World-local post-commit confirmation could prove an on-time original transaction, but rejecting a late confirmation cannot prevent an already-committed late write to normal topology. Already-disclosed deadline-bearing writes remain denied; true staging and the remaining physical deadline design are outside the current Gameplay prerequisite batch. Account-local transaction evidence cannot prove another database's durability. + +The protected-attribution construction replaces Account's environment/hostname Pod selector with a fixed kubelet UID projection and adds an argument-free Game Session producer. Account's isolated, default-off current-metadata method selects an existing complete plan itself, joins the selected Pod through current authenticated inventory, and binds the actual public-JWKS bytes to the exact opaque source revision. Game Session compares that response with its own fixed UID projection and current TLS leaf, then checks its public projection against the authenticated hash. Both external-read phases are followed by current-operation/immutable-plan readback; no network call holds an owner SQL transaction. Hosted admission and exact trusted readback define the bounded Pod projection and routing assumptions. Local render/RBAC contracts and 84 preview-validator cases passed. The corrected local Account, Game Design and Game Session checks passed with 3,341 service test executions and 484 skips, plus 279 Common Platform Core cases; the new readiness proof includes 12 Account metadata cases, 10 protected-UID cases, 10 Game Session identity cases, five public-JWKS cases, nine configuration cases and eight isolated mTLS-suite cases, one of which proves denial before dispatch. Their upstream identity and control-plane responses are fixtures. Live admission, kubelet/CNI routing, replacement-race and promotion proof remain outstanding. This defines and locally exercises the approved alternative but does not establish exact-Pod deployment attribution; duplicate-SPKI denial and all activation gates remain intact. See [Protected Readiness Receiver Attribution](../../architecture/system-architecture-jwt-and-token-contracts.md#protected-readiness-receiver-attribution) for the single normative owner. + +Exact published construction CI at `baf478833175e0fd3e8a11eeee469505065738d5` executed 211 Account, 74 Game Design and 200 World PostgreSQL/integration cases with no skips. It found one Account and two Game Design failures: the legacy delivery-claim trigger expects the V1 entry count for a complete V2 plan, and a selected-publication consumer still derives workflow identity from the private tenant key. These are owned implementation defects, not inherited or flaky proof. Additive V102 corrects the version-aware registry count without rewriting prior migrations; selected reconciliation now compares the exact durable canonical-tenant operation while generic Temporal validation stays unchanged. Local schema generation and affected service checks pass, but the PostgreSQL regression cases skip locally without Docker. The passing earlier World cases and Account's 31 Draft-fence, four source-composition and 12 terms cases do not close the corrected-head physical proof or genuine end-to-end handoffs. This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. diff --git a/dev-tools/hosted/preview/validate-preview-artifact.py b/dev-tools/hosted/preview/validate-preview-artifact.py index ee73dd212b..69cb5da1b6 100644 --- a/dev-tools/hosted/preview/validate-preview-artifact.py +++ b/dev-tools/hosted/preview/validate-preview-artifact.py @@ -1678,6 +1678,10 @@ def validate_service_consumers( expected_mounts["grpc-trust"] = ("/grpc-trust", "firemud-grpc-tls") if service == "account-service": expected_mounts["jwt-jwks"] = ("/var/run/secrets/firemud/jwks", "jwt-jwks") + if service in {"account-service", "game-session-service"}: + expected_mounts["pod-identity"] = ( + "/var/run/secrets/firemud/pod-identity", "metadata.uid" + ) if service == "tcp-proxy-service": if exposure_mode == "public": expected_mounts["telnet-tls"] = ( @@ -1719,14 +1723,26 @@ def validate_service_consumers( mount = mounts[volume_name] if mount.get("mountPath") != mount_path or mount.get("readOnly") is not True: fail(f"Deployment/{service} has an unsafe {volume_name} mount") - if volume_name in {"gateway-ws-server-tls", "gateway-ws-client-tls"} and mount != { + if volume_name in {"gateway-ws-server-tls", "gateway-ws-client-tls", "pod-identity"} and mount != { "name": volume_name, "mountPath": mount_path, "readOnly": True, }: fail(f"Deployment/{service} has an unsafe {volume_name} mount") volume = volumes[volume_name] - if volume_name == "jwt-jwks": + if volume_name == "pod-identity": + if volume != { + "name": "pod-identity", + "downwardAPI": { + "defaultMode": 0o444, + "items": [{ + "path": "uid", + "fieldRef": {"apiVersion": "v1", "fieldPath": "metadata.uid"}, + }], + }, + }: + fail(f"Deployment/{service} has an unsafe pod-identity projection") + elif volume_name == "jwt-jwks": source = _require_mapping( volume.get("configMap") or {}, f"Deployment/{service}.spec.template.spec.volumes[{volume_name}].configMap", diff --git a/dev-tools/hosted/trust-bootstrap/bind-runtime-roles.sh b/dev-tools/hosted/trust-bootstrap/bind-runtime-roles.sh index fbf0611c3c..9f4f709ef3 100755 --- a/dev-tools/hosted/trust-bootstrap/bind-runtime-roles.sh +++ b/dev-tools/hosted/trust-bootstrap/bind-runtime-roles.sh @@ -16,6 +16,73 @@ if [[ -z "${KUBECONFIG:-}" || ! -r "$KUBECONFIG" ]]; then exit 2 fi +# The trusted checkout is the contract authority. Read every complete policy +# and binding before granting either runtime role; names or Fail/Deny alone +# cannot establish that the protected Pod boundary is installed. +repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../../.." && pwd)" +python3 - "$repo_root/k8s/trust-bootstrap/deployment-admission.yaml" <<'PY' +import json +import copy +import subprocess +import sys + +import yaml + +with open(sys.argv[1], encoding="utf-8") as stream: + required = [item for item in yaml.safe_load_all(stream) if item] + +revision_key = "firemud.dev/admission-revision" +expected_names = { + "firemud-trust-runtime-namespace-boundary", + "firemud-trust-runtime-binding-boundary", + "firemud-trust-runtime-pod-boundary", + "firemud-trust-runtime-pod-identity", +} +expected_resources = { + (kind, name) + for kind in ("ValidatingAdmissionPolicy", "ValidatingAdmissionPolicyBinding") + for name in expected_names +} +if {(item["kind"], item["metadata"]["name"]) for item in required} != expected_resources or len(required) != 8: + raise SystemExit("trusted deployment admission manifest does not contain the exact required policy/binding set") + + +def canonical_spec(kind, spec): + if not isinstance(spec, dict): + return spec + result = copy.deepcopy(spec) + # MatchResources defaults empty selectors to all objects/namespaces and + # matchPolicy to Equivalent. An omitted binding matchResources matches all. + # Normalize only those API defaults; all other fields remain exact. + match_key = "matchConstraints" if kind == "ValidatingAdmissionPolicy" else "matchResources" + match = result.setdefault(match_key, {}) + if isinstance(match, dict): + match.setdefault("namespaceSelector", {}) + match.setdefault("objectSelector", {}) + match.setdefault("matchPolicy", "Equivalent") + return result + + +for expected in required: + kind, name = expected["kind"], expected["metadata"]["name"] + actual = json.loads(subprocess.check_output( + ["kubectl", "get", f"{kind}.admissionregistration.k8s.io", name, "-o", "json"], + text=True, + )) + if ( + actual.get("apiVersion") != expected["apiVersion"] + or actual.get("kind") != kind + or actual.get("metadata", {}).get("name") != name + or actual.get("metadata", {}).get("deletionTimestamp") is not None + or expected["metadata"].get("annotations", {}).get(revision_key) != "hosted-pod-identity-v1" + or actual.get("metadata", {}).get("annotations", {}).get(revision_key) != "hosted-pod-identity-v1" + or canonical_spec(kind, actual.get("spec")) != canonical_spec(kind, expected["spec"]) + ): + raise SystemExit(f"required admission {kind}/{name} differs from the trusted content/revision; refusing runtime role grants") + if kind == "ValidatingAdmissionPolicy" and actual.get("status", {}).get("typeChecking", {}).get("expressionWarnings"): + raise SystemExit(f"required admission {name} has CEL type-check warnings; refusing runtime role grants") +PY + namespace_json="$(kubectl get namespace "$namespace" -o json)" if [[ "$namespace" == dev ]]; then jq -e ' diff --git a/dev-tools/tests/hosted-gateway-bridge-contract.sh b/dev-tools/tests/hosted-gateway-bridge-contract.sh index b52bf689c4..ac014bc4c0 100644 --- a/dev-tools/tests/hosted-gateway-bridge-contract.sh +++ b/dev-tools/tests/hosted-gateway-bridge-contract.sh @@ -193,6 +193,39 @@ for deployment in deployments: assert_restricted_workload( deployment, infrastructure_uids.get(deployment_name, 1000) ) + pod_spec = deployment["spec"]["template"]["spec"] + identity_volumes = [ + volume for volume in pod_spec.get("volumes", []) + if volume.get("name") == "pod-identity" + ] + identity_mounts = [ + mount for container in pod_spec["containers"] + for mount in container.get("volumeMounts", []) + if mount.get("name") == "pod-identity" + ] + if deployment_name in {"account-service", "game-session-service"}: + assert len(pod_spec["containers"]) == 1 + assert not pod_spec.get("initContainers") + assert not pod_spec.get("ephemeralContainers") + assert identity_volumes == [{ + "name": "pod-identity", + "downwardAPI": { + "defaultMode": 0o444, + "items": [{ + "path": "uid", + "fieldRef": {"apiVersion": "v1", "fieldPath": "metadata.uid"}, + }], + }, + }], f"{deployment_name} lacks the fixed kubelet UID projection" + assert identity_mounts == [{ + "name": "pod-identity", + "mountPath": "/var/run/secrets/firemud/pod-identity", + "readOnly": True, + }], f"{deployment_name} lacks the fixed read-only UID mount" + else: + assert not identity_volumes and not identity_mounts, ( + f"{deployment_name} unexpectedly received the protected-consumer UID mount" + ) seed_job = named("Job", "firemud-seed") assert_restricted_workload(seed_job, 1000) diff --git a/dev-tools/tests/trust-bootstrap-rbac-contract.sh b/dev-tools/tests/trust-bootstrap-rbac-contract.sh index 56ea432548..35ac10121f 100755 --- a/dev-tools/tests/trust-bootstrap-rbac-contract.sh +++ b/dev-tools/tests/trust-bootstrap-rbac-contract.sh @@ -9,6 +9,9 @@ python3 - "$repo_root" "$deployment_rbac" "$deployment_admission" <<'PY' import sys import copy import re +import json +import subprocess +from unittest.mock import patch from pathlib import Path import yaml @@ -127,7 +130,10 @@ manager_resources = { for rule in rules(manager_role) for resource in rule.get("resources", []) } -assert manager_resources <= {"namespaces", "rolebindings", "clusterroles"} +assert manager_resources <= { + "namespaces", "rolebindings", "clusterroles", + "validatingadmissionpolicies", "validatingadmissionpolicybindings", +} assert "secrets" not in manager_resources assert "certificaterequests" not in manager_resources assert "issuers" not in manager_resources @@ -154,6 +160,8 @@ admission = documents(admission_path) policy_names = { "firemud-trust-runtime-namespace-boundary", "firemud-trust-runtime-binding-boundary", + "firemud-trust-runtime-pod-boundary", + "firemud-trust-runtime-pod-identity", } policies = {item["metadata"]["name"]: item for item in admission if item["kind"] == "ValidatingAdmissionPolicy"} policy_bindings = {item["metadata"]["name"]: item for item in admission if item["kind"] == "ValidatingAdmissionPolicyBinding"} @@ -163,6 +171,131 @@ for name in policy_names: assert policies[name]["spec"]["failurePolicy"] == "Fail" assert policy_bindings[name]["spec"]["policyName"] == name assert policy_bindings[name]["spec"]["validationActions"] == ["Deny"] + for resource in (policies[name], policy_bindings[name]): + assert resource["metadata"]["annotations"]["firemud.dev/admission-revision"] == "hosted-pod-identity-v1" + +admission_reads = [ + rule for rule in rules(manager_role) + if "admissionregistration.k8s.io" in (rule.get("apiGroups") or []) +] +assert admission_reads == [{ + "apiGroups": ["admissionregistration.k8s.io"], + "resources": ["validatingadmissionpolicies", "validatingadmissionpolicybindings"], + "resourceNames": [ + "firemud-trust-runtime-namespace-boundary", + "firemud-trust-runtime-binding-boundary", + "firemud-trust-runtime-pod-boundary", + "firemud-trust-runtime-pod-identity", + ], + "verbs": ["get"], +}] +for role in (runtime_role, cert_role): + assert not any("admissionregistration.k8s.io" in rule.get("apiGroups", []) for rule in rules(role)) + +# These assertions cover routing and security-critical syntax, not execution +# of native CEL. Server-side allow/deny and post-webhook proof remain required. +for name in ("firemud-trust-runtime-pod-boundary", "firemud-trust-runtime-pod-identity"): + spec = policies[name]["spec"] + assert spec["matchConstraints"] == { + "matchPolicy": "Equivalent", + "resourceRules": [{ + "apiGroups": [""], "apiVersions": ["v1"], + "operations": ["CREATE", "UPDATE"], + "resources": ["pods", "pods/ephemeralcontainers"], + "scope": "Namespaced", + }], + } + assert spec["matchConditions"] == [{ + "name": "hosted-runtime-namespace", + "expression": "request.namespace == 'dev' || request.namespace.matches('^pr-[1-9][0-9]{0,50}$')", + }] + assert "objectSelector" not in spec["matchConstraints"] + assert "namespaceSelector" not in spec["matchConstraints"] + +escape_spec = str(policies["firemud-trust-runtime-pod-boundary"]["spec"]) +for needle in ( + "hostNetwork", "hostPID", "hostIPC", "hostPath", "sysctls", + "hostPort", "allowPrivilegeEscalation", "privileged", "procMount", + "hostProcess", "capabilities.drop", "capabilities.add", "ephemeralContainers", +): + assert needle in escape_spec, f"missing all-Pod escape restriction: {needle}" +identity_spec = str(policies["firemud-trust-runtime-pod-identity"]["spec"]) +for needle in ( + "[oldObject]", "p.metadata.labels", "p.metadata.name", "p.metadata.generateName", + "p.spec.serviceAccountName", "p.spec.containers.exists", "account-service", "game-session-service", + "containers.size() == 1", "initContainers.size() == 0", "ephemeralContainers.size() == 0", + "annotations.size() == 0", "runAsNonRoot", "runAsUser > 0", "RuntimeDefault", + "/var/run/secrets/firemud/pod-identity", "v.name == 'pod-identity'", "v.downwardAPI", + "defaultMode == 292", "items.size() == 1", "path == 'uid'", "fieldPath == 'metadata.uid'", + "m.readOnly", "!has(m.subPath)", "!has(m.subPathExpr)", "mountPropagation == 'None'", + "!m.mountPath.endsWith('/')", "segment in ['.', '..']", + "!variables.identityPath.startsWith(m.mountPath + '/')", + "!m.mountPath.startsWith(variables.identityPath + '/')", +): + assert needle in identity_spec, f"missing protected UID restriction: {needle}" + +# Exercise the actual embedded readback gate against canonical and tampered +# API responses. No Kubernetes process or cluster mutation is involved. +bind_script = (root / "dev-tools/hosted/trust-bootstrap/bind-runtime-roles.sh").read_text(encoding="utf-8") +readback_gate = bind_script.split("<<'PY'\n", 1)[1].split("\nPY\n", 1)[0] +assert bind_script.index("<<'PY'") < bind_script.index('namespace_json="$(kubectl') +assert bind_script.index("\nPY\n") < bind_script.index("binding_document()") +canonical = {(item["kind"], item["metadata"]["name"]): item for item in admission} + + +def readback(responses): + calls = [] + + def fake_get(args, **kwargs): + assert args[:2] == ["kubectl", "get"] + assert args[4:] == ["-o", "json"] + key = (args[2].split(".", 1)[0], args[3]) + calls.append(key) + if key not in responses: + raise subprocess.CalledProcessError(1, args) + return json.dumps(responses[key]) + + with patch.object(sys, "argv", ["readback", str(admission_path)]), patch.object(subprocess, "check_output", fake_get): + exec(compile(readback_gate, "bind-runtime-roles:readback", "exec"), {}) + assert set(calls) == set(canonical) + + +readback(canonical) +defaulted = copy.deepcopy(canonical) +for (kind, name), item in defaulted.items(): + match_key = "matchConstraints" if kind == "ValidatingAdmissionPolicy" else "matchResources" + match = item["spec"].setdefault(match_key, {}) + match.setdefault("matchPolicy", "Equivalent") + match.setdefault("namespaceSelector", {}) + match.setdefault("objectSelector", {}) +readback(defaulted) +for key in canonical: + for mutation in ("missing", "revision", "spec", "terminating", "type-warning", "unknown-field"): + if mutation == "type-warning" and key[0] != "ValidatingAdmissionPolicy": + continue + changed = copy.deepcopy(canonical) + if mutation == "missing": + del changed[key] + elif mutation == "revision": + changed[key]["metadata"]["annotations"]["firemud.dev/admission-revision"] = "stale" + elif mutation == "spec": + # Keep Fail/Deny and the same name while dropping actual enforcement. + if key[0] == "ValidatingAdmissionPolicy": + changed[key]["spec"]["validations"][0]["expression"] = "true" + else: + changed[key]["spec"]["matchResources"] = {"namespaceSelector": {"matchLabels": {"bypass": "true"}}} + elif mutation == "terminating": + changed[key]["metadata"]["deletionTimestamp"] = "2026-10-09T00:00:00Z" + elif mutation == "unknown-field": + changed[key]["spec"]["unexpected"] = True + else: + changed[key]["status"] = {"typeChecking": {"expressionWarnings": [{"warning": "invalid CEL"}]}} + try: + readback(changed) + except (SystemExit, subprocess.CalledProcessError): + pass + else: + raise AssertionError(f"readback accepted {mutation}: {key}") namespace_expression = str(policies["firemud-trust-runtime-namespace-boundary"]["spec"]) binding_expression = str(policies["firemud-trust-runtime-binding-boundary"]["spec"]) assert "system:serviceaccount:firemud-system:firemud-preview-namespace-manager" in namespace_expression diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index 817c2c0702..286c6589d0 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -129,6 +129,69 @@ def test_publication_grpc_consumer_accepts_pod_namespace_field_ref(self): [self._publication_grpc_deployment()], "pr-42" ) + def _protected_grpc_deployment(self, service): + document = self._publication_grpc_deployment() + document["metadata"]["name"] = service + pod = document["spec"]["template"]["spec"] + container = pod["containers"][0] + container["name"] = service + pod["volumes"][0]["secret"]["secretName"] = f"firemud-grpc-{service}" + container["volumeMounts"].append({ + "name": "pod-identity", + "mountPath": "/var/run/secrets/firemud/pod-identity", + "readOnly": True, + }) + pod["volumes"].append({ + "name": "pod-identity", + "downwardAPI": { + "defaultMode": 0o444, + "items": [{ + "path": "uid", + "fieldRef": {"apiVersion": "v1", "fieldPath": "metadata.uid"}, + }], + }, + }) + if service == "account-service": + container["volumeMounts"].append({ + "name": "jwt-jwks", + "mountPath": "/var/run/secrets/firemud/jwks", + "readOnly": True, + }) + pod["volumes"].append({"name": "jwt-jwks", "configMap": {"name": "jwt-jwks"}}) + return document + + def test_protected_consumers_require_exact_kubelet_uid_projection(self): + for service in ("account-service", "game-session-service"): + for mode in ("standalone", "hosted-controller"): + with self.subTest(service=service, mode=mode), patch.object(self.validator, "SERVICE_IMAGES", {service}): + self.validator.validate_service_consumers( + [self._protected_grpc_deployment(service)], "pr-42", mode + ) + + def test_protected_consumers_reject_uid_source_and_mount_substitution(self): + mutations = ( + ("missing", lambda pod, mount, volume: pod["volumes"].remove(volume)), + ("duplicate", lambda pod, mount, volume: pod["volumes"].append(copy.deepcopy(volume))), + ("writable", lambda pod, mount, volume: mount.update({"readOnly": False})), + ("shadow-path", lambda pod, mount, volume: mount.update({"mountPath": "/tmp/uid"})), + ("subpath", lambda pod, mount, volume: mount.update({"subPath": "uid"})), + ("mount-propagation", lambda pod, mount, volume: mount.update({"mountPropagation": "Bidirectional"})), + ("wrong-field", lambda pod, mount, volume: volume["downwardAPI"]["items"][0]["fieldRef"].update({"fieldPath": "metadata.name"})), + ("wrong-path", lambda pod, mount, volume: volume["downwardAPI"]["items"][0].update({"path": "other"})), + ("writable-mode", lambda pod, mount, volume: volume["downwardAPI"].update({"defaultMode": 0o644})), + ("configmap", lambda pod, mount, volume: (volume.pop("downwardAPI"), volume.update({"configMap": {"name": "fake-uid"}}))), + ) + for service in ("account-service", "game-session-service"): + for label, mutate in mutations: + with self.subTest(service=service, mutation=label): + document = self._protected_grpc_deployment(service) + pod = document["spec"]["template"]["spec"] + mount = next(m for m in pod["containers"][0]["volumeMounts"] if m["name"] == "pod-identity") + volume = next(v for v in pod["volumes"] if v["name"] == "pod-identity") + mutate(pod, mount, volume) + with patch.object(self.validator, "SERVICE_IMAGES", {service}), self.assertRaises(ValueError): + self.validator.validate_service_consumers([document], "pr-42") + def test_publication_grpc_consumer_rejects_invalid_namespace_binding(self): invalid_envs = ( ("missing", None), @@ -959,6 +1022,21 @@ def test_consumer_validation_rejects_non_mapping_mounts_and_volumes(self): "metadata": {"name": "account-service"}, "spec": {"template": {"spec": pod}}, } + pod["containers"][0]["volumeMounts"].append({ + "name": "pod-identity", + "mountPath": "/var/run/secrets/firemud/pod-identity", + "readOnly": True, + }) + pod["volumes"].append({ + "name": "pod-identity", + "downwardAPI": { + "defaultMode": 0o444, + "items": [{ + "path": "uid", + "fieldRef": {"apiVersion": "v1", "fieldPath": "metadata.uid"}, + }], + }, + }) with patch.object(self.validator, "SERVICE_IMAGES", {"account-service"}): self.validator.validate_service_consumers( [document], "pr-42", "standalone", "public" diff --git a/k8s/helm/firemud/templates/apps.yaml b/k8s/helm/firemud/templates/apps.yaml index cbefb5c198..0850bd792a 100644 --- a/k8s/helm/firemud/templates/apps.yaml +++ b/k8s/helm/firemud/templates/apps.yaml @@ -68,6 +68,7 @@ {{- range $service := .Values.previewStack.services }} {{- $serviceType := default "ClusterIP" $service.serviceType }} {{- $usesGrpcWorkloadIdentity := has $service.name $grpcWorkloadNames }} +{{- $mountPodIdentity := has $service.name (list "account-service" "game-session-service") }} {{- $mountGrpcTrustBundle := and $service.mountGrpcTls $usesGrpcWorkloadIdentity }} {{- $publicTelnetService := and (eq $service.name "tcp-proxy-service") (or (eq $serviceType "NodePort") (eq $serviceType "LoadBalancer")) }} {{- $telnetPort := "" }} @@ -224,8 +225,13 @@ spec: - secretRef: name: firemud-secret {{- end }} - {{- if or $service.mountGrpcTls $mountGrpcTrustBundle $mountTelnetTls $mountGatewayWsServerTls $mountGatewayWsClientTls (and $previewJwt.enabled $service.envFromShared) }} + {{- if or $mountPodIdentity $service.mountGrpcTls $mountGrpcTrustBundle $mountTelnetTls $mountGatewayWsServerTls $mountGatewayWsClientTls (and $previewJwt.enabled $service.envFromShared) }} volumeMounts: + {{- if $mountPodIdentity }} + - name: pod-identity + mountPath: /var/run/secrets/firemud/pod-identity + readOnly: true + {{- end }} {{- if $service.mountGrpcTls }} - name: grpc-tls mountPath: /tls @@ -295,8 +301,18 @@ spec: limits: cpu: {{ default "750m" $.Values.previewStack.resources.app.limits.cpu | quote }} memory: {{ default "512Mi" $.Values.previewStack.resources.app.limits.memory | quote }} - {{- if or $service.mountGrpcTls $mountGrpcTrustBundle $mountTelnetTls $mountGatewayWsServerTls $mountGatewayWsClientTls (and $previewJwt.enabled $service.envFromShared) }} + {{- if or $mountPodIdentity $service.mountGrpcTls $mountGrpcTrustBundle $mountTelnetTls $mountGatewayWsServerTls $mountGatewayWsClientTls (and $previewJwt.enabled $service.envFromShared) }} volumes: + {{- if $mountPodIdentity }} + - name: pod-identity + downwardAPI: + defaultMode: 0444 + items: + - path: uid + fieldRef: + apiVersion: v1 + fieldPath: metadata.uid + {{- end }} {{- if $service.mountGrpcTls }} - name: grpc-tls secret: diff --git a/k8s/trust-bootstrap/deployment-admission.yaml b/k8s/trust-bootstrap/deployment-admission.yaml index 977eb6e4c7..1f6107c2fe 100644 --- a/k8s/trust-bootstrap/deployment-admission.yaml +++ b/k8s/trust-bootstrap/deployment-admission.yaml @@ -2,6 +2,8 @@ apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicy metadata: name: firemud-trust-runtime-namespace-boundary + annotations: + firemud.dev/admission-revision: hosted-pod-identity-v1 spec: failurePolicy: Fail matchConstraints: @@ -26,6 +28,8 @@ apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding metadata: name: firemud-trust-runtime-namespace-boundary + annotations: + firemud.dev/admission-revision: hosted-pod-identity-v1 spec: policyName: firemud-trust-runtime-namespace-boundary validationActions: [Deny] @@ -34,6 +38,8 @@ apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicy metadata: name: firemud-trust-runtime-binding-boundary + annotations: + firemud.dev/admission-revision: hosted-pod-identity-v1 spec: failurePolicy: Fail matchConstraints: @@ -89,6 +95,184 @@ apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding metadata: name: firemud-trust-runtime-binding-boundary + annotations: + firemud.dev/admission-revision: hosted-pod-identity-v1 spec: policyName: firemud-trust-runtime-binding-boundary validationActions: [Deny] +--- +# Match literal hosted namespace names, never removable Pod/Namespace labels. +# Kubernetes evaluates native validation after mutating admission, including +# subresource updates that could otherwise inject an ephemeral container. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: firemud-trust-runtime-pod-boundary + annotations: + firemud.dev/admission-revision: hosted-pod-identity-v1 +spec: + failurePolicy: Fail + matchConstraints: + matchPolicy: Equivalent + resourceRules: + - apiGroups: [""] + apiVersions: [v1] + operations: [CREATE, UPDATE] + resources: [pods, pods/ephemeralcontainers] + scope: Namespaced + matchConditions: + - name: hosted-runtime-namespace + expression: request.namespace == 'dev' || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') + variables: + - name: containers + expression: >- + object.spec.containers + + (has(object.spec.initContainers) ? object.spec.initContainers : []) + - name: ephemeralContainers + expression: >- + has(object.spec.ephemeralContainers) ? object.spec.ephemeralContainers : [] + validations: + - expression: >- + (!has(object.spec.hostNetwork) || !object.spec.hostNetwork) && + (!has(object.spec.hostPID) || !object.spec.hostPID) && + (!has(object.spec.hostIPC) || !object.spec.hostIPC) && + (!has(object.spec.volumes) || object.spec.volumes.all(v, !has(v.hostPath))) && + (!has(object.spec.securityContext) || + !has(object.spec.securityContext.sysctls) || object.spec.securityContext.sysctls.size() == 0) + message: hosted runtime Pods must not use host namespaces, hostPath, or sysctl overrides + reason: Forbidden + - expression: >- + variables.containers.all(c, + (!has(c.ports) || c.ports.all(p, !has(p.hostPort) || p.hostPort == 0)) && + has(c.securityContext) && + (!has(c.securityContext.privileged) || !c.securityContext.privileged) && + has(c.securityContext.allowPrivilegeEscalation) && !c.securityContext.allowPrivilegeEscalation && + (!has(c.securityContext.procMount) || c.securityContext.procMount == 'Default') && + (!has(c.securityContext.windowsOptions) || !has(c.securityContext.windowsOptions.hostProcess) || !c.securityContext.windowsOptions.hostProcess) && + has(c.securityContext.capabilities) && has(c.securityContext.capabilities.drop) && + 'ALL' in c.securityContext.capabilities.drop && + (!has(c.securityContext.capabilities.add) || c.securityContext.capabilities.add.all(capability, capability == 'NET_BIND_SERVICE'))) + message: every hosted runtime application/init container must drop all capabilities and exclude host ports and privilege escalation + reason: Forbidden + - expression: >- + variables.ephemeralContainers.all(c, + (!has(c.ports) || c.ports.all(p, !has(p.hostPort) || p.hostPort == 0)) && + has(c.securityContext) && + (!has(c.securityContext.privileged) || !c.securityContext.privileged) && + has(c.securityContext.allowPrivilegeEscalation) && !c.securityContext.allowPrivilegeEscalation && + (!has(c.securityContext.procMount) || c.securityContext.procMount == 'Default') && + (!has(c.securityContext.windowsOptions) || !has(c.securityContext.windowsOptions.hostProcess) || !c.securityContext.windowsOptions.hostProcess) && + has(c.securityContext.capabilities) && has(c.securityContext.capabilities.drop) && + 'ALL' in c.securityContext.capabilities.drop && + (!has(c.securityContext.capabilities.add) || c.securityContext.capabilities.add.all(capability, capability == 'NET_BIND_SERVICE'))) + message: hosted runtime ephemeral containers must satisfy the same host and capability restrictions + reason: Forbidden +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: firemud-trust-runtime-pod-boundary + annotations: + firemud.dev/admission-revision: hosted-pod-identity-v1 +spec: + policyName: firemud-trust-runtime-pod-boundary + validationActions: [Deny] +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: firemud-trust-runtime-pod-identity + annotations: + firemud.dev/admission-revision: hosted-pod-identity-v1 +spec: + failurePolicy: Fail + matchConstraints: + matchPolicy: Equivalent + resourceRules: + - apiGroups: [""] + apiVersions: [v1] + operations: [CREATE, UPDATE] + resources: [pods, pods/ephemeralcontainers] + scope: Namespaced + matchConditions: + - name: hosted-runtime-namespace + expression: request.namespace == 'dev' || request.namespace.matches('^pr-[1-9][0-9]{0,50}$') + variables: + - name: protected + # Keep the boundary when an UPDATE removes the original identity labels, + # application name, or ServiceAccount. firemud-app is shared by all apps; + # the specific app/name/container selectors identify its protected users. + expression: >- + ([object] + (oldObject != null ? [oldObject] : [])).exists(p, + (has(p.metadata.labels) && + (('app' in p.metadata.labels && p.metadata.labels['app'] in ['account-service', 'game-session-service']) || + ('app.kubernetes.io/name' in p.metadata.labels && p.metadata.labels['app.kubernetes.io/name'] in ['account-service', 'game-session-service']))) || + (has(p.metadata.name) && p.metadata.name.matches('^(account-service|game-session-service)(-|$)')) || + (has(p.metadata.generateName) && p.metadata.generateName.matches('^(account-service|game-session-service)(-|$)')) || + (has(p.spec.serviceAccountName) && p.spec.serviceAccountName in ['account-service', 'game-session-service']) || + p.spec.containers.exists(c, c.name in ['account-service', 'game-session-service'])) + - name: identityPath + expression: "'/var/run/secrets/firemud/pod-identity'" + validations: + - expression: >- + !variables.protected || + (object.spec.containers.size() == 1 && + object.spec.containers[0].name in ['account-service', 'game-session-service'] && + (!has(object.spec.initContainers) || object.spec.initContainers.size() == 0) && + (!has(object.spec.ephemeralContainers) || object.spec.ephemeralContainers.size() == 0) && + (!has(object.metadata.annotations) || object.metadata.annotations.size() == 0)) + message: Account and Game Session require exactly their application container and no init/ephemeral containers or injected annotations + reason: Forbidden + - expression: >- + !variables.protected || + (has(object.spec.securityContext) && + has(object.spec.securityContext.runAsNonRoot) && object.spec.securityContext.runAsNonRoot && + has(object.spec.securityContext.runAsUser) && object.spec.securityContext.runAsUser > 0 && + has(object.spec.securityContext.seccompProfile) && object.spec.securityContext.seccompProfile.type == 'RuntimeDefault' && + object.spec.containers.all(c, + has(c.securityContext) && + (!has(c.securityContext.runAsNonRoot) || c.securityContext.runAsNonRoot) && + (!has(c.securityContext.runAsUser) || c.securityContext.runAsUser > 0) && + (!has(c.securityContext.seccompProfile) || c.securityContext.seccompProfile.type == 'RuntimeDefault') && + (!has(c.volumeDevices) || c.volumeDevices.size() == 0))) + message: protected Pod identity consumers require nonroot RuntimeDefault confinement without block devices + reason: Forbidden + - expression: >- + !variables.protected || + (has(object.spec.volumes) && object.spec.volumes.filter(v, v.name == 'pod-identity').size() == 1 && + object.spec.volumes.filter(v, v.name == 'pod-identity').all(v, + has(v.downwardAPI) && has(v.downwardAPI.defaultMode) && v.downwardAPI.defaultMode == 292 && + has(v.downwardAPI.items) && v.downwardAPI.items.size() == 1 && + v.downwardAPI.items[0].path == 'uid' && + (!has(v.downwardAPI.items[0].mode) || v.downwardAPI.items[0].mode == 292) && + has(v.downwardAPI.items[0].fieldRef) && + v.downwardAPI.items[0].fieldRef.apiVersion == 'v1' && + v.downwardAPI.items[0].fieldRef.fieldPath == 'metadata.uid' && + !has(v.downwardAPI.items[0].resourceFieldRef))) + message: protected Pod UID must come only from the canonical kubelet downwardAPI metadata.uid volume + reason: Forbidden + - expression: >- + !variables.protected || object.spec.containers.all(c, + has(c.volumeMounts) && c.volumeMounts.filter(m, m.name == 'pod-identity').size() == 1 && + c.volumeMounts.all(m, + m.mountPath.startsWith('/') && !m.mountPath.endsWith('/') && !m.mountPath.contains('//') && + !m.mountPath.split('/').exists(segment, segment in ['.', '..']) && + (m.name == 'pod-identity' ? + (m.mountPath == variables.identityPath && has(m.readOnly) && m.readOnly && + !has(m.subPath) && !has(m.subPathExpr) && + (!has(m.mountPropagation) || m.mountPropagation == 'None')) : + (m.mountPath != '/' && m.mountPath != variables.identityPath && + !variables.identityPath.startsWith(m.mountPath + '/') && + !m.mountPath.startsWith(variables.identityPath + '/'))))) + message: protected Pod UID mount must be read-only at the canonical path without subpaths, shadow mounts, or mount propagation + reason: Forbidden +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: firemud-trust-runtime-pod-identity + annotations: + firemud.dev/admission-revision: hosted-pod-identity-v1 +spec: + policyName: firemud-trust-runtime-pod-identity + validationActions: [Deny] diff --git a/k8s/trust-bootstrap/deployment-rbac.yaml b/k8s/trust-bootstrap/deployment-rbac.yaml index dff232f1d4..1fea8248fe 100644 --- a/k8s/trust-bootstrap/deployment-rbac.yaml +++ b/k8s/trust-bootstrap/deployment-rbac.yaml @@ -155,6 +155,16 @@ rules: - firemud-preview-runtime - firemud-standalone-certificate-writer verbs: ["get", "bind"] + # Trusted role grants require exact readback of the installed Pod boundary. + # Named GET cannot list admission resources or alter enforcement. + - apiGroups: ["admissionregistration.k8s.io"] + resources: ["validatingadmissionpolicies", "validatingadmissionpolicybindings"] + resourceNames: + - firemud-trust-runtime-namespace-boundary + - firemud-trust-runtime-binding-boundary + - firemud-trust-runtime-pod-boundary + - firemud-trust-runtime-pod-identity + verbs: ["get"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding diff --git a/protos/account/v1/jwt_readiness_receiver.proto b/protos/account/v1/jwt_readiness_receiver.proto index 1951c87ba6..ee64b0fa91 100644 --- a/protos/account/v1/jwt_readiness_receiver.proto +++ b/protos/account/v1/jwt_readiness_receiver.proto @@ -10,6 +10,9 @@ option java_multiple_files = true; service AccountJwtReadinessProbeOwnerService { rpc GetCurrentReadinessProbeOwner(GetCurrentReadinessProbeOwnerRequest) returns (GetCurrentReadinessProbeOwnerResponse); + // Non-authorizing protected local identity bootstrap; Account selects the current operation. + rpc GetCurrentReadinessReceiverMetadata(GetCurrentReadinessReceiverMetadataRequest) + returns (GetCurrentReadinessReceiverMetadataResponse); } message ReadinessProbeCoordinates { @@ -80,7 +83,26 @@ message ReadinessReceiverLocalIdentity { string source_inventory_digest = 11; string server_leaf_spki_sha256 = 12; AccountSourceIdentity account_jwks_source_identity = 13; - int64 account_jwks_trust_config_revision = 14; + reserved 14; + reserved "account_jwks_trust_config_revision"; + string account_jwks_trust_binding_revision = 15; + string account_public_jwks_sha256 = 16; +} + +// Neither the operation, plan nor source pins are caller-selectable. The UID must come from the +// protected kubelet projection; the leaf pin must describe the caller's actual local TLS leaf. +message GetCurrentReadinessReceiverMetadataRequest { + int32 schema_version = 1; + string projected_pod_uid = 2; + string server_leaf_spki_sha256 = 3; +} + +message GetCurrentReadinessReceiverMetadataResponse { + int32 schema_version = 1; + string rotation_operation_id = 2; + string operation_digest = 3; + string plan_digest = 4; + ReadinessReceiverLocalIdentity current_identity = 5; } // Account's current API/inventory source pins and Pod target. These are not Game Session's diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverConfiguration.java index 0453b0bbef..19b88f34b1 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessPodReceiverConfiguration.java @@ -80,11 +80,7 @@ public AccountJwtReadinessPodLocalIdentityProvider accountJwtPodLocalIdentityPro AccountJwtJwksTrustedSource trustedJwksSource, SslBundles sslBundles) { return new AccountJwtReadinessPodLocalIdentityProvider( - inventorySource, - trustedJwksSource, - sslBundles, - Clock.systemUTC(), - System.getenv("HOSTNAME")); + inventorySource, trustedJwksSource, sslBundles, Clock.systemUTC()); } @Bean diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerConfiguration.java index 8d4e15c1a5..0560a4c151 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerConfiguration.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessProbeOwnerConfiguration.java @@ -2,9 +2,11 @@ import java.time.Clock; import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerProtoMapper; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerService; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverMetadataService; import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; @@ -17,7 +19,7 @@ import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; -/** Default-false composition for the isolated exact-probe owner lookup RPC. */ +/** Default-false composition for isolated protected readiness owner and metadata RPCs. */ @Configuration(proxyBeanMethods = false) @ConditionalOnProperty( prefix = "firemud.account.jwt-readiness.probe-owner", @@ -83,4 +85,24 @@ public AccountJwtReadinessProbeOwnerService accountJwtReadinessProbeOwnerService return new AccountJwtReadinessProbeOwnerService( probeService, materializerTrustBinding, workloadGuard, protoMapper); } + + @Bean + @Lazy + public AccountJwtReadinessReceiverMetadataService accountJwtReadinessReceiverMetadataService( + AccountJwtReadinessProbeService probeService, + AccountJwtValidatorInventorySource inventorySource, + @Qualifier("accountJwtReadinessTrustedJwksSource") + AccountJwtJwksTrustedSource trustedJwksSource, + AccountJwtReadinessProbeOwnerWorkloadGuard workloadGuard, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtReadinessProbeOwnerProtoMapper protoMapper) { + return new AccountJwtReadinessReceiverMetadataService( + probeService, + inventorySource, + trustedJwksSource, + workloadGuard, + materializerTrustBinding, + protoMapper, + Clock.systemUTC()); + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java index c64027e9f2..0af6e44d00 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcService.java @@ -5,11 +5,14 @@ import net.firedevops.firemud.account.v1.AccountJwtReadinessProbeOwnerServiceGrpc; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataResponse; import net.firedevops.firemud.accountservice.config.AccountJwtReadinessPrerequisiteConfiguration; import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerWorkloadGuard; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerProtoMapper; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerService; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverMetadataService; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Lazy; @@ -29,9 +32,13 @@ public final class AccountJwtReadinessProbeOwnerGrpcService private static final String UNAVAILABLE = "Account readiness probe owner is unavailable"; private final AccountJwtReadinessProbeOwnerService owner; + private final AccountJwtReadinessReceiverMetadataService metadata; - public AccountJwtReadinessProbeOwnerGrpcService(AccountJwtReadinessProbeOwnerService owner) { + public AccountJwtReadinessProbeOwnerGrpcService( + AccountJwtReadinessProbeOwnerService owner, + AccountJwtReadinessReceiverMetadataService metadata) { this.owner = owner; + this.metadata = metadata; } @Override @@ -61,4 +68,32 @@ public void getCurrentReadinessProbeOwner( Status.UNAVAILABLE.withDescription(UNAVAILABLE).asRuntimeException()); } } + + @Override + public void getCurrentReadinessReceiverMetadata( + GetCurrentReadinessReceiverMetadataRequest request, + StreamObserver responseObserver) { + try { + responseObserver.onNext(metadata.getCurrentReadinessReceiverMetadata(request)); + responseObserver.onCompleted(); + } catch (AccountJwtReadinessProbeOwnerWorkloadGuard.OwnerReadDeniedException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Authorized Game Session workload is required") + .asRuntimeException()); + } catch (AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Readiness owner request is invalid") + .asRuntimeException()); + } catch (AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException unavailable) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Current readiness owner evidence is unavailable") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE.withDescription(UNAVAILABLE).asRuntimeException()); + } + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java index bff7b6e58f..4da29e2408 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPort.java @@ -257,7 +257,10 @@ private AuthenticatedAcceptance authenticatedResponse( || response.accountJwksSourceIdentity().isEmpty() || !sourceIdentityMatchesTarget( response.accountJwksSourceIdentity().orElseThrow(), invocation.target()) - || !response.trustBindingRevisionValid()) { + || !response + .trustBindingRevision() + .equals(response.accountJwksSourceIdentity().orElseThrow().bindingRevision()) + || (response.publicJwksHashRequired() && !isSha256(response.publicJwksSha256()))) { throw new ReceiverUnavailableException(); } @@ -309,7 +312,9 @@ private static ReceiverObservation observation(ReceiveReadinessProbeResponse res identity.getSourceInventoryDigest(), identity.getServerLeafSpkiSha256(), accountSourceIdentity(identity.getAccountJwksSourceIdentity()), - identity.getAccountJwksTrustConfigRevision() > 0L, + identity.getAccountJwksTrustBindingRevision(), + identity.getAccountPublicJwksSha256(), + true, response.hasAccountPodTarget() ? response.getAccountPodTarget() : AccountPodTargetBinding.getDefaultInstance(), @@ -343,7 +348,9 @@ private static ReceiverObservation observation(ReceiveAccountJwtReadinessProbeRe identity.getSourceInventoryDigest(), identity.getServerLeafSpkiSha256(), accountSourceIdentity(identity.getAccountJwksSourceIdentity()), - isCanonicalRevision(identity.getJwksTrustBindingRevision()), + identity.getJwksTrustBindingRevision(), + "", + false, response.hasAccountPodTarget() ? response.getAccountPodTarget() : AccountPodTargetBinding.getDefaultInstance(), @@ -537,7 +544,9 @@ private record ReceiverObservation( String sourceInventoryDigest, String serverLeafSpkiSha256, Optional accountJwksSourceIdentity, - boolean trustBindingRevisionValid, + String trustBindingRevision, + String publicJwksSha256, + boolean publicJwksHashRequired, AccountPodTargetBinding accountPodTarget, boolean targetUnknownFields, ProbeExpectation outcome, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java index b0959efa5e..019084d88b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProvider.java @@ -11,6 +11,8 @@ import java.util.List; import java.util.Objects; import java.util.Set; +import java.util.function.Supplier; +import java.util.regex.Pattern; import net.firedevops.firemud.account.v1.AccountJwtPodReceiverIdentity; import net.firedevops.firemud.account.v1.AccountSourceIdentity; import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; @@ -23,37 +25,46 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.ProtectedPodUidProjection; import org.springframework.boot.ssl.SslBundle; import org.springframework.boot.ssl.SslBundles; /** - * Derives the local Account Pod identity only from protected live inventory, the active server - * certificate, and Account's protected JWKS source. No receiver-request identity is accepted. + * Derives the local Account Pod identity only from its protected UID projection, live inventory, + * the active server certificate, and Account's protected JWKS source. No receiver-request identity + * is accepted. */ public final class AccountJwtReadinessPodLocalIdentityProvider { private static final String ACCOUNT_VALIDATOR_ID = AccountJwtReadinessProbeCrypto.VALIDATOR_ID; private static final String TLS_BUNDLE_NAME = "firemud-grpc"; + private static final Pattern KUBERNETES_UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); private final AccountJwtValidatorInventorySource inventorySource; private final AccountJwtJwksTrustedSource trustedJwksSource; private final SslBundles sslBundles; private final Clock clock; - private final String localPodName; + private final Supplier localPodUidSource; - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Spring-managed SslBundles is retained for live server-certificate reads.") public AccountJwtReadinessPodLocalIdentityProvider( + AccountJwtValidatorInventorySource inventorySource, + AccountJwtJwksTrustedSource trustedJwksSource, + SslBundles sslBundles, + Clock clock) { + this(inventorySource, trustedJwksSource, sslBundles, clock, ProtectedPodUidProjection::read); + } + + AccountJwtReadinessPodLocalIdentityProvider( AccountJwtValidatorInventorySource inventorySource, AccountJwtJwksTrustedSource trustedJwksSource, SslBundles sslBundles, Clock clock, - String localPodName) { + Supplier localPodUidSource) { this.inventorySource = Objects.requireNonNull(inventorySource); this.trustedJwksSource = Objects.requireNonNull(trustedJwksSource); this.sslBundles = Objects.requireNonNull(sslBundles); this.clock = Objects.requireNonNull(clock); - this.localPodName = localPodName == null ? "" : localPodName.trim(); + this.localPodUidSource = Objects.requireNonNull(localPodUidSource); } /** Re-reads every protected identity source and requires the actual local TLS leaf to match. */ @@ -67,15 +78,19 @@ public LocalObservation observe(String applicabilityMatrixDigest) { public LocalObservation observe( String applicabilityMatrixDigest, ObservationContext observationContext) { try { + String localPodUid = readLocalPodUid(); InventorySnapshot inventory = observationContext == null ? inventorySource.observe() : inventorySource.observe(observationContext); + requireStableLocalPodUid(localPodUid); ValidatorObservation validator = exactAccountValidator(inventory); - PodObservation pod = exactLocalPod(validator, inventory.namespace()); + PodObservation pod = exactLocalPod(validator, inventory.namespace(), localPodUid); SourceIdentity jwksSourceIdentity = readCurrentJwksSourceIdentity(); + requireStableLocalPodUid(localPodUid); requireSameAccountCluster(inventory, jwksSourceIdentity); String actualLeafSpki = localServerLeafSpki(sslBundles, clock, pod.receiverServiceUri()); + requireStableLocalPodUid(localPodUid); if (!actualLeafSpki.equals(pod.leafSpkiSha256())) { throw new IdentityUnavailableException(); } @@ -111,6 +126,7 @@ public LocalObservation observe( .setAccountJwksSourceIdentity(toProto(jwksSourceIdentity)) .setJwksTrustBindingRevision(jwksSourceIdentity.bindingRevision()) .build(); + requireStableLocalPodUid(localPodUid); return new LocalObservation(selectorIdentity, wireIdentity); } catch (IdentityUnavailableException failure) { throw failure; @@ -119,6 +135,24 @@ public LocalObservation observe( } } + private String readLocalPodUid() { + String uid = localPodUidSource.get(); + if (!isCanonicalUid(uid)) { + throw new IdentityUnavailableException(); + } + return uid; + } + + private void requireStableLocalPodUid(String expectedUid) { + if (!expectedUid.equals(readLocalPodUid())) { + throw new IdentityUnavailableException(); + } + } + + private static boolean isCanonicalUid(String value) { + return value != null && KUBERNETES_UID.matcher(value).matches(); + } + private SourceIdentity readCurrentJwksSourceIdentity() { PublicJwksSnapshot snapshot = trustedJwksSource.load(); if (snapshot == null) { @@ -157,12 +191,10 @@ private ValidatorObservation exactAccountValidator(InventorySnapshot inventory) return validator; } - private PodObservation exactLocalPod(ValidatorObservation validator, String namespace) { - if (localPodName.isBlank()) { - throw new IdentityUnavailableException(); - } + private PodObservation exactLocalPod( + ValidatorObservation validator, String namespace, String localPodUid) { List matches = - validator.pods().stream().filter(value -> localPodName.equals(value.name())).toList(); + validator.pods().stream().filter(value -> localPodUid.equals(value.uid())).toList(); if (matches.size() != 1) { throw new IdentityUnavailableException(); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapper.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapper.java index 2f58713901..1a2d8bbd7e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapper.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapper.java @@ -2,20 +2,58 @@ import java.util.UUID; import net.firedevops.firemud.account.v1.AccountPodTargetBinding; +import net.firedevops.firemud.account.v1.AccountSourceIdentity; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataResponse; import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; +import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.OwnerProbeEvidence; import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; /** Strict closed-wire mapper; caller-local Account JWKS pins are validated but never echoed. */ public final class AccountJwtReadinessProbeOwnerProtoMapper { private static final int SCHEMA_VERSION = 1; + private static final int MAX_RECEIVER_METADATA_REQUEST_BYTES = 256; + private static final String SHA256 = "[0-9a-f]{64}"; + private static final String UID = + "[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"; + + /** Strict parse of the two caller-selected local values; neither is owner evidence. */ + public ReceiverMetadataSelector parseReceiverMetadataRequest( + GetCurrentReadinessReceiverMetadataRequest request) { + if (request == null + || request.getSchemaVersion() != SCHEMA_VERSION + || request.getSerializedSize() > MAX_RECEIVER_METADATA_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty()) { + throw new InvalidOwnerReadRequestException(); + } + String podUid = request.getProjectedPodUid(); + String serverLeafSpkiSha256 = request.getServerLeafSpkiSha256(); + try { + if (podUid.length() != 36 || serverLeafSpkiSha256.length() != 64) { + throw new IllegalArgumentException(); + } + UUID parsedUid = UUID.fromString(podUid); + if (!parsedUid.toString().equals(podUid) + || !podUid.matches(UID) + || !serverLeafSpkiSha256.matches(SHA256)) { + throw new IllegalArgumentException(); + } + return new ReceiverMetadataSelector(podUid, serverLeafSpkiSha256); + } catch (RuntimeException invalid) { + throw new InvalidOwnerReadRequestException(); + } + } public AccountJwtReadinessProbeOwnerSelector parse(GetCurrentReadinessProbeOwnerRequest request) { if (request == null @@ -82,7 +120,9 @@ public AccountJwtReadinessProbeOwnerSelector parse(GetCurrentReadinessProbeOwner source.getBindingRevision(), source.getApiServerOrigin(), source.getServingCaSha256()); - if (local.getAccountJwksTrustConfigRevision() <= 0L) { + if (local.getAccountJwksTrustBindingRevision().isEmpty() + || !local.getAccountJwksTrustBindingRevision().equals(source.getBindingRevision()) + || !local.getAccountPublicJwksSha256().matches(SHA256)) { throw new IllegalArgumentException(); } return new AccountJwtReadinessProbeOwnerSelector( @@ -200,6 +240,52 @@ public GetCurrentReadinessProbeOwnerResponse toResponse(OwnerProbeEvidence evide .build(); } + public GetCurrentReadinessReceiverMetadataResponse toReceiverMetadataResponse( + ReadinessProbePlan plan, + InventorySnapshot inventory, + ValidatorObservation validator, + PodObservation pod, + SourceIdentity jwksSourceIdentity, + String publicJwksSha256) { + AccountSourceIdentity sourceIdentity = + AccountSourceIdentity.newBuilder() + .setEnvironmentId(jwksSourceIdentity.environmentId()) + .setClusterId(jwksSourceIdentity.clusterId()) + .setClusterIncarnationUid(jwksSourceIdentity.clusterIncarnationUid()) + .setNamespace(jwksSourceIdentity.namespace()) + .setNamespaceUid(jwksSourceIdentity.namespaceUid()) + .setConfigMapUid(jwksSourceIdentity.configMapUid()) + .setBindingRevision(jwksSourceIdentity.bindingRevision()) + .setApiServerOrigin(jwksSourceIdentity.apiServerOrigin()) + .setServingCaSha256(jwksSourceIdentity.servingCaSha256()) + .build(); + ReadinessReceiverLocalIdentity identity = + ReadinessReceiverLocalIdentity.newBuilder() + .setValidatorId(validator.validatorId()) + .setDeploymentUid(validator.deploymentUid()) + .setPodUid(pod.uid()) + .setPodIp(pod.podIp()) + .setDirectPodEndpoint(pod.endpoint().toString()) + .setCanonicalServiceUri(pod.receiverServiceUri()) + .setImage(pod.image()) + .setVerifierConfigSha256(pod.verifierConfigSha256()) + .setApplicabilityMatrixDigest(plan.applicabilityMatrixDigest()) + .setSourceInventoryRevision(inventory.inventoryBindingRevision()) + .setSourceInventoryDigest(inventory.digest()) + .setServerLeafSpkiSha256(pod.leafSpkiSha256()) + .setAccountJwksSourceIdentity(sourceIdentity) + .setAccountJwksTrustBindingRevision(jwksSourceIdentity.bindingRevision()) + .setAccountPublicJwksSha256(publicJwksSha256) + .build(); + return GetCurrentReadinessReceiverMetadataResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setRotationOperationId(plan.operationId().toString()) + .setOperationDigest(plan.operationDigest()) + .setPlanDigest(plan.planDigest()) + .setCurrentIdentity(identity) + .build(); + } + private static UUID canonicalUuid(String value) { UUID parsed = UUID.fromString(value); if (!parsed.toString().equals(value)) { @@ -208,6 +294,8 @@ private static UUID canonicalUuid(String value) { return parsed; } + public record ReceiverMetadataSelector(String projectedPodUid, String serverLeafSpkiSha256) {} + public static final class InvalidOwnerReadRequestException extends RuntimeException { public InvalidOwnerReadRequestException() { super("Readiness probe owner request is invalid"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java index 470b46922d..c001802deb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java @@ -209,6 +209,11 @@ public AccountJwtValidatorInventorySource.InventorySnapshot observeCurrentInvent return inventorySource.observe(); } + /** Reads only an owner-derived current V2 operation context for the Pod-local receiver proof. */ + ObservationContext readCurrentInventoryObservationContext(Binding binding, TrustFence trust) { + return inTransaction(() -> repository.readCurrentInventoryObservationContext(binding, trust)); + } + /** Reads only an owner-derived current V2 operation context for the Pod-local receiver proof. */ ObservationContext readCurrentInventoryObservationContext( Binding binding, TrustFence trust, UUID operationId) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataService.java new file mode 100644 index 0000000000..2a2468a563 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataService.java @@ -0,0 +1,415 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.net.URI; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerWorkloadGuard; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerWorkloadGuard.AuthenticatedCaller; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ReplicaSetObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Read-only Account producer for protected Game Session readiness receiver metadata. + * + *

The request UID and TLS leaf digest are selectors only. Account independently joins the + * selected Pod through its current protected inventory and never treats either request field as + * proof that the caller is that Pod or that its TLS connection used the selected leaf. + */ +public final class AccountJwtReadinessReceiverMetadataService { + private static final int SCHEMA_VERSION = 1; + private static final int INVENTORY_PLAN_VERSION = + AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION; + private static final String GAME_SESSION_VALIDATOR = "game-session-service"; + private static final String SPIFFE_PREFIX = "spiffe://firemud/ns/"; + private static final String SHA256_PATTERN = "[0-9a-f]{64}"; + private static final String REVISION_PATTERN = "[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"; + + private final AccountJwtReadinessProbeService probeService; + private final AccountJwtValidatorInventorySource inventorySource; + private final AccountJwtJwksTrustedSource trustedJwksSource; + private final AccountJwtReadinessProbeOwnerWorkloadGuard workloadGuard; + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtReadinessProbeOwnerProtoMapper protoMapper; + private final Clock clock; + + public AccountJwtReadinessReceiverMetadataService( + AccountJwtReadinessProbeService probeService, + AccountJwtValidatorInventorySource inventorySource, + AccountJwtJwksTrustedSource trustedJwksSource, + AccountJwtReadinessProbeOwnerWorkloadGuard workloadGuard, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtReadinessProbeOwnerProtoMapper protoMapper, + Clock clock) { + this.probeService = Objects.requireNonNull(probeService); + this.inventorySource = Objects.requireNonNull(inventorySource); + this.trustedJwksSource = Objects.requireNonNull(trustedJwksSource); + this.workloadGuard = Objects.requireNonNull(workloadGuard); + this.materializerTrustBinding = Objects.requireNonNull(materializerTrustBinding); + this.protoMapper = Objects.requireNonNull(protoMapper); + this.clock = Objects.requireNonNull(clock); + } + + public GetCurrentReadinessReceiverMetadataResponse getCurrentReadinessReceiverMetadata( + GetCurrentReadinessReceiverMetadataRequest request) { + requireNoAmbientTransaction(); + AuthenticatedCaller caller = workloadGuard.requireGameSessionOwnerReadCaller(); + AccountJwtReadinessProbeOwnerProtoMapper.ReceiverMetadataSelector selector = + protoMapper.parseReceiverMetadataRequest(request); + try { + return readCurrent(caller, selector); + } catch (AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException unavailable) { + throw unavailable; + } catch (RuntimeException unavailable) { + // Keep repository, Kubernetes, TLS, and JWKS source details out of this read boundary. + throw new AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException(); + } + } + + private GetCurrentReadinessReceiverMetadataResponse readCurrent( + AuthenticatedCaller caller, + AccountJwtReadinessProbeOwnerProtoMapper.ReceiverMetadataSelector selector) { + AccountJwtSignerMaterializerTrustBinding.Binding protectedBinding = caller.accountBinding(); + var accountBinding = protectedBinding.accountBinding(); + TrustFence trustFence = AccountJwtReadinessValidationService.trustFence(protectedBinding); + + AccountJwtValidatorInventorySource.ObservationContext context = + probeService.readCurrentInventoryObservationContext(accountBinding, trustFence); + ReadinessProbePlan plan = + probeService.readCurrentPlan(accountBinding, trustFence, context.operationId()); + requireCurrentCompletePlan(plan, context, accountBinding, trustFence); + + InventorySnapshot firstInventory = observe(context); + requirePlanInventory(plan, firstInventory, context, protectedBinding, trustFence); + SourceRead firstJwks = readPublicJwks(firstInventory, protectedBinding, trustFence); + SelectedPod firstPod = selectGameSessionPod(firstInventory, selector); + + // Re-read the exact current operation and immutable plan identity after all first-pass network + // reads. Plan entry receipts may advance independently and are deliberately not compared. + requireNoAmbientTransaction(); + var currentContext = + probeService.readCurrentInventoryObservationContext(accountBinding, trustFence); + if (!context.equals(currentContext)) { + throw unavailable(); + } + var exactContext = + probeService.readCurrentInventoryObservationContext( + accountBinding, trustFence, context.operationId()); + if (!context.equals(exactContext)) { + throw unavailable(); + } + ReadinessProbePlan currentPlan = + probeService.readCurrentPlan(accountBinding, trustFence, context.operationId()); + requireCurrentCompletePlan(currentPlan, exactContext, accountBinding, trustFence); + if (!PlanIdentity.from(plan).equals(PlanIdentity.from(currentPlan))) { + throw unavailable(); + } + + InventorySnapshot currentInventory = observe(exactContext); + requirePlanInventory(currentPlan, currentInventory, exactContext, protectedBinding, trustFence); + if (!firstInventory.digest().equals(currentInventory.digest())) { + throw unavailable(); + } + SourceRead currentJwks = readPublicJwks(currentInventory, protectedBinding, trustFence); + if (!firstJwks.sourceIdentity().equals(currentJwks.sourceIdentity()) + || !firstJwks.sha256().equals(currentJwks.sha256())) { + throw unavailable(); + } + SelectedPod currentPod = selectGameSessionPod(currentInventory, selector); + if (!firstPod.equals(currentPod)) { + throw unavailable(); + } + + // Fence changes that happen during the second external read phase as well. + requireNoAmbientTransaction(); + var finalContext = + probeService.readCurrentInventoryObservationContext(accountBinding, trustFence); + if (!context.equals(finalContext)) { + throw unavailable(); + } + var finalExactContext = + probeService.readCurrentInventoryObservationContext( + accountBinding, trustFence, context.operationId()); + if (!context.equals(finalExactContext)) { + throw unavailable(); + } + ReadinessProbePlan finalPlan = + probeService.readCurrentPlan(accountBinding, trustFence, context.operationId()); + requireCurrentCompletePlan(finalPlan, finalExactContext, accountBinding, trustFence); + if (!PlanIdentity.from(currentPlan).equals(PlanIdentity.from(finalPlan))) { + throw unavailable(); + } + + AuthenticatedCaller currentCaller = workloadGuard.requireGameSessionOwnerReadCaller(); + Optional latestBinding = + materializerTrustBinding.current(); + if (!protectedBinding.equals(currentCaller.accountBinding()) + || latestBinding.isEmpty() + || !protectedBinding.equals(latestBinding.orElseThrow())) { + throw unavailable(); + } + + return protoMapper.toReceiverMetadataResponse( + currentPlan, + currentInventory, + currentPod.validator(), + currentPod.pod(), + currentJwks.sourceIdentity(), + currentJwks.sha256()); + } + + private InventorySnapshot observe(AccountJwtValidatorInventorySource.ObservationContext context) { + requireNoAmbientTransaction(); + return inventorySource.observe(context); + } + + private SourceRead readPublicJwks( + InventorySnapshot inventory, + AccountJwtSignerMaterializerTrustBinding.Binding binding, + TrustFence trustFence) { + requireNoAmbientTransaction(); + SourceIdentity sourceBefore = trustedJwksSource.sourceIdentity(); + requireJwksSourceMatchesInventory(sourceBefore, inventory, binding, trustFence); + + requireNoAmbientTransaction(); + PublicJwksSnapshot snapshot = trustedJwksSource.load(); + byte[] jwksBytes = snapshot.jwksBytes(); + try { + requireNoAmbientTransaction(); + SourceIdentity sourceAfter = trustedJwksSource.sourceIdentity(); + if (!sourceBefore.equals(snapshot.sourceIdentity()) + || !sourceBefore.equals(sourceAfter) + || jwksBytes == null + || jwksBytes.length == 0 + || jwksBytes.length > AccountPublicJwksCache.MAX_JWKS_BYTES) { + throw unavailable(); + } + String digest = sha256(jwksBytes); + if (!digest.matches(SHA256_PATTERN)) { + throw unavailable(); + } + return new SourceRead(sourceAfter, digest); + } finally { + if (jwksBytes != null) { + Arrays.fill(jwksBytes, (byte) 0); + } + } + } + + private void requireCurrentCompletePlan( + ReadinessProbePlan plan, + AccountJwtValidatorInventorySource.ObservationContext context, + Binding binding, + TrustFence trustFence) { + if (plan == null + || plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || plan.inventorySnapshotDigest().isEmpty() + || !plan.operationId().equals(context.operationId()) + || !plan.operationDigest().equals(context.operationDigest()) + || !plan.binding().equals(binding) + || !plan.trustFence().equals(trustFence) + || plan.planDigest() == null + || !plan.planDigest().matches(SHA256_PATTERN) + || plan.applicabilityMatrixDigest() == null + || !plan.applicabilityMatrixDigest().matches(SHA256_PATTERN) + || plan.expiresAtEpochSecond() <= clock.instant().getEpochSecond()) { + throw unavailable(); + } + } + + private void requirePlanInventory( + ReadinessProbePlan plan, + InventorySnapshot snapshot, + AccountJwtValidatorInventorySource.ObservationContext context, + AccountJwtSignerMaterializerTrustBinding.Binding binding, + TrustFence trustFence) { + if (snapshot == null + || snapshot.observationContext().filter(context::equals).isEmpty() + || !plan.inventorySnapshotDigest().equals(Optional.of(snapshot.digest())) + || !snapshot.digest().matches(SHA256_PATTERN) + || !snapshot.inventoryBindingRevision().matches(REVISION_PATTERN) + || !snapshot.inventoryBindingDigest().matches(SHA256_PATTERN) + || !snapshot.environmentId().equals(binding.environmentId()) + || !snapshot.clusterId().equals(binding.clusterId()) + || !snapshot.namespace().equals(binding.namespace()) + || !snapshot.clusterIncarnationUid().equals(trustFence.expectedClusterIncarnationUid()) + || !snapshot.namespaceUid().equals(trustFence.expectedNamespaceUid())) { + throw unavailable(); + } + } + + private static void requireJwksSourceMatchesInventory( + SourceIdentity source, + InventorySnapshot inventory, + AccountJwtSignerMaterializerTrustBinding.Binding binding, + TrustFence trustFence) { + if (source == null + || !source.environmentId().equals(inventory.environmentId()) + || !source.clusterId().equals(inventory.clusterId()) + || !source.clusterIncarnationUid().equals(inventory.clusterIncarnationUid()) + || !source.namespace().equals(inventory.namespace()) + || !source.namespaceUid().equals(inventory.namespaceUid()) + || !source.environmentId().equals(binding.environmentId()) + || !source.clusterId().equals(binding.clusterId()) + || !source.namespace().equals(binding.namespace()) + || !source.clusterIncarnationUid().equals(trustFence.expectedClusterIncarnationUid()) + || !source.namespaceUid().equals(trustFence.expectedNamespaceUid())) { + throw unavailable(); + } + } + + private static SelectedPod selectGameSessionPod( + InventorySnapshot inventory, + AccountJwtReadinessProbeOwnerProtoMapper.ReceiverMetadataSelector selector) { + List gameSessionValidators = + inventory.validators().stream() + .filter(value -> GAME_SESSION_VALIDATOR.equals(value.validatorId())) + .toList(); + if (gameSessionValidators.size() != 1) { + throw unavailable(); + } + ValidatorObservation validator = gameSessionValidators.getFirst(); + if (inventory.validators().stream() + .flatMap(value -> value.pods().stream()) + .filter(value -> selector.projectedPodUid().equals(value.uid())) + .count() + != 1) { + throw unavailable(); + } + List selected = + validator.pods().stream() + .filter(value -> selector.projectedPodUid().equals(value.uid())) + .toList(); + if (selected.size() != 1) { + throw unavailable(); + } + PodObservation pod = selected.getFirst(); + requirePodDeploymentJoin(inventory, validator, pod); + if (!selector.serverLeafSpkiSha256().equals(pod.leafSpkiSha256())) { + throw unavailable(); + } + return new SelectedPod(validator, pod); + } + + private static void requirePodDeploymentJoin( + InventorySnapshot inventory, ValidatorObservation validator, PodObservation pod) { + List ownedReplicaSets = + validator.replicaSets().stream() + .filter( + replicaSet -> + replicaSet.uid().equals(pod.ownerUid()) + && replicaSet.name().equals(pod.ownerName())) + .toList(); + URI endpoint = pod.endpoint(); + String endpointHost = endpoint == null ? null : endpoint.getHost(); + if (ownedReplicaSets.size() != 1 + || !inventory.namespace().matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?") + || !validator + .deploymentUid() + .matches("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}") + || pod.uid() == null + || !pod.uid() + .matches("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}") + || !AccountJwtValidatorInventoryBinding.canonicalPodIp(pod.podIp()).equals(pod.podIp()) + || endpoint == null + || !"grpcs".equals(endpoint.getScheme()) + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || endpoint.getPort() < 1 + || endpointHost == null + || !(endpointHost.equals(pod.podIp()) || endpointHost.equals("[" + pod.podIp() + "]")) + || pod.image() == null + || !pod.image().equals(validator.image()) + || pod.verifierConfigSha256() == null + || !pod.verifierConfigSha256().matches(SHA256_PATTERN) + || !pod.verifierConfigSha256().equals(validator.verifierConfigSha256()) + || pod.receiverServiceUri() == null + || !pod.receiverServiceUri().startsWith(SPIFFE_PREFIX + inventory.namespace() + "/sa/") + || !pod.receiverServiceUri() + .matches( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw unavailable(); + } + ReplicaSetObservation replicaSet = ownedReplicaSets.getFirst(); + if (!replicaSet.ownerDeploymentName().equals(validator.deploymentName()) + || !replicaSet.ownerDeploymentUid().equals(validator.deploymentUid()) + || !replicaSet.image().equals(validator.image()) + || !replicaSet.image().equals(pod.image()) + || !replicaSet.verifierConfigSha256().equals(validator.verifierConfigSha256()) + || !replicaSet.verifierConfigSha256().equals(pod.verifierConfigSha256()) + || !replicaSet.podTemplateHash().equals(pod.podTemplateHash())) { + throw unavailable(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException failure) { + throw unavailable(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable(); + } + } + + private static AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException + unavailable() { + return new AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException(); + } + + private record SourceRead(SourceIdentity sourceIdentity, String sha256) {} + + private record SelectedPod(ValidatorObservation validator, PodObservation pod) {} + + private record PlanIdentity( + UUID operationId, + String operationDigest, + String planDigest, + String applicabilityMatrixDigest, + Optional inventorySnapshotDigest, + Binding binding, + TrustFence trustFence, + int planVersion, + boolean validatorInventoryComplete, + long expiresAtEpochSecond) { + static PlanIdentity from(ReadinessProbePlan plan) { + return new PlanIdentity( + plan.operationId(), + plan.operationDigest(), + plan.planDigest(), + plan.applicabilityMatrixDigest(), + plan.inventorySnapshotDigest(), + plan.binding(), + plan.trustFence(), + plan.planVersion(), + plan.validatorInventoryComplete(), + plan.expiresAtEpochSecond()); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V102__account_jwt_readiness_version_aware_delivery_claim_guard.sql b/services/account-service/src/main/resources/db/migration/V102__account_jwt_readiness_version_aware_delivery_claim_guard.sql new file mode 100644 index 0000000000..7fbc6992ab --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V102__account_jwt_readiness_version_aware_delivery_claim_guard.sql @@ -0,0 +1,84 @@ +-- Keep delivery claims compatible with retained V1 plans while requiring the complete V2 +-- validator/profile registry created from the exact immutable protected inventory snapshot. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_readiness_delivery_claim_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + snapshot_json jsonb; + expected_entry_count integer; + actual_entry_count integer; +BEGIN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.expected_cluster_incarnation_uid IS DISTINCT FROM plan_row.expected_cluster_incarnation_uid + OR NEW.expected_namespace_uid IS DISTINCT FROM plan_row.expected_namespace_uid + OR NEW.materializer_trust_binding_digest IS DISTINCT FROM plan_row.trust_binding_digest + OR NEW.materializer_trust_config_revision IS DISTINCT FROM plan_row.trust_config_revision + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds + OR NEW.validator_id <> 'account-service' + OR NEW.readiness_binding_valid_until_epoch_seconds <= NEW.claimed_at_epoch_seconds + OR NEW.validator_peer_uri IS DISTINCT FROM + 'spiffe://firemud/ns/' || plan_row.kubernetes_namespace || '/sa/account-jwt-readiness-harness' + OR NEW.claimed_at_epoch_seconds < plan_row.not_before_epoch_seconds + OR NEW.claimed_at_epoch_seconds >= plan_row.expires_at_epoch_seconds + OR CURRENT_TIMESTAMP < to_timestamp(plan_row.not_before_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(plan_row.expires_at_epoch_seconds) THEN + RAISE EXCEPTION 'Account readiness delivery claim differs from its current exact plan' + USING ERRCODE = '23514'; + END IF; + + IF plan_row.plan_version = 1 THEN + expected_entry_count := + 1 + jsonb_array_length(plan_row.applicability_matrix_json::jsonb #> + '{validators,0,applicableProfiles}'); + ELSIF plan_row.plan_version = 2 THEN + IF plan_row.validator_inventory_complete IS DISTINCT FROM TRUE + OR plan_row.inventory_snapshot_digest IS NULL + OR plan_row.applicability_matrix_json::jsonb ->> 'inventorySnapshotDigest' + IS DISTINCT FROM plan_row.inventory_snapshot_digest THEN + RAISE EXCEPTION 'Account readiness delivery claim requires a complete exact V2 inventory plan' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(canonical_snapshot, 'UTF8')::jsonb + INTO snapshot_json + FROM account_jwt_validator_inventory_snapshots + WHERE snapshot_digest = plan_row.inventory_snapshot_digest; + IF NOT FOUND + OR snapshot_json IS NULL + OR jsonb_typeof(snapshot_json -> 'validators') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_json -> 'validators') NOT BETWEEN 1 AND 32 THEN + RAISE EXCEPTION 'Account readiness delivery claim requires its exact V2 inventory snapshot' + USING ERRCODE = '23514'; + END IF; + expected_entry_count := jsonb_array_length(snapshot_json -> 'validators') * 4; + ELSE + RAISE EXCEPTION 'Account readiness delivery claim has an unknown plan version' + USING ERRCODE = '23514'; + END IF; + + SELECT COUNT(*) INTO actual_entry_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest + AND state = 'PLANNED' + AND compact_token_sha256 IS NULL + AND signing_attempted_at_epoch_seconds IS NULL + AND verification_receipt_sha256 IS NULL; + IF actual_entry_count <> expected_entry_count THEN + RAISE EXCEPTION 'Account readiness delivery claim requires untouched planned entries' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java index 86474d316f..a316ec175e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java @@ -822,6 +822,49 @@ void persistsProtectedV2PodClosureAndRequiresFreshExactInventoryForPromotion() t validator.caller().binding(), validator.caller().peer(), now); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> { + assertThat( + context + .dsl() + .execute( + "UPDATE account_jwt_readiness_probe_entries " + + "SET compact_token_sha256 = ?, " + + "signing_attempted_at_epoch_seconds = ?, " + + "entry_version = entry_version + 1 " + + "WHERE rotation_operation_id = ? " + + "AND plan_digest = ? " + + "AND validator_id = 'account-service' " + + "AND token_profile = 'control-ui' " + + "AND audience = 'control-ui' " + + "AND probe_kind = 'REPRESENTATIVE' " + + "AND state = 'PLANNED'", + "0".repeat(64), + now, + result.operationId(), + plan.planDigest())) + .isEqualTo(1); + context + .dsl() + .execute( + "INSERT INTO account_jwt_readiness_delivery_claims " + + "SELECT * FROM account_jwt_readiness_delivery_claims " + + "WHERE rotation_operation_id = ?", + result.operationId()); + return null; + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining( + "Account readiness delivery claim requires untouched planned entries"); + assertThat( + inTransaction( + context, + () -> readiness.readCurrentPlan(BINDING, trust, result.operationId()).entries())) + .containsExactlyElementsOf(plan.entries()); + assertThat(count(context, "account_jwt_readiness_delivery_claims")).isEqualTo(1L); AccountJwtReadinessProbeService probeService = new AccountJwtReadinessProbeService( readiness, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java index 82289cf376..6f28101952 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java @@ -28,6 +28,8 @@ import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataResponse; import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; import net.firedevops.firemud.accountservice.config.AccountJwtReadinessIsolatedGrpcRoutingConfiguration; import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerWorkloadGuard; @@ -36,6 +38,7 @@ import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerProtoMapper; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerService; import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverMetadataService; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import org.junit.jupiter.api.Test; @@ -90,10 +93,28 @@ void ownerLookupIsIndependentlyDefaultDeniedAndUsesTheExactPeerIdentityIntercept }) .when(owner) .getCurrentReadinessProbeOwner(org.mockito.ArgumentMatchers.any()); - var service = new AccountJwtReadinessProbeOwnerGrpcService(owner); + var metadata = mock(AccountJwtReadinessReceiverMetadataService.class); + AtomicReference observedMetadataPeer = new AtomicReference<>(); + doAnswer( + invocation -> { + observedMetadataPeer.set(GrpcPeerIdentity.current()); + return GetCurrentReadinessReceiverMetadataResponse.getDefaultInstance(); + }) + .when(metadata) + .getCurrentReadinessReceiverMetadata(org.mockito.ArgumentMatchers.any()); + var service = new AccountJwtReadinessProbeOwnerGrpcService(owner, metadata); var serviceDefinition = configurer.configure(new GrpcServiceSpec(service, GrpcServiceInfo.from(grpc)), factory); - var methodDefinition = serviceDefinition.getMethods().iterator().next(); + var methodDefinition = + serviceDefinition.getMethods().stream() + .filter( + method -> + method + .getMethodDescriptor() + .getFullMethodName() + .endsWith("/GetCurrentReadinessProbeOwner")) + .findFirst() + .orElseThrow(); ServerCall serverCall = mock(ServerCall.class); when(serverCall.getMethodDescriptor()).thenReturn(methodDefinition.getMethodDescriptor()); String peerUri = "spiffe://firemud/ns/firemud-prod/sa/game-session-service"; @@ -113,6 +134,32 @@ void ownerLookupIsIndependentlyDefaultDeniedAndUsesTheExactPeerIdentityIntercept assertThat(observedPeer.get()).isEqualTo(GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); verify(sslSession, times(1)).getPeerCertificates(); + var metadataMethodDefinition = + serviceDefinition.getMethods().stream() + .filter( + method -> + method + .getMethodDescriptor() + .getFullMethodName() + .endsWith("/GetCurrentReadinessReceiverMetadata")) + .findFirst() + .orElseThrow(); + ServerCall metadataCall = mock(ServerCall.class); + when(metadataCall.getMethodDescriptor()) + .thenReturn(metadataMethodDefinition.getMethodDescriptor()); + when(metadataCall.getAttributes()) + .thenReturn( + Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession).build()); + ServerCall.Listener metadataListener = + metadataMethodDefinition.getServerCallHandler().startCall(metadataCall, new Metadata()); + metadataListener.onMessage(GetCurrentReadinessReceiverMetadataRequest.getDefaultInstance()); + metadataListener.onHalfClose(); + + assertThat(observedMetadataPeer.get()) + .isEqualTo(GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); + verify(metadata).getCurrentReadinessReceiverMetadata(org.mockito.ArgumentMatchers.any()); + assertThat(context.getBean(GlobalPeerIdentityMarker.class).invocations()).hasValue(0); + var ordinary = configurer.configure( new GrpcServiceSpec(new AccountServiceGrpc.AccountServiceImplBase() {}, null), @@ -149,7 +196,9 @@ void missingProtectedAccountBindingDeniesBeforeInventoryOrSqlAccess() { materializerBinding, guard, new AccountJwtReadinessProbeOwnerProtoMapper()); - var service = new AccountJwtReadinessProbeOwnerGrpcService(owner); + var service = + new AccountJwtReadinessProbeOwnerGrpcService( + owner, mock(AccountJwtReadinessReceiverMetadataService.class)); RecordingObserver response = new RecordingObserver(); service.getCurrentReadinessProbeOwner( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java index 67d9922093..37968decb4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessGrpcReceiverInvocationPortTest.java @@ -235,7 +235,8 @@ void validButDifferentAccountSourceClusterNamespaceOrNamespaceUidCannotMatchPodT @Test void loopbackMtlsInvocationRejectsStructurallyValidOtherAccountSourceCluster() throws Exception { AtomicReference currentInvocation = new AtomicReference<>(); - startSourceIdentityServer(pki.pinnedServer(), pki.trustedCa(), currentInvocation, true); + startSourceIdentityServer( + pki.pinnedServer(), pki.trustedCa(), currentInvocation, true, false, false); Invocation invocation = invocation(pki.pinnedServer(), server.getPort()); currentInvocation.set(invocation); @@ -276,7 +277,8 @@ void remoteAddressObservationRequiresOneExactResolvedSocket() { @Test void matchingLoopbackMtlsResponseUsesDirectSocketDespiteJvmProxySelector() throws Exception { AtomicReference currentInvocation = new AtomicReference<>(); - startSourceIdentityServer(pki.pinnedServer(), pki.trustedCa(), currentInvocation, false); + startSourceIdentityServer( + pki.pinnedServer(), pki.trustedCa(), currentInvocation, false, false, false); Invocation invocation = invocation(pki.pinnedServer(), server.getPort()); currentInvocation.set(invocation); @@ -311,6 +313,32 @@ public void connectFailed(URI uri, SocketAddress socketAddress, IOException fail } } + @Test + void loopbackMtlsResponseRequiresOpaqueTrustRevisionToMatchAccountSource() throws Exception { + AtomicReference currentInvocation = new AtomicReference<>(); + startSourceIdentityServer( + pki.pinnedServer(), pki.trustedCa(), currentInvocation, false, true, false); + Invocation invocation = invocation(pki.pinnedServer(), server.getPort()); + currentInvocation.set(invocation); + + assertThatThrownBy(() -> port(pki.accountClient(), pki.trustedCa()).invoke(invocation)) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + assertThat(handlerCalls.get()).isEqualTo(1); + } + + @Test + void loopbackMtlsResponseRequiresPublicJwksSha256() throws Exception { + AtomicReference currentInvocation = new AtomicReference<>(); + startSourceIdentityServer( + pki.pinnedServer(), pki.trustedCa(), currentInvocation, false, false, true); + Invocation invocation = invocation(pki.pinnedServer(), server.getPort()); + currentInvocation.set(invocation); + + assertThatThrownBy(() -> port(pki.accountClient(), pki.trustedCa()).invoke(invocation)) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + assertThat(handlerCalls.get()).isEqualTo(1); + } + private void startServer(TestCertificate serverCertificate, Path trustedCa) throws Exception { SslContext tlsContext = GrpcSslContexts.configure( @@ -387,7 +415,9 @@ private void startSourceIdentityServer( TestCertificate serverCertificate, Path trustedCa, AtomicReference currentInvocation, - boolean otherCluster) + boolean otherCluster, + boolean mismatchTrustRevision, + boolean malformedPublicJwksHash) throws Exception { SslContext tlsContext = tlsContext(serverCertificate, trustedCa); server = @@ -437,10 +467,13 @@ public void receiveReadinessProbe( .setNamespace(target.namespace()) .setNamespaceUid(target.namespaceUid()) .setConfigMapUid("88888888-8888-4888-8888-888888888888") - .setBindingRevision("unrelated-trust-revision") + .setBindingRevision("account-api-r1") .setApiServerOrigin("https://kubernetes.example:6443") .setServingCaSha256("9".repeat(64))) - .setAccountJwksTrustConfigRevision(1L)) + .setAccountJwksTrustBindingRevision( + mismatchTrustRevision ? "account-api-r2" : "account-api-r1") + .setAccountPublicJwksSha256( + malformedPublicJwksHash ? "not-a-digest" : "9".repeat(64))) .setAccountPodTarget(accountTargetBinding(target)) .setObservedAtEpochSeconds(System.currentTimeMillis() / 1000) .setOutcome(ReceiveReadinessProbeResponse.ObservationOutcome.VERIFIED) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java index 37b986e7f1..d269ceb47b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessPodLocalIdentityProviderTest.java @@ -17,6 +17,8 @@ import java.util.HexFormat; import java.util.List; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; @@ -50,6 +52,31 @@ void derivesLocalPodIdentityFromProtectedInventoryAndMatchingServerBundleLeaf() .isEqualTo("55555555-5555-4555-8555-555555555555"); } + @Test + void selectsTheLocalPodByProtectedUidRegardlessOfPodName() throws Exception { + Fixture fixture = new Fixture(false); + when(fixture.pod.name()).thenReturn("unrelated-kubelet-name"); + + var identity = fixture.provider.observe("c".repeat(64)); + + assertThat(identity.selectorIdentity().podUid()).isEqualTo(Fixture.POD_UID); + } + + @Test + void refusesWhenProtectedPodUidChangesDuringInventoryObservation() throws Exception { + Fixture fixture = new Fixture(false); + AtomicInteger reads = new AtomicInteger(); + fixture.provider = + fixture.provider( + () -> + reads.getAndIncrement() == 0 + ? Fixture.POD_UID + : "66666666-6666-4666-8666-666666666666"); + + assertIdentityUnavailable(fixture); + assertThat(reads.get()).isEqualTo(2); + } + @Test void localIdentityRereadUsesTheOwnerBoundInitialCandidateContext() throws Exception { Fixture fixture = new Fixture(false); @@ -84,6 +111,22 @@ void refusesWhenLocalPodHasNoMatchingReplicaSet() throws Exception { assertIdentityUnavailable(fixture); } + @Test + void refusesWhenProtectedPodUidIsAbsentFromInventory() throws Exception { + Fixture fixture = new Fixture(false); + when(fixture.pod.uid()).thenReturn("66666666-6666-4666-8666-666666666666"); + + assertIdentityUnavailable(fixture); + } + + @Test + void refusesDuplicatePodsWithTheProtectedUid() throws Exception { + Fixture fixture = new Fixture(false); + when(fixture.validator.pods()).thenReturn(List.of(fixture.pod, fixture.pod)); + + assertIdentityUnavailable(fixture); + } + @Test void refusesWhenLocalPodOwnerUidDoesNotMatchReplicaSet() throws Exception { Fixture fixture = new Fixture(false); @@ -150,7 +193,7 @@ private static final class Fixture { private final AccountJwtJwksTrustedSource trustedSource = mock(AccountJwtJwksTrustedSource.class); private final SslBundles sslBundles = mock(SslBundles.class); - private final AccountJwtReadinessPodLocalIdentityProvider provider; + private AccountJwtReadinessPodLocalIdentityProvider provider; private Fixture(boolean mismatchProtectedLeafPin) throws Exception { when(inventory.validators()).thenReturn(List.of(validator)); @@ -224,9 +267,12 @@ private Fixture(boolean mismatchProtectedLeafPin) throws Exception { SslBundle sslBundle = mock(SslBundle.class); when(sslBundle.getStores()).thenReturn(stores); when(sslBundles.getBundle("firemud-grpc")).thenReturn(sslBundle); - provider = - new AccountJwtReadinessPodLocalIdentityProvider( - inventorySource, trustedSource, sslBundles, CLOCK, "account-0"); + provider = provider(() -> POD_UID); + } + + private AccountJwtReadinessPodLocalIdentityProvider provider(Supplier podUidSource) { + return new AccountJwtReadinessPodLocalIdentityProvider( + inventorySource, trustedSource, sslBundles, CLOCK, podUidSource); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java index 6a85233df2..011126e553 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java @@ -7,6 +7,7 @@ import net.firedevops.firemud.account.v1.AccountJwtReadinessProbeOwnerServiceGrpc; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; import org.junit.jupiter.api.Test; @@ -61,6 +62,93 @@ void wireHasNoCompactJwtRequestOrResponseField() { .isEqualTo("account.v1.AccountJwtReadinessProbeOwnerService/GetCurrentReadinessProbeOwner"); } + @Test + void receiverMetadataRequestIsClosedAndContainsOnlyCanonicalLocalSelectors() { + var request = + GetCurrentReadinessReceiverMetadataRequest.newBuilder() + .setSchemaVersion(1) + .setProjectedPodUid("66666666-6666-4666-8666-666666666666") + .setServerLeafSpkiSha256("a".repeat(64)) + .build(); + + var parsed = mapper.parseReceiverMetadataRequest(request); + + assertThat(parsed.projectedPodUid()).isEqualTo("66666666-6666-4666-8666-666666666666"); + assertThat(parsed.serverLeafSpkiSha256()).isEqualTo("a".repeat(64)); + assertThatThrownBy( + () -> + mapper.parseReceiverMetadataRequest( + GetCurrentReadinessReceiverMetadataRequest.getDefaultInstance())) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + assertThatThrownBy( + () -> + mapper.parseReceiverMetadataRequest( + request.toBuilder() + .setProjectedPodUid("66666666-6666-4666-8666-66666666666A") + .build())) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + assertThatThrownBy( + () -> + mapper.parseReceiverMetadataRequest( + request.toBuilder().setServerLeafSpkiSha256("A".repeat(64)).build())) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + assertThatThrownBy( + () -> + mapper.parseReceiverMetadataRequest( + request.toBuilder().setProjectedPodUid("6".repeat(4096)).build())) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + assertThatThrownBy( + () -> + mapper.parseReceiverMetadataRequest( + request.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + } + + @Test + void rejectsReservedNumericTrustRevisionAndRequiresExactOpaqueSourceRevisionAndHash() { + UnknownFieldSet reservedNumericRevision = + UnknownFieldSet.newBuilder() + .addField(14, UnknownFieldSet.Field.newBuilder().addVarint(4L).build()) + .build(); + var oldRevision = + request() + .setProtectedLocalIdentity( + request().getProtectedLocalIdentity().toBuilder() + .setUnknownFields(reservedNumericRevision)) + .build(); + assertThatThrownBy(() -> mapper.parse(oldRevision)) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + + var mismatchedOpaqueRevision = + request() + .setProtectedLocalIdentity( + request().getProtectedLocalIdentity().toBuilder() + .setAccountJwksTrustBindingRevision("other-r2")) + .build(); + assertThatThrownBy(() -> mapper.parse(mismatchedOpaqueRevision)) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + + var missingPublicJwksHash = + request() + .setProtectedLocalIdentity( + request().getProtectedLocalIdentity().toBuilder().clearAccountPublicJwksSha256()) + .build(); + assertThatThrownBy(() -> mapper.parse(missingPublicJwksHash)) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + } + private static GetCurrentReadinessProbeOwnerRequest.Builder request() { var coordinates = ReadinessProbeCoordinates.newBuilder() @@ -108,7 +196,8 @@ private static GetCurrentReadinessProbeOwnerRequest.Builder request() { .setSourceInventoryDigest("9".repeat(64)) .setServerLeafSpkiSha256("8".repeat(64)) .setAccountJwksSourceIdentity(source) - .setAccountJwksTrustConfigRevision(4); + .setAccountJwksTrustBindingRevision("source-r1") + .setAccountPublicJwksSha256("7".repeat(64)); return GetCurrentReadinessProbeOwnerRequest.newBuilder() .setSchemaVersion(1) .setExpectedCoordinates(coordinates) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataServiceTest.java new file mode 100644 index 0000000000..cb3b254ea9 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataServiceTest.java @@ -0,0 +1,557 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerWorkloadGuard; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessProbeOwnerWorkloadGuard.AuthenticatedCaller; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ReplicaSetObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJwtReadinessReceiverMetadataServiceTest { + private static final long NOW = 1_800_000_000L; + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String OPERATION_DIGEST = "1".repeat(64); + private static final String PLAN_DIGEST = "2".repeat(64); + private static final String MATRIX_DIGEST = "3".repeat(64); + private static final String INVENTORY_DIGEST = "4".repeat(64); + private static final String POD_UID = "66666666-6666-4666-8666-666666666666"; + private static final String POD_IP = "10.0.0.7"; + private static final String POD_LEAF = "5".repeat(64); + private static final String DEPLOYMENT_UID = "55555555-5555-4555-8555-555555555555"; + private static final String REPLICASET_UID = "77777777-7777-4777-8777-777777777777"; + private static final String NAMESPACE = "firemud-prod"; + private static final String PUBLIC_JWKS = "{\"keys\":[]}"; + private static final byte[] PUBLIC_JWKS_BYTES = PUBLIC_JWKS.getBytes(StandardCharsets.UTF_8); + + private AccountJwtReadinessProbeService probeService; + private AccountJwtValidatorInventorySource inventorySource; + private AccountJwtJwksTrustedSource trustedJwksSource; + private AccountJwtReadinessProbeOwnerWorkloadGuard workloadGuard; + private AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private AccountJwtReadinessProbeOwnerProtoMapper protoMapper; + private AccountJwtSignerMaterializerTrustBinding.Binding protectedBinding; + private net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .Binding + accountBinding; + private TrustFence trustFence; + private AuthenticatedCaller caller; + private ReadinessProbePlan plan; + private InventorySnapshot inventory; + private SourceIdentity sourceIdentity; + private ObservationContext context; + private AccountJwtReadinessReceiverMetadataService service; + + @BeforeEach + void setUp() { + protectedBinding = protectedBinding("trust-r1"); + accountBinding = protectedBinding.accountBinding(); + trustFence = AccountJwtReadinessValidationService.trustFence(protectedBinding); + context = + new ObservationContext(ObservationPurpose.STRICT_READY, OPERATION_ID, OPERATION_DIGEST); + sourceIdentity = sourceIdentity("33333333-3333-4333-8333-333333333333", "account-api-r1"); + + probeService = mock(AccountJwtReadinessProbeService.class); + inventorySource = mock(AccountJwtValidatorInventorySource.class); + trustedJwksSource = mock(AccountJwtJwksTrustedSource.class); + workloadGuard = mock(AccountJwtReadinessProbeOwnerWorkloadGuard.class); + materializerTrustBinding = mock(AccountJwtSignerMaterializerTrustBinding.class); + protoMapper = new AccountJwtReadinessProbeOwnerProtoMapper(); + caller = mock(AuthenticatedCaller.class); + plan = plan(); + inventory = inventory(INVENTORY_DIGEST, gameSessionValidator()); + + when(caller.accountBinding()).thenReturn(protectedBinding); + when(workloadGuard.requireGameSessionOwnerReadCaller()).thenReturn(caller); + when(materializerTrustBinding.current()).thenReturn(Optional.of(protectedBinding)); + when(probeService.readCurrentInventoryObservationContext(accountBinding, trustFence)) + .thenReturn(context); + when(probeService.readCurrentInventoryObservationContext( + accountBinding, trustFence, OPERATION_ID)) + .thenReturn(context); + when(probeService.readCurrentPlan(accountBinding, trustFence, OPERATION_ID)).thenReturn(plan); + when(inventorySource.observe(context)).thenReturn(inventory); + when(trustedJwksSource.sourceIdentity()).thenReturn(sourceIdentity); + when(trustedJwksSource.load()) + .thenAnswer(ignored -> new PublicJwksSnapshot(sourceIdentity, PUBLIC_JWKS_BYTES)); + service = + new AccountJwtReadinessReceiverMetadataService( + probeService, + inventorySource, + trustedJwksSource, + workloadGuard, + materializerTrustBinding, + protoMapper, + Clock.fixed(Instant.ofEpochSecond(NOW), ZoneOffset.UTC)); + } + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void selectsCurrentProtectedOperationAndReturnsOnlyRecheckedMetadataWithoutCreatingPlan() { + when(inventorySource.observe(context)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return inventory; + }); + when(trustedJwksSource.sourceIdentity()) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return sourceIdentity; + }); + when(trustedJwksSource.load()) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new PublicJwksSnapshot(sourceIdentity, PUBLIC_JWKS_BYTES); + }); + + var response = service.getCurrentReadinessReceiverMetadata(request().build()); + + assertThat(response.getSchemaVersion()).isEqualTo(1); + assertThat(response.getRotationOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getOperationDigest()).isEqualTo(OPERATION_DIGEST); + assertThat(response.getPlanDigest()).isEqualTo(PLAN_DIGEST); + assertThat(response.getCurrentIdentity().getValidatorId()).isEqualTo("game-session-service"); + assertThat(response.getCurrentIdentity().getPodUid()).isEqualTo(POD_UID); + assertThat(response.getCurrentIdentity().getServerLeafSpkiSha256()).isEqualTo(POD_LEAF); + assertThat(response.getCurrentIdentity().getSourceInventoryRevision()) + .isEqualTo("inventory-r1"); + assertThat(response.getCurrentIdentity().getSourceInventoryDigest()) + .isEqualTo(INVENTORY_DIGEST); + assertThat(response.getCurrentIdentity().getAccountJwksTrustBindingRevision()) + .isEqualTo(sourceIdentity.bindingRevision()); + assertThat(response.getCurrentIdentity().getAccountPublicJwksSha256()) + .isEqualTo(sha256(PUBLIC_JWKS_BYTES)); + verify(probeService, times(3)) + .readCurrentInventoryObservationContext(accountBinding, trustFence); + verify(probeService, times(2)) + .readCurrentInventoryObservationContext(accountBinding, trustFence, OPERATION_ID); + verify(probeService, times(3)).readCurrentPlan(accountBinding, trustFence, OPERATION_ID); + verify(probeService, never()).planCurrent(any(), any()); + verify(inventorySource, times(2)).observe(context); + verify(trustedJwksSource, times(4)).sourceIdentity(); + verify(trustedJwksSource, times(2)).load(); + } + + @Test + void rejectsMalformedRequestBeforeReadingPlanInventoryOrPublicJwks() { + assertThatThrownBy( + () -> + service.getCurrentReadinessReceiverMetadata( + GetCurrentReadinessReceiverMetadataRequest.getDefaultInstance())) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + assertThatThrownBy( + () -> + service.getCurrentReadinessReceiverMetadata( + request().setUnknownFields(unknown).build())) + .isInstanceOf( + AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); + + verifyNoInteractions(probeService, inventorySource, trustedJwksSource); + } + + @Test + void rejectsWrongWorkloadGuardBeforeAnyOwnerOrNetworkRead() { + when(workloadGuard.requireGameSessionOwnerReadCaller()) + .thenThrow(new AccountJwtReadinessProbeOwnerWorkloadGuard.OwnerReadDeniedException()); + + assertThatThrownBy(() -> service.getCurrentReadinessReceiverMetadata(request().build())) + .isInstanceOf(AccountJwtReadinessProbeOwnerWorkloadGuard.OwnerReadDeniedException.class); + + verifyNoInteractions(probeService, inventorySource, trustedJwksSource); + } + + @Test + void rejectsChangedWorkloadBindingAfterNetworkReads() { + AuthenticatedCaller changedCaller = mock(AuthenticatedCaller.class); + when(changedCaller.accountBinding()).thenReturn(protectedBinding("trust-r2")); + when(workloadGuard.requireGameSessionOwnerReadCaller()).thenReturn(caller, changedCaller); + + assertUnavailable(request().build()); + + verify(inventorySource, times(2)).observe(context); + verify(trustedJwksSource, times(2)).load(); + } + + @Test + void rejectsChangedProtectedMaterializerBindingAfterNetworkReads() { + when(materializerTrustBinding.current()).thenReturn(Optional.of(protectedBinding("trust-r2"))); + + assertUnavailable(request().build()); + + verify(inventorySource, times(2)).observe(context); + verify(trustedJwksSource, times(2)).load(); + } + + @Test + void rejectsMissingExpiredAndPartialPlansWithoutCreatingReplacementPlan() { + when(probeService.readCurrentPlan(accountBinding, trustFence, OPERATION_ID)) + .thenThrow( + new AccountJwtReadinessProbeRepository.MissingPlanException("test missing plan")); + assertUnavailable(request().build()); + verify(inventorySource, never()).observe(any()); + + setUp(); + ReadinessProbePlan expired = plan(NOW); + when(probeService.readCurrentPlan(accountBinding, trustFence, OPERATION_ID)) + .thenReturn(expired); + assertUnavailable(request().build()); + verify(inventorySource, never()).observe(any()); + + setUp(); + ReadinessProbePlan partial = plan(NOW + 60, 1, false); + when(probeService.readCurrentPlan(accountBinding, trustFence, OPERATION_ID)) + .thenReturn(partial); + assertUnavailable(request().build()); + verify(inventorySource, never()).observe(any()); + } + + @Test + void rejectsUnknownPodWrongLeafAndBrokenOwnershipOrRuntimeConfiguration() { + assertUnavailable(request().setProjectedPodUid("88888888-8888-4888-8888-888888888888").build()); + assertUnavailable(request().setServerLeafSpkiSha256("9".repeat(64)).build()); + + ValidatorObservation brokenJoin = gameSessionValidatorWithReplicaSetOwner("other-deployment"); + InventorySnapshot brokenJoinInventory = inventory(INVENTORY_DIGEST, brokenJoin); + when(inventorySource.observe(context)).thenReturn(brokenJoinInventory); + assertUnavailable(request().build()); + + ValidatorObservation brokenConfig = + gameSessionValidatorWithImage("other-image@sha256:" + "e".repeat(64)); + InventorySnapshot brokenConfigInventory = inventory(INVENTORY_DIGEST, brokenConfig); + when(inventorySource.observe(context)).thenReturn(brokenConfigInventory); + assertUnavailable(request().build()); + + ValidatorObservation brokenVerifierConfig = + gameSessionValidatorWithVerifierConfig("b".repeat(64)); + InventorySnapshot brokenVerifierConfigInventory = + inventory(INVENTORY_DIGEST, brokenVerifierConfig); + when(inventorySource.observe(context)).thenReturn(brokenVerifierConfigInventory); + assertUnavailable(request().build()); + } + + @Test + void rejectsMismatchedJwksSourceOrPublicBytes() { + when(trustedJwksSource.sourceIdentity()) + .thenReturn(sourceIdentity("33333333-3333-4333-8333-333333333333", "account-api-r1")); + when(trustedJwksSource.load()) + .thenAnswer( + ignored -> + new PublicJwksSnapshot( + sourceIdentity("88888888-8888-4888-8888-888888888888", "account-api-r1"), + PUBLIC_JWKS_BYTES)); + assertUnavailable(request().build()); + + setUp(); + when(trustedJwksSource.load()) + .thenAnswer( + new org.mockito.stubbing.Answer<>() { + private int reads; + + @Override + public PublicJwksSnapshot answer(org.mockito.invocation.InvocationOnMock invocation) { + reads++; + return new PublicJwksSnapshot( + sourceIdentity, + reads == 1 + ? PUBLIC_JWKS_BYTES + : "{\"keys\":[1]}".getBytes(StandardCharsets.UTF_8)); + } + }); + assertUnavailable(request().build()); + } + + @Test + void rejectsPlanOrInventoryChangesBetweenProtectedReads() { + ReadinessProbePlan changedPlan = plan(); + when(changedPlan.planDigest()).thenReturn("9".repeat(64)); + when(probeService.readCurrentPlan(accountBinding, trustFence, OPERATION_ID)) + .thenReturn(plan, changedPlan); + assertUnavailable(request().build()); + + setUp(); + InventorySnapshot changedInventory = inventory("8".repeat(64), gameSessionValidator()); + when(inventorySource.observe(context)).thenReturn(inventory, changedInventory); + assertUnavailable(request().build()); + + setUp(); + ReadinessProbePlan changedMatrix = plan(); + when(changedMatrix.applicabilityMatrixDigest()).thenReturn("9".repeat(64)); + when(probeService.readCurrentPlan(accountBinding, trustFence, OPERATION_ID)) + .thenReturn(plan, changedMatrix); + assertUnavailable(request().build()); + } + + @Test + void rejectsSourceIdentityChangeDuringSecondPublicJwksRead() { + SourceIdentity changedIdentity = + sourceIdentity("88888888-8888-4888-8888-888888888888", "account-api-r2"); + when(trustedJwksSource.sourceIdentity()) + .thenReturn(sourceIdentity, sourceIdentity, sourceIdentity, changedIdentity); + + assertUnavailable(request().build()); + + verify(inventorySource, times(2)).observe(context); + verify(trustedJwksSource, times(2)).load(); + } + + @Test + void rejectsOperationThatAdvancesDuringSecondInventoryAndJwksRead() { + ObservationContext rotatedContext = + new ObservationContext( + ObservationPurpose.STRICT_READY, + UUID.fromString("99999999-9999-4999-8999-999999999999"), + "9".repeat(64)); + AtomicInteger inventoryReads = new AtomicInteger(); + AtomicBoolean secondNetworkPhaseComplete = new AtomicBoolean(); + when(inventorySource.observe(context)) + .thenAnswer( + ignored -> { + if (inventoryReads.incrementAndGet() == 2) { + secondNetworkPhaseComplete.set(true); + } + return inventory; + }); + when(probeService.readCurrentInventoryObservationContext(accountBinding, trustFence)) + .thenAnswer(ignored -> secondNetworkPhaseComplete.get() ? rotatedContext : context); + + assertUnavailable(request().build()); + + assertThat(inventoryReads).hasValue(2); + verify(probeService, times(2)).readCurrentPlan(accountBinding, trustFence, OPERATION_ID); + } + + @Test + void rejectsAmbientSqlTransactionBeforeAuthenticationOrExternalIo() { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertUnavailable(request().build()); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + verifyNoInteractions(workloadGuard, probeService, inventorySource, trustedJwksSource); + } + + private void assertUnavailable(GetCurrentReadinessReceiverMetadataRequest request) { + assertThatThrownBy(() -> service.getCurrentReadinessReceiverMetadata(request)) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + } + + private GetCurrentReadinessReceiverMetadataRequest.Builder request() { + return GetCurrentReadinessReceiverMetadataRequest.newBuilder() + .setSchemaVersion(1) + .setProjectedPodUid(POD_UID) + .setServerLeafSpkiSha256(POD_LEAF); + } + + private ReadinessProbePlan plan() { + return plan(NOW + 120, AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION, true); + } + + private ReadinessProbePlan plan(long expiresAtEpochSecond) { + return plan( + expiresAtEpochSecond, AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION, true); + } + + private ReadinessProbePlan plan(long expiresAtEpochSecond, int version, boolean complete) { + ReadinessProbePlan result = mock(ReadinessProbePlan.class); + when(result.operationId()).thenReturn(OPERATION_ID); + when(result.operationDigest()).thenReturn(OPERATION_DIGEST); + when(result.planDigest()).thenReturn(PLAN_DIGEST); + when(result.applicabilityMatrixDigest()).thenReturn(MATRIX_DIGEST); + when(result.inventorySnapshotDigest()).thenReturn(Optional.of(INVENTORY_DIGEST)); + when(result.binding()).thenReturn(accountBinding); + when(result.trustFence()).thenReturn(trustFence); + when(result.planVersion()).thenReturn(version); + when(result.validatorInventoryComplete()).thenReturn(complete); + when(result.expiresAtEpochSecond()).thenReturn(expiresAtEpochSecond); + return result; + } + + private InventorySnapshot inventory(String digest, ValidatorObservation validator) { + InventorySnapshot result = mock(InventorySnapshot.class); + when(result.observationContext()).thenReturn(Optional.of(context)); + when(result.digest()).thenReturn(digest); + when(result.environmentId()).thenReturn("prod"); + when(result.clusterId()).thenReturn("cluster-a"); + when(result.clusterIncarnationUid()).thenReturn("11111111-1111-4111-8111-111111111111"); + when(result.namespace()).thenReturn(NAMESPACE); + when(result.namespaceUid()).thenReturn("22222222-2222-4222-8222-222222222222"); + when(result.inventoryBindingRevision()).thenReturn("inventory-r1"); + when(result.inventoryBindingDigest()).thenReturn("a".repeat(64)); + when(result.validators()).thenReturn(List.of(validator)); + return result; + } + + private static ValidatorObservation gameSessionValidator() { + return gameSessionValidator(REPLICASET_UID, DEPLOYMENT_UID, null); + } + + private static ValidatorObservation gameSessionValidatorWithReplicaSetOwner( + String deploymentName) { + return gameSessionValidator(REPLICASET_UID, DEPLOYMENT_UID, deploymentName); + } + + private static ValidatorObservation gameSessionValidatorWithImage(String image) { + ValidatorObservation validator = gameSessionValidator(); + return new ValidatorObservation( + validator.validatorId(), + validator.deploymentName(), + validator.deploymentUid(), + validator.deploymentGeneration(), + validator.deploymentResourceVersion(), + validator.replicas(), + image, + validator.verifierConfigSha256(), + validator.maxCacheAgeSeconds(), + validator.profiles(), + validator.pods(), + validator.replicaSets()); + } + + private static ValidatorObservation gameSessionValidatorWithVerifierConfig( + String verifierConfig) { + ValidatorObservation validator = gameSessionValidator(); + return new ValidatorObservation( + validator.validatorId(), + validator.deploymentName(), + validator.deploymentUid(), + validator.deploymentGeneration(), + validator.deploymentResourceVersion(), + validator.replicas(), + validator.image(), + verifierConfig, + validator.maxCacheAgeSeconds(), + validator.profiles(), + validator.pods(), + validator.replicaSets()); + } + + private static ValidatorObservation gameSessionValidator( + String replicaSetUid, String replicaSetDeploymentUid, String replicaSetDeploymentName) { + String image = "registry.example/game-session@sha256:" + "e".repeat(64); + String verifierConfig = "f".repeat(64); + String deploymentName = "game-session-validator"; + ReplicaSetObservation replicaSet = + new ReplicaSetObservation( + "game-session-validator-abcde", + replicaSetUid, + "21", + 1, + 1, + replicaSetDeploymentName == null ? deploymentName : replicaSetDeploymentName, + replicaSetDeploymentUid, + "abcde", + image, + verifierConfig); + PodObservation pod = + new PodObservation( + "game-session-validator-abcde-xyz", + POD_UID, + "22", + replicaSet.name(), + replicaSet.uid(), + "abcde", + image, + verifierConfig, + POD_IP, + URI.create("grpcs://" + POD_IP + ":9443"), + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-jwt-validator", + POD_LEAF); + return new ValidatorObservation( + "game-session-service", + deploymentName, + DEPLOYMENT_UID, + 1, + "20", + 1, + image, + verifierConfig, + 60, + List.of(), + List.of(pod), + List.of(replicaSet)); + } + + private static Binding protectedBinding(String revision) { + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + String peer = "spiffe://firemud/ns/" + NAMESPACE + "/sa/jwt-signer-materializer"; + List pins = List.of("a".repeat(64)); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, "prod", "cluster-a", NAMESPACE, clusterUid, namespaceUid, peer, pins); + return new Binding( + "prod", "cluster-a", NAMESPACE, clusterUid, namespaceUid, peer, pins, revision, digest); + } + + private static SourceIdentity sourceIdentity(String configMapUid, String bindingRevision) { + return new SourceIdentity( + "prod", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + NAMESPACE, + "22222222-2222-4222-8222-222222222222", + configMapUid, + bindingRevision, + "https://kubernetes.example:6443", + "9".repeat(64)); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/security/ProtectedPodUidProjection.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/security/ProtectedPodUidProjection.java new file mode 100644 index 0000000000..bb86a4a8e5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/security/ProtectedPodUidProjection.java @@ -0,0 +1,278 @@ +package net.firedevops.firemud.common.security; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * Reads a local workload Pod UID from its fixed kubelet-projected downwardAPI volume. Filesystem + * checks constrain the expected projection shape; platform admission must establish its kubelet and + * read-only-mount provenance. + */ +public final class ProtectedPodUidProjection { + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern ATOMIC_WRITER_DIRECTORY = + Pattern.compile("\\.\\.[0-9]{4}_[0-9]{2}_[0-9]{2}_[0-9]{2}_[0-9]{2}_[0-9]{2}(?:\\.[0-9]+)?"); + private static final int UID_LENGTH = 36; + private static final Set WRITE_PERMISSIONS = + Set.of( + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.GROUP_WRITE, + PosixFilePermission.OTHERS_WRITE); + + private ProtectedPodUidProjection() {} + + /** Reads the UID only from {@code /var/run/secrets/firemud/pod-identity/uid}. */ + public static String read() { + return readProjection(protectedProjectionRoot(), 0L, false); + } + + /** Package-private fixture seam; production callers cannot choose a path or owner. */ + static String readForTesting(Path projectionRoot, long expectedOwnerUid) { + return readProjection(projectionRoot, expectedOwnerUid, true); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = "The protected local Pod UID projection has one fixed production path.") + private static Path protectedProjectionRoot() { + return Path.of("/var/run/secrets/firemud/pod-identity"); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "This is the canonical path of the fixed /var/run projection when /var/run aliases /run.") + private static Path canonicalProjectionRoot() { + return Path.of("/run/secrets/firemud/pod-identity"); + } + + private static String readProjection( + Path projectionRoot, long expectedOwnerUid, boolean fixtureRoot) { + try { + if (projectionRoot == null + || !projectionRoot.isAbsolute() + || expectedOwnerUid < 0 + || !projectionRoot.equals(projectionRoot.normalize())) { + throw unavailable(); + } + Path root = projectionRoot; + DirectorySnapshot rootSnapshotBefore = + verifyRootDirectory(root, expectedOwnerUid, fixtureRoot); + + Path uidLink = root.resolve("uid"); + Path dataLink = root.resolve("..data"); + BasicFileAttributes uidLinkBefore = readAttributes(uidLink, false); + BasicFileAttributes dataLinkBefore = readAttributes(dataLink, false); + Path uidLinkTarget = Files.readSymbolicLink(uidLink); + Path dataLinkTarget = Files.readSymbolicLink(dataLink); + if (!uidLinkBefore.isSymbolicLink() + || !dataLinkBefore.isSymbolicLink() + || !Path.of("..data", "uid").equals(uidLinkTarget) + || dataLinkTarget.getNameCount() != 1 + || !ATOMIC_WRITER_DIRECTORY.matcher(dataLinkTarget.toString()).matches()) { + throw unavailable(); + } + verifyOwner(uidLink, expectedOwnerUid); + verifyOwner(dataLink, expectedOwnerUid); + + Path targetDirectory = root.resolve(dataLinkTarget).normalize(); + if (!root.equals(targetDirectory.getParent())) { + throw unavailable(); + } + DirectorySnapshot targetDirectoryBefore = verifyDirectory(targetDirectory, expectedOwnerUid); + Path uidFile = targetDirectory.resolve("uid"); + FileSnapshot uidBefore = readUidFileSnapshot(uidFile, expectedOwnerUid); + String uid = readUid(uidFile, uidBefore.attributes()); + if (!isCanonicalUid(uid)) { + throw unavailable(); + } + + FileSnapshot uidAfter = readUidFileSnapshot(uidFile, expectedOwnerUid); + BasicFileAttributes uidLinkAfter = readAttributes(uidLink, false); + BasicFileAttributes dataLinkAfter = readAttributes(dataLink, false); + Path uidLinkTargetAfter = Files.readSymbolicLink(uidLink); + Path dataLinkTargetAfter = Files.readSymbolicLink(dataLink); + if (!sameAttributes(uidLinkBefore, uidLinkAfter) + || !sameAttributes(dataLinkBefore, dataLinkAfter) + || !uidLinkTarget.equals(uidLinkTargetAfter) + || !dataLinkTarget.equals(dataLinkTargetAfter) + || !uidBefore.sameAs(uidAfter)) { + throw unavailable(); + } + DirectorySnapshot rootSnapshotAfter = + verifyRootDirectory(root, expectedOwnerUid, fixtureRoot); + DirectorySnapshot targetDirectoryAfter = verifyDirectory(targetDirectory, expectedOwnerUid); + if (!rootSnapshotBefore.sameAs(rootSnapshotAfter) + || !targetDirectoryBefore.sameAs(targetDirectoryAfter)) { + throw unavailable(); + } + verifyOwner(uidLink, expectedOwnerUid); + verifyOwner(dataLink, expectedOwnerUid); + return uid; + } catch (IOException | RuntimeException failure) { + if (failure instanceof ProtectedPodUidUnavailableException unavailable) { + throw unavailable; + } + throw unavailable(); + } + } + + private static DirectorySnapshot verifyRootDirectory( + Path root, long expectedOwnerUid, boolean fixtureRoot) throws IOException { + Path realRoot = root.toRealPath(); + boolean canonicalProductionAlias = !fixtureRoot && canonicalProjectionRoot().equals(realRoot); + if (Files.isSymbolicLink(root) || (!root.equals(realRoot) && !canonicalProductionAlias)) { + throw unavailable(); + } + return verifyDirectory(root, expectedOwnerUid); + } + + private static DirectorySnapshot verifyDirectory(Path directory, long expectedOwnerUid) + throws IOException { + BasicFileAttributes attributes = readAttributes(directory, true); + Set mode = + Files.getPosixFilePermissions(directory, LinkOption.NOFOLLOW_LINKS); + long ownerUid = owner(directory); + if (!attributes.isDirectory() || writableByUntrusted(mode) || ownerUid != expectedOwnerUid) { + throw unavailable(); + } + return new DirectorySnapshot(attributes, mode, ownerUid); + } + + private static FileSnapshot readUidFileSnapshot(Path file, long expectedOwnerUid) + throws IOException { + BasicFileAttributes attributes = readAttributes(file, true); + Set mode = Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + long ownerUid = owner(file); + if (!attributes.isRegularFile() + || attributes.size() != UID_LENGTH + || writable(mode) + || !mode.contains(PosixFilePermission.OWNER_READ) + || ownerUid != expectedOwnerUid) { + throw unavailable(); + } + return new FileSnapshot(attributes, mode, ownerUid); + } + + private static String readUid(Path file, BasicFileAttributes before) throws IOException { + byte[] bytes = new byte[UID_LENGTH]; + try (SeekableByteChannel channel = + Files.newByteChannel(file, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw unavailable(); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw unavailable(); + } + } + BasicFileAttributes after = readAttributes(file, true); + if (!sameAttributes(before, after)) { + throw unavailable(); + } + return new String(bytes, StandardCharsets.US_ASCII); + } + + private static BasicFileAttributes readAttributes(Path path, boolean requireRegularOrDirectory) + throws IOException { + BasicFileAttributes attributes = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (requireRegularOrDirectory && !(attributes.isRegularFile() || attributes.isDirectory())) { + throw unavailable(); + } + return attributes; + } + + private static long owner(Path path) throws IOException { + Object value = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (!(value instanceof Number uid)) { + throw unavailable(); + } + return uid.longValue(); + } + + private static void verifyOwner(Path path, long expectedOwnerUid) throws IOException { + if (owner(path) != expectedOwnerUid) { + throw unavailable(); + } + } + + private static boolean writable(Set mode) { + return mode.stream().anyMatch(WRITE_PERMISSIONS::contains); + } + + private static boolean writableByUntrusted(Set mode) { + return mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static boolean sameAttributes(BasicFileAttributes left, BasicFileAttributes right) { + return left.isRegularFile() == right.isRegularFile() + && left.isDirectory() == right.isDirectory() + && left.isSymbolicLink() == right.isSymbolicLink() + && left.size() == right.size() + && Objects.equals(left.fileKey(), right.fileKey()) + && left.creationTime().equals(right.creationTime()) + && left.lastModifiedTime().equals(right.lastModifiedTime()); + } + + private static boolean isCanonicalUid(String uid) { + return UID.matcher(uid).matches(); + } + + private static ProtectedPodUidUnavailableException unavailable() { + return new ProtectedPodUidUnavailableException(); + } + + /** Redacted failure for an unavailable or unsafe projected UID. */ + public static final class ProtectedPodUidUnavailableException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private ProtectedPodUidUnavailableException() { + super("Protected Pod UID projection is unavailable"); + } + } + + private record DirectorySnapshot( + BasicFileAttributes attributes, Set mode, long ownerUid) { + private DirectorySnapshot { + Objects.requireNonNull(attributes); + mode = Set.copyOf(mode); + } + + private boolean sameAs(DirectorySnapshot other) { + return sameAttributes(attributes, other.attributes) + && mode.equals(other.mode) + && ownerUid == other.ownerUid; + } + } + + private record FileSnapshot( + BasicFileAttributes attributes, Set mode, long ownerUid) { + private FileSnapshot { + Objects.requireNonNull(attributes); + mode = Set.copyOf(mode); + } + + private boolean sameAs(FileSnapshot other) { + return sameAttributes(attributes, other.attributes) + && mode.equals(other.mode) + && ownerUid == other.ownerUid; + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedPodUidProjectionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedPodUidProjectionTest.java new file mode 100644 index 0000000000..ae49e2955a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedPodUidProjectionTest.java @@ -0,0 +1,190 @@ +package net.firedevops.firemud.common.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.util.EnumSet; +import java.util.Set; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class ProtectedPodUidProjectionTest { + private static final String POD_UID = "33333333-3333-4333-8333-333333333333"; + private static final String DATA_DIRECTORY = "..2026_10_09_12_34_56.123456789"; + + @TempDir Path temporaryDirectory; + + @Test + void readsCanonicalUidFromAtomicWriterProjectionFixture() throws IOException { + Projection projection = createProjection(POD_UID); + + assertThat(ProtectedPodUidProjection.readForTesting(projection.root(), projection.ownerUid())) + .isEqualTo(POD_UID); + assertThat(Files.getPosixFilePermissions(projection.root())) + .contains(PosixFilePermission.OWNER_WRITE) + .doesNotContain(PosixFilePermission.GROUP_WRITE, PosixFilePermission.OTHERS_WRITE); + assertThat(Files.getPosixFilePermissions(projection.uidFile())) + .containsExactlyInAnyOrder( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ); + } + + @Test + void acceptsCanonicalUidWithLeadingZeroesInFirstGroup() throws IOException { + String uid = "00000000-0000-4000-8000-000000000001"; + Projection projection = createProjection(uid); + + assertThat(ProtectedPodUidProjection.readForTesting(projection.root(), projection.ownerUid())) + .isEqualTo(uid); + } + + @Test + void rejectsMalformedUid() throws IOException { + Projection projection = createProjection(POD_UID + "\n"); + + assertUnavailable(projection); + } + + @Test + void rejectsNilUid() throws IOException { + Projection projection = createProjection("00000000-0000-0000-0000-000000000000"); + + assertUnavailable(projection); + } + + @Test + void rejectsWritableUidFile() throws IOException { + Projection projection = createProjection(POD_UID); + Files.setPosixFilePermissions( + projection.uidFile(), + permissions( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + + assertUnavailable(projection); + } + + @Test + void rejectsGroupWritableProjectionDirectory() throws IOException { + Projection projection = createProjection(POD_UID); + Files.setPosixFilePermissions( + projection.root(), + permissions( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_WRITE, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_EXECUTE)); + + assertUnavailable(projection); + } + + @Test + void rejectsWritableAtomicWriterTargetDirectory() throws IOException { + Projection projection = createProjection(POD_UID); + Files.setPosixFilePermissions( + projection.targetDirectory(), + permissions( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_WRITE, + PosixFilePermission.OTHERS_EXECUTE)); + + assertUnavailable(projection); + } + + @Test + void rejectsUidLinkThatBypassesAtomicWriterDataLink() throws IOException { + Projection projection = createProjection(POD_UID); + Files.delete(projection.root().resolve("uid")); + Files.createSymbolicLink(projection.root().resolve("uid"), Path.of(DATA_DIRECTORY, "uid")); + + assertUnavailable(projection); + } + + @Test + void rejectsNonCanonicalAtomicWriterDataLink() throws IOException { + Projection projection = createProjection(POD_UID); + Files.delete(projection.root().resolve("..data")); + Files.createSymbolicLink(projection.root().resolve("..data"), Path.of("..")); + + assertUnavailable(projection); + } + + @Test + void rejectsWrongOwner() throws IOException { + Projection projection = createProjection(POD_UID); + + assertThatThrownBy( + () -> + ProtectedPodUidProjection.readForTesting( + projection.root(), projection.ownerUid() + 1)) + .isInstanceOf(ProtectedPodUidProjection.ProtectedPodUidUnavailableException.class); + } + + private Projection createProjection(String uidContents) throws IOException { + Path root = Files.createDirectory(temporaryDirectory.resolve("pod-identity")); + Path targetDirectory = Files.createDirectory(root.resolve(DATA_DIRECTORY)); + Path uidFile = Files.writeString(targetDirectory.resolve("uid"), uidContents); + Files.setPosixFilePermissions( + root, + permissions( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_EXECUTE)); + Files.setPosixFilePermissions( + targetDirectory, + permissions( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_EXECUTE)); + Files.setPosixFilePermissions( + uidFile, + permissions( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ)); + Files.createSymbolicLink(root.resolve("..data"), Path.of(DATA_DIRECTORY)); + Files.createSymbolicLink(root.resolve("uid"), Path.of("..data", "uid")); + Object owner = Files.getAttribute(root, "unix:uid"); + if (!(owner instanceof Number uid)) { + throw new IOException("Temporary projection has no Unix owner"); + } + return new Projection(root, targetDirectory, uidFile, uid.longValue()); + } + + private void assertUnavailable(Projection projection) { + assertThatThrownBy( + () -> + ProtectedPodUidProjection.readForTesting(projection.root(), projection.ownerUid())) + .isInstanceOf(ProtectedPodUidProjection.ProtectedPodUidUnavailableException.class); + } + + private static Set permissions(PosixFilePermission... values) { + return EnumSet.copyOf(java.util.List.of(values)); + } + + private record Projection(Path root, Path targetDirectory, Path uidFile, long ownerUid) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index 63d2782d72..3750aa16a0 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -96,12 +96,17 @@ public VersionDto publishFullVersion( public PublishWorkflowSnapshot reconcileFullVersionPublish(PublishWorkflowRequest request) { request = request.recoverMissingPublishRequestId(); validateRequestIdentity(request); + PublishAttempt attempt = + publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()).orElse(null); + return reconcileFullVersionPublish(request, attempt); + } + + private PublishWorkflowSnapshot reconcileFullVersionPublish( + PublishWorkflowRequest request, PublishAttempt attempt) { logger.info( "Reconciling full-version publish workflow tenant={} workflowId={}", request.tenantId(), request.publishWorkflowId()); - PublishAttempt attempt = - publishAttemptRepository.findByPublishWorkflowId(request.publishWorkflowId()).orElse(null); if (attempt == null) { attempt = reserveDraftAttempt(request); } @@ -235,7 +240,6 @@ public PublishWorkflowSnapshot reconcileSelectedDraftFullVersionPublish( PublishWorkflowRequest request = new PublishWorkflowRequest(tenantId, notes, publishRequestId, publishWorkflowId); request = request.recoverMissingPublishRequestId(); - validateRequestIdentity(request); PublishAttempt attempt = publishAttemptRepository .findByPublishWorkflowId(publishWorkflowId) @@ -247,6 +251,7 @@ public PublishWorkflowSnapshot reconcileSelectedDraftFullVersionPublish( throw pendingReconciliation("selected Draft publication identity is unavailable or changed"); } try { + validateFullVersionAttemptIdentity(attempt, request); requireExactSelectedPublication(attempt, request); } catch (PendingReconciliationException unresolved) { throw unresolved; @@ -254,7 +259,7 @@ public PublishWorkflowSnapshot reconcileSelectedDraftFullVersionPublish( throw pendingReconciliation( "selected Draft publication requires exact operation reconciliation", unresolved); } - return reconcileFullVersionPublish(request); + return reconcileFullVersionPublish(request, attempt); } /** User-facing semantics for the unregistered selected-Draft backend path. */ @@ -692,8 +697,16 @@ private void requireExactSelectedPublication( publishAttemptRepository.requireSelectedPublicationReadback(attempt, expectedOutcome); var selection = operation.account().input().selection(); var intent = selection.intent(); + String expectedWorkflowId = + PublicationDigestRequestBinding.full( + intent.canonicalTenantId().toString(), + Long.toString(operation.versionId()), + intent.publishRequestId()) + .derivedWorkflowIdentity(); if (!Objects.equals(operation.tenantKey(), request.tenantId()) || operation.versionId() != attempt.getVersionId() + || !Objects.equals(operation.selectionDigest(), attempt.getRequestDigest()) + || !Objects.equals(operation.workflowId(), expectedWorkflowId) || !Objects.equals(operation.workflowId(), request.publishWorkflowId()) || !Objects.equals(intent.publishRequestId(), request.publishRequestId()) || !Objects.equals(intent.notes(), request.notes())) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 7c02d3093c..deb2f898cc 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -15,6 +16,9 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; @@ -30,6 +34,7 @@ import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.PublishType; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; @@ -105,6 +110,66 @@ void setup() { recordedParticipantDigestService); } + @Test + void selectedPublicationRejectsPrivateTenantDerivedWorkflowIdentity() { + String tenantId = "9002"; + long versionId = 10L; + String publishRequestId = "selected-request-7"; + String notes = "selected draft notes"; + UUID canonicalTenantId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + String privateTenantWorkflowId = + TemporalVersionPublishOrchestrator.workflowId(tenantId, publishRequestId); + String selectedWorkflowId = + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(versionId), publishRequestId) + .derivedWorkflowIdentity(); + assertNotEquals(selectedWorkflowId, privateTenantWorkflowId); + + String selectionDigest = "sha256:" + "a".repeat(64); + PublishAttempt attempt = + fullAttempt(PublishAttemptStatus.PENDING, versionId, 1, privateTenantWorkflowId); + attempt.setTenantId(tenantId); + attempt.setRequestDigest(selectionDigest); + when(publishAttemptRepository.findByPublishWorkflowId(privateTenantWorkflowId)) + .thenReturn(Optional.of(attempt)); + + GameDesignPublicationOperation operation = + org.mockito.Mockito.mock(GameDesignPublicationOperation.class); + AccountPublicationAuthorizationBinding account = + org.mockito.Mockito.mock(AccountPublicationAuthorizationBinding.class); + AccountPublicationAuthorizationBinding.PreallocationInput input = + org.mockito.Mockito.mock(AccountPublicationAuthorizationBinding.PreallocationInput.class); + AuthoredDraftPublishSelectionBinding selection = + org.mockito.Mockito.mock(AuthoredDraftPublishSelectionBinding.class); + AuthoredDraftPublishSelectionBinding.PublishIntent intent = + org.mockito.Mockito.mock(AuthoredDraftPublishSelectionBinding.PublishIntent.class); + when(operation.account()).thenReturn(account); + when(account.input()).thenReturn(input); + when(input.selection()).thenReturn(selection); + when(selection.intent()).thenReturn(intent); + when(intent.canonicalTenantId()).thenReturn(canonicalTenantId); + when(intent.publishRequestId()).thenReturn(publishRequestId); + when(intent.notes()).thenReturn(notes); + when(operation.tenantKey()).thenReturn(tenantId); + when(operation.versionId()).thenReturn(versionId); + when(operation.selectionDigest()).thenReturn(selectionDigest); + when(operation.workflowId()).thenReturn(privateTenantWorkflowId); + when(publishAttemptRepository.requireSelectedPublicationReadback(attempt, "PENDING")) + .thenReturn(operation); + + VersionPublishCommandServiceImpl.PendingReconciliationException thrown = + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileSelectedDraftFullVersionPublish( + tenantId, versionId, notes, publishRequestId, privateTenantWorkflowId)); + + assertTrue( + thrown.getCause().getMessage().contains("SELECTED_PUBLICATION_REQUEST_IDENTITY_CHANGED")); + verify(publishAttemptRepository).requireSelectedPublicationReadback(attempt, "PENDING"); + verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); + } + @Test void publishFullVersionUsesTenantScopedVersionSequence() { Game game = new Game(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfiguration.java index 4a35de823c..c4cc44b9fb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfiguration.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfiguration.java @@ -12,28 +12,40 @@ import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProbeOwnerClient; import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProbeOwnerReadPort; import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProtectedJwksSource; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProtectedLocalIdentityProvider; import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverEngine; import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverProtoMapper; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.ssl.SslBundles; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; /** - * Explicit default-off composition; absence of protected Pod identity leaves the route - * unregistered. + * Explicit default-off composition; every identity read requires current protected Pod and TLS + * evidence plus authenticated Account metadata. */ @Configuration(proxyBeanMethods = false) @ConditionalOnProperty( prefix = "firemud.game-session.jwt-readiness.receiver", name = "enabled", havingValue = "true") -@ConditionalOnBean(GameSessionJwtReadinessLocalIdentityProvider.class) +@ConditionalOnBean(SslBundles.class) @Lazy public class GameSessionJwtReadinessReceiverConfiguration { + @Bean + @Lazy + public GameSessionJwtReadinessLocalIdentityProvider gameSessionJwtReadinessLocalIdentityProvider( + GameSessionJwtReadinessProbeOwnerClient metadataReadClient, + SslBundles sslBundles, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new GameSessionJwtReadinessProtectedLocalIdentityProvider( + metadataReadClient, sslBundles, workloadNamespace); + } + @Bean @Lazy public GameSessionJwtReadinessProtectedJwksSource gameSessionJwtReadinessPublicJwksSource( @@ -75,7 +87,7 @@ public GameSessionJwtReadinessProbeCrypto gameSessionJwtReadinessProbeCrypto( @Bean @Lazy - public GameSessionJwtReadinessProbeOwnerReadPort gameSessionJwtReadinessProbeOwnerReadPort( + public GameSessionJwtReadinessProbeOwnerClient gameSessionJwtReadinessProbeOwnerReadPort( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessLocalIdentityProvider.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessLocalIdentityProvider.java index 16a75451d9..24bac6ed3e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessLocalIdentityProvider.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessLocalIdentityProvider.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; +import java.util.regex.Pattern; import net.firedevops.firemud.account.v1.AccountSourceIdentity; import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; @@ -14,6 +15,8 @@ public interface GameSessionJwtReadinessLocalIdentityProvider { record LocalObservation( ReadinessReceiverLocalIdentity wireIdentity, SourceIdentity jwksSourceIdentity) { + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "ReadinessReceiverLocalIdentity is an immutable generated protobuf value.") @@ -22,7 +25,10 @@ record LocalObservation( Objects.requireNonNull(jwksSourceIdentity, "protected JWKS source identity is required"); if (!wireIdentity.hasAccountJwksSourceIdentity() || !jwksSourceIdentity.equals(fromProto(wireIdentity.getAccountJwksSourceIdentity())) - || wireIdentity.getAccountJwksTrustConfigRevision() <= 0L) { + || !wireIdentity + .getAccountJwksTrustBindingRevision() + .equals(jwksSourceIdentity.bindingRevision()) + || !SHA256.matcher(wireIdentity.getAccountPublicJwksSha256()).matches()) { throw new IllegalArgumentException("Protected receiver JWKS identity is inconsistent"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerClient.java index ea04851f0f..5bcc91d20e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProbeOwnerClient.java @@ -4,18 +4,23 @@ import io.grpc.ManagedChannel; import java.util.Objects; import java.util.concurrent.TimeUnit; +import java.util.function.Function; import net.firedevops.firemud.account.v1.AccountJwtReadinessProbeOwnerServiceGrpc; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataResponse; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Direct mTLS-only client for the exact Account readiness owner read; attaches no bearer token. */ public final class GameSessionJwtReadinessProbeOwnerClient - implements GameSessionJwtReadinessProbeOwnerReadPort { + implements GameSessionJwtReadinessProbeOwnerReadPort, + GameSessionJwtReadinessReceiverMetadataReadPort { private static final int DEFAULT_ACCOUNT_PORT = 6565; private static final long DEADLINE_SECONDS = 5L; private static final long SHUTDOWN_SECONDS = 2L; @@ -47,6 +52,25 @@ public GameSessionJwtReadinessProbeOwnerClient( public GetCurrentReadinessProbeOwnerResponse readCurrent( GetCurrentReadinessProbeOwnerRequest request) { Objects.requireNonNull(request, "Current Account owner read request is required"); + return callAccount(service -> service.getCurrentReadinessProbeOwner(request)); + } + + @Override + public GetCurrentReadinessReceiverMetadataResponse readCurrent( + GetCurrentReadinessReceiverMetadataRequest request) { + Objects.requireNonNull(request, "Current Account receiver metadata request is required"); + return callAccount(service -> service.getCurrentReadinessReceiverMetadata(request)); + } + + private T callAccount( + Function< + AccountJwtReadinessProbeOwnerServiceGrpc + .AccountJwtReadinessProbeOwnerServiceBlockingStub, + T> + call) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new OwnerReadUnavailableException(); + } ManagedChannel channel = null; try { String target = endpoints.getAccountService(); @@ -59,9 +83,9 @@ public GetCurrentReadinessProbeOwnerResponse readCurrent( var accountChannel = ClientInterceptors.intercept( channel, new GrpcServerPeerIdentityClientInterceptor(expectedAccountUri)); - return AccountJwtReadinessProbeOwnerServiceGrpc.newBlockingStub(accountChannel) - .withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS) - .getCurrentReadinessProbeOwner(request); + return call.apply( + AccountJwtReadinessProbeOwnerServiceGrpc.newBlockingStub(accountChannel) + .withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS)); } catch (RuntimeException | javax.net.ssl.SSLException unavailable) { throw new OwnerReadUnavailableException(); } finally { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java index 7a24ec1700..d76cc273bb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java @@ -10,6 +10,7 @@ import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; import java.util.Objects; import java.util.Set; import net.firedevops.firemud.common.security.AccountPublicJwksCache; @@ -23,13 +24,13 @@ public final class GameSessionJwtReadinessProtectedJwksSource implements TrustedPublicJwksSource { public static final Path JWKS_PATH = fixedJwksPath(); - private static final Path JWKS_DIRECTORY = - Objects.requireNonNull( - JWKS_PATH.getParent(), "The fixed Account JWKS path must have a parent"); - private static final Path DATA_LINK = JWKS_DIRECTORY.resolve("..data"); private static final int MAX_FILE_BYTES = AccountPublicJwksCache.MAX_JWKS_BYTES; private final GameSessionJwtReadinessLocalIdentityProvider identityProvider; + private final Path jwksPath; + private final Path jwksDirectory; + private final Path dataLink; + private final long expectedOwnerUid; @SuppressFBWarnings( value = "DMI_HARDCODED_ABSOLUTE_FILENAME", @@ -41,7 +42,27 @@ private static Path fixedJwksPath() { public GameSessionJwtReadinessProtectedJwksSource( GameSessionJwtReadinessLocalIdentityProvider identityProvider) { + this(identityProvider, JWKS_PATH, 0L); + } + + GameSessionJwtReadinessProtectedJwksSource( + GameSessionJwtReadinessLocalIdentityProvider identityProvider, + Path jwksPath, + long expectedOwnerUid) { this.identityProvider = Objects.requireNonNull(identityProvider); + this.jwksPath = Objects.requireNonNull(jwksPath); + this.jwksDirectory = + Objects.requireNonNull(jwksPath.getParent(), "The Account JWKS path must have a parent"); + this.dataLink = jwksDirectory.resolve("..data"); + Path fileName = jwksPath.getFileName(); + if (!jwksPath.isAbsolute() + || !jwksPath.equals(jwksPath.normalize()) + || fileName == null + || !"jwks.json".equals(fileName.toString()) + || expectedOwnerUid < 0L) { + throw new IllegalArgumentException("Protected Account JWKS path or owner is invalid"); + } + this.expectedOwnerUid = expectedOwnerUid; } @Override @@ -51,6 +72,9 @@ public PublicJwksSnapshot load() { Objects.requireNonNull(identityProvider.observe()); byte[] bytes = readProjectedFile(); try { + if (!before.wireIdentity().getAccountPublicJwksSha256().equals(sha256(bytes))) { + throw unavailable(); + } GameSessionJwtReadinessLocalIdentityProvider.LocalObservation after = Objects.requireNonNull(identityProvider.observe()); if (!before.equals(after)) { @@ -67,38 +91,38 @@ public PublicJwksSnapshot load() { } } - private static byte[] readProjectedFile() throws IOException { - Path normalizedDirectory = JWKS_DIRECTORY.toAbsolutePath().normalize(); - if (!normalizedDirectory.equals(JWKS_DIRECTORY) - || Files.isSymbolicLink(JWKS_DIRECTORY) - || !Files.isSymbolicLink(DATA_LINK) - || !Files.isSymbolicLink(JWKS_PATH) - || !Path.of("..data/jwks.json").equals(Files.readSymbolicLink(JWKS_PATH))) { + private byte[] readProjectedFile() throws IOException { + Path normalizedDirectory = jwksDirectory.toAbsolutePath().normalize(); + if (!normalizedDirectory.equals(jwksDirectory) + || Files.isSymbolicLink(jwksDirectory) + || !Files.isSymbolicLink(dataLink) + || !Files.isSymbolicLink(jwksPath) + || !Path.of("..data/jwks.json").equals(Files.readSymbolicLink(jwksPath))) { throw unavailable(); } - Path dataVersion = Files.readSymbolicLink(DATA_LINK); + Path dataVersion = Files.readSymbolicLink(dataLink); if (dataVersion.isAbsolute() || dataVersion.getNameCount() != 1 || !dataVersion.toString().matches("\\.\\.[A-Za-z0-9._-]{1,128}")) { throw unavailable(); } - Path trustedDirectory = JWKS_DIRECTORY.toRealPath(LinkOption.NOFOLLOW_LINKS); - verifyRootOwnedReadOnly(trustedDirectory, true); - Path dataTarget = DATA_LINK.toRealPath(); + Path trustedDirectory = jwksDirectory.toRealPath(LinkOption.NOFOLLOW_LINKS); + verifyOwnedProjectionPath(trustedDirectory, true); + Path dataTarget = dataLink.toRealPath(); Path dataTargetParent = dataTarget.getParent(); if (dataTargetParent == null || !dataTargetParent.equals(trustedDirectory) || !Files.isDirectory(dataTarget, LinkOption.NOFOLLOW_LINKS)) { throw unavailable(); } - verifyRootOwnedReadOnly(dataTarget, true); + verifyOwnedProjectionPath(dataTarget, true); Path file = dataTarget.resolve("jwks.json"); BasicFileAttributes before = Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); if (!before.isRegularFile() || before.size() <= 0L || before.size() > MAX_FILE_BYTES) { throw unavailable(); } - verifyRootOwnedReadOnly(file, false); + verifyOwnedProjectionPath(file, false); byte[] bytes = new byte[(int) before.size()]; try (SeekableByteChannel channel = Files.newByteChannel(file, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { @@ -117,17 +141,17 @@ private static byte[] readProjectedFile() throws IOException { if (!Objects.equals(before.fileKey(), after.fileKey()) || before.size() != after.size() || !before.lastModifiedTime().equals(after.lastModifiedTime()) - || !dataVersion.equals(Files.readSymbolicLink(DATA_LINK)) - || !dataTarget.equals(DATA_LINK.toRealPath()) - || !Path.of("..data/jwks.json").equals(Files.readSymbolicLink(JWKS_PATH))) { + || !dataVersion.equals(Files.readSymbolicLink(dataLink)) + || !dataTarget.equals(dataLink.toRealPath()) + || !Path.of("..data/jwks.json").equals(Files.readSymbolicLink(jwksPath))) { java.util.Arrays.fill(bytes, (byte) 0); throw unavailable(); } - verifyRootOwnedReadOnly(file, false); + verifyOwnedProjectionPath(file, false); return bytes; } - private static void verifyRootOwnedReadOnly(Path path, boolean directory) throws IOException { + private void verifyOwnedProjectionPath(Path path, boolean directory) throws IOException { BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); if ((directory && !attributes.isDirectory()) || (!directory && !attributes.isRegularFile())) { @@ -135,15 +159,23 @@ private static void verifyRootOwnedReadOnly(Path path, boolean directory) throws } Object owner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); Set mode = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); - if (!(owner instanceof Number uid) - || uid.longValue() != 0L - || mode.contains(PosixFilePermission.OWNER_WRITE) - || mode.contains(PosixFilePermission.GROUP_WRITE) - || mode.contains(PosixFilePermission.OTHERS_WRITE)) { + boolean unsafeWrite = + mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE) + || (!directory && mode.contains(PosixFilePermission.OWNER_WRITE)); + if (!(owner instanceof Number uid) || uid.longValue() != expectedOwnerUid || unsafeWrite) { throw unavailable(); } } + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception unavailable) { + throw new SourceUnavailableException(); + } + } + private static SourceUnavailableException unavailable() { return new SourceUnavailableException(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProvider.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProvider.java new file mode 100644 index 0000000000..ee409f2f87 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProvider.java @@ -0,0 +1,410 @@ +package net.firedevops.firemud.gamesession.service; + +import java.net.URI; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.AccountSourceIdentity; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataResponse; +import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.ProtectedPodUidProjection; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Builds Game Session's local readiness identity from the protected Pod UID, its active TLS leaf, + * and Account's authenticated current receiver-metadata read. + */ +public final class GameSessionJwtReadinessProtectedLocalIdentityProvider + implements GameSessionJwtReadinessLocalIdentityProvider { + private static final String TLS_BUNDLE_NAME = "firemud-grpc"; + private static final String GAME_SESSION_VALIDATOR = "game-session-service"; + private static final Pattern KUBERNETES_UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern INVENTORY_REVISION = + Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern IMMUTABLE_IMAGE = Pattern.compile("[^\\s@]+@sha256:[0-9a-f]{64}"); + + private final GameSessionJwtReadinessReceiverMetadataReadPort metadataReadPort; + private final SslBundles sslBundles; + private final Clock clock; + private final String workloadNamespace; + private final Supplier projectedPodUidSource; + + public GameSessionJwtReadinessProtectedLocalIdentityProvider( + GameSessionJwtReadinessReceiverMetadataReadPort metadataReadPort, + SslBundles sslBundles, + String workloadNamespace) { + this( + metadataReadPort, + sslBundles, + workloadNamespace, + Clock.systemUTC(), + ProtectedPodUidProjection::read); + } + + GameSessionJwtReadinessProtectedLocalIdentityProvider( + GameSessionJwtReadinessReceiverMetadataReadPort metadataReadPort, + SslBundles sslBundles, + String workloadNamespace, + Clock clock, + Supplier projectedPodUidSource) { + this.metadataReadPort = Objects.requireNonNull(metadataReadPort); + this.sslBundles = Objects.requireNonNull(sslBundles); + this.clock = Objects.requireNonNull(clock); + this.projectedPodUidSource = Objects.requireNonNull(projectedPodUidSource); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Protected Game Session workload namespace is required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public LocalObservation observe() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw unavailable(); + } + try { + String podUidBefore = readProjectedPodUid(); + LocalTlsLeaf tlsLeafBefore = readLocalTlsLeaf(); + GetCurrentReadinessReceiverMetadataRequest request = + GetCurrentReadinessReceiverMetadataRequest.newBuilder() + .setSchemaVersion(1) + .setProjectedPodUid(podUidBefore) + .setServerLeafSpkiSha256(tlsLeafBefore.spkiSha256()) + .build(); + GetCurrentReadinessReceiverMetadataResponse response = metadataReadPort.readCurrent(request); + ReadinessReceiverLocalIdentity identity = + requireCurrentIdentity(response, podUidBefore, tlsLeafBefore); + + String podUidAfter = readProjectedPodUid(); + LocalTlsLeaf tlsLeafAfter = readLocalTlsLeaf(); + if (!podUidBefore.equals(podUidAfter) + || !tlsLeafBefore.equals(tlsLeafAfter) + || !identity.getPodUid().equals(podUidAfter) + || !identity.getServerLeafSpkiSha256().equals(tlsLeafAfter.spkiSha256())) { + throw unavailable(); + } + return new LocalObservation( + identity, sourceIdentity(identity.getAccountJwksSourceIdentity())); + } catch (IdentityUnavailableException failure) { + throw failure; + } catch (Exception failure) { + throw unavailable(); + } + } + + private ReadinessReceiverLocalIdentity requireCurrentIdentity( + GetCurrentReadinessReceiverMetadataResponse response, + String projectedPodUid, + LocalTlsLeaf tlsLeaf) { + if (response == null + || response.getSchemaVersion() != 1 + || !response.getUnknownFields().asMap().isEmpty() + || !canonicalUuid(response.getRotationOperationId()) + || !isSha256(response.getOperationDigest()) + || !isSha256(response.getPlanDigest()) + || !response.hasCurrentIdentity()) { + throw unavailable(); + } + ReadinessReceiverLocalIdentity identity = response.getCurrentIdentity(); + if (!identity.getUnknownFields().asMap().isEmpty() + || !identity.hasAccountJwksSourceIdentity() + || !identity.getAccountJwksSourceIdentity().getUnknownFields().asMap().isEmpty() + || !GAME_SESSION_VALIDATOR.equals(identity.getValidatorId()) + || !isCanonicalUid(identity.getDeploymentUid()) + || !projectedPodUid.equals(identity.getPodUid()) + || !isCanonicalUid(identity.getPodUid()) + || !isImmutableImage(identity.getImage()) + || !INVENTORY_REVISION.matcher(identity.getSourceInventoryRevision()).matches() + || !isCanonicalPodEndpoint(identity.getPodIp(), identity.getDirectPodEndpoint()) + || !tlsLeaf.spkiSha256().equals(identity.getServerLeafSpkiSha256()) + || !expectedServiceUri().equals(identity.getCanonicalServiceUri()) + || !isSha256(identity.getVerifierConfigSha256()) + || !isSha256(identity.getApplicabilityMatrixDigest()) + || !isSha256(identity.getSourceInventoryDigest()) + || !isSha256(identity.getAccountPublicJwksSha256()) + || !identity + .getAccountJwksTrustBindingRevision() + .equals(identity.getAccountJwksSourceIdentity().getBindingRevision())) { + throw unavailable(); + } + SourceIdentity source = sourceIdentity(identity.getAccountJwksSourceIdentity()); + if (!workloadNamespace.equals(source.namespace())) { + throw unavailable(); + } + return identity; + } + + private String readProjectedPodUid() { + String uid = projectedPodUidSource.get(); + if (!isCanonicalUid(uid)) { + throw unavailable(); + } + return uid; + } + + private static boolean isCanonicalUid(String value) { + return value != null && KUBERNETES_UID.matcher(value).matches(); + } + + private static boolean isImmutableImage(String value) { + return value != null && value.length() <= 1024 && IMMUTABLE_IMAGE.matcher(value).matches(); + } + + private static boolean isCanonicalPodEndpoint(String podIp, String endpointValue) { + String canonicalIp = canonicalPodIp(podIp); + if (canonicalIp == null || endpointValue == null || endpointValue.length() > 256) { + return false; + } + try { + URI endpoint = URI.create(endpointValue); + String endpointHost = endpoint.getHost(); + String bracketedIp = canonicalIp.indexOf(':') >= 0 ? "[" + canonicalIp + "]" : canonicalIp; + return endpoint.toString().equals(endpointValue) + && "grpcs".equals(endpoint.getScheme()) + && endpoint.getRawUserInfo() == null + && endpoint.getRawQuery() == null + && endpoint.getRawFragment() == null + && (endpoint.getRawPath() == null || endpoint.getRawPath().isEmpty()) + && endpoint.getPort() > 0 + && endpoint.getPort() <= 65535 + && (canonicalIp.equals(endpointHost) || bracketedIp.equals(endpointHost)) + && endpointValue.equals("grpcs://" + bracketedIp + ":" + endpoint.getPort()); + } catch (IllegalArgumentException invalid) { + return false; + } + } + + private static String canonicalPodIp(String value) { + if (value == null || value.isBlank() || value.indexOf('%') >= 0) { + return null; + } + try { + if (value.indexOf(':') < 0) { + String[] components = value.split("\\.", -1); + if (components.length != 4) { + return null; + } + for (String component : components) { + if (component.isEmpty() + || (component.length() > 1 && component.charAt(0) == '0') + || !component.matches("[0-9]{1,3}") + || Integer.parseInt(component) > 255) { + return null; + } + } + return "0.0.0.0".equals(value) || "255.255.255.255".equals(value) ? null : value; + } + String canonical = canonicalIpv6Literal(value); + return value.equals(canonical) ? value : null; + } catch (NumberFormatException invalid) { + return null; + } + } + + private static String canonicalIpv6Literal(String value) { + if (!value.matches("[0-9A-Fa-f:]+")) { + return null; + } + int compressionIndex = value.indexOf("::"); + if (compressionIndex != value.lastIndexOf("::")) { + return null; + } + List left; + List right; + if (compressionIndex < 0) { + left = parseIpv6Groups(value); + right = List.of(); + if (left == null || left.size() != 8) { + return null; + } + } else { + left = parseIpv6Groups(value.substring(0, compressionIndex)); + right = parseIpv6Groups(value.substring(compressionIndex + 2)); + if (left == null || right == null || left.size() + right.size() >= 8) { + return null; + } + } + int[] groups = new int[8]; + int index = 0; + for (int group : left) { + groups[index++] = group; + } + if (compressionIndex >= 0) { + index = 8 - right.size(); + } + for (int group : right) { + groups[index++] = group; + } + byte[] address = new byte[16]; + for (int groupIndex = 0; groupIndex < groups.length; groupIndex++) { + address[groupIndex * 2] = (byte) (groups[groupIndex] >>> 8); + address[groupIndex * 2 + 1] = (byte) groups[groupIndex]; + } + return canonicalIpv6(address); + } + + private static List parseIpv6Groups(String value) { + if (value.isEmpty()) { + return List.of(); + } + List groups = new ArrayList<>(); + for (String group : value.split(":", -1)) { + if (group.isEmpty() || group.length() > 4 || !group.matches("[0-9A-Fa-f]{1,4}")) { + return null; + } + groups.add(Integer.parseInt(group, 16)); + } + return groups; + } + + private static String canonicalIpv6(byte[] bytes) { + if (bytes.length != 16) { + return ""; + } + int[] groups = new int[8]; + for (int index = 0; index < groups.length; index++) { + groups[index] = + Byte.toUnsignedInt(bytes[index * 2]) << 8 | Byte.toUnsignedInt(bytes[index * 2 + 1]); + } + int bestStart = -1; + int bestLength = 1; + for (int index = 0; index < groups.length; ) { + if (groups[index] != 0) { + index++; + continue; + } + int end = index; + while (end < groups.length && groups[end] == 0) { + end++; + } + if (end - index > bestLength) { + bestStart = index; + bestLength = end - index; + } + index = end; + } + StringBuilder canonical = new StringBuilder(); + for (int index = 0; index < groups.length; ) { + if (index == bestStart) { + canonical.append("::"); + index += bestLength; + continue; + } + if (canonical.length() > 0 && canonical.charAt(canonical.length() - 1) != ':') { + canonical.append(':'); + } + canonical.append(Integer.toHexString(groups[index])); + index++; + } + return canonical.toString(); + } + + private LocalTlsLeaf readLocalTlsLeaf() { + try { + SslBundle bundle = Objects.requireNonNull(sslBundles.getBundle(TLS_BUNDLE_NAME)); + KeyStore keyStore = Objects.requireNonNull(bundle.getStores().getKeyStore()); + List leaves = new ArrayList<>(); + var aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (!keyStore.isKeyEntry(alias)) { + continue; + } + Certificate certificate = keyStore.getCertificate(alias); + if (!(certificate instanceof X509Certificate x509)) { + throw unavailable(); + } + leaves.add(x509); + } + if (leaves.size() != 1) { + throw unavailable(); + } + X509Certificate leaf = leaves.getFirst(); + leaf.checkValidity(java.util.Date.from(clock.instant())); + GrpcPeerIdentity peer = + GrpcPeerIdentity.fromCertificate(leaf).orElseThrow(IdentityUnavailableException::new); + if (!expectedServiceUri().equals(peer.uri())) { + throw unavailable(); + } + String digest = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(leaf.getPublicKey().getEncoded())); + return new LocalTlsLeaf(peer.uri(), digest); + } catch (IdentityUnavailableException failure) { + throw failure; + } catch (Exception failure) { + throw unavailable(); + } + } + + private SourceIdentity sourceIdentity(AccountSourceIdentity value) { + try { + return new SourceIdentity( + value.getEnvironmentId(), + value.getClusterId(), + value.getClusterIncarnationUid(), + value.getNamespace(), + value.getNamespaceUid(), + value.getConfigMapUid(), + value.getBindingRevision(), + value.getApiServerOrigin(), + value.getServingCaSha256()); + } catch (RuntimeException invalid) { + throw unavailable(); + } + } + + private String expectedServiceUri() { + return "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + } + + private static boolean canonicalUuid(String value) { + if (value == null || value.isEmpty()) { + return false; + } + try { + UUID operationId = UUID.fromString(value); + return operationId.toString().equals(value) + && operationId.version() == 4 + && operationId.variant() == 2; + } catch (IllegalArgumentException invalid) { + return false; + } + } + + private static boolean isSha256(String value) { + return value != null && SHA256.matcher(value).matches(); + } + + private static IdentityUnavailableException unavailable() { + return new IdentityUnavailableException(); + } + + private record LocalTlsLeaf(String serviceUri, String spkiSha256) {} + + /** Redacted denial for unavailable or inconsistent protected Game Session identity evidence. */ + public static final class IdentityUnavailableException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public IdentityUnavailableException() { + super("Protected Game Session receiver identity is unavailable"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverMetadataReadPort.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverMetadataReadPort.java new file mode 100644 index 0000000000..b407235da1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverMetadataReadPort.java @@ -0,0 +1,11 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataResponse; + +/** Authenticated, read-only Account lookup for its current protected receiver metadata. */ +@FunctionalInterface +public interface GameSessionJwtReadinessReceiverMetadataReadPort { + GetCurrentReadinessReceiverMetadataResponse readCurrent( + GetCurrentReadinessReceiverMetadataRequest request); +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java index 02b0b6d1e7..4f8cca1ab1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java @@ -53,6 +53,8 @@ import net.firedevops.firemud.account.v1.AccountSourceIdentity; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerRequest; import net.firedevops.firemud.account.v1.GetCurrentReadinessProbeOwnerResponse; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataResponse; import net.firedevops.firemud.account.v1.ReadinessProbeCoordinates; import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -93,6 +95,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.json.JsonMapper; /** @@ -123,21 +126,29 @@ class GameSessionJwtReadinessReceiverMtlsIntegrationTest { private static TestPki pki; private Server gameSessionServer; private Server accountOwnerServer; + private GameSessionJwtReadinessProbeOwnerClient ownerClient; private TestIdentityFiles accountClientFiles; private TestIdentityFiles gameSessionFiles; private Path caCertificateFile; private final AtomicReference ownerResponseMode = new AtomicReference<>(OwnerResponseMode.EXACT); private final AtomicInteger ownerReadCalls = new AtomicInteger(); + private final AtomicInteger metadataReadCalls = new AtomicInteger(); private final AtomicReference lastOwnerRequest = new AtomicReference<>(); + private final AtomicReference lastMetadataRequest = + new AtomicReference<>(); private final AtomicReference ownerSawPeerUri = new AtomicReference<>(); + private final AtomicReference metadataSawPeerUri = new AtomicReference<>(); + private final AtomicReference metadataResponse = + new AtomicReference<>(); private final AtomicReference ownerTarget = new AtomicReference<>(); private final AtomicReference localObservation = new AtomicReference<>(); private final AtomicBoolean responseHadNoApplicationAuthContext = new AtomicBoolean(); private KeyPair signingKey; private AccountPublicJwksCache.SourceIdentity jwksSourceIdentity; + private String fixturePublicJwksSha256; private ReadinessReceiverLocalIdentity localIdentity; private AccountPodTargetBinding exactOwnerTarget; private ReceiveReadinessProbeRequest validRequest; @@ -171,8 +182,12 @@ static void createTestCertificates() throws Exception { void startIsolatedTransports() throws Exception { ownerResponseMode.set(OwnerResponseMode.EXACT); ownerReadCalls.set(0); + metadataReadCalls.set(0); lastOwnerRequest.set(null); + lastMetadataRequest.set(null); ownerSawPeerUri.set(null); + metadataSawPeerUri.set(null); + metadataResponse.set(null); ownerTarget.set(null); localObservation.set(null); responseHadNoApplicationAuthContext.set(false); @@ -183,13 +198,14 @@ void startIsolatedTransports() throws Exception { accountOwnerServer = startAccountOwnerServer(); ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("127.0.0.1:" + accountOwnerServer.getPort()); - GameSessionJwtReadinessProbeOwnerClient ownerClient = + ownerClient = new GameSessionJwtReadinessProbeOwnerClient( endpoints, clientProperties(gameSessionFiles), new GrpcChannelFactory(), NAMESPACE); signingKey = rsaKeyPair(3072); jwksSourceIdentity = sourceIdentity(); String jwks = jwks(KID, (RSAPublicKey) signingKey.getPublic()); + fixturePublicJwksSha256 = sha256(jwks); AccountPublicJwksCache keyCache = new AccountPublicJwksCache( () -> @@ -225,6 +241,14 @@ void startIsolatedTransports() throws Exception { .start(); localIdentity = localIdentity(gameSessionServer.getPort()); + metadataResponse.set( + GetCurrentReadinessReceiverMetadataResponse.newBuilder() + .setSchemaVersion(1) + .setRotationOperationId("66666666-6666-4666-8666-666666666666") + .setOperationDigest("a".repeat(64)) + .setPlanDigest("b".repeat(64)) + .setCurrentIdentity(localIdentity) + .build()); exactOwnerTarget = ownerTarget(localIdentity); localObservation.set( new GameSessionJwtReadinessLocalIdentityProvider.LocalObservation( @@ -278,6 +302,54 @@ void accountMtlsCallUsesProductionOwnerReadAndRealProfileVerificationWithoutAuth assertThat(SessionContext.getServiceInstanceId()).isNull(); } + @Test + void currentMetadataBootstrapUsesAccountMtlsAndOnlyProjectedUidAndActualLeafPin() + throws Exception { + GetCurrentReadinessReceiverMetadataRequest request = + GetCurrentReadinessReceiverMetadataRequest.newBuilder() + .setSchemaVersion(1) + .setProjectedPodUid(POD_UID) + .setServerLeafSpkiSha256(spkiSha256(pki.gameSession().certificate())) + .build(); + + GetCurrentReadinessReceiverMetadataResponse response = ownerClient.readCurrent(request); + + assertThat(response).isEqualTo(metadataResponse.get()); + assertThat(metadataReadCalls).hasValue(1); + assertThat(lastMetadataRequest.get()).isEqualTo(request); + assertThat(lastMetadataRequest.get().getUnknownFields().asMap()).isEmpty(); + assertThat(metadataSawPeerUri).hasValue(GAME_SESSION_URI); + assertThat(SessionContext.getAccountId()).isNull(); + assertThat(SessionContext.getGlobalRoles()).isEmpty(); + assertThat(SessionContext.getScopedRolesMap()).isEmpty(); + assertThat(SessionContext.isInternalService()).isFalse(); + } + + @Test + void ambientSqlTransactionDeniesBothAccountReadsBeforeDispatch() { + boolean previousTransactionState = + TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + ownerClient.readCurrent( + GetCurrentReadinessProbeOwnerRequest.newBuilder().build())) + .isInstanceOf( + GameSessionJwtReadinessProbeOwnerClient.OwnerReadUnavailableException.class); + assertThatThrownBy( + () -> + ownerClient.readCurrent( + GetCurrentReadinessReceiverMetadataRequest.newBuilder().build())) + .isInstanceOf( + GameSessionJwtReadinessProbeOwnerClient.OwnerReadUnavailableException.class); + assertThat(ownerReadCalls).hasValue(0); + assertThat(metadataReadCalls).hasValue(0); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previousTransactionState); + } + } + @Test void wrongWorkloadAndMissingWorkloadIdentityAreDeniedBeforeOwnerRead() throws Exception { for (TestCertificate caller : List.of(pki.wrongWorkload(), pki.missingWorkloadUri())) { @@ -423,6 +495,18 @@ public void getCurrentReadinessProbeOwner( ownerResponse(request, ownerResponseMode.get(), ownerReadCalls.get())); responseObserver.onCompleted(); } + + @Override + public void getCurrentReadinessReceiverMetadata( + GetCurrentReadinessReceiverMetadataRequest request, + StreamObserver responseObserver) { + metadataReadCalls.incrementAndGet(); + lastMetadataRequest.set(request); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + metadataSawPeerUri.set(peer == null ? null : peer.uri()); + responseObserver.onNext(metadataResponse.get()); + responseObserver.onCompleted(); + } }; return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .sslContext(serverTlsContext(writeIdentityFiles("account-server", pki.account()))) @@ -609,7 +693,8 @@ private ReadinessReceiverLocalIdentity localIdentity(int port) throws Exception .setSourceInventoryDigest("d".repeat(64)) .setServerLeafSpkiSha256(spkiSha256(pki.gameSession().certificate())) .setAccountJwksSourceIdentity(sourceIdentityProto()) - .setAccountJwksTrustConfigRevision(1L) + .setAccountJwksTrustBindingRevision(jwksSourceIdentity.bindingRevision()) + .setAccountPublicJwksSha256(fixturePublicJwksSha256) .build(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java index a7aaf556d6..3a9b544553 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionJwtReadinessReceiverConfigurationTest.java @@ -2,25 +2,48 @@ 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.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import io.grpc.ServerInterceptor; import io.grpc.ServerServiceDefinition; import io.grpc.TlsServerCredentials; +import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.util.Collections; import java.util.List; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; +import net.firedevops.firemud.common.security.ProtectedPodUidProjection; import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessLocalIdentityProvider; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProbeOwnerClient; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProtectedLocalIdentityProvider; import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessReceiverEngine; import net.firedevops.firemud.gamesession.service.impl.GameSessionJwtReadinessReceiverGrpcService; import net.firedevops.firemud.gamesession.v1.GameSessionJwtReadinessReceiverServiceGrpc; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.boot.ssl.SslStoreBundle; import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; import org.springframework.grpc.server.GrpcServerFactory; import org.springframework.grpc.server.ShadedNettyGrpcServerFactory; import org.springframework.grpc.server.service.GrpcService; class GameSessionJwtReadinessReceiverConfigurationTest { private static final String ENABLED = "firemud.game-session.jwt-readiness.receiver.enabled=true"; + private static final String POD_UID = "44444444-4444-4444-8444-444444444444"; private final ApplicationContextRunner routingRunner = new ApplicationContextRunner() @@ -66,6 +89,87 @@ void explicitEnablementWithoutProtectedLocalIdentityStillLeavesReceiverUnregiste }); } + @Test + void explicitEnablementComposesOnlyWithSpringManagedTlsIdentitySource() { + contextRunner + .withUserConfiguration(TestReadinessDependencies.class) + .withBean(SslBundles.class, () -> mock(SslBundles.class)) + .withPropertyValues(ENABLED) + .run( + context -> + assertThat(context) + .hasSingleBean(GameSessionJwtReadinessLocalIdentityProvider.class) + .hasSingleBean(GameSessionJwtReadinessReceiverEngine.class) + .hasSingleBean(GameSessionJwtReadinessReceiverGrpcService.class)); + } + + @Test + void selectedIdentityProviderRejectsMissingWorkloadNamespace() { + contextRunner + .withUserConfiguration(TestReadinessDependencies.class) + .withBean(SslBundles.class, () -> mock(SslBundles.class)) + .withPropertyValues(ENABLED) + .run( + context -> + assertThatThrownBy( + () -> context.getBean(GameSessionJwtReadinessLocalIdentityProvider.class)) + .hasRootCauseInstanceOf(IllegalArgumentException.class)); + } + + @Test + void selectedIdentityProviderRejectsMissingFiremudGrpcLeafBeforeAccountRead() { + try (MockedStatic uidProjection = + mockStatic(ProtectedPodUidProjection.class)) { + uidProjection.when(ProtectedPodUidProjection::read).thenReturn(POD_UID); + contextRunner + .withUserConfiguration(TestReadinessDependencies.class) + .withBean(SslBundles.class, () -> mock(SslBundles.class)) + .withPropertyValues(ENABLED, "firemud.grpc.workload-namespace=firemud-prod") + .run( + context -> { + GameSessionJwtReadinessProbeOwnerClient metadataReadClient = + context.getBean(GameSessionJwtReadinessProbeOwnerClient.class); + var identityProvider = + context.getBean(GameSessionJwtReadinessLocalIdentityProvider.class); + assertThatThrownBy(identityProvider::observe) + .isInstanceOf( + GameSessionJwtReadinessProtectedLocalIdentityProvider + .IdentityUnavailableException.class); + verify(metadataReadClient, never()) + .readCurrent(any(GetCurrentReadinessReceiverMetadataRequest.class)); + }); + } + } + + @Test + void selectedIdentityProviderRejectsUnavailableAccountMetadataRead() throws Exception { + SslBundles sslBundles = tlsBundlesWithGameSessionLeaf(); + try (MockedStatic uidProjection = + mockStatic(ProtectedPodUidProjection.class)) { + uidProjection.when(ProtectedPodUidProjection::read).thenReturn(POD_UID); + contextRunner + .withUserConfiguration(TestReadinessDependencies.class) + .withBean(SslBundles.class, () -> sslBundles) + .withPropertyValues(ENABLED, "firemud.grpc.workload-namespace=firemud-prod") + .run( + context -> { + GameSessionJwtReadinessProbeOwnerClient metadataClient = + context.getBean(GameSessionJwtReadinessProbeOwnerClient.class); + doThrow(new GameSessionJwtReadinessProbeOwnerClient.OwnerReadUnavailableException()) + .when(metadataClient) + .readCurrent(any(GetCurrentReadinessReceiverMetadataRequest.class)); + var identityProvider = + context.getBean(GameSessionJwtReadinessLocalIdentityProvider.class); + assertThatThrownBy(identityProvider::observe) + .isInstanceOf( + GameSessionJwtReadinessProtectedLocalIdentityProvider + .IdentityUnavailableException.class); + verify(metadataClient) + .readCurrent(any(GetCurrentReadinessReceiverMetadataRequest.class)); + }); + } + } + @Test void disabledRoutingDoesNotAlterFilteringOrRequireSupportedFactory() { routingRunner.run( @@ -117,4 +221,38 @@ private static ShadedNettyGrpcServerFactory factory() { private static ServerServiceDefinition definition(String name) { return ServerServiceDefinition.builder(name).build(); } + + private static GameSessionJwtReadinessProbeOwnerClient mockMetadataClient() { + return mock(GameSessionJwtReadinessProbeOwnerClient.class); + } + + private static SslBundles tlsBundlesWithGameSessionLeaf() throws Exception { + String serviceUri = "spiffe://firemud/ns/firemud-prod/sa/game-session-service"; + X509Certificate certificate = mock(X509Certificate.class); + PublicKey publicKey = mock(PublicKey.class); + when(certificate.getPublicKey()).thenReturn(publicKey); + when(publicKey.getEncoded()) + .thenReturn("game-session tls leaf".getBytes(StandardCharsets.US_ASCII)); + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, serviceUri))); + KeyStore keyStore = mock(KeyStore.class); + when(keyStore.aliases()).thenReturn(Collections.enumeration(List.of("game-session"))); + when(keyStore.isKeyEntry("game-session")).thenReturn(true); + when(keyStore.getCertificate("game-session")).thenReturn(certificate); + SslStoreBundle stores = mock(SslStoreBundle.class); + when(stores.getKeyStore()).thenReturn(keyStore); + SslBundle bundle = mock(SslBundle.class); + when(bundle.getStores()).thenReturn(stores); + SslBundles sslBundles = mock(SslBundles.class); + when(sslBundles.getBundle("firemud-grpc")).thenReturn(bundle); + return sslBundles; + } + + @Configuration(proxyBeanMethods = false) + static class TestReadinessDependencies { + @Bean + @Primary + GameSessionJwtReadinessProbeOwnerClient testMetadataClient() { + return mockMetadataClient(); + } + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSourceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSourceTest.java new file mode 100644 index 0000000000..2042da5a46 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSourceTest.java @@ -0,0 +1,199 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountSourceIdentity; +import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessLocalIdentityProvider.LocalObservation; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class GameSessionJwtReadinessProtectedJwksSourceTest { + private static final String JWKS = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"projected\"}]}"; + private static final Set MODE_0755 = + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_EXECUTE); + private static final Set MODE_0444 = + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ); + + @TempDir Path tempDirectory; + + @Test + void readsOnlyDigestMatchedAtomicProjectionAndAllowsOwnerWritable0755Directories() + throws Exception { + ProjectionFixture fixture = new ProjectionFixture(JWKS); + fixture.createProjection(MODE_0755, MODE_0755, MODE_0444); + var source = + fixture.source(fixture.observation(sha256(JWKS.getBytes(StandardCharsets.US_ASCII)))); + + PublicJwksSnapshot snapshot = source.load(); + + assertThat(snapshot.sourceIdentity()).isEqualTo(fixture.sourceIdentity); + assertThat(snapshot.jwksBytes()).isEqualTo(JWKS.getBytes(StandardCharsets.US_ASCII)); + } + + @Test + void rejectsProjectedBytesThatDoNotMatchAccountMetadataDigest() throws Exception { + ProjectionFixture fixture = new ProjectionFixture(JWKS); + fixture.createProjection(MODE_0755, MODE_0755, MODE_0444); + var source = fixture.source(fixture.observation("a".repeat(64))); + + assertUnavailable(source); + } + + @Test + void rejectsNonAtomicWriterProjectionShape() throws Exception { + ProjectionFixture fixture = new ProjectionFixture(JWKS); + fixture.createProjection(MODE_0755, MODE_0755, MODE_0444); + Files.delete(fixture.projection.resolve("jwks.json")); + Files.createSymbolicLink(fixture.projection.resolve("jwks.json"), Path.of("jwks.json")); + var source = + fixture.source(fixture.observation(sha256(JWKS.getBytes(StandardCharsets.US_ASCII)))); + + assertUnavailable(source); + } + + @Test + void rejectsGroupOrOtherWritableProjectionDirectoriesAndAnyWritableFile() throws Exception { + ProjectionFixture fixture = new ProjectionFixture(JWKS); + fixture.createProjection( + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_WRITE, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_EXECUTE), + MODE_0755, + MODE_0444); + var source = + fixture.source(fixture.observation(sha256(JWKS.getBytes(StandardCharsets.US_ASCII)))); + assertUnavailable(source); + + fixture.createProjection(MODE_0755, MODE_0755, MODE_0755); + source = fixture.source(fixture.observation(sha256(JWKS.getBytes(StandardCharsets.US_ASCII)))); + assertUnavailable(source); + } + + @Test + void rejectsChangedLocalIdentityAcrossProtectedFileRead() throws Exception { + ProjectionFixture fixture = new ProjectionFixture(JWKS); + fixture.createProjection(MODE_0755, MODE_0755, MODE_0444); + var source = + fixture.source( + fixture.observation(sha256(JWKS.getBytes(StandardCharsets.US_ASCII))), + fixture.observation("b".repeat(64))); + + assertUnavailable(source); + } + + private static void assertUnavailable(GameSessionJwtReadinessProtectedJwksSource source) { + assertThatThrownBy(source::load).isInstanceOf(SourceUnavailableException.class); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception unavailable) { + throw new AssertionError(unavailable); + } + } + + private final class ProjectionFixture { + private final Path projection = tempDirectory.resolve("jwks"); + private final Path dataDirectory = projection.resolve("..2026_10_09_00_00_00"); + private final Path jwksPath = projection.resolve("jwks.json"); + private final long ownerUid; + private final SourceIdentity sourceIdentity = + new SourceIdentity( + "prod", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "55555555-5555-4555-8555-555555555555", + "account-api-r1", + "https://kubernetes.example.test:6443", + "9".repeat(64)); + + private ProjectionFixture(String bytes) throws Exception { + Files.createDirectories(projection); + Files.createDirectory(dataDirectory); + Files.writeString(dataDirectory.resolve("jwks.json"), bytes, StandardCharsets.US_ASCII); + ownerUid = ((Number) Files.getAttribute(projection, "unix:uid")).longValue(); + } + + private void createProjection( + Set rootMode, + Set dataMode, + Set fileMode) + throws Exception { + Files.setPosixFilePermissions(projection, rootMode); + Files.setPosixFilePermissions(dataDirectory, dataMode); + Files.setPosixFilePermissions(dataDirectory.resolve("jwks.json"), fileMode); + Path dataLink = projection.resolve("..data"); + if (Files.exists(dataLink, java.nio.file.LinkOption.NOFOLLOW_LINKS)) { + Files.delete(dataLink); + } + Files.createSymbolicLink(dataLink, dataDirectory.getFileName()); + if (Files.exists(jwksPath, java.nio.file.LinkOption.NOFOLLOW_LINKS)) { + Files.delete(jwksPath); + } + Files.createSymbolicLink(jwksPath, Path.of("..data/jwks.json")); + } + + private LocalObservation observation(String digest) { + var identity = + ReadinessReceiverLocalIdentity.newBuilder() + .setAccountJwksSourceIdentity( + AccountSourceIdentity.newBuilder() + .setEnvironmentId(sourceIdentity.environmentId()) + .setClusterId(sourceIdentity.clusterId()) + .setClusterIncarnationUid(sourceIdentity.clusterIncarnationUid()) + .setNamespace(sourceIdentity.namespace()) + .setNamespaceUid(sourceIdentity.namespaceUid()) + .setConfigMapUid(sourceIdentity.configMapUid()) + .setBindingRevision(sourceIdentity.bindingRevision()) + .setApiServerOrigin(sourceIdentity.apiServerOrigin()) + .setServingCaSha256(sourceIdentity.servingCaSha256())) + .setAccountJwksTrustBindingRevision(sourceIdentity.bindingRevision()) + .setAccountPublicJwksSha256(digest) + .build(); + return new LocalObservation(identity, sourceIdentity); + } + + private GameSessionJwtReadinessProtectedJwksSource source(LocalObservation... observations) { + var identityProvider = mock(GameSessionJwtReadinessLocalIdentityProvider.class); + AtomicInteger index = new AtomicInteger(); + when(identityProvider.observe()) + .thenAnswer( + ignored -> observations[Math.min(index.getAndIncrement(), observations.length - 1)]); + return new GameSessionJwtReadinessProtectedJwksSource(identityProvider, jwksPath, ownerUid); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProviderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProviderTest.java new file mode 100644 index 0000000000..b64d2cb9bb --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProviderTest.java @@ -0,0 +1,383 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.util.Collections; +import java.util.HexFormat; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AccountSourceIdentity; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataRequest; +import net.firedevops.firemud.account.v1.GetCurrentReadinessReceiverMetadataResponse; +import net.firedevops.firemud.account.v1.ReadinessReceiverLocalIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.boot.ssl.SslStoreBundle; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionJwtReadinessProtectedLocalIdentityProviderTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String SERVICE_URI = + "spiffe://firemud/ns/firemud-prod/sa/game-session-service"; + private static final String POD_UID = "44444444-4444-4444-8444-444444444444"; + private static final String OTHER_POD_UID = "55555555-5555-4555-8555-555555555555"; + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2030-06-01T00:10:00Z"), ZoneId.of("UTC")); + + @Test + void returnsAccountSelectedCurrentMetadataBracketingTheAuthenticatedReadWithLocalPins() + throws Exception { + Fixture fixture = new Fixture(); + AtomicInteger uidReads = new AtomicInteger(); + var provider = + fixture.provider( + () -> { + uidReads.incrementAndGet(); + return POD_UID; + }); + + var observation = provider.observe(); + + assertThat(observation.wireIdentity()).isEqualTo(fixture.identity); + assertThat(observation.jwksSourceIdentity()).isEqualTo(fixture.sourceIdentity); + assertThat(observation.wireIdentity().getPodUid()).isEqualTo(POD_UID); + ArgumentCaptor request = + ArgumentCaptor.forClass(GetCurrentReadinessReceiverMetadataRequest.class); + verify(fixture.metadataReadPort).readCurrent(request.capture()); + assertThat(request.getValue().getSchemaVersion()).isEqualTo(1); + assertThat(request.getValue().getProjectedPodUid()).isEqualTo(POD_UID); + assertThat(request.getValue().getServerLeafSpkiSha256()).isEqualTo(fixture.leafDigest); + assertThat(request.getValue().getUnknownFields().asMap()).isEmpty(); + assertThat(uidReads.get()).isEqualTo(2); + } + + @Test + void deniesWhenProjectedPodUidChangesAroundCurrentMetadataRead() throws Exception { + Fixture fixture = new Fixture(); + AtomicInteger reads = new AtomicInteger(); + var provider = fixture.provider(() -> reads.getAndIncrement() == 0 ? POD_UID : OTHER_POD_UID); + + assertUnavailable(provider); + assertThat(reads.get()).isEqualTo(2); + } + + @Test + void deniesWhenActiveTlsLeafChangesAroundCurrentMetadataRead() throws Exception { + Fixture fixture = new Fixture(); + fixture.useDifferentSecondLeaf(); + var provider = fixture.provider(() -> POD_UID); + + assertUnavailable(provider); + } + + @Test + void deniesMissingProtectedUidWithoutCallingAccount() throws Exception { + Fixture fixture = new Fixture(); + var provider = fixture.provider(() -> null); + + assertUnavailable(provider); + verify(fixture.metadataReadPort, never()).readCurrent(any()); + } + + @Test + void deniesUnavailableAccountMetadataTransport() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.metadataReadPort.readCurrent(any())) + .thenThrow(new GameSessionJwtReadinessProbeOwnerClient.OwnerReadUnavailableException()); + var provider = fixture.provider(() -> POD_UID); + + assertUnavailable(provider); + } + + @Test + void deniesObservationInsideAmbientSqlTransactionBeforeMetadataRead() throws Exception { + Fixture fixture = new Fixture(); + var provider = fixture.provider(() -> POD_UID); + boolean previousTransactionState = + TransactionSynchronizationManager.isActualTransactionActive(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertUnavailable(provider); + verify(fixture.metadataReadPort, never()).readCurrent(any()); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(previousTransactionState); + } + } + + @Test + void deniesNonGameSessionLocalTlsPeerBeforeAccountRead() throws Exception { + Fixture fixture = new Fixture(); + fixture.useCertificateWithUri("spiffe://firemud/ns/firemud-prod/sa/game-design-service"); + var provider = fixture.provider(() -> POD_UID); + + assertUnavailable(provider); + verify(fixture.metadataReadPort, never()).readCurrent(any()); + } + + @Test + void rejectsWrongUidLeafValidatorSourceNamespaceRevisionAndPublicJwksHash() throws Exception { + Fixture fixture = new Fixture(); + List rejectedResponses = + List.of( + fixture.response(fixture.identity.toBuilder().setPodUid(OTHER_POD_UID).build()), + fixture.response( + fixture.identity.toBuilder().setServerLeafSpkiSha256("f".repeat(64)).build()), + fixture.response( + fixture.identity.toBuilder().setValidatorId("account-service").build()), + fixture.response( + fixture.identity.toBuilder() + .setCanonicalServiceUri("spiffe://firemud/ns/other-ns/sa/game-session-service") + .build()), + fixture.response( + fixture.identity.toBuilder() + .setAccountJwksSourceIdentity( + fixture.sourceProto.toBuilder().setNamespace("other-ns").build()) + .build()), + fixture.response( + fixture.identity.toBuilder() + .setAccountJwksSourceIdentity( + fixture.sourceProto.toBuilder().setConfigMapUid("invalid").build()) + .build()), + fixture.response(fixture.identity.toBuilder().clearAccountJwksSourceIdentity().build()), + fixture.response( + fixture.identity.toBuilder() + .setAccountJwksTrustBindingRevision("changed-revision") + .build()), + fixture.response( + fixture.identity.toBuilder().setAccountPublicJwksSha256("z".repeat(64)).build())); + + for (GetCurrentReadinessReceiverMetadataResponse rejected : rejectedResponses) { + when(fixture.metadataReadPort.readCurrent(any())).thenReturn(rejected); + assertUnavailable(fixture.provider(() -> POD_UID)); + } + } + + @Test + void rejectsInvalidTargetShapeAndPreservesCanonicalIpv6PodEndpoints() throws Exception { + Fixture fixture = new Fixture(); + List rejectedIdentities = + List.of( + fixture.identity.toBuilder().setDeploymentUid("deployment").build(), + fixture.identity.toBuilder().setImage("registry.example/game-session:latest").build(), + fixture.identity.toBuilder().setSourceInventoryRevision(" ").build(), + fixture.identity.toBuilder().setSourceInventoryRevision("r".repeat(129)).build(), + fixture.identity.toBuilder().setPodIp("10.0.0.13").build(), + fixture.identity.toBuilder().setDirectPodEndpoint("https://10.0.0.12:6565").build(), + fixture.identity.toBuilder().setDirectPodEndpoint("grpcs://10.0.0.12:06565").build(), + fixture.identity.toBuilder() + .setDirectPodEndpoint("grpcs://user@10.0.0.12:6565") + .build(), + fixture.identity.toBuilder() + .setDirectPodEndpoint("grpcs://10.0.0.12:6565?route=other") + .build(), + fixture.identity.toBuilder() + .setDirectPodEndpoint("grpcs://10.0.0.12:6565/path") + .build(), + fixture.identity.toBuilder().setPodIp("010.0.0.12").build()); + + for (ReadinessReceiverLocalIdentity rejected : rejectedIdentities) { + when(fixture.metadataReadPort.readCurrent(any())).thenReturn(fixture.response(rejected)); + assertUnavailable(fixture.provider(() -> POD_UID)); + } + + ReadinessReceiverLocalIdentity ipv6Identity = + fixture.identity.toBuilder() + .setPodIp("2001:db8::12") + .setDirectPodEndpoint("grpcs://[2001:db8::12]:6565") + .build(); + when(fixture.metadataReadPort.readCurrent(any())).thenReturn(fixture.response(ipv6Identity)); + + assertThat(fixture.provider(() -> POD_UID).observe().wireIdentity()).isEqualTo(ipv6Identity); + } + + @Test + void rejectsUnknownFieldsAndMalformedCurrentOperationMetadata() throws Exception { + Fixture fixture = new Fixture(); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + List rejectedResponses = + List.of( + fixture.response(fixture.identity, response -> response.setUnknownFields(unknown)), + fixture.response(fixture.identity.toBuilder().setUnknownFields(unknown).build()), + fixture.response( + fixture.identity.toBuilder() + .setAccountJwksSourceIdentity( + fixture.sourceProto.toBuilder().setUnknownFields(unknown).build()) + .build()), + fixture.response(fixture.identity, response -> response.setRotationOperationId("1")), + fixture.response( + fixture.identity, + response -> + response.setRotationOperationId("11111111-1111-1111-8111-111111111111")), + fixture.response( + fixture.identity, response -> response.setOperationDigest("A".repeat(64))), + fixture.response(fixture.identity, response -> response.setPlanDigest("not-a-digest")), + fixture.response(fixture.identity, response -> response.setSchemaVersion(2))); + + for (GetCurrentReadinessReceiverMetadataResponse rejected : rejectedResponses) { + when(fixture.metadataReadPort.readCurrent(any())).thenReturn(rejected); + assertUnavailable(fixture.provider(() -> POD_UID)); + } + } + + private static void assertUnavailable( + GameSessionJwtReadinessProtectedLocalIdentityProvider provider) { + assertThatThrownBy(provider::observe) + .isInstanceOf( + GameSessionJwtReadinessProtectedLocalIdentityProvider.IdentityUnavailableException + .class); + } + + private static final class Fixture { + private final byte[] encodedPublicKey = + "game-session server public key".getBytes(java.nio.charset.StandardCharsets.US_ASCII); + private final String leafDigest = sha256(encodedPublicKey); + private final String publicJwksDigest = + sha256( + "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"fixture\"}]}" + .getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + private final GameSessionJwtReadinessReceiverMetadataReadPort metadataReadPort = + mock(GameSessionJwtReadinessReceiverMetadataReadPort.class); + private final SslBundles sslBundles = mock(SslBundles.class); + private final KeyStore keyStore = mock(KeyStore.class); + private final X509Certificate certificate = certificate(SERVICE_URI, encodedPublicKey); + private final AccountSourceIdentity sourceProto = sourceProto(); + private final SourceIdentity sourceIdentity = sourceIdentity(sourceProto); + private final ReadinessReceiverLocalIdentity identity = identity(); + + private Fixture() throws Exception { + when(keyStore.aliases()) + .thenAnswer(ignored -> Collections.enumeration(List.of("game-session"))); + when(keyStore.isKeyEntry("game-session")).thenReturn(true); + when(keyStore.getCertificate("game-session")).thenReturn(certificate); + SslStoreBundle stores = mock(SslStoreBundle.class); + when(stores.getKeyStore()).thenReturn(keyStore); + SslBundle bundle = mock(SslBundle.class); + when(bundle.getStores()).thenReturn(stores); + when(sslBundles.getBundle("firemud-grpc")).thenReturn(bundle); + when(metadataReadPort.readCurrent(any())).thenReturn(response(identity)); + } + + private GameSessionJwtReadinessProtectedLocalIdentityProvider provider( + Supplier projectedUidSource) { + return new GameSessionJwtReadinessProtectedLocalIdentityProvider( + metadataReadPort, sslBundles, NAMESPACE, CLOCK, projectedUidSource); + } + + private void useDifferentSecondLeaf() throws Exception { + X509Certificate secondCertificate = + certificate( + SERVICE_URI, + "different server public key".getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + when(keyStore.getCertificate("game-session")).thenReturn(certificate, secondCertificate); + } + + private void useCertificateWithUri(String uri) throws Exception { + X509Certificate replacement = certificate(uri, encodedPublicKey); + when(keyStore.getCertificate("game-session")).thenReturn(replacement); + } + + private ReadinessReceiverLocalIdentity identity() { + return ReadinessReceiverLocalIdentity.newBuilder() + .setValidatorId("game-session-service") + .setDeploymentUid("33333333-3333-4333-8333-333333333333") + .setPodUid(POD_UID) + .setPodIp("10.0.0.12") + .setDirectPodEndpoint("grpcs://10.0.0.12:6565") + .setCanonicalServiceUri(SERVICE_URI) + .setImage("registry.example/game-session@sha256:" + "a".repeat(64)) + .setVerifierConfigSha256("b".repeat(64)) + .setApplicabilityMatrixDigest("c".repeat(64)) + .setSourceInventoryRevision("inventory-r1") + .setSourceInventoryDigest("d".repeat(64)) + .setServerLeafSpkiSha256(leafDigest) + .setAccountJwksSourceIdentity(sourceProto) + .setAccountJwksTrustBindingRevision(sourceIdentity.bindingRevision()) + .setAccountPublicJwksSha256(publicJwksDigest) + .build(); + } + + private GetCurrentReadinessReceiverMetadataResponse response( + ReadinessReceiverLocalIdentity value) { + return response(value, ignored -> {}); + } + + private GetCurrentReadinessReceiverMetadataResponse response( + ReadinessReceiverLocalIdentity value, + java.util.function.Consumer change) { + var builder = + GetCurrentReadinessReceiverMetadataResponse.newBuilder() + .setSchemaVersion(1) + .setRotationOperationId("66666666-6666-4666-8666-666666666666") + .setOperationDigest("e".repeat(64)) + .setPlanDigest("f".repeat(64)) + .setCurrentIdentity(value); + change.accept(builder); + return builder.build(); + } + + private AccountSourceIdentity sourceProto() { + return AccountSourceIdentity.newBuilder() + .setEnvironmentId("prod") + .setClusterId("cluster-a") + .setClusterIncarnationUid("11111111-1111-4111-8111-111111111111") + .setNamespace(NAMESPACE) + .setNamespaceUid("22222222-2222-4222-8222-222222222222") + .setConfigMapUid("55555555-5555-4555-8555-555555555555") + .setBindingRevision("account-api-r1") + .setApiServerOrigin("https://kubernetes.example.test:6443") + .setServingCaSha256("9".repeat(64)) + .build(); + } + + private static SourceIdentity sourceIdentity(AccountSourceIdentity source) { + return new SourceIdentity( + source.getEnvironmentId(), + source.getClusterId(), + source.getClusterIncarnationUid(), + source.getNamespace(), + source.getNamespaceUid(), + source.getConfigMapUid(), + source.getBindingRevision(), + source.getApiServerOrigin(), + source.getServingCaSha256()); + } + } + + private static X509Certificate certificate(String uri, byte[] encodedPublicKey) throws Exception { + X509Certificate certificate = mock(X509Certificate.class); + PublicKey publicKey = mock(PublicKey.class); + when(certificate.getPublicKey()).thenReturn(publicKey); + when(publicKey.getEncoded()).thenReturn(encodedPublicKey); + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, uri))); + return certificate; + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (Exception unavailable) { + throw new AssertionError(unavailable); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngineTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngineTest.java index 15e24471b4..25740def1c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngineTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverEngineTest.java @@ -234,10 +234,24 @@ private static ReadinessReceiverLocalIdentity wireIdentity() { .setBindingRevision("account-api-r1") .setApiServerOrigin("https://kubernetes.example.test:6443") .setServingCaSha256("9".repeat(64))) - .setAccountJwksTrustConfigRevision(1L) + .setAccountJwksTrustBindingRevision("account-api-r1") + .setAccountPublicJwksSha256(fixturePublicJwksSha256()) .build(); } + private static String fixturePublicJwksSha256() { + try { + return java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest( + "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"fixture\"}]}" + .getBytes(java.nio.charset.StandardCharsets.US_ASCII))); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new AssertionError(unavailable); + } + } + private static AccountPublicJwksCache.SourceIdentity sourceIdentity() { return new AccountPublicJwksCache.SourceIdentity( "prod", From 155408b5c9c8faa7f4a842423053858703e7d065 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 04:49:35 +1300 Subject: [PATCH 019/129] Serialize hosted terms disclosure with original Draft commit ordering --- ...ame-authoring-publishing-and-activation.md | 2 +- .../DraftAuthorizationFenceRepository.java | 51 +++- ...ostedTermsDisclosureHandoffRepository.java | 10 +- ...orizationFencePostgresIntegrationTest.java | 11 + ...untHostedTermsPostgresIntegrationTest.java | 8 +- ...closureHandoffPostgresIntegrationTest.java | 289 ++++++++++++++++++ ...ronmentBindingPostgresIntegrationTest.java | 10 +- 7 files changed, 357 insertions(+), 24 deletions(-) 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 88a19fe496..1a477ff8ed 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 @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a The current Gameplay-prerequisite construction remains non-activating. Full-version finalization now reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. The real backend control-ui issuance/current-actor source, complete Account source-writer fencing and callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Earlier construction CI executed all four Account source-composition, five environment-binding and 31 Draft authorization PostgreSQL cases successfully, while three Game Design canonical-release fixtures failed for missing policy source capture. Their receiving correction now freezes actual Game Design command/policy source snapshots before sealing; corrected physical execution remains required. These bounded changes do not upgrade the broader capability ratings below. -The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. At `ed928219ee3428073910f1845eaa975e8814a30a`, local validation is complete for the held-order/source-fencing batch, but physical PostgreSQL validation was skipped. The Account-owned disclosure journal now defines an immutable request, predecessor/candidate, effective instant, exact source vector and opaque authority binding, with exact dispatch/ambiguity/result readback. Its non-revoking preparation check refuses already-reserved or unsettled original operations under sorted source locks. This is only a storage foundation: handoff-aware capture/reserve/claim, both publication paths including environment binding, authenticated notice production/readback and the physical World deadline gate remain unimplemented or unproved. In particular, preparation-first serialization is not closed while later capture and ordering do not consult the journal; there is no production disclosure/currentness path. Reconsider only after focused PostgreSQL proof covers both orderings of preparation versus original `COMMIT_ORDER` acquisition and settlement, every deadline-introduction path including environment binding, exact retry/restart/ambiguous-notice readback, and World commit-time denial at the disclosed instant without early ordinary-authoring freeze or date rewriting. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. +The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. At `ed928219ee3428073910f1845eaa975e8814a30a`, local validation is complete for the held-order/source-fencing batch, but physical PostgreSQL validation was skipped. The Account-owned disclosure journal now defines an immutable request, predecessor/candidate, effective instant, exact source vector and opaque authority binding, with exact dispatch/ambiguity/result readback. Its non-revoking preparation check refuses already-reserved or unsettled original operations under sorted source locks. The journal now serializes dispatch authorization and original reserve/claim under the same sorted source locks. PREPARED alone permits ordinary original acquisition; first dispatch rechecks exact settlement, while authorized, ambiguous or disclosed handoffs deny a new no-deadline order only for their exact changed terms source evidence. Existing original retries and obsolete source history do not acquire new authority or blanket-block unrelated sources. Focused both-ordering and concurrency proof definitions are present, but physical PostgreSQL execution remains required. This is still a bounded storage/ordering foundation: complete capture/currentness integration, both catalog and environment publication paths, authenticated notice production/readback and the physical World deadline gate remain unimplemented or unproved; there is no production disclosure/currentness path. Reconsider only after focused PostgreSQL proof covers both orderings of preparation versus original `COMMIT_ORDER` acquisition and settlement, every deadline-introduction path including environment binding, exact retry/restart/ambiguous-notice readback, and World commit-time denial at the disclosed instant without early ordinary-authoring freeze or date rewriting. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. Creator issuance preserves the existing OTP failure budget by committing a primary-authentication denial's accounting before returning the credential error; successful OTP consumption still rolls back if subsequent preparation fails. Its real PostgreSQL definitions use the primary hook's Spring transaction interceptor, not only a direct method call. The construction includes a selective Account per-Pod readiness/receipt closure and commit-bound signer coordinator, together with a default-inactive Game Session receiver using production cryptographic profile validation and exact Account owner readback. Six loopback mTLS cases executed without skips through the real Game Session verifier and owner-read client; their Account owner responses, protected local identity and public JWKS remain test fixtures. These sources do not establish a production signer: protected input delivery, deployed isolated routing, current inventory and mounted correspondence, corrected PostgreSQL proof, and live convergence/promotion remain open. The current inventory rejects shared receiver-Pod leaf-key pins, while the base Deployment uses the accepted workload-level certificate delivery. Unique replica SPKI is a code-selected strengthening, not an ADR 0038 prerequisite; the approved alternative is described below but remains unproved. A complete claim without protected per-validator evidence remains quarantined; synthetic signer fixtures cannot close the original APPLIED/release prerequisite. Password and wrong-secret PostgreSQL proof is separate from restricted-account authentication: the latter has unit coverage, while an authentic owner lifecycle transition needed for its physical fixture remains unavailable. The broader JWT capability remains owned by [Shared Runtime Contracts](./shared-runtime-contracts-and-persistence.md). diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 9d294e4479..400876ec77 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -186,6 +186,7 @@ public FenceSnapshot reserve(DraftAuthorizationFenceBinding binding) { if (hasWaitingChange(binding.sources())) { throw new IllegalStateException("Applicable authority source change is waiting"); } + requireNoAuthorizedDisclosure(binding.sources()); dsl.execute( "INSERT INTO " + FENCES @@ -222,6 +223,7 @@ public FenceSnapshot claimCommitOrder(DraftAuthorizationFenceBinding binding) { if (ordering == Ordering.REVOKE_ORDER || hasWaitingChange(binding.sources())) { throw new IllegalStateException("Revocation precedes this owner commit"); } + requireNoAuthorizedDisclosure(binding.sources()); dsl.execute( "UPDATE " + FENCES @@ -242,6 +244,27 @@ public FenceSnapshot claimCommitOrder(DraftAuthorizationFenceBinding binding) { * paths. No lock obtained here may be held across an RPC. */ public void requireDisclosurePreparation(List exactSources) { + lockDisclosureSources(exactSources); + List sources = List.copyOf(exactSources); + if (hasWaitingChange(sources)) { + throw new IllegalStateException("Applicable Account source change is unresolved"); + } + for (UUID operationId : affectedOperations(sources)) { + Record row = readOperation(operationId); + if (row == null) { + throw new IllegalStateException("Affected original Draft operation disappeared"); + } + DraftAuthorizationFenceBinding original = originalBinding(row); + Ordering ordering = Ordering.valueOf(row.get("ordering", String.class)); + if (ordering == Ordering.RESERVED || settlement(original, ordering) == Settlement.PENDING) { + throw new IllegalStateException( + "Disclosure deadline cannot pass an unsettled original Draft operation"); + } + } + } + + /** Locks the complete sorted vector before any disclosure journal or operation row lock. */ + public void lockDisclosureSources(List exactSources) { requireTransaction(); List sources = List.copyOf(Objects.requireNonNull(exactSources, "exact disclosure sources")).stream() @@ -258,19 +281,21 @@ public void requireDisclosurePreparation(List exactSources) { } } lockSources(sources); - if (hasWaitingChange(sources)) { - throw new IllegalStateException("Applicable Account source change is unresolved"); - } - for (UUID operationId : affectedOperations(sources)) { - Record row = readOperation(operationId); - if (row == null) { - throw new IllegalStateException("Affected original Draft operation disappeared"); - } - DraftAuthorizationFenceBinding original = originalBinding(row); - Ordering ordering = Ordering.valueOf(row.get("ordering", String.class)); - if (ordering == Ordering.RESERVED || settlement(original, ordering) == Settlement.PENDING) { - throw new IllegalStateException( - "Disclosure deadline cannot pass an unsettled original Draft operation"); + } + + private void requireNoAuthorizedDisclosure(List sources) { + for (SourceEvidence source : sources) { + if (source.kind() == SourceKind.HOSTED_TERMS + && !dsl.fetch( + "SELECT 1 FROM account_hosted_terms_disclosure_handoffs h " + + "JOIN account_hosted_terms_disclosure_sources s ON s.handoff_id = h.handoff_id " + + "WHERE h.source_key = ? AND s.source_key = h.source_key " + + "AND s.source_evidence = ? " + + "AND h.status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS', 'DISCLOSED')", + source.key(), + source.canonicalBytes()) + .isEmpty()) { + throw new IllegalStateException("Exact hosted terms source has authorized disclosure"); } } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java index 294d70911f..fbff4669c8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java @@ -88,6 +88,7 @@ public Snapshot prepare(HostedTermsDisclosureHandoff handoff) { requireWriteTransaction(); Objects.requireNonNull(handoff); byte[] exactBinding = handoff.canonicalBytes(); + fenceRepository.lockDisclosureSources(handoff.sources()); Record existing = findByIdentity(handoff.handoffId(), handoff.requestId()); if (existing != null) { return exactSnapshot(existing, handoff, exactBinding); @@ -142,14 +143,19 @@ public Snapshot prepare(HostedTermsDisclosureHandoff handoff) { * Durably authorizes one dispatch before the caller leaves the transaction. A pre-existing * DISPATCH_AUTHORIZED row is recovered by readback, not by guessing that a previous RPC failed. * An exact retry after explicit ambiguity may reauthorize the same stable request identity; the - * external receiver must deduplicate it. + * external receiver must deduplicate it. Sorted source locks precede journal and operation locks; + * a prepared handoff rechecks original settlement before its first dispatch authorization. */ public DispatchPermit authorizeDispatch(HostedTermsDisclosureHandoff handoff) { requireWriteTransaction(); Objects.requireNonNull(handoff); + fenceRepository.lockDisclosureSources(handoff.sources()); Record row = requireExactRow(handoff); Status status = Status.valueOf(row.get("status", String.class)); boolean newlyAuthorized = false; + if (status == Status.PREPARED) { + fenceRepository.requireDisclosurePreparation(handoff.sources()); + } if (status == Status.PREPARED || status == Status.AMBIGUOUS) { int updated = dsl.execute( @@ -172,6 +178,7 @@ public DispatchPermit authorizeDispatch(HostedTermsDisclosureHandoff handoff) { public Snapshot recordAmbiguous(HostedTermsDisclosureHandoff handoff) { requireWriteTransaction(); Objects.requireNonNull(handoff); + fenceRepository.lockDisclosureSources(handoff.sources()); Record row = requireExactRow(handoff); Status status = Status.valueOf(row.get("status", String.class)); if (status == Status.DISPATCH_AUTHORIZED) { @@ -200,6 +207,7 @@ public Snapshot recordResult(HostedTermsDisclosureHandoff handoff, DisclosureRes requireWriteTransaction(); Objects.requireNonNull(handoff); Objects.requireNonNull(result); + fenceRepository.lockDisclosureSources(handoff.sources()); Record row = requireExactRow(handoff); byte[] resultBytes = result.canonicalBytes(); String resultDigest = HostedTermsEncoding.digest(resultBytes); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java index 1a2a645c0a..3352055270 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -1413,6 +1413,8 @@ void v2MixedResultsHoldBothSourceTransitionsAndPreserveAppliedBytes() { @Test void forwardMigrationRetainsV1BindingReadbackAndFlywayChecksumsExactly() { + // Seed the retained V92 row with an ACCOUNT-only source vector, then advance through V93 + // explicitly before using the current runtime repository against this historical fixture. Context context = context("92"); DraftAuthorizationFenceBinding base = binding(context); SourceEvidence legacy512 = @@ -1450,6 +1452,15 @@ void forwardMigrationRetainsV1BindingReadbackAndFlywayChecksumsExactly() { .fetch( "SELECT version, checksum FROM flyway_schema_history WHERE version IS DISTINCT FROM '93' ORDER BY installed_rank")) .isEqualTo(checksums); + Flyway.configure() + .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("latest") + .load() + .migrate(); assertThat( Objects.requireNonNull( context diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java index 8365fc14e4..dc55944233 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java @@ -104,7 +104,7 @@ void migrationRetainsExistingPartyAndBackfillsNoCatalogOrAcceptance() throws Exc @Test void realServicePublishesAffirmativelyAcceptsReadsBackAndAdvancesMateriality() throws Exception { - Database db = database("96"); + Database db = database("latest"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -251,7 +251,7 @@ void realServicePublishesAffirmativelyAcceptsReadsBackAndAdvancesMateriality() t @Test void acceptanceRejectsWrongSignerNegativeActionChangedShownTermsAndUnavailableIdentity() throws Exception { - Database db = database("96"); + Database db = database("latest"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -318,7 +318,7 @@ void acceptanceRejectsWrongSignerNegativeActionChangedShownTermsAndUnavailableId @Test void futureTermsCarryDeadlineWithoutFreezingPriorTermsEarly() throws Exception { - Database db = database("96"); + Database db = database("latest"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -482,7 +482,7 @@ private static void awaitLatch(CountDownLatch latch, String message) { @Test void ownerTransactionRollbackRemovesUncommittedCatalogAndPublicationIntent() throws Exception { - Database db = database("96"); + Database db = database("latest"); HostedTermsRepository repository = new HostedTermsRepository(db.dsl()); UUID scopeId = UUID.randomUUID(); UUID requestId = UUID.randomUUID(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java index e0cbca61bf..0e7ec62081 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java @@ -9,7 +9,14 @@ import java.time.Instant; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff; @@ -246,6 +253,288 @@ void preparationRefusesReservedAndUnsettledCommitOrderWithoutRewritingEither() t .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER); } + @Test + void preparedHandoffAllowsOriginalOrderingButDispatchWaitsForExactSettlement() throws Exception { + Database database = database(); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(database.dsl()); + HostedTermsDisclosureHandoffRepository journal = + new HostedTermsDisclosureHandoffRepository(database.dsl(), fences); + SourceEvidence source = source("prepare-first"); + HostedTermsDisclosureHandoff handoff = handoff(source); + DraftAuthorizationFenceBinding original = draftBinding(source); + + tx(database, () -> journal.prepare(handoff)); + tx(database, () -> fences.reserve(original)); + assertDispatchUnsettled(database, journal, handoff); + tx(database, () -> fences.claimCommitOrder(original)); + assertDispatchUnsettled(database, journal, handoff); + tx( + database, + () -> { + recordOwnerResult(fences, original, Owner.GAME_DESIGN); + return null; + }); + assertDispatchUnsettled(database, journal, handoff); + tx( + database, + () -> { + recordOwnerResult(fences, original, Owner.WORLD); + return null; + }); + assertThat(tx(database, () -> journal.authorizeDispatch(handoff)).newlyAuthorized()).isTrue(); + assertThat(tx(database, () -> fences.reserve(original)).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER); + assertThat(tx(database, () -> fences.claimCommitOrder(original)).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER); + assertDisclosureBlocked(database, fences, draftBinding(source)); + } + + @Test + void dispatchGuardUsesOnlyExactChangedTermsEvidenceAndDefinitiveNegativeReleasesIt() + throws Exception { + Database database = database(); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(database.dsl()); + HostedTermsDisclosureHandoffRepository journal = + new HostedTermsDisclosureHandoffRepository(database.dsl(), fences); + SourceEvidence changed = source("exact-changed-source"); + SourceEvidence unrelated = source("unrelated-terms-source"); + SourceEvidence account = + new SourceEvidence( + SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + null, + null, + "test-only-account-evidence".getBytes(StandardCharsets.UTF_8)); + HostedTermsDisclosureHandoff original = handoff(changed); + HostedTermsDisclosureHandoff handoff = + new HostedTermsDisclosureHandoff( + original.handoffId(), + original.requestId(), + original.kind(), + original.sourceKey(), + original.predecessorDigest(), + original.candidateDigest(), + original.effectiveAt(), + List.of(changed, unrelated, account), + original.authenticatedAuthorityEvidence()); + tx(database, () -> journal.prepare(handoff)); + tx(database, () -> journal.authorizeDispatch(handoff)); + assertDisclosureBlocked(database, fences, draftBinding(changed)); + // Other vector members and newer source bytes cannot inherit the changed source's guard. + tx(database, () -> fences.reserve(draftBinding(unrelated))); + tx(database, () -> fences.reserve(draftBinding(account))); + SourceEvidence newer = + new SourceEvidence( + changed.kind(), + changed.scopeId(), + changed.generation(), + "8", + null, + null, + "test-only-newer-terms-evidence".getBytes(StandardCharsets.UTF_8)); + DraftAuthorizationFenceBinding newerOriginal = draftBinding(newer); + tx(database, () -> fences.reserve(newerOriginal)); + tx(database, () -> fences.claimCommitOrder(newerOriginal)); + tx(database, () -> journal.recordAmbiguous(handoff)); + assertDisclosureBlocked(database, fences, draftBinding(changed)); + assertThat(tx(database, () -> journal.authorizeDispatch(handoff)).newlyAuthorized()).isTrue(); + tx( + database, + () -> + journal.recordResult( + handoff, + new DisclosureResult( + handoff.handoffId(), + handoff.requestId(), + HostedTermsEncoding.digest(handoff.canonicalBytes()), + Outcome.DEFINITIVELY_NOT_DISCLOSED, + "test-only-definitive-negative".getBytes(StandardCharsets.UTF_8)))); + DraftAuthorizationFenceBinding afterNegative = draftBinding(changed); + tx(database, () -> fences.reserve(afterNegative)); + tx(database, () -> fences.claimCommitOrder(afterNegative)); + + SourceEvidence disclosedSource = source("disclosed-guard"); + HostedTermsDisclosureHandoff disclosed = handoff(disclosedSource); + tx(database, () -> journal.prepare(disclosed)); + tx(database, () -> journal.authorizeDispatch(disclosed)); + tx( + database, + () -> + journal.recordResult( + disclosed, + new DisclosureResult( + disclosed.handoffId(), + disclosed.requestId(), + HostedTermsEncoding.digest(disclosed.canonicalBytes()), + Outcome.DISCLOSED, + "test-only-disclosed-result".getBytes(StandardCharsets.UTF_8)))); + assertDisclosureBlocked(database, fences, draftBinding(disclosedSource)); + SourceEvidence differentBytes = + new SourceEvidence( + disclosedSource.kind(), + disclosedSource.scopeId(), + disclosedSource.generation(), + disclosedSource.sourceVersion(), + null, + null, + "test-only-different-source-bytes".getBytes(StandardCharsets.UTF_8)); + tx(database, () -> fences.reserve(draftBinding(differentBytes))); + SourceEvidence newerDisclosed = + new SourceEvidence( + disclosedSource.kind(), + disclosedSource.scopeId(), + disclosedSource.generation(), + "8", + null, + null, + "test-only-new-version".getBytes(StandardCharsets.UTF_8)); + tx(database, () -> fences.reserve(draftBinding(newerDisclosed))); + } + + @Test + void sourceLocksSerializeConcurrentOriginalAcquisitionBeforeDispatch() throws Exception { + concurrentAcquisitionAndDispatch(false); + } + + @Test + void sourceLocksSerializeConcurrentDispatchBeforeOriginalAcquisition() throws Exception { + concurrentAcquisitionAndDispatch(true); + } + + private static void concurrentAcquisitionAndDispatch(boolean dispatchFirst) throws Exception { + Database database = database(); + DraftAuthorizationFenceRepository fences = + new DraftAuthorizationFenceRepository(database.dsl()); + HostedTermsDisclosureHandoffRepository journal = + new HostedTermsDisclosureHandoffRepository(database.dsl(), fences); + SourceEvidence source = source("concurrent-" + dispatchFirst); + HostedTermsDisclosureHandoff handoff = handoff(source); + DraftAuthorizationFenceBinding original = draftBinding(source); + tx(database, () -> journal.prepare(handoff)); + CountDownLatch firstLocked = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + AtomicInteger firstPid = new AtomicInteger(); + AtomicInteger secondPid = new AtomicInteger(); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> + tx( + database, + () -> { + firstPid.set( + Objects.requireNonNull( + database.dsl().fetchOne("SELECT pg_backend_pid()"), + "Expected first transaction PostgreSQL backend PID row") + .get(0, Integer.class)); + if (dispatchFirst) { + journal.authorizeDispatch(handoff); + } else { + fences.reserve(original); + fences.claimCommitOrder(original); + } + firstLocked.countDown(); + await(releaseFirst); + return null; + })); + assertThat(firstLocked.await(10, TimeUnit.SECONDS)).isTrue(); + var second = + executor.submit( + () -> + tx( + database, + () -> { + secondPid.set( + Objects.requireNonNull( + database.dsl().fetchOne("SELECT pg_backend_pid()"), + "Expected second transaction PostgreSQL backend PID row") + .get(0, Integer.class)); + secondStarted.countDown(); + if (dispatchFirst) { + fences.reserve(original); + } else { + journal.authorizeDispatch(handoff); + } + return null; + })); + assertThat(secondStarted.await(10, TimeUnit.SECONDS)).isTrue(); + awaitBlocked(database, secondPid.get(), firstPid.get()); + assertThatThrownBy(() -> second.get(200, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + releaseFirst.countDown(); + first.get(10, TimeUnit.SECONDS); + assertThatThrownBy(() -> second.get(10, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class) + .hasRootCauseMessage( + dispatchFirst + ? "Exact hosted terms source has authorized disclosure" + : "Disclosure deadline cannot pass an unsettled original Draft operation"); + assertThat(tx(database, () -> journal.read(handoff.handoffId())).orElseThrow().status()) + .isEqualTo(dispatchFirst ? Status.DISPATCH_AUTHORIZED : Status.PREPARED); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + } + } + + private static void awaitBlocked(Database database, int waitingPid, int blockerPid) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + if (Boolean.TRUE.equals( + Objects.requireNonNull( + database + .dsl() + .fetchOne("SELECT ? = ANY(pg_blocking_pids(?))", blockerPid, waitingPid), + "Expected PostgreSQL blocking-state row") + .get(0, Boolean.class))) { + return; + } + Thread.sleep(10); + } + throw new IllegalStateException( + "Expected original and dispatch transactions to share source locks"); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for test transaction release"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted waiting for test transaction release", interrupted); + } + } + + private static void assertDispatchUnsettled( + Database database, + HostedTermsDisclosureHandoffRepository journal, + HostedTermsDisclosureHandoff handoff) { + assertThatThrownBy(() -> tx(database, () -> journal.authorizeDispatch(handoff))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unsettled original Draft operation"); + assertThat(tx(database, () -> journal.read(handoff.handoffId())).orElseThrow().status()) + .isEqualTo(Status.PREPARED); + } + + private static void assertDisclosureBlocked( + Database database, + DraftAuthorizationFenceRepository fences, + DraftAuthorizationFenceBinding binding) { + assertThatThrownBy(() -> tx(database, () -> fences.reserve(binding))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact hosted terms source has authorized disclosure"); + } + private static void recordOwnerResult( DraftAuthorizationFenceRepository fences, DraftAuthorizationFenceBinding binding, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java index 481401cd77..fd6d646e6a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java @@ -78,7 +78,7 @@ class HostedTermsEnvironmentBindingPostgresIntegrationTest { @Test void realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersions() throws Exception { - Database db = database("97"); + Database db = database("latest"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -271,7 +271,7 @@ void realAccountWorkflowBindsCurrentEnvironmentAndFencesIndependentSourceVersion @Test void bindingUpdateWaitsForExactTerminalSettlementOfAffectedDraftOperation() throws Exception { - Database db = database("97"); + Database db = database("latest"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -359,7 +359,7 @@ void bindingUpdateWaitsForExactTerminalSettlementOfAffectedDraftOperation() thro @Test void boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline() throws Exception { - Database db = database("97"); + Database db = database("latest"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -439,7 +439,7 @@ void boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline() throws @Test void capturedEnvironmentDoesNotExemptCurrentnessAfterScheduledDeadline() throws Exception { - Database db = database("97"); + Database db = database("latest"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); @@ -544,7 +544,7 @@ void capturedEnvironmentDoesNotExemptCurrentnessAfterScheduledDeadline() throws @Test void environmentBindingPublisherWaitsUntilCallerOwnedCurrentnessTransactionEnds() throws Exception { - Database db = database("97"); + Database db = database("latest"); UUID accountId = insertAccount(db); UUID partyId = UUID.randomUUID(); UUID scopeId = UUID.randomUUID(); From a64642435eef2ffb2f35408334667ec2dc6c4a57 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 05:00:01 +1300 Subject: [PATCH 020/129] Repair protected UID consumer fixtures and prepare native admission proof --- dev-tools/hosted/README.md | 1 + .../prove-protected-pod-boundary.sh | 230 ++++++++++++++++++ ...d-identity-controller-manifest-contract.sh | 107 ++++++++ .../protected-pod-live-proof-contract.sh | 163 +++++++++++++ 4 files changed, 501 insertions(+) create mode 100644 dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh create mode 100644 dev-tools/tests/protected-pod-live-proof-contract.sh diff --git a/dev-tools/hosted/README.md b/dev-tools/hosted/README.md index fa0d4d44a2..62bcaf318f 100644 --- a/dev-tools/hosted/README.md +++ b/dev-tools/hosted/README.md @@ -37,5 +37,6 @@ Use it before ad hoc live inspection so preview debugging stays deterministic an ## Public Helpers +- [trust-bootstrap/prove-protected-pod-boundary.sh](trust-bootstrap/prove-protected-pod-boundary.sh) – operator-invoked native admission proof: `bash dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh --context CONTEXT --namespace dev --pod EXACT_PROTECTED_POD` (also canonical `pr-N`). Requires Python/PyYAML and kubectl; verifies installed trusted policy content and compilation, then uses only server dry-run CREATE/UPDATE/ephemeral-container requests. This is partial admission evidence, not routing, replacement-race, shared-key closure or promotion proof; see [the attribution owner](../../design/architecture/system-architecture-jwt-and-token-contracts.md#protected-readiness-receiver-attribution). - [shared/show-rollout-diagnostics.sh](shared/show-rollout-diagnostics.sh) – first-look diagnostics for a hosted namespace when a rollout is blocked. - [shared/wait-for-hosted-runtime-rollouts.sh](shared/wait-for-hosted-runtime-rollouts.sh) – bounded readiness wait for the canonical hosted runtime deployment inventory. diff --git a/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh b/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh new file mode 100644 index 0000000000..c2a4f5a465 --- /dev/null +++ b/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh @@ -0,0 +1,230 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Operator-invoked live admission proof; every POST/PUT is server dry-run. +# No credentials, temporary RBAC, real Pods, or cluster cleanup are created. +repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../../.." && pwd)" +python3 - "$repo_root/k8s/trust-bootstrap/deployment-admission.yaml" "$@" <<'PY' +import argparse +import copy +import json +import re +import subprocess +import sys +import uuid + +import yaml + + +def fail(message): + raise SystemExit("protected-Pod admission proof failed: " + message) + + +parser = argparse.ArgumentParser(description="Live native Pod admission proof using dryRun=All only") +parser.add_argument("--context", required=True) +parser.add_argument("--namespace", required=True) +parser.add_argument("--pod", required=True, help="Exact existing Account or Game Session Pod name") +args = parser.parse_args(sys.argv[2:]) +if not args.context.strip() or args.context.startswith("-"): + parser.error("an explicit nonempty context is required") +if not re.fullmatch(r"dev|pr-[1-9][0-9]{0,50}", args.namespace): + parser.error("namespace must be exactly dev or canonical pr-N") +if not re.fullmatch(r"[a-z0-9](?:[-a-z0-9.]{0,251}[a-z0-9])?", args.pod): + parser.error("--pod must be an exact Pod name") +kubectl = ["kubectl", "--context", args.context, "--request-timeout=30s"] + + +def call(command, body=None): + try: + return subprocess.run(kubectl + command, input=None if body is None else json.dumps(body), + text=True, capture_output=True, check=False, timeout=45) + except (OSError, subprocess.TimeoutExpired): + fail("kubectl unavailable or timed out; no admission conclusion") + + +def get(resource, name, namespaced=False): + command = (["-n", args.namespace] if namespaced else []) + ["get", resource, name, "-o", "json"] + result = call(command) + if result.returncode: + fail("cannot read " + resource + "/" + name) + try: + return json.loads(result.stdout) + except ValueError: + fail("malformed API readback for " + resource) + + +boundary = "firemud-trust-runtime-pod-boundary" +identity = "firemud-trust-runtime-pod-identity" +revision_key = "firemud.dev/admission-revision" +with open(sys.argv[1], encoding="utf-8") as stream: + expected = [item for item in yaml.safe_load_all(stream) + if item and item.get("metadata", {}).get("name") in (boundary, identity)] +if len(expected) != 4 or {(item["kind"], item["metadata"]["name"]) for item in expected} != { + (kind, name) for kind in ("ValidatingAdmissionPolicy", "ValidatingAdmissionPolicyBinding") + for name in (boundary, identity) +}: + fail("trusted manifest lacks the exact protected Pod policy/binding set") + + +def canonical_spec(kind, spec): + result = copy.deepcopy(spec) + if not isinstance(result, dict): + return result + match = result.setdefault("matchConstraints" if kind == "ValidatingAdmissionPolicy" else "matchResources", {}) + if isinstance(match, dict): + match.setdefault("namespaceSelector", {}) + match.setdefault("objectSelector", {}) + match.setdefault("matchPolicy", "Equivalent") + return result + + +def verify_policies(): + versions = {} + for wanted in expected: + kind, name = wanted["kind"], wanted["metadata"]["name"] + actual = get(kind + ".admissionregistration.k8s.io", name) + metadata = actual.get("metadata", {}) + if (actual.get("apiVersion") != wanted["apiVersion"] or actual.get("kind") != kind + or metadata.get("name") != name or metadata.get("deletionTimestamp") is not None + or wanted["metadata"].get("annotations", {}).get(revision_key) != "hosted-pod-identity-v1" + or metadata.get("annotations", {}).get(revision_key) != "hosted-pod-identity-v1" + or canonical_spec(kind, actual.get("spec")) != canonical_spec(kind, wanted["spec"]) + or not metadata.get("uid") or not metadata.get("resourceVersion")): + fail("installed policy/binding differs from exact trusted revision: " + name) + if kind == "ValidatingAdmissionPolicy": + status = actual.get("status", {}) + if (actual["spec"].get("failurePolicy") != "Fail" + or not isinstance(metadata.get("generation"), int) + or status.get("observedGeneration") != metadata["generation"] + or not isinstance(status.get("typeChecking"), dict) + or status["typeChecking"].get("expressionWarnings", []) != []): + fail("policy typechecking/current generation/Fail not proved: " + name) + elif actual["spec"].get("validationActions") != ["Deny"]: + fail("binding is not exact Deny: " + name) + versions[(kind, name)] = (metadata["uid"], metadata["resourceVersion"]) + return versions + + +namespace = get("namespace", args.namespace) +labels = namespace.get("metadata", {}).get("labels", {}) +if (namespace.get("metadata", {}).get("name") != args.namespace + or namespace.get("metadata", {}).get("deletionTimestamp") is not None + or namespace.get("status", {}).get("phase") != "Active"): + fail("namespace is absent, terminating, or not Active") +if args.namespace == "dev": + valid_namespace = labels.get("firemud.dev/dev-demo") == "true" and labels.get("firemud.dev/environment-class") == "dev-demo-cluster" +else: + valid_namespace = labels.get("firemud.dev/preview") == "true" and labels.get("firemud.dev/pr-number") == args.namespace[3:] +if not valid_namespace: + fail("namespace does not carry canonical hosted ownership labels") +policy_versions = verify_policies() +base_path = "/api/v1/namespaces/" + args.namespace + "/pods" + + +def probe(description, body, policy=None, message=None, path=None): + command = ["replace" if path else "create", "--raw", (path or base_path) + "?dryRun=All", "-f", "-"] + result = call(command, body) + if policy is None: + if result.returncode: + fail(description + ": valid control was not admitted") + try: + returned = json.loads(result.stdout) + except ValueError: + fail(description + ": no valid Pod response") + if returned.get("kind") != "Pod" or returned.get("metadata", {}).get("name") != body["metadata"]["name"]: + fail(description + ": unexpected successful response") + else: + # Authentication, schema, immutability, conflict and arbitrary API errors + # are never accepted as admission proof. Require native named rejection. + rejection = (r"ValidatingAdmissionPolicy [\"']" + re.escape(policy) + + r"[\"'] with binding [\"']" + re.escape(policy) + + r"[\"'] denied request: " + re.escape(message)) + if result.returncode == 0 or not re.search(rejection, result.stderr): + fail(description + ": expected exact named admission denial was not observed") + print("PASS " + description, flush=True) + + +security = {"allowPrivilegeEscalation": False, "capabilities": {"drop": ["ALL"]}} +mount_path = "/var/run/secrets/firemud/pod-identity" +run_id = uuid.uuid4().hex[:12] +for app in ("account-service", "game-session-service"): + pod = {"apiVersion": "v1", "kind": "Pod", "metadata": { + "name": app + "-admission-proof-" + run_id, "namespace": args.namespace}, "spec": { + "automountServiceAccountToken": False, "restartPolicy": "Never", + "securityContext": {"runAsNonRoot": True, "runAsUser": 1000, "seccompProfile": {"type": "RuntimeDefault"}}, + "containers": [{"name": app, "image": "registry.k8s.io/pause:3.10", "securityContext": copy.deepcopy(security), + "volumeMounts": [{"name": "pod-identity", "mountPath": mount_path, "readOnly": True}]}], + "volumes": [{"name": "pod-identity", "downwardAPI": {"defaultMode": 292, "items": [ + {"path": "uid", "fieldRef": {"apiVersion": "v1", "fieldPath": "metadata.uid"}}]}}]}} + probe(app + " valid CREATE", pod) + host_message = "hosted runtime Pods must not use host namespaces, hostPath, or sysctl overrides" + container_message = "every hosted runtime application/init container must drop all capabilities and exclude host ports and privilege escalation" + injection_message = "Account and Game Session require exactly their application container and no init/ephemeral containers or injected annotations" + confinement_message = "protected Pod identity consumers require nonroot RuntimeDefault confinement without block devices" + volume_message = "protected Pod UID must come only from the canonical kubelet downwardAPI metadata.uid volume" + mount_message = "protected Pod UID mount must be read-only at the canonical path without subpaths, shadow mounts, or mount propagation" + + def deny(label, mutate, policy, message): + candidate = copy.deepcopy(pod) + mutate(candidate) + probe(app + " CREATE " + label, candidate, policy, message) + + for field in ("hostNetwork", "hostPID", "hostIPC"): + deny(field, lambda p, field=field: p["spec"].update({field: True}), boundary, host_message) + deny("hostPath", lambda p: p["spec"]["volumes"].append({"name": "host", "hostPath": {"path": "/tmp"}}), boundary, host_message) + deny("sysctls", lambda p: p["spec"]["securityContext"].update({"sysctls": [{"name": "net.ipv4.ip_local_port_range", "value": "1024 65535"}]}), boundary, host_message) + for label, change in (("privileged", {"privileged": True}), ("escalation", {"allowPrivilegeEscalation": True}), + ("NET_ADMIN", {"capabilities": {"drop": ["ALL"], "add": ["NET_ADMIN"]}}), + ("missing-drop", {"capabilities": {"drop": []}}), ("procMount", {"procMount": "Unmasked"})): + deny(label, lambda p, change=change: p["spec"]["containers"][0]["securityContext"].update(change), boundary, container_message) + deny("hostPort", lambda p: p["spec"]["containers"][0].update({"ports": [{"containerPort": 8080, "hostPort": 8080}]}), boundary, container_message) + deny("sidecar", lambda p: p["spec"]["containers"].append({"name": "proxy", "image": "registry.k8s.io/pause:3.10", "securityContext": security}), identity, injection_message) + deny("init", lambda p: p["spec"].update({"initContainers": [{"name": "proxy", "image": "registry.k8s.io/pause:3.10", "securityContext": security}]}), identity, injection_message) + deny("annotations", lambda p: p["metadata"].update({"annotations": {"proof.firemud.dev/inject": "true"}}), identity, injection_message) + deny("root", lambda p: p["spec"]["securityContext"].update({"runAsUser": 0}), identity, confinement_message) + deny("seccomp", lambda p: p["spec"]["securityContext"].update({"seccompProfile": {"type": "Unconfined"}}), identity, confinement_message) + deny("UID-source", lambda p: p["spec"]["volumes"][0]["downwardAPI"]["items"][0]["fieldRef"].update({"fieldPath": "metadata.name"}), identity, volume_message) + deny("UID-mode", lambda p: p["spec"]["volumes"][0]["downwardAPI"].update({"defaultMode": 420}), identity, volume_message) + for label, change in (("writable", {"readOnly": False}), ("subPath", {"subPath": "uid"}), + ("subPathExpr", {"subPathExpr": "uid"}), ("propagation", {"mountPropagation": "HostToContainer"}), + ("noncanonical-path", {"mountPath": mount_path + "/../pod-identity"})): + deny(label, lambda p, change=change: p["spec"]["containers"][0]["volumeMounts"][0].update(change), identity, mount_message) + for shadow_path in ("/var/run/secrets/firemud", mount_path + "/uid"): + def shadow(p, shadow_path=shadow_path): + p["spec"]["volumes"].append({"name": "shadow", "emptyDir": {}}) + p["spec"]["containers"][0]["volumeMounts"].append({"name": "shadow", "mountPath": shadow_path}) + deny("shadow-" + shadow_path, shadow, identity, mount_message) + +existing = get("pod", args.pod, True) +metadata = existing.get("metadata", {}) +containers = existing.get("spec", {}).get("containers", []) +if (existing.get("apiVersion") != "v1" or existing.get("kind") != "Pod" + or metadata.get("name") != args.pod or metadata.get("namespace") != args.namespace + or not metadata.get("uid") or not metadata.get("resourceVersion") + or metadata.get("deletionTimestamp") is not None or len(containers) != 1 + or containers[0].get("name") not in ("account-service", "game-session-service")): + fail("--pod does not identify one current protected Pod with exact UID/resourceVersion") +existing.pop("status", None) +metadata.pop("managedFields", None) +pod_path = base_path + "/" + args.pod +probe("existing Pod valid UPDATE", existing, path=pod_path) +changed = copy.deepcopy(existing) +changed["metadata"].setdefault("annotations", {})["proof.firemud.dev/inject"] = "true" +probe("existing Pod annotation UPDATE", changed, identity, injection_message, pod_path) +probe("existing Pod valid ephemeralcontainers control", existing, path=pod_path + "/ephemeralcontainers") +changed = copy.deepcopy(existing) +changed["spec"].setdefault("ephemeralContainers", []).append({ + "name": "proof-" + run_id, "image": "registry.k8s.io/pause:3.10", "securityContext": security}) +probe("existing Pod ephemeral injection", changed, identity, injection_message, pod_path + "/ephemeralcontainers") +changed["spec"]["ephemeralContainers"][-1]["securityContext"] = { + "allowPrivilegeEscalation": True, "capabilities": {"drop": ["ALL"], "add": ["NET_ADMIN"]}} +probe("existing Pod ephemeral privilege escape", changed, boundary, + "hosted runtime ephemeral containers must satisfy the same host and capability restrictions", pod_path + "/ephemeralcontainers") +current = get("pod", args.pod, True).get("metadata", {}) +if any(current.get(key) != metadata[key] for key in ("uid", "resourceVersion")) or current.get("deletionTimestamp") is not None: + fail("existing Pod changed during proof; rerun against a stable explicit target") +if verify_policies() != policy_versions: + fail("installed policy/binding changed during proof") +print("PASS native admission only; UPDATE/ephemeral evidence covers the explicitly selected Pod.") +print("UNPROVED: CNI/socket routing, kubelet UID-to-process correspondence, replacement races, shared-key closure, and promotion readiness.") +PY diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index 008695e9bc..95934893ac 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -3965,6 +3965,31 @@ def service_consumer_documents(): {"key": "ca.crt", "path": "ca.crt"}, ] volumes.append({"name": name, kind: projection}) + if service in {"account-service", "game-session-service"}: + mounts.append( + { + "name": "pod-identity", + "mountPath": "/var/run/secrets/firemud/pod-identity", + "readOnly": True, + } + ) + volumes.append( + { + "name": "pod-identity", + "downwardAPI": { + "defaultMode": 0o444, + "items": [ + { + "path": "uid", + "fieldRef": { + "apiVersion": "v1", + "fieldPath": "metadata.uid", + }, + } + ], + }, + } + ) container = { "name": service, "volumeMounts": mounts, @@ -4024,6 +4049,88 @@ def service_consumer_documents(): valid_consumers = service_consumer_documents() validator.validate_service_consumers(valid_consumers, "pr-42", "standalone", "public") +for service in ("account-service", "game-session-service"): + missing_pod_identity_projection = copy.deepcopy(valid_consumers) + identity_deployment = next( + document + for document in missing_pod_identity_projection + if document["metadata"]["name"] == service + ) + identity_pod = identity_deployment["spec"]["template"]["spec"] + identity_pod["volumes"] = [ + volume + for volume in identity_pod["volumes"] + if volume["name"] != "pod-identity" + ] + assert_rejected( + lambda documents=missing_pod_identity_projection: validator.validate_service_consumers( + documents, "pr-42", "standalone", "public" + ), + f"Deployment/{service} has duplicate or unexpected identity consumers", + ) + + writable_pod_identity_projection = copy.deepcopy(valid_consumers) + identity_deployment = next( + document + for document in writable_pod_identity_projection + if document["metadata"]["name"] == service + ) + identity_volume = next( + volume + for volume in identity_deployment["spec"]["template"]["spec"]["volumes"] + if volume["name"] == "pod-identity" + ) + identity_volume["downwardAPI"]["defaultMode"] = 0o644 + assert_rejected( + lambda documents=writable_pod_identity_projection: validator.validate_service_consumers( + documents, "pr-42", "standalone", "public" + ), + f"Deployment/{service} has an unsafe pod-identity projection", + ) + + substituted_pod_identity_projection = copy.deepcopy(valid_consumers) + identity_deployment = next( + document + for document in substituted_pod_identity_projection + if document["metadata"]["name"] == service + ) + identity_volume = next( + volume + for volume in identity_deployment["spec"]["template"]["spec"]["volumes"] + if volume["name"] == "pod-identity" + ) + identity_volume["downwardAPI"]["items"][0]["fieldRef"]["fieldPath"] = ( + "metadata.name" + ) + assert_rejected( + lambda documents=substituted_pod_identity_projection: validator.validate_service_consumers( + documents, "pr-42", "standalone", "public" + ), + f"Deployment/{service} has an unsafe pod-identity projection", + ) + + duplicate_pod_identity_mount = copy.deepcopy(valid_consumers) + identity_deployment = next( + document + for document in duplicate_pod_identity_mount + if document["metadata"]["name"] == service + ) + identity_container = identity_deployment["spec"]["template"]["spec"][ + "containers" + ][0] + identity_mount = next( + mount + for mount in identity_container["volumeMounts"] + if mount["name"] == "pod-identity" + ) + identity_container["volumeMounts"].append(copy.deepcopy(identity_mount)) + assert_rejected( + lambda documents=duplicate_pod_identity_mount: validator.validate_service_consumers( + documents, "pr-42", "standalone", "public" + ), + f"Deployment/{service} has duplicate or unexpected identity consumers", + ) + missing_publication_trust_mount = copy.deepcopy(valid_consumers) publication_deployment = next( document diff --git a/dev-tools/tests/protected-pod-live-proof-contract.sh b/dev-tools/tests/protected-pod-live-proof-contract.sh new file mode 100644 index 0000000000..3f978740c4 --- /dev/null +++ b/dev-tools/tests/protected-pod-live-proof-contract.sh @@ -0,0 +1,163 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)" +python3 - "$repo_root" <<'PY' +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import yaml + +root = Path(sys.argv[1]) +tool = root / "dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh" +# This fake API exercises the executable transport and outcomes; it is not a +# CEL evaluator or evidence that a live API server compiles/enforces the policy. +mock = r''' +#!/usr/bin/env python3 +import copy +import json +import os +from pathlib import Path +import sys +import yaml + +args = sys.argv[1:] +assert args[:4] == ['--context', 'proof-context', '--request-timeout=30s', 'get'] or args[:3] == ['--context', 'proof-context', '--request-timeout=30s'] +args = args[3:] +mode = os.environ['PROOF_MODE'] +namespace = os.environ.get('PROOF_NAMESPACE', 'dev') +if args[:2] == ['-n', namespace]: + args = args[2:] +with open(os.environ['PROOF_LOG'], 'a') as stream: + stream.write(json.dumps(args) + '\n') +boundary = 'firemud-trust-runtime-pod-boundary' +identity = 'firemud-trust-runtime-pod-identity' +if args[0] == 'get': + resource, name = args[1:3] + if resource == 'namespace': + labels = {'firemud.dev/dev-demo': 'true', 'firemud.dev/environment-class': 'dev-demo-cluster'} if namespace == 'dev' else {'firemud.dev/preview': 'true', 'firemud.dev/pr-number': namespace[3:]} + if mode == 'namespace-labels': labels = {} + result = {'metadata': {'name': namespace, 'labels': labels}, 'status': {'phase': 'Active'}} + elif resource == 'pod': + result = json.loads(Path(os.environ['PROOF_POD']).read_text()) + if mode == 'wrong-pod': result['spec']['containers'][0]['name'] = 'other' + if mode == 'missing-uid': result['metadata'].pop('uid') + if mode == 'pod-drift': + if Path(os.environ['PROOF_POD'] + '.seen').exists(): result['metadata']['resourceVersion'] = '99' + Path(os.environ['PROOF_POD'] + '.seen').touch() + else: + documents = list(yaml.safe_load_all(Path(os.environ['PROOF_POLICY']).read_text())) + result = next(x for x in documents if x and x['kind'] + '.admissionregistration.k8s.io' == resource and x['metadata']['name'] == name) + result['metadata'].update(uid='policy-uid-' + name, resourceVersion='10', generation=1) + if result['kind'] == 'ValidatingAdmissionPolicy': + result['status'] = {'observedGeneration': 1, 'typeChecking': {'expressionWarnings': []}} + if mode == 'warning': result['status']['typeChecking']['expressionWarnings'] = [{'warning': 'bad CEL'}] + if mode == 'missing-typecheck': result['status'].pop('typeChecking') + if mode == 'stale-generation': result['status']['observedGeneration'] = 0 + if mode == 'fail-open': result['spec']['failurePolicy'] = 'Ignore' + if mode == 'spec-drift': result['spec']['matchConditions'] = [] + else: + if mode == 'audit-only': result['spec']['validationActions'] = ['Audit'] + if mode == 'wrong-revision': result['metadata']['annotations']['firemud.dev/admission-revision'] = 'old' + if mode == 'defaulted': + match = result['spec'].setdefault('matchConstraints' if result['kind'] == 'ValidatingAdmissionPolicy' else 'matchResources', {}) + match.update(namespaceSelector={}, objectSelector={}, matchPolicy='Equivalent') + print(json.dumps(result)) + sys.exit(0) + +# Fail hard if the executor attempts anything outside dry-run native Pod POST/PUT. +assert args[0] in ('create', 'replace'), args +assert args[1] == '--raw' and args[3:] == ['-f', '-'], args +path = args[2] +assert path.startswith('/api/v1/namespaces/' + namespace + '/pods'), path +assert path.endswith('?dryRun=All') and path.count('?') == 1, path +pod = json.load(sys.stdin) +assert pod['kind'] == 'Pod' and pod['metadata']['namespace'] == namespace +if args[0] == 'replace': + assert pod['metadata']['uid'] == 'existing-uid' and pod['metadata']['resourceVersion'] == '8' + assert '/account-service-existing' in path +spec = pod['spec'] +container = spec['containers'][0] +security = container['securityContext'] +policy = None +message = None +if any(spec.get(k) for k in ('hostNetwork', 'hostPID', 'hostIPC')) or any('hostPath' in v for v in spec['volumes']) or spec['securityContext'].get('sysctls'): + policy, message = boundary, 'hosted runtime Pods must not use host namespaces, hostPath, or sysctl overrides' +elif (security.get('privileged') or security.get('allowPrivilegeEscalation') or security.get('procMount', 'Default') != 'Default' + or 'ALL' not in security['capabilities']['drop'] or security['capabilities'].get('add') + or any(p.get('hostPort', 0) for p in container.get('ports', []))): + policy, message = boundary, 'every hosted runtime application/init container must drop all capabilities and exclude host ports and privilege escalation' +elif any(c['securityContext'].get('allowPrivilegeEscalation') for c in spec.get('ephemeralContainers', [])): + policy, message = boundary, 'hosted runtime ephemeral containers must satisfy the same host and capability restrictions' +elif len(spec['containers']) != 1 or spec.get('initContainers') or spec.get('ephemeralContainers') or pod['metadata'].get('annotations'): + policy, message = identity, 'Account and Game Session require exactly their application container and no init/ephemeral containers or injected annotations' +elif spec['securityContext']['runAsUser'] <= 0 or spec['securityContext']['seccompProfile']['type'] != 'RuntimeDefault': + policy, message = identity, 'protected Pod identity consumers require nonroot RuntimeDefault confinement without block devices' +elif spec['volumes'][0]['downwardAPI']['items'][0]['fieldRef']['fieldPath'] != 'metadata.uid' or spec['volumes'][0]['downwardAPI']['defaultMode'] != 292: + policy, message = identity, 'protected Pod UID must come only from the canonical kubelet downwardAPI metadata.uid volume' +else: + mount = container['volumeMounts'][0] + if (len(container['volumeMounts']) != 1 or not mount['readOnly'] or mount['mountPath'] != '/var/run/secrets/firemud/pod-identity' + or 'subPath' in mount or 'subPathExpr' in mount or mount.get('mountPropagation', 'None') != 'None'): + policy, message = identity, 'protected Pod UID mount must be read-only at the canonical path without subpaths, shadow mounts, or mount propagation' +if policy: + if mode == 'allow-escape': print(json.dumps(pod)); sys.exit(0) + if mode == 'auth-error': print('Error from server (Forbidden): user cannot create pods', file=sys.stderr) + elif mode == 'conflict': print('Error from server (Conflict): resource version stale', file=sys.stderr) + elif mode == 'wrong-policy': print("ValidatingAdmissionPolicy 'other' with binding 'other' denied request: " + message, file=sys.stderr) + elif mode == 'wrong-message': print("ValidatingAdmissionPolicy '" + policy + "' with binding '" + policy + "' denied request: different constraint", file=sys.stderr) + else: print("Error from server (Forbidden): ValidatingAdmissionPolicy '" + policy + "' with binding '" + policy + "' denied request: " + message, file=sys.stderr) + sys.exit(1) +if mode == 'valid-denied': print('unavailable', file=sys.stderr); sys.exit(1) +if mode == 'malformed-success': print('{}'); sys.exit(0) +print(json.dumps(pod)) +''' + +with tempfile.TemporaryDirectory(prefix="firemud-pod-proof-contract-") as directory: + temporary = Path(directory) + executable = temporary / "kubectl" + executable.write_text(mock.lstrip(), encoding="utf-8") + executable.chmod(0o700) + pod_file = temporary / "pod.json" + pod = {"apiVersion": "v1", "kind": "Pod", "metadata": {"name": "account-service-existing", "namespace": "dev", "uid": "existing-uid", "resourceVersion": "8"}, "spec": { + "securityContext": {"runAsNonRoot": True, "runAsUser": 1000, "seccompProfile": {"type": "RuntimeDefault"}}, + "containers": [{"name": "account-service", "image": "registry.k8s.io/pause:3.10", "securityContext": {"allowPrivilegeEscalation": False, "capabilities": {"drop": ["ALL"]}}, + "volumeMounts": [{"name": "pod-identity", "mountPath": "/var/run/secrets/firemud/pod-identity", "readOnly": True}]}], + "volumes": [{"name": "pod-identity", "downwardAPI": {"defaultMode": 292, "items": [{"path": "uid", "fieldRef": {"apiVersion": "v1", "fieldPath": "metadata.uid"}}]}}]}} + pod_file.write_text(json.dumps(pod), encoding="utf-8") + environment = dict(os.environ, PATH=str(temporary) + os.pathsep + os.environ["PATH"], + PROOF_POLICY=str(root / "k8s/trust-bootstrap/deployment-admission.yaml"), + PROOF_POD=str(pod_file), PROOF_LOG=str(temporary / "calls")) + arguments = ["--context", "proof-context", "--namespace", "dev", "--pod", "account-service-existing"] + cases = ["normal", "defaulted", "namespace-labels", "warning", "missing-typecheck", "stale-generation", "fail-open", "spec-drift", "audit-only", "wrong-revision", "wrong-pod", "missing-uid", "pod-drift", "allow-escape", "auth-error", "conflict", "wrong-policy", "wrong-message", "valid-denied", "malformed-success"] + for mode in cases: + result = subprocess.run(["bash", str(tool)] + arguments, env=dict(environment, PROOF_MODE=mode), text=True, capture_output=True) + assert (result.returncode == 0) == (mode in ("normal", "defaulted")), (mode, result.stdout, result.stderr) + if mode == "normal": + assert "UNPROVED: CNI/socket" in result.stdout + assert "ephemeral privilege escape" in result.stdout + assert "game-session-service CREATE shadow-" in result.stdout + print("PASS mock-kubectl " + mode) + pod["metadata"]["namespace"] = "pr-23" + pod_file.write_text(json.dumps(pod), encoding="utf-8") + preview_args = ["--context", "proof-context", "--namespace", "pr-23", "--pod", "account-service-existing"] + result = subprocess.run(["bash", str(tool)] + preview_args, env=dict(environment, PROOF_MODE="normal", PROOF_NAMESPACE="pr-23"), text=True, capture_output=True) + assert result.returncode == 0, result.stderr + print("PASS mock-kubectl canonical pr-N") + before = (temporary / "calls").read_text() + for invalid in ([], ["--namespace", "dev", "--pod", "account-service-existing"], + ["--context", "", "--namespace", "dev", "--pod", "account-service-existing"], + ["--context", "proof-context", "--namespace", "pr-01", "--pod", "account-service-existing"], + ["--context", "proof-context", "--namespace", "production", "--pod", "account-service-existing"], + ["--context", "proof-context", "--namespace", "dev"], + ["--context", "proof-context", "--namespace", "dev", "--pod", "a/b"]): + result = subprocess.run(["bash", str(tool)] + invalid, env=dict(environment, PROOF_MODE="normal"), text=True, capture_output=True) + assert result.returncode != 0 + assert (temporary / "calls").read_text() == before, "invalid arguments reached kubectl" + print("PASS argument rejection before API access") +print("PASS protected Pod live-proof behavioral contract (mock only; no live cluster commands)") +PY From c7ea3ff35c517f8df8679ae2a7cc3111ca1fb448 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 05:18:18 +1300 Subject: [PATCH 021/129] Guard later terms deadlines and prepare isolated admission artifacts --- ...ame-authoring-publishing-and-activation.md | 2 +- dev-tools/hosted/README.md | 28 +++ .../protected-pod-admission-proof.yaml | 137 +++++++++++++++ .../protected-pod-live-proof-contract.sh | 38 ++++ .../AccountHostedTermsService.java | 39 ++++- ...untHostedTermsPostgresIntegrationTest.java | 160 +++++++++++++++++ ...ronmentBindingPostgresIntegrationTest.java | 163 ++++++++++++++++++ 7 files changed, 561 insertions(+), 6 deletions(-) create mode 100644 dev-tools/hosted/trust-bootstrap/fixtures/protected-pod-admission-proof.yaml 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 1a477ff8ed..a0230e87be 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 @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a The current Gameplay-prerequisite construction remains non-activating. Full-version finalization now reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. The real backend control-ui issuance/current-actor source, complete Account source-writer fencing and callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Earlier construction CI executed all four Account source-composition, five environment-binding and 31 Draft authorization PostgreSQL cases successfully, while three Game Design canonical-release fixtures failed for missing policy source capture. Their receiving correction now freezes actual Game Design command/policy source snapshots before sealing; corrected physical execution remains required. These bounded changes do not upgrade the broader capability ratings below. -The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. At `ed928219ee3428073910f1845eaa975e8814a30a`, local validation is complete for the held-order/source-fencing batch, but physical PostgreSQL validation was skipped. The Account-owned disclosure journal now defines an immutable request, predecessor/candidate, effective instant, exact source vector and opaque authority binding, with exact dispatch/ambiguity/result readback. Its non-revoking preparation check refuses already-reserved or unsettled original operations under sorted source locks. The journal now serializes dispatch authorization and original reserve/claim under the same sorted source locks. PREPARED alone permits ordinary original acquisition; first dispatch rechecks exact settlement, while authorized, ambiguous or disclosed handoffs deny a new no-deadline order only for their exact changed terms source evidence. Existing original retries and obsolete source history do not acquire new authority or blanket-block unrelated sources. Focused both-ordering and concurrency proof definitions are present, but physical PostgreSQL execution remains required. This is still a bounded storage/ordering foundation: complete capture/currentness integration, both catalog and environment publication paths, authenticated notice production/readback and the physical World deadline gate remain unimplemented or unproved; there is no production disclosure/currentness path. Reconsider only after focused PostgreSQL proof covers both orderings of preparation versus original `COMMIT_ORDER` acquisition and settlement, every deadline-introduction path including environment binding, exact retry/restart/ambiguous-notice readback, and World commit-time denial at the disclosed instant without early ordinary-authoring freeze or date rewriting. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. +The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read alone does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. At `ed928219ee3428073910f1845eaa975e8814a30a`, local validation is complete for the held-order/source-fencing batch, but physical PostgreSQL validation was skipped. The Account-owned disclosure journal now defines an immutable request, predecessor/candidate, effective instant, exact source vector and opaque authority binding, with exact dispatch/ambiguity/result readback. Its non-revoking preparation check refuses already-reserved or unsettled original operations under sorted source locks. The journal now serializes dispatch authorization and original reserve/claim under the same sorted source locks. PREPARED alone permits ordinary original acquisition; first dispatch rechecks exact settlement, while authorized, ambiguous or disclosed handoffs deny a new no-deadline order only for their exact changed terms source evidence. Existing original retries and obsolete source history do not acquire new authority or blanket-block unrelated sources. Focused both-ordering and concurrency proof definitions are present, but physical PostgreSQL execution remains required. This is still a bounded storage/ordering foundation: complete capture/currentness integration, authenticated notice production/readback and the physical World deadline gate remain unimplemented or unproved; there is no production disclosure/currentness path. Reconsider only after focused PostgreSQL proof covers both orderings of preparation versus original `COMMIT_ORDER` acquisition and settlement, every deadline-introduction path including environment binding, exact retry/restart/ambiguous-notice readback, and World commit-time denial at the disclosed instant without early ordinary-authoring freeze or date rewriting. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. The current catalog scheduling correction checks the exact operative terms source before introducing a future deadline, and a binding change checks existing predecessor/current sources only when it would newly expose a different scope's scheduled future deadline. Focused PostgreSQL definitions cover denial while an original operation is unsettled, exact request retry after owner settlement, same-scope non-introducing binding refresh, and the existing non-deadline pending behavior; the consolidated Account gate passed, but these PostgreSQL cases skipped locally without Docker and still require physical execution. This adds local ordering/denial proof only: actual notice dispatch, authenticated production authority and World commit-time enforcement remain unavailable. Future-only proposal/final-result digest design: exclude generated notice-result fields alone from the pre-disclosure proposal digest; bind all exact source, document, materiality, operator, scope, effective-time and authorized-notice inputs; then bind the unchanged proposal together with the authenticated result into the final catalog. `candidateDigest` remains opaque/uncomputed today, so this is a future design note, not a present digest-cycle defect. Creator issuance preserves the existing OTP failure budget by committing a primary-authentication denial's accounting before returning the credential error; successful OTP consumption still rolls back if subsequent preparation fails. Its real PostgreSQL definitions use the primary hook's Spring transaction interceptor, not only a direct method call. The construction includes a selective Account per-Pod readiness/receipt closure and commit-bound signer coordinator, together with a default-inactive Game Session receiver using production cryptographic profile validation and exact Account owner readback. Six loopback mTLS cases executed without skips through the real Game Session verifier and owner-read client; their Account owner responses, protected local identity and public JWKS remain test fixtures. These sources do not establish a production signer: protected input delivery, deployed isolated routing, current inventory and mounted correspondence, corrected PostgreSQL proof, and live convergence/promotion remain open. The current inventory rejects shared receiver-Pod leaf-key pins, while the base Deployment uses the accepted workload-level certificate delivery. Unique replica SPKI is a code-selected strengthening, not an ADR 0038 prerequisite; the approved alternative is described below but remains unproved. A complete claim without protected per-validator evidence remains quarantined; synthetic signer fixtures cannot close the original APPLIED/release prerequisite. Password and wrong-secret PostgreSQL proof is separate from restricted-account authentication: the latter has unit coverage, while an authentic owner lifecycle transition needed for its physical fixture remains unavailable. The broader JWT capability remains owned by [Shared Runtime Contracts](./shared-runtime-contracts-and-persistence.md). diff --git a/dev-tools/hosted/README.md b/dev-tools/hosted/README.md index 62bcaf318f..db4645a953 100644 --- a/dev-tools/hosted/README.md +++ b/dev-tools/hosted/README.md @@ -40,3 +40,31 @@ Use it before ad hoc live inspection so preview debugging stays deterministic an - [trust-bootstrap/prove-protected-pod-boundary.sh](trust-bootstrap/prove-protected-pod-boundary.sh) – operator-invoked native admission proof: `bash dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh --context CONTEXT --namespace dev --pod EXACT_PROTECTED_POD` (also canonical `pr-N`). Requires Python/PyYAML and kubectl; verifies installed trusted policy content and compilation, then uses only server dry-run CREATE/UPDATE/ephemeral-container requests. This is partial admission evidence, not routing, replacement-race, shared-key closure or promotion proof; see [the attribution owner](../../design/architecture/system-architecture-jwt-and-token-contracts.md#protected-readiness-receiver-attribution). - [shared/show-rollout-diagnostics.sh](shared/show-rollout-diagnostics.sh) – first-look diagnostics for a hosted namespace when a rollout is blocked. - [shared/wait-for-hosted-runtime-rollouts.sh](shared/wait-for-hosted-runtime-rollouts.sh) – bounded readiness wait for the canonical hosted runtime deployment inventory. + +## Disposable Native Admission Fixture + +[The admission-only fixture](trust-bootstrap/fixtures/protected-pod-admission-proof.yaml) supplies real Account/Game Session-named Pod targets running pause, not application receivers. The automated runner entrypoint must first establish ownership of a wholly fresh disposable cluster and arrange exact-cluster teardown on success, failure and cancellation. Neither a context name, an absent `dev` Namespace nor fixture labels establish that ownership. Never use this fixture against shared environments. The fixture uses the existing test-tool `pause:3.10` reference; execution remains blocked until the entrypoint supplies an independently verified immutable `PROOF_PAUSE_IMAGE` digest. No digest is invented or resolved by this example. + +After that prerequisite, the entrypoint can automate this sequence from the repository root with kubectl, jq and Python/PyYAML available: + +```bash +set -euo pipefail +: "${proof_context:?explicit run-owned disposable context required}" +: "${PROOF_PAUSE_IMAGE:?verified registry.k8s.io/pause@sha256 digest required}" +[[ "$PROOF_PAUSE_IMAGE" =~ ^registry\.k8s\.io/pause@sha256:[a-f0-9]{64}$ ]] +existing_namespace=$(kubectl --context "$proof_context" get namespace dev --ignore-not-found -o name) +[[ -z "$existing_namespace" ]] +kubectl --context "$proof_context" create -f k8s/trust-bootstrap/deployment-admission.yaml +sed "s|registry.k8s.io/pause:3.10|$PROOF_PAUSE_IMAGE|g" \ + dev-tools/hosted/trust-bootstrap/fixtures/protected-pod-admission-proof.yaml \ + | kubectl --context "$proof_context" create -f - +for app in account-service game-session-service; do + kubectl --context "$proof_context" -n dev rollout status "deployment/$app" --timeout=180s + proof_pod=$(kubectl --context "$proof_context" -n dev get pods -l "app=$app" -o json \ + | jq -er '.items | select(length == 1) | .[0].metadata.name') + bash dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh \ + --context "$proof_context" --namespace dev --pod "$proof_pod" +done +``` + +Any missing compilation status, unexpected API/schema/PSA rejection, ambiguous Pod selection or changed target fails this stage; do not disable protections or count an unrelated rejection as the expected native-policy denial. This sequence creates fixture resources only in the owned disposable cluster; the executor's probes remain server dry-run. It establishes only native admission evidence, with no real TLS, application UID/process correspondence, CNI routing, replacement-race, shared-key closure, signer or promotion claim. Both fixture Deployments use hosted Helm's shared `firemud-app` ServiceAccount name, with token automount disabled. diff --git a/dev-tools/hosted/trust-bootstrap/fixtures/protected-pod-admission-proof.yaml b/dev-tools/hosted/trust-bootstrap/fixtures/protected-pod-admission-proof.yaml new file mode 100644 index 0000000000..5c7bbf6041 --- /dev/null +++ b/dev-tools/hosted/trust-bootstrap/fixtures/protected-pod-admission-proof.yaml @@ -0,0 +1,137 @@ +# ADMISSION-ONLY TEST FIXTURE. Never deploy to an existing/shared environment. +# The runner must own a wholly fresh disposable cluster; labels are not ownership proof. +# These pause processes are NOT Account/Game Session receivers, TLS endpoints, +# UID-to-application-process attribution, or signer/promotion readiness evidence. +# Execution gate: replace the existing test-tool image tag below with a verified +# immutable pause digest before creating resources. No trusted digest is pinned here. +apiVersion: v1 +kind: Namespace +metadata: + name: dev + labels: + firemud.dev/dev-demo: "true" + firemud.dev/environment-class: dev-demo-cluster + firemud.dev/admission-proof-only: "true" +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: firemud-app + namespace: dev +automountServiceAccountToken: false +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: account-service + namespace: dev + labels: + firemud.dev/admission-proof-only: "true" +spec: + replicas: 1 + selector: + matchLabels: + app: account-service + template: + metadata: + labels: + app: account-service + firemud.dev/admission-proof-only: "true" + spec: + serviceAccountName: firemud-app + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + seccompProfile: + type: RuntimeDefault + containers: + - name: account-service + image: registry.k8s.io/pause:3.10 + imagePullPolicy: IfNotPresent + securityContext: + allowPrivilegeEscalation: false + runAsUser: 1000 + runAsGroup: 1000 + capabilities: + drop: [ALL] + resources: + requests: + cpu: 10m + memory: 8Mi + limits: + cpu: 100m + memory: 32Mi + volumeMounts: + - name: pod-identity + mountPath: /var/run/secrets/firemud/pod-identity + readOnly: true + volumes: + - name: pod-identity + downwardAPI: + defaultMode: 0444 + items: + - path: uid + fieldRef: + apiVersion: v1 + fieldPath: metadata.uid +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: game-session-service + namespace: dev + labels: + firemud.dev/admission-proof-only: "true" +spec: + replicas: 1 + selector: + matchLabels: + app: game-session-service + template: + metadata: + labels: + app: game-session-service + firemud.dev/admission-proof-only: "true" + spec: + serviceAccountName: firemud-app + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + seccompProfile: + type: RuntimeDefault + containers: + - name: game-session-service + image: registry.k8s.io/pause:3.10 + imagePullPolicy: IfNotPresent + securityContext: + allowPrivilegeEscalation: false + runAsUser: 1000 + runAsGroup: 1000 + capabilities: + drop: [ALL] + resources: + requests: + cpu: 10m + memory: 8Mi + limits: + cpu: 100m + memory: 32Mi + volumeMounts: + - name: pod-identity + mountPath: /var/run/secrets/firemud/pod-identity + readOnly: true + volumes: + - name: pod-identity + downwardAPI: + defaultMode: 0444 + items: + - path: uid + fieldRef: + apiVersion: v1 + fieldPath: metadata.uid diff --git a/dev-tools/tests/protected-pod-live-proof-contract.sh b/dev-tools/tests/protected-pod-live-proof-contract.sh index 3f978740c4..c399cac975 100644 --- a/dev-tools/tests/protected-pod-live-proof-contract.sh +++ b/dev-tools/tests/protected-pod-live-proof-contract.sh @@ -14,6 +14,44 @@ import yaml root = Path(sys.argv[1]) tool = root / "dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh" +# Fixture shape proof is local only: no API admission or CEL success is inferred. +fixture_path = root / "dev-tools/hosted/trust-bootstrap/fixtures/protected-pod-admission-proof.yaml" +fixture_text = fixture_path.read_text(encoding="utf-8") +assert "ADMISSION-ONLY TEST FIXTURE" in fixture_text and "Execution gate:" in fixture_text +fixture = list(yaml.safe_load_all(fixture_text)) +assert len(fixture) == 4 +assert {(item["kind"], item["metadata"]["name"]) for item in fixture} == { + ("Namespace", "dev"), ("ServiceAccount", "firemud-app"), + ("Deployment", "account-service"), ("Deployment", "game-session-service")} +namespace_fixture = next(item for item in fixture if item["kind"] == "Namespace") +assert namespace_fixture["metadata"]["labels"] == { + "firemud.dev/dev-demo": "true", "firemud.dev/environment-class": "dev-demo-cluster", + "firemud.dev/admission-proof-only": "true"} +for item in fixture: + if item["kind"] == "Namespace": + continue + assert item["metadata"]["namespace"] == "dev" + if item["kind"] == "ServiceAccount": + assert item["automountServiceAccountToken"] is False + assert set(item) == {"apiVersion", "kind", "metadata", "automountServiceAccountToken"} + continue + app = item["metadata"]["name"] + assert item["spec"]["replicas"] == 1 + assert item["spec"]["selector"] == {"matchLabels": {"app": app}} + template = item["spec"]["template"] + assert template["metadata"] == {"labels": {"app": app, "firemud.dev/admission-proof-only": "true"}} + spec = template["spec"] + assert set(spec) == {"serviceAccountName", "automountServiceAccountToken", "securityContext", "containers", "volumes"} + assert spec["serviceAccountName"] == "firemud-app" and spec["automountServiceAccountToken"] is False + assert spec["securityContext"] == {"runAsNonRoot": True, "runAsUser": 1000, "runAsGroup": 1000, "fsGroup": 1000, "seccompProfile": {"type": "RuntimeDefault"}} + assert len(spec["containers"]) == 1 + container = spec["containers"][0] + assert set(container) == {"name", "image", "imagePullPolicy", "securityContext", "resources", "volumeMounts"} + assert container["name"] == app and container["image"] == "registry.k8s.io/pause:3.10" + assert container["securityContext"] == {"allowPrivilegeEscalation": False, "runAsUser": 1000, "runAsGroup": 1000, "capabilities": {"drop": ["ALL"]}} + assert container["volumeMounts"] == [{"name": "pod-identity", "mountPath": "/var/run/secrets/firemud/pod-identity", "readOnly": True}] + assert spec["volumes"] == [{"name": "pod-identity", "downwardAPI": {"defaultMode": 292, "items": [{"path": "uid", "fieldRef": {"apiVersion": "v1", "fieldPath": "metadata.uid"}}]}}] +print("PASS local admission-only fixture shape (not API/CEL proof)", flush=True) # This fake API exercises the executable transport and outcomes; it is not a # CEL evaluator or evidence that a live API server compiles/enforces the policy. mock = r''' diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java index 712b530035..5f9cabaa4a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java @@ -298,6 +298,17 @@ private EnvironmentBindingPublicationResult publishEnvironmentBindingInTransacti HostedTermsCatalogVersion targetCatalog = targetScope.current(); requireExactBindingCatalog(evidence, targetCatalog, targetScope.databaseNow()); + boolean introducesFutureDeadline = + hasFutureScheduledDeadline(targetScope) + && (predecessor == null + || !predecessor.hostedScopeId().equals(evidence.hostedScopeId())); + if (introducesFutureDeadline) { + List protectedSources = + predecessor == null + ? List.of(catalogSourceEvidence(targetCatalog)) + : bindingSourceEvidence(predecessor, catalogScopes); + draftFences.requireDisclosurePreparation(protectedSources); + } HostedTermsEnvironmentBinding candidate = environmentBindings.insertCandidate(UUID.randomUUID(), requestId, evidence, predecessor); DraftAuthorizationFenceRepository.SourceChange change = @@ -383,6 +394,15 @@ private DraftAuthorizationFenceRepository.SourceChange bindingSourceChange( HostedTermsEnvironmentBinding predecessor, Map catalogScopes, HostedTermsEnvironmentBinding candidate) { + return new DraftAuthorizationFenceRepository.SourceChange( + changeId, + bindingSourceEvidence(predecessor, catalogScopes), + HostedTermsEnvironmentBindingEncoding.receipt(candidate)); + } + + private List bindingSourceEvidence( + HostedTermsEnvironmentBinding predecessor, + Map catalogScopes) { Map sources = new LinkedHashMap<>(); SourceEvidence bindingSource = predecessor.sourceEvidence(); sources.put(bindingSource.key(), bindingSource); @@ -391,10 +411,7 @@ private DraftAuthorizationFenceRepository.SourceChange bindingSourceChange( .filter(Objects::nonNull) .map(this::catalogSourceEvidence) .forEach(source -> sources.put(source.key(), source)); - return new DraftAuthorizationFenceRepository.SourceChange( - changeId, - List.copyOf(sources.values()), - HostedTermsEnvironmentBindingEncoding.receipt(candidate)); + return sources.values().stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); } private SourceEvidence catalogSourceEvidence(HostedTermsCatalogVersion catalog) { @@ -408,6 +425,14 @@ private SourceEvidence catalogSourceEvidence(HostedTermsCatalogVersion catalog) HostedTermsEncoding.catalog(catalog)); } + private boolean hasFutureScheduledDeadline(HostedTermsRepository.ScopeSnapshot scope) { + HostedTermsRepository.PublicationOperation pending = scope.unsettledPublication(); + if (pending == null || pending.status() != HostedTermsRepository.PublicationStatus.SCHEDULED) { + return false; + } + return repository.readCandidate(pending).effectiveAt().isAfter(scope.databaseNow().toInstant()); + } + private void requireExactBindingCatalog( HostedTermsEnvironmentBinding.PublicationEvidence evidence, HostedTermsCatalogVersion current, @@ -553,11 +578,15 @@ private PublicationResult publishInTransaction( throw new IllegalStateException("Another hosted terms publication is scheduled or pending"); } HostedTermsCatalogVersion candidate = candidate(evidence, scope.current()); - repository.insertCandidate(candidate); if (candidate.effectiveAt().isAfter(scope.databaseNow().toInstant())) { + if (scope.current() != null) { + draftFences.requireDisclosurePreparation(List.of(catalogSourceEvidence(scope.current()))); + } + repository.insertCandidate(candidate); repository.markScheduled(requestId, candidate); return result(HostedTermsRepository.PublicationStatus.SCHEDULED, candidate); } + repository.insertCandidate(candidate); return activate(operation, candidate, scope.current(), null, scope.databaseNow()); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java index dc55944233..8ecffd08dd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java @@ -10,6 +10,7 @@ import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; @@ -31,6 +32,16 @@ import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Record; @@ -373,6 +384,99 @@ void futureTermsCarryDeadlineWithoutFreezingPriorTermsEarly() throws Exception { .isTrue(); } + @Test + void futureTermsCannotPassUnsettledOriginalCommitOrderAndExactRetryWaitsForSettlement() + throws Exception { + Database db = database("latest"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID scopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId, 1, "test-id-evidence-v1"); + tx(db, () -> insertParty(db, party)); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + AccountHostedTermsService service = service(db, publications, actions); + + UUID initialRequest = UUID.randomUUID(); + publications.put( + initialRequest, + publication( + scopeId, + "test-terms-v1".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.INITIAL, + databaseNow(db).minusSeconds(10))); + HostedTermsCatalogVersion initial = service.publish(initialRequest).candidate(); + UUID actionId = UUID.randomUUID(); + actions.put(actionId, action(actionId, accountId, partyId, scopeId, initial, true)); + service.accept(actionId); + + AccountHostedTermsService.CurrentnessEvidence beforeDeadline = + service.requireCurrentness(scopeId, partyId); + assertThat(beforeDeadline.disclosedDeadline()).isNull(); + SourceEvidence currentTermsSource = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + scopeId.toString(), + Long.toString(beforeDeadline.materialGeneration()), + Long.toString(beforeDeadline.sourceVersion()), + null, + null, + beforeDeadline.exactCurrentnessSource()); + DraftAuthorizationFenceBinding originalOrder = + testDraftBinding(accountId, List.of(currentTermsSource)); + DraftAuthorizationFenceRepository fences = new DraftAuthorizationFenceRepository(db.dsl()); + tx( + db, + () -> { + fences.reserve(originalOrder); + fences.claimCommitOrder(originalOrder); + }); + + UUID futureRequest = UUID.randomUUID(); + Instant deadline = databaseNow(db).plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.MICROS); + publications.put( + futureRequest, + publication( + scopeId, + "test-terms-v2".getBytes(), + "Test Operator", + 1, + HostedTermsCatalogVersion.Materiality.MATERIAL, + deadline)); + assertThatThrownBy(() -> service.publish(futureRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Disclosure deadline cannot pass an unsettled original Draft operation"); + assertThat( + db.dsl() + .fetchOne( + "SELECT request_id FROM account_hosted_terms_publication_operations " + + "WHERE request_id = ?", + futureRequest)) + .isNull(); + assertThat(service.requireCurrentness(scopeId, partyId).disclosedDeadline()).isNull(); + String originalOrdering = + db.transactions().execute(ignored -> fences.read(originalOrder).ordering().name()); + assertThat(originalOrdering).isEqualTo("COMMIT_ORDER"); + + tx( + db, + () -> { + fences.recordOwnerReadback( + originalOrder, testReadback(originalOrder, Owner.WORLD, Outcome.COMMITTED)); + fences.recordOwnerReadback( + originalOrder, testReadback(originalOrder, Owner.GAME_DESIGN, Outcome.COMMITTED)); + }); + AccountHostedTermsService.PublicationResult scheduled = service.publish(futureRequest); + assertThat(scheduled.status()).isEqualTo(HostedTermsRepository.PublicationStatus.SCHEDULED); + assertThat(scheduled.candidate().effectiveAt()).isEqualTo(deadline); + assertThat(service.publish(futureRequest)).isEqualTo(scheduled); + assertThat(service.requireCurrentness(scopeId, partyId).disclosedDeadline()) + .isEqualTo(scheduled.candidate()); + } + private static boolean currentnessBlockedAcrossEffectiveDateIsDenied( Database db, AccountHostedTermsService service, UUID scopeId, UUID partyId, Instant deadline) throws Exception { @@ -539,6 +643,62 @@ private static AccountHostedTermsService service( Objects.requireNonNull(actions.get(actionId), "test-only identity/action fixture")); } + private static DraftAuthorizationFenceBinding testDraftBinding( + UUID actorAccountId, List sources) { + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID commitId = UUID.randomUUID(); + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof(tenantId, versionId, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + requestId, + commitId, + "opaque/base:1", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-only")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "test-region", + "aggregate", + "test-region", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + requestId, + commitId, + UUID.randomUUID(), + actorAccountId, + tenantId, + versionId, + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + sources) + .withRequiredOwners(); + } + + private static OwnerReadback testReadback( + DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { + return new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {1}); + } + private static AccountHostedTermsService.PublicationEvidence publication( UUID scope, byte[] document, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java index fd6d646e6a..57d916a4e2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java @@ -357,6 +357,156 @@ void bindingUpdateWaitsForExactTerminalSettlementOfAffectedDraftOperation() thro .isEqualTo(2); } + @Test + void bindingDeadlineIntroductionWaitsForOriginalOrderAndExactRetryReusesItsRequest() + throws Exception { + Database db = database("latest"); + UUID accountId = insertAccount(db); + UUID partyId = UUID.randomUUID(); + UUID priorScopeId = UUID.randomUUID(); + UUID targetScopeId = UUID.randomUUID(); + IndividualCreatorPartySource party = party(partyId, accountId); + tx(db, () -> insertParty(db, party)); + Map catalogPublications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindingPublications = + new HashMap<>(); + String boundaryName = "deadline-introduction-test-environment"; + AtomicReference boundary = + new AtomicReference<>(currentBoundary(boundaryName)); + AccountHostedTermsService service = + service(db, catalogPublications, actions, bindingPublications, boundary); + + UUID priorTermsRequest = UUID.randomUUID(); + catalogPublications.put( + priorTermsRequest, + publication( + priorScopeId, + "test-only prior scope terms".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.INITIAL, + databaseNow(db).minusSeconds(10))); + HostedTermsCatalogVersion priorCatalog = service.publish(priorTermsRequest).candidate(); + UUID priorAcceptanceRequest = UUID.randomUUID(); + actions.put( + priorAcceptanceRequest, action(priorAcceptanceRequest, accountId, partyId, priorCatalog)); + service.accept(priorAcceptanceRequest); + + UUID firstBindingRequest = UUID.randomUUID(); + bindingPublications.put( + firstBindingRequest, + bindingEvidence(boundaryName, priorCatalog, null, null, "test-only-prior-publisher")); + var priorBinding = service.publishEnvironmentBinding(firstBindingRequest); + + UUID targetTermsRequest = UUID.randomUUID(); + catalogPublications.put( + targetTermsRequest, + publication( + targetScopeId, + "test-only target scope terms".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.INITIAL, + databaseNow(db).minusSeconds(10))); + HostedTermsCatalogVersion targetCatalog = service.publish(targetTermsRequest).candidate(); + UUID targetAcceptanceRequest = UUID.randomUUID(); + actions.put( + targetAcceptanceRequest, + action(targetAcceptanceRequest, accountId, partyId, targetCatalog)); + service.accept(targetAcceptanceRequest); + + UUID scheduledRequest = UUID.randomUUID(); + Instant deadline = databaseNow(db).plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.MICROS); + catalogPublications.put( + scheduledRequest, + publication( + targetScopeId, + "test-only scheduled target terms".getBytes(StandardCharsets.UTF_8), + HostedTermsCatalogVersion.Materiality.MATERIAL, + deadline)); + var scheduled = service.publish(scheduledRequest); + assertThat(scheduled.status()).isEqualTo(HostedTermsRepository.PublicationStatus.SCHEDULED); + + var priorCurrentness = service.requireCurrentnessForCurrentEnvironment(partyId); + assertThat(priorCurrentness.binding()).isEqualTo(priorBinding.candidate()); + assertThat(priorCurrentness.terms().disclosedDeadline()).isNull(); + DraftAuthorizationFenceBinding originalOrder = + testDraftBinding(accountId, priorCurrentness.sourceEvidence()); + var fences = new DraftAuthorizationFenceRepository(db.dsl()); + tx( + db, + () -> { + fences.reserve(originalOrder); + fences.claimCommitOrder(originalOrder); + }); + + UUID targetBindingRequest = UUID.randomUUID(); + HostedTermsEnvironmentBinding.PublicationEvidence targetBindingEvidence = + bindingEvidence( + boundaryName, + targetCatalog, + priorBinding.candidate().bindingId(), + priorBinding.candidate().sourceVersion(), + "test-only-target-publisher"); + bindingPublications.put(targetBindingRequest, targetBindingEvidence); + assertThatThrownBy(() -> service.publishEnvironmentBinding(targetBindingRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Disclosure deadline cannot pass an unsettled original Draft operation"); + assertThat( + db.dsl() + .fetchOne( + "SELECT request_id FROM account_hosted_terms_environment_binding_publications " + + "WHERE request_id = ?", + targetBindingRequest)) + .isNull(); + String originalOrdering = + db.transactions().execute(ignored -> fences.read(originalOrder).ordering().name()); + assertThat(originalOrdering).isEqualTo("COMMIT_ORDER"); + assertThat(service.requireCurrentnessForCurrentEnvironment(partyId).binding()) + .isEqualTo(priorBinding.candidate()); + + tx( + db, + () -> { + fences.recordOwnerReadback( + originalOrder, testCommittedReadback(originalOrder, Owner.WORLD)); + fences.recordOwnerReadback( + originalOrder, testCommittedReadback(originalOrder, Owner.GAME_DESIGN)); + }); + var retriedBinding = service.publishEnvironmentBinding(targetBindingRequest); + assertThat(retriedBinding.status()) + .isEqualTo(HostedTermsEnvironmentBindingRepository.PublicationStatus.COMMITTED); + assertThat(retriedBinding.candidate().hostedScopeId()).isEqualTo(targetScopeId); + assertThat(service.publishEnvironmentBinding(targetBindingRequest)).isEqualTo(retriedBinding); + var targetCurrentness = service.requireCurrentnessForCurrentEnvironment(partyId); + assertThat(targetCurrentness.terms().disclosedDeadline()).isEqualTo(scheduled.candidate()); + assertThat(targetCurrentness.terms().validUntil()).isEqualTo(deadline); + + DraftAuthorizationFenceBinding deadlineQualifiedOrder = + testDraftBinding(accountId, targetCurrentness.sourceEvidence()); + tx( + db, + () -> { + fences.reserve(deadlineQualifiedOrder); + fences.claimCommitOrder(deadlineQualifiedOrder); + }); + UUID sameScopeRefreshRequest = UUID.randomUUID(); + bindingPublications.put( + sameScopeRefreshRequest, + bindingEvidence( + boundaryName, + targetCatalog, + retriedBinding.candidate().bindingId(), + retriedBinding.candidate().sourceVersion(), + "test-only-same-scope-refresh")); + var pendingSameScopeRefresh = service.publishEnvironmentBinding(sameScopeRefreshRequest); + assertThat(pendingSameScopeRefresh.status()) + .isEqualTo( + HostedTermsEnvironmentBindingRepository.PublicationStatus.PENDING_OWNER_SETTLEMENT); + assertThat(pendingSameScopeRefresh.candidate().hostedScopeId()).isEqualTo(targetScopeId); + String deadlineQualifiedOrdering = + db.transactions().execute(ignored -> fences.read(deadlineQualifiedOrder).ordering().name()); + assertThat(deadlineQualifiedOrdering).isEqualTo("COMMIT_ORDER"); + } + @Test void boundCurrentnessCarriesExactScheduledCatalogAndUnextendedDeadline() throws Exception { Database db = database("latest"); @@ -730,6 +880,19 @@ private static OwnerReadback testReadback( exactTestResult); } + private static OwnerReadback testCommittedReadback( + DraftAuthorizationFenceBinding binding, Owner owner) { + return new OwnerReadback( + owner, + Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {1}); + } + private static AccountHostedTermsService service( Database db, Map catalogPublications, From 077829af77c89e4bff416f406ea4603290f64995 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 05:28:56 +1300 Subject: [PATCH 022/129] Repair closed readiness signing and binding-head no-op ordering --- ...stedTermsEnvironmentBindingRepository.java | 4 + .../AccountMountedJwtSignerBundle.java | 17 ++-- ...ronmentBindingPostgresIntegrationTest.java | 40 ++++++++ ...countJwtReadinessProbeSigningSpecTest.java | 91 +++++++++++++++++++ 4 files changed, 145 insertions(+), 7 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeSigningSpecTest.java diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java index 27d949819c..cec24c3388 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java @@ -73,6 +73,10 @@ public record HeadSnapshot( public void ensureHead(String environmentBoundary) { requireWriteTransaction(); String boundary = requireBoundary(environmentBoundary); + if (dsl.fetchOne("SELECT 1 FROM " + HEADS + " WHERE environment_boundary = ?", boundary) + != null) { + return; + } dsl.execute( "INSERT INTO " + HEADS + " (environment_boundary) VALUES (?) ON CONFLICT DO NOTHING", boundary); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java index 63a4980e0d..f1bb70f08a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java @@ -69,6 +69,7 @@ public final class AccountMountedJwtSignerBundle { static final String READINESS_CANARY_TYPE = "account_jwt_readiness_canary"; static final String READINESS_CANARY_AUDIENCE = "firemud-account-jwt-readiness"; static final String READINESS_VALIDATOR_ID = "account-service"; + static final String GAME_SESSION_VALIDATOR_ID = "game-session-service"; static final String REPRESENTATIVE_PROFILE = GameSessionAccountDelegationProfile.PROFILE; static final String REPRESENTATIVE_AUDIENCE = GameSessionAccountDelegationProfile.AUDIENCE; private static final String ISSUER = "firemud-account-service"; @@ -1169,7 +1170,8 @@ record ReadinessProbeSigningSpec( long expiresAtEpochSecond) { ReadinessProbeSigningSpec { if (validatorId == null - || !READINESS_VALIDATOR_ID.equals(validatorId) + || (!READINESS_VALIDATOR_ID.equals(validatorId) + && !GAME_SESSION_VALIDATOR_ID.equals(validatorId)) || probeKind == null || jti == null || jti.version() != 4 @@ -1190,12 +1192,13 @@ record ReadinessProbeSigningSpec( } } else { boolean exactProfileAudience = - (ControlUiJwtProfileValidator.PROFILE.equals(tokenProfile) - && ControlUiJwtProfileValidator.AUDIENCE.equals(audience)) - || (PlayerBootstrapJwtProfileValidator.PROFILE.equals(tokenProfile) - && PlayerBootstrapJwtProfileValidator.AUDIENCE.equals(audience)) - || (REPRESENTATIVE_PROFILE.equals(tokenProfile) - && REPRESENTATIVE_AUDIENCE.equals(audience)); + (REPRESENTATIVE_PROFILE.equals(tokenProfile) + && REPRESENTATIVE_AUDIENCE.equals(audience)) + || (READINESS_VALIDATOR_ID.equals(validatorId) + && ((ControlUiJwtProfileValidator.PROFILE.equals(tokenProfile) + && ControlUiJwtProfileValidator.AUDIENCE.equals(audience)) + || (PlayerBootstrapJwtProfileValidator.PROFILE.equals(tokenProfile) + && PlayerBootstrapJwtProfileValidator.AUDIENCE.equals(audience)))); if (!exactProfileAudience) { throw invalid(); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java index 57d916a4e2..2ca43bd0ef 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingPostgresIntegrationTest.java @@ -314,6 +314,46 @@ void bindingUpdateWaitsForExactTerminalSettlementOfAffectedDraftOperation() thro var draftFences = new DraftAuthorizationFenceRepository(db.dsl()); tx(db, () -> draftFences.reserve(pendingDraft)); + var bindingRepository = new HostedTermsEnvironmentBindingRepository(db.dsl()); + tx(db, () -> bindingRepository.ensureHead("settlement-test-environment")); + var headAfterEnsure = + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT current_binding_id, current_source_version " + + "FROM account_hosted_terms_environment_binding_heads " + + "WHERE environment_boundary = ?", + "settlement-test-environment")); + assertThat(headAfterEnsure.get("current_binding_id", UUID.class)) + .isEqualTo(first.candidate().bindingId()); + assertThat(headAfterEnsure.get("current_source_version", Long.class)).isEqualTo(1L); + assertThatThrownBy( + () -> + tx( + db, + () -> + db.dsl() + .execute( + "UPDATE account_hosted_terms_environment_binding_heads " + + "SET current_binding_id = ?, current_source_version = ? " + + "WHERE environment_boundary = ?", + UUID.randomUUID(), + 2L, + "settlement-test-environment"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Required creator source is held"); + var headAfterRejectedWrite = + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT current_binding_id, current_source_version " + + "FROM account_hosted_terms_environment_binding_heads " + + "WHERE environment_boundary = ?", + "settlement-test-environment")); + assertThat(headAfterRejectedWrite.get("current_binding_id", UUID.class)) + .isEqualTo(first.candidate().bindingId()); + assertThat(headAfterRejectedWrite.get("current_source_version", Long.class)).isEqualTo(1L); + UUID secondRequest = UUID.randomUUID(); HostedTermsEnvironmentBinding.PublicationEvidence secondEvidence = bindingEvidence( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeSigningSpecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeSigningSpecTest.java new file mode 100644 index 0000000000..d736999f8b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeSigningSpecTest.java @@ -0,0 +1,91 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec; +import org.junit.jupiter.api.Test; + +class AccountJwtReadinessProbeSigningSpecTest { + @Test + void acceptsAccountCanaryAndEveryProtectedProductionProfile() { + assertValid( + AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, + ProbeKind.CANARY, + AccountMountedJwtSignerBundle.READINESS_CANARY_PROFILE, + AccountMountedJwtSignerBundle.READINESS_CANARY_AUDIENCE); + assertValid( + AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + "control-ui", + "control-ui"); + assertValid( + AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + "player-bootstrap", + "player-bootstrap"); + assertValid( + AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_AUDIENCE); + } + + @Test + void acceptsGameSessionCanaryAndItsOnlyProtectedProductionProfile() { + assertValid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.CANARY, + AccountMountedJwtSignerBundle.READINESS_CANARY_PROFILE, + AccountMountedJwtSignerBundle.READINESS_CANARY_AUDIENCE); + assertValid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_AUDIENCE); + } + + @Test + void rejectsUnknownAndCrossValidatorProfileAudienceCombinations() { + assertInvalid( + "unknown-service", + ProbeKind.CANARY, + AccountMountedJwtSignerBundle.READINESS_CANARY_PROFILE, + AccountMountedJwtSignerBundle.READINESS_CANARY_AUDIENCE); + assertInvalid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + "control-ui", + "control-ui"); + assertInvalid( + AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, + "control-ui"); + assertInvalid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.CANARY, + AccountMountedJwtSignerBundle.READINESS_CANARY_PROFILE, + "account-service"); + } + + private static void assertValid( + String validatorId, ProbeKind kind, String profile, String audience) { + assertThatCode(() -> signingSpec(validatorId, kind, profile, audience)) + .doesNotThrowAnyException(); + } + + private static void assertInvalid( + String validatorId, ProbeKind kind, String profile, String audience) { + assertThatThrownBy(() -> signingSpec(validatorId, kind, profile, audience)) + .isInstanceOf(AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class); + } + + private static ReadinessProbeSigningSpec signingSpec( + String validatorId, ProbeKind kind, String profile, String audience) { + return new ReadinessProbeSigningSpec( + validatorId, kind, profile, audience, UUID.randomUUID(), "1", "key-1", 20_300, 20_480); + } +} From f14c7950827dd435ac0fe5c4cc230a1de32fa96d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 05:57:00 +1300 Subject: [PATCH 023/129] Repair readiness rejection probes and prove strict registry CAS --- .../hostedterms/HostedTermsRepository.java | 3 + .../AccountMountedJwtSignerBundle.java | 9 +- ...untHostedTermsPostgresIntegrationTest.java | 48 ++ ...ControlUiRegistryRedisIntegrationTest.java | 429 ++++++++++++++++++ ...countJwtReadinessProbeSigningSpecTest.java | 22 +- 5 files changed, 500 insertions(+), 11 deletions(-) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryRedisIntegrationTest.java diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java index 7e13ce38a8..b23696c6b5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java @@ -76,6 +76,9 @@ public record ScopeSnapshot( public void ensureScope(UUID scopeId) { requireWriteTransaction(); HostedTermsEncoding.requireUuid(scopeId, "hosted scope"); + if (dsl.fetchOne("SELECT 1 FROM " + SCOPES + " WHERE hosted_scope_id = ?", scopeId) != null) { + return; + } dsl.execute( "INSERT INTO " + SCOPES + " (hosted_scope_id) VALUES (?) ON CONFLICT DO NOTHING", scopeId); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java index f1bb70f08a..934804b789 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java @@ -1194,11 +1194,10 @@ record ReadinessProbeSigningSpec( boolean exactProfileAudience = (REPRESENTATIVE_PROFILE.equals(tokenProfile) && REPRESENTATIVE_AUDIENCE.equals(audience)) - || (READINESS_VALIDATOR_ID.equals(validatorId) - && ((ControlUiJwtProfileValidator.PROFILE.equals(tokenProfile) - && ControlUiJwtProfileValidator.AUDIENCE.equals(audience)) - || (PlayerBootstrapJwtProfileValidator.PROFILE.equals(tokenProfile) - && PlayerBootstrapJwtProfileValidator.AUDIENCE.equals(audience)))); + || (ControlUiJwtProfileValidator.PROFILE.equals(tokenProfile) + && ControlUiJwtProfileValidator.AUDIENCE.equals(audience)) + || (PlayerBootstrapJwtProfileValidator.PROFILE.equals(tokenProfile) + && PlayerBootstrapJwtProfileValidator.AUDIENCE.equals(audience)); if (!exactProfileAudience) { throw invalid(); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java index 8ecffd08dd..0f78d567de 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java @@ -434,6 +434,53 @@ void futureTermsCannotPassUnsettledOriginalCommitOrderAndExactRetryWaitsForSettl fences.claimCommitOrder(originalOrder); }); + HostedTermsRepository repository = new HostedTermsRepository(db.dsl()); + tx(db, () -> repository.ensureScope(scopeId)); + var scopeAfterEnsure = + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT current_version_id, current_source_version, " + + "current_material_generation FROM account_hosted_terms_scopes " + + "WHERE hosted_scope_id = ?", + scopeId)); + assertThat(scopeAfterEnsure.get("current_version_id", UUID.class)) + .isEqualTo(initial.versionId()); + assertThat(scopeAfterEnsure.get("current_source_version", Long.class)) + .isEqualTo(initial.sourceVersion()); + assertThat(scopeAfterEnsure.get("current_material_generation", Long.class)) + .isEqualTo(initial.materialGeneration()); + assertThatThrownBy( + () -> + tx( + db, + () -> + db.dsl() + .execute( + "UPDATE account_hosted_terms_scopes " + + "SET current_version_id = ?, current_source_version = ?, " + + "current_material_generation = ? WHERE hosted_scope_id = ?", + UUID.randomUUID(), + 2L, + 2L, + scopeId))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("Required creator source is held"); + var scopeAfterRejectedWrite = + Objects.requireNonNull( + db.dsl() + .fetchOne( + "SELECT current_version_id, current_source_version, " + + "current_material_generation FROM account_hosted_terms_scopes " + + "WHERE hosted_scope_id = ?", + scopeId)); + assertThat(scopeAfterRejectedWrite.get("current_version_id", UUID.class)) + .isEqualTo(initial.versionId()); + assertThat(scopeAfterRejectedWrite.get("current_source_version", Long.class)) + .isEqualTo(initial.sourceVersion()); + assertThat(scopeAfterRejectedWrite.get("current_material_generation", Long.class)) + .isEqualTo(initial.materialGeneration()); + UUID futureRequest = UUID.randomUUID(); Instant deadline = databaseNow(db).plus(1, ChronoUnit.DAYS).truncatedTo(ChronoUnit.MICROS); publications.put( @@ -475,6 +522,7 @@ void futureTermsCannotPassUnsettledOriginalCommitOrderAndExactRetryWaitsForSettl assertThat(service.publish(futureRequest)).isEqualTo(scheduled); assertThat(service.requireCurrentness(scopeId, partyId).disclosedDeadline()) .isEqualTo(scheduled.candidate()); + assertThat(service.requireCurrentness(scopeId, partyId).validUntil()).isEqualTo(deadline); } private static boolean currentnessBlockedAcrossEffectiveDateIsDenied( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryRedisIntegrationTest.java new file mode 100644 index 0000000000..196336951d --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryRedisIntegrationTest.java @@ -0,0 +1,429 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.output.StatusOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.AcknowledgementRequirements; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Physical Coordination Redis proof for Account's pending token-registry CAS only. Inputs and any + * directly seeded active read fixture are synthetic and non-authorizing; this does not prove + * Account issuance, committed signer provenance, or the Account-owned activation transition. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountControlUiRegistryRedisIntegrationTest { + private static final int REDIS_PORT = 6379; + private static final String ACCOUNT_USER = "account_coord_app"; + private static final String ACCOUNT_PASSWORD = UUID.randomUUID().toString().replace("-", ""); + private static final String WRONG_USER = "account_coord_wrong"; + private static final String WRONG_PASSWORD = UUID.randomUUID().toString().replace("-", ""); + private static final Network REDIS_NETWORK = Network.newNetwork(); + + @Container + static final GenericContainer primary = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(REDIS_NETWORK) + .withNetworkAliases("control-ui-coordination-primary") + .withExposedPorts(REDIS_PORT) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(REDIS_NETWORK) + .dependsOn(primary) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "control-ui-coordination-primary", + Integer.toString(REDIS_PORT)); + + private static final RedisScriptCatalog TEST_CATALOG = testCatalog(); + private static RedisClient adminClient; + + @BeforeAll + static void configureIsolatedRedis() throws InterruptedException { + adminClient = client(null, null); + try (var connection = adminClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = connection.sync(); + configureApplicationUser(commands, ACCOUNT_USER, ACCOUNT_PASSWORD, true); + configureApplicationUser(commands, WRONG_USER, WRONG_PASSWORD, false); + awaitLocalAndReplicaAof(commands); + } + } + + @AfterAll + static void stopClients() { + if (adminClient != null) { + adminClient.shutdown(); + } + } + + @Test + void pendingRegistrationRequiresRealAofAckExactRetryAndImmutableCas() { + String tokenHash = tokenHash(); + long expiryMillis = (Instant.now().getEpochSecond() + 300) * 1000L; + byte[] pending = syntheticRecord(tokenHash, "pending", expiryMillis / 1000, "request-a"); + byte[] key = key(tokenHash); + + try (var pinned = new PinnedAccountConnection(ACCOUNT_USER, ACCOUNT_PASSWORD)) { + AccountControlUiCoordination underDurabilityThreshold = + coordination(pinned, new AcknowledgementRequirements(1, 2, 1000)); + assertThatThrownBy( + () -> underDurabilityThreshold.registerPending(tokenHash, pending, expiryMillis)) + .isInstanceOf(IllegalStateException.class); + // The Redis write occurred, but the under-threshold WAITAOF result created no owner receipt. + assertThat(adminGet(key)).isEqualTo(pending); + + AccountControlUiCoordination owner = + coordination(pinned, new AcknowledgementRequirements(1, 1, 1000)); + var created = owner.registerPending(tokenHash, pending, expiryMillis); + assertThat(created.tokenHash).isEqualTo(tokenHash); + assertThat(created.recordDigest).isEqualTo(AccountControlUiIssuanceRepository.hash(pending)); + assertThat(created.expiryMillis).isEqualTo(expiryMillis); + assertThat(created.localAof).isEqualTo(1); + assertThat(created.replicas).isEqualTo(1); + assertThat(adminGet(key)).isEqualTo(pending); + + // Exact retry reasserts the bytes, obtains a fresh same-connection WAITAOF, and reads back. + var retried = owner.registerPending(tokenHash, pending, expiryMillis); + assertThat(retried.tokenHash).isEqualTo(created.tokenHash); + assertThat(retried.recordDigest).isEqualTo(created.recordDigest); + assertThat(retried.expiryMillis).isEqualTo(created.expiryMillis); + assertThat(retried.localAof).isEqualTo(1); + assertThat(retried.replicas).isEqualTo(1); + + byte[] changedBinding = + syntheticRecord(tokenHash, "pending", expiryMillis / 1000, "request-b"); + assertThatThrownBy(() -> owner.registerPending(tokenHash, changedBinding, expiryMillis)) + .isInstanceOf(IllegalStateException.class); + assertThat(adminGet(key)).isEqualTo(pending); + + // PENDING is deliberately not accepted as an active actor registry record. + assertThatThrownBy(() -> owner.readActive(tokenHash)) + .isInstanceOf(IllegalStateException.class); + assertThat(pinned.openedConnections()).isGreaterThan(0); + } + } + + @Test + void wrongAuthenticatedPrincipalCannotReadEvenASyntheticActiveProjection() { + String tokenHash = tokenHash(); + long expiryMillis = (Instant.now().getEpochSecond() + 300) * 1000L; + byte[] active = syntheticRecord(tokenHash, "active", expiryMillis / 1000, "read-only-fixture"); + adminSetWithExpiry(key(tokenHash), active, expiryMillis); + + try (var wrongPrincipal = new PinnedAccountConnection(WRONG_USER, WRONG_PASSWORD)) { + // Prove this authenticated test-only principal can reach the same synthetic key and + // physical-expiry commands before the production identity guard rejects it. + try (var connection = wrongPrincipal.openPinnedConnection()) { + RedisCommands commands = connection.sync(); + assertThat(commands.aclWhoami()).isEqualTo(WRONG_USER); + assertThat(commands.get(key(tokenHash))).isEqualTo(active); + assertThat(commands.pexpiretime(key(tokenHash))).isEqualTo(expiryMillis); + } + + AccountControlUiCoordination client = + coordination(wrongPrincipal, new AcknowledgementRequirements(1, 1, 1000)); + assertThatThrownBy(() -> client.readActive(tokenHash)) + .isInstanceOf(IllegalStateException.class); + assertThat(wrongPrincipal.openedConnections()).isEqualTo(2); + } + } + + @Test + void activeReadRequiresExactPhysicalExpiryAndExpiredProjectionDenies() { + String tokenHash = tokenHash(); + long expiryMillis = (Instant.now().getEpochSecond() + 300) * 1000L; + byte[] active = syntheticRecord(tokenHash, "active", expiryMillis / 1000, "read-only-fixture"); + byte[] key = key(tokenHash); + adminSetWithExpiry(key, active, expiryMillis); + + try (var pinned = new PinnedAccountConnection(ACCOUNT_USER, ACCOUNT_PASSWORD)) { + AccountControlUiCoordination client = + coordination(pinned, new AcknowledgementRequirements(1, 1, 1000)); + // Direct seeding exists only to exercise the actual read predicate; it is not activation. + assertThat(client.readActive(tokenHash)).isEqualTo(active); + + adminSetExpiry(key, expiryMillis - 1000L); + assertThatThrownBy(() -> client.readActive(tokenHash)) + .isInstanceOf(IllegalStateException.class); + + String expiredHash = tokenHash(); + long expiredMillis = (Instant.now().getEpochSecond() - 30) * 1000L; + adminSetWithExpiry( + key(expiredHash), + syntheticRecord(expiredHash, "active", expiredMillis / 1000, "expired-fixture"), + expiredMillis); + assertThatThrownBy(() -> client.readActive(expiredHash)) + .isInstanceOf(IllegalStateException.class); + } + } + + private static AccountControlUiCoordination coordination( + AccountCoordinationPinnedConnectionProvider provider, + AcknowledgementRequirements acknowledgements) { + return new AccountControlUiCoordination(provider, acknowledgements, TEST_CATALOG); + } + + private static RedisScriptCatalog testCatalog() { + // The isolated fixture contributes the production descriptor as-is; it does not register it + // in Account's runtime ServiceLoader catalog or claim deployment/ACL registration. + RedisScriptContribution contribution = + new RedisScriptContribution() { + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + return List.of(AccountControlUiRegistryContract.descriptor()); + } + }; + RedisScriptCatalog catalog = RedisScriptCatalog.fromContributions(List.of(contribution)); + if (!AccountControlUiRegistryContract.descriptor() + .equals(catalog.require(AccountControlUiRegistryContract.SCRIPT_ID))) { + throw new IllegalStateException("Exact Account Control UI registry descriptor required"); + } + return catalog; + } + + private static void configureApplicationUser( + RedisCommands commands, String username, String password, boolean registry) { + if (registry) { + commands.aclSetuser( + username, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:auth:token:*") + // Narrow transport permissions required by this test's authenticated Lettuce client. + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.PEXPIRETIME) + .addCommand(CommandType.TIME)); + // WAITAOF is newer than this Lettuce version's CommandType catalog, so use its supported + // low-level command dispatch to add only that exact top-level ACL command. + commands.dispatch( + TestAclSetuser.INSTANCE, + new StatusOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE).add("SETUSER").add(username).add("+waitaof")); + } else { + // The isolated Redis contains only synthetic test records. The wrong principal receives + // read/physical-expiry access to that key family, but no registry-write or script rights. + commands.aclSetuser( + username, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:auth:token:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.GET) + .addCommand(CommandType.PEXPIRETIME)); + } + } + + private static void awaitLocalAndReplicaAof(RedisCommands commands) + throws InterruptedException { + byte[] probeKey = bytes("test-only:account-coordination-aof-probe:" + UUID.randomUUID()); + commands.set(probeKey, bytes("test-only-replication-probe")); + long deadline = System.nanoTime() + java.time.Duration.ofSeconds(30).toNanos(); + while (System.nanoTime() < deadline) { + List counts = + commands.dispatch( + TestWaitAof.INSTANCE, + new ArrayOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE).add(1).add(1).add(500)); + if (hasAofCounts(counts, 1, 1)) { + return; + } + Thread.sleep(50); + } + throw new IllegalStateException("Test Coordination Redis replica did not acknowledge AOF"); + } + + private static boolean hasAofCounts(List counts, long local, long replicas) { + return counts != null + && counts.size() == 2 + && counts.get(0) instanceof Long observedLocal + && counts.get(1) instanceof Long observedReplicas + && observedLocal >= local + && observedReplicas >= replicas; + } + + private static byte[] adminGet(byte[] key) { + try (var connection = adminClient.connect(ByteArrayCodec.INSTANCE)) { + return connection.sync().get(key); + } + } + + private static void adminSetWithExpiry(byte[] key, byte[] value, long expiryMillis) { + try (var connection = adminClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = connection.sync(); + commands.set(key, value); + commands.pexpireat(key, expiryMillis); + } + } + + private static void adminSetExpiry(byte[] key, long expiryMillis) { + try (var connection = adminClient.connect(ByteArrayCodec.INSTANCE)) { + connection.sync().pexpireat(key, expiryMillis); + } + } + + private static RedisClient client(String username, String password) { + RedisURI.Builder uri = + RedisURI.Builder.redis(primary.getHost(), primary.getMappedPort(REDIS_PORT)); + if (username != null) { + uri.withAuthentication(username, password); + } + RedisClient client = RedisClient.create(uri.build()); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + private static byte[] syntheticRecord( + String tokenHash, String state, long expiryEpochSecond, String testOnlyBinding) { + return AccountControlUiAuthority.canonical( + Map.of( + "schemaVersion", + 1, + "registryVersion", + "active".equals(state) ? 2 : 1, + "profile", + "control-ui", + "type", + "control-ui", + "audience", + "control-ui", + "issuer", + "firemud-account-service", + "tokenHash", + tokenHash, + "state", + state, + "exp", + expiryEpochSecond, + "testOnlyBinding", + testOnlyBinding)); + } + + private static String tokenHash() { + return AccountControlUiIssuanceRepository.hash( + bytes("test-only-control-ui-registry/" + UUID.randomUUID())); + } + + private static byte[] key(String tokenHash) { + return bytes("session:auth:token:" + tokenHash); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static final class PinnedAccountConnection + implements AccountCoordinationPinnedConnectionProvider, AutoCloseable { + private final RedisClient client; + private final AtomicInteger openedConnections = new AtomicInteger(); + + PinnedAccountConnection(String username, String password) { + client = client(username, password); + } + + @Override + public StatefulRedisConnection openPinnedConnection() { + openedConnections.incrementAndGet(); + return client.connect(ByteArrayCodec.INSTANCE); + } + + int openedConnections() { + return openedConnections.get(); + } + + @Override + public void close() { + client.shutdown(); + } + } + + private enum TestWaitAof implements ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "WAITAOF".getBytes(StandardCharsets.US_ASCII); + } + } + + private enum TestAclSetuser implements ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "ACL".getBytes(StandardCharsets.US_ASCII); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeSigningSpecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeSigningSpecTest.java index d736999f8b..0bd4f21164 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeSigningSpecTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeSigningSpecTest.java @@ -34,12 +34,22 @@ void acceptsAccountCanaryAndEveryProtectedProductionProfile() { } @Test - void acceptsGameSessionCanaryAndItsOnlyProtectedProductionProfile() { + void permitsCanonicalProfilesForGameSessionInapplicableRejectionProbes() { assertValid( AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, ProbeKind.CANARY, AccountMountedJwtSignerBundle.READINESS_CANARY_PROFILE, AccountMountedJwtSignerBundle.READINESS_CANARY_AUDIENCE); + assertValid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + "control-ui", + "control-ui"); + assertValid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + "player-bootstrap", + "player-bootstrap"); assertValid( AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, ProbeKind.REPRESENTATIVE, @@ -48,21 +58,21 @@ void acceptsGameSessionCanaryAndItsOnlyProtectedProductionProfile() { } @Test - void rejectsUnknownAndCrossValidatorProfileAudienceCombinations() { + void rejectsUnknownValidatorAndMismatchedProfileAudienceCombinations() { assertInvalid( "unknown-service", ProbeKind.CANARY, AccountMountedJwtSignerBundle.READINESS_CANARY_PROFILE, AccountMountedJwtSignerBundle.READINESS_CANARY_AUDIENCE); assertInvalid( - AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, ProbeKind.REPRESENTATIVE, - "control-ui", + AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, "control-ui"); assertInvalid( - AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, ProbeKind.REPRESENTATIVE, - AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, + "player-bootstrap", "control-ui"); assertInvalid( AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, From e414c67baf2af86d5051c9b21ec14d28841a6677 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:06:19 +1300 Subject: [PATCH 024/129] Define composed Account issuer and exact recovery PostgreSQL proof --- ...iOwnerWorkflowPostgresIntegrationTest.java | 32 +- ...iPositiveOwnerPostgresIntegrationTest.java | 1209 +++++++++++++++++ 2 files changed, 1232 insertions(+), 9 deletions(-) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java index d449f27fda..fe729b45f4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java @@ -101,9 +101,9 @@ @Testcontainers(disabledWithoutDocker = true) class AccountControlUiOwnerWorkflowPostgresIntegrationTest { private static final String NAMESPACE = "control-ui-owner-proof"; - private static final String CALLER = + static final String CALLER = "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; - private static final String OTP = "test-only-original-creator-otp"; + static final String OTP = "test-only-original-creator-otp"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -236,7 +236,7 @@ void changedProtectedCallerAndUnboundCurrentEnvironmentDenyWithoutConsumingOtp() f.assertNoIssuance(); } - private static final class Fixture { + static final class Fixture { final DSLContext dsl; final TransactionTemplate transactions; final Account account; @@ -250,8 +250,18 @@ private static final class Fixture { final AccountHostedTermsService terms; final AccountControlUiAuthority authority; final AccountControlUiIssuanceService service; + final DataSourceTransactionManager manager; + final DraftAuthorizationFenceRepository fences; + final AccountServiceImpl primary; Fixture(Path root) { + this(root, true); + } + + /** + * Reuses actual Account/source/auth owners while a composed test supplies signer/Redis owners. + */ + Fixture(Path root, boolean installNegativeIssuer) { String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); var dataSource = new DriverManagerDataSource( @@ -265,7 +275,7 @@ private static final class Fixture { .locations("classpath:db/migration") .load() .migrate(); - var manager = new DataSourceTransactionManager(dataSource); + manager = new DataSourceTransactionManager(dataSource); transactions = new TransactionTemplate(manager); transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); @@ -346,7 +356,7 @@ private static final class Fixture { insertTestParty(dsl, party); var parties = new IndividualCreatorPartyRepository(dsl, fresh, bootstrapOperations); tx(() -> parties.associateFresh(UUID.randomUUID(), creator, party)); - var fences = new DraftAuthorizationFenceRepository(dsl); + fences = new DraftAuthorizationFenceRepository(dsl); Map publications = new HashMap<>(); Map actions = new HashMap<>(); Map bindings = new HashMap<>(); @@ -430,7 +440,7 @@ private static final class Fixture { challenge.setUpdatedAt(now); return challenges.save(challenge); }); - var primary = + var primaryTarget = new AccountServiceImpl( accounts, null, @@ -458,11 +468,15 @@ private static final class Fixture { null, manager); // Exercise the real MANDATORY interceptor: noRollbackFor must not poison the owner callback. - var primaryProxy = new ProxyFactory(primary); + var primaryProxy = new ProxyFactory(primaryTarget); primaryProxy.setProxyTargetClass(true); primaryProxy.addAdvice( new TransactionInterceptor(manager, new AnnotationTransactionAttributeSource())); primary = (AccountServiceImpl) primaryProxy.getProxy(); + if (!installNegativeIssuer) { + service = null; + return; + } var signerRepository = new AccountJwtSignerDesiredStateRepository(dsl); var trust = new AccountJwtSignerMaterializerTrustBinding(false, ""); var api = new AccountJwtJwksApiBinding(); @@ -604,14 +618,14 @@ private static void requireOutsideTransaction() { } } - private static PeerScope withPeer(String uri) { + static PeerScope withPeer(String uri) { var attached = Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); return new PeerScope(attached.attach(), attached); } - private record PeerScope(Context previous, Context attached) implements AutoCloseable { + record PeerScope(Context previous, Context attached) implements AutoCloseable { @Override public void close() { attached.detach(previous); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java new file mode 100644 index 0000000000..4e8763372a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -0,0 +1,1209 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import io.grpc.stub.StreamObserver; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.codec.ByteArrayCodec; +import java.math.BigInteger; +import java.net.URI; +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.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collection; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import net.firedevops.firemud.account.v1.EnrollBootstrapRequest; +import net.firedevops.firemud.account.v1.EnrollBootstrapResponse; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; +import net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity; +import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; +import net.firedevops.firemud.account.v1.RecordSecretObservationRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtSignerMaterializationService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** + * Isolated positive Account storage/producer proof with explicitly stipulated upstream trust, + * materializer Secret observations, validator inventory/acceptance and external creator/legal + * evidence. Generated ephemeral key custody and test-only ConfigMap CAS replace platform delivery. + * Real Account repositories, transactions, coordinator, materialization RPC owner, mounted signer, + * issuance, physical Coordination Redis and actor/order owners execute. No production trust, + * deployed Pod attribution, World APPLIED, public wiring or runtime activation is established. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountControlUiPositiveOwnerPostgresIntegrationTest { + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String SECRET_UID = "33333333-3333-4333-8333-333333333333"; + private static final String CONFIG_MAP_UID = "44444444-4444-4444-8444-444444444444"; + private static final String TRUST_REVISION = "trust-r1"; + private static final String MATERIALIZER_URI = + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + private static final List MATERIALIZER_PINS = List.of("c".repeat(64)); + private static final String TRUST_DIGEST = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + TRUST_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + MATERIALIZER_PINS); + private static final String API_DIGEST = "b".repeat(64), API_REVISION = "api-r1"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Network NETWORK = Network.newNetwork(); + private static final String PASSWORD = UUID.randomUUID().toString(); + + @Container + static final PostgreSQLContainer postgres = + AccountControlUiOwnerWorkflowPostgresIntegrationTest.postgres; + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("positive-control-ui-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "positive-control-ui-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() throws Exception { + var f = new AccountControlUiOwnerWorkflowPostgresIntegrationTest.Fixture(temporary, false); + var lifecycle = new SignerLifecycle(f, temporary); + lifecycle.commit(); + // This is the actual private lifecycle-derived signer receipt, never a handcrafted Capture. + var originalSigner = f.tx(lifecycle.signer::captureCurrent); + assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) + .isEqualTo(originalSigner.receipt()); + custody("encryption", "enc1", 11); + custody("request-mac", "mac1", 29); + try (var connections = new RedisFixture()) { + var admin = connections.admin; + var accountClient = connections.account; + try (var connection = admin.connect(ByteArrayCodec.INSTANCE)) { + connection + .sync() + .aclSetuser( + "account_coord_app", + new io.lettuce.core.AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern("session:auth:token:*") + .addCommand(io.lettuce.core.protocol.CommandType.HELLO) + .addCommand(io.lettuce.core.protocol.CommandType.PING) + .addCommand( + io.lettuce.core.protocol.CommandType.CLIENT, + io.lettuce.core.protocol.CommandKeyword.SETINFO) + .addCommand( + io.lettuce.core.protocol.CommandType.ACL, + io.lettuce.core.protocol.CommandKeyword.WHOAMI) + .addCommand( + io.lettuce.core.protocol.CommandType.SCRIPT, + io.lettuce.core.protocol.CommandKeyword.LOAD) + .addCommand(io.lettuce.core.protocol.CommandType.EVALSHA) + .addCommand(io.lettuce.core.protocol.CommandType.GET) + .addCommand(io.lettuce.core.protocol.CommandType.SET) + .addCommand(io.lettuce.core.protocol.CommandType.PEXPIRETIME) + .addCommand(io.lettuce.core.protocol.CommandType.TIME)); + connection + .sync() + .dispatch( + TestAclCommand.INSTANCE, + new io.lettuce.core.output.StatusOutput<>(ByteArrayCodec.INSTANCE), + new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) + .add("SETUSER") + .add("account_coord_app") + .add("+waitaof")); + awaitLocalAndReplicaAof(connection.sync()); + } + var registry = + new AccountControlUiCoordination( + () -> accountClient.connect(ByteArrayCodec.INSTANCE), + new AccountGameplayDelegationRedisClient.AcknowledgementRequirements(1, 1, 5000), + testCatalog()); + var operations = new AccountControlUiIssuanceRepository(f.dsl); + var publicSource = + new AccountJwtJwksTrustedSource( + lifecycle.client, + lifecycle.trust, + lifecycle.desired, + lifecycle.publication, + f.manager); + var actors = + new AccountControlUiActorService( + operations, + f.authority, + lifecycle.signer, + registry, + publicSource, + f.fences, + f.manager, + Clock.systemUTC()); + var issuance = + new AccountControlUiIssuanceService( + f.primary, + operations, + f.authority, + f.fences, + lifecycle.signer, + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary.resolve("custody")), Clock.systemUTC()), + registry, + actors, + f.manager, + Clock.systemUTC(), + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + String compact; + byte[] originalCompact; + Instant originalExpiry, originalRecoveryExpiry; + try (var peer = + AccountControlUiOwnerWorkflowPostgresIntegrationTest.withPeer( + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER); + var issued = + issuance.issue( + f.request(AccountControlUiOwnerWorkflowPostgresIntegrationTest.OTP), + environment)) { + originalCompact = issued.compactBytes(); + compact = new String(originalCompact, StandardCharsets.US_ASCII); + originalExpiry = issued.expiresAt(); + originalRecoveryExpiry = issued.recoveryExpiresAt(); + } + assertThat(f.challenges.findByAccountId(f.account.getId())).isEmpty(); + var originalOperation = f.tx(() -> operations.findRequest(f.request)); + var originalEnvelope = f.tx(() -> operations.envelope(originalOperation)); + // Simulate loss of the completed response: recover with the original, now-consumed OTP. + // No new challenge or primary-auth credential is installed before the exact retry. + try (var peer = + AccountControlUiOwnerWorkflowPostgresIntegrationTest.withPeer( + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER); + var recovered = + issuance.issue( + f.request(AccountControlUiOwnerWorkflowPostgresIntegrationTest.OTP), + environment)) { + assertThat(recovered.compactBytes()).isEqualTo(originalCompact); + assertThat(recovered.expiresAt()).isEqualTo(originalExpiry); + assertThat(recovered.recoveryExpiresAt()).isEqualTo(originalRecoveryExpiry); + assertThatThrownBy(() -> issuance.issue(f.request("changed-original-otp"), environment)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Control-ui issuance idempotency conflict"); + } + assertThat(f.challenges.findByAccountId(f.account.getId())).isEmpty(); + var recoveredOperation = f.tx(() -> operations.findRequest(f.request)); + assertThat(recoveredOperation.operationId).isEqualTo(originalOperation.operationId); + assertThat(recoveredOperation.status).isEqualTo("COMMITTED"); + assertThat(recoveredOperation.tokenHash).isEqualTo(originalOperation.tokenHash); + assertThat(recoveredOperation.claims).isEqualTo(originalOperation.claims); + var recoveredEnvelope = f.tx(() -> operations.envelope(recoveredOperation)); + assertThat(recoveredEnvelope.encrypted()).isEqualTo(originalEnvelope.encrypted()); + assertThat(recoveredEnvelope.binding()).isEqualTo(originalEnvelope.binding()); + assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))) + .isEqualTo(1); + assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isEqualTo(1); + var actor = actors.authenticate(compact, f.tenant, environment); + assertThat(actor.accountId()).isEqualTo(f.account.getAccountUuid()); + var snapshot = f.tx(() -> f.authority.captureInitial(f.tenant, environment)); + var binding = originalBinding(f, snapshot.sources()); + var claimed = actors.claimOriginalDraft(compact, binding, environment); + assertThat(claimed.ordering().name()).isEqualTo("COMMIT_ORDER"); + assertOrder(actors.claimOriginalDraft(compact, binding, environment), binding); + assertOrder(f.tx(() -> f.fences.read(binding)), binding); + assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))) + .isEqualTo(1); + assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isEqualTo(1); + String tokenHash = + AccountControlUiIssuanceRepository.hash(compact.getBytes(StandardCharsets.US_ASCII)); + var retained = f.tx(() -> operations.findToken(tokenHash)); + assertThat(retained.status).isEqualTo("COMMITTED"); + assertThat(retained.signerReceipt).isEqualTo(originalSigner.receipt()); + var active = registry.readActive(tokenHash); + assertThat(active).isNotEmpty(); + var committed = f.tx(() -> operations.requireCommitted(operations.findToken(tokenHash))); + var insufficientAck = + new AccountControlUiCoordination( + () -> accountClient.connect(ByteArrayCodec.INSTANCE), + new AccountGameplayDelegationRedisClient.AcknowledgementRequirements(1, 2, 1000), + testCatalog()); + assertThatThrownBy(() -> insufficientAck.activate(committed)) + .isInstanceOf(IllegalStateException.class); + assertThat(registry.readActive(tokenHash)).isEqualTo(active); + // An exact actor cannot claim an original binding whose retained Account source is changed. + var changed = new ArrayList<>(snapshot.sources()); + var first = changed.getFirst(); + changed.set( + 0, + new DraftAuthorizationFenceBinding.SourceEvidence( + first.kind(), + first.scopeId(), + first.generation(), + first.sourceVersion(), + first.checkpointStream(), + first.checkpointSequence(), + new byte[] {99})); + var changedBinding = originalBinding(f, changed); + assertThatThrownBy(() -> actors.claimOriginalDraft(compact, changedBinding, environment)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact current authenticated initial creator required"); + assertOrder(f.tx(() -> f.fences.read(binding)), binding); + } + } + + private static DraftAuthorizationFenceBinding originalBinding( + AccountControlUiOwnerWorkflowPostgresIntegrationTest.Fixture f, + List sources) { + var complete = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + f.tenant, + UUID.randomUUID(), + 1, + "test-game-key", + 2, + "test-game-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "test-only-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-only-world-input")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + sources); + } + + private final class SignerLifecycle { + final AccountControlUiOwnerWorkflowPostgresIntegrationTest.Fixture f; + final AccountJwtSignerDesiredStateRepository desired; + final AccountJwtJwksPublicationRepository publication; + final AccountJwtReadinessProbeRepository readiness; + final AccountJwtSignerMaterializerTrustBinding trust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + final AccountJwtJwksApiBinding api = mock(AccountJwtJwksApiBinding.class); + final AccountJwtJwksConfigMapClient client = mock(AccountJwtJwksConfigMapClient.class); + final AccountJwtValidatorInventorySource inventory = + mock(AccountJwtValidatorInventorySource.class); + final AtomicReference configMap = + new AtomicReference<>( + new AccountJwtJwksConfigMapClient.ConfigMapSnapshot( + CONFIG_MAP_UID, "41", Map.of("jwks.json", "{\"keys\":[]}"))); + final Path privateRoot, publicRoot; + final AccountJwtSignerBootstrapCoordinator coordinator; + final AccountJwtSignerMaterializationService materializer; + final AccountControlUiSignerOwner signer; + + SignerLifecycle(AccountControlUiOwnerWorkflowPostgresIntegrationTest.Fixture fixture, Path root) + throws Exception { + f = fixture; + privateRoot = Files.createDirectories(root.resolve("private")); + publicRoot = Files.createDirectories(root.resolve("public")); + desired = new AccountJwtSignerDesiredStateRepository(f.dsl); + publication = new AccountJwtJwksPublicationRepository(f.dsl, desired); + readiness = new AccountJwtReadinessProbeRepository(f.dsl, desired, publication); + when(trust.current()).thenReturn(Optional.of(materializerBinding())); + when(api.current()) + .thenReturn( + new AccountJwtJwksApiBinding.ParsedBinding( + API_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + URI.create("https://kubernetes.default.svc:6443/"), + "kubernetes.default.svc", + root.resolve("test-only-ca"), + "d".repeat(64), + root.resolve("test-only-bearer"), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + "system:serviceaccount:firemud-prod:account-service", + API_DIGEST)); + when(client.identity()) + .thenReturn( + new AccountJwtJwksConfigMapClient.BindingIdentity( + API_DIGEST, + API_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + "https://kubernetes.default.svc:6443/", + "kubernetes.default.svc", + "d".repeat(64), + "system:serviceaccount:firemud-prod:account-service")); + when(client.observe()).thenAnswer(ignored -> configMap.get()); + when(client.publish(any(), any())) + .thenAnswer(call -> publish(call.getArgument(0), call.getArgument(1))); + when(client.publishActiveProjection(any(), any(), any())) + .thenAnswer(call -> publish(call.getArgument(0), call.getArgument(2))); + when(inventory.observe(any(ObservationContext.class))) + .thenAnswer(call -> completeInventorySnapshot(now(), call.getArgument(0))); + var mounted = + new AccountJwtJwksPrepublicationService.MountedProjection( + privateRoot, + Path.of("pending.key"), + publicRoot, + Path.of("jwks.json"), + Path.of("jwt-generation.json")); + var prepublication = + new AccountJwtJwksPrepublicationService( + desired, publication, trust, client, f.manager, mounted); + var beans = new StaticListableBeanFactory(); + beans.addBean("testOnlyInventoryInput", inventory); + coordinator = + new AccountJwtSignerBootstrapCoordinator( + trust, + client, + desired, + prepublication, + readiness, + beans.getBeanProvider(AccountJwtValidatorInventorySource.class), + f.transactions); + beans.addBean("actualAccountCoordinator", coordinator); + materializer = + new AccountJwtSignerMaterializationService( + desired, + readiness, + trust, + f.manager, + beans.getBeanProvider(AccountJwtSignerBootstrapCoordinator.class), + beans.getBeanProvider(AccountJwtValidatorInventorySource.class)); + signer = new AccountControlUiSignerOwner(desired, trust, api, privateRoot, publicRoot); + } + + AccountJwtJwksConfigMapClient.CasObservation publish( + AccountJwtJwksConfigMapClient.ConfigMapSnapshot expected, Map data) + throws Exception { + assertThat(configMap.get()).isEqualTo(expected); + var next = + new AccountJwtJwksConfigMapClient.ConfigMapSnapshot( + CONFIG_MAP_UID, Long.toString(Long.parseLong(expected.resourceVersion()) + 1), data); + configMap.set(next); + for (var entry : data.entrySet()) + Files.writeString(publicRoot.resolve(entry.getKey()), entry.getValue()); + return new AccountJwtJwksConfigMapClient.CasObservation( + CONFIG_MAP_UID, + expected.resourceVersion(), + next.resourceVersion(), + data, + data, + AccountJwtJwksConfigMapClient.Outcome.APPLIED); + } + + void commit() throws Exception { + // Only the protected upstream identity is stipulated; every owner method/transaction is real. + try (var authenticated = mockStatic(AccountJwtSignerMaterializerTlsInterceptor.class)) { + authenticated + .when(AccountJwtSignerMaterializerTlsInterceptor::authenticatedBinding) + .thenReturn(materializerBinding()); + AccountControlUiPositiveOwnerPostgresIntegrationTest.rpc( + out -> + materializer.enrollBootstrap( + EnrollBootstrapRequest.newBuilder().setSchemaVersion(1).build(), out)); + GetCurrentGenerationRequestResponse initial = + rpc( + out -> + materializer.getCurrentGenerationRequest( + GetCurrentGenerationRequestRequest.newBuilder().setSchemaVersion(1).build(), + out)); + var request = f.tx(() -> desired.readCurrentGenerationRequest(BINDING, trust())); + GetCurrentGenerationRequestResponse observed = + rpc( + out -> + materializer.recordSecretObservation( + RecordSecretObservationRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(initial.getOperationId()) + .setOperationDigest(initial.getOperationDigest()) + .setSecretUid(SECRET_UID) + .setObservedResourceVersion("12") + .build(), + out)); + var pair = generateRsa3072(); + var publicKey = publicJwk(request.targetKid(), (RSAPublicKey) pair.getPublic()); + RecordGenerationResultResponse recorded = + rpc( + out -> + materializer.recordGenerationResult( + RecordGenerationResultRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(initial.getOperationId()) + .setGenerationRequestDigest(observed.getGenerationRequestDigest()) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion("12") + .setObservedResourceVersion("13") + .setPublicJwkJson(publicKey.json()) + .build(), + out)); + var result = f.tx(() -> desired.readCurrentGenerationResult(BINDING, trust())); + assertThat(recorded.getOperationId()).isEqualTo(result.operationId().toString()); + assertThat(recorded.getOperationDigest()).isEqualTo(result.operationDigest()); + assertThat(recorded.getGenerationRequestDigest()) + .isEqualTo(result.generationRequestDigest()); + assertThat(recorded.getGenerationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(recorded.getObservedResourceVersion()) + .isEqualTo(result.observedResourceVersion()); + assertThat(recorded.getPublicKeyFingerprint()).isEqualTo(result.publicKeyFingerprint()); + Files.writeString( + privateRoot.resolve("pending.key"), privateBundleJson(request, result, pair)); + assertThat( + coordinator + .reconcileCurrentGenerationOnce(result.operationId()) + .publicKeyPrepublished()) + .isTrue(); + var context = + f.tx(() -> readiness.readCurrentInventoryObservationContext(BINDING, trust())); + var plannedAt = now().minusSeconds(300); + var planned = completeInventorySnapshot(plannedAt, context); + var plan = f.tx(() -> readiness.planCurrent(BINDING, trust(), plannedAt, planned)); + var harnessUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"; + var harnessPin = "e".repeat(64); + long validUntil = now().plusSeconds(3600).getEpochSecond(); + String readinessDigest = + net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding + .computeBindingDigest( + "test-readiness-r1", + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + harnessUri, + List.of(harnessPin), + "test-only-validator", + validUntil); + var harness = + new net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding + .Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + harnessUri, + List.of(harnessPin), + "test-readiness-r1", + "account-service", + "test-only-validator", + validUntil, + readinessDigest); + var peer = + new net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding + .PeerIdentity(harnessUri, harnessPin); + var claim = + f.tx(() -> readiness.claimSingleDelivery(BINDING, trust(), plan, harness, peer, now())); + var producer = + new AccountJwtReadinessProbeService( + readiness, + f.transactions, + Clock.systemUTC(), + privateRoot, + Path.of("pending.key"), + publicRoot, + Path.of("jwks.json")); + var delivered = + producer.issueCurrentPlan( + BINDING, + trust(), + result.operationId(), + claim, + (metadata, compact) -> { + assertThat(compact).isNotEmpty(); + var issued = + f + .tx( + () -> + readiness.readCurrentPlan(BINDING, trust(), result.operationId())) + .entries() + .stream() + .filter(entry -> entry.jti().equals(metadata.jti())) + .findFirst() + .orElseThrow(); + var current = completeInventorySnapshot(now(), context); + var pods = + f.tx( + () -> + readiness.readCurrentExpectedPods(BINDING, trust(), issued, current)); + for (var pod : pods) { + var acceptance = + testAuthenticatedAcceptance(issued, pod, now().getEpochSecond()); + f.tx( + () -> + readiness.recordPodAcceptance( + BINDING, trust(), issued, pod, acceptance, current)); + } + }); + assertThat(delivered) + .hasSize(8) + .allSatisfy( + entry -> + assertThat(entry.state()) + .isEqualTo(AccountJwtReadinessProbeRepository.ProbeState.VERIFIED)); + assertThat(f.dsl.fetchCount(DSL.table("account_jwt_readiness_pod_receipts"))).isEqualTo(12); + assertThat( + f.dsl.fetchCount( + DSL.table("account_jwt_readiness_pod_receipts"), + DSL.field("outcome").eq("INAPPLICABLE_REJECT"))) + .isEqualTo(2); + var prepared = coordinator.prepareCurrentPromotionOnce().orElseThrow(); + GetCurrentPromotionRequestResponse dispatched = + rpc( + out -> + materializer.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + out)); + var promotion = + f.tx(() -> desired.readPreparedGenerationForRecovery(BINDING, trust())).promotion(); + assertThat(prepared.operationId()).isEqualTo(promotion.operationId()); + assertThat(dispatched.getPromotionOperationId()) + .isEqualTo(promotion.operationId().toString()); + assertThat(dispatched.getPromotionRequestDigest()).isEqualTo(promotion.requestDigest()); + assertThat(dispatched.getGenerationOperationId()) + .isEqualTo(result.operationId().toString()); + assertThat(dispatched.getGenerationOperationDigest()).isEqualTo(result.operationDigest()); + assertThat(dispatched.getGenerationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(dispatched.getExpectedSecretUid()).isEqualTo(promotion.secretUid()); + assertThat(dispatched.getExpectedSecretResourceVersion()) + .isEqualTo(promotion.expectedPrivateResourceVersion()); + Files.writeString( + privateRoot.resolve("current.key"), privateBundleJson(request, result, pair)); + RecordPrivatePromotionResultResponse committed = + rpc( + out -> + materializer.recordPrivatePromotionResult( + RecordPrivatePromotionResultRequest.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(promotion.operationId().toString()) + .setPromotionRequestDigest(promotion.requestDigest()) + .setGenerationOperationId(result.operationId().toString()) + .setGenerationOperationDigest(result.operationDigest()) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion( + promotion.expectedPrivateResourceVersion()) + .setObservedResourceVersion("14") + .setCurrent( + PromotionPublicKeyIdentity.newBuilder() + .setGeneration(result.targetGeneration()) + .setKid(result.targetKid()) + .setPublicKeyFingerprint(result.publicKeyFingerprint())) + .addResultingSlots("current") + .build(), + out)); + var durableCommit = + f.tx( + () -> + desired.readCurrentCommittedSigner( + BINDING, trust(), API_DIGEST, API_REVISION)) + .orElseThrow(); + assertThat(committed.getPromotionOperationId()) + .isEqualTo(durableCommit.promotion().operationId().toString()); + assertThat(committed.getGenerationOperationId()) + .isEqualTo(durableCommit.generationResult().operationId().toString()); + assertThat(committed.getObservedResourceVersion()) + .isEqualTo(durableCommit.privateReceipt().observedResourceVersion()); + assertThat(committed.getPublicReceiptDigest()) + .isEqualTo(durableCommit.privateReceipt().receiptDigest()); + } + } + } + + private static T rpc(Consumer> invocation) { + AtomicReference result = new AtomicReference<>(); + AtomicReference failure = new AtomicReference<>(); + invocation.accept( + new StreamObserver<>() { + @Override + public void onNext(T value) { + result.set(value); + } + + @Override + public void onError(Throwable error) { + failure.set(error); + } + + @Override + public void onCompleted() {} + }); + if (failure.get() != null) + throw new AssertionError("Actual Account materialization RPC failed", failure.get()); + return java.util.Objects.requireNonNull(result.get()); + } + + private static RedisClient redisClient(boolean application) { + var uri = RedisURI.Builder.redis(redis.getHost(), redis.getMappedPort(6379)); + if (application) uri.withAuthentication("account_coord_app", PASSWORD); + var result = RedisClient.create(uri.build()); + result.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return result; + } + + private static RedisScriptCatalog testCatalog() { + return RedisScriptCatalog.fromContributions( + List.of( + new RedisScriptContribution() { + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + return List.of(AccountControlUiRegistryContract.descriptor()); + } + })); + } + + private void custody(String purpose, String id, int value) throws Exception { + byte[] key = new byte[32]; + java.util.Arrays.fill(key, (byte) value); + var directory = Files.createDirectories(temporary.resolve("custody").resolve(purpose)); + Files.writeString( + directory.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive " + + id + + " " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n"); + } + + private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + + private static void assertOrder( + net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository + .FenceSnapshot + observed, + DraftAuthorizationFenceBinding binding) { + assertThat(observed.ordering().name()).isEqualTo("COMMIT_ORDER"); + assertThat(observed.binding()).isEqualTo(binding.canonicalBytes()); + assertThat(observed.orderedAt()).isNotNull(); + } + + private static final class RedisFixture implements AutoCloseable { + final RedisClient admin = redisClient(false), account = redisClient(true); + + @Override + public void close() { + account.shutdown(); + admin.shutdown(); + } + } + + private static void awaitLocalAndReplicaAof( + io.lettuce.core.api.sync.RedisCommands commands) throws InterruptedException { + byte[] probeKey = + ("test-only:positive-account-coordination-aof-probe:" + UUID.randomUUID()) + .getBytes(StandardCharsets.US_ASCII); + commands.set(probeKey, "test-only-replication-probe".getBytes(StandardCharsets.US_ASCII)); + long deadline = System.nanoTime() + java.time.Duration.ofSeconds(30).toNanos(); + while (System.nanoTime() < deadline) { + List counts = + commands.dispatch( + TestWaitAof.INSTANCE, + new io.lettuce.core.output.ArrayOutput<>(ByteArrayCodec.INSTANCE), + new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) + .add(1) + .add(1) + .add(500)); + if (counts != null + && counts.size() == 2 + && counts.get(0) instanceof Long local + && counts.get(1) instanceof Long replicas + && local >= 1 + && replicas >= 1) { + return; + } + Thread.sleep(50); + } + throw new IllegalStateException("Test Coordination Redis replica did not acknowledge AOF"); + } + + private enum TestWaitAof implements io.lettuce.core.protocol.ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "WAITAOF".getBytes(StandardCharsets.US_ASCII); + } + } + + private enum TestAclCommand implements io.lettuce.core.protocol.ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "ACL".getBytes(StandardCharsets.US_ASCII); + } + } + + private static Instant now() { + return Instant.ofEpochSecond(Instant.now().getEpochSecond()); + } + + private static TrustFence trust() { + return new TrustFence(CLUSTER_UID, NAMESPACE_UID, TRUST_DIGEST, TRUST_REVISION); + } + + private static AccountJwtSignerMaterializerTrustBinding.Binding materializerBinding() { + return new AccountJwtSignerMaterializerTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + MATERIALIZER_PINS, + TRUST_REVISION, + TRUST_DIGEST); + } + + private static String privateBundleJson( + GenerationRequest request, GenerationResult result, KeyPair pair) { + Map bundle = new LinkedHashMap<>(); + bundle.put("version", 1); + bundle.put("environmentId", request.binding().environmentId()); + bundle.put("clusterId", request.binding().clusterId()); + bundle.put("namespace", request.binding().namespace()); + bundle.put("operationId", request.operationId().toString()); + bundle.put("generation", result.targetGeneration()); + bundle.put("kid", result.targetKid()); + bundle.put("algorithm", "RS256"); + bundle.put( + "privateKeyPkcs8", + Base64.getUrlEncoder().withoutPadding().encodeToString(pair.getPrivate().getEncoded())); + bundle.put("publicKeyFingerprint", result.publicKeyFingerprint()); + return JSON.writeValueAsString(bundle); + } + + private static PublicJwk publicJwk(String kid, RSAPublicKey key) throws Exception { + String modulus = encodeUnsigned(key.getModulus()); + String exponent = encodeUnsigned(key.getPublicExponent()); + Map jwk = new LinkedHashMap<>(); + jwk.put("alg", "RS256"); + jwk.put("e", exponent); + jwk.put("key_ops", List.of("verify")); + jwk.put("kid", kid); + jwk.put("kty", "RSA"); + jwk.put("n", modulus); + jwk.put("use", "sig"); + String json = canonicalJson(jwk); + Map withoutKeyOps = new LinkedHashMap<>(jwk); + withoutKeyOps.remove("key_ops"); + String jsonWithoutKeyOps = canonicalJson(withoutKeyOps); + String fingerprint = + sha256( + Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(Map.of("e", exponent, "kty", "RSA", "n", modulus)))); + return new PublicJwk(json, jsonWithoutKeyOps, fingerprint); + } + + private static String canonicalJson(Map value) throws Exception { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + private static KeyPair generateRsa3072() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3_072); + return generator.generateKeyPair(); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is required for the persistence fixture", ex); + } + } + + /** Stipulated platform input only; Account's real owners derive all private proof from it. */ + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, ObservationContext observationContext) { + return completeInventorySnapshot(observedAt, "10.11.0.11", observationContext); + } + + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, String firstAccountPodIp, ObservationContext observationContext) { + return completeInventorySnapshot( + observedAt, firstAccountPodIp, observationContext, "77777777-7777-4777-8777-777777777777"); + } + + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, + String firstAccountPodIp, + ObservationContext observationContext, + String firstAccountPodUid) { + String accountImage = "registry.example/account-validator@sha256:" + "1".repeat(64); + String gameSessionImage = "registry.example/game-session-validator@sha256:" + "3".repeat(64); + String accountConfigDigest = "2".repeat(64); + String gameSessionConfigDigest = "4".repeat(64); + String accountServiceUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator"; + String gameSessionServiceUri = "spiffe://firemud/ns/firemud-prod/sa/game-session-jwt-validator"; + List accountProfiles = + List.of( + new ProfileExpectation("control-ui", "control-ui"), + new ProfileExpectation("game-session-account-delegation", "account-service"), + new ProfileExpectation("player-bootstrap", "player-bootstrap")); + List gameSessionProfiles = + List.of(new ProfileExpectation("game-session-account-delegation", "account-service")); + List accountPods = + List.of( + inventoryPod( + "account-a", + firstAccountPodUid, + "account-rs", + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "acct1", + firstAccountPodIp, + 9443, + accountImage, + accountConfigDigest, + accountServiceUri, + "5".repeat(64)), + inventoryPod( + "account-b", + "88888888-8888-4888-8888-888888888888", + "account-rs", + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "acct1", + "10.11.0.12", + 9443, + accountImage, + accountConfigDigest, + accountServiceUri, + "6".repeat(64))); + List gameSessionPods = + List.of( + inventoryPod( + "game-session-a", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "game-session-rs", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "games", + "10.12.0.11", + 9444, + gameSessionImage, + gameSessionConfigDigest, + gameSessionServiceUri, + "7".repeat(64))); + List validators = + List.of( + new ValidatorObservation( + "account-service", + "account-service", + "66666666-6666-4666-8666-666666666666", + 1L, + "51", + 2, + accountImage, + accountConfigDigest, + 300, + accountProfiles, + accountPods, + List.of()), + new ValidatorObservation( + "game-session-service", + "game-session-service", + "99999999-9999-4999-8999-999999999999", + 1L, + "52", + 1, + gameSessionImage, + gameSessionConfigDigest, + 300, + gameSessionProfiles, + gameSessionPods, + List.of())); + List> validatorMaps = + List.of( + inventoryValidatorMap(validators.get(0), accountServiceUri, 9443), + inventoryValidatorMap(validators.get(1), gameSessionServiceUri, 9444)); + Map preimage = new LinkedHashMap<>(); + preimage.put("domain", "firemud-account-validator-inventory/v2"); + preimage.put("environmentId", BINDING.environmentId()); + preimage.put("clusterId", BINDING.clusterId()); + preimage.put("clusterIncarnationUid", CLUSTER_UID); + preimage.put("namespace", BINDING.namespace()); + preimage.put("namespaceUid", NAMESPACE_UID); + preimage.put("apiBindingRevision", API_REVISION); + preimage.put("apiBindingDigest", API_DIGEST); + preimage.put("inventoryBindingRevision", "inventory-r1"); + preimage.put("inventoryBindingDigest", "c".repeat(64)); + preimage.put( + "observationContext", + Map.of( + "purpose", observationContext.purpose().name(), + "operationId", observationContext.operationId().toString(), + "operationDigest", observationContext.operationDigest())); + preimage.put("validators", validatorMaps); + byte[] bytes; + try { + bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + } catch (Exception failure) { + throw new AssertionError(failure); + } + InventorySnapshot snapshot = mock(InventorySnapshot.class); + when(snapshot.observedAt()).thenReturn(observedAt); + when(snapshot.environmentId()).thenReturn(BINDING.environmentId()); + when(snapshot.clusterId()).thenReturn(BINDING.clusterId()); + when(snapshot.clusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(snapshot.namespace()).thenReturn(BINDING.namespace()); + when(snapshot.namespaceUid()).thenReturn(NAMESPACE_UID); + when(snapshot.apiBindingRevision()).thenReturn(API_REVISION); + when(snapshot.apiBindingDigest()).thenReturn(API_DIGEST); + when(snapshot.inventoryBindingRevision()).thenReturn("inventory-r1"); + when(snapshot.inventoryBindingDigest()).thenReturn("c".repeat(64)); + when(snapshot.observationContext()).thenReturn(Optional.of(observationContext)); + when(snapshot.validators()).thenReturn(validators); + when(snapshot.canonicalBytes()).thenReturn(bytes.clone()); + when(snapshot.digest()).thenReturn(sha256(bytes)); + return snapshot; + } + + private static PodObservation inventoryPod( + String name, + String uid, + String ownerName, + String ownerUid, + String podTemplateHash, + String podIp, + int receiverPort, + String image, + String configDigest, + String serviceUri, + String spkiDigest) { + String host = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + return new PodObservation( + name, + uid, + "11", + ownerName, + ownerUid, + podTemplateHash, + image, + configDigest, + podIp, + URI.create("grpcs://" + host + ":" + receiverPort), + serviceUri, + spkiDigest); + } + + private static Map inventoryValidatorMap( + ValidatorObservation validator, String serviceUri, int receiverPort) { + Map result = new LinkedHashMap<>(); + result.put("validatorId", validator.validatorId()); + result.put("deploymentName", validator.deploymentName()); + result.put("deploymentUid", validator.deploymentUid()); + result.put("deploymentGeneration", Long.toString(validator.deploymentGeneration())); + result.put("deploymentResourceVersion", validator.deploymentResourceVersion()); + result.put("replicas", Integer.toString(validator.replicas())); + result.put("image", validator.image()); + result.put("verifierConfigSha256", validator.verifierConfigSha256()); + result.put("maxCacheAgeSeconds", Integer.toString(validator.maxCacheAgeSeconds())); + result.put( + "profiles", + validator.profiles().stream() + .map( + profile -> + Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .toList()); + result.put( + "pods", + validator.pods().stream() + .map( + pod -> + Map.ofEntries( + Map.entry("name", pod.name()), + Map.entry("uid", pod.uid()), + Map.entry("resourceVersion", pod.resourceVersion()), + Map.entry("ownerReplicaSetName", pod.ownerName()), + Map.entry("ownerReplicaSetUid", pod.ownerUid()), + Map.entry("podTemplateHash", pod.podTemplateHash()), + Map.entry("image", pod.image()), + Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), + Map.entry("podIp", pod.podIp()), + Map.entry("exactPodEndpoint", pod.endpoint().toString()), + Map.entry("canonicalServiceUri", pod.receiverServiceUri()), + Map.entry("leafSpkiSha256", pod.leafSpkiSha256()))) + .toList()); + result.put("receiverServiceUri", serviceUri); + result.put("receiverPort", receiverPort); + result.put("replicaSets", List.of()); + return result; + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + long observedAtEpochSecond) { + return testAuthenticatedAcceptance( + entry, expectedPod, observedAtEpochSecond, entry.targetKid()); + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + long observedAtEpochSecond, + String verifiedKid) { + return testAuthenticatedAcceptance( + entry, + expectedPod, + observedAtEpochSecond, + verifiedKid, + expectedPod.target().exactPodEndpoint().orElseThrow().toString()); + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + long observedAtEpochSecond, + String verifiedKid, + String actualPodEndpoint) { + var target = expectedPod.target(); + return AccountJwtReadinessReceiverInvocationPort.authenticatedAcceptance( + target.podUid(), + actualPodEndpoint, + target.image(), + target.verifierConfigSha256(), + target.canonicalServiceUri().orElseThrow(), + target.podLeafSpkiSha256().orElseThrow(), + entry.jti(), + entry.compactTokenSha256().orElseThrow(), + verifiedKid, + target.expectation(), + observedAtEpochSecond); + } +} From 72d6c8a11d933c7d1fedba6876bb1577a3cad051 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:42:27 +1300 Subject: [PATCH 025/129] Compose real Account order with World application and preserve admission diagnostics --- ...ame-authoring-publishing-and-activation.md | 2 +- .../prove-protected-pod-boundary.sh | 19 +- .../protected-pod-live-proof-contract.sh | 20 +- services/account-service/build.gradle.kts | 39 + ...ccountJwtSignerDesiredStateRepository.java | 2 +- ...iOwnerWorkflowPostgresIntegrationTest.java | 498 +---------- ...iPositiveOwnerPostgresIntegrationTest.java | 798 +----------------- ...dinessProbePersistenceIntegrationTest.java | 30 +- .../AccountControlUiOriginalOrderFixture.java | 284 +++++++ .../AccountControlUiOwnerSourcesFixture.java | 498 +++++++++++ .../AccountControlUiSignerFixture.java | 791 +++++++++++++++++ .../world-management-service/build.gradle.kts | 1 + ...uthorizedDraftPostgresIntegrationTest.java | 778 +++++++++++++++++ 13 files changed, 2482 insertions(+), 1278 deletions(-) create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java 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 a0230e87be..af8e7734fa 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 @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The current Gameplay-prerequisite construction remains non-activating. Full-version finalization now reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. The real backend control-ui issuance/current-actor source, complete Account source-writer fencing and callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Earlier construction CI executed all four Account source-composition, five environment-binding and 31 Draft authorization PostgreSQL cases successfully, while three Game Design canonical-release fixtures failed for missing policy source capture. Their receiving correction now freezes actual Game Design command/policy source snapshots before sealing; corrected physical execution remains required. These bounded changes do not upgrade the broader capability ratings below. +The current Gameplay-prerequisite construction remains non-activating. Full-version finalization reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. Production backend control-ui issuance/current-actor integration, complete Account source-writer fencing and the callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. In particular, the distinct selected-publication operation still needs authenticated Account authorization; original Draft permission cannot substitute. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Construction CI at `f14c7950827dd435ac0fe5c4cc230a1de32fa96d` executed all 74 Game Design and 200 World integration cases without skips or failures, including the corrected canonical-release and selected-publication transaction regressions. Its 220 Account integration executions passed the future-terms, environment-binding, disclosure-handoff and three real Redis registry cases; one readiness-promotion fixture assertion still compared its initial plan with subsequently progressed entries. A corrected assertion and the composed Account-to-World handoff need separate validation. These bounded results do not upgrade the broader capability ratings below. The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read alone does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. At `ed928219ee3428073910f1845eaa975e8814a30a`, local validation is complete for the held-order/source-fencing batch, but physical PostgreSQL validation was skipped. The Account-owned disclosure journal now defines an immutable request, predecessor/candidate, effective instant, exact source vector and opaque authority binding, with exact dispatch/ambiguity/result readback. Its non-revoking preparation check refuses already-reserved or unsettled original operations under sorted source locks. The journal now serializes dispatch authorization and original reserve/claim under the same sorted source locks. PREPARED alone permits ordinary original acquisition; first dispatch rechecks exact settlement, while authorized, ambiguous or disclosed handoffs deny a new no-deadline order only for their exact changed terms source evidence. Existing original retries and obsolete source history do not acquire new authority or blanket-block unrelated sources. Focused both-ordering and concurrency proof definitions are present, but physical PostgreSQL execution remains required. This is still a bounded storage/ordering foundation: complete capture/currentness integration, authenticated notice production/readback and the physical World deadline gate remain unimplemented or unproved; there is no production disclosure/currentness path. Reconsider only after focused PostgreSQL proof covers both orderings of preparation versus original `COMMIT_ORDER` acquisition and settlement, every deadline-introduction path including environment binding, exact retry/restart/ambiguous-notice readback, and World commit-time denial at the disclosed instant without early ordinary-authoring freeze or date rewriting. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. The current catalog scheduling correction checks the exact operative terms source before introducing a future deadline, and a binding change checks existing predecessor/current sources only when it would newly expose a different scope's scheduled future deadline. Focused PostgreSQL definitions cover denial while an original operation is unsettled, exact request retry after owner settlement, same-scope non-introducing binding refresh, and the existing non-deadline pending behavior; the consolidated Account gate passed, but these PostgreSQL cases skipped locally without Docker and still require physical execution. This adds local ordering/denial proof only: actual notice dispatch, authenticated production authority and World commit-time enforcement remain unavailable. Future-only proposal/final-result digest design: exclude generated notice-result fields alone from the pre-disclosure proposal digest; bind all exact source, document, materiality, operator, scope, effective-time and authorized-notice inputs; then bind the unchanged proposal together with the authenticated result into the final catalog. `candidateDigest` remains opaque/uncomputed today, so this is a future design note, not a present digest-cycle defect. diff --git a/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh b/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh index c2a4f5a465..b6ac8f68c4 100644 --- a/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh +++ b/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh @@ -139,8 +139,23 @@ def probe(description, body, policy=None, message=None, path=None): rejection = (r"ValidatingAdmissionPolicy [\"']" + re.escape(policy) + r"[\"'] with binding [\"']" + re.escape(policy) + r"[\"'] denied request: " + re.escape(message)) - if result.returncode == 0 or not re.search(rejection, result.stderr): - fail(description + ": expected exact named admission denial was not observed") + if result.returncode == 0: + reason = "unexpected success; request was accepted instead of denied" + elif re.search(rejection, result.stderr): + reason = None + elif re.search(r"ValidatingAdmissionPolicy [\"'].* denied request:", result.stderr): + reason = "named-policy/message mismatch; denial did not match the exact expected policy, binding, and message" + else: + reason = "API/schema rejection; this is not evidence of the expected admission-policy denial" + if reason: + def bounded(value, limit=512): + value = value.replace("\r", "\\r").replace("\n", "\\n") + if len(value) > limit: + return value[:limit] + "...[truncated " + str(len(value) - limit) + " chars]" + return value + + fail(description + ": " + reason + "; kubectl exit status=" + str(result.returncode) + + "; stdout=" + bounded(result.stdout) + "; stderr=" + bounded(result.stderr)) print("PASS " + description, flush=True) diff --git a/dev-tools/tests/protected-pod-live-proof-contract.sh b/dev-tools/tests/protected-pod-live-proof-contract.sh index c399cac975..46abb40c37 100644 --- a/dev-tools/tests/protected-pod-live-proof-contract.sh +++ b/dev-tools/tests/protected-pod-live-proof-contract.sh @@ -146,6 +146,12 @@ if policy: if mode == 'allow-escape': print(json.dumps(pod)); sys.exit(0) if mode == 'auth-error': print('Error from server (Forbidden): user cannot create pods', file=sys.stderr) elif mode == 'conflict': print('Error from server (Conflict): resource version stale', file=sys.stderr) + elif mode == 'schema-error': + print('partial response from kubectl') + print('Error from server (BadRequest): strict decoding error: unknown field "spec.hostNames"', file=sys.stderr) + elif mode == 'noisy-error': + print('O' * 5000) + print('E' * 5000, file=sys.stderr) elif mode == 'wrong-policy': print("ValidatingAdmissionPolicy 'other' with binding 'other' denied request: " + message, file=sys.stderr) elif mode == 'wrong-message': print("ValidatingAdmissionPolicy '" + policy + "' with binding '" + policy + "' denied request: different constraint", file=sys.stderr) else: print("Error from server (Forbidden): ValidatingAdmissionPolicy '" + policy + "' with binding '" + policy + "' denied request: " + message, file=sys.stderr) @@ -171,10 +177,22 @@ with tempfile.TemporaryDirectory(prefix="firemud-pod-proof-contract-") as direct PROOF_POLICY=str(root / "k8s/trust-bootstrap/deployment-admission.yaml"), PROOF_POD=str(pod_file), PROOF_LOG=str(temporary / "calls")) arguments = ["--context", "proof-context", "--namespace", "dev", "--pod", "account-service-existing"] - cases = ["normal", "defaulted", "namespace-labels", "warning", "missing-typecheck", "stale-generation", "fail-open", "spec-drift", "audit-only", "wrong-revision", "wrong-pod", "missing-uid", "pod-drift", "allow-escape", "auth-error", "conflict", "wrong-policy", "wrong-message", "valid-denied", "malformed-success"] + cases = ["normal", "defaulted", "namespace-labels", "warning", "missing-typecheck", "stale-generation", "fail-open", "spec-drift", "audit-only", "wrong-revision", "wrong-pod", "missing-uid", "pod-drift", "allow-escape", "auth-error", "conflict", "schema-error", "noisy-error", "wrong-policy", "wrong-message", "valid-denied", "malformed-success"] for mode in cases: result = subprocess.run(["bash", str(tool)] + arguments, env=dict(environment, PROOF_MODE=mode), text=True, capture_output=True) assert (result.returncode == 0) == (mode in ("normal", "defaulted")), (mode, result.stdout, result.stderr) + if mode == "allow-escape": + assert "unexpected success" in result.stderr and "kubectl exit status=0" in result.stderr, result.stderr + assert "stdout={" in result.stderr, result.stderr + if mode == "schema-error": + assert "API/schema rejection" in result.stderr and "kubectl exit status=1" in result.stderr, result.stderr + assert "stdout=partial response from kubectl" in result.stderr, result.stderr + assert "strict decoding error" in result.stderr, result.stderr + if mode in ("wrong-policy", "wrong-message"): + assert "named-policy/message mismatch" in result.stderr and "kubectl exit status=1" in result.stderr, result.stderr + assert "denied request" in result.stderr, result.stderr + if mode == "noisy-error": + assert len(result.stderr) < 1800 and "[truncated " in result.stderr, len(result.stderr) if mode == "normal": assert "UNPROVED: CNI/socket" in result.stdout assert "ephemeral privilege escape" in result.stdout diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 30a8ee9034..ba39d41887 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -13,7 +13,29 @@ firemudJooq { accountInventoryMigrationProjection.set(true) } +// The extracted owner setup directly constructs main collaborators, not replacement test doubles. +configurations.named("testFixturesImplementation") { + extendsFrom(configurations.implementation.get()) +} + dependencies { + testFixturesImplementation(platform(libs.spring.boot.dependencies)) + testFixturesImplementation(project(":common-platform-core")) + testFixturesImplementation(project(":common-security")) + testFixturesImplementation(project(":common-data-runtime")) + testFixturesImplementation(project(":common-redis-contracts")) + testFixturesImplementation(libs.spring.boot.starter.test) + testFixturesImplementation(libs.spring.boot.starter.jdbc) + testFixturesImplementation(libs.spring.boot.starter.data.redis) + testFixturesImplementation(libs.spring.aop) + testFixturesImplementation(libs.mapstruct) + testFixturesImplementation(libs.argon2) + testFixturesImplementation(libs.jooq) + testFixturesImplementation(libs.flyway.core) + testFixturesImplementation("com.fasterxml.jackson.core:jackson-databind") + testFixturesImplementation("tools.jackson.core:jackson-databind") + testFixturesImplementation("com.google.protobuf:protobuf-java:${libs.versions.protobuf.get()}") + testFixturesImplementation("io.grpc:grpc-stub:${libs.versions.grpc.get()}") testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) implementation(project(":common-redis-contracts")) @@ -24,3 +46,20 @@ dependencies { testImplementation(testFixtures(project(":account-service"))) integrationTestImplementation(testFixtures(project(":account-service"))) } + +// Opt-in proof artifact: never expose Account migrations/application resources to World's tests. +val accountOriginalOrderProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("original-order-proof") + from(sourceSets.main.get().output.classesDirs) + from(sourceSets["testFixtures"].output.classesDirs) + from("src/main/resources") { + include("redis/lua/account-control-ui-registry-cas.lua") + } +} + +val accountOriginalOrderProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(accountOriginalOrderProofJar) +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java index e07e834015..cc819f0e1d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java @@ -2282,7 +2282,7 @@ private void insertPromotion(StoredPromotion promotion) { + "readiness_evidence_digest, expected_public_jwks_json, " + "expected_active_generation_marker_json) " + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'RS256', ?, ?, ?, ?, ?, " - + "'PROMOTE_PENDING', ?, 'PREPARED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + "'PROMOTE_PENDING', ?, 'PREPARED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", promotion.operationId(), promotion.binding().environmentId(), promotion.binding().clusterId(), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java index fe729b45f4..39a9c4b183 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java @@ -3,89 +3,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import de.mkammerer.argon2.Argon2Factory; -import io.grpc.Context; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.time.Clock; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.temporal.ChronoUnit; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Supplier; -import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; -import net.firedevops.firemud.accountservice.authordraft.AccountDraftSourceCompositionService; -import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; -import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; -import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; -import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; -import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; -import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; -import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; -import net.firedevops.firemud.accountservice.entity.Account; -import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; -import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; -import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; -import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; -import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingRepository; -import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; -import net.firedevops.firemud.accountservice.mapper.AccountMapper; -import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; -import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; -import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; -import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; -import net.firedevops.firemud.accountservice.repository.AccountRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; -import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; -import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; -import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; -import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.AcknowledgementRequirements; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; -import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; -import org.flywaydb.core.Flyway; -import org.jooq.DSLContext; -import org.jooq.SQLDialect; -import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import org.mapstruct.factory.Mappers; -import org.springframework.aop.framework.ProxyFactory; -import org.springframework.beans.factory.support.StaticListableBeanFactory; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; -import org.springframework.transaction.interceptor.TransactionInterceptor; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -100,7 +26,6 @@ */ @Testcontainers(disabledWithoutDocker = true) class AccountControlUiOwnerWorkflowPostgresIntegrationTest { - private static final String NAMESPACE = "control-ui-owner-proof"; static final String CALLER = "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; static final String OTP = "test-only-original-creator-otp"; @@ -112,7 +37,9 @@ class AccountControlUiOwnerWorkflowPostgresIntegrationTest { @Test void realSourceAndPrimaryCompositionRollsBackOtpWhenGenuineSignerIsUnavailable() { - Fixture f = new Fixture(temporary); + var f = + new AccountControlUiOwnerSourcesFixture( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), temporary, true); var environment = f.terms.captureCurrentEnvironmentBoundary(); var source = f.tx(() -> f.authority.captureInitial(f.tenant, environment)); assertThat(source.actor()).isEqualTo(f.account.getAccountUuid()); @@ -140,7 +67,9 @@ void realSourceAndPrimaryCompositionRollsBackOtpWhenGenuineSignerIsUnavailable() @Test void invalidOtpBudgetPersistsThroughProxiedPrimaryDenialAndExhaustsExistingFiveAttemptLimit() { - Fixture f = new Fixture(temporary); + var f = + new AccountControlUiOwnerSourcesFixture( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), temporary, true); var environment = f.terms.captureCurrentEnvironmentBoundary(); var original = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); try (var ignored = withPeer(CALLER)) { @@ -164,7 +93,9 @@ void invalidOtpBudgetPersistsThroughProxiedPrimaryDenialAndExhaustsExistingFiveA @Test void concurrentInvalidAttemptsBothCommitTheirOwnAccountingWithoutMinting() throws Exception { - Fixture f = new Fixture(temporary); + var f = + new AccountControlUiOwnerSourcesFixture( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), temporary, true); var environment = f.terms.captureCurrentEnvironmentBoundary(); var ready = new CountDownLatch(2); var start = new CountDownLatch(1); @@ -216,7 +147,9 @@ private static void awaitLatch(CountDownLatch latch) { @Test void changedProtectedCallerAndUnboundCurrentEnvironmentDenyWithoutConsumingOtp() { - Fixture f = new Fixture(temporary); + var f = + new AccountControlUiOwnerSourcesFixture( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), temporary, true); var environment = f.terms.captureCurrentEnvironmentBoundary(); var originalOtp = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); try (var ignored = @@ -236,413 +169,12 @@ void changedProtectedCallerAndUnboundCurrentEnvironmentDenyWithoutConsumingOtp() f.assertNoIssuance(); } - static final class Fixture { - final DSLContext dsl; - final TransactionTemplate transactions; - final Account account; - final UUID tenant = UUID.randomUUID(), - request = UUID.randomUUID(), - callerContext = UUID.randomUUID(); - final AtomicReference boundary = - new AtomicReference<>(testBoundary("test-production")); - final AtomicInteger coordinationCalls = new AtomicInteger(); - final AccountEmailLoginChallengeRepository challenges; - final AccountHostedTermsService terms; - final AccountControlUiAuthority authority; - final AccountControlUiIssuanceService service; - final DataSourceTransactionManager manager; - final DraftAuthorizationFenceRepository fences; - final AccountServiceImpl primary; - - Fixture(Path root) { - this(root, true); - } - - /** - * Reuses actual Account/source/auth owners while a composed test supplies signer/Redis owners. - */ - Fixture(Path root, boolean installNegativeIssuer) { - String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); - var dataSource = - new DriverManagerDataSource( - postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); - dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); - manager = new DataSourceTransactionManager(dataSource); - transactions = new TransactionTemplate(manager); - transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - var generations = new AccountAuthorityGenerationRepository(dsl); - var outbox = new AccountAuthorityOutboxRepository(dsl); - var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); - var accounts = new AccountRepository(dsl, sourceEvidence); - account = - tx( - () -> { - Account candidate = new Account(); - String suffix = UUID.randomUUID().toString(); - candidate.setUsername("owner-" + suffix); - candidate.setEmail(suffix + "@example.test"); - candidate.setPasswordHash(hash("test-only-disabled-password")); - candidate.setLoginAuthModes("EMAIL_OTP"); - return accounts.save(candidate); - }); - var creator = testCreation(account.getAccountUuid(), tenant); - var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); - tx( - () -> { - fresh.importVerified(creator.creationEvidence()); - generations.initializeTenantIfAbsent(tenant); - return null; - }); - var pairs = new AccountMembershipPairAuthorityRepository(dsl); - var memberships = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); - var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); - var bootstrapOperations = new AccountTenantCreationBootstrapOperationRepository(dsl); - var reader = - new AccountCreatorMembershipSourceReader( - accounts, - new AccountJoinOperationRepository(dsl), - memberships, - pairs, - roles, - fresh, - generations, - outbox, - sourceEvidence, - bootstrapOperations); - var beans = new StaticListableBeanFactory(); - AccountTenantCreationBootstrapAuthorizationSource externalBootstrap = - (actual, mutation) -> { - if (!creator.equals(actual) - || !TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException( - "Exact test-only external bootstrap fixture required"); - } - return mutation.get(); - }; - beans.addBean("testOnlyBootstrapAuthority", externalBootstrap); - var bootstrap = - new AccountTenantCreationBootstrapService( - accounts, - fresh, - reader, - pairs, - memberships, - roles, - outbox, - new AccountAuditOutboxRepository(dsl), - bootstrapOperations, - beans.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class)); - tx(() -> bootstrap.bootstrap(creator)); - var party = - new IndividualCreatorPartySource( - UUID.randomUUID(), - account.getAccountUuid(), - VerificationStatus.VERIFIED, - 1L, - "test-only-policy", - 1L, - "test-only-verification", - 1L, - 1L); - insertTestParty(dsl, party); - var parties = new IndividualCreatorPartyRepository(dsl, fresh, bootstrapOperations); - tx(() -> parties.associateFresh(UUID.randomUUID(), creator, party)); - fences = new DraftAuthorizationFenceRepository(dsl); - Map publications = new HashMap<>(); - Map actions = new HashMap<>(); - Map bindings = new HashMap<>(); - terms = - new AccountHostedTermsService( - manager, - new HostedTermsRepository(dsl), - parties, - fences, - id -> externalFixture(publications, id), - id -> externalFixture(actions, id), - new HostedTermsEnvironmentBindingRepository(dsl), - id -> externalFixture(bindings, id), - () -> { - requireOutsideTransaction(); - return boundary.get(); - }); - UUID publication = UUID.randomUUID(); - publications.put( - publication, - new AccountHostedTermsService.PublicationEvidence( - UUID.randomUUID(), - "Test-only Operator", - 1L, - bytes("Test-only initial terms"), - HostedTermsCatalogVersion.Materiality.INITIAL, - null, - null, - "test-only-publication-audit", - 1L, - "test-only-notice", - 1L, - Instant.now().minusSeconds(30).truncatedTo(ChronoUnit.MICROS))); - var catalog = terms.publish(publication).candidate(); - UUID action = UUID.randomUUID(); - actions.put( - action, - new AccountHostedTermsService.AcceptanceAction( - action, - true, - account.getAccountUuid(), - party.creatorPartyId(), - catalog.hostedScopeId(), - catalog.versionId(), - catalog.documentDigest(), - catalog.operatorLegalIdentity(), - catalog.operatorIdentityVersion(), - "test-only-affirmative-action", - 1L, - OffsetDateTime.now(ZoneOffset.UTC))); - terms.accept(action); - UUID binding = UUID.randomUUID(); - bindings.put( - binding, - new HostedTermsEnvironmentBinding.PublicationEvidence( - "test-production", - catalog.hostedScopeId(), - catalog.operatorLegalIdentity(), - catalog.operatorIdentityVersion(), - catalog.versionId(), - catalog.sourceVersion(), - "test-only-environment-publisher", - "test-only-environment-publication/" + binding, - null, - null)); - terms.publishEnvironmentBinding(binding); - authority = - new AccountControlUiAuthority( - new AccountDraftSourceCompositionService( - dsl, parties, bootstrap, terms, sourceEvidence)); - challenges = new AccountEmailLoginChallengeRepository(dsl); - tx( - () -> { - var challenge = new AccountEmailLoginChallenge(); - var now = LocalDateTime.now().withNano(0); - challenge.setAccountId(account.getId()); - challenge.setCodeHash(hash(OTP)); - challenge.setExpiresAt(now.plusMinutes(5)); - challenge.setResendAvailableAt(now.plusMinutes(1)); - challenge.setCreatedAt(now); - challenge.setUpdatedAt(now); - return challenges.save(challenge); - }); - var primaryTarget = - new AccountServiceImpl( - accounts, - null, - null, - null, - challenges, - null, - null, - Mappers.getMapper(AccountMapper.class), - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - null, - manager); - // Exercise the real MANDATORY interceptor: noRollbackFor must not poison the owner callback. - var primaryProxy = new ProxyFactory(primaryTarget); - primaryProxy.setProxyTargetClass(true); - primaryProxy.addAdvice( - new TransactionInterceptor(manager, new AnnotationTransactionAttributeSource())); - primary = (AccountServiceImpl) primaryProxy.getProxy(); - if (!installNegativeIssuer) { - service = null; - return; - } - var signerRepository = new AccountJwtSignerDesiredStateRepository(dsl); - var trust = new AccountJwtSignerMaterializerTrustBinding(false, ""); - var api = new AccountJwtJwksApiBinding(); - var signer = - new AccountControlUiSignerOwner( - signerRepository, trust, api, root.resolve("private"), root.resolve("public")); - var operations = new AccountControlUiIssuanceRepository(dsl); - var crypto = - new AccountControlUiResponseCryptography( - new AccountControlUiKeyring(root.resolve("custody")), Clock.systemUTC()); - var registry = - new AccountControlUiCoordination( - () -> { - coordinationCalls.incrementAndGet(); - throw new IllegalStateException("No physical Redis fixture in this negative proof"); - }, - new AcknowledgementRequirements(1, 1, 1000), - RedisScriptCatalog.fromContributions(List.of())); - var publicSource = - new AccountJwtJwksTrustedSource( - new AccountJwtJwksConfigMapClient(api), - trust, - signerRepository, - new AccountJwtJwksPublicationRepository(dsl, signerRepository), - manager); - var actors = - new AccountControlUiActorService( - operations, - authority, - signer, - registry, - publicSource, - fences, - manager, - Clock.systemUTC()); - service = - new AccountControlUiIssuanceService( - primary, - operations, - authority, - fences, - signer, - crypto, - registry, - actors, - manager, - Clock.systemUTC(), - CALLER); - } - - AccountControlUiIssuanceService.Request request(String secret) { - return new AccountControlUiIssuanceService.Request( - request, account.getEmail(), secret, tenant, callerContext); - } - - T tx(Supplier action) { - return transactions.execute(ignored -> action.get()); - } - - void assertNoIssuance() { - assertThat(dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))).isZero(); - assertThat(dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isZero(); - assertThat(coordinationCalls).hasValue(0); - } - } - - private static FreshTenantCreatorEvidence testCreation(UUID account, UUID tenant) { - UUID request = UUID.randomUUID(), - operation = UUID.randomUUID(), - authorization = UUID.randomUUID(); - String key = "test-only-game-row-17"; - String digest = - GameTenantCreationDigest.requestDigest(NAMESPACE, request, key, "Test game", null); - var creation = - new FreshTenantCreationEvidence( - 1, - NAMESPACE, - request, - operation, - digest, - tenant, - 17L, - key, - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); - String authorizationDigest = "sha256:" + "8".repeat(64); - return new FreshTenantCreatorEvidence( - 1, - creation, - account, - authorization, - authorizationDigest, - FreshTenantCreatorDigest.evidenceDigest( - 1, creation, account, authorization, authorizationDigest)); - } - - private static void insertTestParty(DSLContext dsl, IndividualCreatorPartySource party) { - byte[] source = CreatorPartyEncoding.party(party); - dsl.execute( - "INSERT INTO account_individual_creator_party_sources" - + " (creator_party_id, account_uuid, verification_status, identity_version, policy_reference, policy_version," - + " verification_evidence_reference, verification_evidence_version, source_version, source_payload, source_digest)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - party.creatorPartyId(), - party.accountId(), - party.verificationStatus().name(), - party.identityVersion(), - party.policyReference(), - party.policyVersion(), - party.verificationEvidenceReference(), - party.verificationEvidenceVersion(), - party.sourceVersion(), - source, - CreatorPartyEncoding.digest(source)); - } - private static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary testBoundary( String name) { - byte[] source = bytes("test-only-environment-observation/" + name); - return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( - name, - "test-only-environment-owner", - "test-only-observation/" + name, - source, - HostedTermsEncoding.digest(source)); - } - - private static T externalFixture(Map values, UUID request) { - requireOutsideTransaction(); - return Objects.requireNonNull( - values.get(request), "Exact test-only external evidence required"); - } - - private static void requireOutsideTransaction() { - if (TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException( - "External fixture observation must precede Account owner locks"); - } - } - - static PeerScope withPeer(String uri) { - var attached = - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); - return new PeerScope(attached.attach(), attached); + return AccountControlUiOwnerSourcesFixture.testBoundary(name); } - record PeerScope(Context previous, Context attached) implements AutoCloseable { - @Override - public void close() { - attached.detach(previous); - } - } - - private static byte[] bytes(String value) { - return value.getBytes(StandardCharsets.UTF_8); - } - - private static String hash(String value) { - char[] secret = value.toCharArray(); - var argon = Argon2Factory.create(); - try { - return argon.hash(2, 4096, 1, secret); - } finally { - argon.wipeArray(secret); - } + static AccountControlUiOwnerSourcesFixture.PeerScope withPeer(String uri) { + return AccountControlUiOwnerSourcesFixture.withPeer(uri); } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java index 4e8763372a..009aec292e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -2,71 +2,23 @@ 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.mockStatic; -import static org.mockito.Mockito.when; -import io.grpc.stub.StreamObserver; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.codec.ByteArrayCodec; -import java.math.BigInteger; -import java.net.URI; 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.MessageDigest; -import java.security.interfaces.RSAPublicKey; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; -import java.util.HexFormat; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; -import java.util.Optional; import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; -import net.firedevops.firemud.account.v1.EnrollBootstrapRequest; -import net.firedevops.firemud.account.v1.EnrollBootstrapResponse; -import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestRequest; -import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse; -import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest; -import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; -import net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity; -import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; -import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; -import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest; -import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; -import net.firedevops.firemud.account.v1.RecordSecretObservationRequest; -import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; -import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; -import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; -import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; -import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; -import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; -import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; -import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; -import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; -import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; -import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; -import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; -import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor; -import net.firedevops.firemud.accountservice.service.impl.AccountJwtSignerMaterializationService; -import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; -import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; -import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; -import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; @@ -74,13 +26,11 @@ import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import org.springframework.beans.factory.support.StaticListableBeanFactory; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import tools.jackson.databind.json.JsonMapper; /** * Isolated positive Account storage/producer proof with explicitly stipulated upstream trust, @@ -93,32 +43,6 @@ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class AccountControlUiPositiveOwnerPostgresIntegrationTest { - private static final Binding BINDING = - new Binding( - "prod", - "prod-cluster-1", - "firemud-prod", - CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); - private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; - private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; - private static final String SECRET_UID = "33333333-3333-4333-8333-333333333333"; - private static final String CONFIG_MAP_UID = "44444444-4444-4444-8444-444444444444"; - private static final String TRUST_REVISION = "trust-r1"; - private static final String MATERIALIZER_URI = - "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; - private static final List MATERIALIZER_PINS = List.of("c".repeat(64)); - private static final String TRUST_DIGEST = - AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( - TRUST_REVISION, - BINDING.environmentId(), - BINDING.clusterId(), - BINDING.namespace(), - CLUSTER_UID, - NAMESPACE_UID, - MATERIALIZER_URI, - MATERIALIZER_PINS); - private static final String API_DIGEST = "b".repeat(64), API_REVISION = "api-r1"; - private static final JsonMapper JSON = JsonMapper.builder().build(); private static final Network NETWORK = Network.newNetwork(); private static final String PASSWORD = UUID.randomUUID().toString(); @@ -166,8 +90,14 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest { @Test void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() throws Exception { - var f = new AccountControlUiOwnerWorkflowPostgresIntegrationTest.Fixture(temporary, false); - var lifecycle = new SignerLifecycle(f, temporary); + var f = + new AccountControlUiOwnerSourcesFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + temporary, + false); + var lifecycle = new AccountControlUiSignerFixture(f, temporary); lifecycle.commit(); // This is the actual private lifecycle-derived signer receipt, never a handcrafted Capture. var originalSigner = f.tx(lifecycle.signer::captureCurrent); @@ -348,7 +278,7 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() } private static DraftAuthorizationFenceBinding originalBinding( - AccountControlUiOwnerWorkflowPostgresIntegrationTest.Fixture f, + AccountControlUiOwnerSourcesFixture f, List sources) { var complete = DraftCommitBinding.create( @@ -393,364 +323,6 @@ private static DraftAuthorizationFenceBinding originalBinding( sources); } - private final class SignerLifecycle { - final AccountControlUiOwnerWorkflowPostgresIntegrationTest.Fixture f; - final AccountJwtSignerDesiredStateRepository desired; - final AccountJwtJwksPublicationRepository publication; - final AccountJwtReadinessProbeRepository readiness; - final AccountJwtSignerMaterializerTrustBinding trust = - mock(AccountJwtSignerMaterializerTrustBinding.class); - final AccountJwtJwksApiBinding api = mock(AccountJwtJwksApiBinding.class); - final AccountJwtJwksConfigMapClient client = mock(AccountJwtJwksConfigMapClient.class); - final AccountJwtValidatorInventorySource inventory = - mock(AccountJwtValidatorInventorySource.class); - final AtomicReference configMap = - new AtomicReference<>( - new AccountJwtJwksConfigMapClient.ConfigMapSnapshot( - CONFIG_MAP_UID, "41", Map.of("jwks.json", "{\"keys\":[]}"))); - final Path privateRoot, publicRoot; - final AccountJwtSignerBootstrapCoordinator coordinator; - final AccountJwtSignerMaterializationService materializer; - final AccountControlUiSignerOwner signer; - - SignerLifecycle(AccountControlUiOwnerWorkflowPostgresIntegrationTest.Fixture fixture, Path root) - throws Exception { - f = fixture; - privateRoot = Files.createDirectories(root.resolve("private")); - publicRoot = Files.createDirectories(root.resolve("public")); - desired = new AccountJwtSignerDesiredStateRepository(f.dsl); - publication = new AccountJwtJwksPublicationRepository(f.dsl, desired); - readiness = new AccountJwtReadinessProbeRepository(f.dsl, desired, publication); - when(trust.current()).thenReturn(Optional.of(materializerBinding())); - when(api.current()) - .thenReturn( - new AccountJwtJwksApiBinding.ParsedBinding( - API_REVISION, - BINDING.environmentId(), - BINDING.clusterId(), - URI.create("https://kubernetes.default.svc:6443/"), - "kubernetes.default.svc", - root.resolve("test-only-ca"), - "d".repeat(64), - root.resolve("test-only-bearer"), - BINDING.namespace(), - CLUSTER_UID, - NAMESPACE_UID, - "system:serviceaccount:firemud-prod:account-service", - API_DIGEST)); - when(client.identity()) - .thenReturn( - new AccountJwtJwksConfigMapClient.BindingIdentity( - API_DIGEST, - API_REVISION, - BINDING.environmentId(), - BINDING.clusterId(), - BINDING.namespace(), - CLUSTER_UID, - NAMESPACE_UID, - "https://kubernetes.default.svc:6443/", - "kubernetes.default.svc", - "d".repeat(64), - "system:serviceaccount:firemud-prod:account-service")); - when(client.observe()).thenAnswer(ignored -> configMap.get()); - when(client.publish(any(), any())) - .thenAnswer(call -> publish(call.getArgument(0), call.getArgument(1))); - when(client.publishActiveProjection(any(), any(), any())) - .thenAnswer(call -> publish(call.getArgument(0), call.getArgument(2))); - when(inventory.observe(any(ObservationContext.class))) - .thenAnswer(call -> completeInventorySnapshot(now(), call.getArgument(0))); - var mounted = - new AccountJwtJwksPrepublicationService.MountedProjection( - privateRoot, - Path.of("pending.key"), - publicRoot, - Path.of("jwks.json"), - Path.of("jwt-generation.json")); - var prepublication = - new AccountJwtJwksPrepublicationService( - desired, publication, trust, client, f.manager, mounted); - var beans = new StaticListableBeanFactory(); - beans.addBean("testOnlyInventoryInput", inventory); - coordinator = - new AccountJwtSignerBootstrapCoordinator( - trust, - client, - desired, - prepublication, - readiness, - beans.getBeanProvider(AccountJwtValidatorInventorySource.class), - f.transactions); - beans.addBean("actualAccountCoordinator", coordinator); - materializer = - new AccountJwtSignerMaterializationService( - desired, - readiness, - trust, - f.manager, - beans.getBeanProvider(AccountJwtSignerBootstrapCoordinator.class), - beans.getBeanProvider(AccountJwtValidatorInventorySource.class)); - signer = new AccountControlUiSignerOwner(desired, trust, api, privateRoot, publicRoot); - } - - AccountJwtJwksConfigMapClient.CasObservation publish( - AccountJwtJwksConfigMapClient.ConfigMapSnapshot expected, Map data) - throws Exception { - assertThat(configMap.get()).isEqualTo(expected); - var next = - new AccountJwtJwksConfigMapClient.ConfigMapSnapshot( - CONFIG_MAP_UID, Long.toString(Long.parseLong(expected.resourceVersion()) + 1), data); - configMap.set(next); - for (var entry : data.entrySet()) - Files.writeString(publicRoot.resolve(entry.getKey()), entry.getValue()); - return new AccountJwtJwksConfigMapClient.CasObservation( - CONFIG_MAP_UID, - expected.resourceVersion(), - next.resourceVersion(), - data, - data, - AccountJwtJwksConfigMapClient.Outcome.APPLIED); - } - - void commit() throws Exception { - // Only the protected upstream identity is stipulated; every owner method/transaction is real. - try (var authenticated = mockStatic(AccountJwtSignerMaterializerTlsInterceptor.class)) { - authenticated - .when(AccountJwtSignerMaterializerTlsInterceptor::authenticatedBinding) - .thenReturn(materializerBinding()); - AccountControlUiPositiveOwnerPostgresIntegrationTest.rpc( - out -> - materializer.enrollBootstrap( - EnrollBootstrapRequest.newBuilder().setSchemaVersion(1).build(), out)); - GetCurrentGenerationRequestResponse initial = - rpc( - out -> - materializer.getCurrentGenerationRequest( - GetCurrentGenerationRequestRequest.newBuilder().setSchemaVersion(1).build(), - out)); - var request = f.tx(() -> desired.readCurrentGenerationRequest(BINDING, trust())); - GetCurrentGenerationRequestResponse observed = - rpc( - out -> - materializer.recordSecretObservation( - RecordSecretObservationRequest.newBuilder() - .setSchemaVersion(1) - .setOperationId(initial.getOperationId()) - .setOperationDigest(initial.getOperationDigest()) - .setSecretUid(SECRET_UID) - .setObservedResourceVersion("12") - .build(), - out)); - var pair = generateRsa3072(); - var publicKey = publicJwk(request.targetKid(), (RSAPublicKey) pair.getPublic()); - RecordGenerationResultResponse recorded = - rpc( - out -> - materializer.recordGenerationResult( - RecordGenerationResultRequest.newBuilder() - .setSchemaVersion(1) - .setOperationId(initial.getOperationId()) - .setGenerationRequestDigest(observed.getGenerationRequestDigest()) - .setSecretUid(SECRET_UID) - .setExpectedPriorResourceVersion("12") - .setObservedResourceVersion("13") - .setPublicJwkJson(publicKey.json()) - .build(), - out)); - var result = f.tx(() -> desired.readCurrentGenerationResult(BINDING, trust())); - assertThat(recorded.getOperationId()).isEqualTo(result.operationId().toString()); - assertThat(recorded.getOperationDigest()).isEqualTo(result.operationDigest()); - assertThat(recorded.getGenerationRequestDigest()) - .isEqualTo(result.generationRequestDigest()); - assertThat(recorded.getGenerationReceiptDigest()).isEqualTo(result.receiptDigest()); - assertThat(recorded.getObservedResourceVersion()) - .isEqualTo(result.observedResourceVersion()); - assertThat(recorded.getPublicKeyFingerprint()).isEqualTo(result.publicKeyFingerprint()); - Files.writeString( - privateRoot.resolve("pending.key"), privateBundleJson(request, result, pair)); - assertThat( - coordinator - .reconcileCurrentGenerationOnce(result.operationId()) - .publicKeyPrepublished()) - .isTrue(); - var context = - f.tx(() -> readiness.readCurrentInventoryObservationContext(BINDING, trust())); - var plannedAt = now().minusSeconds(300); - var planned = completeInventorySnapshot(plannedAt, context); - var plan = f.tx(() -> readiness.planCurrent(BINDING, trust(), plannedAt, planned)); - var harnessUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"; - var harnessPin = "e".repeat(64); - long validUntil = now().plusSeconds(3600).getEpochSecond(); - String readinessDigest = - net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding - .computeBindingDigest( - "test-readiness-r1", - BINDING.environmentId(), - BINDING.clusterId(), - BINDING.namespace(), - CLUSTER_UID, - NAMESPACE_UID, - harnessUri, - List.of(harnessPin), - "test-only-validator", - validUntil); - var harness = - new net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding - .Binding( - BINDING.environmentId(), - BINDING.clusterId(), - BINDING.namespace(), - CLUSTER_UID, - NAMESPACE_UID, - harnessUri, - List.of(harnessPin), - "test-readiness-r1", - "account-service", - "test-only-validator", - validUntil, - readinessDigest); - var peer = - new net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding - .PeerIdentity(harnessUri, harnessPin); - var claim = - f.tx(() -> readiness.claimSingleDelivery(BINDING, trust(), plan, harness, peer, now())); - var producer = - new AccountJwtReadinessProbeService( - readiness, - f.transactions, - Clock.systemUTC(), - privateRoot, - Path.of("pending.key"), - publicRoot, - Path.of("jwks.json")); - var delivered = - producer.issueCurrentPlan( - BINDING, - trust(), - result.operationId(), - claim, - (metadata, compact) -> { - assertThat(compact).isNotEmpty(); - var issued = - f - .tx( - () -> - readiness.readCurrentPlan(BINDING, trust(), result.operationId())) - .entries() - .stream() - .filter(entry -> entry.jti().equals(metadata.jti())) - .findFirst() - .orElseThrow(); - var current = completeInventorySnapshot(now(), context); - var pods = - f.tx( - () -> - readiness.readCurrentExpectedPods(BINDING, trust(), issued, current)); - for (var pod : pods) { - var acceptance = - testAuthenticatedAcceptance(issued, pod, now().getEpochSecond()); - f.tx( - () -> - readiness.recordPodAcceptance( - BINDING, trust(), issued, pod, acceptance, current)); - } - }); - assertThat(delivered) - .hasSize(8) - .allSatisfy( - entry -> - assertThat(entry.state()) - .isEqualTo(AccountJwtReadinessProbeRepository.ProbeState.VERIFIED)); - assertThat(f.dsl.fetchCount(DSL.table("account_jwt_readiness_pod_receipts"))).isEqualTo(12); - assertThat( - f.dsl.fetchCount( - DSL.table("account_jwt_readiness_pod_receipts"), - DSL.field("outcome").eq("INAPPLICABLE_REJECT"))) - .isEqualTo(2); - var prepared = coordinator.prepareCurrentPromotionOnce().orElseThrow(); - GetCurrentPromotionRequestResponse dispatched = - rpc( - out -> - materializer.getCurrentPromotionRequest( - GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), - out)); - var promotion = - f.tx(() -> desired.readPreparedGenerationForRecovery(BINDING, trust())).promotion(); - assertThat(prepared.operationId()).isEqualTo(promotion.operationId()); - assertThat(dispatched.getPromotionOperationId()) - .isEqualTo(promotion.operationId().toString()); - assertThat(dispatched.getPromotionRequestDigest()).isEqualTo(promotion.requestDigest()); - assertThat(dispatched.getGenerationOperationId()) - .isEqualTo(result.operationId().toString()); - assertThat(dispatched.getGenerationOperationDigest()).isEqualTo(result.operationDigest()); - assertThat(dispatched.getGenerationReceiptDigest()).isEqualTo(result.receiptDigest()); - assertThat(dispatched.getExpectedSecretUid()).isEqualTo(promotion.secretUid()); - assertThat(dispatched.getExpectedSecretResourceVersion()) - .isEqualTo(promotion.expectedPrivateResourceVersion()); - Files.writeString( - privateRoot.resolve("current.key"), privateBundleJson(request, result, pair)); - RecordPrivatePromotionResultResponse committed = - rpc( - out -> - materializer.recordPrivatePromotionResult( - RecordPrivatePromotionResultRequest.newBuilder() - .setSchemaVersion(1) - .setPromotionOperationId(promotion.operationId().toString()) - .setPromotionRequestDigest(promotion.requestDigest()) - .setGenerationOperationId(result.operationId().toString()) - .setGenerationOperationDigest(result.operationDigest()) - .setSecretUid(SECRET_UID) - .setExpectedPriorResourceVersion( - promotion.expectedPrivateResourceVersion()) - .setObservedResourceVersion("14") - .setCurrent( - PromotionPublicKeyIdentity.newBuilder() - .setGeneration(result.targetGeneration()) - .setKid(result.targetKid()) - .setPublicKeyFingerprint(result.publicKeyFingerprint())) - .addResultingSlots("current") - .build(), - out)); - var durableCommit = - f.tx( - () -> - desired.readCurrentCommittedSigner( - BINDING, trust(), API_DIGEST, API_REVISION)) - .orElseThrow(); - assertThat(committed.getPromotionOperationId()) - .isEqualTo(durableCommit.promotion().operationId().toString()); - assertThat(committed.getGenerationOperationId()) - .isEqualTo(durableCommit.generationResult().operationId().toString()); - assertThat(committed.getObservedResourceVersion()) - .isEqualTo(durableCommit.privateReceipt().observedResourceVersion()); - assertThat(committed.getPublicReceiptDigest()) - .isEqualTo(durableCommit.privateReceipt().receiptDigest()); - } - } - } - - private static T rpc(Consumer> invocation) { - AtomicReference result = new AtomicReference<>(); - AtomicReference failure = new AtomicReference<>(); - invocation.accept( - new StreamObserver<>() { - @Override - public void onNext(T value) { - result.set(value); - } - - @Override - public void onError(Throwable error) { - failure.set(error); - } - - @Override - public void onCompleted() {} - }); - if (failure.get() != null) - throw new AssertionError("Actual Account materialization RPC failed", failure.get()); - return java.util.Objects.requireNonNull(result.get()); - } - private static RedisClient redisClient(boolean application) { var uri = RedisURI.Builder.redis(redis.getHost(), redis.getMappedPort(6379)); if (application) uri.withAuthentication("account_coord_app", PASSWORD); @@ -788,8 +360,6 @@ private void custody(String purpose, String id, int value) throws Exception { + "\n"); } - private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} - private static void assertOrder( net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository .FenceSnapshot @@ -856,354 +426,4 @@ public byte[] getBytes() { return "ACL".getBytes(StandardCharsets.US_ASCII); } } - - private static Instant now() { - return Instant.ofEpochSecond(Instant.now().getEpochSecond()); - } - - private static TrustFence trust() { - return new TrustFence(CLUSTER_UID, NAMESPACE_UID, TRUST_DIGEST, TRUST_REVISION); - } - - private static AccountJwtSignerMaterializerTrustBinding.Binding materializerBinding() { - return new AccountJwtSignerMaterializerTrustBinding.Binding( - BINDING.environmentId(), - BINDING.clusterId(), - BINDING.namespace(), - CLUSTER_UID, - NAMESPACE_UID, - MATERIALIZER_URI, - MATERIALIZER_PINS, - TRUST_REVISION, - TRUST_DIGEST); - } - - private static String privateBundleJson( - GenerationRequest request, GenerationResult result, KeyPair pair) { - Map bundle = new LinkedHashMap<>(); - bundle.put("version", 1); - bundle.put("environmentId", request.binding().environmentId()); - bundle.put("clusterId", request.binding().clusterId()); - bundle.put("namespace", request.binding().namespace()); - bundle.put("operationId", request.operationId().toString()); - bundle.put("generation", result.targetGeneration()); - bundle.put("kid", result.targetKid()); - bundle.put("algorithm", "RS256"); - bundle.put( - "privateKeyPkcs8", - Base64.getUrlEncoder().withoutPadding().encodeToString(pair.getPrivate().getEncoded())); - bundle.put("publicKeyFingerprint", result.publicKeyFingerprint()); - return JSON.writeValueAsString(bundle); - } - - private static PublicJwk publicJwk(String kid, RSAPublicKey key) throws Exception { - String modulus = encodeUnsigned(key.getModulus()); - String exponent = encodeUnsigned(key.getPublicExponent()); - Map jwk = new LinkedHashMap<>(); - jwk.put("alg", "RS256"); - jwk.put("e", exponent); - jwk.put("key_ops", List.of("verify")); - jwk.put("kid", kid); - jwk.put("kty", "RSA"); - jwk.put("n", modulus); - jwk.put("use", "sig"); - String json = canonicalJson(jwk); - Map withoutKeyOps = new LinkedHashMap<>(jwk); - withoutKeyOps.remove("key_ops"); - String jsonWithoutKeyOps = canonicalJson(withoutKeyOps); - String fingerprint = - sha256( - Rfc8785CanonicalJson.canonicalizeUtf8( - JSON.writeValueAsString(Map.of("e", exponent, "kty", "RSA", "n", modulus)))); - return new PublicJwk(json, jsonWithoutKeyOps, fingerprint); - } - - private static String canonicalJson(Map value) throws Exception { - return new String( - Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), - StandardCharsets.UTF_8); - } - - private static String encodeUnsigned(BigInteger value) { - byte[] bytes = value.toByteArray(); - int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; - return Base64.getUrlEncoder() - .withoutPadding() - .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); - } - - private static KeyPair generateRsa3072() throws Exception { - KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); - generator.initialize(3_072); - return generator.generateKeyPair(); - } - - private static String sha256(byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (java.security.NoSuchAlgorithmException ex) { - throw new IllegalStateException("SHA-256 is required for the persistence fixture", ex); - } - } - - /** Stipulated platform input only; Account's real owners derive all private proof from it. */ - private static InventorySnapshot completeInventorySnapshot( - Instant observedAt, ObservationContext observationContext) { - return completeInventorySnapshot(observedAt, "10.11.0.11", observationContext); - } - - private static InventorySnapshot completeInventorySnapshot( - Instant observedAt, String firstAccountPodIp, ObservationContext observationContext) { - return completeInventorySnapshot( - observedAt, firstAccountPodIp, observationContext, "77777777-7777-4777-8777-777777777777"); - } - - private static InventorySnapshot completeInventorySnapshot( - Instant observedAt, - String firstAccountPodIp, - ObservationContext observationContext, - String firstAccountPodUid) { - String accountImage = "registry.example/account-validator@sha256:" + "1".repeat(64); - String gameSessionImage = "registry.example/game-session-validator@sha256:" + "3".repeat(64); - String accountConfigDigest = "2".repeat(64); - String gameSessionConfigDigest = "4".repeat(64); - String accountServiceUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator"; - String gameSessionServiceUri = "spiffe://firemud/ns/firemud-prod/sa/game-session-jwt-validator"; - List accountProfiles = - List.of( - new ProfileExpectation("control-ui", "control-ui"), - new ProfileExpectation("game-session-account-delegation", "account-service"), - new ProfileExpectation("player-bootstrap", "player-bootstrap")); - List gameSessionProfiles = - List.of(new ProfileExpectation("game-session-account-delegation", "account-service")); - List accountPods = - List.of( - inventoryPod( - "account-a", - firstAccountPodUid, - "account-rs", - "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", - "acct1", - firstAccountPodIp, - 9443, - accountImage, - accountConfigDigest, - accountServiceUri, - "5".repeat(64)), - inventoryPod( - "account-b", - "88888888-8888-4888-8888-888888888888", - "account-rs", - "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", - "acct1", - "10.11.0.12", - 9443, - accountImage, - accountConfigDigest, - accountServiceUri, - "6".repeat(64))); - List gameSessionPods = - List.of( - inventoryPod( - "game-session-a", - "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", - "game-session-rs", - "cccccccc-cccc-4ccc-8ccc-cccccccccccc", - "games", - "10.12.0.11", - 9444, - gameSessionImage, - gameSessionConfigDigest, - gameSessionServiceUri, - "7".repeat(64))); - List validators = - List.of( - new ValidatorObservation( - "account-service", - "account-service", - "66666666-6666-4666-8666-666666666666", - 1L, - "51", - 2, - accountImage, - accountConfigDigest, - 300, - accountProfiles, - accountPods, - List.of()), - new ValidatorObservation( - "game-session-service", - "game-session-service", - "99999999-9999-4999-8999-999999999999", - 1L, - "52", - 1, - gameSessionImage, - gameSessionConfigDigest, - 300, - gameSessionProfiles, - gameSessionPods, - List.of())); - List> validatorMaps = - List.of( - inventoryValidatorMap(validators.get(0), accountServiceUri, 9443), - inventoryValidatorMap(validators.get(1), gameSessionServiceUri, 9444)); - Map preimage = new LinkedHashMap<>(); - preimage.put("domain", "firemud-account-validator-inventory/v2"); - preimage.put("environmentId", BINDING.environmentId()); - preimage.put("clusterId", BINDING.clusterId()); - preimage.put("clusterIncarnationUid", CLUSTER_UID); - preimage.put("namespace", BINDING.namespace()); - preimage.put("namespaceUid", NAMESPACE_UID); - preimage.put("apiBindingRevision", API_REVISION); - preimage.put("apiBindingDigest", API_DIGEST); - preimage.put("inventoryBindingRevision", "inventory-r1"); - preimage.put("inventoryBindingDigest", "c".repeat(64)); - preimage.put( - "observationContext", - Map.of( - "purpose", observationContext.purpose().name(), - "operationId", observationContext.operationId().toString(), - "operationDigest", observationContext.operationDigest())); - preimage.put("validators", validatorMaps); - byte[] bytes; - try { - bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); - } catch (Exception failure) { - throw new AssertionError(failure); - } - InventorySnapshot snapshot = mock(InventorySnapshot.class); - when(snapshot.observedAt()).thenReturn(observedAt); - when(snapshot.environmentId()).thenReturn(BINDING.environmentId()); - when(snapshot.clusterId()).thenReturn(BINDING.clusterId()); - when(snapshot.clusterIncarnationUid()).thenReturn(CLUSTER_UID); - when(snapshot.namespace()).thenReturn(BINDING.namespace()); - when(snapshot.namespaceUid()).thenReturn(NAMESPACE_UID); - when(snapshot.apiBindingRevision()).thenReturn(API_REVISION); - when(snapshot.apiBindingDigest()).thenReturn(API_DIGEST); - when(snapshot.inventoryBindingRevision()).thenReturn("inventory-r1"); - when(snapshot.inventoryBindingDigest()).thenReturn("c".repeat(64)); - when(snapshot.observationContext()).thenReturn(Optional.of(observationContext)); - when(snapshot.validators()).thenReturn(validators); - when(snapshot.canonicalBytes()).thenReturn(bytes.clone()); - when(snapshot.digest()).thenReturn(sha256(bytes)); - return snapshot; - } - - private static PodObservation inventoryPod( - String name, - String uid, - String ownerName, - String ownerUid, - String podTemplateHash, - String podIp, - int receiverPort, - String image, - String configDigest, - String serviceUri, - String spkiDigest) { - String host = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; - return new PodObservation( - name, - uid, - "11", - ownerName, - ownerUid, - podTemplateHash, - image, - configDigest, - podIp, - URI.create("grpcs://" + host + ":" + receiverPort), - serviceUri, - spkiDigest); - } - - private static Map inventoryValidatorMap( - ValidatorObservation validator, String serviceUri, int receiverPort) { - Map result = new LinkedHashMap<>(); - result.put("validatorId", validator.validatorId()); - result.put("deploymentName", validator.deploymentName()); - result.put("deploymentUid", validator.deploymentUid()); - result.put("deploymentGeneration", Long.toString(validator.deploymentGeneration())); - result.put("deploymentResourceVersion", validator.deploymentResourceVersion()); - result.put("replicas", Integer.toString(validator.replicas())); - result.put("image", validator.image()); - result.put("verifierConfigSha256", validator.verifierConfigSha256()); - result.put("maxCacheAgeSeconds", Integer.toString(validator.maxCacheAgeSeconds())); - result.put( - "profiles", - validator.profiles().stream() - .map( - profile -> - Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) - .toList()); - result.put( - "pods", - validator.pods().stream() - .map( - pod -> - Map.ofEntries( - Map.entry("name", pod.name()), - Map.entry("uid", pod.uid()), - Map.entry("resourceVersion", pod.resourceVersion()), - Map.entry("ownerReplicaSetName", pod.ownerName()), - Map.entry("ownerReplicaSetUid", pod.ownerUid()), - Map.entry("podTemplateHash", pod.podTemplateHash()), - Map.entry("image", pod.image()), - Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), - Map.entry("podIp", pod.podIp()), - Map.entry("exactPodEndpoint", pod.endpoint().toString()), - Map.entry("canonicalServiceUri", pod.receiverServiceUri()), - Map.entry("leafSpkiSha256", pod.leafSpkiSha256()))) - .toList()); - result.put("receiverServiceUri", serviceUri); - result.put("receiverPort", receiverPort); - result.put("replicaSets", List.of()); - return result; - } - - private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance - testAuthenticatedAcceptance( - ProbeEntry entry, - AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, - long observedAtEpochSecond) { - return testAuthenticatedAcceptance( - entry, expectedPod, observedAtEpochSecond, entry.targetKid()); - } - - private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance - testAuthenticatedAcceptance( - ProbeEntry entry, - AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, - long observedAtEpochSecond, - String verifiedKid) { - return testAuthenticatedAcceptance( - entry, - expectedPod, - observedAtEpochSecond, - verifiedKid, - expectedPod.target().exactPodEndpoint().orElseThrow().toString()); - } - - private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance - testAuthenticatedAcceptance( - ProbeEntry entry, - AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, - long observedAtEpochSecond, - String verifiedKid, - String actualPodEndpoint) { - var target = expectedPod.target(); - return AccountJwtReadinessReceiverInvocationPort.authenticatedAcceptance( - target.podUid(), - actualPodEndpoint, - target.image(), - target.verifierConfigSha256(), - target.canonicalServiceUri().orElseThrow(), - target.podLeafSpkiSha256().orElseThrow(), - entry.jti(), - entry.compactTokenSha256().orElseThrow(), - verifiedKid, - target.expectation(), - observedAtEpochSecond); - } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java index a316ec175e..15ac85920f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java @@ -904,7 +904,35 @@ void persistsProtectedV2PodClosureAndRequiresFreshExactInventoryForPromotion() t () -> readiness.readCurrentProbeOwner( BINDING, trust, selector, refreshedObservation, BINDING.namespace())); - assertThat(ownerEvidence.plan()).isEqualTo(plan); + assertThat(ownerEvidence.plan()) + .usingRecursiveComparison() + .ignoringFields("entries") + .isEqualTo(plan); + assertThat(ownerEvidence.plan().entries()) + .usingRecursiveFieldByFieldElementComparatorIgnoringFields( + "entryVersion", + "state", + "terminalOutcome", + "signingAttemptedAtEpochSecond", + "compactTokenSha256", + "verificationReceipt") + .containsExactlyElementsOf(plan.entries()); + assertThat(ownerEvidence.plan().entries()) + .extracting(ProbeEntry::state) + .containsExactly( + ProbeState.VERIFIED, + ProbeState.VERIFIED, + ProbeState.VERIFIED, + ProbeState.VERIFIED, + ProbeState.ISSUED, + ProbeState.ISSUED, + ProbeState.ISSUED, + ProbeState.ISSUED); + assertThat(ownerEvidence.plan()) + .isEqualTo( + inTransaction( + context, + () -> readiness.readCurrentPlan(BINDING, trust, result.operationId()))); assertThat(ownerEvidence.entry()).isEqualTo(entry); assertThat(ownerEvidence.expectedPod()).isEqualTo(expectedPod); var ownerResponse = diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java new file mode 100644 index 0000000000..92493cb324 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -0,0 +1,284 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.codec.ByteArrayCodec; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.util.Base64; +import java.util.Collection; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; + +/** + * Genuine Account owner mutations. Fresh creator/legal sources and signer platform evidence are + * explicitly test-only upstream inputs; this fixture is not production activation or settlement. + */ +public final class AccountControlUiOriginalOrderFixture implements AutoCloseable { + private final AccountControlUiOwnerSourcesFixture f; + private final AccountControlUiActorService actors; + private final AccountControlUiIssuanceService issuance; + private final RedisClient accountClient; + private final Path temporary; + + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary) + throws Exception { + this.temporary = temporary; + f = new AccountControlUiOwnerSourcesFixture(jdbcUrl, username, password, temporary, false); + var lifecycle = new AccountControlUiSignerFixture(f, temporary); + lifecycle.commit(); + var originalSigner = f.tx(lifecycle.signer::captureCurrent); + assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) + .isEqualTo(originalSigner.receipt()); + custody("encryption", "enc1", 11); + custody("request-mac", "mac1", 29); + String PASSWORD = UUID.randomUUID().toString(); + var admin = RedisClient.create(RedisURI.Builder.redis(redisHost, redisPort).build()); + accountClient = + RedisClient.create( + RedisURI.Builder.redis(redisHost, redisPort) + .withAuthentication("account_coord_app", PASSWORD) + .build()); + accountClient.setOptions(ClientOptions.builder().autoReconnect(false).build()); + try (var connection = admin.connect(ByteArrayCodec.INSTANCE)) { + connection + .sync() + .aclSetuser( + "account_coord_app", + new io.lettuce.core.AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern("session:auth:token:*") + .addCommand(io.lettuce.core.protocol.CommandType.HELLO) + .addCommand(io.lettuce.core.protocol.CommandType.PING) + .addCommand( + io.lettuce.core.protocol.CommandType.CLIENT, + io.lettuce.core.protocol.CommandKeyword.SETINFO) + .addCommand( + io.lettuce.core.protocol.CommandType.ACL, + io.lettuce.core.protocol.CommandKeyword.WHOAMI) + .addCommand( + io.lettuce.core.protocol.CommandType.SCRIPT, + io.lettuce.core.protocol.CommandKeyword.LOAD) + .addCommand(io.lettuce.core.protocol.CommandType.EVALSHA) + .addCommand(io.lettuce.core.protocol.CommandType.GET) + .addCommand(io.lettuce.core.protocol.CommandType.SET) + .addCommand(io.lettuce.core.protocol.CommandType.PEXPIRETIME) + .addCommand(io.lettuce.core.protocol.CommandType.TIME)); + connection + .sync() + .dispatch( + TestAclCommand.INSTANCE, + new io.lettuce.core.output.StatusOutput<>(ByteArrayCodec.INSTANCE), + new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) + .add("SETUSER") + .add("account_coord_app") + .add("+waitaof")); + awaitLocalAndReplicaAof(connection.sync()); + + } finally { + admin.shutdown(); + } + var registry = + new AccountControlUiCoordination( + () -> accountClient.connect(ByteArrayCodec.INSTANCE), + new AccountGameplayDelegationRedisClient.AcknowledgementRequirements(1, 1, 5000), + testCatalog()); + var operations = new AccountControlUiIssuanceRepository(f.dsl); + var publicSource = + new AccountJwtJwksTrustedSource( + lifecycle.client, lifecycle.trust, lifecycle.desired, lifecycle.publication, f.manager); + actors = + new AccountControlUiActorService( + operations, + f.authority, + lifecycle.signer, + registry, + publicSource, + f.fences, + f.manager, + Clock.systemUTC()); + issuance = + new AccountControlUiIssuanceService( + f.primary, + operations, + f.authority, + f.fences, + lifecycle.signer, + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary.resolve("custody")), Clock.systemUTC()), + registry, + actors, + f.manager, + Clock.systemUTC(), + AccountControlUiOwnerSourcesFixture.CALLER); + } + + public UUID tenantId() { + return f.tenant; + } + + /** Caller supplies the real World plan before Account authenticates and captures its sources. */ + public DraftAuthorizationFenceBinding claimOriginal(DraftCommitBinding complete) { + if (!f.tenant.equals(complete.target().canonicalTenantId())) + throw new IllegalArgumentException("World plan must target the retained Account tenant"); + var issued = issueCreator(); + var compact = issued.compact(); + var environment = issued.environment(); + var sources = f.tx(() -> f.authority.captureInitial(f.tenant, environment)).sources(); + var binding = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + sources) + .withRequiredOwners(); + var claimed = actors.claimOriginalDraft(compact, binding, environment); + assertThat(claimed.ordering().name()).isEqualTo("COMMIT_ORDER"); + assertThat(claimed.binding()).isEqualTo(binding.canonicalBytes()); + var retained = f.tx(() -> f.fences.read(binding)); + assertThat(retained.ordering().name()).isEqualTo("COMMIT_ORDER"); + assertThat(retained.binding()).isEqualTo(binding.canonicalBytes()); + assertThat(retained.orderedAt()).isNotNull(); + return binding; + } + + /** Same-package proof reuse; returns only an actual owner-issued and authenticated credential. */ + IssuedCreator issueCreator() { + var environment = f.terms.captureCurrentEnvironmentBoundary(); + String compact; + try (var peer = + AccountControlUiOwnerSourcesFixture.withPeer( + AccountControlUiOwnerSourcesFixture.CALLER); + var issued = + issuance.issue(f.request(AccountControlUiOwnerSourcesFixture.OTP), environment)) { + compact = new String(issued.compactBytes(), StandardCharsets.US_ASCII); + } + assertThat(f.challenges.findByAccountId(f.account.getId())).isEmpty(); + assertThat(actors.authenticate(compact, f.tenant, environment).accountId()) + .isEqualTo(f.account.getAccountUuid()); + return new IssuedCreator(compact, actors, environment, f); + } + + record IssuedCreator( + String compact, + AccountControlUiActorService actors, + CapturedEnvironmentBoundary environment, + AccountControlUiOwnerSourcesFixture sources) {} + + public net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadService + heldOrderOwner(String namespace) { + return new net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadService( + f.fences, f.manager, namespace); + } + + @Override + public void close() { + accountClient.shutdown(); + } + + private static RedisScriptCatalog testCatalog() { + return RedisScriptCatalog.fromContributions( + List.of( + new RedisScriptContribution() { + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + return List.of(AccountControlUiRegistryContract.descriptor()); + } + })); + } + + private void custody(String purpose, String id, int value) throws Exception { + byte[] key = new byte[32]; + java.util.Arrays.fill(key, (byte) value); + var directory = Files.createDirectories(temporary.resolve("custody").resolve(purpose)); + Files.writeString( + directory.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive " + + id + + " " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n"); + } + + private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + + private static void awaitLocalAndReplicaAof( + io.lettuce.core.api.sync.RedisCommands commands) throws InterruptedException { + byte[] probeKey = + ("test-only:positive-account-coordination-aof-probe:" + UUID.randomUUID()) + .getBytes(StandardCharsets.US_ASCII); + commands.set(probeKey, "test-only-replication-probe".getBytes(StandardCharsets.US_ASCII)); + long deadline = System.nanoTime() + java.time.Duration.ofSeconds(30).toNanos(); + while (System.nanoTime() < deadline) { + List counts = + commands.dispatch( + TestWaitAof.INSTANCE, + new io.lettuce.core.output.ArrayOutput<>(ByteArrayCodec.INSTANCE), + new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) + .add(1) + .add(1) + .add(500)); + if (counts != null + && counts.size() == 2 + && counts.get(0) instanceof Long local + && counts.get(1) instanceof Long replicas + && local >= 1 + && replicas >= 1) { + return; + } + Thread.sleep(50); + } + throw new IllegalStateException("Test Coordination Redis replica did not acknowledge AOF"); + } + + private enum TestWaitAof implements io.lettuce.core.protocol.ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "WAITAOF".getBytes(StandardCharsets.US_ASCII); + } + } + + private enum TestAclCommand implements io.lettuce.core.protocol.ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "ACL".getBytes(StandardCharsets.US_ASCII); + } + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java new file mode 100644 index 0000000000..39c1ac966f --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -0,0 +1,498 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; + +import de.mkammerer.argon2.Argon2Factory; +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftSourceCompositionService; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.mapper.AccountMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient.AcknowledgementRequirements; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.mapstruct.factory.Mappers; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Real Account source/auth owners with explicitly stipulated upstream creator/legal inputs. */ +final class AccountControlUiOwnerSourcesFixture { + private static final String NAMESPACE = "control-ui-owner-proof"; + static final String CALLER = + "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; + public static final String OTP = "test-only-original-creator-otp"; + final DSLContext dsl; + final TransactionTemplate transactions; + final Account account; + final UUID tenant = UUID.randomUUID(), + request = UUID.randomUUID(), + callerContext = UUID.randomUUID(); + final AtomicReference boundary = + new AtomicReference<>(testBoundary("test-production")); + final AtomicInteger coordinationCalls = new AtomicInteger(); + final AccountEmailLoginChallengeRepository challenges; + final AccountHostedTermsService terms; + final AccountControlUiAuthority authority; + final AccountControlUiIssuanceService service; + final DataSourceTransactionManager manager; + final DraftAuthorizationFenceRepository fences; + final AccountServiceImpl primary; + + /** + * Reuses actual Account/source/auth owners while a composed test supplies signer/Redis owners. + */ + AccountControlUiOwnerSourcesFixture( + String jdbcUrl, String username, String password, Path root, boolean installNegativeIssuer) { + String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = new DriverManagerDataSource(jdbcUrl, username, password); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + accountMigrations()) + .load() + .migrate(); + manager = new DataSourceTransactionManager(dataSource); + transactions = new TransactionTemplate(manager); + transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var accounts = new AccountRepository(dsl, sourceEvidence); + account = + tx( + () -> { + Account candidate = new Account(); + String suffix = UUID.randomUUID().toString(); + candidate.setUsername("owner-" + suffix); + candidate.setEmail(suffix + "@example.test"); + candidate.setPasswordHash(hash("test-only-disabled-password")); + candidate.setLoginAuthModes("EMAIL_OTP"); + return accounts.save(candidate); + }); + var creator = testCreation(account.getAccountUuid(), tenant); + var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + tx( + () -> { + fresh.importVerified(creator.creationEvidence()); + generations.initializeTenantIfAbsent(tenant); + return null; + }); + var pairs = new AccountMembershipPairAuthorityRepository(dsl); + var memberships = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var bootstrapOperations = new AccountTenantCreationBootstrapOperationRepository(dsl); + var reader = + new AccountCreatorMembershipSourceReader( + accounts, + new AccountJoinOperationRepository(dsl), + memberships, + pairs, + roles, + fresh, + generations, + outbox, + sourceEvidence, + bootstrapOperations); + var beans = new StaticListableBeanFactory(); + AccountTenantCreationBootstrapAuthorizationSource externalBootstrap = + (actual, mutation) -> { + if (!creator.equals(actual) + || !TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Exact test-only external bootstrap fixture required"); + } + return mutation.get(); + }; + beans.addBean("testOnlyBootstrapAuthority", externalBootstrap); + var bootstrap = + new AccountTenantCreationBootstrapService( + accounts, + fresh, + reader, + pairs, + memberships, + roles, + outbox, + new AccountAuditOutboxRepository(dsl), + bootstrapOperations, + beans.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class)); + tx(() -> bootstrap.bootstrap(creator)); + var party = + new IndividualCreatorPartySource( + UUID.randomUUID(), + account.getAccountUuid(), + VerificationStatus.VERIFIED, + 1L, + "test-only-policy", + 1L, + "test-only-verification", + 1L, + 1L); + insertTestParty(dsl, party); + var parties = new IndividualCreatorPartyRepository(dsl, fresh, bootstrapOperations); + tx(() -> parties.associateFresh(UUID.randomUUID(), creator, party)); + fences = new DraftAuthorizationFenceRepository(dsl); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindings = new HashMap<>(); + terms = + new AccountHostedTermsService( + manager, + new HostedTermsRepository(dsl), + parties, + fences, + id -> externalFixture(publications, id), + id -> externalFixture(actions, id), + new HostedTermsEnvironmentBindingRepository(dsl), + id -> externalFixture(bindings, id), + () -> { + requireOutsideTransaction(); + return boundary.get(); + }); + UUID publication = UUID.randomUUID(); + publications.put( + publication, + new AccountHostedTermsService.PublicationEvidence( + UUID.randomUUID(), + "Test-only Operator", + 1L, + bytes("Test-only initial terms"), + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-only-publication-audit", + 1L, + "test-only-notice", + 1L, + Instant.now().minusSeconds(30).truncatedTo(ChronoUnit.MICROS))); + var catalog = terms.publish(publication).candidate(); + UUID action = UUID.randomUUID(); + actions.put( + action, + new AccountHostedTermsService.AcceptanceAction( + action, + true, + account.getAccountUuid(), + party.creatorPartyId(), + catalog.hostedScopeId(), + catalog.versionId(), + catalog.documentDigest(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + "test-only-affirmative-action", + 1L, + OffsetDateTime.now(ZoneOffset.UTC))); + terms.accept(action); + UUID binding = UUID.randomUUID(); + bindings.put( + binding, + new HostedTermsEnvironmentBinding.PublicationEvidence( + "test-production", + catalog.hostedScopeId(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + catalog.versionId(), + catalog.sourceVersion(), + "test-only-environment-publisher", + "test-only-environment-publication/" + binding, + null, + null)); + terms.publishEnvironmentBinding(binding); + authority = + new AccountControlUiAuthority( + new AccountDraftSourceCompositionService( + dsl, parties, bootstrap, terms, sourceEvidence)); + challenges = new AccountEmailLoginChallengeRepository(dsl); + tx( + () -> { + var challenge = new AccountEmailLoginChallenge(); + var now = LocalDateTime.now().withNano(0); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash(OTP)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); + var primaryTarget = + new AccountServiceImpl( + accounts, + null, + null, + null, + challenges, + null, + null, + Mappers.getMapper(AccountMapper.class), + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + manager); + // Exercise the real MANDATORY interceptor: noRollbackFor must not poison the owner callback. + var primaryProxy = new ProxyFactory(primaryTarget); + primaryProxy.setProxyTargetClass(true); + primaryProxy.addAdvice( + new TransactionInterceptor(manager, new AnnotationTransactionAttributeSource())); + primary = (AccountServiceImpl) primaryProxy.getProxy(); + if (!installNegativeIssuer) { + service = null; + return; + } + var signerRepository = new AccountJwtSignerDesiredStateRepository(dsl); + var trust = new AccountJwtSignerMaterializerTrustBinding(false, ""); + var api = new AccountJwtJwksApiBinding(); + var signer = + new AccountControlUiSignerOwner( + signerRepository, trust, api, root.resolve("private"), root.resolve("public")); + var operations = new AccountControlUiIssuanceRepository(dsl); + var crypto = + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(root.resolve("custody")), Clock.systemUTC()); + var registry = + new AccountControlUiCoordination( + () -> { + coordinationCalls.incrementAndGet(); + throw new IllegalStateException("No physical Redis fixture in this negative proof"); + }, + new AcknowledgementRequirements(1, 1, 1000), + RedisScriptCatalog.fromContributions(List.of())); + var publicSource = + new AccountJwtJwksTrustedSource( + new AccountJwtJwksConfigMapClient(api), + trust, + signerRepository, + new AccountJwtJwksPublicationRepository(dsl, signerRepository), + manager); + var actors = + new AccountControlUiActorService( + operations, + authority, + signer, + registry, + publicSource, + fences, + manager, + Clock.systemUTC()); + service = + new AccountControlUiIssuanceService( + primary, + operations, + authority, + fences, + signer, + crypto, + registry, + actors, + manager, + Clock.systemUTC(), + CALLER); + } + + AccountControlUiIssuanceService.Request request(String secret) { + return new AccountControlUiIssuanceService.Request( + request, account.getEmail(), secret, tenant, callerContext); + } + + T tx(Supplier action) { + return transactions.execute(ignored -> action.get()); + } + + void assertNoIssuance() { + assertThat(dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isZero(); + assertThat(coordinationCalls).hasValue(0); + } + + private static FreshTenantCreatorEvidence testCreation(UUID account, UUID tenant) { + UUID request = UUID.randomUUID(), + operation = UUID.randomUUID(), + authorization = UUID.randomUUID(); + String key = "test-only-game-row-17"; + String digest = + GameTenantCreationDigest.requestDigest(NAMESPACE, request, key, "Test game", null); + var creation = + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + request, + operation, + digest, + tenant, + 17L, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); + String authorizationDigest = "sha256:" + "8".repeat(64); + return new FreshTenantCreatorEvidence( + 1, + creation, + account, + authorization, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, account, authorization, authorizationDigest)); + } + + private static void insertTestParty(DSLContext dsl, IndividualCreatorPartySource party) { + byte[] source = CreatorPartyEncoding.party(party); + dsl.execute( + "INSERT INTO account_individual_creator_party_sources" + + " (creator_party_id, account_uuid, verification_status, identity_version, policy_reference, policy_version," + + " verification_evidence_reference, verification_evidence_version, source_version, source_payload, source_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + source, + CreatorPartyEncoding.digest(source)); + } + + static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary testBoundary(String name) { + byte[] source = bytes("test-only-environment-observation/" + name); + return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + name, + "test-only-environment-owner", + "test-only-observation/" + name, + source, + HostedTermsEncoding.digest(source)); + } + + private static T externalFixture(Map values, UUID request) { + requireOutsideTransaction(); + return Objects.requireNonNull( + values.get(request), "Exact test-only external evidence required"); + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "External fixture observation must precede Account owner locks"); + } + } + + static PeerScope withPeer(String uri) { + var attached = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + return new PeerScope(attached.attach(), attached); + } + + record PeerScope(Context previous, Context attached) implements AutoCloseable { + @Override + public void close() { + attached.detach(previous); + } + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String hash(String value) { + char[] secret = value.toCharArray(); + var argon = Argon2Factory.create(); + try { + return argon.hash(2, 4096, 1, secret); + } finally { + argon.wipeArray(secret); + } + } + + private static Path accountMigrations() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + Path migrations = current.resolve("services/account-service/src/main/resources/db/migration"); + if (java.nio.file.Files.isDirectory(migrations)) return migrations; + current = current.getParent(); + } + throw new IllegalStateException("Exact Account migration directory is required"); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java new file mode 100644 index 0000000000..4a27146e10 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java @@ -0,0 +1,791 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import io.grpc.stub.StreamObserver; +import java.math.BigInteger; +import java.net.URI; +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.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import net.firedevops.firemud.account.v1.EnrollBootstrapRequest; +import net.firedevops.firemud.account.v1.EnrollBootstrapResponse; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; +import net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity; +import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; +import net.firedevops.firemud.account.v1.RecordSecretObservationRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtSignerMaterializationService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.impl.DSL; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import tools.jackson.databind.json.JsonMapper; + +/** + * Actual signer/readiness owner lifecycle; trust, platform inventory and Pod acceptance are + * stipulated test inputs. + */ +final class AccountControlUiSignerFixture { + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String SECRET_UID = "33333333-3333-4333-8333-333333333333"; + private static final String CONFIG_MAP_UID = "44444444-4444-4444-8444-444444444444"; + private static final String TRUST_REVISION = "trust-r1"; + private static final String MATERIALIZER_URI = + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + private static final List MATERIALIZER_PINS = List.of("c".repeat(64)); + private static final String TRUST_DIGEST = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + TRUST_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + MATERIALIZER_PINS); + private static final String API_DIGEST = "b".repeat(64), API_REVISION = "api-r1"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + final AccountControlUiOwnerSourcesFixture f; + final AccountJwtSignerDesiredStateRepository desired; + final AccountJwtJwksPublicationRepository publication; + final AccountJwtReadinessProbeRepository readiness; + final AccountJwtSignerMaterializerTrustBinding trust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + final AccountJwtJwksApiBinding api = mock(AccountJwtJwksApiBinding.class); + final AccountJwtJwksConfigMapClient client = mock(AccountJwtJwksConfigMapClient.class); + final AccountJwtValidatorInventorySource inventory = + mock(AccountJwtValidatorInventorySource.class); + final AtomicReference configMap = + new AtomicReference<>( + new AccountJwtJwksConfigMapClient.ConfigMapSnapshot( + CONFIG_MAP_UID, "41", Map.of("jwks.json", "{\"keys\":[]}"))); + final Path privateRoot, publicRoot; + final AccountJwtSignerBootstrapCoordinator coordinator; + final AccountJwtSignerMaterializationService materializer; + final AccountControlUiSignerOwner signer; + + AccountControlUiSignerFixture(AccountControlUiOwnerSourcesFixture fixture, Path root) + throws Exception { + f = fixture; + privateRoot = Files.createDirectories(root.resolve("private")); + publicRoot = Files.createDirectories(root.resolve("public")); + desired = new AccountJwtSignerDesiredStateRepository(f.dsl); + publication = new AccountJwtJwksPublicationRepository(f.dsl, desired); + readiness = new AccountJwtReadinessProbeRepository(f.dsl, desired, publication); + when(trust.current()).thenReturn(Optional.of(materializerBinding())); + when(api.current()) + .thenReturn( + new AccountJwtJwksApiBinding.ParsedBinding( + API_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + URI.create("https://kubernetes.default.svc:6443/"), + "kubernetes.default.svc", + root.resolve("test-only-ca"), + "d".repeat(64), + root.resolve("test-only-bearer"), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + "system:serviceaccount:firemud-prod:account-service", + API_DIGEST)); + when(client.identity()) + .thenReturn( + new AccountJwtJwksConfigMapClient.BindingIdentity( + API_DIGEST, + API_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + "https://kubernetes.default.svc:6443/", + "kubernetes.default.svc", + "d".repeat(64), + "system:serviceaccount:firemud-prod:account-service")); + when(client.observe()).thenAnswer(ignored -> configMap.get()); + when(client.publish(any(), any())) + .thenAnswer(call -> publish(call.getArgument(0), call.getArgument(1))); + when(client.publishActiveProjection(any(), any(), any())) + .thenAnswer(call -> publish(call.getArgument(0), call.getArgument(2))); + when(inventory.observe(any(ObservationContext.class))) + .thenAnswer(call -> completeInventorySnapshot(now(), call.getArgument(0))); + var mounted = + new AccountJwtJwksPrepublicationService.MountedProjection( + privateRoot, + Path.of("pending.key"), + publicRoot, + Path.of("jwks.json"), + Path.of("jwt-generation.json")); + var prepublication = + new AccountJwtJwksPrepublicationService( + desired, publication, trust, client, f.manager, mounted); + var beans = new StaticListableBeanFactory(); + beans.addBean("testOnlyInventoryInput", inventory); + coordinator = + new AccountJwtSignerBootstrapCoordinator( + trust, + client, + desired, + prepublication, + readiness, + beans.getBeanProvider(AccountJwtValidatorInventorySource.class), + f.transactions); + beans.addBean("actualAccountCoordinator", coordinator); + materializer = + new AccountJwtSignerMaterializationService( + desired, + readiness, + trust, + f.manager, + beans.getBeanProvider(AccountJwtSignerBootstrapCoordinator.class), + beans.getBeanProvider(AccountJwtValidatorInventorySource.class)); + signer = new AccountControlUiSignerOwner(desired, trust, api, privateRoot, publicRoot); + } + + AccountJwtJwksConfigMapClient.CasObservation publish( + AccountJwtJwksConfigMapClient.ConfigMapSnapshot expected, Map data) + throws Exception { + assertThat(configMap.get()).isEqualTo(expected); + var next = + new AccountJwtJwksConfigMapClient.ConfigMapSnapshot( + CONFIG_MAP_UID, Long.toString(Long.parseLong(expected.resourceVersion()) + 1), data); + configMap.set(next); + for (var entry : data.entrySet()) + Files.writeString(publicRoot.resolve(entry.getKey()), entry.getValue()); + return new AccountJwtJwksConfigMapClient.CasObservation( + CONFIG_MAP_UID, + expected.resourceVersion(), + next.resourceVersion(), + data, + data, + AccountJwtJwksConfigMapClient.Outcome.APPLIED); + } + + void commit() throws Exception { + // Only the protected upstream identity is stipulated; every owner method/transaction is real. + try (var authenticated = mockStatic(AccountJwtSignerMaterializerTlsInterceptor.class)) { + authenticated + .when(AccountJwtSignerMaterializerTlsInterceptor::authenticatedBinding) + .thenReturn(materializerBinding()); + AccountControlUiSignerFixture.rpc( + out -> + materializer.enrollBootstrap( + EnrollBootstrapRequest.newBuilder().setSchemaVersion(1).build(), out)); + GetCurrentGenerationRequestResponse initial = + rpc( + out -> + materializer.getCurrentGenerationRequest( + GetCurrentGenerationRequestRequest.newBuilder().setSchemaVersion(1).build(), + out)); + var request = f.tx(() -> desired.readCurrentGenerationRequest(BINDING, trust())); + GetCurrentGenerationRequestResponse observed = + rpc( + out -> + materializer.recordSecretObservation( + RecordSecretObservationRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(initial.getOperationId()) + .setOperationDigest(initial.getOperationDigest()) + .setSecretUid(SECRET_UID) + .setObservedResourceVersion("12") + .build(), + out)); + var pair = generateRsa3072(); + var publicKey = publicJwk(request.targetKid(), (RSAPublicKey) pair.getPublic()); + RecordGenerationResultResponse recorded = + rpc( + out -> + materializer.recordGenerationResult( + RecordGenerationResultRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(initial.getOperationId()) + .setGenerationRequestDigest(observed.getGenerationRequestDigest()) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion("12") + .setObservedResourceVersion("13") + .setPublicJwkJson(publicKey.json()) + .build(), + out)); + var result = f.tx(() -> desired.readCurrentGenerationResult(BINDING, trust())); + assertThat(recorded.getOperationId()).isEqualTo(result.operationId().toString()); + assertThat(recorded.getOperationDigest()).isEqualTo(result.operationDigest()); + assertThat(recorded.getGenerationRequestDigest()).isEqualTo(result.generationRequestDigest()); + assertThat(recorded.getGenerationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(recorded.getObservedResourceVersion()).isEqualTo(result.observedResourceVersion()); + assertThat(recorded.getPublicKeyFingerprint()).isEqualTo(result.publicKeyFingerprint()); + Files.writeString( + privateRoot.resolve("pending.key"), privateBundleJson(request, result, pair)); + assertThat( + coordinator + .reconcileCurrentGenerationOnce(result.operationId()) + .publicKeyPrepublished()) + .isTrue(); + var context = f.tx(() -> readiness.readCurrentInventoryObservationContext(BINDING, trust())); + var plannedAt = now().minusSeconds(300); + var planned = completeInventorySnapshot(plannedAt, context); + var plan = f.tx(() -> readiness.planCurrent(BINDING, trust(), plannedAt, planned)); + var harnessUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"; + var harnessPin = "e".repeat(64); + long validUntil = now().plusSeconds(3600).getEpochSecond(); + String readinessDigest = + net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding + .computeBindingDigest( + "test-readiness-r1", + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + harnessUri, + List.of(harnessPin), + "test-only-validator", + validUntil); + var harness = + new net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + harnessUri, + List.of(harnessPin), + "test-readiness-r1", + "account-service", + "test-only-validator", + validUntil, + readinessDigest); + var peer = + new net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding + .PeerIdentity(harnessUri, harnessPin); + var claim = + f.tx(() -> readiness.claimSingleDelivery(BINDING, trust(), plan, harness, peer, now())); + var producer = + new AccountJwtReadinessProbeService( + readiness, + f.transactions, + Clock.systemUTC(), + privateRoot, + Path.of("pending.key"), + publicRoot, + Path.of("jwks.json")); + var delivered = + producer.issueCurrentPlan( + BINDING, + trust(), + result.operationId(), + claim, + (metadata, compact) -> { + assertThat(compact).isNotEmpty(); + var issued = + f + .tx(() -> readiness.readCurrentPlan(BINDING, trust(), result.operationId())) + .entries() + .stream() + .filter(entry -> entry.jti().equals(metadata.jti())) + .findFirst() + .orElseThrow(); + var current = completeInventorySnapshot(now(), context); + var pods = + f.tx( + () -> readiness.readCurrentExpectedPods(BINDING, trust(), issued, current)); + for (var pod : pods) { + var acceptance = testAuthenticatedAcceptance(issued, pod, now().getEpochSecond()); + f.tx( + () -> + readiness.recordPodAcceptance( + BINDING, trust(), issued, pod, acceptance, current)); + } + }); + assertThat(delivered) + .hasSize(8) + .allSatisfy( + entry -> + assertThat(entry.state()) + .isEqualTo(AccountJwtReadinessProbeRepository.ProbeState.VERIFIED)); + assertThat(f.dsl.fetchCount(DSL.table("account_jwt_readiness_pod_receipts"))).isEqualTo(12); + assertThat( + f.dsl.fetchCount( + DSL.table("account_jwt_readiness_pod_receipts"), + DSL.field("outcome").eq("INAPPLICABLE_REJECT"))) + .isEqualTo(2); + var prepared = coordinator.prepareCurrentPromotionOnce().orElseThrow(); + GetCurrentPromotionRequestResponse dispatched = + rpc( + out -> + materializer.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + out)); + var promotion = + f.tx(() -> desired.readPreparedGenerationForRecovery(BINDING, trust())).promotion(); + assertThat(prepared.operationId()).isEqualTo(promotion.operationId()); + assertThat(dispatched.getPromotionOperationId()) + .isEqualTo(promotion.operationId().toString()); + assertThat(dispatched.getPromotionRequestDigest()).isEqualTo(promotion.requestDigest()); + assertThat(dispatched.getGenerationOperationId()).isEqualTo(result.operationId().toString()); + assertThat(dispatched.getGenerationOperationDigest()).isEqualTo(result.operationDigest()); + assertThat(dispatched.getGenerationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(dispatched.getExpectedSecretUid()).isEqualTo(promotion.secretUid()); + assertThat(dispatched.getExpectedSecretResourceVersion()) + .isEqualTo(promotion.expectedPrivateResourceVersion()); + Files.writeString( + privateRoot.resolve("current.key"), privateBundleJson(request, result, pair)); + RecordPrivatePromotionResultResponse committed = + rpc( + out -> + materializer.recordPrivatePromotionResult( + RecordPrivatePromotionResultRequest.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(promotion.operationId().toString()) + .setPromotionRequestDigest(promotion.requestDigest()) + .setGenerationOperationId(result.operationId().toString()) + .setGenerationOperationDigest(result.operationDigest()) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion( + promotion.expectedPrivateResourceVersion()) + .setObservedResourceVersion("14") + .setCurrent( + PromotionPublicKeyIdentity.newBuilder() + .setGeneration(result.targetGeneration()) + .setKid(result.targetKid()) + .setPublicKeyFingerprint(result.publicKeyFingerprint())) + .addResultingSlots("current") + .build(), + out)); + var durableCommit = + f.tx(() -> desired.readCurrentCommittedSigner(BINDING, trust(), API_DIGEST, API_REVISION)) + .orElseThrow(); + assertThat(committed.getPromotionOperationId()) + .isEqualTo(durableCommit.promotion().operationId().toString()); + assertThat(committed.getGenerationOperationId()) + .isEqualTo(durableCommit.generationResult().operationId().toString()); + assertThat(committed.getObservedResourceVersion()) + .isEqualTo(durableCommit.privateReceipt().observedResourceVersion()); + assertThat(committed.getPublicReceiptDigest()) + .isEqualTo(durableCommit.privateReceipt().receiptDigest()); + } + } + + private static T rpc(Consumer> invocation) { + AtomicReference result = new AtomicReference<>(); + AtomicReference failure = new AtomicReference<>(); + invocation.accept( + new StreamObserver<>() { + @Override + public void onNext(T value) { + result.set(value); + } + + @Override + public void onError(Throwable error) { + failure.set(error); + } + + @Override + public void onCompleted() {} + }); + if (failure.get() != null) + throw new AssertionError("Actual Account materialization RPC failed", failure.get()); + return java.util.Objects.requireNonNull(result.get()); + } + + private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + + private static Instant now() { + return Instant.ofEpochSecond(Instant.now().getEpochSecond()); + } + + private static TrustFence trust() { + return new TrustFence(CLUSTER_UID, NAMESPACE_UID, TRUST_DIGEST, TRUST_REVISION); + } + + private static AccountJwtSignerMaterializerTrustBinding.Binding materializerBinding() { + return new AccountJwtSignerMaterializerTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + MATERIALIZER_PINS, + TRUST_REVISION, + TRUST_DIGEST); + } + + private static String privateBundleJson( + GenerationRequest request, GenerationResult result, KeyPair pair) { + Map bundle = new LinkedHashMap<>(); + bundle.put("version", 1); + bundle.put("environmentId", request.binding().environmentId()); + bundle.put("clusterId", request.binding().clusterId()); + bundle.put("namespace", request.binding().namespace()); + bundle.put("operationId", request.operationId().toString()); + bundle.put("generation", result.targetGeneration()); + bundle.put("kid", result.targetKid()); + bundle.put("algorithm", "RS256"); + bundle.put( + "privateKeyPkcs8", + Base64.getUrlEncoder().withoutPadding().encodeToString(pair.getPrivate().getEncoded())); + bundle.put("publicKeyFingerprint", result.publicKeyFingerprint()); + return JSON.writeValueAsString(bundle); + } + + private static PublicJwk publicJwk(String kid, RSAPublicKey key) throws Exception { + String modulus = encodeUnsigned(key.getModulus()); + String exponent = encodeUnsigned(key.getPublicExponent()); + Map jwk = new LinkedHashMap<>(); + jwk.put("alg", "RS256"); + jwk.put("e", exponent); + jwk.put("key_ops", List.of("verify")); + jwk.put("kid", kid); + jwk.put("kty", "RSA"); + jwk.put("n", modulus); + jwk.put("use", "sig"); + String json = canonicalJson(jwk); + Map withoutKeyOps = new LinkedHashMap<>(jwk); + withoutKeyOps.remove("key_ops"); + String jsonWithoutKeyOps = canonicalJson(withoutKeyOps); + String fingerprint = + sha256( + Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(Map.of("e", exponent, "kty", "RSA", "n", modulus)))); + return new PublicJwk(json, jsonWithoutKeyOps, fingerprint); + } + + private static String canonicalJson(Map value) throws Exception { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + private static KeyPair generateRsa3072() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3_072); + return generator.generateKeyPair(); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is required for the persistence fixture", ex); + } + } + + /** Stipulated platform input only; Account's real owners derive all private proof from it. */ + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, ObservationContext observationContext) { + return completeInventorySnapshot(observedAt, "10.11.0.11", observationContext); + } + + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, String firstAccountPodIp, ObservationContext observationContext) { + return completeInventorySnapshot( + observedAt, firstAccountPodIp, observationContext, "77777777-7777-4777-8777-777777777777"); + } + + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, + String firstAccountPodIp, + ObservationContext observationContext, + String firstAccountPodUid) { + String accountImage = "registry.example/account-validator@sha256:" + "1".repeat(64); + String gameSessionImage = "registry.example/game-session-validator@sha256:" + "3".repeat(64); + String accountConfigDigest = "2".repeat(64); + String gameSessionConfigDigest = "4".repeat(64); + String accountServiceUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator"; + String gameSessionServiceUri = "spiffe://firemud/ns/firemud-prod/sa/game-session-jwt-validator"; + List accountProfiles = + List.of( + new ProfileExpectation("control-ui", "control-ui"), + new ProfileExpectation("game-session-account-delegation", "account-service"), + new ProfileExpectation("player-bootstrap", "player-bootstrap")); + List gameSessionProfiles = + List.of(new ProfileExpectation("game-session-account-delegation", "account-service")); + List accountPods = + List.of( + inventoryPod( + "account-a", + firstAccountPodUid, + "account-rs", + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "acct1", + firstAccountPodIp, + 9443, + accountImage, + accountConfigDigest, + accountServiceUri, + "5".repeat(64)), + inventoryPod( + "account-b", + "88888888-8888-4888-8888-888888888888", + "account-rs", + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "acct1", + "10.11.0.12", + 9443, + accountImage, + accountConfigDigest, + accountServiceUri, + "6".repeat(64))); + List gameSessionPods = + List.of( + inventoryPod( + "game-session-a", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "game-session-rs", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "games", + "10.12.0.11", + 9444, + gameSessionImage, + gameSessionConfigDigest, + gameSessionServiceUri, + "7".repeat(64))); + List validators = + List.of( + new ValidatorObservation( + "account-service", + "account-service", + "66666666-6666-4666-8666-666666666666", + 1L, + "51", + 2, + accountImage, + accountConfigDigest, + 300, + accountProfiles, + accountPods, + List.of()), + new ValidatorObservation( + "game-session-service", + "game-session-service", + "99999999-9999-4999-8999-999999999999", + 1L, + "52", + 1, + gameSessionImage, + gameSessionConfigDigest, + 300, + gameSessionProfiles, + gameSessionPods, + List.of())); + List> validatorMaps = + List.of( + inventoryValidatorMap(validators.get(0), accountServiceUri, 9443), + inventoryValidatorMap(validators.get(1), gameSessionServiceUri, 9444)); + Map preimage = new LinkedHashMap<>(); + preimage.put("domain", "firemud-account-validator-inventory/v2"); + preimage.put("environmentId", BINDING.environmentId()); + preimage.put("clusterId", BINDING.clusterId()); + preimage.put("clusterIncarnationUid", CLUSTER_UID); + preimage.put("namespace", BINDING.namespace()); + preimage.put("namespaceUid", NAMESPACE_UID); + preimage.put("apiBindingRevision", API_REVISION); + preimage.put("apiBindingDigest", API_DIGEST); + preimage.put("inventoryBindingRevision", "inventory-r1"); + preimage.put("inventoryBindingDigest", "c".repeat(64)); + preimage.put( + "observationContext", + Map.of( + "purpose", observationContext.purpose().name(), + "operationId", observationContext.operationId().toString(), + "operationDigest", observationContext.operationDigest())); + preimage.put("validators", validatorMaps); + byte[] bytes; + try { + bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + } catch (Exception failure) { + throw new AssertionError(failure); + } + InventorySnapshot snapshot = mock(InventorySnapshot.class); + when(snapshot.observedAt()).thenReturn(observedAt); + when(snapshot.environmentId()).thenReturn(BINDING.environmentId()); + when(snapshot.clusterId()).thenReturn(BINDING.clusterId()); + when(snapshot.clusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(snapshot.namespace()).thenReturn(BINDING.namespace()); + when(snapshot.namespaceUid()).thenReturn(NAMESPACE_UID); + when(snapshot.apiBindingRevision()).thenReturn(API_REVISION); + when(snapshot.apiBindingDigest()).thenReturn(API_DIGEST); + when(snapshot.inventoryBindingRevision()).thenReturn("inventory-r1"); + when(snapshot.inventoryBindingDigest()).thenReturn("c".repeat(64)); + when(snapshot.observationContext()).thenReturn(Optional.of(observationContext)); + when(snapshot.validators()).thenReturn(validators); + when(snapshot.canonicalBytes()).thenReturn(bytes.clone()); + when(snapshot.digest()).thenReturn(sha256(bytes)); + return snapshot; + } + + private static PodObservation inventoryPod( + String name, + String uid, + String ownerName, + String ownerUid, + String podTemplateHash, + String podIp, + int receiverPort, + String image, + String configDigest, + String serviceUri, + String spkiDigest) { + String host = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + return new PodObservation( + name, + uid, + "11", + ownerName, + ownerUid, + podTemplateHash, + image, + configDigest, + podIp, + URI.create("grpcs://" + host + ":" + receiverPort), + serviceUri, + spkiDigest); + } + + private static Map inventoryValidatorMap( + ValidatorObservation validator, String serviceUri, int receiverPort) { + Map result = new LinkedHashMap<>(); + result.put("validatorId", validator.validatorId()); + result.put("deploymentName", validator.deploymentName()); + result.put("deploymentUid", validator.deploymentUid()); + result.put("deploymentGeneration", Long.toString(validator.deploymentGeneration())); + result.put("deploymentResourceVersion", validator.deploymentResourceVersion()); + result.put("replicas", Integer.toString(validator.replicas())); + result.put("image", validator.image()); + result.put("verifierConfigSha256", validator.verifierConfigSha256()); + result.put("maxCacheAgeSeconds", Integer.toString(validator.maxCacheAgeSeconds())); + result.put( + "profiles", + validator.profiles().stream() + .map( + profile -> + Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .toList()); + result.put( + "pods", + validator.pods().stream() + .map( + pod -> + Map.ofEntries( + Map.entry("name", pod.name()), + Map.entry("uid", pod.uid()), + Map.entry("resourceVersion", pod.resourceVersion()), + Map.entry("ownerReplicaSetName", pod.ownerName()), + Map.entry("ownerReplicaSetUid", pod.ownerUid()), + Map.entry("podTemplateHash", pod.podTemplateHash()), + Map.entry("image", pod.image()), + Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), + Map.entry("podIp", pod.podIp()), + Map.entry("exactPodEndpoint", pod.endpoint().toString()), + Map.entry("canonicalServiceUri", pod.receiverServiceUri()), + Map.entry("leafSpkiSha256", pod.leafSpkiSha256()))) + .toList()); + result.put("receiverServiceUri", serviceUri); + result.put("receiverPort", receiverPort); + result.put("replicaSets", List.of()); + return result; + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + long observedAtEpochSecond) { + return testAuthenticatedAcceptance( + entry, expectedPod, observedAtEpochSecond, entry.targetKid()); + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + long observedAtEpochSecond, + String verifiedKid) { + return testAuthenticatedAcceptance( + entry, + expectedPod, + observedAtEpochSecond, + verifiedKid, + expectedPod.target().exactPodEndpoint().orElseThrow().toString()); + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + long observedAtEpochSecond, + String verifiedKid, + String actualPodEndpoint) { + var target = expectedPod.target(); + return AccountJwtReadinessReceiverInvocationPort.authenticatedAcceptance( + target.podUid(), + actualPodEndpoint, + target.image(), + target.verifierConfigSha256(), + target.canonicalServiceUri().orElseThrow(), + target.podLeafSpkiSha256().orElseThrow(), + entry.jti(), + entry.compactTokenSha256().orElseThrow(), + verifiedKid, + target.expectation(), + observedAtEpochSecond); + } +} diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index e1e883e154..c124123251 100644 --- a/services/world-management-service/build.gradle.kts +++ b/services/world-management-service/build.gradle.kts @@ -13,6 +13,7 @@ firemudJooq { } dependencies { + integrationTestImplementation(project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof"))) implementation(project(":common-security")) testImplementation(libs.bouncycastle.pkix) testCompileOnly(libs.spotbugs.annotations) diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java new file mode 100644 index 0000000000..4593576532 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -0,0 +1,778 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.util.JsonFormat; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +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 java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadClient; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +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.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.WorldManagementServiceApplication; +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.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.jooq.DSLContext; +import org.jooq.impl.DSL; +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.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** + * Real Account COMMIT_ORDER -> real World APPLIED -> authenticated exact immutable selector read. + * Platform/custody, legal source, and upstream Game Design source/version/selection inputs are + * test-only stipulations. No release, settlement, admission, deadline-bearing write or activation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = "spring.grpc.server.port=0") +class WorldAccountAuthorizedDraftPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final long GAME_DESIGN_VERSION = 9_000_000_000_000_001L; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer accountPostgres = + new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("positive-control-ui-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "positive-control-ui-primary", + "6379"); + + @TempDir Path temporary; + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private PlatformTransactionManager manager; + @Autowired private WorldAuthoredSourceIntakeRepository intakeRepository; + @Autowired private WorldDesignPublicationFenceRepository fence; + @Autowired private ObjectMapper mapper; + @Autowired private WorldAuthoredGraphSnapshotRepository snapshots; + + @Autowired + private net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService + digestService; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @MockitoBean(enforceOverride = true) + private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + + @Test + void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() throws Exception { + try (var account = + new AccountControlUiOriginalOrderFixture( + accountPostgres.getJdbcUrl(), + accountPostgres.getUsername(), + accountPostgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary.resolve("account"))) { + var world = fixture(intakeRepository, manager, dsl, account.tenantId()); + var plan = plan(world); + // The real World plan is supplied before Account captures sources and claims original order. + var original = account.claimOriginal(plan.binding()); + var operation = + new WorldDraftTerminalOperation( + original.operationId(), + original.requestId(), + original.commitId(), + original.fenceId(), + original.tenantId(), + original.versionId(), + plan.binding(), + plan.ownerBinding(), + original.canonicalBytes()); + var application = new WorldDraftGraphApplication(operation, plan); + var pki = new TestPki(temporary.resolve("pki")); + var accountServer = + serve( + new AccountDraftCommitOrderReadGrpcService( + account.heldOrderOwner(NAMESPACE), NAMESPACE), + pki.accountServer, + pki); + try { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + accountServer.getPort()); + try (var read = + new DraftCommitOrderReadClient( + endpoints, + pki.worldClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + read.init(); + var heldRequest = + DraftCommitOrderReadEvidence.Request.create(NAMESPACE, original.canonicalBytes()); + assertThat(read.read(heldRequest).request()).isEqualTo(heldRequest); + var writer = + new WorldDraftGraphApplicationService( + appliedRepository(), manager, new WorldDraftCommitOrderVerifier(read, NAMESPACE)); + var applied = writer.apply(application); + assertThat(applied.status()).isEqualTo("APPLIED"); + assertThat(applied.application().operation().accountBindingBytes()) + .isEqualTo(original.canonicalBytes()); + assertThat(applied.application().plan().binding().canonicalBytes()) + .isEqualTo(plan.binding().canonicalBytes()); + assertThat(writer.readCommitted(application).orElseThrow().canonicalBytes()) + .isEqualTo(applied.canonicalBytes()); + assertThat(writer.apply(application).canonicalBytes()) + .isEqualTo(applied.canonicalBytes()); + // Freeze a test-only publication selection of these actual authored owner rows. + var frozen = capture(plan); + var selectors = + new WorldPublishedStartLocationRepository( + dsl, frozenRepository(), appliedRepository()); + var retained = selectors.readCommitted(frozen.request().freeze()).orElseThrow(); + var request = selectorRequest(frozen.request().freeze()); + var worldServer = + serve( + new WorldPublishedStartLocationReadGrpcService(selectors, NAMESPACE), + pki.worldServer, + pki); + try { + endpoints.setWorldManagementService("localhost:" + worldServer.getPort()); + try (var client = + new WorldPublishedStartLocationClient( + endpoints, + pki.gameDesignClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + client.init(); + var evidence = client.read(request); + assertThat(evidence.request()).isEqualTo(request); + assertThat(evidence.originalAccountBindingBytes()) + .isEqualTo(original.canonicalBytes()); + assertThat(evidence.appliedResultBytes()).isEqualTo(applied.canonicalBytes()); + assertThat(evidence.selectorReceiptBytes()) + .isEqualTo(retained.selectorReceipt().canonicalBytes()); + assertThat(client.read(request).canonicalBytes()) + .isEqualTo(evidence.canonicalBytes()); + } + // Trusted CA alone is not authority: the World workload cannot read the GD-only + // selector. + try (var wrong = + new WorldPublishedStartLocationClient( + endpoints, + pki.worldClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + wrong.init(); + assertThatThrownBy(() -> wrong.read(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + } + } finally { + stop(worldServer); + } + // APPLIED does not settle either owner or replace the original Account ordering. + assertThat(read.read(heldRequest).request()).isEqualTo(heldRequest); + assertThat(dsl.fetchCount(DSL.table("world_draft_graph_application"))).isEqualTo(1); + } + } finally { + stop(accountServer); + } + } + } + + private WorldDraftGraphApplicationRepository appliedRepository() { + return new WorldDraftGraphApplicationRepository(dsl, fence, mapper); + } + + private WorldCanonicalFrozenTopologyRepository frozenRepository() { + return new WorldCanonicalFrozenTopologyRepository( + dsl, snapshots, new WorldDraftTopologyCommitRepository(dsl, fence, mapper), digestService); + } + + private TransactionTemplate ownerTransaction() { + return ownerTransaction(manager); + } + + private TransactionTemplate ownerTransaction(PlatformTransactionManager owner) { + var tx = new TransactionTemplate(owner); + tx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return tx; + } + + private static String json(WorldDesignMutationRevision mutation) { + try { + return JsonFormat.printer().omittingInsignificantWhitespace().print(mutation); + } catch (InvalidProtocolBufferException failure) { + throw new AssertionError(failure); + } + } + + private static WorldPublishedStartLocationEvidence.Request selectorRequest( + WorldAuthoredGraphSnapshot.CaptureRequest freeze) { + return new WorldPublishedStartLocationEvidence.Request( + freeze.targetNamespace(), + freeze.canonicalTenantId(), + freeze.canonicalVersionId(), + freeze.intakeRequestId(), + freeze.publicationFence(), + freeze.publicationRequestId(), + freeze.requestDigest(), + freeze.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + freeze.contentDigest(), + freeze.digestSchemaVersion(), + freeze.suppliedOwnedAffectedTuples().stream() + .map( + t -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + t.owner(), + t.aggregateType(), + t.aggregateId(), + t.scopeType(), + t.scopeId(), + t.expectedEpoch())) + .toList()); + } + + private static Server serve(io.grpc.BindableService service, TestIdentity identity, TestPki pki) + throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer(identity.certificate.toFile(), identity.key.toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Test server did not stop"); + } + + private Fixture fixture( + WorldAuthoredSourceIntakeRepository sourceIntake, + PlatformTransactionManager transactionManager, + DSLContext context, + UUID tenant) { + UUID registration = UUID.randomUUID(); + UUID sourceOperation = UUID.randomUUID(); + String tenantSlug = "tenant-" + tenant.toString().replace("-", ""); + String worldSlug = "world-" + UUID.randomUUID().toString().replace("-", ""); + long sourceRow = Math.max(1L, UUID.randomUUID().getLeastSignificantBits() & Long.MAX_VALUE); + String sourceTenant = "gd-row-" + sourceRow; + String digest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, tenant, tenantSlug, worldSlug, "Synthetic component world"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + sourceOperation, + digest, + tenant, + tenantSlug, + worldSlug, + "Synthetic component world", + sourceRow, + sourceTenant, + "NEW_GAME_ROW", + evidenceDigest); + UUID intakeRequest = UUID.randomUUID(); + ownerTransaction(transactionManager) + .execute(status -> sourceIntake.acceptFresh(NAMESPACE, intakeRequest, source)); + WorldAuthoredSourceIntakeReceipt intake = + sourceIntake.read(NAMESPACE, intakeRequest).orElseThrow(); + return Objects.requireNonNull( + ownerTransaction(transactionManager) + .execute( + status -> { + UUID canonicalVersion = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + worldSlug, + sourceOperation, + evidenceDigest, + GAME_DESIGN_VERSION); + WorldAuthoredVersionIdentityReceipt version = + new WorldAuthoredVersionIdentityRepository(context) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + tenant, + canonicalVersion, + version.operationId(), + GAME_DESIGN_VERSION, + intakeRequest, + intake.operationId(), + intake.requestDigest(), + sourceOperation, + evidenceDigest, + intake.receiptDigest()); + return new Fixture(intake, version, owner); + })); + } + + private WorldDraftTopologyCommitPlan plan(Fixture f) { + UUID logical = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + List values = new ArrayList<>(); + values.add( + mutation( + commit, + logical, + logical, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("region") + .setWeather("rain") + .setShardId(7)) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder().setName("zone").setRegionId(logical.toString())) + .build()); + values.add( + mutation( + commit, logical, logical, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("room") + .setZoneId(logical.toString()) + .setDescription("description") + .setNameLocalizedVariantsJson("{\"en\":\"room\"}") + .setDescriptionLocalizedVariantsJson("{\"en\":\"description\"}")) + .build()); + var declaration = + WorldFreshGraphDeclaration.newBuilder() + .setTenantId(f.owner().canonicalTenantId().toString()) + .setVersionId(f.owner().canonicalVersionId().toString()) + .setStartLocation( + net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef.newBuilder() + .setTenantId(f.owner().canonicalTenantId().toString()) + .setVersionId(f.owner().canonicalVersionId().toString()) + .setRoomTemplateId(logical.toString())) + .addFamilyCounts( + count(values, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION)) + .addFamilyCounts( + count(values, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE)) + .addFamilyCounts( + count(values, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM)) + .addFamilyCounts( + count(values, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT)) + .addFamilyCounts( + count(values, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE)) + .addFamilyCounts( + count( + values, + WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) + .build(); + values.set(0, values.getFirst().toBuilder().setFreshGraphDeclaration(declaration).build()); + List revisions = new ArrayList<>(); + List units = new ArrayList<>(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + "synthetic Game Design control-plane input")); + units.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "VERSION", + f.owner().canonicalVersionId().toString(), + "AGGREGATE", + f.owner().canonicalVersionId().toString(), + "0")); + // Original input order deliberately places children before their parents. + for (var m : values.reversed()) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(m.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + json(m))); + String family = m.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "AGGREGATE", + m.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + m.getAggregateId(), + "REGION_SUBTREE", + m.getScopeId(), + "0")); + } + var s = f.intake().source(); + var target = + new DraftCommitBinding.TargetProof( + f.owner().canonicalTenantId(), + f.owner().canonicalVersionId(), + GAME_DESIGN_VERSION, + s.sourceGameTenantKey(), + s.sourceGameRowId(), + s.sourceGameTenantKey(), + s.provenanceKind()); + return WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + target, UUID.randomUUID(), commit, "retained-base", revisions, units), + f.owner()); + } + + private WorldFreshGraphFamilyCount count( + List mutations, WorldDesignAggregateType family) { + int count = + (int) mutations.stream().filter(mutation -> mutation.getAggregateType() == family).count(); + return WorldFreshGraphFamilyCount.newBuilder().setFamily(family).setCount(count).build(); + } + + private WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID id, UUID scope, WorldDesignAggregateType type) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(id.toString()) + .setAggregateType(type) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(scope.toString()); + } + + private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) { + var owner = plan.ownerBinding(); + String publicationRequest = "selector-" + UUID.randomUUID(); + // Stipulated test-only Game Design selection; no release/settlement is claimed. + var evidence = + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + publicationRequest, + "a".repeat(64), + 1, + "publish:" + owner.canonicalTenantId() + ":publish-request:" + publicationRequest); + var attempt = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, + () -> { + var identity = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT local_tenant_key,local_version_key FROM world_authored_version_identity WHERE operation_id=?", + owner.versionIdentityOperationId())); + var digest = + digestService.getDraftDesignDigest( + identity.get("local_tenant_key", Long.class).toString(), + identity.get("local_version_key", Long.class).toString()); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + plan.binding().commitId().toString(), digest.contentDigest(), 3); + }))); + var tuples = + plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldAuthoredGraphSnapshot.CaptureRequest( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.intakeRequestId(), + attempt.publicationFence(), + publicationRequest, + evidence.requestDigest(), + evidence.versionStateEpoch(), + evidence.publishWorkflowId(), + attempt.checkpoint().appliedCommitId(), + attempt.checkpoint().contentDigest(), + attempt.checkpoint().digestSchemaVersion(), + tuples); + return new WorldCanonicalFrozenTopologyService(frozenRepository(), manager) + .capture(new WorldCanonicalFrozenTopology.Request(plan, request)); + } + + private record Fixture( + WorldAuthoredSourceIntakeReceipt intake, + WorldAuthoredVersionIdentityReceipt version, + OwnerBinding owner) {} + + /** Ephemeral certificate authority, never a deployed trust root or live workload credential. */ + private static final class TestPki { + final Path ca; + final TestIdentity accountServer, worldServer, worldClient, gameDesignClient; + + TestPki(Path root) throws Exception { + Files.createDirectories(root); + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var caKeys = generator.generateKeyPair(); + var name = new org.bouncycastle.asn1.x500.X500Name("CN=Test-only Account World proof CA"); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + name, + java.math.BigInteger.ONE, + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + name, + caKeys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(true)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage(org.bouncycastle.asn1.x509.KeyUsage.keyCertSign)); + var signer = + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()); + var caCert = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate(builder.build(signer)); + ca = pem(root.resolve("ca.pem"), caCert); + accountServer = issue(root, "account-service", true, caKeys, caCert); + worldServer = issue(root, "world-management-service", true, caKeys, caCert); + worldClient = issue(root, "world-management-service", false, caKeys, caCert); + gameDesignClient = issue(root, "game-design-service", false, caKeys, caCert); + } + + private static TestIdentity issue( + Path root, + String service, + boolean server, + java.security.KeyPair caKeys, + java.security.cert.X509Certificate caCert) + throws Exception { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var keys = generator.generateKeyPair(); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caCert, + new java.math.BigInteger(120, new java.security.SecureRandom()), + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + new org.bouncycastle.asn1.x500.X500Name("CN=" + service), + keys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(false)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage( + org.bouncycastle.asn1.x509.KeyUsage.digitalSignature + | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.extendedKeyUsage, + false, + new org.bouncycastle.asn1.x509.ExtendedKeyUsage( + server + ? org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_serverAuth + : org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_clientAuth)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, + false, + new org.bouncycastle.asn1.x509.GeneralNames( + new org.bouncycastle.asn1.x509.GeneralName[] { + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.uniformResourceIdentifier, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.dNSName, "localhost"), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.iPAddress, "127.0.0.1") + })); + var certificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + builder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + String prefix = service + (server ? "-server" : "-client"); + return new TestIdentity( + pem(root.resolve(prefix + ".crt"), certificate), + pem(root.resolve(prefix + ".key"), keys.getPrivate())); + } + + private static Path pem(Path path, Object value) throws Exception { + try (var writer = + new org.bouncycastle.openssl.jcajce.JcaPEMWriter(Files.newBufferedWriter(path))) { + writer.writeObject(value); + } + return path; + } + } + + private record TestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var result = new CommonGrpcClientProperties(); + result.setPlaintext(false); + result.setCertChain(certificate.toString()); + result.setPrivateKey(key.toString()); + result.setCaCert(ca.toString()); + return result; + } + } +} From 906fb30de00192d29d88513769cdd2bc3ec544f7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:09:04 +1300 Subject: [PATCH 026/129] Bind distinct Account publication authority and repair owner proof guards --- .../account-service/api-contracts.md | 2 + ...ame-authoring-publishing-and-activation.md | 2 + .../prove-protected-pod-boundary.sh | 3 +- .../protected-pod-live-proof-contract.sh | 7 + .../publication_authorization_service.proto | 39 ++ .../DraftAuthorizationFenceRepository.java | 32 + .../session/AccountControlUiActorService.java | 4 +- ...blicationAuthorizationReadGrpcService.java | 78 +++ ...ntPublicationAuthorizationReadService.java | 80 +++ ...untPublicationAuthorizationRepository.java | 235 +++++++ ...ccountPublicationAuthorizationService.java | 54 ++ ...unt_selected_publication_authorization.sql | 182 +++++ ...t_jwt_signer_promotion_receipt_binding.sql | 125 ++++ ...dinessProbePersistenceIntegrationTest.java | 4 +- ...nAuthorizationPostgresIntegrationTest.java | 621 ++++++++++++++++++ ...blicationAuthorizationReadServiceTest.java | 227 +++++++ ...ntPublicationAuthorizationServiceTest.java | 43 ++ ...ccountPublicationAuthorizationBinding.java | 4 +- ...untPublicationAuthorizationReadClient.java | 159 +++++ ...tPublicationAuthorizationReadEvidence.java | 115 ++++ ...PublicationAuthorizationReadGrpcCodec.java | 108 +++ ...ublicationAuthorizationReadClientTest.java | 165 +++++ ...icationAuthorizationReadGrpcCodecTest.java | 172 +++++ 23 files changed, 2455 insertions(+), 6 deletions(-) create mode 100644 protos/account/v1/publication_authorization_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java create mode 100644 services/account-service/src/main/resources/db/migration/V103__account_selected_publication_authorization.sql create mode 100644 services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodecTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index ab3c239ffc..5451787a9e 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -78,6 +78,8 @@ For `security_locked` accounts, Account's successful recovery authorization issu ## gRPC APIs +The standalone, unregistered `AccountPublicationAuthorizationReadService.ReadHeldPublicationAuthorization` contract is defined in [its proto](../../../../protos/account/v1/publication_authorization_service.proto). Only the verified same-namespace Game Design workload may read an exact retained, distinct publication authorization; the complete canonical binding and digest are lookup evidence, not caller authority. `HELD` confirms the original Account order and source participation, not Game Design publication, World application, owner settlement, or admission. Original Draft permission cannot substitute. Runtime registration and composed proof remain gated in [Game Authoring, Publishing and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). + `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. 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 af8e7734fa..0d2b2f8a21 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The standalone Account selected-publication producer now defines a distinct immutable authorization from the current initial creator, selected Draft descriptor and original issuance/source/checkpoint evidence. Its unregistered owner reader permits only the verified same-namespace Game Design workload, checks exact retained participation and committed issuance in one independent snapshot, and returns no publication terminal result. Pending publication participates in source-writer and prepare-before-disclose guards. These are implementation and proof definitions: the World descriptor in the Account-local fixture is stipulated, physical PostgreSQL/Redis execution and actual authenticated transport composition remain unproved, and no runtime path is enabled. Physical CI for `72d6c8a11d933c7d1fedba6876bb1577a3cad051` executed 221 Account and 201 World integration cases without skips; the Account positive-owner and World composition cases failed on the same signer guard's nonexistent promotion-row receipt field, and a readiness read-only fixture incorrectly expected zero previously stored receipts. Additive V104 binds the immutable readiness plan's generation receipt to the actual generation result, while the corrected read-only assertion preserves the existing receipt count. Corrected physical execution remains required. The earlier fail-closed admission WAL-coverage denial did not reproduce in this run's 40 passing lease-persistence cases; that does not establish its underlying cause or justify relaxing durability. + The current Gameplay-prerequisite construction remains non-activating. Full-version finalization reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. Production backend control-ui issuance/current-actor integration, complete Account source-writer fencing and the callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. In particular, the distinct selected-publication operation still needs authenticated Account authorization; original Draft permission cannot substitute. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Construction CI at `f14c7950827dd435ac0fe5c4cc230a1de32fa96d` executed all 74 Game Design and 200 World integration cases without skips or failures, including the corrected canonical-release and selected-publication transaction regressions. Its 220 Account integration executions passed the future-terms, environment-binding, disclosure-handoff and three real Redis registry cases; one readiness-promotion fixture assertion still compared its initial plan with subsequently progressed entries. A corrected assertion and the composed Account-to-World handoff need separate validation. These bounded results do not upgrade the broader capability ratings below. The minimum backend control-ui construction is standalone and unregistered: real Account primary-authentication extraction, immutable issuance/candidate/commit storage, distinct protected response custody, asymmetric signing, exact registry CAS/readback and current-actor original Draft ordering are defined for one existing initial creator. Permanent original-response loss records a non-authorizing terminal intent before external revocation; unavailable or ambiguous readback cannot establish completed revocation. Issuance and Draft ordering deny deadline-qualified terms evidence because physical commit-time enforcement is not supplied. The additive Account held-order read authenticates World and reads the exact retained `COMMIT_ORDER` plus pending settlement in one owner transaction; its World verifier uses a strict Account mTLS client. That read alone does not close the later-scheduling race: terms may acquire a disclosed deadline after the original no-deadline capture, while catalog activation waits for owner settlement and World still sees the original order. Account scheduling and the World physical commit need a proved safe boundary before runtime wiring; a preflight timestamp or postponed disclosed date is insufficient. These adapters are unregistered, and a structural carrier or an injected test owner is not authentication. At `ed928219ee3428073910f1845eaa975e8814a30a`, local validation is complete for the held-order/source-fencing batch, but physical PostgreSQL validation was skipped. The Account-owned disclosure journal now defines an immutable request, predecessor/candidate, effective instant, exact source vector and opaque authority binding, with exact dispatch/ambiguity/result readback. Its non-revoking preparation check refuses already-reserved or unsettled original operations under sorted source locks. The journal now serializes dispatch authorization and original reserve/claim under the same sorted source locks. PREPARED alone permits ordinary original acquisition; first dispatch rechecks exact settlement, while authorized, ambiguous or disclosed handoffs deny a new no-deadline order only for their exact changed terms source evidence. Existing original retries and obsolete source history do not acquire new authority or blanket-block unrelated sources. Focused both-ordering and concurrency proof definitions are present, but physical PostgreSQL execution remains required. This is still a bounded storage/ordering foundation: complete capture/currentness integration, authenticated notice production/readback and the physical World deadline gate remain unimplemented or unproved; there is no production disclosure/currentness path. Reconsider only after focused PostgreSQL proof covers both orderings of preparation versus original `COMMIT_ORDER` acquisition and settlement, every deadline-introduction path including environment binding, exact retry/restart/ambiguous-notice readback, and World commit-time denial at the disclosed instant without early ordinary-authoring freeze or date rewriting. Consolidated validation, physical PostgreSQL/Coordination recovery and source races, historical signer rotation, protected production caller/custody bindings, real Account-to-World application and the distinct Account publication-authority producer remain open. No source capture, registry row, local signing result or compiled fixture grants runtime activation. The current catalog scheduling correction checks the exact operative terms source before introducing a future deadline, and a binding change checks existing predecessor/current sources only when it would newly expose a different scope's scheduled future deadline. Focused PostgreSQL definitions cover denial while an original operation is unsettled, exact request retry after owner settlement, same-scope non-introducing binding refresh, and the existing non-deadline pending behavior; the consolidated Account gate passed, but these PostgreSQL cases skipped locally without Docker and still require physical execution. This adds local ordering/denial proof only: actual notice dispatch, authenticated production authority and World commit-time enforcement remain unavailable. Future-only proposal/final-result digest design: exclude generated notice-result fields alone from the pre-disclosure proposal digest; bind all exact source, document, materiality, operator, scope, effective-time and authorized-notice inputs; then bind the unchanged proposal together with the authenticated result into the final catalog. `candidateDigest` remains opaque/uncomputed today, so this is a future design note, not a present digest-cycle defect. diff --git a/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh b/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh index b6ac8f68c4..37451fe05d 100644 --- a/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh +++ b/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh @@ -188,7 +188,8 @@ for app in ("account-service", "game-session-service"): deny(field, lambda p, field=field: p["spec"].update({field: True}), boundary, host_message) deny("hostPath", lambda p: p["spec"]["volumes"].append({"name": "host", "hostPath": {"path": "/tmp"}}), boundary, host_message) deny("sysctls", lambda p: p["spec"]["securityContext"].update({"sysctls": [{"name": "net.ipv4.ip_local_port_range", "value": "1024 65535"}]}), boundary, host_message) - for label, change in (("privileged", {"privileged": True}), ("escalation", {"allowPrivilegeEscalation": True}), + for label, change in (("privileged", {"privileged": True, "allowPrivilegeEscalation": True}), + ("escalation", {"allowPrivilegeEscalation": True}), ("NET_ADMIN", {"capabilities": {"drop": ["ALL"], "add": ["NET_ADMIN"]}}), ("missing-drop", {"capabilities": {"drop": []}}), ("procMount", {"procMount": "Unmasked"})): deny(label, lambda p, change=change: p["spec"]["containers"][0]["securityContext"].update(change), boundary, container_message) diff --git a/dev-tools/tests/protected-pod-live-proof-contract.sh b/dev-tools/tests/protected-pod-live-proof-contract.sh index 46abb40c37..e1bb068f6f 100644 --- a/dev-tools/tests/protected-pod-live-proof-contract.sh +++ b/dev-tools/tests/protected-pod-live-proof-contract.sh @@ -121,6 +121,11 @@ if args[0] == 'replace': spec = pod['spec'] container = spec['containers'][0] security = container['securityContext'] +# Kubernetes rejects privileged=true with allowPrivilegeEscalation=false at +# schema validation, before the protected-Pod admission policy can deny it. +if security.get('privileged') and security.get('allowPrivilegeEscalation') is False: + print('Error from server (BadRequest): privileged containers require allowPrivilegeEscalation=true', file=sys.stderr) + sys.exit(1) policy = None message = None if any(spec.get(k) for k in ('hostNetwork', 'hostPID', 'hostIPC')) or any('hostPath' in v for v in spec['volumes']) or spec['securityContext'].get('sysctls'): @@ -197,6 +202,8 @@ with tempfile.TemporaryDirectory(prefix="firemud-pod-proof-contract-") as direct assert "UNPROVED: CNI/socket" in result.stdout assert "ephemeral privilege escape" in result.stdout assert "game-session-service CREATE shadow-" in result.stdout + assert "PASS account-service CREATE privileged" in result.stdout + assert "PASS game-session-service CREATE privileged" in result.stdout print("PASS mock-kubectl " + mode) pod["metadata"]["namespace"] = "pr-23" pod_file.write_text(json.dumps(pod), encoding="utf-8") diff --git a/protos/account/v1/publication_authorization_service.proto b/protos/account/v1/publication_authorization_service.proto new file mode 100644 index 0000000000..39594d7db0 --- /dev/null +++ b/protos/account/v1/publication_authorization_service.proto @@ -0,0 +1,39 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone read of a distinct immutable selected-publication authorization. Account must +// authenticate only the exact same-namespace Game Design workload peer for this method. It does +// not read or reuse the original Draft COMMIT_ORDER. +service AccountPublicationAuthorizationReadService { + rpc ReadHeldPublicationAuthorization(ReadHeldPublicationAuthorizationRequest) + returns (ReadHeldPublicationAuthorizationResponse); +} + +message ReadHeldPublicationAuthorizationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical AccountPublicationAuthorizationBinding bytes and their SHA-256 digest. + // The tuple is a lookup identity, not caller authority. + bytes original_publication_authorization_binding = 4; + string publication_authorization_digest = 5; +} + +enum HeldPublicationAuthorizationStatus { + HELD_PUBLICATION_AUTHORIZATION_STATUS_UNSPECIFIED = 0; + HELD_PUBLICATION_AUTHORIZATION_STATUS_HELD = 1; +} + +message ReadHeldPublicationAuthorizationResponse { + // The complete request tuple is echoed exactly. Only HELD is a successful response. + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_publication_authorization_binding = 4; + string publication_authorization_digest = 5; + HeldPublicationAuthorizationStatus status = 6; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 400876ec77..5d24429b60 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -249,6 +249,7 @@ public void requireDisclosurePreparation(List exactSources) { if (hasWaitingChange(sources)) { throw new IllegalStateException("Applicable Account source change is unresolved"); } + requireNoPendingPublication(sources); for (UUID operationId : affectedOperations(sources)) { Record row = readOperation(operationId); if (row == null) { @@ -300,6 +301,34 @@ private void requireNoAuthorizedDisclosure(List sources) { } } + /** Distinct publication admission after authenticated source capture and sorted source locks. */ + public void requirePublicationAdmission(List sources) { + requireTransaction(); + lockProducerSourcesNowait(sources); + if (hasWaitingChange(sources)) { + throw new IllegalStateException("Applicable authority source change is waiting"); + } + requireNoAuthorizedDisclosure(sources); + } + + private boolean hasPendingPublication(List sources) { + for (SourceEvidence source : sources) { + if (!dsl.fetch( + "SELECT operation_id FROM account_selected_publication_sources WHERE source_key = ?", + source.key()) + .isEmpty()) { + return true; + } + } + return false; + } + + private void requireNoPendingPublication(List sources) { + if (hasPendingPublication(sources)) { + throw new IllegalStateException("Distinct selected-publication operation remains pending"); + } + } + /** * Commit this WAITING result even when false: rolling back would lose revocation intent. True * means settled or an exact SOURCE_COMMITTED replay; call sourceMutationPermitted before writing. @@ -730,6 +759,9 @@ private List affectedOperations(List sources) { * evidence always remains pending. */ private boolean allAffectedSettled(List sources) { + if (hasPendingPublication(sources)) { + return false; + } for (UUID operation : affectedOperations(sources)) { Record row = readOperation(operation); if (settlement(originalBinding(row), Ordering.valueOf(row.get("ordering", String.class))) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java index ceaa10cf60..3a63a9df9f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -105,7 +105,7 @@ public DraftAuthorizationFenceRepository.FenceSnapshot claimOriginalDraft( }); } - private T withCurrent( + T withCurrent( String compactJwt, UUID selectedTenant, CapturedEnvironmentBoundary environment, @@ -186,7 +186,7 @@ private static boolean exactSources( return true; } - private record Current( + record Current( AccountControlUiIssuanceRepository.Stored stored, AccountControlUiAuthority.Snapshot source) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java new file mode 100644 index 0000000000..3bedfb6d7e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountPublicationAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadGrpcCodec; + +/** Standalone endpoint only: peer authentication precedes decoding and persistence lookup. */ +public final class AccountPublicationAuthorizationReadGrpcService + extends AccountPublicationAuthorizationReadServiceGrpc + .AccountPublicationAuthorizationReadServiceImplBase { + private final AccountPublicationAuthorizationReadService owner; + private final String trustedNamespace; + + public AccountPublicationAuthorizationReadGrpcService( + AccountPublicationAuthorizationReadService owner, String trustedNamespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest request, + StreamObserver observer) { + try { + AccountPublicationAuthorizationReadService.requirePeer(trustedNamespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence + .Request + decoded; + try { + decoded = AccountPublicationAuthorizationReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical Account publication read required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Account publication namespace differs from peer") + .asRuntimeException()); + return; + } + final ReadHeldPublicationAuthorizationResponse response; + try { + owner.requireHeld(decoded); + response = AccountPublicationAuthorizationReadGrpcCodec.toHeldResponse(decoded); + } catch (StatusRuntimeException failure) { + observer.onError( + Status.fromCode(Status.fromThrowable(failure).getCode()) + .withDescription("Account publication authorization owner read denied or unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Account publication owner read unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java new file mode 100644 index 0000000000..37fca75217 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java @@ -0,0 +1,80 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered owner read of a distinct retained publication order; never a terminal result. */ +public final class AccountPublicationAuthorizationReadService { + private final AccountPublicationAuthorizationRepository repository; + private final String trustedNamespace; + private final TransactionTemplate ownerTransaction; + + public AccountPublicationAuthorizationReadService( + AccountPublicationAuthorizationRepository repository, + PlatformTransactionManager transactions, + String trustedNamespace) { + this.repository = Objects.requireNonNull(repository); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + public void requireHeld(AccountPublicationAuthorizationReadEvidence.Request request) { + requirePeer(trustedNamespace); + Objects.requireNonNull(request); + if (!trustedNamespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("Account publication namespace differs from peer") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent Account publication owner transaction required") + .asRuntimeException(); + } + try { + ownerTransaction.execute( + status -> { + repository.readHeld(request.binding()); + return null; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (IllegalArgumentException inconsistent) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact held Account publication authorization unavailable") + .asRuntimeException(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Account publication owner read unavailable") + .asRuntimeException(); + } + } + + static void requirePeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java new file mode 100644 index 0000000000..5bd6d47c47 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java @@ -0,0 +1,235 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-transaction persistence only; no caller-carried terminal proof is accepted. */ +public final class AccountPublicationAuthorizationRepository { + private final DSLContext dsl; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner persistence collaborator.") + public AccountPublicationAuthorizationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + AccountPublicationAuthorizationBinding authorize( + AccountPublicationAuthorizationBinding.PreallocationInput input, + WorldPublishedStartLocationEvidence world, + AccountControlUiActorService.Current current, + Runnable admission) { + requireTransaction(); + Record prior = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations" + + " WHERE tenant_uuid = ? AND publish_request_id = ? FOR UPDATE", + current.stored().tenantId, + input.selection().intent().publishRequestId()); + if (prior != null) { + var original = + AccountPublicationAuthorizationBinding.fromStored(prior.get("binding", byte[].class)); + requireExact(prior, original, input, world, current); + return original; + } + admission.run(); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, current.source().sources()); + // The shared closed operation checks the entire selection and World relation, not authority. + new GameDesignPublicationOperationBinding(binding, world); + dsl.execute( + "INSERT INTO account_selected_publication_authorizations" + + " (operation_id, fence_id, actor_account_uuid, tenant_uuid, publish_request_id," + + " input_digest, binding, world_evidence, issuance_operation_id, issuance_fence," + + " source_payload, issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + input.actorAccountId(), + binding.tenantId(), + binding.publishRequestId(), + input.digest(), + binding.canonicalBytes(), + world.canonicalBytes(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints())); + for (var source : binding.sources()) { + dsl.execute( + "INSERT INTO account_selected_publication_sources" + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + source.key(), + source.canonicalBytes()); + } + Record retained = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations WHERE operation_id = ? FOR UPDATE", + binding.operationId()); + requireExact(retained, binding, input, world, current); + return binding; + } + + /** Exact owner read; caller-carried structure alone can never establish HELD. */ + public void readHeld(AccountPublicationAuthorizationBinding requested) { + requireTransaction(); + Objects.requireNonNull(requested); + // Sources precede the operation. No transport is permitted in this owner transaction. + for (var source : requested.sources()) { + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks" + + " WHERE source_key = ? FOR UPDATE", + source.key()) + == null) { + throw new IllegalArgumentException("Original publication source lock is absent"); + } + } + Record row = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations" + + " WHERE operation_id = ? FOR UPDATE", + requested.operationId()); + if (row == null + || !Arrays.equals(requested.canonicalBytes(), row.get("binding", byte[].class))) { + throw new IllegalArgumentException("Exact held publication authorization is absent"); + } + var retained = + AccountPublicationAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + var world = + WorldPublishedStartLocationEvidence.fromStored(row.get("world_evidence", byte[].class)); + new GameDesignPublicationOperationBinding(retained, world); + // Issuance producers acquire this row before source capture. Do not wait backwards while + // holding sources; a concurrent issuer/source writer must cause a retry, never a lock cycle. + Record issuance = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations" + + " WHERE operation_id = ? FOR UPDATE NOWAIT", + row.get("issuance_operation_id", UUID.class)); + if (issuance == null) { + throw new IllegalArgumentException("Original committed issuance is absent"); + } + var originalIssuer = new AccountControlUiIssuanceRepository.Stored(issuance); + var bundle = AccountControlUiIssuanceRepository.object(originalIssuer.bundle); + var sources = AccountControlUiIssuanceRepository.object(originalIssuer.sources); + var rawVector = sources.get("sources"); + if (!"COMMITTED".equals(originalIssuer.status) + || !retained.operationId().equals(row.get("operation_id", UUID.class)) + || !retained.fenceId().equals(row.get("fence_id", UUID.class)) + || !retained.input().actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !retained.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !retained.publishRequestId().equals(row.get("publish_request_id", String.class)) + || !retained.input().digest().equals(row.get("input_digest", String.class)) + || !retained.input().actorAccountId().equals(originalIssuer.accountId) + || !retained.tenantId().equals(originalIssuer.tenantId) + || !originalIssuer.operationId.equals(row.get("issuance_operation_id", UUID.class)) + || !Arrays.equals(originalIssuer.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(originalIssuer.bundle, row.get("issuance_bundle", byte[].class)) + || !(bundle.get("issuanceFence") instanceof Number fence) + || fence.longValue() != row.get("issuance_fence", Long.class) + || !Arrays.equals( + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + bundle.get("outboxCheckpoints")), + row.get("outbox_checkpoints", byte[].class)) + || !originalIssuer.accountId.toString().equals(sources.get("accountId")) + || !originalIssuer.tenantId.toString().equals(sources.get("tenantId")) + || !(rawVector instanceof java.util.List vector) + || vector.size() != retained.sources().size()) { + throw new IllegalArgumentException("Changed original publication issuance evidence"); + } + var participation = + dsl + .fetch( + "SELECT source_key, source_evidence FROM account_selected_publication_sources" + + " WHERE operation_id = ?", + retained.operationId()) + .stream() + .sorted(java.util.Comparator.comparing(r -> r.get("source_key", String.class))) + .toList(); + if (participation.size() != retained.sources().size()) { + throw new IllegalArgumentException("Incomplete original publication source participation"); + } + for (int i = 0; i < retained.sources().size(); i++) { + var source = retained.sources().get(i); + if (!(vector.get(i) instanceof String encoded) + || !Arrays.equals(source.canonicalBytes(), java.util.Base64.getDecoder().decode(encoded)) + || !source.key().equals(participation.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), participation.get(i).get("source_evidence", byte[].class))) { + throw new IllegalArgumentException("Changed original publication source participation"); + } + } + } + + private void requireExact( + Record row, + AccountPublicationAuthorizationBinding binding, + AccountPublicationAuthorizationBinding.PreallocationInput input, + WorldPublishedStartLocationEvidence world, + AccountControlUiActorService.Current current) { + new GameDesignPublicationOperationBinding(binding, world); + if (row == null + || !binding.operationId().equals(row.get("operation_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class)) + || !input.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !binding.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !binding.publishRequestId().equals(row.get("publish_request_id", String.class)) + || !input.digest().equals(row.get("input_digest", String.class)) + || !Arrays.equals(input.canonicalBytes(), binding.input().canonicalBytes()) + || !Arrays.equals(binding.canonicalBytes(), row.get("binding", byte[].class)) + || !Arrays.equals(world.canonicalBytes(), row.get("world_evidence", byte[].class)) + || !current.stored().operationId.equals(row.get("issuance_operation_id", UUID.class)) + || current.source().issuanceFence() != row.get("issuance_fence", Long.class) + || !Arrays.equals(current.stored().sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(current.stored().bundle, row.get("issuance_bundle", byte[].class)) + || !Arrays.equals( + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints()), + row.get("outbox_checkpoints", byte[].class))) { + throw new IllegalArgumentException("Changed immutable selected-publication authorization"); + } + var stored = + dsl + .fetch( + "SELECT source_key, source_evidence FROM account_selected_publication_sources" + + " WHERE operation_id = ?", + binding.operationId()) + .stream() + .sorted(java.util.Comparator.comparing(r -> r.get("source_key", String.class))) + .toList(); + if (stored.size() != binding.sources().size() + || stored.size() != current.source().sources().size()) { + throw new IllegalStateException("Incomplete publication source participation"); + } + for (int i = 0; i < stored.size(); i++) { + var source = binding.sources().get(i); + if (!source.key().equals(stored.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), stored.get(i).get("source_evidence", byte[].class)) + || !Arrays.equals( + source.canonicalBytes(), current.source().sources().get(i).canonicalBytes())) { + throw new IllegalArgumentException("Changed original publication source vector"); + } + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Objects.equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(), + Connection.TRANSACTION_READ_COMMITTED)) { + throw new IllegalStateException("Writable READ_COMMITTED Account owner transaction required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java new file mode 100644 index 0000000000..f6b36779eb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Objects; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** + * Unregistered Account producer for a distinct selected-publication order. Authenticates the + * current initial creator through the real issuance owner. Supplied World evidence is structurally + * checked and retained, not authenticated by this component; protected owner transport remains a + * separate integration boundary. No remote calls, terminalization, or activation occur here. + */ +public final class AccountPublicationAuthorizationService { + private final AccountControlUiActorService actors; + private final DraftAuthorizationFenceRepository fences; + private final AccountPublicationAuthorizationRepository publications; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner transaction collaborators.") + public AccountPublicationAuthorizationService( + AccountControlUiActorService actors, + DraftAuthorizationFenceRepository fences, + AccountPublicationAuthorizationRepository publications) { + this.actors = Objects.requireNonNull(actors); + this.fences = Objects.requireNonNull(fences); + this.publications = Objects.requireNonNull(publications); + } + + public AccountPublicationAuthorizationBinding authorize( + String compactJwt, + AuthoredDraftPublishSelectionBinding selection, + WorldPublishedStartLocationEvidence world, + CapturedEnvironmentBoundary environment) { + Objects.requireNonNull(selection); + Objects.requireNonNull(world); + return actors.withCurrent( + compactJwt, + selection.intent().canonicalTenantId(), + environment, + current -> { + fences.lockProducerSourcesNowait(current.source().sources()); + return publications.authorize( + new AccountPublicationAuthorizationBinding.PreallocationInput( + current.stored().accountId, selection), + world, + current, + () -> fences.requirePublicationAdmission(current.source().sources())); + }); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V103__account_selected_publication_authorization.sql b/services/account-service/src/main/resources/db/migration/V103__account_selected_publication_authorization.sql new file mode 100644 index 0000000000..30afe17861 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V103__account_selected_publication_authorization.sql @@ -0,0 +1,182 @@ +-- Distinct non-activating publication order. There is deliberately no terminal-write surface: +-- authenticated publication-owner readback is a subsequent integration boundary. +CREATE TABLE account_selected_publication_authorizations ( + operation_id UUID PRIMARY KEY, + fence_id UUID NOT NULL UNIQUE, + actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + publish_request_id VARCHAR(256) NOT NULL CHECK (length(publish_request_id) > 0 AND octet_length(publish_request_id) <= 256), + input_digest VARCHAR(71) NOT NULL CHECK (input_digest ~ '^sha256:[0-9a-f]{64}$'), + binding BYTEA NOT NULL CHECK (octet_length(binding) BETWEEN 1 AND 1048576), + world_evidence BYTEA NOT NULL CHECK (octet_length(world_evidence) BETWEEN 1 AND 4194304), + issuance_operation_id UUID NOT NULL REFERENCES account_control_ui_issuance_operations(operation_id), + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + issuance_bundle BYTEA NOT NULL CHECK (octet_length(issuance_bundle) BETWEEN 1 AND 131072), + outbox_checkpoints BYTEA NOT NULL CHECK (octet_length(outbox_checkpoints) BETWEEN 1 AND 131072), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + ordered_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (tenant_uuid, publish_request_id) +); + +CREATE TABLE account_selected_publication_sources ( + operation_id UUID NOT NULL REFERENCES account_selected_publication_authorizations(operation_id), + source_key VARCHAR(512) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_selected_publication_source_lookup ON account_selected_publication_sources(source_key, operation_id); + +-- [jooq ignore start] +CREATE FUNCTION account_selected_publication_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_selected_publication_authorizations + WHERE operation_id = NEW.operation_id AND producer_xid = txid_current()) THEN + RAISE EXCEPTION 'Publication sources must accompany the original owner transaction' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_selected_publication_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + p INTEGER := 1; + parsed BYTEA; + input_bytes BYTEA; + source_bytes BYTEA; + source_position INTEGER; + kind TEXT; + scope TEXT; + source_key_value TEXT; + seen TEXT[] := ARRAY[]::TEXT[]; + source_count INTEGER; + issuer account_control_ui_issuance_operations%ROWTYPE; +BEGIN + SELECT * INTO issuer FROM account_control_ui_issuance_operations WHERE operation_id = NEW.issuance_operation_id; + IF issuer.status IS DISTINCT FROM 'COMMITTED' OR issuer.account_uuid <> NEW.actor_account_uuid + OR issuer.tenant_uuid <> NEW.tenant_uuid OR issuer.source_payload <> NEW.source_payload + OR issuer.bundle_payload <> NEW.issuance_bundle + OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT <> NEW.issuance_fence + OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' + IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB + OR NEW.producer_xid <> txid_current() + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'accountId' <> NEW.actor_account_uuid::TEXT + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'tenantId' <> NEW.tenant_uuid::TEXT THEN + RAISE EXCEPTION 'Publication requires exact original committed issuance evidence' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> 'account-publication-authorization/v1' THEN + RAISE EXCEPTION 'Invalid publication schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.operation_id::TEXT THEN + RAISE EXCEPTION 'Changed publication operation' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.fence_id::TEXT THEN + RAISE EXCEPTION 'Changed publication fence' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO input_bytes, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF 'sha256:' || encode(sha256(input_bytes), 'hex') <> NEW.input_digest THEN + RAISE EXCEPTION 'Changed publication input digest' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(input_bytes, 1); + IF convert_from(parsed, 'UTF8') <> 'account-publication-input/v1' THEN + RAISE EXCEPTION 'Invalid publication input schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(input_bytes, source_position); + IF convert_from(parsed, 'UTF8') <> NEW.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Changed publication actor' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(input_bytes, source_position); + IF convert_from(parsed, 'UTF8')::JSONB->'intent'->>'canonicalTenantId' <> NEW.tenant_uuid::TEXT + OR convert_from(parsed, 'UTF8')::JSONB->'intent'->>'publishRequestId' <> NEW.publish_request_id THEN + RAISE EXCEPTION 'Changed publication selection identity' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + source_count := convert_from(parsed, 'UTF8')::INTEGER; + IF source_count < 1 OR source_count <> (SELECT count(*) FROM account_selected_publication_sources WHERE operation_id = NEW.operation_id) + OR source_count <> jsonb_array_length(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources') THEN + RAISE EXCEPTION 'Incomplete publication sources' USING ERRCODE = '23514'; + END IF; + FOR i IN 1..source_count LOOP + SELECT frame_value, next_position INTO source_bytes, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF source_bytes <> decode(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'->>(i - 1), 'base64') THEN + RAISE EXCEPTION 'Publication source differs from original complete issuance vector' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(source_bytes, 1); + IF convert_from(parsed, 'UTF8') <> 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Invalid publication source schema' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO kind, source_position FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO scope, source_position FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := kind || ':' || scope; + IF source_key_value = ANY(seen) OR NOT EXISTS (SELECT 1 FROM account_selected_publication_sources + WHERE operation_id = NEW.operation_id AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Changed publication source participation' USING ERRCODE = '23514'; + END IF; + seen := array_append(seen, source_key_value); + END LOOP; + IF p <> octet_length(NEW.binding) + 1 THEN + RAISE EXCEPTION 'Trailing publication evidence' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_selected_publication_complete + AFTER INSERT ON account_selected_publication_authorizations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_selected_publication_complete_guard(); +CREATE TRIGGER account_selected_publication_source_insert + BEFORE INSERT ON account_selected_publication_sources FOR EACH ROW + EXECUTE FUNCTION account_selected_publication_source_insert_guard(); +CREATE TRIGGER account_selected_publication_immutable + BEFORE UPDATE OR DELETE ON account_selected_publication_authorizations + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_publication_sources_immutable + BEFORE UPDATE OR DELETE ON account_selected_publication_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_publication_no_truncate + BEFORE TRUNCATE ON account_selected_publication_authorizations + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_publication_sources_no_truncate + BEFORE TRUNCATE ON account_selected_publication_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +-- Preserve original Draft ordering and add the separate publication participants. A Draft +-- terminal readback can never clear this publication hold. +CREATE OR REPLACE FUNCTION account_control_ui_hold_required_sources(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql AS $$ +DECLARE + source_key_value TEXT; + operation_value UUID; +BEGIN + FOR source_key_value IN SELECT value FROM + (SELECT DISTINCT value FROM unnest(source_keys) value WHERE value IS NOT NULL) exact_keys + ORDER BY account_publication_authorization_source_sort_key(value) LOOP + INSERT INTO account_draft_authorization_source_locks(source_key) + VALUES (source_key_value) ON CONFLICT DO NOTHING; + PERFORM source_key FROM account_draft_authorization_source_locks + WHERE source_key = source_key_value FOR UPDATE NOWAIT; + END LOOP; + FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_draft_authorization_sources s WHERE s.source_key = ANY(source_keys) + ORDER BY s.operation_id LOOP + PERFORM operation_id FROM account_draft_authorization_fences + WHERE operation_id = operation_value FOR UPDATE NOWAIT; + IF NOT account_draft_authorization_is_settled(operation_value) THEN + RAISE EXCEPTION 'Required creator source is held until every original owner settles' USING ERRCODE = '55P03'; + END IF; + END LOOP; + FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_selected_publication_sources s WHERE s.source_key = ANY(source_keys) + ORDER BY s.operation_id LOOP + PERFORM operation_id FROM account_selected_publication_authorizations + WHERE operation_id = operation_value FOR UPDATE NOWAIT; + RAISE EXCEPTION 'Distinct selected-publication operation remains pending' USING ERRCODE = '55P03'; + END LOOP; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql b/services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql new file mode 100644 index 0000000000..e3391179d8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql @@ -0,0 +1,125 @@ +-- Correct the promotion insert guard's receipt source without adding a duplicate promotion-row +-- field. The immutable readiness plan already binds the generation receipt digest. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_signer_promotion_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_row RECORD; + generation_row RECORD; + result_row RECORD; + plan_generation_receipt_digest VARCHAR(64); + plan_inventory_complete BOOLEAN; + plan_expires_at BIGINT; + entry_count BIGINT; + verified_count BIGINT; +BEGIN + IF NEW.operation_action <> 'PROMOTE_PENDING' + OR NEW.generation_operation_id IS NULL + OR NEW.expected_cluster_incarnation_uid IS NULL + OR NEW.expected_namespace_uid IS NULL + OR NEW.expected_private_secret_uid IS NULL + OR NEW.expected_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'Promotion request lacks its exact lifecycle binding' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + -- Lock order is desired state, then source generation, then immutable evidence. + SELECT * INTO state_row FROM account_jwt_signer_desired_states + WHERE environment_id = NEW.environment_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT signer desired state is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO generation_row FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation operation is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO result_row FROM account_jwt_signer_generation_results + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation result is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + IF state_row.generation_operation_id IS DISTINCT FROM NEW.generation_operation_id + OR state_row.prepared_operation_id IS NOT NULL + OR state_row.record_version IS DISTINCT FROM NEW.expected_record_version + OR (state_row.cluster_id, state_row.kubernetes_namespace, state_row.custody_mode) + IS DISTINCT FROM (NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode) + OR (state_row.durable_active_generation, state_row.durable_active_kid) + IS DISTINCT FROM (NEW.expected_previous_generation, NEW.expected_previous_kid) + OR (state_row.published_active_generation, state_row.published_active_kid) + IS DISTINCT FROM (NEW.expected_public_active_generation, NEW.expected_public_active_kid) + OR state_row.enrollment_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR state_row.enrollment_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR state_row.enrollment_materializer_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR state_row.enrollment_materializer_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR state_row.enrollment_api_binding_digest IS DISTINCT FROM NEW.api_binding_digest + OR state_row.enrollment_api_config_revision IS DISTINCT FROM NEW.api_config_revision + OR state_row.enrollment_public_config_map_uid IS DISTINCT FROM NEW.expected_public_config_map_uid + OR generation_row.operation_id IS NULL + OR generation_row.environment_id IS DISTINCT FROM NEW.environment_id + OR generation_row.expected_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR generation_row.expected_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR generation_row.trust_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR generation_row.trust_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR generation_row.target_generation IS DISTINCT FROM NEW.target_generation + OR generation_row.target_kid IS DISTINCT FROM NEW.target_kid + OR generation_row.expected_record_version + 1 IS DISTINCT FROM result_row.desired_state_version + OR result_row.secret_uid IS DISTINCT FROM NEW.expected_private_secret_uid + OR result_row.observed_resource_version IS DISTINCT FROM NEW.expected_private_secret_resource_version + OR result_row.public_key_fingerprint IS DISTINCT FROM NEW.target_public_key_fingerprint THEN + RAISE EXCEPTION 'JWT promotion request does not match current Account generation evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + SELECT generation_receipt_digest, validator_inventory_complete, expires_at_epoch_seconds + INTO plan_generation_receipt_digest, plan_inventory_complete, plan_expires_at + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest FOR SHARE; + IF plan_generation_receipt_digest IS DISTINCT FROM result_row.receipt_digest + OR plan_inventory_complete IS DISTINCT FROM TRUE + OR plan_expires_at IS NULL + OR plan_expires_at <= floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT THEN + RAISE EXCEPTION 'JWT promotion requires current complete validator inventory proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + SELECT count(*), count(*) FILTER (WHERE state = 'VERIFIED' + AND verified_at_epoch_seconds < expires_at_epoch_seconds) + INTO entry_count, verified_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest; + IF entry_count = 0 OR verified_count <> entry_count THEN + RAISE EXCEPTION 'JWT promotion requires every exact readiness probe to be VERIFIED' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + + IF NOT EXISTS ( + SELECT 1 FROM account_jwt_jwks_prepublication_intents AS intent + JOIN account_jwt_jwks_publication_receipts AS receipt + ON receipt.operation_id = intent.operation_id + AND receipt.intent_digest = intent.intent_digest + JOIN account_jwt_jwks_mount_observations AS mount + ON mount.operation_id = intent.operation_id + WHERE intent.operation_id = NEW.generation_operation_id + AND intent.intent_digest = NEW.prepublication_intent_digest + AND receipt.receipt_digest = NEW.prepublication_receipt_digest + AND mount.observation_digest = NEW.mounted_observation_digest + AND intent.config_map_uid = NEW.expected_public_config_map_uid + AND intent.api_binding_digest = NEW.api_binding_digest + AND intent.api_config_revision = NEW.api_config_revision + AND receipt.observed_resource_version = NEW.expected_public_jwks_resource_version + AND intent.public_key_fingerprint = NEW.target_public_key_fingerprint + AND intent.jwks_json = NEW.expected_public_jwks_json) THEN + RAISE EXCEPTION 'JWT promotion request does not match exact current prepublication evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java index 15ac85920f..20ea46e8eb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java @@ -896,6 +896,7 @@ void persistsProtectedV2PodClosureAndRequiresFreshExactInventoryForPromotion() t () -> readiness.readCurrentExpectedPods(BINDING, trust, entry, refreshedObservation)); assertThat(targets).isNotEmpty(); if (!testedCurrentProbeOwnerRead && entry.validatorId().equals("game-session-service")) { + long receiptsBeforeOwnerRead = count(context, "account_jwt_readiness_pod_receipts"); var expectedPod = targets.getFirst(); var selector = ownerSelector(plan, entry, expectedPod); var ownerEvidence = @@ -1085,7 +1086,8 @@ void persistsProtectedV2PodClosureAndRequiresFreshExactInventoryForPromotion() t BINDING.namespace()))) .isInstanceOf( AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); - assertThat(count(context, "account_jwt_readiness_pod_receipts")).isZero(); + assertThat(count(context, "account_jwt_readiness_pod_receipts")) + .isEqualTo(receiptsBeforeOwnerRead); testedCurrentProbeOwnerRead = true; } for (AccountJwtReadinessProbeRepository.ExpectedPod target : targets) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java new file mode 100644 index 0000000000..89632928a1 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -0,0 +1,621 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Account signer/issuance/Redis/current-actor and PostgreSQL ordering. World APPLIED and + * synchronized selection bytes below are explicitly test-only upstream stipulations. This does not + * prove authenticated World transport, publication terminalization or runtime activation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountPublicationAuthorizationPostgresIntegrationTest { + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("publication-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "publication-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void authenticatesDistinctOrderReplaysExactlyAndBlocksSourceWritersAndDisclosure() + throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + var original = + service.authorize( + issued.compact(), proof.selection(), proof.world(), issued.environment()); + var replay = + service.authorize( + issued.compact(), proof.selection(), proof.world(), issued.environment()); + assertThat(replay.canonicalBytes()).isEqualTo(original.canonicalBytes()); + assertThat(original.operationId()).isNotEqualTo(proof.original().operationId()); + assertThat(original.fenceId()).isNotEqualTo(proof.original().fenceId()); + assertThat(f.dsl.fetchCount(org.jooq.impl.DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat(original.sources()).hasSize(8); + var readOwner = + new AccountPublicationAuthorizationReadService( + new AccountPublicationAuthorizationRepository(f.dsl), f.manager, "test"); + var readRequest = + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence + .Request.create("test", original); + asGameDesign(() -> readOwner.requireHeld(readRequest)); + var mismatched = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + original.operationId(), UUID.randomUUID(), original.input(), original.sources()); + var unknown = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + UUID.randomUUID(), original.fenceId(), original.input(), original.sources()); + for (var rejected : List.of(mismatched, unknown)) { + assertThatThrownBy( + () -> + asGameDesign( + () -> + readOwner.requireHeld( + net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadEvidence.Request.create( + "test", rejected)))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + } + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(original.sources()); + return null; + })) + .hasMessageContaining("selected-publication"); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), original.sources(), new byte[] {1}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + // An exact retained replay remains possible while a later source change waits. + assertThat( + service + .authorize( + issued.compact(), proof.selection(), proof.world(), issued.environment()) + .canonicalBytes()) + .isEqualTo(original.canonicalBytes()); + asGameDesign(() -> readOwner.requireHeld(readRequest)); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_authorizations SET fence_id = ?", + UUID.randomUUID()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> f.tx(() -> f.dsl.execute("DELETE FROM account_selected_publication_sources"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + var changed = selection(proof.selection().selectedCommit(), "changed notes"); + assertThatThrownBy( + () -> + service.authorize(issued.compact(), changed, proof.world(), issued.environment())) + .isInstanceOf(IllegalArgumentException.class); + var request = proof.world().request(); + var changedWorld = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + UUID.randomUUID(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + proof.world().selectorReceiptBytes(), + proof.world().originalAccountBindingBytes(), + proof.world().appliedResultBytes()); + assertThatThrownBy( + () -> + service.authorize( + issued.compact(), proof.selection(), changedWorld, issued.environment())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed immutable"); + assertThatThrownBy( + () -> + service.authorize( + issued.compact() + "changed", + proof.selection(), + proof.world(), + issued.environment())) + .isInstanceOf(RuntimeException.class); + // Original source/issuance identity is immutable even if a privileged SQL caller tries it. + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_authorizations SET issuance_fence = issuance_fence + 1"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_sources SET source_evidence = ?", + new byte[] {9}))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + + @Test + void earlierWaitingSourceChangeWinsAndDeniedAuthenticationCreatesNoOperation() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var source = + f.tx( + () -> + f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), source.sources(), new byte[] {2}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isTrue(); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + assertThatThrownBy( + () -> + service.authorize( + issued.compact(), proof.selection(), proof.world(), issued.environment())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source change is waiting"); + assertThatThrownBy( + () -> + service.authorize( + "unsigned-caller-claim", + proof.selection(), + proof.world(), + issued.environment())) + .isInstanceOf(RuntimeException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isTrue(); + } + } + + @Test + void actualSourceWriterBlocksCreatorCaptureThenWinsBeforePublication() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + var accounts = new net.firedevops.firemud.accountservice.repository.AccountRepository(f.dsl); + var executor = java.util.concurrent.Executors.newSingleThreadExecutor(); + var attempt = + new java.util.concurrent.atomic.AtomicReference>(); + try { + f.tx( + () -> { + int blockerPid = + java.util.Objects.requireNonNull( + f.dsl.fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected PostgreSQL source-writer connection") + .get("pid", Integer.class); + var account = + java.util.Objects.requireNonNull( + accounts.findByIdForUpdate(f.account.getId()).orElseThrow(), + "Expected locked Account source before canonical role mutation"); + assertThat(account.getRole()).isNotEqualTo("player"); + attempt.set( + executor.submit( + () -> + service.authorize( + issued.compact(), + proof.selection(), + proof.world(), + issued.environment()))); + long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); + Integer blockedPid = null; + while (System.nanoTime() < deadline && blockedPid == null) { + var blocked = + f.dsl.fetchOne( + "SELECT pid FROM pg_stat_activity WHERE datname = current_database()" + + " AND ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' LIMIT 1", + blockerPid); + if (blocked != null) blockedPid = blocked.get("pid", Integer.class); + else Thread.onSpinWait(); + } + assertThat(blockedPid) + .as("Distinct creator connection physically waits on source-writer Account row") + .isNotNull(); + assertThat(blockedPid).isNotEqualTo(blockerPid); + assertThat(attempt.get().isDone()).isFalse(); + // Actual guarded source write, held until this transaction commits. The old signed + // credential cannot authorize a publication from the newly changed Account state. + account.setRole("player"); + assertThat(accounts.save(account).getRole()).isEqualTo("player"); + return null; + }); + assertThatThrownBy(() -> attempt.get().get(10, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(RuntimeException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat(accounts.findById(f.account.getId()).orElseThrow().getRole()) + .isEqualTo("player"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + } + + private AccountControlUiOriginalOrderFixture fixture() throws Exception { + return new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary); + } + + private static void asGameDesign(Runnable action) { + io.grpc.Context.current() + .withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()) + .run(action); + } + + private record Proof( + AuthoredDraftPublishSelectionBinding selection, + WorldPublishedStartLocationEvidence world, + DraftAuthorizationFenceBinding original) {} + + /** Closed World codec bytes copied in spirit from the existing isolated selector fixtures. */ + private static Proof proof( + AccountControlUiOwnerSourcesFixture f, + net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService + .CapturedEnvironmentBoundary + environment) + throws Exception { + UUID version = UUID.randomUUID(), request = UUID.randomUUID(), commit = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + f.tenant, + version, + 17, + "test-private-tenant", + 11, + "test-private-tenant", + "NEW_GAME_ROW"); + List families = List.of("REGION", "ZONE", "ROOM"); + List templates = List.of(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); + List revisions = new ArrayList<>(); + List affected = new ArrayList<>(); + for (int i = 0; i < families.size(); i++) { + UUID revision = UUID.randomUUID(); + var mutation = new LinkedHashMap(); + mutation.put("logicalRevisionId", revision.toString()); + mutation.put("commitId", commit.toString()); + mutation.put("aggregateType", "WORLD_DESIGN_AGGREGATE_TYPE_" + families.get(i)); + mutation.put("aggregateId", templates.get(i).toString()); + if (i == 0) + mutation.put( + "freshGraphDeclaration", + Map.of( + "tenantId", + f.tenant.toString(), + "versionId", + version.toString(), + "startLocation", + Map.of( + "tenantId", + f.tenant.toString(), + "versionId", + version.toString(), + "roomTemplateId", + templates.get(2).toString()), + "familyCounts", + List.of( + "REGION", + "ZONE", + "ROOM", + "ROOM_EXIT", + "GENERATION_RULE", + "WORLD_ENTITY_SPAWN_BINDING") + .stream() + .map( + family -> + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_" + family, + "count", + families.contains(family) ? 1 : 0)) + .toList())); + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + revision, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + new tools.jackson.databind.ObjectMapper().writeValueAsString(mutation))); + affected.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + families.get(i), + templates.get(i).toString(), + "AGGREGATE", + templates.get(i).toString(), + "0")); + } + var draft = DraftCommitBinding.create(target, request, commit, "base-1", revisions, affected); + var selection = selection(draft, "selected publication proof"); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + request, + commit, + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + version, + "base-1", + "0", + draft.canonicalBytes(), + draft.canonicalBytes(), + draft.digest(), + f.tx(() -> f.authority.capture(f.account.getAccountUuid(), f.tenant, environment)) + .sources()); + UUID intake = UUID.randomUUID(); + var operation = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(operation, "world-draft-terminal-operation/v1"); + for (UUID id : + List.of(original.operationId(), request, commit, original.fenceId(), f.tenant, version)) + DraftAuthorizationFenceBinding.frame(operation, id.toString()); + DraftAuthorizationFenceBinding.frame(operation, draft.canonicalBytes()); + for (String value : + List.of( + "test", + f.tenant.toString(), + version.toString(), + original.operationId().toString(), + "17", + intake.toString(), + UUID.randomUUID().toString(), + "a".repeat(64), + UUID.randomUUID().toString(), + "b".repeat(64), + "c".repeat(64), + DraftAuthorizationFenceBinding.digest(original.canonicalBytes()))) + DraftAuthorizationFenceBinding.frame(operation, value); + DraftAuthorizationFenceBinding.frame(operation, original.canonicalBytes()); + List> rows = new ArrayList<>(); + for (int i = 0; i < revisions.size(); i++) { + var mapping = new LinkedHashMap(); + mapping.put("id", i + 1); + mapping.put("target_namespace", "test"); + mapping.put("canonical_tenant_id", f.tenant.toString()); + mapping.put("canonical_version_id", version.toString()); + mapping.put("family", families.get(i)); + mapping.put("template_id", templates.get(i).toString()); + mapping.put("private_row_key", 101 + i); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", original.operationId().toString()); + mapping.put("request_id", request.toString()); + mapping.put("commit_id", commit.toString()); + mapping.put("revision_id", revisions.get(i).revisionId().toString()); + mapping.put("revision_order", Integer.toString(i)); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + byte[] graph = + AccountControlUiAuthority.canonical( + Map.of( + "schemaVersion", + "2", + "canonicalTenantId", + f.tenant.toString(), + "canonicalVersionId", + version.toString(), + "rows", + rows)); + String graphDigest = DraftAuthorizationFenceBinding.digest(graph); + var receipt = + WorldDraftStartLocationEvidence.create( + "test", + original.operationId(), + request, + commit, + original.fenceId(), + DraftAuthorizationFenceBinding.digest(original.canonicalBytes()), + draft.digest(), + new RoomTemplateRef(f.tenant, version, templates.get(2)), + graphDigest); + var applied = new LinkedHashMap(); + applied.put("schema", "world-draft-graph-applied/v2"); + applied.put("status", "APPLIED"); + applied.put("operationBytesBase64", b64(operation.toByteArray())); + applied.put("graphBytesBase64", b64(graph)); + applied.put("graphDigest", graphDigest); + applied.put("startLocationReceiptBase64", b64(receipt.canonicalBytes())); + applied.put("startLocationReceiptDigest", receipt.receiptDigest()); + applied.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + Map.of( + "aggregateType", + u.aggregateType(), + "aggregateId", + u.aggregateId(), + "scopeType", + u.scopeType(), + "scopeId", + u.scopeId(), + "expectedEpoch", + "0", + "resultingEpoch", + "1")) + .toList()); + var worldRequest = + new WorldPublishedStartLocationEvidence.Request( + "test", + f.tenant, + version, + intake, + UUID.randomUUID(), + selection.intent().publishRequestId(), + selection.digest().substring(7), + 5, + PublicationDigestRequestBinding.full( + f.tenant.toString(), "17", selection.intent().publishRequestId()) + .derivedWorkflowIdentity(), + commit.toString(), + "b".repeat(64), + 3, + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList()); + return new Proof( + selection, + new WorldPublishedStartLocationEvidence( + worldRequest, + receipt.canonicalBytes(), + original.canonicalBytes(), + AccountControlUiAuthority.canonical(applied)), + original); + } + + private static String b64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static AuthoredDraftPublishSelectionBinding selection( + DraftCommitBinding draft, String notes) { + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + "publication-request", + "5", + notes, + draft.requestId(), + draft.commitId(), + draft.digest()), + draft.target(), + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + draft.target(), + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java new file mode 100644 index 0000000000..dcc932463a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java @@ -0,0 +1,227 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.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 io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Context-level owner tests; supplied peer contexts are not actual TLS-positive proof. */ +class AccountPublicationAuthorizationReadServiceTest { + private final AccountPublicationAuthorizationRepository repository = + mock(AccountPublicationAuthorizationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final TransactionStatus status = mock(TransactionStatus.class); + private final AccountPublicationAuthorizationReadService service = + new AccountPublicationAuthorizationReadService(repository, transactions, "test"); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void commitsAnIndependentOwnerReadBeforeReturningHeld() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + asPeer("test", "game-design-service", () -> service.requireHeld(request)); + verify(repository).readHeld(any()); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(transactions).commit(status); + } + + @Test + void rejectsUnverifiedWrongWorkloadCrossNamespaceAndAmbientTransactionBeforeLookup() { + var request = request("test"); + assertCode(Status.Code.UNAUTHENTICATED, () -> service.requireHeld(request)); + for (String workload : + List.of("account-service", "world-management-service", "spring-cloud-gateway")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", workload, () -> service.requireHeld(request))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "game-design-service", () -> service.requireHeld(request))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request("other")))); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + verifyNoInteractions(repository, transactions); + } + + @Test + void absentOrChangedOwnerStateCannotProduceHeldAndStorageFailureFailsClosed() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + doThrow(new IllegalArgumentException("absent or changed")).when(repository).readHeld(any()); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + doThrow(new org.jooq.exception.DataAccessException("offline")).when(repository).readHeld(any()); + assertCode( + Status.Code.UNAVAILABLE, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + } + + @Test + void grpcAuthenticatesBeforeDecodingMalformedCallerCarriers() { + var endpoint = new AccountPublicationAuthorizationReadGrpcService(service, "test"); + var error = new AtomicReference(); + StreamObserver observer = + new StreamObserver<>() { + @Override + public void onNext(ReadHeldPublicationAuthorizationResponse value) { + throw new AssertionError("Malformed request cannot return HELD"); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() { + throw new AssertionError("Malformed request cannot complete"); + } + }; + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer); + assertThat(Status.fromThrowable(error.get()).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + asPeer( + "test", + "world-management-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + asPeer( + "other", + "game-design-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + asPeer( + "test", + "game-design-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository, transactions); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(action); + } + + private static AccountPublicationAuthorizationReadEvidence.Request request(String namespace) { + UUID actor = UUID.randomUUID(), + tenant = UUID.randomUUID(), + version = UUID.randomUUID(), + revision = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 17, "test-tenant", 11, "test-tenant", "NEW_GAME_ROW"); + var draft = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", revision, DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "ROOM", + "room", + "ROOM_SCOPE", + "room", + "0"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "proof", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + return AccountPublicationAuthorizationReadEvidence.Request.create(namespace, binding); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java new file mode 100644 index 0000000000..276ee3fe28 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountPublicationAuthorizationServiceTest { + @Test + void persistenceCannotBeCalledWithoutTheWritableAccountOwnerTransaction() { + var dsl = mock(DSLContext.class); + var repository = new AccountPublicationAuthorizationRepository(dsl); + assertThatThrownBy(() -> repository.authorize(null, null, null, () -> {})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable READ_COMMITTED"); + verifyNoInteractions(dsl); + } + + @Test + void readOnlyOrDifferentIsolationCannotMintPublicationPermission() { + var dsl = mock(DSLContext.class); + var repository = new AccountPublicationAuthorizationRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + java.sql.Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.authorize(null, null, null, () -> {})) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + java.sql.Connection.TRANSACTION_REPEATABLE_READ); + assertThatThrownBy(() -> repository.authorize(null, null, null, () -> {})) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java index 8d4257ef55..8c5c4506cd 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationBinding.java @@ -15,8 +15,8 @@ /** * Distinct publication operation's immutable original input and Account source participation. This * validates complete selected Draft structure, not actor authentication or positive source - * authority. The future Account producer must independently establish the complete current source - * vector, including party and operative hosted terms. Draft COMMIT_ORDER and creation results never + * authority. The Account producer must independently establish the complete current source vector, + * including party and operative hosted terms. Draft COMMIT_ORDER and creation results never * authorize or settle this operation. Later World captures and release/artifact results remain * separate and must never rewrite the original selection digest. */ diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClient.java new file mode 100644 index 0000000000..5c1b166de9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClient.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountPublicationAuthorizationReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for Game Design's exact Account authorization read. */ +public final class AccountPublicationAuthorizationReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountPublicationAuthorizationReadServiceGrpc + .AccountPublicationAuthorizationReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountPublicationAuthorizationReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountPublicationAuthorizationReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account publication authorization read client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account publication authorization read stub unavailable"); + } + initialized = true; + } + + /** Returns HELD evidence only after exact Account server identity and response verification. */ + public AccountPublicationAuthorizationReadEvidence read( + AccountPublicationAuthorizationReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account publication authorization read requires no owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account publication authorization read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readHeldPublicationAuthorization( + AccountPublicationAuthorizationReadGrpcCodec.toRequest(request)); + try { + return AccountPublicationAuthorizationReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid publication authorization evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountPublicationAuthorizationReadServiceGrpc + .AccountPublicationAuthorizationReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountPublicationAuthorizationReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountPublicationAuthorizationReadServiceGrpc + .AccountPublicationAuthorizationReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account publication authorization read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account publication authorization read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account publication authorization read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account publication authorization read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account publication authorization read " + label + " must be a file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account publication authorization read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadEvidence.java new file mode 100644 index 0000000000..c2193fa707 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadEvidence.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.common.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** + * Exact HELD read returned by the authenticated Account mTLS client. Constructing the request or + * decoding structurally valid bytes is not proof; callers obtain this value from {@link + * AccountPublicationAuthorizationReadClient} after exact peer and response verification. + */ +public final class AccountPublicationAuthorizationReadEvidence { + private final Request request; + + AccountPublicationAuthorizationReadEvidence(Request request) { + this.request = Objects.requireNonNull(request, "request"); + } + + public Request request() { + return request; + } + + /** Complete immutable Account authorization binding plus read correlation identity and digest. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] originalPublicationAuthorizationBinding, + String publicationAuthorizationDigest) { + public static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported Account publication-authorization read schema version"); + } + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace is required"); + } + if (readRequestId == null || NIL_UUID.equals(readRequestId)) { + throw new IllegalArgumentException("Non-nil read request identity is required"); + } + if (originalPublicationAuthorizationBinding == null + || originalPublicationAuthorizationBinding.length == 0) { + throw new IllegalArgumentException( + "Complete original Account publication authorization binding is required"); + } + originalPublicationAuthorizationBinding = originalPublicationAuthorizationBinding.clone(); + AccountPublicationAuthorizationBinding binding = + AccountPublicationAuthorizationBinding.fromStored( + originalPublicationAuthorizationBinding); + if (!Arrays.equals(originalPublicationAuthorizationBinding, binding.canonicalBytes())) { + throw new IllegalArgumentException( + "Canonical original Account publication authorization binding is required"); + } + String expectedDigest = DraftAuthorizationFenceBinding.digest(binding.canonicalBytes()); + if (!expectedDigest.equals(publicationAuthorizationDigest)) { + throw new IllegalArgumentException( + "Account publication authorization digest differs from its canonical binding"); + } + if (readRequestId.equals(binding.operationId()) || readRequestId.equals(binding.fenceId())) { + throw new IllegalArgumentException( + "Publication authorization read requires a separate request identity"); + } + } + + public static Request create( + String targetNamespace, AccountPublicationAuthorizationBinding binding) { + Objects.requireNonNull(binding, "binding"); + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.fenceId())); + byte[] canonicalBytes = binding.canonicalBytes(); + return new Request( + SCHEMA_VERSION, + targetNamespace, + readRequestId, + canonicalBytes, + DraftAuthorizationFenceBinding.digest(canonicalBytes)); + } + + @Override + public byte[] originalPublicationAuthorizationBinding() { + return originalPublicationAuthorizationBinding.clone(); + } + + public AccountPublicationAuthorizationBinding binding() { + return AccountPublicationAuthorizationBinding.fromStored( + originalPublicationAuthorizationBinding); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals( + originalPublicationAuthorizationBinding, that.originalPublicationAuthorizationBinding) + && publicationAuthorizationDigest.equals(that.publicationAuthorizationDigest); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + schemaVersion, targetNamespace, readRequestId, publicationAuthorizationDigest); + return 31 * result + Arrays.hashCode(originalPublicationAuthorizationBinding); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodec.java new file mode 100644 index 0000000000..cdd0c7c2f8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodec.java @@ -0,0 +1,108 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.HeldPublicationAuthorizationStatus; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; + +/** Closed wire mapping and exact request-echo validation for the Account authorization read. */ +public final class AccountPublicationAuthorizationReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountPublicationAuthorizationReadGrpcCodec() {} + + public static ReadHeldPublicationAuthorizationRequest toRequest( + AccountPublicationAuthorizationReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadHeldPublicationAuthorizationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalPublicationAuthorizationBinding( + ByteString.copyFrom(request.originalPublicationAuthorizationBinding())) + .setPublicationAuthorizationDigest(request.publicationAuthorizationDigest()) + .build(); + } + + /** Decode only after Account authenticates its exact same-namespace Game Design peer. */ + public static AccountPublicationAuthorizationReadEvidence.Request fromRequest( + ReadHeldPublicationAuthorizationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadHeldPublicationAuthorizationRequest"); + try { + return new AccountPublicationAuthorizationReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalUuid(request.getReadRequestId()), + request.getOriginalPublicationAuthorizationBinding().toByteArray(), + request.getPublicationAuthorizationDigest()); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Account publication authorization read request is invalid", invalid); + } + } + + /** Account may emit HELD only after its owner read proves the exact immutable authorization. */ + public static ReadHeldPublicationAuthorizationResponse toHeldResponse( + AccountPublicationAuthorizationReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadHeldPublicationAuthorizationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalPublicationAuthorizationBinding( + ByteString.copyFrom(request.originalPublicationAuthorizationBinding())) + .setPublicationAuthorizationDigest(request.publicationAuthorizationDigest()) + .setStatus(HeldPublicationAuthorizationStatus.HELD_PUBLICATION_AUTHORIZATION_STATUS_HELD) + .build(); + } + + /** Validate a positive response; all other owner states are non-OK RPC failures. */ + static AccountPublicationAuthorizationReadEvidence fromResponse( + AccountPublicationAuthorizationReadEvidence.Request request, + ReadHeldPublicationAuthorizationResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadHeldPublicationAuthorizationResponse"); + if (response.getSchemaVersion() != request.schemaVersion() + || !response.getTargetNamespace().equals(request.targetNamespace()) + || !response.getReadRequestId().equals(request.readRequestId().toString()) + || !Arrays.equals( + response.getOriginalPublicationAuthorizationBinding().toByteArray(), + request.originalPublicationAuthorizationBinding()) + || !response + .getPublicationAuthorizationDigest() + .equals(request.publicationAuthorizationDigest())) { + throw new IllegalArgumentException( + "Account response changed the exact publication authorization read"); + } + if (response.getStatus() + != HeldPublicationAuthorizationStatus.HELD_PUBLICATION_AUTHORIZATION_STATUS_HELD) { + throw new IllegalArgumentException("Account did not confirm held publication authorization"); + } + return new AccountPublicationAuthorizationReadEvidence(request); + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalUuid(String value) { + if (value == null) throw new IllegalArgumentException("Canonical read request UUID required"); + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil read request UUID required"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Canonical non-nil read request UUID required", invalid); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClientTest.java new file mode 100644 index 0000000000..6a6a9118e1 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClientTest.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.AbstractStub; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountPublicationAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; +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.GrpcServerPeerIdentityCallCredentials; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountPublicationAuthorizationReadClientTest { + @Test + void rejectsPlaintextWrongNamespaceAndUninitializedCallsBeforeTransport(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountPublicationAuthorizationReadClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var client = + new AccountPublicationAuthorizationReadClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + try { + var request = AccountPublicationAuthorizationReadGrpcCodecTest.request(); + assertThatThrownBy( + () -> + client.read( + new AccountPublicationAuthorizationReadEvidence.Request( + request.schemaVersion(), + "other", + request.readRequestId(), + request.originalPublicationAuthorizationBinding(), + request.publicationAuthorizationDigest()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(factory); + } finally { + client.close(); + } + } + + @Test + void configuresExactAccountPeerAndReturnsOnlyExactHeldResponse(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(factory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new AccountPublicationAuthorizationReadClient(endpoints, tls(directory), factory, "test"); + try { + client.init(); + AbstractStub initialized = initializedStub(client); + assertThat(initialized.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(initialized.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + + var stub = + mock( + AccountPublicationAuthorizationReadServiceGrpc + .AccountPublicationAuthorizationReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + setStub(client, stub); + var request = AccountPublicationAuthorizationReadGrpcCodecTest.request(); + var held = AccountPublicationAuthorizationReadGrpcCodec.toHeldResponse(request); + when(stub.readHeldPublicationAuthorization(any())).thenReturn(held); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(stub); + + assertThat(client.read(request).request()).isEqualTo(request); + verify(stub).readHeldPublicationAuthorization(any()); + + when(stub.readHeldPublicationAuthorization(any())) + .thenReturn(held.toBuilder().setTargetNamespace("other").build()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid publication authorization evidence"); + when(stub.readHeldPublicationAuthorization(any())) + .thenReturn(ReadHeldPublicationAuthorizationResponse.getDefaultInstance()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid publication authorization evidence"); + when(stub.readHeldPublicationAuthorization(any())) + .thenThrow(Status.UNAVAILABLE.withDescription("offline").asRuntimeException()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + } finally { + client.close(); + } + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return tls; + } + + private static AbstractStub initializedStub(AccountPublicationAuthorizationReadClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + private static void setStub( + AccountPublicationAuthorizationReadClient client, + AccountPublicationAuthorizationReadServiceGrpc + .AccountPublicationAuthorizationReadServiceBlockingStub + stub) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodecTest.java new file mode 100644 index 0000000000..2876d32318 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodecTest.java @@ -0,0 +1,172 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.HeldPublicationAuthorizationStatus; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import org.junit.jupiter.api.Test; + +class AccountPublicationAuthorizationReadGrpcCodecTest { + @Test + void mapsCompleteCanonicalBindingDigestAndStableReadIdentity() { + var request = request(); + + var decoded = + AccountPublicationAuthorizationReadGrpcCodec.fromRequest( + AccountPublicationAuthorizationReadGrpcCodec.toRequest(request)); + var evidence = + AccountPublicationAuthorizationReadGrpcCodec.fromResponse( + request, AccountPublicationAuthorizationReadGrpcCodec.toHeldResponse(request)); + + assertThat(decoded).isEqualTo(request); + assertThat(evidence.request()).isEqualTo(request); + assertThat(evidence.request().binding().canonicalBytes()) + .containsExactly(request.originalPublicationAuthorizationBinding()); + assertThat(evidence.request().binding().operationId()) + .isEqualTo(request.binding().operationId()); + } + + @Test + void rejectsMalformedRequestsUnknownFieldsAndChangedBindingDigest() { + var request = AccountPublicationAuthorizationReadGrpcCodec.toRequest(request()); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatThrownBy( + () -> + AccountPublicationAuthorizationReadGrpcCodec.fromRequest( + request.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AccountPublicationAuthorizationReadGrpcCodec.fromRequest( + request.toBuilder().setReadRequestId("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountPublicationAuthorizationReadGrpcCodec.fromRequest( + request.toBuilder().setSchemaVersion(2).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountPublicationAuthorizationReadGrpcCodec.fromRequest( + request.toBuilder() + .setPublicationAuthorizationDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account publication authorization read request is invalid") + .hasRootCauseMessage( + "Account publication authorization digest differs from its canonical binding"); + } + + @Test + void rejectsResponseSubstitutionUnknownFieldsAndNonHeldStatuses() { + var request = request(); + var held = AccountPublicationAuthorizationReadGrpcCodec.toHeldResponse(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + for (ReadHeldPublicationAuthorizationResponse changed : + List.of( + held.toBuilder().setTargetNamespace("other").build(), + held.toBuilder().setReadRequestId(UUID.randomUUID().toString()).build(), + held.toBuilder() + .setOriginalPublicationAuthorizationBinding(ByteString.copyFrom(new byte[] {1})) + .build(), + held.toBuilder().setPublicationAuthorizationDigest("sha256:" + "0".repeat(64)).build(), + held.toBuilder() + .setStatus( + HeldPublicationAuthorizationStatus + .HELD_PUBLICATION_AUTHORIZATION_STATUS_UNSPECIFIED) + .build(), + held.toBuilder().setUnknownFields(unknown).build())) { + assertThatThrownBy( + () -> AccountPublicationAuthorizationReadGrpcCodec.fromResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + static AccountPublicationAuthorizationReadEvidence.Request request() { + var binding = binding(); + return AccountPublicationAuthorizationReadEvidence.Request.create("test", binding); + } + + static AccountPublicationAuthorizationBinding binding() { + UUID actor = uuid("11111111-1111-4111-8111-111111111111"); + UUID tenant = uuid("22222222-2222-4222-8222-222222222222"); + UUID version = uuid("33333333-3333-4333-8333-333333333333"); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "5", + "test selection", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return new AccountPublicationAuthorizationBinding( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selected), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, actor.toString(), null, "1", null, null, new byte[] {1}))); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} From 20c1ae0f4d1e3e8789438bbf52221f8ea3ab3b14 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:15:11 +1300 Subject: [PATCH 027/129] Admit selected publication only through authenticated owner readbacks --- .../game-design-service/version-control.md | 2 +- ...horizationMtlsPostgresIntegrationTest.java | 405 ++++++++++++++++++ ...nAuthorizationPostgresIntegrationTest.java | 4 +- ...ectedDraftPublicationAdmissionService.java | 165 +++++++ ...dDraftPublicationAdmissionServiceTest.java | 218 ++++++++++ 5 files changed, 791 insertions(+), 3 deletions(-) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index e92aebc03c..c5dbbb4a3c 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -6,7 +6,7 @@ Game Design is the canonical authored-history, publication-coordination, release ## Implementation Status -Full-version finalization now requires the exact original World selector evidence retained by its pending publication operation and passes it to the v2 release-bundle path; missing or changed evidence remains pending for reconciliation, not permission to recapture or abort. The unregistered `SelectedDraftPublicationOwner` reserves one existing synchronized Draft, using its exact immutable selection digest for the pending attempt and source-backed publication operation. Its backend finalization entry requires exact durable selection/operation readback and shares the existing finalization transaction; it does not allocate a replacement Draft or translate a legacy full-publish digest. Typed Account and World inputs are not authentication of their producers. This local enforcement does not supply the missing authenticated creator/Account commit-order producer or enable the standalone selector transport. Current construction and executable proof limits are recorded in the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +Full-version finalization now requires the exact original World selector evidence retained by its pending publication operation and passes it to the v2 release-bundle path; missing or changed evidence remains pending for reconciliation, not permission to recapture or abort. The unregistered `SelectedDraftPublicationOwner` reserves one existing synchronized Draft, using its exact immutable selection digest for the pending attempt and source-backed publication operation. Its backend finalization entry requires exact durable selection/operation readback and shares the existing finalization transaction; it does not allocate a replacement Draft or translate a legacy full-publish digest. Typed Account and World inputs are not authentication of their producers. The standalone, unregistered `SelectedDraftPublicationAdmissionService` obtains both the distinct Account held-publication authorization and exact World selector through their authenticated clients outside SQL, validates their complete operation relationship, then opens the local reservation transaction. Its unit proof covers denial and ordering, not genuine positive transport/release composition. It does not create a World freeze, register a creator ingress, or enable publication or runtime paths. Current construction and executable proof limits are recorded in the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). External Git synchronization and canonical multi-branch merge semantics are not implemented. Current authoring uses Game Design-owned revision APIs with optimistic validation and ordered mutation calls, but `SaveRevision` does not provide deterministic replay: it lacks durable request/revision deduplication and can leave a World mutation committed without its corresponding Game Design revision when the later local save fails. ADR 0129's durable multi-owner coordinator, owner-local compare-and-swap application, synchronized commit fence, and proof that partially applied owner rows remain invisible to ordinary Draft reads are also not implemented. Current release-bundle schema and plugin publication/activation code incorrectly reuse Automation & Scripting's aggregate participant `contentDigest` where the dedicated Game Logic-owned `abilitySchemaDigest` is required; exact ability-schema compatibility therefore remains an implementation and proof gap. Plugin publication currently uses signed-only intake; [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md)'s approved unsigned provenance remains target-only. The plugin publication path now rejects terminal-state reuse: an uploaded `SUPERSEDED` or `REVOKED_DESIGN` row cannot be republished under the same `pluginVersionId`; target rollback still uses a new immutable plugin version and leaves the prior terminal row unchanged, while new-version rollback proof remains absent. Duplicate signed plugin `assetId` values are likewise not rejected before export and can produce ambiguous distribution-manifest keys; target intake rejects them deterministically before publication/export. The live World Management design handoff adds a separate lifecycle race: it checks Game Design's authoritative remote version state (`GetVersionState(...).versionState=DRAFT`) before its own transaction, but has no durable owner-local publication freeze or exact Game Design version-state epoch/fence in the mutation request. That remote state check is not proof that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java new file mode 100644 index 0000000000..bf3f884bee --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -0,0 +1,405 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +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.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Genuine Account issuance/current actor, publication producer/storage, loopback mutual TLS and + * production read client. Trust provisioning, legal sources, synchronized Draft and World APPLIED + * descriptors are explicitly stipulated test inputs. No real World handoff, Game Design release, + * deployed workload trust, public wiring, or activation is established by this isolated proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountPublicationAuthorizationMtlsPostgresIntegrationTest { + private static final String NAMESPACE = "test"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("publication-mtls-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "publication-mtls-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void genuineProducerToMtlsReaderReplaysExactlyAndRejectsTrustedPeerAndBindingSubstitution() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("pki"))); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve("owner")))) { + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var descriptor = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var producer = + new AccountPublicationAuthorizationService(issued.actors(), sources.fences, repository); + var original = + producer.authorize( + issued.compact(), descriptor.selection(), descriptor.world(), issued.environment()); + var request = AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, original); + var endpoint = + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE), + NAMESPACE); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + pki.server.certificate().toFile(), pki.server.key().toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + try { + try (var client = client(server.getPort(), pki.gameDesign, pki.ca)) { + var first = client.read(request); + var retry = client.read(request); + assertThat(first.request()).isEqualTo(request); + assertThat(retry.request()).isEqualTo(first.request()); + assertThat(first.request().originalPublicationAuthorizationBinding()) + .isEqualTo(original.canonicalBytes()); + var freshRead = + AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, original); + assertThat(client.read(freshRead).request()).isEqualTo(freshRead); + var unknown = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), original.fenceId(), original.input(), original.sources()); + var changedFence = + new AccountPublicationAuthorizationBinding( + original.operationId(), UUID.randomUUID(), original.input(), original.sources()); + for (var rejected : List.of(unknown, changedFence)) { + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + client.read( + AccountPublicationAuthorizationReadEvidence.Request.create( + NAMESPACE, rejected))); + } + // A negative read cannot change the exact held owner row or prevent its next read. + assertThat(client.read(request).request()).isEqualTo(request); + } + for (var wrongPeer : List.of(pki.wrongWorkload, pki.otherNamespace)) { + try (var client = client(server.getPort(), wrongPeer, pki.ca)) { + assertCode(Status.Code.PERMISSION_DENIED, () -> client.read(request)); + } + } + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat( + java.util.Objects.requireNonNull( + sources.dsl.fetchOne( + "SELECT binding FROM account_selected_publication_authorizations WHERE operation_id = ?", + original.operationId()), + "Expected exact retained publication after transport reads") + .get("binding", byte[].class)) + .isEqualTo(original.canonicalBytes()); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static AccountPublicationAuthorizationReadClient client( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var client = + new AccountPublicationAuthorizationReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private record TestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + } + + /** Ephemeral keytool PKI, following Account's existing loopback test; no runtime credentials. */ + private static final class TestPki { + private static final String PASSWORD = "test-only-publication-mtls-password"; + final Path ca; + final TestIdentity server, gameDesign, wrongWorkload, otherNamespace; + + TestPki(Path root) throws Exception { + Path caStore = root.resolve("ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=Account publication test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + ca = root.resolve("ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + ca.toString(), + "-rfc"); + server = issue(root, caStore, "account-server", NAMESPACE, "account-service", true); + gameDesign = + issue(root, caStore, "game-design-client", NAMESPACE, "game-design-service", false); + wrongWorkload = + issue(root, caStore, "world-client", NAMESPACE, "world-management-service", false); + otherNamespace = + issue( + root, + caStore, + "other-game-design-client", + "other-test", + "game-design-service", + false); + } + + private static TestIdentity issue( + Path root, Path caStore, String alias, String namespace, String workload, boolean server) + throws Exception { + Path store = root.resolve(alias + ".p12"), + request = root.resolve(alias + ".csr"), + certificate = root.resolve(alias + ".crt"); + String san = + "URI:spiffe://firemud/ns/" + + namespace + + "/sa/" + + workload + + ",DNS:localhost,IP:127.0.0.1"; + String eku = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san); + var keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, PASSWORD.toCharArray()); + } + byte[] privateKey = + java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull( + keyStore.getKey(alias, PASSWORD.toCharArray()), + "Expected ephemeral test private key") + .getEncoded(), + "Expected encoded ephemeral test private key"); + Path key = root.resolve(alias + ".key"); + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(privateKey); + Files.writeString( + key, + "-----BEGIN PRIVATE KEY-----\n" + body + "\n-----END PRIVATE KEY-----\n", + StandardCharsets.US_ASCII); + java.util.Arrays.fill(privateKey, (byte) 0); + return new TestIdentity(certificate, key); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("Ephemeral test certificate generation timed out"); + } + try (var output = process.getInputStream()) { + String details = new String(output.readAllBytes(), StandardCharsets.UTF_8); + if (process.exitValue() != 0) + throw new IllegalStateException("Test keytool failed: " + details); + } + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index 89632928a1..adb64a9c8a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -364,13 +364,13 @@ private static void asGameDesign(Runnable action) { .run(action); } - private record Proof( + record Proof( AuthoredDraftPublishSelectionBinding selection, WorldPublishedStartLocationEvidence world, DraftAuthorizationFenceBinding original) {} /** Closed World codec bytes copied in spirit from the existing isolated selector fixtures. */ - private static Proof proof( + static Proof proof( AccountControlUiOwnerSourcesFixture f, net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService .CapturedEnvironmentBoundary diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java new file mode 100644 index 0000000000..4b35c8b981 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Game Design admission boundary for one exact selected-Draft publication. Both owner + * reads complete and are correlated before the local reservation transaction begins. + */ +public final class SelectedDraftPublicationAdmissionService { + private final AccountPublicationAuthorizationReadClient accountClient; + private final WorldPublishedStartLocationClient worldClient; + private final SelectedDraftPublicationOwner owner; + private final TransactionTemplate reservationTransaction; + private final String workloadNamespace; + + public SelectedDraftPublicationAdmissionService( + DSLContext dsl, + PlatformTransactionManager transactionManager, + AccountPublicationAuthorizationReadClient accountClient, + WorldPublishedStartLocationClient worldClient, + String workloadNamespace) { + this( + transactionManager, + accountClient, + worldClient, + new SelectedDraftPublicationOwner(Objects.requireNonNull(dsl, "dsl")), + workloadNamespace); + } + + SelectedDraftPublicationAdmissionService( + PlatformTransactionManager transactionManager, + AccountPublicationAuthorizationReadClient accountClient, + WorldPublishedStartLocationClient worldClient, + SelectedDraftPublicationOwner owner, + String workloadNamespace) { + this.accountClient = Objects.requireNonNull(accountClient, "accountClient"); + this.worldClient = Objects.requireNonNull(worldClient, "worldClient"); + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.reservationTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + this.reservationTransaction.setName("selected-draft-publication-reservation"); + this.reservationTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + this.reservationTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.reservationTransaction.setReadOnly(false); + } + + /** + * Authenticates exact HELD Account and World readbacks before reserving their unchanged inputs. + * The caller-supplied binding and World request are lookup identities only, never authority. + */ + public SelectedDraftPublicationOwner.Reservation admitAndReserve( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding, + WorldPublishedStartLocationEvidence.Request worldRequest) { + requireNoAmbientTransaction(); + Objects.requireNonNull(intent, "intent"); + Objects.requireNonNull(accountBinding, "accountBinding"); + Objects.requireNonNull(worldRequest, "worldRequest"); + requireRequestIdentity(intent, accountBinding, worldRequest); + + AccountPublicationAuthorizationReadEvidence.Request accountReadRequest = + AccountPublicationAuthorizationReadEvidence.Request.create( + workloadNamespace, accountBinding); + AccountPublicationAuthorizationReadEvidence accountEvidence = + accountClient.read(accountReadRequest); + requireExactAccountReadback(accountReadRequest, accountBinding, accountEvidence); + + WorldPublishedStartLocationEvidence worldEvidence = worldClient.read(worldRequest); + requireExactWorldReadback(worldRequest, worldEvidence); + new GameDesignPublicationOperationBinding(accountEvidence.request().binding(), worldEvidence); + + return Objects.requireNonNull( + reservationTransaction.execute( + status -> owner.reserve(intent, accountEvidence.request().binding(), worldEvidence)), + "Selected Draft publication reservation returned no result"); + } + + private void requireRequestIdentity( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding, + WorldPublishedStartLocationEvidence.Request worldRequest) { + var selection = accountBinding.input().selection(); + var intentFromBinding = selection.intent(); + var expectedIntent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + String expectedWorkflowId = + PublicationDigestRequestBinding.full( + intent.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity(); + String expectedRequestDigest = selection.digest().substring("sha256:".length()); + + if (!expectedIntent.equals(intentFromBinding) + || !workloadNamespace.equals(worldRequest.targetNamespace()) + || !intent.canonicalTenantId().equals(worldRequest.canonicalTenantId()) + || !intent.canonicalVersionId().equals(worldRequest.canonicalVersionId()) + || !intent.publishRequestId().equals(worldRequest.publicationRequestId()) + || !Long.toString(worldRequest.versionStateEpoch()) + .equals(intent.expectedVersionStateEpoch()) + || !expectedWorkflowId.equals(worldRequest.publishWorkflowId()) + || !intent.selectedCommitId().toString().equals(worldRequest.appliedCommitId()) + || !expectedRequestDigest.equals(worldRequest.requestDigest())) { + throw new IllegalArgumentException( + "Account publication binding and World selector request must match the exact selected Draft intent"); + } + } + + private static void requireExactAccountReadback( + AccountPublicationAuthorizationReadEvidence.Request expectedRequest, + AccountPublicationAuthorizationBinding expectedBinding, + AccountPublicationAuthorizationReadEvidence evidence) { + if (evidence == null + || !expectedRequest.equals(evidence.request()) + || !java.util.Arrays.equals( + expectedBinding.canonicalBytes(), evidence.request().binding().canonicalBytes())) { + throw new IllegalStateException( + "Account publication authorization readback differs from the exact request"); + } + } + + private static void requireExactWorldReadback( + WorldPublishedStartLocationEvidence.Request expectedRequest, + WorldPublishedStartLocationEvidence evidence) { + if (evidence == null || !expectedRequest.equals(evidence.request())) { + throw new IllegalStateException( + "World publication selector readback differs from the exact request"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Selected Draft publication owner reads require no ambient transaction"); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java new file mode 100644 index 0000000000..2045f61205 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java @@ -0,0 +1,218 @@ +package net.firedevops.firemud.gamedesign.publication; + +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unit proof for the admission ordering and exact preflight checks; clients are transport doubles. + */ +class SelectedDraftPublicationAdmissionServiceTest { + private static final String NAMESPACE = "test"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void rejectsAmbientSqlTransactionBeforeEitherOwnerRead() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = service(accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + service.admitAndReserve( + fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void rejectsAmbientSynchronizationBeforeEitherOwnerRead() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = service(accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy( + () -> + service.admitAndReserve( + fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void rejectsChangedIntentAndWorldRequestIdentityBeforeOwnerReads() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = service(accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + var original = fixture.intent(); + var changedIntent = + new AuthoredDraftPublishSelection.PublishIntent( + original.canonicalTenantId(), + original.canonicalVersionId(), + original.publishRequestId(), + original.expectedVersionStateEpoch(), + "changed notes", + original.selectedCommitRequestId(), + original.selectedCommitId(), + original.selectedCommitDigest()); + + assertThatThrownBy( + () -> + service.admitAndReserve( + changedIntent, fixture.operation().account(), fixture.worldRequest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected Draft intent"); + assertThatThrownBy( + () -> + service.admitAndReserve( + fixture.intent(), + fixture.operation().account(), + withPublicationRequestId(fixture.worldRequest(), "different-request"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected Draft intent"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void accountDenialOrUnavailableReadNeverReadsWorldOrReserves() throws Exception { + for (Status.Code code : + new Status.Code[] {Status.Code.PERMISSION_DENIED, Status.Code.UNAVAILABLE}) { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var service = service(accountClient, worldClient, owner); + var failure = Status.fromCode(code).asRuntimeException(); + when(accountClient.read(any())).thenThrow(failure); + + assertThatThrownBy( + () -> + service.admitAndReserve( + fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + .isSameAs(failure); + + verify(accountClient).read(any()); + verifyNoInteractions(worldClient, owner); + } + } + + @Test + void worldUnavailableAfterAccountReadNeverOpensReservation() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var service = service(accountClient, worldClient, owner); + + // The client is a transport double here; the mock evidence is never accepted as proof because + // the World read fails before the reservation boundary. + when(accountClient.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var failure = Status.UNAVAILABLE.asRuntimeException(); + when(worldClient.read(fixture.worldRequest())).thenThrow(failure); + + assertThatThrownBy( + () -> + service.admitAndReserve( + fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + .isSameAs(failure); + + verify(accountClient).read(any()); + verify(worldClient).read(fixture.worldRequest()); + verifyNoInteractions(owner); + } + + private static SelectedDraftPublicationAdmissionService service( + AccountPublicationAuthorizationReadClient accountClient, + WorldPublishedStartLocationClient worldClient, + SelectedDraftPublicationOwner owner) { + return new SelectedDraftPublicationAdmissionService( + mock(PlatformTransactionManager.class), accountClient, worldClient, owner, NAMESPACE); + } + + private static Fixture fixture() throws Exception { + var target = + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + var original = IsolatedPublicationOperationFixtures.fresh(target); + var selectionIntent = original.account().input().selection().intent(); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + selectionIntent.canonicalTenantId(), + selectionIntent.canonicalVersionId(), + selectionIntent.publishRequestId(), + selectionIntent.expectedVersionStateEpoch(), + selectionIntent.notes(), + selectionIntent.selectedCommitRequestId(), + selectionIntent.selectedCommitId(), + selectionIntent.selectedCommitDigest()); + return new Fixture(original, intent, original.world().request()); + } + + private static WorldPublishedStartLocationEvidence.Request withPublicationRequestId( + WorldPublishedStartLocationEvidence.Request request, String publicationRequestId) { + return new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + publicationRequestId, + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()); + } + + private record Fixture( + GameDesignPublicationOperation operation, + AuthoredDraftPublishSelection.PublishIntent intent, + WorldPublishedStartLocationEvidence.Request worldRequest) {} +} From 60c507243987705094a3028e0b46f3bccd5d9504 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:53:20 +1300 Subject: [PATCH 028/129] Fix exact publication ordering and signer recovery identity proof --- .../account-service/api-contracts.md | 4 +- .../game-design-service/version-control.md | 2 +- .../world-management-service/api-contracts.md | 6 +- .../runtime-and-data.md | 2 +- ...ame-authoring-publishing-and-activation.md | 6 +- .../prove-protected-pod-boundary.sh | 9 +- .../protected-pod-live-proof-contract.sh | 12 +- .../publication_authorization_service.proto | 4 +- .../AccountJwtSignerBootstrapCoordinator.java | 15 +- ...ntPublicationAuthorizationReadService.java | 6 +- ...untPublicationAuthorizationRepository.java | 30 +-- ...ccountPublicationAuthorizationService.java | 10 +- ...__account_publication_pre_freeze_order.sql | 5 + ...closureHandoffPostgresIntegrationTest.java | 2 +- ...issionLeasePersistenceIntegrationTest.java | 39 ++++ .../AccountPostgresIntegrationFixture.java | 138 ++++++++++++ ...AccountPostgresIntegrationFixtureTest.java | 85 +++++++ ...dinessProbePersistenceIntegrationTest.java | 15 +- ...horizationMtlsPostgresIntegrationTest.java | 30 ++- ...nAuthorizationPostgresIntegrationTest.java | 74 ++---- ...ountJwtSignerBootstrapCoordinatorTest.java | 27 ++- ...blicationAuthorizationReadServiceTest.java | 27 ++- ...ntPublicationAuthorizationServiceTest.java | 6 +- .../WorldDraftGraphApplicationRepository.java | 46 ++++ ...dDraftPublicationCheckpointRepository.java | 69 ++++++ ...uthorizedDraftPostgresIntegrationTest.java | 212 +++++++++++++++--- 26 files changed, 738 insertions(+), 143 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V106__account_publication_pre_freeze_order.sql create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 5451787a9e..3e5aaad90b 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -78,7 +78,9 @@ For `security_locked` accounts, Account's successful recovery authorization issu ## gRPC APIs -The standalone, unregistered `AccountPublicationAuthorizationReadService.ReadHeldPublicationAuthorization` contract is defined in [its proto](../../../../protos/account/v1/publication_authorization_service.proto). Only the verified same-namespace Game Design workload may read an exact retained, distinct publication authorization; the complete canonical binding and digest are lookup evidence, not caller authority. `HELD` confirms the original Account order and source participation, not Game Design publication, World application, owner settlement, or admission. Original Draft permission cannot substitute. Runtime registration and composed proof remain gated in [Game Authoring, Publishing and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). +The standalone, unregistered `AccountPublicationAuthorizationReadService.ReadHeldPublicationAuthorization` contract is defined in [its proto](../../../../protos/account/v1/publication_authorization_service.proto). Only the verified same-namespace Game Design and World Management workloads may read an exact retained, distinct publication authorization; the complete canonical binding and digest are lookup evidence, not caller authority. This exact-method permission grants World neither order creation nor settlement authority. `HELD` confirms the original Account order and source participation, not Game Design publication, World application, owner settlement, or admission. Original Draft permission cannot substitute. Runtime registration and composed proof remain gated in [Game Authoring, Publishing and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). + +Account acquires this distinct publication order from the authenticated acting account and immutable Game Design Draft selection before World freeze. Its original actor, canonical tenant, selected-Draft digest, exact source versions and Account fence remain immutable across retry and recovery. The later World capture is correlated separately and must not rewrite the original order or its digest. Applicable source participation protects the authorized operation through actual World commit; a remote `HELD` sample alone is not commit-time protection. Participation may be released only after authenticated exact publication commit/abort readback, never from timeout, absence, a Draft terminal receipt or ambiguous publication evidence. Retained orders and their evidence remain immutable under forward-only migration. The current unregistered producer/read components do not yet establish this complete terminal settlement boundary. `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index c5dbbb4a3c..1d393b9ea0 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -62,7 +62,7 @@ Game Design owns the durable, creator-visible coordination record for every shar #### Publication freeze and owner handoff (Target State) -The synchronized Draft fence is also the lifecycle handoff into publication. Before collecting the World Management participant digest, reading the final release state, or committing `published_release_bundle` and `PUBLISHED` metadata, Game Design must obtain and retain the exact WMS owner-freeze acknowledgement, then complete or abort that same owner operation after reconciling its publication outcome. The canonical WMS operations, fields, phase transitions, exact replay/conflict behavior, and current implementation/proof boundary are defined in [World Management API Contracts](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state). This is one owner-local freeze protocol, not a distributed transaction: the freeze serializes WMS Draft writes, while Game Design remains the lifecycle and final-attestation authority. Focused proof must interleave a WMS mutation with freeze acquisition, publication, retry, abort, and lost-response reconciliation and prove that no post-freeze Draft row or digest can become part of a Published release. +The synchronized Draft fence is also the lifecycle handoff into publication. Game Design first obtains the distinct [Account publication authorization](../account-service/api-contracts.md#grpc-apis) for its authenticated immutable Draft selection, then presents that exact order for World freeze; later World capture is separate correlation, not a rewrite of Account authorization. Before collecting the World Management participant digest, reading the final release state, or committing `published_release_bundle` and `PUBLISHED` metadata, Game Design must obtain and retain the exact WMS owner-freeze acknowledgement, then complete or abort that same owner operation after reconciling its publication outcome. The canonical WMS operations, fields, phase transitions, exact replay/conflict behavior, and current implementation/proof boundary are defined in [World Management API Contracts](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state). This is one owner-local freeze protocol, not a distributed transaction: the freeze serializes WMS Draft writes, while Game Design remains the lifecycle and final-attestation authority. Focused proof must interleave a WMS mutation with freeze acquisition, publication, retry, abort, and lost-response reconciliation and prove that no post-freeze Draft row or digest can become part of a Published release. **Current implementation gap:** World Management currently lacks the durable owner-local publication freeze and exact Game Design version-state epoch/fence enforcement required by this target contract. Its live handoff checks the authoritative remote Game Design `DRAFT` state before its own transaction, but that check does not prove that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 79084c5b1e..986010ae15 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -84,7 +84,7 @@ World Management exposes design-time APIs used by Game Design to write Draft tem ### Publication freeze and terminal handoff (target state) -The publication-freeze operations are target contract surfaces. They are deliberately specified here as the World Management owner contract; the current proto, DTOs, client adapter, persistence schema, handler, and focused proof do not exist. No current caller may infer a freeze, publication, or terminal owner result from a digest, a remote `GetVersionState` read, or a Temporal run identity. +The publication-freeze operations below remain unregistered target contract surfaces. Current construction includes internal owner-lock/freeze persistence, immutable terminal storage and a selected-fresh-graph checkpoint callback; these do not supply an authenticated publication-freeze handler or complete owner handoff. The callback derives the selected commit from an actual Account-bound World `APPLIED` result and rechecks the complete retained graph against current topology and epochs under the shared owner lock. It does not authenticate Game Design's selection or establish the generic highest-applied-commit digest contract. No current caller may infer a public freeze, publication, or terminal owner result from internal storage, a digest, a remote `GetVersionState` read, or a Temporal run identity. Current capability and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). `BeginVersionPublicationFreeze` accepts exactly: @@ -92,7 +92,9 @@ The publication-freeze operations are target contract surfaces. They are deliber - stable `publicationRequestId`, supplied by the Game Design publish workflow and reused for every retry or recovery of that publication attempt; - `expectedVersionStateEpoch`, read from the authoritative Game Design version state; - the canonical `requestDigest` for the complete publication request; and -- authenticated Game Design service-caller identity and authorization evidence for the target tenant. +- authenticated Game Design service-caller identity and the exact distinct Account publication order for the target tenant and immutable selected Draft, verified through the narrowly authorized Account owner read. + +Account must acquire that publication order before World freeze; the later World capture is correlated separately without rewriting it. The [Account publication authorization contract](../account-service/api-contracts.md#grpc-apis) owns its immutable identity, protected source participation and terminal settlement. World verifies the exact selection/order relationship, not original Draft permission or workload identity alone. A remote held-order sample does not authorize releasing source protection before the actual World commit. WMS authenticates the caller, resolves the target `(tenantId, versionId)`, verifies that Game Design still reports the expected Draft state/epoch, and in one owner-local transaction locks or creates the durable owner-freeze row for that pair, persists `publicationRequestId`, `requestDigest`, the observed Game Design `versionStateEpoch`, one equality-only opaque `publicationFence`, and the WMS digest checkpoint `{appliedCommitId, contentDigest, digestSchemaVersion}`, then changes the phase to `FROZEN`. The successful acknowledgement is emitted only after that transaction commits. The phase vocabulary is `OPEN`, `FROZEN`, `PUBLISHED`, `ABORTED`, and `RECONCILIATION_REQUIRED`; `FROZEN` is entered only after the row, opaque fence, and checkpoint commit, while terminal attempt evidence remains available for exact replay before a later attempt may reopen an `ABORTED` row. Every Draft mutation takes the same row lock, so a writer that reaches the lock after the freeze cannot commit an unbound `OPEN` mutation. A missing/changed epoch, missing Draft authority, unauthorized caller, conflicting nonterminal request, or changed request digest fails closed. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 16a5c81f04..7dba6e63f6 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -8,7 +8,7 @@ - Legacy topology scope/version introduction is also not mapped: `V2__add_tenant_and_expiration.sql` assigns `tenant_id = 0` to existing zone, room, and instance rows, while `V18__version_scoped_world_templates.sql` assigns `version_id = 1` across existing template tables without hierarchy/version-graph backfill evidence. Positive tenant/version reads can orphan or misattribute those rows. A retained-data deployment remains blocked until the owner records a verified no-data boundary or explicit retained-row disposition/mapping and exact readback; this remains migration/proof drift rather than a new identity authority. - The live versioned topology and spawn schemas carry tenant/version columns, but parent references remain scalar-ID foreign keys, so SQL does not enforce child/parent tenant/version equality. Normal typed mutation guards resolve parents with tenant/version predicates, but that is not database integrity and does not protect retained or direct-written rows. Target convergence requires composite parent keys/foreign keys or an equivalent owner-local guard, plus database integration and readback proof. This is separate from the sentinel-default and hierarchy/version-graph backfill drift above. - The live `ApplyWorldDesignMutation` path performs a remote Game Design Draft-state read before its local transaction, but carries no Game Design `versionStateEpoch` or owner publication fence and has no durable WMS version-freeze row. A concurrent Game Design publish can therefore pass its digest read and transition the version while the pre-checked WMS mutation is still able to commit. This is a current lifecycle-handoff gap, not proof of Published-template immutability; the target freeze/acknowledgement protocol is canonical in [Game Design Version Control](../game-design-service/version-control.md#publication-freeze-and-owner-handoff). -- The target WMS publication owner contract, including `BeginVersionPublicationFreeze` and the outcome-typed `CompleteVersionPublication` terminal handoff, is specified in [World Management API Contracts](./api-contracts.md#publication-freeze-and-terminal-handoff-target-state). The current proto, DTOs, client adapter, persistence schema, handlers, and focused race/retry proof do not implement those surfaces: `ApplyWorldDesignMutation` still has no publication request, Game Design epoch, or WMS `publicationFence` fields. This remains a publication-readiness blocker; no digest, preflight state read, or Temporal completion may be promoted to freeze or terminal owner evidence. +- The target WMS publication owner contract, including `BeginVersionPublicationFreeze` and the outcome-typed `CompleteVersionPublication` terminal handoff, is specified in [World Management API Contracts](./api-contracts.md#publication-freeze-and-terminal-handoff-target-state). Internal construction retains owner freeze/terminal rows and derives a selected fresh-graph checkpoint from the exact Account-bound `APPLIED` result plus complete current topology/epoch readback. It remains unregistered and does not authenticate the Game Design selection or publication permission. The legacy `ApplyWorldDesignMutation` route still has no publication request, Game Design epoch, or WMS `publicationFence` fields. Complete authenticated producers, transport, composed race/retry proof and runtime wiring remain publication-readiness blockers; internal storage, a digest, a preflight state read or Temporal completion cannot substitute. - Procedural-generation persistence has a current identity gap: `V21__scoped_generation_rules.sql` creates a unique index over nullable `scope_type`/`scope_id`. Under PostgreSQL, multiple NULLs are distinct, so unscoped rows can duplicate the same `(tenant_id, version_id, name)` and destabilize deterministic generation-rule identity/digests. The current scope-aware repository lookup also compares nullable scope columns with SQL `=`, so it cannot retrieve an unscoped row. The target schema and mutation path must either prohibit unscoped rows or provide an explicit null-safe schema/query uniqueness contract, with focused proof; procedural-generation readiness remains blocked until that contract is enforced. - The current termination command returns a `TERMINATED` snapshot before comparing the supplied `terminationRequestId`. A different request identity therefore appears successful instead of conflicting with the terminal operation. The target requires exact request-identity replay and fail-closed mismatch handling, with focused terminal retry/conflict proof; this remains an implementation/proof blocker. - The current termination orchestration keeps the Entity Management cleanup RPC outside an open World transaction, preserves `TERMINATING` while remote cleanup or local finalization is incomplete, and commits local runtime-row cleanup with the `TERMINATED` lifecycle state in one local transaction. [WorldLifecycleCommandServiceImplTest](../../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) covers the owner-local control flow and RPC/transaction separation at unit level; it does not provide live PostgreSQL rollback, crash, or concurrency proof. This does not close the terminal request-identity mismatch above or the Temporal lost-response gaps below. 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 0d2b2f8a21..f0ebdc2e97 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 @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The standalone Account selected-publication producer now defines a distinct immutable authorization from the current initial creator, selected Draft descriptor and original issuance/source/checkpoint evidence. Its unregistered owner reader permits only the verified same-namespace Game Design workload, checks exact retained participation and committed issuance in one independent snapshot, and returns no publication terminal result. Pending publication participates in source-writer and prepare-before-disclose guards. These are implementation and proof definitions: the World descriptor in the Account-local fixture is stipulated, physical PostgreSQL/Redis execution and actual authenticated transport composition remain unproved, and no runtime path is enabled. Physical CI for `72d6c8a11d933c7d1fedba6876bb1577a3cad051` executed 221 Account and 201 World integration cases without skips; the Account positive-owner and World composition cases failed on the same signer guard's nonexistent promotion-row receipt field, and a readiness read-only fixture incorrectly expected zero previously stored receipts. Additive V104 binds the immutable readiness plan's generation receipt to the actual generation result, while the corrected read-only assertion preserves the existing receipt count. Corrected physical execution remains required. The earlier fail-closed admission WAL-coverage denial did not reproduce in this run's 40 passing lease-persistence cases; that does not establish its underlying cause or justify relaxing durability. +The World selected-fresh-graph checkpoint callback derives its commit identity from the exact retained Account-bound `APPLIED` application, rather than a caller-supplied checkpoint. Under the shared owner lock it rechecks the complete current graph and epoch set and computes the schema-3 content digest. The composition definition uses this callback while still stipulating Game Design's publication selection. It does not implement an authenticated freeze producer, change the generic digest's synthetic highest-commit limitation, or establish physical execution or publication authority. The approved [Account order-before-freeze contract](../../architecture/microservices/account-service/api-contracts.md#grpc-apis) now settles the ordering gap; complete authenticated World verification and terminal settlement still require implementation and proof. + +The standalone Account selected-publication producer defines a distinct immutable authorization from the authenticated current initial creator, immutable selected Draft and original issuance/source/checkpoint evidence before World capture. Its unregistered owner reader permits only verified same-namespace Game Design or World Management workloads and checks exact retained participation and committed issuance in one independent snapshot. V106 permits new pre-freeze orders without World evidence while retaining immutable V103 evidence unchanged and checking it when present; retained-row upgrade execution remains unproved. Later World correlation cannot rewrite the Account order. Pending publication participates in source-writer and prepare-before-disclose guards, but authenticated exact terminal readback and settlement remain open. Producer, transport and database test definitions are not runtime activation. + +Substantive construction CI at `20c1ae0f4d1e3e8789438bbf52221f8ea3ab3b14` executed 225 Account, 201 World and 74 Game Design integration cases with no skips or errors. Six Account failures and the World owner-composition failure share the signer coordinator's incorrect comparison of a promotion UUID with its originating generation UUID; the correction validates their exact persisted relationship through locked recovery readback. Six terms-handoff failures require the fixture's real V103 publication schema instead of its obsolete V101 ceiling. Four Account admission cases still failed closed on unavailable WAL coverage; no durability or deadline guard is relaxed. These fixes require corrected-head physical execution. Local World validation executed 518 unit cases; all 201 PostgreSQL cases skipped without Docker. Earlier V104 repaired the separate nonexistent promotion-row receipt field; it did not fix this subsequent coordinator identity defect. The current Gameplay-prerequisite construction remains non-activating. Full-version finalization reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. Production backend control-ui issuance/current-actor integration, complete Account source-writer fencing and the callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. In particular, the distinct selected-publication operation still needs authenticated Account authorization; original Draft permission cannot substitute. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Construction CI at `f14c7950827dd435ac0fe5c4cc230a1de32fa96d` executed all 74 Game Design and 200 World integration cases without skips or failures, including the corrected canonical-release and selected-publication transaction regressions. Its 220 Account integration executions passed the future-terms, environment-binding, disclosure-handoff and three real Redis registry cases; one readiness-promotion fixture assertion still compared its initial plan with subsequently progressed entries. A corrected assertion and the composed Account-to-World handoff need separate validation. These bounded results do not upgrade the broader capability ratings below. diff --git a/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh b/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh index 37451fe05d..f8d32c1ab6 100644 --- a/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh +++ b/dev-tools/hosted/trust-bootstrap/prove-protected-pod-boundary.sh @@ -191,8 +191,13 @@ for app in ("account-service", "game-session-service"): for label, change in (("privileged", {"privileged": True, "allowPrivilegeEscalation": True}), ("escalation", {"allowPrivilegeEscalation": True}), ("NET_ADMIN", {"capabilities": {"drop": ["ALL"], "add": ["NET_ADMIN"]}}), - ("missing-drop", {"capabilities": {"drop": []}}), ("procMount", {"procMount": "Unmasked"})): + ("missing-drop", {"capabilities": {"drop": []}})): deny(label, lambda p, change=change: p["spec"]["containers"][0]["securityContext"].update(change), boundary, container_message) + def unmasked_proc(p): + # Kubernetes v1.35 requires Unmasked procMount to use a Pod user namespace. + p["spec"]["hostUsers"] = False + p["spec"]["containers"][0]["securityContext"]["procMount"] = "Unmasked" + deny("procMount", unmasked_proc, boundary, container_message) deny("hostPort", lambda p: p["spec"]["containers"][0].update({"ports": [{"containerPort": 8080, "hostPort": 8080}]}), boundary, container_message) deny("sidecar", lambda p: p["spec"]["containers"].append({"name": "proxy", "image": "registry.k8s.io/pause:3.10", "securityContext": security}), identity, injection_message) deny("init", lambda p: p["spec"].update({"initContainers": [{"name": "proxy", "image": "registry.k8s.io/pause:3.10", "securityContext": security}]}), identity, injection_message) @@ -203,7 +208,7 @@ for app in ("account-service", "game-session-service"): deny("UID-mode", lambda p: p["spec"]["volumes"][0]["downwardAPI"].update({"defaultMode": 420}), identity, volume_message) for label, change in (("writable", {"readOnly": False}), ("subPath", {"subPath": "uid"}), ("subPathExpr", {"subPathExpr": "uid"}), ("propagation", {"mountPropagation": "HostToContainer"}), - ("noncanonical-path", {"mountPath": mount_path + "/../pod-identity"})): + ("noncanonical-path", {"mountPath": mount_path + "-alternate"})): deny(label, lambda p, change=change: p["spec"]["containers"][0]["volumeMounts"][0].update(change), identity, mount_message) for shadow_path in ("/var/run/secrets/firemud", mount_path + "/uid"): def shadow(p, shadow_path=shadow_path): diff --git a/dev-tools/tests/protected-pod-live-proof-contract.sh b/dev-tools/tests/protected-pod-live-proof-contract.sh index e1bb068f6f..6ef94d5e8e 100644 --- a/dev-tools/tests/protected-pod-live-proof-contract.sh +++ b/dev-tools/tests/protected-pod-live-proof-contract.sh @@ -121,11 +121,19 @@ if args[0] == 'replace': spec = pod['spec'] container = spec['containers'][0] security = container['securityContext'] -# Kubernetes rejects privileged=true with allowPrivilegeEscalation=false at -# schema validation, before the protected-Pod admission policy can deny it. +# Kubernetes rejects invalid security-context combinations and path traversal +# at schema validation, before the protected-Pod admission policy can deny them. if security.get('privileged') and security.get('allowPrivilegeEscalation') is False: print('Error from server (BadRequest): privileged containers require allowPrivilegeEscalation=true', file=sys.stderr) sys.exit(1) +if security.get('procMount') == 'Unmasked' and spec.get('hostUsers', True): + print('Error from server (BadRequest): `hostUsers` must be false to use `Unmasked`', file=sys.stderr) + sys.exit(1) +for candidate_container in spec.get('containers', []) + spec.get('initContainers', []) + spec.get('ephemeralContainers', []): + for mount in candidate_container.get('volumeMounts', []): + if any(segment == '..' for segment in mount.get('mountPath', '').split('/')): + print('Error from server (BadRequest): mountPath must not contain `..`', file=sys.stderr) + sys.exit(1) policy = None message = None if any(spec.get(k) for k in ('hostNetwork', 'hostPID', 'hostIPC')) or any('hostPath' in v for v in spec['volumes']) or spec['securityContext'].get('sysctls'): diff --git a/protos/account/v1/publication_authorization_service.proto b/protos/account/v1/publication_authorization_service.proto index 39594d7db0..5d4aea16dd 100644 --- a/protos/account/v1/publication_authorization_service.proto +++ b/protos/account/v1/publication_authorization_service.proto @@ -6,8 +6,8 @@ option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; // Standalone read of a distinct immutable selected-publication authorization. Account must -// authenticate only the exact same-namespace Game Design workload peer for this method. It does -// not read or reuse the original Draft COMMIT_ORDER. +// authenticate only the exact same-namespace Game Design or World Management workload peer for +// this method. It does not read or reuse the original Draft COMMIT_ORDER. service AccountPublicationAuthorizationReadService { rpc ReadHeldPublicationAuthorization(ReadHeldPublicationAuthorizationRequest) returns (ReadHeldPublicationAuthorizationResponse); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java index 1278db60f7..4e5ab7a257 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java @@ -213,6 +213,17 @@ public Optional prepareCurrentPromotionOnce() { trustFence(sources.materializerBinding()), preparation, verifiedProof); + PreparedGenerationEvidence readback = + desiredStateRepository.readPreparedGenerationForRecovery( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding())); + if (!readback.promotion().operationId().equals(persisted.operationId()) + || !readback.promotion().requestDigest().equals(persisted.requestDigest()) + || !readback.promotion().generationOperationId().equals(request.operationId()) + || !readback.generationResult().equals(verifiedProof.generationResult()) + || !"PREPARED".equals(persisted.status())) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } requireUnchangedProtectedBindings(sources); return persisted; }); @@ -220,10 +231,6 @@ public Optional prepareCurrentPromotionOnce() { return Optional.empty(); } requireUnchangedProtectedBindings(sources); - if (!prepared.operationId().equals(request.operationId()) - || !"PREPARED".equals(prepared.status())) { - throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); - } return Optional.of(prepared); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java index 37fca75217..fd596bb3d8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java @@ -71,9 +71,11 @@ static void requirePeer(String namespace) { .withDescription("Verified workload identity required") .asRuntimeException(); } - if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + String peerUri = peer.uri(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peerUri) + && !("spiffe://firemud/ns/" + namespace + "/sa/world-management-service").equals(peerUri)) { throw Status.PERMISSION_DENIED - .withDescription("Exact same-namespace Game Design workload required") + .withDescription("Exact same-namespace Game Design or World Management workload required") .asRuntimeException(); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java index 5bd6d47c47..ebfcd210b3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java @@ -24,7 +24,6 @@ public AccountPublicationAuthorizationRepository(DSLContext dsl) { AccountPublicationAuthorizationBinding authorize( AccountPublicationAuthorizationBinding.PreallocationInput input, - WorldPublishedStartLocationEvidence world, AccountControlUiActorService.Current current, Runnable admission) { requireTransaction(); @@ -37,20 +36,18 @@ AccountPublicationAuthorizationBinding authorize( if (prior != null) { var original = AccountPublicationAuthorizationBinding.fromStored(prior.get("binding", byte[].class)); - requireExact(prior, original, input, world, current); + requireExact(prior, original, input, current); return original; } admission.run(); var binding = new AccountPublicationAuthorizationBinding( UUID.randomUUID(), UUID.randomUUID(), input, current.source().sources()); - // The shared closed operation checks the entire selection and World relation, not authority. - new GameDesignPublicationOperationBinding(binding, world); dsl.execute( "INSERT INTO account_selected_publication_authorizations" + " (operation_id, fence_id, actor_account_uuid, tenant_uuid, publish_request_id," - + " input_digest, binding, world_evidence, issuance_operation_id, issuance_fence," - + " source_payload, issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + " input_digest, binding, issuance_operation_id, issuance_fence," + + " source_payload, issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", binding.operationId(), binding.fenceId(), input.actorAccountId(), @@ -58,7 +55,6 @@ AccountPublicationAuthorizationBinding authorize( binding.publishRequestId(), input.digest(), binding.canonicalBytes(), - world.canonicalBytes(), current.stored().operationId, current.source().issuanceFence(), current.stored().sources, @@ -77,7 +73,7 @@ AccountPublicationAuthorizationBinding authorize( dsl.fetchOne( "SELECT * FROM account_selected_publication_authorizations WHERE operation_id = ? FOR UPDATE", binding.operationId()); - requireExact(retained, binding, input, world, current); + requireExact(retained, binding, input, current); return binding; } @@ -106,9 +102,7 @@ public void readHeld(AccountPublicationAuthorizationBinding requested) { } var retained = AccountPublicationAuthorizationBinding.fromStored(row.get("binding", byte[].class)); - var world = - WorldPublishedStartLocationEvidence.fromStored(row.get("world_evidence", byte[].class)); - new GameDesignPublicationOperationBinding(retained, world); + validateRetainedWorldIfPresent(row, retained); // Issuance producers acquire this row before source capture. Do not wait backwards while // holding sources; a concurrent issuer/source writer must cause a retry, never a lock cycle. Record issuance = @@ -175,9 +169,8 @@ private void requireExact( Record row, AccountPublicationAuthorizationBinding binding, AccountPublicationAuthorizationBinding.PreallocationInput input, - WorldPublishedStartLocationEvidence world, AccountControlUiActorService.Current current) { - new GameDesignPublicationOperationBinding(binding, world); + validateRetainedWorldIfPresent(row, binding); if (row == null || !binding.operationId().equals(row.get("operation_id", UUID.class)) || !binding.fenceId().equals(row.get("fence_id", UUID.class)) @@ -187,7 +180,6 @@ private void requireExact( || !input.digest().equals(row.get("input_digest", String.class)) || !Arrays.equals(input.canonicalBytes(), binding.input().canonicalBytes()) || !Arrays.equals(binding.canonicalBytes(), row.get("binding", byte[].class)) - || !Arrays.equals(world.canonicalBytes(), row.get("world_evidence", byte[].class)) || !current.stored().operationId.equals(row.get("issuance_operation_id", UUID.class)) || current.source().issuanceFence() != row.get("issuance_fence", Long.class) || !Arrays.equals(current.stored().sources, row.get("source_payload", byte[].class)) @@ -223,6 +215,16 @@ private void requireExact( } } + /** Historical V103 World evidence remains immutable and is checked when a row contains it. */ + private static void validateRetainedWorldIfPresent( + Record row, AccountPublicationAuthorizationBinding binding) { + byte[] worldEvidence = row == null ? null : row.get("world_evidence", byte[].class); + if (worldEvidence != null) { + new GameDesignPublicationOperationBinding( + binding, WorldPublishedStartLocationEvidence.fromStored(worldEvidence)); + } + } + private static void requireTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java index f6b36779eb..6e51691691 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java @@ -5,13 +5,12 @@ import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; -import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; /** * Unregistered Account producer for a distinct selected-publication order. Authenticates the - * current initial creator through the real issuance owner. Supplied World evidence is structurally - * checked and retained, not authenticated by this component; protected owner transport remains a - * separate integration boundary. No remote calls, terminalization, or activation occur here. + * current initial creator through the real issuance owner and retains the immutable Draft selection + * before World freezes it. World capture and correlation are a separate later boundary. No remote + * calls, terminalization, or activation occur here. */ public final class AccountPublicationAuthorizationService { private final AccountControlUiActorService actors; @@ -33,10 +32,8 @@ public AccountPublicationAuthorizationService( public AccountPublicationAuthorizationBinding authorize( String compactJwt, AuthoredDraftPublishSelectionBinding selection, - WorldPublishedStartLocationEvidence world, CapturedEnvironmentBoundary environment) { Objects.requireNonNull(selection); - Objects.requireNonNull(world); return actors.withCurrent( compactJwt, selection.intent().canonicalTenantId(), @@ -46,7 +43,6 @@ public AccountPublicationAuthorizationBinding authorize( return publications.authorize( new AccountPublicationAuthorizationBinding.PreallocationInput( current.stored().accountId, selection), - world, current, () -> fences.requirePublicationAdmission(current.source().sources())); }); diff --git a/services/account-service/src/main/resources/db/migration/V106__account_publication_pre_freeze_order.sql b/services/account-service/src/main/resources/db/migration/V106__account_publication_pre_freeze_order.sql new file mode 100644 index 0000000000..e92e4ea5dd --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V106__account_publication_pre_freeze_order.sql @@ -0,0 +1,5 @@ +-- The Account publication order is acquired from the authenticated immutable Draft selection +-- before World capture. Existing V103 World evidence remains retained and immutable; new orders +-- leave the optional later-correlation evidence absent. +ALTER TABLE account_selected_publication_authorizations + ALTER COLUMN world_evidence DROP NOT NULL; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java index 0e7ec62081..0aa7b108f2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java @@ -646,7 +646,7 @@ private static Database database() throws Exception { .defaultSchema(database.schema()) .placeholders(Map.of("serviceSchema", database.schema())) .locations("classpath:db/migration") - .target("101") + .target("latest") .load() .migrate(); return database; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index d938af3e49..ee7924cd61 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -45,6 +45,8 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.extension.TestExecutionExceptionHandler; import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DelegatingDataSource; @@ -60,6 +62,43 @@ class AccountGameplayAdmissionLeasePersistenceIntegrationTest { private static final AccountPostgresIntegrationFixture POSTGRES = new AccountPostgresIntegrationFixture(true); + + @RegisterExtension + static final TestExecutionExceptionHandler WAL_FAILURE_DIAGNOSTICS = + (context, failure) -> { + // Only unexpected test failures reach this hook; expected assertThrows cases do not. + try { + Throwable cause = failure; + var visited = + java.util.Collections.newSetFromMap( + new java.util.IdentityHashMap()); + while (cause != null && visited.add(cause)) { + if (cause instanceof PSQLException postgresFailure) { + var error = postgresFailure.getServerErrorMessage(); + if ("23514".equals(postgresFailure.getSQLState()) + && error != null + && ("account_admission_confirmation_wal_coverage".equals(error.getConstraint()) + || "account_admission_original_ack_receipt_wal_coverage" + .equals(error.getConstraint()))) { + System.err.println( + "WAL diagnostic for " + + context.getDisplayName() + + ":\n" + + POSTGRES.describeWalCoverageFailure(error.getDetail())); + break; + } + } + cause = cause.getCause(); + } + } catch (Throwable diagnosticFailure) { + // Do not replace, suppress or retry the original test failure, even if capture fails. + if (diagnosticFailure instanceof InterruptedException) Thread.currentThread().interrupt(); + System.err.println( + "WAL diagnostic unavailable: " + diagnosticFailure.getClass().getSimpleName()); + } + throw failure; + }; + private static final String TENANT = "22222222-2222-4222-8222-222222222222"; private static final String OTHER = "33333333-3333-4333-8333-333333333333"; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java index 7f6ceb2993..17f1efcc84 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java @@ -2,8 +2,10 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; +import java.math.BigInteger; import java.net.URI; import java.util.Properties; +import java.util.regex.Pattern; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.DockerClientFactory; @@ -18,6 +20,142 @@ public final class AccountPostgresIntegrationFixture { private final boolean requireDurablePrimary; private boolean started; + private static final BigInteger MAX_UINT64 = + BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); + private static final Pattern WAL_FAILURE_DETAIL = + Pattern.compile( + "(?:phase=(?:create|receipt-read) )?snapshot=[0-9:,]+ own_xid_if_assigned=([0-9]*)" + + " finalization_xid=([1-9][0-9]{0,19}) receipt_xid=([0-9]*)" + + " insert_fence=([0-9A-F]{1,8}/[0-9A-F]{1,8})" + + " initial_flush=([0-9A-F]{1,8}/[0-9A-F]{1,8})" + + " final_flush=([0-9A-F]{1,8}/[0-9A-F]{1,8})" + + "(?: observed_db_ms=([1-9][0-9]{0,18}))?" + + " unchanged_expiry_ms=([1-9][0-9]{0,18})"); + + /** Failure-only observation; never opens a database connection or changes database settings. */ + public String describeWalCoverageFailure(String detail) throws Exception { + if (detail == null || detail.length() > 1024) { + return "WAL diagnostic unavailable: missing or oversized server DETAIL"; + } + var fields = WAL_FAILURE_DETAIL.matcher(detail); + if (!fields.matches()) return "WAL diagnostic unavailable: unsupported server DETAIL shape"; + String[] snapshot = + detail + .substring(detail.indexOf("snapshot=") + 9, detail.indexOf(" own_xid_if_assigned=")) + .split(":", -1); + if (snapshot.length != 3 + || !validXid(snapshot[0]) + || !validXid(snapshot[1]) + || new BigInteger(snapshot[0]).compareTo(new BigInteger(snapshot[1])) > 0) { + return "WAL diagnostic unavailable: invalid snapshot"; + } + if (!snapshot[2].isEmpty()) { + for (String xid : snapshot[2].split(",", -1)) { + if (!validXid(xid) + || new BigInteger(xid).compareTo(new BigInteger(snapshot[0])) < 0 + || new BigInteger(xid).compareTo(new BigInteger(snapshot[1])) >= 0) { + return "WAL diagnostic unavailable: invalid snapshot XID"; + } + } + } + for (int group : new int[] {1, 2, 3}) { + String xid = fields.group(group); + if (!xid.isEmpty() && !validXid(xid)) { + return "WAL diagnostic unavailable: invalid XID"; + } + } + for (int group : new int[] {7, 8}) { + if (fields.group(group) != null) Long.parseLong(fields.group(group)); + } + BigInteger insert = parseLsn(fields.group(4)); + BigInteger initialFlush = parseLsn(fields.group(5)); + BigInteger finalFlush = parseLsn(fields.group(6)); + if (insert.signum() <= 0 + || initialFlush.compareTo(finalFlush) > 0 + || finalFlush.compareTo(insert) >= 0) { + return "WAL diagnostic unavailable: inconsistent WAL fences"; + } + if (container == null) { + return "WAL diagnostic unavailable: external loopback fixture has no owned container WAL access"; + } + if (!started) return "WAL diagnostic unavailable: owned container is not running"; + + // Search only the preceding 1 MiB. Missing/recycled records or a COMMIT outside this window + // remain explicitly inconclusive. This observes WAL files after failure, not flush durability. + String start = + formatLsn(finalFlush.subtract(BigInteger.valueOf(1_048_576)).max(BigInteger.ZERO)); + StringBuilder result = new StringBuilder("WAL failure DETAIL: ").append(detail); + result.append("\nUnflushed interval (up to 256 records):\n"); + result.append(dumpWal(fields.group(6), fields.group(4), null)); + for (int group : new int[] {2, 3}) { + String xid = fields.group(group); + if (xid.isEmpty()) continue; + // pg_waldump filters 32-bit WAL XIDs, whereas the server DETAIL retains full xid8 identity. + String walXid = + new BigInteger(xid).and(BigInteger.ONE.shiftLeft(32).subtract(BigInteger.ONE)).toString(); + result + .append("\nXID8 ") + .append(xid) + .append(" (WAL xid ") + .append(walXid) + .append(") records in bounded lookback ") + .append(start) + .append("..") + .append(fields.group(4)) + .append(":\n"); + result.append(dumpWal(start, fields.group(4), walXid)); + } + return result + .append( + "\nLimits: each dump <=6s, <=16KiB, <=256 matching records; output may be truncated. " + + "Missing COMMIT is inconclusive. WAL file presence is not a flush observation; " + + "compare records with the original logged flush fence. pg_waldump reports record start " + + "and length, not an independently measured COMMIT end/flush bound.") + .toString(); + } + + private String dumpWal(String start, String end, String xid) throws Exception { + // The shell program is constant; validated values travel only as positional arguments. + var arguments = + new java.util.ArrayList( + java.util.List.of( + "sh", + "-c", + "set -o pipefail; timeout -k 1 5 pg_waldump \"$@\" 2>&1 | head -c 16384", + "wal-diagnostic", + "-p", + "/var/lib/postgresql/data/pg_wal", + "-s", + start, + "-e", + end, + "-n", + "256")); + if (xid != null) { + arguments.add("-x"); + arguments.add(xid); + } + var output = container.execInContainer(arguments.toArray(String[]::new)); + return "pipeline_exit=" + output.getExitCode() + "\n" + output.getStdout() + output.getStderr(); + } + + private static BigInteger parseLsn(String lsn) { + String[] halves = lsn.split("/"); + return new BigInteger(halves[0], 16).shiftLeft(32).add(new BigInteger(halves[1], 16)); + } + + private static boolean validXid(String xid) { + return xid.matches("[1-9][0-9]{0,19}") && new BigInteger(xid).compareTo(MAX_UINT64) <= 0; + } + + private static String formatLsn(BigInteger lsn) { + return lsn.shiftRight(32).toString(16).toUpperCase(java.util.Locale.ROOT) + + "/" + + lsn.and(BigInteger.ONE.shiftLeft(32).subtract(BigInteger.ONE)) + .toString(16) + .toUpperCase(java.util.Locale.ROOT); + } + public AccountPostgresIntegrationFixture() { this(false); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java index 4d39468d9a..196561b722 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java @@ -7,6 +7,91 @@ import org.junit.jupiter.api.Test; class AccountPostgresIntegrationFixtureTest { + private static final String V90_DETAIL = + "phase=create snapshot=4847:4847: own_xid_if_assigned= finalization_xid=4846 receipt_xid=" + + " insert_fence=0/8754AB0 initial_flush=0/8754A70 final_flush=0/8754A70" + + " observed_db_ms=1791484179743 unchanged_expiry_ms=1791484194098"; + private static final String V92_DETAIL = + "snapshot=5581:5581: own_xid_if_assigned= finalization_xid=5579 receipt_xid=5580" + + " insert_fence=0/9AEF178 initial_flush=0/9AEF138 final_flush=0/9AEF138" + + " unchanged_expiry_ms=1791484201634"; + + @Test + void loggedWalFailureDetailsParseBeforeUnstartedFixtureRefusesCapture() throws Exception { + var fixture = new AccountPostgresIntegrationFixture(true); + String configuredUrl = System.getenv(AccountPostgresIntegrationFixture.JDBC_URL_ENV); + String unavailable = + configuredUrl == null || configuredUrl.isBlank() + ? "WAL diagnostic unavailable: owned container is not running" + : "WAL diagnostic unavailable: external loopback fixture has no owned container WAL access"; + for (String detail : List.of(V90_DETAIL, V92_DETAIL)) { + assertThat(fixture.describeWalCoverageFailure(detail)).isEqualTo(unavailable); + } + } + + @Test + void malformedOrInjectedWalFailureDetailsAreRejectedBeforeCapture() throws Exception { + var fixture = new AccountPostgresIntegrationFixture(true); + for (String detail : + List.of( + V90_DETAIL + "; touch /tmp/untrusted", + V90_DETAIL.replace("0/8754AB0", "$(id)"), + V90_DETAIL.replace("0/8754AB0", "0/100000000"), + V90_DETAIL.replace("0/8754AB0", "0/-1"), + V90_DETAIL.replace("phase=create", "phase=unknown"), + V92_DETAIL.replace("receipt_xid=5580", "receipt_xid=-1"))) { + assertThat(fixture.describeWalCoverageFailure(detail)) + .isEqualTo("WAL diagnostic unavailable: unsupported server DETAIL shape"); + } + assertThat(fixture.describeWalCoverageFailure(null)) + .isEqualTo("WAL diagnostic unavailable: missing or oversized server DETAIL"); + assertThat(fixture.describeWalCoverageFailure("x".repeat(1025))) + .isEqualTo("WAL diagnostic unavailable: missing or oversized server DETAIL"); + } + + @Test + void invalidWalIdentitiesSnapshotsAndFenceOrderingAreRejectedBeforeCapture() throws Exception { + var fixture = new AccountPostgresIntegrationFixture(true); + for (String detail : + List.of( + V90_DETAIL.replace("finalization_xid=4846", "finalization_xid=18446744073709551616"), + V92_DETAIL.replace("receipt_xid=5580", "receipt_xid=0"), + V92_DETAIL.replace( + "own_xid_if_assigned=", "own_xid_if_assigned=18446744073709551616"))) { + assertThat(fixture.describeWalCoverageFailure(detail)) + .isEqualTo("WAL diagnostic unavailable: invalid XID"); + } + for (String snapshot : + List.of("5582:5581:", "0:5581:", "18446744073709551616:18446744073709551616:", "5581::")) { + assertThat(fixture.describeWalCoverageFailure(V92_DETAIL.replace("5581:5581:", snapshot))) + .isEqualTo("WAL diagnostic unavailable: invalid snapshot"); + } + for (String snapshot : List.of("5581:5582:5580", "5581:5582:5582", "5581:5582:5581,")) { + assertThat(fixture.describeWalCoverageFailure(V92_DETAIL.replace("5581:5581:", snapshot))) + .isEqualTo("WAL diagnostic unavailable: invalid snapshot XID"); + } + for (String detail : + List.of( + V90_DETAIL.replace("insert_fence=0/8754AB0", "insert_fence=0/0"), + V90_DETAIL.replace("final_flush=0/8754A70", "final_flush=0/8754A60"), + V90_DETAIL.replace("final_flush=0/8754A70", "final_flush=0/8754AB0"))) { + assertThat(fixture.describeWalCoverageFailure(detail)) + .isEqualTo("WAL diagnostic unavailable: inconsistent WAL fences"); + } + } + + @Test + void overflowingWalFailureClockCountersCannotReachCapture() { + var fixture = new AccountPostgresIntegrationFixture(true); + for (String detail : + List.of( + V90_DETAIL.replace("1791484179743", "9223372036854775808"), + V92_DETAIL.replace("1791484201634", "9223372036854775808"))) { + assertThatThrownBy(() -> fixture.describeWalCoverageFailure(detail)) + .isInstanceOf(NumberFormatException.class); + } + } + @Test void acceptsIpv4AndBracketedIpv6LoopbackUrls() { for (String jdbcUrl : diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java index 20ea46e8eb..a530d598d2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbePersistenceIntegrationTest.java @@ -1332,10 +1332,17 @@ void persistsProtectedV2PodClosureAndRequiresFreshExactInventoryForPromotion() t when(inventorySource.observe(initialObservationContext)).thenReturn(proofInventory); Optional prepared = coordinator.prepareCurrentPromotionOnce(); assertThat(prepared).isPresent(); - assertThat(prepared.orElseThrow().operationId()).isEqualTo(result.operationId()); + assertThat(prepared.orElseThrow().operationId()).isNotEqualTo(result.operationId()); assertThat(prepared.orElseThrow().status()).isEqualTo("PREPARED"); - assertThat(inTransaction(context, () -> desired.read(BINDING).preparedOperationId())) - .contains(result.operationId()); + var preparedEvidence = + inTransaction(context, () -> desired.readPreparedGenerationForRecovery(BINDING, trust)); + assertThat(preparedEvidence.desiredState().preparedOperationId()) + .contains(prepared.orElseThrow().operationId()); + assertThat(preparedEvidence.promotion().operationId()) + .isEqualTo(prepared.orElseThrow().operationId()); + assertThat(preparedEvidence.promotion().generationOperationId()) + .isEqualTo(result.operationId()); + assertThat(preparedEvidence.generationResult()).isEqualTo(result); assertThat(count(context, "account_jwt_signer_promotion_operations")).isEqualTo(1L); assertThat( inTransaction( @@ -1346,8 +1353,6 @@ void persistsProtectedV2PodClosureAndRequiresFreshExactInventoryForPromotion() t .isPresent(); assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(12L); - var preparedEvidence = - inTransaction(context, () -> desired.readPreparedGenerationForRecovery(BINDING, trust)); var promotion = preparedEvidence.promotion(); inTransaction(context, () -> desired.readAndMarkPreparedPromotionDispatched(BINDING, trust)); PrivatePromotionObservation privateObservation = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java index bf3f884bee..38e9f85b20 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -90,7 +90,7 @@ class AccountPublicationAuthorizationMtlsPostgresIntegrationTest { @TempDir Path temporary; @Test - void genuineProducerToMtlsReaderReplaysExactlyAndRejectsTrustedPeerAndBindingSubstitution() + void genuineProducerToGameDesignAndWorldMtlsReadersReplaysExactlyAndRejectsSubstitution() throws Exception { var pki = new TestPki(Files.createDirectories(temporary.resolve("pki"))); try (var fixture = @@ -110,8 +110,7 @@ void genuineProducerToMtlsReaderReplaysExactlyAndRejectsTrustedPeerAndBindingSub var producer = new AccountPublicationAuthorizationService(issued.actors(), sources.fences, repository); var original = - producer.authorize( - issued.compact(), descriptor.selection(), descriptor.world(), issued.environment()); + producer.authorize(issued.compact(), descriptor.selection(), issued.environment()); var request = AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, original); var endpoint = new AccountPublicationAuthorizationReadGrpcService( @@ -157,7 +156,16 @@ void genuineProducerToMtlsReaderReplaysExactlyAndRejectsTrustedPeerAndBindingSub // A negative read cannot change the exact held owner row or prevent its next read. assertThat(client.read(request).request()).isEqualTo(request); } - for (var wrongPeer : List.of(pki.wrongWorkload, pki.otherNamespace)) { + try (var client = client(server.getPort(), pki.worldManagement, pki.ca)) { + var first = client.read(request); + var retry = client.read(request); + assertThat(first.request()).isEqualTo(request); + assertThat(retry.request()).isEqualTo(first.request()); + assertThat(first.request().originalPublicationAuthorizationBinding()) + .isEqualTo(original.canonicalBytes()); + } + for (var wrongPeer : + List.of(pki.wrongWorkload, pki.otherNamespace, pki.otherWorldNamespace)) { try (var client = client(server.getPort(), wrongPeer, pki.ca)) { assertCode(Status.Code.PERMISSION_DENIED, () -> client.read(request)); } @@ -223,7 +231,12 @@ CommonGrpcClientProperties properties(Path ca) { private static final class TestPki { private static final String PASSWORD = "test-only-publication-mtls-password"; final Path ca; - final TestIdentity server, gameDesign, wrongWorkload, otherNamespace; + final TestIdentity server, + gameDesign, + worldManagement, + wrongWorkload, + otherNamespace, + otherWorldNamespace; TestPki(Path root) throws Exception { Path caStore = root.resolve("ca.p12"); @@ -268,8 +281,10 @@ private static final class TestPki { server = issue(root, caStore, "account-server", NAMESPACE, "account-service", true); gameDesign = issue(root, caStore, "game-design-client", NAMESPACE, "game-design-service", false); - wrongWorkload = + worldManagement = issue(root, caStore, "world-client", NAMESPACE, "world-management-service", false); + wrongWorkload = + issue(root, caStore, "game-session-client", NAMESPACE, "game-session-service", false); otherNamespace = issue( root, @@ -278,6 +293,9 @@ private static final class TestPki { "other-test", "game-design-service", false); + otherWorldNamespace = + issue( + root, caStore, "other-world-client", "other-test", "world-management-service", false); } private static TestIdentity issue( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index adb64a9c8a..77d5c6bc29 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -81,7 +81,7 @@ class AccountPublicationAuthorizationPostgresIntegrationTest { @TempDir Path temporary; @Test - void authenticatesDistinctOrderReplaysExactlyAndBlocksSourceWritersAndDisclosure() + void authenticatesPreFreezeDistinctOrderReplaysExactlyAndBlocksSourceWritersAndDisclosure() throws Exception { try (var fixture = fixture()) { var issued = fixture.issueCreator(); @@ -90,12 +90,8 @@ void authenticatesDistinctOrderReplaysExactlyAndBlocksSourceWritersAndDisclosure var service = new AccountPublicationAuthorizationService( issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); - var original = - service.authorize( - issued.compact(), proof.selection(), proof.world(), issued.environment()); - var replay = - service.authorize( - issued.compact(), proof.selection(), proof.world(), issued.environment()); + var original = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var replay = service.authorize(issued.compact(), proof.selection(), issued.environment()); assertThat(replay.canonicalBytes()).isEqualTo(original.canonicalBytes()); assertThat(original.operationId()).isNotEqualTo(proof.original().operationId()); assertThat(original.fenceId()).isNotEqualTo(proof.original().fenceId()); @@ -105,6 +101,18 @@ void authenticatesDistinctOrderReplaysExactlyAndBlocksSourceWritersAndDisclosure f.dsl.fetchCount( org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) .isEqualTo(1); + assertThat( + java.util.Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT world_evidence FROM account_selected_publication_authorizations" + + " WHERE operation_id = ?", + original.operationId()), + "Expected exact pre-freeze Account order") + .get("world_evidence", byte[].class)) + .isNull(); + // The immutable Account order is available before the separate World capture is correlated. + new net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding( + original, proof.world()); assertThat(original.sources()).hasSize(8); var readOwner = new AccountPublicationAuthorizationReadService( @@ -150,8 +158,7 @@ void authenticatesDistinctOrderReplaysExactlyAndBlocksSourceWritersAndDisclosure // An exact retained replay remains possible while a later source change waits. assertThat( service - .authorize( - issued.compact(), proof.selection(), proof.world(), issued.environment()) + .authorize(issued.compact(), proof.selection(), issued.environment()) .canonicalBytes()) .isEqualTo(original.canonicalBytes()); asGameDesign(() -> readOwner.requireHeld(readRequest)); @@ -176,43 +183,12 @@ void authenticatesDistinctOrderReplaysExactlyAndBlocksSourceWritersAndDisclosure () -> f.tx(() -> f.dsl.execute("DELETE FROM account_selected_publication_sources"))) .isInstanceOf(org.jooq.exception.DataAccessException.class); var changed = selection(proof.selection().selectedCommit(), "changed notes"); - assertThatThrownBy( - () -> - service.authorize(issued.compact(), changed, proof.world(), issued.environment())) + assertThatThrownBy(() -> service.authorize(issued.compact(), changed, issued.environment())) .isInstanceOf(IllegalArgumentException.class); - var request = proof.world().request(); - var changedWorld = - new WorldPublishedStartLocationEvidence( - new WorldPublishedStartLocationEvidence.Request( - request.targetNamespace(), - request.canonicalTenantId(), - request.canonicalVersionId(), - request.intakeRequestId(), - UUID.randomUUID(), - request.publicationRequestId(), - request.requestDigest(), - request.versionStateEpoch(), - request.publishWorkflowId(), - request.appliedCommitId(), - request.contentDigest(), - request.digestSchemaVersion(), - request.worldAffectedTuples()), - proof.world().selectorReceiptBytes(), - proof.world().originalAccountBindingBytes(), - proof.world().appliedResultBytes()); - assertThatThrownBy( - () -> - service.authorize( - issued.compact(), proof.selection(), changedWorld, issued.environment())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Changed immutable"); assertThatThrownBy( () -> service.authorize( - issued.compact() + "changed", - proof.selection(), - proof.world(), - issued.environment())) + issued.compact() + "changed", proof.selection(), issued.environment())) .isInstanceOf(RuntimeException.class); // Original source/issuance identity is immutable even if a privileged SQL caller tries it. assertThatThrownBy( @@ -251,18 +227,13 @@ void earlierWaitingSourceChangeWinsAndDeniedAuthenticationCreatesNoOperation() t new AccountPublicationAuthorizationService( issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); assertThatThrownBy( - () -> - service.authorize( - issued.compact(), proof.selection(), proof.world(), issued.environment())) + () -> service.authorize(issued.compact(), proof.selection(), issued.environment())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("source change is waiting"); assertThatThrownBy( () -> service.authorize( - "unsigned-caller-claim", - proof.selection(), - proof.world(), - issued.environment())) + "unsigned-caller-claim", proof.selection(), issued.environment())) .isInstanceOf(RuntimeException.class); assertThat( f.dsl.fetchCount( @@ -302,10 +273,7 @@ void actualSourceWriterBlocksCreatorCaptureThenWinsBeforePublication() throws Ex executor.submit( () -> service.authorize( - issued.compact(), - proof.selection(), - proof.world(), - issued.environment()))); + issued.compact(), proof.selection(), issued.environment()))); long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); Integer blockedPid = null; while (System.nanoTime() < deadline && blockedPid == null) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinatorTest.java index 0a2ee8dd64..8f1a333b5a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinatorTest.java @@ -545,7 +545,25 @@ void completeOwnerProofPreparesOnlyItsExactCurrentGenerationOnce() { Optional.of(operationId), Optional.empty(), Optional.of(enrollment))); - PreparedPromotion prepared = new PreparedPromotion(operationId, "6".repeat(64), "PREPARED"); + UUID promotionId = UUID.randomUUID(); + PreparedPromotion prepared = new PreparedPromotion(promotionId, "6".repeat(64), "PREPARED"); + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + when(promotion.operationId()).thenReturn(promotionId); + when(promotion.requestDigest()).thenReturn(prepared.requestDigest()); + when(promotion.generationOperationId()).thenReturn(operationId); + PreparedGenerationEvidence readback = mock(PreparedGenerationEvidence.class); + when(readback.promotion()).thenReturn(promotion); + when(readback.generationResult()).thenReturn(generation); + when(fixture + .repository() + .readPreparedGenerationForRecovery( + eq(fixture.binding().accountBinding()), eq(trustFence(fixture.binding())))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(insideTransaction.get()).isTrue(); + return readback; + }); when(fixture .repository() .prepareCurrentGeneration( @@ -561,6 +579,7 @@ void completeOwnerProofPreparesOnlyItsExactCurrentGenerationOnce() { }); assertThat(fixture.coordinator().prepareCurrentPromotionOnce()).contains(prepared); + assertThat(prepared.operationId()).isNotEqualTo(operationId); ArgumentCaptor preparation = ArgumentCaptor.forClass(PromotionPreparation.class); @@ -576,6 +595,12 @@ void completeOwnerProofPreparesOnlyItsExactCurrentGenerationOnce() { assertThat(preparation.getValue().readinessPlanDigest()).isEqualTo("4".repeat(64)); assertThat(preparation.getValue().readinessEvidenceDigest()).isEqualTo("5".repeat(64)); assertThat(insideTransaction.get()).isFalse(); + + when(promotion.generationOperationId()).thenReturn(UUID.randomUUID()); + assertThatThrownBy(fixture.coordinator()::prepareCurrentPromotionOnce) + .isInstanceOf(BootstrapOperationException.class) + .extracting(error -> ((BootstrapOperationException) error).failureCode()) + .isEqualTo(FailureCode.ACCOUNT_STATE_AMBIGUOUS); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java index dcc932463a..98b3fce42e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java @@ -63,12 +63,28 @@ void commitsAnIndependentOwnerReadBeforeReturningHeld() { verify(transactions).commit(status); } + @Test + void commitsAnIndependentWorldOwnerReadBeforeReturningHeld() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + asPeer("test", "world-management-service", () -> service.requireHeld(request)); + verify(repository).readHeld(any()); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(transactions).commit(status); + } + @Test void rejectsUnverifiedWrongWorkloadCrossNamespaceAndAmbientTransactionBeforeLookup() { var request = request("test"); assertCode(Status.Code.UNAUTHENTICATED, () -> service.requireHeld(request)); for (String workload : - List.of("account-service", "world-management-service", "spring-cloud-gateway")) { + List.of("account-service", "game-session-service", "spring-cloud-gateway")) { assertCode( Status.Code.PERMISSION_DENIED, () -> asPeer("test", workload, () -> service.requireHeld(request))); @@ -76,6 +92,9 @@ void rejectsUnverifiedWrongWorkloadCrossNamespaceAndAmbientTransactionBeforeLook assertCode( Status.Code.PERMISSION_DENIED, () -> asPeer("other", "game-design-service", () -> service.requireHeld(request))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "world-management-service", () -> service.requireHeld(request))); assertCode( Status.Code.PERMISSION_DENIED, () -> asPeer("test", "game-design-service", () -> service.requireHeld(request("other")))); @@ -126,7 +145,7 @@ public void onCompleted() { assertThat(Status.fromThrowable(error.get()).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); asPeer( "test", - "world-management-service", + "account-service", () -> endpoint.readHeldPublicationAuthorization( ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); @@ -134,7 +153,7 @@ public void onCompleted() { .isEqualTo(Status.Code.PERMISSION_DENIED); asPeer( "other", - "game-design-service", + "world-management-service", () -> endpoint.readHeldPublicationAuthorization( ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); @@ -142,7 +161,7 @@ public void onCompleted() { .isEqualTo(Status.Code.PERMISSION_DENIED); asPeer( "test", - "game-design-service", + "world-management-service", () -> endpoint.readHeldPublicationAuthorization( ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java index 276ee3fe28..b272b7e034 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java @@ -13,7 +13,7 @@ class AccountPublicationAuthorizationServiceTest { void persistenceCannotBeCalledWithoutTheWritableAccountOwnerTransaction() { var dsl = mock(DSLContext.class); var repository = new AccountPublicationAuthorizationRepository(dsl); - assertThatThrownBy(() -> repository.authorize(null, null, null, () -> {})) + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Writable READ_COMMITTED"); verifyNoInteractions(dsl); @@ -28,12 +28,12 @@ void readOnlyOrDifferentIsolationCannotMintPublicationPermission() { TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( java.sql.Connection.TRANSACTION_READ_COMMITTED); - assertThatThrownBy(() -> repository.authorize(null, null, null, () -> {})) + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) .isInstanceOf(IllegalStateException.class); TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( java.sql.Connection.TRANSACTION_REPEATABLE_READ); - assertThatThrownBy(() -> repository.authorize(null, null, null, () -> {})) + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(dsl); } finally { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java index ad1f185430..44f9d96499 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java @@ -195,6 +195,52 @@ public Optional readSynchronized( new WorldCanonicalAuthoredGraphReader().read(application.plan(), result.graphBytes())); } + /** + * Reads the actual APPLIED carrier for the one exact fresh graph selected for an internal World + * publication checkpoint. The caller holds the shared OPEN owner lock in the same transaction; + * this is not a substitute for Game Design selection or authenticated transport evidence. + */ + WorldDraftGraphAppliedResult readAppliedForPublicationCheckpoint( + WorldDesignPublicationFenceEvidence freeze, WorldDraftTopologyCommitPlan selectedPlan) { + Objects.requireNonNull(freeze, "freeze"); + Objects.requireNonNull(selectedPlan, "selectedPlan"); + requireTransaction(); + if (!freeze.ownerBinding().equals(selectedPlan.ownerBinding()) + || selectedPlan.graph().freshGraphDeclaration().isEmpty()) { + throw new ConflictException( + "World publication checkpoint requires the exact selected fresh graph owner"); + } + var binding = selectedPlan.binding(); + var rows = + dsl.fetch( + selectSql() + " WHERE a.request_id=? OR a.commit_id=?", + binding.requestId(), + binding.commitId()); + if (rows.isEmpty()) { + throw new ConflictException( + "World publication checkpoint requires an actual APPLIED graph application"); + } + if (rows.size() != 1) { + throw new ConflictException( + "Selected World graph request and commit identify conflicting applications"); + } + Record row = rows.getFirst(); + WorldDraftGraphApplication application = reconstruct(row); + if (!selectedPlan.binding().equals(application.plan().binding()) + || !selectedPlan.ownerBinding().equals(application.plan().ownerBinding()) + || !freeze.ownerBinding().equals(application.operation().ownerBinding()) + || !binding.requestId().equals(application.operation().requestId()) + || !binding.commitId().equals(application.operation().commitId())) { + throw new ConflictException( + "World APPLIED graph application differs from the exact selected commit or freeze owner"); + } + WorldDraftGraphAppliedResult result = readExact(application, row); + if (!"APPLIED".equals(result.status())) { + throw new ConflictException("World selected graph application is not APPLIED"); + } + return result; + } + private WorldDraftGraphApplication reconstruct(Record row) { try { var account = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java new file mode 100644 index 0000000000..93d447632d --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; + +/** + * Captures the owner-derived checkpoint for one exact, currently applied fresh World graph. + * + *

This internal seam is intended to run as the {@link WorldDesignPublicationFenceRepository} + * freeze callback. It does not implement Game Design publication selection, caller authentication, + * or a public freeze route, and it does not change the generic digest's highest-commit contract. + */ +final class WorldSelectedDraftPublicationCheckpointRepository { + private static final int REQUIRED_DIGEST_SCHEMA_VERSION = 3; + + private final WorldDesignPublicationFenceRepository fence; + private final WorldDraftGraphApplicationRepository applications; + private final WorldDraftTopologyCommitRepository topology; + private final WorldDraftDesignDigestService digestService; + + WorldSelectedDraftPublicationCheckpointRepository( + WorldDesignPublicationFenceRepository fence, + WorldDraftGraphApplicationRepository applications, + WorldDraftTopologyCommitRepository topology, + WorldDraftDesignDigestService digestService) { + this.fence = Objects.requireNonNull(fence, "fence"); + this.applications = Objects.requireNonNull(applications, "applications"); + this.topology = Objects.requireNonNull(topology, "topology"); + this.digestService = Objects.requireNonNull(digestService, "digestService"); + } + + Checkpoint capture( + WorldDesignPublicationFenceEvidence freeze, WorldDraftTopologyCommitPlan selectedPlan) { + Objects.requireNonNull(freeze, "freeze"); + Objects.requireNonNull(selectedPlan, "selectedPlan"); + if (!freeze.ownerBinding().equals(selectedPlan.ownerBinding())) { + throw new ConflictException( + "World checkpoint selection differs from the exact publication-freeze owner"); + } + + // Reacquiring this exact row inside claimFreeze's callback is reentrant and keeps the same + // owner lock held while APPLIED history, current rows/epochs, and the schema-3 digest are read. + var owner = fence.lockOpenAndResolve(freeze.ownerBinding()); + var applied = applications.readAppliedForPublicationCheckpoint(freeze, selectedPlan); + var stored = topology.readUnderFrozenLock(selectedPlan); + if (!stored.binding().equals(applied.application().operation().binding()) + || !stored.ownerBinding().equals(freeze.ownerBinding())) { + throw new ConflictException( + "World stored topology differs from the exact APPLIED selected graph application"); + } + + var digest = + digestService.getDraftDesignDigest( + Long.toString(owner.localTenantKey()), Long.toString(owner.localVersionKey())); + if (!Long.toString(owner.localTenantKey()).equals(digest.tenantId()) + || !Long.toString(owner.localVersionKey()).equals(digest.scopeValue()) + || digest.digestSchemaVersion() != REQUIRED_DIGEST_SCHEMA_VERSION) { + throw new ConflictException( + "World selected graph digest differs from the exact local schema-3 Draft scope"); + } + + return new Checkpoint( + applied.application().operation().commitId().toString(), + digest.contentDigest(), + digest.digestSchemaVersion()); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 4593576532..5c1be52e07 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -18,6 +18,7 @@ import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; import net.firedevops.firemud.common.authoring.DraftCommitBinding; @@ -184,6 +185,27 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() plan.ownerBinding(), original.canonicalBytes()); var application = new WorldDraftGraphApplication(operation, plan); + var missingApplicationEvidence = + publicationFreezeEvidence(plan, "unapplied-" + UUID.randomUUID()); + var stateBeforeMissingApplicationDenial = ownerSnapshot(world, plan); + assertThat(stateBeforeMissingApplicationDenial.publicationOwnerRows()).isEmpty(); + assertThat(stateBeforeMissingApplicationDenial.publicationAttemptRows()).isEmpty(); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + missingApplicationEvidence, + () -> + checkpointRepository() + .capture(missingApplicationEvidence, plan)))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("actual APPLIED graph application"); + var stateAfterMissingApplicationDenial = ownerSnapshot(world, plan); + assertThat(stateAfterMissingApplicationDenial).isEqualTo(stateBeforeMissingApplicationDenial); + assertThat(stateAfterMissingApplicationDenial.publicationOwnerRows()).isEmpty(); + assertThat(stateAfterMissingApplicationDenial.publicationAttemptRows()).isEmpty(); var pki = new TestPki(temporary.resolve("pki")); var accountServer = serve( @@ -219,6 +241,35 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() .isEqualTo(applied.canonicalBytes()); // Freeze a test-only publication selection of these actual authored owner rows. var frozen = capture(plan); + assertThat(frozen.request().freeze().appliedCommitId()) + .isEqualTo(applied.application().operation().commitId().toString()); + var retryEvidence = + publicationFreezeEvidence(plan, frozen.request().freeze().publicationRequestId()); + var stateBeforeExactRetry = ownerSnapshot(world, plan); + var checkpointCallbackInvocations = new AtomicInteger(); + var exactRetry = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + retryEvidence, + () -> { + checkpointCallbackInvocations.incrementAndGet(); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + "recapture-must-not-run", "b".repeat(64), 3); + }))); + assertThat(exactRetry.request()).isEqualTo(retryEvidence); + assertThat(exactRetry.publicationFence()) + .isEqualTo(frozen.request().freeze().publicationFence()); + assertThat(exactRetry.checkpoint()) + .isEqualTo( + new WorldDesignPublicationFenceEvidence.Checkpoint( + frozen.request().freeze().appliedCommitId(), + frozen.request().freeze().contentDigest(), + frozen.request().freeze().digestSchemaVersion())); + assertThat(checkpointCallbackInvocations.get()).isZero(); + assertThat(ownerSnapshot(world, plan)).isEqualTo(stateBeforeExactRetry); var selectors = new WorldPublishedStartLocationRepository( dsl, frozenRepository(), appliedRepository()); @@ -581,43 +632,14 @@ private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) var owner = plan.ownerBinding(); String publicationRequest = "selector-" + UUID.randomUUID(); // Stipulated test-only Game Design selection; no release/settlement is claimed. - var evidence = - new WorldDesignPublicationFenceEvidence( - owner.targetNamespace(), - owner.canonicalTenantId(), - owner.canonicalVersionId(), - owner.versionIdentityOperationId(), - owner.gameDesignVersionId(), - owner.intakeRequestId(), - owner.intakeOperationId(), - owner.intakeRequestDigest(), - owner.sourceOperationId(), - owner.sourceEvidenceDigest(), - owner.intakeReceiptDigest(), - publicationRequest, - "a".repeat(64), - 1, - "publish:" + owner.canonicalTenantId() + ":publish-request:" + publicationRequest); + var evidence = publicationFreezeEvidence(plan, publicationRequest); var attempt = Objects.requireNonNull( ownerTransaction() .execute( status -> fence.claimFreeze( - evidence, - () -> { - var identity = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT local_tenant_key,local_version_key FROM world_authored_version_identity WHERE operation_id=?", - owner.versionIdentityOperationId())); - var digest = - digestService.getDraftDesignDigest( - identity.get("local_tenant_key", Long.class).toString(), - identity.get("local_version_key", Long.class).toString()); - return new WorldDesignPublicationFenceEvidence.Checkpoint( - plan.binding().commitId().toString(), digest.contentDigest(), 3); - }))); + evidence, () -> checkpointRepository().capture(evidence, plan)))); var tuples = plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() .map( @@ -649,6 +671,134 @@ private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) .capture(new WorldCanonicalFrozenTopology.Request(plan, request)); } + private WorldSelectedDraftPublicationCheckpointRepository checkpointRepository() { + return new WorldSelectedDraftPublicationCheckpointRepository( + fence, + appliedRepository(), + new WorldDraftTopologyCommitRepository(dsl, fence, mapper), + digestService); + } + + private DraftOwnerSnapshot ownerSnapshot(Fixture fixture, WorldDraftTopologyCommitPlan plan) { + long tenant = fixture.intake().localTenantKey(); + long version = fixture.version().localVersionKey(); + List currentRows = new ArrayList<>(); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding")) { + rowJson( + "SELECT to_jsonb(t)::text AS row_json FROM " + + table + + " t WHERE tenant_id=? AND version_id=? ORDER BY id", + tenant, + version) + .forEach(row -> currentRows.add(table + ":" + row)); + } + var aggregateEpochRows = + rowJson( + "SELECT to_jsonb(t)::text AS row_json FROM world_design_aggregate_epoch t " + + "WHERE tenant_id=? AND version_id=? ORDER BY aggregate_type,aggregate_id", + tenant, + version); + var scopeEpochRows = + rowJson( + "SELECT to_jsonb(t)::text AS row_json FROM world_design_scope_epoch t " + + "WHERE tenant_id=? AND version_id=? ORDER BY scope_type,scope_id", + tenant, + version); + var revisionRows = + rowJson( + "SELECT to_jsonb(t)::text AS row_json FROM world_design_revision_ledger t " + + "WHERE tenant_id=? AND version_id=? ORDER BY id", + tenant, + version); + var topologyRows = + rowJson( + "SELECT to_jsonb(t)::text AS row_json FROM world_topology_draft_commit t " + + "WHERE request_id=? OR commit_id=? ORDER BY request_id", + plan.binding().requestId(), + plan.binding().commitId()); + var applicationRows = + rowJson( + "SELECT to_jsonb(t)::text AS row_json FROM world_draft_graph_application t " + + "WHERE request_id=? OR commit_id=? ORDER BY request_id", + plan.binding().requestId(), + plan.binding().commitId()); + var terminalIdentityRows = + rowJson( + "SELECT to_jsonb(t)::text AS row_json FROM world_draft_graph_terminal_identity t " + + "WHERE request_id=? OR commit_id=? ORDER BY request_id", + plan.binding().requestId(), + plan.binding().commitId()); + var publicationOwnerRows = + rowJson( + "SELECT to_jsonb(t)::text AS row_json FROM world_design_publication_fence_owner t " + + "WHERE target_namespace=? AND canonical_tenant_id=? AND version_id=? " + + "ORDER BY target_namespace,canonical_tenant_id,version_id", + fixture.owner().targetNamespace(), + fixture.owner().canonicalTenantId(), + version); + var publicationAttemptRows = + rowJson( + "SELECT to_jsonb(t)::text AS row_json FROM world_design_publication_fence_attempt t " + + "WHERE target_namespace=? AND canonical_tenant_id=? AND version_id=? " + + "ORDER BY publication_fence", + fixture.owner().targetNamespace(), + fixture.owner().canonicalTenantId(), + version); + return new DraftOwnerSnapshot( + List.copyOf(currentRows), + aggregateEpochRows, + scopeEpochRows, + revisionRows, + topologyRows, + applicationRows, + terminalIdentityRows, + publicationOwnerRows, + publicationAttemptRows); + } + + private List rowJson(String sql, Object... bindings) { + return dsl.resultQuery(sql, bindings).fetch(0, String.class); + } + + private record DraftOwnerSnapshot( + List currentRows, + List aggregateEpochRows, + List scopeEpochRows, + List revisionRows, + List topologyRows, + List applicationRows, + List terminalIdentityRows, + List publicationOwnerRows, + List publicationAttemptRows) {} + + private WorldDesignPublicationFenceEvidence publicationFreezeEvidence( + WorldDraftTopologyCommitPlan plan, String publicationRequest) { + var owner = plan.ownerBinding(); + return new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + publicationRequest, + "a".repeat(64), + 1, + "publish:" + owner.canonicalTenantId() + ":publish-request:" + publicationRequest); + } + private record Fixture( WorldAuthoredSourceIntakeReceipt intake, WorldAuthoredVersionIdentityReceipt version, From 5132fb96b98f2d33b9db5d09d763aebb63efafb2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:49:33 +1300 Subject: [PATCH 029/129] Bind selected publication freeze to authenticated owner evidence --- .../account-service/api-contracts.md | 2 + .../account-service/operations.md | 2 +- .../game-design-service/api-contracts.md | 18 + .../game-design-service/version-control.md | 2 + .../world-management-service/api-contracts.md | 4 +- .../system-architecture-testing.md | 4 +- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 14 +- .../publication_terminal_read_service.proto | 32 + .../selected_draft_publication_service.proto | 38 + ...tSelectedDraftPublicationOrderService.java | 88 ++ ...nAuthorizationPostgresIntegrationTest.java | 18 + ...ectedDraftPublicationOrderServiceTest.java | 292 ++++++ ...thoredDraftPublishSelectionReadClient.java | 166 +++ ...oredDraftPublishSelectionReadEvidence.java | 102 ++ ...redDraftPublishSelectionReadGrpcCodec.java | 106 ++ ...meDesignPublicationTerminalReadClient.java | 161 +++ ...DesignPublicationTerminalReadEvidence.java | 98 ++ ...esignPublicationTerminalReadGrpcCodec.java | 103 ++ ...edDraftPublishSelectionReadClientTest.java | 230 +++++ ...raftPublishSelectionReadGrpcCodecTest.java | 212 ++++ ...signPublicationTerminalReadClientTest.java | 235 +++++ ...gnPublicationTerminalReadEvidenceTest.java | 55 + ...nPublicationTerminalReadGrpcCodecTest.java | 263 +++++ ...lectedDraftPublicationReadGrpcService.java | 112 ++ ...ignPublicationTerminalReadGrpcService.java | 93 ++ ...eDesignPublicationTerminalReadService.java | 130 +++ ...emptServiceTransactionIntegrationTest.java | 408 ++++++++ ...edDraftPublicationReadGrpcServiceTest.java | 275 +++++ ...ublicationTerminalReadGrpcServiceTest.java | 231 +++++ ...ignPublicationTerminalReadServiceTest.java | 258 +++++ ...aftPublicationAuthorizationRepository.java | 223 ++++ ...SelectedDraftPublicationFreezeService.java | 387 +++++++ ...d_selected_publication_account_binding.sql | 86 ++ ...uthorizedDraftPostgresIntegrationTest.java | 467 ++++++++- ...ctedDraftPublicationFreezeServiceTest.java | 970 ++++++++++++++++++ 36 files changed, 5865 insertions(+), 26 deletions(-) create mode 100644 protos/game-design/v1/publication_terminal_read_service.proto create mode 100644 protos/game-design/v1/selected_draft_publication_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadService.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadServiceTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationAuthorizationRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V53__world_selected_publication_account_binding.sql create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3e5aaad90b..3a5e24efc6 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -82,6 +82,8 @@ The standalone, unregistered `AccountPublicationAuthorizationReadService.ReadHel Account acquires this distinct publication order from the authenticated acting account and immutable Game Design Draft selection before World freeze. Its original actor, canonical tenant, selected-Draft digest, exact source versions and Account fence remain immutable across retry and recovery. The later World capture is correlated separately and must not rewrite the original order or its digest. Applicable source participation protects the authorized operation through actual World commit; a remote `HELD` sample alone is not commit-time protection. Participation may be released only after authenticated exact publication commit/abort readback, never from timeout, absence, a Draft terminal receipt or ambiguous publication evidence. Retained orders and their evidence remain immutable under forward-only migration. The current unregistered producer/read components do not yet establish this complete terminal settlement boundary. +The selected-order composition authenticates the exact same-namespace Game Design caller, obtains the [immutable selected-Draft owner read](../game-design-service/api-contracts.md#immutable-selected-draft-publication-read) outside Account SQL, then passes the unchanged creator credential and exact retained selection to Account's current-actor/source-hold owner transaction. `SELECTED` alone is not actor authorization. No database lock may span that read, and unavailable or substituted selection evidence cannot create an order. Implementation and executed proof remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index a054fd8f7a..f8d768e488 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -8,7 +8,7 @@ This document collects the Account Service operational behavior, readiness model - `liveness` is process-local only. - `readiness` is truthful local readiness for the currently implemented authentication/account slice and must fail when the service cannot safely satisfy new authentication traffic with its required local persistence/session infrastructure. - Logging, metrics, and tracing follow the standard [Logging & Monitoring](../../system-architecture-logging-monitoring.md) pipeline. -- Expired connect-scope cleanup requires PostgreSQL 16 or later because its deletion predicate uses `pg_input_is_valid`; local Docker Compose uses PostgreSQL 18, and Account's shared Testcontainers fixture selects the digest-pinned PostgreSQL 18 baseline in [Testing Architecture's shared container image references](../../system-architecture-testing.md#shared-container-image-references). Fixture selection does not demonstrate Docker-backed execution of Account integration tests, which remains pending proof. Keep the guarded delete predicate and do not add a pre-16 compatibility query. +- Expired connect-scope cleanup requires PostgreSQL 16 or later because its deletion predicate uses `pg_input_is_valid`; local Docker Compose uses PostgreSQL 18. The shared test-image resource selects the digest-pinned PostgreSQL 18 baseline in [Testing Architecture's shared container image references](../../system-architecture-testing.md#shared-container-image-references), but Account's current `AccountPostgresIntegrationFixture` explicitly selects `postgres:16-alpine`. The admission original/receipt commit executors and V92 guards support PostgreSQL 16 only and deny other major versions; the shared image baseline does not widen that supported physical-COMMIT boundary. Fixture selection alone proves no Docker-backed execution. Keep the guarded delete predicate and do not add a pre-16 compatibility query. ### V26 membership migration preflight diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index fe3ee5265f..69ac6c80f6 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -45,6 +45,24 @@ For every creator-intent `SaveRevision`, including revision-only requests, the e For a `SaveRevision` request carrying `worldDesignMutation`, the same authorization invariant additionally applies to every participating authoritative mutation. Participating owners may use prepare or other non-authoritative staging before the authoritative commit boundary, but this contract selects no transaction, lease, fence, saga, route, or schema mechanism. If the boundary cannot be satisfied, no participating owner commits, and SaveRevision must not report success for a partial cross-owner commit. +## Immutable Selected-Draft Publication Read + +`GameDesignSelectedDraftPublicationReadService.ReadSelectedDraftPublication` is a standalone, unregistered owner-read boundary for the exact immutable selection reserved by Game Design before Account acquires the distinct publication order. Only an authenticated, same-namespace Account or World Management workload may use it. Authenticate the peer before decoding the selection or accessing owner storage; a JWT claim, caller-carried digest or valid selection codec alone is not owner authentication. + +The closed version-1 request binds `schemaVersion`, `targetNamespace`, a canonical non-nil `readRequestId`, the complete original selection's canonical bytes, and its `selectionDigest`. The selection contains the canonical tenant and Version, stable publish request, expected version-state epoch, exact synchronized commit and result fence, and retained private source provenance. Game Design reads its retained selection by the exact canonical tenant, Version and publish request, then compares the complete bytes and digest. Missing, inconsistent or changed evidence fails closed. Unknown wire fields and unsupported versions are rejected rather than ignored. + +A successful response echoes the entire request unchanged and reports only `SELECTED`. It attests the immutable retained selection, not current lifecycle state, a live permission, an Account source hold, World freeze, terminal publication, settlement or admission. Those remain separate owner checks. Consumers authenticate the exact Game Design workload server, verify the full response echo, and complete this bounded read outside their SQL transaction. No owner database lock may be held across the RPC. Exact retries read the same retained bytes; no retry may select a newer commit under the old publication request. + +The transport is construction work, not runtime registration. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records executed proof and remaining producer, composition and activation gates. The [Account contract](../account-service/api-contracts.md#grpc-apis) owns publication authorization and source participation; the [World contract](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) owns freeze and terminal handoff. + +## Exact Publication Terminal Read + +`GameDesignPublicationTerminalReadService.ReadPublicationTerminal` reads the original immutable terminal result, not current permission or a new publication attempt. Its closed version-1 request binds the canonical workload namespace, a non-nil canonical read-request UUID and the complete original `game-design-publication-operation/v1` bytes. The receiver authenticates the exact same-namespace Account or World Management workload before decoding input or accessing storage. + +The owner uses one independent read-only repeatable-read snapshot to verify the original operation and complete terminal backing. Success echoes every request field unchanged and returns the exact retained terminal bytes: either `PUBLISHED` with the complete original release and publication epoch, or `NO_PUBLICATION` with its immutable no-publication evidence. Missing, pending, legacy-incomplete, corrupt or mismatched backing returns no terminal evidence. Consumers authenticate the exact Game Design server and verify both the response echo and the complete operation/terminal relationship outside their SQL transactions. A lost response is recovered by the same exact read, never by reconstructing evidence from current Version state or a Temporal status. + +This historical result grants no current creator permission or runtime admission and does not itself release Account participation or complete World settlement. Those owners must verify their own exact operation and committed postconditions under the [Account settlement contract](../account-service/api-contracts.md#grpc-apis) and [World terminal contract](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state). Runtime registration and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + ## Implementation Status The fresh-tenant owner source includes V29 canonical UUID/provenance storage, V30 exact creation-operation persistence, the owner-local transaction producer and source readback, and the exact Account/Game Session peer receipt read RPC. Validation evidence and remaining gaps belong to the linked implementation tracker. No creator RPC or authenticated creator authority is wired, and no Account association, membership, JOIN, or runtime admission is enabled by this source. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 1d393b9ea0..3acf9cf70e 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -62,6 +62,8 @@ Game Design owns the durable, creator-visible coordination record for every shar #### Publication freeze and owner handoff (Target State) +The [immutable selected-Draft owner read](api-contracts.md#immutable-selected-draft-publication-read) preserves Game Design's original reserved selection across the Account-order and World-freeze handoffs. Its `SELECTED` response is not current Draft-state or permission evidence; consumers must retain those separate lifecycle and Account checks. + The synchronized Draft fence is also the lifecycle handoff into publication. Game Design first obtains the distinct [Account publication authorization](../account-service/api-contracts.md#grpc-apis) for its authenticated immutable Draft selection, then presents that exact order for World freeze; later World capture is separate correlation, not a rewrite of Account authorization. Before collecting the World Management participant digest, reading the final release state, or committing `published_release_bundle` and `PUBLISHED` metadata, Game Design must obtain and retain the exact WMS owner-freeze acknowledgement, then complete or abort that same owner operation after reconciling its publication outcome. The canonical WMS operations, fields, phase transitions, exact replay/conflict behavior, and current implementation/proof boundary are defined in [World Management API Contracts](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state). This is one owner-local freeze protocol, not a distributed transaction: the freeze serializes WMS Draft writes, while Game Design remains the lifecycle and final-attestation authority. Focused proof must interleave a WMS mutation with freeze acquisition, publication, retry, abort, and lost-response reconciliation and prove that no post-freeze Draft row or digest can become part of a Published release. **Current implementation gap:** World Management currently lacks the durable owner-local publication freeze and exact Game Design version-state epoch/fence enforcement required by this target contract. Its live handoff checks the authoritative remote Game Design `DRAFT` state before its own transaction, but that check does not prove that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 986010ae15..b97262a8f5 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -84,7 +84,7 @@ World Management exposes design-time APIs used by Game Design to write Draft tem ### Publication freeze and terminal handoff (target state) -The publication-freeze operations below remain unregistered target contract surfaces. Current construction includes internal owner-lock/freeze persistence, immutable terminal storage and a selected-fresh-graph checkpoint callback; these do not supply an authenticated publication-freeze handler or complete owner handoff. The callback derives the selected commit from an actual Account-bound World `APPLIED` result and rechecks the complete retained graph against current topology and epochs under the shared owner lock. It does not authenticate Game Design's selection or establish the generic highest-applied-commit digest contract. No current caller may infer a public freeze, publication, or terminal owner result from internal storage, a digest, a remote `GetVersionState` read, or a Temporal run identity. Current capability and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The publication-freeze operations below remain unregistered target contract surfaces. Current construction includes owner-lock/freeze persistence, immutable terminal storage, a selected-fresh-graph checkpoint callback and a standalone selected-publication composition; these do not supply a registered publication-freeze RPC or complete owner handoff. The callback derives the selected commit from an actual Account-bound World `APPLIED` result and rechecks the complete retained graph against current topology and epochs under the shared owner lock. The standalone composition additionally obtains authenticated Game Design selection/current-Draft and Account held-order reads, retaining the original Account correlation with the first freeze. It does not establish the generic highest-applied-commit digest contract. No current caller may infer a public freeze, publication, or terminal owner result from internal storage, a digest, a remote `GetVersionState` read, or a Temporal run identity. Current capability and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). `BeginVersionPublicationFreeze` accepts exactly: @@ -96,6 +96,8 @@ The publication-freeze operations below remain unregistered target contract surf Account must acquire that publication order before World freeze; the later World capture is correlated separately without rewriting it. The [Account publication authorization contract](../account-service/api-contracts.md#grpc-apis) owns its immutable identity, protected source participation and terminal settlement. World verifies the exact selection/order relationship, not original Draft permission or workload identity alone. A remote held-order sample does not authorize releasing source protection before the actual World commit. +World retains the complete original Account publication-order binding, including its operation and fence identity, atomically with the first qualified freeze. A committed exact retry compares that immutable correlation and returns the stored checkpoint before recapturing mutable Game Design state; changed authorization cannot be attached to the old freeze even when the selection is unchanged. Historical freezes without that correlation remain unqualified and fail closed: neither a current `HELD` sample nor later terminal evidence may invent their original Account authorization. + WMS authenticates the caller, resolves the target `(tenantId, versionId)`, verifies that Game Design still reports the expected Draft state/epoch, and in one owner-local transaction locks or creates the durable owner-freeze row for that pair, persists `publicationRequestId`, `requestDigest`, the observed Game Design `versionStateEpoch`, one equality-only opaque `publicationFence`, and the WMS digest checkpoint `{appliedCommitId, contentDigest, digestSchemaVersion}`, then changes the phase to `FROZEN`. The successful acknowledgement is emitted only after that transaction commits. The phase vocabulary is `OPEN`, `FROZEN`, `PUBLISHED`, `ABORTED`, and `RECONCILIATION_REQUIRED`; `FROZEN` is entered only after the row, opaque fence, and checkpoint commit, while terminal attempt evidence remains available for exact replay before a later attempt may reopen an `ABORTED` row. Every Draft mutation takes the same row lock, so a writer that reaches the lock after the freeze cannot commit an unbound `OPEN` mutation. A missing/changed epoch, missing Draft authority, unauthorized caller, conflicting nonterminal request, or changed request digest fails closed. The successful acknowledgement is the complete tuple `{tenantId, versionId, publicationRequestId, requestDigest, versionStateEpoch, publicationFence, ownerFreezePhase, appliedCommitId, contentDigest, digestSchemaVersion}`. An exact retry returns the stored acknowledgement and does not mint a second fence; reuse of the request identity with any changed or omitted field returns `IDEMPOTENCY_CONFLICT`. A lost response is reconciled by reading this owner row with the same request identity and digest. diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index 237d6baeaf..2a525ae180 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -227,7 +227,9 @@ For workflows that span multiple services, such as account creation and world pr ### Shared Container Image References -PostgreSQL and Redis Testcontainers fixtures use `TestContainerImages.postgres()` and `TestContainerImages.redis()` from `common-test-support`. The fixture artifact exports [`container-images.properties`](../../services/common-test-support/src/testFixtures/resources/net/firedevops/firemud/test/container-images.properties) as a classpath resource; this file owns the selected test image references. PostgreSQL uses the approved digest-pinned PostgreSQL 18 test baseline, and the selected Redis test image is recorded in the shared [container image resource](../../services/common-test-support/src/testFixtures/resources/net/firedevops/firemud/test/container-images.properties). Renovate updates this resource, including digest pinning, rather than editing Java source literals. PostgreSQL tagged digests retain the canonical Testcontainers compatible-substitute handling. These disposable fixture selections do not change deployed database version or migration/restore requirements. +Fixtures using the shared image selectors obtain PostgreSQL and Redis references from `TestContainerImages.postgres()` and `TestContainerImages.redis()` in `common-test-support`. The fixture artifact exports [`container-images.properties`](../../services/common-test-support/src/testFixtures/resources/net/firedevops/firemud/test/container-images.properties) as a classpath resource; this file owns those selected test image references. PostgreSQL uses the approved digest-pinned PostgreSQL 18 test baseline, and the selected Redis test image is recorded in the shared [container image resource](../../services/common-test-support/src/testFixtures/resources/net/firedevops/firemud/test/container-images.properties). Renovate updates this resource, including digest pinning, rather than editing Java source literals. PostgreSQL tagged digests retain the canonical Testcontainers compatible-substitute handling. These disposable fixture selections do not change deployed database version or migration/restore requirements. + +Not every current fixture consumes this shared resource. Account's `AccountPostgresIntegrationFixture` explicitly uses PostgreSQL 16; its admission physical-COMMIT guards also require that major version. The [Account operations contract](./microservices/account-service/operations.md#operational-notes) records that local boundary. Neither the shared PostgreSQL 18 selection nor successful PostgreSQL 16 execution proves admission support on another major version. ### Example Workflow diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8ef0b60f95..3de156fa40 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -92,3 +92,9 @@ Entry format: - Observation: Installed Spring gRPC 1.0.3 uses that flag to control sorting, not exclusion. Its supported server-factory filter removes global interceptors before explicitly selected interceptors are appended; a null-factory test cannot prove that filtering path. - Expected pattern: Prove isolated and ordinary service composition with the production factory customization, preserving exact peer extraction and ordinary application authentication. Annotation assertions alone are insufficient. - Current status: The composition test exposed the defect before publication of the routing correction. A bounded service-local factory filter and positive/negative proof are being integrated; deployed composition remains unproved. + +- `2026-10-08`: Separate global WAL-frontier denial from target COMMIT durability + - Context: PR #3105's exact original-ack recovery test denied because its captured global insert frontier remained 64 bytes beyond the logged flush. Failure-only WAL diagnostics decoded both target COMMIT records, including full record lengths and aligned end boundaries; those boundaries were covered by the independently logged flush. + - Observation: A global-frontier shortfall does not identify an unflushed target transaction. Conversely, record presence or a COMMIT start address alone does not establish durability; alignment, continuation pages, exact transaction identity and an independent flush observation matter. COMMIT record timestamps are not authenticated physical-flush deadline evidence. + - Expected pattern: Preserve fail-closed acceptance while distinguishing an unavailable conservative proof from a demonstrated durability failure. A production exact-record recovery mechanism needs a supported locator, retained WAL availability, timeline/transaction-epoch checks and separate flush coverage; offline artifact decoding cannot silently replace that mechanism. + - Current status: The production recovery path has no independent exact-COMMIT locator and remains denied. A bounded supported-mechanism proposal has been routed to Overseer; no database extension, privilege expansion, deadline relaxation or runtime activation is authorized by this diagnostic. 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 f0ebdc2e97..d1772ff28d 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 @@ -6,11 +6,21 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The World selected-fresh-graph checkpoint callback derives its commit identity from the exact retained Account-bound `APPLIED` application, rather than a caller-supplied checkpoint. Under the shared owner lock it rechecks the complete current graph and epoch set and computes the schema-3 content digest. The composition definition uses this callback while still stipulating Game Design's publication selection. It does not implement an authenticated freeze producer, change the generic digest's synthetic highest-commit limitation, or establish physical execution or publication authority. The approved [Account order-before-freeze contract](../../architecture/microservices/account-service/api-contracts.md#grpc-apis) now settles the ordering gap; complete authenticated World verification and terminal settlement still require implementation and proof. +The current publication handoff batch has passing local unit XML for 302 Common, 1,067 Account, 341 Game Design and 533 World cases. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. Local database integration cases skip without Docker; final combined formatting, static checks, packaging and documentation validation are recorded with the published construction checkpoint. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. + +Overseer-owned isolated [Pod admission run 37830726704](https://github.com/benhook1013/FireMUD/actions/runs/37830726704) passed the Account and Game Session CREATE/adversarial matrices plus UPDATE and ephemeral-container checks; Overseer reported the owned cluster deleted after the run. This is admission-only evidence. CNI/socket routing, kubelet UID/process correspondence, replacement races, shared-key closure and promotion readiness remain unproved; duplicate-SPKI rejection and activation denial are unchanged. + +The [immutable selected-Draft owner read](../../architecture/microservices/game-design-service/api-contracts.md#immutable-selected-draft-publication-read) now has a closed proto, strict file-backed mTLS client and standalone Game Design receiver. It authenticates only exact same-namespace Account/World peers and compares the complete retained selection before emitting `SELECTED`. Unit proof and the new real PostgreSQL/loopback-mTLS definition remain subject to the current validation batch; the latter stipulates upstream owner outcomes and is not genuine end-to-end publication provenance. The route remains unregistered, and current Draft-state, Account authorization, World freeze and terminal settlement remain separate requirements. + +The legacy World numeric mutation route lacks the target shared-lock handoff, but the existing canonical-tenant manifest and mapped-row guards deny its writes to the exact fresh canonical target. The current composition adds negative PostgreSQL definitions through the real mutation service, deriving private selectors from retained mapping evidence and checking unchanged content, mappings, epochs, ledger, application and freeze history. These definitions have not yet executed physically; they do not justify opening the legacy route or claiming its broader target contract complete. + +The World selected-fresh-graph checkpoint callback derives its commit identity from the exact retained Account-bound `APPLIED` application, rather than a caller-supplied checkpoint. Under the shared owner lock it rechecks the complete current graph and epoch set and computes the schema-3 content digest. Construction CI at `60c507243987705094a3028e0b46f3bccd5d9504` executed the actual Account-order-to-World-APPLIED and selected-checkpoint cases. The standalone selected-publication freeze composition now obtains authenticated immutable selection, current Game Design Draft state and exact Account held-order reads outside SQL, then retains the complete Account binding atomically with the first World freeze. V53 denies late qualification of historical attempts. Exact committed retry verifies the stored order before recapturing mutable authority. New qualification/rollback definitions still require physical execution; their distinct Account publication order is explicitly stipulated, not a substitute for the genuine producer. This does not change the generic digest's synthetic highest-commit limitation, register a freeze RPC, settle either owner, or establish end-to-end publication authority. + +The standalone Game Design terminal owner read verifies complete original operation and terminal backing in an independent read-only repeatable-read snapshot. Its closed transport follows the [exact terminal-read contract](../../architecture/microservices/game-design-service/api-contracts.md#exact-publication-terminal-read); owner/transport unit definitions do not establish physical authenticated terminal composition. The receiver remains unregistered. World completion and distinct Account settlement after both exact authenticated owner outcomes remain open. The standalone Account selected-publication producer defines a distinct immutable authorization from the authenticated current initial creator, immutable selected Draft and original issuance/source/checkpoint evidence before World capture. Its unregistered owner reader permits only verified same-namespace Game Design or World Management workloads and checks exact retained participation and committed issuance in one independent snapshot. V106 permits new pre-freeze orders without World evidence while retaining immutable V103 evidence unchanged and checking it when present; retained-row upgrade execution remains unproved. Later World correlation cannot rewrite the Account order. Pending publication participates in source-writer and prepare-before-disclose guards, but authenticated exact terminal readback and settlement remain open. Producer, transport and database test definitions are not runtime activation. -Substantive construction CI at `20c1ae0f4d1e3e8789438bbf52221f8ea3ab3b14` executed 225 Account, 201 World and 74 Game Design integration cases with no skips or errors. Six Account failures and the World owner-composition failure share the signer coordinator's incorrect comparison of a promotion UUID with its originating generation UUID; the correction validates their exact persisted relationship through locked recovery readback. Six terms-handoff failures require the fixture's real V103 publication schema instead of its obsolete V101 ceiling. Four Account admission cases still failed closed on unavailable WAL coverage; no durability or deadline guard is relaxed. These fixes require corrected-head physical execution. Local World validation executed 518 unit cases; all 201 PostgreSQL cases skipped without Docker. Earlier V104 repaired the separate nonexistent promotion-row receipt field; it did not fix this subsequent coordinator identity defect. +Substantive construction CI [37827785558](https://github.com/benhook1013/FireMUD/actions/runs/37827785558) for `60c507243987705094a3028e0b46f3bccd5d9504` executed 229 Account, 201 World and 74 Game Design integration cases with no skips or errors. Game Design and World passed; Account had two failures. The signer generation/promotion identity correction and V103 terms-fixture correction passed their affected cases. One remaining Account concurrency test reused a frozen activity-statistics snapshot while waiting for a blocked creator; its observer correction requires corrected-head execution. Original-ack receipt recovery still fails closed against the conservative global WAL insert fence. Decoded target COMMIT boundaries were covered by the independently logged flush, but the production recovery path has no supported independent exact-COMMIT locator; this diagnostic does not weaken durability or deadline requirements. The run tested a synthetic merge whose first parent was `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`; it supplies no exact-integrated-base or ancestry-closure proof. Local PostgreSQL definitions remain skipped without Docker. The current Gameplay-prerequisite construction remains non-activating. Full-version finalization reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. Production backend control-ui issuance/current-actor integration, complete Account source-writer fencing and the callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. In particular, the distinct selected-publication operation still needs authenticated Account authorization; original Draft permission cannot substitute. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Construction CI at `f14c7950827dd435ac0fe5c4cc230a1de32fa96d` executed all 74 Game Design and 200 World integration cases without skips or failures, including the corrected canonical-release and selected-publication transaction regressions. Its 220 Account integration executions passed the future-terms, environment-binding, disclosure-handoff and three real Redis registry cases; one readiness-promotion fixture assertion still compared its initial plan with subsequently progressed entries. A corrected assertion and the composed Account-to-World handoff need separate validation. These bounded results do not upgrade the broader capability ratings below. diff --git a/protos/game-design/v1/publication_terminal_read_service.proto b/protos/game-design/v1/publication_terminal_read_service.proto new file mode 100644 index 0000000000..382e2bc960 --- /dev/null +++ b/protos/game-design/v1/publication_terminal_read_service.proto @@ -0,0 +1,32 @@ +syntax = "proto3"; + +package game_design.v1; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Standalone historical owner read. Only verified same-namespace Account and World Management +// workloads may call. No runtime registration, source release, World completion, or admission. +service GameDesignPublicationTerminalReadService { + rpc ReadPublicationTerminal(ReadPublicationTerminalRequest) + returns (ReadPublicationTerminalResponse); +} + +message ReadPublicationTerminalRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical GameDesignPublicationOperationBinding bytes; lookup data, not authority. + bytes original_operation = 4; +} + +message ReadPublicationTerminalResponse { + // Complete request echoed unchanged; unavailable/nonterminal/legacy evidence is a non-OK RPC. + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_operation = 4; + // Exact original GameDesignPublicationTerminalEvidence, including exhaustive PUBLISHED content + // or explicit NO_PUBLICATION. Transport never mints or upgrades retained terminal bytes. + bytes terminal_evidence = 5; +} diff --git a/protos/game-design/v1/selected_draft_publication_service.proto b/protos/game-design/v1/selected_draft_publication_service.proto new file mode 100644 index 0000000000..b40df96d6e --- /dev/null +++ b/protos/game-design/v1/selected_draft_publication_service.proto @@ -0,0 +1,38 @@ +syntax = "proto3"; + +package game_design.v1; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Standalone immutable reservation read; authenticate exact same-namespace Account or World +// Management workload before decoding. SELECTED attests neither current DRAFT state nor actor +// authority, a source hold, World freeze, release/settlement, or runtime admission. +service GameDesignSelectedDraftPublicationReadService { + rpc ReadSelectedDraftPublication(ReadSelectedDraftPublicationRequest) + returns (ReadSelectedDraftPublicationResponse); +} + +message ReadSelectedDraftPublicationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete original AuthoredDraftPublishSelectionBinding canonical bytes and SHA-256 digest. + bytes original_selection = 4; + string selection_digest = 5; +} + +enum SelectedDraftPublicationStatus { + SELECTED_DRAFT_PUBLICATION_STATUS_UNSPECIFIED = 0; + SELECTED_DRAFT_PUBLICATION_STATUS_SELECTED = 1; +} + +message ReadSelectedDraftPublicationResponse { + // Echo every request field exactly. Missing/conflicting/unavailable storage is a non-OK RPC. + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_selection = 4; + string selection_digest = 5; + SelectedDraftPublicationStatus status = 6; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java new file mode 100644 index 0000000000..45180b793b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Standalone, unregistered composition of authenticated Game Design selection read and distinct + * Account publication ordering. SELECTED attests immutable reservation only; Account's existing + * owner primitive remains the authority for the original creator, currentness and source holds. + * World freeze/capture, settlement and runtime admission are separate boundaries. + */ +public final class AccountSelectedDraftPublicationOrderService { + private final AuthoredDraftPublishSelectionReadClient selectionClient; + private final AccountPublicationAuthorizationService owner; + private final String workloadNamespace; + + public AccountSelectedDraftPublicationOrderService( + AuthoredDraftPublishSelectionReadClient selectionClient, + AccountPublicationAuthorizationService owner, + String workloadNamespace) { + this.selectionClient = Objects.requireNonNull(selectionClient, "selectionClient"); + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * The caller's selection is lookup data. Only the exact authenticated Game Design read is passed + * to Account's local producer, with the original creator JWT and environment unchanged. The + * remote read completes before the producer opens its own owner transaction. + */ + public AccountPublicationAuthorizationBinding authorize( + String compactJwt, + AuthoredDraftPublishSelectionBinding lookupSelection, + CapturedEnvironmentBoundary environment) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(lookupSelection, "lookupSelection"); + var request = + AuthoredDraftPublishSelectionReadEvidence.Request.create( + workloadNamespace, lookupSelection); + var evidence = selectionClient.read(request); + if (evidence == null + || !request.equals(evidence.request()) + || !Arrays.equals( + lookupSelection.canonicalBytes(), evidence.request().binding().canonicalBytes()) + || !lookupSelection.digest().equals(evidence.request().binding().digest())) { + throw new IllegalStateException( + "Authenticated Game Design selection differs from the exact publication order request"); + } + requireNoAmbientTransaction(); + return owner.authorize(compactJwt, evidence.request().binding(), environment); + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected publication ordering requires no ambient transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index 77d5c6bc29..0e189cfee1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -277,6 +277,24 @@ void actualSourceWriterBlocksCreatorCaptureThenWinsBeforePublication() throws Ex long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); Integer blockedPid = null; while (System.nanoTime() < deadline && blockedPid == null) { + if (attempt.get().isDone()) { + try { + attempt.get().get(); + } catch (java.util.concurrent.ExecutionException failure) { + throw new AssertionError( + "Creator authorization failed before the Account-row wait was observed", + failure.getCause()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError( + "Interrupted while diagnosing completed creator authorization", + interrupted); + } + throw new AssertionError( + "Creator authorization succeeded before the source writer committed"); + } + // Activity snapshots are otherwise frozen for this blocker transaction. + f.dsl.fetch("SELECT pg_stat_clear_snapshot()"); var blocked = f.dsl.fetchOne( "SELECT pid FROM pg_stat_activity WHERE datname = current_database()" diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java new file mode 100644 index 0000000000..375ee54ec9 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java @@ -0,0 +1,292 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Composition ordering units with stipulated peer context and mocked owner evidence/producer. These + * fixture values are not genuine cross-owner mTLS, creator or PostgreSQL proof. + */ +class AccountSelectedDraftPublicationOrderServiceTest { + private static final String COMPACT_JWT = "original-compact-creator-jwt"; + private final AuthoredDraftPublishSelectionReadClient client = + mock(AuthoredDraftPublishSelectionReadClient.class); + private final AccountPublicationAuthorizationService owner = + mock(AccountPublicationAuthorizationService.class); + private final CapturedEnvironmentBoundary environment = mock(CapturedEnvironmentBoundary.class); + private final AccountSelectedDraftPublicationOrderService service = + new AccountSelectedDraftPublicationOrderService(client, owner, "test"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void deniesMissingWrongServiceAndCrossNamespacePeerBeforeTransportOrOwner() { + // Null lookup also proves authentication precedes carrier inspection. + assertCode(Status.Code.UNAUTHENTICATED, () -> service.authorize(null, null, null)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", workload, () -> service.authorize(null, null, null))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "game-design-service", () -> service.authorize(null, null, null))); + verifyNoInteractions(client, owner); + } + + @Test + void rejectsActualTransactionAndSynchronizationBeforeRemoteRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + verifyNoInteractions(client, owner); + } + + @Test + void exactReadCompletesBeforeOwnerReceivesUnchangedCreatorJwtEnvironmentAndSelection() { + var lookup = selection(); + var result = mock(AccountPublicationAuthorizationBinding.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var request = + invocation.getArgument( + 0, AuthoredDraftPublishSelectionReadEvidence.Request.class); + assertThat(request.targetNamespace()).isEqualTo("test"); + assertThat(request.originalSelection()).containsExactly(lookup.canonicalBytes()); + assertThat(request.selectionDigest()).isEqualTo(lookup.digest()); + return fixtureEvidence(request); + }); + when(owner.authorize(eq(COMPACT_JWT), eq(lookup), same(environment))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return result; + }); + assertThat(authorized(() -> service.authorize(COMPACT_JWT, lookup, environment))) + .isSameAs(result); + var request = ArgumentCaptor.forClass(AuthoredDraftPublishSelectionReadEvidence.Request.class); + var order = inOrder(client, owner); + order.verify(client).read(request.capture()); + order.verify(owner).authorize(eq(COMPACT_JWT), eq(lookup), same(environment)); + order.verifyNoMoreInteractions(); + assertThat(request.getValue().binding()).isEqualTo(lookup); + } + + @Test + void missingOrSubstitutedReadbackNeverInvokesAccountOwner() { + when(client.read(any())).thenReturn(null); + assertThatThrownBy( + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))) + .isInstanceOf(IllegalStateException.class); + for (String changed : List.of("namespace", "readIdentity", "selection")) { + doAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, AuthoredDraftPublishSelectionReadEvidence.Request.class); + if ("selection".equals(changed)) { + var original = request.binding(); + var intent = original.intent(); + var replaced = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + "changed notes", + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()), + original.target(), + original.selectedCommit(), + new VisibilityFence( + original.target(), + original.fenceRequestId(), + original.fenceCommitId(), + original.fenceInputDigest(), + original.fenceResultVectorJson(), + OffsetDateTime.parse(original.fenceCreatedAt()))); + return fixtureEvidence( + new AuthoredDraftPublishSelectionReadEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + request.readRequestId(), + replaced.canonicalBytes(), + replaced.digest())); + } + return fixtureEvidence( + new AuthoredDraftPublishSelectionReadEvidence.Request( + request.schemaVersion(), + "namespace".equals(changed) ? "other" : request.targetNamespace(), + "readIdentity".equals(changed) + ? UUID.randomUUID() + : request.readRequestId(), + request.originalSelection(), + request.selectionDigest())); + }) + .when(client) + .read(any()); + assertThatThrownBy( + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from the exact publication order request"); + } + verifyNoInteractions(owner); + } + + @Test + void unavailableOrDeniedSelectionReadNeverInvokesOwner() { + for (Status failure : List.of(Status.UNAVAILABLE, Status.NOT_FOUND, Status.PERMISSION_DENIED)) { + doThrow(failure.asRuntimeException()).when(client).read(any()); + assertCode( + failure.getCode(), + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + } + verifyNoInteractions(owner); + } + + @Test + void lowerLevelCreatorDenialPropagatesAfterExactOwnerRead() { + when(client.read(any())).thenAnswer(invocation -> fixtureEvidence(invocation.getArgument(0))); + when(owner.authorize(any(), any(), any())) + .thenThrow(Status.PERMISSION_DENIED.asRuntimeException()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + var order = inOrder(client, owner); + order.verify(client).read(any()); + order.verify(owner).authorize(eq(COMPACT_JWT), eq(selection()), same(environment)); + } + + private static AuthoredDraftPublishSelectionReadEvidence fixtureEvidence( + AuthoredDraftPublishSelectionReadEvidence.Request request) { + var evidence = mock(AuthoredDraftPublishSelectionReadEvidence.class); + when(evidence.request()).thenReturn(request); + return evidence; + } + + private static T authorized(Supplier action) { + return asPeer("test", "game-design-service", action); + } + + private static T asPeer(String namespace, String workload, Supplier action) { + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static AuthoredDraftPublishSelectionBinding selection() { + UUID tenant = uuid("22222222-2222-4222-8222-222222222222"); + UUID version = uuid("33333333-3333-4333-8333-333333333333"); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "5", + "test selection", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return selected; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClient.java new file mode 100644 index 0000000000..3318ee52dd --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClient.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.common.publication; + +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.GameDesignSelectedDraftPublicationReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for the exact immutable Game Design selection read. */ +public final class AuthoredDraftPublishSelectionReadClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AuthoredDraftPublishSelectionReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AuthoredDraftPublishSelectionReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException( + "Game Design selected Draft publication read client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Game Design selected Draft publication read stub unavailable"); + } + initialized = true; + } + + /** + * Returns SELECTED evidence only after exact Game Design server identity and response + * verification. + */ + public AuthoredDraftPublishSelectionReadEvidence read( + AuthoredDraftPublishSelectionReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Game Design selected Draft publication read requires no owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Design selected Draft publication read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedDraftPublication( + AuthoredDraftPublishSelectionReadGrpcCodec.toRequest(request)); + try { + return AuthoredDraftPublishSelectionReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid selected Draft publication evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignSelectedDraftPublicationReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Design selected Draft publication read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Game Design selected Draft publication read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Design selected Draft publication read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Design selected Draft publication read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Design selected Draft publication read " + label + " must be a file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Design selected Draft publication read " + + label + + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadEvidence.java new file mode 100644 index 0000000000..c23a926595 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadEvidence.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.common.publication; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Exact immutable SELECTED read returned by the authenticated Game Design client. This attests + * reserved selection only, not current DRAFT state, actor authority, source holds, World freeze, + * release/settlement, or runtime admission. Structurally valid bytes alone are not owner evidence. + */ +public final class AuthoredDraftPublishSelectionReadEvidence { + private final Request request; + + AuthoredDraftPublishSelectionReadEvidence(Request request) { + this.request = Objects.requireNonNull(request, "request"); + } + + public Request request() { + return request; + } + + /** Complete original immutable selection plus read correlation identity and digest. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] originalSelection, + String selectionDigest) { + public static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported selected Draft publication read schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace is required"); + } + if (readRequestId == null || NIL_UUID.equals(readRequestId)) { + throw new IllegalArgumentException("Non-nil read request identity is required"); + } + if (originalSelection == null || originalSelection.length == 0 || selectionDigest == null) { + throw new IllegalArgumentException("Complete original selection and digest are required"); + } + originalSelection = originalSelection.clone(); + AuthoredDraftPublishSelectionBinding binding = decode(originalSelection, selectionDigest); + if (!Arrays.equals(originalSelection, binding.canonicalBytes())) { + throw new IllegalArgumentException("Exact canonical original selection bytes are required"); + } + } + + public static Request create( + String targetNamespace, AuthoredDraftPublishSelectionBinding binding) { + Objects.requireNonNull(binding, "binding"); + return new Request( + SCHEMA_VERSION, + targetNamespace, + UUID.randomUUID(), + binding.canonicalBytes(), + binding.digest()); + } + + @Override + public byte[] originalSelection() { + return originalSelection.clone(); + } + + public AuthoredDraftPublishSelectionBinding binding() { + return decode(originalSelection, selectionDigest); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals(originalSelection, that.originalSelection) + && selectionDigest.equals(that.selectionDigest); + } + + @Override + public int hashCode() { + return 31 * Objects.hash(schemaVersion, targetNamespace, readRequestId, selectionDigest) + + Arrays.hashCode(originalSelection); + } + + private static AuthoredDraftPublishSelectionBinding decode(byte[] bytes, String digest) { + try { + return AuthoredDraftPublishSelectionBinding.fromStored( + new String(bytes, StandardCharsets.UTF_8), digest); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Exact canonical original selection and digest required", invalid); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodec.java new file mode 100644 index 0000000000..16fa458d1f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodec.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse; +import net.firedevops.firemud.gamedesign.v1.SelectedDraftPublicationStatus; + +/** + * Closed wire mapping and exact request-echo validation for the selected Draft publication read. + */ +public final class AuthoredDraftPublishSelectionReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AuthoredDraftPublishSelectionReadGrpcCodec() {} + + public static ReadSelectedDraftPublicationRequest toRequest( + AuthoredDraftPublishSelectionReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadSelectedDraftPublicationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .setSelectionDigest(request.selectionDigest()) + .build(); + } + + /** Decode only after Game Design authenticates its exact same-namespace Account or World peer. */ + public static AuthoredDraftPublishSelectionReadEvidence.Request fromRequest( + ReadSelectedDraftPublicationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadSelectedDraftPublicationRequest"); + try { + return new AuthoredDraftPublishSelectionReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalUuid(request.getReadRequestId()), + request.getOriginalSelection().toByteArray(), + request.getSelectionDigest()); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Selected Draft publication read request is invalid", invalid); + } + } + + /** Game Design may emit SELECTED only after reading the exact immutable retained selection. */ + public static ReadSelectedDraftPublicationResponse toSelectedResponse( + AuthoredDraftPublishSelectionReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadSelectedDraftPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .setSelectionDigest(request.selectionDigest()) + .setStatus(SelectedDraftPublicationStatus.SELECTED_DRAFT_PUBLICATION_STATUS_SELECTED) + .build(); + } + + /** Validate a positive response; all other owner states are non-OK RPC failures. */ + static AuthoredDraftPublishSelectionReadEvidence fromResponse( + AuthoredDraftPublishSelectionReadEvidence.Request request, + ReadSelectedDraftPublicationResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadSelectedDraftPublicationResponse"); + if (response.getSchemaVersion() != request.schemaVersion() + || !response.getTargetNamespace().equals(request.targetNamespace()) + || !response.getReadRequestId().equals(request.readRequestId().toString()) + || !Arrays.equals( + response.getOriginalSelection().toByteArray(), request.originalSelection()) + || !response.getSelectionDigest().equals(request.selectionDigest())) { + throw new IllegalArgumentException( + "Game Design response changed the exact selected Draft publication read"); + } + if (response.getStatus() + != SelectedDraftPublicationStatus.SELECTED_DRAFT_PUBLICATION_STATUS_SELECTED) { + throw new IllegalArgumentException( + "Game Design did not confirm the exact selected Draft publication"); + } + return new AuthoredDraftPublishSelectionReadEvidence(request); + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalUuid(String value) { + if (value == null) throw new IllegalArgumentException("Canonical read request UUID required"); + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil read request UUID required"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Canonical non-nil read request UUID required", invalid); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadClient.java new file mode 100644 index 0000000000..08e350ef57 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadClient.java @@ -0,0 +1,161 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for the exact original Game Design terminal read. */ +public final class GameDesignPublicationTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameDesignPublicationTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameDesignPublicationTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Game Design publication terminal read client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Game Design publication terminal read stub unavailable"); + } + initialized = true; + } + + /** + * Returns complete original terminal evidence only after exact Game Design server identity and + * response verification. + */ + public GameDesignPublicationTerminalReadEvidence read( + GameDesignPublicationTerminalReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Game Design publication terminal read requires no owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Design publication terminal read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readPublicationTerminal(GameDesignPublicationTerminalReadGrpcCodec.toRequest(request)); + try { + return GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid publication terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignPublicationTerminalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Design publication terminal read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Game Design publication terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Design publication terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Design publication terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Design publication terminal read " + label + " must be a file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Design publication terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidence.java new file mode 100644 index 0000000000..34dbc1f139 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidence.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.common.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Complete original terminal evidence returned by the strict authenticated Game Design client. + * Structural decoding alone is not owner authentication. Consumers still own settlement, + * applicability and admission decisions; this value does not perform those decisions. + */ +public final class GameDesignPublicationTerminalReadEvidence { + private final Request request; + private final GameDesignPublicationTerminalEvidence terminal; + + GameDesignPublicationTerminalReadEvidence(Request request, byte[] terminalBytes) { + this.request = Objects.requireNonNull(request, "request"); + this.terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + if (!Arrays.equals(request.originalOperation(), terminal.operationBytes()) + || !Arrays.equals(terminalBytes, terminal.canonicalBytes())) { + throw new IllegalArgumentException( + "Terminal evidence differs from the exact original operation"); + } + } + + public Request request() { + return request; + } + + public GameDesignPublicationTerminalEvidence terminalEvidence() { + return terminal; + } + + /** Complete canonical original operation and independent read correlation. */ + public record Request( + int schemaVersion, String targetNamespace, UUID readRequestId, byte[] originalOperation) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported publication terminal read schema"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + if (readRequestId == null || readRequestId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Non-nil read request identity required"); + } + if (originalOperation == null || originalOperation.length == 0) { + throw new IllegalArgumentException("Complete original publication operation required"); + } + originalOperation = originalOperation.clone(); + GameDesignPublicationOperationBinding operation; + try { + operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Complete canonical original operation required", malformed); + } + if (!Arrays.equals(originalOperation, operation.canonicalBytes())) { + throw new IllegalArgumentException("Exact canonical original operation required"); + } + } + + public static Request create( + String targetNamespace, GameDesignPublicationOperationBinding operation) { + Objects.requireNonNull(operation, "operation"); + return new Request( + SCHEMA_VERSION, targetNamespace, UUID.randomUUID(), operation.canonicalBytes()); + } + + @Override + public byte[] originalOperation() { + return originalOperation.clone(); + } + + public GameDesignPublicationOperationBinding operation() { + return GameDesignPublicationOperationBinding.fromStored(originalOperation); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals(originalOperation, that.originalOperation); + } + + @Override + public int hashCode() { + return 31 * Objects.hash(schemaVersion, targetNamespace, readRequestId) + + Arrays.hashCode(originalOperation); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..20eb3fb2d2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodec.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalResponse; + +/** Closed version-one transport; structural validation never authenticates an owner. */ +public final class GameDesignPublicationTerminalReadGrpcCodec { + private GameDesignPublicationTerminalReadGrpcCodec() {} + + public static ReadPublicationTerminalRequest toRequest( + GameDesignPublicationTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadPublicationTerminalRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .build(); + } + + /** Receiver must authenticate its exact same-namespace Account or World peer before decoding. */ + public static GameDesignPublicationTerminalReadEvidence.Request fromRequest( + ReadPublicationTerminalRequest request) { + Objects.requireNonNull(request, "request"); + noUnknownFields(request); + return new GameDesignPublicationTerminalReadEvidence.Request( + request.getSchemaVersion(), request.getTargetNamespace(), + canonicalUuid(request.getReadRequestId()), request.getOriginalOperation().toByteArray()); + } + + /** Emit only an exact complete original terminal returned by the actual owner snapshot read. */ + public static ReadPublicationTerminalResponse toResponse( + GameDesignPublicationTerminalReadEvidence.Request request, + GameDesignPublicationTerminalEvidence terminal) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(terminal, "terminal"); + requireExactTerminal(request, terminal.canonicalBytes()); + return ReadPublicationTerminalResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setTerminalEvidence(ByteString.copyFrom(terminal.canonicalBytes())) + .build(); + } + + static GameDesignPublicationTerminalReadEvidence fromResponse( + GameDesignPublicationTerminalReadEvidence.Request request, + ReadPublicationTerminalResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + noUnknownFields(response); + if (response.getSchemaVersion() != request.schemaVersion() + || !request.targetNamespace().equals(response.getTargetNamespace()) + || !request.readRequestId().toString().equals(response.getReadRequestId()) + || !Arrays.equals( + request.originalOperation(), response.getOriginalOperation().toByteArray())) { + throw new IllegalArgumentException("Game Design changed the exact publication terminal read"); + } + byte[] originalTerminal = response.getTerminalEvidence().toByteArray(); + requireExactTerminal(request, originalTerminal); + return new GameDesignPublicationTerminalReadEvidence(request, originalTerminal); + } + + private static void requireExactTerminal( + GameDesignPublicationTerminalReadEvidence.Request request, byte[] bytes) { + final GameDesignPublicationTerminalEvidence terminal; + try { + terminal = GameDesignPublicationTerminalEvidence.fromStored(bytes); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Complete canonical original terminal evidence required", malformed); + } + if (!Arrays.equals(request.originalOperation(), terminal.operationBytes()) + || !Arrays.equals(bytes, terminal.canonicalBytes())) { + throw new IllegalArgumentException("Terminal evidence differs from the original operation"); + } + } + + private static void noUnknownFields(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Publication terminal read contains unsupported fields"); + } + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil read UUID required"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException("Canonical non-nil read UUID required", malformed); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClientTest.java new file mode 100644 index 0000000000..de1e2bf271 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClientTest.java @@ -0,0 +1,230 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.AbstractStub; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +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.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedDraftPublicationReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AuthoredDraftPublishSelectionReadClientTest { + @Test + void requiresReadableFileBackedMaterialAndCanonicalNamespace(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + for (String badPath : + java.util.List.of( + "", + "classpath:client.crt", + directory.resolve("absent.crt").toString(), + directory.toString())) { + var invalid = tls(directory); + invalid.setCertChain(badPath); + assertThatThrownBy( + () -> + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), invalid, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var noKey = tls(directory); + noKey.setPrivateKey(null); + assertThatThrownBy( + () -> + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), noKey, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + var noCa = tls(directory); + noCa.setCaCert(null); + assertThatThrownBy( + () -> + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), noCa, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + var valid = tls(directory); + assertThatThrownBy( + () -> + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), valid, factory, "Test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void closedClientCannotInitializeOrRead(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var client = + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + client.close(); + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + assertThatThrownBy(() -> client.read(AuthoredDraftPublishSelectionReadGrpcCodecTest.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(factory); + } + + @Test + void rejectsPlaintextWrongNamespaceAndUninitializedCallsBeforeTransport(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var client = + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + try { + var request = AuthoredDraftPublishSelectionReadGrpcCodecTest.request(); + assertThatThrownBy( + () -> + client.read( + new AuthoredDraftPublishSelectionReadEvidence.Request( + request.schemaVersion(), + "other", + request.readRequestId(), + request.originalSelection(), + request.selectionDigest()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(factory); + } finally { + client.close(); + } + } + + @Test + void configuresExactGameDesignPeerAndReturnsOnlyExactSelectedResponse(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("design.internal:6565"); + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(factory.buildChannel( + eq("design.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new AuthoredDraftPublishSelectionReadClient(endpoints, tls(directory), factory, "test"); + try { + client.init(); + AbstractStub initialized = initializedStub(client); + assertThat(initialized.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(initialized.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/game-design-service"); + + var stub = + mock( + GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + setStub(client, stub); + var request = AuthoredDraftPublishSelectionReadGrpcCodecTest.request(); + var held = AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(request); + when(stub.readSelectedDraftPublication(any())).thenReturn(held); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(stub); + + assertThat(client.read(request).request()).isEqualTo(request); + verify(stub).readSelectedDraftPublication(any()); + + when(stub.readSelectedDraftPublication(any())) + .thenReturn(held.toBuilder().setTargetNamespace("other").build()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid selected Draft publication evidence"); + when(stub.readSelectedDraftPublication(any())) + .thenReturn(ReadSelectedDraftPublicationResponse.getDefaultInstance()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid selected Draft publication evidence"); + when(stub.readSelectedDraftPublication(any())) + .thenThrow(Status.UNAVAILABLE.withDescription("offline").asRuntimeException()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + } finally { + client.close(); + } + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return tls; + } + + private static AbstractStub initializedStub(AuthoredDraftPublishSelectionReadClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + private static void setStub( + AuthoredDraftPublishSelectionReadClient client, + GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceBlockingStub + stub) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodecTest.java new file mode 100644 index 0000000000..adcbb6d0b5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodecTest.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse; +import net.firedevops.firemud.gamedesign.v1.SelectedDraftPublicationStatus; +import org.junit.jupiter.api.Test; + +class AuthoredDraftPublishSelectionReadGrpcCodecTest { + @Test + void rejectsNilNoncanonicalIdentityAndMalformedOrNoncanonicalSelectionBytes() { + var request = AuthoredDraftPublishSelectionReadGrpcCodec.toRequest(request()); + for (String invalidId : + List.of( + "00000000-0000-0000-0000-000000000000", + "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", + "1-1-1-1-1")) { + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setReadRequestId(invalidId).build())) + .isInstanceOf(IllegalArgumentException.class); + } + String canonical = binding().canonicalJson(); + for (byte[] invalidBytes : + List.of( + new byte[0], + new byte[] {(byte) 0xff}, + (" " + canonical).getBytes(StandardCharsets.UTF_8), + (canonical.substring(0, canonical.length() - 1) + ",\"unknown\":\"value\"}") + .getBytes(StandardCharsets.UTF_8))) { + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder() + .setOriginalSelection(ByteString.copyFrom(invalidBytes)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + for (String namespace : List.of("", "Test", "test.other")) { + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setTargetNamespace(namespace).build())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void retainsDefensiveCopiesOfTheExactOriginalBytes() { + var binding = binding(); + byte[] original = binding.canonicalBytes(); + var request = + new AuthoredDraftPublishSelectionReadEvidence.Request( + 1, "test", UUID.randomUUID(), original, binding.digest()); + original[0] = 0; + byte[] returned = request.originalSelection(); + returned[0] = 0; + assertThat(request.originalSelection()).containsExactly(binding.canonicalBytes()); + assertThat(request.binding()).isEqualTo(binding); + } + + @Test + void mapsCompleteCanonicalBindingDigestAndStableReadIdentity() { + var request = request(); + + var decoded = + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + AuthoredDraftPublishSelectionReadGrpcCodec.toRequest(request)); + var evidence = + AuthoredDraftPublishSelectionReadGrpcCodec.fromResponse( + request, AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(request)); + + assertThat(decoded).isEqualTo(request); + assertThat(evidence.request()).isEqualTo(request); + assertThat(evidence.request().binding().canonicalBytes()) + .containsExactly(request.originalSelection()); + assertThat(evidence.request().binding().intent()).isEqualTo(request.binding().intent()); + } + + @Test + void rejectsMalformedRequestsUnknownFieldsAndChangedBindingDigest() { + var request = AuthoredDraftPublishSelectionReadGrpcCodec.toRequest(request()); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setReadRequestId("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setSchemaVersion(2).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setSelectionDigest("sha256:" + "0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Selected Draft publication read request is invalid") + .hasCauseInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsResponseSubstitutionUnknownFieldsAndNonSelectedStatuses() { + var request = request(); + var held = AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + for (ReadSelectedDraftPublicationResponse changed : + List.of( + held.toBuilder().setSchemaVersion(2).build(), + held.toBuilder().setTargetNamespace("other").build(), + held.toBuilder().setReadRequestId(UUID.randomUUID().toString()).build(), + held.toBuilder().setOriginalSelection(ByteString.copyFrom(new byte[] {1})).build(), + held.toBuilder().setSelectionDigest("sha256:" + "0".repeat(64)).build(), + held.toBuilder() + .setStatus( + SelectedDraftPublicationStatus.SELECTED_DRAFT_PUBLICATION_STATUS_UNSPECIFIED) + .build(), + held.toBuilder().setStatusValue(99).build(), + held.toBuilder().setUnknownFields(unknown).build())) { + assertThatThrownBy( + () -> AuthoredDraftPublishSelectionReadGrpcCodec.fromResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + static AuthoredDraftPublishSelectionReadEvidence.Request request() { + var binding = binding(); + return AuthoredDraftPublishSelectionReadEvidence.Request.create("test", binding); + } + + static AuthoredDraftPublishSelectionBinding binding() { + UUID tenant = uuid("22222222-2222-4222-8222-222222222222"); + UUID version = uuid("33333333-3333-4333-8333-333333333333"); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "5", + "test selection", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return selected; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadClientTest.java new file mode 100644 index 0000000000..ad0385cff9 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadClientTest.java @@ -0,0 +1,235 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.AbstractStub; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +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.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalResponse; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameDesignPublicationTerminalReadClientTest { + @Test + void requiresReadableFileBackedMaterialAndCanonicalNamespace(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + for (String badPath : + java.util.List.of( + "", + "classpath:client.crt", + directory.resolve("absent.crt").toString(), + directory.toString())) { + var invalid = tls(directory); + invalid.setCertChain(badPath); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalReadClient( + new ServiceEndpointsProperties(), invalid, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var noKey = tls(directory); + noKey.setPrivateKey(null); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalReadClient( + new ServiceEndpointsProperties(), noKey, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + var noCa = tls(directory); + noCa.setCaCert(null); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalReadClient( + new ServiceEndpointsProperties(), noCa, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + var valid = tls(directory); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalReadClient( + new ServiceEndpointsProperties(), valid, factory, "Test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void closedClientCannotInitializeOrRead(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var client = + new GameDesignPublicationTerminalReadClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + client.close(); + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + assertThatThrownBy(() -> client.read(GameDesignPublicationTerminalReadGrpcCodecTest.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(factory); + } + + @Test + void rejectsPlaintextWrongNamespaceAndUninitializedCallsBeforeTransport(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalReadClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var client = + new GameDesignPublicationTerminalReadClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + try { + var request = GameDesignPublicationTerminalReadGrpcCodecTest.request(); + assertThatThrownBy( + () -> + client.read( + new GameDesignPublicationTerminalReadEvidence.Request( + request.schemaVersion(), + "other", + request.readRequestId(), + request.originalOperation()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(factory); + } finally { + client.close(); + } + } + + @Test + void configuresExactGameDesignPeerAndReturnsOnlyCompleteOriginalTerminal(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("design.internal:6565"); + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(factory.buildChannel( + eq("design.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new GameDesignPublicationTerminalReadClient(endpoints, tls(directory), factory, "test"); + try { + client.init(); + AbstractStub initialized = initializedStub(client); + assertThat(initialized.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(initialized.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/game-design-service"); + + var stub = + mock( + GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + setStub(client, stub); + var request = GameDesignPublicationTerminalReadGrpcCodecTest.request(); + var held = + GameDesignPublicationTerminalReadGrpcCodec.toResponse( + request, + GameDesignPublicationTerminalReadGrpcCodecTest.terminal( + request.operation(), + net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence + .Outcome.NO_PUBLICATION)); + when(stub.readPublicationTerminal(any())).thenReturn(held); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(stub); + + assertThat(client.read(request).request()).isEqualTo(request); + verify(stub).readPublicationTerminal(any()); + + when(stub.readPublicationTerminal(any())) + .thenReturn(held.toBuilder().setTargetNamespace("other").build()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid publication terminal evidence"); + when(stub.readPublicationTerminal(any())) + .thenReturn(ReadPublicationTerminalResponse.getDefaultInstance()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid publication terminal evidence"); + when(stub.readPublicationTerminal(any())) + .thenThrow(Status.UNAVAILABLE.withDescription("offline").asRuntimeException()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + } finally { + client.close(); + } + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return tls; + } + + private static AbstractStub initializedStub(GameDesignPublicationTerminalReadClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + private static void setStub( + GameDesignPublicationTerminalReadClient client, + GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub + stub) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidenceTest.java new file mode 100644 index 0000000000..046da4db0d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidenceTest.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.common.publication; + +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.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import org.junit.jupiter.api.Test; + +class GameDesignPublicationTerminalReadEvidenceTest { + @Test + void requestAndTerminalRetainDefensiveExactOriginalBytes() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + byte[] bytes = operation.canonicalBytes(); + var request = + new GameDesignPublicationTerminalReadEvidence.Request(1, "test", UUID.randomUUID(), bytes); + bytes[0] = 0; + request.originalOperation()[0] = 0; + assertThat(request.originalOperation()).containsExactly(operation.canonicalBytes()); + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.NO_PUBLICATION); + byte[] terminalBytes = terminal.canonicalBytes(); + var evidence = new GameDesignPublicationTerminalReadEvidence(request, terminalBytes); + terminalBytes[0] = 0; + evidence.terminalEvidence().canonicalBytes()[0] = 0; + assertThat(evidence.terminalEvidence().canonicalBytes()) + .containsExactly(terminal.canonicalBytes()); + } + + @Test + void requestRejectsUnsupportedVersionInvalidNamespaceNilIdentityAndAbsentOperation() + throws Exception { + byte[] bytes = GameDesignPublicationTerminalReadGrpcCodecTest.operation().canonicalBytes(); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalReadEvidence.Request( + 2, "test", UUID.randomUUID(), bytes)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalReadEvidence.Request( + 1, "Test", UUID.randomUUID(), bytes)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalReadEvidence.Request( + 1, "test", new UUID(0L, 0L), bytes)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalReadEvidence.Request( + 1, "test", UUID.randomUUID(), null)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..5d1f0dced8 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java @@ -0,0 +1,263 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodecTest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalRequest; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +/** + * Structural transport units; the original Account/World inputs below are test-only stipulations. + */ +class GameDesignPublicationTerminalReadGrpcCodecTest { + @Test + void preservesCompleteOriginalTerminalBytesAndExactRetryForBothOutcomes() throws Exception { + var request = request(); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request))) + .isEqualTo(request); + for (Outcome outcome : Outcome.values()) { + var terminal = terminal(request.operation(), outcome); + var response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, terminal); + var first = GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response); + var retry = GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response); + assertThat(first.request()).isEqualTo(request); + assertThat(first.terminalEvidence().outcome()).isEqualTo(outcome); + assertThat(first.terminalEvidence().canonicalBytes()) + .containsExactly(terminal.canonicalBytes()); + assertThat(retry.terminalEvidence().canonicalBytes()) + .containsExactly(terminal.canonicalBytes()); + } + } + + @Test + void rejectsUnknownUnsupportedMalformedAndNoncanonicalRequests() throws Exception { + var wire = GameDesignPublicationTerminalReadGrpcCodec.toRequest(request()); + for (ReadPublicationTerminalRequest invalid : + List.of( + wire.toBuilder().setUnknownFields(unknown()).build(), + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setReadRequestId("00000000-0000-0000-0000-000000000000").build(), + wire.toBuilder().setReadRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA").build(), + wire.toBuilder().setReadRequestId("1-1-1-1-1").build(), + wire.toBuilder().setOriginalOperation(ByteString.EMPTY).build(), + wire.toBuilder().setOriginalOperation(ByteString.copyFrom(new byte[] {1})).build(), + wire.toBuilder() + .setOriginalOperation( + wire.getOriginalOperation().concat(ByteString.copyFrom(new byte[] {0}))) + .build())) { + assertThatThrownBy(() -> GameDesignPublicationTerminalReadGrpcCodec.fromRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsEveryEchoSubstitutionUnknownAndMissingMalformedOrChangedTerminal() throws Exception { + var request = request(); + var terminal = terminal(request.operation(), Outcome.NO_PUBLICATION); + var response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, terminal); + var changed = terminal(operation(), Outcome.NO_PUBLICATION); + for (var invalid : + List.of( + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setReadRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder() + .setOriginalOperation(ByteString.copyFrom(changed.operationBytes())) + .build(), + response.toBuilder().setUnknownFields(unknown()).build(), + response.toBuilder().clearTerminalEvidence().build(), + response.toBuilder().setTerminalEvidence(ByteString.copyFrom(new byte[] {1})).build(), + response.toBuilder() + .setTerminalEvidence(ByteString.copyFrom(changed.canonicalBytes())) + .build(), + response.toBuilder() + .setTerminalEvidence( + response.getTerminalEvidence().concat(ByteString.copyFrom(new byte[] {0}))) + .build())) { + assertThatThrownBy( + () -> GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + static GameDesignPublicationTerminalReadEvidence.Request request() throws Exception { + return GameDesignPublicationTerminalReadEvidence.Request.create("test", operation()); + } + + static GameDesignPublicationOperationBinding operation() throws Exception { + var upstream = + WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); + var applied = + WorldDraftTerminalReadGrpcCodecTest.committedFreshGraphReadbackForStartLocationEvidenceTest( + upstream); + var original = upstream.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var target = draft.target(); + var intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publication-request", + "5", + "fixture", + draft.requestId(), + draft.commitId(), + draft.digest()); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + intent, + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + // Distinct publication-order source stipulation, not the upstream Draft COMMIT_ORDER vector. + // This structural fixture proves neither current actor authority nor an actual source hold. + var publicationSources = + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + "stipulated-publication-account-source".getBytes(StandardCharsets.UTF_8))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selection), + publicationSources); + var tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList(); + String workflow = + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity(); + var result = JsonMapper.builder().build().readTree(applied.result()); + var appliedOperation = + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.FrameReader( + Base64.getDecoder().decode(result.get("operationBytesBase64").textValue())); + // Retain the actual intake identity at frame 13 of the existing APPLIED operation. + appliedOperation.expect("world-draft-terminal-operation/v1"); + for (int frame = 1; frame < 13; frame++) { + appliedOperation.bytes(); + } + UUID intakeRequestId = UUID.fromString(appliedOperation.text()); + var worldRequest = + new WorldPublishedStartLocationEvidence.Request( + "test", + target.canonicalTenantId(), + target.canonicalVersionId(), + intakeRequestId, + UUID.randomUUID(), + intent.publishRequestId(), + selection.digest().substring(7), + 5L, + workflow, + draft.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var world = + new WorldPublishedStartLocationEvidence( + worldRequest, + Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()), + applied.fullBinding(), + applied.result()); + return new GameDesignPublicationOperationBinding(account, world); + } + + static GameDesignPublicationTerminalEvidence terminal( + GameDesignPublicationOperationBinding operation, Outcome outcome) { + if (outcome == Outcome.NO_PUBLICATION) { + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), outcome, null, null); + } + var selection = operation.account().input().selection(); + var world = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(selection.target().gameDesignVersionRowId()), + null, + world.appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) ? world.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, + null, + null)) + .toList(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + "fixture-bundle", + 1, + "v2", + world.publishWorkflowId(), + "sha256:" + "a".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of(), + "generation-1", + operation.world()); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), outcome, release, 6L); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java new file mode 100644 index 0000000000..1bd2aec08e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcService.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.gamedesign.draft; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedDraftPublicationReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse; + +/** + * Standalone, unregistered immutable selection owner read. Does not inspect mutable Version state + * or establish actor authorization, source holds, World freeze, release, or runtime admission. + */ +public final class GameDesignSelectedDraftPublicationReadGrpcService + extends GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceImplBase { + private final AuthoredDraftPublishSelectionRepository repository; + private final String trustedNamespace; + + public GameDesignSelectedDraftPublicationReadGrpcService( + AuthoredDraftPublishSelectionRepository repository, String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readSelectedDraftPublication( + ReadSelectedDraftPublicationRequest request, + StreamObserver observer) { + try { + requirePeer(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final AuthoredDraftPublishSelectionReadEvidence.Request decoded; + try { + decoded = AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical selected Draft publication read required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Selection namespace differs from peer") + .asRuntimeException()); + return; + } + final ReadSelectedDraftPublicationResponse response; + try { + var intent = decoded.binding().intent(); + var retained = + repository.read( + intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId()); + if (retained.isEmpty()) { + throw Status.NOT_FOUND + .withDescription("Exact selected Draft publication unavailable") + .asRuntimeException(); + } + var selection = retained.orElseThrow().selection(); + if (!Arrays.equals(selection.canonicalBytes(), decoded.originalSelection()) + || !selection.digest().equals(decoded.selectionDigest())) { + throw Status.FAILED_PRECONDITION + .withDescription("Retained selection differs from request") + .asRuntimeException(); + } + response = AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(decoded); + } catch (StatusRuntimeException failure) { + observer.onError( + Status.fromCode(Status.fromThrowable(failure).getCode()) + .withDescription("Selected Draft publication read denied or unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Design selection storage unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + trustedNamespace + "/sa/account-service").equals(peer.uri()) + && !("spiffe://firemud/ns/" + trustedNamespace + "/sa/world-management-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Account or World Management workload required") + .asRuntimeException(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java new file mode 100644 index 0000000000..97f0e5c790 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcService.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalResponse; + +/** Standalone, unregistered transport over the actual complete terminal owner snapshot read. */ +public final class GameDesignPublicationTerminalReadGrpcService + extends GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceImplBase { + private final GameDesignPublicationTerminalReadService owner; + private final String workloadNamespace; + + public GameDesignPublicationTerminalReadGrpcService( + GameDesignPublicationTerminalReadService owner, String workloadNamespace) { + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readPublicationTerminal( + ReadPublicationTerminalRequest request, + StreamObserver observer) { + try { + requirePeer(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final GameDesignPublicationTerminalReadEvidence.Request decoded; + try { + decoded = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical complete publication terminal read required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Publication terminal namespace differs from peer") + .asRuntimeException()); + return; + } + final ReadPublicationTerminalResponse response; + try { + var terminal = owner.read(decoded.targetNamespace(), decoded.originalOperation()); + response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(decoded, terminal); + } catch (StatusRuntimeException failure) { + observer.onError( + Status.fromCode(failure.getStatus().getCode()) + .withDescription("Publication terminal owner read denied or unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Complete publication terminal evidence unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service").equals(peer.uri()) + && !("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Account or World Management workload required") + .asRuntimeException(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadService.java new file mode 100644 index 0000000000..6f60279cdb --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadService.java @@ -0,0 +1,130 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Standalone, unregistered read of complete original publication terminal evidence. This reads + * historical owner truth without releasing Account sources, completing World operations, or + * granting current authority or runtime admission. + */ +public final class GameDesignPublicationTerminalReadService { + private final GameDesignPublicationOperationRepository repository; + private final TransactionTemplate snapshot; + private final String workloadNamespace; + + public GameDesignPublicationTerminalReadService( + GameDesignPublicationOperationRepository repository, + PlatformTransactionManager transactions, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + snapshot = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + snapshot.setName("game-design-publication-terminal-read"); + snapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + snapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + snapshot.setReadOnly(true); + } + + /** Complete original operation bytes are lookup identity, never caller authority. */ + public GameDesignPublicationTerminalEvidence read( + String targetNamespace, byte[] originalOperationBytes) { + requirePeer(); + if (!workloadNamespace.equals(targetNamespace)) { + throw Status.PERMISSION_DENIED + .withDescription("Publication read namespace differs from peer") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent publication terminal snapshot required") + .asRuntimeException(); + } + final GameDesignPublicationOperationBinding requested; + try { + requested = + GameDesignPublicationOperationBinding.fromStored( + Objects.requireNonNull(originalOperationBytes, "originalOperationBytes")); + } catch (RuntimeException malformed) { + throw Status.INVALID_ARGUMENT + .withDescription("Canonical complete publication operation required") + .asRuntimeException(); + } + if (!workloadNamespace.equals(requested.world().request().targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("Original publication namespace differs") + .asRuntimeException(); + } + try { + return Objects.requireNonNull( + snapshot.execute( + status -> { + // The binding validates this workflow against the canonical tenant and original + // request. + var stored = + repository + .read(requested.world().request().publishWorkflowId()) + .orElseThrow( + () -> + Status.NOT_FOUND + .withDescription("Publication operation unavailable") + .asRuntimeException()); + if (!Arrays.equals(requested.canonicalBytes(), stored.operation().canonicalBytes()) + || !("PUBLISHED".equals(stored.outcome()) + || "NO_PUBLICATION".equals(stored.outcome())) + || stored.terminalEvidenceBytes() == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact complete terminal publication evidence unavailable") + .asRuntimeException(); + } + byte[] originalTerminalBytes = stored.terminalEvidenceBytes(); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(originalTerminalBytes); + if (!Arrays.equals(requested.canonicalBytes(), terminal.operationBytes()) + || !stored.outcome().equals(terminal.outcome().name()) + || !Arrays.equals(originalTerminalBytes, terminal.canonicalBytes())) { + throw Status.FAILED_PRECONDITION + .withDescription("Terminal evidence differs from original publication") + .asRuntimeException(); + } + return terminal; + }), + "Publication terminal snapshot returned no result"); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Publication terminal owner storage unavailable") + .asRuntimeException(); + } + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service").equals(peer.uri()) + && !("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Account or World Management workload required") + .asRuntimeException(); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 4bfab791bf..476c552ff3 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -4,18 +4,42 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Base64; import java.util.List; import java.util.UUID; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +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.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignSelectedDraftPublicationReadGrpcService; import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.Game; @@ -46,6 +70,7 @@ import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -785,6 +810,389 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( publishAttemptRepository.requireNoPublicationOperation(attempt); } + /** + * Real PostgreSQL selection and production loopback mTLS owner read. Original Account/World + * outcomes are stipulated by the isolated setup; this does not prove full cross-owner APPLIED + * provenance, deployed custody, current DRAFT authority, publication, or runtime activation. + */ + @Test + void retainedSelectedDraftOwnerReadOverMtlsReplaysExactlyAndDeniesSubstitution( + @TempDir Path temporary) throws Exception { + String tenantId = "9009"; + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("selected-draft-mtls-proof-game"); + gameRepository.save(game); + Version candidate = new Version(); + candidate.setTenantId(tenantId); + candidate.setVersionNumber(1); + candidate.setVersionState(VersionLifecycleState.DRAFT); + candidate.setVersionStateEpoch(1L); + candidate.setNotes("selected Draft mTLS proof"); + candidate = versionRepository.save(candidate); + TargetProof target = targetProof(candidate); + long epoch = candidate.getVersionStateEpoch(); + var selected = + inOwnerTransaction( + () -> { + try { + // Actual GD source/fence/selection writes; remote owner outcomes remain fixture + // inputs. + return IsolatedPublicationOwnerSetup.selectSourceBackedDraft( + dsl, target, epoch, "selected Draft mTLS proof") + .selection(); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + var original = + AuthoredDraftPublishSelectionBinding.fromStored( + selected.canonicalJson(), selected.digest()); + var request = AuthoredDraftPublishSelectionReadEvidence.Request.create("test", original); + var repository = + new AuthoredDraftPublishSelectionRepository(dsl, new DraftCommitCoordinatorRepository(dsl)); + int selectionRowsBefore = + dsl.fetchCount(org.jooq.impl.DSL.table("game_design_authored_draft_publish_selection")); + var retainedBefore = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_design_authored_draft_publish_selection" + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId())) + .intoMap(); + var pki = new SelectionReadTestPki(Files.createDirectories(temporary.resolve("pki"))); + var endpoint = new GameDesignSelectedDraftPublicationReadGrpcService(repository, "test"); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + pki.server.certificate().toFile(), pki.server.key().toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + try { + for (var identity : List.of(pki.account, pki.worldManagement)) { + try (var client = selectionReadClient(server.getPort(), identity, pki.ca)) { + var first = client.read(request); + var retry = client.read(request); + assertThat(first.request()).isEqualTo(request); + assertThat(retry.request()).isEqualTo(first.request()); + assertThat(first.request().originalSelection()) + .containsExactly(selected.canonicalBytes()); + assertThat(first.request().selectionDigest()).isEqualTo(selected.digest()); + var freshRead = + AuthoredDraftPublishSelectionReadEvidence.Request.create("test", original); + assertThat(client.read(freshRead).request()).isEqualTo(freshRead); + var intent = original.intent(); + var changed = selectionReadVariant(original, intent.publishRequestId(), "changed notes"); + var missing = + selectionReadVariant(original, UUID.randomUUID().toString(), intent.notes()); + assertSelectionReadCode( + Status.Code.FAILED_PRECONDITION, + () -> + client.read( + AuthoredDraftPublishSelectionReadEvidence.Request.create("test", changed))); + assertSelectionReadCode( + Status.Code.NOT_FOUND, + () -> + client.read( + AuthoredDraftPublishSelectionReadEvidence.Request.create("test", missing))); + assertThat(client.read(request).request()).isEqualTo(request); + } + } + for (var identity : List.of(pki.wrongWorkload, pki.otherNamespace, pki.otherWorldNamespace)) { + try (var client = selectionReadClient(server.getPort(), identity, pki.ca)) { + assertSelectionReadCode(Status.Code.PERMISSION_DENIED, () -> client.read(request)); + } + } + var retainedAfter = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_design_authored_draft_publish_selection" + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId())) + .intoMap(); + assertThat(retainedAfter).isEqualTo(retainedBefore); + assertThat( + dsl.fetchCount( + org.jooq.impl.DSL.table("game_design_authored_draft_publish_selection"))) + .isEqualTo(selectionRowsBefore); + assertThat( + repository + .read( + target.canonicalTenantId(), + target.canonicalVersionId(), + original.intent().publishRequestId()) + .orElseThrow() + .selection() + .canonicalBytes()) + .containsExactly(selected.canonicalBytes()); + assertThat( + versionRepository + .findByTenantIdAndId(tenantId, target.gameDesignVersionRowId()) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.DRAFT); + assertThat( + publishedReleaseBundleRepository.findByTenantIdAndVersionId( + tenantId, target.gameDesignVersionRowId())) + .isEmpty(); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static AuthoredDraftPublishSelectionBinding selectionReadVariant( + AuthoredDraftPublishSelectionBinding original, String publishRequestId, String notes) { + var intent = original.intent(); + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + publishRequestId, + intent.expectedVersionStateEpoch(), + notes, + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()), + original.target(), + original.selectedCommit(), + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + original.target(), + original.fenceRequestId(), + original.fenceCommitId(), + original.fenceInputDigest(), + original.fenceResultVectorJson(), + java.time.OffsetDateTime.parse(original.fenceCreatedAt()))); + } + + private static AuthoredDraftPublishSelectionReadClient selectionReadClient( + int port, SelectionReadTestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + port); + var client = + new AuthoredDraftPublishSelectionReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), "test"); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + private static void assertSelectionReadCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private record SelectionReadTestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + } + + /** Ephemeral keytool PKI, following Account's existing loopback test; no runtime credentials. */ + private static final class SelectionReadTestPki { + private static final String PASSWORD = "test-only-publication-mtls-password"; + final Path ca; + final SelectionReadTestIdentity server, + account, + worldManagement, + wrongWorkload, + otherNamespace, + otherWorldNamespace; + + SelectionReadTestPki(Path root) throws Exception { + Path caStore = root.resolve("ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=Game Design selected Draft read test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + ca = root.resolve("ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + ca.toString(), + "-rfc"); + server = issue(root, caStore, "game-design-server", "test", "game-design-service", true); + account = issue(root, caStore, "account-client", "test", "account-service", false); + worldManagement = + issue(root, caStore, "world-client", "test", "world-management-service", false); + wrongWorkload = + issue(root, caStore, "game-session-client", "test", "game-session-service", false); + otherNamespace = + issue(root, caStore, "other-account-client", "other-test", "account-service", false); + otherWorldNamespace = + issue( + root, caStore, "other-world-client", "other-test", "world-management-service", false); + } + + private static SelectionReadTestIdentity issue( + Path root, Path caStore, String alias, String namespace, String workload, boolean server) + throws Exception { + Path store = root.resolve(alias + ".p12"), + request = root.resolve(alias + ".csr"), + certificate = root.resolve(alias + ".crt"); + String san = + "URI:spiffe://firemud/ns/" + + namespace + + "/sa/" + + workload + + ",DNS:localhost,IP:127.0.0.1"; + String eku = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san); + var keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, PASSWORD.toCharArray()); + } + byte[] privateKey = + java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull( + keyStore.getKey(alias, PASSWORD.toCharArray()), + "Expected ephemeral test private key") + .getEncoded(), + "Expected encoded ephemeral test private key"); + Path key = root.resolve(alias + ".key"); + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(privateKey); + Files.writeString( + key, + "-----BEGIN PRIVATE KEY-----\n" + body + "\n-----END PRIVATE KEY-----\n", + StandardCharsets.US_ASCII); + java.util.Arrays.fill(privateKey, (byte) 0); + return new SelectionReadTestIdentity(certificate, key); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("Ephemeral test certificate generation timed out"); + } + try (var output = process.getInputStream()) { + String details = new String(output.readAllBytes(), StandardCharsets.UTF_8); + if (process.exitValue() != 0) + throw new IllegalStateException("Test keytool failed: " + details); + } + } + } + private static String firstStackFrame(Throwable failure) { if (failure == null || failure.getStackTrace().length == 0) { return "none"; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java new file mode 100644 index 0000000000..6da5ec3126 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSelectedDraftPublicationReadGrpcServiceTest.java @@ -0,0 +1,275 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse; +import net.firedevops.firemud.gamedesign.v1.SelectedDraftPublicationStatus; +import org.junit.jupiter.api.Test; + +/** Receiver unit proof uses stipulated verified peer context and mocked selection storage. */ +class GameDesignSelectedDraftPublicationReadGrpcServiceTest { + private static final String NAMESPACE = "test"; + + @Test + void rejectsMissingWrongServiceAndWrongNamespacePeersBeforeDecodingAndStorage() { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + var malformed = ReadSelectedDraftPublicationRequest.getDefaultInstance(); + var absent = new Collector(); + service.readSelectedDraftPublication(malformed, absent); + assertFailure(absent, Status.Code.UNAUTHENTICATED); + for (var peer : + List.of( + peer("game-design-service", NAMESPACE), + peer("account-service", "other"), + peer("world-management-service", "other"))) { + var denied = invokeAs(service, malformed, peer); + assertFailure(denied, Status.Code.PERMISSION_DENIED); + } + verifyNoInteractions(repository); + } + + @Test + void rejectsMalformedUnknownAndCrossNamespaceRequestsBeforeStorage() { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + var request = wireRequest(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + List.of( + ReadSelectedDraftPublicationRequest.getDefaultInstance(), + request.toBuilder().setUnknownFields(unknown).build(), + request.toBuilder().setSelectionDigest("sha256:" + "0".repeat(64)).build())) { + assertFailure( + invokeAs(service, invalid, peer("account-service", NAMESPACE)), + Status.Code.INVALID_ARGUMENT); + } + assertFailure( + invokeAs( + service, + request.toBuilder().setTargetNamespace("other").build(), + peer("account-service", NAMESPACE)), + Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void readsExactCanonicalIdentityAndReturnsOnlyExactRetainedSelectionForBothCallers() { + for (String caller : List.of("account-service", "world-management-service")) { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + var binding = binding(); + when(repository.read(any(), any(), any())).thenReturn(Optional.of(snapshot(binding))); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + var request = wireRequest(); + var response = invokeAs(service, request, peer(caller, NAMESPACE)); + var intent = binding.intent(); + verify(repository) + .read(intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId()); + assertThat(response.errorCode).isNull(); + assertThat(response.completed).isTrue(); + assertThat(response.value) + .isEqualTo( + AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse( + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest(request))); + assertThat(response.value.getStatus()) + .isEqualTo(SelectedDraftPublicationStatus.SELECTED_DRAFT_PUBLICATION_STATUS_SELECTED); + } + } + + @Test + void missingSelectionDoesNotInventSuccessfulOrTerminalEvidence() { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + when(repository.read(any(), any(), any())).thenReturn(Optional.empty()); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + assertFailure( + invokeAs(service, wireRequest(), peer("account-service", NAMESPACE)), + Status.Code.NOT_FOUND); + } + + @Test + void changedStoredSelectionFailsWithoutPartialBytes() { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + var original = binding(); + var intent = original.intent(); + var changed = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + "changed notes", + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()), + original.target(), + original.selectedCommit(), + new VisibilityFence( + original.target(), + original.fenceRequestId(), + original.fenceCommitId(), + original.fenceInputDigest(), + original.fenceResultVectorJson(), + OffsetDateTime.parse(original.fenceCreatedAt()))); + when(repository.read(any(), any(), any())).thenReturn(Optional.of(snapshot(changed))); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + assertFailure( + invokeAs(service, wireRequest(), peer("world-management-service", NAMESPACE)), + Status.Code.FAILED_PRECONDITION); + } + + @Test + void corruptOrUnavailableStorageReturnsNoEvidence() { + for (RuntimeException failure : + List.of( + new IllegalStateException("corrupt retained selection"), + new org.jooq.exception.DataAccessException("storage unavailable"))) { + var repository = mock(AuthoredDraftPublishSelectionRepository.class); + when(repository.read(any(), any(), any())).thenThrow(failure); + var service = new GameDesignSelectedDraftPublicationReadGrpcService(repository, NAMESPACE); + assertFailure( + invokeAs(service, wireRequest(), peer("account-service", NAMESPACE)), + Status.Code.UNAVAILABLE); + } + } + + private static AuthoredDraftPublishSelectionRepository.SelectionSnapshot snapshot( + AuthoredDraftPublishSelectionBinding binding) { + return new AuthoredDraftPublishSelectionRepository.SelectionSnapshot( + AuthoredDraftPublishSelection.fromStored(binding.canonicalJson(), binding.digest()), + OffsetDateTime.parse("2026-10-01T00:00:00Z")); + } + + private static ReadSelectedDraftPublicationRequest wireRequest() { + return AuthoredDraftPublishSelectionReadGrpcCodec.toRequest( + AuthoredDraftPublishSelectionReadEvidence.Request.create(NAMESPACE, binding())); + } + + private static void assertFailure(Collector collector, Status.Code expected) { + assertThat(collector.errorCode).isEqualTo(expected); + assertThat(collector.value).isNull(); + assertThat(collector.completed).isFalse(); + } + + private static Collector invokeAs( + GameDesignSelectedDraftPublicationReadGrpcService service, + ReadSelectedDraftPublicationRequest request, + GrpcPeerIdentity peer) { + var result = new Collector(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readSelectedDraftPublication(request, result); + return result; + } finally { + context.detach(previous); + } + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static AuthoredDraftPublishSelectionBinding binding() { + UUID tenant = uuid("22222222-2222-4222-8222-222222222222"); + UUID version = uuid("33333333-3333-4333-8333-333333333333"); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "5", + "test selection", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return selected; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Collector + implements StreamObserver { + private ReadSelectedDraftPublicationResponse value; + private Status.Code errorCode; + private boolean completed; + + @Override + public void onNext(ReadSelectedDraftPublicationResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + errorCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcServiceTest.java new file mode 100644 index 0000000000..43fe5ca091 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadGrpcServiceTest.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalRequest; +import net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalResponse; +import org.junit.jupiter.api.Test; + +/** Stipulated peer context and mocked owner units; not TLS or physical PostgreSQL proof. */ +class GameDesignPublicationTerminalReadGrpcServiceTest { + private final GameDesignPublicationTerminalReadService owner = + mock(GameDesignPublicationTerminalReadService.class); + private final GameDesignPublicationTerminalReadGrpcService service = + new GameDesignPublicationTerminalReadGrpcService(owner, "test"); + + @Test + void authenticatesBeforeMalformedRequestOrOwnerLookup() { + assertThat(call(null, null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String peer : + List.of( + "spiffe://firemud/ns/test/sa/game-session-service", + "spiffe://firemud/ns/test/sa/game-design-service", + "spiffe://firemud/ns/other/sa/account-service", + "spiffe://firemud/ns/other/sa/world-management-service")) { + assertThat(call(peer, null).code()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + verifyNoInteractions(owner); + } + + @Test + void malformedUnknownAndWrongNamespaceNeverReachOwner() throws Exception { + var request = request(operation()); + for (var malformed : + List.of( + ReadPublicationTerminalRequest.getDefaultInstance(), + request.toBuilder().setSchemaVersion(2).build(), + request.toBuilder().setReadRequestId("00000000-0000-0000-0000-000000000000").build(), + request.toBuilder().clearOriginalOperation().build(), + request.toBuilder() + .setOriginalOperation(com.google.protobuf.ByteString.copyFrom(new byte[] {1})) + .build(), + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertThat(call(account(), malformed).code()).isEqualTo(Status.Code.INVALID_ARGUMENT); + } + assertThat(call(account(), request.toBuilder().setTargetNamespace("other").build()).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } + + @Test + void bothOwnerPeersReceiveExactOriginalCompleteTerminalAndRetry() throws Exception { + var operation = operation(); + var request = request(operation); + for (Outcome outcome : Outcome.values()) { + var terminal = terminal(operation, outcome); + when(owner.read(eq("test"), any())).thenReturn(terminal); + for (String peer : + List.of(account(), "spiffe://firemud/ns/test/sa/world-management-service")) { + var first = call(peer, request); + var retry = call(peer, request); + assertThat(first.failure).isNull(); + assertThat(first.completed).isTrue(); + assertThat(first.response) + .isEqualTo( + GameDesignPublicationTerminalReadGrpcCodec.toResponse( + GameDesignPublicationTerminalReadGrpcCodec.fromRequest(request), terminal)); + assertThat(retry.response).isEqualTo(first.response); + assertThat(first.response.getOriginalOperation().toByteArray()) + .containsExactly(operation.canonicalBytes()); + assertThat(first.response.getTerminalEvidence().toByteArray()) + .containsExactly(terminal.canonicalBytes()); + } + } + } + + @Test + void ownerDenialsUnavailableMissingAndSubstitutedEvidenceCannotSucceed() throws Exception { + var operation = operation(); + var request = request(operation); + for (Status status : + List.of(Status.NOT_FOUND, Status.FAILED_PRECONDITION, Status.UNAVAILABLE)) { + doThrow(status.withDescription("private storage details").asRuntimeException()) + .when(owner) + .read(eq("test"), any()); + var result = call(account(), request); + assertThat(result.code()).isEqualTo(status.getCode()); + assertThat(result.failure.getDescription()).doesNotContain("private storage details"); + assertThat(result.response).isNull(); + assertThat(result.completed).isFalse(); + } + doReturn(null).when(owner).read(eq("test"), any()); + assertThat(call(account(), request).code()).isEqualTo(Status.Code.UNAVAILABLE); + doReturn(terminal(operation(), Outcome.NO_PUBLICATION)).when(owner).read(eq("test"), any()); + assertThat(call(account(), request).code()).isEqualTo(Status.Code.UNAVAILABLE); + } + + private static String account() { + return "spiffe://firemud/ns/test/sa/account-service"; + } + + private static ReadPublicationTerminalRequest request(GameDesignPublicationOperation operation) { + return GameDesignPublicationTerminalReadGrpcCodec.toRequest( + new GameDesignPublicationTerminalReadEvidence.Request( + 1, "test", UUID.randomUUID(), operation.canonicalBytes())); + } + + private Capture call(String peerUri, ReadPublicationTerminalRequest request) { + var capture = new Capture(); + Context context = + peerUri == null + ? Context.current() + : Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); + Context prior = context.attach(); + try { + service.readPublicationTerminal(request, capture); + return capture; + } finally { + context.detach(prior); + } + } + + private static final class Capture implements StreamObserver { + private ReadPublicationTerminalResponse response; + private Status failure; + private boolean completed; + + @Override + public void onNext(ReadPublicationTerminalResponse value) { + response = value; + } + + @Override + public void onError(Throwable value) { + failure = Status.fromThrowable(value).withCause(null); + } + + @Override + public void onCompleted() { + completed = true; + } + + private Status.Code code() { + return failure.getCode(); + } + } + + private static GameDesignPublicationOperation operation() throws Exception { + return IsolatedPublicationOperationFixtures.fresh( + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW")); + } + + private static GameDesignPublicationTerminalEvidence terminal( + GameDesignPublicationOperation operation, Outcome outcome) { + if (outcome == Outcome.NO_PUBLICATION) { + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), outcome, null, null); + } + var participants = + PublishedWorldSelectorFixtures.participants(operation.versionId(), operation.world()) + .stream() + .map( + p -> + new GameDesignPublicationTerminalEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionId(), + p.appliedCommitId(), + p.contentDigest(), + p.digestSchemaVersion(), + p.abilitySchemaDigest(), + p.errorCode(), + p.errorMessage())) + .toList(); + var selection = operation.account().input().selection(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + "retained-bundle", + 1, + "v2", + operation.workflowId(), + "sha256:" + "a".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of(), + "generation-1", + operation.world()); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + outcome, + release, + Math.addExact(operation.world().request().versionStateEpoch(), 1L)); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadServiceTest.java new file mode 100644 index 0000000000..bf2ff64c6e --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationTerminalReadServiceTest.java @@ -0,0 +1,258 @@ +package net.firedevops.firemud.gamedesign.publication; + +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.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Owner-read units use stipulated workload context, upstream operation fixtures and mocked + * repository/transactions. They do not prove authenticated transport, physical PostgreSQL backing + * or source settlement. Complete terminal parsing uses the production evidence codec. + */ +class GameDesignPublicationTerminalReadServiceTest { + private final GameDesignPublicationOperationRepository repository = + mock(GameDesignPublicationOperationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final TransactionStatus transactionStatus = mock(TransactionStatus.class); + private final GameDesignPublicationTerminalReadService service = + new GameDesignPublicationTerminalReadService(repository, transactions, "test"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeDecodingOrStorage() { + assertCode(Status.Code.UNAUTHENTICATED, () -> service.read(null, null)); + for (String workload : List.of("game-design-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", workload, () -> service.read(null, null))); + } + for (String workload : List.of("account-service", "world-management-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", workload, () -> service.read(null, null))); + } + verifyNoInteractions(repository, transactions); + } + + @Test + void rejectsNamespaceAmbientTransactionSynchronizationAndMalformedOperationBeforeStorage() { + assertCode(Status.Code.PERMISSION_DENIED, () -> authorized(() -> service.read("other", null))); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read("test", null))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read("test", null))); + TransactionSynchronizationManager.clearSynchronization(); + assertCode( + Status.Code.INVALID_ARGUMENT, () -> authorized(() -> service.read("test", new byte[] {1}))); + verifyNoInteractions(repository, transactions); + } + + @Test + void returnsExactCompleteTerminalBytesOnlyAfterDedicatedReadOnlyRepeatableReadSnapshot() + throws Exception { + var operation = operation(); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + for (Outcome outcome : Outcome.values()) { + var terminal = terminal(operation, outcome); + when(repository.read(operation.workflowId())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + operation, outcome.name(), new byte[] {1}, terminal.canonicalBytes()))); + for (String workload : List.of("account-service", "world-management-service")) { + var returned = + asPeer("test", workload, () -> service.read("test", operation.canonicalBytes())); + assertThat(returned.canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(returned.operationBytes()).containsExactly(operation.canonicalBytes()); + assertThat(returned.outcome()).isEqualTo(outcome); + } + } + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + var order = inOrder(transactions, repository); + for (int i = 0; i < 4; i++) { + order.verify(transactions).getTransaction(definition.capture()); + order.verify(repository).read(operation.workflowId()); + order.verify(transactions).commit(transactionStatus); + } + for (var selected : definition.getAllValues()) { + assertThat(selected.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(selected.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(selected.isReadOnly()).isTrue(); + } + } + + @Test + void missingPendingLegacyAndChangedOperationCannotProduceTerminalEvidence() throws Exception { + var operation = operation(); + var changed = operation(); + var noPublication = terminal(operation, Outcome.NO_PUBLICATION); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(repository.read(operation.workflowId())).thenReturn(Optional.empty()); + assertCode( + Status.Code.NOT_FOUND, + () -> authorized(() -> service.read("test", operation.canonicalBytes()))); + for (var stored : + List.of( + new GameDesignPublicationOperationRepository.Readback(operation, "PENDING", null, null), + new GameDesignPublicationOperationRepository.Readback( + operation, "NO_PUBLICATION", new byte[] {1}), + new GameDesignPublicationOperationRepository.Readback( + operation, "PUBLISHED", new byte[] {1}), + new GameDesignPublicationOperationRepository.Readback( + changed, + "NO_PUBLICATION", + new byte[] {1}, + terminal(changed, Outcome.NO_PUBLICATION).canonicalBytes()), + new GameDesignPublicationOperationRepository.Readback( + operation, "PUBLISHED", new byte[] {1}, noPublication.canonicalBytes()), + new GameDesignPublicationOperationRepository.Readback( + operation, + "NO_PUBLICATION", + new byte[] {1}, + terminal(changed, Outcome.NO_PUBLICATION).canonicalBytes()))) { + when(repository.read(operation.workflowId())).thenReturn(Optional.of(stored)); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.read("test", operation.canonicalBytes()))); + } + } + + @Test + void corruptTerminalAndOwnerBackingFailuresFailClosed() throws Exception { + var operation = operation(); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(repository.read(operation.workflowId())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + operation, "PUBLISHED", new byte[] {1}, new byte[] {1, 2}))); + assertCode( + Status.Code.UNAVAILABLE, + () -> authorized(() -> service.read("test", operation.canonicalBytes()))); + // The real repository owns immutable complete release/attempt comparison. + for (RuntimeException failure : + List.of( + new IllegalStateException("PUBLICATION_TERMINAL_BACKING_CONFLICT"), + new IllegalStateException("PUBLICATION_RECEIPT_ATTEMPT_CONFLICT"), + new org.jooq.exception.DataAccessException("storage unavailable"))) { + doThrow(failure).when(repository).read(operation.workflowId()); + assertCode( + Status.Code.UNAVAILABLE, + () -> authorized(() -> service.read("test", operation.canonicalBytes()))); + } + } + + private static GameDesignPublicationOperation operation() throws Exception { + return IsolatedPublicationOperationFixtures.fresh( + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW")); + } + + private static GameDesignPublicationTerminalEvidence terminal( + GameDesignPublicationOperation operation, Outcome outcome) { + if (outcome == Outcome.NO_PUBLICATION) { + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), outcome, null, null); + } + var participants = + PublishedWorldSelectorFixtures.participants(operation.versionId(), operation.world()) + .stream() + .map( + p -> + new GameDesignPublicationTerminalEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionId(), + p.appliedCommitId(), + p.contentDigest(), + p.digestSchemaVersion(), + p.abilitySchemaDigest(), + p.errorCode(), + p.errorMessage())) + .toList(); + var selection = operation.account().input().selection(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + "retained-bundle", + 1, + "v2", + operation.workflowId(), + "sha256:" + "a".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of(), + "generation-1", + operation.world()); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + outcome, + release, + Math.addExact(operation.world().request().versionStateEpoch(), 1L)); + } + + private static T authorized(Supplier action) { + return asPeer("test", "account-service", action); + } + + private static T asPeer(String namespace, String workload, Supplier action) { + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationAuthorizationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationAuthorizationRepository.java new file mode 100644 index 0000000000..bcc7349983 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationAuthorizationRepository.java @@ -0,0 +1,223 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal immutable correlation between a newly-created World freeze and its distinct original + * Account publication authorization. This does not settle or release Account source participation. + */ +final class WorldSelectedDraftPublicationAuthorizationRepository { + private static final String SELECT_BINDING = + "SELECT publication_fence, account_operation_id, account_fence_id, " + + "account_binding_bytes, account_binding_digest " + + "FROM world_design_publication_account_binding WHERE publication_fence=?"; + private static final String SELECT_ATTEMPT_AND_OWNER = + "SELECT a.*, o.owner_freeze_phase, o.current_publication_fence " + + "FROM world_design_publication_fence_attempt a " + + "JOIN world_design_publication_fence_owner o " + + "ON o.target_namespace=a.target_namespace " + + "AND o.canonical_tenant_id=a.canonical_tenant_id " + + "AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id " + + "WHERE a.publication_fence=?"; + + private final DSLContext dsl; + + WorldSelectedDraftPublicationAuthorizationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Reads the exact immutable qualification after commit. Absence means the attempt is unqualified, + * not that current Account state may be sampled to upgrade it. + */ + Optional readCommitted(FrozenAttempt attempt) { + Objects.requireNonNull(attempt, "attempt"); + requireNoAmbientTransaction(); + requireExactAttempt(attempt, false, false); + Record row = dsl.fetchOne(SELECT_BINDING, attempt.publicationFence()); + return row == null ? Optional.empty() : Optional.of(decodeExact(row, attempt)); + } + + /** + * Retains or replays the original Account binding while the first-freeze owner transaction is + * still holding its World version row lock. + * + *

{@code attemptCreatedInThisTransaction} must be set only from the actual checkpoint callback + * invocation by {@link WorldDesignPublicationFenceRepository#claimFreeze}; absence of that signal + * permits exact replay only and never late qualification of an old frozen attempt. + */ + AccountPublicationAuthorizationBinding retainOrRequireExact( + FrozenAttempt attempt, + AccountPublicationAuthorizationBinding supplied, + boolean attemptCreatedInThisTransaction) { + Objects.requireNonNull(attempt, "attempt"); + Objects.requireNonNull(supplied, "supplied"); + requireWritableReadCommittedOwnerTransaction(); + requireExactAttempt(attempt, true, true); + + Record existing = dsl.fetchOne(SELECT_BINDING, attempt.publicationFence()); + if (existing != null) { + return requireSameBinding(supplied, decodeExact(existing, attempt)); + } + if (!attemptCreatedInThisTransaction) { + throw conflict("Historical or concurrent World freeze has no original Account qualification"); + } + + byte[] canonicalBytes = supplied.canonicalBytes(); + String digest = DraftAuthorizationFenceBinding.digest(canonicalBytes); + int inserted = + dsl.execute( + "INSERT INTO world_design_publication_account_binding " + + "(publication_fence, account_operation_id, account_fence_id, " + + "account_binding_bytes, account_binding_digest) VALUES (?, ?, ?, ?, ?)", + attempt.publicationFence(), + supplied.operationId(), + supplied.fenceId(), + canonicalBytes, + digest); + if (inserted != 1) { + throw conflict("World publication Account binding was not retained"); + } + Record readback = dsl.fetchOne(SELECT_BINDING, attempt.publicationFence()); + if (readback == null) { + throw conflict("New World freeze has no Account qualification readback"); + } + return requireSameBinding(supplied, decodeExact(readback, attempt)); + } + + private void requireExactAttempt( + FrozenAttempt expected, boolean lockOwner, boolean requireCurrentFreeze) { + String sql = SELECT_ATTEMPT_AND_OWNER + (lockOwner ? " FOR UPDATE OF o" : ""); + Record row = dsl.fetchOne(sql, expected.publicationFence()); + if (row == null) { + throw conflict("World Account qualification has no exact retained publication attempt"); + } + var request = expected.request(); + var checkpoint = expected.checkpoint(); + if (!Short.valueOf((short) 1).equals(required(row, "owner_binding_schema_version", Short.class)) + || !request.targetNamespace().equals(required(row, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(row, "canonical_tenant_id", UUID.class)) + || !request.canonicalVersionId().equals(required(row, "canonical_version_id", UUID.class)) + || !request + .versionIdentityOperationId() + .equals(required(row, "version_identity_operation_id", UUID.class)) + || request.gameDesignVersionId() != required(row, "game_design_version_id", Long.class) + || !request.intakeRequestId().equals(required(row, "intake_request_id", UUID.class)) + || !request.intakeOperationId().equals(required(row, "intake_operation_id", UUID.class)) + || !request + .intakeRequestDigest() + .equals(required(row, "intake_request_digest", String.class)) + || !request.sourceOperationId().equals(required(row, "source_operation_id", UUID.class)) + || !request + .sourceEvidenceDigest() + .equals(required(row, "source_evidence_digest", String.class)) + || !request + .intakeReceiptDigest() + .equals(required(row, "intake_receipt_digest", String.class)) + || !request + .publicationRequestId() + .equals(required(row, "publication_request_id", String.class)) + || !request.requestDigest().equals(required(row, "request_digest", String.class)) + || request.versionStateEpoch() != required(row, "version_state_epoch", Long.class) + || !request.publishWorkflowId().equals(required(row, "publish_workflow_id", String.class)) + || !checkpoint.appliedCommitId().equals(required(row, "applied_commit_id", String.class)) + || !checkpoint.contentDigest().equals(required(row, "content_digest", String.class)) + || checkpoint.digestSchemaVersion() != required(row, "digest_schema_version", Integer.class) + || (requireCurrentFreeze + && (!"FROZEN".equals(required(row, "owner_freeze_phase", String.class)) + || !expected + .publicationFence() + .equals(required(row, "current_publication_fence", UUID.class))))) { + throw conflict("World Account qualification differs from the exact retained frozen attempt"); + } + } + + private static AccountPublicationAuthorizationBinding decodeExact( + Record row, FrozenAttempt attempt) { + UUID fence = required(row, "publication_fence", UUID.class); + UUID accountOperation = required(row, "account_operation_id", UUID.class); + UUID accountFence = required(row, "account_fence_id", UUID.class); + byte[] bytes = required(row, "account_binding_bytes", byte[].class); + String digest = required(row, "account_binding_digest", String.class); + if (!attempt.publicationFence().equals(fence) + || !DraftAuthorizationFenceBinding.digest(bytes).equals(digest)) { + throw conflict("Stored World Account publication binding is corrupt"); + } + final AccountPublicationAuthorizationBinding binding; + try { + binding = AccountPublicationAuthorizationBinding.fromStored(bytes); + } catch (RuntimeException invalid) { + throw new WorldDesignPublicationFenceRepository.ConflictException( + "Stored World Account publication binding is not canonical"); + } + if (!accountOperation.equals(binding.operationId()) + || !accountFence.equals(binding.fenceId()) + || !Arrays.equals(bytes, binding.canonicalBytes())) { + throw conflict("Stored World Account publication binding identity differs from its bytes"); + } + return binding; + } + + private static AccountPublicationAuthorizationBinding requireSameBinding( + AccountPublicationAuthorizationBinding supplied, + AccountPublicationAuthorizationBinding stored) { + if (!supplied.operationId().equals(stored.operationId()) + || !supplied.fenceId().equals(stored.fenceId()) + || !Arrays.equals(supplied.canonicalBytes(), stored.canonicalBytes())) { + throw conflict("World publication retry changed its original Account authorization"); + } + return stored; + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World Account qualification requires a writable owner transaction"); + } + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (isolation != null && isolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World Account qualification requires READ COMMITTED"); + } + 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 Account qualification requires a writable READ COMMITTED owner transaction"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World committed Account qualification read requires no ambient transaction"); + } + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) { + throw conflict("World Account qualification is missing retained field " + field); + } + return value; + } + + private static WorldDesignPublicationFenceRepository.ConflictException conflict(String message) { + return new WorldDesignPublicationFenceRepository.ConflictException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java new file mode 100644 index 0000000000..fd7508d5d0 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java @@ -0,0 +1,387 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Internal, unregistered composition for freezing one exact selected fresh World Draft graph. + * + *

It does not create a publication order, settle/release Account source participation, expose an + * RPC, or claim a terminal publication result. The Account HELD read is only a prerequisite to the + * World commit; applicable Account source writers remain protected by the retained order and this + * service has no release path. + */ +final class WorldSelectedDraftPublicationFreezeService { + private final String workloadNamespace; + private final AuthoredDraftPublishSelectionReadClient selectionReadClient; + private final AuthoredWorldVersionStateClient versionStateClient; + private final AccountPublicationAuthorizationReadClient accountReadClient; + private final WorldAuthoredSourceIntakeRepository intakeRepository; + private final WorldDesignPublicationFenceRepository fence; + private final WorldSelectedDraftPublicationCheckpointRepository checkpointRepository; + private final WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository; + private final TransactionTemplate ownerTransaction; + + WorldSelectedDraftPublicationFreezeService( + String workloadNamespace, + AuthoredDraftPublishSelectionReadClient selectionReadClient, + AuthoredWorldVersionStateClient versionStateClient, + AccountPublicationAuthorizationReadClient accountReadClient, + WorldAuthoredSourceIntakeRepository intakeRepository, + WorldDesignPublicationFenceRepository fence, + WorldSelectedDraftPublicationCheckpointRepository checkpointRepository, + WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository, + PlatformTransactionManager transactionManager) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.selectionReadClient = Objects.requireNonNull(selectionReadClient, "selectionReadClient"); + this.versionStateClient = Objects.requireNonNull(versionStateClient, "versionStateClient"); + this.accountReadClient = Objects.requireNonNull(accountReadClient, "accountReadClient"); + this.intakeRepository = Objects.requireNonNull(intakeRepository, "intakeRepository"); + this.fence = Objects.requireNonNull(fence, "fence"); + this.checkpointRepository = + Objects.requireNonNull(checkpointRepository, "checkpointRepository"); + this.authorizationRepository = + Objects.requireNonNull(authorizationRepository, "authorizationRepository"); + this.ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Freezes and returns only the exact committed World checkpoint and Account-order correlation. + * + *

The supplied plan and Account binding are exact lookup identities, not authority. On a + * committed retry the immutable World attempt and Account correlation are checked before any + * mutable Game Design state or remote Account HELD read is repeated. + */ + FrozenAttempt freeze( + WorldDesignPublicationFenceEvidence evidence, + WorldDraftTopologyCommitPlan selectedPlan, + AccountPublicationAuthorizationBinding accountBinding) { + requireAuthenticatedGameDesignCaller(); + requireNoAmbientTransaction(); + if (!workloadNamespace.equals(evidence.targetNamespace())) { + throw new SecurityException( + "World selected-publication freeze target namespace differs from this workload"); + } + validateRelation(evidence, selectedPlan, accountBinding); + + Optional prior = fence.readAttempt(evidence); + if (prior.isPresent()) { + FrozenAttempt stored = prior.orElseThrow(); + requireCheckpointMatchesSelection(stored, selectedPlan, accountBinding.input().selection()); + AccountPublicationAuthorizationBinding retained = + authorizationRepository + .readCommitted(stored) + .orElseThrow( + () -> + conflict( + "World freeze attempt has no original Account publication qualification")); + requireSameAccountBinding(accountBinding, retained); + return stored; + } + + WorldAuthoredSourceIntakeReceipt intake = readExactIntake(evidence); + requireSelectedDraft(intake, evidence, accountBinding.input().selection()); + requireCurrentDraftState(intake, evidence, accountBinding.input().selection()); + requireAccountHeld(accountBinding); + + AtomicBoolean attemptCreatedInTransaction = new AtomicBoolean(); + FrozenAttempt transactionResult = + Objects.requireNonNull( + ownerTransaction.execute( + status -> { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World selected-publication freeze requires a writable owner transaction"); + } + FrozenAttempt attempt = + fence.claimFreeze( + evidence, + () -> { + Checkpoint checkpoint = + checkpointRepository.capture(evidence, selectedPlan); + attemptCreatedInTransaction.set(true); + return checkpoint; + }); + AccountPublicationAuthorizationBinding retained = + authorizationRepository.retainOrRequireExact( + attempt, accountBinding, attemptCreatedInTransaction.get()); + requireSameAccountBinding(accountBinding, retained); + requireCheckpointMatchesSelection( + attempt, selectedPlan, accountBinding.input().selection()); + return attempt; + }), + "World selected-publication freeze transaction did not commit"); + + // Acknowledgement follows the owner transaction's commit and exact immutable readback. + FrozenAttempt committed = + fence + .readAttempt(evidence) + .orElseThrow( + () -> + conflict("Committed World selected-publication freeze has no exact readback")); + if (!transactionResult.equals(committed)) { + throw conflict("Committed World freeze differs from its owner-transaction result"); + } + AccountPublicationAuthorizationBinding retained = + authorizationRepository + .readCommitted(committed) + .orElseThrow( + () -> + conflict( + "Committed World freeze has no exact Account publication qualification")); + requireSameAccountBinding(accountBinding, retained); + requireCheckpointMatchesSelection(committed, selectedPlan, accountBinding.input().selection()); + return committed; + } + + private void requireSelectedDraft( + WorldAuthoredSourceIntakeReceipt intake, + WorldDesignPublicationFenceEvidence evidence, + AuthoredDraftPublishSelectionBinding suppliedSelection) { + AuthoredDraftPublishSelectionReadEvidence.Request request = + AuthoredDraftPublishSelectionReadEvidence.Request.create( + workloadNamespace, suppliedSelection); + AuthoredDraftPublishSelectionReadEvidence read = selectionReadClient.read(request); + if (read == null + || !request.equals(read.request()) + || !Arrays.equals(request.originalSelection(), suppliedSelection.canonicalBytes()) + || !request.selectionDigest().equals(suppliedSelection.digest()) + || !read.request().binding().equals(suppliedSelection)) { + throw conflict("Game Design selected Draft read differs from the exact Account order"); + } + requireSelectionOwnerBinding(evidence, suppliedSelection); + if (!intake.targetNamespace().equals(workloadNamespace) + || !intake.canonicalTenantId().equals(evidence.canonicalTenantId()) + || !intake.worldSlug().equals(intake.source().worldSlug()) + || !intake.sourceOperationId().equals(evidence.sourceOperationId()) + || !intake.sourceEvidenceDigest().equals(evidence.sourceEvidenceDigest()) + || suppliedSelection.target().sourceGameRowId() != intake.source().sourceGameRowId() + || !suppliedSelection + .target() + .sourceGameTenantKey() + .equals(intake.source().sourceGameTenantKey()) + || !suppliedSelection + .target() + .gameDesignVersionTenantKey() + .equals(intake.source().sourceGameTenantKey()) + || !suppliedSelection + .target() + .sourceProvenanceKind() + .equals(intake.source().provenanceKind())) { + throw conflict("World selected Draft differs from its exact retained source intake"); + } + } + + private void requireCurrentDraftState( + WorldAuthoredSourceIntakeReceipt intake, + WorldDesignPublicationFenceEvidence evidence, + AuthoredDraftPublishSelectionBinding selection) { + UUID readId; + do { + readId = UUID.randomUUID(); + } while (readId.equals(intake.intakeRequestId()) + || readId.equals(intake.operationId()) + || readId.equals(intake.sourceOperationId()) + || readId.equals(intake.source().registrationRequestId()) + || readId.equals(evidence.canonicalVersionId())); + AuthoredWorldVersionStateEvidence.Request request = + new AuthoredWorldVersionStateEvidence.Request( + 1, + workloadNamespace, + readId, + intake.canonicalTenantId(), + intake.worldSlug(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + selection.target().gameDesignVersionRowId()); + AuthoredWorldVersionStateEvidence current = versionStateClient.read(request); + try { + current.requireValid(); + } catch (RuntimeException invalid) { + throw new WorldDesignPublicationFenceRepository.ConflictException( + "Game Design returned invalid current World version-state evidence"); + } + if (!request.equals(current.request()) + || !intake.source().equals(current.sourceEvidence()) + || !evidence.canonicalVersionId().equals(current.canonicalVersionId()) + || current.versionState() != VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT + || current.versionStateEpoch() != evidence.versionStateEpoch() + || !selection + .intent() + .expectedVersionStateEpoch() + .equals(Long.toString(current.versionStateEpoch()))) { + throw conflict("Current Game Design Version is not the exact selected DRAFT epoch"); + } + } + + private void requireAccountHeld(AccountPublicationAuthorizationBinding binding) { + AccountPublicationAuthorizationReadEvidence.Request request = + AccountPublicationAuthorizationReadEvidence.Request.create(workloadNamespace, binding); + AccountPublicationAuthorizationReadEvidence read = accountReadClient.read(request); + if (read == null + || !request.equals(read.request()) + || !Arrays.equals( + request.originalPublicationAuthorizationBinding(), binding.canonicalBytes()) + || !request + .publicationAuthorizationDigest() + .equals(DraftAuthorizationFenceBinding.digest(binding.canonicalBytes())) + || !read.request().binding().operationId().equals(binding.operationId()) + || !read.request().binding().fenceId().equals(binding.fenceId()) + || !Arrays.equals(read.request().binding().canonicalBytes(), binding.canonicalBytes())) { + throw conflict("Account HELD read differs from the exact original publication order"); + } + } + + private WorldAuthoredSourceIntakeReceipt readExactIntake( + WorldDesignPublicationFenceEvidence evidence) { + WorldAuthoredSourceIntakeReceipt intake = + intakeRepository + .read(evidence.targetNamespace(), evidence.intakeRequestId()) + .orElseThrow(() -> conflict("World freeze requires an exact committed source intake")); + if (!evidence + .ownerBinding() + .equals( + new WorldDesignPublicationFenceEvidence.OwnerBinding( + intake.targetNamespace(), + intake.canonicalTenantId(), + evidence.canonicalVersionId(), + evidence.versionIdentityOperationId(), + evidence.gameDesignVersionId(), + intake.intakeRequestId(), + intake.operationId(), + intake.requestDigest(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.receiptDigest())) + || !"NEW_GAME_ROW".equals(intake.source().provenanceKind())) { + throw conflict("World freeze owner differs from its exact retained fresh source intake"); + } + return intake; + } + + private static void validateRelation( + WorldDesignPublicationFenceEvidence evidence, + WorldDraftTopologyCommitPlan plan, + AccountPublicationAuthorizationBinding account) { + Objects.requireNonNull(evidence, "evidence"); + Objects.requireNonNull(plan, "selectedPlan"); + Objects.requireNonNull(account, "accountBinding"); + AuthoredDraftPublishSelectionBinding selection = account.input().selection(); + if (!evidence.targetNamespace().equals(plan.ownerBinding().targetNamespace()) + || !evidence.ownerBinding().equals(plan.ownerBinding()) + || !selection.intent().canonicalTenantId().equals(evidence.canonicalTenantId()) + || !account.tenantId().equals(evidence.canonicalTenantId()) + || !selection.intent().canonicalVersionId().equals(evidence.canonicalVersionId()) + || selection.target().gameDesignVersionRowId() != evidence.gameDesignVersionId() + || !selection.intent().publishRequestId().equals(evidence.publicationRequestId()) + || !selection + .intent() + .expectedVersionStateEpoch() + .equals(Long.toString(evidence.versionStateEpoch())) + || !selection.digest().equals("sha256:" + evidence.requestDigest()) + || !PublicationDigestRequestBinding.full( + evidence.canonicalTenantId().toString(), + Long.toString(evidence.gameDesignVersionId()), + evidence.publicationRequestId()) + .derivedWorkflowIdentity() + .equals(evidence.publishWorkflowId()) + || !selection.selectedCommit().equals(plan.binding()) + || !Arrays.equals( + selection.selectedCommit().canonicalBytes(), plan.binding().canonicalBytes())) { + throw conflict("World freeze, selected Draft, and Account publication order are not exact"); + } + } + + private static void requireSelectionOwnerBinding( + WorldDesignPublicationFenceEvidence evidence, + AuthoredDraftPublishSelectionBinding selection) { + if (!selection.intent().canonicalTenantId().equals(evidence.canonicalTenantId()) + || !selection.intent().canonicalVersionId().equals(evidence.canonicalVersionId()) + || selection.target().gameDesignVersionRowId() != evidence.gameDesignVersionId() + || !selection.intent().publishRequestId().equals(evidence.publicationRequestId()) + || !selection + .intent() + .expectedVersionStateEpoch() + .equals(Long.toString(evidence.versionStateEpoch())) + || !selection.digest().equals("sha256:" + evidence.requestDigest())) { + throw conflict("Game Design selection differs from the exact World freeze request"); + } + } + + private static void requireCheckpointMatchesSelection( + FrozenAttempt attempt, + WorldDraftTopologyCommitPlan plan, + AuthoredDraftPublishSelectionBinding selection) { + if (!attempt.request().ownerBinding().equals(plan.ownerBinding()) + || !selection.selectedCommit().equals(plan.binding()) + || !attempt.checkpoint().appliedCommitId().equals(plan.binding().commitId().toString()) + || !attempt + .checkpoint() + .appliedCommitId() + .equals(selection.selectedCommit().commitId().toString())) { + throw conflict("World frozen APPLIED checkpoint differs from the exact selected commit"); + } + } + + private static void requireSameAccountBinding( + AccountPublicationAuthorizationBinding supplied, + AccountPublicationAuthorizationBinding retained) { + if (!supplied.operationId().equals(retained.operationId()) + || !supplied.fenceId().equals(retained.fenceId()) + || !Arrays.equals(supplied.canonicalBytes(), retained.canonicalBytes())) { + throw conflict("World freeze retry changed its exact original Account publication order"); + } + } + + private void requireAuthenticatedGameDesignCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(workloadNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "World selected-publication freeze requires the authenticated same-namespace Game Design workload"); + } + } + + private void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World selected-publication freeze cannot span owner reads from an ambient transaction"); + } + } + + private static WorldDesignPublicationFenceRepository.ConflictException conflict(String message) { + return new WorldDesignPublicationFenceRepository.ConflictException(message); + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V53__world_selected_publication_account_binding.sql b/services/world-management-service/src/main/resources/db/migration/V53__world_selected_publication_account_binding.sql new file mode 100644 index 0000000000..7651fc48f1 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V53__world_selected_publication_account_binding.sql @@ -0,0 +1,86 @@ +-- Preserve the distinct original Account publication order beside only a newly created World +-- freeze attempt. Historical attempts remain unqualified; their Account order is not inferred. +CREATE TABLE world_design_publication_account_binding ( + publication_fence UUID NOT NULL PRIMARY KEY + REFERENCES world_design_publication_fence_attempt(publication_fence) ON DELETE RESTRICT, + account_operation_id UUID NOT NULL, + account_fence_id UUID NOT NULL, + account_binding_bytes BYTEA NOT NULL CHECK (octet_length(account_binding_bytes) > 0), + account_binding_digest VARCHAR(71) NOT NULL + CHECK (account_binding_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT uq_world_publication_account_operation UNIQUE (account_operation_id), + CONSTRAINT uq_world_publication_account_fence UNIQUE (account_fence_id), + CONSTRAINT ck_world_publication_account_binding_ids CHECK ( + account_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + ) +); + +-- A canonical binding may qualify only an attempt inserted by this same transaction. This makes +-- late attachment to an older unqualified FROZEN attempt impossible even for direct SQL writers. +-- The repository additionally decodes and exact-compares the complete Account binding. +-- [jooq ignore start] +-- Existing attempts retain NULL; only attempts inserted after this forward-only stamp receive +-- their full transaction identity. Do not backfill historical rows from their wrapping xmin. +ALTER TABLE world_design_publication_fence_attempt + ADD COLUMN attempt_created_full_xid xid8; +ALTER TABLE world_design_publication_fence_attempt + ALTER COLUMN attempt_created_full_xid SET DEFAULT pg_current_xact_id(); + +REVOKE ALL ON world_design_publication_account_binding FROM PUBLIC; + +CREATE FUNCTION world_validate_selected_publication_account_binding() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World selected-publication Account binding is immutable' + USING ERRCODE = '55000'; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'World selected-publication Account binding requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT attempt + FROM "${serviceSchema}".world_design_publication_fence_attempt a + WHERE a.publication_fence = NEW.publication_fence + AND a.attempt_created_full_xid = pg_current_xact_id() + AND a.xmin::TEXT = (txid_current() % 4294967296)::TEXT; + SELECT * INTO STRICT owner_row + FROM "${serviceSchema}".world_design_publication_fence_owner o + WHERE o.target_namespace = attempt.target_namespace + AND o.canonical_tenant_id = attempt.canonical_tenant_id + AND o.local_tenant_key = attempt.local_tenant_key + AND o.version_id = attempt.version_id + FOR UPDATE; + + IF attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR owner_row.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence + OR encode(sha256(NEW.account_binding_bytes), 'hex') + IS DISTINCT FROM substring(NEW.account_binding_digest FROM 8) + OR NEW.account_operation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.account_fence_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'World Account binding differs from a newly committed qualified freeze' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_publication_account_binding_validate + BEFORE INSERT ON world_design_publication_account_binding FOR EACH ROW + EXECUTE FUNCTION world_validate_selected_publication_account_binding(); +CREATE TRIGGER trg_world_publication_account_binding_immutable + BEFORE UPDATE OR DELETE ON world_design_publication_account_binding FOR EACH ROW + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +CREATE TRIGGER trg_world_publication_account_binding_no_truncate + BEFORE TRUNCATE ON world_design_publication_account_binding FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 5c1be52e07..705a508302 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.when; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.JsonFormat; @@ -21,6 +22,7 @@ import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -31,11 +33,17 @@ 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.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; @@ -44,6 +52,8 @@ 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.dto.WorldDesignMutationRequestDto; +import net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; @@ -146,6 +156,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private WorldDesignPublicationFenceRepository fence; @Autowired private ObjectMapper mapper; @Autowired private WorldAuthoredGraphSnapshotRepository snapshots; + @Autowired private WorldDesignMutationService mutationService; @Autowired private net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService @@ -239,26 +250,77 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() .isEqualTo(applied.canonicalBytes()); assertThat(writer.apply(application).canonicalBytes()) .isEqualTo(applied.canonicalBytes()); - // Freeze a test-only publication selection of these actual authored owner rows. - var frozen = capture(plan); + assertLegacyNumericWritesCannotChangeCanonicalFreshGraph(world, plan); + // Both the immutable selection and distinct Account publication order are fixture-only + // stipulations. They are not proof that Account created or currently holds that order. + String publicationRequest = "selector-" + UUID.randomUUID(); + var publicationSelection = publicationSelection(plan, publicationRequest, 1L); + var stipulatedPublicationOrder = stipulatedPublicationOrder(publicationSelection); + var freezeEvidence = publicationFreezeEvidence(plan, publicationSelection); + var publicationAuthorizationRepository = publicationAuthorizationRepository(); + var stateBeforeFirstQualifiedCapture = ownerSnapshot(world, plan); + assertThat(stateBeforeFirstQualifiedCapture.publicationOwnerRows()).hasSize(1); + String openPublicationOwnerRow = + stateBeforeFirstQualifiedCapture.publicationOwnerRows().get(0); + assertThat(mapper.readTree(openPublicationOwnerRow).path("owner_freeze_phase").asText()) + .isEqualTo("OPEN"); + assertThat(stateBeforeFirstQualifiedCapture.publicationAttemptRows()).isEmpty(); + assertThat(stateBeforeFirstQualifiedCapture.publicationAuthorizationRows()).isEmpty(); + var forcedRollback = + new IllegalStateException("forced first-freeze qualification rollback"); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + var candidate = + fence.claimFreeze( + freezeEvidence, + () -> checkpointRepository().capture(freezeEvidence, plan)); + assertThat( + publicationAuthorizationRepository + .retainOrRequireExact( + candidate, stipulatedPublicationOrder, true) + .canonicalBytes()) + .containsExactly(stipulatedPublicationOrder.canonicalBytes()); + throw forcedRollback; + })) + .isSameAs(forcedRollback); + var stateAfterFirstQualifiedCaptureRollback = ownerSnapshot(world, plan); + assertThat(stateAfterFirstQualifiedCaptureRollback) + .isEqualTo(stateBeforeFirstQualifiedCapture); + assertThat(stateAfterFirstQualifiedCaptureRollback.publicationOwnerRows()) + .containsExactly(openPublicationOwnerRow); + assertThat(stateAfterFirstQualifiedCaptureRollback.publicationAttemptRows()).isEmpty(); + assertThat(stateAfterFirstQualifiedCaptureRollback.publicationAuthorizationRows()) + .isEmpty(); + var frozen = capture(plan, freezeEvidence, stipulatedPublicationOrder); assertThat(frozen.request().freeze().appliedCommitId()) .isEqualTo(applied.application().operation().commitId().toString()); - var retryEvidence = - publicationFreezeEvidence(plan, frozen.request().freeze().publicationRequestId()); + var retryEvidence = freezeEvidence; var stateBeforeExactRetry = ownerSnapshot(world, plan); var checkpointCallbackInvocations = new AtomicInteger(); var exactRetry = Objects.requireNonNull( ownerTransaction() .execute( - status -> - fence.claimFreeze( - retryEvidence, - () -> { - checkpointCallbackInvocations.incrementAndGet(); - return new WorldDesignPublicationFenceEvidence.Checkpoint( - "recapture-must-not-run", "b".repeat(64), 3); - }))); + status -> { + WorldDesignPublicationFenceEvidence.FrozenAttempt retry = + fence.claimFreeze( + retryEvidence, + () -> { + checkpointCallbackInvocations.incrementAndGet(); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + "recapture-must-not-run", "b".repeat(64), 3); + }); + assertThat( + publicationAuthorizationRepository + .retainOrRequireExact( + retry, stipulatedPublicationOrder, false) + .canonicalBytes()) + .containsExactly(stipulatedPublicationOrder.canonicalBytes()); + return retry; + })); assertThat(exactRetry.request()).isEqualTo(retryEvidence); assertThat(exactRetry.publicationFence()) .isEqualTo(frozen.request().freeze().publicationFence()); @@ -270,6 +332,43 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() frozen.request().freeze().digestSchemaVersion())); assertThat(checkpointCallbackInvocations.get()).isZero(); assertThat(ownerSnapshot(world, plan)).isEqualTo(stateBeforeExactRetry); + assertThat( + publicationAuthorizationRepository + .readCommitted(exactRetry) + .orElseThrow() + .canonicalBytes()) + .containsExactly(stipulatedPublicationOrder.canonicalBytes()); + var changedOperation = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + stipulatedPublicationOrder.fenceId(), + stipulatedPublicationOrder.input(), + stipulatedPublicationOrder.sources()); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + publicationAuthorizationRepository.retainOrRequireExact( + exactRetry, changedOperation, false))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("changed"); + var changedFence = + new AccountPublicationAuthorizationBinding( + stipulatedPublicationOrder.operationId(), + UUID.randomUUID(), + stipulatedPublicationOrder.input(), + stipulatedPublicationOrder.sources()); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + publicationAuthorizationRepository.retainOrRequireExact( + exactRetry, changedFence, false))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("changed"); + assertThat(ownerSnapshot(world, plan)).isEqualTo(stateBeforeExactRetry); var selectors = new WorldPublishedStartLocationRepository( dsl, frozenRepository(), appliedRepository()); @@ -328,10 +427,214 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() } } + @Test + void committedUnqualifiedAttemptCannotBeLateQualified() throws Exception { + try (var account = + new AccountControlUiOriginalOrderFixture( + accountPostgres.getJdbcUrl(), + accountPostgres.getUsername(), + accountPostgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary.resolve("unqualified-account"))) { + var world = fixture(intakeRepository, manager, dsl, account.tenantId()); + var plan = plan(world); + var original = account.claimOriginal(plan.binding()); + var operation = + new WorldDraftTerminalOperation( + original.operationId(), + original.requestId(), + original.commitId(), + original.fenceId(), + original.tenantId(), + original.versionId(), + plan.binding(), + plan.ownerBinding(), + original.canonicalBytes()); + var application = new WorldDraftGraphApplication(operation, plan); + var pki = new TestPki(temporary.resolve("unqualified-pki")); + var accountServer = + serve( + new AccountDraftCommitOrderReadGrpcService( + account.heldOrderOwner(NAMESPACE), NAMESPACE), + pki.accountServer, + pki); + try { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + accountServer.getPort()); + try (var read = + new DraftCommitOrderReadClient( + endpoints, + pki.worldClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + read.init(); + var writer = + new WorldDraftGraphApplicationService( + appliedRepository(), manager, new WorldDraftCommitOrderVerifier(read, NAMESPACE)); + assertThat(writer.apply(application).status()).isEqualTo("APPLIED"); + + // A real World APPLIED graph and checkpoint are retained first. The distinct + // publication selection/order below is explicitly stipulated; this isolates storage + // qualification and does not claim an authenticated Account HELD read. + String publicationRequest = "unqualified-" + UUID.randomUUID(); + var selection = publicationSelection(plan, publicationRequest, 1L); + var stipulatedOrder = stipulatedPublicationOrder(selection); + var evidence = publicationFreezeEvidence(plan, selection); + var unqualified = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + evidence, () -> checkpointRepository().capture(evidence, plan)))); + var authorizationRepository = publicationAuthorizationRepository(); + assertThat(authorizationRepository.readCommitted(unqualified)).isEmpty(); + var before = ownerSnapshot(world, plan); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> + authorizationRepository.retainOrRequireExact( + unqualified, stipulatedOrder, true))) + .satisfies(failure -> assertSqlState(failure, "P0002")); + assertThat(authorizationRepository.readCommitted(unqualified)).isEmpty(); + assertThat(ownerSnapshot(world, plan)).isEqualTo(before); + assertThat(before.publicationAuthorizationRows()).isEmpty(); + } + } finally { + stop(accountServer); + } + } + } + + private static void assertSqlState(Throwable failure, String expectedState) { + String sqlState = null; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sqlException) { + sqlState = sqlException.getSQLState(); + } + } + assertThat(sqlState).isEqualTo(expectedState); + } + private WorldDraftGraphApplicationRepository appliedRepository() { return new WorldDraftGraphApplicationRepository(dsl, fence, mapper); } + private void assertLegacyNumericWritesCannotChangeCanonicalFreshGraph( + Fixture fixture, WorldDraftTopologyCommitPlan plan) { + // Use only retained owner receipts/mappings for the private selectors; do not derive them from + // canonical UUIDs or assume Game Design's numeric selectors are World database keys. + long tenantKey = fixture.intake().localTenantKey(); + long versionKey = fixture.version().localVersionKey(); + assertThat(fixture.version().sourceIntakeReceipt().localTenantKey()).isEqualTo(tenantKey); + + when(gameDesignClient.getVersionState(tenantKey, versionKey)) + .thenReturn( + GetVersionStateResponse.newBuilder() + .setVersionState( + VersionStateSnapshot.newBuilder() + .setTenantId(Long.toString(tenantKey)) + .setVersionId(versionKey) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT) + .setVersionStateEpoch(1L) + .build()) + .build()); + + var owner = plan.ownerBinding(); + List mappedRegionIds = + dsl.resultQuery( + "SELECT private_row_key FROM world_authored_topology_identity " + + "WHERE target_namespace=? AND canonical_tenant_id=? " + + "AND canonical_version_id=? AND family='REGION'", + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId()) + .fetch(0, Long.class); + assertThat(mappedRegionIds).hasSize(1); + long mappedRegionId = mappedRegionIds.getFirst(); + Long aggregateEpoch = + dsl.resultQuery( + "SELECT draft_revision_epoch FROM world_design_aggregate_epoch " + + "WHERE tenant_id=? AND version_id=? AND aggregate_type='REGION' AND aggregate_id=?", + tenantKey, + versionKey, + mappedRegionId) + .fetchOne(0, Long.class); + assertThat(aggregateEpoch).isNotNull(); + + var before = ownerSnapshot(fixture, plan); + assertThat(before.currentRows()).hasSize(3); + assertThat(before.mappingRows()).hasSize(3); + assertThat(before.startLocationRows()).hasSize(1); + assertThat(before.publicationOwnerRows()).hasSize(1); + assertThat(before.publicationAttemptRows()).isEmpty(); + + var updateRequest = + legacyRegionMutation(tenantKey, versionKey, Long.toString(mappedRegionId), aggregateEpoch); + assertThatThrownBy(() -> mutationService.applyMutation(updateRequest)) + .satisfies( + failure -> + assertDatabaseGuardFailure( + failure, + "Mapped UUID World content cannot be changed by numeric writers", + "World tenant key is reserved for a canonical authored source")); + assertThat(ownerSnapshot(fixture, plan)).isEqualTo(before); + + var createRequest = legacyRegionMutation(tenantKey, versionKey, "", 0L); + assertThatThrownBy(() -> mutationService.applyMutation(createRequest)) + .satisfies( + failure -> + assertDatabaseGuardFailure( + failure, "World tenant key is reserved for a canonical authored source")); + assertThat(ownerSnapshot(fixture, plan)).isEqualTo(before); + } + + private static WorldDesignMutationRequestDto legacyRegionMutation( + long tenantKey, long versionKey, String aggregateId, long expectedEpoch) { + return new WorldDesignMutationRequestDto( + tenantKey, + versionKey, + "legacy-commit-" + UUID.randomUUID(), + "legacy-revision-" + UUID.randomUUID(), + "UPSERT", + "REGION", + aggregateId, + expectedEpoch, + "", + "", + 0L, + "", + new WorldDesignMutationRequestDto.RegionMutationDto( + "legacy-write", "clear", 8, 17L, "ROOM_GRAPH", "{}", 1.0d), + null, + null, + null, + null, + null, + null); + } + + private static void assertDatabaseGuardFailure(Throwable failure, String... messageFragments) { + String sqlState = null; + StringBuilder messages = new StringBuilder(); + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sqlException) { + sqlState = sqlException.getSQLState(); + } + if (cause.getMessage() != null) { + messages.append(cause.getMessage()).append('\n'); + } + } + assertThat(sqlState).isEqualTo("23514"); + String combinedMessages = messages.toString(); + assertThat(java.util.Arrays.stream(messageFragments).anyMatch(combinedMessages::contains)) + .isTrue(); + } + private WorldCanonicalFrozenTopologyRepository frozenRepository() { return new WorldCanonicalFrozenTopologyRepository( dsl, snapshots, new WorldDraftTopologyCommitRepository(dsl, fence, mapper), digestService); @@ -628,18 +931,34 @@ private WorldDesignMutationRevision.Builder mutation( .setScopeId(scope.toString()); } - private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) { + private WorldCanonicalFrozenTopology capture( + WorldDraftTopologyCommitPlan plan, + WorldDesignPublicationFenceEvidence evidence, + AccountPublicationAuthorizationBinding stipulatedAccountOrder) { var owner = plan.ownerBinding(); - String publicationRequest = "selector-" + UUID.randomUUID(); - // Stipulated test-only Game Design selection; no release/settlement is claimed. - var evidence = publicationFreezeEvidence(plan, publicationRequest); + String publicationRequest = evidence.publicationRequestId(); + var authorizationRepository = publicationAuthorizationRepository(); + var checkpointCaptured = new AtomicInteger(); var attempt = Objects.requireNonNull( ownerTransaction() .execute( - status -> - fence.claimFreeze( - evidence, () -> checkpointRepository().capture(evidence, plan)))); + status -> { + var frozen = + fence.claimFreeze( + evidence, + () -> { + var checkpoint = checkpointRepository().capture(evidence, plan); + checkpointCaptured.incrementAndGet(); + return checkpoint; + }); + var stored = + authorizationRepository.retainOrRequireExact( + frozen, stipulatedAccountOrder, checkpointCaptured.get() == 1); + assertThat(stored.canonicalBytes()) + .containsExactly(stipulatedAccountOrder.canonicalBytes()); + return frozen; + })); var tuples = plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() .map( @@ -679,6 +998,11 @@ private WorldSelectedDraftPublicationCheckpointRepository checkpointRepository() digestService); } + private WorldSelectedDraftPublicationAuthorizationRepository + publicationAuthorizationRepository() { + return new WorldSelectedDraftPublicationAuthorizationRepository(dsl); + } + private DraftOwnerSnapshot ownerSnapshot(Fixture fixture, WorldDraftTopologyCommitPlan plan) { long tenant = fixture.intake().localTenantKey(); long version = fixture.version().localVersionKey(); @@ -705,6 +1029,14 @@ private DraftOwnerSnapshot ownerSnapshot(Fixture fixture, WorldDraftTopologyComm + "WHERE tenant_id=? AND version_id=? ORDER BY aggregate_type,aggregate_id", tenant, version); + var mappingRows = + rowJson( + "SELECT to_jsonb(t)::text AS row_json FROM world_authored_topology_identity t " + + "WHERE target_namespace=? AND canonical_tenant_id=? AND canonical_version_id=? " + + "ORDER BY family,private_row_key", + fixture.owner().targetNamespace(), + fixture.owner().canonicalTenantId(), + fixture.owner().canonicalVersionId()); var scopeEpochRows = rowJson( "SELECT to_jsonb(t)::text AS row_json FROM world_design_scope_epoch t " @@ -723,6 +1055,12 @@ private DraftOwnerSnapshot ownerSnapshot(Fixture fixture, WorldDraftTopologyComm + "WHERE request_id=? OR commit_id=? ORDER BY request_id", plan.binding().requestId(), plan.binding().commitId()); + var startLocationRows = + rowJson( + "SELECT to_jsonb(t)::text AS row_json FROM world_draft_start_location_receipt t " + + "WHERE request_id=? OR commit_id=? ORDER BY request_id", + plan.binding().requestId(), + plan.binding().commitId()); var applicationRows = rowJson( "SELECT to_jsonb(t)::text AS row_json FROM world_draft_graph_application t " @@ -751,16 +1089,28 @@ private DraftOwnerSnapshot ownerSnapshot(Fixture fixture, WorldDraftTopologyComm fixture.owner().targetNamespace(), fixture.owner().canonicalTenantId(), version); + var publicationAuthorizationRows = + rowJson( + "SELECT to_jsonb(b)::text AS row_json FROM world_design_publication_account_binding b " + + "JOIN world_design_publication_fence_attempt a USING (publication_fence) " + + "WHERE a.target_namespace=? AND a.canonical_tenant_id=? AND a.version_id=? " + + "ORDER BY b.publication_fence", + fixture.owner().targetNamespace(), + fixture.owner().canonicalTenantId(), + version); return new DraftOwnerSnapshot( List.copyOf(currentRows), + mappingRows, aggregateEpochRows, scopeEpochRows, revisionRows, topologyRows, + startLocationRows, applicationRows, terminalIdentityRows, publicationOwnerRows, - publicationAttemptRows); + publicationAttemptRows, + publicationAuthorizationRows); } private List rowJson(String sql, Object... bindings) { @@ -769,14 +1119,89 @@ private List rowJson(String sql, Object... bindings) { private record DraftOwnerSnapshot( List currentRows, + List mappingRows, List aggregateEpochRows, List scopeEpochRows, List revisionRows, List topologyRows, + List startLocationRows, List applicationRows, List terminalIdentityRows, List publicationOwnerRows, - List publicationAttemptRows) {} + List publicationAttemptRows, + List publicationAuthorizationRows) {} + + private AuthoredDraftPublishSelectionBinding publicationSelection( + WorldDraftTopologyCommitPlan plan, String publicationRequest, long versionStateEpoch) { + var binding = plan.binding(); + var target = binding.target(); + return AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + publicationRequest, + Long.toString(versionStateEpoch), + "test-only stipulated immutable publication selection", + binding.requestId(), + binding.commitId(), + binding.digest()), + target, + binding, + new VisibilityFence( + target, + binding.requestId(), + binding.commitId(), + binding.digest(), + "[]", + java.time.OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + } + + private AccountPublicationAuthorizationBinding stipulatedPublicationOrder( + AuthoredDraftPublishSelectionBinding selection) { + return stipulatedPublicationOrder(selection, UUID.randomUUID(), UUID.randomUUID()); + } + + private AccountPublicationAuthorizationBinding stipulatedPublicationOrder( + AuthoredDraftPublishSelectionBinding selection, UUID operationId, UUID fenceId) { + UUID actor = UUID.randomUUID(); + return new AccountPublicationAuthorizationBinding( + operationId, + fenceId, + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + + private WorldDesignPublicationFenceEvidence publicationFreezeEvidence( + WorldDraftTopologyCommitPlan plan, AuthoredDraftPublishSelectionBinding selection) { + var owner = plan.ownerBinding(); + return new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + selection.intent().publishRequestId(), + selection.digest().substring("sha256:".length()), + Long.parseLong(selection.intent().expectedVersionStateEpoch()), + "publish:" + + owner.canonicalTenantId() + + ":publish-request:" + + selection.intent().publishRequestId()); + } private WorldDesignPublicationFenceEvidence publicationFreezeEvidence( WorldDraftTopologyCommitPlan plan, String publicationRequest) { diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java new file mode 100644 index 0000000000..413f924211 --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java @@ -0,0 +1,970 @@ +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.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +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.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldSelectedDraftPublicationFreezeServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = uuid("22222222-2222-4222-8222-222222222222"); + private static final long GAME_DESIGN_VERSION = 17L; + private static final long VERSION_EPOCH = 9L; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void callerAuthenticationPrecedesAnyRepositoryOrRemoteRead() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> + withoutPeer( + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-design-service"), + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(SecurityException.class); + + collaborators.verifyNoReadsOrWrites(); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void exactCommittedRetryUsesFrozenAccountCorrelationBeforeMutableRemoteReads() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + FrozenAttempt prior = frozen(fixture.evidence(), fixture.binding()); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.of(prior)); + when(collaborators.authorizationRepository.readCommitted(prior)) + .thenReturn(Optional.of(fixture.accountBinding())); + var service = service(fixture, collaborators); + + FrozenAttempt result = + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding())); + + assertThat(result).isEqualTo(prior); + verifyNoInteractions( + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient); + verify(collaborators.checkpointRepository, never()).capture(any(), any()); + verify(collaborators.fence, never()).claimFreeze(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void changedAccountOperationOrFenceDeniesAnOtherwiseExactRetry() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + FrozenAttempt prior = frozen(fixture.evidence(), fixture.binding()); + var changed = + accountBinding( + fixture.selection(), + uuid("33333333-3333-4333-8333-333333333333"), + fixture.accountBinding().fenceId()); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.of(prior)); + when(collaborators.authorizationRepository.readCommitted(prior)) + .thenReturn(Optional.of(fixture.accountBinding())); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> withGameDesign(() -> service.freeze(fixture.evidence(), fixture.plan(), changed))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("Account"); + verifyNoInteractions( + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient); + assertThat(collaborators.transactionManager.commits).isZero(); + + var changedFence = + accountBinding( + fixture.selection(), + fixture.accountBinding().operationId(), + uuid("14141414-1414-4414-8414-141414141414")); + assertThatThrownBy( + () -> + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), changedFence))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("Account"); + verifyNoInteractions( + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void unqualifiedHistoricalAttemptIsDeniedWithoutCurrentStateOrHeldResampling() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + FrozenAttempt prior = frozen(fixture.evidence(), fixture.binding()); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.of(prior)); + when(collaborators.authorizationRepository.readCommitted(prior)).thenReturn(Optional.empty()); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("no original Account"); + verifyNoInteractions( + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient); + verify(collaborators.fence, never()).claimFreeze(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void completeAccountSelectionRelationIsRejectedBeforeStorageOrTransport() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + var changedSelection = + selection(fixture.binding(), "changed-publication-request", VERSION_EPOCH, "different"); + var changedOrder = + accountBinding(changedSelection, uuid("15151515-1515-4515-8515-151515151515")); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), changedOrder))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("not exact"); + collaborators.verifyNoReadsOrWrites(); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void selectedReadMustEchoExactImmutableSelectionBeforeStateOrAccountReads() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.empty()); + when(collaborators.intakeRepository.read(NAMESPACE, fixture.evidence().intakeRequestId())) + .thenReturn(Optional.of(fixture.intake())); + var changedSelection = + selection(fixture.binding(), "other-selection", VERSION_EPOCH, "other immutable selection"); + when(collaborators.selectionClient.read(any())) + .thenAnswer( + invocation -> + selectionRead( + AuthoredDraftPublishSelectionReadEvidence.Request.create( + NAMESPACE, changedSelection))); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("selected Draft read"); + verify(collaborators.versionStateClient, never()).read(any()); + verify(collaborators.accountClient, never()).read(any()); + verify(collaborators.fence, never()).claimFreeze(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void firstFreezeReadsSelectionCurrentDraftAndAccountHeldBeforeOwnerTransaction() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + FrozenAttempt committed = frozen(fixture.evidence(), fixture.binding()); + when(collaborators.intakeRepository.read(NAMESPACE, fixture.evidence().intakeRequestId())) + .thenReturn(Optional.of(fixture.intake())); + when(collaborators.fence.readAttempt(fixture.evidence())) + .thenReturn(Optional.empty(), Optional.of(committed)); + when(collaborators.selectionClient.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return selectionRead(invocation.getArgument(0)); + }); + when(collaborators.versionStateClient.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH); + }); + when(collaborators.accountClient.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return accountRead(invocation.getArgument(0)); + }); + when(collaborators.checkpointRepository.capture(fixture.evidence(), fixture.plan())) + .thenReturn(fixture.checkpoint()); + when(collaborators.fence.claimFreeze(eq(fixture.evidence()), any())) + .thenAnswer( + invocation -> { + Checkpoint checkpoint = ((Supplier) invocation.getArgument(1)).get(); + return new FrozenAttempt( + fixture.evidence(), committed.publicationFence(), checkpoint); + }); + when(collaborators.authorizationRepository.retainOrRequireExact( + committed, fixture.accountBinding(), true)) + .thenReturn(fixture.accountBinding()); + when(collaborators.authorizationRepository.readCommitted(committed)) + .thenReturn(Optional.of(fixture.accountBinding())); + var service = service(fixture, collaborators); + + FrozenAttempt result = + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding())); + + assertThat(result).isEqualTo(committed); + assertThat(collaborators.transactionManager.commits).isEqualTo(1); + assertThat(collaborators.transactionManager.rollbacks).isZero(); + assertThat(collaborators.transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(collaborators.transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(collaborators.transactionManager.startedWith.isReadOnly()).isFalse(); + var order = + inOrder( + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient, + collaborators.fence, + collaborators.authorizationRepository); + order.verify(collaborators.selectionClient).read(any()); + order.verify(collaborators.versionStateClient).read(any()); + order.verify(collaborators.accountClient).read(any()); + order.verify(collaborators.fence).claimFreeze(eq(fixture.evidence()), any()); + order + .verify(collaborators.authorizationRepository) + .retainOrRequireExact(committed, fixture.accountBinding(), true); + verify(collaborators.checkpointRepository).capture(fixture.evidence(), fixture.plan()); + } + + @Test + void currentStateMustStillBeExactDraftEpochBeforeAccountReadOrFreeze() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + when(collaborators.intakeRepository.read(NAMESPACE, fixture.evidence().intakeRequestId())) + .thenReturn(Optional.of(fixture.intake())); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.empty()); + when(collaborators.selectionClient.read(any())) + .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); + when(collaborators.versionStateClient.read(any())) + .thenAnswer( + invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + VERSION_EPOCH)); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("DRAFT epoch"); + verify(collaborators.accountClient, never()).read(any()); + verify(collaborators.fence, never()).claimFreeze(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void staleCurrentEpochIsRejectedBeforeAccountReadOrFreeze() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + when(collaborators.intakeRepository.read(NAMESPACE, fixture.evidence().intakeRequestId())) + .thenReturn(Optional.of(fixture.intake())); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.empty()); + when(collaborators.selectionClient.read(any())) + .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); + when(collaborators.versionStateClient.read(any())) + .thenAnswer( + invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH + 1L)); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("DRAFT epoch"); + verify(collaborators.accountClient, never()).read(any()); + verify(collaborators.fence, never()).claimFreeze(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void changedCurrentSourceSelectorIsRejectedBeforeAccountReadOrFreeze() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + when(collaborators.intakeRepository.read(NAMESPACE, fixture.evidence().intakeRequestId())) + .thenReturn(Optional.of(fixture.intake())); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.empty()); + when(collaborators.selectionClient.read(any())) + .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); + when(collaborators.versionStateClient.read(any())) + .thenAnswer( + invocation -> { + AuthoredWorldVersionStateEvidence.Request expected = invocation.getArgument(0); + AuthoredWorldSourceEvidence changedSource = changedSource(fixture.source()); + var changedRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + expected.readRequestId(), + expected.canonicalTenantId(), + changedSource.worldSlug(), + changedSource.operationId(), + changedSource.evidenceDigest(), + expected.versionId()); + return AuthoredWorldVersionStateEvidence.create( + changedRequest, + changedSource, + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH); + }); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("DRAFT epoch"); + verify(collaborators.accountClient, never()).read(any()); + verify(collaborators.fence, never()).claimFreeze(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void accountReadMustEchoExactHeldOrderBeforeOwnerFreeze() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + when(collaborators.intakeRepository.read(NAMESPACE, fixture.evidence().intakeRequestId())) + .thenReturn(Optional.of(fixture.intake())); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.empty()); + when(collaborators.selectionClient.read(any())) + .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); + when(collaborators.versionStateClient.read(any())) + .thenAnswer( + invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH)); + var changed = accountBinding(fixture.selection(), uuid("16161616-1616-4616-8616-161616161616")); + when(collaborators.accountClient.read(any())) + .thenAnswer( + invocation -> + accountRead( + AccountPublicationAuthorizationReadEvidence.Request.create( + NAMESPACE, changed))); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("HELD read"); + verify(collaborators.fence, never()).claimFreeze(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void unavailableAccountReadDoesNotCreateOrAcknowledgeFreeze() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + when(collaborators.intakeRepository.read(NAMESPACE, fixture.evidence().intakeRequestId())) + .thenReturn(Optional.of(fixture.intake())); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.empty()); + when(collaborators.selectionClient.read(any())) + .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); + when(collaborators.versionStateClient.read(any())) + .thenAnswer( + invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH)); + when(collaborators.accountClient.read(any())) + .thenThrow(new IllegalStateException("Account authorization read unavailable")); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + verify(collaborators.fence, never()).claimFreeze(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void transactionFailureAfterClaimRollsBackAndReturnsNoAcknowledgement() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + FrozenAttempt claimed = frozen(fixture.evidence(), fixture.binding()); + when(collaborators.intakeRepository.read(NAMESPACE, fixture.evidence().intakeRequestId())) + .thenReturn(Optional.of(fixture.intake())); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.empty()); + when(collaborators.selectionClient.read(any())) + .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); + when(collaborators.versionStateClient.read(any())) + .thenAnswer( + invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH)); + when(collaborators.accountClient.read(any())) + .thenAnswer(invocation -> accountRead(invocation.getArgument(0))); + when(collaborators.checkpointRepository.capture(fixture.evidence(), fixture.plan())) + .thenReturn(fixture.checkpoint()); + when(collaborators.fence.claimFreeze(eq(fixture.evidence()), any())) + .thenAnswer( + invocation -> { + ((Supplier) invocation.getArgument(1)).get(); + return claimed; + }); + when(collaborators.authorizationRepository.retainOrRequireExact( + claimed, fixture.accountBinding(), true)) + .thenThrow( + new WorldDesignPublicationFenceRepository.ConflictException( + "qualification readback failed")); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("qualification readback"); + assertThat(collaborators.transactionManager.commits).isZero(); + assertThat(collaborators.transactionManager.rollbacks).isEqualTo(1); + verify(collaborators.fence).readAttempt(fixture.evidence()); + } + + @Test + void raceLoserCannotAttachAccountOrderToAnExistingUnqualifiedFreeze() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + FrozenAttempt unqualified = frozen(fixture.evidence(), fixture.binding()); + when(collaborators.intakeRepository.read(NAMESPACE, fixture.evidence().intakeRequestId())) + .thenReturn(Optional.of(fixture.intake())); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.empty()); + when(collaborators.selectionClient.read(any())) + .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); + when(collaborators.versionStateClient.read(any())) + .thenAnswer( + invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH)); + when(collaborators.accountClient.read(any())) + .thenAnswer(invocation -> accountRead(invocation.getArgument(0))); + when(collaborators.fence.claimFreeze(eq(fixture.evidence()), any())).thenReturn(unqualified); + when(collaborators.authorizationRepository.retainOrRequireExact( + unqualified, fixture.accountBinding(), false)) + .thenThrow( + new WorldDesignPublicationFenceRepository.ConflictException( + "unqualified race winner cannot be attached to this Account order")); + var service = service(fixture, collaborators); + + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("cannot be attached"); + verify(collaborators.checkpointRepository, never()).capture(any(), any()); + verify(collaborators.fence).readAttempt(fixture.evidence()); + assertThat(collaborators.transactionManager.commits).isZero(); + assertThat(collaborators.transactionManager.rollbacks).isEqualTo(1); + } + + @Test + void ambientTransactionIsRejectedBeforeAnyRead() { + Fixture fixture = fixture(); + var collaborators = new Collaborators(); + var service = service(fixture, collaborators); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.freeze( + fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + } finally { + TransactionSynchronizationManager.clear(); + } + collaborators.verifyNoReadsOrWrites(); + } + + private static WorldSelectedDraftPublicationFreezeService service( + Fixture fixture, Collaborators collaborators) { + return new WorldSelectedDraftPublicationFreezeService( + NAMESPACE, + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient, + collaborators.intakeRepository, + collaborators.fence, + collaborators.checkpointRepository, + collaborators.authorizationRepository, + collaborators.transactionManager); + } + + private static Fixture fixture() { + UUID versionIdentityOperation = uuid("44444444-4444-4444-8444-444444444444"); + UUID intakeRequest = uuid("55555555-5555-4555-8555-555555555555"); + UUID sourceOperation = uuid("77777777-7777-4777-8777-777777777777"); + UUID registrationRequest = uuid("88888888-8888-4888-8888-888888888888"); + String worldSlug = "violet-wilds"; + long sourceGameRow = 41L; + String gameDesignTenantKey = "gd-tenant-41"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequest, TENANT, "tenant-violet", worldSlug, "Violet Wilds"); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequest, + sourceOperation, + sourceRequestDigest, + TENANT, + "tenant-violet", + worldSlug, + "Violet Wilds", + sourceGameRow, + gameDesignTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequest, + sourceOperation, + sourceRequestDigest, + TENANT, + "tenant-violet", + worldSlug, + "Violet Wilds", + sourceGameRow, + gameDesignTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + String intakeRequestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, intakeRequest, source); + UUID intakeId = uuid("99999999-9999-4999-8999-999999999999"); + long localTenantKey = 502L; + String intakeReceiptDigest = + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, intakeId, intakeRequestDigest, source, localTenantKey); + var intake = + new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + intakeRequest, + intakeId, + TENANT, + worldSlug, + sourceOperation, + sourceEvidenceDigest, + intakeRequestDigest, + intakeReceiptDigest, + localTenantKey, + source); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + TENANT, + VERSION, + versionIdentityOperation, + GAME_DESIGN_VERSION, + intakeRequest, + intakeId, + intakeRequestDigest, + sourceOperation, + sourceEvidenceDigest, + intakeReceiptDigest); + TargetProof target = + new TargetProof( + TENANT, + VERSION, + GAME_DESIGN_VERSION, + gameDesignTenantKey, + sourceGameRow, + gameDesignTenantKey, + "NEW_GAME_ROW"); + UUID commitRequest = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID commitId = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + UUID revisionId = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + UUID aggregateId = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + var binding = + DraftCommitBinding.create( + target, + commitRequest, + commitId, + "base-commit", + List.of(new RevisionPayload("0", revisionId, Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "REGION", + aggregateId.toString(), + "AGGREGATE", + aggregateId.toString(), + "0"))); + WorldDraftTopologyCommitPlan plan = mock(WorldDraftTopologyCommitPlan.class); + when(plan.binding()).thenReturn(binding); + when(plan.ownerBinding()).thenReturn(owner); + String publicationRequest = "publication-request-17"; + var selection = + selection(binding, publicationRequest, VERSION_EPOCH, "stipulated immutable selection"); + var account = accountBinding(selection, uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee")); + var evidence = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + TENANT, + VERSION, + versionIdentityOperation, + GAME_DESIGN_VERSION, + intakeRequest, + intakeId, + intakeRequestDigest, + sourceOperation, + sourceEvidenceDigest, + intakeReceiptDigest, + publicationRequest, + selection.digest().substring("sha256:".length()), + VERSION_EPOCH, + "publish:" + TENANT + ":publish-request:" + publicationRequest); + Checkpoint checkpoint = new Checkpoint(commitId.toString(), "a".repeat(64), 3); + return new Fixture( + source, intake, owner, binding, plan, selection, account, evidence, checkpoint); + } + + private static AccountPublicationAuthorizationBinding accountBinding( + AuthoredDraftPublishSelectionBinding selection, UUID operationId) { + return accountBinding(selection, operationId, uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")); + } + + private static AccountPublicationAuthorizationBinding accountBinding( + AuthoredDraftPublishSelectionBinding selection, UUID operationId, UUID fenceId) { + return new AccountPublicationAuthorizationBinding( + operationId, + fenceId, + new AccountPublicationAuthorizationBinding.PreallocationInput( + uuid("12121212-1212-4212-8212-121212121212"), selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + "12121212-1212-4212-8212-121212121212", + "1", + "1", + null, + null, + new byte[] {1}))); + } + + private static AuthoredDraftPublishSelectionBinding selection( + DraftCommitBinding binding, String publicationRequest, long versionStateEpoch, String notes) { + var target = binding.target(); + return AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + publicationRequest, + Long.toString(versionStateEpoch), + notes, + binding.requestId(), + binding.commitId(), + binding.digest()), + target, + binding, + new VisibilityFence( + target, + binding.requestId(), + binding.commitId(), + binding.digest(), + "[]", + java.time.OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + } + + private static AuthoredWorldSourceEvidence changedSource(AuthoredWorldSourceEvidence source) { + UUID operationId = UUID.randomUUID(); + String worldSlug = "changed-" + UUID.randomUUID().toString().replace("-", ""); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + source.registrationRequestId(), + source.canonicalTenantId(), + source.tenantSlug(), + worldSlug, + source.worldDisplayName()); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + source.registrationRequestId(), + operationId, + requestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + worldSlug, + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + source.registrationRequestId(), + operationId, + requestDigest, + source.canonicalTenantId(), + source.tenantSlug(), + worldSlug, + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + evidenceDigest); + } + + private static FrozenAttempt frozen( + WorldDesignPublicationFenceEvidence evidence, DraftCommitBinding binding) { + return new FrozenAttempt( + evidence, + uuid("13131313-1313-4313-8313-131313131313"), + new Checkpoint(binding.commitId().toString(), "a".repeat(64), 3)); + } + + private static AuthoredDraftPublishSelectionReadEvidence selectionRead( + AuthoredDraftPublishSelectionReadEvidence.Request request) { + var evidence = mock(AuthoredDraftPublishSelectionReadEvidence.class); + when(evidence.request()).thenReturn(request); + return evidence; + } + + private static AccountPublicationAuthorizationReadEvidence accountRead( + AccountPublicationAuthorizationReadEvidence.Request request) { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(request); + return evidence; + } + + 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 UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + AuthoredWorldSourceEvidence source, + WorldAuthoredSourceIntakeReceipt intake, + OwnerBinding owner, + DraftCommitBinding binding, + WorldDraftTopologyCommitPlan plan, + AuthoredDraftPublishSelectionBinding selection, + AccountPublicationAuthorizationBinding accountBinding, + WorldDesignPublicationFenceEvidence evidence, + Checkpoint checkpoint) {} + + private static final class Collaborators { + final AuthoredDraftPublishSelectionReadClient selectionClient = + mock(AuthoredDraftPublishSelectionReadClient.class); + final AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + final AccountPublicationAuthorizationReadClient accountClient = + mock(AccountPublicationAuthorizationReadClient.class); + final WorldAuthoredSourceIntakeRepository intakeRepository = + mock(WorldAuthoredSourceIntakeRepository.class); + final WorldDesignPublicationFenceRepository fence = + mock(WorldDesignPublicationFenceRepository.class); + final WorldSelectedDraftPublicationCheckpointRepository checkpointRepository = + mock(WorldSelectedDraftPublicationCheckpointRepository.class); + final WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository = + mock(WorldSelectedDraftPublicationAuthorizationRepository.class); + final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + + void verifyNoReadsOrWrites() { + verifyNoInteractions( + selectionClient, + versionStateClient, + accountClient, + intakeRepository, + fence, + checkpointRepository, + authorizationRepository); + } + } + + private static final class RecordingTransactionManager + implements org.springframework.transaction.PlatformTransactionManager { + TransactionDefinition startedWith; + int commits; + int rollbacks; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commits++; + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + rollbacks++; + TransactionSynchronizationManager.clear(); + } + } +} From 2560d12a8265db943a06e43d1e9e261bb2cdd923 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:35:16 +1300 Subject: [PATCH 030/129] Bind publication terminal readback to immutable Account settlement --- .github/workflows/ci.yml | 4 +- .../account-service/api-contracts.md | 2 + .../world-management-service/api-contracts.md | 4 + design/project-management/ai-observations.md | 10 + ...ame-authoring-publishing-and-activation.md | 14 +- .../publication_terminal_read_service.proto | 41 + .../DraftAuthorizationFenceRepository.java | 3 +- ...ntPublicationAuthorizationReadService.java | 3 + ...untPublicationAuthorizationRepository.java | 97 +- ...ctedDraftPublicationSettlementService.java | 138 +++ ...ccount_selected_publication_settlement.sql | 167 ++++ ...issionWalBoundaryProofIntegrationTest.java | 699 ++++++++++++++ ...horizationMtlsPostgresIntegrationTest.java | 372 ++++++++ ...nAuthorizationPostgresIntegrationTest.java | 488 +++++++++- ...DraftPublicationSettlementServiceTest.java | 376 ++++++++ .../account-admission-wal-boundary-proof.sql | 250 +++++ .../WorldPublicationTerminalReadClient.java | 154 +++ .../WorldPublicationTerminalReadEvidence.java | 165 ++++ ...WorldPublicationTerminalReadGrpcCodec.java | 125 +++ ...orldPublicationTerminalReadClientTest.java | 233 +++++ ...ldPublicationTerminalReadEvidenceTest.java | 107 +++ ...dPublicationTerminalReadGrpcCodecTest.java | 124 +++ ...emptServiceTransactionIntegrationTest.java | 197 +++- ...GameDesignPublicationTerminalVerifier.java | 120 +++ ...rldPublicationTerminalReadGrpcService.java | 100 ++ .../WorldPublicationTerminalReadService.java | 120 +++ .../WorldPublicationTerminalRepository.java | 56 +- ...d_publication_terminal_account_binding.sql | 115 +++ ...dGraphSnapshotPostgresIntegrationTest.java | 41 +- ...FrozenTopologyPostgresIntegrationTest.java | 26 +- ...nceAssociationPostgresIntegrationTest.java | 108 ++- ...aphApplicationPostgresIntegrationTest.java | 888 +++++++++++++++++- ...ftRegionCommitPostgresIntegrationTest.java | 52 +- ...DesignPublicationTerminalVerifierTest.java | 776 +++++++++++++++ ...ublicationTerminalReadGrpcServiceTest.java | 110 +++ ...rldPublicationTerminalReadServiceTest.java | 44 + 36 files changed, 6222 insertions(+), 107 deletions(-) create mode 100644 protos/world-management/v1/publication_terminal_read_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java create mode 100644 services/account-service/src/main/resources/db/migration/V107__account_selected_publication_settlement.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java create mode 100644 services/account-service/src/test/resources/account-admission-wal-boundary-proof.sql create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodecTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifier.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V54__world_publication_terminal_account_binding.sql create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadServiceTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6c02b1552f..8d78dc28e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -992,7 +992,7 @@ jobs: id: checks run: | echo "::group::Run Module Validation" - ./gradlew :${{ matrix.module }}:check -PfullCheck + ./gradlew -Dorg.gradle.jvmargs='-Xmx3g -Dfile.encoding=UTF-8' --no-parallel --max-workers=2 :${{ matrix.module }}:check -PfullCheck echo "::endgroup::" - name: 📤 Capture owner integration test XML @@ -1054,7 +1054,7 @@ jobs: - name: 📦 Build Runtime JAR if: ${{ contains(fromJSON(needs.changes.outputs.bootable_modules), matrix.module) }} - run: ./gradlew :${{ matrix.module }}:bootJar -PfullCheck + run: ./gradlew -Dorg.gradle.jvmargs='-Xmx3g -Dfile.encoding=UTF-8' --no-parallel --max-workers=2 :${{ matrix.module }}:bootJar -PfullCheck - name: 📈 Parse Coverage % id: coverage diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3a5e24efc6..d34d1703cb 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -82,6 +82,8 @@ The standalone, unregistered `AccountPublicationAuthorizationReadService.ReadHel Account acquires this distinct publication order from the authenticated acting account and immutable Game Design Draft selection before World freeze. Its original actor, canonical tenant, selected-Draft digest, exact source versions and Account fence remain immutable across retry and recovery. The later World capture is correlated separately and must not rewrite the original order or its digest. Applicable source participation protects the authorized operation through actual World commit; a remote `HELD` sample alone is not commit-time protection. Participation may be released only after authenticated exact publication commit/abort readback, never from timeout, absence, a Draft terminal receipt or ambiguous publication evidence. Retained orders and their evidence remain immutable under forward-only migration. The current unregistered producer/read components do not yet establish this complete terminal settlement boundary. +Settlement compares two distinct authenticated owner results: Game Design's original immutable terminal and World's independently committed terminal for the same complete publication operation. `PUBLISHED` must agree with World `PUBLISHED`; Game Design `NO_PUBLICATION` must agree with World `ABORTED`. Both must bind the same complete original operation and terminal bytes. Account obtains the owner reads outside SQL, then serializes its immutable settlement receipt with the original order and sorted source locks. Only that exact committed receipt removes this order's pending participation; it does not rewrite the original authorization or clear another operation. Read correlation IDs are not settlement mutation identities: exact retries replay the original receipt even when new owner-read correlations are used. Once settled, an external `HELD` read must deny; internal exact historical validation remains available for recovery without minting fresh authority. Any disagreement or unresolved owner result preserves participation and grants no admission. + The selected-order composition authenticates the exact same-namespace Game Design caller, obtains the [immutable selected-Draft owner read](../game-design-service/api-contracts.md#immutable-selected-draft-publication-read) outside Account SQL, then passes the unchanged creator credential and exact retained selection to Account's current-actor/source-hold owner transaction. `SELECTED` alone is not actor authorization. No database lock may span that read, and unavailable or substituted selection evidence cannot create an order. Implementation and executed proof remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index b97262a8f5..05b5b64afb 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -108,6 +108,10 @@ Game Design completes the handoff through one outcome-typed terminal operation, Terminal retries are exact only when the complete request, digest, fence, outcome, and evidence match the stored terminal result. Changed or omitted input returns `IDEMPOTENCY_CONFLICT`; a conflicting nonterminal request, unknown fence, contradictory bundle/digest evidence, or unavailable owner read remains `RECONCILIATION_REQUIRED` and must not release the freeze. A failed or ambiguous publication therefore reuses the original `publicationRequestId` and `publicationFence` until WMS and Game Design agree on the durable bundle/version outcome; it cannot mint a second freeze or resume Draft writes by timeout. +First terminal completion and every terminal retry/readback must also compare the complete distinct Account publication-order bytes, operation ID and fence against the immutable qualification retained with the first World freeze. The older Account Draft `COMMIT_ORDER` inside the World application evidence is not that publication order. An unqualified historical freeze cannot be upgraded by supplying later terminal evidence. World verifies the original Game Design terminal through an authenticated owner read outside SQL; that immutable result remains historical evidence through the local commit, not a remote Account lock or permission to release Account source participation. + +Account settlement requires a separate World-authenticated terminal read. Its versioned request binds the namespace, non-nil read correlation ID, complete original publication operation and exact expected Game Design terminal bytes; those bytes identify the lookup and do not prove a World commit. Only the authenticated same-namespace Account workload may call it, and World must authenticate that caller before decoding or reading storage. World returns the exact request and original stored terminal bytes only after its own independent owner snapshot proves the qualified attempt and matching terminal phase (`PUBLISHED` or `ABORTED`). Missing, pending, unqualified, substituted, corrupt or unavailable owner evidence supplies no settlement result. The read never completes publication, releases an Account hold or authorizes admission; registration and executed proof remain separately gated in the implementation tracker. + World Management also exposes a read-only design-time synchronization surface so Game Design can validate convergence before publish: - `GetDraftDesignDigest(GetDraftDesignDigestRequest)` returns `{tenantId, scope, appliedCommitId, contentDigest, digestSchemaVersion}`. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 3de156fa40..15f9896df6 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -98,3 +98,13 @@ Entry format: - Observation: A global-frontier shortfall does not identify an unflushed target transaction. Conversely, record presence or a COMMIT start address alone does not establish durability; alignment, continuation pages, exact transaction identity and an independent flush observation matter. COMMIT record timestamps are not authenticated physical-flush deadline evidence. - Expected pattern: Preserve fail-closed acceptance while distinguishing an unavailable conservative proof from a demonstrated durability failure. A production exact-record recovery mechanism needs a supported locator, retained WAL availability, timeline/transaction-epoch checks and separate flush coverage; offline artifact decoding cannot silently replace that mechanism. - Current status: The production recovery path has no independent exact-COMMIT locator and remains denied. A bounded supported-mechanism proposal has been routed to Overseer; no database extension, privilege expansion, deadline relaxation or runtime activation is authorized by this diagnostic. + +- `2026-10-08`: Attribute composed CI to the actual checked-out merge parents + - Context: PR #3105 Validation run 37834941641 reported the expected child head and recorded base, but its checked-out synthetic merge's first parent differed from that base. + - Observation: Exact child-head metadata and passing owner tests do not establish which composed parent was executed. The reason for this parent discrepancy remains unresolved; no branch or queue change was inferred from it. + - Expected pattern: Retain the actual checkout commit, tree and ordered parents with physical test results. Credit executed cases to that composition and keep intended-parent alignment open until independently verified. + +- `2026-10-08`: Distinguish dependent compilation heap exhaustion from owner test failure + - Context: PR #3105 Game Session and TCP matrix jobs exhausted Gradle's 1.5 GiB Java heap while compiling dependent services, before owner integration tests ran. + - Observation: These jobs supplied no owner execution proof and no demonstrated semantic compiler error. Configuration-cache diagnostics were separate from the heap failure. + - Expected pattern: Preserve the complete validation tasks and artifact capture while applying a bounded resource profile, then require corrected-head CI. The local 3 GiB, nonparallel, two-worker profile is preparation, not proof that hosted compilation is repaired. 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 d1772ff28d..7086ba3b28 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 @@ -6,7 +6,15 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The current publication handoff batch has passing local unit XML for 302 Common, 1,067 Account, 341 Game Design and 533 World cases. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. Local database integration cases skip without Docker; final combined formatting, static checks, packaging and documentation validation are recorded with the published construction checkpoint. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. +The current publication handoff batch has passing local unit XML for 309 Common, 1,073 Account, 341 Game Design and 540 World cases, plus seven non-database Account integration cases. All 508 database integration definitions skip without Docker: 227 Account, 75 Game Design and 206 World. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. Four-owner formatting, static checks, packaging and documentation gates pass after the final World integration-fixture compilation correction; Flyway sanity covers 12 sets / 246 versioned files. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. + +Published-head `5132fb96b98f2d33b9db5d09d763aebb63efafb2` [Validation run 37834941641](https://github.com/benhook1013/FireMUD/actions/runs/37834941641) executed 229 Account, 75 Game Design and 202 World owner integration cases without skips. Game Design passed; Account retained one V92 original-acknowledgement WAL-coverage denial, and four World historical-upgrade fixtures failed after the additive full-XID column changed their copy/snapshot shapes. The bounded fixture correction preserves all historical fields and explicitly proves the new stamp stays null; corrected-head physical execution remains required. Game Session and TCP Proxy failed in dependent Java compilation with heap exhaustion, before their owner integration tests executed. The runner used synthetic merge `6d8435b7e31f5306defe357703139ccaa23e3fe6` with first parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`; these results do not close actual-parent alignment. Passing source intake mTLS cases do not separately establish the complete V53 qualification or genuine publication boundary. + +The terminal construction adds V54's bounded operation-frame check and repository checks against the complete distinct V53 Account publication qualification on first completion and exact retry/readback. Its unregistered Game Design terminal verifier authenticates before decoding and reads immutable owner evidence outside SQL; this is not a remote Account source lock. Qualified fixture changes preserve that distinction and retain the original order with the first freeze instead of attaching it later. The separate World-authenticated terminal read verifies independently committed World phase and exact original terminal backing. Account's unregistered composition obtains both strict authenticated owner reads outside SQL, then commits and separately reads back V107's immutable settlement receipt; only that exact receipt releases this order's pending source participation. Historical retry does not recapture current credentials, and an external `HELD` read denies after settlement. These are bounded construction components, not completed genuine handoffs; all four Gameplay prerequisites and runtime activation remain open. + +Expanded Game Design and World terminal repository/loopback-mTLS definitions retain actual local owner storage while stipulating upstream authorities. Account settlement's loopback-mTLS definition exercises its real creator/order/storage with two distinct strict clients, but the remote terminal endpoints and incoming Game Design context are stipulated. The independent Account readback connection checks commit before the second owner transaction; this is not an actual network lost-acknowledgement injection. These definitions require corrected-head physical execution and cannot establish a genuine multi-owner publication chain by themselves. The bounded CI heap-profile repair preserves full matrix validation and packaging tasks; its hosted outcome remains unproved. + +The isolated Account WAL investigation is test-only and leaves V92's conservative production denial unchanged. Its seven dedicated PostgreSQL 16 definitions compile/discover but all skip locally without Docker. They define transactional immutable locators, exact target COMMIT readback and restricted-reader recovery; synthetic ambiguity/identity/capability classifications do not prove physical epoch wrap, promotion, WAL recycling, an unrelated unflushed tail or insufficient target flush. Extension feasibility, physical positive/negative execution, locator retention and any production adoption remain separate gates. The shared PostgreSQL 18 baseline does not change the Account admission executors' PostgreSQL 16-only guards. Overseer-owned isolated [Pod admission run 37830726704](https://github.com/benhook1013/FireMUD/actions/runs/37830726704) passed the Account and Game Session CREATE/adversarial matrices plus UPDATE and ephemeral-container checks; Overseer reported the owned cluster deleted after the run. This is admission-only evidence. CNI/socket routing, kubelet UID/process correspondence, replacement races, shared-key closure and promotion readiness remain unproved; duplicate-SPKI rejection and activation denial are unchanged. @@ -16,9 +24,9 @@ The legacy World numeric mutation route lacks the target shared-lock handoff, bu The World selected-fresh-graph checkpoint callback derives its commit identity from the exact retained Account-bound `APPLIED` application, rather than a caller-supplied checkpoint. Under the shared owner lock it rechecks the complete current graph and epoch set and computes the schema-3 content digest. Construction CI at `60c507243987705094a3028e0b46f3bccd5d9504` executed the actual Account-order-to-World-APPLIED and selected-checkpoint cases. The standalone selected-publication freeze composition now obtains authenticated immutable selection, current Game Design Draft state and exact Account held-order reads outside SQL, then retains the complete Account binding atomically with the first World freeze. V53 denies late qualification of historical attempts. Exact committed retry verifies the stored order before recapturing mutable authority. New qualification/rollback definitions still require physical execution; their distinct Account publication order is explicitly stipulated, not a substitute for the genuine producer. This does not change the generic digest's synthetic highest-commit limitation, register a freeze RPC, settle either owner, or establish end-to-end publication authority. -The standalone Game Design terminal owner read verifies complete original operation and terminal backing in an independent read-only repeatable-read snapshot. Its closed transport follows the [exact terminal-read contract](../../architecture/microservices/game-design-service/api-contracts.md#exact-publication-terminal-read); owner/transport unit definitions do not establish physical authenticated terminal composition. The receiver remains unregistered. World completion and distinct Account settlement after both exact authenticated owner outcomes remain open. +The standalone Game Design terminal owner read verifies complete original operation and terminal backing in an independent read-only repeatable-read snapshot. Its closed transport follows the [exact terminal-read contract](../../architecture/microservices/game-design-service/api-contracts.md#exact-publication-terminal-read); owner/transport unit definitions do not establish physical authenticated terminal composition. The receiver remains unregistered. World completion and distinct Account settlement now have unregistered construction components, but their genuine composed producer and physical proof remain open. -The standalone Account selected-publication producer defines a distinct immutable authorization from the authenticated current initial creator, immutable selected Draft and original issuance/source/checkpoint evidence before World capture. Its unregistered owner reader permits only verified same-namespace Game Design or World Management workloads and checks exact retained participation and committed issuance in one independent snapshot. V106 permits new pre-freeze orders without World evidence while retaining immutable V103 evidence unchanged and checking it when present; retained-row upgrade execution remains unproved. Later World correlation cannot rewrite the Account order. Pending publication participates in source-writer and prepare-before-disclose guards, but authenticated exact terminal readback and settlement remain open. Producer, transport and database test definitions are not runtime activation. +The standalone Account selected-publication producer defines a distinct immutable authorization from the authenticated current initial creator, immutable selected Draft and original issuance/source/checkpoint evidence before World capture. Its unregistered owner reader permits only verified same-namespace Game Design or World Management workloads and checks exact retained participation and committed issuance in one independent snapshot. V106 permits new pre-freeze orders without World evidence while retaining immutable V103 evidence unchanged and checking it when present; retained-row upgrade execution remains unproved. Later World correlation cannot rewrite the Account order. Pending publication participates in source-writer and prepare-before-disclose guards; V107's exact immutable receipt removes only its settled order from those predicates. Genuine authenticated terminal composition and physical settlement proof remain open. Producer, transport and database test definitions are not runtime activation. Substantive construction CI [37827785558](https://github.com/benhook1013/FireMUD/actions/runs/37827785558) for `60c507243987705094a3028e0b46f3bccd5d9504` executed 229 Account, 201 World and 74 Game Design integration cases with no skips or errors. Game Design and World passed; Account had two failures. The signer generation/promotion identity correction and V103 terms-fixture correction passed their affected cases. One remaining Account concurrency test reused a frozen activity-statistics snapshot while waiting for a blocked creator; its observer correction requires corrected-head execution. Original-ack receipt recovery still fails closed against the conservative global WAL insert fence. Decoded target COMMIT boundaries were covered by the independently logged flush, but the production recovery path has no supported independent exact-COMMIT locator; this diagnostic does not weaken durability or deadline requirements. The run tested a synthetic merge whose first parent was `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`; it supplies no exact-integrated-base or ancestry-closure proof. Local PostgreSQL definitions remain skipped without Docker. diff --git a/protos/world-management/v1/publication_terminal_read_service.proto b/protos/world-management/v1/publication_terminal_read_service.proto new file mode 100644 index 0000000000..7c5a44d7e8 --- /dev/null +++ b/protos/world-management/v1/publication_terminal_read_service.proto @@ -0,0 +1,41 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Standalone authenticated readback of World-owned publication terminal state. +service WorldPublicationTerminalReadService { + rpc ReadPublicationTerminal(ReadPublicationTerminalRequest) + returns (ReadPublicationTerminalResponse); +} + +enum WorldPublicationTerminalReadOutcome { + WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_UNSPECIFIED = 0; + WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_PUBLISHED = 1; + WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_ABORTED = 2; +} + +message ReadPublicationTerminalRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical game-design-publication-operation/v1 bytes; lookup data, not authority. + bytes original_operation = 4; + // Exact expected Game Design terminal bytes; never interpreted as World-authenticated proof. + bytes expected_game_design_terminal_evidence = 5; +} + +message ReadPublicationTerminalResponse { + // The complete request tuple is echoed byte-for-byte. + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_operation = 4; + bytes expected_game_design_terminal_evidence = 5; + // World-owned terminal phase, distinct from the producer/outcome in the embedded GDS bytes. + WorldPublicationTerminalReadOutcome world_outcome = 6; + // Complete immutable Game Design terminal bytes actually retained by the World owner. + bytes world_terminal_evidence = 7; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 5d24429b60..b8b17ebcfd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -314,7 +314,8 @@ public void requirePublicationAdmission(List sources) { private boolean hasPendingPublication(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( - "SELECT operation_id FROM account_selected_publication_sources WHERE source_key = ?", + "SELECT operation_id FROM account_selected_publication_sources" + + " WHERE source_key = ? AND NOT account_selected_publication_is_settled(operation_id)", source.key()) .isEmpty()) { return true; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java index fd596bb3d8..aabbb848e7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java @@ -16,6 +16,9 @@ public final class AccountPublicationAuthorizationReadService { private final String trustedNamespace; private final TransactionTemplate ownerTransaction; + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner persistence collaborator.") public AccountPublicationAuthorizationReadService( AccountPublicationAuthorizationRepository repository, PlatformTransactionManager transactions, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java index ebfcd210b3..2970647349 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java @@ -4,6 +4,8 @@ import java.util.Arrays; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; @@ -11,7 +13,9 @@ import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Owner-transaction persistence only; no caller-carried terminal proof is accepted. */ +/** + * Internal owner-transaction storage; remote evidence must first be authenticated by composition. + */ public final class AccountPublicationAuthorizationRepository { private final DSLContext dsl; @@ -79,10 +83,25 @@ AccountPublicationAuthorizationBinding authorize( /** Exact owner read; caller-carried structure alone can never establish HELD. */ public void readHeld(AccountPublicationAuthorizationBinding requested) { + readOriginal(requested); + if (dsl.fetchOne( + "SELECT 1 FROM account_selected_publication_settlements WHERE operation_id = ?", + requested.operationId()) + != null) { + throw new IllegalArgumentException("Publication authorization is already settled"); + } + } + + /** Historical validation uses the original committed issuance, never current credentials. */ + private void readOriginal(AccountPublicationAuthorizationBinding requested) { requireTransaction(); Objects.requireNonNull(requested); // Sources precede the operation. No transport is permitted in this owner transaction. - for (var source : requested.sources()) { + for (var source : + requested.sources().stream() + .sorted( + java.util.Comparator.comparing(DraftAuthorizationFenceBinding.SourceEvidence::key)) + .toList()) { if (dsl.fetchOne( "SELECT source_key FROM account_draft_authorization_source_locks" + " WHERE source_key = ? FOR UPDATE", @@ -165,6 +184,80 @@ public void readHeld(AccountPublicationAuthorizationBinding requested) { } } + /** + * Persist only after strict authenticated reads from both owners, outside this transaction. + * Structure alone is not owner authentication. World retains the same complete terminal bytes + * with PUBLISHED or ABORTED phase. Transport request IDs deliberately do not enter identity. + */ + public byte[] settle( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence gameDesign, + String worldOutcome, + byte[] worldTerminalEvidence) { + requireTransaction(); + operation = GameDesignPublicationOperationBinding.fromStored(operation.canonicalBytes()); + gameDesign = GameDesignPublicationTerminalEvidence.fromStored(gameDesign.canonicalBytes()); + var world = GameDesignPublicationTerminalEvidence.fromStored(worldTerminalEvidence); + String expectedPhase = + gameDesign.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + if (!expectedPhase.equals(worldOutcome) + || !Arrays.equals(operation.canonicalBytes(), gameDesign.operationBytes()) + || !Arrays.equals(gameDesign.canonicalBytes(), world.canonicalBytes())) { + throw new IllegalArgumentException("Exact publication owner outcomes disagree"); + } + readOriginal(operation.account()); + byte[] receipt = settlementReceipt(operation, gameDesign, worldOutcome, worldTerminalEvidence); + Record prior = + dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + operation.account().operationId()); + if (prior != null) { + if (!Arrays.equals(receipt, prior.get("receipt", byte[].class))) { + throw new IllegalArgumentException("Changed original publication settlement"); + } + return prior.get("receipt", byte[].class); + } + dsl.execute( + "INSERT INTO account_selected_publication_settlements" + + " (operation_id, fence_id, account_binding, publication_operation," + + " game_design_outcome, game_design_terminal, world_outcome, world_terminal, receipt)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + operation.account().operationId(), + operation.account().fenceId(), + operation.account().canonicalBytes(), + operation.canonicalBytes(), + gameDesign.outcome().name(), + gameDesign.canonicalBytes(), + worldOutcome, + worldTerminalEvidence, + receipt); + Record retained = + dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + operation.account().operationId()); + if (retained == null || !Arrays.equals(receipt, retained.get("receipt", byte[].class))) { + throw new IllegalStateException("Exact publication settlement readback is absent"); + } + return retained.get("receipt", byte[].class); + } + + private static byte[] settlementReceipt( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence gameDesign, + String worldOutcome, + byte[] worldTerminalEvidence) { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, gameDesign.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, worldOutcome); + DraftAuthorizationFenceBinding.frame(out, worldTerminalEvidence); + return out.toByteArray(); + } + private void requireExact( Record row, AccountPublicationAuthorizationBinding binding, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java new file mode 100644 index 0000000000..53bb5ffb78 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java @@ -0,0 +1,138 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered composition of two authenticated owner reads and Account's immutable receipt. + * Historical settlement grants neither creator authority nor runtime admission. + */ +public final class AccountSelectedDraftPublicationSettlementService { + private final AccountPublicationAuthorizationRepository repository; + private final GameDesignPublicationTerminalReadClient gameDesignClient; + private final WorldPublicationTerminalReadClient worldClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal owner persistence and strict mTLS clients.") + public AccountSelectedDraftPublicationSettlementService( + AccountPublicationAuthorizationRepository repository, + GameDesignPublicationTerminalReadClient gameDesignClient, + WorldPublicationTerminalReadClient worldClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient); + this.worldClient = Objects.requireNonNull(worldClient); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** Caller bytes identify the original order; only independent authenticated owners settle it. */ + public byte[] settle(byte[] originalOperation) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + var operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); + if (!Arrays.equals(originalOperation, operation.canonicalBytes()) + || !workloadNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException("Exact original publication operation namespace required"); + } + var gameDesignRequest = + GameDesignPublicationTerminalReadEvidence.Request.create(workloadNamespace, operation); + var gameDesign = gameDesignClient.read(gameDesignRequest); + if (gameDesign == null + || !gameDesignRequest.equals(gameDesign.request()) + || gameDesign.terminalEvidence() == null) { + throw new IllegalStateException("Game Design terminal differs from exact owner read request"); + } + var terminal = + GameDesignPublicationTerminalEvidence.fromStored( + gameDesign.terminalEvidence().canonicalBytes()); + if (!Arrays.equals(operation.canonicalBytes(), terminal.operationBytes())) { + throw new IllegalStateException("Game Design terminal substitutes original operation"); + } + requireNoAmbientTransaction(); + var worldRequest = + WorldPublicationTerminalReadEvidence.Request.create( + workloadNamespace, operation.canonicalBytes(), terminal.canonicalBytes()); + var world = worldClient.read(worldRequest); + if (world == null + || !worldRequest.equals(world.request()) + || world.worldOutcome() != worldRequest.expectedWorldOutcome() + || world.terminalEvidence() == null + || !Arrays.equals(operation.canonicalBytes(), world.terminalEvidence().operationBytes()) + || !Arrays.equals(terminal.canonicalBytes(), world.terminalEvidence().canonicalBytes()) + || !Arrays.equals(terminal.canonicalBytes(), world.worldTerminalEvidence())) { + throw new IllegalStateException("World terminal differs from exact independent owner read"); + } + requireNoAmbientTransaction(); + byte[] receipt = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository.settle( + operation, + terminal, + world.worldOutcome().name(), + world.worldTerminalEvidence()))); + // A second transaction establishes post-commit historical readback; no new issuer or + // credential capture is involved. Neither SQL phase can contain an owner RPC. + requireNoAmbientTransaction(); + byte[] committed = + ownerTransaction.execute( + ignored -> + repository.settle( + operation, + terminal, + world.worldOutcome().name(), + world.worldTerminalEvidence())); + if (!Arrays.equals(receipt, committed)) { + throw new IllegalStateException("Committed Account settlement readback differs from receipt"); + } + return receipt; + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Publication settlement requires no ambient transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V107__account_selected_publication_settlement.sql b/services/account-service/src/main/resources/db/migration/V107__account_selected_publication_settlement.sql new file mode 100644 index 0000000000..77a8ef1b66 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V107__account_selected_publication_settlement.sql @@ -0,0 +1,167 @@ +-- Internal persistence after authenticated exact reads from BOTH publication owners. Decoding +-- these bytes does not authenticate either remote owner and is not an external write surface. +CREATE TABLE account_selected_publication_settlements ( + operation_id UUID PRIMARY KEY REFERENCES account_selected_publication_authorizations(operation_id), + fence_id UUID NOT NULL, + account_binding BYTEA NOT NULL CHECK (octet_length(account_binding) BETWEEN 1 AND 1048576), + publication_operation BYTEA NOT NULL CHECK (octet_length(publication_operation) BETWEEN 1 AND 8388608), + game_design_outcome VARCHAR(32) NOT NULL CHECK (game_design_outcome IN ('PUBLISHED', 'NO_PUBLICATION')), + game_design_terminal BYTEA NOT NULL CHECK (octet_length(game_design_terminal) BETWEEN 1 AND 16777216), + world_outcome VARCHAR(16) NOT NULL CHECK (world_outcome IN ('PUBLISHED', 'ABORTED')), + world_terminal BYTEA NOT NULL CHECK (world_terminal = game_design_terminal), + receipt BYTEA NOT NULL CHECK (octet_length(receipt) BETWEEN 1 AND 50331648), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + settled_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK ((game_design_outcome = 'PUBLISHED' AND world_outcome = 'PUBLISHED') + OR (game_design_outcome = 'NO_PUBLICATION' AND world_outcome = 'ABORTED')) +); + +-- [jooq ignore start] +CREATE FUNCTION account_selected_publication_settlement_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_selected_publication_authorizations%ROWTYPE; + issuer account_control_ui_issuance_operations%ROWTYPE; + source_key_value TEXT; + p INTEGER; + parsed BYTEA; + world_bytes BYTEA; + world JSONB; + selection JSONB; + input_bytes BYTEA; + terminal_frames BYTEA[] := ARRAY[]::BYTEA[]; + receipt_frames BYTEA[] := ARRAY[]::BYTEA[]; + i INTEGER; +BEGIN + -- Same canonical source-before-operation order as source writers. Never wait backwards on + -- issuance, whose producers take it before sources. Nothing here performs a remote read. + FOR source_key_value IN SELECT source_key FROM account_selected_publication_sources + WHERE operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(source_key) LOOP + PERFORM source_key FROM account_draft_authorization_source_locks + WHERE source_key = source_key_value FOR UPDATE; + END LOOP; + SELECT * INTO STRICT original FROM account_selected_publication_authorizations + WHERE operation_id = NEW.operation_id FOR UPDATE; + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations + WHERE operation_id = original.issuance_operation_id FOR UPDATE NOWAIT; + IF NEW.producer_xid <> txid_current() OR NEW.fence_id <> original.fence_id + OR NEW.account_binding <> original.binding OR issuer.status <> 'COMMITTED' + OR issuer.source_payload <> original.source_payload + OR issuer.bundle_payload <> original.issuance_bundle THEN + RAISE EXCEPTION 'Settlement differs from exact original committed Account order' USING ERRCODE = '23514'; + END IF; + p := 1; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF parsed <> convert_to('game-design-publication-operation/v1', 'UTF8') THEN + RAISE EXCEPTION 'Invalid publication operation schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF parsed <> original.binding THEN + RAISE EXCEPTION 'Substituted original Account order' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_bytes, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF p <> octet_length(NEW.publication_operation) + 1 OR octet_length(world_bytes) = 0 THEN + RAISE EXCEPTION 'Incomplete publication operation' USING ERRCODE = '23514'; + END IF; + world := convert_from(world_bytes, 'UTF8')::JSONB; + -- Retrieve the original immutable selection, without recapturing current authority. + p := 1; + FOR i IN 1..4 LOOP + SELECT frame_value, next_position INTO input_bytes, p FROM account_publication_authorization_read_frame(original.binding, p); + END LOOP; + p := 1; + FOR i IN 1..3 LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(input_bytes, p); + END LOOP; + selection := convert_from(parsed, 'UTF8')::JSONB; + IF world->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR world->'request'->>'canonicalTenantId' IS DISTINCT FROM original.tenant_uuid::TEXT + OR world->'request'->>'canonicalVersionId' IS DISTINCT FROM selection->'intent'->>'canonicalVersionId' + OR world->'request'->>'publicationRequestId' IS DISTINCT FROM original.publish_request_id + OR world->'request'->>'versionStateEpoch' IS DISTINCT FROM selection->'intent'->>'expectedVersionStateEpoch' + OR world->'request'->>'appliedCommitId' IS DISTINCT FROM selection->'intent'->>'selectedCommitId' + OR 'sha256:' || (world->'request'->>'requestDigest') IS DISTINCT FROM + 'sha256:' || encode(sha256(parsed), 'hex') + OR (original.world_evidence IS NOT NULL AND original.world_evidence <> world_bytes) THEN + RAISE EXCEPTION 'Publication World evidence differs from original selected order' USING ERRCODE = '23514'; + END IF; + p := 1; + WHILE p <= octet_length(NEW.game_design_terminal) LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.game_design_terminal, p); + terminal_frames := array_append(terminal_frames, parsed); + IF cardinality(terminal_frames) > 5 THEN + RAISE EXCEPTION 'Trailing publication terminal fields' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF terminal_frames[1] IS DISTINCT FROM convert_to('game-design-publication-terminal/v1', 'UTF8') + OR terminal_frames[2] IS DISTINCT FROM NEW.publication_operation + OR terminal_frames[3] IS DISTINCT FROM convert_to(NEW.game_design_outcome, 'UTF8') + OR cardinality(terminal_frames) <> CASE WHEN NEW.game_design_outcome = 'PUBLISHED' THEN 5 ELSE 3 END THEN + RAISE EXCEPTION 'Changed complete publication terminal relationship' USING ERRCODE = '23514'; + END IF; + IF NEW.game_design_outcome = 'PUBLISHED' THEN + IF convert_from(terminal_frames[5], 'UTF8') !~ '^[1-9][0-9]*$' + OR convert_from(terminal_frames[5], 'UTF8')::BIGINT <> + (world->'request'->>'versionStateEpoch')::BIGINT + 1 THEN + RAISE EXCEPTION 'Changed committed publication epoch' USING ERRCODE = '23514'; + END IF; + -- Game Design owns release semantics. Its canonical codec and the authenticated owner + -- read validate the opaque complete content; Account binds all its exact bytes here. + IF octet_length(terminal_frames[4]) = 0 THEN + RAISE EXCEPTION 'Missing complete published release content' USING ERRCODE = '23514'; + END IF; + END IF; + p := 1; + WHILE p <= octet_length(NEW.receipt) LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.receipt, p); + receipt_frames := array_append(receipt_frames, parsed); + IF cardinality(receipt_frames) > 6 THEN + RAISE EXCEPTION 'Trailing settlement receipt' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF receipt_frames IS DISTINCT FROM ARRAY[convert_to('account-selected-publication-settlement/v1', 'UTF8'), + NEW.account_binding, NEW.publication_operation, NEW.game_design_terminal, + convert_to(NEW.world_outcome, 'UTF8'), NEW.world_terminal] THEN + RAISE EXCEPTION 'Changed exact settlement receipt' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_selected_publication_settlement_insert BEFORE INSERT + ON account_selected_publication_settlements FOR EACH ROW + EXECUTE FUNCTION account_selected_publication_settlement_guard(); +CREATE TRIGGER account_selected_publication_settlement_immutable BEFORE UPDATE OR DELETE + ON account_selected_publication_settlements FOR EACH ROW + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_publication_settlement_no_truncate BEFORE TRUNCATE + ON account_selected_publication_settlements FOR EACH STATEMENT + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +-- No old authorization/source row is rewritten or qualified. Only receipts committed through +-- the insert guard settle their exact original order; every other order remains pending. +CREATE FUNCTION account_selected_publication_is_settled(operation_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT EXISTS (SELECT 1 FROM account_selected_publication_settlements s + JOIN account_selected_publication_authorizations a ON a.operation_id = s.operation_id + WHERE s.operation_id = operation_value AND s.account_binding = a.binding AND s.fence_id = a.fence_id); +$$; + +-- Keep every V103 Draft/order/source/terms guard and change only publication pending detection. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ RAISE EXCEPTION 'Distinct selected-publication operation remains pending' USING ERRCODE = '55P03';$anchor$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V103 pending publication guard'; + END IF; + EXECUTE replace(original, anchor, + ' IF NOT account_selected_publication_is_settled(operation_value) THEN' || chr(10) + || anchor || chr(10) || ' END IF;'); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java new file mode 100644 index 0000000000..d383853188 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java @@ -0,0 +1,699 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.JSONB; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DelegatingDataSource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Isolated investigation, not production extension adoption or admission proof. + * + *

Actual unchanged original/receipt transactions retain test-only lower search locators. + * Synthetic classifier cases explicitly do not prove physical wraparound, promotion, recycle, + * unrelated unflushed tails or insufficient-flush behavior. Production V92 remains unchanged. + */ +@Testcontainers(disabledWithoutDocker = true) +@Execution(ExecutionMode.SAME_THREAD) +class AccountGameplayAdmissionWalBoundaryProofIntegrationTest { + // Deliberately owns its container: never honors the shared fixture's external database override. + // PG18 is rejected by the unchanged production executors and V92. + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>("postgres:16-alpine") + .withCommand("postgres", "-c", "fsync=on", "-c", "synchronous_commit=on"); + + private static final String TENANT = "22222222-2222-4222-8222-222222222222"; + private static final String OTHER = "33333333-3333-4333-8333-333333333333"; + private static final String RECORD = + "{\"start_lsn\":\"0/1000020\",\"end_lsn\":\"0/1000048\"," + + "\"xid\":\"100\",\"resource_manager\":\"Transaction\",\"record_type\":\"COMMIT\"}"; + + @BeforeAll + static void installIsolatedExtension() { + var admin = + DSL.using( + source(null, POSTGRES.getUsername(), POSTGRES.getPassword()), SQLDialect.POSTGRES); + assertThat( + admin + .fetchSingle("SELECT current_setting('server_version_num')::integer") + .get(0, Integer.class)) + .isBetween(160000, 169999); + // Missing image module fails visibly; do not silently skip or provision another image. + assertThat( + admin + .fetchSingle( + "SELECT EXISTS(SELECT 1 FROM pg_available_extensions WHERE name = 'pg_walinspect')") + .get(0, Boolean.class)) + .isTrue(); + admin.execute("CREATE SCHEMA wal_proof_extension"); + admin.execute("REVOKE ALL ON SCHEMA wal_proof_extension FROM PUBLIC"); + admin.execute("CREATE EXTENSION pg_walinspect WITH SCHEMA wal_proof_extension VERSION '1.1'"); + } + + @Test + void locatorsCommitAndRollBackWithTheirExactOriginalAndReceiptTransactions() { + var context = context(); + var evidence = pending(context); + UUID decision = UUID.randomUUID(); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + context + .transaction() + .executeWithoutResult( + status -> { + repository.recordCommitted(evidence, decision); + assertThat(context.dsl().fetchCount(DSL.table("wal_proof_locators"))).isEqualTo(1); + assertThat(independent(context).fetchCount(DSL.table("wal_proof_locators"))).isZero(); + assertThat(operation(independent(context), evidence).get("status", String.class)) + .isEqualTo("PENDING"); + status.setRollbackOnly(); + }); + assertThat(independent(context).fetchCount(DSL.table("wal_proof_locators"))).isZero(); + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(context.source()) + .execute(evidence, decision); + var originalLocator = locator(context, evidence, "original"); + assertThat(originalLocator.get("target_xid", String.class)) + .isEqualTo(acknowledgement.finalizationXid()); + context + .transaction() + .executeWithoutResult( + status -> { + new AccountGameplayAdmissionOriginalAckReceiptRepository(context.dsl(), repository) + .create(acknowledgement); + assertThat(context.dsl().fetchCount(DSL.table("wal_proof_locators"))).isEqualTo(2); + assertThat(independent(context).fetchCount(DSL.table("wal_proof_locators"))) + .isEqualTo(1); + assertThat( + independent(context) + .fetchCount( + DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isZero(); + status.setRollbackOnly(); + }); + assertThat(independent(context).fetchCount(DSL.table("wal_proof_locators"))).isEqualTo(1); + assertThat(locator(context, evidence, "original").intoMap()) + .isEqualTo(originalLocator.intoMap()); + // No receipt COMMIT or original-bound receipt has been manufactured by this experiment. + var proof = read(context, evidence, decision, "original"); + assertThat(proof.get("original_bound", Long.class)).isNull(); + assertCovered(context, proof); + } + + @Test + void freshConnectionLocatesExactReceiptCommitAfterLostAcknowledgementWithoutRestamping() { + var context = context(); + var evidence = pending(context); + UUID decision = UUID.randomUUID(); + var loseNextCommit = new AtomicBoolean(); + var source = lostAcknowledgementSource(context.source(), loseNextCommit); + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(source).execute(evidence, decision); + loseNextCommit.set(true); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source) + .confirm(acknowledgement)) + .hasMessageContaining("Account receipt physical COMMIT unavailable"); + var operationBefore = operation(independent(context), evidence).intoMap(); + var receiptBefore = receipt(context, evidence).intoMap(); + var locatorsBefore = + independent(context).fetch("SELECT * FROM wal_proof_locators ORDER BY phase").intoMaps(); + assertThat(locatorsBefore).hasSize(2); + assertThat(locator(context, evidence, "receipt").get("target_xid", String.class)) + .isEqualTo(receiptBefore.get("receipt_xid")) + .isNotEqualTo(acknowledgement.finalizationXid()); + // The probe uses its restricted independent connection, not V92 or a fresh confirming write. + var receiptProof = read(context, evidence, decision, "receipt"); + var originalProof = read(context, evidence, decision, "original"); + assertCovered(context, receiptProof); + assertCovered(context, originalProof); + assertThat(receiptProof.get("original_bound", Long.class)) + .isEqualTo(acknowledgement.committedBeforeMs()); + assertThat(receiptProof.get("unchanged_expiry", Long.class)).isEqualTo(expiry(evidence)); + assertThat(operation(independent(context), evidence).intoMap()).isEqualTo(operationBefore); + assertThat(receipt(context, evidence).intoMap()).isEqualTo(receiptBefore); + assertThat( + independent(context) + .fetch("SELECT * FROM wal_proof_locators ORDER BY phase") + .intoMaps()) + .isEqualTo(locatorsBefore); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(source) + .execute(evidence, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + } + + @Test + void physicalOriginalCommitAndLocatorCannotReplaceLostOriginalAcknowledgement() { + var context = context(); + var evidence = pending(context); + UUID decision = UUID.randomUUID(); + var source = lostAcknowledgementSource(context.source(), new AtomicBoolean(true)); + var executor = new AccountGameplayAdmissionOriginalCommitExecutor(source); + assertThatThrownBy(() -> executor.execute(evidence, decision)) + .hasMessageContaining("Original Account physical COMMIT unavailable"); + assertThat(operation(independent(context), evidence).get("status", String.class)) + .isEqualTo("COMMITTED"); + assertThat(locator(context, evidence, "original")).isNotNull(); + var diagnostic = read(context, evidence, decision, "original"); + assertCovered(context, diagnostic); + assertThat(diagnostic.get("original_bound", Long.class)).isNull(); + assertThat( + independent(context) + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isZero(); + assertThatThrownBy(() -> executor.execute(evidence, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); + assertThatThrownBy(() -> read(context, evidence, decision, "receipt")) + .hasMessageContaining("locator unavailable"); + } + + @Test + void restrictedReaderCannotUseRawWalOrMutateLocatorsAndRevocationDeniesProof() { + var context = context(); + var evidence = pending(context); + UUID decision = UUID.randomUUID(); + new AccountGameplayAdmissionOriginalCommitExecutor(context.source()) + .execute(evidence, decision); + var reader = DSL.using(context.reader(), SQLDialect.POSTGRES); + assertThat( + reader + .fetchSingle("SELECT pg_has_role(current_user, 'pg_read_server_files', 'MEMBER')") + .get(0, Boolean.class)) + .isFalse(); + assertThatThrownBy( + () -> + reader.fetch( + "SELECT * FROM wal_proof_extension.pg_get_wal_records_info('0/1000000','0/1000048')")) + .hasMessageContaining("permission denied"); + // Schema USAGE alone does not grant direct function EXECUTE. + context + .dsl() + .execute("GRANT USAGE ON SCHEMA wal_proof_extension TO " + context.schema() + "_reader"); + assertThatThrownBy( + () -> + reader.fetch( + "SELECT * FROM wal_proof_extension.pg_get_wal_records_info('0/1000000','0/1000048')")) + .hasMessageContaining("permission denied for function"); + assertThatThrownBy(() -> reader.fetch("SELECT * FROM wal_proof_locators")) + .hasMessageContaining("permission denied"); + assertThatThrownBy(() -> reader.execute("UPDATE wal_proof_locators SET target_xid = '1'")) + .hasMessageContaining("permission denied"); + assertThatThrownBy(() -> reader.execute("SET ROLE " + context.schema() + "_owner")) + .hasMessageContaining("permission denied"); + assertThatThrownBy( + () -> + reader.execute( + "ALTER TABLE account_gameplay_admission_lease_operations DISABLE TRIGGER wal_proof_original_capture")) + .hasMessageContaining("must be owner"); + assertCovered(context, read(context, evidence, decision, "original")); + assertThatThrownBy(() -> read(context, evidence, UUID.randomUUID(), "original")) + .hasMessageContaining("identity unavailable"); + assertThatThrownBy(() -> read(context, changedDigest(evidence), decision, "original")) + .hasMessageContaining("identity unavailable"); + context + .dsl() + .execute( + "REVOKE EXECUTE ON FUNCTION wal_proof_extension.pg_get_wal_records_info(pg_lsn, pg_lsn) FROM " + + context.schema() + + "_owner"); + assertThatThrownBy(() -> read(context, evidence, decision, "original")) + .hasMessageContaining("permission denied for function"); + } + + @Test + void realSearchEndingBeforeTargetCommitHasNoCandidateAndMissingExtensionDenies() { + var context = context(); + var evidence = pending(context); + UUID decision = UUID.randomUUID(); + new AccountGameplayAdmissionOriginalCommitExecutor(context.source()) + .execute(evidence, decision); + String lower = locator(context, evidence, "original").get("search_lower_lsn", String.class); + var records = + context + .dsl() + .fetchOne( + "SELECT coalesce(jsonb_agg(to_jsonb(r)), '[]'::jsonb) AS records " + + "FROM wal_proof_extension.pg_get_wal_records_info(?::pg_lsn, ?::pg_lsn) r", + lower, + lower); + assertThat(records.get("records", JSONB.class).data()).isEqualTo("[]"); + assertThatThrownBy(() -> classify(context, "100", "101", lower, lower, lower, "[]")) + .hasMessageContaining("COMMIT unavailable"); + // Class-local owned container only; restored for subsequent tests. No live database option. + context.dsl().execute("DROP EXTENSION pg_walinspect"); + try { + assertThatThrownBy(() -> read(context, evidence, decision, "original")) + .hasMessageContaining("environment unavailable"); + } finally { + context + .dsl() + .execute("CREATE EXTENSION pg_walinspect WITH SCHEMA wal_proof_extension VERSION '1.1'"); + } + } + + @Test + void syntheticRecordClassifierRejectsEpochCollisionAmbiguityUncoveredAndUnboundedEvidence() { + var context = context(); + var accepted = + classify(context, "100", "101", "0/1000000", "0/1000080", "0/1000080", "[" + RECORD + "]"); + assertThat(accepted.get("record_end", String.class)).isEqualTo("0/1000048"); + for (String records : + List.of( + "[]", + "[" + RECORD + "," + RECORD + "]", + "[" + RECORD.replace("\"COMMIT\"", "\"ABORT\"") + "]", + "[" + RECORD.replace("\"100\"", "\"101\"") + "]", + "[" + RECORD.replace("\"Transaction\"", "\"Heap\"") + "]", + "[{\"xid\":\"100\"}]", + "[" + String.join(",", java.util.Collections.nCopies(257, RECORD)) + "]")) { + assertThatThrownBy( + () -> classify(context, "100", "101", "0/1000000", "0/1000080", "0/1000080", records)) + .hasMessageContaining("WAL proof"); + } + assertThatThrownBy( + () -> + classify( + context, + "4294967396", + "101", + "0/1000000", + "0/1000080", + "0/1000080", + "[" + RECORD + "]")) + .hasMessageContaining("full XID unavailable"); + assertThatThrownBy( + () -> + classify( + context, + "100", + "4294967397", + "0/1000000", + "0/1000080", + "0/1000080", + "[" + RECORD + "]")) + .hasMessageContaining("full XID unavailable"); + assertThatThrownBy( + () -> + classify( + context, + "100", + "101", + "0/1000000", + "0/1200000", + "0/1200000", + "[" + RECORD + "]")) + .hasMessageContaining("search bound"); + assertThatThrownBy( + () -> + classify( + context, + "100", + "101", + "0/1000000", + "0/1000080", + "0/1000040", + "[" + RECORD + "]")) + .hasMessageContaining("COMMIT unavailable"); + assertThatThrownBy( + () -> + classify( + context, + "100", + "101", + "0/1000000", + "0/1000040", + "0/1000080", + "[" + RECORD + "]")) + .hasMessageContaining("outside search bound"); + // Actual WAL read error on an unsupported bootstrap location, not physical recycle proof. + assertThatThrownBy( + () -> + context + .dsl() + .fetch("SELECT * FROM wal_proof_extension.pg_get_wal_record_info('0/0')")) + .hasMessageContaining("could not read WAL"); + } + + @Test + void syntheticEnvironmentClassifierRejectsVersionsCapabilitiesAndClusterTimelineChanges() { + var context = context(); + for (Object[] values : + List.of( + new Object[] {180000, false, "on", "1.1", "cluster", "cluster", 1L, 1L}, + new Object[] {150000, false, "on", "1.1", "cluster", "cluster", 1L, 1L}, + new Object[] {160000, true, "on", "1.1", "cluster", "cluster", 1L, 1L}, + new Object[] {160000, false, "off", "1.1", "cluster", "cluster", 1L, 1L}, + new Object[] {160000, false, "on", "1.0", "cluster", "cluster", 1L, 1L}, + new Object[] {160000, false, "on", "1.1", "cluster", "other", 1L, 1L}, + new Object[] {160000, false, "on", "1.1", "cluster", "cluster", 1L, 2L})) { + assertThatThrownBy( + () -> + context + .dsl() + .fetch( + "SELECT wal_proof_environment(?::integer, ?::boolean, ?::text, ?::text, ?::text, ?::text, ?::bigint, ?::bigint)", + values)) + .hasMessageContaining("environment unavailable"); + } + } + + private static Record classify( + Context context, + String xid, + String xmax, + String lower, + String upper, + String flush, + String records) { + return context + .dsl() + .fetchOne( + "SELECT * FROM wal_proof_classify(?, ?, ?::pg_lsn, ?::pg_lsn, ?::pg_lsn, ?::jsonb)", + xid, + xmax, + lower, + upper, + flush, + records); + } + + private static Record read( + Context context, + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decision, + String phase) { + var transaction = new TransactionTemplate(new DataSourceTransactionManager(context.reader())); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(true); + return transaction.execute( + ignored -> { + var dsl = + DSL.using(new TransactionAwareDataSourceProxy(context.reader()), SQLDialect.POSTGRES); + // Set before the proof statement: function-local GUC changes alone are not a timeout + // proof. + dsl.execute("SET LOCAL statement_timeout = '2s'"); + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM wal_proof_read(?, ?, ?, ?)", + request(evidence), + phase, + evidence.sha256(), + decision)); + }); + } + + private static void assertCovered(Context context, Record proof) { + assertThat( + context + .dsl() + .fetchSingle( + "SELECT ?::pg_lsn < ?::pg_lsn AND ?::pg_lsn <= ?::pg_lsn", + proof.get("commit_start", String.class), + proof.get("commit_end", String.class), + proof.get("commit_end", String.class), + proof.get("observed_flush", String.class)) + .get(0, Boolean.class)) + .isTrue(); + } + + private static Record locator( + Context context, AccountGameplayAdmissionLeaseEvidence evidence, String phase) { + return independent(context) + .fetchOne( + "SELECT * FROM wal_proof_locators WHERE request_id = ? AND phase = ?", + request(evidence), + phase); + } + + private static Record receipt(Context context, AccountGameplayAdmissionLeaseEvidence evidence) { + return independent(context) + .fetchOne( + "SELECT * FROM account_gameplay_admission_original_commit_ack_receipts WHERE request_id = ?", + request(evidence)); + } + + private static Record operation(DSLContext dsl, AccountGameplayAdmissionLeaseEvidence evidence) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM account_gameplay_admission_lease_operations WHERE request_id = ?", + request(evidence))); + } + + private static UUID request(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString((String) evidence.carrier().get("requestId")); + } + + private static long expiry(AccountGameplayAdmissionLeaseEvidence evidence) { + return Long.parseLong((String) evidence.carrier().get("expiresAt")); + } + + private static AccountGameplayAdmissionLeaseEvidence changedDigest( + AccountGameplayAdmissionLeaseEvidence original) { + var carrier = new LinkedHashMap<>(original.carrier()); + carrier.put( + "evaluatedAt", Long.toString(Long.parseLong((String) carrier.get("evaluatedAt")) + 1)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private static DSLContext independent(Context context) { + return DSL.using(context.source(), SQLDialect.POSTGRES); + } + + private static DataSource lostAcknowledgementSource(DataSource source, AtomicBoolean armed) { + return new DelegatingDataSource(source) { + @Override + public Connection getConnection() throws SQLException { + return wrap(super.getConnection()); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return wrap(super.getConnection(username, password)); + } + + private Connection wrap(Connection physical) { + return (Connection) + Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("commit") && method.getParameterCount() == 0) { + physical.commit(); + if (armed.compareAndSet(true, false)) + throw new SQLException("Test lost actual COMMIT acknowledgement", "08006"); + return null; + } + try { + return method.invoke(physical, arguments); + } catch (InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } + }; + } + + private static Context context() { + String schema = "walproof_" + UUID.randomUUID().toString().replace("-", ""); + var source = source(schema, POSTGRES.getUsername(), POSTGRES.getPassword()); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + try (var resource = + Objects.requireNonNull( + AccountGameplayAdmissionWalBoundaryProofIntegrationTest.class.getResourceAsStream( + "/account-admission-wal-boundary-proof.sql"))) { + dsl.execute( + new String(resource.readAllBytes(), StandardCharsets.UTF_8).replace("__S__", schema)); + } catch (IOException failure) { + throw new IllegalStateException("Test-only WAL proof fixture unavailable", failure); + } + return new Context( + schema, + source, + source(schema, schema + "_reader", "isolated-proof-only"), + dsl, + transaction); + } + + private static DriverManagerDataSource source(String schema, String username, String password) { + var source = new DriverManagerDataSource(); + source.setUrl( + POSTGRES.getJdbcUrl() + + (schema == null + ? "" + : (POSTGRES.getJdbcUrl().contains("?") ? "&" : "?") + "currentSchema=" + schema)); + source.setUsername(username); + source.setPassword(password); + return source; + } + + private static AccountGameplayAdmissionLeaseEvidence pending(Context context) { + return tx( + context, + () -> { + var authorities = new AccountAuthorityGenerationRepository(context.dsl()); + var sources = + new AccountAuthoritySourceEvidenceRepository( + context.dsl(), authorities, new AccountAuthorityOutboxRepository(context.dsl())); + sources.initializeIssuerIfAbsent("firemud-account-service"); + var account = new Account(); + account.setUsername("walproof-" + UUID.randomUUID()); + account.setEmail(UUID.randomUUID() + "@example.test"); + account.setPasswordHash("storage-fixture-only"); + account.setLoginAuthModes("PASSWORD"); + UUID accountId = + new AccountRepository(context.dsl(), sources).save(account).getAccountUuid(); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var allocation = repository.allocate(accountId, UUID.randomUUID(), UUID.randomUUID()); + var evidence = evidence(allocation); + repository.beginPending(evidence); + return evidence; + }); + } + + private static AccountGameplayAdmissionLeaseEvidence evidence( + AccountGameplayAdmissionLeaseRepository.Allocation allocation) { + String account = allocation.accountId().toString(); + long now = Instant.now().toEpochMilli(); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", "test"); + carrier.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + carrier.put("requestId", allocation.requestId().toString()); + carrier.put("leaseId", allocation.leaseId().toString()); + carrier.put("leaseFence", Long.toString(allocation.leaseFence())); + carrier.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, OTHER); + scope.put("accountId", account); + scope.put("tenantId", TENANT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "1"); + carrier.put("bindingScope", scope); + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + Map.of(TENANT, "1"), + "privateRealmGrantVersions", + List.of())); + carrier.put("issuanceFence", "7"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + "1")); + carrier.put( + "outboxCheckpoints", + List.of( + "account/" + account, + "issuer/firemud-account-service", + "membership/" + account + "/" + TENANT, + "tenant/" + TENANT) + .stream() + .map( + suffix -> + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + "1")) + .toList()); + Map token = new LinkedHashMap<>(); + token.put("accountId", account); + for (String key : List.of("operationId", "issuanceRequestId", "tokenJti")) + token.put(key, OTHER); + token.put("tokenSHA256", "a".repeat(64)); + token.put("tokenProfile", "game-session-account-delegation"); + token.put("tokenGeneration", "1"); + token.put("issuanceFence", "7"); + token.put("tokenIdentityFence", "9"); + token.put("issuedAt", Long.toString(now / 1000 - 1)); + token.put("notBefore", Long.toString(now / 1000 - 1)); + token.put("expiresAt", Long.toString(now / 1000 + 300)); + carrier.put("tokenIdentityEvidence", token); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put("expiresAt", Long.toString(now + 15000)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private static T tx(Context context, Supplier action) { + return context.transaction().execute(ignored -> action.get()); + } + + private record Context( + String schema, + DriverManagerDataSource source, + DriverManagerDataSource reader, + DSLContext dsl, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java index 38e9f85b20..22b7bb7398 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -20,16 +20,28 @@ import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadGrpcCodec; import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.PostgreSQLContainer; @@ -89,6 +101,358 @@ class AccountPublicationAuthorizationMtlsPostgresIntegrationTest { @TempDir Path temporary; + /** + * Real Account storage and two strict loopback mTLS clients. Remote immutable terminals and the + * incoming Game Design request context are stipulated; remote owner databases are not exercised. + */ + @Test + void twoAuthenticatedTerminalOwnersSettleActualAccountOrderAndReadBackAfterCommit() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("settlement-pki"))); + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve(outcome.name())))) { + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var descriptor = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()); + var repository = + org.mockito.Mockito.spy(new AccountPublicationAuthorizationRepository(sources.dsl)); + var order = + new AccountPublicationAuthorizationService(issued.actors(), sources.fences, repository) + .authorize(issued.compact(), descriptor.selection(), issued.environment()); + var operation = new GameDesignPublicationOperationBinding(order, descriptor.world()); + var terminal = + AccountPublicationAuthorizationPostgresIntegrationTest.terminal(operation, outcome); + var mode = new AtomicReference<>("exact"); + var gdReads = new java.util.concurrent.CopyOnWriteArrayList(); + var worldReads = new java.util.concurrent.CopyOnWriteArrayList(); + var gdEndpoint = + new net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceImplBase() { + @Override + public void readPublicationTerminal( + net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalRequest wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalResponse> + observer) { + try { + requireAccountClient(); + var request = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wire); + gdReads.add(wire.getReadRequestId()); + if (mode.get().equals("gd-missing")) throw Status.NOT_FOUND.asRuntimeException(); + if (mode.get().equals("gd-unavailable")) + throw Status.UNAVAILABLE.asRuntimeException(); + var response = + GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, terminal) + .toBuilder(); + if (mode.get().equals("gd-correlation")) + response.setReadRequestId(UUID.randomUUID().toString()); + if (mode.get().equals("gd-operation")) + response.setOriginalOperation(com.google.protobuf.ByteString.EMPTY); + if (mode.get().equals("gd-unknown")) { + var invalid = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + invalid, GameDesignPublicationTerminalEvidence.SCHEMA); + DraftAuthorizationFenceBinding.frame(invalid, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(invalid, "UNKNOWN"); + response.setTerminalEvidence( + com.google.protobuf.ByteString.copyFrom(invalid.toByteArray())); + } + observer.onNext(response.build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + var worldEndpoint = + new net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadServiceGrpc + .WorldPublicationTerminalReadServiceImplBase() { + @Override + public void readPublicationTerminal( + net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalRequest wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalResponse> + observer) { + try { + requireAccountClient(); + var request = WorldPublicationTerminalReadGrpcCodec.fromRequest(wire); + worldReads.add(wire.getReadRequestId()); + if (mode.get().equals("world-missing")) + throw Status.NOT_FOUND.asRuntimeException(); + if (mode.get().equals("world-unavailable")) + throw Status.UNAVAILABLE.asRuntimeException(); + var response = + WorldPublicationTerminalReadGrpcCodec.toResponse(request, terminal) + .toBuilder(); + if (mode.get().equals("world-correlation")) + response.setReadRequestId(UUID.randomUUID().toString()); + if (mode.get().equals("world-operation")) + response.setOriginalOperation(com.google.protobuf.ByteString.EMPTY); + if (mode.get().equals("world-terminal")) + response.setWorldTerminalEvidence(com.google.protobuf.ByteString.EMPTY); + if (mode.get().equals("world-unknown")) response.setWorldOutcomeValue(99); + if (mode.get().equals("world-phase")) + response.setWorldOutcomeValue( + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED ? 2 : 1); + observer.onNext(response.build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + Server gdServer = terminalServer(pki.gameDesignServer, pki.ca, gdEndpoint); + Server worldServer = terminalServer(pki.worldServer, pki.ca, worldEndpoint); + Server wrongServer = terminalServer(pki.server, pki.ca, gdEndpoint, worldEndpoint); + try (var gdClient = gameDesignClient(gdServer.getPort(), pki.accountClient, pki.ca); + var worldClient = worldClient(worldServer.getPort(), pki.accountClient, pki.ca)) { + var composition = + new AccountSelectedDraftPublicationSettlementService( + repository, gdClient, worldClient, sources.manager, NAMESPACE); + for (String failure : + List.of( + "gd-missing", + "gd-unavailable", + "gd-correlation", + "gd-operation", + "gd-unknown", + "world-missing", + "world-unavailable", + "world-correlation", + "world-operation", + "world-terminal", + "world-unknown", + "world-phase")) { + mode.set(failure); + assertThatThrownBy( + () -> asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + } + mode.set("exact"); + try (var wrongGd = gameDesignClient(wrongServer.getPort(), pki.accountClient, pki.ca); + var wrongWorld = worldClient(wrongServer.getPort(), pki.accountClient, pki.ca)) { + var wrongGdComposition = + new AccountSelectedDraftPublicationSettlementService( + repository, wrongGd, worldClient, sources.manager, NAMESPACE); + var wrongWorldComposition = + new AccountSelectedDraftPublicationSettlementService( + repository, gdClient, wrongWorld, sources.manager, NAMESPACE); + assertThatThrownBy( + () -> asGameDesign(() -> wrongGdComposition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + assertThatThrownBy( + () -> + asGameDesign( + () -> wrongWorldComposition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + } + var invocations = new AtomicInteger(); + var corruptReadback = new java.util.concurrent.atomic.AtomicBoolean(); + String schema = + java.util.Objects.requireNonNull( + sources.dsl.fetchOne("SELECT current_schema() AS schema")) + .get("schema", String.class); + org.mockito.Mockito.doAnswer( + call -> { + int invocation = invocations.incrementAndGet(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_READ_COMMITTED); + if (invocation == 2) { + // Independent connection cannot see the first transaction's uncommitted + // insert. + // Seeing its exact row before the second owner invocation proves prior + // commit. + try (var connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword())) { + connection.setSchema(schema); + try (var statement = + connection.prepareStatement( + "SELECT game_design_terminal FROM account_selected_publication_settlements WHERE operation_id = ?")) { + statement.setObject(1, order.operationId()); + try (var result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getBytes(1)).isEqualTo(terminal.canonicalBytes()); + assertThat(result.next()).isFalse(); + } + } + } + } + byte[] readback = (byte[]) call.callRealMethod(); + return corruptReadback.get() && invocation % 2 == 0 + ? new byte[] {99} + : readback; + }) + .when(repository) + .settle( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + gdReads.clear(); + worldReads.clear(); + byte[] receipt = asGameDesign(() -> composition.settle(operation.canonicalBytes())); + assertThat(asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isEqualTo(receipt); + assertThat(invocations).hasValue(4); + assertThat(gdReads).hasSize(2).doesNotHaveDuplicates(); + assertThat(worldReads).hasSize(2).doesNotHaveDuplicates(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isEqualTo(1); + var heldReader = + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + asGameDesign( + () -> { + heldReader.requireHeld( + AccountPublicationAuthorizationReadEvidence.Request.create( + NAMESPACE, order)); + return null; + })); + assertThat( + sources.tx( + () -> + sources.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + sources.account.getId()))) + .isEqualTo(1); + corruptReadback.set(true); + assertThatThrownBy( + () -> asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs"); + assertThat( + java.util.Objects.requireNonNull( + sources.dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + order.operationId())) + .get("receipt", byte[].class)) + .isEqualTo(receipt); + } finally { + for (Server server : List.of(gdServer, worldServer, wrongServer)) server.shutdownNow(); + for (Server server : List.of(gdServer, worldServer, wrongServer)) + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + } + + private static void assertPending( + AccountControlUiOwnerSourcesFixture sources, + AccountPublicationAuthorizationRepository repository, + AccountPublicationAuthorizationBinding order) { + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + sources.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy( + () -> + sources.tx( + () -> + sources.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + sources.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + private static void requireAccountClient() { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !("spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private static T asGameDesign(Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static Server terminalServer( + TestIdentity identity, Path ca, io.grpc.BindableService... endpoints) throws Exception { + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + for (var endpoint : endpoints) + builder.addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())); + return builder.build().start(); + } + + private static GameDesignPublicationTerminalReadClient gameDesignClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + port); + var client = + new GameDesignPublicationTerminalReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + private static WorldPublicationTerminalReadClient worldClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + port); + var client = + new WorldPublicationTerminalReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + @Test void genuineProducerToGameDesignAndWorldMtlsReadersReplaysExactlyAndRejectsSubstitution() throws Exception { @@ -232,6 +596,9 @@ private static final class TestPki { private static final String PASSWORD = "test-only-publication-mtls-password"; final Path ca; final TestIdentity server, + accountClient, + gameDesignServer, + worldServer, gameDesign, worldManagement, wrongWorkload, @@ -279,6 +646,11 @@ private static final class TestPki { ca.toString(), "-rfc"); server = issue(root, caStore, "account-server", NAMESPACE, "account-service", true); + accountClient = issue(root, caStore, "account-client", NAMESPACE, "account-service", false); + gameDesignServer = + issue(root, caStore, "game-design-server", NAMESPACE, "game-design-service", true); + worldServer = + issue(root, caStore, "world-server", NAMESPACE, "world-management-service", true); gameDesign = issue(root, caStore, "game-design-client", NAMESPACE, "game-design-service", false); worldManagement = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index 0e189cfee1..46691a18c4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -15,7 +15,10 @@ import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.world.RoomTemplateRef; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; @@ -80,6 +83,484 @@ class AccountPublicationAuthorizationPostgresIntegrationTest { @TempDir Path temporary; + /** + * Both owner readbacks here are upstream authenticated-owner stipulations, not transport proof. + */ + @Test + void exactTwoOwnerSettlementRollsBackAtomicallyThenReplaysAfterLostAcknowledgement() + throws Exception { + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var order = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = new GameDesignPublicationOperationBinding(order, proof.world()); + var terminal = terminal(operation, outcome); + String phase = + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.settle(operation, terminal, phase, terminal.canonicalBytes()); + throw new IllegalStateException("rollback before owner commit"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + + byte[] originalBinding = order.canonicalBytes(); + byte[] receipt = + f.tx(() -> repository.settle(operation, terminal, phase, terminal.canonicalBytes())); + // A committed response may be lost. Fresh outside transport correlations never enter + // settlement identity; historical replay does not authenticate a new creator credential. + UUID firstTransportRead = UUID.randomUUID(), retryTransportRead = UUID.randomUUID(); + assertThat(firstTransportRead).isNotEqualTo(retryTransportRead); + assertThat( + f.tx( + () -> repository.settle(operation, terminal, phase, terminal.canonicalBytes()))) + .isEqualTo(receipt); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isEqualTo(1); + assertThat( + f.dsl + .fetchSingle( + "SELECT binding FROM account_selected_publication_authorizations WHERE operation_id = ?", + order.operationId()) + .get("binding", byte[].class)) + .isEqualTo(originalBinding); + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.readHeld(order); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("already settled"); + var readOwner = + new AccountPublicationAuthorizationReadService(repository, f.manager, "test"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + readOwner.requireHeld( + net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadEvidence.Request.create( + "test", order)))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + assertThat( + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()))) + .isEqualTo(1); + // Even after the source changes, the original committed issuance and receipt replay. + assertThat( + f.tx( + () -> repository.settle(operation, terminal, phase, terminal.canonicalBytes()))) + .isEqualTo(receipt); + for (String mutation : + List.of( + "UPDATE account_selected_publication_settlements SET world_outcome = 'ABORTED'", + "DELETE FROM account_selected_publication_settlements", + "TRUNCATE account_selected_publication_settlements")) { + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(mutation))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + } + } + + @Test + void missingAmbiguousSubstitutedAndDisagreeingOwnersKeepOriginalSourcesHeld() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var order = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = new GameDesignPublicationOperationBinding(order, proof.world()); + var noPublication = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var published = terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED); + var wrongFence = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + order.operationId(), UUID.randomUUID(), order.input(), order.sources()); + var wrongOperation = new GameDesignPublicationOperationBinding(wrongFence, proof.world()); + for (Runnable rejected : + List.of( + () -> + repository.settle( + operation, noPublication, "PUBLISHED", noPublication.canonicalBytes()), + () -> + repository.settle( + operation, noPublication, "ABORTED", published.canonicalBytes()), + () -> + repository.settle( + operation, + noPublication, + "RECONCILIATION_REQUIRED", + noPublication.canonicalBytes()), + () -> repository.settle(operation, noPublication, "ABORTED", new byte[0]), + () -> repository.settle(operation, noPublication, "ABORTED", null), + () -> + repository.settle( + wrongOperation, + terminal( + wrongOperation, + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION), + "ABORTED", + terminal( + wrongOperation, + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION) + .canonicalBytes()))) { + assertThatThrownBy( + () -> + f.tx( + () -> { + rejected.run(); + return null; + })) + .isInstanceOf(RuntimeException.class); + } + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThat( + f.dsl.fetchCount(org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + + byte[] receipt = + f.tx( + () -> + repository.settle( + operation, noPublication, "ABORTED", noPublication.canonicalBytes())); + assertThatThrownBy( + () -> + f.tx( + () -> + repository.settle( + operation, published, "PUBLISHED", published.canonicalBytes()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed original"); + assertThat( + f.dsl + .fetchSingle( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + order.operationId()) + .get("receipt", byte[].class)) + .isEqualTo(receipt); + } + } + + @Test + void settlingOneOrderLeavesEveryOtherOriginalSourceParticipationPending() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var first = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var secondSelection = + selection(proof.selection().selectedCommit(), "other order", "another-publication"); + var second = service.authorize(issued.compact(), secondSelection, issued.environment()); + var operation = new GameDesignPublicationOperationBinding(first, proof.world()); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + f.tx(() -> repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes())); + f.tx( + () -> { + repository.readHeld(second); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + var captured = + f.tx( + () -> + f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), captured.sources(), new byte[] {1}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + } + } + + static GameDesignPublicationTerminalEvidence terminal( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence.Outcome outcome) { + if (outcome == GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION) { + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), outcome, null, null); + } + var request = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + request.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "a".repeat(64) : null, + null, + null)) + .toList(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + operation.account().tenantId(), + request.canonicalVersionId(), + "release-exact", + 1, + "v2", + request.publishWorkflowId(), + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of("look"), + "generation-1", + operation.world()); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + outcome, + release, + Math.addExact(request.versionStateEpoch(), 1)); + } + + @Test + void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = new GameDesignPublicationOperationBinding(order, proof.world()); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, order.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, "ABORTED"); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + byte[] receipt = out.toByteArray(); + String insert = + "INSERT INTO account_selected_publication_settlements" + + " (operation_id, fence_id, account_binding, publication_operation, game_design_outcome," + + " game_design_terminal, world_outcome, world_terminal, receipt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; + List malformed = + List.of( + new Object[] { + order.operationId(), + UUID.randomUUID(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + new byte[] {0}, + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + new byte[] {0}, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + new byte[] {0}, + "ABORTED", + new byte[] {0}, + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "PUBLISHED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + new byte[] {0} + }); + for (Object[] values : malformed) { + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, values))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + assertThat( + f.dsl.fetchCount(org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + + @Test + void sourceWriterCannotPassUncommittedSettlementAndCanRetryAfterItsCommit() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = new GameDesignPublicationOperationBinding(order, proof.world()); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var executor = java.util.concurrent.Executors.newSingleThreadExecutor(); + try { + f.tx( + () -> { + repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes()); + int settlementPid = + f.dsl.fetchSingle("SELECT pg_backend_pid() AS pid").get("pid", Integer.class); + var writer = + executor.submit( + () -> + f.tx( + () -> { + int writerPid = + f.dsl + .fetchSingle("SELECT pg_backend_pid() AS pid") + .get("pid", Integer.class); + assertThat(writerPid).isNotEqualTo(settlementPid); + // The actual source trigger takes the same source locks NOWAIT. A + // pending + // transaction cannot release its protection to a different writer + // connection. + return f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()); + })); + assertThatThrownBy(() -> writer.get(10, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(org.jooq.exception.DataAccessException.class); + return null; + }); + assertThat( + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()))) + .isEqualTo(1); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + } + @Test void authenticatesPreFreezeDistinctOrderReplaysExactlyAndBlocksSourceWritersAndDisclosure() throws Exception { @@ -584,11 +1065,16 @@ private static String b64(byte[] value) { private static AuthoredDraftPublishSelectionBinding selection( DraftCommitBinding draft, String notes) { + return selection(draft, notes, "publication-request"); + } + + private static AuthoredDraftPublishSelectionBinding selection( + DraftCommitBinding draft, String notes, String publishRequestId) { return AuthoredDraftPublishSelectionBinding.capture( new AuthoredDraftPublishSelectionBinding.PublishIntent( draft.target().canonicalTenantId(), draft.target().canonicalVersionId(), - "publication-request", + publishRequestId, "5", notes, draft.requestId(), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java new file mode 100644 index 0000000000..0d17f37a4f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java @@ -0,0 +1,376 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Composition seams only: canonical codec outputs, owner results and peer identity are stipulated + * here. Actual PostgreSQL, codec integrity and mounted-certificate mTLS are separate proof. + */ +class AccountSelectedDraftPublicationSettlementServiceTest { + private final AccountPublicationAuthorizationRepository repository = + mock(AccountPublicationAuthorizationRepository.class); + private final GameDesignPublicationTerminalReadClient gameDesign = + mock(GameDesignPublicationTerminalReadClient.class); + private final WorldPublicationTerminalReadClient world = + mock(WorldPublicationTerminalReadClient.class); + private final OwnerTransactions transactions = new OwnerTransactions(); + private final AccountSelectedDraftPublicationSettlementService service = + new AccountSelectedDraftPublicationSettlementService( + repository, gameDesign, world, transactions, "test"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeMalformedDecodeOrOwnerReads() { + assertCode(Status.Code.UNAUTHENTICATED, () -> service.settle(null)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("test", workload, () -> service.settle(new byte[] {0}))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("other", "game-design-service", () -> service.settle(null))); + assertThatThrownBy(() -> authorized(() -> service.settle(new byte[] {0}))) + .isInstanceOf(RuntimeException.class); + verifyNoInteractions(repository, gameDesign, world); + assertThat(transactions.begins).isZero(); + } + + @Test + void deniesAmbientTransactionAndSynchronizationBeforeDecode() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null))); + verifyNoInteractions(repository, gameDesign, world); + } + + @Test + void agreeingOwnersCommitThenSeparatelyReadBackAndRetriesUseFreshReadCorrelations() { + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = new CodecOutputs(outcome)) { + var gameDesignReads = new ArrayList(); + var worldReads = new ArrayList(); + doAnswer( + call -> { + assertNoSql(); + var request = + call.getArgument(0, GameDesignPublicationTerminalReadEvidence.Request.class); + gameDesignReads.add(request.readRequestId()); + return gameDesignEvidence(request, fixture.terminal); + }) + .when(gameDesign) + .read(any()); + doAnswer( + call -> { + assertNoSql(); + var request = + call.getArgument(0, WorldPublicationTerminalReadEvidence.Request.class); + worldReads.add(request.readRequestId()); + return worldEvidence(request, fixture.terminal, request.expectedWorldOutcome()); + }) + .when(world) + .read(any()); + var calls = new AtomicInteger(); + int priorCommits = transactions.commits; + byte[] receipt = new byte[] {9, 8}; + doAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_READ_COMMITTED); + assertThat(transactions.commits - priorCommits) + .isEqualTo(calls.getAndIncrement()); + assertThat(call.getArgument(0, GameDesignPublicationOperationBinding.class)) + .isSameAs(fixture.operation); + assertThat(call.getArgument(1, GameDesignPublicationTerminalEvidence.class)) + .isSameAs(fixture.terminal); + assertThat(call.getArgument(2, String.class)).isEqualTo(fixture.phase.name()); + assertThat(call.getArgument(3, byte[].class)) + .containsExactly(fixture.terminalBytes); + return receipt.clone(); + }) + .when(repository) + .settle(any(), any(), anyString(), any()); + assertThat(authorized(() -> service.settle(fixture.operationBytes))) + .containsExactly(receipt); + assertThat(authorized(() -> service.settle(fixture.operationBytes))) + .containsExactly(receipt); + assertThat(calls).hasValue(4); + assertThat(transactions.commits - priorCommits).isEqualTo(4); + assertThat(gameDesignReads).hasSize(2).doesNotHaveDuplicates(); + assertThat(worldReads).hasSize(2).doesNotHaveDuplicates(); + assertNoSql(); + } + } + } + + @Test + void missingSubstitutedOrUnavailableGameDesignResultNeverReadsWorldOrWritesAccount() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(gameDesign.read(any())).thenReturn(null); + assertFailure(fixture); + doAnswer( + call -> { + var request = + call.getArgument(0, GameDesignPublicationTerminalReadEvidence.Request.class); + return gameDesignEvidence( + new GameDesignPublicationTerminalReadEvidence.Request( + 1, "test", UUID.randomUUID(), request.originalOperation()), + fixture.terminal); + }) + .when(gameDesign) + .read(any()); + assertFailure(fixture); + var substituted = mock(GameDesignPublicationTerminalEvidence.class); + when(substituted.canonicalBytes()).thenReturn(new byte[] {99}); + doAnswer(call -> gameDesignEvidence(call.getArgument(0), substituted)) + .when(gameDesign) + .read(any()); + assertFailure(fixture); + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(gameDesign).read(any()); + assertCode( + Status.Code.UNAVAILABLE, () -> authorized(() -> service.settle(fixture.operationBytes))); + verifyNoInteractions(world, repository); + assertThat(transactions.begins).isZero(); + } + } + + @Test + void + worldNamespaceMismatchMissingChangedRequestTerminalPhaseAndUnavailableKeepAccountUntouched() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(fixture.worldRequest.targetNamespace()).thenReturn("other"); + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(gameDesign, world, repository); + when(fixture.worldRequest.targetNamespace()).thenReturn("test"); + when(gameDesign.read(any())) + .thenAnswer(call -> gameDesignEvidence(call.getArgument(0), fixture.terminal)); + for (String changed : + List.of("missing", "correlation", "namespace", "phase", "terminal", "operation")) { + doAnswer( + call -> { + var request = + call.getArgument(0, WorldPublicationTerminalReadEvidence.Request.class); + if (changed.equals("missing")) return null; + var response = worldEvidence(request, fixture.terminal, fixture.phase); + if (changed.equals("correlation") || changed.equals("namespace")) { + // Mock the returned request itself to exercise a substituted owner echo without + // treating a structurally invalid carrier as a genuine codec result. + when(response.request()) + .thenReturn(mock(WorldPublicationTerminalReadEvidence.Request.class)); + } + if (changed.equals("phase")) + when(response.worldOutcome()) + .thenReturn(WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED); + if (changed.equals("terminal")) + when(response.worldTerminalEvidence()).thenReturn(new byte[] {99}); + if (changed.equals("operation")) { + var other = mock(GameDesignPublicationTerminalEvidence.class); + when(other.operationBytes()).thenReturn(new byte[] {99}); + when(response.terminalEvidence()).thenReturn(other); + } + return response; + }) + .when(world) + .read(any()); + assertFailure(fixture); + } + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(world).read(any()); + assertCode( + Status.Code.UNAVAILABLE, () -> authorized(() -> service.settle(fixture.operationBytes))); + verifyNoInteractions(repository); + assertThat(transactions.begins).isZero(); + } + } + + @Test + void changedPostCommitReadbackCannotReturnSuccess() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(gameDesign.read(any())) + .thenAnswer(call -> gameDesignEvidence(call.getArgument(0), fixture.terminal)); + when(world.read(any())) + .thenAnswer(call -> worldEvidence(call.getArgument(0), fixture.terminal, fixture.phase)); + when(repository.settle(any(), any(), anyString(), any())) + .thenReturn(new byte[] {1}, new byte[] {2}); + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs"); + assertThat(transactions.commits).isEqualTo(2); + assertNoSql(); + } + } + + private void assertFailure(CodecOutputs fixture) { + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(RuntimeException.class); + } + + private static GameDesignPublicationTerminalReadEvidence gameDesignEvidence( + GameDesignPublicationTerminalReadEvidence.Request request, + GameDesignPublicationTerminalEvidence terminal) { + var result = mock(GameDesignPublicationTerminalReadEvidence.class); + when(result.request()).thenReturn(request); + when(result.terminalEvidence()).thenReturn(terminal); + return result; + } + + private static WorldPublicationTerminalReadEvidence worldEvidence( + WorldPublicationTerminalReadEvidence.Request request, + GameDesignPublicationTerminalEvidence terminal, + WorldPublicationTerminalReadEvidence.WorldOutcome phase) { + byte[] terminalBytes = terminal.canonicalBytes(); + var result = mock(WorldPublicationTerminalReadEvidence.class); + when(result.request()).thenReturn(request); + when(result.terminalEvidence()).thenReturn(terminal); + when(result.worldTerminalEvidence()).thenReturn(terminalBytes); + when(result.worldOutcome()).thenReturn(phase); + return result; + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static T authorized(Supplier action) { + return peer("test", "game-design-service", action); + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static final class CodecOutputs implements AutoCloseable { + final byte[] operationBytes = new byte[] {11}; + final byte[] terminalBytes = new byte[] {22}; + final GameDesignPublicationOperationBinding operation = + mock(GameDesignPublicationOperationBinding.class); + final GameDesignPublicationTerminalEvidence terminal = + mock(GameDesignPublicationTerminalEvidence.class); + final WorldPublishedStartLocationEvidence.Request worldRequest = + mock(WorldPublishedStartLocationEvidence.Request.class); + final WorldPublicationTerminalReadEvidence.WorldOutcome phase; + final org.mockito.MockedStatic operations = + mockStatic(GameDesignPublicationOperationBinding.class); + final org.mockito.MockedStatic terminals = + mockStatic(GameDesignPublicationTerminalEvidence.class); + + CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome outcome) { + var world = mock(WorldPublishedStartLocationEvidence.class); + when(operation.canonicalBytes()).thenReturn(operationBytes); + when(operation.world()).thenReturn(world); + when(world.request()).thenReturn(worldRequest); + when(worldRequest.targetNamespace()).thenReturn("test"); + when(terminal.canonicalBytes()).thenReturn(terminalBytes); + when(terminal.operationBytes()).thenReturn(operationBytes); + when(terminal.outcome()).thenReturn(outcome); + operations + .when(() -> GameDesignPublicationOperationBinding.fromStored(operationBytes)) + .thenReturn(operation); + terminals + .when(() -> GameDesignPublicationTerminalEvidence.fromStored(terminalBytes)) + .thenReturn(terminal); + phase = + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED + : WorldPublicationTerminalReadEvidence.WorldOutcome.ABORTED; + } + + @Override + public void close() { + terminals.close(); + operations.close(); + } + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/resources/account-admission-wal-boundary-proof.sql b/services/account-service/src/test/resources/account-admission-wal-boundary-proof.sql new file mode 100644 index 0000000000..77f4010c52 --- /dev/null +++ b/services/account-service/src/test/resources/account-admission-wal-boundary-proof.sql @@ -0,0 +1,250 @@ +-- Disposable-container experiment only. Never a Flyway migration or production authority. +-- __S__ is a generated, validated test schema. No historical locator is backfilled. +CREATE ROLE __S___owner NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT; +CREATE ROLE __S___reader LOGIN PASSWORD 'isolated-proof-only' NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT; +REVOKE ALL ON SCHEMA __S__ FROM PUBLIC; +GRANT USAGE ON SCHEMA __S__ TO __S___owner, __S___reader; +GRANT CREATE ON SCHEMA __S__ TO __S___owner; +GRANT USAGE ON SCHEMA wal_proof_extension TO __S___owner; +GRANT EXECUTE ON FUNCTION wal_proof_extension.pg_get_wal_records_info(pg_lsn, pg_lsn) TO __S___owner; +GRANT EXECUTE ON FUNCTION pg_catalog.pg_control_system() TO __S___owner; +GRANT SELECT ON __S__.account_gameplay_admission_lease_operations, + __S__.account_gameplay_admission_original_commit_ack_receipts TO __S___owner; + +CREATE TABLE __S__.wal_proof_locators ( + request_id UUID NOT NULL, + phase TEXT NOT NULL CHECK (phase IN ('original', 'receipt')), + account_uuid UUID NOT NULL, + lease_id UUID NOT NULL, + lease_fence BIGINT NOT NULL, + evidence_sha256 TEXT NOT NULL, + binding_decision_id UUID NOT NULL, + expires_at_ms BIGINT NOT NULL, + finalization_xid TEXT NOT NULL, + target_xid TEXT NOT NULL, + search_lower_lsn PG_LSN NOT NULL, + system_identifier TEXT NOT NULL, + insertion_timeline BIGINT NOT NULL, + PRIMARY KEY (request_id, phase) +); +ALTER TABLE __S__.wal_proof_locators OWNER TO __S___owner; + +CREATE FUNCTION __S__.wal_proof_immutable() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Test WAL locator is immutable' USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER wal_proof_immutable BEFORE UPDATE OR DELETE ON __S__.wal_proof_locators + FOR EACH ROW EXECUTE FUNCTION __S__.wal_proof_immutable(); +CREATE TRIGGER wal_proof_no_truncate BEFORE TRUNCATE ON __S__.wal_proof_locators + FOR EACH STATEMENT EXECUTE FUNCTION __S__.wal_proof_immutable(); + +CREATE FUNCTION __S__.wal_proof_capture() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$ +DECLARE + phase_value TEXT; + target_value TEXT; + lower_value PG_LSN; + cluster_value TEXT; + timeline_value BIGINT; +BEGIN + IF TG_TABLE_NAME = 'account_gameplay_admission_lease_operations' THEN + phase_value := 'original'; + target_value := NEW.finalization_xid; + ELSE + phase_value := 'receipt'; + target_value := NEW.receipt_xid; + END IF; + IF target_value IS DISTINCT FROM pg_current_xact_id_if_assigned()::text THEN + RAISE EXCEPTION 'Test WAL locator requires exact own top-level XID' USING ERRCODE = '23514'; + END IF; + -- This is only a lower search bound. The target COMMIT does not exist yet. + lower_value := pg_current_wal_insert_lsn(); + SELECT c.system_identifier::text INTO cluster_value FROM pg_control_system() c; + SELECT f.timeline_id INTO timeline_value + FROM pg_split_walfile_name(pg_walfile_name(lower_value)) f; + INSERT INTO __S__.wal_proof_locators VALUES ( + NEW.request_id, phase_value, NEW.account_uuid, NEW.lease_id, NEW.lease_fence, + NEW.evidence_sha256, NEW.binding_decision_id, NEW.expires_at_ms, + NEW.finalization_xid, target_value, lower_value, cluster_value, timeline_value); + RETURN NEW; +END; +$$; +ALTER FUNCTION __S__.wal_proof_capture() OWNER TO __S___owner; +REVOKE ALL ON FUNCTION __S__.wal_proof_capture() FROM PUBLIC; +CREATE TRIGGER wal_proof_original_capture AFTER UPDATE ON __S__.account_gameplay_admission_lease_operations + FOR EACH ROW WHEN (OLD.status = 'PENDING' AND NEW.status = 'COMMITTED') + EXECUTE FUNCTION __S__.wal_proof_capture(); +CREATE TRIGGER wal_proof_receipt_capture AFTER INSERT ON __S__.account_gameplay_admission_original_commit_ack_receipts + FOR EACH ROW EXECUTE FUNCTION __S__.wal_proof_capture(); + +-- These two classifiers are called by the real reader. Direct synthetic calls in tests +-- exercise denial decisions, not physical promotion, wraparound, recycle or flush failures. +CREATE FUNCTION __S__.wal_proof_environment( + version_value INTEGER, recovery_value BOOLEAN, fsync_value TEXT, extension_value TEXT, + expected_cluster TEXT, observed_cluster TEXT, expected_timeline BIGINT, observed_timeline BIGINT) +RETURNS VOID LANGUAGE plpgsql AS $$ +BEGIN + IF version_value IS NULL OR version_value < 160000 OR version_value >= 170000 + OR recovery_value IS DISTINCT FROM FALSE OR fsync_value IS DISTINCT FROM 'on' + OR extension_value IS DISTINCT FROM '1.1' + OR expected_cluster IS NULL OR expected_cluster IS DISTINCT FROM observed_cluster + OR expected_timeline IS NULL OR expected_timeline IS DISTINCT FROM observed_timeline THEN + RAISE EXCEPTION 'WAL proof environment unavailable or mismatched' USING ERRCODE = '23514'; + END IF; +END; +$$; +ALTER FUNCTION __S__.wal_proof_environment(INTEGER, BOOLEAN, TEXT, TEXT, TEXT, TEXT, BIGINT, BIGINT) + OWNER TO __S___owner; +REVOKE ALL ON FUNCTION __S__.wal_proof_environment(INTEGER, BOOLEAN, TEXT, TEXT, TEXT, TEXT, BIGINT, BIGINT) + FROM PUBLIC; + +CREATE FUNCTION __S__.wal_proof_classify( + expected_xid TEXT, snapshot_xmax TEXT, lower_value PG_LSN, upper_value PG_LSN, + independent_flush PG_LSN, records_value JSONB) +RETURNS TABLE(record_start PG_LSN, record_end PG_LSN) LANGUAGE plpgsql AS $$ +DECLARE + expected_number NUMERIC; + xmax_number NUMERIC; + wal_xid TEXT; + item JSONB; + candidate_count INTEGER := 0; + start_value PG_LSN; + end_value PG_LSN; +BEGIN + expected_number := expected_xid::numeric; + xmax_number := snapshot_xmax::numeric; + -- Deliberately bounded same-epoch probe. Never infer an epoch from a truncated WAL XID. + IF expected_number <= 0 OR expected_number > 18446744073709551615 + OR xmax_number <= expected_number OR xmax_number - expected_number >= 2147483648 + OR floor(expected_number / 4294967296) <> floor(xmax_number / 4294967296) + OR lower_value IS NULL OR lower_value <= '0/0'::pg_lsn + OR upper_value IS NULL OR upper_value < lower_value + OR upper_value - lower_value > 1048576 + OR independent_flush IS NULL + OR records_value IS NULL OR jsonb_typeof(records_value) <> 'array' + OR jsonb_array_length(records_value) > 256 THEN + RAISE EXCEPTION 'WAL proof search bound or full XID unavailable' USING ERRCODE = '23514'; + END IF; + wal_xid := mod(expected_number, 4294967296)::text; + FOR item IN SELECT value FROM jsonb_array_elements(records_value) LOOP + IF (item->>'start_lsn')::pg_lsn IS NULL OR (item->>'end_lsn')::pg_lsn IS NULL + OR (item->>'start_lsn')::pg_lsn < lower_value + OR (item->>'end_lsn')::pg_lsn <= (item->>'start_lsn')::pg_lsn + OR (item->>'end_lsn')::pg_lsn > upper_value THEN + RAISE EXCEPTION 'WAL proof record outside search bound' USING ERRCODE = '23514'; + END IF; + IF item->>'xid' = wal_xid AND item->>'resource_manager' = 'Transaction' THEN + IF item->>'record_type' IS DISTINCT FROM 'COMMIT' THEN + RAISE EXCEPTION 'WAL proof transaction record unsupported' USING ERRCODE = '23514'; + END IF; + candidate_count := candidate_count + 1; + start_value := (item->>'start_lsn')::pg_lsn; + end_value := (item->>'end_lsn')::pg_lsn; + END IF; + END LOOP; + IF candidate_count <> 1 OR end_value > independent_flush THEN + RAISE EXCEPTION 'WAL proof exact covered COMMIT unavailable or ambiguous' USING ERRCODE = '23514'; + END IF; + RETURN QUERY SELECT start_value, end_value; +END; +$$; +ALTER FUNCTION __S__.wal_proof_classify(TEXT, TEXT, PG_LSN, PG_LSN, PG_LSN, JSONB) OWNER TO __S___owner; +REVOKE ALL ON FUNCTION __S__.wal_proof_classify(TEXT, TEXT, PG_LSN, PG_LSN, PG_LSN, JSONB) FROM PUBLIC; + +CREATE FUNCTION __S__.wal_proof_read( + requested_request UUID, requested_phase TEXT, expected_sha TEXT, expected_decision UUID) +RETURNS TABLE(target_xid TEXT, commit_start PG_LSN, commit_end PG_LSN, + observed_flush PG_LSN, original_bound BIGINT, unchanged_expiry BIGINT) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$ +DECLARE + locator __S__.wal_proof_locators%ROWTYPE; + operation __S__.account_gameplay_admission_lease_operations%ROWTYPE; + receipt __S__.account_gameplay_admission_original_commit_ack_receipts%ROWTYPE; + fixed_snapshot PG_SNAPSHOT; + upper_value PG_LSN; + flush_value PG_LSN; + cluster_value TEXT; + timeline_value BIGINT; + extension_value TEXT; + records_value JSONB; + boundary RECORD; +BEGIN + IF current_setting('transaction_isolation') <> 'serializable' THEN + RAISE EXCEPTION 'Independent SERIALIZABLE test WAL reader required' USING ERRCODE = '23514'; + END IF; + fixed_snapshot := pg_current_snapshot(); + SELECT * INTO locator FROM __S__.wal_proof_locators l + WHERE l.request_id = requested_request AND l.phase = requested_phase; + IF NOT FOUND THEN + RAISE EXCEPTION 'WAL proof locator unavailable; no historical backfill' USING ERRCODE = '23514'; + END IF; + SELECT * INTO operation FROM __S__.account_gameplay_admission_lease_operations o + WHERE o.request_id = requested_request; + IF NOT FOUND OR operation.status <> 'COMMITTED' + OR operation.account_uuid IS DISTINCT FROM locator.account_uuid + OR operation.lease_id IS DISTINCT FROM locator.lease_id + OR operation.lease_fence IS DISTINCT FROM locator.lease_fence + OR operation.evidence_sha256 IS DISTINCT FROM locator.evidence_sha256 + OR operation.binding_decision_id IS DISTINCT FROM locator.binding_decision_id + OR operation.expires_at_ms IS DISTINCT FROM locator.expires_at_ms + OR operation.finalization_xid IS DISTINCT FROM locator.finalization_xid + OR expected_sha IS DISTINCT FROM locator.evidence_sha256 + OR expected_decision IS DISTINCT FROM locator.binding_decision_id + OR locator.target_xid = pg_current_xact_id_if_assigned()::text + OR NOT pg_visible_in_snapshot(locator.target_xid::xid8, fixed_snapshot) THEN + RAISE EXCEPTION 'WAL proof exact independent identity unavailable' USING ERRCODE = '23514'; + END IF; + IF requested_phase = 'receipt' THEN + SELECT * INTO receipt FROM __S__.account_gameplay_admission_original_commit_ack_receipts r + WHERE r.request_id = requested_request; + IF NOT FOUND OR receipt.receipt_xid IS DISTINCT FROM locator.target_xid + OR receipt.finalization_xid IS DISTINCT FROM locator.finalization_xid + OR receipt.account_uuid IS DISTINCT FROM locator.account_uuid + OR receipt.lease_id IS DISTINCT FROM locator.lease_id + OR receipt.lease_fence IS DISTINCT FROM locator.lease_fence + OR receipt.evidence_sha256 IS DISTINCT FROM locator.evidence_sha256 + OR receipt.binding_decision_id IS DISTINCT FROM locator.binding_decision_id + OR receipt.expires_at_ms IS DISTINCT FROM locator.expires_at_ms + OR receipt.committed_before_ms <= 0 OR receipt.committed_before_ms >= locator.expires_at_ms THEN + RAISE EXCEPTION 'WAL proof exact original ACK receipt unavailable' USING ERRCODE = '23514'; + END IF; + ELSIF requested_phase <> 'original' OR locator.target_xid IS DISTINCT FROM locator.finalization_xid THEN + RAISE EXCEPTION 'WAL proof phase unavailable' USING ERRCODE = '23514'; + END IF; + SELECT c.system_identifier::text INTO cluster_value FROM pg_control_system() c; + SELECT f.timeline_id INTO timeline_value + FROM pg_split_walfile_name(pg_walfile_name(pg_current_wal_insert_lsn())) f; + SELECT e.extversion INTO extension_value FROM pg_extension e + JOIN pg_namespace n ON n.oid = e.extnamespace + WHERE e.extname = 'pg_walinspect' AND n.nspname = 'wal_proof_extension'; + PERFORM __S__.wal_proof_environment(current_setting('server_version_num')::integer, + pg_is_in_recovery(), current_setting('fsync'), extension_value, + locator.system_identifier, cluster_value, locator.insertion_timeline, timeline_value); + -- Independent statement; no marker, target flush request, clock substitution or widened retry. + upper_value := pg_current_wal_flush_lsn(); + IF upper_value < locator.search_lower_lsn OR upper_value - locator.search_lower_lsn > 1048576 THEN + RAISE EXCEPTION 'WAL proof search budget unavailable' USING ERRCODE = '23514'; + END IF; + SELECT coalesce(jsonb_agg(to_jsonb(r)), '[]'::jsonb) INTO records_value + FROM wal_proof_extension.pg_get_wal_records_info(locator.search_lower_lsn, upper_value) r; + flush_value := pg_current_wal_flush_lsn(); + SELECT * INTO boundary FROM __S__.wal_proof_classify(locator.target_xid, + pg_snapshot_xmax(fixed_snapshot)::text, locator.search_lower_lsn, upper_value, + flush_value, records_value); + SELECT c.system_identifier::text INTO cluster_value FROM pg_control_system() c; + SELECT f.timeline_id INTO timeline_value + FROM pg_split_walfile_name(pg_walfile_name(pg_current_wal_insert_lsn())) f; + PERFORM __S__.wal_proof_environment(current_setting('server_version_num')::integer, + pg_is_in_recovery(), current_setting('fsync'), extension_value, + locator.system_identifier, cluster_value, locator.insertion_timeline, timeline_value); + -- original phase is diagnostic only: WAL never reconstructs a missing typed original ACK. + RETURN QUERY SELECT locator.target_xid, boundary.record_start, boundary.record_end, + flush_value, receipt.committed_before_ms, locator.expires_at_ms; +END; +$$; +ALTER FUNCTION __S__.wal_proof_read(UUID, TEXT, TEXT, UUID) OWNER TO __S___owner; +REVOKE ALL ON FUNCTION __S__.wal_proof_read(UUID, TEXT, TEXT, UUID) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION __S__.wal_proof_read(UUID, TEXT, TEXT, UUID) TO __S___reader; +REVOKE CREATE ON SCHEMA __S__ FROM __S___owner; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClient.java new file mode 100644 index 0000000000..41d26891a0 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClient.java @@ -0,0 +1,154 @@ +package net.firedevops.firemud.common.publication; + +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.WorldPublicationTerminalReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for the World-owned exact publication terminal read. */ +public final class WorldPublicationTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + WorldPublicationTerminalReadServiceGrpc.WorldPublicationTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldPublicationTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldPublicationTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World publication terminal read client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World publication terminal read stub unavailable"); + } + initialized = true; + } + + /** Returns only the exact original terminal after World server identity and response checks. */ + public WorldPublicationTerminalReadEvidence read( + WorldPublicationTerminalReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World publication terminal read requires no owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World publication terminal read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readPublicationTerminal(WorldPublicationTerminalReadGrpcCodec.toRequest(request)); + try { + return WorldPublicationTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid publication terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldPublicationTerminalReadServiceGrpc.WorldPublicationTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldPublicationTerminalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldPublicationTerminalReadServiceGrpc.WorldPublicationTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World publication terminal read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World publication terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World publication terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World publication terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World publication terminal read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World publication terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidence.java new file mode 100644 index 0000000000..1b588e7027 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidence.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.common.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * World-owned readback of its terminal phase and the exact embedded Game Design terminal bytes. + * Decoding alone does not authenticate World; only the strict World mTLS client establishes that + * producer identity. The embedded terminal remains Game Design-produced evidence. + */ +public final class WorldPublicationTerminalReadEvidence { + private final Request request; + private final WorldOutcome worldOutcome; + private final GameDesignPublicationTerminalEvidence terminal; + + private WorldPublicationTerminalReadEvidence( + Request request, WorldOutcome worldOutcome, byte[] worldTerminalEvidence) { + this.request = Objects.requireNonNull(request, "request"); + this.worldOutcome = Objects.requireNonNull(worldOutcome, "worldOutcome"); + this.terminal = GameDesignPublicationTerminalEvidence.fromStored(worldTerminalEvidence); + if (!Arrays.equals(request.originalOperation(), terminal.operationBytes()) + || !Arrays.equals(request.expectedGameDesignTerminalEvidence(), terminal.canonicalBytes()) + || worldOutcome != worldOutcome(terminal.outcome())) { + throw new IllegalArgumentException( + "World terminal read differs from the exact operation, terminal, or owner phase"); + } + } + + public static WorldPublicationTerminalReadEvidence fromOwnerRead( + Request request, WorldOutcome worldOutcome, byte[] worldTerminalEvidence) { + return new WorldPublicationTerminalReadEvidence(request, worldOutcome, worldTerminalEvidence); + } + + public Request request() { + return request; + } + + /** World owner phase, not the identity of the producer of {@link #terminalEvidence()}. */ + public WorldOutcome worldOutcome() { + return worldOutcome; + } + + /** Exact original terminal payload, whose producer is Game Design. */ + public GameDesignPublicationTerminalEvidence terminalEvidence() { + return terminal; + } + + public byte[] worldTerminalEvidence() { + return terminal.canonicalBytes(); + } + + private static WorldOutcome worldOutcome(GameDesignPublicationTerminalEvidence.Outcome outcome) { + return outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldOutcome.PUBLISHED + : WorldOutcome.ABORTED; + } + + public enum WorldOutcome { + PUBLISHED, + ABORTED + } + + /** + * Exact owner-read lookup tuple. The read UUID is only transport correlation; settlement remains + * identified by the immutable Account order nested in the original operation. + */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] originalOperation, + byte[] expectedGameDesignTerminalEvidence) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World publication terminal read schema"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace required"); + } + if (readRequestId == null || readRequestId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Non-nil canonical read request identity required"); + } + if (originalOperation == null || originalOperation.length == 0) { + throw new IllegalArgumentException("Complete original publication operation required"); + } + if (expectedGameDesignTerminalEvidence == null + || expectedGameDesignTerminalEvidence.length == 0) { + throw new IllegalArgumentException("Exact expected Game Design terminal evidence required"); + } + originalOperation = originalOperation.clone(); + expectedGameDesignTerminalEvidence = expectedGameDesignTerminalEvidence.clone(); + GameDesignPublicationOperationBinding operation; + GameDesignPublicationTerminalEvidence terminal; + try { + operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); + terminal = + GameDesignPublicationTerminalEvidence.fromStored(expectedGameDesignTerminalEvidence); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Canonical complete publication operation and terminal evidence required", malformed); + } + if (!Arrays.equals(originalOperation, operation.canonicalBytes()) + || !Arrays.equals(expectedGameDesignTerminalEvidence, terminal.canonicalBytes()) + || !Arrays.equals(originalOperation, terminal.operationBytes())) { + throw new IllegalArgumentException( + "Expected terminal evidence differs from the exact original operation"); + } + if (!targetNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException( + "Original publication operation differs from the World workload namespace"); + } + } + + public static Request create( + String targetNamespace, + byte[] originalOperation, + byte[] expectedGameDesignTerminalEvidence) { + return new Request( + SCHEMA_VERSION, + targetNamespace, + UUID.randomUUID(), + originalOperation, + expectedGameDesignTerminalEvidence); + } + + @Override + public byte[] originalOperation() { + return originalOperation.clone(); + } + + @Override + public byte[] expectedGameDesignTerminalEvidence() { + return expectedGameDesignTerminalEvidence.clone(); + } + + public WorldOutcome expectedWorldOutcome() { + return worldOutcome( + GameDesignPublicationTerminalEvidence.fromStored(expectedGameDesignTerminalEvidence) + .outcome()); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals(originalOperation, that.originalOperation) + && Arrays.equals( + expectedGameDesignTerminalEvidence, that.expectedGameDesignTerminalEvidence); + } + + @Override + public int hashCode() { + int result = Objects.hash(schemaVersion, targetNamespace, readRequestId); + result = 31 * result + Arrays.hashCode(originalOperation); + return 31 * result + Arrays.hashCode(expectedGameDesignTerminalEvidence); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..4b57f0268b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodec.java @@ -0,0 +1,125 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence.WorldOutcome; +import net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadOutcome; + +/** Closed World-owned transport mapping and exact echo/outcome validation. */ +public final class WorldPublicationTerminalReadGrpcCodec { + private WorldPublicationTerminalReadGrpcCodec() {} + + public static ReadPublicationTerminalRequest toRequest( + WorldPublicationTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + return ReadPublicationTerminalRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setExpectedGameDesignTerminalEvidence( + ByteString.copyFrom(request.expectedGameDesignTerminalEvidence())) + .build(); + } + + /** Caller authenticates the exact Account peer before invoking this decoder. */ + public static WorldPublicationTerminalReadEvidence.Request fromRequest( + ReadPublicationTerminalRequest request) { + Objects.requireNonNull(request, "request"); + noUnknownFields(request); + try { + return new WorldPublicationTerminalReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + canonicalUuid(request.getReadRequestId()), + request.getOriginalOperation().toByteArray(), + request.getExpectedGameDesignTerminalEvidence().toByteArray()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "World publication terminal read request is invalid", malformed); + } + } + + /** Emits the exact original terminal only after the World owner read confirms its phase. */ + public static ReadPublicationTerminalResponse toResponse( + WorldPublicationTerminalReadEvidence.Request request, + GameDesignPublicationTerminalEvidence terminal) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(terminal, "terminal"); + var evidence = + WorldPublicationTerminalReadEvidence.fromOwnerRead( + request, request.expectedWorldOutcome(), terminal.canonicalBytes()); + return ReadPublicationTerminalResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setExpectedGameDesignTerminalEvidence( + ByteString.copyFrom(request.expectedGameDesignTerminalEvidence())) + .setWorldOutcome(toWireOutcome(evidence.worldOutcome())) + .setWorldTerminalEvidence(ByteString.copyFrom(evidence.worldTerminalEvidence())) + .build(); + } + + /** Verifies complete echo, canonical terminal bytes, and World owner phase mapping. */ + public static WorldPublicationTerminalReadEvidence fromResponse( + WorldPublicationTerminalReadEvidence.Request request, + ReadPublicationTerminalResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + noUnknownFields(response); + if (response.getSchemaVersion() != request.schemaVersion() + || !request.targetNamespace().equals(response.getTargetNamespace()) + || !request.readRequestId().toString().equals(response.getReadRequestId()) + || !Arrays.equals( + request.originalOperation(), response.getOriginalOperation().toByteArray()) + || !Arrays.equals( + request.expectedGameDesignTerminalEvidence(), + response.getExpectedGameDesignTerminalEvidence().toByteArray())) { + throw new IllegalArgumentException( + "World changed the exact publication terminal read request"); + } + WorldOutcome outcome = fromWireOutcome(response.getWorldOutcome()); + return WorldPublicationTerminalReadEvidence.fromOwnerRead( + request, outcome, response.getWorldTerminalEvidence().toByteArray()); + } + + private static WorldPublicationTerminalReadOutcome toWireOutcome(WorldOutcome outcome) { + return outcome == WorldOutcome.PUBLISHED + ? WorldPublicationTerminalReadOutcome.WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_PUBLISHED + : WorldPublicationTerminalReadOutcome.WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_ABORTED; + } + + private static WorldOutcome fromWireOutcome(WorldPublicationTerminalReadOutcome outcome) { + return switch (outcome) { + case WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_PUBLISHED -> WorldOutcome.PUBLISHED; + case WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_ABORTED -> WorldOutcome.ABORTED; + case WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("World owner terminal outcome is required"); + }; + } + + private static void noUnknownFields(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("World publication terminal read has unsupported fields"); + } + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil read UUID required"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException("Canonical non-nil read UUID required", malformed); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClientTest.java new file mode 100644 index 0000000000..e4f4139171 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClientTest.java @@ -0,0 +1,233 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.AbstractStub; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +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.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldPublicationTerminalReadClientTest { + @Test + void requiresReadableFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + for (String badPath : + java.util.List.of( + "", + "classpath:client.crt", + directory.resolve("absent.crt").toString(), + directory.toString())) { + var invalid = tls(directory); + invalid.setCertChain(badPath); + assertThatThrownBy( + () -> + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), invalid, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var noKey = tls(directory); + noKey.setPrivateKey(null); + assertThatThrownBy( + () -> + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), noKey, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + var noCa = tls(directory); + noCa.setCaCert(null); + assertThatThrownBy( + () -> + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), noCa, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), tls(directory), factory, "Test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void rejectsPlaintextWrongNamespaceAndUninitializedCallsBeforeTransport(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + var client = + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + try { + var request = request(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(factory); + } finally { + client.close(); + } + + var wrongTargetClient = + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), tls(directory), factory, "other"); + try { + assertThatThrownBy(() -> wrongTargetClient.read(request())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(factory); + } finally { + wrongTargetClient.close(); + } + } + + @Test + // The mocked channel/stub verifies client configuration and response validation, not a TLS + // handshake. + void configuresExactWorldPeerAndVerifiesResponseOutsideTransactions(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(factory.buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = new WorldPublicationTerminalReadClient(endpoints, tls(directory), factory, "test"); + try { + client.init(); + var initialized = initializedStub(client); + assertThat(initialized.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(initialized.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/world-management-service"); + + var stub = + mock( + WorldPublicationTerminalReadServiceGrpc + .WorldPublicationTerminalReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + setStub(client, stub); + var request = request(); + var operation = GameDesignPublicationOperationBinding.fromStored(request.originalOperation()); + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal( + operation, + net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome + .NO_PUBLICATION); + var expected = WorldPublicationTerminalReadGrpcCodec.toResponse(request, terminal); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(stub); + + when(stub.readPublicationTerminal(any())).thenReturn(expected); + var read = client.read(request); + assertThat(read.request()).isEqualTo(request); + assertThat(read.worldOutcome()) + .isEqualTo(WorldPublicationTerminalReadEvidence.WorldOutcome.ABORTED); + verify(stub).readPublicationTerminal(any()); + + when(stub.readPublicationTerminal(any())) + .thenReturn(expected.toBuilder().setTargetNamespace("other").build()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid publication terminal evidence"); + when(stub.readPublicationTerminal(any())) + .thenReturn(ReadPublicationTerminalResponse.getDefaultInstance()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid publication terminal evidence"); + when(stub.readPublicationTerminal(any())) + .thenThrow(Status.UNAVAILABLE.withDescription("offline").asRuntimeException()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + } finally { + client.close(); + } + } + + private static WorldPublicationTerminalReadEvidence.Request request() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal( + operation, + net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome + .NO_PUBLICATION); + return WorldPublicationTerminalReadEvidence.Request.create( + "test", operation.canonicalBytes(), terminal.canonicalBytes()); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return tls; + } + + private static AbstractStub initializedStub(WorldPublicationTerminalReadClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + private static void setStub( + WorldPublicationTerminalReadClient client, + WorldPublicationTerminalReadServiceGrpc.WorldPublicationTerminalReadServiceBlockingStub stub) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java new file mode 100644 index 0000000000..9570fe748c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.common.publication; + +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.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import org.junit.jupiter.api.Test; + +class WorldPublicationTerminalReadEvidenceTest { + @Test + void retainsExactRequestAndWorldOutcomeForPublishedAndAborted() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + for (Outcome producerOutcome : Outcome.values()) { + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, producerOutcome); + byte[] operationBytes = operation.canonicalBytes(); + byte[] terminalBytes = terminal.canonicalBytes(); + var request = + WorldPublicationTerminalReadEvidence.Request.create( + "test", operationBytes, terminalBytes); + operationBytes[0] = 0; + terminalBytes[0] = 0; + + var worldOutcome = + producerOutcome == Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED + : WorldPublicationTerminalReadEvidence.WorldOutcome.ABORTED; + var evidence = + WorldPublicationTerminalReadEvidence.fromOwnerRead( + request, worldOutcome, terminal.canonicalBytes()); + assertThat(evidence.request()).isEqualTo(request); + assertThat(evidence.worldOutcome()).isEqualTo(worldOutcome); + assertThat(evidence.terminalEvidence().outcome()).isEqualTo(producerOutcome); + assertThat(evidence.worldTerminalEvidence()).containsExactly(terminal.canonicalBytes()); + assertThat(request.originalOperation()).containsExactly(operation.canonicalBytes()); + assertThat(request.expectedGameDesignTerminalEvidence()) + .containsExactly(terminal.canonicalBytes()); + assertThat(request.readRequestId()).isNotEqualTo(new UUID(0L, 0L)); + } + } + + @Test + void rejectsInvalidRequestBindingsAndAWorldOutcomeThatDoesNotMatchTheStoredPhase() + throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.NO_PUBLICATION); + var request = + WorldPublicationTerminalReadEvidence.Request.create( + "test", operation.canonicalBytes(), terminal.canonicalBytes()); + + assertThatThrownBy( + () -> + new WorldPublicationTerminalReadEvidence.Request( + 2, + "test", + UUID.randomUUID(), + operation.canonicalBytes(), + terminal.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new WorldPublicationTerminalReadEvidence.Request( + 1, + "Test", + UUID.randomUUID(), + operation.canonicalBytes(), + terminal.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new WorldPublicationTerminalReadEvidence.Request( + 1, + "test", + new UUID(0L, 0L), + operation.canonicalBytes(), + terminal.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new WorldPublicationTerminalReadEvidence.Request( + 1, "test", UUID.randomUUID(), new byte[] {1}, terminal.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + + var changedOperation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var changedTerminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal( + changedOperation, Outcome.NO_PUBLICATION); + assertThatThrownBy( + () -> + new WorldPublicationTerminalReadEvidence.Request( + 1, + "test", + UUID.randomUUID(), + operation.canonicalBytes(), + changedTerminal.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublicationTerminalReadEvidence.fromOwnerRead( + request, + WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED, + terminal.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..ef856d253c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodecTest.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence.WorldOutcome; +import net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadOutcome; +import org.junit.jupiter.api.Test; + +class WorldPublicationTerminalReadGrpcCodecTest { + @Test + void roundTripsExactRequestAndWorldOwnedOutcomeForBothTerminalPhases() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + for (Outcome producerOutcome : Outcome.values()) { + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, producerOutcome); + var request = + WorldPublicationTerminalReadEvidence.Request.create( + "test", operation.canonicalBytes(), terminal.canonicalBytes()); + assertThat( + WorldPublicationTerminalReadGrpcCodec.fromRequest( + WorldPublicationTerminalReadGrpcCodec.toRequest(request))) + .isEqualTo(request); + + var response = WorldPublicationTerminalReadGrpcCodec.toResponse(request, terminal); + var first = WorldPublicationTerminalReadGrpcCodec.fromResponse(request, response); + var retry = WorldPublicationTerminalReadGrpcCodec.fromResponse(request, response); + WorldOutcome expectedWorldOutcome = + producerOutcome == Outcome.PUBLISHED ? WorldOutcome.PUBLISHED : WorldOutcome.ABORTED; + assertThat(first.request()).isEqualTo(request); + assertThat(first.worldOutcome()).isEqualTo(expectedWorldOutcome); + assertThat(first.terminalEvidence().outcome()).isEqualTo(producerOutcome); + assertThat(retry.worldTerminalEvidence()).containsExactly(terminal.canonicalBytes()); + assertThat(response.getWorldOutcome()) + .isEqualTo( + producerOutcome == Outcome.PUBLISHED + ? WorldPublicationTerminalReadOutcome + .WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_PUBLISHED + : WorldPublicationTerminalReadOutcome + .WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_ABORTED); + } + } + + @Test + void rejectsUnknownOrNoncanonicalRequestAndEveryChangedEchoOrOutcome() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.NO_PUBLICATION); + var request = + WorldPublicationTerminalReadEvidence.Request.create( + "test", operation.canonicalBytes(), terminal.canonicalBytes()); + var wireRequest = WorldPublicationTerminalReadGrpcCodec.toRequest(request); + for (ReadPublicationTerminalRequest invalid : + List.of( + wireRequest.toBuilder().setUnknownFields(unknown()).build(), + wireRequest.toBuilder().setSchemaVersion(2).build(), + wireRequest.toBuilder().setTargetNamespace("Test").build(), + wireRequest.toBuilder() + .setReadRequestId("00000000-0000-0000-0000-000000000000") + .build(), + wireRequest.toBuilder() + .setReadRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA") + .build(), + wireRequest.toBuilder().setReadRequestId("1-1-1-1-1").build(), + wireRequest.toBuilder().setOriginalOperation(ByteString.EMPTY).build(), + wireRequest.toBuilder() + .setExpectedGameDesignTerminalEvidence(ByteString.copyFrom(new byte[] {1})) + .build())) { + assertThatThrownBy(() -> WorldPublicationTerminalReadGrpcCodec.fromRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + var response = WorldPublicationTerminalReadGrpcCodec.toResponse(request, terminal); + var changedOperation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var changedTerminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal( + changedOperation, Outcome.NO_PUBLICATION); + for (var invalid : + List.of( + response.toBuilder().setUnknownFields(unknown()).build(), + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setReadRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder() + .setOriginalOperation(ByteString.copyFrom(changedOperation.canonicalBytes())) + .build(), + response.toBuilder() + .setExpectedGameDesignTerminalEvidence( + ByteString.copyFrom(changedTerminal.canonicalBytes())) + .build(), + response.toBuilder() + .setWorldOutcome( + WorldPublicationTerminalReadOutcome + .WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_PUBLISHED) + .build(), + response.toBuilder() + .setWorldOutcome( + WorldPublicationTerminalReadOutcome + .WORLD_PUBLICATION_TERMINAL_READ_OUTCOME_UNSPECIFIED) + .build(), + response.toBuilder().clearWorldTerminalEvidence().build(), + response.toBuilder() + .setWorldTerminalEvidence(ByteString.copyFrom(changedTerminal.canonicalBytes())) + .build())) { + assertThatThrownBy(() -> WorldPublicationTerminalReadGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> WorldPublicationTerminalReadGrpcCodec.toResponse(request, changedTerminal)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 476c552ff3..bb7eb81ad7 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -26,13 +26,19 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; 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.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadGrpcCodec; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; @@ -53,7 +59,11 @@ import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadService; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; @@ -65,6 +75,7 @@ import net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures; import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflow; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; @@ -396,7 +407,8 @@ void publishAttemptSaveUsesRevisionCasAndRejectsStaleAndTerminalUpdates() { } @Test - void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogether() { + void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogether( + @TempDir Path temporary) throws Exception { String tenantId = "9002"; Game game = new Game(); game.setTenantId(tenantId); @@ -411,6 +423,8 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth candidate.setNotes("successful transaction proof"); candidate = versionRepository.save(candidate); var operation = reserveSelectedDraft(candidate, "successful transaction proof"); + var terminalPki = new SelectionReadTestPki(Files.createDirectories(temporary.resolve("pki"))); + assertTerminalOwnerReadOverMtls(operation, null, terminalPki); assertThat(candidate.getTenantId()).isEqualTo(tenantId); assertThat(candidate.getTenantId()).isNotEqualTo(candidate.getCanonicalTenantId().toString()); assertThat(operation.workflowId()) @@ -492,6 +506,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth assertThat(terminalOperation.outcome()).isEqualTo("PUBLISHED"); assertThat(terminalOperation.terminalEvidenceBytes()).isNotNull(); publishAttemptRepository.requirePublishedOperation(attempt); + assertTerminalOwnerReadOverMtls(operation, Outcome.PUBLISHED, terminalPki); } @Test @@ -642,7 +657,8 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( } @Test - void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet() { + void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( + @TempDir Path temporary) throws Exception { String tenantId = "9003"; Game game = new Game(); game.setTenantId(tenantId); @@ -667,6 +683,8 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( AtomicReference candidateVersionId = new AtomicReference<>(); AtomicReference candidateVersionNumber = new AtomicReference<>(); var operation = reserveSelectedDraft(candidate, "failed remap proof"); + var terminalPki = new SelectionReadTestPki(Files.createDirectories(temporary.resolve("pki"))); + assertTerminalOwnerReadOverMtls(operation, null, terminalPki); String publishRequestId = operation.account().publishRequestId(); String publishWorkflowId = operation.workflowId(); long selectedCandidateVersionId = candidate.getId(); @@ -808,6 +826,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( assertThat(terminalOperation.outcome()).isEqualTo("NO_PUBLICATION"); assertThat(terminalOperation.terminalEvidenceBytes()).isNotNull(); publishAttemptRepository.requireNoPublicationOperation(attempt); + assertTerminalOwnerReadOverMtls(operation, Outcome.NO_PUBLICATION, terminalPki); } /** @@ -948,6 +967,180 @@ void retainedSelectedDraftOwnerReadOverMtlsReplaysExactlyAndDeniesSubstitution( } } + /** + * Real GD PostgreSQL terminal backing and production loopback mTLS transport. Upstream Account, + * World, participant digests and asset export remain stipulated by the surrounding owner case; + * this does not prove cross-owner issuance/APPLIED provenance, settlement, custody or activation. + * A null expected outcome checks the actual reserved PENDING row before finalization. + */ + private void assertTerminalOwnerReadOverMtls( + GameDesignPublicationOperation operation, Outcome expected, SelectionReadTestPki pki) + throws Exception { + var repository = new GameDesignPublicationOperationRepository(dsl); + var before = repository.read(operation.workflowId()).orElseThrow(); + assertThat(before.operation().canonicalBytes()).containsExactly(operation.canonicalBytes()); + assertThat(before.outcome()).isEqualTo(expected == null ? "PENDING" : expected.name()); + byte[] originalTerminal = before.terminalEvidenceBytes(); + if (expected != null) { + assertThat(originalTerminal).isNotEmpty(); + // Existing immutability guards must reject backing replacement; do not disable them to + // manufacture corrupt historical evidence. This write transaction ends before any RPC. + assertThatThrownBy( + () -> + inOwnerTransaction( + () -> + dsl.execute( + "UPDATE game_design_publication_operation SET terminal_evidence_bytes = ?" + + " WHERE publish_workflow_id = ?", + new byte[] {1}, + operation.workflowId()))) + .rootCause() + .isInstanceOf(java.sql.SQLException.class) + .hasMessageContaining("immutable") + .satisfies( + failure -> + assertThat(((java.sql.SQLException) failure).getSQLState()).isEqualTo("23514")); + } + var binding = GameDesignPublicationOperationBinding.fromStored(operation.canonicalBytes()); + var request = GameDesignPublicationTerminalReadEvidence.Request.create("test", binding); + var changedAccount = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + operation.account().input(), + operation.account().sources()); + var substituted = new GameDesignPublicationOperationBinding(changedAccount, operation.world()); + var missing = + IsolatedPublicationOperationFixtures.fresh( + operation.account().input().selection().target()); + assertThat(repository.read(missing.workflowId())).isEmpty(); + var endpoint = + new GameDesignPublicationTerminalReadGrpcService( + new GameDesignPublicationTerminalReadService(repository, transactionManager, "test"), + "test"); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + pki.server.certificate().toFile(), pki.server.key().toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + try { + for (var identity : List.of(pki.account, pki.worldManagement)) { + try (var client = terminalReadClient(server.getPort(), identity, pki.ca)) { + if (expected == null) { + assertSelectionReadCode(Status.Code.FAILED_PRECONDITION, () -> client.read(request)); + } else { + var first = client.read(request); + var retry = client.read(request); + assertThat(first.request()).isEqualTo(request); + assertThat(retry.request()).isEqualTo(request); + assertThat(first.request().originalOperation()) + .containsExactly(operation.canonicalBytes()); + assertThat(first.terminalEvidence().operationBytes()) + .containsExactly(operation.canonicalBytes()); + assertThat(first.terminalEvidence().canonicalBytes()).containsExactly(originalTerminal); + assertThat(retry.terminalEvidence().canonicalBytes()).containsExactly(originalTerminal); + assertThat(first.terminalEvidence().outcome()).isEqualTo(expected); + var fresh = GameDesignPublicationTerminalReadEvidence.Request.create("test", binding); + var freshResult = client.read(fresh); + assertThat(freshResult.request()).isEqualTo(fresh); + assertThat(freshResult.terminalEvidence().canonicalBytes()) + .containsExactly(originalTerminal); + } + assertSelectionReadCode( + Status.Code.NOT_FOUND, + () -> + client.read( + GameDesignPublicationTerminalReadEvidence.Request.create( + "test", + GameDesignPublicationOperationBinding.fromStored( + missing.canonicalBytes())))); + assertSelectionReadCode( + Status.Code.FAILED_PRECONDITION, + () -> + client.read( + GameDesignPublicationTerminalReadEvidence.Request.create( + "test", substituted))); + } + } + for (var identity : List.of(pki.wrongWorkload, pki.otherNamespace, pki.otherWorldNamespace)) { + try (var client = terminalReadClient(server.getPort(), identity, pki.ca)) { + assertSelectionReadCode(Status.Code.PERMISSION_DENIED, () -> client.read(request)); + } + } + // A strict client cannot construct malformed input. Use an authenticated test-only wire + // stub to exercise the actual receiver's closed-schema rejection, without minting evidence. + var channel = + new GrpcChannelFactory() + .buildChannel( + "127.0.0.1:" + server.getPort(), 6565, pki.account.properties(pki.ca), true); + try { + var stub = + GameDesignPublicationTerminalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials( + new GrpcServerPeerIdentityCallCredentials( + "spiffe://firemud/ns/test/sa/game-design-service")) + .withDeadlineAfter(5, TimeUnit.SECONDS); + var wire = GameDesignPublicationTerminalReadGrpcCodec.toRequest(request); + for (var invalid : + List.of( + wire.toBuilder() + .setOriginalOperation(com.google.protobuf.ByteString.copyFrom(new byte[] {1})) + .build(), + wire.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1) + .build()) + .build()) + .build())) { + assertSelectionReadCode( + Status.Code.INVALID_ARGUMENT, () -> stub.readPublicationTerminal(invalid)); + } + assertSelectionReadCode( + Status.Code.PERMISSION_DENIED, + () -> + stub.readPublicationTerminal(wire.toBuilder().setTargetNamespace("other").build())); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + var after = repository.read(operation.workflowId()).orElseThrow(); + assertThat(after.operation().canonicalBytes()) + .containsExactly(before.operation().canonicalBytes()); + assertThat(after.outcome()).isEqualTo(before.outcome()); + assertThat(after.receiptBytes()).isEqualTo(before.receiptBytes()); + assertThat(after.terminalEvidenceBytes()).isEqualTo(originalTerminal); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static GameDesignPublicationTerminalReadClient terminalReadClient( + int port, SelectionReadTestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + port); + var client = + new GameDesignPublicationTerminalReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), "test"); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + private static AuthoredDraftPublishSelectionBinding selectionReadVariant( AuthoredDraftPublishSelectionBinding original, String publishRequestId, String notes) { var intent = original.intent(); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifier.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifier.java new file mode 100644 index 0000000000..cefffe8e4b --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifier.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered World verifier for the immutable Game Design publication terminal. + * + *

The authenticated read proves only the exact historical Game Design result. Its local + * authority token stays valid through the World commit but is not an Account source lock, a + * settlement, or permission to release Account participation. Account source protection remains + * governed by its original pending publication order and owner-side writer guards. + */ +final class WorldGameDesignPublicationTerminalVerifier + implements WorldPublicationTerminalService.TerminalAuthorityVerifier { + private final String workloadNamespace; + private final GameDesignPublicationTerminalReadClient terminalReadClient; + + WorldGameDesignPublicationTerminalVerifier( + String workloadNamespace, GameDesignPublicationTerminalReadClient terminalReadClient) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.terminalReadClient = Objects.requireNonNull(terminalReadClient, "terminalReadClient"); + } + + @Override + public WorldPublicationTerminalService.VerifiedTerminal authenticateAndVerifyAndHold( + byte[] operationBytes, byte[] terminalBytes) { + requireAuthenticatedGameDesignCaller(); + requireNoAmbientTransaction(); + Objects.requireNonNull(operationBytes, "operationBytes"); + Objects.requireNonNull(terminalBytes, "terminalBytes"); + + GameDesignPublicationOperationBinding operation = + GameDesignPublicationOperationBinding.fromStored(operationBytes); + if (!Arrays.equals(operationBytes, operation.canonicalBytes())) { + throw new IllegalArgumentException("Canonical original Game Design operation required"); + } + GameDesignPublicationTerminalReadEvidence.Request request = + GameDesignPublicationTerminalReadEvidence.Request.create(workloadNamespace, operation); + GameDesignPublicationTerminalReadEvidence read = terminalReadClient.read(request); + if (read == null + || !request.equals(read.request()) + || !Arrays.equals(request.originalOperation(), operationBytes)) { + throw new SecurityException( + "Game Design terminal read differs from the exact original operation request"); + } + + GameDesignPublicationTerminalEvidence terminal = read.terminalEvidence(); + if (terminal == null + || !Arrays.equals(operationBytes, terminal.operationBytes()) + || !Arrays.equals(terminalBytes, terminal.canonicalBytes())) { + throw new SecurityException( + "Authenticated Game Design terminal differs from the submitted exact operation or result"); + } + WorldPublicationTerminal.Request worldRequest = + WorldPublicationTerminal.Request.fromStored(terminal.canonicalBytes()); + return new WorldPublicationTerminalService.VerifiedTerminal( + worldRequest, new ExactTerminalReadAuthority(operationBytes, terminal.canonicalBytes())); + } + + private void requireAuthenticatedGameDesignCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(workloadNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "World publication terminal requires the authenticated same-namespace Game Design workload"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World publication terminal must read Game Design evidence outside owner transactions"); + } + } + + private static final class ExactTerminalReadAuthority + implements WorldPublicationTerminalService.HeldTerminalAuthority { + private final byte[] operationBytes; + private final byte[] terminalBytes; + private final AtomicBoolean open = new AtomicBoolean(true); + + private ExactTerminalReadAuthority(byte[] operationBytes, byte[] terminalBytes) { + this.operationBytes = operationBytes.clone(); + this.terminalBytes = terminalBytes.clone(); + } + + @Override + public void requireHeld() { + if (!open.get() + || operationBytes.length == 0 + || terminalBytes.length == 0 + || !Arrays.equals( + operationBytes, + WorldPublicationTerminal.Request.fromStored(terminalBytes).operationBytes())) { + throw new IllegalStateException( + "Exact authenticated Game Design terminal read authority is no longer valid"); + } + } + + @Override + public void close() { + open.set(false); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcService.java new file mode 100644 index 0000000000..40337ab45f --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcService.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadServiceGrpc; + +/** Standalone Account-authenticated transport; deliberately not registered at runtime. */ +public final class WorldPublicationTerminalReadGrpcService + extends WorldPublicationTerminalReadServiceGrpc.WorldPublicationTerminalReadServiceImplBase { + private final WorldPublicationTerminalReadService owner; + private final String workloadNamespace; + + public WorldPublicationTerminalReadGrpcService( + WorldPublicationTerminalReadService owner, String workloadNamespace) { + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readPublicationTerminal( + ReadPublicationTerminalRequest request, + StreamObserver observer) { + try { + requireAuthenticatedAccountPeer(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final WorldPublicationTerminalReadEvidence.Request decoded; + try { + // Do not parse the supplied operation or terminal until the Account workload is + // authenticated. + decoded = WorldPublicationTerminalReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World publication terminal read is required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("World publication terminal namespace differs from the owner") + .asRuntimeException()); + return; + } + + final ReadPublicationTerminalResponse response; + try { + GameDesignPublicationTerminalEvidence terminal = owner.read(decoded); + response = WorldPublicationTerminalReadGrpcCodec.toResponse(decoded, terminal); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + return; + } catch (IllegalArgumentException inconsistent) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("World publication terminal evidence is inconsistent") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + observer.onError( + Status.INTERNAL + .withDescription("World publication terminal read failed") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private void requireAuthenticatedAccountPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service").equals(peer.uri()) + || !peer.isService("account-service") + || !peer.isInNamespace(workloadNamespace)) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Account workload required") + .asRuntimeException(); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java new file mode 100644 index 0000000000..408db6ba92 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; +import org.springframework.dao.DataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone World owner read of its exact persisted publication terminal and phase. */ +public final class WorldPublicationTerminalReadService { + private final WorldPublicationTerminalRepository repository; + private final String workloadNamespace; + + public WorldPublicationTerminalReadService( + WorldPublicationTerminalRepository repository, String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Complete operation and terminal bytes are lookup identity only, never Account authority. */ + public GameDesignPublicationTerminalEvidence read( + WorldPublicationTerminalReadEvidence.Request request) { + requireAuthenticatedAccountPeer(); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("World publication terminal namespace differs from the owner") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent World publication terminal snapshot required") + .asRuntimeException(); + } + + final GameDesignPublicationOperationBinding operation; + final WorldPublicationTerminal.Request terminalRequest; + try { + operation = GameDesignPublicationOperationBinding.fromStored(request.originalOperation()); + terminalRequest = + WorldPublicationTerminal.request(request.expectedGameDesignTerminalEvidence()); + } catch (RuntimeException malformed) { + throw Status.INVALID_ARGUMENT + .withDescription("Canonical original publication operation and terminal are required") + .asRuntimeException(); + } + if (!Arrays.equals(operation.canonicalBytes(), request.originalOperation()) + || !Arrays.equals(terminalRequest.operationBytes(), request.originalOperation()) + || !Arrays.equals( + terminalRequest.terminalBytes(), request.expectedGameDesignTerminalEvidence()) + || !workloadNamespace.equals(operation.world().request().targetNamespace())) { + throw Status.FAILED_PRECONDITION + .withDescription("World terminal lookup differs from the exact original publication") + .asRuntimeException(); + } + + try { + GameDesignPublicationTerminalEvidence committed = + repository + .readCommitted(terminalRequest) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact committed World terminal is unavailable") + .asRuntimeException()); + if (!Arrays.equals( + request.expectedGameDesignTerminalEvidence(), committed.canonicalBytes())) { + throw Status.FAILED_PRECONDITION + .withDescription("World terminal differs from the exact expected Game Design result") + .asRuntimeException(); + } + // readCommitted verifies the World owner phase against this exact original terminal. + return committed; + } catch (StatusRuntimeException failure) { + throw failure; + } catch (WorldPublicationTerminalRepository.PublicationTerminalConflictException conflict) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact World publication terminal owner evidence is unavailable") + .asRuntimeException(); + } catch (DataAccessException | org.jooq.exception.DataAccessException unavailable) { + throw Status.UNAVAILABLE + .withDescription("World publication terminal owner read is unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException inconsistent) { + throw Status.FAILED_PRECONDITION + .withDescription("World publication terminal owner evidence is inconsistent") + .asRuntimeException(); + } catch (RuntimeException failure) { + throw Status.INTERNAL + .withDescription("World publication terminal owner read failed") + .asRuntimeException(); + } + } + + private void requireAuthenticatedAccountPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + String expected = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + if (!expected.equals(peer.uri()) + || !peer.isService("account-service") + || !peer.isInNamespace(workloadNamespace)) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Account workload required") + .asRuntimeException(); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java index 86a1194249..d7a99eed12 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java @@ -7,7 +7,11 @@ import java.util.HexFormat; import java.util.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import org.jooq.DSLContext; import org.jooq.Record; @@ -34,7 +38,11 @@ public final class WorldPublicationTerminalRepository { + "a.publish_workflow_id AS joined_attempt_publish_workflow_id, " + "a.applied_commit_id AS joined_attempt_applied_commit_id, " + "a.content_digest AS joined_attempt_content_digest, " - + "a.digest_schema_version AS joined_attempt_digest_schema_version " + + "a.digest_schema_version AS joined_attempt_digest_schema_version, " + + "q.account_operation_id AS joined_account_operation_id, " + + "q.account_fence_id AS joined_account_fence_id, " + + "q.account_binding_bytes AS joined_account_binding_bytes, " + + "q.account_binding_digest AS joined_account_binding_digest " + "FROM world_design_publication_terminal t " + "LEFT JOIN world_design_publication_fence_attempt a " + "ON a.publication_fence=t.publication_fence " @@ -42,14 +50,22 @@ public final class WorldPublicationTerminalRepository { + "ON o.target_namespace=a.target_namespace " + "AND o.canonical_tenant_id=a.canonical_tenant_id " + "AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id " + + "LEFT JOIN world_design_publication_account_binding q " + + "ON q.publication_fence=t.publication_fence " + "WHERE t.publication_fence=?"; private static final String ORIGINAL_OWNER_READ = - "SELECT a.*, o.owner_freeze_phase, o.current_publication_fence " + "SELECT a.*, o.owner_freeze_phase, o.current_publication_fence, " + + "q.account_operation_id AS joined_account_operation_id, " + + "q.account_fence_id AS joined_account_fence_id, " + + "q.account_binding_bytes AS joined_account_binding_bytes, " + + "q.account_binding_digest AS joined_account_binding_digest " + "FROM world_design_publication_fence_attempt a " + "JOIN world_design_publication_fence_owner o " + "ON o.target_namespace=a.target_namespace " + "AND o.canonical_tenant_id=a.canonical_tenant_id " + "AND o.local_tenant_key=a.local_tenant_key AND o.version_id=a.version_id " + + "LEFT JOIN world_design_publication_account_binding q " + + "ON q.publication_fence=a.publication_fence " + "WHERE a.publication_fence=? AND a.target_namespace=? " + "AND a.canonical_tenant_id=? AND a.canonical_version_id=? " + "AND o.current_publication_fence=a.publication_fence"; @@ -172,7 +188,7 @@ private Record lockOriginalOwner(WorldPublicationTerminal.Request request) { world.targetNamespace(), world.canonicalTenantId(), world.canonicalVersionId()); - requireOriginalOwnerBinding(world, row); + requireOriginalOwnerBinding(request, row); return row; } @@ -189,7 +205,7 @@ private void requirePendingOwner(WorldPublicationTerminal.Request request) { throw new PublicationTerminalConflictException( "World terminal request has no exact retained V25 attempt and current owner association"); } - requireOriginalOwnerBinding(world, owner); + requireOriginalOwnerBinding(request, owner); if (!"FROZEN".equals(required(owner, "owner_freeze_phase", String.class))) { throw new PublicationTerminalConflictException( "Missing World publication terminal conflicts with the retained owner phase"); @@ -197,7 +213,8 @@ private void requirePendingOwner(WorldPublicationTerminal.Request request) { } private static void requireOriginalOwnerBinding( - WorldPublishedStartLocationEvidence.Request world, Record row) { + WorldPublicationTerminal.Request request, Record row) { + WorldPublishedStartLocationEvidence.Request world = request.worldEvidence().request(); if (row == null) { throw new PublicationTerminalConflictException( "World terminal request has no exact retained V25 attempt and current owner association"); @@ -219,6 +236,34 @@ private static void requireOriginalOwnerBinding( throw new PublicationTerminalConflictException( "World terminal evidence differs from its exact immutable V25 publication checkpoint"); } + requireQualifiedAccountBinding(request, row); + } + + private static void requireQualifiedAccountBinding( + WorldPublicationTerminal.Request request, Record row) { + var operation = GameDesignPublicationOperationBinding.fromStored(request.operationBytes()); + UUID storedOperationId = required(row, "joined_account_operation_id", java.util.UUID.class); + UUID storedFenceId = required(row, "joined_account_fence_id", java.util.UUID.class); + byte[] storedBytes = required(row, "joined_account_binding_bytes", byte[].class); + String storedDigest = required(row, "joined_account_binding_digest", String.class); + final AccountPublicationAuthorizationBinding retained; + try { + retained = AccountPublicationAuthorizationBinding.fromStored(storedBytes); + } catch (RuntimeException invalid) { + throw new InvalidPublicationTerminalEvidenceException( + "Retained World Account publication qualification is not canonical"); + } + AccountPublicationAuthorizationBinding original = operation.account(); + if (!DraftAuthorizationFenceBinding.digest(storedBytes).equals(storedDigest) + || !storedOperationId.equals(retained.operationId()) + || !storedFenceId.equals(retained.fenceId()) + || !original.operationId().equals(storedOperationId) + || !original.fenceId().equals(storedFenceId) + || !Arrays.equals(original.canonicalBytes(), storedBytes) + || !Arrays.equals(retained.canonicalBytes(), storedBytes)) { + throw new PublicationTerminalConflictException( + "World terminal operation differs from its exact original Account publication qualification"); + } } private void insertTerminal(WorldPublicationTerminal.Request request) { @@ -274,6 +319,7 @@ private Record readTerminalWithOwner(WorldPublicationTerminal.Request request, b private GameDesignPublicationTerminalEvidence exactReadback( WorldPublicationTerminal.Request request, Record row) { + requireQualifiedAccountBinding(request, row); byte[] stored = required(row, "terminal_evidence_bytes", byte[].class); if (!request.exactBytes(stored)) { throw new PublicationTerminalConflictException( diff --git a/services/world-management-service/src/main/resources/db/migration/V54__world_publication_terminal_account_binding.sql b/services/world-management-service/src/main/resources/db/migration/V54__world_publication_terminal_account_binding.sql new file mode 100644 index 0000000000..cec14bd1e5 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V54__world_publication_terminal_account_binding.sql @@ -0,0 +1,115 @@ +-- Keep Game Design's complete original Account publication order bound to the exact World +-- terminal operation, rather than substituting the older Account Draft authorization receipt. +-- [jooq ignore start] +CREATE FUNCTION world_publication_operation_frame(operation_bytes BYTEA, frame_offset INTEGER) +RETURNS BYTEA +LANGUAGE plpgsql IMMUTABLE STRICT +AS $$ +DECLARE + frame_length BIGINT; + remaining_bytes BIGINT; +BEGIN + IF frame_offset < 0 OR frame_offset > octet_length(operation_bytes) - 4 THEN + RAISE EXCEPTION 'World publication operation contains a truncated frame header' + USING ERRCODE = '23514'; + END IF; + + frame_length := + get_byte(operation_bytes, frame_offset)::BIGINT * 16777216 + + get_byte(operation_bytes, frame_offset + 1)::BIGINT * 65536 + + get_byte(operation_bytes, frame_offset + 2)::BIGINT * 256 + + get_byte(operation_bytes, frame_offset + 3)::BIGINT; + remaining_bytes := octet_length(operation_bytes)::BIGINT - frame_offset::BIGINT - 4; + IF frame_length > 4194304 OR frame_length > remaining_bytes THEN + RAISE EXCEPTION 'World publication operation contains a negative or oversized frame' + USING ERRCODE = '23514'; + END IF; + RETURN substring(operation_bytes FROM frame_offset + 5 FOR frame_length::INTEGER); +END; +$$; +REVOKE ALL ON FUNCTION world_publication_operation_frame(BYTEA, INTEGER) FROM PUBLIC; + +CREATE FUNCTION world_require_publication_operation_account_binding( + p_operation_bytes BYTEA, + p_publication_fence UUID, + p_world_evidence_bytes BYTEA +) +RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + frame_offset INTEGER := 0; + schema_bytes BYTEA; + account_binding_bytes BYTEA; + framed_world_evidence BYTEA; + retained_account_binding BYTEA; + retained_account_digest VARCHAR(71); +BEGIN + IF p_operation_bytes IS NULL + OR octet_length(p_operation_bytes) > 4194304 + OR octet_length(p_operation_bytes) < 4 THEN + RAISE EXCEPTION 'World publication operation is empty or oversized' + USING ERRCODE = '23514'; + END IF; + + schema_bytes := world_publication_operation_frame(p_operation_bytes, frame_offset); + IF schema_bytes IS DISTINCT FROM convert_to('game-design-publication-operation/v1', 'UTF8') THEN + RAISE EXCEPTION 'World publication operation has an unsupported schema frame' + USING ERRCODE = '23514'; + END IF; + frame_offset := frame_offset + 4 + octet_length(schema_bytes); + + account_binding_bytes := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(account_binding_bytes); + + framed_world_evidence := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(framed_world_evidence); + IF frame_offset <> octet_length(p_operation_bytes) THEN + RAISE EXCEPTION 'World publication operation contains trailing frames or bytes' + USING ERRCODE = '23514'; + END IF; + IF framed_world_evidence IS DISTINCT FROM p_world_evidence_bytes THEN + RAISE EXCEPTION 'World publication operation differs from its exact World evidence' + USING ERRCODE = '23514'; + END IF; + + SELECT q.account_binding_bytes, q.account_binding_digest + INTO STRICT retained_account_binding, retained_account_digest + FROM "${serviceSchema}".world_design_publication_account_binding q + WHERE q.publication_fence = p_publication_fence; + IF encode(sha256(retained_account_binding), 'hex') + IS DISTINCT FROM substring(retained_account_digest FROM 8) THEN + RAISE EXCEPTION 'World publication Account qualification has a corrupt binding digest' + USING ERRCODE = '23514'; + END IF; + + RETURN account_binding_bytes IS NOT DISTINCT FROM retained_account_binding; +END; +$$; +REVOKE ALL ON FUNCTION world_require_publication_operation_account_binding(BYTEA, UUID, BYTEA) + FROM PUBLIC; + +-- Add only the exact original-order guard to V44's terminal validator. The original body remains +-- the source of every existing owner, APPLIED, selector, digest, release and outcome check. +DO $migration$ +DECLARE + original TEXT; + operation_anchor TEXT := $anchor$ world_evidence := convert_from(NEW.world_evidence_bytes, 'UTF8')::JSONB;$anchor$; + operation_guard TEXT := $replacement$ IF NOT world_require_publication_operation_account_binding( + NEW.operation_bytes, NEW.publication_fence, NEW.world_evidence_bytes) THEN + RAISE EXCEPTION 'World terminal operation differs from the exact qualified Account publication binding' + USING ERRCODE = '23514'; + END IF; + world_evidence := convert_from(NEW.world_evidence_bytes, 'UTF8')::JSONB;$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_publication_terminal()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, operation_anchor, ''))) + / length(operation_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V44 World terminal evidence decode anchor'; + END IF; + EXECUTE replace(original, operation_anchor, operation_guard); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java index e20deac775..50dfc77c87 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java @@ -977,11 +977,18 @@ void v32PreservesOriginalSchema2SnapshotBytesAndExactRetry() throws Exception { for (String table : tables) { String override = table.equals("world_authored_version_identity") ? " OVERRIDING SYSTEM VALUE" : ""; + String historicalColumns = + table.equals("world_design_publication_fence_attempt") + ? retainedColumns(retained, schema, table) + : null; retained.execute( "INSERT INTO " + table + + (historicalColumns == null ? "" : " (" + historicalColumns + ")") + override - + " SELECT * FROM world_management_service." + + " SELECT " + + (historicalColumns == null ? "*" : historicalColumns) + + " FROM world_management_service." + table + " WHERE local_tenant_key=?", fixture.intakeReceipt().localTenantKey()); @@ -1013,7 +1020,8 @@ void v32PreservesOriginalSchema2SnapshotBytesAndExactRetry() throws Exception { String attemptBefore = Objects.requireNonNull( retained.fetchOne( - "SELECT to_jsonb(t)::text FROM world_design_publication_fence_attempt t"), + "SELECT (to_jsonb(t) - 'attempt_created_full_xid')::text " + + "FROM world_design_publication_fence_attempt t"), "expected retained publication-fence attempt row") .get(0, String.class); Flyway.configure() @@ -1034,10 +1042,25 @@ void v32PreservesOriginalSchema2SnapshotBytesAndExactRetry() throws Exception { assertThat( Objects.requireNonNull( retained.fetchOne( - "SELECT to_jsonb(t)::text FROM world_design_publication_fence_attempt t"), + "SELECT (to_jsonb(t) - 'attempt_created_full_xid')::text " + + "FROM world_design_publication_fence_attempt t"), "expected retained publication-fence attempt row") .get(0, String.class)) .isEqualTo(attemptBefore); + assertThat( + retained + .resultQuery( + "SELECT count(*) FROM world_design_publication_fence_attempt " + + "WHERE attempt_created_full_xid IS NULL") + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat( + retained + .resultQuery( + "SELECT count(*) FROM world_design_publication_fence_attempt " + + "WHERE attempt_created_full_xid IS NOT NULL") + .fetchOne(0, Long.class)) + .isZero(); var repo = new WorldAuthoredGraphSnapshotRepository(retained); var capture = new WorldAuthoredGraphSnapshotCapture( @@ -1334,6 +1357,18 @@ private long snapshotCount(UUID fence) { "Snapshot count query returned no value"); } + private String retainedColumns(DSLContext retained, String schema, String table) { + return Objects.requireNonNull( + retained + .resultQuery( + "SELECT string_agg(quote_ident(column_name), ', ' ORDER BY ordinal_position) " + + "FROM information_schema.columns WHERE table_schema = ? AND table_name = ?", + schema, + table) + .fetchOne(0, String.class), + "historical fixture must expose its original columns"); + } + private List syntheticRetentionRowCounts(Fixture fixture) { return SYNTHETIC_RETENTION_TABLES.stream() .map( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java index 9b4327a641..e57ad5895b 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java @@ -465,6 +465,8 @@ void v31UpgradePreservesExistingV30SourceRowsMappingsResultsAndFrozenCheckpoint( .load() .migrate(); assertThat(retainedRows(retained, tables)).isEqualTo(before); + assertRetainedAttemptBirthStampsAreNull( + retained, before.get("world_design_publication_fence_attempt").size()); assertNoPromotionOfRetainedTopology(retained); assertThat( retained @@ -498,7 +500,9 @@ private Map> retainedRows(DSLContext database, Map> retainedRows(DSLContext database, Map { WorldDraftTopologyCommitPlan draft = topologyPlan(fixture); - appliedComponent().apply(draftApplication(draft)); + var draftApplication = draftApplication(draft); + appliedComponent().apply(draftApplication); var owner = draft.ownerBinding(); String publicationRequest = "preparation-capture-" + UUID.randomUUID(); // V27/release evidence retains the post-publication epoch; the original Draft freeze @@ -1385,10 +1387,13 @@ private WorldCanonicalInstanceTopologyPlan frozenPlan(Fixture fixture) { long freezeEpoch = Math.subtractExact( fixture.versionIdentity().versionStateEvidence().versionStateEpoch(), 1L); - String requestDigest = - publicationSelection(draft, publicationRequest, freezeEpoch) - .digest() - .substring("sha256:".length()); + var selection = publicationSelection(draft, publicationRequest, freezeEpoch); + String requestDigest = selection.digest().substring("sha256:".length()); + var accountBinding = + isolatedPublicationAccountBinding( + draftApplication.operation().accountBindingBytes(), + selection, + publicationRequest); WorldDesignPublicationFenceEvidence evidence = new WorldDesignPublicationFenceEvidence( owner.targetNamespace(), @@ -1409,25 +1414,35 @@ private WorldCanonicalInstanceTopologyPlan frozenPlan(Fixture fixture) { + owner.canonicalTenantId() + ":publish-request:" + publicationRequest); + var attemptCreatedInTransaction = new AtomicBoolean(); var attempt = Objects.requireNonNull( ownerTransaction() .execute( - status -> - publicationFence.claimFreeze( - evidence, - () -> { - var digest = - digestService.getDraftDesignDigest( - Long.toString( - fixture.source().receipt().localTenantKey()), - Long.toString( - fixture.versionIdentity().localVersionKey())); - return new WorldDesignPublicationFenceEvidence.Checkpoint( - draft.binding().commitId().toString(), - digest.contentDigest(), - 3); - })), + status -> { + var frozenAttempt = + publicationFence.claimFreeze( + evidence, + () -> { + var digest = + digestService.getDraftDesignDigest( + Long.toString( + fixture.source().receipt().localTenantKey()), + Long.toString( + fixture.versionIdentity().localVersionKey())); + attemptCreatedInTransaction.set(true); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + draft.binding().commitId().toString(), + digest.contentDigest(), + 3); + }); + new WorldSelectedDraftPublicationAuthorizationRepository(dsl) + .retainOrRequireExact( + frozenAttempt, + accountBinding, + attemptCreatedInTransaction.get()); + return frozenAttempt; + }), "Synthetic frozen preparation fixture returned no publication checkpoint"); List tuples = draft.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() @@ -1595,8 +1610,6 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( throw new IllegalStateException( "Isolated PUBLISHED terminal must retain the next publication epoch after its World freeze"); } - var originalAccount = - DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()); var selection = publicationSelection( input.topologyPlan().sourceBinding().plan(), @@ -1607,24 +1620,8 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( "Isolated publication selection differs from the retained World request digest"); } var account = - new AccountPublicationAuthorizationBinding( - UUID.nameUUIDFromBytes( - (world.request().publicationFence() + "/account-operation") - .getBytes(StandardCharsets.UTF_8)), - UUID.nameUUIDFromBytes( - (world.request().publicationFence() + "/account-fence") - .getBytes(StandardCharsets.UTF_8)), - new AccountPublicationAuthorizationBinding.PreallocationInput( - originalAccount.actorAccountId(), selection), - List.of( - new DraftAuthorizationFenceBinding.SourceEvidence( - DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, - originalAccount.actorAccountId().toString(), - "1", - "1", - null, - null, - new byte[] {1}))); + isolatedPublicationAccountBinding( + world.originalAccountBindingBytes(), selection, world.request().publicationRequestId()); var operation = new GameDesignPublicationOperationBinding(account, world); return new GameDesignPublicationTerminalEvidence( operation.canonicalBytes(), @@ -1633,6 +1630,37 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( release.versionStateEpoch()); } + private AccountPublicationAuthorizationBinding isolatedPublicationAccountBinding( + byte[] originalDraftAccountBinding, + AuthoredDraftPublishSelectionBinding selection, + String publicationRequestId) { + var originalAccount = DraftAuthorizationFenceBinding.fromStored(originalDraftAccountBinding); + String stableIdentity = + selection.target().canonicalTenantId() + + ":" + + selection.target().canonicalVersionId() + + ":" + + publicationRequestId; + // Fixture-only distinct Account order retained atomically with the first freeze; not producer + // proof. + return new AccountPublicationAuthorizationBinding( + UUID.nameUUIDFromBytes( + (stableIdentity + "/account-operation").getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + (stableIdentity + "/account-fence").getBytes(StandardCharsets.UTF_8)), + new AccountPublicationAuthorizationBinding.PreallocationInput( + originalAccount.actorAccountId(), selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + originalAccount.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + private ReleaseContent isolatedReleaseContent(WorldCanonicalInstancePreparation.Input input) { var release = input.completeLaunchBinding().evidence().releaseAttestation(); var world = Objects.requireNonNull(release.worldStartLocationEvidence()); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 8c01a5006d..79f7513053 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -5,6 +5,7 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.UnknownFieldSet; import com.google.protobuf.util.JsonFormat; import io.grpc.Context; import io.grpc.ManagedChannel; @@ -67,6 +68,9 @@ import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadGrpcCodec; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; @@ -105,6 +109,7 @@ import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; import net.firedevops.firemud.worldmanagement.v1.GenerationRuleDesignMutation; import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalRequest; import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomExitDesignMutation; @@ -115,6 +120,7 @@ import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -217,7 +223,8 @@ void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRunt .getLast(); var application = withStartRoom(original, lastRoom); appliedComponent().apply(application); - var frozen = capture(application.plan()); + var frozen = + captureForTerminal(application.plan(), application.operation().accountBindingBytes()); var selector = publishedEvidence( publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); @@ -242,11 +249,15 @@ void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRunt // This isolated fixture writes and reads back an actual retained World PUBLISHED terminal. var originalTerminal = isolatedTerminalEvidence(seedInput); byte[] originalTerminalBytes = originalTerminal.canonicalBytes(); + publicationTerminalComponent(originalTerminal) + .complete(originalTerminal.operationBytes(), originalTerminalBytes); publicationTerminalComponent(originalTerminal) .complete(originalTerminal.operationBytes(), originalTerminalBytes); UUID publicationFence = selector.request().publicationFence(); assertThat(publicationOwnerPhase(publicationFence)).isEqualTo("PUBLISHED"); assertThat(publicationTerminalBytes(publicationFence)).containsExactly(originalTerminalBytes); + assertThat(publicationTerminalCount(publicationFence)).isEqualTo(1L); + assertThat(publicationAccountQualificationCount(publicationFence)).isEqualTo(1L); UUID canonicalGameInstanceId = UUID.randomUUID(); var stableSelector = @@ -356,7 +367,8 @@ void authenticatedPreparationAdapterBindsFreshLaunchAndReadsActualPreparingLifec .getLast(); var application = withStartRoom(original, selectedRoom); appliedComponent().apply(application); - var frozen = capture(application.plan()); + var frozen = + captureForTerminal(application.plan(), application.operation().accountBindingBytes()); var selector = publishedEvidence( publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); @@ -632,7 +644,7 @@ void canonicalPreparationKeepsOriginalPublicationEpochForLaterReleaseResolution( .getLast(); var applied = withStartRoom(original, selectedRoom); appliedComponent().apply(applied); - var frozen = capture(applied.plan()); + var frozen = captureForTerminal(applied.plan(), applied.operation().accountBindingBytes()); var selector = publishedEvidence( publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); @@ -690,6 +702,399 @@ void canonicalPreparationKeepsOriginalPublicationEpochForLaterReleaseResolution( assertOrigin(); } + @Test + void terminalRequiresTheExactV53AccountOrderForFirstCompletionAndExactRetry() { + Fixture f = fixture(); + var graphApplication = application(f); + appliedComponent().apply(graphApplication); + var frozen = + captureForTerminal( + graphApplication.plan(), graphApplication.operation().accountBindingBytes()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var original = isolatedTerminalEvidence(input); + var request = WorldPublicationTerminal.Request.fromStored(original.canonicalBytes()); + UUID fence = selector.request().publicationFence(); + var ownerBefore = ownerSnapshot(f, graphApplication.plan()); + var account = + GameDesignPublicationOperationBinding.fromStored(original.operationBytes()).account(); + + var changedOperation = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), account.fenceId(), account.input(), account.sources()); + var changedFence = + new AccountPublicationAuthorizationBinding( + account.operationId(), UUID.randomUUID(), account.input(), account.sources()); + var source = account.sources().getFirst(); + var changedBytes = + new AccountPublicationAuthorizationBinding( + account.operationId(), + account.fenceId(), + account.input(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + new byte[] {2}))); + + for (AccountPublicationAuthorizationBinding changed : + List.of(changedOperation, changedFence, changedBytes)) { + var altered = isolatedTerminalEvidence(original, changed); + assertThatThrownBy( + () -> + publicationTerminalComponent(altered) + .complete(altered.operationBytes(), altered.canonicalBytes())) + .isInstanceOf( + WorldPublicationTerminalRepository.PublicationTerminalConflictException.class) + .hasMessageContaining("original Account publication qualification"); + assertThat(ownerSnapshot(f, graphApplication.plan())).isEqualTo(ownerBefore); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat(publicationTerminalCount(fence)).isZero(); + assertThat(publicationAccountQualificationCount(fence)).isEqualTo(1L); + } + + var first = + publicationTerminalComponent(original) + .complete(request.operationBytes(), request.terminalBytes()); + var retry = + publicationTerminalComponent(original) + .complete(request.operationBytes(), request.terminalBytes()); + assertThat(retry.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); + assertThat(publicationTerminalCount(fence)).isEqualTo(1L); + assertThat(publicationAccountQualificationCount(fence)).isEqualTo(1L); + + var committedRead = + new WorldPublicationTerminalRepository(dsl, manager).readCommitted(request).orElseThrow(); + assertThat(committedRead.canonicalBytes()).containsExactly(first.canonicalBytes()); + for (AccountPublicationAuthorizationBinding changed : + List.of(changedOperation, changedFence, changedBytes)) { + var altered = isolatedTerminalEvidence(original, changed); + var alteredRequest = WorldPublicationTerminal.Request.fromStored(altered.canonicalBytes()); + assertThatThrownBy( + () -> + publicationTerminalComponent(altered) + .complete(altered.operationBytes(), altered.canonicalBytes())) + .isInstanceOf( + WorldPublicationTerminalRepository.PublicationTerminalConflictException.class) + .hasMessageContaining("original Account publication qualification"); + assertThatThrownBy( + () -> + new WorldPublicationTerminalRepository(dsl, manager) + .readCommitted(alteredRequest)) + .isInstanceOf( + WorldPublicationTerminalRepository.PublicationTerminalConflictException.class) + .hasMessageContaining("original Account publication qualification"); + assertThat(ownerSnapshot(f, graphApplication.plan())).isEqualTo(ownerBefore); + assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); + assertThat(publicationTerminalCount(fence)).isEqualTo(1L); + assertThat(publicationTerminalBytes(fence)).containsExactly(first.canonicalBytes()); + assertThat(publicationAccountQualificationCount(fence)).isEqualTo(1L); + } + } + + @Test + void worldTerminalReadUsesIndependentQualifiedOwnerAndRequiredMtls() throws Exception { + var pki = WorldTerminalReadTestPki.create(temporaryDirectory.resolve("terminal-read-pki")); + for (Outcome outcome : List.of(Outcome.PUBLISHED, Outcome.NO_PUBLICATION)) { + Fixture f = fixture(); + var graphApplication = application(f); + appliedComponent().apply(graphApplication); + var frozen = + captureForTerminal( + graphApplication.plan(), graphApplication.operation().accountBindingBytes()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var published = isolatedTerminalEvidence(input); + var terminal = + outcome == Outcome.PUBLISHED + ? published + : new GameDesignPublicationTerminalEvidence( + published.operationBytes(), Outcome.NO_PUBLICATION, null, null); + var request = + WorldPublicationTerminalReadEvidence.Request.create( + NAMESPACE, terminal.operationBytes(), terminal.canonicalBytes()); + UUID fence = selector.request().publicationFence(); + var terminalRepository = Mockito.spy(new WorldPublicationTerminalRepository(dsl, manager)); + var ownerRead = new WorldPublicationTerminalReadService(terminalRepository, NAMESPACE); + var adapter = new WorldPublicationTerminalReadGrpcService(ownerRead, NAMESPACE); + Server server = startWorldPublicationTerminalReadTransport(adapter, pki); + try (WorldPublicationTerminalReadClient client = + worldPublicationTerminalReadClient( + server, pki.accountClient.clientProperties(pki.caCertificate))) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + + // A valid exact lookup remains unavailable while the real retained terminal is pending. + assertStatus(Status.Code.FAILED_PRECONDITION, () -> client.read(request)); + Mockito.verify(terminalRepository).readCommitted(Mockito.any()); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat(publicationTerminalCount(fence)).isZero(); + assertThat(publicationAccountQualificationCount(fence)).isEqualTo(1L); + + // The owner transition and terminal are committed before any RPC is issued. + var committed = + publicationTerminalComponent(terminal) + .complete(terminal.operationBytes(), terminal.canonicalBytes()); + assertThat(committed.canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var ownerStateAfterCommit = publicationOwnerState(fence); + assertThat(publicationOwnerPhase(fence)) + .isEqualTo(outcome == Outcome.PUBLISHED ? "PUBLISHED" : "ABORTED"); + assertThat(publicationTerminalBytes(fence)).containsExactly(terminal.canonicalBytes()); + assertThat(publicationTerminalCount(fence)).isEqualTo(1L); + assertThat(publicationAccountQualificationCount(fence)).isEqualTo(1L); + + // Same correlation is an idempotent read; a fresh UUID is transport-only correlation. + var firstRead = client.read(request); + var exactRetry = client.read(request); + var freshRequest = + WorldPublicationTerminalReadEvidence.Request.create( + NAMESPACE, terminal.operationBytes(), terminal.canonicalBytes()); + var freshRetry = client.read(freshRequest); + assertThat(firstRead.request()).isEqualTo(request); + assertThat(exactRetry.request()).isEqualTo(request); + assertThat(freshRetry.request().readRequestId()).isNotEqualTo(request.readRequestId()); + for (var evidence : List.of(firstRead, exactRetry, freshRetry)) { + assertThat(evidence.worldOutcome()) + .isEqualTo( + outcome == Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED + : WorldPublicationTerminalReadEvidence.WorldOutcome.ABORTED); + assertThat(evidence.worldTerminalEvidence()).containsExactly(terminal.canonicalBytes()); + } + assertThat(publicationOwnerState(fence)).isEqualTo(ownerStateAfterCommit); + assertThat(publicationTerminalBytes(fence)).containsExactly(terminal.canonicalBytes()); + assertThat(publicationTerminalCount(fence)).isEqualTo(1L); + assertThat(publicationAccountQualificationCount(fence)).isEqualTo(1L); + + // A trusted Account peer cannot smuggle malformed or unknown wire fields into owner reads. + var wireRequest = WorldPublicationTerminalReadGrpcCodec.toRequest(request); + var malformedWireRequest = wireRequest.toBuilder().setReadRequestId("not-a-uuid").build(); + var unknownFieldWireRequest = + wireRequest.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(127, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var otherNamespaceWireRequest = + wireRequest.toBuilder().setTargetNamespace("other-namespace").build(); + ManagedChannel channel = + publicationTerminalReadChannel( + server, pki.accountClient.clientProperties(pki.caCertificate)); + try { + var rawStub = publicationTerminalReadStub(channel); + for (ReadPublicationTerminalRequest malformed : + List.of(malformedWireRequest, unknownFieldWireRequest)) { + Mockito.clearInvocations(terminalRepository); + assertStatus( + Status.Code.INVALID_ARGUMENT, () -> rawStub.readPublicationTerminal(malformed)); + Mockito.verify(terminalRepository, Mockito.never()).readCommitted(Mockito.any()); + } + Mockito.clearInvocations(terminalRepository); + assertStatus( + Status.Code.INVALID_ARGUMENT, + () -> rawStub.readPublicationTerminal(otherNamespaceWireRequest)); + Mockito.verify(terminalRepository, Mockito.never()).readCommitted(Mockito.any()); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + + // The server authenticates the exact same-namespace Account SPIFFE identity first. + for (var identity : List.of(pki.wrongWorkloadClient, pki.crossNamespaceAccountClient)) { + try (WorldPublicationTerminalReadClient untrustedClient = + worldPublicationTerminalReadClient( + server, identity.clientProperties(pki.caCertificate))) { + Mockito.clearInvocations(terminalRepository); + assertStatus(Status.Code.PERMISSION_DENIED, () -> untrustedClient.read(request)); + Mockito.verify(terminalRepository, Mockito.never()).readCommitted(Mockito.any()); + } + } + assertThat(publicationOwnerState(fence)).isEqualTo(ownerStateAfterCommit); + assertThat(publicationTerminalBytes(fence)).containsExactly(terminal.canonicalBytes()); + assertThat(publicationTerminalCount(fence)).isEqualTo(1L); + assertThat(publicationAccountQualificationCount(fence)).isEqualTo(1L); + + // Canonical but changed immutable Account identity is denied against the retained order. + var originalOperation = + GameDesignPublicationOperationBinding.fromStored(terminal.operationBytes()); + var originalAccount = originalOperation.account(); + var source = originalAccount.sources().getFirst(); + var changedAccounts = + List.of( + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + originalAccount.fenceId(), + originalAccount.input(), + originalAccount.sources()), + new AccountPublicationAuthorizationBinding( + originalAccount.operationId(), + UUID.randomUUID(), + originalAccount.input(), + originalAccount.sources()), + new AccountPublicationAuthorizationBinding( + originalAccount.operationId(), + originalAccount.fenceId(), + originalAccount.input(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + new byte[] {2})))); + for (AccountPublicationAuthorizationBinding changedAccount : changedAccounts) { + var changedOperation = + new GameDesignPublicationOperationBinding(changedAccount, originalOperation.world()); + var changedTerminal = + outcome == Outcome.PUBLISHED + ? new GameDesignPublicationTerminalEvidence( + changedOperation.canonicalBytes(), + Outcome.PUBLISHED, + terminal.releaseContent(), + terminal.publicationVersionStateEpoch()) + : new GameDesignPublicationTerminalEvidence( + changedOperation.canonicalBytes(), Outcome.NO_PUBLICATION, null, null); + var changedRequest = + WorldPublicationTerminalReadEvidence.Request.create( + NAMESPACE, changedOperation.canonicalBytes(), changedTerminal.canonicalBytes()); + assertStatus(Status.Code.FAILED_PRECONDITION, () -> client.read(changedRequest)); + assertThat(publicationOwnerState(fence)).isEqualTo(ownerStateAfterCommit); + assertThat(publicationTerminalBytes(fence)).containsExactly(terminal.canonicalBytes()); + assertThat(publicationTerminalCount(fence)).isEqualTo(1L); + assertThat(publicationAccountQualificationCount(fence)).isEqualTo(1L); + } + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + } + + @Test + void terminalRejectsUnqualifiedHistoricalFreezeWithoutInventingAccountOrder() { + Fixture f = fixture(); + var graphApplication = application(f); + appliedComponent().apply(graphApplication); + var frozen = capture(graphApplication.plan()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var original = isolatedTerminalEvidence(input); + var request = WorldPublicationTerminal.Request.fromStored(original.canonicalBytes()); + UUID fence = selector.request().publicationFence(); + var ownerBefore = ownerSnapshot(f, graphApplication.plan()); + + assertThat(publicationAccountQualificationCount(fence)).isZero(); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + insertPublicationTerminal(request); + return null; + })) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + publicationTerminalComponent(original) + .complete(request.operationBytes(), request.terminalBytes())) + .isInstanceOf( + WorldPublicationTerminalRepository.PublicationTerminalConflictException.class); + assertThat(ownerSnapshot(f, graphApplication.plan())).isEqualTo(ownerBefore); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat(publicationTerminalCount(fence)).isZero(); + assertThat(publicationAccountQualificationCount(fence)).isZero(); + } + + @Test + void terminalSqlRejectsMalformedOversizedAndTrailingOperationFrames() { + Fixture f = fixture(); + var graphApplication = application(f); + appliedComponent().apply(graphApplication); + var frozen = + captureForTerminal( + graphApplication.plan(), graphApplication.operation().accountBindingBytes()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + var request = + WorldPublicationTerminal.Request.fromStored( + isolatedTerminalEvidence(input).canonicalBytes()); + UUID fence = selector.request().publicationFence(); + var ownerBefore = ownerSnapshot(f, graphApplication.plan()); + byte[] original = request.operationBytes(); + byte[] wrongSchema = original.clone(); + wrongSchema[4] ^= 1; + byte[] negativeLength = original.clone(); + Arrays.fill(negativeLength, 0, 4, (byte) 0xff); + byte[] oversizedLength = original.clone(); + oversizedLength[0] = 0x7f; + Arrays.fill(oversizedLength, 1, 4, (byte) 0xff); + byte[] truncatedHeader = new byte[] {0, 1}; + byte[] truncatedPayload = Arrays.copyOf(original, original.length - 1); + byte[] trailingByte = Arrays.copyOf(original, original.length + 1); + byte[] oversizedOperation = Arrays.copyOf(original, 4_194_305); + + for (byte[] malformed : + List.of( + wrongSchema, + negativeLength, + oversizedLength, + truncatedHeader, + truncatedPayload, + trailingByte, + oversizedOperation)) { + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + insertPublicationTerminal(request, malformed); + return null; + })) + .satisfies(failure -> assertPublicationGuardSqlState(failure, "23514")); + assertThat(ownerSnapshot(f, graphApplication.plan())).isEqualTo(ownerBefore); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat(publicationTerminalCount(fence)).isZero(); + assertThat(publicationAccountQualificationCount(fence)).isEqualTo(1L); + } + } + + private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( + GameDesignPublicationTerminalEvidence original, + AccountPublicationAuthorizationBinding account) { + var operation = new GameDesignPublicationOperationBinding(account, original.worldEvidence()); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + original.outcome(), + original.releaseContent(), + original.publicationVersionStateEpoch()); + } + + private static void assertPublicationGuardSqlState(Throwable failure, String expectedState) { + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current instanceof java.sql.SQLException sqlFailure) { + assertThat(sqlFailure.getSQLState()).isEqualTo(expectedState); + return; + } + } + throw new AssertionError("Expected PostgreSQL publication-operation guard failure", failure); + } + @Test void rawTerminalReceiptCannotCommitWithoutMatchingOwnerPhaseCas() { Fixture f = fixture(); @@ -705,7 +1110,7 @@ void rawTerminalReceiptCannotCommitWithoutMatchingOwnerPhaseCas() { .getLast(); var applied = withStartRoom(original, selectedRoom); appliedComponent().apply(applied); - var frozen = capture(applied.plan()); + var frozen = captureForTerminal(applied.plan(), applied.operation().accountBindingBytes()); var selector = publishedEvidence( publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); @@ -746,6 +1151,121 @@ private String publicationOwnerPhase(UUID fence) { .get("owner_freeze_phase", String.class); } + private List ownerSnapshot(Fixture fixture, WorldDraftTopologyCommitPlan plan) { + long tenant = fixture.intake().localTenantKey(); + long version = fixture.version().localVersionKey(); + List snapshot = new ArrayList<>(); + for (String table : + List.of( + "region", + "zone", + "room", + "room_exit", + "generation_rule", + "world_entity_spawn_binding")) { + rowJson( + "SELECT to_jsonb(t)::text FROM " + + table + + " t WHERE tenant_id=? AND version_id=? ORDER BY id", + tenant, + version) + .forEach(row -> snapshot.add(table + ":" + row)); + } + rowJson( + "SELECT to_jsonb(t)::text FROM world_authored_topology_identity t " + + "WHERE target_namespace=? AND canonical_tenant_id=? AND canonical_version_id=? " + + "ORDER BY family,private_row_key", + fixture.owner().targetNamespace(), + fixture.owner().canonicalTenantId(), + fixture.owner().canonicalVersionId()) + .forEach(row -> snapshot.add("topology-identity:" + row)); + rowJson( + "SELECT to_jsonb(t)::text FROM world_design_aggregate_epoch t " + + "WHERE tenant_id=? AND version_id=? ORDER BY aggregate_type,aggregate_id", + tenant, + version) + .forEach(row -> snapshot.add("aggregate-epoch:" + row)); + rowJson( + "SELECT to_jsonb(t)::text FROM world_design_scope_epoch t " + + "WHERE tenant_id=? AND version_id=? ORDER BY scope_type,scope_id", + tenant, + version) + .forEach(row -> snapshot.add("scope-epoch:" + row)); + rowJson( + "SELECT to_jsonb(t)::text FROM world_design_revision_ledger t " + + "WHERE tenant_id=? AND version_id=? ORDER BY id", + tenant, + version) + .forEach(row -> snapshot.add("revision:" + row)); + rowJson( + "SELECT to_jsonb(t)::text FROM world_topology_draft_commit t " + + "WHERE request_id=? OR commit_id=? ORDER BY request_id", + plan.binding().requestId(), + plan.binding().commitId()) + .forEach(row -> snapshot.add("draft-commit:" + row)); + rowJson( + "SELECT to_jsonb(t)::text FROM world_draft_start_location_receipt t " + + "WHERE request_id=? OR commit_id=? ORDER BY request_id", + plan.binding().requestId(), + plan.binding().commitId()) + .forEach(row -> snapshot.add("start-location-receipt:" + row)); + rowJson( + "SELECT to_jsonb(t)::text FROM world_draft_graph_application t " + + "WHERE request_id=? OR commit_id=? ORDER BY request_id", + plan.binding().requestId(), + plan.binding().commitId()) + .forEach(row -> snapshot.add("graph-application:" + row)); + rowJson( + "SELECT to_jsonb(t)::text FROM world_draft_graph_terminal_identity t " + + "WHERE request_id=? OR commit_id=? ORDER BY request_id", + plan.binding().requestId(), + plan.binding().commitId()) + .forEach(row -> snapshot.add("graph-terminal-identity:" + row)); + rowJson( + "SELECT to_jsonb(t)::text FROM world_design_publication_fence_owner t " + + "WHERE target_namespace=? AND canonical_tenant_id=? AND version_id=? " + + "ORDER BY target_namespace,canonical_tenant_id,version_id", + fixture.owner().targetNamespace(), + fixture.owner().canonicalTenantId(), + version) + .forEach(row -> snapshot.add("publication-owner:" + row)); + rowJson( + "SELECT to_jsonb(t)::text FROM world_design_publication_fence_attempt t " + + "WHERE target_namespace=? AND canonical_tenant_id=? AND version_id=? " + + "ORDER BY publication_fence", + fixture.owner().targetNamespace(), + fixture.owner().canonicalTenantId(), + version) + .forEach(row -> snapshot.add("publication-attempt:" + row)); + rowJson( + "SELECT to_jsonb(b)::text FROM world_design_publication_account_binding b " + + "JOIN world_design_publication_fence_attempt a USING (publication_fence) " + + "WHERE a.target_namespace=? AND a.canonical_tenant_id=? AND a.version_id=? " + + "ORDER BY b.publication_fence", + fixture.owner().targetNamespace(), + fixture.owner().canonicalTenantId(), + version) + .forEach(row -> snapshot.add("publication-account-binding:" + row)); + return List.copyOf(snapshot); + } + + private List rowJson(String sql, Object... bindings) { + return dsl.resultQuery(sql, bindings).fetch(0, String.class); + } + + private Map publicationOwnerState(UUID fence) { + Record owner = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT owner_freeze_phase,current_publication_fence " + + "FROM world_design_publication_fence_owner " + + "WHERE current_publication_fence=?", + fence)); + return Map.of( + "phase", owner.get("owner_freeze_phase", String.class), + "fence", owner.get("current_publication_fence", UUID.class)); + } + private byte[] publicationTerminalBytes(UUID fence) { return Objects.requireNonNull( dsl.fetchOne( @@ -755,7 +1275,28 @@ private byte[] publicationTerminalBytes(UUID fence) { .get("terminal_evidence_bytes", byte[].class); } + private long publicationTerminalCount(UUID fence) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_terminal WHERE publication_fence=?", + fence)) + .get(0, Long.class); + } + + private long publicationAccountQualificationCount(UUID fence) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_design_publication_account_binding WHERE publication_fence=?", + fence)) + .get(0, Long.class); + } + private void insertPublicationTerminal(WorldPublicationTerminal.Request request) { + insertPublicationTerminal(request, request.operationBytes()); + } + + private void insertPublicationTerminal( + WorldPublicationTerminal.Request request, byte[] operationBytes) { var world = request.worldEvidence().request(); dsl.execute( "INSERT INTO world_design_publication_terminal (publication_fence,target_namespace," @@ -781,7 +1322,7 @@ private void insertPublicationTerminal(WorldPublicationTerminal.Request request) request.publicationVersionStateEpoch(), request.releaseBundleRef(), request.releaseBundleDigest(), - request.operationBytes(), + operationBytes, request.terminalBytes(), sha256Digest(request.terminalBytes()).substring("sha256:".length()), request.worldEvidenceBytes(), @@ -3724,6 +4265,55 @@ private static Server startActivationTransport( .start(); } + private static Server startWorldPublicationTerminalReadTransport( + WorldPublicationTerminalReadGrpcService adapter, WorldTerminalReadTestPki pki) + throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.worldServer.certificate.toFile(), pki.worldServer.privateKey.toFile())) + .trustManager(pki.caCertificate.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(adapter, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static WorldPublicationTerminalReadClient worldPublicationTerminalReadClient( + Server server, CommonGrpcClientProperties tlsProperties) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + server.getPort()); + var client = + new WorldPublicationTerminalReadClient( + endpoints, tlsProperties, new GrpcChannelFactory(), NAMESPACE); + client.init(); + return client; + } + + private static ManagedChannel publicationTerminalReadChannel( + Server server, CommonGrpcClientProperties tlsProperties) throws Exception { + return new GrpcChannelFactory() + .buildChannel("127.0.0.1:" + server.getPort(), server.getPort(), tlsProperties, false); + } + + private static WorldPublicationTerminalReadServiceGrpc + .WorldPublicationTerminalReadServiceBlockingStub + publicationTerminalReadStub(ManagedChannel channel) { + return WorldPublicationTerminalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(WORLD_SERVER_WORKLOAD_URI)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(WORLD_SERVER_WORKLOAD_URI)); + } + + private static void assertStatus( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + private static ActivateCanonicalWorldInstanceRequest activationTransportRequest( WorldCanonicalInstanceActivation.Request request) { return ActivateCanonicalWorldInstanceRequest.newBuilder() @@ -3873,8 +4463,6 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( WorldCanonicalInstanceTopologyPlan topologyPlan) { var release = launchEvidence.releaseAttestation(); var world = Objects.requireNonNull(release.worldStartLocationEvidence()); - var originalAccount = - DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()); var selection = publicationSelection( topologyPlan.sourceBinding().plan(), @@ -3885,24 +4473,8 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( "Isolated publication selection differs from the retained World request digest"); } var account = - new AccountPublicationAuthorizationBinding( - UUID.nameUUIDFromBytes( - (world.request().publicationFence() + "/account-operation") - .getBytes(StandardCharsets.UTF_8)), - UUID.nameUUIDFromBytes( - (world.request().publicationFence() + "/account-fence") - .getBytes(StandardCharsets.UTF_8)), - new AccountPublicationAuthorizationBinding.PreallocationInput( - originalAccount.actorAccountId(), selection), - List.of( - new DraftAuthorizationFenceBinding.SourceEvidence( - DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, - originalAccount.actorAccountId().toString(), - "1", - "1", - null, - null, - new byte[] {1}))); + isolatedPublicationAccountBinding( + world.originalAccountBindingBytes(), selection, world.request().publicationRequestId()); var operation = new GameDesignPublicationOperationBinding(account, world); return new GameDesignPublicationTerminalEvidence( operation.canonicalBytes(), @@ -4005,6 +4577,36 @@ private AuthoredDraftPublishSelectionBinding publicationSelection( OffsetDateTime.parse("2026-01-01T00:00:00Z"))); } + private AccountPublicationAuthorizationBinding isolatedPublicationAccountBinding( + byte[] originalDraftAccountBinding, + AuthoredDraftPublishSelectionBinding selection, + String publicationRequestId) { + var originalAccount = DraftAuthorizationFenceBinding.fromStored(originalDraftAccountBinding); + String stableIdentity = + selection.target().canonicalTenantId() + + ":" + + selection.target().canonicalVersionId() + + ":" + + publicationRequestId; + // Fixture-only distinct Account order, retained before the first freeze; not producer proof. + return new AccountPublicationAuthorizationBinding( + UUID.nameUUIDFromBytes( + (stableIdentity + "/account-operation").getBytes(StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + (stableIdentity + "/account-fence").getBytes(StandardCharsets.UTF_8)), + new AccountPublicationAuthorizationBinding.PreallocationInput( + originalAccount.actorAccountId(), selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + originalAccount.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + /** Reuses genuine graph/release/materialization/activation; upstream authority is stipulated. */ ActivePlayerAdmissionFixture activePlayerAdmissionFixture() { var prepared = materializedLifecycleFixture(); @@ -5009,9 +5611,27 @@ private WorldPublishedStartLocationRepository publishedSelectors() { } private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) { - var owner = plan.ownerBinding(); String publicationRequest = "selector-" + UUID.randomUUID(); var selection = publicationSelection(plan, publicationRequest, 1L); + return capture(plan, publicationRequest, selection, null); + } + + private WorldCanonicalFrozenTopology captureForTerminal( + WorldDraftTopologyCommitPlan plan, byte[] originalDraftAccountBinding) { + String publicationRequest = "selector-" + UUID.randomUUID(); + var selection = publicationSelection(plan, publicationRequest, 1L); + var accountBinding = + isolatedPublicationAccountBinding( + originalDraftAccountBinding, selection, publicationRequest); + return capture(plan, publicationRequest, selection, accountBinding); + } + + private WorldCanonicalFrozenTopology capture( + WorldDraftTopologyCommitPlan plan, + String publicationRequest, + AuthoredDraftPublishSelectionBinding selection, + AccountPublicationAuthorizationBinding accountBinding) { + var owner = plan.ownerBinding(); var evidence = new WorldDesignPublicationFenceEvidence( owner.targetNamespace(), @@ -5029,26 +5649,38 @@ private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) selection.digest().substring("sha256:".length()), 1, "publish:" + owner.canonicalTenantId() + ":publish-request:" + publicationRequest); + var attemptCreatedInTransaction = new AtomicBoolean(); var attempt = Objects.requireNonNull( ownerTransaction() .execute( - status -> - fence.claimFreeze( - evidence, - () -> { - var identity = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT local_tenant_key,local_version_key FROM world_authored_version_identity WHERE operation_id=?", - owner.versionIdentityOperationId())); - var digest = - digestService.getDraftDesignDigest( - identity.get("local_tenant_key", Long.class).toString(), - identity.get("local_version_key", Long.class).toString()); - return new WorldDesignPublicationFenceEvidence.Checkpoint( - plan.binding().commitId().toString(), digest.contentDigest(), 3); - }))); + status -> { + var frozenAttempt = + fence.claimFreeze( + evidence, + () -> { + var identity = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT local_tenant_key,local_version_key FROM world_authored_version_identity WHERE operation_id=?", + owner.versionIdentityOperationId())); + var digest = + digestService.getDraftDesignDigest( + identity.get("local_tenant_key", Long.class).toString(), + identity.get("local_version_key", Long.class).toString()); + attemptCreatedInTransaction.set(true); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + plan.binding().commitId().toString(), + digest.contentDigest(), + 3); + }); + if (accountBinding != null) { + new WorldSelectedDraftPublicationAuthorizationRepository(dsl) + .retainOrRequireExact( + frozenAttempt, accountBinding, attemptCreatedInTransaction.get()); + } + return frozenAttempt; + })); var tuples = plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() .map( @@ -6782,4 +7414,176 @@ private record PreparedLifecycleFixture( WorldCanonicalInstanceLifecycleReadRepository lifecycleRepository, WorldCanonicalInstanceLifecycleEvidence.Request readRequest, WorldCanonicalInstanceLifecycleEvidence preparing) {} + + /** Ephemeral identities for the physical World terminal-read mTLS boundary only. */ + private static final class WorldTerminalReadTestPki { + private final Path caCertificate; + private final WorldTerminalReadTestIdentity worldServer; + private final WorldTerminalReadTestIdentity accountClient; + private final WorldTerminalReadTestIdentity wrongWorkloadClient; + private final WorldTerminalReadTestIdentity crossNamespaceAccountClient; + + private WorldTerminalReadTestPki( + Path caCertificate, + WorldTerminalReadTestIdentity worldServer, + WorldTerminalReadTestIdentity accountClient, + WorldTerminalReadTestIdentity wrongWorkloadClient, + WorldTerminalReadTestIdentity crossNamespaceAccountClient) { + this.caCertificate = caCertificate; + this.worldServer = worldServer; + this.accountClient = accountClient; + this.wrongWorkloadClient = wrongWorkloadClient; + this.crossNamespaceAccountClient = crossNamespaceAccountClient; + } + + private static WorldTerminalReadTestPki create(Path directory) throws Exception { + java.nio.file.Files.createDirectories(directory); + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var caKeys = generator.generateKeyPair(); + var caName = new org.bouncycastle.asn1.x500.X500Name("CN=World terminal read test CA"); + var now = java.time.Instant.now(); + var caBuilder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caName, + java.math.BigInteger.ONE, + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(14L * 24L * 60L * 60L)), + caName, + caKeys.getPublic()); + caBuilder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(true)); + caBuilder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage( + org.bouncycastle.asn1.x509.KeyUsage.keyCertSign + | org.bouncycastle.asn1.x509.KeyUsage.cRLSign)); + var caCertificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + caBuilder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + Path caPath = pem(directory.resolve("test-ca.pem"), caCertificate); + return new WorldTerminalReadTestPki( + caPath, + issue( + directory, + "world-server", + NAMESPACE, + "world-management-service", + true, + caKeys, + caCertificate), + issue( + directory, + "account-client", + NAMESPACE, + "account-service", + false, + caKeys, + caCertificate), + issue( + directory, + "wrong-workload-client", + NAMESPACE, + "game-design-service", + false, + caKeys, + caCertificate), + issue( + directory, + "cross-namespace-account-client", + "other", + "account-service", + false, + caKeys, + caCertificate)); + } + + private static WorldTerminalReadTestIdentity issue( + Path directory, + String alias, + String namespace, + String service, + boolean server, + java.security.KeyPair caKeys, + java.security.cert.X509Certificate caCertificate) + throws Exception { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var keys = generator.generateKeyPair(); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caCertificate, + new java.math.BigInteger(120, new java.security.SecureRandom()), + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(14L * 24L * 60L * 60L)), + new org.bouncycastle.asn1.x500.X500Name("CN=" + alias), + keys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(false)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage( + org.bouncycastle.asn1.x509.KeyUsage.digitalSignature + | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.extendedKeyUsage, + false, + new org.bouncycastle.asn1.x509.ExtendedKeyUsage( + server + ? org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_serverAuth + : org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_clientAuth)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, + false, + new org.bouncycastle.asn1.x509.GeneralNames( + new org.bouncycastle.asn1.x509.GeneralName[] { + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.uniformResourceIdentifier, + "spiffe://firemud/ns/" + namespace + "/sa/" + service), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.dNSName, "localhost"), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.iPAddress, "127.0.0.1") + })); + var certificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + builder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + return new WorldTerminalReadTestIdentity( + pem(directory.resolve(alias + ".crt"), certificate), + pem(directory.resolve(alias + ".key"), keys.getPrivate())); + } + + private static Path pem(Path path, Object value) throws Exception { + try (var writer = + new org.bouncycastle.openssl.jcajce.JcaPEMWriter( + java.nio.file.Files.newBufferedWriter(path))) { + writer.writeObject(value); + } + return path; + } + } + + private record WorldTerminalReadTestIdentity(Path certificate, Path privateKey) { + private CommonGrpcClientProperties clientProperties(Path caCertificate) { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caCertificate.toString()); + return properties; + } + } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java index cb93a4a59b..475aea9776 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftRegionCommitPostgresIntegrationTest.java @@ -534,6 +534,10 @@ void v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory() throw scope.getKey().equals("world_authored_version_identity") ? " OVERRIDING SYSTEM VALUE" : ""; + String historicalColumns = + scope.getKey().equals("world_design_publication_fence_attempt") + ? retainedColumns(retained, schema, scope.getKey()) + : null; String columns = scope.getKey().equals("world_entity_spawn_binding") ? "id,tenant_id,version_id,room_id,entity_template_type,entity_template_id,spawn_count,respawn_delay_seconds,version" @@ -541,10 +545,14 @@ void v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory() throw retained.execute( "INSERT INTO " + scope.getKey() - + (columns == null ? "" : " (" + columns + ")") + + (historicalColumns != null + ? " (" + historicalColumns + ")" + : columns == null ? "" : " (" + columns + ")") + override + " SELECT " - + (columns == null ? "*" : columns) + + (historicalColumns != null + ? historicalColumns + : columns == null ? "*" : columns) + " FROM world_management_service." + scope.getKey() + " WHERE " @@ -595,6 +603,8 @@ void v29UpgradePreservesRetainedV28FrozenSourceGraphFenceAndEpochHistory() throw .load() .migrate(); assertThat(retainedRows(retained, scopes.keySet().stream().toList(), true)).isEqualTo(before); + assertHistoricalAttemptBirthStampsAreNull( + retained, before.get("world_design_publication_fence_attempt").size()); assertThat( retained .resultQuery( @@ -653,9 +663,11 @@ private Map> retainedRows( Map> rows = new LinkedHashMap<>(); for (String table : tables) { String expression = - retainedSpawnColumnsOnly && table.equals("world_entity_spawn_binding") - ? "to_jsonb(t) - 'entity_canonical_tenant_id' - 'entity_canonical_version_id' - 'entity_canonical_template_id'" - : "to_jsonb(t)"; + table.equals("world_design_publication_fence_attempt") + ? "to_jsonb(t) - 'attempt_created_full_xid'" + : retainedSpawnColumnsOnly && table.equals("world_entity_spawn_binding") + ? "to_jsonb(t) - 'entity_canonical_tenant_id' - 'entity_canonical_version_id' - 'entity_canonical_template_id'" + : "to_jsonb(t)"; rows.put( table, retained @@ -672,6 +684,36 @@ private Map> retainedRows( return rows; } + private String retainedColumns(DSLContext retained, String schema, String table) { + return Objects.requireNonNull( + retained + .resultQuery( + "SELECT string_agg(quote_ident(column_name), ', ' ORDER BY ordinal_position) " + + "FROM information_schema.columns WHERE table_schema = ? AND table_name = ?", + schema, + table) + .fetchOne(0, String.class), + "historical fixture must expose its original columns"); + } + + private void assertHistoricalAttemptBirthStampsAreNull( + DSLContext retained, int expectedRetainedRows) { + assertThat( + retained + .resultQuery( + "SELECT count(*) FROM world_design_publication_fence_attempt " + + "WHERE attempt_created_full_xid IS NULL") + .fetchOne(0, Long.class)) + .isEqualTo((long) expectedRetainedRows); + assertThat( + retained + .resultQuery( + "SELECT count(*) FROM world_design_publication_fence_attempt " + + "WHERE attempt_created_full_xid IS NOT NULL") + .fetchOne(0, Long.class)) + .isZero(); + } + private Map> regionOperationState() { return retainedRows( dsl, diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java new file mode 100644 index 0000000000..dc249c13f2 --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java @@ -0,0 +1,776 @@ +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.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.ManagedChannel; +import io.grpc.stub.AbstractStub; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.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.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class WorldGameDesignPublicationTerminalVerifierTest { + private static final String NAMESPACE = "test"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesSameNamespaceGameDesignCallerBeforeDecodingOrCallingClient() { + var client = mock(GameDesignPublicationTerminalReadClient.class); + var verifier = new WorldGameDesignPublicationTerminalVerifier(NAMESPACE, client); + + assertThatThrownBy(() -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2})) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("same-namespace Game Design"); + assertThatThrownBy( + () -> + withPeer( + peer("other", "game-design-service"), + () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) + .isInstanceOf(SecurityException.class); + + verifyNoInteractions(client); + } + + @Test + void requiresNoAmbientTransactionAndRejectsMalformedOperationBeforeRemoteRead() throws Exception { + var client = mock(GameDesignPublicationTerminalReadClient.class); + var verifier = new WorldGameDesignPublicationTerminalVerifier(NAMESPACE, client); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside owner transactions"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(client); + + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(client); + } + + @Test + // The real client and codec are exercised over a stubbed channel; this is not physical mTLS + // proof. + void authenticatedExactCanonicalReadReturnsClosableAuthorityThroughTheRealClientCodec( + @TempDir Path directory) throws Exception { + var operation = operation(); + var terminal = terminal(operation, Outcome.NO_PUBLICATION); + try (var upstream = new StubbedGameDesignClient(directory)) { + upstream.respondWith( + wireRequest -> { + var readRequest = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wireRequest); + return GameDesignPublicationTerminalReadGrpcCodec.toResponse(readRequest, terminal); + }); + var verifier = new WorldGameDesignPublicationTerminalVerifier(NAMESPACE, upstream.client); + var verified = + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> + verifier.authenticateAndVerifyAndHold( + operation.canonicalBytes(), terminal.canonicalBytes())); + + assertThat(verified.request().operationBytes()).containsExactly(operation.canonicalBytes()); + assertThat(verified.request().terminalBytes()).containsExactly(terminal.canonicalBytes()); + verified.authority().requireHeld(); + verified.authority().close(); + assertThatThrownBy(verified.authority()::requireHeld) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no longer valid"); + assertThat(upstream.expectedServerIdentity()) + .isEqualTo("spiffe://firemud/ns/test/sa/game-design-service"); + verify(upstream.stub).readPublicationTerminal(any()); + } + } + + @Test + void rejectsChangedReadEchoAndSubstitutedCanonicalTerminal(@TempDir Path directory) + throws Exception { + var operation = operation(); + var expectedTerminal = terminal(operation, Outcome.NO_PUBLICATION); + var substitutedTerminal = terminal(operation, Outcome.PUBLISHED); + try (var upstream = new StubbedGameDesignClient(directory)) { + var verifier = new WorldGameDesignPublicationTerminalVerifier(NAMESPACE, upstream.client); + upstream.respondWith( + wireRequest -> { + var readRequest = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wireRequest); + return GameDesignPublicationTerminalReadGrpcCodec.toResponse( + readRequest, expectedTerminal) + .toBuilder() + .setReadRequestId(UUID.randomUUID().toString()) + .build(); + }); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> + verifier.authenticateAndVerifyAndHold( + operation.canonicalBytes(), expectedTerminal.canonicalBytes()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid publication terminal evidence"); + + upstream.respondWith( + wireRequest -> { + var readRequest = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wireRequest); + return GameDesignPublicationTerminalReadGrpcCodec.toResponse( + readRequest, substitutedTerminal); + }); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> + verifier.authenticateAndVerifyAndHold( + operation.canonicalBytes(), expectedTerminal.canonicalBytes()))) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("differs from the submitted exact operation or result"); + } + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static T withPeer(GrpcPeerIdentity identity, Callable task) throws Exception { + return Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, identity).call(task); + } + + private static GameDesignPublicationOperationBinding operation() throws Exception { + // Canonical structural inputs only; this fixture does not stipulate real owner commits or + // source holds. + var upstream = freshGraphRequest(); + var applied = committedFreshGraphReadback(upstream); + var original = upstream.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var target = draft.target(); + var intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publication-request", + "5", + "fixture", + draft.requestId(), + draft.commitId(), + draft.digest()); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + intent, + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var publicationSources = + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + "stipulated-publication-account-source".getBytes(StandardCharsets.UTF_8))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selection), + publicationSources); + var tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + String workflow = + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity(); + var result = JsonMapper.builder().build().readTree(applied.result()); + var appliedOperation = + new DraftAuthorizationFenceBinding.FrameReader( + Base64.getDecoder().decode(result.get("operationBytesBase64").textValue())); + appliedOperation.expect("world-draft-terminal-operation/v1"); + for (int frame = 1; frame < 13; frame++) appliedOperation.bytes(); + UUID intakeRequestId = UUID.fromString(appliedOperation.text()); + var worldRequest = + new WorldPublishedStartLocationEvidence.Request( + NAMESPACE, + target.canonicalTenantId(), + target.canonicalVersionId(), + intakeRequestId, + UUID.randomUUID(), + intent.publishRequestId(), + selection.digest().substring(7), + 5L, + workflow, + draft.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var world = + new WorldPublishedStartLocationEvidence( + worldRequest, + Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()), + applied.fullBinding(), + applied.result()); + return new GameDesignPublicationOperationBinding(account, world); + } + + private static GameDesignPublicationTerminalEvidence terminal( + GameDesignPublicationOperationBinding operation, Outcome outcome) { + if (outcome == Outcome.NO_PUBLICATION) { + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), outcome, null, null); + } + var selection = operation.account().input().selection(); + var world = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(selection.target().gameDesignVersionRowId()), + null, + world.appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) ? world.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, + null, + null)) + .toList(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + "fixture-bundle", + 1, + "v2", + world.publishWorkflowId(), + "sha256:" + "a".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of(), + "generation-1", + operation.world()); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), outcome, release, 6L); + } + + private static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { + var draft = freshGraphBinding(); + return new WorldDraftTerminalReadEvidence.Request( + 1, NAMESPACE, uuid("33333333-3333-4333-8333-333333333333"), accountBinding(draft)); + } + + private static DraftCommitBinding freshGraphBinding() throws Exception { + UUID tenantId = uuid("11111111-1111-4111-8111-111111111111"); + UUID versionId = uuid("22222222-2222-4222-8222-222222222222"); + UUID roomTemplateId = uuid("77777777-7777-4777-8777-777777777777"); + UUID regionTemplateId = uuid("88888888-8888-4888-8888-888888888888"); + UUID zoneTemplateId = uuid("99999999-9999-4999-8999-999999999999"); + UUID requestId = uuid("44444444-4444-4444-8444-444444444444"); + UUID commitId = uuid("55555555-5555-4555-8555-555555555555"); + var json = JsonMapper.builder().build(); + String declaration = + json.writeValueAsString( + Map.of( + "tenantId", tenantId.toString(), + "versionId", versionId.toString(), + "startLocation", + Map.of( + "tenantId", tenantId.toString(), + "versionId", versionId.toString(), + "roomTemplateId", roomTemplateId.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + UUID regionRevision = uuid("12345678-1234-4234-8234-123456789001"); + UUID zoneRevision = uuid("12345678-1234-4234-8234-123456789002"); + UUID roomRevision = uuid("12345678-1234-4234-8234-123456789003"); + return DraftCommitBinding.create( + new TargetProof(tenantId, versionId, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + requestId, + commitId, + "base-1", + List.of( + new RevisionPayload( + "0", + regionRevision, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + json, + commitId, + regionRevision, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + regionTemplateId, + declaration)), + new RevisionPayload( + "1", + zoneRevision, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + json, + commitId, + zoneRevision, + "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", + zoneTemplateId, + null)), + new RevisionPayload( + "2", + roomRevision, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + json, + commitId, + roomRevision, + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", + roomTemplateId, + null))), + List.of( + affected("REGION", regionTemplateId, "REGION_SUBTREE", regionTemplateId), + affected("ZONE", zoneTemplateId, "REGION_SUBTREE", regionTemplateId), + affected("ROOM", roomTemplateId, "ZONE_SUBTREE", zoneTemplateId)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static String worldRevisionPayload( + JsonMapper json, + UUID commitId, + UUID revisionId, + String family, + UUID templateId, + String declaration) + throws Exception { + var payload = new LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", commitId.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", json.readTree(declaration)); + return json.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + draft.requestId(), + draft.commitId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedFreshGraphReadback( + WorldDraftTerminalReadEvidence.Request request) throws Exception { + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = graphBytes(request, draft); + String graphDigest = sha256(graph); + var result = new LinkedHashMap(); + result.put("schema", "world-draft-graph-applied/v2"); + result.put("status", "APPLIED"); + result.put("operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", unit.aggregateType(), + "aggregateId", unit.aggregateId(), + "scopeType", unit.scopeType(), + "scopeId", unit.scopeId(), + "expectedEpoch", unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + return new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JsonMapper.builder().build().valueToTree(result))); + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + var json = JsonMapper.builder().build(); + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + JsonNode mutation = json.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return json.writeValueAsBytes(root); + } + + private static tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft, String graphDigest) + throws Exception { + var account = request.accountBinding(); + var selector = + Map.of( + "tenantId", account.tenantId().toString(), + "versionId", account.versionId().toString(), + "roomTemplateId", "77777777-7777-4777-8777-777777777777"); + String accountBindingDigest = sha256(request.originalAccountBinding()); + String receiptDigest = + startLocationReceiptDigest( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + accountBindingDigest, + draft.digest(), + account.tenantId(), + account.versionId(), + uuid("77777777-7777-4777-8777-777777777777"), + graphDigest); + var value = new LinkedHashMap(); + value.put("schema", "world-draft-start-location-receipt/v1"); + value.put("targetNamespace", request.targetNamespace()); + value.put("operationId", account.operationId().toString()); + value.put("requestId", account.requestId().toString()); + value.put("commitId", account.commitId().toString()); + value.put("authorizationFenceId", account.fenceId().toString()); + value.put("accountBindingDigest", accountBindingDigest); + value.put("bindingDigest", draft.digest()); + value.put("startLocation", selector); + value.put("graphDigest", graphDigest); + value.put("receiptDigest", receiptDigest); + return (tools.jackson.databind.node.ObjectNode) JsonMapper.builder().build().valueToTree(value); + } + + private static String startLocationReceiptDigest( + String namespace, + UUID operationId, + UUID requestId, + UUID commitId, + UUID fenceId, + String accountDigest, + String bindingDigest, + UUID tenantId, + UUID versionId, + UUID roomId, + String graphDigest) + throws Exception { + var framed = new ByteArrayOutputStream(); + for (String value : + List.of( + "world-draft-start-location-receipt/v1", + namespace, + operationId.toString(), + requestId.toString(), + commitId.toString(), + fenceId.toString(), + accountDigest, + bindingDigest, + tenantId.toString(), + versionId.toString(), + roomId.toString(), + graphDigest)) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + framed.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + framed.writeBytes(bytes); + } + return sha256(framed.toByteArray()); + } + + private static byte[] canonical(JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class StubbedGameDesignClient implements AutoCloseable { + private final GameDesignPublicationTerminalReadClient client; + private final String serverIdentity; + private final GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub + stub; + + private StubbedGameDesignClient(Path directory) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("design.internal:6565"); + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + var channelFactory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + org.mockito.ArgumentMatchers.eq("design.internal:6565"), + org.mockito.ArgumentMatchers.eq(6565), + any(CommonGrpcClientProperties.class), + org.mockito.ArgumentMatchers.eq(true))) + .thenReturn(channel); + client = + new GameDesignPublicationTerminalReadClient(endpoints, tls, channelFactory, NAMESPACE); + client.init(); + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + AbstractStub initialized = (AbstractStub) field.get(client); + var credentials = initialized.getCallOptions().getCredentials(); + if (!(credentials instanceof GrpcServerPeerIdentityCallCredentials)) { + throw new AssertionError("Strict Game Design peer identity credentials are required"); + } + Field peerField = credentials.getClass().getDeclaredField("expectedPeerUri"); + peerField.setAccessible(true); + serverIdentity = (String) peerField.get(credentials); + stub = + mock( + GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + field.set(client, stub); + } + + private void respondWith( + java.util.function.Function< + net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalRequest, + ReadPublicationTerminalResponse> + response) { + doAnswer(call -> response.apply(call.getArgument(0))) + .when(stub) + .readPublicationTerminal(any()); + } + + private String expectedServerIdentity() throws Exception { + return serverIdentity; + } + + @Override + public void close() throws Exception { + client.close(); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcServiceTest.java new file mode 100644 index 0000000000..89362bf218 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadGrpcServiceTest.java @@ -0,0 +1,110 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.ByteString; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalReadService; +import net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalResponse; +import org.junit.jupiter.api.Test; + +class WorldPublicationTerminalReadGrpcServiceTest { + @Test + void authenticatesExactAccountPeerBeforeDecodingOrCallingOwner() { + var owner = mock(WorldPublicationTerminalReadService.class); + var service = new WorldPublicationTerminalReadGrpcService(owner, "test"); + var malformed = malformedRequest(); + + Collector missingPeer = new Collector(); + service.readPublicationTerminal(malformed, missingPeer); + assertThat(Status.fromThrowable(missingPeer.error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + + Collector wrongPeer = new Collector(); + callAs(service, peer("world-management-service", "test"), malformed, wrongPeer); + assertThat(Status.fromThrowable(wrongPeer.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + Collector wrongNamespace = new Collector(); + callAs(service, peer("account-service", "other"), malformed, wrongNamespace); + assertThat(Status.fromThrowable(wrongNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } + + @Test + void authenticatedAccountMalformedRequestFailsBeforeOwnerStorage() { + var owner = mock(WorldPublicationTerminalReadService.class); + var service = new WorldPublicationTerminalReadGrpcService(owner, "test"); + Collector response = new Collector(); + callAs(service, peer("account-service", "test"), malformedRequest(), response); + + assertThat(Status.fromThrowable(response.error).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + verifyNoInteractions(owner); + } + + private static ReadPublicationTerminalRequest malformedRequest() { + return ReadPublicationTerminalRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace("test") + .setReadRequestId(UUID.randomUUID().toString()) + .setOriginalOperation(ByteString.copyFrom(new byte[] {1})) + .setExpectedGameDesignTerminalEvidence(ByteString.copyFrom(new byte[] {2})) + .build(); + } + + private static void callAs( + WorldPublicationTerminalReadGrpcService service, + GrpcPeerIdentity peer, + ReadPublicationTerminalRequest request, + Collector collector) { + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var previous = context.attach(); + try { + service.readPublicationTerminal(request, collector); + } finally { + context.detach(previous); + } + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static final class Collector implements StreamObserver { + private ReadPublicationTerminalResponse value; + private Throwable error; + private boolean completed; + + @Override + public void onNext(ReadPublicationTerminalResponse response) { + value = response; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The test collector retains the original throwable for assertion.") + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadServiceTest.java new file mode 100644 index 0000000000..894a4d5e40 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadServiceTest.java @@ -0,0 +1,44 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalReadService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalRepository; +import org.junit.jupiter.api.Test; + +class WorldPublicationTerminalReadServiceTest { + @Test + void rejectsMissingOrWrongAccountPeerBeforeInspectingRequestOrReadingStorage() { + var repository = mock(WorldPublicationTerminalRepository.class); + var service = new WorldPublicationTerminalReadService(repository, "test"); + + assertThatThrownBy(() -> service.read(null)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .extracting(failure -> Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + + var wrongPeer = peer("world-management-service", "test"); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer); + var previous = context.attach(); + try { + assertThatThrownBy(() -> service.read(null)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .extracting(failure -> Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + context.detach(previous); + } + + verifyNoInteractions(repository); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } +} From 9158561db4505e730274ac2c1f00069631481f9e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 10:09:00 +1300 Subject: [PATCH 031/129] Connect selected publication producer and repair physical proof setup --- .../account-service/api-contracts.md | 2 + .../game-design-service/api-contracts.md | 2 + design/project-management/ai-observations.md | 12 + ...ame-authoring-publishing-and-activation.md | 10 +- .../selected_publication_order_service.proto | 30 + ...ectedDraftPublicationOrderGrpcService.java | 152 +++++ ...ccount_selected_publication_settlement.sql | 2 +- ...horizationMtlsPostgresIntegrationTest.java | 252 +++++++ ...dDraftPublicationOrderGrpcServiceTest.java | 305 +++++++++ .../AccountControlUiOriginalOrderFixture.java | 91 +++ ...AccountSelectedPublicationOrderClient.java | 137 ++++ ...ntSelectedPublicationOrderCredentials.java | 113 ++++ ...ountSelectedPublicationOrderGrpcCodec.java | 152 +++++ ...untSelectedPublicationOrderClientTest.java | 158 +++++ ...lectedPublicationOrderCredentialsTest.java | 99 +++ ...SelectedPublicationOrderGrpcCodecTest.java | 112 ++++ ...electedDraftPublicationCommandService.java | 283 ++++++++ ...tedDraftPublicationCommandServiceTest.java | 321 +++++++++ ...uthorizedDraftPostgresIntegrationTest.java | 619 ++++++++++++------ ...aphApplicationPostgresIntegrationTest.java | 18 +- 20 files changed, 2656 insertions(+), 214 deletions(-) create mode 100644 protos/account/v1/selected_publication_order_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandServiceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d34d1703cb..2342e34cf0 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -86,6 +86,8 @@ Settlement compares two distinct authenticated owner results: Game Design's orig The selected-order composition authenticates the exact same-namespace Game Design caller, obtains the [immutable selected-Draft owner read](../game-design-service/api-contracts.md#immutable-selected-draft-publication-read) outside Account SQL, then passes the unchanged creator credential and exact retained selection to Account's current-actor/source-hold owner transaction. `SELECTED` alone is not actor authorization. No database lock may span that read, and unavailable or substituted selection evidence cannot create an order. Implementation and executed proof remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The standalone, unregistered [`AccountSelectedPublicationOrderService.AuthorizeSelectedPublication`](../../../../protos/account/v1/selected_publication_order_service.proto) producer accepts schema version 1, the exact target namespace, a fresh nonzero transport correlation UUID and complete canonical selected-Draft bytes. The unchanged original creator credential travels only in protected, method-specific per-call metadata, never in protobuf request or response text; metadata must not be logged. Only the verified same-namespace Game Design workload may call it; Account authenticates before accessing or decoding credential metadata, decoding the request or capturing authority, and World has no producer permission. The receiver binds its credential interceptor internally; missing, duplicate, malformed or oversized credentials deny without owner mutation. Account captures its current environment boundary internally and validates it through the existing owner transaction; no caller-supplied environment or currentness value is authority. The response echoes the complete non-secret request tuple and exact canonical Account authorization binding, never the credential. Transport correlation does not change the durable publication identity: retry retains the original order, source evidence and fence. Unknown or noncanonical fields, changed response correlation or selection, unavailable currentness and substituted server identity fail closed. Calls require file-backed mutual TLS with exact Account server identity, a bounded five-second deadline and no ambient SQL transaction. Future registration must account for the transport metadata budget; a lower server limit still fails closed rather than truncating credentials. This transport defines no runtime registration or production environment-authority provider. + `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 69ac6c80f6..7d4825009d 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -55,6 +55,8 @@ A successful response echoes the entire request unchanged and reports only `SELE The transport is construction work, not runtime registration. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records executed proof and remaining producer, composition and activation gates. The [Account contract](../account-service/api-contracts.md#grpc-apis) owns publication authorization and source participation; the [World contract](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) owns freeze and terminal handoff. +The internal selected-publication command connects authenticated Account/World admission to finalization of that exact existing Draft, never to the ordinary path that allocates a new Version. The immutable selection must already exist before Account authorization. With no retained publication operation, Game Design verifies that selection against the complete original intent and owner lookup inputs, obtains both authenticated owner reads outside SQL, and reserves its local operation before finalization. Once the exact operation exists, retries compare the complete retained selection, original Account binding and World request before reconciling that same attempt. They do not recapture mutable Draft state, require a new `HELD` result after settlement, or mint another authorization or release identity. Missing selection, contradictory or incomplete operation evidence remains denied. Historical identity is not current creator permission; an unregistered internal composition is not a public creator ingress or runtime activation. + ## Exact Publication Terminal Read `GameDesignPublicationTerminalReadService.ReadPublicationTerminal` reads the original immutable terminal result, not current permission or a new publication attempt. Its closed version-1 request binds the canonical workload namespace, a non-nil canonical read-request UUID and the complete original `game-design-publication-operation/v1` bytes. The receiver authenticates the exact same-namespace Account or World Management workload before decoding input or accessing storage. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 15f9896df6..a511692c77 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -108,3 +108,15 @@ Entry format: - Context: PR #3105 Game Session and TCP matrix jobs exhausted Gradle's 1.5 GiB Java heap while compiling dependent services, before owner integration tests ran. - Observation: These jobs supplied no owner execution proof and no demonstrated semantic compiler error. Configuration-cache diagnostics were separate from the heap failure. - Expected pattern: Preserve the complete validation tasks and artifact capture while applying a bounded resource profile, then require corrected-head CI. The local 3 GiB, nonparallel, two-worker profile is preparation, not proof that hosted compilation is repaired. + +- `2026-10-08`: Verify protobuf credential redaction in the actual language runtime + - Context: The new unpublished Account publication-order transport marked its credential field with protobuf `debug_redact`, but the Java generated message's text representation still exposed a synthetic credential in focused proof. + - Observation: The schema annotation did not supply the assumed Java redaction guarantee. The redacted domain request was insufficient to protect the generated wire representation. + - Expected pattern: Prove credential-safe representations in the actual generated runtime, keep credentials out of message text and diagnostics, and never log protected authorization metadata. Do not remove a failing safety assertion to claim redaction. + - Current status: The focused gate caught the mismatch before publication. The credential is now absent from the protobuf request and travels in method-specific protected metadata; the corrected 316-case Common unit run passes, including redacted wrappers, protected-method emission and malformed-header denial. Physical transport execution remains required, and runtime registration stays denied. + +- `2026-10-08`: Resolve synthetic-merge attribution against the current target ref + - Context: The exact `2560d12a` observer compared PR metadata's base `1a8eefe` with the live target ref and synthetic merge first parent `fe15a31`. + - Observation: The target had advanced 21 commits beyond the recorded base, accounting for 33 extra paths in the merge tree, with no Account, Game Design or World owner paths. This explains the observed tree difference without proving each job's checkout from metadata alone. + - Expected pattern: Distinguish recorded-base metadata, current target ref, merge-object ancestry and actual job checkout. Parent movement does not authorize topology changes or confer exact-integrated-base proof. + - Current status: The completed observer verified Account, World, Game Design, Game Session and TCP job logs actually checked out synthetic merge `e2bdaf5`, with parents `fe15a31` and published `2560d12a`; intended-parent alignment remains a separate gate. 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 7086ba3b28..8f3aa005fa 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 @@ -6,13 +6,15 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The current publication handoff batch has passing local unit XML for 309 Common, 1,073 Account, 341 Game Design and 540 World cases, plus seven non-database Account integration cases. All 508 database integration definitions skip without Docker: 227 Account, 75 Game Design and 206 World. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. Four-owner formatting, static checks, packaging and documentation gates pass after the final World integration-fixture compilation correction; Flyway sanity covers 12 sets / 246 versioned files. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. +Published-head `2560d12a8265db943a06e43d1e9e261bb2cdd923` [Validation run 37840711622](https://github.com/benhook1013/FireMUD/actions/runs/37840711622) finished red: 36 jobs passed, Account/World/the aggregate gate failed, and one tooling contract job skipped. Its physical XML records 233 Account cases with 208 failures, 206 World cases with 42 failures, and 75 Game Design cases with no failures; all have zero skips and errors. V107's PL/pgSQL syntax error blocked Account initialization and two World cases. All seven isolated WAL tests failed during migration setup, before their proof logic; this is neither WAL execution proof nor a new V92 durability verdict. World's other failures expose stale terminal fixtures missing V53 qualification (36 cases) and four terminal fixtures incorrectly entering unsupported generation/spawn preparation. The bounded syntax and fixture repairs require corrected-head physical execution; no production qualification or generation-intent guard may be weakened. Game Session and TCP Gradle checks passed with the bounded resource profile. Actual owner jobs checked out synthetic merge `e2bdaf5d011ba97d9a407183892e9ec7b069a909`, tree `1fb483d5c7ed53f27b483587a38909181aa3316b`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and `2560d12a8265db943a06e43d1e9e261bb2cdd923`. The live target had advanced 21 commits/33 paths beyond recorded base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`, with no Account/Game Design/World service differences; this explains composition but does not close intended-parent alignment. Substantive [CodeQL run 37840711613](https://github.com/benhook1013/FireMUD/actions/runs/37840711613) succeeded. Its dependency-deferred duplicate supplied no additional analysis; likewise metadata-only Validation run 37840712794 supplied no runtime proof. + +The current publication handoff batch has passing local unit XML for 316 Common, 1,079 Account, 347 Game Design and 540 World cases, plus seven non-database Account integration cases. All 509 database integration definitions skip without Docker: 228 Account, 75 Game Design and 206 World. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. The consolidated Common/Account/Game Design gate failed solely on an unnecessary new receiver suppression; removing it and rerunning Account formatting/main static analysis/packaging plus the complete World gate passed. Common and Game Design full gates, all three service boot jars and the remaining Account static gates passed in the consolidated run. Documentation validation remains separate; Flyway sanity covers 12 sets / 246 versioned files. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. Published-head `5132fb96b98f2d33b9db5d09d763aebb63efafb2` [Validation run 37834941641](https://github.com/benhook1013/FireMUD/actions/runs/37834941641) executed 229 Account, 75 Game Design and 202 World owner integration cases without skips. Game Design passed; Account retained one V92 original-acknowledgement WAL-coverage denial, and four World historical-upgrade fixtures failed after the additive full-XID column changed their copy/snapshot shapes. The bounded fixture correction preserves all historical fields and explicitly proves the new stamp stays null; corrected-head physical execution remains required. Game Session and TCP Proxy failed in dependent Java compilation with heap exhaustion, before their owner integration tests executed. The runner used synthetic merge `6d8435b7e31f5306defe357703139ccaa23e3fe6` with first parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`; these results do not close actual-parent alignment. Passing source intake mTLS cases do not separately establish the complete V53 qualification or genuine publication boundary. The terminal construction adds V54's bounded operation-frame check and repository checks against the complete distinct V53 Account publication qualification on first completion and exact retry/readback. Its unregistered Game Design terminal verifier authenticates before decoding and reads immutable owner evidence outside SQL; this is not a remote Account source lock. Qualified fixture changes preserve that distinction and retain the original order with the first freeze instead of attaching it later. The separate World-authenticated terminal read verifies independently committed World phase and exact original terminal backing. Account's unregistered composition obtains both strict authenticated owner reads outside SQL, then commits and separately reads back V107's immutable settlement receipt; only that exact receipt releases this order's pending source participation. Historical retry does not recapture current credentials, and an external `HELD` read denies after settlement. These are bounded construction components, not completed genuine handoffs; all four Gameplay prerequisites and runtime activation remain open. -Expanded Game Design and World terminal repository/loopback-mTLS definitions retain actual local owner storage while stipulating upstream authorities. Account settlement's loopback-mTLS definition exercises its real creator/order/storage with two distinct strict clients, but the remote terminal endpoints and incoming Game Design context are stipulated. The independent Account readback connection checks commit before the second owner transaction; this is not an actual network lost-acknowledgement injection. These definitions require corrected-head physical execution and cannot establish a genuine multi-owner publication chain by themselves. The bounded CI heap-profile repair preserves full matrix validation and packaging tasks; its hosted outcome remains unproved. +Expanded Game Design and World terminal repository/loopback-mTLS definitions retain actual local owner storage while stipulating upstream authorities. Account settlement's loopback-mTLS definition exercises its real creator/order/storage with two distinct strict clients, but the remote terminal endpoints and incoming Game Design context are stipulated. The independent Account readback connection checks commit before the second owner transaction; this is not an actual network lost-acknowledgement injection. These definitions require corrected-head physical execution and cannot establish a genuine multi-owner publication chain by themselves. The bounded CI heap-profile repair preserves full matrix validation and packaging tasks; the `2560d12a` Game Session and TCP jobs passed under that profile, without proving every future composed head. The isolated Account WAL investigation is test-only and leaves V92's conservative production denial unchanged. Its seven dedicated PostgreSQL 16 definitions compile/discover but all skip locally without Docker. They define transactional immutable locators, exact target COMMIT readback and restricted-reader recovery; synthetic ambiguity/identity/capability classifications do not prove physical epoch wrap, promotion, WAL recycling, an unrelated unflushed tail or insufficient target flush. Extension feasibility, physical positive/negative execution, locator retention and any production adoption remain separate gates. The shared PostgreSQL 18 baseline does not change the Account admission executors' PostgreSQL 16-only guards. @@ -22,12 +24,14 @@ The [immutable selected-Draft owner read](../../architecture/microservices/game- The legacy World numeric mutation route lacks the target shared-lock handoff, but the existing canonical-tenant manifest and mapped-row guards deny its writes to the exact fresh canonical target. The current composition adds negative PostgreSQL definitions through the real mutation service, deriving private selectors from retained mapping evidence and checking unchanged content, mappings, epochs, ledger, application and freeze history. These definitions have not yet executed physically; they do not justify opening the legacy route or claiming its broader target contract complete. -The World selected-fresh-graph checkpoint callback derives its commit identity from the exact retained Account-bound `APPLIED` application, rather than a caller-supplied checkpoint. Under the shared owner lock it rechecks the complete current graph and epoch set and computes the schema-3 content digest. Construction CI at `60c507243987705094a3028e0b46f3bccd5d9504` executed the actual Account-order-to-World-APPLIED and selected-checkpoint cases. The standalone selected-publication freeze composition now obtains authenticated immutable selection, current Game Design Draft state and exact Account held-order reads outside SQL, then retains the complete Account binding atomically with the first World freeze. V53 denies late qualification of historical attempts. Exact committed retry verifies the stored order before recapturing mutable authority. New qualification/rollback definitions still require physical execution; their distinct Account publication order is explicitly stipulated, not a substitute for the genuine producer. This does not change the generic digest's synthetic highest-commit limitation, register a freeze RPC, settle either owner, or establish end-to-end publication authority. +The World selected-fresh-graph checkpoint callback derives its commit identity from the exact retained Account-bound `APPLIED` application, rather than a caller-supplied checkpoint. Under the shared owner lock it rechecks the complete current graph and epoch set and computes the schema-3 content digest. Construction CI at `60c507243987705094a3028e0b46f3bccd5d9504` executed the actual Account-order-to-World-APPLIED and selected-checkpoint cases. The standalone selected-publication freeze composition obtains authenticated immutable selection, current Game Design Draft state and exact Account held-order reads outside SQL, then retains the complete Account binding atomically with the first World freeze. V53 denies late qualification of historical attempts. Exact committed retry verifies the stored order before recapturing mutable authority. The revised combined PostgreSQL definition uses the original owner-issued creator credential to obtain a real distinct Account publication order, reads its actual `HELD` state over strict loopback mTLS, and invokes the World freeze composition for first commit and exact retry. Game Design selection/current-Draft endpoints and the incoming Game Design caller context remain explicit fixture stipulations. Source protection is checked before and after freeze, but the original Draft order also remains pending, so writer denial does not isolate publication as its sole cause. The revised qualification/rollback definitions still require physical execution. This does not change the generic digest's synthetic highest-commit limitation, register a freeze RPC, settle either owner, or establish end-to-end publication authority. The standalone Game Design terminal owner read verifies complete original operation and terminal backing in an independent read-only repeatable-read snapshot. Its closed transport follows the [exact terminal-read contract](../../architecture/microservices/game-design-service/api-contracts.md#exact-publication-terminal-read); owner/transport unit definitions do not establish physical authenticated terminal composition. The receiver remains unregistered. World completion and distinct Account settlement now have unregistered construction components, but their genuine composed producer and physical proof remain open. The standalone Account selected-publication producer defines a distinct immutable authorization from the authenticated current initial creator, immutable selected Draft and original issuance/source/checkpoint evidence before World capture. Its unregistered owner reader permits only verified same-namespace Game Design or World Management workloads and checks exact retained participation and committed issuance in one independent snapshot. V106 permits new pre-freeze orders without World evidence while retaining immutable V103 evidence unchanged and checking it when present; retained-row upgrade execution remains unproved. Later World correlation cannot rewrite the Account order. Pending publication participates in source-writer and prepare-before-disclose guards; V107's exact immutable receipt removes only its settled order from those predicates. Genuine authenticated terminal composition and physical settlement proof remain open. Producer, transport and database test definitions are not runtime activation. +The new standalone Account producer transport binds its method-specific credential interceptor internally and captures the environment boundary through Account's owner service, not caller input. Local Common units prove credential-free protobuf text, redacted wrappers and protected exact-method emission; receiver units prove peer-first denial and owner ordering. The new PostgreSQL/loopback-mTLS definition drives real creator issuance, the producer transport and retained publication sources, but stipulates upstream Game Design selection. The production environment-authority provider and runtime registration are absent; physical execution is pending. Game Design's unregistered selected-publication command now composes authenticated admission with the existing selected-Version v2 finalizer and exact retained-operation retry. Its six local unit cases use mocked collaborators and do not prove PostgreSQL command composition, a genuine release manifest or complete multi-owner publication. These limitations must remain beside each bounded proof claim. + Substantive construction CI [37827785558](https://github.com/benhook1013/FireMUD/actions/runs/37827785558) for `60c507243987705094a3028e0b46f3bccd5d9504` executed 229 Account, 201 World and 74 Game Design integration cases with no skips or errors. Game Design and World passed; Account had two failures. The signer generation/promotion identity correction and V103 terms-fixture correction passed their affected cases. One remaining Account concurrency test reused a frozen activity-statistics snapshot while waiting for a blocked creator; its observer correction requires corrected-head execution. Original-ack receipt recovery still fails closed against the conservative global WAL insert fence. Decoded target COMMIT boundaries were covered by the independently logged flush, but the production recovery path has no supported independent exact-COMMIT locator; this diagnostic does not weaken durability or deadline requirements. The run tested a synthetic merge whose first parent was `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`; it supplies no exact-integrated-base or ancestry-closure proof. Local PostgreSQL definitions remain skipped without Docker. The current Gameplay-prerequisite construction remains non-activating. Full-version finalization reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. Production backend control-ui issuance/current-actor integration, complete Account source-writer fencing and the callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. In particular, the distinct selected-publication operation still needs authenticated Account authorization; original Draft permission cannot substitute. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Construction CI at `f14c7950827dd435ac0fe5c4cc230a1de32fa96d` executed all 74 Game Design and 200 World integration cases without skips or failures, including the corrected canonical-release and selected-publication transaction regressions. Its 220 Account integration executions passed the future-terms, environment-binding, disclosure-handoff and three real Redis registry cases; one readiness-promotion fixture assertion still compared its initial plan with subsequently progressed entries. A corrected assertion and the composed Account-to-World handoff need separate validation. These bounded results do not upgrade the broader capability ratings below. diff --git a/protos/account/v1/selected_publication_order_service.proto b/protos/account/v1/selected_publication_order_service.proto new file mode 100644 index 0000000000..a23b205803 --- /dev/null +++ b/protos/account/v1/selected_publication_order_service.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered Game Design-only producer. No environment authority is caller supplied. +service AccountSelectedPublicationOrderService { + rpc AuthorizeSelectedPublication(AuthorizeSelectedPublicationRequest) + returns (AuthorizeSelectedPublicationResponse); +} + +message AuthorizeSelectedPublicationRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Transport correlation only; the selected publication request owns durable identity. + string request_id = 3; + bytes original_selection = 4; + // The original creator credential travels only in protected per-call metadata. + reserved 5; + reserved "original_creator_credential"; +} + +message AuthorizeSelectedPublicationResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + bytes original_selection = 4; + bytes publication_authorization_binding = 5; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java new file mode 100644 index 0000000000..3e26220f58 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.BindableService; +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone, unregistered producer; Account obtains environment authority internally. */ +public final class AccountSelectedDraftPublicationOrderGrpcService implements BindableService { + private final AccountSelectedDraftPublicationOrderService owner; + private final AccountHostedTermsService terms; + private final String namespace; + + public AccountSelectedDraftPublicationOrderGrpcService( + AccountSelectedDraftPublicationOrderService owner, + AccountHostedTermsService terms, + String namespace) { + this.owner = Objects.requireNonNull(owner); + this.terms = Objects.requireNonNull(terms); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + /** + * Binding always includes the method-local credential interceptor; peer identity runs outside it. + */ + @Override + public ServerServiceDefinition bindService() { + var handler = + new AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceImplBase() { + @Override + public void authorizeSelectedPublication( + AuthorizeSelectedPublicationRequest request, + StreamObserver observer) { + AccountSelectedDraftPublicationOrderGrpcService.this.authorizeSelectedPublication( + request, observer); + } + }; + return ServerInterceptors.intercept( + handler, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Status denied = peerDenial(); + if (denied != null) { + call.close(sanitized(denied), new Metadata()); + return new ServerCall.Listener<>() {}; + } + final AccountSelectedPublicationOrderCredentials.Credential credential; + try { + credential = AccountSelectedPublicationOrderCredentials.readAuthenticated(headers); + } catch (IllegalArgumentException malformed) { + call.close(sanitized(Status.UNAUTHENTICATED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + var context = + Context.current() + .withValue(AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, credential); + return Contexts.interceptCall(context, call, headers, next); + } + }); + } + + public void authorizeSelectedPublication( + AuthorizeSelectedPublicationRequest wire, + StreamObserver observer) { + Status denied = peerDenial(); + if (denied != null) { + deny(observer, denied); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + final AccountSelectedPublicationOrderGrpcCodec.Request request; + final String credential; + try { + var protectedCredential = AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get(); + if (protectedCredential == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + credential = protectedCredential.value(); + } catch (IllegalArgumentException malformed) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + try { + request = AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, credential); + } catch (IllegalArgumentException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + final AuthorizeSelectedPublicationResponse response; + try { + var captured = terms.captureCurrentEnvironmentBoundary(); + var binding = + owner.authorize(request.originalCreatorCredential(), request.selection(), captured); + response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + } catch (StatusRuntimeException failure) { + deny(observer, Status.fromCode(failure.getStatus().getCode())); + return; + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError(sanitized(status).asRuntimeException()); + } + + private Status peerDenial() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) return Status.UNAUTHENTICATED; + return ("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri()) + ? null + : Status.PERMISSION_DENIED; + } + + private static Status sanitized(Status status) { + return status.withDescription("Account selected-publication order denied or unavailable"); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V107__account_selected_publication_settlement.sql b/services/account-service/src/main/resources/db/migration/V107__account_selected_publication_settlement.sql index 77a8ef1b66..661d7c34c7 100644 --- a/services/account-service/src/main/resources/db/migration/V107__account_selected_publication_settlement.sql +++ b/services/account-service/src/main/resources/db/migration/V107__account_selected_publication_settlement.sql @@ -97,7 +97,7 @@ BEGIN IF terminal_frames[1] IS DISTINCT FROM convert_to('game-design-publication-terminal/v1', 'UTF8') OR terminal_frames[2] IS DISTINCT FROM NEW.publication_operation OR terminal_frames[3] IS DISTINCT FROM convert_to(NEW.game_design_outcome, 'UTF8') - OR cardinality(terminal_frames) <> CASE WHEN NEW.game_design_outcome = 'PUBLISHED' THEN 5 ELSE 3 END THEN + OR cardinality(terminal_frames) <> (CASE WHEN NEW.game_design_outcome = 'PUBLISHED' THEN 5 ELSE 3 END) THEN RAISE EXCEPTION 'Changed complete publication terminal relationship' USING ERRCODE = '23514'; END IF; IF NEW.game_design_outcome = 'PUBLISHED' THEN diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java index 22b7bb7398..b41fcc5ea3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -33,6 +33,11 @@ import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadClient; import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadGrpcCodec; @@ -101,6 +106,253 @@ class AccountPublicationAuthorizationMtlsPostgresIntegrationTest { @TempDir Path temporary; + /** + * Real creator issuance, automatic Account environment capture and publication transaction over + * loopback mTLS. The strict upstream Game Design reader serves a stipulated immutable selection, + * not an actual Game Design reservation/database. Platform/legal/trust inputs remain fixtures. + */ + @Test + void selectedOrderProducerTransportUsesOriginalCreatorAndReplaysOneDurableHeldOrder() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("producer-pki"))); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve("producer-owner")))) { + // Exactly one issuance/OTP consumption; no owner order is fabricated or preseeded. + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var selection = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()) + .selection(); + var issuance = + sources.dsl.fetchSingle( + "SELECT operation_id, token_hash FROM account_control_ui_issuance_operations WHERE status = 'COMMITTED'"); + var reads = new java.util.concurrent.CopyOnWriteArrayList(); + var upstream = + new net.firedevops.firemud.gamedesign.v1.GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceImplBase() { + @Override + public void readSelectedDraftPublication( + net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse> + observer) { + try { + requireAccountClient(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var request = AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest(wire); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.originalSelection()).isEqualTo(selection.canonicalBytes()); + reads.add(wire.getReadRequestId()); + observer.onNext( + AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(request)); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + Server gdServer = terminalServer(pki.gameDesignServer, pki.ca, upstream); + try (var selectionClient = selectionClient(gdServer.getPort(), pki.accountClient, pki.ca)) { + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var owner = + new AccountSelectedDraftPublicationOrderService( + selectionClient, + new AccountPublicationAuthorizationService( + issued.actors(), sources.fences, repository), + NAMESPACE); + var producer = + new AccountSelectedDraftPublicationOrderGrpcService(owner, sources.terms, NAMESPACE); + var held = + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE), + NAMESPACE); + Server accountServer = terminalServer(pki.server, pki.ca, producer, held); + try { + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, issued.compact()); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + assertThat(wire.toString()).doesNotContain(issued.compact()); + var rawKey = + io.grpc.Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + io.grpc.Metadata.BINARY_BYTE_MARSHALLER); + var malformed = new io.grpc.Metadata(); + malformed.put(rawKey, new byte[] {(byte) 128}); + var duplicate = new io.grpc.Metadata(); + duplicate.put(rawKey, issued.compact().getBytes(StandardCharsets.US_ASCII)); + duplicate.put(rawKey, issued.compact().getBytes(StandardCharsets.US_ASCII)); + for (var wrongPeer : List.of(pki.worldManagement, pki.otherNamespace)) { + assertProducerHeaderDenied( + accountServer.getPort(), + wrongPeer, + pki.ca, + wire, + malformed, + Status.Code.PERMISSION_DENIED); + } + for (var headers : List.of(new io.grpc.Metadata(), malformed, duplicate)) { + assertProducerHeaderDenied( + accountServer.getPort(), + pki.gameDesign, + pki.ca, + wire, + headers, + Status.Code.UNAUTHENTICATED); + } + assertThat(reads).isEmpty(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isZero(); + for (var wrongPeer : List.of(pki.worldManagement, pki.otherNamespace)) { + try (var client = producerClient(accountServer.getPort(), wrongPeer, pki.ca)) { + assertCode(Status.Code.PERMISSION_DENIED, () -> client.authorize(request)); + } + assertThat(reads).isEmpty(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isZero(); + } + try (var client = producerClient(accountServer.getPort(), pki.gameDesign, pki.ca)) { + var first = client.authorize(request); + var retry = client.authorize(request); + var fresh = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, issued.compact()); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat(fresh.originalCreatorCredential()) + .isEqualTo(request.originalCreatorCredential()); + var correlatedRetry = client.authorize(fresh); + assertThat(retry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + assertThat(correlatedRetry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + assertThat(first.input().selection().canonicalBytes()) + .isEqualTo(selection.canonicalBytes()); + assertThat(first.input().actorAccountId()).isEqualTo(sources.account.getAccountUuid()); + assertThat(reads).hasSize(3).doesNotHaveDuplicates(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isEqualTo(first.sources().size()); + var stored = + sources.dsl.fetchSingle( + "SELECT binding, issuance_operation_id FROM account_selected_publication_authorizations WHERE operation_id = ?", + first.operationId()); + assertThat(stored.get("binding", byte[].class)).isEqualTo(first.canonicalBytes()); + assertThat(stored.get("issuance_operation_id", UUID.class)) + .isEqualTo(issuance.get("operation_id", UUID.class)); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_control_ui_issuance_operations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchSingle( + "SELECT operation_id, token_hash FROM account_control_ui_issuance_operations WHERE status = 'COMMITTED'")) + .isEqualTo(issuance); + assertPending(sources, repository, first); + try (var reader = client(accountServer.getPort(), pki.worldManagement, pki.ca)) { + var exactHeld = + AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, first); + assertThat(reader.read(exactHeld).request()).isEqualTo(exactHeld); + } + } + } finally { + accountServer.shutdownNow(); + assertThat(accountServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } finally { + gdServer.shutdownNow(); + assertThat(gdServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static AccountSelectedPublicationOrderClient producerClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var client = + new AccountSelectedPublicationOrderClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + /** Negative transport only: deliberately bypasses the production credential emitter. */ + private static void assertProducerHeaderDenied( + int port, + TestIdentity identity, + Path ca, + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest wire, + io.grpc.Metadata headers, + Status.Code expected) + throws Exception { + var channel = + new GrpcChannelFactory() + .buildChannel("127.0.0.1:" + port, 6565, identity.properties(ca), true); + try { + var peer = "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service"; + var stub = + net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc + .newBlockingStub(channel) + .withCallCredentials( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( + peer)) + .withInterceptors( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( + peer), + io.grpc.stub.MetadataUtils.newAttachHeadersInterceptor(headers)) + .withDeadlineAfter(5, TimeUnit.SECONDS); + assertCode(expected, () -> stub.authorizeSelectedPublication(wire)); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static AuthoredDraftPublishSelectionReadClient selectionClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + port); + var client = + new AuthoredDraftPublishSelectionReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + /** * Real Account storage and two strict loopback mTLS clients. Remote immutable terminals and the * incoming Game Design request context are stipulated; remote owner databases are not exercised. diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java new file mode 100644 index 0000000000..53a1c94d72 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java @@ -0,0 +1,305 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Context-level receiver units, not mounted-certificate or real Account currentness proof. */ +class AccountSelectedDraftPublicationOrderGrpcServiceTest { + private static final String CREDENTIAL = "original.secret.credential"; + private final AccountSelectedDraftPublicationOrderService owner = + mock(AccountSelectedDraftPublicationOrderService.class); + private final AccountHostedTermsService terms = mock(AccountHostedTermsService.class); + private final AccountSelectedDraftPublicationOrderGrpcService receiver = + new AccountSelectedDraftPublicationOrderGrpcService(owner, terms, "test"); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeMalformedDecodeAndCaptureAndDeniesWorld() { + assertThat(invoke(null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String workload : + List.of("world-management-service", "account-service", "game-session-service")) { + assertThat(peer("test", workload, () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(peer("other", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + authorized(() -> invoke(AuthorizeSelectedPublicationRequest.getDefaultInstance())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner, terms); + } + + @Test + void boundInterceptorAuthenticatesBeforeTouchingMalformedCredentialMetadata() { + var headers = mock(io.grpc.Metadata.class); + assertThat(boundCode(headers)).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer("test", "world-management-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(headers, owner, terms); + var malformed = new io.grpc.Metadata(); + malformed.put( + io.grpc.Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + io.grpc.Metadata.BINARY_BYTE_MARSHALLER), + new byte[] {(byte) 128}); + assertThat(peer("test", "game-design-service", () -> boundCode(malformed))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer("test", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(owner, terms); + } + + @SuppressWarnings("unchecked") + private Status.Code boundCode(io.grpc.Metadata headers) { + var method = + (io.grpc.ServerMethodDefinition< + AuthorizeSelectedPublicationRequest, AuthorizeSelectedPublicationResponse>) + receiver.bindService().getMethods().iterator().next(); + io.grpc.ServerCall + call = mock(io.grpc.ServerCall.class); + method.getServerCallHandler().startCall(call, headers); + var status = org.mockito.ArgumentCaptor.forClass(Status.class); + org.mockito.Mockito.verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any()); + return status.getValue().getCode(); + } + + @Test + void deniesAmbientSqlNamespaceAndUnknownFieldsBeforeCapture() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(authorized(() -> invoke(null)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThat(authorized(() -> invoke(null)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clearSynchronization(); + var request = request(); + assertThat( + authorized(() -> invoke(request.toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + authorized( + () -> + invoke( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner, terms); + } + + @Test + void + automaticallyCapturesAccountEnvironmentAndHandsOffOriginalCredentialAndSelectionOutsideSql() { + var request = request(); + var decoded = AccountSelectedPublicationOrderGrpcCodec.fromRequest(request, CREDENTIAL); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + UUID actor = UUID.randomUUID(); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + actor, decoded.selection()), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + when(terms.captureCurrentEnvironmentBoundary()) + .thenAnswer( + call -> { + outsideSql(); + return captured; + }); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenAnswer( + call -> { + outsideSql(); + assertThat( + call.getArgument(1, AuthoredDraftPublishSelectionBinding.class) + .canonicalBytes()) + .isEqualTo(decoded.originalSelection()); + return binding; + }); + var result = authorized(() -> invoke(request)); + assertThat(result.error()).isNull(); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse(decoded, result.response()) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + assertThat(result.response().toString()).doesNotContain(CREDENTIAL); + } + + @Test + void unavailableCaptureReturnsSanitizedFailure() { + when(terms.captureCurrentEnvironmentBoundary()) + .thenThrow(new IllegalStateException(CREDENTIAL)); + var denied = authorized(() -> invoke(request())); + assertThat(denied.code()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + verifyNoInteractions(owner); + } + + @Test + void secretBearingOwnerStatusReturnsOnlyItsCodeAndSanitizedDescription() { + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenThrow(Status.PERMISSION_DENIED.withDescription(CREDENTIAL).asRuntimeException()); + var denied = authorized(() -> invoke(request())); + assertThat(denied.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + assertThat(denied.error().getCause()).isNull(); + } + + private record Result(AuthorizeSelectedPublicationResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private Result invoke(AuthorizeSelectedPublicationRequest request) { + var response = new AtomicReference(); + var error = new AtomicReference(); + receiver.authorizeSelectedPublication( + request, + new io.grpc.stub.StreamObserver<>() { + @Override + public void onNext(AuthorizeSelectedPublicationResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() {} + }); + return new Result(response.get(), error.get()); + } + + private static void outsideSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static T authorized(java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, + AccountSelectedPublicationOrderCredentials.Credential.of(CREDENTIAL)); + var prior = context.attach(); + try { + return peer("test", "game-design-service", action); + } finally { + context.detach(prior); + } + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static AuthorizeSelectedPublicationRequest request() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19, "tenant-key", 42, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "fixture", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return AccountSelectedPublicationOrderGrpcCodec.toRequest( + AccountSelectedPublicationOrderGrpcCodec.Request.create("test", selected, CREDENTIAL)); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 92493cb324..269659637d 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.accountservice.service.session; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; @@ -17,6 +18,10 @@ import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; @@ -31,6 +36,7 @@ public final class AccountControlUiOriginalOrderFixture implements AutoCloseable private final AccountControlUiIssuanceService issuance; private final RedisClient accountClient; private final Path temporary; + private IssuedCreator originalCreator; public AccountControlUiOriginalOrderFixture( String jdbcUrl, @@ -167,9 +173,94 @@ public DraftAuthorizationFenceBinding claimOriginal(DraftCommitBinding complete) assertThat(retained.ordering().name()).isEqualTo("COMMIT_ORDER"); assertThat(retained.binding()).isEqualTo(binding.canonicalBytes()); assertThat(retained.orderedAt()).isNotNull(); + originalCreator = issued; return binding; } + /** + * Uses the original Draft creator credential unchanged, after an actual strict selected-Draft + * read. The incoming Game Design context and upstream selection/platform/legal evidence remain + * explicit test stipulations; this helper does not establish production publication authority. + */ + public AccountPublicationAuthorizationBinding authorizePublication( + AuthoredDraftPublishSelectionBinding selection, + AuthoredDraftPublishSelectionReadClient selectionClient, + String namespace) { + if (originalCreator == null) { + throw new IllegalStateException("Claim the original Draft before publication authorization"); + } + var owner = + new AccountPublicationAuthorizationService( + actors, f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + var composition = + new AccountSelectedDraftPublicationOrderService(selectionClient, owner, namespace); + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + namespace + "/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + return composition.authorize( + originalCreator.compact(), selection, originalCreator.environment()); + } finally { + context.detach(prior); + } + } + + /** Real exact retained-order read owner; no publication registration or settlement is implied. */ + public AccountPublicationAuthorizationReadService heldPublicationOwner(String namespace) { + return new AccountPublicationAuthorizationReadService( + new AccountPublicationAuthorizationRepository(f.dsl), f.manager, namespace); + } + + /** + * Verifies the complete original publication/source vector and guarded mutation denial. The + * original Draft is also pending, so writer denial does not isolate publication as its sole + * cause. + */ + public void assertPublicationSourcesHeld(AccountPublicationAuthorizationBinding order) { + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + var participation = + f.dsl.fetch( + "SELECT source_key, source_evidence FROM account_selected_publication_sources" + + " WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + order.operationId()); + assertThat(participation).hasSize(order.sources().size()); + for (int i = 0; i < order.sources().size(); i++) { + assertThat(participation.get(i).get("source_key", String.class)) + .isEqualTo(order.sources().get(i).key()); + assertThat(participation.get(i).get("source_evidence", byte[].class)) + .isEqualTo(order.sources().get(i).canonicalBytes()); + } + String originalRole = + f.dsl + .fetchSingle("SELECT role FROM accounts WHERE id = ?", f.account.getId()) + .get("role", String.class); + String changedRole = "admin".equals(originalRole) ? "player" : "admin"; + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = ? WHERE id = ?", + changedRole, + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat( + f.dsl + .fetchSingle("SELECT role FROM accounts WHERE id = ?", f.account.getId()) + .get("role", String.class)) + .isEqualTo(originalRole); + } + /** Same-package proof reuse; returns only an actual owner-issued and authenticated credential. */ IssuedCreator issueCreator() { var environment = f.terms.captureCurrentEnvironmentBoundary(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java new file mode 100644 index 0000000000..79273b345a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java @@ -0,0 +1,137 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.CompositeCallCredentials; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Strict explicit mTLS client; never registers or enables the Account producer. */ +public final class AccountSelectedPublicationOrderClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub> { + private final String namespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountSelectedPublicationOrderClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory factory, + String namespace) { + super(endpoints, requireMtls(tls), factory, AccountSelectedPublicationOrderClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account selected-publication client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account selected-publication stub unavailable"); + initialized = true; + } + + public AccountPublicationAuthorizationBinding authorize( + AccountSelectedPublicationOrderGrpcCodec.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException( + "Account selected-publication transport requires no owner transaction"); + Objects.requireNonNull(request); + if (!namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Account selected-publication namespace mismatch"); + var current = stub(); + if (closed || !initialized || current == null) + throw new IllegalStateException("Account selected-publication client unavailable"); + try { + var response = + current + .withCallCredentials( + new CompositeCallCredentials( + new GrpcServerPeerIdentityCallCredentials( + "spiffe://firemud/ns/" + namespace + "/sa/account-service"), + AccountSelectedPublicationOrderCredentials.forCall( + request.originalCreatorCredential()))) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .authorizeSelectedPublication( + AccountSelectedPublicationOrderGrpcCodec.toRequest(request)); + return AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, response); + } catch (StatusRuntimeException unavailable) { + // Remote diagnostics are not trusted to exclude credential-bearing request data. + throw Status.fromCode(unavailable.getStatus().getCode()) + .withDescription("Account selected-publication order denied or unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Account returned invalid selected-publication order evidence"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + return AccountSelectedPublicationOrderServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private static CommonGrpcClientProperties requireMtls(CommonGrpcClientProperties tls) { + if (tls == null || tls.isPlaintext()) + throw new IllegalArgumentException("Account selected-publication requires workload mTLS"); + for (String configured : + new String[] {tls.getCertChain(), tls.getPrivateKey(), tls.getCaCert()}) { + if (configured == null || configured.isBlank() || configured.trim().startsWith("classpath:")) + throw new IllegalArgumentException( + "Account selected-publication requires readable file-backed TLS material"); + Path file; + try { + file = Path.of(configured.trim()); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Account selected-publication requires file-backed TLS material"); + } + if (!Files.isRegularFile(file) || !Files.isReadable(file)) + throw new IllegalArgumentException( + "Account selected-publication requires readable file-backed TLS material"); + } + return tls; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java new file mode 100644 index 0000000000..a62175efec --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.CallCredentials; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Executor; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; + +/** + * Purpose-specific protected metadata for the original creator credential. Never log metadata: + * metadata's wire serialization necessarily contains the secret, unlike this redacted wrapper. The + * receiver must authenticate its workload peer before reading or decoding this header. + */ +public final class AccountSelectedPublicationOrderCredentials { + public static final Context.Key CONTEXT_KEY = + Context.key("account-selected-publication-original-creator"); + public static final Metadata.Key HEADER = + Metadata.Key.of( + "firemud-selected-publication-creator-bin", + new Metadata.BinaryMarshaller<>() { + @Override + public byte[] toBytes(Credential value) { + return value.bytes.clone(); + } + + // Parsing deliberately defers all credential validation until after workload + // authentication. + @Override + public Credential parseBytes(byte[] serialized) { + return new Credential(serialized); + } + }); + + private AccountSelectedPublicationOrderCredentials() {} + + public static final class Credential { + private final byte[] bytes; + + private Credential(byte[] bytes) { + this.bytes = bytes.clone(); + } + + public static Credential of(String value) { + if (value == null + || value.isEmpty() + || value.length() > AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES + || value.chars().anyMatch(c -> c <= 32 || c >= 127)) throw invalid(); + return new Credential(value.getBytes(StandardCharsets.US_ASCII)); + } + + public String value() { + if (bytes.length == 0 + || bytes.length > AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES) + throw invalid(); + for (byte value : bytes) if (value <= 32 || value >= 127) throw invalid(); + return new String(bytes, StandardCharsets.US_ASCII); + } + + @Override + public String toString() { + return "SelectedPublicationCredential[redacted]"; + } + } + + /** Only after authenticating the exact same-namespace Game Design peer. */ + public static Credential readAuthenticated(Metadata headers) { + var values = headers.getAll(HEADER); + if (values == null) throw invalid(); + var iterator = values.iterator(); + if (!iterator.hasNext()) throw invalid(); + Credential credential = iterator.next(); + if (iterator.hasNext()) throw invalid(); + credential.value(); + return credential; + } + + public static CallCredentials forCall(String value) { + var credential = Credential.of(value); + return new CallCredentials() { + @Override + public void applyRequestMetadata( + RequestInfo info, Executor executor, MetadataApplier applier) { + if (info.getSecurityLevel() != SecurityLevel.PRIVACY_AND_INTEGRITY + || !AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod() + .getFullMethodName() + .equals(info.getMethodDescriptor().getFullMethodName())) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Protected selected-publication transport required")); + return; + } + var headers = new Metadata(); + headers.put(HEADER, credential); + applier.apply(headers); + } + + @Override + public void thisUsesUnstableApi() {} + + @Override + public String toString() { + return "SelectedPublicationCallCredentials[redacted]"; + } + }; + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-publication credential metadata"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java new file mode 100644 index 0000000000..93c01ecb90 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed producer transport. Credential data never appears in responses or diagnostics. */ +public final class AccountSelectedPublicationOrderGrpcCodec { + public static final int MAX_CREDENTIAL_BYTES = 16384; + public static final int MAX_SELECTION_BYTES = 1048576; + + private AccountSelectedPublicationOrderGrpcCodec() {} + + public record Request( + int schemaVersion, + String targetNamespace, + UUID requestId, + byte[] originalSelection, + String originalCreatorCredential) { + public Request { + if (schemaVersion != 1 + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || requestId == null + || requestId.equals(new UUID(0, 0))) { + throw invalid(); + } + if (originalSelection == null + || originalSelection.length == 0 + || originalSelection.length > MAX_SELECTION_BYTES + || originalCreatorCredential == null + || originalCreatorCredential.isEmpty() + || originalCreatorCredential.length() > MAX_CREDENTIAL_BYTES + || originalCreatorCredential.chars().anyMatch(c -> c <= 32 || c >= 127)) { + throw invalid(); + } + originalSelection = originalSelection.clone(); + var selection = decodeSelection(originalSelection); + if (!Arrays.equals(originalSelection, selection.canonicalBytes())) throw invalid(); + } + + public static Request create( + String namespace, AuthoredDraftPublishSelectionBinding selection, String credential) { + return new Request(1, namespace, UUID.randomUUID(), selection.canonicalBytes(), credential); + } + + @Override + public byte[] originalSelection() { + return originalSelection.clone(); + } + + public AuthoredDraftPublishSelectionBinding selection() { + return decodeSelection(originalSelection); + } + + @Override + public String toString() { + return "AccountSelectedPublicationOrder.Request[redacted]"; + } + } + + public static AuthorizeSelectedPublicationRequest toRequest(Request request) { + Objects.requireNonNull(request); + return AuthorizeSelectedPublicationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .build(); + } + + /** Invoke only after authenticating the exact same-namespace Game Design workload. */ + public static Request fromRequest(AuthorizeSelectedPublicationRequest wire, String credential) { + try { + noUnknown(wire); + UUID id = UUID.fromString(wire.getRequestId()); + if (!id.toString().equals(wire.getRequestId())) throw invalid(); + return new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + id, + wire.getOriginalSelection().toByteArray(), + credential); + } catch (RuntimeException malformed) { + // Do not retain a parsing cause that could contain credential-bearing request data. + throw invalid(); + } + } + + public static AuthorizeSelectedPublicationResponse toResponse( + Request request, AccountPublicationAuthorizationBinding binding) { + requireSelection(request, binding); + return AuthorizeSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .setPublicationAuthorizationBinding(ByteString.copyFrom(binding.canonicalBytes())) + .build(); + } + + public static AccountPublicationAuthorizationBinding fromResponse( + Request request, AuthorizeSelectedPublicationResponse wire) { + try { + noUnknown(wire); + if (wire.getSchemaVersion() != request.schemaVersion() + || !wire.getTargetNamespace().equals(request.targetNamespace()) + || !wire.getRequestId().equals(request.requestId().toString()) + || !Arrays.equals(wire.getOriginalSelection().toByteArray(), request.originalSelection()) + || wire.getPublicationAuthorizationBinding().size() > MAX_SELECTION_BYTES) + throw invalid(); + var binding = + AccountPublicationAuthorizationBinding.fromStored( + wire.getPublicationAuthorizationBinding().toByteArray()); + requireSelection(request, binding); + return binding; + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static void requireSelection( + Request request, AccountPublicationAuthorizationBinding binding) { + if (binding == null + || !Arrays.equals( + request.originalSelection(), binding.input().selection().canonicalBytes())) + throw invalid(); + } + + private static AuthoredDraftPublishSelectionBinding decodeSelection(byte[] bytes) { + try { + return AuthoredDraftPublishSelectionBinding.fromStored( + new String(bytes, StandardCharsets.UTF_8), DraftAuthorizationFenceBinding.digest(bytes)); + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static void noUnknown(Message wire) { + if (wire == null || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-publication order transport evidence"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java new file mode 100644 index 0000000000..26d4ac5fde --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.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.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +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.GrpcServerPeerIdentityCallCredentials; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Stub configuration/codec units; mocked channels do not prove an mTLS handshake. */ +class AccountSelectedPublicationOrderClientTest { + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var tls = tls(directory); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + tls.setPlaintext(false); + for (String bad : + new String[] { + null, + "", + "classpath:credential.pem", + directory.toString(), + directory.resolve("missing.pem").toString() + }) { + tls.setCertChain(bad); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var valid = tls(directory); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), valid, factory, "Test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void configuresExactAccountPeerDeadlineAndValidatesEchoOutsideSql(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + when(factory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new AccountSelectedPublicationOrderClient(endpoints, tls(directory), factory, "test"); + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), "original.secret.credential"); + try { + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + client.init(); + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + var initialized = (io.grpc.stub.AbstractStub) field.get(client); + var credentials = initialized.getCallOptions().getCredentials(); + assertThat(credentials).isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + var peerField = + GrpcServerPeerIdentityCallCredentials.class.getDeclaredField("expectedPeerUri"); + peerField.setAccessible(true); + assertThat(peerField.get(credentials)) + .isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + var stub = + mock( + AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withCallCredentials(any())).thenReturn(stub); + field.set(client, stub); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.clearSynchronization(); + var wrongNamespace = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "other", binding.input().selection(), "original.secret.credential"); + assertThatThrownBy(() -> client.authorize(wrongNamespace)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(stub); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + when(stub.authorizeSelectedPublication(any())).thenReturn(response); + assertThat(client.authorize(request).canonicalBytes()).isEqualTo(binding.canonicalBytes()); + verify(stub).withDeadlineAfter(5, TimeUnit.SECONDS); + var wire = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest.class); + verify(stub).authorizeSelectedPublication(wire.capture()); + assertThat(wire.getValue().toString()).doesNotContain(request.originalCreatorCredential()); + var perCall = org.mockito.ArgumentCaptor.forClass(io.grpc.CallCredentials.class); + verify(stub).withCallCredentials(perCall.capture()); + assertThat(perCall.getValue()).isInstanceOf(io.grpc.CompositeCallCredentials.class); + when(stub.authorizeSelectedPublication(any())) + .thenReturn(response.toBuilder().setTargetNamespace("other").build()); + assertThatThrownBy(() -> client.authorize(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageNotContaining(request.originalCreatorCredential()); + when(stub.authorizeSelectedPublication(any())) + .thenThrow( + io.grpc.Status.UNAVAILABLE + .withDescription(request.originalCreatorCredential()) + .asRuntimeException()); + assertThatThrownBy(() -> client.authorize(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageNotContaining(request.originalCreatorCredential()) + .hasNoCause(); + } finally { + client.close(); + } + assertThatThrownBy(client::init).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private-key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "ca").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java new file mode 100644 index 0000000000..a003a624f5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.CallCredentials; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import java.nio.charset.StandardCharsets; +import java.util.List; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationOrderCredentialsTest { + private static final String SECRET = "original.secret.credential"; + private static final Metadata.Key RAW = + Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + Metadata.BINARY_BYTE_MARSHALLER); + + @Test + void carrierAndWrapperAreRedactedAndApplyOnlyToProtectedExactMethod() { + var credentials = AccountSelectedPublicationOrderCredentials.forCall(SECRET); + assertThat(credentials.toString()).doesNotContain(SECRET); + assertThat(AccountSelectedPublicationOrderCredentials.Credential.of(SECRET).toString()) + .doesNotContain(SECRET); + var info = mock(CallCredentials.RequestInfo.class); + when(info.getSecurityLevel()).thenReturn(SecurityLevel.PRIVACY_AND_INTEGRITY); + org.mockito.Mockito.doReturn( + AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod()) + .when(info) + .getMethodDescriptor(); + var applier = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, applier); + var captured = org.mockito.ArgumentCaptor.forClass(Metadata.class); + verify(applier).apply(captured.capture()); + assertThat( + AccountSelectedPublicationOrderCredentials.readAuthenticated(captured.getValue()) + .value()) + .isEqualTo(SECRET); + for (var level : List.of(SecurityLevel.NONE, SecurityLevel.INTEGRITY)) { + when(info.getSecurityLevel()).thenReturn(level); + var denied = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, denied); + verify(denied) + .fail( + org.mockito.ArgumentMatchers.argThat( + status -> status.getCode() == io.grpc.Status.Code.UNAUTHENTICATED)); + } + when(info.getSecurityLevel()).thenReturn(SecurityLevel.PRIVACY_AND_INTEGRITY); + org.mockito.Mockito.doReturn( + AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod() + .toBuilder() + .setFullMethodName("different/Method") + .build()) + .when(info) + .getMethodDescriptor(); + var denied = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, denied); + verify(denied).fail(org.mockito.ArgumentMatchers.any()); + } + + @Test + void + authenticatedReadRejectsMissingDuplicateOversizedAndMalformedHeadersWithoutSecretDiagnostics() { + var missing = new Metadata(); + var duplicate = new Metadata(); + duplicate.put(RAW, SECRET.getBytes(StandardCharsets.US_ASCII)); + duplicate.put(RAW, SECRET.getBytes(StandardCharsets.US_ASCII)); + for (var headers : + List.of( + missing, + duplicate, + raw(new byte[0]), + raw(new byte[] {(byte) 128}), + raw((SECRET + "\n").getBytes(StandardCharsets.US_ASCII)), + raw(new byte[16385]))) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderCredentials.readAuthenticated(headers)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(SECRET) + .hasNoCause(); + } + var exact = + AccountSelectedPublicationOrderCredentials.readAuthenticated( + raw(SECRET.getBytes(StandardCharsets.US_ASCII))); + assertThat(exact.value()).isEqualTo(SECRET); + assertThat(exact.toString()).doesNotContain(SECRET); + } + + private static Metadata raw(byte[] bytes) { + var headers = new Metadata(); + headers.put(RAW, bytes); + return headers; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java new file mode 100644 index 0000000000..9b39340b8a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationOrderGrpcCodecTest { + private static final String CREDENTIAL = "original.secret.credential"; + + @Test + void preservesOriginalCredentialAndCanonicalSelectionWithoutEchoingSecret() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + var decoded = AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, CREDENTIAL); + assertThat(decoded.originalCreatorCredential()).isEqualTo(CREDENTIAL); + assertThat(decoded.originalSelection()).isEqualTo(request.originalSelection()); + assertThat(decoded.requestId()).isEqualTo(request.requestId()); + assertThat(decoded.toString()).doesNotContain(CREDENTIAL); + assertThat(wire.toString()).doesNotContain(CREDENTIAL); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + assertThat(response.toString()).doesNotContain(CREDENTIAL); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + var fresh = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse( + fresh, AccountSelectedPublicationOrderGrpcCodec.toResponse(fresh, binding)) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + } + + @Test + void rejectsUnknownNoncanonicalOversizedAndMissingRequestFieldsWithoutSecretDiagnostics() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + for (AuthorizeSelectedPublicationRequest invalid : + List.of( + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setRequestId("1-1-1-1-1").build(), + wire.toBuilder().setRequestId(new UUID(0, 0).toString()).build(), + wire.toBuilder().setRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA").build(), + wire.toBuilder().setUnknownFields(unknown()).build(), + wire.toBuilder().clearOriginalSelection().build(), + wire.toBuilder().setOriginalSelection(ByteString.copyFrom(new byte[1048577])).build(), + wire.toBuilder() + .setOriginalSelection( + wire.getOriginalSelection().concat(ByteString.copyFromUtf8(" "))) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderGrpcCodec.fromRequest(invalid, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + for (String invalid : List.of("", "x".repeat(16385), CREDENTIAL + "\n")) { + assertThatThrownBy(() -> AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, invalid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + } + + @Test + void rejectsChangedResponseEchoBindingAndUnknownFields() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + for (var invalid : + List.of( + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder().clearOriginalSelection().build(), + response.toBuilder().setUnknownFields(unknown()).build(), + response.toBuilder().clearPublicationAuthorizationBinding().build(), + response.toBuilder() + .setPublicationAuthorizationBinding(ByteString.copyFrom(new byte[] {1})) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java new file mode 100644 index 0000000000..8c7c85cf1d --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java @@ -0,0 +1,283 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.dto.VersionDto; +import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered composition for authenticated selected-Draft admission and full-version publish. + * + *

Existing local operation bytes identify an already admitted attempt for exact reconciliation; + * they are not current Account authorization. A new operation always enters the authenticated + * Account and World admission path before the existing-version finalizer is called. + */ +public final class SelectedDraftPublicationCommandService { + private final SelectedDraftPublicationAdmissionService admission; + private final DurableStateReader durableStateReader; + private final VersionPublishCommandServiceImpl finalizer; + + public SelectedDraftPublicationCommandService( + DSLContext dsl, + PlatformTransactionManager transactionManager, + AccountPublicationAuthorizationReadClient accountClient, + WorldPublishedStartLocationClient worldClient, + String workloadNamespace, + VersionPublishCommandServiceImpl finalizer) { + this( + new SelectedDraftPublicationAdmissionService( + dsl, transactionManager, accountClient, worldClient, workloadNamespace), + new DatabaseDurableStateReader(dsl), + finalizer); + } + + SelectedDraftPublicationCommandService( + SelectedDraftPublicationAdmissionService admission, + DurableStateReader durableStateReader, + VersionPublishCommandServiceImpl finalizer) { + this.admission = Objects.requireNonNull(admission, "admission"); + this.durableStateReader = Objects.requireNonNull(durableStateReader, "durableStateReader"); + this.finalizer = Objects.requireNonNull(finalizer, "finalizer"); + } + + /** + * Publishes the exact selected existing Draft. The World request is an identity supplied for + * first admission and must match the embedded request on exact retries. + */ + public VersionDto publishSelectedDraftFullVersion( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding, + WorldPublishedStartLocationEvidence.Request worldRequest) { + requireNoAmbientTransaction(); + Objects.requireNonNull(intent, "intent"); + Objects.requireNonNull(accountBinding, "accountBinding"); + Objects.requireNonNull(worldRequest, "worldRequest"); + requireIntentMatchesAccount(intent, accountBinding); + + DurableState state = durableStateReader.read(intent, accountBinding); + boolean selectionExists = state.selection().isPresent(); + boolean operationExists = state.operation().isPresent(); + if (!selectionExists) { + if (operationExists) { + throw new IllegalStateException( + "SELECTED_PUBLICATION_LOCAL_IDENTITY_INCOMPLETE: operation exists without its durable selection"); + } + throw new IllegalStateException( + "SELECTED_PUBLICATION_SELECTION_UNAVAILABLE: exact immutable selection must precede Account authorization"); + } + + AuthoredDraftPublishSelection selection = state.selection().orElseThrow(); + if (!operationExists) { + // The immutable selection precedes Account authorization on the first publication entry. + requireExactSelection(intent, accountBinding, worldRequest, selection); + SelectedDraftPublicationOwner.Reservation reservation = + admission.admitAndReserve(intent, accountBinding, worldRequest); + Objects.requireNonNull(reservation, "selected Draft admission returned no reservation"); + if (!Arrays.equals(selection.canonicalBytes(), reservation.selection().canonicalBytes())) { + throw new IllegalStateException( + "SELECTED_PUBLICATION_RESERVATION_SELECTION_CONFLICT: admitted selection differs from the immutable preselection"); + } + requireExactAdmission(intent, accountBinding, worldRequest, reservation); + return finalizeSelectedDraft(intent, accountBinding, worldRequest, selection); + } + GameDesignPublicationOperationRepository.Readback operationReadback = + state.operation().orElseThrow(); + requireExactRetry(intent, accountBinding, worldRequest, selection, operationReadback); + return finalizeSelectedDraft(intent, accountBinding, worldRequest, selection); + } + + private VersionDto finalizeSelectedDraft( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding, + WorldPublishedStartLocationEvidence.Request worldRequest, + AuthoredDraftPublishSelection selection) { + var target = selection.target(); + String workflowId = workflowId(accountBinding); + if (!workflowId.equals(worldRequest.publishWorkflowId())) { + throw new IllegalArgumentException( + "Selected Draft publication workflow differs from the original World request"); + } + return finalizer.publishSelectedDraftFullVersion( + target.gameDesignVersionTenantKey(), + target.gameDesignVersionRowId(), + intent.notes(), + intent.publishRequestId(), + workflowId); + } + + private static void requireExactRetry( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding, + WorldPublishedStartLocationEvidence.Request worldRequest, + AuthoredDraftPublishSelection selection, + GameDesignPublicationOperationRepository.Readback operationReadback) { + requireExactSelection(intent, accountBinding, worldRequest, selection); + GameDesignPublicationOperation operation = operationReadback.operation(); + if (!Arrays.equals(accountBinding.canonicalBytes(), operation.account().canonicalBytes()) + || !worldRequest.equals(operation.world().request()) + || !operation.workflowId().equals(workflowId(accountBinding)) + || !operation.tenantKey().equals(selection.target().gameDesignVersionTenantKey()) + || operation.versionId() != selection.target().gameDesignVersionRowId() + || !operation.selectionDigest().equals(selection.digest())) { + throw new IllegalStateException( + "SELECTED_PUBLICATION_LOCAL_IDENTITY_CONFLICT: retry differs from the original intent, " + + "Account binding, World request, selection, or release identity"); + } + if (!"PENDING".equals(operationReadback.outcome()) + && !"PUBLISHED".equals(operationReadback.outcome()) + && !"NO_PUBLICATION".equals(operationReadback.outcome())) { + throw new IllegalStateException( + "SELECTED_PUBLICATION_LOCAL_OUTCOME_UNAVAILABLE: original publication outcome is " + + "not reconcilable"); + } + } + + private static void requireExactAdmission( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding, + WorldPublishedStartLocationEvidence.Request worldRequest, + SelectedDraftPublicationOwner.Reservation reservation) { + GameDesignPublicationOperation operation = reservation.operation(); + requireExactSelection(intent, accountBinding, worldRequest, reservation.selection()); + if (!Arrays.equals(accountBinding.canonicalBytes(), operation.account().canonicalBytes()) + || !worldRequest.equals(operation.world().request()) + || !operation.workflowId().equals(workflowId(accountBinding)) + || !operation.selectionDigest().equals(reservation.selection().digest()) + || operation.versionId() != reservation.selection().target().gameDesignVersionRowId() + || !operation + .tenantKey() + .equals(reservation.selection().target().gameDesignVersionTenantKey())) { + throw new IllegalStateException( + "SELECTED_PUBLICATION_ADMISSION_READBACK_CONFLICT: authenticated admission differs from its exact inputs or selected release identity"); + } + } + + private static void requireExactSelection( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding, + WorldPublishedStartLocationEvidence.Request worldRequest, + AuthoredDraftPublishSelection selection) { + var accountSelection = accountBinding.input().selection(); + if (!intent.equals(selection.intent()) + || !Arrays.equals(selection.canonicalBytes(), accountSelection.canonicalBytes()) + || !selection.digest().equals(accountSelection.digest()) + || !selection.target().canonicalTenantId().equals(worldRequest.canonicalTenantId()) + || !selection.target().canonicalVersionId().equals(worldRequest.canonicalVersionId()) + || !intent.publishRequestId().equals(worldRequest.publicationRequestId()) + || !intent + .expectedVersionStateEpoch() + .equals(Long.toString(worldRequest.versionStateEpoch())) + || !selection.digest().equals("sha256:" + worldRequest.requestDigest()) + || !intent.selectedCommitId().toString().equals(worldRequest.appliedCommitId()) + || !workflowId(accountBinding).equals(worldRequest.publishWorkflowId())) { + throw new IllegalStateException( + "SELECTED_PUBLICATION_SELECTION_IDENTITY_CONFLICT: selection differs from the " + + "complete original intent or owner requests"); + } + } + + private static void requireIntentMatchesAccount( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding) { + var accountIntent = accountBinding.input().selection().intent(); + var suppliedIntent = + new AuthoredDraftPublishSelection.PublishIntent( + accountIntent.canonicalTenantId(), + accountIntent.canonicalVersionId(), + accountIntent.publishRequestId(), + accountIntent.expectedVersionStateEpoch(), + accountIntent.notes(), + accountIntent.selectedCommitRequestId(), + accountIntent.selectedCommitId(), + accountIntent.selectedCommitDigest()); + if (!intent.equals(suppliedIntent)) { + throw new IllegalArgumentException( + "Account binding must retain the complete supplied original selected Draft intent"); + } + } + + private static String workflowId(AccountPublicationAuthorizationBinding accountBinding) { + var selection = accountBinding.input().selection(); + return PublicationDigestRequestBinding.full( + selection.intent().canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + selection.intent().publishRequestId()) + .derivedWorkflowIdentity(); + } + + private static String workflowId(AuthoredDraftPublishSelection selection) { + return PublicationDigestRequestBinding.full( + selection.target().canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + selection.intent().publishRequestId()) + .derivedWorkflowIdentity(); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Selected Draft publication composition requires no ambient SQL transaction"); + } + } + + @FunctionalInterface + interface DurableStateReader { + DurableState read( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding); + } + + record DurableState( + Optional selection, + Optional operation) { + DurableState { + Objects.requireNonNull(selection, "selection"); + Objects.requireNonNull(operation, "operation"); + } + + static DurableState absent() { + return new DurableState(Optional.empty(), Optional.empty()); + } + } + + private static final class DatabaseDurableStateReader implements DurableStateReader { + private final AuthoredDraftPublishSelectionRepository selections; + private final GameDesignPublicationOperationRepository operations; + + private DatabaseDurableStateReader(DSLContext dsl) { + Objects.requireNonNull(dsl, "dsl"); + selections = + new AuthoredDraftPublishSelectionRepository( + dsl, new DraftCommitCoordinatorRepository(dsl)); + operations = new GameDesignPublicationOperationRepository(dsl); + } + + @Override + public DurableState read( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding) { + Optional selection = + selections + .readByPublishRequest(intent.canonicalTenantId(), intent.publishRequestId()) + .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection); + String retainedWorkflow = + selection + .map(SelectedDraftPublicationCommandService::workflowId) + .orElseGet(() -> workflowId(accountBinding)); + return new DurableState(selection, operations.read(retainedWorkflow)); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandServiceTest.java new file mode 100644 index 0000000000..48ca132e96 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandServiceTest.java @@ -0,0 +1,321 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; +import net.firedevops.firemud.gamedesign.dto.VersionDto; +import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class SelectedDraftPublicationCommandServiceTest { + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void preselectedDraftAdmissionCompletesBeforeSelectedExistingVersionFinalizer() throws Exception { + var fixture = fixture(); + var admission = mock(SelectedDraftPublicationAdmissionService.class); + var reader = mock(SelectedDraftPublicationCommandService.DurableStateReader.class); + var finalizer = mock(VersionPublishCommandServiceImpl.class); + var reservation = mock(SelectedDraftPublicationOwner.Reservation.class); + var result = mock(VersionDto.class); + when(reader.read(fixture.intent(), fixture.operation().account())) + .thenReturn(selectionOnly(fixture)); + when(admission.admitAndReserve( + fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + .thenReturn(reservation); + when(reservation.selection()).thenReturn(fixture.selection()); + when(reservation.operation()).thenReturn(fixture.operation()); + when(finalizer.publishSelectedDraftFullVersion( + fixture.selection().target().gameDesignVersionTenantKey(), + fixture.selection().target().gameDesignVersionRowId(), + fixture.intent().notes(), + fixture.intent().publishRequestId(), + fixture.operation().workflowId())) + .thenReturn(result); + var service = service(admission, reader, finalizer); + + var actual = + service.publishSelectedDraftFullVersion( + fixture.intent(), fixture.operation().account(), fixture.worldRequest()); + + org.assertj.core.api.Assertions.assertThat(actual).isSameAs(result); + var publicationOrder = inOrder(admission, finalizer); + publicationOrder + .verify(admission) + .admitAndReserve(fixture.intent(), fixture.operation().account(), fixture.worldRequest()); + publicationOrder + .verify(finalizer) + .publishSelectedDraftFullVersion( + fixture.selection().target().gameDesignVersionTenantKey(), + fixture.selection().target().gameDesignVersionRowId(), + fixture.intent().notes(), + fixture.intent().publishRequestId(), + fixture.operation().workflowId()); + verify(finalizer, never()) + .publishFullVersion(anyString(), anyString(), anyString(), anyString()); + } + + @Test + void exactSettledRetryUsesStoredIdentityWithoutFreshHeldReadOrReservation() throws Exception { + var fixture = fixture(); + var admission = mock(SelectedDraftPublicationAdmissionService.class); + var reader = mock(SelectedDraftPublicationCommandService.DurableStateReader.class); + var finalizer = mock(VersionPublishCommandServiceImpl.class); + var result = mock(VersionDto.class); + when(reader.read(fixture.intent(), fixture.operation().account())) + .thenReturn(state(fixture, "PUBLISHED")); + when(finalizer.publishSelectedDraftFullVersion( + fixture.selection().target().gameDesignVersionTenantKey(), + fixture.selection().target().gameDesignVersionRowId(), + fixture.intent().notes(), + fixture.intent().publishRequestId(), + fixture.operation().workflowId())) + .thenReturn(result); + var service = service(admission, reader, finalizer); + + var actual = + service.publishSelectedDraftFullVersion( + fixture.intent(), fixture.operation().account(), fixture.worldRequest()); + + org.assertj.core.api.Assertions.assertThat(actual).isSameAs(result); + verify(admission, never()).admitAndReserve(any(), any(), any()); + verify(finalizer) + .publishSelectedDraftFullVersion( + fixture.selection().target().gameDesignVersionTenantKey(), + fixture.selection().target().gameDesignVersionRowId(), + fixture.intent().notes(), + fixture.intent().publishRequestId(), + fixture.operation().workflowId()); + verify(finalizer, never()) + .publishFullVersion(anyString(), anyString(), anyString(), anyString()); + } + + @Test + void admissionDenialAndPartialLocalIdentityNeverReachFinalizer() throws Exception { + var fixture = fixture(); + var denial = new IllegalStateException("Account publication authorization denied"); + var admission = mock(SelectedDraftPublicationAdmissionService.class); + var reader = mock(SelectedDraftPublicationCommandService.DurableStateReader.class); + var finalizer = mock(VersionPublishCommandServiceImpl.class); + when(reader.read(fixture.intent(), fixture.operation().account())) + .thenReturn(selectionOnly(fixture)); + when(admission.admitAndReserve( + fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + .thenThrow(denial); + + assertThatThrownBy( + () -> + service(admission, reader, finalizer) + .publishSelectedDraftFullVersion( + fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + .isSameAs(denial); + verifyNoInteractions(finalizer); + + var partialAdmission = mock(SelectedDraftPublicationAdmissionService.class); + var partialReader = mock(SelectedDraftPublicationCommandService.DurableStateReader.class); + var partialFinalizer = mock(VersionPublishCommandServiceImpl.class); + when(partialReader.read(fixture.intent(), fixture.operation().account())) + .thenReturn( + new SelectedDraftPublicationCommandService.DurableState( + Optional.empty(), + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1})))); + + assertThatThrownBy( + () -> + service(partialAdmission, partialReader, partialFinalizer) + .publishSelectedDraftFullVersion( + fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("LOCAL_IDENTITY_INCOMPLETE"); + verifyNoInteractions(partialAdmission, partialFinalizer); + } + + @Test + void missingSelectionFailsClosedBeforeAccountOrWorldAdmission() throws Exception { + var fixture = fixture(); + var admission = mock(SelectedDraftPublicationAdmissionService.class); + var reader = mock(SelectedDraftPublicationCommandService.DurableStateReader.class); + var finalizer = mock(VersionPublishCommandServiceImpl.class); + when(reader.read(fixture.intent(), fixture.operation().account())) + .thenReturn(SelectedDraftPublicationCommandService.DurableState.absent()); + + assertThatThrownBy( + () -> + service(admission, reader, finalizer) + .publishSelectedDraftFullVersion( + fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SELECTION_UNAVAILABLE"); + + verifyNoInteractions(admission, finalizer); + } + + @Test + void exactRetryRejectsChangedIntentAccountBindingOrWorldRequest() throws Exception { + var fixture = fixture(); + var alteredIntent = withNotes(fixture.intent(), "substituted notes"); + assertRejectedRetry( + fixture, alteredIntent, fixture.operation().account(), fixture.worldRequest()); + + var changedAccount = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + fixture.operation().account().fenceId(), + fixture.operation().account().input(), + fixture.operation().account().sources()); + assertRejectedRetry(fixture, fixture.intent(), changedAccount, fixture.worldRequest()); + + var changedWorldRequest = + withPublicationRequestId(fixture.worldRequest(), "substituted-publication-request"); + assertRejectedRetry( + fixture, fixture.intent(), fixture.operation().account(), changedWorldRequest); + } + + @Test + void compositionRejectsAmbientTransactionBeforeLocalReadsAdmissionOrFinalizer() throws Exception { + var fixture = fixture(); + var admission = mock(SelectedDraftPublicationAdmissionService.class); + var reader = mock(SelectedDraftPublicationCommandService.DurableStateReader.class); + var finalizer = mock(VersionPublishCommandServiceImpl.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + service(admission, reader, finalizer) + .publishSelectedDraftFullVersion( + fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL transaction"); + + verifyNoInteractions(reader, admission, finalizer); + } + + private static void assertRejectedRetry( + Fixture fixture, + PublishIntent intent, + AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence.Request worldRequest) { + var admission = mock(SelectedDraftPublicationAdmissionService.class); + var reader = mock(SelectedDraftPublicationCommandService.DurableStateReader.class); + var finalizer = mock(VersionPublishCommandServiceImpl.class); + when(reader.read(any(), any())).thenReturn(state(fixture, "PENDING")); + + assertThatThrownBy( + () -> + service(admission, reader, finalizer) + .publishSelectedDraftFullVersion(intent, account, worldRequest)) + .isInstanceOf(RuntimeException.class); + + verifyNoInteractions(admission, finalizer); + } + + private static SelectedDraftPublicationCommandService service( + SelectedDraftPublicationAdmissionService admission, + SelectedDraftPublicationCommandService.DurableStateReader reader, + VersionPublishCommandServiceImpl finalizer) { + return new SelectedDraftPublicationCommandService(admission, reader, finalizer); + } + + private static SelectedDraftPublicationCommandService.DurableState state( + Fixture fixture, String outcome) { + return new SelectedDraftPublicationCommandService.DurableState( + Optional.of(fixture.selection()), + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), outcome, new byte[] {1}))); + } + + private static SelectedDraftPublicationCommandService.DurableState selectionOnly( + Fixture fixture) { + return new SelectedDraftPublicationCommandService.DurableState( + Optional.of(fixture.selection()), Optional.empty()); + } + + private static Fixture fixture() throws Exception { + var target = + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + var operation = IsolatedPublicationOperationFixtures.fresh(target); + var binding = operation.account().input().selection(); + var bindingIntent = binding.intent(); + var intent = + new PublishIntent( + bindingIntent.canonicalTenantId(), + bindingIntent.canonicalVersionId(), + bindingIntent.publishRequestId(), + bindingIntent.expectedVersionStateEpoch(), + bindingIntent.notes(), + bindingIntent.selectedCommitRequestId(), + bindingIntent.selectedCommitId(), + bindingIntent.selectedCommitDigest()); + var selection = + AuthoredDraftPublishSelection.fromStored(binding.canonicalJson(), binding.digest()); + return new Fixture(operation, selection, intent, operation.world().request()); + } + + private static PublishIntent withNotes(PublishIntent intent, String notes) { + return new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + notes, + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + } + + private static WorldPublishedStartLocationEvidence.Request withPublicationRequestId( + WorldPublishedStartLocationEvidence.Request request, String publicationRequestId) { + return new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + publicationRequestId, + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()); + } + + private record Fixture( + GameDesignPublicationOperation operation, + AuthoredDraftPublishSelection selection, + PublishIntent intent, + WorldPublishedStartLocationEvidence.Request worldRequest) {} +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 705a508302..83941bda5d 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -6,22 +6,30 @@ import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.JsonFormat; +import io.grpc.BindableService; +import io.grpc.Context; import io.grpc.Server; import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.stub.StreamObserver; import java.net.InetSocketAddress; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; +import net.firedevops.firemud.accountservice.service.session.AccountPublicationAuthorizationReadGrpcService; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; @@ -29,19 +37,31 @@ import net.firedevops.firemud.common.authoring.DraftCommitOrderReadClient; import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedDraftPublicationReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateRequest; +import net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; @@ -54,6 +74,7 @@ import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; import net.firedevops.firemud.worldmanagement.dto.WorldDesignMutationRequestDto; import net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; @@ -84,9 +105,10 @@ import tools.jackson.databind.ObjectMapper; /** - * Real Account COMMIT_ORDER -> real World APPLIED -> authenticated exact immutable selector read. - * Platform/custody, legal source, and upstream Game Design source/version/selection inputs are - * test-only stipulations. No release, settlement, admission, deadline-bearing write or activation. + * Real Account COMMIT_ORDER -> real World APPLIED -> real distinct Account publication order and + * authenticated HELD read -> World selected-publication freeze. Game Design selected-Draft/current + * DRAFT responses and Account platform/custody/legal inputs remain explicit test stipulations. No + * release, settlement, admission, deadline-bearing write or activation. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -219,11 +241,13 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() assertThat(stateAfterMissingApplicationDenial.publicationAttemptRows()).isEmpty(); var pki = new TestPki(temporary.resolve("pki")); var accountServer = - serve( + serveAll( + pki.accountServer, + pki, new AccountDraftCommitOrderReadGrpcService( account.heldOrderOwner(NAMESPACE), NAMESPACE), - pki.accountServer, - pki); + new AccountPublicationAuthorizationReadGrpcService( + account.heldPublicationOwner(NAMESPACE), NAMESPACE)); try { var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("localhost:" + accountServer.getPort()); @@ -251,175 +275,230 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() assertThat(writer.apply(application).canonicalBytes()) .isEqualTo(applied.canonicalBytes()); assertLegacyNumericWritesCannotChangeCanonicalFreshGraph(world, plan); - // Both the immutable selection and distinct Account publication order are fixture-only - // stipulations. They are not proof that Account created or currently holds that order. String publicationRequest = "selector-" + UUID.randomUUID(); var publicationSelection = publicationSelection(plan, publicationRequest, 1L); - var stipulatedPublicationOrder = stipulatedPublicationOrder(publicationSelection); var freezeEvidence = publicationFreezeEvidence(plan, publicationSelection); var publicationAuthorizationRepository = publicationAuthorizationRepository(); - var stateBeforeFirstQualifiedCapture = ownerSnapshot(world, plan); - assertThat(stateBeforeFirstQualifiedCapture.publicationOwnerRows()).hasSize(1); - String openPublicationOwnerRow = - stateBeforeFirstQualifiedCapture.publicationOwnerRows().get(0); - assertThat(mapper.readTree(openPublicationOwnerRow).path("owner_freeze_phase").asText()) - .isEqualTo("OPEN"); - assertThat(stateBeforeFirstQualifiedCapture.publicationAttemptRows()).isEmpty(); - assertThat(stateBeforeFirstQualifiedCapture.publicationAuthorizationRows()).isEmpty(); - var forcedRollback = - new IllegalStateException("forced first-freeze qualification rollback"); - assertThatThrownBy( - () -> - ownerTransaction() - .execute( - status -> { - var candidate = - fence.claimFreeze( - freezeEvidence, - () -> checkpointRepository().capture(freezeEvidence, plan)); - assertThat( - publicationAuthorizationRepository - .retainOrRequireExact( - candidate, stipulatedPublicationOrder, true) - .canonicalBytes()) - .containsExactly(stipulatedPublicationOrder.canonicalBytes()); - throw forcedRollback; - })) - .isSameAs(forcedRollback); - var stateAfterFirstQualifiedCaptureRollback = ownerSnapshot(world, plan); - assertThat(stateAfterFirstQualifiedCaptureRollback) - .isEqualTo(stateBeforeFirstQualifiedCapture); - assertThat(stateAfterFirstQualifiedCaptureRollback.publicationOwnerRows()) - .containsExactly(openPublicationOwnerRow); - assertThat(stateAfterFirstQualifiedCaptureRollback.publicationAttemptRows()).isEmpty(); - assertThat(stateAfterFirstQualifiedCaptureRollback.publicationAuthorizationRows()) - .isEmpty(); - var frozen = capture(plan, freezeEvidence, stipulatedPublicationOrder); - assertThat(frozen.request().freeze().appliedCommitId()) - .isEqualTo(applied.application().operation().commitId().toString()); - var retryEvidence = freezeEvidence; - var stateBeforeExactRetry = ownerSnapshot(world, plan); - var checkpointCallbackInvocations = new AtomicInteger(); - var exactRetry = - Objects.requireNonNull( - ownerTransaction() - .execute( - status -> { - WorldDesignPublicationFenceEvidence.FrozenAttempt retry = - fence.claimFreeze( - retryEvidence, - () -> { - checkpointCallbackInvocations.incrementAndGet(); - return new WorldDesignPublicationFenceEvidence.Checkpoint( - "recapture-must-not-run", "b".repeat(64), 3); - }); - assertThat( - publicationAuthorizationRepository - .retainOrRequireExact( - retry, stipulatedPublicationOrder, false) - .canonicalBytes()) - .containsExactly(stipulatedPublicationOrder.canonicalBytes()); - return retry; - })); - assertThat(exactRetry.request()).isEqualTo(retryEvidence); - assertThat(exactRetry.publicationFence()) - .isEqualTo(frozen.request().freeze().publicationFence()); - assertThat(exactRetry.checkpoint()) - .isEqualTo( - new WorldDesignPublicationFenceEvidence.Checkpoint( - frozen.request().freeze().appliedCommitId(), - frozen.request().freeze().contentDigest(), - frozen.request().freeze().digestSchemaVersion())); - assertThat(checkpointCallbackInvocations.get()).isZero(); - assertThat(ownerSnapshot(world, plan)).isEqualTo(stateBeforeExactRetry); - assertThat( - publicationAuthorizationRepository - .readCommitted(exactRetry) - .orElseThrow() - .canonicalBytes()) - .containsExactly(stipulatedPublicationOrder.canonicalBytes()); - var changedOperation = - new AccountPublicationAuthorizationBinding( - UUID.randomUUID(), - stipulatedPublicationOrder.fenceId(), - stipulatedPublicationOrder.input(), - stipulatedPublicationOrder.sources()); - assertThatThrownBy( - () -> - ownerTransaction() - .execute( - status -> - publicationAuthorizationRepository.retainOrRequireExact( - exactRetry, changedOperation, false))) - .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) - .hasMessageContaining("changed"); - var changedFence = - new AccountPublicationAuthorizationBinding( - stipulatedPublicationOrder.operationId(), - UUID.randomUUID(), - stipulatedPublicationOrder.input(), - stipulatedPublicationOrder.sources()); - assertThatThrownBy( - () -> - ownerTransaction() - .execute( - status -> - publicationAuthorizationRepository.retainOrRequireExact( - exactRetry, changedFence, false))) - .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) - .hasMessageContaining("changed"); - assertThat(ownerSnapshot(world, plan)).isEqualTo(stateBeforeExactRetry); - var selectors = - new WorldPublishedStartLocationRepository( - dsl, frozenRepository(), appliedRepository()); - var retained = selectors.readCommitted(frozen.request().freeze()).orElseThrow(); - var request = selectorRequest(frozen.request().freeze()); - var worldServer = - serve( - new WorldPublishedStartLocationReadGrpcService(selectors, NAMESPACE), - pki.worldServer, - pki); - try { - endpoints.setWorldManagementService("localhost:" + worldServer.getPort()); - try (var client = - new WorldPublishedStartLocationClient( - endpoints, - pki.gameDesignClient.properties(pki.ca), - new GrpcChannelFactory(), - NAMESPACE)) { - client.init(); - var evidence = client.read(request); - assertThat(evidence.request()).isEqualTo(request); - assertThat(evidence.originalAccountBindingBytes()) - .isEqualTo(original.canonicalBytes()); - assertThat(evidence.appliedResultBytes()).isEqualTo(applied.canonicalBytes()); - assertThat(evidence.selectorReceiptBytes()) - .isEqualTo(retained.selectorReceipt().canonicalBytes()); - assertThat(client.read(request).canonicalBytes()) - .isEqualTo(evidence.canonicalBytes()); - } - // Trusted CA alone is not authority: the World workload cannot read the GD-only - // selector. - try (var wrong = - new WorldPublishedStartLocationClient( - endpoints, - pki.worldClient.properties(pki.ca), - new GrpcChannelFactory(), - NAMESPACE)) { - wrong.init(); - assertThatThrownBy(() -> wrong.read(request)) - .isInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - error -> - assertThat(io.grpc.Status.fromThrowable(error).getCode()) - .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + var selectedReadCalls = new AtomicInteger(); + var versionStateReadCalls = new AtomicInteger(); + var gameDesignServer = + serveAll( + pki.gameDesignServer, + pki, + new SelectedDraftReadFixture(publicationSelection, selectedReadCalls), + new CurrentVersionStateReadFixture( + world.intake().source(), + world.version().canonicalVersionId(), + world.owner().gameDesignVersionId(), + 1L, + versionStateReadCalls)); + try (var selectionRead = + new AuthoredDraftPublishSelectionReadClient( + endpoints, + pki.worldClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE); + var versionStateRead = + new AuthoredWorldVersionStateClient( + endpoints, + pki.worldClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE); + var accountRead = + new AccountPublicationAuthorizationReadClient( + endpoints, + pki.worldClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + endpoints.setGameDesignService("localhost:" + gameDesignServer.getPort()); + selectionRead.init(); + versionStateRead.init(); + accountRead.init(); + var publicationOrder = + account.authorizePublication(publicationSelection, selectionRead, NAMESPACE); + assertThat(publicationOrder.input().actorAccountId()) + .isEqualTo(original.actorAccountId()); + assertThat(publicationOrder.input().selection()).isEqualTo(publicationSelection); + assertThat(publicationOrder.operationId()).isNotEqualTo(original.operationId()); + assertThat(publicationOrder.fenceId()).isNotEqualTo(original.fenceId()); + assertThat(publicationOrder.canonicalBytes()).isNotEmpty(); + // The original Draft COMMIT_ORDER also remains pending; this source-protection check + // does not isolate publication as the sole cause of writer denial. + account.assertPublicationSourcesHeld(publicationOrder); + var selectedFreezeService = + selectedPublicationFreezeService(selectionRead, versionStateRead, accountRead); + + var stateBeforeMissingHeldDenial = ownerSnapshot(world, plan); + assertThat(stateBeforeMissingHeldDenial.publicationOwnerRows()).hasSize(1); + assertThat(stateBeforeMissingHeldDenial.publicationAttemptRows()).isEmpty(); + assertThat(stateBeforeMissingHeldDenial.publicationAuthorizationRows()).isEmpty(); + var missingHeldOrder = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + publicationOrder.fenceId(), + publicationOrder.input(), + publicationOrder.sources()); + assertThatThrownBy( + () -> + withGameDesignCaller( + () -> + selectedFreezeService.freeze( + freezeEvidence, plan, missingHeldOrder))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(ownerSnapshot(world, plan)).isEqualTo(stateBeforeMissingHeldDenial); + + var stateBeforeFirstQualifiedCapture = ownerSnapshot(world, plan); + assertThat(stateBeforeFirstQualifiedCapture.publicationOwnerRows()).hasSize(1); + String openPublicationOwnerRow = + stateBeforeFirstQualifiedCapture.publicationOwnerRows().get(0); + assertThat(mapper.readTree(openPublicationOwnerRow).path("owner_freeze_phase").asText()) + .isEqualTo("OPEN"); + assertThat(stateBeforeFirstQualifiedCapture.publicationAttemptRows()).isEmpty(); + assertThat(stateBeforeFirstQualifiedCapture.publicationAuthorizationRows()).isEmpty(); + var forcedRollback = + new IllegalStateException("forced first-freeze qualification rollback"); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + var candidate = + fence.claimFreeze( + freezeEvidence, + () -> + checkpointRepository().capture(freezeEvidence, plan)); + assertThat( + publicationAuthorizationRepository + .retainOrRequireExact( + candidate, publicationOrder, true) + .canonicalBytes()) + .containsExactly(publicationOrder.canonicalBytes()); + throw forcedRollback; + })) + .isSameAs(forcedRollback); + var stateAfterFirstQualifiedCaptureRollback = ownerSnapshot(world, plan); + assertThat(stateAfterFirstQualifiedCaptureRollback) + .isEqualTo(stateBeforeFirstQualifiedCapture); + assertThat(stateAfterFirstQualifiedCaptureRollback.publicationOwnerRows()) + .containsExactly(openPublicationOwnerRow); + assertThat(stateAfterFirstQualifiedCaptureRollback.publicationAttemptRows()).isEmpty(); + assertThat(stateAfterFirstQualifiedCaptureRollback.publicationAuthorizationRows()) + .isEmpty(); + var frozenAttempt = + withGameDesignCaller( + () -> selectedFreezeService.freeze(freezeEvidence, plan, publicationOrder)); + account.assertPublicationSourcesHeld(publicationOrder); + var frozen = capture(plan, freezeEvidence, frozenAttempt); + assertThat(frozenAttempt.checkpoint().appliedCommitId()) + .isEqualTo(applied.application().operation().commitId().toString()); + var retryEvidence = freezeEvidence; + var stateBeforeExactRetry = ownerSnapshot(world, plan); + int selectedReadsBeforeRetry = selectedReadCalls.get(); + int stateReadsBeforeRetry = versionStateReadCalls.get(); + var exactRetry = + withGameDesignCaller( + () -> selectedFreezeService.freeze(retryEvidence, plan, publicationOrder)); + assertThat(exactRetry.request()).isEqualTo(retryEvidence); + assertThat(exactRetry.publicationFence()).isEqualTo(frozenAttempt.publicationFence()); + assertThat(exactRetry.checkpoint()).isEqualTo(frozenAttempt.checkpoint()); + assertThat(exactRetry).isEqualTo(frozenAttempt); + assertThat(ownerSnapshot(world, plan)).isEqualTo(stateBeforeExactRetry); + assertThat(selectedReadCalls.get()).isEqualTo(selectedReadsBeforeRetry); + assertThat(versionStateReadCalls.get()).isEqualTo(stateReadsBeforeRetry); + assertThat( + publicationAuthorizationRepository + .readCommitted(exactRetry) + .orElseThrow() + .canonicalBytes()) + .containsExactly(publicationOrder.canonicalBytes()); + account.assertPublicationSourcesHeld(publicationOrder); + var changedOperation = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + publicationOrder.fenceId(), + publicationOrder.input(), + publicationOrder.sources()); + assertThatThrownBy( + () -> + withGameDesignCaller( + () -> + selectedFreezeService.freeze( + retryEvidence, plan, changedOperation))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("changed"); + var changedFence = + new AccountPublicationAuthorizationBinding( + publicationOrder.operationId(), + UUID.randomUUID(), + publicationOrder.input(), + publicationOrder.sources()); + assertThatThrownBy( + () -> + withGameDesignCaller( + () -> selectedFreezeService.freeze(retryEvidence, plan, changedFence))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("changed"); + assertThat(ownerSnapshot(world, plan)).isEqualTo(stateBeforeExactRetry); + assertThat(selectedReadCalls.get()).isEqualTo(selectedReadsBeforeRetry); + assertThat(versionStateReadCalls.get()).isEqualTo(stateReadsBeforeRetry); + var selectors = + new WorldPublishedStartLocationRepository( + dsl, frozenRepository(), appliedRepository()); + var retained = selectors.readCommitted(frozen.request().freeze()).orElseThrow(); + var request = selectorRequest(frozen.request().freeze()); + var worldServer = + serve( + new WorldPublishedStartLocationReadGrpcService(selectors, NAMESPACE), + pki.worldServer, + pki); + try { + endpoints.setWorldManagementService("localhost:" + worldServer.getPort()); + try (var client = + new WorldPublishedStartLocationClient( + endpoints, + pki.gameDesignClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + client.init(); + var evidence = client.read(request); + assertThat(evidence.request()).isEqualTo(request); + assertThat(evidence.originalAccountBindingBytes()) + .isEqualTo(original.canonicalBytes()); + assertThat(evidence.appliedResultBytes()).isEqualTo(applied.canonicalBytes()); + assertThat(evidence.selectorReceiptBytes()) + .isEqualTo(retained.selectorReceipt().canonicalBytes()); + assertThat(client.read(request).canonicalBytes()) + .isEqualTo(evidence.canonicalBytes()); + } + // Trusted CA alone is not authority: the World workload cannot read the GD-only + // selector. + try (var wrong = + new WorldPublishedStartLocationClient( + endpoints, + pki.worldClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + wrong.init(); + assertThatThrownBy(() -> wrong.read(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + } + } finally { + stop(worldServer); } + // APPLIED does not settle either owner or replace the original Account ordering. + assertThat(read.read(heldRequest).request()).isEqualTo(heldRequest); + assertThat(dsl.fetchCount(DSL.table("world_draft_graph_application"))).isEqualTo(1); } finally { - stop(worldServer); + stop(gameDesignServer); } - // APPLIED does not settle either owner or replace the original Account ordering. - assertThat(read.read(heldRequest).request()).isEqualTo(heldRequest); - assertThat(dsl.fetchCount(DSL.table("world_draft_graph_application"))).isEqualTo(1); } } finally { stop(accountServer); @@ -689,15 +768,22 @@ private static WorldPublishedStartLocationEvidence.Request selectorRequest( private static Server serve(io.grpc.BindableService service, TestIdentity identity, TestPki pki) throws Exception { - return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.forServer(identity.certificate.toFile(), identity.key.toFile()) - .trustManager(pki.ca.toFile()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) - .build() - .start(); + return serveAll(identity, pki, service); + } + + private static Server serveAll(TestIdentity identity, TestPki pki, BindableService... services) + throws Exception { + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer(identity.certificate.toFile(), identity.key.toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + for (BindableService service : services) { + builder.addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + } + return builder.build().start(); } private static void stop(Server server) throws InterruptedException { @@ -706,6 +792,123 @@ private static void stop(Server server) throws InterruptedException { throw new IllegalStateException("Test server did not stop"); } + /** Strict loopback fixture for the stipulated immutable Game Design selection read. */ + private static final class SelectedDraftReadFixture + extends GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceImplBase { + private final AuthoredDraftPublishSelectionBinding selection; + private final AtomicInteger reads; + + SelectedDraftReadFixture(AuthoredDraftPublishSelectionBinding selection, AtomicInteger reads) { + this.selection = selection; + this.reads = reads; + } + + @Override + public void readSelectedDraftPublication( + ReadSelectedDraftPublicationRequest request, + StreamObserver observer) { + if (!requireWorldManagementPeer(observer)) return; + try { + var decoded = AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest(request); + if (!NAMESPACE.equals(decoded.targetNamespace()) + || !Arrays.equals(decoded.originalSelection(), selection.canonicalBytes()) + || !decoded.selectionDigest().equals(selection.digest())) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Fixture selection differs from the exact requested binding") + .asRuntimeException()); + return; + } + reads.incrementAndGet(); + observer.onNext(AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(decoded)); + observer.onCompleted(); + } catch (IllegalArgumentException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Fixture requires a canonical selected-Draft request") + .asRuntimeException()); + } + } + } + + /** Strict loopback fixture for the stipulated source-qualified current DRAFT read. */ + private static final class CurrentVersionStateReadFixture + extends GameDesignServiceGrpc.GameDesignServiceImplBase { + private final AuthoredWorldSourceEvidence source; + private final UUID canonicalVersionId; + private final long gameDesignVersionId; + private final long versionStateEpoch; + private final AtomicInteger reads; + + CurrentVersionStateReadFixture( + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + long gameDesignVersionId, + long versionStateEpoch, + AtomicInteger reads) { + this.source = source; + this.canonicalVersionId = canonicalVersionId; + this.gameDesignVersionId = gameDesignVersionId; + this.versionStateEpoch = versionStateEpoch; + this.reads = reads; + } + + @Override + public void getAuthoredWorldVersionState( + GetAuthoredWorldVersionStateRequest request, + StreamObserver observer) { + if (!requireWorldManagementPeer(observer)) return; + try { + var decoded = AuthoredWorldVersionStateGrpcCodec.fromRequest(request); + if (!NAMESPACE.equals(decoded.targetNamespace()) + || !source.canonicalTenantId().equals(decoded.canonicalTenantId()) + || !source.worldSlug().equals(decoded.worldSlug()) + || !source.operationId().equals(decoded.sourceOperationId()) + || !source.evidenceDigest().equals(decoded.expectedSourceEvidenceDigest()) + || decoded.versionId() != gameDesignVersionId) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Fixture version-state source binding differs") + .asRuntimeException()); + return; + } + reads.incrementAndGet(); + observer.onNext( + AuthoredWorldVersionStateGrpcCodec.toResponse( + AuthoredWorldVersionStateEvidence.create( + decoded, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + versionStateEpoch))); + observer.onCompleted(); + } catch (IllegalArgumentException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Fixture requires a canonical version-state request") + .asRuntimeException()); + } + } + } + + private static boolean requireWorldManagementPeer(StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError( + Status.UNAUTHENTICATED.withDescription("Verified peer required").asRuntimeException()); + return false; + } + if (!peer.isService("world-management-service") || !peer.isInNamespace(NAMESPACE)) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World Management peer required") + .asRuntimeException()); + return false; + } + return true; + } + private Fixture fixture( WorldAuthoredSourceIntakeRepository sourceIntake, PlatformTransactionManager transactionManager, @@ -934,31 +1137,8 @@ private WorldDesignMutationRevision.Builder mutation( private WorldCanonicalFrozenTopology capture( WorldDraftTopologyCommitPlan plan, WorldDesignPublicationFenceEvidence evidence, - AccountPublicationAuthorizationBinding stipulatedAccountOrder) { + FrozenAttempt attempt) { var owner = plan.ownerBinding(); - String publicationRequest = evidence.publicationRequestId(); - var authorizationRepository = publicationAuthorizationRepository(); - var checkpointCaptured = new AtomicInteger(); - var attempt = - Objects.requireNonNull( - ownerTransaction() - .execute( - status -> { - var frozen = - fence.claimFreeze( - evidence, - () -> { - var checkpoint = checkpointRepository().capture(evidence, plan); - checkpointCaptured.incrementAndGet(); - return checkpoint; - }); - var stored = - authorizationRepository.retainOrRequireExact( - frozen, stipulatedAccountOrder, checkpointCaptured.get() == 1); - assertThat(stored.canonicalBytes()) - .containsExactly(stipulatedAccountOrder.canonicalBytes()); - return frozen; - })); var tuples = plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() .map( @@ -978,7 +1158,7 @@ private WorldCanonicalFrozenTopology capture( owner.canonicalVersionId(), owner.intakeRequestId(), attempt.publicationFence(), - publicationRequest, + evidence.publicationRequestId(), evidence.requestDigest(), evidence.versionStateEpoch(), evidence.publishWorkflowId(), @@ -990,6 +1170,38 @@ private WorldCanonicalFrozenTopology capture( .capture(new WorldCanonicalFrozenTopology.Request(plan, request)); } + private WorldSelectedDraftPublicationFreezeService selectedPublicationFreezeService( + AuthoredDraftPublishSelectionReadClient selectionRead, + AuthoredWorldVersionStateClient versionStateRead, + AccountPublicationAuthorizationReadClient accountRead) { + return new WorldSelectedDraftPublicationFreezeService( + NAMESPACE, + selectionRead, + versionStateRead, + accountRead, + intakeRepository, + fence, + checkpointRepository(), + publicationAuthorizationRepository(), + manager); + } + + private static T withGameDesignCaller(Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + private WorldSelectedDraftPublicationCheckpointRepository checkpointRepository() { return new WorldSelectedDraftPublicationCheckpointRepository( fence, @@ -1232,7 +1444,7 @@ private record Fixture( /** Ephemeral certificate authority, never a deployed trust root or live workload credential. */ private static final class TestPki { final Path ca; - final TestIdentity accountServer, worldServer, worldClient, gameDesignClient; + final TestIdentity accountServer, worldServer, worldClient, gameDesignClient, gameDesignServer; TestPki(Path root) throws Exception { Files.createDirectories(root); @@ -1268,6 +1480,7 @@ private static final class TestPki { worldServer = issue(root, "world-management-service", true, caKeys, caCert); worldClient = issue(root, "world-management-service", false, caKeys, caCert); gameDesignClient = issue(root, "game-design-service", false, caKeys, caCert); + gameDesignServer = issue(root, "game-design-service", true, caKeys, caCert); } private static TestIdentity issue( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 79f7513053..7f53ecdd2c 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -705,7 +705,7 @@ void canonicalPreparationKeepsOriginalPublicationEpochForLaterReleaseResolution( @Test void terminalRequiresTheExactV53AccountOrderForFirstCompletionAndExactRetry() { Fixture f = fixture(); - var graphApplication = application(f); + var graphApplication = application(generationFreePlan(f)); appliedComponent().apply(graphApplication); var frozen = captureForTerminal( @@ -804,7 +804,7 @@ void worldTerminalReadUsesIndependentQualifiedOwnerAndRequiredMtls() throws Exce var pki = WorldTerminalReadTestPki.create(temporaryDirectory.resolve("terminal-read-pki")); for (Outcome outcome : List.of(Outcome.PUBLISHED, Outcome.NO_PUBLICATION)) { Fixture f = fixture(); - var graphApplication = application(f); + var graphApplication = application(generationFreePlan(f)); appliedComponent().apply(graphApplication); var frozen = captureForTerminal( @@ -985,7 +985,7 @@ void worldTerminalReadUsesIndependentQualifiedOwnerAndRequiredMtls() throws Exce @Test void terminalRejectsUnqualifiedHistoricalFreezeWithoutInventingAccountOrder() { Fixture f = fixture(); - var graphApplication = application(f); + var graphApplication = application(generationFreePlan(f)); appliedComponent().apply(graphApplication); var frozen = capture(graphApplication.plan()); var selector = @@ -1022,7 +1022,7 @@ void terminalRejectsUnqualifiedHistoricalFreezeWithoutInventingAccountOrder() { @Test void terminalSqlRejectsMalformedOversizedAndTrailingOperationFrames() { Fixture f = fixture(); - var graphApplication = application(f); + var graphApplication = application(generationFreePlan(f)); appliedComponent().apply(graphApplication); var frozen = captureForTerminal( @@ -1461,7 +1461,8 @@ void canonicalLifecycleReadRejectsIncompleteOrSubstitutedRegionAssignments() { .getLast(); var application = withStartRoom(original, roomTemplateId); appliedComponent().apply(application); - var frozen = capture(application.plan()); + var frozen = + captureForTerminal(application.plan(), application.operation().accountBindingBytes()); var selector = publishedEvidence( publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); @@ -3563,7 +3564,8 @@ void selectorPreparationLateFenceLossRollsBackSelectorRuntimeAndAssociationToget Fixture f = fixture(); var application = application(generationFreePlan(f)); appliedComponent().apply(application); - var frozen = capture(application.plan()); + var frozen = + captureForTerminal(application.plan(), application.operation().accountBindingBytes()); var selector = publishedEvidence( publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); @@ -4644,7 +4646,9 @@ private PreparedLifecycleFixture materializedLifecycleFixture() { .getLast(); var applied = withStartRoom(original, selectedRoom); appliedComponent().apply(applied); - var frozen = capture(applied.plan()); + // Retain the fixture-only distinct Account order at first freeze; preparation derives its + // later terminal from the exact same binding carried by the frozen selector. + var frozen = captureForTerminal(applied.plan(), applied.operation().accountBindingBytes()); var selector = publishedEvidence( publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); From ab77d05daa0c7fc885d5f6745d2e87ceafe6bd53 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 10:21:40 +1300 Subject: [PATCH 032/129] Prove composed selected publication and align World digest schema --- .../game-logic-service/runtime-and-data.md | 2 +- .../runtime-and-data.md | 4 +- ...ame-authoring-publishing-and-activation.md | 6 +- .../service/impl/PublishGateServiceImpl.java | 2 +- .../draft/IsolatedPublicationOwnerSetup.java | 26 +- ...emptServiceTransactionIntegrationTest.java | 471 +++++++++++++++++- .../impl/PublishGateServiceImplTest.java | 33 +- 7 files changed, 524 insertions(+), 20 deletions(-) diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index 268ba9f5ff..512adc1660 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -6,7 +6,7 @@ This document defines the Game Logic Service runtime model, dependency ownership The sections below define the target-state runtime contract. Current implementation and proof status is: -- The current implementation attests an empty owned-rule manifest and returns synthetic `appliedCommitId = "version:"` because Game Logic does not yet own version-scoped draft rule tables. The empty-manifest digest is intentional and does not represent hidden service state. +- Full-version digest reads fail closed because Game Logic lacks an owner-local manifest and provenance sufficient to attest the selected version's rule inputs. It does not return an empty-manifest attestation or infer an empty authored set from absent storage. The [API implementation status](api-contracts.md#implementation-status) records this publication prerequisite; the Draft digest contract below defines the required owner boundary, not completed producer proof. - Same-type Game Logic takeover behind an existing edge connection is target behavior, but suppression of a client-visible reconnect after an ordinary qualifying Game Logic restart remains implementation or proof debt under ADR 0013. - Target: `SendCommunication` and every other player-delegated gameplay RPC propagate one complete, validated typed `PlayerExecutionContext` from Game Session through Game Logic and onward. Game Logic validates the context against request and owner evidence, never treats caller-supplied identifiers as authority, remains stateless, and owns semantic gameplay outcomes; Game Session owns session, reconnect, and presentation state. This is the ADR 0024 target contract. - Current implementation gap: the live `SendCommunicationRequest` is still a flat schema with tenant/session/character/account, communication/text and target metadata, room, game-instance, speaker, and effect fields plus legacy `session_attestation`; its current proto does not carry typed `playableStateNamespaceId`, `playableStateScope`, region/epoch, pointer, or admitted-bundle fields. Complete typed-context propagation is therefore not current behavior or proof. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 7dba6e63f6..f117d74289 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -168,7 +168,7 @@ Implementation Notes: - Current concrete `room` digest fields include `id`, `zoneId`, `name`, `description`, `nameLocalizedVariantsJson`, and `descriptionLocalizedVariantsJson`. - Current concrete `room_exit` digest fields include `id`, `fromRoomId`, `toRoomId`, `direction`, and `cost`. - Current concrete `generation_rule` digest fields include `id`, `name`, `scopeType`, `scopeId`, and `value`; generation-rule mutations that carry a subtree scope must validate that declared scope, share the same scope epoch, and participate in `REPLACE_SCOPE` / `SEED_APPEND_ONLY` enforcement. -- Current concrete `world_entity_spawn_binding` digest fields include `id`, `roomId`, `entityTemplateType`, `entityTemplateId`, `spawnCount`, and `respawnDelaySeconds`. +- Current concrete `world_entity_spawn_binding` digest fields include `id`, `roomId`, `entityTemplateType`, `entityReference`, `spawnCount`, and `respawnDelaySeconds`. `entityReference` is a tagged object: `CANONICAL_UUID` carries non-nil UUID `tenantId`, `versionId`, and `templateId`; `RETAINED_PRIVATE_KEY` carries a positive-decimal string `templateId`. A numeric reference mixed with any canonical UUID, an incomplete canonical triple, or a nonpositive numeric reference fails closed. The retained private-key tag records only the existing reference representation; it supplies neither canonical publication identity nor publication admission authority. - Included objects: - version-scoped topology tables such as `region_template`, `zone_template`, `room_template`, `terrain_template`, `room_exit_template`, and equivalent normalized topology relations; @@ -184,7 +184,7 @@ Implementation Notes: - stable table ordering; - primary-key ordering within each table; - deterministic encoding for included semantic fields. -- Current implementation note: the concrete first-slice table order is `regions`, `zones`, `rooms`, `roomExits`, `generationRules`, then `worldEntitySpawnBindings`, each ordered by ascending primary key. Null string values are canonicalized as empty strings before hashing. The current World digest schema version is `2` because scoped generation-rule metadata is now hashed. +- Current implementation note: the concrete first-slice table order is `regions`, `zones`, `rooms`, `roomExits`, `generationRules`, then `worldEntitySpawnBindings`, each ordered by ascending primary key. Nested object fields are sorted by key, and null string values are canonicalized as empty strings before hashing. The current World digest schema version is `3`, superseding schema `2` because spawn references now use the tagged `entityReference` serialization. Previously retained schema-2 evidence must not be relabeled as schema 3; schema adoption requires recomputation and replay or re-recording under the publication digest migration rules in [Game Design Version Control](../game-design-service/version-control.md#digest-schema-migration). This serialization change does not close the generic digest's synthetic applied-commit gap described above. - `digestSchemaVersion` must increment whenever included tables, field-selection rules, or canonical serialization semantics change. Publish gating fails closed if World Management cannot attest a digest consistent with this manifest. 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 8f3aa005fa..d543e64a71 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 @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a Published-head `2560d12a8265db943a06e43d1e9e261bb2cdd923` [Validation run 37840711622](https://github.com/benhook1013/FireMUD/actions/runs/37840711622) finished red: 36 jobs passed, Account/World/the aggregate gate failed, and one tooling contract job skipped. Its physical XML records 233 Account cases with 208 failures, 206 World cases with 42 failures, and 75 Game Design cases with no failures; all have zero skips and errors. V107's PL/pgSQL syntax error blocked Account initialization and two World cases. All seven isolated WAL tests failed during migration setup, before their proof logic; this is neither WAL execution proof nor a new V92 durability verdict. World's other failures expose stale terminal fixtures missing V53 qualification (36 cases) and four terminal fixtures incorrectly entering unsupported generation/spawn preparation. The bounded syntax and fixture repairs require corrected-head physical execution; no production qualification or generation-intent guard may be weakened. Game Session and TCP Gradle checks passed with the bounded resource profile. Actual owner jobs checked out synthetic merge `e2bdaf5d011ba97d9a407183892e9ec7b069a909`, tree `1fb483d5c7ed53f27b483587a38909181aa3316b`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and `2560d12a8265db943a06e43d1e9e261bb2cdd923`. The live target had advanced 21 commits/33 paths beyond recorded base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`, with no Account/Game Design/World service differences; this explains composition but does not close intended-parent alignment. Substantive [CodeQL run 37840711613](https://github.com/benhook1013/FireMUD/actions/runs/37840711613) succeeded. Its dependency-deferred duplicate supplied no additional analysis; likewise metadata-only Validation run 37840712794 supplied no runtime proof. -The current publication handoff batch has passing local unit XML for 316 Common, 1,079 Account, 347 Game Design and 540 World cases, plus seven non-database Account integration cases. All 509 database integration definitions skip without Docker: 228 Account, 75 Game Design and 206 World. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. The consolidated Common/Account/Game Design gate failed solely on an unnecessary new receiver suppression; removing it and rerunning Account formatting/main static analysis/packaging plus the complete World gate passed. Common and Game Design full gates, all three service boot jars and the remaining Account static gates passed in the consolidated run. Documentation validation remains separate; Flyway sanity covers 12 sets / 246 versioned files. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. +The current publication handoff batch has passing local unit XML for 316 Common, 1,079 Account, 348 Game Design and 540 World cases, plus seven non-database Account integration cases. All 510 database integration definitions skip without Docker: 228 Account, 76 Game Design and 206 World. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. The consolidated Common/Account/Game Design gate failed solely on an unnecessary new receiver suppression; removing it and rerunning Account formatting/main static analysis/packaging plus the complete World gate passed. Common and Game Design full gates, all three service boot jars and the remaining Account static gates passed. The subsequent Game Design full gate passed after adding composed-command PostgreSQL proof and aligning the World schema gate. Links and Markdown also passed; Flyway sanity covers 12 sets / 246 versioned files. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. Published-head `5132fb96b98f2d33b9db5d09d763aebb63efafb2` [Validation run 37834941641](https://github.com/benhook1013/FireMUD/actions/runs/37834941641) executed 229 Account, 75 Game Design and 202 World owner integration cases without skips. Game Design passed; Account retained one V92 original-acknowledgement WAL-coverage denial, and four World historical-upgrade fixtures failed after the additive full-XID column changed their copy/snapshot shapes. The bounded fixture correction preserves all historical fields and explicitly proves the new stamp stays null; corrected-head physical execution remains required. Game Session and TCP Proxy failed in dependent Java compilation with heap exhaustion, before their owner integration tests executed. The runner used synthetic merge `6d8435b7e31f5306defe357703139ccaa23e3fe6` with first parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`; these results do not close actual-parent alignment. Passing source intake mTLS cases do not separately establish the complete V53 qualification or genuine publication boundary. @@ -32,6 +32,10 @@ The standalone Account selected-publication producer defines a distinct immutabl The new standalone Account producer transport binds its method-specific credential interceptor internally and captures the environment boundary through Account's owner service, not caller input. Local Common units prove credential-free protobuf text, redacted wrappers and protected exact-method emission; receiver units prove peer-first denial and owner ordering. The new PostgreSQL/loopback-mTLS definition drives real creator issuance, the producer transport and retained publication sources, but stipulates upstream Game Design selection. The production environment-authority provider and runtime registration are absent; physical execution is pending. Game Design's unregistered selected-publication command now composes authenticated admission with the existing selected-Version v2 finalizer and exact retained-operation retry. Its six local unit cases use mocked collaborators and do not prove PostgreSQL command composition, a genuine release manifest or complete multi-owner publication. These limitations must remain beside each bounded proof claim. +The composed-command PostgreSQL definition now uses real Game Design selection, admission, reservation, finalization and terminal storage with strict loopback-mTLS clients. Account `HELD`, World selector, original Draft outcomes, participant digests and immutable empty export remain expressly stipulated; the definition compiled but skipped locally and requires physical execution. It checks denied admission before reservation, exact selected-Version v2 publication, immutable terminal readback, unchanged retry without fresh owner reads, and changed-lookup denial. The live World digest emits schema 3, already required by shared release evidence; Game Design now accepts that schema and denies obsolete 2 and unknown 4 in focused units. World's owner manifest describes the same tagged references. This alignment does not relabel retained digests, make synthetic commits authoritative or open any route. + +Actual producer tracing still blocks a genuine v2 release: Game Logic denies full-version reads without its owner-local rule/ability manifest and lacks the dedicated ability-schema response field; Automation full-version scripts/bindings and Game Design template/asset wiring remain tenant-wide rather than exact selected-version inputs; Entity and generic owner digests retain synthetic commit tokens; and the live asset exporter cannot return the complete immutable artifact evidence required by the v2 writer. The canonical owners remain [Game Logic API contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status), [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). No missing mapping or absent row proves an empty authored set. Generic digest workflow derivation also still uses Game Design's private tenant selector, unlike the canonical tenant UUID in selected publication; identity convergence and owner-local selector resolution remain required. The concrete Game Logic manifest input boundary has been referred to Overseer before inventing a producer contract. These are implementation dependencies, not failures cured by mocked command proof or by making synthetic tokens equal. + Substantive construction CI [37827785558](https://github.com/benhook1013/FireMUD/actions/runs/37827785558) for `60c507243987705094a3028e0b46f3bccd5d9504` executed 229 Account, 201 World and 74 Game Design integration cases with no skips or errors. Game Design and World passed; Account had two failures. The signer generation/promotion identity correction and V103 terms-fixture correction passed their affected cases. One remaining Account concurrency test reused a frozen activity-statistics snapshot while waiting for a blocked creator; its observer correction requires corrected-head execution. Original-ack receipt recovery still fails closed against the conservative global WAL insert fence. Decoded target COMMIT boundaries were covered by the independently logged flush, but the production recovery path has no supported independent exact-COMMIT locator; this diagnostic does not weaken durability or deadline requirements. The run tested a synthetic merge whose first parent was `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`; it supplies no exact-integrated-base or ancestry-closure proof. Local PostgreSQL definitions remain skipped without Docker. The current Gameplay-prerequisite construction remains non-activating. Full-version finalization reads the original World evidence from the exact pending publication operation before local publication writes and uses the selector-bearing v2 bundle path. Missing or changed evidence leaves the attempt pending for exact reconciliation. An opt-in Game Design selector client reuses the canonical file-backed mTLS transport and refuses network capture under owner transactions; it is not a registered creator or publication producer. Production backend control-ui issuance/current-actor integration, complete Account source-writer fencing and the callable original Account commit-order -> World APPLIED -> Game Design publication path remain open. In particular, the distinct selected-publication operation still needs authenticated Account authorization; original Draft permission cannot substitute. Isolated owner fixtures may drive real storage with explicitly test-only upstream authority; they do not prove production issuance or genuine preexisting provenance. Construction CI at `f14c7950827dd435ac0fe5c4cc230a1de32fa96d` executed all 74 Game Design and 200 World integration cases without skips or failures, including the corrected canonical-release and selected-publication transaction regressions. Its 220 Account integration executions passed the future-terms, environment-binding, disclosure-handoff and three real Redis registry cases; one readiness-promotion fixture assertion still compared its initial plan with subsequently progressed entries. A corrected assertion and the composed Account-to-World handoff need separate validation. These bounded results do not upgrade the broader capability ratings below. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java index 4155e3b6d1..a70eb5a7f4 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java @@ -24,7 +24,7 @@ public class PublishGateServiceImpl implements PublishGateService { private static final Map SUPPORTED_DIGEST_SCHEMA_VERSIONS = Map.of( - PublishParticipantKey.WORLD_MANAGEMENT.name(), 2, + PublishParticipantKey.WORLD_MANAGEMENT.name(), 3, PublishParticipantKey.ENTITY_MANAGEMENT.name(), 1, PublishParticipantKey.GAME_LOGIC.name(), 1, PublishParticipantKey.AUTOMATION_SCRIPTING.name(), 5, diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index 658ca9cb1d..76a8b8d57f 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -5,6 +5,7 @@ import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; @@ -69,7 +70,19 @@ public static GameDesignPublicationOperation retainSourceBacked( public static AuthoredDraftPublishSelectionRepository.SelectionSnapshot selectSourceBackedDraft( DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) throws Exception { - return prepareSelection(dsl, target, draftEpoch, notes, true).selection(); + return selectSourceBackedDraftWithWorld(dsl, target, draftEpoch, notes).selection(); + } + + /** + * Creates actual synchronized source rows and selection, retaining its exact isolated World seed + * so publication fixtures can derive matching Account and selector inputs without regenerating + * the randomized source binding. + */ + public static SourceBackedSelection selectSourceBackedDraftWithWorld( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + PreparedSelection prepared = prepareSelection(dsl, target, draftEpoch, notes, true); + return new SourceBackedSelection(prepared.selection(), prepared.world()); } private static GameDesignPublicationOperation retain( @@ -179,7 +192,16 @@ private static PreparedSelection prepareSelection( private record PreparedSelection( AuthoredDraftPublishSelectionRepository.SelectionSnapshot selection, - net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence world) {} + WorldPublishedStartLocationEvidence world) {} + + public record SourceBackedSelection( + AuthoredDraftPublishSelectionRepository.SelectionSnapshot selection, + WorldPublishedStartLocationEvidence world) { + public SourceBackedSelection { + java.util.Objects.requireNonNull(selection, "selection"); + java.util.Objects.requireNonNull(world, "world"); + } + } /** Storage fixture commit only; does not substitute for actual command finalization proof. */ public static PublishedReleaseBundle commitStorage( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index bb7eb81ad7..cd2862b6c9 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.catchThrowable; +import io.grpc.BindableService; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; @@ -11,6 +12,7 @@ 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.stub.StreamObserver; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -23,15 +25,23 @@ import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountPublicationAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadGrpcCodec; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; @@ -41,7 +51,10 @@ import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadGrpcCodec; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationGrpcCodec; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; @@ -64,6 +77,7 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadGrpcService; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadService; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationCommandService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; @@ -79,6 +93,9 @@ import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationReadServiceGrpc; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -114,6 +131,7 @@ }) @Import(NoGrpcServerTestConfiguration.class) class PublishAttemptServiceTransactionIntegrationTest { + private static final String NAMESPACE = "test"; private static final String TENANT_ID = "9001"; private static final String WORKFLOW_ID = "full-version-transaction-integration-test"; @@ -509,6 +527,294 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth assertTerminalOwnerReadOverMtls(operation, Outcome.PUBLISHED, terminalPki); } + /** + * Exercises the real GD admission, owner reservation, and finalizer. The Account HELD response, + * World selector, original Draft outcomes, participant digests, and empty export are explicitly + * stipulated test fixtures; this is not genuine upstream production proof. + */ + @Test + void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Release( + @TempDir Path temporary) throws Exception { + String tenantId = "9010"; + Game game = new Game(); + game.setTenantId(tenantId); + game.setName("selected-command-composition-proof-game"); + gameRepository.save(game); + + Version candidate = new Version(); + candidate.setTenantId(tenantId); + candidate.setVersionNumber(1); + candidate.setVersionState(VersionLifecycleState.DRAFT); + candidate.setVersionStateEpoch(1L); + candidate.setNotes("selected command composition proof"); + candidate = versionRepository.save(candidate); + TargetProof target = targetProof(candidate); + long candidateEpoch = candidate.getVersionStateEpoch(); + var prepared = + inOwnerTransaction( + () -> { + try { + return IsolatedPublicationOwnerSetup.selectSourceBackedDraftWithWorld( + dsl, target, candidateEpoch, "selected command composition proof"); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + var selectionSnapshot = prepared.selection(); + var selection = selectionSnapshot.selection(); + var operation = + IsolatedPublicationOperationFixtures.forSelection( + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + prepared.world()); + assertThat(operation.account().input().selection().canonicalBytes()) + .containsExactly(selection.canonicalBytes()); + assertThat(operation.world().selectorReceiptBytes()) + .containsExactly(prepared.world().selectorReceiptBytes()); + assertThat(operation.world().originalAccountBindingBytes()) + .containsExactly(prepared.world().originalAccountBindingBytes()); + assertThat(operation.world().appliedResultBytes()) + .containsExactly(prepared.world().appliedResultBytes()); + var projectedWorldRequest = operation.world().request(); + assertThat(projectedWorldRequest.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(projectedWorldRequest.canonicalTenantId()) + .isEqualTo(selection.intent().canonicalTenantId()); + assertThat(projectedWorldRequest.canonicalVersionId()) + .isEqualTo(selection.intent().canonicalVersionId()); + assertThat(projectedWorldRequest.intakeRequestId()) + .isEqualTo(prepared.world().request().intakeRequestId()); + assertThat(projectedWorldRequest.publicationRequestId()) + .isEqualTo(selection.intent().publishRequestId()); + assertThat(projectedWorldRequest.requestDigest()) + .isEqualTo(selection.digest().substring("sha256:".length())); + assertThat(projectedWorldRequest.versionStateEpoch()) + .isEqualTo(Long.parseLong(selection.intent().expectedVersionStateEpoch())); + String expectedWorkflowId = + PublicationDigestRequestBinding.full( + selection.intent().canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + selection.intent().publishRequestId()) + .derivedWorkflowIdentity(); + assertThat(projectedWorldRequest.publishWorkflowId()).isEqualTo(expectedWorkflowId); + assertThat(projectedWorldRequest.appliedCommitId()) + .isEqualTo(selection.intent().selectedCommitId().toString()); + assertThat(projectedWorldRequest.contentDigest()) + .isEqualTo(prepared.world().request().contentDigest()); + assertThat(projectedWorldRequest.worldAffectedTuples()) + .isEqualTo(prepared.world().request().worldAffectedTuples()); + + String workflowId = operation.workflowId(); + String publishRequestId = operation.account().publishRequestId(); + String publishedWorldEvidenceJson = + new String(operation.world().canonicalBytes(), StandardCharsets.UTF_8); + var participantDigests = + PublishedWorldSelectorFixtures.participants(candidate.getId(), operation.world()); + Mockito.when( + publishGateService.collectFullVersionParticipantDigests( + Mockito.any(VersionDto.class), + Mockito.eq(publishRequestId), + Mockito.eq(workflowId))) + .thenReturn(participantDigests); + Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(immutableEmptyManifest()); + + var pki = new SelectionReadTestPki(Files.createDirectories(temporary.resolve("pki"))); + var publicationReadIdentities = pki.publicationReadIdentities(); + var heldDenied = new AtomicBoolean(true); + var accountEndpoint = + new StipulatedAccountPublicationReadEndpoint(operation.account(), heldDenied); + var worldEndpoint = new StipulatedWorldPublicationReadEndpoint(operation.world()); + Server accountServer = + publicationOwnerServer(publicationReadIdentities.accountServer(), pki, accountEndpoint); + Server worldServer = + publicationOwnerServer( + publicationReadIdentities.worldManagementServer(), pki, worldEndpoint); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + accountServer.getPort()); + endpoints.setWorldManagementService("127.0.0.1:" + worldServer.getPort()); + try { + try (var accountClient = + new AccountPublicationAuthorizationReadClient( + endpoints, + publicationReadIdentities.gameDesignClient().properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE); + var worldClient = + new WorldPublishedStartLocationClient( + endpoints, + publicationReadIdentities.gameDesignClient().properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + accountClient.init(); + worldClient.init(); + var command = + new SelectedDraftPublicationCommandService( + dsl, + transactionManager, + accountClient, + worldClient, + NAMESPACE, + versionPublishCommandService); + + assertSelectionReadCode( + Status.Code.FAILED_PRECONDITION, + () -> + command.publishSelectedDraftFullVersion( + selection.intent(), operation.account(), operation.world().request())); + assertThat(accountEndpoint.readCount()).isEqualTo(1); + assertThat(worldEndpoint.readCount()).isZero(); + assertThat(publishAttemptRepository.findByPublishWorkflowId(workflowId)).isEmpty(); + assertThat(new GameDesignPublicationOperationRepository(dsl).read(workflowId)).isEmpty(); + assertThat( + new AuthoredDraftPublishSelectionRepository( + dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId()) + .orElseThrow() + .selection() + .canonicalBytes()) + .containsExactly(selection.canonicalBytes()); + assertThat( + versionRepository + .findByTenantIdAndId(tenantId, candidate.getId()) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.DRAFT); + assertThat( + publishedReleaseBundleRepository.findByTenantIdAndVersionId( + tenantId, candidate.getId())) + .isEmpty(); + assertThat( + versionAssetArtifactRepository.findByTenantIdAndVersionId( + tenantId, candidate.getId())) + .isEmpty(); + assertThat(versionCountForTenant(tenantId)).isEqualTo(1L); + + heldDenied.set(false); + long versionCountBeforePublish = versionCountForTenant(tenantId); + VersionDto published = + command.publishSelectedDraftFullVersion( + selection.intent(), operation.account(), operation.world().request()); + assertThat(published.id()).isEqualTo(candidate.getId()); + assertThat(versionCountForTenant(tenantId)).isEqualTo(versionCountBeforePublish); + assertThat(accountEndpoint.readCount()).isEqualTo(2); + assertThat(worldEndpoint.readCount()).isEqualTo(1); + + PublishAttempt attempt = + publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow(); + Version storedVersion = + versionRepository.findByTenantIdAndId(tenantId, candidate.getId()).orElseThrow(); + PublishedReleaseBundle bundle = + publishedReleaseBundleRepository + .findByTenantIdAndVersionId(tenantId, candidate.getId()) + .orElseThrow(); + VersionAssetArtifact artifact = + versionAssetArtifactRepository + .findByTenantIdAndVersionId(tenantId, candidate.getId()) + .orElseThrow(); + var retainedOperation = + new GameDesignPublicationOperationRepository(dsl).read(workflowId).orElseThrow(); + assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.SUCCEEDED); + assertThat(attempt.getVersionId()).isEqualTo(candidate.getId()); + assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.PUBLISHED); + assertThat(bundle.getAttestationSchemaVersion()).isEqualTo("v2"); + assertThat(bundle.getWorldPublishedStartLocationEvidenceJson()) + .isEqualTo(publishedWorldEvidenceJson); + assertThat(bundle.getPublishWorkflowId()).isEqualTo(workflowId); + assertThat(artifact.getArtifactState()).isEqualTo(VersionAssetArtifactState.PUBLISHED); + assertThat(retainedOperation.operation().canonicalBytes()) + .containsExactly(operation.canonicalBytes()); + assertThat(retainedOperation.outcome()).isEqualTo("PUBLISHED"); + assertThat(retainedOperation.terminalEvidenceBytes()).isNotEmpty(); + publishAttemptRepository.requirePublishedOperation(attempt); + + assertTerminalOwnerReadOverMtls(operation, Outcome.PUBLISHED, pki); + byte[] terminalBeforeChangedRetry = retainedOperation.terminalEvidenceBytes(); + long attemptIdBeforeRetry = attempt.getId(); + long attemptRevisionBeforeRetry = attempt.getRevision(); + Long bundleIdBeforeRetry = bundle.getId(); + String releaseRefBeforeRetry = bundle.getPublishedReleaseBundleRef(); + VersionDto exactRetry = + command.publishSelectedDraftFullVersion( + selection.intent(), operation.account(), operation.world().request()); + assertThat(exactRetry.id()).isEqualTo(published.id()); + assertThat( + publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow().getId()) + .isEqualTo(attemptIdBeforeRetry); + assertThat( + publishAttemptRepository + .findByPublishWorkflowId(workflowId) + .orElseThrow() + .getRevision()) + .isEqualTo(attemptRevisionBeforeRetry); + var bundleAfterExactRetry = + publishedReleaseBundleRepository + .findByTenantIdAndVersionId(tenantId, candidate.getId()) + .orElseThrow(); + assertThat(bundleAfterExactRetry.getId()).isEqualTo(bundleIdBeforeRetry); + assertThat(bundleAfterExactRetry.getPublishedReleaseBundleRef()) + .isEqualTo(releaseRefBeforeRetry); + var operationAfterExactRetry = + new GameDesignPublicationOperationRepository(dsl).read(workflowId).orElseThrow(); + assertThat(operationAfterExactRetry.operation().canonicalBytes()) + .containsExactly(operation.canonicalBytes()); + assertThat(operationAfterExactRetry.terminalEvidenceBytes()) + .containsExactly(terminalBeforeChangedRetry); + assertThat( + dsl.fetchSingle( + "SELECT COUNT(*) FROM published_release_bundle WHERE tenant_id = ?", + tenantId) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.fetchSingle( + "SELECT COUNT(*) FROM publish_attempt WHERE publish_workflow_id = ?", + workflowId) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat(accountEndpoint.readCount()).isEqualTo(2); + assertThat(worldEndpoint.readCount()).isEqualTo(1); + assertThat(versionCountForTenant(tenantId)).isEqualTo(versionCountBeforePublish); + + var request = operation.world().request(); + var changedWorldRequest = + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + UUID.randomUUID(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()); + assertThatThrownBy( + () -> + command.publishSelectedDraftFullVersion( + selection.intent(), operation.account(), changedWorldRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("LOCAL_IDENTITY_CONFLICT"); + var retainedAfterChangedRetry = + new GameDesignPublicationOperationRepository(dsl).read(workflowId).orElseThrow(); + assertThat(retainedAfterChangedRetry.operation().canonicalBytes()) + .containsExactly(operation.canonicalBytes()); + assertThat(retainedAfterChangedRetry.terminalEvidenceBytes()) + .containsExactly(terminalBeforeChangedRetry); + assertThat(accountEndpoint.readCount()).isEqualTo(2); + assertThat(worldEndpoint.readCount()).isEqualTo(1); + assertThat(versionCountForTenant(tenantId)).isEqualTo(versionCountBeforePublish); + } + } finally { + shutdownServer(accountServer); + shutdownServer(worldServer); + } + } + @Test void selectedDraftPublicationRemainsPendingWithoutItsOriginalOperation() throws Exception { String tenantId = "9007"; @@ -1125,6 +1431,153 @@ private void assertTerminalOwnerReadOverMtls( } } + private static Server publicationOwnerServer( + SelectionReadTestIdentity identity, SelectionReadTestPki pki, BindableService endpoint) + throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static boolean requireGameDesignPeer(StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError( + Status.UNAUTHENTICATED + .withDescription("Verified workload required") + .asRuntimeException()); + return false; + } + if (!peer.uri().equals("spiffe://firemud/ns/test/sa/game-design-service")) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Exact Game Design peer required") + .asRuntimeException()); + return false; + } + return true; + } + + private static void shutdownServer(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private long versionCountForTenant(String tenantId) { + return dsl.fetchSingle("SELECT COUNT(*) FROM version WHERE tenant_id = ?", tenantId) + .get(0, Long.class); + } + + /** Test-only HELD endpoint; it accepts only the exact stipulated Account binding. */ + private static final class StipulatedAccountPublicationReadEndpoint + extends AccountPublicationAuthorizationReadServiceGrpc + .AccountPublicationAuthorizationReadServiceImplBase { + private final byte[] expectedBinding; + private final AtomicBoolean heldDenied; + private final AtomicInteger reads = new AtomicInteger(); + + private StipulatedAccountPublicationReadEndpoint( + AccountPublicationAuthorizationBinding expectedBinding, AtomicBoolean heldDenied) { + this.expectedBinding = expectedBinding.canonicalBytes(); + this.heldDenied = heldDenied; + } + + @Override + public void readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest request, + StreamObserver observer) { + if (!requireGameDesignPeer(observer)) return; + reads.incrementAndGet(); + final AccountPublicationAuthorizationReadEvidence.Request decoded; + try { + decoded = AccountPublicationAuthorizationReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Invalid stipulated read request") + .asRuntimeException()); + return; + } + if (!java.util.Arrays.equals(decoded.binding().canonicalBytes(), expectedBinding)) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Different stipulated Account binding") + .asRuntimeException()); + return; + } + if (!NAMESPACE.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Different stipulated Account namespace") + .asRuntimeException()); + return; + } + if (heldDenied.get()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Stipulated Account order is not HELD") + .asRuntimeException()); + return; + } + observer.onNext(AccountPublicationAuthorizationReadGrpcCodec.toHeldResponse(decoded)); + observer.onCompleted(); + } + + int readCount() { + return reads.get(); + } + } + + /** Test-only selector endpoint; it returns only the exact stipulated World evidence. */ + private static final class StipulatedWorldPublicationReadEndpoint + extends WorldPublishedStartLocationReadServiceGrpc + .WorldPublishedStartLocationReadServiceImplBase { + private final WorldPublishedStartLocationEvidence expectedEvidence; + private final AtomicInteger reads = new AtomicInteger(); + + private StipulatedWorldPublicationReadEndpoint( + WorldPublishedStartLocationEvidence expectedEvidence) { + this.expectedEvidence = expectedEvidence; + } + + @Override + public void readWorldPublishedStartLocation( + ReadWorldPublishedStartLocationRequest request, + StreamObserver observer) { + if (!requireGameDesignPeer(observer)) return; + reads.incrementAndGet(); + final WorldPublishedStartLocationEvidence.Request decoded; + try { + decoded = WorldPublishedStartLocationGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Invalid stipulated selector request") + .asRuntimeException()); + return; + } + if (!expectedEvidence.request().equals(decoded)) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Different stipulated World selector") + .asRuntimeException()); + return; + } + observer.onNext(WorldPublishedStartLocationGrpcCodec.toResponse(decoded, expectedEvidence)); + observer.onCompleted(); + } + + int readCount() { + return reads.get(); + } + } + private static GameDesignPublicationTerminalReadClient terminalReadClient( int port, SelectionReadTestIdentity identity, Path ca) throws Exception { var endpoints = new ServiceEndpointsProperties(); @@ -1202,6 +1655,8 @@ CommonGrpcClientProperties properties(Path ca) { /** Ephemeral keytool PKI, following Account's existing loopback test; no runtime credentials. */ private static final class SelectionReadTestPki { private static final String PASSWORD = "test-only-publication-mtls-password"; + private final Path root; + private final Path caStore; final Path ca; final SelectionReadTestIdentity server, account, @@ -1211,7 +1666,8 @@ private static final class SelectionReadTestPki { otherWorldNamespace; SelectionReadTestPki(Path root) throws Exception { - Path caStore = root.resolve("ca.p12"); + this.root = root; + this.caStore = root.resolve("ca.p12"); runKeytool( "-genkeypair", "-alias", @@ -1263,6 +1719,19 @@ private static final class SelectionReadTestPki { root, caStore, "other-world-client", "other-test", "world-management-service", false); } + PublicationReadIdentities publicationReadIdentities() throws Exception { + return new PublicationReadIdentities( + issue(root, caStore, "game-design-client", "test", "game-design-service", false), + issue(root, caStore, "account-server", "test", "account-service", true), + issue( + root, caStore, "world-management-server", "test", "world-management-service", true)); + } + + private record PublicationReadIdentities( + SelectionReadTestIdentity gameDesignClient, + SelectionReadTestIdentity accountServer, + SelectionReadTestIdentity worldManagementServer) {} + private static SelectionReadTestIdentity issue( Path root, Path caStore, String alias, String namespace, String workload, boolean server) throws Exception { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java index 8f59504bac..31d2ff84fa 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java @@ -10,6 +10,7 @@ import java.time.LocalDateTime; import java.util.List; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; import net.firedevops.firemud.gamedesign.client.EntityManagementClient; @@ -24,6 +25,8 @@ import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -68,7 +71,7 @@ void collectFullVersionParticipantDigestsPassesWhenParticipantsConverge() { any(PublicationDigestRequestBinding.class))) .thenReturn( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null)); + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null)); when(entityManagementClient.getDraftDesignDigestForVersion( any(PublicationDigestRequestBinding.class))) .thenReturn( @@ -92,6 +95,10 @@ void collectFullVersionParticipantDigestsPassesWhenParticipantsConverge() { assertEquals(5, digests.size()); assertEquals("WORLD_MANAGEMENT", digests.get(0).participantKey()); + assertEquals( + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + "WORLD_MANAGEMENT"), + digests.get(0).digestSchemaVersion()); assertDoesNotThrow(() -> service.assertGatePassed(version, digests)); PublicationDigestRequestBinding expectedBinding = @@ -120,7 +127,7 @@ void fullVersionGateRejectsUnavailableGameLogicManifest() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), new PublishParticipantDigestDto( @@ -139,8 +146,9 @@ void fullVersionGateRejectsUnavailableGameLogicManifest() { assertTrue(thrown.getMessage().contains("GAME_LOGIC")); } - @Test - void fullVersionGateFailsClosedForUnsupportedSchema() { + @ParameterizedTest + @ValueSource(ints = {2, 4}) + void fullVersionGateRejectsObsoleteAndUnknownWorldSchemas(int worldSchema) { VersionDto version = new VersionDto( 7L, @@ -157,13 +165,13 @@ void fullVersionGateFailsClosedForUnsupportedSchema() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", worldSchema, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), new PublishParticipantDigestDto( "GAME_LOGIC", "7", "version:7", "digest-logic", 1, null, null), new PublishParticipantDigestDto( - "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 4, null, null), + "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 5, null, null), new PublishParticipantDigestDto( "GAME_DESIGN_CONTROL_PLANE", "7", "version:7", "digest-design", 1, null, null)); @@ -171,6 +179,7 @@ void fullVersionGateFailsClosedForUnsupportedSchema() { assertThrows( PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); assertEquals(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, thrown.failureCode()); + assertTrue(thrown.getMessage().contains("WORLD_MANAGEMENT")); } @Test @@ -191,7 +200,7 @@ void fullVersionGateChecksEachParticipantAgainstItsOwnDigestSchema() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( "AUTOMATION_SCRIPTING", "7", "version:7", "digest-script", 5, null, null), new PublishParticipantDigestDto( @@ -227,7 +236,7 @@ void fullVersionGateRejectsObsoleteAutomationDigestSchema() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), new PublishParticipantDigestDto( @@ -316,9 +325,9 @@ void fullVersionGateFailsClosedForDuplicateParticipantKey() { List digests = List.of( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world-2", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world-2", 3, null, null), new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), new PublishParticipantDigestDto( @@ -353,7 +362,7 @@ void fullVersionGateFailsClosedForNullParticipantObservation() { List digests = java.util.Arrays.asList( new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 2, null, null), + "WORLD_MANAGEMENT", "7", "version:7", "digest-world", 3, null, null), null, new PublishParticipantDigestDto( "ENTITY_MANAGEMENT", "7", "version:7", "digest-entity", 1, null, null), @@ -530,7 +539,7 @@ void scriptPatchGateFailsClosedForWrongParticipantSet() { 7L, "script-patch:patch-1", "digest-world", - 2, + 3, null, null)); From 67a665036c04b155f83c252e606cefbc91f8fe4a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 10:57:09 +1300 Subject: [PATCH 033/129] Add authenticated World freeze producer and exact asset snapshot proof --- .../game-design-service/version-control.md | 2 +- .../game-logic-service/runtime-and-data.md | 14 +- .../world-management-service/api-contracts.md | 6 +- ...ame-authoring-publishing-and-activation.md | 16 +- ...ted_draft_publication_freeze_service.proto | 51 +++ ...horizationMtlsPostgresIntegrationTest.java | 19 +- ...nAuthorizationPostgresIntegrationTest.java | 29 +- .../AccountControlUiOwnerSourcesFixture.java | 10 +- ...dSelectedDraftPublicationFreezeClient.java | 159 +++++++ ...electedDraftPublicationFreezeEvidence.java | 225 ++++++++++ ...lectedDraftPublicationFreezeGrpcCodec.java | 157 +++++++ ...ectedDraftPublicationFreezeClientTest.java | 165 +++++++ ...edDraftPublicationFreezeGrpcCodecTest.java | 153 +++++++ .../VersionAssetPublicationRepository.java | 20 +- ...setPublicationPostgresIntegrationTest.java | 318 ++++++++++++++ ...VersionAssetPublicationRepositoryTest.java | 52 +++ .../WorldDraftGraphApplicationRepository.java | 71 +++ ...ctedDraftPublicationFreezeGrpcService.java | 132 ++++++ ...SelectedDraftPublicationFreezeService.java | 114 +++++ ...uthorizedDraftPostgresIntegrationTest.java | 81 +++- ...aphApplicationPostgresIntegrationTest.java | 3 +- ...DraftPublicationFreezeGrpcServiceTest.java | 153 +++++++ ...ctedDraftPublicationFreezeRequestTest.java | 412 ++++++++++++++++++ 23 files changed, 2301 insertions(+), 61 deletions(-) create mode 100644 protos/world-management/v1/world_selected_draft_publication_freeze_service.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepositoryTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcService.java create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 3acf9cf70e..35e9f0a881 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -130,7 +130,7 @@ The shared golden vectors are `FULL_VERSION` `{tenantId=tenant-alpha, versionId= **Implementation status:** The four `GetDraftDesignDigest` receivers authenticate a distinct Game Design publication workload certificate, enforce an exact method allowlist, and reject other workloads and user/admin JWT substitution before content read. The shared request contract carries and validates tenant, complete typed scope, stable publish request, derived workflow identity, and the framed request digest; Game Design exact-compares each response's tenant and full scope before gating it. Script-patch participant evidence and the protected Game Design publication read now retain the exact base-version/patch pair. Automation's schema-5 script-patch content digest includes the retained base version; its full digest input remains tenant-wide, and Game Design still lacks an exact version-to-template/asset mapping for its control-plane content digest. Local negative tests do not replace live mounted-certificate, Temporal activity, or multi-version owner proof. -Game Logic's owner-local full-version manifest and provenance remain unproved. Its digest receiver therefore rejects full-version requests without returning a participant digest, and Game Design fails the required participant gate rather than accepting the former fixed empty `ownedDraftRuleRows` hash and synthetic `version:` applied commit. Full-version publication remains unavailable until Game Logic can attest under a defined owner-local manifest; script-patch publication does not require the Game Logic participant. +Game Logic's retained selected-release manifest and source-operation provenance remain unproved. Its digest receiver therefore rejects full-version requests without returning a participant digest, and Game Design fails the required participant gate rather than accepting the former fixed empty `ownedDraftRuleRows` hash and synthetic `version:` applied commit. Game Design remains the authoring and revision-history owner for authored gameplay rule inputs; its source operation must hand Game Logic the complete selected tenant/version/commit input set with current authority and operation-bound mutation authorization. Game Logic validates and immutably retains that evidence, then owns its participant and dedicated ability-schema attestations. The target ownership and input boundary are defined in the [Game Logic Draft Digest Contract](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) and the authoring shapes in [Ability & Action Design Tools](./ability-action-tools.md); this handoff is not current producer or intake proof. Full-version publication remains unavailable until Game Logic can attest under that contract; script-patch publication does not require the Game Logic participant. #### Launch and attestation read authorization (target state) diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index 512adc1660..b60710f507 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -6,7 +6,7 @@ This document defines the Game Logic Service runtime model, dependency ownership The sections below define the target-state runtime contract. Current implementation and proof status is: -- Full-version digest reads fail closed because Game Logic lacks an owner-local manifest and provenance sufficient to attest the selected version's rule inputs. It does not return an empty-manifest attestation or infer an empty authored set from absent storage. The [API implementation status](api-contracts.md#implementation-status) records this publication prerequisite; the Draft digest contract below defines the required owner boundary, not completed producer proof. +- Full-version digest reads fail closed because Game Logic lacks the retained selected-release manifest and source-operation provenance needed to attest the selected version's rule inputs. It does not return an empty-manifest attestation or infer an empty authored set from absent storage. The [API implementation status](api-contracts.md#implementation-status) records this publication prerequisite; the Draft digest contract below defines the required owner boundary, not completed producer or intake proof. Runtime activation remains unavailable until publication carries the required release attestation. - Same-type Game Logic takeover behind an existing edge connection is target behavior, but suppression of a client-visible reconnect after an ordinary qualifying Game Logic restart remains implementation or proof debt under ADR 0013. - Target: `SendCommunication` and every other player-delegated gameplay RPC propagate one complete, validated typed `PlayerExecutionContext` from Game Session through Game Logic and onward. Game Logic validates the context against request and owner evidence, never treats caller-supplied identifiers as authority, remains stateless, and owns semantic gameplay outcomes; Game Session owns session, reconnect, and presentation state. This is the ADR 0024 target contract. - Current implementation gap: the live `SendCommunicationRequest` is still a flat schema with tenant/session/character/account, communication/text and target metadata, room, game-instance, speaker, and effect fields plus legacy `session_attestation`; its current proto does not carry typed `playableStateNamespaceId`, `playableStateScope`, region/epoch, pointer, or admitted-bundle fields. Complete typed-context propagation is therefore not current behavior or proof. @@ -40,13 +40,23 @@ Role classification: Game Logic is a digest-gate participant for full publishes, For full-version publish gating, this service is still a required digest participant even though it does not orchestrate publish-workflow steps. It must expose `GetDraftDesignDigest(tenantId, versionId)` and publish a service-local digest input manifest with: -- included objects such as version-scoped rule and configuration tables this service owns that affect runtime command behavior; +- included objects and source ownership for the complete effective, version-scoped set of supported command inputs that affect runtime command behavior; - excluded objects such as runtime queues, caches, telemetry tables, and other non-launchability data; - canonicalization rules covering stable ordering, normalization, and null or default handling before hashing; and - `digestSchemaVersion` bump criteria, where any include, exclude, or canonicalization change requires an explicit schema bump and replay or re-record workflow. Publish gating must fail closed if this service cannot attest a digest under its documented manifest for the reported `digestSchemaVersion`. +### Selected-Release Rule Inputs and Intake + +Game Design remains the authoring and revision-history owner for authored gameplay rule inputs. Game Logic owns validation and immutable retention of the selected release's rule-input evidence, and attests only the exact selected tenant, version, and applied commit received through an authenticated, operation-bound source operation. A workload identity by itself does not authorize that mutation; the current authority and the source operation's mutation authorization must remain bound through commit. The producer handoff and retained manifest are target behavior and are not established by the current digest receiver. + +The retained input set must be complete for the supported command inputs effective in that version. It includes supported ability and action definitions and the referenced actor-state, resource, condition, and effect catalogs; command and action metadata including admission tags; disposition and continuous-overlay policy; observation, targeting, target-selection, and default target-set bindings; and cost, cooldown, feedback, or lifecycle declarations when they are part of the selected authoritative source. The authoring shapes and ownership remain defined by [Ability & Action Design Tools](../game-design-service/ability-action-tools.md) and the owning domain contracts. This list defines the completeness boundary, not a new wire schema or an additional execution engine. Unknown or unsupported authored inputs make intake and attestation fail closed; they must not be filtered out to produce an apparently empty or partial manifest. + +Intake is a separate, mutation-authorized source operation. `GetDraftDesignDigest` remains a read-only full-version publication read over the already retained, exact-version evidence; it does not populate or repair that evidence. An empty selected input set is attestable only when an authenticated source operation proves the complete owner inventory for the exact selected commit is empty. Missing storage, a missing producer, or absent rows are not evidence of an empty authored set. + +The full-version manifest and the dedicated `abilitySchemaDigest` share the selected commit and Game Logic's existing canonicalization and `digestSchemaVersion` contract, but they attest distinct scopes. The aggregate full-manifest `contentDigest` is not an ability-schema digest, and neither the Automation & Scripting digest nor Game Design's control-plane digest substitutes for either Game Logic attestation. Any change to the dedicated ability-schema input set or its canonicalization requires the same explicit schema bump and digest replay or re-record process as other manifest changes. This contract governs publication evidence only; it does not authorize activation of unpublished rules or make Game Logic a participant in Game Design's publication workflow mutations. Game Logic does not read an admin database for runtime rules. + ## Redis Role and Prefixes ### Coordination Redis diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 05b5b64afb..8517d3497c 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -20,8 +20,8 @@ This API contract is target-state canonical; implementation coverage is partial - `ListRoomOccupants` – **target state:** returns the authoritative typed occupant list for actors in a room, scoped by `RoomInstanceRef`. The current LOOK path is fixture-backed and has no World-owned location/occupancy persistence or authoritative read/write surface; it must not be treated as gameplay occupancy truth. - `ApplyRoomAmbientStatePatch` – applies a typed ambient fact patch to the target runtime scope under expected epoch/version preconditions and an operation/aggregate/request-digest-bound guard derived from the root `EffectId`; matching replay returns the durable prior result and a conflicting identity or payload fails closed. - `GetDraftDesignDigest` – returns the publish-gating digest for Draft world templates using the typed scope request `GetDraftDesignDigestRequest { tenantId, scope: oneof { versionId, scriptPatchVersion } }`. World Management supports `versionId` scope only and must return `UNSUPPORTED_SCOPE` for `scriptPatchVersion`. -- `BeginVersionPublicationFreeze` – **Target state:** starts or exactly replays the durable WMS owner freeze for one `(tenantId, versionId)` publication request and returns the request/fence/epoch/digest checkpoint acknowledgement defined below. It is not present in the current proto or implementation. -- `CompleteVersionPublication` – **Target state:** exactly replays or terminalizes the same WMS freeze with a `PUBLISHED` or `ABORTED` outcome and matching bundle/digest evidence. It is not present in the current proto or implementation. +- `BeginVersionPublicationFreeze` – starts or exactly replays the durable WMS owner freeze for one `(tenantId, versionId)` publication request and returns the request/fence/epoch/digest checkpoint acknowledgement defined below. A closed standalone proto, strict client and owner-resolving receiver are construction components only; runtime registration and the complete producer handoff remain unavailable. +- `CompleteVersionPublication` – **Target state:** exactly replays or terminalizes the same WMS freeze with a `PUBLISHED` or `ABORTED` outcome and matching bundle/digest evidence. Unregistered terminal composition and storage exist, but a registered completion RPC and genuine composed terminal handoff remain unavailable. - `ValidateWorldUpgradeMappings` – validates world-owned durable references and approved remap sets for replacement-instance cutover to a target `(tenantId, versionId)`. - `PrepareWorldInstance` – creates or reuses the canonical `PREPARING` world lifecycle row for a resolved launch descriptor, validates release-bundle and `versionStateEpoch` proof against Game Design, and materializes first-cut instance topology rows without admitting gameplay yet. - `ActivatePreparedWorldInstance` – performs the fenced `PREPARING -> ACTIVE` lifecycle transition after Game Session has finished local start-up work for the same `gameInstanceId`. @@ -84,7 +84,7 @@ World Management exposes design-time APIs used by Game Design to write Draft tem ### Publication freeze and terminal handoff (target state) -The publication-freeze operations below remain unregistered target contract surfaces. Current construction includes owner-lock/freeze persistence, immutable terminal storage, a selected-fresh-graph checkpoint callback and a standalone selected-publication composition; these do not supply a registered publication-freeze RPC or complete owner handoff. The callback derives the selected commit from an actual Account-bound World `APPLIED` result and rechecks the complete retained graph against current topology and epochs under the shared owner lock. The standalone composition additionally obtains authenticated Game Design selection/current-Draft and Account held-order reads, retaining the original Account correlation with the first freeze. It does not establish the generic highest-applied-commit digest contract. No current caller may infer a public freeze, publication, or terminal owner result from internal storage, a digest, a remote `GetVersionState` read, or a Temporal run identity. Current capability and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The publication-freeze operations below remain unregistered target contract surfaces. Current construction includes owner-lock/freeze persistence, immutable terminal storage, a selected-fresh-graph checkpoint callback and a standalone selected-publication composition; these do not supply a registered publication-freeze RPC or complete owner handoff. The closed standalone freeze transport authenticates the exact same-namespace Game Design workload before decoding and resolves the complete private World owner binding from the immutable retained selected `APPLIED` application, never from caller-supplied private IDs or a topology plan. The callback rechecks the complete retained graph against current topology and epochs under the shared owner lock. The composition additionally obtains authenticated Game Design selection/current-Draft and Account held-order reads, retaining the original Account correlation with the first freeze. Its acknowledgement is the committed freeze event, not the current terminal phase or admission authority; exact replay preserves the original fence and owner-observed epoch without recapturing mutable remote authority. It does not establish the generic highest-applied-commit digest contract. No current caller may infer a public freeze, publication, or terminal owner result from internal storage, a digest, a remote `GetVersionState` read, or a Temporal run identity. Current capability and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). `BeginVersionPublicationFreeze` accepts exactly: 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 d543e64a71..ae471fd9c8 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 @@ -6,9 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Published-head `9158561db4505e730274ac2c1f00069631481f9e` [Validation run 37844737121](https://github.com/benhook1013/FireMUD/actions/runs/37844737121) completed with 36 successful jobs, three failures (Account, World and the aggregate gate), and one skipped tooling-contract job. Physical integration XML records 240 Account cases with three failures, 206 World cases with two failures, and 75 Game Design cases with no failures; all have zero skips and errors. All seven isolated WAL cases executed and passed, without changing V92's conservative production denial or proving production adoption. The Account failures are source-event guards correctly rejecting test probes that directly changed a role without using the real Account owner; the correction routes those probes through its atomic authority/event update. World requires endpoint configuration before strict client construction and a post-terminal snapshot assertion against committed `PUBLISHED`, not the earlier `FROZEN` state. These fixture corrections still require corrected-head physical execution. The Account producer/reader and Game Design selected-owner mTLS cases passed, but their upstream/terminal fixtures remain stipulated rather than genuine composed owner authority. Owner jobs checked out merge `503db73556970c9baf1c26176c601bdbcb8b4668`, tree `9bdedfe9be1f911bba365c50972f04f76671accb`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and `9158561db4505e730274ac2c1f00069631481f9e`; the live target differs from the recorded integrated base, so intended-parent alignment remains open. Security, CodeQL, License and Kustomize checks passed. The dependency-deferred duplicate Validation run supplies no additional runtime proof. + Published-head `2560d12a8265db943a06e43d1e9e261bb2cdd923` [Validation run 37840711622](https://github.com/benhook1013/FireMUD/actions/runs/37840711622) finished red: 36 jobs passed, Account/World/the aggregate gate failed, and one tooling contract job skipped. Its physical XML records 233 Account cases with 208 failures, 206 World cases with 42 failures, and 75 Game Design cases with no failures; all have zero skips and errors. V107's PL/pgSQL syntax error blocked Account initialization and two World cases. All seven isolated WAL tests failed during migration setup, before their proof logic; this is neither WAL execution proof nor a new V92 durability verdict. World's other failures expose stale terminal fixtures missing V53 qualification (36 cases) and four terminal fixtures incorrectly entering unsupported generation/spawn preparation. The bounded syntax and fixture repairs require corrected-head physical execution; no production qualification or generation-intent guard may be weakened. Game Session and TCP Gradle checks passed with the bounded resource profile. Actual owner jobs checked out synthetic merge `e2bdaf5d011ba97d9a407183892e9ec7b069a909`, tree `1fb483d5c7ed53f27b483587a38909181aa3316b`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and `2560d12a8265db943a06e43d1e9e261bb2cdd923`. The live target had advanced 21 commits/33 paths beyond recorded base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`, with no Account/Game Design/World service differences; this explains composition but does not close intended-parent alignment. Substantive [CodeQL run 37840711613](https://github.com/benhook1013/FireMUD/actions/runs/37840711613) succeeded. Its dependency-deferred duplicate supplied no additional analysis; likewise metadata-only Validation run 37840712794 supplied no runtime proof. -The current publication handoff batch has passing local unit XML for 316 Common, 1,079 Account, 348 Game Design and 540 World cases, plus seven non-database Account integration cases. All 510 database integration definitions skip without Docker: 228 Account, 76 Game Design and 206 World. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. The consolidated Common/Account/Game Design gate failed solely on an unnecessary new receiver suppression; removing it and rerunning Account formatting/main static analysis/packaging plus the complete World gate passed. Common and Game Design full gates, all three service boot jars and the remaining Account static gates passed. The subsequent Game Design full gate passed after adding composed-command PostgreSQL proof and aligning the World schema gate. Links and Markdown also passed; Flyway sanity covers 12 sets / 246 versioned files. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. +The current publication handoff batch has passing local unit XML for 321 Common, 1,079 Account, 351 Game Design and 546 World cases, plus seven non-database Account integration cases. All 515 database integration definitions skip without Docker: 228 Account, 81 Game Design and 206 World. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. Consolidated validation found an intentionally retained test throwable requiring the existing narrow test-collector suppression and one unused fixture variable; neither correction changes production guards. Common's full gate passed in the combined run; corrected Account and World full gates passed in the next run, and Game Design's full gate passed after removing the unused fixture variable. All three service boot jars, links and Markdown passed; Flyway sanity covers 12 sets / 246 versioned files. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. Published-head `5132fb96b98f2d33b9db5d09d763aebb63efafb2` [Validation run 37834941641](https://github.com/benhook1013/FireMUD/actions/runs/37834941641) executed 229 Account, 75 Game Design and 202 World owner integration cases without skips. Game Design passed; Account retained one V92 original-acknowledgement WAL-coverage denial, and four World historical-upgrade fixtures failed after the additive full-XID column changed their copy/snapshot shapes. The bounded fixture correction preserves all historical fields and explicitly proves the new stamp stays null; corrected-head physical execution remains required. Game Session and TCP Proxy failed in dependent Java compilation with heap exhaustion, before their owner integration tests executed. The runner used synthetic merge `6d8435b7e31f5306defe357703139ccaa23e3fe6` with first parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`; these results do not close actual-parent alignment. Passing source intake mTLS cases do not separately establish the complete V53 qualification or genuine publication boundary. @@ -16,7 +18,7 @@ The terminal construction adds V54's bounded operation-frame check and repositor Expanded Game Design and World terminal repository/loopback-mTLS definitions retain actual local owner storage while stipulating upstream authorities. Account settlement's loopback-mTLS definition exercises its real creator/order/storage with two distinct strict clients, but the remote terminal endpoints and incoming Game Design context are stipulated. The independent Account readback connection checks commit before the second owner transaction; this is not an actual network lost-acknowledgement injection. These definitions require corrected-head physical execution and cannot establish a genuine multi-owner publication chain by themselves. The bounded CI heap-profile repair preserves full matrix validation and packaging tasks; the `2560d12a` Game Session and TCP jobs passed under that profile, without proving every future composed head. -The isolated Account WAL investigation is test-only and leaves V92's conservative production denial unchanged. Its seven dedicated PostgreSQL 16 definitions compile/discover but all skip locally without Docker. They define transactional immutable locators, exact target COMMIT readback and restricted-reader recovery; synthetic ambiguity/identity/capability classifications do not prove physical epoch wrap, promotion, WAL recycling, an unrelated unflushed tail or insufficient target flush. Extension feasibility, physical positive/negative execution, locator retention and any production adoption remain separate gates. The shared PostgreSQL 18 baseline does not change the Account admission executors' PostgreSQL 16-only guards. +The isolated Account WAL investigation is test-only and leaves V92's conservative production denial unchanged. All seven dedicated PostgreSQL 16 cases executed and passed in the `9158561` CI above; they still skip locally without Docker. They exercise transactional immutable locators, exact target COMMIT readback and restricted-reader recovery. Synthetic ambiguity/identity/capability classifications do not prove physical epoch wrap, promotion, WAL recycling, an unrelated unflushed tail or insufficient target flush. Production extension feasibility, additional physical failure/retention cases and any adoption remain separate gates. The shared PostgreSQL 18 baseline does not change the Account admission executors' PostgreSQL 16-only guards. Overseer-owned isolated [Pod admission run 37830726704](https://github.com/benhook1013/FireMUD/actions/runs/37830726704) passed the Account and Game Session CREATE/adversarial matrices plus UPDATE and ephemeral-container checks; Overseer reported the owned cluster deleted after the run. This is admission-only evidence. CNI/socket routing, kubelet UID/process correspondence, replacement races, shared-key closure and promotion readiness remain unproved; duplicate-SPKI rejection and activation denial are unchanged. @@ -24,7 +26,9 @@ The [immutable selected-Draft owner read](../../architecture/microservices/game- The legacy World numeric mutation route lacks the target shared-lock handoff, but the existing canonical-tenant manifest and mapped-row guards deny its writes to the exact fresh canonical target. The current composition adds negative PostgreSQL definitions through the real mutation service, deriving private selectors from retained mapping evidence and checking unchanged content, mappings, epochs, ledger, application and freeze history. These definitions have not yet executed physically; they do not justify opening the legacy route or claiming its broader target contract complete. -The World selected-fresh-graph checkpoint callback derives its commit identity from the exact retained Account-bound `APPLIED` application, rather than a caller-supplied checkpoint. Under the shared owner lock it rechecks the complete current graph and epoch set and computes the schema-3 content digest. Construction CI at `60c507243987705094a3028e0b46f3bccd5d9504` executed the actual Account-order-to-World-APPLIED and selected-checkpoint cases. The standalone selected-publication freeze composition obtains authenticated immutable selection, current Game Design Draft state and exact Account held-order reads outside SQL, then retains the complete Account binding atomically with the first World freeze. V53 denies late qualification of historical attempts. Exact committed retry verifies the stored order before recapturing mutable authority. The revised combined PostgreSQL definition uses the original owner-issued creator credential to obtain a real distinct Account publication order, reads its actual `HELD` state over strict loopback mTLS, and invokes the World freeze composition for first commit and exact retry. Game Design selection/current-Draft endpoints and the incoming Game Design caller context remain explicit fixture stipulations. Source protection is checked before and after freeze, but the original Draft order also remains pending, so writer denial does not isolate publication as its sole cause. The revised qualification/rollback definitions still require physical execution. This does not change the generic digest's synthetic highest-commit limitation, register a freeze RPC, settle either owner, or establish end-to-end publication authority. +The World selected-fresh-graph checkpoint callback derives its commit identity from the exact retained Account-bound `APPLIED` application, rather than a caller-supplied checkpoint. Under the shared owner lock it rechecks the complete current graph and epoch set and computes the schema-3 content digest. Construction CI at `60c507243987705094a3028e0b46f3bccd5d9504` executed the actual Account-order-to-World-APPLIED and selected-checkpoint cases. The standalone selected-publication freeze composition obtains authenticated immutable selection, current Game Design Draft state and exact Account held-order reads outside SQL, then retains the complete Account binding atomically with the first World freeze. V53 denies late qualification of historical attempts. The new closed freeze transport owner-resolves the retained APPLIED plan without accepting caller-supplied private World identities or topology. Its acknowledgement retains the committed freeze event and owner-observed epoch, not terminal publication or admission authority. Exact committed retry verifies the stored order before recapturing mutable authority. The revised combined PostgreSQL definition uses the original owner-issued creator credential to obtain a real distinct Account publication order, reads its actual `HELD` state over strict loopback mTLS, and invokes first freeze and exact retry through a fresh authenticated Game Design-to-World socket. Game Design selection/current-Draft endpoints remain explicit fixture stipulations. Source protection is checked before and after freeze, but the original Draft order also remains pending, so writer denial does not isolate publication as its sole cause. The corrected qualification/rollback and transport definitions still require physical execution. This does not change the generic digest's synthetic highest-commit limitation, register a freeze RPC, settle either owner, or establish end-to-end publication authority. + +The bounded Game Logic manifest contract is recorded at its [canonical owner](../../architecture/microservices/game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake), but its producer and intake remain unimplemented. Game Design currently retains command-definition and realm-entry-policy source captures; the command empty-genesis receipt does not establish a complete empty ability/catalog inventory. Complete authored-input inventory, immutable Game Logic retention, dedicated ability-schema evidence and Account-backed authorization through the intake commit remain concrete prerequisites. Unsupported or unknown families stay denied rather than being filtered into an empty manifest. Separately, the existing V37 asset mapping/snapshot storage now has explicit caller-transaction guards and five PostgreSQL proof definitions for exact version isolation, retained-row denial, immutable readback and source substitution; these local definitions skip without Docker and do not wire the production exporter. The standalone Game Design terminal owner read verifies complete original operation and terminal backing in an independent read-only repeatable-read snapshot. Its closed transport follows the [exact terminal-read contract](../../architecture/microservices/game-design-service/api-contracts.md#exact-publication-terminal-read); owner/transport unit definitions do not establish physical authenticated terminal composition. The receiver remains unregistered. World completion and distinct Account settlement now have unregistered construction components, but their genuine composed producer and physical proof remain open. @@ -172,7 +176,7 @@ The broader authored-action model is not complete. The locked expansion boundary ### Publication, Temporal Workflows, and Release Attestation -Asset lifecycle status and proof remain partial: export is still tenant-wide and unscoped with only a process-local selection because durable `version_asset` mappings and `version_asset_export_item` snapshots are absent. Version-scoped readiness, lifecycle operation safety, and publication recovery remain unproved. The canonical upload, hosted-gate, version-scoped export, attestation, lifecycle, and purge rules are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions); this tracker records the current status and proof gaps without repeating those owner contracts. +Asset lifecycle status and proof remain partial: V37 and `VersionAssetPublicationRepository` provide durable `version_asset` mappings and export snapshot/item storage, but the live exporter does not consume them and still selects tenant-wide assets with only process-local retry evidence. V38's candidate-evidence columns are groundwork, not a proved pre-write export journal or immutable object readback. Version-scoped readiness, lifecycle operation safety, and publication recovery remain unproved. The canonical upload, hosted-gate, version-scoped export, attestation, lifecycle, and purge rules are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions); this tracker records the current status and proof gaps without repeating those owner contracts. Full-version and script-patch publication use the live durable `publish_attempt`/participant-observation framework. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence with focused proof remains incomplete. End-to-end full-version publication remains blocked because the Game Logic full-version owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; its implementation status is recorded in [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The canonical digest and participant contracts are owned by [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); this tracker records only those implementation/proof gaps. @@ -184,7 +188,7 @@ Temporal publication authorization has a distinct Game Design gRPC workload iden ### Published Asset Lifecycle -Current status/evidence: Game Design owns publication and the `version_asset_artifact` proof read, but the live export remains tenant-wide with only a process-local selection because durable `version_asset` mappings and export-item snapshots are absent. Published/active repair and retired-version handling retain fail-closed drift, and version-scoped readiness is not proven. Focused asset export, attestation, and lifecycle proof remains partial. +Current status/evidence: Game Design owns publication and the `version_asset_artifact` proof read. Durable mapping and snapshot storage exists under V37, but its production authoring/export callers are absent; live export remains tenant-wide with only a process-local selection. Published/active repair and retired-version handling retain fail-closed drift, and version-scoped readiness is not proven. Focused asset export, attestation, and lifecycle proof remains partial. Lifecycle status/proof is also incomplete: artifact and Version epoch checks lack database CAS; tombstone eligibility and failed-candidate abandonment are not fully implemented; post-bundle publish-failure reconciliation and durable ADR 0048 operation identity are absent. The canonical state, transition, purge, repair, and reachability rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions); this tracker records only implementation status and proof gaps. @@ -218,7 +222,7 @@ Game Design owns revision history, commits, version state, and publish orchestra - Inventory/equipment was a documentation-only authority decision with no runtime behavior change; its recorded proof is `./gradlew linkCheck lintMarkdown`. - Settings schema/reference generation and verification are available through `./gradlew updatePlatformSettingsDocs` and `./gradlew verifyPlatformSettingsDocs`; persistence, resolution, cache/invalidation, generation, and surfaced-domain coverage are complete at their recorded boundaries. - The broader domain's aggregate documentation checkpoint completed on 2026-08-14 Pacific/Auckland (2026-08-13 UTC): `./gradlew linkCheck lintMarkdown` checked 4,574 links (4,536 OK, 0 errors, 38 excluded) and 454 Markdown files with 0 issues; `bash dev-tools/tests/architecture-doc-contracts.sh` also passed separately (184 tests passed). -- Asset purge and publication proof remains incomplete. The owning [Asset Storage contract](../../architecture/microservices/game-design-service/asset-storage.md#api) defines purge eligibility, lifecycle ordering, and publication recovery; [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) defines the shared operation identity and replay boundary. Current implementation still lacks the required version-asset mappings, uses server-generated random purge workflow IDs, and lacks database CAS/affected-row and exact committed-bundle readback proof; these remain implementation gaps rather than completed lifecycle guarantees. +- Asset purge and publication proof remains incomplete. The owning [Asset Storage contract](../../architecture/microservices/game-design-service/asset-storage.md#api) defines purge eligibility, lifecycle ordering, and publication recovery; [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) defines the shared operation identity and replay boundary. Current implementation has mapping/snapshot storage but lacks its required authoring/export integration, uses server-generated random purge workflow IDs, and lacks database CAS/affected-row and exact committed-bundle readback proof; these remain implementation gaps rather than completed lifecycle guarantees. - The current Packet 5 documentation-only validation record is maintained in the canonical [design capability allocation](../design-alignment/design-capability-allocation.md#validation-and-proof-references); that ledger entry proves only the Packet 5 documentation/allocation checkpoint. It neither claims runtime proof for that parcel nor weakens the separately listed implementation proof and commands in this tracker. ## Active Gaps diff --git a/protos/world-management/v1/world_selected_draft_publication_freeze_service.proto b/protos/world-management/v1/world_selected_draft_publication_freeze_service.proto new file mode 100644 index 0000000000..587f2da6f1 --- /dev/null +++ b/protos/world-management/v1/world_selected_draft_publication_freeze_service.proto @@ -0,0 +1,51 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Standalone Game Design-to-World selected-publication freeze transport. The authenticated +// producer sends the exact Account order and immutable selection digest; World resolves the +// retained APPLIED graph and derives its private owner binding locally. +service WorldSelectedDraftPublicationFreezeService { + rpc BeginVersionPublicationFreeze(BeginVersionPublicationFreezeRequest) + returns (BeginVersionPublicationFreezeResponse); +} + +enum WorldSelectedDraftPublicationFreezePhase { + WORLD_SELECTED_DRAFT_PUBLICATION_FREEZE_PHASE_UNSPECIFIED = 0; + WORLD_SELECTED_DRAFT_PUBLICATION_FREEZE_PHASE_FROZEN = 1; +} + +message BeginVersionPublicationFreezeRequest { + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string canonical_version_id = 4; + string publication_request_id = 5; + int64 expected_version_state_epoch = 6; + // The lowercase SHA-256 hex digest of the complete immutable Game Design selection. + string request_digest = 7; + // Complete canonical AccountPublicationAuthorizationBinding bytes; lookup identity only, max 1 MiB. + bytes account_publication_authorization_binding = 8; +} + +message BeginVersionPublicationFreezeResponse { + // Echo every request field exactly, then return the complete committed World freeze tuple. + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string canonical_version_id = 4; + string publication_request_id = 5; + int64 expected_version_state_epoch = 6; + string request_digest = 7; + bytes account_publication_authorization_binding = 8; + string publication_fence = 9; + WorldSelectedDraftPublicationFreezePhase owner_freeze_phase = 10; + string applied_commit_id = 11; + string content_digest = 12; + int32 digest_schema_version = 13; + // Owner-observed epoch from the committed freeze, separately bound to the request expectation. + int64 version_state_epoch = 14; +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java index b41fcc5ea3..c487035522 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -585,13 +585,7 @@ public void readPublicationTerminal( NAMESPACE, order)); return null; })); - assertThat( - sources.tx( - () -> - sources.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", - sources.account.getId()))) - .isEqualTo(1); + assertThat(sources.tx(sources::changeRoleToAdmin).getRole()).isEqualTo("admin"); corruptReadback.set(true); assertThatThrownBy( () -> asGameDesign(() -> composition.settle(operation.canonicalBytes()))) @@ -626,14 +620,9 @@ private static void assertPending( repository.readHeld(order); return null; }); - assertThatThrownBy( - () -> - sources.tx( - () -> - sources.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", - sources.account.getId()))) - .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy(() -> sources.tx(sources::changeRoleToAdmin)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); } private static void requireAccountClient() { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index 46691a18c4..b8ad471d23 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -121,14 +121,9 @@ void exactTwoOwnerSettlementRollsBackAtomicallyThenReplaysAfterLostAcknowledgeme repository.readHeld(order); return null; }); - assertThatThrownBy( - () -> - f.tx( - () -> - f.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", - f.account.getId()))) - .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy(() -> f.tx(f::changeRoleToAdmin)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); byte[] originalBinding = order.canonicalBytes(); byte[] receipt = @@ -176,12 +171,7 @@ void exactTwoOwnerSettlementRollsBackAtomicallyThenReplaysAfterLostAcknowledgeme failure -> assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); - assertThat( - f.tx( - () -> - f.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()))) - .isEqualTo(1); + assertThat(f.tx(f::changeRoleToAdmin).getRole()).isEqualTo("admin"); // Even after the source changes, the original committed issuance and receipt replay. assertThat( f.tx( @@ -539,21 +529,14 @@ void sourceWriterCannotPassUncommittedSettlementAndCanRetryAfterItsCommit() thro // pending // transaction cannot release its protection to a different writer // connection. - return f.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", - f.account.getId()); + return f.changeRoleToAdmin(); })); assertThatThrownBy(() -> writer.get(10, java.util.concurrent.TimeUnit.SECONDS)) .isInstanceOf(java.util.concurrent.ExecutionException.class) .hasCauseInstanceOf(org.jooq.exception.DataAccessException.class); return null; }); - assertThat( - f.tx( - () -> - f.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()))) - .isEqualTo(1); + assertThat(f.tx(f::changeRoleToAdmin).getRole()).isEqualTo("admin"); } finally { executor.shutdownNow(); assertThat(executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 39c1ac966f..427086879a 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -88,6 +88,7 @@ final class AccountControlUiOwnerSourcesFixture { final DSLContext dsl; final TransactionTemplate transactions; final Account account; + final AccountRepository accounts; final UUID tenant = UUID.randomUUID(), request = UUID.randomUUID(), callerContext = UUID.randomUUID(); @@ -125,7 +126,7 @@ final class AccountControlUiOwnerSourcesFixture { var generations = new AccountAuthorityGenerationRepository(dsl); var outbox = new AccountAuthorityOutboxRepository(dsl); var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); - var accounts = new AccountRepository(dsl, sourceEvidence); + accounts = new AccountRepository(dsl, sourceEvidence); account = tx( () -> { @@ -378,6 +379,13 @@ T tx(Supplier action) { return transactions.execute(ignored -> action.get()); } + /** Uses the real owner to advance generation, fence and source event with the scalar role. */ + Account changeRoleToAdmin() { + Account current = accounts.findById(account.getId()).orElseThrow(); + current.setRole("admin"); + return accounts.save(current); + } + void assertNoIssuance() { assertThat(dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))).isZero(); assertThat(dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isZero(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClient.java new file mode 100644 index 0000000000..a193936f90 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClient.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.publication; + +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.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.WorldSelectedDraftPublicationFreezeServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for Game Design's exact World selected-publication freeze. */ +public final class WorldSelectedDraftPublicationFreezeClient + extends AbstractReloadingBlockingGrpcClient< + WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldSelectedDraftPublicationFreezeClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldSelectedDraftPublicationFreezeClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World selected-publication freeze client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World selected-publication freeze stub unavailable"); + } + initialized = true; + } + + /** Returns evidence only after exact World server identity and complete echo verification. */ + public WorldSelectedDraftPublicationFreezeEvidence begin(Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World selected-publication freeze requires no ambient owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World selected-publication freeze must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .beginVersionPublicationFreeze( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(request)); + try { + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid selected-publication freeze acknowledgement", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldSelectedDraftPublicationFreezeServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World selected-publication freeze client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "World selected-publication freeze 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 selected-publication freeze requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World selected-publication freeze requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World selected-publication freeze " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World selected-publication freeze " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java new file mode 100644 index 0000000000..1cc766cc5f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java @@ -0,0 +1,225 @@ +package net.firedevops.firemud.common.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact selected-publication freeze request and its committed World acknowledgement. */ +public final class WorldSelectedDraftPublicationFreezeEvidence { + private final Request request; + private final Acknowledgement acknowledgement; + + WorldSelectedDraftPublicationFreezeEvidence(Request request, Acknowledgement acknowledgement) { + this.request = Objects.requireNonNull(request, "request"); + this.acknowledgement = Objects.requireNonNull(acknowledgement, "acknowledgement"); + if (!request.equals(acknowledgement.request())) { + throw new IllegalArgumentException("World freeze acknowledgement changed its exact request"); + } + } + + public Request request() { + return request; + } + + public Acknowledgement acknowledgement() { + return acknowledgement; + } + + /** Complete exact request from Game Design; its Account bytes are correlation, not authority. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publicationRequestId, + long expectedVersionStateEpoch, + String requestDigest, + byte[] accountPublicationAuthorizationBinding) { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_ACCOUNT_BINDING_BYTES = 1_048_576; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World selected-freeze schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + requireUuid(canonicalTenantId, "canonicalTenantId"); + requireUuid(canonicalVersionId, "canonicalVersionId"); + if (expectedVersionStateEpoch <= 0L) { + throw new IllegalArgumentException("Expected Version state epoch must be positive"); + } + if (requestDigest == null || !SHA256.matcher(requestDigest).matches()) { + throw new IllegalArgumentException( + "Request digest must be 64 lowercase hexadecimal digits"); + } + if (accountPublicationAuthorizationBinding == null + || accountPublicationAuthorizationBinding.length == 0 + || accountPublicationAuthorizationBinding.length > MAX_ACCOUNT_BINDING_BYTES) { + throw new IllegalArgumentException( + "Complete bounded Account publication binding is required"); + } + accountPublicationAuthorizationBinding = accountPublicationAuthorizationBinding.clone(); + AccountPublicationAuthorizationBinding account = + AccountPublicationAuthorizationBinding.fromStored(accountPublicationAuthorizationBinding); + if (!Arrays.equals(accountPublicationAuthorizationBinding, account.canonicalBytes())) { + throw new IllegalArgumentException("Account publication binding is not canonical"); + } + var selection = account.input().selection(); + if (!account.tenantId().equals(canonicalTenantId) + || !selection.intent().canonicalVersionId().equals(canonicalVersionId) + || !selection.intent().publishRequestId().equals(publicationRequestId) + || !selection + .intent() + .expectedVersionStateEpoch() + .equals(Long.toString(expectedVersionStateEpoch)) + || !selection.digest().equals("sha256:" + requestDigest)) { + throw new IllegalArgumentException( + "World freeze request differs from the exact Account-bound immutable selection"); + } + // Also validates the canonical full-version request identity and stable workflow syntax. + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + publicationRequestId); + } + + public static Request create( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String publicationRequestId, + long expectedVersionStateEpoch, + String requestDigest, + AccountPublicationAuthorizationBinding accountBinding) { + Objects.requireNonNull(accountBinding, "accountBinding"); + return new Request( + SCHEMA_VERSION, + targetNamespace, + canonicalTenantId, + canonicalVersionId, + publicationRequestId, + expectedVersionStateEpoch, + requestDigest, + accountBinding.canonicalBytes()); + } + + @Override + public byte[] accountPublicationAuthorizationBinding() { + return accountPublicationAuthorizationBinding.clone(); + } + + /** Reconstructs the complete canonical original Account publication order. */ + public AccountPublicationAuthorizationBinding accountBinding() { + AccountPublicationAuthorizationBinding binding = + AccountPublicationAuthorizationBinding.fromStored(accountPublicationAuthorizationBinding); + if (!Arrays.equals(accountPublicationAuthorizationBinding, binding.canonicalBytes())) { + throw new IllegalArgumentException("Account publication binding is not canonical"); + } + return binding; + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && canonicalTenantId.equals(that.canonicalTenantId) + && canonicalVersionId.equals(that.canonicalVersionId) + && publicationRequestId.equals(that.publicationRequestId) + && expectedVersionStateEpoch == that.expectedVersionStateEpoch + && requestDigest.equals(that.requestDigest) + && Arrays.equals( + accountPublicationAuthorizationBinding, that.accountPublicationAuthorizationBinding); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + schemaVersion, + targetNamespace, + canonicalTenantId, + canonicalVersionId, + publicationRequestId, + expectedVersionStateEpoch, + requestDigest) + + Arrays.hashCode(accountPublicationAuthorizationBinding); + } + + private static void requireUuid(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + } + + /** Acknowledgement of the committed FROZEN event only, never a terminal or admission result. */ + public record Acknowledgement( + Request request, + long versionStateEpoch, + UUID publicationFence, + OwnerFreezePhase ownerFreezePhase, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); + + public Acknowledgement { + Objects.requireNonNull(request, "request"); + if (versionStateEpoch <= 0L || versionStateEpoch != request.expectedVersionStateEpoch()) { + throw new IllegalArgumentException( + "World-observed Version state epoch differs from the exact request expectation"); + } + if (publicationFence == null || NIL_UUID.equals(publicationFence)) { + throw new IllegalArgumentException("World publication fence must be a non-nil UUID"); + } + if (ownerFreezePhase != OwnerFreezePhase.FROZEN) { + throw new IllegalArgumentException("World freeze acknowledgement must be FROZEN"); + } + UUID selectedCommitId = + request.accountBinding().input().selection().selectedCommit().commitId(); + if (!selectedCommitId.toString().equals(appliedCommitId)) { + throw new IllegalArgumentException( + "World applied commit differs from the exact selected Draft commit"); + } + if (contentDigest == null || !CONTENT_DIGEST.matcher(contentDigest).matches()) { + throw new IllegalArgumentException( + "World content digest must be canonical lowercase SHA-256"); + } + if (digestSchemaVersion <= 0) { + throw new IllegalArgumentException("World digest schema version must be positive"); + } + } + + public String tenantId() { + return request.canonicalTenantId().toString(); + } + + public String versionId() { + return request.canonicalVersionId().toString(); + } + + public String publicationRequestId() { + return request.publicationRequestId(); + } + + public String requestDigest() { + return request.requestDigest(); + } + + public long versionStateEpoch() { + return versionStateEpoch; + } + } + + public enum OwnerFreezePhase { + FROZEN + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodec.java new file mode 100644 index 0000000000..a6baa81d6a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodec.java @@ -0,0 +1,157 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeRequest; +import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldSelectedDraftPublicationFreezePhase; + +/** Closed World selected-freeze wire mapping and exact request/acknowledgement validation. */ +public final class WorldSelectedDraftPublicationFreezeGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private WorldSelectedDraftPublicationFreezeGrpcCodec() {} + + public static BeginVersionPublicationFreezeRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + return BeginVersionPublicationFreezeRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setPublicationRequestId(request.publicationRequestId()) + .setExpectedVersionStateEpoch(request.expectedVersionStateEpoch()) + .setRequestDigest(request.requestDigest()) + .setAccountPublicationAuthorizationBinding( + ByteString.copyFrom(request.accountPublicationAuthorizationBinding())) + .build(); + } + + /** Decode only after the receiver authenticates the exact same-namespace Game Design peer. */ + public static Request fromRequest(BeginVersionPublicationFreezeRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "BeginVersionPublicationFreezeRequest"); + try { + return new Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + canonicalUuid(request.getCanonicalTenantId()), + canonicalUuid(request.getCanonicalVersionId()), + request.getPublicationRequestId(), + request.getExpectedVersionStateEpoch(), + request.getRequestDigest(), + boundedBytes(request.getAccountPublicationAuthorizationBinding().toByteArray())); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("World selected-freeze request is invalid", invalid); + } + } + + /** Builds only the complete committed owner-freeze acknowledgement tuple. */ + public static BeginVersionPublicationFreezeResponse toResponse(Acknowledgement acknowledgement) { + Objects.requireNonNull(acknowledgement, "acknowledgement"); + Request request = acknowledgement.request(); + return BeginVersionPublicationFreezeResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setCanonicalVersionId(request.canonicalVersionId().toString()) + .setPublicationRequestId(request.publicationRequestId()) + .setExpectedVersionStateEpoch(request.expectedVersionStateEpoch()) + .setRequestDigest(request.requestDigest()) + .setAccountPublicationAuthorizationBinding( + ByteString.copyFrom(request.accountPublicationAuthorizationBinding())) + .setPublicationFence(acknowledgement.publicationFence().toString()) + .setOwnerFreezePhase(toWirePhase(acknowledgement.ownerFreezePhase())) + .setAppliedCommitId(acknowledgement.appliedCommitId()) + .setContentDigest(acknowledgement.contentDigest()) + .setDigestSchemaVersion(acknowledgement.digestSchemaVersion()) + .setVersionStateEpoch(acknowledgement.versionStateEpoch()) + .build(); + } + + /** Checks exact request echo and the entire FROZEN acknowledgement tuple. */ + public static WorldSelectedDraftPublicationFreezeEvidence fromResponse( + Request expected, BeginVersionPublicationFreezeResponse response) { + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "BeginVersionPublicationFreezeResponse"); + if (response.getSchemaVersion() != expected.schemaVersion() + || !response.getTargetNamespace().equals(expected.targetNamespace()) + || !response.getCanonicalTenantId().equals(expected.canonicalTenantId().toString()) + || !response.getCanonicalVersionId().equals(expected.canonicalVersionId().toString()) + || !response.getPublicationRequestId().equals(expected.publicationRequestId()) + || response.getExpectedVersionStateEpoch() != expected.expectedVersionStateEpoch() + || response.getVersionStateEpoch() != expected.expectedVersionStateEpoch() + || !response.getRequestDigest().equals(expected.requestDigest()) + || !Arrays.equals( + response.getAccountPublicationAuthorizationBinding().toByteArray(), + expected.accountPublicationAuthorizationBinding())) { + throw new IllegalArgumentException("World changed the exact selected-freeze request"); + } + final Acknowledgement acknowledgement; + try { + acknowledgement = + new Acknowledgement( + expected, + response.getVersionStateEpoch(), + canonicalUuid(response.getPublicationFence()), + fromWirePhase(response.getOwnerFreezePhase()), + response.getAppliedCommitId(), + response.getContentDigest(), + response.getDigestSchemaVersion()); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("World freeze acknowledgement is invalid", invalid); + } + return new WorldSelectedDraftPublicationFreezeEvidence(expected, acknowledgement); + } + + private static WorldSelectedDraftPublicationFreezePhase toWirePhase(OwnerFreezePhase phase) { + return switch (phase) { + case FROZEN -> + WorldSelectedDraftPublicationFreezePhase + .WORLD_SELECTED_DRAFT_PUBLICATION_FREEZE_PHASE_FROZEN; + }; + } + + private static OwnerFreezePhase fromWirePhase(WorldSelectedDraftPublicationFreezePhase phase) { + return switch (phase) { + case WORLD_SELECTED_DRAFT_PUBLICATION_FREEZE_PHASE_FROZEN -> OwnerFreezePhase.FROZEN; + case WORLD_SELECTED_DRAFT_PUBLICATION_FREEZE_PHASE_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("World owner freeze phase must be FROZEN"); + }; + } + + private static byte[] boundedBytes(byte[] value) { + if (value.length == 0 + || value.length + > WorldSelectedDraftPublicationFreezeEvidence.Request.MAX_ACCOUNT_BINDING_BYTES) { + throw new IllegalArgumentException("Account publication binding is absent or oversized"); + } + return value; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID canonicalUuid(String value) { + if (value == null) throw new IllegalArgumentException("Canonical UUID required"); + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil UUID required"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Canonical non-nil UUID required", invalid); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java new file mode 100644 index 0000000000..e9dd79e460 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.AbstractStub; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +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.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.worldmanagement.v1.WorldSelectedDraftPublicationFreezeServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldSelectedDraftPublicationFreezeClientTest { + @Test + void requiresFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldSelectedDraftPublicationFreezeClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + assertThatThrownBy( + () -> + new WorldSelectedDraftPublicationFreezeClient( + new ServiceEndpointsProperties(), tls(directory), factory, "Test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void usesExactWorldServerIdentityBoundedDeadlineAndNoAmbientTransaction(@TempDir Path directory) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(factory.buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new WorldSelectedDraftPublicationFreezeClient(endpoints, tls(directory), factory, "test"); + try { + client.init(); + AbstractStub initialized = initializedStub(client); + assertThat(initialized.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(initialized.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/world-management-service"); + + var stub = + mock( + WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + setStub(client, stub); + var request = WorldSelectedDraftPublicationFreezeGrpcCodecTest.request(); + var response = + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse( + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + request, + request.expectedVersionStateEpoch(), + java.util.UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + request + .accountBinding() + .input() + .selection() + .selectedCommit() + .commitId() + .toString(), + "a".repeat(64), + 3)); + when(stub.beginVersionPublicationFreeze(any())).thenReturn(response); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.begin(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.begin(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(stub); + + var evidence = client.begin(request); + assertThat(evidence.request()).isEqualTo(request); + assertThat(evidence.acknowledgement().requestDigest()).isEqualTo(request.requestDigest()); + verify(stub).beginVersionPublicationFreeze(any()); + + when(stub.beginVersionPublicationFreeze(any())) + .thenReturn(response.toBuilder().setTargetNamespace("other").build()); + assertThatThrownBy(() -> client.begin(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid selected-publication freeze acknowledgement"); + when(stub.beginVersionPublicationFreeze(any())) + .thenThrow(Status.UNAVAILABLE.withDescription("offline").asRuntimeException()); + assertThatThrownBy(() -> client.begin(request)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + } finally { + client.close(); + } + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return tls; + } + + private static AbstractStub initializedStub(WorldSelectedDraftPublicationFreezeClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + private static void setStub( + WorldSelectedDraftPublicationFreezeClient client, + WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceBlockingStub + stub) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java new file mode 100644 index 0000000000..cb69a18f9e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java @@ -0,0 +1,153 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldSelectedDraftPublicationFreezePhase; +import org.junit.jupiter.api.Test; + +class WorldSelectedDraftPublicationFreezeGrpcCodecTest { + @Test + void roundTripsTheClosedRequestAndCompleteFrozenAcknowledgement() { + var request = request(); + var decoded = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(request)); + var acknowledgement = acknowledgement(request); + var evidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + + assertThat(decoded).isEqualTo(request); + assertThat(evidence.request()).isEqualTo(request); + assertThat(evidence.acknowledgement()).isEqualTo(acknowledgement); + assertThat(evidence.acknowledgement().requestDigest()).isEqualTo(request.requestDigest()); + } + + @Test + void rejectsUnknownFieldsMalformedBindingsAndNoncanonicalRequestValues() { + var wire = WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(request()); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatThrownBy( + () -> + WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + for (var changed : + List.of( + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setCanonicalTenantId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA").build(), + wire.toBuilder().setCanonicalVersionId("00000000-0000-0000-0000-000000000000").build(), + wire.toBuilder().setExpectedVersionStateEpoch(0).build(), + wire.toBuilder().setRequestDigest("A".repeat(64)).build(), + wire.toBuilder().setAccountPublicationAuthorizationBinding(ByteString.EMPTY).build(), + wire.toBuilder() + .setAccountPublicationAuthorizationBinding( + ByteString.copyFrom( + new byte + [WorldSelectedDraftPublicationFreezeEvidence.Request + .MAX_ACCOUNT_BINDING_BYTES + + 1])) + .build())) { + assertThatThrownBy(() -> WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsEchoSubstitutionUnknownFieldsAndNonFrozenOrIncompleteAcknowledgements() { + var request = request(); + var response = + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement(request)); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + for (BeginVersionPublicationFreezeResponse changed : + List.of( + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder() + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .build(), + response.toBuilder().setPublicationRequestId("different").build(), + response.toBuilder().setExpectedVersionStateEpoch(2).build(), + response.toBuilder().setVersionStateEpoch(2).build(), + response.toBuilder().setRequestDigest("0".repeat(64)).build(), + response.toBuilder() + .setAccountPublicationAuthorizationBinding(ByteString.copyFrom(new byte[] {1})) + .build(), + response.toBuilder().setPublicationFence("not-a-uuid").build(), + response.toBuilder() + .setOwnerFreezePhase( + WorldSelectedDraftPublicationFreezePhase + .WORLD_SELECTED_DRAFT_PUBLICATION_FREEZE_PHASE_UNSPECIFIED) + .build(), + response.toBuilder().setOwnerFreezePhaseValue(77).build(), + response.toBuilder().setAppliedCommitId(UUID.randomUUID().toString()).build(), + response.toBuilder().setContentDigest("not-a-digest").build(), + response.toBuilder().setDigestSchemaVersion(0).build(), + response.toBuilder().setUnknownFields(unknown).build())) { + assertThatThrownBy( + () -> WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + static WorldSelectedDraftPublicationFreezeEvidence.Request request() { + var selection = AuthoredDraftPublishSelectionReadGrpcCodecTest.binding(); + UUID actor = uuid("77777777-7777-4777-8777-777777777777"); + var account = + new AccountPublicationAuthorizationBinding( + uuid("88888888-8888-4888-8888-888888888888"), + uuid("99999999-9999-4999-8999-999999999999"), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}))); + return WorldSelectedDraftPublicationFreezeEvidence.Request.create( + "test", + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId(), + Long.parseLong(selection.intent().expectedVersionStateEpoch()), + selection.digest().substring("sha256:".length()), + account); + } + + private static Acknowledgement acknowledgement( + WorldSelectedDraftPublicationFreezeEvidence.Request request) { + return new Acknowledgement( + request, + request.expectedVersionStateEpoch(), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + OwnerFreezePhase.FROZEN, + request.accountBinding().input().selection().selectedCommit().commitId().toString(), + "a".repeat(64), + 3); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java index de00d10285..3e3dbf202c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java @@ -16,6 +16,8 @@ import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Owner-local persistence boundary for Draft asset mappings and durable export snapshots. */ @Repository @@ -36,9 +38,11 @@ public VersionAssetPublicationRepository(DSLContext dsl) { /** * Associates an ordinary source asset with an exact tenant-owned Draft Version. Numeric ids in - * this method are private Game Design owner keys and are not public identity aliases. + * this method are private Game Design owner keys and are not public identity aliases. The caller + * must hold a writable READ_COMMITTED transaction. */ public void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType) { + requireWritableReadCommittedTransaction(); requireTenantId(tenantId); if (versionId <= 0 || assetId <= 0) { throw new IllegalArgumentException("Version and asset owner keys must be positive"); @@ -95,9 +99,11 @@ public void associateDraftAsset(String tenantId, long versionId, long assetId, S /** * Freezes the current exact Draft mapping set or reads an earlier frozen snapshot. The caller - * must hold a transaction because the Version lock serializes mapping writes with first freeze. + * must hold a writable READ_COMMITTED transaction because the Version lock serializes mapping + * writes with first freeze. */ public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { + requireWritableReadCommittedTransaction(); requireTenantId(tenantId); if (versionNumber <= 0) { throw new IllegalArgumentException("Version number must be positive"); @@ -459,6 +465,16 @@ private static void requireTenantId(String tenantId) { } } + private static void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Version asset publication writes require caller-owned writable READ_COMMITTED transaction"); + } + } + private static void validateUsageKey(String usageKey) { if (usageKey == null || usageKey.isBlank()) { throw new IllegalStateException("Asset source file name cannot be a blank usage key"); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java new file mode 100644 index 0000000000..21a447a420 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java @@ -0,0 +1,318 @@ +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.charset.StandardCharsets; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Persistence proof for version-scoped asset selection. Fixtures create synthetic Game and Version + * rows through Game Design repositories; those fixture values are test inputs, not authenticated + * Account or Gameplay source authority. + */ +@Testcontainers(disabledWithoutDocker = true) +class VersionAssetPublicationPostgresIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final MigrationVersion V35 = MigrationVersion.fromVersion("35"); + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void exactTenantVersionMappingsExcludeUnmappedAssetsAndSnapshotSurvivesRepositoryRestart() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "a"); + Game otherOwner = saveGame(fixture, "b"); + Version selectedVersion = saveDraftVersion(fixture, owner, 1); + Version siblingVersion = saveDraftVersion(fixture, owner, 2); + Version foreignVersion = saveDraftVersion(fixture, otherOwner, 1); + GameAsset selected = saveAsset(fixture, owner, "selected.png", "selected-bytes"); + GameAsset sibling = saveAsset(fixture, owner, "sibling.png", "sibling-bytes"); + saveAsset(fixture, owner, "unmapped.png", "unmapped-bytes"); + GameAsset foreign = saveAsset(fixture, otherOwner, "foreign.png", "foreign-bytes"); + + assertThatThrownBy( + () -> associate(fixture, owner.getTenantId(), foreignVersion.getId(), selected.getId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact tenant Version row was not found"); + assertThatThrownBy( + () -> associate(fixture, owner.getTenantId(), selectedVersion.getId(), foreign.getId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact tenant game asset row was not found"); + assertThat(mappingCount(fixture, owner.getTenantId(), selectedVersion.getId())).isZero(); + associate(fixture, owner.getTenantId(), selectedVersion.getId(), selected.getId()); + associate(fixture, owner.getTenantId(), siblingVersion.getId(), sibling.getId()); + + VersionAssetPublicationRepository repository = fixture.publicationRepository(); + VersionAssetPublicationRepository.ExportSnapshot frozen = + inTransaction( + fixture, + () -> + repository.freezeOrReadSnapshot( + owner.getTenantId(), selectedVersion.getVersionNumber())); + + assertThat(frozen.canonicalTenantId()).isEqualTo(owner.getCanonicalTenantId()); + assertThat(frozen.canonicalVersionId()).isEqualTo(selectedVersion.getCanonicalVersionId()); + assertThat(frozen.items()) + .extracting(VersionAssetPublicationRepository.AssetSelection::usageKey) + .containsExactly("selected.png"); + assertThat(frozen.items().get(0).assetId()).isEqualTo(selected.getId()); + assertThat(frozen.items().get(0).bytes()).containsExactly(selected.getData()); + assertThat(frozen.items().get(0).contentDigest()).matches("sha256:[0-9a-f]{64}"); + + VersionAssetPublicationRepository restartedRepository = + new VersionAssetPublicationRepository(fixture.dsl()); + VersionAssetPublicationRepository.ExportSnapshot reloaded = + restartedRepository.readFrozenSnapshot( + owner.getTenantId(), selectedVersion.getVersionNumber()); + assertThat(reloaded.canonicalTenantId()).isEqualTo(frozen.canonicalTenantId()); + assertThat(reloaded.canonicalVersionId()).isEqualTo(frozen.canonicalVersionId()); + assertThat(reloaded.items()).hasSize(1); + assertThat(reloaded.items().get(0).usageKey()).isEqualTo("selected.png"); + assertThat(reloaded.items().get(0).assetId()).isEqualTo(selected.getId()); + assertThat(reloaded.items().get(0).bytes()).containsExactly(selected.getData()); + assertThat(reloaded.items().get(0).contentDigest()) + .isEqualTo(frozen.items().get(0).contentDigest()); + + VersionAssetPublicationRepository.ExportSnapshot retried = + inTransaction( + fixture, + () -> + restartedRepository.freezeOrReadSnapshot( + owner.getTenantId(), selectedVersion.getVersionNumber())); + assertThat(retried.items()).hasSize(1); + assertThat(retried.items().get(0).assetId()).isEqualTo(selected.getId()); + assertThat(retried.items().get(0).contentDigest()) + .isEqualTo(frozen.items().get(0).contentDigest()); + } + + @Test + void retainedVersionWithoutCanonicalSourceCannotReceiveAssetMapping() { + Fixture fixture = fixture(V35); + Game owner = saveGame(fixture, "c"); + Long retainedVersionId = insertUnqualifiedRetainedVersion(fixture.dsl(), owner.getTenantId()); + migrate(fixture.dataSource(), fixture.schema(), null); + GameAsset asset = saveAsset(fixture, owner, "retained.png", "retained-bytes"); + + assertThatThrownBy( + () -> associate(fixture, owner.getTenantId(), retainedVersionId, asset.getId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Version lacks a complete canonical owner identity"); + assertThat(mappingCount(fixture, owner.getTenantId(), retainedVersionId)).isZero(); + } + + @Test + void changedSourceBytesInvalidateCommittedSnapshotReadback() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "d"); + Version version = saveDraftVersion(fixture, owner, 1); + GameAsset asset = saveAsset(fixture, owner, "mutable-source.png", "content-original"); + associate(fixture, owner.getTenantId(), version.getId(), asset.getId()); + inTransaction( + fixture, + () -> fixture.publicationRepository().freezeOrReadSnapshot(owner.getTenantId(), 1)); + + fixture + .dsl() + .execute( + "UPDATE game_assets SET data = ? WHERE tenant_id = ? AND id = ?", + "content-replaced".getBytes(StandardCharsets.UTF_8), + owner.getTenantId(), + asset.getId()); + + assertThatThrownBy( + () -> + fixture + .publicationRepository() + .readFrozenSnapshot(owner.getTenantId(), version.getVersionNumber())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Frozen Version asset source bytes or mapping failed verification"); + } + + @Test + void associationAfterSnapshotFreezeIsRejected() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "e"); + Version version = saveDraftVersion(fixture, owner, 1); + GameAsset first = saveAsset(fixture, owner, "first.png", "first-bytes"); + GameAsset second = saveAsset(fixture, owner, "second.png", "second-bytes"); + associate(fixture, owner.getTenantId(), version.getId(), first.getId()); + inTransaction( + fixture, + () -> fixture.publicationRepository().freezeOrReadSnapshot(owner.getTenantId(), 1)); + + assertThatThrownBy( + () -> associate(fixture, owner.getTenantId(), version.getId(), second.getId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Version asset mappings are frozen by the durable export snapshot"); + assertThat(mappingCount(fixture, owner.getTenantId(), version.getId())).isEqualTo(1); + } + + @Test + void absentSnapshotIsNotReadAsAnEmptySelection() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "f"); + Version version = saveDraftVersion(fixture, owner, 1); + + assertThatThrownBy( + () -> + fixture + .publicationRepository() + .readFrozenSnapshot(owner.getTenantId(), version.getVersionNumber())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("No durable frozen Version asset snapshot exists"); + } + + private Fixture fixture(MigrationVersion target) { + String schema = "gd_asset_publication_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + migrate(dataSource, schema, target); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Fixture( + schema, + dataSource, + dsl, + transaction, + new GameRepository(dsl), + new VersionRepository(dsl), + new GameAssetRepository(dsl), + new VersionAssetPublicationRepository(dsl)); + } + + 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 Game saveGame(Fixture fixture, String tenantPrefix) { + Game game = new Game(); + game.setTenantId(tenantPrefix + "-" + UUID.randomUUID().toString().replace("-", "")); + game.setName("Version asset publication fixture"); + game.setDescription("Synthetic Game Design source row for persistence proof"); + return Objects.requireNonNull( + fixture.transaction().execute(status -> fixture.games().save(game))); + } + + private Version saveDraftVersion(Fixture fixture, Game game, int versionNumber) { + Version version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(versionNumber); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + version.setNotes("Synthetic version asset publication fixture"); + return Objects.requireNonNull( + fixture.transaction().execute(status -> fixture.versions().save(version))); + } + + private GameAsset saveAsset(Fixture fixture, Game game, String fileName, String contents) { + GameAsset asset = new GameAsset(); + asset.setTenantId(game.getTenantId()); + asset.setFileName(fileName); + asset.setContentType("image/png"); + asset.setData(contents.getBytes(StandardCharsets.UTF_8)); + return Objects.requireNonNull( + fixture.transaction().execute(status -> fixture.assets().save(asset))); + } + + private void associate(Fixture fixture, String tenantId, long versionId, long assetId) { + fixture + .transaction() + .execute( + status -> { + fixture + .publicationRepository() + .associateDraftAsset(tenantId, versionId, assetId, null); + return null; + }); + } + + private T inTransaction(Fixture fixture, java.util.function.Supplier action) { + return Objects.requireNonNull(fixture.transaction().execute(status -> action.get())); + } + + private long mappingCount(Fixture fixture, String tenantId, long versionId) { + Record countRecord = + Objects.requireNonNull( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) AS mapping_count FROM version_asset " + + "WHERE tenant_id = ? AND version_id = ?", + tenantId, + versionId)); + return Objects.requireNonNull(countRecord.get("mapping_count", Long.class)); + } + + private long insertUnqualifiedRetainedVersion(DSLContext dsl, String tenantId) { + Record insertedVersion = + Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch, " + + "script_patch_version, base_version_id, is_script_only, notes) " + + "VALUES (?, 9, 'FAILED', 3, NULL, NULL, FALSE, 'retained history') RETURNING id", + tenantId) + .fetchSingle()); + return Objects.requireNonNull(insertedVersion.get("id", Long.class)); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + TransactionTemplate transaction, + GameRepository games, + VersionRepository versions, + GameAssetRepository assets, + VersionAssetPublicationRepository publicationRepository) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepositoryTest.java new file mode 100644 index 0000000000..105e768b5f --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepositoryTest.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.stream.Stream; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class VersionAssetPublicationRepositoryTest { + private static final String TRANSACTION_REQUIRED = + "Version asset publication writes require caller-owned writable READ_COMMITTED transaction"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @ParameterizedTest + @MethodSource("invalidTransactionContexts") + void mappingAndSnapshotWritesRejectInvalidTransactionBeforeSql( + boolean transactionActive, boolean readOnly, Integer isolationLevel) { + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.setActualTransactionActive(transactionActive); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(isolationLevel); + DSLContext dsl = mock(DSLContext.class); + VersionAssetPublicationRepository repository = new VersionAssetPublicationRepository(dsl); + + assertThatThrownBy(() -> repository.associateDraftAsset("tenant", 1, 1, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessage(TRANSACTION_REQUIRED); + assertThatThrownBy(() -> repository.freezeOrReadSnapshot("tenant", 1)) + .isInstanceOf(IllegalStateException.class) + .hasMessage(TRANSACTION_REQUIRED); + + verifyNoInteractions(dsl); + } + + private static Stream invalidTransactionContexts() { + return Stream.of( + Arguments.of(false, false, null), + Arguments.of(true, true, TransactionDefinition.ISOLATION_READ_COMMITTED), + Arguments.of(true, false, TransactionDefinition.ISOLATION_SERIALIZABLE)); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java index 44f9d96499..6318b9dd48 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationService.CommitOrderProof; @@ -46,6 +47,76 @@ public Optional readCommitted( return Optional.of(readExact(application, rows.getFirst())); } + /** + * Resolves one exact immutable selected commit to its retained World APPLIED application. + * + *

The complete Game Design selection is only a lookup and equality constraint. This read + * derives the private World owner binding from persisted APPLIED evidence and never constructs a + * World operation, guesses a local owner key, or grants permission to freeze. + */ + Optional readSelectedPublicationApplication( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + AuthoredDraftPublishSelectionBinding suppliedSelection) { + requireCommittedRead(); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace is required"); + } + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + Objects.requireNonNull(suppliedSelection, "suppliedSelection"); + final AuthoredDraftPublishSelectionBinding selection; + try { + selection = + AuthoredDraftPublishSelectionBinding.fromStored( + suppliedSelection.canonicalJson(), suppliedSelection.digest()); + } catch (RuntimeException invalid) { + throw new ConflictException("World selected-publication lookup has invalid selection bytes"); + } + if (!selection.intent().canonicalTenantId().equals(canonicalTenantId) + || !selection.intent().canonicalVersionId().equals(canonicalVersionId)) { + throw new ConflictException( + "World selected-publication lookup differs from its canonical tenant or version"); + } + + DraftCommitBinding selectedCommit = selection.selectedCommit(); + var rows = + dsl.fetch( + selectSql() + " WHERE a.request_id=? OR a.commit_id=?", + selectedCommit.requestId(), + selectedCommit.commitId()); + if (rows.isEmpty()) return Optional.empty(); + if (rows.size() != 1) { + throw new ConflictException( + "World selected-publication request and commit identify conflicting applications"); + } + + Record row = rows.getFirst(); + WorldDraftGraphApplication application = reconstruct(row); + WorldDraftGraphAppliedResult result = readExact(application, row); + if (!"APPLIED".equals(result.status()) + || !selectedCommit.equals(application.operation().binding()) + || !Arrays.equals( + selectedCommit.canonicalBytes(), application.operation().binding().canonicalBytes()) + || !selectedCommit.digest().equals(application.operation().binding().digest()) + || !selectedCommit.requestId().equals(application.operation().requestId()) + || !selectedCommit.commitId().equals(application.operation().commitId()) + || !selection.target().equals(application.operation().binding().target()) + || application.plan().graph().freshGraphDeclaration().isEmpty() + || !targetNamespace.equals(application.operation().ownerBinding().targetNamespace()) + || !canonicalTenantId.equals(application.operation().canonicalTenantId()) + || !canonicalVersionId.equals(application.operation().canonicalVersionId()) + || !canonicalTenantId.equals(application.operation().ownerBinding().canonicalTenantId()) + || !canonicalVersionId.equals(application.operation().ownerBinding().canonicalVersionId()) + || selection.target().gameDesignVersionRowId() + != application.operation().ownerBinding().gameDesignVersionId()) { + throw new ConflictException( + "World retained APPLIED application differs from the complete selected Draft binding"); + } + return Optional.of(application); + } + /** Exact original Account recovery selector; decoding is not workload authentication. */ public Optional readCommitted( String targetNamespace, byte[] originalAccountBinding) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcService.java new file mode 100644 index 0000000000..9b2bfaf040 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcService.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Request; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeRequest; +import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldSelectedDraftPublicationFreezeServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered, same-namespace Game Design receiver for the selected World publication freeze. + * + *

Workload identity is checked before protobuf parsing. This class deliberately has no + * registration annotation, so the new boundary remains unavailable until an owner integration + * explicitly wires and proves it. + */ +public final class WorldSelectedDraftPublicationFreezeGrpcService + extends WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceImplBase { + private final WorldSelectedDraftPublicationFreezeService freezeService; + private final String trustedNamespace; + + public WorldSelectedDraftPublicationFreezeGrpcService( + WorldSelectedDraftPublicationFreezeService freezeService, String trustedNamespace) { + this.freezeService = Objects.requireNonNull(freezeService, "freezeService"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void beginVersionPublicationFreeze( + BeginVersionPublicationFreezeRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeer(responseObserver)) return; + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World selected freeze requires an independent owner operation") + .asRuntimeException()); + return; + } + + final Request decoded; + try { + decoded = WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("A complete canonical selected World freeze request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(decoded.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("World freeze namespace must match the authenticated peer") + .asRuntimeException()); + return; + } + + final BeginVersionPublicationFreezeResponse response; + try { + response = + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freezeService.begin(decoded)); + } catch (StatusRuntimeException failure) { + responseObserver.onError(failure); + return; + } catch (SecurityException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Authenticated same-namespace Game Design workload is required") + .asRuntimeException()); + return; + } catch (WorldDesignPublicationFenceRepository.ConflictException + | IllegalArgumentException inconsistent) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact World selected-freeze owner evidence is unavailable") + .asRuntimeException()); + return; + } catch (org.springframework.dao.DataAccessException + | org.jooq.exception.DataAccessException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World selected-freeze owner storage is unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL + .withDescription("World selected-publication freeze failed") + .asRuntimeException()); + return; + } + + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean requireAuthenticatedGameDesignPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + responseObserver.onError( + Status.UNAUTHENTICATED + .withDescription("Verified Game Design workload identity required") + .asRuntimeException()); + return false; + } + String expected = "spiffe://firemud/ns/" + trustedNamespace + "/sa/game-design-service"; + if (expected.equals(peer.uri()) + && peer.isService("game-design-service") + && peer.isInNamespace(trustedNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Only the verified same-namespace Game Design workload without end-user context is allowed") + .asRuntimeException()); + return false; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java index fd7508d5d0..f926fae9c3 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java @@ -16,6 +16,9 @@ import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Request; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; @@ -42,6 +45,7 @@ final class WorldSelectedDraftPublicationFreezeService { private final WorldDesignPublicationFenceRepository fence; private final WorldSelectedDraftPublicationCheckpointRepository checkpointRepository; private final WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository; + private final WorldDraftGraphApplicationRepository graphApplicationRepository; private final TransactionTemplate ownerTransaction; WorldSelectedDraftPublicationFreezeService( @@ -54,6 +58,30 @@ final class WorldSelectedDraftPublicationFreezeService { WorldSelectedDraftPublicationCheckpointRepository checkpointRepository, WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository, PlatformTransactionManager transactionManager) { + this( + workloadNamespace, + selectionReadClient, + versionStateClient, + accountReadClient, + intakeRepository, + fence, + checkpointRepository, + authorizationRepository, + null, + transactionManager); + } + + WorldSelectedDraftPublicationFreezeService( + String workloadNamespace, + AuthoredDraftPublishSelectionReadClient selectionReadClient, + AuthoredWorldVersionStateClient versionStateClient, + AccountPublicationAuthorizationReadClient accountReadClient, + WorldAuthoredSourceIntakeRepository intakeRepository, + WorldDesignPublicationFenceRepository fence, + WorldSelectedDraftPublicationCheckpointRepository checkpointRepository, + WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository, + WorldDraftGraphApplicationRepository graphApplicationRepository, + PlatformTransactionManager transactionManager) { if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { throw new IllegalArgumentException("World workload namespace is invalid"); } @@ -67,12 +95,98 @@ final class WorldSelectedDraftPublicationFreezeService { Objects.requireNonNull(checkpointRepository, "checkpointRepository"); this.authorizationRepository = Objects.requireNonNull(authorizationRepository, "authorizationRepository"); + this.graphApplicationRepository = graphApplicationRepository; this.ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); this.ownerTransaction.setReadOnly(false); } + /** + * Owner-resolves the exact selected APPLIED graph before deriving private World freeze evidence. + * + *

The caller supplies no plan or private World identity. A committed retry resolves the same + * immutable APPLIED carrier, then returns the retained freeze and Account correlation before any + * mutable Game Design or Account remote read is repeated. + */ + Acknowledgement begin(Request request) { + requireAuthenticatedGameDesignCaller(); + requireNoAmbientTransaction(); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new SecurityException( + "World selected-publication freeze target namespace differs from this workload"); + } + if (graphApplicationRepository == null) { + throw new IllegalStateException( + "World selected-publication freeze requires its committed APPLIED resolver"); + } + + AccountPublicationAuthorizationBinding accountBinding = request.accountBinding(); + AuthoredDraftPublishSelectionBinding selection = accountBinding.input().selection(); + WorldDraftGraphApplication application = + graphApplicationRepository + .readSelectedPublicationApplication( + workloadNamespace, + request.canonicalTenantId(), + request.canonicalVersionId(), + selection) + .orElseThrow( + () -> + conflict( + "World selected-publication request has no exact retained APPLIED graph")); + WorldDraftTopologyCommitPlan selectedPlan = application.plan(); + WorldDraftTerminalOperation operation = application.operation(); + WorldDesignPublicationFenceEvidence.OwnerBinding owner = operation.ownerBinding(); + if (!selection.selectedCommit().equals(selectedPlan.binding()) + || !Arrays.equals( + selection.selectedCommit().canonicalBytes(), selectedPlan.binding().canonicalBytes()) + || !selection.selectedCommit().equals(operation.binding()) + || !Arrays.equals( + selection.selectedCommit().canonicalBytes(), operation.binding().canonicalBytes()) + || !selectedPlan.graph().freshGraphDeclaration().isPresent() + || !workloadNamespace.equals(owner.targetNamespace()) + || !request.canonicalTenantId().equals(operation.canonicalTenantId()) + || !request.canonicalVersionId().equals(operation.canonicalVersionId()) + || !request.canonicalTenantId().equals(owner.canonicalTenantId()) + || !request.canonicalVersionId().equals(owner.canonicalVersionId()) + || selection.target().gameDesignVersionRowId() != owner.gameDesignVersionId()) { + throw conflict( + "World retained APPLIED graph differs from the complete selected publication request"); + } + + WorldDesignPublicationFenceEvidence evidence = + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + request.publicationRequestId(), + request.requestDigest(), + request.expectedVersionStateEpoch(), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()); + FrozenAttempt attempt = freeze(evidence, selectedPlan, accountBinding); + return new Acknowledgement( + request, + attempt.request().versionStateEpoch(), + attempt.publicationFence(), + OwnerFreezePhase.FROZEN, + attempt.checkpoint().appliedCommitId(), + attempt.checkpoint().contentDigest(), + attempt.checkpoint().digestSchemaVersion()); + } + /** * Freezes and returns only the exact committed World checkpoint and Account-order correlation. * diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 83941bda5d..5d915e4013 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -51,6 +51,8 @@ import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; @@ -292,6 +294,7 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() world.owner().gameDesignVersionId(), 1L, versionStateReadCalls)); + endpoints.setGameDesignService("localhost:" + gameDesignServer.getPort()); try (var selectionRead = new AuthoredDraftPublishSelectionReadClient( endpoints, @@ -310,7 +313,6 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() pki.worldClient.properties(pki.ca), new GrpcChannelFactory(), NAMESPACE)) { - endpoints.setGameDesignService("localhost:" + gameDesignServer.getPort()); selectionRead.init(); versionStateRead.init(); accountRead.init(); @@ -388,9 +390,26 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() assertThat(stateAfterFirstQualifiedCaptureRollback.publicationAttemptRows()).isEmpty(); assertThat(stateAfterFirstQualifiedCaptureRollback.publicationAuthorizationRows()) .isEmpty(); - var frozenAttempt = - withGameDesignCaller( - () -> selectedFreezeService.freeze(freezeEvidence, plan, publicationOrder)); + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + world.owner().canonicalTenantId(), + world.version().canonicalVersionId(), + publicationRequest, + 1L, + publicationSelection.digest().substring("sha256:".length()), + publicationOrder); + var firstFreeze = beginOverMtls(selectedFreezeService, freezeRequest, pki); + var frozenAttempt = fence.readAttempt(freezeEvidence).orElseThrow(); + assertThat(firstFreeze.request()).isEqualTo(freezeRequest); + assertThat(firstFreeze.acknowledgement().publicationFence()) + .isEqualTo(frozenAttempt.publicationFence()); + assertThat(firstFreeze.acknowledgement().appliedCommitId()) + .isEqualTo(frozenAttempt.checkpoint().appliedCommitId()); + assertThat(firstFreeze.acknowledgement().contentDigest()) + .isEqualTo(frozenAttempt.checkpoint().contentDigest()); + assertThat(firstFreeze.acknowledgement().digestSchemaVersion()) + .isEqualTo(frozenAttempt.checkpoint().digestSchemaVersion()); account.assertPublicationSourcesHeld(publicationOrder); var frozen = capture(plan, freezeEvidence, frozenAttempt); assertThat(frozenAttempt.checkpoint().appliedCommitId()) @@ -399,9 +418,12 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() var stateBeforeExactRetry = ownerSnapshot(world, plan); int selectedReadsBeforeRetry = selectedReadCalls.get(); int stateReadsBeforeRetry = versionStateReadCalls.get(); - var exactRetry = - withGameDesignCaller( - () -> selectedFreezeService.freeze(retryEvidence, plan, publicationOrder)); + // A fresh authenticated transport recovers the committed acknowledgement without + // repeating the stipulated Game Design selection/current-Draft reads. + var retryFreeze = beginOverMtls(selectedFreezeService, freezeRequest, pki); + assertThat(retryFreeze.request()).isEqualTo(firstFreeze.request()); + assertThat(retryFreeze.acknowledgement()).isEqualTo(firstFreeze.acknowledgement()); + var exactRetry = fence.readAttempt(retryEvidence).orElseThrow(); assertThat(exactRetry.request()).isEqualTo(retryEvidence); assertThat(exactRetry.publicationFence()).isEqualTo(frozenAttempt.publicationFence()); assertThat(exactRetry.checkpoint()).isEqualTo(frozenAttempt.checkpoint()); @@ -422,6 +444,23 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() publicationOrder.fenceId(), publicationOrder.input(), publicationOrder.sources()); + var changedFreezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + freezeRequest.canonicalTenantId(), + freezeRequest.canonicalVersionId(), + publicationRequest, + freezeRequest.expectedVersionStateEpoch(), + freezeRequest.requestDigest(), + changedOperation); + assertThatThrownBy( + () -> beginOverMtls(selectedFreezeService, changedFreezeRequest, pki)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(ownerSnapshot(world, plan)).isEqualTo(stateBeforeExactRetry); assertThatThrownBy( () -> withGameDesignCaller( @@ -1183,9 +1222,37 @@ private WorldSelectedDraftPublicationFreezeService selectedPublicationFreezeServ fence, checkpointRepository(), publicationAuthorizationRepository(), + appliedRepository(), manager); } + private WorldSelectedDraftPublicationFreezeEvidence beginOverMtls( + WorldSelectedDraftPublicationFreezeService service, + WorldSelectedDraftPublicationFreezeEvidence.Request request, + TestPki pki) + throws Exception { + var server = + serveAll( + pki.worldServer, + pki, + new WorldSelectedDraftPublicationFreezeGrpcService(service, NAMESPACE)); + try { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + server.getPort()); + try (var client = + new WorldSelectedDraftPublicationFreezeClient( + endpoints, + pki.gameDesignClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + client.init(); + return client.begin(request); + } + } finally { + stop(server); + } + } + private static T withGameDesignCaller(Supplier action) { var context = Context.current() diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 7f53ecdd2c..0bc4dce528 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -773,6 +773,7 @@ void terminalRequiresTheExactV53AccountOrderForFirstCompletionAndExactRetry() { var committedRead = new WorldPublicationTerminalRepository(dsl, manager).readCommitted(request).orElseThrow(); assertThat(committedRead.canonicalBytes()).containsExactly(first.canonicalBytes()); + var ownerAfterCompletion = ownerSnapshot(f, graphApplication.plan()); for (AccountPublicationAuthorizationBinding changed : List.of(changedOperation, changedFence, changedBytes)) { var altered = isolatedTerminalEvidence(original, changed); @@ -791,7 +792,7 @@ void terminalRequiresTheExactV53AccountOrderForFirstCompletionAndExactRetry() { .isInstanceOf( WorldPublicationTerminalRepository.PublicationTerminalConflictException.class) .hasMessageContaining("original Account publication qualification"); - assertThat(ownerSnapshot(f, graphApplication.plan())).isEqualTo(ownerBefore); + assertThat(ownerSnapshot(f, graphApplication.plan())).isEqualTo(ownerAfterCompletion); assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); assertThat(publicationTerminalCount(fence)).isEqualTo(1L); assertThat(publicationTerminalBytes(fence)).containsExactly(first.canonicalBytes()); diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java new file mode 100644 index 0000000000..1c58f833d3 --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java @@ -0,0 +1,153 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeRequest; +import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class WorldSelectedDraftPublicationFreezeGrpcServiceTest { + private static final String NAMESPACE = "firemud"; + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void authenticatesExactSameNamespaceGameDesignPeerBeforeParsingOrDelegating() { + var delegate = mock(WorldSelectedDraftPublicationFreezeService.class); + var receiver = new WorldSelectedDraftPublicationFreezeGrpcService(delegate, NAMESPACE); + var malformed = BeginVersionPublicationFreezeRequest.getDefaultInstance(); + + var anonymous = new RecordingObserver(); + withoutPeer(() -> receiver.beginVersionPublicationFreeze(malformed, anonymous)); + assertThat(Status.fromThrowable(anonymous.error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + + var wrongWorkload = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "account-service"), + () -> receiver.beginVersionPublicationFreeze(malformed, wrongWorkload)); + assertThat(Status.fromThrowable(wrongWorkload.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + var wrongNamespace = new RecordingObserver(); + withPeer( + peer("other", "game-design-service"), + () -> receiver.beginVersionPublicationFreeze(malformed, wrongNamespace)); + assertThat(Status.fromThrowable(wrongNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + SessionContext.setContext( + "11111111-1111-4111-8111-111111111111", java.util.List.of(), java.util.Map.of()); + var endUserContext = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> receiver.beginVersionPublicationFreeze(malformed, endUserContext)); + assertThat(Status.fromThrowable(endUserContext.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + var authenticatedMalformed = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> receiver.beginVersionPublicationFreeze(malformed, authenticatedMalformed)); + assertThat(Status.fromThrowable(authenticatedMalformed.error).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(delegate); + } + + @Test + void exactGameDesignPeerReceivesOnlyTheCompleteCommittedFreezeAcknowledgement() { + var fixture = WorldSelectedDraftPublicationFreezeRequestTest.fixture(); + var delegate = mock(WorldSelectedDraftPublicationFreezeService.class); + var receiver = new WorldSelectedDraftPublicationFreezeGrpcService(delegate, NAMESPACE); + var acknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + fixture.request(), + fixture.request().expectedVersionStateEpoch(), + java.util.UUID.fromString("18181818-1818-4818-8818-181818181818"), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + fixture.binding().commitId().toString(), + "a".repeat(64), + 3); + when(delegate.begin(fixture.request())).thenReturn(acknowledgement); + var observer = new RecordingObserver(); + + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> + receiver.beginVersionPublicationFreeze( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(fixture.request()), + observer)); + + assertThat(observer.response) + .isEqualTo(WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + verify(delegate).begin(fixture.request()); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + private static void withoutPeer(Runnable action) { + Context previous = Context.ROOT.attach(); + try { + action.run(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static final class RecordingObserver + implements StreamObserver { + BeginVersionPublicationFreezeResponse response; + Throwable error; + boolean completed; + + @Override + public void onNext(BeginVersionPublicationFreezeResponse value) { + response = value; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The test collector retains the original throwable for assertion.") + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java new file mode 100644 index 0000000000..c2b62deac5 --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java @@ -0,0 +1,412 @@ +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.inOrder; +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.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldSelectedDraftPublicationFreezeRequestTest { + private static final String NAMESPACE = "firemud"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = uuid("22222222-2222-4222-8222-222222222222"); + private static final long GD_VERSION = 17L; + private static final long EPOCH = 9L; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void callerDenialPrecedesOwnerResolutionAndEveryOtherRead() { + Fixture fixture = fixture(); + Collaborators collaborators = new Collaborators(); + var service = service(fixture, collaborators); + + assertThatThrownBy(() -> withoutPeer(() -> service.begin(fixture.request()))) + .isInstanceOf(SecurityException.class); + + collaborators.verifyNoReadsOrWrites(); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void ownerResolvesAppliedBeforeExactRetryAndRetrySkipsMutableRemoteReads() { + Fixture fixture = fixture(); + Collaborators collaborators = new Collaborators(); + FrozenAttempt prior = frozen(fixture.evidence(), fixture.binding()); + when(collaborators.applications.readSelectedPublicationApplication( + NAMESPACE, TENANT, VERSION, fixture.selection())) + .thenReturn(Optional.of(fixture.application())); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.of(prior)); + when(collaborators.authorizationRepository.readCommitted(prior)) + .thenReturn(Optional.of(fixture.accountBinding())); + var service = service(fixture, collaborators); + + var acknowledgement = withGameDesign(() -> service.begin(fixture.request())); + + assertThat(acknowledgement.request()).isEqualTo(fixture.request()); + assertThat(acknowledgement.versionStateEpoch()).isEqualTo(EPOCH); + assertThat(acknowledgement.publicationFence()).isEqualTo(prior.publicationFence()); + assertThat(acknowledgement.appliedCommitId()) + .isEqualTo(fixture.binding().commitId().toString()); + assertThat(acknowledgement.ownerFreezePhase()) + .isEqualTo(WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN); + var order = + inOrder( + collaborators.applications, collaborators.fence, collaborators.authorizationRepository); + order + .verify(collaborators.applications) + .readSelectedPublicationApplication(NAMESPACE, TENANT, VERSION, fixture.selection()); + order.verify(collaborators.fence).readAttempt(fixture.evidence()); + order.verify(collaborators.authorizationRepository).readCommitted(prior); + verifyNoInteractions( + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient); + verify(collaborators.fence, never()).claimFreeze(any(), any()); + verify(collaborators.checkpointRepository, never()).capture(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void missingAppliedSelectionIsDeniedBeforeFreezeHistoryOrRemoteReads() { + Fixture fixture = fixture(); + Collaborators collaborators = new Collaborators(); + when(collaborators.applications.readSelectedPublicationApplication( + NAMESPACE, TENANT, VERSION, fixture.selection())) + .thenReturn(Optional.empty()); + var service = service(fixture, collaborators); + + assertThatThrownBy(() -> withGameDesign(() -> service.begin(fixture.request()))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("no exact retained APPLIED"); + + verify(collaborators.fence, never()).readAttempt(any()); + verifyNoInteractions( + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient, + collaborators.authorizationRepository, + collaborators.checkpointRepository); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void exactSelectionRetryCannotAttachChangedAccountOrder() { + Fixture fixture = fixture(); + Collaborators collaborators = new Collaborators(); + var changedAccount = + accountBinding( + fixture.selection(), + uuid("abababab-abab-4bab-8bab-abababababab"), + fixture.accountBinding().fenceId()); + var changedRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + TENANT, + VERSION, + fixture.selection().intent().publishRequestId(), + EPOCH, + fixture.selection().digest().substring("sha256:".length()), + changedAccount); + FrozenAttempt prior = frozen(fixture.evidence(), fixture.binding()); + when(collaborators.applications.readSelectedPublicationApplication( + NAMESPACE, TENANT, VERSION, fixture.selection())) + .thenReturn(Optional.of(fixture.application())); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.of(prior)); + when(collaborators.authorizationRepository.readCommitted(prior)) + .thenReturn(Optional.of(fixture.accountBinding())); + var service = service(fixture, collaborators); + + assertThatThrownBy(() -> withGameDesign(() -> service.begin(changedRequest))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("Account"); + + verifyNoInteractions( + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient); + verify(collaborators.fence, never()).claimFreeze(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + private static WorldSelectedDraftPublicationFreezeService service( + Fixture fixture, Collaborators collaborators) { + return new WorldSelectedDraftPublicationFreezeService( + NAMESPACE, + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient, + collaborators.intakeRepository, + collaborators.fence, + collaborators.checkpointRepository, + collaborators.authorizationRepository, + collaborators.applications, + collaborators.transactionManager); + } + + static Fixture fixture() { + var target = + new TargetProof(TENANT, VERSION, GD_VERSION, "gd-tenant", 41L, "gd-tenant", "NEW_GAME_ROW"); + UUID commitRequest = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID commitId = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + var binding = + DraftCommitBinding.create( + target, + commitRequest, + commitId, + "base-commit", + List.of( + new RevisionPayload( + "0", + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + TENANT, + VERSION, + "publication-request", + Long.toString(EPOCH), + "immutable selection", + binding.requestId(), + binding.commitId(), + binding.digest()), + target, + binding, + new VisibilityFence( + target, + binding.requestId(), + binding.commitId(), + binding.digest(), + "[]", + java.time.OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = accountBinding(selection, uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee")); + var request = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + TENANT, + VERSION, + selection.intent().publishRequestId(), + EPOCH, + selection.digest().substring("sha256:".length()), + account); + var owner = owner(); + var evidence = + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + TENANT, + VERSION, + owner.versionIdentityOperationId(), + GD_VERSION, + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + request.publicationRequestId(), + request.requestDigest(), + EPOCH, + "publish:" + TENANT + ":publish-request:" + request.publicationRequestId()); + var plan = mock(WorldDraftTopologyCommitPlan.class); + when(plan.binding()).thenReturn(binding); + when(plan.ownerBinding()).thenReturn(owner); + when(plan.graph()) + .thenReturn( + new WorldDraftTopologyInputGraph( + TENANT, + VERSION, + List.of(), + new WorldDraftTopologyInputGraph.FreshGraphDeclaration( + TENANT, + VERSION, + new RoomTemplateRef( + TENANT, VERSION, uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd")), + List.of()))); + var operation = mock(WorldDraftTerminalOperation.class); + when(operation.binding()).thenReturn(binding); + when(operation.ownerBinding()).thenReturn(owner); + when(operation.canonicalTenantId()).thenReturn(TENANT); + when(operation.canonicalVersionId()).thenReturn(VERSION); + var application = new WorldDraftGraphApplication(operation, plan); + return new Fixture(selection, binding, account, request, owner, evidence, application); + } + + private static OwnerBinding owner() { + return new OwnerBinding( + NAMESPACE, + TENANT, + VERSION, + uuid("12121212-1212-4212-8212-121212121212"), + GD_VERSION, + uuid("13131313-1313-4313-8313-131313131313"), + uuid("14141414-1414-4414-8414-141414141414"), + "sha256:" + "1".repeat(64), + uuid("15151515-1515-4515-8515-151515151515"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + } + + private static AccountPublicationAuthorizationBinding accountBinding( + AuthoredDraftPublishSelectionBinding selection, UUID operationId) { + return accountBinding(selection, operationId, uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")); + } + + private static AccountPublicationAuthorizationBinding accountBinding( + AuthoredDraftPublishSelectionBinding selection, UUID operationId, UUID fenceId) { + UUID actor = uuid("16161616-1616-4616-8616-161616161616"); + return new AccountPublicationAuthorizationBinding( + operationId, + fenceId, + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + + private static FrozenAttempt frozen( + WorldDesignPublicationFenceEvidence evidence, DraftCommitBinding binding) { + return new FrozenAttempt( + evidence, + uuid("17171717-1717-4717-8717-171717171717"), + new Checkpoint(binding.commitId().toString(), "a".repeat(64), 3)); + } + + private static T withGameDesign(Supplier action) { + return withPeer( + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service") + .orElseThrow(), + 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 UUID uuid(String value) { + return UUID.fromString(value); + } + + record Fixture( + AuthoredDraftPublishSelectionBinding selection, + DraftCommitBinding binding, + AccountPublicationAuthorizationBinding accountBinding, + WorldSelectedDraftPublicationFreezeEvidence.Request request, + OwnerBinding owner, + WorldDesignPublicationFenceEvidence evidence, + WorldDraftGraphApplication application) {} + + private static final class Collaborators { + final AuthoredDraftPublishSelectionReadClient selectionClient = + mock(AuthoredDraftPublishSelectionReadClient.class); + final AuthoredWorldVersionStateClient versionStateClient = + mock(AuthoredWorldVersionStateClient.class); + final AccountPublicationAuthorizationReadClient accountClient = + mock(AccountPublicationAuthorizationReadClient.class); + final WorldAuthoredSourceIntakeRepository intakeRepository = + mock(WorldAuthoredSourceIntakeRepository.class); + final WorldDesignPublicationFenceRepository fence = + mock(WorldDesignPublicationFenceRepository.class); + final WorldSelectedDraftPublicationCheckpointRepository checkpointRepository = + mock(WorldSelectedDraftPublicationCheckpointRepository.class); + final WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository = + mock(WorldSelectedDraftPublicationAuthorizationRepository.class); + final WorldDraftGraphApplicationRepository applications = + mock(WorldDraftGraphApplicationRepository.class); + final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + + void verifyNoReadsOrWrites() { + verifyNoInteractions( + selectionClient, + versionStateClient, + accountClient, + intakeRepository, + fence, + checkpointRepository, + authorizationRepository, + applications); + } + } + + private static final class RecordingTransactionManager + implements org.springframework.transaction.PlatformTransactionManager { + int commits; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + throw new AssertionError("A committed retry must not open the World owner transaction"); + } + + @Override + public void commit(TransactionStatus status) { + commits++; + } + + @Override + public void rollback(TransactionStatus status) { + throw new AssertionError("A committed retry must not roll back a World owner transaction"); + } + } +} From 88ca68fcf8c7278304429d35536c6339fa8e0982 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:13:55 +1300 Subject: [PATCH 034/129] Compose selected publication freeze before owner reservation --- .../game-design-service/api-contracts.md | 2 +- .../game-design-service/asset-storage.md | 25 +- .../world-management-service/api-contracts.md | 2 + ...ame-authoring-publishing-and-activation.md | 14 +- ...ted_draft_publication_freeze_service.proto | 3 + ...issionWalBoundaryProofIntegrationTest.java | 105 ++++++++ ...electedDraftPublicationFreezeEvidence.java | 5 + ...lectedDraftPublicationFreezeGrpcCodec.java | 2 + ...ectedDraftPublicationFreezeClientTest.java | 1 + ...edDraftPublicationFreezeGrpcCodecTest.java | 10 + ...ectedDraftPublicationAdmissionService.java | 124 +++++++--- ...electedDraftPublicationCommandService.java | 32 ++- ...emptServiceTransactionIntegrationTest.java | 172 +++++++++---- ...dDraftPublicationAdmissionServiceTest.java | 232 ++++++++++++++---- ...tedDraftPublicationCommandServiceTest.java | 67 ++--- ...SelectedDraftPublicationFreezeService.java | 1 + ...uthorizedDraftPostgresIntegrationTest.java | 2 + ...DraftPublicationFreezeGrpcServiceTest.java | 1 + ...ctedDraftPublicationFreezeRequestTest.java | 3 + 19 files changed, 598 insertions(+), 205 deletions(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 7d4825009d..4249024401 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -55,7 +55,7 @@ A successful response echoes the entire request unchanged and reports only `SELE The transport is construction work, not runtime registration. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records executed proof and remaining producer, composition and activation gates. The [Account contract](../account-service/api-contracts.md#grpc-apis) owns publication authorization and source participation; the [World contract](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) owns freeze and terminal handoff. -The internal selected-publication command connects authenticated Account/World admission to finalization of that exact existing Draft, never to the ordinary path that allocates a new Version. The immutable selection must already exist before Account authorization. With no retained publication operation, Game Design verifies that selection against the complete original intent and owner lookup inputs, obtains both authenticated owner reads outside SQL, and reserves its local operation before finalization. Once the exact operation exists, retries compare the complete retained selection, original Account binding and World request before reconciling that same attempt. They do not recapture mutable Draft state, require a new `HELD` result after settlement, or mint another authorization or release identity. Missing selection, contradictory or incomplete operation evidence remains denied. Historical identity is not current creator permission; an unregistered internal composition is not a public creator ingress or runtime activation. +The internal selected-publication command connects authenticated Account/World admission to finalization of that exact existing Draft, never to the ordinary path that allocates a new Version. The immutable selection must already exist before Account authorization. With no retained publication operation, Game Design verifies that selection against the complete original intent and Account binding, reads the exact Account `HELD` evidence, and requests the [World-owned freeze](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state). It derives the World selector-read request internally from that authenticated acknowledgement, World's retained intake correlation and the unchanged selected commit's complete World affected tuples; a caller cannot supply a topology plan, private World identity or independent selector request. All owner calls complete outside SQL, and Game Design reserves its local operation only after the exact authenticated selector readback. If World committed the freeze but Game Design has not reserved locally, the same inputs replay World’s original freeze before selector readback and reservation; no second fence or release identity is allocated. Once the exact Game Design operation exists, retries compare the complete retained selection and original Account binding and reuse its stored World request before reconciling that same attempt. They do not recapture mutable Draft state, require a new `HELD` result after settlement, or mint another authorization or release identity. Missing selection, contradictory or incomplete operation evidence remains denied. Historical identity is not current creator permission; an unregistered internal composition is not a public creator ingress or runtime activation. ## Exact Publication Terminal Read diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 8e9aada97c..1f786fdb8e 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,7 +6,7 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b ## Implementation Status -- **Current first slice:** Ordinary uploaded bytes are persisted in `game_assets.data`, which is the retained repair source selected by the process-local snapshot for Published/Active binary assets. This source is not database-enforced immutable: the repository can update `data` for an existing row, even though no current REST update route is exposed. Publication currently exports the bytes to version-scoped object storage and exposes the numeric `GameAssetDto.id`; the target private-candidate/content-addressed publication and opaque logical asset identifier are not live. +- **Current first slice:** Ordinary uploaded bytes are persisted in `game_assets.data`, which the live exporter selects through a process-local snapshot for Published/Active binary assets. V37 now provides durable version-asset mapping and export-snapshot storage plus owner-local freeze/read methods, but production Draft mapping authoring and exporter wiring are absent; current publication therefore does not prove use of that persisted selection. The byte source is not database-enforced immutable: the repository can update `data` for an existing row, even though no current REST update route is exposed. Publication currently exports the bytes to version-scoped object storage and exposes the numeric `GameAssetDto.id`; the target private-candidate/content-addressed publication and opaque logical asset identifier are not live. See the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle) for the storage and proof boundary. - **Current upload admission gap:** The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) are requirements, not current proof. `AssetController` accepts multipart uploads and `GameAssetServiceImpl` calls `MultipartFile.getBytes()` without size or quota enforcement; `AssetStoreProperties` has no matching limits. Upload admission and resource-safety readiness therefore remain incomplete and the route must not be treated as ready for external enablement. - **Hosted-content gate gap:** Current asset upload and publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The current Gateway's coarse `/api/design/**` route nevertheless forwards `/api/design/assets` (after `StripPrefix=2`) to the live `POST /assets` controller, whose Game Design boundary checks only privileged JWT/tenant access. Official-hosted asset-upload readiness is blocked until Gateway denies that route or the exact Account-owned gate is implemented and proved. - **Current lifecycle proof:** `version_asset_artifact` records the exported version-number prefix and manifest asset keys, but it does not yet freeze the target exact immutable object-key/digest set or implement the target global publication/purge fence. Repair writes those live prefix objects and the manifest before its exact release-bundle comparison, so pre-write verification is target-only. @@ -248,7 +248,7 @@ The `game_assets` table stores ordinary design-time upload records. In the curre Future metadata-only storage may replace `data` with fields such as `storage_key`, `content_hash`, and `size_bytes`, but only if the new schema preserves the same repair invariant: Published/Active releases must be exactly reproducible for as long as their assets remain non-Retired or design-history reachable. -To associate assets with specific published versions while still allowing reuse across versions, the target Game Design contract requires a separate mapping table. The current implementation has neither this table nor a Draft-version authoring path for its mappings; the following shape and constraints are target-state until both exist: +To associate assets with specific published versions while still allowing reuse across versions, the Game Design contract uses a separate mapping table. V37 implements `version_asset` and its database guards, and `VersionAssetPublicationRepository` exposes owner-local association and freeze/read methods; no production Draft-version authoring path calls them yet, so production publication still lacks authoritative per-version mappings. The schema and focused proof status are recorded in the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle). - `version_asset`: - `tenant_id` – owning game @@ -301,14 +301,7 @@ The target record would be written only by Game Design's authorized owner-local Any state or epoch change before tombstoning, or any release-bundle/release-reachability evidence, invalidates or rejects the record. `TombstoneVersionAssets` must atomically consume a still-valid `RECORDED` proof while transitioning the matching `FAILED` artifact to `TOMBSTONED`; `BeginPurgeVersionAssets` must require the resulting `TOMBSTONE_CONSUMED` proof, matching `tombstone_state_epoch`, continued caller-tenant `FAILED` authority, and a fresh no-release-reachability/eligibility check. A failed candidate without this durable proof is not eligible, even when its artifact state is `FAILED` or `TOMBSTONED`. -Before the first byte is exported for a version, the target workflow must freeze an -immutable durable per-version export snapshot. The target shape is a -`version_asset_export_item` projection keyed by `(tenant_id, version_id, usage_key)` -with the selected `asset_id`, source-row identity, and computed source `content_hash` -(plus size/type metadata when needed for verification). Same-version retries and -exact-bytes repair must use this snapshot, never re-select the current tenant asset -list or mutable draft mappings. This durable projection is deferred target -convergence and is not implemented by the current first slice. +Before the first byte is exported for a version, the workflow must freeze an immutable durable per-version export snapshot. V37 implements `version_asset_export_snapshot` and `version_asset_export_item`, keyed by `(tenant_id, version_id)` and `(tenant_id, version_id, usage_key)` respectively; the item projection records the selected `asset_id`, source content type, SHA-256 content hash, and byte size. `VersionAssetPublicationRepository.freezeOrReadSnapshot` freezes the exact Draft mapping set under the caller's writable `READ_COMMITTED` transaction, records the canonical tenant/version identity and captured Version epoch, and verifies the mapped source rows and bytes; `readFrozenSnapshot` reads a committed snapshot and fails if its header is absent, never treating absence as an empty set. Same-version retries and exact-bytes repair must use this snapshot, never re-select a tenant asset list or mutable Draft mappings. The repository methods are not wired into production Draft mapping authoring or `AssetExportServiceImpl`, so production exports still lack this persisted proof; the tracker records the PostgreSQL proof definitions and their current execution limit. `(tenant_id, version_id)` is unique in `version_asset_artifact`. This enum list is the canonical schema contract for both persistence and API validation. Target lifecycle transitions must use compare-and-set on `state_epoch` so concurrent publish/repair/purge workflows cannot race; the current implementation's in-memory check followed by an unconditional row-ID update is documented in the implementation-status and lifecycle sections below. @@ -364,7 +357,7 @@ In the target contract, the `published_release_bundle` attestation must referenc ### Interaction with Script-Only Patches -Script-only patches (see `system-architecture-versioning-runtime.md`) do not change assets or any data stored in `game_assets` / `version_asset`. In the target contract, published asset selection is bound to `(tenantId, versionId)` and exported during full `PublishVersion` flows. The current first slice does not yet persist that binding: `AssetExportServiceImpl` initially selects every tenant asset, freezes the selection only in process-local memory, and has no `version_asset` authoring path. A same-runtime rerun reuses the frozen selection; a Published/Active retry fails with `REPAIR_VERSION_SCOPE_UNAVAILABLE` when that selection is unavailable instead of reselecting the tenant-wide list. Asset changes therefore belong in a new `versionId` in the target state, while the current tenant-wide selection remains an implementation gap to be corrected before persisted version-bound export can be treated as proven. +Script-only patches (see `system-architecture-versioning-runtime.md`) do not change assets or any data stored in `game_assets` / `version_asset`. In the target contract, published asset selection is bound to `(tenantId, versionId)` and exported during full `PublishVersion` flows. The current production path does not yet use the V37 persisted binding: `AssetExportServiceImpl` selects every tenant asset and freezes the selection only in process-local memory, while no production `version_asset` authoring caller exists. A same-runtime rerun reuses the frozen selection; a Published/Active retry fails with `REPAIR_VERSION_SCOPE_UNAVAILABLE` when that selection is unavailable instead of reselecting the tenant-wide list. Asset changes therefore belong in a new `versionId` in the target state, while the current tenant-wide selection remains an implementation gap to be corrected before persisted version-bound export can be treated as proven. ### Asset Lifecycle and Publish Workflow @@ -416,15 +409,15 @@ Transition enforcement contract: - `PUBLISHED` is the only success state that may be treated as launchable. Object-store bytes in `STAGED` or `EXPORTED_UNATTESTED` are not publish-complete on their own. - For each `(tenantId, versionId)` the durable publish workflow runs an `ExportAssets` step that: - - **Current implementation:** initially selects every `game_assets` row for `tenantId` through `GameAssetRepository.findByTenantId`, including assets with no `version_asset` mapping, and reads the export bytes from `game_assets.data`. It freezes that selection in process-local memory before writing bytes. The `version_asset` table and a Draft-version authoring action that creates or removes those mappings are not implemented yet. + - **Current implementation:** initially selects every `game_assets` row for `tenantId` through `GameAssetRepository.findByTenantId`, including assets with no `version_asset` mapping, and reads the export bytes from `game_assets.data`. It freezes that selection in process-local memory before writing bytes. V37's `version_asset` table and repository methods exist, but no production Draft-version authoring action creates or removes mappings and the exporter does not consume the V37 snapshot. - **Target convergence:** freezes a persisted selection from `version_asset` joined to `game_assets` for the target `(tenantId, versionId)`; unmapped tenant assets are excluded from that version's export. The candidate is built privately, every selected byte is SHA-256 hashed, and the verified manifest and objects receive immutable content-addressed keys before public delivery. - Copies the selected ordinary asset bytes from `game_assets.data` (or a future equivalent immutable repair source) into private candidate storage, verifies the complete candidate, and only then publishes immutable content-addressed objects. A tenant/version prefix may remain a delivery grouping, but it is not the object identity or lifecycle authority. - Writes the version-scoped `manifest.json` as a content-addressed immutable object after candidate verification; it must not overwrite an attested manifest key. - Updates version metadata with the manifest location. - Transitions `version_asset_artifact` from `STAGED` to `EXPORTED_UNATTESTED`. - - **Target-only validation:** once `version_asset` authoring exists, fails the workflow step if any asset referenced in `version_asset` for the target `(tenantId, versionId)` is missing, so partially published versions cannot be marked as Published. The current implementation cannot perform this validation because the mapping table and authoring path do not exist. + - **Target-only validation:** fails the workflow step if any asset referenced in `version_asset` for the target `(tenantId, versionId)` is missing, so partially published versions cannot be marked as Published. Although V37 supplies the mapping table and a repository snapshot check, production authoring/export is not wired to that boundary, so the live exporter does not perform this validation. - **Target-state retry behavior:** Once the frozen export snapshot exists, rerunning `ExportAssets` for the same `(tenantId, versionId)` reuses that snapshot, recomputes and verifies the same content-addressed bytes, and leaves the version metadata consistent. It must not re-select assets after the snapshot is frozen, and it must not overwrite an attested public key. Changed bytes require a new key and release version. -- **Current implementation boundary:** `AssetExportServiceImpl` freezes a process-local version-scoped snapshot and reuses it for same-runtime reruns, but it does not persist `version_asset_export_item` evidence. A Published/Active retry reuses that frozen snapshot when it is still available and fails closed with `REPAIR_VERSION_SCOPE_UNAVAILABLE` when it is absent, rather than calling `GameAssetRepository.findByTenantId` again. After process loss, exact repair therefore remains unavailable until the target persisted snapshot exists. **Current drift:** if the Version row is now `RETIRED`, the live resolver can instead take a fresh tenant-wide `findByTenantId` snapshot after process loss because only `PUBLISHED`/`ACTIVE` fail closed; that selection is not exact repair proof and operators must treat the path as fail-closed until the target durable snapshot exists. +- **Current implementation boundary:** `AssetExportServiceImpl` freezes a process-local version-scoped snapshot and reuses it for same-runtime reruns. V37 can persist `version_asset_export_item` evidence through `VersionAssetPublicationRepository`, but the production exporter does not call it, so current publication does not guarantee that a durable snapshot exists. A Published/Active retry reuses the process-local snapshot when it is still available and fails closed with `REPAIR_VERSION_SCOPE_UNAVAILABLE` when it is absent, rather than calling `GameAssetRepository.findByTenantId` again. After process loss, exact repair remains unavailable because the live exporter does not consume V37 snapshots, even when one exists. **Current drift:** if the Version row is now `RETIRED`, the live resolver can instead take a fresh tenant-wide `findByTenantId` snapshot after process loss because only `PUBLISHED`/`ACTIVE` fail closed; that selection is not exact repair proof and operators must treat the path as fail-closed until a durable version-scoped snapshot is used by the production exporter. - A later `FinalizePublishedRelease` step must read the computed `manifestHash`, write `published_release_bundle`, and only then transition `version_asset_artifact` from `EXPORTED_UNATTESTED` to `PUBLISHED`. If the attestation write has a lost or ambiguous response, the artifact remains `EXPORTED_UNATTESTED` and reconciliation-required; it may move to `FAILED` only after exact readback proves that no `published_release_bundle` exists for the tenant/version at all and no unresolved attestation write or cleanup ambiguity remains. Any existing row, including a mismatched attestation, keeps the artifact nonterminal until owner reconciliation determines the outcome; a matching committed attestation permits reconciliation to `PUBLISHED` and never `FAILED`. Implementations must not expose launchable `PUBLISHED` assets without a matching release attestation. - The `EXPORTED_UNATTESTED` readback and any transition to `FAILED` must be serialized against concurrent publication for the same `(tenantId, versionId)`. The owner transaction (or one shared lifecycle CAS/lock fence held across the readback and state transition) must lock or compare the artifact row and exact `published_release_bundle` identity together, re-read the bundle immediately before deciding `FAILED`, and reject a stale state epoch. A matching bundle that committed before or during the readback reconciles the artifact to `PUBLISHED`; a missing bundle can transition to `FAILED` only when the same fenced readback proves no publication committed and no external write remains ambiguous. A later failure must never demote a matching publication or delete its version/assets. - Current implementation drift is sharper than the target rule: after bundle creation, the publish catch path still marks failure, performs best-effort cleanup, and calls `VersionRepository.delete`. Since `published_release_bundle.version_id` is a non-cascading foreign key, that compensation delete can fail after a committed bundle. Target recovery must reconcile bundle/readback evidence and must never delete Version to compensate for an ambiguous post-bundle failure; focused proof must cover committed-bundle, missing-bundle, and lost-response branches. @@ -514,12 +507,12 @@ Race-safe purge workflow: To prevent persistence and performance failures in asset workflows: - Maximum single asset size is 25 MiB; oversized uploads must fail with `ASSET_TOO_LARGE`. -- Per-tenant draft asset quota is 2 GiB. **Target admission rule:** exclude bytes retained solely because a `version_asset` reference keeps them reachable from a Published, Active, or Failed version. The current first slice has no authoritative `version_asset` mapping and performs no quota accounting or enforcement; it therefore neither proves that exemption nor applies a conservative charge. Once version-scoped references and quota enforcement exist, the quota query must derive exempt bytes from those normalized references rather than from tenant-wide export contents or object-store path conventions. Writes that would exceed the target quota must fail with `ASSET_QUOTA_EXCEEDED`. A future metadata-only storage model may measure retained immutable draft-object bytes instead, without changing the draft-only target boundary. +- Per-tenant draft asset quota is 2 GiB. **Target admission rule:** exclude bytes retained solely because a `version_asset` reference keeps them reachable from a Published, Active, or Failed version. V37 provides mapping storage, but no production authoring path supplies authoritative references and the current first slice performs no quota accounting or enforcement; it therefore neither proves that exemption nor applies a conservative charge. Once version-scoped references and quota enforcement exist, the quota query must derive exempt bytes from those normalized references rather than from tenant-wide export contents or object-store path conventions. Writes that would exceed the target quota must fail with `ASSET_QUOTA_EXCEEDED`. A future metadata-only storage model may measure retained immutable draft-object bytes instead, without changing the draft-only target boundary. - Upload/download APIs must support streaming/chunked transfer at the transport layer; services must not require buffering full payloads in memory before persistence. - Publish/export workers must process assets in bounded batches (configurable), with backpressure metrics to avoid starving version publish orchestration. - Quota and size limits must be configurable per environment but default to the values above when unset. -In the current first slice, `game_assets` is the canonical design-time store for asset metadata and bytes. Its retained `data` values become the repair source only after the frozen version-scoped export snapshot identifies the exact rows and hashes used by that release; neither the database schema nor repository update path enforces immutability, so editing a referenced row would invalidate that assumption. Until the snapshot is available, same-version repair fails with `REPAIR_VERSION_SCOPE_UNAVAILABLE` for Published/Active releases. A future metadata-only storage model may treat the table as metadata and use retained immutable object-store draft keys, but that is target-only. +In the current first slice, `game_assets` is the canonical design-time store for asset metadata and bytes. Its retained `data` values become the repair source only after the frozen version-scoped export snapshot identifies the exact rows and hashes used by that release; V37 provides that snapshot storage, but the production exporter does not yet create or consume it. Neither the database schema nor repository update path enforces immutability, so editing a referenced row would invalidate that assumption. Until the production export path uses a durable snapshot, same-version repair fails with `REPAIR_VERSION_SCOPE_UNAVAILABLE` for Published/Active releases after process loss. A future metadata-only storage model may treat the table as metadata and use retained immutable object-store draft keys, but that is target-only. Published assets still retain their `game_assets` rows for design history and exact-bytes repair. In the target contract, version-level `FinalizePurgeVersionAssets` deletes only the frozen version-artifact objects and never removes those source rows or `game_assets.data` bytes; it routes through the Game Design reachability and CAS-guarded artifact-purge workflow rather than direct object-store commands. The current implementation only deletes the frozen version-prefix objects and lacks that database CAS/reachability fence. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 8517d3497c..54aae869ab 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -102,6 +102,8 @@ WMS authenticates the caller, resolves the target `(tenantId, versionId)`, verif The successful acknowledgement is the complete tuple `{tenantId, versionId, publicationRequestId, requestDigest, versionStateEpoch, publicationFence, ownerFreezePhase, appliedCommitId, contentDigest, digestSchemaVersion}`. An exact retry returns the stored acknowledgement and does not mint a second fence; reuse of the request identity with any changed or omitted field returns `IDEMPOTENCY_CONFLICT`. A lost response is reconciled by reading this owner row with the same request identity and digest. +For the selected-Draft producer, World also returns the immutable `worldIntakeRequestId` resolved from that exact retained `APPLIED` application. This UUID is selector correlation, not a private numeric key or caller-supplied association. Game Design combines it with the authenticated freeze acknowledgement and the complete affected tuples from its unchanged selected commit to construct the exact World selector-read request. World must verify that request against its retained application and selector evidence; the freeze acknowledgement and intake correlation alone do not supply the selector receipt, terminal publication evidence or admission authority. Exact retries preserve the same intake correlation with the original freeze. + Every Draft `ApplyWorldDesignMutation` must first lock and check the same owner-freeze row for its `(tenantId, versionId)` target, including an ordinary or otherwise unbound mutation that does not carry a publication request identity. An ordinary mutation may proceed only while the owner row is in its writable `OPEN` state with no active publication freeze. A publication-bound mutation must additionally carry `publicationRequestId`, the exact `requestDigest`, the exact observed Game Design `versionStateEpoch`, and the exact WMS `publicationFence` from that acknowledgement, so it cannot be admitted before the fence exists. It may execute in `FROZEN` only when it is one of the explicitly pre-authorized final publication mutations covered by that request digest; `FROZEN` is not reopened for arbitrary Draft writes, and an unbound or mismatched mutation remains rejected. The final publication digest checkpoint includes the result of any such authorized mutation, and the owner must not accept another mutation after that bounded publication step. Both forms reject or drain stale or mismatched evidence, `PUBLISHED`, `RECONCILIATION_REQUIRED`, and any unauthorized `FROZEN` phase; an `ABORTED` attempt remains closed to ordinary writes until its failed or ambiguous outcome is reconciled and the owner row is reopened without accepting the old fence. A pre-freeze writer that already holds the row lock may finish before the acknowledgement; no writer reaching the lock afterward may commit unless it is the exact pre-authorized publication-bound mutation. The owner mutation result and updated digest checkpoint remain bound to the applicable request, digest, and fence. Game Design completes the handoff through one outcome-typed terminal operation, `CompleteVersionPublication`, carrying exactly `tenantId`, `versionId`, `publicationRequestId`, `publishWorkflowId`, `requestDigest`, `publicationFence`, `outcome`, and the final owner evidence. The cross-service field bindings are canonical: Game Design `publishRequestId` is WMS `publicationRequestId`; Game Design `publishWorkflowId` is the durable publication-workflow identity for the attempt and is required as explicit input and evidence; Game Design `publishedReleaseBundleRef` is WMS `publishedReleaseBundleId`; and each Game Design participant `commitId` is WMS `appliedCommitId`. `outcome=PUBLISHED` requires the immutable release evidence `{publishedReleaseBundleId, publishedReleaseBundleDigest, publishWorkflowId, versionStateEpoch}` plus the final WMS digest checkpoint `{appliedCommitId, contentDigest, digestSchemaVersion}`. Every participant digest and artifact evidence item is bound under that same outer `publishWorkflowId`, and WMS exact-compares the workflow identity across the request, release bundle, participant attestations, and stored publication attempt; any mismatch, omission, or incomplete binding fails closed as an idempotency or reconciliation conflict. WMS records that evidence and atomically advances the row to `PUBLISHED`, after which all later Draft mutations with that fence are rejected. `outcome=ABORTED` requires the same request/fence/workflow identity and reconciled no-publication evidence, records the terminal abort, and permits Draft writes only after the failed/ambiguous Game Design attempt has been reconciled and the old fence is no longer accepted. The operation authenticates the Game Design caller and never treats a Temporal completion as owner proof. 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 ae471fd9c8..7489296415 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 @@ -10,7 +10,7 @@ Published-head `9158561db4505e730274ac2c1f00069631481f9e` [Validation run 378447 Published-head `2560d12a8265db943a06e43d1e9e261bb2cdd923` [Validation run 37840711622](https://github.com/benhook1013/FireMUD/actions/runs/37840711622) finished red: 36 jobs passed, Account/World/the aggregate gate failed, and one tooling contract job skipped. Its physical XML records 233 Account cases with 208 failures, 206 World cases with 42 failures, and 75 Game Design cases with no failures; all have zero skips and errors. V107's PL/pgSQL syntax error blocked Account initialization and two World cases. All seven isolated WAL tests failed during migration setup, before their proof logic; this is neither WAL execution proof nor a new V92 durability verdict. World's other failures expose stale terminal fixtures missing V53 qualification (36 cases) and four terminal fixtures incorrectly entering unsupported generation/spawn preparation. The bounded syntax and fixture repairs require corrected-head physical execution; no production qualification or generation-intent guard may be weakened. Game Session and TCP Gradle checks passed with the bounded resource profile. Actual owner jobs checked out synthetic merge `e2bdaf5d011ba97d9a407183892e9ec7b069a909`, tree `1fb483d5c7ed53f27b483587a38909181aa3316b`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and `2560d12a8265db943a06e43d1e9e261bb2cdd923`. The live target had advanced 21 commits/33 paths beyond recorded base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`, with no Account/Game Design/World service differences; this explains composition but does not close intended-parent alignment. Substantive [CodeQL run 37840711613](https://github.com/benhook1013/FireMUD/actions/runs/37840711613) succeeded. Its dependency-deferred duplicate supplied no additional analysis; likewise metadata-only Validation run 37840712794 supplied no runtime proof. -The current publication handoff batch has passing local unit XML for 321 Common, 1,079 Account, 351 Game Design and 546 World cases, plus seven non-database Account integration cases. All 515 database integration definitions skip without Docker: 228 Account, 81 Game Design and 206 World. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. Consolidated validation found an intentionally retained test throwable requiring the existing narrow test-collector suppression and one unused fixture variable; neither correction changes production guards. Common's full gate passed in the combined run; corrected Account and World full gates passed in the next run, and Game Design's full gate passed after removing the unused fixture variable. All three service boot jars, links and Markdown passed; Flyway sanity covers 12 sets / 246 versioned files. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. +The current publication handoff batch has passing local unit XML for 321 Common, 1,079 Account, 354 Game Design and 546 World cases, plus seven non-database Account integration cases. All 517 database integration definitions skip without Docker: 230 Account, 81 Game Design and 206 World. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. The freeze-to-reservation gate found one test mock comparing decoded Account selection objects by identity; matching the complete canonical bytes repairs that test without changing production checks or ordering assertions. Common and World full checks passed in the combined run; the corrected Game Design full check then passed. Account's previous full check remains passing, and the changed WAL definitions pass compilation, formatting, Checkstyle and SpotBugs but skip execution. All three service boot jars, links and Markdown passed; Flyway sanity covers 12 sets / 246 versioned files. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. Published-head `5132fb96b98f2d33b9db5d09d763aebb63efafb2` [Validation run 37834941641](https://github.com/benhook1013/FireMUD/actions/runs/37834941641) executed 229 Account, 75 Game Design and 202 World owner integration cases without skips. Game Design passed; Account retained one V92 original-acknowledgement WAL-coverage denial, and four World historical-upgrade fixtures failed after the additive full-XID column changed their copy/snapshot shapes. The bounded fixture correction preserves all historical fields and explicitly proves the new stamp stays null; corrected-head physical execution remains required. Game Session and TCP Proxy failed in dependent Java compilation with heap exhaustion, before their owner integration tests executed. The runner used synthetic merge `6d8435b7e31f5306defe357703139ccaa23e3fe6` with first parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`; these results do not close actual-parent alignment. Passing source intake mTLS cases do not separately establish the complete V53 qualification or genuine publication boundary. @@ -18,7 +18,7 @@ The terminal construction adds V54's bounded operation-frame check and repositor Expanded Game Design and World terminal repository/loopback-mTLS definitions retain actual local owner storage while stipulating upstream authorities. Account settlement's loopback-mTLS definition exercises its real creator/order/storage with two distinct strict clients, but the remote terminal endpoints and incoming Game Design context are stipulated. The independent Account readback connection checks commit before the second owner transaction; this is not an actual network lost-acknowledgement injection. These definitions require corrected-head physical execution and cannot establish a genuine multi-owner publication chain by themselves. The bounded CI heap-profile repair preserves full matrix validation and packaging tasks; the `2560d12a` Game Session and TCP jobs passed under that profile, without proving every future composed head. -The isolated Account WAL investigation is test-only and leaves V92's conservative production denial unchanged. All seven dedicated PostgreSQL 16 cases executed and passed in the `9158561` CI above; they still skip locally without Docker. They exercise transactional immutable locators, exact target COMMIT readback and restricted-reader recovery. Synthetic ambiguity/identity/capability classifications do not prove physical epoch wrap, promotion, WAL recycling, an unrelated unflushed tail or insufficient target flush. Production extension feasibility, additional physical failure/retention cases and any adoption remain separate gates. The shared PostgreSQL 18 baseline does not change the Account admission executors' PostgreSQL 16-only guards. +The isolated Account WAL investigation is test-only and leaves V92's conservative production denial unchanged. All seven original dedicated PostgreSQL 16 cases executed and passed in the `9158561` CI above. Two additional definitions exercise actual locator-owner immutable-storage triggers and genuine committed-WAL search-budget exhaustion after lost receipt acknowledgement, preserving complete operation, receipt and locator readback. Restricted-reader permission denials are also expanded. All nine definitions compile but skip locally without Docker; the two new cases still need physical execution. The fixture has no deterministic flush-control hook, and PostgreSQL 16 `pg_walinspect` exposes only complete records within the flush frontier; synthetic classifier inputs cannot establish either unflushed-tail success or exact-target insufficient-flush denial. Physical epoch wrap, promotion, WAL recycling and both flush scenarios remain open. Search-budget exhaustion is not recycled-WAL proof. Production extension feasibility and any adoption remain separate gates. The shared PostgreSQL 18 baseline does not change the Account admission executors' PostgreSQL 16-only guards. Overseer-owned isolated [Pod admission run 37830726704](https://github.com/benhook1013/FireMUD/actions/runs/37830726704) passed the Account and Game Session CREATE/adversarial matrices plus UPDATE and ephemeral-container checks; Overseer reported the owned cluster deleted after the run. This is admission-only evidence. CNI/socket routing, kubelet UID/process correspondence, replacement races, shared-key closure and promotion readiness remain unproved; duplicate-SPKI rejection and activation denial are unchanged. @@ -36,7 +36,7 @@ The standalone Account selected-publication producer defines a distinct immutabl The new standalone Account producer transport binds its method-specific credential interceptor internally and captures the environment boundary through Account's owner service, not caller input. Local Common units prove credential-free protobuf text, redacted wrappers and protected exact-method emission; receiver units prove peer-first denial and owner ordering. The new PostgreSQL/loopback-mTLS definition drives real creator issuance, the producer transport and retained publication sources, but stipulates upstream Game Design selection. The production environment-authority provider and runtime registration are absent; physical execution is pending. Game Design's unregistered selected-publication command now composes authenticated admission with the existing selected-Version v2 finalizer and exact retained-operation retry. Its six local unit cases use mocked collaborators and do not prove PostgreSQL command composition, a genuine release manifest or complete multi-owner publication. These limitations must remain beside each bounded proof claim. -The composed-command PostgreSQL definition now uses real Game Design selection, admission, reservation, finalization and terminal storage with strict loopback-mTLS clients. Account `HELD`, World selector, original Draft outcomes, participant digests and immutable empty export remain expressly stipulated; the definition compiled but skipped locally and requires physical execution. It checks denied admission before reservation, exact selected-Version v2 publication, immutable terminal readback, unchanged retry without fresh owner reads, and changed-lookup denial. The live World digest emits schema 3, already required by shared release evidence; Game Design now accepts that schema and denies obsolete 2 and unknown 4 in focused units. World's owner manifest describes the same tagged references. This alignment does not relabel retained digests, make synthetic commits authoritative or open any route. +The unregistered Game Design admission component now reads its actual immutable selection, authenticates exact Account `HELD`, invokes World first freeze, derives the selector request from that acknowledgement and the selected World tuples, and only then opens the local reservation transaction. The acknowledgement's owner-resolved intake UUID is correlation, not authority to substitute another application. Public command callers no longer supply a World selector request. The composed-command PostgreSQL definition uses real Game Design selection, admission, reservation, finalization and terminal storage with strict loopback-mTLS clients; Account `HELD`, World freeze and selector, original Draft outcomes, participant digests and immutable empty export remain expressly stipulated. It covers selector failure after freeze before reservation, retry of that same freeze, exact selected-Version v2 publication, immutable terminal readback and unchanged retained-operation retry without fresh owner reads. These revised definitions require corrected-head physical execution. The live World digest emits schema 3, already required by shared release evidence; Game Design accepts that schema and denies obsolete 2 and unknown 4 in focused units. This alignment does not relabel retained digests, make synthetic commits authoritative, prove a genuine release manifest or open any route. Actual producer tracing still blocks a genuine v2 release: Game Logic denies full-version reads without its owner-local rule/ability manifest and lacks the dedicated ability-schema response field; Automation full-version scripts/bindings and Game Design template/asset wiring remain tenant-wide rather than exact selected-version inputs; Entity and generic owner digests retain synthetic commit tokens; and the live asset exporter cannot return the complete immutable artifact evidence required by the v2 writer. The canonical owners remain [Game Logic API contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status), [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). No missing mapping or absent row proves an empty authored set. Generic digest workflow derivation also still uses Game Design's private tenant selector, unlike the canonical tenant UUID in selected publication; identity convergence and owner-local selector resolution remain required. The concrete Game Logic manifest input boundary has been referred to Overseer before inventing a producer contract. These are implementation dependencies, not failures cured by mocked command proof or by making synthetic tokens equal. @@ -89,7 +89,7 @@ The live `CompareAndSetVersionState` path has an additional transition-safety ga - `AR-1.3`: [ADR 0127](../../architecture/decisions/adr-0127-game-authored-equipment-layouts-with-fail-closed-publication.md) makes the complete game-authored equipment vocabulary/body-layout publication gate a target obligation. [ADR 0130](../../architecture/decisions/adr-0130-historical-equipment-body-layout-authority.md) is superseded by it. Existing equipment/editor and publication caveats remain unchanged. - `AR-1.3`: [ADR 0128](../../architecture/decisions/adr-0128-game-design-plugin-trust-provenance.md) records Game Design's accepted local provenance record under [ADR 0111](../../architecture/decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md); it does not upgrade current signed intake, runtime readiness, compatibility, or activation proof. - `AR-1.5`: [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) records exact-base/digest Draft proposals and owner-local CAS/read-fence obligations. The current implementation and focused proof remain partial, with no silent-merge or distributed-transaction claim. -- `AR-1.5`: Full-version publication currently has no WMS owner-local publication-freeze acknowledgement: WMS performs only a remote Draft-state pre-check before its local mutation commit. The target exact `versionStateEpoch`/`publicationFence` handoff, post-freeze rejection or drain, and interleaved mutation/publish retry proof are canonical in [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff); current status remains partial. +- `AR-1.5`: The unregistered selected-Draft construction now retains a World owner-local publication freeze and exposes an exact authenticated acknowledgement consumed by Game Design admission. Legacy publication and ordinary mutation ingress do not thereby acquire that boundary. Genuine producer composition, owner-terminal settlement and corrected-head physical retry/race proof remain incomplete. The target handoff remains canonical in [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff). - `AR-1.5`: Publish participant authorization and identity remain blocked across the owner seam. Automation is currently admin-role-only while WMS, Entity, and Game Logic digest handlers are bearer-only; the live Game Design participant DTO/client/gate omit and do not compare `tenantId`, and Game Logic accepts a blank tenant with a tenant/version-independent empty manifest. The shared target owner allowlist, exact publication binding, tenant comparison, and wrong-workload/cross-tenant/identity proof are canonical in [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). - `AR-1.5`: The typed WMS `ApplyWorldDesignMutation` write path has the same unrecorded owner-boundary gap: its live gRPC handler accepts any shared-JWT bearer and does not enforce the target tenant or an allowlisted Game Design caller before mutation. This is distinct from participant digest authorization and the legacy REST generation-rule ingress; cross-tenant/wrong-workload denial remains unimplemented and unproved, while the target Game Design caller/tenant authorization remains canonical in the WMS API contract. @@ -104,8 +104,8 @@ These links add decision provenance only; they do not change existing implementa | `AR-1.1` World, entity, rule, and content authoring | `partial` | `proven` for the typed revision-to-World mutation, authored help/command, and entity-template validation seams; complete world, entity, rule, and content authoring remains unproved. | [Game Design ownership](../../architecture/microservices/game-design-service/README.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md); [ability/action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [item and equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [GameAuthoredHelpTopicServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql); [EntityTemplateReferenceServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImpl.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [GameAuthoredHelpTopicServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java); [EntityTemplateReferenceServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md) | Partial: typed revision-to-World mutation, authored help/commands, and entity template/runtime validation seams exist, but complete rule/action/effect catalogs and creator-facing authoring workflows are not implemented. Accepted procedural-generation decisions now define World-owned typed ingress and preview-bound replacement, but typed generation ingress, destructive plan protocol, and identity/reference proof remain incomplete. | | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and typed generation mutation seams; LLM-assisted authoring, typed generation ingress, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and typed generation mutations exist. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. Accepted procedural-generation decisions now define one World-owned engine, request-bounded replay, bounded persistence, previewed replacement, and sparse/full-grid semantics; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | -| `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `audited` | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: export, artifact-state, manifest-hashing, repair, and purge seams exist, but the required fail-closed version-scoped publication gate is not implemented. The `version_asset` mapping table and its Draft-version authoring path are absent; `AssetExportServiceImpl` exports every tenant asset, and publication does not prove that only mapped assets were selected. The release bundle also lacks canonical target-commit, manifest-schema, and applicable artifact-digest fields. Release readiness cannot be claimed until the mapping/authoring path and guard exist with focused proof. Normalized asset/history and derived-artifact substrates plus complete creator asset UX remain absent. Accepted asset/publication decisions now define content-addressed bytes, fail-closed attestation, and version-scoped publication; version-scoped asset mapping and complete release-bundle digest fields remain incomplete. | -| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for current revision/version publication, the fail-closed publish gate, and happy-path release-bundle and participant-digest seams; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: revision/version publication and fail-closed gate seams exist, but participant tokens are synthetic, World emits schema 2 while the gate accepts schema 1, and the release bundle is still minimal, so actual same-commit attestation convergence is not established. Accepted publication, release, asset, and procedural-generation decisions now define the target authority chain; complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | +| `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `audited` | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: export, artifact-state, manifest-hashing, repair, and purge seams exist, but the required fail-closed version-scoped publication gate is not implemented. V37 mapping/snapshot storage and its repository exist, but production Draft-version authoring/export integration is absent; `AssetExportServiceImpl` exports every tenant asset, and publication does not prove that only mapped assets were selected. The selected-Version v2 bundle binds target commit, manifest schema and exact participant/artifact evidence; the live exporter cannot yet supply its complete immutable artifact evidence. Release readiness cannot be claimed until the mapping/authoring path and guard exist with focused proof. Normalized asset/history and derived-artifact substrates plus complete creator asset UX remain absent. Accepted asset/publication decisions now define content-addressed bytes, fail-closed attestation, and version-scoped publication; version-scoped asset production/export, complete owner evidence and genuine release readiness remain incomplete. | +| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for current revision/version publication, the fail-closed publish gate, and happy-path release-bundle and participant-digest seams; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: revision/version publication and fail-closed gate seams exist, but generic participant tokens remain synthetic and genuine same-commit attestation convergence is not established. The selected-Version v2 bundle and schema-3 World gate are implemented construction boundaries, not proof of complete immutable participant/export production. Accepted publication, release, asset, and procedural-generation decisions now define the target authority chain; complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | @@ -212,7 +212,7 @@ Design-time revoke is explicit through `RevokePluginVersion`. Upload verificatio ### World Design Authoring Handoff -Game Design owns revision history, commits, version state, and publish orchestration; World Management owns authoritative Draft and Published world template rows. `SaveRevision` is version-scoped and carries typed `worldDesignMutation` payloads, including `WORLD_GENERATION_SUBTREE`, through the canonical World Management API. The first caller path saves revision history and applies the concrete change through that API rather than directly mutating World tables or treating opaque revision JSON as the authoritative world graph. The current seam permits only Draft version design-time writes; Published, Active, Failed, and Retired scopes are rejected. Publication freeze and terminal handoff are target-only owner operations; their exact fields and current absent implementation/proof are maintained by the [World Management owner contract](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state), rather than repeated in this tracker. +Game Design owns revision history, commits, version state, and publish orchestration; World Management owns authoritative Draft and Published world template rows. `SaveRevision` is version-scoped and carries typed `worldDesignMutation` payloads, including `WORLD_GENERATION_SUBTREE`, through the canonical World Management API. The first caller path saves revision history and applies the concrete change through that API rather than directly mutating World tables or treating opaque revision JSON as the authoritative world graph. The current seam permits only Draft version design-time writes; Published, Active, Failed, and Retired scopes are rejected. Standalone selected-publication freeze and terminal components now exist, but are unregistered and do not establish genuine multi-owner production handoff. Their target behavior remains owned by the [World Management contract](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state); remaining producer and proof gaps are recorded above. ### Validation and Proof diff --git a/protos/world-management/v1/world_selected_draft_publication_freeze_service.proto b/protos/world-management/v1/world_selected_draft_publication_freeze_service.proto index 587f2da6f1..69a0297cfc 100644 --- a/protos/world-management/v1/world_selected_draft_publication_freeze_service.proto +++ b/protos/world-management/v1/world_selected_draft_publication_freeze_service.proto @@ -48,4 +48,7 @@ message BeginVersionPublicationFreezeResponse { int32 digest_schema_version = 13; // Owner-observed epoch from the committed freeze, separately bound to the request expectation. int64 version_state_epoch = 14; + // Exact World intake correlation from the retained APPLIED owner binding; not caller input or + // publication authority. The later selector read validates it against that same APPLIED result. + string world_intake_request_id = 15; } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java index d383853188..12e48f989a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java @@ -204,6 +204,90 @@ void physicalOriginalCommitAndLocatorCannotReplaceLostOriginalAcknowledgement() .hasMessageContaining("locator unavailable"); } + @Test + void lostReceiptAcknowledgementRetainsExactEvidenceWhenCommittedWalExhaustsSearchBudget() { + var context = context(); + var evidence = pending(context); + UUID decision = UUID.randomUUID(); + var loseNextCommit = new AtomicBoolean(); + var source = lostAcknowledgementSource(context.source(), loseNextCommit); + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(source).execute(evidence, decision); + loseNextCommit.set(true); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(source) + .confirm(acknowledgement)) + .hasMessageContaining("Account receipt physical COMMIT unavailable"); + var operationBefore = operation(independent(context), evidence).intoMap(); + var receiptBefore = receipt(context, evidence).intoMap(); + var locatorsBefore = + independent(context).fetch("SELECT * FROM wal_proof_locators ORDER BY phase").intoMaps(); + assertThat(locatorsBefore).hasSize(2); + assertThat(receiptBefore.get("committed_before_ms")) + .isEqualTo(acknowledgement.committedBeforeMs()); + assertThat(receiptBefore.get("expires_at_ms")).isEqualTo(expiry(evidence)); + + // Fixed-volume logged rows, committed independently of the retained target transactions. + // This exhausts the real search budget; it does not simulate WAL loss or recycling. + context.dsl().execute("CREATE TABLE wal_proof_search_pressure (payload TEXT NOT NULL)"); + String before = + independent(context) + .fetchSingle("SELECT pg_current_wal_insert_lsn()::text") + .get(0, String.class); + tx( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO wal_proof_search_pressure SELECT md5(n::text) FROM generate_series(1, 32768) n")); + assertThat(independent(context).fetchCount(DSL.table("wal_proof_search_pressure"))) + .isEqualTo(32768); + assertThat( + independent(context) + .fetchSingle("SELECT pg_current_wal_flush_lsn() - ?::pg_lsn > 1048576", before) + .get(0, Boolean.class)) + .isTrue(); + assertThatThrownBy(() -> read(context, evidence, decision, "receipt")) + .hasMessageContaining("search budget unavailable"); + assertThatThrownBy(() -> read(context, evidence, decision, "original")) + .hasMessageContaining("search budget unavailable"); + assertThat(operation(independent(context), evidence).intoMap()).isEqualTo(operationBefore); + assertThat(receipt(context, evidence).intoMap()).isEqualTo(receiptBefore); + assertThat( + independent(context) + .fetch("SELECT * FROM wal_proof_locators ORDER BY phase") + .intoMaps()) + .isEqualTo(locatorsBefore); + } + + @Test + void locatorOwnerCannotUpdateDeleteOrTruncateRetainedLocators() throws SQLException { + var context = context(); + var evidence = pending(context); + UUID decision = UUID.randomUUID(); + new AccountGameplayAdmissionOriginalCommitExecutor(context.source()) + .execute(evidence, decision); + var before = locator(context, evidence, "original").intoMap(); + try (var connection = context.source().getConnection()) { + var owner = DSL.using(connection, SQLDialect.POSTGRES); + owner.execute("SET ROLE " + context.schema() + "_owner"); + assertThat(owner.fetchSingle("SELECT current_user").get(0, String.class)) + .isEqualTo(context.schema() + "_owner"); + for (String statement : + List.of( + "UPDATE wal_proof_locators SET target_xid = '1'", + "DELETE FROM wal_proof_locators", + "TRUNCATE wal_proof_locators")) { + assertThatThrownBy(() -> owner.execute(statement)) + .hasMessageContaining("Test WAL locator is immutable"); + } + } + assertThat(locator(context, evidence, "original").intoMap()).isEqualTo(before); + assertCovered(context, read(context, evidence, decision, "original")); + } + @Test void restrictedReaderCannotUseRawWalOrMutateLocatorsAndRevocationDeniesProof() { var context = context(); @@ -235,6 +319,27 @@ void restrictedReaderCannotUseRawWalOrMutateLocatorsAndRevocationDeniesProof() { .hasMessageContaining("permission denied"); assertThatThrownBy(() -> reader.execute("UPDATE wal_proof_locators SET target_xid = '1'")) .hasMessageContaining("permission denied"); + for (String statement : + List.of( + "INSERT INTO wal_proof_locators DEFAULT VALUES", + "DELETE FROM wal_proof_locators", + "TRUNCATE wal_proof_locators", + "CREATE TABLE wal_proof_reader_write (value INTEGER)")) { + assertThatThrownBy(() -> reader.execute(statement)).hasMessageContaining("permission denied"); + } + assertThatThrownBy(() -> reader.fetch("SELECT pg_read_binary_file('PG_VERSION')")) + .hasMessageContaining("permission denied for function"); + assertThatThrownBy( + () -> + reader.fetch( + "SELECT * FROM wal_proof_classify('100', '101', '0/1000000'::pg_lsn, " + + "'0/1000080'::pg_lsn, '0/1000080'::pg_lsn, '[]'::jsonb)")) + .hasMessageContaining("permission denied for function"); + assertThatThrownBy( + () -> + reader.execute( + "ALTER FUNCTION wal_proof_read(UUID, TEXT, TEXT, UUID) RENAME TO wal_proof_reader_replacement")) + .hasMessageContaining("must be owner"); assertThatThrownBy(() -> reader.execute("SET ROLE " + context.schema() + "_owner")) .hasMessageContaining("permission denied"); assertThatThrownBy( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java index 1cc766cc5f..e4a2dce3ac 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java @@ -162,6 +162,7 @@ private static void requireUuid(UUID value, String label) { /** Acknowledgement of the committed FROZEN event only, never a terminal or admission result. */ public record Acknowledgement( Request request, + UUID intakeRequestId, long versionStateEpoch, UUID publicationFence, OwnerFreezePhase ownerFreezePhase, @@ -173,6 +174,10 @@ public record Acknowledgement( public Acknowledgement { Objects.requireNonNull(request, "request"); + if (intakeRequestId == null || NIL_UUID.equals(intakeRequestId)) { + throw new IllegalArgumentException( + "World intake correlation must be a non-nil owner-produced UUID"); + } if (versionStateEpoch <= 0L || versionStateEpoch != request.expectedVersionStateEpoch()) { throw new IllegalArgumentException( "World-observed Version state epoch differs from the exact request expectation"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodec.java index a6baa81d6a..e65f786d7a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodec.java @@ -72,6 +72,7 @@ public static BeginVersionPublicationFreezeResponse toResponse(Acknowledgement a .setContentDigest(acknowledgement.contentDigest()) .setDigestSchemaVersion(acknowledgement.digestSchemaVersion()) .setVersionStateEpoch(acknowledgement.versionStateEpoch()) + .setWorldIntakeRequestId(acknowledgement.intakeRequestId().toString()) .build(); } @@ -99,6 +100,7 @@ public static WorldSelectedDraftPublicationFreezeEvidence fromResponse( acknowledgement = new Acknowledgement( expected, + canonicalUuid(response.getWorldIntakeRequestId()), response.getVersionStateEpoch(), canonicalUuid(response.getPublicationFence()), fromWirePhase(response.getOwnerFreezePhase()), diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java index e9dd79e460..5876904e7e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java @@ -78,6 +78,7 @@ void usesExactWorldServerIdentityBoundedDeadlineAndNoAmbientTransaction(@TempDir WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse( new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( request, + java.util.UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), request.expectedVersionStateEpoch(), java.util.UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java index cb69a18f9e..f4ae02f454 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java @@ -30,6 +30,8 @@ void roundTripsTheClosedRequestAndCompleteFrozenAcknowledgement() { assertThat(evidence.request()).isEqualTo(request); assertThat(evidence.acknowledgement()).isEqualTo(acknowledgement); assertThat(evidence.acknowledgement().requestDigest()).isEqualTo(request.requestDigest()); + assertThat(evidence.acknowledgement().intakeRequestId()) + .isEqualTo(uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); } @Test @@ -101,6 +103,13 @@ void rejectsEchoSubstitutionUnknownFieldsAndNonFrozenOrIncompleteAcknowledgement response.toBuilder().setAppliedCommitId(UUID.randomUUID().toString()).build(), response.toBuilder().setContentDigest("not-a-digest").build(), response.toBuilder().setDigestSchemaVersion(0).build(), + response.toBuilder().setWorldIntakeRequestId("").build(), + response.toBuilder() + .setWorldIntakeRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA") + .build(), + response.toBuilder() + .setWorldIntakeRequestId("00000000-0000-0000-0000-000000000000") + .build(), response.toBuilder().setUnknownFields(unknown).build())) { assertThatThrownBy( () -> WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(request, changed)) @@ -139,6 +148,7 @@ private static Acknowledgement acknowledgement( WorldSelectedDraftPublicationFreezeEvidence.Request request) { return new Acknowledgement( request, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), request.expectedVersionStateEpoch(), uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), OwnerFreezePhase.FROZEN, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java index 4b35c8b981..d55330ba44 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java @@ -1,6 +1,9 @@ package net.firedevops.firemud.gamedesign.publication; +import java.util.Arrays; import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; @@ -8,9 +11,13 @@ import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import org.jooq.DSLContext; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -18,12 +25,14 @@ import org.springframework.transaction.support.TransactionTemplate; /** - * Unregistered Game Design admission boundary for one exact selected-Draft publication. Both owner - * reads complete and are correlated before the local reservation transaction begins. + * Unregistered Game Design admission boundary for one exact selected-Draft publication. Account + * authorization, World freeze and selector capture finish before the local reservation transaction. */ public final class SelectedDraftPublicationAdmissionService { private final AccountPublicationAuthorizationReadClient accountClient; private final WorldPublishedStartLocationClient worldClient; + private final WorldSelectedDraftPublicationFreezeClient freezeClient; + private final SelectionReader selectionReader; private final SelectedDraftPublicationOwner owner; private final TransactionTemplate reservationTransaction; private final String workloadNamespace; @@ -32,24 +41,38 @@ public SelectedDraftPublicationAdmissionService( DSLContext dsl, PlatformTransactionManager transactionManager, AccountPublicationAuthorizationReadClient accountClient, + WorldSelectedDraftPublicationFreezeClient freezeClient, WorldPublishedStartLocationClient worldClient, String workloadNamespace) { this( transactionManager, accountClient, + freezeClient, worldClient, new SelectedDraftPublicationOwner(Objects.requireNonNull(dsl, "dsl")), + intent -> + new AuthoredDraftPublishSelectionRepository( + dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId()) + .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection), workloadNamespace); } SelectedDraftPublicationAdmissionService( PlatformTransactionManager transactionManager, AccountPublicationAuthorizationReadClient accountClient, + WorldSelectedDraftPublicationFreezeClient freezeClient, WorldPublishedStartLocationClient worldClient, SelectedDraftPublicationOwner owner, + SelectionReader selectionReader, String workloadNamespace) { this.accountClient = Objects.requireNonNull(accountClient, "accountClient"); this.worldClient = Objects.requireNonNull(worldClient, "worldClient"); + this.freezeClient = Objects.requireNonNull(freezeClient, "freezeClient"); + this.selectionReader = Objects.requireNonNull(selectionReader, "selectionReader"); this.owner = Objects.requireNonNull(owner, "owner"); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); @@ -64,18 +87,21 @@ public SelectedDraftPublicationAdmissionService( } /** - * Authenticates exact HELD Account and World readbacks before reserving their unchanged inputs. - * The caller-supplied binding and World request are lookup identities only, never authority. + * Verifies the retained selection, authenticates Account HELD, freezes World, then reads its + * exact selector before reserving locally. All remote calls complete outside SQL. */ public SelectedDraftPublicationOwner.Reservation admitAndReserve( AuthoredDraftPublishSelection.PublishIntent intent, - AccountPublicationAuthorizationBinding accountBinding, - WorldPublishedStartLocationEvidence.Request worldRequest) { + AccountPublicationAuthorizationBinding accountBinding) { requireNoAmbientTransaction(); Objects.requireNonNull(intent, "intent"); Objects.requireNonNull(accountBinding, "accountBinding"); - Objects.requireNonNull(worldRequest, "worldRequest"); - requireRequestIdentity(intent, accountBinding, worldRequest); + AuthoredDraftPublishSelection selection = + selectionReader + .read(intent) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")); + requireRequestIdentity(intent, accountBinding, selection); AccountPublicationAuthorizationReadEvidence.Request accountReadRequest = AccountPublicationAuthorizationReadEvidence.Request.create( @@ -84,6 +110,55 @@ public SelectedDraftPublicationOwner.Reservation admitAndReserve( accountClient.read(accountReadRequest); requireExactAccountReadback(accountReadRequest, accountBinding, accountEvidence); + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + workloadNamespace, + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + selection.digest().substring("sha256:".length()), + accountEvidence.request().binding()); + var freeze = freezeClient.begin(freezeRequest); + if (freeze == null + || !freezeRequest.equals(freeze.request()) + || !freezeRequest.equals(freeze.acknowledgement().request())) { + throw new IllegalStateException( + "World publication freeze readback differs from the exact request"); + } + var acknowledgement = freeze.acknowledgement(); + var worldRequest = + new WorldPublishedStartLocationEvidence.Request( + workloadNamespace, + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + acknowledgement.intakeRequestId(), + acknowledgement.publicationFence(), + intent.publishRequestId(), + freezeRequest.requestDigest(), + acknowledgement.versionStateEpoch(), + PublicationDigestRequestBinding.full( + intent.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity(), + acknowledgement.appliedCommitId(), + acknowledgement.contentDigest(), + acknowledgement.digestSchemaVersion(), + selection + .selectedCommit() + .affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT) + .stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList()); WorldPublishedStartLocationEvidence worldEvidence = worldClient.read(worldRequest); requireExactWorldReadback(worldRequest, worldEvidence); new GameDesignPublicationOperationBinding(accountEvidence.request().binding(), worldEvidence); @@ -97,9 +172,8 @@ public SelectedDraftPublicationOwner.Reservation admitAndReserve( private void requireRequestIdentity( AuthoredDraftPublishSelection.PublishIntent intent, AccountPublicationAuthorizationBinding accountBinding, - WorldPublishedStartLocationEvidence.Request worldRequest) { - var selection = accountBinding.input().selection(); - var intentFromBinding = selection.intent(); + AuthoredDraftPublishSelection selection) { + var intentFromBinding = accountBinding.input().selection().intent(); var expectedIntent = new AuthoredDraftPublishSelectionBinding.PublishIntent( intent.canonicalTenantId(), @@ -110,29 +184,21 @@ private void requireRequestIdentity( intent.selectedCommitRequestId(), intent.selectedCommitId(), intent.selectedCommitDigest()); - String expectedWorkflowId = - PublicationDigestRequestBinding.full( - intent.canonicalTenantId().toString(), - Long.toString(selection.target().gameDesignVersionRowId()), - intent.publishRequestId()) - .derivedWorkflowIdentity(); - String expectedRequestDigest = selection.digest().substring("sha256:".length()); - if (!expectedIntent.equals(intentFromBinding) - || !workloadNamespace.equals(worldRequest.targetNamespace()) - || !intent.canonicalTenantId().equals(worldRequest.canonicalTenantId()) - || !intent.canonicalVersionId().equals(worldRequest.canonicalVersionId()) - || !intent.publishRequestId().equals(worldRequest.publicationRequestId()) - || !Long.toString(worldRequest.versionStateEpoch()) - .equals(intent.expectedVersionStateEpoch()) - || !expectedWorkflowId.equals(worldRequest.publishWorkflowId()) - || !intent.selectedCommitId().toString().equals(worldRequest.appliedCommitId()) - || !expectedRequestDigest.equals(worldRequest.requestDigest())) { + || !intent.equals(selection.intent()) + || !Arrays.equals( + selection.canonicalBytes(), accountBinding.input().selection().canonicalBytes())) { throw new IllegalArgumentException( - "Account publication binding and World selector request must match the exact selected Draft intent"); + "Account publication binding and retained selection must match the exact selected Draft intent"); } } + @FunctionalInterface + interface SelectionReader { + Optional read( + AuthoredDraftPublishSelection.PublishIntent intent); + } + private static void requireExactAccountReadback( AccountPublicationAuthorizationReadEvidence.Request expectedRequest, AccountPublicationAuthorizationBinding expectedBinding, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java index 8c7c85cf1d..d7cbff60ee 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java @@ -6,6 +6,7 @@ import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; @@ -33,12 +34,13 @@ public SelectedDraftPublicationCommandService( DSLContext dsl, PlatformTransactionManager transactionManager, AccountPublicationAuthorizationReadClient accountClient, + WorldSelectedDraftPublicationFreezeClient freezeClient, WorldPublishedStartLocationClient worldClient, String workloadNamespace, VersionPublishCommandServiceImpl finalizer) { this( new SelectedDraftPublicationAdmissionService( - dsl, transactionManager, accountClient, worldClient, workloadNamespace), + dsl, transactionManager, accountClient, freezeClient, worldClient, workloadNamespace), new DatabaseDurableStateReader(dsl), finalizer); } @@ -53,17 +55,15 @@ public SelectedDraftPublicationCommandService( } /** - * Publishes the exact selected existing Draft. The World request is an identity supplied for - * first admission and must match the embedded request on exact retries. + * Publishes the exact selected existing Draft. Admission derives the World selector from its + * authenticated freeze; exact retries use the original locally retained World request. */ public VersionDto publishSelectedDraftFullVersion( AuthoredDraftPublishSelection.PublishIntent intent, - AccountPublicationAuthorizationBinding accountBinding, - WorldPublishedStartLocationEvidence.Request worldRequest) { + AccountPublicationAuthorizationBinding accountBinding) { requireNoAmbientTransaction(); Objects.requireNonNull(intent, "intent"); Objects.requireNonNull(accountBinding, "accountBinding"); - Objects.requireNonNull(worldRequest, "worldRequest"); requireIntentMatchesAccount(intent, accountBinding); DurableState state = durableStateReader.read(intent, accountBinding); @@ -81,19 +81,21 @@ public VersionDto publishSelectedDraftFullVersion( AuthoredDraftPublishSelection selection = state.selection().orElseThrow(); if (!operationExists) { // The immutable selection precedes Account authorization on the first publication entry. - requireExactSelection(intent, accountBinding, worldRequest, selection); + requireExactSelection(intent, accountBinding, selection); SelectedDraftPublicationOwner.Reservation reservation = - admission.admitAndReserve(intent, accountBinding, worldRequest); + admission.admitAndReserve(intent, accountBinding); Objects.requireNonNull(reservation, "selected Draft admission returned no reservation"); if (!Arrays.equals(selection.canonicalBytes(), reservation.selection().canonicalBytes())) { throw new IllegalStateException( "SELECTED_PUBLICATION_RESERVATION_SELECTION_CONFLICT: admitted selection differs from the immutable preselection"); } + var worldRequest = reservation.operation().world().request(); requireExactAdmission(intent, accountBinding, worldRequest, reservation); return finalizeSelectedDraft(intent, accountBinding, worldRequest, selection); } GameDesignPublicationOperationRepository.Readback operationReadback = state.operation().orElseThrow(); + var worldRequest = operationReadback.operation().world().request(); requireExactRetry(intent, accountBinding, worldRequest, selection, operationReadback); return finalizeSelectedDraft(intent, accountBinding, worldRequest, selection); } @@ -164,11 +166,25 @@ private static void requireExactAdmission( } } + private static void requireExactSelection( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding, + AuthoredDraftPublishSelection selection) { + if (!intent.equals(selection.intent()) + || !Arrays.equals( + selection.canonicalBytes(), accountBinding.input().selection().canonicalBytes()) + || !selection.digest().equals(accountBinding.input().selection().digest())) { + throw new IllegalStateException( + "SELECTED_PUBLICATION_SELECTION_IDENTITY_CONFLICT: selection differs from the complete original intent or Account binding"); + } + } + private static void requireExactSelection( AuthoredDraftPublishSelection.PublishIntent intent, AccountPublicationAuthorizationBinding accountBinding, WorldPublishedStartLocationEvidence.Request worldRequest, AuthoredDraftPublishSelection selection) { + requireExactSelection(intent, accountBinding, selection); var accountSelection = accountBinding.input().selection(); if (!intent.equals(selection.intent()) || !Arrays.equals(selection.canonicalBytes(), accountSelection.canonicalBytes()) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index cd2862b6c9..ad9ddf15b4 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -50,6 +50,9 @@ import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadEvidence; import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadGrpcCodec; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationGrpcCodec; @@ -93,9 +96,12 @@ import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeRequest; +import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeResponse; import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationReadServiceGrpc; +import net.firedevops.firemud.worldmanagement.v1.WorldSelectedDraftPublicationFreezeServiceGrpc; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -529,8 +535,8 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth /** * Exercises the real GD admission, owner reservation, and finalizer. The Account HELD response, - * World selector, original Draft outcomes, participant digests, and empty export are explicitly - * stipulated test fixtures; this is not genuine upstream production proof. + * World freeze/selector, original Draft outcomes, participant digests, and empty export are + * explicitly stipulated test fixtures; this is not genuine upstream production proof. */ @Test void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Release( @@ -623,11 +629,12 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele var accountEndpoint = new StipulatedAccountPublicationReadEndpoint(operation.account(), heldDenied); var worldEndpoint = new StipulatedWorldPublicationReadEndpoint(operation.world()); + var freezeEndpoint = new StipulatedWorldFreezeEndpoint(operation); Server accountServer = publicationOwnerServer(publicationReadIdentities.accountServer(), pki, accountEndpoint); Server worldServer = publicationOwnerServer( - publicationReadIdentities.worldManagementServer(), pki, worldEndpoint); + publicationReadIdentities.worldManagementServer(), pki, worldEndpoint, freezeEndpoint); var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("127.0.0.1:" + accountServer.getPort()); endpoints.setWorldManagementService("127.0.0.1:" + worldServer.getPort()); @@ -638,6 +645,12 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele publicationReadIdentities.gameDesignClient().properties(pki.ca), new GrpcChannelFactory(), NAMESPACE); + var freezeClient = + new WorldSelectedDraftPublicationFreezeClient( + endpoints, + publicationReadIdentities.gameDesignClient().properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE); var worldClient = new WorldPublishedStartLocationClient( endpoints, @@ -645,23 +658,24 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele new GrpcChannelFactory(), NAMESPACE)) { accountClient.init(); + freezeClient.init(); worldClient.init(); var command = new SelectedDraftPublicationCommandService( dsl, transactionManager, accountClient, + freezeClient, worldClient, NAMESPACE, versionPublishCommandService); assertSelectionReadCode( Status.Code.FAILED_PRECONDITION, - () -> - command.publishSelectedDraftFullVersion( - selection.intent(), operation.account(), operation.world().request())); + () -> command.publishSelectedDraftFullVersion(selection.intent(), operation.account())); assertThat(accountEndpoint.readCount()).isEqualTo(1); assertThat(worldEndpoint.readCount()).isZero(); + assertThat(freezeEndpoint.beginCount()).isZero(); assertThat(publishAttemptRepository.findByPublishWorkflowId(workflowId)).isEmpty(); assertThat(new GameDesignPublicationOperationRepository(dsl).read(workflowId)).isEmpty(); assertThat( @@ -692,14 +706,24 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) assertThat(versionCountForTenant(tenantId)).isEqualTo(1L); heldDenied.set(false); + // World has acknowledged its stipulated freeze, but the subsequent selector response is + // unavailable. No GD reservation exists; retry must send the exact same Begin request. + worldEndpoint.unavailable.set(true); + assertSelectionReadCode( + Status.Code.UNAVAILABLE, + () -> command.publishSelectedDraftFullVersion(selection.intent(), operation.account())); + assertThat(freezeEndpoint.beginCount()).isEqualTo(1); + assertThat(new GameDesignPublicationOperationRepository(dsl).read(workflowId)).isEmpty(); + assertThat(publishAttemptRepository.findByPublishWorkflowId(workflowId)).isEmpty(); + worldEndpoint.unavailable.set(false); long versionCountBeforePublish = versionCountForTenant(tenantId); VersionDto published = - command.publishSelectedDraftFullVersion( - selection.intent(), operation.account(), operation.world().request()); + command.publishSelectedDraftFullVersion(selection.intent(), operation.account()); assertThat(published.id()).isEqualTo(candidate.getId()); assertThat(versionCountForTenant(tenantId)).isEqualTo(versionCountBeforePublish); - assertThat(accountEndpoint.readCount()).isEqualTo(2); - assertThat(worldEndpoint.readCount()).isEqualTo(1); + assertThat(accountEndpoint.readCount()).isEqualTo(3); + assertThat(worldEndpoint.readCount()).isEqualTo(2); + assertThat(freezeEndpoint.beginCount()).isEqualTo(2); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow(); @@ -736,8 +760,7 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) Long bundleIdBeforeRetry = bundle.getId(); String releaseRefBeforeRetry = bundle.getPublishedReleaseBundleRef(); VersionDto exactRetry = - command.publishSelectedDraftFullVersion( - selection.intent(), operation.account(), operation.world().request()); + command.publishSelectedDraftFullVersion(selection.intent(), operation.account()); assertThat(exactRetry.id()).isEqualTo(published.id()); assertThat( publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow().getId()) @@ -773,30 +796,17 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) workflowId) .get(0, Long.class)) .isEqualTo(1L); - assertThat(accountEndpoint.readCount()).isEqualTo(2); - assertThat(worldEndpoint.readCount()).isEqualTo(1); + assertThat(accountEndpoint.readCount()).isEqualTo(3); + assertThat(worldEndpoint.readCount()).isEqualTo(2); + assertThat(freezeEndpoint.beginCount()).isEqualTo(2); assertThat(versionCountForTenant(tenantId)).isEqualTo(versionCountBeforePublish); - var request = operation.world().request(); - var changedWorldRequest = - new WorldPublishedStartLocationEvidence.Request( - request.targetNamespace(), - request.canonicalTenantId(), - request.canonicalVersionId(), - UUID.randomUUID(), - request.publicationFence(), - request.publicationRequestId(), - request.requestDigest(), - request.versionStateEpoch(), - request.publishWorkflowId(), - request.appliedCommitId(), - request.contentDigest(), - request.digestSchemaVersion(), - request.worldAffectedTuples()); + var changedAccount = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), operation.account().fenceId(), + operation.account().input(), operation.account().sources()); assertThatThrownBy( - () -> - command.publishSelectedDraftFullVersion( - selection.intent(), operation.account(), changedWorldRequest)) + () -> command.publishSelectedDraftFullVersion(selection.intent(), changedAccount)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("LOCAL_IDENTITY_CONFLICT"); var retainedAfterChangedRetry = @@ -805,8 +815,9 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) .containsExactly(operation.canonicalBytes()); assertThat(retainedAfterChangedRetry.terminalEvidenceBytes()) .containsExactly(terminalBeforeChangedRetry); - assertThat(accountEndpoint.readCount()).isEqualTo(2); - assertThat(worldEndpoint.readCount()).isEqualTo(1); + assertThat(accountEndpoint.readCount()).isEqualTo(3); + assertThat(worldEndpoint.readCount()).isEqualTo(2); + assertThat(freezeEndpoint.beginCount()).isEqualTo(2); assertThat(versionCountForTenant(tenantId)).isEqualTo(versionCountBeforePublish); } } finally { @@ -1432,17 +1443,19 @@ private void assertTerminalOwnerReadOverMtls( } private static Server publicationOwnerServer( - SelectionReadTestIdentity identity, SelectionReadTestPki pki, BindableService endpoint) + SelectionReadTestIdentity identity, SelectionReadTestPki pki, BindableService... endpoints) throws Exception { - return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) - .trustManager(pki.ca.toFile()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())) - .build() - .start(); + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + for (var endpoint : endpoints) { + builder.addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())); + } + return builder.build().start(); } private static boolean requireGameDesignPeer(StreamObserver observer) { @@ -1534,12 +1547,74 @@ int readCount() { } } + /** Test-only freeze RPC: upstream World state and checkpoint are expressly stipulated. */ + private static final class StipulatedWorldFreezeEndpoint + extends WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceImplBase { + private final GameDesignPublicationOperation operation; + private final AtomicInteger begins = new AtomicInteger(); + + private StipulatedWorldFreezeEndpoint(GameDesignPublicationOperation operation) { + this.operation = operation; + } + + @Override + public void beginVersionPublicationFreeze( + BeginVersionPublicationFreezeRequest request, + StreamObserver observer) { + if (!requireGameDesignPeer(observer)) return; + begins.incrementAndGet(); + try { + var decoded = WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(request); + var world = operation.world().request(); + var expected = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + world.canonicalTenantId(), + world.canonicalVersionId(), + world.publicationRequestId(), + world.versionStateEpoch(), + world.requestDigest(), + operation.account()); + if (!expected.equals(decoded)) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Different stipulated World freeze request") + .asRuntimeException()); + return; + } + var acknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + decoded, + world.intakeRequestId(), + world.versionStateEpoch(), + world.publicationFence(), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + world.appliedCommitId(), + world.contentDigest(), + world.digestSchemaVersion()); + observer.onNext(WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + observer.onCompleted(); + } catch (IllegalArgumentException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Invalid stipulated freeze request") + .asRuntimeException()); + } + } + + int beginCount() { + return begins.get(); + } + } + /** Test-only selector endpoint; it returns only the exact stipulated World evidence. */ private static final class StipulatedWorldPublicationReadEndpoint extends WorldPublishedStartLocationReadServiceGrpc .WorldPublishedStartLocationReadServiceImplBase { private final WorldPublishedStartLocationEvidence expectedEvidence; private final AtomicInteger reads = new AtomicInteger(); + private final AtomicBoolean unavailable = new AtomicBoolean(false); private StipulatedWorldPublicationReadEndpoint( WorldPublishedStartLocationEvidence expectedEvidence) { @@ -1569,6 +1644,13 @@ public void readWorldPublishedStartLocation( .asRuntimeException()); return; } + if (unavailable.get()) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Stipulated selector unavailable") + .asRuntimeException()); + return; + } observer.onNext(WorldPublishedStartLocationGrpcCodec.toResponse(decoded, expectedEvidence)); observer.onCompleted(); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java index 2045f61205..c4318569a1 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java @@ -1,17 +1,27 @@ package net.firedevops.firemud.gamedesign.publication; +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.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.inOrder; 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.Status; +import java.util.Arrays; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; @@ -26,6 +36,126 @@ class SelectedDraftPublicationAdmissionServiceTest { private static final String NAMESPACE = "test"; + @Test + void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = freezeClient(fixture); + var world = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var reader = mock(SelectedDraftPublicationAdmissionService.SelectionReader.class); + var transactions = mock(PlatformTransactionManager.class); + var retained = + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest()); + when(reader.read(fixture.intent())).thenReturn(Optional.of(retained)); + when(account.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + when(world.read(fixture.worldRequest())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return fixture.operation().world(); + }); + var reservation = mock(SelectedDraftPublicationOwner.Reservation.class); + // Request.binding() reconstructs the exact Account bytes; its nested selection does not use + // value equality. Match the complete canonical binding rather than decoded object identity. + when(owner.reserve( + eq(fixture.intent()), + argThat( + binding -> + Arrays.equals( + binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), + same(fixture.operation().world()))) + .thenReturn(reservation); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, account, freeze, world, owner, reader, NAMESPACE); + + assertThat(service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(reservation); + var order = inOrder(reader, account, freeze, world, transactions, owner); + order.verify(reader).read(fixture.intent()); + order.verify(account).read(any()); + order.verify(freeze).begin(any()); + order.verify(world).read(fixture.worldRequest()); + order.verify(transactions).getTransaction(any()); + order + .verify(owner) + .reserve( + eq(fixture.intent()), + argThat( + binding -> + Arrays.equals( + binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), + same(fixture.operation().world())); + } + + @Test + void missingRetainedSelectionNeverReadsAccountFreezesWorldOrOpensSql() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, account, freeze, world, owner, intent -> Optional.empty(), NAMESPACE); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SELECTION_UNAVAILABLE"); + verifyNoInteractions(account, freeze, world, owner, transactions); + } + + @Test + void freezeFailureNeverReadsSelectorOrReserves() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var selection = fixture.operation().account().input().selection(); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freeze, + world, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + selection.canonicalJson(), selection.digest())), + NAMESPACE); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var failure = Status.UNAVAILABLE.asRuntimeException(); + when(freeze.begin(any())).thenThrow(failure); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(failure); + verifyNoInteractions(world, owner, transactions); + } + @AfterEach void clearTransactionState() { TransactionSynchronizationManager.setActualTransactionActive(false); @@ -39,13 +169,12 @@ void rejectsAmbientSqlTransactionBeforeEitherOwnerRead() throws Exception { var fixture = fixture(); var accountClient = mock(AccountPublicationAuthorizationReadClient.class); var worldClient = mock(WorldPublishedStartLocationClient.class); - var service = service(accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy( - () -> - service.admitAndReserve( - fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no ambient transaction"); @@ -57,13 +186,12 @@ void rejectsAmbientSynchronizationBeforeEitherOwnerRead() throws Exception { var fixture = fixture(); var accountClient = mock(AccountPublicationAuthorizationReadClient.class); var worldClient = mock(WorldPublishedStartLocationClient.class); - var service = service(accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); TransactionSynchronizationManager.initSynchronization(); assertThatThrownBy( - () -> - service.admitAndReserve( - fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no ambient transaction"); @@ -71,11 +199,12 @@ void rejectsAmbientSynchronizationBeforeEitherOwnerRead() throws Exception { } @Test - void rejectsChangedIntentAndWorldRequestIdentityBeforeOwnerReads() throws Exception { + void rejectsChangedIntentBeforeOwnerReads() throws Exception { var fixture = fixture(); var accountClient = mock(AccountPublicationAuthorizationReadClient.class); var worldClient = mock(WorldPublishedStartLocationClient.class); - var service = service(accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); var original = fixture.intent(); var changedIntent = new AuthoredDraftPublishSelection.PublishIntent( @@ -88,18 +217,7 @@ void rejectsChangedIntentAndWorldRequestIdentityBeforeOwnerReads() throws Except original.selectedCommitId(), original.selectedCommitDigest()); - assertThatThrownBy( - () -> - service.admitAndReserve( - changedIntent, fixture.operation().account(), fixture.worldRequest())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("exact selected Draft intent"); - assertThatThrownBy( - () -> - service.admitAndReserve( - fixture.intent(), - fixture.operation().account(), - withPublicationRequestId(fixture.worldRequest(), "different-request"))) + assertThatThrownBy(() -> service.admitAndReserve(changedIntent, fixture.operation().account())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact selected Draft intent"); @@ -114,14 +232,12 @@ void accountDenialOrUnavailableReadNeverReadsWorldOrReserves() throws Exception var accountClient = mock(AccountPublicationAuthorizationReadClient.class); var worldClient = mock(WorldPublishedStartLocationClient.class); var owner = mock(SelectedDraftPublicationOwner.class); - var service = service(accountClient, worldClient, owner); + var service = service(fixture, accountClient, worldClient, owner); var failure = Status.fromCode(code).asRuntimeException(); when(accountClient.read(any())).thenThrow(failure); assertThatThrownBy( - () -> - service.admitAndReserve( - fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) .isSameAs(failure); verify(accountClient).read(any()); @@ -135,7 +251,7 @@ void worldUnavailableAfterAccountReadNeverOpensReservation() throws Exception { var accountClient = mock(AccountPublicationAuthorizationReadClient.class); var worldClient = mock(WorldPublishedStartLocationClient.class); var owner = mock(SelectedDraftPublicationOwner.class); - var service = service(accountClient, worldClient, owner); + var service = service(fixture, accountClient, worldClient, owner); // The client is a transport double here; the mock evidence is never accepted as proof because // the World read fails before the reservation boundary. @@ -150,9 +266,7 @@ void worldUnavailableAfterAccountReadNeverOpensReservation() throws Exception { when(worldClient.read(fixture.worldRequest())).thenThrow(failure); assertThatThrownBy( - () -> - service.admitAndReserve( - fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) .isSameAs(failure); verify(accountClient).read(any()); @@ -161,11 +275,49 @@ void worldUnavailableAfterAccountReadNeverOpensReservation() throws Exception { } private static SelectedDraftPublicationAdmissionService service( + Fixture fixture, AccountPublicationAuthorizationReadClient accountClient, WorldPublishedStartLocationClient worldClient, SelectedDraftPublicationOwner owner) { return new SelectedDraftPublicationAdmissionService( - mock(PlatformTransactionManager.class), accountClient, worldClient, owner, NAMESPACE); + mock(PlatformTransactionManager.class), + accountClient, + freezeClient(fixture), + worldClient, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest())), + NAMESPACE); + } + + private static WorldSelectedDraftPublicationFreezeClient freezeClient(Fixture fixture) { + var client = mock(WorldSelectedDraftPublicationFreezeClient.class); + when(client.begin(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + WorldSelectedDraftPublicationFreezeEvidence.Request request = + invocation.getArgument(0); + var world = fixture.worldRequest(); + var acknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + request, + world.intakeRequestId(), + world.versionStateEpoch(), + world.publicationFence(), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + world.appliedCommitId(), + world.contentDigest(), + world.digestSchemaVersion()); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + }); + return client; } private static Fixture fixture() throws Exception { @@ -193,24 +345,6 @@ private static Fixture fixture() throws Exception { return new Fixture(original, intent, original.world().request()); } - private static WorldPublishedStartLocationEvidence.Request withPublicationRequestId( - WorldPublishedStartLocationEvidence.Request request, String publicationRequestId) { - return new WorldPublishedStartLocationEvidence.Request( - request.targetNamespace(), - request.canonicalTenantId(), - request.canonicalVersionId(), - request.intakeRequestId(), - request.publicationFence(), - publicationRequestId, - request.requestDigest(), - request.versionStateEpoch(), - request.publishWorkflowId(), - request.appliedCommitId(), - request.contentDigest(), - request.digestSchemaVersion(), - request.worldAffectedTuples()); - } - private record Fixture( GameDesignPublicationOperation operation, AuthoredDraftPublishSelection.PublishIntent intent, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandServiceTest.java index 48ca132e96..7113742d4c 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandServiceTest.java @@ -14,7 +14,6 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; -import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.PublishIntent; import net.firedevops.firemud.gamedesign.dto.VersionDto; @@ -42,8 +41,7 @@ void preselectedDraftAdmissionCompletesBeforeSelectedExistingVersionFinalizer() var result = mock(VersionDto.class); when(reader.read(fixture.intent(), fixture.operation().account())) .thenReturn(selectionOnly(fixture)); - when(admission.admitAndReserve( - fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + when(admission.admitAndReserve(fixture.intent(), fixture.operation().account())) .thenReturn(reservation); when(reservation.selection()).thenReturn(fixture.selection()); when(reservation.operation()).thenReturn(fixture.operation()); @@ -57,14 +55,13 @@ void preselectedDraftAdmissionCompletesBeforeSelectedExistingVersionFinalizer() var service = service(admission, reader, finalizer); var actual = - service.publishSelectedDraftFullVersion( - fixture.intent(), fixture.operation().account(), fixture.worldRequest()); + service.publishSelectedDraftFullVersion(fixture.intent(), fixture.operation().account()); org.assertj.core.api.Assertions.assertThat(actual).isSameAs(result); var publicationOrder = inOrder(admission, finalizer); publicationOrder .verify(admission) - .admitAndReserve(fixture.intent(), fixture.operation().account(), fixture.worldRequest()); + .admitAndReserve(fixture.intent(), fixture.operation().account()); publicationOrder .verify(finalizer) .publishSelectedDraftFullVersion( @@ -96,11 +93,10 @@ void exactSettledRetryUsesStoredIdentityWithoutFreshHeldReadOrReservation() thro var service = service(admission, reader, finalizer); var actual = - service.publishSelectedDraftFullVersion( - fixture.intent(), fixture.operation().account(), fixture.worldRequest()); + service.publishSelectedDraftFullVersion(fixture.intent(), fixture.operation().account()); org.assertj.core.api.Assertions.assertThat(actual).isSameAs(result); - verify(admission, never()).admitAndReserve(any(), any(), any()); + verify(admission, never()).admitAndReserve(any(), any()); verify(finalizer) .publishSelectedDraftFullVersion( fixture.selection().target().gameDesignVersionTenantKey(), @@ -121,15 +117,14 @@ void admissionDenialAndPartialLocalIdentityNeverReachFinalizer() throws Exceptio var finalizer = mock(VersionPublishCommandServiceImpl.class); when(reader.read(fixture.intent(), fixture.operation().account())) .thenReturn(selectionOnly(fixture)); - when(admission.admitAndReserve( - fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + when(admission.admitAndReserve(fixture.intent(), fixture.operation().account())) .thenThrow(denial); assertThatThrownBy( () -> service(admission, reader, finalizer) .publishSelectedDraftFullVersion( - fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + fixture.intent(), fixture.operation().account())) .isSameAs(denial); verifyNoInteractions(finalizer); @@ -148,7 +143,7 @@ void admissionDenialAndPartialLocalIdentityNeverReachFinalizer() throws Exceptio () -> service(partialAdmission, partialReader, partialFinalizer) .publishSelectedDraftFullVersion( - fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + fixture.intent(), fixture.operation().account())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("LOCAL_IDENTITY_INCOMPLETE"); verifyNoInteractions(partialAdmission, partialFinalizer); @@ -167,7 +162,7 @@ void missingSelectionFailsClosedBeforeAccountOrWorldAdmission() throws Exception () -> service(admission, reader, finalizer) .publishSelectedDraftFullVersion( - fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + fixture.intent(), fixture.operation().account())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SELECTION_UNAVAILABLE"); @@ -175,11 +170,10 @@ void missingSelectionFailsClosedBeforeAccountOrWorldAdmission() throws Exception } @Test - void exactRetryRejectsChangedIntentAccountBindingOrWorldRequest() throws Exception { + void exactRetryRejectsChangedIntentOrAccountBinding() throws Exception { var fixture = fixture(); var alteredIntent = withNotes(fixture.intent(), "substituted notes"); - assertRejectedRetry( - fixture, alteredIntent, fixture.operation().account(), fixture.worldRequest()); + assertRejectedRetry(fixture, alteredIntent, fixture.operation().account()); var changedAccount = new AccountPublicationAuthorizationBinding( @@ -187,12 +181,7 @@ void exactRetryRejectsChangedIntentAccountBindingOrWorldRequest() throws Excepti fixture.operation().account().fenceId(), fixture.operation().account().input(), fixture.operation().account().sources()); - assertRejectedRetry(fixture, fixture.intent(), changedAccount, fixture.worldRequest()); - - var changedWorldRequest = - withPublicationRequestId(fixture.worldRequest(), "substituted-publication-request"); - assertRejectedRetry( - fixture, fixture.intent(), fixture.operation().account(), changedWorldRequest); + assertRejectedRetry(fixture, fixture.intent(), changedAccount); } @Test @@ -207,7 +196,7 @@ void compositionRejectsAmbientTransactionBeforeLocalReadsAdmissionOrFinalizer() () -> service(admission, reader, finalizer) .publishSelectedDraftFullVersion( - fixture.intent(), fixture.operation().account(), fixture.worldRequest())) + fixture.intent(), fixture.operation().account())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no ambient SQL transaction"); @@ -215,10 +204,7 @@ void compositionRejectsAmbientTransactionBeforeLocalReadsAdmissionOrFinalizer() } private static void assertRejectedRetry( - Fixture fixture, - PublishIntent intent, - AccountPublicationAuthorizationBinding account, - WorldPublishedStartLocationEvidence.Request worldRequest) { + Fixture fixture, PublishIntent intent, AccountPublicationAuthorizationBinding account) { var admission = mock(SelectedDraftPublicationAdmissionService.class); var reader = mock(SelectedDraftPublicationCommandService.DurableStateReader.class); var finalizer = mock(VersionPublishCommandServiceImpl.class); @@ -227,7 +213,7 @@ private static void assertRejectedRetry( assertThatThrownBy( () -> service(admission, reader, finalizer) - .publishSelectedDraftFullVersion(intent, account, worldRequest)) + .publishSelectedDraftFullVersion(intent, account)) .isInstanceOf(RuntimeException.class); verifyNoInteractions(admission, finalizer); @@ -280,7 +266,7 @@ private static Fixture fixture() throws Exception { bindingIntent.selectedCommitDigest()); var selection = AuthoredDraftPublishSelection.fromStored(binding.canonicalJson(), binding.digest()); - return new Fixture(operation, selection, intent, operation.world().request()); + return new Fixture(operation, selection, intent); } private static PublishIntent withNotes(PublishIntent intent, String notes) { @@ -295,27 +281,8 @@ private static PublishIntent withNotes(PublishIntent intent, String notes) { intent.selectedCommitDigest()); } - private static WorldPublishedStartLocationEvidence.Request withPublicationRequestId( - WorldPublishedStartLocationEvidence.Request request, String publicationRequestId) { - return new WorldPublishedStartLocationEvidence.Request( - request.targetNamespace(), - request.canonicalTenantId(), - request.canonicalVersionId(), - request.intakeRequestId(), - request.publicationFence(), - publicationRequestId, - request.requestDigest(), - request.versionStateEpoch(), - request.publishWorkflowId(), - request.appliedCommitId(), - request.contentDigest(), - request.digestSchemaVersion(), - request.worldAffectedTuples()); - } - private record Fixture( GameDesignPublicationOperation operation, AuthoredDraftPublishSelection selection, - PublishIntent intent, - WorldPublishedStartLocationEvidence.Request worldRequest) {} + PublishIntent intent) {} } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java index f926fae9c3..41cd1de483 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java @@ -179,6 +179,7 @@ Acknowledgement begin(Request request) { FrozenAttempt attempt = freeze(evidence, selectedPlan, accountBinding); return new Acknowledgement( request, + owner.intakeRequestId(), attempt.request().versionStateEpoch(), attempt.publicationFence(), OwnerFreezePhase.FROZEN, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 5d915e4013..650c9fe04f 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -402,6 +402,8 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() var firstFreeze = beginOverMtls(selectedFreezeService, freezeRequest, pki); var frozenAttempt = fence.readAttempt(freezeEvidence).orElseThrow(); assertThat(firstFreeze.request()).isEqualTo(freezeRequest); + assertThat(firstFreeze.acknowledgement().intakeRequestId()) + .isEqualTo(applied.application().operation().ownerBinding().intakeRequestId()); assertThat(firstFreeze.acknowledgement().publicationFence()) .isEqualTo(frozenAttempt.publicationFence()); assertThat(firstFreeze.acknowledgement().appliedCommitId()) diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java index 1c58f833d3..2bcdad8a9d 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java @@ -79,6 +79,7 @@ void exactGameDesignPeerReceivesOnlyTheCompleteCommittedFreezeAcknowledgement() var acknowledgement = new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( fixture.request(), + fixture.owner().intakeRequestId(), fixture.request().expectedVersionStateEpoch(), java.util.UUID.fromString("18181818-1818-4818-8818-181818181818"), WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java index c2b62deac5..6812714f09 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java @@ -81,10 +81,13 @@ void ownerResolvesAppliedBeforeExactRetryAndRetrySkipsMutableRemoteReads() { var acknowledgement = withGameDesign(() -> service.begin(fixture.request())); assertThat(acknowledgement.request()).isEqualTo(fixture.request()); + assertThat(acknowledgement.intakeRequestId()).isEqualTo(fixture.owner().intakeRequestId()); assertThat(acknowledgement.versionStateEpoch()).isEqualTo(EPOCH); assertThat(acknowledgement.publicationFence()).isEqualTo(prior.publicationFence()); assertThat(acknowledgement.appliedCommitId()) .isEqualTo(fixture.binding().commitId().toString()); + assertThat(acknowledgement.contentDigest()).isEqualTo("a".repeat(64)); + assertThat(acknowledgement.digestSchemaVersion()).isEqualTo(3); assertThat(acknowledgement.ownerFreezePhase()) .isEqualTo(WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN); var order = From 39b800bdfe07cf94028fd4a175f79f42eb51c8e7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:27:05 +1300 Subject: [PATCH 035/129] Repair asset insert readback and isolate serialization proof --- ...ame-authoring-publishing-and-activation.md | 8 +- ...issionLeasePersistenceIntegrationTest.java | 7 +- .../repository/GameAssetRepository.java | 5 +- .../repository/GameAssetRepositoryTest.java | 97 +++++++++++++++++++ 4 files changed, 111 insertions(+), 6 deletions(-) create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java 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 7489296415..611a0d6a74 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 @@ -6,11 +6,13 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Published-head `9158561db4505e730274ac2c1f00069631481f9e` [Validation run 37844737121](https://github.com/benhook1013/FireMUD/actions/runs/37844737121) completed with 36 successful jobs, three failures (Account, World and the aggregate gate), and one skipped tooling-contract job. Physical integration XML records 240 Account cases with three failures, 206 World cases with two failures, and 75 Game Design cases with no failures; all have zero skips and errors. All seven isolated WAL cases executed and passed, without changing V92's conservative production denial or proving production adoption. The Account failures are source-event guards correctly rejecting test probes that directly changed a role without using the real Account owner; the correction routes those probes through its atomic authority/event update. World requires endpoint configuration before strict client construction and a post-terminal snapshot assertion against committed `PUBLISHED`, not the earlier `FROZEN` state. These fixture corrections still require corrected-head physical execution. The Account producer/reader and Game Design selected-owner mTLS cases passed, but their upstream/terminal fixtures remain stipulated rather than genuine composed owner authority. Owner jobs checked out merge `503db73556970c9baf1c26176c601bdbcb8b4668`, tree `9bdedfe9be1f911bba365c50972f04f76671accb`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and `9158561db4505e730274ac2c1f00069631481f9e`; the live target differs from the recorded integrated base, so intended-parent alignment remains open. Security, CodeQL, License and Kustomize checks passed. The dependency-deferred duplicate Validation run supplies no additional runtime proof. +Published-head `67a665036c04b155f83c252e606cefbc91f8fe4a` [Validation run 37850400728](https://github.com/benhook1013/FireMUD/actions/runs/37850400728) completed red. Physical integration XML records 240 Account cases with one failure, 206 World cases with no failures, and 81 Game Design cases with four failures; all have zero skips and errors. The previous three Account source-event and two World fixture failures are fixed. All seven original isolated WAL cases, the authenticated World first-freeze/terminal cases, and Game Design's selected-publication composition executed and passed. Four new asset cases fail before assertions because the live asset repository's dynamic-table insert does not return its saved row; explicit persisted-field readback and a focused regression are the bounded correction, not a fixture bypass. Account's remaining serialization test reaches V90's conservative receipt-read WAL denial: insert fence `0/4678018` exceeds initial/final flush `0/4678000`. That is an open durability limitation, not a reason to relax V90/V92 or claim the isolated investigation proves production adoption. Owner jobs checked out merge `a9607e8cd55f5245cbb87100fe2817400f752ded`, tree `7e0df9be73f2bdcdc71c28b9aaa3b503758b300a`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and `67a665036c04b155f83c252e606cefbc91f8fe4a`; intended-parent alignment remains open. Security, CodeQL, License, Kustomize, PR preview and dependency submission passed; this is not full-stack Smoke. Dependency-deferred duplicates add no runtime evidence. The later freeze-to-reservation composition and two additional WAL definitions were not in this run and still require corrected-head physical execution. Published-head `2560d12a8265db943a06e43d1e9e261bb2cdd923` [Validation run 37840711622](https://github.com/benhook1013/FireMUD/actions/runs/37840711622) finished red: 36 jobs passed, Account/World/the aggregate gate failed, and one tooling contract job skipped. Its physical XML records 233 Account cases with 208 failures, 206 World cases with 42 failures, and 75 Game Design cases with no failures; all have zero skips and errors. V107's PL/pgSQL syntax error blocked Account initialization and two World cases. All seven isolated WAL tests failed during migration setup, before their proof logic; this is neither WAL execution proof nor a new V92 durability verdict. World's other failures expose stale terminal fixtures missing V53 qualification (36 cases) and four terminal fixtures incorrectly entering unsupported generation/spawn preparation. The bounded syntax and fixture repairs require corrected-head physical execution; no production qualification or generation-intent guard may be weakened. Game Session and TCP Gradle checks passed with the bounded resource profile. Actual owner jobs checked out synthetic merge `e2bdaf5d011ba97d9a407183892e9ec7b069a909`, tree `1fb483d5c7ed53f27b483587a38909181aa3316b`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and `2560d12a8265db943a06e43d1e9e261bb2cdd923`. The live target had advanced 21 commits/33 paths beyond recorded base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`, with no Account/Game Design/World service differences; this explains composition but does not close intended-parent alignment. Substantive [CodeQL run 37840711613](https://github.com/benhook1013/FireMUD/actions/runs/37840711613) succeeded. Its dependency-deferred duplicate supplied no additional analysis; likewise metadata-only Validation run 37840712794 supplied no runtime proof. -The current publication handoff batch has passing local unit XML for 321 Common, 1,079 Account, 354 Game Design and 546 World cases, plus seven non-database Account integration cases. All 517 database integration definitions skip without Docker: 230 Account, 81 Game Design and 206 World. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. The freeze-to-reservation gate found one test mock comparing decoded Account selection objects by identity; matching the complete canonical bytes repairs that test without changing production checks or ordering assertions. Common and World full checks passed in the combined run; the corrected Game Design full check then passed. Account's previous full check remains passing, and the changed WAL definitions pass compilation, formatting, Checkstyle and SpotBugs but skip execution. All three service boot jars, links and Markdown passed; Flyway sanity covers 12 sets / 246 versioned files. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. +The current publication handoff batch has passing local unit XML for 321 Common, 1,079 Account, 356 Game Design and 546 World cases, plus seven non-database Account integration cases. All 517 database integration definitions skip without Docker: 230 Account, 81 Game Design and 206 World. This is owner/transport/storage-contract unit evidence, not PostgreSQL or end-to-end authority proof. The freeze-to-reservation gate found one test mock comparing decoded Account selection objects by identity; matching the complete canonical bytes repairs that test without changing production checks or ordering assertions. Common and World full checks passed in the combined run; the corrected Game Design full check then passed. Account's previous full check remains passing, and the changed WAL definitions pass compilation, formatting, Checkstyle and SpotBugs but skip execution. The corrected asset insert and its two PostgreSQL-dialect unit regressions pass Game Design's full check and boot jar. The narrowed Account serialization fixture passes formatting, compilation, Checkstyle and SpotBugs; its PostgreSQL execution still skips locally. All three service boot jars, links and Markdown passed; Flyway sanity covers 12 sets / 246 versioned files. V53 retains a full transaction-ID creation stamp only for new attempts; existing attempts remain unqualified rather than receiving inferred birth or Account evidence. + +The serialization-specific Account fixture now compares the complete winning receipt through committed owner-storage readback after requiring SQLSTATE `40001`, exact fresh confirmation replay, a single retained receipt and unchanged authority/operation snapshots. It no longer claims that those concurrency assertions establish the separate global-WAL durability gate. Dedicated independent receipt-COMMIT/readback, lost-acknowledgement and same-transaction denial cases remain unchanged. The observed `67a665036` WAL-coverage denial above remains an unresolved durability limitation; this test-scope correction neither closes it nor permits production recovery. Published-head `5132fb96b98f2d33b9db5d09d763aebb63efafb2` [Validation run 37834941641](https://github.com/benhook1013/FireMUD/actions/runs/37834941641) executed 229 Account, 75 Game Design and 202 World owner integration cases without skips. Game Design passed; Account retained one V92 original-acknowledgement WAL-coverage denial, and four World historical-upgrade fixtures failed after the additive full-XID column changed their copy/snapshot shapes. The bounded fixture correction preserves all historical fields and explicitly proves the new stamp stays null; corrected-head physical execution remains required. Game Session and TCP Proxy failed in dependent Java compilation with heap exhaustion, before their owner integration tests executed. The runner used synthetic merge `6d8435b7e31f5306defe357703139ccaa23e3fe6` with first parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`; these results do not close actual-parent alignment. Passing source intake mTLS cases do not separately establish the complete V53 qualification or genuine publication boundary. @@ -18,7 +20,7 @@ The terminal construction adds V54's bounded operation-frame check and repositor Expanded Game Design and World terminal repository/loopback-mTLS definitions retain actual local owner storage while stipulating upstream authorities. Account settlement's loopback-mTLS definition exercises its real creator/order/storage with two distinct strict clients, but the remote terminal endpoints and incoming Game Design context are stipulated. The independent Account readback connection checks commit before the second owner transaction; this is not an actual network lost-acknowledgement injection. These definitions require corrected-head physical execution and cannot establish a genuine multi-owner publication chain by themselves. The bounded CI heap-profile repair preserves full matrix validation and packaging tasks; the `2560d12a` Game Session and TCP jobs passed under that profile, without proving every future composed head. -The isolated Account WAL investigation is test-only and leaves V92's conservative production denial unchanged. All seven original dedicated PostgreSQL 16 cases executed and passed in the `9158561` CI above. Two additional definitions exercise actual locator-owner immutable-storage triggers and genuine committed-WAL search-budget exhaustion after lost receipt acknowledgement, preserving complete operation, receipt and locator readback. Restricted-reader permission denials are also expanded. All nine definitions compile but skip locally without Docker; the two new cases still need physical execution. The fixture has no deterministic flush-control hook, and PostgreSQL 16 `pg_walinspect` exposes only complete records within the flush frontier; synthetic classifier inputs cannot establish either unflushed-tail success or exact-target insufficient-flush denial. Physical epoch wrap, promotion, WAL recycling and both flush scenarios remain open. Search-budget exhaustion is not recycled-WAL proof. Production extension feasibility and any adoption remain separate gates. The shared PostgreSQL 18 baseline does not change the Account admission executors' PostgreSQL 16-only guards. +The isolated Account WAL investigation is test-only and leaves V92's conservative production denial unchanged. All seven original dedicated PostgreSQL 16 cases executed and passed in the `67a665036` CI above. Two additional definitions exercise actual locator-owner immutable-storage triggers and genuine committed-WAL search-budget exhaustion after lost receipt acknowledgement, preserving complete operation, receipt and locator readback. Restricted-reader permission denials are also expanded. All nine definitions compile but skip locally without Docker; the two new cases still need physical execution. The fixture has no deterministic flush-control hook, and PostgreSQL 16 `pg_walinspect` exposes only complete records within the flush frontier; synthetic classifier inputs cannot establish either unflushed-tail success or exact-target insufficient-flush denial. Physical epoch wrap, promotion, WAL recycling and both flush scenarios remain open. Search-budget exhaustion is not recycled-WAL proof. Production extension feasibility and any adoption remain separate gates. The shared PostgreSQL 18 baseline does not change the Account admission executors' PostgreSQL 16-only guards. Overseer-owned isolated [Pod admission run 37830726704](https://github.com/benhook1013/FireMUD/actions/runs/37830726704) passed the Account and Game Session CREATE/adversarial matrices plus UPDATE and ephemeral-container checks; Overseer reported the owned cluster deleted after the run. This is admission-only evidence. CNI/socket routing, kubelet UID/process correspondence, replacement races, shared-key closure and promotion readiness remain unproved; duplicate-SPKI rejection and activation denial are unchanged. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index ee7924cd61..ce97064c2f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -1383,8 +1383,11 @@ void staleSerializableConfirmationInsertRetriesInsteadOfLeakingUniqueViolation() assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("40001"); }); assertThat(tx(context, () -> confirm(context, original, decision))).isEqualTo(retained); - assertThat(tx(context, () -> readConfirmation(context, original, decision))) - .isEqualTo(retained); + // This case proves serialization and exact retained storage, not the distinct V90 WAL + // durability observation. Dedicated independent-read/receipt-COMMIT cases cover that gate; + // a global insert-frontier denial remains an open durability limitation, never a bypass. + assertThat(tx(context, () -> confirmationRow(context, original)).intoMap()) + .isEqualTo(retained.intoMap()); } assertThat( context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java index 5fb4ca04b7..16e14be596 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java @@ -50,8 +50,11 @@ public GameAsset save(GameAsset asset) { .set(CONTENT_TYPE, asset.getContentType()) .set(DATA, asset.getData()) .set(CREATED_AT, createdAt) - .returning() + .returning(ID, TENANT_ID, FILE_NAME, CONTENT_TYPE, DATA, CREATED_AT) .fetchOne(); + if (record == null) { + throw new IllegalStateException("Game asset insert did not return its persisted row"); + } return toEntity(record); } dsl.update(TABLE_REF) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java new file mode 100644 index 0000000000..f8c151d283 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.LocalDateTime; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.Test; + +class GameAssetRepositoryTest { + private static final Field ID = DSL.field(DSL.name("id"), Long.class); + private static final Field TENANT_ID = DSL.field(DSL.name("tenant_id"), String.class); + private static final Field FILE_NAME = DSL.field(DSL.name("file_name"), String.class); + private static final Field CONTENT_TYPE = + DSL.field(DSL.name("content_type"), String.class); + private static final Field DATA = DSL.field(DSL.name("data"), byte[].class); + private static final Field CREATED_AT = + DSL.field(DSL.name("created_at"), LocalDateTime.class); + + @Test + void insertUsesPostgresReturningFieldsAndMapsThePersistedRow() { + AtomicReference executedSql = new AtomicReference<>(); + DSLContext dsl = + DSL.using( + new MockConnection( + context -> { + executedSql.set(context.sql()); + var result = + DSL.using(SQLDialect.POSTGRES) + .newResult(ID, TENANT_ID, FILE_NAME, CONTENT_TYPE, DATA, CREATED_AT); + var returned = + DSL.using(SQLDialect.POSTGRES) + .newRecord(ID, TENANT_ID, FILE_NAME, CONTENT_TYPE, DATA, CREATED_AT); + returned.set(ID, 73L); + returned.set(TENANT_ID, "tenant-1"); + returned.set(FILE_NAME, "map.png"); + returned.set(CONTENT_TYPE, "image/png"); + returned.set(DATA, new byte[] {1, 2, 3}); + returned.set(CREATED_AT, LocalDateTime.of(2026, 10, 9, 12, 30)); + result.add(returned); + return new MockResult[] {new MockResult(1, result)}; + }), + SQLDialect.POSTGRES); + GameAsset input = new GameAsset(); + input.setTenantId("tenant-1"); + input.setFileName("map.png"); + input.setContentType("image/png"); + input.setData(new byte[] {1, 2, 3}); + input.setCreatedAt(LocalDateTime.of(2026, 10, 9, 12, 30)); + + GameAsset saved = new GameAssetRepository(dsl).save(input); + + assertThat(executedSql.get().toLowerCase(Locale.ROOT)) + .contains( + "insert into \"game_assets\"", + "returning \"id\", \"tenant_id\", \"file_name\", \"content_type\", " + + "\"data\", \"created_at\""); + assertThat(saved.getId()).isEqualTo(73L); + assertThat(saved.getTenantId()).isEqualTo("tenant-1"); + assertThat(saved.getFileName()).isEqualTo("map.png"); + assertThat(saved.getContentType()).isEqualTo("image/png"); + assertThat(saved.getData()).containsExactly(1, 2, 3); + assertThat(saved.getCreatedAt()).isEqualTo(LocalDateTime.of(2026, 10, 9, 12, 30)); + } + + @Test + void insertFailsClearlyWhenPostgresReturnsNoPersistedRow() { + DSLContext dsl = + DSL.using( + new MockConnection( + context -> + new MockResult[] { + new MockResult( + 0, + DSL.using(SQLDialect.POSTGRES) + .newResult(ID, TENANT_ID, FILE_NAME, CONTENT_TYPE, DATA, CREATED_AT)) + }), + SQLDialect.POSTGRES); + GameAsset input = new GameAsset(); + input.setTenantId("tenant-1"); + input.setFileName("map.png"); + input.setContentType("image/png"); + input.setData(new byte[] {1, 2, 3}); + + assertThatThrownBy(() -> new GameAssetRepository(dsl).save(input)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Game asset insert did not return its persisted row"); + } +} From 9f59da0ae5cad71fc8666f16cf12a543949536da Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:02:56 +1300 Subject: [PATCH 036/129] Retain exact World artifact inventory and durable asset export evidence --- .../game-design-service/asset-storage.md | 27 +- .../game-design-service/configuration.md | 1 - .../game-design-service/version-control.md | 1 + .../world-management-service/api-contracts.md | 2 + .../runtime-and-data.md | 10 + ...system-architecture-asset-store-runbook.md | 4 +- ...ame-authoring-publishing-and-activation.md | 16 +- .../config/AssetStoreProperties.java | 8 - .../service/impl/AssetExportServiceImpl.java | 118 +-- ...setPublicationPostgresIntegrationTest.java | 129 ++- .../service/AssetExportServiceImplTest.java | 252 +++-- ...dDraftPublicationCheckpointRepository.java | 28 +- ...SelectedDraftPublicationFreezeService.java | 24 +- ...dSelectedPublicationArtifactInventory.java | 857 ++++++++++++++++++ ...ublicationArtifactInventoryRepository.java | 202 +++++ ...elected_publication_artifact_inventory.sql | 112 +++ ...uthorizedDraftPostgresIntegrationTest.java | 97 +- ...ctedDraftPublicationFreezeRequestTest.java | 14 +- ...ctedDraftPublicationFreezeServiceTest.java | 34 +- ...ectedPublicationArtifactInventoryTest.java | 219 +++++ 20 files changed, 1841 insertions(+), 314 deletions(-) create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryRepository.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V55__selected_publication_artifact_inventory.sql create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 1f786fdb8e..44794d9b48 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,7 +6,7 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b ## Implementation Status -- **Current first slice:** Ordinary uploaded bytes are persisted in `game_assets.data`, which the live exporter selects through a process-local snapshot for Published/Active binary assets. V37 now provides durable version-asset mapping and export-snapshot storage plus owner-local freeze/read methods, but production Draft mapping authoring and exporter wiring are absent; current publication therefore does not prove use of that persisted selection. The byte source is not database-enforced immutable: the repository can update `data` for an existing row, even though no current REST update route is exposed. Publication currently exports the bytes to version-scoped object storage and exposes the numeric `GameAssetDto.id`; the target private-candidate/content-addressed publication and opaque logical asset identifier are not live. See the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle) for the storage and proof boundary. +- **Current first slice:** The ordinary exporter requires V37's durable version-scoped snapshot and verifies its mappings and retained `game_assets.data` bytes before each export or retry. There is no tenant-wide fallback or process-local selection cache. Production Draft mapping/source authoring and automatic snapshot creation remain absent, so missing evidence denies export rather than proving an empty release. Frozen source bytes are database-protected, while unreferenced Draft uploads remain mutable. Version-prefix object writes, numeric public asset identifiers and post-write repair comparison remain drift from the target immutable-candidate lifecycle. See the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle) for capability and proof limits. - **Current upload admission gap:** The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) are requirements, not current proof. `AssetController` accepts multipart uploads and `GameAssetServiceImpl` calls `MultipartFile.getBytes()` without size or quota enforcement; `AssetStoreProperties` has no matching limits. Upload admission and resource-safety readiness therefore remain incomplete and the route must not be treated as ready for external enablement. - **Hosted-content gate gap:** Current asset upload and publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The current Gateway's coarse `/api/design/**` route nevertheless forwards `/api/design/assets` (after `StripPrefix=2`) to the live `POST /assets` controller, whose Game Design boundary checks only privileged JWT/tenant access. Official-hosted asset-upload readiness is blocked until Gateway denies that route or the exact Account-owned gate is implemented and proved. - **Current lifecycle proof:** `version_asset_artifact` records the exported version-number prefix and manifest asset keys, but it does not yet freeze the target exact immutable object-key/digest set or implement the target global publication/purge fence. Repair writes those live prefix objects and the manifest before its exact release-bundle comparison, so pre-write verification is target-only. @@ -116,6 +116,14 @@ Required-artifact attestation contract: - If `requiredManifestAssetKeys[]` contains `world.navmesh` or `world.pathGraph`, runtime launch and cutover tooling must require the corresponding `manifest.json` entry to exist and match the attested release metadata. - Consumers must not infer requiredness from filename conventions, producer type, or the mere presence or absence of an entry in `manifest.json`. +### Complete selected-release asset inventory + +Game Design separately owns the complete immutable asset manifest and requiredness/export attestation for one exact selected release. Its versioned closed source model must enumerate every applicable ordinary asset selection, normalized template/branding reference and supported launch-requiredness input, including explicitly proved empty families. The evidence binds the canonical tenant/version/commit, selected source identity and source revisions, and exact Account publication operation. Every exported asset additionally binds its immutable actual-byte digest and manifest entry. Unknown, unrepresentable, omitted or unbound source inputs deny completeness; nullable `version_asset.usage_type`, missing mappings, tenant-wide upload enumeration and mutable template JSON are not requiredness authority. + +An empty `requiredManifestAssetKeys[]` is valid only with authenticated complete evidence that this selected release has zero required and exported assets. A frozen ordinary mapping snapshot alone does not establish that condition. Likewise, fresh command/policy genesis does not prove asset-source genesis. Any explicitly empty baseline must originate in the actual fresh source-creation transaction, remain bound to that source's subsequent writer/commit history and survive exact durable readback; retained or unqualified source records cannot receive an inferred empty baseline. + +Game Design verifies the independent [World inventory](../world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) through common exact selection/source-graph and publication bindings. World cannot attest Game Design assets, and Game Design cannot replace World requiredness with its own missing manifest entry. The two records must not depend on circular mutual receipt issuance. If a release requires `world.navmesh` or `world.pathGraph`, the corresponding actual-byte artifact digest and manifest entry remain mandatory; an unavailable producer denies publication. This contract is not evidence that the complete source writer, inventory producer, immutable export or authenticated read has executed; those gaps remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + Illustrative `GetPublishedReleaseBundle` fragment: This target-state attestation example uses a UUID-shaped `versionId`. Current Game Design transport examples must use numeric `int64` `versionId` values until the related protobuf fields are migrated together. @@ -338,14 +346,14 @@ Implementation notes: - `GetVersionAssetArtifactState`, `RepairPublishedVersionAssets`, `TombstoneVersionAssets`, `CanDeleteVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `GetVersionAssetPurgeStatus` are now live in `game-design-service`. - `version_asset_artifact` is now a persisted control-plane row and full-version publish updates it through `EXPORTED_UNATTESTED` and `PUBLISHED`. -- the persisted artifact row now stores the exact exported version number plus manifest asset keys for current completed-export cleanup/prefix deletion; it does not yet provide the durable frozen source-row/content proof or immutable object-key/digest proof required for exact repair or target content-addressed purge. The current first slice therefore keeps Published/Active repair unavailable after process loss and uses only its current version-prefix cleanup path; a failed write before `ExportAssets` returns still has no durable key proof and remains an implementation gap. See the lifecycle and repair/purge sections below for the target proof boundary. +- The persisted artifact row stores exported version number and manifest asset keys for completed-export prefix cleanup; V37 separately supplies the durable frozen ordinary source selection now required by export. Neither record supplies the target immutable object-key/digest proof or pre-write ambiguous-export journal. Detailed remaining lifecycle and recovery gaps belong in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle). - `CanDeleteVersionAssets` now also fails closed on live launch-descriptor references and on approved template remap sets that still name the source or target version, so purge cannot silently remove bytes still needed by current launch and replacement-cutover control-plane truth. - `version_asset_purge_workflow` is now the retained workflow-status surface for purge start/finalization outcomes. A basic repository (`GameAssetRepository`) and service implementation (`GameAssetServiceImpl`) persist uploads through the service-local jOOQ/PostgreSQL data boundary. -At publish time, the current implementation reads asset bytes from `game_assets.data`, freezes a process-local selection for the version, revalidates that the version has not become Published/Active immediately before caching the snapshot, and exports those bytes into version-scoped published prefixes in object storage, referencing them in the generated `manifest.json`. This direct prefix export is implementation drift; target convergence builds and verifies a private candidate with mandatory actual-byte digests, then exposes immutable content-addressed objects through the [Asset Lifecycle and Publish Workflow](#asset-lifecycle-and-publish-workflow). Duplicate file-name usage keys and the reserved `manifest.json` key fail closed before any object-store write. The process-local snapshot cache is bounded by `asset.store.frozen-snapshot-cache-max-entries` (default `256`); a new uncached version scope fails closed with `EXPORT_SNAPSHOT_CAPACITY` at capacity rather than evicting retry evidence. Target runtime clients load branding and theme resources directly from the approved public `/assets/**` origin using the manifest; that origin may be backed by a CDN, but a CDN is not required. The Game Design Service is not involved in byte delivery, but its `GetPublishedReleaseBundle` response and attested `manifestHash` remain the control-plane authority. In the current first slice, generated manifest URLs use the private `ASSET_STORE_ENDPOINT` and are not client-facing or usable by runtime clients; delivery remains blocked pending a separate approved public origin/provisioner for canonical `/assets/**`, and private MinIO is not public delivery. A future metadata-only storage model may use retained immutable object-store draft keys, but those keys are target-only and are not the current upload or repair source. See [Game Design Service Architecture](README.md) for how these assets fit into published versions. +Publication exports only the exact retained version selection, verifying every source-row identity and actual-byte hash before any object-store write. Missing or inconsistent owner evidence fails closed; a process restart never permits reselection from current tenant uploads. The target immutable private-candidate and content-addressed output contract remains in the [Asset Lifecycle and Publish Workflow](#asset-lifecycle-and-publish-workflow). Current ordinary export still writes version-prefix objects and generates private `ASSET_STORE_ENDPOINT` URLs, not usable public delivery; those limitations remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle). Runtime branding/theme bytes use the separately provisioned public `/assets/**` origin; Game Design's attested manifest remains release authority, not the origin or its optional CDN. The current repair ordering is not the target pre-write safety rule: `AssetExportServiceImpl` writes each version-prefix object and then `manifest.json`; only after that export returns does `VersionAssetArtifactServiceImpl` compare the resulting hash/key set with the published release bundle. A repair mismatch can therefore write or overwrite live prefix keys before it fails with `REPAIR_ATTESTATION_MISMATCH`. Target repair must build and verify away from published keys before any live write; this target rule is not current implementation proof. @@ -357,7 +365,7 @@ In the target contract, the `published_release_bundle` attestation must referenc ### Interaction with Script-Only Patches -Script-only patches (see `system-architecture-versioning-runtime.md`) do not change assets or any data stored in `game_assets` / `version_asset`. In the target contract, published asset selection is bound to `(tenantId, versionId)` and exported during full `PublishVersion` flows. The current production path does not yet use the V37 persisted binding: `AssetExportServiceImpl` selects every tenant asset and freezes the selection only in process-local memory, while no production `version_asset` authoring caller exists. A same-runtime rerun reuses the frozen selection; a Published/Active retry fails with `REPAIR_VERSION_SCOPE_UNAVAILABLE` when that selection is unavailable instead of reselecting the tenant-wide list. Asset changes therefore belong in a new `versionId` in the target state, while the current tenant-wide selection remains an implementation gap to be corrected before persisted version-bound export can be treated as proven. +Script-only patches (see [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md)) do not change assets or any data stored in `game_assets` / `version_asset`. Published asset selection is bound to `(tenantId, versionId)` and exported during full `PublishVersion` flows. Asset changes belong in a new `versionId`; the ordinary exporter consumes only that version's retained snapshot. Missing source authoring, completeness and lifecycle proof remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle), not an alternate tenant-wide selection rule. ### Asset Lifecycle and Publish Workflow @@ -409,15 +417,15 @@ Transition enforcement contract: - `PUBLISHED` is the only success state that may be treated as launchable. Object-store bytes in `STAGED` or `EXPORTED_UNATTESTED` are not publish-complete on their own. - For each `(tenantId, versionId)` the durable publish workflow runs an `ExportAssets` step that: - - **Current implementation:** initially selects every `game_assets` row for `tenantId` through `GameAssetRepository.findByTenantId`, including assets with no `version_asset` mapping, and reads the export bytes from `game_assets.data`. It freezes that selection in process-local memory before writing bytes. V37's `version_asset` table and repository methods exist, but no production Draft-version authoring action creates or removes mappings and the exporter does not consume the V37 snapshot. + - **Current implementation:** requires the retained V37 mapping snapshot and verifies actual source bytes before writing; it neither creates that snapshot nor falls back to tenant-wide uploads. Production Draft mapping/source authoring and complete requiredness remain gaps in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle). - **Target convergence:** freezes a persisted selection from `version_asset` joined to `game_assets` for the target `(tenantId, versionId)`; unmapped tenant assets are excluded from that version's export. The candidate is built privately, every selected byte is SHA-256 hashed, and the verified manifest and objects receive immutable content-addressed keys before public delivery. - Copies the selected ordinary asset bytes from `game_assets.data` (or a future equivalent immutable repair source) into private candidate storage, verifies the complete candidate, and only then publishes immutable content-addressed objects. A tenant/version prefix may remain a delivery grouping, but it is not the object identity or lifecycle authority. - Writes the version-scoped `manifest.json` as a content-addressed immutable object after candidate verification; it must not overwrite an attested manifest key. - Updates version metadata with the manifest location. - Transitions `version_asset_artifact` from `STAGED` to `EXPORTED_UNATTESTED`. - - **Target-only validation:** fails the workflow step if any asset referenced in `version_asset` for the target `(tenantId, versionId)` is missing, so partially published versions cannot be marked as Published. Although V37 supplies the mapping table and a repository snapshot check, production authoring/export is not wired to that boundary, so the live exporter does not perform this validation. + - **Current source validation:** a missing or mismatched asset referenced by the retained target snapshot denies export before object-store writes. Complete source authoring, private-candidate verification and the final publication gate remain separately unproved; this ordinary snapshot check alone cannot establish that the release is complete. - **Target-state retry behavior:** Once the frozen export snapshot exists, rerunning `ExportAssets` for the same `(tenantId, versionId)` reuses that snapshot, recomputes and verifies the same content-addressed bytes, and leaves the version metadata consistent. It must not re-select assets after the snapshot is frozen, and it must not overwrite an attested public key. Changed bytes require a new key and release version. -- **Current implementation boundary:** `AssetExportServiceImpl` freezes a process-local version-scoped snapshot and reuses it for same-runtime reruns. V37 can persist `version_asset_export_item` evidence through `VersionAssetPublicationRepository`, but the production exporter does not call it, so current publication does not guarantee that a durable snapshot exists. A Published/Active retry reuses the process-local snapshot when it is still available and fails closed with `REPAIR_VERSION_SCOPE_UNAVAILABLE` when it is absent, rather than calling `GameAssetRepository.findByTenantId` again. After process loss, exact repair remains unavailable because the live exporter does not consume V37 snapshots, even when one exists. **Current drift:** if the Version row is now `RETIRED`, the live resolver can instead take a fresh tenant-wide `findByTenantId` snapshot after process loss because only `PUBLISHED`/`ACTIVE` fail closed; that selection is not exact repair proof and operators must treat the path as fail-closed until a durable version-scoped snapshot is used by the production exporter. +- **Current implementation boundary:** retries and reconstructed exporters re-read the same V37 snapshot and verify source bytes before writing. An absent or inconsistent snapshot denies export in every lifecycle state, including `RETIRED`; process loss never permits tenant-wide reselection. This ordinary source-selection boundary does not establish immutable object readback, complete requiredness or safe pre-write repair attestation. - A later `FinalizePublishedRelease` step must read the computed `manifestHash`, write `published_release_bundle`, and only then transition `version_asset_artifact` from `EXPORTED_UNATTESTED` to `PUBLISHED`. If the attestation write has a lost or ambiguous response, the artifact remains `EXPORTED_UNATTESTED` and reconciliation-required; it may move to `FAILED` only after exact readback proves that no `published_release_bundle` exists for the tenant/version at all and no unresolved attestation write or cleanup ambiguity remains. Any existing row, including a mismatched attestation, keeps the artifact nonterminal until owner reconciliation determines the outcome; a matching committed attestation permits reconciliation to `PUBLISHED` and never `FAILED`. Implementations must not expose launchable `PUBLISHED` assets without a matching release attestation. - The `EXPORTED_UNATTESTED` readback and any transition to `FAILED` must be serialized against concurrent publication for the same `(tenantId, versionId)`. The owner transaction (or one shared lifecycle CAS/lock fence held across the readback and state transition) must lock or compare the artifact row and exact `published_release_bundle` identity together, re-read the bundle immediately before deciding `FAILED`, and reject a stale state epoch. A matching bundle that committed before or during the readback reconciles the artifact to `PUBLISHED`; a missing bundle can transition to `FAILED` only when the same fenced readback proves no publication committed and no external write remains ambiguous. A later failure must never demote a matching publication or delete its version/assets. - Current implementation drift is sharper than the target rule: after bundle creation, the publish catch path still marks failure, performs best-effort cleanup, and calls `VersionRepository.delete`. Since `published_release_bundle.version_id` is a non-cascading foreign key, that compensation delete can fail after a committed bundle. Target recovery must reconcile bundle/readback evidence and must never delete Version to compensate for an ambiguous post-bundle failure; focused proof must cover committed-bundle, missing-bundle, and lost-response branches. @@ -444,8 +452,8 @@ Exact-bytes repair rule: - Repair of a Published/Active version must begin by reading `GetPublishedReleaseBundle(tenantId, versionId)`. - **Target state:** Repair must also read `GetVersionAssetArtifactState(tenantId, versionId)` and prove the expected `artifactState`, `stateEpoch`, and `manifestHash` before any bytes are rewritten. **Current implementation:** the export invoked by repair writes version-prefix objects and `manifest.json` before `VersionAssetArtifactServiceImpl` performs the exact repair-match comparison, so a mismatch can mutate live prefix keys before returning `REPAIR_ATTESTATION_MISMATCH`. - Repair must materialize candidate bytes away from published keys and verify every attested object and manifest digest before writing any missing immutable object. It may restore only exact attested content-addressed objects; if a repair source or digest is unavailable, it fails closed and requires a new version. -- Repair must read and verify the immutable per-version export snapshot, including every exported source-row ID and content hash. In the current implementation, the process-local frozen selection is the only available snapshot evidence; if it is absent because the service restarted or the version was exported without that evidence, Published/Active repair must fail closed with `REPAIR_VERSION_SCOPE_UNAVAILABLE` rather than guessing from current draft assets. Recovery then requires publishing a new `versionId` until the target persisted snapshot exists. -- Once version-scoped selection and its frozen snapshot exist, the repair workflow may regenerate ordinary object-store bytes from the retained `game_assets.data` rows recorded by that snapshot. The current repository does not enforce those rows as immutable and can update `data` by ID; target publication must replace bytes with a new source row or otherwise provide a retained immutable repair source before a Published/Active release relies on it. +- Repair must read and verify the immutable per-version export snapshot, including every exported source-row ID and content hash. Missing snapshot or source evidence fails closed rather than guessing from current Draft assets; service restart does not invalidate an existing exact durable snapshot or authorize a replacement selection. +- Once version-scoped selection and its frozen snapshot exist, the repair workflow may regenerate ordinary object-store bytes from the retained `game_assets.data` rows recorded by that snapshot. V37 prevents changes to those referenced source bytes; replacement requires a new source row and version mapping. This source protection does not substitute for verifying attested output before writing live objects. - If a future storage model replaces `game_assets.data` with metadata plus object-store handles, the replacement repair source must be immutable and retained for every non-Retired or design-history-reachable release. A mutable draft object key by itself is not a valid repair source. - The repair workflow may only regenerate object-store bytes that reproduce the existing attested `manifestHash` and every mandatory actual-byte digest in `artifactDigests[]`. - If regenerated bytes would change the attestation payload, the workflow must fail closed and require a new `versionId` rather than mutating the published release in place. @@ -455,7 +463,6 @@ Required deterministic repair/purge failure vocabulary: - `VERSION_ASSET_NOT_DELETABLE` when `CanDeleteVersionAssets` rejects eligibility. - `ASSET_ARTIFACT_STATE_CONFLICT` when `state_epoch` CAS fails or the lifecycle row no longer matches the caller's proof. - `ASSET_USAGE_KEY_COLLISION` when duplicate file-name-derived manifest keys or the reserved `manifest.json` key make the export ambiguous. -- `EXPORT_SNAPSHOT_CAPACITY` when the bounded process-local snapshot cache cannot admit a new version scope without evicting retry evidence. - `REPAIR_VERSION_SCOPE_UNAVAILABLE` when a Published/Active release lacks the frozen version-scoped export snapshot required for exact repair. - `REPAIR_ATTESTATION_MISMATCH` when repair cannot reproduce the attested `manifestHash`. - `PURGE_WORKFLOW_NOT_FOUND` when status or finalization reads reference an unknown `purgeWorkflowId`. diff --git a/design/architecture/microservices/game-design-service/configuration.md b/design/architecture/microservices/game-design-service/configuration.md index 038b2a5e59..4522036c4a 100644 --- a/design/architecture/microservices/game-design-service/configuration.md +++ b/design/architecture/microservices/game-design-service/configuration.md @@ -34,4 +34,3 @@ Published assets are uploaded to an S3-compatible bucket. Configure the client w | `ASSET_STORE_REGION` | Region name for the S3 client | `ap-southeast-2` | | `ASSET_STORE_ACCESS_KEY` | Access key for the bucket | *(none)* | | `ASSET_STORE_SECRET_KEY` | Secret key for the bucket | *(none)* | -| `ASSET_STORE_FROZEN_SNAPSHOT_CACHE_MAX_ENTRIES` | Maximum process-local frozen export snapshots retained; a new uncached scope fails closed at capacity rather than evicting retry evidence | `256` | diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 35e9f0a881..df64a8b4f9 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -144,6 +144,7 @@ In addition to domain-service digests, publish safety requires a Game Design con - The control-plane digest surface should be exposed through a read-only API (for example `GetDesignControlPlaneDigest`) so publish tooling uses a uniform participant contract. - `GetDesignControlPlaneDigest` should return at minimum `{tenantId, versionId or scriptPatchVersion scope, appliedCommitId, contentDigest, digestSchemaVersion}` so publish gates compare like-for-like payloads across all participants. - After all digest gates and verified private-candidate asset export succeed, Game Design must persist a single immutable `published_release_bundle` attestation for `(tenantId, versionId)` that captures the final participant digests, the manifest digest, the complete required artifact set, and `generationConfigRevision`. +- The [complete selected-release asset inventory](asset-storage.md#complete-selected-release-asset-inventory) owns the positive completeness and explicit-zero proof required before this export/attestation. Publication compares it with independent World evidence through the same exact selected source graph; neither an empty ordinary mapping snapshot nor a missing artifact producer can substitute. - Game Design must expose the attestation through `GetPublishedReleaseBundle(tenantId, versionId)` with deterministic response fields at minimum: - `tenantId`, `versionId`, `commitId`, `publishWorkflowId`, `publishedAt` - `participantDigests[] { serviceName, appliedCommitId, contentDigest, digestSchemaVersion }` diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 54aae869ab..e2a197accf 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -104,6 +104,8 @@ The successful acknowledgement is the complete tuple `{tenantId, versionId, publ For the selected-Draft producer, World also returns the immutable `worldIntakeRequestId` resolved from that exact retained `APPLIED` application. This UUID is selector correlation, not a private numeric key or caller-supplied association. Game Design combines it with the authenticated freeze acknowledgement and the complete affected tuples from its unchanged selected commit to construct the exact World selector-read request. World must verify that request against its retained application and selector evidence; the freeze acknowledgement and intake correlation alone do not supply the selector receipt, terminal publication evidence or admission authority. Exact retries preserve the same intake correlation with the original freeze. +The selected-release artifact inventory/read must authenticate Game Design before content access and return the exact immutable inventory retained with the qualified selected graph and freeze. Its closed-model completeness, source bindings and artifact requiredness are owned by [World runtime and data](runtime-and-data.md#complete-selected-release-artifact-inventory). Missing or mismatched inventory evidence cannot be represented as an empty artifact list, and this owner read confers neither Account settlement nor release/admission authority. + Every Draft `ApplyWorldDesignMutation` must first lock and check the same owner-freeze row for its `(tenantId, versionId)` target, including an ordinary or otherwise unbound mutation that does not carry a publication request identity. An ordinary mutation may proceed only while the owner row is in its writable `OPEN` state with no active publication freeze. A publication-bound mutation must additionally carry `publicationRequestId`, the exact `requestDigest`, the exact observed Game Design `versionStateEpoch`, and the exact WMS `publicationFence` from that acknowledgement, so it cannot be admitted before the fence exists. It may execute in `FROZEN` only when it is one of the explicitly pre-authorized final publication mutations covered by that request digest; `FROZEN` is not reopened for arbitrary Draft writes, and an unbound or mismatched mutation remains rejected. The final publication digest checkpoint includes the result of any such authorized mutation, and the owner must not accept another mutation after that bounded publication step. Both forms reject or drain stale or mismatched evidence, `PUBLISHED`, `RECONCILIATION_REQUIRED`, and any unauthorized `FROZEN` phase; an `ABORTED` attempt remains closed to ordinary writes until its failed or ambiguous outcome is reconciled and the owner row is reopened without accepting the old fence. A pre-freeze writer that already holds the row lock may finish before the acknowledgement; no writer reaching the lock afterward may commit unless it is the exact pre-authorized publication-bound mutation. The owner mutation result and updated digest checkpoint remain bound to the applicable request, digest, and fence. Game Design completes the handoff through one outcome-typed terminal operation, `CompleteVersionPublication`, carrying exactly `tenantId`, `versionId`, `publicationRequestId`, `publishWorkflowId`, `requestDigest`, `publicationFence`, `outcome`, and the final owner evidence. The cross-service field bindings are canonical: Game Design `publishRequestId` is WMS `publicationRequestId`; Game Design `publishWorkflowId` is the durable publication-workflow identity for the attempt and is required as explicit input and evidence; Game Design `publishedReleaseBundleRef` is WMS `publishedReleaseBundleId`; and each Game Design participant `commitId` is WMS `appliedCommitId`. `outcome=PUBLISHED` requires the immutable release evidence `{publishedReleaseBundleId, publishedReleaseBundleDigest, publishWorkflowId, versionStateEpoch}` plus the final WMS digest checkpoint `{appliedCommitId, contentDigest, digestSchemaVersion}`. Every participant digest and artifact evidence item is bound under that same outer `publishWorkflowId`, and WMS exact-compares the workflow identity across the request, release bundle, participant attestations, and stored publication attempt; any mismatch, omission, or incomplete binding fails closed as an idempotency or reconciliation conflict. WMS records that evidence and atomically advances the row to `PUBLISHED`, after which all later Draft mutations with that fence are rejected. `outcome=ABORTED` requires the same request/fence/workflow identity and reconciled no-publication evidence, records the terminal abort, and permits Draft writes only after the failed/ambiguous Game Design attempt has been reconciled and the old fence is no longer accepted. The operation authenticates the Game Design caller and never treats a Temporal completion as owner proof. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index f117d74289..a7c06d11ae 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -191,6 +191,16 @@ Publish gating fails closed if World Management cannot attest a digest consisten In the initial slice, exported world artifacts such as navmesh/path-graph bundles are not folded into World Management’s `contentDigest`. Instead, the publish workflow must attest them separately through typed artifact digest entries and manifest usage keys bound to the same release identity as the world participant digest. +### Complete selected-release artifact inventory + +World owns a typed, authenticated, immutable `COMPLETE` inventory for the exact selected, retained `APPLIED` graph. It binds the canonical tenant/version/commit, original source and application identities, complete affected scopes and applied epochs, exact Account publication-order identity and fence, topology result and graph digest, and the publication freeze/checkpoint. World captures and durably reads back that inventory under the same owner lock as its qualified first freeze; a caller-supplied inventory or later current-state sample cannot replace the selected graph. Exact retries preserve the original inventory rather than reclassifying mutable source state. + +The inventory identifies a versioned, closed source model and enumerates all six current topology families from the digest manifest, including explicit zero counts. Its requiredness evaluation covers the complete typed topology, region generator type/parameters, generation-rule name/scope/value, and typed spawn bindings. Unknown schemas, fields, families, omitted requiredness inputs, or unrepresentable generation semantics deny `COMPLETE`; missing producer rows or runtime consumers never establish that an artifact is unnecessary. The direct-authored room/exit model uses its persisted directed edges and does not require a separate generated navigation bundle; typed room-bound spawn references alone do not change that rule. Opaque generation inputs cannot inherit this classification without a defined, proved requiredness interpretation. + +The complete derived-family enumeration includes `NAVMESH` and `PATH_GRAPH`, each with an explicit decision bound to those source inputs. If the selected source requires either family, publication requires the actual finalized producer record and byte digest under the [Game Design asset handoff](../game-design-service/asset-storage.md#complete-selected-release-asset-inventory); an absent producer denies that release, rather than changing its requiredness or omitting the family. A supported release must not be relabeled empty or unsupported merely to avoid producing its required artifacts. + +World's inventory attests only World-owned source and derived-artifact requirements. It does not establish Game Design asset completeness, export success, release attestation, or runtime admission. Game Design compares its independent asset evidence with World evidence using their common exact selection/source-graph and publication bindings, not mutually issued receipts. Current implementation and physical proof remain separately recorded in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + ## Instance-Scoped Population Schedule Contract Runtime population materialization is documented separately from published spawn bindings: diff --git a/design/architecture/system-architecture-asset-store-runbook.md b/design/architecture/system-architecture-asset-store-runbook.md index 5aa44b6e28..9c7be1792c 100644 --- a/design/architecture/system-architecture-asset-store-runbook.md +++ b/design/architecture/system-architecture-asset-store-runbook.md @@ -8,7 +8,7 @@ Game Design owns publication coordination, release descriptors, asset lifecycle, ## Implementation Status -- `CanDeleteVersionAssets`, `GetVersionAssetArtifactState`, `RepairPublishedVersionAssets`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `GetVersionAssetPurgeStatus` are live Game Design control-plane APIs. The `version_asset_artifact` proof row currently records lifecycle state, state epoch, manifest hash, exported version number, and exported manifest asset keys. In the current first slice, `RepairPublishedVersionAssets` repairs ordinary assets from `game_assets.data` to those persisted exported version-scoped keys only while the process-local frozen version selection remains available; the proof row alone is not restart-safe, and an unavailable selection fails closed with `REPAIR_VERSION_SCOPE_UNAVAILABLE`. +- `CanDeleteVersionAssets`, `GetVersionAssetArtifactState`, `RepairPublishedVersionAssets`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `GetVersionAssetPurgeStatus` are live Game Design control-plane APIs. Ordinary export/repair requires the exact retained V37 selection and source-byte verification on every call, including after process restart; missing evidence denies before export and cannot be replaced by tenant-wide upload selection. The artifact proof row alone is insufficient. Remaining lifecycle, immutable output and pre-write attestation gaps are recorded in the [authoring tracker](../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle). - Content-addressed private-candidate publication and producer-owned derived-artifact handoff remain target-state. The current first slice still repairs ordinary bytes from `game_assets.data`, exports version-scoped objects, and persists a narrower `published_release_bundle` that lacks the complete target manifest-schema and mandatory actual-byte artifact-digest fields. - The live `TombstoneVersionAssets` implementation accepts only `FAILED` and `PURGE_FAILED`; target tombstoning of an eligible retired `PUBLISHED` release is not implemented. The runbook must fail closed for that path rather than claim the current API supports it. - The target failed-candidate path requires the Game Design-owned, idempotent `AbandonFailedVersionAssets` record/read proof bound to the caller tenant, `FAILED` version/artifact epochs, request identity/digest, and no release reachability. That abandonment record/API is not implemented; the current tombstone path does not enforce it. @@ -23,7 +23,7 @@ Game Design owns publication coordination, release descriptors, asset lifecycle, ## Health Checks - Monitor storage availability, latency, and error rates. -- Verify supported Game Design uploads and the persisted Game Design artifact/bundle metadata reads used by the current repair path. Game Design does not currently expose a version-asset object-store GET/HEAD or byte-readback operation; current repair re-exports from the process-local frozen snapshot and fails closed after process loss. Client-facing asset download remains target-only because the approved public `/assets/**` origin is not implemented. +- Verify supported Game Design uploads and the persisted Game Design artifact/bundle metadata reads used by repair. The ordinary exporter revalidates its durable version snapshot across restart; that source evidence does not prove object-store output. Game Design still has no version-asset object-store GET/HEAD or byte-readback operation, and client download remains target-only pending the approved public `/assets/**` origin. ## Incident Handling 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 611a0d6a74..e72b2bc6c1 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The selected-release inventory contract is now explicit in the [World owner](../../architecture/microservices/world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) and [Game Design asset owner](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). World source-complete requiredness does not prove Game Design asset completeness. Game Design's actual synchronized source repository currently covers commands and realm policy only; V37's ordinary mappings and nullable usage classifier do not enumerate selected template/branding references or launch requiredness, and mutable template configuration has no exact selected-commit source binding. A complete asset-source writer, fenced commit history, immutable manifest/export producer and authenticated readback remain required. Fresh command/policy genesis, absent mappings or absent consumers cannot supply an empty asset baseline. All genuine publication and runtime activation gates remain open obligations, not completed handoffs. + +Published-head `39b800bdfe07cf94028fd4a175f79f42eb51c8e7` [Validation run 37853634338](https://github.com/benhook1013/FireMUD/actions/runs/37853634338) executed 245 Account, 81 Game Design and 206 World integration cases, with zero errors or skips. World passed in full. Game Design's selected-publication composition and four of five asset cases passed; the remaining asset fixture attempted a forbidden frozen-source update and correctly encountered the immutable-source trigger. The corrected fixture now requires SQLSTATE `23514`, unchanged source bytes and exact snapshot/retry readback; corrected-head PostgreSQL execution remains required. Account's serialization-specific retry and all nine isolated WAL cases passed. Its sole failure was the independent receipt-confirmation case at V90's conservative global-WAL coverage check: insert fence `0/4C2F760` exceeded flush `0/4C2F720`. This is still an open durability limitation, not production adoption of the isolated WAL investigation. Owner jobs used merge `a7d44052a8b69826f9673392da2a5a6bc973a7ad`, tree `aca615119c487f744e4f787a3042df993a8dbf65`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head; intended-parent alignment remains open. Security, CodeQL, License, Kustomize, preview planning and dependency submission passed. Optional downstream preview steps skipped, so this is not full-stack Smoke or proof of the later World inventory/export corrections. + Published-head `67a665036c04b155f83c252e606cefbc91f8fe4a` [Validation run 37850400728](https://github.com/benhook1013/FireMUD/actions/runs/37850400728) completed red. Physical integration XML records 240 Account cases with one failure, 206 World cases with no failures, and 81 Game Design cases with four failures; all have zero skips and errors. The previous three Account source-event and two World fixture failures are fixed. All seven original isolated WAL cases, the authenticated World first-freeze/terminal cases, and Game Design's selected-publication composition executed and passed. Four new asset cases fail before assertions because the live asset repository's dynamic-table insert does not return its saved row; explicit persisted-field readback and a focused regression are the bounded correction, not a fixture bypass. Account's remaining serialization test reaches V90's conservative receipt-read WAL denial: insert fence `0/4678018` exceeds initial/final flush `0/4678000`. That is an open durability limitation, not a reason to relax V90/V92 or claim the isolated investigation proves production adoption. Owner jobs checked out merge `a9607e8cd55f5245cbb87100fe2817400f752ded`, tree `7e0df9be73f2bdcdc71c28b9aaa3b503758b300a`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and `67a665036c04b155f83c252e606cefbc91f8fe4a`; intended-parent alignment remains open. Security, CodeQL, License, Kustomize, PR preview and dependency submission passed; this is not full-stack Smoke. Dependency-deferred duplicates add no runtime evidence. The later freeze-to-reservation composition and two additional WAL definitions were not in this run and still require corrected-head physical execution. Published-head `2560d12a8265db943a06e43d1e9e261bb2cdd923` [Validation run 37840711622](https://github.com/benhook1013/FireMUD/actions/runs/37840711622) finished red: 36 jobs passed, Account/World/the aggregate gate failed, and one tooling contract job skipped. Its physical XML records 233 Account cases with 208 failures, 206 World cases with 42 failures, and 75 Game Design cases with no failures; all have zero skips and errors. V107's PL/pgSQL syntax error blocked Account initialization and two World cases. All seven isolated WAL tests failed during migration setup, before their proof logic; this is neither WAL execution proof nor a new V92 durability verdict. World's other failures expose stale terminal fixtures missing V53 qualification (36 cases) and four terminal fixtures incorrectly entering unsupported generation/spawn preparation. The bounded syntax and fixture repairs require corrected-head physical execution; no production qualification or generation-intent guard may be weakened. Game Session and TCP Gradle checks passed with the bounded resource profile. Actual owner jobs checked out synthetic merge `e2bdaf5d011ba97d9a407183892e9ec7b069a909`, tree `1fb483d5c7ed53f27b483587a38909181aa3316b`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and `2560d12a8265db943a06e43d1e9e261bb2cdd923`. The live target had advanced 21 commits/33 paths beyond recorded base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`, with no Account/Game Design/World service differences; this explains composition but does not close intended-parent alignment. Substantive [CodeQL run 37840711613](https://github.com/benhook1013/FireMUD/actions/runs/37840711613) succeeded. Its dependency-deferred duplicate supplied no additional analysis; likewise metadata-only Validation run 37840712794 supplied no runtime proof. @@ -20,7 +24,7 @@ The terminal construction adds V54's bounded operation-frame check and repositor Expanded Game Design and World terminal repository/loopback-mTLS definitions retain actual local owner storage while stipulating upstream authorities. Account settlement's loopback-mTLS definition exercises its real creator/order/storage with two distinct strict clients, but the remote terminal endpoints and incoming Game Design context are stipulated. The independent Account readback connection checks commit before the second owner transaction; this is not an actual network lost-acknowledgement injection. These definitions require corrected-head physical execution and cannot establish a genuine multi-owner publication chain by themselves. The bounded CI heap-profile repair preserves full matrix validation and packaging tasks; the `2560d12a` Game Session and TCP jobs passed under that profile, without proving every future composed head. -The isolated Account WAL investigation is test-only and leaves V92's conservative production denial unchanged. All seven original dedicated PostgreSQL 16 cases executed and passed in the `67a665036` CI above. Two additional definitions exercise actual locator-owner immutable-storage triggers and genuine committed-WAL search-budget exhaustion after lost receipt acknowledgement, preserving complete operation, receipt and locator readback. Restricted-reader permission denials are also expanded. All nine definitions compile but skip locally without Docker; the two new cases still need physical execution. The fixture has no deterministic flush-control hook, and PostgreSQL 16 `pg_walinspect` exposes only complete records within the flush frontier; synthetic classifier inputs cannot establish either unflushed-tail success or exact-target insufficient-flush denial. Physical epoch wrap, promotion, WAL recycling and both flush scenarios remain open. Search-budget exhaustion is not recycled-WAL proof. Production extension feasibility and any adoption remain separate gates. The shared PostgreSQL 18 baseline does not change the Account admission executors' PostgreSQL 16-only guards. +The isolated Account WAL investigation is test-only and leaves V92's conservative production denial unchanged. All nine dedicated PostgreSQL 16 cases executed and passed in the `39b800bdf` CI above, including actual locator-owner immutable-storage triggers and genuine committed-WAL search-budget exhaustion after lost receipt acknowledgement with unchanged operation, receipt and locator evidence. Restricted-reader permission denials are also covered. They still skip locally without Docker. The fixture has no deterministic flush-control hook, and PostgreSQL 16 `pg_walinspect` exposes only complete records within the flush frontier; synthetic classifier inputs cannot establish either unflushed-tail success or exact-target insufficient-flush denial. Physical epoch wrap, promotion, WAL recycling and both flush scenarios remain open. Search-budget exhaustion is not recycled-WAL proof. Production extension feasibility and any adoption remain separate gates. The shared PostgreSQL 18 baseline does not change the Account admission executors' PostgreSQL 16-only guards. Overseer-owned isolated [Pod admission run 37830726704](https://github.com/benhook1013/FireMUD/actions/runs/37830726704) passed the Account and Game Session CREATE/adversarial matrices plus UPDATE and ephemeral-container checks; Overseer reported the owned cluster deleted after the run. This is admission-only evidence. CNI/socket routing, kubelet UID/process correspondence, replacement races, shared-key closure and promotion readiness remain unproved; duplicate-SPKI rejection and activation denial are unchanged. @@ -30,7 +34,7 @@ The legacy World numeric mutation route lacks the target shared-lock handoff, bu The World selected-fresh-graph checkpoint callback derives its commit identity from the exact retained Account-bound `APPLIED` application, rather than a caller-supplied checkpoint. Under the shared owner lock it rechecks the complete current graph and epoch set and computes the schema-3 content digest. Construction CI at `60c507243987705094a3028e0b46f3bccd5d9504` executed the actual Account-order-to-World-APPLIED and selected-checkpoint cases. The standalone selected-publication freeze composition obtains authenticated immutable selection, current Game Design Draft state and exact Account held-order reads outside SQL, then retains the complete Account binding atomically with the first World freeze. V53 denies late qualification of historical attempts. The new closed freeze transport owner-resolves the retained APPLIED plan without accepting caller-supplied private World identities or topology. Its acknowledgement retains the committed freeze event and owner-observed epoch, not terminal publication or admission authority. Exact committed retry verifies the stored order before recapturing mutable authority. The revised combined PostgreSQL definition uses the original owner-issued creator credential to obtain a real distinct Account publication order, reads its actual `HELD` state over strict loopback mTLS, and invokes first freeze and exact retry through a fresh authenticated Game Design-to-World socket. Game Design selection/current-Draft endpoints remain explicit fixture stipulations. Source protection is checked before and after freeze, but the original Draft order also remains pending, so writer denial does not isolate publication as its sole cause. The corrected qualification/rollback and transport definitions still require physical execution. This does not change the generic digest's synthetic highest-commit limitation, register a freeze RPC, settle either owner, or establish end-to-end publication authority. -The bounded Game Logic manifest contract is recorded at its [canonical owner](../../architecture/microservices/game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake), but its producer and intake remain unimplemented. Game Design currently retains command-definition and realm-entry-policy source captures; the command empty-genesis receipt does not establish a complete empty ability/catalog inventory. Complete authored-input inventory, immutable Game Logic retention, dedicated ability-schema evidence and Account-backed authorization through the intake commit remain concrete prerequisites. Unsupported or unknown families stay denied rather than being filtered into an empty manifest. Separately, the existing V37 asset mapping/snapshot storage now has explicit caller-transaction guards and five PostgreSQL proof definitions for exact version isolation, retained-row denial, immutable readback and source substitution; these local definitions skip without Docker and do not wire the production exporter. +The bounded Game Logic manifest contract is recorded at its [canonical owner](../../architecture/microservices/game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake), but its producer and intake remain unimplemented. Game Design currently retains command-definition and realm-entry-policy source captures; the command empty-genesis receipt does not establish a complete empty ability/catalog inventory. Complete authored-input inventory, immutable Game Logic retention, dedicated ability-schema evidence and Account-backed authorization through the intake commit remain concrete prerequisites. Unsupported or unknown families stay denied rather than being filtered into an empty manifest. Separately, V37 asset mapping/snapshot storage has caller-transaction guards and five PostgreSQL proof definitions for exact version isolation, retained-row denial, immutable readback and source substitution. The ordinary exporter now consumes its durable verified snapshot; the expanded actual repository-to-exporter test uses a mocked object-store sink and skips locally without Docker, so it is not executed storage-delivery proof. The standalone Game Design terminal owner read verifies complete original operation and terminal backing in an independent read-only repeatable-read snapshot. Its closed transport follows the [exact terminal-read contract](../../architecture/microservices/game-design-service/api-contracts.md#exact-publication-terminal-read); owner/transport unit definitions do not establish physical authenticated terminal composition. The receiver remains unregistered. World completion and distinct Account settlement now have unregistered construction components, but their genuine composed producer and physical proof remain open. @@ -106,7 +110,7 @@ These links add decision provenance only; they do not change existing implementa | `AR-1.1` World, entity, rule, and content authoring | `partial` | `proven` for the typed revision-to-World mutation, authored help/command, and entity-template validation seams; complete world, entity, rule, and content authoring remains unproved. | [Game Design ownership](../../architecture/microservices/game-design-service/README.md); [world editing tools](../../architecture/microservices/game-design-service/world-editing-tools.md); [ability/action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [item and equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [GameAuthoredHelpTopicServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql); [EntityTemplateReferenceServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImpl.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [GameAuthoredHelpTopicServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java); [EntityTemplateReferenceServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityTemplateReferenceServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md) | Partial: typed revision-to-World mutation, authored help/commands, and entity template/runtime validation seams exist, but complete rule/action/effect catalogs and creator-facing authoring workflows are not implemented. Accepted procedural-generation decisions now define World-owned typed ingress and preview-bound replacement, but typed generation ingress, destructive plan protocol, and identity/reference proof remain incomplete. | | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and typed generation mutation seams; LLM-assisted authoring, typed generation ingress, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and typed generation mutations exist. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. Accepted procedural-generation decisions now define one World-owned engine, request-bounded replay, bounded persistence, previewed replacement, and sparse/full-grid semantics; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | -| `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `audited` | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: export, artifact-state, manifest-hashing, repair, and purge seams exist, but the required fail-closed version-scoped publication gate is not implemented. V37 mapping/snapshot storage and its repository exist, but production Draft-version authoring/export integration is absent; `AssetExportServiceImpl` exports every tenant asset, and publication does not prove that only mapped assets were selected. The selected-Version v2 bundle binds target commit, manifest schema and exact participant/artifact evidence; the live exporter cannot yet supply its complete immutable artifact evidence. Release readiness cannot be claimed until the mapping/authoring path and guard exist with focused proof. Normalized asset/history and derived-artifact substrates plus complete creator asset UX remain absent. Accepted asset/publication decisions now define content-addressed bytes, fail-closed attestation, and version-scoped publication; version-scoped asset production/export, complete owner evidence and genuine release readiness remain incomplete. | +| `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `audited` | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: export, artifact-state, manifest-hashing, repair, and purge seams exist, but the required fail-closed version-scoped publication gate is not implemented. The ordinary exporter now requires V37's durable verified version selection with no tenant-wide fallback. Production Draft source/mapping authoring, complete requiredness and automatic snapshot creation remain absent; the actual repository-to-exporter proof is defined but skips locally without Docker. The selected-Version v2 bundle binds target commit, manifest schema and exact participant/artifact evidence; the live exporter cannot yet supply its complete immutable artifact evidence. Release readiness cannot be claimed until the mapping/authoring path and guard exist with focused proof. Normalized asset/history and derived-artifact substrates plus complete creator asset UX remain absent. Accepted asset/publication decisions now define content-addressed bytes, fail-closed attestation, and version-scoped publication; version-scoped asset production/export, complete owner evidence and genuine release readiness remain incomplete. | | `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` only for current revision/version publication, the fail-closed publish gate, and happy-path release-bundle and participant-digest seams; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: revision/version publication and fail-closed gate seams exist, but generic participant tokens remain synthetic and genuine same-commit attestation convergence is not established. The selected-Version v2 bundle and schema-3 World gate are implemented construction boundaries, not proof of complete immutable participant/export production. Accepted publication, release, asset, and procedural-generation decisions now define the target authority chain; complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | @@ -178,7 +182,7 @@ The broader authored-action model is not complete. The locked expansion boundary ### Publication, Temporal Workflows, and Release Attestation -Asset lifecycle status and proof remain partial: V37 and `VersionAssetPublicationRepository` provide durable `version_asset` mappings and export snapshot/item storage, but the live exporter does not consume them and still selects tenant-wide assets with only process-local retry evidence. V38's candidate-evidence columns are groundwork, not a proved pre-write export journal or immutable object readback. Version-scoped readiness, lifecycle operation safety, and publication recovery remain unproved. The canonical upload, hosted-gate, version-scoped export, attestation, lifecycle, and purge rules are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions); this tracker records the current status and proof gaps without repeating those owner contracts. +Asset lifecycle status and proof remain partial: the ordinary exporter now consumes V37's durable `version_asset` snapshot and revalidates source bytes on every retry, with no process-local or tenant-wide fallback. Production source/mapping authoring and automatic snapshot creation remain absent; a missing snapshot denies before object-store writes. V38's candidate-evidence columns are groundwork, not a proved pre-write export journal or immutable object readback. Version-scoped readiness, complete requiredness, lifecycle operation safety and publication recovery remain unproved. The canonical upload, hosted-gate, version-scoped export, attestation, lifecycle and purge rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions). Full-version and script-patch publication use the live durable `publish_attempt`/participant-observation framework. World emits schema `2`, which the gate supports; current participant observations still use synthetic scope tokens, and same-commit convergence with focused proof remains incomplete. End-to-end full-version publication remains blocked because the Game Logic full-version owner digest fails closed without owner-local manifest/provenance for the version's rule inputs; its implementation status is recorded in [Game Logic API Contracts](../../architecture/microservices/game-logic-service/api-contracts.md#implementation-status). The canonical digest and participant contracts are owned by [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); this tracker records only those implementation/proof gaps. @@ -190,7 +194,7 @@ Temporal publication authorization has a distinct Game Design gRPC workload iden ### Published Asset Lifecycle -Current status/evidence: Game Design owns publication and the `version_asset_artifact` proof read. Durable mapping and snapshot storage exists under V37, but its production authoring/export callers are absent; live export remains tenant-wide with only a process-local selection. Published/active repair and retired-version handling retain fail-closed drift, and version-scoped readiness is not proven. Focused asset export, attestation, and lifecycle proof remains partial. +Current status/evidence: Game Design owns publication and the `version_asset_artifact` proof read. Ordinary export and reconstructed exporters require V37's durable snapshot and verify exact source bytes before writing. No production source/mapping authoring or automatic snapshot creation is wired; missing evidence denies in every lifecycle state. Complete requiredness, pre-write attestation, content-addressed output, version-scoped readiness and lifecycle proof remain incomplete. Lifecycle status/proof is also incomplete: artifact and Version epoch checks lack database CAS; tombstone eligibility and failed-candidate abandonment are not fully implemented; post-bundle publish-failure reconciliation and durable ADR 0048 operation identity are absent. The canonical state, transition, purge, repair, and reachability rules remain owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow) and the [Asset Store Runbook](../../architecture/system-architecture-asset-store-runbook.md#removing-published-versions); this tracker records only implementation status and proof gaps. @@ -224,7 +228,7 @@ Game Design owns revision history, commits, version state, and publish orchestra - Inventory/equipment was a documentation-only authority decision with no runtime behavior change; its recorded proof is `./gradlew linkCheck lintMarkdown`. - Settings schema/reference generation and verification are available through `./gradlew updatePlatformSettingsDocs` and `./gradlew verifyPlatformSettingsDocs`; persistence, resolution, cache/invalidation, generation, and surfaced-domain coverage are complete at their recorded boundaries. - The broader domain's aggregate documentation checkpoint completed on 2026-08-14 Pacific/Auckland (2026-08-13 UTC): `./gradlew linkCheck lintMarkdown` checked 4,574 links (4,536 OK, 0 errors, 38 excluded) and 454 Markdown files with 0 issues; `bash dev-tools/tests/architecture-doc-contracts.sh` also passed separately (184 tests passed). -- Asset purge and publication proof remains incomplete. The owning [Asset Storage contract](../../architecture/microservices/game-design-service/asset-storage.md#api) defines purge eligibility, lifecycle ordering, and publication recovery; [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) defines the shared operation identity and replay boundary. Current implementation has mapping/snapshot storage but lacks its required authoring/export integration, uses server-generated random purge workflow IDs, and lacks database CAS/affected-row and exact committed-bundle readback proof; these remain implementation gaps rather than completed lifecycle guarantees. +- Asset purge and publication proof remains incomplete. The owning [Asset Storage contract](../../architecture/microservices/game-design-service/asset-storage.md#api) defines purge eligibility, lifecycle ordering and publication recovery; [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) defines the shared operation identity and replay boundary. Durable ordinary export selection is wired, but source/mapping authoring and complete requiredness are not. Server-generated random purge identities, missing database CAS/affected-row proof and incomplete exact committed-bundle readback remain gaps rather than completed lifecycle guarantees. - The current Packet 5 documentation-only validation record is maintained in the canonical [design capability allocation](../design-alignment/design-capability-allocation.md#validation-and-proof-references); that ledger entry proves only the Packet 5 documentation/allocation checkpoint. It neither claims runtime proof for that parcel nor weakens the separately listed implementation proof and commands in this tracker. ## Active Gaps diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java index dadeac19cc..b17b1bba7c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreProperties.java @@ -1,22 +1,14 @@ package net.firedevops.firemud.gamedesign.config; -import jakarta.validation.constraints.Min; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.validation.annotation.Validated; @Data -@Validated @ConfigurationProperties(prefix = "asset.store") public class AssetStoreProperties { - private static final int DEFAULT_FROZEN_SNAPSHOT_CACHE_MAX_ENTRIES = 256; - private String endpoint; private String bucket; private String region; private String accessKey; private String secretKey; - - @Min(1) - private int frozenSnapshotCacheMaxEntries = DEFAULT_FROZEN_SNAPSHOT_CACHE_MAX_ENTRIES; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java index fd21101b9d..cf8f9cd665 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java @@ -6,17 +6,12 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; -import net.firedevops.firemud.gamedesign.entity.GameAsset; -import net.firedevops.firemud.gamedesign.entity.Version; -import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; -import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import org.springframework.stereotype.Service; @@ -31,14 +26,9 @@ value = "EI_EXPOSE_REP2", justification = "Injected collaborators remain internal service dependencies") public class AssetExportServiceImpl implements AssetExportService { - private static final String ASSET_USAGE_KEY_COLLISION = "ASSET_USAGE_KEY_COLLISION"; - private static final String EXPORT_SNAPSHOT_CAPACITY = "EXPORT_SNAPSHOT_CAPACITY"; private static final String MANIFEST_OBJECT_KEY = "manifest.json"; - private static final String REPAIR_VERSION_SCOPE_UNAVAILABLE = "REPAIR_VERSION_SCOPE_UNAVAILABLE"; - private final GameAssetRepository repository; - private final VersionRepository versionRepository; - private final Map frozenSnapshots; + private final VersionAssetPublicationRepository publicationRepository; @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "S3Client is thread-safe") private final S3Client s3Client; @@ -47,17 +37,14 @@ public class AssetExportServiceImpl implements AssetExportService { private final ObjectMapper objectMapper; public AssetExportServiceImpl( - GameAssetRepository repository, + VersionAssetPublicationRepository publicationRepository, S3Client s3Client, AssetStoreProperties properties, - ObjectMapper objectMapper, - VersionRepository versionRepository) { - this.repository = repository; - this.versionRepository = versionRepository; + ObjectMapper objectMapper) { + this.publicationRepository = publicationRepository; this.s3Client = s3Client; this.properties = copyProperties(properties); this.objectMapper = objectMapper; - this.frozenSnapshots = Collections.synchronizedMap(new LinkedHashMap<>(16, 0.75f, true)); } private static AssetStoreProperties copyProperties(AssetStoreProperties source) { @@ -67,30 +54,33 @@ private static AssetStoreProperties copyProperties(AssetStoreProperties source) copy.setRegion(source.getRegion()); copy.setAccessKey(source.getAccessKey()); copy.setSecretKey(source.getSecretKey()); - copy.setFrozenSnapshotCacheMaxEntries(source.getFrozenSnapshotCacheMaxEntries()); return copy; } @Override @Timed("gamedesign.asset.export") public ExportedAssetManifest exportAssets(String tenantId, int version) { - VersionResolution resolution = resolveVersionScope(tenantId, version); - FrozenAssetSnapshot snapshot = resolveSnapshot(resolution.scope(), resolution.versionState()); + // The owner read verifies the complete retained mapping projection and actual source bytes + // before any object-store write. Export never creates a selection or falls back to uploads. + var snapshot = publicationRepository.readFrozenSnapshot(tenantId, version); + if (!tenantId.equals(snapshot.tenantId()) || version != snapshot.versionNumber()) { + throw new IllegalStateException("ASSET_EXPORT_SNAPSHOT_SCOPE_MISMATCH"); + } String prefix = tenantId + "/" + version + "/"; Map manifest = new LinkedHashMap<>(); ArrayList requiredManifestAssetKeys = new ArrayList<>(); - for (FrozenAsset asset : snapshot.assets()) { - String key = prefix + asset.fileName(); + for (var asset : snapshot.items()) { + String key = prefix + asset.usageKey(); s3Client.putObject( PutObjectRequest.builder() .bucket(properties.getBucket()) .key(key) .contentType(asset.contentType()) .build(), - RequestBody.fromBytes(asset.data())); + RequestBody.fromBytes(asset.bytes())); String url = properties.getEndpoint() + "/" + properties.getBucket() + "/" + key; - manifest.put(asset.fileName(), url); - requiredManifestAssetKeys.add(asset.fileName()); + manifest.put(asset.usageKey(), url); + requiredManifestAssetKeys.add(asset.usageKey()); } try { String manifestJson = objectMapper.writeValueAsString(manifest); @@ -109,60 +99,6 @@ public ExportedAssetManifest exportAssets(String tenantId, int version) { } } - private VersionResolution resolveVersionScope(String tenantId, int versionNumber) { - Version version = - versionRepository - .findByTenantIdAndVersionNumber(tenantId, versionNumber) - .orElseThrow(() -> new IllegalArgumentException(REPAIR_VERSION_SCOPE_UNAVAILABLE)); - return new VersionResolution( - new VersionScope(tenantId, version.getId(), versionNumber), version.getVersionState()); - } - - private FrozenAssetSnapshot resolveSnapshot( - VersionScope scope, VersionLifecycleState versionState) { - FrozenAssetSnapshot existing = frozenSnapshots.get(scope); - if (existing != null) { - return existing; - } - if (versionState == VersionLifecycleState.PUBLISHED - || versionState == VersionLifecycleState.ACTIVE) { - throw new IllegalStateException(REPAIR_VERSION_SCOPE_UNAVAILABLE); - } - FrozenAssetSnapshot candidate = freeze(repository.findByTenantId(scope.tenantId())); - synchronized (frozenSnapshots) { - FrozenAssetSnapshot concurrent = frozenSnapshots.get(scope); - if (concurrent != null) { - return concurrent; - } - VersionResolution current = resolveVersionScope(scope.tenantId(), scope.versionNumber()); - if (!scope.equals(current.scope()) - || current.versionState() == VersionLifecycleState.PUBLISHED - || current.versionState() == VersionLifecycleState.ACTIVE) { - throw new IllegalStateException(REPAIR_VERSION_SCOPE_UNAVAILABLE); - } - if (frozenSnapshots.size() >= properties.getFrozenSnapshotCacheMaxEntries()) { - throw new IllegalStateException(EXPORT_SNAPSHOT_CAPACITY); - } - frozenSnapshots.put(scope, candidate); - return candidate; - } - } - - private FrozenAssetSnapshot freeze(List assets) { - Map frozenByUsageKey = new LinkedHashMap<>(); - for (GameAsset asset : assets) { - byte[] data = asset.getData(); - FrozenAsset frozen = - new FrozenAsset( - asset.getId(), asset.getFileName(), asset.getContentType(), data, sha256(data)); - if (MANIFEST_OBJECT_KEY.equals(asset.getFileName()) - || frozenByUsageKey.putIfAbsent(asset.getFileName(), frozen) != null) { - throw new IllegalStateException(ASSET_USAGE_KEY_COLLISION); - } - } - return new FrozenAssetSnapshot(List.copyOf(frozenByUsageKey.values())); - } - @Override @Timed("gamedesign.asset.delete") public void deleteExportedAssets(String tenantId, int version, List manifestAssetKeys) { @@ -193,26 +129,4 @@ private String sha256(byte[] value) { throw new IllegalStateException("SHA-256 unavailable", ex); } } - - private record VersionResolution(VersionScope scope, VersionLifecycleState versionState) {} - - private record VersionScope(String tenantId, Long versionId, int versionNumber) {} - - private record FrozenAssetSnapshot(List assets) { - private FrozenAssetSnapshot { - assets = List.copyOf(assets); - } - } - - private record FrozenAsset( - Long sourceAssetId, String fileName, String contentType, byte[] data, String contentHash) { - private FrozenAsset { - data = data == null ? null : data.clone(); - } - - @Override - public byte[] data() { - return data == null ? null : data.clone(); - } - } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java index 21a447a420..a4fad5cd97 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java @@ -2,11 +2,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.sql.SQLException; import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.entity.Version; @@ -15,6 +21,7 @@ import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.AssetExportServiceImpl; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -23,6 +30,7 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -31,6 +39,10 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import tools.jackson.databind.ObjectMapper; /** * Persistence proof for version-scoped asset selection. Fixtures create synthetic Game and Version @@ -47,7 +59,8 @@ class VersionAssetPublicationPostgresIntegrationTest { new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void exactTenantVersionMappingsExcludeUnmappedAssetsAndSnapshotSurvivesRepositoryRestart() { + void exactTenantVersionMappingsExcludeUnmappedAssetsAndSnapshotSurvivesRepositoryRestart() + throws IOException { Fixture fixture = fixture(null); Game owner = saveGame(fixture, "a"); Game otherOwner = saveGame(fixture, "b"); @@ -112,6 +125,43 @@ void exactTenantVersionMappingsExcludeUnmappedAssetsAndSnapshotSurvivesRepositor assertThat(retried.items().get(0).assetId()).isEqualTo(selected.getId()); assertThat(retried.items().get(0).contentDigest()) .isEqualTo(frozen.items().get(0).contentDigest()); + + // Exercise the actual exporter and actual PostgreSQL snapshot read. Only S3 is simulated. + S3Client sink = mock(S3Client.class); + AssetStoreProperties properties = new AssetStoreProperties(); + properties.setBucket("bucket"); + properties.setEndpoint("http://asset-origin"); + var exporter = new AssetExportServiceImpl(repository, sink, properties, new ObjectMapper()); + var firstManifest = exporter.exportAssets(owner.getTenantId(), 1); + var restartedExporter = + new AssetExportServiceImpl(restartedRepository, sink, properties, new ObjectMapper()); + var replayManifest = restartedExporter.exportAssets(owner.getTenantId(), 1); + + assertThat(replayManifest).isEqualTo(firstManifest); + assertThat(firstManifest.requiredManifestAssetKeys()) + .containsExactly("selected.png", "manifest.json"); + var requests = ArgumentCaptor.forClass(PutObjectRequest.class); + var bodies = ArgumentCaptor.forClass(RequestBody.class); + verify(sink, times(4)).putObject(requests.capture(), bodies.capture()); + String prefix = owner.getTenantId() + "/1/"; + assertThat(requests.getAllValues()) + .extracting(PutObjectRequest::key) + .containsExactly( + prefix + "selected.png", prefix + "manifest.json", + prefix + "selected.png", prefix + "manifest.json"); + assertThat(requests.getAllValues().get(0).contentType()).isEqualTo("image/png"); + try (var selectedStream = bodies.getAllValues().get(0).contentStreamProvider().newStream()) { + assertThat(selectedStream.readAllBytes()).containsExactly(selected.getData()); + } + for (int index = 0; index < 2; index++) { + assertThat(requests.getAllValues().get(index + 2)) + .isEqualTo(requests.getAllValues().get(index)); + try (var firstStream = bodies.getAllValues().get(index).contentStreamProvider().newStream(); + var replayStream = + bodies.getAllValues().get(index + 2).contentStreamProvider().newStream()) { + assertThat(replayStream.readAllBytes()).containsExactly(firstStream.readAllBytes()); + } + } } @Test @@ -130,31 +180,55 @@ void retainedVersionWithoutCanonicalSourceCannotReceiveAssetMapping() { } @Test - void changedSourceBytesInvalidateCommittedSnapshotReadback() { + void immutableSourceRejectsChangedBytesBeforeCommittedSnapshotReadback() { Fixture fixture = fixture(null); Game owner = saveGame(fixture, "d"); Version version = saveDraftVersion(fixture, owner, 1); GameAsset asset = saveAsset(fixture, owner, "mutable-source.png", "content-original"); associate(fixture, owner.getTenantId(), version.getId(), asset.getId()); - inTransaction( - fixture, - () -> fixture.publicationRepository().freezeOrReadSnapshot(owner.getTenantId(), 1)); - - fixture - .dsl() - .execute( - "UPDATE game_assets SET data = ? WHERE tenant_id = ? AND id = ?", - "content-replaced".getBytes(StandardCharsets.UTF_8), - owner.getTenantId(), - asset.getId()); + VersionAssetPublicationRepository.ExportSnapshot frozen = + inTransaction( + fixture, + () -> fixture.publicationRepository().freezeOrReadSnapshot(owner.getTenantId(), 1)); assertThatThrownBy( () -> fixture - .publicationRepository() - .readFrozenSnapshot(owner.getTenantId(), version.getVersionNumber())) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Frozen Version asset source bytes or mapping failed verification"); + .dsl() + .execute( + "UPDATE game_assets SET data = ? WHERE tenant_id = ? AND id = ?", + "content-replaced".getBytes(StandardCharsets.UTF_8), + owner.getTenantId(), + asset.getId())) + .rootCause() + .isInstanceOf(SQLException.class) + .hasMessageContaining("game asset source rows are immutable") + .satisfies( + failure -> assertThat(((SQLException) failure).getSQLState()).isEqualTo("23514")); + + Record persistedAsset = + Objects.requireNonNull( + fixture + .dsl() + .fetchSingle( + "SELECT data FROM game_assets WHERE tenant_id = ? AND id = ?", + owner.getTenantId(), + asset.getId())); + assertThat(persistedAsset.get("data", byte[].class)).containsExactly(asset.getData()); + + VersionAssetPublicationRepository restartedRepository = + new VersionAssetPublicationRepository(fixture.dsl()); + VersionAssetPublicationRepository.ExportSnapshot reloaded = + restartedRepository.readFrozenSnapshot(owner.getTenantId(), version.getVersionNumber()); + assertSameSnapshot(frozen, reloaded); + + VersionAssetPublicationRepository.ExportSnapshot retried = + inTransaction( + fixture, + () -> + restartedRepository.freezeOrReadSnapshot( + owner.getTenantId(), version.getVersionNumber())); + assertSameSnapshot(frozen, retried); } @Test @@ -294,6 +368,27 @@ private long mappingCount(Fixture fixture, String tenantId, long versionId) { return Objects.requireNonNull(countRecord.get("mapping_count", Long.class)); } + private void assertSameSnapshot( + VersionAssetPublicationRepository.ExportSnapshot expected, + VersionAssetPublicationRepository.ExportSnapshot actual) { + assertThat(actual.tenantId()).isEqualTo(expected.tenantId()); + assertThat(actual.versionId()).isEqualTo(expected.versionId()); + assertThat(actual.versionNumber()).isEqualTo(expected.versionNumber()); + assertThat(actual.capturedVersionStateEpoch()).isEqualTo(expected.capturedVersionStateEpoch()); + assertThat(actual.canonicalTenantId()).isEqualTo(expected.canonicalTenantId()); + assertThat(actual.canonicalVersionId()).isEqualTo(expected.canonicalVersionId()); + assertThat(actual.items()).hasSize(expected.items().size()); + for (int i = 0; i < expected.items().size(); i++) { + VersionAssetPublicationRepository.AssetSelection expectedItem = expected.items().get(i); + VersionAssetPublicationRepository.AssetSelection actualItem = actual.items().get(i); + assertThat(actualItem.usageKey()).isEqualTo(expectedItem.usageKey()); + assertThat(actualItem.assetId()).isEqualTo(expectedItem.assetId()); + assertThat(actualItem.contentType()).isEqualTo(expectedItem.contentType()); + assertThat(actualItem.contentDigest()).isEqualTo(expectedItem.contentDigest()); + assertThat(actualItem.bytes()).containsExactly(expectedItem.bytes()); + } + } + private long insertUnqualifiedRetainedVersion(DSLContext dsl, String tenantId) { Record insertedVersion = Objects.requireNonNull( diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java index 98eee02d1d..e9b900e4e6 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java @@ -1,30 +1,33 @@ package net.firedevops.firemud.gamedesign.service; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; import java.util.List; -import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; -import net.firedevops.firemud.gamedesign.entity.GameAsset; -import net.firedevops.firemud.gamedesign.entity.Version; -import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; -import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.AssetSelection; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository.ExportSnapshot; import net.firedevops.firemud.gamedesign.service.impl.AssetExportServiceImpl; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import software.amazon.awssdk.core.sync.RequestBody; @@ -33,208 +36,175 @@ import software.amazon.awssdk.services.s3.model.PutObjectRequest; import tools.jackson.databind.ObjectMapper; +/** Export delegation proof; physical source validation belongs to the PostgreSQL owner tests. */ @ExtendWith(MockitoExtension.class) class AssetExportServiceImplTest { - @Mock private GameAssetRepository repository; - @Mock private VersionRepository versionRepository; + @Mock private VersionAssetPublicationRepository publicationRepository; @Mock private S3Client s3Client; private AssetExportServiceImpl service; @BeforeEach void setup() { - service = newService(256); + service = newService(); } - private AssetExportServiceImpl newService(int frozenSnapshotCacheMaxEntries) { + private AssetExportServiceImpl newService() { AssetStoreProperties props = new AssetStoreProperties(); props.setBucket("bucket"); props.setEndpoint("http://localhost:9000"); props.setRegion("ap-southeast-2"); props.setAccessKey("a"); props.setSecretKey("s"); - props.setFrozenSnapshotCacheMaxEntries(frozenSnapshotCacheMaxEntries); - return new AssetExportServiceImpl( - repository, s3Client, props, new ObjectMapper(), versionRepository); + return new AssetExportServiceImpl(publicationRepository, s3Client, props, new ObjectMapper()); } @Test - void exportUploadsAssetsAndManifest() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(VersionLifecycleState.DRAFT))); - GameAsset asset = gameAsset("logo.png", "data"); - when(repository.findByTenantId("t")).thenReturn(List.of(asset)); + void exportsOnlyRetainedVersionSelection() throws IOException { + when(publicationRepository.readFrozenSnapshot("t", 1)) + .thenReturn(snapshot("t", 1, List.of(asset("logo.png", "selected-bytes")))); ExportedAssetManifest manifest = service.exportAssets("t", 1); - verify(s3Client) - .putObject( - argThat((PutObjectRequest r) -> r.key().equals("t/1/logo.png")), - any(RequestBody.class)); - verify(s3Client) - .putObject( - argThat((PutObjectRequest r) -> r.key().equals("t/1/manifest.json")), - any(RequestBody.class)); + var requests = ArgumentCaptor.forClass(PutObjectRequest.class); + var bodies = ArgumentCaptor.forClass(RequestBody.class); + verify(s3Client, times(2)).putObject(requests.capture(), bodies.capture()); + assertEquals( + List.of("t/1/logo.png", "t/1/manifest.json"), + requests.getAllValues().stream().map(PutObjectRequest::key).toList()); + assertEquals("image/png", requests.getAllValues().getFirst().contentType()); + assertArrayEquals( + "selected-bytes".getBytes(StandardCharsets.UTF_8), bytes(bodies.getAllValues().getFirst())); + assertEquals( + "{\"logo.png\":\"http://localhost:9000/bucket/t/1/logo.png\"}", + new String(bytes(bodies.getAllValues().getLast()), StandardCharsets.UTF_8)); assertEquals(List.of("logo.png", "manifest.json"), manifest.requiredManifestAssetKeys()); + verify(publicationRepository).readFrozenSnapshot("t", 1); } @Test - void sameVersionRetryReusesFrozenSnapshot() { - Version draft = version(VersionLifecycleState.DRAFT); - Version published = version(VersionLifecycleState.PUBLISHED); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(draft), Optional.of(draft), Optional.of(published)); - GameAsset original = gameAsset("logo.png", "original"); - GameAsset changed = gameAsset("changed.png", "changed"); - when(repository.findByTenantId("t")).thenReturn(List.of(original), List.of(changed)); + void independentlyReconstructedExporterReplaysDurableSelectionExactly() throws IOException { + when(publicationRepository.readFrozenSnapshot("t", 1)) + .thenReturn(snapshot("t", 1, List.of(asset("logo.png", "original")))); ExportedAssetManifest first = service.exportAssets("t", 1); - ExportedAssetManifest retry = service.exportAssets("t", 1); + ExportedAssetManifest retry = newService().exportAssets("t", 1); assertEquals(first, retry); - verify(versionRepository, times(3)).findByTenantIdAndVersionNumber("t", 1); - verify(repository, times(1)).findByTenantId("t"); + var requests = ArgumentCaptor.forClass(PutObjectRequest.class); + var bodies = ArgumentCaptor.forClass(RequestBody.class); + verify(s3Client, times(4)).putObject(requests.capture(), bodies.capture()); + for (int index = 0; index < 2; index++) { + assertEquals(requests.getAllValues().get(index), requests.getAllValues().get(index + 2)); + assertArrayEquals( + bytes(bodies.getAllValues().get(index)), bytes(bodies.getAllValues().get(index + 2))); + } + verify(publicationRepository, times(2)).readFrozenSnapshot("t", 1); } - @Test - void unknownVersionIsRejectedWithoutSelectingTenantAssets() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 99)).thenReturn(Optional.empty()); - - IllegalArgumentException thrown = - assertThrows(IllegalArgumentException.class, () -> service.exportAssets("t", 99)); - - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); - verifyNoInteractions(repository, s3Client); - } - - @Test - void duplicateUsageKeysAreRejectedBeforeWritingAssets() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(VersionLifecycleState.DRAFT))); - when(repository.findByTenantId("t")) - .thenReturn(List.of(gameAsset("logo.png", "one"), gameAsset("logo.png", "two"))); - - IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); - - assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); + @ParameterizedTest + @ValueSource( + strings = { + "No durable frozen Version asset snapshot exists", + "Frozen Version asset snapshot identity is inconsistent", + "Frozen Version asset source bytes or mapping failed verification", + "Exact tenant Version was not found" + }) + void ownerReadFailureDeniesBeforeAnyObjectStoreSideEffect(String ownerFailure) { + when(publicationRepository.readFrozenSnapshot("t", 1)) + .thenThrow(new IllegalStateException(ownerFailure)); + + var thrown = assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + + assertEquals(ownerFailure, thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void reservedManifestUsageKeyIsRejectedBeforeWritingAssets() { - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(VersionLifecycleState.DRAFT))); - when(repository.findByTenantId("t")) - .thenReturn(List.of(gameAsset("manifest.json", "asset data"))); - - IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + void retryRevalidatesOwnerBytesBeforeAnyFurtherWrite() { + when(publicationRepository.readFrozenSnapshot("t", 1)) + .thenReturn(snapshot("t", 1, List.of(asset("logo.png", "original")))) + .thenThrow( + new IllegalStateException( + "Frozen Version asset source bytes or mapping failed verification")); + service.exportAssets("t", 1); + org.mockito.Mockito.clearInvocations(s3Client); - assertEquals("ASSET_USAGE_KEY_COLLISION", thrown.getMessage()); - verifyNoInteractions(s3Client); - } + assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); - @ParameterizedTest - @EnumSource( - value = VersionLifecycleState.class, - names = {"PUBLISHED", "ACTIVE"}) - void publishedAndActiveRetryFailsWithoutFrozenSnapshot(VersionLifecycleState state) { - Version version = version(state); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)).thenReturn(Optional.of(version)); - - IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); - - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); - verify(repository, never()).findByTenantId("t"); + verify(publicationRepository, times(2)).readFrozenSnapshot("t", 1); verifyNoInteractions(s3Client); } @Test - void publishedRetryReusesSnapshotFrozenBeforePublication() { - Version draft = version(VersionLifecycleState.DRAFT); - Version published = version(VersionLifecycleState.PUBLISHED); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(draft), Optional.of(draft), Optional.of(published)); + void mismatchedReturnedTenantScopeDeniesBeforeWrites() { + when(publicationRepository.readFrozenSnapshot("t", 1)) + .thenReturn(snapshot("other", 1, List.of(asset("logo.png", "data")))); - GameAsset original = gameAsset("logo.png", "original"); - GameAsset changed = gameAsset("changed.png", "changed"); - when(repository.findByTenantId("t")).thenReturn(List.of(original), List.of(changed)); + var thrown = assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); - ExportedAssetManifest first = service.exportAssets("t", 1); - ExportedAssetManifest retry = service.exportAssets("t", 1); - - assertEquals(first, retry); - verify(versionRepository, times(3)).findByTenantIdAndVersionNumber("t", 1); - verify(repository, times(1)).findByTenantId("t"); + assertEquals("ASSET_EXPORT_SNAPSHOT_SCOPE_MISMATCH", thrown.getMessage()); + verifyNoInteractions(s3Client); } @Test - void fullSnapshotCacheFailsClosedInsteadOfEvictingRetryEvidence() { - service = newService(1); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(version(7L, 1, VersionLifecycleState.DRAFT))); - when(versionRepository.findByTenantIdAndVersionNumber("t", 2)) - .thenReturn(Optional.of(version(8L, 2, VersionLifecycleState.DRAFT))); - when(repository.findByTenantId("t")) - .thenReturn( - List.of(gameAsset("first.png", "first")), List.of(gameAsset("second.png", "second"))); + void mismatchedReturnedVersionScopeDeniesBeforeWrites() { + when(publicationRepository.readFrozenSnapshot("t", 1)) + .thenReturn(snapshot("t", 2, List.of(asset("logo.png", "data")))); - service.exportAssets("t", 1); - org.mockito.Mockito.clearInvocations(s3Client); + var thrown = assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); - IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 2)); - - assertEquals("EXPORT_SNAPSHOT_CAPACITY", thrown.getMessage()); + assertEquals("ASSET_EXPORT_SNAPSHOT_SCOPE_MISMATCH", thrown.getMessage()); verifyNoInteractions(s3Client); } @Test - void publicationRacingSnapshotCreationFailsBeforeObjectStoreWrites() { - Version draft = version(VersionLifecycleState.DRAFT); - Version published = version(VersionLifecycleState.PUBLISHED); - when(versionRepository.findByTenantIdAndVersionNumber("t", 1)) - .thenReturn(Optional.of(draft), Optional.of(published)); - when(repository.findByTenantId("t")).thenReturn(List.of(gameAsset("logo.png", "data"))); + void explicitlyRetainedEmptySelectionExportsManifestOnly() { + when(publicationRepository.readFrozenSnapshot("t", 1)).thenReturn(snapshot("t", 1, List.of())); - IllegalStateException thrown = - assertThrows(IllegalStateException.class, () -> service.exportAssets("t", 1)); + var manifest = service.exportAssets("t", 1); - assertEquals("REPAIR_VERSION_SCOPE_UNAVAILABLE", thrown.getMessage()); - verifyNoInteractions(s3Client); + verify(s3Client) + .putObject( + argThat((PutObjectRequest r) -> r.key().equals("t/1/manifest.json")), + any(RequestBody.class)); + assertEquals(List.of("manifest.json"), manifest.requiredManifestAssetKeys()); } @Test void deleteExportedAssetsUsesExactManifestKeyList() { - service.deleteExportedAssets("t", 1, List.of("logo.png", "manifest.json")); + service.deleteExportedAssets("t", 1, List.of("logo.png", "manifest.json", "logo.png")); verify(s3Client) .deleteObject(argThat((DeleteObjectRequest r) -> r.key().equals("t/1/logo.png"))); verify(s3Client) .deleteObject(argThat((DeleteObjectRequest r) -> r.key().equals("t/1/manifest.json"))); + verifyNoInteractions(publicationRepository); } - private static Version version(VersionLifecycleState state) { - return version(7L, 1, state); + private static ExportSnapshot snapshot( + String tenantId, int versionNumber, List assets) { + return new ExportSnapshot( + tenantId, 7L, versionNumber, 1L, UUID.randomUUID(), UUID.randomUUID(), assets); } - private static Version version(Long id, int versionNumber, VersionLifecycleState state) { - Version version = new Version(); - version.setId(id); - version.setTenantId("t"); - version.setVersionNumber(versionNumber); - version.setVersionState(state); - return version; + private static AssetSelection asset(String usageKey, String data) { + byte[] bytes = data.getBytes(StandardCharsets.UTF_8); + try { + return new AssetSelection( + usageKey, + 11L, + bytes, + "image/png", + "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } } - private static GameAsset gameAsset(String fileName, String data) { - GameAsset asset = new GameAsset(); - asset.setTenantId("t"); - asset.setFileName(fileName); - asset.setContentType("image/png"); - asset.setData(data.getBytes(StandardCharsets.UTF_8)); - return asset; + private static byte[] bytes(RequestBody body) throws IOException { + try (var stream = body.contentStreamProvider().newStream()) { + return stream.readAllBytes(); + } } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java index 93d447632d..ff212ca939 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.worldmanagement.tenant; +import java.util.Arrays; import java.util.Objects; import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; @@ -20,6 +21,13 @@ final class WorldSelectedDraftPublicationCheckpointRepository { private final WorldDraftTopologyCommitRepository topology; private final WorldDraftDesignDigestService digestService; + record CapturedCheckpoint( + Checkpoint checkpoint, + WorldDraftGraphAppliedResult application, + WorldDraftTopologyCommitEvidence topology, + WorldCanonicalAuthoredGraph graph, + WorldDesignPublicationFenceRepository.OpenOwner owner) {} + WorldSelectedDraftPublicationCheckpointRepository( WorldDesignPublicationFenceRepository fence, WorldDraftGraphApplicationRepository applications, @@ -31,7 +39,7 @@ final class WorldSelectedDraftPublicationCheckpointRepository { this.digestService = Objects.requireNonNull(digestService, "digestService"); } - Checkpoint capture( + CapturedCheckpoint captureWithSource( WorldDesignPublicationFenceEvidence freeze, WorldDraftTopologyCommitPlan selectedPlan) { Objects.requireNonNull(freeze, "freeze"); Objects.requireNonNull(selectedPlan, "selectedPlan"); @@ -46,10 +54,13 @@ Checkpoint capture( var applied = applications.readAppliedForPublicationCheckpoint(freeze, selectedPlan); var stored = topology.readUnderFrozenLock(selectedPlan); if (!stored.binding().equals(applied.application().operation().binding()) - || !stored.ownerBinding().equals(freeze.ownerBinding())) { + || !stored.ownerBinding().equals(freeze.ownerBinding()) + || !Arrays.equals(stored.graphBytes(), applied.graphBytes())) { throw new ConflictException( "World stored topology differs from the exact APPLIED selected graph application"); } + var graph = + topology.verifyImmutableBytes(selectedPlan, stored.graphBytes(), stored.resultBytes()); var digest = digestService.getDraftDesignDigest( @@ -61,9 +72,14 @@ Checkpoint capture( "World selected graph digest differs from the exact local schema-3 Draft scope"); } - return new Checkpoint( - applied.application().operation().commitId().toString(), - digest.contentDigest(), - digest.digestSchemaVersion()); + return new CapturedCheckpoint( + new Checkpoint( + applied.application().operation().commitId().toString(), + digest.contentDigest(), + digest.digestSchemaVersion()), + applied, + stored, + graph, + owner); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java index 41cd1de483..7961888702 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java @@ -5,6 +5,7 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; @@ -21,7 +22,6 @@ import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Request; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; -import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.Checkpoint; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -45,6 +45,7 @@ final class WorldSelectedDraftPublicationFreezeService { private final WorldDesignPublicationFenceRepository fence; private final WorldSelectedDraftPublicationCheckpointRepository checkpointRepository; private final WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository; + private final WorldSelectedPublicationArtifactInventoryRepository artifactInventoryRepository; private final WorldDraftGraphApplicationRepository graphApplicationRepository; private final TransactionTemplate ownerTransaction; @@ -57,6 +58,7 @@ final class WorldSelectedDraftPublicationFreezeService { WorldDesignPublicationFenceRepository fence, WorldSelectedDraftPublicationCheckpointRepository checkpointRepository, WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository, + WorldSelectedPublicationArtifactInventoryRepository artifactInventoryRepository, PlatformTransactionManager transactionManager) { this( workloadNamespace, @@ -67,6 +69,7 @@ final class WorldSelectedDraftPublicationFreezeService { fence, checkpointRepository, authorizationRepository, + artifactInventoryRepository, null, transactionManager); } @@ -80,6 +83,7 @@ final class WorldSelectedDraftPublicationFreezeService { WorldDesignPublicationFenceRepository fence, WorldSelectedDraftPublicationCheckpointRepository checkpointRepository, WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository, + WorldSelectedPublicationArtifactInventoryRepository artifactInventoryRepository, WorldDraftGraphApplicationRepository graphApplicationRepository, PlatformTransactionManager transactionManager) { if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -95,6 +99,8 @@ final class WorldSelectedDraftPublicationFreezeService { Objects.requireNonNull(checkpointRepository, "checkpointRepository"); this.authorizationRepository = Objects.requireNonNull(authorizationRepository, "authorizationRepository"); + this.artifactInventoryRepository = + Objects.requireNonNull(artifactInventoryRepository, "artifactInventoryRepository"); this.graphApplicationRepository = graphApplicationRepository; this.ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); @@ -219,6 +225,7 @@ FrozenAttempt freeze( conflict( "World freeze attempt has no original Account publication qualification")); requireSameAccountBinding(accountBinding, retained); + artifactInventoryRepository.readCommitted(stored, retained); return stored; } @@ -228,6 +235,8 @@ FrozenAttempt freeze( requireAccountHeld(accountBinding); AtomicBoolean attemptCreatedInTransaction = new AtomicBoolean(); + AtomicReference + capturedCheckpoint = new AtomicReference<>(); FrozenAttempt transactionResult = Objects.requireNonNull( ownerTransaction.execute( @@ -241,15 +250,21 @@ FrozenAttempt freeze( fence.claimFreeze( evidence, () -> { - Checkpoint checkpoint = - checkpointRepository.capture(evidence, selectedPlan); + var captured = + checkpointRepository.captureWithSource(evidence, selectedPlan); + capturedCheckpoint.set(captured); attemptCreatedInTransaction.set(true); - return checkpoint; + return captured.checkpoint(); }); AccountPublicationAuthorizationBinding retained = authorizationRepository.retainOrRequireExact( attempt, accountBinding, attemptCreatedInTransaction.get()); requireSameAccountBinding(accountBinding, retained); + artifactInventoryRepository.retainOrRequireExact( + attempt, + retained, + attemptCreatedInTransaction.get(), + capturedCheckpoint.get()); requireCheckpointMatchesSelection( attempt, selectedPlan, accountBinding.input().selection()); return attempt; @@ -274,6 +289,7 @@ FrozenAttempt freeze( conflict( "Committed World freeze has no exact Account publication qualification")); requireSameAccountBinding(accountBinding, retained); + artifactInventoryRepository.readCommitted(committed, retained); requireCheckpointMatchesSelection(committed, selectedPlan, accountBinding.input().selection()); return committed; } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java new file mode 100644 index 0000000000..69a0d1c3a4 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java @@ -0,0 +1,857 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.io.IOException; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable, owner-derived complete inventory for the closed logical room/exit source model. + * + *

This is not an artifact payload or an Asset Storage manifest. It is derived from the exact + * retained APPLIED graph/2 and the World-owned freeze checkpoint. The supported room/exit profile + * uses authored edges directly and has no separate NAVMESH or PATH_GRAPH bundle requirement. + */ +public final class WorldSelectedPublicationArtifactInventory { + static final String SCHEMA = "world-selected-publication-artifact-inventory/v1"; + private static final String SOURCE_MODEL = "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1"; + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern HEX_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + private static final List SUPPORTED_FAMILY_ORDER = + List.of( + WorldCanonicalAuthoredGraph.Family.REGION, + WorldCanonicalAuthoredGraph.Family.ZONE, + WorldCanonicalAuthoredGraph.Family.ROOM, + WorldCanonicalAuthoredGraph.Family.ROOM_EXIT, + WorldCanonicalAuthoredGraph.Family.GENERATION_RULE, + WorldCanonicalAuthoredGraph.Family.WORLD_ENTITY_SPAWN_BINDING); + private static final List REGION_FIELDS = + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"); + private static final List ZONE_FIELDS = List.of("id", "regionId", "name"); + private static final List ROOM_FIELDS = + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"); + private static final List ROOM_EXIT_FIELDS = + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"); + private static final List GENERATION_RULE_FIELDS = + List.of("id", "name", "scopeType", "scopeId", "value"); + private static final List SPAWN_BINDING_FIELDS = + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"); + private static final List ARTIFACT_DECISIONS = + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH")); + + enum UnrepresentableReason { + UNKNOWN_GRAPH_FAMILY, + ROOM_TOPOLOGY_REQUIRED, + REGION_GENERATOR_INPUT, + GENERATION_RULE_INPUT, + SPAWN_BINDING_INPUT + } + + static final class UnrepresentableRequirednessException extends ConflictException { + private final UnrepresentableReason reason; + + UnrepresentableRequirednessException(UnrepresentableReason reason, String message) { + super(message); + this.reason = Objects.requireNonNull(reason, "reason"); + } + + UnrepresentableReason reason() { + return reason; + } + } + + record OwnerScope( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + String localTenantKey, + String localVersionKey, + UUID versionIdentityOperationId, + String gameDesignVersionId, + UUID intakeRequestId, + UUID intakeOperationId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest) {} + + record SourceIntake( + String worldSlug, + String sourceGameRowId, + String sourceGameTenantKey, + String sourceProvenanceKind) {} + + public record FamilyCount(String family, int rowCount) {} + + public record RegionGeneratorInput( + UUID regionTemplateId, String generatorType, String generatorParams) {} + + public record SpawnBindingInput( + UUID bindingTemplateId, + UUID roomTemplateId, + String entityTemplateType, + String entityReferenceKind, + UUID entityTenantId, + UUID entityVersionId, + UUID entityTemplateId, + int spawnCount, + int respawnDelaySeconds) {} + + public record SourceModel( + String modelId, + int graphSchemaVersion, + String graphDigest, + String topologyResultDigest, + List familyCounts, + List regionGeneratorInputs, + List generationRuleFields, + List regionFields, + List zoneFields, + List roomFields, + List roomExitFields, + List spawnBindingFields, + List spawnBindingInputs, + int generationRuleInputCount, + int spawnBindingCount, + List appliedEpochs) { + public SourceModel { + familyCounts = List.copyOf(Objects.requireNonNull(familyCounts, "familyCounts")); + regionGeneratorInputs = + List.copyOf(Objects.requireNonNull(regionGeneratorInputs, "regionGeneratorInputs")); + generationRuleFields = + List.copyOf(Objects.requireNonNull(generationRuleFields, "generationRuleFields")); + regionFields = List.copyOf(Objects.requireNonNull(regionFields, "regionFields")); + zoneFields = List.copyOf(Objects.requireNonNull(zoneFields, "zoneFields")); + roomFields = List.copyOf(Objects.requireNonNull(roomFields, "roomFields")); + roomExitFields = List.copyOf(Objects.requireNonNull(roomExitFields, "roomExitFields")); + spawnBindingFields = + List.copyOf(Objects.requireNonNull(spawnBindingFields, "spawnBindingFields")); + spawnBindingInputs = + List.copyOf(Objects.requireNonNull(spawnBindingInputs, "spawnBindingInputs")); + appliedEpochs = List.copyOf(Objects.requireNonNull(appliedEpochs, "appliedEpochs")); + } + } + + public record SelectedApplication( + UUID applicationOperationId, + UUID applicationRequestId, + String appliedCommitId, + String bindingDigest, + String appliedResultDigest) {} + + public record AccountOrder( + UUID operationId, + UUID fenceId, + UUID actorAccountId, + String publicationRequestId, + String selectionDigest, + String selectedCommitId, + String bindingDigest, + byte[] canonicalBindingBytes) { + public AccountOrder { + canonicalBindingBytes = + Objects.requireNonNull(canonicalBindingBytes, "canonicalBindingBytes").clone(); + } + + @Override + public byte[] canonicalBindingBytes() { + return canonicalBindingBytes.clone(); + } + } + + public record Freeze( + UUID publicationFence, + String publicationRequestId, + String requestDigest, + String versionStateEpoch, + String publishWorkflowId) {} + + public record Checkpoint(String appliedCommitId, String contentDigest, int digestSchemaVersion) {} + + public record ArtifactDecision(String artifactKind, String state, String rule) {} + + /** Public Account order fields; the internal exact canonical bytes remain owner-private. */ + public record PublicAccountOrder( + UUID operationId, + UUID fenceId, + UUID actorAccountId, + String publicationRequestId, + String selectionDigest, + String selectedCommitId, + String bindingDigest) {} + + /** Public canonical projection; it intentionally omits every private numeric owner key. */ + public record PublicOwnerScope( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + UUID intakeRequestId, + UUID intakeOperationId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest) {} + + /** + * Safe egress view after the authenticated World owner read has verified the durable envelope. + */ + public record PublicEvidence( + String schema, + int schemaVersion, + String completeness, + PublicOwnerScope ownerScope, + SelectedApplication selectedApplication, + PublicAccountOrder accountOrder, + Freeze freeze, + Checkpoint checkpoint, + SourceModel sourceModel, + List artifactDecisions) { + public PublicEvidence { + artifactDecisions = List.copyOf(Objects.requireNonNull(artifactDecisions)); + } + } + + record Envelope( + String schema, + int schemaVersion, + String completeness, + OwnerScope ownerScope, + SourceIntake sourceIntake, + SelectedApplication selectedApplication, + AccountOrder accountOrder, + Freeze freeze, + Checkpoint checkpoint, + SourceModel sourceModel, + List artifactDecisions) { + Envelope { + Objects.requireNonNull(schema, "schema"); + Objects.requireNonNull(completeness, "completeness"); + Objects.requireNonNull(ownerScope, "ownerScope"); + Objects.requireNonNull(sourceIntake, "sourceIntake"); + Objects.requireNonNull(selectedApplication, "selectedApplication"); + Objects.requireNonNull(accountOrder, "accountOrder"); + Objects.requireNonNull(freeze, "freeze"); + Objects.requireNonNull(checkpoint, "checkpoint"); + Objects.requireNonNull(sourceModel, "sourceModel"); + artifactDecisions = + List.copyOf(Objects.requireNonNull(artifactDecisions, "artifactDecisions")); + } + } + + private final Envelope envelope; + private final byte[] canonicalBytes; + private final String contentDigest; + + WorldSelectedPublicationArtifactInventory(Envelope envelope, byte[] canonicalBytes) { + this.envelope = Objects.requireNonNull(envelope, "envelope"); + this.canonicalBytes = Objects.requireNonNull(canonicalBytes, "canonicalBytes").clone(); + this.contentDigest = WorldDraftGraphAppliedResult.digest(this.canonicalBytes); + } + + static WorldSelectedPublicationArtifactInventory capture( + FrozenAttempt attempt, + AccountPublicationAuthorizationBinding accountBinding, + WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint captured) { + Objects.requireNonNull(attempt, "attempt"); + Objects.requireNonNull(accountBinding, "accountBinding"); + Objects.requireNonNull(captured, "captured"); + var request = attempt.request(); + var checkpoint = attempt.checkpoint(); + if (!captured.checkpoint().equals(checkpoint) + || !request.ownerBinding().equals(captured.owner().binding()) + || !request + .ownerBinding() + .equals(captured.application().application().operation().ownerBinding()) + || !request.canonicalTenantId().equals(captured.graph().tenantId()) + || !request.canonicalVersionId().equals(captured.graph().versionId()) + || captured.graph().localTenantKey() != captured.owner().localTenantKey() + || captured.graph().localVersionKey() != captured.owner().localVersionKey() + || !checkpoint + .appliedCommitId() + .equals(captured.application().application().operation().commitId().toString()) + || !accountBinding + .input() + .selection() + .selectedCommit() + .equals(captured.application().application().operation().binding()) + || !Arrays.equals( + accountBinding.input().selection().selectedCommit().canonicalBytes(), + captured.application().application().operation().binding().canonicalBytes())) { + throw new ConflictException( + "World artifact inventory source differs from exact APPLIED selection and freeze checkpoint"); + } + + WorldCanonicalAuthoredGraph graph = captured.graph(); + requireSupportedFamilySchema(); + List counts = new ArrayList<>(); + for (WorldCanonicalAuthoredGraph.Family family : SUPPORTED_FAMILY_ORDER) { + counts.add(new FamilyCount(family.name(), graph.family(family).size())); + } + int roomCount = familyCount(counts, WorldCanonicalAuthoredGraph.Family.ROOM.name()); + if (roomCount == 0 || graph.family(WorldCanonicalAuthoredGraph.Family.ROOM).isEmpty()) { + throw unrepresentable( + UnrepresentableReason.ROOM_TOPOLOGY_REQUIRED, + "World complete artifact inventory requires the selected fresh graph's typed start room"); + } + + List generatorInputs = new ArrayList<>(); + for (var row : graph.family(WorldCanonicalAuthoredGraph.Family.REGION)) { + if (!row.authored().mutation().hasRegion()) { + throw unrepresentable( + UnrepresentableReason.UNKNOWN_GRAPH_FAMILY, + "World selected graph region lacks its closed generator-input representation"); + } + var region = row.authored().mutation().getRegion(); + String generatorType = region.getGeneratorType(); + String generatorParams = region.getGeneratorParams(); + generatorInputs.add( + new RegionGeneratorInput(row.template().templateId(), generatorType, generatorParams)); + } + + int generationRuleCount = + graph.family(WorldCanonicalAuthoredGraph.Family.GENERATION_RULE).size(); + + List spawnInputs = new ArrayList<>(); + for (var row : graph.family(WorldCanonicalAuthoredGraph.Family.WORLD_ENTITY_SPAWN_BINDING)) { + if (!row.content().hasWorldEntitySpawnBinding() || row.entityReference() == null) { + throw unrepresentable( + UnrepresentableReason.UNKNOWN_GRAPH_FAMILY, + "World selected graph spawn binding lacks its closed typed Entity reference"); + } + var spawn = row.content().getWorldEntitySpawnBinding(); + var reference = row.entityReference(); + spawnInputs.add( + new SpawnBindingInput( + row.template().templateId(), + UUID.fromString(spawn.getRoomId()), + spawn.getEntityTemplateType().name(), + reference.kind().name(), + reference.tenantId(), + reference.versionId(), + reference.templateId(), + spawn.getSpawnCount(), + spawn.getRespawnDelaySeconds())); + } + requireSupportedRequiredness( + graph.tenantId(), graph.versionId(), generatorInputs, generationRuleCount, spawnInputs); + + var operation = captured.application().application().operation(); + var selected = accountBinding.input().selection(); + var source = captured.owner().receipt().source(); + var owner = request.ownerBinding(); + var sourceModel = + new SourceModel( + SOURCE_MODEL, + 2, + WorldDraftGraphAppliedResult.digest(captured.application().graphBytes()), + WorldDraftGraphAppliedResult.digest(captured.topology().resultBytes()), + counts, + generatorInputs, + GENERATION_RULE_FIELDS, + REGION_FIELDS, + ZONE_FIELDS, + ROOM_FIELDS, + ROOM_EXIT_FIELDS, + SPAWN_BINDING_FIELDS, + spawnInputs, + generationRuleCount, + familyCount( + counts, WorldCanonicalAuthoredGraph.Family.WORLD_ENTITY_SPAWN_BINDING.name()), + captured.application().appliedEpochs()); + var bindingBytes = accountBinding.canonicalBytes(); + var envelope = + new Envelope( + SCHEMA, + 1, + "COMPLETE", + new OwnerScope( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + Long.toString(captured.owner().localTenantKey()), + Long.toString(captured.owner().localVersionKey()), + owner.versionIdentityOperationId(), + Long.toString(owner.gameDesignVersionId()), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest()), + new SourceIntake( + captured.owner().receipt().worldSlug(), + Long.toString(source.sourceGameRowId()), + source.sourceGameTenantKey(), + source.provenanceKind()), + new SelectedApplication( + operation.operationId(), + operation.requestId(), + operation.commitId().toString(), + operation.binding().digest(), + captured.application().digest()), + new AccountOrder( + accountBinding.operationId(), + accountBinding.fenceId(), + accountBinding.input().actorAccountId(), + selected.intent().publishRequestId(), + selected.digest(), + selected.selectedCommit().commitId().toString(), + WorldDraftGraphAppliedResult.digest(bindingBytes), + bindingBytes), + new Freeze( + attempt.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(request.versionStateEpoch()), + request.publishWorkflowId()), + new Checkpoint( + checkpoint.appliedCommitId(), + checkpoint.contentDigest(), + checkpoint.digestSchemaVersion()), + sourceModel, + ARTIFACT_DECISIONS); + requireEnvelopeBinding(envelope, attempt, accountBinding); + return new WorldSelectedPublicationArtifactInventory(envelope, encode(envelope)); + } + + static WorldSelectedPublicationArtifactInventory fromStored( + byte[] canonicalBytes, + String storedDigest, + FrozenAttempt attempt, + AccountPublicationAuthorizationBinding accountBinding, + long expectedLocalTenantKey, + long expectedLocalVersionKey) { + Objects.requireNonNull(canonicalBytes, "canonicalBytes"); + Objects.requireNonNull(storedDigest, "storedDigest"); + Envelope envelope = decodeCanonicalEnvelope(canonicalBytes); + if (!WorldDraftGraphAppliedResult.digest(canonicalBytes).equals(storedDigest) + || !Long.toString(expectedLocalTenantKey).equals(envelope.ownerScope().localTenantKey()) + || !Long.toString(expectedLocalVersionKey) + .equals(envelope.ownerScope().localVersionKey())) { + throw new ConflictException("Stored World artifact inventory is corrupt or noncanonical"); + } + requireEnvelopeBinding(envelope, attempt, accountBinding); + requireCompleteSupportedModel(envelope); + return new WorldSelectedPublicationArtifactInventory(envelope, canonicalBytes); + } + + static Envelope decodeCanonicalEnvelope(byte[] canonicalBytes) { + Objects.requireNonNull(canonicalBytes, "canonicalBytes"); + final Envelope envelope; + try { + envelope = JSON.readValue(canonicalBytes, Envelope.class); + } catch (RuntimeException invalid) { + throw new ConflictException("Stored World artifact inventory is not a closed typed value"); + } + if (envelope == null || !Arrays.equals(canonicalBytes, encode(envelope))) { + throw new ConflictException("Stored World artifact inventory is null or noncanonical"); + } + requireCanonicalLongFields(envelope); + return envelope; + } + + Envelope envelope() { + return envelope; + } + + byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + String contentDigest() { + return contentDigest; + } + + /** Returns the public canonical inventory projection, never private numeric owner/source keys. */ + public PublicEvidence publicEvidence() { + var owner = envelope.ownerScope(); + return new PublicEvidence( + envelope.schema(), + envelope.schemaVersion(), + envelope.completeness(), + new PublicOwnerScope( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest()), + envelope.selectedApplication(), + publicAccountOrder(envelope.accountOrder()), + envelope.freeze(), + envelope.checkpoint(), + envelope.sourceModel(), + envelope.artifactDecisions()); + } + + /** Canonical bytes for the safe public projection; private owner keys are never serialized. */ + public byte[] publicCanonicalBytes() { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(publicEvidence())); + } catch (IOException failure) { + throw new IllegalStateException( + "World public artifact inventory could not be encoded", failure); + } + } + + /** + * Digest of {@link #publicCanonicalBytes()}, distinct from the private durable-envelope digest. + */ + public String publicDigest() { + return WorldDraftGraphAppliedResult.digest(publicCanonicalBytes()); + } + + private static PublicAccountOrder publicAccountOrder(AccountOrder account) { + return new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.actorAccountId(), + account.publicationRequestId(), + account.selectionDigest(), + account.selectedCommitId(), + account.bindingDigest()); + } + + private static void requireEnvelopeBinding( + Envelope envelope, + FrozenAttempt attempt, + AccountPublicationAuthorizationBinding accountBinding) { + requireCanonicalLongFields(envelope); + var request = attempt.request(); + var owner = request.ownerBinding(); + var identity = envelope.ownerScope(); + var selected = accountBinding.input().selection(); + var selectedCommit = selected.selectedCommit(); + var checkpoint = attempt.checkpoint(); + var freeze = envelope.freeze(); + var account = envelope.accountOrder(); + var application = envelope.selectedApplication(); + var source = envelope.sourceIntake(); + var sourceModel = envelope.sourceModel(); + if (!SCHEMA.equals(envelope.schema()) + || envelope.schemaVersion() != 1 + || !"COMPLETE".equals(envelope.completeness()) + || !nonNil(identity.canonicalTenantId()) + || !nonNil(identity.canonicalVersionId()) + || !nonNil(identity.versionIdentityOperationId()) + || !nonNil(identity.intakeRequestId()) + || !nonNil(identity.intakeOperationId()) + || !nonNil(identity.sourceOperationId()) + || !isSha256(identity.intakeRequestDigest()) + || !isSha256(identity.sourceEvidenceDigest()) + || !isSha256(identity.intakeReceiptDigest()) + || !hasText(source.worldSlug()) + || !hasText(source.sourceGameTenantKey()) + || !hasText(source.sourceProvenanceKind()) + || !owner.targetNamespace().equals(identity.targetNamespace()) + || !owner.canonicalTenantId().equals(identity.canonicalTenantId()) + || !owner.canonicalVersionId().equals(identity.canonicalVersionId()) + || !owner.versionIdentityOperationId().equals(identity.versionIdentityOperationId()) + || !Long.toString(owner.gameDesignVersionId()).equals(identity.gameDesignVersionId()) + || !owner.intakeRequestId().equals(identity.intakeRequestId()) + || !owner.intakeOperationId().equals(identity.intakeOperationId()) + || !owner.intakeRequestDigest().equals(identity.intakeRequestDigest()) + || !owner.sourceOperationId().equals(identity.sourceOperationId()) + || !owner.sourceEvidenceDigest().equals(identity.sourceEvidenceDigest()) + || !owner.intakeReceiptDigest().equals(identity.intakeReceiptDigest()) + || !attempt.publicationFence().equals(freeze.publicationFence()) + || !request.publicationRequestId().equals(freeze.publicationRequestId()) + || !request.requestDigest().equals(freeze.requestDigest()) + || !Long.toString(request.versionStateEpoch()).equals(freeze.versionStateEpoch()) + || !request.publishWorkflowId().equals(freeze.publishWorkflowId()) + || !checkpoint.appliedCommitId().equals(envelope.checkpoint().appliedCommitId()) + || !checkpoint.contentDigest().equals(envelope.checkpoint().contentDigest()) + || checkpoint.digestSchemaVersion() != envelope.checkpoint().digestSchemaVersion() + || !accountBinding.operationId().equals(account.operationId()) + || !accountBinding.fenceId().equals(account.fenceId()) + || !accountBinding.input().actorAccountId().equals(account.actorAccountId()) + || !selected.intent().publishRequestId().equals(account.publicationRequestId()) + || !selected.digest().equals(account.selectionDigest()) + || !selected.selectedCommit().commitId().toString().equals(account.selectedCommitId()) + || !isSha256(account.selectionDigest()) + || !isSha256(account.bindingDigest()) + || !WorldDraftGraphAppliedResult.digest(accountBinding.canonicalBytes()) + .equals(account.bindingDigest()) + || !Arrays.equals(accountBinding.canonicalBytes(), account.canonicalBindingBytes()) + || !checkpoint.appliedCommitId().equals(application.appliedCommitId()) + || !selectedCommit.commitId().toString().equals(application.appliedCommitId()) + || !selectedCommit.requestId().equals(application.applicationRequestId()) + || !selectedCommit.digest().equals(application.bindingDigest()) + || application.applicationOperationId() == null + || application.applicationOperationId().equals(new UUID(0L, 0L)) + || application.applicationRequestId() == null + || application.applicationRequestId().equals(new UUID(0L, 0L)) + || !application.applicationRequestId().equals(selectedCommit.requestId()) + || !isSha256(application.bindingDigest()) + || !isSha256(application.appliedResultDigest()) + || !nonNil(account.operationId()) + || !nonNil(account.fenceId()) + || !nonNil(account.actorAccountId()) + || !nonNil(freeze.publicationFence()) + || !isHexDigest(freeze.requestDigest()) + || !isSha256(sourceModel.graphDigest()) + || !isSha256(sourceModel.topologyResultDigest()) + || !appliedEpochsMatch(selectedCommit, sourceModel.appliedEpochs()) + || !accountBinding.operationId().equals(account.operationId())) { + throw new ConflictException( + "World artifact inventory differs from exact Account order, selected graph, or freeze"); + } + } + + private static void requireCompleteSupportedModel(Envelope envelope) { + if (envelope.sourceModel() == null + || !SOURCE_MODEL.equals(envelope.sourceModel().modelId()) + || envelope.sourceModel().graphSchemaVersion() != 2 + || envelope.sourceModel().generationRuleInputCount() != 0 + || envelope.sourceModel().familyCounts().size() != SUPPORTED_FAMILY_ORDER.size() + || !envelope.sourceModel().regionFields().equals(REGION_FIELDS) + || !envelope.sourceModel().zoneFields().equals(ZONE_FIELDS) + || !envelope.sourceModel().roomFields().equals(ROOM_FIELDS) + || !envelope.sourceModel().roomExitFields().equals(ROOM_EXIT_FIELDS) + || !envelope.sourceModel().generationRuleFields().equals(GENERATION_RULE_FIELDS) + || !envelope.sourceModel().spawnBindingFields().equals(SPAWN_BINDING_FIELDS) + || envelope.artifactDecisions().size() != ARTIFACT_DECISIONS.size() + || !envelope.artifactDecisions().equals(ARTIFACT_DECISIONS) + || !isSha256(envelope.sourceModel().graphDigest()) + || !isSha256(envelope.sourceModel().topologyResultDigest()) + || !isHexDigest(envelope.checkpoint().contentDigest()) + || envelope.checkpoint().digestSchemaVersion() != 3) { + throw new ConflictException( + "Stored World artifact inventory does not declare the complete supported source model"); + } + for (int index = 0; index < SUPPORTED_FAMILY_ORDER.size(); index++) { + var familyCount = envelope.sourceModel().familyCounts().get(index); + if (!SUPPORTED_FAMILY_ORDER.get(index).name().equals(familyCount.family()) + || familyCount.rowCount() < 0) { + throw new ConflictException( + "Stored World artifact inventory family enumeration is incomplete"); + } + } + if (familyCount( + envelope.sourceModel().familyCounts(), + WorldCanonicalAuthoredGraph.Family.ROOM.name()) + == 0 + || familyCount( + envelope.sourceModel().familyCounts(), + WorldCanonicalAuthoredGraph.Family.GENERATION_RULE.name()) + != 0 + || familyCount( + envelope.sourceModel().familyCounts(), + WorldCanonicalAuthoredGraph.Family.WORLD_ENTITY_SPAWN_BINDING.name()) + != envelope.sourceModel().spawnBindingCount() + || envelope.sourceModel().spawnBindingInputs().size() + != envelope.sourceModel().spawnBindingCount() + || envelope.sourceModel().regionGeneratorInputs().size() + != familyCount( + envelope.sourceModel().familyCounts(), + WorldCanonicalAuthoredGraph.Family.REGION.name()) + || envelope.sourceModel().appliedEpochs().isEmpty()) { + throw new ConflictException( + "Stored World artifact inventory claims an unsupported requiredness input"); + } + requireSupportedRequiredness( + envelope.ownerScope().canonicalTenantId(), + envelope.ownerScope().canonicalVersionId(), + envelope.sourceModel().regionGeneratorInputs(), + envelope.sourceModel().generationRuleInputCount(), + envelope.sourceModel().spawnBindingInputs()); + } + + private static void requireSupportedFamilySchema() { + if (!Arrays.equals( + WorldCanonicalAuthoredGraph.Family.values(), + SUPPORTED_FAMILY_ORDER.toArray(WorldCanonicalAuthoredGraph.Family[]::new))) { + throw unrepresentable( + UnrepresentableReason.UNKNOWN_GRAPH_FAMILY, + "World authored graph family catalog changed without an artifact-requiredness rule"); + } + } + + static void requireSupportedRequiredness( + UUID canonicalTenantId, + UUID canonicalVersionId, + List regionInputs, + int generationRuleInputCount, + List spawnInputs) { + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + if (generationRuleInputCount != 0) { + throw unrepresentable( + UnrepresentableReason.GENERATION_RULE_INPUT, + "World selected graph has GENERATION_RULE name/scope/value inputs without a closed requiredness registry"); + } + for (var region : regionInputs) { + if (region.regionTemplateId() == null + || region.generatorType() == null + || region.generatorParams() == null) { + throw unrepresentable( + UnrepresentableReason.UNKNOWN_GRAPH_FAMILY, + "World complete inventory omitted an explicit REGION generatorType/generatorParams input"); + } + if (!region.generatorType().isEmpty() || !region.generatorParams().isEmpty()) { + throw unrepresentable( + UnrepresentableReason.REGION_GENERATOR_INPUT, + "World selected graph has non-empty opaque REGION generatorType/generatorParams; derived-artifact requiredness is unrepresentable"); + } + } + for (var spawn : spawnInputs) { + if (spawn == null + || !"ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID".equals(spawn.entityReferenceKind()) + || !canonicalTenantId.equals(spawn.entityTenantId()) + || !canonicalVersionId.equals(spawn.entityVersionId()) + || spawn.bindingTemplateId() == null + || spawn.roomTemplateId() == null + || spawn.entityTemplateId() == null + || !("ITEM".equals(spawn.entityTemplateType()) + || "NPC".equals(spawn.entityTemplateType())) + || spawn.spawnCount() <= 0 + || spawn.respawnDelaySeconds() < 0) { + throw unrepresentable( + UnrepresentableReason.SPAWN_BINDING_INPUT, + "World selected graph spawn binding has an unsupported typed Entity reference or count representation"); + } + } + } + + private static int familyCount(List counts, String family) { + return counts.stream() + .filter(count -> family.equals(count.family())) + .mapToInt(FamilyCount::rowCount) + .findFirst() + .orElseThrow( + () -> + unrepresentable( + UnrepresentableReason.UNKNOWN_GRAPH_FAMILY, + "World selected graph omitted a required closed source family")); + } + + private static boolean isSha256(String value) { + return value != null && SHA256.matcher(value).matches(); + } + + private static boolean isHexDigest(String value) { + return value != null && HEX_DIGEST.matcher(value).matches(); + } + + private static void requireCanonicalLongFields(Envelope envelope) { + var owner = envelope.ownerScope(); + var source = envelope.sourceIntake(); + var freeze = envelope.freeze(); + parsePositiveCanonicalLong(owner.localTenantKey(), "localTenantKey"); + parsePositiveCanonicalLong(owner.localVersionKey(), "localVersionKey"); + parsePositiveCanonicalLong(owner.gameDesignVersionId(), "gameDesignVersionId"); + parsePositiveCanonicalLong(source.sourceGameRowId(), "sourceGameRowId"); + parsePositiveCanonicalLong(freeze.versionStateEpoch(), "versionStateEpoch"); + } + + private static long parsePositiveCanonicalLong(String value, String field) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw new ConflictException( + "Stored World artifact inventory has a noncanonical positive decimal " + field); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new ConflictException( + "Stored World artifact inventory has a noncanonical positive decimal " + field); + } + return parsed; + } catch (NumberFormatException invalid) { + throw new ConflictException( + "Stored World artifact inventory has an out-of-range positive decimal " + field); + } + } + + private static boolean nonNil(UUID value) { + return value != null && !value.equals(new UUID(0L, 0L)); + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } + + private static boolean appliedEpochsMatch( + net.firedevops.firemud.common.authoring.DraftCommitBinding selectedCommit, + List actual) { + var expected = + selectedCommit.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + return !expected.isEmpty() && expected.equals(actual); + } + + static byte[] encode(Envelope envelope) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(envelope)); + } catch (IOException failure) { + throw new ConflictException("World complete artifact inventory could not be encoded"); + } + } + + private static UnrepresentableRequirednessException unrepresentable( + UnrepresentableReason reason, String message) { + return new UnrepresentableRequirednessException(reason, message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryRepository.java new file mode 100644 index 0000000000..0aea6cb8a8 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryRepository.java @@ -0,0 +1,202 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local immutable capture and historical readback for one selected-publication inventory. */ +final class WorldSelectedPublicationArtifactInventoryRepository { + private static final String SELECT_INVENTORY = + "SELECT i.publication_fence, i.target_namespace, i.canonical_tenant_id, " + + "i.canonical_version_id, i.local_tenant_key, i.local_version_key, " + + "i.applied_commit_id, i.account_operation_id, i.account_fence_id, " + + "i.inventory_schema_version, i.inventory_bytes, i.inventory_digest, " + + "a.account_binding_bytes, a.account_binding_digest " + + "FROM world_selected_publication_artifact_inventory i " + + "JOIN world_design_publication_account_binding a USING (publication_fence) " + + "WHERE i.publication_fence=?"; + + private final DSLContext dsl; + + WorldSelectedPublicationArtifactInventoryRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Stores only a first-freeze source captured by the checkpoint callback, or reads the exact + * immutable prior inventory when another claimant already froze the owner. + */ + WorldSelectedPublicationArtifactInventory retainOrRequireExact( + FrozenAttempt attempt, + AccountPublicationAuthorizationBinding accountBinding, + boolean attemptCreatedInThisTransaction, + WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint captured) { + Objects.requireNonNull(attempt, "attempt"); + Objects.requireNonNull(accountBinding, "accountBinding"); + requireWritableReadCommittedOwnerTransaction(); + if (attemptCreatedInThisTransaction) { + if (captured == null) { + throw conflict("New World freeze has no exact source for complete artifact inventory"); + } + if (dsl.fetchOne(SELECT_INVENTORY, attempt.publicationFence()) != null) { + throw conflict("New World freeze unexpectedly has a prior artifact inventory"); + } + var inventory = + WorldSelectedPublicationArtifactInventory.capture(attempt, accountBinding, captured); + var owner = inventory.envelope().ownerScope(); + int inserted = + dsl.execute( + "INSERT INTO world_selected_publication_artifact_inventory " + + "(publication_fence, target_namespace, canonical_tenant_id, " + + "canonical_version_id, local_tenant_key, local_version_key, applied_commit_id, " + + "account_operation_id, account_fence_id, inventory_schema_version, " + + "inventory_bytes, inventory_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + attempt.publicationFence(), + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + Long.parseLong(owner.localTenantKey()), + Long.parseLong(owner.localVersionKey()), + attempt.checkpoint().appliedCommitId(), + accountBinding.operationId(), + accountBinding.fenceId(), + inventory.envelope().schemaVersion(), + inventory.canonicalBytes(), + inventory.contentDigest()); + if (inserted != 1) { + throw conflict("World complete artifact inventory was not inserted"); + } + var readback = readExact(attempt, accountBinding); + if (!Arrays.equals(inventory.canonicalBytes(), readback.canonicalBytes()) + || !inventory.contentDigest().equals(readback.contentDigest())) { + throw conflict("World complete artifact inventory differs from first-freeze readback"); + } + return readback; + } + if (captured != null) { + throw conflict("Historical World freeze attempted to recapture artifact inventory source"); + } + return readExact(attempt, accountBinding); + } + + /** Exact post-commit read; absence or corrupt rows deny rather than imply an empty inventory. */ + WorldSelectedPublicationArtifactInventory readCommitted( + FrozenAttempt attempt, AccountPublicationAuthorizationBinding accountBinding) { + Objects.requireNonNull(attempt, "attempt"); + Objects.requireNonNull(accountBinding, "accountBinding"); + requireNoAmbientTransaction(); + return readExact(attempt, accountBinding); + } + + private WorldSelectedPublicationArtifactInventory readExact( + FrozenAttempt attempt, AccountPublicationAuthorizationBinding accountBinding) { + Record row = dsl.fetchOne(SELECT_INVENTORY, attempt.publicationFence()); + if (row == null) { + throw conflict("Exact frozen World publication has no complete artifact inventory"); + } + UUID publicationFence = required(row, "publication_fence", UUID.class); + String targetNamespace = required(row, "target_namespace", String.class); + UUID tenantId = required(row, "canonical_tenant_id", UUID.class); + UUID versionId = required(row, "canonical_version_id", UUID.class); + long localTenantKey = required(row, "local_tenant_key", Long.class); + long localVersionKey = required(row, "local_version_key", Long.class); + String appliedCommitId = required(row, "applied_commit_id", String.class); + UUID accountOperationId = required(row, "account_operation_id", UUID.class); + UUID accountFenceId = required(row, "account_fence_id", UUID.class); + short schemaVersion = required(row, "inventory_schema_version", Short.class); + byte[] inventoryBytes = required(row, "inventory_bytes", byte[].class); + String inventoryDigest = required(row, "inventory_digest", String.class); + byte[] retainedAccountBytes = required(row, "account_binding_bytes", byte[].class); + String retainedAccountDigest = required(row, "account_binding_digest", String.class); + var request = attempt.request(); + if (!publicationFence.equals(attempt.publicationFence()) + || !targetNamespace.equals(request.targetNamespace()) + || !tenantId.equals(request.canonicalTenantId()) + || !versionId.equals(request.canonicalVersionId()) + || !appliedCommitId.equals(attempt.checkpoint().appliedCommitId()) + || !accountOperationId.equals(accountBinding.operationId()) + || !accountFenceId.equals(accountBinding.fenceId()) + || schemaVersion != 1 + || !Arrays.equals(retainedAccountBytes, accountBinding.canonicalBytes()) + || !DraftAuthorizationFenceBinding.digest(retainedAccountBytes) + .equals(retainedAccountDigest)) { + throw conflict( + "Stored World artifact inventory columns differ from exact freeze and Account order"); + } + try { + var retainedAccount = AccountPublicationAuthorizationBinding.fromStored(retainedAccountBytes); + if (!Arrays.equals(retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) { + throw conflict("Stored World artifact inventory Account order is not exact"); + } + } catch (RuntimeException invalid) { + throw conflict("Stored World artifact inventory Account order is corrupt"); + } + var inventory = + WorldSelectedPublicationArtifactInventory.fromStored( + inventoryBytes, + inventoryDigest, + attempt, + accountBinding, + localTenantKey, + localVersionKey); + var scope = inventory.envelope().ownerScope(); + if (!scope.targetNamespace().equals(targetNamespace) + || !scope.canonicalTenantId().equals(tenantId) + || !scope.canonicalVersionId().equals(versionId) + || !Long.toString(localTenantKey).equals(scope.localTenantKey()) + || !Long.toString(localVersionKey).equals(scope.localVersionKey())) { + throw conflict("Stored World artifact inventory owner scope differs from its row"); + } + return inventory; + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World artifact inventory capture requires a writable owner transaction"); + } + Integer isolation = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (isolation != null && isolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("World artifact inventory capture requires READ COMMITTED"); + } + 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 artifact inventory capture requires writable READ COMMITTED storage"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World artifact inventory committed read requires no ambient transaction"); + } + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) { + throw conflict("World artifact inventory is missing retained field " + field); + } + return value; + } + + private static ConflictException conflict(String message) { + return new ConflictException(message); + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V55__selected_publication_artifact_inventory.sql b/services/world-management-service/src/main/resources/db/migration/V55__selected_publication_artifact_inventory.sql new file mode 100644 index 0000000000..21f2f442bb --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V55__selected_publication_artifact_inventory.sql @@ -0,0 +1,112 @@ +CREATE TABLE world_selected_publication_artifact_inventory ( + publication_fence UUID NOT NULL PRIMARY KEY + REFERENCES world_design_publication_fence_attempt(publication_fence) ON DELETE RESTRICT, + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + local_tenant_key BIGINT NOT NULL, + local_version_key BIGINT NOT NULL, + applied_commit_id VARCHAR(256) NOT NULL, + account_operation_id UUID NOT NULL, + account_fence_id UUID NOT NULL, + inventory_schema_version SMALLINT NOT NULL CHECK (inventory_schema_version = 1), + inventory_bytes BYTEA NOT NULL CHECK (octet_length(inventory_bytes) > 0), + inventory_digest VARCHAR(71) NOT NULL + CHECK (inventory_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT fk_world_selected_publication_inventory_account + FOREIGN KEY (publication_fence) + REFERENCES world_design_publication_account_binding(publication_fence) + ON DELETE RESTRICT, + CONSTRAINT uq_world_selected_publication_inventory_account_operation + UNIQUE (account_operation_id), + CONSTRAINT uq_world_selected_publication_inventory_account_fence + UNIQUE (account_fence_id), + CONSTRAINT ck_world_selected_publication_inventory_scope + CHECK (local_tenant_key > 0 AND local_version_key > 0), + CONSTRAINT ck_world_selected_publication_inventory_ids + CHECK ( + publication_fence <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_world_selected_publication_inventory_namespace + CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' + ), + CONSTRAINT ck_world_selected_publication_inventory_commit + CHECK (octet_length(applied_commit_id) BETWEEN 1 AND 256) +); + +-- [jooq ignore start] +REVOKE ALL ON world_selected_publication_artifact_inventory FROM PUBLIC; + +CREATE FUNCTION world_validate_selected_publication_artifact_inventory() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + account_binding "${serviceSchema}".world_design_publication_account_binding%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World selected-publication artifact inventory is immutable' + USING ERRCODE = '55000'; + END IF; + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'World selected-publication artifact inventory requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT attempt + FROM "${serviceSchema}".world_design_publication_fence_attempt a + WHERE a.publication_fence = NEW.publication_fence + AND a.attempt_created_full_xid = pg_current_xact_id() + AND a.xmin::TEXT = (txid_current() % 4294967296)::TEXT; + SELECT * INTO STRICT owner_row + FROM "${serviceSchema}".world_design_publication_fence_owner o + WHERE o.target_namespace = attempt.target_namespace + AND o.canonical_tenant_id = attempt.canonical_tenant_id + AND o.local_tenant_key = attempt.local_tenant_key + AND o.version_id = attempt.version_id + FOR UPDATE; + SELECT * INTO STRICT account_binding + FROM "${serviceSchema}".world_design_publication_account_binding b + WHERE b.publication_fence = NEW.publication_fence; + + IF attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR attempt.target_namespace IS DISTINCT FROM NEW.target_namespace + OR attempt.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR attempt.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR attempt.version_id IS DISTINCT FROM NEW.local_version_key + OR attempt.local_tenant_key IS DISTINCT FROM NEW.local_tenant_key + OR attempt.applied_commit_id IS DISTINCT FROM NEW.applied_commit_id + OR account_binding.account_operation_id IS DISTINCT FROM NEW.account_operation_id + OR account_binding.account_fence_id IS DISTINCT FROM NEW.account_fence_id + OR encode(sha256(account_binding.account_binding_bytes), 'hex') + IS DISTINCT FROM substring(account_binding.account_binding_digest FROM 8) + OR encode(sha256(NEW.inventory_bytes), 'hex') + IS DISTINCT FROM substring(NEW.inventory_digest FROM 8) + OR owner_row.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence THEN + RAISE EXCEPTION 'World artifact inventory differs from the newly qualified selected freeze' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_selected_publication_artifact_inventory_validate + BEFORE INSERT ON world_selected_publication_artifact_inventory FOR EACH ROW + EXECUTE FUNCTION world_validate_selected_publication_artifact_inventory(); +CREATE TRIGGER trg_world_selected_publication_artifact_inventory_immutable + BEFORE UPDATE OR DELETE ON world_selected_publication_artifact_inventory FOR EACH ROW + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +CREATE TRIGGER trg_world_selected_publication_artifact_inventory_no_truncate + BEFORE TRUNCATE ON world_selected_publication_artifact_inventory FOR EACH STATEMENT + EXECUTE FUNCTION world_reject_publication_attempt_history_mutation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 650c9fe04f..2c44ac9241 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -26,6 +26,7 @@ import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; @@ -87,6 +88,7 @@ import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -234,7 +236,8 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() missingApplicationEvidence, () -> checkpointRepository() - .capture(missingApplicationEvidence, plan)))) + .captureWithSource(missingApplicationEvidence, plan) + .checkpoint()))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("actual APPLIED graph application"); var stateAfterMissingApplicationDenial = ownerSnapshot(world, plan); @@ -361,6 +364,7 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() .isEqualTo("OPEN"); assertThat(stateBeforeFirstQualifiedCapture.publicationAttemptRows()).isEmpty(); assertThat(stateBeforeFirstQualifiedCapture.publicationAuthorizationRows()).isEmpty(); + assertThat(stateBeforeFirstQualifiedCapture.artifactInventoryRows()).isEmpty(); var forcedRollback = new IllegalStateException("forced first-freeze qualification rollback"); assertThatThrownBy( @@ -368,17 +372,32 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() ownerTransaction() .execute( status -> { + var capturedCheckpoint = + new AtomicReference< + WorldSelectedDraftPublicationCheckpointRepository + .CapturedCheckpoint>(); var candidate = fence.claimFreeze( freezeEvidence, - () -> - checkpointRepository().capture(freezeEvidence, plan)); + () -> { + var captured = + checkpointRepository() + .captureWithSource(freezeEvidence, plan); + capturedCheckpoint.set(captured); + return captured.checkpoint(); + }); assertThat( publicationAuthorizationRepository .retainOrRequireExact( candidate, publicationOrder, true) .canonicalBytes()) .containsExactly(publicationOrder.canonicalBytes()); + artifactInventoryRepository() + .retainOrRequireExact( + candidate, + publicationOrder, + true, + capturedCheckpoint.get()); throw forcedRollback; })) .isSameAs(forcedRollback); @@ -390,6 +409,7 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() assertThat(stateAfterFirstQualifiedCaptureRollback.publicationAttemptRows()).isEmpty(); assertThat(stateAfterFirstQualifiedCaptureRollback.publicationAuthorizationRows()) .isEmpty(); + assertThat(stateAfterFirstQualifiedCaptureRollback.artifactInventoryRows()).isEmpty(); var freezeRequest = WorldSelectedDraftPublicationFreezeEvidence.Request.create( NAMESPACE, @@ -412,12 +432,43 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() .isEqualTo(frozenAttempt.checkpoint().contentDigest()); assertThat(firstFreeze.acknowledgement().digestSchemaVersion()) .isEqualTo(frozenAttempt.checkpoint().digestSchemaVersion()); + var inventoryRepository = artifactInventoryRepository(); + var inventory = inventoryRepository.readCommitted(frozenAttempt, publicationOrder); + var publicInventory = inventory.publicEvidence(); + assertThat(publicInventory.completeness()).isEqualTo("COMPLETE"); + assertThat(publicInventory.sourceModel().familyCounts()) + .extracting(WorldSelectedPublicationArtifactInventory.FamilyCount::family) + .containsExactly( + "REGION", + "ZONE", + "ROOM", + "ROOM_EXIT", + "GENERATION_RULE", + "WORLD_ENTITY_SPAWN_BINDING"); + assertThat(publicInventory.sourceModel().familyCounts()) + .extracting(WorldSelectedPublicationArtifactInventory.FamilyCount::rowCount) + .containsExactly(1, 1, 1, 0, 0, 0); + assertThat(publicInventory.artifactDecisions()) + .extracting( + WorldSelectedPublicationArtifactInventory.ArtifactDecision::artifactKind) + .containsExactly("NAVMESH", "PATH_GRAPH"); + assertThat(publicInventory.accountOrder().bindingDigest()) + .isEqualTo( + DraftAuthorizationFenceBinding.digest(publicationOrder.canonicalBytes())); + String publicInventoryJson = + new String( + inventory.publicCanonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + assertThat(publicInventoryJson) + .doesNotContain( + "localTenantKey", "localVersionKey", "gameDesignVersionId", "sourceGameRowId"); + assertThat(inventory.publicDigest()).matches("sha256:[0-9a-f]{64}"); account.assertPublicationSourcesHeld(publicationOrder); var frozen = capture(plan, freezeEvidence, frozenAttempt); assertThat(frozenAttempt.checkpoint().appliedCommitId()) .isEqualTo(applied.application().operation().commitId().toString()); var retryEvidence = freezeEvidence; var stateBeforeExactRetry = ownerSnapshot(world, plan); + assertThat(stateBeforeExactRetry.artifactInventoryRows()).hasSize(1); int selectedReadsBeforeRetry = selectedReadCalls.get(); int stateReadsBeforeRetry = versionStateReadCalls.get(); // A fresh authenticated transport recovers the committed acknowledgement without @@ -439,7 +490,20 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() .orElseThrow() .canonicalBytes()) .containsExactly(publicationOrder.canonicalBytes()); + var retryInventory = inventoryRepository.readCommitted(exactRetry, publicationOrder); + assertThat(retryInventory.canonicalBytes()).containsExactly(inventory.canonicalBytes()); + assertThat(retryInventory.publicCanonicalBytes()) + .containsExactly(inventory.publicCanonicalBytes()); account.assertPublicationSourcesHeld(publicationOrder); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE world_selected_publication_artifact_inventory " + + "SET inventory_bytes=? WHERE publication_fence=?", + "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8), + exactRetry.publicationFence())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("immutable"); var changedOperation = new AccountPublicationAuthorizationBinding( UUID.randomUUID(), @@ -607,7 +671,11 @@ void committedUnqualifiedAttemptCannotBeLateQualified() throws Exception { .execute( status -> fence.claimFreeze( - evidence, () -> checkpointRepository().capture(evidence, plan)))); + evidence, + () -> + checkpointRepository() + .captureWithSource(evidence, plan) + .checkpoint()))); var authorizationRepository = publicationAuthorizationRepository(); assertThat(authorizationRepository.readCommitted(unqualified)).isEmpty(); var before = ownerSnapshot(world, plan); @@ -1224,6 +1292,7 @@ private WorldSelectedDraftPublicationFreezeService selectedPublicationFreezeServ fence, checkpointRepository(), publicationAuthorizationRepository(), + artifactInventoryRepository(), appliedRepository(), manager); } @@ -1284,6 +1353,10 @@ private WorldSelectedDraftPublicationCheckpointRepository checkpointRepository() return new WorldSelectedDraftPublicationAuthorizationRepository(dsl); } + private WorldSelectedPublicationArtifactInventoryRepository artifactInventoryRepository() { + return new WorldSelectedPublicationArtifactInventoryRepository(dsl); + } + private DraftOwnerSnapshot ownerSnapshot(Fixture fixture, WorldDraftTopologyCommitPlan plan) { long tenant = fixture.intake().localTenantKey(); long version = fixture.version().localVersionKey(); @@ -1379,6 +1452,16 @@ private DraftOwnerSnapshot ownerSnapshot(Fixture fixture, WorldDraftTopologyComm fixture.owner().targetNamespace(), fixture.owner().canonicalTenantId(), version); + var artifactInventoryRows = + rowJson( + "SELECT to_jsonb(i)::text AS row_json " + + "FROM world_selected_publication_artifact_inventory i " + + "JOIN world_design_publication_fence_attempt a USING (publication_fence) " + + "WHERE a.target_namespace=? AND a.canonical_tenant_id=? AND a.version_id=? " + + "ORDER BY i.publication_fence", + fixture.owner().targetNamespace(), + fixture.owner().canonicalTenantId(), + version); return new DraftOwnerSnapshot( List.copyOf(currentRows), mappingRows, @@ -1391,7 +1474,8 @@ private DraftOwnerSnapshot ownerSnapshot(Fixture fixture, WorldDraftTopologyComm terminalIdentityRows, publicationOwnerRows, publicationAttemptRows, - publicationAuthorizationRows); + publicationAuthorizationRows, + artifactInventoryRows); } private List rowJson(String sql, Object... bindings) { @@ -1410,7 +1494,8 @@ private record DraftOwnerSnapshot( List terminalIdentityRows, List publicationOwnerRows, List publicationAttemptRows, - List publicationAuthorizationRows) {} + List publicationAuthorizationRows, + List artifactInventoryRows) {} private AuthoredDraftPublishSelectionBinding publicationSelection( WorldDraftTopologyCommitPlan plan, String publicationRequest, long versionStateEpoch) { diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java index 6812714f09..54c58c4817 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java @@ -92,18 +92,24 @@ void ownerResolvesAppliedBeforeExactRetryAndRetrySkipsMutableRemoteReads() { .isEqualTo(WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN); var order = inOrder( - collaborators.applications, collaborators.fence, collaborators.authorizationRepository); + collaborators.applications, + collaborators.fence, + collaborators.authorizationRepository, + collaborators.artifactInventoryRepository); order .verify(collaborators.applications) .readSelectedPublicationApplication(NAMESPACE, TENANT, VERSION, fixture.selection()); order.verify(collaborators.fence).readAttempt(fixture.evidence()); order.verify(collaborators.authorizationRepository).readCommitted(prior); + order + .verify(collaborators.artifactInventoryRepository) + .readCommitted(prior, fixture.accountBinding()); verifyNoInteractions( collaborators.selectionClient, collaborators.versionStateClient, collaborators.accountClient); verify(collaborators.fence, never()).claimFreeze(any(), any()); - verify(collaborators.checkpointRepository, never()).capture(any(), any()); + verify(collaborators.checkpointRepository, never()).captureWithSource(any(), any()); assertThat(collaborators.transactionManager.commits).isZero(); } @@ -180,6 +186,7 @@ private static WorldSelectedDraftPublicationFreezeService service( collaborators.fence, collaborators.checkpointRepository, collaborators.authorizationRepository, + collaborators.artifactInventoryRepository, collaborators.applications, collaborators.transactionManager); } @@ -376,6 +383,8 @@ private static final class Collaborators { mock(WorldSelectedDraftPublicationCheckpointRepository.class); final WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository = mock(WorldSelectedDraftPublicationAuthorizationRepository.class); + final WorldSelectedPublicationArtifactInventoryRepository artifactInventoryRepository = + mock(WorldSelectedPublicationArtifactInventoryRepository.class); final WorldDraftGraphApplicationRepository applications = mock(WorldDraftGraphApplicationRepository.class); final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); @@ -389,6 +398,7 @@ void verifyNoReadsOrWrites() { fence, checkpointRepository, authorizationRepository, + artifactInventoryRepository, applications); } } diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java index 413f924211..7ff400fb35 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java @@ -111,7 +111,7 @@ void exactCommittedRetryUsesFrozenAccountCorrelationBeforeMutableRemoteReads() { collaborators.selectionClient, collaborators.versionStateClient, collaborators.accountClient); - verify(collaborators.checkpointRepository, never()).capture(any(), any()); + verify(collaborators.checkpointRepository, never()).captureWithSource(any(), any()); verify(collaborators.fence, never()).claimFreeze(any(), any()); assertThat(collaborators.transactionManager.commits).isZero(); } @@ -270,8 +270,10 @@ void firstFreezeReadsSelectionCurrentDraftAndAccountHeldBeforeOwnerTransaction() assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); return accountRead(invocation.getArgument(0)); }); - when(collaborators.checkpointRepository.capture(fixture.evidence(), fixture.plan())) - .thenReturn(fixture.checkpoint()); + when(collaborators.checkpointRepository.captureWithSource(fixture.evidence(), fixture.plan())) + .thenReturn( + new WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint( + fixture.checkpoint(), null, null, null, null)); when(collaborators.fence.claimFreeze(eq(fixture.evidence()), any())) .thenAnswer( invocation -> { @@ -284,6 +286,9 @@ void firstFreezeReadsSelectionCurrentDraftAndAccountHeldBeforeOwnerTransaction() .thenReturn(fixture.accountBinding()); when(collaborators.authorizationRepository.readCommitted(committed)) .thenReturn(Optional.of(fixture.accountBinding())); + when(collaborators.artifactInventoryRepository.retainOrRequireExact( + eq(committed), eq(fixture.accountBinding()), eq(true), any())) + .thenReturn(null); var service = service(fixture, collaborators); FrozenAttempt result = @@ -304,7 +309,8 @@ void firstFreezeReadsSelectionCurrentDraftAndAccountHeldBeforeOwnerTransaction() collaborators.versionStateClient, collaborators.accountClient, collaborators.fence, - collaborators.authorizationRepository); + collaborators.authorizationRepository, + collaborators.artifactInventoryRepository); order.verify(collaborators.selectionClient).read(any()); order.verify(collaborators.versionStateClient).read(any()); order.verify(collaborators.accountClient).read(any()); @@ -312,7 +318,11 @@ void firstFreezeReadsSelectionCurrentDraftAndAccountHeldBeforeOwnerTransaction() order .verify(collaborators.authorizationRepository) .retainOrRequireExact(committed, fixture.accountBinding(), true); - verify(collaborators.checkpointRepository).capture(fixture.evidence(), fixture.plan()); + order + .verify(collaborators.artifactInventoryRepository) + .retainOrRequireExact(eq(committed), eq(fixture.accountBinding()), eq(true), any()); + verify(collaborators.checkpointRepository) + .captureWithSource(fixture.evidence(), fixture.plan()); } @Test @@ -521,8 +531,10 @@ void transactionFailureAfterClaimRollsBackAndReturnsNoAcknowledgement() { VERSION_EPOCH)); when(collaborators.accountClient.read(any())) .thenAnswer(invocation -> accountRead(invocation.getArgument(0))); - when(collaborators.checkpointRepository.capture(fixture.evidence(), fixture.plan())) - .thenReturn(fixture.checkpoint()); + when(collaborators.checkpointRepository.captureWithSource(fixture.evidence(), fixture.plan())) + .thenReturn( + new WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint( + fixture.checkpoint(), null, null, null, null)); when(collaborators.fence.claimFreeze(eq(fixture.evidence()), any())) .thenAnswer( invocation -> { @@ -586,7 +598,7 @@ void raceLoserCannotAttachAccountOrderToAnExistingUnqualifiedFreeze() { fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("cannot be attached"); - verify(collaborators.checkpointRepository, never()).capture(any(), any()); + verify(collaborators.checkpointRepository, never()).captureWithSource(any(), any()); verify(collaborators.fence).readAttempt(fixture.evidence()); assertThat(collaborators.transactionManager.commits).isZero(); assertThat(collaborators.transactionManager.rollbacks).isEqualTo(1); @@ -624,6 +636,7 @@ private static WorldSelectedDraftPublicationFreezeService service( collaborators.fence, collaborators.checkpointRepository, collaborators.authorizationRepository, + collaborators.artifactInventoryRepository, collaborators.transactionManager); } @@ -924,6 +937,8 @@ private static final class Collaborators { mock(WorldSelectedDraftPublicationCheckpointRepository.class); final WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository = mock(WorldSelectedDraftPublicationAuthorizationRepository.class); + final WorldSelectedPublicationArtifactInventoryRepository artifactInventoryRepository = + mock(WorldSelectedPublicationArtifactInventoryRepository.class); final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); void verifyNoReadsOrWrites() { @@ -934,7 +949,8 @@ void verifyNoReadsOrWrites() { intakeRepository, fence, checkpointRepository, - authorizationRepository); + authorizationRepository, + artifactInventoryRepository); } } diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java new file mode 100644 index 0000000000..75368914ef --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java @@ -0,0 +1,219 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class WorldSelectedPublicationArtifactInventoryTest { + private static final UUID TENANT = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID VERSION = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + @Test + void acceptsExplicitEmptyRegionInputsAndClosedCanonicalSpawnBinding() { + var region = + new WorldSelectedPublicationArtifactInventory.RegionGeneratorInput( + UUID.randomUUID(), "", ""); + var spawn = + new WorldSelectedPublicationArtifactInventory.SpawnBindingInput( + UUID.randomUUID(), + UUID.randomUUID(), + "NPC", + "ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID", + TENANT, + VERSION, + UUID.randomUUID(), + 2, + 30); + + assertThatCode( + () -> + WorldSelectedPublicationArtifactInventory.requireSupportedRequiredness( + TENANT, VERSION, List.of(region), 0, List.of(spawn))) + .doesNotThrowAnyException(); + } + + @Test + void rejectsMissingOrNullRegionRequirednessInputsInsteadOfTreatingThemAsEmpty() { + var missingType = + new WorldSelectedPublicationArtifactInventory.RegionGeneratorInput( + UUID.randomUUID(), null, ""); + var missingParams = + new WorldSelectedPublicationArtifactInventory.RegionGeneratorInput( + UUID.randomUUID(), "", null); + + assertReason( + () -> + WorldSelectedPublicationArtifactInventory.requireSupportedRequiredness( + TENANT, VERSION, List.of(missingType), 0, List.of()), + WorldSelectedPublicationArtifactInventory.UnrepresentableReason.UNKNOWN_GRAPH_FAMILY); + assertReason( + () -> + WorldSelectedPublicationArtifactInventory.requireSupportedRequiredness( + TENANT, VERSION, List.of(missingParams), 0, List.of()), + WorldSelectedPublicationArtifactInventory.UnrepresentableReason.UNKNOWN_GRAPH_FAMILY); + } + + @Test + void rejectsOpaqueRegionAndGenerationRuleInputsAsUnrepresentable() { + var opaqueGenerator = + new WorldSelectedPublicationArtifactInventory.RegionGeneratorInput( + UUID.randomUUID(), "noise-v1", "{\"seed\":9}"); + + assertReason( + () -> + WorldSelectedPublicationArtifactInventory.requireSupportedRequiredness( + TENANT, VERSION, List.of(opaqueGenerator), 0, List.of()), + WorldSelectedPublicationArtifactInventory.UnrepresentableReason.REGION_GENERATOR_INPUT); + assertReason( + () -> + WorldSelectedPublicationArtifactInventory.requireSupportedRequiredness( + TENANT, VERSION, List.of(), 1, List.of()), + WorldSelectedPublicationArtifactInventory.UnrepresentableReason.GENERATION_RULE_INPUT); + } + + @Test + void rejectsUnsupportedEntityReferenceScopeOrRepresentation() { + var unsupportedReference = + new WorldSelectedPublicationArtifactInventory.SpawnBindingInput( + UUID.randomUUID(), + UUID.randomUUID(), + "NPC", + "ENTITY_TEMPLATE_REFERENCE_TYPE_RETAINED_TAG", + TENANT, + VERSION, + UUID.randomUUID(), + 1, + 0); + + assertReason( + () -> + WorldSelectedPublicationArtifactInventory.requireSupportedRequiredness( + TENANT, VERSION, List.of(), 0, List.of(unsupportedReference)), + WorldSelectedPublicationArtifactInventory.UnrepresentableReason.SPAWN_BINDING_INPUT); + } + + @Test + void canonicalLongFieldsRoundTripAsExactDecimalStrings() { + long beyondBinary64IntegerPrecision = 9_007_199_254_740_993L; + long maximumLong = Long.MAX_VALUE; + var envelope = + new WorldSelectedPublicationArtifactInventory.Envelope( + WorldSelectedPublicationArtifactInventory.SCHEMA, + 1, + "COMPLETE", + new WorldSelectedPublicationArtifactInventory.OwnerScope( + "world", + TENANT, + VERSION, + Long.toString(beyondBinary64IntegerPrecision), + Long.toString(maximumLong), + UUID.randomUUID(), + Long.toString(maximumLong), + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "1".repeat(64), + UUID.randomUUID(), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)), + new WorldSelectedPublicationArtifactInventory.SourceIntake( + "world", Long.toString(maximumLong), "source-tenant", "CANONICAL"), + new WorldSelectedPublicationArtifactInventory.SelectedApplication( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID().toString(), + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64)), + new WorldSelectedPublicationArtifactInventory.AccountOrder( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "publish", + "sha256:" + "6".repeat(64), + UUID.randomUUID().toString(), + "sha256:" + "7".repeat(64), + new byte[] {1}), + new WorldSelectedPublicationArtifactInventory.Freeze( + UUID.randomUUID(), + "publish", + "8".repeat(64), + Long.toString(maximumLong), + "workflow"), + new WorldSelectedPublicationArtifactInventory.Checkpoint( + UUID.randomUUID().toString(), "9".repeat(64), 3), + new WorldSelectedPublicationArtifactInventory.SourceModel( + "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1", + 2, + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + List.of(), + List.of(), + List.of(), + List.of(), + List.of(), + List.of(), + List.of(), + List.of(), + List.of(), + 0, + 0, + List.of()), + List.of()); + byte[] canonicalBytes = WorldSelectedPublicationArtifactInventory.encode(envelope); + String canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); + + assertThat(canonicalJson) + .contains("\"localTenantKey\":\"9007199254740993\"") + .contains("\"localVersionKey\":\"9223372036854775807\"") + .contains("\"gameDesignVersionId\":\"9223372036854775807\"") + .contains("\"sourceGameRowId\":\"9223372036854775807\"") + .contains("\"versionStateEpoch\":\"9223372036854775807\""); + + var decoded = WorldSelectedPublicationArtifactInventory.decodeCanonicalEnvelope(canonicalBytes); + var originalInventory = new WorldSelectedPublicationArtifactInventory(envelope, canonicalBytes); + var decodedInventory = new WorldSelectedPublicationArtifactInventory(decoded, canonicalBytes); + assertThat(decoded.ownerScope().localTenantKey()) + .isEqualTo(Long.toString(beyondBinary64IntegerPrecision)); + assertThat(decoded.ownerScope().localVersionKey()).isEqualTo(Long.toString(maximumLong)); + assertThat(decoded.sourceIntake().sourceGameRowId()).isEqualTo(Long.toString(maximumLong)); + assertThat(decoded.freeze().versionStateEpoch()).isEqualTo(Long.toString(maximumLong)); + assertThat(decodedInventory.publicEvidence().freeze().versionStateEpoch()) + .isEqualTo(Long.toString(maximumLong)); + assertThat(new String(decodedInventory.publicCanonicalBytes(), StandardCharsets.UTF_8)) + .contains("\"versionStateEpoch\":\"9223372036854775807\""); + assertThat(decodedInventory.publicDigest()).isEqualTo(originalInventory.publicDigest()); + + String zeroPaddedEpoch = + canonicalJson.replace( + "\"versionStateEpoch\":\"9223372036854775807\"", + "\"versionStateEpoch\":\"09223372036854775807\""); + assertThatThrownBy( + () -> + WorldSelectedPublicationArtifactInventory.decodeCanonicalEnvelope( + zeroPaddedEpoch.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + String floatingEpoch = + canonicalJson.replace( + "\"versionStateEpoch\":\"9223372036854775807\"", + "\"versionStateEpoch\":9223372036854775807.0"); + assertThatThrownBy( + () -> + WorldSelectedPublicationArtifactInventory.decodeCanonicalEnvelope( + floatingEpoch.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); + } + + private static void assertReason( + Runnable action, WorldSelectedPublicationArtifactInventory.UnrepresentableReason expected) { + Throwable failure = catchThrowable(action::run); + assertThat(failure) + .isInstanceOfSatisfying( + WorldSelectedPublicationArtifactInventory.UnrepresentableRequirednessException.class, + exception -> assertThat(exception.reason()).isEqualTo(expected)); + } +} From 7bab528928f6e1eb754b9a8a449937c323f21665 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:30:16 +1300 Subject: [PATCH 037/129] Retain ordinary asset source history and authenticate World inventory reads --- .../game-design-service/asset-storage.md | 11 +- .../game-design-service/game-templates.md | 44 +- .../game-design-service/version-control.md | 2 + .../world-management-service/api-contracts.md | 1 + .../runtime-and-data.md | 2 + ...ame-authoring-publishing-and-activation.md | 3 +- ...ted_draft_publication_freeze_service.proto | 18 + ...tedPublicationArtifactInventoryClient.java | 160 +++++ ...dPublicationArtifactInventoryEvidence.java | 595 ++++++++++++++++++ ...PublicationArtifactInventoryGrpcCodec.java | 77 +++ ...ublicationArtifactInventoryClientTest.java | 162 +++++ ...icationArtifactInventoryGrpcCodecTest.java | 396 ++++++++++++ .../publication/AssetApplication.java | 43 ++ .../gamedesign/publication/AssetSnapshot.java | 202 ++++++ .../gamedesign/publication/AssetSource.java | 327 ++++++++++ .../publication/AssetSourceRepository.java | 574 +++++++++++++++++ .../gamedesign/publication/CommandSource.java | 6 +- .../publication/CommandSourceRepository.java | 6 +- .../GameDesignSourceRepository.java | 138 +++- .../publication/RealmPolicySource.java | 2 +- .../VersionAssetPublicationRepository.java | 110 +--- .../migration/V55__ordinary_asset_source.sql | 389 ++++++++++++ .../draft/IsolatedPublicationOwnerSetup.java | 60 ++ ...setPublicationPostgresIntegrationTest.java | 489 +++++++++++++- .../publication/AssetSnapshotTest.java | 93 +++ .../publication/AssetSourceTest.java | 270 ++++++++ ...VersionAssetPublicationRepositoryTest.java | 17 + ...WorldDesignPublicationFenceRepository.java | 14 + ...ctedDraftPublicationFreezeGrpcService.java | 79 ++- ...dSelectedPublicationArtifactInventory.java | 165 ++--- ...blicationArtifactInventoryReadService.java | 130 ++++ ...uthorizedDraftPostgresIntegrationTest.java | 151 ++++- ...DraftPublicationFreezeGrpcServiceTest.java | 95 ++- ...ectedPublicationArtifactInventoryTest.java | 274 ++++++-- 34 files changed, 4767 insertions(+), 338 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V55__ordinary_asset_source.sql create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSourceTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryReadService.java diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 44794d9b48..56f4eaefa4 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,7 +6,8 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b ## Implementation Status -- **Current first slice:** The ordinary exporter requires V37's durable version-scoped snapshot and verifies its mappings and retained `game_assets.data` bytes before each export or retry. There is no tenant-wide fallback or process-local selection cache. Production Draft mapping/source authoring and automatic snapshot creation remain absent, so missing evidence denies export rather than proving an empty release. Frozen source bytes are database-protected, while unreferenced Draft uploads remain mutable. Version-prefix object writes, numeric public asset identifiers and post-write repair comparison remain drift from the target immutable-candidate lifecycle. See the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle) for capability and proof limits. +- **Current first slice:** The ordinary exporter requires V37's durable version-scoped snapshot and verifies its mappings and retained `game_assets.data` bytes before each export or retry. There is no tenant-wide fallback or process-local selection cache. A local `ASSET_REFERENCE` producer candidate now supplies coordinator/history/genesis/snapshot writing and export agreement, but it has not yet been validated or published; until then, production Draft source authoring and automatic snapshot creation remain unavailable, and missing evidence denies export rather than proving an empty release. Frozen source bytes are database-protected, while unreferenced Draft uploads remain mutable. Version-prefix object writes, numeric public asset identifiers and post-write repair comparison remain drift from the target immutable-candidate lifecycle. See the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle) for capability and proof limits. +- **Selected source coverage:** The construction branch includes the World owner's typed selected-release inventory, retained authenticated read and artifact-export checkpoint, which cover World-owned topology and derived-artifact requiredness only. Game Design's ordinary `ASSET_REFERENCE` source participates in actual fresh-Draft genesis, coordinator application, immutable commit snapshots and export-selection agreement. It is not total Game Design `COMPLETE`: the closed template-reference/config writer, branding records, exact requiredness authority across families and their owner-qualified readback remain absent. Ordinary assets remain `RESOURCE/REQUIRED`; branding has no implemented owner/consumer fallback policy, so no branding role is currently authoritatively `OPTIONAL`. The complete Game Design source/export gate remains closed until all families have exact selected-commit evidence. PostgreSQL and composed producer/consumer execution remain separate proof requirements; the unregistered authenticated World read is not yet retained in Game Design's durable publication operation. - **Current upload admission gap:** The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) are requirements, not current proof. `AssetController` accepts multipart uploads and `GameAssetServiceImpl` calls `MultipartFile.getBytes()` without size or quota enforcement; `AssetStoreProperties` has no matching limits. Upload admission and resource-safety readiness therefore remain incomplete and the route must not be treated as ready for external enablement. - **Hosted-content gate gap:** Current asset upload and publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The current Gateway's coarse `/api/design/**` route nevertheless forwards `/api/design/assets` (after `StripPrefix=2`) to the live `POST /assets` controller, whose Game Design boundary checks only privileged JWT/tenant access. Official-hosted asset-upload readiness is blocked until Gateway denies that route or the exact Account-owned gate is implemented and proved. - **Current lifecycle proof:** `version_asset_artifact` records the exported version-number prefix and manifest asset keys, but it does not yet freeze the target exact immutable object-key/digest set or implement the target global publication/purge fence. Repair writes those live prefix objects and the manifest before its exact release-bundle comparison, so pre-write verification is target-only. @@ -118,9 +119,13 @@ Required-artifact attestation contract: ### Complete selected-release asset inventory -Game Design separately owns the complete immutable asset manifest and requiredness/export attestation for one exact selected release. Its versioned closed source model must enumerate every applicable ordinary asset selection, normalized template/branding reference and supported launch-requiredness input, including explicitly proved empty families. The evidence binds the canonical tenant/version/commit, selected source identity and source revisions, and exact Account publication operation. Every exported asset additionally binds its immutable actual-byte digest and manifest entry. Unknown, unrepresentable, omitted or unbound source inputs deny completeness; nullable `version_asset.usage_type`, missing mappings, tenant-wide upload enumeration and mutable template JSON are not requiredness authority. +Game Design owns a closed, versioned source inventory and the immutable manifest/requiredness attestation for one exact selected release. The bounded source families are ordinary assets (`RESOURCE`), the closed template-config reference collections, and branding (`LOGO`, `FAVICON`, `THEME`). Each family and each branding role has an explicit presence/empty declaration; omission is not an empty value. Template references use the schema and owner-qualified identities defined by [Game Templates and Configuration Tools](./game-templates.md#closed-versioned-configuration-and-references-target-state). A family whose owner producer, canonical identity or exact readback is not implemented cannot be asserted empty or complete: publication fails closed until that source can be read and bound to the selected commit. -An empty `requiredManifestAssetKeys[]` is valid only with authenticated complete evidence that this selected release has zero required and exported assets. A frozen ordinary mapping snapshot alone does not establish that condition. Likewise, fresh command/policy genesis does not prove asset-source genesis. Any explicitly empty baseline must originate in the actual fresh source-creation transaction, remain bound to that source's subsequent writer/commit history and survive exact durable readback; retained or unqualified source records cannot receive an inferred empty baseline. +Every present entry declares `REQUIRED` or `OPTIONAL`, but author-supplied requiredness is not authoritative by itself. Ordinary `RESOURCE` is currently `REQUIRED`; absence of a mapping is not proof that the selected release has no required resource. Branding may be `OPTIONAL` only where the actual consumer has a defined fallback/absence behavior and the owner can prove that behavior for the role. Otherwise that role is denied rather than defaulted to optional. Launch/runtime-authoritative settings, including runtime flags and pinned scripts, are never optional presentation inputs. Unknown roles, unsupported settings, unqualified retained config, missing policy, unrepresentable input, and unsupported owner kinds deny completeness. + +The inventory evidence binds canonical tenant, base version, selected commit/source graph, source identity and revision, each explicit empty/present declaration, resolved owner reference, requiredness authority, and exact Account publication operation. Every present entry must resolve within that selected scope and be digest-attested against actual bytes plus its exact manifest entry. `version_asset.usage_type`, absent mappings, tenant-wide upload enumeration, or mutable template JSON alone are not requiredness or completeness authority. Numeric database IDs never substitute for logical owner identities. + +An empty `requiredManifestAssetKeys[]` is valid only with authenticated complete evidence that this selected release has zero required and exported assets across every applicable family. A frozen ordinary mapping snapshot alone does not establish that condition. Likewise, fresh command/policy genesis does not prove template/config or branding source genesis. Any explicitly empty family must originate in the actual fresh source-creation transaction, remain bound to that source's subsequent writer/commit history and survive exact durable readback; retained or unqualified source records cannot receive an inferred empty baseline. Game Design verifies the independent [World inventory](../world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) through common exact selection/source-graph and publication bindings. World cannot attest Game Design assets, and Game Design cannot replace World requiredness with its own missing manifest entry. The two records must not depend on circular mutual receipt issuance. If a release requires `world.navmesh` or `world.pathGraph`, the corresponding actual-byte artifact digest and manifest entry remain mandatory; an unavailable producer denies publication. This contract is not evidence that the complete source writer, inventory producer, immutable export or authenticated read has executed; those gaps remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 5fe7c4e939..9c0e698966 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -9,8 +9,7 @@ creators can quickly spin up new projects without starting from scratch. - **World Layout** – predefined regions and rooms loaded from the World Management Service. - **Starter Items and NPCs** – basic entity definitions for a new game. -- **Default Rulesets** – gameplay rules and runtime flags stored with the - template. +- **Owner bindings and launch inputs** – typed references to owner-managed content plus any explicitly supported settings. Runtime flags are launch-authoritative inputs, not non-authoritative presentation defaults. - **Administrator provisioning** – not stored in templates. Any future bootstrap flow must use Account-owned account, membership, and grant operations; Game Design does not create administrator authority. ## Implementation Status @@ -19,6 +18,7 @@ creators can quickly spin up new projects without starting from scratch. - Current script-patch resolution is not yet the target launch predicate: a full-version template/request can persist an arbitrary patch ID without proving a same-base `PUBLISHED` Game Design publication or Automation `READY` status. These are implementation gaps; the target validation and fail-before-instance-row rules remain below. - The target tenant-scoped `GetTemplateReferencePhase` cutover read is not implemented in the current proto or service. Current launch resolution checks only the per-template `templateReferencePhase` field (`ENFORCED`/`LEGACY`); it does not expose or consume the target durable tenant phase (`BACKFILLING`/`VALIDATED`/`ENFORCED`) required by launch and retirement tooling. - Normalized `game_template_*_ref` storage and its lifecycle/query authority are target-only. The current implementation persists `game_templates` and revision rows, but has no normalized reference tables, create/update derivation and atomic synchronization, one-time backfill/validation marker, or retirement/reference-query tooling; current lifecycle checks cannot rely on those rows and remain unimplemented or unproven. +- Closed selected-commit config production and reference readback are also absent. World authored-template IDs have the canonical UUID shape, but Game Design has no config writer/inventory that binds those references to an exact selected commit. Entity's current reference validator recognizes only `ITEM` and `NPC` and resolves a legacy positive-decimal key; it does not implement the canonical UUID read boundary or exact equippable-item semantics proof. Equipment-oriented input is an `ITEM` reference, not an independent equipment identity. Automation currently keys scripts by exact name plus raw patch string and base row, with no canonical UUID bridge for the selected base; Automation does not own a `RULESET` family. Game Logic's exact selected-source receipt is not yet retained/read back under the approved owner contract. No non-authoritative settings members are registered, and current runtime flags remain authoritative. Until Game Design durably retains owner-qualified selected-commit evidence for these sources, nonempty unsupported references and legacy opaque config deny publication; missing producers/readback do not prove empty families. - The current REST `POST /templates` path is named and documented as create-only, but a caller-supplied `id` is accepted by the DTO and makes the repository update the row by global `id` while also writing the supplied `tenantId`; the subsequent tenant-filtered readback can then hide the changed row. This is a current cross-tenant reassignment/overwrite gap, not tenant-scoped update safety. The target contract must reject `id` on create and make any future update and readback exact-tenant-qualified while keeping the stored tenant binding immutable; focused cross-tenant denial proof is absent. - Current template-remap-set APIs persist tenant-scoped `DRAFT`/`APPROVED` sets and entries. When `ResolveLaunchDescriptor` receives a `sourceVersionId` that differs from the resolved target, it selects exactly one `APPROVED` set for the source/target pair and persists and returns that set's `remapSetId`; it does not collect or verify owning-domain attestations. The target attestation predicate remains below. @@ -53,13 +53,21 @@ This guarded planning and application is target-state behavior. The current `Sav After a successful upgrade, the exact profile baseline advances to `N`, while retained local differences, explicit deletions, detachments, mappings, and resolution outcomes remain recorded for the next upgrade. This makes repeated upgrades deterministic without turning the profile into an authoring or runtime inheritance layer. -`GameTemplateDto` includes `id`, `tenantId`, `name`, an optional `description`, the raw `config` JSON and a `createdAt` timestamp. On a normal create with `id` omitted, the database assigns the ID when the template is saved. The current DTO/service path also accepts a caller-supplied `id` and can update a row by that global ID while changing its claimed tenant; this is the cross-tenant overwrite/reassignment gap recorded in [Implementation Status](#implementation-status), not supported create behavior. The target create contract rejects `id`, and future updates/readbacks must use exact tenant-qualified identity while keeping the stored tenant binding immutable. The `config` field uses a structured schema describing world layout, starter items, default rulesets, template references, and non-authoritative settings. +`GameTemplateDto` includes `id`, `tenantId`, `name`, an optional `description`, the raw `config` JSON and a `createdAt` timestamp. On a normal create with `id` omitted, the database assigns the ID when the template is saved. The current DTO/service path also accepts a caller-supplied `id` and can update a row by that global ID while changing its claimed tenant; this is the cross-tenant overwrite/reassignment gap recorded in [Implementation Status](#implementation-status), not supported create behavior. The target create contract rejects `id`, and future updates/readbacks must use exact tenant-qualified identity while keeping the stored tenant binding immutable. The `config` field follows the closed schema below; arbitrary JSON is not a supported compatibility form. -The `config` payload does not embed authoritative copies of world, entity, or script definitions. Instead it carries: +### Closed, Versioned Configuration and References (Target State) -- References to world templates (regions, rooms) using stable identifiers owned by the World Management Service and scoped by `(tenantId, versionId)`. -- References to starter items, NPCs, and equipment using stable identifiers owned by the Entity Management Service and scoped by `(tenantId, versionId)`. -- References to rulesets and scripts via identifiers defined by the Automation & Scripting Service. +`GameTemplateDto.config` is a closed, versioned wiring document, not an extensible JSON bag. Schema version 1 binds one `baseVersionId`, `world.regions[]`, `world.rooms[]`, `entity.items[]`, `entity.npcs[]`, a distinct `gameLogic` section, `automation.scripts[]`, `automation.scriptPatch` (explicitly present or absent), and `supportedSettings[]`. These are distinct owner families: Game Logic owns gameplay rules/configuration and selected-source evidence; Automation owns authored scripts, event bindings, and script patches. There is no `RULESET` collection or independent Entity `EQUIPMENT` identity. Each supported collection is explicit, including when empty; an omitted collection, unknown field or kind, unqualified reference, or retained opaque/unversioned config is invalid for selected-release completeness. A missing or malformed value is never interpreted as an empty collection. Existing retained config is not guessed, backfilled as empty, or reinterpreted at runtime; it remains denied for publication until an authorized versioned writer produces and durably reads back the closed representation. + +World `regions[]` entries carry `regionTemplateId`; `rooms[]` carry `roomTemplateId`. Entity `items[]` and `npcs[]` entries carry `entityTemplateId`, containing only the owner's canonical authored-template UUID. References resolve only inside exact `(tenantId, baseVersionId)`; the selected version is identity scope, not a translation key. World references distinguish `REGION` and `ROOM`; the current Entity reference validator/read path supports only `ITEM` and `NPC` through legacy numeric keys, not the canonical UUID producer/readback boundary. An equipment-oriented template input is the same canonical `ITEM` reference, accepted as equipment-capable only when Entity's owner read validates the item definition's equippable semantics. Equipment compatibility/slot data remains on the authored item/schema, while equipped runtime state is a separate first-class Entity binding that references the item. No separate equipment template ID, item alias, or loadout identity is introduced. The [Entity runtime/data contract](../entity-management-service/runtime-and-data.md) and [Item & Equipment Balancing owner](./item-equipment-balancing.md#target-equipment-schema-requirements) define these distinctions; equipment-related data and bindings still need complete owner proof/digest coverage. + +Automation's supported template sources are `SCRIPT` (including its owner-managed event bindings) and `SCRIPT_PATCH`; it has no `RULESET` identity. A script reference carries the current exact owner key `scriptId` (the persisted `name` string) under the template's selected tenant/base-version scope. The optional pinned `scriptPatchVersion` is the exact persisted nonblank patch string, paired with the same `baseVersionId`; it is not a UUID. These raw strings describe current owner keys, not proof of same-base publication or exact selected-version readback. The [Automation runtime/data contract](../automation-scripting-service/runtime-and-data.md) and [API contract](../automation-scripting-service/api-contracts.md) own script identity and patch semantics. Current code does not establish the canonical-UUID-to-owner-version binding or all required publication/readiness predicates; unsupported or unreadable entries deny selected-release completeness rather than implying an empty script family. + +Game Logic owns the version-scoped gameplay rules/configuration, not Automation. The separate `gameLogic` section may select only Game Logic's genuine owner-retained canonical configuration/source receipt for the exact tenant, `baseVersionId`, and selected commit, under the approved Game Logic producer contract. The receipt is the complete owner evidence, not a set of invented per-rule IDs, a `latest` lookup, or a substitute digest from Automation or Game Design. [Game Logic runtime/data](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) defines the owner boundary. The current producer/readback does not establish that receipt, so Game Logic input cannot yet be represented as complete or empty in a publishable config; its wire receipt shape must come from the actual owner contract rather than being fabricated here. + +`supportedSettings` is the explicitly non-authoritative settings subset accepted by this schema; it is closed and owner-defined, not arbitrary runtime configuration. No concrete non-authoritative setting members are currently registered. An explicitly authored empty collection is representable, but still requires the same authorized source-creation, selected-commit history and durable readback proof; missing settings storage or producers cannot supply it. `defaultRuntimeFlagsJson` and any other setting that changes launch/runtime behavior are authoritative inputs, not presentation settings, and must not be placed in this subset or marked optional. Adding a supported setting requires its owner, exact accepted member/value schema, and absence/fallback semantics to be defined before it can be authored. + +No owner reference is resolved by parsing retained config in runtime services. Game Design's authorized versioned writer validates the closed schema and owner references, persists normalized rows atomically with config, and supplies exact durable readback to publication. Every present reference must resolve and be digest-attested against the selected source graph; absence is valid only when the corresponding explicit collection is empty and its owner/source inventory proves that fact. Creator-facing launch-default note: @@ -67,30 +75,32 @@ Creator-facing launch-default note: - Caller overrides may fill unset launch fields, but they must not silently replace a template-pinned script patch. - If a creator wants a different default patch, the template itself must be updated and republished rather than relying on arbitrary per-launch override behavior. -Canonical schemas, identifiers, and versioned template rows remain in the owning domain services; `GameTemplateDto.config` is a configuration and wiring layer that composes these existing templates for bootstrapping new games. +Canonical schemas, identifiers, and versioned source rows remain in World Management, Entity Management, Game Logic, and Automation & Scripting; `GameTemplateDto.config` selects or wires those owner records for bootstrapping new games without copying their authoritative definitions. ### Normalized Reference Storage (Target State) The target design includes game templates in version retirement, auditing, and bulk migration workflows. Because `GameTemplateDto.config` is JSON, the implemented target must not rely on ad hoc JSON parsing to enforce invariants like “do not retire a version that is still referenced” or to perform controlled rewrites of references. -The target Game Design implementation stores normalized reference rows alongside the JSON config, derived and validated on every create/update: +The target Game Design implementation stores normalized reference rows alongside the JSON config, derived and validated on every authorized versioned write: - `game_template_version_ref` keyed by `(tenantId, gameTemplateId, versionId)` for the base design bundle referenced by the template. -- `game_template_world_ref` keyed by `(tenantId, gameTemplateId, versionId, regionTemplateId/roomTemplateId/...)` for any explicit world references present in the config. -- `game_template_entity_ref` keyed by `(tenantId, gameTemplateId, versionId, entityTemplateId/lootTableId/...)` for starter items/NPCs and related entity wiring. -- `game_template_script_ref` keyed by `(tenantId, gameTemplateId, versionId, scriptId/...)` for script bindings where templates need to pin or validate script identifiers. -- `game_template_script_patch_ref` keyed by `(tenantId, gameTemplateId, baseVersionId, scriptPatchVersion)` when a template pins a default `scriptPatchVersion` for a base version. +- `game_template_world_ref` keyed by `(tenantId, gameTemplateId, baseVersionId, kind, ownerTemplateId)` for explicit `REGION` and `ROOM` references. +- `game_template_entity_ref` keyed by `(tenantId, gameTemplateId, baseVersionId, kind, entityTemplateId)` for explicit `ITEM` and `NPC` references. Equipment-oriented configuration uses the same `ITEM` identity and requires owner-validated equippable semantics; runtime equipment bindings are separate Entity data. +- An Automation reference projection for `SCRIPT`/event-binding and `SCRIPT_PATCH` owner keys only; use Automation's exact identity contract rather than a generic or fabricated ID format. +- Game Logic's exact selected-source receipt retained under its owner-defined contract; do not define a per-rule identity, substitute another participant digest, or infer a receipt/table shape before that producer contract exists. +- `game_template_script_patch_ref` keyed by `(tenantId, gameTemplateId, baseVersionId, scriptPatchVersion)` when a template pins a default patch, with the declared base required to equal the one template base. +- `game_template_supported_setting` (or an equivalent closed projection) for registered non-authoritative settings only; no runtime-authoritative flags are admitted here. In the target state, administrative tooling and lifecycle checks (retirement eligibility, “list templates referencing version”, bulk migrations) operate on these normalized tables. The JSON config remains the user-facing payload and can be reconstructed or validated against normalized rows, but it is not the only queryable representation of dependencies. ### Single Base-Version Invariant -Launchable game templates must resolve to exactly one base design bundle version. +Launchable game templates must resolve to exactly one base design bundle version. The config's `baseVersionId` is a canonical UUID logical ID; current numeric version transports and database keys are implementation migration gaps and cannot be serialized into this config as aliases. The runtime architecture owns the complete resolved tuple and admission predicate. Game Design owns the normalized template-reference invariant that supplies the tuple's base-version input; this section does not define a second runtime release-selection policy. - `game_template_version_ref` is not advisory metadata; it identifies the single canonical `versionId` used to resolve the launch descriptor for that template. -- Every normalized world/entity/script reference row for the template must use that same `versionId`. +- Every normalized World/Entity/Automation reference and any selected Game Logic source receipt for the template must bind to that same `versionId`. - Mixed-version template composition is not allowed for launchable templates. A template update that would produce reference rows spanning multiple base `versionId` values must fail validation rather than relying on runtime resolution heuristics. - `game_template_script_patch_ref` is the only supported patch-level override and must reference the same `baseVersionId` as the template’s canonical `game_template_version_ref`. - If future workflows need cross-version migration planning, they must represent that as an explicit control-plane migration artifact, not as a launchable template with mixed-version dependencies. @@ -146,9 +156,9 @@ Ownership can be summarized as: ### Runtime Defaults -Game templates may optionally carry default runtime configuration alongside their structural wiring: +Game templates may carry versioned launch-authoritative inputs alongside their structural wiring: -- `GameTemplateDto.config` can include optional fields such as a default `scriptPatchVersion` or initial feature-flag presets that the Game Session Service uses when creating new `gameInstanceId` values from the template. +- A pinned `scriptPatchVersion` or runtime flag is launch-authoritative. It must be represented by a supported owner-bound reference/input in the closed schema and included in exact selected-commit validation; it is not a non-authoritative presentation setting and cannot be made optional by labeling it a default. - Templates must not implicitly promise survival of instance-scoped world state across replacement-instance upgrades. Any persistent carry-forward behavior must be defined by the runtime-state upgrade contract in `system-architecture-versioning-runtime.md`. - When these defaults are present, instance-creation flows must apply them explicitly; when they are absent, callers may provide the desired `scriptPatchVersion` and runtime flags at creation time. If neither the template nor the caller selects a script patch, resolution uses explicit null/semantic `UNPINNED` and creates no script work. Templates must not implicitly select “latest READY patch” or other moving targets without operator input. - If a template pins a default `scriptPatchVersion`, instance creation must validate that Automation & Scripting has marked that patch `READY` for the tenant and that the patch targets the template's canonical `baseVersionId` before pinning it for a running instance; otherwise instance creation fails with a clear error and no instance rows are created. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index df64a8b4f9..e19fe1020e 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -50,6 +50,8 @@ The exact-base, digest-bound, multi-owner commit contract is owned by [ADR 0129] Game Design owns the durable, creator-visible coordination record for every shared-Draft commit and isolated proposal. Each record binds the target `tenantId` and `versionId`, exact `baseCommitId`, stable request or proposal identity, canonical digest of the complete input, canonical revision order, the complete affected `(tenantId, versionId, owner, aggregateId, scopeId, epoch)` set, and durable per-owner application status. +The selected commit's template/config references and asset-source declarations are part of that exact input and its publish consequences, not runtime JSON interpretation. Their closed schema and requiredness are owned by [Game Templates](./game-templates.md#closed-versioned-configuration-and-references-target-state) and [Asset Storage](./asset-storage.md#complete-selected-release-asset-inventory). A commit is not publish-complete until those owners' exact selected-source records, owner reads and digest-attested exports are retained against the same tenant/version/commit and publication operation; a disjoint owner checkpoint or a missing source family cannot be treated as an empty selection. + - External AI/tool clients use ordinary scoped public creator APIs. A first-party agent uses the trusted scoped tool broker to build an isolated, reviewable Draft proposal; proposal acceptance creates or selects one exact commit application and does not grant a separate write or merge path. Both flows use the same exact tenant/version, base, complete-diff, affected-epoch, revision-order, and digest contract. - Reusing one request, proposal, or commit identity returns the recorded result only when the complete binding matches. Reusing it with changed or omitted tenant/version, input, base, revision order, affected set, or digest is rejected. - Each owner applies its portion through one storage-level atomic compare-and-swap transaction. That transaction checks every expected epoch required by the typed mutation for every fencing tuple in the complete subset owned by that service, while validating the complete affected set required by the typed mutation; it applies the local mutation, advances those epochs, and records the exact commit/digest result. A service-layer read followed by an unconditional update is not sufficient. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index e2a197accf..6a12f7b5fd 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -21,6 +21,7 @@ This API contract is target-state canonical; implementation coverage is partial - `ApplyRoomAmbientStatePatch` – applies a typed ambient fact patch to the target runtime scope under expected epoch/version preconditions and an operation/aggregate/request-digest-bound guard derived from the root `EffectId`; matching replay returns the durable prior result and a conflicting identity or payload fails closed. - `GetDraftDesignDigest` – returns the publish-gating digest for Draft world templates using the typed scope request `GetDraftDesignDigestRequest { tenantId, scope: oneof { versionId, scriptPatchVersion } }`. World Management supports `versionId` scope only and must return `UNSUPPORTED_SCOPE` for `scriptPatchVersion`. - `BeginVersionPublicationFreeze` – starts or exactly replays the durable WMS owner freeze for one `(tenantId, versionId)` publication request and returns the request/fence/epoch/digest checkpoint acknowledgement defined below. A closed standalone proto, strict client and owner-resolving receiver are construction components only; runtime registration and the complete producer handoff remain unavailable. +- `ReadSelectedPublicationArtifactInventory` – reads only the exact immutable inventory for the supplied original freeze request and committed acknowledgement. The construction adapter authenticates same-namespace Game Design before parsing, checks retained freeze/Account bindings and returns the canonical public projection plus its distinct digest. It does not begin a freeze, recapture sources, or return private numeric owner keys. Runtime registration and Game Design durable-operation consumption remain unavailable; [World runtime/data](runtime-and-data.md#complete-selected-release-artifact-inventory) owns the inventory contract. - `CompleteVersionPublication` – **Target state:** exactly replays or terminalizes the same WMS freeze with a `PUBLISHED` or `ABORTED` outcome and matching bundle/digest evidence. Unregistered terminal composition and storage exist, but a registered completion RPC and genuine composed terminal handoff remain unavailable. - `ValidateWorldUpgradeMappings` – validates world-owned durable references and approved remap sets for replacement-instance cutover to a target `(tenantId, versionId)`. - `PrepareWorldInstance` – creates or reuses the canonical `PREPARING` world lifecycle row for a resolved launch descriptor, validates release-bundle and `versionStateEpoch` proof against Game Design, and materializes first-cut instance topology rows without admitting gameplay yet. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index a7c06d11ae..9aa1c4800e 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -195,6 +195,8 @@ In the initial slice, exported world artifacts such as navmesh/path-graph bundle World owns a typed, authenticated, immutable `COMPLETE` inventory for the exact selected, retained `APPLIED` graph. It binds the canonical tenant/version/commit, original source and application identities, complete affected scopes and applied epochs, exact Account publication-order identity and fence, topology result and graph digest, and the publication freeze/checkpoint. World captures and durably reads back that inventory under the same owner lock as its qualified first freeze; a caller-supplied inventory or later current-state sample cannot replace the selected graph. Exact retries preserve the original inventory rather than reclassifying mutable source state. +The authenticated owner read takes the exact original freeze request and committed acknowledgement as lookup identity, verifies them against the retained attempt and original Account order, and returns only the closed canonical public inventory and its public-view digest. Its same-namespace Game Design workload check precedes parsing and storage access; end-user context and ambient owner transactions are rejected. Private numeric owner/source keys and raw Account binding bytes remain outside the public inventory. Public region-generator and spawn-binding inputs use unique canonical UUID-string order, independently of the retained private envelope's source order. This projection never rewrites private history. Byte/digest validation alone does not authenticate the producer; the client must verify the concrete World workload identity over mTLS. + The inventory identifies a versioned, closed source model and enumerates all six current topology families from the digest manifest, including explicit zero counts. Its requiredness evaluation covers the complete typed topology, region generator type/parameters, generation-rule name/scope/value, and typed spawn bindings. Unknown schemas, fields, families, omitted requiredness inputs, or unrepresentable generation semantics deny `COMPLETE`; missing producer rows or runtime consumers never establish that an artifact is unnecessary. The direct-authored room/exit model uses its persisted directed edges and does not require a separate generated navigation bundle; typed room-bound spawn references alone do not change that rule. Opaque generation inputs cannot inherit this classification without a defined, proved requiredness interpretation. The complete derived-family enumeration includes `NAVMESH` and `PATH_GRAPH`, each with an explicit decision bound to those source inputs. If the selected source requires either family, publication requires the actual finalized producer record and byte digest under the [Game Design asset handoff](../game-design-service/asset-storage.md#complete-selected-release-asset-inventory); an absent producer denies that release, rather than changing its requiredness or omitting the family. A supported release must not be relabeled empty or unsupported merely to avoid producing its required artifacts. 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 e72b2bc6c1..ff6f9fe906 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 @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The selected-release inventory contract is now explicit in the [World owner](../../architecture/microservices/world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) and [Game Design asset owner](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). World source-complete requiredness does not prove Game Design asset completeness. Game Design's actual synchronized source repository currently covers commands and realm policy only; V37's ordinary mappings and nullable usage classifier do not enumerate selected template/branding references or launch requiredness, and mutable template configuration has no exact selected-commit source binding. A complete asset-source writer, fenced commit history, immutable manifest/export producer and authenticated readback remain required. Fresh command/policy genesis, absent mappings or absent consumers cannot supply an empty asset baseline. All genuine publication and runtime activation gates remain open obligations, not completed handoffs. +The selected-release inventory contract is explicit in the [World owner](../../architecture/microservices/world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) and [Game Design asset owner](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). The construction branch includes the World selected-graph inventory, retained authenticated read and derived-artifact export checkpoint; these attest World source only and do not establish Game Design source completeness, a release bundle or activation. Game Design's synchronized source repository covers commands, realm policy and ordinary `ASSET_REFERENCE` source history, with actual fresh-Version genesis, coordinator application, immutable selected-commit snapshots and export agreement. The ordinary source has focused unit and PostgreSQL test definitions, but local PostgreSQL execution and composed producer/consumer proof remain required. V37's mappings and nullable usage classifier do not enumerate selected template/branding references or launch requiredness, and mutable template configuration has no exact selected-commit source binding. The canonical closed config schema is documented in [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state), but its versioned writer, normalized reference rows, owner-resolved readback and integration into the selected source inventory remain unimplemented. The real authorized source-writing ingress and retention of World inventory in Game Design's durable publication operation are also incomplete. Complete source coverage still requires the template/config and branding families, exact requiredness authority, fenced commit history and immutable manifest/export proof. Fresh command/policy/ordinary genesis, absent mappings or absent consumers cannot supply an empty baseline for other families. All genuine publication and runtime activation gates remain open obligations, not completed handoffs. Published-head `39b800bdfe07cf94028fd4a175f79f42eb51c8e7` [Validation run 37853634338](https://github.com/benhook1013/FireMUD/actions/runs/37853634338) executed 245 Account, 81 Game Design and 206 World integration cases, with zero errors or skips. World passed in full. Game Design's selected-publication composition and four of five asset cases passed; the remaining asset fixture attempted a forbidden frozen-source update and correctly encountered the immutable-source trigger. The corrected fixture now requires SQLSTATE `23514`, unchanged source bytes and exact snapshot/retry readback; corrected-head PostgreSQL execution remains required. Account's serialization-specific retry and all nine isolated WAL cases passed. Its sole failure was the independent receipt-confirmation case at V90's conservative global-WAL coverage check: insert fence `0/4C2F760` exceeded flush `0/4C2F720`. This is still an open durability limitation, not production adoption of the isolated WAL investigation. Owner jobs used merge `a7d44052a8b69826f9673392da2a5a6bc973a7ad`, tree `aca615119c487f744e4f787a3042df993a8dbf65`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head; intended-parent alignment remains open. Security, CodeQL, License, Kustomize, preview planning and dependency submission passed. Optional downstream preview steps skipped, so this is not full-stack Smoke or proof of the later World inventory/export corrections. @@ -239,6 +239,7 @@ Game Design owns revision history, commits, version state, and publish orchestra - The broader authoring and publication domain remains in progress. Participant digests still need actual target-commit provenance and coordinated schema adoption, and the release bundle still needs canonical target-commit, manifest-schema, and applicable artifact-digest fields. Future domain-template families must join the version-scoped digest gate; future release-bundle consumers must apply missing-attestation, unsupported-schema, and exact-asset-proof hard failures. - Publish/version synchronization remains incomplete across downstream domain-owned schemas. Game Design owns revision history, version metadata, and publish orchestration, while Entity Management and World Management retain authoritative entity and world rows; the current participant observations and first World mutation handoff do not yet establish actual same-commit convergence or cover every future editor caller or template family. - Asset lifecycle follow-through remains incomplete. The current implementation lacks the version-scoped asset mapping/authoring path and corresponding publication/export guard; purge and publication recovery also lack complete durable operation, CAS, and exact readback proof. The canonical lifecycle and operation contracts are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); this tracker records the status and proof gaps without repeating those normative details. +- Closed config/reference production remains a separate gap from the committed World source checkpoint: World and Entity authored-template logical IDs use canonical UUID strings, but Game Design has no exact selected-commit reference writer/readback. Entity's current validator/read path covers only `ITEM`/`NPC` through a positive-decimal storage key, not the canonical UUID readback or owner proof that an `ITEM` is equippable; equipment-oriented input is that `ITEM` identity, while runtime equipment binding remains separate. Automation owns `SCRIPT`, event-binding, and `SCRIPT_PATCH`, using current exact script name/raw patch keys without a canonical base-UUID bridge; it has no `RULESET` family. Game Logic's exact owner-retained configuration/source receipt for the selected tenant/base/commit is not currently produced/read back, so it cannot be replaced by per-rule IDs, `latest`, or another participant digest. No non-authoritative settings member is registered; runtime flags remain launch-authoritative. These are producer/readback gaps, not evidence that any unavailable source family is empty. - Launch/activation follow-through includes broader cutover and retirement consumers, later runtime-state families, exact Entity target-template validation once version-scoped entity-template tables exist, and replacement of remaining placeholder runtime topology/state rows. - Normalized-template cutover phase is target-only: no tenant-scoped `GetTemplateReferencePhase` RPC, durable phase authority, or `BACKFILLING`/`VALIDATED`/`ENFORCED` consumer contract exists in the current slice; live launch checks only the per-template `ENFORCED`/`LEGACY` field. The target API and fail-before-launch behavior remain unimplemented and unproved. - StartSession still needs to validate same-base `PUBLISHED` patch identity and join Automation's tenant-scoped script-patch status, failing closed unless the pinned patch is runtime `READY`; current descriptor validation proves neither publication identity nor readiness. diff --git a/protos/world-management/v1/world_selected_draft_publication_freeze_service.proto b/protos/world-management/v1/world_selected_draft_publication_freeze_service.proto index 69a0297cfc..d5b0f143ce 100644 --- a/protos/world-management/v1/world_selected_draft_publication_freeze_service.proto +++ b/protos/world-management/v1/world_selected_draft_publication_freeze_service.proto @@ -11,6 +11,9 @@ option java_multiple_files = true; service WorldSelectedDraftPublicationFreezeService { rpc BeginVersionPublicationFreeze(BeginVersionPublicationFreezeRequest) returns (BeginVersionPublicationFreezeResponse); + rpc ReadSelectedPublicationArtifactInventory( + ReadSelectedPublicationArtifactInventoryRequest) + returns (ReadSelectedPublicationArtifactInventoryResponse); } enum WorldSelectedDraftPublicationFreezePhase { @@ -52,3 +55,18 @@ message BeginVersionPublicationFreezeResponse { // publication authority. The later selector read validates it against that same APPLIED result. string world_intake_request_id = 15; } + +message ReadSelectedPublicationArtifactInventoryRequest { + int32 schema_version = 1; + // The exact original freeze input and committed acknowledgement are lookup identity only. + BeginVersionPublicationFreezeRequest freeze_request = 2; + BeginVersionPublicationFreezeResponse freeze_acknowledgement = 3; +} + +message ReadSelectedPublicationArtifactInventoryResponse { + int32 schema_version = 1; + // Canonical WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence bytes. This is + // the public projection only; the private owner envelope and numeric owner keys never egress. + bytes canonical_public_inventory = 2; + string public_inventory_digest = 3; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClient.java new file mode 100644 index 0000000000..a73379e08a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClient.java @@ -0,0 +1,160 @@ +package net.firedevops.firemud.common.publication; + +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.WorldSelectedDraftPublicationFreezeServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for one exact immutable selected-publication inventory read. */ +public final class WorldSelectedPublicationArtifactInventoryClient + extends AbstractReloadingBlockingGrpcClient< + WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldSelectedPublicationArtifactInventoryClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldSelectedPublicationArtifactInventoryClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World selected-publication inventory client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World selected-publication inventory stub unavailable"); + } + initialized = true; + } + + /** Returns only the canonical public inventory bound to the exact acknowledged freeze. */ + public WorldSelectedPublicationArtifactInventoryEvidence read( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World selected-publication inventory read requires no ambient owner transaction"); + } + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + if (!workloadNamespace.equals(freezeEvidence.request().targetNamespace())) { + throw new IllegalArgumentException( + "World selected-publication inventory read must use the configured namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedPublicationArtifactInventory( + WorldSelectedPublicationArtifactInventoryGrpcCodec.toRequest(freezeEvidence)); + try { + return WorldSelectedPublicationArtifactInventoryGrpcCodec.fromResponse( + freezeEvidence, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid selected-publication inventory evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldSelectedDraftPublicationFreezeServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World selected-publication inventory client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "World selected-publication inventory read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World selected-publication inventory read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World selected-publication inventory read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World selected-publication inventory " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World selected-publication inventory " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java new file mode 100644 index 0000000000..cf26895281 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java @@ -0,0 +1,595 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Request; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** + * Typed World public inventory bound to one exact retained selected-publication freeze. + * + *

This value alone does not authenticate its producer; the authenticated mTLS caller and + * verified World server identity path supply that boundary. + */ +public final class WorldSelectedPublicationArtifactInventoryEvidence { + public static final String SCHEMA = "world-selected-publication-artifact-inventory/v1"; + public static final String SOURCE_MODEL = "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1"; + public static final int SCHEMA_VERSION = 1; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern HEX_SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final List FAMILY_ORDER = + List.of( + "REGION", "ZONE", "ROOM", "ROOM_EXIT", "GENERATION_RULE", "WORLD_ENTITY_SPAWN_BINDING"); + private static final List REGION_FIELDS = + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"); + private static final List ZONE_FIELDS = List.of("id", "regionId", "name"); + private static final List ROOM_FIELDS = + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"); + private static final List ROOM_EXIT_FIELDS = + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"); + private static final List GENERATION_RULE_FIELDS = + List.of("id", "name", "scopeType", "scopeId", "value"); + private static final List SPAWN_BINDING_FIELDS = + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"); + private static final List ARTIFACT_DECISIONS = + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH")); + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + + private final WorldSelectedDraftPublicationFreezeEvidence freezeEvidence; + private final PublicEvidence publicEvidence; + private final byte[] canonicalBytes; + private final String digest; + + private WorldSelectedPublicationArtifactInventoryEvidence( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, PublicEvidence publicEvidence) { + this.freezeEvidence = Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + this.publicEvidence = Objects.requireNonNull(publicEvidence, "publicEvidence"); + requireFreezeBinding(freezeEvidence, publicEvidence); + this.canonicalBytes = publicEvidence.canonicalBytes(); + this.digest = sha256(canonicalBytes); + } + + /** Creates evidence from World’s typed public projection and validates every public binding. */ + public static WorldSelectedPublicationArtifactInventoryEvidence fromPublicEvidence( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, PublicEvidence publicEvidence) { + return new WorldSelectedPublicationArtifactInventoryEvidence(freezeEvidence, publicEvidence); + } + + /** + * Strictly parses canonical public evidence, validates its digest, then binds it to the freeze. + */ + public static WorldSelectedPublicationArtifactInventoryEvidence fromCanonicalBytes( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + byte[] canonicalBytes, + String expectedDigest) { + Objects.requireNonNull(canonicalBytes, "canonicalBytes"); + requireDigest(expectedDigest, "public inventory digest"); + if (!sha256(canonicalBytes).equals(expectedDigest)) { + throw new IllegalArgumentException("World public inventory digest does not match its bytes"); + } + final PublicEvidence evidence; + try { + evidence = JSON.readValue(canonicalBytes, PublicEvidence.class); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World public inventory is not a closed typed value", invalid); + } + if (evidence == null || !Arrays.equals(canonicalBytes, evidence.canonicalBytes())) { + throw new IllegalArgumentException("World public inventory is not canonical JSON"); + } + return new WorldSelectedPublicationArtifactInventoryEvidence(freezeEvidence, evidence); + } + + public WorldSelectedDraftPublicationFreezeEvidence freezeEvidence() { + return freezeEvidence; + } + + public PublicEvidence publicEvidence() { + return publicEvidence; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + private static void requireFreezeBinding( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, PublicEvidence evidence) { + Request request = freezeEvidence.request(); + Acknowledgement acknowledgement = freezeEvidence.acknowledgement(); + AccountPublicationAuthorizationBinding account = request.accountBinding(); + var selection = account.input().selection(); + var intent = selection.intent(); + var selectedCommit = selection.selectedCommit(); + var owner = evidence.ownerScope(); + var application = evidence.selectedApplication(); + var accountOrder = evidence.accountOrder(); + var freeze = evidence.freeze(); + var checkpoint = evidence.checkpoint(); + var sourceModel = evidence.sourceModel(); + String expectedWorkflow = + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity(); + + if (!owner.targetNamespace().equals(request.targetNamespace()) + || !owner.canonicalTenantId().equals(request.canonicalTenantId()) + || !owner.canonicalVersionId().equals(request.canonicalVersionId()) + || !owner.intakeRequestId().equals(acknowledgement.intakeRequestId()) + || !application.applicationRequestId().equals(selectedCommit.requestId()) + || !application.appliedCommitId().equals(selectedCommit.commitId().toString()) + || !application.bindingDigest().equals(selectedCommit.digest()) + || !accountOrder.operationId().equals(account.operationId()) + || !accountOrder.fenceId().equals(account.fenceId()) + || !accountOrder.actorAccountId().equals(account.input().actorAccountId()) + || !accountOrder.publicationRequestId().equals(intent.publishRequestId()) + || !accountOrder.selectionDigest().equals(selection.digest()) + || !accountOrder.selectedCommitId().equals(selectedCommit.commitId().toString()) + || !accountOrder.bindingDigest().equals(sha256(account.canonicalBytes())) + || !freeze.publicationFence().equals(acknowledgement.publicationFence()) + || !freeze.publicationRequestId().equals(request.publicationRequestId()) + || !freeze.requestDigest().equals(request.requestDigest()) + || !freeze.versionStateEpoch().equals(Long.toString(acknowledgement.versionStateEpoch())) + || !freeze.publishWorkflowId().equals(expectedWorkflow) + || !checkpoint.appliedCommitId().equals(acknowledgement.appliedCommitId()) + || !checkpoint.contentDigest().equals(acknowledgement.contentDigest()) + || checkpoint.digestSchemaVersion() != acknowledgement.digestSchemaVersion() + || !appliedEpochsMatch(selectedCommit, sourceModel.appliedEpochs())) { + throw new IllegalArgumentException( + "World public inventory differs from exact selected Account order or freeze checkpoint"); + } + } + + private static boolean appliedEpochsMatch( + DraftCommitBinding selectedCommit, List actual) { + List expected = + selectedCommit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + return !expected.isEmpty() && expected.equals(actual); + } + + private static String sha256(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be canonical lowercase SHA-256"); + } + } + + private static void requireUuid(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static UUID canonicalUuid(String value, String label) { + if (value == null) throw new IllegalArgumentException(label + " is required"); + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static long parsePositiveCanonicalLong(String value, String label) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException(label + " must be a canonical positive decimal string"); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " is not a canonical positive decimal string"); + } + return parsed; + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(label + " is outside the supported long range", invalid); + } + } + + private static boolean isText(String value) { + return value != null && !value.isBlank() && value.equals(value.strip()); + } + + /** Typed canonical public inventory. This schema intentionally has no private World row keys. */ + public record PublicEvidence( + String schema, + int schemaVersion, + String completeness, + PublicOwnerScope ownerScope, + SelectedApplication selectedApplication, + PublicAccountOrder accountOrder, + Freeze freeze, + Checkpoint checkpoint, + SourceModel sourceModel, + List artifactDecisions) { + public PublicEvidence { + Objects.requireNonNull(schema, "schema"); + Objects.requireNonNull(completeness, "completeness"); + Objects.requireNonNull(ownerScope, "ownerScope"); + Objects.requireNonNull(selectedApplication, "selectedApplication"); + Objects.requireNonNull(accountOrder, "accountOrder"); + Objects.requireNonNull(freeze, "freeze"); + Objects.requireNonNull(checkpoint, "checkpoint"); + Objects.requireNonNull(sourceModel, "sourceModel"); + artifactDecisions = + List.copyOf(Objects.requireNonNull(artifactDecisions, "artifactDecisions")); + requireSupportedProfile( + schema, + schemaVersion, + completeness, + ownerScope, + selectedApplication, + accountOrder, + freeze, + checkpoint, + sourceModel, + artifactDecisions); + } + + public byte[] canonicalBytes() { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(this)); + } catch (IOException failure) { + throw new IllegalStateException("World public inventory could not be encoded", failure); + } + } + + public String digest() { + return sha256(canonicalBytes()); + } + + private static void requireSupportedProfile( + String schema, + int schemaVersion, + String completeness, + PublicOwnerScope owner, + SelectedApplication application, + PublicAccountOrder account, + Freeze freeze, + Checkpoint checkpoint, + SourceModel model, + List artifactDecisions) { + if (!SCHEMA.equals(schema) + || schemaVersion != SCHEMA_VERSION + || !"COMPLETE".equals(completeness) + || artifactDecisions.size() != ARTIFACT_DECISIONS.size() + || !artifactDecisions.equals(ARTIFACT_DECISIONS)) { + throw new IllegalArgumentException("Unsupported or incomplete World inventory profile"); + } + requireUuid(owner.canonicalTenantId(), "canonicalTenantId"); + requireUuid(owner.canonicalVersionId(), "canonicalVersionId"); + requireUuid(owner.versionIdentityOperationId(), "versionIdentityOperationId"); + requireUuid(owner.intakeRequestId(), "intakeRequestId"); + requireUuid(owner.intakeOperationId(), "intakeOperationId"); + requireUuid(owner.sourceOperationId(), "sourceOperationId"); + if (!GrpcPeerIdentity.isValidNamespace(owner.targetNamespace()) + || !isText(owner.intakeRequestDigest()) + || !isText(owner.sourceEvidenceDigest()) + || !isText(owner.intakeReceiptDigest())) { + throw new IllegalArgumentException("World public inventory owner scope is incomplete"); + } + requireDigest(owner.intakeRequestDigest(), "intakeRequestDigest"); + requireDigest(owner.sourceEvidenceDigest(), "sourceEvidenceDigest"); + requireDigest(owner.intakeReceiptDigest(), "intakeReceiptDigest"); + + requireUuid(application.applicationOperationId(), "applicationOperationId"); + requireUuid(application.applicationRequestId(), "applicationRequestId"); + canonicalUuid(application.appliedCommitId(), "application.appliedCommitId"); + requireDigest(application.bindingDigest(), "application.bindingDigest"); + requireDigest(application.appliedResultDigest(), "application.appliedResultDigest"); + + requireUuid(account.operationId(), "account.operationId"); + requireUuid(account.fenceId(), "account.fenceId"); + requireUuid(account.actorAccountId(), "account.actorAccountId"); + if (!isText(account.publicationRequestId())) { + throw new IllegalArgumentException("World public Account order is incomplete"); + } + requireDigest(account.selectionDigest(), "account.selectionDigest"); + canonicalUuid(account.selectedCommitId(), "account.selectedCommitId"); + requireDigest(account.bindingDigest(), "account.bindingDigest"); + + requireUuid(freeze.publicationFence(), "publicationFence"); + if (!isText(freeze.publicationRequestId()) || !isText(freeze.publishWorkflowId())) { + throw new IllegalArgumentException("World public freeze binding is incomplete"); + } + if (freeze.requestDigest() == null || !HEX_SHA256.matcher(freeze.requestDigest()).matches()) { + throw new IllegalArgumentException("World freeze request digest must be lowercase SHA-256"); + } + parsePositiveCanonicalLong(freeze.versionStateEpoch(), "versionStateEpoch"); + + canonicalUuid(checkpoint.appliedCommitId(), "checkpoint.appliedCommitId"); + if (checkpoint.contentDigest() == null + || !HEX_SHA256.matcher(checkpoint.contentDigest()).matches() + || checkpoint.digestSchemaVersion() <= 0) { + throw new IllegalArgumentException("World checkpoint is incomplete or malformed"); + } + + if (!SOURCE_MODEL.equals(model.modelId()) + || model.graphSchemaVersion() != 2 + || !isSha256(model.graphDigest()) + || !isSha256(model.topologyResultDigest()) + || model.generationRuleInputCount() != 0 + || !model.generationRuleFields().equals(GENERATION_RULE_FIELDS) + || !model.regionFields().equals(REGION_FIELDS) + || !model.zoneFields().equals(ZONE_FIELDS) + || !model.roomFields().equals(ROOM_FIELDS) + || !model.roomExitFields().equals(ROOM_EXIT_FIELDS) + || !model.spawnBindingFields().equals(SPAWN_BINDING_FIELDS) + || model.familyCounts().size() != FAMILY_ORDER.size()) { + throw new IllegalArgumentException("World source model is unsupported or incomplete"); + } + for (int index = 0; index < FAMILY_ORDER.size(); index++) { + FamilyCount count = model.familyCounts().get(index); + if (!FAMILY_ORDER.get(index).equals(count.family()) || count.rowCount() < 0) { + throw new IllegalArgumentException("World source family enumeration is incomplete"); + } + } + int roomCount = familyCount(model.familyCounts(), "ROOM"); + int regionCount = familyCount(model.familyCounts(), "REGION"); + int generationRuleCount = familyCount(model.familyCounts(), "GENERATION_RULE"); + int spawnCount = familyCount(model.familyCounts(), "WORLD_ENTITY_SPAWN_BINDING"); + if (roomCount < 1 + || generationRuleCount != 0 + || model.regionGeneratorInputs().size() != regionCount + || model.generationRuleInputCount() != generationRuleCount + || model.spawnBindingCount() != spawnCount + || model.spawnBindingInputs().size() != spawnCount + || model.appliedEpochs().isEmpty()) { + throw new IllegalArgumentException( + "World source-model counts do not establish completeness"); + } + for (RegionGeneratorInput region : model.regionGeneratorInputs()) { + requireUuid(region.regionTemplateId(), "regionTemplateId"); + if (region.generatorType() == null || region.generatorParams() == null) { + throw new IllegalArgumentException("World region generator inputs must be explicit"); + } + if (!region.generatorType().isEmpty() || !region.generatorParams().isEmpty()) { + throw new IllegalArgumentException( + "Opaque World region generator inputs have no supported requiredness interpretation"); + } + } + requireCanonicalRegionOrder(model.regionGeneratorInputs()); + UUID tenantId = owner.canonicalTenantId(); + UUID versionId = owner.canonicalVersionId(); + for (SpawnBindingInput spawn : model.spawnBindingInputs()) { + requireUuid(spawn.bindingTemplateId(), "spawn.bindingTemplateId"); + requireUuid(spawn.roomTemplateId(), "spawn.roomTemplateId"); + requireUuid(spawn.entityTemplateId(), "spawn.entityTemplateId"); + if (!"ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID".equals(spawn.entityReferenceKind()) + || !tenantId.equals(spawn.entityTenantId()) + || !versionId.equals(spawn.entityVersionId()) + || !("ITEM".equals(spawn.entityTemplateType()) + || "NPC".equals(spawn.entityTemplateType())) + || spawn.spawnCount() <= 0 + || spawn.respawnDelaySeconds() < 0) { + throw new IllegalArgumentException( + "World spawn binding is outside the closed supported profile"); + } + } + requireCanonicalSpawnOrder(model.spawnBindingInputs()); + } + + private static void requireCanonicalRegionOrder(List inputs) { + Set seen = new HashSet<>(); + String previous = null; + for (RegionGeneratorInput input : inputs) { + String key = input.regionTemplateId().toString(); + if (!seen.add(input.regionTemplateId()) + || (previous != null && previous.compareTo(key) >= 0)) { + throw new IllegalArgumentException( + "World region generator inputs must have unique canonical UUID order"); + } + previous = key; + } + } + + private static void requireCanonicalSpawnOrder(List inputs) { + Set seen = new HashSet<>(); + String previous = null; + for (SpawnBindingInput input : inputs) { + String key = input.bindingTemplateId().toString(); + if (!seen.add(input.bindingTemplateId()) + || (previous != null && previous.compareTo(key) >= 0)) { + throw new IllegalArgumentException( + "World spawn binding inputs must have unique canonical UUID order"); + } + previous = key; + } + } + + private static int familyCount(List counts, String family) { + return counts.stream() + .filter(count -> family.equals(count.family())) + .mapToInt(FamilyCount::rowCount) + .findFirst() + .orElseThrow( + () -> new IllegalArgumentException("World inventory omitted family " + family)); + } + + private static boolean isSha256(String value) { + return value != null && SHA256.matcher(value).matches(); + } + } + + public record FamilyCount(String family, int rowCount) { + public FamilyCount { + Objects.requireNonNull(family, "family"); + if (rowCount < 0) throw new IllegalArgumentException("rowCount must be nonnegative"); + } + } + + public record RegionGeneratorInput( + UUID regionTemplateId, String generatorType, String generatorParams) {} + + public record SpawnBindingInput( + UUID bindingTemplateId, + UUID roomTemplateId, + String entityTemplateType, + String entityReferenceKind, + UUID entityTenantId, + UUID entityVersionId, + UUID entityTemplateId, + int spawnCount, + int respawnDelaySeconds) {} + + public record SelectedApplication( + UUID applicationOperationId, + UUID applicationRequestId, + String appliedCommitId, + String bindingDigest, + String appliedResultDigest) {} + + public record PublicAccountOrder( + UUID operationId, + UUID fenceId, + UUID actorAccountId, + String publicationRequestId, + String selectionDigest, + String selectedCommitId, + String bindingDigest) {} + + /** Public World scope; private local tenant/version keys and source-intake rows are omitted. */ + public record PublicOwnerScope( + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID versionIdentityOperationId, + UUID intakeRequestId, + UUID intakeOperationId, + String intakeRequestDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String intakeReceiptDigest) {} + + public record Freeze( + UUID publicationFence, + String publicationRequestId, + String requestDigest, + String versionStateEpoch, + String publishWorkflowId) {} + + public record Checkpoint(String appliedCommitId, String contentDigest, int digestSchemaVersion) {} + + public record ArtifactDecision(String artifactKind, String state, String rule) { + public ArtifactDecision { + Objects.requireNonNull(artifactKind, "artifactKind"); + Objects.requireNonNull(state, "state"); + Objects.requireNonNull(rule, "rule"); + } + } + + public record SourceModel( + String modelId, + int graphSchemaVersion, + String graphDigest, + String topologyResultDigest, + List familyCounts, + List regionGeneratorInputs, + List generationRuleFields, + List regionFields, + List zoneFields, + List roomFields, + List roomExitFields, + List spawnBindingFields, + List spawnBindingInputs, + int generationRuleInputCount, + int spawnBindingCount, + List appliedEpochs) { + public SourceModel { + familyCounts = List.copyOf(Objects.requireNonNull(familyCounts, "familyCounts")); + regionGeneratorInputs = + List.copyOf(Objects.requireNonNull(regionGeneratorInputs, "regionGeneratorInputs")); + generationRuleFields = + List.copyOf(Objects.requireNonNull(generationRuleFields, "generationRuleFields")); + regionFields = List.copyOf(Objects.requireNonNull(regionFields, "regionFields")); + zoneFields = List.copyOf(Objects.requireNonNull(zoneFields, "zoneFields")); + roomFields = List.copyOf(Objects.requireNonNull(roomFields, "roomFields")); + roomExitFields = List.copyOf(Objects.requireNonNull(roomExitFields, "roomExitFields")); + spawnBindingFields = + List.copyOf(Objects.requireNonNull(spawnBindingFields, "spawnBindingFields")); + spawnBindingInputs = + List.copyOf(Objects.requireNonNull(spawnBindingInputs, "spawnBindingInputs")); + appliedEpochs = List.copyOf(Objects.requireNonNull(appliedEpochs, "appliedEpochs")); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodec.java new file mode 100644 index 0000000000..d9d3c1e3b1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodec.java @@ -0,0 +1,77 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedPublicationArtifactInventoryRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedPublicationArtifactInventoryResponse; + +/** Closed wire mapping for the authenticated retained World inventory read. */ +public final class WorldSelectedPublicationArtifactInventoryGrpcCodec { + private static final int SCHEMA_VERSION = 1; + + private WorldSelectedPublicationArtifactInventoryGrpcCodec() {} + + public static ReadSelectedPublicationArtifactInventoryRequest toRequest( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + return ReadSelectedPublicationArtifactInventoryRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setFreezeRequest( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freezeEvidence.request())) + .setFreezeAcknowledgement( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse( + freezeEvidence.acknowledgement())) + .build(); + } + + /** Decodes the exact existing freeze request+acknowledgement as immutable lookup identity. */ + public static WorldSelectedDraftPublicationFreezeEvidence fromRequest( + ReadSelectedPublicationArtifactInventoryRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadSelectedPublicationArtifactInventoryRequest"); + if (request.getSchemaVersion() != SCHEMA_VERSION + || !request.hasFreezeRequest() + || !request.hasFreezeAcknowledgement()) { + throw new IllegalArgumentException("Complete World freeze lookup identity is required"); + } + var freezeRequest = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(request.getFreezeRequest()); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, request.getFreezeAcknowledgement()); + } + + public static ReadSelectedPublicationArtifactInventoryResponse toResponse( + WorldSelectedPublicationArtifactInventoryEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + return ReadSelectedPublicationArtifactInventoryResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setCanonicalPublicInventory(ByteString.copyFrom(evidence.canonicalBytes())) + .setPublicInventoryDigest(evidence.digest()) + .build(); + } + + /** Strictly decodes the one public typed view and binds it to the caller's exact freeze. */ + public static WorldSelectedPublicationArtifactInventoryEvidence fromResponse( + WorldSelectedDraftPublicationFreezeEvidence expectedFreeze, + ReadSelectedPublicationArtifactInventoryResponse response) { + Objects.requireNonNull(expectedFreeze, "expectedFreeze"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadSelectedPublicationArtifactInventoryResponse"); + if (response.getSchemaVersion() != SCHEMA_VERSION + || response.getCanonicalPublicInventory().isEmpty() + || response.getPublicInventoryDigest().isEmpty()) { + throw new IllegalArgumentException("World response lacks a complete public inventory"); + } + return WorldSelectedPublicationArtifactInventoryEvidence.fromCanonicalBytes( + expectedFreeze, + response.getCanonicalPublicInventory().toByteArray(), + response.getPublicInventoryDigest()); + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClientTest.java new file mode 100644 index 0000000000..4ec65676b3 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClientTest.java @@ -0,0 +1,162 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.AbstractStub; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +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.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.worldmanagement.v1.WorldSelectedDraftPublicationFreezeServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldSelectedPublicationArtifactInventoryClientTest { + @Test + void requiresFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldSelectedPublicationArtifactInventoryClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + assertThatThrownBy( + () -> + new WorldSelectedPublicationArtifactInventoryClient( + new ServiceEndpointsProperties(), tls(directory), factory, "Test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void usesExactWorldIdentityAndBoundedDeadlineAndRejectsInvalidReadback(@TempDir Path directory) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(factory.buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new WorldSelectedPublicationArtifactInventoryClient( + endpoints, tls(directory), factory, "test"); + try { + client.init(); + AbstractStub initialized = initializedStub(client); + assertThat(initialized.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(initialized.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/world-management-service"); + + var stub = + mock( + WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + setStub(client, stub); + var fixture = WorldSelectedPublicationArtifactInventoryGrpcCodecTest.fixture(); + var expectedEvidence = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + fixture.freezeEvidence(), fixture.publicEvidence()); + var expectedResponse = + WorldSelectedPublicationArtifactInventoryGrpcCodec.toResponse(expectedEvidence); + when(stub.readSelectedPublicationArtifactInventory(any())).thenReturn(expectedResponse); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(fixture.freezeEvidence())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(fixture.freezeEvidence())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(stub); + + var actual = client.read(fixture.freezeEvidence()); + assertThat(actual.canonicalBytes()).containsExactly(expectedEvidence.canonicalBytes()); + assertThat(actual.digest()).isEqualTo(expectedEvidence.digest()); + verify(stub) + .readSelectedPublicationArtifactInventory( + eq( + WorldSelectedPublicationArtifactInventoryGrpcCodec.toRequest( + fixture.freezeEvidence()))); + + when(stub.readSelectedPublicationArtifactInventory(any())) + .thenReturn( + expectedResponse.toBuilder() + .setPublicInventoryDigest("sha256:" + "0".repeat(64)) + .build()); + assertThatThrownBy(() -> client.read(fixture.freezeEvidence())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid selected-publication inventory evidence"); + when(stub.readSelectedPublicationArtifactInventory(any())) + .thenThrow(Status.UNAVAILABLE.withDescription("offline").asRuntimeException()); + assertThatThrownBy(() -> client.read(fixture.freezeEvidence())) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + } finally { + client.close(); + } + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return tls; + } + + private static AbstractStub initializedStub( + WorldSelectedPublicationArtifactInventoryClient client) throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + private static void setStub( + WorldSelectedPublicationArtifactInventoryClient client, + WorldSelectedDraftPublicationFreezeServiceGrpc + .WorldSelectedDraftPublicationFreezeServiceBlockingStub + stub) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java new file mode 100644 index 0000000000..999ee9253a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java @@ -0,0 +1,396 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; +import org.junit.jupiter.api.Test; + +class WorldSelectedPublicationArtifactInventoryGrpcCodecTest { + @Test + void roundTripsTypedPublicInventoryBoundToTheExactFreezeWithoutPrivateOwnerKeys() { + var fixture = fixture(); + var evidence = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + fixture.freezeEvidence(), fixture.publicEvidence()); + var response = WorldSelectedPublicationArtifactInventoryGrpcCodec.toResponse(evidence); + var decoded = + WorldSelectedPublicationArtifactInventoryGrpcCodec.fromResponse( + fixture.freezeEvidence(), response); + + assertThat(decoded.canonicalBytes()).containsExactly(evidence.canonicalBytes()); + assertThat(decoded.digest()).isEqualTo(evidence.digest()); + assertThat(decoded.publicEvidence()).isEqualTo(fixture.publicEvidence()); + assertThat(new String(decoded.canonicalBytes(), StandardCharsets.UTF_8)) + .doesNotContain( + "localTenantKey", "localVersionKey", "gameDesignVersionId", "sourceGameRowId"); + var request = + WorldSelectedPublicationArtifactInventoryGrpcCodec.toRequest(fixture.freezeEvidence()); + var decodedFreeze = WorldSelectedPublicationArtifactInventoryGrpcCodec.fromRequest(request); + assertThat(WorldSelectedPublicationArtifactInventoryGrpcCodec.toRequest(decodedFreeze)) + .isEqualTo(request); + assertThat(decodedFreeze.request()).isEqualTo(fixture.freezeEvidence().request()); + assertThat(decodedFreeze.acknowledgement()) + .isEqualTo(fixture.freezeEvidence().acknowledgement()); + } + + @Test + void rejectsChangedFreezeDigestUnknownFieldsAndNoncanonicalOrOpenPublicBytes() { + var fixture = fixture(); + var evidence = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + fixture.freezeEvidence(), fixture.publicEvidence()); + var response = WorldSelectedPublicationArtifactInventoryGrpcCodec.toResponse(evidence); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatThrownBy( + () -> + WorldSelectedPublicationArtifactInventoryGrpcCodec.fromResponse( + fixture.freezeEvidence(), + response.toBuilder() + .setPublicInventoryDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldSelectedPublicationArtifactInventoryGrpcCodec.fromResponse( + fixture.freezeEvidence(), + response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var original = fixture.publicEvidence(); + var owner = original.ownerScope(); + var changedOwner = + new PublicOwnerScope( + owner.targetNamespace(), + uuid("17171717-1717-4717-8717-171717171717"), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest()); + var changedEvidence = + new PublicEvidence( + original.schema(), + original.schemaVersion(), + original.completeness(), + changedOwner, + original.selectedApplication(), + original.accountOrder(), + original.freeze(), + original.checkpoint(), + original.sourceModel(), + original.artifactDecisions()); + byte[] changedBytes = changedEvidence.canonicalBytes(); + assertThatThrownBy( + () -> + WorldSelectedPublicationArtifactInventoryEvidence.fromCanonicalBytes( + fixture.freezeEvidence(), changedBytes, sha256(changedBytes))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from exact selected Account order or freeze checkpoint"); + + String canonical = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); + String unknownJson = canonical.replaceFirst("\\{", "{\"unexpected\":true,"); + assertRejectedPublicJson(fixture, unknownJson); + String duplicateJson = canonical.replaceFirst("\\{", "{\"schema\":\"ignored\","); + assertRejectedPublicJson(fixture, duplicateJson); + assertRejectedPublicJson(fixture, canonical + "{}"); + assertRejectedPublicJson( + fixture, + canonical.replace( + "\"versionStateEpoch\":\"" + + fixture.freezeEvidence().acknowledgement().versionStateEpoch() + + "\"", + "\"versionStateEpoch\":" + + fixture.freezeEvidence().acknowledgement().versionStateEpoch())); + assertRejectedPublicJson( + fixture, + canonical.replace( + "\"versionStateEpoch\":\"" + + fixture.freezeEvidence().acknowledgement().versionStateEpoch() + + "\"", + "\"versionStateEpoch\":\"01\"")); + + String region = + "{\"generatorParams\":\"\",\"generatorType\":\"\"," + + "\"regionTemplateId\":\"15151515-1515-4515-8515-151515151515\"}"; + String duplicateRegion = + canonical + .replace("\"family\":\"REGION\",\"rowCount\":1", "\"family\":\"REGION\",\"rowCount\":2") + .replace( + "\"regionGeneratorInputs\":[" + region + "]", + "\"regionGeneratorInputs\":[" + region + "," + region + "]"); + assertRejectedPublicJson(fixture, duplicateRegion); + String higherRegion = + region.replace( + "15151515-1515-4515-8515-151515151515", "25252525-2525-4525-8525-252525252525"); + String reversedRegions = + canonical + .replace("\"family\":\"REGION\",\"rowCount\":1", "\"family\":\"REGION\",\"rowCount\":2") + .replace( + "\"regionGeneratorInputs\":[" + region + "]", + "\"regionGeneratorInputs\":[" + higherRegion + "," + region + "]"); + assertRejectedPublicJson(fixture, reversedRegions); + + String spawn = + "{\"bindingTemplateId\":\"18181818-1818-4818-8818-181818181818\"," + + "\"entityReferenceKind\":\"ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID\"," + + "\"entityTemplateId\":\"19191919-1919-4919-8919-191919191919\"," + + "\"entityTemplateType\":\"ITEM\"," + + "\"entityTenantId\":\"" + + fixture.publicEvidence().ownerScope().canonicalTenantId() + + "\",\"entityVersionId\":\"" + + fixture.publicEvidence().ownerScope().canonicalVersionId() + + "\",\"respawnDelaySeconds\":0," + + "\"roomTemplateId\":\"20202020-2020-4020-8020-202020202020\"," + + "\"spawnCount\":1}"; + String duplicateSpawn = + canonical + .replace( + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":0", + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":2") + .replace("\"spawnBindingCount\":0", "\"spawnBindingCount\":2") + .replace( + "\"spawnBindingInputs\":[]", + "\"spawnBindingInputs\":[" + spawn + "," + spawn + "]"); + assertRejectedPublicJson(fixture, duplicateSpawn); + String higherSpawn = + spawn.replace( + "18181818-1818-4818-8818-181818181818", "25252525-2525-4525-8525-252525252525"); + String reversedSpawns = + canonical + .replace( + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":0", + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":2") + .replace("\"spawnBindingCount\":0", "\"spawnBindingCount\":2") + .replace( + "\"spawnBindingInputs\":[]", + "\"spawnBindingInputs\":[" + higherSpawn + "," + spawn + "]"); + assertRejectedPublicJson(fixture, reversedSpawns); + + var model = fixture.publicEvidence().sourceModel(); + var unsupportedModel = + new SourceModel( + "UNSUPPORTED_MODEL", + model.graphSchemaVersion(), + model.graphDigest(), + model.topologyResultDigest(), + model.familyCounts(), + model.regionGeneratorInputs(), + model.generationRuleFields(), + model.regionFields(), + model.zoneFields(), + model.roomFields(), + model.roomExitFields(), + model.spawnBindingFields(), + model.spawnBindingInputs(), + model.generationRuleInputCount(), + model.spawnBindingCount(), + model.appliedEpochs()); + assertThatThrownBy( + () -> + new PublicEvidence( + fixture.publicEvidence().schema(), + fixture.publicEvidence().schemaVersion(), + fixture.publicEvidence().completeness(), + fixture.publicEvidence().ownerScope(), + fixture.publicEvidence().selectedApplication(), + fixture.publicEvidence().accountOrder(), + fixture.publicEvidence().freeze(), + fixture.publicEvidence().checkpoint(), + unsupportedModel, + fixture.publicEvidence().artifactDecisions())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source model is unsupported or incomplete"); + } + + static Fixture fixture() { + var request = WorldSelectedDraftPublicationFreezeGrpcCodecTest.request(); + var acknowledgement = acknowledgement(request); + var freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + var selected = request.accountBinding().input().selection(); + var commit = selected.selectedCommit(); + var account = request.accountBinding(); + var owner = + new PublicOwnerScope( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + uuid("12121212-1212-4212-8212-121212121212"), + acknowledgement.intakeRequestId(), + uuid("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + uuid("14141414-1414-4414-8414-141414141414"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + var sourceModel = + new SourceModel( + "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1", + 2, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 0), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(uuid("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + commit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList()); + var publicEvidence = + new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA, + 1, + "COMPLETE", + owner, + new SelectedApplication( + uuid("16161616-1616-4616-8616-161616161616"), + commit.requestId(), + commit.commitId().toString(), + commit.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selected.intent().publishRequestId(), + selected.digest(), + commit.commitId().toString(), + sha256(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selected.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint( + acknowledgement.appliedCommitId(), + acknowledgement.contentDigest(), + acknowledgement.digestSchemaVersion()), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", + "NOT_REQUIRED", + "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + return new Fixture(freezeEvidence, publicEvidence); + } + + private static void assertRejectedPublicJson(Fixture fixture, String json) { + byte[] bytes = json.getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + WorldSelectedPublicationArtifactInventoryEvidence.fromCanonicalBytes( + fixture.freezeEvidence(), bytes, sha256(bytes))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Acknowledgement acknowledgement( + WorldSelectedDraftPublicationFreezeEvidence.Request request) { + return new Acknowledgement( + request, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + request.expectedVersionStateEpoch(), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + OwnerFreezePhase.FROZEN, + request.accountBinding().input().selection().selectedCommit().commitId().toString(), + "a".repeat(64), + 3); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + record Fixture( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, PublicEvidence publicEvidence) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java new file mode 100644 index 0000000000..f4158090b4 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; + +/** Exact ordinary-source application evidence, composed into one control-plane owner result. */ +public record AssetApplication( + DraftCommitBinding binding, String expectedEpoch, AssetSnapshot snapshot) { + public AssetApplication { + Objects.requireNonNull(binding); + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || !binding.equals(snapshot.binding()) + || AssetSource.mutations(binding).isEmpty() + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch())) + throw new IllegalArgumentException( + "Ordinary asset application must advance its exact bound epoch"); + } + + public AppliedEpoch appliedEpoch() { + return new AppliedEpoch( + AssetSource.SCOPE, + binding.target().canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + expectedEpoch, + snapshot.sourceEpoch()); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-ordinary-asset-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java new file mode 100644 index 0000000000..e6fc02b7e2 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java @@ -0,0 +1,202 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; + +/** Ordinary selected source only; no total inventory or template/branding completeness claim. */ +public record AssetSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List items) { + public AssetSnapshot { + Objects.requireNonNull(binding); + Objects.requireNonNull(genesisReceiptId); + if (!sourceEpoch.matches("0|[1-9][0-9]*") || new UUID(0, 0).equals(genesisReceiptId)) + throw new IllegalArgumentException("Exact ordinary asset source epoch and genesis required"); + items = List.copyOf(items); + new AssetSource.Snapshot(binding, items.stream().map(Item::reference).toList()); + var ordered = + items.stream() + .sorted( + java.util.Comparator.comparing( + item -> item.reference().usageKey(), + (String left, String right) -> + java.util.Arrays.compareUnsigned( + left.getBytes(StandardCharsets.UTF_8), + right.getBytes(StandardCharsets.UTF_8)))) + .toList(); + if (!items.equals(ordered)) + throw new IllegalArgumentException("Ordinary asset items must be in canonical key order"); + } + + public record Item( + AssetSource.Reference reference, String contentType, String contentDigest, long byteSize) { + public Item { + Objects.requireNonNull(reference); + if (contentType == null + || contentType.isBlank() + || contentType.codePointCount(0, contentType.length()) > 100 + || contentDigest == null + || !contentDigest.matches("sha256:[0-9a-f]{64}") + || byteSize < 0) + throw new IllegalArgumentException("Exact ordinary asset byte metadata required"); + } + + Map object() { + var r = reference; + return Map.ofEntries( + Map.entry("family", r.family()), + Map.entry("role", r.role()), + Map.entry("usageKey", r.usageKey()), + Map.entry("assetRowId", r.assetRowId()), + Map.entry("requiredness", r.requiredness().name()), + Map.entry("sourceBindingJson", r.sourceBinding().canonicalJson()), + Map.entry("sourceBindingDigest", r.sourceBinding().digest()), + Map.entry("revisionOrder", r.revisionOrder()), + Map.entry("revisionId", r.revisionId().toString()), + Map.entry("contentType", contentType), + Map.entry("contentDigest", contentDigest), + Map.entry("byteSize", Long.toString(byteSize))); + } + } + + public String canonicalJson() { + return CommandSource.canonical( + Map.of( + "schema", + "game-design-ordinary-asset-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptId", + genesisReceiptId.toString(), + "items", + items.stream().map(Item::object).toList())); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static AssetSnapshot fromStored(String json) { + var root = CommandSource.tree(json); + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "items"); + if (!"game-design-ordinary-asset-source-snapshot/v1" + .equals(CommandSource.requiredStoredText(root, "schema")) + || !root.path("items").isArray()) + throw new IllegalArgumentException("Unsupported ordinary asset snapshot"); + var binding = + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(root, "bindingJson"), + CommandSource.requiredStoredText(root, "bindingDigest")); + var items = new java.util.ArrayList(); + for (var node : root.path("items")) { + CommandSource.requireStoredFields( + node, + "family", + "role", + "usageKey", + "assetRowId", + "requiredness", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId", + "contentType", + "contentDigest", + "byteSize"); + if (!AssetSource.FAMILY.equals(CommandSource.requiredStoredText(node, "family")) + || !AssetSource.ROLE.equals(CommandSource.requiredStoredText(node, "role"))) + throw new IllegalArgumentException("Unsupported ordinary source family or role"); + var reference = + new AssetSource.Reference( + CommandSource.requiredStoredText(node, "usageKey"), + CommandSource.requiredStoredText(node, "assetRowId"), + AssetSource.Requiredness.valueOf( + CommandSource.requiredStoredText(node, "requiredness")), + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(node, "sourceBindingJson"), + CommandSource.requiredStoredText(node, "sourceBindingDigest")), + CommandSource.requiredStoredText(node, "revisionOrder"), + UUID.fromString(CommandSource.requiredStoredText(node, "revisionId"))); + items.add( + new Item( + reference, + CommandSource.requiredStoredText(node, "contentType"), + CommandSource.requiredStoredText(node, "contentDigest"), + Long.parseLong(CommandSource.requiredStoredText(node, "byteSize")))); + } + if (!root.path("inheritedCommitId").isTextual()) + throw new IllegalArgumentException("Stored inherited commit must be text"); + String inherited = root.path("inheritedCommitId").textValue(); + var result = + new AssetSnapshot( + binding, + CommandSource.requiredStoredText(root, "sourceEpoch"), + inherited.isEmpty() ? null : UUID.fromString(inherited), + UUID.fromString(CommandSource.requiredStoredText(root, "genesisReceiptId")), + items); + if (!result.canonicalJson().equals(json)) + throw new IllegalArgumentException("Noncanonical ordinary asset snapshot"); + return result; + } + + public record Genesis(TargetProof target, UUID receiptId, String creationTransactionId) { + public Genesis { + Objects.requireNonNull(target); + if (receiptId == null + || new UUID(0, 0).equals(receiptId) + || creationTransactionId == null + || !creationTransactionId.matches("[1-9][0-9]*")) + throw new IllegalArgumentException("Exact ordinary source creation evidence required"); + } + } + + public record Capture(GameDesignPublicationOperation operation, AssetSnapshot snapshot) { + public Capture { + Objects.requireNonNull(operation); + Objects.requireNonNull(snapshot); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) + throw new IllegalArgumentException("Ordinary asset capture differs from selected commit"); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, "game-design-ordinary-asset-source-capture/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, operation.canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java new file mode 100644 index 0000000000..f9a780447e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java @@ -0,0 +1,327 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed ordinary asset-reference source operations for the existing Draft coordinator. This codec + * does not qualify asset rows, authenticate an operation, establish genesis or attest completeness. + */ +public final class AssetSource { + public static final String SCOPE = "ASSET_REFERENCE_SET"; + public static final String SCOPE_ID = "effective"; + public static final String REVISION_KIND = "ASSET_REFERENCE"; + public static final String FAMILY = "ORDINARY"; + public static final String ROLE = "RESOURCE"; + + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private AssetSource() {} + + public enum OperationKind { + UPSERT, + DELETE + } + + public enum Requiredness { + REQUIRED, + OPTIONAL + } + + /** The complete original binding retains request, target, commit and exact payload identity. */ + public record Mutation( + DraftCommitBinding binding, + String revisionOrder, + UUID revisionId, + OperationKind operation, + String usageKey, + String assetRowId, + Requiredness requiredness) { + public Mutation { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(operation, "operation"); + requireUsageKey(usageKey); + var revision = + binding.revisions().stream() + .filter(value -> value.revisionId().equals(revisionId)) + .filter(value -> value.revisionOrder().equals(revisionOrder)) + .filter(value -> value.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .findFirst() + .orElseThrow( + () -> new IllegalArgumentException("Asset revision is not in its exact binding")); + String expectedPayload; + if (operation == OperationKind.UPSERT) { + expectedPayload = upsertPayload(assetRowId, usageKey, requiredness); + } else { + if (assetRowId != null || requiredness != null) { + throw new IllegalArgumentException("Asset DELETE cannot carry UPSERT fields"); + } + expectedPayload = deletePayload(usageKey); + } + // Parse before canonicalization so duplicate fields or trailing JSON can never collapse. + JsonNode actual = tree(revision.payload()); + if (!actual.path("schemaVersion").isInt() || actual.path("schemaVersion").intValue() != 1) { + throw new IllegalArgumentException("Unsupported asset source schemaVersion"); + } + fields( + actual, + operation == OperationKind.UPSERT + ? Set.of( + "schemaVersion", + "revisionKind", + "family", + "role", + "operation", + "assetRowId", + "usageKey", + "requiredness") + : Set.of("schemaVersion", "revisionKind", "family", "role", "operation", "usageKey")); + if (!canonical(actual).equals(expectedPayload)) { + throw new IllegalArgumentException("Asset mutation differs from the exact bound revision"); + } + } + } + + /** Exact creating source provenance; numeric asset row identity is internal to Game Design. */ + public record Reference( + String usageKey, + String assetRowId, + Requiredness requiredness, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId) { + public Reference { + // A reference cannot rewrite the requiredness or asset identity of its creating UPSERT. + new Mutation( + sourceBinding, + revisionOrder, + revisionId, + OperationKind.UPSERT, + usageKey, + assetRowId, + requiredness); + } + + public String family() { + return FAMILY; + } + + public String role() { + return ROLE; + } + } + + /** Typed source snapshot only; presence or an empty list is not COMPLETE evidence. */ + public record Snapshot(DraftCommitBinding binding, List references) { + public Snapshot { + Objects.requireNonNull(binding, "binding"); + references = List.copyOf(Objects.requireNonNull(references, "references")); + requireDistinctReferences(references); + for (Reference reference : references) { + if (!binding.target().equals(reference.sourceBinding().target())) { + throw new IllegalArgumentException("Asset reference belongs to another source target"); + } + } + } + } + + public static List mutations(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + List result = new ArrayList<>(); + for (var revision : binding.revisions()) { + if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; + JsonNode payload = tree(revision.payload()); + String kind = text(payload, "revisionKind"); + if ("COMMAND_DEFINITION".equals(kind) || "REALM_ENTRY_POLICY".equals(kind)) continue; + if (!REVISION_KIND.equals(kind)) { + throw new IllegalArgumentException("Unsupported Game Design asset source revision kind"); + } + if (!payload.path("schemaVersion").isInt() || payload.path("schemaVersion").intValue() != 1) { + throw new IllegalArgumentException("Unsupported asset source schemaVersion"); + } + OperationKind operation = OperationKind.valueOf(text(payload, "operation")); + result.add( + new Mutation( + binding, + revision.revisionOrder(), + revision.revisionId(), + operation, + text(payload, "usageKey"), + operation == OperationKind.UPSERT ? text(payload, "assetRowId") : null, + operation == OperationKind.UPSERT + ? Requiredness.valueOf(text(payload, "requiredness")) + : null)); + } + return List.copyOf(result); + } + + public static String upsertPayload( + String assetRowId, String usageKey, Requiredness requiredness) { + requireAssetRowId(assetRowId); + requireUsageKey(usageKey); + if (requiredness != Requiredness.REQUIRED) { + throw new IllegalArgumentException("Ordinary RESOURCE requires REQUIRED owner policy"); + } + return canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + REVISION_KIND, + "family", + FAMILY, + "role", + ROLE, + "operation", + "UPSERT", + "assetRowId", + assetRowId, + "usageKey", + usageKey, + "requiredness", + requiredness.name())); + } + + public static String deletePayload(String usageKey) { + requireUsageKey(usageKey); + return canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + REVISION_KIND, + "family", + FAMILY, + "role", + ROLE, + "operation", + "DELETE", + "usageKey", + usageKey)); + } + + /** Applies only explicit ordered operations, preserving provenance on untouched references. */ + public static Snapshot replay(List inherited, DraftCommitBinding binding) { + var baseline = new Snapshot(binding, inherited); + Map effective = new HashMap<>(); + for (Reference reference : baseline.references()) + effective.put(reference.usageKey(), reference); + for (Mutation mutation : mutations(binding)) { + if (mutation.operation() == OperationKind.DELETE) { + effective.remove(mutation.usageKey()); + } else { + Reference reference = + new Reference( + mutation.usageKey(), + mutation.assetRowId(), + mutation.requiredness(), + binding, + mutation.revisionOrder(), + mutation.revisionId()); + for (Reference current : effective.values()) { + if (current.assetRowId().equals(reference.assetRowId()) + && !current.usageKey().equals(reference.usageKey())) { + throw new IllegalArgumentException( + "One asset source cannot acquire multiple usage aliases"); + } + } + effective.put(reference.usageKey(), reference); + } + } + return new Snapshot( + binding, + effective.values().stream() + .sorted(Comparator.comparing(Reference::usageKey, AssetSource::compareUtf8)) + .toList()); + } + + private static void requireDistinctReferences(List references) { + Set keys = new HashSet<>(); + Set assets = new HashSet<>(); + for (Reference reference : references) { + if (!keys.add(reference.usageKey()) || !assets.add(reference.assetRowId())) { + throw new IllegalArgumentException("Asset source repeats a usage key or source row"); + } + } + } + + private static void requireAssetRowId(String value) { + if (value == null || value.length() > 19 || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "assetRowId must be a positive canonical BIGINT decimal string"); + } + try { + Long.parseLong(value); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("assetRowId exceeds its owner BIGINT range", exception); + } + } + + private static void requireUsageKey(String value) { + if (value == null + || value.isBlank() + || value.codePointCount(0, value.length()) > 255 + || "manifest.json".equals(value)) { + throw new IllegalArgumentException( + "Asset usageKey must fit its exact nonblank owner filename"); + } + } + + private static String text(JsonNode value, String field) { + if (!value.isObject() || !value.path(field).isTextual()) { + throw new IllegalArgumentException("Asset source requires textual " + field); + } + return value.path(field).textValue(); + } + + private static void fields(JsonNode value, Set expected) { + if (!value.isObject() + || value.size() != expected.size() + || value.properties().stream().anyMatch(entry -> !expected.contains(entry.getKey()))) { + throw new IllegalArgumentException("Asset source members differ from the closed schema"); + } + } + + private static JsonNode tree(String value) { + try { + return JSON.readTree(value); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Malformed asset source JSON", exception); + } + } + + private static String canonical(Object value) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("Asset source canonicalization failed", exception); + } + } + + private static int compareUtf8(String left, String right) { + return java.util.Arrays.compareUnsigned( + left.getBytes(StandardCharsets.UTF_8), right.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java new file mode 100644 index 0000000000..f734179ca8 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java @@ -0,0 +1,574 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Actual ordinary source writes under the existing coordinator; never total inventory authority. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner-local injected persistence collaborator") +public final class AssetSourceRepository { + private final DSLContext dsl; + private final DraftCommitCoordinatorRepository coordinator; + + public AssetSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + } + + public AssetSnapshot.Genesis enrollFreshDraft(TargetProof target) { + write(); + lock(target); + var prior = readGenesis(target); + if (prior.isPresent()) return prior.orElseThrow(); + var witness = + dsl.fetchOne( + "SELECT creation_transaction_id FROM game_design_realm_policy_version_insert " + + "WHERE version_id = ? AND creation_transaction_id = pg_current_xact_id()::TEXT", + target.gameDesignVersionRowId()); + if (witness == null) throw new IllegalStateException("ASSET_SOURCE_FRESH_INSERT_UNAVAILABLE"); + var genesis = + new AssetSnapshot.Genesis(target, UUID.randomUUID(), witness.get(0, String.class)); + dsl.execute( + "INSERT INTO game_design_asset_source_genesis " + + "(canonical_tenant_id, canonical_version_id, version_id, receipt_id, creation_transaction_id, target_json) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + genesis.receiptId(), + genesis.creationTransactionId(), + CommandSource.canonical(CommandSource.targetObject(target))); + dsl.execute( + "INSERT INTO game_design_asset_source_head " + + "(canonical_tenant_id, canonical_version_id, source_epoch, genesis_receipt_id) VALUES (?, ?, '0', ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + genesis.receiptId()); + if (!genesis.equals(readGenesis(target).orElseThrow())) + throw new IllegalStateException("ASSET_SOURCE_GENESIS_READBACK_CONFLICT"); + return genesis; + } + + public Optional readGenesis(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_asset_source_genesis WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!CommandSource.canonical(CommandSource.targetObject(target)) + .equals(row.get("target_json", String.class)) + || target.gameDesignVersionRowId() != row.get("version_id", Long.class)) + throw new IllegalStateException("ASSET_SOURCE_GENESIS_TARGET_CONFLICT"); + return Optional.of( + new AssetSnapshot.Genesis( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class))); + } + + public Optional apply(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var mutations = AssetSource.mutations(binding); + var prior = application(binding); + if (prior.isPresent()) return prior; + if (mutations.isEmpty()) return Optional.empty(); + open(binding.target()); + var slot = coordinator.readApplicationSlot(binding.target()).orElseThrow(); + var owner = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (!binding.requestId().equals(slot.requestId()) + || !binding.commitId().equals(slot.commitId()) + || owner == null + || (owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.IN_PROGRESS + && owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN)) + throw new IllegalStateException("ASSET_SOURCE_COORDINATOR_APPLICATION_UNAVAILABLE"); + Record head = head(binding.target()); + var units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(AssetSourceRepository::isScope) + .toList(); + String epoch = head.get("source_epoch", String.class); + if (units.size() != 1 + || !binding.target().canonicalVersionId().toString().equals(units.getFirst().aggregateId()) + || !epoch.equals(units.getFirst().expectedEpoch())) + throw new IllegalStateException("ASSET_SOURCE_EPOCH_CONFLICT"); + UUID inherited = head.get("visible_commit_id", UUID.class); + requirePreviousFence(binding.target(), inherited); + List previous = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().items(); + if (inherited == null && !"0".equals(epoch)) + throw new IllegalStateException("ASSET_SOURCE_GENESIS_NOT_CURRENT"); + // Lock all actual source rows in owner-key order before writing any revision history. + mutations.stream() + .filter(m -> m.operation() == AssetSource.OperationKind.UPSERT) + .map(m -> Long.parseLong(m.assetRowId())) + .distinct() + .sorted() + .forEach( + id -> { + if (dsl.fetchOne( + "SELECT id FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", + binding.target().gameDesignVersionTenantKey(), + id) + == null) throw new IllegalStateException("ASSET_SOURCE_ROW_UNAVAILABLE"); + }); + for (var mutation : mutations) { + AssetSnapshot.Item item = + mutation.operation() == AssetSource.OperationKind.UPSERT + ? qualify( + new AssetSource.Reference( + mutation.usageKey(), + mutation.assetRowId(), + mutation.requiredness(), + binding, + mutation.revisionOrder(), + mutation.revisionId()), + true) + : null; + dsl.execute( + "INSERT INTO game_design_asset_source_revision " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, operation_kind, usage_key, asset_id, requiredness, content_type, content_digest, byte_size) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + mutation.revisionId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.operation().name(), + mutation.usageKey(), + item == null ? null : Long.parseLong(mutation.assetRowId()), + item == null ? null : mutation.requiredness().name(), + item == null ? null : item.contentType(), + item == null ? null : item.contentDigest(), + item == null ? null : item.byteSize()); + } + var references = + AssetSource.replay(previous.stream().map(AssetSnapshot.Item::reference).toList(), binding) + .references(); + var snapshot = + new AssetSnapshot( + binding, + new BigInteger(epoch).add(BigInteger.ONE).toString(), + inherited, + head.get("genesis_receipt_id", UUID.class), + references.stream().map(r -> qualify(r, false)).toList()); + var result = new AssetApplication(binding, epoch, snapshot); + dsl.execute( + "INSERT INTO game_design_asset_source_application " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, expected_epoch, snapshot_json, result_bytes) VALUES (?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + epoch, + snapshot.canonicalJson(), + result.canonicalBytes()); + if (dsl.execute( + "UPDATE game_design_asset_source_head SET source_epoch = ?, applied_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID)", + snapshot.sourceEpoch(), + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + epoch, + inherited) + != 1) throw new IllegalStateException("ASSET_SOURCE_EPOCH_CONFLICT"); + return Optional.of(application(binding).orElseThrow()); + } + + public AssetSnapshot captureSynchronized(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var prior = readSnapshot(binding.target(), binding.commitId()); + if (prior.isPresent()) { + if (!prior.orElseThrow().binding().equals(binding)) + throw new IllegalStateException("ASSET_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + return prior.orElseThrow(); + } + open(binding.target()); + requireFence(binding); + var head = head(binding.target()); + UUID inherited = head.get("visible_commit_id", UUID.class); + var applied = application(binding); + AssetSnapshot snapshot; + if (!AssetSource.mutations(binding).isEmpty()) { + var result = + applied.orElseThrow( + () -> new IllegalStateException("ASSET_SOURCE_APPLICATION_UNAVAILABLE")); + snapshot = result.snapshot(); + if (!Objects.equals(inherited, snapshot.inheritedCommitId())) + throw new IllegalStateException("ASSET_SOURCE_PREDECESSOR_CHANGED"); + } else { + var items = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().items(); + snapshot = + new AssetSnapshot( + binding, + head.get("source_epoch", String.class), + inherited, + head.get("genesis_receipt_id", UUID.class), + items); + } + if (!snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("ASSET_SOURCE_PARTIAL_WRITE_NOT_VISIBLE"); + dsl.execute( + "INSERT INTO game_design_asset_source_snapshot " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, snapshot_json, snapshot_digest) VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + snapshot.canonicalJson(), + snapshot.digest()); + dsl.execute( + "UPDATE game_design_asset_source_head SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + return readSnapshot(binding.target(), binding.commitId()).orElseThrow(); + } + + public Optional readSnapshot(TargetProof target, UUID commitId) { + var row = + dsl.fetchOne( + "SELECT snapshot_json, snapshot_digest FROM game_design_asset_source_snapshot WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId); + if (row == null) return Optional.empty(); + var snapshot = AssetSnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId) + || !snapshot.digest().equals(row.get("snapshot_digest", String.class))) + throw new IllegalStateException("ASSET_SOURCE_SNAPSHOT_READBACK_CONFLICT"); + exact(snapshot.binding()); + var fence = + dsl.fetchOne( + "SELECT input_digest FROM game_design_draft_commit_visibility_fence WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.binding().requestId(), + commitId); + if (fence == null || !snapshot.binding().digest().equals(fence.get(0, String.class))) { + throw new IllegalStateException("ASSET_SOURCE_SNAPSHOT_FENCE_CONFLICT"); + } + verifyItems(snapshot); + if (dsl.fetchOne( + "SELECT 1 FROM game_design_asset_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND visible_commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId) + != null) { + var mappings = + dsl.fetch( + "SELECT asset_id, usage_key, usage_type FROM version_asset WHERE tenant_id = ? AND version_id = ?", + target.gameDesignVersionTenantKey(), + target.gameDesignVersionRowId()); + if (mappings.size() != snapshot.items().size() + || mappings.stream() + .anyMatch( + mapping -> + mapping.get("usage_type") != null + || snapshot.items().stream() + .noneMatch( + item -> + item.reference() + .assetRowId() + .equals( + mapping.get("asset_id", Long.class).toString()) + && item.reference() + .usageKey() + .equals(mapping.get("usage_key", String.class))))) { + throw new IllegalStateException("ASSET_SOURCE_PROJECTION_READBACK_CONFLICT"); + } + } + return Optional.of(snapshot); + } + + public AssetSnapshot.Capture freeze(GameDesignPublicationOperation operation) { + write(); + var selection = operation.account().input().selection(); + lock(selection.target()); + var prior = readCapture(operation); + if (prior.isPresent()) return prior.orElseThrow(); + var retained = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(); + GameDesignPublicationOperationRepository.exact(retained.operation(), operation); + if (!"PENDING".equals(retained.outcome())) + throw new IllegalStateException("ASSET_SOURCE_OPERATION_SEALED"); + requireFence(selection.selectedCommit()); + var selected = + dsl.fetchOne( + "SELECT selection_json FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId()); + if (selected == null || !selection.canonicalJson().equals(selected.get(0, String.class))) + throw new IllegalStateException("ASSET_SOURCE_SELECTION_CHANGED"); + var snapshot = + readSnapshot(selection.target(), selection.selectedCommit().commitId()).orElseThrow(); + var head = head(selection.target()); + if (!snapshot.binding().equals(selection.selectedCommit()) + || !snapshot.sourceEpoch().equals(head.get("source_epoch", String.class)) + || !snapshot.binding().commitId().equals(head.get("visible_commit_id", UUID.class))) + throw new IllegalStateException("ASSET_SOURCE_NOT_SYNCHRONIZED"); + var capture = new AssetSnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_asset_source_capture (canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, operation_bytes, capture_bytes, capture_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + operation.workflowId(), + snapshot.binding().commitId(), + operation.canonicalBytes(), + capture.canonicalBytes(), + capture.digest()); + return readCapture(operation).orElseThrow(); + } + + public Optional readCapture(GameDesignPublicationOperation operation) { + var target = operation.account().input().selection().target(); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_asset_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + var capture = + new AssetSnapshot.Capture( + operation, readSnapshot(target, row.get("commit_id", UUID.class)).orElseThrow()); + if (!operation.workflowId().equals(row.get("publish_workflow_id", String.class)) + || !Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class)) + || !capture.digest().equals(row.get("capture_digest", String.class))) + throw new IllegalStateException("ASSET_SOURCE_CAPTURE_READBACK_CONFLICT"); + return Optional.of(capture); + } + + /** + * Requires actual synchronized source, including empty ordinary sets; never invents a baseline. + */ + public AssetSnapshot requireExportSelection(String tenantId, long versionId) { + var version = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByTenantIdAndId(tenantId, versionId) + .orElseThrow(); + var canonical = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByCanonicalTenantIdAndCanonicalVersionId( + version.getCanonicalTenantId(), version.getCanonicalVersionId()) + .orElseThrow(() -> new IllegalStateException("ASSET_SOURCE_TARGET_UNQUALIFIED")); + if (!version.getId().equals(canonical.getId())) + throw new IllegalStateException("ASSET_SOURCE_TARGET_CHANGED"); + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + versionId, + tenantId, + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + var head = readHead(target, false); + UUID commit = head.get("visible_commit_id", UUID.class); + if (commit == null) + throw new IllegalStateException("ASSET_SOURCE_SYNCHRONIZED_SELECTION_UNAVAILABLE"); + var snapshot = readSnapshot(target, commit).orElseThrow(); + requireFence(snapshot.binding()); + if (!snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("ASSET_SOURCE_NOT_SYNCHRONIZED"); + return snapshot; + } + + private Optional application(DraftCommitBinding binding) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_asset_source_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) return Optional.empty(); + var result = + new AssetApplication( + binding, + row.get("expected_epoch", String.class), + AssetSnapshot.fromStored(row.get("snapshot_json", String.class))); + if (!Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class)) + || !binding.requestId().equals(row.get("request_id", UUID.class))) + throw new IllegalStateException("ASSET_SOURCE_APPLICATION_READBACK_CONFLICT"); + verifyItems(result.snapshot()); + return Optional.of(result); + } + + private AssetSnapshot.Item qualify(AssetSource.Reference reference, boolean lock) { + var target = reference.sourceBinding().target(); + var row = + dsl.fetchOne( + "SELECT file_name, content_type, data FROM game_assets WHERE tenant_id = ? AND id = ?" + + (lock ? " FOR UPDATE" : ""), + target.gameDesignVersionTenantKey(), + Long.parseLong(reference.assetRowId())); + if (row == null + || !reference.usageKey().equals(row.get("file_name", String.class)) + || row.get("data", byte[].class) == null) + throw new IllegalStateException("ASSET_SOURCE_EXACT_BYTES_UNAVAILABLE"); + byte[] bytes = row.get("data", byte[].class); + return new AssetSnapshot.Item( + reference, + row.get("content_type", String.class), + CommandSource.sha256(bytes), + bytes.length); + } + + private void verifyItems(AssetSnapshot snapshot) { + for (var item : snapshot.items()) { + if (!item.equals(qualify(item.reference(), false))) + throw new IllegalStateException("ASSET_SOURCE_BYTE_READBACK_CONFLICT"); + var r = item.reference(); + var row = + dsl.fetchOne( + "SELECT content_digest, content_type, byte_size FROM game_design_asset_source_revision " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ? AND commit_id = ? AND request_id = ? AND revision_order = ? AND asset_id = ? AND usage_key = ? AND requiredness = ?", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + r.revisionId(), + r.sourceBinding().commitId(), + r.sourceBinding().requestId(), + Integer.parseInt(r.revisionOrder()), + Long.parseLong(r.assetRowId()), + r.usageKey(), + r.requiredness().name()); + if (row == null + || !item.contentDigest().equals(row.get("content_digest", String.class)) + || !item.contentType().equals(row.get("content_type", String.class)) + || item.byteSize() != row.get("byte_size", Long.class)) + throw new IllegalStateException("ASSET_SOURCE_REVISION_READBACK_CONFLICT"); + } + } + + private Record head(TargetProof target) { + return readHead(target, true); + } + + private Record readHead(TargetProof target, boolean lock) { + readGenesis(target) + .orElseThrow(() -> new IllegalStateException("ASSET_SOURCE_GENESIS_UNAVAILABLE")); + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_design_asset_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ?" + + (lock ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId()), + "ASSET_SOURCE_HEAD_UNAVAILABLE"); + } + + private void exact(DraftCommitBinding binding) { + if (!coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .binding() + .equals(binding)) throw new IllegalStateException("ASSET_SOURCE_BINDING_CHANGED"); + } + + private void requirePreviousFence(TargetProof target, UUID inherited) { + var fence = coordinator.readVisibilityFence(target); + if (inherited == null + ? fence.isPresent() + : fence.isEmpty() || !inherited.equals(fence.orElseThrow().commitId())) + throw new IllegalStateException("ASSET_SOURCE_PREVIOUS_FENCE_CHANGED"); + } + + private void requireFence(DraftCommitBinding binding) { + var fence = coordinator.readVisibilityFence(binding.target()).orElseThrow(); + if (!binding.commitId().equals(fence.commitId()) + || !binding.requestId().equals(fence.requestId()) + || !binding.digest().equals(fence.inputDigest()) + || coordinator.read(binding.target(), binding.requestId()).orElseThrow().workflowState() + != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED) + throw new IllegalStateException("ASSET_SOURCE_SYNCHRONIZED_FENCE_UNAVAILABLE"); + } + + private void open(TargetProof target) { + if (dsl.fetchOne( + "SELECT id FROM version WHERE id = ? AND version_state = 'DRAFT' AND NOT is_script_only AND base_version_id IS NULL AND script_patch_version IS NULL", + target.gameDesignVersionRowId()) + == null + || dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null + || dsl.fetchOne( + "SELECT 1 FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + target.gameDesignVersionTenantKey(), + target.gameDesignVersionRowId()) + != null) throw new IllegalStateException("ASSET_SOURCE_FROZEN_OR_NOT_DRAFT"); + } + + private void lock(TargetProof target) { + var qualified = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByCanonicalTenantIdAndCanonicalVersionId( + target.canonicalTenantId(), target.canonicalVersionId()) + .orElseThrow(); + var version = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByTenantIdAndIdForUpdate( + target.gameDesignVersionTenantKey(), target.gameDesignVersionRowId()) + .orElseThrow(); + var actual = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + if (!target.equals(actual) || !qualified.getId().equals(version.getId())) + throw new IllegalStateException("ASSET_SOURCE_TARGET_CHANGED"); + } + + static boolean isScope(DraftCommitBinding.AffectedUnit unit) { + return AssetSource.SCOPE.equals(unit.aggregateType()) + && AssetSource.SCOPE.equals(unit.scopeType()) + && AssetSource.SCOPE_ID.equals(unit.scopeId()); + } + + private static void write() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) + throw new IllegalStateException( + "Ordinary asset source requires writable READ_COMMITTED transaction"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java index 40a0d14213..249d747402 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java @@ -155,7 +155,8 @@ public static List mutations(DraftCommitBinding binding) { throw new IllegalArgumentException("Closed Game Design owner revision kind is required"); } String revisionKind = payload.path("revisionKind").asText(); - if (REALM_POLICY_REVISION_KIND.equals(revisionKind)) continue; + if (REALM_POLICY_REVISION_KIND.equals(revisionKind) + || AssetSource.REVISION_KIND.equals(revisionKind)) continue; if (!REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } @@ -204,7 +205,8 @@ public static boolean hasRealmPolicyRevision(DraftCommitBinding binding) { String revisionKind = payload.path("revisionKind").asText(); if (REALM_POLICY_REVISION_KIND.equals(revisionKind)) { found = true; - } else if (!REVISION_KIND.equals(revisionKind)) { + } else if (!REVISION_KIND.equals(revisionKind) + && !AssetSource.REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java index ffc60d15a4..7151cf0d12 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java @@ -548,14 +548,18 @@ private void requireCompleteControlPlaneScopes( units.stream().filter(this::isCommandScope).toList(); List policies = units.stream().filter(this::isPolicyScope).toList(); + var assets = units.stream().filter(AssetSourceRepository::isScope).toList(); + boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); if (commands.size() != (commandMutations.isEmpty() ? 0 : 1) || policies.size() != (policyMutation ? 1 : 0) - || commands.size() + policies.size() != units.size()) { + || assets.size() != (assetMutation ? 1 : 0) + || commands.size() + policies.size() + assets.size() != units.size()) { throw new IllegalArgumentException( "Complete supported Game Design control-plane scopes are required"); } if (!commands.isEmpty()) requireScopeTarget(commands.getFirst(), binding.target()); if (!policies.isEmpty()) requireScopeTarget(policies.getFirst(), binding.target()); + if (!assets.isEmpty()) requireScopeTarget(assets.getFirst(), binding.target()); } private boolean isCommandScope(DraftCommitBinding.AffectedUnit unit) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java index a9892ae52d..da3443a065 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java @@ -19,16 +19,18 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Joins the two actual Game Design sources under one caller-owned coordinator transaction. */ +/** Joins actual Game Design sources under one caller-owned coordinator transaction. */ public final class GameDesignSourceRepository { private final RealmPolicySourceRepository policies; private final CommandSourceRepository commands; + private final AssetSourceRepository assets; private final DraftCommitCoordinatorRepository coordinator; public GameDesignSourceRepository(DSLContext dsl) { Objects.requireNonNull(dsl, "dsl"); policies = new RealmPolicySourceRepository(dsl); commands = new CommandSourceRepository(dsl); + assets = new AssetSourceRepository(dsl); coordinator = new DraftCommitCoordinatorRepository(dsl); } @@ -41,7 +43,7 @@ public Genesis enrollFreshDraft(TargetProof target) { commands.enrollNewDraftGenesis( new CommandSource.NewDraftGenesisReceipt( target, policy.receiptId(), policy.creationTransactionId())); - Genesis result = new Genesis(policy, command); + Genesis result = new Genesis(policy, command, assets.enrollFreshDraft(target)); if (!result.equals( readGenesis(target) .orElseThrow( @@ -57,11 +59,13 @@ public Optional readGenesis(TargetProof target) { Objects.requireNonNull(target, "target"); var policy = policies.readGenesis(target); var command = commands.readNewDraftGenesis(target); - if (policy.isEmpty() && command.isEmpty()) return Optional.empty(); - if (policy.isEmpty() || command.isEmpty()) { + var asset = assets.readGenesis(target); + if (policy.isEmpty() && command.isEmpty() && asset.isEmpty()) return Optional.empty(); + if (policy.isEmpty() || command.isEmpty() || asset.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); } - return Optional.of(new Genesis(policy.orElseThrow(), command.orElseThrow())); + return Optional.of( + new Genesis(policy.orElseThrow(), command.orElseThrow(), asset.orElseThrow())); } /** Stage actual source writes and record exactly one complete local owner outcome. */ @@ -70,9 +74,13 @@ public Application apply(DraftCommitBinding binding) { Objects.requireNonNull(binding, "binding"); List commandMutations = CommandSource.mutations(binding); boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); - requireCompleteScopes(binding, !commandMutations.isEmpty(), policyMutation); + boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); + requireCompleteScopes(binding, !commandMutations.isEmpty(), policyMutation, assetMutation); requireGenesis(binding.target()); Optional command = commands.apply(binding); + Optional asset = assets.apply(binding); + if (asset.isPresent() != assetMutation) + throw new IllegalStateException("GAME_DESIGN_ASSET_APPLICATION_INCOMPLETE"); if (command.isPresent() != !commandMutations.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_COMMAND_APPLICATION_INCOMPLETE"); } @@ -82,10 +90,57 @@ public Application apply(DraftCommitBinding binding) { // first, then records the combined result using the command store's actual readback bytes. policy = Optional.of( - command.isPresent() ? policies.applyMutation(binding) : policies.apply(binding)); + command.isPresent() || asset.isPresent() + ? policies.applyMutation(binding) + : policies.apply(binding)); } OwnerOutcome expected; - if (policy.isPresent() && command.isPresent()) { + if (asset.isPresent()) { + var component = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + component, "game-design-control-plane-sibling-components/v1"); + var epochs = new java.util.ArrayList(); + if (command.isPresent()) { + DraftAuthorizationFenceBinding.frame(component, "COMMAND"); + DraftAuthorizationFenceBinding.frame(component, command.orElseThrow().canonicalBytes()); + epochs.add(command.orElseThrow().commandAppliedEpoch()); + } + DraftAuthorizationFenceBinding.frame(component, "ASSET"); + DraftAuthorizationFenceBinding.frame(component, asset.orElseThrow().canonicalBytes()); + epochs.add(asset.orElseThrow().appliedEpoch()); + if (policy.isPresent()) { + var policyResult = policy.orElseThrow(); + epochs.add(policyResult.ownerOutcome().appliedEpochs().getFirst()); + epochs.sort( + java.util.Comparator.comparing(AppliedEpoch::aggregateType) + .thenComparing(AppliedEpoch::aggregateId) + .thenComparing(AppliedEpoch::scopeType) + .thenComparing(AppliedEpoch::scopeId)); + policies.recordCombinedOwnerOutcome(binding, component.toByteArray(), List.copyOf(epochs)); + expected = policyResult.combinedOwnerOutcome(component.toByteArray(), List.copyOf(epochs)); + } else { + epochs.sort( + java.util.Comparator.comparing(AppliedEpoch::aggregateType) + .thenComparing(AppliedEpoch::aggregateId) + .thenComparing(AppliedEpoch::scopeType) + .thenComparing(AppliedEpoch::scopeId)); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + out, "game-design-control-plane-ordinary-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, component.toByteArray()); + expected = + new OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "ordinary-source:" + binding.commitId(), + out.toByteArray(), + List.copyOf(epochs)); + coordinator.recordOwnerOutcome(binding, expected); + } + } else if (policy.isPresent() && command.isPresent()) { var policyResult = policy.orElseThrow(); var commandResult = command.orElseThrow(); List epochs = @@ -113,7 +168,7 @@ public Application apply(DraftCommitBinding binding) { if (!expected.equals(retained)) { throw new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_CONFLICT"); } - return new Application(binding, command, policy, retained); + return new Application(binding, command, policy, asset, retained); } /** Invoke after the actual coordinator fence advances, before releasing its application slot. */ @@ -123,10 +178,11 @@ public SynchronizedSources captureSynchronized(DraftCommitBinding binding) { requireGenesis(binding.target()); CommandSnapshot command = commands.captureSynchronized(binding); RealmPolicySnapshot policy = policies.captureSynchronized(binding); + AssetSnapshot asset = assets.captureSynchronized(binding); if (!binding.equals(command.binding()) || !binding.equals(policy.binding())) { throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_BINDING_CONFLICT"); } - return new SynchronizedSources(command, policy); + return new SynchronizedSources(command, policy, asset); } /** Freeze both complete, selected source snapshots against the same retained operation. */ @@ -136,13 +192,14 @@ public Capture freeze(GameDesignPublicationOperation operation) { requireGenesis(operation.account().input().selection().target()); RealmPolicySnapshot.Capture policy = policies.freeze(operation); CommandSnapshot.Capture command = commands.freeze(operation); - Capture result = new Capture(command, policy); + Capture result = new Capture(command, policy, assets.freeze(operation)); Capture retained = readCapture(operation) .orElseThrow( () -> new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_UNAVAILABLE")); if (!Arrays.equals(result.command().canonicalBytes(), retained.command().canonicalBytes()) - || !Arrays.equals(result.policy().canonicalBytes(), retained.policy().canonicalBytes())) { + || !Arrays.equals(result.policy().canonicalBytes(), retained.policy().canonicalBytes()) + || !Arrays.equals(result.asset().canonicalBytes(), retained.asset().canonicalBytes())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_CONFLICT"); } return retained; @@ -153,11 +210,13 @@ public Optional readCapture(GameDesignPublicationOperation operation) { Objects.requireNonNull(operation, "operation"); var command = commands.readCapture(operation); var policy = policies.readCapture(operation); - if (command.isEmpty() && policy.isEmpty()) return Optional.empty(); - if (command.isEmpty() || policy.isEmpty()) { + var asset = assets.readCapture(operation); + if (command.isEmpty() && policy.isEmpty() && asset.isEmpty()) return Optional.empty(); + if (command.isEmpty() || policy.isEmpty() || asset.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); } - return Optional.of(new Capture(command.orElseThrow(), policy.orElseThrow())); + return Optional.of( + new Capture(command.orElseThrow(), policy.orElseThrow(), asset.orElseThrow())); } public Optional readSynchronized(TargetProof target, UUID commitId) { @@ -165,11 +224,13 @@ public Optional readSynchronized(TargetProof target, UUID c Objects.requireNonNull(commitId, "commitId"); var command = commands.readSnapshot(target, commitId); var policy = policies.readSnapshot(target, commitId); - if (command.isEmpty() && policy.isEmpty()) return Optional.empty(); - if (command.isEmpty() || policy.isEmpty()) { + var asset = assets.readSnapshot(target, commitId); + if (command.isEmpty() && policy.isEmpty() && asset.isEmpty()) return Optional.empty(); + if (command.isEmpty() || policy.isEmpty() || asset.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); } - return Optional.of(new SynchronizedSources(command.orElseThrow(), policy.orElseThrow())); + return Optional.of( + new SynchronizedSources(command.orElseThrow(), policy.orElseThrow(), asset.orElseThrow())); } private void requireGenesis(TargetProof target) { @@ -195,8 +256,8 @@ private static OwnerOutcome commandOnlyOutcome( } private static void requireCompleteScopes( - DraftCommitBinding binding, boolean hasCommand, boolean hasPolicy) { - if (!hasCommand && !hasPolicy + DraftCommitBinding binding, boolean hasCommand, boolean hasPolicy, boolean hasAsset) { + if (!hasCommand && !hasPolicy && !hasAsset || !binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE)) { throw new IllegalArgumentException("Game Design owner requires typed source revisions"); } @@ -217,9 +278,11 @@ private static void requireCompleteScopes( && RealmPolicySource.SCOPE.equals(unit.scopeType()) && "effective".equals(unit.scopeId())) .toList(); + var assets = units.stream().filter(AssetSourceRepository::isScope).toList(); if (commands.size() != (hasCommand ? 1 : 0) || policies.size() != (hasPolicy ? 1 : 0) - || commands.size() + policies.size() != units.size() + || assets.size() != (hasAsset ? 1 : 0) + || commands.size() + policies.size() + assets.size() != units.size() || units.stream() .anyMatch( unit -> @@ -244,13 +307,19 @@ private static void requireWrite() { } } - public record Genesis(RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command) { + public record Genesis( + RealmPolicyGenesis policy, + CommandSource.NewDraftGenesisReceipt command, + AssetSnapshot.Genesis asset) { public Genesis { Objects.requireNonNull(policy, "policy"); Objects.requireNonNull(command, "command"); + Objects.requireNonNull(asset, "asset"); if (!policy.target().equals(command.target()) || !policy.receiptId().equals(command.receiptId()) - || !policy.creationTransactionId().equals(command.creationTransactionId())) { + || !policy.creationTransactionId().equals(command.creationTransactionId()) + || !policy.target().equals(asset.target()) + || !policy.creationTransactionId().equals(asset.creationTransactionId())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_IDENTITY_CONFLICT"); } } @@ -260,15 +329,18 @@ public record Application( DraftCommitBinding binding, Optional command, Optional policy, + Optional asset, OwnerOutcome ownerOutcome) { public Application { Objects.requireNonNull(binding, "binding"); command = Objects.requireNonNull(command, "command"); policy = Objects.requireNonNull(policy, "policy"); + asset = Objects.requireNonNull(asset, "asset"); Objects.requireNonNull(ownerOutcome, "ownerOutcome"); - if (command.isEmpty() && policy.isEmpty() + if (command.isEmpty() && policy.isEmpty() && asset.isEmpty() || command.isPresent() && !binding.equals(command.orElseThrow().binding()) || policy.isPresent() && !binding.equals(policy.orElseThrow().snapshot().binding()) + || asset.isPresent() && !binding.equals(asset.orElseThrow().binding()) || ownerOutcome.owner() != Owner.GAME_DESIGN_CONTROL_PLANE || ownerOutcome.status() != OwnerStatus.APPLIED || !binding.commitId().equals(ownerOutcome.commitId()) @@ -278,22 +350,32 @@ public record Application( } } - public record SynchronizedSources(CommandSnapshot command, RealmPolicySnapshot policy) { + public record SynchronizedSources( + CommandSnapshot command, RealmPolicySnapshot policy, AssetSnapshot asset) { public SynchronizedSources { Objects.requireNonNull(command, "command"); Objects.requireNonNull(policy, "policy"); - if (!command.binding().equals(policy.binding())) { + Objects.requireNonNull(asset, "asset"); + if (!command.binding().equals(policy.binding()) + || !command.binding().equals(asset.binding())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_SNAPSHOT_BINDING_CONFLICT"); } } } - public record Capture(CommandSnapshot.Capture command, RealmPolicySnapshot.Capture policy) { + public record Capture( + CommandSnapshot.Capture command, + RealmPolicySnapshot.Capture policy, + AssetSnapshot.Capture asset) { public Capture { Objects.requireNonNull(command, "command"); Objects.requireNonNull(policy, "policy"); + Objects.requireNonNull(asset, "asset"); if (!Arrays.equals(command.operation().canonicalBytes(), policy.operation().canonicalBytes()) - || !command.snapshot().binding().equals(policy.snapshot().binding())) { + || !command.snapshot().binding().equals(policy.snapshot().binding()) + || !command.snapshot().binding().equals(asset.snapshot().binding()) + || !Arrays.equals( + command.operation().canonicalBytes(), asset.operation().canonicalBytes())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_BINDING_CONFLICT"); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java index 504e5cc3e9..323b46e342 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java @@ -43,7 +43,7 @@ public record Policy( public static boolean isPolicyRevision(DraftCommitBinding.RevisionPayload input) { var kind = text(tree(input.payload()), "revisionKind"); if (RealmEntryPolicy.REVISION_KIND.equals(kind)) return true; - if ("COMMAND_DEFINITION".equals(kind)) return false; + if ("COMMAND_DEFINITION".equals(kind) || AssetSource.REVISION_KIND.equals(kind)) return false; throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java index 3e3dbf202c..f710774553 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java @@ -13,6 +13,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import net.firedevops.firemud.gamedesign.publication.AssetSourceRepository; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; @@ -37,64 +38,13 @@ public VersionAssetPublicationRepository(DSLContext dsl) { } /** - * Associates an ordinary source asset with an exact tenant-owned Draft Version. Numeric ids in - * this method are private Game Design owner keys and are not public identity aliases. The caller - * must hold a writable READ_COMMITTED transaction. + * Rejects the former direct-mapping path. Ordinary references must be authored in an exact Draft + * commit; only synchronized source projection can populate version_asset. */ public void associateDraftAsset(String tenantId, long versionId, long assetId, String usageType) { requireWritableReadCommittedTransaction(); - requireTenantId(tenantId); - if (versionId <= 0 || assetId <= 0) { - throw new IllegalArgumentException("Version and asset owner keys must be positive"); - } - - VersionRow version = - lockVersionByTenantAndId(tenantId, versionId) - .orElseThrow(() -> new IllegalStateException("Exact tenant Version row was not found")); - qualifyVersion(version); - requireDraft(version); - requireNoSnapshot(tenantId, versionId); - - AssetRow asset = - findAssetForUpdate(tenantId, assetId) - .orElseThrow( - () -> new IllegalStateException("Exact tenant game asset row was not found")); - validateUsageKey(asset.fileName()); - - Record existing = - dsl.fetchOne( - "SELECT usage_key, usage_type FROM version_asset " - + "WHERE tenant_id = ? AND version_id = ? AND asset_id = ?", - tenantId, - versionId, - assetId); - if (existing != null) { - if (Objects.equals(existing.get("usage_key", String.class), asset.fileName()) - && Objects.equals(existing.get("usage_type", String.class), usageType)) { - return; - } - throw new IllegalStateException("Conflicting Version asset association already exists"); - } - - Record usageCollision = - dsl.fetchOne( - "SELECT asset_id FROM version_asset " - + "WHERE tenant_id = ? AND version_id = ? AND usage_key = ?", - tenantId, - versionId, - asset.fileName()); - if (usageCollision != null) { - throw new IllegalStateException("Version asset usage key is already mapped to another asset"); - } - - dsl.execute( - "INSERT INTO version_asset " - + "(tenant_id, version_id, asset_id, usage_key, usage_type) VALUES (?, ?, ?, ?, ?)", - tenantId, - versionId, - assetId, - asset.fileName(), - usageType); + throw new IllegalStateException( + "Version asset associations require synchronized ASSET_REFERENCE source projection"); } /** @@ -112,6 +62,7 @@ public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { lockVersionByTenantAndVersionNumber(tenantId, versionNumber) .orElseThrow(() -> new IllegalStateException("Exact tenant Version was not found")); qualifyVersion(version); + new AssetSourceRepository(dsl).requireExportSelection(tenantId, version.id()); if (hasSnapshot(tenantId, version.id())) { return readSnapshot(version); @@ -294,6 +245,24 @@ private ExportSnapshot readSnapshot(VersionRow version) { new AssetSelection(usageKey, snapshotAssetId, sourceData, sourceType, snapshotDigest)); } items.sort(Comparator.comparing(AssetSelection::usageKey, UTF8_BYTE_ORDER)); + var ordinary = + new AssetSourceRepository(dsl).requireExportSelection(version.tenantId(), version.id()); + if (ordinary.items().size() != items.size()) { + throw new IllegalStateException( + "Frozen export differs from synchronized ordinary asset source"); + } + for (int index = 0; index < items.size(); index++) { + var retained = ordinary.items().get(index); + var exported = items.get(index); + if (!retained.reference().usageKey().equals(exported.usageKey()) + || Long.parseLong(retained.reference().assetRowId()) != exported.assetId() + || !retained.contentType().equals(exported.contentType()) + || !retained.contentDigest().equals(exported.contentDigest()) + || retained.byteSize() != exported.bytes().length) { + throw new IllegalStateException( + "Frozen export differs from synchronized ordinary asset source"); + } + } return new ExportSnapshot( version.tenantId(), @@ -325,28 +294,6 @@ private List lockMappedSourceAssets(String tenantId, long versionId row.get("data", byte[].class))); } - private Optional findAssetForUpdate(String tenantId, long assetId) { - Record row = - dsl.fetchOne( - "SELECT file_name FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", - tenantId, - assetId); - if (row == null) { - return Optional.empty(); - } - return Optional.of(new AssetRow(row.get("file_name", String.class))); - } - - private Optional lockVersionByTenantAndId(String tenantId, long versionId) { - return readVersion( - "SELECT id, tenant_id, version_number, version_state, version_state_epoch, " - + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, " - + "identity_source_game_tenant_key, identity_source_provenance_kind " - + "FROM version WHERE tenant_id = ? AND id = ? FOR UPDATE", - tenantId, - versionId); - } - private Optional lockVersionByTenantAndVersionNumber( String tenantId, int versionNumber) { return readVersion( @@ -444,13 +391,6 @@ private void requireDraft(VersionRow version) { } } - private void requireNoSnapshot(String tenantId, long versionId) { - if (hasSnapshot(tenantId, versionId)) { - throw new IllegalStateException( - "Version asset mappings are frozen by the durable export snapshot"); - } - } - private boolean hasSnapshot(String tenantId, long versionId) { return dsl.fetchOne( "SELECT 1 FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", @@ -535,8 +475,6 @@ private record VersionRow( String identitySourceGameTenantKey, String identitySourceProvenanceKind) {} - private record AssetRow(String fileName) {} - private record SourceAsset( String usageKey, Long assetId, String fileName, String contentType, byte[] bytes) {} diff --git a/services/game-design-service/src/main/resources/db/migration/V55__ordinary_asset_source.sql b/services/game-design-service/src/main/resources/db/migration/V55__ordinary_asset_source.sql new file mode 100644 index 0000000000..6771f1b0b2 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V55__ordinary_asset_source.sql @@ -0,0 +1,389 @@ +-- Ordinary source only. These records never attest total asset-family completeness. +CREATE TABLE game_design_asset_source_genesis ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + version_id BIGINT NOT NULL UNIQUE, receipt_id UUID NOT NULL UNIQUE, + creation_transaction_id TEXT NOT NULL, target_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (version_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id), + FOREIGN KEY (version_id) REFERENCES game_design_realm_policy_version_insert (version_id), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); +CREATE TABLE game_design_asset_source_application ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, expected_epoch TEXT NOT NULL, + snapshot_json TEXT NOT NULL, result_bytes BYTEA NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), CHECK (octet_length(result_bytes) > 0) +); +CREATE TABLE game_design_asset_source_revision ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, revision_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), operation_kind VARCHAR(16) NOT NULL, + usage_key VARCHAR(255) NOT NULL, asset_id BIGINT, requiredness VARCHAR(16), + content_type VARCHAR(100), content_digest VARCHAR(71), byte_size BIGINT, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_asset_source_application (canonical_tenant_id, canonical_version_id, commit_id) + DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (asset_id) REFERENCES game_assets (id), + CHECK (usage_key !~ '^[[:space:]]*$' AND usage_key <> 'manifest.json'), + CHECK ((operation_kind = 'UPSERT' AND asset_id > 0 AND requiredness = 'REQUIRED' + AND content_type IS NOT NULL AND content_type !~ '^[[:space:]]*$' + AND content_digest ~ '^sha256:[0-9a-f]{64}$' AND byte_size >= 0) + OR (operation_kind = 'DELETE' AND asset_id IS NULL AND requiredness IS NULL + AND content_type IS NULL AND content_digest IS NULL AND byte_size IS NULL)) +); +CREATE TABLE game_design_asset_source_snapshot ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, snapshot_json TEXT NOT NULL, + snapshot_digest VARCHAR(71) NOT NULL CHECK (snapshot_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit_visibility_fence (canonical_tenant_id, canonical_version_id, request_id, commit_id) +); +CREATE TABLE game_design_asset_source_head ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + genesis_receipt_id UUID NOT NULL REFERENCES game_design_asset_source_genesis (receipt_id), + applied_commit_id UUID, visible_commit_id UUID, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_asset_source_genesis (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, applied_commit_id) + REFERENCES game_design_asset_source_application (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_asset_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); +CREATE TABLE game_design_asset_source_capture ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE REFERENCES game_design_publication_operation (publish_workflow_id), + commit_id UUID NOT NULL, operation_bytes BYTEA NOT NULL, capture_bytes BYTEA NOT NULL, + capture_digest VARCHAR(71) NOT NULL CHECK (capture_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_asset_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION ordinary_asset_revision_item(r game_design_asset_source_revision) RETURNS JSONB AS $$ + SELECT jsonb_build_object('family', 'ORDINARY', 'role', 'RESOURCE', 'usageKey', r.usage_key, + 'assetRowId', r.asset_id::TEXT, 'requiredness', r.requiredness, + 'sourceBindingJson', c.binding_json, 'sourceBindingDigest', c.input_digest, + 'revisionOrder', r.revision_order::TEXT, 'revisionId', r.revision_id::TEXT, + 'contentType', r.content_type, 'contentDigest', r.content_digest, 'byteSize', r.byte_size::TEXT) + FROM game_design_draft_commit c WHERE c.canonical_tenant_id = r.canonical_tenant_id + AND c.canonical_version_id = r.canonical_version_id AND c.request_id = r.request_id AND c.commit_id = r.commit_id; +$$ LANGUAGE SQL STABLE; + +CREATE FUNCTION guard_ordinary_asset_source() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; g game_design_asset_source_genesis%ROWTYPE; + h game_design_asset_source_head%ROWTYPE; c game_design_draft_commit%ROWTYPE; + a game_design_asset_source_application%ROWTYPE; op game_design_publication_operation%ROWTYPE; + s game_design_asset_source_snapshot%ROWTYPE; selected game_design_authored_draft_publish_selection%ROWTYPE; + asset game_assets%ROWTYPE; revision JSONB; payload JSONB; prior JSONB; expected_items JSONB; + snapshot JSONB; expected BYTEA; bytes BYTEA; count_declared BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'ordinary asset source history is immutable' USING ERRCODE = '23514'; END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL OR v.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'ordinary source requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'game_design_asset_source_genesis' THEN + IF TG_OP <> 'INSERT' OR v.id <> NEW.version_id OR v.version_state_epoch <> 1 + OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_version_insert w WHERE w.version_id = v.id + AND w.creation_transaction_id = NEW.creation_transaction_id) + OR NEW.target_json::JSONB IS DISTINCT FROM jsonb_build_object( + 'canonicalTenantId', v.canonical_tenant_id::TEXT, 'canonicalVersionId', v.canonical_version_id::TEXT, + 'gameDesignVersionRowId', v.id, 'gameDesignVersionTenantKey', v.tenant_id, + 'sourceGameRowId', v.identity_source_game_row_id, + 'sourceGameTenantKey', v.identity_source_game_tenant_key, 'sourceProvenanceKind', v.identity_source_provenance_kind) + OR EXISTS (SELECT 1 FROM version_asset va WHERE va.tenant_id = v.tenant_id AND va.version_id = v.id) + OR EXISTS (SELECT 1 FROM game_design_draft_commit c0 WHERE c0.canonical_tenant_id = NEW.canonical_tenant_id AND c0.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'ordinary genesis requires its actual fresh Version insertion' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT g FROM game_design_asset_source_genesis WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF TG_TABLE_NAME = 'game_design_asset_source_head' AND TG_OP = 'INSERT' THEN + IF NEW.source_epoch <> '0' OR NEW.applied_commit_id IS NOT NULL OR NEW.visible_commit_id IS NOT NULL OR NEW.genesis_receipt_id <> g.receipt_id THEN + RAISE EXCEPTION 'ordinary head requires exact fresh baseline' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT h FROM game_design_asset_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF TG_TABLE_NAME <> 'game_design_asset_source_capture' AND ( + EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id)) THEN + RAISE EXCEPTION 'ordinary source is frozen by selected publication or export' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_asset_source_head' THEN + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.genesis_receipt_id IS DISTINCT FROM OLD.genesis_receipt_id THEN + RAISE EXCEPTION 'ordinary head identity immutable' USING ERRCODE = '23514'; END IF; + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + SELECT * INTO STRICT a FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.applied_commit_id; + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 OR a.expected_epoch <> OLD.source_epoch + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN RAISE EXCEPTION 'ordinary staged epoch mismatch' USING ERRCODE = '23514'; END IF; + ELSIF NEW.applied_commit_id IS DISTINCT FROM OLD.applied_commit_id THEN RAISE EXCEPTION 'ordinary staged pointer mismatch' USING ERRCODE = '23514'; END IF; + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + SELECT * INTO STRICT s FROM game_design_asset_source_snapshot WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.visible_commit_id; + IF s.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR s.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(OLD.visible_commit_id::TEXT, '') THEN + RAISE EXCEPTION 'ordinary visible pointer mismatch' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'ordinary source history is immutable' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_asset_source_capture' THEN + SELECT * INTO STRICT op FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selected FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT s FROM game_design_asset_source_snapshot WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-ordinary-asset-source-capture/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + expected := expected || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + bytes := convert_to(s.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF op.outcome <> 'PENDING' OR op.request_bytes IS DISTINCT FROM NEW.operation_bytes OR op.version_id <> v.id OR op.tenant_id <> v.tenant_id + OR op.selection_digest <> selected.selection_digest OR selected.selected_commit_id <> NEW.commit_id + OR selected.version_state_epoch <> v.version_state_epoch OR h.visible_commit_id IS DISTINCT FROM NEW.commit_id + OR h.source_epoch IS DISTINCT FROM s.snapshot_json::JSONB->>'sourceEpoch' + OR expected IS DISTINCT FROM NEW.capture_bytes OR NEW.capture_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.capture_bytes), 'hex') THEN + RAISE EXCEPTION 'ordinary capture lacks exact selected operation/source' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF TG_TABLE_NAME IN ('game_design_asset_source_revision', 'game_design_asset_source_application') THEN + IF NOT EXISTS (SELECT 1 FROM game_design_draft_commit_application_slot slot WHERE slot.canonical_tenant_id = NEW.canonical_tenant_id AND slot.canonical_version_id = NEW.canonical_version_id AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_owner_result r WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id AND r.request_id = NEW.request_id AND r.owner = 'GAME_DESIGN_CONTROL_PLANE' AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'ordinary source write requires active coordinator application' USING ERRCODE = '23514'; END IF; + END IF; + IF TG_TABLE_NAME = 'game_design_asset_source_revision' THEN + SELECT r INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r WHERE r->>'revisionId' = NEW.revision_id::TEXT AND r->>'revisionOrder' = NEW.revision_order::TEXT AND r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + payload := (revision->>'payload')::JSONB; + IF (SELECT count(*) FROM json_object_keys((revision->>'payload')::JSON)) <> + (SELECT count(*) FROM jsonb_object_keys(payload)) + OR (revision->>'payload')::JSON->>'schemaVersion' IS DISTINCT FROM '1' + OR payload->>'revisionKind' IS DISTINCT FROM 'ASSET_REFERENCE' OR payload->'schemaVersion' IS DISTINCT FROM '1'::JSONB + OR payload->>'family' IS DISTINCT FROM 'ORDINARY' OR payload->>'role' IS DISTINCT FROM 'RESOURCE' + OR payload->>'operation' IS DISTINCT FROM NEW.operation_kind OR payload->>'usageKey' IS DISTINCT FROM NEW.usage_key + OR jsonb_typeof(payload->'usageKey') IS DISTINCT FROM 'string' THEN RAISE EXCEPTION 'ordinary revision differs from exact payload' USING ERRCODE = '23514'; END IF; + IF NEW.operation_kind = 'UPSERT' THEN + SELECT * INTO STRICT asset FROM game_assets WHERE id = NEW.asset_id AND tenant_id = v.tenant_id FOR UPDATE; + IF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 8 OR jsonb_typeof(payload->'assetRowId') IS DISTINCT FROM 'string' + OR payload->>'assetRowId' IS DISTINCT FROM NEW.asset_id::TEXT OR payload->>'requiredness' IS DISTINCT FROM 'REQUIRED' + OR NEW.requiredness IS DISTINCT FROM 'REQUIRED' OR asset.file_name IS DISTINCT FROM NEW.usage_key + OR asset.content_type IS DISTINCT FROM NEW.content_type OR asset.data IS NULL + OR NEW.content_digest IS DISTINCT FROM 'sha256:' || encode(sha256(asset.data), 'hex') OR NEW.byte_size IS DISTINCT FROM octet_length(asset.data)::BIGINT THEN + RAISE EXCEPTION 'ordinary RESOURCE requires exact required source bytes' USING ERRCODE = '23514'; END IF; + ELSIF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 6 THEN RAISE EXCEPTION 'ordinary DELETE fields invalid' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + snapshot := NEW.snapshot_json::JSONB; + IF snapshot->>'schema' IS DISTINCT FROM 'game-design-ordinary-asset-source-snapshot/v1' + OR snapshot->>'bindingJson' IS DISTINCT FROM c.binding_json OR snapshot->>'bindingDigest' IS DISTINCT FROM c.input_digest + OR snapshot->>'genesisReceiptId' IS DISTINCT FROM g.receipt_id::TEXT + OR snapshot->>'inheritedCommitId' IS DISTINCT FROM coalesce(h.visible_commit_id::TEXT, '') + OR jsonb_typeof(snapshot->'items') IS DISTINCT FROM 'array' + OR (SELECT count(*) FROM jsonb_object_keys(snapshot)) <> 7 THEN RAISE EXCEPTION 'ordinary snapshot binding invalid' USING ERRCODE = '23514'; END IF; + SELECT s0.snapshot_json::JSONB->'items' INTO prior FROM game_design_asset_source_snapshot s0 WHERE s0.canonical_tenant_id = NEW.canonical_tenant_id AND s0.canonical_version_id = NEW.canonical_version_id AND s0.commit_id = h.visible_commit_id; + prior := coalesce(prior, '[]'::JSONB); + IF TG_TABLE_NAME = 'game_design_asset_source_application' THEN + IF NEW.expected_epoch IS DISTINCT FROM h.source_epoch OR snapshot->>'sourceEpoch' IS DISTINCT FROM (h.source_epoch::NUMERIC + 1)::TEXT + OR NOT (c.binding_json::JSONB->'affectedUnits' @> jsonb_build_array(jsonb_build_object('owner', 'GAME_DESIGN_CONTROL_PLANE', + 'aggregateType', 'ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, + 'scopeType', 'ASSET_REFERENCE_SET', 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch))) THEN + RAISE EXCEPTION 'ordinary application lacks exact scope epoch' USING ERRCODE = '23514'; END IF; + WITH choices AS ( + SELECT item->>'usageKey' AS key, -1 AS ord, FALSE AS deleted, item FROM jsonb_array_elements(prior) item + UNION ALL SELECT r.usage_key, r.revision_order, r.operation_kind = 'DELETE', ordinary_asset_revision_item(r) + FROM game_design_asset_source_revision r WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id AND r.commit_id = NEW.commit_id + ), final AS (SELECT DISTINCT ON (key) * FROM choices ORDER BY key, ord DESC) + SELECT coalesce(jsonb_agg(item ORDER BY convert_to(key, 'UTF8')) FILTER (WHERE NOT deleted), '[]'::JSONB) INTO expected_items FROM final; + IF expected_items IS DISTINCT FROM snapshot->'items' + OR (SELECT count(DISTINCT item->>'assetRowId') FROM jsonb_array_elements(expected_items) item) <> jsonb_array_length(expected_items) THEN + RAISE EXCEPTION 'ordinary application must replay exact source without aliases' USING ERRCODE = '23514'; END IF; + ELSE + SELECT * INTO a FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT count(*) INTO count_declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r WHERE r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (r->>'payload')::JSONB->>'revisionKind' = 'ASSET_REFERENCE'; + IF (count_declared > 0) IS DISTINCT FROM (a.commit_id IS NOT NULL) + OR snapshot->>'sourceEpoch' IS DISTINCT FROM h.source_epoch + OR (a.commit_id IS NOT NULL AND a.snapshot_json IS DISTINCT FROM NEW.snapshot_json) + OR (a.commit_id IS NULL AND snapshot->'items' IS DISTINCT FROM prior) + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR c.workflow_state <> 'SYNCHRONIZED' + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility f WHERE f.canonical_tenant_id = NEW.canonical_tenant_id AND f.canonical_version_id = NEW.canonical_version_id AND f.request_id = NEW.request_id AND f.commit_id = NEW.commit_id AND f.input_digest = c.input_digest) THEN + RAISE EXCEPTION 'ordinary snapshot requires exact synchronized source inheritance' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION verify_ordinary_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_asset_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; declared BIGINT; retained BIGINT; + components BYTEA; command_bytes BYTEA; policy_bytes BYTEA; epochs JSONB; unit JSONB; +BEGIN + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT r FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT h FROM game_design_asset_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_asset_source_revision x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id AND x.commit_id = NEW.commit_id; + bytes := convert_to('game-design-ordinary-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR r.status <> 'APPLIED' OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id + OR expected IS DISTINCT FROM NEW.result_bytes OR NOT (r.applied_units_json::JSONB @> jsonb_build_array(jsonb_build_object( + 'aggregateType', 'ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, 'scopeType', 'ASSET_REFERENCE_SET', + 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch, 'resultingEpoch', h.source_epoch))) THEN + RAISE EXCEPTION 'ordinary application requires atomic combined owner outcome' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); + components := int4send(octet_length(bytes)) || bytes; + epochs := '[]'::JSONB; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF command_bytes IS NOT NULL THEN + bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; + END IF; + bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + SELECT result_bytes INTO policy_bytes FROM game_design_realm_policy_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND coalesce((x->>'payload')::JSONB->>'revisionKind', '') NOT IN ('COMMAND_DEFINITION', 'REALM_ENTRY_POLICY', 'ASSET_REFERENCE')) + OR (command_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION') + OR (policy_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'REALM_ENTRY_POLICY') THEN + RAISE EXCEPTION 'ordinary mixed application requires every declared supported sibling source' USING ERRCODE = '23514'; END IF; + -- The vector has one entry per exact declared local scope, ordered as the Java composition. + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' + LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' + OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'ordinary combined scope unknown' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); + expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs + OR jsonb_array_length(epochs) <> (1 + CASE WHEN command_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN policy_bytes IS NULL THEN 0 ELSE 1 END) THEN + RAISE EXCEPTION 'ordinary combined outcome must contain exact tagged components and complete epochs' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER ordinary_asset_genesis_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_genesis FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE TRIGGER ordinary_asset_head_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_head FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE TRIGGER ordinary_asset_revision_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_revision FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE TRIGGER ordinary_asset_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_application FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE TRIGGER ordinary_asset_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_snapshot FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE TRIGGER ordinary_asset_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_asset_source_capture FOR EACH ROW EXECUTE FUNCTION guard_ordinary_asset_source(); +CREATE CONSTRAINT TRIGGER ordinary_asset_application_commit_guard AFTER INSERT ON game_design_asset_source_application DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_ordinary_asset_application_commit(); + +CREATE FUNCTION project_synchronized_ordinary_assets() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; item JSONB; +BEGIN + SELECT * INTO STRICT v FROM version WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + DELETE FROM version_asset WHERE tenant_id = v.tenant_id AND version_id = v.id; + FOR item IN SELECT * FROM jsonb_array_elements(NEW.snapshot_json::JSONB->'items') LOOP + INSERT INTO version_asset (tenant_id, version_id, asset_id, usage_key, usage_type) + VALUES (v.tenant_id, v.id, (item->>'assetRowId')::BIGINT, item->>'usageKey', NULL); + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER ordinary_asset_snapshot_projection AFTER INSERT ON game_design_asset_source_snapshot FOR EACH ROW EXECUTE FUNCTION project_synchronized_ordinary_assets(); + +CREATE FUNCTION require_ordinary_asset_projection() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; s game_design_asset_source_snapshot%ROWTYPE; tenant_key TEXT; version_key BIGINT; +BEGIN + tenant_key := CASE WHEN TG_OP = 'DELETE' THEN OLD.tenant_id ELSE NEW.tenant_id END; + version_key := CASE WHEN TG_OP = 'DELETE' THEN OLD.version_id ELSE NEW.version_id END; + SELECT * INTO STRICT v FROM version WHERE tenant_id = tenant_key AND id = version_key FOR UPDATE; + SELECT source.* INTO s FROM game_design_asset_source_snapshot source JOIN game_design_draft_commit_visibility f + USING (canonical_tenant_id, canonical_version_id, request_id, commit_id) + WHERE source.canonical_tenant_id = v.canonical_tenant_id AND source.canonical_version_id = v.canonical_version_id; + IF pg_trigger_depth() < 2 OR s.commit_id IS NULL OR TG_OP = 'UPDATE' + OR EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection selected WHERE selected.canonical_tenant_id = v.canonical_tenant_id AND selected.canonical_version_id = v.canonical_version_id) + OR (TG_OP = 'INSERT' AND (NEW.usage_type IS NOT NULL OR NOT EXISTS ( + SELECT 1 FROM jsonb_array_elements(s.snapshot_json::JSONB->'items') item WHERE item->>'assetRowId' = NEW.asset_id::TEXT AND item->>'usageKey' = NEW.usage_key))) THEN + RAISE EXCEPTION 'version_asset writes require exact synchronized ordinary source projection' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER ordinary_asset_mapping_projection_guard BEFORE INSERT OR UPDATE OR DELETE ON version_asset FOR EACH ROW EXECUTE FUNCTION require_ordinary_asset_projection(); + +CREATE FUNCTION require_ordinary_asset_export_source() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; s game_design_asset_source_snapshot%ROWTYPE; +BEGIN + SELECT * INTO STRICT v FROM version WHERE tenant_id = NEW.tenant_id AND id = NEW.version_id FOR UPDATE; + SELECT source.* INTO STRICT s FROM game_design_asset_source_snapshot source + JOIN game_design_asset_source_head h USING (canonical_tenant_id, canonical_version_id) + JOIN game_design_draft_commit_visibility f USING (canonical_tenant_id, canonical_version_id) + WHERE source.canonical_tenant_id = v.canonical_tenant_id AND source.canonical_version_id = v.canonical_version_id + AND source.commit_id = h.visible_commit_id AND source.commit_id = f.commit_id + AND source.request_id = f.request_id + AND source.snapshot_json::JSONB->>'sourceEpoch' = h.source_epoch; + IF TG_TABLE_NAME = 'version_asset_export_snapshot' THEN + IF NEW.item_count <> jsonb_array_length(s.snapshot_json::JSONB->'items') THEN + RAISE EXCEPTION 'export requires exact synchronized ordinary source' USING ERRCODE = '23514'; END IF; + ELSIF NOT EXISTS (SELECT 1 FROM jsonb_array_elements(s.snapshot_json::JSONB->'items') item + WHERE item->>'usageKey' = NEW.usage_key AND item->>'assetRowId' = NEW.asset_id::TEXT + AND item->>'contentType' = NEW.content_type AND item->>'contentDigest' = NEW.content_hash + AND item->>'byteSize' = NEW.byte_size::TEXT) THEN + RAISE EXCEPTION 'export item differs from synchronized ordinary source' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER ordinary_asset_export_snapshot_source_guard BEFORE INSERT ON version_asset_export_snapshot FOR EACH ROW EXECUTE FUNCTION require_ordinary_asset_export_source(); +CREATE TRIGGER ordinary_asset_export_item_source_guard BEFORE INSERT ON version_asset_export_item FOR EACH ROW EXECUTE FUNCTION require_ordinary_asset_export_source(); + +CREATE FUNCTION protect_ordinary_asset_bytes() RETURNS TRIGGER AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_asset_source_revision r WHERE r.asset_id = OLD.id) AND + (TG_OP = 'DELETE' OR NEW IS DISTINCT FROM OLD) THEN + RAISE EXCEPTION 'ordinary asset source bytes are immutable from source history' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER ordinary_asset_byte_history_guard BEFORE UPDATE OR DELETE ON game_assets FOR EACH ROW EXECUTE FUNCTION protect_ordinary_asset_bytes(); + +CREATE FUNCTION deny_ordinary_asset_truncate() RETURNS TRIGGER AS $$ +BEGIN RAISE EXCEPTION 'ordinary asset source history/projection cannot be truncated' USING ERRCODE = '23514'; END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER ordinary_asset_genesis_no_truncate BEFORE TRUNCATE ON game_design_asset_source_genesis EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_head_no_truncate BEFORE TRUNCATE ON game_design_asset_source_head EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_revision_no_truncate BEFORE TRUNCATE ON game_design_asset_source_revision EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_application_no_truncate BEFORE TRUNCATE ON game_design_asset_source_application EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_snapshot_no_truncate BEFORE TRUNCATE ON game_design_asset_source_snapshot EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_capture_no_truncate BEFORE TRUNCATE ON game_design_asset_source_capture EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_mapping_no_truncate BEFORE TRUNCATE ON version_asset EXECUTE FUNCTION deny_ordinary_asset_truncate(); +CREATE TRIGGER ordinary_asset_bytes_no_truncate BEFORE TRUNCATE ON game_assets EXECUTE FUNCTION deny_ordinary_asset_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index 76a8b8d57f..ccc3d4606b 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -13,6 +13,7 @@ import net.firedevops.firemud.gamedesign.model.PublishType; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.AssetSource; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; @@ -30,6 +31,65 @@ public final class IsolatedPublicationOwnerSetup { private IsolatedPublicationOwnerSetup() {} + /** Actual ordinary source/coordinator transaction; does not stipulate complete inventory. */ + public static DraftCommitBinding applyOrdinaryReferences( + DSLContext dsl, DraftCommitBinding.TargetProof target, List payloads) { + var head = + dsl.fetchOne( + "SELECT source_epoch FROM game_design_asset_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (head == null) throw new IllegalStateException("ASSET_SOURCE_GENESIS_UNAVAILABLE"); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + var prior = coordinator.readVisibilityFence(target); + var revisions = new java.util.ArrayList(); + for (int index = 0; index < payloads.size(); index++) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(index), + java.util.UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payloads.get(index))); + } + var binding = + DraftCommitBinding.create( + target, + java.util.UUID.randomUUID(), + java.util.UUID.randomUUID(), + prior.map(value -> value.commitId().toString()).orElse("base-commit-0"), + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + target.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + head.get("source_epoch", String.class)))); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = new GameDesignSourceRepository(dsl).apply(binding); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(applied.ownerOutcome()))); + coordinator.releaseApplicationSlot(binding); + return binding; + } + + /** + * Fixture-only source visibility advance; the coordinator still validates every exact outcome. + */ + public static void advanceSourceVisibility( + DSLContext dsl, + DraftCommitBinding binding, + List outcomes) { + new DraftCommitCoordinatorRepository(dsl) + .advanceSourceVisibilityFence( + binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + } + /** Fixture-only visibility advance; supplied owner authority remains explicitly isolated. */ public static void advanceIsolatedVisibility( DSLContext dsl, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java index a4fad5cd97..f36f293f7b 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java @@ -9,14 +9,26 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.sql.SQLException; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.AssetSource; +import net.firedevops.firemud.gamedesign.publication.AssetSourceRepository; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; @@ -30,6 +42,8 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -164,6 +178,365 @@ void exactTenantVersionMappingsExcludeUnmappedAssetsAndSnapshotSurvivesRepositor } } + @Test + void ordinarySourceIsImmutableBeforeExportAndCannotBeBypassedByRepositoryOrSql() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "ordinary-source"); + Version version = saveDraftVersion(fixture, owner, 1); + GameAsset asset = saveAsset(fixture, owner, "resource.png", "source-bytes"); + assertThatThrownBy( + () -> + inTransaction( + fixture, + () -> + fixture + .publicationRepository() + .freezeOrReadSnapshot(owner.getTenantId(), 1))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> { + fixture + .publicationRepository() + .associateDraftAsset( + owner.getTenantId(), version.getId(), asset.getId(), null); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synchronized ASSET_REFERENCE"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO version_asset (tenant_id, version_id, asset_id, usage_key) VALUES (?, ?, ?, ?)", + owner.getTenantId(), + version.getId(), + asset.getId(), + asset.getFileName())) + .rootCause() + .isInstanceOf(SQLException.class); + associate(fixture, owner.getTenantId(), version.getId(), asset.getId()); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_assets SET data = ? WHERE id = ?", + new byte[] {9}, + asset.getId())) + .rootCause() + .isInstanceOf(SQLException.class) + .hasMessageContaining("immutable from source history"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM version_asset_export_snapshot") + .get(0, Long.class)) + .isZero(); + } + + @Test + void mixedCommandAssetOutcomeRetriesExactlyAndDisjointCommandInheritsWithoutAssetEpochAdvance() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "mixed-source"); + Version version = saveDraftVersion(fixture, owner, 1); + GameAsset asset = saveAsset(fixture, owner, "resource.png", "source-bytes"); + var binding = + sourceBinding( + fixture, + version, + CommandSource.deletePayload("not-present"), + AssetSource.upsertPayload( + asset.getId().toString(), asset.getFileName(), AssetSource.Requiredness.REQUIRED)); + var applied = inTransaction(fixture, () -> applySources(fixture, binding)); + assertThat(applied.ownerOutcome().appliedEpochs()).hasSize(2); + assertThat(applied.command()).isPresent(); + assertThat(applied.asset()).isPresent(); + var replay = + inTransaction(fixture, () -> new GameDesignSourceRepository(fixture.dsl()).apply(binding)); + assertThat(replay.ownerOutcome()).isEqualTo(applied.ownerOutcome()); + var changed = + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.deletePayload(asset.getFileName()))), + binding.affectedUnits()); + assertThatThrownBy( + () -> + inTransaction( + fixture, () -> new GameDesignSourceRepository(fixture.dsl()).apply(changed))) + .isInstanceOf(IllegalArgumentException.class); + var disjoint = + sourceBinding(fixture, version, CommandSource.deletePayload("still-not-present")); + inTransaction(fixture, () -> applySources(fixture, disjoint)); + var inherited = + new AssetSourceRepository(fixture.dsl()) + .readSnapshot(disjoint.target(), disjoint.commitId()) + .orElseThrow(); + assertThat(inherited.sourceEpoch()).isEqualTo("1"); + assertThat(inherited.items()).isEqualTo(applied.asset().orElseThrow().snapshot().items()); + assertThat(inherited.items().getFirst().reference().sourceBinding()).isEqualTo(binding); + var deletion = sourceBinding(fixture, version, AssetSource.deletePayload(asset.getFileName())); + inTransaction(fixture, () -> applySources(fixture, deletion)); + assertThat(mappingCount(fixture, owner.getTenantId(), version.getId())).isZero(); + assertThat( + new AssetSourceRepository(fixture.dsl()) + .readSnapshot(deletion.target(), deletion.commitId()) + .orElseThrow() + .sourceEpoch()) + .isEqualTo("2"); + assertThatThrownBy( + () -> fixture.dsl().execute("DELETE FROM game_assets WHERE id = ?", asset.getId())) + .rootCause() + .isInstanceOf(SQLException.class); + } + + @Test + void policyCommandAndAssetShareOneExactOwnerOutcomeAndSynchronizedSnapshot() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "all-local-sources"); + Version version = saveDraftVersion(fixture, owner, 1); + GameAsset asset = saveAsset(fixture, owner, "resource.png", "source-bytes"); + String reference = + AssetSource.upsertPayload( + asset.getId().toString(), asset.getFileName(), AssetSource.Requiredness.REQUIRED); + var target = sourceBinding(fixture, version, reference).target(); + // Only the policy input is borrowed; no Account or World authority is claimed by this test. + String policy = + IsolatedPublicationOperationFixtures.fresh(target) + .account() + .input() + .selection() + .selectedCommit() + .revisions() + .stream() + .filter( + revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) + .map(DraftCommitBinding.RevisionPayload::payload) + .filter(payload -> payload.contains("REALM_ENTRY_POLICY")) + .findFirst() + .orElseThrow(); + var binding = + sourceBinding( + fixture, version, CommandSource.deletePayload("not-present"), reference, policy); + var result = inTransaction(fixture, () -> applySources(fixture, binding)); + assertThat(result.ownerOutcome().resultIdentity()) + .isEqualTo("control-plane-source:" + binding.commitId()); + assertThat(result.ownerOutcome().appliedEpochs()) + .extracting(DraftCommitCoordinatorRepository.AppliedEpoch::aggregateType) + .containsExactly(AssetSource.SCOPE, CommandSource.SCOPE, RealmPolicySource.SCOPE); + var readback = + new GameDesignSourceRepository(fixture.dsl()) + .readSynchronized(target, binding.commitId()) + .orElseThrow(); + assertThat(readback.asset()).isEqualTo(result.asset().orElseThrow().snapshot()); + assertThat(readback.command()).isEqualTo(result.command().orElseThrow().snapshot()); + assertThat(readback.policy()).isEqualTo(result.policy().orElseThrow().snapshot()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void stagedOrdinaryApplicationCannotCommitWithoutItsCompleteAppliedOwnerOutcome(boolean unknown) { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "partial-source"); + Version version = saveDraftVersion(fixture, owner, 1); + GameAsset asset = saveAsset(fixture, owner, "resource.png", "source-bytes"); + var binding = + sourceBinding( + fixture, + version, + AssetSource.upsertPayload( + asset.getId().toString(), asset.getFileName(), AssetSource.Requiredness.REQUIRED)); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> { + var coordinator = new DraftCommitCoordinatorRepository(fixture.dsl()); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + new AssetSourceRepository(fixture.dsl()).apply(binding).orElseThrow(); + if (unknown) { + coordinator.recordOwnerOutcome( + binding, + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN, + binding.commitId(), + binding.digest(), + null, + null, + List.of())); + } + assertThat( + new AssetSourceRepository(fixture.dsl()) + .readSnapshot(binding.target(), binding.commitId())) + .isEmpty(); + assertThatThrownBy( + () -> + new AssetSourceRepository(fixture.dsl()) + .requireExportSelection( + owner.getTenantId(), version.getId())) + .isInstanceOf(IllegalStateException.class); + return null; + })) + .rootCause() + .isInstanceOf(SQLException.class); + assertThat(mappingCount(fixture, owner.getTenantId(), version.getId())).isZero(); + assertThat( + new DraftCommitCoordinatorRepository(fixture.dsl()) + .readVisibilityFence(binding.target())) + .isEmpty(); + } + + @Test + void sourceVisibilityAndProjectionRollbackTogether() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "source-rollback"); + Version version = saveDraftVersion(fixture, owner, 1); + GameAsset asset = saveAsset(fixture, owner, "resource.png", "source-bytes"); + var binding = + sourceBinding( + fixture, + version, + AssetSource.upsertPayload( + asset.getId().toString(), asset.getFileName(), AssetSource.Requiredness.REQUIRED)); + assertThatThrownBy( + () -> + fixture + .transaction() + .execute( + status -> { + applySources(fixture, binding); + throw new IllegalStateException("fixture rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("fixture rollback"); + assertThat(mappingCount(fixture, owner.getTenantId(), version.getId())).isZero(); + assertThat( + new GameDesignSourceRepository(fixture.dsl()) + .readSynchronized(binding.target(), binding.commitId())) + .isEmpty(); + assertThat( + new DraftCommitCoordinatorRepository(fixture.dsl()) + .readVisibilityFence(binding.target())) + .isEmpty(); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT source_epoch FROM game_design_asset_source_head WHERE canonical_version_id = ?", + version.getCanonicalVersionId()) + .get(0, String.class)) + .isEqualTo("0"); + } + + @Test + void selectedCommitFreezesOrdinarySourceAndRetainsExactExportAfterReconstruction() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selected-ordinary"); + Version version = saveDraftVersion(fixture, owner, 1); + GameAsset asset = saveAsset(fixture, owner, "resource.png", "source-bytes"); + var binding = + sourceBinding( + fixture, + version, + AssetSource.upsertPayload( + asset.getId().toString(), asset.getFileName(), AssetSource.Requiredness.REQUIRED)); + inTransaction(fixture, () -> applySources(fixture, binding)); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + owner.getCanonicalTenantId(), + version.getCanonicalVersionId(), + UUID.randomUUID().toString(), + "1", + "local selected ordinary source proof", + binding.requestId(), + binding.commitId(), + binding.digest()); + var selected = + inTransaction( + fixture, + () -> + new AuthoredDraftPublishSelectionRepository( + fixture.dsl(), new DraftCommitCoordinatorRepository(fixture.dsl())) + .reserve(intent)); + assertThat(selected.selection().selectedCommit()).isEqualTo(binding); + var frozen = + inTransaction( + fixture, + () -> fixture.publicationRepository().freezeOrReadSnapshot(owner.getTenantId(), 1)); + var restarted = + new VersionAssetPublicationRepository(fixture.dsl()) + .readFrozenSnapshot(owner.getTenantId(), 1); + assertSameSnapshot(frozen, restarted); + assertThat( + new AssetSourceRepository(fixture.dsl()) + .requireExportSelection(owner.getTenantId(), version.getId()) + .binding()) + .isEqualTo(binding); + var changed = sourceBinding(fixture, version, AssetSource.deletePayload(asset.getFileName())); + assertThatThrownBy(() -> inTransaction(fixture, () -> applySources(fixture, changed))) + .isInstanceOf(RuntimeException.class); + assertThat(mappingCount(fixture, owner.getTenantId(), version.getId())).isEqualTo(1); + } + + @Test + void qualifiedRetainedDraftCannotReceiveInventedFreshOrdinaryGenesis() { + Fixture fixture = fixture(MigrationVersion.fromVersion("54")); + Game owner = saveGame(fixture, "retained-qualified"); + UUID versionId = UUID.randomUUID(); + Long rowId = + fixture + .dsl() + .fetchSingle( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch, is_script_only, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, identity_source_game_tenant_key, identity_source_provenance_kind) " + + "SELECT tenant_id, 1, 'DRAFT', 1, FALSE, canonical_tenant_id, ?, id, tenant_id, tenant_identity_provenance_kind FROM game WHERE id = ? RETURNING id", + versionId, + owner.getId()) + .get(0, Long.class); + migrate(fixture.dataSource(), fixture.schema(), null); + Version retained = + fixture.versions().findByTenantIdAndId(owner.getTenantId(), rowId).orElseThrow(); + var target = + new DraftCommitBinding.TargetProof( + retained.getCanonicalTenantId(), + retained.getCanonicalVersionId(), + rowId, + retained.getTenantId(), + retained.getIdentitySourceGameRowId(), + retained.getIdentitySourceGameTenantKey(), + retained.getIdentitySourceProvenanceKind()); + assertThatThrownBy( + () -> + inTransaction( + fixture, + () -> new AssetSourceRepository(fixture.dsl()).enrollFreshDraft(target))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("ASSET_SOURCE_FRESH_INSERT_UNAVAILABLE"); + assertThat(new AssetSourceRepository(fixture.dsl()).readGenesis(target)).isEmpty(); + assertThatThrownBy( + () -> + new AssetSourceRepository(fixture.dsl()) + .requireExportSelection(owner.getTenantId(), rowId)) + .isInstanceOf(IllegalStateException.class); + } + @Test void retainedVersionWithoutCanonicalSourceCannotReceiveAssetMapping() { Fixture fixture = fixture(V35); @@ -202,7 +575,7 @@ void immutableSourceRejectsChangedBytesBeforeCommittedSnapshotReadback() { asset.getId())) .rootCause() .isInstanceOf(SQLException.class) - .hasMessageContaining("game asset source rows are immutable") + .hasMessageContaining("immutable") .satisfies( failure -> assertThat(((SQLException) failure).getSQLState()).isEqualTo("23514")); @@ -246,7 +619,7 @@ void associationAfterSnapshotFreezeIsRejected() { assertThatThrownBy( () -> associate(fixture, owner.getTenantId(), version.getId(), second.getId())) .isInstanceOf(IllegalStateException.class) - .hasMessage("Version asset mappings are frozen by the durable export snapshot"); + .hasMessage("ASSET_SOURCE_FROZEN_OR_NOT_DRAFT"); assertThat(mappingCount(fixture, owner.getTenantId(), version.getId())).isEqualTo(1); } @@ -344,13 +717,119 @@ private void associate(Fixture fixture, String tenantId, long versionId, long as .transaction() .execute( status -> { - fixture - .publicationRepository() - .associateDraftAsset(tenantId, versionId, assetId, null); + var version = + fixture + .versions() + .findByTenantIdAndId(tenantId, versionId) + .orElseThrow( + () -> + new IllegalStateException("Exact tenant Version row was not found")); + if (version.getCanonicalTenantId() == null + || version.getCanonicalVersionId() == null) { + throw new IllegalStateException( + "Version lacks a complete canonical owner identity"); + } + var asset = + fixture + .dsl() + .fetchOne( + "SELECT file_name FROM game_assets WHERE tenant_id = ? AND id = ?", + tenantId, + assetId); + if (asset == null) + throw new IllegalStateException("Exact tenant game asset row was not found"); + var target = + new DraftCommitBinding.TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + versionId, + tenantId, + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + IsolatedPublicationOwnerSetup.applyOrdinaryReferences( + fixture.dsl(), + target, + List.of( + AssetSource.upsertPayload( + Long.toString(assetId), + asset.get("file_name", String.class), + AssetSource.Requiredness.REQUIRED))); return null; }); } + private DraftCommitBinding sourceBinding(Fixture fixture, Version version, String... payloads) { + var target = + new DraftCommitBinding.TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + var revisions = new java.util.ArrayList(); + var units = new java.util.ArrayList(); + for (int index = 0; index < payloads.length; index++) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[index])); + } + for (String scope : List.of(CommandSource.SCOPE, AssetSource.SCOPE, RealmPolicySource.SCOPE)) { + String kind = + scope.equals(AssetSource.SCOPE) + ? "ASSET_REFERENCE" + : scope.equals(RealmPolicySource.SCOPE) ? "REALM_ENTRY_POLICY" : "COMMAND_DEFINITION"; + if (List.of(payloads).stream().noneMatch(payload -> payload.contains(kind))) continue; + String table = + scope.equals(AssetSource.SCOPE) + ? "game_design_asset_source_head" + : scope.equals(RealmPolicySource.SCOPE) + ? "game_design_realm_policy_source" + : "game_design_command_source_head"; + String epoch = + fixture + .dsl() + .fetchSingle( + "SELECT source_epoch FROM " + table + " WHERE canonical_version_id = ?", + version.getCanonicalVersionId()) + .get(0, String.class); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + scope, + target.canonicalVersionId().toString(), + scope, + "effective", + epoch)); + } + var prior = new DraftCommitCoordinatorRepository(fixture.dsl()).readVisibilityFence(target); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + prior.map(fence -> fence.commitId().toString()).orElse("base-commit-0"), + revisions, + units); + } + + private GameDesignSourceRepository.Application applySources( + Fixture fixture, DraftCommitBinding binding) { + var coordinator = new DraftCommitCoordinatorRepository(fixture.dsl()); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = new GameDesignSourceRepository(fixture.dsl()).apply(binding); + IsolatedPublicationOwnerSetup.advanceSourceVisibility( + fixture.dsl(), binding, List.of(applied.ownerOutcome())); + coordinator.releaseApplicationSlot(binding); + return applied; + } + private T inTransaction(Fixture fixture, java.util.function.Supplier action) { return Objects.requireNonNull(fixture.transaction().execute(status -> action.get())); } diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java new file mode 100644 index 0000000000..9cfcf1c28b --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +class AssetSnapshotTest { + @Test + void exactTypedSnapshotRoundTripsAndOwnsItsImmutableCollection() { + var binding = binding(); + var reference = AssetSource.replay(List.of(), binding).references().getFirst(); + var item = + new AssetSnapshot.Item(reference, "image/png", CommandSource.sha256(new byte[] {1, 2}), 2); + var mutable = new ArrayList<>(List.of(item)); + var snapshot = new AssetSnapshot(binding, "1", null, UUID.randomUUID(), mutable); + mutable.clear(); + assertThat(AssetSnapshot.fromStored(snapshot.canonicalJson())).isEqualTo(snapshot); + assertThat(snapshot.items()).containsExactly(item); + assertThatThrownBy(() -> snapshot.items().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(snapshot.items().getFirst().reference().family()).isEqualTo("ORDINARY"); + assertThat(snapshot.items().getFirst().reference().role()).isEqualTo("RESOURCE"); + assertThat(new AssetApplication(binding, "0", snapshot).appliedEpoch().resultingEpoch()) + .isEqualTo("1"); + assertThatThrownBy(() -> new AssetApplication(binding, "1", snapshot)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void storedSnapshotCannotChangeBoundRequirednessIdentityOrCanonicalRepresentation() { + var binding = binding(); + var reference = AssetSource.replay(List.of(), binding).references().getFirst(); + var snapshot = + new AssetSnapshot( + binding, + "1", + null, + UUID.randomUUID(), + List.of( + new AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[0]), 0))); + String json = snapshot.canonicalJson(); + for (String invalid : + List.of( + json.replace("\"requiredness\":\"REQUIRED\"", "\"requiredness\":\"OPTIONAL\""), + json.replace("\"family\":\"ORDINARY\"", "\"family\":\"UNKNOWN\""), + json.replace("\"role\":\"RESOURCE\"", "\"role\":\"PRESENTATION\""), + " " + json)) { + assertThatThrownBy(() -> AssetSnapshot.fromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> new AssetSnapshot.Item(reference, "", CommandSource.sha256(new byte[0]), 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new AssetSnapshot.Item(reference, "image/png", "sha256:00", 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[0]), -1)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DraftCommitBinding binding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "tenant", 2, "tenant", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.upsertPayload("3", "logo.png", AssetSource.Requiredness.REQUIRED))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + target.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + "0"))); + } +} diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSourceTest.java new file mode 100644 index 0000000000..9b33fff94e --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSourceTest.java @@ -0,0 +1,270 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class AssetSourceTest { + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID VERSION = UUID.randomUUID(); + + @Test + void extractionPreservesExactBindingOrderAndExplicitRequiredness() { + var binding = + binding( + AssetSource.upsertPayload( + "9223372036854775807", " Logo.png ", AssetSource.Requiredness.REQUIRED), + "{\"revisionKind\":\"COMMAND_DEFINITION\"}", + "{\"revisionKind\":\"REALM_ENTRY_POLICY\"}", + AssetSource.upsertPayload("2", "required.png", AssetSource.Requiredness.REQUIRED)); + var mutations = AssetSource.mutations(binding); + + assertThat(mutations).hasSize(2); + assertThat(mutations).extracting(AssetSource.Mutation::revisionOrder).containsExactly("0", "3"); + assertThat(mutations.getFirst().binding()).isSameAs(binding); + assertThat(mutations.getFirst().revisionId()) + .isEqualTo(binding.revisions().getFirst().revisionId()); + assertThat(mutations.getFirst().usageKey()).isEqualTo(" Logo.png "); + assertThat(mutations.getFirst().requiredness()).isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(mutations.getLast().requiredness()).isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(mutations.getFirst().binding()).isSameAs(binding); + assertThatThrownBy(() -> mutations.clear()).isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void replayReplacesOnlyExplicitKeysAndRetainsExactSourceProvenance() { + var original = + binding( + AssetSource.upsertPayload("1", "one.png", AssetSource.Requiredness.REQUIRED), + AssetSource.upsertPayload("2", "two.png", AssetSource.Requiredness.REQUIRED)); + var baseline = AssetSource.replay(List.of(), original); + var changed = + binding( + AssetSource.deletePayload("one.png"), + AssetSource.upsertPayload("3", "one.png", AssetSource.Requiredness.REQUIRED)); + var result = AssetSource.replay(baseline.references(), changed); + + assertThat(result.binding()).isSameAs(changed); + assertThat(result.references()) + .extracting(AssetSource.Reference::usageKey) + .containsExactly("one.png", "two.png"); + assertThat(result.references().getFirst().assetRowId()).isEqualTo("3"); + assertThat(result.references().getFirst().requiredness()) + .isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(result.references().getFirst().family()).isEqualTo("ORDINARY"); + assertThat(result.references().getFirst().role()).isEqualTo("RESOURCE"); + assertThat(result.references().getFirst().sourceBinding()).isSameAs(changed); + assertThat(result.references().getLast().sourceBinding()).isSameAs(original); + assertThat(AssetSource.replay(result.references(), changed)).isEqualTo(result); + assertThat( + AssetSource.replay(result.references(), binding(AssetSource.deletePayload("two.png"))) + .references()) + .extracting(AssetSource.Reference::usageKey) + .containsExactly("one.png"); + } + + @Test + void referenceCannotRewriteItsBoundRequirednessOrRevisionIdentity() { + var binding = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var revision = binding.revisions().getFirst(); + + assertThatThrownBy( + () -> + new AssetSource.Reference( + "logo.png", + "1", + AssetSource.Requiredness.OPTIONAL, + binding, + "0", + revision.revisionId())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AssetSource.Reference( + "logo.png", + "1", + AssetSource.Requiredness.REQUIRED, + binding, + "0", + UUID.randomUUID())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void snapshotRejectsForeignTargetDuplicateKeysAndSourceAliases() { + var original = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var references = AssetSource.replay(List.of(), original).references(); + var foreign = binding(UUID.randomUUID(), AssetSource.deletePayload("logo.png")); + + assertThatThrownBy(() -> AssetSource.replay(references, foreign)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AssetSource.Snapshot( + original, List.of(references.getFirst(), references.getFirst()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AssetSource.replay( + references, + binding( + AssetSource.upsertPayload( + "1", "alias.png", AssetSource.Requiredness.REQUIRED)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void snapshotDefensivelyRetainsItsReferenceList() { + var binding = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var mutable = new ArrayList<>(AssetSource.replay(List.of(), binding).references()); + var snapshot = new AssetSource.Snapshot(binding, mutable); + mutable.clear(); + + assertThat(snapshot.references()).hasSize(1); + assertThatThrownBy(() -> snapshot.references().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "0", + "01", + "-1", + "+1", + "1.0", + "1e2", + " 1", + "9223372036854775808", + "999999999999999999999999" + }) + void deniesNoncanonicalOrOverflowingOwnerRowId(String value) { + assertThatThrownBy( + () -> AssetSource.mutations(binding(upsert("\"" + value + "\"", "\"REQUIRED\"")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"1", "1.0", "1e0", "null", "true", "{}", "[]"}) + void ownerRowIdMustBeTextNotCoercedJson(String value) { + assertThatThrownBy(() -> AssetSource.mutations(binding(upsert(value, "\"REQUIRED\"")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"\"UNKNOWN\"", "\"required\"", "null", "true", "1", "{}"}) + void deniesUnknownOrUntypedRequiredness(String value) { + assertThatThrownBy(() -> AssetSource.mutations(binding(upsert("\"1\"", value)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void deniesMissingRequirednessUnknownMembersDuplicateFieldsAndTrailingJson() { + String valid = upsert("\"1\"", "\"REQUIRED\""); + List invalid = + List.of( + valid.replace(",\"requiredness\":\"REQUIRED\"", ""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1.0"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":\"1\""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":2"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"), + valid.replace("\"usageKey\":\"logo.png\"", "\"usageKey\":\"logo.png\",\"extra\":true"), + valid + " {}", + "{\"revisionKind\":\"UNSUPPORTED\"}", + "{}", + AssetSource.deletePayload("logo.png") + .replace( + "\"operation\":\"DELETE\"", + "\"operation\":\"DELETE\",\"requiredness\":\"OPTIONAL\"")); + for (String payload : invalid) { + assertThatThrownBy(() -> AssetSource.mutations(binding(payload))) + .as(payload) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void usageKeyIsExactBoundedAndCannotReserveManifestName() { + for (String key : List.of("", " ", "manifest.json", "x".repeat(256))) { + assertThatThrownBy( + () -> AssetSource.upsertPayload("1", key, AssetSource.Requiredness.REQUIRED)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat( + AssetSource.mutations( + binding( + AssetSource.upsertPayload( + "1", "x".repeat(255), AssetSource.Requiredness.REQUIRED)))) + .hasSize(1); + } + + @Test + void ordinaryResourceCannotClaimOptionalPresentationOrAnUnknownFamilyOrRole() { + assertThatThrownBy( + () -> AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.OPTIONAL)) + .isInstanceOf(IllegalArgumentException.class); + String required = upsert("\"1\"", "\"REQUIRED\""); + for (String payload : + List.of( + required.replace("REQUIRED", "OPTIONAL"), + required.replace("ORDINARY", "BRANDING"), + required.replace("RESOURCE", "PRESENTATION"), + required.replace(",\"role\":\"RESOURCE\"", ""), + required.replace(",\"family\":\"ORDINARY\"", ""))) { + assertThatThrownBy(() -> AssetSource.mutations(binding(payload))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static String upsert(String rowIdJson, String requirednessJson) { + return "{\"schemaVersion\":1,\"revisionKind\":\"ASSET_REFERENCE\",\"family\":\"ORDINARY\",\"role\":\"RESOURCE\",\"operation\":\"UPSERT\",\"assetRowId\":" + + rowIdJson + + ",\"usageKey\":\"logo.png\",\"requiredness\":" + + requirednessJson + + "}"; + } + + private static DraftCommitBinding binding(String... payloads) { + return binding(VERSION, payloads); + } + + private static DraftCommitBinding binding(UUID versionId, String... payloads) { + List revisions = new ArrayList<>(); + for (int index = 0; index < payloads.length; index++) { + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[index])); + } + return DraftCommitBinding.create( + new TargetProof(TENANT, versionId, 23L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + versionId.toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + "0"))); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepositoryTest.java index 105e768b5f..f5b26aeffc 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepositoryTest.java @@ -7,6 +7,7 @@ import java.util.stream.Stream; import org.jooq.DSLContext; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -43,6 +44,22 @@ void mappingAndSnapshotWritesRejectInvalidTransactionBeforeSql( verifyNoInteractions(dsl); } + @Test + void directAssociationCannotBypassSourceEvenInAnOtherwiseValidOwnerTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + DSLContext dsl = mock(DSLContext.class); + assertThatThrownBy( + () -> + new VersionAssetPublicationRepository(dsl) + .associateDraftAsset("tenant", 1, 1, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synchronized ASSET_REFERENCE"); + verifyNoInteractions(dsl); + } + private static Stream invalidTransactionContexts() { return Stream.of( Arguments.of(false, false, null), diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java index e2ddd3823c..c0cfd708f5 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java @@ -241,6 +241,20 @@ public Optional readAttempt(WorldDesignPublicationFenceEvidence e return Optional.of(stored); } + /** Reads one retained attempt by its opaque fence without resolving mutable source state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readAttemptByFence(UUID publicationFence) { + if (publicationFence == null || NIL_UUID.equals(publicationFence)) { + throw new IllegalArgumentException("A non-nil World publication fence is required"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("World publication attempt read requires a committed read"); + } + FrozenAttempt stored = findAttemptByFence(publicationFence); + return Optional.ofNullable(stored); + } + private ResolvedVersion resolveVersion(OwnerBinding binding) { Objects.requireNonNull(binding, "binding"); WorldAuthoredSourceIntakeReceipt receipt = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcService.java index 9b2bfaf040..8d6e9689bd 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcService.java @@ -7,9 +7,12 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Request; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryGrpcCodec; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeRequest; import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedPublicationArtifactInventoryRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedPublicationArtifactInventoryResponse; import net.firedevops.firemud.worldmanagement.v1.WorldSelectedDraftPublicationFreezeServiceGrpc; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -24,11 +27,16 @@ public final class WorldSelectedDraftPublicationFreezeGrpcService extends WorldSelectedDraftPublicationFreezeServiceGrpc .WorldSelectedDraftPublicationFreezeServiceImplBase { private final WorldSelectedDraftPublicationFreezeService freezeService; + private final WorldSelectedPublicationArtifactInventoryReadService inventoryReadService; private final String trustedNamespace; public WorldSelectedDraftPublicationFreezeGrpcService( - WorldSelectedDraftPublicationFreezeService freezeService, String trustedNamespace) { + WorldSelectedDraftPublicationFreezeService freezeService, + WorldSelectedPublicationArtifactInventoryReadService inventoryReadService, + String trustedNamespace) { this.freezeService = Objects.requireNonNull(freezeService, "freezeService"); + this.inventoryReadService = + Objects.requireNonNull(inventoryReadService, "inventoryReadService"); if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { throw new IllegalArgumentException("World workload namespace is invalid"); } @@ -106,6 +114,75 @@ public void beginVersionPublicationFreeze( responseObserver.onCompleted(); } + @Override + public void readSelectedPublicationArtifactInventory( + ReadSelectedPublicationArtifactInventoryRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeer(responseObserver)) return; + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("World selected inventory read requires an independent owner read") + .asRuntimeException()); + return; + } + + final net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence + freezeEvidence; + try { + freezeEvidence = WorldSelectedPublicationArtifactInventoryGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Complete canonical World freeze lookup identity is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(freezeEvidence.request().targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("World inventory namespace must match the authenticated peer") + .asRuntimeException()); + return; + } + + final ReadSelectedPublicationArtifactInventoryResponse response; + try { + response = + WorldSelectedPublicationArtifactInventoryGrpcCodec.toResponse( + inventoryReadService.read(freezeEvidence)); + } catch (SecurityException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Authenticated same-namespace Game Design workload is required") + .asRuntimeException()); + return; + } catch (WorldDesignPublicationFenceRepository.ConflictException + | IllegalArgumentException inconsistent) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact retained World artifact inventory is unavailable") + .asRuntimeException()); + return; + } catch (org.springframework.dao.DataAccessException + | org.jooq.exception.DataAccessException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("World selected inventory owner storage is unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL + .withDescription("World selected-publication inventory read failed") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + private boolean requireAuthenticatedGameDesignPeer(StreamObserver responseObserver) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer == null) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java index 69a0d1c3a4..50d72c44d4 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java @@ -4,6 +4,7 @@ import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; +import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.UUID; @@ -12,6 +13,17 @@ import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SpawnBindingInput; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; import tools.jackson.core.StreamReadFeature; @@ -130,64 +142,6 @@ record SourceIntake( String sourceGameTenantKey, String sourceProvenanceKind) {} - public record FamilyCount(String family, int rowCount) {} - - public record RegionGeneratorInput( - UUID regionTemplateId, String generatorType, String generatorParams) {} - - public record SpawnBindingInput( - UUID bindingTemplateId, - UUID roomTemplateId, - String entityTemplateType, - String entityReferenceKind, - UUID entityTenantId, - UUID entityVersionId, - UUID entityTemplateId, - int spawnCount, - int respawnDelaySeconds) {} - - public record SourceModel( - String modelId, - int graphSchemaVersion, - String graphDigest, - String topologyResultDigest, - List familyCounts, - List regionGeneratorInputs, - List generationRuleFields, - List regionFields, - List zoneFields, - List roomFields, - List roomExitFields, - List spawnBindingFields, - List spawnBindingInputs, - int generationRuleInputCount, - int spawnBindingCount, - List appliedEpochs) { - public SourceModel { - familyCounts = List.copyOf(Objects.requireNonNull(familyCounts, "familyCounts")); - regionGeneratorInputs = - List.copyOf(Objects.requireNonNull(regionGeneratorInputs, "regionGeneratorInputs")); - generationRuleFields = - List.copyOf(Objects.requireNonNull(generationRuleFields, "generationRuleFields")); - regionFields = List.copyOf(Objects.requireNonNull(regionFields, "regionFields")); - zoneFields = List.copyOf(Objects.requireNonNull(zoneFields, "zoneFields")); - roomFields = List.copyOf(Objects.requireNonNull(roomFields, "roomFields")); - roomExitFields = List.copyOf(Objects.requireNonNull(roomExitFields, "roomExitFields")); - spawnBindingFields = - List.copyOf(Objects.requireNonNull(spawnBindingFields, "spawnBindingFields")); - spawnBindingInputs = - List.copyOf(Objects.requireNonNull(spawnBindingInputs, "spawnBindingInputs")); - appliedEpochs = List.copyOf(Objects.requireNonNull(appliedEpochs, "appliedEpochs")); - } - } - - public record SelectedApplication( - UUID applicationOperationId, - UUID applicationRequestId, - String appliedCommitId, - String bindingDigest, - String appliedResultDigest) {} - public record AccountOrder( UUID operationId, UUID fenceId, @@ -208,59 +162,6 @@ public byte[] canonicalBindingBytes() { } } - public record Freeze( - UUID publicationFence, - String publicationRequestId, - String requestDigest, - String versionStateEpoch, - String publishWorkflowId) {} - - public record Checkpoint(String appliedCommitId, String contentDigest, int digestSchemaVersion) {} - - public record ArtifactDecision(String artifactKind, String state, String rule) {} - - /** Public Account order fields; the internal exact canonical bytes remain owner-private. */ - public record PublicAccountOrder( - UUID operationId, - UUID fenceId, - UUID actorAccountId, - String publicationRequestId, - String selectionDigest, - String selectedCommitId, - String bindingDigest) {} - - /** Public canonical projection; it intentionally omits every private numeric owner key. */ - public record PublicOwnerScope( - String targetNamespace, - UUID canonicalTenantId, - UUID canonicalVersionId, - UUID versionIdentityOperationId, - UUID intakeRequestId, - UUID intakeOperationId, - String intakeRequestDigest, - UUID sourceOperationId, - String sourceEvidenceDigest, - String intakeReceiptDigest) {} - - /** - * Safe egress view after the authenticated World owner read has verified the durable envelope. - */ - public record PublicEvidence( - String schema, - int schemaVersion, - String completeness, - PublicOwnerScope ownerScope, - SelectedApplication selectedApplication, - PublicAccountOrder accountOrder, - Freeze freeze, - Checkpoint checkpoint, - SourceModel sourceModel, - List artifactDecisions) { - public PublicEvidence { - artifactDecisions = List.copyOf(Objects.requireNonNull(artifactDecisions)); - } - } - record Envelope( String schema, int schemaVersion, @@ -534,25 +435,51 @@ public PublicEvidence publicEvidence() { publicAccountOrder(envelope.accountOrder()), envelope.freeze(), envelope.checkpoint(), - envelope.sourceModel(), + publicSourceModel(envelope.sourceModel()), envelope.artifactDecisions()); } + /** + * Stable public projection order; retained private-envelope bytes preserve original graph order. + */ + private static SourceModel publicSourceModel(SourceModel model) { + List regions = + model.regionGeneratorInputs().stream() + .sorted(Comparator.comparing(input -> input.regionTemplateId().toString())) + .toList(); + List spawnBindings = + model.spawnBindingInputs().stream() + .sorted(Comparator.comparing(input -> input.bindingTemplateId().toString())) + .toList(); + return new SourceModel( + model.modelId(), + model.graphSchemaVersion(), + model.graphDigest(), + model.topologyResultDigest(), + model.familyCounts(), + regions, + model.generationRuleFields(), + model.regionFields(), + model.zoneFields(), + model.roomFields(), + model.roomExitFields(), + model.spawnBindingFields(), + spawnBindings, + model.generationRuleInputCount(), + model.spawnBindingCount(), + model.appliedEpochs()); + } + /** Canonical bytes for the safe public projection; private owner keys are never serialized. */ public byte[] publicCanonicalBytes() { - try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(publicEvidence())); - } catch (IOException failure) { - throw new IllegalStateException( - "World public artifact inventory could not be encoded", failure); - } + return publicEvidence().canonicalBytes(); } /** * Digest of {@link #publicCanonicalBytes()}, distinct from the private durable-envelope digest. */ public String publicDigest() { - return WorldDraftGraphAppliedResult.digest(publicCanonicalBytes()); + return publicEvidence().digest(); } private static PublicAccountOrder publicAccountOrder(AccountOrder account) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryReadService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryReadService.java new file mode 100644 index 0000000000..cc5545c8ac --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryReadService.java @@ -0,0 +1,130 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.FrozenAttempt; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Read-only authenticated owner composition for the immutable selected-publication inventory. */ +final class WorldSelectedPublicationArtifactInventoryReadService { + private final String workloadNamespace; + private final WorldDesignPublicationFenceRepository fence; + private final WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository; + private final WorldSelectedPublicationArtifactInventoryRepository inventoryRepository; + + WorldSelectedPublicationArtifactInventoryReadService( + String workloadNamespace, + WorldDesignPublicationFenceRepository fence, + WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository, + WorldSelectedPublicationArtifactInventoryRepository inventoryRepository) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.fence = Objects.requireNonNull(fence, "fence"); + this.authorizationRepository = + Objects.requireNonNull(authorizationRepository, "authorizationRepository"); + this.inventoryRepository = Objects.requireNonNull(inventoryRepository, "inventoryRepository"); + } + + /** Reads only a committed attempt and its original Account/inventory rows; never recaptures. */ + WorldSelectedPublicationArtifactInventoryEvidence read( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + requireAuthenticatedGameDesignCaller(); + requireNoAmbientTransaction(); + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new SecurityException("World inventory target namespace differs from this workload"); + } + FrozenAttempt attempt = + fence + .readAttemptByFence(acknowledgement.publicationFence()) + .orElseThrow( + () -> conflict("World inventory read has no retained freeze for its fence")); + requireAttemptMatchesAcknowledgement(attempt, freezeEvidence); + + AccountPublicationAuthorizationBinding retained = + authorizationRepository + .readCommitted(attempt) + .orElseThrow( + () -> conflict("World inventory read has no original Account qualification")); + if (!Arrays.equals( + request.accountPublicationAuthorizationBinding(), retained.canonicalBytes())) { + throw conflict("World inventory read changed the original Account publication order"); + } + + WorldSelectedPublicationArtifactInventory inventory = + inventoryRepository.readCommitted(attempt, retained); + return WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freezeEvidence, inventory.publicEvidence()); + } + + private static void requireAttemptMatchesAcknowledgement( + FrozenAttempt attempt, WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + var retained = attempt.request(); + var owner = retained.ownerBinding(); + var selected = request.accountBinding().input().selection(); + String workflowId = + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selected.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity(); + + if (!attempt.publicationFence().equals(acknowledgement.publicationFence()) + || !owner.targetNamespace().equals(request.targetNamespace()) + || !owner.canonicalTenantId().equals(request.canonicalTenantId()) + || !owner.canonicalVersionId().equals(request.canonicalVersionId()) + || !retained.publicationRequestId().equals(request.publicationRequestId()) + || !retained.requestDigest().equals(request.requestDigest()) + || retained.versionStateEpoch() != request.expectedVersionStateEpoch() + || !retained.publishWorkflowId().equals(workflowId) + || !retained.intakeRequestId().equals(acknowledgement.intakeRequestId()) + || acknowledgement.versionStateEpoch() != retained.versionStateEpoch() + || !attempt.checkpoint().appliedCommitId().equals(acknowledgement.appliedCommitId()) + || !attempt.checkpoint().contentDigest().equals(acknowledgement.contentDigest()) + || attempt.checkpoint().digestSchemaVersion() != acknowledgement.digestSchemaVersion() + || !selected + .selectedCommit() + .commitId() + .toString() + .equals(acknowledgement.appliedCommitId())) { + throw conflict( + "World inventory read differs from the complete retained freeze acknowledgement"); + } + } + + private void requireAuthenticatedGameDesignCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(workloadNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "World inventory read requires the authenticated same-namespace Game Design workload"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("World inventory read requires no ambient owner transaction"); + } + } + + private static ConflictException conflict(String message) { + return new ConflictException(message); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 2c44ac9241..746594bd88 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -54,6 +54,9 @@ import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; @@ -437,7 +440,7 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() var publicInventory = inventory.publicEvidence(); assertThat(publicInventory.completeness()).isEqualTo("COMPLETE"); assertThat(publicInventory.sourceModel().familyCounts()) - .extracting(WorldSelectedPublicationArtifactInventory.FamilyCount::family) + .extracting(WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount::family) .containsExactly( "REGION", "ZONE", @@ -446,11 +449,12 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() "GENERATION_RULE", "WORLD_ENTITY_SPAWN_BINDING"); assertThat(publicInventory.sourceModel().familyCounts()) - .extracting(WorldSelectedPublicationArtifactInventory.FamilyCount::rowCount) + .extracting(WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount::rowCount) .containsExactly(1, 1, 1, 0, 0, 0); assertThat(publicInventory.artifactDecisions()) .extracting( - WorldSelectedPublicationArtifactInventory.ArtifactDecision::artifactKind) + WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision + ::artifactKind) .containsExactly("NAVMESH", "PATH_GRAPH"); assertThat(publicInventory.accountOrder().bindingDigest()) .isEqualTo( @@ -462,6 +466,26 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() .doesNotContain( "localTenantKey", "localVersionKey", "gameDesignVersionId", "sourceGameRowId"); assertThat(inventory.publicDigest()).matches("sha256:[0-9a-f]{64}"); + var firstInventoryRead = + readArtifactInventoryOverMtls(selectedFreezeService, firstFreeze, pki); + assertThat(firstInventoryRead.canonicalBytes()) + .containsExactly(inventory.publicCanonicalBytes()); + assertThat(firstInventoryRead.digest()).isEqualTo(inventory.publicDigest()); + assertThat( + new String( + firstInventoryRead.canonicalBytes(), + java.nio.charset.StandardCharsets.UTF_8)) + .doesNotContain( + "localTenantKey", "localVersionKey", "gameDesignVersionId", "sourceGameRowId"); + assertThatThrownBy( + () -> + readArtifactInventoryOverMtls( + selectedFreezeService, firstFreeze, pki, pki.worldClient)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); account.assertPublicationSourcesHeld(publicationOrder); var frozen = capture(plan, freezeEvidence, frozenAttempt); assertThat(frozenAttempt.checkpoint().appliedCommitId()) @@ -476,6 +500,11 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() var retryFreeze = beginOverMtls(selectedFreezeService, freezeRequest, pki); assertThat(retryFreeze.request()).isEqualTo(firstFreeze.request()); assertThat(retryFreeze.acknowledgement()).isEqualTo(firstFreeze.acknowledgement()); + var retryInventoryRead = + readArtifactInventoryOverMtls(selectedFreezeService, retryFreeze, pki); + assertThat(retryInventoryRead.canonicalBytes()) + .containsExactly(firstInventoryRead.canonicalBytes()); + assertThat(retryInventoryRead.digest()).isEqualTo(firstInventoryRead.digest()); var exactRetry = fence.readAttempt(retryEvidence).orElseThrow(); assertThat(exactRetry.request()).isEqualTo(retryEvidence); assertThat(exactRetry.publicationFence()).isEqualTo(frozenAttempt.publicationFence()); @@ -519,6 +548,79 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() freezeRequest.expectedVersionStateEpoch(), freezeRequest.requestDigest(), changedOperation); + var substitutedAccountAcknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + changedFreezeRequest, + firstFreeze.acknowledgement().intakeRequestId(), + firstFreeze.acknowledgement().versionStateEpoch(), + firstFreeze.acknowledgement().publicationFence(), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + firstFreeze.acknowledgement().appliedCommitId(), + firstFreeze.acknowledgement().contentDigest(), + firstFreeze.acknowledgement().digestSchemaVersion()); + var substitutedAccountFreeze = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + changedFreezeRequest, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse( + substitutedAccountAcknowledgement)); + assertThatThrownBy( + () -> + readArtifactInventoryOverMtls( + selectedFreezeService, substitutedAccountFreeze, pki)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + var substitutedCheckpointAcknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + freezeRequest, + firstFreeze.acknowledgement().intakeRequestId(), + firstFreeze.acknowledgement().versionStateEpoch(), + firstFreeze.acknowledgement().publicationFence(), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + firstFreeze.acknowledgement().appliedCommitId(), + "b".repeat(64), + firstFreeze.acknowledgement().digestSchemaVersion()); + var substitutedCheckpointFreeze = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse( + substitutedCheckpointAcknowledgement)); + assertThatThrownBy( + () -> + readArtifactInventoryOverMtls( + selectedFreezeService, substitutedCheckpointFreeze, pki)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + var substitutedFenceAcknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + freezeRequest, + firstFreeze.acknowledgement().intakeRequestId(), + firstFreeze.acknowledgement().versionStateEpoch(), + UUID.randomUUID(), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + firstFreeze.acknowledgement().appliedCommitId(), + firstFreeze.acknowledgement().contentDigest(), + firstFreeze.acknowledgement().digestSchemaVersion()); + var substitutedFenceFreeze = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse( + substitutedFenceAcknowledgement)); + assertThatThrownBy( + () -> + readArtifactInventoryOverMtls( + selectedFreezeService, substitutedFenceFreeze, pki)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(ownerSnapshot(world, plan)).isEqualTo(stateBeforeExactRetry); assertThatThrownBy( () -> beginOverMtls(selectedFreezeService, changedFreezeRequest, pki)) .isInstanceOf(StatusRuntimeException.class) @@ -1306,7 +1408,8 @@ private WorldSelectedDraftPublicationFreezeEvidence beginOverMtls( serveAll( pki.worldServer, pki, - new WorldSelectedDraftPublicationFreezeGrpcService(service, NAMESPACE)); + new WorldSelectedDraftPublicationFreezeGrpcService( + service, selectedPublicationArtifactInventoryReadService(), NAMESPACE)); try { var endpoints = new ServiceEndpointsProperties(); endpoints.setWorldManagementService("localhost:" + server.getPort()); @@ -1324,6 +1427,40 @@ private WorldSelectedDraftPublicationFreezeEvidence beginOverMtls( } } + private WorldSelectedPublicationArtifactInventoryEvidence readArtifactInventoryOverMtls( + WorldSelectedDraftPublicationFreezeService service, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + TestPki pki) + throws Exception { + return readArtifactInventoryOverMtls(service, freezeEvidence, pki, pki.gameDesignClient); + } + + private WorldSelectedPublicationArtifactInventoryEvidence readArtifactInventoryOverMtls( + WorldSelectedDraftPublicationFreezeService service, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + TestPki pki, + TestIdentity clientIdentity) + throws Exception { + var server = + serveAll( + pki.worldServer, + pki, + new WorldSelectedDraftPublicationFreezeGrpcService( + service, selectedPublicationArtifactInventoryReadService(), NAMESPACE)); + try { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("localhost:" + server.getPort()); + try (var client = + new WorldSelectedPublicationArtifactInventoryClient( + endpoints, clientIdentity.properties(pki.ca), new GrpcChannelFactory(), NAMESPACE)) { + client.init(); + return client.read(freezeEvidence); + } + } finally { + stop(server); + } + } + private static T withGameDesignCaller(Supplier action) { var context = Context.current() @@ -1357,6 +1494,12 @@ private WorldSelectedPublicationArtifactInventoryRepository artifactInventoryRep return new WorldSelectedPublicationArtifactInventoryRepository(dsl); } + private WorldSelectedPublicationArtifactInventoryReadService + selectedPublicationArtifactInventoryReadService() { + return new WorldSelectedPublicationArtifactInventoryReadService( + NAMESPACE, fence, publicationAuthorizationRepository(), artifactInventoryRepository()); + } + private DraftOwnerSnapshot ownerSnapshot(Fixture fixture, WorldDraftTopologyCommitPlan plan) { long tenant = fixture.intake().localTenantKey(); long version = fixture.version().localVersionKey(); diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java index 2bcdad8a9d..91e509e114 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeGrpcServiceTest.java @@ -16,8 +16,11 @@ import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeRequest; import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedPublicationArtifactInventoryRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedPublicationArtifactInventoryResponse; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; class WorldSelectedDraftPublicationFreezeGrpcServiceTest { private static final String NAMESPACE = "firemud"; @@ -30,7 +33,9 @@ void clearCallerContext() { @Test void authenticatesExactSameNamespaceGameDesignPeerBeforeParsingOrDelegating() { var delegate = mock(WorldSelectedDraftPublicationFreezeService.class); - var receiver = new WorldSelectedDraftPublicationFreezeGrpcService(delegate, NAMESPACE); + var receiver = + new WorldSelectedDraftPublicationFreezeGrpcService( + delegate, mock(WorldSelectedPublicationArtifactInventoryReadService.class), NAMESPACE); var malformed = BeginVersionPublicationFreezeRequest.getDefaultInstance(); var anonymous = new RecordingObserver(); @@ -75,7 +80,9 @@ void authenticatesExactSameNamespaceGameDesignPeerBeforeParsingOrDelegating() { void exactGameDesignPeerReceivesOnlyTheCompleteCommittedFreezeAcknowledgement() { var fixture = WorldSelectedDraftPublicationFreezeRequestTest.fixture(); var delegate = mock(WorldSelectedDraftPublicationFreezeService.class); - var receiver = new WorldSelectedDraftPublicationFreezeGrpcService(delegate, NAMESPACE); + var receiver = + new WorldSelectedDraftPublicationFreezeGrpcService( + delegate, mock(WorldSelectedPublicationArtifactInventoryReadService.class), NAMESPACE); var acknowledgement = new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( fixture.request(), @@ -103,6 +110,65 @@ void exactGameDesignPeerReceivesOnlyTheCompleteCommittedFreezeAcknowledgement() verify(delegate).begin(fixture.request()); } + @Test + void authenticatesInventoryReadBeforeParsingAndRequiresAnIndependentRead() { + var freezeService = mock(WorldSelectedDraftPublicationFreezeService.class); + var readService = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + var receiver = + new WorldSelectedDraftPublicationFreezeGrpcService(freezeService, readService, NAMESPACE); + var malformed = ReadSelectedPublicationArtifactInventoryRequest.getDefaultInstance(); + + var anonymous = new InventoryRecordingObserver(); + withoutPeer(() -> receiver.readSelectedPublicationArtifactInventory(malformed, anonymous)); + assertInventoryDenied(anonymous, Status.Code.UNAUTHENTICATED); + + var wrongWorkload = new InventoryRecordingObserver(); + withPeer( + peer(NAMESPACE, "account-service"), + () -> receiver.readSelectedPublicationArtifactInventory(malformed, wrongWorkload)); + assertInventoryDenied(wrongWorkload, Status.Code.PERMISSION_DENIED); + + var wrongNamespace = new InventoryRecordingObserver(); + withPeer( + peer("other", "game-design-service"), + () -> receiver.readSelectedPublicationArtifactInventory(malformed, wrongNamespace)); + assertInventoryDenied(wrongNamespace, Status.Code.PERMISSION_DENIED); + + SessionContext.setContext( + "11111111-1111-4111-8111-111111111111", java.util.List.of(), java.util.Map.of()); + var endUserContext = new InventoryRecordingObserver(); + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> receiver.readSelectedPublicationArtifactInventory(malformed, endUserContext)); + assertInventoryDenied(endUserContext, Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + var ambientTransaction = new InventoryRecordingObserver(); + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> receiver.readSelectedPublicationArtifactInventory(malformed, ambientTransaction)); + assertInventoryDenied(ambientTransaction, Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + var authenticatedMalformed = new InventoryRecordingObserver(); + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> receiver.readSelectedPublicationArtifactInventory(malformed, authenticatedMalformed)); + assertInventoryDenied(authenticatedMalformed, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(readService, freezeService); + } + + private static void assertInventoryDenied( + InventoryRecordingObserver observer, Status.Code expectedCode) { + assertThat(Status.fromThrowable(observer.error).getCode()).isEqualTo(expectedCode); + assertThat(observer.response).isNull(); + assertThat(observer.completed).isFalse(); + } + private static GrpcPeerIdentity peer(String namespace, String service) { return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) .orElseThrow(); @@ -151,4 +217,29 @@ public void onCompleted() { completed = true; } } + + private static final class InventoryRecordingObserver + implements StreamObserver { + ReadSelectedPublicationArtifactInventoryResponse response; + Throwable error; + boolean completed; + + @Override + public void onNext(ReadSelectedPublicationArtifactInventoryResponse value) { + response = value; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The test collector retains the original throwable for assertion.") + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } } diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java index 75368914ef..b4d206d8a1 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java @@ -8,6 +8,8 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; import org.junit.jupiter.api.Test; class WorldSelectedPublicationArtifactInventoryTest { @@ -17,10 +19,10 @@ class WorldSelectedPublicationArtifactInventoryTest { @Test void acceptsExplicitEmptyRegionInputsAndClosedCanonicalSpawnBinding() { var region = - new WorldSelectedPublicationArtifactInventory.RegionGeneratorInput( + new WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput( UUID.randomUUID(), "", ""); var spawn = - new WorldSelectedPublicationArtifactInventory.SpawnBindingInput( + new WorldSelectedPublicationArtifactInventoryEvidence.SpawnBindingInput( UUID.randomUUID(), UUID.randomUUID(), "NPC", @@ -41,10 +43,10 @@ void acceptsExplicitEmptyRegionInputsAndClosedCanonicalSpawnBinding() { @Test void rejectsMissingOrNullRegionRequirednessInputsInsteadOfTreatingThemAsEmpty() { var missingType = - new WorldSelectedPublicationArtifactInventory.RegionGeneratorInput( + new WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput( UUID.randomUUID(), null, ""); var missingParams = - new WorldSelectedPublicationArtifactInventory.RegionGeneratorInput( + new WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput( UUID.randomUUID(), "", null); assertReason( @@ -62,7 +64,7 @@ void rejectsMissingOrNullRegionRequirednessInputsInsteadOfTreatingThemAsEmpty() @Test void rejectsOpaqueRegionAndGenerationRuleInputsAsUnrepresentable() { var opaqueGenerator = - new WorldSelectedPublicationArtifactInventory.RegionGeneratorInput( + new WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput( UUID.randomUUID(), "noise-v1", "{\"seed\":9}"); assertReason( @@ -80,7 +82,7 @@ void rejectsOpaqueRegionAndGenerationRuleInputsAsUnrepresentable() { @Test void rejectsUnsupportedEntityReferenceScopeOrRepresentation() { var unsupportedReference = - new WorldSelectedPublicationArtifactInventory.SpawnBindingInput( + new WorldSelectedPublicationArtifactInventoryEvidence.SpawnBindingInput( UUID.randomUUID(), UUID.randomUUID(), "NPC", @@ -102,68 +104,7 @@ void rejectsUnsupportedEntityReferenceScopeOrRepresentation() { void canonicalLongFieldsRoundTripAsExactDecimalStrings() { long beyondBinary64IntegerPrecision = 9_007_199_254_740_993L; long maximumLong = Long.MAX_VALUE; - var envelope = - new WorldSelectedPublicationArtifactInventory.Envelope( - WorldSelectedPublicationArtifactInventory.SCHEMA, - 1, - "COMPLETE", - new WorldSelectedPublicationArtifactInventory.OwnerScope( - "world", - TENANT, - VERSION, - Long.toString(beyondBinary64IntegerPrecision), - Long.toString(maximumLong), - UUID.randomUUID(), - Long.toString(maximumLong), - UUID.randomUUID(), - UUID.randomUUID(), - "sha256:" + "1".repeat(64), - UUID.randomUUID(), - "sha256:" + "2".repeat(64), - "sha256:" + "3".repeat(64)), - new WorldSelectedPublicationArtifactInventory.SourceIntake( - "world", Long.toString(maximumLong), "source-tenant", "CANONICAL"), - new WorldSelectedPublicationArtifactInventory.SelectedApplication( - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID().toString(), - "sha256:" + "4".repeat(64), - "sha256:" + "5".repeat(64)), - new WorldSelectedPublicationArtifactInventory.AccountOrder( - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - "publish", - "sha256:" + "6".repeat(64), - UUID.randomUUID().toString(), - "sha256:" + "7".repeat(64), - new byte[] {1}), - new WorldSelectedPublicationArtifactInventory.Freeze( - UUID.randomUUID(), - "publish", - "8".repeat(64), - Long.toString(maximumLong), - "workflow"), - new WorldSelectedPublicationArtifactInventory.Checkpoint( - UUID.randomUUID().toString(), "9".repeat(64), 3), - new WorldSelectedPublicationArtifactInventory.SourceModel( - "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1", - 2, - "sha256:" + "a".repeat(64), - "sha256:" + "b".repeat(64), - List.of(), - List.of(), - List.of(), - List.of(), - List.of(), - List.of(), - List.of(), - List.of(), - List.of(), - 0, - 0, - List.of()), - List.of()); + var envelope = envelopeWithCanonicalLongFields(beyondBinary64IntegerPrecision, maximumLong); byte[] canonicalBytes = WorldSelectedPublicationArtifactInventory.encode(envelope); String canonicalJson = new String(canonicalBytes, StandardCharsets.UTF_8); @@ -208,6 +149,203 @@ void canonicalLongFieldsRoundTripAsExactDecimalStrings() { .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); } + private static WorldSelectedPublicationArtifactInventory.Envelope envelopeWithCanonicalLongFields( + long beyondBinary64IntegerPrecision, long maximumLong) { + var complete = envelopeWithReversePublicInputOrder(); + var owner = complete.ownerScope(); + return new WorldSelectedPublicationArtifactInventory.Envelope( + complete.schema(), + complete.schemaVersion(), + complete.completeness(), + new WorldSelectedPublicationArtifactInventory.OwnerScope( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + Long.toString(beyondBinary64IntegerPrecision), + Long.toString(maximumLong), + owner.versionIdentityOperationId(), + Long.toString(maximumLong), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest()), + new WorldSelectedPublicationArtifactInventory.SourceIntake( + complete.sourceIntake().worldSlug(), + Long.toString(maximumLong), + complete.sourceIntake().sourceGameTenantKey(), + complete.sourceIntake().sourceProvenanceKind()), + complete.selectedApplication(), + complete.accountOrder(), + new WorldSelectedPublicationArtifactInventoryEvidence.Freeze( + complete.freeze().publicationFence(), + complete.freeze().publicationRequestId(), + complete.freeze().requestDigest(), + Long.toString(maximumLong), + complete.freeze().publishWorkflowId()), + complete.checkpoint(), + complete.sourceModel(), + complete.artifactDecisions()); + } + + @Test + void publicProjectionSortsTypedInputKeysWithoutRewritingRetainedPrivateEnvelope() { + var envelope = envelopeWithReversePublicInputOrder(); + byte[] storedBytes = WorldSelectedPublicationArtifactInventory.encode(envelope); + var inventory = new WorldSelectedPublicationArtifactInventory(envelope, storedBytes); + + assertThat(inventory.envelope().sourceModel().regionGeneratorInputs()) + .extracting( + WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput + ::regionTemplateId) + .containsExactly( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + UUID.fromString("11111111-1111-4111-8111-111111111111")); + assertThat(inventory.envelope().sourceModel().spawnBindingInputs()) + .extracting( + WorldSelectedPublicationArtifactInventoryEvidence.SpawnBindingInput::bindingTemplateId) + .containsExactly( + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + UUID.fromString("22222222-2222-4222-8222-222222222222")); + + var publicModel = inventory.publicEvidence().sourceModel(); + assertThat(publicModel.regionGeneratorInputs()) + .extracting( + WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput + ::regionTemplateId) + .containsExactly( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + assertThat(publicModel.spawnBindingInputs()) + .extracting( + WorldSelectedPublicationArtifactInventoryEvidence.SpawnBindingInput::bindingTemplateId) + .containsExactly( + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + assertThat(inventory.canonicalBytes()).containsExactly(storedBytes); + } + + private static WorldSelectedPublicationArtifactInventory.Envelope + envelopeWithReversePublicInputOrder() { + var sourceModel = + new WorldSelectedPublicationArtifactInventoryEvidence.SourceModel( + "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1", + 2, + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + List.of( + new WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount("REGION", 2), + new WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount("ZONE", 1), + new WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount("ROOM", 1), + new WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount("ROOM_EXIT", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount( + "GENERATION_RULE", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount( + "WORLD_ENTITY_SPAWN_BINDING", 2)), + List.of( + new WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), "", ""), + new WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput( + UUID.fromString("11111111-1111-4111-8111-111111111111"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of( + spawnBinding("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + spawnBinding("22222222-2222-4222-8222-222222222222")), + 0, + 2, + List.of(new AppliedEpoch("ROOM", "room-1", "ZONE", "zone-1", "1", "2"))); + return new WorldSelectedPublicationArtifactInventory.Envelope( + WorldSelectedPublicationArtifactInventory.SCHEMA, + 1, + "COMPLETE", + new WorldSelectedPublicationArtifactInventory.OwnerScope( + "world", + TENANT, + VERSION, + "9007199254740993", + "9223372036854775807", + UUID.randomUUID(), + "9223372036854775807", + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "1".repeat(64), + UUID.randomUUID(), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)), + new WorldSelectedPublicationArtifactInventory.SourceIntake( + "world", "9223372036854775807", "source-tenant", "CANONICAL"), + new WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID().toString(), + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64)), + new WorldSelectedPublicationArtifactInventory.AccountOrder( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "publish", + "sha256:" + "6".repeat(64), + UUID.randomUUID().toString(), + "sha256:" + "7".repeat(64), + new byte[] {1}), + new WorldSelectedPublicationArtifactInventoryEvidence.Freeze( + UUID.randomUUID(), "publish", "8".repeat(64), "9", "workflow"), + new WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint( + UUID.randomUUID().toString(), "9".repeat(64), 3), + sourceModel, + List.of( + new WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static WorldSelectedPublicationArtifactInventoryEvidence.SpawnBindingInput spawnBinding( + String bindingId) { + return new WorldSelectedPublicationArtifactInventoryEvidence.SpawnBindingInput( + UUID.fromString(bindingId), + UUID.randomUUID(), + "ITEM", + "ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID", + TENANT, + VERSION, + UUID.randomUUID(), + 1, + 0); + } + private static void assertReason( Runnable action, WorldSelectedPublicationArtifactInventory.UnrepresentableReason expected) { Throwable failure = catchThrowable(action::run); From fc07d1da90041e4e06d1814d11700c229b73143e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:04:46 +1300 Subject: [PATCH 038/129] Bind original World inventory into publication operations --- .../account-service/api-contracts.md | 2 +- .../ability-action-tools.md | 17 +- .../game-design-service/asset-storage.md | 4 +- .../game-design-service/version-control.md | 4 +- .../game-logic-service/runtime-and-data.md | 4 +- .../world-management-service/api-contracts.md | 4 +- ...ame-authoring-publishing-and-activation.md | 6 +- ...untPublicationAuthorizationRepository.java | 2 +- ...108__selected_publication_inventory_v2.sql | 465 ++++++++++++++++++ ...horizationMtlsPostgresIntegrationTest.java | 5 +- ...nAuthorizationPostgresIntegrationTest.java | 102 +++- .../common-platform-core/build.gradle.kts | 1 + ...GameDesignPublicationOperationBinding.java | 41 +- ...dPublicationArtifactInventoryEvidence.java | 82 +++ ...DesignPublicationOperationBindingTest.java | 101 ++++ ...nPublicationTerminalReadGrpcCodecTest.java | 6 +- ...atedWorldPublicationInventoryFixtures.java | 163 ++++++ .../GameDesignPublicationOperation.java | 24 +- ...ectedDraftPublicationAdmissionService.java | 20 +- ...electedDraftPublicationCommandService.java | 10 +- .../SelectedDraftPublicationOwner.java | 6 +- ...56__publication_operation_inventory_v2.sql | 291 +++++++++++ .../draft/IsolatedPublicationOwnerSetup.java | 2 +- .../IsolatedPublicationOperationFixtures.java | 6 +- ...setPublicationPostgresIntegrationTest.java | 4 +- ...emptServiceTransactionIntegrationTest.java | 159 +++++- ...dDraftPublicationAdmissionServiceTest.java | 79 ++- ...56__publication_operation_inventory_v2.sql | 192 ++++++++ ...uthorizedDraftPostgresIntegrationTest.java | 126 +++++ ...nceAssociationPostgresIntegrationTest.java | 50 +- ...aphApplicationPostgresIntegrationTest.java | 51 +- ...DesignPublicationTerminalVerifierTest.java | 4 +- 32 files changed, 1959 insertions(+), 74 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V108__selected_publication_inventory_v2.sql create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java create mode 100644 services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V56__publication_operation_inventory_v2.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V56__publication_operation_inventory_v2.sql diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 2342e34cf0..0d441a20d2 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -82,7 +82,7 @@ The standalone, unregistered `AccountPublicationAuthorizationReadService.ReadHel Account acquires this distinct publication order from the authenticated acting account and immutable Game Design Draft selection before World freeze. Its original actor, canonical tenant, selected-Draft digest, exact source versions and Account fence remain immutable across retry and recovery. The later World capture is correlated separately and must not rewrite the original order or its digest. Applicable source participation protects the authorized operation through actual World commit; a remote `HELD` sample alone is not commit-time protection. Participation may be released only after authenticated exact publication commit/abort readback, never from timeout, absence, a Draft terminal receipt or ambiguous publication evidence. Retained orders and their evidence remain immutable under forward-only migration. The current unregistered producer/read components do not yet establish this complete terminal settlement boundary. -Settlement compares two distinct authenticated owner results: Game Design's original immutable terminal and World's independently committed terminal for the same complete publication operation. `PUBLISHED` must agree with World `PUBLISHED`; Game Design `NO_PUBLICATION` must agree with World `ABORTED`. Both must bind the same complete original operation and terminal bytes. Account obtains the owner reads outside SQL, then serializes its immutable settlement receipt with the original order and sorted source locks. Only that exact committed receipt removes this order's pending participation; it does not rewrite the original authorization or clear another operation. Read correlation IDs are not settlement mutation identities: exact retries replay the original receipt even when new owner-read correlations are used. Once settled, an external `HELD` read must deny; internal exact historical validation remains available for recovery without minting fresh authority. Any disagreement or unresolved owner result preserves participation and grants no admission. +Settlement compares two distinct authenticated owner results: Game Design's original immutable terminal and World's independently committed terminal for the same complete publication operation. `PUBLISHED` must agree with World `PUBLISHED`; Game Design `NO_PUBLICATION` must agree with World `ABORTED`. Both must bind the same complete original operation and terminal bytes, including the original authenticated World inventory under the [Game Design operation binding](../game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state); incomplete historical evidence cannot authorize a new settlement. Account obtains the owner reads outside SQL, then serializes its immutable settlement receipt with the original order and sorted source locks. Only that exact committed receipt removes this order's pending participation; it does not rewrite the original authorization or clear another operation. Read correlation IDs are not settlement mutation identities: exact retries replay the original receipt even when new owner-read correlations are used. Once settled, an external `HELD` read must deny; internal exact historical validation remains available for recovery without minting fresh authority. Any disagreement or unresolved owner result preserves participation and grants no admission. The selected-order composition authenticates the exact same-namespace Game Design caller, obtains the [immutable selected-Draft owner read](../game-design-service/api-contracts.md#immutable-selected-draft-publication-read) outside Account SQL, then passes the unchanged creator credential and exact retained selection to Account's current-actor/source-hold owner transaction. `SELECTED` alone is not actor authorization. No database lock may span that read, and unavailable or substituted selection evidence cannot create an order. Implementation and executed proof remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). diff --git a/design/architecture/microservices/game-design-service/ability-action-tools.md b/design/architecture/microservices/game-design-service/ability-action-tools.md index d938afe9f5..916d3292bc 100644 --- a/design/architecture/microservices/game-design-service/ability-action-tools.md +++ b/design/architecture/microservices/game-design-service/ability-action-tools.md @@ -1,6 +1,6 @@ # Ability & Action Design Tools -This document outlines the editors for defining abilities, actions, and combat mechanics. The tooling is part of the Game Design Service and pushes finalized data to the [Game Logic Service](../game-logic-service/README.md) during version publishing. +This document outlines Game Design's authored ability, action and combat definitions. Game Design owns their authoring and revision history; Game Logic owns validation and immutable retention of the exact selected gameplay-rule inputs under its [selected-release intake contract](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake). That mutation-authorized source handoff precedes the read-only publication digest gate. Game Logic is not a mutation participant in the publication workflow, and a digest read never creates or repairs its retained source. The publish workflow is part of the durable control-plane workflow described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). @@ -8,8 +8,7 @@ The publish workflow is part of the durable control-plane workflow described in The current proven behavior is stable-reference validation against the exact published base version for the plugin publication path. `abilitySchemaDigest` is persisted in plugin metadata and exposed by the publication read, but dedicated Game Logic-owned release-attested ability-schema validation remains target-state and unproved. Current plugin publication and activation compare the plugin's `abilitySchemaDigest` with the published `AUTOMATION_SCRIPTING` aggregate participant digest; that aggregate comparison is not a dedicated ability-schema attestation. Script-patch publication does not currently enforce same-tenant published-base identity, and launch resolution does not currently prove same-base published patch identity or Automation `READY`; those are implementation gaps. Exact `scriptPinEpoch` propagation and same-version old-epoch rejection at runtime handoff are target-state and remain unproved; this design-time editor does not establish that runtime proof. See the [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#script-transition-reconciliation) and [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). -Data entered in these editors is stored as revisions using the `SaveRevision` gRPC call defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). -Finalized versions are published with `PublishVersion` so the Game Logic Service can load the rules as part of the cross-service publish workflow described in the [Game Design Service Architecture](README.md). +The current `SaveRevision` API in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto) stores revision data; its supported `COMMAND_DEFINITION` shape and selected command-source capture do not implement the complete ability/action catalogs, policies or targeting declarations below. In particular, its existing `actionTags` are not the dedicated `admissionTags` contract. An authenticated Game Design source producer, Game Logic retained manifest and exact source-operation readback remain absent; missing storage or unsupported declarations cannot establish an empty rule set. `PublishVersion` must consume the independently retained owner evidence rather than populate Game Logic through the digest read. Ability definitions use a structured schema delivered through the API. @@ -121,7 +120,7 @@ Example: if an `onInterval` combat-support handler can branch into at most eight At runtime, a published game version ties together: -- Ability/action definitions owned by the Game Logic Service. +- Game Design-authored ability/action definitions validated and immutably retained by Game Logic for the exact selected release. - Script and plugin patch versions owned by the Automation & Scripting Service. Within a given published game version: @@ -160,12 +159,12 @@ From an observability perspective, live script and plugin invocations (`isDryRun - **Balancing Metrics** – display damage, healing, and resource impact to help tune gameplay. - **Integration with [Item & Equipment Balancing](item-equipment-balancing.md)** – ability damage values can be compared against item statistics for overall balance. -## Workflow +## Target Workflow -1. Abilities and actions are created in the web UI and saved via `SaveRevision`. -2. Designers can group related abilities into categories for organization. -3. Each revision becomes part of a published version through `PublishVersion`. -4. When a version is published, abilities are copied to the Game Logic Service using the `version_id`. +1. Designers author typed ability/action and referenced catalog definitions through Game Design's revision and synchronized-commit boundary. The complete editor and source writers remain subject to the implementation limits above. +2. Before publication digest collection, an authenticated, mutation-authorized source operation delivers the exact selected commit's complete effective inputs to Game Logic for validation and immutable retention. +3. `PublishVersion` reads the already retained Game Logic evidence and independently checks its aggregate manifest and dedicated ability-schema attestations for that same selection. It neither copies abilities as a publication mutation nor repairs missing source through a digest read. +4. Runtime consumes only the resulting pinned, published release. Intake or digest success alone does not activate it. ## Related Documentation diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 56f4eaefa4..57ba3c8948 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,8 +6,8 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b ## Implementation Status -- **Current first slice:** The ordinary exporter requires V37's durable version-scoped snapshot and verifies its mappings and retained `game_assets.data` bytes before each export or retry. There is no tenant-wide fallback or process-local selection cache. A local `ASSET_REFERENCE` producer candidate now supplies coordinator/history/genesis/snapshot writing and export agreement, but it has not yet been validated or published; until then, production Draft source authoring and automatic snapshot creation remain unavailable, and missing evidence denies export rather than proving an empty release. Frozen source bytes are database-protected, while unreferenced Draft uploads remain mutable. Version-prefix object writes, numeric public asset identifiers and post-write repair comparison remain drift from the target immutable-candidate lifecycle. See the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle) for capability and proof limits. -- **Selected source coverage:** The construction branch includes the World owner's typed selected-release inventory, retained authenticated read and artifact-export checkpoint, which cover World-owned topology and derived-artifact requiredness only. Game Design's ordinary `ASSET_REFERENCE` source participates in actual fresh-Draft genesis, coordinator application, immutable commit snapshots and export-selection agreement. It is not total Game Design `COMPLETE`: the closed template-reference/config writer, branding records, exact requiredness authority across families and their owner-qualified readback remain absent. Ordinary assets remain `RESOURCE/REQUIRED`; branding has no implemented owner/consumer fallback policy, so no branding role is currently authoritatively `OPTIONAL`. The complete Game Design source/export gate remains closed until all families have exact selected-commit evidence. PostgreSQL and composed producer/consumer execution remain separate proof requirements; the unregistered authenticated World read is not yet retained in Game Design's durable publication operation. +- **Current first slice:** The ordinary exporter requires V37's durable version-scoped snapshot and verifies its mappings and retained `game_assets.data` bytes before each export or retry. There is no tenant-wide fallback or process-local selection cache. The published construction includes an `ASSET_REFERENCE` source repository with coordinator/history/genesis/snapshot writing and export agreement; this is not a registered production authoring ingress or proof of complete template/config and branding coverage. Missing evidence denies export rather than proving an empty release. Frozen source bytes are database-protected, while unreferenced Draft uploads remain mutable. Version-prefix object writes, numeric public asset identifiers and post-write repair comparison remain drift from the target immutable-candidate lifecycle. See the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle) for capability and proof limits. +- **Selected source coverage:** The construction branch includes the World owner's typed selected-release inventory, retained authenticated read and artifact-export checkpoint, which cover World-owned topology and derived-artifact requiredness only. Game Design's ordinary `ASSET_REFERENCE` source participates in actual fresh-Draft genesis, coordinator application, immutable commit snapshots and export-selection agreement. It is not total Game Design `COMPLETE`: the closed template-reference/config writer, branding records, exact requiredness authority across families and their owner-qualified readback remain absent. Ordinary assets remain `RESOURCE/REQUIRED`; branding has no implemented owner/consumer fallback policy, so no branding role is currently authoritatively `OPTIONAL`. The complete Game Design source/export gate remains closed until all families have exact selected-commit evidence. The unregistered admission construction retains the authenticated World read in its complete original publication operation; PostgreSQL and genuine composed producer/consumer execution remain separate proof requirements in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). - **Current upload admission gap:** The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) are requirements, not current proof. `AssetController` accepts multipart uploads and `GameAssetServiceImpl` calls `MultipartFile.getBytes()` without size or quota enforcement; `AssetStoreProperties` has no matching limits. Upload admission and resource-safety readiness therefore remain incomplete and the route must not be treated as ready for external enablement. - **Hosted-content gate gap:** Current asset upload and publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The current Gateway's coarse `/api/design/**` route nevertheless forwards `/api/design/assets` (after `StripPrefix=2`) to the live `POST /assets` controller, whose Game Design boundary checks only privileged JWT/tenant access. Official-hosted asset-upload readiness is blocked until Gateway denies that route or the exact Account-owned gate is implemented and proved. - **Current lifecycle proof:** `version_asset_artifact` records the exported version-number prefix and manifest asset keys, but it does not yet freeze the target exact immutable object-key/digest set or implement the target global publication/purge fence. Repair writes those live prefix objects and the manifest before its exact release-bundle comparison, so pre-write verification is target-only. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index e19fe1020e..d241ad0285 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -6,7 +6,7 @@ Game Design is the canonical authored-history, publication-coordination, release ## Implementation Status -Full-version finalization now requires the exact original World selector evidence retained by its pending publication operation and passes it to the v2 release-bundle path; missing or changed evidence remains pending for reconciliation, not permission to recapture or abort. The unregistered `SelectedDraftPublicationOwner` reserves one existing synchronized Draft, using its exact immutable selection digest for the pending attempt and source-backed publication operation. Its backend finalization entry requires exact durable selection/operation readback and shares the existing finalization transaction; it does not allocate a replacement Draft or translate a legacy full-publish digest. Typed Account and World inputs are not authentication of their producers. The standalone, unregistered `SelectedDraftPublicationAdmissionService` obtains both the distinct Account held-publication authorization and exact World selector through their authenticated clients outside SQL, validates their complete operation relationship, then opens the local reservation transaction. Its unit proof covers denial and ordering, not genuine positive transport/release composition. It does not create a World freeze, register a creator ingress, or enable publication or runtime paths. Current construction and executable proof limits are recorded in the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +Full-version finalization requires the exact original World evidence retained by its pending publication operation and passes the selected World input to the v2 release-bundle path; missing or changed evidence remains pending for reconciliation, not permission to recapture or abort. The unregistered `SelectedDraftPublicationOwner` reserves one existing synchronized Draft, using its exact immutable selection digest for the pending attempt and source-backed publication operation. Its backend finalization entry requires exact durable selection/operation readback and shares the existing finalization transaction; it does not allocate a replacement Draft or translate a legacy full-publish digest. Typed Account and World inputs are not authentication of their producers. The standalone, unregistered `SelectedDraftPublicationAdmissionService` obtains distinct Account held-publication authorization, begins or exactly replays World's authenticated freeze, and reads its exact selector and immutable inventory outside SQL before opening the local reservation transaction. Its bounded ordering and retention proof does not establish genuine positive release composition. It registers no creator ingress and enables no publication or runtime paths. Current construction and executable proof limits are recorded in the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). External Git synchronization and canonical multi-branch merge semantics are not implemented. Current authoring uses Game Design-owned revision APIs with optimistic validation and ordered mutation calls, but `SaveRevision` does not provide deterministic replay: it lacks durable request/revision deduplication and can leave a World mutation committed without its corresponding Game Design revision when the later local save fails. ADR 0129's durable multi-owner coordinator, owner-local compare-and-swap application, synchronized commit fence, and proof that partially applied owner rows remain invisible to ordinary Draft reads are also not implemented. Current release-bundle schema and plugin publication/activation code incorrectly reuse Automation & Scripting's aggregate participant `contentDigest` where the dedicated Game Logic-owned `abilitySchemaDigest` is required; exact ability-schema compatibility therefore remains an implementation and proof gap. Plugin publication currently uses signed-only intake; [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md)'s approved unsigned provenance remains target-only. The plugin publication path now rejects terminal-state reuse: an uploaded `SUPERSEDED` or `REVOKED_DESIGN` row cannot be republished under the same `pluginVersionId`; target rollback still uses a new immutable plugin version and leaves the prior terminal row unchanged, while new-version rollback proof remains absent. Duplicate signed plugin `assetId` values are likewise not rejected before export and can produce ambiguous distribution-manifest keys; target intake rejects them deterministically before publication/export. The live World Management design handoff adds a separate lifecycle race: it checks Game Design's authoritative remote version state (`GetVersionState(...).versionState=DRAFT`) before its own transaction, but has no durable owner-local publication freeze or exact Game Design version-state epoch/fence in the mutation request. That remote state check is not proof that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). @@ -68,6 +68,8 @@ The [immutable selected-Draft owner read](api-contracts.md#immutable-selected-dr The synchronized Draft fence is also the lifecycle handoff into publication. Game Design first obtains the distinct [Account publication authorization](../account-service/api-contracts.md#grpc-apis) for its authenticated immutable Draft selection, then presents that exact order for World freeze; later World capture is separate correlation, not a rewrite of Account authorization. Before collecting the World Management participant digest, reading the final release state, or committing `published_release_bundle` and `PUBLISHED` metadata, Game Design must obtain and retain the exact WMS owner-freeze acknowledgement, then complete or abort that same owner operation after reconciling its publication outcome. The canonical WMS operations, fields, phase transitions, exact replay/conflict behavior, and current implementation/proof boundary are defined in [World Management API Contracts](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state). This is one owner-local freeze protocol, not a distributed transaction: the freeze serializes WMS Draft writes, while Game Design remains the lifecycle and final-attestation authority. Focused proof must interleave a WMS mutation with freeze acquisition, publication, retry, abort, and lost-response reconciliation and prove that no post-freeze Draft row or digest can become part of a Published release. +The original durable operation uses the closed `game-design-publication-operation/v2` binding. In fixed order it contains exactly five ADR 0047-style byte-length frames: schema, original Account authorization bytes, original World selector bytes, canonical public World inventory bytes, and that inventory's `sha256:`-prefixed digest. The complete operation is bounded to 4 MiB. The inventory must satisfy the [World owner contract](../world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) for the same original Account order, selection, retained freeze/checkpoint and applied graph; a valid digest alone does not authenticate that evidence. Game Design obtains authenticated owner reads outside SQL before the first reservation and retains their exact bytes with the operation. Exact durable retries read back that original operation without recapturing Account authority, a new freeze, selector or inventory. Terminal publication and Account settlement compare the same complete operation. Older retained operations are not rewritten, backfilled or supplied an inferred inventory; an incomplete historical operation cannot authorize new positive publication or settlement. + **Current implementation gap:** World Management currently lacks the durable owner-local publication freeze and exact Game Design version-state epoch/fence enforcement required by this target contract. Its live handoff checks the authoritative remote Game Design `DRAFT` state before its own transaction, but that check does not prove that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). The Game Design Service tracks a derived `designSyncStatus` for each `(tenantId, versionId)`. It is `IN_SYNC` only when the durable commit record, every required owner result, and the synchronized commit fence agree on the exact commit and digest. The `PublishVersion` workflow must verify this state before starting durable publication. The coordinator may use the canonical durable workflow substrate and transactional outbox delivery where appropriate, but it must not claim cross-database atomicity or expose partial application as accepted Draft state. diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index b60710f507..c7c702132f 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -32,7 +32,7 @@ The sections below define the target-state runtime contract. Current implementat The Game Logic Service does not orchestrate or own synchronous saga or Temporal workflows. All gameplay commands execute inside ticks using Redis-based rollback and the transaction model described in [Transaction Strategies](../../system-architecture-transactions.md). -When a game version is published, its rule data is prepared and finalized by the Game Design and Game Session services; this service reads the already-published, versioned rule data for the active `runtime_version` and does not participate directly in the durable `publish` workflow. +Before a game version's publication digest gate, Game Design supplies its authored inputs through the separate authenticated source-intake boundary below, and Game Logic validates and immutably retains those exact inputs. Publication reads that retained evidence; it does not copy or finalize rule data here as a workflow mutation. Game Session remains the runtime orchestrator, not an alternate rule-authoring or source-retention authority. Runtime reads only the published, pinned release for the active `runtime_version`. Role classification: Game Logic is a digest-gate participant for full publishes, not a workflow-step participant, unless future publish workflows add explicit finalize or compensation steps owned by this service. @@ -55,6 +55,8 @@ The retained input set must be complete for the supported command inputs effecti Intake is a separate, mutation-authorized source operation. `GetDraftDesignDigest` remains a read-only full-version publication read over the already retained, exact-version evidence; it does not populate or repair that evidence. An empty selected input set is attestable only when an authenticated source operation proves the complete owner inventory for the exact selected commit is empty. Missing storage, a missing producer, or absent rows are not evidence of an empty authored set. +The authenticated publication read must preserve the exact source-operation and selected-commit correlation through its retained-manifest lookup and readback. Validating the publication request and then resolving content by tenant/version alone is insufficient when it can select a different source operation; neither a latest lookup nor request authentication repairs missing immutable provenance. + The full-version manifest and the dedicated `abilitySchemaDigest` share the selected commit and Game Logic's existing canonicalization and `digestSchemaVersion` contract, but they attest distinct scopes. The aggregate full-manifest `contentDigest` is not an ability-schema digest, and neither the Automation & Scripting digest nor Game Design's control-plane digest substitutes for either Game Logic attestation. Any change to the dedicated ability-schema input set or its canonicalization requires the same explicit schema bump and digest replay or re-record process as other manifest changes. This contract governs publication evidence only; it does not authorize activation of unpublished rules or make Game Logic a participant in Game Design's publication workflow mutations. Game Logic does not read an admin database for runtime rules. ## Redis Role and Prefixes diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 6a12f7b5fd..86fcd2d7fe 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -21,7 +21,7 @@ This API contract is target-state canonical; implementation coverage is partial - `ApplyRoomAmbientStatePatch` – applies a typed ambient fact patch to the target runtime scope under expected epoch/version preconditions and an operation/aggregate/request-digest-bound guard derived from the root `EffectId`; matching replay returns the durable prior result and a conflicting identity or payload fails closed. - `GetDraftDesignDigest` – returns the publish-gating digest for Draft world templates using the typed scope request `GetDraftDesignDigestRequest { tenantId, scope: oneof { versionId, scriptPatchVersion } }`. World Management supports `versionId` scope only and must return `UNSUPPORTED_SCOPE` for `scriptPatchVersion`. - `BeginVersionPublicationFreeze` – starts or exactly replays the durable WMS owner freeze for one `(tenantId, versionId)` publication request and returns the request/fence/epoch/digest checkpoint acknowledgement defined below. A closed standalone proto, strict client and owner-resolving receiver are construction components only; runtime registration and the complete producer handoff remain unavailable. -- `ReadSelectedPublicationArtifactInventory` – reads only the exact immutable inventory for the supplied original freeze request and committed acknowledgement. The construction adapter authenticates same-namespace Game Design before parsing, checks retained freeze/Account bindings and returns the canonical public projection plus its distinct digest. It does not begin a freeze, recapture sources, or return private numeric owner keys. Runtime registration and Game Design durable-operation consumption remain unavailable; [World runtime/data](runtime-and-data.md#complete-selected-release-artifact-inventory) owns the inventory contract. +- `ReadSelectedPublicationArtifactInventory` – reads only the exact immutable inventory for the supplied original freeze request and committed acknowledgement. The construction adapter authenticates same-namespace Game Design before parsing, checks retained freeze/Account bindings and returns the canonical public projection plus its distinct digest. It does not begin a freeze, recapture sources, or return private numeric owner keys. The unregistered Game Design admission construction consumes and retains this read; runtime registration and genuine composed proof remain unavailable. [World runtime/data](runtime-and-data.md#complete-selected-release-artifact-inventory) owns the inventory contract. - `CompleteVersionPublication` – **Target state:** exactly replays or terminalizes the same WMS freeze with a `PUBLISHED` or `ABORTED` outcome and matching bundle/digest evidence. Unregistered terminal composition and storage exist, but a registered completion RPC and genuine composed terminal handoff remain unavailable. - `ValidateWorldUpgradeMappings` – validates world-owned durable references and approved remap sets for replacement-instance cutover to a target `(tenantId, versionId)`. - `PrepareWorldInstance` – creates or reuses the canonical `PREPARING` world lifecycle row for a resolved launch descriptor, validates release-bundle and `versionStateEpoch` proof against Game Design, and materializes first-cut instance topology rows without admitting gameplay yet. @@ -113,7 +113,7 @@ Game Design completes the handoff through one outcome-typed terminal operation, Terminal retries are exact only when the complete request, digest, fence, outcome, and evidence match the stored terminal result. Changed or omitted input returns `IDEMPOTENCY_CONFLICT`; a conflicting nonterminal request, unknown fence, contradictory bundle/digest evidence, or unavailable owner read remains `RECONCILIATION_REQUIRED` and must not release the freeze. A failed or ambiguous publication therefore reuses the original `publicationRequestId` and `publicationFence` until WMS and Game Design agree on the durable bundle/version outcome; it cannot mint a second freeze or resume Draft writes by timeout. -First terminal completion and every terminal retry/readback must also compare the complete distinct Account publication-order bytes, operation ID and fence against the immutable qualification retained with the first World freeze. The older Account Draft `COMMIT_ORDER` inside the World application evidence is not that publication order. An unqualified historical freeze cannot be upgraded by supplying later terminal evidence. World verifies the original Game Design terminal through an authenticated owner read outside SQL; that immutable result remains historical evidence through the local commit, not a remote Account lock or permission to release Account source participation. +First terminal completion and every terminal retry/readback must also compare the complete distinct Account publication-order bytes, operation ID and fence against the immutable qualification retained with the first World freeze. The older Account Draft `COMMIT_ORDER` inside the World application evidence is not that publication order. The [complete Game Design operation binding](../game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state) includes World's original canonical public inventory and digest; World compares that complete projection with its own retained inventory, not a caller reconstruction or later source sample. An unqualified historical freeze cannot be upgraded by supplying later terminal evidence. World verifies the original Game Design terminal through an authenticated owner read outside SQL; that immutable result remains historical evidence through the local commit, not a remote Account lock or permission to release Account source participation. Account settlement requires a separate World-authenticated terminal read. Its versioned request binds the namespace, non-nil read correlation ID, complete original publication operation and exact expected Game Design terminal bytes; those bytes identify the lookup and do not prove a World commit. Only the authenticated same-namespace Account workload may call it, and World must authenticate that caller before decoding or reading storage. World returns the exact request and original stored terminal bytes only after its own independent owner snapshot proves the qualified attempt and matching terminal phase (`PUBLISHED` or `ABORTED`). Missing, pending, unqualified, substituted, corrupt or unavailable owner evidence supplies no settlement result. The read never completes publication, releases an Account hold or authorizes admission; registration and executed proof remain separately gated in the implementation tracker. 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 ff6f9fe906..eff444a1e7 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 @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The selected-release inventory contract is explicit in the [World owner](../../architecture/microservices/world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) and [Game Design asset owner](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). The construction branch includes the World selected-graph inventory, retained authenticated read and derived-artifact export checkpoint; these attest World source only and do not establish Game Design source completeness, a release bundle or activation. Game Design's synchronized source repository covers commands, realm policy and ordinary `ASSET_REFERENCE` source history, with actual fresh-Version genesis, coordinator application, immutable selected-commit snapshots and export agreement. The ordinary source has focused unit and PostgreSQL test definitions, but local PostgreSQL execution and composed producer/consumer proof remain required. V37's mappings and nullable usage classifier do not enumerate selected template/branding references or launch requiredness, and mutable template configuration has no exact selected-commit source binding. The canonical closed config schema is documented in [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state), but its versioned writer, normalized reference rows, owner-resolved readback and integration into the selected source inventory remain unimplemented. The real authorized source-writing ingress and retention of World inventory in Game Design's durable publication operation are also incomplete. Complete source coverage still requires the template/config and branding families, exact requiredness authority, fenced commit history and immutable manifest/export proof. Fresh command/policy/ordinary genesis, absent mappings or absent consumers cannot supply an empty baseline for other families. All genuine publication and runtime activation gates remain open obligations, not completed handoffs. +The selected-release inventory contract is explicit in the [World owner](../../architecture/microservices/world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) and [Game Design asset owner](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). Construction includes World's immutable selected-graph inventory and authenticated read, plus Game Design's mandatory v2 retention of that inventory in the complete original publication operation. The unregistered first-admission path obtains authenticated Account, freeze, inventory and selector evidence outside SQL; local durable retries reuse their original bytes without those RPCs. Additive owner guards reject incomplete v1 inputs for new operations, captures, terminal outcomes and settlement; retained history is not rewritten. This is not a genuine complete producer-to-release-to-settlement handoff or activation. + +Game Design's synchronized source repository covers commands, realm policy and ordinary `ASSET_REFERENCE` source history, with actual fresh-Version genesis, coordinator application, immutable selected-commit snapshots and export agreement. Total Game Design source completeness remains unimplemented: V37 mappings and nullable usage classifiers do not enumerate selected template/branding references or launch requiredness, and mutable template configuration is not selected-commit evidence. The [closed config contract](../../architecture/microservices/game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state) still needs its actual authorized versioned writers, normalized references, owner-qualified readback and inventory integration. Game Logic's complete authored-input producer/intake, exact requiredness authority, immutable manifest/export, registered ingress and composed proof remain open. Fresh command/policy/ordinary genesis, absent mappings or absent consumers cannot establish empty families. All four genuine Gameplay handoffs and runtime activation remain open obligations. + +The v2 Common/Game Design local gate executed 328 Common and 390 Game Design unit cases without failures or skips; 88 Game Design PostgreSQL definitions compiled but skipped without Docker. Game Design V56 schema generation, formatting, static checks, coverage, boot jar, links and Markdown passed. Its additional direct-SQL historical-v1 policy-set denial and the separate Account V108/World V56 guard-and-fixture batch require the subsequent consolidated gate and physical execution. The inventory loopback endpoint in Game Design's composition test is explicitly stipulated upstream evidence, not execution of World's real inventory producer. Published-head `39b800bdfe07cf94028fd4a175f79f42eb51c8e7` [Validation run 37853634338](https://github.com/benhook1013/FireMUD/actions/runs/37853634338) executed 245 Account, 81 Game Design and 206 World integration cases, with zero errors or skips. World passed in full. Game Design's selected-publication composition and four of five asset cases passed; the remaining asset fixture attempted a forbidden frozen-source update and correctly encountered the immutable-source trigger. The corrected fixture now requires SQLSTATE `23514`, unchanged source bytes and exact snapshot/retry readback; corrected-head PostgreSQL execution remains required. Account's serialization-specific retry and all nine isolated WAL cases passed. Its sole failure was the independent receipt-confirmation case at V90's conservative global-WAL coverage check: insert fence `0/4C2F760` exceeded flush `0/4C2F720`. This is still an open durability limitation, not production adoption of the isolated WAL investigation. Owner jobs used merge `a7d44052a8b69826f9673392da2a5a6bc973a7ad`, tree `aca615119c487f744e4f787a3042df993a8dbf65`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head; intended-parent alignment remains open. Security, CodeQL, License, Kustomize, preview planning and dependency submission passed. Optional downstream preview steps skipped, so this is not full-stack Smoke or proof of the later World inventory/export corrections. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java index 2970647349..f583c222a5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java @@ -313,7 +313,7 @@ private static void validateRetainedWorldIfPresent( Record row, AccountPublicationAuthorizationBinding binding) { byte[] worldEvidence = row == null ? null : row.get("world_evidence", byte[].class); if (worldEvidence != null) { - new GameDesignPublicationOperationBinding( + GameDesignPublicationOperationBinding.requireAccountWorldCorrelation( binding, WorldPublishedStartLocationEvidence.fromStored(worldEvidence)); } } diff --git a/services/account-service/src/main/resources/db/migration/V108__selected_publication_inventory_v2.sql b/services/account-service/src/main/resources/db/migration/V108__selected_publication_inventory_v2.sql new file mode 100644 index 0000000000..3a61bd3ef4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V108__selected_publication_inventory_v2.sql @@ -0,0 +1,465 @@ +-- Mandatory v2 inventory applies to new settlements only; immutable retained rows are not upgraded. +-- [jooq ignore start] +CREATE FUNCTION selected_inventory_operation_frame(operation_bytes BYTEA, frame_offset INTEGER) RETURNS BYTEA AS $$ +DECLARE length_bytes BIGINT; +BEGIN + IF frame_offset < 0 OR frame_offset > octet_length(operation_bytes) - 4 THEN + RAISE EXCEPTION 'Truncated publication inventory frame' USING ERRCODE = '23514'; END IF; + length_bytes := get_byte(operation_bytes, frame_offset)::BIGINT * 16777216 + + get_byte(operation_bytes, frame_offset + 1)::BIGINT * 65536 + + get_byte(operation_bytes, frame_offset + 2)::BIGINT * 256 + + get_byte(operation_bytes, frame_offset + 3)::BIGINT; + IF length_bytes > 4194304 OR length_bytes > octet_length(operation_bytes) - frame_offset - 4 THEN + RAISE EXCEPTION 'Oversized publication inventory frame' USING ERRCODE = '23514'; END IF; + RETURN substring(operation_bytes FROM frame_offset + 5 FOR length_bytes::INTEGER); +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION selected_inventory_operation_nth(operation_bytes BYTEA, frame_index INTEGER) RETURNS BYTEA AS $$ +DECLARE offset_bytes INTEGER := 0; value BYTEA; i INTEGER; +BEGIN + IF frame_index < 0 THEN RAISE EXCEPTION 'Negative frame index' USING ERRCODE = '23514'; END IF; + FOR i IN 0..frame_index LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + END LOOP; + RETURN value; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION require_selected_inventory_operation_v2(operation_bytes BYTEA) RETURNS VOID AS $$ +DECLARE frames BYTEA[] := ARRAY[]::BYTEA[]; value BYTEA; offset_bytes INTEGER := 0; + account_bytes BYTEA; input_bytes BYTEA; selection_bytes BYTEA; + selector JSONB; inventory JSONB; selected JSONB; selected_binding JSONB; + applied JSONB; applied_bytes BYTEA; applied_operation BYTEA; original_account BYTEA; + owner JSONB; application JSONB; account_order JSONB; frozen JSONB; checkpoint JSONB; + model JSONB; expected_epochs JSONB; expected_tuples JSONB; i INTEGER; + shape RECORD; member RECORD; item JSONB; previous_key TEXT; + counts INTEGER[] := ARRAY[]::INTEGER[]; +BEGIN + IF operation_bytes IS NULL OR octet_length(operation_bytes) NOT BETWEEN 1 AND 4194304 THEN + RAISE EXCEPTION 'Complete bounded v2 publication operation required' USING ERRCODE = '23514'; END IF; + FOR i IN 0..4 LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + frames := array_append(frames, value); + END LOOP; + IF offset_bytes <> octet_length(operation_bytes) OR frames[1] <> convert_to('game-design-publication-operation/v2', 'UTF8') + OR frames[5] IS DISTINCT FROM convert_to('sha256:' || encode(sha256(frames[4]), 'hex'), 'UTF8') THEN + RAISE EXCEPTION 'Publication v2 schema, exact frame count or inventory digest invalid' USING ERRCODE = '23514'; END IF; + account_bytes := frames[2]; + input_bytes := selected_inventory_operation_nth(account_bytes, 3); + selection_bytes := selected_inventory_operation_nth(input_bytes, 2); + IF NOT (convert_from(selection_bytes, 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'Original Account selection requires unique closed JSON members' USING ERRCODE = '23514'; END IF; + selected := convert_from(selection_bytes, 'UTF8')::JSONB; + IF NOT ((selected->>'selectedCommitBindingJson') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'Selected Account commit binding requires unique closed JSON members' USING ERRCODE = '23514'; END IF; + selected_binding := (selected->>'selectedCommitBindingJson')::JSONB; + IF octet_length(frames[3]) = 0 OR octet_length(frames[4]) = 0 + OR NOT (convert_from(frames[3], 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) + OR NOT (convert_from(frames[4], 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'Complete unique World selector and public inventory required' USING ERRCODE = '23514'; END IF; + selector := convert_from(frames[3], 'UTF8')::JSONB; + inventory := convert_from(frames[4], 'UTF8')::JSONB; + applied_bytes := decode(selector->>'appliedResultBytesBase64', 'base64'); + IF NOT (convert_from(applied_bytes, 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'APPLIED result requires unique closed JSON members' USING ERRCODE = '23514'; END IF; + applied := convert_from(applied_bytes, 'UTF8')::JSONB; + applied_operation := decode(applied->>'operationBytesBase64', 'base64'); + original_account := decode(selector->>'originalAccountBindingBytesBase64', 'base64'); + owner := inventory->'ownerScope'; application := inventory->'selectedApplication'; + account_order := inventory->'accountOrder'; frozen := inventory->'freeze'; + checkpoint := inventory->'checkpoint'; model := inventory->'sourceModel'; + FOR shape IN SELECT * FROM (VALUES + (inventory, ARRAY['schema','schemaVersion','completeness','ownerScope','selectedApplication','accountOrder','freeze','checkpoint','sourceModel','artifactDecisions']), + (owner, ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId','versionIdentityOperationId','intakeRequestId','intakeOperationId','intakeRequestDigest','sourceOperationId','sourceEvidenceDigest','intakeReceiptDigest']), + (application, ARRAY['applicationOperationId','applicationRequestId','appliedCommitId','bindingDigest','appliedResultDigest']), + (account_order, ARRAY['operationId','fenceId','actorAccountId','publicationRequestId','selectionDigest','selectedCommitId','bindingDigest']), + (frozen, ARRAY['publicationFence','publicationRequestId','requestDigest','versionStateEpoch','publishWorkflowId']), + (checkpoint, ARRAY['appliedCommitId','contentDigest','digestSchemaVersion']), + (model, ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs']) + ) AS shapes(value, keys) LOOP + IF jsonb_typeof(shape.value) IS DISTINCT FROM 'object' + OR NOT shape.value ?& shape.keys + OR (SELECT count(*) FROM jsonb_object_keys(shape.value)) <> cardinality(shape.keys) + OR EXISTS (SELECT 1 FROM jsonb_each(shape.value) entry WHERE entry.value = 'null'::JSONB) THEN + RAISE EXCEPTION 'Incomplete or unknown public inventory members' USING ERRCODE = '23514'; END IF; + END LOOP; + FOR shape IN SELECT * FROM (VALUES (owner), (application), (account_order), (frozen), (checkpoint)) AS shapes(value) LOOP + FOR member IN SELECT * FROM jsonb_each(shape.value) LOOP + IF member.key <> 'digestSchemaVersion' AND jsonb_typeof(member.value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Inventory binding members require exact string types' USING ERRCODE = '23514'; END IF; + IF member.key IN ('canonicalTenantId','canonicalVersionId','versionIdentityOperationId','intakeRequestId','intakeOperationId','sourceOperationId','applicationOperationId','applicationRequestId','appliedCommitId','operationId','fenceId','actorAccountId','selectedCommitId','publicationFence') + AND ((member.value #>> '{}') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (member.value #>> '{}') = '00000000-0000-0000-0000-000000000000') THEN + RAISE EXCEPTION 'Canonical nonzero inventory UUID required' USING ERRCODE = '23514'; END IF; + IF member.key IN ('intakeRequestDigest','sourceEvidenceDigest','intakeReceiptDigest','bindingDigest','appliedResultDigest','selectionDigest') + AND (member.value #>> '{}') !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Canonical inventory digest required' USING ERRCODE = '23514'; END IF; + END LOOP; + END LOOP; + IF owner->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' OR length(owner->>'targetNamespace') > 63 + OR frozen->>'versionStateEpoch' !~ '^[1-9][0-9]*$' OR (frozen->>'versionStateEpoch')::NUMERIC > 9223372036854775807 + OR frozen->>'requestDigest' !~ '^[0-9a-f]{64}$' OR checkpoint->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR jsonb_typeof(checkpoint->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR checkpoint->>'digestSchemaVersion' !~ '^[1-9][0-9]*$' OR (checkpoint->>'digestSchemaVersion')::NUMERIC > 2147483647 + OR btrim(account_order->>'publicationRequestId') = '' OR btrim(account_order->>'publicationRequestId') <> account_order->>'publicationRequestId' + OR btrim(frozen->>'publicationRequestId') = '' OR btrim(frozen->>'publicationRequestId') <> frozen->>'publicationRequestId' + OR btrim(frozen->>'publishWorkflowId') = '' OR btrim(frozen->>'publishWorkflowId') <> frozen->>'publishWorkflowId' + OR model->>'graphDigest' !~ '^sha256:[0-9a-f]{64}$' OR model->>'topologyResultDigest' !~ '^sha256:[0-9a-f]{64}$' + OR jsonb_typeof(model->'modelId') IS DISTINCT FROM 'string' + OR jsonb_typeof(model->'graphSchemaVersion') IS DISTINCT FROM 'number' + OR jsonb_typeof(model->'graphDigest') IS DISTINCT FROM 'string' + OR jsonb_typeof(model->'topologyResultDigest') IS DISTINCT FROM 'string' + OR model->'generationRuleFields' IS DISTINCT FROM '["id","name","scopeType","scopeId","value"]'::JSONB + OR model->'regionFields' IS DISTINCT FROM '["id","shardId","name","weather","generationSeed","generatorType","generatorParams","spacingMultiplier"]'::JSONB + OR model->'zoneFields' IS DISTINCT FROM '["id","regionId","name"]'::JSONB + OR model->'roomFields' IS DISTINCT FROM '["id","zoneId","name","description","nameLocalizedVariantsJson","descriptionLocalizedVariantsJson"]'::JSONB + OR model->'roomExitFields' IS DISTINCT FROM '["id","fromRoomId","toRoomId","direction","cost"]'::JSONB + OR model->'spawnBindingFields' IS DISTINCT FROM '["id","roomId","entityTemplateType","entityReference.kind","entityReference.tenantId","entityReference.versionId","entityReference.templateId","spawnCount","respawnDelaySeconds"]'::JSONB + OR jsonb_typeof(model->'familyCounts') IS DISTINCT FROM 'array' OR jsonb_array_length(model->'familyCounts') IS DISTINCT FROM 6 + OR jsonb_typeof(model->'regionGeneratorInputs') IS DISTINCT FROM 'array' + OR jsonb_typeof(model->'spawnBindingInputs') IS DISTINCT FROM 'array' + OR jsonb_typeof(model->'appliedEpochs') IS DISTINCT FROM 'array' + OR jsonb_typeof(model->'generationRuleInputCount') IS DISTINCT FROM 'number' + OR model->>'generationRuleInputCount' IS DISTINCT FROM '0' + OR jsonb_typeof(model->'spawnBindingCount') IS DISTINCT FROM 'number' + OR model->>'spawnBindingCount' !~ '^(0|[1-9][0-9]*)$' + OR (model->>'spawnBindingCount')::NUMERIC > 2147483647 THEN + RAISE EXCEPTION 'Unsupported public inventory source profile' USING ERRCODE = '23514'; END IF; + FOR i IN 0..5 LOOP + item := model->'familyCounts'->i; + IF jsonb_typeof(item) IS DISTINCT FROM 'object' OR NOT item ?& ARRAY['family','rowCount'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 2 + OR item->'family' IS DISTINCT FROM to_jsonb((ARRAY['REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING'])[i+1]) + OR jsonb_typeof(item->'rowCount') IS DISTINCT FROM 'number' OR item->>'rowCount' !~ '^(0|[1-9][0-9]*)$' + OR (item->>'rowCount')::NUMERIC > 2147483647 THEN + RAISE EXCEPTION 'Incomplete source family enumeration' USING ERRCODE = '23514'; END IF; + counts := array_append(counts, (item->>'rowCount')::INTEGER); + END LOOP; + IF counts[3] < 1 OR counts[5] <> 0 + OR counts[1] <> jsonb_array_length(model->'regionGeneratorInputs') + OR counts[6] <> jsonb_array_length(model->'spawnBindingInputs') + OR counts[6] <> (model->>'spawnBindingCount')::INTEGER THEN + RAISE EXCEPTION 'Source inventory counts differ from explicit inputs' USING ERRCODE = '23514'; END IF; + previous_key := NULL; + FOR item IN SELECT * FROM jsonb_array_elements(model->'regionGeneratorInputs') LOOP + IF jsonb_typeof(item) IS DISTINCT FROM 'object' OR NOT item ?& ARRAY['regionTemplateId','generatorType','generatorParams'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 3 + OR jsonb_typeof(item->'regionTemplateId') IS DISTINCT FROM 'string' + OR item->>'regionTemplateId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR item->>'regionTemplateId' = '00000000-0000-0000-0000-000000000000' + OR previous_key COLLATE "C" >= (item->>'regionTemplateId') COLLATE "C" + OR item->'generatorType' IS DISTINCT FROM '""'::JSONB + OR item->'generatorParams' IS DISTINCT FROM '""'::JSONB THEN + RAISE EXCEPTION 'Unsupported or unordered region generator input' USING ERRCODE = '23514'; END IF; + previous_key := item->>'regionTemplateId'; + END LOOP; + previous_key := NULL; + FOR item IN SELECT * FROM jsonb_array_elements(model->'spawnBindingInputs') LOOP + IF jsonb_typeof(item) IS DISTINCT FROM 'object' OR NOT item ?& ARRAY['bindingTemplateId','roomTemplateId','entityTemplateType','entityReferenceKind','entityTenantId','entityVersionId','entityTemplateId','spawnCount','respawnDelaySeconds'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 9 THEN + RAISE EXCEPTION 'Incomplete spawn input' USING ERRCODE = '23514'; END IF; + FOR member IN SELECT * FROM jsonb_each(item) LOOP + IF member.key NOT IN ('spawnCount','respawnDelaySeconds') AND jsonb_typeof(member.value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Spawn reference exact string required' USING ERRCODE = '23514'; END IF; + IF member.key IN ('bindingTemplateId','roomTemplateId','entityTenantId','entityVersionId','entityTemplateId') + AND ((member.value #>> '{}') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (member.value #>> '{}') = '00000000-0000-0000-0000-000000000000') THEN + RAISE EXCEPTION 'Canonical spawn UUID required' USING ERRCODE = '23514'; END IF; + END LOOP; + IF item->>'entityReferenceKind' IS DISTINCT FROM 'ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID' + OR item->>'entityTenantId' IS DISTINCT FROM owner->>'canonicalTenantId' + OR item->>'entityVersionId' IS DISTINCT FROM owner->>'canonicalVersionId' + OR item->>'entityTemplateType' NOT IN ('ITEM','NPC') + OR jsonb_typeof(item->'spawnCount') IS DISTINCT FROM 'number' OR item->>'spawnCount' !~ '^[1-9][0-9]*$' + OR (item->>'spawnCount')::NUMERIC > 2147483647 + OR jsonb_typeof(item->'respawnDelaySeconds') IS DISTINCT FROM 'number' OR item->>'respawnDelaySeconds' !~ '^(0|[1-9][0-9]*)$' + OR (item->>'respawnDelaySeconds')::NUMERIC > 2147483647 + OR previous_key COLLATE "C" >= (item->>'bindingTemplateId') COLLATE "C" THEN + RAISE EXCEPTION 'Unsupported or unordered scoped spawn input' USING ERRCODE = '23514'; END IF; + previous_key := item->>'bindingTemplateId'; + END LOOP; + SELECT coalesce(jsonb_agg(unit ORDER BY unit->>'owner', unit->>'aggregateType', unit->>'aggregateId', + unit->>'scopeType', unit->>'scopeId', unit->>'expectedEpoch'), '[]'::JSONB) + INTO expected_tuples FROM jsonb_array_elements(selected_binding->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + SELECT coalesce(jsonb_agg((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT) + ORDER BY unit->>'aggregateType', unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId'), '[]'::JSONB) + INTO expected_epochs FROM jsonb_array_elements(selected_binding->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF NOT (convert_from(frames[3], 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) + OR NOT (convert_from(frames[4], 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) + OR jsonb_typeof(selector) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selector)) <> 5 + OR selector->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR NOT (selector ?& ARRAY['schema', 'request', 'selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64', 'appliedResultBytesBase64']) + OR jsonb_typeof(selector->'request') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selector->'request')) <> 13 + OR NOT ((selector->'request') ?& ARRAY['targetNamespace', 'canonicalTenantId', + 'canonicalVersionId', 'intakeRequestId', 'publicationFence', 'publicationRequestId', + 'requestDigest', 'versionStateEpoch', 'publishWorkflowId', 'appliedCommitId', + 'contentDigest', 'digestSchemaVersion', 'worldAffectedTuples']) + OR jsonb_typeof(selector->'request'->'worldAffectedTuples') IS DISTINCT FROM 'array' + OR jsonb_typeof(selector->'request'->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR EXISTS (SELECT 1 FROM jsonb_each(selector->'request') field + WHERE field.key NOT IN ('digestSchemaVersion','worldAffectedTuples') + AND jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR EXISTS (SELECT 1 FROM jsonb_array_elements(selector->'request'->'worldAffectedTuples') tuple + WHERE jsonb_typeof(tuple) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(tuple)) <> 6 + OR NOT (tuple ?& ARRAY['owner','aggregateType','aggregateId','scopeType','scopeId','expectedEpoch']) + OR EXISTS (SELECT 1 FROM jsonb_each(tuple) field WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR tuple->>'owner' IS DISTINCT FROM 'WORLD_MANAGEMENT' + OR tuple->>'expectedEpoch' !~ '^(0|[1-9][0-9]*)$') + OR selected_inventory_operation_nth(account_bytes, 0) IS DISTINCT FROM convert_to('account-publication-authorization/v1', 'UTF8') + OR selected_inventory_operation_nth(input_bytes, 0) IS DISTINCT FROM convert_to('account-publication-input/v1', 'UTF8') + OR selected_inventory_operation_nth(input_bytes, 3) IS DISTINCT FROM + convert_to('sha256:' || encode(sha256(selection_bytes), 'hex'), 'UTF8') + OR selected->>'schemaVersion' IS DISTINCT FROM '1' + OR (SELECT count(*) FROM jsonb_object_keys(selected)) <> 6 + OR NOT (selected ?& ARRAY['schemaVersion','intent','target','selectedCommitBindingJson','selectedCommitDigest','synchronizedFence']) + OR jsonb_typeof(selected->'intent') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selected->'intent')) <> 8 + OR NOT (selected->'intent' ?& ARRAY['canonicalTenantId','canonicalVersionId','publishRequestId','expectedVersionStateEpoch','notes','selectedCommitRequestId','selectedCommitId','selectedCommitDigest']) + OR jsonb_typeof(selected->'target') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selected->'target')) <> 7 + OR NOT (selected->'target' ?& ARRAY['canonicalTenantId','canonicalVersionId','gameDesignVersionRowId','gameDesignVersionTenantKey','sourceGameRowId','sourceGameTenantKey','sourceProvenanceKind']) + OR jsonb_typeof(selected->'synchronizedFence') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selected->'synchronizedFence')) <> 5 + OR NOT (selected->'synchronizedFence' ?& ARRAY['requestId','commitId','inputDigest','resultVectorJson','createdAt']) + OR applied->>'status' IS DISTINCT FROM 'APPLIED' + OR jsonb_typeof(inventory) IS DISTINCT FROM 'object' + OR inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE' + OR (SELECT count(*) FROM jsonb_object_keys(inventory)) <> 10 + OR NOT (inventory ?& ARRAY['schema', 'schemaVersion', 'completeness', 'ownerScope', + 'selectedApplication', 'accountOrder', 'freeze', 'checkpoint', 'sourceModel', 'artifactDecisions']) + OR jsonb_typeof(owner) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(owner)) <> 10 + OR NOT (owner ?& ARRAY['targetNamespace', 'canonicalTenantId', 'canonicalVersionId', + 'versionIdentityOperationId', 'intakeRequestId', 'intakeOperationId', 'intakeRequestDigest', + 'sourceOperationId', 'sourceEvidenceDigest', 'intakeReceiptDigest']) + OR jsonb_typeof(application) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(application)) <> 5 + OR NOT (application ?& ARRAY['applicationOperationId', 'applicationRequestId', 'appliedCommitId', + 'bindingDigest', 'appliedResultDigest']) + OR jsonb_typeof(account_order) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(account_order)) <> 7 + OR NOT (account_order ?& ARRAY['operationId', 'fenceId', 'actorAccountId', + 'publicationRequestId', 'selectionDigest', 'selectedCommitId', 'bindingDigest']) + OR jsonb_typeof(frozen) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(frozen)) <> 5 + OR NOT (frozen ?& ARRAY['publicationFence', 'publicationRequestId', 'requestDigest', + 'versionStateEpoch', 'publishWorkflowId']) + OR jsonb_typeof(checkpoint) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(checkpoint)) <> 3 + OR NOT (checkpoint ?& ARRAY['appliedCommitId', 'contentDigest', 'digestSchemaVersion']) + OR jsonb_typeof(model) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(model)) <> 16 + OR NOT (model ?& ARRAY['modelId', 'graphSchemaVersion', 'graphDigest', 'topologyResultDigest', + 'familyCounts', 'regionGeneratorInputs', 'generationRuleFields', 'regionFields', 'zoneFields', + 'roomFields', 'roomExitFields', 'spawnBindingFields', 'spawnBindingInputs', + 'generationRuleInputCount', 'spawnBindingCount', 'appliedEpochs']) + OR jsonb_typeof(model->'familyCounts') IS DISTINCT FROM 'array' + OR jsonb_array_length(model->'familyCounts') IS DISTINCT FROM 6 + OR jsonb_typeof(model->'regionGeneratorInputs') IS DISTINCT FROM 'array' + OR jsonb_typeof(model->'spawnBindingInputs') IS DISTINCT FROM 'array' + OR jsonb_typeof(model->'appliedEpochs') IS DISTINCT FROM 'array' + OR (SELECT jsonb_agg(entry->>'family' ORDER BY ordinal) FROM + jsonb_array_elements(model->'familyCounts') WITH ORDINALITY AS entries(entry, ordinal)) + IS DISTINCT FROM '["REGION","ZONE","ROOM","ROOM_EXIT","GENERATION_RULE","WORLD_ENTITY_SPAWN_BINDING"]'::JSONB + OR EXISTS (SELECT 1 FROM jsonb_array_elements(model->'familyCounts') entry + WHERE jsonb_typeof(entry) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(entry)) <> 2 + OR NOT (entry ?& ARRAY['family', 'rowCount']) + OR jsonb_typeof(entry->'rowCount') IS DISTINCT FROM 'number' + OR (entry->>'rowCount')::NUMERIC < 0) + OR (SELECT jsonb_agg(entry ORDER BY entry->>'regionTemplateId') FROM + jsonb_array_elements(model->'regionGeneratorInputs') entry) + IS DISTINCT FROM model->'regionGeneratorInputs' + OR EXISTS (SELECT 1 FROM jsonb_array_elements(model->'regionGeneratorInputs') entry + WHERE jsonb_typeof(entry) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(entry)) <> 3 + OR NOT (entry ?& ARRAY['regionTemplateId', 'generatorType', 'generatorParams']) + OR entry->>'generatorType' IS DISTINCT FROM '' + OR entry->>'generatorParams' IS DISTINCT FROM '') + OR (SELECT jsonb_agg(entry ORDER BY entry->>'bindingTemplateId') FROM + jsonb_array_elements(model->'spawnBindingInputs') entry) + IS DISTINCT FROM model->'spawnBindingInputs' + OR EXISTS (SELECT 1 FROM jsonb_array_elements(model->'spawnBindingInputs') entry + WHERE jsonb_typeof(entry) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(entry)) <> 9 + OR NOT (entry ?& ARRAY['bindingTemplateId', 'roomTemplateId', 'entityTemplateType', + 'entityReferenceKind', 'entityTenantId', 'entityVersionId', 'entityTemplateId', + 'spawnCount', 'respawnDelaySeconds']) + OR entry->>'entityReferenceKind' IS DISTINCT FROM 'ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID' + OR entry->>'entityTenantId' IS DISTINCT FROM owner->>'canonicalTenantId' + OR entry->>'entityVersionId' IS DISTINCT FROM owner->>'canonicalVersionId' + OR entry->>'entityTemplateType' NOT IN ('ITEM', 'NPC') + OR (entry->>'spawnCount')::NUMERIC <= 0 + OR (entry->>'respawnDelaySeconds')::NUMERIC < 0) + OR model->'generationRuleFields' IS DISTINCT FROM '["id","name","scopeType","scopeId","value"]'::JSONB + OR model->'regionFields' IS DISTINCT FROM '["id","shardId","name","weather","generationSeed","generatorType","generatorParams","spacingMultiplier"]'::JSONB + OR model->'zoneFields' IS DISTINCT FROM '["id","regionId","name"]'::JSONB + OR model->'roomFields' IS DISTINCT FROM '["id","zoneId","name","description","nameLocalizedVariantsJson","descriptionLocalizedVariantsJson"]'::JSONB + OR model->'roomExitFields' IS DISTINCT FROM '["id","fromRoomId","toRoomId","direction","cost"]'::JSONB + OR model->'spawnBindingFields' IS DISTINCT FROM '["id","roomId","entityTemplateType","entityReference.kind","entityReference.tenantId","entityReference.versionId","entityReference.templateId","spawnCount","respawnDelaySeconds"]'::JSONB + OR (SELECT count(*) FROM jsonb_array_elements(model->'regionGeneratorInputs')) IS DISTINCT FROM + (SELECT (entry->>'rowCount')::INTEGER FROM jsonb_array_elements(model->'familyCounts') entry WHERE entry->>'family' = 'REGION') + OR (SELECT count(*) FROM jsonb_array_elements(model->'spawnBindingInputs')) IS DISTINCT FROM + (SELECT (entry->>'rowCount')::INTEGER FROM jsonb_array_elements(model->'familyCounts') entry WHERE entry->>'family' = 'WORLD_ENTITY_SPAWN_BINDING') + OR (SELECT (entry->>'rowCount')::INTEGER FROM jsonb_array_elements(model->'familyCounts') entry WHERE entry->>'family' = 'ROOM') < 1 + OR (SELECT (entry->>'rowCount')::INTEGER FROM jsonb_array_elements(model->'familyCounts') entry WHERE entry->>'family' = 'GENERATION_RULE') <> 0 + OR model->'generationRuleInputCount' IS DISTINCT FROM '0'::JSONB + OR model->'spawnBindingCount' IS DISTINCT FROM + (SELECT entry->'rowCount' FROM jsonb_array_elements(model->'familyCounts') entry WHERE entry->>'family' = 'WORLD_ENTITY_SPAWN_BINDING') + OR selector->'request'->'worldAffectedTuples' IS DISTINCT FROM expected_tuples + OR owner->>'targetNamespace' IS DISTINCT FROM selector->'request'->>'targetNamespace' + OR owner->>'canonicalTenantId' IS DISTINCT FROM selector->'request'->>'canonicalTenantId' + OR owner->>'canonicalVersionId' IS DISTINCT FROM selector->'request'->>'canonicalVersionId' + OR owner->>'intakeRequestId' IS DISTINCT FROM selector->'request'->>'intakeRequestId' + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(applied_operation, 1), 'UTF8') + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(original_account, 1), 'UTF8') + OR application->>'applicationRequestId' IS DISTINCT FROM selected->'intent'->>'selectedCommitRequestId' + OR application->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR application->>'bindingDigest' IS DISTINCT FROM selected->'intent'->>'selectedCommitDigest' + OR application->>'appliedResultDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(applied_bytes), 'hex') + OR account_order->>'operationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 1), 'UTF8') + OR account_order->>'fenceId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 2), 'UTF8') + OR account_order->>'actorAccountId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 1), 'UTF8') + OR account_order->>'publicationRequestId' IS DISTINCT FROM selected->'intent'->>'publishRequestId' + OR account_order->>'selectionDigest' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 3), 'UTF8') + OR account_order->>'selectedCommitId' IS DISTINCT FROM selected->'intent'->>'selectedCommitId' + OR account_order->>'bindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes), 'hex') + OR frozen->>'publicationFence' IS DISTINCT FROM selector->'request'->>'publicationFence' + OR frozen->>'publicationRequestId' IS DISTINCT FROM selector->'request'->>'publicationRequestId' + OR frozen->>'requestDigest' IS DISTINCT FROM selector->'request'->>'requestDigest' + OR frozen->>'versionStateEpoch' IS DISTINCT FROM selector->'request'->>'versionStateEpoch' + OR frozen->>'publishWorkflowId' IS DISTINCT FROM selector->'request'->>'publishWorkflowId' + OR checkpoint->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR checkpoint->>'contentDigest' IS DISTINCT FROM selector->'request'->>'contentDigest' + OR checkpoint->'digestSchemaVersion' IS DISTINCT FROM selector->'request'->'digestSchemaVersion' + OR model->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR model->'appliedEpochs' IS DISTINCT FROM expected_epochs OR expected_epochs = '[]'::JSONB + OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB + OR model->'generationRuleInputCount' IS DISTINCT FROM '0'::JSONB + OR inventory->'artifactDecisions' IS DISTINCT FROM + '[{"artifactKind":"NAVMESH","state":"NOT_REQUIRED","rule":"ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"},{"artifactKind":"PATH_GRAPH","state":"NOT_REQUIRED","rule":"AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"}]'::JSONB THEN + RAISE EXCEPTION 'Inventory differs from exact original selected Account, APPLIED graph or freeze' USING ERRCODE = '23514'; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE OR REPLACE FUNCTION account_selected_publication_settlement_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_selected_publication_authorizations%ROWTYPE; + issuer account_control_ui_issuance_operations%ROWTYPE; + source_key_value TEXT; + p INTEGER; + parsed BYTEA; + world_bytes BYTEA; + world JSONB; + selection JSONB; + input_bytes BYTEA; + terminal_frames BYTEA[] := ARRAY[]::BYTEA[]; + receipt_frames BYTEA[] := ARRAY[]::BYTEA[]; + i INTEGER; +BEGIN + -- Same canonical source-before-operation order as source writers. Never wait backwards on + -- issuance, whose producers take it before sources. Nothing here performs a remote read. + FOR source_key_value IN SELECT source_key FROM account_selected_publication_sources + WHERE operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(source_key) LOOP + PERFORM source_key FROM account_draft_authorization_source_locks + WHERE source_key = source_key_value FOR UPDATE; + END LOOP; + SELECT * INTO STRICT original FROM account_selected_publication_authorizations + WHERE operation_id = NEW.operation_id FOR UPDATE; + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations + WHERE operation_id = original.issuance_operation_id FOR UPDATE NOWAIT; + IF NEW.producer_xid <> txid_current() OR NEW.fence_id <> original.fence_id + OR NEW.account_binding <> original.binding OR issuer.status <> 'COMMITTED' + OR issuer.source_payload <> original.source_payload + OR issuer.bundle_payload <> original.issuance_bundle THEN + RAISE EXCEPTION 'Settlement differs from exact original committed Account order' USING ERRCODE = '23514'; + END IF; + PERFORM require_selected_inventory_operation_v2(NEW.publication_operation); + p := 1; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF parsed <> convert_to('game-design-publication-operation/v2', 'UTF8') THEN + RAISE EXCEPTION 'Invalid publication operation schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF parsed <> original.binding THEN + RAISE EXCEPTION 'Substituted original Account order' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_bytes, p FROM account_publication_authorization_read_frame(NEW.publication_operation, p); + IF octet_length(world_bytes) = 0 THEN + RAISE EXCEPTION 'Incomplete publication operation' USING ERRCODE = '23514'; + END IF; + world := convert_from(world_bytes, 'UTF8')::JSONB; + -- Retrieve the original immutable selection, without recapturing current authority. + p := 1; + FOR i IN 1..4 LOOP + SELECT frame_value, next_position INTO input_bytes, p FROM account_publication_authorization_read_frame(original.binding, p); + END LOOP; + p := 1; + FOR i IN 1..3 LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(input_bytes, p); + END LOOP; + selection := convert_from(parsed, 'UTF8')::JSONB; + IF world->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR world->'request'->>'canonicalTenantId' IS DISTINCT FROM original.tenant_uuid::TEXT + OR world->'request'->>'canonicalVersionId' IS DISTINCT FROM selection->'intent'->>'canonicalVersionId' + OR world->'request'->>'publicationRequestId' IS DISTINCT FROM original.publish_request_id + OR world->'request'->>'versionStateEpoch' IS DISTINCT FROM selection->'intent'->>'expectedVersionStateEpoch' + OR world->'request'->>'appliedCommitId' IS DISTINCT FROM selection->'intent'->>'selectedCommitId' + OR 'sha256:' || (world->'request'->>'requestDigest') IS DISTINCT FROM + 'sha256:' || encode(sha256(parsed), 'hex') + OR (original.world_evidence IS NOT NULL AND original.world_evidence <> world_bytes) THEN + RAISE EXCEPTION 'Publication World evidence differs from original selected order' USING ERRCODE = '23514'; + END IF; + p := 1; + WHILE p <= octet_length(NEW.game_design_terminal) LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.game_design_terminal, p); + terminal_frames := array_append(terminal_frames, parsed); + IF cardinality(terminal_frames) > 5 THEN + RAISE EXCEPTION 'Trailing publication terminal fields' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF terminal_frames[1] IS DISTINCT FROM convert_to('game-design-publication-terminal/v1', 'UTF8') + OR terminal_frames[2] IS DISTINCT FROM NEW.publication_operation + OR terminal_frames[3] IS DISTINCT FROM convert_to(NEW.game_design_outcome, 'UTF8') + OR cardinality(terminal_frames) <> (CASE WHEN NEW.game_design_outcome = 'PUBLISHED' THEN 5 ELSE 3 END) THEN + RAISE EXCEPTION 'Changed complete publication terminal relationship' USING ERRCODE = '23514'; + END IF; + IF NEW.game_design_outcome = 'PUBLISHED' THEN + IF convert_from(terminal_frames[5], 'UTF8') !~ '^[1-9][0-9]*$' + OR convert_from(terminal_frames[5], 'UTF8')::BIGINT <> + (world->'request'->>'versionStateEpoch')::BIGINT + 1 THEN + RAISE EXCEPTION 'Changed committed publication epoch' USING ERRCODE = '23514'; + END IF; + -- Game Design owns release semantics. Its canonical codec and the authenticated owner + -- read validate the opaque complete content; Account binds all its exact bytes here. + IF octet_length(terminal_frames[4]) = 0 THEN + RAISE EXCEPTION 'Missing complete published release content' USING ERRCODE = '23514'; + END IF; + END IF; + p := 1; + WHILE p <= octet_length(NEW.receipt) LOOP + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.receipt, p); + receipt_frames := array_append(receipt_frames, parsed); + IF cardinality(receipt_frames) > 6 THEN + RAISE EXCEPTION 'Trailing settlement receipt' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF receipt_frames IS DISTINCT FROM ARRAY[convert_to('account-selected-publication-settlement/v1', 'UTF8'), + NEW.account_binding, NEW.publication_operation, NEW.game_design_terminal, + convert_to(NEW.world_outcome, 'UTF8'), NEW.world_terminal] THEN + RAISE EXCEPTION 'Changed exact settlement receipt' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java index c487035522..f8c51bc9a1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -38,7 +38,6 @@ import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; -import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadClient; import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadGrpcCodec; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; @@ -380,7 +379,9 @@ void twoAuthenticatedTerminalOwnersSettleActualAccountOrderAndReadBackAfterCommi var order = new AccountPublicationAuthorizationService(issued.actors(), sources.fences, repository) .authorize(issued.compact(), descriptor.selection(), issued.environment()); - var operation = new GameDesignPublicationOperationBinding(order, descriptor.world()); + var operation = + AccountPublicationAuthorizationPostgresIntegrationTest.operation( + order, descriptor.world()); var terminal = AccountPublicationAuthorizationPostgresIntegrationTest.terminal(operation, outcome); var mode = new AtomicReference<>("exact"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index b8ad471d23..6681e0f53c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -23,6 +23,7 @@ import net.firedevops.firemud.common.world.RoomTemplateRef; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -98,7 +99,7 @@ void exactTwoOwnerSettlementRollsBackAtomicallyThenReplaysAfterLostAcknowledgeme var service = new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); var order = service.authorize(issued.compact(), proof.selection(), issued.environment()); - var operation = new GameDesignPublicationOperationBinding(order, proof.world()); + var operation = operation(order, proof.world()); var terminal = terminal(operation, outcome); String phase = outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED @@ -199,14 +200,14 @@ void missingAmbiguousSubstitutedAndDisagreeingOwnersKeepOriginalSourcesHeld() th var service = new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); var order = service.authorize(issued.compact(), proof.selection(), issued.environment()); - var operation = new GameDesignPublicationOperationBinding(order, proof.world()); + var operation = operation(order, proof.world()); var noPublication = terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); var published = terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED); var wrongFence = new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( order.operationId(), UUID.randomUUID(), order.input(), order.sources()); - var wrongOperation = new GameDesignPublicationOperationBinding(wrongFence, proof.world()); + var wrongOperation = operation(wrongFence, proof.world()); for (Runnable rejected : List.of( () -> @@ -296,7 +297,7 @@ void settlingOneOrderLeavesEveryOtherOriginalSourceParticipationPending() throws var secondSelection = selection(proof.selection().selectedCommit(), "other order", "another-publication"); var second = service.authorize(issued.compact(), secondSelection, issued.environment()); - var operation = new GameDesignPublicationOperationBinding(first, proof.world()); + var operation = operation(first, proof.world()); var terminal = terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); f.tx(() -> repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes())); @@ -379,6 +380,36 @@ static GameDesignPublicationTerminalEvidence terminal( Math.addExact(request.versionStateEpoch(), 1)); } + static GameDesignPublicationOperationBinding operation( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world) { + return new GameDesignPublicationOperationBinding( + account, world, IsolatedWorldPublicationInventoryFixtures.stipulated(account, world)); + } + + private static byte[] rawOperation( + String schema, byte[] accountBytes, byte[] worldBytes, byte[] inventoryBytes, String digest) { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, schema); + DraftAuthorizationFenceBinding.frame(out, accountBytes); + DraftAuthorizationFenceBinding.frame(out, worldBytes); + if (schema.equals(GameDesignPublicationOperationBinding.SCHEMA)) { + DraftAuthorizationFenceBinding.frame(out, inventoryBytes); + DraftAuthorizationFenceBinding.frame(out, digest); + } + return out.toByteArray(); + } + + private static void assertSqlState(Throwable failure, String expectedState) { + String sqlState = null; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sqlException) { + sqlState = sqlException.getSQLState(); + } + } + assertThat(sqlState).isEqualTo(expectedState); + } + @Test void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throws Exception { try (var fixture = fixture()) { @@ -389,7 +420,7 @@ void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throw var order = new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) .authorize(issued.compact(), proof.selection(), issued.environment()); - var operation = new GameDesignPublicationOperationBinding(order, proof.world()); + var operation = operation(order, proof.world()); var terminal = terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); var out = new java.io.ByteArrayOutputStream(); @@ -476,6 +507,62 @@ void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throw assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, values))) .isInstanceOf(org.jooq.exception.DataAccessException.class); } + String publicInventoryJson = + new String( + operation.inventory().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + String graphDigest = operation.inventory().publicEvidence().sourceModel().graphDigest(); + byte[] substitutedInventory = + publicInventoryJson + .replace( + "\"graphDigest\":\"" + graphDigest + "\"", + "\"graphDigest\":\"sha256:" + "0".repeat(64) + "\"") + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] validOperation = operation.canonicalBytes(); + List invalidOperations = + List.of( + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + new byte[0], + DraftAuthorizationFenceBinding.digest(new byte[0])), + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + operation.inventory().canonicalBytes(), + "sha256:" + "0".repeat(64)), + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + substitutedInventory, + DraftAuthorizationFenceBinding.digest(substitutedInventory)), + rawOperation( + "game-design-publication-operation/v1", + order.canonicalBytes(), + proof.world().canonicalBytes(), + null, + null), + java.util.Arrays.copyOf(validOperation, validOperation.length + 1)); + for (byte[] invalidOperation : invalidOperations) { + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + insert, + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + invalidOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt))) + .satisfies(failure -> assertSqlState(failure, "23514")); + } assertThat( f.dsl.fetchCount(org.jooq.impl.DSL.table("account_selected_publication_settlements"))) .isZero(); @@ -505,7 +592,7 @@ void sourceWriterCannotPassUncommittedSettlementAndCanRetryAfterItsCommit() thro var order = new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) .authorize(issued.compact(), proof.selection(), issued.environment()); - var operation = new GameDesignPublicationOperationBinding(order, proof.world()); + var operation = operation(order, proof.world()); var terminal = terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); var executor = java.util.concurrent.Executors.newSingleThreadExecutor(); @@ -575,8 +662,7 @@ void authenticatesPreFreezeDistinctOrderReplaysExactlyAndBlocksSourceWritersAndD .get("world_evidence", byte[].class)) .isNull(); // The immutable Account order is available before the separate World capture is correlated. - new net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding( - original, proof.world()); + operation(original, proof.world()); assertThat(original.sources()).hasSize(8); var readOwner = new AccountPublicationAuthorizationReadService( diff --git a/services/common-platform-core/build.gradle.kts b/services/common-platform-core/build.gradle.kts index c0ff7af025..7a433ad11a 100644 --- a/services/common-platform-core/build.gradle.kts +++ b/services/common-platform-core/build.gradle.kts @@ -27,4 +27,5 @@ dependencies { compileOnly(libs.spotbugs.annotations) testImplementation(libs.grpc.spring.boot.starter) testImplementation(libs.spring.boot.starter.test) + testImplementation(testFixtures(project(":common-test-support"))) } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java index 0d664c9a04..cbc08d8aec 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBinding.java @@ -8,8 +8,11 @@ /** Original closed publication input; byte integrity never authenticates its producer. */ public record GameDesignPublicationOperationBinding( - AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { - public static final String SCHEMA = "game-design-publication-operation/v1"; + AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world, + WorldSelectedPublicationArtifactInventoryEvidence inventory) { + public static final String SCHEMA = "game-design-publication-operation/v2"; + public static final int MAX_OPERATION_BYTES = 4 * 1024 * 1024; public GameDesignPublicationOperationBinding { account = @@ -18,6 +21,25 @@ public record GameDesignPublicationOperationBinding( world = WorldPublishedStartLocationEvidence.fromStored( Objects.requireNonNull(world).canonicalBytes()); + requireAccountWorldCorrelation(account, world); + Objects.requireNonNull(inventory, "inventory"); + inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + account, world, inventory.canonicalBytes(), inventory.digest()); + long size = + 5L * Integer.BYTES + + SCHEMA.getBytes(java.nio.charset.StandardCharsets.UTF_8).length + + account.canonicalBytes().length + + world.canonicalBytes().length + + inventory.canonicalBytes().length + + inventory.digest().length(); + if (size > MAX_OPERATION_BYTES) + throw new IllegalArgumentException("Publication operation exceeds 4 MiB"); + } + + /** Historical correlation only; neither authentication nor complete operation authority. */ + public static void requireAccountWorldCorrelation( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { var selection = account.input().selection(); var intent = selection.intent(); var freeze = world.request(); @@ -48,16 +70,27 @@ public byte[] canonicalBytes() { DraftAuthorizationFenceBinding.frame(out, SCHEMA); DraftAuthorizationFenceBinding.frame(out, account.canonicalBytes()); DraftAuthorizationFenceBinding.frame(out, world.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, inventory.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, inventory.digest()); return out.toByteArray(); } public static GameDesignPublicationOperationBinding fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_OPERATION_BYTES) + throw new IllegalArgumentException("Complete bounded v2 publication operation required"); var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); reader.expect(SCHEMA); + var account = AccountPublicationAuthorizationBinding.fromStored(reader.bytes()); + var world = WorldPublishedStartLocationEvidence.fromStored(reader.bytes()); + var inventoryBytes = reader.bytes(); + var digestBytes = reader.bytes(); + String digest = new String(digestBytes, java.nio.charset.StandardCharsets.US_ASCII); var operation = new GameDesignPublicationOperationBinding( - AccountPublicationAuthorizationBinding.fromStored(reader.bytes()), - WorldPublishedStartLocationEvidence.fromStored(reader.bytes())); + account, + world, + WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + account, world, inventoryBytes, digest)); reader.requireEnd(); if (!Arrays.equals(bytes, operation.canonicalBytes())) { throw new IllegalArgumentException("Noncanonical publication operation"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java index cf26895281..43df3884ca 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java @@ -95,6 +95,17 @@ public final class WorldSelectedPublicationArtifactInventoryEvidence { private final byte[] canonicalBytes; private final String digest; + @Override + public boolean equals(Object other) { + return other instanceof WorldSelectedPublicationArtifactInventoryEvidence evidence + && Arrays.equals(canonicalBytes, evidence.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + private WorldSelectedPublicationArtifactInventoryEvidence( WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, PublicEvidence publicEvidence) { this.freezeEvidence = Objects.requireNonNull(freezeEvidence, "freezeEvidence"); @@ -135,6 +146,77 @@ public static WorldSelectedPublicationArtifactInventoryEvidence fromCanonicalByt return new WorldSelectedPublicationArtifactInventoryEvidence(freezeEvidence, evidence); } + /** + * Reconstructs original freeze correlation from retained Account/selector evidence. This never + * authenticates a producer anew and cannot substitute for the first authenticated owner read. + */ + public static WorldSelectedPublicationArtifactInventoryEvidence fromRetainedSelection( + AccountPublicationAuthorizationBinding account, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence world, + byte[] inventoryBytes, + String inventoryDigest) { + GameDesignPublicationOperationBinding.requireAccountWorldCorrelation(account, world); + var selector = world.request(); + var request = + Request.create( + selector.targetNamespace(), + selector.canonicalTenantId(), + selector.canonicalVersionId(), + selector.publicationRequestId(), + selector.versionStateEpoch(), + selector.requestDigest(), + account); + var acknowledgement = + new Acknowledgement( + request, + selector.intakeRequestId(), + selector.versionStateEpoch(), + selector.publicationFence(), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + selector.appliedCommitId(), + selector.contentDigest(), + selector.digestSchemaVersion()); + var result = + fromCanonicalBytes( + new WorldSelectedDraftPublicationFreezeEvidence(request, acknowledgement), + inventoryBytes, + inventoryDigest); + var original = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.fromStored( + world.originalAccountBindingBytes()); + var receipt = + net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence.fromStored( + world.selectorReceiptBytes()); + final tools.jackson.databind.JsonNode applied; + try { + applied = JSON.readTree(world.appliedResultBytes()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Retained World APPLIED bytes are invalid", invalid); + } + byte[] operationBytes; + try { + operationBytes = + java.util.Base64.getDecoder().decode(applied.path("operationBytesBase64").textValue()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Retained World APPLIED operation is invalid", invalid); + } + var operation = + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.FrameReader( + operationBytes); + operation.expect("world-draft-terminal-operation/v1"); + String operationId = new String(operation.bytes(), java.nio.charset.StandardCharsets.UTF_8); + var application = result.publicEvidence().selectedApplication(); + if (!sha256(world.appliedResultBytes()).equals(application.appliedResultDigest()) + || !original.operationId().equals(application.applicationOperationId()) + || !application.applicationOperationId().toString().equals(operationId) + || !receipt.graphDigest().equals(result.publicEvidence().sourceModel().graphDigest()) + || !receipt.graphDigest().equals(applied.path("graphDigest").textValue())) { + throw new IllegalArgumentException( + "World inventory differs from exact selector APPLIED operation or graph"); + } + return result; + } + public WorldSelectedDraftPublicationFreezeEvidence freezeEvidence() { return freezeEvidence; } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java new file mode 100644 index 0000000000..e127a929b0 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java @@ -0,0 +1,101 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import org.junit.jupiter.api.Test; + +/** Structural retention proof; upstream authority is explicitly stipulated by the fixture. */ +class GameDesignPublicationOperationBindingTest { + @Test + void fiveFramesRetainExactInventoryAndReconstructOriginalFreeze() throws Exception { + var original = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var bytes = original.canonicalBytes(); + var frames = new DraftAuthorizationFenceBinding.FrameReader(bytes); + frames.expect("game-design-publication-operation/v2"); + assertThat(frames.bytes()).containsExactly(original.account().canonicalBytes()); + assertThat(frames.bytes()).containsExactly(original.world().canonicalBytes()); + assertThat(frames.bytes()).containsExactly(original.inventory().canonicalBytes()); + assertThat(frames.text()).isEqualTo(original.inventory().digest()); + frames.requireEnd(); + var retained = GameDesignPublicationOperationBinding.fromStored(bytes); + assertThat(retained.canonicalBytes()).containsExactly(bytes); + assertThat(retained.inventory().canonicalBytes()) + .containsExactly(original.inventory().canonicalBytes()); + assertThat(retained.inventory().freezeEvidence().request()) + .isEqualTo(original.inventory().freezeEvidence().request()); + assertThat(retained.inventory().freezeEvidence().acknowledgement()) + .isEqualTo(original.inventory().freezeEvidence().acknowledgement()); + bytes[0] ^= 1; + assertThat(retained.canonicalBytes()).containsExactly(original.canonicalBytes()); + } + + @Test + void absentInventoryV1WrongDigestTrailingAndOversizeInputsDeny() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var v1 = prefix(operation, "game-design-publication-operation/v1"); + assertThatThrownBy(() -> GameDesignPublicationOperationBinding.fromStored(v1.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + var absent = prefix(operation, GameDesignPublicationOperationBinding.SCHEMA); + assertThatThrownBy(() -> GameDesignPublicationOperationBinding.fromStored(absent.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + var wrong = prefix(operation, GameDesignPublicationOperationBinding.SCHEMA); + DraftAuthorizationFenceBinding.frame(wrong, operation.inventory().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(wrong, "sha256:" + "0".repeat(64)); + assertThatThrownBy(() -> GameDesignPublicationOperationBinding.fromStored(wrong.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + var trailing = new ByteArrayOutputStream(); + trailing.writeBytes(operation.canonicalBytes()); + trailing.write(0); + assertThatThrownBy( + () -> GameDesignPublicationOperationBinding.fromStored(trailing.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameDesignPublicationOperationBinding.fromStored( + new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void digestCorrectChangedAppliedOperationAndGraphStillDeny() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var inventory = operation.inventory().publicEvidence(); + for (String changed : + new String[] { + new String(inventory.canonicalBytes(), StandardCharsets.UTF_8) + .replace( + inventory.selectedApplication().appliedResultDigest(), + "sha256:" + "0".repeat(64)), + new String(inventory.canonicalBytes(), StandardCharsets.UTF_8) + .replace(inventory.sourceModel().graphDigest(), "sha256:" + "1".repeat(64)), + new String(inventory.canonicalBytes(), StandardCharsets.UTF_8) + .replace( + inventory.selectedApplication().applicationOperationId().toString(), + java.util.UUID.randomUUID().toString()) + }) { + var bytes = changed.getBytes(StandardCharsets.UTF_8); + var digest = + "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + assertThatThrownBy( + () -> + WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + operation.account(), operation.world(), bytes, digest)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static ByteArrayOutputStream prefix( + GameDesignPublicationOperationBinding operation, String schema) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, schema); + DraftAuthorizationFenceBinding.frame(out, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.world().canonicalBytes()); + return out; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java index 5d1f0dced8..db30a362f8 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java @@ -214,7 +214,11 @@ static GameDesignPublicationOperationBinding operation() throws Exception { Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()), applied.fullBinding(), applied.result()); - return new GameDesignPublicationOperationBinding(account, world); + return new GameDesignPublicationOperationBinding( + account, + world, + net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures.stipulated( + account, world)); } static GameDesignPublicationTerminalEvidence terminal( diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java new file mode 100644 index 0000000000..f7aeb7ae1b --- /dev/null +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java @@ -0,0 +1,163 @@ +package net.firedevops.firemud.test; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** + * ISOLATED stipulated external COMPLETE evidence for local consumer tests only. This does not + * execute World's source inventory producer or establish actual graph requiredness/completeness. + * Actual World persistence tests must use their real retained inventory instead. + */ +public final class IsolatedWorldPublicationInventoryFixtures { + private IsolatedWorldPublicationInventoryFixtures() {} + + public static WorldSelectedPublicationArtifactInventoryEvidence stipulated( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + var selected = account.input().selection(); + var commit = selected.selectedCommit(); + var request = world.request(); + var original = DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()); + var graph = + WorldDraftStartLocationEvidence.fromStored(world.selectorReceiptBytes()).graphDigest(); + UUID fixtureId = + UUID.nameUUIDFromBytes("ISOLATED World inventory input".getBytes(StandardCharsets.UTF_8)); + var evidence = + new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA, + 1, + "COMPLETE", + new PublicOwnerScope( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + fixtureId, + request.intakeRequestId(), + fixtureId, + sha256(world.originalAccountBindingBytes()), + fixtureId, + sha256(world.selectorReceiptBytes()), + sha256(world.selectorReceiptBytes())), + new SelectedApplication( + original.operationId(), + commit.requestId(), + commit.commitId().toString(), + commit.digest(), + sha256(world.appliedResultBytes())), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selected.intent().publishRequestId(), + selected.digest(), + commit.commitId().toString(), + sha256(account.canonicalBytes())), + new Freeze( + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(request.versionStateEpoch()), + request.publishWorkflowId()), + new Checkpoint( + request.appliedCommitId(), request.contentDigest(), request.digestSchemaVersion()), + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.SOURCE_MODEL, + 2, + graph, + sha256("ISOLATED topology result".getBytes(StandardCharsets.UTF_8)), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 0), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(fixtureId, "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + commit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()) + .add(BigInteger.ONE) + .toString())) + .toList()), + List.of( + new ArtifactDecision( + "NAVMESH", + "NOT_REQUIRED", + "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + return WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + account, world, evidence.canonicalBytes(), evidence.digest()); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java index 45d095299a..1ae0232582 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.java @@ -2,26 +2,42 @@ import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; /** Closed original operation input. Codec validation supplies integrity, never authorization. */ public record GameDesignPublicationOperation( - AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world, + WorldSelectedPublicationArtifactInventoryEvidence inventory) { public static final String SCHEMA = GameDesignPublicationOperationBinding.SCHEMA; public GameDesignPublicationOperation { - var binding = new GameDesignPublicationOperationBinding(account, world); + var binding = new GameDesignPublicationOperationBinding(account, world, inventory); account = binding.account(); world = binding.world(); + inventory = binding.inventory(); } public byte[] canonicalBytes() { - return new GameDesignPublicationOperationBinding(account, world).canonicalBytes(); + return new GameDesignPublicationOperationBinding(account, world, inventory).canonicalBytes(); + } + + @Override + public boolean equals(Object other) { + return other instanceof GameDesignPublicationOperation operation + && java.util.Arrays.equals(canonicalBytes(), operation.canonicalBytes()); + } + + @Override + public int hashCode() { + return java.util.Arrays.hashCode(canonicalBytes()); } public static GameDesignPublicationOperation fromStored(byte[] bytes) { var binding = GameDesignPublicationOperationBinding.fromStored(bytes); - return new GameDesignPublicationOperation(binding.account(), binding.world()); + return new GameDesignPublicationOperation( + binding.account(), binding.world(), binding.inventory()); } public String workflowId() { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java index d55330ba44..3cf08e7cae 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java @@ -13,6 +13,7 @@ import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; @@ -32,6 +33,7 @@ public final class SelectedDraftPublicationAdmissionService { private final AccountPublicationAuthorizationReadClient accountClient; private final WorldPublishedStartLocationClient worldClient; private final WorldSelectedDraftPublicationFreezeClient freezeClient; + private final WorldSelectedPublicationArtifactInventoryClient inventoryClient; private final SelectionReader selectionReader; private final SelectedDraftPublicationOwner owner; private final TransactionTemplate reservationTransaction; @@ -42,12 +44,14 @@ public SelectedDraftPublicationAdmissionService( PlatformTransactionManager transactionManager, AccountPublicationAuthorizationReadClient accountClient, WorldSelectedDraftPublicationFreezeClient freezeClient, + WorldSelectedPublicationArtifactInventoryClient inventoryClient, WorldPublishedStartLocationClient worldClient, String workloadNamespace) { this( transactionManager, accountClient, freezeClient, + inventoryClient, worldClient, new SelectedDraftPublicationOwner(Objects.requireNonNull(dsl, "dsl")), intent -> @@ -65,6 +69,7 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) PlatformTransactionManager transactionManager, AccountPublicationAuthorizationReadClient accountClient, WorldSelectedDraftPublicationFreezeClient freezeClient, + WorldSelectedPublicationArtifactInventoryClient inventoryClient, WorldPublishedStartLocationClient worldClient, SelectedDraftPublicationOwner owner, SelectionReader selectionReader, @@ -72,6 +77,7 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) this.accountClient = Objects.requireNonNull(accountClient, "accountClient"); this.worldClient = Objects.requireNonNull(worldClient, "worldClient"); this.freezeClient = Objects.requireNonNull(freezeClient, "freezeClient"); + this.inventoryClient = Objects.requireNonNull(inventoryClient, "inventoryClient"); this.selectionReader = Objects.requireNonNull(selectionReader, "selectionReader"); this.owner = Objects.requireNonNull(owner, "owner"); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -127,6 +133,13 @@ public SelectedDraftPublicationOwner.Reservation admitAndReserve( "World publication freeze readback differs from the exact request"); } var acknowledgement = freeze.acknowledgement(); + var inventory = inventoryClient.read(freeze); + if (inventory == null + || !freeze.request().equals(inventory.freezeEvidence().request()) + || !freeze.acknowledgement().equals(inventory.freezeEvidence().acknowledgement())) { + throw new IllegalStateException( + "World inventory readback differs from exact acknowledged freeze"); + } var worldRequest = new WorldPublishedStartLocationEvidence.Request( workloadNamespace, @@ -161,11 +174,14 @@ public SelectedDraftPublicationOwner.Reservation admitAndReserve( .toList()); WorldPublishedStartLocationEvidence worldEvidence = worldClient.read(worldRequest); requireExactWorldReadback(worldRequest, worldEvidence); - new GameDesignPublicationOperationBinding(accountEvidence.request().binding(), worldEvidence); + new GameDesignPublicationOperationBinding( + accountEvidence.request().binding(), worldEvidence, inventory); return Objects.requireNonNull( reservationTransaction.execute( - status -> owner.reserve(intent, accountEvidence.request().binding(), worldEvidence)), + status -> + owner.reserve( + intent, accountEvidence.request().binding(), worldEvidence, inventory)), "Selected Draft publication reservation returned no result"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java index d7cbff60ee..76bc30f219 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java @@ -7,6 +7,7 @@ import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; @@ -35,12 +36,19 @@ public SelectedDraftPublicationCommandService( PlatformTransactionManager transactionManager, AccountPublicationAuthorizationReadClient accountClient, WorldSelectedDraftPublicationFreezeClient freezeClient, + WorldSelectedPublicationArtifactInventoryClient inventoryClient, WorldPublishedStartLocationClient worldClient, String workloadNamespace, VersionPublishCommandServiceImpl finalizer) { this( new SelectedDraftPublicationAdmissionService( - dsl, transactionManager, accountClient, freezeClient, worldClient, workloadNamespace), + dsl, + transactionManager, + accountClient, + freezeClient, + inventoryClient, + worldClient, + workloadNamespace), new DatabaseDurableStateReader(dsl), finalizer); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java index 75654ed088..9ad418caeb 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java @@ -4,6 +4,7 @@ import java.util.Objects; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; @@ -53,7 +54,8 @@ public SelectedDraftPublicationOwner(DSLContext dsl) { public Reservation reserve( AuthoredDraftPublishSelection.PublishIntent intent, AccountPublicationAuthorizationBinding account, - WorldPublishedStartLocationEvidence world) { + WorldPublishedStartLocationEvidence world, + WorldSelectedPublicationArtifactInventoryEvidence inventory) { requireWritableReadCommittedTransaction(); Objects.requireNonNull(intent, "intent"); Objects.requireNonNull(account, "account"); @@ -81,7 +83,7 @@ public Reservation reserve( throw new IllegalStateException("SELECTED_PUBLICATION_SELECTION_CHANGED"); } - var operation = new GameDesignPublicationOperation(account, world); + var operation = new GameDesignPublicationOperation(account, world, inventory); String workflowId = PublicationDigestRequestBinding.full( selection.target().canonicalTenantId().toString(), diff --git a/services/game-design-service/src/main/resources/db/migration/V56__publication_operation_inventory_v2.sql b/services/game-design-service/src/main/resources/db/migration/V56__publication_operation_inventory_v2.sql new file mode 100644 index 0000000000..db15cdbffc --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V56__publication_operation_inventory_v2.sql @@ -0,0 +1,291 @@ +-- Mandatory original World public inventory; retained operation/capture bytes are never rewritten. +-- [jooq ignore start] +CREATE FUNCTION selected_inventory_operation_frame(operation_bytes BYTEA, frame_offset INTEGER) RETURNS BYTEA AS $$ +DECLARE length_bytes BIGINT; +BEGIN + IF frame_offset < 0 OR frame_offset > octet_length(operation_bytes) - 4 THEN + RAISE EXCEPTION 'Truncated publication inventory frame' USING ERRCODE = '23514'; END IF; + length_bytes := get_byte(operation_bytes, frame_offset)::BIGINT * 16777216 + + get_byte(operation_bytes, frame_offset + 1)::BIGINT * 65536 + + get_byte(operation_bytes, frame_offset + 2)::BIGINT * 256 + + get_byte(operation_bytes, frame_offset + 3)::BIGINT; + IF length_bytes > 4194304 OR length_bytes > octet_length(operation_bytes) - frame_offset - 4 THEN + RAISE EXCEPTION 'Oversized publication inventory frame' USING ERRCODE = '23514'; END IF; + RETURN substring(operation_bytes FROM frame_offset + 5 FOR length_bytes::INTEGER); +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION selected_inventory_operation_nth(operation_bytes BYTEA, frame_index INTEGER) RETURNS BYTEA AS $$ +DECLARE offset_bytes INTEGER := 0; value BYTEA; i INTEGER; +BEGIN + IF frame_index < 0 THEN RAISE EXCEPTION 'Negative frame index' USING ERRCODE = '23514'; END IF; + FOR i IN 0..frame_index LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + END LOOP; + RETURN value; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION require_selected_inventory_operation_v2(operation_bytes BYTEA) RETURNS VOID AS $$ +DECLARE frames BYTEA[] := ARRAY[]::BYTEA[]; value BYTEA; offset_bytes INTEGER := 0; + account_bytes BYTEA; input_bytes BYTEA; selector JSONB; inventory JSONB; selected JSONB; + applied JSONB; applied_bytes BYTEA; applied_operation BYTEA; original_account BYTEA; + owner JSONB; application JSONB; account_order JSONB; frozen JSONB; checkpoint JSONB; + model JSONB; expected_epochs JSONB; i INTEGER; shape RECORD; member RECORD; + item JSONB; previous_key TEXT; counts INTEGER[] := ARRAY[]::INTEGER[]; +BEGIN + IF operation_bytes IS NULL OR octet_length(operation_bytes) NOT BETWEEN 1 AND 4194304 THEN + RAISE EXCEPTION 'Complete bounded v2 publication operation required' USING ERRCODE = '23514'; END IF; + FOR i IN 0..4 LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + frames := array_append(frames, value); + END LOOP; + IF offset_bytes <> octet_length(operation_bytes) OR frames[1] <> convert_to('game-design-publication-operation/v2', 'UTF8') + OR frames[5] IS DISTINCT FROM convert_to('sha256:' || encode(sha256(frames[4]), 'hex'), 'UTF8') THEN + RAISE EXCEPTION 'Publication v2 schema, exact frame count or inventory digest invalid' USING ERRCODE = '23514'; END IF; + account_bytes := frames[2]; + input_bytes := selected_inventory_operation_nth(account_bytes, 3); + selected := convert_from(selected_inventory_operation_nth(input_bytes, 2), 'UTF8')::JSONB; + selector := convert_from(frames[3], 'UTF8')::JSONB; + IF NOT (convert_from(frames[4], 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) THEN + RAISE EXCEPTION 'Inventory requires unique closed JSON members' USING ERRCODE = '23514'; END IF; + inventory := convert_from(frames[4], 'UTF8')::JSONB; + applied_bytes := decode(selector->>'appliedResultBytesBase64', 'base64'); + applied := convert_from(applied_bytes, 'UTF8')::JSONB; + applied_operation := decode(applied->>'operationBytesBase64', 'base64'); + original_account := decode(selector->>'originalAccountBindingBytesBase64', 'base64'); + owner := inventory->'ownerScope'; application := inventory->'selectedApplication'; + account_order := inventory->'accountOrder'; frozen := inventory->'freeze'; + checkpoint := inventory->'checkpoint'; model := inventory->'sourceModel'; + -- Closed public structure is mandatory even for direct SQL callers. This checks structure, + -- not producer authentication; GD cannot independently reconstruct World's private inputs. + FOR shape IN SELECT * FROM (VALUES + (inventory, ARRAY['schema','schemaVersion','completeness','ownerScope','selectedApplication','accountOrder','freeze','checkpoint','sourceModel','artifactDecisions']), + (owner, ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId','versionIdentityOperationId','intakeRequestId','intakeOperationId','intakeRequestDigest','sourceOperationId','sourceEvidenceDigest','intakeReceiptDigest']), + (application, ARRAY['applicationOperationId','applicationRequestId','appliedCommitId','bindingDigest','appliedResultDigest']), + (account_order, ARRAY['operationId','fenceId','actorAccountId','publicationRequestId','selectionDigest','selectedCommitId','bindingDigest']), + (frozen, ARRAY['publicationFence','publicationRequestId','requestDigest','versionStateEpoch','publishWorkflowId']), + (checkpoint, ARRAY['appliedCommitId','contentDigest','digestSchemaVersion']), + (model, ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs']) + ) AS shapes(value, keys) LOOP + IF jsonb_typeof(shape.value) IS DISTINCT FROM 'object' + OR NOT shape.value ?& shape.keys + OR (SELECT count(*) FROM jsonb_object_keys(shape.value)) <> cardinality(shape.keys) + OR EXISTS (SELECT 1 FROM jsonb_each(shape.value) e WHERE e.value = 'null'::JSONB) THEN + RAISE EXCEPTION 'Incomplete or unknown public inventory members' USING ERRCODE = '23514'; END IF; + END LOOP; + FOR shape IN SELECT * FROM (VALUES (owner), (application), (account_order), (frozen), (checkpoint)) AS shapes(value) LOOP + FOR member IN SELECT * FROM jsonb_each(shape.value) LOOP + IF member.key <> 'digestSchemaVersion' AND jsonb_typeof(member.value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Inventory binding members require exact string types' USING ERRCODE = '23514'; END IF; + IF member.key IN ('canonicalTenantId','canonicalVersionId','versionIdentityOperationId','intakeRequestId','intakeOperationId','sourceOperationId','applicationOperationId','applicationRequestId','appliedCommitId','operationId','fenceId','actorAccountId','selectedCommitId','publicationFence') + AND (member.value #>> '{}') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR member.key IN ('canonicalTenantId','canonicalVersionId','versionIdentityOperationId','intakeRequestId','intakeOperationId','sourceOperationId','applicationOperationId','applicationRequestId','appliedCommitId','operationId','fenceId','actorAccountId','selectedCommitId','publicationFence') + AND (member.value #>> '{}') = '00000000-0000-0000-0000-000000000000' THEN + RAISE EXCEPTION 'Canonical nonzero inventory UUID required' USING ERRCODE = '23514'; END IF; + IF member.key IN ('intakeRequestDigest','sourceEvidenceDigest','intakeReceiptDigest','bindingDigest','appliedResultDigest','selectionDigest') + AND (member.value #>> '{}') !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Canonical inventory digest required' USING ERRCODE = '23514'; END IF; + END LOOP; + END LOOP; + IF owner->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]*[a-z0-9])?$' OR length(owner->>'targetNamespace') > 63 + OR frozen->>'versionStateEpoch' !~ '^[1-9][0-9]*$' OR (frozen->>'versionStateEpoch')::NUMERIC > 9223372036854775807 + OR frozen->>'requestDigest' !~ '^[0-9a-f]{64}$' OR checkpoint->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR jsonb_typeof(checkpoint->'digestSchemaVersion') <> 'number' OR checkpoint->>'digestSchemaVersion' !~ '^[1-9][0-9]*$' + OR (checkpoint->>'digestSchemaVersion')::NUMERIC > 2147483647 + OR btrim(account_order->>'publicationRequestId') = '' OR btrim(account_order->>'publicationRequestId') <> account_order->>'publicationRequestId' + OR btrim(frozen->>'publicationRequestId') = '' OR btrim(frozen->>'publicationRequestId') <> frozen->>'publicationRequestId' + OR btrim(frozen->>'publishWorkflowId') = '' OR btrim(frozen->>'publishWorkflowId') <> frozen->>'publishWorkflowId' + OR model->>'graphDigest' !~ '^sha256:[0-9a-f]{64}$' OR model->>'topologyResultDigest' !~ '^sha256:[0-9a-f]{64}$' + OR jsonb_typeof(model->'modelId') <> 'string' OR jsonb_typeof(model->'graphDigest') <> 'string' + OR jsonb_typeof(model->'topologyResultDigest') <> 'string' + OR model->'generationRuleFields' <> '["id","name","scopeType","scopeId","value"]'::JSONB + OR model->'regionFields' <> '["id","shardId","name","weather","generationSeed","generatorType","generatorParams","spacingMultiplier"]'::JSONB + OR model->'zoneFields' <> '["id","regionId","name"]'::JSONB + OR model->'roomFields' <> '["id","zoneId","name","description","nameLocalizedVariantsJson","descriptionLocalizedVariantsJson"]'::JSONB + OR model->'roomExitFields' <> '["id","fromRoomId","toRoomId","direction","cost"]'::JSONB + OR model->'spawnBindingFields' <> '["id","roomId","entityTemplateType","entityReference.kind","entityReference.tenantId","entityReference.versionId","entityReference.templateId","spawnCount","respawnDelaySeconds"]'::JSONB + OR jsonb_typeof(model->'familyCounts') <> 'array' OR jsonb_array_length(model->'familyCounts') <> 6 + OR jsonb_typeof(model->'regionGeneratorInputs') <> 'array' OR jsonb_typeof(model->'spawnBindingInputs') <> 'array' + OR jsonb_typeof(model->'spawnBindingCount') <> 'number' OR model->>'spawnBindingCount' !~ '^(0|[1-9][0-9]*)$' + OR (model->>'spawnBindingCount')::NUMERIC > 2147483647 THEN + RAISE EXCEPTION 'Unsupported public inventory source profile' USING ERRCODE = '23514'; END IF; + FOR i IN 0..5 LOOP + item := model->'familyCounts'->i; + IF jsonb_typeof(item) <> 'object' OR NOT item ?& ARRAY['family','rowCount'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 2 + OR item->'family' IS DISTINCT FROM to_jsonb((ARRAY['REGION','ZONE','ROOM','ROOM_EXIT','GENERATION_RULE','WORLD_ENTITY_SPAWN_BINDING'])[i+1]) + OR jsonb_typeof(item->'rowCount') IS DISTINCT FROM 'number' OR item->>'rowCount' !~ '^(0|[1-9][0-9]*)$' + OR (item->>'rowCount')::NUMERIC > 2147483647 THEN + RAISE EXCEPTION 'Incomplete source family enumeration' USING ERRCODE = '23514'; END IF; + counts := array_append(counts, (item->>'rowCount')::INTEGER); + END LOOP; + IF counts[3] < 1 OR counts[5] <> 0 OR counts[1] <> jsonb_array_length(model->'regionGeneratorInputs') + OR counts[6] <> jsonb_array_length(model->'spawnBindingInputs') OR counts[6] <> (model->>'spawnBindingCount')::INTEGER THEN + RAISE EXCEPTION 'Source inventory counts differ from explicit inputs' USING ERRCODE = '23514'; END IF; + previous_key := NULL; + FOR item IN SELECT * FROM jsonb_array_elements(model->'regionGeneratorInputs') LOOP + IF jsonb_typeof(item) <> 'object' OR NOT item ?& ARRAY['regionTemplateId','generatorType','generatorParams'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 3 + OR jsonb_typeof(item->'regionTemplateId') IS DISTINCT FROM 'string' + OR item->>'regionTemplateId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR item->>'regionTemplateId' = '00000000-0000-0000-0000-000000000000' + OR previous_key COLLATE "C" >= (item->>'regionTemplateId') COLLATE "C" + OR item->'generatorType' IS DISTINCT FROM '""'::JSONB OR item->'generatorParams' IS DISTINCT FROM '""'::JSONB THEN + RAISE EXCEPTION 'Unsupported or unordered region generator input' USING ERRCODE = '23514'; END IF; + previous_key := item->>'regionTemplateId'; + END LOOP; + previous_key := NULL; + FOR item IN SELECT * FROM jsonb_array_elements(model->'spawnBindingInputs') LOOP + IF jsonb_typeof(item) <> 'object' OR NOT item ?& ARRAY['bindingTemplateId','roomTemplateId','entityTemplateType','entityReferenceKind','entityTenantId','entityVersionId','entityTemplateId','spawnCount','respawnDelaySeconds'] + OR (SELECT count(*) FROM jsonb_object_keys(item)) <> 9 THEN + RAISE EXCEPTION 'Incomplete spawn input' USING ERRCODE = '23514'; END IF; + FOR member IN SELECT * FROM jsonb_each(item) LOOP + IF member.key NOT IN ('spawnCount','respawnDelaySeconds') AND jsonb_typeof(member.value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Spawn reference exact string required' USING ERRCODE = '23514'; END IF; + IF member.key IN ('bindingTemplateId','roomTemplateId','entityTenantId','entityVersionId','entityTemplateId') + AND ((member.value #>> '{}') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (member.value #>> '{}') = '00000000-0000-0000-0000-000000000000') THEN + RAISE EXCEPTION 'Canonical spawn UUID required' USING ERRCODE = '23514'; END IF; + END LOOP; + IF item->>'entityReferenceKind' <> 'ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID' + OR item->>'entityTenantId' <> owner->>'canonicalTenantId' OR item->>'entityVersionId' <> owner->>'canonicalVersionId' + OR item->>'entityTemplateType' NOT IN ('ITEM','NPC') + OR jsonb_typeof(item->'spawnCount') IS DISTINCT FROM 'number' OR item->>'spawnCount' !~ '^[1-9][0-9]*$' + OR (item->>'spawnCount')::NUMERIC > 2147483647 + OR jsonb_typeof(item->'respawnDelaySeconds') IS DISTINCT FROM 'number' OR item->>'respawnDelaySeconds' !~ '^(0|[1-9][0-9]*)$' + OR (item->>'respawnDelaySeconds')::NUMERIC > 2147483647 + OR previous_key COLLATE "C" >= (item->>'bindingTemplateId') COLLATE "C" THEN + RAISE EXCEPTION 'Unsupported or unordered scoped spawn input' USING ERRCODE = '23514'; END IF; + previous_key := item->>'bindingTemplateId'; + END LOOP; + SELECT coalesce(jsonb_agg((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT) + ORDER BY unit->>'aggregateType', unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId'), '[]'::JSONB) + INTO expected_epochs FROM jsonb_array_elements((selected->>'selectedCommitBindingJson')::JSONB->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE' + OR (SELECT count(*) FROM jsonb_object_keys(inventory)) <> 10 + OR owner->>'targetNamespace' IS DISTINCT FROM selector->'request'->>'targetNamespace' + OR owner->>'canonicalTenantId' IS DISTINCT FROM selector->'request'->>'canonicalTenantId' + OR owner->>'canonicalVersionId' IS DISTINCT FROM selector->'request'->>'canonicalVersionId' + OR owner->>'intakeRequestId' IS DISTINCT FROM selector->'request'->>'intakeRequestId' + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(applied_operation, 1), 'UTF8') + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(original_account, 1), 'UTF8') + OR application->>'applicationRequestId' IS DISTINCT FROM selected->'intent'->>'selectedCommitRequestId' + OR application->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR application->>'bindingDigest' IS DISTINCT FROM selected->'intent'->>'selectedCommitDigest' + OR application->>'appliedResultDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(applied_bytes), 'hex') + OR account_order->>'operationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 1), 'UTF8') + OR account_order->>'fenceId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 2), 'UTF8') + OR account_order->>'actorAccountId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 1), 'UTF8') + OR account_order->>'publicationRequestId' IS DISTINCT FROM selected->'intent'->>'publishRequestId' + OR account_order->>'selectionDigest' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 3), 'UTF8') + OR account_order->>'selectedCommitId' IS DISTINCT FROM selected->'intent'->>'selectedCommitId' + OR account_order->>'bindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes), 'hex') + OR frozen->>'publicationFence' IS DISTINCT FROM selector->'request'->>'publicationFence' + OR frozen->>'publicationRequestId' IS DISTINCT FROM selector->'request'->>'publicationRequestId' + OR frozen->>'requestDigest' IS DISTINCT FROM selector->'request'->>'requestDigest' + OR frozen->>'versionStateEpoch' IS DISTINCT FROM selector->'request'->>'versionStateEpoch' + OR frozen->>'publishWorkflowId' IS DISTINCT FROM selector->'request'->>'publishWorkflowId' + OR checkpoint->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR checkpoint->>'contentDigest' IS DISTINCT FROM selector->'request'->>'contentDigest' + OR checkpoint->'digestSchemaVersion' IS DISTINCT FROM selector->'request'->'digestSchemaVersion' + OR model->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR model->'appliedEpochs' IS DISTINCT FROM expected_epochs OR expected_epochs = '[]'::JSONB + OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB + OR model->'generationRuleInputCount' IS DISTINCT FROM '0'::JSONB + OR inventory->'artifactDecisions' IS DISTINCT FROM + '[{"artifactKind":"NAVMESH","state":"NOT_REQUIRED","rule":"ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"},{"artifactKind":"PATH_GRAPH","state":"NOT_REQUIRED","rule":"AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"}]'::JSONB THEN + RAISE EXCEPTION 'Inventory differs from exact original selected Account, APPLIED graph or freeze' USING ERRCODE = '23514'; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE OR REPLACE FUNCTION guard_game_design_publication_operation() RETURNS trigger AS $$ +DECLARE attempt publish_attempt%ROWTYPE; selected game_design_authored_draft_publish_selection%ROWTYPE; + account_bytes BYTEA; input_bytes BYTEA; world_json JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'publication operation history is immutable' USING ERRCODE = 'check_violation'; + END IF; + PERFORM 1 FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM publish_attempt + WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + PERFORM 1 FROM version WHERE id = NEW.version_id AND tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT selected FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = NEW.tenant_id AND game_design_version_row_id = NEW.version_id; + PERFORM require_selected_inventory_operation_v2(NEW.request_bytes); + account_bytes := published_world_selector_frame(NEW.request_bytes, 1); + input_bytes := published_world_selector_frame(account_bytes, 3); + world_json := convert_from(published_world_selector_frame(NEW.request_bytes, 2), 'UTF8')::JSONB; + IF convert_from(published_world_selector_frame(NEW.request_bytes, 0), 'UTF8') <> 'game-design-publication-operation/v2' + OR convert_from(published_world_selector_frame(account_bytes, 0), 'UTF8') <> 'account-publication-authorization/v1' + OR convert_from(published_world_selector_frame(input_bytes, 0), 'UTF8') <> 'account-publication-input/v1' + OR published_world_selector_frame(input_bytes, 2) IS DISTINCT FROM convert_to(selected.selection_json, 'UTF8') + OR convert_from(published_world_selector_frame(input_bytes, 3), 'UTF8') IS DISTINCT FROM selected.selection_digest + OR world_json->'request'->>'requestDigest' IS DISTINCT FROM substring(selected.selection_digest FROM 8) + OR world_json->'request'->>'canonicalTenantId' IS DISTINCT FROM selected.canonical_tenant_id::TEXT + OR world_json->'request'->>'canonicalVersionId' IS DISTINCT FROM selected.canonical_version_id::TEXT + OR world_json->'request'->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR world_json->'request'->>'publicationRequestId' IS DISTINCT FROM selected.publish_request_id + OR world_json->'request'->>'versionStateEpoch' IS DISTINCT FROM selected.version_state_epoch::TEXT THEN + RAISE EXCEPTION 'publication operation bytes differ from exact owner selection' USING ERRCODE = 'check_violation'; + END IF; + IF attempt.tenant_id <> NEW.tenant_id OR attempt.version_id <> NEW.version_id + OR attempt.publish_type <> 'FULL_VERSION' OR attempt.request_digest IS DISTINCT FROM NEW.selection_digest + OR NOT EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.game_design_version_tenant_key = NEW.tenant_id + AND s.game_design_version_row_id = NEW.version_id AND s.selection_digest = NEW.selection_digest) THEN + RAISE EXCEPTION 'publication operation does not bind exact selected attempt' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.outcome <> 'PENDING' OR NEW.revision <> 1 OR attempt.status <> 'PENDING' + OR EXISTS (SELECT 1 FROM published_release_bundle WHERE tenant_id = NEW.tenant_id AND version_id = NEW.version_id) THEN + RAISE EXCEPTION 'historical attempts cannot acquire publication authority' USING ERRCODE = 'check_violation'; + END IF; + ELSE + IF OLD.outcome <> 'PENDING' OR NEW.outcome = 'PENDING' + OR NEW.revision <> OLD.revision + 1 + OR (NEW.publish_workflow_id, NEW.tenant_id, NEW.version_id, NEW.selection_digest, NEW.request_bytes) + IS DISTINCT FROM (OLD.publish_workflow_id, OLD.tenant_id, OLD.version_id, OLD.selection_digest, OLD.request_bytes) THEN + RAISE EXCEPTION 'publication operation identity or terminal outcome is immutable' USING ERRCODE = 'check_violation'; + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] + +-- A retained v1 operation stays immutable, but cannot acquire a new source capture. +-- [jooq ignore start] +CREATE FUNCTION guard_selected_inventory_capture_v2() RETURNS trigger AS $$ +BEGIN + PERFORM require_selected_inventory_operation_v2(NEW.operation_bytes); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER command_capture_inventory_v2 BEFORE INSERT ON game_design_command_source_capture + FOR EACH ROW EXECUTE FUNCTION guard_selected_inventory_capture_v2(); +CREATE TRIGGER policy_capture_inventory_v2 BEFORE INSERT ON game_design_realm_policy_capture + FOR EACH ROW EXECUTE FUNCTION guard_selected_inventory_capture_v2(); +CREATE TRIGGER asset_capture_inventory_v2 BEFORE INSERT ON game_design_asset_source_capture + FOR EACH ROW EXECUTE FUNCTION guard_selected_inventory_capture_v2(); + +-- Historical v1 publication bytes remain readable history, never new derived policy authority. +-- Run before the original policy-set guard; all of its lifecycle/immutability checks still run +-- for a structurally valid v2 operation, including the one permitted sealing UPDATE. +CREATE FUNCTION guard_published_policy_inventory_v2() RETURNS trigger AS $$ +BEGIN + IF selected_inventory_operation_nth(NEW.operation_bytes, 0) + IS DISTINCT FROM convert_to('game-design-publication-operation/v2', 'UTF8') THEN + RAISE EXCEPTION 'Published realm policy evidence requires immutable v2 operation' + USING ERRCODE = '23514'; + END IF; + PERFORM require_selected_inventory_operation_v2(NEW.operation_bytes); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER a_published_policy_inventory_v2 BEFORE INSERT OR UPDATE + ON game_design_published_realm_policy_set + FOR EACH ROW EXECUTE FUNCTION guard_published_policy_inventory_v2(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index ccc3d4606b..ec3ae01518 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -163,7 +163,7 @@ private static GameDesignPublicationOperation retain( if (captureSources) { operation = new SelectedDraftPublicationOwner(dsl) - .reserve(intent, operation.account(), operation.world()) + .reserve(intent, operation.account(), operation.world(), operation.inventory()) .operation(); } else { var attempt = new PublishAttempt(); diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java index b501f5ae9f..3e416710bc 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -157,6 +157,10 @@ public static GameDesignPublicationOperation forSelection( seed.selectorReceiptBytes(), seed.originalAccountBindingBytes(), seed.appliedResultBytes()); - return new GameDesignPublicationOperation(account, world); + return new GameDesignPublicationOperation( + account, + world, + net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures.stipulated( + account, world)); } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java index f36f293f7b..700e8dd2a4 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java @@ -684,8 +684,8 @@ private void migrate(DriverManagerDataSource dataSource, String schema, Migratio private Game saveGame(Fixture fixture, String tenantPrefix) { Game game = new Game(); - game.setTenantId(tenantPrefix + "-" + UUID.randomUUID().toString().replace("-", "")); - game.setName("Version asset publication fixture"); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Version asset publication fixture: " + tenantPrefix); game.setDescription("Synthetic Game Design source row for persistence proof"); return Objects.requireNonNull( fixture.transaction().execute(status -> fixture.games().save(game))); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index ad9ddf15b4..f8a9c59840 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -466,7 +466,11 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth inOwnerTransaction( () -> new SelectedDraftPublicationOwner(dsl) - .reserve(selection.intent(), operation.account(), operation.world())); + .reserve( + selection.intent(), + operation.account(), + operation.world(), + operation.inventory())); assertThat(exactReservationRetry.selection()).isEqualTo(selection); assertThat(exactReservationRetry.operation().canonicalBytes()) .containsExactly(operation.canonicalBytes()); @@ -651,6 +655,13 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele publicationReadIdentities.gameDesignClient().properties(pki.ca), new GrpcChannelFactory(), NAMESPACE); + var inventoryClient = + new net.firedevops.firemud.common.publication + .WorldSelectedPublicationArtifactInventoryClient( + endpoints, + publicationReadIdentities.gameDesignClient().properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE); var worldClient = new WorldPublishedStartLocationClient( endpoints, @@ -659,6 +670,7 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele NAMESPACE)) { accountClient.init(); freezeClient.init(); + inventoryClient.init(); worldClient.init(); var command = new SelectedDraftPublicationCommandService( @@ -666,6 +678,7 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele transactionManager, accountClient, freezeClient, + inventoryClient, worldClient, NAMESPACE, versionPublishCommandService); @@ -724,6 +737,7 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) assertThat(accountEndpoint.readCount()).isEqualTo(3); assertThat(worldEndpoint.readCount()).isEqualTo(2); assertThat(freezeEndpoint.beginCount()).isEqualTo(2); + assertThat(freezeEndpoint.inventoryReadCount()).isEqualTo(2); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow(); @@ -761,6 +775,10 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) String releaseRefBeforeRetry = bundle.getPublishedReleaseBundleRef(); VersionDto exactRetry = command.publishSelectedDraftFullVersion(selection.intent(), operation.account()); + assertThat(freezeEndpoint.inventoryReadCount()).isEqualTo(2); + assertThat(freezeEndpoint.beginCount()).isEqualTo(2); + assertThat(accountEndpoint.readCount()).isEqualTo(3); + assertThat(worldEndpoint.readCount()).isEqualTo(2); assertThat(exactRetry.id()).isEqualTo(published.id()); assertThat( publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow().getId()) @@ -905,7 +923,8 @@ void selectedDraftPublicationRemainsPendingWithoutItsOriginalOperation() throws } @Test - void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence() { + void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence() + throws Exception { String tenantId = "9006"; Game game = new Game(); game.setTenantId(tenantId); @@ -940,7 +959,11 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( inOwnerTransaction( () -> new SelectedDraftPublicationOwner(dsl) - .reserve(changedIntent, operation.account(), operation.world()))) + .reserve( + changedIntent, + operation.account(), + operation.world(), + operation.inventory()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("changed notes"); @@ -955,9 +978,13 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( inOwnerTransaction( () -> new SelectedDraftPublicationOwner(dsl) - .reserve(selection.intent(), changedAccount, operation.world()))) + .reserve( + selection.intent(), + changedAccount, + operation.world(), + operation.inventory()))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + .hasMessageContaining("World public inventory differs from exact selected Account order"); var retained = new GameDesignPublicationOperationRepository(dsl) @@ -965,6 +992,89 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( .orElseThrow(); assertThat(retained.outcome()).isEqualTo("PENDING"); assertThat(retained.operation().canonicalBytes()).containsExactly(operation.canonicalBytes()); + // Real owner SQL rejects partial/unknown profiles even when the forged payload has a fresh + // matching digest. Upstream inventory authority is still expressly stipulated in this fixture. + var mapper = tools.jackson.databind.json.JsonMapper.builder().build(); + for (int mutation = 0; mutation < 5; mutation++) { + var publicJson = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(operation.inventory().canonicalBytes()); + var model = (tools.jackson.databind.node.ObjectNode) publicJson.get("sourceModel"); + switch (mutation) { + case 0 -> + ((tools.jackson.databind.node.ObjectNode) publicJson.get("ownerScope")) + .remove("intakeReceiptDigest"); + case 1 -> model.put("unknownSourceFamily", true); + case 2 -> model.putArray("familyCounts"); + case 3 -> + ((tools.jackson.databind.node.ObjectNode) model.get("regionGeneratorInputs").get(0)) + .put("generatorType", "opaque"); + case 4 -> + ((tools.jackson.databind.node.ObjectNode) model.get("familyCounts").get(2)) + .put("rowCount", 0); + default -> throw new AssertionError(); + } + byte[] changedInventory = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(publicJson)); + var bytes = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + bytes, GameDesignPublicationOperationBinding.SCHEMA); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + bytes, operation.account().canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + bytes, operation.world().canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + bytes, changedInventory); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + bytes, + "sha256:" + + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256").digest(changedInventory))); + assertThatThrownBy( + () -> + dsl.fetch( + "SELECT require_selected_inventory_operation_v2(?)", bytes.toByteArray())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + dsl.fetch("SELECT require_selected_inventory_operation_v2(?)", operation.canonicalBytes()); + // Supply the historical three-frame schema without retrofitting any retained owner rows. + // This is actual policy-table ingress denial, not proof that a genuine v1 row was migrated. + var historicalV1 = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + historicalV1, "game-design-publication-operation/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + historicalV1, operation.account().canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + historicalV1, operation.world().canonicalBytes()); + var policySetsBefore = + dsl.fetch("SELECT * FROM game_design_published_realm_policy_set").intoMaps(); + var policiesBefore = dsl.fetch("SELECT * FROM game_design_published_realm_policy").intoMaps(); + assertThatThrownBy( + () -> + inOwnerTransaction( + () -> + dsl.execute( + "INSERT INTO game_design_published_realm_policy_set (operation_bytes) VALUES (?)", + historicalV1.toByteArray()))) + .rootCause() + .isInstanceOf(java.sql.SQLException.class) + .hasMessageContaining("Published realm policy evidence requires immutable v2 operation") + .satisfies( + failure -> + assertThat(((java.sql.SQLException) failure).getSQLState()).isEqualTo("23514")); + assertThat(dsl.fetch("SELECT * FROM game_design_published_realm_policy_set").intoMaps()) + .isEqualTo(policySetsBefore); + assertThat(dsl.fetch("SELECT * FROM game_design_published_realm_policy").intoMaps()) + .isEqualTo(policiesBefore); + assertThat( + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow() + .operation() + .canonicalBytes()) + .containsExactly(operation.canonicalBytes()); assertThat( publishAttemptRepository .findByPublishWorkflowId(operation.workflowId()) @@ -1326,7 +1436,12 @@ private void assertTerminalOwnerReadOverMtls( UUID.randomUUID(), operation.account().input(), operation.account().sources()); - var substituted = new GameDesignPublicationOperationBinding(changedAccount, operation.world()); + var substituted = + new GameDesignPublicationOperationBinding( + changedAccount, + operation.world(), + net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures.stipulated( + changedAccount, operation.world())); var missing = IsolatedPublicationOperationFixtures.fresh( operation.account().input().selection().target()); @@ -1553,6 +1668,7 @@ private static final class StipulatedWorldFreezeEndpoint .WorldSelectedDraftPublicationFreezeServiceImplBase { private final GameDesignPublicationOperation operation; private final AtomicInteger begins = new AtomicInteger(); + private final AtomicInteger inventoryReads = new AtomicInteger(); private StipulatedWorldFreezeEndpoint(GameDesignPublicationOperation operation) { this.operation = operation; @@ -1603,6 +1719,37 @@ public void beginVersionPublicationFreeze( } } + @Override + public void readSelectedPublicationArtifactInventory( + net.firedevops.firemud.worldmanagement.v1.ReadSelectedPublicationArtifactInventoryRequest + request, + StreamObserver< + net.firedevops.firemud.worldmanagement.v1 + .ReadSelectedPublicationArtifactInventoryResponse> + observer) { + if (!requireGameDesignPeer(observer)) return; + inventoryReads.incrementAndGet(); + var freeze = + net.firedevops.firemud.common.publication + .WorldSelectedPublicationArtifactInventoryGrpcCodec.fromRequest(request); + if (!freeze.request().equals(operation.inventory().freezeEvidence().request()) + || !freeze + .acknowledgement() + .equals(operation.inventory().freezeEvidence().acknowledgement())) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + observer.onNext( + net.firedevops.firemud.common.publication + .WorldSelectedPublicationArtifactInventoryGrpcCodec.toResponse( + operation.inventory())); + observer.onCompleted(); + } + + int inventoryReadCount() { + return inventoryReads.get(); + } + int beginCount() { return begins.get(); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java index c4318569a1..955909d95e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; @@ -41,6 +42,7 @@ void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws var fixture = fixture(); var account = mock(AccountPublicationAuthorizationReadClient.class); var freeze = freezeClient(fixture); + var inventory = inventoryClient(fixture); var world = mock(WorldPublishedStartLocationClient.class); var owner = mock(SelectedDraftPublicationOwner.class); var reader = mock(SelectedDraftPublicationAdmissionService.SelectionReader.class); @@ -75,18 +77,20 @@ void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws binding -> Arrays.equals( binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), - same(fixture.operation().world()))) + same(fixture.operation().world()), + same(fixture.operation().inventory()))) .thenReturn(reservation); var service = new SelectedDraftPublicationAdmissionService( - transactions, account, freeze, world, owner, reader, NAMESPACE); + transactions, account, freeze, inventory, world, owner, reader, NAMESPACE); assertThat(service.admitAndReserve(fixture.intent(), fixture.operation().account())) .isSameAs(reservation); - var order = inOrder(reader, account, freeze, world, transactions, owner); + var order = inOrder(reader, account, freeze, inventory, world, transactions, owner); order.verify(reader).read(fixture.intent()); order.verify(account).read(any()); order.verify(freeze).begin(any()); + order.verify(inventory).read(any()); order.verify(world).read(fixture.worldRequest()); order.verify(transactions).getTransaction(any()); order @@ -97,7 +101,8 @@ void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws binding -> Arrays.equals( binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), - same(fixture.operation().world())); + same(fixture.operation().world()), + same(fixture.operation().inventory())); } @Test @@ -105,18 +110,26 @@ void missingRetainedSelectionNeverReadsAccountFreezesWorldOrOpensSql() throws Ex var fixture = fixture(); var account = mock(AccountPublicationAuthorizationReadClient.class); var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); var world = mock(WorldPublishedStartLocationClient.class); var owner = mock(SelectedDraftPublicationOwner.class); var transactions = mock(PlatformTransactionManager.class); var service = new SelectedDraftPublicationAdmissionService( - transactions, account, freeze, world, owner, intent -> Optional.empty(), NAMESPACE); + transactions, + account, + freeze, + inventory, + world, + owner, + intent -> Optional.empty(), + NAMESPACE); assertThatThrownBy( () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SELECTION_UNAVAILABLE"); - verifyNoInteractions(account, freeze, world, owner, transactions); + verifyNoInteractions(account, freeze, inventory, world, owner, transactions); } @Test @@ -124,6 +137,7 @@ void freezeFailureNeverReadsSelectorOrReserves() throws Exception { var fixture = fixture(); var account = mock(AccountPublicationAuthorizationReadClient.class); var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); var world = mock(WorldPublishedStartLocationClient.class); var owner = mock(SelectedDraftPublicationOwner.class); var transactions = mock(PlatformTransactionManager.class); @@ -133,6 +147,7 @@ void freezeFailureNeverReadsSelectorOrReserves() throws Exception { transactions, account, freeze, + inventory, world, owner, intent -> @@ -153,7 +168,7 @@ void freezeFailureNeverReadsSelectorOrReserves() throws Exception { assertThatThrownBy( () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) .isSameAs(failure); - verifyNoInteractions(world, owner, transactions); + verifyNoInteractions(inventory, world, owner, transactions); } @AfterEach @@ -164,6 +179,43 @@ void clearTransactionState() { } } + @Test + void missingInventoryAfterAcknowledgedFreezeNeverReadsSelectorOrOpensSql() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var selection = fixture.operation().account().input().selection(); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freezeClient(fixture), + inventory, + world, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + selection.canonicalJson(), selection.digest())), + NAMESPACE); + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("inventory readback"); + verify(inventory).read(any()); + verifyNoInteractions(world, owner, transactions); + } + @Test void rejectsAmbientSqlTransactionBeforeEitherOwnerRead() throws Exception { var fixture = fixture(); @@ -283,6 +335,7 @@ private static SelectedDraftPublicationAdmissionService service( mock(PlatformTransactionManager.class), accountClient, freezeClient(fixture), + inventoryClient(fixture), worldClient, owner, intent -> @@ -293,6 +346,18 @@ private static SelectedDraftPublicationAdmissionService service( NAMESPACE); } + private static WorldSelectedPublicationArtifactInventoryClient inventoryClient(Fixture fixture) { + var client = mock(WorldSelectedPublicationArtifactInventoryClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return fixture.operation().inventory(); + }); + return client; + } + private static WorldSelectedDraftPublicationFreezeClient freezeClient(Fixture fixture) { var client = mock(WorldSelectedDraftPublicationFreezeClient.class); when(client.begin(any())) diff --git a/services/world-management-service/src/main/resources/db/migration/V56__publication_operation_inventory_v2.sql b/services/world-management-service/src/main/resources/db/migration/V56__publication_operation_inventory_v2.sql new file mode 100644 index 0000000000..2e09511e43 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V56__publication_operation_inventory_v2.sql @@ -0,0 +1,192 @@ +-- Mandatory v2 public evidence, derived from unchanged private retained inventory. +-- [jooq ignore start] +CREATE FUNCTION selected_inventory_operation_frame(operation_bytes BYTEA, frame_offset INTEGER) RETURNS BYTEA AS $$ +DECLARE length_bytes BIGINT; +BEGIN + IF frame_offset < 0 OR frame_offset > octet_length(operation_bytes) - 4 THEN + RAISE EXCEPTION 'Truncated publication inventory frame' USING ERRCODE = '23514'; END IF; + length_bytes := get_byte(operation_bytes, frame_offset)::BIGINT * 16777216 + + get_byte(operation_bytes, frame_offset + 1)::BIGINT * 65536 + + get_byte(operation_bytes, frame_offset + 2)::BIGINT * 256 + + get_byte(operation_bytes, frame_offset + 3)::BIGINT; + IF length_bytes > 4194304 OR length_bytes > octet_length(operation_bytes) - frame_offset - 4 THEN + RAISE EXCEPTION 'Oversized publication inventory frame' USING ERRCODE = '23514'; END IF; + RETURN substring(operation_bytes FROM frame_offset + 5 FOR length_bytes::INTEGER); +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION selected_inventory_operation_nth(operation_bytes BYTEA, frame_index INTEGER) RETURNS BYTEA AS $$ +DECLARE offset_bytes INTEGER := 0; value BYTEA; i INTEGER; +BEGIN + IF frame_index < 0 THEN RAISE EXCEPTION 'Negative frame index' USING ERRCODE = '23514'; END IF; + FOR i IN 0..frame_index LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + END LOOP; + RETURN value; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; +CREATE FUNCTION require_selected_inventory_operation_v2(operation_bytes BYTEA) RETURNS VOID AS $$ +DECLARE frames BYTEA[] := ARRAY[]::BYTEA[]; value BYTEA; offset_bytes INTEGER := 0; + account_bytes BYTEA; input_bytes BYTEA; selector JSONB; inventory JSONB; selected JSONB; + applied JSONB; applied_bytes BYTEA; applied_operation BYTEA; original_account BYTEA; + owner JSONB; application JSONB; account_order JSONB; frozen JSONB; checkpoint JSONB; + model JSONB; expected_epochs JSONB; i INTEGER; +BEGIN + IF operation_bytes IS NULL OR octet_length(operation_bytes) NOT BETWEEN 1 AND 4194304 THEN + RAISE EXCEPTION 'Complete bounded v2 publication operation required' USING ERRCODE = '23514'; END IF; + FOR i IN 0..4 LOOP + value := selected_inventory_operation_frame(operation_bytes, offset_bytes); + offset_bytes := offset_bytes + 4 + octet_length(value); + frames := array_append(frames, value); + END LOOP; + IF offset_bytes <> octet_length(operation_bytes) OR frames[1] <> convert_to('game-design-publication-operation/v2', 'UTF8') + OR frames[5] IS DISTINCT FROM convert_to('sha256:' || encode(sha256(frames[4]), 'hex'), 'UTF8') THEN + RAISE EXCEPTION 'Publication v2 schema, exact frame count or inventory digest invalid' USING ERRCODE = '23514'; END IF; + account_bytes := frames[2]; + input_bytes := selected_inventory_operation_nth(account_bytes, 3); + selected := convert_from(selected_inventory_operation_nth(input_bytes, 2), 'UTF8')::JSONB; + selector := convert_from(frames[3], 'UTF8')::JSONB; + inventory := convert_from(frames[4], 'UTF8')::JSONB; + applied_bytes := decode(selector->>'appliedResultBytesBase64', 'base64'); + applied := convert_from(applied_bytes, 'UTF8')::JSONB; + applied_operation := decode(applied->>'operationBytesBase64', 'base64'); + original_account := decode(selector->>'originalAccountBindingBytesBase64', 'base64'); + owner := inventory->'ownerScope'; application := inventory->'selectedApplication'; + account_order := inventory->'accountOrder'; frozen := inventory->'freeze'; + checkpoint := inventory->'checkpoint'; model := inventory->'sourceModel'; + SELECT coalesce(jsonb_agg((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT) + ORDER BY unit->>'aggregateType', unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId'), '[]'::JSONB) + INTO expected_epochs FROM jsonb_array_elements((selected->>'selectedCommitBindingJson')::JSONB->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE' + OR (SELECT count(*) FROM jsonb_object_keys(inventory)) <> 10 + OR owner->>'targetNamespace' IS DISTINCT FROM selector->'request'->>'targetNamespace' + OR owner->>'canonicalTenantId' IS DISTINCT FROM selector->'request'->>'canonicalTenantId' + OR owner->>'canonicalVersionId' IS DISTINCT FROM selector->'request'->>'canonicalVersionId' + OR owner->>'intakeRequestId' IS DISTINCT FROM selector->'request'->>'intakeRequestId' + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(applied_operation, 1), 'UTF8') + OR application->>'applicationOperationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(original_account, 1), 'UTF8') + OR application->>'applicationRequestId' IS DISTINCT FROM selected->'intent'->>'selectedCommitRequestId' + OR application->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR application->>'bindingDigest' IS DISTINCT FROM selected->'intent'->>'selectedCommitDigest' + OR application->>'appliedResultDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(applied_bytes), 'hex') + OR account_order->>'operationId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 1), 'UTF8') + OR account_order->>'fenceId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(account_bytes, 2), 'UTF8') + OR account_order->>'actorAccountId' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 1), 'UTF8') + OR account_order->>'publicationRequestId' IS DISTINCT FROM selected->'intent'->>'publishRequestId' + OR account_order->>'selectionDigest' IS DISTINCT FROM convert_from(selected_inventory_operation_nth(input_bytes, 3), 'UTF8') + OR account_order->>'selectedCommitId' IS DISTINCT FROM selected->'intent'->>'selectedCommitId' + OR account_order->>'bindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes), 'hex') + OR frozen->>'publicationFence' IS DISTINCT FROM selector->'request'->>'publicationFence' + OR frozen->>'publicationRequestId' IS DISTINCT FROM selector->'request'->>'publicationRequestId' + OR frozen->>'requestDigest' IS DISTINCT FROM selector->'request'->>'requestDigest' + OR frozen->>'versionStateEpoch' IS DISTINCT FROM selector->'request'->>'versionStateEpoch' + OR frozen->>'publishWorkflowId' IS DISTINCT FROM selector->'request'->>'publishWorkflowId' + OR checkpoint->>'appliedCommitId' IS DISTINCT FROM selector->'request'->>'appliedCommitId' + OR checkpoint->>'contentDigest' IS DISTINCT FROM selector->'request'->>'contentDigest' + OR checkpoint->'digestSchemaVersion' IS DISTINCT FROM selector->'request'->'digestSchemaVersion' + OR model->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR model->'appliedEpochs' IS DISTINCT FROM expected_epochs OR expected_epochs = '[]'::JSONB + OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB + OR model->'generationRuleInputCount' IS DISTINCT FROM '0'::JSONB + OR inventory->'artifactDecisions' IS DISTINCT FROM + '[{"artifactKind":"NAVMESH","state":"NOT_REQUIRED","rule":"ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"},{"artifactKind":"PATH_GRAPH","state":"NOT_REQUIRED","rule":"AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"}]'::JSONB THEN + RAISE EXCEPTION 'Inventory differs from exact original selected Account, APPLIED graph or freeze' USING ERRCODE = '23514'; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE OR REPLACE FUNCTION world_require_publication_operation_account_binding( + p_operation_bytes BYTEA, + p_publication_fence UUID, + p_world_evidence_bytes BYTEA +) +RETURNS BOOLEAN +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + frame_offset INTEGER := 0; + schema_bytes BYTEA; + account_binding_bytes BYTEA; + framed_world_evidence BYTEA; + retained_account_binding BYTEA; + retained_account_digest VARCHAR(71); + public_inventory BYTEA; public_digest BYTEA; private_inventory JSONB; expected_public JSONB; model JSONB; +BEGIN + IF p_operation_bytes IS NULL + OR octet_length(p_operation_bytes) > 4194304 + OR octet_length(p_operation_bytes) < 4 THEN + RAISE EXCEPTION 'World publication operation is empty or oversized' + USING ERRCODE = '23514'; + END IF; + + schema_bytes := world_publication_operation_frame(p_operation_bytes, frame_offset); + IF schema_bytes IS DISTINCT FROM convert_to('game-design-publication-operation/v2', 'UTF8') THEN + RAISE EXCEPTION 'World publication operation has an unsupported schema frame' + USING ERRCODE = '23514'; + END IF; + frame_offset := frame_offset + 4 + octet_length(schema_bytes); + + account_binding_bytes := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(account_binding_bytes); + + PERFORM require_selected_inventory_operation_v2(p_operation_bytes); + framed_world_evidence := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(framed_world_evidence); + public_inventory := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(public_inventory); + public_digest := world_publication_operation_frame(p_operation_bytes, frame_offset); + frame_offset := frame_offset + 4 + octet_length(public_digest); + IF frame_offset <> octet_length(p_operation_bytes) THEN + RAISE EXCEPTION 'World publication operation contains trailing frames or bytes' + USING ERRCODE = '23514'; + END IF; + IF framed_world_evidence IS DISTINCT FROM p_world_evidence_bytes THEN + RAISE EXCEPTION 'World publication operation differs from its exact World evidence' + USING ERRCODE = '23514'; + END IF; + + SELECT q.account_binding_bytes, q.account_binding_digest + INTO STRICT retained_account_binding, retained_account_digest + FROM "${serviceSchema}".world_design_publication_account_binding q + WHERE q.publication_fence = p_publication_fence; + IF encode(sha256(retained_account_binding), 'hex') + IS DISTINCT FROM substring(retained_account_digest FROM 8) THEN + RAISE EXCEPTION 'World publication Account qualification has a corrupt binding digest' + USING ERRCODE = '23514'; + END IF; + + SELECT convert_from(i.inventory_bytes, 'UTF8')::JSONB INTO STRICT private_inventory + FROM "${serviceSchema}".world_selected_publication_artifact_inventory i + WHERE i.publication_fence = p_publication_fence + AND i.inventory_digest = 'sha256:' || encode(sha256(i.inventory_bytes), 'hex'); + model := private_inventory->'sourceModel'; + model := jsonb_set(model, '{regionGeneratorInputs}', + coalesce((SELECT jsonb_agg(x ORDER BY x->>'regionTemplateId') FROM jsonb_array_elements(model->'regionGeneratorInputs') x), '[]'::JSONB)); + model := jsonb_set(model, '{spawnBindingInputs}', + coalesce((SELECT jsonb_agg(x ORDER BY x->>'bindingTemplateId') FROM jsonb_array_elements(model->'spawnBindingInputs') x), '[]'::JSONB)); + expected_public := jsonb_build_object( + 'schema', private_inventory->'schema', 'schemaVersion', private_inventory->'schemaVersion', + 'completeness', private_inventory->'completeness', + 'ownerScope', private_inventory->'ownerScope' - ARRAY['localTenantKey', 'localVersionKey', 'gameDesignVersionId'], + 'selectedApplication', private_inventory->'selectedApplication', + 'accountOrder', private_inventory->'accountOrder' - ARRAY['canonicalBindingBytes'], + 'freeze', private_inventory->'freeze', 'checkpoint', private_inventory->'checkpoint', + 'sourceModel', model, 'artifactDecisions', private_inventory->'artifactDecisions'); + IF jsonb_typeof(private_inventory) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(private_inventory)) <> 11 + OR NOT (private_inventory ?& ARRAY['schema', 'schemaVersion', 'completeness', 'ownerScope', + 'sourceIntake', 'selectedApplication', 'accountOrder', 'freeze', 'checkpoint', + 'sourceModel', 'artifactDecisions']) + OR jsonb_typeof(private_inventory->'sourceIntake') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(private_inventory->'sourceIntake')) <> 4 + OR NOT (private_inventory->'sourceIntake' ?& ARRAY['worldSlug', 'sourceGameRowId', + 'sourceGameTenantKey', 'sourceProvenanceKind']) + OR NOT (convert_from(public_inventory, 'UTF8') IS JSON OBJECT WITH UNIQUE KEYS) + OR convert_from(public_inventory, 'UTF8')::JSONB IS DISTINCT FROM expected_public + OR public_digest IS DISTINCT FROM convert_to('sha256:' || encode(sha256(public_inventory), 'hex'), 'UTF8') THEN + RAISE EXCEPTION 'World terminal inventory differs from complete retained public projection' USING ERRCODE = '23514'; END IF; + RETURN account_binding_bytes IS NOT DISTINCT FROM retained_account_binding; +END; +$$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 746594bd88..56ac4c1340 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -52,6 +52,7 @@ import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; @@ -466,6 +467,20 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() .doesNotContain( "localTenantKey", "localVersionKey", "gameDesignVersionId", "sourceGameRowId"); assertThat(inventory.publicDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + var directOwnerInventoryRead = + withGameDesignCaller( + () -> selectedPublicationArtifactInventoryReadService().read(firstFreeze)); + assertThat(directOwnerInventoryRead.canonicalBytes()) + .containsExactly(inventory.publicCanonicalBytes()); + assertThat(directOwnerInventoryRead.digest()).isEqualTo(inventory.publicDigest()); var firstInventoryRead = readArtifactInventoryOverMtls(selectedFreezeService, firstFreeze, pki); assertThat(firstInventoryRead.canonicalBytes()) @@ -680,6 +695,104 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() .isEqualTo(retained.selectorReceipt().canonicalBytes()); assertThat(client.read(request).canonicalBytes()) .isEqualTo(evidence.canonicalBytes()); + var inventoryEvidence = + WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + publicationOrder, + evidence, + inventory.publicCanonicalBytes(), + inventory.publicDigest()); + var publicationOperation = + new GameDesignPublicationOperationBinding( + publicationOrder, evidence, inventoryEvidence); + assertThat(publicationOperation.inventory().canonicalBytes()) + .containsExactly(inventory.publicCanonicalBytes()); + String privateInventoryJson = + new String(inventory.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + assertThat(privateInventoryJson) + .contains( + "\"sourceIntake\"", + "\"localTenantKey\"", + "\"localVersionKey\"", + "\"gameDesignVersionId\"", + "\"canonicalBindingBytes\""); + assertThat(publicInventoryJson) + .doesNotContain( + "sourceIntake", + "localTenantKey", + "localVersionKey", + "gameDesignVersionId", + "canonicalBindingBytes", + "sourceGameRowId"); + var ownerBeforeInventoryOperation = ownerSnapshot(world, plan); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT world_require_publication_operation_account_binding(?,?,?)", + publicationOperation.canonicalBytes(), + evidence.request().publicationFence(), + evidence.canonicalBytes()), + "World publication operation guard returned no result") + .get(0, Boolean.class)) + .isTrue(); + String sourceGraphDigest = inventory.publicEvidence().sourceModel().graphDigest(); + byte[] substitutedInventory = + publicInventoryJson + .replace( + "\"graphDigest\":\"" + sourceGraphDigest + "\"", + "\"graphDigest\":\"sha256:" + "0".repeat(64) + "\"") + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] validOperation = publicationOperation.canonicalBytes(); + byte[] missingInventory = + operationBytes( + GameDesignPublicationOperationBinding.SCHEMA, + publicationOrder.canonicalBytes(), + evidence.canonicalBytes(), + new byte[0], + DraftAuthorizationFenceBinding.digest(new byte[0])); + byte[] mismatchedDigest = + operationBytes( + GameDesignPublicationOperationBinding.SCHEMA, + publicationOrder.canonicalBytes(), + evidence.canonicalBytes(), + inventory.publicCanonicalBytes(), + "sha256:" + "0".repeat(64)); + byte[] changedInventory = + operationBytes( + GameDesignPublicationOperationBinding.SCHEMA, + publicationOrder.canonicalBytes(), + evidence.canonicalBytes(), + substitutedInventory, + DraftAuthorizationFenceBinding.digest(substitutedInventory)); + byte[] retainedV1 = + operationBytes( + "game-design-publication-operation/v1", + publicationOrder.canonicalBytes(), + evidence.canonicalBytes(), + null, + null); + byte[] trailingOperation = Arrays.copyOf(validOperation, validOperation.length + 1); + for (byte[] rejectedOperation : + List.of( + missingInventory, + mismatchedDigest, + changedInventory, + retainedV1, + trailingOperation)) { + assertThatThrownBy( + () -> + dsl.fetchOne( + "SELECT world_require_publication_operation_account_binding(?,?,?)", + rejectedOperation, + evidence.request().publicationFence(), + evidence.canonicalBytes())) + .satisfies(failure -> assertSqlState(failure, "23514")); + assertThat(ownerSnapshot(world, plan)).isEqualTo(ownerBeforeInventoryOperation); + } + assertThat( + inventoryRepository + .readCommitted(frozenAttempt, publicationOrder) + .canonicalBytes()) + .containsExactly(inventory.canonicalBytes()); } // Trusted CA alone is not authority: the World workload cannot read the GD-only // selector. @@ -800,6 +913,19 @@ void committedUnqualifiedAttemptCannotBeLateQualified() throws Exception { } } + private static byte[] operationBytes( + String schema, byte[] accountBytes, byte[] worldBytes, byte[] inventoryBytes, String digest) { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, schema); + DraftAuthorizationFenceBinding.frame(out, accountBytes); + DraftAuthorizationFenceBinding.frame(out, worldBytes); + if (schema.equals(GameDesignPublicationOperationBinding.SCHEMA)) { + DraftAuthorizationFenceBinding.frame(out, inventoryBytes); + DraftAuthorizationFenceBinding.frame(out, digest); + } + return out.toByteArray(); + } + private static void assertSqlState(Throwable failure, String expectedState) { String sqlState = null; for (Throwable cause = failure; cause != null; cause = cause.getCause()) { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index fbe556b229..e70380eb86 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -28,6 +28,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; @@ -43,6 +44,7 @@ import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; @@ -1415,6 +1417,9 @@ private WorldCanonicalInstanceTopologyPlan frozenPlan(Fixture fixture) { + ":publish-request:" + publicationRequest); var attemptCreatedInTransaction = new AtomicBoolean(); + var capturedCheckpoint = + new AtomicReference< + WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint>(); var attempt = Objects.requireNonNull( ownerTransaction() @@ -1424,23 +1429,23 @@ private WorldCanonicalInstanceTopologyPlan frozenPlan(Fixture fixture) { publicationFence.claimFreeze( evidence, () -> { - var digest = - digestService.getDraftDesignDigest( - Long.toString( - fixture.source().receipt().localTenantKey()), - Long.toString( - fixture.versionIdentity().localVersionKey())); + var captured = + checkpointRepository().captureWithSource(evidence, draft); + capturedCheckpoint.set(captured); attemptCreatedInTransaction.set(true); - return new WorldDesignPublicationFenceEvidence.Checkpoint( - draft.binding().commitId().toString(), - digest.contentDigest(), - 3); + return captured.checkpoint(); }); new WorldSelectedDraftPublicationAuthorizationRepository(dsl) .retainOrRequireExact( frozenAttempt, accountBinding, attemptCreatedInTransaction.get()); + artifactInventoryRepository() + .retainOrRequireExact( + frozenAttempt, + accountBinding, + attemptCreatedInTransaction.get(), + capturedCheckpoint.get()); return frozenAttempt; }), "Synthetic frozen preparation fixture returned no publication checkpoint"); @@ -1539,6 +1544,27 @@ private WorldCanonicalFrozenTopologyRepository frozenRepository() { digestService); } + private WorldSelectedDraftPublicationCheckpointRepository checkpointRepository() { + return new WorldSelectedDraftPublicationCheckpointRepository( + publicationFence, + appliedRepository(), + new WorldDraftTopologyCommitRepository(dsl, publicationFence, objectMapper), + digestService); + } + + private WorldSelectedPublicationArtifactInventoryRepository artifactInventoryRepository() { + return new WorldSelectedPublicationArtifactInventoryRepository(dsl); + } + + private WorldSelectedPublicationArtifactInventoryEvidence retainedInventoryEvidence( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + var attempt = + publicationFence.readAttemptByFence(world.request().publicationFence()).orElseThrow(); + var retained = artifactInventoryRepository().readCommitted(attempt, account); + return WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + account, world, retained.publicCanonicalBytes(), retained.publicDigest()); + } + private WorldPublishedStartLocationRepository publishedSelectors() { return new WorldPublishedStartLocationRepository(dsl, frozenRepository(), appliedRepository()); } @@ -1622,7 +1648,9 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( var account = isolatedPublicationAccountBinding( world.originalAccountBindingBytes(), selection, world.request().publicationRequestId()); - var operation = new GameDesignPublicationOperationBinding(account, world); + var operation = + new GameDesignPublicationOperationBinding( + account, world, retainedInventoryEvidence(account, world)); return new GameDesignPublicationTerminalEvidence( operation.canonicalBytes(), Outcome.PUBLISHED, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 0bc4dce528..3b0366855e 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -71,6 +71,7 @@ import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; @@ -957,7 +958,11 @@ void worldTerminalReadUsesIndependentQualifiedOwnerAndRequiredMtls() throws Exce new byte[] {2})))); for (AccountPublicationAuthorizationBinding changedAccount : changedAccounts) { var changedOperation = - new GameDesignPublicationOperationBinding(changedAccount, originalOperation.world()); + new GameDesignPublicationOperationBinding( + changedAccount, + originalOperation.world(), + net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures.stipulated( + changedAccount, originalOperation.world())); var changedTerminal = outcome == Outcome.PUBLISHED ? new GameDesignPublicationTerminalEvidence( @@ -1078,7 +1083,12 @@ void terminalSqlRejectsMalformedOversizedAndTrailingOperationFrames() { private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( GameDesignPublicationTerminalEvidence original, AccountPublicationAuthorizationBinding account) { - var operation = new GameDesignPublicationOperationBinding(account, original.worldEvidence()); + var operation = + new GameDesignPublicationOperationBinding( + account, + original.worldEvidence(), + net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures.stipulated( + account, original.worldEvidence())); return new GameDesignPublicationTerminalEvidence( operation.canonicalBytes(), original.outcome(), @@ -4478,7 +4488,9 @@ private GameDesignPublicationTerminalEvidence isolatedTerminalEvidence( var account = isolatedPublicationAccountBinding( world.originalAccountBindingBytes(), selection, world.request().publicationRequestId()); - var operation = new GameDesignPublicationOperationBinding(account, world); + var operation = + new GameDesignPublicationOperationBinding( + account, world, retainedInventoryEvidence(account, world)); return new GameDesignPublicationTerminalEvidence( operation.canonicalBytes(), Outcome.PUBLISHED, @@ -5611,6 +5623,23 @@ private WorldCanonicalFrozenTopologyRepository frozenRepository() { return new WorldCanonicalFrozenTopologyRepository(dsl, snapshots, repository(), digestService); } + private WorldSelectedDraftPublicationCheckpointRepository checkpointRepository() { + return new WorldSelectedDraftPublicationCheckpointRepository( + fence, appliedRepository(), repository(), digestService); + } + + private WorldSelectedPublicationArtifactInventoryRepository artifactInventoryRepository() { + return new WorldSelectedPublicationArtifactInventoryRepository(dsl); + } + + private WorldSelectedPublicationArtifactInventoryEvidence retainedInventoryEvidence( + AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world) { + var attempt = fence.readAttemptByFence(world.request().publicationFence()).orElseThrow(); + var retained = artifactInventoryRepository().readCommitted(attempt, account); + return WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + account, world, retained.publicCanonicalBytes(), retained.publicDigest()); + } + private WorldPublishedStartLocationRepository publishedSelectors() { return new WorldPublishedStartLocationRepository(dsl, frozenRepository(), appliedRepository()); } @@ -5655,6 +5684,9 @@ private WorldCanonicalFrozenTopology capture( 1, "publish:" + owner.canonicalTenantId() + ":publish-request:" + publicationRequest); var attemptCreatedInTransaction = new AtomicBoolean(); + var capturedCheckpoint = + new java.util.concurrent.atomic.AtomicReference< + WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint>(); var attempt = Objects.requireNonNull( ownerTransaction() @@ -5664,6 +5696,13 @@ private WorldCanonicalFrozenTopology capture( fence.claimFreeze( evidence, () -> { + if (accountBinding != null) { + var captured = + checkpointRepository().captureWithSource(evidence, plan); + capturedCheckpoint.set(captured); + attemptCreatedInTransaction.set(true); + return captured.checkpoint(); + } var identity = Objects.requireNonNull( dsl.fetchOne( @@ -5683,6 +5722,12 @@ private WorldCanonicalFrozenTopology capture( new WorldSelectedDraftPublicationAuthorizationRepository(dsl) .retainOrRequireExact( frozenAttempt, accountBinding, attemptCreatedInTransaction.get()); + artifactInventoryRepository() + .retainOrRequireExact( + frozenAttempt, + accountBinding, + attemptCreatedInTransaction.get(), + capturedCheckpoint.get()); } return frozenAttempt; })); diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java index dc249c13f2..1cbc2bbd0a 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java @@ -54,6 +54,7 @@ import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; import net.firedevops.firemud.gamedesign.v1.ReadPublicationTerminalResponse; +import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -304,7 +305,8 @@ private static GameDesignPublicationOperationBinding operation() throws Exceptio Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()), applied.fullBinding(), applied.result()); - return new GameDesignPublicationOperationBinding(account, world); + return new GameDesignPublicationOperationBinding( + account, world, IsolatedWorldPublicationInventoryFixtures.stipulated(account, world)); } private static GameDesignPublicationTerminalEvidence terminal( From 64c3d8db0ae1b302f8ae7e48e991d5b2ceb39fc6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:11:41 +1300 Subject: [PATCH 039/129] Retain typed gameplay-rule source evidence and correct inventory guards --- .../account-service/api-contracts.md | 6 +- .../ability-action-tools.md | 36 +- .../game-logic-service/api-contracts.md | 2 +- .../game-logic-service/runtime-and-data.md | 8 +- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 10 +- .../v1/draft_commit_order_service.proto | 4 +- .../v1/game_logic_intake_authorization.proto | 21 + .../v1/gameplay_rule_source_service.proto | 22 + ...ccountDraftCommitOrderReadGrpcService.java | 15 +- .../AccountDraftCommitOrderReadService.java | 33 +- .../DraftAuthorizationFenceRepository.java | 41 +- ...gicIntakeAuthorizationReadGrpcService.java | 55 + ...meLogicIntakeAuthorizationReadService.java | 62 + ...ameLogicIntakeAuthorizationRepository.java | 182 +++ ...ntGameLogicIntakeAuthorizationService.java | 79 ++ .../V109__game_logic_intake_authorization.sql | 175 +++ .../V110__selected_inventory_empty_arrays.sql | 34 + ...ommitOrderReadPostgresIntegrationTest.java | 153 ++- ...eAuthorizationPostgresIntegrationTest.java | 353 +++++ ...nAuthorizationPostgresIntegrationTest.java | 165 +++ ...countDraftCommitOrderReadGrpcMtlsTest.java | 60 +- ...ntDraftCommitOrderReadGrpcServiceTest.java | 62 +- ...ccountDraftCommitOrderReadServiceTest.java | 147 ++- ...ntakeAuthorizationReadGrpcServiceTest.java | 62 + .../GameLogicIntakeAuthorizationBinding.java | 107 ++ ...ameLogicIntakeAuthorizationReadClient.java | 156 +++ ...eLogicIntakeAuthorizationReadEvidence.java | 30 + ...LogicIntakeAuthorizationReadGrpcCodec.java | 59 + .../gamelogic/GameplayRuleManifest.java | 1160 +++++++++++++++++ .../gamelogic/GameplayRuleSelectedSource.java | 106 ++ .../GameplayRuleSourceReadClient.java | 156 +++ .../GameplayRuleSourceReadEvidence.java | 33 + .../GameplayRuleSourceReadGrpcCodec.java | 58 + .../gamelogic/GameplayRuleSourceRevision.java | 23 + .../GameplayRuleSelectedSourceTest.java | 181 +++ .../gamedesign/publication/AssetSource.java | 4 +- .../gamedesign/publication/CommandSource.java | 6 +- .../publication/CommandSourceRepository.java | 6 +- ...signGameplayRuleSourceReadGrpcService.java | 59 + ...meDesignGameplayRuleSourceReadService.java | 66 + .../GameDesignSourceRepository.java | 96 +- .../publication/GameplayRuleSnapshot.java | 185 +++ .../publication/GameplayRuleSource.java | 212 +++ .../GameplayRuleSourceRepository.java | 433 ++++++ .../publication/RealmPolicySource.java | 4 +- .../service/impl/RevisionServiceImpl.java | 4 + .../migration/V57__gameplay_rule_source.sql | 400 ++++++ ...setPublicationPostgresIntegrationTest.java | 407 +++++- ...emptServiceTransactionIntegrationTest.java | 42 +- ...GameplayRuleSourceReadGrpcServiceTest.java | 61 + ...signGameplayRuleSourceReadServiceTest.java | 78 ++ .../publication/GameplayRuleSourceTest.java | 376 ++++++ .../service/impl/RevisionServiceImplTest.java | 29 + services/game-logic-service/build.gradle.kts | 6 + .../GameLogicGameplayRuleIntakeOperation.java | 50 + ...GameLogicGameplayRuleIntakeRepository.java | 108 ++ .../GameLogicGameplayRuleIntakeService.java | 196 +++ .../GameLogicGameplayRuleIntakeTerminal.java | 159 +++ ..._immutable_gameplay_rule_source_intake.sql | 52 + ...playRuleIntakePostgresIntegrationTest.java | 270 ++++ ...ameLogicGameplayRuleIntakeServiceTest.java | 432 ++++++ ...WorldDesignPublicationFenceRepository.java | 9 +- ...nceAssociationPostgresIntegrationTest.java | 5 +- ...signPublicationFenceCommittedReadTest.java | 106 ++ 65 files changed, 7585 insertions(+), 138 deletions(-) create mode 100644 protos/account/v1/game_logic_intake_authorization.proto create mode 100644 protos/game-design/v1/gameplay_rule_source_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java create mode 100644 services/account-service/src/main/resources/db/migration/V109__game_logic_intake_authorization.sql create mode 100644 services/account-service/src/main/resources/db/migration/V110__selected_inventory_empty_arrays.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceRevision.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSnapshot.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSource.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V57__gameplay_rule_source.sql create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeOperation.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminal.java create mode 100644 services/game-logic-service/src/main/resources/db/migration/V2__immutable_gameplay_rule_source_intake.sql create mode 100644 services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java create mode 100644 services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 0d441a20d2..3f671a28d8 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -62,7 +62,7 @@ Current explicit JOIN status: the local `/auth/bootstrap/join` controller and op Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. -Bounded hosted Creator Party, terms-catalog, acceptance/currentness and environment-binding owner storage exists, but no registered hosted-terms API or complete creator-authorized commit path is enabled. The unregistered backend control-ui construction adds primary-authenticated issuance, exact protected recovery and a current-actor Draft ordering entry for one existing initial creator; neither that entry nor the standalone World-only held-order read enables a public route or supplies an authenticated end-to-end World commit by itself. Deadline-qualified authorizations remain denied without physical commit enforcement. The [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md) records the implemented boundary and remaining proof. Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. +Bounded hosted Creator Party, terms-catalog, acceptance/currentness and environment-binding owner storage exists, but no registered hosted-terms API or complete creator-authorized commit path is enabled. The unregistered backend control-ui construction adds primary-authenticated issuance, exact protected recovery and a current-actor Draft ordering entry for one existing initial creator; neither that entry nor the standalone held-order read enables a public route or supplies an authenticated end-to-end commit by itself. `ReadHeldOriginalCommitOrder` accepts exact same-namespace World, and same-namespace Game Logic only when the canonical original binding's required-owner vector includes `GAME_LOGIC`; it reads the retained original bytes, order and pending settlement in an independent Account transaction and grants no order-creation or settlement authority. Deadline-qualified authorizations remain denied without physical commit enforcement. The [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md) records the implemented boundary and remaining proof. Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. @@ -88,6 +88,10 @@ The selected-order composition authenticates the exact same-namespace Game Desig The standalone, unregistered [`AccountSelectedPublicationOrderService.AuthorizeSelectedPublication`](../../../../protos/account/v1/selected_publication_order_service.proto) producer accepts schema version 1, the exact target namespace, a fresh nonzero transport correlation UUID and complete canonical selected-Draft bytes. The unchanged original creator credential travels only in protected, method-specific per-call metadata, never in protobuf request or response text; metadata must not be logged. Only the verified same-namespace Game Design workload may call it; Account authenticates before accessing or decoding credential metadata, decoding the request or capturing authority, and World has no producer permission. The receiver binds its credential interceptor internally; missing, duplicate, malformed or oversized credentials deny without owner mutation. Account captures its current environment boundary internally and validates it through the existing owner transaction; no caller-supplied environment or currentness value is authority. The response echoes the complete non-secret request tuple and exact canonical Account authorization binding, never the credential. Transport correlation does not change the durable publication identity: retry retains the original order, source evidence and fence. Unknown or noncanonical fields, changed response correlation or selection, unavailable currentness and substituted server identity fail closed. Calls require file-backed mutual TLS with exact Account server identity, a bounded five-second deadline and no ambient SQL transaction. Future registration must account for the transport metadata budget; a lower server limit still fails closed rather than truncating credentials. This transport defines no runtime registration or production environment-authority provider. +Game Logic's [selected-release source intake](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) uses a distinct Account authorization, not an original Draft or publication order. After the original authored Draft is synchronized and its Account operation has committed settlement, Account obtains the exact complete immutable Game Design source over its authenticated owner read outside SQL. Account's existing current-creator transaction then binds the stable intake request, acting account, canonical target, unchanged selected commit and source bytes/digest, complete current source vector and a distinct operation/fence; it retains full source participation atomically. Exact retries preserve that original order; changed source or actor evidence cannot reuse the request identity. This neither changes the original Draft's participant vector nor advances its commit to manufacture Game Logic participation. + +Only the verified same-namespace Game Logic workload may call [`ReadHeldGameLogicIntakeAuthorization`](../../../../protos/account/v1/game_logic_intake_authorization.proto). Its complete request and original authorization bytes/digest must match the retained order. A `HELD` read does not grant fresh creator authority or establish completed intake. Applicable source changes and elective deadline disclosure remain blocked until Account verifies an authenticated exact Game Logic retention or definitive-abort terminal and commits settlement for this same operation. Absence, timeout or ambiguous outcome cannot release participation, and a definitive abort must exclude later retention. Owner reads run outside SQL; settlement uses the existing sorted source-lock ordering and exact immutable readback. The current unregistered construction has no settlement writer, so its orders remain pending; implementation and proof limits belong in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. diff --git a/design/architecture/microservices/game-design-service/ability-action-tools.md b/design/architecture/microservices/game-design-service/ability-action-tools.md index 916d3292bc..9d91aab0bb 100644 --- a/design/architecture/microservices/game-design-service/ability-action-tools.md +++ b/design/architecture/microservices/game-design-service/ability-action-tools.md @@ -8,7 +8,7 @@ The publish workflow is part of the durable control-plane workflow described in The current proven behavior is stable-reference validation against the exact published base version for the plugin publication path. `abilitySchemaDigest` is persisted in plugin metadata and exposed by the publication read, but dedicated Game Logic-owned release-attested ability-schema validation remains target-state and unproved. Current plugin publication and activation compare the plugin's `abilitySchemaDigest` with the published `AUTOMATION_SCRIPTING` aggregate participant digest; that aggregate comparison is not a dedicated ability-schema attestation. Script-patch publication does not currently enforce same-tenant published-base identity, and launch resolution does not currently prove same-base published patch identity or Automation `READY`; those are implementation gaps. Exact `scriptPinEpoch` propagation and same-version old-epoch rejection at runtime handoff are target-state and remain unproved; this design-time editor does not establish that runtime proof. See the [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#script-transition-reconciliation) and [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). -The current `SaveRevision` API in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto) stores revision data; its supported `COMMAND_DEFINITION` shape and selected command-source capture do not implement the complete ability/action catalogs, policies or targeting declarations below. In particular, its existing `actionTags` are not the dedicated `admissionTags` contract. An authenticated Game Design source producer, Game Logic retained manifest and exact source-operation readback remain absent; missing storage or unsupported declarations cannot establish an empty rule set. `PublishVersion` must consume the independently retained owner evidence rather than populate Game Logic through the digest read. +The current `SaveRevision` API in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto) stores revision data; its supported `COMMAND_DEFINITION` shape and selected command-source capture do not implement the complete ability/action catalogs, policies or targeting declarations below. In particular, its existing `actionTags` are not the dedicated `admissionTags` contract. The construction includes a separate typed `GAMEPLAY_RULE` source, actual fresh-Version inventory creation, coordinated UPSERT/DELETE history and immutable synchronized snapshots. These components do not establish a registered authenticated authoring ingress or complete Game Logic intake. Generic `SaveRevision` rejects `GAMEPLAY_RULE` rather than bypassing the authorized coordinator. Any retained generic `GAMEPLAY_RULE` rows for that exact tenant/version, or nonempty legacy effective `COMMAND_DEFINITION` inventory, deny the new complete-source handoff until explicitly reconciled. Missing storage or unsupported declarations cannot establish an empty rule set. `PublishVersion` must consume independently retained owner evidence rather than populate Game Logic through the digest read. Ability definitions use a structured schema delivered through the API. @@ -16,6 +16,40 @@ Game creators build complex combat systems without modifying the core engine. Al The web-based editor described in [Web-Based Visual Design Interface](web-visual-interface.md) serves as the front end for these tools. +## Selected Rule-Source Authoring Schema + +`gameplay-rule-manifest/v1` is the closed declaration grammar for selected-source production. Its root has exactly `schema` and `families`. The inventory contains an explicit array for each family below, including empty arrays. An omitted family is invalid. Each definition uses its typed logical key; display names and private database keys are never substitutes. + +| Family | Typed definition members | +| --- | --- | +| `STATS` | `statKey`, `primitiveKind` (`NUMERIC` or `BOOLEAN_FLAG`), `baseValue`, `flagValue`, `minimum`, `maximum`, `visibility`, `tags` | +| `RESOURCES` | `statKey`, `defaultCurrent`, `minimum`, `defaultMaximum`, `hardMaximum`, `visibility`, `tags`; this is the `BOUNDED_RESOURCE` primitive | +| `CONDITIONS` | `conditionKey`, `reapplication`, `durationPolicy`, `durationTicks`, `maximumStacks`, `visibility`, `tags`, ordered `effectKeys`, `removalPriority` | +| `EFFECTS` | `effectKey`, `lifecycle`, `operation`, `statKey`, `statField`, `amount`, `conditionKey`, `capacityChangePolicy` | +| `ABILITIES` | `abilityId`, `name`, `actionSequenceId` | +| `ACTIONS` | `actionSequenceId`, `name`, ordered `admissionTags`, `targetSets`, `costs`, `cooldowns`, `effects`, `feedbackKeys` | +| `COMMANDS` | `commandId`, `actionSequenceId`, `semanticOwner`, `executionDiscipline`, `stageRequirement`, `promptPolicy`, `actionCategory`, `historyRecordable`, `aliases`, `actionTags`, ordered `admissionTags` | +| `ADMISSION_TAGS` | `tagKey` | +| `DISPOSITIONS` | `dispositionKey`, `deniedAdmissionTags`, `safeFeedbackKey` | +| `CONTINUOUS_OVERLAYS` | `overlayKey`, `eligibleWhen`, `deniedAdmissionTags`, ordered `effectKeys` | +| `OBSERVATION_POLICIES` | `observationPolicyKey`, `observableWhen` | +| `TARGETING_POLICIES` | `targetingPolicyKey`, `candidateSelector`, `observationPolicyKey`, `eligibleWhen`, `safeFailureFeedbackKey` | +| `SELECTION_POLICIES` | `targetSelectionPolicyKey`, `cardinality`, `minTargets`, `maxTargets`, `strategy`, `truncationStrategy`, ordered `comparators` | +| `DEFAULT_BINDINGS` | `bindingKey`, ordered `targetSets` | +| `FEEDBACK` | `feedbackKey`, `outcomeEvent`, `audience`, `messageKey`, `messageTemplate`, ordered `arguments`, `visibility`, `replayPolicy` | + +All members are explicit. A member inapplicable to a discriminated declaration is JSON `null`, not an inferred semantic default. A numeric stat requires `baseValue` and may declare bounds; a boolean stat requires `flagValue` and forbids numeric fields. Resource bounds and current values must agree. `maximumStacks` is required only for `STACK`; the supported condition duration is an explicit positive tick count. Numeric values must survive RFC 8785 canonicalization without precision loss, and tick counts are positive integers no greater than `9007199254740991`. + +An action target set contains `targetSetKey`, `targetingPolicyKey`, `targetSelectionPolicyKey`, `required`, `unresolvedFeedbackKey` and `playerSelectorInputSlot`. `SOURCE` is implicit and cannot be declared again. Optional target sets require an authored unresolved feedback key. A player-selection strategy, including a truncation strategy, requires its declared input slot. Each action effect binds `effectKey` to an existing `targetSetKey` or `SOURCE`. A cost contains `statKey`, `amount` and `commitPolicy`; a cooldown contains `cooldownKey`, `durationTicks` and `commitPolicy`. A ranking comparator contains `statKey`, `statField` and `direction`. A feedback argument contains `key` and `kind` (`TEXT`, `NUMBER`, `BOOLEAN` or `ACTOR_ID`). These collections retain author declaration order; definition replacement retains its position and explicit deletion followed by recreation appends it within that family. + +The initial retained effect grammar supports the already declared `CONTINUOUS` numeric modifiers `ADD`, `MULTIPLY`, `CLAMP_MIN` and `CLAMP_MAX` on `VALUE` or a resource's typed `MAXIMUM`, plus `INSTANT` `ADJUST_RESOURCE`, exact-key `APPLY_CONDITION` and exact-key `REMOVE_CONDITION`. Maximum modifiers may declare the capacity policy described below. Actions reference only instant effects; continuous overlays reference only continuous effects. The narrower source grammar does not infer tag/source condition-removal selectors, granted state, damage, disposition transitions or other unimplemented extensions. Such declarations deny this schema until explicitly supported. + +Predicates contain `kind`, `actor`, `factKey`, `comparison`, `number` and ordered `operands`. The supported kinds are explicit `TRUE`/`FALSE`, bounded `ALL`/`ANY`/`NOT`, numeric `STAT_COMPARE`, `CONDITION_PRESENT` and `DISPOSITION_EQUALS`, using `SOURCE` or `TARGET` and declared actor catalog keys. Numeric comparisons are `EQ`, `NE`, `LT`, `LE`, `GT` and `GE`; boolean compositions have at most 64 direct operands and 32 nesting levels. These are declarations of existing actor facts, not authorization for arbitrary owner reads. Actor-tag predicates, relationship/spatial predicates and undeclared primitive kinds remain rejected until their exact typed fact-owner contract is registered. Intrinsic catalog tags remain authored metadata and never become dedicated admission tags implicitly. + +Every reference resolves against the complete atomic post-mutation inventory. Unknown members, unknown kinds, duplicate keys, stale references and invalid lifecycle or selector combinations deny; no unsupported input is removed to manufacture a complete set. `GameplayRuleManifest` is the shared codec for this owner-defined grammar, not mutation authorization or a Game Logic receipt. + +Game Design retains `GAMEPLAY_RULE` UPSERT/DELETE revisions under the existing coordinator. The complete affected tuple is its canonical tenant/version, `GAME_DESIGN_CONTROL_PLANE`, aggregate and scope type `GAMEPLAY_RULE_SET`, aggregate ID equal to the canonical version UUID, scope ID `effective`, and the original expected source epoch. All rule revisions in the commit share that atomic catalog epoch. Fresh genesis writes every explicit empty family only inside the actual new full-Draft Version insertion transaction; retained versions receive no backfill. Synchronized snapshots retain the exact original creating revisions and inherited commit, and become visible only with the same complete coordinator result. This authored source epoch is separate from a later Game Logic intake-operation identity. + ## Canonical Ability References Published ability and action references use stable design identifiers, not display names. Ability definitions must expose an `abilityId` stable within `(tenantId, versionId)`, and action sequences must expose an `actionSequenceId` stable within the same scope. Designer-facing names may change across revisions, but scripts, plugins, and validation records must store the stable identifiers. diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md index 1c9ef57cab..73a11b4ff1 100644 --- a/design/architecture/microservices/game-logic-service/api-contracts.md +++ b/design/architecture/microservices/game-logic-service/api-contracts.md @@ -6,7 +6,7 @@ This document defines the Game Logic Service REST and gRPC surfaces, exposure cl - The current Game Logic adapters still return `shared.v1.ErrorDetail` for many failures and record `grpc.app_error`; that is implementation drift and a migration/proof gap, not a second contract. - Causal-read status is target-only: the complete `CausalReadFence` and participant-proof enforcement described below are not current behavior. The live `ResolveLook` request/proto and World/Entity adapters remain floor-free, so protobuf propagation, adapter evidence, and focused causal-floor proof are implementation gaps. -- The publish-gate digest handler enforces the distinct workload/method authorization and exact Game Design publication binding implemented by `PublicationReadGuard` and `PublicationDigestRequestBinding` (tenant, version scope, stable publish request, derived workflow identity, and request digest), with focused denial and response-scope checks. For a full-version request, the owner digest fails closed because Game Logic has no owner-local manifest and provenance sufficient to attest the version's rule inputs; it does not attest those inputs as an empty manifest. End-to-end full-version publication therefore remains blocked. The target workload, tenant/scope/request/workflow/digest context, exact response identity comparison, and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). +- The publish-gate digest handler enforces the distinct workload/method authorization and exact Game Design publication binding implemented by `PublicationReadGuard` and `PublicationDigestRequestBinding` (tenant, version scope, stable publish request, derived workflow identity, and request digest), with focused denial and response-scope checks. For a full-version request, the owner digest remains fail closed until the separate authenticated intake, exact terminal settlement and selected-manifest lookup are proved; it does not attest missing inputs as an empty manifest. End-to-end full-version publication therefore remains blocked. The [runtime owner](runtime-and-data.md#implementation-status) links current construction and proof limits. The target workload, tenant/scope/request/workflow/digest context, exact response identity comparison, and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). ### Player execution context diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index c7c702132f..bf09f22b9c 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -6,14 +6,14 @@ This document defines the Game Logic Service runtime model, dependency ownership The sections below define the target-state runtime contract. Current implementation and proof status is: -- Full-version digest reads fail closed because Game Logic lacks the retained selected-release manifest and source-operation provenance needed to attest the selected version's rule inputs. It does not return an empty-manifest attestation or infer an empty authored set from absent storage. The [API implementation status](api-contracts.md#implementation-status) records this publication prerequisite; the Draft digest contract below defines the required owner boundary, not completed producer or intake proof. Runtime activation remains unavailable until publication carries the required release attestation. +- Full-version digest reads remain fail closed: the bounded owner-local source-intake construction does not yet establish the complete authenticated producer, terminal settlement and selected-manifest lookup needed for attestation. It does not return an empty-manifest attestation or infer an empty authored set from absent storage. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) owns construction and proof status; the Draft digest contract below is not a claim of completed producer or intake proof. Runtime activation remains unavailable until publication carries the required release attestation. - Same-type Game Logic takeover behind an existing edge connection is target behavior, but suppression of a client-visible reconnect after an ordinary qualifying Game Logic restart remains implementation or proof debt under ADR 0013. - Target: `SendCommunication` and every other player-delegated gameplay RPC propagate one complete, validated typed `PlayerExecutionContext` from Game Session through Game Logic and onward. Game Logic validates the context against request and owner evidence, never treats caller-supplied identifiers as authority, remains stateless, and owns semantic gameplay outcomes; Game Session owns session, reconnect, and presentation state. This is the ADR 0024 target contract. - Current implementation gap: the live `SendCommunicationRequest` is still a flat schema with tenant/session/character/account, communication/text and target metadata, room, game-instance, speaker, and effect fields plus legacy `session_attestation`; its current proto does not carry typed `playableStateNamespaceId`, `playableStateScope`, region/epoch, pointer, or admitted-bundle fields. Complete typed-context propagation is therefore not current behavior or proof. ## Runtime Notes -- Stateless service accessed over gRPC by other microservices. +- Stateless gameplay execution accessed over gRPC by other microservices; immutable authored-source intake evidence is durable owner storage, not process-local player or session state. - No authoritative gameplay state may exist only in Game Logic process memory. Any state that must survive instance loss belongs in authoritative domain services, durable ledgers, or Game Session-owned coordination, so another Game Logic instance can take over immediately. - Same-type Game Logic instances must be freely replaceable behind the current caller connection. Meaningful gameplay state needed after a non-edge restart must be reconstructed from authoritative service APIs and Game Session-provided tick/session context rather than preserved only in local memory. - Uses a modular command parser for extensibility. The text protocol's system commands such as `LOGIN`, `LOGON`, and `PING` are interpreted and completed by Game Session; this service focuses on gameplay commands only, as described in the [Game Session Service](../game-session-service/protocols.md#minimal-text-command-protocol). @@ -25,7 +25,7 @@ The sections below define the target-state runtime contract. Current implementat - The target runtime contract is that every player-delegated gameplay RPC carries the complete validated typed `PlayerExecutionContext`, including `tenantId`, `playableStateNamespaceId`, server-derived `playableStateScope`, active `gameInstanceId`, and applicable region/epoch or executor fences. The live per-RPC schemas, including `SendCommunication` and its legacy `session_attestation`, remain an implementation gap; see the [PlayerExecutionContext contract](../../system-architecture-authentication.md#gameplay-player-execution-context-contract-normative). - Gameplay gRPC requests do not include JWTs. Game Session provides player identity from Redis via `SessionContext`, may refresh a JWT from Account Service if roles change, and does not validate tokens for gameplay. Service-to-service traffic still uses mutual TLS as described in the [Security Architecture](../../system-architecture-security.md). - Utilizes the [Shared Libraries](../../system-architecture-shared-libraries.md) for DTO definitions, logging interceptors, and Micrometer metrics. -- Flyway is enabled for consistency with other services, but the initial migration is empty because no tables are required. +- Flyway preserves the empty initial migration and adds owner-local immutable source-intake storage separately; this does not introduce authoritative player or session state here. - NPC morale and aggression-state evaluation remain part of this service's runtime behavior. When gameplay rules consume faction or reputation signals sourced from Social & Groups, the local morale logic is still owned here, including transitions such as `FLEEING` and `SURRENDERED`; cross-service reputation data informs the decision, but Game Logic owns the gameplay-state consequence. ## Workflow Participation @@ -55,6 +55,8 @@ The retained input set must be complete for the supported command inputs effecti Intake is a separate, mutation-authorized source operation. `GetDraftDesignDigest` remains a read-only full-version publication read over the already retained, exact-version evidence; it does not populate or repair that evidence. An empty selected input set is attestable only when an authenticated source operation proves the complete owner inventory for the exact selected commit is empty. Missing storage, a missing producer, or absent rows are not evidence of an empty authored set. +The original Game Design author operation settles before this intake. Game Logic obtains the complete synchronized source from Game Design's authenticated exact-commit owner read and verifies a distinct [Account intake authorization](../account-service/api-contracts.md#grpc-apis) for that same immutable source. It does not retrospectively join the original Draft's participant vector or allocate another selected commit. Account source participation remains held through Game Logic's local commit and exact terminal settlement; a remote `HELD` sample alone is insufficient. Retained source, complete manifest/provenance and the immutable intake result commit atomically. A definitive abort uses the same operation serialization and prevents later retention; missing rows or expired waits do not prove abort. Identical recovery returns the original result, never a latest source or replacement manifest. These obligations do not make Game Logic a publication-workflow mutation participant. + The authenticated publication read must preserve the exact source-operation and selected-commit correlation through its retained-manifest lookup and readback. Validating the publication request and then resolving content by tenant/version alone is insufficient when it can select a different source operation; neither a latest lookup nor request authentication repairs missing immutable provenance. The full-version manifest and the dedicated `abilitySchemaDigest` share the selected commit and Game Logic's existing canonicalization and `digestSchemaVersion` contract, but they attest distinct scopes. The aggregate full-manifest `contentDigest` is not an ability-schema digest, and neither the Automation & Scripting digest nor Game Design's control-plane digest substitutes for either Game Logic attestation. Any change to the dedicated ability-schema input set or its canonicalization requires the same explicit schema bump and digest replay or re-record process as other manifest changes. This contract governs publication evidence only; it does not authorize activation of unpublished rules or make Game Logic a participant in Game Design's publication workflow mutations. Game Logic does not read an admin database for runtime rules. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a511692c77..6d3956cb6e 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -120,3 +120,9 @@ Entry format: - Observation: The target had advanced 21 commits beyond the recorded base, accounting for 33 extra paths in the merge tree, with no Account, Game Design or World owner paths. This explains the observed tree difference without proving each job's checkout from metadata alone. - Expected pattern: Distinguish recorded-base metadata, current target ref, merge-object ancestry and actual job checkout. Parent movement does not authorize topology changes or confer exact-integrated-base proof. - Current status: The completed observer verified Account, World, Game Design, Game Session and TCP job logs actually checked out synthetic merge `e2bdaf5`, with parents `fe15a31` and published `2560d12a`; intended-parent alignment remains a separate gate. + +- `2026-10-09`: Test strict committed reads through the actual Spring proxy + - Context: PR #3105's physical World inventory read failed because a `NOT_SUPPORTED` transaction annotation created an empty synchronization scope that the method's strict no-synchronization guard correctly rejected. + - Observation: Calling an unproxied repository directly did not reproduce the failure; a clean caller alone did not establish a clean invocation inside the proxy. + - Expected pattern: Exercise the real transaction proxy when proving an outside-SQL owner read. Preserve rejection of both ambient transactions and empty synchronization scopes rather than weakening the guard to accommodate its own annotation. + - Current status: The annotation was removed and a three-case proxy regression passed locally. Corrected-head PostgreSQL/transport execution remains required. 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 eff444a1e7..506156f2a6 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 @@ -8,7 +8,13 @@ This is a non-normative implementation tracker for game authoring, publishing, a The selected-release inventory contract is explicit in the [World owner](../../architecture/microservices/world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) and [Game Design asset owner](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). Construction includes World's immutable selected-graph inventory and authenticated read, plus Game Design's mandatory v2 retention of that inventory in the complete original publication operation. The unregistered first-admission path obtains authenticated Account, freeze, inventory and selector evidence outside SQL; local durable retries reuse their original bytes without those RPCs. Additive owner guards reject incomplete v1 inputs for new operations, captures, terminal outcomes and settlement; retained history is not rewritten. This is not a genuine complete producer-to-release-to-settlement handoff or activation. -Game Design's synchronized source repository covers commands, realm policy and ordinary `ASSET_REFERENCE` source history, with actual fresh-Version genesis, coordinator application, immutable selected-commit snapshots and export agreement. Total Game Design source completeness remains unimplemented: V37 mappings and nullable usage classifiers do not enumerate selected template/branding references or launch requiredness, and mutable template configuration is not selected-commit evidence. The [closed config contract](../../architecture/microservices/game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state) still needs its actual authorized versioned writers, normalized references, owner-qualified readback and inventory integration. Game Logic's complete authored-input producer/intake, exact requiredness authority, immutable manifest/export, registered ingress and composed proof remain open. Fresh command/policy/ordinary genesis, absent mappings or absent consumers cannot establish empty families. All four genuine Gameplay handoffs and runtime activation remain open obligations. +Game Design's synchronized source repository covers commands, realm policy and ordinary `ASSET_REFERENCE` source history, with actual fresh-Version genesis, coordinator application, immutable selected-commit snapshots and export agreement. The current V57 construction adds the closed `GAMEPLAY_RULE` authored family, exact original revisions, complete typed catalogs and immutable synchronized source snapshots; the actual authorized ingress/coordinator wiring, physical PostgreSQL and composed owner proof remain pending. Generic `SaveRevision` cannot stand in for that producer: it rejects new `GAMEPLAY_RULE` writes, and retained generic rule rows deny source completeness without guessed reconciliation. Total Game Design source completeness remains unimplemented: V37 mappings and nullable usage classifiers do not enumerate selected template/branding references or launch requiredness, and mutable template configuration is not selected-commit evidence. The [closed config contract](../../architecture/microservices/game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state) still needs its actual authorized versioned writers, normalized references, owner-qualified readback and inventory integration. Game Logic's separate immutable intake/terminal settlement, exact requiredness authority, manifest/export attestation, registered ingress and composed proof remain open. Fresh source genesis, absent mappings or absent consumers cannot establish empty families. All four genuine Gameplay handoffs and runtime activation remain open obligations. + +Published-head `fc07d1da90041e4e06d1814d11700c229b73143e` [Validation run 37862911308](https://github.com/benhook1013/FireMUD/actions/runs/37862911308) executed 245 Account, 89 Game Design and 206 World integration cases with zero skips or errors. Account had six failures, Game Design one and World 56. All 13 Game Design asset-source cases passed; its remaining negative-inventory case expected the wrong exception wrapper, and the local correction checks root SQLSTATE `23514` and each exact guard message. World exposed a committed-read annotation that itself created the synchronization scope rejected by its strict guard, plus opaque generator values in static-graph fixtures; bounded corrections and a Spring-proxy regression require corrected-head execution. Five Account settlement cases rejected explicit empty inventory arrays because of the V108 aggregate defect described below. The sixth reached V92's existing conservative global-WAL coverage denial: insert fence `0/5A76110` exceeds initial/final flush `0/5A760D0`; this proves unavailable coverage, not which transaction owns that tail, and does not authorize changing V92. V56/V108 migrations, Flyway sanity and the PostgreSQL runtime upgrade check passed. Synthetic merge `4b1de956cf2c4575b7bf2bc8617ee7bb33135bda`, tree `fa843c76b22fd6357fc103876dc29b009f8d7084`, has parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head, not the recorded integrated base as its first parent. This run gives no fresh-image boot, preview or Smoke proof, and excludes the subsequent V57/V109 construction. + +Follow-up adjudication traced the five Account inventory failures to V108's ordering aggregates: an explicit empty input array yields SQL `NULL` from `jsonb_agg`, not canonical `[]`. Additive V110 coalesces both region and spawn aggregates, retaining every other identity, shape and ordering guard; its focused direct-SQL definitions reject resealed unsorted inputs and preserve pending source holds. It also restores V93's 2048-character source-key capacity to selected-publication participation. Corrected-head PostgreSQL execution remains required. The separate V109 source-intake order and Game Logic V2 immutable terminal remain unregistered construction: Account and Game Design source reads in the Game Logic database definitions are stipulated upstream clients, not genuine composed authorization proof. Account terminal settlement and transport are still absent, so its source holds are never released by this slice and publication digest reads remain denied. + +The corrected construction passes local affected checks: R170 completed Common, Account, Game Design and World checks; R172 completed Game Logic's full check after its fixture/static corrections. All four service boot JARs, formatting, Checkstyle, SpotBugs and coverage passed. Actual unit results are 331 Common, 1085 Account, 399 Game Design, 101 Game Logic and 556 World cases, all without failures, errors or skips. Twelve non-PostgreSQL integration cases execute; 537 PostgreSQL definitions compile but skip without Docker (233 Account, 96 Game Design, 206 World and two Game Logic). Owner schema generation and Flyway sanity pass across 12 migration sets and 255 versioned files. These checks do not prove corrected physical migrations, genuine authenticated source production, composed owner settlement, fresh-image boot or Smoke. The scoped independent local source/intake review accepted a generic-rule completeness gap and an extra Account read peer; fail-closed corrections are integrated, while the actual authorized authoring producer remains open rather than being claimed complete by those denials. The v2 Common/Game Design local gate executed 328 Common and 390 Game Design unit cases without failures or skips; 88 Game Design PostgreSQL definitions compiled but skipped without Docker. Game Design V56 schema generation, formatting, static checks, coverage, boot jar, links and Markdown passed. Its additional direct-SQL historical-v1 policy-set denial and the separate Account V108/World V56 guard-and-fixture batch require the subsequent consolidated gate and physical execution. The inventory loopback endpoint in Game Design's composition test is explicitly stipulated upstream evidence, not execution of World's real inventory producer. @@ -38,7 +44,7 @@ The legacy World numeric mutation route lacks the target shared-lock handoff, bu The World selected-fresh-graph checkpoint callback derives its commit identity from the exact retained Account-bound `APPLIED` application, rather than a caller-supplied checkpoint. Under the shared owner lock it rechecks the complete current graph and epoch set and computes the schema-3 content digest. Construction CI at `60c507243987705094a3028e0b46f3bccd5d9504` executed the actual Account-order-to-World-APPLIED and selected-checkpoint cases. The standalone selected-publication freeze composition obtains authenticated immutable selection, current Game Design Draft state and exact Account held-order reads outside SQL, then retains the complete Account binding atomically with the first World freeze. V53 denies late qualification of historical attempts. The new closed freeze transport owner-resolves the retained APPLIED plan without accepting caller-supplied private World identities or topology. Its acknowledgement retains the committed freeze event and owner-observed epoch, not terminal publication or admission authority. Exact committed retry verifies the stored order before recapturing mutable authority. The revised combined PostgreSQL definition uses the original owner-issued creator credential to obtain a real distinct Account publication order, reads its actual `HELD` state over strict loopback mTLS, and invokes first freeze and exact retry through a fresh authenticated Game Design-to-World socket. Game Design selection/current-Draft endpoints remain explicit fixture stipulations. Source protection is checked before and after freeze, but the original Draft order also remains pending, so writer denial does not isolate publication as its sole cause. The corrected qualification/rollback and transport definitions still require physical execution. This does not change the generic digest's synthetic highest-commit limitation, register a freeze RPC, settle either owner, or establish end-to-end publication authority. -The bounded Game Logic manifest contract is recorded at its [canonical owner](../../architecture/microservices/game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake), but its producer and intake remain unimplemented. Game Design currently retains command-definition and realm-entry-policy source captures; the command empty-genesis receipt does not establish a complete empty ability/catalog inventory. Complete authored-input inventory, immutable Game Logic retention, dedicated ability-schema evidence and Account-backed authorization through the intake commit remain concrete prerequisites. Unsupported or unknown families stay denied rather than being filtered into an empty manifest. Separately, V37 asset mapping/snapshot storage has caller-transaction guards and five PostgreSQL proof definitions for exact version isolation, retained-row denial, immutable readback and source substitution. The ordinary exporter now consumes its durable verified snapshot; the expanded actual repository-to-exporter test uses a mocked object-store sink and skips locally without Docker, so it is not executed storage-delivery proof. +The bounded Game Logic manifest contract is recorded at its [canonical owner](../../architecture/microservices/game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake). Game Design now defines a closed authored rule inventory with genuine fresh-Version genesis, original versioned revisions, atomic coordinated source results and immutable synchronized snapshots. Its authenticated exact-source read denies missing inventory and nonempty unqualified legacy command sources; neither the older command empty-genesis receipt nor absent rows prove a complete empty ability/catalog inventory. A distinct unregistered Account intake producer reads that exact source outside SQL, verifies the original author operation's committed Account settlement, then uses existing current-creator/source locks to retain an immutable order and full source participation. Its exact Game Logic-only HELD read is separate from Draft/publication orders; pending intake participates in Java and SQL source-change and disclosure guards. These new source/order definitions still require consolidated validation and physical PostgreSQL/composed mTLS proof. Legacy command-source convergence, actual immutable Game Logic retention and authenticated terminal settlement, dedicated ability-schema evidence and exact publication lookup remain concrete prerequisites; no runtime or positive digest activation is enabled. Unsupported or unknown families stay denied rather than being filtered into an empty manifest. Separately, V37 asset mapping/snapshot storage has caller-transaction guards and five PostgreSQL proof definitions for exact version isolation, retained-row denial, immutable readback and source substitution. The ordinary exporter now consumes its durable verified snapshot; the expanded actual repository-to-exporter test uses a mocked object-store sink and skips locally without Docker, so it is not executed storage-delivery proof. The standalone Game Design terminal owner read verifies complete original operation and terminal backing in an independent read-only repeatable-read snapshot. Its closed transport follows the [exact terminal-read contract](../../architecture/microservices/game-design-service/api-contracts.md#exact-publication-terminal-read); owner/transport unit definitions do not establish physical authenticated terminal composition. The receiver remains unregistered. World completion and distinct Account settlement now have unregistered construction components, but their genuine composed producer and physical proof remain open. diff --git a/protos/account/v1/draft_commit_order_service.proto b/protos/account/v1/draft_commit_order_service.proto index 75d585c526..fe27f2e469 100644 --- a/protos/account/v1/draft_commit_order_service.proto +++ b/protos/account/v1/draft_commit_order_service.proto @@ -5,7 +5,9 @@ package account.v1; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; -// Standalone exact held-COMMIT_ORDER read. It is intentionally not runtime-registered here. +// Standalone exact held-COMMIT_ORDER read. Same-namespace World may read any original order; +// Game Logic may read only when the exact canonical original binding requires GAME_LOGIC. +// This service is intentionally not runtime-registered here. service AccountDraftCommitOrderReadService { rpc ReadHeldOriginalCommitOrder(ReadHeldOriginalCommitOrderRequest) returns (ReadHeldOriginalCommitOrderResponse); diff --git a/protos/account/v1/game_logic_intake_authorization.proto b/protos/account/v1/game_logic_intake_authorization.proto new file mode 100644 index 0000000000..572e72deeb --- /dev/null +++ b/protos/account/v1/game_logic_intake_authorization.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Distinct immutable intake order. No original Draft/publication order or settlement is accepted. +service AccountGameLogicIntakeAuthorizationReadService { + rpc ReadHeldGameLogicIntakeAuthorization(ReadHeldGameLogicIntakeAuthorizationRequest) + returns (ReadHeldGameLogicIntakeAuthorizationResponse); +} +message ReadHeldGameLogicIntakeAuthorizationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_intake_authorization = 4; + string intake_authorization_digest = 5; +} +message ReadHeldGameLogicIntakeAuthorizationResponse { + ReadHeldGameLogicIntakeAuthorizationRequest request = 1; + bool held = 2; +} diff --git a/protos/game-design/v1/gameplay_rule_source_service.proto b/protos/game-design/v1/gameplay_rule_source_service.proto new file mode 100644 index 0000000000..978d7244c8 --- /dev/null +++ b/protos/game-design/v1/gameplay_rule_source_service.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; +package game_design.v1; +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Unregistered exact immutable synchronized source read, allowlisted to Account and GL. +service GameDesignGameplayRuleSourceReadService { + rpc ReadSelectedGameplayRuleSource(ReadSelectedGameplayRuleSourceRequest) + returns (ReadSelectedGameplayRuleSourceResponse); +} +message ReadSelectedGameplayRuleSourceRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string game_design_binding_json = 4; + string game_design_binding_digest = 5; +} +message ReadSelectedGameplayRuleSourceResponse { + ReadSelectedGameplayRuleSourceRequest request = 1; + string complete_source_snapshot_json = 2; + string complete_source_snapshot_digest = 3; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcService.java index 2a30efd571..b6d2cad04c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcService.java @@ -30,7 +30,7 @@ public AccountDraftCommitOrderReadGrpcService( public void readHeldOriginalCommitOrder( ReadHeldOriginalCommitOrderRequest request, StreamObserver observer) { - if (!requireAuthenticatedWorldPeer(observer)) return; + if (!requireAuthenticatedPeer(observer)) return; final DraftCommitOrderReadEvidence.Request decoded; try { @@ -68,7 +68,7 @@ public void readHeldOriginalCommitOrder( observer.onCompleted(); } - private boolean requireAuthenticatedWorldPeer(StreamObserver observer) { + private boolean requireAuthenticatedPeer(StreamObserver observer) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer == null) { observer.onError( @@ -77,11 +77,13 @@ private boolean requireAuthenticatedWorldPeer(StreamObserver observer) { .asRuntimeException()); return false; } - String expected = "spiffe://firemud/ns/" + trustedNamespace + "/sa/world-management-service"; - if (expected.equals(peer.uri())) return true; + String prefix = "spiffe://firemud/ns/" + trustedNamespace + "/sa/"; + if ((prefix + "world-management-service").equals(peer.uri()) + || (prefix + "game-logic-service").equals(peer.uri())) return true; observer.onError( Status.PERMISSION_DENIED - .withDescription("Exact same-namespace World workload required") + .withDescription( + "Exact same-namespace World or participating Game Logic workload required") .asRuntimeException()); return false; } @@ -94,7 +96,8 @@ private static StatusRuntimeException sanitized(StatusRuntimeException failure) .asRuntimeException(); case PERMISSION_DENIED -> Status.PERMISSION_DENIED - .withDescription("Exact same-namespace World workload required") + .withDescription( + "Exact same-namespace World or participating Game Logic workload required") .asRuntimeException(); case INVALID_ARGUMENT -> Status.INVALID_ARGUMENT diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java index f4d366ccd8..ab60f297a2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java @@ -41,10 +41,12 @@ public AccountDraftCommitOrderReadService( /** * Returns only after this owner transaction reads the exact retained operation, COMMIT_ORDER, and - * PENDING settlement. Absence, mismatch, reservation/revocation, or any settlement denies. + * PENDING settlement. World may read any exact original order; Game Logic may read only when it + * is an owner in that exact original binding. Absence, mismatch, reservation/revocation, or any + * settlement denies. */ public void requireHeld(DraftCommitOrderReadEvidence.Request request) { - requireAuthenticatedWorldPeer(); + boolean gameLogicPeer = requireAuthenticatedPeer(); Objects.requireNonNull(request, "request"); if (!trustedNamespace.equals(request.targetNamespace())) { throw denied("COMMIT_ORDER read namespace differs from the Account workload namespace"); @@ -56,8 +58,17 @@ public void requireHeld(DraftCommitOrderReadEvidence.Request request) { .asRuntimeException(); } - DraftAuthorizationFenceBinding requested = - DraftAuthorizationFenceBinding.fromStored(request.originalAccountBinding()); + DraftAuthorizationFenceBinding requested; + try { + requested = DraftAuthorizationFenceBinding.fromStored(request.originalAccountBinding()); + } catch (IllegalArgumentException malformed) { + throw invalid("Complete canonical original Account binding is required"); + } + if (gameLogicPeer + && !requested.requiredOwners().contains(DraftAuthorizationFenceBinding.Owner.GAME_LOGIC)) { + throw denied("Game Logic is not a required owner in the original Account binding"); + } + if (!Arrays.equals(request.originalAccountBinding(), requested.canonicalBytes())) { throw invalid("Complete canonical original Account binding is required"); } @@ -97,19 +108,19 @@ public void requireHeld(DraftCommitOrderReadEvidence.Request request) { } } - private void requireAuthenticatedWorldPeer() { + private boolean requireAuthenticatedPeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer == null) { throw Status.UNAUTHENTICATED .withDescription("Verified workload identity required") .asRuntimeException(); } - String expected = "spiffe://firemud/ns/" + trustedNamespace + "/sa/world-management-service"; - if (!expected.equals(peer.uri())) { - throw Status.PERMISSION_DENIED - .withDescription("Exact same-namespace World workload required") - .asRuntimeException(); - } + String prefix = "spiffe://firemud/ns/" + trustedNamespace + "/sa/"; + if ((prefix + "world-management-service").equals(peer.uri())) return false; + if ((prefix + "game-logic-service").equals(peer.uri())) return true; + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World or participating Game Logic workload required") + .asRuntimeException(); } private static StatusRuntimeException unheld() { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index b8b17ebcfd..a6ce3e9bfb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -250,6 +251,7 @@ public void requireDisclosurePreparation(List exactSources) { throw new IllegalStateException("Applicable Account source change is unresolved"); } requireNoPendingPublication(sources); + requireNoPendingGameLogicIntake(sources); for (UUID operationId : affectedOperations(sources)) { Record row = readOperation(operationId); if (row == null) { @@ -311,6 +313,43 @@ public void requirePublicationAdmission(List sources) { requireNoAuthorizedDisclosure(sources); } + /** Distinct rule-intake acquisition uses the same current source/disclosure ordering. */ + public void requireGameLogicIntakeAdmission( + List sources, DraftCommitBinding selected) { + requirePublicationAdmission(sources); + Record originalRow = + dsl.fetchOne( + "SELECT * FROM " + FENCES + " WHERE request_id = ? AND commit_id = ? FOR UPDATE", + selected.requestId(), + selected.commitId()); + if (originalRow == null) { + throw new IllegalStateException("Selected author operation is unavailable"); + } + DraftAuthorizationFenceBinding original = originalBinding(originalRow); + if (!Arrays.equals(original.gameDesignBinding(), selected.canonicalBytes()) + || settlement(original, Ordering.valueOf(originalRow.get("ordering", String.class))) + != Settlement.COMMITTED) { + throw new IllegalStateException( + "Exact selected author operation has not committed and settled"); + } + } + + private boolean hasPendingGameLogicIntake(List sources) { + for (SourceEvidence source : sources) { + if (!dsl.fetch( + "SELECT operation_id FROM account_game_logic_intake_sources WHERE source_key = ?", + source.key()) + .isEmpty()) return true; + } + return false; + } + + private void requireNoPendingGameLogicIntake(List sources) { + if (hasPendingGameLogicIntake(sources)) { + throw new IllegalStateException("Distinct Game Logic intake remains pending"); + } + } + private boolean hasPendingPublication(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( @@ -760,7 +799,7 @@ private List affectedOperations(List sources) { * evidence always remains pending. */ private boolean allAffectedSettled(List sources) { - if (hasPendingPublication(sources)) { + if (hasPendingPublication(sources) || hasPendingGameLogicIntake(sources)) { return false; } for (UUID operation : affectedOperations(sources)) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcService.java new file mode 100644 index 0000000000..9d753285f8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcService.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadGrpcCodec; + +/** Standalone only; authenticate exact workload before parsing a caller-carried binding. */ +public final class AccountGameLogicIntakeAuthorizationReadGrpcService + extends AccountGameLogicIntakeAuthorizationReadServiceGrpc + .AccountGameLogicIntakeAuthorizationReadServiceImplBase { + private final AccountGameLogicIntakeAuthorizationReadService owner; + private final String namespace; + + public AccountGameLogicIntakeAuthorizationReadGrpcService( + AccountGameLogicIntakeAuthorizationReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + @Override + public void readHeldGameLogicIntakeAuthorization( + ReadHeldGameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + try { + AccountGameLogicIntakeAuthorizationReadService.requirePeer(namespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence.Request + decoded; + try { + decoded = GameLogicIntakeAuthorizationReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + owner.requireHeld(decoded); + observer.onNext(GameLogicIntakeAuthorizationReadGrpcCodec.toHeldResponse(decoded)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java new file mode 100644 index 0000000000..fdac09368e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered exact held-source read; all current orders remain pending, never settled. */ +public final class AccountGameLogicIntakeAuthorizationReadService { + private final AccountGameLogicIntakeAuthorizationRepository repository; + private final TransactionTemplate transaction; + private final String namespace; + + public AccountGameLogicIntakeAuthorizationReadService( + AccountGameLogicIntakeAuthorizationRepository repository, + PlatformTransactionManager transactions, + String namespace) { + this.repository = Objects.requireNonNull(repository); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + public void requireHeld(GameLogicIntakeAuthorizationReadEvidence.Request request) { + requirePeer(namespace); + if (!namespace.equals(request.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + try { + transaction.execute( + ignored -> { + repository.readHeld(request.binding()); + return null; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (IllegalArgumentException changed) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } + } + + static void requirePeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + String prefix = "spiffe://firemud/ns/" + namespace + "/sa/"; + if (!(prefix + "game-logic-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java new file mode 100644 index 0000000000..3626489f91 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java @@ -0,0 +1,182 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Immutable pending intake and full source participation; no terminal-write/settlement surface. */ +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner persistence collaborator.") +public final class AccountGameLogicIntakeAuthorizationRepository { + private final DSLContext dsl; + + public AccountGameLogicIntakeAuthorizationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + GameLogicIntakeAuthorizationBinding authorize( + UUID requestId, + GameplayRuleSelectedSource source, + AccountControlUiActorService.Current current, + Runnable admission) { + requireTransaction(); + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_authorizations WHERE tenant_uuid = ? AND intake_request_id = ? FOR UPDATE", + current.stored().tenantId, + requestId); + if (row != null) { + var original = + GameLogicIntakeAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + if (!original.intakeRequestId().equals(requestId) + || !original.actorAccountId().equals(current.stored().accountId) + || !original.source().equals(source)) + throw new IllegalArgumentException( + "Intake request identity conflicts with original source"); + requireExact(row, original); + return original; + } + admission.run(); + var binding = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + requestId, + current.stored().accountId, + source, + current.source().sources()); + dsl.execute( + "INSERT INTO account_game_logic_intake_authorizations (operation_id, fence_id, actor_account_uuid, " + + "tenant_uuid, version_uuid, intake_request_id, source_digest, binding, issuance_operation_id, " + + "issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + binding.actorAccountId(), + binding.tenantId(), + binding.versionId(), + requestId, + source.digest(), + binding.canonicalBytes(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints())); + for (var value : binding.sources()) + dsl.execute( + "INSERT INTO account_game_logic_intake_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + value.key(), + value.canonicalBytes()); + requireExact( + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_authorizations WHERE operation_id = ? FOR UPDATE", + binding.operationId()), + binding); + return binding; + } + + public void readHeld(GameLogicIntakeAuthorizationBinding requested) { + requireTransaction(); + // Deny a changed lookup before acquiring caller-selected authority locks. + var lookup = + dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + requested.operationId()); + if (lookup == null + || !Arrays.equals(requested.canonicalBytes(), lookup.get("binding", byte[].class))) + throw new IllegalArgumentException("Original intake order absent or changed"); + var original = + GameLogicIntakeAuthorizationBinding.fromStored(lookup.get("binding", byte[].class)); + for (var value : original.sources()) + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + value.key()) + == null) throw new IllegalArgumentException("Original intake source lock absent"); + requireExact( + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_authorizations WHERE operation_id = ? FOR UPDATE", + original.operationId()), + original); + // Every immutable order remains pending until a later authenticated terminal integration + // exists. + } + + private void requireExact(Record row, GameLogicIntakeAuthorizationBinding binding) { + if (row == null + || !Arrays.equals(binding.canonicalBytes(), row.get("binding", byte[].class)) + || !binding.operationId().equals(row.get("operation_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class)) + || !binding.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !binding.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !binding.versionId().equals(row.get("version_uuid", UUID.class)) + || !binding.intakeRequestId().equals(row.get("intake_request_id", UUID.class)) + || !binding.source().digest().equals(row.get("source_digest", String.class))) + throw new IllegalArgumentException("Original intake order absent or changed"); + var issuer = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ? FOR UPDATE NOWAIT", + row.get("issuance_operation_id", UUID.class)); + if (issuer == null) throw new IllegalArgumentException("Original committed issuance absent"); + var original = new AccountControlUiIssuanceRepository.Stored(issuer); + // Source-writer guards prevent revocation while this operation participates. + if (!"COMMITTED".equals(original.status) + || !binding.actorAccountId().equals(original.accountId) + || !binding.tenantId().equals(original.tenantId) + || !Arrays.equals(original.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(original.bundle, row.get("issuance_bundle", byte[].class))) + throw new IllegalArgumentException("Changed original intake issuance"); + var bundle = AccountControlUiIssuanceRepository.object(original.bundle); + var payload = AccountControlUiIssuanceRepository.object(original.sources); + if (!(bundle.get("issuanceFence") instanceof Number fence) + || fence.longValue() != row.get("issuance_fence", Long.class) + || !Arrays.equals( + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + bundle.get("outboxCheckpoints")), + row.get("outbox_checkpoints", byte[].class)) + || !(payload.get("sources") instanceof java.util.List vector) + || vector.size() != binding.sources().size()) + throw new IllegalArgumentException("Incomplete original issuance vector"); + var participation = + dsl + .fetch( + "SELECT source_key, source_evidence FROM account_game_logic_intake_sources WHERE operation_id = ?", + binding.operationId()) + .stream() + .sorted(java.util.Comparator.comparing(v -> v.get("source_key", String.class))) + .toList(); + if (participation.size() != binding.sources().size()) + throw new IllegalArgumentException("Incomplete intake participation"); + for (int i = 0; i < participation.size(); i++) { + var source = binding.sources().get(i); + if (!(vector.get(i) instanceof String encoded) + || !Arrays.equals(source.canonicalBytes(), java.util.Base64.getDecoder().decode(encoded)) + || !source.key().equals(participation.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), participation.get(i).get("source_evidence", byte[].class))) + throw new IllegalArgumentException("Changed intake participation"); + } + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + throw new IllegalStateException("Writable Account owner transaction required"); + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) + throw new IllegalStateException( + "Writable READ_COMMITTED Account owner transaction required"); + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java new file mode 100644 index 0000000000..b82cd4f146 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered distinct intake producer. Genuine current creator and GD owner reads are mandatory. + */ +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner transaction collaborators.") +public final class AccountGameLogicIntakeAuthorizationService { + private final AccountControlUiActorService actors; + private final DraftAuthorizationFenceRepository fences; + private final AccountGameLogicIntakeAuthorizationRepository repository; + private final GameplayRuleSourceReadClient sources; + private final String namespace; + + public AccountGameLogicIntakeAuthorizationService( + AccountControlUiActorService actors, + DraftAuthorizationFenceRepository fences, + AccountGameLogicIntakeAuthorizationRepository repository, + GameplayRuleSourceReadClient sources, + String namespace) { + this.actors = Objects.requireNonNull(actors); + this.fences = Objects.requireNonNull(fences); + this.repository = Objects.requireNonNull(repository); + this.sources = Objects.requireNonNull(sources); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + public GameLogicIntakeAuthorizationBinding authorize( + String compactJwt, + UUID intakeRequestId, + DraftCommitBinding selected, + CapturedEnvironmentBoundary environment) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.requireUuid( + intakeRequestId); + Objects.requireNonNull(selected); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION + .withDescription("Source read must precede Account SQL") + .asRuntimeException(); + var request = GameplayRuleSourceReadEvidence.Request.create(namespace, selected); + var evidence = sources.read(request); + if (evidence == null + || !request.equals(evidence.request()) + || !selected.equals(evidence.source().binding())) + throw new IllegalStateException("Exact authenticated complete GD source required"); + return actors.withCurrent( + compactJwt, + selected.target().canonicalTenantId(), + environment, + current -> { + fences.lockProducerSourcesNowait(current.source().sources()); + return repository.authorize( + intakeRequestId, + evidence.source(), + current, + () -> fences.requireGameLogicIntakeAdmission(current.source().sources(), selected)); + }); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V109__game_logic_intake_authorization.sql b/services/account-service/src/main/resources/db/migration/V109__game_logic_intake_authorization.sql new file mode 100644 index 0000000000..82cfbdbc36 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V109__game_logic_intake_authorization.sql @@ -0,0 +1,175 @@ +-- Unregistered distinct intake order. Every retained order remains pending: no settlement writer. +CREATE TABLE account_game_logic_intake_authorizations ( + operation_id UUID PRIMARY KEY, + fence_id UUID NOT NULL UNIQUE, + actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + version_uuid UUID NOT NULL, + intake_request_id UUID NOT NULL, + source_digest VARCHAR(71) NOT NULL CHECK (source_digest ~ '^sha256:[0-9a-f]{64}$'), + binding BYTEA NOT NULL CHECK (octet_length(binding) BETWEEN 1 AND 4194304), + issuance_operation_id UUID NOT NULL REFERENCES account_control_ui_issuance_operations(operation_id), + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + issuance_bundle BYTEA NOT NULL CHECK (octet_length(issuance_bundle) BETWEEN 1 AND 131072), + outbox_checkpoints BYTEA NOT NULL CHECK (octet_length(outbox_checkpoints) BETWEEN 1 AND 131072), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + ordered_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (tenant_uuid, intake_request_id) +); +CREATE TABLE account_game_logic_intake_sources ( + operation_id UUID NOT NULL REFERENCES account_game_logic_intake_authorizations(operation_id), + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_game_logic_intake_source_lookup ON account_game_logic_intake_sources(source_key, operation_id); + +-- [jooq ignore start] +CREATE FUNCTION account_game_logic_intake_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_game_logic_intake_authorizations + WHERE operation_id = NEW.operation_id AND producer_xid = txid_current()) THEN + RAISE EXCEPTION 'Intake sources must accompany the original owner transaction' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_game_logic_intake_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + p INTEGER := 1; + parsed BYTEA; + source_bytes BYTEA; + source_position INTEGER; + kind TEXT; + scope TEXT; + source_key_value TEXT; + seen TEXT[] := ARRAY[]::TEXT[]; + source_count INTEGER; + snapshot JSONB; + selected JSONB; + issuer account_control_ui_issuance_operations%ROWTYPE; +BEGIN + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations + WHERE operation_id = NEW.issuance_operation_id; + IF issuer.status IS DISTINCT FROM 'COMMITTED' OR issuer.account_uuid IS DISTINCT FROM NEW.actor_account_uuid + OR issuer.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid OR issuer.source_payload IS DISTINCT FROM NEW.source_payload + OR issuer.bundle_payload IS DISTINCT FROM NEW.issuance_bundle + OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT IS DISTINCT FROM NEW.issuance_fence + OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' + IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB + OR NEW.producer_xid <> txid_current() + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'accountId' IS DISTINCT FROM NEW.actor_account_uuid::TEXT + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT THEN + RAISE EXCEPTION 'Intake requires exact committed creator issuance evidence' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> 'account-game-logic-intake-authorization/v1' THEN + RAISE EXCEPTION 'Invalid intake schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.operation_id::TEXT THEN + RAISE EXCEPTION 'Changed intake operation' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.fence_id::TEXT THEN + RAISE EXCEPTION 'Changed intake fence' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.intake_request_id::TEXT THEN + RAISE EXCEPTION 'Changed intake request' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF convert_from(parsed, 'UTF8') <> NEW.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Changed intake actor' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF 'sha256:' || encode(sha256(parsed), 'hex') <> NEW.source_digest THEN + RAISE EXCEPTION 'Changed complete intake source digest' USING ERRCODE = '23514'; + END IF; + snapshot := convert_from(parsed, 'UTF8')::JSONB; + selected := (snapshot->>'bindingJson')::JSONB; + IF snapshot->>'schema' IS DISTINCT FROM 'game-design-gameplay-rule-source-snapshot/v1' + OR selected->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR selected->>'canonicalVersionId' IS DISTINCT FROM NEW.version_uuid::TEXT + OR snapshot->>'bindingDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(convert_to(snapshot->>'bindingJson', 'UTF8')), 'hex') THEN + RAISE EXCEPTION 'Changed selected source identity' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); + source_count := convert_from(parsed, 'UTF8')::INTEGER; + IF source_count < 1 OR source_count <> (SELECT count(*) FROM account_game_logic_intake_sources WHERE operation_id = NEW.operation_id) + OR source_count IS DISTINCT FROM jsonb_array_length(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources') THEN + RAISE EXCEPTION 'Incomplete intake source participation' USING ERRCODE = '23514'; + END IF; + FOR i IN 1..source_count LOOP + SELECT frame_value, next_position INTO source_bytes, p FROM account_publication_authorization_read_frame(NEW.binding, p); + IF source_bytes IS DISTINCT FROM decode(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'->>(i - 1), 'base64') THEN + RAISE EXCEPTION 'Intake source differs from original complete issuance vector' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(source_bytes, 1); + IF convert_from(parsed, 'UTF8') <> 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Invalid intake authority source schema' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO kind, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO scope, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := kind || ':' || scope; + IF source_key_value = ANY(seen) OR NOT EXISTS (SELECT 1 FROM account_game_logic_intake_sources + WHERE operation_id = NEW.operation_id AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Changed intake authority participation' USING ERRCODE = '23514'; + END IF; + seen := array_append(seen, source_key_value); + END LOOP; + IF p <> octet_length(NEW.binding) + 1 THEN + RAISE EXCEPTION 'Trailing intake authorization evidence' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER account_game_logic_intake_complete + AFTER INSERT ON account_game_logic_intake_authorizations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_game_logic_intake_complete_guard(); +CREATE TRIGGER account_game_logic_intake_source_insert + BEFORE INSERT ON account_game_logic_intake_sources FOR EACH ROW + EXECUTE FUNCTION account_game_logic_intake_source_insert_guard(); +CREATE TRIGGER account_game_logic_intake_immutable + BEFORE UPDATE OR DELETE ON account_game_logic_intake_authorizations FOR EACH ROW + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_sources_immutable + BEFORE UPDATE OR DELETE ON account_game_logic_intake_sources FOR EACH ROW + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_no_truncate + BEFORE TRUNCATE ON account_game_logic_intake_authorizations FOR EACH STATEMENT + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_sources_no_truncate + BEFORE TRUNCATE ON account_game_logic_intake_sources FOR EACH STATEMENT + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +-- Preserve the existing source-writer locks and Draft/publication decisions exactly. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_selected_publication_sources s WHERE s.source_key = ANY(source_keys)$anchor$; + intake_guard TEXT := $guard$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_game_logic_intake_sources s WHERE s.source_key = ANY(source_keys) + ORDER BY s.operation_id LOOP + PERFORM operation_id FROM account_game_logic_intake_authorizations + WHERE operation_id = operation_value FOR UPDATE NOWAIT; + RAISE EXCEPTION 'Distinct Game Logic intake remains pending' USING ERRCODE = '55P03'; + END LOOP; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one existing publication source-writer guard'; + END IF; + EXECUTE replace(original, anchor, intake_guard || anchor); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V110__selected_inventory_empty_arrays.sql b/services/account-service/src/main/resources/db/migration/V110__selected_inventory_empty_arrays.sql new file mode 100644 index 0000000000..b307544bcc --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V110__selected_inventory_empty_arrays.sql @@ -0,0 +1,34 @@ +-- Preserve the full source-key capacity of Account participation and accept explicit empty +-- selected-inventory input arrays while retaining canonical ordering checks for nonempty arrays. +ALTER TABLE account_selected_publication_sources + ALTER COLUMN source_key TYPE VARCHAR(2048); + +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + region_anchor TEXT := $anchor$ OR (SELECT jsonb_agg(entry ORDER BY entry->>'regionTemplateId') FROM + jsonb_array_elements(model->'regionGeneratorInputs') entry) + IS DISTINCT FROM model->'regionGeneratorInputs'$anchor$; + region_replacement TEXT := $replacement$ OR (SELECT coalesce(jsonb_agg(entry ORDER BY entry->>'regionTemplateId'), '[]'::JSONB) FROM + jsonb_array_elements(model->'regionGeneratorInputs') entry) + IS DISTINCT FROM model->'regionGeneratorInputs'$replacement$; + spawn_anchor TEXT := $anchor$ OR (SELECT jsonb_agg(entry ORDER BY entry->>'bindingTemplateId') FROM + jsonb_array_elements(model->'spawnBindingInputs') entry) + IS DISTINCT FROM model->'spawnBindingInputs'$anchor$; + spawn_replacement TEXT := $replacement$ OR (SELECT coalesce(jsonb_agg(entry ORDER BY entry->>'bindingTemplateId'), '[]'::JSONB) FROM + jsonb_array_elements(model->'spawnBindingInputs') entry) + IS DISTINCT FROM model->'spawnBindingInputs'$replacement$; +BEGIN + SELECT pg_get_functiondef('require_selected_inventory_operation_v2(BYTEA)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, region_anchor, ''))) / length(region_anchor) <> 1 + OR (length(original) - length(replace(original, spawn_anchor, ''))) / length(spawn_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V108 ordering guard for each selected inventory input array'; + END IF; + original := replace(original, region_anchor, region_replacement); + original := replace(original, spawn_anchor, spawn_replacement); + EXECUTE original; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java index 7430bd3ffa..c1a75820d4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java @@ -6,6 +6,7 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.StatusRuntimeException; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; @@ -104,11 +105,64 @@ void acceptsOnlyExactCommittedHeldOrderInSeparateWritableReadCommittedTransactio assertThat(snapshot(fixture)).isEqualTo(before); } + @Test + void acceptsExactGameLogicParticipantAndPreservesOriginalBindingBytes() throws Exception { + Fixture fixture = fixture(); + DraftAuthorizationFenceBinding binding = binding(fixture, true); + assertThat(binding.schemaVersion()).isEqualTo(DraftAuthorizationFenceBinding.SCHEMA_V2); + assertThat(binding.requiredOwners()).contains(Owner.GAME_LOGIC); + reserveAndCommitOrder(fixture, binding); + var before = snapshot(fixture); + fixture.transactions.reset(); + + asGameLogic(() -> fixture.reader.requireHeld(request(binding))); + + assertThat(fixture.transactions.beginCount()).isOne(); + assertThat(fixture.transactions.lastDefinition().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(fixture.transactions.lastDefinition().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(fixture.transactions.lastDefinition().isReadOnly()).isFalse(); + assertThat(snapshot(fixture)).isEqualTo(before); + assertThat(fixture.tx(() -> fixture.repository.readSettlement(binding))) + .isEqualTo(Settlement.PENDING); + assertThat( + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT binding FROM account_draft_authorization_fences WHERE operation_id = ?", + binding.operationId())) + .get("binding", byte[].class)) + .containsExactly(binding.canonicalBytes()); + } + + @Test + void deniesNonparticipatingGameLogicBeforeDatabaseAccessOrMutation() throws Exception { + Fixture fixture = fixture(); + DraftAuthorizationFenceBinding binding = binding(fixture); + reserveAndCommitOrder(fixture, binding); + var before = snapshot(fixture); + fixture.transactions.reset(); + + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> asGameLogic(() -> fixture.reader.requireHeld(request(binding)))); + + assertThat(fixture.transactions.beginCount()).isZero(); + assertThat(snapshot(fixture)).isEqualTo(before); + assertThat( + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT binding FROM account_draft_authorization_fences WHERE operation_id = ?", + binding.operationId())) + .get("binding", byte[].class)) + .containsExactly(binding.canonicalBytes()); + } + @Test void deniesReservedRevokedSettledChangedAndMissingBindings() { for (ReadCase readCase : ReadCase.values()) { Fixture fixture = fixture(); - DraftAuthorizationFenceBinding original = binding(fixture); + DraftAuthorizationFenceBinding original = binding(fixture, true); DraftAuthorizationFenceBinding requested = original; switch (readCase) { case RESERVED -> fixture.tx(() -> fixture.repository.reserve(original)); @@ -124,6 +178,7 @@ void deniesReservedRevokedSettledChangedAndMissingBindings() { reserveAndCommitOrder(fixture, original); recordReadback(fixture, original, Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {1}); recordReadback(fixture, original, Owner.WORLD, Outcome.COMMITTED, new byte[] {2}); + recordReadback(fixture, original, Owner.GAME_LOGIC, Outcome.COMMITTED, new byte[] {3}); assertThat(fixture.tx(() -> fixture.repository.readSettlement(original))) .isEqualTo(Settlement.COMMITTED); } @@ -131,15 +186,17 @@ void deniesReservedRevokedSettledChangedAndMissingBindings() { reserveAndCommitOrder(fixture, original); requested = changedBinding(original); } - case MISSING -> requested = binding(fixture); + case MISSING -> requested = binding(fixture, true); } + var before = snapshot(fixture); fixture.transactions.reset(); DraftAuthorizationFenceBinding submitted = requested; assertStatus( Status.Code.FAILED_PRECONDITION, - () -> asWorld(() -> fixture.reader.requireHeld(request(submitted)))); + () -> asGameLogic(() -> fixture.reader.requireHeld(request(submitted)))); assertThat(fixture.transactions.beginCount()).isOne(); + assertThat(snapshot(fixture)).isEqualTo(before); if (readCase != ReadCase.MISSING) { assertThat( Objects.requireNonNull( @@ -201,6 +258,11 @@ private static Fixture fixture() { } private static DraftAuthorizationFenceBinding binding(Fixture fixture) { + return binding(fixture, false); + } + + private static DraftAuthorizationFenceBinding binding( + Fixture fixture, boolean gameLogicRequired) { UUID account = fixture.tx( () -> { @@ -215,19 +277,16 @@ private static DraftAuthorizationFenceBinding binding(Fixture fixture) { UUID version = UUID.randomUUID(); UUID request = UUID.randomUUID(); UUID commit = UUID.randomUUID(); - DraftCommitBinding complete = - DraftCommitBinding.create( - new TargetProof( - tenant, version, 17L, "test-tenant", 23L, "test-tenant", "NEW_GAME_ROW"), - request, - commit, - "test-base", + List revisions = + new ArrayList<>( List.of( new RevisionPayload( "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, - "test-change")), + "test-change"))); + List affectedUnits = + new ArrayList<>( List.of( new AffectedUnit( DraftCommitBinding.Owner.WORLD_MANAGEMENT, @@ -236,29 +295,53 @@ private static DraftAuthorizationFenceBinding binding(Fixture fixture) { "AGGREGATE", "test-region", "0"))); + if (gameLogicRequired) { + revisions.add( + new RevisionPayload( + "1", UUID.randomUUID(), DraftCommitBinding.Owner.GAME_LOGIC, "test-rule-change")); + affectedUnits.add( + new AffectedUnit( + DraftCommitBinding.Owner.GAME_LOGIC, + "RULE_SET", + "test-rules", + "AGGREGATE", + "test-rules", + "0")); + } + DraftCommitBinding complete = + DraftCommitBinding.create( + new TargetProof( + tenant, version, 17L, "test-tenant", 23L, "test-tenant", "NEW_GAME_ROW"), + request, + commit, + "test-base", + revisions, + affectedUnits); byte[] draftBytes = complete.canonicalBytes(); - return new DraftAuthorizationFenceBinding( - UUID.randomUUID(), - request, - commit, - UUID.randomUUID(), - account, - tenant, - version, - complete.baseCommitId(), - "0", - draftBytes, - draftBytes, - complete.digest(), - List.of( - new SourceEvidence( - SourceKind.ACCOUNT, - account.toString(), - "1", - "1", - "test-account-stream/" + account, - "0", - new byte[] {7}))); + DraftAuthorizationFenceBinding binding = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + request, + commit, + UUID.randomUUID(), + account, + tenant, + version, + complete.baseCommitId(), + "0", + draftBytes, + draftBytes, + complete.digest(), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + "1", + "1", + "test-account-stream/" + account, + "0", + new byte[] {7}))); + return gameLogicRequired ? binding.withRequiredOwners() : binding; } private static DraftAuthorizationFenceBinding changedBinding( @@ -365,6 +448,10 @@ private static void asWorld(Runnable operation) { asPeer("spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", operation); } + private static void asGameLogic(Runnable operation) { + asPeer("spiffe://firemud/ns/" + NAMESPACE + "/sa/game-logic-service", operation); + } + private static void asPeer(String uri, Runnable operation) { GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(uri).orElseThrow(); Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java new file mode 100644 index 0000000000..bd7f2cea68 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java @@ -0,0 +1,353 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceRevision; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real creator issuance/currentness, Account transactions, V109 and source guards. GD source + * transport and the original author's terminal are explicit upstream fixtures, not composed + * production or mTLS proof. No GL terminal, settlement, digest or activation is claimed. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountGameLogicIntakeAuthorizationPostgresIntegrationTest { + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("intake-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "intake-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisclosure() + throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + var captured = f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + selected.requestId(), + selected.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + selected.target().canonicalVersionId(), + selected.baseCommitId(), + "0", + selected.canonicalBytes(), + selected.canonicalBytes(), + selected.digest(), + captured.sources()) + .withRequiredOwners(); + issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); + var source = source(selected); + var gd = mock(GameplayRuleSourceReadClient.class); + when(gd.read(any())) + .thenAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)); + var repository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); + var service = + new AccountGameLogicIntakeAuthorizationService( + issued.actors(), f.fences, repository, gd, "test"); + var requestId = UUID.randomUUID(); + + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment()))) + .isInstanceOf(IllegalStateException.class); + assertThat( + f.dsl.fetchCount(org.jooq.impl.DSL.table("account_game_logic_intake_authorizations"))) + .isZero(); + f.tx( + () -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); + var order = + asGameDesign( + () -> service.authorize(issued.compact(), requestId, selected, issued.environment())); + assertThat(order.source()).isEqualTo(source); + assertThat(order.sources()).hasSize(captured.sources().size()); + assertThat( + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment())) + .canonicalBytes()) + .isEqualTo(order.canonicalBytes()); + String genesis = + GameplayRuleManifest.tree(source.snapshotJson()).path("genesisReceiptId").textValue(); + var substituted = + new GameplayRuleSelectedSource( + source.snapshotJson().replace(genesis, UUID.randomUUID().toString())); + when(gd.read(any())) + .thenAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), substituted)); + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + when(gd.read(any())) + .thenAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)); + + UUID rolledBackRequest = UUID.randomUUID(); + assertThatThrownBy( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + f.fences.lockProducerSourcesNowait(current.source().sources()); + repository.authorize( + rolledBackRequest, + source, + current, + () -> + f.fences.requireGameLogicIntakeAdmission( + current.source().sources(), selected)); + throw new IllegalStateException("rollback before owner commit"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat( + f.dsl.fetchOne( + "SELECT 1 FROM account_game_logic_intake_authorizations WHERE intake_request_id = ?", + rolledBackRequest)) + .isNull(); + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(order.sources()); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("intake"); + + // Only the distinct intake is pending; original Draft settlement is already COMMITTED. + assertThat(f.tx(() -> f.fences.readSettlement(original))) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.COMMITTED); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); + return null; + })) + .hasStackTraceContaining("Distinct Game Logic intake remains pending"); + + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), order.sources(), new byte[] {2}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceAbortPermitted(change))).isFalse(); + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "UPDATE account_game_logic_intake_authorizations SET source_digest = ? WHERE operation_id = ?", + "sha256:" + "0".repeat(64), + order.operationId()); + return null; + })) + .hasStackTraceContaining("immutable"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + "invalid-credential", + UUID.randomUUID(), + selected, + issued.environment()))) + .isInstanceOf(RuntimeException.class); + } + } + + private static DraftCommitBinding selected(UUID tenant) { + var target = + new DraftCommitBinding.TargetProof( + tenant, UUID.randomUUID(), 17, "private", 11, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding selected) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + Map> families = + new EnumMap<>(GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + selected.canonicalJson(), + "sourceBindingDigest", + selected.digest(), + "revisionOrder", + "0", + "revisionId", + selected.revisions().getFirst().revisionId().toString()))))); + } + + private static T asGameDesign(java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index 6681e0f53c..915383ffc0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -421,6 +421,29 @@ void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throw new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) .authorize(issued.compact(), proof.selection(), issued.environment()); var operation = operation(order, proof.world()); + Integer selectedSourceKeyWidth = + f.dsl + .fetchSingle( + "SELECT character_maximum_length FROM information_schema.columns" + + " WHERE table_schema = current_schema()" + + " AND table_name = 'account_selected_publication_sources'" + + " AND column_name = 'source_key'") + .get(0, Integer.class); + assertThat(selectedSourceKeyWidth).isEqualTo(2048); + String inventoryGuard = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('require_selected_inventory_operation_v2(bytea)'::regprocedure)") + .get(0, String.class); + assertThat(inventoryGuard) + .contains("coalesce(jsonb_agg(entry ORDER BY entry->>'regionTemplateId'), '[]'::JSONB)") + .contains("coalesce(jsonb_agg(entry ORDER BY entry->>'bindingTemplateId'), '[]'::JSONB)") + .contains( + "OR selector->'request'->'worldAffectedTuples' IS DISTINCT FROM expected_tuples") + .contains( + "OR model->'appliedEpochs' IS DISTINCT FROM expected_epochs OR expected_epochs = '[]'::JSONB") + .contains( + "Inventory differs from exact original selected Account, APPLIED graph or freeze"); var terminal = terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); var out = new java.io.ByteArrayOutputStream(); @@ -518,6 +541,110 @@ void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throw "\"graphDigest\":\"sha256:" + "0".repeat(64) + "\"") .getBytes(java.nio.charset.StandardCharsets.UTF_8); byte[] validOperation = operation.canonicalBytes(); + String tenantId = proof.world().request().canonicalTenantId().toString(); + String versionId = proof.world().request().canonicalVersionId().toString(); + String originalRegionTemplateId = + operation + .inventory() + .publicEvidence() + .sourceModel() + .regionGeneratorInputs() + .get(0) + .regionTemplateId() + .toString(); + String originalRegionInputs = + "\"regionGeneratorInputs\":[" + + inventoryRegionGeneratorInput(originalRegionTemplateId) + + "]"; + String unsortedRegionInputs = + "[" + + inventoryRegionGeneratorInput("00000000-0000-0000-0000-000000000002") + + "," + + inventoryRegionGeneratorInput("00000000-0000-0000-0000-000000000001") + + "]"; + assertThat(publicInventoryJson) + .contains("\"family\":\"REGION\",\"rowCount\":1") + .contains(originalRegionInputs); + byte[] unsortedRegionInventory = + publicInventoryJson + .replace( + "\"family\":\"REGION\",\"rowCount\":1", "\"family\":\"REGION\",\"rowCount\":2") + .replace(originalRegionInputs, "\"regionGeneratorInputs\":" + unsortedRegionInputs) + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] unsortedRegionOperation = + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + unsortedRegionInventory, + DraftAuthorizationFenceBinding.digest(unsortedRegionInventory)); + Object[] unsortedRegionSettlement = { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + unsortedRegionOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }; + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, unsortedRegionSettlement))) + .satisfies( + failure -> + assertSqlFailure( + failure, "23514", "Unsupported or unordered region generator input")); + String unsortedSpawnInputs = + "[" + + inventorySpawnBindingInput( + "00000000-0000-0000-0000-000000000002", + "00000000-0000-0000-0000-000000000003", + "00000000-0000-0000-0000-000000000004", + tenantId, + versionId) + + "," + + inventorySpawnBindingInput( + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000005", + "00000000-0000-0000-0000-000000000006", + tenantId, + versionId) + + "]"; + assertThat(publicInventoryJson) + .contains("\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":0") + .contains("\"spawnBindingCount\":0") + .contains("\"spawnBindingInputs\":[]"); + byte[] unsortedSpawnInventory = + publicInventoryJson + .replace( + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":0", + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":2") + .replace("\"spawnBindingCount\":0", "\"spawnBindingCount\":2") + .replace("\"spawnBindingInputs\":[]", "\"spawnBindingInputs\":" + unsortedSpawnInputs) + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] unsortedSpawnOperation = + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + unsortedSpawnInventory, + DraftAuthorizationFenceBinding.digest(unsortedSpawnInventory)); + Object[] unsortedSpawnSettlement = { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + unsortedSpawnOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }; + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, unsortedSpawnSettlement))) + .satisfies( + failure -> + assertSqlFailure( + failure, "23514", "Unsupported or unordered scoped spawn input")); List invalidOperations = List.of( rawOperation( @@ -1132,6 +1259,44 @@ private static String b64(byte[] value) { return Base64.getEncoder().encodeToString(value); } + private static String inventorySpawnBindingInput( + String bindingTemplateId, + String roomTemplateId, + String entityTemplateId, + String tenantId, + String versionId) { + return "{\"bindingTemplateId\":\"" + + bindingTemplateId + + "\",\"entityReferenceKind\":\"ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID\",\"entityTemplateId\":\"" + + entityTemplateId + + "\",\"entityTemplateType\":\"ITEM\",\"entityTenantId\":\"" + + tenantId + + "\",\"entityVersionId\":\"" + + versionId + + "\",\"respawnDelaySeconds\":0,\"roomTemplateId\":\"" + + roomTemplateId + + "\",\"spawnCount\":1}"; + } + + private static String inventoryRegionGeneratorInput(String regionTemplateId) { + return "{\"generatorParams\":\"\",\"generatorType\":\"\",\"regionTemplateId\":\"" + + regionTemplateId + + "\"}"; + } + + private static void assertSqlFailure( + Throwable failure, String expectedState, String expectedMessage) { + java.sql.SQLException sqlFailure = null; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sqlException) sqlFailure = sqlException; + } + assertThat((Throwable) sqlFailure).isNotNull(); + var exactSqlFailure = + java.util.Objects.requireNonNull(sqlFailure, "Expected SQL failure from direct insert"); + assertThat(exactSqlFailure.getSQLState()).isEqualTo(expectedState); + assertThat(exactSqlFailure.getMessage()).contains(expectedMessage); + } + private static AuthoredDraftPublishSelectionBinding selection( DraftCommitBinding draft, String notes) { return selection(draft, notes, "publication-request"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcMtlsTest.java index 082228ebaf..366eb8beab 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcMtlsTest.java @@ -7,6 +7,7 @@ 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.ByteString; import io.grpc.ManagedChannel; @@ -34,6 +35,7 @@ import java.util.ArrayList; import java.util.Base64; import java.util.List; +import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -43,6 +45,10 @@ import net.firedevops.firemud.account.v1.ReadHeldOriginalCommitOrderResponse; import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadService; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.FenceSnapshot; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; import net.firedevops.firemud.common.authoring.DraftCommitOrderReadGrpcCodec; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -53,12 +59,15 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; /** Physical loopback mTLS proof for the Account held-COMMIT_ORDER gRPC handler boundary. */ class AccountDraftCommitOrderReadGrpcMtlsTest { private static final String NAMESPACE = "test"; private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String GAME_LOGIC_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; private static final String WRONG_WORKLOAD_URI = "spiffe://firemud/ns/test/sa/game-design-service"; private static final String OTHER_NAMESPACE_WORLD_URI = @@ -111,6 +120,48 @@ void trustedWrongWorkloadAndNamespaceAreDeniedBeforeOwnerReads() throws Exceptio } } + @Test + void gameLogicMtlsReadsOnlyItsExactRequiredOwnerBinding() throws Exception { + var repository = mock(DraftAuthorizationFenceRepository.class); + var manager = mock(PlatformTransactionManager.class); + var transactionStatus = mock(TransactionStatus.class); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + var participatingBinding = AccountDraftCommitOrderReadServiceTest.bindingWithGameLogic(1); + when(repository.readOriginalBinding(participatingBinding.operationId())) + .thenReturn(Optional.of(participatingBinding)); + when(repository.read(participatingBinding)) + .thenReturn( + new FenceSnapshot( + Ordering.COMMIT_ORDER, participatingBinding.canonicalBytes(), null, null)); + when(repository.readSettlement(participatingBinding)).thenReturn(Settlement.PENDING); + var owner = new AccountDraftCommitOrderReadService(repository, manager, NAMESPACE); + try (TransportServer server = startServer(owner); + ClientTransport client = newClient(server.port(), pki.gameLogicClient())) { + ReadHeldOriginalCommitOrderResponse response = + client.read( + DraftCommitOrderReadGrpcCodec.toRequest( + AccountDraftCommitOrderReadServiceTest.request(participatingBinding))); + + assertThat(response.getStatus()) + .isEqualTo(HeldOriginalCommitOrderStatus.HELD_ORIGINAL_COMMIT_ORDER_STATUS_HELD); + assertThat(response.getOriginalAccountBinding().toByteArray()) + .containsExactly(participatingBinding.canonicalBytes()); + + var worldOnlyBinding = AccountDraftCommitOrderReadServiceTest.binding(1); + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> + client.read( + DraftCommitOrderReadGrpcCodec.toRequest( + AccountDraftCommitOrderReadServiceTest.request(worldOnlyBinding)))); + assertThat(server.handlerCalls()).hasValue(2); + verify(manager).getTransaction(any()); + verify(repository).readOriginalBinding(participatingBinding.operationId()); + verify(repository, org.mockito.Mockito.never()) + .readOriginalBinding(worldOnlyBinding.operationId()); + } + } + @Test void missingClientCertificateIsRejectedBeforeHandlerOrOwnerRead() throws Exception { TestOnlyHeldOwner owner = new TestOnlyHeldOwner(); @@ -172,9 +223,14 @@ private static void assertStatus( } private static TransportServer startServer(TestOnlyHeldOwner owner) throws Exception { + return startServer(owner.service()); + } + + private static TransportServer startServer(AccountDraftCommitOrderReadService owner) + throws Exception { AtomicInteger handlerCalls = new AtomicInteger(); AccountDraftCommitOrderReadGrpcService service = - new AccountDraftCommitOrderReadGrpcService(owner.service(), NAMESPACE); + new AccountDraftCommitOrderReadGrpcService(owner, NAMESPACE); ServerInterceptor countHandlerCalls = new ServerInterceptor() { @Override @@ -295,6 +351,7 @@ private record TestPki( Path caCertificatePem, TestIdentity accountServer, TestIdentity worldClient, + TestIdentity gameLogicClient, TestIdentity wrongWorkloadClient, TestIdentity otherNamespaceClient) { private static TestPki create(Path directory) throws Exception { @@ -343,6 +400,7 @@ private static TestPki create(Path directory) throws Exception { caFile, issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), issueIdentity(directory, caStore, caFile, "world-client", WORLD_URI, false), + issueIdentity(directory, caStore, caFile, "game-logic-client", GAME_LOGIC_URI, false), issueIdentity( directory, caStore, caFile, "wrong-workload-client", WRONG_WORKLOAD_URI, false), issueIdentity( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcServiceTest.java index 37abaf28a7..7e85e3e4a0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadGrpcServiceTest.java @@ -27,7 +27,7 @@ class AccountDraftCommitOrderReadGrpcServiceTest { @Test - void authenticatesExactWorldPeerBeforeDecodingOrOwnerAccess() { + void authenticatesExactOwnerPeerBeforeDecodingOrOwnerAccess() { var repository = mock(DraftAuthorizationFenceRepository.class); var manager = mock(PlatformTransactionManager.class); var owner = new AccountDraftCommitOrderReadService(repository, manager, "test"); @@ -47,6 +47,11 @@ void authenticatesExactWorldPeerBeforeDecodingOrOwnerAccess() { asPeer(identity, () -> service.readHeldOriginalCommitOrder(malformed, wrong)); assertThat(wrong.errorStatus.getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); } + Collector malformedGameLogic = new Collector(); + asPeer( + "spiffe://firemud/ns/test/sa/game-logic-service", + () -> service.readHeldOriginalCommitOrder(malformed, malformedGameLogic)); + assertThat(malformedGameLogic.errorStatus.getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); verifyNoInteractions(repository, manager); } @@ -80,6 +85,61 @@ void authenticatedWorldPeerGetsHeldOnlyForExactPendingCommitOrder() { .containsExactly(binding.canonicalBytes()); } + @Test + void authenticatedGameLogicPeerGetsHeldOnlyForExactRequiredOwnerBinding() { + var repository = mock(DraftAuthorizationFenceRepository.class); + var manager = mock(PlatformTransactionManager.class); + var transactionStatus = mock(TransactionStatus.class); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + var binding = AccountDraftCommitOrderReadServiceTest.bindingWithGameLogic(1); + when(repository.readOriginalBinding(binding.operationId())).thenReturn(Optional.of(binding)); + when(repository.read(binding)) + .thenReturn(new FenceSnapshot(Ordering.COMMIT_ORDER, binding.canonicalBytes(), null, null)); + when(repository.readSettlement(binding)).thenReturn(Settlement.PENDING); + var service = + new AccountDraftCommitOrderReadGrpcService( + new AccountDraftCommitOrderReadService(repository, manager, "test"), "test"); + var request = AccountDraftCommitOrderReadServiceTest.request(binding); + Collector result = new Collector(); + + asPeer( + "spiffe://firemud/ns/test/sa/game-logic-service", + () -> + service.readHeldOriginalCommitOrder( + DraftCommitOrderReadGrpcCodec.toRequest(request), result)); + + assertThat(result.errorStatus).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.value.getStatus()) + .isEqualTo(HeldOriginalCommitOrderStatus.HELD_ORIGINAL_COMMIT_ORDER_STATUS_HELD); + assertThat(result.value.getOriginalAccountBinding().toByteArray()) + .containsExactly(binding.canonicalBytes()); + } + + @Test + void gameLogicPeerCannotReadWorldOnlyBindingOrOpenOwnerTransaction() { + var repository = mock(DraftAuthorizationFenceRepository.class); + var manager = mock(PlatformTransactionManager.class); + var service = + new AccountDraftCommitOrderReadGrpcService( + new AccountDraftCommitOrderReadService(repository, manager, "test"), "test"); + var binding = AccountDraftCommitOrderReadServiceTest.binding(1); + Collector result = new Collector(); + + asPeer( + "spiffe://firemud/ns/test/sa/game-logic-service", + () -> + service.readHeldOriginalCommitOrder( + DraftCommitOrderReadGrpcCodec.toRequest( + AccountDraftCommitOrderReadServiceTest.request(binding)), + result)); + + assertThat(result.errorStatus.getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(result.value).isNull(); + assertThat(result.completed).isFalse(); + verifyNoInteractions(repository, manager); + } + @Test void invalidCanonicalRequestAndUnheldOperationNeverProducePositiveResponse() { var repository = mock(DraftAuthorizationFenceRepository.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadServiceTest.java index 3851be893a..612711a3fd 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadServiceTest.java @@ -13,6 +13,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.time.OffsetDateTime; +import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; @@ -76,6 +77,38 @@ void acceptsOnlyExactHeldOriginalCommitOrderInOwnedWritableReadCommittedTransact verify(repository).readSettlement(binding); } + @Test + void acceptsGameLogicOnlyWhenExactV2BindingRequiresGameLogic() { + var binding = bindingWithGameLogic(1); + assertThat(binding.schemaVersion()).isEqualTo(DraftAuthorizationFenceBinding.SCHEMA_V2); + assertThat(binding.requiredOwners()).contains(DraftAuthorizationFenceBinding.Owner.GAME_LOGIC); + var request = request(binding); + when(manager.getTransaction(any())).thenReturn(transactionStatus); + when(repository.readOriginalBinding(binding.operationId())).thenReturn(Optional.of(binding)); + when(repository.read(binding)) + .thenReturn(new FenceSnapshot(Ordering.COMMIT_ORDER, binding.canonicalBytes(), null, null)); + when(repository.readSettlement(binding)).thenReturn(Settlement.PENDING); + + asGameLogic(() -> service.requireHeld(request)); + + verify(manager).getTransaction(any()); + verify(manager).commit(transactionStatus); + verify(repository).readOriginalBinding(binding.operationId()); + verify(repository).read(binding); + verify(repository).readSettlement(binding); + } + + @Test + void deniesGameLogicForWorldOnlyBindingBeforeOwnerTransactionOrStorage() { + var binding = binding(1); + + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> asGameLogic(() -> service.requireHeld(request(binding)))); + + verifyNoInteractions(repository, manager); + } + @Test void deniesAbsentChangedReservedRevokedAndSettledOperationsWithoutChangingOwnerState() { var original = binding(1); @@ -149,10 +182,26 @@ void rejectsMissingWrongWorkloadAndAmbientTransactionBeforeRepositoryOrOwnerTran asPeer( "spiffe://firemud/ns/other/sa/world-management-service", () -> service.requireHeld(request))); + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "spiffe://firemud/ns/other/sa/game-logic-service", + () -> service.requireHeld(request))); + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "spiffe://firemud/ns/test/sa/game-session-service", + () -> service.requireHeld(request))); TransactionSynchronizationManager.setActualTransactionActive(true); assertStatus( Status.Code.FAILED_PRECONDITION, () -> asWorld(() -> service.requireHeld(request))); + var gameLogicBinding = bindingWithGameLogic(1); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameLogic(() -> service.requireHeld(request(gameLogicBinding)))); verifyNoInteractions(repository, manager); } @@ -193,6 +242,10 @@ private static void asWorld(Runnable call) { asPeer("spiffe://firemud/ns/test/sa/world-management-service", call); } + private static void asGameLogic(Runnable call) { + asPeer("spiffe://firemud/ns/test/sa/game-logic-service", call); + } + private static void asPeer(String uri, Runnable call) { var peer = GrpcPeerIdentity.parseUri(uri).orElseThrow(); var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); @@ -213,22 +266,29 @@ static DraftCommitOrderReadEvidence.Request request(DraftAuthorizationFenceBindi } static DraftAuthorizationFenceBinding binding(long sourceGeneration) { + return binding(sourceGeneration, false); + } + + static DraftAuthorizationFenceBinding bindingWithGameLogic(long sourceGeneration) { + return binding(sourceGeneration, true); + } + + private static DraftAuthorizationFenceBinding binding( + long sourceGeneration, boolean gameLogicRequired) { UUID tenant = uuid("11111111-1111-4111-8111-111111111111"); UUID version = uuid("22222222-2222-4222-8222-222222222222"); UUID request = uuid("44444444-4444-4444-8444-444444444444"); UUID commit = uuid("55555555-5555-4555-8555-555555555555"); - DraftCommitBinding draft = - DraftCommitBinding.create( - new TargetProof(tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), - request, - commit, - "base-1", + List revisions = + new ArrayList<>( List.of( new RevisionPayload( "0", uuid("66666666-6666-4666-8666-666666666666"), DraftCommitBinding.Owner.WORLD_MANAGEMENT, - "{}")), + "{}"))); + List affectedUnits = + new ArrayList<>( List.of( new AffectedUnit( DraftCommitBinding.Owner.WORLD_MANAGEMENT, @@ -237,29 +297,58 @@ static DraftAuthorizationFenceBinding binding(long sourceGeneration) { "ROOM_SCOPE", "room-1", "0"))); + if (gameLogicRequired) { + revisions.add( + new RevisionPayload( + "1", + uuid("77777777-7777-4777-8777-777777777777"), + DraftCommitBinding.Owner.GAME_LOGIC, + "{}")); + affectedUnits.add( + new AffectedUnit( + DraftCommitBinding.Owner.GAME_LOGIC, + "RULE_SET", + "rules-1", + "AGGREGATE", + "rules-1", + "0")); + } + DraftCommitBinding draft = + DraftCommitBinding.create( + new TargetProof(tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + "base-1", + revisions, + affectedUnits); byte[] draftBytes = draft.canonicalBytes(); - return new DraftAuthorizationFenceBinding( - uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), - request, - commit, - uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), - uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), - tenant, - version, - "base-1", - "0", - draftBytes, - draftBytes, - draft.digest(), - List.of( - new SourceEvidence( - SourceKind.GLOBAL_ROLES, - "dddddddd-dddd-4ddd-8ddd-dddddddddddd", - null, - Long.toString(sourceGeneration), - null, - null, - new byte[] {1}))); + DraftAuthorizationFenceBinding binding = + new DraftAuthorizationFenceBinding( + uuid( + gameLogicRequired + ? "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab" + : "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request, + commit, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + tenant, + version, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + null, + Long.toString(sourceGeneration), + null, + null, + new byte[] {1}))); + return gameLogicRequired ? binding.withRequiredOwners() : binding; } private static UUID uuid(String value) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcServiceTest.java new file mode 100644 index 0000000000..7f34ac6a63 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadGrpcServiceTest.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; + +class AccountGameLogicIntakeAuthorizationReadGrpcServiceTest { + @Test + void callerAuthenticationPrecedesBindingParsingAndRepositoryAccess() { + var owner = mock(AccountGameLogicIntakeAuthorizationReadService.class); + var service = new AccountGameLogicIntakeAuthorizationReadGrpcService(owner, "test"); + var malformed = + ReadHeldGameLogicIntakeAuthorizationRequest.newBuilder().setSchemaVersion(-1).build(); + var missing = new Collector(); + service.readHeldGameLogicIntakeAuthorization(malformed, missing); + assertThat(missing.error).isEqualTo(Status.Code.UNAUTHENTICATED); + for (var caller : + new String[] {"world-management-service", "account-service", "game-design-service"}) { + var result = new Collector(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/" + caller).orElseThrow()) + .run(() -> service.readHeldGameLogicIntakeAuthorization(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + var allowedMalformed = new Collector(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-logic-service") + .orElseThrow()) + .run(() -> service.readHeldGameLogicIntakeAuthorization(malformed, allowedMalformed)); + assertThat(allowedMalformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + private static final class Collector + implements StreamObserver { + Status.Code error; + + public void onNext(ReadHeldGameLogicIntakeAuthorizationResponse value) { + throw new AssertionError("No positive result"); + } + + public void onError(Throwable value) { + error = Status.fromThrowable(value).getCode(); + } + + public void onCompleted() { + throw new AssertionError("No successful read"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java new file mode 100644 index 0000000000..45f8c54856 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; + +/** Distinct GL retention permission input. Only Account's genuine producer may establish HELD. */ +public record GameLogicIntakeAuthorizationBinding( + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + UUID actorAccountId, + GameplayRuleSelectedSource source, + List sources) { + public static final String SCHEMA = "account-game-logic-intake-authorization/v1"; + + public GameLogicIntakeAuthorizationBinding { + for (var id : List.of(operationId, fenceId, intakeRequestId, actorAccountId)) + DraftAuthorizationFenceBinding.requireUuid(id); + Objects.requireNonNull(source); + sources = + List.copyOf(Objects.requireNonNull(sources)).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) + throw new IllegalArgumentException("Complete distinct Account sources required"); + for (var value : sources) { + String scope = + switch (value.kind()) { + case ACCOUNT, GLOBAL_ROLES -> actorAccountId.toString(); + case TENANT -> tenantId(source).toString(); + case MEMBERSHIP -> actorAccountId + "/" + tenantId(source); + default -> null; + }; + if (scope != null && !scope.equals(value.scopeId())) + throw new IllegalArgumentException("Intake source differs from actor/tenant"); + } + } + + private static UUID tenantId(GameplayRuleSelectedSource source) { + return source.binding().target().canonicalTenantId(); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + public UUID tenantId() { + return tenantId(source); + } + + public UUID versionId() { + return source.binding().target().canonicalVersionId(); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + for (var id : List.of(operationId, fenceId, intakeRequestId, actorAccountId)) + DraftAuthorizationFenceBinding.frame(out, id.toString()); + DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(sources.size())); + for (var value : sources) DraftAuthorizationFenceBinding.frame(out, value.canonicalBytes()); + if (out.size() > 4194304) throw new IllegalArgumentException("Intake order exceeds 4 MiB"); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static GameLogicIntakeAuthorizationBinding fromStored(byte[] bytes) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + UUID operation = uuid(reader.text()), + fence = uuid(reader.text()), + request = uuid(reader.text()), + actor = uuid(reader.text()); + var source = new GameplayRuleSelectedSource(new String(reader.bytes(), StandardCharsets.UTF_8)); + String countText = reader.text(); + DraftAuthorizationFenceBinding.decimal(countText, false); + int count = Integer.parseInt(countText); + if (count > reader.remaining() / Integer.BYTES) + throw new IllegalArgumentException("Incomplete source vector"); + var sources = new java.util.ArrayList(); + for (int i = 0; i < count; i++) sources.add(SourceEvidence.fromStored(reader.bytes())); + reader.requireEnd(); + var result = + new GameLogicIntakeAuthorizationBinding(operation, fence, request, actor, source, sources); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical intake order"); + return result; + } + + private static UUID uuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java new file mode 100644 index 0000000000..dadb56b705 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** + * Explicit file-backed mTLS client for the exact same-namespace Account intake authorization read. + */ +public final class GameLogicIntakeAuthorizationReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountGameLogicIntakeAuthorizationReadServiceGrpc + .AccountGameLogicIntakeAuthorizationReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameLogicIntakeAuthorizationReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameLogicIntakeAuthorizationReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) + throw new IllegalStateException("Account GL intake authorization read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account GL intake authorization read stub unavailable"); + initialized = true; + } + + /** Returns a validated HELD result only after exact Account server mTLS identity verification. */ + public GameLogicIntakeAuthorizationReadEvidence read( + GameLogicIntakeAuthorizationReadEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + throw new IllegalStateException("Account intake transport must run outside SQL"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account GL intake authorization read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readHeldGameLogicIntakeAuthorization( + GameLogicIntakeAuthorizationReadGrpcCodec.toRequest(request)); + try { + return GameLogicIntakeAuthorizationReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Account returned invalid COMMIT_ORDER evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountGameLogicIntakeAuthorizationReadServiceGrpc + .AccountGameLogicIntakeAuthorizationReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountGameLogicIntakeAuthorizationReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountGameLogicIntakeAuthorizationReadServiceGrpc + .AccountGameLogicIntakeAuthorizationReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account GL intake authorization read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account GL intake authorization read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account GL intake authorization read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadEvidence.java new file mode 100644 index 0000000000..5ce523813d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadEvidence.java @@ -0,0 +1,30 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Lookup tuple only. HELD must come from the authenticated Account read. */ +public record GameLogicIntakeAuthorizationReadEvidence(Request request) { + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + GameLogicIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Supported intake read schema and namespace required"); + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + Objects.requireNonNull(binding); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.fenceId()) + || readRequestId.equals(binding.intakeRequestId())) + throw new IllegalArgumentException("Separate transport correlation required"); + } + + public static Request create(String namespace, GameLogicIntakeAuthorizationBinding binding) { + return new Request(1, namespace, UUID.randomUUID(), binding); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadGrpcCodec.java new file mode 100644 index 0000000000..3c68268515 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadGrpcCodec.java @@ -0,0 +1,59 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldGameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Exact closed HELD wire mapping; authentication precedes decoding at the receiver. */ +public final class GameLogicIntakeAuthorizationReadGrpcCodec { + private GameLogicIntakeAuthorizationReadGrpcCodec() {} + + public static ReadHeldGameLogicIntakeAuthorizationRequest toRequest( + GameLogicIntakeAuthorizationReadEvidence.Request value) { + return ReadHeldGameLogicIntakeAuthorizationRequest.newBuilder() + .setSchemaVersion(value.schemaVersion()) + .setTargetNamespace(value.targetNamespace()) + .setReadRequestId(value.readRequestId().toString()) + .setOriginalIntakeAuthorization(ByteString.copyFrom(value.binding().canonicalBytes())) + .setIntakeAuthorizationDigest(value.binding().digest()) + .build(); + } + + public static GameLogicIntakeAuthorizationReadEvidence.Request fromRequest( + ReadHeldGameLogicIntakeAuthorizationRequest value) { + if (!value.getUnknownFields().asMap().isEmpty()) + throw new IllegalArgumentException("Unknown intake read fields"); + DraftAuthorizationFenceBinding.canonicalUuid(value.getReadRequestId()); + var binding = + GameLogicIntakeAuthorizationBinding.fromStored( + value.getOriginalIntakeAuthorization().toByteArray()); + if (!binding.digest().equals(value.getIntakeAuthorizationDigest())) + throw new IllegalArgumentException("Changed intake digest"); + return new GameLogicIntakeAuthorizationReadEvidence.Request( + value.getSchemaVersion(), + value.getTargetNamespace(), + UUID.fromString(value.getReadRequestId()), + binding); + } + + public static ReadHeldGameLogicIntakeAuthorizationResponse toHeldResponse( + GameLogicIntakeAuthorizationReadEvidence.Request request) { + return ReadHeldGameLogicIntakeAuthorizationResponse.newBuilder() + .setRequest(toRequest(request)) + .setHeld(true) + .build(); + } + + public static GameLogicIntakeAuthorizationReadEvidence fromResponse( + GameLogicIntakeAuthorizationReadEvidence.Request request, + ReadHeldGameLogicIntakeAuthorizationResponse response) { + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || !response.getHeld()) + throw new IllegalArgumentException("Exact held intake response required"); + return new GameLogicIntakeAuthorizationReadEvidence(request); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifest.java new file mode 100644 index 0000000000..9d5522b858 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifest.java @@ -0,0 +1,1160 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed authored input grammar. This value is neither source provenance nor mutation authority. + */ +public record GameplayRuleManifest(Map> families) { + public static final String SCHEMA = "gameplay-rule-manifest/v1"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) + .build(); + + public enum Family { + STATS, + RESOURCES, + CONDITIONS, + EFFECTS, + ABILITIES, + ACTIONS, + COMMANDS, + ADMISSION_TAGS, + DISPOSITIONS, + CONTINUOUS_OVERLAYS, + OBSERVATION_POLICIES, + TARGETING_POLICIES, + SELECTION_POLICIES, + DEFAULT_BINDINGS, + FEEDBACK + } + + public enum PrimitiveKind { + NUMERIC, + BOOLEAN_FLAG + } + + public enum Visibility { + PUBLIC, + PRIVATE, + NON_DISCLOSING + } + + public enum Lifecycle { + CONTINUOUS, + INSTANT + } + + public enum EffectOperation { + ADD, + MULTIPLY, + CLAMP_MIN, + CLAMP_MAX, + ADJUST_RESOURCE, + APPLY_CONDITION, + REMOVE_CONDITION + } + + public enum StatField { + VALUE, + MAXIMUM + } + + public enum CapacityChangePolicy { + CLAMP_ONLY, + PRESERVE_RATIO, + PRESERVE_DEFICIT + } + + public enum Reapplication { + REPLACE, + REFRESH, + STACK, + PARALLEL + } + + public enum DurationPolicy { + RESET, + EXTEND, + PRESERVE_LONGER + } + + public enum CommitPolicy { + ON_EXECUTION, + ON_EFFECT_SUCCESS + } + + public enum CandidateSelector { + SELF, + DIRECT_ACTOR + } + + public enum Cardinality { + EXACTLY_ONE, + UP_TO_N, + ALL_ELIGIBLE + } + + public enum SelectionStrategy { + PLAYER_SELECTED, + CANONICAL_ORDER, + RANKED, + RANDOM_SEEDED + } + + public enum Direction { + ASCENDING, + DESCENDING + } + + public enum ActorRole { + SOURCE, + TARGET + } + + public enum PredicateKind { + TRUE, + FALSE, + ALL, + ANY, + NOT, + STAT_COMPARE, + CONDITION_PRESENT, + DISPOSITION_EQUALS + } + + public enum Comparison { + EQ, + NE, + LT, + LE, + GT, + GE + } + + public enum Audience { + SOURCE_ACTOR, + DIRECT_TARGET, + AUTHORIZED_OBSERVER + } + + public enum ArgumentKind { + TEXT, + NUMBER, + BOOLEAN, + ACTOR_ID + } + + public enum ReplayPolicy { + EFFECT_IDEMPOTENT + } + + public enum Stage { + NONE, + LOGIN, + GAMEPLAY + } + + public enum PromptPolicy { + NEVER, + WHEN_LOGGED_IN, + WHEN_GAMEPLAY + } + + public enum ActionCategory { + GAMEPLAY, + SOCIAL, + META, + ADMIN, + SYSTEM + } + + public enum ExecutionDiscipline { + DURABLE_GAMEPLAY + } + + public enum ActionTag { + MOVEMENT, + COMMUNICATION, + COMBAT, + INVENTORY, + WORLD_BROWSE, + SOCIAL_PRESENCE, + AUTHORING, + SESSION, + UI + } + + public sealed interface Definition + permits Stat, + Resource, + Condition, + Effect, + Ability, + Action, + Command, + AdmissionTag, + Disposition, + ContinuousOverlay, + ObservationPolicy, + TargetingPolicy, + SelectionPolicy, + DefaultBinding, + Feedback { + String key(); + + Family family(); + } + + public record Stat( + String statKey, + PrimitiveKind primitiveKind, + BigDecimal baseValue, + Boolean flagValue, + BigDecimal minimum, + BigDecimal maximum, + Visibility visibility, + List tags) + implements Definition { + public Stat { + identifier(statKey); + Objects.requireNonNull(primitiveKind); + Objects.requireNonNull(visibility); + numbers(baseValue, minimum, maximum); + tags = keys(tags); + if (primitiveKind == PrimitiveKind.NUMERIC) { + Objects.requireNonNull(baseValue); + bounds(minimum, baseValue, maximum); + absent(flagValue); + } else { + Objects.requireNonNull(flagValue); + absent(baseValue, minimum, maximum); + } + } + + @Override + public String key() { + return statKey; + } + + @Override + public Family family() { + return Family.STATS; + } + + public List tags() { + return List.copyOf(tags); + } + } + + /** A BOUNDED_RESOURCE is one typed resource, never an invented max_ key. */ + public record Resource( + String statKey, + BigDecimal defaultCurrent, + BigDecimal minimum, + BigDecimal defaultMaximum, + BigDecimal hardMaximum, + Visibility visibility, + List tags) + implements Definition { + public Resource { + identifier(statKey); + Objects.requireNonNull(defaultCurrent); + Objects.requireNonNull(minimum); + Objects.requireNonNull(defaultMaximum); + Objects.requireNonNull(hardMaximum); + Objects.requireNonNull(visibility); + tags = keys(tags); + numbers(defaultCurrent, minimum, defaultMaximum, hardMaximum); + bounds(minimum, defaultCurrent, defaultMaximum); + bounds(minimum, defaultMaximum, hardMaximum); + } + + @Override + public String key() { + return statKey; + } + + @Override + public Family family() { + return Family.RESOURCES; + } + + public List tags() { + return List.copyOf(tags); + } + } + + public record Condition( + String conditionKey, + Reapplication reapplication, + DurationPolicy durationPolicy, + Long durationTicks, + Integer maximumStacks, + Visibility visibility, + List tags, + List effectKeys, + int removalPriority) + implements Definition { + public Condition { + identifier(conditionKey); + Objects.requireNonNull(reapplication); + Objects.requireNonNull(durationPolicy); + Objects.requireNonNull(visibility); + tags = keys(tags); + effectKeys = keys(effectKeys); + ticks(Objects.requireNonNull(durationTicks)); + if (reapplication == Reapplication.STACK) { + if (maximumStacks == null || maximumStacks < 1) fail("STACK requires maximumStacks"); + } else absent(maximumStacks); + } + + @Override + public String key() { + return conditionKey; + } + + @Override + public Family family() { + return Family.CONDITIONS; + } + + public List tags() { + return List.copyOf(tags); + } + + public List effectKeys() { + return List.copyOf(effectKeys); + } + } + + public record Effect( + String effectKey, + Lifecycle lifecycle, + EffectOperation operation, + String statKey, + StatField statField, + BigDecimal amount, + String conditionKey, + CapacityChangePolicy capacityChangePolicy) + implements Definition { + public Effect { + identifier(effectKey); + Objects.requireNonNull(lifecycle); + Objects.requireNonNull(operation); + numbers(amount); + switch (operation) { + case ADD, MULTIPLY, CLAMP_MIN, CLAMP_MAX -> { + if (lifecycle != Lifecycle.CONTINUOUS) fail("Derived-state modifiers are CONTINUOUS"); + identifier(statKey); + Objects.requireNonNull(statField); + Objects.requireNonNull(amount); + absent(conditionKey); + if (statField != StatField.MAXIMUM) absent(capacityChangePolicy); + } + case ADJUST_RESOURCE -> { + if (lifecycle != Lifecycle.INSTANT) fail("Resource adjustment is INSTANT"); + identifier(statKey); + Objects.requireNonNull(amount); + absent(statField, conditionKey, capacityChangePolicy); + } + case APPLY_CONDITION, REMOVE_CONDITION -> { + if (lifecycle != Lifecycle.INSTANT) fail("Condition mutation is INSTANT"); + identifier(conditionKey); + absent(statKey, statField, amount, capacityChangePolicy); + } + } + } + + @Override + public String key() { + return effectKey; + } + + @Override + public Family family() { + return Family.EFFECTS; + } + } + + public record Ability(String abilityId, String name, String actionSequenceId) + implements Definition { + public Ability { + identifier(abilityId); + text(name); + identifier(actionSequenceId); + } + + @Override + public String key() { + return abilityId; + } + + @Override + public Family family() { + return Family.ABILITIES; + } + } + + public record Cost(String statKey, BigDecimal amount, CommitPolicy commitPolicy) { + public Cost { + identifier(statKey); + Objects.requireNonNull(amount); + Objects.requireNonNull(commitPolicy); + numbers(amount); + if (amount.signum() < 0) fail("Cost cannot be negative"); + } + } + + public record Cooldown(String cooldownKey, long durationTicks, CommitPolicy commitPolicy) { + public Cooldown { + identifier(cooldownKey); + Objects.requireNonNull(commitPolicy); + ticks(durationTicks); + } + } + + public record TargetSet( + String targetSetKey, + String targetingPolicyKey, + String targetSelectionPolicyKey, + boolean required, + String unresolvedFeedbackKey, + String playerSelectorInputSlot) { + public TargetSet { + identifier(targetSetKey); + identifier(targetingPolicyKey); + identifier(targetSelectionPolicyKey); + if ("SOURCE".equals(targetSetKey)) fail("SOURCE is the implicit reserved target set"); + if (required) absent(unresolvedFeedbackKey); + else identifier(unresolvedFeedbackKey); + if (playerSelectorInputSlot != null) identifier(playerSelectorInputSlot); + } + } + + public record EffectBinding(String effectKey, String targetSetKey) { + public EffectBinding { + identifier(effectKey); + identifier(targetSetKey); + } + } + + public record Action( + String actionSequenceId, + String name, + List admissionTags, + List targetSets, + List costs, + List cooldowns, + List effects, + List feedbackKeys) + implements Definition { + public Action { + identifier(actionSequenceId); + text(name); + admissionTags = keys(admissionTags); + targetSets = copy(targetSets); + costs = copy(costs); + cooldowns = copy(cooldowns); + effects = copy(effects); + feedbackKeys = keys(feedbackKeys); + unique(targetSets.stream().map(TargetSet::targetSetKey).toList()); + unique(cooldowns.stream().map(Cooldown::cooldownKey).toList()); + Set targets = + new HashSet<>(targetSets.stream().map(TargetSet::targetSetKey).toList()); + targets.add("SOURCE"); + for (EffectBinding effect : effects) + if (!targets.contains(effect.targetSetKey())) fail("Effect uses undeclared target set"); + } + + @Override + public String key() { + return actionSequenceId; + } + + @Override + public Family family() { + return Family.ACTIONS; + } + + public List admissionTags() { + return List.copyOf(admissionTags); + } + + public List targetSets() { + return List.copyOf(targetSets); + } + + public List costs() { + return List.copyOf(costs); + } + + public List cooldowns() { + return List.copyOf(cooldowns); + } + + public List effects() { + return List.copyOf(effects); + } + + public List feedbackKeys() { + return List.copyOf(feedbackKeys); + } + } + + public record Command( + String commandId, + String actionSequenceId, + String semanticOwner, + ExecutionDiscipline executionDiscipline, + Stage stageRequirement, + PromptPolicy promptPolicy, + ActionCategory actionCategory, + boolean historyRecordable, + List aliases, + List actionTags, + List admissionTags) + implements Definition { + public Command { + identifier(commandId); + identifier(actionSequenceId); + text(semanticOwner); + Objects.requireNonNull(executionDiscipline); + Objects.requireNonNull(stageRequirement); + Objects.requireNonNull(promptPolicy); + Objects.requireNonNull(actionCategory); + aliases = keys(aliases); + actionTags = copy(actionTags); + admissionTags = keys(admissionTags); + if (new HashSet<>(actionTags).size() != actionTags.size()) fail("Duplicate action tag"); + } + + @Override + public String key() { + return commandId; + } + + @Override + public Family family() { + return Family.COMMANDS; + } + + public List aliases() { + return List.copyOf(aliases); + } + + public List actionTags() { + return List.copyOf(actionTags); + } + + public List admissionTags() { + return List.copyOf(admissionTags); + } + } + + public record AdmissionTag(String tagKey) implements Definition { + public AdmissionTag { + identifier(tagKey); + } + + @Override + public String key() { + return tagKey; + } + + @Override + public Family family() { + return Family.ADMISSION_TAGS; + } + } + + public record Disposition( + String dispositionKey, List deniedAdmissionTags, String safeFeedbackKey) + implements Definition { + public Disposition { + identifier(dispositionKey); + deniedAdmissionTags = keys(deniedAdmissionTags); + identifier(safeFeedbackKey); + } + + @Override + public String key() { + return dispositionKey; + } + + @Override + public Family family() { + return Family.DISPOSITIONS; + } + + public List deniedAdmissionTags() { + return List.copyOf(deniedAdmissionTags); + } + } + + public record ContinuousOverlay( + String overlayKey, + Predicate eligibleWhen, + List deniedAdmissionTags, + List effectKeys) + implements Definition { + public ContinuousOverlay { + identifier(overlayKey); + Objects.requireNonNull(eligibleWhen); + deniedAdmissionTags = keys(deniedAdmissionTags); + effectKeys = keys(effectKeys); + } + + @Override + public String key() { + return overlayKey; + } + + @Override + public Family family() { + return Family.CONTINUOUS_OVERLAYS; + } + + public List deniedAdmissionTags() { + return List.copyOf(deniedAdmissionTags); + } + + public List effectKeys() { + return List.copyOf(effectKeys); + } + } + + /** Only already declared Entity-owned actor facts; spatial/relationship extensions deny. */ + public record Predicate( + PredicateKind kind, + ActorRole actor, + String factKey, + Comparison comparison, + BigDecimal number, + List operands) { + public Predicate { + Objects.requireNonNull(kind); + operands = copy(operands); + numbers(number); + if (operands.size() > 64) fail("Predicate operand ceiling exceeded"); + switch (kind) { + case TRUE, FALSE -> { + absent(actor, factKey, comparison, number); + empty(operands); + } + case ALL, ANY, NOT -> { + absent(actor, factKey, comparison, number); + if (operands.isEmpty() || kind == PredicateKind.NOT && operands.size() != 1) + fail("Invalid predicate operands"); + } + case STAT_COMPARE -> { + Objects.requireNonNull(actor); + identifier(factKey); + Objects.requireNonNull(comparison); + Objects.requireNonNull(number); + empty(operands); + } + case CONDITION_PRESENT, DISPOSITION_EQUALS -> { + Objects.requireNonNull(actor); + identifier(factKey); + absent(comparison, number); + empty(operands); + } + } + } + + public List operands() { + return List.copyOf(operands); + } + } + + public record ObservationPolicy(String observationPolicyKey, Predicate observableWhen) + implements Definition { + public ObservationPolicy { + identifier(observationPolicyKey); + Objects.requireNonNull(observableWhen); + } + + @Override + public String key() { + return observationPolicyKey; + } + + @Override + public Family family() { + return Family.OBSERVATION_POLICIES; + } + } + + public record TargetingPolicy( + String targetingPolicyKey, + CandidateSelector candidateSelector, + String observationPolicyKey, + Predicate eligibleWhen, + String safeFailureFeedbackKey) + implements Definition { + public TargetingPolicy { + identifier(targetingPolicyKey); + Objects.requireNonNull(candidateSelector); + identifier(observationPolicyKey); + Objects.requireNonNull(eligibleWhen); + identifier(safeFailureFeedbackKey); + } + + @Override + public String key() { + return targetingPolicyKey; + } + + @Override + public Family family() { + return Family.TARGETING_POLICIES; + } + } + + public record RankComparator(String statKey, StatField statField, Direction direction) { + public RankComparator { + identifier(statKey); + Objects.requireNonNull(statField); + Objects.requireNonNull(direction); + } + } + + public record SelectionPolicy( + String targetSelectionPolicyKey, + Cardinality cardinality, + Integer minTargets, + Integer maxTargets, + SelectionStrategy strategy, + SelectionStrategy truncationStrategy, + List comparators) + implements Definition { + public SelectionPolicy { + identifier(targetSelectionPolicyKey); + Objects.requireNonNull(cardinality); + Objects.requireNonNull(strategy); + comparators = copy(comparators); + if (cardinality == Cardinality.UP_TO_N) { + if (minTargets == null + || maxTargets == null + || minTargets < 0 + || maxTargets < 1 + || minTargets > maxTargets) fail("UP_TO_N requires explicit valid bounds"); + } else absent(minTargets, maxTargets); + if (cardinality == Cardinality.ALL_ELIGIBLE) Objects.requireNonNull(truncationStrategy); + else absent(truncationStrategy); + if (strategy == SelectionStrategy.RANKED || truncationStrategy == SelectionStrategy.RANKED) { + if (comparators.isEmpty()) fail("RANKED requires comparators"); + } else empty(comparators); + } + + @Override + public String key() { + return targetSelectionPolicyKey; + } + + @Override + public Family family() { + return Family.SELECTION_POLICIES; + } + + public List comparators() { + return List.copyOf(comparators); + } + } + + public record DefaultBinding(String bindingKey, List targetSets) + implements Definition { + public DefaultBinding { + identifier(bindingKey); + targetSets = copy(targetSets); + unique(targetSets.stream().map(TargetSet::targetSetKey).toList()); + } + + @Override + public String key() { + return bindingKey; + } + + @Override + public Family family() { + return Family.DEFAULT_BINDINGS; + } + + public List targetSets() { + return List.copyOf(targetSets); + } + } + + public record Argument(String key, ArgumentKind kind) { + public Argument { + identifier(key); + Objects.requireNonNull(kind); + } + } + + public record Feedback( + String feedbackKey, + String outcomeEvent, + Audience audience, + String messageKey, + String messageTemplate, + List arguments, + Visibility visibility, + ReplayPolicy replayPolicy) + implements Definition { + public Feedback { + identifier(feedbackKey); + identifier(outcomeEvent); + Objects.requireNonNull(audience); + identifier(messageKey); + text(messageTemplate); + arguments = copy(arguments); + unique(arguments.stream().map(Argument::key).toList()); + Objects.requireNonNull(visibility); + Objects.requireNonNull(replayPolicy); + } + + @Override + public String key() { + return feedbackKey; + } + + @Override + public Family family() { + return Family.FEEDBACK; + } + + public List arguments() { + return List.copyOf(arguments); + } + } + + public GameplayRuleManifest { + Objects.requireNonNull(families, "Explicit complete family inventory required"); + if (!families.keySet().equals(Set.of(Family.values()))) fail("Missing/unknown rule family"); + EnumMap> retained = new EnumMap<>(Family.class); + families.forEach( + (family, definitions) -> { + List values = copy(definitions); + unique(values.stream().map(Definition::key).toList()); + for (Definition definition : values) + if (definition.family() != family) fail("Definition belongs to another family"); + retained.put(family, values); + }); + families = java.util.Collections.unmodifiableMap(retained); + validateReferences(families); + } + + /** Only the actual fresh-source insertion transaction may use this as empty-source evidence. */ + public static GameplayRuleManifest explicitEmpty() { + EnumMap> families = new EnumMap<>(Family.class); + for (Family family : Family.values()) families.put(family, List.of()); + return new GameplayRuleManifest(families); + } + + public String canonicalJson() { + Map inventory = new LinkedHashMap<>(); + for (Family family : Family.values()) inventory.put(family.name(), families.get(family)); + return canonical(Map.of("schema", SCHEMA, "families", inventory)); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return sha256(canonicalBytes()); + } + + public static GameplayRuleManifest fromStored(String json) { + JsonNode root = tree(json); + fields(root, Set.of("schema", "families")); + if (!SCHEMA.equals(root.path("schema").asText())) fail("Unsupported manifest schema"); + Set names = new HashSet<>(); + for (Family family : Family.values()) names.add(family.name()); + fields(root.path("families"), names); + EnumMap> families = new EnumMap<>(Family.class); + for (Family family : Family.values()) { + JsonNode array = root.path("families").path(family.name()); + if (!array.isArray()) fail("Explicit family array required"); + List values = new ArrayList<>(); + for (JsonNode value : array) values.add(definition(family, canonical(value))); + families.put(family, values); + } + GameplayRuleManifest result = new GameplayRuleManifest(families); + if (!result.canonicalJson().equals(json)) fail("Noncanonical manifest"); + return result; + } + + public static Definition definition(Family family, String json) { + Class type = + switch (family) { + case STATS -> Stat.class; + case RESOURCES -> Resource.class; + case CONDITIONS -> Condition.class; + case EFFECTS -> Effect.class; + case ABILITIES -> Ability.class; + case ACTIONS -> Action.class; + case COMMANDS -> Command.class; + case ADMISSION_TAGS -> AdmissionTag.class; + case DISPOSITIONS -> Disposition.class; + case CONTINUOUS_OVERLAYS -> ContinuousOverlay.class; + case OBSERVATION_POLICIES -> ObservationPolicy.class; + case TARGETING_POLICIES -> TargetingPolicy.class; + case SELECTION_POLICIES -> SelectionPolicy.class; + case DEFAULT_BINDINGS -> DefaultBinding.class; + case FEEDBACK -> Feedback.class; + }; + try { + Definition result = JSON.treeToValue(tree(json), type); + if (!canonical(result).equals(canonical(tree(json)))) + fail("Definition has coerced or omitted typed fields"); + return result; + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Invalid typed rule definition", invalid); + } + } + + private static void validateReferences(Map> families) { + Map> keys = new EnumMap<>(Family.class); + families.forEach( + (family, values) -> + keys.put(family, Set.copyOf(values.stream().map(Definition::key).toList()))); + Set stats = new HashSet<>(keys.get(Family.STATS)); + for (String resource : keys.get(Family.RESOURCES)) + if (!stats.add(resource)) fail("Resource/stat key collision"); + Set numericStats = new HashSet<>(keys.get(Family.RESOURCES)); + for (Definition definition : families.get(Family.STATS)) { + Stat stat = (Stat) definition; + if (stat.primitiveKind() == PrimitiveKind.NUMERIC) numericStats.add(stat.key()); + } + for (List values : families.values()) + for (Definition definition : values) { + if (definition instanceof Condition value) refs(keys, Family.EFFECTS, value.effectKeys()); + else if (definition instanceof Effect value) { + if (value.statKey() != null) { + if (value.operation() == EffectOperation.ADJUST_RESOURCE + || value.statField() == StatField.MAXIMUM) + ref(keys, Family.RESOURCES, value.statKey()); + else if (!numericStats.contains(value.statKey())) + fail("Effect requires a declared numeric stat"); + } + if (value.conditionKey() != null) ref(keys, Family.CONDITIONS, value.conditionKey()); + } else if (definition instanceof Ability value) + ref(keys, Family.ACTIONS, value.actionSequenceId()); + else if (definition instanceof Action value) { + refs(keys, Family.ADMISSION_TAGS, value.admissionTags()); + targets(keys, families, value.targetSets()); + for (Cost cost : value.costs()) ref(keys, Family.RESOURCES, cost.statKey()); + for (EffectBinding effect : value.effects()) { + ref(keys, Family.EFFECTS, effect.effectKey()); + if (effect(families, effect.effectKey()).lifecycle() != Lifecycle.INSTANT) + fail("Action effect must be INSTANT"); + } + refs(keys, Family.FEEDBACK, value.feedbackKeys()); + } else if (definition instanceof Command value) { + ref(keys, Family.ACTIONS, value.actionSequenceId()); + refs(keys, Family.ADMISSION_TAGS, value.admissionTags()); + } else if (definition instanceof Disposition value) { + refs(keys, Family.ADMISSION_TAGS, value.deniedAdmissionTags()); + ref(keys, Family.FEEDBACK, value.safeFeedbackKey()); + } else if (definition instanceof ContinuousOverlay value) { + predicate(keys, numericStats, value.eligibleWhen(), 0); + refs(keys, Family.ADMISSION_TAGS, value.deniedAdmissionTags()); + refs(keys, Family.EFFECTS, value.effectKeys()); + for (String key : value.effectKeys()) + if (effect(families, key).lifecycle() != Lifecycle.CONTINUOUS) + fail("Overlay effect must be CONTINUOUS"); + } else if (definition instanceof ObservationPolicy value) + predicate(keys, numericStats, value.observableWhen(), 0); + else if (definition instanceof TargetingPolicy value) { + ref(keys, Family.OBSERVATION_POLICIES, value.observationPolicyKey()); + predicate(keys, numericStats, value.eligibleWhen(), 0); + ref(keys, Family.FEEDBACK, value.safeFailureFeedbackKey()); + } else if (definition instanceof SelectionPolicy value) { + for (RankComparator comparator : value.comparators()) { + if (!numericStats.contains(comparator.statKey())) + fail("Comparator requires a declared numeric stat"); + if (comparator.statField() == StatField.MAXIMUM) + ref(keys, Family.RESOURCES, comparator.statKey()); + } + } else if (definition instanceof DefaultBinding value) + targets(keys, families, value.targetSets()); + } + Set commandTokens = new HashSet<>(); + for (Definition definition : families.get(Family.COMMANDS)) { + Command command = (Command) definition; + for (String token : + java.util.stream.Stream.concat( + java.util.stream.Stream.of(command.key()), command.aliases().stream()) + .toList()) + if (!commandTokens.add(token.toLowerCase(java.util.Locale.ROOT))) + fail("Command token collision"); + } + } + + private static Effect effect(Map> families, String key) { + return (Effect) + families.get(Family.EFFECTS).stream() + .filter(value -> value.key().equals(key)) + .findFirst() + .orElseThrow(); + } + + private static void targets( + Map> keys, + Map> families, + List targets) { + for (TargetSet target : targets) { + ref(keys, Family.TARGETING_POLICIES, target.targetingPolicyKey()); + ref(keys, Family.SELECTION_POLICIES, target.targetSelectionPolicyKey()); + if (target.unresolvedFeedbackKey() != null) + ref(keys, Family.FEEDBACK, target.unresolvedFeedbackKey()); + SelectionPolicy policy = + (SelectionPolicy) + families.get(Family.SELECTION_POLICIES).stream() + .filter(value -> value.key().equals(target.targetSelectionPolicyKey())) + .findFirst() + .orElseThrow(); + if ((target.playerSelectorInputSlot() != null) + != (policy.strategy() == SelectionStrategy.PLAYER_SELECTED + || policy.truncationStrategy() == SelectionStrategy.PLAYER_SELECTED)) + fail("Target selector input does not match selection policy"); + } + } + + private static void predicate( + Map> keys, Set stats, Predicate value, int depth) { + if (depth > 32 || value.operands().size() > 64) fail("Predicate exceeds bounded grammar"); + switch (value.kind()) { + case STAT_COMPARE -> { + if (!stats.contains(value.factKey())) fail("Unknown predicate stat"); + } + case CONDITION_PRESENT -> ref(keys, Family.CONDITIONS, value.factKey()); + case DISPOSITION_EQUALS -> ref(keys, Family.DISPOSITIONS, value.factKey()); + default -> {} + } + for (Predicate operand : value.operands()) predicate(keys, stats, operand, depth + 1); + } + + private static void refs(Map> keys, Family family, List values) { + for (String value : values) ref(keys, family, value); + } + + private static void ref(Map> keys, Family family, String key) { + if (!keys.get(family).contains(key)) fail("Unresolved " + family + " reference: " + key); + } + + public static String canonical(Object value) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } catch (java.io.IOException | RuntimeException invalid) { + throw new IllegalArgumentException("Invalid rule JSON", invalid); + } + } + + public static JsonNode tree(String json) { + try { + return JSON.readTree(json); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Invalid rule JSON", invalid); + } + } + + public static void fields(JsonNode node, Set expected) { + Set actual = new HashSet<>(); + node.propertyNames().forEach(actual::add); + if (!node.isObject() || !actual.equals(expected)) fail("Unknown or missing rule fields"); + } + + public static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + public static void identifier(String value) { + if (value == null || !value.matches("[A-Za-z][A-Za-z0-9_.:-]{0,127}")) + fail("Invalid authored identifier"); + } + + private static void text(String value) { + if (value == null || value.isBlank()) fail("Required text missing"); + } + + private static List copy(List values) { + return List.copyOf(Objects.requireNonNull(values)); + } + + private static List keys(List values) { + List result = copy(values); + result.forEach(GameplayRuleManifest::identifier); + unique(result); + return result; + } + + private static void unique(List values) { + if (new HashSet<>(values).size() != values.size()) fail("Duplicate authored key"); + } + + private static void absent(Object... values) { + for (Object value : values) + if (value != null) fail("Field is not valid for this typed declaration"); + } + + private static void empty(List values) { + if (!values.isEmpty()) fail("Unexpected declaration values"); + } + + private static void bounds(BigDecimal minimum, BigDecimal value, BigDecimal maximum) { + if (minimum != null && value.compareTo(minimum) < 0 + || maximum != null && value.compareTo(maximum) > 0 + || minimum != null && maximum != null && minimum.compareTo(maximum) > 0) + fail("Invalid numeric bounds"); + } + + private static void numbers(BigDecimal... values) { + for (BigDecimal value : values) + if (value != null) { + double number = value.doubleValue(); + if (!Double.isFinite(number) || BigDecimal.valueOf(number).compareTo(value) != 0) + fail("Number cannot be retained exactly by the canonical JSON schema"); + } + } + + private static void ticks(long value) { + if (value < 1 || value > 9007199254740991L) + fail("Ticks must be a canonical positive safe integer"); + } + + private static void fail(String message) { + throw new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java new file mode 100644 index 0000000000..1cf9399f79 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Closed GD owner export. Structure and digest are not authentication of its producer. */ +public record GameplayRuleSelectedSource(String snapshotJson) { + public GameplayRuleSelectedSource { + if (snapshotJson == null || snapshotJson.getBytes(StandardCharsets.UTF_8).length > 4194304) + throw new IllegalArgumentException("Bounded complete GD source required"); + var root = GameplayRuleManifest.tree(snapshotJson); + GameplayRuleManifest.fields( + root, + Set.of( + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "manifestJson", + "entries")); + if (!"game-design-gameplay-rule-source-snapshot/v1".equals(text(root, "schema")) + || !root.path("entries").isArray() + || !text(root, "sourceEpoch").matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Complete supported GD rule snapshot required"); + var binding = + DraftCommitBinding.fromStored(text(root, "bindingJson"), text(root, "bindingDigest")); + DraftAuthorizationFenceBinding.canonicalUuid(text(root, "genesisReceiptId")); + String inherited = text(root, "inheritedCommitId"); + if (!inherited.isEmpty()) DraftAuthorizationFenceBinding.canonicalUuid(inherited); + var manifest = GameplayRuleManifest.fromStored(text(root, "manifestJson")); + Map> inventory = + new EnumMap<>(GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) + inventory.put(family, new ArrayList<>()); + for (var entry : root.path("entries")) { + GameplayRuleManifest.fields( + entry, + Set.of( + "family", + "definitionJson", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId")); + var family = GameplayRuleManifest.Family.valueOf(text(entry, "family")); + var origin = + DraftCommitBinding.fromStored( + text(entry, "sourceBindingJson"), text(entry, "sourceBindingDigest")); + if (!origin.target().equals(binding.target()) + || !text(entry, "revisionOrder").matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Selected rule provenance differs"); + String revisionId = text(entry, "revisionId"); + DraftAuthorizationFenceBinding.canonicalUuid(revisionId); + var definition = GameplayRuleManifest.definition(family, text(entry, "definitionJson")); + String expectedPayload = GameplayRuleSourceRevision.upsertPayload(definition); + boolean originalRevision = + origin.revisions().stream() + .anyMatch( + revision -> + revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE + && revision.revisionId().toString().equals(revisionId) + && revision.revisionOrder().equals(text(entry, "revisionOrder")) + && expectedPayload.equals( + GameplayRuleManifest.canonical( + GameplayRuleManifest.tree(revision.payload())))); + if (!originalRevision) + throw new IllegalArgumentException("Rule entry lacks exact original UPSERT revision"); + inventory.get(family).add(definition); + } + if (!manifest.equals(new GameplayRuleManifest(inventory)) + || !snapshotJson.equals(GameplayRuleManifest.canonical(root))) + throw new IllegalArgumentException("Selected manifest differs from complete snapshot"); + } + + public DraftCommitBinding binding() { + var root = GameplayRuleManifest.tree(snapshotJson); + return DraftCommitBinding.fromStored(text(root, "bindingJson"), text(root, "bindingDigest")); + } + + public GameplayRuleManifest manifest() { + return GameplayRuleManifest.fromStored( + text(GameplayRuleManifest.tree(snapshotJson), "manifestJson")); + } + + public byte[] canonicalBytes() { + return snapshotJson.getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return GameplayRuleManifest.sha256(canonicalBytes()); + } + + private static String text(tools.jackson.databind.JsonNode node, String name) { + if (!node.path(name).isTextual()) + throw new IllegalArgumentException("Text source field required"); + return node.path(name).textValue(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java new file mode 100644 index 0000000000..d5436b4f29 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignGameplayRuleSourceReadServiceGrpc; + +/** Explicit file-backed mTLS client for the exact same-namespace GD source read. */ +public final class GameplayRuleSourceReadClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignGameplayRuleSourceReadServiceGrpc + .GameDesignGameplayRuleSourceReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameplayRuleSourceReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameplayRuleSourceReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) + throw new IllegalStateException("Game Design complete gameplay source read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Game Design complete gameplay source read stub unavailable"); + initialized = true; + } + + /** Returns exact source evidence only after Game Design server mTLS identity verification. */ + public GameplayRuleSourceReadEvidence read(GameplayRuleSourceReadEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + throw new IllegalStateException("GD source transport must run outside SQL"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedGameplayRuleSource(GameplayRuleSourceReadGrpcCodec.toRequest(request)); + try { + return GameplayRuleSourceReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid complete source evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignGameplayRuleSourceReadServiceGrpc + .GameDesignGameplayRuleSourceReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignGameplayRuleSourceReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignGameplayRuleSourceReadServiceGrpc + .GameDesignGameplayRuleSourceReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Design complete gameplay source read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read " + label + " must be a file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Design complete gameplay source read " + + label + + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java new file mode 100644 index 0000000000..cfcad13524 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java @@ -0,0 +1,33 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact authenticated GD complete-source read; never a mutation authorization. */ +public record GameplayRuleSourceReadEvidence(Request request, GameplayRuleSelectedSource source) { + public GameplayRuleSourceReadEvidence { + Objects.requireNonNull(request); + Objects.requireNonNull(source); + if (!request.binding().equals(source.binding())) + throw new IllegalArgumentException("GD source differs from selected complete binding"); + } + + public record Request( + int schemaVersion, String targetNamespace, UUID readRequestId, DraftCommitBinding binding) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Supported source schema and namespace required"); + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + Objects.requireNonNull(binding); + if (readRequestId.equals(binding.requestId()) || readRequestId.equals(binding.commitId())) + throw new IllegalArgumentException("Separate source read correlation required"); + } + + public static Request create(String namespace, DraftCommitBinding binding) { + return new Request(1, namespace, UUID.randomUUID(), binding); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java new file mode 100644 index 0000000000..21a1ea17d8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceResponse; + +/** Closed wire and exact request/source correlation. Decode only after peer authentication. */ +public final class GameplayRuleSourceReadGrpcCodec { + private GameplayRuleSourceReadGrpcCodec() {} + + public static ReadSelectedGameplayRuleSourceRequest toRequest( + GameplayRuleSourceReadEvidence.Request value) { + return ReadSelectedGameplayRuleSourceRequest.newBuilder() + .setSchemaVersion(value.schemaVersion()) + .setTargetNamespace(value.targetNamespace()) + .setReadRequestId(value.readRequestId().toString()) + .setGameDesignBindingJson(value.binding().canonicalJson()) + .setGameDesignBindingDigest(value.binding().digest()) + .build(); + } + + public static GameplayRuleSourceReadEvidence.Request fromRequest( + ReadSelectedGameplayRuleSourceRequest value) { + if (!value.getUnknownFields().asMap().isEmpty()) + throw new IllegalArgumentException("Unknown source fields"); + DraftAuthorizationFenceBinding.canonicalUuid(value.getReadRequestId()); + return new GameplayRuleSourceReadEvidence.Request( + value.getSchemaVersion(), + value.getTargetNamespace(), + UUID.fromString(value.getReadRequestId()), + DraftCommitBinding.fromStored( + value.getGameDesignBindingJson(), value.getGameDesignBindingDigest())); + } + + public static ReadSelectedGameplayRuleSourceResponse toResponse( + GameplayRuleSourceReadEvidence evidence) { + return ReadSelectedGameplayRuleSourceResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setCompleteSourceSnapshotJson(evidence.source().snapshotJson()) + .setCompleteSourceSnapshotDigest(evidence.source().digest()) + .build(); + } + + public static GameplayRuleSourceReadEvidence fromResponse( + GameplayRuleSourceReadEvidence.Request request, + ReadSelectedGameplayRuleSourceResponse response) { + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !toRequest(request).equals(response.getRequest())) + throw new IllegalArgumentException("Changed source read correlation"); + var source = new GameplayRuleSelectedSource(response.getCompleteSourceSnapshotJson()); + if (!source.digest().equals(response.getCompleteSourceSnapshotDigest())) + throw new IllegalArgumentException("Changed source digest"); + return new GameplayRuleSourceReadEvidence(request, source); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceRevision.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceRevision.java new file mode 100644 index 0000000000..c313d0322a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceRevision.java @@ -0,0 +1,23 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Map; + +/** Existing canonical GD gameplay-rule UPSERT payload, shared with its provenance reader. */ +public final class GameplayRuleSourceRevision { + private GameplayRuleSourceRevision() {} + + public static String upsertPayload(GameplayRuleManifest.Definition definition) { + return GameplayRuleManifest.canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + "GAMEPLAY_RULE", + "operation", + "UPSERT", + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition))); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java new file mode 100644 index 0000000000..9dfc666c6c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java @@ -0,0 +1,181 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +class GameplayRuleSelectedSourceTest { + @Test + void retainsExactNonemptySourceAndRejectsSubstitutedOriginalRevision() { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + var binding = binding(GameplayRuleSourceRevision.upsertPayload(definition)); + var entry = entry(binding, definition); + var source = source(binding, List.of(entry), manifest(definition)); + assertThat(source.binding()).isEqualTo(binding); + assertThat(source.manifest()).isEqualTo(manifest(definition)); + var changed = new java.util.LinkedHashMap<>(entry); + changed.put("revisionId", UUID.randomUUID().toString()); + assertThatThrownBy(() -> source(binding, List.of(changed), manifest(definition))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> source(binding, List.of(), manifest(definition))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void distinctIntakeRoundTripsAndCannotDecodeAnOriginalDraftOrder() { + var binding = binding("{}"); + var source = source(binding, List.of(), GameplayRuleManifest.explicitEmpty()); + var actor = UUID.randomUUID(); + var evidence = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}); + var order = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(evidence)); + assertThat( + GameLogicIntakeAuthorizationBinding.fromStored(order.canonicalBytes()).canonicalBytes()) + .isEqualTo(order.canonicalBytes()); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + binding.requestId(), + binding.commitId(), + UUID.randomUUID(), + actor, + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.baseCommitId(), + "0", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of(evidence)) + .withRequiredOwners(); + assertThatThrownBy( + () -> GameLogicIntakeAuthorizationBinding.fromStored(original.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + var request = GameLogicIntakeAuthorizationReadEvidence.Request.create("test", order); + var response = GameLogicIntakeAuthorizationReadGrpcCodec.toHeldResponse(request); + assertThat(GameLogicIntakeAuthorizationReadGrpcCodec.fromResponse(request, response).request()) + .isEqualTo(request); + assertThatThrownBy( + () -> + GameLogicIntakeAuthorizationReadGrpcCodec.fromResponse( + request, response.toBuilder().setHeld(false).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void sourceReadRequiresExactCorrelationAndDigest() { + var binding = binding("{}"); + var source = source(binding, List.of(), GameplayRuleManifest.explicitEmpty()); + var request = GameplayRuleSourceReadEvidence.Request.create("test", binding); + var response = + GameplayRuleSourceReadGrpcCodec.toResponse( + new GameplayRuleSourceReadEvidence(request, source)); + assertThat(GameplayRuleSourceReadGrpcCodec.fromResponse(request, response).source()) + .isEqualTo(source); + assertThatThrownBy( + () -> + GameplayRuleSourceReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCompleteSourceSnapshotDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DraftCommitBinding binding(String payload) { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameplayRuleManifest manifest(GameplayRuleManifest.Definition definition) { + Map> values = + new EnumMap<>(GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) values.put(family, new ArrayList<>()); + values.get(definition.family()).add(definition); + return new GameplayRuleManifest(values); + } + + private static Map entry( + DraftCommitBinding binding, GameplayRuleManifest.Definition definition) { + return Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + binding.canonicalJson(), + "sourceBindingDigest", + binding.digest(), + "revisionOrder", + "0", + "revisionId", + binding.revisions().getFirst().revisionId().toString()); + } + + private static GameplayRuleSelectedSource source( + DraftCommitBinding binding, + List> entries, + GameplayRuleManifest manifest) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + entries))); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java index f9a780447e..1d18214398 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java @@ -152,7 +152,9 @@ public static List mutations(DraftCommitBinding binding) { if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; JsonNode payload = tree(revision.payload()); String kind = text(payload, "revisionKind"); - if ("COMMAND_DEFINITION".equals(kind) || "REALM_ENTRY_POLICY".equals(kind)) continue; + if ("COMMAND_DEFINITION".equals(kind) + || "REALM_ENTRY_POLICY".equals(kind) + || GameplayRuleSource.REVISION_KIND.equals(kind)) continue; if (!REVISION_KIND.equals(kind)) { throw new IllegalArgumentException("Unsupported Game Design asset source revision kind"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java index 249d747402..f1f690b685 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java @@ -156,7 +156,8 @@ public static List mutations(DraftCommitBinding binding) { } String revisionKind = payload.path("revisionKind").asText(); if (REALM_POLICY_REVISION_KIND.equals(revisionKind) - || AssetSource.REVISION_KIND.equals(revisionKind)) continue; + || AssetSource.REVISION_KIND.equals(revisionKind) + || GameplayRuleSource.REVISION_KIND.equals(revisionKind)) continue; if (!REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } @@ -206,7 +207,8 @@ public static boolean hasRealmPolicyRevision(DraftCommitBinding binding) { if (REALM_POLICY_REVISION_KIND.equals(revisionKind)) { found = true; } else if (!REVISION_KIND.equals(revisionKind) - && !AssetSource.REVISION_KIND.equals(revisionKind)) { + && !AssetSource.REVISION_KIND.equals(revisionKind) + && !GameplayRuleSource.REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java index 7151cf0d12..4d3e3c6cf8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java @@ -549,17 +549,21 @@ private void requireCompleteControlPlaneScopes( List policies = units.stream().filter(this::isPolicyScope).toList(); var assets = units.stream().filter(AssetSourceRepository::isScope).toList(); + var gameplay = units.stream().filter(GameplayRuleSource::isScope).toList(); boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); + boolean gameplayMutation = !GameplayRuleSource.mutations(binding).isEmpty(); if (commands.size() != (commandMutations.isEmpty() ? 0 : 1) || policies.size() != (policyMutation ? 1 : 0) || assets.size() != (assetMutation ? 1 : 0) - || commands.size() + policies.size() + assets.size() != units.size()) { + || gameplay.size() != (gameplayMutation ? 1 : 0) + || commands.size() + policies.size() + assets.size() + gameplay.size() != units.size()) { throw new IllegalArgumentException( "Complete supported Game Design control-plane scopes are required"); } if (!commands.isEmpty()) requireScopeTarget(commands.getFirst(), binding.target()); if (!policies.isEmpty()) requireScopeTarget(policies.getFirst(), binding.target()); if (!assets.isEmpty()) requireScopeTarget(assets.getFirst(), binding.target()); + if (!gameplay.isEmpty()) requireScopeTarget(gameplay.getFirst(), binding.target()); } private boolean isCommandScope(DraftCommitBinding.AffectedUnit unit) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcService.java new file mode 100644 index 0000000000..aff884a9d9 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcService.java @@ -0,0 +1,59 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.GameDesignGameplayRuleSourceReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceResponse; + +/** Standalone endpoint; authenticate before parsing any source selectors. */ +public final class GameDesignGameplayRuleSourceReadGrpcService + extends GameDesignGameplayRuleSourceReadServiceGrpc + .GameDesignGameplayRuleSourceReadServiceImplBase { + private final GameDesignGameplayRuleSourceReadService owner; + private final String namespace; + + public GameDesignGameplayRuleSourceReadGrpcService( + GameDesignGameplayRuleSourceReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + @Override + public void readSelectedGameplayRuleSource( + ReadSelectedGameplayRuleSourceRequest request, + StreamObserver observer) { + try { + GameDesignGameplayRuleSourceReadService.requirePeer(namespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence.Request decoded; + try { + decoded = GameplayRuleSourceReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + var result = owner.read(decoded); + observer.onNext(GameplayRuleSourceReadGrpcCodec.toResponse(result)); + observer.onCompleted(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + } catch (IllegalArgumentException | IllegalStateException unavailable) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Complete synchronized rule source unavailable") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java new file mode 100644 index 0000000000..83ff84e443 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java @@ -0,0 +1,66 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered owner read; authenticates complete synchronized source, never creator permission. + */ +public final class GameDesignGameplayRuleSourceReadService { + private final GameplayRuleSourceRepository repository; + private final TransactionTemplate transaction; + private final String namespace; + + public GameDesignGameplayRuleSourceReadService( + GameplayRuleSourceRepository repository, + PlatformTransactionManager transactions, + String namespace) { + this.repository = Objects.requireNonNull(repository); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + public GameplayRuleSourceReadEvidence read(GameplayRuleSourceReadEvidence.Request request) { + requirePeer(namespace); + if (!namespace.equals(request.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION + .withDescription("Independent GD owner read required") + .asRuntimeException(); + return transaction.execute( + ignored -> { + var snapshot = + repository.requireCompleteForGameLogic( + request.binding().target(), request.binding().commitId()); + if (!snapshot.binding().equals(request.binding())) + throw Status.FAILED_PRECONDITION + .withDescription("Selected rule binding differs") + .asRuntimeException(); + return new GameplayRuleSourceReadEvidence( + request, new GameplayRuleSelectedSource(snapshot.canonicalJson())); + }); + } + + static void requirePeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + String prefix = "spiffe://firemud/ns/" + namespace + "/sa/"; + if (!(prefix + "account-service").equals(peer.uri()) + && !(prefix + "game-logic-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java index da3443a065..6a1119cd46 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java @@ -24,6 +24,7 @@ public final class GameDesignSourceRepository { private final RealmPolicySourceRepository policies; private final CommandSourceRepository commands; private final AssetSourceRepository assets; + private final GameplayRuleSourceRepository gameplayRules; private final DraftCommitCoordinatorRepository coordinator; public GameDesignSourceRepository(DSLContext dsl) { @@ -31,6 +32,7 @@ public GameDesignSourceRepository(DSLContext dsl) { policies = new RealmPolicySourceRepository(dsl); commands = new CommandSourceRepository(dsl); assets = new AssetSourceRepository(dsl); + gameplayRules = new GameplayRuleSourceRepository(dsl); coordinator = new DraftCommitCoordinatorRepository(dsl); } @@ -43,7 +45,12 @@ public Genesis enrollFreshDraft(TargetProof target) { commands.enrollNewDraftGenesis( new CommandSource.NewDraftGenesisReceipt( target, policy.receiptId(), policy.creationTransactionId())); - Genesis result = new Genesis(policy, command, assets.enrollFreshDraft(target)); + Genesis result = + new Genesis( + policy, + command, + assets.enrollFreshDraft(target), + gameplayRules.enrollFreshDraft(target)); if (!result.equals( readGenesis(target) .orElseThrow( @@ -60,12 +67,18 @@ public Optional readGenesis(TargetProof target) { var policy = policies.readGenesis(target); var command = commands.readNewDraftGenesis(target); var asset = assets.readGenesis(target); - if (policy.isEmpty() && command.isEmpty() && asset.isEmpty()) return Optional.empty(); - if (policy.isEmpty() || command.isEmpty() || asset.isEmpty()) { + var gameplay = gameplayRules.readGenesis(target); + if (policy.isEmpty() && command.isEmpty() && asset.isEmpty() && gameplay.isEmpty()) + return Optional.empty(); + if (policy.isEmpty() || command.isEmpty() || asset.isEmpty() || gameplay.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); } return Optional.of( - new Genesis(policy.orElseThrow(), command.orElseThrow(), asset.orElseThrow())); + new Genesis( + policy.orElseThrow(), + command.orElseThrow(), + asset.orElseThrow(), + gameplay.orElseThrow())); } /** Stage actual source writes and record exactly one complete local owner outcome. */ @@ -75,10 +88,15 @@ public Application apply(DraftCommitBinding binding) { List commandMutations = CommandSource.mutations(binding); boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); - requireCompleteScopes(binding, !commandMutations.isEmpty(), policyMutation, assetMutation); + boolean gameplayMutation = !GameplayRuleSource.mutations(binding).isEmpty(); + requireCompleteScopes( + binding, !commandMutations.isEmpty(), policyMutation, assetMutation, gameplayMutation); requireGenesis(binding.target()); Optional command = commands.apply(binding); Optional asset = assets.apply(binding); + Optional gameplay = gameplayRules.apply(binding); + if (gameplay.isPresent() != gameplayMutation) + throw new IllegalStateException("GAME_DESIGN_GAMEPLAY_APPLICATION_INCOMPLETE"); if (asset.isPresent() != assetMutation) throw new IllegalStateException("GAME_DESIGN_ASSET_APPLICATION_INCOMPLETE"); if (command.isPresent() != !commandMutations.isEmpty()) { @@ -90,12 +108,12 @@ public Application apply(DraftCommitBinding binding) { // first, then records the combined result using the command store's actual readback bytes. policy = Optional.of( - command.isPresent() || asset.isPresent() + command.isPresent() || asset.isPresent() || gameplay.isPresent() ? policies.applyMutation(binding) : policies.apply(binding)); } OwnerOutcome expected; - if (asset.isPresent()) { + if (asset.isPresent() || gameplay.isPresent()) { var component = new ByteArrayOutputStream(); DraftAuthorizationFenceBinding.frame( component, "game-design-control-plane-sibling-components/v1"); @@ -105,9 +123,16 @@ public Application apply(DraftCommitBinding binding) { DraftAuthorizationFenceBinding.frame(component, command.orElseThrow().canonicalBytes()); epochs.add(command.orElseThrow().commandAppliedEpoch()); } - DraftAuthorizationFenceBinding.frame(component, "ASSET"); - DraftAuthorizationFenceBinding.frame(component, asset.orElseThrow().canonicalBytes()); - epochs.add(asset.orElseThrow().appliedEpoch()); + if (asset.isPresent()) { + DraftAuthorizationFenceBinding.frame(component, "ASSET"); + DraftAuthorizationFenceBinding.frame(component, asset.orElseThrow().canonicalBytes()); + epochs.add(asset.orElseThrow().appliedEpoch()); + } + if (gameplay.isPresent()) { + DraftAuthorizationFenceBinding.frame(component, "GAMEPLAY"); + DraftAuthorizationFenceBinding.frame(component, gameplay.orElseThrow().canonicalBytes()); + epochs.add(gameplay.orElseThrow().appliedEpoch()); + } if (policy.isPresent()) { var policyResult = policy.orElseThrow(); epochs.add(policyResult.ownerOutcome().appliedEpochs().getFirst()); @@ -168,7 +193,7 @@ public Application apply(DraftCommitBinding binding) { if (!expected.equals(retained)) { throw new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_CONFLICT"); } - return new Application(binding, command, policy, asset, retained); + return new Application(binding, command, policy, asset, gameplay, retained); } /** Invoke after the actual coordinator fence advances, before releasing its application slot. */ @@ -179,10 +204,11 @@ public SynchronizedSources captureSynchronized(DraftCommitBinding binding) { CommandSnapshot command = commands.captureSynchronized(binding); RealmPolicySnapshot policy = policies.captureSynchronized(binding); AssetSnapshot asset = assets.captureSynchronized(binding); + GameplayRuleSnapshot gameplay = gameplayRules.captureSynchronized(binding); if (!binding.equals(command.binding()) || !binding.equals(policy.binding())) { throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_BINDING_CONFLICT"); } - return new SynchronizedSources(command, policy, asset); + return new SynchronizedSources(command, policy, asset, gameplay); } /** Freeze both complete, selected source snapshots against the same retained operation. */ @@ -225,12 +251,18 @@ public Optional readSynchronized(TargetProof target, UUID c var command = commands.readSnapshot(target, commitId); var policy = policies.readSnapshot(target, commitId); var asset = assets.readSnapshot(target, commitId); - if (command.isEmpty() && policy.isEmpty() && asset.isEmpty()) return Optional.empty(); - if (command.isEmpty() || policy.isEmpty() || asset.isEmpty()) { + var gameplay = gameplayRules.readSnapshot(target, commitId); + if (command.isEmpty() && policy.isEmpty() && asset.isEmpty() && gameplay.isEmpty()) + return Optional.empty(); + if (command.isEmpty() || policy.isEmpty() || asset.isEmpty() || gameplay.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); } return Optional.of( - new SynchronizedSources(command.orElseThrow(), policy.orElseThrow(), asset.orElseThrow())); + new SynchronizedSources( + command.orElseThrow(), + policy.orElseThrow(), + asset.orElseThrow(), + gameplay.orElseThrow())); } private void requireGenesis(TargetProof target) { @@ -256,8 +288,12 @@ private static OwnerOutcome commandOnlyOutcome( } private static void requireCompleteScopes( - DraftCommitBinding binding, boolean hasCommand, boolean hasPolicy, boolean hasAsset) { - if (!hasCommand && !hasPolicy && !hasAsset + DraftCommitBinding binding, + boolean hasCommand, + boolean hasPolicy, + boolean hasAsset, + boolean hasGameplay) { + if (!hasCommand && !hasPolicy && !hasAsset && !hasGameplay || !binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE)) { throw new IllegalArgumentException("Game Design owner requires typed source revisions"); } @@ -279,10 +315,12 @@ private static void requireCompleteScopes( && "effective".equals(unit.scopeId())) .toList(); var assets = units.stream().filter(AssetSourceRepository::isScope).toList(); + var gameplay = units.stream().filter(GameplayRuleSource::isScope).toList(); if (commands.size() != (hasCommand ? 1 : 0) || policies.size() != (hasPolicy ? 1 : 0) || assets.size() != (hasAsset ? 1 : 0) - || commands.size() + policies.size() + assets.size() != units.size() + || gameplay.size() != (hasGameplay ? 1 : 0) + || commands.size() + policies.size() + assets.size() + gameplay.size() != units.size() || units.stream() .anyMatch( unit -> @@ -310,16 +348,20 @@ private static void requireWrite() { public record Genesis( RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command, - AssetSnapshot.Genesis asset) { + AssetSnapshot.Genesis asset, + GameplayRuleSnapshot.Genesis gameplay) { public Genesis { Objects.requireNonNull(policy, "policy"); Objects.requireNonNull(command, "command"); Objects.requireNonNull(asset, "asset"); + Objects.requireNonNull(gameplay, "gameplay"); if (!policy.target().equals(command.target()) || !policy.receiptId().equals(command.receiptId()) || !policy.creationTransactionId().equals(command.creationTransactionId()) || !policy.target().equals(asset.target()) - || !policy.creationTransactionId().equals(asset.creationTransactionId())) { + || !policy.creationTransactionId().equals(asset.creationTransactionId()) + || !policy.target().equals(gameplay.target()) + || !policy.creationTransactionId().equals(gameplay.creationTransactionId())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_IDENTITY_CONFLICT"); } } @@ -330,17 +372,20 @@ public record Application( Optional command, Optional policy, Optional asset, + Optional gameplay, OwnerOutcome ownerOutcome) { public Application { Objects.requireNonNull(binding, "binding"); command = Objects.requireNonNull(command, "command"); policy = Objects.requireNonNull(policy, "policy"); asset = Objects.requireNonNull(asset, "asset"); + gameplay = Objects.requireNonNull(gameplay, "gameplay"); Objects.requireNonNull(ownerOutcome, "ownerOutcome"); - if (command.isEmpty() && policy.isEmpty() && asset.isEmpty() + if (command.isEmpty() && policy.isEmpty() && asset.isEmpty() && gameplay.isEmpty() || command.isPresent() && !binding.equals(command.orElseThrow().binding()) || policy.isPresent() && !binding.equals(policy.orElseThrow().snapshot().binding()) || asset.isPresent() && !binding.equals(asset.orElseThrow().binding()) + || gameplay.isPresent() && !binding.equals(gameplay.orElseThrow().binding()) || ownerOutcome.owner() != Owner.GAME_DESIGN_CONTROL_PLANE || ownerOutcome.status() != OwnerStatus.APPLIED || !binding.commitId().equals(ownerOutcome.commitId()) @@ -351,13 +396,18 @@ public record Application( } public record SynchronizedSources( - CommandSnapshot command, RealmPolicySnapshot policy, AssetSnapshot asset) { + CommandSnapshot command, + RealmPolicySnapshot policy, + AssetSnapshot asset, + GameplayRuleSnapshot gameplay) { public SynchronizedSources { Objects.requireNonNull(command, "command"); Objects.requireNonNull(policy, "policy"); Objects.requireNonNull(asset, "asset"); + Objects.requireNonNull(gameplay, "gameplay"); if (!command.binding().equals(policy.binding()) - || !command.binding().equals(asset.binding())) { + || !command.binding().equals(asset.binding()) + || !command.binding().equals(gameplay.binding())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_SNAPSHOT_BINDING_CONFLICT"); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSnapshot.java new file mode 100644 index 0000000000..68b5b4bbfb --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSnapshot.java @@ -0,0 +1,185 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; + +/** Complete authored source and immutable original revisions, not a GL retained-source receipt. */ +public record GameplayRuleSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List entries) { + public static final String SCHEMA = "game-design-gameplay-rule-source-snapshot/v1"; + + public GameplayRuleSnapshot { + Objects.requireNonNull(binding); + counter(sourceEpoch); + DraftAuthorizationFenceBinding.requireUuid(genesisReceiptId); + if (inheritedCommitId != null) DraftAuthorizationFenceBinding.requireUuid(inheritedCommitId); + entries = List.copyOf(entries); + for (var entry : entries) + if (!entry.sourceBinding().target().equals(binding.target())) + throw new IllegalArgumentException("Rule source belongs to another canonical target"); + GameplayRuleSource.manifest(entries); + } + + public GameplayRuleManifest manifest() { + return GameplayRuleSource.manifest(entries); + } + + public String canonicalJson() { + return GameplayRuleManifest.canonical( + Map.of( + "schema", + SCHEMA, + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptId", + genesisReceiptId.toString(), + "manifestJson", + manifest().canonicalJson(), + "entries", + entries.stream().map(GameplayRuleSource.Entry::object).toList())); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return GameplayRuleManifest.sha256(canonicalBytes()); + } + + public static GameplayRuleSnapshot fromStored(String json) { + var root = GameplayRuleManifest.tree(json); + GameplayRuleManifest.fields( + root, + Set.of( + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "manifestJson", + "entries")); + if (!SCHEMA.equals(GameplayRuleSource.text(root, "schema")) || !root.path("entries").isArray()) + throw new IllegalArgumentException("Unsupported rule snapshot"); + var binding = + DraftCommitBinding.fromStored( + GameplayRuleSource.text(root, "bindingJson"), + GameplayRuleSource.text(root, "bindingDigest")); + List entries = new ArrayList<>(); + for (var node : root.path("entries")) { + GameplayRuleManifest.fields( + node, + Set.of( + "family", + "definitionJson", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId")); + Family family = Family.valueOf(GameplayRuleSource.text(node, "family")); + entries.add( + new GameplayRuleSource.Entry( + family, + GameplayRuleManifest.definition( + family, GameplayRuleSource.text(node, "definitionJson")), + DraftCommitBinding.fromStored( + GameplayRuleSource.text(node, "sourceBindingJson"), + GameplayRuleSource.text(node, "sourceBindingDigest")), + GameplayRuleSource.text(node, "revisionOrder"), + UUID.fromString(GameplayRuleSource.text(node, "revisionId")))); + } + if (!root.path("inheritedCommitId").isTextual()) + throw new IllegalArgumentException("Invalid predecessor"); + String inherited = root.path("inheritedCommitId").textValue(); + var result = + new GameplayRuleSnapshot( + binding, + GameplayRuleSource.text(root, "sourceEpoch"), + inherited.isEmpty() ? null : UUID.fromString(inherited), + UUID.fromString(GameplayRuleSource.text(root, "genesisReceiptId")), + entries); + if (!result + .manifest() + .equals(GameplayRuleManifest.fromStored(GameplayRuleSource.text(root, "manifestJson"))) + || !result.canonicalJson().equals(json)) + throw new IllegalArgumentException("Changed rule snapshot bytes"); + return result; + } + + public record Genesis( + TargetProof target, + UUID receiptId, + String creationTransactionId, + GameplayRuleManifest inventory) { + public Genesis { + Objects.requireNonNull(target); + DraftAuthorizationFenceBinding.requireUuid(receiptId); + if (creationTransactionId == null + || !creationTransactionId.matches("[1-9][0-9]*") + || !GameplayRuleManifest.explicitEmpty().equals(inventory)) + throw new IllegalArgumentException( + "Actual fresh creation requires complete empty inventory"); + } + } + + public record Application( + DraftCommitBinding binding, String expectedEpoch, GameplayRuleSnapshot snapshot) { + public Application { + counter(expectedEpoch); + Objects.requireNonNull(snapshot); + if (!binding.equals(snapshot.binding()) + || GameplayRuleSource.mutations(binding).isEmpty() + || !new java.math.BigInteger(expectedEpoch) + .add(java.math.BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch())) + throw new IllegalArgumentException( + "Rule application must advance its original bound epoch"); + } + + public AppliedEpoch appliedEpoch() { + return new AppliedEpoch( + GameplayRuleSource.SCOPE, + binding.target().canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + expectedEpoch, + snapshot.sourceEpoch()); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-gameplay-rule-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + } + + private static void counter(String value) { + if (value == null || !value.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Invalid source epoch"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSource.java new file mode 100644 index 0000000000..f78b7d2e14 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSource.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Definition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; + +/** Real Game Design-owned revisions; author history is separate from Game Logic retention. */ +public final class GameplayRuleSource { + public static final String REVISION_KIND = "GAMEPLAY_RULE"; + public static final String SCOPE = "GAMEPLAY_RULE_SET"; + public static final String SCOPE_ID = "effective"; + + private GameplayRuleSource() {} + + public enum OperationKind { + UPSERT, + DELETE + } + + public record Mutation( + DraftCommitBinding binding, + String revisionOrder, + UUID revisionId, + OperationKind operation, + Family family, + String key, + Definition definition) { + public Mutation { + Objects.requireNonNull(binding); + Objects.requireNonNull(operation); + Objects.requireNonNull(family); + GameplayRuleManifest.identifier(key); + var revision = + binding.revisions().stream() + .filter(value -> value.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .filter(value -> value.revisionId().equals(revisionId)) + .filter(value -> value.revisionOrder().equals(revisionOrder)) + .findFirst() + .orElseThrow(); + String expected; + if (operation == OperationKind.UPSERT) { + Objects.requireNonNull(definition); + if (definition.family() != family || !definition.key().equals(key)) + throw new IllegalArgumentException("Rule UPSERT identity differs from definition"); + expected = upsertPayload(definition); + } else { + if (definition != null) throw new IllegalArgumentException("DELETE carries no definition"); + expected = deletePayload(family, key); + } + if (!expected.equals( + GameplayRuleManifest.canonical(GameplayRuleManifest.tree(revision.payload())))) + throw new IllegalArgumentException("Rule mutation differs from original revision"); + } + + public String payload() { + return operation == OperationKind.UPSERT + ? upsertPayload(definition) + : deletePayload(family, key); + } + } + + public record Entry( + Family family, + Definition definition, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId) { + public Entry { + Objects.requireNonNull(definition); + new Mutation( + sourceBinding, + revisionOrder, + revisionId, + OperationKind.UPSERT, + family, + definition.key(), + definition); + } + + public Map object() { + return Map.of( + "family", + family.name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + sourceBinding.canonicalJson(), + "sourceBindingDigest", + sourceBinding.digest(), + "revisionOrder", + revisionOrder, + "revisionId", + revisionId.toString()); + } + } + + public static List mutations(DraftCommitBinding binding) { + List result = new ArrayList<>(); + for (var revision : binding.revisions()) { + if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; + var node = GameplayRuleManifest.tree(revision.payload()); + String kind = text(node, "revisionKind"); + if (Set.of("COMMAND_DEFINITION", "REALM_ENTRY_POLICY", "ASSET_REFERENCE").contains(kind)) + continue; + if (!REVISION_KIND.equals(kind)) + throw new IllegalArgumentException("Unknown Game Design revision kind"); + OperationKind operation = OperationKind.valueOf(text(node, "operation")); + GameplayRuleManifest.fields( + node, + operation == OperationKind.UPSERT + ? Set.of("schemaVersion", "revisionKind", "operation", "family", "definitionJson") + : Set.of("schemaVersion", "revisionKind", "operation", "family", "key")); + if (!node.path("schemaVersion").isInt() || node.path("schemaVersion").intValue() != 1) + throw new IllegalArgumentException("Unsupported rule-source schema"); + Family family = Family.valueOf(text(node, "family")); + Definition definition = + operation == OperationKind.UPSERT + ? GameplayRuleManifest.definition(family, text(node, "definitionJson")) + : null; + result.add( + new Mutation( + binding, + revision.revisionOrder(), + revision.revisionId(), + operation, + family, + definition == null ? text(node, "key") : definition.key(), + definition)); + } + return List.copyOf(result); + } + + public static String upsertPayload(Definition definition) { + return net.firedevops.firemud.common.gamelogic.GameplayRuleSourceRevision.upsertPayload( + definition); + } + + public static String deletePayload(Family family, String key) { + GameplayRuleManifest.identifier(key); + return GameplayRuleManifest.canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + REVISION_KIND, + "operation", + "DELETE", + "family", + family.name(), + "key", + key)); + } + + public static List replay(List inherited, DraftCommitBinding binding) { + Map> families = new EnumMap<>(Family.class); + for (Family family : Family.values()) families.put(family, new LinkedHashMap<>()); + for (Entry entry : inherited) { + if (!entry.sourceBinding().target().equals(binding.target()) + || families.get(entry.family()).put(entry.definition().key(), entry) != null) + throw new IllegalArgumentException("Invalid inherited rule-source inventory"); + } + for (Mutation mutation : mutations(binding)) { + var family = families.get(mutation.family()); + if (mutation.operation() == OperationKind.DELETE) { + if (family.remove(mutation.key()) == null) + throw new IllegalArgumentException("Rule DELETE requires an existing authored key"); + } else + family.put( + mutation.key(), + new Entry( + mutation.family(), + mutation.definition(), + binding, + mutation.revisionOrder(), + mutation.revisionId())); + } + List result = + families.values().stream().flatMap(value -> value.values().stream()).toList(); + manifest(result); // Validate the complete atomic result, allowing forward references within a + // commit. + return result; + } + + public static GameplayRuleManifest manifest(List entries) { + Map> families = new EnumMap<>(Family.class); + for (Family family : Family.values()) families.put(family, new ArrayList<>()); + for (Entry entry : entries) families.get(entry.family()).add(entry.definition()); + return new GameplayRuleManifest(families); + } + + public static boolean isScope(DraftCommitBinding.AffectedUnit unit) { + return SCOPE.equals(unit.aggregateType()) + && SCOPE.equals(unit.scopeType()) + && SCOPE_ID.equals(unit.scopeId()); + } + + static String text(tools.jackson.databind.JsonNode node, String key) { + if (!node.path(key).isTextual() || node.path(key).textValue().isBlank()) + throw new IllegalArgumentException("Required rule-source field missing: " + key); + return node.path(key).textValue(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java new file mode 100644 index 0000000000..e4d77b7158 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java @@ -0,0 +1,433 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Actual coordinated author history. Account mutation authority must be supplied by its owner. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner-local persistence collaborator") +public final class GameplayRuleSourceRepository { + private final DSLContext dsl; + private final DraftCommitCoordinatorRepository coordinator; + + public GameplayRuleSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + } + + public GameplayRuleSnapshot.Genesis enrollFreshDraft(TargetProof target) { + write(); + lock(target); + var existing = readGenesis(target); + if (existing.isPresent()) return existing.orElseThrow(); + Record witness = + dsl.fetchOne( + "SELECT creation_transaction_id FROM game_design_realm_policy_version_insert " + + "WHERE version_id = ? AND creation_transaction_id = pg_current_xact_id()::TEXT", + target.gameDesignVersionRowId()); + if (witness == null) throw new IllegalStateException("GAMEPLAY_RULE_FRESH_INSERT_UNAVAILABLE"); + var result = + new GameplayRuleSnapshot.Genesis( + target, + UUID.randomUUID(), + witness.get(0, String.class), + GameplayRuleManifest.explicitEmpty()); + dsl.execute( + "INSERT INTO game_design_gameplay_rule_genesis (canonical_tenant_id, canonical_version_id, " + + "version_id, receipt_id, creation_transaction_id, target_json, inventory_json) VALUES (?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + result.receiptId(), + result.creationTransactionId(), + CommandSource.canonical(CommandSource.targetObject(target)), + result.inventory().canonicalJson()); + dsl.execute( + "INSERT INTO game_design_gameplay_rule_head (canonical_tenant_id, canonical_version_id, source_epoch, genesis_receipt_id) " + + "VALUES (?, ?, '0', ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + result.receiptId()); + if (!result.equals(readGenesis(target).orElseThrow())) + throw new IllegalStateException("GAMEPLAY_RULE_GENESIS_READBACK_CONFLICT"); + return result; + } + + public Optional readGenesis(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_gameplay_rule_genesis WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!CommandSource.canonical(CommandSource.targetObject(target)) + .equals(row.get("target_json", String.class)) + || target.gameDesignVersionRowId() != row.get("version_id", Long.class)) + throw new IllegalStateException("GAMEPLAY_RULE_GENESIS_TARGET_CONFLICT"); + return Optional.of( + new GameplayRuleSnapshot.Genesis( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class), + GameplayRuleManifest.fromStored(row.get("inventory_json", String.class)))); + } + + public Optional apply(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var prior = application(binding); + if (prior.isPresent()) return prior; + var mutations = GameplayRuleSource.mutations(binding); + if (mutations.isEmpty()) return Optional.empty(); + open(binding.target()); + var slot = coordinator.readApplicationSlot(binding.target()).orElseThrow(); + var owner = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (!slot.commitId().equals(binding.commitId()) + || !slot.requestId().equals(binding.requestId()) + || owner == null + || owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.IN_PROGRESS + && owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN) + throw new IllegalStateException("GAMEPLAY_RULE_COORDINATOR_APPLICATION_UNAVAILABLE"); + Record head = head(binding.target()); + String epoch = head.get("source_epoch", String.class); + var units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(GameplayRuleSource::isScope) + .toList(); + if (units.size() != 1 + || !units.getFirst().aggregateId().equals(binding.target().canonicalVersionId().toString()) + || !epoch.equals(units.getFirst().expectedEpoch())) + throw new IllegalStateException("GAMEPLAY_RULE_EPOCH_CONFLICT"); + UUID inherited = head.get("visible_commit_id", UUID.class); + var fence = coordinator.readVisibilityFence(binding.target()); + if (inherited == null + ? fence.isPresent() || !"0".equals(epoch) + : fence.isEmpty() || !inherited.equals(fence.orElseThrow().commitId())) + throw new IllegalStateException("GAMEPLAY_RULE_PREVIOUS_FENCE_CHANGED"); + List previous = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().entries(); + var snapshot = + new GameplayRuleSnapshot( + binding, + new BigInteger(epoch).add(BigInteger.ONE).toString(), + inherited, + head.get("genesis_receipt_id", UUID.class), + GameplayRuleSource.replay(previous, binding)); + for (var mutation : mutations) + dsl.execute( + "INSERT INTO game_design_gameplay_rule_revision " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, operation_kind, family, definition_key, payload_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + mutation.revisionId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.operation().name(), + mutation.family().name(), + mutation.key(), + mutation.payload()); + var result = new GameplayRuleSnapshot.Application(binding, epoch, snapshot); + dsl.execute( + "INSERT INTO game_design_gameplay_rule_application (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "expected_epoch, snapshot_json, result_bytes) VALUES (?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + epoch, + snapshot.canonicalJson(), + result.canonicalBytes()); + if (dsl.execute( + "UPDATE game_design_gameplay_rule_head SET source_epoch = ?, applied_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID)", + snapshot.sourceEpoch(), + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + epoch, + inherited) + != 1) throw new IllegalStateException("GAMEPLAY_RULE_EPOCH_CONFLICT"); + return Optional.of(application(binding).orElseThrow()); + } + + public GameplayRuleSnapshot captureSynchronized(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var existing = readSnapshot(binding.target(), binding.commitId()); + if (existing.isPresent()) { + if (!existing.orElseThrow().binding().equals(binding)) + throw new IllegalStateException("GAMEPLAY_RULE_SNAPSHOT_BINDING_CONFLICT"); + return existing.orElseThrow(); + } + open(binding.target()); + requireFence(binding); + var head = head(binding.target()); + UUID inherited = head.get("visible_commit_id", UUID.class); + var applied = application(binding); + GameplayRuleSnapshot snapshot; + if (!GameplayRuleSource.mutations(binding).isEmpty()) { + snapshot = applied.orElseThrow().snapshot(); + if (!Objects.equals(inherited, snapshot.inheritedCommitId())) + throw new IllegalStateException("GAMEPLAY_RULE_PREDECESSOR_CHANGED"); + } else { + if (applied.isPresent()) + throw new IllegalStateException("GAMEPLAY_RULE_UNDECLARED_APPLICATION"); + var entries = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().entries(); + if (inherited == null && !"0".equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("GAMEPLAY_RULE_GENESIS_NOT_CURRENT"); + snapshot = + new GameplayRuleSnapshot( + binding, + head.get("source_epoch", String.class), + inherited, + head.get("genesis_receipt_id", UUID.class), + entries); + } + if (!snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("GAMEPLAY_RULE_PARTIAL_WRITE_NOT_VISIBLE"); + dsl.execute( + "INSERT INTO game_design_gameplay_rule_snapshot (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "snapshot_json, snapshot_digest) VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + snapshot.canonicalJson(), + snapshot.digest()); + if (dsl.execute( + "UPDATE game_design_gameplay_rule_head SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID) AND source_epoch = ?", + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + inherited, + snapshot.sourceEpoch()) + != 1) throw new IllegalStateException("GAMEPLAY_RULE_VISIBILITY_CONFLICT"); + return readSnapshot(binding.target(), binding.commitId()).orElseThrow(); + } + + public Optional readSnapshot(TargetProof target, UUID commitId) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_gameplay_rule_snapshot WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId); + if (row == null) return Optional.empty(); + var snapshot = GameplayRuleSnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId) + || !snapshot.binding().requestId().equals(row.get("request_id", UUID.class)) + || !snapshot.digest().equals(row.get("snapshot_digest", String.class))) + throw new IllegalStateException("GAMEPLAY_RULE_SNAPSHOT_READBACK_CONFLICT"); + exact(snapshot.binding()); + var genesis = readGenesis(target).orElseThrow(); + if (!snapshot.genesisReceiptId().equals(genesis.receiptId())) + throw new IllegalStateException("GAMEPLAY_RULE_GENESIS_CHANGED"); + var fence = + dsl.fetchOne( + "SELECT input_digest FROM game_design_draft_commit_visibility_fence WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.binding().requestId(), + commitId); + if (fence == null || !snapshot.binding().digest().equals(fence.get(0, String.class))) + throw new IllegalStateException("GAMEPLAY_RULE_SNAPSHOT_FENCE_CONFLICT"); + verifyEntries(snapshot); + return Optional.of(snapshot); + } + + /** No generic rule revision or legacy effective command may disappear from a complete handoff. */ + public GameplayRuleSnapshot requireCompleteForGameLogic(TargetProof target, UUID commitId) { + var snapshot = + readSnapshot(target, commitId) + .orElseThrow( + () -> new IllegalStateException("GAMEPLAY_RULE_SELECTED_SOURCE_UNAVAILABLE")); + // Generic revisions have no authorized commit/source binding, even when IDs or payloads match. + if (dsl.fetchOne( + "SELECT 1 FROM revision WHERE tenant_id = ? AND version_id = ? " + + "AND revision_kind = 'GAMEPLAY_RULE' LIMIT 1", + target.gameDesignVersionTenantKey(), + target.gameDesignVersionRowId()) + != null) { + throw new IllegalStateException("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED"); + } + var commands = + new CommandSourceRepository(dsl) + .readSnapshot(target, commitId) + .orElseThrow( + () -> + new IllegalStateException( + "GAMEPLAY_RULE_LEGACY_COMMAND_INVENTORY_UNAVAILABLE")); + if (!commands.binding().equals(snapshot.binding()) || !commands.definitions().isEmpty()) + throw new IllegalStateException("GAMEPLAY_RULE_LEGACY_COMMAND_SOURCE_NOT_CONVERGED"); + return snapshot; + } + + private Optional application(DraftCommitBinding binding) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) return Optional.empty(); + var result = + new GameplayRuleSnapshot.Application( + binding, + row.get("expected_epoch", String.class), + GameplayRuleSnapshot.fromStored(row.get("snapshot_json", String.class))); + if (!binding.requestId().equals(row.get("request_id", UUID.class)) + || !Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class))) + throw new IllegalStateException("GAMEPLAY_RULE_APPLICATION_READBACK_CONFLICT"); + var stored = + dsl.fetch( + "SELECT payload_json FROM game_design_gameplay_rule_revision WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND commit_id = ? ORDER BY revision_order", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()) + .getValues("payload_json", String.class); + if (!stored.equals( + GameplayRuleSource.mutations(binding).stream() + .map(GameplayRuleSource.Mutation::payload) + .toList())) throw new IllegalStateException("GAMEPLAY_RULE_REVISION_READBACK_CONFLICT"); + verifyEntries(result.snapshot()); + return Optional.of(result); + } + + private void verifyEntries(GameplayRuleSnapshot snapshot) { + for (var entry : snapshot.entries()) { + exact(entry.sourceBinding()); + var mutation = + new GameplayRuleSource.Mutation( + entry.sourceBinding(), + entry.revisionOrder(), + entry.revisionId(), + GameplayRuleSource.OperationKind.UPSERT, + entry.family(), + entry.definition().key(), + entry.definition()); + var row = + dsl.fetchOne( + "SELECT payload_json FROM game_design_gameplay_rule_revision WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ? AND revision_id = ? AND revision_order = ? AND family = ? AND definition_key = ? AND operation_kind = 'UPSERT'", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + entry.sourceBinding().requestId(), + entry.sourceBinding().commitId(), + entry.revisionId(), + Integer.parseInt(entry.revisionOrder()), + entry.family().name(), + entry.definition().key()); + if (row == null || !mutation.payload().equals(row.get(0, String.class))) + throw new IllegalStateException("GAMEPLAY_RULE_ENTRY_PROVENANCE_CHANGED"); + } + } + + private Record head(TargetProof target) { + readGenesis(target) + .orElseThrow(() -> new IllegalStateException("GAMEPLAY_RULE_GENESIS_UNAVAILABLE")); + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_design_gameplay_rule_head WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + target.canonicalTenantId(), + target.canonicalVersionId()), + "GAMEPLAY_RULE_HEAD_UNAVAILABLE"); + } + + private void exact(DraftCommitBinding binding) { + if (!coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .binding() + .equals(binding)) throw new IllegalStateException("GAMEPLAY_RULE_BINDING_CHANGED"); + } + + private void requireFence(DraftCommitBinding binding) { + var fence = coordinator.readVisibilityFence(binding.target()).orElseThrow(); + if (!binding.commitId().equals(fence.commitId()) + || !binding.requestId().equals(fence.requestId()) + || !binding.digest().equals(fence.inputDigest()) + || coordinator.read(binding.target(), binding.requestId()).orElseThrow().workflowState() + != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED) + throw new IllegalStateException("GAMEPLAY_RULE_SYNCHRONIZED_FENCE_UNAVAILABLE"); + } + + private void open(TargetProof target) { + if (dsl.fetchOne( + "SELECT id FROM version WHERE id = ? AND version_state = 'DRAFT' AND NOT is_script_only " + + "AND base_version_id IS NULL AND script_patch_version IS NULL", + target.gameDesignVersionRowId()) + == null + || dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) throw new IllegalStateException("GAMEPLAY_RULE_FROZEN_OR_NOT_DRAFT"); + } + + private void lock(TargetProof target) { + var repository = new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl); + var qualified = + repository + .findByCanonicalTenantIdAndCanonicalVersionId( + target.canonicalTenantId(), target.canonicalVersionId()) + .orElseThrow(); + var version = + repository + .findByTenantIdAndIdForUpdate( + target.gameDesignVersionTenantKey(), target.gameDesignVersionRowId()) + .orElseThrow(); + var actual = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + if (!target.equals(actual) || !qualified.getId().equals(version.getId())) + throw new IllegalStateException("GAMEPLAY_RULE_TARGET_CHANGED"); + } + + private static void write() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) + throw new IllegalStateException( + "Gameplay rule source requires writable READ_COMMITTED transaction"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java index 323b46e342..aa86ac5768 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java @@ -43,7 +43,9 @@ public record Policy( public static boolean isPolicyRevision(DraftCommitBinding.RevisionPayload input) { var kind = text(tree(input.payload()), "revisionKind"); if (RealmEntryPolicy.REVISION_KIND.equals(kind)) return true; - if ("COMMAND_DEFINITION".equals(kind) || AssetSource.REVISION_KIND.equals(kind)) return false; + if ("COMMAND_DEFINITION".equals(kind) + || AssetSource.REVISION_KIND.equals(kind) + || GameplayRuleSource.REVISION_KIND.equals(kind)) return false; throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java index 7dac9d7d3b..a5d2f5812e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java @@ -46,6 +46,10 @@ public RevisionDto saveRevision(RevisionDto dto) { dto.tenantId(), dto.versionId(), dto.revisionKind()); + if ("GAMEPLAY_RULE".equals(dto.revisionKind())) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: GAMEPLAY_RULE requires authorized coordinated source authoring"); + } Game game = Optional.ofNullable(gameRepository.findByTenantId(dto.tenantId())) .orElseThrow(() -> new IllegalArgumentException("game not found")); diff --git a/services/game-design-service/src/main/resources/db/migration/V57__gameplay_rule_source.sql b/services/game-design-service/src/main/resources/db/migration/V57__gameplay_rule_source.sql new file mode 100644 index 0000000000..fa170cf253 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V57__gameplay_rule_source.sql @@ -0,0 +1,400 @@ +-- Authored gameplay-rule inventory. No retained Draft receives an inferred empty baseline. +CREATE TABLE game_design_gameplay_rule_genesis ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + version_id BIGINT NOT NULL UNIQUE, receipt_id UUID NOT NULL UNIQUE, + creation_transaction_id TEXT NOT NULL, target_json TEXT NOT NULL, inventory_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (version_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id), + FOREIGN KEY (version_id) REFERENCES game_design_realm_policy_version_insert (version_id), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); +CREATE TABLE game_design_gameplay_rule_application ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, expected_epoch TEXT NOT NULL, + snapshot_json TEXT NOT NULL, result_bytes BYTEA NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), CHECK (octet_length(result_bytes) > 0) +); +CREATE TABLE game_design_gameplay_rule_revision ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, revision_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), operation_kind VARCHAR(16) NOT NULL, + family VARCHAR(64) NOT NULL, definition_key VARCHAR(128) NOT NULL, payload_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_gameplay_rule_application (canonical_tenant_id, canonical_version_id, commit_id) + DEFERRABLE INITIALLY DEFERRED, + CHECK (operation_kind IN ('UPSERT', 'DELETE')), + CHECK (definition_key ~ '^[A-Za-z][A-Za-z0-9_.:-]{0,127}$') +); +CREATE TABLE game_design_gameplay_rule_snapshot ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, snapshot_json TEXT NOT NULL, + snapshot_digest VARCHAR(71) NOT NULL CHECK (snapshot_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit_visibility_fence (canonical_tenant_id, canonical_version_id, request_id, commit_id) +); +CREATE TABLE game_design_gameplay_rule_head ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + genesis_receipt_id UUID NOT NULL REFERENCES game_design_gameplay_rule_genesis (receipt_id), + applied_commit_id UUID, visible_commit_id UUID, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_gameplay_rule_genesis (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, applied_commit_id) + REFERENCES game_design_gameplay_rule_application (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_gameplay_rule_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION gameplay_rule_families() RETURNS TEXT[] AS $$ + SELECT ARRAY['STATS', 'RESOURCES', 'CONDITIONS', 'EFFECTS', 'ABILITIES', 'ACTIONS', 'COMMANDS', + 'ADMISSION_TAGS', 'DISPOSITIONS', 'CONTINUOUS_OVERLAYS', 'OBSERVATION_POLICIES', + 'TARGETING_POLICIES', 'SELECTION_POLICIES', 'DEFAULT_BINDINGS', 'FEEDBACK']::TEXT[]; +$$ LANGUAGE SQL IMMUTABLE; + +CREATE FUNCTION gameplay_rule_definition_key(family TEXT, definition JSONB) RETURNS TEXT AS $$ + SELECT CASE family WHEN 'ABILITIES' THEN definition->>'abilityId' + WHEN 'ACTIONS' THEN definition->>'actionSequenceId' + WHEN 'STATS' THEN definition->>'statKey' WHEN 'RESOURCES' THEN definition->>'statKey' + WHEN 'CONDITIONS' THEN definition->>'conditionKey' WHEN 'EFFECTS' THEN definition->>'effectKey' + WHEN 'COMMANDS' THEN definition->>'commandId' WHEN 'ADMISSION_TAGS' THEN definition->>'tagKey' + WHEN 'DISPOSITIONS' THEN definition->>'dispositionKey' WHEN 'CONTINUOUS_OVERLAYS' THEN definition->>'overlayKey' + WHEN 'OBSERVATION_POLICIES' THEN definition->>'observationPolicyKey' + WHEN 'TARGETING_POLICIES' THEN definition->>'targetingPolicyKey' + WHEN 'SELECTION_POLICIES' THEN definition->>'targetSelectionPolicyKey' + WHEN 'DEFAULT_BINDINGS' THEN definition->>'bindingKey' WHEN 'FEEDBACK' THEN definition->>'feedbackKey' ELSE NULL END; +$$ LANGUAGE SQL IMMUTABLE; + +CREATE FUNCTION guard_gameplay_rule_source() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; g game_design_gameplay_rule_genesis%ROWTYPE; + h game_design_gameplay_rule_head%ROWTYPE; c game_design_draft_commit%ROWTYPE; + a game_design_gameplay_rule_application%ROWTYPE; s game_design_gameplay_rule_snapshot%ROWTYPE; + revision JSONB; payload JSONB; snapshot JSONB; prior JSONB; manifest JSONB; + expected_entries JSONB; replacement JSONB; r game_design_gameplay_rule_revision%ROWTYPE; + family TEXT; family_values JSONB; present BOOLEAN; actual_count BIGINT; declared_count BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'gameplay source history is immutable' USING ERRCODE = '23514'; END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game source + ON source.id = owner.identity_source_game_row_id AND source.tenant_id = owner.identity_source_game_tenant_key + AND source.tenant_id = owner.tenant_id AND source.canonical_tenant_id = owner.canonical_tenant_id + AND source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND source.tenant_identity_source_game_id = source.id AND source.tenant_identity_source_legacy_tenant_id = source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL OR v.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'gameplay source requires exact canonical full Draft' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_gameplay_rule_genesis' THEN + manifest := NEW.inventory_json::JSONB; + IF TG_OP <> 'INSERT' OR v.id <> NEW.version_id OR v.version_state_epoch <> 1 + OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_version_insert w + WHERE w.version_id = v.id AND w.creation_transaction_id = NEW.creation_transaction_id) + OR EXISTS (SELECT 1 FROM game_design_draft_commit old_commit WHERE old_commit.canonical_tenant_id = NEW.canonical_tenant_id + AND old_commit.canonical_version_id = NEW.canonical_version_id) + OR NEW.target_json::JSONB IS DISTINCT FROM jsonb_build_object('canonicalTenantId', v.canonical_tenant_id::TEXT, + 'canonicalVersionId', v.canonical_version_id::TEXT, 'gameDesignVersionRowId', v.id, + 'gameDesignVersionTenantKey', v.tenant_id, 'sourceGameRowId', v.identity_source_game_row_id, + 'sourceGameTenantKey', v.identity_source_game_tenant_key, 'sourceProvenanceKind', v.identity_source_provenance_kind) + OR manifest->>'schema' IS DISTINCT FROM 'gameplay-rule-manifest/v1' + OR (SELECT count(*) FROM jsonb_object_keys(manifest)) <> 2 + OR (SELECT count(*) FROM jsonb_object_keys(manifest->'families')) <> cardinality(gameplay_rule_families()) THEN + RAISE EXCEPTION 'gameplay genesis requires actual fresh complete owner inventory' USING ERRCODE = '23514'; END IF; + FOREACH family IN ARRAY gameplay_rule_families() LOOP + IF manifest->'families'->family IS DISTINCT FROM '[]'::JSONB THEN + RAISE EXCEPTION 'every fresh gameplay family must be explicitly empty' USING ERRCODE = '23514'; END IF; + END LOOP; + RETURN NEW; + END IF; + SELECT * INTO STRICT g FROM game_design_gameplay_rule_genesis WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + IF TG_TABLE_NAME = 'game_design_gameplay_rule_head' AND TG_OP = 'INSERT' THEN + IF NEW.source_epoch <> '0' OR NEW.applied_commit_id IS NOT NULL OR NEW.visible_commit_id IS NOT NULL + OR NEW.genesis_receipt_id <> g.receipt_id THEN RAISE EXCEPTION 'gameplay head requires exact fresh genesis' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT h FROM game_design_gameplay_rule_head WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection p WHERE p.canonical_tenant_id = NEW.canonical_tenant_id + AND p.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'selected gameplay source is frozen' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_gameplay_rule_head' THEN + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.genesis_receipt_id IS DISTINCT FROM OLD.genesis_receipt_id THEN RAISE EXCEPTION 'gameplay head identity immutable' USING ERRCODE = '23514'; END IF; + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + SELECT * INTO STRICT a FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.applied_commit_id; + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 OR a.expected_epoch <> OLD.source_epoch + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN RAISE EXCEPTION 'gameplay epoch mismatch' USING ERRCODE = '23514'; END IF; + ELSIF NEW.applied_commit_id IS DISTINCT FROM OLD.applied_commit_id THEN RAISE EXCEPTION 'gameplay application pointer mismatch' USING ERRCODE = '23514'; END IF; + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + SELECT * INTO STRICT s FROM game_design_gameplay_rule_snapshot WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.visible_commit_id; + IF s.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR s.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(OLD.visible_commit_id::TEXT, '') THEN + RAISE EXCEPTION 'gameplay visibility pointer mismatch' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'gameplay source history is immutable' USING ERRCODE = '23514'; END IF; + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF TG_TABLE_NAME = 'game_design_gameplay_rule_revision' THEN + SELECT x INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'revisionId' = NEW.revision_id::TEXT + AND (x->>'revisionOrder')::INTEGER = NEW.revision_order; + payload := (revision->>'payload')::JSONB; + IF payload IS DISTINCT FROM NEW.payload_json::JSONB OR payload->>'revisionKind' IS DISTINCT FROM 'GAMEPLAY_RULE' + OR payload->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR payload->>'operation' IS DISTINCT FROM NEW.operation_kind + OR payload->>'family' IS DISTINCT FROM NEW.family OR NOT NEW.family = ANY(gameplay_rule_families()) + OR (NEW.operation_kind = 'UPSERT' AND (gameplay_rule_definition_key(NEW.family, (payload->>'definitionJson')::JSONB) IS DISTINCT FROM NEW.definition_key + OR (SELECT count(*) FROM jsonb_object_keys(payload)) <> 5)) + OR (NEW.operation_kind = 'DELETE' AND (payload->>'key' IS DISTINCT FROM NEW.definition_key + OR (SELECT count(*) FROM jsonb_object_keys(payload)) <> 5)) THEN + RAISE EXCEPTION 'gameplay revision differs from original complete binding' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + snapshot := NEW.snapshot_json::JSONB; + IF snapshot->>'schema' IS DISTINCT FROM 'game-design-gameplay-rule-source-snapshot/v1' + OR snapshot->>'bindingJson' IS DISTINCT FROM c.binding_json OR snapshot->>'bindingDigest' IS DISTINCT FROM c.input_digest + OR snapshot->>'genesisReceiptId' IS DISTINCT FROM g.receipt_id::TEXT + OR snapshot->>'inheritedCommitId' IS DISTINCT FROM coalesce(h.visible_commit_id::TEXT, '') + OR jsonb_typeof(snapshot->'entries') IS DISTINCT FROM 'array' + OR (SELECT count(*) FROM jsonb_object_keys(snapshot)) <> 8 THEN + RAISE EXCEPTION 'gameplay snapshot exact binding missing' USING ERRCODE = '23514'; END IF; + SELECT old_snapshot.snapshot_json::JSONB->'entries' INTO prior FROM game_design_gameplay_rule_snapshot old_snapshot + WHERE old_snapshot.canonical_tenant_id = NEW.canonical_tenant_id AND old_snapshot.canonical_version_id = NEW.canonical_version_id + AND old_snapshot.commit_id = h.visible_commit_id; + IF h.visible_commit_id IS NOT NULL AND prior IS NULL THEN RAISE EXCEPTION 'gameplay predecessor unavailable' USING ERRCODE = '23514'; END IF; + expected_entries := coalesce(prior, '[]'::JSONB); + IF TG_TABLE_NAME = 'game_design_gameplay_rule_application' THEN + IF NEW.expected_epoch IS DISTINCT FROM h.source_epoch OR snapshot->>'sourceEpoch' IS DISTINCT FROM (h.source_epoch::NUMERIC + 1)::TEXT + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_application_slot slot WHERE slot.canonical_tenant_id = NEW.canonical_tenant_id + AND slot.canonical_version_id = NEW.canonical_version_id AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT (c.binding_json::JSONB->'affectedUnits' @> jsonb_build_array(jsonb_build_object('owner', 'GAME_DESIGN_CONTROL_PLANE', + 'aggregateType', 'GAMEPLAY_RULE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, 'scopeType', 'GAMEPLAY_RULE_SET', + 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch))) THEN + RAISE EXCEPTION 'gameplay application scope epoch mismatch' USING ERRCODE = '23514'; END IF; + FOR r IN SELECT * FROM game_design_gameplay_rule_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id ORDER BY revision_order LOOP + SELECT EXISTS (SELECT 1 FROM jsonb_array_elements(expected_entries) item WHERE item->>'family' = r.family + AND gameplay_rule_definition_key(r.family, (item->>'definitionJson')::JSONB) = r.definition_key) INTO present; + IF r.operation_kind = 'DELETE' THEN + IF NOT present THEN RAISE EXCEPTION 'gameplay DELETE requires existing key' USING ERRCODE = '23514'; END IF; + SELECT coalesce(jsonb_agg(item ORDER BY ordinal), '[]'::JSONB) INTO expected_entries + FROM jsonb_array_elements(expected_entries) WITH ORDINALITY x(item, ordinal) + WHERE NOT (item->>'family' = r.family AND gameplay_rule_definition_key(r.family, (item->>'definitionJson')::JSONB) = r.definition_key); + ELSE + replacement := jsonb_build_object('family', r.family, 'definitionJson', r.payload_json::JSONB->>'definitionJson', + 'sourceBindingJson', c.binding_json, 'sourceBindingDigest', c.input_digest, + 'revisionOrder', r.revision_order::TEXT, 'revisionId', r.revision_id::TEXT); + IF present THEN + SELECT jsonb_agg(CASE WHEN item->>'family' = r.family AND gameplay_rule_definition_key(r.family, (item->>'definitionJson')::JSONB) = r.definition_key + THEN replacement ELSE item END ORDER BY ordinal) INTO expected_entries + FROM jsonb_array_elements(expected_entries) WITH ORDINALITY x(item, ordinal); + ELSE expected_entries := expected_entries || jsonb_build_array(replacement); END IF; + END IF; + END LOOP; + SELECT coalesce(jsonb_agg(item ORDER BY array_position(gameplay_rule_families(), item->>'family'), ordinal), '[]'::JSONB) + INTO expected_entries FROM jsonb_array_elements(expected_entries) WITH ORDINALITY x(item, ordinal); + ELSE + SELECT * INTO a FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT count(*) INTO declared_count FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE'; + IF (declared_count > 0) IS DISTINCT FROM (a.commit_id IS NOT NULL) OR snapshot->>'sourceEpoch' IS DISTINCT FROM h.source_epoch + OR (a.commit_id IS NOT NULL AND NEW.snapshot_json IS DISTINCT FROM a.snapshot_json) + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR c.workflow_state <> 'SYNCHRONIZED' + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility visible WHERE visible.canonical_tenant_id = NEW.canonical_tenant_id + AND visible.canonical_version_id = NEW.canonical_version_id AND visible.request_id = NEW.request_id + AND visible.commit_id = NEW.commit_id AND visible.input_digest = c.input_digest) THEN + RAISE EXCEPTION 'gameplay snapshot lacks synchronized complete owner source' USING ERRCODE = '23514'; END IF; + IF a.commit_id IS NOT NULL THEN expected_entries := a.snapshot_json::JSONB->'entries'; END IF; + END IF; + IF snapshot->'entries' IS DISTINCT FROM expected_entries THEN RAISE EXCEPTION 'gameplay snapshot must replay exact original revisions' USING ERRCODE = '23514'; END IF; + manifest := (snapshot->>'manifestJson')::JSONB; + IF manifest->>'schema' IS DISTINCT FROM 'gameplay-rule-manifest/v1' + OR (SELECT count(*) FROM jsonb_object_keys(manifest)) <> 2 + OR (SELECT count(*) FROM jsonb_object_keys(manifest->'families')) <> cardinality(gameplay_rule_families()) THEN + RAISE EXCEPTION 'gameplay snapshot inventory is incomplete' USING ERRCODE = '23514'; END IF; + FOREACH family IN ARRAY gameplay_rule_families() LOOP + SELECT coalesce(jsonb_agg((item->>'definitionJson')::JSONB ORDER BY ordinal), '[]'::JSONB) INTO family_values + FROM jsonb_array_elements(expected_entries) WITH ORDINALITY x(item, ordinal) WHERE item->>'family' = family; + IF manifest->'families'->family IS DISTINCT FROM family_values THEN + RAISE EXCEPTION 'gameplay manifest differs from its complete original source' USING ERRCODE = '23514'; END IF; + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION verify_gameplay_rule_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_gameplay_rule_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT r FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT h FROM game_design_gameplay_rule_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE'; + SELECT count(*) INTO retained FROM game_design_gameplay_rule_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-gameplay-rule-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'gameplay application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'gameplay mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'gameplay combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'gameplay scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'gameplay owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gameplay_rule_genesis_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_gameplay_rule_genesis FOR EACH ROW EXECUTE FUNCTION guard_gameplay_rule_source(); +CREATE TRIGGER gameplay_rule_head_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_gameplay_rule_head FOR EACH ROW EXECUTE FUNCTION guard_gameplay_rule_source(); +CREATE TRIGGER gameplay_rule_revision_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_gameplay_rule_revision FOR EACH ROW EXECUTE FUNCTION guard_gameplay_rule_source(); +CREATE TRIGGER gameplay_rule_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_gameplay_rule_application FOR EACH ROW EXECUTE FUNCTION guard_gameplay_rule_source(); +CREATE TRIGGER gameplay_rule_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_gameplay_rule_snapshot FOR EACH ROW EXECUTE FUNCTION guard_gameplay_rule_source(); +CREATE CONSTRAINT TRIGGER gameplay_rule_application_commit_guard AFTER INSERT ON game_design_gameplay_rule_application DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_gameplay_rule_application_commit(); +CREATE FUNCTION deny_gameplay_rule_truncate() RETURNS TRIGGER AS $$ +BEGIN RAISE EXCEPTION 'gameplay source history cannot be truncated' USING ERRCODE = '23514'; END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER gameplay_rule_genesis_no_truncate BEFORE TRUNCATE ON game_design_gameplay_rule_genesis EXECUTE FUNCTION deny_gameplay_rule_truncate(); +CREATE TRIGGER gameplay_rule_head_no_truncate BEFORE TRUNCATE ON game_design_gameplay_rule_head EXECUTE FUNCTION deny_gameplay_rule_truncate(); +CREATE TRIGGER gameplay_rule_revision_no_truncate BEFORE TRUNCATE ON game_design_gameplay_rule_revision EXECUTE FUNCTION deny_gameplay_rule_truncate(); +CREATE TRIGGER gameplay_rule_application_no_truncate BEFORE TRUNCATE ON game_design_gameplay_rule_application EXECUTE FUNCTION deny_gameplay_rule_truncate(); +CREATE TRIGGER gameplay_rule_snapshot_no_truncate BEFORE TRUNCATE ON game_design_gameplay_rule_snapshot EXECUTE FUNCTION deny_gameplay_rule_truncate(); +CREATE OR REPLACE FUNCTION verify_ordinary_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_asset_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; declared BIGINT; retained BIGINT; + components BYTEA; command_bytes BYTEA; policy_bytes BYTEA; gameplay_bytes BYTEA; epochs JSONB; unit JSONB; +BEGIN + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT r FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT h FROM game_design_asset_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_asset_source_revision x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id AND x.commit_id = NEW.commit_id; + bytes := convert_to('game-design-ordinary-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR r.status <> 'APPLIED' OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id + OR expected IS DISTINCT FROM NEW.result_bytes OR NOT (r.applied_units_json::JSONB @> jsonb_build_array(jsonb_build_object( + 'aggregateType', 'ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, 'scopeType', 'ASSET_REFERENCE_SET', + 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch, 'resultingEpoch', h.source_epoch))) THEN + RAISE EXCEPTION 'ordinary application requires atomic combined owner outcome' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); + components := int4send(octet_length(bytes)) || bytes; + epochs := '[]'::JSONB; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF command_bytes IS NOT NULL THEN + bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; + END IF; + bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + SELECT result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF gameplay_bytes IS NOT NULL THEN + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; + END IF; + SELECT result_bytes INTO policy_bytes FROM game_design_realm_policy_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND coalesce((x->>'payload')::JSONB->>'revisionKind', '') NOT IN ('COMMAND_DEFINITION', 'REALM_ENTRY_POLICY', 'ASSET_REFERENCE', 'GAMEPLAY_RULE')) + OR (command_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION') + OR (policy_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'REALM_ENTRY_POLICY') THEN + RAISE EXCEPTION 'ordinary mixed application requires every declared supported sibling source' USING ERRCODE = '23514'; END IF; + IF (gameplay_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE') THEN + RAISE EXCEPTION 'ordinary mixed application lacks exact declared gameplay source' USING ERRCODE = '23514'; END IF; + -- The vector has one entry per exact declared local scope, ordered as the Java composition. + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' + LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' + OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'ordinary combined scope unknown' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); + expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs + OR jsonb_array_length(epochs) <> (1 + CASE WHEN command_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN policy_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN gameplay_bytes IS NULL THEN 0 ELSE 1 END) THEN + RAISE EXCEPTION 'ordinary combined outcome must contain exact tagged components and complete epochs' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java index 700e8dd2a4..fc86741d1d 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java @@ -14,6 +14,7 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; @@ -27,6 +28,8 @@ import net.firedevops.firemud.gamedesign.publication.AssetSourceRepository; import net.firedevops.firemud.gamedesign.publication.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; +import net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; @@ -658,6 +661,395 @@ private Fixture fixture(MigrationVersion target) { new VersionAssetPublicationRepository(dsl)); } + @Test + void gameplaySourceAuthorsNonemptyReferencedCatalogWithMixedAssetsAndExactDurableRetry() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "gameplay-source"); + Version version = saveDraftVersion(fixture, owner, 1); + GameAsset asset = saveAsset(fixture, owner, "resource.png", "actual-source-bytes"); + var payloads = new java.util.ArrayList<>(gameplayPayloads()); + payloads.add( + AssetSource.upsertPayload( + asset.getId().toString(), asset.getFileName(), AssetSource.Requiredness.REQUIRED)); + var binding = sourceBinding(fixture, version, payloads.toArray(String[]::new)); + var application = inTransaction(fixture, () -> applySources(fixture, binding)); + var repository = new GameplayRuleSourceRepository(fixture.dsl()); + var snapshot = repository.requireCompleteForGameLogic(binding.target(), binding.commitId()); + + assertThat(snapshot.manifest().families()).hasSize(GameplayRuleManifest.Family.values().length); + assertThat(snapshot.manifest().families().get(GameplayRuleManifest.Family.ACTIONS)).hasSize(1); + assertThat(snapshot.entries()) + .allSatisfy(entry -> assertThat(entry.sourceBinding()).isEqualTo(binding)); + assertThat(application.gameplay().orElseThrow().snapshot().canonicalBytes()) + .containsExactly(snapshot.canonicalBytes()); + var restarted = new GameplayRuleSourceRepository(fixture.dsl()); + assertThat( + restarted + .requireCompleteForGameLogic(binding.target(), binding.commitId()) + .canonicalBytes()) + .containsExactly(snapshot.canonicalBytes()); + var retry = + inTransaction(fixture, () -> new GameDesignSourceRepository(fixture.dsl()).apply(binding)); + assertThat(retry.ownerOutcome()).isEqualTo(application.ownerOutcome()); + assertThat(retry.gameplay().orElseThrow().canonicalBytes()) + .containsExactly(application.gameplay().orElseThrow().canonicalBytes()); + + var disjoint = sourceBinding(fixture, version, AssetSource.deletePayload(asset.getFileName())); + inTransaction(fixture, () -> applySources(fixture, disjoint)); + var inherited = restarted.requireCompleteForGameLogic(disjoint.target(), disjoint.commitId()); + assertThat(inherited.sourceEpoch()).isEqualTo("1"); + assertThat(inherited.inheritedCommitId()).isEqualTo(binding.commitId()); + assertThat(inherited.manifest().canonicalBytes()) + .containsExactly(snapshot.manifest().canonicalBytes()); + assertThat(inherited.entries()) + .allSatisfy(entry -> assertThat(entry.sourceBinding()).isEqualTo(binding)); + assertThat( + restarted + .readSnapshot(binding.target(), binding.commitId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(snapshot.canonicalBytes()); + + var deletion = + sourceBinding( + fixture, + version, + GameplayRuleSource.deletePayload(GameplayRuleManifest.Family.ABILITIES, "focusAbility"), + GameplayRuleSource.deletePayload(GameplayRuleManifest.Family.ACTIONS, "focusAction")); + inTransaction(fixture, () -> applySources(fixture, deletion)); + assertThat( + restarted + .requireCompleteForGameLogic(deletion.target(), deletion.commitId()) + .sourceEpoch()) + .isEqualTo("2"); + assertThat( + restarted + .requireCompleteForGameLogic(deletion.target(), deletion.commitId()) + .manifest() + .families() + .get(GameplayRuleManifest.Family.ACTIONS)) + .isEmpty(); + } + + @Test + void gameplaySourceDeniesStaleEpochAndMissingRetainedVersionGenesis() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "gameplay-conflict"); + Version version = saveDraftVersion(fixture, owner, 1); + var first = sourceBinding(fixture, version, gameplayPayloads().toArray(String[]::new)); + var stale = + sourceBinding( + fixture, + version, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("newTag"))); + inTransaction(fixture, () -> applySources(fixture, first)); + assertThatThrownBy(() -> inTransaction(fixture, () -> applySources(fixture, stale))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_EPOCH_CONFLICT"); + assertThat( + new GameplayRuleSourceRepository(fixture.dsl()) + .readSnapshot(first.target(), stale.commitId())) + .isEmpty(); + + var unqualified = + new DraftCommitBinding.TargetProof( + first.target().canonicalTenantId(), + UUID.randomUUID(), + first.target().gameDesignVersionRowId(), + first.target().gameDesignVersionTenantKey(), + first.target().sourceGameRowId(), + first.target().sourceGameTenantKey(), + first.target().sourceProvenanceKind()); + assertThat(new GameplayRuleSourceRepository(fixture.dsl()).readGenesis(unqualified)).isEmpty(); + assertThatThrownBy( + () -> + new GameplayRuleSourceRepository(fixture.dsl()) + .requireCompleteForGameLogic(unqualified, first.commitId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_SELECTED_SOURCE_UNAVAILABLE"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_design_gameplay_rule_snapshot SET snapshot_json = '{}' WHERE canonical_version_id = ?", + version.getCanonicalVersionId())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_design_gameplay_rule_genesis WHERE canonical_version_id = ?", + version.getCanonicalVersionId())) + .isInstanceOf(RuntimeException.class); + } + + @Test + void preexistingQualifiedDraftCannotReceiveInventedGameplayInventoryAfterMigration() { + Fixture fixture = fixture(MigrationVersion.fromVersion("56")); + Game owner = saveGame(fixture, "retained-gameplay"); + UUID versionId = UUID.randomUUID(); + Long rowId = + fixture + .dsl() + .fetchSingle( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch, is_script_only, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, identity_source_game_tenant_key, identity_source_provenance_kind) " + + "SELECT tenant_id, 1, 'DRAFT', 1, FALSE, canonical_tenant_id, ?, id, tenant_id, tenant_identity_provenance_kind FROM game WHERE id = ? RETURNING id", + versionId, + owner.getId()) + .get(0, Long.class); + migrate(fixture.dataSource(), fixture.schema(), null); + Version retained = + fixture.versions().findByTenantIdAndId(owner.getTenantId(), rowId).orElseThrow(); + var target = + new DraftCommitBinding.TargetProof( + retained.getCanonicalTenantId(), + retained.getCanonicalVersionId(), + rowId, + retained.getTenantId(), + retained.getIdentitySourceGameRowId(), + retained.getIdentitySourceGameTenantKey(), + retained.getIdentitySourceProvenanceKind()); + var repository = new GameplayRuleSourceRepository(fixture.dsl()); + assertThat(repository.readGenesis(target)).isEmpty(); + assertThatThrownBy(() -> inTransaction(fixture, () -> repository.enrollFreshDraft(target))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_FRESH_INSERT_UNAVAILABLE"); + assertThat(repository.readGenesis(target)).isEmpty(); + assertThatThrownBy(() -> repository.requireCompleteForGameLogic(target, UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_SELECTED_SOURCE_UNAVAILABLE"); + } + + @Test + void gameplayHandoffDeniesUnqualifiedLegacyEffectiveCommands() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "legacy-command-source"); + Version version = saveDraftVersion(fixture, owner, 1); + var command = + "{\"schemaVersion\":1,\"commandId\":\"legacy\",\"semanticOwner\":\"GAME_LOGIC\"," + + "\"executionDiscipline\":\"DURABLE_GAMEPLAY\",\"stageRequirement\":\"GAMEPLAY\"," + + "\"promptPolicy\":\"WHEN_GAMEPLAY\",\"actionCategory\":\"GAMEPLAY\",\"historyRecordable\":true," + + "\"aliases\":[],\"actionTags\":[],\"effects\":[]}"; + var binding = sourceBinding(fixture, version, CommandSource.upsertPayload(command)); + inTransaction(fixture, () -> applySources(fixture, binding)); + assertThat( + new GameplayRuleSourceRepository(fixture.dsl()) + .readSnapshot(binding.target(), binding.commitId())) + .isPresent(); + assertThatThrownBy( + () -> + new GameplayRuleSourceRepository(fixture.dsl()) + .requireCompleteForGameLogic(binding.target(), binding.commitId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_LEGACY_COMMAND_SOURCE_NOT_CONVERGED"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void gameplayHandoffDeniesGenericRuleEvenWhenTypedRevisionMatches(boolean legacyBeforeSnapshot) { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "legacy-gameplay-source"); + Version version = saveDraftVersion(fixture, owner, 1); + var binding = sourceBinding(fixture, version, gameplayPayloads().toArray(String[]::new)); + var revision = binding.revisions().getFirst(); + if (!legacyBeforeSnapshot) { + inTransaction(fixture, () -> applySources(fixture, binding)); + } + fixture + .dsl() + .execute( + "INSERT INTO revision (tenant_id, version_id, author_account_id, revision_kind, logical_revision_id, data) " + + "VALUES (?, ?, 1, 'GAMEPLAY_RULE', ?, CAST(? AS JSONB))", + version.getTenantId(), + version.getId(), + revision.revisionId().toString(), + revision.payload()); + var retainedRows = fixture.dsl().fetch("SELECT * FROM revision ORDER BY id"); + if (legacyBeforeSnapshot) { + inTransaction(fixture, () -> applySources(fixture, binding)); + } + var repository = new GameplayRuleSourceRepository(fixture.dsl()); + var snapshot = repository.readSnapshot(binding.target(), binding.commitId()).orElseThrow(); + assertThat(snapshot.entries()).isNotEmpty(); + + assertThatThrownBy( + () -> repository.requireCompleteForGameLogic(binding.target(), binding.commitId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED"); + assertThatThrownBy( + () -> + new GameplayRuleSourceRepository(fixture.dsl()) + .requireCompleteForGameLogic(binding.target(), binding.commitId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED"); + assertThat(repository.readSnapshot(binding.target(), binding.commitId()).orElseThrow()) + .isEqualTo(snapshot); + assertThat(fixture.dsl().fetch("SELECT * FROM revision ORDER BY id")).isEqualTo(retainedRows); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void gameplayHandoffGenericRuleGuardUsesExactPrivateTenantAndVersion(boolean differentTenant) { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "scoped-legacy-gameplay-source"); + Version version = saveDraftVersion(fixture, owner, 1); + Version otherVersion = saveDraftVersion(fixture, owner, 2); + Game otherOwner = saveGame(fixture, "other-legacy-gameplay-source"); + var binding = sourceBinding(fixture, version, gameplayPayloads().toArray(String[]::new)); + inTransaction(fixture, () -> applySources(fixture, binding)); + var repository = new GameplayRuleSourceRepository(fixture.dsl()); + var snapshot = repository.requireCompleteForGameLogic(binding.target(), binding.commitId()); + // Generic history has no composite owner FK; scope both private keys even for retained rows. + fixture + .dsl() + .execute( + "INSERT INTO revision (tenant_id, version_id, author_account_id, revision_kind, data) " + + "VALUES (?, ?, 1, 'GAMEPLAY_RULE', '{}'::JSONB)", + differentTenant ? otherOwner.getTenantId() : owner.getTenantId(), + differentTenant ? version.getId() : otherVersion.getId()); + var retainedRows = fixture.dsl().fetch("SELECT * FROM revision ORDER BY id"); + + assertThat(repository.requireCompleteForGameLogic(binding.target(), binding.commitId())) + .isEqualTo(snapshot); + assertThat(fixture.dsl().fetch("SELECT * FROM revision ORDER BY id")).isEqualTo(retainedRows); + } + + @Test + void gameplayHandoffCannotClaimEmptyWhileGenericRuleHistoryExists() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "empty-with-legacy-gameplay-source"); + Version version = saveDraftVersion(fixture, owner, 1); + var binding = sourceBinding(fixture, version, CommandSource.deletePayload("not-present")); + inTransaction(fixture, () -> applySources(fixture, binding)); + var repository = new GameplayRuleSourceRepository(fixture.dsl()); + assertThat( + repository.requireCompleteForGameLogic(binding.target(), binding.commitId()).entries()) + .isEmpty(); + fixture + .dsl() + .execute( + "INSERT INTO revision (tenant_id, version_id, author_account_id, revision_kind, data) " + + "VALUES (?, ?, 1, 'GAMEPLAY_RULE', '{}'::JSONB)", + version.getTenantId(), + version.getId()); + var retainedRows = fixture.dsl().fetch("SELECT * FROM revision ORDER BY id"); + + assertThatThrownBy( + () -> repository.requireCompleteForGameLogic(binding.target(), binding.commitId())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED"); + assertThat(fixture.dsl().fetch("SELECT * FROM revision ORDER BY id")).isEqualTo(retainedRows); + } + + @Test + void mixedAssetGameplayOwnerResultRejectsSubstitutedRuleComponent() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "gameplay-component-substitution"); + Version version = saveDraftVersion(fixture, owner, 1); + GameAsset asset = saveAsset(fixture, owner, "resource.png", "actual-source-bytes"); + var payloads = new java.util.ArrayList<>(gameplayPayloads()); + payloads.add( + AssetSource.upsertPayload( + asset.getId().toString(), asset.getFileName(), AssetSource.Requiredness.REQUIRED)); + var binding = sourceBinding(fixture, version, payloads.toArray(String[]::new)); + assertThatThrownBy( + () -> + inTransaction( + fixture, + () -> { + var coordinator = new DraftCommitCoordinatorRepository(fixture.dsl()); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var assetResult = + new AssetSourceRepository(fixture.dsl()).apply(binding).orElseThrow(); + var gameplayResult = + new GameplayRuleSourceRepository(fixture.dsl()) + .apply(binding) + .orElseThrow(); + var components = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + components, "game-design-control-plane-sibling-components/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + components, "ASSET"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + components, assetResult.canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + components, "GAMEPLAY"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + components, assetResult.canonicalBytes()); + var result = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + result, "game-design-control-plane-ordinary-source-application/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + result, binding.canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + result, components.toByteArray()); + coordinator.recordOwnerOutcome( + binding, + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "substituted-rule-component", + result.toByteArray(), + List.of(assetResult.appliedEpoch(), gameplayResult.appliedEpoch()))); + return true; + })) + .isInstanceOf(RuntimeException.class); + assertThat( + new GameplayRuleSourceRepository(fixture.dsl()) + .readSnapshot(binding.target(), binding.commitId())) + .isEmpty(); + } + + private List gameplayPayloads() { + var action = + new GameplayRuleManifest.Action( + "focusAction", + "Focus", + List.of("canFocus"), + List.of(), + List.of( + new GameplayRuleManifest.Cost( + "energy", + java.math.BigDecimal.ONE, + GameplayRuleManifest.CommitPolicy.ON_EXECUTION)), + List.of( + new GameplayRuleManifest.Cooldown( + "focusCooldown", 3L, GameplayRuleManifest.CommitPolicy.ON_EFFECT_SUCCESS)), + List.of(new GameplayRuleManifest.EffectBinding("restore", "SOURCE")), + List.of()); + List definitions = + List.of( + new GameplayRuleManifest.AdmissionTag("canFocus"), + new GameplayRuleManifest.Resource( + "energy", + java.math.BigDecimal.TEN, + java.math.BigDecimal.ZERO, + java.math.BigDecimal.TEN, + java.math.BigDecimal.valueOf(100), + GameplayRuleManifest.Visibility.PUBLIC, + List.of()), + new GameplayRuleManifest.Effect( + "restore", + GameplayRuleManifest.Lifecycle.INSTANT, + GameplayRuleManifest.EffectOperation.ADJUST_RESOURCE, + "energy", + null, + java.math.BigDecimal.ONE, + null, + null), + action, + new GameplayRuleManifest.Ability("focusAbility", "Focus ability", "focusAction")); + return definitions.stream().map(GameplayRuleSource::upsertPayload).toList(); + } + private DriverManagerDataSource dataSource(String schema) { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setUrl(POSTGRES.getJdbcUrl()); @@ -779,18 +1171,27 @@ private DraftCommitBinding sourceBinding(Fixture fixture, Version version, Strin DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, payloads[index])); } - for (String scope : List.of(CommandSource.SCOPE, AssetSource.SCOPE, RealmPolicySource.SCOPE)) { + for (String scope : + List.of( + CommandSource.SCOPE, + AssetSource.SCOPE, + RealmPolicySource.SCOPE, + GameplayRuleSource.SCOPE)) { String kind = scope.equals(AssetSource.SCOPE) ? "ASSET_REFERENCE" - : scope.equals(RealmPolicySource.SCOPE) ? "REALM_ENTRY_POLICY" : "COMMAND_DEFINITION"; + : scope.equals(RealmPolicySource.SCOPE) + ? "REALM_ENTRY_POLICY" + : scope.equals(GameplayRuleSource.SCOPE) ? "GAMEPLAY_RULE" : "COMMAND_DEFINITION"; if (List.of(payloads).stream().noneMatch(payload -> payload.contains(kind))) continue; String table = scope.equals(AssetSource.SCOPE) ? "game_design_asset_source_head" : scope.equals(RealmPolicySource.SCOPE) ? "game_design_realm_policy_source" - : "game_design_command_source_head"; + : scope.equals(GameplayRuleSource.SCOPE) + ? "game_design_gameplay_rule_head" + : "game_design_command_source_head"; String epoch = fixture .dsl() diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index f8a9c59840..986cc54765 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -1000,18 +1000,31 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( (tools.jackson.databind.node.ObjectNode) mapper.readTree(operation.inventory().canonicalBytes()); var model = (tools.jackson.databind.node.ObjectNode) publicJson.get("sourceModel"); + String expectedRejectionMessage; switch (mutation) { - case 0 -> - ((tools.jackson.databind.node.ObjectNode) publicJson.get("ownerScope")) - .remove("intakeReceiptDigest"); - case 1 -> model.put("unknownSourceFamily", true); - case 2 -> model.putArray("familyCounts"); - case 3 -> - ((tools.jackson.databind.node.ObjectNode) model.get("regionGeneratorInputs").get(0)) - .put("generatorType", "opaque"); - case 4 -> - ((tools.jackson.databind.node.ObjectNode) model.get("familyCounts").get(2)) - .put("rowCount", 0); + case 0 -> { + ((tools.jackson.databind.node.ObjectNode) publicJson.get("ownerScope")) + .remove("intakeReceiptDigest"); + expectedRejectionMessage = "Incomplete or unknown public inventory members"; + } + case 1 -> { + model.put("unknownSourceFamily", true); + expectedRejectionMessage = "Incomplete or unknown public inventory members"; + } + case 2 -> { + model.putArray("familyCounts"); + expectedRejectionMessage = "Unsupported public inventory source profile"; + } + case 3 -> { + ((tools.jackson.databind.node.ObjectNode) model.get("regionGeneratorInputs").get(0)) + .put("generatorType", "opaque"); + expectedRejectionMessage = "Unsupported or unordered region generator input"; + } + case 4 -> { + ((tools.jackson.databind.node.ObjectNode) model.get("familyCounts").get(2)) + .put("rowCount", 0); + expectedRejectionMessage = "Source inventory counts differ from explicit inputs"; + } default -> throw new AssertionError(); } byte[] changedInventory = @@ -1036,7 +1049,12 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( () -> dsl.fetch( "SELECT require_selected_inventory_operation_v2(?)", bytes.toByteArray())) - .isInstanceOf(org.jooq.exception.DataAccessException.class); + .rootCause() + .isInstanceOf(java.sql.SQLException.class) + .hasMessageContaining(expectedRejectionMessage) + .satisfies( + failure -> + assertThat(((java.sql.SQLException) failure).getSQLState()).isEqualTo("23514")); } dsl.fetch("SELECT require_selected_inventory_operation_v2(?)", operation.canonicalBytes()); // Supply the historical three-frame schema without retrofitting any retained owner rows. diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcServiceTest.java new file mode 100644 index 0000000000..d0c6fc3757 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadGrpcServiceTest.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceRequest; +import net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceResponse; +import org.junit.jupiter.api.Test; + +class GameDesignGameplayRuleSourceReadGrpcServiceTest { + @Test + void authenticatesExactAccountOrGameLogicBeforeDecoding() { + var owner = mock(GameDesignGameplayRuleSourceReadService.class); + var service = new GameDesignGameplayRuleSourceReadGrpcService(owner, "test"); + var malformed = ReadSelectedGameplayRuleSourceRequest.newBuilder().setSchemaVersion(-1).build(); + var missing = new Collector(); + service.readSelectedGameplayRuleSource(malformed, missing); + assertThat(missing.error).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String caller : new String[] {"game-design-service", "world-management-service"}) { + var result = new Collector(); + peer("test", caller).run(() -> service.readSelectedGameplayRuleSource(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + for (String caller : new String[] {"account-service", "game-logic-service"}) { + var result = new Collector(); + peer("test", caller).run(() -> service.readSelectedGameplayRuleSource(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(owner); + } + + private static Context peer(String namespace, String service) { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow()); + } + + private static final class Collector + implements StreamObserver { + Status.Code error; + + public void onNext(ReadSelectedGameplayRuleSourceResponse value) { + throw new AssertionError("No positive result"); + } + + public void onError(Throwable value) { + error = Status.fromThrowable(value).getCode(); + } + + public void onCompleted() { + throw new AssertionError("No successful read"); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java new file mode 100644 index 0000000000..2a9a79fd5e --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.gamedesign.publication; + +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.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; + +class GameDesignGameplayRuleSourceReadServiceTest { + @Test + void exportsOnlyTheCompleteOwnerReadForTheExactSynchronizedBinding() { + var repository = mock(GameplayRuleSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + when(transactions.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); + var owner = new GameDesignGameplayRuleSourceReadService(repository, transactions, "test"); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var selected = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + target.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + var snapshot = + new GameplayRuleSnapshot( + selected, "1", null, UUID.randomUUID(), GameplayRuleSource.replay(List.of(), selected)); + when(repository.requireCompleteForGameLogic(target, selected.commitId())).thenReturn(snapshot); + var request = GameplayRuleSourceReadEvidence.Request.create("test", selected); + var result = new AtomicReference(); + asAccount(() -> result.set(owner.read(request))); + assertThat(result.get().source().canonicalBytes()).containsExactly(snapshot.canonicalBytes()); + assertThat(result.get().source().manifest()).isEqualTo(snapshot.manifest()); + verify(repository).requireCompleteForGameLogic(target, selected.commitId()); + + when(repository.requireCompleteForGameLogic(target, selected.commitId())) + .thenThrow(new IllegalStateException("GAMEPLAY_RULE_LEGACY_COMMAND_SOURCE_NOT_CONVERGED")); + assertThatThrownBy(() -> asAccount(() -> owner.read(request))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("NOT_CONVERGED"); + } + + private static void asAccount(Runnable action) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/account-service").orElseThrow()) + .run(action); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java new file mode 100644 index 0000000000..7ae8cbb3e0 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java @@ -0,0 +1,376 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Ability; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Action; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActionCategory; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActionTag; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActorRole; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.AdmissionTag; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CandidateSelector; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CapacityChangePolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cardinality; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Command; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CommitPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Condition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ContinuousOverlay; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cooldown; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cost; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.DefaultBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Definition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.DurationPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Effect; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.EffectBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.EffectOperation; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ExecutionDiscipline; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Lifecycle; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ObservationPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Predicate; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PredicateKind; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PrimitiveKind; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PromptPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Reapplication; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ReplayPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Resource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.SelectionPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.SelectionStrategy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stage; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stat; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.StatField; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetSet; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetingPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import org.junit.jupiter.api.Test; + +class GameplayRuleSourceTest { + private static final TargetProof TARGET = + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + "private-owner-key", + 1L, + "private-owner-key", + "NEW_GAME_ROW"); + + @Test + void realNonemptyCatalogRetainsOrderedDeclarationsAndEveryOriginalRevision() { + var manifest = exampleManifest(); + var binding = + binding( + manifest.families().values().stream() + .flatMap(List::stream) + .map(GameplayRuleSource::upsertPayload) + .toList()); + var entries = GameplayRuleSource.replay(List.of(), binding); + var snapshot = new GameplayRuleSnapshot(binding, "1", null, UUID.randomUUID(), entries); + var read = GameplayRuleSnapshot.fromStored(snapshot.canonicalJson()); + + assertThat(read.canonicalBytes()).containsExactly(snapshot.canonicalBytes()); + assertThat(read.manifest().canonicalBytes()).containsExactly(manifest.canonicalBytes()); + assertThat(read.entries()).hasSize(entries.size()); + assertThat(read.entries()) + .allSatisfy(entry -> assertThat(entry.sourceBinding()).isEqualTo(binding)); + var action = (Action) read.manifest().families().get(Family.ACTIONS).getFirst(); + assertThat(action.admissionTags()).containsExactly("gameplay", "canFocus"); + assertThat(action.effects()) + .extracting(EffectBinding::effectKey) + .containsExactly("restore", "cleanse"); + var command = (Command) read.manifest().families().get(Family.COMMANDS).getFirst(); + assertThat(command.actionTags()).containsExactly(ActionTag.COMBAT); + assertThat(command.admissionTags()).containsExactly("gameplay", "canFocus"); + } + + @Test + void inheritedCatalogPreservesUnchangedProvenanceAndExplicitDelete() { + var initial = + binding( + List.of( + GameplayRuleSource.upsertPayload(new AdmissionTag("first")), + GameplayRuleSource.upsertPayload(new AdmissionTag("second")))); + var original = GameplayRuleSource.replay(List.of(), initial); + var changed = + binding( + List.of( + GameplayRuleSource.deletePayload(Family.ADMISSION_TAGS, "first"), + GameplayRuleSource.upsertPayload(new AdmissionTag("third")))); + var replayed = GameplayRuleSource.replay(original, changed); + assertThat(replayed) + .extracting(entry -> entry.definition().key()) + .containsExactly("second", "third"); + assertThat(replayed.getFirst().sourceBinding()).isEqualTo(initial); + assertThat(replayed.getLast().sourceBinding()).isEqualTo(changed); + assertThatThrownBy( + () -> + GameplayRuleSource.replay( + replayed, + binding( + List.of( + GameplayRuleSource.deletePayload(Family.ADMISSION_TAGS, "missing"))))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void incompleteInventoryAndUnresolvedReferencesDenyInsteadOfBecomingEmpty() { + var families = + new EnumMap>(GameplayRuleManifest.explicitEmpty().families()); + families.remove(Family.FEEDBACK); + assertThatThrownBy(() -> new GameplayRuleManifest(families)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleSource.replay( + List.of(), + binding( + List.of( + GameplayRuleSource.upsertPayload( + new Ability("ability", "Ability", "missingAction")))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unresolved ACTIONS"); + assertThatThrownBy( + () -> + GameplayRuleManifest.fromStored( + "{\"schema\":\"gameplay-rule-manifest/v1\",\"families\":{}}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void unknownDefinitionFieldsDuplicateFieldsAndMissingAdmissionTagsDeny() { + String command = + GameplayRuleManifest.canonical( + exampleManifest().families().get(Family.COMMANDS).getFirst()); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.COMMANDS, + command.replace("\"admissionTags\":[\"gameplay\",\"canFocus\"],", ""))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.ADMISSION_TAGS, "{\"tagKey\":\"tag\",\"unknownPolicy\":true}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.ADMISSION_TAGS, "{\"tagKey\":\"first\",\"tagKey\":\"second\"}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition(Family.ADMISSION_TAGS, "{\"tagKey\":\"first\"} {}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleSource.mutations( + binding(List.of("{\"revisionKind\":\"UNKNOWN_RULE_FAMILY\"}")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void continuousEffectsCannotBecomeInstantActionEffectsOrGrantDeniedAdmission() { + var source = exampleManifest(); + var families = new EnumMap>(source.families()); + Action action = (Action) families.get(Family.ACTIONS).getFirst(); + families.put( + Family.ACTIONS, + List.of( + new Action( + action.key(), + action.name(), + action.admissionTags(), + action.targetSets(), + action.costs(), + action.cooldowns(), + List.of(new EffectBinding("capacity", "SOURCE")), + action.feedbackKeys()))); + assertThatThrownBy(() -> new GameplayRuleManifest(families)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.CONTINUOUS_OVERLAYS, + GameplayRuleManifest.canonical( + Map.of( + "overlayKey", + "overlay", + "eligibleWhen", + truth(), + "deniedAdmissionTags", + List.of(), + "effectKeys", + List.of(), + "grantedAdmissionTags", + List.of("gameplay"))))) + .isInstanceOf(IllegalArgumentException.class); + } + + static GameplayRuleManifest exampleManifest() { + List definitions = + List.of( + new Stat( + "focus", + PrimitiveKind.NUMERIC, + BigDecimal.ONE, + null, + BigDecimal.ZERO, + BigDecimal.TEN, + Visibility.PUBLIC, + List.of()), + new Resource( + "energy", + BigDecimal.TEN, + BigDecimal.ZERO, + BigDecimal.TEN, + BigDecimal.valueOf(100), + Visibility.PUBLIC, + List.of()), + new Condition( + "weary", + Reapplication.REFRESH, + DurationPolicy.RESET, + 5L, + null, + Visibility.PUBLIC, + List.of(), + List.of(), + 0), + new Effect( + "restore", + Lifecycle.INSTANT, + EffectOperation.ADJUST_RESOURCE, + "energy", + null, + BigDecimal.ONE, + null, + null), + new Effect( + "cleanse", + Lifecycle.INSTANT, + EffectOperation.REMOVE_CONDITION, + null, + null, + null, + "weary", + null), + new Effect( + "capacity", + Lifecycle.CONTINUOUS, + EffectOperation.ADD, + "energy", + StatField.MAXIMUM, + BigDecimal.ONE, + null, + CapacityChangePolicy.CLAMP_ONLY), + new AdmissionTag("gameplay"), + new AdmissionTag("canFocus"), + new Feedback( + "unavailable", + "ACTION_REJECTED", + Audience.SOURCE_ACTOR, + "action.unavailable", + "Unavailable.", + List.of(), + Visibility.PRIVATE, + ReplayPolicy.EFFECT_IDEMPOTENT), + new Disposition("ready", List.of(), "unavailable"), + new ContinuousOverlay( + "wearyOverlay", + new Predicate( + PredicateKind.CONDITION_PRESENT, + ActorRole.SOURCE, + "weary", + null, + null, + List.of()), + List.of("canFocus"), + List.of("capacity")), + new ObservationPolicy("observable", truth()), + new TargetingPolicy( + "self", CandidateSelector.SELF, "observable", truth(), "unavailable"), + new SelectionPolicy( + "one", + Cardinality.EXACTLY_ONE, + null, + null, + SelectionStrategy.CANONICAL_ORDER, + null, + List.of()), + new DefaultBinding( + "focusDefault", List.of(new TargetSet("subject", "self", "one", true, null, null))), + new Action( + "focusAction", + "Focus", + List.of("gameplay", "canFocus"), + List.of(new TargetSet("subject", "self", "one", true, null, null)), + List.of(new Cost("energy", BigDecimal.ONE, CommitPolicy.ON_EXECUTION)), + List.of(new Cooldown("focusCooldown", 3L, CommitPolicy.ON_EFFECT_SUCCESS)), + List.of( + new EffectBinding("restore", "subject"), + new EffectBinding("cleanse", "SOURCE")), + List.of("unavailable")), + new Ability("focusAbility", "Focus ability", "focusAction"), + new Command( + "focusCommand", + "focusAction", + "GAME_LOGIC", + ExecutionDiscipline.DURABLE_GAMEPLAY, + Stage.GAMEPLAY, + PromptPolicy.WHEN_GAMEPLAY, + ActionCategory.GAMEPLAY, + true, + List.of("focus"), + List.of(ActionTag.COMBAT), + List.of("gameplay", "canFocus"))); + Map> families = new EnumMap<>(Family.class); + for (Family family : Family.values()) families.put(family, new ArrayList<>()); + for (Definition definition : definitions) families.get(definition.family()).add(definition); + return new GameplayRuleManifest(families); + } + + private static Predicate truth() { + return new Predicate(PredicateKind.TRUE, null, null, null, null, List.of()); + } + + private static DraftCommitBinding binding(List payloads) { + List revisions = new ArrayList<>(); + for (int i = 0; i < payloads.size(); i++) + revisions.add( + new RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads.get(i))); + return DraftCommitBinding.create( + TARGET, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + TARGET.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java index 34efaaa994..8179b68126 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java @@ -8,6 +8,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.List; @@ -25,6 +26,8 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -69,6 +72,32 @@ void saveRevisionPersistsEntity() { assertEquals(10L, result.id()); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void saveRevisionRejectsGameplayRulesBeforeAnyRepositoryOrWorldCall(boolean withWorldMutation) { + RevisionDto dto = + new RevisionDto( + null, + "1", + 7L, + 3L, + "{}", + "GAMEPLAY_RULE", + "rule-revision", + withWorldMutation ? generationSubtreeMutation() : null, + null, + null); + + IllegalArgumentException ex = + assertThrows(IllegalArgumentException.class, () -> service.saveRevision(dto)); + + assertEquals( + "INVALID_ARGUMENT: GAMEPLAY_RULE requires authorized coordinated source authoring", + ex.getMessage()); + verifyNoInteractions( + gameRepository, versionRepository, revisionRepository, worldManagementClient); + } + @Test void saveRevisionRejectsPublishedVersionBeforePersistingOrApplyingMutations() { Game game = new Game(); diff --git a/services/game-logic-service/build.gradle.kts b/services/game-logic-service/build.gradle.kts index dbd48d7512..513a7bcb07 100644 --- a/services/game-logic-service/build.gradle.kts +++ b/services/game-logic-service/build.gradle.kts @@ -4,6 +4,12 @@ apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { id("net.firedevops.firemud.service-conventions") id("net.firedevops.firemud.openapi-conventions") + id("net.firedevops.firemud.sql-postgres-conventions") + id("net.firedevops.firemud.jooq-conventions") +} + +firemudJooq { + packageName.set("net.firedevops.firemud.gamelogic.jooq") } dependencies { diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeOperation.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeOperation.java new file mode 100644 index 0000000000..c7ab1566c0 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeOperation.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact namespace and Account authorization identity for one independent GL source intake. */ +public record GameLogicGameplayRuleIntakeOperation( + String targetNamespace, GameLogicIntakeAuthorizationBinding authorization) { + public static final String SCHEMA = "game-logic-gameplay-rule-intake-operation/v1"; + + public GameLogicGameplayRuleIntakeOperation { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical intake namespace required"); + } + Objects.requireNonNull(authorization, "Original Account intake order required"); + } + + public byte[] canonicalBytes() { + var output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, targetNamespace); + DraftAuthorizationFenceBinding.frame(output, authorization.canonicalBytes()); + return output.toByteArray(); + } + + public byte[] authorizationBytes() { + return authorization.canonicalBytes(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static GameLogicGameplayRuleIntakeOperation fromStored(byte[] original) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(original); + reader.expect(SCHEMA); + var operation = + new GameLogicGameplayRuleIntakeOperation( + reader.text(), GameLogicIntakeAuthorizationBinding.fromStored(reader.bytes())); + reader.requireEnd(); + if (!Arrays.equals(original, operation.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical GL intake operation"); + } + return operation; + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java new file mode 100644 index 0000000000..b4b858e3d2 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java @@ -0,0 +1,108 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Owner-local immutable intake evidence storage. All writes require the caller's local transaction. + */ +public final class GameLogicGameplayRuleIntakeRepository { + private static final long OPERATION_LOCK_NAMESPACE = 0x474c494e54414b45L; + + private final DSLContext dsl; + + public GameLogicGameplayRuleIntakeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** Serializes fresh retention and explicit abort before a row exists and on exact retries. */ + public void lockOperation(UUID operationId) { + requireReadCommittedTransaction(); + dsl.fetch( + "select pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended(?, ?))", + "game-logic-source-intake:" + operationId, + OPERATION_LOCK_NAMESPACE); + } + + /** Immutable readback is independent of Account's later settlement state. */ + public Optional findTerminal(UUID operationId) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_logic_gameplay_rule_intake_terminal WHERE operation_id = ?", + Objects.requireNonNull(operationId, "operationId")); + if (row == null) return Optional.empty(); + byte[] terminalBytes = row.get("terminal_bytes", byte[].class); + var terminal = GameLogicGameplayRuleIntakeTerminal.fromStored(terminalBytes); + var operation = terminal.operation(); + var authorization = operation.authorization(); + var sourceBinding = authorization.source().binding(); + if (!operationId.equals(row.get("operation_id", UUID.class)) + || !operation.targetNamespace().equals(row.get("target_namespace", String.class)) + || !authorization.actorAccountId().equals(row.get("actor_account_id", UUID.class)) + || !authorization.tenantId().equals(row.get("canonical_tenant_id", UUID.class)) + || !authorization.versionId().equals(row.get("canonical_version_id", UUID.class)) + || !sourceBinding.commitId().equals(row.get("selected_commit_id", UUID.class)) + || !operation.digest().equals(row.get("operation_digest", String.class)) + || !authorization.digest().equals(row.get("authorization_digest", String.class)) + || !terminal.outcome().name().equals(row.get("outcome", String.class)) + || !terminal.digest().equals(row.get("terminal_digest", String.class)) + || !java.util.Arrays.equals( + authorization.canonicalBytes(), row.get("authorization_bytes", byte[].class)) + || !same(terminal.selectedSourceBytes(), row.get("selected_source_bytes", byte[].class)) + || !same(terminal.manifestBytes(), row.get("manifest_bytes", byte[].class)) + || !Objects.equals( + terminal.selectedSourceDigest(), row.get("selected_source_digest", String.class)) + || !Objects.equals(terminal.manifestDigest(), row.get("manifest_digest", String.class))) { + throw new IllegalStateException("GL_GAMEPLAY_RULE_INTAKE_READBACK_CONFLICT"); + } + return Optional.of(terminal); + } + + /** One INSERT stores order, exact GD provenance, manifest, and RETAINED terminal atomically. */ + public void insertTerminal(GameLogicGameplayRuleIntakeTerminal terminal) { + requireReadCommittedTransaction(); + Objects.requireNonNull(terminal, "terminal"); + var operation = terminal.operation(); + var authorization = operation.authorization(); + dsl.execute( + "INSERT INTO game_logic_gameplay_rule_intake_terminal (operation_id, target_namespace, " + + "actor_account_id, canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "operation_digest, authorization_digest, authorization_bytes, outcome, " + + "selected_source_bytes, selected_source_digest, manifest_bytes, manifest_digest, " + + "terminal_bytes, terminal_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + authorization.operationId(), + operation.targetNamespace(), + authorization.actorAccountId(), + authorization.tenantId(), + authorization.versionId(), + authorization.source().binding().commitId(), + operation.digest(), + authorization.digest(), + terminal.authorizationBytes(), + terminal.outcome().name(), + terminal.selectedSourceBytes(), + terminal.selectedSourceDigest(), + terminal.manifestBytes(), + terminal.manifestDigest(), + terminal.canonicalBytes(), + terminal.digest()); + } + + private static void requireReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !Integer.valueOf( + org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "GL intake storage requires an owner READ COMMITTED transaction"); + } + } + + private static boolean same(byte[] left, byte[] right) { + return java.util.Arrays.equals(left, right); + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java new file mode 100644 index 0000000000..53d0c12885 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java @@ -0,0 +1,196 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered owner-local exact-source intake. The caller is the same-namespace GD workload; + * Account and GD reads complete before this service opens its independent retention transaction. + */ +public final class GameLogicGameplayRuleIntakeService { + private final GameLogicGameplayRuleIntakeRepository repository; + private final GameLogicIntakeAuthorizationReadClient accountAuthorizationReader; + private final GameplayRuleSourceReadClient gameDesignSourceReader; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + + public GameLogicGameplayRuleIntakeService( + GameLogicGameplayRuleIntakeRepository repository, + PlatformTransactionManager transactionManager, + GameLogicIntakeAuthorizationReadClient accountAuthorizationReader, + GameplayRuleSourceReadClient gameDesignSourceReader, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.accountAuthorizationReader = + Objects.requireNonNull(accountAuthorizationReader, "accountAuthorizationReader"); + this.gameDesignSourceReader = + Objects.requireNonNull(gameDesignSourceReader, "gameDesignSourceReader"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Logic workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + ownerTransaction.setName("game-logic-gameplay-rule-source-intake"); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** Returns the original terminal for exact retries, including after Account settles the order. */ + public GameLogicGameplayRuleIntakeTerminal retain( + net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding authorization) { + var operation = requestOperation(authorization); + requireNoActiveTransaction(); + Optional prior = + repository.findTerminal(authorization.operationId()); + if (prior.isPresent()) return exactTerminal(prior.orElseThrow(), operation); + + var authorizationRequest = + GameLogicIntakeAuthorizationReadEvidence.Request.create(workloadNamespace, authorization); + var held = accountAuthorizationReader.read(authorizationRequest); + if (held == null || !authorizationRequest.equals(held.request())) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact HELD Account intake authorization required") + .asRuntimeException(); + } + + var selectedBinding = authorization.source().binding(); + var sourceRequest = + GameplayRuleSourceReadEvidence.Request.create(workloadNamespace, selectedBinding); + var sourceEvidence = gameDesignSourceReader.read(sourceRequest); + if (sourceEvidence == null + || !sourceRequest.equals(sourceEvidence.request()) + || !Arrays.equals( + authorization.source().canonicalBytes(), sourceEvidence.source().canonicalBytes())) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact complete selected GD source differs from Account authorization") + .asRuntimeException(); + } + + byte[] sourceBytes = sourceEvidence.source().canonicalBytes(); + byte[] manifestBytes = + sourceEvidence.source().manifest().canonicalJson().getBytes(StandardCharsets.UTF_8); + var retained = + GameLogicGameplayRuleIntakeTerminal.retained(operation, sourceBytes, manifestBytes); + return ownerTransaction.execute( + status -> { + repository.lockOperation(authorization.operationId()); + var concurrent = repository.findTerminal(authorization.operationId()); + if (concurrent.isPresent()) return exactTerminal(concurrent.orElseThrow(), operation); + repository.insertTerminal(retained); + return repository + .findTerminal(authorization.operationId()) + .filter(value -> Arrays.equals(value.canonicalBytes(), retained.canonicalBytes())) + .orElseThrow( + () -> + new IllegalStateException( + "GL_GAMEPLAY_RULE_INTAKE_COMMIT_READBACK_MISMATCH")); + }); + } + + /** No value means there is no actual owner terminal; ABORTED is an explicit durable terminal. */ + public Optional readTerminal( + net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding authorization) { + var operation = requestOperation(authorization); + requireNoActiveTransaction(); + return repository + .findTerminal(authorization.operationId()) + .map(value -> exactTerminal(value, operation)); + } + + /** Explicit owner abort is serialized with retention and never inferred from a read failure. */ + public GameLogicGameplayRuleIntakeTerminal abort( + net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding authorization) { + var operation = requestOperation(authorization); + requireNoActiveTransaction(); + Optional prior = + repository.findTerminal(authorization.operationId()); + if (prior.isPresent()) return exactTerminal(prior.orElseThrow(), operation); + + var authorizationRequest = + GameLogicIntakeAuthorizationReadEvidence.Request.create(workloadNamespace, authorization); + var held = accountAuthorizationReader.read(authorizationRequest); + if (held == null || !authorizationRequest.equals(held.request())) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact HELD Account intake authorization required for explicit abort") + .asRuntimeException(); + } + + return ownerTransaction.execute( + status -> { + repository.lockOperation(authorization.operationId()); + var concurrent = repository.findTerminal(authorization.operationId()); + if (concurrent.isPresent()) return exactTerminal(concurrent.orElseThrow(), operation); + var aborted = GameLogicGameplayRuleIntakeTerminal.aborted(operation); + repository.insertTerminal(aborted); + return repository + .findTerminal(authorization.operationId()) + .filter(value -> Arrays.equals(value.canonicalBytes(), aborted.canonicalBytes())) + .orElseThrow( + () -> + new IllegalStateException("GL_GAMEPLAY_RULE_INTAKE_ABORT_READBACK_MISMATCH")); + }); + } + + private GameLogicGameplayRuleIntakeOperation requestOperation( + net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding authorization) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + if (!peer.isInNamespace(workloadNamespace) + || !peer.isService("game-design-service") + || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + if (AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get() != null) { + throw Status.PERMISSION_DENIED + .withDescription("Creator publication credentials cannot accompany GL source intake") + .asRuntimeException(); + } + if (authorization == null) { + throw Status.INVALID_ARGUMENT + .withDescription("Original GL intake authorization required") + .asRuntimeException(); + } + return new GameLogicGameplayRuleIntakeOperation(workloadNamespace, authorization); + } + + private static GameLogicGameplayRuleIntakeTerminal exactTerminal( + GameLogicGameplayRuleIntakeTerminal terminal, + GameLogicGameplayRuleIntakeOperation requested) { + if (!Arrays.equals(terminal.operation().canonicalBytes(), requested.canonicalBytes())) { + throw Status.ALREADY_EXISTS + .withDescription("GL intake operation identity was reused with changed authorization") + .asRuntimeException(); + } + return terminal; + } + + private static void requireNoActiveTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("GL intake owner reads must run outside SQL") + .asRuntimeException(); + } + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminal.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminal.java new file mode 100644 index 0000000000..f00bbf0791 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminal.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; + +/** Durable owner terminal. Empty/absent storage is represented separately from ABORTED. */ +public final class GameLogicGameplayRuleIntakeTerminal { + public static final String SCHEMA = "game-logic-gameplay-rule-intake-terminal/v1"; + + public enum Outcome { + RETAINED, + ABORTED + } + + private final GameLogicGameplayRuleIntakeOperation operation; + private final Outcome outcome; + private final byte[] authorizationBytes; + private final byte[] selectedSourceBytes; + private final byte[] manifestBytes; + + private GameLogicGameplayRuleIntakeTerminal( + GameLogicGameplayRuleIntakeOperation operation, + Outcome outcome, + byte[] authorizationBytes, + byte[] selectedSourceBytes, + byte[] manifestBytes) { + this.operation = Objects.requireNonNull(operation, "operation"); + this.outcome = Objects.requireNonNull(outcome, "outcome"); + this.authorizationBytes = copy(authorizationBytes); + this.selectedSourceBytes = nullableCopy(selectedSourceBytes); + this.manifestBytes = nullableCopy(manifestBytes); + if (!Arrays.equals(this.authorizationBytes, operation.authorizationBytes())) { + throw new IllegalArgumentException("Terminal authorization differs from its operation"); + } + if (outcome == Outcome.RETAINED) { + if (this.selectedSourceBytes == null || this.manifestBytes == null) { + throw new IllegalArgumentException("Retained terminal requires source and manifest bytes"); + } + var source = + new GameplayRuleSelectedSource( + new String(this.selectedSourceBytes, StandardCharsets.UTF_8)); + if (!Arrays.equals(this.selectedSourceBytes, source.canonicalBytes()) + || !Arrays.equals( + this.selectedSourceBytes, operation.authorization().source().canonicalBytes()) + || !Arrays.equals( + this.manifestBytes, + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException( + "Retained source or manifest differs from authorization"); + } + } else if (this.selectedSourceBytes != null || this.manifestBytes != null) { + throw new IllegalArgumentException("Aborted terminal cannot claim retained source"); + } + } + + public static GameLogicGameplayRuleIntakeTerminal retained( + GameLogicGameplayRuleIntakeOperation operation, byte[] sourceBytes, byte[] manifestBytes) { + return new GameLogicGameplayRuleIntakeTerminal( + operation, Outcome.RETAINED, operation.authorizationBytes(), sourceBytes, manifestBytes); + } + + public static GameLogicGameplayRuleIntakeTerminal aborted( + GameLogicGameplayRuleIntakeOperation operation) { + return new GameLogicGameplayRuleIntakeTerminal( + operation, Outcome.ABORTED, operation.authorizationBytes(), null, null); + } + + public GameLogicGameplayRuleIntakeOperation operation() { + return operation; + } + + public Outcome outcome() { + return outcome; + } + + public byte[] authorizationBytes() { + return authorizationBytes.clone(); + } + + public byte[] selectedSourceBytes() { + return nullableCopy(selectedSourceBytes); + } + + public byte[] manifestBytes() { + return nullableCopy(manifestBytes); + } + + public String authorizationDigest() { + return operation.authorization().digest(); + } + + public String selectedSourceDigest() { + return selectedSourceBytes == null ? null : GameplayRuleManifest.sha256(selectedSourceBytes); + } + + public String manifestDigest() { + return manifestBytes == null ? null : GameplayRuleManifest.sha256(manifestBytes); + } + + public byte[] canonicalBytes() { + var output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, outcome.name()); + DraftAuthorizationFenceBinding.frame(output, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(output, authorizationBytes); + frameOptional(output, selectedSourceBytes); + frameOptional(output, manifestBytes); + return output.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static GameLogicGameplayRuleIntakeTerminal fromStored(byte[] original) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(original); + reader.expect(SCHEMA); + Outcome outcome = Outcome.valueOf(reader.text()); + var operation = GameLogicGameplayRuleIntakeOperation.fromStored(reader.bytes()); + byte[] authorization = reader.bytes(); + byte[] source = readOptional(reader); + byte[] manifest = readOptional(reader); + reader.requireEnd(); + var terminal = + new GameLogicGameplayRuleIntakeTerminal( + operation, outcome, authorization, source, manifest); + if (!Arrays.equals(original, terminal.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical GL intake terminal"); + } + return terminal; + } + + private static void frameOptional(ByteArrayOutputStream output, byte[] value) { + DraftAuthorizationFenceBinding.frame(output, value == null ? "ABSENT" : "PRESENT"); + if (value != null) DraftAuthorizationFenceBinding.frame(output, value); + } + + private static byte[] readOptional(DraftAuthorizationFenceBinding.FrameReader reader) { + String presence = reader.text(); + if ("ABSENT".equals(presence)) return null; + if (!"PRESENT".equals(presence)) { + throw new IllegalArgumentException("Invalid optional GL intake terminal frame"); + } + return reader.bytes(); + } + + private static byte[] copy(byte[] value) { + return Objects.requireNonNull(value, "bytes").clone(); + } + + private static byte[] nullableCopy(byte[] value) { + return value == null ? null : value.clone(); + } +} diff --git a/services/game-logic-service/src/main/resources/db/migration/V2__immutable_gameplay_rule_source_intake.sql b/services/game-logic-service/src/main/resources/db/migration/V2__immutable_gameplay_rule_source_intake.sql new file mode 100644 index 0000000000..ce411672be --- /dev/null +++ b/services/game-logic-service/src/main/resources/db/migration/V2__immutable_gameplay_rule_source_intake.sql @@ -0,0 +1,52 @@ +CREATE TABLE game_logic_gameplay_rule_intake_terminal ( + operation_id UUID PRIMARY KEY, + target_namespace VARCHAR(63) NOT NULL CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + actor_account_id UUID NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + operation_digest VARCHAR(71) NOT NULL CHECK (operation_digest ~ '^sha256:[0-9a-f]{64}$'), + authorization_digest VARCHAR(71) NOT NULL CHECK (authorization_digest ~ '^sha256:[0-9a-f]{64}$'), + authorization_bytes BYTEA NOT NULL CHECK (octet_length(authorization_bytes) BETWEEN 1 AND 4194304), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('RETAINED', 'ABORTED')), + selected_source_bytes BYTEA, + selected_source_digest VARCHAR(71), + manifest_bytes BYTEA, + manifest_digest VARCHAR(71), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 16777216), + terminal_digest VARCHAR(71) NOT NULL CHECK (terminal_digest ~ '^sha256:[0-9a-f]{64}$'), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK ( + (outcome = 'RETAINED' + AND selected_source_bytes IS NOT NULL + AND octet_length(selected_source_bytes) BETWEEN 1 AND 4194304 + AND selected_source_digest IS NOT NULL + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND manifest_bytes IS NOT NULL + AND octet_length(manifest_bytes) BETWEEN 1 AND 4194304 + AND manifest_digest IS NOT NULL + AND manifest_digest ~ '^sha256:[0-9a-f]{64}$') + OR + (outcome = 'ABORTED' + AND selected_source_bytes IS NULL + AND selected_source_digest IS NULL + AND manifest_bytes IS NULL + AND manifest_digest IS NULL) + ) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_game_logic_gameplay_rule_intake_mutation() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Logic gameplay-rule intake terminals are immutable' USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_logic_gameplay_rule_intake_immutable + BEFORE UPDATE OR DELETE ON game_logic_gameplay_rule_intake_terminal + FOR EACH ROW EXECUTE FUNCTION reject_game_logic_gameplay_rule_intake_mutation(); + +CREATE TRIGGER game_logic_gameplay_rule_intake_no_truncate + BEFORE TRUNCATE ON game_logic_gameplay_rule_intake_terminal + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_logic_gameplay_rule_intake_mutation(); +-- [jooq ignore stop] diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java new file mode 100644 index 0000000000..8adf4a47c4 --- /dev/null +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java @@ -0,0 +1,270 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +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.when; + +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameLogicGameplayRuleIntakePostgresIntegrationTest { + private static final String NAMESPACE = "test"; + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void exactConcurrentRetriesRetainOneImmutableOriginalTerminalAndReadItWithoutOwnerReads() + throws Exception { + var fixture = fixture(); + var authorization = authorization(); + var source = authorization.source(); + var bothSourceReads = new CountDownLatch(2); + var accountReads = new AtomicInteger(); + var gameDesignReads = new AtomicInteger(); + var accountReader = mock(GameLogicIntakeAuthorizationReadClient.class); + var gameDesignReader = mock(GameplayRuleSourceReadClient.class); + when(accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + accountReads.incrementAndGet(); + return new GameLogicIntakeAuthorizationReadEvidence(invocation.getArgument(0)); + }); + when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + gameDesignReads.incrementAndGet(); + bothSourceReads.countDown(); + if (!bothSourceReads.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent source-read barrier timed out"); + } + return new GameplayRuleSourceReadEvidence(invocation.getArgument(0), source); + }); + var first = fixture.service(accountReader, gameDesignReader); + var second = fixture.service(accountReader, gameDesignReader); + byte[] originalTerminalBytes; + + try (var executor = Executors.newFixedThreadPool(2)) { + var left = executor.submit(() -> asGameDesign(() -> first.retain(authorization))); + var right = executor.submit(() -> asGameDesign(() -> second.retain(authorization))); + var retained = left.get(15, TimeUnit.SECONDS); + var retry = right.get(15, TimeUnit.SECONDS); + originalTerminalBytes = retained.canonicalBytes(); + assertThat(retained.canonicalBytes()).containsExactly(retry.canonicalBytes()); + } + + assertThat(accountReads).hasValue(2); + assertThat(gameDesignReads).hasValue(2); + assertThat(fixture.dsl.fetchCount(DSL.table("game_logic_gameplay_rule_intake_terminal"))) + .isEqualTo(1); + var stored = fixture.repository.findTerminal(authorization.operationId()).orElseThrow(); + assertThat(stored.authorizationBytes()).containsExactly(authorization.canonicalBytes()); + assertThat(stored.selectedSourceBytes()).containsExactly(source.canonicalBytes()); + assertThat(stored.manifestBytes()) + .containsExactly(source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_logic_gameplay_rule_intake_terminal SET outcome = 'ABORTED' WHERE operation_id = ?", + authorization.operationId())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_logic_gameplay_rule_intake_terminal WHERE operation_id = ?", + authorization.operationId())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE game_logic_gameplay_rule_intake_terminal")) + .isInstanceOf(RuntimeException.class); + assertThat(fixture.dsl.fetchCount(DSL.table("game_logic_gameplay_rule_intake_terminal"))) + .isEqualTo(1); + + var unavailableAccount = mock(GameLogicIntakeAuthorizationReadClient.class); + var unavailableDesign = mock(GameplayRuleSourceReadClient.class); + when(unavailableAccount.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenThrow(new AssertionError("Stored terminal retry must not reread Account")); + when(unavailableDesign.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenThrow(new AssertionError("Stored terminal retry must not reread latest GD source")); + var restarted = fixture.service(unavailableAccount, unavailableDesign); + var recovered = asGameDesign(() -> restarted.retain(authorization)); + assertThat(recovered.canonicalBytes()).containsExactly(originalTerminalBytes); + } + + @Test + void explicitAbortWinsBeforeRetentionAndPreventsLaterSourceReadsAndCommit() throws Exception { + var fixture = fixture(); + var authorization = authorization(); + var sourceReadEntered = new CountDownLatch(1); + var allowSourceRead = new CountDownLatch(1); + var accountReader = mock(GameLogicIntakeAuthorizationReadClient.class); + var gameDesignReader = mock(GameplayRuleSourceReadClient.class); + when(accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenAnswer( + invocation -> new GameLogicIntakeAuthorizationReadEvidence(invocation.getArgument(0))); + when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenAnswer( + invocation -> { + sourceReadEntered.countDown(); + if (!allowSourceRead.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Source-read barrier timed out"); + } + return new GameplayRuleSourceReadEvidence( + invocation.getArgument(0), authorization.source()); + }); + var service = fixture.service(accountReader, gameDesignReader); + + try (var executor = Executors.newSingleThreadExecutor()) { + var retention = executor.submit(() -> asGameDesign(() -> service.retain(authorization))); + assertThat(sourceReadEntered.await(5, TimeUnit.SECONDS)).isTrue(); + var aborted = asGameDesign(() -> service.abort(authorization)); + allowSourceRead.countDown(); + var observed = retention.get(15, TimeUnit.SECONDS); + assertThat(aborted.outcome()).isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + assertThat(observed.canonicalBytes()).containsExactly(aborted.canonicalBytes()); + } finally { + allowSourceRead.countDown(); + } + + assertThat(fixture.dsl.fetchCount(DSL.table("game_logic_gameplay_rule_intake_terminal"))) + .isEqualTo(1); + assertThat(fixture.repository.findTerminal(authorization.operationId()).orElseThrow().outcome()) + .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + } + + private static Fixture fixture() { + String schema = "gl_intake_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = new DriverManagerDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + dataSource.setSchema(schema); + org.flywaydb.core.Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations("classpath:db/migration") + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var transactionManager = new DataSourceTransactionManager(dataSource); + return new Fixture(dsl, transactionManager, new GameLogicGameplayRuleIntakeRepository(dsl)); + } + + private static T asGameDesign(java.util.concurrent.Callable action) throws Exception { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", NAMESPACE, "game-design-service"); + Context previous = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).attach(); + try { + return action.call(); + } finally { + Context.current().detach(previous); + } + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + var actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", "1", + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {4, 5, 6}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } + + private record Fixture( + DSLContext dsl, + DataSourceTransactionManager transactionManager, + GameLogicGameplayRuleIntakeRepository repository) { + private GameLogicGameplayRuleIntakeService service( + GameLogicIntakeAuthorizationReadClient accountReader, + GameplayRuleSourceReadClient gameDesignReader) { + return new GameLogicGameplayRuleIntakeService( + repository, transactionManager, accountReader, gameDesignReader, NAMESPACE); + } + } +} diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java new file mode 100644 index 0000000000..c3975dfb7b --- /dev/null +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java @@ -0,0 +1,432 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +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.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameLogicGameplayRuleIntakeServiceTest { + private static final String NAMESPACE = "test"; + + @Test + void exactHeldAuthorizationAndSelectedSourceAreRetainedAsOneExactTerminal() { + var fixture = new Fixture(); + var authorization = authorization(); + var selected = authorization.source(); + fixture.respondFor(authorization, selected); + + var terminal = asGameDesign(() -> fixture.service.retain(authorization)); + + assertThat(terminal.outcome()).isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED); + assertThat(terminal.authorizationBytes()).containsExactly(authorization.canonicalBytes()); + assertThat(terminal.selectedSourceBytes()).containsExactly(selected.canonicalBytes()); + assertThat(terminal.manifestBytes()) + .containsExactly(selected.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat( + GameLogicGameplayRuleIntakeTerminal.fromStored(terminal.canonicalBytes()) + .canonicalBytes()) + .containsExactly(terminal.canonicalBytes()); + var calls = inOrder(fixture.accountReader, fixture.gameDesignReader); + calls + .verify(fixture.accountReader) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + calls.verify(fixture.gameDesignReader).read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void exactRetryReturnsOriginalBytesWithoutRecheckingSettledAccountOrLatestSource() { + var fixture = new Fixture(); + var authorization = authorization(); + var operation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization); + var original = + GameLogicGameplayRuleIntakeTerminal.retained( + operation, + authorization.source().canonicalBytes(), + authorization.source().manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + fixture.stored.set(original); + fixture.repositoryFindsStored(); + + var retry = asGameDesign(() -> fixture.service.retain(authorization)); + + assertThat(retry.canonicalBytes()).containsExactly(original.canonicalBytes()); + verify(fixture.accountReader, never()) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void explicitAbortIsDurableAndBlocksLaterRetentionWithoutInferringFromMissingReads() { + var fixture = new Fixture(); + var authorization = authorization(); + fixture.repositoryFindsStored(); + fixture.respondAuthorizationOnly(authorization); + + var aborted = asGameDesign(() -> fixture.service.abort(authorization)); + var retry = asGameDesign(() -> fixture.service.retain(authorization)); + + assertThat(aborted.outcome()).isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + assertThat(retry.canonicalBytes()).containsExactly(aborted.canonicalBytes()); + assertThat(asGameDesign(() -> fixture.service.readTerminal(authorization))).contains(aborted); + verify(fixture.accountReader).read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void explicitAbortRequiresAnExactHeldAccountReadAndDoesNotWriteOnAbsence() { + var fixture = new Fixture(); + var authorization = authorization(); + fixture.repositoryFindsStored(); + when(fixture.accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenThrow(Status.FAILED_PRECONDITION.asRuntimeException()); + + assertThatThrownBy(() -> asGameDesign(() -> fixture.service.abort(authorization))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(fixture.stored.get()).isNull(); + verify(fixture.repository, never()) + .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void explicitAbortRejectsAChangedAccountAuthorizationReadback() { + var fixture = new Fixture(); + var authorization = authorization(); + var changed = + new GameLogicIntakeAuthorizationBinding( + authorization.operationId(), + UUID.randomUUID(), + authorization.intakeRequestId(), + authorization.actorAccountId(), + authorization.source(), + authorization.sources()); + when(fixture.accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenAnswer( + invocation -> + new GameLogicIntakeAuthorizationReadEvidence( + new GameLogicIntakeAuthorizationReadEvidence.Request( + 1, + NAMESPACE, + invocation + .getArgument(0) + .readRequestId(), + changed))); + + assertThatThrownBy(() -> asGameDesign(() -> fixture.service.abort(authorization))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(fixture.stored.get()).isNull(); + verify(fixture.repository, never()) + .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void authenticatedSourceMismatchDeniesWithoutWritingAnAbortOrTerminal() { + var fixture = new Fixture(); + var authorization = authorization(); + var changed = source(authorization.source().binding(), "2"); + fixture.respondFor(authorization, changed); + + assertThatThrownBy(() -> asGameDesign(() -> fixture.service.retain(authorization))) + .isInstanceOf(RuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(fixture.stored.get()).isNull(); + assertThat(asGameDesign(() -> fixture.service.readTerminal(authorization))).isEmpty(); + verify(fixture.repository, never()) + .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); + } + + @Test + void unavailableAccountReadLeavesNoTerminalAndDoesNotInferAbort() { + var fixture = new Fixture(); + var authorization = authorization(); + when(fixture.accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + + assertThatThrownBy(() -> asGameDesign(() -> fixture.service.retain(authorization))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(fixture.stored.get()).isNull(); + assertThat(asGameDesign(() -> fixture.service.readTerminal(authorization))).isEmpty(); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + verify(fixture.repository, never()) + .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); + } + + @Test + void changedOrderUnderExistingOperationIdentityIsDeniedBeforeRemoteReads() { + var fixture = new Fixture(); + var originalAuthorization = authorization(); + var operation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, originalAuthorization); + var original = GameLogicGameplayRuleIntakeTerminal.aborted(operation); + fixture.stored.set(original); + fixture.repositoryFindsStored(); + var changedAuthorization = + new GameLogicIntakeAuthorizationBinding( + originalAuthorization.operationId(), + UUID.randomUUID(), + originalAuthorization.intakeRequestId(), + originalAuthorization.actorAccountId(), + originalAuthorization.source(), + originalAuthorization.sources()); + + assertThatThrownBy(() -> asGameDesign(() -> fixture.service.retain(changedAuthorization))) + .isInstanceOf(RuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); + verify(fixture.accountReader, never()) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void onlyTheExactSameNamespaceGameDesignPeerCanInvokeTheOwner() { + var fixture = new Fixture(); + var authorization = authorization(); + var accountPeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/account-service", NAMESPACE, "account-service"); + Context previous = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, accountPeer).attach(); + try { + assertThatThrownBy(() -> fixture.service.retain(authorization)) + .isInstanceOf(RuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } finally { + Context.current().detach(previous); + } + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + verify(fixture.accountReader, never()) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + @Test + void creatorPublicationCredentialCannotBeMixedWithTheServicePeer() { + var fixture = new Fixture(); + var authorization = authorization(); + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", NAMESPACE, "game-design-service"); + Context request = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .withValue( + AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, + AccountSelectedPublicationOrderCredentials.Credential.of( + "creator-order-credential")); + Context previous = request.attach(); + try { + assertThatThrownBy(() -> fixture.service.retain(authorization)) + .isInstanceOf(RuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } finally { + Context.current().detach(previous); + } + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + verify(fixture.accountReader, never()) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(fixture.gameDesignReader, never()) + .read(any(GameplayRuleSourceReadEvidence.Request.class)); + } + + private static T asGameDesign(java.util.function.Supplier action) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", NAMESPACE, "game-design-service"); + Context previous = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).attach(); + try { + return action.get(); + } finally { + Context.current().detach(previous); + } + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + var actor = UUID.randomUUID(); + var source = source(binding(), "1"); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } + + private static DraftCommitBinding binding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding binding, String epoch) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", epoch, + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + } + + private static final class Fixture { + private final GameLogicGameplayRuleIntakeRepository repository = + mock(GameLogicGameplayRuleIntakeRepository.class); + private final GameLogicIntakeAuthorizationReadClient accountReader = + mock(GameLogicIntakeAuthorizationReadClient.class); + private final GameplayRuleSourceReadClient gameDesignReader = + mock(GameplayRuleSourceReadClient.class); + private final AtomicReference stored = + new AtomicReference<>(); + private final GameLogicGameplayRuleIntakeService service = + new GameLogicGameplayRuleIntakeService( + repository, new UnitTransactionManager(), accountReader, gameDesignReader, NAMESPACE); + + private Fixture() { + when(repository.findTerminal(any(UUID.class))) + .thenAnswer(ignored -> Optional.ofNullable(stored.get())); + org.mockito.Mockito.doAnswer( + invocation -> { + stored.set(invocation.getArgument(0)); + return null; + }) + .when(repository) + .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); + } + + private void repositoryFindsStored() { + when(repository.findTerminal(any(UUID.class))) + .thenAnswer(ignored -> Optional.ofNullable(stored.get())); + } + + private void respondFor( + GameLogicIntakeAuthorizationBinding authorization, GameplayRuleSelectedSource selected) { + respondAuthorizationOnly(authorization); + when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var request = invocation.getArgument(0); + return new GameplayRuleSourceReadEvidence(request, selected); + }); + } + + private void respondAuthorizationOnly(GameLogicIntakeAuthorizationBinding authorization) { + when(accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var request = + invocation.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.binding()).isEqualTo(authorization); + return new GameLogicIntakeAuthorizationReadEvidence(request); + }); + } + } + + private static final class UnitTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + var actualDefinition = definition == null ? TransactionDefinition.withDefaults() : definition; + assertThat(actualDefinition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java index c0cfd708f5..bef80a1324 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java @@ -241,8 +241,13 @@ public Optional readAttempt(WorldDesignPublicationFenceEvidence e return Optional.of(stored); } - /** Reads one retained attempt by its opaque fence without resolving mutable source state. */ - @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + /** + * Reads one retained attempt by its opaque fence without resolving mutable source state. + * + *

This committed read requires a caller with no owner transaction or synchronization scope. It + * deliberately declares no transaction boundary so Spring does not create an empty + * synchronization scope around the read. + */ public Optional readAttemptByFence(UUID publicationFence) { if (publicationFence == null || NIL_UUID.equals(publicationFence)) { throw new IllegalArgumentException("A non-nil World publication fence is required"); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index e70380eb86..7319452b2a 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -1780,8 +1780,9 @@ private WorldDraftTopologyCommitPlan topologyPlan(Fixture fixture) { .setWeather("rain") .setShardId(7) .setGenerationSeed(9001) - .setGeneratorType("synthetic") - .setGeneratorParams("{}")) + // Hand-authored topology has no supported generator input. + .setGeneratorType("") + .setGeneratorParams("")) .build(), mutation( commitId, diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java new file mode 100644 index 0000000000..7f8d343ffa --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java @@ -0,0 +1,106 @@ +package unit.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.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import org.jooq.Condition; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SelectConditionStep; +import org.jooq.SelectWhereStep; +import org.jooq.Table; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldDesignPublicationFenceCommittedReadTest { + private static final UUID PUBLICATION_FENCE = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + @AfterEach + void clearTransactionState() { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void springProxyReadsWithNoAmbientTransactionOrSynchronization() { + DSLContext dsl = mockMissingAttemptQuery(); + WorldDesignPublicationFenceRepository repository = proxiedRepository(dsl); + + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(repository.readAttemptByFence(PUBLICATION_FENCE)).isEmpty(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + verify(dsl).selectFrom(any(Table.class)); + } + + @Test + void rejectsAnAmbientActualTransactionBeforeQuerying() { + DSLContext dsl = mock(DSLContext.class); + WorldDesignPublicationFenceRepository repository = proxiedRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.readAttemptByFence(PUBLICATION_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("World publication attempt read requires a committed read"); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + verifyNoInteractions(dsl); + } + + @Test + void rejectsAnAmbientEmptySynchronizationBeforeQuerying() { + DSLContext dsl = mock(DSLContext.class); + WorldDesignPublicationFenceRepository repository = proxiedRepository(dsl); + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy(() -> repository.readAttemptByFence(PUBLICATION_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("World publication attempt read requires a committed read"); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + verifyNoInteractions(dsl); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static DSLContext mockMissingAttemptQuery() { + DSLContext dsl = mock(DSLContext.class); + SelectWhereStep selectedTable = mock(SelectWhereStep.class); + SelectConditionStep selectedAttempt = mock(SelectConditionStep.class); + doReturn(selectedTable).when(dsl).selectFrom(any(Table.class)); + when(selectedTable.where(any(Condition.class))).thenReturn(selectedAttempt); + when(selectedAttempt.fetchOne()).thenReturn(null); + return dsl; + } + + private static WorldDesignPublicationFenceRepository proxiedRepository(DSLContext dsl) { + var repository = + new WorldDesignPublicationFenceRepository( + dsl, mock(WorldAuthoredSourceIntakeRepository.class)); + var transactionInterceptor = new TransactionInterceptor(); + transactionInterceptor.setTransactionManager( + new DataSourceTransactionManager(mock(DataSource.class))); + transactionInterceptor.setTransactionAttributeSource( + new AnnotationTransactionAttributeSource()); + var proxy = new ProxyFactory(repository); + proxy.setProxyTargetClass(true); + proxy.addAdvice(transactionInterceptor); + return (WorldDesignPublicationFenceRepository) proxy.getProxy(); + } +} From 681cb132a6810e035665db78309ec9fe1f042be5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:06:10 +1300 Subject: [PATCH 040/129] Recover original source orders and settle exact gameplay-rule terminals --- .../account-service/api-contracts.md | 4 +- .../game-design-service/version-control.md | 4 +- .../game-logic-service/api-contracts.md | 6 + ...ame-authoring-publishing-and-activation.md | 14 +- .../v1/original_draft_order_service.proto | 31 + ...ameplay_rule_intake_terminal_service.proto | 24 + .../DraftAuthorizationFenceRepository.java | 3 +- .../session/AccountControlUiActorService.java | 27 +- ...meLogicIntakeAuthorizationReadService.java | 6 +- ...ameLogicIntakeAuthorizationRepository.java | 102 +- .../AccountGameLogicIntakeSettlement.java | 42 + ...countGameLogicIntakeSettlementService.java | 68 + .../AccountOriginalDraftOrderGrpcService.java | 148 ++ .../AccountOriginalDraftOrderService.java | 57 + ..._game_logic_intake_terminal_settlement.sql | 129 ++ ...eAuthorizationPostgresIntegrationTest.java | 17 +- ...inalDraftOrderPostgresIntegrationTest.java | 374 +++++ ...ountOriginalDraftOrderGrpcServiceTest.java | 285 ++++ .../AccountOriginalDraftOrderServiceTest.java | 112 ++ .../AccountControlUiOriginalOrderFixture.java | 109 +- .../AccountControlUiOwnerSourcesFixture.java | 16 +- .../AccountOriginalDraftOrderClient.java | 133 ++ .../AccountOriginalDraftOrderCredentials.java | 113 ++ .../AccountOriginalDraftOrderEvidence.java | 40 + .../AccountOriginalDraftOrderGrpcCodec.java | 146 ++ .../GameLogicGameplayRuleIntakeOperation.java | 3 +- .../GameLogicGameplayRuleIntakeTerminal.java | 17 +- .../GameLogicIntakeAuthorizationBinding.java | 2 + .../GameLogicIntakeTerminalReadClient.java | 156 ++ .../GameLogicIntakeTerminalReadEvidence.java | 61 + .../GameLogicIntakeTerminalReadGrpcCodec.java | 83 + .../AccountOriginalDraftOrderClientTest.java | 158 ++ ...ountOriginalDraftOrderCredentialsTest.java | 93 ++ ...ccountOriginalDraftOrderGrpcCodecTest.java | 159 ++ .../GameLogicIntakeTerminalReadGrpcTest.java | 624 ++++++++ services/game-design-service/build.gradle.kts | 2 + .../DraftCommitCoordinatorRepository.java | 61 +- .../draft/GameDesignSourceCommitService.java | 175 +++ ..._draft_application_lifecycle_interlock.sql | 124 ++ ...gnSourceCommitPostgresIntegrationTest.java | 1381 +++++++++++++++++ ...emptServiceTransactionIntegrationTest.java | 22 +- .../GameDesignSourceCommitServiceTest.java | 211 +++ services/game-logic-service/build.gradle.kts | 2 + ...GameLogicGameplayRuleIntakeRepository.java | 1 + .../GameLogicGameplayRuleIntakeService.java | 5 +- ...playRuleIntakeTerminalReadGrpcService.java | 54 + ...GameplayRuleIntakeTerminalReadService.java | 52 + ...playRuleIntakePostgresIntegrationTest.java | 2 + ...lementComposedPostgresIntegrationTest.java | 678 ++++++++ ...ameLogicGameplayRuleIntakeServiceTest.java | 23 +- ...cation_inventory_projection_precedence.sql | 19 + ...uthorizedDraftPostgresIntegrationTest.java | 16 + ...aphApplicationPostgresIntegrationTest.java | 32 +- 53 files changed, 6171 insertions(+), 55 deletions(-) create mode 100644 protos/account/v1/original_draft_order_service.proto create mode 100644 protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderService.java create mode 100644 services/account-service/src/main/resources/db/migration/V111__game_logic_intake_terminal_settlement.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderCredentials.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderGrpcCodec.java rename services/{game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake => common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic}/GameLogicGameplayRuleIntakeOperation.java (93%) rename services/{game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake => common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic}/GameLogicGameplayRuleIntakeTerminal.java (88%) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderCredentialsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitService.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V58__draft_application_lifecycle_interlock.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitServiceTest.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java create mode 100644 services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V57__world_publication_inventory_projection_precedence.sql diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3f671a28d8..dbc002fb28 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -78,6 +78,8 @@ For `security_locked` accounts, Account's successful recovery authorization issu ## gRPC APIs +The unregistered [`AccountOriginalDraftOrderService.ClaimOriginalDraft`](../../../../protos/account/v1/original_draft_order_service.proto) producer accepts the complete canonical original Draft authorization, not a caller-selected replacement source vector. Only verified same-namespace Game Design may call it. For a new operation, Account authenticates that workload before reading protected method-local creator-credential metadata or decoding the request, captures current environment authority internally, and runs its current-creator/source-lock transaction to reserve and order that exact operation; this requires the actual signed creator credential and complete source capture. Before that fresh-authority path, Account looks up an already-held exact original operation. It returns the retained `COMMIT_ORDER` and pending settlement without revalidating creator expiry/currentness or recapturing environment authority; the same protected metadata gate remains in force. Unavailable or changed evidence, revocation, or prior settlement denies, while only definitive absence permits a fresh, fully authenticated acquisition. The unchanged creator credential never enters protobuf, response evidence, or diagnostics. A successful response binds the original authorization bytes and `COMMIT_ORDER` to the exact namespace and fresh transport correlation; correlation is not a new durable operation identity. The client verifies Account's workload identity and rejects substituted, noncanonical or unavailable evidence outside SQL. This producer grants neither owner mutation nor settlement authority by itself; registration, metadata/message budgets and composed proof remain gates in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + The standalone, unregistered `AccountPublicationAuthorizationReadService.ReadHeldPublicationAuthorization` contract is defined in [its proto](../../../../protos/account/v1/publication_authorization_service.proto). Only the verified same-namespace Game Design and World Management workloads may read an exact retained, distinct publication authorization; the complete canonical binding and digest are lookup evidence, not caller authority. This exact-method permission grants World neither order creation nor settlement authority. `HELD` confirms the original Account order and source participation, not Game Design publication, World application, owner settlement, or admission. Original Draft permission cannot substitute. Runtime registration and composed proof remain gated in [Game Authoring, Publishing and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). Account acquires this distinct publication order from the authenticated acting account and immutable Game Design Draft selection before World freeze. Its original actor, canonical tenant, selected-Draft digest, exact source versions and Account fence remain immutable across retry and recovery. The later World capture is correlated separately and must not rewrite the original order or its digest. Applicable source participation protects the authorized operation through actual World commit; a remote `HELD` sample alone is not commit-time protection. Participation may be released only after authenticated exact publication commit/abort readback, never from timeout, absence, a Draft terminal receipt or ambiguous publication evidence. Retained orders and their evidence remain immutable under forward-only migration. The current unregistered producer/read components do not yet establish this complete terminal settlement boundary. @@ -90,7 +92,7 @@ The standalone, unregistered [`AccountSelectedPublicationOrderService.AuthorizeS Game Logic's [selected-release source intake](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) uses a distinct Account authorization, not an original Draft or publication order. After the original authored Draft is synchronized and its Account operation has committed settlement, Account obtains the exact complete immutable Game Design source over its authenticated owner read outside SQL. Account's existing current-creator transaction then binds the stable intake request, acting account, canonical target, unchanged selected commit and source bytes/digest, complete current source vector and a distinct operation/fence; it retains full source participation atomically. Exact retries preserve that original order; changed source or actor evidence cannot reuse the request identity. This neither changes the original Draft's participant vector nor advances its commit to manufacture Game Logic participation. -Only the verified same-namespace Game Logic workload may call [`ReadHeldGameLogicIntakeAuthorization`](../../../../protos/account/v1/game_logic_intake_authorization.proto). Its complete request and original authorization bytes/digest must match the retained order. A `HELD` read does not grant fresh creator authority or establish completed intake. Applicable source changes and elective deadline disclosure remain blocked until Account verifies an authenticated exact Game Logic retention or definitive-abort terminal and commits settlement for this same operation. Absence, timeout or ambiguous outcome cannot release participation, and a definitive abort must exclude later retention. Owner reads run outside SQL; settlement uses the existing sorted source-lock ordering and exact immutable readback. The current unregistered construction has no settlement writer, so its orders remain pending; implementation and proof limits belong in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +Only the verified same-namespace Game Logic workload may call [`ReadHeldGameLogicIntakeAuthorization`](../../../../protos/account/v1/game_logic_intake_authorization.proto). Its complete request and original authorization bytes/digest must match the retained order. A `HELD` read does not grant fresh creator authority or establish completed intake. Applicable source changes and elective deadline disclosure remain blocked until Account obtains a fresh authenticated same-namespace Game Logic terminal read outside SQL and commits an exact immutable settlement receipt for this same operation. Only the original `RETAINED` or definitive `ABORTED` terminal can settle; absence, timeout, or ambiguous outcome preserves participation, and an abort must exclude later retention. Account checks for an exact existing receipt before the remote read, then serializes a new settlement using the existing sorted source-lock ordering. Exact receipt recovery authenticates the permitted caller and compares the complete original order before returning retained evidence without another remote read. The receipt preserves the original Game Logic terminal; a new read correlation cannot create or rewrite a settlement. Only this operation's settled participation is released, and its external `HELD` read then denies. The unregistered terminal reader and settlement writer do not enable intake or admission; implementation and proof limits belong in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index d241ad0285..86db196cda 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -8,7 +8,7 @@ Game Design is the canonical authored-history, publication-coordination, release Full-version finalization requires the exact original World evidence retained by its pending publication operation and passes the selected World input to the v2 release-bundle path; missing or changed evidence remains pending for reconciliation, not permission to recapture or abort. The unregistered `SelectedDraftPublicationOwner` reserves one existing synchronized Draft, using its exact immutable selection digest for the pending attempt and source-backed publication operation. Its backend finalization entry requires exact durable selection/operation readback and shares the existing finalization transaction; it does not allocate a replacement Draft or translate a legacy full-publish digest. Typed Account and World inputs are not authentication of their producers. The standalone, unregistered `SelectedDraftPublicationAdmissionService` obtains distinct Account held-publication authorization, begins or exactly replays World's authenticated freeze, and reads its exact selector and immutable inventory outside SQL before opening the local reservation transaction. Its bounded ordering and retention proof does not establish genuine positive release composition. It registers no creator ingress and enables no publication or runtime paths. Current construction and executable proof limits are recorded in the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). -External Git synchronization and canonical multi-branch merge semantics are not implemented. Current authoring uses Game Design-owned revision APIs with optimistic validation and ordered mutation calls, but `SaveRevision` does not provide deterministic replay: it lacks durable request/revision deduplication and can leave a World mutation committed without its corresponding Game Design revision when the later local save fails. ADR 0129's durable multi-owner coordinator, owner-local compare-and-swap application, synchronized commit fence, and proof that partially applied owner rows remain invisible to ordinary Draft reads are also not implemented. Current release-bundle schema and plugin publication/activation code incorrectly reuse Automation & Scripting's aggregate participant `contentDigest` where the dedicated Game Logic-owned `abilitySchemaDigest` is required; exact ability-schema compatibility therefore remains an implementation and proof gap. Plugin publication currently uses signed-only intake; [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md)'s approved unsigned provenance remains target-only. The plugin publication path now rejects terminal-state reuse: an uploaded `SUPERSEDED` or `REVOKED_DESIGN` row cannot be republished under the same `pluginVersionId`; target rollback still uses a new immutable plugin version and leaves the prior terminal row unchanged, while new-version rollback proof remains absent. Duplicate signed plugin `assetId` values are likewise not rejected before export and can produce ambiguous distribution-manifest keys; target intake rejects them deterministically before publication/export. The live World Management design handoff adds a separate lifecycle race: it checks Game Design's authoritative remote version state (`GetVersionState(...).versionState=DRAFT`) before its own transaction, but has no durable owner-local publication freeze or exact Game Design version-state epoch/fence in the mutation request. That remote state check is not proof that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). +External Git synchronization and canonical multi-branch merge semantics are not implemented. Current authoring uses Game Design-owned revision APIs with optimistic validation and ordered mutation calls, but `SaveRevision` does not provide deterministic replay: it lacks durable request/revision deduplication and can leave a World mutation committed without its corresponding Game Design revision when the later local save fails. That live entry does not consume the bounded unregistered ADR 0129 coordinator, owner-local application, source snapshots or synchronized fence components; their existence does not establish complete authenticated multi-owner authoring or ordinary-read visibility proof. The local Game Design-only source composition below remains separately gated. Current release-bundle schema and plugin publication/activation code incorrectly reuse Automation & Scripting's aggregate participant `contentDigest` where the dedicated Game Logic-owned `abilitySchemaDigest` is required; exact ability-schema compatibility therefore remains an implementation and proof gap. Plugin publication currently uses signed-only intake; [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md)'s approved unsigned provenance remains target-only. The plugin publication path now rejects terminal-state reuse: an uploaded `SUPERSEDED` or `REVOKED_DESIGN` row cannot be republished under the same `pluginVersionId`; target rollback still uses a new immutable plugin version and leaves the prior terminal row unchanged, while new-version rollback proof remains absent. Duplicate signed plugin `assetId` values are likewise not rejected before export and can produce ambiguous distribution-manifest keys; target intake rejects them deterministically before publication/export. The live World Management design handoff adds a separate lifecycle race: it checks Game Design's authoritative remote version state (`GetVersionState(...).versionState=DRAFT`) before its own transaction, but has no durable owner-local publication freeze or exact Game Design version-state epoch/fence in the mutation request. That remote state check is not proof that a WMS mutation cannot commit after publication; current status and evidence remain in [World Management Runtime and Data](../world-management-service/runtime-and-data.md#implementation-status). Migration V28 corrects the historical V13 default by retaining every affected row while moving only non-script-only rows whose exact V13 marker remains (`version_state=PUBLISHED`, `version_state_epoch=1`) and whose exact `(tenant_id, version_id)` `published_release_bundle` is absent to `FAILED`, incrementing the epoch and refreshing `updated_at`. Bundled full versions and script-only publication rows are untouched, and the marker predicate makes the correction idempotent. Validation follows the shared [Validation and Runtime Proof](../../../developer-workflows/validation-and-runtime-proof.md) workflow; PostgreSQL retained-row execution remains a required migration gate. This data correction is separate from the still-open `CompareAndSetVersionState` transition gap: the live path still accepts any non-null lifecycle state after its in-memory epoch check and does not enforce release-bundle/artifact or retirement guards. @@ -62,6 +62,8 @@ The selected commit's template/config references and asset-source declarations a - Game Design advances the synchronized fence only after every required owner durably reports the same exact commit and digest. Partial application remains diagnostic workflow state and cannot satisfy `IN_SYNC` or become a publish target. - Conflict assistance may construct a new proposed diff, but it must produce a new digest and exact base/epoch binding for creator review. Reconciliation never silently merges a stale proposal. +For an entirely Game Design-owned source commit, the local coordinator first durably claims the exact operation and application slot, then calls the [Account original-order producer](../account-service/api-contracts.md#grpc-apis) outside SQL. A second local transaction applies the source, records the owner result, advances the source-aware synchronized fence, and releases the slot. This path requires the complete owner vector to be Game Design-only at both bindings; it must reject, not filter out, World or other owner participation. An unsuccessful or uncertain Account acquisition does not prove Account abort: under the same local serialization, Game Design must prove its owner is still `NOT_ATTEMPTED`, persist the exact no-application rejection, definitive-abort terminal and tombstone, then release the slot so no late application can pass. If source application commits first, exact terminal recovery returns that committed result without applying revisions again. Version state, epoch advancement, and publication selection cannot pass an unresolved application slot. A local abort does not assert that Account never ordered the operation; any late Account completion must reconcile through the existing exact owner-terminal settlement. Internal exact readback is not a public creator-authentication surface, and local source completion is not Account settlement, Game Logic retention or publication proof. This standalone construction remains unregistered; implementation and executed proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + #### Publication freeze and owner handoff (Target State) The [immutable selected-Draft owner read](api-contracts.md#immutable-selected-draft-publication-read) preserves Game Design's original reserved selection across the Account-order and World-freeze handoffs. Its `SELECTED` response is not current Draft-state or permission evidence; consumers must retain those separate lifecycle and Account checks. diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md index 73a11b4ff1..0d51a2b74b 100644 --- a/design/architecture/microservices/game-logic-service/api-contracts.md +++ b/design/architecture/microservices/game-logic-service/api-contracts.md @@ -53,6 +53,12 @@ Expected response: ## gRPC +### Selected-source terminal read + +The separate, unregistered [`ReadGameplayRuleIntakeTerminal`](../../../../protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto) method accepts only verified same-namespace Account callers, authenticating before decoding source evidence. Its versioned request binds the namespace, fresh read correlation and exact original Account intake authorization bytes/digest. Its closed response echoes that tuple and returns either the original canonical terminal and digest or explicit absence; absence is not an abort. The read is allowlisted to Account and performs no source creation, retention, abort, settlement, or admission. The [Account owner contract](../account-service/api-contracts.md#grpc-apis) defines held-order fencing and exact settlement authority; the [runtime/data owner](runtime-and-data.md#selected-release-rule-inputs-and-intake) defines intake and definitive-abort semantics. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records unregistered transport, bounded-message and physical proof gates. + +### Gameplay methods + - `Ping(PingRequest) returns (PingResponse)` is the basic connectivity check defined in [`game_logic_service.proto`](../../../../protos/game-logic/v1/game_logic_service.proto). - `ExecuteCommand(ExecuteCommandRequest) returns (ExecuteCommandResponse)` evaluates a parsed gameplay command and returns the outcome. - `SendCommunication` is the target gameplay communication contract: it inherits the complete validated `PlayerExecutionContext` from Game Session, classifies a world/gameplay communication type, resolves topology/perception/capability/effect facts, and forwards one bounded plan with stable identity, authorized candidate views, and owner handoffs. The current Game Logic adapter first requires `account_id` to be present, positive, and numeric; malformed, missing, or non-positive account identity returns `INVALID_ARGUMENT` before Entity Management or Social calls. It then projects the flat request to Social & Groups as `tenant_id`, that validated account identity as `sender_id`, mapped communication `type`, normalized text as `content`, the resolved recipient when applicable, and `effect_id`; it never falls back to `character_id` for sender authority. It does not forward `session_id`, room context, target kind/name, or legacy `session_attestation` unchanged. Game Logic owns validating the incoming request fields against the target context, but focused tenant/session/character/target mismatch and projection proof remains an implementation gap. Until that target context is propagated, the live request remains the flat field set documented under [Player execution context](#player-execution-context), including legacy `session_attestation`; those request fields are data to validate against the target context, never caller authority. Account messaging, ordinary group/channel communication, browser social actions, and ordinary account/social mail are Social-owned classes and may use an authenticated in-game adapter without becoming Game Logic actions or exposing private content to tenant-authored scripts. Deliberately world-specific mail is a gameplay communication class under [ADR 0147](../../decisions/adr-0147-explicit-communication-classes-and-owner-delivery.md); [ADR 0148](../../decisions/adr-0148-social-relationship-authority-and-entity-owned-value.md) remains the value and attachment authority. See active ADR 0147, mapped from reviewed archive record `archive-ADR-0134`. 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 506156f2a6..9c99a9395b 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 @@ -8,11 +8,19 @@ This is a non-normative implementation tracker for game authoring, publishing, a The selected-release inventory contract is explicit in the [World owner](../../architecture/microservices/world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) and [Game Design asset owner](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). Construction includes World's immutable selected-graph inventory and authenticated read, plus Game Design's mandatory v2 retention of that inventory in the complete original publication operation. The unregistered first-admission path obtains authenticated Account, freeze, inventory and selector evidence outside SQL; local durable retries reuse their original bytes without those RPCs. Additive owner guards reject incomplete v1 inputs for new operations, captures, terminal outcomes and settlement; retained history is not rewritten. This is not a genuine complete producer-to-release-to-settlement handoff or activation. -Game Design's synchronized source repository covers commands, realm policy and ordinary `ASSET_REFERENCE` source history, with actual fresh-Version genesis, coordinator application, immutable selected-commit snapshots and export agreement. The current V57 construction adds the closed `GAMEPLAY_RULE` authored family, exact original revisions, complete typed catalogs and immutable synchronized source snapshots; the actual authorized ingress/coordinator wiring, physical PostgreSQL and composed owner proof remain pending. Generic `SaveRevision` cannot stand in for that producer: it rejects new `GAMEPLAY_RULE` writes, and retained generic rule rows deny source completeness without guessed reconciliation. Total Game Design source completeness remains unimplemented: V37 mappings and nullable usage classifiers do not enumerate selected template/branding references or launch requiredness, and mutable template configuration is not selected-commit evidence. The [closed config contract](../../architecture/microservices/game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state) still needs its actual authorized versioned writers, normalized references, owner-qualified readback and inventory integration. Game Logic's separate immutable intake/terminal settlement, exact requiredness authority, manifest/export attestation, registered ingress and composed proof remain open. Fresh source genesis, absent mappings or absent consumers cannot establish empty families. All four genuine Gameplay handoffs and runtime activation remain open obligations. +Game Design's synchronized source repository covers commands, realm policy and ordinary `ASSET_REFERENCE` source history, with actual fresh-Version genesis, coordinator application, immutable selected-commit snapshots and export agreement. The V57 construction adds the closed `GAMEPLAY_RULE` authored family, exact original revisions, complete typed catalogs and immutable synchronized source snapshots. The new unregistered original-order producer and local source-commit composition connect Account's current creator transaction to the complete Game Design-only coordinator, source-aware fence and exact terminal readback; public creator ingress, deployed environment authority and physical composed proof remain pending. Generic `SaveRevision` cannot stand in for that producer: it rejects new `GAMEPLAY_RULE` writes, and retained generic rule rows deny source completeness without guessed reconciliation. Total Game Design source completeness remains unimplemented: V37 mappings and nullable usage classifiers do not enumerate selected template/branding references or launch requiredness, and mutable template configuration is not selected-commit evidence. The [closed config contract](../../architecture/microservices/game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state) still needs its actual authorized versioned writers, normalized references, owner-qualified readback and inventory integration. Game Logic intake and exact Account settlement now have bounded unregistered components, not completed composed handoffs. Exact requiredness authority, manifest/export attestation, registered ingress and composed proof remain open. Fresh source genesis, absent mappings or absent consumers cannot establish empty families. All four genuine Gameplay handoffs and runtime activation remain open obligations. -Published-head `fc07d1da90041e4e06d1814d11700c229b73143e` [Validation run 37862911308](https://github.com/benhook1013/FireMUD/actions/runs/37862911308) executed 245 Account, 89 Game Design and 206 World integration cases with zero skips or errors. Account had six failures, Game Design one and World 56. All 13 Game Design asset-source cases passed; its remaining negative-inventory case expected the wrong exception wrapper, and the local correction checks root SQLSTATE `23514` and each exact guard message. World exposed a committed-read annotation that itself created the synchronization scope rejected by its strict guard, plus opaque generator values in static-graph fixtures; bounded corrections and a Spring-proxy regression require corrected-head execution. Five Account settlement cases rejected explicit empty inventory arrays because of the V108 aggregate defect described below. The sixth reached V92's existing conservative global-WAL coverage denial: insert fence `0/5A76110` exceeds initial/final flush `0/5A760D0`; this proves unavailable coverage, not which transaction owns that tail, and does not authorize changing V92. V56/V108 migrations, Flyway sanity and the PostgreSQL runtime upgrade check passed. Synthetic merge `4b1de956cf2c4575b7bf2bc8617ee7bb33135bda`, tree `fa843c76b22fd6357fc103876dc29b009f8d7084`, has parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head, not the recorded integrated base as its first parent. This run gives no fresh-image boot, preview or Smoke proof, and excludes the subsequent V57/V109 construction. +Published-head `64c3d8db0ae1b302f8ae7e48e991d5b2ceb39fc6` [Validation run 37868588598](https://github.com/benhook1013/FireMUD/actions/runs/37868588598) completed red. Physical reports record 248 Account integration cases with two failures, 99 Game Design with one, seven Game Logic with two, and 206 World with 55; all executed with zero skips. Game Logic's XML capture step skipped, so its counts come from the uploaded HTML report. The four services' 1085, 399, 101 and 556 unit cases passed. Five previously failing Account selected-publication settlement cases now pass against V110, as does the separate three-case mTLS settlement suite. Game Design's six typed-source/handoff guard cases and World's 18 authored-source intake cases pass. This is not complete producer-to-release proof. The synthetic checkout is merge `793426c02775085d53aef7ef250da234f5b1b546`, tree `33d43a8217513e01237a0e36b7f14ebf82f09584`, with parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head; its first parent differs from the run's recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`. Intended-parent alignment, fresh-image boot, preview and Smoke proof remain open. -Follow-up adjudication traced the five Account inventory failures to V108's ordering aggregates: an explicit empty input array yields SQL `NULL` from `jsonb_agg`, not canonical `[]`. Additive V110 coalesces both region and spawn aggregates, retaining every other identity, shape and ordering guard; its focused direct-SQL definitions reject resealed unsorted inputs and preserve pending source holds. It also restores V93's 2048-character source-key capacity to selected-publication participation. Corrected-head PostgreSQL execution remains required. The separate V109 source-intake order and Game Logic V2 immutable terminal remain unregistered construction: Account and Game Design source reads in the Game Logic database definitions are stipulated upstream clients, not genuine composed authorization proof. Account terminal settlement and transport are still absent, so its source holds are never released by this slice and publication digest reads remain denied. +Additive V110 coalesces empty region/spawn ordering aggregates to canonical `[]`, retaining the remaining identity, shape and ordering guards, and restores V93's 2048-character source-key capacity to selected-publication participation. Its five settlement regressions now have physical execution evidence above. The separate V109 source-intake order and Game Logic V2 immutable terminal remain unregistered construction. The subsequent V111 component obtains authenticated exact Game Logic terminal readback outside SQL and stores an immutable Account settlement under the original source locks; only that exact settled operation releases participation. Its composed definition uses actual Account and Game Logic storage and HELD/terminal mTLS endpoints, while Game Design source and original-author terminal inputs remain explicit upstream stipulations. This is not complete authenticated authoring-to-intake proof, and publication digest reads remain denied. + +The original-source composition definitions use persisted Game Design-issued Game/Version identities, real Account creator issuance and first original-order RPC, actual Game Design source application/fence/terminal, and authenticated original-terminal reconciliation. Public ingress, bootstrap/environment authority and physical composed proof remain open. Scoped independent review of the unpublished composition accepted two recovery gaps and unnecessary creator-credential retention. The corrected producer reserves the exact local operation and application slot before Account ordering, and can terminalize a failed acquisition only by proving its local owner remains unattempted and durably excluding application. V58 interlocks raw lifecycle and publication-selection writes in both ordering directions, including stale Repeatable Read and Serializable snapshots. Account exact held-order recovery precedes creator expiry/currentness validation; only an absent original order may enter fresh authorization. The response evidence no longer retains the original credential-bearing request. Negative, lost-response and concurrent definitions compile but have no physical execution credit. Internal terminal readback is not a public creator-authentication surface. + +The remaining published-head failures are owned corrections, not blanket fixture noise. World V56's public-inventory projection applies JSONB subtraction before extraction; additive V57 parenthesizes the extracted owner scope while preserving exact v2 operation, Account qualification and inventory guards. A deliberately unqualified historical freeze must deny inventory construction; its stale fixture now asserts that denial rather than inventing inventory. The owner-phase guard assertion remains intact. Game Logic's two cases fail before their bodies because their Flyway fixture omits the shared `serviceSchema` placeholder. Game Design compares binary snapshot arrays by identity, and Account invokes a previous Mockito answer while restubbing with a null matcher. Bounded fixture corrections preserve full migration execution and guard assertions. Corrected-head physical proof remains required. Account's independent acknowledgement concurrency case still reaches V92's conservative WAL denial: insert `0/9F81E68` exceeds flush `0/9F81E28`; no target-tail ownership proof or production relaxation is established. + +The corrected unpublished composition gates R175–R177 passed: 341 Common, 1093 Account, 406 Game Design and 556 World unit cases, plus 101 Game Logic unit cases and 12 non-PostgreSQL integration cases, executed without failures or skips. All 554 PostgreSQL definitions compiled and skipped locally without Docker: 234 Account, 111 Game Design, three Game Logic and 206 World. Account V111, Game Design V58 and World V57 schema generation, affected service boot JARs, formatting, Checkstyle, SpotBugs and documentation checks passed. R176 first exposed a new test-only inventory accessor type error; R177 corrected and reran the complete World gate without changing the production guard. The large-terminal transport case executed an over-4-MiB response through strict mutual TLS and rejected a wrong server identity; its source content is synthetic transport material, not owner provenance. These are working-tree results, not exact published-head or PostgreSQL proof. + +The operation-bound Game Design read-authorization producer remains open under incoming controller route `6745816584f3f7eac3b09c1463c09359ba385ad550637336b081d17b62f83cc0` from Gameplay #3120. Existing immutable source, publication and launch content identities do not themselves authorize their readers. The producer must bind the authenticated reader and exact selected source to an independently authorized governing operation; Gameplay owns the coordinated receiver/caller proof. No selector, correlation identifier, workload-only check or historical creator tuple is a substitute, and no activation gate changes. The corrected construction passes local affected checks: R170 completed Common, Account, Game Design and World checks; R172 completed Game Logic's full check after its fixture/static corrections. All four service boot JARs, formatting, Checkstyle, SpotBugs and coverage passed. Actual unit results are 331 Common, 1085 Account, 399 Game Design, 101 Game Logic and 556 World cases, all without failures, errors or skips. Twelve non-PostgreSQL integration cases execute; 537 PostgreSQL definitions compile but skip without Docker (233 Account, 96 Game Design, 206 World and two Game Logic). Owner schema generation and Flyway sanity pass across 12 migration sets and 255 versioned files. These checks do not prove corrected physical migrations, genuine authenticated source production, composed owner settlement, fresh-image boot or Smoke. The scoped independent local source/intake review accepted a generic-rule completeness gap and an extra Account read peer; fail-closed corrections are integrated, while the actual authorized authoring producer remains open rather than being claimed complete by those denials. diff --git a/protos/account/v1/original_draft_order_service.proto b/protos/account/v1/original_draft_order_service.proto new file mode 100644 index 0000000000..b0f839f688 --- /dev/null +++ b/protos/account/v1/original_draft_order_service.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Unregistered original creator producer. Environment authority is Account-owned. +service AccountOriginalDraftOrderService { + rpc ClaimOriginalDraft(ClaimOriginalDraftRequest) returns (ClaimOriginalDraftResponse); +} + +message ClaimOriginalDraftRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Correlation only, separate from every durable identity in original_account_binding. + string request_id = 3; + bytes original_account_binding = 4; +} + +message ClaimOriginalDraftResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + bytes original_account_binding = 4; + OriginalDraftOrderStatus status = 5; +} + +enum OriginalDraftOrderStatus { + ORIGINAL_DRAFT_ORDER_STATUS_UNSPECIFIED = 0; + ORIGINAL_DRAFT_ORDER_STATUS_COMMIT_ORDER = 1; +} diff --git a/protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto b/protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto new file mode 100644 index 0000000000..ed6dce8134 --- /dev/null +++ b/protos/game-logic/v1/gameplay_rule_intake_terminal_service.proto @@ -0,0 +1,24 @@ +syntax = "proto3"; +package game_logic.v1; +option java_package = "net.firedevops.firemud.gamelogic.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. Only the same-namespace Account workload may read. +service GameLogicGameplayRuleIntakeTerminalReadService { + rpc ReadGameplayRuleIntakeTerminal(ReadGameplayRuleIntakeTerminalRequest) returns (ReadGameplayRuleIntakeTerminalResponse); +} +message ReadGameplayRuleIntakeTerminalRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + bytes original_intake_authorization = 4; + string intake_authorization_digest = 5; +} +message ReadGameplayRuleIntakeTerminalResponse { + ReadGameplayRuleIntakeTerminalRequest request = 1; + oneof result { + bool absent = 2; + bytes original_terminal = 3; + } + string terminal_digest = 4; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index a6ce3e9bfb..4a32ac4376 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -337,7 +337,8 @@ public void requireGameLogicIntakeAdmission( private boolean hasPendingGameLogicIntake(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( - "SELECT operation_id FROM account_game_logic_intake_sources WHERE source_key = ?", + "SELECT operation_id FROM account_game_logic_intake_sources WHERE source_key = ?" + + " AND NOT account_game_logic_intake_is_settled(operation_id)", source.key()) .isEmpty()) return true; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java index 3a63a9df9f..5296b902ac 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -83,6 +83,28 @@ public AuthenticatedActor authenticate( current.stored.tokenHash)); } + /** Exact retained producer recovery; absence alone permits a fresh authenticated claim. */ + boolean readHeldOriginalDraft(DraftAuthorizationFenceBinding original) { + outsideSql(); + return Objects.requireNonNull( + transaction.execute( + ignored -> { + var retained = fences.readOriginalBinding(original.operationId()); + if (retained.isEmpty()) return false; + if (!Arrays.equals(retained.get().canonicalBytes(), original.canonicalBytes())) + throw io.grpc.Status.FAILED_PRECONDITION.asRuntimeException(); + var order = fences.read(original); + if (order.ordering() != DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER + || order.reservedAt() == null + || order.orderedAt() == null + || !Arrays.equals(order.binding(), original.canonicalBytes()) + || fences.readSettlement(original) + != DraftAuthorizationFenceRepository.Settlement.PENDING) + throw io.grpc.Status.FAILED_PRECONDITION.asRuntimeException(); + return true; + })); + } + /** No transport or World mutation: original Account reservation/order is the only effect. */ public DraftAuthorizationFenceRepository.FenceSnapshot claimOriginalDraft( String compactJwt, @@ -101,7 +123,10 @@ public DraftAuthorizationFenceRepository.FenceSnapshot claimOriginalDraft( // Never wait for a source-first writer while retaining captured owner rows. fences.lockProducerSourcesNowait(current.source.sources()); fences.reserve(original); - return fences.claimCommitOrder(original); + var order = fences.claimCommitOrder(original); + if (fences.readSettlement(original) + != DraftAuthorizationFenceRepository.Settlement.PENDING) throw denied(); + return order; }); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java index fdac09368e..8341215465 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.service.session; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.util.Objects; @@ -10,12 +11,15 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; -/** Unregistered exact held-source read; all current orders remain pending, never settled. */ +/** Unregistered exact held-source read; settled orders cannot mint fresh HELD evidence. */ public final class AccountGameLogicIntakeAuthorizationReadService { private final AccountGameLogicIntakeAuthorizationRepository repository; private final TransactionTemplate transaction; private final String namespace; + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected repository is an intentionally shared service collaborator.") public AccountGameLogicIntakeAuthorizationReadService( AccountGameLogicIntakeAuthorizationRepository repository, PlatformTransactionManager transactions, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java index 3626489f91..a8ef577cb7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java @@ -10,7 +10,7 @@ import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Immutable pending intake and full source participation; no terminal-write/settlement surface. */ +/** Immutable intake orders, exact terminal settlements, and full original source participation. */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Internal Account owner persistence collaborator.") @@ -106,8 +106,104 @@ public void readHeld(GameLogicIntakeAuthorizationBinding requested) { "SELECT * FROM account_game_logic_intake_authorizations WHERE operation_id = ? FOR UPDATE", original.operationId()), original); - // Every immutable order remains pending until a later authenticated terminal integration - // exists. + if (dsl.fetchOne( + "SELECT operation_id FROM account_game_logic_intake_settlements WHERE operation_id = ?", + original.operationId()) + != null) throw new IllegalArgumentException("Original intake order already settled"); + } + + /** Only called after the producer's authenticated GL read, with no remote read under locks. */ + java.util.Optional findSettlement( + GameLogicIntakeAuthorizationBinding requested, String namespace) { + requireTransaction(); + var order = + dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + requested.operationId()); + if (order == null + || !Arrays.equals(requested.canonicalBytes(), order.get("binding", byte[].class))) + throw new IllegalArgumentException("Original intake order absent or changed"); + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_settlements WHERE operation_id = ?", + requested.operationId()); + if (row == null) return java.util.Optional.empty(); + var receipt = + AccountGameLogicIntakeSettlement.fromStored(row.get("receipt_bytes", byte[].class)); + if (!namespace.equals(receipt.terminal().operation().targetNamespace()) + || !Arrays.equals(requested.canonicalBytes(), receipt.terminal().authorizationBytes())) + throw new IllegalArgumentException("Changed exact intake settlement"); + return java.util.Optional.of(exactSettlement(row, receipt)); + } + + /** Only called after the producer's authenticated GL read, with no remote read under locks. */ + AccountGameLogicIntakeSettlement settle(AccountGameLogicIntakeSettlement requested) { + requireTransaction(); + var binding = requested.terminal().operation().authorization(); + var lookup = + dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + binding.operationId()); + if (lookup == null + || !Arrays.equals(binding.canonicalBytes(), lookup.get("binding", byte[].class))) + throw new IllegalArgumentException("Original intake order absent or changed"); + // The retained original determines the sorted locks, never an unchecked caller source vector. + var original = + GameLogicIntakeAuthorizationBinding.fromStored(lookup.get("binding", byte[].class)); + for (var source : original.sources()) + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + source.key()) + == null) throw new IllegalArgumentException("Original intake source lock absent"); + var order = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_authorizations WHERE operation_id = ? FOR UPDATE", + original.operationId()); + if (order == null + || !Arrays.equals(original.canonicalBytes(), order.get("binding", byte[].class))) + throw new IllegalArgumentException("Changed original intake order"); + var prior = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_settlements WHERE operation_id = ? FOR UPDATE", + original.operationId()); + if (prior != null) return exactSettlement(prior, requested); + requireExact(order, original); + var terminal = requested.terminal(); + dsl.execute( + "INSERT INTO account_game_logic_intake_settlements (operation_id, target_namespace, outcome, terminal_bytes, terminal_digest, receipt_bytes, receipt_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + original.operationId(), + terminal.operation().targetNamespace(), + terminal.outcome().name(), + terminal.canonicalBytes(), + terminal.digest(), + requested.canonicalBytes(), + requested.digest()); + return exactSettlement( + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_settlements WHERE operation_id = ? FOR UPDATE", + original.operationId()), + requested); + } + + private static AccountGameLogicIntakeSettlement exactSettlement( + Record row, AccountGameLogicIntakeSettlement requested) { + if (row == null) throw new IllegalStateException("Settlement commit readback absent"); + var original = + AccountGameLogicIntakeSettlement.fromStored(row.get("receipt_bytes", byte[].class)); + var terminal = original.terminal(); + if (!Arrays.equals(original.canonicalBytes(), requested.canonicalBytes()) + || !original.digest().equals(row.get("receipt_digest", String.class)) + || !terminal.digest().equals(row.get("terminal_digest", String.class)) + || !Arrays.equals(terminal.canonicalBytes(), row.get("terminal_bytes", byte[].class)) + || !terminal + .operation() + .authorization() + .operationId() + .equals(row.get("operation_id", UUID.class)) + || !terminal.operation().targetNamespace().equals(row.get("target_namespace", String.class)) + || !terminal.outcome().name().equals(row.get("outcome", String.class))) + throw new IllegalArgumentException("Changed exact intake settlement"); + return original; } private void requireExact(Record row, GameLogicIntakeAuthorizationBinding binding) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java new file mode 100644 index 0000000000..b94b7bd93e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; + +/** Immutable Account receipt; transport correlations never enter mutation identity. */ +public record AccountGameLogicIntakeSettlement(GameLogicGameplayRuleIntakeTerminal terminal) { + public static final String SCHEMA = "account-game-logic-intake-settlement/v1"; + + public AccountGameLogicIntakeSettlement { + Objects.requireNonNull(terminal); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static AccountGameLogicIntakeSettlement fromStored(byte[] bytes) { + if (bytes == null + || bytes.length > GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES + 1024) + throw new IllegalArgumentException("Oversized settlement receipt"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + var receipt = + new AccountGameLogicIntakeSettlement( + GameLogicGameplayRuleIntakeTerminal.fromStored(reader.bytes())); + reader.requireEnd(); + if (!Arrays.equals(bytes, receipt.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical settlement"); + return receipt; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementService.java new file mode 100644 index 0000000000..ec5d7c569f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementService.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered GD-only producer: genuine GL terminal read completes before Account SQL. */ +public final class AccountGameLogicIntakeSettlementService { + private final AccountGameLogicIntakeAuthorizationRepository repository; + private final GameLogicIntakeTerminalReadClient terminals; + private final TransactionTemplate transaction; + private final String namespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected repository is an intentionally shared service collaborator.") + public AccountGameLogicIntakeSettlementService( + AccountGameLogicIntakeAuthorizationRepository repository, + GameLogicIntakeTerminalReadClient terminals, + PlatformTransactionManager transactions, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.terminals = Objects.requireNonNull(terminals); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + public AccountGameLogicIntakeSettlement settle(GameLogicIntakeAuthorizationBinding original) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + Objects.requireNonNull(original); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION + .withDescription("Terminal read must precede Account SQL") + .asRuntimeException(); + var prior = transaction.execute(ignored -> repository.findSettlement(original, namespace)); + if (prior != null && prior.isPresent()) return prior.orElseThrow(); + var request = GameLogicIntakeTerminalReadEvidence.Request.create(namespace, original); + var evidence = terminals.read(request); + if (evidence == null || !request.equals(evidence.request()) || evidence.terminal().isEmpty()) + throw Status.FAILED_PRECONDITION + .withDescription("Exact definitive GL terminal required") + .asRuntimeException(); + var terminal = evidence.terminal().orElseThrow(); + if (!namespace.equals(terminal.operation().targetNamespace()) + || !Arrays.equals(original.canonicalBytes(), terminal.authorizationBytes())) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + return transaction.execute( + ignored -> repository.settle(new AccountGameLogicIntakeSettlement(terminal))); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcService.java new file mode 100644 index 0000000000..b87e3f2606 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcService.java @@ -0,0 +1,148 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.BindableService; +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountOriginalDraftOrderServiceGrpc; +import net.firedevops.firemud.account.v1.ClaimOriginalDraftRequest; +import net.firedevops.firemud.account.v1.ClaimOriginalDraftResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone, unregistered producer; Account obtains environment authority internally. */ +public final class AccountOriginalDraftOrderGrpcService implements BindableService { + private final AccountOriginalDraftOrderService owner; + private final AccountHostedTermsService terms; + private final String namespace; + + public AccountOriginalDraftOrderGrpcService( + AccountOriginalDraftOrderService owner, AccountHostedTermsService terms, String namespace) { + this.owner = Objects.requireNonNull(owner); + this.terms = Objects.requireNonNull(terms); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + /** + * Binding always includes the method-local credential interceptor; peer identity runs outside it. + */ + @Override + public ServerServiceDefinition bindService() { + var handler = + new AccountOriginalDraftOrderServiceGrpc.AccountOriginalDraftOrderServiceImplBase() { + @Override + public void claimOriginalDraft( + ClaimOriginalDraftRequest request, + StreamObserver observer) { + AccountOriginalDraftOrderGrpcService.this.claimOriginalDraft(request, observer); + } + }; + return ServerInterceptors.intercept( + handler, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Status denied = peerDenial(); + if (denied != null) { + call.close(sanitized(denied), new Metadata()); + return new ServerCall.Listener<>() {}; + } + final AccountOriginalDraftOrderCredentials.Credential credential; + try { + credential = AccountOriginalDraftOrderCredentials.readAuthenticated(headers); + } catch (IllegalArgumentException malformed) { + call.close(sanitized(Status.UNAUTHENTICATED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + var context = + Context.current() + .withValue(AccountOriginalDraftOrderCredentials.CONTEXT_KEY, credential); + return Contexts.interceptCall(context, call, headers, next); + } + }); + } + + public void claimOriginalDraft( + ClaimOriginalDraftRequest wire, StreamObserver observer) { + Status denied = peerDenial(); + if (denied != null) { + deny(observer, denied); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + final AccountOriginalDraftOrderGrpcCodec.Request request; + final String credential; + try { + var protectedCredential = AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get(); + if (protectedCredential == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + credential = protectedCredential.value(); + } catch (IllegalArgumentException malformed) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + try { + request = AccountOriginalDraftOrderGrpcCodec.fromRequest(wire, credential); + } catch (IllegalArgumentException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + final ClaimOriginalDraftResponse response; + try { + owner.claimWithEnvironmentCapture( + request.originalCreatorCredential(), + request.original(), + terms::captureCurrentEnvironmentBoundary); + response = AccountOriginalDraftOrderGrpcCodec.toResponse(request); + } catch (StatusRuntimeException failure) { + deny(observer, Status.fromCode(failure.getStatus().getCode())); + return; + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError(sanitized(status).asRuntimeException()); + } + + private Status peerDenial() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) return Status.UNAUTHENTICATED; + return ("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri()) + ? null + : Status.PERMISSION_DENIED; + } + + private static Status sanitized(Status status) { + return status.withDescription("Account original-draft order denied or unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderService.java new file mode 100644 index 0000000000..bd3fe3c82b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderService.java @@ -0,0 +1,57 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered authenticated producer of the exact original Account COMMIT_ORDER. */ +public final class AccountOriginalDraftOrderService { + private final AccountControlUiActorService actors; + private final String namespace; + + public AccountOriginalDraftOrderService(AccountControlUiActorService actors, String namespace) { + this.actors = Objects.requireNonNull(actors); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + public void claim( + String originalCredential, + DraftAuthorizationFenceBinding original, + CapturedEnvironmentBoundary environment) { + claimWithEnvironmentCapture(originalCredential, original, () -> environment); + } + + public void claimWithEnvironmentCapture( + String originalCredential, + DraftAuthorizationFenceBinding original, + Supplier environment) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + Objects.requireNonNull(original); + // Workload-authenticated recovery reads the original held authority, never creator currentness. + // Only definitive absence enters the existing fresh creator producer; read failures deny. + if (actors.readHeldOriginalDraft(original)) return; + // The existing owner performs signed/current creator and complete source validation, then + // reserves and orders this exact original operation atomically. No input is rewritten. + var ordered = actors.claimOriginalDraft(originalCredential, original, environment.get()); + if (ordered == null + || ordered.ordering() != DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER + || ordered.reservedAt() == null + || ordered.orderedAt() == null + || !Arrays.equals(original.canonicalBytes(), ordered.binding())) + throw new IllegalStateException("Exact original Account COMMIT_ORDER unavailable"); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V111__game_logic_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V111__game_logic_intake_terminal_settlement.sql new file mode 100644 index 0000000000..e1bcb15889 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V111__game_logic_intake_terminal_settlement.sql @@ -0,0 +1,129 @@ +-- Forward-only exact Game Logic terminal settlement. Original orders/participation stay immutable. +CREATE TABLE account_game_logic_intake_settlements ( + operation_id UUID PRIMARY KEY REFERENCES account_game_logic_intake_authorizations(operation_id), + target_namespace VARCHAR(63) NOT NULL CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('RETAINED', 'ABORTED')), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 16777216), + terminal_digest VARCHAR(71) NOT NULL CHECK (terminal_digest ~ '^sha256:[0-9a-f]{64}$'), + receipt_bytes BYTEA NOT NULL CHECK (octet_length(receipt_bytes) BETWEEN 1 AND 16778240), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + settled_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- [jooq ignore start] +CREATE FUNCTION account_game_logic_intake_settlement_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_game_logic_intake_authorizations%ROWTYPE; + p INTEGER := 1; + q INTEGER := 1; + parsed BYTEA; + operation_bytes BYTEA; + selected_source BYTEA; + manifest BYTEA; + expected_source BYTEA; + marker TEXT; +BEGIN + -- Same sorted original source locks as Account's producer/source writers. + SELECT * INTO STRICT original FROM account_game_logic_intake_authorizations WHERE operation_id = NEW.operation_id; + PERFORM l.source_key FROM account_draft_authorization_source_locks l + JOIN account_game_logic_intake_sources s ON s.source_key = l.source_key + WHERE s.operation_id = NEW.operation_id ORDER BY l.source_key FOR UPDATE OF l; + PERFORM operation_id FROM account_game_logic_intake_authorizations WHERE operation_id = NEW.operation_id FOR UPDATE; + IF NEW.terminal_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') + OR NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') THEN + RAISE EXCEPTION 'Changed intake settlement digest' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF convert_from(parsed, 'UTF8') <> 'account-game-logic-intake-settlement/v1' THEN + RAISE EXCEPTION 'Invalid intake settlement schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF parsed IS DISTINCT FROM NEW.terminal_bytes OR p <> octet_length(NEW.receipt_bytes) + 1 THEN + RAISE EXCEPTION 'Changed original settlement terminal' USING ERRCODE = '23514'; + END IF; + + p := 1; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF convert_from(parsed, 'UTF8') <> 'game-logic-gameplay-rule-intake-terminal/v1' THEN + RAISE EXCEPTION 'Invalid Game Logic terminal schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.outcome THEN + RAISE EXCEPTION 'Changed Game Logic terminal outcome' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO operation_bytes, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(operation_bytes, q); + IF convert_from(parsed, 'UTF8') <> 'game-logic-gameplay-rule-intake-operation/v1' THEN + RAISE EXCEPTION 'Invalid Game Logic operation schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(operation_bytes, q); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.target_namespace THEN + RAISE EXCEPTION 'Changed Game Logic operation namespace' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(operation_bytes, q); + IF parsed IS DISTINCT FROM original.binding OR q <> octet_length(operation_bytes) + 1 THEN + RAISE EXCEPTION 'Changed original Game Logic operation authorization' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF parsed IS DISTINCT FROM original.binding THEN + RAISE EXCEPTION 'Changed Game Logic terminal authorization' USING ERRCODE = '23514'; + END IF; + -- Original binding: schema, four UUID frames, then the exact complete selected source. + q := 1; + FOR i IN 1..5 LOOP + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(original.binding, q); + END LOOP; + SELECT frame_value, next_position INTO expected_source, q FROM account_publication_authorization_read_frame(original.binding, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF NEW.outcome = 'RETAINED' THEN + IF marker <> 'PRESENT' THEN RAISE EXCEPTION 'Retained terminal missing source' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO selected_source, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF marker <> 'PRESENT' THEN RAISE EXCEPTION 'Retained terminal missing manifest' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO manifest, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF selected_source IS DISTINCT FROM expected_source + OR manifest IS DISTINCT FROM convert_to(convert_from(expected_source, 'UTF8')::JSONB->>'manifestJson', 'UTF8') THEN + RAISE EXCEPTION 'Changed retained source or manifest' USING ERRCODE = '23514'; + END IF; + ELSE + IF marker <> 'ABSENT' THEN RAISE EXCEPTION 'Aborted terminal claims retained source' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p FROM account_publication_authorization_read_frame(NEW.terminal_bytes, p); + IF marker <> 'ABSENT' THEN RAISE EXCEPTION 'Aborted terminal claims manifest' USING ERRCODE = '23514'; END IF; + END IF; + IF p <> octet_length(NEW.terminal_bytes) + 1 THEN + RAISE EXCEPTION 'Trailing Game Logic terminal bytes' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_game_logic_intake_settlement_validate + BEFORE INSERT ON account_game_logic_intake_settlements FOR EACH ROW + EXECUTE FUNCTION account_game_logic_intake_settlement_guard(); +CREATE TRIGGER account_game_logic_intake_settlement_immutable + BEFORE UPDATE OR DELETE ON account_game_logic_intake_settlements FOR EACH ROW + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_settlement_no_truncate + BEFORE TRUNCATE ON account_game_logic_intake_settlements FOR EACH STATEMENT + EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +CREATE FUNCTION account_game_logic_intake_is_settled(operation_value UUID) +RETURNS BOOLEAN LANGUAGE sql STABLE AS $$ + SELECT EXISTS (SELECT 1 FROM account_game_logic_intake_settlements WHERE operation_id = operation_value); +$$; + +-- Release only this exact receipt's participation; preserve every other writer/disclosure guard. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$FROM account_game_logic_intake_sources s WHERE s.source_key = ANY(source_keys)$anchor$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one existing intake source-writer guard'; + END IF; + EXECUTE replace(original, anchor, anchor || ' AND NOT account_game_logic_intake_is_settled(s.operation_id)'); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java index bd7f2cea68..fb7b1d9fa0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java @@ -3,8 +3,8 @@ 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.doAnswer; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import io.grpc.Context; import java.nio.file.Path; @@ -116,8 +116,9 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); var source = source(selected); var gd = mock(GameplayRuleSourceReadClient.class); - when(gd.read(any())) - .thenAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)); + doAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)) + .when(gd) + .read(any()); var repository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); var service = new AccountGameLogicIntakeAuthorizationService( @@ -166,8 +167,9 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc var substituted = new GameplayRuleSelectedSource( source.snapshotJson().replace(genesis, UUID.randomUUID().toString())); - when(gd.read(any())) - .thenAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), substituted)); + doAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), substituted)) + .when(gd) + .read(any()); assertThatThrownBy( () -> asGameDesign( @@ -176,8 +178,9 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc issued.compact(), requestId, selected, issued.environment()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("conflicts"); - when(gd.read(any())) - .thenAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)); + doAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)) + .when(gd) + .read(any()); UUID rolledBackRequest = UUID.randomUUID(); assertThatThrownBy( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java new file mode 100644 index 0000000000..824a314834 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java @@ -0,0 +1,374 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Genuine Account issuance, PostgreSQL ordering and Coordination Redis; receiver contexts and + * terminal owner evidence are explicit upstream test stipulations, not mTLS or terminal proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountOriginalDraftOrderPostgresIntegrationTest { + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("original-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "original-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrSubstitute() + throws Exception { + var clock = new ActorClock(); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + clock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var target = + new DraftCommitBinding.TargetProof( + f.tenant, UUID.randomUUID(), 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"); + var complete = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULES", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULES", + "all", + "0"))); + var sources = + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())).sources(); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + target.canonicalVersionId(), + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + sources) + .withRequiredOwners(); + var request = + AccountOriginalDraftOrderGrpcCodec.Request.create("test", original, issued.compact()); + var receiver = + (AccountOriginalDraftOrderGrpcService) fixture.originalDraftOrderProducer("test"); + // The actual owner commits before the response is deliberately discarded by the caller. + asPeer("test", "game-design-service", () -> invoke(receiver, request, true)); + fixture.assertOriginalDraftOrderPending(original); + var before = f.tx(() -> f.fences.read(original)); + clock.advance(Duration.ofMinutes(10)); + assertThatThrownBy(() -> issued.actors().verifySigned(issued.compact())) + .isInstanceOf(RuntimeException.class); + + asPeer("test", "game-design-service", () -> invoke(receiver, request)); + var owner = new AccountOriginalDraftOrderService(issued.actors(), "test"); + asPeer( + "test", + "game-design-service", + () -> + owner.claimWithEnvironmentCapture( + issued.compact(), + original, + () -> { + throw new AssertionError("Recovery recaptured environment"); + })); + assertThat(f.tx(() -> f.fences.read(original)).orderedAt()).isEqualTo(before.orderedAt()); + fixture.assertOriginalDraftOrderPending(original); + + var changed = + new DraftAuthorizationFenceBinding( + original.operationId(), + original.requestId(), + original.commitId(), + original.fenceId(), + UUID.randomUUID(), + original.tenantId(), + original.versionId(), + original.baseCommitId(), + original.expectedDraftEpoch(), + original.gameDesignBinding(), + original.normalizedInput(), + original.inputDigest(), + original.sources()) + .withRequiredOwners(); + assertThatThrownBy( + () -> + asPeer( + "test", + "game-design-service", + () -> owner.claim(issued.compact(), changed, issued.environment()))) + .isInstanceOf(RuntimeException.class); + var absent = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + original.requestId(), + original.commitId(), + UUID.randomUUID(), + original.actorAccountId(), + original.tenantId(), + original.versionId(), + original.baseCommitId(), + original.expectedDraftEpoch(), + original.gameDesignBinding(), + original.normalizedInput(), + original.inputDigest(), + original.sources()) + .withRequiredOwners(); + assertThatThrownBy( + () -> + asPeer( + "test", + "game-design-service", + () -> owner.claim(issued.compact(), absent, issued.environment()))) + .isInstanceOf(RuntimeException.class); + assertThat(f.tx(() -> f.fences.readOriginalBinding(absent.operationId()))).isEmpty(); + for (String[] peer : + List.of( + new String[] {"other", "game-design-service"}, + new String[] {"test", "world-management-service"})) { + assertThatThrownBy( + () -> + asPeer( + peer[0], + peer[1], + () -> owner.claim(issued.compact(), original, issued.environment()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + } + // Explicit upstream terminal stipulation tests settled denial; it never fabricates HELD. + f.tx( + () -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); + assertThatThrownBy( + () -> + asPeer( + "test", + "game-design-service", + () -> owner.claim(issued.compact(), original, issued.environment()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + var reservedInput = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + complete.baseCommitId(), + complete.revisions(), + complete.affectedUnits()); + var reserved = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + reservedInput.requestId(), + reservedInput.commitId(), + UUID.randomUUID(), + original.actorAccountId(), + original.tenantId(), + original.versionId(), + original.baseCommitId(), + original.expectedDraftEpoch(), + reservedInput.canonicalBytes(), + reservedInput.canonicalBytes(), + reservedInput.digest(), + sources) + .withRequiredOwners(); + f.tx(() -> f.fences.reserve(reserved)); + assertThatThrownBy( + () -> + asPeer( + "test", + "game-design-service", + () -> owner.claim(issued.compact(), reserved, issued.environment()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + var change = + new net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository + .SourceChange(UUID.randomUUID(), sources, new byte[] {9}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.read(reserved)).ordering().name()).isEqualTo("REVOKE_ORDER"); + assertThatThrownBy( + () -> + asPeer( + "test", + "game-design-service", + () -> owner.claim(issued.compact(), reserved, issued.environment()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + } + } + + private static void invoke( + AccountOriginalDraftOrderGrpcService receiver, + AccountOriginalDraftOrderGrpcCodec.Request request) { + invoke(receiver, request, false); + } + + private static void invoke( + AccountOriginalDraftOrderGrpcService receiver, + AccountOriginalDraftOrderGrpcCodec.Request request, + boolean discardResponse) { + var context = + Context.current() + .withValue( + AccountOriginalDraftOrderCredentials.CONTEXT_KEY, + AccountOriginalDraftOrderCredentials.Credential.of( + request.originalCreatorCredential())); + var prior = context.attach(); + try { + var result = + new AtomicReference(); + var failure = new AtomicReference(); + receiver.claimOriginalDraft( + AccountOriginalDraftOrderGrpcCodec.toRequest(request), + new io.grpc.stub.StreamObserver<>() { + public void onNext( + net.firedevops.firemud.account.v1.ClaimOriginalDraftResponse response) { + if (!discardResponse) result.set(response); + } + + public void onError(Throwable error) { + failure.set(error); + } + + public void onCompleted() {} + }); + assertThat(failure.get()).isNull(); + if (discardResponse) assertThat(result.get()).isNull(); + else + assertThat( + AccountOriginalDraftOrderGrpcCodec.fromResponse(request, result.get()) + .matches(request)) + .isTrue(); + } finally { + context.detach(prior); + } + } + + private static void asPeer(String namespace, String workload, Runnable action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + action.run(); + } finally { + context.detach(prior); + } + } + + private static final class ActorClock extends Clock { + private Duration offset = Duration.ZERO; + + void advance(Duration amount) { + offset = offset.plus(amount); + } + + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + public Clock withZone(ZoneId zone) { + return Clock.offset(Clock.system(zone), offset); + } + + public Instant instant() { + return Instant.now().plus(offset); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcServiceTest.java new file mode 100644 index 0000000000..f3083e15a0 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcServiceTest.java @@ -0,0 +1,285 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.ClaimOriginalDraftRequest; +import net.firedevops.firemud.account.v1.ClaimOriginalDraftResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Context-level receiver units, not mounted-certificate or real Account currentness proof. */ +class AccountOriginalDraftOrderGrpcServiceTest { + private static final String CREDENTIAL = "original.secret.credential"; + private final AccountOriginalDraftOrderService owner = + mock(AccountOriginalDraftOrderService.class); + private final AccountHostedTermsService terms = mock(AccountHostedTermsService.class); + private final AccountOriginalDraftOrderGrpcService receiver = + new AccountOriginalDraftOrderGrpcService(owner, terms, "test"); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeMalformedDecodeAndCaptureAndDeniesWorld() { + assertThat(invoke(null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String workload : + List.of("world-management-service", "account-service", "game-session-service")) { + assertThat(peer("test", workload, () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(peer("other", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(authorized(() -> invoke(ClaimOriginalDraftRequest.getDefaultInstance())).code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner, terms); + } + + @Test + void boundInterceptorAuthenticatesBeforeTouchingMalformedCredentialMetadata() { + var headers = mock(io.grpc.Metadata.class); + assertThat(boundCode(headers)).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer("test", "world-management-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(headers, owner, terms); + var malformed = new io.grpc.Metadata(); + malformed.put( + io.grpc.Metadata.Key.of( + AccountOriginalDraftOrderCredentials.HEADER.name(), + io.grpc.Metadata.BINARY_BYTE_MARSHALLER), + new byte[] {(byte) 128}); + assertThat(peer("test", "game-design-service", () -> boundCode(malformed))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer("test", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(owner, terms); + } + + @SuppressWarnings("unchecked") + private Status.Code boundCode(io.grpc.Metadata headers) { + var method = + (io.grpc.ServerMethodDefinition) + receiver.bindService().getMethods().iterator().next(); + io.grpc.ServerCall call = + mock(io.grpc.ServerCall.class); + method.getServerCallHandler().startCall(call, headers); + var status = org.mockito.ArgumentCaptor.forClass(Status.class); + org.mockito.Mockito.verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any()); + return status.getValue().getCode(); + } + + @Test + void deniesAmbientSqlNamespaceAndUnknownFieldsBeforeCapture() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(authorized(() -> invoke(null)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThat(authorized(() -> invoke(null)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clearSynchronization(); + var request = request(); + assertThat( + authorized(() -> invoke(request.toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + authorized( + () -> + invoke( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner, terms); + } + + @Test + void capturesEnvironmentInternallyAndPreservesOriginalCredentialAndCompleteBinding() { + var wire = request(); + var decoded = AccountOriginalDraftOrderGrpcCodec.fromRequest(wire, CREDENTIAL); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()) + .thenAnswer( + call -> { + outsideSql(); + return captured; + }); + org.mockito.Mockito.doAnswer( + call -> { + outsideSql(); + assertThat(call.getArgument(0, String.class)).isEqualTo(CREDENTIAL); + assertThat(call.getArgument(1, DraftAuthorizationFenceBinding.class).canonicalBytes()) + .isEqualTo(decoded.originalAccountBinding()); + java.util.function.Supplier + capture = call.getArgument(2); + assertThat(capture.get()).isSameAs(captured); + return null; + }) + .when(owner) + .claimWithEnvironmentCapture(eq(CREDENTIAL), any(), any()); + var result = authorized(() -> invoke(wire)); + assertThat(result.error()).isNull(); + assertThat( + AccountOriginalDraftOrderGrpcCodec.fromResponse(decoded, result.response()) + .original() + .canonicalBytes()) + .isEqualTo(decoded.originalAccountBinding()); + assertThat(result.response().toString()).doesNotContain(CREDENTIAL); + } + + @Test + void ownerFailureNeverEchoesCredentialDiagnostics() { + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + org.mockito.Mockito.doThrow( + io.grpc.Status.PERMISSION_DENIED.withDescription(CREDENTIAL).asRuntimeException()) + .when(owner) + .claimWithEnvironmentCapture(eq(CREDENTIAL), any(), any()); + var denied = authorized(() -> invoke(request())); + assertThat(denied.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + assertThat(denied.error().getCause()).isNull(); + } + + private static ClaimOriginalDraftRequest request() { + return AccountOriginalDraftOrderGrpcCodec.toRequest( + AccountOriginalDraftOrderGrpcCodec.Request.create("test", original(), CREDENTIAL)); + } + + private record Result(ClaimOriginalDraftResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private Result invoke(ClaimOriginalDraftRequest request) { + var response = new AtomicReference(); + var error = new AtomicReference(); + receiver.claimOriginalDraft( + request, + new io.grpc.stub.StreamObserver<>() { + @Override + public void onNext(ClaimOriginalDraftResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() {} + }); + return new Result(response.get(), error.get()); + } + + private static void outsideSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static T authorized(java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + AccountOriginalDraftOrderCredentials.CONTEXT_KEY, + AccountOriginalDraftOrderCredentials.Credential.of(CREDENTIAL)); + var prior = context.attach(); + try { + return peer("test", "game-design-service", action); + } finally { + context.detach(prior); + } + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + static DraftAuthorizationFenceBinding original() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULES", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULES", + "all", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + binding.requestId(), + binding.commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.baseCommitId(), + "0", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + "account", + "1", + new byte[] {1}))) + .withRequiredOwners(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderServiceTest.java new file mode 100644 index 0000000000..bdfdf5fd32 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderServiceTest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.time.OffsetDateTime; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; + +class AccountOriginalDraftOrderServiceTest { + @Test + void heldReplaySkipsCreatorAndEnvironmentAndUnavailableReadCannotFallThrough() { + var actors = mock(AccountControlUiActorService.class); + var service = new AccountOriginalDraftOrderService(actors, "test"); + var original = AccountOriginalDraftOrderGrpcServiceTest.original(); + java.util.function.Supplier capture = + mock(java.util.function.Supplier.class); + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + when(actors.readHeldOriginalDraft(original)).thenReturn(true); + service.claimWithEnvironmentCapture("expired.original.credential", original, capture); + verifyNoInteractions(capture); + org.mockito.Mockito.verify(actors, org.mockito.Mockito.never()) + .claimOriginalDraft( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + when(actors.readHeldOriginalDraft(original)) + .thenThrow(new IllegalStateException("ambiguous")); + assertThatThrownBy( + () -> + service.claimWithEnvironmentCapture( + "expired.original.credential", original, capture)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(capture); + } finally { + context.detach(prior); + } + } + + @Test + void exactOwnerOrderIsRequiredWithUnchangedCreatorAndEnvironment() { + var actors = mock(AccountControlUiActorService.class); + var service = new AccountOriginalDraftOrderService(actors, "test"); + var original = AccountOriginalDraftOrderGrpcServiceTest.original(); + var environment = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + var now = OffsetDateTime.now(); + when(actors.claimOriginalDraft("unchanged.original.credential", original, environment)) + .thenReturn( + new DraftAuthorizationFenceRepository.FenceSnapshot( + DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER, + original.canonicalBytes(), + now, + now)); + service.claim("unchanged.original.credential", original, environment); + verify(actors).claimOriginalDraft("unchanged.original.credential", original, environment); + for (var ordering : + java.util.List.of( + DraftAuthorizationFenceRepository.Ordering.RESERVED, + DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER)) { + when(actors.claimOriginalDraft("unchanged.original.credential", original, environment)) + .thenReturn( + new DraftAuthorizationFenceRepository.FenceSnapshot( + ordering, original.canonicalBytes(), now, now)); + assertThatThrownBy( + () -> service.claim("unchanged.original.credential", original, environment)) + .isInstanceOf(IllegalStateException.class); + } + when(actors.claimOriginalDraft("unchanged.original.credential", original, environment)) + .thenReturn( + new DraftAuthorizationFenceRepository.FenceSnapshot( + DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER, + AccountOriginalDraftOrderGrpcServiceTest.original().canonicalBytes(), + now, + now)); + assertThatThrownBy( + () -> service.claim("unchanged.original.credential", original, environment)) + .isInstanceOf(IllegalStateException.class); + } finally { + context.detach(prior); + } + } + + @Test + void unknownCallerCannotReachOriginalCreatorOwner() { + var actors = mock(AccountControlUiActorService.class); + assertThatThrownBy( + () -> new AccountOriginalDraftOrderService(actors, "test").claim(null, null, null)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + verifyNoInteractions(actors); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 269659637d..53930ddc50 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -46,8 +46,44 @@ public AccountControlUiOriginalOrderFixture( int redisPort, Path temporary) throws Exception { + this(jdbcUrl, username, password, redisHost, redisPort, temporary, UUID.randomUUID()); + } + + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant) + throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + Clock.systemUTC()); + } + + /** Actor clock is injectable for genuine signed-credential expiry recovery proof. */ + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + Clock actorClock) + throws Exception { this.temporary = temporary; - f = new AccountControlUiOwnerSourcesFixture(jdbcUrl, username, password, temporary, false); + f = + new AccountControlUiOwnerSourcesFixture( + jdbcUrl, username, password, temporary, false, gameDesignTenant); var lifecycle = new AccountControlUiSignerFixture(f, temporary); lifecycle.commit(); var originalSigner = f.tx(lifecycle.signer::captureCurrent); @@ -121,7 +157,7 @@ public AccountControlUiOriginalOrderFixture( publicSource, f.fences, f.manager, - Clock.systemUTC()); + actorClock); issuance = new AccountControlUiIssuanceService( f.primary, @@ -142,6 +178,75 @@ public UUID tenantId() { return f.tenant; } + /** Genuine issuance and source capture only; first reservation/order occurs over the producer. */ + public net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec.Request + prepareOriginalDraftOrder(DraftCommitBinding complete, String namespace) { + if (!f.tenant.equals(complete.target().canonicalTenantId())) + throw new IllegalArgumentException("Original Draft must target the retained Account tenant"); + if (originalCreator == null) originalCreator = issueCreator(); + var sources = + f.tx(() -> f.authority.captureInitial(f.tenant, originalCreator.environment())).sources(); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + sources) + .withRequiredOwners(); + return net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec.Request + .create(namespace, original, originalCreator.compact()); + } + + /** Real unregistered Account producer, with Account-internal environment capture. */ + public io.grpc.BindableService originalDraftOrderProducer(String namespace) { + return new AccountOriginalDraftOrderGrpcService( + new AccountOriginalDraftOrderService(actors, namespace), f.terms, namespace); + } + + /** Exact source participation remains pending; local Game Design success cannot settle it. */ + public void assertOriginalDraftOrderPending(DraftAuthorizationFenceBinding original) { + var retained = f.tx(() -> f.fences.read(original)); + assertThat(retained.ordering().name()).isEqualTo("COMMIT_ORDER"); + assertThat(retained.binding()).isEqualTo(original.canonicalBytes()); + assertThat(retained.orderedAt()).isNotNull(); + assertThat(f.tx(() -> f.fences.readSettlement(original)).name()).isEqualTo("PENDING"); + } + + /** Uses only actual authenticated terminal clients; it never installs constructed readbacks. */ + public void reconcileOriginalDraft( + DraftAuthorizationFenceBinding original, + net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient gameDesign, + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient world, + String namespace) { + reconcileOriginalDraft(original, gameDesign, world, namespace, "COMMITTED"); + } + + public void reconcileOriginalDraft( + DraftAuthorizationFenceBinding original, + net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient gameDesign, + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient world, + String namespace, + String expectedSettlementOutcome) { + var recovery = + new net.firedevops.firemud.accountservice.authordraft + .AccountDraftTerminalReconciliationService( + f.fences, f.manager, gameDesign, world, namespace); + assertThat(recovery.reconcile(original.operationId()).orElseThrow().name()) + .isEqualTo(expectedSettlementOutcome); + assertThat(f.tx(() -> f.fences.readSettlement(original)).name()) + .isEqualTo(expectedSettlementOutcome); + assertThat(f.tx(() -> f.fences.read(original)).binding()).isEqualTo(original.canonicalBytes()); + } + /** Caller supplies the real World plan before Account authenticates and captures its sources. */ public DraftAuthorizationFenceBinding claimOriginal(DraftCommitBinding complete) { if (!f.tenant.equals(complete.target().canonicalTenantId())) diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 427086879a..6b012a954b 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -89,9 +89,8 @@ final class AccountControlUiOwnerSourcesFixture { final TransactionTemplate transactions; final Account account; final AccountRepository accounts; - final UUID tenant = UUID.randomUUID(), - request = UUID.randomUUID(), - callerContext = UUID.randomUUID(); + final UUID tenant; + final UUID request = UUID.randomUUID(), callerContext = UUID.randomUUID(); final AtomicReference boundary = new AtomicReference<>(testBoundary("test-production")); final AtomicInteger coordinationCalls = new AtomicInteger(); @@ -108,6 +107,17 @@ final class AccountControlUiOwnerSourcesFixture { */ AccountControlUiOwnerSourcesFixture( String jdbcUrl, String username, String password, Path root, boolean installNegativeIssuer) { + this(jdbcUrl, username, password, root, installNegativeIssuer, UUID.randomUUID()); + } + + AccountControlUiOwnerSourcesFixture( + String jdbcUrl, + String username, + String password, + Path root, + boolean installNegativeIssuer, + UUID tenant) { + this.tenant = Objects.requireNonNull(tenant); String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); var dataSource = new DriverManagerDataSource(jdbcUrl, username, password); dataSource.setSchema(schema); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClient.java new file mode 100644 index 0000000000..baba526c8f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClient.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.common.authoring; + +import io.grpc.CompositeCallCredentials; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountOriginalDraftOrderServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Strict explicit mTLS client; never registers or enables the Account producer. */ +public final class AccountOriginalDraftOrderClient + extends AbstractReloadingBlockingGrpcClient< + AccountOriginalDraftOrderServiceGrpc.AccountOriginalDraftOrderServiceBlockingStub> { + private final String namespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountOriginalDraftOrderClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory factory, + String namespace) { + super(endpoints, requireMtls(tls), factory, AccountOriginalDraftOrderClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account original-draft client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) throw new IllegalStateException("Account original-draft stub unavailable"); + initialized = true; + } + + public AccountOriginalDraftOrderEvidence claim( + AccountOriginalDraftOrderGrpcCodec.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException( + "Account original-draft transport requires no owner transaction"); + Objects.requireNonNull(request); + if (!namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Account original-draft namespace mismatch"); + var current = stub(); + if (closed || !initialized || current == null) + throw new IllegalStateException("Account original-draft client unavailable"); + try { + var response = + current + .withCallCredentials( + new CompositeCallCredentials( + new GrpcServerPeerIdentityCallCredentials( + "spiffe://firemud/ns/" + namespace + "/sa/account-service"), + AccountOriginalDraftOrderCredentials.forCall( + request.originalCreatorCredential()))) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .claimOriginalDraft(AccountOriginalDraftOrderGrpcCodec.toRequest(request)); + return AccountOriginalDraftOrderGrpcCodec.fromResponse(request, response); + } catch (StatusRuntimeException unavailable) { + // Remote diagnostics are not trusted to exclude credential-bearing request data. + throw Status.fromCode(unavailable.getStatus().getCode()) + .withDescription("Account original-draft order denied or unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException("Account returned invalid original-draft order evidence"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountOriginalDraftOrderServiceGrpc.AccountOriginalDraftOrderServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + return AccountOriginalDraftOrderServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(AccountOriginalDraftOrderGrpcCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private static CommonGrpcClientProperties requireMtls(CommonGrpcClientProperties tls) { + if (tls == null || tls.isPlaintext()) + throw new IllegalArgumentException("Account original-draft requires workload mTLS"); + for (String configured : + new String[] {tls.getCertChain(), tls.getPrivateKey(), tls.getCaCert()}) { + if (configured == null || configured.isBlank() || configured.trim().startsWith("classpath:")) + throw new IllegalArgumentException( + "Account original-draft requires readable file-backed TLS material"); + Path file; + try { + file = Path.of(configured.trim()); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Account original-draft requires file-backed TLS material"); + } + if (!Files.isRegularFile(file) || !Files.isReadable(file)) + throw new IllegalArgumentException( + "Account original-draft requires readable file-backed TLS material"); + } + return tls; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderCredentials.java new file mode 100644 index 0000000000..f1f3b5da41 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderCredentials.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.common.authoring; + +import io.grpc.CallCredentials; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Executor; +import net.firedevops.firemud.account.v1.AccountOriginalDraftOrderServiceGrpc; + +/** + * Purpose-specific protected metadata for the original creator credential. Never log metadata: + * metadata's wire serialization necessarily contains the secret, unlike this redacted wrapper. The + * receiver must authenticate its workload peer before reading or decoding this header. + */ +public final class AccountOriginalDraftOrderCredentials { + public static final Context.Key CONTEXT_KEY = + Context.key("account-original-draft-original-creator"); + public static final Metadata.Key HEADER = + Metadata.Key.of( + "firemud-original-draft-creator-bin", + new Metadata.BinaryMarshaller<>() { + @Override + public byte[] toBytes(Credential value) { + return value.bytes.clone(); + } + + // Parsing deliberately defers all credential validation until after workload + // authentication. + @Override + public Credential parseBytes(byte[] serialized) { + return new Credential(serialized); + } + }); + + private AccountOriginalDraftOrderCredentials() {} + + public static final class Credential { + private final byte[] bytes; + + private Credential(byte[] bytes) { + this.bytes = bytes.clone(); + } + + public static Credential of(String value) { + if (value == null + || value.isEmpty() + || value.length() > AccountOriginalDraftOrderGrpcCodec.MAX_CREDENTIAL_BYTES + || value.chars().anyMatch(c -> c <= 32 || c >= 127)) throw invalid(); + return new Credential(value.getBytes(StandardCharsets.US_ASCII)); + } + + public String value() { + if (bytes.length == 0 + || bytes.length > AccountOriginalDraftOrderGrpcCodec.MAX_CREDENTIAL_BYTES) + throw invalid(); + for (byte value : bytes) if (value <= 32 || value >= 127) throw invalid(); + return new String(bytes, StandardCharsets.US_ASCII); + } + + @Override + public String toString() { + return "OriginalDraftCredential[redacted]"; + } + } + + /** Only after authenticating the exact same-namespace Game Design peer. */ + public static Credential readAuthenticated(Metadata headers) { + var values = headers.getAll(HEADER); + if (values == null) throw invalid(); + var iterator = values.iterator(); + if (!iterator.hasNext()) throw invalid(); + Credential credential = iterator.next(); + if (iterator.hasNext()) throw invalid(); + credential.value(); + return credential; + } + + public static CallCredentials forCall(String value) { + var credential = Credential.of(value); + return new CallCredentials() { + @Override + public void applyRequestMetadata( + RequestInfo info, Executor executor, MetadataApplier applier) { + if (info.getSecurityLevel() != SecurityLevel.PRIVACY_AND_INTEGRITY + || !AccountOriginalDraftOrderServiceGrpc.getClaimOriginalDraftMethod() + .getFullMethodName() + .equals(info.getMethodDescriptor().getFullMethodName())) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Protected original-draft transport required")); + return; + } + var headers = new Metadata(); + headers.put(HEADER, credential); + applier.apply(headers); + } + + @Override + public void thisUsesUnstableApi() {} + + @Override + public String toString() { + return "OriginalDraftCallCredentials[redacted]"; + } + }; + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid original-draft credential metadata"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderEvidence.java new file mode 100644 index 0000000000..e2a04b041c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderEvidence.java @@ -0,0 +1,40 @@ +package net.firedevops.firemud.common.authoring; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; + +/** + * Exact producer response obtained from the strict Account client; shape alone is not authority. + */ +public final class AccountOriginalDraftOrderEvidence { + private final int schemaVersion; + private final String targetNamespace; + private final UUID requestId; + private final byte[] originalAccountBinding; + + AccountOriginalDraftOrderEvidence(AccountOriginalDraftOrderGrpcCodec.Request request) { + Objects.requireNonNull(request); + schemaVersion = request.schemaVersion(); + targetNamespace = request.targetNamespace(); + requestId = request.requestId(); + originalAccountBinding = request.originalAccountBinding(); + } + + public boolean matches(AccountOriginalDraftOrderGrpcCodec.Request request) { + return request != null + && schemaVersion == request.schemaVersion() + && targetNamespace.equals(request.targetNamespace()) + && requestId.equals(request.requestId()) + && Arrays.equals(originalAccountBinding, request.originalAccountBinding()); + } + + public DraftAuthorizationFenceBinding original() { + return DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + } + + @Override + public String toString() { + return "AccountOriginalDraftOrderEvidence[redacted]"; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderGrpcCodec.java new file mode 100644 index 0000000000..8708b6ef4c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderGrpcCodec.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.common.authoring; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ClaimOriginalDraftRequest; +import net.firedevops.firemud.account.v1.ClaimOriginalDraftResponse; +import net.firedevops.firemud.account.v1.OriginalDraftOrderStatus; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed original-order mapping. Neither credentials nor environment authority enter protobuf. */ +public final class AccountOriginalDraftOrderGrpcCodec { + public static final int MAX_CREDENTIAL_BYTES = 16384; + public static final int MAX_BINDING_BYTES = 4 * 1024 * 1024; + public static final int MAX_WIRE_BYTES = MAX_BINDING_BYTES + 1024; + public static final int MAX_METADATA_BYTES = ((MAX_CREDENTIAL_BYTES + 2) / 3) * 4 + 1024; + + private AccountOriginalDraftOrderGrpcCodec() {} + + public record Request( + int schemaVersion, + String targetNamespace, + UUID requestId, + byte[] originalAccountBinding, + String originalCreatorCredential) { + public Request { + if (schemaVersion != 1 + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || requestId == null + || requestId.equals(new UUID(0, 0)) + || originalAccountBinding == null + || originalAccountBinding.length == 0 + || originalAccountBinding.length > MAX_BINDING_BYTES) throw invalid(); + AccountOriginalDraftOrderCredentials.Credential.of(originalCreatorCredential); + originalAccountBinding = originalAccountBinding.clone(); + var original = DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + if (!Arrays.equals(originalAccountBinding, original.canonicalBytes()) + || requestId.equals(original.operationId()) + || requestId.equals(original.requestId()) + || requestId.equals(original.commitId()) + || requestId.equals(original.fenceId())) throw invalid(); + } + + public static Request create( + String namespace, DraftAuthorizationFenceBinding original, String credential) { + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (correlation.equals(original.operationId()) + || correlation.equals(original.requestId()) + || correlation.equals(original.commitId()) + || correlation.equals(original.fenceId())); + return new Request(1, namespace, correlation, original.canonicalBytes(), credential); + } + + @Override + public byte[] originalAccountBinding() { + return originalAccountBinding.clone(); + } + + public DraftAuthorizationFenceBinding original() { + return DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + } + + public boolean exactlyMatches(Request other) { + return other != null + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && requestId.equals(other.requestId) + && Arrays.equals(originalAccountBinding, other.originalAccountBinding) + && originalCreatorCredential.equals(other.originalCreatorCredential); + } + + @Override + public String toString() { + return "AccountOriginalDraftOrder.Request[redacted]"; + } + } + + public static ClaimOriginalDraftRequest toRequest(Request request) { + Objects.requireNonNull(request); + return ClaimOriginalDraftRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalAccountBinding(ByteString.copyFrom(request.originalAccountBinding())) + .build(); + } + + /** + * Only after same-namespace Game Design workload authentication and protected metadata checks. + */ + public static Request fromRequest(ClaimOriginalDraftRequest wire, String credential) { + try { + noUnknown(wire); + var correlation = UUID.fromString(wire.getRequestId()); + if (!correlation.toString().equals(wire.getRequestId())) throw invalid(); + return new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + correlation, + wire.getOriginalAccountBinding().toByteArray(), + credential); + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + /** Caller must first verify actual Account owner COMMIT_ORDER with these exact binding bytes. */ + public static ClaimOriginalDraftResponse toResponse(Request request) { + return ClaimOriginalDraftResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalAccountBinding(ByteString.copyFrom(request.originalAccountBinding())) + .setStatus(OriginalDraftOrderStatus.ORIGINAL_DRAFT_ORDER_STATUS_COMMIT_ORDER) + .build(); + } + + public static AccountOriginalDraftOrderEvidence fromResponse( + Request request, ClaimOriginalDraftResponse wire) { + try { + noUnknown(wire); + if (wire.getSchemaVersion() != request.schemaVersion() + || !wire.getTargetNamespace().equals(request.targetNamespace()) + || !wire.getRequestId().equals(request.requestId().toString()) + || !Arrays.equals( + wire.getOriginalAccountBinding().toByteArray(), request.originalAccountBinding()) + || wire.getStatus() != OriginalDraftOrderStatus.ORIGINAL_DRAFT_ORDER_STATUS_COMMIT_ORDER) + throw invalid(); + return new AccountOriginalDraftOrderEvidence(request); + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static void noUnknown(Message wire) { + if (wire == null || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid original Draft order transport evidence"); + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeOperation.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeOperation.java similarity index 93% rename from services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeOperation.java rename to services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeOperation.java index c7ab1566c0..403b56ae2a 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeOperation.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeOperation.java @@ -1,10 +1,9 @@ -package net.firedevops.firemud.gamelogic.sourceintake; +package net.firedevops.firemud.common.gamelogic; import java.io.ByteArrayOutputStream; import java.util.Arrays; import java.util.Objects; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; -import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; /** Exact namespace and Account authorization identity for one independent GL source intake. */ diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminal.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeTerminal.java similarity index 88% rename from services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminal.java rename to services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeTerminal.java index f00bbf0791..3f92885987 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminal.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicGameplayRuleIntakeTerminal.java @@ -1,15 +1,22 @@ -package net.firedevops.firemud.gamelogic.sourceintake; +package net.firedevops.firemud.common.gamelogic; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Objects; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; -import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; /** Durable owner terminal. Empty/absent storage is represented separately from ABORTED. */ public final class GameLogicGameplayRuleIntakeTerminal { + public static final int MAX_CANONICAL_BYTES = 16 * 1024 * 1024; + + /** + * A response carries at most 16 MiB terminal plus 4 MiB original order and bounded namespace, + * UUID, digests, and protobuf framing. 24 MiB includes that closed maximum's envelope overhead. + * Standalone servers must use the same limit; this is not a runtime-registration assertion. + */ + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + public static final String SCHEMA = "game-logic-gameplay-rule-intake-terminal/v1"; public enum Outcome { @@ -110,6 +117,8 @@ public byte[] canonicalBytes() { DraftAuthorizationFenceBinding.frame(output, authorizationBytes); frameOptional(output, selectedSourceBytes); frameOptional(output, manifestBytes); + if (output.size() > MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Terminal exceeds 16 MiB"); return output.toByteArray(); } @@ -118,6 +127,8 @@ public String digest() { } public static GameLogicGameplayRuleIntakeTerminal fromStored(byte[] original) { + if (original == null || original.length == 0 || original.length > MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Invalid terminal size"); var reader = new DraftAuthorizationFenceBinding.FrameReader(original); reader.expect(SCHEMA); Outcome outcome = Outcome.valueOf(reader.text()); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java index 45f8c54856..7fa89fbf1c 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationBinding.java @@ -78,6 +78,8 @@ public String digest() { } public static GameLogicIntakeAuthorizationBinding fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > 4194304) + throw new IllegalArgumentException("Invalid original intake order size"); var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); reader.expect(SCHEMA); UUID operation = uuid(reader.text()), diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java new file mode 100644 index 0000000000..900069c6f8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeTerminalReadServiceGrpc; + +/** Explicit file-backed mTLS client for the exact same-namespace Game Logic terminal read. */ +public final class GameLogicIntakeTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + GameLogicGameplayRuleIntakeTerminalReadServiceGrpc + .GameLogicGameplayRuleIntakeTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameLogicIntakeTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameLogicIntakeTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Game Logic intake terminal read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Game Logic intake terminal read stub unavailable"); + initialized = true; + } + + /** + * Returns a validated terminal or explicit absence after exact Game Logic server mTLS + * verification. + */ + public GameLogicIntakeTerminalReadEvidence read( + GameLogicIntakeTerminalReadEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + throw new IllegalStateException("Game Logic terminal transport must run outside SQL"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Logic intake terminal read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readGameplayRuleIntakeTerminal( + GameLogicIntakeTerminalReadGrpcCodec.toRequest(request)); + try { + return GameLogicIntakeTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Game Logic returned invalid terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameLogicService(); + } + + @Override + protected String defaultTarget() { + return "game-logic-service:6565"; + } + + @Override + protected GameLogicGameplayRuleIntakeTerminalReadServiceGrpc + .GameLogicGameplayRuleIntakeTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-logic-service"; + return GameLogicGameplayRuleIntakeTerminalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withMaxInboundMessageSize(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameLogicGameplayRuleIntakeTerminalReadServiceGrpc + .GameLogicGameplayRuleIntakeTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Logic intake terminal read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Game Logic intake terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Logic intake terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Logic intake terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Logic intake terminal read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Logic intake terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java new file mode 100644 index 0000000000..f039ee5405 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Absence is a successful lookup result, never an abort or permission to release participation. */ +public record GameLogicIntakeTerminalReadEvidence( + Request request, Optional terminal) { + public GameLogicIntakeTerminalReadEvidence { + Objects.requireNonNull(request); + Objects.requireNonNull(terminal); + terminal.ifPresent( + value -> { + var expected = + new GameLogicGameplayRuleIntakeOperation( + request.targetNamespace(), request.binding()); + if (!Arrays.equals(expected.canonicalBytes(), value.operation().canonicalBytes())) + throw new IllegalArgumentException("Terminal differs from exact original intake"); + }); + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + GameLogicIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Supported terminal read schema and namespace required"); + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + Objects.requireNonNull(binding); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.fenceId()) + || readRequestId.equals(binding.intakeRequestId())) + throw new IllegalArgumentException("Separate transport correlation required"); + } + + public static Request create(String namespace, GameLogicIntakeAuthorizationBinding binding) { + return new Request(1, namespace, UUID.randomUUID(), binding); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && readRequestId.equals(other.readRequestId) + && Arrays.equals(binding.canonicalBytes(), other.binding.canonicalBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, targetNamespace, readRequestId, Arrays.hashCode(binding.canonicalBytes())); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..09c6755f5c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcCodec.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalRequest; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalResponse; + +/** Closed exact request echo and canonical original terminal mapping. */ +public final class GameLogicIntakeTerminalReadGrpcCodec { + private GameLogicIntakeTerminalReadGrpcCodec() {} + + public static ReadGameplayRuleIntakeTerminalRequest toRequest( + GameLogicIntakeTerminalReadEvidence.Request request) { + return ReadGameplayRuleIntakeTerminalRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalIntakeAuthorization(ByteString.copyFrom(request.binding().canonicalBytes())) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + } + + public static GameLogicIntakeTerminalReadEvidence.Request fromRequest( + ReadGameplayRuleIntakeTerminalRequest request) { + if (!request.getUnknownFields().asMap().isEmpty() + || request.getOriginalIntakeAuthorization().size() > 4194304) + throw new IllegalArgumentException("Unknown or oversized terminal lookup"); + DraftAuthorizationFenceBinding.canonicalUuid(request.getReadRequestId()); + var binding = + GameLogicIntakeAuthorizationBinding.fromStored( + request.getOriginalIntakeAuthorization().toByteArray()); + if (!binding.digest().equals(request.getIntakeAuthorizationDigest())) + throw new IllegalArgumentException("Changed original intake digest"); + return new GameLogicIntakeTerminalReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getReadRequestId()), + binding); + } + + public static ReadGameplayRuleIntakeTerminalResponse toResponse( + GameLogicIntakeTerminalReadEvidence evidence) { + var response = + ReadGameplayRuleIntakeTerminalResponse.newBuilder() + .setRequest(toRequest(evidence.request())); + if (evidence.terminal().isEmpty()) return response.setAbsent(true).build(); + var terminal = evidence.terminal().orElseThrow(); + byte[] bytes = terminal.canonicalBytes(); + if (bytes.length > GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Oversized original terminal"); + return response + .setOriginalTerminal(ByteString.copyFrom(bytes)) + .setTerminalDigest(terminal.digest()) + .build(); + } + + public static GameLogicIntakeTerminalReadEvidence fromResponse( + GameLogicIntakeTerminalReadEvidence.Request request, + ReadGameplayRuleIntakeTerminalResponse response) { + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !toRequest(request).equals(response.getRequest())) + throw new IllegalArgumentException("Changed terminal read correlation"); + return switch (response.getResultCase()) { + case ABSENT -> { + if (!response.getAbsent() || !response.getTerminalDigest().isEmpty()) + throw new IllegalArgumentException("Invalid absence evidence"); + yield new GameLogicIntakeTerminalReadEvidence(request, Optional.empty()); + } + case ORIGINAL_TERMINAL -> { + var terminal = + GameLogicGameplayRuleIntakeTerminal.fromStored( + response.getOriginalTerminal().toByteArray()); + if (!terminal.digest().equals(response.getTerminalDigest())) + throw new IllegalArgumentException("Changed terminal digest"); + yield new GameLogicIntakeTerminalReadEvidence(request, Optional.of(terminal)); + } + default -> throw new IllegalArgumentException("Explicit owner result required"); + }; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClientTest.java new file mode 100644 index 0000000000..32fd46cd37 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClientTest.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.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.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountOriginalDraftOrderServiceGrpc; +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.GrpcServerPeerIdentityCallCredentials; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Stub configuration/codec units; mocked channels do not prove an mTLS handshake. */ +class AccountOriginalDraftOrderClientTest { + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var tls = tls(directory); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountOriginalDraftOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + tls.setPlaintext(false); + for (String bad : + new String[] { + null, + "", + "classpath:credential.pem", + directory.toString(), + directory.resolve("missing.pem").toString() + }) { + tls.setCertChain(bad); + assertThatThrownBy( + () -> + new AccountOriginalDraftOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var valid = tls(directory); + assertThatThrownBy( + () -> + new AccountOriginalDraftOrderClient( + new ServiceEndpointsProperties(), valid, factory, "Test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void configuresExactAccountPeerDeadlineAndValidatesEchoOutsideSql(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + when(factory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = new AccountOriginalDraftOrderClient(endpoints, tls(directory), factory, "test"); + var binding = AccountOriginalDraftOrderGrpcCodecTest.original(); + var request = + AccountOriginalDraftOrderGrpcCodec.Request.create( + "test", binding, "original.secret.credential"); + try { + assertThatThrownBy(() -> client.claim(request)).isInstanceOf(IllegalStateException.class); + client.init(); + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + var initialized = (io.grpc.stub.AbstractStub) field.get(client); + var credentials = initialized.getCallOptions().getCredentials(); + assertThat(credentials).isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + var peerField = + GrpcServerPeerIdentityCallCredentials.class.getDeclaredField("expectedPeerUri"); + peerField.setAccessible(true); + assertThat(peerField.get(credentials)) + .isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + var stub = + mock( + AccountOriginalDraftOrderServiceGrpc.AccountOriginalDraftOrderServiceBlockingStub + .class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withCallCredentials(any())).thenReturn(stub); + field.set(client, stub); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.claim(request)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.claim(request)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.clearSynchronization(); + var wrongNamespace = + AccountOriginalDraftOrderGrpcCodec.Request.create( + "other", binding, "original.secret.credential"); + assertThatThrownBy(() -> client.claim(wrongNamespace)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(stub); + var response = AccountOriginalDraftOrderGrpcCodec.toResponse(request); + when(stub.claimOriginalDraft(any())).thenReturn(response); + assertThat(client.claim(request).original().canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + verify(stub).withDeadlineAfter(5, TimeUnit.SECONDS); + var wire = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.account.v1.ClaimOriginalDraftRequest.class); + verify(stub).claimOriginalDraft(wire.capture()); + assertThat(wire.getValue().toString()).doesNotContain(request.originalCreatorCredential()); + var perCall = org.mockito.ArgumentCaptor.forClass(io.grpc.CallCredentials.class); + verify(stub).withCallCredentials(perCall.capture()); + assertThat(perCall.getValue()).isInstanceOf(io.grpc.CompositeCallCredentials.class); + when(stub.claimOriginalDraft(any())) + .thenReturn(response.toBuilder().setTargetNamespace("other").build()); + assertThatThrownBy(() -> client.claim(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageNotContaining(request.originalCreatorCredential()); + when(stub.claimOriginalDraft(any())) + .thenThrow( + io.grpc.Status.UNAVAILABLE + .withDescription(request.originalCreatorCredential()) + .asRuntimeException()); + assertThatThrownBy(() -> client.claim(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageNotContaining(request.originalCreatorCredential()) + .hasNoCause(); + } finally { + client.close(); + } + assertThatThrownBy(client::init).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> client.claim(request)).isInstanceOf(IllegalStateException.class); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private-key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "ca").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderCredentialsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderCredentialsTest.java new file mode 100644 index 0000000000..adbb2e71f1 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderCredentialsTest.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.CallCredentials; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import java.nio.charset.StandardCharsets; +import java.util.List; +import net.firedevops.firemud.account.v1.AccountOriginalDraftOrderServiceGrpc; +import org.junit.jupiter.api.Test; + +class AccountOriginalDraftOrderCredentialsTest { + private static final String SECRET = "original.secret.credential"; + private static final Metadata.Key RAW = + Metadata.Key.of( + AccountOriginalDraftOrderCredentials.HEADER.name(), Metadata.BINARY_BYTE_MARSHALLER); + + @Test + void carrierAndWrapperAreRedactedAndApplyOnlyToProtectedExactMethod() { + var credentials = AccountOriginalDraftOrderCredentials.forCall(SECRET); + assertThat(credentials.toString()).doesNotContain(SECRET); + assertThat(AccountOriginalDraftOrderCredentials.Credential.of(SECRET).toString()) + .doesNotContain(SECRET); + var info = mock(CallCredentials.RequestInfo.class); + when(info.getSecurityLevel()).thenReturn(SecurityLevel.PRIVACY_AND_INTEGRITY); + org.mockito.Mockito.doReturn(AccountOriginalDraftOrderServiceGrpc.getClaimOriginalDraftMethod()) + .when(info) + .getMethodDescriptor(); + var applier = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, applier); + var captured = org.mockito.ArgumentCaptor.forClass(Metadata.class); + verify(applier).apply(captured.capture()); + assertThat(AccountOriginalDraftOrderCredentials.readAuthenticated(captured.getValue()).value()) + .isEqualTo(SECRET); + for (var level : List.of(SecurityLevel.NONE, SecurityLevel.INTEGRITY)) { + when(info.getSecurityLevel()).thenReturn(level); + var denied = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, denied); + verify(denied) + .fail( + org.mockito.ArgumentMatchers.argThat( + status -> status.getCode() == io.grpc.Status.Code.UNAUTHENTICATED)); + } + when(info.getSecurityLevel()).thenReturn(SecurityLevel.PRIVACY_AND_INTEGRITY); + org.mockito.Mockito.doReturn( + AccountOriginalDraftOrderServiceGrpc.getClaimOriginalDraftMethod().toBuilder() + .setFullMethodName("different/Method") + .build()) + .when(info) + .getMethodDescriptor(); + var denied = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, denied); + verify(denied).fail(org.mockito.ArgumentMatchers.any()); + } + + @Test + void + authenticatedReadRejectsMissingDuplicateOversizedAndMalformedHeadersWithoutSecretDiagnostics() { + var missing = new Metadata(); + var duplicate = new Metadata(); + duplicate.put(RAW, SECRET.getBytes(StandardCharsets.US_ASCII)); + duplicate.put(RAW, SECRET.getBytes(StandardCharsets.US_ASCII)); + for (var headers : + List.of( + missing, + duplicate, + raw(new byte[0]), + raw(new byte[] {(byte) 128}), + raw((SECRET + "\n").getBytes(StandardCharsets.US_ASCII)), + raw(new byte[16385]))) { + assertThatThrownBy(() -> AccountOriginalDraftOrderCredentials.readAuthenticated(headers)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(SECRET) + .hasNoCause(); + } + var exact = + AccountOriginalDraftOrderCredentials.readAuthenticated( + raw(SECRET.getBytes(StandardCharsets.US_ASCII))); + assertThat(exact.value()).isEqualTo(SECRET); + assertThat(exact.toString()).doesNotContain(SECRET); + } + + private static Metadata raw(byte[] bytes) { + var headers = new Metadata(); + headers.put(RAW, bytes); + return headers; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderGrpcCodecTest.java new file mode 100644 index 0000000000..32b5ffc2a6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderGrpcCodecTest.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AccountOriginalDraftOrderGrpcCodecTest { + private static final String CREDENTIAL = "original.secret.credential"; + + @Test + void exactCanonicalOriginalOrderAndCorrelationRoundTripWithoutCredentialEcho() { + var original = original(); + var request = AccountOriginalDraftOrderGrpcCodec.Request.create("test", original, CREDENTIAL); + var wire = AccountOriginalDraftOrderGrpcCodec.toRequest(request); + var decoded = AccountOriginalDraftOrderGrpcCodec.fromRequest(wire, CREDENTIAL); + assertThat(decoded.exactlyMatches(request)).isTrue(); + assertThat(wire.toString()).doesNotContain(CREDENTIAL); + assertThat(request.toString()).doesNotContain(CREDENTIAL); + var response = AccountOriginalDraftOrderGrpcCodec.toResponse(decoded); + assertThat(response.toString()).doesNotContain(CREDENTIAL); + var evidence = AccountOriginalDraftOrderGrpcCodec.fromResponse(request, response); + assertThat(evidence.matches(request)).isTrue(); + // The response echoes only these fields; credentials are request custody, not evidence. + assertThat( + evidence.matches( + new AccountOriginalDraftOrderGrpcCodec.Request( + request.schemaVersion(), + request.targetNamespace(), + request.requestId(), + request.originalAccountBinding(), + "another.secret.credential"))) + .isTrue(); + assertThat( + evidence.matches( + AccountOriginalDraftOrderGrpcCodec.Request.create("test", original, CREDENTIAL))) + .isFalse(); + assertThat( + java.util.Arrays.stream(AccountOriginalDraftOrderEvidence.class.getDeclaredFields()) + .noneMatch( + field -> field.getType() == AccountOriginalDraftOrderGrpcCodec.Request.class)) + .isTrue(); + assertThat(evidence.original().canonicalBytes()).isEqualTo(original.canonicalBytes()); + assertThat(evidence.toString()).doesNotContain(CREDENTIAL); + var retry = AccountOriginalDraftOrderGrpcCodec.Request.create("test", original, CREDENTIAL); + assertThat(retry.requestId()).isNotEqualTo(request.requestId()); + assertThat(retry.originalAccountBinding()).isEqualTo(request.originalAccountBinding()); + assertThatThrownBy(() -> AccountOriginalDraftOrderGrpcCodec.fromResponse(retry, response)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsUnknownNoncanonicalOversizedOrDurableCorrelationRequest() { + var original = original(); + var request = AccountOriginalDraftOrderGrpcCodec.Request.create("test", original, CREDENTIAL); + var wire = AccountOriginalDraftOrderGrpcCodec.toRequest(request); + for (var invalid : + List.of( + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setRequestId("1-1-1-1-1").build(), + wire.toBuilder().setRequestId(original.operationId().toString()).build(), + wire.toBuilder().setRequestId(original.requestId().toString()).build(), + wire.toBuilder().setRequestId(original.commitId().toString()).build(), + wire.toBuilder().setRequestId(original.fenceId().toString()).build(), + wire.toBuilder().setUnknownFields(unknown()).build(), + wire.toBuilder().clearOriginalAccountBinding().build(), + wire.toBuilder() + .setOriginalAccountBinding(ByteString.copyFrom(new byte[4194305])) + .build())) { + assertThatThrownBy(() -> AccountOriginalDraftOrderGrpcCodec.fromRequest(invalid, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class) + .hasNoCause() + .hasMessageNotContaining(CREDENTIAL); + } + } + + @Test + void rejectsAllChangedResponseBindingsAndNonCommitOrderStatus() { + var request = AccountOriginalDraftOrderGrpcCodec.Request.create("test", original(), CREDENTIAL); + var response = AccountOriginalDraftOrderGrpcCodec.toResponse(request); + for (var invalid : + List.of( + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder() + .setOriginalAccountBinding(ByteString.copyFrom(original().canonicalBytes())) + .build(), + response.toBuilder().clearOriginalAccountBinding().build(), + response.toBuilder().clearStatus().build(), + response.toBuilder().setStatusValue(99).build(), + response.toBuilder().setUnknownFields(unknown()).build())) { + assertThatThrownBy(() -> AccountOriginalDraftOrderGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class) + .hasNoCause() + .hasMessageNotContaining(CREDENTIAL); + } + } + + static DraftAuthorizationFenceBinding original() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULES", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULES", + "all", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + binding.requestId(), + binding.commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.baseCommitId(), + "0", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + "account", + "1", + new byte[] {1}))) + .withRequiredOwners(); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java new file mode 100644 index 0000000000..f1dc62a597 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java @@ -0,0 +1,624 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalRequest; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Structural and actual loopback-mTLS proof for the closed GL terminal read transport. */ +class GameLogicIntakeTerminalReadGrpcTest { + private static final String NAMESPACE = "test"; + private static final String GL_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; + private static final String WRONG_GL_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final int LARGE_SOURCE_ENTRIES = 1800; + + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private GameLogicIntakeTerminalReadClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createTrustedCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void roundTripsRetainedAbortedAndExplicitAbsenceAndPreservesArrayValueSemantics() { + var small = evidence("test", 1, Outcome.RETAINED); + var retainedResponse = GameLogicIntakeTerminalReadGrpcCodec.toResponse(small); + var retained = + GameLogicIntakeTerminalReadGrpcCodec.fromResponse(small.request(), retainedResponse); + assertThat(retained.terminal().orElseThrow().canonicalBytes()) + .isEqualTo(small.terminal().orElseThrow().canonicalBytes()); + assertThat(retained.terminal().orElseThrow().outcome()) + .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED); + + var aborted = evidence("test", 1, Outcome.ABORTED); + var abortedResponse = GameLogicIntakeTerminalReadGrpcCodec.toResponse(aborted); + assertThat( + GameLogicIntakeTerminalReadGrpcCodec.fromResponse(aborted.request(), abortedResponse) + .terminal() + .orElseThrow() + .outcome()) + .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + + var absent = new GameLogicIntakeTerminalReadEvidence(small.request(), Optional.empty()); + var absentResponse = GameLogicIntakeTerminalReadGrpcCodec.toResponse(absent); + assertThat(absentResponse.getAbsent()).isTrue(); + assertThat( + GameLogicIntakeTerminalReadGrpcCodec.fromResponse(small.request(), absentResponse) + .terminal()) + .isEmpty(); + + var requestWire = GameLogicIntakeTerminalReadGrpcCodec.toRequest(small.request()); + var decodedRequest = GameLogicIntakeTerminalReadGrpcCodec.fromRequest(requestWire); + assertThat(decodedRequest).isEqualTo(small.request()); + assertThat(decodedRequest.hashCode()).isEqualTo(small.request().hashCode()); + assertThat(decodedRequest.binding().canonicalBytes()) + .isEqualTo(small.request().binding().canonicalBytes()); + } + + @Test + void rejectsUnknownFieldsChangedOperationDigestAndTerminalPayload() { + var evidence = evidence("test", 1, Outcome.RETAINED); + var request = evidence.request(); + var response = GameLogicIntakeTerminalReadGrpcCodec.toResponse(evidence); + + var requestWithUnknown = + ReadGameplayRuleIntakeTerminalRequest.newBuilder() + .mergeFrom(GameLogicIntakeTerminalReadGrpcCodec.toRequest(request)) + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 100, + com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + assertThatThrownBy(() -> GameLogicIntakeTerminalReadGrpcCodec.fromRequest(requestWithUnknown)) + .isInstanceOf(IllegalArgumentException.class); + + var otherOperation = evidence("test", 1, Outcome.RETAINED).request().binding(); + var changedOperation = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setOriginalIntakeAuthorization( + ByteString.copyFrom(otherOperation.canonicalBytes())) + .setIntakeAuthorizationDigest(otherOperation.digest())) + .build(); + assertThatThrownBy( + () -> GameLogicIntakeTerminalReadGrpcCodec.fromResponse(request, changedOperation)) + .isInstanceOf(IllegalArgumentException.class); + + var changedDigest = response.toBuilder().setTerminalDigest("sha256:" + "0".repeat(64)).build(); + assertThatThrownBy( + () -> GameLogicIntakeTerminalReadGrpcCodec.fromResponse(request, changedDigest)) + .isInstanceOf(IllegalArgumentException.class); + + byte[] changedPayload = response.getOriginalTerminal().toByteArray(); + changedPayload[changedPayload.length - 1] ^= 1; + var changedTerminal = + response.toBuilder().setOriginalTerminal(ByteString.copyFrom(changedPayload)).build(); + assertThatThrownBy( + () -> GameLogicIntakeTerminalReadGrpcCodec.fromResponse(request, changedTerminal)) + .isInstanceOf(IllegalArgumentException.class); + + var responseWithUnknown = + response.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 100, + com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + assertThatThrownBy( + () -> GameLogicIntakeTerminalReadGrpcCodec.fromResponse(request, responseWithUnknown)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void loopbackStrictMtlsTransportsLargeCanonicalTerminalAndPinsBothPeerIdentities() + throws Exception { + var large = evidence(NAMESPACE, LARGE_SOURCE_ENTRIES, Outcome.RETAINED); + byte[] terminalBytes = large.terminal().orElseThrow().canonicalBytes(); + assertThat(terminalBytes.length) + .isGreaterThan(4 * 1024 * 1024) + .isLessThanOrEqualTo(GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES); + assertThat(GameLogicIntakeTerminalReadGrpcCodec.toResponse(large).getSerializedSize()) + .isLessThanOrEqualTo(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES); + + startServer(pki.gameLogicServer(), large); + client = newClient(server, pki.accountClient()); + client.init(); + var actual = client.read(large.request()); + assertThat(actual.terminal().orElseThrow().canonicalBytes()).isEqualTo(terminalBytes); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + + stopTransport(); + startServer(pki.wrongServer(), large); + client = newClient(server, pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.read(large.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + + private enum Outcome { + RETAINED, + ABORTED + } + + private void startServer(TestIdentity identity, GameLogicIntakeTerminalReadEvidence evidence) + throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var service = + new GameLogicGameplayRuleIntakeTerminalReadServiceGrpc + .GameLogicGameplayRuleIntakeTerminalReadServiceImplBase() { + @Override + public void readGameplayRuleIntakeTerminal( + ReadGameplayRuleIntakeTerminalRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + var request = GameLogicIntakeTerminalReadGrpcCodec.fromRequest(wire); + var response = + GameLogicIntakeTerminalReadGrpcCodec.toResponse( + new GameLogicIntakeTerminalReadEvidence(request, evidence.terminal())); + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GameLogicIntakeTerminalReadClient newClient(Server target, TestIdentity local) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameLogicService("localhost:" + target.getPort()); + return new GameLogicIntakeTerminalReadClient( + endpoints, pki.clientProperties(tempDirectory, local), new GrpcChannelFactory(), NAMESPACE); + } + + /** These canonical bytes are deliberately synthetic transport evidence, not owner provenance. */ + private static GameLogicIntakeTerminalReadEvidence evidence( + String namespace, int entryCount, Outcome outcome) { + var tenant = UUID.randomUUID(); + var version = UUID.randomUUID(); + var requestId = UUID.randomUUID(); + var commitId = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + var definitions = new ArrayList(); + var revisions = new ArrayList(); + var revisionIds = new ArrayList(); + for (int index = 0; index < entryCount; index++) { + var definition = + new GameplayRuleManifest.AdmissionTag( + String.format(java.util.Locale.ROOT, "tag-%05d", index)); + definitions.add(definition); + var revisionId = UUID.randomUUID(); + revisionIds.add(revisionId); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + revisionId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload(definition))); + } + var selectedBinding = + DraftCommitBinding.create( + target, + requestId, + commitId, + "genesis", + List.of(revisions.getFirst()), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var definitionsByFamily = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) + definitionsByFamily.put(family, new ArrayList<>()); + definitionsByFamily.get(GameplayRuleManifest.Family.ADMISSION_TAGS).addAll(definitions); + var manifest = new GameplayRuleManifest(definitionsByFamily); + var entries = new ArrayList>(); + for (int index = 0; index < entryCount; index++) { + var definition = definitions.get(index); + var entryBinding = + DraftCommitBinding.create( + target, + requestId, + UUID.randomUUID(), + "genesis", + List.of(revisions.get(index)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + Integer.toString(index)))); + entries.add( + Map.of( + "family", definition.family().name(), + "definitionJson", GameplayRuleManifest.canonical(definition), + "sourceBindingJson", entryBinding.canonicalJson(), + "sourceBindingDigest", entryBinding.digest(), + "revisionOrder", "0", + "revisionId", revisionIds.get(index).toString())); + } + String snapshot = + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + entries)); + var source = new GameplayRuleSelectedSource(snapshot); + var accountEvidence = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + var authorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.fromString(accountEvidence.scopeId()), + source, + List.of(accountEvidence)); + var operation = new GameLogicGameplayRuleIntakeOperation(namespace, authorization); + var terminal = + outcome == Outcome.RETAINED + ? GameLogicGameplayRuleIntakeTerminal.retained( + operation, + source.canonicalBytes(), + manifest.canonicalJson().getBytes(StandardCharsets.UTF_8)) + : GameLogicGameplayRuleIntakeTerminal.aborted(operation); + return new GameLogicIntakeTerminalReadEvidence( + GameLogicIntakeTerminalReadEvidence.Request.create(namespace, authorization), + Optional.of(terminal)); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameLogicServer, + TestIdentity wrongServer, + TestIdentity accountClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("terminal-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD terminal-read test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("terminal-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "game-logic-server", GL_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_GL_URI, true), + issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("terminal-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 27fab397ed..e15ab6624c 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -24,9 +24,11 @@ testing { } dependencies { + integrationTestImplementation(project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof"))) compileOnly(libs.spotbugs.annotations) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) testImplementation(libs.bouncycastle.pkix) + integrationTestImplementation(libs.bouncycastle.pkix) implementation(libs.aws.sdk.s3) } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java index 680d974385..2996747af9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.draft; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; @@ -218,6 +219,60 @@ public ApplicationSlot claimApplicationSlot(DraftCommitBinding binding) { return slot; } + /** + * Produces a definitive local no-application terminal for the bounded Game Design-only source + * entry. The same Version lock serializes this proof with source application. Account absence or + * failure is not evidence: the retained terminal itself excludes every later local writer. + */ + GameDesignDraftTerminalOutcome abortUnattemptedLocalSource( + GameDesignDraftTerminalOperation operation) { + requireWritableReadCommittedTransaction(); + DraftCommitBinding binding = operation.gameDesignBinding(); + if (!binding.requiredOwners().equals(List.of(Owner.GAME_DESIGN_CONTROL_PLANE)) + || !operation + .accountBinding() + .requiredOwners() + .equals(List.of(DraftAuthorizationFenceBinding.Owner.GAME_DESIGN))) { + throw new IllegalArgumentException("Complete Game Design-only owner vector required"); + } + lockVersionTarget(binding.target()); + Optional terminal = terminalOutcomes.read(operation); + if (terminal.isPresent()) return terminal.orElseThrow(); + GameDesignDraftTerminalOperation retained = + terminalOutcomes.readOperation(operation.accountBinding().operationId()).orElseThrow(); + if (!operation.exactlyMatches(retained)) { + throw new DraftCommitIdentityConflictException("Exact original local operation required"); + } + requireExactCommitInTransaction(binding); + requireActiveSlot(binding); + OwnerState owner = requireOwnerState(binding, Owner.GAME_DESIGN_CONTROL_PLANE, true); + if (owner.status() != OwnerStatus.NOT_ATTEMPTED) { + throw new DraftCommitStateConflictException( + "Local no-application proof requires an unattempted owner"); + } + var result = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(result, "game-design-local-source-no-application/v1"); + DraftAuthorizationFenceBinding.frame(result, operation.accountBindingBytes()); + DraftAuthorizationFenceBinding.frame(result, binding.canonicalBytes()); + byte[] evidence = result.toByteArray(); + // These transitions and the tombstone commit together. No IN_PROGRESS state escapes this + // transaction, and no source mutation is called on this branch. + markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + recordOwnerOutcome( + binding, + new OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.REJECTED, + binding.commitId(), + binding.digest(), + "local-no-application:" + binding.commitId(), + evidence, + List.of())); + recordDefinitiveFinalAbort(binding, evidence); + releaseApplicationSlot(binding); + return terminalOutcomes.read(operation).orElseThrow(); + } + /** Marks an owner dispatch in progress before the caller makes any remote owner call. */ @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) public OwnerState markOwnerInProgress(DraftCommitBinding binding, Owner owner) { @@ -605,7 +660,9 @@ private void deleteApplicationSlot(DraftCommitBinding binding) { /** * Stores exact, already-authenticated producer no-commit evidence for a definitive owner vector * and atomically makes this commit terminally non-publishable. This storage method does not - * authenticate arbitrary bytes; only a future authenticated recovery producer may call it. + * authenticate arbitrary bytes. The bounded local source producer establishes its own + * no-application proof under the same Version lock; other recovery producers must authenticate + * their complete owner evidence independently. */ @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) public FinalAbortReceipt recordDefinitiveFinalAbort( @@ -1239,7 +1296,7 @@ LockedVersion lockVersionTarget(UUID canonicalTenantId, UUID canonicalVersionId) row.get("base_version_id", Long.class)); } - private LockedVersion lockVersionTarget(TargetProof expected) { + LockedVersion lockVersionTarget(TargetProof expected) { Objects.requireNonNull(expected, "expected"); LockedVersion locked = lockVersionTarget(expected.canonicalTenantId(), expected.canonicalVersionId()); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitService.java new file mode 100644 index 0000000000..a08766b9a6 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitService.java @@ -0,0 +1,175 @@ +package net.firedevops.firemud.gamedesign.draft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.CoordinatorProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered original creator-to-Account-to-local-source composition. This bounded entry accepts + * only a complete Game Design-only owner vector. The generic multi-owner coordinator is unchanged. + * Account participation remains pending until the existing authenticated terminal settlement. + */ +public final class GameDesignSourceCommitService { + private final AccountOriginalDraftOrderClient account; + private final DraftCommitCoordinatorRepository coordinator; + private final GameDesignDraftTerminalOutcomeRepository terminals; + private final GameDesignSourceRepository sources; + private final TransactionTemplate write; + private final TransactionTemplate read; + private final String namespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories are intentionally shared service collaborators.") + public GameDesignSourceCommitService( + AccountOriginalDraftOrderClient account, + DraftCommitCoordinatorRepository coordinator, + GameDesignDraftTerminalOutcomeRepository terminals, + GameDesignSourceRepository sources, + PlatformTransactionManager transactions, + String namespace) { + this.account = Objects.requireNonNull(account); + this.coordinator = Objects.requireNonNull(coordinator); + this.terminals = Objects.requireNonNull(terminals); + this.sources = Objects.requireNonNull(sources); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + write = new TransactionTemplate(Objects.requireNonNull(transactions)); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + read = new TransactionTemplate(transactions); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + } + + /** + * Internal application entry only. Exact terminal replay uses durable operation/source identity + * without reauthenticating a creator credential; this is not an authenticated public recovery + * API. + */ + public GameDesignDraftTerminalOutcome commit( + DraftAuthorizationFenceBinding original, String originalCreatorCredential) { + outsideSql(); + var operation = new GameDesignDraftTerminalOperation(original); + DraftCommitBinding binding = operation.gameDesignBinding(); + if (!binding.requiredOwners().equals(List.of(Owner.GAME_DESIGN_CONTROL_PLANE)) + || !original + .requiredOwners() + .equals(List.of(DraftAuthorizationFenceBinding.Owner.GAME_DESIGN))) + throw new IllegalArgumentException("Complete Game Design-only owner vector required"); + // Terminal retry reads its exact retained operation and source snapshots before any mutable + // creator/currentness recapture. A changed operation conflicts in the terminal repository. + Optional retained = + read.execute(ignored -> terminal(operation)); + if (Objects.requireNonNull(retained).isPresent()) return retained.orElseThrow(); + return begin(operation, originalCreatorCredential); + } + + private GameDesignDraftTerminalOutcome begin( + GameDesignDraftTerminalOperation operation, String credential) { + var original = operation.accountBinding(); + var binding = operation.gameDesignBinding(); + Optional admitted = + write.execute( + ignored -> { + coordinator.lockVersionTarget(binding.target()); + var retained = terminal(operation); + if (retained.isPresent()) return retained; + coordinator.claim(binding, original); + coordinator.claimApplicationSlot(binding); + return Optional.empty(); + }); + if (Objects.requireNonNull(admitted).isPresent()) return admitted.orElseThrow(); + outsideSql(); + try { + var request = + AccountOriginalDraftOrderGrpcCodec.Request.create(namespace, original, credential); + var ordered = account.claim(request); + if (ordered == null || !ordered.matches(request)) + throw new IllegalStateException("Exact authenticated original Account order required"); + } catch (RuntimeException unavailableOrder) { + // A lost/denied Account response cannot prove Account absence. Instead the local owner + // durably excludes its own application; a late Account order settles against that terminal. + write.executeWithoutResult(ignored -> coordinator.abortUnattemptedLocalSource(operation)); + outsideSql(); + return Objects.requireNonNull(read.execute(ignored -> terminal(operation).orElseThrow())); + } + outsideSql(); + write.executeWithoutResult( + ignored -> { + coordinator.lockVersionTarget(binding.target()); + if (terminal(operation).isPresent()) return; + // The exact retained reservation precedes Account ordering and survives local rollback. + var claimed = coordinator.claim(binding, original); + if (!claimed.binding().equals(binding)) + throw new IllegalStateException("Exact local source binding required"); + coordinator.claimApplicationSlot(binding); + var owner = claimed.ownerStates().get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (owner == null) throw new IllegalStateException("Complete local owner state required"); + DraftCommitCoordinatorRepository.OwnerOutcome outcome; + if (owner.status() == OwnerStatus.NOT_ATTEMPTED) { + coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + outcome = sources.apply(binding).ownerOutcome(); + } else if (owner.status() == OwnerStatus.APPLIED) { + // Recovery uses the original retained result; it cannot apply source mutations twice. + outcome = owner.outcome().orElseThrow(); + } else { + throw new IllegalStateException("Unresolved local owner requires exact recovery"); + } + if (outcome.owner() != Owner.GAME_DESIGN_CONTROL_PLANE + || outcome.status() != OwnerStatus.APPLIED + || !binding.commitId().equals(outcome.commitId()) + || !binding.digest().equals(outcome.bindingDigest())) + throw new IllegalStateException("Exact local APPLIED source result required"); + coordinator.advanceSourceVisibilityFence( + binding, new CoordinatorProof(binding, List.of(outcome))); + coordinator.releaseApplicationSlot(binding); + terminal(operation) + .orElseThrow(() -> new IllegalStateException("Terminal source readback unavailable")); + }); + outsideSql(); + return Objects.requireNonNull(read.execute(ignored -> terminal(operation).orElseThrow())); + } + + private Optional terminal( + GameDesignDraftTerminalOperation operation) { + var retained = terminals.read(operation); + if (retained.isEmpty()) return Optional.empty(); + var outcome = retained.orElseThrow(); + if (!operation.exactlyMatches(outcome.operation())) + throw new IllegalStateException("Terminal source operation conflict"); + if (outcome.result() == GameDesignDraftTerminalOutcome.Result.COMMITTED) { + var binding = operation.gameDesignBinding(); + var synchronizedSources = + sources + .readSynchronized(binding.target(), binding.commitId()) + .orElseThrow( + () -> new IllegalStateException("Synchronized source readback unavailable")); + if (!binding.equals(synchronizedSources.command().binding())) + throw new IllegalStateException("Synchronized source binding conflict"); + } + return retained; + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Original source commit requires no ambient transaction"); + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V58__draft_application_lifecycle_interlock.sql b/services/game-design-service/src/main/resources/db/migration/V58__draft_application_lifecycle_interlock.sql new file mode 100644 index 0000000000..52e038eb63 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V58__draft_application_lifecycle_interlock.sql @@ -0,0 +1,124 @@ +-- An admitted original source operation must remain locally completable or definitively abortable +-- while Account ordering runs outside SQL. Publication selection has its existing V43 interlock. +-- [jooq ignore start] +-- Keep retained-state preflight and guard installation atomic against both writer directions. +LOCK TABLE version IN SHARE ROW EXCLUSIVE MODE; +LOCK TABLE game_design_draft_commit_application_slot IN SHARE ROW EXCLUSIVE MODE; +LOCK TABLE game_design_authored_draft_publish_selection IN SHARE ROW EXCLUSIVE MODE; + +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM game_design_draft_commit_application_slot s + LEFT JOIN game_design_draft_commit c + ON c.canonical_tenant_id = s.canonical_tenant_id + AND c.canonical_version_id = s.canonical_version_id + AND c.request_id = s.request_id AND c.commit_id = s.commit_id + LEFT JOIN version v + ON v.id = c.game_design_version_row_id + AND v.tenant_id = c.game_design_version_tenant_key + AND v.canonical_tenant_id = c.canonical_tenant_id + AND v.canonical_version_id = c.canonical_version_id + AND v.identity_source_game_row_id = c.source_game_row_id + AND v.identity_source_game_tenant_key = c.source_game_tenant_key + AND v.identity_source_provenance_kind = c.source_provenance_kind + WHERE v.id IS NULL OR v.version_state IS DISTINCT FROM 'DRAFT' + ) THEN + RAISE EXCEPTION 'Retained Draft application slot lacks its exact DRAFT Version' + USING ERRCODE = 'check_violation'; + END IF; + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_application_slot slot + JOIN game_design_authored_draft_publish_selection selection + USING (canonical_tenant_id, canonical_version_id) + ) THEN + RAISE EXCEPTION 'Retained Draft application slot conflicts with authored publication selection' + USING ERRCODE = 'check_violation'; + END IF; +END; +$$; + +CREATE FUNCTION reject_gd_version_lifecycle_during_draft_application() RETURNS trigger AS $$ +BEGIN + IF NEW.version_state IS NOT DISTINCT FROM OLD.version_state + AND NEW.version_state_epoch IS NOT DISTINCT FROM OLD.version_state_epoch THEN + RETURN NEW; + END IF; + IF EXISTS ( + SELECT 1 FROM game_design_draft_commit_application_slot s + WHERE s.canonical_tenant_id = OLD.canonical_tenant_id + AND s.canonical_version_id = OLD.canonical_version_id + ) THEN + RAISE EXCEPTION 'Active or unresolved Draft application prevents Version lifecycle changes' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_version_draft_application_lifecycle_interlock + BEFORE UPDATE OF version_state, version_state_epoch ON version + FOR EACH ROW + EXECUTE FUNCTION reject_gd_version_lifecycle_during_draft_application(); + +CREATE FUNCTION serialize_gd_draft_application_version() RETURNS trigger AS $$ +BEGIN + -- Acquire the Version write lock before V42's parent-commit lock or any slot lock. A physical + -- no-logical-change UPDATE creates an MVCC conflict for stale REPEATABLE READ/SERIALIZABLE + -- lifecycle writers; a row lock alone would let their old snapshot miss a committed slot. + -- All Version fields, including epoch, timestamps and history, retain their exact values. + UPDATE version v SET version_state = v.version_state + FROM game_design_draft_commit c + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = NEW.request_id AND c.commit_id = NEW.commit_id + AND v.id = c.game_design_version_row_id + AND v.tenant_id = c.game_design_version_tenant_key + AND v.canonical_tenant_id = c.canonical_tenant_id + AND v.canonical_version_id = c.canonical_version_id + AND v.identity_source_game_row_id = c.source_game_row_id + AND v.identity_source_game_tenant_key = c.source_game_tenant_key + AND v.identity_source_provenance_kind = c.source_provenance_kind + AND v.version_state = 'DRAFT'; + IF NOT FOUND THEN + RAISE EXCEPTION 'Draft application slot requires its exact current DRAFT Version' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- PostgreSQL runs same-kind triggers by name: this must precede both retained V42/V43 guards. +CREATE TRIGGER a_gd_draft_application_version_interlock + BEFORE INSERT ON game_design_draft_commit_application_slot + FOR EACH ROW + EXECUTE FUNCTION serialize_gd_draft_application_version(); + +CREATE FUNCTION serialize_gd_authored_selection_version() RETURNS trigger AS $$ +BEGIN + -- The reverse publication ordering needs the same MVCC serialization: merely locking Version + -- in V43 leaves a stale slot inserter's snapshot unaware of a newly committed selection. + UPDATE version v SET version_state = v.version_state + WHERE v.id = NEW.game_design_version_row_id + AND v.tenant_id = NEW.game_design_version_tenant_key + AND v.canonical_tenant_id = NEW.canonical_tenant_id + AND v.canonical_version_id = NEW.canonical_version_id + AND v.identity_source_game_row_id = NEW.source_game_row_id + AND v.identity_source_game_tenant_key = NEW.source_game_tenant_key + AND v.identity_source_provenance_kind = NEW.source_provenance_kind + AND v.version_state = 'DRAFT' + AND v.version_state_epoch = NEW.version_state_epoch; + IF NOT FOUND THEN + RAISE EXCEPTION 'Authored Draft selection requires its exact current DRAFT Version' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER a_gd_authored_selection_version_interlock + BEFORE INSERT ON game_design_authored_draft_publish_selection + FOR EACH ROW + EXECUTE FUNCTION serialize_gd_authored_selection_version(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java new file mode 100644 index 0000000000..a39ceb8d15 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java @@ -0,0 +1,1381 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +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 java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +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.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real GD-issued Game/Version identity and typed gameplay source -> real Account creator issuance, + * original COMMIT_ORDER over strict loopback mTLS -> atomic GD source/fence/terminal readback. + * Account creator/legal bootstrap, platform custody and signer observations remain explicitly + * stipulated upstream inputs. This defines internal construction proof, not authenticated public + * recovery, deployed environment authority or runtime activation. Original Account settlement is + * driven through the existing real authenticated GD terminal read after the local commit. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameDesignSourceCommitPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer ACCOUNT_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("positive-control-ui-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer REPLICA = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(REDIS) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "positive-control-ui-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void genuineOriginalProducerCommitsSourcesAndRetainsExactTerminalRetryWithoutRecapture() + throws Exception { + var local = local(); + try (var account = account(local); + var remote = remote(account)) { + var request = account.prepareOriginalDraftOrder(binding(local, "focus"), NAMESPACE); + assertThat(local.dsl.fetchCount(DSL.table("game_design_draft_commit"))).isZero(); + var service = service(local, remote.client, new GameDesignSourceRepository(local.dsl)); + var terminal = service.commit(request.original(), request.originalCreatorCredential()); + assertThat(terminal.result()).isEqualTo(GameDesignDraftTerminalOutcome.Result.COMMITTED); + assertThat(terminal.operation().accountBindingBytes()) + .isEqualTo(request.originalAccountBinding()); + assertThat(remote.calls.get()).isEqualTo(1); + assertSynchronized(local, request.original()); + account.assertOriginalDraftOrderPending(request.original()); + + // No public recovery endpoint exists: internal exact terminal replay accepts retained source + // identity without a fresh mutable credential. It cannot replace the original durable input. + var retry = service.commit(request.original(), null); + assertThat(retry.finalEvidenceBytes()).isEqualTo(terminal.finalEvidenceBytes()); + assertThat(remote.calls.get()).isEqualTo(1); + assertSynchronized(local, request.original()); + var original = request.original(); + var changedOperation = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + original.requestId(), + original.commitId(), + original.fenceId(), + original.actorAccountId(), + original.tenantId(), + original.versionId(), + original.baseCommitId(), + original.expectedDraftEpoch(), + original.gameDesignBinding(), + original.normalizedInput(), + original.inputDigest(), + original.sources(), + original.schemaVersion(), + original.requiredOwners()); + assertThatThrownBy( + () -> service.commit(changedOperation, request.originalCreatorCredential())) + .isInstanceOf( + DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + var changedSources = new java.util.ArrayList<>(original.sources()); + var source = changedSources.getFirst(); + changedSources.set( + 0, + new DraftAuthorizationFenceBinding.SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + new byte[] {99})); + var substitutedSource = + new DraftAuthorizationFenceBinding( + original.operationId(), + original.requestId(), + original.commitId(), + original.fenceId(), + original.actorAccountId(), + original.tenantId(), + original.versionId(), + original.baseCommitId(), + original.expectedDraftEpoch(), + original.gameDesignBinding(), + original.normalizedInput(), + original.inputDigest(), + changedSources, + original.schemaVersion(), + original.requiredOwners()); + assertThatThrownBy( + () -> service.commit(substitutedSource, request.originalCreatorCredential())) + .isInstanceOf( + DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); + assertThat(remote.calls.get()).isEqualTo(1); + account.assertOriginalDraftOrderPending(original); + settleOriginal(account, local, original); + assertThat(service.commit(original, null).finalEvidenceBytes()) + .isEqualTo(terminal.finalEvidenceBytes()); + assertThat(remote.calls.get()).isEqualTo(1); + } + } + + @Test + void failureAfterActualSourceAwareFenceRollsBackAllLocalEffectsAndRetriesOriginalOrder() + throws Exception { + var local = local(); + try (var account = account(local); + var remote = remote(account)) { + var request = account.prepareOriginalDraftOrder(binding(local, "rollback"), NAMESPACE); + var failingSources = spy(new GameDesignSourceRepository(local.dsl)); + doAnswer( + call -> { + var actual = call.callRealMethod(); + assertThat(actual).isNotNull(); + assertThat( + new DraftCommitCoordinatorRepository(local.dsl) + .readVisibilityFence(local.target)) + .isPresent(); + throw new IllegalStateException("test-only failure after source-aware visibility"); + }) + .when(failingSources) + .readSynchronized(local.target, request.original().commitId()); + assertThatThrownBy( + () -> + service(local, remote.client, failingSources) + .commit(request.original(), request.originalCreatorCredential())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("test-only failure after source-aware visibility"); + var coordinator = new DraftCommitCoordinatorRepository(local.dsl); + assertThat( + coordinator + .read(local.target, request.original().requestId()) + .orElseThrow() + .workflowState()) + .isEqualTo(DraftCommitCoordinatorRepository.WorkflowState.QUEUED); + assertThat(coordinator.readApplicationSlot(local.target)).isPresent(); + assertThat(coordinator.readVisibilityFence(local.target)).isEmpty(); + assertThat( + new GameDesignSourceRepository(local.dsl) + .readSynchronized(local.target, request.original().commitId())) + .isEmpty(); + assertThat(epoch(local)).isEqualTo("0"); + account.assertOriginalDraftOrderPending(request.original()); + + var committed = + service(local, remote.client, new GameDesignSourceRepository(local.dsl)) + .commit(request.original(), request.originalCreatorCredential()); + assertThat(committed.operation().accountBindingBytes()) + .isEqualTo(request.originalAccountBinding()); + assertSynchronized(local, request.original()); + account.assertOriginalDraftOrderPending(request.original()); + } + } + + @Test + void concurrentExactClaimsCannotApplySourceTwice() throws Exception { + var local = local(); + try (var account = account(local); + var remote = remote(account)) { + var request = account.prepareOriginalDraftOrder(binding(local, "concurrent"), NAMESPACE); + // Establish the same genuine original order; concurrent owner retries may fail NOWAIT, + // but must never replace this operation or commit a second source application. + remote.client.claim(request); + var service = service(local, remote.client, new GameDesignSourceRepository(local.dsl)); + try (var workers = java.util.concurrent.Executors.newFixedThreadPool(2)) { + var start = new java.util.concurrent.CountDownLatch(1); + var attempts = + java.util.stream.IntStream.range(0, 2) + .mapToObj( + i -> + workers.submit( + () -> { + start.await(); + try { + service.commit( + request.original(), request.originalCreatorCredential()); + } catch (io.grpc.StatusRuntimeException transientAccountRace) { + assertThat(transientAccountRace.getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.UNAVAILABLE); + } + return true; + })) + .toList(); + start.countDown(); + for (var attempt : attempts) assertThat(attempt.get(20, TimeUnit.SECONDS)).isTrue(); + } + var terminal = service.commit(request.original(), request.originalCreatorCredential()); + if (terminal.result() == GameDesignDraftTerminalOutcome.Result.COMMITTED) { + assertSynchronized(local, request.original()); + } else { + assertAborted(local, request.original()); + } + assertThat(local.dsl.fetchCount(DSL.table("game_design_draft_commit"))).isEqualTo(1); + account.assertOriginalDraftOrderPending(request.original()); + } + } + + @Test + void nonDraftAndOccupiedTargetsCannotCreateAccountOrders() throws Exception { + var local = local(); + try (var account = account(local)) { + var request = account.prepareOriginalDraftOrder(binding(local, "ineligible"), NAMESPACE); + var unusedAccount = mock(AccountOriginalDraftOrderClient.class); + local.dsl.execute( + "UPDATE version SET version_state = 'RETIRED' WHERE id = ?", + local.target.gameDesignVersionRowId()); + assertThatThrownBy( + () -> + service(local, unusedAccount, new GameDesignSourceRepository(local.dsl)) + .commit(request.original(), request.originalCreatorCredential())) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + local.dsl.execute( + "UPDATE version SET version_state = 'DRAFT' WHERE id = ?", + local.target.gameDesignVersionRowId()); + var other = binding(local, "other-slot"); + tx(local) + .executeWithoutResult( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(local.dsl); + coordinator.claim(other); + coordinator.claimApplicationSlot(other); + }); + assertThatThrownBy( + () -> + service(local, unusedAccount, new GameDesignSourceRepository(local.dsl)) + .commit(request.original(), request.originalCreatorCredential())) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + verifyNoInteractions(unusedAccount); + assertThat( + new GameDesignDraftTerminalOutcomeRepository(local.dsl) + .read(new GameDesignDraftTerminalOperation(request.original()))) + .isEmpty(); + assertThat(epoch(local)).isEqualTo("0"); + } + } + + @Test + void selectedPublicationCannotOrderAnotherOriginalSourceCommit() throws Exception { + var local = local(); + try (var account = account(local); + var remote = remote(account)) { + var first = account.prepareOriginalDraftOrder(binding(local, "selected"), NAMESPACE); + service(local, remote.client, new GameDesignSourceRepository(local.dsl)) + .commit(first.original(), first.originalCreatorCredential()); + var selected = new GameDesignDraftTerminalOperation(first.original()).gameDesignBinding(); + tx(local) + .executeWithoutResult( + ignored -> + new AuthoredDraftPublishSelectionRepository( + local.dsl, new DraftCommitCoordinatorRepository(local.dsl)) + .reserve( + new AuthoredDraftPublishSelection.PublishIntent( + local.target.canonicalTenantId(), + local.target.canonicalVersionId(), + UUID.randomUUID().toString(), + "1", + "selected", + selected.requestId(), + selected.commitId(), + selected.digest()))); + var later = account.prepareOriginalDraftOrder(binding(local, "after-selection"), NAMESPACE); + var unusedAccount = mock(AccountOriginalDraftOrderClient.class); + assertThatThrownBy( + () -> + service(local, unusedAccount, new GameDesignSourceRepository(local.dsl)) + .commit(later.original(), later.originalCreatorCredential())) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + verifyNoInteractions(unusedAccount); + assertThat(remote.calls.get()).isEqualTo(1); + assertThat(epoch(local)).isEqualTo("1"); + } + } + + @Test + void deniedAccountAcquisitionProducesImmutableLocalAbortWithoutApplyingSources() + throws Exception { + var local = local(); + try (var account = account(local)) { + var request = account.prepareOriginalDraftOrder(binding(local, "denied"), NAMESPACE); + var denied = mock(AccountOriginalDraftOrderClient.class); + when(denied.claim(org.mockito.ArgumentMatchers.any())) + .thenThrow(io.grpc.Status.PERMISSION_DENIED.asRuntimeException()); + var service = service(local, denied, new GameDesignSourceRepository(local.dsl)); + var aborted = service.commit(request.original(), request.originalCreatorCredential()); + assertAborted(local, request.original()); + assertThat(service.commit(request.original(), null).finalEvidenceBytes()) + .isEqualTo(aborted.finalEvidenceBytes()); + org.mockito.Mockito.verify(denied, org.mockito.Mockito.times(1)) + .claim(org.mockito.ArgumentMatchers.any()); + assertThatThrownBy( + () -> + local.dsl.execute( + "UPDATE game_design_draft_commit_final_abort SET abort_bytes = ? WHERE commit_id = ?", + new byte[] {99}, + request.original().commitId())) + .hasMessageContaining("Game Design Draft final-abort evidence is immutable and retained"); + assertThatThrownBy( + () -> + tx(local) + .executeWithoutResult( + ignored -> + new DraftCommitCoordinatorRepository(local.dsl) + .claim( + new GameDesignDraftTerminalOperation(request.original()) + .gameDesignBinding(), + request.original()))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + } + } + + @Test + void lostAccountResponseSettlesAgainstActualDurableLocalAbort() throws Exception { + var local = local(); + try (var account = account(local); + var remote = remote(account)) { + var request = account.prepareOriginalDraftOrder(binding(local, "lost-response"), NAMESPACE); + var lost = spy(remote.client); + doAnswer( + call -> { + call.callRealMethod(); + throw io.grpc.Status.UNAVAILABLE + .withDescription("test-only lost reply") + .asRuntimeException(); + }) + .when(lost) + .claim(org.mockito.ArgumentMatchers.any()); + var service = service(local, lost, new GameDesignSourceRepository(local.dsl)); + var aborted = service.commit(request.original(), request.originalCreatorCredential()); + assertAborted(local, request.original()); + account.assertOriginalDraftOrderPending(request.original()); + settleOriginal(account, local, request.original(), "FAILED_NONPUBLICATION"); + assertThat(service.commit(request.original(), null).finalEvidenceBytes()) + .isEqualTo(aborted.finalEvidenceBytes()); + assertThat(remote.calls.get()).isEqualTo(1); + } + } + + @Test + void lateAccountCompletionCannotBypassAbortAndLifecycleRemainsFencedUntilTerminal() + throws Exception { + var local = local(); + try (var account = account(local); + var remote = remote(account); + var worker = java.util.concurrent.Executors.newSingleThreadExecutor()) { + var request = account.prepareOriginalDraftOrder(binding(local, "late-order"), NAMESPACE); + var entered = new java.util.concurrent.CountDownLatch(1); + var finishAccount = new java.util.concurrent.CountDownLatch(1); + var late = spy(remote.client); + doAnswer( + call -> { + entered.countDown(); + if (!finishAccount.await(20, TimeUnit.SECONDS)) + throw new AssertionError("late Account wait"); + return call.callRealMethod(); + }) + .when(late) + .claim(org.mockito.ArgumentMatchers.any()); + var attempt = + worker.submit( + () -> + service(local, late, new GameDesignSourceRepository(local.dsl)) + .commit(request.original(), request.originalCreatorCredential())); + try { + assertThat(entered.await(20, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy( + () -> + local.dsl.execute( + "UPDATE version SET version_state_epoch = version_state_epoch + 1 WHERE id = ?", + local.target.gameDesignVersionRowId())) + .hasMessageContaining( + "Active or unresolved Draft application prevents Version lifecycle changes"); + assertThatThrownBy( + () -> + local.dsl.execute( + "UPDATE version SET version_state = 'RETIRED' WHERE id = ?", + local.target.gameDesignVersionRowId())) + .hasMessageContaining( + "Active or unresolved Draft application prevents Version lifecycle changes"); + assertThat( + local.dsl.execute( + "UPDATE version SET version_state = version_state, version_state_epoch = version_state_epoch WHERE id = ?", + local.target.gameDesignVersionRowId())) + .isEqualTo(1); + var binding = new GameDesignDraftTerminalOperation(request.original()).gameDesignBinding(); + assertThatThrownBy( + () -> + tx(local) + .executeWithoutResult( + ignored -> + new AuthoredDraftPublishSelectionRepository( + local.dsl, new DraftCommitCoordinatorRepository(local.dsl)) + .reserve( + new AuthoredDraftPublishSelection.PublishIntent( + local.target.canonicalTenantId(), + local.target.canonicalVersionId(), + UUID.randomUUID().toString(), + "1", + "blocked during order", + binding.requestId(), + binding.commitId(), + binding.digest())))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class) + .hasMessage( + "An active or unresolved owner application prevents Draft publication selection"); + var denied = mock(AccountOriginalDraftOrderClient.class); + when(denied.claim(org.mockito.ArgumentMatchers.any())) + .thenThrow(io.grpc.Status.UNAVAILABLE.asRuntimeException()); + service(local, denied, new GameDesignSourceRepository(local.dsl)) + .commit(request.original(), request.originalCreatorCredential()); + assertAborted(local, request.original()); + } finally { + finishAccount.countDown(); + } + assertThat(attempt.get(20, TimeUnit.SECONDS).result()) + .isEqualTo(GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED); + assertAborted(local, request.original()); + account.assertOriginalDraftOrderPending(request.original()); + settleOriginal(account, local, request.original(), "FAILED_NONPUBLICATION"); + assertThat( + local.dsl.execute( + "UPDATE version SET version_state_epoch = version_state_epoch + 1 WHERE id = ?", + local.target.gameDesignVersionRowId())) + .isEqualTo(1); + } + } + + @Test + void concurrentApplicationWinningVersionLockReturnsCommittedInsteadOfAborting() throws Exception { + var local = local(); + try (var account = account(local); + var remote = remote(account); + var workers = java.util.concurrent.Executors.newFixedThreadPool(2)) { + var request = account.prepareOriginalDraftOrder(binding(local, "apply-wins"), NAMESPACE); + var firstOrdered = new java.util.concurrent.CountDownLatch(1); + var permitApply = new java.util.concurrent.CountDownLatch(1); + var failedCallEntered = new java.util.concurrent.CountDownLatch(1); + var permitFailure = new java.util.concurrent.CountDownLatch(1); + var applicationEntered = new java.util.concurrent.CountDownLatch(1); + var permitCommit = new java.util.concurrent.CountDownLatch(1); + var firstClient = spy(remote.client); + doAnswer( + call -> { + var evidence = call.callRealMethod(); + firstOrdered.countDown(); + if (!permitApply.await(20, TimeUnit.SECONDS)) + throw new AssertionError("apply admission wait"); + return evidence; + }) + .when(firstClient) + .claim(org.mockito.ArgumentMatchers.any()); + var failedClient = mock(AccountOriginalDraftOrderClient.class); + doAnswer( + call -> { + failedCallEntered.countDown(); + if (!permitFailure.await(20, TimeUnit.SECONDS)) + throw new AssertionError("failure wait"); + throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); + }) + .when(failedClient) + .claim(org.mockito.ArgumentMatchers.any()); + var heldSources = spy(new GameDesignSourceRepository(local.dsl)); + doAnswer( + call -> { + var applied = call.callRealMethod(); + applicationEntered.countDown(); + if (!permitCommit.await(20, TimeUnit.SECONDS)) + throw new AssertionError("source commit wait"); + return applied; + }) + .when(heldSources) + .apply(org.mockito.ArgumentMatchers.any()); + var applying = + workers.submit( + () -> + service(local, firstClient, heldSources) + .commit(request.original(), request.originalCreatorCredential())); + java.util.concurrent.Future aborting = null; + try { + assertThat(firstOrdered.await(20, TimeUnit.SECONDS)).isTrue(); + aborting = + workers.submit( + () -> + service(local, failedClient, new GameDesignSourceRepository(local.dsl)) + .commit(request.original(), request.originalCreatorCredential())); + assertThat(failedCallEntered.await(20, TimeUnit.SECONDS)).isTrue(); + permitApply.countDown(); + assertThat(applicationEntered.await(20, TimeUnit.SECONDS)).isTrue(); + permitFailure.countDown(); + } finally { + permitApply.countDown(); + permitFailure.countDown(); + permitCommit.countDown(); + } + var committed = applying.get(20, TimeUnit.SECONDS); + assertThat(committed.result()).isEqualTo(GameDesignDraftTerminalOutcome.Result.COMMITTED); + assertThat(Objects.requireNonNull(aborting).get(20, TimeUnit.SECONDS).finalEvidenceBytes()) + .isEqualTo(committed.finalEvidenceBytes()); + assertSynchronized(local, request.original()); + settleOriginal(account, local, request.original()); + } + } + + private void assertAborted(Local local, DraftAuthorizationFenceBinding original) { + var terminal = + new GameDesignDraftTerminalOutcomeRepository(local.dsl) + .read(new GameDesignDraftTerminalOperation(original)) + .orElseThrow(); + assertThat(terminal.result()) + .isEqualTo(GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED); + var coordinator = new DraftCommitCoordinatorRepository(local.dsl); + var state = coordinator.read(local.target, original.requestId()).orElseThrow(); + assertThat(state.workflowState()) + .isEqualTo(DraftCommitCoordinatorRepository.WorkflowState.FAILED_NONPUBLICATION); + assertThat(state.ownerStates().get(DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE).status()) + .isEqualTo(DraftCommitCoordinatorRepository.OwnerStatus.REJECTED); + assertThat(coordinator.readApplicationSlot(local.target)).isEmpty(); + assertThat(coordinator.readVisibilityFence(local.target)).isEmpty(); + assertThat(epoch(local)).isEqualTo("0"); + } + + @Test + void noApplicationProducerCannotAbortInProgressUnknownOrActuallyAppliedOwner() throws Exception { + var local = local(); + try (var account = account(local); + var remote = remote(account)) { + var request = account.prepareOriginalDraftOrder(binding(local, "unsafe-abort"), NAMESPACE); + var operation = new GameDesignDraftTerminalOperation(request.original()); + var binding = operation.gameDesignBinding(); + var coordinator = new DraftCommitCoordinatorRepository(local.dsl); + remote.client.claim(request); + tx(local) + .executeWithoutResult( + ignored -> { + coordinator.claim(binding, request.original()); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + }); + assertUnsafeLocalAbort(local, coordinator, operation); + // This storage-only diagnostic setup supplies uncertainty, never positive owner evidence. + tx(local) + .executeWithoutResult( + ignored -> + coordinator.recordOwnerOutcome( + binding, + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN, + binding.commitId(), + binding.digest(), + null, + null, + List.of()))); + assertUnsafeLocalAbort(local, coordinator, operation); + var applied = + tx(local).execute(ignored -> new GameDesignSourceRepository(local.dsl).apply(binding)); + assertUnsafeLocalAbort(local, coordinator, operation); + tx(local) + .executeWithoutResult( + ignored -> { + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(Objects.requireNonNull(applied).ownerOutcome()))); + coordinator.releaseApplicationSlot(binding); + }); + assertSynchronized(local, request.original()); + settleOriginal(account, local, request.original()); + } + } + + private void assertUnsafeLocalAbort( + Local local, + DraftCommitCoordinatorRepository coordinator, + GameDesignDraftTerminalOperation operation) { + assertThatThrownBy( + () -> tx(local).execute(ignored -> coordinator.abortUnattemptedLocalSource(operation))) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class) + .hasMessage("Local no-application proof requires an unattempted owner"); + assertThat(coordinator.readApplicationSlot(local.target)).isPresent(); + assertThat(new GameDesignDraftTerminalOutcomeRepository(local.dsl).read(operation)).isEmpty(); + } + + private TransactionTemplate tx(Local local) { + var result = new TransactionTemplate(local.manager); + result.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return result; + } + + @Test + void rawLifecycleFirstRejectsSlotInsertAcrossSupportedIsolationLevels() throws Exception { + for (int isolation : storageIsolationLevels()) { + var local = local(); + var binding = binding(local, "lifecycle-first"); + tx(local) + .executeWithoutResult( + ignored -> new DraftCommitCoordinatorRepository(local.dsl).claim(binding)); + try (var slot = storageConnection(local, isolation); + var lifecycle = storageConnection(local, Connection.TRANSACTION_READ_COMMITTED); + var worker = java.util.concurrent.Executors.newSingleThreadExecutor()) { + var slotSql = DSL.using(slot, SQLDialect.POSTGRES); + slotSql.fetch("SELECT * FROM version WHERE id = ?", local.target.gameDesignVersionRowId()); + DSL.using(lifecycle, SQLDialect.POSTGRES) + .execute( + "UPDATE version SET version_state = 'RETIRED', version_state_epoch = version_state_epoch + 1 WHERE id = ?", + local.target.gameDesignVersionRowId()); + var started = new java.util.concurrent.CountDownLatch(1); + var inserting = + worker.submit( + () -> { + started.countDown(); + return failedStorageWrite(() -> insertRawSlot(slotSql, binding)); + }); + try { + assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + } finally { + lifecycle.commit(); + } + assertThat(inserting.get(20, TimeUnit.SECONDS)) + .isEqualTo(isolation == Connection.TRANSACTION_READ_COMMITTED ? "23514" : "40001"); + slot.rollback(); + assertThat( + new DraftCommitCoordinatorRepository(local.dsl).readApplicationSlot(local.target)) + .isEmpty(); + assertThat( + local + .dsl + .fetchSingle( + "SELECT version_state FROM version WHERE id = ?", + local.target.gameDesignVersionRowId()) + .get(0, String.class)) + .isEqualTo("RETIRED"); + } + } + } + + @Test + void rawSlotFirstRejectsLifecycleWriteIncludingStaleSnapshotsWithoutChangingVersionFields() + throws Exception { + for (int isolation : storageIsolationLevels()) { + var local = local(); + var binding = binding(local, "slot-first"); + tx(local) + .executeWithoutResult( + ignored -> new DraftCommitCoordinatorRepository(local.dsl).claim(binding)); + var before = versionFields(local); + try (var slot = storageConnection(local, Connection.TRANSACTION_READ_COMMITTED); + var lifecycle = storageConnection(local, isolation); + var worker = java.util.concurrent.Executors.newSingleThreadExecutor()) { + var lifecycleSql = DSL.using(lifecycle, SQLDialect.POSTGRES); + lifecycleSql.fetch( + "SELECT * FROM version WHERE id = ?", local.target.gameDesignVersionRowId()); + insertRawSlot(DSL.using(slot, SQLDialect.POSTGRES), binding); + var started = new java.util.concurrent.CountDownLatch(1); + var updating = + worker.submit( + () -> { + started.countDown(); + return failedStorageWrite( + () -> + lifecycleSql.execute( + "UPDATE version SET version_state = 'RETIRED', version_state_epoch = version_state_epoch + 1 WHERE id = ?", + local.target.gameDesignVersionRowId())); + }); + try { + assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + } finally { + slot.commit(); + } + assertThat(updating.get(20, TimeUnit.SECONDS)) + .isEqualTo(isolation == Connection.TRANSACTION_READ_COMMITTED ? "23514" : "40001"); + lifecycle.rollback(); + assertThat(versionFields(local)).isEqualTo(before); + assertThat( + new DraftCommitCoordinatorRepository(local.dsl).readApplicationSlot(local.target)) + .isPresent(); + } + } + } + + @Test + void rawSelectionFirstRejectsSlotInsertEvenWhenSlotSnapshotPredatesSelection() throws Exception { + for (int isolation : storageIsolationLevels()) { + var local = local(); + var selected = synchronizedStorageSelection(local); + var later = binding(local, "after-selection"); + tx(local) + .executeWithoutResult( + ignored -> new DraftCommitCoordinatorRepository(local.dsl).claim(later)); + var before = versionFields(local); + try (var slot = storageConnection(local, isolation); + var selection = storageConnection(local, Connection.TRANSACTION_READ_COMMITTED); + var worker = java.util.concurrent.Executors.newSingleThreadExecutor()) { + var slotSql = DSL.using(slot, SQLDialect.POSTGRES); + slotSql.fetch("SELECT * FROM version WHERE id = ?", local.target.gameDesignVersionRowId()); + insertRawSelection(DSL.using(selection, SQLDialect.POSTGRES), selected); + var started = new java.util.concurrent.CountDownLatch(1); + var inserting = + worker.submit( + () -> { + started.countDown(); + return failedStorageWrite(() -> insertRawSlot(slotSql, later)); + }); + try { + assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + } finally { + selection.commit(); + } + assertThat(inserting.get(20, TimeUnit.SECONDS)) + .isEqualTo(isolation == Connection.TRANSACTION_READ_COMMITTED ? "23514" : "40001"); + slot.rollback(); + assertThat(versionFields(local)).isEqualTo(before); + assertThat( + new DraftCommitCoordinatorRepository(local.dsl).readApplicationSlot(local.target)) + .isEmpty(); + assertThat(local.dsl.fetchCount(DSL.table("game_design_authored_draft_publish_selection"))) + .isEqualTo(1); + } + } + } + + @Test + void rawSlotFirstRejectsSelectionEvenWhenSelectionSnapshotPredatesSlot() throws Exception { + for (int isolation : storageIsolationLevels()) { + var local = local(); + var selected = synchronizedStorageSelection(local); + var later = binding(local, "slot-before-selection"); + tx(local) + .executeWithoutResult( + ignored -> new DraftCommitCoordinatorRepository(local.dsl).claim(later)); + var before = versionFields(local); + try (var slot = storageConnection(local, Connection.TRANSACTION_READ_COMMITTED); + var selection = storageConnection(local, isolation); + var worker = java.util.concurrent.Executors.newSingleThreadExecutor()) { + var selectionSql = DSL.using(selection, SQLDialect.POSTGRES); + selectionSql.fetch( + "SELECT * FROM version WHERE id = ?", local.target.gameDesignVersionRowId()); + insertRawSlot(DSL.using(slot, SQLDialect.POSTGRES), later); + var started = new java.util.concurrent.CountDownLatch(1); + var inserting = + worker.submit( + () -> { + started.countDown(); + return failedStorageWrite(() -> insertRawSelection(selectionSql, selected)); + }); + try { + assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); + } finally { + slot.commit(); + } + assertThat(inserting.get(20, TimeUnit.SECONDS)) + .isEqualTo(isolation == Connection.TRANSACTION_READ_COMMITTED ? "23514" : "40001"); + selection.rollback(); + assertThat(versionFields(local)).isEqualTo(before); + assertThat( + new DraftCommitCoordinatorRepository(local.dsl).readApplicationSlot(local.target)) + .isPresent(); + assertThat(local.dsl.fetchCount(DSL.table("game_design_authored_draft_publish_selection"))) + .isZero(); + } + } + } + + @Test + void migrationRejectsRetainedNonDraftSlotWithoutChangingHistory() { + var local = local("57"); + var binding = binding(local, "retained-invalid"); + tx(local) + .executeWithoutResult( + ignored -> new DraftCommitCoordinatorRepository(local.dsl).claim(binding)); + insertRawSlot(local.dsl, binding); + local.dsl.execute( + "UPDATE version SET version_state = 'RETIRED' WHERE id = ?", + local.target.gameDesignVersionRowId()); + var before = versionFields(local); + var retainedSlot = + local + .dsl + .fetchSingle( + "SELECT to_jsonb(s)::text FROM game_design_draft_commit_application_slot s") + .get(0, String.class); + var schema = local.dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + assertThatThrownBy( + () -> + Flyway.configure() + .dataSource(Objects.requireNonNull(local.manager.getDataSource())) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate()) + .hasStackTraceContaining("Retained Draft application slot lacks its exact DRAFT Version"); + assertThat(versionFields(local)).isEqualTo(before); + assertThat( + local + .dsl + .fetchSingle( + "SELECT to_jsonb(s)::text FROM game_design_draft_commit_application_slot s") + .get(0, String.class)) + .isEqualTo(retainedSlot); + } + + private int[] storageIsolationLevels() { + return new int[] { + Connection.TRANSACTION_READ_COMMITTED, + Connection.TRANSACTION_REPEATABLE_READ, + Connection.TRANSACTION_SERIALIZABLE + }; + } + + private Connection storageConnection(Local local, int isolation) throws SQLException { + var connection = Objects.requireNonNull(local.manager.getDataSource()).getConnection(); + connection.setTransactionIsolation(isolation); + connection.setAutoCommit(false); + DSL.using(connection, SQLDialect.POSTGRES).execute("SET LOCAL lock_timeout = '10s'"); + return connection; + } + + private String failedStorageWrite(Runnable action) { + try { + action.run(); + throw new AssertionError("Conflicting storage write unexpectedly succeeded"); + } catch (org.jooq.exception.DataAccessException failure) { + Throwable cause = failure; + while (cause != null) { + if (cause instanceof SQLException sql) return sql.getSQLState(); + cause = cause.getCause(); + } + throw failure; + } + } + + private String versionFields(Local local) { + return local + .dsl + .fetchSingle( + "SELECT to_jsonb(v)::text FROM version v WHERE id = ?", + local.target.gameDesignVersionRowId()) + .get(0, String.class); + } + + private void insertRawSlot(DSLContext sql, DraftCommitBinding binding) { + sql.execute( + "INSERT INTO game_design_draft_commit_application_slot " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id) VALUES (?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + } + + private AuthoredDraftPublishSelection synchronizedStorageSelection(Local local) { + // Storage-only setup uses actual typed source application/fence, without asserting creator or + // Account authorization. Both racing writes below bypass the Java coordinator entirely. + var binding = binding(local, "storage-selected"); + return Objects.requireNonNull( + tx(local) + .execute( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(local.dsl); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = new GameDesignSourceRepository(local.dsl).apply(binding); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(applied.ownerOutcome()))); + coordinator.releaseApplicationSlot(binding); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + local.target.canonicalTenantId(), + local.target.canonicalVersionId(), + UUID.randomUUID().toString(), + "1", + "storage race", + binding.requestId(), + binding.commitId(), + binding.digest()); + return AuthoredDraftPublishSelection.capture( + intent, + local.target, + coordinator.requireSynchronizedPublicationEvidence( + local.target, binding.requestId(), binding.commitId(), binding.digest())); + })); + } + + private void insertRawSelection(DSLContext sql, AuthoredDraftPublishSelection selected) { + var target = selected.target(); + var intent = selected.intent(); + sql.execute( + "INSERT INTO game_design_authored_draft_publish_selection " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, " + + "game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, publish_request_id, version_state_epoch, " + + "selected_commit_request_id, selected_commit_id, selected_commit_digest, selection_digest, selection_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest(), + selected.digest(), + selected.canonicalJson()); + } + + private void assertSynchronized(Local local, DraftAuthorizationFenceBinding original) { + var snapshot = + new GameDesignSourceRepository(local.dsl) + .readSynchronized(local.target, original.commitId()) + .orElseThrow(); + assertThat( + snapshot + .gameplay() + .manifest() + .families() + .get(GameplayRuleManifest.Family.ADMISSION_TAGS)) + .hasSize(1); + assertThat(snapshot.gameplay().binding().canonicalBytes()) + .isEqualTo(original.gameDesignBinding()); + var coordinator = new DraftCommitCoordinatorRepository(local.dsl); + assertThat(coordinator.read(local.target, original.requestId()).orElseThrow().workflowState()) + .isEqualTo(DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED); + assertThat(coordinator.readApplicationSlot(local.target)).isEmpty(); + assertThat(epoch(local)).isEqualTo("1"); + } + + private String epoch(Local local) { + return local + .dsl + .fetchSingle( + "SELECT source_epoch FROM game_design_gameplay_rule_head WHERE canonical_version_id = ?", + local.target.canonicalVersionId()) + .get(0, String.class); + } + + private GameDesignSourceCommitService service( + Local local, AccountOriginalDraftOrderClient client, GameDesignSourceRepository sources) { + return new GameDesignSourceCommitService( + client, + new DraftCommitCoordinatorRepository(local.dsl), + new GameDesignDraftTerminalOutcomeRepository(local.dsl), + sources, + local.manager, + NAMESPACE); + } + + private AccountControlUiOriginalOrderFixture account(Local local) throws Exception { + return new AccountControlUiOriginalOrderFixture( + ACCOUNT_POSTGRES.getJdbcUrl(), + ACCOUNT_POSTGRES.getUsername(), + ACCOUNT_POSTGRES.getPassword(), + REDIS.getHost(), + REDIS.getMappedPort(6379), + temporary.resolve(UUID.randomUUID().toString()), + local.target.canonicalTenantId()); + } + + private DraftCommitBinding binding(Local local, String tag) { + return DraftCommitBinding.create( + local.target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag(tag)))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + local.target.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + "effective", + "0"))); + } + + private Local local() { + return local(null); + } + + private Local local(String maximumMigration) { + var schema = "source_commit_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + data.setSchema(schema); + var migrations = + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (maximumMigration != null) migrations.target(maximumMigration); + migrations.load().migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(data); + var tx = new TransactionTemplate(manager); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Genuine source commit Game"); + game.setDescription("Actual GD repository identity; Account bootstrap trust is stipulated"); + var savedGame = + Objects.requireNonNull(tx.execute(ignored -> new GameRepository(dsl).save(game))); + var version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + var saved = + Objects.requireNonNull(tx.execute(ignored -> new VersionRepository(dsl).save(version))); + var target = + new DraftCommitBinding.TargetProof( + saved.getCanonicalTenantId(), + saved.getCanonicalVersionId(), + saved.getId(), + saved.getTenantId(), + saved.getIdentitySourceGameRowId(), + saved.getIdentitySourceGameTenantKey(), + saved.getIdentitySourceProvenanceKind()); + assertThat(target.canonicalTenantId()).isEqualTo(savedGame.getCanonicalTenantId()); + return new Local(dsl, manager, target); + } + + private record Local( + DSLContext dsl, + DataSourceTransactionManager manager, + DraftCommitBinding.TargetProof target) {} + + private void settleOriginal( + AccountControlUiOriginalOrderFixture account, + Local local, + DraftAuthorizationFenceBinding original) + throws Exception { + settleOriginal(account, local, original, "COMMITTED"); + } + + private void settleOriginal( + AccountControlUiOriginalOrderFixture account, + Local local, + DraftAuthorizationFenceBinding original, + String expectedSettlementOutcome) + throws Exception { + var pki = new TestPki(temporary.resolve(UUID.randomUUID().toString())); + var server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(AccountOriginalDraftOrderGrpcCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.forServer( + pki.gameDesignServer.certificate.toFile(), + pki.gameDesignServer.key.toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new GameDesignDraftTerminalReadGrpcService( + new GameDesignDraftTerminalOutcomeRepository(local.dsl), NAMESPACE), + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + server.getPort()); + var unusedWorld = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient.class); + try (var client = + new net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient( + endpoints, pki.accountClient.properties(pki.ca), new GrpcChannelFactory(), NAMESPACE)) { + client.init(); + account.reconcileOriginalDraft( + original, client, unusedWorld, NAMESPACE, expectedSettlementOutcome); + org.mockito.Mockito.verifyNoInteractions(unusedWorld); + } finally { + server.shutdownNow(); + if (!server.awaitTermination(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Test server did not stop"); + } + } + + private Remote remote(AccountControlUiOriginalOrderFixture account) throws Exception { + var pki = new TestPki(temporary.resolve(UUID.randomUUID().toString())); + var calls = new AtomicInteger(); + var server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(AccountOriginalDraftOrderGrpcCodec.MAX_WIRE_BYTES) + .maxInboundMetadataSize(AccountOriginalDraftOrderGrpcCodec.MAX_METADATA_BYTES) + .sslContext( + GrpcSslContexts.forServer( + pki.accountServer.certificate.toFile(), pki.accountServer.key.toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + account.originalDraftOrderProducer(NAMESPACE), + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + calls.incrementAndGet(); + return next.startCall(call, headers); + } + }, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + server.getPort()); + var client = + new AccountOriginalDraftOrderClient( + endpoints, + pki.gameDesignClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE); + try { + client.init(); + return new Remote(server, client, calls); + } catch (Exception failure) { + server.shutdownNow(); + throw failure; + } + } + + private record Remote(Server server, AccountOriginalDraftOrderClient client, AtomicInteger calls) + implements AutoCloseable { + @Override + public void close() throws Exception { + client.close(); + server.shutdownNow(); + if (!server.awaitTermination(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Test server did not stop"); + } + } + + /** Ephemeral certificate authority, never a deployed trust root or live workload credential. */ + private static final class TestPki { + final Path ca; + final TestIdentity accountServer, gameDesignClient, accountClient, gameDesignServer; + + TestPki(Path root) throws Exception { + Files.createDirectories(root); + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var caKeys = generator.generateKeyPair(); + var name = new org.bouncycastle.asn1.x500.X500Name("CN=Test-only Account World proof CA"); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + name, + java.math.BigInteger.ONE, + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + name, + caKeys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(true)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage(org.bouncycastle.asn1.x509.KeyUsage.keyCertSign)); + var signer = + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()); + var caCert = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate(builder.build(signer)); + ca = pem(root.resolve("ca.pem"), caCert); + accountServer = issue(root, "account-service", true, caKeys, caCert); + gameDesignClient = issue(root, "game-design-service", false, caKeys, caCert); + accountClient = issue(root, "account-service", false, caKeys, caCert); + gameDesignServer = issue(root, "game-design-service", true, caKeys, caCert); + } + + private static TestIdentity issue( + Path root, + String service, + boolean server, + java.security.KeyPair caKeys, + java.security.cert.X509Certificate caCert) + throws Exception { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var keys = generator.generateKeyPair(); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caCert, + new java.math.BigInteger(120, new java.security.SecureRandom()), + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + new org.bouncycastle.asn1.x500.X500Name("CN=" + service), + keys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(false)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage( + org.bouncycastle.asn1.x509.KeyUsage.digitalSignature + | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.extendedKeyUsage, + false, + new org.bouncycastle.asn1.x509.ExtendedKeyUsage( + server + ? org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_serverAuth + : org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_clientAuth)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, + false, + new org.bouncycastle.asn1.x509.GeneralNames( + new org.bouncycastle.asn1.x509.GeneralName[] { + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.uniformResourceIdentifier, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.dNSName, "localhost"), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.iPAddress, "127.0.0.1") + })); + var certificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + builder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + String prefix = service + (server ? "-server" : "-client"); + return new TestIdentity( + pem(root.resolve(prefix + ".crt"), certificate), + pem(root.resolve(prefix + ".key"), keys.getPrivate())); + } + + private static Path pem(Path path, Object value) throws Exception { + try (var writer = + new org.bouncycastle.openssl.jcajce.JcaPEMWriter(Files.newBufferedWriter(path))) { + writer.writeObject(value); + } + return path; + } + } + + private record TestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var result = new CommonGrpcClientProperties(); + result.setPlaintext(false); + result.setCertChain(certificate.toString()); + result.setPrivateKey(key.toString()); + result.setCaCert(ca.toString()); + return result; + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 986cc54765..298ecf341a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -1067,8 +1067,13 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( historicalV1, operation.world().canonicalBytes()); var policySetsBefore = - dsl.fetch("SELECT * FROM game_design_published_realm_policy_set").intoMaps(); - var policiesBefore = dsl.fetch("SELECT * FROM game_design_published_realm_policy").intoMaps(); + dsl.fetch( + "SELECT * FROM game_design_published_realm_policy_set ORDER BY canonical_tenant_id, canonical_version_id") + .intoMaps(); + var policiesBefore = + dsl.fetch( + "SELECT * FROM game_design_published_realm_policy ORDER BY canonical_tenant_id, canonical_version_id, ordinal") + .intoMaps(); assertThatThrownBy( () -> inOwnerTransaction( @@ -1082,9 +1087,18 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( .satisfies( failure -> assertThat(((java.sql.SQLException) failure).getSQLState()).isEqualTo("23514")); - assertThat(dsl.fetch("SELECT * FROM game_design_published_realm_policy_set").intoMaps()) + // JDBC creates new byte[] values on readback; compare every retained value by content. + assertThat( + dsl.fetch( + "SELECT * FROM game_design_published_realm_policy_set ORDER BY canonical_tenant_id, canonical_version_id") + .intoMaps()) + .usingRecursiveComparison() .isEqualTo(policySetsBefore); - assertThat(dsl.fetch("SELECT * FROM game_design_published_realm_policy").intoMaps()) + assertThat( + dsl.fetch( + "SELECT * FROM game_design_published_realm_policy ORDER BY canonical_tenant_id, canonical_version_id, ordinal") + .intoMaps()) + .usingRecursiveComparison() .isEqualTo(policiesBefore); assertThat( new GameDesignPublicationOperationRepository(dsl) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitServiceTest.java new file mode 100644 index 0000000000..f536cd3240 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitServiceTest.java @@ -0,0 +1,211 @@ +package net.firedevops.firemud.gamedesign.draft; + +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.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameDesignSourceCommitServiceTest { + private final AccountOriginalDraftOrderClient account = + mock(AccountOriginalDraftOrderClient.class); + private final DraftCommitCoordinatorRepository coordinator = + mock(DraftCommitCoordinatorRepository.class); + private final GameDesignDraftTerminalOutcomeRepository terminal = + mock(GameDesignDraftTerminalOutcomeRepository.class); + private final GameDesignSourceRepository sources = mock(GameDesignSourceRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final GameDesignSourceCommitService service = + new GameDesignSourceCommitService( + account, coordinator, terminal, sources, transactions, "test"); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void completeMixedOwnerVectorIsDeniedBeforeAnyCaptureOrLocalClaim() { + assertThatThrownBy(() -> service.commit(original(true), "creator.credential")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Complete Game Design-only owner vector required"); + verifyNoInteractions(account, coordinator, terminal, sources, transactions); + } + + @Test + void historicalWorldParticipationCannotBeDroppedFromAnOtherwiseLocalBinding() { + var local = original(false); + var historical = + new DraftAuthorizationFenceBinding( + local.operationId(), + local.requestId(), + local.commitId(), + local.fenceId(), + local.actorAccountId(), + local.tenantId(), + local.versionId(), + local.baseCommitId(), + local.expectedDraftEpoch(), + local.gameDesignBinding(), + local.normalizedInput(), + local.inputDigest(), + local.sources()); + assertThatThrownBy(() -> service.commit(historical, "creator.credential")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(account, coordinator, terminal, sources, transactions); + } + + @Test + void ambientSqlOrSynchronizationCannotEncloseAccountTransport() { + var local = original(false); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> service.commit(local, "creator.credential")) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> service.commit(local, "creator.credential")) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(account, coordinator, terminal, sources, transactions); + } + + @Test + void ineligibleLocalReservationNeverCallsAccount() { + var original = original(false); + doThrow(new DraftCommitCoordinatorRepository.DraftCommitStateConflictException("not DRAFT")) + .when(coordinator) + .claim(any(), any()); + assertThatThrownBy(() -> service.commit(original, "creator.credential")) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + verifyNoInteractions(account, sources); + } + + @Test + void occupiedOrSelectedApplicationSlotNeverCallsAccount() { + var original = original(false); + doThrow(new DraftCommitCoordinatorRepository.DraftCommitStateConflictException("slot denied")) + .when(coordinator) + .claimApplicationSlot(any()); + assertThatThrownBy(() -> service.commit(original, "creator.credential")) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + verifyNoInteractions(account, sources); + } + + @Test + void unavailableAccountOrderUsesDurableLocalAbortAfterReservation() { + var original = original(false); + var aborted = mock(GameDesignDraftTerminalOutcome.class); + when(aborted.operation()).thenReturn(new GameDesignDraftTerminalOperation(original)); + when(aborted.result()).thenReturn(GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED); + when(terminal.read(any(GameDesignDraftTerminalOperation.class))) + .thenReturn(Optional.empty(), Optional.empty(), Optional.of(aborted)); + when(account.claim(any())).thenThrow(io.grpc.Status.UNAVAILABLE.asRuntimeException()); + when(coordinator.abortUnattemptedLocalSource(any())).thenReturn(aborted); + assertThat(service.commit(original, "creator.credential")).isSameAs(aborted); + var order = inOrder(coordinator, account); + order.verify(coordinator).lockVersionTarget(any(DraftCommitBinding.TargetProof.class)); + order.verify(coordinator).claim(any(), any()); + order.verify(coordinator).claimApplicationSlot(any()); + order.verify(account).claim(any()); + order.verify(coordinator).abortUnattemptedLocalSource(any()); + verifyNoInteractions(sources); + } + + @Test + void exactAbortedTerminalRetryNeverRecapturesCreatorOrAccount() { + var original = original(false); + var operation = new GameDesignDraftTerminalOperation(original); + var aborted = mock(GameDesignDraftTerminalOutcome.class); + when(aborted.operation()).thenReturn(operation); + when(aborted.result()).thenReturn(GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED); + when(terminal.read(any(GameDesignDraftTerminalOperation.class))) + .thenReturn(Optional.of(aborted)); + assertThat(service.commit(original, null)).isSameAs(aborted); + verify(terminal).read(any(GameDesignDraftTerminalOperation.class)); + verifyNoInteractions(account, coordinator, sources); + } + + private static DraftAuthorizationFenceBinding original(boolean includeWorld) { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULES", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULES", + "all", + "0"))); + if (includeWorld) + binding = + DraftCommitBinding.create( + target, + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + List.of( + binding.revisions().getFirst(), + new DraftCommitBinding.RevisionPayload( + "1", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + binding.affectedUnits().getFirst(), + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world", + "ROOM_SCOPE", + "room", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + binding.requestId(), + binding.commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.baseCommitId(), + "0", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + "account", + "1", + new byte[] {1}))) + .withRequiredOwners(); + } +} diff --git a/services/game-logic-service/build.gradle.kts b/services/game-logic-service/build.gradle.kts index 513a7bcb07..ca414ad898 100644 --- a/services/game-logic-service/build.gradle.kts +++ b/services/game-logic-service/build.gradle.kts @@ -13,6 +13,8 @@ firemudJooq { } dependencies { + integrationTestImplementation(project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof"))) + integrationTestImplementation(libs.bouncycastle.pkix) compileOnly(libs.spotbugs.annotations) implementation(project(":common-security")) annotationProcessor(libs.spring.boot.configuration.processor) diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java index b4b858e3d2..97c00a0990 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeRepository.java @@ -3,6 +3,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java index 53d0c12885..aa22bb636d 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java @@ -5,6 +5,8 @@ import java.util.Arrays; import java.util.Objects; import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; @@ -105,7 +107,8 @@ public GameLogicGameplayRuleIntakeTerminal retain( /** No value means there is no actual owner terminal; ABORTED is an explicit durable terminal. */ public Optional readTerminal( net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding authorization) { - var operation = requestOperation(authorization); + GameLogicGameplayRuleIntakeTerminalReadService.requirePeer(workloadNamespace); + var operation = new GameLogicGameplayRuleIntakeOperation(workloadNamespace, authorization); requireNoActiveTransaction(); return repository .findTerminal(authorization.operationId()) diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java new file mode 100644 index 0000000000..b572a1f0c6 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcService.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadGrpcCodec; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalRequest; +import net.firedevops.firemud.gamelogic.v1.ReadGameplayRuleIntakeTerminalResponse; + +/** No automatic registration; authenticate Account before parsing caller-carried evidence. */ +public final class GameLogicGameplayRuleIntakeTerminalReadGrpcService + extends GameLogicGameplayRuleIntakeTerminalReadServiceGrpc + .GameLogicGameplayRuleIntakeTerminalReadServiceImplBase { + private final GameLogicGameplayRuleIntakeTerminalReadService owner; + private final String namespace; + + public GameLogicGameplayRuleIntakeTerminalReadGrpcService( + GameLogicGameplayRuleIntakeTerminalReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + @Override + public void readGameplayRuleIntakeTerminal( + ReadGameplayRuleIntakeTerminalRequest request, + StreamObserver observer) { + try { + GameLogicGameplayRuleIntakeTerminalReadService.requirePeer(namespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadEvidence.Request + decoded; + try { + decoded = GameLogicIntakeTerminalReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + observer.onNext(GameLogicIntakeTerminalReadGrpcCodec.toResponse(owner.read(decoded))); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java new file mode 100644 index 0000000000..a9638ec90d --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone Account-only read over actual immutable Game Logic storage. */ +public final class GameLogicGameplayRuleIntakeTerminalReadService { + private final GameLogicGameplayRuleIntakeRepository repository; + private final String namespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected repository is an intentionally shared service collaborator.") + public GameLogicGameplayRuleIntakeTerminalReadService( + GameLogicGameplayRuleIntakeRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + public GameLogicIntakeTerminalReadEvidence read( + GameLogicIntakeTerminalReadEvidence.Request request) { + requirePeer(namespace); + if (!namespace.equals(request.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + var original = new GameLogicGameplayRuleIntakeOperation(namespace, request.binding()); + var terminal = repository.findTerminal(request.binding().operationId()); + terminal.ifPresent( + value -> { + if (!Arrays.equals(original.canonicalBytes(), value.operation().canonicalBytes())) + throw Status.ALREADY_EXISTS.asRuntimeException(); + }); + return new GameLogicIntakeTerminalReadEvidence(request, terminal); + } + + static void requirePeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } +} diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java index 8adf4a47c4..0fa9d55a98 100644 --- a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java @@ -17,6 +17,7 @@ import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; @@ -180,6 +181,7 @@ private static Fixture fixture() { .dataSource(dataSource) .schemas(schema) .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) .table("flyway_schema_history") .locations("classpath:db/migration") .load() diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java new file mode 100644 index 0000000000..505ea9efa8 --- /dev/null +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java @@ -0,0 +1,678 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamelogic.*; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamelogic.sourceintake.*; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual Account intake producer/SQL guards, GL storage and HELD/terminal mTLS endpoints. GD + * immutable source and the original author's terminal are explicit upstream stipulations. This + * defines downstream composition proof, not full authoring-chain or registered runtime proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameLogicIntakeSettlementComposedPostgresIntegrationTest { + private static final String NAMESPACE = "test"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("intake-settlement-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "intake-settlement-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void exactTerminalSettlementReleasesOnlyItsOrderAndSurvivesOwnerOutage() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + var captured = f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + selected.requestId(), + selected.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + selected.target().canonicalVersionId(), + selected.baseCommitId(), + "0", + selected.canonicalBytes(), + selected.canonicalBytes(), + selected.digest(), + captured.sources()) + .withRequiredOwners(); + issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); + // Upstream original-author terminal fixture; this test does not manufacture GL HELD evidence. + f.tx( + () -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); + var source = source(selected); + var gd = mock(GameplayRuleSourceReadClient.class); + when(gd.read(any())) + .thenAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)); + var accountRepository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); + var producer = + new AccountGameLogicIntakeAuthorizationService( + issued.actors(), f.fences, accountRepository, gd, NAMESPACE); + var retainedOrder = + asGameDesign( + () -> + producer.authorize( + issued.compact(), UUID.randomUUID(), selected, issued.environment())); + var abortedOrder = + asGameDesign( + () -> + producer.authorize( + issued.compact(), UUID.randomUUID(), selected, issued.environment())); + + String schema = "gl_settlement_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + dataSource.setSchema(schema); + org.flywaydb.core.Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + var glDsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var glManager = new DataSourceTransactionManager(dataSource); + var glTransaction = new TransactionTemplate(glManager); + glTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var glRepository = new GameLogicGameplayRuleIntakeRepository(glDsl); + var pki = new TestPki(temporary.resolve("pki")); + var heldOwner = + new AccountGameLogicIntakeAuthorizationReadGrpcService( + new AccountGameLogicIntakeAuthorizationReadService( + accountRepository, f.manager, NAMESPACE), + NAMESPACE); + var terminalOwner = + new GameLogicGameplayRuleIntakeTerminalReadGrpcService( + new GameLogicGameplayRuleIntakeTerminalReadService(glRepository, NAMESPACE), + NAMESPACE); + Server accountServer = server(heldOwner, pki.accountServer, pki); + Server glServer = server(terminalOwner, pki.gameLogicServer, pki); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + accountServer.getPort()); + endpoints.setGameLogicService("127.0.0.1:" + glServer.getPort()); + try (var held = + new GameLogicIntakeAuthorizationReadClient( + endpoints, + pki.gameLogicClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE); + var terminals = + new GameLogicIntakeTerminalReadClient( + endpoints, + pki.accountClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + held.init(); + terminals.init(); + var glOwner = + new GameLogicGameplayRuleIntakeService(glRepository, glManager, held, gd, NAMESPACE); + var settlement = + new AccountGameLogicIntakeSettlementService( + accountRepository, terminals, f.manager, NAMESPACE); + var request = GameLogicIntakeTerminalReadEvidence.Request.create(NAMESPACE, retainedOrder); + assertThat(terminals.read(request).terminal()).isEmpty(); + assertThatThrownBy(() -> asGameDesign(() -> settlement.settle(retainedOrder))) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(f.dsl.fetchCount(DSL.table("account_game_logic_intake_settlements"))).isZero(); + f.tx( + () -> { + accountRepository.readHeld(retainedOrder); + return null; + }); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), retainedOrder.sources(), new byte[] {2}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + + // Actual HELD transport and local terminal transaction. Both outcomes remain pending here. + var retained = asGameDesign(() -> glOwner.retain(retainedOrder)); + var aborted = asGameDesign(() -> glOwner.abort(abortedOrder)); + assertThat(asGameDesign(() -> glOwner.retain(abortedOrder)).canonicalBytes()) + .isEqualTo(aborted.canonicalBytes()); + assertThat(aborted.outcome()) + .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + assertThat(terminals.read(request).terminal().orElseThrow().canonicalBytes()) + .isEqualTo(retained.canonicalBytes()); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(retainedOrder.sources()); + return null; + })) + .isInstanceOf(IllegalStateException.class); + + // Unknown/changed operation identity, peer workload and namespace fail at the real + // endpoint. + var changed = + new GameLogicIntakeAuthorizationBinding( + retainedOrder.operationId(), + retainedOrder.fenceId(), + UUID.randomUUID(), + retainedOrder.actorAccountId(), + retainedOrder.source(), + retainedOrder.sources()); + assertThatThrownBy( + () -> + terminals.read( + GameLogicIntakeTerminalReadEvidence.Request.create(NAMESPACE, changed))) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); + for (var identity : List.of(pki.wrongClient, pki.otherNamespaceClient)) { + try (var denied = + new GameLogicIntakeTerminalReadClient( + endpoints, identity.properties(pki.ca), new GrpcChannelFactory(), NAMESPACE)) { + denied.init(); + assertThatThrownBy(() -> denied.read(request)) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + } + for (var identity : List.of(pki.wrongServer, pki.otherNamespaceServer)) { + Server substituted = server(terminalOwner, identity, pki); + var substitutedEndpoints = endpoints.copy(); + substitutedEndpoints.setGameLogicService("127.0.0.1:" + substituted.getPort()); + try (var denied = + new GameLogicIntakeTerminalReadClient( + substitutedEndpoints, + pki.accountClient.properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE)) { + denied.init(); + assertThatThrownBy(() -> denied.read(request)) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + } finally { + stop(substituted); + } + } + + // Rollback leaves the exact order held; a fabricated/different terminal cannot release it. + assertThatThrownBy( + () -> + f.tx( + () -> { + accountRepository.settle(new AccountGameLogicIntakeSettlement(retained)); + throw new IllegalStateException("rollback settlement"); + })) + .hasMessageContaining("rollback"); + f.tx( + () -> { + accountRepository.readHeld(retainedOrder); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> { + var receipt = new AccountGameLogicIntakeSettlement(retained); + f.dsl.execute( + "INSERT INTO account_game_logic_intake_settlements (operation_id, target_namespace, outcome, terminal_bytes, terminal_digest, receipt_bytes, receipt_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + abortedOrder.operationId(), + NAMESPACE, + "RETAINED", + retained.canonicalBytes(), + retained.digest(), + receipt.canonicalBytes(), + receipt.digest()); + return null; + })) + .hasStackTraceContaining("Changed original Game Logic operation authorization"); + + AccountGameLogicIntakeSettlement receipt; + try (var executor = Executors.newFixedThreadPool(2)) { + var first = executor.submit(() -> asGameDesign(() -> settlement.settle(retainedOrder))); + var second = executor.submit(() -> asGameDesign(() -> settlement.settle(retainedOrder))); + receipt = first.get(20, TimeUnit.SECONDS); + assertThat(second.get(20, TimeUnit.SECONDS).canonicalBytes()) + .isEqualTo(receipt.canonicalBytes()); + } + assertThat(receipt.terminal().canonicalBytes()).isEqualTo(retained.canonicalBytes()); + assertThat(f.dsl.fetchCount(DSL.table("account_game_logic_intake_settlements"))) + .isEqualTo(1); + assertThatThrownBy( + () -> + held.read( + GameLogicIntakeAuthorizationReadEvidence.Request.create( + NAMESPACE, retainedOrder))) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + f.tx( + () -> { + accountRepository.readHeld(abortedOrder); + return null; + }); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(retainedOrder.sources()); + return null; + })) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); + return null; + })) + .hasStackTraceContaining("Distinct Game Logic intake remains pending"); + var abortReceipt = asGameDesign(() -> settlement.settle(abortedOrder)); + assertThat(abortReceipt.terminal().canonicalBytes()).isEqualTo(aborted.canonicalBytes()); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isTrue(); + f.tx( + () -> { + f.fences.markSourceAborted( + change, + DraftAuthorizationFenceRepository.SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + }); + f.tx( + () -> { + f.fences.requireDisclosurePreparation(retainedOrder.sources()); + return null; + }); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE account_game_logic_intake_settlements SET outcome = 'ABORTED' WHERE operation_id = ?", + retainedOrder.operationId())) + .hasStackTraceContaining("immutable"); + assertThatThrownBy( + () -> + f.dsl.execute( + "DELETE FROM account_game_logic_intake_settlements WHERE operation_id = ?", + retainedOrder.operationId())) + .hasStackTraceContaining("immutable"); + assertThatThrownBy(() -> f.dsl.execute("TRUNCATE account_game_logic_intake_settlements")) + .hasStackTraceContaining("immutable"); + stop(glServer); + glServer = null; + // New process collaborators return the stored receipt without an available GL channel. + var restarted = + new AccountGameLogicIntakeSettlementService( + new AccountGameLogicIntakeAuthorizationRepository(f.dsl), + terminals, + f.manager, + NAMESPACE); + assertThat(asGameDesign(() -> restarted.settle(retainedOrder)).canonicalBytes()) + .isEqualTo(receipt.canonicalBytes()); + assertThatThrownBy(() -> asGameDesign(() -> restarted.settle(changed))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(f.dsl.fetchCount(DSL.table("account_game_logic_intake_settlements"))) + .isEqualTo(2); + // Historical GL retry remains exact after Account no longer permits HELD. + assertThat(asGameDesign(() -> glOwner.retain(retainedOrder)).canonicalBytes()) + .isEqualTo(retained.canonicalBytes()); + } finally { + stop(accountServer); + if (glServer != null) stop(glServer); + } + } + } + + private static Server server(io.grpc.BindableService owner, TestIdentity identity, TestPki pki) + throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + identity.certificate().toFile(), identity.key().toFile())) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(owner, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static void stop(Server server) throws Exception { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static DraftCommitBinding selected(UUID tenant) { + var target = + new DraftCommitBinding.TargetProof( + tenant, UUID.randomUUID(), 17, "private", 11, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload( + new GameplayRuleManifest.AdmissionTag("gameplay")))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding selected) { + var definition = new GameplayRuleManifest.AdmissionTag("gameplay"); + Map> families = + new EnumMap<>(GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(definition.family()).add(definition); + var manifest = new GameplayRuleManifest(families); + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + List.of( + Map.of( + "family", + definition.family().name(), + "definitionJson", + GameplayRuleManifest.canonical(definition), + "sourceBindingJson", + selected.canonicalJson(), + "sourceBindingDigest", + selected.digest(), + "revisionOrder", + "0", + "revisionId", + selected.revisions().getFirst().revisionId().toString()))))); + } + + private static T asGameDesign(java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + /** Ephemeral certificate authority, never a deployed trust root or live workload credential. */ + private static final class TestPki { + final Path ca; + final TestIdentity accountServer, + gameLogicServer, + gameLogicClient, + accountClient, + wrongServer, + wrongClient, + otherNamespaceClient, + otherNamespaceServer; + + TestPki(Path root) throws Exception { + Files.createDirectories(root); + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var caKeys = generator.generateKeyPair(); + var name = + new org.bouncycastle.asn1.x500.X500Name("CN=Test-only Account Game Logic proof CA"); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + name, + java.math.BigInteger.ONE, + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + name, + caKeys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(true)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage(org.bouncycastle.asn1.x509.KeyUsage.keyCertSign)); + var signer = + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()); + var caCert = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate(builder.build(signer)); + ca = pem(root.resolve("ca.pem"), caCert); + accountServer = issue(root, "account-service", true, caKeys, caCert, NAMESPACE); + gameLogicServer = issue(root, "game-logic-service", true, caKeys, caCert, NAMESPACE); + gameLogicClient = issue(root, "game-logic-service", false, caKeys, caCert, NAMESPACE); + accountClient = issue(root, "account-service", false, caKeys, caCert, NAMESPACE); + wrongServer = issue(root, "game-design-service", true, caKeys, caCert, NAMESPACE); + wrongClient = issue(root, "game-design-service", false, caKeys, caCert, NAMESPACE); + otherNamespaceClient = issue(root, "account-service", false, caKeys, caCert, "other-test"); + otherNamespaceServer = issue(root, "game-logic-service", true, caKeys, caCert, "other-test"); + } + + private static TestIdentity issue( + Path root, + String service, + boolean server, + java.security.KeyPair caKeys, + java.security.cert.X509Certificate caCert, + String namespace) + throws Exception { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var keys = generator.generateKeyPair(); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caCert, + new java.math.BigInteger(120, new java.security.SecureRandom()), + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + new org.bouncycastle.asn1.x500.X500Name("CN=" + service), + keys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(false)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage( + org.bouncycastle.asn1.x509.KeyUsage.digitalSignature + | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.extendedKeyUsage, + false, + new org.bouncycastle.asn1.x509.ExtendedKeyUsage( + server + ? org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_serverAuth + : org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_clientAuth)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, + false, + new org.bouncycastle.asn1.x509.GeneralNames( + new org.bouncycastle.asn1.x509.GeneralName[] { + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.uniformResourceIdentifier, + "spiffe://firemud/ns/" + namespace + "/sa/" + service), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.dNSName, "localhost"), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.iPAddress, "127.0.0.1") + })); + var certificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + builder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + String prefix = namespace + "-" + service + (server ? "-server" : "-client"); + return new TestIdentity( + pem(root.resolve(prefix + ".crt"), certificate), + pem(root.resolve(prefix + ".key"), keys.getPrivate())); + } + + private static Path pem(Path path, Object value) throws Exception { + try (var writer = + new org.bouncycastle.openssl.jcajce.JcaPEMWriter(Files.newBufferedWriter(path))) { + writer.writeObject(value); + } + return path; + } + } + + private record TestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var result = new CommonGrpcClientProperties(); + result.setPlaintext(false); + result.setCertChain(certificate.toString()); + result.setPrivateKey(key.toString()); + result.setCaCert(ca.toString()); + return result; + } + } +} diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java index c3975dfb7b..930a407f7f 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java @@ -20,6 +20,8 @@ import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; @@ -98,7 +100,7 @@ void explicitAbortIsDurableAndBlocksLaterRetentionWithoutInferringFromMissingRea assertThat(aborted.outcome()).isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); assertThat(retry.canonicalBytes()).containsExactly(aborted.canonicalBytes()); - assertThat(asGameDesign(() -> fixture.service.readTerminal(authorization))).contains(aborted); + assertThat(asAccount(() -> fixture.service.readTerminal(authorization))).contains(aborted); verify(fixture.accountReader).read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); verify(fixture.gameDesignReader, never()) .read(any(GameplayRuleSourceReadEvidence.Request.class)); @@ -176,7 +178,7 @@ void authenticatedSourceMismatchDeniesWithoutWritingAnAbortOrTerminal() { assertThat(Status.fromThrowable(error).getCode()) .isEqualTo(Status.Code.FAILED_PRECONDITION)); assertThat(fixture.stored.get()).isNull(); - assertThat(asGameDesign(() -> fixture.service.readTerminal(authorization))).isEmpty(); + assertThat(asAccount(() -> fixture.service.readTerminal(authorization))).isEmpty(); verify(fixture.repository, never()) .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); } @@ -195,7 +197,7 @@ void unavailableAccountReadLeavesNoTerminalAndDoesNotInferAbort() { assertThat(Status.fromThrowable(error).getCode()) .isEqualTo(Status.Code.UNAVAILABLE)); assertThat(fixture.stored.get()).isNull(); - assertThat(asGameDesign(() -> fixture.service.readTerminal(authorization))).isEmpty(); + assertThat(asAccount(() -> fixture.service.readTerminal(authorization))).isEmpty(); verify(fixture.gameDesignReader, never()) .read(any(GameplayRuleSourceReadEvidence.Request.class)); verify(fixture.repository, never()) @@ -289,6 +291,21 @@ void creatorPublicationCredentialCannotBeMixedWithTheServicePeer() { .read(any(GameplayRuleSourceReadEvidence.Request.class)); } + private static T asAccount(java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/account-service") + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + private static T asGameDesign(java.util.function.Supplier action) { var peer = new GrpcPeerIdentity( diff --git a/services/world-management-service/src/main/resources/db/migration/V57__world_publication_inventory_projection_precedence.sql b/services/world-management-service/src/main/resources/db/migration/V57__world_publication_inventory_projection_precedence.sql new file mode 100644 index 0000000000..21fdd21f8a --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V57__world_publication_inventory_projection_precedence.sql @@ -0,0 +1,19 @@ +-- Preserve the V56 public inventory projection while making JSONB extraction bind before `-`. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + projection_anchor TEXT := $anchor$ 'ownerScope', private_inventory->'ownerScope' - ARRAY['localTenantKey', 'localVersionKey', 'gameDesignVersionId'],$anchor$; + corrected_projection TEXT := $replacement$ 'ownerScope', (private_inventory->'ownerScope') - ARRAY['localTenantKey', 'localVersionKey', 'gameDesignVersionId'],$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_require_publication_operation_account_binding(BYTEA, UUID, BYTEA)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, projection_anchor, ''))) + / length(projection_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V56 World ownerScope projection expression'; + END IF; + EXECUTE replace(original, projection_anchor, corrected_projection); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 56ac4c1340..9aa762c6a3 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -724,6 +724,8 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() "canonicalBindingBytes", "sourceGameRowId"); var ownerBeforeInventoryOperation = ownerSnapshot(world, plan); + // This canonical five-frame operation exercises the SQL projection using the + // exact original Account order and World-retained inventory. assertThat( Objects.requireNonNull( dsl.fetchOne( @@ -741,6 +743,12 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() "\"graphDigest\":\"" + sourceGraphDigest + "\"", "\"graphDigest\":\"sha256:" + "0".repeat(64) + "\"") .getBytes(java.nio.charset.StandardCharsets.UTF_8); + String substitutedOwnerScopeJson = + publicInventoryJson.replace( + "\"ownerScope\":{", "\"ownerScope\":{\"substitutedField\":\"unexpected\","); + assertThat(substitutedOwnerScopeJson).contains("\"substitutedField\""); + byte[] substitutedOwnerScope = + substitutedOwnerScopeJson.getBytes(java.nio.charset.StandardCharsets.UTF_8); byte[] validOperation = publicationOperation.canonicalBytes(); byte[] missingInventory = operationBytes( @@ -763,6 +771,13 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() evidence.canonicalBytes(), substitutedInventory, DraftAuthorizationFenceBinding.digest(substitutedInventory)); + byte[] changedOwnerScope = + operationBytes( + GameDesignPublicationOperationBinding.SCHEMA, + publicationOrder.canonicalBytes(), + evidence.canonicalBytes(), + substitutedOwnerScope, + DraftAuthorizationFenceBinding.digest(substitutedOwnerScope)); byte[] retainedV1 = operationBytes( "game-design-publication-operation/v1", @@ -776,6 +791,7 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() missingInventory, mismatchedDigest, changedInventory, + changedOwnerScope, retainedV1, trailingOperation)) { assertThatThrownBy( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 3b0366855e..bca54dcc28 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -998,28 +998,26 @@ void terminalRejectsUnqualifiedHistoricalFreezeWithoutInventingAccountOrder() { publishedEvidence( publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); var input = preparationInput(f, frozen, selector); - var original = isolatedTerminalEvidence(input); - var request = WorldPublicationTerminal.Request.fromStored(original.canonicalBytes()); UUID fence = selector.request().publicationFence(); var ownerBefore = ownerSnapshot(f, graphApplication.plan()); + var artifactInventoryRowsBefore = + rowJson( + "SELECT to_jsonb(i)::text FROM world_selected_publication_artifact_inventory i " + + "WHERE publication_fence=? ORDER BY publication_fence", + fence); assertThat(publicationAccountQualificationCount(fence)).isZero(); - assertThatThrownBy( - () -> - ownerTransaction() - .execute( - status -> { - insertPublicationTerminal(request); - return null; - })) - .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - publicationTerminalComponent(original) - .complete(request.operationBytes(), request.terminalBytes())) - .isInstanceOf( - WorldPublicationTerminalRepository.PublicationTerminalConflictException.class); + assertThat(artifactInventoryRowsBefore).isEmpty(); + assertThatThrownBy(() -> isolatedTerminalEvidence(input)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessage("Exact frozen World publication has no complete artifact inventory"); assertThat(ownerSnapshot(f, graphApplication.plan())).isEqualTo(ownerBefore); + assertThat( + rowJson( + "SELECT to_jsonb(i)::text FROM world_selected_publication_artifact_inventory i " + + "WHERE publication_fence=? ORDER BY publication_fence", + fence)) + .isEqualTo(artifactInventoryRowsBefore); assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); assertThat(publicationTerminalCount(fence)).isZero(); assertThat(publicationAccountQualificationCount(fence)).isZero(); From 2e466c5eca5de83e7e63ba211c3d07414192a67e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:47:39 +1300 Subject: [PATCH 041/129] Retain exact branding and template configuration source history --- .../game-design-service/asset-storage.md | 4 +- .../game-design-service/game-templates.md | 18 +- .../game-design-service/version-control.md | 2 + ...ame-authoring-publishing-and-activation.md | 8 +- .../gamedesign/publication/AssetSource.java | 4 +- .../publication/BrandingSource.java | 345 +++++++ .../BrandingSourceApplication.java | 43 + .../publication/BrandingSourceRepository.java | 519 +++++++++++ .../publication/BrandingSourceSnapshot.java | 219 +++++ .../gamedesign/publication/CommandSource.java | 8 +- .../GameDesignSourceRepository.java | 199 +++- .../publication/GameplayRuleSource.java | 9 +- .../publication/TemplateConfigSource.java | 405 ++++++++ .../TemplateConfigSourceRepository.java | 699 ++++++++++++++ .../TemplateConfigSourceSnapshot.java | 194 ++++ .../repository/GameTemplateRepository.java | 27 +- .../service/impl/GameTemplateServiceImpl.java | 4 + .../V59__branding_asset_source_history.sql | 495 ++++++++++ .../V60__template_config_source_history.sql | 870 ++++++++++++++++++ ...BrandingSourcePostgresIntegrationTest.java | 451 +++++++++ ...gnSourceCommitPostgresIntegrationTest.java | 46 +- ...teConfigSourcePostgresIntegrationTest.java | 424 +++++++++ ...aunchDescriptorServiceIntegrationTest.java | 26 +- .../publication/BrandingSourceTest.java | 142 +++ .../publication/TemplateConfigSourceTest.java | 172 ++++ .../GameTemplateRepositoryTest.java | 69 ++ .../impl/GameTemplateServiceImplTest.java | 18 + 27 files changed, 5354 insertions(+), 66 deletions(-) create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSource.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V59__branding_asset_source_history.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V60__template_config_source_history.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTemplateRepositoryTest.java diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 57ba3c8948..645be105c9 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -7,7 +7,7 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b ## Implementation Status - **Current first slice:** The ordinary exporter requires V37's durable version-scoped snapshot and verifies its mappings and retained `game_assets.data` bytes before each export or retry. There is no tenant-wide fallback or process-local selection cache. The published construction includes an `ASSET_REFERENCE` source repository with coordinator/history/genesis/snapshot writing and export agreement; this is not a registered production authoring ingress or proof of complete template/config and branding coverage. Missing evidence denies export rather than proving an empty release. Frozen source bytes are database-protected, while unreferenced Draft uploads remain mutable. Version-prefix object writes, numeric public asset identifiers and post-write repair comparison remain drift from the target immutable-candidate lifecycle. See the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle) for capability and proof limits. -- **Selected source coverage:** The construction branch includes the World owner's typed selected-release inventory, retained authenticated read and artifact-export checkpoint, which cover World-owned topology and derived-artifact requiredness only. Game Design's ordinary `ASSET_REFERENCE` source participates in actual fresh-Draft genesis, coordinator application, immutable commit snapshots and export-selection agreement. It is not total Game Design `COMPLETE`: the closed template-reference/config writer, branding records, exact requiredness authority across families and their owner-qualified readback remain absent. Ordinary assets remain `RESOURCE/REQUIRED`; branding has no implemented owner/consumer fallback policy, so no branding role is currently authoritatively `OPTIONAL`. The complete Game Design source/export gate remains closed until all families have exact selected-commit evidence. The unregistered admission construction retains the authenticated World read in its complete original publication operation; PostgreSQL and genuine composed producer/consumer execution remain separate proof requirements in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +- **Selected source coverage:** The construction branch includes the World owner's typed selected-release inventory, retained authenticated read and artifact-export checkpoint, which cover World-owned topology and derived-artifact requiredness only. Game Design's ordinary `ASSET_REFERENCE` source participates in actual fresh-Draft genesis, coordinator application, immutable commit snapshots and export-selection agreement. The separate `BRANDING_ASSET_REFERENCE` construction now joins the same source pipeline through fresh genesis, exact ordered revision history, synchronized snapshots and selected-operation capture. It is not total Game Design `COMPLETE`: external template owner reads, complete inventory composition and immutable export remain open. Ordinary assets remain `RESOURCE/REQUIRED`; branding has no implemented owner/consumer fallback policy, so no branding role is currently authoritatively `OPTIONAL`. The complete Game Design source/export gate remains closed until all families have exact selected-commit evidence. The unregistered admission construction retains the authenticated World read in its complete original publication operation; executed local codec proof, skipped PostgreSQL definitions and genuine composed producer/consumer limits remain separate in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). - **Current upload admission gap:** The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) are requirements, not current proof. `AssetController` accepts multipart uploads and `GameAssetServiceImpl` calls `MultipartFile.getBytes()` without size or quota enforcement; `AssetStoreProperties` has no matching limits. Upload admission and resource-safety readiness therefore remain incomplete and the route must not be treated as ready for external enablement. - **Hosted-content gate gap:** Current asset upload and publish paths do not evaluate Account currentness or persist a tenant/evidence binding. The target gate also applies to Draft asset writes and changed-term stale acceptance; no current route, schema, storage, UI/status, or focused proof implements it. The current Gateway's coarse `/api/design/**` route nevertheless forwards `/api/design/assets` (after `StripPrefix=2`) to the live `POST /assets` controller, whose Game Design boundary checks only privileged JWT/tenant access. Official-hosted asset-upload readiness is blocked until Gateway denies that route or the exact Account-owned gate is implemented and proved. - **Current lifecycle proof:** `version_asset_artifact` records the exported version-number prefix and manifest asset keys, but it does not yet freeze the target exact immutable object-key/digest set or implement the target global publication/purge fence. Repair writes those live prefix objects and the manifest before its exact release-bundle comparison, so pre-write verification is target-only. @@ -127,6 +127,8 @@ The inventory evidence binds canonical tenant, base version, selected commit/sou An empty `requiredManifestAssetKeys[]` is valid only with authenticated complete evidence that this selected release has zero required and exported assets across every applicable family. A frozen ordinary mapping snapshot alone does not establish that condition. Likewise, fresh command/policy genesis does not prove template/config or branding source genesis. Any explicitly empty family must originate in the actual fresh source-creation transaction, remain bound to that source's subsequent writer/commit history and survive exact durable readback; retained or unqualified source records cannot receive an inferred empty baseline. +The bounded branding source construction uses its distinct `BRANDING` family and closed `RESOURCE`, `LOGO`, `FAVICON`, and `THEME` roles. Every synchronized snapshot explicitly declares each role `PRESENT` or `EMPTY`; these declarations derive only from the family's actual fresh-Version genesis and subsequent exact bound writer history. V59 does not backfill retained Versions. A missing branding genesis, source head, selected-commit snapshot, original revision, exact tenant-qualified asset row or actual-byte digest denies branding readback and new complete publication. Exact historical source reads for pre-V59 commits retain the original known components and return branding as explicitly unknown, provided no branding genesis or revision exists; they do not infer an empty family or authorize a new complete capture. UPSERT and DELETE revisions retain the complete original Draft binding; present references preserve their creating revision across later sibling commits. All present branding references are `REQUIRED`; `OPTIONAL` denies until an approved consumer fallback has an implemented owner proof. Branding history retains and protects its selected `game_assets.data` bytes without relabeling ordinary asset history or projecting branding into the ordinary `version_asset` export selection. The existing Account-authorized source commit coordinator composes the family into its exact local owner result. This construction is unregistered and does not provide total inventory, template-config completeness, immutable export, runtime delivery or activation. + Game Design verifies the independent [World inventory](../world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) through common exact selection/source-graph and publication bindings. World cannot attest Game Design assets, and Game Design cannot replace World requiredness with its own missing manifest entry. The two records must not depend on circular mutual receipt issuance. If a release requires `world.navmesh` or `world.pathGraph`, the corresponding actual-byte artifact digest and manifest entry remain mandatory; an unavailable producer denies publication. This contract is not evidence that the complete source writer, inventory producer, immutable export or authenticated read has executed; those gaps remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). Illustrative `GetPublishedReleaseBundle` fragment: diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 9c0e698966..c0b4837ac2 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -17,9 +17,9 @@ creators can quickly spin up new projects without starting from scratch. - The launch plugin-selection presence modes remain target-only and unimplemented: a presence-capable selection wrapper/mode, fresh omission or explicit empty resolving to the same immutable empty selection, rollback omission reusing a named target, rollback explicit empty, and explicit non-empty selection are not yet represented in proto/generated clients, launch-descriptor persistence/response, the request digest, service logic, or focused proof. Launch-resolution APIs are live, but the current implementation does not yet persist, expose, or prove the complete `enabledPluginVersions[]` set for deterministic retry and rollback. The detailed target contract remains below. - Current script-patch resolution is not yet the target launch predicate: a full-version template/request can persist an arbitrary patch ID without proving a same-base `PUBLISHED` Game Design publication or Automation `READY` status. These are implementation gaps; the target validation and fail-before-instance-row rules remain below. - The target tenant-scoped `GetTemplateReferencePhase` cutover read is not implemented in the current proto or service. Current launch resolution checks only the per-template `templateReferencePhase` field (`ENFORCED`/`LEGACY`); it does not expose or consume the target durable tenant phase (`BACKFILLING`/`VALIDATED`/`ENFORCED`) required by launch and retirement tooling. -- Normalized `game_template_*_ref` storage and its lifecycle/query authority are target-only. The current implementation persists `game_templates` and revision rows, but has no normalized reference tables, create/update derivation and atomic synchronization, one-time backfill/validation marker, or retirement/reference-query tooling; current lifecycle checks cannot rely on those rows and remain unimplemented or unproven. -- Closed selected-commit config production and reference readback are also absent. World authored-template IDs have the canonical UUID shape, but Game Design has no config writer/inventory that binds those references to an exact selected commit. Entity's current reference validator recognizes only `ITEM` and `NPC` and resolves a legacy positive-decimal key; it does not implement the canonical UUID read boundary or exact equippable-item semantics proof. Equipment-oriented input is an `ITEM` reference, not an independent equipment identity. Automation currently keys scripts by exact name plus raw patch string and base row, with no canonical UUID bridge for the selected base; Automation does not own a `RULESET` family. Game Logic's exact selected-source receipt is not yet retained/read back under the approved owner contract. No non-authoritative settings members are registered, and current runtime flags remain authoritative. Until Game Design durably retains owner-qualified selected-commit evidence for these sources, nonempty unsupported references and legacy opaque config deny publication; missing producers/readback do not prove empty families. -- The current REST `POST /templates` path is named and documented as create-only, but a caller-supplied `id` is accepted by the DTO and makes the repository update the row by global `id` while also writing the supplied `tenantId`; the subsequent tenant-filtered readback can then hide the changed row. This is a current cross-tenant reassignment/overwrite gap, not tenant-scoped update safety. The target contract must reject `id` on create and make any future update and readback exact-tenant-qualified while keeping the stored tenant binding immutable; focused cross-tenant denial proof is absent. +- The target `game_template_*_ref` projections and tenant-wide lifecycle/query authority remain unimplemented. The unregistered source writer's normalized base/gameplay references are local selected-commit evidence, not the tenant cutover marker, complete external-owner projections, or retirement/reference-query tooling; lifecycle consumers cannot treat them as that broader proof. +- The unregistered selected-source construction adds closed config history, actual generated template-row provenance, normalized base/gameplay references and immutable snapshots. It is not total template or release completeness: nonempty World, Entity and Automation references remain denied without genuine exact owner readback, and publication still lacks the separate derived Game Logic receipt join. Newly qualified rows remain non-launchable; legacy opaque/unqualified config is not mapped or backfilled. See the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) for construction and proof limits. +- REST `POST /templates` rejects a caller-supplied `id` before mapping or persistence. The repository save update path matches both `id` and `tenant_id`, leaves the tenant binding unchanged, and denies a tenant mismatch before tenant-qualified readback. Focused unit definitions cover create rejection and tenant-qualified update; production PostgreSQL proof remains open. This identity fix does not establish template configuration source completeness or the separate producer/readback gaps described above. - Current template-remap-set APIs persist tenant-scoped `DRAFT`/`APPROVED` sets and entries. When `ResolveLaunchDescriptor` receives a `sourceVersionId` that differs from the resolved target, it selects exactly one `APPROVED` set for the source/target pair and persists and returns that set's `remapSetId`; it does not collect or verify owning-domain attestations. The target attestation predicate remains below. ## Starter Experience Profiles @@ -53,17 +53,17 @@ This guarded planning and application is target-state behavior. The current `Sav After a successful upgrade, the exact profile baseline advances to `N`, while retained local differences, explicit deletions, detachments, mappings, and resolution outcomes remain recorded for the next upgrade. This makes repeated upgrades deterministic without turning the profile into an authoring or runtime inheritance layer. -`GameTemplateDto` includes `id`, `tenantId`, `name`, an optional `description`, the raw `config` JSON and a `createdAt` timestamp. On a normal create with `id` omitted, the database assigns the ID when the template is saved. The current DTO/service path also accepts a caller-supplied `id` and can update a row by that global ID while changing its claimed tenant; this is the cross-tenant overwrite/reassignment gap recorded in [Implementation Status](#implementation-status), not supported create behavior. The target create contract rejects `id`, and future updates/readbacks must use exact tenant-qualified identity while keeping the stored tenant binding immutable. The `config` field follows the closed schema below; arbitrary JSON is not a supported compatibility form. +`GameTemplateDto` includes `id`, `tenantId`, `name`, an optional `description`, the raw `config` JSON and a `createdAt` timestamp. On a normal create with `id` omitted, the database assigns the ID when the template is saved. The service rejects a caller-supplied `id` before mapping or persistence. The repository save update path matches both `id` and `tenant_id`, leaves the stored tenant binding unchanged, and denies a tenant mismatch before exact-tenant readback. Focused unit definitions cover these identity behaviors; production PostgreSQL proof remains open. The `config` field follows the closed schema below; arbitrary JSON is not a supported compatibility form. ### Closed, Versioned Configuration and References (Target State) -`GameTemplateDto.config` is a closed, versioned wiring document, not an extensible JSON bag. Schema version 1 binds one `baseVersionId`, `world.regions[]`, `world.rooms[]`, `entity.items[]`, `entity.npcs[]`, a distinct `gameLogic` section, `automation.scripts[]`, `automation.scriptPatch` (explicitly present or absent), and `supportedSettings[]`. These are distinct owner families: Game Logic owns gameplay rules/configuration and selected-source evidence; Automation owns authored scripts, event bindings, and script patches. There is no `RULESET` collection or independent Entity `EQUIPMENT` identity. Each supported collection is explicit, including when empty; an omitted collection, unknown field or kind, unqualified reference, or retained opaque/unversioned config is invalid for selected-release completeness. A missing or malformed value is never interpreted as an empty collection. Existing retained config is not guessed, backfilled as empty, or reinterpreted at runtime; it remains denied for publication until an authorized versioned writer produces and durably reads back the closed representation. +`GameTemplateDto.config` is a closed, versioned wiring document, not an extensible JSON bag. Schema version 1 binds one `baseVersionId`, `world.regions[]`, `world.rooms[]`, `entity.items[]`, `entity.npcs[]`, a distinct `gameLogic` section, `automation.scripts[]`, `automation.scriptPatch` (explicitly present or absent), and `supportedSettings[]`. These are distinct owner families: Game Logic owns gameplay rules/configuration and selected-source evidence; Automation owns authored scripts, event bindings, and script patches. The authored `gameLogic` configuration binds exact Game Design-owned gameplay input identities and revisions. It does not contain Game Logic's derived receipt, a final-commit digest, or a complete Draft commit binding computed from that same commit; those would make the authored request preimage recursive. After the Game Design source operation settles, publication joins Game Logic's independently authorized and durably retained receipt for the exact unchanged tenant/version/selected commit as separate evidence outside that authored preimage. There is no `RULESET` collection or independent Entity `EQUIPMENT` identity. Each supported collection is explicit, including when empty; an omitted collection, unknown field or kind, unqualified reference, or retained opaque/unversioned config is invalid for selected-release completeness. A missing or malformed value is never interpreted as an empty collection. Existing retained config is not guessed, backfilled as empty, or reinterpreted at runtime; it remains denied for publication until an authorized versioned writer produces and durably reads back the closed representation. World `regions[]` entries carry `regionTemplateId`; `rooms[]` carry `roomTemplateId`. Entity `items[]` and `npcs[]` entries carry `entityTemplateId`, containing only the owner's canonical authored-template UUID. References resolve only inside exact `(tenantId, baseVersionId)`; the selected version is identity scope, not a translation key. World references distinguish `REGION` and `ROOM`; the current Entity reference validator/read path supports only `ITEM` and `NPC` through legacy numeric keys, not the canonical UUID producer/readback boundary. An equipment-oriented template input is the same canonical `ITEM` reference, accepted as equipment-capable only when Entity's owner read validates the item definition's equippable semantics. Equipment compatibility/slot data remains on the authored item/schema, while equipped runtime state is a separate first-class Entity binding that references the item. No separate equipment template ID, item alias, or loadout identity is introduced. The [Entity runtime/data contract](../entity-management-service/runtime-and-data.md) and [Item & Equipment Balancing owner](./item-equipment-balancing.md#target-equipment-schema-requirements) define these distinctions; equipment-related data and bindings still need complete owner proof/digest coverage. Automation's supported template sources are `SCRIPT` (including its owner-managed event bindings) and `SCRIPT_PATCH`; it has no `RULESET` identity. A script reference carries the current exact owner key `scriptId` (the persisted `name` string) under the template's selected tenant/base-version scope. The optional pinned `scriptPatchVersion` is the exact persisted nonblank patch string, paired with the same `baseVersionId`; it is not a UUID. These raw strings describe current owner keys, not proof of same-base publication or exact selected-version readback. The [Automation runtime/data contract](../automation-scripting-service/runtime-and-data.md) and [API contract](../automation-scripting-service/api-contracts.md) own script identity and patch semantics. Current code does not establish the canonical-UUID-to-owner-version binding or all required publication/readiness predicates; unsupported or unreadable entries deny selected-release completeness rather than implying an empty script family. -Game Logic owns the version-scoped gameplay rules/configuration, not Automation. The separate `gameLogic` section may select only Game Logic's genuine owner-retained canonical configuration/source receipt for the exact tenant, `baseVersionId`, and selected commit, under the approved Game Logic producer contract. The receipt is the complete owner evidence, not a set of invented per-rule IDs, a `latest` lookup, or a substitute digest from Automation or Game Design. [Game Logic runtime/data](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) defines the owner boundary. The current producer/readback does not establish that receipt, so Game Logic input cannot yet be represented as complete or empty in a publishable config; its wire receipt shape must come from the actual owner contract rather than being fabricated here. +Game Logic owns the version-scoped gameplay rules/configuration, not Automation. The authored `gameLogic.inputs[]` entries select Game Design-owned gameplay inputs by exact `{family, key, revisionId}` from the supported authored gameplay source families. They do not serialize Game Logic's derived receipt or invent per-rule IDs. For publication, Game Logic's genuine owner-retained receipt must be independently joined to the exact unchanged tenant, `baseVersionId`, and selected commit after source settlement and authorized intake. A missing receipt, changed input or commit, or merely latest receipt cannot satisfy the join; exact retries recover the original retained result. [Game Logic runtime/data](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) defines the owner boundary and receipt semantics; this document does not define a receipt schema. Retaining and resolving authored input references does not establish that separate receipt or join, so no complete publishable config is claimed yet. `supportedSettings` is the explicitly non-authoritative settings subset accepted by this schema; it is closed and owner-defined, not arbitrary runtime configuration. No concrete non-authoritative setting members are currently registered. An explicitly authored empty collection is representable, but still requires the same authorized source-creation, selected-commit history and durable readback proof; missing settings storage or producers cannot supply it. `defaultRuntimeFlagsJson` and any other setting that changes launch/runtime behavior are authoritative inputs, not presentation settings, and must not be placed in this subset or marked optional. Adding a supported setting requires its owner, exact accepted member/value schema, and absence/fallback semantics to be defined before it can be authored. @@ -87,7 +87,7 @@ The target Game Design implementation stores normalized reference rows alongside - `game_template_world_ref` keyed by `(tenantId, gameTemplateId, baseVersionId, kind, ownerTemplateId)` for explicit `REGION` and `ROOM` references. - `game_template_entity_ref` keyed by `(tenantId, gameTemplateId, baseVersionId, kind, entityTemplateId)` for explicit `ITEM` and `NPC` references. Equipment-oriented configuration uses the same `ITEM` identity and requires owner-validated equippable semantics; runtime equipment bindings are separate Entity data. - An Automation reference projection for `SCRIPT`/event-binding and `SCRIPT_PATCH` owner keys only; use Automation's exact identity contract rather than a generic or fabricated ID format. -- Game Logic's exact selected-source receipt retained under its owner-defined contract; do not define a per-rule identity, substitute another participant digest, or infer a receipt/table shape before that producer contract exists. +- Game Logic's exact selected-source receipt retained under its owner-defined contract and joined to the unchanged selected tenant/version/commit during publication; it is derived evidence outside the authored config preimage. Do not define a per-rule identity, substitute another participant digest, or infer a receipt/table shape before that producer contract exists. - `game_template_script_patch_ref` keyed by `(tenantId, gameTemplateId, baseVersionId, scriptPatchVersion)` when a template pins a default patch, with the declared base required to equal the one template base. - `game_template_supported_setting` (or an equivalent closed projection) for registered non-authoritative settings only; no runtime-authoritative flags are admitted here. @@ -100,7 +100,7 @@ Launchable game templates must resolve to exactly one base design bundle version The runtime architecture owns the complete resolved tuple and admission predicate. Game Design owns the normalized template-reference invariant that supplies the tuple's base-version input; this section does not define a second runtime release-selection policy. - `game_template_version_ref` is not advisory metadata; it identifies the single canonical `versionId` used to resolve the launch descriptor for that template. -- Every normalized World/Entity/Automation reference and any selected Game Logic source receipt for the template must bind to that same `versionId`. +- Every normalized World/Entity/Automation reference and the separately joined Game Logic source receipt for the template must bind to that same `versionId`; the receipt is not an authored config member. - Mixed-version template composition is not allowed for launchable templates. A template update that would produce reference rows spanning multiple base `versionId` values must fail validation rather than relying on runtime resolution heuristics. - `game_template_script_patch_ref` is the only supported patch-level override and must reference the same `baseVersionId` as the template’s canonical `game_template_version_ref`. - If future workflows need cross-version migration planning, they must represent that as an explicit control-plane migration artifact, not as a launchable template with mixed-version dependencies. @@ -390,7 +390,7 @@ Game templates participate in the same version lifecycle as the domain templates ## Creating Templates -The current REST endpoint is a local/internal implementation seam, not an approved official-hosted or general operator provisioning workflow. External exposure of `POST /templates` must remain unavailable until the hosted-content gate, tenant-safe create/readback behavior, and focused proof are implemented. The request must omit `id`; although the database assigns it for a normal create, the current DTO/service path accepts a caller-supplied id and can overwrite a row under the wrong tenant before tenant-filtered readback hides the result. Do not use this current seam for external or production template provisioning. +The current REST endpoint is a local/internal implementation seam, not an approved official-hosted or general operator provisioning workflow. External exposure of `POST /templates` must remain unavailable until the hosted-content gate and focused production proof are complete. The request must omit `id`; the service rejects a supplied id before persistence, and repository updates require exact tenant/id identity while preserving the stored tenant binding. Focused unit definitions cover these behaviors; production PostgreSQL proof remains open. Do not use this current seam for external or production template provisioning. For local or otherwise explicitly isolated development use, creators can submit a `GameTemplateDto` via the REST API: diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 86db196cda..98cf6875fa 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -138,6 +138,8 @@ The shared golden vectors are `FULL_VERSION` `{tenantId=tenant-alpha, versionId= Game Logic's retained selected-release manifest and source-operation provenance remain unproved. Its digest receiver therefore rejects full-version requests without returning a participant digest, and Game Design fails the required participant gate rather than accepting the former fixed empty `ownedDraftRuleRows` hash and synthetic `version:` applied commit. Game Design remains the authoring and revision-history owner for authored gameplay rule inputs; its source operation must hand Game Logic the complete selected tenant/version/commit input set with current authority and operation-bound mutation authorization. Game Logic validates and immutably retains that evidence, then owns its participant and dedicated ability-schema attestations. The target ownership and input boundary are defined in the [Game Logic Draft Digest Contract](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) and the authoring shapes in [Ability & Action Design Tools](./ability-action-tools.md); this handoff is not current producer or intake proof. Full-version publication remains unavailable until Game Logic can attest under that contract; script-patch publication does not require the Game Logic participant. +The authored gameplay configuration binds exact Game Design-owned input identities and revisions. It excludes Game Logic's final receipt, a final-commit digest, and any complete Draft commit binding derived from that same commit, so canonicalizing the authored request does not depend on its own result. After the original Game Design source operation settles and Game Logic's distinct intake authorization and immutable retention succeed, the full-version publication gate must join the genuine Game Logic evidence for the exact unchanged `(tenantId, versionId, commitId)`. That derived join and retained receipt are outside the authored request preimage. A changed authored input or selected commit, a missing receipt, or evidence for a different/latest commit fails closed; an exact retry returns the original retained result and cannot substitute another commit. The owner-defined receipt and intake fields remain governed by the [Game Logic Draft Digest Contract](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake), not duplicated here. The nonrecursive canonicalization, changed-input/commit denial, missing-receipt denial, and exact-retry proof are not implemented; this contract does not claim those producer, join, or proof boundaries are live. + #### Launch and attestation read authorization (target state) Launch and release-attestation reads are owner-to-owner control-plane APIs, not a generic internal-service read class. Each RPC must have an explicit authenticated workload allowlist and bind the caller's authorized tenant/scope to the request before reading data; a bearer that merely declares `isInternalService` is insufficient. The target launch/read allowlist is: `ResolveLaunchDescriptor` — Game Session only; `GetTemplateReferencePhase` — Game Session for launch preflight and the explicitly named Game Design/retirement-control-plane workload for cutover tooling; `GetPublishedReleaseBundle` — Game Session, World Management, and Automation & Scripting; `GetVersionState` and `GetVersionAssetArtifactState` — Game Session and World Management for launch/activation reads. `GetVersionAssetArtifactState` also has a separate operator-diagnostic use: Logging & Admin may broker an authenticated read for operators, and CI/runbook automation may use only a dedicated named operator-read workload identity (or the Logging & Admin operator surface), never a generic internal-service bearer. That operator path is diagnostic evidence and does not grant launch or mutation authority. Each request must exact-bind its tenant and version/template/request scope (including source/target versions where present), and the owner must reject a wrong workload, cross-tenant scope, omitted scope, or changed replay identity before returning a descriptor, attestation, lifecycle state, or artifact state. Focused proof must exercise every allowlisted caller and a denied internal workload plus cross-tenant requests for each RPC, including the separate operator-read path where it is implemented. 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 9c99a9395b..2ddee9e53d 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 @@ -8,7 +8,13 @@ This is a non-normative implementation tracker for game authoring, publishing, a The selected-release inventory contract is explicit in the [World owner](../../architecture/microservices/world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) and [Game Design asset owner](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). Construction includes World's immutable selected-graph inventory and authenticated read, plus Game Design's mandatory v2 retention of that inventory in the complete original publication operation. The unregistered first-admission path obtains authenticated Account, freeze, inventory and selector evidence outside SQL; local durable retries reuse their original bytes without those RPCs. Additive owner guards reject incomplete v1 inputs for new operations, captures, terminal outcomes and settlement; retained history is not rewritten. This is not a genuine complete producer-to-release-to-settlement handoff or activation. -Game Design's synchronized source repository covers commands, realm policy and ordinary `ASSET_REFERENCE` source history, with actual fresh-Version genesis, coordinator application, immutable selected-commit snapshots and export agreement. The V57 construction adds the closed `GAMEPLAY_RULE` authored family, exact original revisions, complete typed catalogs and immutable synchronized source snapshots. The new unregistered original-order producer and local source-commit composition connect Account's current creator transaction to the complete Game Design-only coordinator, source-aware fence and exact terminal readback; public creator ingress, deployed environment authority and physical composed proof remain pending. Generic `SaveRevision` cannot stand in for that producer: it rejects new `GAMEPLAY_RULE` writes, and retained generic rule rows deny source completeness without guessed reconciliation. Total Game Design source completeness remains unimplemented: V37 mappings and nullable usage classifiers do not enumerate selected template/branding references or launch requiredness, and mutable template configuration is not selected-commit evidence. The [closed config contract](../../architecture/microservices/game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state) still needs its actual authorized versioned writers, normalized references, owner-qualified readback and inventory integration. Game Logic intake and exact Account settlement now have bounded unregistered components, not completed composed handoffs. Exact requiredness authority, manifest/export attestation, registered ingress and composed proof remain open. Fresh source genesis, absent mappings or absent consumers cannot establish empty families. All four genuine Gameplay handoffs and runtime activation remain open obligations. +Game Design's published synchronized source repository covers commands, realm policy, ordinary `ASSET_REFERENCE` and closed `GAMEPLAY_RULE` history, with actual fresh-Version genesis, coordinator application, immutable selected-commit snapshots and exact readback. The unregistered original-order producer connects Account's current creator transaction to the Game Design-only coordinator, source-aware fence and terminal readback; public creator ingress, deployed environment authority and physical composed proof remain pending. Generic `SaveRevision` cannot substitute for that producer, and retained generic rule rows remain denied rather than guessed into complete inventory. + +The current source-completeness construction adds the separate branding writer, required asset-byte qualification, original history and selected snapshots/captures under V59. The V60 template-config writer uses actual generated template rows with original operation/revision provenance, normalized authored references and immutable readback, not legacy row-ID or tenant-key inference. Its closed input contract remains owned by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state). Nonempty World, Entity and Automation references stay denied until their genuine selected-base owner reads exist. Game Design-authored gameplay references are separate from Game Logic's derived receipt; the exact immutable publication join remains unimplemented. Newly qualified templates remain non-launchable, not proof of tenant reference cutover. Retained original terminals preserve their known bytes; absent new-family genesis remains unknown and cannot supply an empty family or fresh complete publication capture. An explicit-target legacy template cannot be silently omitted from new completeness evidence: deferred row guards require genuine CREATE qualification, and new snapshot/freeze inventory checks deny unresolved rows while preserving qualified DELETE tombstones. + +The composed V59/V60 local gate R183 passed Game Design schema generation, full service checks, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown: 416 unit cases executed with no failures, errors or skips. All 120 PostgreSQL definitions compiled but skipped without Docker, including three branding and six template-config cases. Two preceding runs failed only on new fixture compilation: package-private coordinator proof access and a checked fixture exception; production visibility was not widened. A separate legacy descriptor-retry fixture now models retained historical default drift without inventing new source qualification, preserving its original replay assertions. These results are not physical migration, source/freeze, authenticated producer-to-release or activation proof. + +Total cross-owner source completeness, immutable manifest/export attestation, registered ingress and composed proof remain open. Game Logic intake and exact Account settlement have bounded unregistered components, not completed handoffs. Neither fresh source genesis nor absent mappings/consumers establishes empty unavailable families. All four genuine Gameplay handoffs and runtime activation remain open obligations. Published-head `64c3d8db0ae1b302f8ae7e48e991d5b2ceb39fc6` [Validation run 37868588598](https://github.com/benhook1013/FireMUD/actions/runs/37868588598) completed red. Physical reports record 248 Account integration cases with two failures, 99 Game Design with one, seven Game Logic with two, and 206 World with 55; all executed with zero skips. Game Logic's XML capture step skipped, so its counts come from the uploaded HTML report. The four services' 1085, 399, 101 and 556 unit cases passed. Five previously failing Account selected-publication settlement cases now pass against V110, as does the separate three-case mTLS settlement suite. Game Design's six typed-source/handoff guard cases and World's 18 authored-source intake cases pass. This is not complete producer-to-release proof. The synthetic checkout is merge `793426c02775085d53aef7ef250da234f5b1b546`, tree `33d43a8217513e01237a0e36b7f14ebf82f09584`, with parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head; its first parent differs from the run's recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`. Intended-parent alignment, fresh-image boot, preview and Smoke proof remain open. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java index 1d18214398..1257d52680 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java @@ -154,7 +154,9 @@ public static List mutations(DraftCommitBinding binding) { String kind = text(payload, "revisionKind"); if ("COMMAND_DEFINITION".equals(kind) || "REALM_ENTRY_POLICY".equals(kind) - || GameplayRuleSource.REVISION_KIND.equals(kind)) continue; + || TemplateConfigSource.REVISION_KIND.equals(kind) + || GameplayRuleSource.REVISION_KIND.equals(kind) + || BrandingSource.REVISION_KIND.equals(kind)) continue; if (!REVISION_KIND.equals(kind)) { throw new IllegalArgumentException("Unsupported Game Design asset source revision kind"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSource.java new file mode 100644 index 0000000000..93d948c425 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSource.java @@ -0,0 +1,345 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed branding asset-reference source operations for the existing Draft coordinator. This codec + * does not qualify asset rows, authenticate an operation, establish genesis or attest completeness. + */ +public final class BrandingSource { + public static final String SCOPE = "BRANDING_ASSET_REFERENCE_SET"; + public static final String SCOPE_ID = "effective"; + public static final String REVISION_KIND = "BRANDING_ASSET_REFERENCE"; + public static final String FAMILY = "BRANDING"; + + public enum Role { + RESOURCE, + LOGO, + FAVICON, + THEME + } + + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private BrandingSource() {} + + public static Map emptyRoleDeclarations() { + return Map.of("RESOURCE", "EMPTY", "LOGO", "EMPTY", "FAVICON", "EMPTY", "THEME", "EMPTY"); + } + + public enum OperationKind { + UPSERT, + DELETE + } + + public enum Requiredness { + REQUIRED, + OPTIONAL + } + + /** The complete original binding retains request, target, commit and exact payload identity. */ + public record Mutation( + DraftCommitBinding binding, + String revisionOrder, + UUID revisionId, + OperationKind operation, + String usageKey, + String assetRowId, + Role role, + Requiredness requiredness) { + public Mutation { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(operation, "operation"); + requireUsageKey(usageKey); + Objects.requireNonNull(role, "role"); + var revision = + binding.revisions().stream() + .filter(value -> value.revisionId().equals(revisionId)) + .filter(value -> value.revisionOrder().equals(revisionOrder)) + .filter(value -> value.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .findFirst() + .orElseThrow( + () -> new IllegalArgumentException("Asset revision is not in its exact binding")); + String expectedPayload; + if (operation == OperationKind.UPSERT) { + expectedPayload = upsertPayload(assetRowId, usageKey, role, requiredness); + } else { + if (assetRowId != null || requiredness != null) { + throw new IllegalArgumentException("Asset DELETE cannot carry UPSERT fields"); + } + expectedPayload = deletePayload(usageKey, role); + } + // Parse before canonicalization so duplicate fields or trailing JSON can never collapse. + JsonNode actual = tree(revision.payload()); + if (!actual.path("schemaVersion").isInt() || actual.path("schemaVersion").intValue() != 1) { + throw new IllegalArgumentException("Unsupported asset source schemaVersion"); + } + fields( + actual, + operation == OperationKind.UPSERT + ? Set.of( + "schemaVersion", + "revisionKind", + "family", + "role", + "operation", + "assetRowId", + "usageKey", + "requiredness") + : Set.of("schemaVersion", "revisionKind", "family", "role", "operation", "usageKey")); + if (!canonical(actual).equals(expectedPayload)) { + throw new IllegalArgumentException("Asset mutation differs from the exact bound revision"); + } + } + } + + /** Exact creating source provenance; numeric asset row identity is internal to Game Design. */ + public record Reference( + String usageKey, + String assetRowId, + Role role, + Requiredness requiredness, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId) { + public Reference { + // A reference cannot rewrite the requiredness or asset identity of its creating UPSERT. + new Mutation( + sourceBinding, + revisionOrder, + revisionId, + OperationKind.UPSERT, + usageKey, + assetRowId, + role, + requiredness); + } + + public String family() { + return FAMILY; + } + } + + /** Typed source snapshot only; presence or an empty list is not COMPLETE evidence. */ + public record Snapshot(DraftCommitBinding binding, List references) { + public Snapshot { + Objects.requireNonNull(binding, "binding"); + references = List.copyOf(Objects.requireNonNull(references, "references")); + requireDistinctReferences(references); + for (Reference reference : references) { + if (!binding.target().equals(reference.sourceBinding().target())) { + throw new IllegalArgumentException("Asset reference belongs to another source target"); + } + } + } + } + + public static List mutations(DraftCommitBinding binding) { + Objects.requireNonNull(binding, "binding"); + List result = new ArrayList<>(); + for (var revision : binding.revisions()) { + if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; + JsonNode payload = tree(revision.payload()); + String kind = text(payload, "revisionKind"); + if ("COMMAND_DEFINITION".equals(kind) + || "REALM_ENTRY_POLICY".equals(kind) + || TemplateConfigSource.REVISION_KIND.equals(kind) + || GameplayRuleSource.REVISION_KIND.equals(kind) + || AssetSource.REVISION_KIND.equals(kind)) continue; + if (!REVISION_KIND.equals(kind)) { + throw new IllegalArgumentException("Unsupported Game Design asset source revision kind"); + } + if (!payload.path("schemaVersion").isInt() || payload.path("schemaVersion").intValue() != 1) { + throw new IllegalArgumentException("Unsupported asset source schemaVersion"); + } + OperationKind operation = OperationKind.valueOf(text(payload, "operation")); + result.add( + new Mutation( + binding, + revision.revisionOrder(), + revision.revisionId(), + operation, + text(payload, "usageKey"), + operation == OperationKind.UPSERT ? text(payload, "assetRowId") : null, + Role.valueOf(text(payload, "role")), + operation == OperationKind.UPSERT + ? Requiredness.valueOf(text(payload, "requiredness")) + : null)); + } + return List.copyOf(result); + } + + public static String upsertPayload( + String assetRowId, String usageKey, Role role, Requiredness requiredness) { + requireAssetRowId(assetRowId); + Objects.requireNonNull(role, "role"); + requireUsageKey(usageKey); + if (requiredness != Requiredness.REQUIRED) { + throw new IllegalArgumentException("Branding RESOURCE requires REQUIRED owner policy"); + } + return canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + REVISION_KIND, + "family", + FAMILY, + "role", + role.name(), + "operation", + "UPSERT", + "assetRowId", + assetRowId, + "usageKey", + usageKey, + "requiredness", + requiredness.name())); + } + + public static String deletePayload(String usageKey, Role role) { + Objects.requireNonNull(role, "role"); + requireUsageKey(usageKey); + return canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + REVISION_KIND, + "family", + FAMILY, + "role", + role.name(), + "operation", + "DELETE", + "usageKey", + usageKey)); + } + + /** Applies only explicit ordered operations, preserving provenance on untouched references. */ + public static Snapshot replay(List inherited, DraftCommitBinding binding) { + var baseline = new Snapshot(binding, inherited); + Map effective = new HashMap<>(); + for (Reference reference : baseline.references()) + effective.put(reference.usageKey(), reference); + for (Mutation mutation : mutations(binding)) { + if (mutation.operation() == OperationKind.DELETE) { + effective.remove(mutation.usageKey()); + } else { + Reference reference = + new Reference( + mutation.usageKey(), + mutation.assetRowId(), + mutation.role(), + mutation.requiredness(), + binding, + mutation.revisionOrder(), + mutation.revisionId()); + for (Reference current : effective.values()) { + if (current.assetRowId().equals(reference.assetRowId()) + && !current.usageKey().equals(reference.usageKey())) { + throw new IllegalArgumentException( + "One asset source cannot acquire multiple usage aliases"); + } + } + effective.put(reference.usageKey(), reference); + } + } + return new Snapshot( + binding, + effective.values().stream() + .sorted(Comparator.comparing(Reference::usageKey, BrandingSource::compareUtf8)) + .toList()); + } + + private static void requireDistinctReferences(List references) { + Set keys = new HashSet<>(); + Set assets = new HashSet<>(); + for (Reference reference : references) { + if (!keys.add(reference.usageKey()) || !assets.add(reference.assetRowId())) { + throw new IllegalArgumentException("Asset source repeats a usage key or source row"); + } + } + } + + private static void requireAssetRowId(String value) { + if (value == null || value.length() > 19 || !value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "assetRowId must be a positive canonical BIGINT decimal string"); + } + try { + Long.parseLong(value); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("assetRowId exceeds its owner BIGINT range", exception); + } + } + + private static void requireUsageKey(String value) { + if (value == null + || value.isBlank() + || value.codePointCount(0, value.length()) > 255 + || "manifest.json".equals(value)) { + throw new IllegalArgumentException( + "Asset usageKey must fit its exact nonblank owner filename"); + } + } + + private static String text(JsonNode value, String field) { + if (!value.isObject() || !value.path(field).isTextual()) { + throw new IllegalArgumentException("Asset source requires textual " + field); + } + return value.path(field).textValue(); + } + + private static void fields(JsonNode value, Set expected) { + if (!value.isObject() + || value.size() != expected.size() + || value.properties().stream().anyMatch(entry -> !expected.contains(entry.getKey()))) { + throw new IllegalArgumentException("Asset source members differ from the closed schema"); + } + } + + private static JsonNode tree(String value) { + try { + return JSON.readTree(value); + } catch (RuntimeException exception) { + throw new IllegalArgumentException("Malformed asset source JSON", exception); + } + } + + private static String canonical(Object value) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalArgumentException("Asset source canonicalization failed", exception); + } + } + + private static int compareUtf8(String left, String right) { + return java.util.Arrays.compareUnsigned( + left.getBytes(StandardCharsets.UTF_8), right.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java new file mode 100644 index 0000000000..d6244ccae3 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; + +/** Exact branding-source application evidence, composed into one control-plane owner result. */ +public record BrandingSourceApplication( + DraftCommitBinding binding, String expectedEpoch, BrandingSourceSnapshot snapshot) { + public BrandingSourceApplication { + Objects.requireNonNull(binding); + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || !binding.equals(snapshot.binding()) + || BrandingSource.mutations(binding).isEmpty() + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch())) + throw new IllegalArgumentException( + "Branding asset application must advance its exact bound epoch"); + } + + public AppliedEpoch appliedEpoch() { + return new AppliedEpoch( + BrandingSource.SCOPE, + binding.target().canonicalVersionId().toString(), + BrandingSource.SCOPE, + BrandingSource.SCOPE_ID, + expectedEpoch, + snapshot.sourceEpoch()); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-branding-asset-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java new file mode 100644 index 0000000000..c1914c7cb3 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java @@ -0,0 +1,519 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Actual branding source writes under the existing coordinator; never total inventory authority. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner-local injected persistence collaborator") +public final class BrandingSourceRepository { + private final DSLContext dsl; + private final DraftCommitCoordinatorRepository coordinator; + + public BrandingSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + } + + public BrandingSourceSnapshot.Genesis enrollFreshDraft(TargetProof target) { + write(); + lock(target); + var prior = readGenesis(target); + if (prior.isPresent()) return prior.orElseThrow(); + var witness = + dsl.fetchOne( + "SELECT creation_transaction_id FROM game_design_realm_policy_version_insert " + + "WHERE version_id = ? AND creation_transaction_id = pg_current_xact_id()::TEXT", + target.gameDesignVersionRowId()); + if (witness == null) + throw new IllegalStateException("BRANDING_SOURCE_FRESH_INSERT_UNAVAILABLE"); + var genesis = + new BrandingSourceSnapshot.Genesis(target, UUID.randomUUID(), witness.get(0, String.class)); + dsl.execute( + "INSERT INTO game_design_branding_source_genesis " + + "(canonical_tenant_id, canonical_version_id, version_id, receipt_id, creation_transaction_id, target_json, roles_json) VALUES (?, ?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + genesis.receiptId(), + genesis.creationTransactionId(), + CommandSource.canonical(CommandSource.targetObject(target)), + CommandSource.canonical(BrandingSource.emptyRoleDeclarations())); + dsl.execute( + "INSERT INTO game_design_branding_source_head " + + "(canonical_tenant_id, canonical_version_id, source_epoch, genesis_receipt_id) VALUES (?, ?, '0', ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + genesis.receiptId()); + if (!genesis.equals(readGenesis(target).orElseThrow())) + throw new IllegalStateException("BRANDING_SOURCE_GENESIS_READBACK_CONFLICT"); + return genesis; + } + + public Optional readGenesis(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_branding_source_genesis WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!CommandSource.canonical(CommandSource.targetObject(target)) + .equals(row.get("target_json", String.class)) + || target.gameDesignVersionRowId() != row.get("version_id", Long.class) + || !CommandSource.canonical(BrandingSource.emptyRoleDeclarations()) + .equals(row.get("roles_json", String.class))) + throw new IllegalStateException("BRANDING_SOURCE_GENESIS_TARGET_CONFLICT"); + return Optional.of( + new BrandingSourceSnapshot.Genesis( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class))); + } + + public Optional apply(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var mutations = BrandingSource.mutations(binding); + var prior = application(binding); + if (prior.isPresent()) return prior; + if (mutations.isEmpty()) return Optional.empty(); + open(binding.target()); + var slot = coordinator.readApplicationSlot(binding.target()).orElseThrow(); + var owner = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (!binding.requestId().equals(slot.requestId()) + || !binding.commitId().equals(slot.commitId()) + || owner == null + || (owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.IN_PROGRESS + && owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN)) + throw new IllegalStateException("BRANDING_SOURCE_COORDINATOR_APPLICATION_UNAVAILABLE"); + Record head = head(binding.target()); + var units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(BrandingSourceRepository::isScope) + .toList(); + String epoch = head.get("source_epoch", String.class); + if (units.size() != 1 + || !binding.target().canonicalVersionId().toString().equals(units.getFirst().aggregateId()) + || !epoch.equals(units.getFirst().expectedEpoch())) + throw new IllegalStateException("BRANDING_SOURCE_EPOCH_CONFLICT"); + UUID inherited = head.get("visible_commit_id", UUID.class); + requirePreviousFence(binding.target(), inherited); + List previous = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().items(); + if (inherited == null && !"0".equals(epoch)) + throw new IllegalStateException("BRANDING_SOURCE_GENESIS_NOT_CURRENT"); + // Lock all actual source rows in owner-key order before writing any revision history. + mutations.stream() + .filter(m -> m.operation() == BrandingSource.OperationKind.UPSERT) + .map(m -> Long.parseLong(m.assetRowId())) + .distinct() + .sorted() + .forEach( + id -> { + if (dsl.fetchOne( + "SELECT id FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", + binding.target().gameDesignVersionTenantKey(), + id) + == null) throw new IllegalStateException("BRANDING_SOURCE_ROW_UNAVAILABLE"); + }); + for (var mutation : mutations) { + BrandingSourceSnapshot.Item item = + mutation.operation() == BrandingSource.OperationKind.UPSERT + ? qualify( + new BrandingSource.Reference( + mutation.usageKey(), + mutation.assetRowId(), + mutation.role(), + mutation.requiredness(), + binding, + mutation.revisionOrder(), + mutation.revisionId()), + true) + : null; + dsl.execute( + "INSERT INTO game_design_branding_source_revision " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, operation_kind, usage_key, role, asset_id, requiredness, content_type, content_digest, byte_size) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + mutation.revisionId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.operation().name(), + mutation.usageKey(), + mutation.role().name(), + item == null ? null : Long.parseLong(mutation.assetRowId()), + item == null ? null : mutation.requiredness().name(), + item == null ? null : item.contentType(), + item == null ? null : item.contentDigest(), + item == null ? null : item.byteSize()); + } + var references = + BrandingSource.replay( + previous.stream().map(BrandingSourceSnapshot.Item::reference).toList(), binding) + .references(); + var snapshot = + new BrandingSourceSnapshot( + binding, + new BigInteger(epoch).add(BigInteger.ONE).toString(), + inherited, + head.get("genesis_receipt_id", UUID.class), + references.stream().map(r -> qualify(r, false)).toList()); + var result = new BrandingSourceApplication(binding, epoch, snapshot); + dsl.execute( + "INSERT INTO game_design_branding_source_application " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, expected_epoch, snapshot_json, result_bytes) VALUES (?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + epoch, + snapshot.canonicalJson(), + result.canonicalBytes()); + if (dsl.execute( + "UPDATE game_design_branding_source_head SET source_epoch = ?, applied_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID)", + snapshot.sourceEpoch(), + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + epoch, + inherited) + != 1) throw new IllegalStateException("BRANDING_SOURCE_EPOCH_CONFLICT"); + return Optional.of(application(binding).orElseThrow()); + } + + public BrandingSourceSnapshot captureSynchronized(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var prior = readSnapshot(binding.target(), binding.commitId()); + if (prior.isPresent()) { + if (!prior.orElseThrow().binding().equals(binding)) + throw new IllegalStateException("BRANDING_SOURCE_SNAPSHOT_BINDING_CONFLICT"); + return prior.orElseThrow(); + } + open(binding.target()); + requireFence(binding); + var head = head(binding.target()); + UUID inherited = head.get("visible_commit_id", UUID.class); + var applied = application(binding); + BrandingSourceSnapshot snapshot; + if (!BrandingSource.mutations(binding).isEmpty()) { + var result = + applied.orElseThrow( + () -> new IllegalStateException("BRANDING_SOURCE_APPLICATION_UNAVAILABLE")); + snapshot = result.snapshot(); + if (!Objects.equals(inherited, snapshot.inheritedCommitId())) + throw new IllegalStateException("BRANDING_SOURCE_PREDECESSOR_CHANGED"); + } else { + var items = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().items(); + snapshot = + new BrandingSourceSnapshot( + binding, + head.get("source_epoch", String.class), + inherited, + head.get("genesis_receipt_id", UUID.class), + items); + } + if (!snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("BRANDING_SOURCE_PARTIAL_WRITE_NOT_VISIBLE"); + dsl.execute( + "INSERT INTO game_design_branding_source_snapshot " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, snapshot_json, snapshot_digest) VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + snapshot.canonicalJson(), + snapshot.digest()); + dsl.execute( + "UPDATE game_design_branding_source_head SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + return readSnapshot(binding.target(), binding.commitId()).orElseThrow(); + } + + public Optional readSnapshot(TargetProof target, UUID commitId) { + var row = + dsl.fetchOne( + "SELECT snapshot_json, snapshot_digest FROM game_design_branding_source_snapshot WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId); + if (row == null) return Optional.empty(); + var snapshot = BrandingSourceSnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId) + || !snapshot.digest().equals(row.get("snapshot_digest", String.class))) + throw new IllegalStateException("BRANDING_SOURCE_SNAPSHOT_READBACK_CONFLICT"); + exact(snapshot.binding()); + var fence = + dsl.fetchOne( + "SELECT input_digest FROM game_design_draft_commit_visibility_fence WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.binding().requestId(), + commitId); + if (fence == null || !snapshot.binding().digest().equals(fence.get(0, String.class))) { + throw new IllegalStateException("BRANDING_SOURCE_SNAPSHOT_FENCE_CONFLICT"); + } + verifyItems(snapshot); + return Optional.of(snapshot); + } + + public BrandingSourceSnapshot.Capture freeze(GameDesignPublicationOperation operation) { + write(); + var selection = operation.account().input().selection(); + lock(selection.target()); + var prior = readCapture(operation); + if (prior.isPresent()) return prior.orElseThrow(); + var retained = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(); + GameDesignPublicationOperationRepository.exact(retained.operation(), operation); + if (!"PENDING".equals(retained.outcome())) + throw new IllegalStateException("BRANDING_SOURCE_OPERATION_SEALED"); + requireFence(selection.selectedCommit()); + var selected = + dsl.fetchOne( + "SELECT selection_json FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId()); + if (selected == null || !selection.canonicalJson().equals(selected.get(0, String.class))) + throw new IllegalStateException("BRANDING_SOURCE_SELECTION_CHANGED"); + var snapshot = + readSnapshot(selection.target(), selection.selectedCommit().commitId()).orElseThrow(); + var head = head(selection.target()); + if (!snapshot.binding().equals(selection.selectedCommit()) + || !snapshot.sourceEpoch().equals(head.get("source_epoch", String.class)) + || !snapshot.binding().commitId().equals(head.get("visible_commit_id", UUID.class))) + throw new IllegalStateException("BRANDING_SOURCE_NOT_SYNCHRONIZED"); + var capture = new BrandingSourceSnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_branding_source_capture (canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, operation_bytes, capture_bytes, capture_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + operation.workflowId(), + snapshot.binding().commitId(), + operation.canonicalBytes(), + capture.canonicalBytes(), + capture.digest()); + return readCapture(operation).orElseThrow(); + } + + public Optional readCapture( + GameDesignPublicationOperation operation) { + var target = operation.account().input().selection().target(); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_branding_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + var capture = + new BrandingSourceSnapshot.Capture( + operation, readSnapshot(target, row.get("commit_id", UUID.class)).orElseThrow()); + if (!operation.workflowId().equals(row.get("publish_workflow_id", String.class)) + || !Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class)) + || !capture.digest().equals(row.get("capture_digest", String.class))) + throw new IllegalStateException("BRANDING_SOURCE_CAPTURE_READBACK_CONFLICT"); + return Optional.of(capture); + } + + private Optional application(DraftCommitBinding binding) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_branding_source_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) return Optional.empty(); + var result = + new BrandingSourceApplication( + binding, + row.get("expected_epoch", String.class), + BrandingSourceSnapshot.fromStored(row.get("snapshot_json", String.class))); + if (!Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class)) + || !binding.requestId().equals(row.get("request_id", UUID.class))) + throw new IllegalStateException("BRANDING_SOURCE_APPLICATION_READBACK_CONFLICT"); + verifyItems(result.snapshot()); + return Optional.of(result); + } + + private BrandingSourceSnapshot.Item qualify(BrandingSource.Reference reference, boolean lock) { + var target = reference.sourceBinding().target(); + var row = + dsl.fetchOne( + "SELECT file_name, content_type, data FROM game_assets WHERE tenant_id = ? AND id = ?" + + (lock ? " FOR UPDATE" : ""), + target.gameDesignVersionTenantKey(), + Long.parseLong(reference.assetRowId())); + if (row == null + || !reference.usageKey().equals(row.get("file_name", String.class)) + || row.get("data", byte[].class) == null) + throw new IllegalStateException("BRANDING_SOURCE_EXACT_BYTES_UNAVAILABLE"); + byte[] bytes = row.get("data", byte[].class); + return new BrandingSourceSnapshot.Item( + reference, + row.get("content_type", String.class), + CommandSource.sha256(bytes), + bytes.length); + } + + private void verifyItems(BrandingSourceSnapshot snapshot) { + for (var item : snapshot.items()) { + if (!item.equals(qualify(item.reference(), false))) + throw new IllegalStateException("BRANDING_SOURCE_BYTE_READBACK_CONFLICT"); + var r = item.reference(); + var row = + dsl.fetchOne( + "SELECT content_digest, content_type, byte_size FROM game_design_branding_source_revision " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ? AND commit_id = ? AND request_id = ? AND revision_order = ? AND asset_id = ? AND usage_key = ? AND role = ? AND requiredness = ?", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + r.revisionId(), + r.sourceBinding().commitId(), + r.sourceBinding().requestId(), + Integer.parseInt(r.revisionOrder()), + Long.parseLong(r.assetRowId()), + r.usageKey(), + r.role().name(), + r.requiredness().name()); + if (row == null + || !item.contentDigest().equals(row.get("content_digest", String.class)) + || !item.contentType().equals(row.get("content_type", String.class)) + || item.byteSize() != row.get("byte_size", Long.class)) + throw new IllegalStateException("BRANDING_SOURCE_REVISION_READBACK_CONFLICT"); + } + } + + private Record head(TargetProof target) { + return readHead(target, true); + } + + private Record readHead(TargetProof target, boolean lock) { + readGenesis(target) + .orElseThrow(() -> new IllegalStateException("BRANDING_SOURCE_GENESIS_UNAVAILABLE")); + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_design_branding_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ?" + + (lock ? " FOR UPDATE" : ""), + target.canonicalTenantId(), + target.canonicalVersionId()), + "BRANDING_SOURCE_HEAD_UNAVAILABLE"); + } + + private void exact(DraftCommitBinding binding) { + if (!coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .binding() + .equals(binding)) throw new IllegalStateException("BRANDING_SOURCE_BINDING_CHANGED"); + } + + private void requirePreviousFence(TargetProof target, UUID inherited) { + var fence = coordinator.readVisibilityFence(target); + if (inherited == null + ? fence.isPresent() + : fence.isEmpty() || !inherited.equals(fence.orElseThrow().commitId())) + throw new IllegalStateException("BRANDING_SOURCE_PREVIOUS_FENCE_CHANGED"); + } + + private void requireFence(DraftCommitBinding binding) { + var fence = coordinator.readVisibilityFence(binding.target()).orElseThrow(); + if (!binding.commitId().equals(fence.commitId()) + || !binding.requestId().equals(fence.requestId()) + || !binding.digest().equals(fence.inputDigest()) + || coordinator.read(binding.target(), binding.requestId()).orElseThrow().workflowState() + != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED) + throw new IllegalStateException("BRANDING_SOURCE_SYNCHRONIZED_FENCE_UNAVAILABLE"); + } + + private void open(TargetProof target) { + if (dsl.fetchOne( + "SELECT id FROM version WHERE id = ? AND version_state = 'DRAFT' AND NOT is_script_only AND base_version_id IS NULL AND script_patch_version IS NULL", + target.gameDesignVersionRowId()) + == null + || dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null + || dsl.fetchOne( + "SELECT 1 FROM version_asset_export_snapshot WHERE tenant_id = ? AND version_id = ?", + target.gameDesignVersionTenantKey(), + target.gameDesignVersionRowId()) + != null) throw new IllegalStateException("BRANDING_SOURCE_FROZEN_OR_NOT_DRAFT"); + } + + private void lock(TargetProof target) { + var qualified = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByCanonicalTenantIdAndCanonicalVersionId( + target.canonicalTenantId(), target.canonicalVersionId()) + .orElseThrow(); + var version = + new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl) + .findByTenantIdAndIdForUpdate( + target.gameDesignVersionTenantKey(), target.gameDesignVersionRowId()) + .orElseThrow(); + var actual = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + if (!target.equals(actual) || !qualified.getId().equals(version.getId())) + throw new IllegalStateException("BRANDING_SOURCE_TARGET_CHANGED"); + } + + static boolean isScope(DraftCommitBinding.AffectedUnit unit) { + return BrandingSource.SCOPE.equals(unit.aggregateType()) + && BrandingSource.SCOPE.equals(unit.scopeType()) + && BrandingSource.SCOPE_ID.equals(unit.scopeId()); + } + + private static void write() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) + throw new IllegalStateException( + "Branding asset source requires writable READ_COMMITTED transaction"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java new file mode 100644 index 0000000000..a683ec1cd6 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java @@ -0,0 +1,219 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; + +/** Branding selected source only; no total inventory or template completeness claim. */ +public record BrandingSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List items) { + public BrandingSourceSnapshot { + Objects.requireNonNull(binding); + Objects.requireNonNull(genesisReceiptId); + if (!sourceEpoch.matches("0|[1-9][0-9]*") || new UUID(0, 0).equals(genesisReceiptId)) + throw new IllegalArgumentException("Exact branding asset source epoch and genesis required"); + items = List.copyOf(items); + new BrandingSource.Snapshot(binding, items.stream().map(Item::reference).toList()); + var ordered = + items.stream() + .sorted( + java.util.Comparator.comparing( + item -> item.reference().usageKey(), + (String left, String right) -> + java.util.Arrays.compareUnsigned( + left.getBytes(StandardCharsets.UTF_8), + right.getBytes(StandardCharsets.UTF_8)))) + .toList(); + if (!items.equals(ordered)) + throw new IllegalArgumentException("Branding asset items must be in canonical key order"); + } + + public record Item( + BrandingSource.Reference reference, String contentType, String contentDigest, long byteSize) { + public Item { + Objects.requireNonNull(reference); + if (contentType == null + || contentType.isBlank() + || contentType.codePointCount(0, contentType.length()) > 100 + || contentDigest == null + || !contentDigest.matches("sha256:[0-9a-f]{64}") + || byteSize < 0) + throw new IllegalArgumentException("Exact branding asset byte metadata required"); + } + + Map object() { + var r = reference; + return Map.ofEntries( + Map.entry("family", r.family()), + Map.entry("role", r.role().name()), + Map.entry("usageKey", r.usageKey()), + Map.entry("assetRowId", r.assetRowId()), + Map.entry("requiredness", r.requiredness().name()), + Map.entry("sourceBindingJson", r.sourceBinding().canonicalJson()), + Map.entry("sourceBindingDigest", r.sourceBinding().digest()), + Map.entry("revisionOrder", r.revisionOrder()), + Map.entry("revisionId", r.revisionId().toString()), + Map.entry("contentType", contentType), + Map.entry("contentDigest", contentDigest), + Map.entry("byteSize", Long.toString(byteSize))); + } + } + + public String canonicalJson() { + return CommandSource.canonical( + Map.of( + "schema", + "game-design-branding-asset-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptId", + genesisReceiptId.toString(), + "roles", + roleDeclarations(), + "items", + items.stream().map(Item::object).toList())); + } + + /** Every role is explicitly declared against actual genesis and selected writer history. */ + public Map roleDeclarations() { + var result = new java.util.TreeMap(); + for (var role : BrandingSource.Role.values()) + result.put( + role.name(), + items.stream().anyMatch(item -> item.reference().role() == role) ? "PRESENT" : "EMPTY"); + return Map.copyOf(result); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static BrandingSourceSnapshot fromStored(String json) { + var root = CommandSource.tree(json); + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "roles", + "items"); + if (!"game-design-branding-asset-source-snapshot/v1" + .equals(CommandSource.requiredStoredText(root, "schema")) + || !root.path("items").isArray()) + throw new IllegalArgumentException("Unsupported branding asset snapshot"); + var binding = + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(root, "bindingJson"), + CommandSource.requiredStoredText(root, "bindingDigest")); + var items = new java.util.ArrayList(); + for (var node : root.path("items")) { + CommandSource.requireStoredFields( + node, + "family", + "role", + "usageKey", + "assetRowId", + "requiredness", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId", + "contentType", + "contentDigest", + "byteSize"); + if (!BrandingSource.FAMILY.equals(CommandSource.requiredStoredText(node, "family"))) + throw new IllegalArgumentException("Unsupported branding source family or role"); + var reference = + new BrandingSource.Reference( + CommandSource.requiredStoredText(node, "usageKey"), + CommandSource.requiredStoredText(node, "assetRowId"), + BrandingSource.Role.valueOf(CommandSource.requiredStoredText(node, "role")), + BrandingSource.Requiredness.valueOf( + CommandSource.requiredStoredText(node, "requiredness")), + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(node, "sourceBindingJson"), + CommandSource.requiredStoredText(node, "sourceBindingDigest")), + CommandSource.requiredStoredText(node, "revisionOrder"), + UUID.fromString(CommandSource.requiredStoredText(node, "revisionId"))); + items.add( + new Item( + reference, + CommandSource.requiredStoredText(node, "contentType"), + CommandSource.requiredStoredText(node, "contentDigest"), + Long.parseLong(CommandSource.requiredStoredText(node, "byteSize")))); + } + if (!root.path("inheritedCommitId").isTextual()) + throw new IllegalArgumentException("Stored inherited commit must be text"); + String inherited = root.path("inheritedCommitId").textValue(); + var result = + new BrandingSourceSnapshot( + binding, + CommandSource.requiredStoredText(root, "sourceEpoch"), + inherited.isEmpty() ? null : UUID.fromString(inherited), + UUID.fromString(CommandSource.requiredStoredText(root, "genesisReceiptId")), + items); + if (!result.canonicalJson().equals(json)) + throw new IllegalArgumentException("Noncanonical branding asset snapshot"); + return result; + } + + public record Genesis(TargetProof target, UUID receiptId, String creationTransactionId) { + public Genesis { + Objects.requireNonNull(target); + if (receiptId == null + || new UUID(0, 0).equals(receiptId) + || creationTransactionId == null + || !creationTransactionId.matches("[1-9][0-9]*")) + throw new IllegalArgumentException("Exact branding source creation evidence required"); + } + + public Map roleDeclarations() { + return BrandingSource.emptyRoleDeclarations(); + } + } + + public record Capture(GameDesignPublicationOperation operation, BrandingSourceSnapshot snapshot) { + public Capture { + Objects.requireNonNull(operation); + Objects.requireNonNull(snapshot); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) + throw new IllegalArgumentException("Branding asset capture differs from selected commit"); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, "game-design-branding-asset-source-capture/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, operation.canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java index f1f690b685..2e7aeec475 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java @@ -157,7 +157,9 @@ public static List mutations(DraftCommitBinding binding) { String revisionKind = payload.path("revisionKind").asText(); if (REALM_POLICY_REVISION_KIND.equals(revisionKind) || AssetSource.REVISION_KIND.equals(revisionKind) - || GameplayRuleSource.REVISION_KIND.equals(revisionKind)) continue; + || GameplayRuleSource.REVISION_KIND.equals(revisionKind) + || BrandingSource.REVISION_KIND.equals(revisionKind) + || TemplateConfigSource.REVISION_KIND.equals(revisionKind)) continue; if (!REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } @@ -208,7 +210,9 @@ public static boolean hasRealmPolicyRevision(DraftCommitBinding binding) { found = true; } else if (!REVISION_KIND.equals(revisionKind) && !AssetSource.REVISION_KIND.equals(revisionKind) - && !GameplayRuleSource.REVISION_KIND.equals(revisionKind)) { + && !GameplayRuleSource.REVISION_KIND.equals(revisionKind) + && !BrandingSource.REVISION_KIND.equals(revisionKind) + && !TemplateConfigSource.REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java index 6a1119cd46..e0876b5bc1 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java @@ -24,6 +24,8 @@ public final class GameDesignSourceRepository { private final RealmPolicySourceRepository policies; private final CommandSourceRepository commands; private final AssetSourceRepository assets; + private final BrandingSourceRepository branding; + private final TemplateConfigSourceRepository templateConfigs; private final GameplayRuleSourceRepository gameplayRules; private final DraftCommitCoordinatorRepository coordinator; @@ -32,6 +34,8 @@ public GameDesignSourceRepository(DSLContext dsl) { policies = new RealmPolicySourceRepository(dsl); commands = new CommandSourceRepository(dsl); assets = new AssetSourceRepository(dsl); + branding = new BrandingSourceRepository(dsl); + templateConfigs = new TemplateConfigSourceRepository(dsl); gameplayRules = new GameplayRuleSourceRepository(dsl); coordinator = new DraftCommitCoordinatorRepository(dsl); } @@ -50,7 +54,9 @@ public Genesis enrollFreshDraft(TargetProof target) { policy, command, assets.enrollFreshDraft(target), - gameplayRules.enrollFreshDraft(target)); + gameplayRules.enrollFreshDraft(target), + branding.enrollFreshDraft(target), + templateConfigs.enrollFreshDraft(target)); if (!result.equals( readGenesis(target) .orElseThrow( @@ -68,9 +74,20 @@ public Optional readGenesis(TargetProof target) { var command = commands.readNewDraftGenesis(target); var asset = assets.readGenesis(target); var gameplay = gameplayRules.readGenesis(target); - if (policy.isEmpty() && command.isEmpty() && asset.isEmpty() && gameplay.isEmpty()) - return Optional.empty(); - if (policy.isEmpty() || command.isEmpty() || asset.isEmpty() || gameplay.isEmpty()) { + var brand = branding.readGenesis(target); + var template = templateConfigs.readGenesis(target); + if (policy.isEmpty() + && command.isEmpty() + && asset.isEmpty() + && gameplay.isEmpty() + && brand.isEmpty() + && template.isEmpty()) return Optional.empty(); + if (policy.isEmpty() + || command.isEmpty() + || asset.isEmpty() + || gameplay.isEmpty() + || brand.isEmpty() + || template.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); } return Optional.of( @@ -78,7 +95,9 @@ public Optional readGenesis(TargetProof target) { policy.orElseThrow(), command.orElseThrow(), asset.orElseThrow(), - gameplay.orElseThrow())); + gameplay.orElseThrow(), + brand.orElseThrow(), + template.orElseThrow())); } /** Stage actual source writes and record exactly one complete local owner outcome. */ @@ -89,12 +108,26 @@ public Application apply(DraftCommitBinding binding) { boolean policyMutation = CommandSource.hasRealmPolicyRevision(binding); boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); boolean gameplayMutation = !GameplayRuleSource.mutations(binding).isEmpty(); + boolean brandingMutation = !BrandingSource.mutations(binding).isEmpty(); + boolean templateMutation = !TemplateConfigSource.mutations(binding).isEmpty(); requireCompleteScopes( - binding, !commandMutations.isEmpty(), policyMutation, assetMutation, gameplayMutation); + binding, + !commandMutations.isEmpty(), + policyMutation, + assetMutation, + gameplayMutation, + brandingMutation, + templateMutation); requireGenesis(binding.target()); Optional command = commands.apply(binding); Optional asset = assets.apply(binding); Optional gameplay = gameplayRules.apply(binding); + Optional brand = branding.apply(binding); + Optional template = templateConfigs.apply(binding); + if (template.isPresent() != templateMutation) + throw new IllegalStateException("GAME_DESIGN_TEMPLATE_CONFIG_APPLICATION_INCOMPLETE"); + if (brand.isPresent() != brandingMutation) + throw new IllegalStateException("GAME_DESIGN_BRANDING_APPLICATION_INCOMPLETE"); if (gameplay.isPresent() != gameplayMutation) throw new IllegalStateException("GAME_DESIGN_GAMEPLAY_APPLICATION_INCOMPLETE"); if (asset.isPresent() != assetMutation) @@ -108,12 +141,16 @@ public Application apply(DraftCommitBinding binding) { // first, then records the combined result using the command store's actual readback bytes. policy = Optional.of( - command.isPresent() || asset.isPresent() || gameplay.isPresent() + command.isPresent() + || asset.isPresent() + || gameplay.isPresent() + || brand.isPresent() + || template.isPresent() ? policies.applyMutation(binding) : policies.apply(binding)); } OwnerOutcome expected; - if (asset.isPresent() || gameplay.isPresent()) { + if (asset.isPresent() || gameplay.isPresent() || brand.isPresent() || template.isPresent()) { var component = new ByteArrayOutputStream(); DraftAuthorizationFenceBinding.frame( component, "game-design-control-plane-sibling-components/v1"); @@ -133,6 +170,16 @@ public Application apply(DraftCommitBinding binding) { DraftAuthorizationFenceBinding.frame(component, gameplay.orElseThrow().canonicalBytes()); epochs.add(gameplay.orElseThrow().appliedEpoch()); } + if (brand.isPresent()) { + DraftAuthorizationFenceBinding.frame(component, "BRANDING"); + DraftAuthorizationFenceBinding.frame(component, brand.orElseThrow().canonicalBytes()); + epochs.add(brand.orElseThrow().appliedEpoch()); + } + if (template.isPresent()) { + DraftAuthorizationFenceBinding.frame(component, "TEMPLATE_CONFIG"); + DraftAuthorizationFenceBinding.frame(component, template.orElseThrow().canonicalBytes()); + epochs.add(template.orElseThrow().appliedEpoch()); + } if (policy.isPresent()) { var policyResult = policy.orElseThrow(); epochs.add(policyResult.ownerOutcome().appliedEpochs().getFirst()); @@ -193,7 +240,7 @@ public Application apply(DraftCommitBinding binding) { if (!expected.equals(retained)) { throw new IllegalStateException("GAME_DESIGN_OWNER_RESULT_READBACK_CONFLICT"); } - return new Application(binding, command, policy, asset, gameplay, retained); + return new Application(binding, command, policy, asset, gameplay, brand, template, retained); } /** Invoke after the actual coordinator fence advances, before releasing its application slot. */ @@ -205,10 +252,13 @@ public SynchronizedSources captureSynchronized(DraftCommitBinding binding) { RealmPolicySnapshot policy = policies.captureSynchronized(binding); AssetSnapshot asset = assets.captureSynchronized(binding); GameplayRuleSnapshot gameplay = gameplayRules.captureSynchronized(binding); + BrandingSourceSnapshot brand = branding.captureSynchronized(binding); + TemplateConfigSourceSnapshot template = templateConfigs.captureSynchronized(binding); if (!binding.equals(command.binding()) || !binding.equals(policy.binding())) { throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_BINDING_CONFLICT"); } - return new SynchronizedSources(command, policy, asset, gameplay); + return new SynchronizedSources( + command, policy, asset, gameplay, Optional.of(brand), Optional.of(template)); } /** Freeze both complete, selected source snapshots against the same retained operation. */ @@ -218,14 +268,23 @@ public Capture freeze(GameDesignPublicationOperation operation) { requireGenesis(operation.account().input().selection().target()); RealmPolicySnapshot.Capture policy = policies.freeze(operation); CommandSnapshot.Capture command = commands.freeze(operation); - Capture result = new Capture(command, policy, assets.freeze(operation)); + Capture result = + new Capture( + command, + policy, + assets.freeze(operation), + branding.freeze(operation), + templateConfigs.freeze(operation)); Capture retained = readCapture(operation) .orElseThrow( () -> new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_UNAVAILABLE")); if (!Arrays.equals(result.command().canonicalBytes(), retained.command().canonicalBytes()) || !Arrays.equals(result.policy().canonicalBytes(), retained.policy().canonicalBytes()) - || !Arrays.equals(result.asset().canonicalBytes(), retained.asset().canonicalBytes())) { + || !Arrays.equals(result.asset().canonicalBytes(), retained.asset().canonicalBytes()) + || !Arrays.equals(result.branding().canonicalBytes(), retained.branding().canonicalBytes()) + || !Arrays.equals( + result.templateConfig().canonicalBytes(), retained.templateConfig().canonicalBytes())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_READBACK_CONFLICT"); } return retained; @@ -237,12 +296,27 @@ public Optional readCapture(GameDesignPublicationOperation operation) { var command = commands.readCapture(operation); var policy = policies.readCapture(operation); var asset = assets.readCapture(operation); - if (command.isEmpty() && policy.isEmpty() && asset.isEmpty()) return Optional.empty(); - if (command.isEmpty() || policy.isEmpty() || asset.isEmpty()) { + var brand = branding.readCapture(operation); + var template = templateConfigs.readCapture(operation); + if (command.isEmpty() + && policy.isEmpty() + && asset.isEmpty() + && brand.isEmpty() + && template.isEmpty()) return Optional.empty(); + if (command.isEmpty() + || policy.isEmpty() + || asset.isEmpty() + || brand.isEmpty() + || template.isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); } return Optional.of( - new Capture(command.orElseThrow(), policy.orElseThrow(), asset.orElseThrow())); + new Capture( + command.orElseThrow(), + policy.orElseThrow(), + asset.orElseThrow(), + brand.orElseThrow(), + template.orElseThrow())); } public Optional readSynchronized(TargetProof target, UUID commitId) { @@ -252,9 +326,26 @@ public Optional readSynchronized(TargetProof target, UUID c var policy = policies.readSnapshot(target, commitId); var asset = assets.readSnapshot(target, commitId); var gameplay = gameplayRules.readSnapshot(target, commitId); - if (command.isEmpty() && policy.isEmpty() && asset.isEmpty() && gameplay.isEmpty()) - return Optional.empty(); - if (command.isEmpty() || policy.isEmpty() || asset.isEmpty() || gameplay.isEmpty()) { + var brand = branding.readSnapshot(target, commitId); + var template = templateConfigs.readSnapshot(target, commitId); + if (command.isEmpty() + && policy.isEmpty() + && asset.isEmpty() + && gameplay.isEmpty() + && brand.isEmpty() + && template.isEmpty()) return Optional.empty(); + // Retained pre-branding commits keep exact original readback, with branding explicitly unknown. + // Fresh publication capture requires all-family genesis and cannot consume that unknown value. + if (command.isEmpty() + || policy.isEmpty() + || asset.isEmpty() + || gameplay.isEmpty() + || brand.isEmpty() + && (branding.readGenesis(target).isPresent() + || !BrandingSource.mutations(command.orElseThrow().binding()).isEmpty()) + || template.isEmpty() + && (templateConfigs.readGenesis(target).isPresent() + || !TemplateConfigSource.mutations(command.orElseThrow().binding()).isEmpty())) { throw new IllegalStateException("GAME_DESIGN_SYNCHRONIZED_SOURCE_INCOMPLETE"); } return Optional.of( @@ -262,7 +353,9 @@ public Optional readSynchronized(TargetProof target, UUID c command.orElseThrow(), policy.orElseThrow(), asset.orElseThrow(), - gameplay.orElseThrow())); + gameplay.orElseThrow(), + brand, + template)); } private void requireGenesis(TargetProof target) { @@ -292,8 +385,10 @@ private static void requireCompleteScopes( boolean hasCommand, boolean hasPolicy, boolean hasAsset, - boolean hasGameplay) { - if (!hasCommand && !hasPolicy && !hasAsset && !hasGameplay + boolean hasGameplay, + boolean hasBranding, + boolean hasTemplate) { + if (!hasCommand && !hasPolicy && !hasAsset && !hasGameplay && !hasBranding && !hasTemplate || !binding.requiredOwners().contains(Owner.GAME_DESIGN_CONTROL_PLANE)) { throw new IllegalArgumentException("Game Design owner requires typed source revisions"); } @@ -316,11 +411,21 @@ private static void requireCompleteScopes( .toList(); var assets = units.stream().filter(AssetSourceRepository::isScope).toList(); var gameplay = units.stream().filter(GameplayRuleSource::isScope).toList(); + var brands = units.stream().filter(BrandingSourceRepository::isScope).toList(); + var templates = units.stream().filter(TemplateConfigSource::isScope).toList(); if (commands.size() != (hasCommand ? 1 : 0) || policies.size() != (hasPolicy ? 1 : 0) || assets.size() != (hasAsset ? 1 : 0) || gameplay.size() != (hasGameplay ? 1 : 0) - || commands.size() + policies.size() + assets.size() + gameplay.size() != units.size() + || brands.size() != (hasBranding ? 1 : 0) + || templates.size() != (hasTemplate ? 1 : 0) + || commands.size() + + policies.size() + + assets.size() + + gameplay.size() + + brands.size() + + templates.size() + != units.size() || units.stream() .anyMatch( unit -> @@ -349,19 +454,27 @@ public record Genesis( RealmPolicyGenesis policy, CommandSource.NewDraftGenesisReceipt command, AssetSnapshot.Genesis asset, - GameplayRuleSnapshot.Genesis gameplay) { + GameplayRuleSnapshot.Genesis gameplay, + BrandingSourceSnapshot.Genesis branding, + TemplateConfigSourceSnapshot.Genesis templateConfig) { public Genesis { Objects.requireNonNull(policy, "policy"); Objects.requireNonNull(command, "command"); Objects.requireNonNull(asset, "asset"); Objects.requireNonNull(gameplay, "gameplay"); + Objects.requireNonNull(branding, "branding"); + Objects.requireNonNull(templateConfig, "templateConfig"); if (!policy.target().equals(command.target()) || !policy.receiptId().equals(command.receiptId()) || !policy.creationTransactionId().equals(command.creationTransactionId()) || !policy.target().equals(asset.target()) || !policy.creationTransactionId().equals(asset.creationTransactionId()) || !policy.target().equals(gameplay.target()) - || !policy.creationTransactionId().equals(gameplay.creationTransactionId())) { + || !policy.creationTransactionId().equals(gameplay.creationTransactionId()) + || !policy.target().equals(branding.target()) + || !policy.creationTransactionId().equals(branding.creationTransactionId()) + || !policy.target().equals(templateConfig.target()) + || !policy.creationTransactionId().equals(templateConfig.creationTransactionId())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_IDENTITY_CONFLICT"); } } @@ -373,6 +486,8 @@ public record Application( Optional policy, Optional asset, Optional gameplay, + Optional branding, + Optional templateConfig, OwnerOutcome ownerOutcome) { public Application { Objects.requireNonNull(binding, "binding"); @@ -380,12 +495,21 @@ public record Application( policy = Objects.requireNonNull(policy, "policy"); asset = Objects.requireNonNull(asset, "asset"); gameplay = Objects.requireNonNull(gameplay, "gameplay"); + branding = Objects.requireNonNull(branding, "branding"); + templateConfig = Objects.requireNonNull(templateConfig, "templateConfig"); Objects.requireNonNull(ownerOutcome, "ownerOutcome"); - if (command.isEmpty() && policy.isEmpty() && asset.isEmpty() && gameplay.isEmpty() + if (command.isEmpty() + && policy.isEmpty() + && asset.isEmpty() + && gameplay.isEmpty() + && branding.isEmpty() + && templateConfig.isEmpty() || command.isPresent() && !binding.equals(command.orElseThrow().binding()) || policy.isPresent() && !binding.equals(policy.orElseThrow().snapshot().binding()) || asset.isPresent() && !binding.equals(asset.orElseThrow().binding()) || gameplay.isPresent() && !binding.equals(gameplay.orElseThrow().binding()) + || branding.isPresent() && !binding.equals(branding.orElseThrow().binding()) + || templateConfig.isPresent() && !binding.equals(templateConfig.orElseThrow().binding()) || ownerOutcome.owner() != Owner.GAME_DESIGN_CONTROL_PLANE || ownerOutcome.status() != OwnerStatus.APPLIED || !binding.commitId().equals(ownerOutcome.commitId()) @@ -399,15 +523,22 @@ public record SynchronizedSources( CommandSnapshot command, RealmPolicySnapshot policy, AssetSnapshot asset, - GameplayRuleSnapshot gameplay) { + GameplayRuleSnapshot gameplay, + Optional branding, + Optional templateConfig) { public SynchronizedSources { Objects.requireNonNull(command, "command"); Objects.requireNonNull(policy, "policy"); Objects.requireNonNull(asset, "asset"); Objects.requireNonNull(gameplay, "gameplay"); + Objects.requireNonNull(branding, "branding"); + Objects.requireNonNull(templateConfig, "templateConfig"); if (!command.binding().equals(policy.binding()) || !command.binding().equals(asset.binding()) - || !command.binding().equals(gameplay.binding())) { + || !command.binding().equals(gameplay.binding()) + || branding.isPresent() && !command.binding().equals(branding.orElseThrow().binding()) + || templateConfig.isPresent() + && !command.binding().equals(templateConfig.orElseThrow().binding())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_SNAPSHOT_BINDING_CONFLICT"); } } @@ -416,16 +547,26 @@ public record SynchronizedSources( public record Capture( CommandSnapshot.Capture command, RealmPolicySnapshot.Capture policy, - AssetSnapshot.Capture asset) { + AssetSnapshot.Capture asset, + BrandingSourceSnapshot.Capture branding, + TemplateConfigSourceSnapshot.Capture templateConfig) { public Capture { Objects.requireNonNull(command, "command"); Objects.requireNonNull(policy, "policy"); Objects.requireNonNull(asset, "asset"); + Objects.requireNonNull(branding, "branding"); + Objects.requireNonNull(templateConfig, "templateConfig"); if (!Arrays.equals(command.operation().canonicalBytes(), policy.operation().canonicalBytes()) || !command.snapshot().binding().equals(policy.snapshot().binding()) || !command.snapshot().binding().equals(asset.snapshot().binding()) || !Arrays.equals( - command.operation().canonicalBytes(), asset.operation().canonicalBytes())) { + command.operation().canonicalBytes(), asset.operation().canonicalBytes()) + || !command.snapshot().binding().equals(branding.snapshot().binding()) + || !Arrays.equals( + command.operation().canonicalBytes(), branding.operation().canonicalBytes()) + || !command.snapshot().binding().equals(templateConfig.snapshot().binding()) + || !Arrays.equals( + command.operation().canonicalBytes(), templateConfig.operation().canonicalBytes())) { throw new IllegalStateException("GAME_DESIGN_SOURCE_CAPTURE_BINDING_CONFLICT"); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSource.java index f78b7d2e14..36e760c912 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSource.java @@ -110,8 +110,13 @@ public static List mutations(DraftCommitBinding binding) { if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; var node = GameplayRuleManifest.tree(revision.payload()); String kind = text(node, "revisionKind"); - if (Set.of("COMMAND_DEFINITION", "REALM_ENTRY_POLICY", "ASSET_REFERENCE").contains(kind)) - continue; + if (Set.of( + "COMMAND_DEFINITION", + "REALM_ENTRY_POLICY", + "ASSET_REFERENCE", + BrandingSource.REVISION_KIND, + TemplateConfigSource.REVISION_KIND) + .contains(kind)) continue; if (!REVISION_KIND.equals(kind)) throw new IllegalArgumentException("Unknown Game Design revision kind"); OperationKind operation = OperationKind.valueOf(text(node, "operation")); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java new file mode 100644 index 0000000000..d708940075 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java @@ -0,0 +1,405 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import tools.jackson.databind.JsonNode; + +/** Closed authored wiring. Syntax validation never qualifies an external owner's reference. */ +public final class TemplateConfigSource { + public static final String REVISION_KIND = "TEMPLATE_CONFIG"; + public static final String SCOPE = "TEMPLATE_CONFIG_SET"; + public static final String SCOPE_ID = "effective"; + + private TemplateConfigSource() {} + + public enum OperationKind { + CREATE, + UPSERT, + DELETE + } + + public record GameplayInput(Family family, String key, UUID revisionId) { + public GameplayInput { + Objects.requireNonNull(family); + GameplayRuleManifest.identifier(key); + uuid(revisionId.toString()); + } + } + + /** Canonical config remains the actual authored document, without derived commit evidence. */ + public record Config(String canonicalJson) { + public Config { + JsonNode root = CommandSource.tree(canonicalJson); + fields( + root, + "schemaVersion", + "baseVersionId", + "world", + "entity", + "gameLogic", + "automation", + "supportedSettings"); + if (!root.path("schemaVersion").isInt() || root.path("schemaVersion").intValue() != 1) + throw new IllegalArgumentException("Unsupported template config schemaVersion"); + uuid(text(root, "baseVersionId")); + fields(root.path("world"), "regions", "rooms"); + ownerIds(root.path("world"), "regions", "regionTemplateId"); + ownerIds(root.path("world"), "rooms", "roomTemplateId"); + fields(root.path("entity"), "items", "npcs"); + ownerIds(root.path("entity"), "items", "entityTemplateId"); + ownerIds(root.path("entity"), "npcs", "entityTemplateId"); + fields(root.path("gameLogic"), "inputs"); + Set rules = new HashSet<>(); + for (JsonNode node : array(root.path("gameLogic"), "inputs")) { + fields(node, "family", "key", "revisionId"); + Family family = Family.valueOf(text(node, "family")); + String key = text(node, "key"); + GameplayRuleManifest.identifier(key); + uuid(text(node, "revisionId")); + if (!rules.add(family.name() + ":" + key)) + throw new IllegalArgumentException("Duplicate template gameplay input"); + } + fields(root.path("automation"), "scripts", "scriptPatch"); + Set scripts = new HashSet<>(); + for (JsonNode node : array(root.path("automation"), "scripts")) { + fields(node, "scriptId", "eventBindings"); + if (!scripts.add(text(node, "scriptId"))) + throw new IllegalArgumentException("Duplicate template script name"); + Set bindings = new HashSet<>(); + for (JsonNode event : array(node, "eventBindings")) { + fields( + event, + "eventType", + "eventSchemaVersion", + "bindingId", + "targetScopeType", + "targetScopeId"); + text(event, "eventType"); + text(event, "eventSchemaVersion"); + for (String key : List.of("bindingId", "targetScopeType", "targetScopeId")) + if (!event.path(key).isTextual()) + throw new IllegalArgumentException("Exact Automation binding key required"); + if (!bindings.add(CommandSource.canonical(event))) + throw new IllegalArgumentException("Duplicate template event binding"); + } + } + JsonNode patch = root.path("automation").path("scriptPatch"); + String presence = text(patch, "presence"); + if ("ABSENT".equals(presence)) fields(patch, "presence"); + else if ("PRESENT".equals(presence)) { + fields(patch, "presence", "scriptPatchVersion"); + text(patch, "scriptPatchVersion"); + } else throw new IllegalArgumentException("Explicit template script-patch presence required"); + if (!array(root, "supportedSettings").isEmpty()) + throw new IllegalArgumentException( + "No supported non-authoritative settings are registered"); + canonicalJson = CommandSource.canonical(root); + } + + public UUID baseVersionId() { + return uuid(text(CommandSource.tree(canonicalJson), "baseVersionId")); + } + + public List gameplayInputs() { + List inputs = new ArrayList<>(); + for (JsonNode node : CommandSource.tree(canonicalJson).path("gameLogic").path("inputs")) + inputs.add( + new GameplayInput( + Family.valueOf(text(node, "family")), + text(node, "key"), + uuid(text(node, "revisionId")))); + return List.copyOf(inputs); + } + + /** These missing authenticated owner boundaries deliberately prevent qualification. */ + public void requireAvailableOwnerReads() { + var root = CommandSource.tree(canonicalJson); + if (!root.path("world").path("regions").isEmpty() + || !root.path("world").path("rooms").isEmpty()) + throw new IllegalStateException("TEMPLATE_CONFIG_WORLD_EXACT_OWNER_READ_UNAVAILABLE"); + if (!root.path("entity").path("items").isEmpty() + || !root.path("entity").path("npcs").isEmpty()) + throw new IllegalStateException("TEMPLATE_CONFIG_ENTITY_EXACT_OWNER_READ_UNAVAILABLE"); + if (!root.path("automation").path("scripts").isEmpty() + || "PRESENT".equals(text(root.path("automation").path("scriptPatch"), "presence"))) + throw new IllegalStateException("TEMPLATE_CONFIG_AUTOMATION_EXACT_OWNER_READ_UNAVAILABLE"); + } + } + + public record Mutation( + DraftCommitBinding binding, + String revisionOrder, + UUID revisionId, + OperationKind operation, + String templateId, + String templateName, + Config config) { + public Mutation { + Objects.requireNonNull(binding); + Objects.requireNonNull(operation); + if (operation == OperationKind.CREATE) { + if (templateId != null + || templateName == null + || templateName.isBlank() + || templateName.length() > 100) + throw new IllegalArgumentException( + "CREATE requires a display name and no caller template id"); + } else { + requireTemplateId(templateId); + if (templateName != null) + throw new IllegalArgumentException("Only CREATE carries a display name"); + } + if (operation != OperationKind.DELETE) { + Objects.requireNonNull(config); + if (!binding.target().canonicalVersionId().equals(config.baseVersionId())) + throw new IllegalArgumentException( + "Template config base differs from its exact source version"); + } else if (config != null) + throw new IllegalArgumentException("Template DELETE carries no config"); + var revision = + binding.revisions().stream() + .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .filter( + r -> r.revisionId().equals(revisionId) && r.revisionOrder().equals(revisionOrder)) + .findFirst() + .orElseThrow(); + String expected = + operation == OperationKind.CREATE + ? createPayload(templateName, config) + : operation == OperationKind.UPSERT + ? upsertPayload(templateId, config) + : deletePayload(templateId); + if (!expected.equals(CommandSource.canonical(CommandSource.tree(revision.payload())))) + throw new IllegalArgumentException( + "Template config differs from its exact original revision"); + } + + public String payload() { + return operation == OperationKind.CREATE + ? createPayload(templateName, config) + : operation == OperationKind.UPSERT + ? upsertPayload(templateId, config) + : deletePayload(templateId); + } + } + + public record Entry( + String templateId, + Config config, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId, + String createdName) { + public Entry { + requireTemplateId(templateId); + new Mutation( + sourceBinding, + revisionOrder, + revisionId, + createdName == null ? OperationKind.UPSERT : OperationKind.CREATE, + createdName == null ? templateId : null, + createdName, + config); + } + + Map object() { + return Map.of( + "templateId", + templateId, + "configJson", + config.canonicalJson(), + "sourceBindingJson", + sourceBinding.canonicalJson(), + "sourceBindingDigest", + sourceBinding.digest(), + "revisionOrder", + revisionOrder, + "revisionId", + revisionId.toString(), + "createdName", + createdName == null ? "" : createdName); + } + } + + public static List mutations(DraftCommitBinding binding) { + List result = new ArrayList<>(); + for (var revision : binding.revisions()) { + if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; + JsonNode root = CommandSource.tree(revision.payload()); + String kind = text(root, "revisionKind"); + if (Set.of( + "COMMAND_DEFINITION", + "REALM_ENTRY_POLICY", + "ASSET_REFERENCE", + "GAMEPLAY_RULE", + "BRANDING_ASSET_REFERENCE") + .contains(kind)) continue; + if (!REVISION_KIND.equals(kind)) + throw new IllegalArgumentException("Unknown Game Design revision kind"); + OperationKind operation = OperationKind.valueOf(text(root, "operation")); + fields( + root, + operation == OperationKind.CREATE + ? new String[] { + "schemaVersion", "revisionKind", "operation", "templateName", "configJson" + } + : operation == OperationKind.UPSERT + ? new String[] { + "schemaVersion", "revisionKind", "operation", "templateId", "configJson" + } + : new String[] {"schemaVersion", "revisionKind", "operation", "templateId"}); + if (!root.path("schemaVersion").isInt() || root.path("schemaVersion").intValue() != 1) + throw new IllegalArgumentException("Unsupported template source schemaVersion"); + result.add( + new Mutation( + binding, + revision.revisionOrder(), + revision.revisionId(), + operation, + operation == OperationKind.CREATE ? null : text(root, "templateId"), + operation == OperationKind.CREATE ? text(root, "templateName") : null, + operation != OperationKind.DELETE ? new Config(text(root, "configJson")) : null)); + } + return List.copyOf(result); + } + + public static String upsertPayload(String templateId, Config config) { + requireTemplateId(templateId); + return CommandSource.canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + REVISION_KIND, + "operation", + "UPSERT", + "templateId", + templateId, + "configJson", + config.canonicalJson())); + } + + public static String createPayload(String templateName, Config config) { + if (templateName == null || templateName.isBlank() || templateName.length() > 100) + throw new IllegalArgumentException("Template display name required"); + return CommandSource.canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + REVISION_KIND, + "operation", + "CREATE", + "templateName", + templateName, + "configJson", + config.canonicalJson())); + } + + public static String deletePayload(String templateId) { + requireTemplateId(templateId); + return CommandSource.canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + REVISION_KIND, + "operation", + "DELETE", + "templateId", + templateId)); + } + + public static List replay( + List inherited, DraftCommitBinding binding, Map createdRows) { + Map entries = new java.util.HashMap<>(); + for (Entry entry : inherited) { + if (!binding.target().equals(entry.sourceBinding().target()) + || entries.put(entry.templateId(), entry) != null) + throw new IllegalArgumentException("Invalid inherited template config inventory"); + } + for (Mutation mutation : mutations(binding)) { + if (mutation.operation() == OperationKind.DELETE) { + if (entries.remove(mutation.templateId()) == null) + throw new IllegalArgumentException("Template DELETE requires an authored entry"); + } else { + String id = + mutation.operation() == OperationKind.CREATE + ? Objects.requireNonNull( + createdRows.get(mutation.revisionId()), + "Actual generated template row required") + : mutation.templateId(); + if (mutation.operation() == OperationKind.CREATE && entries.containsKey(id) + || mutation.operation() == OperationKind.UPSERT && !entries.containsKey(id)) + throw new IllegalArgumentException( + "Template source identity is not an existing qualified entry"); + entries.put( + id, + new Entry( + id, + mutation.config(), + binding, + mutation.revisionOrder(), + mutation.revisionId(), + mutation.templateName())); + } + } + return entries.values().stream() + .sorted(Comparator.comparing(e -> new BigInteger(e.templateId()))) + .toList(); + } + + public static boolean isScope(DraftCommitBinding.AffectedUnit unit) { + return SCOPE.equals(unit.aggregateType()) + && SCOPE.equals(unit.scopeType()) + && SCOPE_ID.equals(unit.scopeId()); + } + + private static void requireTemplateId(String value) { + if (value == null + || !value.matches("[1-9][0-9]*") + || new BigInteger(value).compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) + throw new IllegalArgumentException("Exact Game Design template row identity required"); + } + + static UUID uuid(String value) { + UUID result = UUID.fromString(value); + if (!result.toString().equals(value) || new UUID(0, 0).equals(result)) + throw new IllegalArgumentException("Canonical nonzero owner UUID required"); + return result; + } + + private static void ownerIds(JsonNode root, String collection, String key) { + Set ids = new HashSet<>(); + for (JsonNode node : array(root, collection)) { + fields(node, key); + if (!ids.add(uuid(text(node, key)))) + throw new IllegalArgumentException("Duplicate owner template reference"); + } + } + + private static JsonNode array(JsonNode root, String key) { + if (!root.path(key).isArray()) + throw new IllegalArgumentException("Explicit template config collection required: " + key); + return root.path(key); + } + + private static void fields(JsonNode node, String... fields) { + CommandSource.requireStoredFields(node, fields); + } + + private static String text(JsonNode node, String key) { + return CommandSource.requiredStoredText(node, key); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java new file mode 100644 index 0000000000..79a2143135 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java @@ -0,0 +1,699 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Actual coordinated author history. Account mutation authority must be supplied by its owner. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner-local persistence collaborator") +public final class TemplateConfigSourceRepository { + private final DSLContext dsl; + private final DraftCommitCoordinatorRepository coordinator; + + public TemplateConfigSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + coordinator = new DraftCommitCoordinatorRepository(dsl); + } + + public TemplateConfigSourceSnapshot.Genesis enrollFreshDraft(TargetProof target) { + write(); + lock(target); + var existing = readGenesis(target); + if (existing.isPresent()) return existing.orElseThrow(); + Record witness = + dsl.fetchOne( + "SELECT creation_transaction_id FROM game_design_realm_policy_version_insert " + + "WHERE version_id = ? AND creation_transaction_id = pg_current_xact_id()::TEXT", + target.gameDesignVersionRowId()); + if (witness == null) + throw new IllegalStateException("TEMPLATE_CONFIG_FRESH_INSERT_UNAVAILABLE"); + var result = + new TemplateConfigSourceSnapshot.Genesis( + target, UUID.randomUUID(), witness.get(0, String.class)); + dsl.execute( + "INSERT INTO game_design_template_config_source_genesis (canonical_tenant_id, canonical_version_id, " + + "version_id, receipt_id, creation_transaction_id, target_json) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + result.receiptId(), + result.creationTransactionId(), + CommandSource.canonical(CommandSource.targetObject(target))); + dsl.execute( + "INSERT INTO game_design_template_config_source_head (canonical_tenant_id, canonical_version_id, source_epoch, genesis_receipt_id) " + + "VALUES (?, ?, '0', ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + result.receiptId()); + if (!result.equals(readGenesis(target).orElseThrow())) + throw new IllegalStateException("TEMPLATE_CONFIG_GENESIS_READBACK_CONFLICT"); + return result; + } + + public Optional readGenesis(TargetProof target) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_template_config_source_genesis WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + if (!CommandSource.canonical(CommandSource.targetObject(target)) + .equals(row.get("target_json", String.class)) + || target.gameDesignVersionRowId() != row.get("version_id", Long.class)) + throw new IllegalStateException("TEMPLATE_CONFIG_GENESIS_TARGET_CONFLICT"); + return Optional.of( + new TemplateConfigSourceSnapshot.Genesis( + target, + row.get("receipt_id", UUID.class), + row.get("creation_transaction_id", String.class))); + } + + public Optional apply(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var prior = application(binding); + if (prior.isPresent()) return prior; + var mutations = TemplateConfigSource.mutations(binding); + if (mutations.isEmpty()) return Optional.empty(); + open(binding.target()); + var slot = coordinator.readApplicationSlot(binding.target()).orElseThrow(); + var owner = + coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (!slot.commitId().equals(binding.commitId()) + || !slot.requestId().equals(binding.requestId()) + || owner == null + || owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.IN_PROGRESS + && owner.status() != DraftCommitCoordinatorRepository.OwnerStatus.UNKNOWN) + throw new IllegalStateException("TEMPLATE_CONFIG_COORDINATOR_APPLICATION_UNAVAILABLE"); + Record head = head(binding.target()); + String epoch = head.get("source_epoch", String.class); + var units = + binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(TemplateConfigSource::isScope) + .toList(); + if (units.size() != 1 + || !units.getFirst().aggregateId().equals(binding.target().canonicalVersionId().toString()) + || !epoch.equals(units.getFirst().expectedEpoch())) + throw new IllegalStateException("TEMPLATE_CONFIG_EPOCH_CONFLICT"); + UUID inherited = head.get("visible_commit_id", UUID.class); + var fence = coordinator.readVisibilityFence(binding.target()); + if (inherited == null + ? fence.isPresent() || !"0".equals(epoch) + : fence.isEmpty() || !inherited.equals(fence.orElseThrow().commitId())) + throw new IllegalStateException("TEMPLATE_CONFIG_PREVIOUS_FENCE_CHANGED"); + List previous = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().entries(); + var createdRows = new java.util.HashMap(); + for (var mutation : mutations) { + if (mutation.config() != null) { + mutation.config().requireAvailableOwnerReads(); + requireGameplayInputs(binding, mutation.config()); + } + String templateId = mutation.templateId(); + if (mutation.operation() == TemplateConfigSource.OperationKind.CREATE) { + var row = + dsl.fetchOne( + "INSERT INTO game_templates (tenant_id, name, config, default_version_id, template_reference_phase) " + + "VALUES (?, ?, CAST(? AS JSONB), ?, 'LEGACY') RETURNING id", + binding.target().gameDesignVersionTenantKey(), + mutation.templateName(), + mutation.config().canonicalJson(), + binding.target().gameDesignVersionRowId()); + templateId = Objects.requireNonNull(row).get("id", Long.class).toString(); + createdRows.put(mutation.revisionId(), templateId); + dsl.execute( + "INSERT INTO game_design_template_config_source_qualification " + + "(template_id, canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + Long.parseLong(templateId), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + mutation.revisionId(), + Integer.parseInt(mutation.revisionOrder())); + } else { + requireQualified(binding.target(), templateId, true); + if (mutation.operation() == TemplateConfigSource.OperationKind.UPSERT) + dsl.execute( + "UPDATE game_templates SET config = CAST(? AS JSONB) WHERE id = ? AND tenant_id = ?", + mutation.config().canonicalJson(), + Long.parseLong(templateId), + binding.target().gameDesignVersionTenantKey()); + } + dsl.execute( + "INSERT INTO game_design_template_config_source_revision " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, operation_kind, template_id, payload_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + mutation.revisionId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.operation().name(), + Long.parseLong(templateId), + mutation.payload()); + if (mutation.config() != null) { + dsl.execute( + "INSERT INTO game_design_template_config_source_ref " + + "(canonical_tenant_id, canonical_version_id, revision_id, ref_kind, ref_key, referenced_revision_id) " + + "VALUES (?, ?, ?, 'BASE_VERSION', ?, NULL)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + mutation.revisionId(), + mutation.config().baseVersionId().toString()); + for (var input : mutation.config().gameplayInputs()) + dsl.execute( + "INSERT INTO game_design_template_config_source_ref " + + "(canonical_tenant_id, canonical_version_id, revision_id, ref_kind, ref_key, referenced_revision_id) " + + "VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + mutation.revisionId(), + input.family().name(), + input.key(), + input.revisionId()); + } + } + var snapshot = + new TemplateConfigSourceSnapshot( + binding, + new BigInteger(epoch).add(BigInteger.ONE).toString(), + inherited, + head.get("genesis_receipt_id", UUID.class), + TemplateConfigSource.replay(previous, binding, createdRows)); + var result = new TemplateConfigSourceSnapshot.Application(binding, epoch, snapshot); + dsl.execute( + "INSERT INTO game_design_template_config_source_application (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "expected_epoch, snapshot_json, result_bytes) VALUES (?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + epoch, + snapshot.canonicalJson(), + result.canonicalBytes()); + if (dsl.execute( + "UPDATE game_design_template_config_source_head SET source_epoch = ?, applied_commit_id = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND source_epoch = ? AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID)", + snapshot.sourceEpoch(), + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + epoch, + inherited) + != 1) throw new IllegalStateException("TEMPLATE_CONFIG_EPOCH_CONFLICT"); + return Optional.of(application(binding).orElseThrow()); + } + + public TemplateConfigSourceSnapshot captureSynchronized(DraftCommitBinding binding) { + write(); + lock(binding.target()); + exact(binding); + var existing = readSnapshot(binding.target(), binding.commitId()); + if (existing.isPresent()) { + if (!existing.orElseThrow().binding().equals(binding)) + throw new IllegalStateException("TEMPLATE_CONFIG_SNAPSHOT_BINDING_CONFLICT"); + return existing.orElseThrow(); + } + open(binding.target()); + requireFence(binding); + var head = head(binding.target()); + UUID inherited = head.get("visible_commit_id", UUID.class); + var applied = application(binding); + TemplateConfigSourceSnapshot snapshot; + if (!TemplateConfigSource.mutations(binding).isEmpty()) { + snapshot = applied.orElseThrow().snapshot(); + if (!Objects.equals(inherited, snapshot.inheritedCommitId())) + throw new IllegalStateException("TEMPLATE_CONFIG_PREDECESSOR_CHANGED"); + } else { + if (applied.isPresent()) + throw new IllegalStateException("TEMPLATE_CONFIG_UNDECLARED_APPLICATION"); + var entries = + inherited == null + ? List.of() + : readSnapshot(binding.target(), inherited).orElseThrow().entries(); + if (inherited == null && !"0".equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_GENESIS_NOT_CURRENT"); + snapshot = + new TemplateConfigSourceSnapshot( + binding, + head.get("source_epoch", String.class), + inherited, + head.get("genesis_receipt_id", UUID.class), + entries); + } + requireSelectedReferences(snapshot); + requireCurrentInventory(snapshot); + if (!snapshot.sourceEpoch().equals(head.get("source_epoch", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_PARTIAL_WRITE_NOT_VISIBLE"); + dsl.execute( + "INSERT INTO game_design_template_config_source_snapshot (canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "snapshot_json, snapshot_digest) VALUES (?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + snapshot.canonicalJson(), + snapshot.digest()); + if (dsl.execute( + "UPDATE game_design_template_config_source_head SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND visible_commit_id IS NOT DISTINCT FROM CAST(? AS UUID) AND source_epoch = ?", + binding.commitId(), + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + inherited, + snapshot.sourceEpoch()) + != 1) throw new IllegalStateException("TEMPLATE_CONFIG_VISIBILITY_CONFLICT"); + return readSnapshot(binding.target(), binding.commitId()).orElseThrow(); + } + + public Optional readSnapshot(TargetProof target, UUID commitId) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_template_config_source_snapshot WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + commitId); + if (row == null) return Optional.empty(); + var snapshot = TemplateConfigSourceSnapshot.fromStored(row.get("snapshot_json", String.class)); + if (!snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(commitId) + || !snapshot.binding().requestId().equals(row.get("request_id", UUID.class)) + || !snapshot.digest().equals(row.get("snapshot_digest", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_SNAPSHOT_READBACK_CONFLICT"); + exact(snapshot.binding()); + var genesis = readGenesis(target).orElseThrow(); + if (!snapshot.genesisReceiptId().equals(genesis.receiptId())) + throw new IllegalStateException("TEMPLATE_CONFIG_GENESIS_CHANGED"); + var fence = + dsl.fetchOne( + "SELECT input_digest FROM game_design_draft_commit_visibility_fence WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND request_id = ? AND commit_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.binding().requestId(), + commitId); + if (fence == null || !snapshot.binding().digest().equals(fence.get(0, String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_SNAPSHOT_FENCE_CONFLICT"); + verifyEntries(snapshot); + requireSelectedReferences(snapshot); + return Optional.of(snapshot); + } + + public TemplateConfigSourceSnapshot.Capture freeze(GameDesignPublicationOperation operation) { + write(); + var selection = operation.account().input().selection(); + lock(selection.target()); + var prior = readCapture(operation); + if (prior.isPresent()) return prior.orElseThrow(); + var retained = + new GameDesignPublicationOperationRepository(dsl) + .read(operation.workflowId()) + .orElseThrow(); + GameDesignPublicationOperationRepository.exact(retained.operation(), operation); + if (!"PENDING".equals(retained.outcome())) + throw new IllegalStateException("TEMPLATE_CONFIG_OPERATION_SEALED"); + requireFence(selection.selectedCommit()); + var selected = + dsl.fetchOne( + "SELECT selection_json FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId()); + if (selected == null || !selection.canonicalJson().equals(selected.get(0, String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_SELECTION_CHANGED"); + var snapshot = + readSnapshot(selection.target(), selection.selectedCommit().commitId()).orElseThrow(); + var head = head(selection.target()); + if (!snapshot.binding().equals(selection.selectedCommit()) + || !snapshot.sourceEpoch().equals(head.get("source_epoch", String.class)) + || !snapshot.binding().commitId().equals(head.get("visible_commit_id", UUID.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_NOT_SYNCHRONIZED"); + requireSelectedReferences(snapshot); + requireCurrentInventory(snapshot); + for (var entry : snapshot.entries()) { + var row = + dsl.fetchOne( + "SELECT config::TEXT, default_version_id, default_script_patch_version, default_runtime_flags_json " + + "FROM game_templates WHERE id = ? AND tenant_id = ? FOR UPDATE", + Long.parseLong(entry.templateId()), + selection.target().gameDesignVersionTenantKey()); + if (row == null + || !entry + .config() + .canonicalJson() + .equals(CommandSource.canonical(CommandSource.tree(row.get(0, String.class)))) + || !Long.valueOf(selection.target().gameDesignVersionRowId()) + .equals(row.get(1, Long.class)) + || row.get(2, String.class) != null + || !"{}".equals(CommandSource.canonical(CommandSource.tree(row.get(3, String.class))))) + throw new IllegalStateException("TEMPLATE_CONFIG_LIVE_ROW_DIFFERS_FROM_SELECTED_SOURCE"); + } + var capture = new TemplateConfigSourceSnapshot.Capture(operation, snapshot); + dsl.execute( + "INSERT INTO game_design_template_config_source_capture (canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, operation_bytes, capture_bytes, capture_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + operation.workflowId(), + snapshot.binding().commitId(), + operation.canonicalBytes(), + capture.canonicalBytes(), + capture.digest()); + return readCapture(operation).orElseThrow(); + } + + public Optional readCapture( + GameDesignPublicationOperation operation) { + var target = operation.account().input().selection().target(); + var row = + dsl.fetchOne( + "SELECT * FROM game_design_template_config_source_capture WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) return Optional.empty(); + var capture = + new TemplateConfigSourceSnapshot.Capture( + operation, readSnapshot(target, row.get("commit_id", UUID.class)).orElseThrow()); + if (!operation.workflowId().equals(row.get("publish_workflow_id", String.class)) + || !Arrays.equals(operation.canonicalBytes(), row.get("operation_bytes", byte[].class)) + || !Arrays.equals(capture.canonicalBytes(), row.get("capture_bytes", byte[].class)) + || !capture.digest().equals(row.get("capture_digest", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_CAPTURE_READBACK_CONFLICT"); + return Optional.of(capture); + } + + private void requireCurrentInventory(TemplateConfigSourceSnapshot snapshot) { + var target = snapshot.binding().target(); + Boolean complete = + dsl.fetchSingle( + "SELECT template_config_current_inventory(?, ?, ?, ?, CAST(? AS JSONB))", + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + snapshot.canonicalJson()) + .get(0, Boolean.class); + if (!Boolean.TRUE.equals(complete)) + throw new IllegalStateException("TEMPLATE_CONFIG_EXPLICIT_TARGET_INVENTORY_UNQUALIFIED"); + } + + private void requireSelectedReferences(TemplateConfigSourceSnapshot snapshot) { + var gameplay = + new GameplayRuleSourceRepository(dsl) + .readSnapshot(snapshot.binding().target(), snapshot.binding().commitId()) + .orElseThrow(); + if (!snapshot.binding().equals(gameplay.binding())) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_SELECTION_CHANGED"); + for (var entry : snapshot.entries()) + for (var input : entry.config().gameplayInputs()) + if (gameplay.entries().stream() + .noneMatch( + e -> + e.family() == input.family() + && e.definition().key().equals(input.key()) + && e.revisionId().equals(input.revisionId()))) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_INPUT_CHANGED"); + } + + private Optional application( + DraftCommitBinding binding) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_template_config_source_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + if (row == null) return Optional.empty(); + var result = + new TemplateConfigSourceSnapshot.Application( + binding, + row.get("expected_epoch", String.class), + TemplateConfigSourceSnapshot.fromStored(row.get("snapshot_json", String.class))); + if (!binding.requestId().equals(row.get("request_id", UUID.class)) + || !Arrays.equals(result.canonicalBytes(), row.get("result_bytes", byte[].class))) + throw new IllegalStateException("TEMPLATE_CONFIG_APPLICATION_READBACK_CONFLICT"); + var stored = + dsl.fetch( + "SELECT payload_json FROM game_design_template_config_source_revision WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND commit_id = ? ORDER BY revision_order", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()) + .getValues("payload_json", String.class); + if (!stored.equals( + TemplateConfigSource.mutations(binding).stream() + .map(TemplateConfigSource.Mutation::payload) + .toList())) + throw new IllegalStateException("TEMPLATE_CONFIG_REVISION_READBACK_CONFLICT"); + verifyEntries(result.snapshot()); + return Optional.of(result); + } + + private void verifyEntries(TemplateConfigSourceSnapshot snapshot) { + for (var entry : snapshot.entries()) { + exact(entry.sourceBinding()); + requireQualified(snapshot.binding().target(), entry.templateId(), false); + var mutation = + new TemplateConfigSource.Mutation( + entry.sourceBinding(), + entry.revisionOrder(), + entry.revisionId(), + entry.createdName() == null + ? TemplateConfigSource.OperationKind.UPSERT + : TemplateConfigSource.OperationKind.CREATE, + entry.createdName() == null ? entry.templateId() : null, + entry.createdName(), + entry.config()); + var row = + dsl.fetchOne( + "SELECT payload_json FROM game_design_template_config_source_revision WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ? AND revision_id = ? AND revision_order = ? AND template_id = ?", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + entry.sourceBinding().requestId(), + entry.sourceBinding().commitId(), + entry.revisionId(), + Integer.parseInt(entry.revisionOrder()), + Long.parseLong(entry.templateId())); + if (row == null || !mutation.payload().equals(row.get(0, String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_ENTRY_PROVENANCE_CHANGED"); + entry.config().requireAvailableOwnerReads(); + verifyNormalizedReferences(snapshot.binding().target(), entry); + } + } + + private void requireQualified(TargetProof target, String templateId, boolean lock) { + var row = + dsl.fetchOne( + "SELECT t.id, q.request_id, q.commit_id, q.revision_id, q.revision_order, c.binding_json, c.input_digest " + + "FROM game_templates t JOIN game_design_template_config_source_qualification q ON q.template_id = t.id " + + "JOIN game_design_draft_commit c ON c.canonical_tenant_id = q.canonical_tenant_id " + + "AND c.canonical_version_id = q.canonical_version_id AND c.request_id = q.request_id AND c.commit_id = q.commit_id " + + "WHERE t.id = ? AND t.tenant_id = ? AND q.canonical_tenant_id = ? AND q.canonical_version_id = ?" + + (lock ? " FOR UPDATE OF t" : ""), + Long.parseLong(templateId), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId()); + if (row == null) + throw new IllegalStateException("TEMPLATE_CONFIG_TEMPLATE_OWNER_PROVENANCE_UNAVAILABLE"); + var original = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + if (!target.equals(original.target())) + throw new IllegalStateException("TEMPLATE_CONFIG_TEMPLATE_OWNER_PROVENANCE_CHANGED"); + exact(original); + var create = + TemplateConfigSource.mutations(original).stream() + .filter(m -> m.revisionId().equals(row.get("revision_id", UUID.class))) + .filter( + m -> m.revisionOrder().equals(row.get("revision_order", Integer.class).toString())) + .filter(m -> m.operation() == TemplateConfigSource.OperationKind.CREATE) + .findFirst() + .orElseThrow(); + var retained = + dsl.fetchOne( + "SELECT payload_json FROM game_design_template_config_source_revision " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ? AND template_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + create.revisionId(), + Long.parseLong(templateId)); + if (retained == null || !create.payload().equals(retained.get(0, String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_TEMPLATE_CREATE_READBACK_UNAVAILABLE"); + } + + private void requireGameplayInputs( + DraftCommitBinding binding, TemplateConfigSource.Config config) { + var head = + dsl.fetchOne( + "SELECT visible_commit_id, applied_commit_id FROM game_design_gameplay_rule_head " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId()); + if (head == null) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_SOURCE_UNAVAILABLE"); + String json; + if (binding.commitId().equals(head.get("applied_commit_id", UUID.class))) { + var row = + dsl.fetchOne( + "SELECT snapshot_json FROM game_design_gameplay_rule_application " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()); + json = + Objects.requireNonNull(row, "TEMPLATE_CONFIG_GAMEPLAY_APPLICATION_UNAVAILABLE") + .get(0, String.class); + } else { + UUID visible = head.get("visible_commit_id", UUID.class); + var fence = coordinator.readVisibilityFence(binding.target()); + if (visible == null && fence.isEmpty()) { + new GameplayRuleSourceRepository(dsl).readGenesis(binding.target()).orElseThrow(); + if (!config.gameplayInputs().isEmpty()) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_INPUT_UNAVAILABLE"); + return; + } + if (fence.isEmpty() || !Objects.equals(visible, fence.orElseThrow().commitId())) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_SOURCE_NOT_SYNCHRONIZED"); + json = + new GameplayRuleSourceRepository(dsl) + .readSnapshot(binding.target(), visible) + .orElseThrow() + .canonicalJson(); + } + var rules = GameplayRuleSnapshot.fromStored(json); + for (var input : config.gameplayInputs()) + if (rules.entries().stream() + .noneMatch( + e -> + e.family() == input.family() + && e.definition().key().equals(input.key()) + && e.revisionId().equals(input.revisionId()))) + throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_INPUT_UNAVAILABLE"); + } + + private void verifyNormalizedReferences(TargetProof target, TemplateConfigSource.Entry entry) { + var refs = + dsl.fetch( + "SELECT ref_kind, ref_key, referenced_revision_id FROM game_design_template_config_source_ref " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + entry.revisionId()); + var expected = new java.util.HashSet(); + expected.add("BASE_VERSION:" + entry.config().baseVersionId() + ":"); + for (var input : entry.config().gameplayInputs()) + expected.add(input.family().name() + ":" + input.key() + ":" + input.revisionId()); + var actual = new java.util.HashSet(); + for (var ref : refs) + actual.add( + ref.get("ref_kind", String.class) + + ":" + + ref.get("ref_key", String.class) + + ":" + + (ref.get("referenced_revision_id", UUID.class) == null + ? "" + : ref.get("referenced_revision_id", UUID.class))); + if (!expected.equals(actual) || refs.size() != expected.size()) + throw new IllegalStateException("TEMPLATE_CONFIG_NORMALIZED_REFERENCE_READBACK_CONFLICT"); + } + + private Record head(TargetProof target) { + readGenesis(target) + .orElseThrow(() -> new IllegalStateException("TEMPLATE_CONFIG_GENESIS_UNAVAILABLE")); + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM game_design_template_config_source_head WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + target.canonicalTenantId(), + target.canonicalVersionId()), + "TEMPLATE_CONFIG_HEAD_UNAVAILABLE"); + } + + private void exact(DraftCommitBinding binding) { + if (!coordinator + .read(binding.target(), binding.requestId()) + .orElseThrow() + .binding() + .equals(binding)) throw new IllegalStateException("TEMPLATE_CONFIG_BINDING_CHANGED"); + } + + private void requireFence(DraftCommitBinding binding) { + var fence = coordinator.readVisibilityFence(binding.target()).orElseThrow(); + if (!binding.commitId().equals(fence.commitId()) + || !binding.requestId().equals(fence.requestId()) + || !binding.digest().equals(fence.inputDigest()) + || coordinator.read(binding.target(), binding.requestId()).orElseThrow().workflowState() + != DraftCommitCoordinatorRepository.WorkflowState.SYNCHRONIZED) + throw new IllegalStateException("TEMPLATE_CONFIG_SYNCHRONIZED_FENCE_UNAVAILABLE"); + } + + private void open(TargetProof target) { + if (dsl.fetchOne( + "SELECT id FROM version WHERE id = ? AND version_state = 'DRAFT' AND NOT is_script_only " + + "AND base_version_id IS NULL AND script_patch_version IS NULL", + target.gameDesignVersionRowId()) + == null + || dsl.fetchOne( + "SELECT 1 FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId()) + != null) throw new IllegalStateException("TEMPLATE_CONFIG_FROZEN_OR_NOT_DRAFT"); + } + + private void lock(TargetProof target) { + var repository = new net.firedevops.firemud.gamedesign.repository.VersionRepository(dsl); + var qualified = + repository + .findByCanonicalTenantIdAndCanonicalVersionId( + target.canonicalTenantId(), target.canonicalVersionId()) + .orElseThrow(); + var version = + repository + .findByTenantIdAndIdForUpdate( + target.gameDesignVersionTenantKey(), target.gameDesignVersionRowId()) + .orElseThrow(); + var actual = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + if (!target.equals(actual) || !qualified.getId().equals(version.getId())) + throw new IllegalStateException("TEMPLATE_CONFIG_TARGET_CHANGED"); + } + + private static void write() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) + throw new IllegalStateException( + "Template config source requires writable READ_COMMITTED transaction"); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java new file mode 100644 index 0000000000..ed596ee480 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java @@ -0,0 +1,194 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; + +/** Actual template wiring history only; no Game Logic receipt or total-release completeness. */ +public record TemplateConfigSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List entries) { + public static final String SCHEMA = "game-design-template-config-source-snapshot/v1"; + + public TemplateConfigSourceSnapshot { + Objects.requireNonNull(binding); + if (sourceEpoch == null || !sourceEpoch.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Exact template source epoch required"); + DraftAuthorizationFenceBinding.requireUuid(genesisReceiptId); + if (inheritedCommitId != null) DraftAuthorizationFenceBinding.requireUuid(inheritedCommitId); + entries = List.copyOf(entries); + var keys = new java.util.HashSet(); + for (var entry : entries) + if (!entry.sourceBinding().target().equals(binding.target()) || !keys.add(entry.templateId())) + throw new IllegalArgumentException("Template source target or identity conflict"); + if (!entries.equals( + entries.stream() + .sorted(java.util.Comparator.comparing(e -> new BigInteger(e.templateId()))) + .toList())) throw new IllegalArgumentException("Canonical template row order required"); + } + + public String canonicalJson() { + return CommandSource.canonical( + Map.of( + "schema", + SCHEMA, + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptId", + genesisReceiptId.toString(), + "entries", + entries.stream().map(TemplateConfigSource.Entry::object).toList())); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static TemplateConfigSourceSnapshot fromStored(String json) { + var root = CommandSource.tree(json); + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "entries"); + if (!SCHEMA.equals(CommandSource.requiredStoredText(root, "schema")) + || !root.path("entries").isArray()) + throw new IllegalArgumentException("Unsupported template config source snapshot"); + var binding = + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(root, "bindingJson"), + CommandSource.requiredStoredText(root, "bindingDigest")); + List entries = new ArrayList<>(); + for (var node : root.path("entries")) { + CommandSource.requireStoredFields( + node, + "templateId", + "configJson", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId", + "createdName"); + if (!node.path("createdName").isTextual()) + throw new IllegalArgumentException("Explicit source operation identity required"); + String name = node.path("createdName").textValue(); + entries.add( + new TemplateConfigSource.Entry( + CommandSource.requiredStoredText(node, "templateId"), + new TemplateConfigSource.Config(CommandSource.requiredStoredText(node, "configJson")), + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(node, "sourceBindingJson"), + CommandSource.requiredStoredText(node, "sourceBindingDigest")), + CommandSource.requiredStoredText(node, "revisionOrder"), + TemplateConfigSource.uuid(CommandSource.requiredStoredText(node, "revisionId")), + name.isEmpty() ? null : name)); + } + if (!root.path("inheritedCommitId").isTextual()) + throw new IllegalArgumentException("Explicit predecessor required"); + String inherited = root.path("inheritedCommitId").textValue(); + var result = + new TemplateConfigSourceSnapshot( + binding, + CommandSource.requiredStoredText(root, "sourceEpoch"), + inherited.isEmpty() ? null : TemplateConfigSource.uuid(inherited), + TemplateConfigSource.uuid(CommandSource.requiredStoredText(root, "genesisReceiptId")), + entries); + if (!json.equals(result.canonicalJson())) + throw new IllegalArgumentException("Noncanonical template config snapshot"); + return result; + } + + public record Genesis(TargetProof target, UUID receiptId, String creationTransactionId) { + public Genesis { + Objects.requireNonNull(target); + DraftAuthorizationFenceBinding.requireUuid(receiptId); + if (creationTransactionId == null || !creationTransactionId.matches("[1-9][0-9]*")) + throw new IllegalArgumentException( + "Actual fresh template source creation witness required"); + } + } + + public record Application( + DraftCommitBinding binding, String expectedEpoch, TemplateConfigSourceSnapshot snapshot) { + public Application { + Objects.requireNonNull(binding); + if (expectedEpoch == null + || !expectedEpoch.matches("0|[1-9][0-9]*") + || !binding.equals(snapshot.binding()) + || TemplateConfigSource.mutations(binding).isEmpty() + || !new BigInteger(expectedEpoch) + .add(BigInteger.ONE) + .toString() + .equals(snapshot.sourceEpoch())) + throw new IllegalArgumentException( + "Exact template source application must advance its epoch"); + } + + public AppliedEpoch appliedEpoch() { + return new AppliedEpoch( + TemplateConfigSource.SCOPE, + binding.target().canonicalVersionId().toString(), + TemplateConfigSource.SCOPE, + TemplateConfigSource.SCOPE_ID, + expectedEpoch, + snapshot.sourceEpoch()); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + out, "game-design-template-config-source-application/v1"); + DraftAuthorizationFenceBinding.frame(out, expectedEpoch); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + } + + public record Capture( + GameDesignPublicationOperation operation, TemplateConfigSourceSnapshot snapshot) { + public Capture { + Objects.requireNonNull(operation); + Objects.requireNonNull(snapshot); + if (!operation.account().input().selection().selectedCommit().equals(snapshot.binding())) + throw new IllegalArgumentException( + "Template source differs from exact publication selection"); + } + + public byte[] canonicalBytes() { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-template-config-source-capture/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, snapshot.canonicalBytes()); + return out.toByteArray(); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java index baa68c9523..5d1f848f5a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java @@ -122,18 +122,21 @@ public GameTemplate save(GameTemplate template) { .fetchOne(ID); return findByTenantIdAndId(template.getTenantId(), generatedId).orElseThrow(); } - dsl.update(TABLE_REF) - .set(TENANT_ID, template.getTenantId()) - .set(NAME, template.getName()) - .set(DESCRIPTION, template.getDescription()) - .set(CONFIG, jsonbParam(template.getConfig())) - .set(DEFAULT_VERSION_ID, template.getDefaultVersionId()) - .set(DEFAULT_SCRIPT_PATCH_VERSION, template.getDefaultScriptPatchVersion()) - .set(DEFAULT_RUNTIME_FLAGS_JSON, template.getDefaultRuntimeFlagsJson()) - .set(TEMPLATE_REFERENCE_PHASE, template.getTemplateReferencePhase().name()) - .set(CREATED_AT, Timestamp.valueOf(createdAt)) - .where(ID.eq(template.getId())) - .execute(); + int updatedRows = + dsl.update(TABLE_REF) + .set(NAME, template.getName()) + .set(DESCRIPTION, template.getDescription()) + .set(CONFIG, jsonbParam(template.getConfig())) + .set(DEFAULT_VERSION_ID, template.getDefaultVersionId()) + .set(DEFAULT_SCRIPT_PATCH_VERSION, template.getDefaultScriptPatchVersion()) + .set(DEFAULT_RUNTIME_FLAGS_JSON, template.getDefaultRuntimeFlagsJson()) + .set(TEMPLATE_REFERENCE_PHASE, template.getTemplateReferencePhase().name()) + .set(CREATED_AT, Timestamp.valueOf(createdAt)) + .where(ID.eq(template.getId()).and(TENANT_ID.eq(template.getTenantId()))) + .execute(); + if (updatedRows != 1) { + throw new IllegalArgumentException("game template not found for tenant"); + } return findByTenantIdAndId(template.getTenantId(), template.getId()).orElseThrow(); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImpl.java index 04054e31c1..9214fca496 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImpl.java @@ -27,6 +27,10 @@ public class GameTemplateServiceImpl implements GameTemplateService { @Transactional @Timed(value = "gamedesign.template.create") public GameTemplateDto createTemplate(GameTemplateDto dto) { + if (dto.id() != null) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: template id must not be supplied on create"); + } logger.info("Creating game template {}", dto.name()); GameTemplate entity = mapper.toEntity(dto); if (entity.getDefaultRuntimeFlagsJson() == null diff --git a/services/game-design-service/src/main/resources/db/migration/V59__branding_asset_source_history.sql b/services/game-design-service/src/main/resources/db/migration/V59__branding_asset_source_history.sql new file mode 100644 index 0000000000..298efd4b32 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V59__branding_asset_source_history.sql @@ -0,0 +1,495 @@ +-- Branding source only. These records never attest total asset-family completeness. +CREATE TABLE game_design_branding_source_genesis ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + version_id BIGINT NOT NULL UNIQUE, receipt_id UUID NOT NULL UNIQUE, + creation_transaction_id TEXT NOT NULL, target_json TEXT NOT NULL, roles_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (version_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id), + FOREIGN KEY (version_id) REFERENCES game_design_realm_policy_version_insert (version_id), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); +CREATE TABLE game_design_branding_source_application ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, expected_epoch TEXT NOT NULL, + snapshot_json TEXT NOT NULL, result_bytes BYTEA NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), CHECK (octet_length(result_bytes) > 0) +); +CREATE TABLE game_design_branding_source_revision ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, revision_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), operation_kind VARCHAR(16) NOT NULL, + usage_key VARCHAR(255) NOT NULL, role VARCHAR(16) NOT NULL CHECK (role IN ('RESOURCE', 'LOGO', 'FAVICON', 'THEME')), asset_id BIGINT, requiredness VARCHAR(16), + content_type VARCHAR(100), content_digest VARCHAR(71), byte_size BIGINT, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_branding_source_application (canonical_tenant_id, canonical_version_id, commit_id) + DEFERRABLE INITIALLY DEFERRED, + FOREIGN KEY (asset_id) REFERENCES game_assets (id), + CHECK (usage_key !~ '^[[:space:]]*$' AND usage_key <> 'manifest.json'), + CHECK ((operation_kind = 'UPSERT' AND asset_id > 0 AND requiredness = 'REQUIRED' + AND content_type IS NOT NULL AND content_type !~ '^[[:space:]]*$' + AND content_digest ~ '^sha256:[0-9a-f]{64}$' AND byte_size >= 0) + OR (operation_kind = 'DELETE' AND asset_id IS NULL AND requiredness IS NULL + AND content_type IS NULL AND content_digest IS NULL AND byte_size IS NULL)) +); +CREATE TABLE game_design_branding_source_snapshot ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, snapshot_json TEXT NOT NULL, + snapshot_digest VARCHAR(71) NOT NULL CHECK (snapshot_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit_visibility_fence (canonical_tenant_id, canonical_version_id, request_id, commit_id) +); +CREATE TABLE game_design_branding_source_head ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + genesis_receipt_id UUID NOT NULL REFERENCES game_design_branding_source_genesis (receipt_id), + applied_commit_id UUID, visible_commit_id UUID, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_branding_source_genesis (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, applied_commit_id) + REFERENCES game_design_branding_source_application (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_branding_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); +CREATE TABLE game_design_branding_source_capture ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE REFERENCES game_design_publication_operation (publish_workflow_id), + commit_id UUID NOT NULL, operation_bytes BYTEA NOT NULL, capture_bytes BYTEA NOT NULL, + capture_digest VARCHAR(71) NOT NULL CHECK (capture_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_branding_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +-- [jooq ignore start] +CREATE FUNCTION branding_asset_revision_item(r game_design_branding_source_revision) RETURNS JSONB AS $$ + SELECT jsonb_build_object('family', 'BRANDING', 'role', r.role, 'usageKey', r.usage_key, + 'assetRowId', r.asset_id::TEXT, 'requiredness', r.requiredness, + 'sourceBindingJson', c.binding_json, 'sourceBindingDigest', c.input_digest, + 'revisionOrder', r.revision_order::TEXT, 'revisionId', r.revision_id::TEXT, + 'contentType', r.content_type, 'contentDigest', r.content_digest, 'byteSize', r.byte_size::TEXT) + FROM game_design_draft_commit c WHERE c.canonical_tenant_id = r.canonical_tenant_id + AND c.canonical_version_id = r.canonical_version_id AND c.request_id = r.request_id AND c.commit_id = r.commit_id; +$$ LANGUAGE SQL STABLE; + +CREATE FUNCTION guard_branding_asset_source() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; g game_design_branding_source_genesis%ROWTYPE; + h game_design_branding_source_head%ROWTYPE; c game_design_draft_commit%ROWTYPE; + a game_design_branding_source_application%ROWTYPE; op game_design_publication_operation%ROWTYPE; + s game_design_branding_source_snapshot%ROWTYPE; selected game_design_authored_draft_publish_selection%ROWTYPE; + asset game_assets%ROWTYPE; revision JSONB; payload JSONB; prior JSONB; expected_items JSONB; + snapshot JSONB; expected BYTEA; bytes BYTEA; count_declared BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'branding asset source history is immutable' USING ERRCODE = '23514'; END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL OR v.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'branding source requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'game_design_branding_source_genesis' THEN + IF TG_OP <> 'INSERT' OR v.id <> NEW.version_id OR v.version_state_epoch <> 1 + OR NEW.roles_json::JSONB IS DISTINCT FROM '{"RESOURCE":"EMPTY","LOGO":"EMPTY","FAVICON":"EMPTY","THEME":"EMPTY"}'::JSONB + OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_version_insert w WHERE w.version_id = v.id + AND w.creation_transaction_id = NEW.creation_transaction_id) + OR NEW.target_json::JSONB IS DISTINCT FROM jsonb_build_object( + 'canonicalTenantId', v.canonical_tenant_id::TEXT, 'canonicalVersionId', v.canonical_version_id::TEXT, + 'gameDesignVersionRowId', v.id, 'gameDesignVersionTenantKey', v.tenant_id, + 'sourceGameRowId', v.identity_source_game_row_id, + 'sourceGameTenantKey', v.identity_source_game_tenant_key, 'sourceProvenanceKind', v.identity_source_provenance_kind) + OR EXISTS (SELECT 1 FROM version_asset va WHERE va.tenant_id = v.tenant_id AND va.version_id = v.id) + OR EXISTS (SELECT 1 FROM game_design_draft_commit c0 WHERE c0.canonical_tenant_id = NEW.canonical_tenant_id AND c0.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'branding genesis requires its actual fresh Version insertion' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT g FROM game_design_branding_source_genesis WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF TG_TABLE_NAME = 'game_design_branding_source_head' AND TG_OP = 'INSERT' THEN + IF NEW.source_epoch <> '0' OR NEW.applied_commit_id IS NOT NULL OR NEW.visible_commit_id IS NOT NULL OR NEW.genesis_receipt_id <> g.receipt_id THEN + RAISE EXCEPTION 'branding head requires exact fresh baseline' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT h FROM game_design_branding_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF TG_TABLE_NAME <> 'game_design_branding_source_capture' AND ( + EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id)) THEN + RAISE EXCEPTION 'branding source is frozen by selected publication or export' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_branding_source_head' THEN + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.genesis_receipt_id IS DISTINCT FROM OLD.genesis_receipt_id THEN + RAISE EXCEPTION 'branding head identity immutable' USING ERRCODE = '23514'; END IF; + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + SELECT * INTO STRICT a FROM game_design_branding_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.applied_commit_id; + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 OR a.expected_epoch <> OLD.source_epoch + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN RAISE EXCEPTION 'branding staged epoch mismatch' USING ERRCODE = '23514'; END IF; + ELSIF NEW.applied_commit_id IS DISTINCT FROM OLD.applied_commit_id THEN RAISE EXCEPTION 'branding staged pointer mismatch' USING ERRCODE = '23514'; END IF; + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + SELECT * INTO STRICT s FROM game_design_branding_source_snapshot WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.visible_commit_id; + IF s.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR s.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(OLD.visible_commit_id::TEXT, '') THEN + RAISE EXCEPTION 'branding visible pointer mismatch' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'branding source history is immutable' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_branding_source_capture' THEN + SELECT * INTO STRICT op FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selected FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT s FROM game_design_branding_source_snapshot WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-branding-asset-source-capture/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + expected := expected || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + bytes := convert_to(s.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF op.outcome <> 'PENDING' OR op.request_bytes IS DISTINCT FROM NEW.operation_bytes OR op.version_id <> v.id OR op.tenant_id <> v.tenant_id + OR op.selection_digest <> selected.selection_digest OR selected.selected_commit_id <> NEW.commit_id + OR selected.version_state_epoch <> v.version_state_epoch OR h.visible_commit_id IS DISTINCT FROM NEW.commit_id + OR h.source_epoch IS DISTINCT FROM s.snapshot_json::JSONB->>'sourceEpoch' + OR expected IS DISTINCT FROM NEW.capture_bytes OR NEW.capture_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.capture_bytes), 'hex') THEN + RAISE EXCEPTION 'branding capture lacks exact selected operation/source' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF TG_TABLE_NAME IN ('game_design_branding_source_revision', 'game_design_branding_source_application') THEN + IF NOT EXISTS (SELECT 1 FROM game_design_draft_commit_application_slot slot WHERE slot.canonical_tenant_id = NEW.canonical_tenant_id AND slot.canonical_version_id = NEW.canonical_version_id AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_owner_result r WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id AND r.request_id = NEW.request_id AND r.owner = 'GAME_DESIGN_CONTROL_PLANE' AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'branding source write requires active coordinator application' USING ERRCODE = '23514'; END IF; + END IF; + IF TG_TABLE_NAME = 'game_design_branding_source_revision' THEN + SELECT r INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r WHERE r->>'revisionId' = NEW.revision_id::TEXT AND r->>'revisionOrder' = NEW.revision_order::TEXT AND r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + payload := (revision->>'payload')::JSONB; + IF (SELECT count(*) FROM json_object_keys((revision->>'payload')::JSON)) <> + (SELECT count(*) FROM jsonb_object_keys(payload)) + OR (revision->>'payload')::JSON->>'schemaVersion' IS DISTINCT FROM '1' + OR payload->>'revisionKind' IS DISTINCT FROM 'BRANDING_ASSET_REFERENCE' OR payload->'schemaVersion' IS DISTINCT FROM '1'::JSONB + OR payload->>'family' IS DISTINCT FROM 'BRANDING' OR payload->>'role' IS DISTINCT FROM NEW.role + OR payload->>'operation' IS DISTINCT FROM NEW.operation_kind OR payload->>'usageKey' IS DISTINCT FROM NEW.usage_key + OR jsonb_typeof(payload->'usageKey') IS DISTINCT FROM 'string' THEN RAISE EXCEPTION 'branding revision differs from exact payload' USING ERRCODE = '23514'; END IF; + IF NEW.operation_kind = 'UPSERT' THEN + SELECT * INTO STRICT asset FROM game_assets WHERE id = NEW.asset_id AND tenant_id = v.tenant_id FOR UPDATE; + IF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 8 OR jsonb_typeof(payload->'assetRowId') IS DISTINCT FROM 'string' + OR payload->>'assetRowId' IS DISTINCT FROM NEW.asset_id::TEXT OR payload->>'requiredness' IS DISTINCT FROM 'REQUIRED' + OR NEW.requiredness IS DISTINCT FROM 'REQUIRED' OR asset.file_name IS DISTINCT FROM NEW.usage_key + OR asset.content_type IS DISTINCT FROM NEW.content_type OR asset.data IS NULL + OR NEW.content_digest IS DISTINCT FROM 'sha256:' || encode(sha256(asset.data), 'hex') OR NEW.byte_size IS DISTINCT FROM octet_length(asset.data)::BIGINT THEN + RAISE EXCEPTION 'branding RESOURCE requires exact required source bytes' USING ERRCODE = '23514'; END IF; + ELSIF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 6 THEN RAISE EXCEPTION 'branding DELETE fields invalid' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + snapshot := NEW.snapshot_json::JSONB; + IF snapshot->>'schema' IS DISTINCT FROM 'game-design-branding-asset-source-snapshot/v1' + OR snapshot->>'bindingJson' IS DISTINCT FROM c.binding_json OR snapshot->>'bindingDigest' IS DISTINCT FROM c.input_digest + OR snapshot->>'genesisReceiptId' IS DISTINCT FROM g.receipt_id::TEXT + OR snapshot->>'inheritedCommitId' IS DISTINCT FROM coalesce(h.visible_commit_id::TEXT, '') + OR jsonb_typeof(snapshot->'items') IS DISTINCT FROM 'array' + OR (SELECT count(*) FROM jsonb_object_keys(snapshot)) <> 8 THEN RAISE EXCEPTION 'branding snapshot binding invalid' USING ERRCODE = '23514'; END IF; + IF snapshot->'roles' IS DISTINCT FROM ( + SELECT jsonb_object_agg(role, CASE WHEN EXISTS ( + SELECT 1 FROM jsonb_array_elements(snapshot->'items') item WHERE item->>'role' = role + ) THEN 'PRESENT' ELSE 'EMPTY' END) + FROM unnest(ARRAY['RESOURCE', 'LOGO', 'FAVICON', 'THEME']) role + ) THEN RAISE EXCEPTION 'branding snapshot requires every explicit role declaration' USING ERRCODE = '23514'; END IF; + SELECT s0.snapshot_json::JSONB->'items' INTO prior FROM game_design_branding_source_snapshot s0 WHERE s0.canonical_tenant_id = NEW.canonical_tenant_id AND s0.canonical_version_id = NEW.canonical_version_id AND s0.commit_id = h.visible_commit_id; + prior := coalesce(prior, '[]'::JSONB); + IF TG_TABLE_NAME = 'game_design_branding_source_application' THEN + IF NEW.expected_epoch IS DISTINCT FROM h.source_epoch OR snapshot->>'sourceEpoch' IS DISTINCT FROM (h.source_epoch::NUMERIC + 1)::TEXT + OR NOT (c.binding_json::JSONB->'affectedUnits' @> jsonb_build_array(jsonb_build_object('owner', 'GAME_DESIGN_CONTROL_PLANE', + 'aggregateType', 'BRANDING_ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, + 'scopeType', 'BRANDING_ASSET_REFERENCE_SET', 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch))) THEN + RAISE EXCEPTION 'branding application lacks exact scope epoch' USING ERRCODE = '23514'; END IF; + WITH choices AS ( + SELECT item->>'usageKey' AS key, -1 AS ord, FALSE AS deleted, item FROM jsonb_array_elements(prior) item + UNION ALL SELECT r.usage_key, r.revision_order, r.operation_kind = 'DELETE', branding_asset_revision_item(r) + FROM game_design_branding_source_revision r WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id AND r.commit_id = NEW.commit_id + ), final AS (SELECT DISTINCT ON (key) * FROM choices ORDER BY key, ord DESC) + SELECT coalesce(jsonb_agg(item ORDER BY convert_to(key, 'UTF8')) FILTER (WHERE NOT deleted), '[]'::JSONB) INTO expected_items FROM final; + IF expected_items IS DISTINCT FROM snapshot->'items' + OR (SELECT count(DISTINCT item->>'assetRowId') FROM jsonb_array_elements(expected_items) item) <> jsonb_array_length(expected_items) THEN + RAISE EXCEPTION 'branding application must replay exact source without aliases' USING ERRCODE = '23514'; END IF; + ELSE + SELECT * INTO a FROM game_design_branding_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT count(*) INTO count_declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r WHERE r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (r->>'payload')::JSONB->>'revisionKind' = 'BRANDING_ASSET_REFERENCE'; + IF (count_declared > 0) IS DISTINCT FROM (a.commit_id IS NOT NULL) + OR snapshot->>'sourceEpoch' IS DISTINCT FROM h.source_epoch + OR (a.commit_id IS NOT NULL AND a.snapshot_json IS DISTINCT FROM NEW.snapshot_json) + OR (a.commit_id IS NULL AND snapshot->'items' IS DISTINCT FROM prior) + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR c.workflow_state <> 'SYNCHRONIZED' + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility f WHERE f.canonical_tenant_id = NEW.canonical_tenant_id AND f.canonical_version_id = NEW.canonical_version_id AND f.request_id = NEW.request_id AND f.commit_id = NEW.commit_id AND f.input_digest = c.input_digest) THEN + RAISE EXCEPTION 'branding snapshot requires exact synchronized source inheritance' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION verify_branding_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_branding_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + gameplay_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT r FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT h FROM game_design_branding_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'BRANDING_ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_branding_source_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-branding-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'branding application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'GAMEPLAY_RULE' AND gameplay_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'branding mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'branding combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'branding scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + IF gameplay_bytes IS NOT NULL THEN bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; END IF; + bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'branding owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION verify_gameplay_rule_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_gameplay_rule_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + branding_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT r FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT h FROM game_design_gameplay_rule_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE'; + SELECT count(*) INTO retained FROM game_design_gameplay_rule_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-gameplay-rule-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'gameplay application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO branding_bytes FROM game_design_branding_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'BRANDING_ASSET_REFERENCE' AND branding_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'gameplay mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'gameplay combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'gameplay scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'gameplay owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION verify_ordinary_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_asset_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; declared BIGINT; retained BIGINT; + components BYTEA; command_bytes BYTEA; policy_bytes BYTEA; gameplay_bytes BYTEA; branding_bytes BYTEA; epochs JSONB; unit JSONB; +BEGIN + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT r FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT h FROM game_design_asset_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_asset_source_revision x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id AND x.commit_id = NEW.commit_id; + bytes := convert_to('game-design-ordinary-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR r.status <> 'APPLIED' OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id + OR expected IS DISTINCT FROM NEW.result_bytes OR NOT (r.applied_units_json::JSONB @> jsonb_build_array(jsonb_build_object( + 'aggregateType', 'ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, 'scopeType', 'ASSET_REFERENCE_SET', + 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch, 'resultingEpoch', h.source_epoch))) THEN + RAISE EXCEPTION 'ordinary application requires atomic combined owner outcome' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); + components := int4send(octet_length(bytes)) || bytes; + epochs := '[]'::JSONB; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF command_bytes IS NOT NULL THEN + bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; + END IF; + bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + SELECT result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF gameplay_bytes IS NOT NULL THEN + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; + END IF; + SELECT result_bytes INTO branding_bytes FROM game_design_branding_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + SELECT result_bytes INTO policy_bytes FROM game_design_realm_policy_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND coalesce((x->>'payload')::JSONB->>'revisionKind', '') NOT IN ('COMMAND_DEFINITION', 'REALM_ENTRY_POLICY', 'ASSET_REFERENCE', 'GAMEPLAY_RULE', 'BRANDING_ASSET_REFERENCE')) + OR (branding_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'BRANDING_ASSET_REFERENCE') + OR (command_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION') + OR (policy_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'REALM_ENTRY_POLICY') THEN + RAISE EXCEPTION 'ordinary mixed application requires every declared supported sibling source' USING ERRCODE = '23514'; END IF; + IF (gameplay_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE') THEN + RAISE EXCEPTION 'ordinary mixed application lacks exact declared gameplay source' USING ERRCODE = '23514'; END IF; + -- The vector has one entry per exact declared local scope, ordered as the Java composition. + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' + LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' + OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'ordinary combined scope unknown' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); + expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs + OR jsonb_array_length(epochs) <> (1 + CASE WHEN command_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN policy_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN gameplay_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN branding_bytes IS NULL THEN 0 ELSE 1 END) THEN + RAISE EXCEPTION 'ordinary combined outcome must contain exact tagged components and complete epochs' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER branding_asset_genesis_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_genesis FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE TRIGGER branding_asset_head_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_head FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE TRIGGER branding_asset_revision_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_revision FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE TRIGGER branding_asset_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_application FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE TRIGGER branding_asset_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_snapshot FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE TRIGGER branding_asset_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_branding_source_capture FOR EACH ROW EXECUTE FUNCTION guard_branding_asset_source(); +CREATE CONSTRAINT TRIGGER branding_asset_application_commit_guard AFTER INSERT ON game_design_branding_source_application DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_branding_asset_application_commit(); +CREATE FUNCTION protect_branding_asset_bytes() RETURNS TRIGGER AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_design_branding_source_revision r WHERE r.asset_id = OLD.id) AND + (TG_OP = 'DELETE' OR NEW IS DISTINCT FROM OLD) THEN + RAISE EXCEPTION 'branding asset source bytes are immutable from source history' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER branding_asset_byte_history_guard BEFORE UPDATE OR DELETE ON game_assets FOR EACH ROW EXECUTE FUNCTION protect_branding_asset_bytes(); + +CREATE FUNCTION deny_branding_asset_truncate() RETURNS TRIGGER AS $$ +BEGIN RAISE EXCEPTION 'branding source history cannot be truncated' USING ERRCODE = '23514'; END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER branding_asset_genesis_no_truncate BEFORE TRUNCATE ON game_design_branding_source_genesis EXECUTE FUNCTION deny_branding_asset_truncate(); +CREATE TRIGGER branding_asset_head_no_truncate BEFORE TRUNCATE ON game_design_branding_source_head EXECUTE FUNCTION deny_branding_asset_truncate(); +CREATE TRIGGER branding_asset_revision_no_truncate BEFORE TRUNCATE ON game_design_branding_source_revision EXECUTE FUNCTION deny_branding_asset_truncate(); +CREATE TRIGGER branding_asset_application_no_truncate BEFORE TRUNCATE ON game_design_branding_source_application EXECUTE FUNCTION deny_branding_asset_truncate(); +CREATE TRIGGER branding_asset_snapshot_no_truncate BEFORE TRUNCATE ON game_design_branding_source_snapshot EXECUTE FUNCTION deny_branding_asset_truncate(); +CREATE TRIGGER branding_asset_capture_no_truncate BEFORE TRUNCATE ON game_design_branding_source_capture EXECUTE FUNCTION deny_branding_asset_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V60__template_config_source_history.sql b/services/game-design-service/src/main/resources/db/migration/V60__template_config_source_history.sql new file mode 100644 index 0000000000..e9a2e29735 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V60__template_config_source_history.sql @@ -0,0 +1,870 @@ +-- Template/config authored source only. These records never attest total asset-family completeness. +CREATE TABLE game_design_template_config_source_genesis ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + version_id BIGINT NOT NULL UNIQUE, receipt_id UUID NOT NULL UNIQUE, + creation_transaction_id TEXT NOT NULL, target_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (version_id, canonical_tenant_id, canonical_version_id) + REFERENCES version (id, canonical_tenant_id, canonical_version_id), + FOREIGN KEY (version_id) REFERENCES game_design_realm_policy_version_insert (version_id), + CHECK (receipt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_transaction_id ~ '^[1-9][0-9]*$') +); +CREATE TABLE game_design_template_config_source_application ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, expected_epoch TEXT NOT NULL, + snapshot_json TEXT NOT NULL, result_bytes BYTEA NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + CHECK (expected_epoch ~ '^(0|[1-9][0-9]*)$'), CHECK (octet_length(result_bytes) > 0) +); +CREATE TABLE game_design_template_config_source_revision ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, revision_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), operation_kind VARCHAR(16) NOT NULL, + template_id BIGINT NOT NULL REFERENCES game_templates (id), payload_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_template_config_source_application (canonical_tenant_id, canonical_version_id, commit_id) + DEFERRABLE INITIALLY DEFERRED, + CHECK (operation_kind IN ('CREATE', 'UPSERT', 'DELETE')) +); +CREATE TABLE game_design_template_config_source_snapshot ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, snapshot_json TEXT NOT NULL, + snapshot_digest VARCHAR(71) NOT NULL CHECK (snapshot_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit_visibility_fence (canonical_tenant_id, canonical_version_id, request_id, commit_id) +); +CREATE TABLE game_design_template_config_source_head ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + source_epoch TEXT NOT NULL CHECK (source_epoch ~ '^(0|[1-9][0-9]*)$'), + genesis_receipt_id UUID NOT NULL REFERENCES game_design_template_config_source_genesis (receipt_id), + applied_commit_id UUID, visible_commit_id UUID, + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_template_config_source_genesis (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, applied_commit_id) + REFERENCES game_design_template_config_source_application (canonical_tenant_id, canonical_version_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, visible_commit_id) + REFERENCES game_design_template_config_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); +CREATE TABLE game_design_template_config_source_capture ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL UNIQUE REFERENCES game_design_publication_operation (publish_workflow_id), + commit_id UUID NOT NULL, operation_bytes BYTEA NOT NULL, capture_bytes BYTEA NOT NULL, + capture_digest VARCHAR(71) NOT NULL CHECK (capture_digest ~ '^sha256:[0-9a-f]{64}$'), + PRIMARY KEY (canonical_tenant_id, canonical_version_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_template_config_source_snapshot (canonical_tenant_id, canonical_version_id, commit_id) +); + +CREATE TABLE game_design_template_config_source_qualification ( + template_id BIGINT PRIMARY KEY REFERENCES game_templates (id), + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, commit_id UUID NOT NULL, revision_id UUID NOT NULL, revision_order INTEGER NOT NULL, + UNIQUE (canonical_tenant_id, canonical_version_id, revision_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, revision_id) + REFERENCES game_design_template_config_source_revision (canonical_tenant_id, canonical_version_id, revision_id) + DEFERRABLE INITIALLY DEFERRED +); +CREATE TABLE game_design_template_config_source_ref ( + canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, revision_id UUID NOT NULL, + ref_kind VARCHAR(64) NOT NULL, ref_key VARCHAR(128) NOT NULL, referenced_revision_id UUID, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id, ref_kind, ref_key), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, revision_id) + REFERENCES game_design_template_config_source_revision (canonical_tenant_id, canonical_version_id, revision_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, referenced_revision_id) + REFERENCES game_design_gameplay_rule_revision (canonical_tenant_id, canonical_version_id, revision_id), + CHECK ((ref_kind = 'BASE_VERSION' AND referenced_revision_id IS NULL AND ref_key = canonical_version_id::TEXT) + OR (ref_kind <> 'BASE_VERSION' AND referenced_revision_id IS NOT NULL)) +); +CREATE TABLE game_design_template_config_source_row_insert ( + template_id BIGINT PRIMARY KEY, creation_transaction_id TEXT NOT NULL +); +-- [jooq ignore start] +CREATE FUNCTION template_config_unique_json(value JSON) RETURNS BOOLEAN AS $$ +DECLARE field RECORD; element JSON; +BEGIN + IF json_typeof(value) = 'object' THEN + IF (SELECT count(*) FROM json_each(value)) <> (SELECT count(DISTINCT key) FROM json_each(value)) THEN RETURN FALSE; END IF; + FOR field IN SELECT * FROM json_each(value) LOOP + IF NOT template_config_unique_json(field.value) THEN RETURN FALSE; END IF; + END LOOP; + ELSIF json_typeof(value) = 'array' THEN + FOR element IN SELECT * FROM json_array_elements(value) LOOP + IF NOT template_config_unique_json(element) THEN RETURN FALSE; END IF; + END LOOP; + END IF; + RETURN TRUE; +END; +$$ LANGUAGE plpgsql IMMUTABLE; + +CREATE FUNCTION template_config_supported(config_json TEXT, base_id UUID) RETURNS BOOLEAN AS $$ +DECLARE cfg JSONB := config_json::JSONB; input JSONB; +BEGIN + IF NOT template_config_unique_json(config_json::JSON) + OR (SELECT count(*) FROM jsonb_object_keys(cfg)) <> 7 + OR config_json::JSON->>'schemaVersion' IS DISTINCT FROM '1' + OR cfg->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR cfg->>'baseVersionId' IS DISTINCT FROM base_id::TEXT + OR (SELECT count(*) FROM jsonb_object_keys(cfg->'world')) <> 2 + OR cfg->'world'->'regions' IS DISTINCT FROM '[]'::JSONB OR cfg->'world'->'rooms' IS DISTINCT FROM '[]'::JSONB + OR (SELECT count(*) FROM jsonb_object_keys(cfg->'entity')) <> 2 + OR cfg->'entity'->'items' IS DISTINCT FROM '[]'::JSONB OR cfg->'entity'->'npcs' IS DISTINCT FROM '[]'::JSONB + OR (SELECT count(*) FROM jsonb_object_keys(cfg->'automation')) <> 2 + OR cfg->'automation'->'scripts' IS DISTINCT FROM '[]'::JSONB + OR cfg->'automation'->'scriptPatch' IS DISTINCT FROM '{"presence":"ABSENT"}'::JSONB + OR cfg->'supportedSettings' IS DISTINCT FROM '[]'::JSONB + OR (SELECT count(*) FROM jsonb_object_keys(cfg->'gameLogic')) <> 1 + OR jsonb_typeof(cfg->'gameLogic'->'inputs') IS DISTINCT FROM 'array' THEN RETURN FALSE; END IF; + FOR input IN SELECT * FROM jsonb_array_elements(cfg->'gameLogic'->'inputs') LOOP + IF (SELECT count(*) FROM jsonb_object_keys(input)) <> 3 + OR NOT (input->>'family' = ANY(gameplay_rule_families())) + OR jsonb_typeof(input->'family') IS DISTINCT FROM 'string' + OR jsonb_typeof(input->'key') IS DISTINCT FROM 'string' + OR (input->>'key') !~ '^[A-Za-z][A-Za-z0-9_.:-]{0,127}$' + OR jsonb_typeof(input->'revisionId') IS DISTINCT FROM 'string' + OR input->>'revisionId' IS DISTINCT FROM ((input->>'revisionId')::UUID)::TEXT + OR (input->>'revisionId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID THEN RETURN FALSE; END IF; + END LOOP; + RETURN (SELECT count(*) FROM jsonb_array_elements(cfg->'gameLogic'->'inputs')) = + (SELECT count(DISTINCT (x->>'family', x->>'key')) FROM jsonb_array_elements(cfg->'gameLogic'->'inputs') x); +END; +$$ LANGUAGE plpgsql IMMUTABLE; + +CREATE FUNCTION template_config_revision_item(r game_design_template_config_source_revision) RETURNS JSONB AS $$ + SELECT jsonb_build_object('templateId', r.template_id::TEXT, 'configJson', r.payload_json::JSONB->>'configJson', + 'sourceBindingJson', c.binding_json, 'sourceBindingDigest', c.input_digest, + 'revisionOrder', r.revision_order::TEXT, 'revisionId', r.revision_id::TEXT, + 'createdName', CASE WHEN r.operation_kind = 'CREATE' THEN r.payload_json::JSONB->>'templateName' ELSE '' END) + FROM game_design_draft_commit c WHERE c.canonical_tenant_id = r.canonical_tenant_id + AND c.canonical_version_id = r.canonical_version_id AND c.request_id = r.request_id AND c.commit_id = r.commit_id; +$$ LANGUAGE SQL STABLE; + +CREATE FUNCTION template_config_selected_inputs(snapshot JSONB, p_tenant UUID, p_version UUID, p_commit UUID) RETURNS BOOLEAN AS $$ +DECLARE gameplay game_design_gameplay_rule_snapshot%ROWTYPE; entry JSONB; input JSONB; +BEGIN + SELECT * INTO STRICT gameplay FROM game_design_gameplay_rule_snapshot WHERE canonical_tenant_id = p_tenant + AND canonical_version_id = p_version AND commit_id = p_commit; + IF gameplay.snapshot_json::JSONB->>'bindingJson' IS DISTINCT FROM snapshot->>'bindingJson' THEN RETURN FALSE; END IF; + FOR entry IN SELECT * FROM jsonb_array_elements(snapshot->'entries') LOOP + FOR input IN SELECT * FROM jsonb_array_elements((entry->>'configJson')::JSONB->'gameLogic'->'inputs') LOOP + IF NOT EXISTS (SELECT 1 FROM jsonb_array_elements(gameplay.snapshot_json::JSONB->'entries') e + WHERE e->>'family' = input->>'family' AND e->>'revisionId' = input->>'revisionId' + AND gameplay_rule_definition_key(e->>'family', (e->>'definitionJson')::JSONB) = input->>'key') THEN RETURN FALSE; END IF; + END LOOP; + END LOOP; + RETURN TRUE; +END; +$$ LANGUAGE plpgsql STABLE; +CREATE FUNCTION template_config_current_inventory(p_tenant UUID, p_version UUID, p_private_version BIGINT, + p_legacy_tenant TEXT, snapshot JSONB) RETURNS BOOLEAN AS $$ + SELECT NOT EXISTS ( + SELECT 1 FROM game_templates t + LEFT JOIN game_design_template_config_source_qualification q ON q.template_id = t.id + AND q.canonical_tenant_id = p_tenant AND q.canonical_version_id = p_version + LEFT JOIN LATERAL ( + SELECT r.operation_kind FROM game_design_template_config_source_revision r + JOIN game_design_template_config_source_application a ON a.canonical_tenant_id = r.canonical_tenant_id + AND a.canonical_version_id = r.canonical_version_id AND a.commit_id = r.commit_id + WHERE r.canonical_tenant_id = p_tenant AND r.canonical_version_id = p_version AND r.template_id = t.id + ORDER BY a.expected_epoch::NUMERIC DESC, r.revision_order DESC LIMIT 1 + ) latest ON TRUE + WHERE t.tenant_id = p_legacy_tenant AND t.default_version_id = p_private_version + AND (q.template_id IS NULL OR (latest.operation_kind IS DISTINCT FROM 'DELETE' + AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(snapshot->'entries') e WHERE e->>'templateId' = t.id::TEXT))) + ); +$$ LANGUAGE SQL STABLE; + +CREATE FUNCTION guard_template_config_source() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; g game_design_template_config_source_genesis%ROWTYPE; + h game_design_template_config_source_head%ROWTYPE; c game_design_draft_commit%ROWTYPE; + a game_design_template_config_source_application%ROWTYPE; op game_design_publication_operation%ROWTYPE; + s game_design_template_config_source_snapshot%ROWTYPE; selected game_design_authored_draft_publish_selection%ROWTYPE; + template game_templates%ROWTYPE; revision JSONB; payload JSONB; prior JSONB; expected_items JSONB; + snapshot JSONB; expected BYTEA; bytes BYTEA; count_declared BIGINT; +BEGIN + IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'template config source history is immutable' USING ERRCODE = '23514'; END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL OR v.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'template config source requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'game_design_template_config_source_genesis' THEN + IF TG_OP <> 'INSERT' OR v.id <> NEW.version_id OR v.version_state_epoch <> 1 + OR NEW.creation_transaction_id <> pg_current_xact_id()::TEXT + OR NOT EXISTS (SELECT 1 FROM game_design_realm_policy_version_insert w WHERE w.version_id = v.id + AND w.creation_transaction_id = NEW.creation_transaction_id) + OR NEW.target_json::JSONB IS DISTINCT FROM jsonb_build_object( + 'canonicalTenantId', v.canonical_tenant_id::TEXT, 'canonicalVersionId', v.canonical_version_id::TEXT, + 'gameDesignVersionRowId', v.id, 'gameDesignVersionTenantKey', v.tenant_id, + 'sourceGameRowId', v.identity_source_game_row_id, + 'sourceGameTenantKey', v.identity_source_game_tenant_key, 'sourceProvenanceKind', v.identity_source_provenance_kind) + OR EXISTS (SELECT 1 FROM version_asset va WHERE va.tenant_id = v.tenant_id AND va.version_id = v.id) + OR EXISTS (SELECT 1 FROM game_design_draft_commit c0 WHERE c0.canonical_tenant_id = NEW.canonical_tenant_id AND c0.canonical_version_id = NEW.canonical_version_id) THEN + RAISE EXCEPTION 'template config genesis requires its actual fresh Version insertion' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT g FROM game_design_template_config_source_genesis WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + IF TG_TABLE_NAME = 'game_design_template_config_source_head' AND TG_OP = 'INSERT' THEN + IF NEW.source_epoch <> '0' OR NEW.applied_commit_id IS NOT NULL OR NEW.visible_commit_id IS NOT NULL OR NEW.genesis_receipt_id <> g.receipt_id THEN + RAISE EXCEPTION 'template config head requires exact fresh baseline' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT h FROM game_design_template_config_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF TG_TABLE_NAME <> 'game_design_template_config_source_capture' AND ( + EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id)) THEN + RAISE EXCEPTION 'template config source is frozen by selected publication or export' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_template_config_source_head' THEN + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.genesis_receipt_id IS DISTINCT FROM OLD.genesis_receipt_id THEN + RAISE EXCEPTION 'template config head identity immutable' USING ERRCODE = '23514'; END IF; + IF NEW.source_epoch IS DISTINCT FROM OLD.source_epoch THEN + SELECT * INTO STRICT a FROM game_design_template_config_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.applied_commit_id; + IF NEW.source_epoch::NUMERIC <> OLD.source_epoch::NUMERIC + 1 OR a.expected_epoch <> OLD.source_epoch + OR NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN RAISE EXCEPTION 'template config staged epoch mismatch' USING ERRCODE = '23514'; END IF; + ELSIF NEW.applied_commit_id IS DISTINCT FROM OLD.applied_commit_id THEN RAISE EXCEPTION 'template config staged pointer mismatch' USING ERRCODE = '23514'; END IF; + IF NEW.visible_commit_id IS DISTINCT FROM OLD.visible_commit_id THEN + SELECT * INTO STRICT s FROM game_design_template_config_source_snapshot WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.visible_commit_id; + IF s.snapshot_json::JSONB->>'sourceEpoch' IS DISTINCT FROM NEW.source_epoch + OR s.snapshot_json::JSONB->>'inheritedCommitId' IS DISTINCT FROM coalesce(OLD.visible_commit_id::TEXT, '') THEN + RAISE EXCEPTION 'template config visible pointer mismatch' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; + END IF; + IF TG_OP <> 'INSERT' THEN RAISE EXCEPTION 'template config source history is immutable' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_template_config_source_capture' THEN + SELECT * INTO STRICT op FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + SELECT * INTO STRICT selected FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT s FROM game_design_template_config_source_snapshot WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-template-config-source-capture/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + expected := expected || int4send(octet_length(NEW.operation_bytes)) || NEW.operation_bytes; + bytes := convert_to(s.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF op.outcome <> 'PENDING' OR op.request_bytes IS DISTINCT FROM NEW.operation_bytes OR op.version_id <> v.id OR op.tenant_id <> v.tenant_id + OR op.selection_digest <> selected.selection_digest OR selected.selected_commit_id <> NEW.commit_id + OR selected.version_state_epoch <> v.version_state_epoch OR h.visible_commit_id IS DISTINCT FROM NEW.commit_id + OR h.source_epoch IS DISTINCT FROM s.snapshot_json::JSONB->>'sourceEpoch' + OR NOT template_config_selected_inputs(s.snapshot_json::JSONB, NEW.canonical_tenant_id, NEW.canonical_version_id, NEW.commit_id) + OR NOT template_config_current_inventory(NEW.canonical_tenant_id, NEW.canonical_version_id, v.id, v.tenant_id, s.snapshot_json::JSONB) + OR EXISTS (SELECT 1 FROM jsonb_array_elements(s.snapshot_json::JSONB->'entries') e + LEFT JOIN game_templates t ON t.id = (e->>'templateId')::BIGINT AND t.tenant_id = v.tenant_id + WHERE t.id IS NULL OR t.config IS DISTINCT FROM (e->>'configJson')::JSONB + OR t.default_version_id IS DISTINCT FROM v.id OR t.default_script_patch_version IS NOT NULL + OR t.default_runtime_flags_json::JSONB IS DISTINCT FROM '{}'::JSONB) + OR expected IS DISTINCT FROM NEW.capture_bytes OR NEW.capture_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.capture_bytes), 'hex') THEN + RAISE EXCEPTION 'template config capture lacks exact selected operation/source' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF TG_TABLE_NAME IN ('game_design_template_config_source_qualification', 'game_design_template_config_source_revision', 'game_design_template_config_source_application') THEN + IF NOT EXISTS (SELECT 1 FROM game_design_draft_commit_application_slot slot WHERE slot.canonical_tenant_id = NEW.canonical_tenant_id AND slot.canonical_version_id = NEW.canonical_version_id AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_owner_result r WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id AND r.request_id = NEW.request_id AND r.owner = 'GAME_DESIGN_CONTROL_PLANE' AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'template config source write requires active coordinator application' USING ERRCODE = '23514'; END IF; + END IF; + IF TG_TABLE_NAME IN ('game_design_template_config_source_qualification', 'game_design_template_config_source_revision') THEN + SELECT r INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r + WHERE r->>'revisionId' = NEW.revision_id::TEXT AND r->>'revisionOrder' = NEW.revision_order::TEXT + AND r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + payload := (revision->>'payload')::JSONB; + SELECT * INTO STRICT template FROM game_templates WHERE id = NEW.template_id AND tenant_id = v.tenant_id FOR UPDATE; + IF NOT template_config_unique_json((revision->>'payload')::JSON) + OR (revision->>'payload')::JSON->>'schemaVersion' IS DISTINCT FROM '1' + OR payload->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR payload->>'revisionKind' IS DISTINCT FROM 'TEMPLATE_CONFIG' THEN + RAISE EXCEPTION 'template revision requires closed exact owner payload' USING ERRCODE = '23514'; END IF; + IF TG_TABLE_NAME = 'game_design_template_config_source_qualification' THEN + IF payload->>'operation' IS DISTINCT FROM 'CREATE' OR template.name IS DISTINCT FROM payload->>'templateName' + OR template.config IS DISTINCT FROM (payload->>'configJson')::JSONB OR template.default_version_id IS DISTINCT FROM v.id + OR template.template_reference_phase IS DISTINCT FROM 'LEGACY' + OR template.default_script_patch_version IS NOT NULL OR template.default_runtime_flags_json::JSONB IS DISTINCT FROM '{}'::JSONB + OR NOT EXISTS (SELECT 1 FROM game_design_template_config_source_row_insert w + WHERE w.template_id = NEW.template_id AND w.creation_transaction_id = pg_current_xact_id()::TEXT) THEN + RAISE EXCEPTION 'template qualification requires actual new authorized row' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + IF NEW.payload_json::JSONB IS DISTINCT FROM payload OR NOT template_config_unique_json(NEW.payload_json::JSON) + OR payload->>'operation' IS DISTINCT FROM NEW.operation_kind + OR NOT EXISTS (SELECT 1 FROM game_design_template_config_source_qualification q WHERE q.template_id = NEW.template_id + AND q.canonical_tenant_id = NEW.canonical_tenant_id AND q.canonical_version_id = NEW.canonical_version_id) + OR (NEW.operation_kind = 'CREATE' AND NOT EXISTS (SELECT 1 FROM game_design_template_config_source_qualification q + WHERE q.template_id = NEW.template_id AND q.revision_id = NEW.revision_id AND q.request_id = NEW.request_id + AND q.commit_id = NEW.commit_id AND q.revision_order = NEW.revision_order)) + OR (NEW.operation_kind <> 'CREATE' AND payload->>'templateId' IS DISTINCT FROM NEW.template_id::TEXT) THEN + RAISE EXCEPTION 'template revision or canonical association differs' USING ERRCODE = '23514'; END IF; + IF NEW.operation_kind = 'DELETE' THEN + IF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 4 THEN + RAISE EXCEPTION 'template DELETE fields invalid' USING ERRCODE = '23514'; END IF; + IF NOT EXISTS (SELECT 1 FROM game_design_template_config_source_snapshot s0, + LATERAL jsonb_array_elements(s0.snapshot_json::JSONB->'entries') e + WHERE s0.canonical_tenant_id = NEW.canonical_tenant_id AND s0.canonical_version_id = NEW.canonical_version_id + AND s0.commit_id = h.visible_commit_id AND e->>'templateId' = NEW.template_id::TEXT) + AND NOT EXISTS (SELECT 1 FROM game_design_template_config_source_revision r0 + WHERE r0.canonical_tenant_id = NEW.canonical_tenant_id AND r0.canonical_version_id = NEW.canonical_version_id + AND r0.commit_id = NEW.commit_id AND r0.template_id = NEW.template_id + AND r0.revision_order < NEW.revision_order AND r0.operation_kind IN ('CREATE', 'UPSERT')) THEN + RAISE EXCEPTION 'template DELETE requires actual existing authored entry' USING ERRCODE = '23514'; END IF; + ELSIF (SELECT count(*) FROM jsonb_object_keys(payload)) <> 5 + OR jsonb_typeof(payload->'configJson') IS DISTINCT FROM 'string' + OR NOT template_config_supported(payload->>'configJson', NEW.canonical_version_id) + OR template.config IS DISTINCT FROM (payload->>'configJson')::JSONB THEN + RAISE EXCEPTION 'template config owner inputs unavailable or closed config invalid' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + snapshot := NEW.snapshot_json::JSONB; + IF snapshot->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v1' + OR snapshot->>'bindingJson' IS DISTINCT FROM c.binding_json OR snapshot->>'bindingDigest' IS DISTINCT FROM c.input_digest + OR snapshot->>'genesisReceiptId' IS DISTINCT FROM g.receipt_id::TEXT + OR snapshot->>'inheritedCommitId' IS DISTINCT FROM coalesce(h.visible_commit_id::TEXT, '') + OR jsonb_typeof(snapshot->'entries') IS DISTINCT FROM 'array' + OR (SELECT count(*) FROM jsonb_object_keys(snapshot)) <> 7 THEN RAISE EXCEPTION 'template config snapshot binding invalid' USING ERRCODE = '23514'; END IF; + SELECT s0.snapshot_json::JSONB->'entries' INTO prior FROM game_design_template_config_source_snapshot s0 WHERE s0.canonical_tenant_id = NEW.canonical_tenant_id AND s0.canonical_version_id = NEW.canonical_version_id AND s0.commit_id = h.visible_commit_id; + prior := coalesce(prior, '[]'::JSONB); + IF TG_TABLE_NAME = 'game_design_template_config_source_application' THEN + IF NEW.expected_epoch IS DISTINCT FROM h.source_epoch OR snapshot->>'sourceEpoch' IS DISTINCT FROM (h.source_epoch::NUMERIC + 1)::TEXT + OR NOT (c.binding_json::JSONB->'affectedUnits' @> jsonb_build_array(jsonb_build_object('owner', 'GAME_DESIGN_CONTROL_PLANE', + 'aggregateType', 'TEMPLATE_CONFIG_SET', 'aggregateId', NEW.canonical_version_id::TEXT, + 'scopeType', 'TEMPLATE_CONFIG_SET', 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch))) THEN + RAISE EXCEPTION 'template config application lacks exact scope epoch' USING ERRCODE = '23514'; END IF; + WITH choices AS ( + SELECT (item->>'templateId')::BIGINT AS key, -1 AS ord, FALSE AS deleted, item FROM jsonb_array_elements(prior) item + UNION ALL SELECT r.template_id, r.revision_order, r.operation_kind = 'DELETE', template_config_revision_item(r) + FROM game_design_template_config_source_revision r WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id AND r.commit_id = NEW.commit_id + ), final AS (SELECT DISTINCT ON (key) * FROM choices ORDER BY key, ord DESC) + SELECT coalesce(jsonb_agg(item ORDER BY key) FILTER (WHERE NOT deleted), '[]'::JSONB) INTO expected_items FROM final; + IF expected_items IS DISTINCT FROM snapshot->'entries' THEN + RAISE EXCEPTION 'template config application must replay exact source without aliases' USING ERRCODE = '23514'; END IF; + ELSE + SELECT * INTO a FROM game_design_template_config_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT count(*) INTO count_declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r WHERE r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (r->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG'; + IF (count_declared > 0) IS DISTINCT FROM (a.commit_id IS NOT NULL) + OR snapshot->>'sourceEpoch' IS DISTINCT FROM h.source_epoch + OR (a.commit_id IS NOT NULL AND a.snapshot_json IS DISTINCT FROM NEW.snapshot_json) + OR (a.commit_id IS NULL AND snapshot->'entries' IS DISTINCT FROM prior) + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR NOT template_config_selected_inputs(snapshot, NEW.canonical_tenant_id, NEW.canonical_version_id, NEW.commit_id) + OR NOT template_config_current_inventory(NEW.canonical_tenant_id, NEW.canonical_version_id, v.id, v.tenant_id, snapshot) + OR c.workflow_state <> 'SYNCHRONIZED' + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility f WHERE f.canonical_tenant_id = NEW.canonical_tenant_id AND f.canonical_version_id = NEW.canonical_version_id AND f.request_id = NEW.request_id AND f.commit_id = NEW.commit_id AND f.input_digest = c.input_digest) THEN + RAISE EXCEPTION 'template config snapshot requires exact synchronized source inheritance' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION template_config_row_insert_witness() RETURNS TRIGGER AS $$ +BEGIN + INSERT INTO game_design_template_config_source_row_insert VALUES (NEW.id, pg_current_xact_id()::TEXT); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER template_config_row_insert_witness AFTER INSERT ON game_templates + FOR EACH ROW EXECUTE FUNCTION template_config_row_insert_witness(); + +CREATE FUNCTION guard_template_config_insert_witness() RETURNS TRIGGER AS $$ +BEGIN + IF pg_trigger_depth() <> 2 OR NEW.creation_transaction_id IS DISTINCT FROM pg_current_xact_id()::TEXT + OR NOT EXISTS (SELECT 1 FROM game_templates t WHERE t.id = NEW.template_id + AND t.xmin::TEXT = (pg_current_xact_id()::TEXT::XID)::TEXT) THEN + RAISE EXCEPTION 'template insert witness requires actual row insert trigger' USING ERRCODE = '23514'; END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER template_config_insert_witness_guard BEFORE INSERT ON game_design_template_config_source_row_insert + FOR EACH ROW EXECUTE FUNCTION guard_template_config_insert_witness(); + +CREATE FUNCTION verify_template_config_explicit_target_row() RETURNS TRIGGER AS $$ +DECLARE template game_templates%ROWTYPE; target version%ROWTYPE; +BEGIN + SELECT * INTO template FROM game_templates WHERE id = NEW.id; + IF NOT FOUND OR template.default_version_id IS NULL THEN RETURN NULL; END IF; + SELECT v.* INTO target FROM version v JOIN game_design_template_config_source_genesis g + ON g.version_id = v.id AND g.canonical_tenant_id = v.canonical_tenant_id AND g.canonical_version_id = v.canonical_version_id + WHERE v.id = template.default_version_id AND v.tenant_id = template.tenant_id FOR UPDATE OF v; + IF NOT FOUND THEN RETURN NULL; END IF; + IF NOT EXISTS (SELECT 1 FROM game_design_template_config_source_qualification q + JOIN game_design_template_config_source_revision r ON r.canonical_tenant_id = q.canonical_tenant_id + AND r.canonical_version_id = q.canonical_version_id AND r.revision_id = q.revision_id + AND r.template_id = q.template_id AND r.request_id = q.request_id AND r.commit_id = q.commit_id + AND r.revision_order = q.revision_order AND r.operation_kind = 'CREATE' + WHERE q.template_id = template.id AND q.canonical_tenant_id = target.canonical_tenant_id + AND q.canonical_version_id = target.canonical_version_id) THEN + RAISE EXCEPTION 'explicit template target requires actual authorized CREATE qualification' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER template_config_explicit_target_row_guard AFTER INSERT OR UPDATE ON game_templates + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_template_config_explicit_target_row(); + +CREATE FUNCTION guard_template_config_live_row() RETURNS TRIGGER AS $$ +DECLARE q game_design_template_config_source_qualification%ROWTYPE; c game_design_draft_commit%ROWTYPE; + target version%ROWTYPE; payload JSONB; +BEGIN + SELECT * INTO q FROM game_design_template_config_source_qualification WHERE template_id = OLD.id; + IF q.template_id IS NULL THEN + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + IF (NEW.tenant_id, NEW.default_version_id) IS DISTINCT FROM (OLD.tenant_id, OLD.default_version_id) THEN + SELECT v.* INTO target FROM version v JOIN game_design_template_config_source_genesis g + ON g.version_id = v.id AND g.canonical_tenant_id = v.canonical_tenant_id AND g.canonical_version_id = v.canonical_version_id + WHERE v.id = NEW.default_version_id AND v.tenant_id = NEW.tenant_id FOR UPDATE OF v; + IF FOUND THEN RAISE EXCEPTION 'unqualified template cannot be reassigned into managed source target' USING ERRCODE = '23514'; END IF; + END IF; + RETURN NEW; + END IF; + PERFORM 1 FROM version WHERE canonical_tenant_id = q.canonical_tenant_id AND canonical_version_id = q.canonical_version_id FOR UPDATE; + IF TG_OP = 'DELETE' OR NEW.id IS DISTINCT FROM OLD.id OR NEW.tenant_id IS DISTINCT FROM OLD.tenant_id + OR NEW.name IS DISTINCT FROM OLD.name OR NEW.default_version_id IS DISTINCT FROM OLD.default_version_id + OR NEW.default_script_patch_version IS DISTINCT FROM OLD.default_script_patch_version + OR NEW.default_runtime_flags_json IS DISTINCT FROM OLD.default_runtime_flags_json + OR NEW.template_reference_phase IS DISTINCT FROM OLD.template_reference_phase THEN + RAISE EXCEPTION 'qualified template identity and launch fields immutable' USING ERRCODE = '23514'; END IF; + IF NEW.config IS NOT DISTINCT FROM OLD.config THEN RETURN NEW; END IF; + SELECT owner.* INTO STRICT c FROM game_design_draft_commit owner JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = owner.canonical_tenant_id AND slot.canonical_version_id = owner.canonical_version_id + AND slot.request_id = owner.request_id AND slot.commit_id = owner.commit_id + WHERE owner.canonical_tenant_id = q.canonical_tenant_id AND owner.canonical_version_id = q.canonical_version_id; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection p WHERE p.canonical_tenant_id = q.canonical_tenant_id + AND p.canonical_version_id = q.canonical_version_id) + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_owner_result r WHERE r.canonical_tenant_id = q.canonical_tenant_id + AND r.canonical_version_id = q.canonical_version_id AND r.request_id = c.request_id + AND r.owner = 'GAME_DESIGN_CONTROL_PLANE' AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'qualified template update requires unfrozen active coordinator' USING ERRCODE = '23514'; END IF; + IF NOT EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r + WHERE r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (r->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG' + AND (r->>'payload')::JSONB->>'operation' = 'UPSERT' + AND (r->>'payload')::JSONB->>'templateId' = OLD.id::TEXT + AND ((r->>'payload')::JSONB->>'configJson')::JSONB = NEW.config) THEN + RAISE EXCEPTION 'qualified template update differs from bound revision' USING ERRCODE = '23514'; END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER template_config_live_row_guard BEFORE UPDATE OR DELETE ON game_templates + FOR EACH ROW EXECUTE FUNCTION guard_template_config_live_row(); + +CREATE FUNCTION verify_template_config_references() RETURNS TRIGGER AS $$ +DECLARE r game_design_template_config_source_revision%ROWTYPE; cfg JSONB; expected JSONB; actual JSONB; + rules JSONB; input JSONB; visible UUID; +BEGIN + SELECT * INTO STRICT r FROM game_design_template_config_source_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND revision_id = NEW.revision_id; + IF r.operation_kind = 'DELETE' THEN + IF EXISTS (SELECT 1 FROM game_design_template_config_source_ref x WHERE x.canonical_tenant_id = r.canonical_tenant_id + AND x.canonical_version_id = r.canonical_version_id AND x.revision_id = r.revision_id) THEN + RAISE EXCEPTION 'deleted template has no references' USING ERRCODE = '23514'; END IF; + RETURN NULL; + END IF; + cfg := (r.payload_json::JSONB->>'configJson')::JSONB; + SELECT jsonb_agg(value ORDER BY value->>'refKind', value->>'refKey') INTO expected FROM ( + SELECT jsonb_build_object('refKind', 'BASE_VERSION', 'refKey', r.canonical_version_id::TEXT, 'revisionId', NULL) AS value + UNION ALL SELECT jsonb_build_object('refKind', x->>'family', 'refKey', x->>'key', 'revisionId', x->>'revisionId') + FROM jsonb_array_elements(cfg->'gameLogic'->'inputs') x + ) ref_values; + SELECT jsonb_agg(jsonb_build_object('refKind', x.ref_kind, 'refKey', x.ref_key, 'revisionId', x.referenced_revision_id::TEXT) + ORDER BY x.ref_kind, x.ref_key) INTO actual FROM game_design_template_config_source_ref x + WHERE x.canonical_tenant_id = r.canonical_tenant_id AND x.canonical_version_id = r.canonical_version_id AND x.revision_id = r.revision_id; + IF expected IS DISTINCT FROM actual THEN RAISE EXCEPTION 'template normalized references differ from original config' USING ERRCODE = '23514'; END IF; + SELECT snapshot_json::JSONB->'entries' INTO rules FROM game_design_gameplay_rule_application + WHERE canonical_tenant_id = r.canonical_tenant_id AND canonical_version_id = r.canonical_version_id AND commit_id = r.commit_id; + IF rules IS NULL THEN + SELECT visible_commit_id INTO visible FROM game_design_gameplay_rule_head + WHERE canonical_tenant_id = r.canonical_tenant_id AND canonical_version_id = r.canonical_version_id; + SELECT snapshot_json::JSONB->'entries' INTO rules FROM game_design_gameplay_rule_snapshot + WHERE canonical_tenant_id = r.canonical_tenant_id AND canonical_version_id = r.canonical_version_id AND commit_id = visible; + END IF; + FOR input IN SELECT * FROM jsonb_array_elements(cfg->'gameLogic'->'inputs') LOOP + IF NOT EXISTS (SELECT 1 FROM jsonb_array_elements(rules) e WHERE e->>'family' = input->>'family' + AND e->>'revisionId' = input->>'revisionId' + AND gameplay_rule_definition_key(e->>'family', (e->>'definitionJson')::JSONB) = input->>'key') THEN + RAISE EXCEPTION 'template gameplay input not in actual effective source' USING ERRCODE = '23514'; END IF; + END LOOP; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +CREATE CONSTRAINT TRIGGER template_config_refs_revision_guard AFTER INSERT ON game_design_template_config_source_revision + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_template_config_references(); +CREATE CONSTRAINT TRIGGER template_config_refs_projection_guard AFTER INSERT ON game_design_template_config_source_ref + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_template_config_references(); + +CREATE FUNCTION deny_template_config_history_change() RETURNS TRIGGER AS $$ +BEGIN RAISE EXCEPTION 'template source history immutable' USING ERRCODE = '23514'; END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER template_config_ref_immutable BEFORE UPDATE OR DELETE ON game_design_template_config_source_ref + FOR EACH ROW EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_insert_witness_immutable BEFORE UPDATE OR DELETE ON game_design_template_config_source_row_insert + FOR EACH ROW EXECUTE FUNCTION deny_template_config_history_change(); +CREATE FUNCTION verify_template_config_application_commit() RETURNS TRIGGER AS $$ +DECLARE branding_bytes BYTEA; c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_template_config_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + gameplay_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT result_bytes INTO branding_bytes FROM game_design_branding_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT r FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT h FROM game_design_template_config_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG'; + SELECT count(*) INTO retained FROM game_design_template_config_source_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-template-config-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'branding application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'TEMPLATE_CONFIG' THEN 'TEMPLATE_CONFIG_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'BRANDING_ASSET_REFERENCE' AND branding_bytes IS NULL) OR (kind = 'GAMEPLAY_RULE' AND gameplay_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'branding mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'TEMPLATE_CONFIG_SET', 'BRANDING_ASSET_REFERENCE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'branding combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'branding scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + IF gameplay_bytes IS NOT NULL THEN bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; END IF; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + bytes := convert_to('TEMPLATE_CONFIG', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'branding owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION verify_branding_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE config_bytes BYTEA; c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_branding_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + gameplay_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT result_bytes INTO config_bytes FROM game_design_template_config_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT r FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT h FROM game_design_branding_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'BRANDING_ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_branding_source_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-branding-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'branding application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' WHEN 'TEMPLATE_CONFIG' THEN 'TEMPLATE_CONFIG_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'TEMPLATE_CONFIG' AND config_bytes IS NULL) OR (kind = 'GAMEPLAY_RULE' AND gameplay_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'branding mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET', 'TEMPLATE_CONFIG_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'branding combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'branding scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + IF gameplay_bytes IS NOT NULL THEN bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; END IF; + bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF (config_bytes IS NOT NULL) IS DISTINCT FROM EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG') THEN + RAISE EXCEPTION 'template config sibling application must match declared revisions' USING ERRCODE = '23514'; END IF; + IF config_bytes IS NOT NULL THEN bytes := convert_to('TEMPLATE_CONFIG', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(config_bytes)) || config_bytes; END IF; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'branding owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION verify_gameplay_rule_application_commit() RETURNS TRIGGER AS $$ +DECLARE config_bytes BYTEA; c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_gameplay_rule_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + branding_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; declared BIGINT; retained BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT result_bytes INTO config_bytes FROM game_design_template_config_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT r FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT h FROM game_design_gameplay_rule_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE'; + SELECT count(*) INTO retained FROM game_design_gameplay_rule_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-gameplay-rule-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'gameplay application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO branding_bytes FROM game_design_branding_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' WHEN 'TEMPLATE_CONFIG' THEN 'TEMPLATE_CONFIG_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'TEMPLATE_CONFIG' AND config_bytes IS NULL) OR (kind = 'BRANDING_ASSET_REFERENCE' AND branding_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'gameplay mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET', 'TEMPLATE_CONFIG_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'gameplay combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'gameplay scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + IF (config_bytes IS NOT NULL) IS DISTINCT FROM EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG') THEN + RAISE EXCEPTION 'template config sibling application must match declared revisions' USING ERRCODE = '23514'; END IF; + IF config_bytes IS NOT NULL THEN bytes := convert_to('TEMPLATE_CONFIG', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(config_bytes)) || config_bytes; END IF; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'gameplay owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION verify_ordinary_asset_application_commit() RETURNS TRIGGER AS $$ +DECLARE config_bytes BYTEA; c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_asset_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; declared BIGINT; retained BIGINT; + components BYTEA; command_bytes BYTEA; policy_bytes BYTEA; gameplay_bytes BYTEA; branding_bytes BYTEA; epochs JSONB; unit JSONB; +BEGIN + SELECT result_bytes INTO config_bytes FROM game_design_template_config_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT r FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT h FROM game_design_asset_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'ASSET_REFERENCE'; + SELECT count(*) INTO retained FROM game_design_asset_source_revision x WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id AND x.commit_id = NEW.commit_id; + bytes := convert_to('game-design-ordinary-asset-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained OR r.status <> 'APPLIED' OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id + OR expected IS DISTINCT FROM NEW.result_bytes OR NOT (r.applied_units_json::JSONB @> jsonb_build_array(jsonb_build_object( + 'aggregateType', 'ASSET_REFERENCE_SET', 'aggregateId', NEW.canonical_version_id::TEXT, 'scopeType', 'ASSET_REFERENCE_SET', + 'scopeId', 'effective', 'expectedEpoch', NEW.expected_epoch, 'resultingEpoch', h.source_epoch))) THEN + RAISE EXCEPTION 'ordinary application requires atomic combined owner outcome' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); + components := int4send(octet_length(bytes)) || bytes; + epochs := '[]'::JSONB; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF command_bytes IS NOT NULL THEN + bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; + END IF; + bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + SELECT result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF gameplay_bytes IS NOT NULL THEN + bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; + END IF; + SELECT result_bytes INTO branding_bytes FROM game_design_branding_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + SELECT result_bytes INTO policy_bytes FROM game_design_realm_policy_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND coalesce((x->>'payload')::JSONB->>'revisionKind', '') NOT IN ('COMMAND_DEFINITION', 'REALM_ENTRY_POLICY', 'ASSET_REFERENCE', 'GAMEPLAY_RULE', 'BRANDING_ASSET_REFERENCE', 'TEMPLATE_CONFIG')) + OR (branding_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'BRANDING_ASSET_REFERENCE') + OR (command_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'COMMAND_DEFINITION') + OR (policy_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'REALM_ENTRY_POLICY') THEN + RAISE EXCEPTION 'ordinary mixed application requires every declared supported sibling source' USING ERRCODE = '23514'; END IF; + IF (gameplay_bytes IS NOT NULL) IS DISTINCT FROM EXISTS ( + SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'GAMEPLAY_RULE') THEN + RAISE EXCEPTION 'ordinary mixed application lacks exact declared gameplay source' USING ERRCODE = '23514'; END IF; + -- The vector has one entry per exact declared local scope, ordered as the Java composition. + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' + LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'BRANDING_ASSET_REFERENCE_SET', 'TEMPLATE_CONFIG_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' + OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'ordinary combined scope unknown' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF (config_bytes IS NOT NULL) IS DISTINCT FROM EXISTS (SELECT 1 FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG') THEN + RAISE EXCEPTION 'template config sibling application must match declared revisions' USING ERRCODE = '23514'; END IF; + IF config_bytes IS NOT NULL THEN bytes := convert_to('TEMPLATE_CONFIG', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(config_bytes)) || config_bytes; END IF; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); + expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs + OR jsonb_array_length(epochs) <> (1 + CASE WHEN command_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN policy_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN gameplay_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN branding_bytes IS NULL THEN 0 ELSE 1 END + CASE WHEN config_bytes IS NULL THEN 0 ELSE 1 END) THEN + RAISE EXCEPTION 'ordinary combined outcome must contain exact tagged components and complete epochs' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER template_config_genesis_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_genesis + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_head_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_head + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_revision_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_revision + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_application_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_application + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_snapshot_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_capture_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_capture + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_qualification_guard BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_source_qualification + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); +CREATE CONSTRAINT TRIGGER template_config_application_commit_guard AFTER INSERT ON game_design_template_config_source_application + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION verify_template_config_application_commit(); +CREATE TRIGGER template_config_genesis_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_genesis + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_head_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_head + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_revision_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_revision + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_application_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_application + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_snapshot_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_snapshot + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_capture_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_capture + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_qualification_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_qualification + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_ref_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_ref + EXECUTE FUNCTION deny_template_config_history_change(); +CREATE TRIGGER template_config_row_insert_no_truncate BEFORE TRUNCATE ON game_design_template_config_source_row_insert + EXECUTE FUNCTION deny_template_config_history_change(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java new file mode 100644 index 0000000000..d1515c174e --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -0,0 +1,451 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.AssetSource; +import net.firedevops.firemud.gamedesign.publication.BrandingSource; +import net.firedevops.firemud.gamedesign.publication.BrandingSourceRepository; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Physical storage proof only; Account creator admission is not simulated by this fixture. */ +@Testcontainers(disabledWithoutDocker = true) +class BrandingSourcePostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void actualFreshGenesisMixedSourceApplicationAndRestartReadbackPreserveOriginalHistory() + throws Exception { + var f = fixture(null); + var logo = asset(f, "logo.png"); + var ordinary = asset(f, "ordinary.png"); + // Borrow only typed policy input; the fixture is not Account publication authorization. + var policy = + net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures.fresh( + f.target) + .account() + .input() + .selection() + .selectedCommit() + .revisions() + .stream() + .map(DraftCommitBinding.RevisionPayload::payload) + .filter(p -> p.contains("REALM_ENTRY_POLICY")) + .findFirst() + .orElseThrow(); + var first = + binding( + f, + "0", + BrandingSource.SCOPE, + BrandingSource.upsertPayload( + logo.getId().toString(), + "logo.png", + BrandingSource.Role.LOGO, + BrandingSource.Requiredness.REQUIRED), + AssetSource.upsertPayload( + ordinary.getId().toString(), "ordinary.png", AssetSource.Requiredness.REQUIRED), + GameplayRuleSource.deletePayload( + net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family.ADMISSION_TAGS, + "absent"), + CommandSource.deletePayload("absent"), + policy); + apply(f, first); + var selected = + new GameDesignSourceRepository(f.dsl) + .readSynchronized(f.target, first.commitId()) + .orElseThrow() + .branding() + .orElseThrow(); + assertThat(selected.items()).hasSize(1); + assertThat(selected.items().getFirst().reference().sourceBinding()).isEqualTo(first); + assertThat(selected.roleDeclarations()) + .containsEntry("LOGO", "PRESENT") + .containsEntry("THEME", "EMPTY"); + assertThat(new BrandingSourceRepository(f.dsl).readSnapshot(f.target, UUID.randomUUID())) + .isEmpty(); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_assets SET data = ? WHERE id = ?", new byte[] {9}, logo.getId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy(() -> f.dsl.execute("DELETE FROM game_design_branding_source_revision")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + + var sibling = binding(f, "1", CommandSource.SCOPE, CommandSource.deletePayload("absent")); + apply(f, sibling); + var inherited = + new GameDesignSourceRepository(f.dsl) + .readSynchronized(f.target, sibling.commitId()) + .orElseThrow() + .branding() + .orElseThrow(); + assertThat(inherited.items()).isEqualTo(selected.items()); + assertThat(inherited.sourceEpoch()).isEqualTo("1"); + assertThat(inherited.binding()).isEqualTo(sibling); + var deleted = + binding( + f, + "1", + BrandingSource.SCOPE, + BrandingSource.deletePayload("logo.png", BrandingSource.Role.LOGO)); + apply(f, deleted); + assertThat( + new BrandingSourceRepository(f.dsl) + .readSnapshot(f.target, deleted.commitId()) + .orElseThrow() + .roleDeclarations() + .values()) + .containsOnly("EMPTY"); + assertThat( + new BrandingSourceRepository(f.dsl) + .readSnapshot(f.target, first.commitId()) + .orElseThrow()) + .isEqualTo(selected); + } + + @Test + void retainedVersionCannotAcquireMissingBrandingGenesis() { + var f = fixture("58"); + var original = binding(f, "0", CommandSource.SCOPE, CommandSource.deletePayload("historical")); + f.tx.executeWithoutResult( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + coordinator.claim(original); + coordinator.claimApplicationSlot(original); + coordinator.markOwnerInProgress( + original, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var commands = + new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(f.dsl); + var applied = commands.apply(original).orElseThrow(); + var out = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, "game-design-control-plane-command-application/v1"); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, original.canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + out, applied.canonicalBytes()); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + original.commitId(), + original.digest(), + applied.resultIdentity(), + out.toByteArray(), + List.of(applied.commandAppliedEpoch())); + coordinator.recordOwnerOutcome(original, outcome); + coordinator.advanceVisibilityFence( + original, + new DraftCommitCoordinatorRepository.CoordinatorProof(original, List.of(outcome))); + commands.captureSynchronized(original); + new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository(f.dsl) + .captureSynchronized(original); + new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(f.dsl) + .captureSynchronized(original); + new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository(f.dsl) + .captureSynchronized(original); + coordinator.releaseApplicationSlot(original); + }); + var originalBytes = + f.dsl + .fetchSingle( + "SELECT result_bytes FROM game_design_draft_commit_owner_result WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get(0, byte[].class); + var originalSources = + List.of("command_source", "realm_policy", "asset_source", "gameplay_rule"); + var sourceJson = + originalSources.stream() + .map( + name -> + f.dsl + .fetchSingle( + "SELECT snapshot_json FROM game_design_" + + name + + "_snapshot WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get(0, String.class)) + .toList(); + var fenceJson = + f.dsl + .fetchSingle( + "SELECT to_jsonb(f)::text FROM game_design_draft_commit_visibility_fence f WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get(0, String.class); + f.migrate(); + var historical = + new GameDesignSourceRepository(f.dsl) + .readSynchronized(f.target, original.commitId()) + .orElseThrow(); + assertThat(historical.branding()).isEmpty(); + assertThat(historical.command().binding()).isEqualTo(original); + assertThat( + List.of( + historical.command().canonicalJson(), + historical.policy().canonicalJson(), + historical.asset().canonicalJson(), + historical.gameplay().canonicalJson())) + .isEqualTo(sourceJson); + assertThat( + f.dsl + .fetchSingle( + "SELECT to_jsonb(f)::text FROM game_design_draft_commit_visibility_fence f WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get(0, String.class)) + .isEqualTo(fenceJson); + assertThat( + f.dsl + .fetchSingle( + "SELECT result_bytes FROM game_design_draft_commit_owner_result WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get(0, byte[].class)) + .isEqualTo(originalBytes); + assertThatThrownBy( + () -> + f.tx.execute( + ignored -> new GameDesignSourceRepository(f.dsl).captureSynchronized(original))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); + assertThat(new BrandingSourceRepository(f.dsl).readGenesis(f.target)).isEmpty(); + assertThatThrownBy( + () -> + f.tx.execute( + ignored -> new BrandingSourceRepository(f.dsl).enrollFreshDraft(f.target))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("BRANDING_SOURCE_FRESH_INSERT_UNAVAILABLE"); + assertThatThrownBy(() -> new GameDesignSourceRepository(f.dsl).readGenesis(f.target)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); + } + + @Test + void wrongTenantSourceRowCannotWriteOrExposeSnapshot() { + var f = fixture(null); + var foreignGame = new Game(); + foreignGame.setTenantId(UUID.randomUUID().toString()); + foreignGame.setName("Foreign asset owner"); + var foreign = + Objects.requireNonNull( + f.tx.execute(ignored -> new GameRepository(f.dsl).save(foreignGame))); + var source = new GameAsset(); + source.setTenantId(foreign.getTenantId()); + source.setFileName("foreign.png"); + source.setContentType("image/png"); + source.setData(new byte[] {1}); + var foreignAsset = + Objects.requireNonNull( + f.tx.execute(ignored -> new GameAssetRepository(f.dsl).save(source))); + var payload = + BrandingSource.upsertPayload( + foreignAsset.getId().toString(), + "foreign.png", + BrandingSource.Role.FAVICON, + BrandingSource.Requiredness.REQUIRED); + var binding = binding(f, "0", BrandingSource.SCOPE, payload); + assertThatThrownBy(() -> apply(f, binding)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("BRANDING_SOURCE_ROW_UNAVAILABLE"); + assertThat(new BrandingSourceRepository(f.dsl).readSnapshot(f.target, binding.commitId())) + .isEmpty(); + } + + private void apply(Fixture f, DraftCommitBinding binding) { + f.tx.executeWithoutResult( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var sources = new GameDesignSourceRepository(f.dsl); + var applied = sources.apply(binding); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(applied.ownerOutcome()))); + sources.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + }); + } + + private DraftCommitBinding binding( + Fixture f, String epoch, String primaryScope, String... payloads) { + var revisions = new ArrayList(); + var scopes = new java.util.TreeSet(); + scopes.add(primaryScope); + for (int i = 0; i < payloads.length; i++) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[i])); + if (payloads[i].contains("\"revisionKind\":\"ASSET_REFERENCE\"")) + scopes.add(AssetSource.SCOPE); + if (payloads[i].contains("\"revisionKind\":\"GAMEPLAY_RULE\"")) + scopes.add(GameplayRuleSource.SCOPE); + if (payloads[i].contains("\"revisionKind\":\"COMMAND_DEFINITION\"")) + scopes.add(CommandSource.SCOPE); + if (payloads[i].contains("\"revisionKind\":\"REALM_ENTRY_POLICY\"")) + scopes.add(net.firedevops.firemud.gamedesign.publication.RealmPolicySource.SCOPE); + } + var units = + scopes.stream() + .map( + scope -> + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + scope, + f.target.canonicalVersionId().toString(), + scope, + "effective", + scope.equals(primaryScope) ? epoch : "0")) + .toList(); + return DraftCommitBinding.create( + f.target, UUID.randomUUID(), UUID.randomUUID(), "base-commit-0", revisions, units); + } + + private GameAsset asset(Fixture f, String name) { + var asset = new GameAsset(); + asset.setTenantId(f.target.gameDesignVersionTenantKey()); + asset.setFileName(name); + asset.setContentType("image/png"); + asset.setData(name.getBytes(StandardCharsets.UTF_8)); + return Objects.requireNonNull( + f.tx.execute(ignored -> new GameAssetRepository(f.dsl).save(asset))); + } + + private Fixture fixture(String maximumMigration) { + var schema = "branding_source_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + data.setSchema(schema); + var config = + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (maximumMigration != null) config.target(maximumMigration); + config.load().migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var tx = new TransactionTemplate(new DataSourceTransactionManager(data)); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Branding source storage fixture"); + var savedGame = + Objects.requireNonNull(tx.execute(ignored -> new GameRepository(dsl).save(game))); + var version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + var saved = + Objects.requireNonNull( + tx.execute( + ignored -> { + if (maximumMigration == null) return new VersionRepository(dsl).save(version); + // Retained fixture intentionally uses the pre-branding producer, in its actual + // insert transaction. + long id = + dsl.fetchSingle( + "INSERT INTO version (tenant_id, canonical_tenant_id, canonical_version_id, identity_source_game_row_id, identity_source_game_tenant_key, identity_source_provenance_kind, version_number, version_state, version_state_epoch, is_script_only, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'NEW_GAME_ROW', 1, 'DRAFT', 1, FALSE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) RETURNING id", + savedGame.getTenantId(), + savedGame.getCanonicalTenantId(), + UUID.randomUUID(), + savedGame.getId(), + savedGame.getTenantId()) + .get(0, Long.class); + var retained = new VersionRepository(dsl).findById(id).orElseThrow(); + var oldTarget = + new DraftCommitBinding.TargetProof( + retained.getCanonicalTenantId(), + retained.getCanonicalVersionId(), + id, + retained.getTenantId(), + retained.getIdentitySourceGameRowId(), + retained.getIdentitySourceGameTenantKey(), + retained.getIdentitySourceProvenanceKind()); + var policy = + new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository( + dsl) + .recordFreshGenesis(oldTarget); + new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(dsl) + .enrollNewDraftGenesis( + new CommandSource.NewDraftGenesisReceipt( + oldTarget, policy.receiptId(), policy.creationTransactionId())); + new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(dsl) + .enrollFreshDraft(oldTarget); + new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository( + dsl) + .enrollFreshDraft(oldTarget); + return retained; + })); + var target = + new DraftCommitBinding.TargetProof( + saved.getCanonicalTenantId(), + saved.getCanonicalVersionId(), + saved.getId(), + saved.getTenantId(), + saved.getIdentitySourceGameRowId(), + saved.getIdentitySourceGameTenantKey(), + saved.getIdentitySourceProvenanceKind()); + return new Fixture(dsl, tx, target, data, schema); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate tx, + DraftCommitBinding.TargetProof target, + DriverManagerDataSource data, + String schema) { + void migrate() { + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java index a39ceb8d15..2bdf532768 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java @@ -1130,7 +1130,51 @@ private Local local(String maximumMigration) { version.setVersionState(VersionLifecycleState.DRAFT); version.setVersionStateEpoch(1L); var saved = - Objects.requireNonNull(tx.execute(ignored -> new VersionRepository(dsl).save(version))); + Objects.requireNonNull( + tx.execute( + ignored -> { + if (maximumMigration == null) return new VersionRepository(dsl).save(version); + if (!"57".equals(maximumMigration)) + throw new IllegalArgumentException( + "Historical fixture supports migration 57 only"); + // Actual pre-branding producer setup for retained-history migration proof. + // This is not current creator admission or authority for later empty families. + long id = + dsl.fetchSingle( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch, is_script_only, " + + "canonical_tenant_id, canonical_version_id, identity_source_game_row_id, identity_source_game_tenant_key, identity_source_provenance_kind, created_at, updated_at) " + + "SELECT tenant_id, 1, 'DRAFT', 1, FALSE, canonical_tenant_id, ?, id, tenant_id, tenant_identity_provenance_kind, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP FROM game WHERE id = ? RETURNING id", + UUID.randomUUID(), + savedGame.getId()) + .get(0, Long.class); + var retained = new VersionRepository(dsl).findById(id).orElseThrow(); + var historicalTarget = + new DraftCommitBinding.TargetProof( + retained.getCanonicalTenantId(), + retained.getCanonicalVersionId(), + id, + retained.getTenantId(), + retained.getIdentitySourceGameRowId(), + retained.getIdentitySourceGameTenantKey(), + retained.getIdentitySourceProvenanceKind()); + var policy = + new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository( + dsl) + .recordFreshGenesis(historicalTarget); + new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(dsl) + .enrollNewDraftGenesis( + new net.firedevops.firemud.gamedesign.publication.CommandSource + .NewDraftGenesisReceipt( + historicalTarget, + policy.receiptId(), + policy.creationTransactionId())); + new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(dsl) + .enrollFreshDraft(historicalTarget); + new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository( + dsl) + .enrollFreshDraft(historicalTarget); + return retained; + })); var target = new DraftCommitBinding.TargetProof( saved.getCanonicalTenantId(), diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java new file mode 100644 index 0000000000..131836e485 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -0,0 +1,424 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Local coordinator/storage definitions; upstream Account authority and GL intake are not mocked + * proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class TemplateConfigSourcePostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void actualCreateAndSameCommitGameplayInputHaveDurableGeneratedIdentityAndExactRetry() { + var f = fixture(); + UUID ruleRevision = UUID.randomUUID(); + var rule = + new DraftCommitBinding.RevisionPayload( + "0", + ruleRevision, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("ordinary"))); + var config = + config( + f, + "[{\"family\":\"ADMISSION_TAGS\",\"key\":\"ordinary\",\"revisionId\":\"" + + ruleRevision + + "\"}]"); + var create = + new DraftCommitBinding.RevisionPayload( + "1", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.createPayload("Starter", config)); + var binding = + binding( + f, + List.of(rule, create), + Map.of(GameplayRuleSource.SCOPE, "0", TemplateConfigSource.SCOPE, "0")); + apply(f, binding); + var first = source(f, binding); + String templateId = first.entries().getFirst().templateId(); + assertThat(first.entries().getFirst().sourceBinding()).isEqualTo(binding); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_source_ref WHERE revision_id = ?", + create.revisionId()) + .get(0, Long.class)) + .isEqualTo(2L); + assertThat( + f.dsl + .fetchSingle( + "SELECT template_reference_phase FROM game_templates WHERE id = ?", + Long.parseLong(templateId)) + .get(0, String.class)) + .isEqualTo("LEGACY"); + // Replay reads the actual original stored application, not a second CREATE or current name + // lookup. + f.tx.executeWithoutResult( + ignored -> + assertThat( + new GameDesignSourceRepository(f.dsl) + .apply(binding) + .templateConfig() + .orElseThrow() + .snapshot()) + .isEqualTo(first)); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isEqualTo(1L); + var sibling = binding(f, CommandSource.deletePayload("absent"), CommandSource.SCOPE, "0"); + apply(f, sibling); + assertThat(source(f, sibling).entries()).isEqualTo(first.entries()); + assertThat(source(f, sibling).sourceEpoch()).isEqualTo("1"); + + var update = + binding( + f, + TemplateConfigSource.upsertPayload(templateId, config(f, "[]")), + TemplateConfigSource.SCOPE, + "1"); + apply(f, update); + assertThat(source(f, update).entries().getFirst().sourceBinding()).isEqualTo(update); + assertThat(source(f, binding)).isEqualTo(first); + var delete = + binding(f, TemplateConfigSource.deletePayload(templateId), TemplateConfigSource.SCOPE, "2"); + apply(f, delete); + assertThat(source(f, delete).entries()).isEmpty(); + assertThat(source(f, binding)).isEqualTo(first); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_design_template_config_source_revision SET payload_json = '{}'")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy(() -> f.dsl.execute("DELETE FROM game_design_template_config_source_ref")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_templates SET config = '{}' WHERE id = ?", + Long.parseLong(templateId))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + @Test + void unsupportedExternalOwnerReferencesRollbackWithoutInventingQualifiedRows() { + var f = fixture(); + var unsupported = + new TemplateConfigSource.Config( + config(f, "[]") + .canonicalJson() + .replace( + "\"regions\":[]", + "\"regions\":[{\"regionTemplateId\":\"" + UUID.randomUUID() + "\"}]")); + var binding = + binding( + f, + TemplateConfigSource.createPayload("Denied", unsupported), + TemplateConfigSource.SCOPE, + "0"); + assertThatThrownBy(() -> apply(f, binding)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_CONFIG_WORLD_EXACT_OWNER_READ_UNAVAILABLE"); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isZero(); + assertThat(new TemplateConfigSourceRepository(f.dsl).readSnapshot(f.target, binding.commitId())) + .isEmpty(); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_source_qualification") + .get(0, Long.class)) + .isZero(); + } + + @Test + void legacyTenantMatchingRowCannotAcquireCanonicalSourceAssociation() { + var f = fixture(); + long legacy = + f.dsl + .fetchSingle( + "INSERT INTO game_templates (tenant_id, name, config) VALUES (?, 'Unqualified', '{}'::JSONB) RETURNING id", + f.target.gameDesignVersionTenantKey()) + .get(0, Long.class); + var binding = + binding( + f, + TemplateConfigSource.upsertPayload(Long.toString(legacy), config(f, "[]")), + TemplateConfigSource.SCOPE, + "0"); + assertThatThrownBy(() -> apply(f, binding)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_CONFIG_TEMPLATE_OWNER_PROVENANCE_UNAVAILABLE"); + assertThatThrownBy( + () -> + f.tx.executeWithoutResult( + ignored -> + f.dsl.execute( + "INSERT INTO game_design_template_config_source_row_insert VALUES (?, pg_current_xact_id()::TEXT)", + legacy))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(new TemplateConfigSourceRepository(f.dsl).readSnapshot(f.target, binding.commitId())) + .isEmpty(); + } + + @Test + void explicitTargetRawInsertAndLegacyReassignmentCannotCommit() { + var f = fixture(); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'Raw target', '{}'::JSONB, ?)", + f.target.gameDesignVersionTenantKey(), + f.target.gameDesignVersionRowId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining( + "explicit template target requires actual authorized CREATE qualification"); + long legacy = + f.dsl + .fetchSingle( + "INSERT INTO game_templates (tenant_id, name, config) VALUES (?, 'Unrelated legacy', '{}'::JSONB) RETURNING id", + f.target.gameDesignVersionTenantKey()) + .get(0, Long.class); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_templates SET default_version_id = ? WHERE id = ?", + f.target.gameDesignVersionRowId(), + legacy)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining( + "unqualified template cannot be reassigned into managed source target"); + assertThat( + f.dsl + .fetchSingle("SELECT default_version_id FROM game_templates WHERE id = ?", legacy) + .get(0, Long.class)) + .isNull(); + var selected = binding(f, CommandSource.deletePayload("absent"), CommandSource.SCOPE, "0"); + apply(f, selected); + assertThat(source(f, selected).entries()).isEmpty(); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'After capture', '{}'::JSONB, ?)", + f.target.gameDesignVersionTenantKey(), + f.target.gameDesignVersionRowId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining( + "explicit template target requires actual authorized CREATE qualification"); + assertThat(source(f, selected).entries()).isEmpty(); + } + + @Test + void newCaptureCannotIgnorePendingUnqualifiedExplicitTargetRow() { + var f = fixture(); + var selected = binding(f, CommandSource.deletePayload("absent"), CommandSource.SCOPE, "0"); + assertThatThrownBy( + () -> + f.tx.executeWithoutResult( + ignored -> { + // The deferred insert guard has not fired: new source capture must + // independently deny. + f.dsl.execute( + "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'Pending raw target', '{}'::JSONB, ?)", + f.target.gameDesignVersionTenantKey(), + f.target.gameDesignVersionRowId()); + apply(f, selected); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_CONFIG_EXPLICIT_TARGET_INVENTORY_UNQUALIFIED"); + assertThat( + new TemplateConfigSourceRepository(f.dsl).readSnapshot(f.target, selected.commitId())) + .isEmpty(); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isZero(); + } + + @Test + void changedGameplayRevisionCannotLeaveStaleTemplateReferencesVisible() { + var f = fixture(); + UUID ruleId = UUID.randomUUID(); + var config = + config( + f, + "[{\"family\":\"ADMISSION_TAGS\",\"key\":\"ordinary\",\"revisionId\":\"" + + ruleId + + "\"}]"); + var initial = + binding( + f, + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + ruleId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload( + new GameplayRuleManifest.AdmissionTag("ordinary"))), + new DraftCommitBinding.RevisionPayload( + "1", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.createPayload("Starter", config))), + Map.of(GameplayRuleSource.SCOPE, "0", TemplateConfigSource.SCOPE, "0")); + apply(f, initial); + var changed = + binding( + f, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("ordinary")), + GameplayRuleSource.SCOPE, + "1"); + assertThatThrownBy(() -> apply(f, changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_CONFIG_GAMEPLAY_INPUT_CHANGED"); + assertThat(new TemplateConfigSourceRepository(f.dsl).readSnapshot(f.target, changed.commitId())) + .isEmpty(); + assertThat(source(f, initial).entries()).hasSize(1); + } + + private TemplateConfigSourceSnapshot source(Fixture f, DraftCommitBinding binding) { + return new GameDesignSourceRepository(f.dsl) + .readSynchronized(f.target, binding.commitId()) + .orElseThrow() + .templateConfig() + .orElseThrow(); + } + + private void apply(Fixture f, DraftCommitBinding binding) { + f.tx.executeWithoutResult( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var sources = new GameDesignSourceRepository(f.dsl); + var applied = sources.apply(binding); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(applied.ownerOutcome()))); + sources.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + }); + } + + private static TemplateConfigSource.Config config(Fixture f, String inputs) { + return new TemplateConfigSource.Config( + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + f.target.canonicalVersionId() + + "\",\"world\":{\"regions\":[],\"rooms\":[]},\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":" + + inputs + + "},\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}},\"supportedSettings\":[]}"); + } + + private DraftCommitBinding binding(Fixture f, String payload, String scope, String epoch) { + return binding( + f, + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payload)), + Map.of(scope, epoch)); + } + + private DraftCommitBinding binding( + Fixture f, List revisions, Map scopes) { + var units = + scopes.entrySet().stream() + .map( + e -> + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + e.getKey(), + f.target.canonicalVersionId().toString(), + e.getKey(), + "effective", + e.getValue())) + .toList(); + return DraftCommitBinding.create( + f.target, UUID.randomUUID(), UUID.randomUUID(), "base-commit-0", revisions, units); + } + + private Fixture fixture() { + String schema = "template_config_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + data.setSchema(schema); + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var tx = new TransactionTemplate(new DataSourceTransactionManager(data)); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Template source fixture"); + var savedGame = + Objects.requireNonNull(tx.execute(ignored -> new GameRepository(dsl).save(game))); + var version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + var saved = + Objects.requireNonNull(tx.execute(ignored -> new VersionRepository(dsl).save(version))); + var target = + new DraftCommitBinding.TargetProof( + saved.getCanonicalTenantId(), + saved.getCanonicalVersionId(), + saved.getId(), + saved.getTenantId(), + saved.getIdentitySourceGameRowId(), + saved.getIdentitySourceGameTenantKey(), + saved.getIdentitySourceProvenanceKind()); + return new Fixture(dsl, tx, target); + } + + private record Fixture( + DSLContext dsl, TransactionTemplate tx, DraftCommitBinding.TargetProof target) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index ea71e0f5dc..6b1e5b0921 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -137,14 +137,24 @@ void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionC .isEqualTo(fixture.source().evidenceDigest()); assertThat(original.canonicalTenantId()).isNotEqualTo(fixture.privateSourceTenantKey()); - Version newDraft = new Version(); - newDraft.setTenantId(fixture.privateSourceTenantKey()); - newDraft.setVersionNumber(2); - newDraft.setVersionState(VersionLifecycleState.DRAFT); - newDraft.setVersionStateEpoch(1L); - newDraft.setNotes("new mutable template default"); - newDraft.setUpdatedAt(LocalDateTime.now()); - newDraft = versionRepository.save(newDraft); + // Explicit retained-history Draft fixture: exercise stored descriptor replay after default + // drift without claiming authenticated new authoring or inventing later source-family genesis. + Long changedDefaultId = + dsl.fetchSingle( + "INSERT INTO version (tenant_id, canonical_tenant_id, canonical_version_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, identity_source_provenance_kind, " + + "version_number, version_state, version_state_epoch, is_script_only, notes, created_at, updated_at) " + + "SELECT tenant_id, canonical_tenant_id, ?, identity_source_game_row_id, identity_source_game_tenant_key, identity_source_provenance_kind, " + + "2, 'DRAFT', 1, FALSE, 'retained mutable template default for storage replay', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP " + + "FROM version WHERE id = ? AND tenant_id = ? RETURNING id", + UUID.randomUUID(), + fixture.version().getId(), + fixture.privateSourceTenantKey()) + .get(0, Long.class); + Version newDraft = + versionRepository + .findByTenantIdAndId(fixture.privateSourceTenantKey(), changedDefaultId) + .orElseThrow(); fixture.template().setDefaultVersionId(newDraft.getId()); gameTemplateRepository.save(fixture.template()); fixture.version().setVersionState(VersionLifecycleState.RETIRED); diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java new file mode 100644 index 0000000000..f94af447dc --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +class BrandingSourceTest { + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID VERSION = UUID.randomUUID(); + + @Test + void everyRoleRetainsItsExactBindingAndRequiredPolicy() { + for (var role : BrandingSource.Role.values()) { + var binding = + binding( + BrandingSource.upsertPayload( + "1", "image.png", role, BrandingSource.Requiredness.REQUIRED)); + var reference = BrandingSource.replay(List.of(), binding).references().getFirst(); + assertThat(reference.role()).isEqualTo(role); + assertThat(reference.family()).isEqualTo("BRANDING"); + assertThat(reference.sourceBinding()).isSameAs(binding); + assertThatThrownBy( + () -> + BrandingSource.upsertPayload( + "1", "image.png", role, BrandingSource.Requiredness.OPTIONAL)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void replayPreservesUntouchedOriginalRevisionAndExplicitRoleDeclarations() { + var original = + binding( + BrandingSource.upsertPayload( + "1", "logo.png", BrandingSource.Role.LOGO, BrandingSource.Requiredness.REQUIRED)); + var first = BrandingSource.replay(List.of(), original); + var changed = + binding( + BrandingSource.upsertPayload( + "2", "theme.css", BrandingSource.Role.THEME, BrandingSource.Requiredness.REQUIRED)); + var replay = BrandingSource.replay(first.references(), changed); + assertThat(replay.references().getFirst().sourceBinding()).isEqualTo(original); + var items = + replay.references().stream() + .map( + r -> new BrandingSourceSnapshot.Item(r, "image/png", "sha256:" + "a".repeat(64), 1)) + .toList(); + var snapshot = + new BrandingSourceSnapshot(changed, "2", original.commitId(), UUID.randomUUID(), items); + assertThat(snapshot.roleDeclarations()) + .isEqualTo( + Map.of("RESOURCE", "EMPTY", "LOGO", "PRESENT", "FAVICON", "EMPTY", "THEME", "PRESENT")); + assertThat(BrandingSourceSnapshot.fromStored(snapshot.canonicalJson())).isEqualTo(snapshot); + assertThatThrownBy( + () -> + BrandingSourceSnapshot.fromStored( + snapshot + .canonicalJson() + .replace("\"FAVICON\":\"EMPTY\"", "\"FAVICON\":\"PRESENT\""))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void unknownMalformedOptionalAndOrdinaryReinterpretationDeny() { + String payload = + BrandingSource.upsertPayload( + "1", "logo.png", BrandingSource.Role.LOGO, BrandingSource.Requiredness.REQUIRED); + for (String invalid : + List.of( + payload.replace("LOGO", "UNKNOWN"), + payload.replace("REQUIRED", "OPTIONAL"), + payload.replace("BRANDING_ASSET_REFERENCE", "UNKNOWN"), + payload.replace("\"family\":\"BRANDING\"", "\"family\":\"ORDINARY\""), + payload.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"), + payload + "{}")) { + assertThatThrownBy(() -> BrandingSource.mutations(binding(invalid))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + BrandingSource.replay( + List.of(), + binding( + BrandingSource.upsertPayload( + "1", + "a", + BrandingSource.Role.LOGO, + BrandingSource.Requiredness.REQUIRED), + BrandingSource.upsertPayload( + "1", + "b", + BrandingSource.Role.THEME, + BrandingSource.Requiredness.REQUIRED)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void knownSiblingDispatchPreservesFullBindingWithoutAcceptingUnknownKinds() { + var binding = + binding( + BrandingSource.deletePayload("logo.png", BrandingSource.Role.LOGO), + AssetSource.deletePayload("ordinary.png")); + assertThat(BrandingSource.mutations(binding)).hasSize(1); + assertThat(AssetSource.mutations(binding)).hasSize(1); + assertThat(CommandSource.mutations(binding)).isEmpty(); + assertThat(CommandSource.hasRealmPolicyRevision(binding)).isFalse(); + assertThat(GameplayRuleSource.mutations(binding)).isEmpty(); + assertThat(BrandingSource.mutations(binding).getFirst().binding()).isSameAs(binding); + } + + private static DraftCommitBinding binding(String... payloads) { + var revisions = new ArrayList(); + for (int i = 0; i < payloads.length; i++) + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[i])); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + BrandingSource.SCOPE, + VERSION.toString(), + BrandingSource.SCOPE, + "effective", + "0"))); + } +} diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java new file mode 100644 index 0000000000..43cb4cb5fb --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java @@ -0,0 +1,172 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +class TemplateConfigSourceTest { + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID VERSION = UUID.randomUUID(); + + @Test + void closedDocumentRequiresEveryExplicitCollectionAndRejectsRecursiveEvidence() { + String valid = config(); + assertThat(new TemplateConfigSource.Config(valid).baseVersionId()).isEqualTo(VERSION); + for (String invalid : + List.of( + valid.replace("\"supportedSettings\":[]", "\"unknown\":[]"), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"receipt\":{}"), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"bindingJson\":\"recursive\""), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"commitDigest\":\"recursive\""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":2"), + valid.replace( + "\"supportedSettings\":[]", + "\"supportedSettings\":[{\"defaultRuntimeFlagsJson\":\"{}\"}]"), + valid.replace("\"scriptPatch\":{\"presence\":\"ABSENT\"}", "\"scriptPatch\":null"), + valid + "{}")) + assertThatThrownBy(() -> new TemplateConfigSource.Config(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void canonicalOwnerUuidSyntaxCannotQualifyWorldEntityOrAutomationReferences() { + String ownerId = UUID.randomUUID().toString(); + var world = + new TemplateConfigSource.Config( + config() + .replace( + "\"regions\":[]", "\"regions\":[{\"regionTemplateId\":\"" + ownerId + "\"}]")); + var entity = + new TemplateConfigSource.Config( + config() + .replace("\"items\":[]", "\"items\":[{\"entityTemplateId\":\"" + ownerId + "\"}]")); + var scripts = + new TemplateConfigSource.Config( + config() + .replace( + "\"scripts\":[]", + "\"scripts\":[{\"scriptId\":\"onEnter\",\"eventBindings\":[]}]")); + var patch = + new TemplateConfigSource.Config( + config() + .replace( + "{\"presence\":\"ABSENT\"}", + "{\"presence\":\"PRESENT\",\"scriptPatchVersion\":\" raw-patch-1 \"}")); + assertThatThrownBy(world::requireAvailableOwnerReads) + .hasMessage("TEMPLATE_CONFIG_WORLD_EXACT_OWNER_READ_UNAVAILABLE"); + assertThatThrownBy(entity::requireAvailableOwnerReads) + .hasMessage("TEMPLATE_CONFIG_ENTITY_EXACT_OWNER_READ_UNAVAILABLE"); + assertThatThrownBy(scripts::requireAvailableOwnerReads) + .hasMessage("TEMPLATE_CONFIG_AUTOMATION_EXACT_OWNER_READ_UNAVAILABLE"); + assertThatThrownBy(patch::requireAvailableOwnerReads) + .hasMessage("TEMPLATE_CONFIG_AUTOMATION_EXACT_OWNER_READ_UNAVAILABLE"); + assertThatThrownBy( + () -> + new TemplateConfigSource.Config( + config().replace("\"items\":[]", "\"equipment\":[]"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new TemplateConfigSource.Config( + config() + .replace("\"regions\":[]", "\"regions\":[{\"regionTemplateId\":\"7\"}]"))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void actualGeneratedRowAndOriginalRevisionRemainSeparateFromAuthoredPreimage() { + var create = + binding( + TemplateConfigSource.createPayload( + "Starter", new TemplateConfigSource.Config(config()))); + var revision = create.revisions().getFirst().revisionId(); + assertThat(TemplateConfigSource.mutations(create).getFirst().templateId()).isNull(); + assertThatThrownBy(() -> TemplateConfigSource.replay(List.of(), create, Map.of())) + .isInstanceOf(NullPointerException.class); + var entries = TemplateConfigSource.replay(List.of(), create, Map.of(revision, "7")); + var sibling = binding(CommandSource.deletePayload("absent")); + var inherited = TemplateConfigSource.replay(entries, sibling, Map.of()); + assertThat(inherited.getFirst().sourceBinding()).isSameAs(create); + var snapshot = + new TemplateConfigSourceSnapshot( + sibling, "1", create.commitId(), UUID.randomUUID(), inherited); + assertThat(TemplateConfigSourceSnapshot.fromStored(snapshot.canonicalJson())) + .isEqualTo(snapshot); + assertThatThrownBy( + () -> + TemplateConfigSource.replay( + List.of(), binding(TemplateConfigSource.deletePayload("7")), Map.of())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + TemplateConfigSource.replay( + List.of(), + binding( + TemplateConfigSource.upsertPayload( + "7", new TemplateConfigSource.Config(config()))), + Map.of())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void siblingDispatchDoesNotInventUnknownSourceKindsOrChangeOriginalBinding() { + var binding = + binding( + TemplateConfigSource.createPayload( + "Starter", new TemplateConfigSource.Config(config())), + CommandSource.deletePayload("absent")); + assertThat(TemplateConfigSource.mutations(binding).getFirst().binding()).isSameAs(binding); + assertThat(CommandSource.mutations(binding)).hasSize(1); + assertThat(AssetSource.mutations(binding)).isEmpty(); + assertThat(BrandingSource.mutations(binding)).isEmpty(); + assertThat(GameplayRuleSource.mutations(binding)).isEmpty(); + assertThat(CommandSource.hasRealmPolicyRevision(binding)).isFalse(); + String wrongBase = config().replace(VERSION.toString(), UUID.randomUUID().toString()); + assertThatThrownBy( + () -> + TemplateConfigSource.mutations( + binding( + TemplateConfigSource.createPayload( + "Starter", new TemplateConfigSource.Config(wrongBase))))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static String config() { + return "{\"schemaVersion\":1,\"baseVersionId\":\"" + + VERSION + + "\",\"world\":{\"regions\":[],\"rooms\":[]},\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]},\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}},\"supportedSettings\":[]}"; + } + + private static DraftCommitBinding binding(String... payloads) { + var revisions = new ArrayList(); + for (int i = 0; i < payloads.length; i++) + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[i])); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.SCOPE, + VERSION.toString(), + TemplateConfigSource.SCOPE, + "effective", + "0"))); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTemplateRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTemplateRepositoryTest.java new file mode 100644 index 0000000000..748fe7dc1c --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTemplateRepositoryTest.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.DriverManager; +import java.time.LocalDateTime; +import net.firedevops.firemud.gamedesign.entity.GameTemplate; +import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class GameTemplateRepositoryTest { + @Test + void updateRequiresExistingTenantAndKeepsTenantBindingImmutable() throws Exception { + try (var connection = + DriverManager.getConnection("jdbc:h2:mem:game-template-update;DATABASE_TO_LOWER=TRUE")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createTable(dsl); + dsl.execute( + "INSERT INTO game_templates (id, tenant_id, name, config, created_at, " + + "default_runtime_flags_json, template_reference_phase) " + + "VALUES (1, 'tenant-1', 'Original', '{}', CURRENT_TIMESTAMP, '{}', 'ENFORCED')"); + GameTemplateRepository repository = new GameTemplateRepository(dsl); + + GameTemplate sameTenantUpdate = template(1L, "tenant-1", "Updated"); + GameTemplate updated = repository.save(sameTenantUpdate); + + assertThat(updated.getTenantId()).isEqualTo("tenant-1"); + assertThat(updated.getName()).isEqualTo("Updated"); + + GameTemplate crossTenantUpdate = template(1L, "tenant-2", "Overwritten"); + assertThatThrownBy(() -> repository.save(crossTenantUpdate)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("game template not found for tenant"); + assertThat(repository.findByTenantIdAndId("tenant-1", 1L)) + .get() + .satisfies( + stored -> { + assertThat(stored.getTenantId()).isEqualTo("tenant-1"); + assertThat(stored.getName()).isEqualTo("Updated"); + }); + assertThat(repository.findByTenantIdAndId("tenant-2", 1L)).isEmpty(); + } + } + + private static void createTable(DSLContext dsl) { + dsl.execute( + "CREATE TABLE game_templates (" + + "id BIGINT PRIMARY KEY, tenant_id VARCHAR(36) NOT NULL, name VARCHAR(100) NOT NULL, " + + "description VARCHAR(255), config VARCHAR(100) NOT NULL, default_version_id BIGINT, " + + "default_script_patch_version VARCHAR(128), default_runtime_flags_json VARCHAR(100), " + + "template_reference_phase VARCHAR(32), created_at TIMESTAMP)"); + } + + private static GameTemplate template(Long id, String tenantId, String name) { + GameTemplate template = new GameTemplate(); + template.setId(id); + template.setTenantId(tenantId); + template.setName(name); + template.setConfig("{}"); + template.setDefaultRuntimeFlagsJson("{}"); + template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); + template.setCreatedAt(LocalDateTime.of(2026, 10, 9, 12, 0)); + return template; + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImplTest.java index 3dc378824f..a4ce846e9a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameTemplateServiceImplTest.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.gamedesign.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.List; @@ -15,6 +17,22 @@ import org.springframework.data.domain.PageRequest; class GameTemplateServiceImplTest { + @Test + void createTemplateRejectsCallerSuppliedIdBeforeRepositoryOrMapper() { + GameTemplateRepository repo = Mockito.mock(GameTemplateRepository.class); + GameTemplateMapper mapper = Mockito.mock(GameTemplateMapper.class); + GameTemplateServiceImpl service = new GameTemplateServiceImpl(repo, mapper); + GameTemplateDto dto = + new GameTemplateDto(17L, "tenant-1", "Realm", null, "{}", null, null, "{}", null, null); + + IllegalArgumentException exception = + assertThrows(IllegalArgumentException.class, () -> service.createTemplate(dto)); + + assertEquals( + "INVALID_ARGUMENT: template id must not be supplied on create", exception.getMessage()); + verifyNoInteractions(repo, mapper); + } + @Test void listTemplatesReturnsPage() { GameTemplateRepository repo = Mockito.mock(GameTemplateRepository.class); From 75fdca93c12247c62af46122c9e076a7afd77470 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:34:06 +1300 Subject: [PATCH 042/129] Retain exact selected publication Game Logic settlement evidence --- .../account-service/api-contracts.md | 4 +- .../game-design-service/version-control.md | 2 +- .../game-logic-service/runtime-and-data.md | 2 + design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 8 +- ...game_logic_intake_settlement_service.proto | 27 + .../v1/gameplay_rule_intake_service.proto | 23 + .../AccountGameLogicIntakeSettlement.java | 27 +- ...tGameLogicIntakeSettlementGrpcService.java | 87 +++ ...eLogicIntakeSettlementGrpcServiceTest.java | 313 ++++++++ ...ountGameLogicIntakeSettlementEvidence.java | 47 ++ ...ntGameLogicIntakeSettlementProtoCodec.java | 67 ++ ...ntGameLogicIntakeSettlementReadClient.java | 8 + ...GameLogicIntakeSettlementReadEvidence.java | 56 ++ .../GameLogicIntakeRetainClient.java | 6 + .../GameLogicIntakeRetainEvidence.java | 83 ++ .../GameLogicIntakeRetainProtoCodec.java | 98 +++ ...ntGameLogicIntakeSettlementReadClient.java | 156 ++++ .../GrpcGameLogicIntakeRetainClient.java | 152 ++++ ...GameLogicIntakeSettlementReadGrpcTest.java | 711 ++++++++++++++++++ .../GameLogicIntakeRetainProtoCodecTest.java | 360 +++++++++ ...pcGameLogicIntakeRetainClientMtlsTest.java | 383 ++++++++++ .../publication/CommandSourceRepository.java | 17 +- .../publication/RealmPolicySource.java | 4 +- .../SelectedDraftGameLogicReceipt.java | 71 ++ ...lectedDraftGameLogicReceiptRepository.java | 158 ++++ .../SelectedDraftGameLogicReceiptService.java | 129 ++++ ...elected_publication_game_logic_receipt.sql | 52 ++ ...meLogicReceiptPostgresIntegrationTest.java | 326 ++++++++ .../RealmPolicyApplicationTest.java | 16 + ...ectedDraftGameLogicReceiptServiceTest.java | 200 +++++ .../SelectedDraftGameLogicReceiptTest.java | 224 ++++++ ...ameLogicGameplayRuleIntakeGrpcService.java | 80 ++ ...ogicGameplayRuleIntakeGrpcServiceTest.java | 269 +++++++ ...__publication_account_order_projection.sql | 19 + ...aphApplicationPostgresIntegrationTest.java | 15 + 36 files changed, 4180 insertions(+), 26 deletions(-) create mode 100644 protos/account/v1/game_logic_intake_settlement_service.proto create mode 100644 protos/game-logic/v1/gameplay_rule_intake_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementProtoCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceipt.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V61__selected_publication_game_logic_receipt.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java create mode 100644 services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V58__publication_account_order_projection.sql diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index dbc002fb28..66ebc9a6c0 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -90,10 +90,12 @@ The selected-order composition authenticates the exact same-namespace Game Desig The standalone, unregistered [`AccountSelectedPublicationOrderService.AuthorizeSelectedPublication`](../../../../protos/account/v1/selected_publication_order_service.proto) producer accepts schema version 1, the exact target namespace, a fresh nonzero transport correlation UUID and complete canonical selected-Draft bytes. The unchanged original creator credential travels only in protected, method-specific per-call metadata, never in protobuf request or response text; metadata must not be logged. Only the verified same-namespace Game Design workload may call it; Account authenticates before accessing or decoding credential metadata, decoding the request or capturing authority, and World has no producer permission. The receiver binds its credential interceptor internally; missing, duplicate, malformed or oversized credentials deny without owner mutation. Account captures its current environment boundary internally and validates it through the existing owner transaction; no caller-supplied environment or currentness value is authority. The response echoes the complete non-secret request tuple and exact canonical Account authorization binding, never the credential. Transport correlation does not change the durable publication identity: retry retains the original order, source evidence and fence. Unknown or noncanonical fields, changed response correlation or selection, unavailable currentness and substituted server identity fail closed. Calls require file-backed mutual TLS with exact Account server identity, a bounded five-second deadline and no ambient SQL transaction. Future registration must account for the transport metadata budget; a lower server limit still fails closed rather than truncating credentials. This transport defines no runtime registration or production environment-authority provider. -Game Logic's [selected-release source intake](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) uses a distinct Account authorization, not an original Draft or publication order. After the original authored Draft is synchronized and its Account operation has committed settlement, Account obtains the exact complete immutable Game Design source over its authenticated owner read outside SQL. Account's existing current-creator transaction then binds the stable intake request, acting account, canonical target, unchanged selected commit and source bytes/digest, complete current source vector and a distinct operation/fence; it retains full source participation atomically. Exact retries preserve that original order; changed source or actor evidence cannot reuse the request identity. This neither changes the original Draft's participant vector nor advances its commit to manufacture Game Logic participation. +Game Logic's [selected-release source intake](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) uses a distinct Account authorization, not an original Draft or publication order. After the original authored Draft is synchronized and its Account operation has committed settlement, Account first authenticates the exact Game Design peer and current creator/tenant authority and durably reserves the stable intake request, exact selected commit/target, intended reader and source-read purpose. This preliminary scope permits only that source read, not Game Logic retention. Account obtains the complete immutable Game Design source over the authenticated operation-bound owner read outside SQL, exact-compares its settled-source binding, then revalidates and locks the held Account sources before finalizing the distinct intake order under the existing currentness and settlement rules. The finalized order binds the acting account, canonical target, unchanged selected commit, exact source bytes/digest, complete current source vector and distinct operation/fence, with full source participation. Lost or denied reads remain recoverable or explicitly terminalizable under the same request without stranded authority or fresh mutation under expired authority. Exact retries preserve the original operation; changed actor, source, selection, reader or purpose cannot reuse its identity. Current authority remains protected through the actual mutation boundary. This neither changes the original Draft's participant vector nor advances its commit, and historical recovery or publication grants cannot substitute for this fresh authorization. Only the verified same-namespace Game Logic workload may call [`ReadHeldGameLogicIntakeAuthorization`](../../../../protos/account/v1/game_logic_intake_authorization.proto). Its complete request and original authorization bytes/digest must match the retained order. A `HELD` read does not grant fresh creator authority or establish completed intake. Applicable source changes and elective deadline disclosure remain blocked until Account obtains a fresh authenticated same-namespace Game Logic terminal read outside SQL and commits an exact immutable settlement receipt for this same operation. Only the original `RETAINED` or definitive `ABORTED` terminal can settle; absence, timeout, or ambiguous outcome preserves participation, and an abort must exclude later retention. Account checks for an exact existing receipt before the remote read, then serializes a new settlement using the existing sorted source-lock ordering. Exact receipt recovery authenticates the permitted caller and compares the complete original order before returning retained evidence without another remote read. The receipt preserves the original Game Logic terminal; a new read correlation cannot create or rewrite a settlement. Only this operation's settled participation is released, and its external `HELD` read then denies. The unregistered terminal reader and settlement writer do not enable intake or admission; implementation and proof limits belong in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The standalone [`SettleGameLogicIntake`](../../../../protos/account/v1/game_logic_intake_settlement_service.proto) transport is restricted to the verified same-namespace Game Design workload, authenticated before request decoding. Its closed request carries schema version, namespace, a separate transport correlation, and the complete original intake authorization bytes and digest; its response echoes that exact request and the immutable `account-game-logic-intake-settlement/v1` receipt bytes and digest. The receipt frames its schema and complete original Game Logic terminal, preserving retained and definitive-abort outcomes. A correlation change cannot change settlement identity. The client verifies Account's exact workload identity, requires file-backed mutual TLS, uses a bounded deadline and rejects ambient SQL. Unavailable or changed evidence fails closed. The receipt has its own bounded terminal envelope and is not embedded in the smaller publication operation or authored configuration. This transport supplies neither a fresh intake order nor public or runtime registration; implementation and proof remain in the linked tracker. + `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 98cf6875fa..c1c8013791 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -138,7 +138,7 @@ The shared golden vectors are `FULL_VERSION` `{tenantId=tenant-alpha, versionId= Game Logic's retained selected-release manifest and source-operation provenance remain unproved. Its digest receiver therefore rejects full-version requests without returning a participant digest, and Game Design fails the required participant gate rather than accepting the former fixed empty `ownedDraftRuleRows` hash and synthetic `version:` applied commit. Game Design remains the authoring and revision-history owner for authored gameplay rule inputs; its source operation must hand Game Logic the complete selected tenant/version/commit input set with current authority and operation-bound mutation authorization. Game Logic validates and immutably retains that evidence, then owns its participant and dedicated ability-schema attestations. The target ownership and input boundary are defined in the [Game Logic Draft Digest Contract](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) and the authoring shapes in [Ability & Action Design Tools](./ability-action-tools.md); this handoff is not current producer or intake proof. Full-version publication remains unavailable until Game Logic can attest under that contract; script-patch publication does not require the Game Logic participant. -The authored gameplay configuration binds exact Game Design-owned input identities and revisions. It excludes Game Logic's final receipt, a final-commit digest, and any complete Draft commit binding derived from that same commit, so canonicalizing the authored request does not depend on its own result. After the original Game Design source operation settles and Game Logic's distinct intake authorization and immutable retention succeed, the full-version publication gate must join the genuine Game Logic evidence for the exact unchanged `(tenantId, versionId, commitId)`. That derived join and retained receipt are outside the authored request preimage. A changed authored input or selected commit, a missing receipt, or evidence for a different/latest commit fails closed; an exact retry returns the original retained result and cannot substitute another commit. The owner-defined receipt and intake fields remain governed by the [Game Logic Draft Digest Contract](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake), not duplicated here. The nonrecursive canonicalization, changed-input/commit denial, missing-receipt denial, and exact-retry proof are not implemented; this contract does not claim those producer, join, or proof boundaries are live. +The authored gameplay configuration binds exact Game Design-owned input identities and revisions. It excludes Game Logic's final receipt, a final-commit digest, and any complete Draft commit binding derived from that same commit, so canonicalizing the authored request does not depend on its own result. After the original Game Design source operation settles and Game Logic's distinct intake authorization and immutable retention succeed, the full-version publication gate must join the genuine Game Logic evidence for the exact unchanged `(tenantId, versionId, commitId)`. That derived join and retained receipt are outside the authored request preimage. A changed authored input or selected commit, a missing receipt, or evidence for a different/latest commit fails closed; an exact retry returns the original retained result and cannot substitute another commit. The owner-defined receipt and intake fields remain governed by the [Game Logic Draft Digest Contract](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake), not duplicated here. Current construction, incomplete publication wiring and executed proof are recorded in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); standalone receipt retention does not make this publication boundary live. #### Launch and attestation read authorization (target state) diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index bf09f22b9c..0fa97436eb 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -57,6 +57,8 @@ Intake is a separate, mutation-authorized source operation. `GetDraftDesignDiges The original Game Design author operation settles before this intake. Game Logic obtains the complete synchronized source from Game Design's authenticated exact-commit owner read and verifies a distinct [Account intake authorization](../account-service/api-contracts.md#grpc-apis) for that same immutable source. It does not retrospectively join the original Draft's participant vector or allocate another selected commit. Account source participation remains held through Game Logic's local commit and exact terminal settlement; a remote `HELD` sample alone is insufficient. Retained source, complete manifest/provenance and the immutable intake result commit atomically. A definitive abort uses the same operation serialization and prevents later retention; missing rows or expired waits do not prove abort. Identical recovery returns the original result, never a latest source or replacement manifest. These obligations do not make Game Logic a publication-workflow mutation participant. +The standalone [`RetainGameplayRuleIntake`](../../../../protos/game-logic/v1/gameplay_rule_intake_service.proto) transport admits only verified same-namespace Game Design, authenticated before decoding. It invokes the existing distinct-order intake, not publication authorization. Exact namespace, independent transport correlation and complete original authorization bytes/digest are echoed with the immutable original terminal; both retained and definitive-abort retries preserve their original outcome. The client verifies Game Logic's workload and exact response binding. Game Design obtains the subsequent settlement receipt through the [Account-owned settlement transport](../account-service/api-contracts.md#grpc-apis), never by calling the Account-only terminal reader. These transports remain unregistered; their existence does not establish a fresh authorization producer or publication completion. + The authenticated publication read must preserve the exact source-operation and selected-commit correlation through its retained-manifest lookup and readback. Validating the publication request and then resolving content by tenant/version alone is insufficient when it can select a different source operation; neither a latest lookup nor request authentication repairs missing immutable provenance. The full-version manifest and the dedicated `abilitySchemaDigest` share the selected commit and Game Logic's existing canonicalization and `digestSchemaVersion` contract, but they attest distinct scopes. The aggregate full-manifest `contentDigest` is not an ability-schema digest, and neither the Automation & Scripting digest nor Game Design's control-plane digest substitutes for either Game Logic attestation. Any change to the dedicated ability-schema input set or its canonicalization requires the same explicit schema bump and digest replay or re-record process as other manifest changes. This contract governs publication evidence only; it does not authorize activation of unpublished rules or make Game Logic a participant in Game Design's publication workflow mutations. Game Logic does not read an admin database for runtime rules. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 6d3956cb6e..e3b1c2eaea 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -126,3 +126,9 @@ Entry format: - Observation: Calling an unproxied repository directly did not reproduce the failure; a clean caller alone did not establish a clean invocation inside the proxy. - Expected pattern: Exercise the real transaction proxy when proving an outside-SQL owner read. Preserve rejection of both ambient transactions and empty synchronization scopes rather than weakening the guard to accommodate its own annotation. - Current status: The annotation was removed and a three-case proxy regression passed locally. Corrected-head PostgreSQL/transport execution remains required. + +- `2026-10-09`: Check whether a schema-generation index failure exposes redundant DDL + - Context: The unpublished V61 receipt table's composite unique index included a PostgreSQL `TEXT` workflow identity; jOOQ's H2-backed schema simulator mapped it to an unindexable CLOB and failed generation. + - Observation: The table's existing primary key was a strict subset of that composite key, so the extra unique index enforced no additional uniqueness invariant. This was not evidence that PostgreSQL rejected the migration. + - Expected pattern: Compare the intended invariant with existing keys before adding simulator-specific scaffolding or weakening payload bounds. Remove a genuinely redundant index when the stronger key already enforces the contract; retain separate physical PostgreSQL migration proof. + - Current status: Removing the redundant index restored V61 schema generation. The subsequent integration-fixture and static-check corrections passed the complete Game Design gate R193; all three V61 PostgreSQL definitions compiled but skipped without Docker. Physical V61 proof remains unexecuted locally. 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 2ddee9e53d..01a638a7bf 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 @@ -14,7 +14,13 @@ The current source-completeness construction adds the separate branding writer, The composed V59/V60 local gate R183 passed Game Design schema generation, full service checks, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown: 416 unit cases executed with no failures, errors or skips. All 120 PostgreSQL definitions compiled but skipped without Docker, including three branding and six template-config cases. Two preceding runs failed only on new fixture compilation: package-private coordinator proof access and a checked fixture exception; production visibility was not widened. A separate legacy descriptor-retry fixture now models retained historical default drift without inventing new source qualification, preserving its original replay assertions. These results are not physical migration, source/freeze, authenticated producer-to-release or activation proof. -Total cross-owner source completeness, immutable manifest/export attestation, registered ingress and composed proof remain open. Game Logic intake and exact Account settlement have bounded unregistered components, not completed handoffs. Neither fresh source genesis nor absent mappings/consumers establishes empty unavailable families. All four genuine Gameplay handoffs and runtime activation remain open obligations. +The subsequent receipt/guard batch passes local affected checks across R191 and corrected Game Design gate R193: 351 Common, 1097 Account, 105 Game Logic, 556 World and 425 Game Design unit cases, plus 12 non-PostgreSQL integration cases, execute without failures or skips. All 566 PostgreSQL definitions compile but skip without Docker (234 Account, 123 Game Design, three Game Logic, 206 World); the three new V61 receipt cases are among those skips. The strict mutual-TLS retain and settlement transports execute over-4-MiB payload and wrong-server tests using synthetic content, not genuine source provenance. V58 World and V61 Game Design schema generation, affected full checks, formatting, static checks, coverage and boot JARs pass. R190 exposed the receipt fixture's unit-source-set dependency and constructor annotations; R191/R192 isolated a remaining unnecessary suppression, removed before R193. V61's redundant compound unique index was removed because its primary key already enforces stronger uniqueness, restoring simulator generation without weakening payload limits. Corrected PostgreSQL migration and genuine composed handoff proof remain open. + +Total cross-owner source completeness, immutable manifest/export attestation, registered ingress and composed proof remain open. Game Logic intake and exact Account settlement have bounded unregistered components, not completed handoffs. Their dedicated transport construction preserves exact original authorization and receipt correlation; no deployment registration or fresh authority is supplied by those codecs. The standalone selected-publication receipt producer obtains genuine Game Logic retain and Account settlement readbacks outside SQL, then stores their exact immutable binding to the unchanged selection under V61. It settles a genuine abort without creating a positive publication receipt. It is not yet wired into the selected-publication command or finalizer; its PostgreSQL definitions stipulate predecessor schema and upstream authority rather than proving the complete flow. The fresh intake producer currently reads Game Design source before capturing current creator authority, while that source reader has workload and binding checks but no independent operation-bound permission. Overseer decision `c33d7e62` approves the bounded two-phase repair recorded in the [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#grpc-apis): preliminary authenticated read scope precedes source disclosure, then exact source readback and currentness revalidation precede final retention authority. Its implementation and negative/recovery proof remain open; historical source recovery and publication orders cannot substitute. Neither fresh source genesis nor absent mappings/consumers establishes empty unavailable families. All four genuine Gameplay handoffs and runtime activation remain open obligations. + +Exact published head `2e466c5eca5de83e7e63ba211c3d07414192a67e` [Validation run 37876269262](https://github.com/benhook1013/FireMUD/actions/runs/37876269262) completed red. Account executed all 249 captured PostgreSQL cases successfully, including original-order lost-response and concurrent acknowledgement recovery. Game Logic's unit and integration tasks passed, but no retained XML gives exact counts. Game Design executed 123 PostgreSQL cases with six failures: four template-config and two branding cases exposed missing new-family handling in command-scope completeness and the policy revision classifier. World executed 206 PostgreSQL cases with 54 failures from the `accountOrder` JSONB projection defect. Bounded owning corrections require corrected-head execution; no failed case is counted as proof. The runner checked out synthetic merge `b54ebcd2e5ce1c0c992f8c63434c9b4e0dd17cff`, tree `7789d9ddacf30aaf41186116dd5c2822784d5476`, with parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the pinned head. This is not exact recorded-parent alignment or complete source-to-release proof. + +The subsequent exact-`681cb132a6810e035665db78309ec9fe1f042be5` [Validation run 37873038675](https://github.com/benhook1013/FireMUD/actions/runs/37873038675) ended canceled. Game Design's captured 114 PostgreSQL cases passed without skips; Game Logic's full check passed but its case counts were not published. World executed 556 passing units and 206 PostgreSQL cases with 54 failures, exposing a second JSONB projection-precedence defect in V56's `accountOrder` field; the bounded additive V58 correction preserves the complete order and substitution denial. Account's concurrent original-ack recovery case failed an integrity constraint before cancellation, leaving its totals and precise database message unavailable. This does not newly establish its root cause or prove the V59/V60 source batch. The actual checkout was synthetic merge `99f6d7e07b4201d9461b35474cc00ccd1d660940`, tree `756e38c0fd397e7967f27b05569ab816f5a51dba`, with first parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not recorded integrated parent `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`. The skipped duplicate run supplies no execution credit; intended-parent alignment remains open. Published-head `64c3d8db0ae1b302f8ae7e48e991d5b2ceb39fc6` [Validation run 37868588598](https://github.com/benhook1013/FireMUD/actions/runs/37868588598) completed red. Physical reports record 248 Account integration cases with two failures, 99 Game Design with one, seven Game Logic with two, and 206 World with 55; all executed with zero skips. Game Logic's XML capture step skipped, so its counts come from the uploaded HTML report. The four services' 1085, 399, 101 and 556 unit cases passed. Five previously failing Account selected-publication settlement cases now pass against V110, as does the separate three-case mTLS settlement suite. Game Design's six typed-source/handoff guard cases and World's 18 authored-source intake cases pass. This is not complete producer-to-release proof. The synthetic checkout is merge `793426c02775085d53aef7ef250da234f5b1b546`, tree `33d43a8217513e01237a0e36b7f14ebf82f09584`, with parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head; its first parent differs from the run's recorded integrated base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`. Intended-parent alignment, fresh-image boot, preview and Smoke proof remain open. diff --git a/protos/account/v1/game_logic_intake_settlement_service.proto b/protos/account/v1/game_logic_intake_settlement_service.proto new file mode 100644 index 0000000000..9c276d1abd --- /dev/null +++ b/protos/account/v1/game_logic_intake_settlement_service.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. Only same-namespace Game Design may settle/recover. +// This is receipt production/recovery, never fresh intake or publication authorization. +service AccountGameLogicIntakeSettlementService { + rpc SettleGameLogicIntake(SettleGameLogicIntakeRequest) returns (SettleGameLogicIntakeResponse); +} + +message SettleGameLogicIntakeRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Transport correlation, separate from all durable intake identities. + string read_request_id = 3; + bytes original_intake_authorization = 4; + string intake_authorization_digest = 5; +} + +message SettleGameLogicIntakeResponse { + SettleGameLogicIntakeRequest request = 1; + // Complete immutable Account receipt, never a publication-operation identity. + bytes original_settlement_receipt = 2; + string settlement_receipt_digest = 3; +} diff --git a/protos/game-logic/v1/gameplay_rule_intake_service.proto b/protos/game-logic/v1/gameplay_rule_intake_service.proto new file mode 100644 index 0000000000..42ec1255f3 --- /dev/null +++ b/protos/game-logic/v1/gameplay_rule_intake_service.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; +package game_logic.v1; +option java_package = "net.firedevops.firemud.gamelogic.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. Only the exact same-namespace Game Design workload may request +// retention under an original, distinct Account intake authorization. +service GameLogicGameplayRuleIntakeService { + rpc RetainGameplayRuleIntake(RetainGameplayRuleIntakeRequest) + returns (RetainGameplayRuleIntakeResponse); +} +message RetainGameplayRuleIntakeRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string correlation_id = 3; + bytes original_intake_authorization = 4; + string intake_authorization_digest = 5; +} +message RetainGameplayRuleIntakeResponse { + RetainGameplayRuleIntakeRequest request = 1; + bytes original_terminal = 2; + string terminal_digest = 3; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java index b94b7bd93e..f8cfa11aa8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlement.java @@ -1,42 +1,27 @@ package net.firedevops.firemud.accountservice.service.session; -import java.io.ByteArrayOutputStream; -import java.util.Arrays; import java.util.Objects; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; /** Immutable Account receipt; transport correlations never enter mutation identity. */ public record AccountGameLogicIntakeSettlement(GameLogicGameplayRuleIntakeTerminal terminal) { - public static final String SCHEMA = "account-game-logic-intake-settlement/v1"; + public static final String SCHEMA = AccountGameLogicIntakeSettlementEvidence.SCHEMA; public AccountGameLogicIntakeSettlement { Objects.requireNonNull(terminal); } public byte[] canonicalBytes() { - var out = new ByteArrayOutputStream(); - DraftAuthorizationFenceBinding.frame(out, SCHEMA); - DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); - return out.toByteArray(); + return new AccountGameLogicIntakeSettlementEvidence(terminal).canonicalBytes(); } public String digest() { - return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + return new AccountGameLogicIntakeSettlementEvidence(terminal).digest(); } public static AccountGameLogicIntakeSettlement fromStored(byte[] bytes) { - if (bytes == null - || bytes.length > GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES + 1024) - throw new IllegalArgumentException("Oversized settlement receipt"); - var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); - reader.expect(SCHEMA); - var receipt = - new AccountGameLogicIntakeSettlement( - GameLogicGameplayRuleIntakeTerminal.fromStored(reader.bytes())); - reader.requireEnd(); - if (!Arrays.equals(bytes, receipt.canonicalBytes())) - throw new IllegalArgumentException("Noncanonical settlement"); - return receipt; + return new AccountGameLogicIntakeSettlement( + AccountGameLogicIntakeSettlementEvidence.fromStored(bytes).terminal()); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java new file mode 100644 index 0000000000..d1d8f738d2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcService.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeRequest; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementProtoCodec; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered GD-only transport; Account alone reads GL terminal and owns settlement. */ +public final class AccountGameLogicIntakeSettlementGrpcService + extends AccountGameLogicIntakeSettlementServiceGrpc + .AccountGameLogicIntakeSettlementServiceImplBase { + private final AccountGameLogicIntakeSettlementService owner; + private final String namespace; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The injected owner service is an intentionally shared transport collaborator.") + public AccountGameLogicIntakeSettlementGrpcService( + AccountGameLogicIntakeSettlementService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + @Override + public void settleGameLogicIntake( + SettleGameLogicIntakeRequest wire, StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + final AccountGameLogicIntakeSettlementReadEvidence.Request request; + try { + request = AccountGameLogicIntakeSettlementProtoCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + final SettleGameLogicIntakeResponse response; + try { + var receipt = owner.settle(request.binding()); + response = + AccountGameLogicIntakeSettlementProtoCodec.toResponse( + new AccountGameLogicIntakeSettlementReadEvidence( + request, new AccountGameLogicIntakeSettlementEvidence(receipt.terminal()))); + } catch (StatusRuntimeException failure) { + deny(observer, Status.fromCode(failure.getStatus().getCode())); + return; + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError( + status + .withDescription("Account intake settlement denied or unavailable") + .asRuntimeException()); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java new file mode 100644 index 0000000000..a2ecb6a2b0 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java @@ -0,0 +1,313 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeRequest; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementProtoCodec; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceRevision; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Context-level transport proofs; durable settlement belongs to the owner service. */ +class AccountGameLogicIntakeSettlementGrpcServiceTest { + private final AccountGameLogicIntakeSettlementService owner = + mock(AccountGameLogicIntakeSettlementService.class); + private final AccountGameLogicIntakeSettlementGrpcService receiver = + new AccountGameLogicIntakeSettlementGrpcService(owner, "test"); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeDecodeAndDeniesEveryOtherWorkloadAndNamespace() { + assertThat(invoke(null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (var workload : + List.of( + "account-service", + "game-logic-service", + "world-management-service", + "game-session-service")) { + assertThat(peer("test", workload, () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(peer("other", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(authorized(() -> invoke(SettleGameLogicIntakeRequest.getDefaultInstance())).code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void deniesAmbientSqlAndChangedTargetBeforeOwner() { + var request = + AccountGameLogicIntakeSettlementProtoCodec.toRequest( + evidence("test", 1, Outcome.ABORTED).request()); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(authorized(() -> invoke(request)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThat(authorized(() -> invoke(request)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clearSynchronization(); + assertThat( + authorized(() -> invoke(request.toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } + + @Test + void returnsExactRetainedAndAbortedReceiptForNewCorrelationRetryWithoutChangingBytes() { + for (var outcome : Outcome.values()) { + var evidence = evidence("test", 1, outcome); + var receipt = new AccountGameLogicIntakeSettlement(evidence.receipt().terminal()); + when(owner.settle(any())).thenReturn(receipt); + var first = + authorized( + () -> + invoke(AccountGameLogicIntakeSettlementProtoCodec.toRequest(evidence.request()))); + assertThat(first.error()).isNull(); + assertThat( + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), first.response()) + .receipt() + .canonicalBytes()) + .isEqualTo(receipt.canonicalBytes()); + var retry = + AccountGameLogicIntakeSettlementReadEvidence.Request.create( + "test", evidence.request().binding()); + var replay = + authorized(() -> invoke(AccountGameLogicIntakeSettlementProtoCodec.toRequest(retry))); + assertThat(replay.error()).isNull(); + assertThat(replay.response().getOriginalSettlementReceipt()) + .isEqualTo(first.response().getOriginalSettlementReceipt()); + assertThat(replay.response().getRequest()).isNotEqualTo(first.response().getRequest()); + assertThat(receipt.canonicalBytes()).isEqualTo(evidence.receipt().canonicalBytes()); + assertThat(AccountGameLogicIntakeSettlement.fromStored(receipt.canonicalBytes()).digest()) + .isEqualTo(receipt.digest()); + } + } + + @Test + void substitutedOwnerReceiptAndOwnerFailureDenyWithoutLeakingDiagnostics() { + var evidence = evidence("test", 1, Outcome.RETAINED); + var request = AccountGameLogicIntakeSettlementProtoCodec.toRequest(evidence.request()); + when(owner.settle(any())) + .thenReturn( + new AccountGameLogicIntakeSettlement( + evidence("test", 1, Outcome.RETAINED).receipt().terminal())); + assertThat(authorized(() -> invoke(request)).code()).isEqualTo(Status.Code.UNAVAILABLE); + when(owner.settle(any())) + .thenThrow( + Status.FAILED_PRECONDITION + .withDescription("private-owner-evidence") + .asRuntimeException()); + var failed = authorized(() -> invoke(request)); + assertThat(failed.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(failed.error().toString()).doesNotContain("private-owner-evidence"); + } + + private record Result(SettleGameLogicIntakeResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private Result invoke(SettleGameLogicIntakeRequest request) { + var response = new AtomicReference(); + var error = new AtomicReference(); + receiver.settleGameLogicIntake( + request, + new io.grpc.stub.StreamObserver<>() { + @Override + public void onNext(SettleGameLogicIntakeResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable value) { + error.set(value); + } + + @Override + public void onCompleted() {} + }); + return new Result(response.get(), error.get()); + } + + private static T authorized(java.util.function.Supplier action) { + return peer("test", "game-design-service", action); + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private enum Outcome { + RETAINED, + ABORTED + } + + /** These canonical bytes are deliberately synthetic transport evidence, not owner provenance. */ + private static AccountGameLogicIntakeSettlementReadEvidence evidence( + String namespace, int entryCount, Outcome outcome) { + var tenant = UUID.randomUUID(); + var version = UUID.randomUUID(); + var requestId = UUID.randomUUID(); + var commitId = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + var definitions = new ArrayList(); + var revisions = new ArrayList(); + var revisionIds = new ArrayList(); + for (int index = 0; index < entryCount; index++) { + var definition = + new GameplayRuleManifest.AdmissionTag( + String.format(java.util.Locale.ROOT, "tag-%05d", index)); + definitions.add(definition); + var revisionId = UUID.randomUUID(); + revisionIds.add(revisionId); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + revisionId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload(definition))); + } + var selectedBinding = + DraftCommitBinding.create( + target, + requestId, + commitId, + "genesis", + List.of(revisions.getFirst()), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var definitionsByFamily = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) + definitionsByFamily.put(family, new ArrayList<>()); + definitionsByFamily.get(GameplayRuleManifest.Family.ADMISSION_TAGS).addAll(definitions); + var manifest = new GameplayRuleManifest(definitionsByFamily); + var entries = new ArrayList>(); + for (int index = 0; index < entryCount; index++) { + var definition = definitions.get(index); + var entryBinding = + DraftCommitBinding.create( + target, + requestId, + UUID.randomUUID(), + "genesis", + List.of(revisions.get(index)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + Integer.toString(index)))); + entries.add( + Map.of( + "family", definition.family().name(), + "definitionJson", GameplayRuleManifest.canonical(definition), + "sourceBindingJson", entryBinding.canonicalJson(), + "sourceBindingDigest", entryBinding.digest(), + "revisionOrder", "0", + "revisionId", revisionIds.get(index).toString())); + } + String snapshot = + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + entries)); + var source = new GameplayRuleSelectedSource(snapshot); + var accountEvidence = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + var authorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.fromString(accountEvidence.scopeId()), + source, + List.of(accountEvidence)); + var operation = new GameLogicGameplayRuleIntakeOperation(namespace, authorization); + var terminal = + outcome == Outcome.RETAINED + ? GameLogicGameplayRuleIntakeTerminal.retained( + operation, + source.canonicalBytes(), + manifest.canonicalJson().getBytes(StandardCharsets.UTF_8)) + : GameLogicGameplayRuleIntakeTerminal.aborted(operation); + return new AccountGameLogicIntakeSettlementReadEvidence( + AccountGameLogicIntakeSettlementReadEvidence.Request.create(namespace, authorization), + new AccountGameLogicIntakeSettlementEvidence(terminal)); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementEvidence.java new file mode 100644 index 0000000000..cb88f0cc7c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementEvidence.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Immutable original Account settlement; transport correlation is outside its identity. */ +public record AccountGameLogicIntakeSettlementEvidence( + GameLogicGameplayRuleIntakeTerminal terminal) { + public static final String SCHEMA = "account-game-logic-intake-settlement/v1"; + // Preserve the original stored receipt envelope over the 16 MiB terminal budget. + public static final int MAX_CANONICAL_BYTES = + GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES + 1024; + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + public AccountGameLogicIntakeSettlementEvidence { + Objects.requireNonNull(terminal); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + if (out.size() > MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Oversized settlement receipt"); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static AccountGameLogicIntakeSettlementEvidence fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Oversized settlement receipt"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + var receipt = + new AccountGameLogicIntakeSettlementEvidence( + GameLogicGameplayRuleIntakeTerminal.fromStored(reader.bytes())); + reader.requireEnd(); + if (!Arrays.equals(bytes, receipt.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical settlement"); + return receipt; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementProtoCodec.java new file mode 100644 index 0000000000..c7ee6dd58a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementProtoCodec.java @@ -0,0 +1,67 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeRequest; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed complete request echo and immutable canonical Account receipt transport. */ +public final class AccountGameLogicIntakeSettlementProtoCodec { + private AccountGameLogicIntakeSettlementProtoCodec() {} + + public static SettleGameLogicIntakeRequest toRequest( + AccountGameLogicIntakeSettlementReadEvidence.Request request) { + return SettleGameLogicIntakeRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalIntakeAuthorization(ByteString.copyFrom(request.binding().canonicalBytes())) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + } + + public static AccountGameLogicIntakeSettlementReadEvidence.Request fromRequest( + SettleGameLogicIntakeRequest request) { + if (!request.getUnknownFields().asMap().isEmpty() + || request.getOriginalIntakeAuthorization().size() > 4 * 1024 * 1024) + throw new IllegalArgumentException("Unknown or oversized original intake authorization"); + DraftAuthorizationFenceBinding.canonicalUuid(request.getReadRequestId()); + var binding = + GameLogicIntakeAuthorizationBinding.fromStored( + request.getOriginalIntakeAuthorization().toByteArray()); + if (!binding.digest().equals(request.getIntakeAuthorizationDigest())) + throw new IllegalArgumentException("Changed original intake digest"); + return new AccountGameLogicIntakeSettlementReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getReadRequestId()), + binding); + } + + public static SettleGameLogicIntakeResponse toResponse( + AccountGameLogicIntakeSettlementReadEvidence evidence) { + return SettleGameLogicIntakeResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setOriginalSettlementReceipt(ByteString.copyFrom(evidence.receipt().canonicalBytes())) + .setSettlementReceiptDigest(evidence.receipt().digest()) + .build(); + } + + public static AccountGameLogicIntakeSettlementReadEvidence fromResponse( + AccountGameLogicIntakeSettlementReadEvidence.Request request, + SettleGameLogicIntakeResponse response) { + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || response.getOriginalSettlementReceipt().size() + > AccountGameLogicIntakeSettlementEvidence.MAX_CANONICAL_BYTES) + throw new IllegalArgumentException("Changed or oversized settlement evidence"); + var receipt = + AccountGameLogicIntakeSettlementEvidence.fromStored( + response.getOriginalSettlementReceipt().toByteArray()); + if (!receipt.digest().equals(response.getSettlementReceiptDigest())) + throw new IllegalArgumentException("Changed settlement receipt digest"); + return new AccountGameLogicIntakeSettlementReadEvidence(request, receipt); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadClient.java new file mode 100644 index 0000000000..3fc4c8e5e9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadClient.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.common.gamelogic; + +/** Account-owned settlement production/recovery, invoked outside SQL by Game Design. */ +@FunctionalInterface +public interface AccountGameLogicIntakeSettlementReadClient { + AccountGameLogicIntakeSettlementReadEvidence read( + AccountGameLogicIntakeSettlementReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadEvidence.java new file mode 100644 index 0000000000..bc31949a76 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadEvidence.java @@ -0,0 +1,56 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact Account receipt response; it grants no fresh intake authority. */ +public record AccountGameLogicIntakeSettlementReadEvidence( + Request request, AccountGameLogicIntakeSettlementEvidence receipt) { + public AccountGameLogicIntakeSettlementReadEvidence { + Objects.requireNonNull(request); + Objects.requireNonNull(receipt); + if (!request.targetNamespace().equals(receipt.terminal().operation().targetNamespace()) + || !Arrays.equals( + request.binding().canonicalBytes(), receipt.terminal().authorizationBytes())) + throw new IllegalArgumentException("Receipt differs from original intake authorization"); + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + GameLogicIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Supported settlement schema and namespace required"); + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + Objects.requireNonNull(binding); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.fenceId()) + || readRequestId.equals(binding.intakeRequestId())) + throw new IllegalArgumentException("Separate transport correlation required"); + } + + public static Request create(String namespace, GameLogicIntakeAuthorizationBinding binding) { + return new Request(1, namespace, UUID.randomUUID(), binding); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && readRequestId.equals(other.readRequestId) + && Arrays.equals(binding.canonicalBytes(), other.binding.canonicalBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, targetNamespace, readRequestId, Arrays.hashCode(binding.canonicalBytes())); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainClient.java new file mode 100644 index 0000000000..85bc7978e2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainClient.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.common.gamelogic; + +/** Transport boundary for exact Game Logic selected-source retention. */ +public interface GameLogicIntakeRetainClient { + GameLogicIntakeRetainEvidence retain(GameLogicIntakeRetainEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainEvidence.java new file mode 100644 index 0000000000..b41d580b65 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainEvidence.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact request and terminal evidence for one transport attempt to retain selected rule input. */ +public record GameLogicIntakeRetainEvidence( + Request request, GameLogicGameplayRuleIntakeTerminal terminal) { + public static final int MAX_AUTHORIZATION_BYTES = 4 * 1024 * 1024; + + public GameLogicIntakeRetainEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(terminal, "terminal"); + if (!request.targetNamespace().equals(terminal.operation().targetNamespace()) + || !Arrays.equals(request.originalAuthorizationBytes(), terminal.authorizationBytes()) + || !request.authorizationDigest().equals(terminal.authorizationDigest())) { + throw new IllegalArgumentException( + "Terminal differs from exact namespace or original authorization"); + } + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID correlationId, + GameLogicIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Supported retain schema and namespace required"); + } + DraftAuthorizationFenceBinding.requireUuid(correlationId); + Objects.requireNonNull(binding, "binding"); + if (binding.canonicalBytes().length > MAX_AUTHORIZATION_BYTES) { + throw new IllegalArgumentException("Original intake authorization exceeds 4 MiB"); + } + if (correlationId.equals(binding.operationId()) + || correlationId.equals(binding.fenceId()) + || correlationId.equals(binding.intakeRequestId())) { + throw new IllegalArgumentException("Separate transport correlation required"); + } + } + + public static Request create( + String targetNamespace, GameLogicIntakeAuthorizationBinding binding) { + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (correlation.equals(binding.operationId()) + || correlation.equals(binding.fenceId()) + || correlation.equals(binding.intakeRequestId())); + return new Request(1, targetNamespace, correlation, binding); + } + + public byte[] originalAuthorizationBytes() { + return binding.canonicalBytes(); + } + + public String authorizationDigest() { + return binding.digest(); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && correlationId.equals(other.correlationId) + && Arrays.equals(originalAuthorizationBytes(), other.originalAuthorizationBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, + targetNamespace, + correlationId, + Arrays.hashCode(originalAuthorizationBytes())); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodec.java new file mode 100644 index 0000000000..5090b15279 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodec.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; + +/** Closed request echo and canonical original-terminal mapping for the retain transport. */ +public final class GameLogicIntakeRetainProtoCodec { + public static final int MAX_WIRE_BYTES = GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES; + + private GameLogicIntakeRetainProtoCodec() {} + + public static RetainGameplayRuleIntakeRequest toRequest( + GameLogicIntakeRetainEvidence.Request request) { + var wire = + RetainGameplayRuleIntakeRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setCorrelationId(request.correlationId().toString()) + .setOriginalIntakeAuthorization( + ByteString.copyFrom(request.originalAuthorizationBytes())) + .setIntakeAuthorizationDigest(request.authorizationDigest()) + .build(); + if (wire.getSerializedSize() > MAX_WIRE_BYTES) { + throw new IllegalArgumentException("Oversized intake retain request"); + } + return wire; + } + + /** Call only after authenticating the exact same-namespace Game Design workload. */ + public static GameLogicIntakeRetainEvidence.Request fromRequest( + RetainGameplayRuleIntakeRequest request) { + if (request == null + || !request.getUnknownFields().asMap().isEmpty() + || request.getSerializedSize() > MAX_WIRE_BYTES + || request.getOriginalIntakeAuthorization().isEmpty() + || request.getOriginalIntakeAuthorization().size() + > GameLogicIntakeRetainEvidence.MAX_AUTHORIZATION_BYTES) { + throw new IllegalArgumentException("Unknown or oversized intake retain request"); + } + DraftAuthorizationFenceBinding.canonicalUuid(request.getCorrelationId()); + var bytes = request.getOriginalIntakeAuthorization().toByteArray(); + var binding = GameLogicIntakeAuthorizationBinding.fromStored(bytes); + if (!Arrays.equals(bytes, binding.canonicalBytes()) + || !binding.digest().equals(request.getIntakeAuthorizationDigest())) { + throw new IllegalArgumentException("Changed original intake authorization"); + } + return new GameLogicIntakeRetainEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getCorrelationId()), + binding); + } + + public static RetainGameplayRuleIntakeResponse toResponse( + GameLogicIntakeRetainEvidence evidence) { + var terminal = evidence.terminal(); + byte[] terminalBytes = terminal.canonicalBytes(); + if (terminalBytes.length > GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Oversized original intake terminal"); + } + var response = + RetainGameplayRuleIntakeResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setOriginalTerminal(ByteString.copyFrom(terminalBytes)) + .setTerminalDigest(terminal.digest()) + .build(); + if (response.getSerializedSize() > MAX_WIRE_BYTES) { + throw new IllegalArgumentException("Oversized intake retain response"); + } + return response; + } + + public static GameLogicIntakeRetainEvidence fromResponse( + GameLogicIntakeRetainEvidence.Request request, RetainGameplayRuleIntakeResponse response) { + if (response == null + || !response.getUnknownFields().asMap().isEmpty() + || response.getSerializedSize() > MAX_WIRE_BYTES + || !response.hasRequest() + || !response.getRequest().getUnknownFields().asMap().isEmpty() + || !toRequest(request).equals(response.getRequest()) + || response.getOriginalTerminal().isEmpty() + || response.getOriginalTerminal().size() + > GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Changed intake retain correlation or terminal size"); + } + var terminal = + GameLogicGameplayRuleIntakeTerminal.fromStored( + response.getOriginalTerminal().toByteArray()); + if (!terminal.digest().equals(response.getTerminalDigest())) { + throw new IllegalArgumentException("Changed original intake terminal digest"); + } + return new GameLogicIntakeRetainEvidence(request, terminal); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java new file mode 100644 index 0000000000..fc62e0ae82 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcAccountGameLogicIntakeSettlementReadClient.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSettlementServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Explicit file-backed mTLS client for the exact same-namespace Account settlement read. */ +public final class GrpcAccountGameLogicIntakeSettlementReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountGameLogicIntakeSettlementServiceGrpc + .AccountGameLogicIntakeSettlementServiceBlockingStub> + implements AccountGameLogicIntakeSettlementReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcAccountGameLogicIntakeSettlementReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcAccountGameLogicIntakeSettlementReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account intake settlement read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account intake settlement read stub unavailable"); + initialized = true; + } + + /** + * Returns a validated immutable settlement receipt after exact Account server mTLS verification. + */ + @Override + public AccountGameLogicIntakeSettlementReadEvidence read( + AccountGameLogicIntakeSettlementReadEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + throw new IllegalStateException("Account settlement transport must run outside SQL"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account intake settlement read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .settleGameLogicIntake(AccountGameLogicIntakeSettlementProtoCodec.toRequest(request)); + try { + return AccountGameLogicIntakeSettlementProtoCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Account returned invalid settlement evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountGameLogicIntakeSettlementServiceGrpc + .AccountGameLogicIntakeSettlementServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountGameLogicIntakeSettlementServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withMaxInboundMessageSize(AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountGameLogicIntakeSettlementServiceGrpc + .AccountGameLogicIntakeSettlementServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account intake settlement read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Account intake settlement read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account intake settlement read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account intake settlement read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account intake settlement read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account intake settlement read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java new file mode 100644 index 0000000000..6ec08f5c07 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClient.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeServiceGrpc; + +/** File-backed mTLS client for the unregistered selected-source retain transport. */ +public final class GrpcGameLogicIntakeRetainClient + extends AbstractReloadingBlockingGrpcClient< + GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceBlockingStub> + implements GameLogicIntakeRetainClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcGameLogicIntakeRetainClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcGameLogicIntakeRetainClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Game Logic intake retain client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Game Logic intake retain stub unavailable"); + } + initialized = true; + } + + @Override + public GameLogicIntakeRetainEvidence retain(GameLogicIntakeRetainEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) { + throw new IllegalStateException("Game Logic intake retain transport must run outside SQL"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Logic intake retain must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .retainGameplayRuleIntake(GameLogicIntakeRetainProtoCodec.toRequest(request)); + try { + return GameLogicIntakeRetainProtoCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Logic returned invalid intake retain evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameLogicService(); + } + + @Override + protected String defaultTarget() { + return "game-logic-service:6565"; + } + + @Override + protected GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-logic-service"; + return GameLogicGameplayRuleIntakeServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withMaxInboundMessageSize(GameLogicIntakeRetainProtoCodec.MAX_WIRE_BYTES) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Logic intake retain client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Game Logic intake retain requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Logic intake retain requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Logic intake retain requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Logic intake retain " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Logic intake retain " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java new file mode 100644 index 0000000000..fa86e95a08 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java @@ -0,0 +1,711 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeRequest; +import net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Structural and actual loopback-mTLS proof for the closed Account settlement transport. */ +class AccountGameLogicIntakeSettlementReadGrpcTest { + private static final String NAMESPACE = "test"; + private static final String GL_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_GL_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final int LARGE_SOURCE_ENTRIES = 1800; + + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private GrpcAccountGameLogicIntakeSettlementReadClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createTrustedCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void roundTripsExactReceiptsAndNewCorrelationRetries() { + for (var outcome : Outcome.values()) { + var evidence = evidence("test", 1, outcome); + var originalBytes = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + originalBytes, "account-game-logic-intake-settlement/v1"); + DraftAuthorizationFenceBinding.frame( + originalBytes, evidence.receipt().terminal().canonicalBytes()); + assertThat(evidence.receipt().canonicalBytes()).isEqualTo(originalBytes.toByteArray()); + var request = + AccountGameLogicIntakeSettlementProtoCodec.fromRequest( + AccountGameLogicIntakeSettlementProtoCodec.toRequest(evidence.request())); + assertThat(request).isEqualTo(evidence.request()); + assertThat(request.hashCode()).isEqualTo(evidence.request().hashCode()); + var wire = AccountGameLogicIntakeSettlementProtoCodec.toResponse(evidence); + assertThat( + AccountGameLogicIntakeSettlementProtoCodec.fromResponse(request, wire) + .receipt() + .canonicalBytes()) + .isEqualTo(evidence.receipt().canonicalBytes()); + var retry = + AccountGameLogicIntakeSettlementReadEvidence.Request.create("test", request.binding()); + var replay = new AccountGameLogicIntakeSettlementReadEvidence(retry, evidence.receipt()); + assertThat( + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + retry, AccountGameLogicIntakeSettlementProtoCodec.toResponse(replay)) + .receipt() + .digest()) + .isEqualTo(evidence.receipt().digest()); + assertThatThrownBy(() -> AccountGameLogicIntakeSettlementProtoCodec.fromResponse(retry, wire)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsChangedEvidenceOversizeTrailingAndNoncanonicalReceipts() { + var evidence = evidence("test", 1, Outcome.RETAINED); + var wire = AccountGameLogicIntakeSettlementProtoCodec.toResponse(evidence); + var changed = evidence("test", 1, Outcome.RETAINED); + assertThatThrownBy( + () -> + new AccountGameLogicIntakeSettlementReadEvidence( + evidence.request(), changed.receipt())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountGameLogicIntakeSettlementReadEvidence( + AccountGameLogicIntakeSettlementReadEvidence.Request.create( + "other", evidence.request().binding()), + evidence.receipt())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setSettlementReceiptDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var unknown = + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromRequest( + wire.getRequest().toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setTargetNamespace("other")) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setOriginalSettlementReceipt( + ByteString.copyFrom(changed.receipt().canonicalBytes())) + .setSettlementReceiptDigest(changed.receipt().digest()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), wire.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromRequest( + wire.getRequest().toBuilder().setIntakeAuthorizationDigest("changed").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromRequest( + wire.getRequest().toBuilder() + .setOriginalIntakeAuthorization(ByteString.copyFrom(new byte[4194305])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + byte[] trailing = + java.util.Arrays.copyOf( + evidence.receipt().canonicalBytes(), evidence.receipt().canonicalBytes().length + 1); + assertThatThrownBy(() -> AccountGameLogicIntakeSettlementEvidence.fromStored(trailing)) + .isInstanceOf(IllegalArgumentException.class); + byte[] wrongSchema = evidence.receipt().canonicalBytes(); + wrongSchema[Integer.BYTES] ^= 1; + assertThatThrownBy(() -> AccountGameLogicIntakeSettlementEvidence.fromStored(wrongSchema)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setOriginalSettlementReceipt( + ByteString.copyFrom( + new byte + [AccountGameLogicIntakeSettlementEvidence.MAX_CANONICAL_BYTES + + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse + .getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresFileBackedMtlsConfiguredNamespaceAndNoAmbientSql() throws Exception { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + client = + new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, + pki.clientProperties(tempDirectory, pki.accountClient()), + new GrpcChannelFactory(), + NAMESPACE); + var evidence = evidence("test", 1, Outcome.ABORTED); + assertThatThrownBy(() -> client.read(evidence.request())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + client.read( + AccountGameLogicIntakeSettlementReadEvidence.Request.create( + "other", evidence.request().binding()))) + .isInstanceOf(IllegalArgumentException.class); + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside SQL"); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager.clear(); + } + org.springframework.transaction.support.TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside SQL"); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager.clear(); + } + client.close(); + assertThatThrownBy(() -> client.init()).isInstanceOf(IllegalStateException.class); + } + + @Test + void actualMtlsCarriesReceiptAboveFourMiBAndRejectsSubstitutedServerBeforeDispatch() + throws Exception { + var large = evidence("test", LARGE_SOURCE_ENTRIES, Outcome.RETAINED); + assertThat(large.receipt().canonicalBytes().length).isGreaterThan(4 * 1024 * 1024); + startServer(pki.gameLogicServer(), large); + client = newClient(server, pki.accountClient()); + client.init(); + var actual = client.read(large.request()); + assertThat(actual.receipt().canonicalBytes()).isEqualTo(large.receipt().canonicalBytes()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + stopTransport(); + startServer(pki.wrongServer(), large); + client = newClient(server, pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.read(large.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + + private enum Outcome { + RETAINED, + ABORTED + } + + private void startServer( + TestIdentity identity, AccountGameLogicIntakeSettlementReadEvidence evidence) + throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var service = + new AccountGameLogicIntakeSettlementServiceGrpc + .AccountGameLogicIntakeSettlementServiceImplBase() { + @Override + public void settleGameLogicIntake( + SettleGameLogicIntakeRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + var request = AccountGameLogicIntakeSettlementProtoCodec.fromRequest(wire); + var response = + AccountGameLogicIntakeSettlementProtoCodec.toResponse( + new AccountGameLogicIntakeSettlementReadEvidence(request, evidence.receipt())); + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(AccountGameLogicIntakeSettlementEvidence.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcAccountGameLogicIntakeSettlementReadClient newClient( + Server target, TestIdentity local) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + target.getPort()); + return new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, pki.clientProperties(tempDirectory, local), new GrpcChannelFactory(), NAMESPACE); + } + + /** These canonical bytes are deliberately synthetic transport evidence, not owner provenance. */ + private static AccountGameLogicIntakeSettlementReadEvidence evidence( + String namespace, int entryCount, Outcome outcome) { + var tenant = UUID.randomUUID(); + var version = UUID.randomUUID(); + var requestId = UUID.randomUUID(); + var commitId = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + var definitions = new ArrayList(); + var revisions = new ArrayList(); + var revisionIds = new ArrayList(); + for (int index = 0; index < entryCount; index++) { + var definition = + new GameplayRuleManifest.AdmissionTag( + String.format(java.util.Locale.ROOT, "tag-%05d", index)); + definitions.add(definition); + var revisionId = UUID.randomUUID(); + revisionIds.add(revisionId); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + revisionId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload(definition))); + } + var selectedBinding = + DraftCommitBinding.create( + target, + requestId, + commitId, + "genesis", + List.of(revisions.getFirst()), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var definitionsByFamily = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) + definitionsByFamily.put(family, new ArrayList<>()); + definitionsByFamily.get(GameplayRuleManifest.Family.ADMISSION_TAGS).addAll(definitions); + var manifest = new GameplayRuleManifest(definitionsByFamily); + var entries = new ArrayList>(); + for (int index = 0; index < entryCount; index++) { + var definition = definitions.get(index); + var entryBinding = + DraftCommitBinding.create( + target, + requestId, + UUID.randomUUID(), + "genesis", + List.of(revisions.get(index)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + Integer.toString(index)))); + entries.add( + Map.of( + "family", definition.family().name(), + "definitionJson", GameplayRuleManifest.canonical(definition), + "sourceBindingJson", entryBinding.canonicalJson(), + "sourceBindingDigest", entryBinding.digest(), + "revisionOrder", "0", + "revisionId", revisionIds.get(index).toString())); + } + String snapshot = + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + entries)); + var source = new GameplayRuleSelectedSource(snapshot); + var accountEvidence = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + var authorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.fromString(accountEvidence.scopeId()), + source, + List.of(accountEvidence)); + var operation = new GameLogicGameplayRuleIntakeOperation(namespace, authorization); + var terminal = + outcome == Outcome.RETAINED + ? GameLogicGameplayRuleIntakeTerminal.retained( + operation, + source.canonicalBytes(), + manifest.canonicalJson().getBytes(StandardCharsets.UTF_8)) + : GameLogicGameplayRuleIntakeTerminal.aborted(operation); + return new AccountGameLogicIntakeSettlementReadEvidence( + AccountGameLogicIntakeSettlementReadEvidence.Request.create(namespace, authorization), + new AccountGameLogicIntakeSettlementEvidence(terminal)); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameLogicServer, + TestIdentity wrongServer, + TestIdentity accountClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("terminal-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD terminal-read test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("terminal-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "game-logic-server", GL_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_GL_URI, true), + issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("terminal-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodecTest.java new file mode 100644 index 0000000000..48525ed91f --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeRetainProtoCodecTest.java @@ -0,0 +1,360 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; +import org.junit.jupiter.api.Test; + +class GameLogicIntakeRetainProtoCodecTest { + private static final String NAMESPACE = "test"; + + @Test + void roundTripsExactAuthorizationAndCompleteRetainedTerminal() { + var authorization = authorization(); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, authorization); + var decodedRequest = + GameLogicIntakeRetainProtoCodec.fromRequest( + GameLogicIntakeRetainProtoCodec.toRequest(request)); + assertThat(decodedRequest).isEqualTo(request); + assertThat(decodedRequest.hashCode()).isEqualTo(request.hashCode()); + assertThat(decodedRequest.originalAuthorizationBytes()) + .containsExactly(authorization.canonicalBytes()); + + var source = authorization.source(); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var evidence = new GameLogicIntakeRetainEvidence(request, terminal); + var response = GameLogicIntakeRetainProtoCodec.toResponse(evidence); + var decoded = GameLogicIntakeRetainProtoCodec.fromResponse(request, response); + assertThat(response.getRequest()).isEqualTo(GameLogicIntakeRetainProtoCodec.toRequest(request)); + assertThat(decoded.terminal().canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(GameLogicIntakeRetainProtoCodec.MAX_WIRE_BYTES); + assertThat(GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES).isEqualTo(16 * 1024 * 1024); + assertThat(GameLogicIntakeRetainProtoCodec.MAX_WIRE_BYTES).isEqualTo(24 * 1024 * 1024); + } + + @Test + void rejectsUnknownFieldsChangedRequestEchoChangedBindingAndTerminalEvidence() { + var authorization = authorization(); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, authorization); + var terminal = + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization)); + var response = + GameLogicIntakeRetainProtoCodec.toResponse( + new GameLogicIntakeRetainEvidence(request, terminal)); + + var requestWithUnknown = + GameLogicIntakeRetainProtoCodec.toRequest(request).toBuilder() + .setUnknownFields(unknownFields()) + .build(); + assertThatThrownBy(() -> GameLogicIntakeRetainProtoCodec.fromRequest(requestWithUnknown)) + .isInstanceOf(IllegalArgumentException.class); + + var changedAuthorization = + new GameLogicIntakeAuthorizationBinding( + authorization.operationId(), + UUID.randomUUID(), + authorization.intakeRequestId(), + authorization.actorAccountId(), + authorization.source(), + authorization.sources()); + var changedRequest = + new GameLogicIntakeRetainEvidence.Request( + 1, NAMESPACE, request.correlationId(), changedAuthorization); + assertThatThrownBy(() -> GameLogicIntakeRetainProtoCodec.fromResponse(changedRequest, response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new GameLogicIntakeRetainEvidence(request, terminalFor(changedAuthorization))) + .isInstanceOf(IllegalArgumentException.class); + + var badTerminalDigest = + response.toBuilder().setTerminalDigest("sha256:" + "0".repeat(64)).build(); + assertThatThrownBy( + () -> GameLogicIntakeRetainProtoCodec.fromResponse(request, badTerminalDigest)) + .isInstanceOf(IllegalArgumentException.class); + + byte[] changedBytes = response.getOriginalTerminal().toByteArray(); + changedBytes[changedBytes.length - 1] ^= 1; + var changedTerminal = + response.toBuilder().setOriginalTerminal(ByteString.copyFrom(changedBytes)).build(); + assertThatThrownBy(() -> GameLogicIntakeRetainProtoCodec.fromResponse(request, changedTerminal)) + .isInstanceOf(IllegalArgumentException.class); + + var responseWithUnknown = response.toBuilder().setUnknownFields(unknownFields()).build(); + assertThatThrownBy( + () -> GameLogicIntakeRetainProtoCodec.fromResponse(request, responseWithUnknown)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsTerminalForAnotherNamespaceEvenWhenAuthorizationBytesMatch() { + var authorization = authorization(); + var request = GameLogicIntakeRetainEvidence.Request.create("other", authorization); + var terminalForWrongNamespace = + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization)); + + assertThatThrownBy(() -> new GameLogicIntakeRetainEvidence(request, terminalForWrongNamespace)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + } + + @Test + void rejectsOversizedAuthorizationAndTerminalAtTheirCanonicalLimits() { + var authorization = authorization(); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, authorization); + var oversizedAuthorization = + RetainGameplayRuleIntakeRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setCorrelationId(UUID.randomUUID().toString()) + .setOriginalIntakeAuthorization( + ByteString.copyFrom( + new byte[GameLogicIntakeRetainEvidence.MAX_AUTHORIZATION_BYTES + 1])) + .setIntakeAuthorizationDigest(authorization.digest()) + .build(); + assertThatThrownBy(() -> GameLogicIntakeRetainProtoCodec.fromRequest(oversizedAuthorization)) + .isInstanceOf(IllegalArgumentException.class); + + var oversizedTerminal = + RetainGameplayRuleIntakeResponse.newBuilder() + .setRequest(GameLogicIntakeRetainProtoCodec.toRequest(request)) + .setOriginalTerminal( + ByteString.copyFrom( + new byte[GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES + 1])) + .setTerminalDigest("sha256:" + "0".repeat(64)) + .build(); + assertThat(oversizedTerminal.getSerializedSize()) + .isLessThanOrEqualTo(GameLogicIntakeRetainProtoCodec.MAX_WIRE_BYTES); + assertThatThrownBy( + () -> GameLogicIntakeRetainProtoCodec.fromResponse(request, oversizedTerminal)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void acceptsTerminalAboveDefaultGrpcMessageLimitWithinDeclaredWireLimit() { + var authorization = largeAuthorization(1800); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, authorization); + var source = authorization.source(); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var response = + GameLogicIntakeRetainProtoCodec.toResponse( + new GameLogicIntakeRetainEvidence(request, terminal)); + + assertThat(terminal.canonicalBytes().length).isGreaterThan(4 * 1024 * 1024); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(GameLogicGameplayRuleIntakeTerminal.MAX_WIRE_BYTES); + assertThat( + GameLogicIntakeRetainProtoCodec.fromResponse(request, response) + .terminal() + .canonicalBytes()) + .containsExactly(terminal.canonicalBytes()); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static GameLogicGameplayRuleIntakeTerminal terminalFor( + GameLogicIntakeAuthorizationBinding authorization) { + return GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization)); + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + UUID actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var selectedBinding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var selectedSource = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + selectedSource, + List.of(accountSource)); + } + + static GameLogicIntakeAuthorizationBinding largeAuthorization(int entryCount) { + UUID actor = UUID.randomUUID(); + UUID tenant = UUID.randomUUID(); + UUID version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + var requestId = UUID.randomUUID(); + var definitions = new ArrayList(); + var revisions = new ArrayList(); + var revisionIds = new ArrayList(); + for (int index = 0; index < entryCount; index++) { + var definition = + new GameplayRuleManifest.AdmissionTag( + String.format(java.util.Locale.ROOT, "tag-%05d", index)); + definitions.add(definition); + var revisionId = UUID.randomUUID(); + revisionIds.add(revisionId); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + revisionId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSourceRevision.upsertPayload(definition))); + } + var selectedBinding = + DraftCommitBinding.create( + target, + requestId, + UUID.randomUUID(), + "genesis", + List.of(revisions.getFirst()), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var families = + new EnumMap>( + GameplayRuleManifest.Family.class); + for (var family : GameplayRuleManifest.Family.values()) families.put(family, new ArrayList<>()); + families.get(GameplayRuleManifest.Family.ADMISSION_TAGS).addAll(definitions); + var manifest = new GameplayRuleManifest(families); + var entries = new ArrayList>(); + for (int index = 0; index < entryCount; index++) { + var definition = definitions.get(index); + var entryBinding = + DraftCommitBinding.create( + target, + requestId, + UUID.randomUUID(), + "genesis", + List.of(revisions.get(index)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + Integer.toString(index)))); + entries.add( + Map.of( + "family", definition.family().name(), + "definitionJson", GameplayRuleManifest.canonical(definition), + "sourceBindingJson", entryBinding.canonicalJson(), + "sourceBindingDigest", entryBinding.digest(), + "revisionOrder", "0", + "revisionId", revisionIds.get(index).toString())); + } + String snapshot = + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + manifest.canonicalJson(), + "entries", + entries)); + var source = new GameplayRuleSelectedSource(snapshot); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java new file mode 100644 index 0000000000..c2a6e431fb --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java @@ -0,0 +1,383 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeServiceGrpc; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical mTLS and message-size proof for the standalone GL intake retain client. */ +class GrpcGameLogicIntakeRetainClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String GL_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; + private static final String WRONG_GL_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String GD_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @TempDir static Path tempDirectory; + private static TestPki pki; + + private Server server; + private GrpcGameLogicIntakeRetainClient client; + private AtomicInteger calls; + private AtomicReference clientPeer; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void acceptsLargeTerminalFromExactGameLogicServerAndRejectsSubstitutedServer() throws Exception { + var authorization = GameLogicIntakeRetainProtoCodecTest.largeAuthorization(1800); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, authorization); + var source = authorization.source(); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + byte[] expectedTerminal = terminal.canonicalBytes(); + assertThat(expectedTerminal.length).isGreaterThan(4 * 1024 * 1024); + + startServer(pki.gameLogicServer(), request, terminal); + client = newClient(server.getPort()); + client.init(); + var actual = client.retain(request); + assertThat(actual.terminal().canonicalBytes()).containsExactly(expectedTerminal); + assertThat(calls).hasValue(1); + assertThat(clientPeer).hasValue(GD_URI); + + stopTransport(); + startServer(pki.wrongServer(), request, terminal); + client = newClient(server.getPort()); + client.init(); + assertThatThrownBy(() -> client.retain(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(0); + assertThat(clientPeer.get()).isNull(); + } + + private void startServer( + TestIdentity identity, + GameLogicIntakeRetainEvidence.Request expectedRequest, + GameLogicGameplayRuleIntakeTerminal terminal) + throws Exception { + calls = new AtomicInteger(); + clientPeer = new AtomicReference<>(); + var service = + new GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceImplBase() { + @Override + public void retainGameplayRuleIntake( + RetainGameplayRuleIntakeRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + var peer = GrpcPeerIdentity.current(); + clientPeer.set(peer == null ? null : peer.uri()); + var decoded = GameLogicIntakeRetainProtoCodec.fromRequest(wire); + assertThat(decoded).isEqualTo(expectedRequest); + observer.onNext( + GameLogicIntakeRetainProtoCodec.toResponse( + new GameLogicIntakeRetainEvidence(decoded, terminal))); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameLogicIntakeRetainProtoCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcGameLogicIntakeRetainClient newClient(int port) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameLogicService("localhost:" + port); + return new GrpcGameLogicIntakeRetainClient( + endpoints, + pki.clientProperties(tempDirectory, pki.gameDesignClient()), + new GrpcChannelFactory(), + NAMESPACE); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameLogicServer, + TestIdentity wrongServer, + TestIdentity gameDesignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("intake-retain-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD intake-retain test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("intake-retain-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "game-logic-server", GL_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_GL_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GD_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("intake-retain-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String eku = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + eku, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java index 4d3e3c6cf8..c4678d333b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java @@ -550,13 +550,25 @@ private void requireCompleteControlPlaneScopes( units.stream().filter(this::isPolicyScope).toList(); var assets = units.stream().filter(AssetSourceRepository::isScope).toList(); var gameplay = units.stream().filter(GameplayRuleSource::isScope).toList(); + var branding = units.stream().filter(BrandingSourceRepository::isScope).toList(); + var templateConfigs = units.stream().filter(TemplateConfigSource::isScope).toList(); boolean assetMutation = !AssetSource.mutations(binding).isEmpty(); boolean gameplayMutation = !GameplayRuleSource.mutations(binding).isEmpty(); + boolean brandingMutation = !BrandingSource.mutations(binding).isEmpty(); + boolean templateConfigMutation = !TemplateConfigSource.mutations(binding).isEmpty(); if (commands.size() != (commandMutations.isEmpty() ? 0 : 1) || policies.size() != (policyMutation ? 1 : 0) || assets.size() != (assetMutation ? 1 : 0) || gameplay.size() != (gameplayMutation ? 1 : 0) - || commands.size() + policies.size() + assets.size() + gameplay.size() != units.size()) { + || branding.size() != (brandingMutation ? 1 : 0) + || templateConfigs.size() != (templateConfigMutation ? 1 : 0) + || commands.size() + + policies.size() + + assets.size() + + gameplay.size() + + branding.size() + + templateConfigs.size() + != units.size()) { throw new IllegalArgumentException( "Complete supported Game Design control-plane scopes are required"); } @@ -564,6 +576,9 @@ private void requireCompleteControlPlaneScopes( if (!policies.isEmpty()) requireScopeTarget(policies.getFirst(), binding.target()); if (!assets.isEmpty()) requireScopeTarget(assets.getFirst(), binding.target()); if (!gameplay.isEmpty()) requireScopeTarget(gameplay.getFirst(), binding.target()); + if (!branding.isEmpty()) requireScopeTarget(branding.getFirst(), binding.target()); + if (!templateConfigs.isEmpty()) + requireScopeTarget(templateConfigs.getFirst(), binding.target()); } private boolean isCommandScope(DraftCommitBinding.AffectedUnit unit) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java index aa86ac5768..c22014d880 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java @@ -45,7 +45,9 @@ public static boolean isPolicyRevision(DraftCommitBinding.RevisionPayload input) if (RealmEntryPolicy.REVISION_KIND.equals(kind)) return true; if ("COMMAND_DEFINITION".equals(kind) || AssetSource.REVISION_KIND.equals(kind) - || GameplayRuleSource.REVISION_KIND.equals(kind)) return false; + || GameplayRuleSource.REVISION_KIND.equals(kind) + || BrandingSource.REVISION_KIND.equals(kind) + || TemplateConfigSource.REVISION_KIND.equals(kind)) return false; throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceipt.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceipt.java new file mode 100644 index 0000000000..ea48f81e03 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceipt.java @@ -0,0 +1,71 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; + +/** Derived evidence outside the authored preimage; canonical integrity grants no authority. */ +public record SelectedDraftGameLogicReceipt( + AuthoredDraftPublishSelection selection, + GameLogicIntakeAuthorizationBinding authorization, + AccountGameLogicIntakeSettlementEvidence receipt) { + public static final int MAX_SELECTION_BYTES = 8 * 1024 * 1024; + + public SelectedDraftGameLogicReceipt { + Objects.requireNonNull(receipt, "receipt"); + requireExactSelection(selection, authorization); + requireRetainedTerminal(authorization, receipt.terminal()); + // Enforce each existing codec's closed payload limit before storage. + authorization.canonicalBytes(); + receipt.canonicalBytes(); + } + + static void requireRetainedTerminal( + GameLogicIntakeAuthorizationBinding authorization, + GameLogicGameplayRuleIntakeTerminal terminal) { + if (terminal.outcome() != GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED + || !Arrays.equals(authorization.canonicalBytes(), terminal.authorizationBytes()) + || !authorization.digest().equals(terminal.authorizationDigest()) + || !Arrays.equals( + authorization.source().canonicalBytes(), terminal.selectedSourceBytes())) { + throw new IllegalArgumentException("Exact RETAINED Account settlement required"); + } + } + + public String workflowIdentity() { + return PublicationDigestRequestBinding.full( + selection.intent().canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + selection.intent().publishRequestId()) + .derivedWorkflowIdentity(); + } + + public static void requireExactSelection( + AuthoredDraftPublishSelection selection, GameLogicIntakeAuthorizationBinding authorization) { + Objects.requireNonNull(selection, "selection"); + Objects.requireNonNull(authorization, "authorization"); + if (selection.canonicalBytes().length > MAX_SELECTION_BYTES) + throw new IllegalArgumentException("Selected publication evidence exceeds 8 MiB"); + authorization.canonicalBytes(); + if (!selection.target().canonicalTenantId().equals(authorization.tenantId()) + || !selection.target().canonicalVersionId().equals(authorization.versionId()) + || !Arrays.equals( + selection.selectedCommit().canonicalBytes(), + authorization.source().binding().canonicalBytes())) { + throw new IllegalArgumentException("Intake differs from complete selected Draft binding"); + } + } + + public void requireExactRequest( + AuthoredDraftPublishSelection expectedSelection, + GameLogicIntakeAuthorizationBinding expectedAuthorization) { + if (!Arrays.equals(selection.canonicalBytes(), expectedSelection.canonicalBytes()) + || !Arrays.equals(authorization.canonicalBytes(), expectedAuthorization.canonicalBytes())) { + throw new IllegalStateException("Selected Game Logic receipt identity conflict"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java new file mode 100644 index 0000000000..410be0489f --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.gamedesign.publication; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered immutable derived-receipt storage, separate from publication-operation bytes. */ +public class SelectedDraftGameLogicReceiptRepository { + private final DSLContext dsl; + + @SuppressFBWarnings( + value = {"CT_CONSTRUCTOR_THROW", "EI_EXPOSE_REP2"}, + justification = + "Owner-local persistence collaborator; no resources acquired or finalizer used.") + public SelectedDraftGameLogicReceiptRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + public Optional read( + AuthoredDraftPublishSelection selection, GameLogicIntakeAuthorizationBinding authorization) { + SelectedDraftGameLogicReceipt.requireExactSelection(selection, authorization); + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_selected_game_logic_receipt WHERE canonical_tenant_id = ? AND publish_request_id = ?", + selection.intent().canonicalTenantId(), + selection.intent().publishRequestId()); + if (row == null) return Optional.empty(); + var retained = decode(row); + retained.requireExactRequest(selection, authorization); + return Optional.of(retained); + } + + public SelectedDraftGameLogicReceipt retain(SelectedDraftGameLogicReceipt candidate) { + requireTransaction(); + var selection = candidate.selection(); + // Keep the existing owner lock order: Version before immutable selection. + var target = selection.target(); + if (dsl.fetchOne( + "SELECT v.id FROM version v JOIN game g " + + "ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? " + + "AND v.canonical_version_id = ? AND v.identity_source_game_row_id = ? " + + "AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? " + + "AND v.identity_source_game_row_id > 0 " + + "AND v.identity_source_game_tenant_key = v.tenant_id " + + "AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') " + + "AND v.version_state_epoch > 0 FOR UPDATE OF v", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()) + == null) { + throw new IllegalStateException("Selected Version source proof unavailable"); + } + dsl.fetchOne( + "SELECT canonical_tenant_id FROM game_design_authored_draft_publish_selection WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId()); + var retainedSelection = + new AuthoredDraftPublishSelectionRepository(dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")) + .selection(); + if (!Arrays.equals(selection.canonicalBytes(), retainedSelection.canonicalBytes())) { + throw new IllegalStateException("Selected publication changed before receipt retention"); + } + var prior = read(selection, candidate.authorization()); + if (prior.isPresent()) return requireSameReceipt(candidate, prior.get()); + dsl.execute( + "INSERT INTO game_design_selected_game_logic_receipt (canonical_tenant_id, canonical_version_id, publish_request_id, selection_digest, workflow_identity, selection_bytes, authorization_bytes, authorization_digest, receipt_bytes, receipt_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (canonical_tenant_id, publish_request_id) DO NOTHING", + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId(), + selection.digest(), + candidate.workflowIdentity(), + selection.canonicalBytes(), + candidate.authorization().canonicalBytes(), + candidate.authorization().digest(), + candidate.receipt().canonicalBytes(), + candidate.receipt().digest()); + return requireSameReceipt(candidate, read(selection, candidate.authorization()).orElseThrow()); + } + + private static SelectedDraftGameLogicReceipt requireSameReceipt( + SelectedDraftGameLogicReceipt candidate, SelectedDraftGameLogicReceipt retained) { + if (!Arrays.equals(candidate.receipt().canonicalBytes(), retained.receipt().canonicalBytes())) { + throw new IllegalStateException("Immutable selected Game Logic receipt conflict"); + } + return retained; + } + + private static SelectedDraftGameLogicReceipt decode(Record row) { + byte[] selectionBytes = row.get("selection_bytes", byte[].class); + var selection = + AuthoredDraftPublishSelection.fromStored( + new String(selectionBytes, StandardCharsets.UTF_8), + row.get("selection_digest", String.class)); + var authorization = + GameLogicIntakeAuthorizationBinding.fromStored( + row.get("authorization_bytes", byte[].class)); + var receipt = + AccountGameLogicIntakeSettlementEvidence.fromStored(row.get("receipt_bytes", byte[].class)); + var value = new SelectedDraftGameLogicReceipt(selection, authorization, receipt); + if (!Arrays.equals(selectionBytes, selection.canonicalBytes()) + || !selection + .intent() + .canonicalTenantId() + .equals(row.get("canonical_tenant_id", java.util.UUID.class)) + || !selection + .intent() + .canonicalVersionId() + .equals(row.get("canonical_version_id", java.util.UUID.class)) + || !selection + .intent() + .publishRequestId() + .equals(row.get("publish_request_id", String.class)) + || !value.workflowIdentity().equals(row.get("workflow_identity", String.class)) + || !authorization.digest().equals(row.get("authorization_digest", String.class)) + || !receipt.digest().equals(row.get("receipt_digest", String.class))) { + throw new IllegalStateException("Stored selected Game Logic receipt integrity conflict"); + } + return value; + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Receipt retention requires writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java new file mode 100644 index 0000000000..d5a93c4a87 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptService.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadClient; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered derived-evidence producer. Requires a separately issued original intake order; + * configured authenticated clients, rather than canonical bytes alone, establish owner provenance. + */ +public final class SelectedDraftGameLogicReceiptService { + private final SelectedDraftGameLogicReceiptRepository repository; + private final SelectionReader selections; + private final GameLogicIntakeRetainClient gameLogic; + private final AccountGameLogicIntakeSettlementReadClient account; + private final TransactionTemplate transaction; + private final String namespace; + + public SelectedDraftGameLogicReceiptService( + DSLContext dsl, + PlatformTransactionManager transactions, + GameLogicIntakeRetainClient gameLogic, + AccountGameLogicIntakeSettlementReadClient account, + String namespace) { + this( + new SelectedDraftGameLogicReceiptRepository(dsl), + selection -> + new AuthoredDraftPublishSelectionRepository( + dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId()) + .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection), + transactions, + gameLogic, + account, + namespace); + } + + SelectedDraftGameLogicReceiptService( + SelectedDraftGameLogicReceiptRepository repository, + SelectionReader selections, + PlatformTransactionManager transactions, + GameLogicIntakeRetainClient gameLogic, + AccountGameLogicIntakeSettlementReadClient account, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.selections = Objects.requireNonNull(selections); + this.gameLogic = Objects.requireNonNull(gameLogic); + this.account = Objects.requireNonNull(account); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + transaction.setReadOnly(false); + } + + public SelectedDraftGameLogicReceipt retain( + AuthoredDraftPublishSelection selection, GameLogicIntakeAuthorizationBinding authorization) { + requireNoTransaction(); + SelectedDraftGameLogicReceipt.requireExactSelection(selection, authorization); + var retainedSelection = + selections + .read(selection) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")); + if (!Arrays.equals(selection.canonicalBytes(), retainedSelection.canonicalBytes())) { + throw new IllegalStateException("Selected publication differs from immutable selection"); + } + var prior = repository.read(selection, authorization); + if (prior.isPresent()) { + prior.get().requireExactRequest(selection, authorization); + if (!namespace.equals(prior.get().receipt().terminal().operation().targetNamespace())) + throw new IllegalStateException("Retained intake namespace conflict"); + return prior.get(); + } + var retainRequest = GameLogicIntakeRetainEvidence.Request.create(namespace, authorization); + var retained = gameLogic.retain(retainRequest); + if (retained == null || !retainRequest.equals(retained.request())) { + throw new IllegalStateException("Game Logic retain request readback conflict"); + } + if (!namespace.equals(retained.terminal().operation().targetNamespace()) + || !Arrays.equals(authorization.canonicalBytes(), retained.terminal().authorizationBytes()) + || !authorization.digest().equals(retained.terminal().authorizationDigest())) + throw new IllegalStateException("Game Logic intake authorization or namespace conflict"); + // Settle either genuine terminal. ABORTED releases only its own participation and still + // cannot become a positive publication receipt. + var accountRequest = + AccountGameLogicIntakeSettlementReadEvidence.Request.create(namespace, authorization); + var settled = account.read(accountRequest); + if (settled == null + || !accountRequest.equals(settled.request()) + || !Arrays.equals( + retained.terminal().canonicalBytes(), settled.receipt().terminal().canonicalBytes()) + || !retained.terminal().digest().equals(settled.receipt().terminal().digest())) { + throw new IllegalStateException("Account settlement differs from exact retained intake"); + } + var candidate = new SelectedDraftGameLogicReceipt(selection, authorization, settled.receipt()); + return Objects.requireNonNull(transaction.execute(status -> repository.retain(candidate))); + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Receipt owner RPCs require no ambient SQL transaction"); + } + + @FunctionalInterface + interface SelectionReader { + Optional read(AuthoredDraftPublishSelection selection); + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V61__selected_publication_game_logic_receipt.sql b/services/game-design-service/src/main/resources/db/migration/V61__selected_publication_game_logic_receipt.sql new file mode 100644 index 0000000000..183cd94398 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V61__selected_publication_game_logic_receipt.sql @@ -0,0 +1,52 @@ +-- Derived receipt storage only. Historical selections and publication operations are untouched. +CREATE TABLE game_design_selected_game_logic_receipt ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + publish_request_id VARCHAR(1024) NOT NULL, + selection_digest VARCHAR(71) NOT NULL, + workflow_identity TEXT NOT NULL, + selection_bytes BYTEA NOT NULL, + authorization_bytes BYTEA NOT NULL, + authorization_digest VARCHAR(71) NOT NULL, + receipt_bytes BYTEA NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (canonical_tenant_id, publish_request_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, publish_request_id) + REFERENCES game_design_authored_draft_publish_selection + (canonical_tenant_id, canonical_version_id, publish_request_id) ON DELETE RESTRICT, + CHECK (selection_digest ~ '^sha256:[0-9a-f]{64}$' + AND authorization_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CHECK (workflow_identity = 'publish:' || canonical_tenant_id::text || ':publish-request:' || publish_request_id), + CHECK (octet_length(selection_bytes) BETWEEN 1 AND 8388608), + CHECK (octet_length(authorization_bytes) BETWEEN 1 AND 4194304), + CHECK (octet_length(receipt_bytes) BETWEEN 1 AND 16778240) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_selected_game_logic_receipt() RETURNS trigger AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Selected Game Logic receipts are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM game_design_authored_draft_publish_selection s + WHERE s.canonical_tenant_id = NEW.canonical_tenant_id + AND s.canonical_version_id = NEW.canonical_version_id + AND s.publish_request_id = NEW.publish_request_id + AND s.selection_digest = NEW.selection_digest + AND convert_to(s.selection_json, 'UTF8') = NEW.selection_bytes + ) THEN + RAISE EXCEPTION 'Receipt requires exact existing immutable selection' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_selected_game_logic_receipt + BEFORE INSERT OR UPDATE OR DELETE ON game_design_selected_game_logic_receipt + FOR EACH ROW EXECUTE FUNCTION enforce_gd_selected_game_logic_receipt(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java new file mode 100644 index 0000000000..758c0b3413 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java @@ -0,0 +1,326 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * V61-only PostgreSQL storage proof definitions. The predecessor selection table and upstream + * authority are explicit fixtures; this is not composed authoring or authenticated intake proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class SelectedDraftGameLogicReceiptPostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void migrationPreservesHistoricalSelectionAndReceiptReadbackIsImmutableAndExact() { + var value = receiptFixture(); + var fixture = fixture(value); + var dsl = fixture.dsl(); + var repository = new SelectedDraftGameLogicReceiptRepository(dsl); + fixture.tx().executeWithoutResult(ignored -> repository.retain(value)); + fixture + .tx() + .executeWithoutResult( + ignored -> + assertThat(repository.retain(value).receipt().canonicalBytes()) + .containsExactly(value.receipt().canonicalBytes())); + var recovered = repository.read(value.selection(), value.authorization()).orElseThrow(); + assertThat(recovered.receipt().canonicalBytes()) + .containsExactly(value.receipt().canonicalBytes()); + assertThat(recovered.authorization().canonicalBytes()) + .containsExactly(value.authorization().canonicalBytes()); + assertThat( + dsl.fetchSingle( + "SELECT selection_json FROM game_design_authored_draft_publish_selection") + .get(0, String.class)) + .isEqualTo(value.selection().canonicalJson()); + var changed = + new GameLogicIntakeAuthorizationBinding( + value.authorization().operationId(), + UUID.randomUUID(), + value.authorization().intakeRequestId(), + value.authorization().actorAccountId(), + value.authorization().source(), + value.authorization().sources()); + assertThatThrownBy(() -> repository.read(value.selection(), changed)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_design_selected_game_logic_receipt SET receipt_bytes = ?", + new byte[] {1})) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("DELETE FROM game_design_selected_game_logic_receipt")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + insert( + dsl, + value, + value.selection().canonicalBytes(), + value.receipt().canonicalBytes())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + @Test + void missingReceiptIsAbsentAndChangedSelectionOrOversizedReceiptCannotInsert() { + var value = receiptFixture(); + var fixture = fixture(value); + var dsl = fixture.dsl(); + assertThat( + new SelectedDraftGameLogicReceiptRepository(dsl) + .read(value.selection(), value.authorization())) + .isEmpty(); + assertThatThrownBy(() -> insert(dsl, value, new byte[] {1}, value.receipt().canonicalBytes())) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> insert(dsl, value, value.selection().canonicalBytes(), new byte[16778241])) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM game_design_selected_game_logic_receipt") + .get(0, Long.class)) + .isZero(); + } + + @Test + void ownerTransactionRechecksCompleteSelectionBeforeInsertingDerivedReceipt() { + var value = receiptFixture(); + var fixture = fixture(value); + String altered = + value.selection().canonicalJson().replace("\"notes\":\"\"", "\"notes\":\"changed\""); + String digest = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.digest( + altered.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + // This predecessor fixture permits fault injection; the real V43 owner rejects rewriting. + fixture + .dsl() + .execute( + "UPDATE game_design_authored_draft_publish_selection SET selection_json = ?, selection_digest = ?", + altered, + digest); + var repository = new SelectedDraftGameLogicReceiptRepository(fixture.dsl()); + assertThatThrownBy(() -> fixture.tx().execute(status -> repository.retain(value))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("changed before receipt retention"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM game_design_selected_game_logic_receipt") + .get(0, Long.class)) + .isZero(); + } + + private static Fixture fixture(SelectedDraftGameLogicReceipt value) { + String schema = "receipt_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + DSL.using(data, SQLDialect.POSTGRES).execute("CREATE SCHEMA " + schema); + var scoped = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl() + + (POSTGRES.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema, + POSTGRES.getUsername(), + POSTGRES.getPassword()); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(scoped), SQLDialect.POSTGRES); + dsl.execute( + "CREATE TABLE game_design_authored_draft_publish_selection (canonical_tenant_id UUID NOT NULL, canonical_version_id UUID NOT NULL, publish_request_id TEXT NOT NULL, selection_digest TEXT NOT NULL, selection_json TEXT NOT NULL, game_design_version_row_id BIGINT NOT NULL, game_design_version_tenant_key TEXT NOT NULL, source_game_row_id BIGINT NOT NULL, source_game_tenant_key TEXT NOT NULL, source_provenance_kind TEXT NOT NULL, version_state_epoch BIGINT NOT NULL, selected_commit_request_id UUID NOT NULL, selected_commit_id UUID NOT NULL, selected_commit_digest TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (canonical_tenant_id, canonical_version_id, publish_request_id))"); + dsl.execute( + "CREATE TABLE game (id BIGINT PRIMARY KEY, tenant_id TEXT, canonical_tenant_id UUID, tenant_identity_provenance_kind TEXT, tenant_identity_source_game_id BIGINT, tenant_identity_source_legacy_tenant_id TEXT)"); + dsl.execute( + "CREATE TABLE version (id BIGINT PRIMARY KEY, tenant_id TEXT, canonical_tenant_id UUID, canonical_version_id UUID, identity_source_game_row_id BIGINT, identity_source_game_tenant_key TEXT, identity_source_provenance_kind TEXT, version_state_epoch BIGINT)"); + var target = value.selection().target(); + dsl.execute( + "INSERT INTO game VALUES (?, ?, ?, ?, ?, ?)", + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.canonicalTenantId(), + target.sourceProvenanceKind(), + target.sourceGameRowId(), + target.sourceGameTenantKey()); + dsl.execute( + "INSERT INTO version VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.canonicalTenantId(), + target.canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + Long.parseLong(value.selection().intent().expectedVersionStateEpoch())); + selection(dsl, value); + Flyway.configure() + .dataSource(scoped) + .defaultSchema(schema) + .schemas(schema) + .baselineOnMigrate(true) + .baselineVersion("60") + .target("61") + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + var tx = new TransactionTemplate(new DataSourceTransactionManager(scoped)); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Fixture(dsl, tx); + } + + private static void selection(DSLContext dsl, SelectedDraftGameLogicReceipt value) { + var target = value.selection().target(); + var intent = value.selection().intent(); + dsl.execute( + "INSERT INTO game_design_authored_draft_publish_selection (canonical_tenant_id, canonical_version_id, publish_request_id, selection_digest, selection_json, game_design_version_row_id, game_design_version_tenant_key, source_game_row_id, source_game_tenant_key, source_provenance_kind, version_state_epoch, selected_commit_request_id, selected_commit_id, selected_commit_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + value.selection().intent().canonicalTenantId(), + value.selection().intent().canonicalVersionId(), + value.selection().intent().publishRequestId(), + value.selection().digest(), + value.selection().canonicalJson(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind(), + Long.parseLong(intent.expectedVersionStateEpoch()), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + } + + private static void insert( + DSLContext dsl, + SelectedDraftGameLogicReceipt value, + byte[] selectionBytes, + byte[] receiptBytes) { + dsl.execute( + "INSERT INTO game_design_selected_game_logic_receipt (canonical_tenant_id, canonical_version_id, publish_request_id, selection_digest, workflow_identity, selection_bytes, authorization_bytes, authorization_digest, receipt_bytes, receipt_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + value.selection().intent().canonicalTenantId(), + value.selection().intent().canonicalVersionId(), + value.selection().intent().publishRequestId(), + value.selection().digest(), + value.workflowIdentity(), + selectionBytes, + value.authorization().canonicalBytes(), + value.authorization().digest(), + receiptBytes, + value.receipt().digest()); + } + + private static SelectedDraftGameLogicReceipt receiptFixture() { + UUID actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", "1", + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var auth = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publish-1", + "1", + "", + binding.requestId(), + binding.commitId(), + binding.digest()), + target, + binding, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + binding.requestId(), + binding.commitId(), + binding.digest(), + "[]", + OffsetDateTime.parse("2026-10-08T00:00:00Z"))); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation("test", auth), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + return new SelectedDraftGameLogicReceipt( + AuthoredDraftPublishSelection.fromStored(selected.canonicalJson(), selected.digest()), + auth, + new AccountGameLogicIntakeSettlementEvidence(terminal)); + } + + private record Fixture(DSLContext dsl, TransactionTemplate tx) {} +} diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java index 58bd89a9aa..df3726cff3 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java @@ -75,6 +75,17 @@ void missingBothGenesisAndInheritedCommitAndInvalidRequiredTextAreRejected() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void knownSiblingSourceKindsAreNonPolicyAndUnknownKindsStillDeny() { + assertThat(RealmPolicySource.isPolicyRevision(revision(BrandingSource.REVISION_KIND))) + .isFalse(); + assertThat(RealmPolicySource.isPolicyRevision(revision(TemplateConfigSource.REVISION_KIND))) + .isFalse(); + assertThatThrownBy(() -> RealmPolicySource.isPolicyRevision(revision("UNKNOWN_SOURCE"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported Game Design owner revision kind"); + } + private static RealmPolicyApplication freshApplication() { return new RealmPolicyApplication(freshGenesis(), null, "0", snapshot()); } @@ -107,6 +118,11 @@ private static TargetProof target() { TENANT_ID, VERSION_ID, 23L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); } + private static RevisionPayload revision(String kind) { + return new RevisionPayload( + "0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, "{\"revisionKind\":\"" + kind + "\"}"); + } + private static byte[] frames(byte[]... values) { var output = new ByteArrayOutputStream(); try { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java new file mode 100644 index 0000000000..428881c867 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java @@ -0,0 +1,200 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadClient; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainEvidence; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class SelectedDraftGameLogicReceiptServiceTest { + @Test + void ownerCallsOutsideSqlThenStoresExactAccountReceiptAndRecoversWithoutRpc() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var repository = mock(SelectedDraftGameLogicReceiptRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var gl = mock(GameLogicIntakeRetainClient.class); + var account = mock(AccountGameLogicIntakeSettlementReadClient.class); + when(repository.read(any(), any())).thenReturn(Optional.empty()); + when(repository.retain(any())).thenReturn(value); + when(gl.retain(any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new GameLogicIntakeRetainEvidence( + call.getArgument(0), value.receipt().terminal()); + }); + when(account.read(any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new AccountGameLogicIntakeSettlementReadEvidence( + call.getArgument(0), value.receipt()); + }); + var service = + new SelectedDraftGameLogicReceiptService( + repository, + ignored -> Optional.of(value.selection()), + transactions, + gl, + account, + "test"); + assertThat(service.retain(value.selection(), value.authorization())).isSameAs(value); + var order = inOrder(repository, gl, account, transactions); + order.verify(repository).read(any(), any()); + order.verify(gl).retain(any()); + order.verify(account).read(any()); + order.verify(transactions).getTransaction(any()); + order.verify(repository).retain(any()); + clearInvocations(gl, account, transactions); + when(repository.read(any(), any())).thenReturn(Optional.of(value)); + assertThat(service.retain(value.selection(), value.authorization())).isSameAs(value); + verifyNoInteractions(gl, account, transactions); + } + + @Test + void missingSelectionAndWrongCompleteSelectionDenyBeforeRpcOrTransaction() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var repository = mock(SelectedDraftGameLogicReceiptRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var gl = mock(GameLogicIntakeRetainClient.class); + var account = mock(AccountGameLogicIntakeSettlementReadClient.class); + var service = + new SelectedDraftGameLogicReceiptService( + repository, ignored -> Optional.empty(), transactions, gl, account, "test"); + assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SELECTION_UNAVAILABLE"); + assertThatThrownBy( + () -> + service.retain( + value.selection(), SelectedDraftGameLogicReceiptTest.fixture().authorization())) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(repository, transactions, gl, account); + } + + @Test + void abortedOrMissingRemoteResultCannotStoreReceipt() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var repository = mock(SelectedDraftGameLogicReceiptRepository.class); + when(repository.read(any(), any())).thenReturn(Optional.empty()); + var transactions = mock(PlatformTransactionManager.class); + var gl = mock(GameLogicIntakeRetainClient.class); + var account = mock(AccountGameLogicIntakeSettlementReadClient.class); + var service = + new SelectedDraftGameLogicReceiptService( + repository, + ignored -> Optional.of(value.selection()), + transactions, + gl, + account, + "test"); + assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) + .isInstanceOf(IllegalStateException.class); + when(gl.retain(any())) + .thenAnswer( + call -> + new GameLogicIntakeRetainEvidence( + call.getArgument(0), + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation("test", value.authorization())))); + when(account.read(any())) + .thenAnswer( + call -> + new AccountGameLogicIntakeSettlementReadEvidence( + call.getArgument(0), + new AccountGameLogicIntakeSettlementEvidence( + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation( + "test", value.authorization()))))); + assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) + .isInstanceOf(IllegalArgumentException.class); + verify(account).read(any()); + verifyNoInteractions(transactions); + verify(repository, never()).retain(any()); + } + + @Test + void lostAccountSettlementAcknowledgementRecoversOriginalIntakeWithNewTransportCorrelation() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var repository = mock(SelectedDraftGameLogicReceiptRepository.class); + when(repository.read(any(), any())).thenReturn(Optional.empty()); + when(repository.retain(any())).thenReturn(value); + var transactions = mock(PlatformTransactionManager.class); + var gl = mock(GameLogicIntakeRetainClient.class); + var account = mock(AccountGameLogicIntakeSettlementReadClient.class); + when(gl.retain(any())) + .thenAnswer( + call -> + new GameLogicIntakeRetainEvidence(call.getArgument(0), value.receipt().terminal())); + when(account.read(any())) + .thenThrow(new IllegalStateException("lost settlement acknowledgement")); + var service = + new SelectedDraftGameLogicReceiptService( + repository, + ignored -> Optional.of(value.selection()), + transactions, + gl, + account, + "test"); + assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) + .hasMessage("lost settlement acknowledgement"); + verify(repository, never()).retain(any()); + verifyNoInteractions(transactions); + doAnswer( + call -> + new AccountGameLogicIntakeSettlementReadEvidence( + call.getArgument(0), value.receipt())) + .when(account) + .read(any()); + assertThat(service.retain(value.selection(), value.authorization())).isSameAs(value); + var requests = org.mockito.ArgumentCaptor.forClass(GameLogicIntakeRetainEvidence.Request.class); + verify(gl, times(2)).retain(requests.capture()); + assertThat(requests.getAllValues().get(0).correlationId()) + .isNotEqualTo(requests.getAllValues().get(1).correlationId()); + for (var request : requests.getAllValues()) { + assertThat(request.originalAuthorizationBytes()) + .containsExactly(value.authorization().canonicalBytes()); + } + } + + @Test + void changedRetainedSelectionDeniesEvenWhenTenantVersionAndIntakeMatch() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var alteredJson = + value.selection().canonicalJson().replace("\"notes\":\"\"", "\"notes\":\"changed\""); + var changed = + net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection.fromStored( + alteredJson, + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.digest( + alteredJson.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + var repository = mock(SelectedDraftGameLogicReceiptRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var gl = mock(GameLogicIntakeRetainClient.class); + var account = mock(AccountGameLogicIntakeSettlementReadClient.class); + var service = + new SelectedDraftGameLogicReceiptService( + repository, ignored -> Optional.of(changed), transactions, gl, account, "test"); + assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(repository, transactions, gl, account); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java new file mode 100644 index 0000000000..073eecba48 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java @@ -0,0 +1,224 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import org.junit.jupiter.api.Test; + +/** Canonical fixtures stipulate upstream authority; these are not authenticated owner proof. */ +class SelectedDraftGameLogicReceiptTest { + @Test + void retainsExactSelectionIntakeAndReceiptOutsideAuthoredBytes() { + var receipt = fixture(); + byte[] before = receipt.selection().selectedCommit().canonicalBytes(); + var recovered = + new SelectedDraftGameLogicReceipt( + AuthoredDraftPublishSelection.fromStored( + receipt.selection().canonicalJson(), receipt.selection().digest()), + GameLogicIntakeAuthorizationBinding.fromStored( + receipt.authorization().canonicalBytes()), + AccountGameLogicIntakeSettlementEvidence.fromStored( + receipt.receipt().canonicalBytes())); + recovered.requireExactRequest(receipt.selection(), receipt.authorization()); + assertThat(recovered.receipt().canonicalBytes()) + .containsExactly(receipt.receipt().canonicalBytes()); + assertThat(recovered.selection().selectedCommit().canonicalBytes()).containsExactly(before); + assertThat(recovered.workflowIdentity()) + .isEqualTo("publish:" + receipt.authorization().tenantId() + ":publish-request:publish-1"); + } + + @Test + void rejectsAbortedDifferentSelectionAndChangedAuthorizationRetry() { + var value = fixture(); + var abort = + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation("test", value.authorization())); + assertThatThrownBy( + () -> + new SelectedDraftGameLogicReceipt( + value.selection(), + value.authorization(), + new AccountGameLogicIntakeSettlementEvidence(abort))) + .isInstanceOf(IllegalArgumentException.class); + var other = fixture(); + assertThatThrownBy( + () -> + SelectedDraftGameLogicReceipt.requireExactSelection( + value.selection(), other.authorization())) + .isInstanceOf(IllegalArgumentException.class); + var changed = + new GameLogicIntakeAuthorizationBinding( + value.authorization().operationId(), + UUID.randomUUID(), + value.authorization().intakeRequestId(), + value.authorization().actorAccountId(), + value.authorization().source(), + value.authorization().sources()); + assertThatThrownBy(() -> value.requireExactRequest(value.selection(), changed)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> new SelectedDraftGameLogicReceipt(value.selection(), changed, value.receipt())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedAuthoredInputWithSameTenantVersionRequestAndCommitIds() { + var value = fixture(); + var original = value.authorization().source().binding(); + var revision = original.revisions().getFirst(); + var changedBinding = + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of( + new DraftCommitBinding.RevisionPayload( + revision.revisionOrder(), + revision.revisionId(), + revision.owner(), + "{\"changed\":true}")), + original.affectedUnits()); + var changedSource = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + changedBinding.canonicalJson(), + "bindingDigest", + changedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + GameplayRuleManifest.tree(value.authorization().source().snapshotJson()) + .path("genesisReceiptId") + .textValue(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var changed = + new GameLogicIntakeAuthorizationBinding( + value.authorization().operationId(), + value.authorization().fenceId(), + value.authorization().intakeRequestId(), + value.authorization().actorAccountId(), + changedSource, + value.authorization().sources()); + assertThatThrownBy( + () -> SelectedDraftGameLogicReceipt.requireExactSelection(value.selection(), changed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete selected Draft binding"); + } + + static SelectedDraftGameLogicReceipt fixture() { + UUID actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var auth = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publish-1", + "1", + "", + binding.requestId(), + binding.commitId(), + binding.digest()), + target, + binding, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + binding.requestId(), + binding.commitId(), + binding.digest(), + "[]", + OffsetDateTime.parse("2026-10-08T00:00:00Z"))); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation("test", auth), + source.canonicalBytes(), + source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + return new SelectedDraftGameLogicReceipt( + AuthoredDraftPublishSelection.fromStored(selected.canonicalJson(), selected.digest()), + auth, + new AccountGameLogicIntakeSettlementEvidence(terminal)); + } +} diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java new file mode 100644 index 0000000000..abea6e6c67 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcService.java @@ -0,0 +1,80 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainProtoCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamelogic.v1.GameLogicGameplayRuleIntakeServiceGrpc; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; + +/** Standalone, unregistered transport for the existing owner-local intake service. */ +public final class GameLogicGameplayRuleIntakeGrpcService + extends GameLogicGameplayRuleIntakeServiceGrpc.GameLogicGameplayRuleIntakeServiceImplBase { + private final GameLogicGameplayRuleIntakeService owner; + private final String namespace; + + public GameLogicGameplayRuleIntakeGrpcService( + GameLogicGameplayRuleIntakeService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical namespace required"); + } + this.namespace = namespace; + } + + @Override + public void retainGameplayRuleIntake( + RetainGameplayRuleIntakeRequest request, + StreamObserver observer) { + try { + requireGameDesignPeer(namespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final GameLogicIntakeRetainEvidence.Request decoded; + try { + decoded = GameLogicIntakeRetainProtoCodec.fromRequest(request); + if (!namespace.equals(decoded.targetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var terminal = owner.retain(decoded.binding()); + observer.onNext( + GameLogicIntakeRetainProtoCodec.toResponse( + new GameLogicIntakeRetainEvidence(decoded, terminal))); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } + + private static void requireGameDesignPeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!peer.isInNamespace(namespace) + || !peer.isService("game-design-service") + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } +} diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java new file mode 100644 index 0000000000..6a1474180c --- /dev/null +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java @@ -0,0 +1,269 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeRetainProtoCodec; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeRequest; +import net.firedevops.firemud.gamelogic.v1.RetainGameplayRuleIntakeResponse; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; + +class GameLogicGameplayRuleIntakeGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + + @Test + void exactRetryReturnsAndEchoesTheCompleteOriginalTerminal() { + var fixture = new Fixture(); + var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, fixture.authorization); + var observer = new RecordingObserver(); + + asGameDesign( + () -> + fixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(request), observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + var result = GameLogicIntakeRetainProtoCodec.fromResponse(request, observer.value); + assertThat(result.terminal().canonicalBytes()) + .containsExactly(fixture.terminal.canonicalBytes()); + assertThat(result.terminal().outcome()) + .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED); + verify(fixture.repository).findTerminal(fixture.authorization.operationId()); + verify(fixture.accountReader, never()).read(any()); + verify(fixture.gameDesignReader, never()).read(any()); + } + + @Test + void rejectsUnauthenticatedAndWrongPeersBeforeDecodingOrOwnerAccess() { + var fixture = new Fixture(); + var malformed = RetainGameplayRuleIntakeRequest.getDefaultInstance(); + + var unauthenticated = new RecordingObserver(); + fixture.transport.retainGameplayRuleIntake(malformed, unauthenticated); + assertCode(unauthenticated.error, Status.Code.UNAUTHENTICATED); + + var account = new RecordingObserver(); + withPeer( + "spiffe://firemud/ns/test/sa/account-service", + () -> fixture.transport.retainGameplayRuleIntake(malformed, account)); + assertCode(account.error, Status.Code.PERMISSION_DENIED); + + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + verify(fixture.accountReader, never()).read(any()); + verify(fixture.gameDesignReader, never()).read(any()); + } + + @Test + void rejectsChangedNamespaceAndChangedAuthorizationForExistingOperation() { + var fixture = new Fixture(); + + var wrongNamespace = new RecordingObserver(); + var requestForOtherNamespace = + GameLogicIntakeRetainEvidence.Request.create("other", fixture.authorization); + asGameDesign( + () -> + fixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(requestForOtherNamespace), + wrongNamespace)); + assertCode(wrongNamespace.error, Status.Code.PERMISSION_DENIED); + + var changed = + new GameLogicIntakeAuthorizationBinding( + fixture.authorization.operationId(), + UUID.randomUUID(), + fixture.authorization.intakeRequestId(), + fixture.authorization.actorAccountId(), + fixture.authorization.source(), + fixture.authorization.sources()); + var changedRequest = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, changed); + var conflict = new RecordingObserver(); + asGameDesign( + () -> + fixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(changedRequest), conflict)); + assertCode(conflict.error, Status.Code.ALREADY_EXISTS); + verify(fixture.repository).findTerminal(fixture.authorization.operationId()); + verify(fixture.accountReader, never()).read(any()); + verify(fixture.gameDesignReader, never()).read(any()); + } + + @Test + void authenticatedMalformedRequestIsRejectedBeforeAnyOwnerRead() { + var fixture = new Fixture(); + var request = + RetainGameplayRuleIntakeRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setCorrelationId(UUID.randomUUID().toString()) + .setOriginalIntakeAuthorization( + com.google.protobuf.ByteString.copyFromUtf8("not-an-order")) + .setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)) + .build(); + var observer = new RecordingObserver(); + + asGameDesign(() -> fixture.transport.retainGameplayRuleIntake(request, observer)); + + assertCode(observer.error, Status.Code.INVALID_ARGUMENT); + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + verify(fixture.accountReader, never()).read(any()); + verify(fixture.gameDesignReader, never()).read(any()); + } + + private static void assertCode(Status.Code error, Status.Code expected) { + assertThat(error).isEqualTo(expected); + } + + private static void asGameDesign(Runnable action) { + withPeer(GAME_DESIGN_URI, action); + } + + private static void withPeer(String uri, Runnable action) { + var peer = GrpcPeerIdentity.parseUri(uri).orElseThrow(); + Context previous = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).attach(); + try { + action.run(); + } finally { + Context.current().detach(previous); + } + } + + private static final class RecordingObserver implements StreamObserver { + private T value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(T next) { + value = next; + } + + @Override + public void onError(Throwable failure) { + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private static final class Fixture { + private final GameLogicGameplayRuleIntakeRepository repository = + mock(GameLogicGameplayRuleIntakeRepository.class); + private final GameLogicIntakeAuthorizationReadClient accountReader = + mock(GameLogicIntakeAuthorizationReadClient.class); + private final GameplayRuleSourceReadClient gameDesignReader = + mock(GameplayRuleSourceReadClient.class); + private final GameLogicIntakeAuthorizationBinding authorization = authorization(); + private final GameLogicGameplayRuleIntakeTerminal terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization), + authorization.source().canonicalBytes(), + authorization.source().manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + private final GameLogicGameplayRuleIntakeService owner = + new GameLogicGameplayRuleIntakeService( + repository, + mock(PlatformTransactionManager.class), + accountReader, + gameDesignReader, + NAMESPACE); + private final GameLogicGameplayRuleIntakeGrpcService transport = + new GameLogicGameplayRuleIntakeGrpcService(owner, NAMESPACE); + + private Fixture() { + when(repository.findTerminal(any(UUID.class))).thenReturn(Optional.of(terminal)); + } + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + UUID actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var selectedBinding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selectedBinding.canonicalJson(), + "bindingDigest", + selectedBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V58__publication_account_order_projection.sql b/services/world-management-service/src/main/resources/db/migration/V58__publication_account_order_projection.sql new file mode 100644 index 0000000000..45a28e585b --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V58__publication_account_order_projection.sql @@ -0,0 +1,19 @@ +-- Preserve the complete Account-order projection while binding JSONB extraction before `-`. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + projection_anchor TEXT := $anchor$ 'accountOrder', private_inventory->'accountOrder' - ARRAY['canonicalBindingBytes'],$anchor$; + corrected_projection TEXT := $replacement$ 'accountOrder', (private_inventory->'accountOrder') - ARRAY['canonicalBindingBytes'],$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_require_publication_operation_account_binding(BYTEA, UUID, BYTEA)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, projection_anchor, ''))) + / length(projection_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V56 World accountOrder projection expression'; + END IF; + EXECUTE replace(original, projection_anchor, corrected_projection); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index bca54dcc28..be69056f3e 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -760,6 +760,21 @@ void terminalRequiresTheExactV53AccountOrderForFirstCompletionAndExactRetry() { assertThat(publicationAccountQualificationCount(fence)).isEqualTo(1L); } + var substitutedOperation = isolatedTerminalEvidence(original, changedOperation); + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + insertPublicationTerminal(request, substitutedOperation.operationBytes()); + return null; + })) + .satisfies(failure -> assertPublicationGuardSqlState(failure, "23514")); + assertThat(ownerSnapshot(f, graphApplication.plan())).isEqualTo(ownerBefore); + assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat(publicationTerminalCount(fence)).isZero(); + assertThat(publicationAccountQualificationCount(fence)).isEqualTo(1L); + var first = publicationTerminalComponent(original) .complete(request.operationBytes(), request.terminalBytes()); From 5bd869a20cb0b2f6f6315be17a2c06b069999822 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:10:46 +1300 Subject: [PATCH 043/129] Reserve Account source authority before Game Design disclosure --- .../account-service/api-contracts.md | 4 + .../game-design-service/api-contracts.md | 8 + .../game-logic-service/runtime-and-data.md | 2 +- ...ame-authoring-publishing-and-activation.md | 8 +- ...ame_logic_intake_source_read_service.proto | 26 + .../v1/gameplay_rule_source_service.proto | 6 + .../DraftAuthorizationFenceRepository.java | 5 +- ...ameLogicIntakeAuthorizationRepository.java | 291 ++++++- ...ntGameLogicIntakeAuthorizationService.java | 133 +++- ...tGameLogicIntakeSourceReadGrpcService.java | 94 +++ ...ountGameLogicIntakeSourceReadRecovery.java | 26 + ...countGameLogicIntakeSourceReadService.java | 96 +++ ...e_logic_intake_source_read_reservation.sql | 234 ++++++ ...eAuthorizationPostgresIntegrationTest.java | 532 ++++++++++++- ...eLogicIntakeSourceReadGrpcServiceTest.java | 203 +++++ ...tGameLogicIntakeSourceReadServiceTest.java | 61 ++ .../GameLogicIntakeSourceReadClient.java | 6 + .../GameLogicIntakeSourceReadEvidence.java | 55 ++ .../GameLogicIntakeSourceReadProtoCodec.java | 89 +++ .../GameLogicIntakeSourceReadScope.java | 82 ++ .../GameplayRuleSourceReadClient.java | 1 + .../GameplayRuleSourceReadEvidence.java | 126 ++- .../GameplayRuleSourceReadGrpcCodec.java | 66 +- .../GrpcGameLogicIntakeSourceReadClient.java | 159 ++++ ...ameLogicIntakeSourceReadTransportTest.java | 730 ++++++++++++++++++ .../GameplayRuleSelectedSourceTest.java | 59 +- ...meDesignGameplayRuleSourceReadService.java | 25 +- ...BrandingSourcePostgresIntegrationTest.java | 18 +- ...signGameplayRuleSourceReadServiceTest.java | 120 ++- .../GameLogicGameplayRuleIntakeService.java | 3 +- ...playRuleIntakePostgresIntegrationTest.java | 5 + ...lementComposedPostgresIntegrationTest.java | 2 +- ...ameLogicGameplayRuleIntakeServiceTest.java | 7 + ...uthorizedDraftPostgresIntegrationTest.java | 6 +- 34 files changed, 3222 insertions(+), 66 deletions(-) create mode 100644 protos/account/v1/game_logic_intake_source_read_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadRecovery.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java create mode 100644 services/account-service/src/main/resources/db/migration/V112__game_logic_intake_source_read_reservation.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadProtoCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadScope.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 66ebc9a6c0..f24cf0044a 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -92,6 +92,10 @@ The standalone, unregistered [`AccountSelectedPublicationOrderService.AuthorizeS Game Logic's [selected-release source intake](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) uses a distinct Account authorization, not an original Draft or publication order. After the original authored Draft is synchronized and its Account operation has committed settlement, Account first authenticates the exact Game Design peer and current creator/tenant authority and durably reserves the stable intake request, exact selected commit/target, intended reader and source-read purpose. This preliminary scope permits only that source read, not Game Logic retention. Account obtains the complete immutable Game Design source over the authenticated operation-bound owner read outside SQL, exact-compares its settled-source binding, then revalidates and locks the held Account sources before finalizing the distinct intake order under the existing currentness and settlement rules. The finalized order binds the acting account, canonical target, unchanged selected commit, exact source bytes/digest, complete current source vector and distinct operation/fence, with full source participation. Lost or denied reads remain recoverable or explicitly terminalizable under the same request without stranded authority or fresh mutation under expired authority. Exact retries preserve the original operation; changed actor, source, selection, reader or purpose cannot reuse its identity. Current authority remains protected through the actual mutation boundary. This neither changes the original Draft's participant vector nor advances its commit, and historical recovery or publication grants cannot substitute for this fresh authorization. +The preliminary `account-game-logic-intake-source-read/v1` scope binds the exact namespace, stable intake operation, fence and request identities, acting account, complete selected Draft binding, intended reader and closed `GAME_LOGIC_INTAKE_SOURCE` purpose. Its intended reader is the same-namespace Account workload; the distinct finalized intake authorizes the same-namespace Game Logic reader. These are disjoint proof branches, not interchangeable grants. A reserved preliminary operation participates in the same Account source-change and deadline-disclosure exclusion as a pending finalized intake. Finalization reuses its original operation and fence; neither a lost source response nor a denied read allocates a replacement identity. Exact recovery preserves the original phase and evidence. If the first response was lost before the caller learned its generated scope, Account locates the retained operation using the original stable request and complete selected binding, authenticates the exact Game Design caller and verifies the hash of the exact original creator credential against its retained issuance; it neither infers claims from an expired credential nor persists another credential copy. Finalized exact recovery returns the original authorization without another source read or fresh authorization. Explicit preliminary abort serializes against finalization and excludes a late finalization before releasing only that reservation's participation; expired creator evidence permits no fresh source read or mutation. + +Game Design verifies those two source-read proof branches through the dedicated [`AccountGameLogicIntakeSourceReadService`](../../../../protos/account/v1/game_logic_intake_source_read_service.proto), callable only by its exact verified same-namespace workload. Account authenticates before decoding or storage access and checks the complete original proof, actual intended reader and closed purpose against its durable operation. Preliminary confirmation requires the reserved live authority and source participation; finalized confirmation requires the exact held distinct order. Each bounded read response echoes the complete original request, including independent transport correlation, and confirms only that exact branch. The 4 MiB canonical scope and finalized-authorization limits remain distinct from this transport's 24 MiB wire budget, which accommodates the echoed proof and framing; neither receiver nor client may silently rely on gRPC's smaller default. Missing, unknown, mismatched, expired or unavailable evidence denies. This endpoint neither creates authority nor broadens the separate Game Logic-only held-order reader. Game Design completes authenticated Account readback outside SQL before returning any source content. Implementation, executed proof and registration limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + Only the verified same-namespace Game Logic workload may call [`ReadHeldGameLogicIntakeAuthorization`](../../../../protos/account/v1/game_logic_intake_authorization.proto). Its complete request and original authorization bytes/digest must match the retained order. A `HELD` read does not grant fresh creator authority or establish completed intake. Applicable source changes and elective deadline disclosure remain blocked until Account obtains a fresh authenticated same-namespace Game Logic terminal read outside SQL and commits an exact immutable settlement receipt for this same operation. Only the original `RETAINED` or definitive `ABORTED` terminal can settle; absence, timeout, or ambiguous outcome preserves participation, and an abort must exclude later retention. Account checks for an exact existing receipt before the remote read, then serializes a new settlement using the existing sorted source-lock ordering. Exact receipt recovery authenticates the permitted caller and compares the complete original order before returning retained evidence without another remote read. The receipt preserves the original Game Logic terminal; a new read correlation cannot create or rewrite a settlement. Only this operation's settled participation is released, and its external `HELD` read then denies. The unregistered terminal reader and settlement writer do not enable intake or admission; implementation and proof limits belong in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). The standalone [`SettleGameLogicIntake`](../../../../protos/account/v1/game_logic_intake_settlement_service.proto) transport is restricted to the verified same-namespace Game Design workload, authenticated before request decoding. Its closed request carries schema version, namespace, a separate transport correlation, and the complete original intake authorization bytes and digest; its response echoes that exact request and the immutable `account-game-logic-intake-settlement/v1` receipt bytes and digest. The receipt frames its schema and complete original Game Logic terminal, preserving retained and definitive-abort outcomes. A correlation change cannot change settlement identity. The client verifies Account's exact workload identity, requires file-backed mutual TLS, uses a bounded deadline and rejects ambient SQL. Unavailable or changed evidence fails closed. The receipt has its own bounded terminal envelope and is not embedded in the smaller publication operation or authored configuration. This transport supplies neither a fresh intake order nor public or runtime registration; implementation and proof remain in the linked tracker. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 4249024401..bedc3cef5c 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -57,6 +57,14 @@ The transport is construction work, not runtime registration. The [authoring tra The internal selected-publication command connects authenticated Account/World admission to finalization of that exact existing Draft, never to the ordinary path that allocates a new Version. The immutable selection must already exist before Account authorization. With no retained publication operation, Game Design verifies that selection against the complete original intent and Account binding, reads the exact Account `HELD` evidence, and requests the [World-owned freeze](../world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state). It derives the World selector-read request internally from that authenticated acknowledgement, World's retained intake correlation and the unchanged selected commit's complete World affected tuples; a caller cannot supply a topology plan, private World identity or independent selector request. All owner calls complete outside SQL, and Game Design reserves its local operation only after the exact authenticated selector readback. If World committed the freeze but Game Design has not reserved locally, the same inputs replay World’s original freeze before selector readback and reservation; no second fence or release identity is allocated. Once the exact Game Design operation exists, retries compare the complete retained selection and original Account binding and reuse its stored World request before reconciling that same attempt. They do not recapture mutable Draft state, require a new `HELD` result after settlement, or mint another authorization or release identity. Missing selection, contradictory or incomplete operation evidence remains denied. Historical identity is not current creator permission; an unregistered internal composition is not a public creator ingress or runtime activation. +## Operation-Authorized Gameplay Source Read + +The standalone [`ReadSelectedGameplayRuleSource`](../../../../protos/game-design/v1/gameplay_rule_source_service.proto) boundary authenticates its exact same-namespace Account or Game Logic peer before decoding input or querying source storage. It accepts only the matching preliminary or finalized proof branch defined by the [Account intake source-read contract](../account-service/api-contracts.md#grpc-apis), derives the actual reader from the authenticated peer, and obtains exact authenticated Account confirmation outside SQL before opening its source transaction. A canonical source binding, workload identity, original Draft terminal or publication order alone is insufficient permission. Missing, unavailable, substituted or cross-branch evidence returns no content. + +The source-read transport has an explicit 24 MiB request/response wire budget because its exact request echo carries the authorization alongside the complete source. The individual canonical source and authorization limits remain 4 MiB; transport overhead is not permission to enlarge those objects. Both client and receiver enforce the wire budget without a global gRPC limit change. + +After that confirmation, Game Design reads only the complete immutable source for the proof's exact selected target and commit and compares the complete synchronized binding. Its response echoes the complete request, proof and independent read correlation unchanged. It cannot choose a newer commit, infer an absent family as empty, or turn this source read into permission for mutation, publication or admission. This construction remains unregistered; complete producer, consumer and executed proof status belongs to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + ## Exact Publication Terminal Read `GameDesignPublicationTerminalReadService.ReadPublicationTerminal` reads the original immutable terminal result, not current permission or a new publication attempt. Its closed version-1 request binds the canonical workload namespace, a non-nil canonical read-request UUID and the complete original `game-design-publication-operation/v1` bytes. The receiver authenticates the exact same-namespace Account or World Management workload before decoding input or accessing storage. diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index 0fa97436eb..6541c9b669 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -55,7 +55,7 @@ The retained input set must be complete for the supported command inputs effecti Intake is a separate, mutation-authorized source operation. `GetDraftDesignDigest` remains a read-only full-version publication read over the already retained, exact-version evidence; it does not populate or repair that evidence. An empty selected input set is attestable only when an authenticated source operation proves the complete owner inventory for the exact selected commit is empty. Missing storage, a missing producer, or absent rows are not evidence of an empty authored set. -The original Game Design author operation settles before this intake. Game Logic obtains the complete synchronized source from Game Design's authenticated exact-commit owner read and verifies a distinct [Account intake authorization](../account-service/api-contracts.md#grpc-apis) for that same immutable source. It does not retrospectively join the original Draft's participant vector or allocate another selected commit. Account source participation remains held through Game Logic's local commit and exact terminal settlement; a remote `HELD` sample alone is insufficient. Retained source, complete manifest/provenance and the immutable intake result commit atomically. A definitive abort uses the same operation serialization and prevents later retention; missing rows or expired waits do not prove abort. Identical recovery returns the original result, never a latest source or replacement manifest. These obligations do not make Game Logic a publication-workflow mutation participant. +The original Game Design author operation settles before this intake. Game Logic obtains the complete synchronized source from Game Design's authenticated exact-commit owner read and verifies a distinct [Account intake authorization](../account-service/api-contracts.md#grpc-apis) for that same immutable source. That exact finalized authorization also accompanies its [operation-authorized source read](../game-design-service/api-contracts.md#operation-authorized-gameplay-source-read); Game Logic cannot reuse Account's preliminary read-only branch or omit independent Account readback. It does not retrospectively join the original Draft's participant vector or allocate another selected commit. Account source participation remains held through Game Logic's local commit and exact terminal settlement; a remote `HELD` sample alone is insufficient. Retained source, complete manifest/provenance and the immutable intake result commit atomically. A definitive abort uses the same operation serialization and prevents later retention; missing rows or expired waits do not prove abort. Identical recovery returns the original result, never a latest source or replacement manifest. These obligations do not make Game Logic a publication-workflow mutation participant. The standalone [`RetainGameplayRuleIntake`](../../../../protos/game-logic/v1/gameplay_rule_intake_service.proto) transport admits only verified same-namespace Game Design, authenticated before decoding. It invokes the existing distinct-order intake, not publication authorization. Exact namespace, independent transport correlation and complete original authorization bytes/digest are echoed with the immutable original terminal; both retained and definitive-abort retries preserve their original outcome. The client verifies Game Logic's workload and exact response binding. Game Design obtains the subsequent settlement receipt through the [Account-owned settlement transport](../account-service/api-contracts.md#grpc-apis), never by calling the Account-only terminal reader. These transports remain unregistered; their existence does not establish a fresh authorization producer or publication completion. 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 01a638a7bf..3ccd18bd25 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The two-phase source-read checkpoint passes consolidated local gate R199: 2,545 unit cases (358 Common, 1,101 Account, 425 Game Design, 105 Game Logic and 556 World) and 12 non-PostgreSQL integration cases pass. All 569 PostgreSQL definitions compile but skip without Docker: 237 Account, 123 Game Design, three Game Logic and 206 World. Account V112 schema generation, five-module full checks, formatting, static checks, coverage, four service boot JARs, links and Markdown pass; unchanged task outputs may be reused. The dedicated source-permission and Game Design read transports execute over-4-MiB mutual-TLS cases with synthetic content, not genuine authoring provenance. Reservation/finalization, lost-response, authority-change and abort-race database definitions remain unexecuted locally. This is construction proof, not deployment registration or activation. + +Published head `75fdca93c12247c62af46122c9e076a7afd77470` [Validation run 37879887162](https://github.com/benhook1013/FireMUD/actions/runs/37879887162) completed red with three owned failures. Account executed 249 PostgreSQL cases with one conservative original-acknowledgement WAL-coverage denial; its 1,097 unit cases passed. Game Design executed 126 PostgreSQL cases with one mixed-source branding fixture failure; all template-config cases and all three new V61 selected-publication receipt cases passed. Its 425 unit cases passed. World executed 206 PostgreSQL cases with one negative-fixture SQLSTATE mismatch; its exact original Account-order completion/retry/substitution case and 556 units passed. These database suites had zero skips. Game Logic's unit and integration tasks passed, but accessible reports do not establish their counts. The two bounded fixture corrections now use a genuinely authored admission tag and valid empty-object inventory bytes while preserving strict owner and SQLSTATE denial assertions; corrected-head physical execution remains required. V90/V92 WAL guards remain unchanged. The actual checkout was synthetic merge `74963096e200a3a9c801bede84deecf359de209d`, tree `5e0ada4bd3fad8d96cf3fad9cb5b83890015da94`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the pinned head, not the recorded integrated parent. The later skipped-matrix duplicate supplies no proof. Intended-parent alignment, complete source-to-release composition and all four Gameplay handoffs remain open. + The selected-release inventory contract is explicit in the [World owner](../../architecture/microservices/world-management-service/runtime-and-data.md#complete-selected-release-artifact-inventory) and [Game Design asset owner](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). Construction includes World's immutable selected-graph inventory and authenticated read, plus Game Design's mandatory v2 retention of that inventory in the complete original publication operation. The unregistered first-admission path obtains authenticated Account, freeze, inventory and selector evidence outside SQL; local durable retries reuse their original bytes without those RPCs. Additive owner guards reject incomplete v1 inputs for new operations, captures, terminal outcomes and settlement; retained history is not rewritten. This is not a genuine complete producer-to-release-to-settlement handoff or activation. Game Design's published synchronized source repository covers commands, realm policy, ordinary `ASSET_REFERENCE` and closed `GAMEPLAY_RULE` history, with actual fresh-Version genesis, coordinator application, immutable selected-commit snapshots and exact readback. The unregistered original-order producer connects Account's current creator transaction to the Game Design-only coordinator, source-aware fence and terminal readback; public creator ingress, deployed environment authority and physical composed proof remain pending. Generic `SaveRevision` cannot substitute for that producer, and retained generic rule rows remain denied rather than guessed into complete inventory. @@ -16,7 +20,7 @@ The composed V59/V60 local gate R183 passed Game Design schema generation, full The subsequent receipt/guard batch passes local affected checks across R191 and corrected Game Design gate R193: 351 Common, 1097 Account, 105 Game Logic, 556 World and 425 Game Design unit cases, plus 12 non-PostgreSQL integration cases, execute without failures or skips. All 566 PostgreSQL definitions compile but skip without Docker (234 Account, 123 Game Design, three Game Logic, 206 World); the three new V61 receipt cases are among those skips. The strict mutual-TLS retain and settlement transports execute over-4-MiB payload and wrong-server tests using synthetic content, not genuine source provenance. V58 World and V61 Game Design schema generation, affected full checks, formatting, static checks, coverage and boot JARs pass. R190 exposed the receipt fixture's unit-source-set dependency and constructor annotations; R191/R192 isolated a remaining unnecessary suppression, removed before R193. V61's redundant compound unique index was removed because its primary key already enforces stronger uniqueness, restoring simulator generation without weakening payload limits. Corrected PostgreSQL migration and genuine composed handoff proof remain open. -Total cross-owner source completeness, immutable manifest/export attestation, registered ingress and composed proof remain open. Game Logic intake and exact Account settlement have bounded unregistered components, not completed handoffs. Their dedicated transport construction preserves exact original authorization and receipt correlation; no deployment registration or fresh authority is supplied by those codecs. The standalone selected-publication receipt producer obtains genuine Game Logic retain and Account settlement readbacks outside SQL, then stores their exact immutable binding to the unchanged selection under V61. It settles a genuine abort without creating a positive publication receipt. It is not yet wired into the selected-publication command or finalizer; its PostgreSQL definitions stipulate predecessor schema and upstream authority rather than proving the complete flow. The fresh intake producer currently reads Game Design source before capturing current creator authority, while that source reader has workload and binding checks but no independent operation-bound permission. Overseer decision `c33d7e62` approves the bounded two-phase repair recorded in the [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#grpc-apis): preliminary authenticated read scope precedes source disclosure, then exact source readback and currentness revalidation precede final retention authority. Its implementation and negative/recovery proof remain open; historical source recovery and publication orders cannot substitute. Neither fresh source genesis nor absent mappings/consumers establishes empty unavailable families. All four genuine Gameplay handoffs and runtime activation remain open obligations. +Total cross-owner source completeness, immutable manifest/export attestation, registered ingress and composed proof remain open. Game Logic intake and exact Account settlement have bounded unregistered components, not completed handoffs. Their dedicated transport construction preserves exact original authorization and receipt correlation; no deployment registration or fresh authority is supplied by those codecs. The standalone selected-publication receipt producer obtains genuine Game Logic retain and Account settlement readbacks outside SQL, then stores their exact immutable binding to the unchanged selection under V61. It settles a genuine abort without creating a positive publication receipt. It is not yet wired into the selected-publication command or finalizer; its PostgreSQL definitions stipulate predecessor schema and upstream authority rather than proving the complete flow. The two-phase intake construction implements Overseer decision `c33d7e62` and the [Account owner contract](../../architecture/microservices/account-service/api-contracts.md#grpc-apis): V112 retains preliminary current-creator source-read reservations and participation before Game Design disclosure, and finalization revalidates the same selected binding, creator and source vector under the original operation/fence. Game Design obtains exact authenticated Account permission before reading its source, distinguishing the preliminary Account reader from the finalized Game Logic reader. Lost first responses can recover by the exact original request, selection and retained credential hash without guessing the generated scope; expiry permits historical readback or definitive abort, not another source disclosure or fresh finalization. Finalized exact retries replay retained evidence without another source call. Dedicated transports and owner services remain unregistered; physical migration, negative/race and complete producer-to-consumer proof remain required. Historical source recovery and publication orders cannot substitute. Neither fresh source genesis nor absent mappings/consumers establishes empty unavailable families. All four genuine Gameplay handoffs and runtime activation remain open obligations. Exact published head `2e466c5eca5de83e7e63ba211c3d07414192a67e` [Validation run 37876269262](https://github.com/benhook1013/FireMUD/actions/runs/37876269262) completed red. Account executed all 249 captured PostgreSQL cases successfully, including original-order lost-response and concurrent acknowledgement recovery. Game Logic's unit and integration tasks passed, but no retained XML gives exact counts. Game Design executed 123 PostgreSQL cases with six failures: four template-config and two branding cases exposed missing new-family handling in command-scope completeness and the policy revision classifier. World executed 206 PostgreSQL cases with 54 failures from the `accountOrder` JSONB projection defect. Bounded owning corrections require corrected-head execution; no failed case is counted as proof. The runner checked out synthetic merge `b54ebcd2e5ce1c0c992f8c63434c9b4e0dd17cff`, tree `7789d9ddacf30aaf41186116dd5c2822784d5476`, with parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the pinned head. This is not exact recorded-parent alignment or complete source-to-release proof. @@ -64,7 +68,7 @@ The legacy World numeric mutation route lacks the target shared-lock handoff, bu The World selected-fresh-graph checkpoint callback derives its commit identity from the exact retained Account-bound `APPLIED` application, rather than a caller-supplied checkpoint. Under the shared owner lock it rechecks the complete current graph and epoch set and computes the schema-3 content digest. Construction CI at `60c507243987705094a3028e0b46f3bccd5d9504` executed the actual Account-order-to-World-APPLIED and selected-checkpoint cases. The standalone selected-publication freeze composition obtains authenticated immutable selection, current Game Design Draft state and exact Account held-order reads outside SQL, then retains the complete Account binding atomically with the first World freeze. V53 denies late qualification of historical attempts. The new closed freeze transport owner-resolves the retained APPLIED plan without accepting caller-supplied private World identities or topology. Its acknowledgement retains the committed freeze event and owner-observed epoch, not terminal publication or admission authority. Exact committed retry verifies the stored order before recapturing mutable authority. The revised combined PostgreSQL definition uses the original owner-issued creator credential to obtain a real distinct Account publication order, reads its actual `HELD` state over strict loopback mTLS, and invokes first freeze and exact retry through a fresh authenticated Game Design-to-World socket. Game Design selection/current-Draft endpoints remain explicit fixture stipulations. Source protection is checked before and after freeze, but the original Draft order also remains pending, so writer denial does not isolate publication as its sole cause. The corrected qualification/rollback and transport definitions still require physical execution. This does not change the generic digest's synthetic highest-commit limitation, register a freeze RPC, settle either owner, or establish end-to-end publication authority. -The bounded Game Logic manifest contract is recorded at its [canonical owner](../../architecture/microservices/game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake). Game Design now defines a closed authored rule inventory with genuine fresh-Version genesis, original versioned revisions, atomic coordinated source results and immutable synchronized snapshots. Its authenticated exact-source read denies missing inventory and nonempty unqualified legacy command sources; neither the older command empty-genesis receipt nor absent rows prove a complete empty ability/catalog inventory. A distinct unregistered Account intake producer reads that exact source outside SQL, verifies the original author operation's committed Account settlement, then uses existing current-creator/source locks to retain an immutable order and full source participation. Its exact Game Logic-only HELD read is separate from Draft/publication orders; pending intake participates in Java and SQL source-change and disclosure guards. These new source/order definitions still require consolidated validation and physical PostgreSQL/composed mTLS proof. Legacy command-source convergence, actual immutable Game Logic retention and authenticated terminal settlement, dedicated ability-schema evidence and exact publication lookup remain concrete prerequisites; no runtime or positive digest activation is enabled. Unsupported or unknown families stay denied rather than being filtered into an empty manifest. Separately, V37 asset mapping/snapshot storage has caller-transaction guards and five PostgreSQL proof definitions for exact version isolation, retained-row denial, immutable readback and source substitution. The ordinary exporter now consumes its durable verified snapshot; the expanded actual repository-to-exporter test uses a mocked object-store sink and skips locally without Docker, so it is not executed storage-delivery proof. +The bounded Game Logic manifest contract is recorded at its [canonical owner](../../architecture/microservices/game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake). Game Design now defines a closed authored rule inventory with genuine fresh-Version genesis, original versioned revisions, atomic coordinated source results and immutable synchronized snapshots. Its authenticated exact-source read denies missing inventory and nonempty unqualified legacy command sources; neither the older command empty-genesis receipt nor absent rows prove a complete empty ability/catalog inventory. The distinct unregistered Account intake producer reserves current creator/source participation before disclosure, reads the exact source outside SQL, verifies the original author operation's committed Account settlement, then revalidates and finalizes the same intake operation under the existing source locks. Its exact Game Logic-only HELD read is separate from Draft/publication orders; preliminary reservations and finalized pending intake participate in Java and SQL source-change and disclosure guards. Current local and physical proof limits are recorded above. Legacy command-source convergence, complete authenticated source-to-retention and terminal settlement, dedicated ability-schema evidence and exact publication lookup remain concrete prerequisites; no runtime or positive digest activation is enabled. Unsupported or unknown families stay denied rather than being filtered into an empty manifest. Separately, V37 asset mapping/snapshot storage has caller-transaction guards and five PostgreSQL proof definitions for exact version isolation, retained-row denial, immutable readback and source substitution. The ordinary exporter now consumes its durable verified snapshot; the expanded actual repository-to-exporter test uses a mocked object-store sink and skips locally without Docker, so it is not executed storage-delivery proof. The standalone Game Design terminal owner read verifies complete original operation and terminal backing in an independent read-only repeatable-read snapshot. Its closed transport follows the [exact terminal-read contract](../../architecture/microservices/game-design-service/api-contracts.md#exact-publication-terminal-read); owner/transport unit definitions do not establish physical authenticated terminal composition. The receiver remains unregistered. World completion and distinct Account settlement now have unregistered construction components, but their genuine composed producer and physical proof remain open. diff --git a/protos/account/v1/game_logic_intake_source_read_service.proto b/protos/account/v1/game_logic_intake_source_read_service.proto new file mode 100644 index 0000000000..74cc9e11eb --- /dev/null +++ b/protos/account/v1/game_logic_intake_source_read_service.proto @@ -0,0 +1,26 @@ +syntax = "proto3"; +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Unregistered GD-only owner confirmation; canonical proof bytes are not permission. +service AccountGameLogicIntakeSourceReadService { + rpc ReadSourceScope(GameLogicIntakeSourcePermissionRequest) returns (GameLogicIntakeSourcePermissionResponse); + rpc ReadFinalizedIntake(GameLogicIntakeSourcePermissionRequest) returns (GameLogicIntakeSourcePermissionResponse); +} +message GameLogicIntakeSourcePermissionRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intended_reader = 4; + string purpose = 5; + oneof authorization_proof { + bytes preliminary_source_scope = 6; + bytes finalized_intake_authorization = 7; + } + string authorization_proof_digest = 8; +} +message GameLogicIntakeSourcePermissionResponse { + GameLogicIntakeSourcePermissionRequest request = 1; + bool permitted = 2; +} diff --git a/protos/game-design/v1/gameplay_rule_source_service.proto b/protos/game-design/v1/gameplay_rule_source_service.proto index 978d7244c8..8fb3a8c44b 100644 --- a/protos/game-design/v1/gameplay_rule_source_service.proto +++ b/protos/game-design/v1/gameplay_rule_source_service.proto @@ -14,6 +14,12 @@ message ReadSelectedGameplayRuleSourceRequest { string read_request_id = 3; string game_design_binding_json = 4; string game_design_binding_digest = 5; + oneof authorization_proof { + bytes preliminary_source_scope = 6; + bytes finalized_intake_authorization = 7; + } + string authorization_proof_digest = 8; + string purpose = 9; } message ReadSelectedGameplayRuleSourceResponse { ReadSelectedGameplayRuleSourceRequest request = 1; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 4a32ac4376..66099c9f28 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -338,7 +338,10 @@ private boolean hasPendingGameLogicIntake(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( "SELECT operation_id FROM account_game_logic_intake_sources WHERE source_key = ?" - + " AND NOT account_game_logic_intake_is_settled(operation_id)", + + " AND NOT account_game_logic_intake_is_settled(operation_id)" + + " UNION ALL SELECT operation_id FROM account_game_logic_intake_source_read_sources s" + + " WHERE source_key = ? AND account_game_logic_intake_source_read_is_pending(s.operation_id)", + source.key(), source.key()) .isEmpty()) return true; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java index a8ef577cb7..248dc20021 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java @@ -5,6 +5,7 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import org.jooq.DSLContext; import org.jooq.Record; @@ -21,23 +22,90 @@ public AccountGameLogicIntakeAuthorizationRepository(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl); } - GameLogicIntakeAuthorizationBinding authorize( + GameLogicIntakeSourceReadScope reserveSourceRead( UUID requestId, - GameplayRuleSelectedSource source, + net.firedevops.firemud.common.authoring.DraftCommitBinding selected, AccountControlUiActorService.Current current, + String namespace, Runnable admission) { requireTransaction(); var row = dsl.fetchOne( - "SELECT * FROM account_game_logic_intake_authorizations WHERE tenant_uuid = ? AND intake_request_id = ? FOR UPDATE", + "SELECT * FROM account_game_logic_intake_source_read_reservations WHERE tenant_uuid = ? AND intake_request_id = ? FOR UPDATE", current.stored().tenantId, requestId); if (row != null) { var original = - GameLogicIntakeAuthorizationBinding.fromStored(row.get("binding", byte[].class)); - if (!original.intakeRequestId().equals(requestId) + GameLogicIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class)); + if (!namespace.equals(original.targetNamespace()) || !original.actorAccountId().equals(current.stored().accountId) - || !original.source().equals(source)) + || !original.selected().equals(selected)) + throw new IllegalArgumentException("Intake request identity conflicts with original scope"); + requireReservation(row, original); + requireCurrentReservation(row, current); + if (aborted(original)) throw new IllegalStateException("Original source-read scope aborted"); + return original; + } + admission.run(); + var scope = + new GameLogicIntakeSourceReadScope( + namespace, + UUID.randomUUID(), + UUID.randomUUID(), + requestId, + current.stored().accountId, + selected, + "spiffe://firemud/ns/" + namespace + "/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_reservations " + + "(operation_id, fence_id, intake_request_id, actor_account_uuid, tenant_uuid, version_uuid, " + + "scope_bytes, scope_digest, issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + scope.operationId(), + scope.fenceId(), + requestId, + scope.actorAccountId(), + selected.target().canonicalTenantId(), + selected.target().canonicalVersionId(), + scope.canonicalBytes(), + scope.digest(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints())); + for (var source : current.source().sources()) + dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + scope.operationId(), + source.key(), + source.canonicalBytes()); + requireReservation(reservation(scope), scope); + return scope; + } + + GameLogicIntakeAuthorizationBinding finalizeSourceRead( + GameLogicIntakeSourceReadScope scope, + GameplayRuleSelectedSource source, + AccountControlUiActorService.Current current, + Runnable admission) { + requireTransaction(); + var reserved = reservation(scope); + requireReservation(reserved, scope); + requireCurrentReservation(reserved, current); + if (!scope.selected().equals(source.binding())) + throw new IllegalArgumentException("Source differs from original selected scope"); + if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_authorizations WHERE operation_id = ? FOR UPDATE", + scope.operationId()); + if (row != null) { + var original = + GameLogicIntakeAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + if (!original.source().equals(source)) throw new IllegalArgumentException( "Intake request identity conflicts with original source"); requireExact(row, original); @@ -46,10 +114,10 @@ GameLogicIntakeAuthorizationBinding authorize( admission.run(); var binding = new GameLogicIntakeAuthorizationBinding( - UUID.randomUUID(), - UUID.randomUUID(), - requestId, - current.stored().accountId, + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + scope.actorAccountId(), source, current.source().sources()); dsl.execute( @@ -61,7 +129,7 @@ GameLogicIntakeAuthorizationBinding authorize( binding.actorAccountId(), binding.tenantId(), binding.versionId(), - requestId, + scope.intakeRequestId(), source.digest(), binding.canonicalBytes(), current.stored().operationId, @@ -84,6 +152,207 @@ GameLogicIntakeAuthorizationBinding authorize( return binding; } + AccountGameLogicIntakeSourceReadRecovery recoverSourceRead(GameLogicIntakeSourceReadScope scope) { + requireTransaction(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + var row = + dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + scope.operationId()); + var state = AccountGameLogicIntakeSourceReadRecovery.State.RESERVED; + java.util.Optional result = java.util.Optional.empty(); + if (row != null) { + state = AccountGameLogicIntakeSourceReadRecovery.State.FINALIZED; + var finalOrder = + GameLogicIntakeAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + if (!scope.operationId().equals(finalOrder.operationId()) + || !scope.fenceId().equals(finalOrder.fenceId()) + || !scope.intakeRequestId().equals(finalOrder.intakeRequestId()) + || !scope.actorAccountId().equals(finalOrder.actorAccountId()) + || !scope.selected().equals(finalOrder.source().binding())) + throw new IllegalArgumentException("Finalized order differs from original scope"); + result = java.util.Optional.of(finalOrder); + } else if (aborted(scope)) state = AccountGameLogicIntakeSourceReadRecovery.State.ABORTED; + return new AccountGameLogicIntakeSourceReadRecovery(scope, state, result); + } + + java.util.Optional findSourceReadScope( + UUID requestId, + net.firedevops.firemud.common.authoring.DraftCommitBinding selected, + String namespace, + String originalTokenHash) { + requireTransaction(); + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_source_read_reservations WHERE tenant_uuid = ? AND intake_request_id = ?", + selected.target().canonicalTenantId(), + requestId); + if (row == null) return java.util.Optional.empty(); + var scope = GameLogicIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class)); + requireReservation(row, scope); + var issuer = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ?", + row.get("issuance_operation_id", UUID.class)); + if (!namespace.equals(scope.targetNamespace()) + || !selected.equals(scope.selected()) + || !originalTokenHash.equals( + new AccountControlUiIssuanceRepository.Stored(issuer).tokenHash)) + throw new IllegalArgumentException( + "Intake request conflicts with original actor credential or selection"); + return java.util.Optional.of(scope); + } + + AccountGameLogicIntakeSourceReadRecovery abortSourceRead(GameLogicIntakeSourceReadScope scope) { + var original = recoverSourceRead(scope); + if (original.state() == AccountGameLogicIntakeSourceReadRecovery.State.RESERVED) + dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_aborts (operation_id) VALUES (?)", + scope.operationId()); + return recoverSourceRead(scope); + } + + record SourceReadCurrentness(String tokenHash, String registryDigest, long expiresAt) {} + + SourceReadCurrentness sourceReadCurrentness(GameLogicIntakeSourceReadScope scope) { + requireTransaction(); + // No locks survive this transaction or the following remote registry read. + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + scope.operationId()); + if (row == null) + throw new IllegalArgumentException("Original preliminary scope absent or changed"); + requireReservation(row, scope); + var issuer = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ?", + row.get("issuance_operation_id", UUID.class)); + if (issuer == null) throw new IllegalStateException("Original creator issuance absent"); + var stored = new AccountControlUiIssuanceRepository.Stored(issuer); + if (!"COMMITTED".equals(stored.status)) + throw new IllegalStateException("Original creator issuance is no longer current"); + return new SourceReadCurrentness( + stored.tokenHash, + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.digest( + stored.activeRegistry), + stored.expiresAt.getEpochSecond()); + } + + void readSourceScope( + GameLogicIntakeSourceReadScope scope, SourceReadCurrentness expected, java.time.Instant now) { + var recovered = recoverSourceRead(scope); + if (recovered.state() != AccountGameLogicIntakeSourceReadRecovery.State.RESERVED + || !sourceReadCurrentness(scope).equals(expected) + || now.getEpochSecond() >= expected.expiresAt()) + throw new IllegalStateException("Exact current held preliminary scope required"); + } + + void readFinalizedSourceScope( + GameLogicIntakeAuthorizationBinding authorization, String namespace) { + requireTransaction(); + var row = + dsl.fetchOne( + "SELECT scope_bytes FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + authorization.operationId()); + if (row == null) throw new IllegalArgumentException("Original source-read reservation absent"); + var scope = GameLogicIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class)); + if (!namespace.equals(scope.targetNamespace())) + throw new IllegalArgumentException("Changed original source namespace"); + var recovered = recoverSourceRead(scope); + if (recovered.authorization().isEmpty() + || !Arrays.equals( + authorization.canonicalBytes(), + recovered.authorization().orElseThrow().canonicalBytes())) + throw new IllegalArgumentException("Exact finalized intake authorization required"); + readHeld(authorization); + } + + private Record reservation(GameLogicIntakeSourceReadScope scope) { + return dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ? FOR UPDATE", + scope.operationId()); + } + + private boolean aborted(GameLogicIntakeSourceReadScope scope) { + return dsl.fetchOne( + "SELECT operation_id FROM account_game_logic_intake_source_read_aborts WHERE operation_id = ?", + scope.operationId()) + != null; + } + + private void lockReservedSources(GameLogicIntakeSourceReadScope scope) { + // Reject changed caller bytes before using the retained original's sorted lock vector. + var row = + dsl.fetchOne( + "SELECT * FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + scope.operationId()); + requireReservation(row, scope); + for (var value : + dsl.fetch( + "SELECT source_key FROM account_game_logic_intake_source_read_sources WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + scope.operationId())) + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + value.get("source_key", String.class)) + == null) throw new IllegalStateException("Original preliminary source lock absent"); + } + + private static void requireCurrentReservation( + Record row, AccountControlUiActorService.Current current) { + if (!current.stored().operationId.equals(row.get("issuance_operation_id", UUID.class)) + || !Arrays.equals(current.stored().sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(current.stored().bundle, row.get("issuance_bundle", byte[].class))) + throw new IllegalArgumentException("Changed original intake creator authority"); + } + + private void requireReservation(Record row, GameLogicIntakeSourceReadScope scope) { + if (row == null + || !Arrays.equals(scope.canonicalBytes(), row.get("scope_bytes", byte[].class)) + || !scope.digest().equals(row.get("scope_digest", String.class)) + || !scope.operationId().equals(row.get("operation_id", UUID.class)) + || !scope.fenceId().equals(row.get("fence_id", UUID.class)) + || !scope.intakeRequestId().equals(row.get("intake_request_id", UUID.class)) + || !scope.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !scope.selected().target().canonicalTenantId().equals(row.get("tenant_uuid", UUID.class)) + || !scope + .selected() + .target() + .canonicalVersionId() + .equals(row.get("version_uuid", UUID.class))) + throw new IllegalArgumentException("Original preliminary scope absent or changed"); + var issuer = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ?", + row.get("issuance_operation_id", UUID.class)); + if (issuer == null) throw new IllegalStateException("Original creator issuance absent"); + var original = new AccountControlUiIssuanceRepository.Stored(issuer); + if (!scope.actorAccountId().equals(original.accountId) + || !scope.selected().target().canonicalTenantId().equals(original.tenantId) + || !Arrays.equals(original.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(original.bundle, row.get("issuance_bundle", byte[].class))) + throw new IllegalArgumentException("Changed preliminary creator evidence"); + var vector = AccountControlUiIssuanceRepository.object(original.sources).get("sources"); + var held = + dsl.fetch( + "SELECT source_key, source_evidence FROM account_game_logic_intake_source_read_sources WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + scope.operationId()); + if (!(vector instanceof java.util.List values) + || values.isEmpty() + || held.size() != values.size()) + throw new IllegalArgumentException("Incomplete preliminary source participation"); + for (int i = 0; i < held.size(); i++) { + var bytes = java.util.Base64.getDecoder().decode((String) values.get(i)); + var source = + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence + .fromStored(bytes); + if (!source.key().equals(held.get(i).get("source_key", String.class)) + || !Arrays.equals(bytes, held.get(i).get("source_evidence", byte[].class))) + throw new IllegalArgumentException("Changed preliminary source participation"); + } + } + public void readHeld(GameLogicIntakeAuthorizationBinding requested) { requireTransaction(); // Deny a changed lookup before acquiring caller-selected authority locks. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java index b82cd4f146..96b9f8ff76 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java @@ -7,10 +7,14 @@ import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; /** * Unregistered distinct intake producer. Genuine current creator and GD owner reads are mandatory. @@ -24,12 +28,14 @@ public final class AccountGameLogicIntakeAuthorizationService { private final AccountGameLogicIntakeAuthorizationRepository repository; private final GameplayRuleSourceReadClient sources; private final String namespace; + private final TransactionTemplate transaction; public AccountGameLogicIntakeAuthorizationService( AccountControlUiActorService actors, DraftAuthorizationFenceRepository fences, AccountGameLogicIntakeAuthorizationRepository repository, GameplayRuleSourceReadClient sources, + PlatformTransactionManager transactions, String namespace) { this.actors = Objects.requireNonNull(actors); this.fences = Objects.requireNonNull(fences); @@ -38,6 +44,9 @@ public AccountGameLogicIntakeAuthorizationService( if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw new IllegalArgumentException("Canonical namespace required"); this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); } public GameLogicIntakeAuthorizationBinding authorize( @@ -45,10 +54,7 @@ public GameLogicIntakeAuthorizationBinding authorize( UUID intakeRequestId, DraftCommitBinding selected, CapturedEnvironmentBoundary environment) { - var peer = GrpcPeerIdentity.current(); - if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); - if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) - throw Status.PERMISSION_DENIED.asRuntimeException(); + requirePeer(); net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.requireUuid( intakeRequestId); Objects.requireNonNull(selected); @@ -57,7 +63,19 @@ public GameLogicIntakeAuthorizationBinding authorize( throw Status.FAILED_PRECONDITION .withDescription("Source read must precede Account SQL") .asRuntimeException(); - var request = GameplayRuleSourceReadEvidence.Request.create(namespace, selected); + var retained = findScope(compactJwt, intakeRequestId, selected); + if (retained.isPresent()) { + var original = recover(retained.orElseThrow()); + if (original.authorization().isPresent()) return original.authorization().orElseThrow(); + if (original.state() == AccountGameLogicIntakeSourceReadRecovery.State.ABORTED) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + var scope = reserveSourceRead(compactJwt, intakeRequestId, selected, environment); + var recovered = recover(scope); + if (recovered.authorization().isPresent()) return recovered.authorization().orElseThrow(); + if (recovered.state() != AccountGameLogicIntakeSourceReadRecovery.State.RESERVED) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + var request = GameplayRuleSourceReadEvidence.Request.forAccountSourceScope(namespace, scope); var evidence = sources.read(request); if (evidence == null || !request.equals(evidence.request()) @@ -69,11 +87,112 @@ public GameLogicIntakeAuthorizationBinding authorize( environment, current -> { fences.lockProducerSourcesNowait(current.source().sources()); - return repository.authorize( - intakeRequestId, + return repository.finalizeSourceRead( + scope, evidence.source(), current, () -> fences.requireGameLogicIntakeAdmission(current.source().sources(), selected)); }); } + + public GameLogicIntakeSourceReadScope reserveSourceRead( + String compactJwt, + UUID intakeRequestId, + DraftCommitBinding selected, + CapturedEnvironmentBoundary environment) { + requirePeer(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.requireUuid( + intakeRequestId); + Objects.requireNonNull(selected); + outsideSql(); + return actors.withCurrent( + compactJwt, + selected.target().canonicalTenantId(), + environment, + current -> { + fences.lockProducerSourcesNowait(current.source().sources()); + return repository.reserveSourceRead( + intakeRequestId, + selected, + current, + namespace, + () -> fences.requireGameLogicIntakeAdmission(current.source().sources(), selected)); + }); + } + + /** Exact original evidence, including after creator expiry; never resumes a source read. */ + public AccountGameLogicIntakeSourceReadRecovery recover(GameLogicIntakeSourceReadScope scope) { + requirePeer(); + requireScope(scope); + outsideSql(); + return transaction.execute(ignored -> repository.recoverSourceRead(scope)); + } + + /** + * Recovers a lost first response using the exact original request and retained credential hash. + */ + public AccountGameLogicIntakeSourceReadRecovery recover( + String originalCompactJwt, UUID intakeRequestId, DraftCommitBinding selected) { + return recover( + findScope(originalCompactJwt, intakeRequestId, selected) + .orElseThrow( + () -> new IllegalArgumentException("Original source-read reservation absent"))); + } + + /** A definitive preliminary abort excludes any late finalization of this same operation. */ + public AccountGameLogicIntakeSourceReadRecovery abortSourceRead( + GameLogicIntakeSourceReadScope scope) { + requirePeer(); + requireScope(scope); + outsideSql(); + return transaction.execute(ignored -> repository.abortSourceRead(scope)); + } + + public AccountGameLogicIntakeSourceReadRecovery abortSourceRead( + String originalCompactJwt, UUID intakeRequestId, DraftCommitBinding selected) { + return abortSourceRead( + findScope(originalCompactJwt, intakeRequestId, selected) + .orElseThrow( + () -> new IllegalArgumentException("Original source-read reservation absent"))); + } + + private java.util.Optional findScope( + String originalCompactJwt, UUID intakeRequestId, DraftCommitBinding selected) { + requirePeer(); + outsideSql(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.requireUuid( + intakeRequestId); + Objects.requireNonNull(selected); + if (originalCompactJwt == null + || originalCompactJwt.isEmpty() + || originalCompactJwt.length() > 16384 + || !java.nio.charset.StandardCharsets.US_ASCII.newEncoder().canEncode(originalCompactJwt)) + throw Status.UNAUTHENTICATED.asRuntimeException(); + var hash = + AccountControlUiIssuanceRepository.hash( + originalCompactJwt.getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + return Objects.requireNonNull( + transaction.execute( + ignored -> repository.findSourceReadScope(intakeRequestId, selected, namespace, hash))); + } + + private void requireScope(GameLogicIntakeSourceReadScope scope) { + if (scope == null || !namespace.equals(scope.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION + .withDescription("Independent Account intake phase required") + .asRuntimeException(); + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcService.java new file mode 100644 index 0000000000..8912df9cdc --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcService.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadProtoCodec; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Standalone GD-only confirmation; no runtime registration. */ +public final class AccountGameLogicIntakeSourceReadGrpcService + extends AccountGameLogicIntakeSourceReadServiceGrpc + .AccountGameLogicIntakeSourceReadServiceImplBase { + private final AccountGameLogicIntakeSourceReadService owner; + private final String namespace; + + public AccountGameLogicIntakeSourceReadGrpcService( + AccountGameLogicIntakeSourceReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + @Override + public void readSourceScope( + GameLogicIntakeSourcePermissionRequest request, + StreamObserver observer) { + read(request, observer, true); + } + + @Override + public void readFinalizedIntake( + GameLogicIntakeSourcePermissionRequest request, + StreamObserver observer) { + read(request, observer, false); + } + + private void read( + GameLogicIntakeSourcePermissionRequest request, + StreamObserver observer, + boolean preliminary) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + final net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence.Request decoded; + try { + decoded = GameLogicIntakeSourceReadProtoCodec.fromRequest(request); + if (preliminary != (decoded.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary)) + throw new IllegalArgumentException("Wrong proof method"); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(decoded.targetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + try { + if (decoded.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary proof) { + var result = + owner.readSourceScope(proof.scope(), decoded.intendedReader(), decoded.purpose()); + if (!proof.scope().equals(result)) + throw new IllegalStateException("Changed Account source scope"); + } else { + var proof = (GameplayRuleSourceReadEvidence.Finalized) decoded.proof(); + var result = + owner.readFinalizedIntake( + proof.authorization(), decoded.intendedReader(), decoded.purpose()); + if (!java.util.Arrays.equals( + proof.authorization().canonicalBytes(), result.canonicalBytes())) + throw new IllegalStateException("Changed Account final authorization"); + } + observer.onNext(GameLogicIntakeSourceReadProtoCodec.toResponse(decoded)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + } catch (IllegalArgumentException | IllegalStateException failure) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadRecovery.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadRecovery.java new file mode 100644 index 0000000000..38f6278473 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadRecovery.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; + +/** Original two-phase result only; recovery does not grant a new read or mutation. */ +public record AccountGameLogicIntakeSourceReadRecovery( + GameLogicIntakeSourceReadScope scope, + State state, + Optional authorization) { + public enum State { + RESERVED, + FINALIZED, + ABORTED + } + + public AccountGameLogicIntakeSourceReadRecovery { + Objects.requireNonNull(scope); + Objects.requireNonNull(state); + Objects.requireNonNull(authorization); + if ((state == State.FINALIZED) != authorization.isPresent()) + throw new IllegalArgumentException("Exact phase result required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java new file mode 100644 index 0000000000..5db667b9ee --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java @@ -0,0 +1,96 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.time.Clock; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered GD-only readback of existing source-read authority; never issues a grant. */ +@edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner collaborators.") +public final class AccountGameLogicIntakeSourceReadService { + private final AccountGameLogicIntakeAuthorizationRepository repository; + private final AccountControlUiCoordination registry; + private final TransactionTemplate transaction; + private final Clock clock; + private final String namespace; + + public AccountGameLogicIntakeSourceReadService( + AccountGameLogicIntakeAuthorizationRepository repository, + AccountControlUiCoordination registry, + PlatformTransactionManager transactions, + Clock clock, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.registry = Objects.requireNonNull(registry); + this.clock = Objects.requireNonNull(clock); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + public GameLogicIntakeSourceReadScope readSourceScope( + GameLogicIntakeSourceReadScope scope, String intendedReader, String purpose) { + requirePeer(); + requireReader(intendedReader, purpose, "account-service"); + Objects.requireNonNull(scope); + if (!namespace.equals(scope.targetNamespace()) + || !intendedReader.equals(scope.intendedReader()) + || !purpose.equals(scope.purpose())) throw Status.PERMISSION_DENIED.asRuntimeException(); + outsideSql(); + var current = + Objects.requireNonNull( + transaction.execute(ignored -> repository.sourceReadCurrentness(scope))); + var active = registry.readActive(current.tokenHash()); + if (!current.registryDigest().equals(DraftAuthorizationFenceBinding.digest(active))) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + return transaction.execute( + ignored -> { + repository.readSourceScope(scope, current, clock.instant()); + return scope; + }); + } + + public GameLogicIntakeAuthorizationBinding readFinalizedIntake( + GameLogicIntakeAuthorizationBinding authorization, String intendedReader, String purpose) { + requirePeer(); + requireReader(intendedReader, purpose, "game-logic-service"); + Objects.requireNonNull(authorization); + outsideSql(); + return transaction.execute( + ignored -> { + repository.readFinalizedSourceScope(authorization, namespace); + return authorization; + }); + } + + private void requireReader(String reader, String purpose, String service) { + if (!("spiffe://firemud/ns/" + namespace + "/sa/" + service).equals(reader) + || !GameLogicIntakeSourceReadScope.PURPOSE.equals(purpose)) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V112__game_logic_intake_source_read_reservation.sql b/services/account-service/src/main/resources/db/migration/V112__game_logic_intake_source_read_reservation.sql new file mode 100644 index 0000000000..3564861a6d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V112__game_logic_intake_source_read_reservation.sql @@ -0,0 +1,234 @@ +-- Forward-only preliminary source-read authority. Existing final v1 orders are never rewritten. +CREATE TABLE account_game_logic_intake_source_read_reservations ( + operation_id UUID PRIMARY KEY, + fence_id UUID NOT NULL UNIQUE, + intake_request_id UUID NOT NULL, + actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + version_uuid UUID NOT NULL, + scope_bytes BYTEA NOT NULL CHECK (octet_length(scope_bytes) BETWEEN 1 AND 4194304), + scope_digest VARCHAR(71) NOT NULL CHECK (scope_digest ~ '^sha256:[0-9a-f]{64}$'), + issuance_operation_id UUID NOT NULL REFERENCES account_control_ui_issuance_operations(operation_id), + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + issuance_bundle BYTEA NOT NULL CHECK (octet_length(issuance_bundle) BETWEEN 1 AND 131072), + outbox_checkpoints BYTEA NOT NULL CHECK (octet_length(outbox_checkpoints) BETWEEN 1 AND 131072), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + reserved_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (tenant_uuid, intake_request_id) +); +CREATE TABLE account_game_logic_intake_source_read_sources ( + operation_id UUID NOT NULL REFERENCES account_game_logic_intake_source_read_reservations(operation_id), + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_game_logic_intake_source_read_lookup + ON account_game_logic_intake_source_read_sources(source_key, operation_id); +CREATE TABLE account_game_logic_intake_source_read_aborts ( + operation_id UUID PRIMARY KEY REFERENCES account_game_logic_intake_source_read_reservations(operation_id), + aborted_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- [jooq ignore start] +CREATE FUNCTION account_game_logic_intake_source_read_is_pending(operation_value UUID) +RETURNS BOOLEAN LANGUAGE sql STABLE AS $$ + SELECT EXISTS (SELECT 1 FROM account_game_logic_intake_source_read_reservations r + WHERE r.operation_id = operation_value + AND NOT EXISTS (SELECT 1 FROM account_game_logic_intake_source_read_aborts a WHERE a.operation_id = r.operation_id) + AND NOT EXISTS (SELECT 1 FROM account_game_logic_intake_authorizations f WHERE f.operation_id = r.operation_id)); +$$; + +CREATE FUNCTION account_game_logic_intake_source_read_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + p INTEGER := 1; + q INTEGER := 1; + parsed BYTEA; + selected_bytes BYTEA; + selected JSONB; + namespace_value TEXT; + source_bytes BYTEA; + source_kind TEXT; + source_scope TEXT; + source_key_value TEXT; + seen TEXT[] := ARRAY[]::TEXT[]; + issuer account_control_ui_issuance_operations%ROWTYPE; + original account_draft_authorization_fences%ROWTYPE; + vector JSONB; +BEGIN + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations WHERE operation_id = NEW.issuance_operation_id; + IF NEW.producer_xid <> txid_current() OR issuer.status IS DISTINCT FROM 'COMMITTED' + OR extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second + OR issuer.account_uuid IS DISTINCT FROM NEW.actor_account_uuid + OR issuer.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR issuer.source_payload IS DISTINCT FROM NEW.source_payload + OR issuer.bundle_payload IS DISTINCT FROM NEW.issuance_bundle + OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT IS DISTINCT FROM NEW.issuance_fence + OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' + IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB + OR NEW.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.scope_bytes), 'hex') THEN + RAISE EXCEPTION 'Preliminary scope requires exact current committed creator evidence' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') <> 'account-game-logic-intake-source-read/v1' THEN + RAISE EXCEPTION 'Invalid preliminary scope schema' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF namespace_value !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' THEN + RAISE EXCEPTION 'Invalid preliminary scope namespace' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.operation_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary operation' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.fence_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary fence' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.intake_request_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary request' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Changed preliminary actor' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO selected_bytes, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + selected := convert_from(selected_bytes, 'UTF8')::JSONB; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'sha256:' || encode(sha256(selected_bytes), 'hex') + OR selected->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR selected->>'canonicalVersionId' IS DISTINCT FROM NEW.version_uuid::TEXT THEN + RAISE EXCEPTION 'Changed preliminary selection' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'spiffe://firemud/ns/' || namespace_value || '/sa/account-service' THEN + RAISE EXCEPTION 'Invalid preliminary intended reader' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') <> 'GAME_LOGIC_INTAKE_SOURCE' OR p <> octet_length(NEW.scope_bytes) + 1 THEN + RAISE EXCEPTION 'Invalid preliminary purpose or trailing bytes' USING ERRCODE = '23514'; END IF; + + SELECT * INTO STRICT original FROM account_draft_authorization_fences + WHERE request_id = (selected->>'requestId')::UUID AND commit_id = (selected->>'commitId')::UUID; + FOR i IN 1..12 LOOP + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(original.binding, q); + END LOOP; + IF parsed IS DISTINCT FROM selected_bytes OR original.ordering <> 'COMMIT_ORDER' + OR NOT account_draft_authorization_is_settled(original.operation_id) + OR EXISTS (SELECT 1 FROM account_draft_authorization_owner_readbacks WHERE operation_id = original.operation_id AND outcome <> 'COMMITTED') THEN + RAISE EXCEPTION 'Exact original author must have committed settlement before source scope' USING ERRCODE = '23514'; END IF; + + vector := convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'; + IF jsonb_array_length(vector) < 1 OR jsonb_array_length(vector) <> + (SELECT count(*) FROM account_game_logic_intake_source_read_sources WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Incomplete preliminary source participation' USING ERRCODE = '23514'; END IF; + FOR source_bytes IN SELECT decode(value, 'base64') FROM jsonb_array_elements_text(vector) LOOP + q := 1; + SELECT frame_value, next_position INTO parsed, q FROM account_publication_authorization_read_frame(source_bytes, q); + IF convert_from(parsed, 'UTF8') <> 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Invalid preliminary source schema' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_kind, q FROM account_publication_authorization_read_frame(source_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_scope, q FROM account_publication_authorization_read_frame(source_bytes, q); + source_key_value := source_kind || ':' || source_scope; + IF source_key_value = ANY(seen) OR NOT EXISTS (SELECT 1 FROM account_game_logic_intake_source_read_sources + WHERE operation_id = NEW.operation_id AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Changed preliminary complete source vector' USING ERRCODE = '23514'; END IF; + seen := array_append(seen, source_key_value); + END LOOP; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER account_game_logic_intake_source_read_complete + AFTER INSERT ON account_game_logic_intake_source_read_reservations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_game_logic_intake_source_read_complete_guard(); + +CREATE FUNCTION account_game_logic_intake_source_read_source_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_game_logic_intake_source_read_reservations + WHERE operation_id = NEW.operation_id AND producer_xid = txid_current()) THEN + RAISE EXCEPTION 'Preliminary sources must accompany original reservation transaction' USING ERRCODE = '23514'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_game_logic_intake_source_read_source_validate BEFORE INSERT ON account_game_logic_intake_source_read_sources + FOR EACH ROW EXECUTE FUNCTION account_game_logic_intake_source_read_source_guard(); + +CREATE FUNCTION account_game_logic_intake_source_read_terminal_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_game_logic_intake_source_read_reservations%ROWTYPE; + issuer account_control_ui_issuance_operations%ROWTYPE; + p INTEGER := 1; + q INTEGER := 1; + parsed BYTEA; + selected_bytes BYTEA; + source_bytes BYTEA; +BEGIN + PERFORM l.source_key FROM account_draft_authorization_source_locks l + JOIN account_game_logic_intake_source_read_sources s ON s.source_key = l.source_key + WHERE s.operation_id = NEW.operation_id ORDER BY account_publication_authorization_source_sort_key(l.source_key) FOR UPDATE OF l; + SELECT * INTO STRICT original FROM account_game_logic_intake_source_read_reservations WHERE operation_id = NEW.operation_id FOR UPDATE; + IF TG_TABLE_NAME = 'account_game_logic_intake_source_read_aborts' THEN + IF EXISTS (SELECT 1 FROM account_game_logic_intake_authorizations WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Finalized intake cannot be preliminarily aborted' USING ERRCODE = '23514'; END IF; + RETURN NEW; + END IF; + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations WHERE operation_id = original.issuance_operation_id; + IF EXISTS (SELECT 1 FROM account_game_logic_intake_source_read_aborts WHERE operation_id = NEW.operation_id) + OR extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second OR issuer.status <> 'COMMITTED' + OR NEW.fence_id IS DISTINCT FROM original.fence_id OR NEW.intake_request_id IS DISTINCT FROM original.intake_request_id + OR NEW.actor_account_uuid IS DISTINCT FROM original.actor_account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM original.tenant_uuid OR NEW.version_uuid IS DISTINCT FROM original.version_uuid + OR NEW.issuance_operation_id IS DISTINCT FROM original.issuance_operation_id + OR NEW.issuance_fence IS DISTINCT FROM original.issuance_fence OR NEW.source_payload IS DISTINCT FROM original.source_payload + OR NEW.issuance_bundle IS DISTINCT FROM original.issuance_bundle OR NEW.outbox_checkpoints IS DISTINCT FROM original.outbox_checkpoints THEN + RAISE EXCEPTION 'Finalization requires original current un-aborted source scope' USING ERRCODE = '23514'; END IF; + FOR i IN 1..7 LOOP + SELECT frame_value, next_position INTO selected_bytes, p FROM account_publication_authorization_read_frame(original.scope_bytes, p); + END LOOP; + FOR i IN 1..6 LOOP + SELECT frame_value, next_position INTO source_bytes, q FROM account_publication_authorization_read_frame(NEW.binding, q); + END LOOP; + IF selected_bytes IS DISTINCT FROM convert_to(convert_from(source_bytes, 'UTF8')::JSONB->>'bindingJson', 'UTF8') THEN + RAISE EXCEPTION 'Finalization selected source differs from preliminary scope' USING ERRCODE = '23514'; END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_game_logic_intake_source_read_abort_validate BEFORE INSERT ON account_game_logic_intake_source_read_aborts + FOR EACH ROW EXECUTE FUNCTION account_game_logic_intake_source_read_terminal_guard(); +-- A constraint trigger also enforces expiry at the final owner transaction's commit checks. +CREATE CONSTRAINT TRIGGER account_game_logic_intake_source_read_finalize_validate + AFTER INSERT ON account_game_logic_intake_authorizations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_game_logic_intake_source_read_terminal_guard(); + +CREATE TRIGGER account_game_logic_intake_source_read_immutable BEFORE UPDATE OR DELETE ON account_game_logic_intake_source_read_reservations + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_source_read_no_truncate BEFORE TRUNCATE ON account_game_logic_intake_source_read_reservations + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_source_read_sources_immutable BEFORE UPDATE OR DELETE ON account_game_logic_intake_source_read_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_source_read_sources_no_truncate BEFORE TRUNCATE ON account_game_logic_intake_source_read_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_source_read_aborts_immutable BEFORE UPDATE OR DELETE ON account_game_logic_intake_source_read_aborts + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_game_logic_intake_source_read_aborts_no_truncate BEFORE TRUNCATE ON account_game_logic_intake_source_read_aborts + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_game_logic_intake_sources s WHERE s.source_key = ANY(source_keys)$anchor$; + preliminary_guard TEXT := $guard$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_game_logic_intake_source_read_sources s WHERE s.source_key = ANY(source_keys) + AND account_game_logic_intake_source_read_is_pending(s.operation_id) ORDER BY s.operation_id LOOP + PERFORM operation_id FROM account_game_logic_intake_source_read_reservations + WHERE operation_id = operation_value FOR UPDATE NOWAIT; + RAISE EXCEPTION 'Preliminary Game Logic source read remains pending' USING ERRCODE = '55P03'; + END LOOP; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one existing intake source-writer guard'; END IF; + EXECUTE replace(original, anchor, preliminary_guard || anchor); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java index fb7b1d9fa0..03699c90db 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java @@ -3,11 +3,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import io.grpc.Context; import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; @@ -16,6 +22,7 @@ import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; @@ -32,7 +39,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Real creator issuance/currentness, Account transactions, V109 and source guards. GD source + * Real creator issuance/currentness, Account transactions, V109/V112 and source guards. GD source * transport and the original author's terminal are explicit upstream fixtures, not composed * production or mTLS proof. No GL terminal, settlement, digest or activation is claimed. */ @@ -122,7 +129,7 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc var repository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); var service = new AccountGameLogicIntakeAuthorizationService( - issued.actors(), f.fences, repository, gd, "test"); + issued.actors(), f.fences, repository, gd, f.manager, "test"); var requestId = UUID.randomUUID(); assertThatThrownBy( @@ -132,6 +139,7 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc service.authorize( issued.compact(), requestId, selected, issued.environment()))) .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(gd); assertThat( f.dsl.fetchCount(org.jooq.impl.DSL.table("account_game_logic_intake_authorizations"))) .isZero(); @@ -170,14 +178,15 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc doAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), substituted)) .when(gd) .read(any()); - assertThatThrownBy( - () -> - asGameDesign( + clearInvocations(gd); + assertThat( + asGameDesign( () -> service.authorize( - issued.compact(), requestId, selected, issued.environment()))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("conflicts"); + issued.compact(), requestId, selected, issued.environment())) + .canonicalBytes()) + .isEqualTo(order.canonicalBytes()); + verifyNoInteractions(gd); doAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)) .when(gd) .read(any()); @@ -193,10 +202,11 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc issued.environment(), current -> { f.fences.lockProducerSourcesNowait(current.source().sources()); - repository.authorize( + repository.reserveSourceRead( rolledBackRequest, - source, + selected, current, + "test", () -> f.fences.requireGameLogicIntakeAdmission( current.source().sources(), selected)); @@ -205,7 +215,7 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc .isInstanceOf(IllegalStateException.class); assertThat( f.dsl.fetchOne( - "SELECT 1 FROM account_game_logic_intake_authorizations WHERE intake_request_id = ?", + "SELECT 1 FROM account_game_logic_intake_source_read_reservations WHERE intake_request_id = ?", rolledBackRequest)) .isNull(); f.tx( @@ -272,6 +282,506 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc } } + @Test + void lostFirstResponseRecoversByOriginalRequestAfterExpiryAndAbortReleasesParticipation() + throws Exception { + var offsetSeconds = new java.util.concurrent.atomic.AtomicLong(); + var clock = + new Clock() { + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return Instant.now().plusSeconds(offsetSeconds.get()); + } + }; + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + clock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); + var gd = mock(GameplayRuleSourceReadClient.class); + var service = + new AccountGameLogicIntakeAuthorizationService( + issued.actors(), f.fences, repository, gd, f.manager, "test"); + var requestId = UUID.randomUUID(); + doAnswer( + call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var request = (GameplayRuleSourceReadEvidence.Request) call.getArgument(0); + var scope = ((GameplayRuleSourceReadEvidence.Preliminary) request.proof()).scope(); + var retainedScope = + java.util.Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT scope_bytes FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + scope.operationId()), + "Reserved source scope row required"); + assertThat(retainedScope.get("scope_bytes", byte[].class)) + .isEqualTo(scope.canonicalBytes()); + throw io.grpc.Status.UNAVAILABLE + .withDescription("test-only lost source response") + .asRuntimeException(); + }) + .when(gd) + .read(any()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + var recovered = asGameDesign(() -> service.recover(issued.compact(), requestId, selected)); + assertThat(recovered.state()) + .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.RESERVED); + assertThat( + asGameDesign( + () -> + service.reserveSourceRead( + issued.compact(), requestId, selected, issued.environment())) + .canonicalBytes()) + .isEqualTo(recovered.scope().canonicalBytes()); + doAnswer( + call -> { + throw io.grpc.Status.PERMISSION_DENIED.asRuntimeException(); + }) + .when(gd) + .read(any()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("PERMISSION_DENIED"); + assertThat(asGameDesign(() -> service.recover(issued.compact(), requestId, selected)).scope()) + .isEqualTo(recovered.scope()); + var originalSources = + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())).sources(); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(originalSources); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("intake"); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); + return null; + })) + .hasStackTraceContaining("Preliminary Game Logic source read remains pending"); + assertThatThrownBy( + () -> + asGameDesign( + () -> service.recover("different-original-credential", requestId, selected))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + assertThatThrownBy( + () -> + asGameDesign( + () -> service.recover(issued.compact(), requestId, selected(f.tenant)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts"); + clearInvocations(gd); + offsetSeconds.set(600); + assertThat(asGameDesign(() -> service.recover(issued.compact(), requestId, selected)).scope()) + .isEqualTo(recovered.scope()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment()))) + .isInstanceOf(RuntimeException.class); + verifyNoInteractions(gd); + var aborted = + asGameDesign(() -> service.abortSourceRead(issued.compact(), requestId, selected)); + assertThat(aborted.state()).isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.ABORTED); + assertThat(asGameDesign(() -> service.abortSourceRead(recovered.scope()))).isEqualTo(aborted); + f.tx( + () -> { + f.fences.requireDisclosurePreparation(originalSources); + return null; + }); + f.tx( + () -> { + f.dsl.execute("UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); + return null; + }); + assertThat( + f.dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + recovered.scope().operationId())) + .isNull(); + } + } + + @Test + void abortWhileSourceReadIsInFlightExcludesLateFinalizationAndExactFinalRetrySurvivesExpiry() + throws Exception { + var offsetSeconds = new java.util.concurrent.atomic.AtomicLong(); + var clock = + new Clock() { + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return Instant.now().plusSeconds(offsetSeconds.get()); + } + }; + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + clock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + settleOriginal(issued, selected); + var source = source(selected); + var repository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); + var gd = mock(GameplayRuleSourceReadClient.class); + var service = + new AccountGameLogicIntakeAuthorizationService( + issued.actors(), f.fences, repository, gd, f.manager, "test"); + var arrived = new java.util.concurrent.CountDownLatch(1); + var release = new java.util.concurrent.CountDownLatch(1); + doAnswer( + call -> { + arrived.countDown(); + if (!release.await(20, java.util.concurrent.TimeUnit.SECONDS)) + throw new IllegalStateException("Source response barrier timed out"); + return new GameplayRuleSourceReadEvidence(call.getArgument(0), source); + }) + .when(gd) + .read(any()); + var requestId = UUID.randomUUID(); + var inFlight = + java.util.concurrent.CompletableFuture.supplyAsync( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), requestId, selected, issued.environment()))); + assertThat(arrived.await(20, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + var aborted = + asGameDesign(() -> service.abortSourceRead(issued.compact(), requestId, selected)); + release.countDown(); + assertThatThrownBy(() -> inFlight.get(20, java.util.concurrent.TimeUnit.SECONDS)) + .hasRootCauseMessage("Original source-read scope aborted"); + assertThat(aborted.state()).isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.ABORTED); + assertThat( + f.dsl.fetchOne( + "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + aborted.scope().operationId())) + .isNull(); + doAnswer(call -> new GameplayRuleSourceReadEvidence(call.getArgument(0), source)) + .when(gd) + .read(any()); + var finalRequest = UUID.randomUUID(); + var order = + asGameDesign( + () -> + service.authorize( + issued.compact(), finalRequest, selected, issued.environment())); + var recovery = asGameDesign(() -> service.recover(issued.compact(), finalRequest, selected)); + assertThat(order.operationId()).isEqualTo(recovery.scope().operationId()); + assertThat(order.fenceId()).isEqualTo(recovery.scope().fenceId()); + var readOwner = + new AccountGameLogicIntakeSourceReadService( + repository, + mock(AccountControlUiCoordination.class), + f.manager, + Clock.systemUTC(), + "test"); + assertThat( + asGameDesign( + () -> + readOwner.readFinalizedIntake( + order, + "spiffe://firemud/ns/test/sa/game-logic-service", + GameLogicIntakeSourceReadScope.PURPOSE)) + .canonicalBytes()) + .isEqualTo(order.canonicalBytes()); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_aborts (operation_id) VALUES (?)", + order.operationId()); + return null; + })) + .hasStackTraceContaining("Finalized intake cannot be preliminarily aborted"); + assertThat(asGameDesign(() -> service.abortSourceRead(recovery.scope())).state()) + .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.FINALIZED); + offsetSeconds.set(600); + clearInvocations(gd); + assertThat( + asGameDesign( + () -> + service.authorize( + issued.compact(), finalRequest, selected, issued.environment())) + .canonicalBytes()) + .isEqualTo(order.canonicalBytes()); + verifyNoInteractions(gd); + } + } + + private static void settleOriginal( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, DraftCommitBinding selected) { + var f = issued.sources(); + var captured = f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + selected.requestId(), + selected.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + selected.target().canonicalVersionId(), + selected.baseCommitId(), + "0", + selected.canonicalBytes(), + selected.canonicalBytes(), + selected.digest(), + captured.sources()) + .withRequiredOwners(); + issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); + f.tx( + () -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); + } + + @Test + void sourceReadbackProvesExactCurrentScopeAndChangedAuthorityBetweenPhasesCannotFinalize() + throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); + var registry = mock(AccountControlUiCoordination.class); + doAnswer( + call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var retainedIssuer = + java.util.Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT active_registry FROM account_control_ui_issuance_operations WHERE token_hash = ?", + call.getArgument(0, String.class)), + "Original active registry row required"); + return retainedIssuer.get("active_registry", byte[].class); + }) + .when(registry) + .readActive(any()); + var owner = + new AccountGameLogicIntakeSourceReadService( + repository, registry, f.manager, Clock.systemUTC(), "test"); + var gd = mock(GameplayRuleSourceReadClient.class); + var service = + new AccountGameLogicIntakeAuthorizationService( + issued.actors(), f.fences, repository, gd, f.manager, "test"); + var request = UUID.randomUUID(); + var scope = + asGameDesign( + () -> + service.reserveSourceRead( + issued.compact(), request, selected, issued.environment())); + assertThat( + asGameDesign( + () -> owner.readSourceScope(scope, scope.intendedReader(), scope.purpose())) + .canonicalBytes()) + .isEqualTo(scope.canonicalBytes()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + owner.readSourceScope( + scope, + "spiffe://firemud/ns/test/sa/game-logic-service", + scope.purpose()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy( + () -> + asGameDesign( + () -> owner.readSourceScope(scope, scope.intendedReader(), "PUBLICATION"))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + var changed = + new GameLogicIntakeSourceReadScope( + scope.targetNamespace(), + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + UUID.randomUUID(), + scope.selected(), + scope.intendedReader(), + scope.purpose()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + owner.readSourceScope( + changed, changed.intendedReader(), changed.purpose()))) + .isInstanceOf(IllegalArgumentException.class); + var expiredReader = + new AccountGameLogicIntakeSourceReadService( + repository, + registry, + f.manager, + Clock.offset(Clock.systemUTC(), java.time.Duration.ofMinutes(10)), + "test"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + expiredReader.readSourceScope( + scope, scope.intendedReader(), scope.purpose()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("current held"); + // Direct SQL cannot establish a changed purpose even with exact committed issuance bytes. + var changedPurpose = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(changedPurpose, GameLogicIntakeSourceReadScope.SCHEMA); + DraftAuthorizationFenceBinding.frame(changedPurpose, scope.targetNamespace()); + var badOperation = UUID.randomUUID(); + var badFence = UUID.randomUUID(); + var badRequest = UUID.randomUUID(); + for (var id : List.of(badOperation, badFence, badRequest, scope.actorAccountId())) + DraftAuthorizationFenceBinding.frame(changedPurpose, id.toString()); + DraftAuthorizationFenceBinding.frame(changedPurpose, selected.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(changedPurpose, selected.digest()); + DraftAuthorizationFenceBinding.frame(changedPurpose, scope.intendedReader()); + DraftAuthorizationFenceBinding.frame(changedPurpose, "PUBLICATION"); + var malformed = changedPurpose.toByteArray(); + assertThatThrownBy( + () -> + f.tx( + () -> { + f.dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_reservations " + + "(operation_id, fence_id, intake_request_id, actor_account_uuid, tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) " + + "SELECT ?, ?, ?, actor_account_uuid, tenant_uuid, version_uuid, ?, ?, issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints " + + "FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + badOperation, + badFence, + badRequest, + malformed, + DraftAuthorizationFenceBinding.digest(malformed), + scope.operationId()); + f.dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_sources SELECT ?, source_key, source_evidence FROM account_game_logic_intake_source_read_sources WHERE operation_id = ?", + badOperation, + scope.operationId()); + return null; + })) + .hasStackTraceContaining("Invalid preliminary purpose"); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + badOperation)) + .isNull(); + doAnswer( + call -> { + var sourceRequest = (GameplayRuleSourceReadEvidence.Request) call.getArgument(0); + assertThat( + ((GameplayRuleSourceReadEvidence.Preliminary) sourceRequest.proof()) + .scope()) + .isEqualTo(scope); + owner.readSourceScope(scope, scope.intendedReader(), scope.purpose()); + f.boundary.set( + AccountControlUiOwnerSourcesFixture.testBoundary( + "changed-current-environment")); + return new GameplayRuleSourceReadEvidence(sourceRequest, source(selected)); + }) + .when(gd) + .read(any()); + assertThatThrownBy( + () -> + asGameDesign( + () -> + service.authorize( + issued.compact(), request, selected, issued.environment()))) + .isInstanceOf(RuntimeException.class); + assertThat(asGameDesign(() -> service.recover(issued.compact(), request, selected)).state()) + .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.RESERVED); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_game_logic_intake_authorizations WHERE operation_id = ?", + scope.operationId())) + .isNull(); + assertThat( + asGameDesign(() -> service.abortSourceRead(issued.compact(), request, selected)) + .state()) + .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.ABORTED); + } + } + private static DraftCommitBinding selected(UUID tenant) { var target = new DraftCommitBinding.TargetProof( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java new file mode 100644 index 0000000000..707fcd1ba4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java @@ -0,0 +1,203 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadProtoCodec; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.Test; + +class AccountGameLogicIntakeSourceReadGrpcServiceTest { + @Test + void authenticatesExactGdBeforeDecoding() { + var owner = mock(AccountGameLogicIntakeSourceReadService.class); + var service = new AccountGameLogicIntakeSourceReadGrpcService(owner, "test"); + var malformed = GameLogicIntakeSourcePermissionRequest.getDefaultInstance(); + var missing = new Collector(); + service.readSourceScope(malformed, missing); + assertThat(missing.error).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String caller : + List.of("account-service", "game-logic-service", "world-management-service")) { + var result = new Collector(); + peer("test", caller).run(() -> service.readSourceScope(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + var otherNamespace = new Collector(); + peer("other", "game-design-service") + .run(() -> service.readSourceScope(malformed, otherNamespace)); + assertThat(otherNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + var gd = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(malformed, gd)); + assertThat(gd.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void dispatchesOnlyMatchingProofMethodAndEchoesExactConfirmedRequest() { + var owner = mock(AccountGameLogicIntakeSourceReadService.class); + var service = new AccountGameLogicIntakeSourceReadGrpcService(owner, "test"); + var requests = requests(); + var prelim = GameLogicIntakeSourceReadProtoCodec.toRequest(requests.getFirst()); + var finalized = GameLogicIntakeSourceReadProtoCodec.toRequest(requests.getLast()); + var wrongFirst = new Collector(); + var wrongLast = new Collector(); + peer("test", "game-design-service") + .run( + () -> { + service.readSourceScope(finalized, wrongFirst); + service.readFinalizedIntake(prelim, wrongLast); + }); + assertThat(wrongFirst.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(wrongLast.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + when(owner.readSourceScope(any(), any(), any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(owner.readFinalizedIntake(any(), any(), any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + var first = new Collector(); + var last = new Collector(); + peer("test", "game-design-service") + .run( + () -> { + service.readSourceScope(prelim, first); + service.readFinalizedIntake(finalized, last); + }); + assertThat(first.response.getRequest()).isEqualTo(prelim); + assertThat(last.response.getRequest()).isEqualTo(finalized); + assertThat(first.response.getPermitted()).isTrue(); + assertThat(last.response.getPermitted()).isTrue(); + when(owner.readSourceScope(any(), any(), any())) + .thenThrow(Status.PERMISSION_DENIED.asRuntimeException()); + var denied = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(prelim, denied)); + assertThat(denied.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.response).isNull(); + } + + private static Context peer(String namespace, String service) { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow()); + } + + private static List requests() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var selected = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var actor = UUID.randomUUID(); + var scope = + new GameLogicIntakeSourceReadScope( + "test", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + selected, + "spiffe://firemud/ns/test/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var authorization = + new GameLogicIntakeAuthorizationBinding( + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + return List.of( + GameLogicIntakeSourceReadEvidence.Request.create( + "test", + scope.intendedReader(), + scope.purpose(), + new GameplayRuleSourceReadEvidence.Preliminary(scope)), + GameLogicIntakeSourceReadEvidence.Request.create( + "test", + "spiffe://firemud/ns/test/sa/game-logic-service", + scope.purpose(), + new GameplayRuleSourceReadEvidence.Finalized(authorization))); + } + + private static final class Collector + implements StreamObserver { + Status.Code error; + GameLogicIntakeSourcePermissionResponse response; + + public void onNext(GameLogicIntakeSourcePermissionResponse value) { + response = value; + } + + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + public void onCompleted() {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadServiceTest.java new file mode 100644 index 0000000000..06fca5ec21 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadServiceTest.java @@ -0,0 +1,61 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.StatusRuntimeException; +import java.time.Clock; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; + +class AccountGameLogicIntakeSourceReadServiceTest { + @Test + void ownerAuthenticatesPeerBeforeInspectingEitherProofOrAccessingStorage() { + var repository = mock(AccountGameLogicIntakeAuthorizationRepository.class); + var registry = mock(AccountControlUiCoordination.class); + var transactions = mock(PlatformTransactionManager.class); + var service = + new AccountGameLogicIntakeSourceReadService( + repository, registry, transactions, Clock.systemUTC(), "test"); + assertThatThrownBy(() -> service.readSourceScope(null, null, null)) + .isInstanceOf(StatusRuntimeException.class); + assertThatThrownBy(() -> service.readFinalizedIntake(null, null, null)) + .isInstanceOf(StatusRuntimeException.class); + var wrongPeer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-logic-service") + .orElseThrow()); + var previous = wrongPeer.attach(); + try { + assertThatThrownBy(() -> service.readSourceScope(null, null, null)) + .isInstanceOf(StatusRuntimeException.class); + assertThatThrownBy(() -> service.readFinalizedIntake(null, null, null)) + .isInstanceOf(StatusRuntimeException.class); + } finally { + wrongPeer.detach(previous); + } + verifyNoInteractions(repository, registry, transactions); + } + + @Test + void reservationFinalizationAndRecoveryCannotRunOutsideTheAccountOwnerTransaction() { + var dsl = mock(DSLContext.class); + var repository = new AccountGameLogicIntakeAuthorizationRepository(dsl); + assertThatThrownBy(() -> repository.reserveSourceRead(null, null, null, null, () -> {})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner"); + assertThatThrownBy(() -> repository.finalizeSourceRead(null, null, null, () -> {})) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.recoverSourceRead(null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> repository.abortSourceRead(null)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadClient.java new file mode 100644 index 0000000000..aa29ff84ef --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadClient.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.common.gamelogic; + +/** Dedicated authenticated Account owner readback. */ +public interface GameLogicIntakeSourceReadClient { + GameLogicIntakeSourceReadEvidence read(GameLogicIntakeSourceReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadEvidence.java new file mode 100644 index 0000000000..62e63ab02c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadEvidence.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact Account owner confirmation, never a locally minted permission. */ +public record GameLogicIntakeSourceReadEvidence(Request request) { + public GameLogicIntakeSourceReadEvidence { + Objects.requireNonNull(request); + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + String intendedReader, + String purpose, + GameplayRuleSourceReadEvidence.Proof proof) { + public Request { + if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException( + "Canonical source permission schema and namespace required"); + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + Objects.requireNonNull(proof); + String service = + proof instanceof GameplayRuleSourceReadEvidence.Preliminary + ? "account-service" + : "game-logic-service"; + if (!("spiffe://firemud/ns/" + targetNamespace + "/sa/" + service).equals(intendedReader) + || !GameLogicIntakeSourceReadScope.PURPOSE.equals(purpose)) + throw new IllegalArgumentException("Exact reader and closed purpose required"); + if (proof instanceof GameplayRuleSourceReadEvidence.Preliminary preliminary + && (!targetNamespace.equals(preliminary.scope().targetNamespace()) + || !intendedReader.equals(preliminary.scope().intendedReader()) + || !purpose.equals(preliminary.scope().purpose()))) + throw new IllegalArgumentException("Preliminary scope differs"); + if (readRequestId.equals(proof.operationId()) + || readRequestId.equals(proof.intakeRequestId()) + || readRequestId.equals(proof.fenceId()) + || readRequestId.equals(proof.selected().requestId()) + || readRequestId.equals(proof.selected().commitId())) + throw new IllegalArgumentException("Independent read correlation required"); + } + + public static Request create( + String namespace, + String reader, + String purpose, + GameplayRuleSourceReadEvidence.Proof proof) { + return new Request(1, namespace, UUID.randomUUID(), reader, purpose, proof); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadProtoCodec.java new file mode 100644 index 0000000000..015ed9566c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadProtoCodec.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed canonical proof mapping; decode only after authenticating GD. */ +public final class GameLogicIntakeSourceReadProtoCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + private GameLogicIntakeSourceReadProtoCodec() {} + + public static GameLogicIntakeSourcePermissionRequest toRequest( + GameLogicIntakeSourceReadEvidence.Request request) { + var builder = + GameLogicIntakeSourcePermissionRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setPurpose(request.purpose()) + .setAuthorizationProofDigest(request.proof().digest()); + var bytes = ByteString.copyFrom(request.proof().canonicalBytes()); + if (request.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary) + builder.setPreliminarySourceScope(bytes); + else builder.setFinalizedIntakeAuthorization(bytes); + var wire = builder.build(); + if (wire.getSerializedSize() > MAX_WIRE_BYTES) + throw new IllegalArgumentException("Oversized Account source permission request"); + return wire; + } + + public static GameLogicIntakeSourceReadEvidence.Request fromRequest( + GameLogicIntakeSourcePermissionRequest request) { + if (request == null + || request.getSerializedSize() > MAX_WIRE_BYTES + || !request.getUnknownFields().asMap().isEmpty()) + throw new IllegalArgumentException("Unknown or oversized permission fields"); + DraftAuthorizationFenceBinding.canonicalUuid(request.getReadRequestId()); + GameplayRuleSourceReadEvidence.Proof proof = + switch (request.getAuthorizationProofCase()) { + case PRELIMINARY_SOURCE_SCOPE -> + new GameplayRuleSourceReadEvidence.Preliminary( + GameLogicIntakeSourceReadScope.fromStored( + request.getPreliminarySourceScope().toByteArray())); + case FINALIZED_INTAKE_AUTHORIZATION -> + new GameplayRuleSourceReadEvidence.Finalized( + GameLogicIntakeAuthorizationBinding.fromStored( + request.getFinalizedIntakeAuthorization().toByteArray())); + default -> throw new IllegalArgumentException("Source permission proof required"); + }; + if (!proof.digest().equals(request.getAuthorizationProofDigest())) + throw new IllegalArgumentException("Changed proof digest"); + return new GameLogicIntakeSourceReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getReadRequestId()), + request.getIntendedReader(), + request.getPurpose(), + proof); + } + + public static GameLogicIntakeSourcePermissionResponse toResponse( + GameLogicIntakeSourceReadEvidence.Request request) { + var wire = + GameLogicIntakeSourcePermissionResponse.newBuilder() + .setRequest(toRequest(request)) + .setPermitted(true) + .build(); + if (wire.getSerializedSize() > MAX_WIRE_BYTES) + throw new IllegalArgumentException("Oversized Account source permission response"); + return wire; + } + + public static GameLogicIntakeSourceReadEvidence fromResponse( + GameLogicIntakeSourceReadEvidence.Request request, + GameLogicIntakeSourcePermissionResponse response) { + if (response == null + || response.getSerializedSize() > MAX_WIRE_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || !response.getPermitted()) + throw new IllegalArgumentException("Exact Account source permission confirmation required"); + return new GameLogicIntakeSourceReadEvidence(request); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadScope.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadScope.java new file mode 100644 index 0000000000..101a2492de --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadScope.java @@ -0,0 +1,82 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact preliminary Account source-read scope. Never authorizes Game Logic retention. */ +public record GameLogicIntakeSourceReadScope( + String targetNamespace, + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + UUID actorAccountId, + DraftCommitBinding selected, + String intendedReader, + String purpose) { + public static final String SCHEMA = "account-game-logic-intake-source-read/v1"; + public static final String PURPOSE = "GAME_LOGIC_INTAKE_SOURCE"; + private static final int MAX_BYTES = 4194304; + + public GameLogicIntakeSourceReadScope { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Canonical scope namespace required"); + for (var id : List.of(operationId, fenceId, intakeRequestId, actorAccountId)) + DraftAuthorizationFenceBinding.requireUuid(id); + Objects.requireNonNull(selected); + if (!("spiffe://firemud/ns/" + targetNamespace + "/sa/account-service").equals(intendedReader) + || !PURPOSE.equals(purpose)) + throw new IllegalArgumentException("Exact preliminary Account reader and purpose required"); + } + + public byte[] canonicalBytes() { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, targetNamespace); + for (var id : List.of(operationId, fenceId, intakeRequestId, actorAccountId)) + DraftAuthorizationFenceBinding.frame(out, id.toString()); + DraftAuthorizationFenceBinding.frame(out, selected.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, selected.digest()); + DraftAuthorizationFenceBinding.frame(out, intendedReader); + DraftAuthorizationFenceBinding.frame(out, purpose); + if (out.size() > MAX_BYTES) throw new IllegalArgumentException("Source scope exceeds 4 MiB"); + return out.toByteArray(); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static GameLogicIntakeSourceReadScope fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) + throw new IllegalArgumentException("Invalid source scope size"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + reader.expect(SCHEMA); + var namespace = reader.text(); + var operation = uuid(reader.text()); + var fence = uuid(reader.text()); + var request = uuid(reader.text()); + var actor = uuid(reader.text()); + var selected = + DraftCommitBinding.fromStored( + new String(reader.bytes(), StandardCharsets.UTF_8), reader.text()); + var result = + new GameLogicIntakeSourceReadScope( + namespace, operation, fence, request, actor, selected, reader.text(), reader.text()); + reader.requireEnd(); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical source scope"); + return result; + } + + private static UUID uuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java index d5436b4f29..fbcc6e9844 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadClient.java @@ -93,6 +93,7 @@ protected String defaultTarget() { buildStub(ManagedChannel channel) { String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; return GameDesignGameplayRuleSourceReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(GameplayRuleSourceReadGrpcCodec.MAX_WIRE_BYTES) .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java index cfcad13524..a4bdda852f 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadEvidence.java @@ -16,18 +16,138 @@ public record GameplayRuleSourceReadEvidence(Request request, GameplayRuleSelect } public record Request( - int schemaVersion, String targetNamespace, UUID readRequestId, DraftCommitBinding binding) { + int schemaVersion, + String targetNamespace, + UUID readRequestId, + DraftCommitBinding binding, + Proof proof, + String purpose) { public Request { if (schemaVersion != 1 || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) throw new IllegalArgumentException("Supported source schema and namespace required"); DraftAuthorizationFenceBinding.requireUuid(readRequestId); Objects.requireNonNull(binding); + Objects.requireNonNull(proof); + if (!GameLogicIntakeSourceReadScope.PURPOSE.equals(purpose) + || !binding.equals(proof.selected())) + throw new IllegalArgumentException("Exact source proof and closed purpose required"); + if (proof instanceof Preliminary preliminary + && !targetNamespace.equals(preliminary.scope().targetNamespace())) + throw new IllegalArgumentException("Source proof namespace differs"); if (readRequestId.equals(binding.requestId()) || readRequestId.equals(binding.commitId())) throw new IllegalArgumentException("Separate source read correlation required"); + if (readRequestId.equals(proof.operationId()) + || readRequestId.equals(proof.intakeRequestId()) + || readRequestId.equals(proof.fenceId())) + throw new IllegalArgumentException("Separate intake read correlation required"); } - public static Request create(String namespace, DraftCommitBinding binding) { - return new Request(1, namespace, UUID.randomUUID(), binding); + public static Request forAccountSourceScope( + String namespace, GameLogicIntakeSourceReadScope scope) { + return new Request( + 1, + namespace, + UUID.randomUUID(), + scope.selected(), + new Preliminary(scope), + GameLogicIntakeSourceReadScope.PURPOSE); + } + + public static Request forFinalizedIntake( + String namespace, GameLogicIntakeAuthorizationBinding authorization) { + return new Request( + 1, + namespace, + UUID.randomUUID(), + authorization.source().binding(), + new Finalized(authorization), + GameLogicIntakeSourceReadScope.PURPOSE); + } + } + + public sealed interface Proof permits Preliminary, Finalized { + DraftCommitBinding selected(); + + byte[] canonicalBytes(); + + String digest(); + + UUID operationId(); + + UUID fenceId(); + + UUID intakeRequestId(); + } + + public record Preliminary(GameLogicIntakeSourceReadScope scope) implements Proof { + public Preliminary { + Objects.requireNonNull(scope); + } + + public DraftCommitBinding selected() { + return scope.selected(); + } + + public byte[] canonicalBytes() { + return scope.canonicalBytes(); + } + + public String digest() { + return scope.digest(); + } + + public UUID operationId() { + return scope.operationId(); + } + + public UUID fenceId() { + return scope.fenceId(); + } + + public UUID intakeRequestId() { + return scope.intakeRequestId(); + } + } + + public record Finalized(GameLogicIntakeAuthorizationBinding authorization) implements Proof { + public Finalized { + Objects.requireNonNull(authorization); + } + + @Override + public boolean equals(Object other) { + return this == other + || (other instanceof Finalized finalized + && java.util.Arrays.equals(canonicalBytes(), finalized.canonicalBytes())); + } + + @Override + public int hashCode() { + return java.util.Arrays.hashCode(canonicalBytes()); + } + + public DraftCommitBinding selected() { + return authorization.source().binding(); + } + + public byte[] canonicalBytes() { + return authorization.canonicalBytes(); + } + + public String digest() { + return authorization.digest(); + } + + public UUID operationId() { + return authorization.operationId(); + } + + public UUID fenceId() { + return authorization.fenceId(); + } + + public UUID intakeRequestId() { + return authorization.intakeRequestId(); } } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java index 21a1ea17d8..e21ee2c692 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSourceReadGrpcCodec.java @@ -8,45 +8,81 @@ /** Closed wire and exact request/source correlation. Decode only after peer authentication. */ public final class GameplayRuleSourceReadGrpcCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + private GameplayRuleSourceReadGrpcCodec() {} public static ReadSelectedGameplayRuleSourceRequest toRequest( GameplayRuleSourceReadEvidence.Request value) { - return ReadSelectedGameplayRuleSourceRequest.newBuilder() - .setSchemaVersion(value.schemaVersion()) - .setTargetNamespace(value.targetNamespace()) - .setReadRequestId(value.readRequestId().toString()) - .setGameDesignBindingJson(value.binding().canonicalJson()) - .setGameDesignBindingDigest(value.binding().digest()) - .build(); + var builder = + ReadSelectedGameplayRuleSourceRequest.newBuilder() + .setSchemaVersion(value.schemaVersion()) + .setTargetNamespace(value.targetNamespace()) + .setReadRequestId(value.readRequestId().toString()) + .setGameDesignBindingJson(value.binding().canonicalJson()) + .setGameDesignBindingDigest(value.binding().digest()) + .setPurpose(value.purpose()) + .setAuthorizationProofDigest(value.proof().digest()); + var bytes = com.google.protobuf.ByteString.copyFrom(value.proof().canonicalBytes()); + if (value.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary) + builder.setPreliminarySourceScope(bytes); + else builder.setFinalizedIntakeAuthorization(bytes); + var wire = builder.build(); + if (wire.getSerializedSize() > MAX_WIRE_BYTES) + throw new IllegalArgumentException("Oversized GD source request"); + return wire; } public static GameplayRuleSourceReadEvidence.Request fromRequest( ReadSelectedGameplayRuleSourceRequest value) { - if (!value.getUnknownFields().asMap().isEmpty()) + if (value == null + || value.getSerializedSize() > MAX_WIRE_BYTES + || !value.getUnknownFields().asMap().isEmpty()) throw new IllegalArgumentException("Unknown source fields"); DraftAuthorizationFenceBinding.canonicalUuid(value.getReadRequestId()); + GameplayRuleSourceReadEvidence.Proof proof = + switch (value.getAuthorizationProofCase()) { + case PRELIMINARY_SOURCE_SCOPE -> + new GameplayRuleSourceReadEvidence.Preliminary( + GameLogicIntakeSourceReadScope.fromStored( + value.getPreliminarySourceScope().toByteArray())); + case FINALIZED_INTAKE_AUTHORIZATION -> + new GameplayRuleSourceReadEvidence.Finalized( + GameLogicIntakeAuthorizationBinding.fromStored( + value.getFinalizedIntakeAuthorization().toByteArray())); + default -> throw new IllegalArgumentException("Source permission proof required"); + }; + if (!proof.digest().equals(value.getAuthorizationProofDigest())) + throw new IllegalArgumentException("Changed source proof digest"); return new GameplayRuleSourceReadEvidence.Request( value.getSchemaVersion(), value.getTargetNamespace(), UUID.fromString(value.getReadRequestId()), DraftCommitBinding.fromStored( - value.getGameDesignBindingJson(), value.getGameDesignBindingDigest())); + value.getGameDesignBindingJson(), value.getGameDesignBindingDigest()), + proof, + value.getPurpose()); } public static ReadSelectedGameplayRuleSourceResponse toResponse( GameplayRuleSourceReadEvidence evidence) { - return ReadSelectedGameplayRuleSourceResponse.newBuilder() - .setRequest(toRequest(evidence.request())) - .setCompleteSourceSnapshotJson(evidence.source().snapshotJson()) - .setCompleteSourceSnapshotDigest(evidence.source().digest()) - .build(); + var wire = + ReadSelectedGameplayRuleSourceResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setCompleteSourceSnapshotJson(evidence.source().snapshotJson()) + .setCompleteSourceSnapshotDigest(evidence.source().digest()) + .build(); + if (wire.getSerializedSize() > MAX_WIRE_BYTES) + throw new IllegalArgumentException("Oversized GD source response"); + return wire; } public static GameplayRuleSourceReadEvidence fromResponse( GameplayRuleSourceReadEvidence.Request request, ReadSelectedGameplayRuleSourceResponse response) { - if (!response.getUnknownFields().asMap().isEmpty() + if (response == null + || response.getSerializedSize() > MAX_WIRE_BYTES + || !response.getUnknownFields().asMap().isEmpty() || !response.hasRequest() || !toRequest(request).equals(response.getRequest())) throw new IllegalArgumentException("Changed source read correlation"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java new file mode 100644 index 0000000000..910b480dc7 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeSourceReadClient.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Explicit file-backed mTLS client for same-namespace Account source permission confirmation. */ +public final class GrpcGameLogicIntakeSourceReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountGameLogicIntakeSourceReadServiceGrpc + .AccountGameLogicIntakeSourceReadServiceBlockingStub> + implements GameLogicIntakeSourceReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcGameLogicIntakeSourceReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcGameLogicIntakeSourceReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) + throw new IllegalStateException("Account GL intake authorization read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account GL intake authorization read stub unavailable"); + initialized = true; + } + + /** + * Returns exact source permission confirmation after Account server mTLS identity verification. + */ + public GameLogicIntakeSourceReadEvidence read(GameLogicIntakeSourceReadEvidence.Request request) { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + throw new IllegalStateException("Account intake transport must run outside SQL"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account GL intake authorization read must use the configured workload namespace"); + } + var stub = requireStub().withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + var wire = GameLogicIntakeSourceReadProtoCodec.toRequest(request); + var response = + request.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary + ? stub.readSourceScope(wire) + : stub.readFinalizedIntake(wire); + try { + return GameLogicIntakeSourceReadProtoCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid source permission evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountGameLogicIntakeSourceReadServiceGrpc + .AccountGameLogicIntakeSourceReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountGameLogicIntakeSourceReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountGameLogicIntakeSourceReadServiceGrpc + .AccountGameLogicIntakeSourceReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account GL intake authorization read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account GL intake authorization read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account GL intake authorization read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account GL intake authorization read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java new file mode 100644 index 0000000000..e4ba06f0ed --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java @@ -0,0 +1,730 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Actual loopback mTLS transport fixtures; these bytes do not establish creator provenance. */ +class GameLogicIntakeSourceReadTransportTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_SERVER_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; + private static final String GD_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + @TempDir static Path tempDirectory; + private static TestPki pki; + private Server server; + private GrpcGameLogicIntakeSourceReadClient client; + private final AtomicInteger calls = new AtomicInteger(); + private boolean stall; + private boolean substitute; + + @BeforeAll + static void certificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void close() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void roundTripsBothClosedProofsAndRejectsChangedEchoAndUnknownOrAbsentProof() { + for (var request : requests()) { + var wire = GameLogicIntakeSourceReadProtoCodec.toRequest(request); + assertThat(GameLogicIntakeSourceReadProtoCodec.fromRequest(wire)).isEqualTo(request); + var response = GameLogicIntakeSourceReadProtoCodec.toResponse(request); + assertThat(GameLogicIntakeSourceReadProtoCodec.fromResponse(request, response).request()) + .isEqualTo(request); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + wire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().setPermitted(false).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().clearAuthorizationProof().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setAuthorizationProofDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setPurpose("PUBLICATION").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1) + .build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void pinsAccountServerAndAuthenticatedGdClientForBothMethods() throws Exception { + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + for (var request : requests()) assertThat(client.read(request).request()).isEqualTo(request); + assertThat(calls).hasValue(2); + close(); + start(pki.wrongServer()); + client = newClient(pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.read(requests().getFirst())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(2); + } + + @Test + void rejectsNamespaceAmbientSqlMissingTlsAndSubstitutedResponse() throws Exception { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcGameLogicIntakeSourceReadClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcGameLogicIntakeSourceReadClient( + endpoints, + new CommonGrpcClientProperties(), + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + var original = requests().getFirst(); + var otherNamespace = + new GameLogicIntakeSourceReadEvidence.Request( + 1, + "other", + UUID.randomUUID(), + "spiffe://firemud/ns/other/sa/game-logic-service", + original.purpose(), + requests().getLast().proof()); + assertThatThrownBy(() -> client.read(otherNamespace)) + .isInstanceOf(IllegalArgumentException.class); + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(original)).isInstanceOf(IllegalStateException.class); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager + .setActualTransactionActive(false); + } + assertThat(calls).hasValue(0); + substitute = true; + assertThatThrownBy(() -> client.read(original)).isInstanceOf(IllegalStateException.class); + } + + @Test + void boundsUnavailableReadByDeadline() throws Exception { + stall = true; + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.read(requests().getFirst())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + + @Test + void rejectsOtherAuthenticatedClientWorkload() throws Exception { + start(pki.gameLogicServer()); + var wrongClient = + TestPki.issueIdentity( + tempDirectory, + tempDirectory.resolve("terminal-test-ca.p12"), + tempDirectory.resolve("terminal-test-ca.crt"), + "wrong-source-client", + ACCOUNT_URI, + false); + client = newClient(wrongClient); + client.init(); + assertThatThrownBy(() -> client.read(requests().getFirst())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(calls).hasValue(0); + } + + @Test + void transportsResponsesOverFourMiBWithinBothExplicitWireBudgets() throws Exception { + // Deliberately synthetic owner evidence exercises envelope overhead, not creator authority. + var original = + ((GameplayRuleSourceReadEvidence.Finalized) requests().getLast().proof()).authorization(); + int padding = 4 * 1024 * 1024 - 16 - original.canonicalBytes().length + 1; + var large = + new GameLogicIntakeAuthorizationBinding( + original.operationId(), + original.fenceId(), + original.intakeRequestId(), + original.actorAccountId(), + original.source(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[padding]))); + assertThat(large.canonicalBytes().length).isEqualTo(4 * 1024 * 1024 - 16); + var permission = + GameLogicIntakeSourceReadEvidence.Request.create( + NAMESPACE, + "spiffe://firemud/ns/test/sa/game-logic-service", + GameLogicIntakeSourceReadScope.PURPOSE, + new GameplayRuleSourceReadEvidence.Finalized(large)); + assertThat(GameLogicIntakeSourceReadProtoCodec.toResponse(permission).getSerializedSize()) + .isGreaterThan(4 * 1024 * 1024) + .isLessThanOrEqualTo(GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES); + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + assertThat(client.read(permission).request().proof().canonicalBytes()) + .containsExactly(large.canonicalBytes()); + close(); + + var sourceRequest = GameplayRuleSourceReadEvidence.Request.forFinalizedIntake(NAMESPACE, large); + var sourceEvidence = new GameplayRuleSourceReadEvidence(sourceRequest, large.source()); + assertThat(GameplayRuleSourceReadGrpcCodec.toResponse(sourceEvidence).getSerializedSize()) + .isGreaterThan(4 * 1024 * 1024) + .isLessThanOrEqualTo(GameplayRuleSourceReadGrpcCodec.MAX_WIRE_BYTES); + var gdServer = + TestPki.issueIdentity( + tempDirectory, + tempDirectory.resolve("terminal-test-ca.p12"), + tempDirectory.resolve("terminal-test-ca.crt"), + "source-gd-server", + GD_URI, + true); + var glClient = + TestPki.issueIdentity( + tempDirectory, + tempDirectory.resolve("terminal-test-ca.p12"), + tempDirectory.resolve("terminal-test-ca.crt"), + "source-gl-client", + "spiffe://firemud/ns/test/sa/game-logic-service", + false); + var sourceService = + new net.firedevops.firemud.gamedesign.v1.GameDesignGameplayRuleSourceReadServiceGrpc + .GameDesignGameplayRuleSourceReadServiceImplBase() { + @Override + public void readSelectedGameplayRuleSource( + net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceRequest wire, + StreamObserver< + net.firedevops.firemud.gamedesign.v1.ReadSelectedGameplayRuleSourceResponse> + observer) { + assertThat(GrpcPeerIdentity.current().uri()) + .isEqualTo("spiffe://firemud/ns/test/sa/game-logic-service"); + var request = GameplayRuleSourceReadGrpcCodec.fromRequest(wire); + observer.onNext( + GameplayRuleSourceReadGrpcCodec.toResponse( + new GameplayRuleSourceReadEvidence(request, large.source()))); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameplayRuleSourceReadGrpcCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(gdServer.privateKey(), gdServer.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept(sourceService, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + try (var sourceClient = + new GameplayRuleSourceReadClient( + endpoints, + pki.clientProperties(tempDirectory, glClient), + new GrpcChannelFactory(), + NAMESPACE)) { + sourceClient.init(); + var result = sourceClient.read(sourceRequest); + assertThat(result.request().proof().canonicalBytes()).containsExactly(large.canonicalBytes()); + assertThat(result.source().canonicalBytes()).containsExactly(large.source().canonicalBytes()); + } + } + + @Test + void rejectsEnvelopesOverExplicitWireBudgetBeforeCanonicalDecode() { + var request = requests().getFirst(); + var oversizedAccount = + GameLogicIntakeSourceReadProtoCodec.toRequest(request).toBuilder() + .setPurpose("x".repeat(GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES)) + .build(); + assertThatThrownBy(() -> GameLogicIntakeSourceReadProtoCodec.fromRequest(oversizedAccount)) + .isInstanceOf(IllegalArgumentException.class); + var sourceRequest = + GameplayRuleSourceReadEvidence.Request.forAccountSourceScope( + NAMESPACE, ((GameplayRuleSourceReadEvidence.Preliminary) request.proof()).scope()); + var oversizedGd = + GameplayRuleSourceReadGrpcCodec.toRequest(sourceRequest).toBuilder() + .setPurpose("x".repeat(GameplayRuleSourceReadGrpcCodec.MAX_WIRE_BYTES)) + .build(); + assertThatThrownBy(() -> GameplayRuleSourceReadGrpcCodec.fromRequest(oversizedGd)) + .isInstanceOf(IllegalArgumentException.class); + } + + private void start(TestIdentity identity) throws Exception { + var service = + new AccountGameLogicIntakeSourceReadServiceGrpc + .AccountGameLogicIntakeSourceReadServiceImplBase() { + @Override + public void readSourceScope( + GameLogicIntakeSourcePermissionRequest wire, + StreamObserver observer) { + respond(wire, observer, true); + } + + @Override + public void readFinalizedIntake( + GameLogicIntakeSourcePermissionRequest wire, + StreamObserver observer) { + respond(wire, observer, false); + } + + private void respond( + GameLogicIntakeSourcePermissionRequest wire, + StreamObserver observer, + boolean preliminary) { + if (!GD_URI.equals(GrpcPeerIdentity.current().uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + calls.incrementAndGet(); + assertThat(io.grpc.Context.current().getDeadline()).isNotNull(); + var request = GameLogicIntakeSourceReadProtoCodec.fromRequest(wire); + assertThat(request.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary) + .isEqualTo(preliminary); + if (stall) return; + var response = GameLogicIntakeSourceReadProtoCodec.toResponse(request); + if (substitute) + response = + response.toBuilder() + .setRequest(wire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build(); + observer.onNext(response); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameLogicIntakeSourceReadProtoCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcGameLogicIntakeSourceReadClient newClient(TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new GrpcGameLogicIntakeSourceReadClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static List requests() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); + var binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var actor = UUID.randomUUID(); + var scope = + new GameLogicIntakeSourceReadScope( + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + binding, + ACCOUNT_URI, + GameLogicIntakeSourceReadScope.PURPOSE); + var auth = + new GameLogicIntakeAuthorizationBinding( + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + return List.of( + GameLogicIntakeSourceReadEvidence.Request.create( + NAMESPACE, + ACCOUNT_URI, + scope.purpose(), + new GameplayRuleSourceReadEvidence.Preliminary(scope)), + GameLogicIntakeSourceReadEvidence.Request.create( + NAMESPACE, + "spiffe://firemud/ns/test/sa/game-logic-service", + scope.purpose(), + new GameplayRuleSourceReadEvidence.Finalized(auth))); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameLogicServer, + TestIdentity wrongServer, + TestIdentity accountClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("terminal-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD terminal-read test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("terminal-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "game-logic-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_SERVER_URI, true), + issueIdentity(directory, caStore, caFile, "account-client", GD_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("terminal-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java index 9dfc666c6c..080578d85e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSourceTest.java @@ -88,12 +88,69 @@ void distinctIntakeRoundTripsAndCannotDecodeAnOriginalDraftOrder() { void sourceReadRequiresExactCorrelationAndDigest() { var binding = binding("{}"); var source = source(binding, List.of(), GameplayRuleManifest.explicitEmpty()); - var request = GameplayRuleSourceReadEvidence.Request.create("test", binding); + var request = + GameplayRuleSourceReadEvidence.Request.forAccountSourceScope( + "test", + new GameLogicIntakeSourceReadScope( + "test", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + binding, + "spiffe://firemud/ns/test/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE)); var response = GameplayRuleSourceReadGrpcCodec.toResponse( new GameplayRuleSourceReadEvidence(request, source)); assertThat(GameplayRuleSourceReadGrpcCodec.fromResponse(request, response).source()) .isEqualTo(source); + var wire = GameplayRuleSourceReadGrpcCodec.toRequest(request); + assertThatThrownBy( + () -> + new GameplayRuleSourceReadEvidence.Request( + 1, + "test", + request.proof().fenceId(), + binding, + request.proof(), + request.purpose())) + .isInstanceOf(IllegalArgumentException.class); + assertThat(GameplayRuleSourceReadGrpcCodec.fromRequest(wire)).isEqualTo(request); + assertThatThrownBy( + () -> + GameplayRuleSourceReadGrpcCodec.fromRequest( + wire.toBuilder().clearAuthorizationProof().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleSourceReadGrpcCodec.fromRequest( + wire.toBuilder().setPurpose("PUBLICATION").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleSourceReadGrpcCodec.fromRequest( + wire.toBuilder() + .setAuthorizationProofDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var substituted = binding("{}"); + assertThatThrownBy( + () -> + GameplayRuleSourceReadGrpcCodec.fromRequest( + wire.toBuilder() + .setGameDesignBindingJson(substituted.canonicalJson()) + .setGameDesignBindingDigest(substituted.digest()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleSourceReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest(wire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build())) + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> GameplayRuleSourceReadGrpcCodec.fromResponse( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java index 83ff84e443..26b43d858c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java @@ -11,18 +11,22 @@ import org.springframework.transaction.support.TransactionTemplate; /** - * Unregistered owner read; authenticates complete synchronized source, never creator permission. + * Unregistered exact synchronized source read with Account-confirmed reader permission. This read + * does not grant source mutation or Game Logic retention authority. */ public final class GameDesignGameplayRuleSourceReadService { private final GameplayRuleSourceRepository repository; private final TransactionTemplate transaction; private final String namespace; + private final net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadClient permissions; public GameDesignGameplayRuleSourceReadService( GameplayRuleSourceRepository repository, PlatformTransactionManager transactions, + net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadClient permissions, String namespace) { this.repository = Objects.requireNonNull(repository); + this.permissions = Objects.requireNonNull(permissions); if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw new IllegalArgumentException("Canonical namespace required"); this.namespace = namespace; @@ -41,6 +45,19 @@ public GameplayRuleSourceReadEvidence read(GameplayRuleSourceReadEvidence.Reques throw Status.FAILED_PRECONDITION .withDescription("Independent GD owner read required") .asRuntimeException(); + String reader = GrpcPeerIdentity.current().uri(); + boolean accountReader = + reader.equals("spiffe://firemud/ns/" + namespace + "/sa/account-service"); + if (accountReader != (request.proof() instanceof GameplayRuleSourceReadEvidence.Preliminary)) + throw Status.PERMISSION_DENIED.asRuntimeException(); + var permissionRequest = + net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence.Request.create( + namespace, reader, request.purpose(), request.proof()); + var permission = permissions.read(permissionRequest); + if (permission == null || !permissionRequest.equals(permission.request())) + throw Status.FAILED_PRECONDITION + .withDescription("Exact Account source permission required") + .asRuntimeException(); return transaction.execute( ignored -> { var snapshot = @@ -50,6 +67,12 @@ public GameplayRuleSourceReadEvidence read(GameplayRuleSourceReadEvidence.Reques throw Status.FAILED_PRECONDITION .withDescription("Selected rule binding differs") .asRuntimeException(); + if (request.proof() instanceof GameplayRuleSourceReadEvidence.Finalized finalized + && !java.util.Arrays.equals( + snapshot.canonicalBytes(), finalized.authorization().source().canonicalBytes())) + throw Status.FAILED_PRECONDITION + .withDescription("Finalized source differs") + .asRuntimeException(); return new GameplayRuleSourceReadEvidence( request, new GameplayRuleSelectedSource(snapshot.canonicalJson())); }); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java index d1515c174e..eae553564d 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -10,6 +10,7 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.entity.Version; @@ -77,23 +78,28 @@ void actualFreshGenesisMixedSourceApplicationAndRestartReadbackPreserveOriginalH BrandingSource.Requiredness.REQUIRED), AssetSource.upsertPayload( ordinary.getId().toString(), "ordinary.png", AssetSource.Requiredness.REQUIRED), - GameplayRuleSource.deletePayload( - net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family.ADMISSION_TAGS, - "absent"), + GameplayRuleSource.upsertPayload( + new GameplayRuleManifest.AdmissionTag("branding-proof")), CommandSource.deletePayload("absent"), policy); apply(f, first); - var selected = + var synchronizedSources = new GameDesignSourceRepository(f.dsl) .readSynchronized(f.target, first.commitId()) - .orElseThrow() - .branding() .orElseThrow(); + var selected = synchronizedSources.branding().orElseThrow(); assertThat(selected.items()).hasSize(1); assertThat(selected.items().getFirst().reference().sourceBinding()).isEqualTo(first); assertThat(selected.roleDeclarations()) .containsEntry("LOGO", "PRESENT") .containsEntry("THEME", "EMPTY"); + assertThat( + synchronizedSources + .gameplay() + .manifest() + .families() + .get(GameplayRuleManifest.Family.ADMISSION_TAGS)) + .containsExactly(new GameplayRuleManifest.AdmissionTag("branding-proof")); assertThat(new BrandingSourceRepository(f.dsl).readSnapshot(f.target, UUID.randomUUID())) .isEmpty(); assertThatThrownBy( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java index 2a9a79fd5e..fa9cec4748 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java @@ -25,7 +25,16 @@ void exportsOnlyTheCompleteOwnerReadForTheExactSynchronizedBinding() { var repository = mock(GameplayRuleSourceRepository.class); var transactions = mock(PlatformTransactionManager.class); when(transactions.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); - var owner = new GameDesignGameplayRuleSourceReadService(repository, transactions, "test"); + var permissions = + mock(net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadClient.class); + org.mockito.Mockito.doAnswer( + invocation -> + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( + invocation.getArgument(0))) + .when(permissions) + .read(any()); + var owner = + new GameDesignGameplayRuleSourceReadService(repository, transactions, permissions, "test"); var target = new DraftCommitBinding.TargetProof( UUID.randomUUID(), UUID.randomUUID(), 1, "private", 2, "private", "NEW_GAME_ROW"); @@ -54,12 +63,110 @@ void exportsOnlyTheCompleteOwnerReadForTheExactSynchronizedBinding() { new GameplayRuleSnapshot( selected, "1", null, UUID.randomUUID(), GameplayRuleSource.replay(List.of(), selected)); when(repository.requireCompleteForGameLogic(target, selected.commitId())).thenReturn(snapshot); - var request = GameplayRuleSourceReadEvidence.Request.create("test", selected); + var request = + GameplayRuleSourceReadEvidence.Request.forAccountSourceScope( + "test", + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope( + "test", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + selected, + "spiffe://firemud/ns/test/sa/account-service", + "GAME_LOGIC_INTAKE_SOURCE")); var result = new AtomicReference(); asAccount(() -> result.set(owner.read(request))); assertThat(result.get().source().canonicalBytes()).containsExactly(snapshot.canonicalBytes()); assertThat(result.get().source().manifest()).isEqualTo(snapshot.manifest()); verify(repository).requireCompleteForGameLogic(target, selected.commitId()); + var ordered = org.mockito.Mockito.inOrder(permissions, transactions, repository); + ordered.verify(permissions).read(any()); + ordered.verify(transactions).getTransaction(any()); + ordered.verify(repository).requireCompleteForGameLogic(target, selected.commitId()); + + org.mockito.Mockito.clearInvocations(permissions, transactions, repository); + org.mockito.Mockito.doThrow(io.grpc.Status.PERMISSION_DENIED.asRuntimeException()) + .when(permissions) + .read(any()); + assertThatThrownBy(() -> asAccount(() -> owner.read(request))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verifyNoInteractions(transactions, repository); + org.mockito.Mockito.doAnswer( + invocation -> + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( + invocation.getArgument(0))) + .when(permissions) + .read(any()); + + var actor = UUID.randomUUID(); + var finalAuthorization = + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + new net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource( + snapshot.canonicalJson()), + List.of( + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding + .SourceEvidence( + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding + .SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var finalizedRequest = + GameplayRuleSourceReadEvidence.Request.forFinalizedIntake("test", finalAuthorization); + asGameLogic( + () -> + assertThat(owner.read(finalizedRequest).source().canonicalBytes()) + .containsExactly(snapshot.canonicalBytes())); + org.mockito.Mockito.clearInvocations(permissions, transactions, repository); + assertThatThrownBy(() -> asAccount(() -> owner.read(finalizedRequest))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy(() -> asGameLogic(() -> owner.read(request))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verifyNoInteractions(permissions, transactions, repository); + org.mockito.Mockito.doReturn(null).when(permissions).read(any()); + assertThatThrownBy(() -> asAccount(() -> owner.read(request))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verifyNoInteractions(transactions, repository); + org.mockito.Mockito.doThrow(io.grpc.Status.UNAVAILABLE.asRuntimeException()) + .when(permissions) + .read(any()); + assertThatThrownBy(() -> asAccount(() -> owner.read(request))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verifyNoInteractions(transactions, repository); + org.mockito.Mockito.doAnswer( + invocation -> { + var original = + invocation + . + getArgument(0); + return new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( + net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence.Request + .create( + original.targetNamespace(), + original.intendedReader(), + original.purpose(), + original.proof())); + }) + .when(permissions) + .read(any()); + assertThatThrownBy(() -> asAccount(() -> owner.read(request))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verifyNoInteractions(transactions, repository); + org.mockito.Mockito.doAnswer( + invocation -> + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( + invocation.getArgument(0))) + .when(permissions) + .read(any()); when(repository.requireCompleteForGameLogic(target, selected.commitId())) .thenThrow(new IllegalStateException("GAMEPLAY_RULE_LEGACY_COMMAND_SOURCE_NOT_CONVERGED")); @@ -75,4 +182,13 @@ private static void asAccount(Runnable action) { GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/account-service").orElseThrow()) .run(action); } + + private static void asGameLogic(Runnable action) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-logic-service") + .orElseThrow()) + .run(action); + } } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java index aa22bb636d..9a67751c45 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java @@ -70,9 +70,8 @@ public GameLogicGameplayRuleIntakeTerminal retain( .asRuntimeException(); } - var selectedBinding = authorization.source().binding(); var sourceRequest = - GameplayRuleSourceReadEvidence.Request.create(workloadNamespace, selectedBinding); + GameplayRuleSourceReadEvidence.Request.forFinalizedIntake(workloadNamespace, authorization); var sourceEvidence = gameDesignSourceReader.read(sourceRequest); if (sourceEvidence == null || !sourceRequest.equals(sourceEvidence.request()) diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java index 0fa9d55a98..4217698f8a 100644 --- a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java @@ -71,6 +71,11 @@ void exactConcurrentRetriesRetainOneImmutableOriginalTerminalAndReadItWithoutOwn invocation -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); gameDesignReads.incrementAndGet(); + var sourceRequest = invocation.getArgument(0); + assertThat(sourceRequest.proof()) + .isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class); + assertThat(sourceRequest.proof().canonicalBytes()) + .containsExactly(authorization.canonicalBytes()); bothSourceReads.countDown(); if (!bothSourceReads.await(10, TimeUnit.SECONDS)) { throw new IllegalStateException("Concurrent source-read barrier timed out"); diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java index 505ea9efa8..d34de55c03 100644 --- a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java @@ -157,7 +157,7 @@ void exactTerminalSettlementReleasesOnlyItsOrderAndSurvivesOwnerOutage() throws var accountRepository = new AccountGameLogicIntakeAuthorizationRepository(f.dsl); var producer = new AccountGameLogicIntakeAuthorizationService( - issued.actors(), f.fences, accountRepository, gd, NAMESPACE); + issued.actors(), f.fences, accountRepository, gd, f.manager, NAMESPACE); var retainedOrder = asGameDesign( () -> diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java index 930a407f7f..30a8b35ef7 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java @@ -64,6 +64,13 @@ void exactHeldAuthorizationAndSelectedSourceAreRetainedAsOneExactTerminal() { .verify(fixture.accountReader) .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); calls.verify(fixture.gameDesignReader).read(any(GameplayRuleSourceReadEvidence.Request.class)); + var sourceRequest = + org.mockito.ArgumentCaptor.forClass(GameplayRuleSourceReadEvidence.Request.class); + verify(fixture.gameDesignReader).read(sourceRequest.capture()); + assertThat(sourceRequest.getValue().proof()) + .isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class); + assertThat(sourceRequest.getValue().proof().canonicalBytes()) + .containsExactly(authorization.canonicalBytes()); } @Test diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 9aa762c6a3..6459dd886f 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -750,13 +750,15 @@ void accountOriginalOrderIsAppliedAndReadAsTheExactAuthenticatedWorldSelector() byte[] substitutedOwnerScope = substitutedOwnerScopeJson.getBytes(java.nio.charset.StandardCharsets.UTF_8); byte[] validOperation = publicationOperation.canonicalBytes(); + byte[] missingInventoryPayload = + "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8); byte[] missingInventory = operationBytes( GameDesignPublicationOperationBinding.SCHEMA, publicationOrder.canonicalBytes(), evidence.canonicalBytes(), - new byte[0], - DraftAuthorizationFenceBinding.digest(new byte[0])); + missingInventoryPayload, + DraftAuthorizationFenceBinding.digest(missingInventoryPayload)); byte[] mismatchedDigest = operationBytes( GameDesignPublicationOperationBinding.SCHEMA, From 9bc14c9c2e376ca66c5fed7257116750a35ab806 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:53:31 +1300 Subject: [PATCH 044/129] Add Account intake producer and exact ability-schema projection --- .../account-service/api-contracts.md | 2 + .../game-design-service/version-control.md | 2 +- .../game-logic-service/runtime-and-data.md | 25 + design/project-management/ai-observations.md | 12 + ...ame-authoring-publishing-and-activation.md | 4 + ...e_logic_intake_authorization_service.proto | 36 ++ ...meLogicIntakeAuthorizationGrpcService.java | 260 ++++++++++ ...ntGameLogicIntakeAuthorizationService.java | 19 +- ...eAuthorizationPostgresIntegrationTest.java | 9 +- ...gicIntakeAuthorizationGrpcServiceTest.java | 378 ++++++++++++++ ...eLogicIntakeAuthorizationRecoveryTest.java | 284 +++++++++++ ...meLogicIntakeAuthorizationCredentials.java | 141 ++++++ .../GameLogicIntakeAuthorizationClient.java | 13 + .../GameLogicIntakeAuthorizationEvidence.java | 122 +++++ ...GameLogicIntakeAuthorizationGrpcCodec.java | 141 ++++++ .../GameplayAbilitySchemaProjection.java | 185 +++++++ ...rpcGameLogicIntakeAuthorizationClient.java | 194 ++++++++ ...LogicIntakeAuthorizationGrpcCodecTest.java | 247 ++++++++++ ...ameLogicIntakeSourceReadTransportTest.java | 10 +- .../GameplayAbilitySchemaProjectionTest.java | 464 ++++++++++++++++++ ...ogicIntakeAuthorizationClientMtlsTest.java | 419 ++++++++++++++++ 21 files changed, 2957 insertions(+), 10 deletions(-) create mode 100644 protos/account/v1/game_logic_intake_authorization_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index f24cf0044a..fe05228e03 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -94,6 +94,8 @@ Game Logic's [selected-release source intake](../game-logic-service/runtime-and- The preliminary `account-game-logic-intake-source-read/v1` scope binds the exact namespace, stable intake operation, fence and request identities, acting account, complete selected Draft binding, intended reader and closed `GAME_LOGIC_INTAKE_SOURCE` purpose. Its intended reader is the same-namespace Account workload; the distinct finalized intake authorizes the same-namespace Game Logic reader. These are disjoint proof branches, not interchangeable grants. A reserved preliminary operation participates in the same Account source-change and deadline-disclosure exclusion as a pending finalized intake. Finalization reuses its original operation and fence; neither a lost source response nor a denied read allocates a replacement identity. Exact recovery preserves the original phase and evidence. If the first response was lost before the caller learned its generated scope, Account locates the retained operation using the original stable request and complete selected binding, authenticates the exact Game Design caller and verifies the hash of the exact original creator credential against its retained issuance; it neither infers claims from an expired credential nor persists another credential copy. Finalized exact recovery returns the original authorization without another source read or fresh authorization. Explicit preliminary abort serializes against finalization and excludes a late finalization before releasing only that reservation's participation; expired creator evidence permits no fresh source read or mutation. +The standalone, unregistered [`AccountGameLogicIntakeAuthorizationService`](../../../../protos/account/v1/game_logic_intake_authorization_service.proto) exposes `AuthorizeIntake`, `RecoverIntake` and `AbortIntake` only to the verified same-namespace Game Design workload. Authentication precedes access to protected method-local creator metadata and request decoding. The closed request binds schema version, namespace, independent transport correlation, stable intake request and complete selected Draft bytes; the response echoes that request and the exact retained phase, preliminary scope and finalized authorization where applicable. The creator credential is separate from request and response evidence and is never copied into their canonical bytes. New authorization captures trusted environment evidence before reservation and captures it again after the remote source read, immediately before final current-actor validation; a pre-read observation cannot stand in for post-read currentness. Exact finalized recovery precedes mutable environment capture. Preliminary scope and finalized authorization, when returned together, must agree on operation, fence, request, acting account and complete selection. File-backed mutual TLS pins the Account server identity, calls have a bounded five-second deadline, and ambient SQL is rejected. Canonical content is bounded separately from the 24 MiB wire envelope; malformed, unavailable or substituted evidence fails closed. None of these methods registers a runtime path or grants publication authority. + Game Design verifies those two source-read proof branches through the dedicated [`AccountGameLogicIntakeSourceReadService`](../../../../protos/account/v1/game_logic_intake_source_read_service.proto), callable only by its exact verified same-namespace workload. Account authenticates before decoding or storage access and checks the complete original proof, actual intended reader and closed purpose against its durable operation. Preliminary confirmation requires the reserved live authority and source participation; finalized confirmation requires the exact held distinct order. Each bounded read response echoes the complete original request, including independent transport correlation, and confirms only that exact branch. The 4 MiB canonical scope and finalized-authorization limits remain distinct from this transport's 24 MiB wire budget, which accommodates the echoed proof and framing; neither receiver nor client may silently rely on gRPC's smaller default. Missing, unknown, mismatched, expired or unavailable evidence denies. This endpoint neither creates authority nor broadens the separate Game Logic-only held-order reader. Game Design completes authenticated Account readback outside SQL before returning any source content. Implementation, executed proof and registration limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). Only the verified same-namespace Game Logic workload may call [`ReadHeldGameLogicIntakeAuthorization`](../../../../protos/account/v1/game_logic_intake_authorization.proto). Its complete request and original authorization bytes/digest must match the retained order. A `HELD` read does not grant fresh creator authority or establish completed intake. Applicable source changes and elective deadline disclosure remain blocked until Account obtains a fresh authenticated same-namespace Game Logic terminal read outside SQL and commits an exact immutable settlement receipt for this same operation. Only the original `RETAINED` or definitive `ABORTED` terminal can settle; absence, timeout, or ambiguous outcome preserves participation, and an abort must exclude later retention. Account checks for an exact existing receipt before the remote read, then serializes a new settlement using the existing sorted source-lock ordering. Exact receipt recovery authenticates the permitted caller and compares the complete original order before returning retained evidence without another remote read. The receipt preserves the original Game Logic terminal; a new read correlation cannot create or rewrite a settlement. Only this operation's settled participation is released, and its external `HELD` read then denies. The unregistered terminal reader and settlement writer do not enable intake or admission; implementation and proof limits belong in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index c1c8013791..a53d234542 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -138,7 +138,7 @@ The shared golden vectors are `FULL_VERSION` `{tenantId=tenant-alpha, versionId= Game Logic's retained selected-release manifest and source-operation provenance remain unproved. Its digest receiver therefore rejects full-version requests without returning a participant digest, and Game Design fails the required participant gate rather than accepting the former fixed empty `ownedDraftRuleRows` hash and synthetic `version:` applied commit. Game Design remains the authoring and revision-history owner for authored gameplay rule inputs; its source operation must hand Game Logic the complete selected tenant/version/commit input set with current authority and operation-bound mutation authorization. Game Logic validates and immutably retains that evidence, then owns its participant and dedicated ability-schema attestations. The target ownership and input boundary are defined in the [Game Logic Draft Digest Contract](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) and the authoring shapes in [Ability & Action Design Tools](./ability-action-tools.md); this handoff is not current producer or intake proof. Full-version publication remains unavailable until Game Logic can attest under that contract; script-patch publication does not require the Game Logic participant. -The authored gameplay configuration binds exact Game Design-owned input identities and revisions. It excludes Game Logic's final receipt, a final-commit digest, and any complete Draft commit binding derived from that same commit, so canonicalizing the authored request does not depend on its own result. After the original Game Design source operation settles and Game Logic's distinct intake authorization and immutable retention succeed, the full-version publication gate must join the genuine Game Logic evidence for the exact unchanged `(tenantId, versionId, commitId)`. That derived join and retained receipt are outside the authored request preimage. A changed authored input or selected commit, a missing receipt, or evidence for a different/latest commit fails closed; an exact retry returns the original retained result and cannot substitute another commit. The owner-defined receipt and intake fields remain governed by the [Game Logic Draft Digest Contract](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake), not duplicated here. Current construction, incomplete publication wiring and executed proof are recorded in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); standalone receipt retention does not make this publication boundary live. +The authored gameplay configuration binds exact Game Design-owned input identities and revisions. It excludes Game Logic's final receipt, a final-commit digest, and any complete Draft commit binding derived from that same commit, so canonicalizing the authored request does not depend on its own result. After the original Game Design source operation settles and Game Logic's distinct intake authorization and immutable retention succeed, the full-version publication gate must join the genuine Game Logic evidence for the exact unchanged `(tenantId, versionId, commitId)`. That derived join and retained receipt are outside the authored request preimage. A changed authored input or selected commit, a missing receipt, or evidence for a different/latest commit fails closed; an exact retry returns the original retained result and cannot substitute another commit. The owner-defined receipt and intake fields remain governed by the [Game Logic Draft Digest Contract](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake), not duplicated here. Game Design consumes the distinct [dedicated ability-schema projection](../game-logic-service/runtime-and-data.md#dedicated-ability-schema-projection-v1) with the same exact commit and participant schema/canonicalization evidence; it neither recomputes a different closure nor substitutes the aggregate digest. Current construction, incomplete publication wiring and executed proof are recorded in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); standalone receipt retention does not make this publication boundary live. #### Launch and attestation read authorization (target state) diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index 6541c9b669..dcdad5e278 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -63,6 +63,31 @@ The authenticated publication read must preserve the exact source-operation and The full-version manifest and the dedicated `abilitySchemaDigest` share the selected commit and Game Logic's existing canonicalization and `digestSchemaVersion` contract, but they attest distinct scopes. The aggregate full-manifest `contentDigest` is not an ability-schema digest, and neither the Automation & Scripting digest nor Game Design's control-plane digest substitutes for either Game Logic attestation. Any change to the dedicated ability-schema input set or its canonicalization requires the same explicit schema bump and digest replay or re-record process as other manifest changes. This contract governs publication evidence only; it does not authorize activation of unpublished rules or make Game Logic a participant in Game Design's publication workflow mutations. Game Logic does not read an admin database for runtime rules. +### Dedicated Ability-Schema Projection v1 + +The dedicated content preimage is RFC 8785 canonical UTF-8 JSON with exactly `{"schema":"gameplay-ability-schema/v1","families":{...}}`. `families` contains all 15 names in the closed `gameplay-rule-manifest/v1` grammar, including explicit empty arrays. Validate the complete selected manifest before projecting: unknown fields or definitions, missing families, unresolved references and unsupported shapes fail even outside the selected closure. Seed every `ABILITIES` and every `ACTIONS` definition, then retain the complete typed-reference closure keyed by `(family, logical key)`. Preserve every field of each retained definition, its original selected-manifest family order, and every nested-array order. A visited set terminates reachable cycles while retaining all reachable definitions; this does not establish execution support for an otherwise unsupported cycle. + +The closed grammar's reference edges are exhaustive: + +| Definition family | Typed reference edges | +| --- | --- | +| `ABILITIES` | `actionSequenceId` → `ACTIONS`. | +| `ACTIONS` | `admissionTags` → `ADMISSION_TAGS`; target sets → targeting/selection policies and optional unresolved feedback; costs → `RESOURCES`; effect bindings → `EFFECTS`; `feedbackKeys` → `FEEDBACK`. | +| `CONDITIONS` | `effectKeys` → `EFFECTS`. | +| `EFFECTS` | `statKey` → declared numeric `STATS` or `RESOURCES`; `ADJUST_RESOURCE` and `MAXIMUM` require `RESOURCES`; `conditionKey` → `CONDITIONS`. | +| `OBSERVATION_POLICIES` | Predicate references below. | +| `TARGETING_POLICIES` | `observationPolicyKey` → `OBSERVATION_POLICIES`; eligibility predicate references; `safeFailureFeedbackKey` → `FEEDBACK`. | +| `SELECTION_POLICIES` | Comparator `statKey` → numeric `STATS` or `RESOURCES`; `MAXIMUM` requires `RESOURCES`. | +| `DISPOSITIONS` | `deniedAdmissionTags` → `ADMISSION_TAGS`; `safeFeedbackKey` → `FEEDBACK`. | +| `COMMANDS` | `actionSequenceId` → `ACTIONS`; `admissionTags` → `ADMISSION_TAGS`; commands are not roots or reverse dependencies. | +| `CONTINUOUS_OVERLAYS` | Eligibility predicate references; `deniedAdmissionTags` → `ADMISSION_TAGS`; `effectKeys` → `EFFECTS`. | +| `DEFAULT_BINDINGS` | Target sets → targeting/selection policies and optional unresolved feedback. | +| `STATS`, `RESOURCES`, `ADMISSION_TAGS`, `FEEDBACK` | No external definition references. Their complete fields, tags and feedback arguments remain retained when reached. | + +Target-set policy fields are `targetingPolicyKey` → `TARGETING_POLICIES`, `targetSelectionPolicyKey` → `SELECTION_POLICIES`, and non-null `unresolvedFeedbackKey` → `FEEDBACK`. Predicate operands are traversed recursively: `STAT_COMPARE.factKey` selects its declared numeric stat/resource; `CONDITION_PRESENT.factKey` → `CONDITIONS`; `DISPOSITION_EQUALS.factKey` → `DISPOSITIONS`. `SOURCE` and declared target-set keys are action-local, not catalog aliases. Cooldown keys, names, tags, player-selector slots and feedback argument/message identifiers create no guessed external edges. The closed grammar rejects stat/resource key collisions before resolving a numeric reference. Unreferenced catalogs, commands, overlays and default bindings stay outside this dedicated digest, while remaining in the aggregate manifest. An effective implicit runtime dependency not expressible by this grammar must be reported and denied, not silently omitted or guessed from names. + +Hash these exact bytes with the existing lowercase `sha256:` encoding. Carry the positive participant `digestSchemaVersion`, canonicalization evidence and exact selected-commit/source-operation provenance separately; source/auth receipts, publication metadata and commit IDs never enter this content-only preimage. A valid explicit-empty manifest has a defined content hash but cannot establish authenticated empty-source provenance: the original complete owner inventory and immutable intake must independently prove it. The executable [projection vectors](../../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java) freeze empty preimage/hash `sha256:0207783645e944996b4f7589d2662d5b8309231769681e162ee05de51d34db2a` and the complete two-action/all-root preimage/hash `sha256:659a321a8fd1a02a4825a81568d67dee5039a1cb538756fb91c212aeaea1c536`, plus transitive-field, ordering, unrelated-input and negative cases. Any include/exclude, edge or canonicalization change requires the existing explicit schema bump and replay/re-record process; do not reinterpret retained evidence. Projection construction alone does not register the digest receiver, authorize publication or activate gameplay. + ## Redis Role and Prefixes ### Coordination Redis diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index e3b1c2eaea..8e63b37930 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -132,3 +132,15 @@ Entry format: - Observation: The table's existing primary key was a strict subset of that composite key, so the extra unique index enforced no additional uniqueness invariant. This was not evidence that PostgreSQL rejected the migration. - Expected pattern: Compare the intended invariant with existing keys before adding simulator-specific scaffolding or weakening payload bounds. Remove a genuinely redundant index when the stronger key already enforces the contract; retain separate physical PostgreSQL migration proof. - Current status: Removing the redundant index restored V61 schema generation. The subsequent integration-fixture and static-check corrections passed the complete Game Design gate R193; all three V61 PostgreSQL definitions compiled but skipped without Docker. Physical V61 proof remains unexecuted locally. + +- `2026-10-09`: Distinguish subagent startup builder failures from model capacity + - Context: After publishing PR #3105's source-read checkpoint, fresh Sol High/Medium and Luna XHigh implementation helpers failed at startup with `builder error`, including same-scope retries, before edits or validation. An earlier Luna investigation completed normally. + - Observation: The tool supplied no capacity, thread-limit or model-service diagnostic, so neither model exhaustion nor successful slot recovery is established. Repeated replacement launches supplied no execution work. + - Expected pattern: Preserve the published checkpoint, report the actual error and affected models, and continue dependency-safe lane integration where possible. Do not count failed launches as review evidence or silently treat a model substitution as a successful recovery. + - Current status: Reported to Overseer through controller message `8684fed6`; the cause remains unknown. The parent continued the bounded approved projection. A later same-scope Luna XHigh retry began the Account transport assignment; this establishes partial recovery, not a diagnosed cause or recovery of every failed launch. + +- `2026-10-09`: A launched validation is not a completed continuation checkpoint + - Context: Document ended a heartbeat turn after launching consolidated gate R202 and recording an inbox decision, despite unfinished authorized implementation. The user had to prompt continuation; the gate subsequently exposed seven test failures. + - Observation: Saying validation was underway did not consume its terminal result or advance the assigned correction. A process identifier is not a wake-capable handoff. + - Expected pattern: Remain with local validation through terminal evidence, integrate failures and continue safe assigned work. If a genuine interruption requires yielding, preserve the exact pending process and next action without describing it as completed work. + - Current status: The terminal result was consumed, disjoint Common and Account fixture/transport corrections were delegated, and the parent resumed integration. No proof or completion credit was assigned to the failed gate. 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 3ccd18bd25..f481bb0382 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The callable but unregistered Account intake producer and dedicated ability-schema projection pass consolidated gate R204: 2,569 unit cases (374 Common, 1,109 Account, 425 Game Design, 105 Game Logic and 556 World), plus 12 non-PostgreSQL integration cases. All 569 PostgreSQL definitions compile but skip locally without Docker. Five-module full checks, formatting, static analysis, coverage, four boot JARs, links and Markdown pass; unchanged outputs are reused. The projection's eight cases freeze content-only preimages and digests, complete typed closure, ordering and unsupported-input denial. The new producer transport exercises actual mutual TLS and a response exceeding 4 MiB using synthetic source evidence. Account captures trusted environment authority again after the remote Game Design read, while exact finalized recovery precedes capture. The corrected PostgreSQL regression and canonical post-abort source mutation still require corrected-head physical execution. Earlier R202 and R203 failures were corrected test metadata/interceptor/byte-sequence and randomly regenerated response fixtures; no production authentication guard was weakened. Selected-receipt publication composition, genuine authoring provenance and all four Gameplay handoffs remain open. + +Published `5bd869a20cb0b2f6f6315be17a2c06b069999822` [Validation run 37882677931](https://github.com/benhook1013/FireMUD/actions/runs/37882677931) executed 252 Account PostgreSQL cases with zero skips and two failures. One reveals stale environment evidence reused across the remote Game Design source read; the other bypasses the canonical Account security writer in the post-abort fixture. The prepared correction recaptures trusted environment evidence before finalization and uses the canonical writer without weakening its event guard. Corrected-head execution remains required. Game Design's 126 and World's 206 PostgreSQL cases passed with zero skips, including the previously corrected branding and inventory fixtures. Game Logic tasks passed without accessible exact integration counts. The Account WAL case did not fail in this run, but that does not establish the separately required deterministic target-COMMIT durability mechanism. The actual merge tree was `a0b6b9bfd8dbc4e79611d4480192b94d7038a56a`, with parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head; intended-parent alignment and all four genuine Gameplay handoffs remain open. + The two-phase source-read checkpoint passes consolidated local gate R199: 2,545 unit cases (358 Common, 1,101 Account, 425 Game Design, 105 Game Logic and 556 World) and 12 non-PostgreSQL integration cases pass. All 569 PostgreSQL definitions compile but skip without Docker: 237 Account, 123 Game Design, three Game Logic and 206 World. Account V112 schema generation, five-module full checks, formatting, static checks, coverage, four service boot JARs, links and Markdown pass; unchanged task outputs may be reused. The dedicated source-permission and Game Design read transports execute over-4-MiB mutual-TLS cases with synthetic content, not genuine authoring provenance. Reservation/finalization, lost-response, authority-change and abort-race database definitions remain unexecuted locally. This is construction proof, not deployment registration or activation. Published head `75fdca93c12247c62af46122c9e076a7afd77470` [Validation run 37879887162](https://github.com/benhook1013/FireMUD/actions/runs/37879887162) completed red with three owned failures. Account executed 249 PostgreSQL cases with one conservative original-acknowledgement WAL-coverage denial; its 1,097 unit cases passed. Game Design executed 126 PostgreSQL cases with one mixed-source branding fixture failure; all template-config cases and all three new V61 selected-publication receipt cases passed. Its 425 unit cases passed. World executed 206 PostgreSQL cases with one negative-fixture SQLSTATE mismatch; its exact original Account-order completion/retry/substitution case and 556 units passed. These database suites had zero skips. Game Logic's unit and integration tasks passed, but accessible reports do not establish their counts. The two bounded fixture corrections now use a genuinely authored admission tag and valid empty-object inventory bytes while preserving strict owner and SQLSTATE denial assertions; corrected-head physical execution remains required. V90/V92 WAL guards remain unchanged. The actual checkout was synthetic merge `74963096e200a3a9c801bede84deecf359de209d`, tree `5e0ada4bd3fad8d96cf3fad9cb5b83890015da94`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the pinned head, not the recorded integrated parent. The later skipped-matrix duplicate supplies no proof. Intended-parent alignment, complete source-to-release composition and all four Gameplay handoffs remain open. diff --git a/protos/account/v1/game_logic_intake_authorization_service.proto b/protos/account/v1/game_logic_intake_authorization_service.proto new file mode 100644 index 0000000000..35fa8e2448 --- /dev/null +++ b/protos/account/v1/game_logic_intake_authorization_service.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered Game Design producer for the distinct Game Logic intake order. +service AccountGameLogicIntakeAuthorizationService { + rpc AuthorizeIntake(GameLogicIntakeAuthorizationRequest) + returns (GameLogicIntakeAuthorizationResponse); + rpc RecoverIntake(GameLogicIntakeAuthorizationRequest) + returns (GameLogicIntakeAuthorizationResponse); + rpc AbortIntake(GameLogicIntakeAuthorizationRequest) + returns (GameLogicIntakeAuthorizationResponse); +} + +// The original creator credential is carried only in protected per-call metadata. +message GameLogicIntakeAuthorizationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string transport_request_id = 3; + string intake_request_id = 4; + bytes selected_draft_binding = 5; +} + +message GameLogicIntakeAuthorizationResponse { + enum Outcome { + OUTCOME_UNSPECIFIED = 0; + RESERVED = 1; + FINALIZED = 2; + ABORTED = 3; + } + GameLogicIntakeAuthorizationRequest request = 1; + Outcome outcome = 2; + bytes preliminary_source_scope = 3; + bytes finalized_intake_authorization = 4; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java new file mode 100644 index 0000000000..3b72c49cca --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcService.java @@ -0,0 +1,260 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.BindableService; +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationServiceGrpc; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone, unregistered same-namespace Game Design intake authorization producer. */ +public final class AccountGameLogicIntakeAuthorizationGrpcService implements BindableService { + private final AccountGameLogicIntakeAuthorizationService owner; + private final AccountHostedTermsService terms; + private final String namespace; + + public AccountGameLogicIntakeAuthorizationGrpcService( + AccountGameLogicIntakeAuthorizationService owner, + AccountHostedTermsService terms, + String namespace) { + this.owner = Objects.requireNonNull(owner); + this.terms = Objects.requireNonNull(terms); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + /** Peer authentication precedes protected metadata parsing and all request decoding. */ + @Override + public ServerServiceDefinition bindService() { + var handler = + new AccountGameLogicIntakeAuthorizationServiceGrpc + .AccountGameLogicIntakeAuthorizationServiceImplBase() { + @Override + public void authorizeIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + AccountGameLogicIntakeAuthorizationGrpcService.this.authorizeIntake(request, observer); + } + + @Override + public void recoverIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + AccountGameLogicIntakeAuthorizationGrpcService.this.recoverIntake(request, observer); + } + + @Override + public void abortIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + AccountGameLogicIntakeAuthorizationGrpcService.this.abortIntake(request, observer); + } + }; + return ServerInterceptors.intercept( + handler, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Status denied = peerDenial(); + if (denied != null) { + call.close(sanitized(denied), new Metadata()); + return new ServerCall.Listener<>() {}; + } + String method = call.getMethodDescriptor().getFullMethodName(); + if (!AccountGameLogicIntakeAuthorizationCredentials.allowedMethod(method)) { + call.close(sanitized(Status.UNIMPLEMENTED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + final AccountGameLogicIntakeAuthorizationCredentials.Credential credential; + try { + credential = + AccountGameLogicIntakeAuthorizationCredentials.readAuthenticated(headers, method); + } catch (IllegalArgumentException malformed) { + call.close(sanitized(Status.UNAUTHENTICATED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + var context = + Context.current() + .withValue( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY, credential); + return Contexts.interceptCall(context, call, headers, next); + } + }); + } + + public void authorizeIntake( + GameLogicIntakeAuthorizationRequest wire, + StreamObserver observer) { + final AuthenticatedRequest authenticated; + try { + authenticated = request(wire); + } catch (StatusRuntimeException denied) { + deny(observer, Status.fromCode(denied.getStatus().getCode())); + return; + } + var request = authenticated.request(); + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + final GameLogicIntakeAuthorizationResponse response; + try { + var authorization = + owner.authorizeWithEnvironmentCapture( + authenticated.originalCreatorCredential(), + request.intakeRequestId(), + request.selected(), + terms::captureCurrentEnvironmentBoundary); + response = + GameLogicIntakeAuthorizationGrpcCodec.toResponse( + GameLogicIntakeAuthorizationEvidence.Result.authorized(request, authorization)); + } catch (RuntimeException unavailable) { + deny(observer, statusOf(unavailable)); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + public void recoverIntake( + GameLogicIntakeAuthorizationRequest wire, + StreamObserver observer) { + var authenticated = parseRequest(wire, observer); + if (authenticated == null) return; + var request = authenticated.request(); + final GameLogicIntakeAuthorizationResponse response; + try { + var recovery = + owner.recover( + authenticated.originalCreatorCredential(), + request.intakeRequestId(), + request.selected()); + response = GameLogicIntakeAuthorizationGrpcCodec.toResponse(recovered(request, recovery)); + } catch (RuntimeException unavailable) { + deny(observer, statusOf(unavailable)); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + public void abortIntake( + GameLogicIntakeAuthorizationRequest wire, + StreamObserver observer) { + var authenticated = parseRequest(wire, observer); + if (authenticated == null) return; + var request = authenticated.request(); + final GameLogicIntakeAuthorizationResponse response; + try { + var recovery = + owner.abortSourceRead( + authenticated.originalCreatorCredential(), + request.intakeRequestId(), + request.selected()); + response = GameLogicIntakeAuthorizationGrpcCodec.toResponse(recovered(request, recovery)); + } catch (RuntimeException unavailable) { + deny(observer, statusOf(unavailable)); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private AuthenticatedRequest parseRequest( + GameLogicIntakeAuthorizationRequest wire, + StreamObserver observer) { + try { + var authenticated = request(wire); + var request = authenticated.request(); + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return null; + } + return authenticated; + } catch (StatusRuntimeException denied) { + deny(observer, Status.fromCode(denied.getStatus().getCode())); + return null; + } + } + + private AuthenticatedRequest request(GameLogicIntakeAuthorizationRequest wire) { + Status denied = peerDenial(); + if (denied != null) throw sanitized(denied).asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw sanitized(Status.FAILED_PRECONDITION).asRuntimeException(); + var protectedCredential = AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get(); + if (protectedCredential == null) throw sanitized(Status.UNAUTHENTICATED).asRuntimeException(); + final String credential; + try { + credential = protectedCredential.value(); + } catch (IllegalArgumentException malformed) { + throw sanitized(Status.UNAUTHENTICATED).asRuntimeException(); + } + try { + return new AuthenticatedRequest( + GameLogicIntakeAuthorizationGrpcCodec.fromRequest(wire), credential); + } catch (IllegalArgumentException malformed) { + throw sanitized(Status.INVALID_ARGUMENT).asRuntimeException(); + } + } + + private static GameLogicIntakeAuthorizationEvidence.Result recovered( + GameLogicIntakeAuthorizationEvidence.Request request, + AccountGameLogicIntakeSourceReadRecovery recovery) { + return new GameLogicIntakeAuthorizationEvidence.Result( + request, + GameLogicIntakeAuthorizationEvidence.Outcome.valueOf(recovery.state().name()), + java.util.Optional.of(recovery.scope()), + recovery.authorization()); + } + + private record AuthenticatedRequest( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential) { + @Override + public String toString() { + return "AuthenticatedGameLogicIntakeAuthorizationRequest[redacted]"; + } + } + + private Status peerDenial() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) return Status.UNAUTHENTICATED; + return ("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri()) + ? null + : Status.PERMISSION_DENIED; + } + + private static Status statusOf(RuntimeException error) { + if (error instanceof StatusRuntimeException status) + return Status.fromCode(status.getStatus().getCode()); + if (error instanceof IllegalArgumentException) return Status.FAILED_PRECONDITION; + return Status.UNAVAILABLE; + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError(sanitized(status).asRuntimeException()); + } + + private static Status sanitized(Status status) { + return status.withDescription("Account Game Logic intake authorization denied or unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java index 96b9f8ff76..0ede8e79fe 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationService.java @@ -3,6 +3,7 @@ import io.grpc.Status; import java.util.Objects; import java.util.UUID; +import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; import net.firedevops.firemud.common.authoring.DraftCommitBinding; @@ -54,10 +55,24 @@ public GameLogicIntakeAuthorizationBinding authorize( UUID intakeRequestId, DraftCommitBinding selected, CapturedEnvironmentBoundary environment) { + return authorizeWithEnvironmentCapture( + compactJwt, intakeRequestId, selected, () -> environment); + } + + /** + * Exact finalized recovery precedes mutable environment capture. New work captures authority for + * reservation, then captures it again after the remote source read before finalization. + */ + public GameLogicIntakeAuthorizationBinding authorizeWithEnvironmentCapture( + String compactJwt, + UUID intakeRequestId, + DraftCommitBinding selected, + Supplier environmentCapture) { requirePeer(); net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.requireUuid( intakeRequestId); Objects.requireNonNull(selected); + Objects.requireNonNull(environmentCapture); if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) throw Status.FAILED_PRECONDITION @@ -70,6 +85,7 @@ public GameLogicIntakeAuthorizationBinding authorize( if (original.state() == AccountGameLogicIntakeSourceReadRecovery.State.ABORTED) throw Status.FAILED_PRECONDITION.asRuntimeException(); } + var environment = Objects.requireNonNull(environmentCapture.get()); var scope = reserveSourceRead(compactJwt, intakeRequestId, selected, environment); var recovered = recover(scope); if (recovered.authorization().isPresent()) return recovered.authorization().orElseThrow(); @@ -81,10 +97,11 @@ public GameLogicIntakeAuthorizationBinding authorize( || !request.equals(evidence.request()) || !selected.equals(evidence.source().binding())) throw new IllegalStateException("Exact authenticated complete GD source required"); + var finalizationEnvironment = Objects.requireNonNull(environmentCapture.get()); return actors.withCurrent( compactJwt, selected.target().canonicalTenantId(), - environment, + finalizationEnvironment, current -> { fences.lockProducerSourcesNowait(current.source().sources()); return repository.finalizeSourceRead( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java index 03699c90db..83b701156f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java @@ -433,7 +433,7 @@ public Instant instant() { }); f.tx( () -> { - f.dsl.execute("UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); + f.changeRoleToAdmin(); return null; }); assertThat( @@ -765,8 +765,11 @@ void sourceReadbackProvesExactCurrentScopeAndChangedAuthorityBetweenPhasesCannot () -> asGameDesign( () -> - service.authorize( - issued.compact(), request, selected, issued.environment()))) + service.authorizeWithEnvironmentCapture( + issued.compact(), + request, + selected, + f.terms::captureCurrentEnvironmentBoundary))) .isInstanceOf(RuntimeException.class); assertThat(asGameDesign(() -> service.recover(issued.compact(), request, selected)).state()) .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.RESERVED); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java new file mode 100644 index 0000000000..9752af1f46 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java @@ -0,0 +1,378 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationGrpcCodec; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Receiver boundary tests; no PostgreSQL or genuine authoring provenance is implied. */ +class AccountGameLogicIntakeAuthorizationGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String CREDENTIAL = "original.creator.credential"; + + private final AccountGameLogicIntakeAuthorizationService owner = + mock(AccountGameLogicIntakeAuthorizationService.class); + private final AccountHostedTermsService terms = mock(AccountHostedTermsService.class); + private final AccountGameLogicIntakeAuthorizationGrpcService receiver = + new AccountGameLogicIntakeAuthorizationGrpcService(owner, terms, NAMESPACE); + + @AfterEach + void clearContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactPeerAndCredentialBeforeDecodingOrOwnerCapture() { + assertThat(invokeAuthorize(null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String workload : + List.of("world-management-service", "game-logic-service", "account-service")) + assertThat(peer(NAMESPACE, workload, () -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + peer( + NAMESPACE, + "game-design-service", + () -> invokeAuthorize(GameLogicIntakeAuthorizationRequest.getDefaultInstance())) + .code()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat( + authorized( + () -> + invokeAuthorize( + GameLogicIntakeAuthorizationRequest.newBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1) + .build()) + .build()) + .build())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + authorized( + () -> + invokeAuthorize(request().toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner, terms); + } + + @Test + void boundInterceptorAuthenticatesPeerBeforeReadingMethodLocalCredential() { + var headers = mock(io.grpc.Metadata.class); + assertThat(boundCode(headers)).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer(NAMESPACE, "world-management-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(headers, owner, terms); + + var malformed = new io.grpc.Metadata(); + malformed.put( + io.grpc.Metadata.Key.of( + AccountGameLogicIntakeAuthorizationCredentials.HEADER.name(), + io.grpc.Metadata.BINARY_BYTE_MARSHALLER), + new byte[] {(byte) 255}); + assertThat(peer(NAMESPACE, "game-design-service", () -> boundCode(malformed))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + } + + @Test + void capturesEnvironmentOnlyThroughSupplierAndEchoesExactSelectionWithoutCredential() { + var safeRequest = request(); + var decoded = GameLogicIntakeAuthorizationGrpcCodec.fromRequest(safeRequest); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + var binding = authorization(decoded); + var captures = new AtomicInteger(); + when(terms.captureCurrentEnvironmentBoundary()) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + captures.incrementAndGet(); + return captured; + }); + when(owner.authorizeWithEnvironmentCapture( + eq(CREDENTIAL), eq(decoded.intakeRequestId()), eq(decoded.selected()), any())) + .thenAnswer( + call -> { + Supplier capture = call.getArgument(3); + assertThat(capture.get()).isSameAs(captured); + return binding; + }); + + var result = authorized(() -> invokeAuthorize(safeRequest)); + assertThat(result.error()).isNull(); + assertThat(captures).hasValue(1); + var response = GameLogicIntakeAuthorizationGrpcCodec.fromResponse(decoded, result.response()); + assertThat(response.authorization().orElseThrow().canonicalBytes()) + .containsExactly(binding.canonicalBytes()); + assertThat(result.response().toString()).doesNotContain(CREDENTIAL); + assertThat(safeRequest.toString()).doesNotContain(CREDENTIAL); + } + + @Test + void explicitRecoverAndAbortUseTheSameProtectedRequestWithoutEnvironmentCapture() { + var wire = request(); + var decoded = GameLogicIntakeAuthorizationGrpcCodec.fromRequest(wire); + var selected = decoded.selected(); + var scope = + new GameLogicIntakeSourceReadScope( + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + decoded.intakeRequestId(), + UUID.randomUUID(), + selected, + "spiffe://firemud/ns/test/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + var reserved = + new AccountGameLogicIntakeSourceReadRecovery( + scope, AccountGameLogicIntakeSourceReadRecovery.State.RESERVED, Optional.empty()); + var aborted = + new AccountGameLogicIntakeSourceReadRecovery( + scope, AccountGameLogicIntakeSourceReadRecovery.State.ABORTED, Optional.empty()); + when(owner.recover(CREDENTIAL, decoded.intakeRequestId(), selected)).thenReturn(reserved); + when(owner.abortSourceRead(CREDENTIAL, decoded.intakeRequestId(), selected)) + .thenReturn(aborted); + + var recovered = authorized(() -> invoke(wire, Operation.RECOVER)); + var stopped = authorized(() -> invoke(wire, Operation.ABORT)); + assertThat(recovered.error()).isNull(); + assertThat(stopped.error()).isNull(); + assertThat( + GameLogicIntakeAuthorizationGrpcCodec.fromResponse(decoded, recovered.response()) + .outcome()) + .isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED); + assertThat( + GameLogicIntakeAuthorizationGrpcCodec.fromResponse(decoded, stopped.response()) + .outcome()) + .isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED); + org.mockito.Mockito.verify(owner).recover(CREDENTIAL, decoded.intakeRequestId(), selected); + org.mockito.Mockito.verify(owner) + .abortSourceRead(CREDENTIAL, decoded.intakeRequestId(), selected); + verifyNoInteractions(terms); + } + + @Test + void rejectsAmbientSqlBeforeAnyAccountOwnerAccess() { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThat(authorized(() -> invokeAuthorize(request())).code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(owner, terms); + } + + @Test + void reportsOwnerFailuresBySanitizedStatusAndNeverEchoesCredential() { + when(owner.authorizeWithEnvironmentCapture(eq(CREDENTIAL), any(), any(), any())) + .thenThrow(Status.PERMISSION_DENIED.withDescription(CREDENTIAL).asRuntimeException()); + var denied = authorized(() -> invokeAuthorize(request())); + assertThat(denied.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + assertThat(denied.error().getCause()).isNull(); + } + + private record Result(GameLogicIntakeAuthorizationResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private Result invokeAuthorize(GameLogicIntakeAuthorizationRequest request) { + return invoke(request, Operation.AUTHORIZE); + } + + private Result invoke(GameLogicIntakeAuthorizationRequest request, Operation operation) { + var response = new AtomicReference(); + var error = new AtomicReference(); + var observer = + new io.grpc.stub.StreamObserver() { + @Override + public void onNext(GameLogicIntakeAuthorizationResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() {} + }; + switch (operation) { + case AUTHORIZE -> receiver.authorizeIntake(request, observer); + case RECOVER -> receiver.recoverIntake(request, observer); + case ABORT -> receiver.abortIntake(request, observer); + } + return new Result(response.get(), error.get()); + } + + private enum Operation { + AUTHORIZE, + RECOVER, + ABORT + } + + @SuppressWarnings("unchecked") + private Status.Code boundCode(io.grpc.Metadata headers) { + var method = + (io.grpc.ServerMethodDefinition< + GameLogicIntakeAuthorizationRequest, GameLogicIntakeAuthorizationResponse>) + receiver.bindService().getMethods().stream() + .filter( + candidate -> + candidate + .getMethodDescriptor() + .getFullMethodName() + .equals( + net.firedevops.firemud.account.v1 + .AccountGameLogicIntakeAuthorizationServiceGrpc + .getAuthorizeIntakeMethod() + .getFullMethodName())) + .findFirst() + .orElseThrow(); + io.grpc.ServerCall + call = mock(io.grpc.ServerCall.class); + when(call.getMethodDescriptor()).thenReturn(method.getMethodDescriptor()); + method.getServerCallHandler().startCall(call, headers); + var status = org.mockito.ArgumentCaptor.forClass(Status.class); + org.mockito.Mockito.verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any()); + return status.getValue().getCode(); + } + + private static T authorized(Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY, + AccountGameLogicIntakeAuthorizationCredentials.Credential.of(CREDENTIAL)); + var prior = context.attach(); + try { + return peer(NAMESPACE, "game-design-service", action); + } finally { + context.detach(prior); + } + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static GameLogicIntakeAuthorizationRequest request() { + var safe = + GameLogicIntakeAuthorizationEvidence.Request.create( + NAMESPACE, UUID.randomUUID(), selected()); + return GameLogicIntakeAuthorizationGrpcCodec.toRequest(safe); + } + + private static DraftCommitBinding selected() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameLogicIntakeAuthorizationBinding authorization( + GameLogicIntakeAuthorizationEvidence.Request request) { + var selected = request.selected(); + var actor = UUID.randomUUID(); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + java.util.Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + request.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java new file mode 100644 index 0000000000..764bfd1d1a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java @@ -0,0 +1,284 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadScope; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountGameLogicIntakeAuthorizationRecoveryTest { + private static final String CREDENTIAL = "unchanged.creator.credential"; + private static final String NAMESPACE = "test"; + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactFinalizedRetryRecoversBeforeCapturingMutableEnvironmentAuthority() { + var selected = selected(); + var intakeRequestId = UUID.randomUUID(); + UUID actor = UUID.randomUUID(); + var scope = + new GameLogicIntakeSourceReadScope( + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + intakeRequestId, + actor, + selected, + "spiffe://firemud/ns/test/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + var authorization = authorization(scope, actor); + var actors = mock(AccountControlUiActorService.class); + var fences = + mock( + net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository + .class); + var repository = mock(AccountGameLogicIntakeAuthorizationRepository.class); + var sourceClient = mock(GameplayRuleSourceReadClient.class); + when(repository.findSourceReadScope( + eq(intakeRequestId), eq(selected), eq(NAMESPACE), anyString())) + .thenReturn(Optional.of(scope)); + when(repository.recoverSourceRead(scope)) + .thenReturn( + new AccountGameLogicIntakeSourceReadRecovery( + scope, + AccountGameLogicIntakeSourceReadRecovery.State.FINALIZED, + Optional.of(authorization))); + + var service = + new AccountGameLogicIntakeAuthorizationService( + actors, fences, repository, sourceClient, new NoopTransactionManager(), NAMESPACE); + var captures = new AtomicInteger(); + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + var recovered = + service.authorizeWithEnvironmentCapture( + CREDENTIAL, + intakeRequestId, + selected, + () -> { + captures.incrementAndGet(); + throw new IllegalStateException("mutable environment must not be read on retry"); + }); + assertThat(recovered.canonicalBytes()).containsExactly(authorization.canonicalBytes()); + } finally { + context.detach(prior); + } + assertThat(captures).hasValue(0); + verify(repository) + .findSourceReadScope(eq(intakeRequestId), eq(selected), eq(NAMESPACE), anyString()); + verify(repository).recoverSourceRead(scope); + verifyNoInteractions(actors, fences, sourceClient); + } + + @Test + void requiresFreshAuthorityAfterRemoteSourceReadBeforeFinalization() { + var selected = selected(); + var intakeRequestId = UUID.randomUUID(); + UUID actor = UUID.randomUUID(); + var scope = + new GameLogicIntakeSourceReadScope( + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + intakeRequestId, + actor, + selected, + "spiffe://firemud/ns/test/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + var authorization = authorization(scope, actor); + var actors = mock(AccountControlUiActorService.class); + var fences = mock(DraftAuthorizationFenceRepository.class); + var repository = mock(AccountGameLogicIntakeAuthorizationRepository.class); + var sourceClient = mock(GameplayRuleSourceReadClient.class); + var initialEnvironment = mock(CapturedEnvironmentBoundary.class); + var events = new ArrayList(); + var current = mock(AccountControlUiActorService.Current.class); + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + when(current.source()).thenReturn(snapshot); + when(snapshot.sources()).thenReturn(List.of()); + when(repository.findSourceReadScope( + eq(intakeRequestId), eq(selected), eq(NAMESPACE), anyString())) + .thenReturn(Optional.empty()); + when(repository.reserveSourceRead( + eq(intakeRequestId), eq(selected), eq(current), eq(NAMESPACE), any(Runnable.class))) + .thenReturn(scope); + when(repository.recoverSourceRead(scope)) + .thenReturn( + new AccountGameLogicIntakeSourceReadRecovery( + scope, AccountGameLogicIntakeSourceReadRecovery.State.RESERVED, Optional.empty())); + when(sourceClient.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenAnswer( + call -> { + events.add("source-read"); + return new GameplayRuleSourceReadEvidence( + call.getArgument(0), authorization.source()); + }); + var actorCalls = new AtomicInteger(); + doAnswer( + call -> { + events.add("actor-" + actorCalls.incrementAndGet()); + @SuppressWarnings("unchecked") + Function action = + (Function) call.getArgument(3); + return action.apply(current); + }) + .when(actors) + .withCurrent(anyString(), any(), any(), any()); + + var service = + new AccountGameLogicIntakeAuthorizationService( + actors, fences, repository, sourceClient, new NoopTransactionManager(), NAMESPACE); + var environmentCaptures = new AtomicInteger(); + var currentnessUnavailable = new IllegalStateException("fresh authority unavailable"); + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + assertThatThrownBy( + () -> + service.authorizeWithEnvironmentCapture( + CREDENTIAL, + intakeRequestId, + selected, + () -> { + if (environmentCaptures.incrementAndGet() == 1) { + events.add("capture-reservation"); + return initialEnvironment; + } + events.add("capture-finalization"); + throw currentnessUnavailable; + })) + .isSameAs(currentnessUnavailable); + } finally { + context.detach(prior); + } + + assertThat(environmentCaptures).hasValue(2); + assertThat(actorCalls).hasValue(1); + assertThat(events) + .containsExactly("capture-reservation", "actor-1", "source-read", "capture-finalization"); + verify(repository, never()).finalizeSourceRead(any(), any(), any(), any()); + } + + private static DraftCommitBinding selected() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static GameLogicIntakeAuthorizationBinding authorization( + GameLogicIntakeSourceReadScope scope, UUID actor) { + var selected = scope.selected(); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + java.util.Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + return new GameLogicIntakeAuthorizationBinding( + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + + private static final class NoopTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java new file mode 100644 index 0000000000..7742adfc40 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeAuthorizationCredentials.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.CallCredentials; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Executor; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationServiceGrpc; + +/** Method-scoped protected metadata for the unchanged original creator credential. */ +public final class AccountGameLogicIntakeAuthorizationCredentials { + public static final int MAX_CREDENTIAL_BYTES = 16384; + public static final Context.Key CONTEXT_KEY = + Context.key("account-game-logic-intake-original-creator"); + public static final Metadata.Key HEADER = + Metadata.Key.of( + "firemud-game-logic-intake-creator-bin", + new Metadata.BinaryMarshaller<>() { + @Override + public byte[] toBytes(Credential value) { + return value.bytes.clone(); + } + + // Defer credential validation until the receiver has authenticated its caller. + @Override + public Credential parseBytes(byte[] serialized) { + return new Credential(serialized); + } + }); + + private AccountGameLogicIntakeAuthorizationCredentials() {} + + public static final class Credential { + private final byte[] bytes; + + private Credential(byte[] bytes) { + this.bytes = bytes.clone(); + } + + public static Credential of(String value) { + if (!validCredential(value)) throw invalid(); + return new Credential(value.getBytes(StandardCharsets.US_ASCII)); + } + + public String value() { + if (bytes.length == 0 || bytes.length > MAX_CREDENTIAL_BYTES) throw invalid(); + for (byte value : bytes) if (value <= 32 || value >= 127) throw invalid(); + return new String(bytes, StandardCharsets.US_ASCII); + } + + @Override + public String toString() { + return "GameLogicIntakeCreatorCredential[redacted]"; + } + } + + public static Credential readAuthenticated(Metadata headers, String methodName) { + if (!allowedMethod(methodName)) throw invalid(); + var values = headers.getAll(HEADER); + if (values == null) throw invalid(); + var iterator = values.iterator(); + if (!iterator.hasNext()) throw invalid(); + Credential credential = iterator.next(); + if (iterator.hasNext()) throw invalid(); + credential.value(); + return credential; + } + + public static CallCredentials forAuthorize(String value) { + return forMethod( + value, + AccountGameLogicIntakeAuthorizationServiceGrpc.getAuthorizeIntakeMethod() + .getFullMethodName()); + } + + public static CallCredentials forRecover(String value) { + return forMethod( + value, + AccountGameLogicIntakeAuthorizationServiceGrpc.getRecoverIntakeMethod() + .getFullMethodName()); + } + + public static CallCredentials forAbort(String value) { + return forMethod( + value, + AccountGameLogicIntakeAuthorizationServiceGrpc.getAbortIntakeMethod().getFullMethodName()); + } + + private static CallCredentials forMethod(String value, String allowedMethod) { + var credential = Credential.of(value); + return new CallCredentials() { + @Override + public void applyRequestMetadata( + RequestInfo info, Executor executor, MetadataApplier applier) { + if (info.getSecurityLevel() != SecurityLevel.PRIVACY_AND_INTEGRITY + || !allowedMethod.equals(info.getMethodDescriptor().getFullMethodName())) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Protected Account intake authorization transport required")); + return; + } + var headers = new Metadata(); + headers.put(HEADER, credential); + applier.apply(headers); + } + + @Override + public void thisUsesUnstableApi() {} + + @Override + public String toString() { + return "GameLogicIntakeCreatorCallCredentials[redacted]"; + } + }; + } + + public static boolean allowedMethod(String methodName) { + return AccountGameLogicIntakeAuthorizationServiceGrpc.getAuthorizeIntakeMethod() + .getFullMethodName() + .equals(methodName) + || AccountGameLogicIntakeAuthorizationServiceGrpc.getRecoverIntakeMethod() + .getFullMethodName() + .equals(methodName) + || AccountGameLogicIntakeAuthorizationServiceGrpc.getAbortIntakeMethod() + .getFullMethodName() + .equals(methodName); + } + + private static boolean validCredential(String credential) { + return credential != null + && !credential.isEmpty() + && credential.length() <= MAX_CREDENTIAL_BYTES + && credential.chars().allMatch(value -> value > 32 && value < 127); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Game Logic intake credential metadata"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationClient.java new file mode 100644 index 0000000000..070b7f8c0b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationClient.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.common.gamelogic; + +/** Explicit producer call and same-identity recovery/abort operations. */ +public interface GameLogicIntakeAuthorizationClient { + GameLogicIntakeAuthorizationEvidence.Result authorize( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential); + + GameLogicIntakeAuthorizationEvidence.Result recover( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential); + + GameLogicIntakeAuthorizationEvidence.Result abort( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java new file mode 100644 index 0000000000..8d43cfc7ff --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact closed producer request and bounded recovery result, without credential material. */ +public final class GameLogicIntakeAuthorizationEvidence { + public static final int MAX_SELECTION_BYTES = 4 * 1024 * 1024; + + private GameLogicIntakeAuthorizationEvidence() {} + + public record Request( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + UUID intakeRequestId, + byte[] selectedDraftBinding) { + public Request { + if (schemaVersion != 1 + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || transportRequestId == null + || intakeRequestId == null + || transportRequestId.equals(intakeRequestId)) throw invalid(); + DraftAuthorizationFenceBinding.requireUuid(transportRequestId); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + if (selectedDraftBinding == null + || selectedDraftBinding.length == 0 + || selectedDraftBinding.length > MAX_SELECTION_BYTES) throw invalid(); + selectedDraftBinding = selectedDraftBinding.clone(); + decodeSelection(selectedDraftBinding); + } + + public static Request create( + String namespace, UUID intakeRequestId, DraftCommitBinding selected) { + Objects.requireNonNull(selected); + return new Request( + 1, namespace, UUID.randomUUID(), intakeRequestId, selected.canonicalBytes()); + } + + @Override + public byte[] selectedDraftBinding() { + return selectedDraftBinding.clone(); + } + + public DraftCommitBinding selected() { + return decodeSelection(selectedDraftBinding); + } + + @Override + public String toString() { + return "GameLogicIntakeAuthorization.Request[redacted]"; + } + } + + public enum Outcome { + RESERVED, + FINALIZED, + ABORTED + } + + public record Result( + Request request, + Outcome outcome, + Optional sourceScope, + Optional authorization) { + public Result { + Objects.requireNonNull(request); + Objects.requireNonNull(outcome); + sourceScope = Objects.requireNonNull(sourceScope); + authorization = Objects.requireNonNull(authorization); + sourceScope.ifPresent( + scope -> { + if (!request.targetNamespace().equals(scope.targetNamespace()) + || !request.intakeRequestId().equals(scope.intakeRequestId()) + || !request.selected().equals(scope.selected())) throw invalid(); + }); + authorization.ifPresent( + binding -> { + if (!request.intakeRequestId().equals(binding.intakeRequestId()) + || !request.selected().equals(binding.source().binding())) throw invalid(); + }); + if (sourceScope.isPresent() && authorization.isPresent()) { + var scope = sourceScope.orElseThrow(); + var binding = authorization.orElseThrow(); + if (!scope.operationId().equals(binding.operationId()) + || !scope.fenceId().equals(binding.fenceId()) + || !scope.intakeRequestId().equals(binding.intakeRequestId()) + || !scope.actorAccountId().equals(binding.actorAccountId())) throw invalid(); + } + if (outcome == Outcome.FINALIZED && authorization.isEmpty()) throw invalid(); + if (outcome != Outcome.FINALIZED && (sourceScope.isEmpty() || authorization.isPresent())) + throw invalid(); + } + + public static Result authorized( + Request request, GameLogicIntakeAuthorizationBinding authorization) { + return new Result(request, Outcome.FINALIZED, Optional.empty(), Optional.of(authorization)); + } + } + + static DraftCommitBinding decodeSelection(byte[] bytes) { + try { + String json = new String(bytes, StandardCharsets.UTF_8); + var selection = + DraftCommitBinding.fromStored(json, DraftAuthorizationFenceBinding.digest(bytes)); + if (!Arrays.equals(bytes, selection.canonicalBytes())) throw invalid(); + return selection; + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Game Logic intake authorization evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java new file mode 100644 index 0000000000..d9592f5e85 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.common.gamelogic; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed producer transport codec. The creator credential is never encoded in protobuf. */ +public final class GameLogicIntakeAuthorizationGrpcCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + private static final int MAX_SCOPE_BYTES = 4 * 1024 * 1024; + private static final int MAX_AUTHORIZATION_BYTES = 4 * 1024 * 1024; + + private GameLogicIntakeAuthorizationGrpcCodec() {} + + public static GameLogicIntakeAuthorizationRequest toRequest( + GameLogicIntakeAuthorizationEvidence.Request request) { + var wire = + GameLogicIntakeAuthorizationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setTransportRequestId(request.transportRequestId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setSelectedDraftBinding(ByteString.copyFrom(request.selectedDraftBinding())) + .build(); + requireWireSize(wire.getSerializedSize()); + return wire; + } + + /** Invoke only after authenticating the exact same-namespace Game Design workload. */ + public static GameLogicIntakeAuthorizationEvidence.Request fromRequest( + GameLogicIntakeAuthorizationRequest wire) { + try { + noUnknown(wire); + requireWireSize(wire.getSerializedSize()); + if (wire.getSelectedDraftBinding().size() + > GameLogicIntakeAuthorizationEvidence.MAX_SELECTION_BYTES) throw invalid(); + var request = + new GameLogicIntakeAuthorizationEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + canonicalUuid(wire.getTransportRequestId()), + canonicalUuid(wire.getIntakeRequestId()), + wire.getSelectedDraftBinding().toByteArray()); + if (!toRequest(request).equals(wire)) throw invalid(); + return request; + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + public static GameLogicIntakeAuthorizationResponse toResponse( + GameLogicIntakeAuthorizationEvidence.Result result) { + var builder = + GameLogicIntakeAuthorizationResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setOutcome(toWire(result.outcome())); + result + .sourceScope() + .ifPresent( + scope -> + builder.setPreliminarySourceScope(ByteString.copyFrom(scope.canonicalBytes()))); + result + .authorization() + .ifPresent( + binding -> + builder.setFinalizedIntakeAuthorization( + ByteString.copyFrom(binding.canonicalBytes()))); + var response = builder.build(); + requireWireSize(response.getSerializedSize()); + return response; + } + + public static GameLogicIntakeAuthorizationEvidence.Result fromResponse( + GameLogicIntakeAuthorizationEvidence.Request request, + GameLogicIntakeAuthorizationResponse wire) { + try { + noUnknown(wire); + requireWireSize(wire.getSerializedSize()); + if (!wire.hasRequest() || !toRequest(request).equals(wire.getRequest())) throw invalid(); + Optional scope = Optional.empty(); + Optional authorization = Optional.empty(); + if (wire.getPreliminarySourceScope().size() > MAX_SCOPE_BYTES + || wire.getFinalizedIntakeAuthorization().size() > MAX_AUTHORIZATION_BYTES) + throw invalid(); + if (!wire.getPreliminarySourceScope().isEmpty()) + scope = + Optional.of( + GameLogicIntakeSourceReadScope.fromStored( + wire.getPreliminarySourceScope().toByteArray())); + if (!wire.getFinalizedIntakeAuthorization().isEmpty()) + authorization = + Optional.of( + GameLogicIntakeAuthorizationBinding.fromStored( + wire.getFinalizedIntakeAuthorization().toByteArray())); + return new GameLogicIntakeAuthorizationEvidence.Result( + request, fromWire(wire.getOutcome()), scope, authorization); + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static UUID canonicalUuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } + + private static GameLogicIntakeAuthorizationResponse.Outcome toWire( + GameLogicIntakeAuthorizationEvidence.Outcome outcome) { + return switch (outcome) { + case RESERVED -> GameLogicIntakeAuthorizationResponse.Outcome.RESERVED; + case FINALIZED -> GameLogicIntakeAuthorizationResponse.Outcome.FINALIZED; + case ABORTED -> GameLogicIntakeAuthorizationResponse.Outcome.ABORTED; + }; + } + + private static GameLogicIntakeAuthorizationEvidence.Outcome fromWire( + GameLogicIntakeAuthorizationResponse.Outcome outcome) { + return switch (outcome) { + case RESERVED -> GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED; + case FINALIZED -> GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED; + case ABORTED -> GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED; + default -> throw invalid(); + }; + } + + private static void noUnknown(Message wire) { + if (wire == null || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); + } + + private static void requireWireSize(int size) { + if (size > MAX_WIRE_BYTES) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Game Logic intake authorization transport"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java new file mode 100644 index 0000000000..be45aefd79 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java @@ -0,0 +1,185 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Ability; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Action; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.AdmissionTag; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Command; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Condition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ContinuousOverlay; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.DefaultBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Definition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Effect; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.EffectOperation; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ObservationPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Predicate; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Resource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.SelectionPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stat; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.StatField; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetSet; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetingPolicy; + +/** + * Content-only projection; the caller must independently prove exact retained source provenance. + */ +public final class GameplayAbilitySchemaProjection { + public static final String SCHEMA = "gameplay-ability-schema/v1"; + + private GameplayAbilitySchemaProjection() {} + + public static String canonicalJson(GameplayRuleManifest source) { + // Validate every family, including definitions that will not occur in the projection. + var complete = new GameplayRuleManifest(Objects.requireNonNull(source).families()); + Map definitions = new HashMap<>(); + complete + .families() + .forEach( + (family, values) -> + values.forEach(value -> definitions.put(new Key(family, value.key()), value))); + var pending = new ArrayDeque(); + for (Family root : List.of(Family.ABILITIES, Family.ACTIONS)) + complete.families().get(root).forEach(value -> pending.add(new Key(root, value.key()))); + Set visited = new HashSet<>(); + while (!pending.isEmpty()) { + Key key = pending.remove(); + if (!visited.add(key)) continue; + Definition value = definitions.get(key); + if (value == null) throw new IllegalArgumentException("Unresolved ability-schema reference"); + dependencies(value, definitions, pending); + } + Map> retained = new EnumMap<>(Family.class); + complete + .families() + .forEach( + (family, values) -> + retained.put( + family, + values.stream() + .filter(value -> visited.contains(new Key(family, value.key()))) + .toList())); + // Closure must itself remain a complete, valid inventory; do not repair missing edges with + // defaults. + var projection = new GameplayRuleManifest(retained); + Map families = new LinkedHashMap<>(); + for (Family family : Family.values()) + families.put(family.name(), projection.families().get(family)); + return GameplayRuleManifest.canonical(Map.of("schema", SCHEMA, "families", families)); + } + + public static byte[] canonicalBytes(GameplayRuleManifest source) { + return canonicalJson(source).getBytes(StandardCharsets.UTF_8); + } + + public static String digest(GameplayRuleManifest source) { + return GameplayRuleManifest.sha256(canonicalBytes(source)); + } + + private record Key(Family family, String key) {} + + private static void add(ArrayDeque pending, Family family, String key) { + pending.add(new Key(family, key)); + } + + private static void addAll(ArrayDeque pending, Family family, List keys) { + keys.forEach(key -> add(pending, family, key)); + } + + private static void numeric( + ArrayDeque pending, Map definitions, String key) { + // The closed grammar rejects cross-family stat/resource collisions before traversal. + add( + pending, + definitions.containsKey(new Key(Family.RESOURCES, key)) ? Family.RESOURCES : Family.STATS, + key); + } + + private static void targets(ArrayDeque pending, List targets) { + for (TargetSet target : targets) { + add(pending, Family.TARGETING_POLICIES, target.targetingPolicyKey()); + add(pending, Family.SELECTION_POLICIES, target.targetSelectionPolicyKey()); + if (target.unresolvedFeedbackKey() != null) + add(pending, Family.FEEDBACK, target.unresolvedFeedbackKey()); + } + } + + private static void predicate( + ArrayDeque pending, Map definitions, Predicate value) { + switch (value.kind()) { + case STAT_COMPARE -> numeric(pending, definitions, value.factKey()); + case CONDITION_PRESENT -> add(pending, Family.CONDITIONS, value.factKey()); + case DISPOSITION_EQUALS -> add(pending, Family.DISPOSITIONS, value.factKey()); + case TRUE, FALSE, ALL, ANY, NOT -> {} + } + for (Predicate operand : value.operands()) predicate(pending, definitions, operand); + } + + private static void dependencies( + Definition definition, Map definitions, ArrayDeque pending) { + switch (definition) { + case Stat ignored -> {} + case Resource ignored -> {} + case AdmissionTag ignored -> {} + case Feedback ignored -> {} + case Ability value -> add(pending, Family.ACTIONS, value.actionSequenceId()); + case Condition value -> addAll(pending, Family.EFFECTS, value.effectKeys()); + case Effect value -> { + if (value.statKey() != null) { + if (value.operation() == EffectOperation.ADJUST_RESOURCE + || value.statField() == StatField.MAXIMUM) + add(pending, Family.RESOURCES, value.statKey()); + else numeric(pending, definitions, value.statKey()); + } + if (value.conditionKey() != null) add(pending, Family.CONDITIONS, value.conditionKey()); + } + case Action value -> { + addAll(pending, Family.ADMISSION_TAGS, value.admissionTags()); + targets(pending, value.targetSets()); + value.costs().forEach(cost -> add(pending, Family.RESOURCES, cost.statKey())); + value.effects().forEach(effect -> add(pending, Family.EFFECTS, effect.effectKey())); + addAll(pending, Family.FEEDBACK, value.feedbackKeys()); + } + case Command value -> { + add(pending, Family.ACTIONS, value.actionSequenceId()); + addAll(pending, Family.ADMISSION_TAGS, value.admissionTags()); + } + case Disposition value -> { + addAll(pending, Family.ADMISSION_TAGS, value.deniedAdmissionTags()); + add(pending, Family.FEEDBACK, value.safeFeedbackKey()); + } + case ContinuousOverlay value -> { + predicate(pending, definitions, value.eligibleWhen()); + addAll(pending, Family.ADMISSION_TAGS, value.deniedAdmissionTags()); + addAll(pending, Family.EFFECTS, value.effectKeys()); + } + case ObservationPolicy value -> predicate(pending, definitions, value.observableWhen()); + case TargetingPolicy value -> { + add(pending, Family.OBSERVATION_POLICIES, value.observationPolicyKey()); + predicate(pending, definitions, value.eligibleWhen()); + add(pending, Family.FEEDBACK, value.safeFailureFeedbackKey()); + } + case SelectionPolicy value -> + value + .comparators() + .forEach( + comparator -> { + if (comparator.statField() == StatField.MAXIMUM) + add(pending, Family.RESOURCES, comparator.statKey()); + else numeric(pending, definitions, comparator.statKey()); + }); + case DefaultBinding value -> targets(pending, value.targetSets()); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java new file mode 100644 index 0000000000..70caa14ab4 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClient.java @@ -0,0 +1,194 @@ +package net.firedevops.firemud.common.gamelogic; + +import io.grpc.CompositeCallCredentials; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for the standalone, unregistered Account intake producer. */ +public final class GrpcGameLogicIntakeAuthorizationClient + extends AbstractReloadingBlockingGrpcClient< + AccountGameLogicIntakeAuthorizationServiceGrpc + .AccountGameLogicIntakeAuthorizationServiceBlockingStub> + implements GameLogicIntakeAuthorizationClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcGameLogicIntakeAuthorizationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcGameLogicIntakeAuthorizationClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Canonical workload namespace required"); + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account intake authorization client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account intake authorization stub unavailable"); + initialized = true; + } + + @Override + public GameLogicIntakeAuthorizationEvidence.Result authorize( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential) { + return invoke(request, originalCreatorCredential, Operation.AUTHORIZE); + } + + @Override + public GameLogicIntakeAuthorizationEvidence.Result recover( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential) { + return invoke(request, originalCreatorCredential, Operation.RECOVER); + } + + @Override + public GameLogicIntakeAuthorizationEvidence.Result abort( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential) { + return invoke(request, originalCreatorCredential, Operation.ABORT); + } + + private GameLogicIntakeAuthorizationEvidence.Result invoke( + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential, + Operation operation) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Account intake authorization requires no ambient SQL"); + Objects.requireNonNull(request); + if (!workloadNamespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Account intake authorization namespace mismatch"); + var current = stub(); + if (closed || !initialized || current == null) + throw new IllegalStateException("Account intake authorization client unavailable"); + try { + var secured = + current + .withCallCredentials( + new CompositeCallCredentials( + new GrpcServerPeerIdentityCallCredentials( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"), + credentials(originalCreatorCredential, operation))) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + var wireRequest = GameLogicIntakeAuthorizationGrpcCodec.toRequest(request); + var response = + switch (operation) { + case AUTHORIZE -> secured.authorizeIntake(wireRequest); + case RECOVER -> secured.recoverIntake(wireRequest); + case ABORT -> secured.abortIntake(wireRequest); + }; + var result = GameLogicIntakeAuthorizationGrpcCodec.fromResponse(request, response); + if (operation == Operation.AUTHORIZE + && result.outcome() != GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED) + throw new IllegalArgumentException("Authorization response was not finalized"); + return result; + } catch (StatusRuntimeException unavailable) { + throw Status.fromCode(unavailable.getStatus().getCode()) + .withDescription("Account Game Logic intake authorization denied or unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Account returned invalid Game Logic intake authorization evidence"); + } + } + + private static io.grpc.CallCredentials credentials( + String originalCreatorCredential, Operation operation) { + return switch (operation) { + case AUTHORIZE -> + AccountGameLogicIntakeAuthorizationCredentials.forAuthorize(originalCreatorCredential); + case RECOVER -> + AccountGameLogicIntakeAuthorizationCredentials.forRecover(originalCreatorCredential); + case ABORT -> + AccountGameLogicIntakeAuthorizationCredentials.forAbort(originalCreatorCredential); + }; + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountGameLogicIntakeAuthorizationServiceGrpc + .AccountGameLogicIntakeAuthorizationServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountGameLogicIntakeAuthorizationServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) + throw new IllegalArgumentException("Account intake authorization requires workload mTLS"); + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) + throw new IllegalArgumentException( + "Account intake authorization requires file-backed certificate, key, and CA material"); + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Invalid Account intake authorization " + label + " path"); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) + throw new IllegalArgumentException( + "Account intake authorization " + label + " must be an existing readable file"); + } + + private enum Operation { + AUTHORIZE, + RECOVER, + ABORT + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java new file mode 100644 index 0000000000..5a705acce0 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java @@ -0,0 +1,247 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.junit.jupiter.api.Test; + +class GameLogicIntakeAuthorizationGrpcCodecTest { + private static final String CREDENTIAL = "unchanged.creator.secret"; + + @Test + void roundTripsExactSelectionAndAllRecoveryPhasesWithoutCredentialInWire() { + var request = request(); + var wireRequest = GameLogicIntakeAuthorizationGrpcCodec.toRequest(request); + assertThat(GameLogicIntakeAuthorizationGrpcCodec.fromRequest(wireRequest).selected()) + .isEqualTo(request.selected()); + var credentialBytes = CREDENTIAL.getBytes(java.nio.charset.StandardCharsets.UTF_8); + assertThat(containsSequence(wireRequest.toByteArray(), credentialBytes)).isFalse(); + + var finalized = authorization(request); + var finalizedResult = + GameLogicIntakeAuthorizationEvidence.Result.authorized(request, finalized); + var finalizedWire = GameLogicIntakeAuthorizationGrpcCodec.toResponse(finalizedResult); + var decoded = GameLogicIntakeAuthorizationGrpcCodec.fromResponse(request, finalizedWire); + assertThat(decoded.outcome()).isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED); + assertThat(decoded.authorization().orElseThrow().canonicalBytes()) + .containsExactly(finalized.canonicalBytes()); + assertThat(containsSequence(finalizedWire.toByteArray(), credentialBytes)).isFalse(); + + var scope = scope(request); + for (var outcome : + List.of( + GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED, + GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED)) { + var result = + new GameLogicIntakeAuthorizationEvidence.Result( + request, outcome, Optional.of(scope), Optional.empty()); + var response = GameLogicIntakeAuthorizationGrpcCodec.toResponse(result); + assertThat( + GameLogicIntakeAuthorizationGrpcCodec.fromResponse(request, response).sourceScope()) + .contains(scope); + } + var finalizedRecovery = + new GameLogicIntakeAuthorizationEvidence.Result( + request, + GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED, + Optional.of(scope), + Optional.of(authorization(scope))); + assertThat( + GameLogicIntakeAuthorizationGrpcCodec.fromResponse( + request, GameLogicIntakeAuthorizationGrpcCodec.toResponse(finalizedRecovery)) + .sourceScope()) + .contains(scope); + } + + @Test + void rejectsUnknownChangedAndNoncanonicalEvidenceAndCredentialInputs() { + var request = request(); + var wireRequest = GameLogicIntakeAuthorizationGrpcCodec.toRequest(request); + var response = + GameLogicIntakeAuthorizationGrpcCodec.toResponse( + GameLogicIntakeAuthorizationEvidence.Result.authorized( + request, authorization(request))); + assertThatThrownBy( + () -> + GameLogicIntakeAuthorizationGrpcCodec.fromRequest( + wireRequest.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeAuthorizationGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + wireRequest.toBuilder() + .setTransportRequestId(UUID.randomUUID().toString()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeAuthorizationGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + wireRequest.toBuilder() + .setSelectedDraftBinding(ByteString.copyFromUtf8("{}")) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeAuthorizationGrpcCodec.fromResponse( + request, response.toBuilder().setOutcomeValue(99).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicIntakeAuthorizationGrpcCodec.fromRequest( + wireRequest.toBuilder() + .setSelectedDraftBinding( + ByteString.copyFrom( + new byte + [GameLogicIntakeAuthorizationEvidence.MAX_SELECTION_BYTES + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameLogicIntakeAuthorizationCredentials.Credential.of("contains whitespace")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameLogicIntakeAuthorizationEvidence.Result( + request, + GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED, + Optional.of(scope(request)), + Optional.of(authorization(request)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsResponsesOverTheExplicitTwentyFourMiBWireBudget() { + var request = request(); + var response = + GameLogicIntakeAuthorizationGrpcCodec.toResponse( + GameLogicIntakeAuthorizationEvidence.Result.authorized( + request, authorization(request))); + var oversized = + response.toBuilder() + .setRequest( + GameLogicIntakeAuthorizationGrpcCodec.toRequest(request).toBuilder() + .setSelectedDraftBinding( + ByteString.copyFrom( + new byte[GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES])) + .build()) + .build(); + assertThatThrownBy(() -> GameLogicIntakeAuthorizationGrpcCodec.fromResponse(request, oversized)) + .isInstanceOf(IllegalArgumentException.class); + } + + static GameLogicIntakeAuthorizationEvidence.Request request() { + return GameLogicIntakeAuthorizationEvidence.Request.create( + "test", UUID.randomUUID(), selected()); + } + + static DraftCommitBinding selected() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + static GameLogicIntakeAuthorizationBinding authorization( + GameLogicIntakeAuthorizationEvidence.Request request) { + return authorization(scope(request)); + } + + static GameLogicIntakeAuthorizationBinding authorization(GameLogicIntakeSourceReadScope scope) { + var selected = scope.selected(); + UUID actor = scope.actorAccountId(); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + java.util.Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + return new GameLogicIntakeAuthorizationBinding( + scope.operationId(), + scope.fenceId(), + scope.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + + static GameLogicIntakeSourceReadScope scope( + GameLogicIntakeAuthorizationEvidence.Request request) { + return new GameLogicIntakeSourceReadScope( + request.targetNamespace(), + UUID.randomUUID(), + UUID.randomUUID(), + request.intakeRequestId(), + UUID.randomUUID(), + request.selected(), + "spiffe://firemud/ns/" + request.targetNamespace() + "/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + } + + private static boolean containsSequence(byte[] bytes, byte[] sequence) { + for (int start = 0; start <= bytes.length - sequence.length; start++) { + int index = 0; + while (index < sequence.length && bytes[start + index] == sequence[index]) index++; + if (index == sequence.length) return true; + } + return false; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java index e4ba06f0ed..f19cda58ae 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java @@ -505,14 +505,14 @@ private static List requests() { new GameplayRuleSourceReadEvidence.Finalized(auth))); } - private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} - private record TestPki( + record TestPki( X509Certificate caCertificate, TestIdentity gameLogicServer, TestIdentity wrongServer, TestIdentity accountClient) { - private static TestPki create(Path directory) throws Exception { + static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("terminal-test-ca.p12"); runKeytool( "-genkeypair", @@ -560,7 +560,7 @@ private static TestPki create(Path directory) throws Exception { issueIdentity(directory, caStore, caFile, "account-client", GD_URI, false)); } - private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) throws Exception { Path certificate = writePem( @@ -584,7 +584,7 @@ private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity return properties; } - private static TestIdentity issueIdentity( + static TestIdentity issueIdentity( Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) throws Exception { Path store = directory.resolve(alias + ".p12"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java new file mode 100644 index 0000000000..979b73fabf --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java @@ -0,0 +1,464 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Definition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import org.junit.jupiter.api.Test; + +class GameplayAbilitySchemaProjectionTest { + private static final String EMPTY_FAMILIES = + "\"ABILITIES\":[],\"ACTIONS\":[],\"ADMISSION_TAGS\":[],\"COMMANDS\":[],\"CONDITIONS\":[]," + + "\"CONTINUOUS_OVERLAYS\":[],\"DEFAULT_BINDINGS\":[],\"DISPOSITIONS\":[],\"EFFECTS\":[]," + + "\"FEEDBACK\":[],\"OBSERVATION_POLICIES\":[],\"RESOURCES\":[],\"SELECTION_POLICIES\":[]," + + "\"STATS\":[],\"TARGETING_POLICIES\":[]"; + private static final String EMPTY_VECTOR = + "{\"families\":{" + EMPTY_FAMILIES + "},\"schema\":\"gameplay-ability-schema/v1\"}"; + private static final String ROOT_VECTOR = + "{\"families\":{\"ABILITIES\":[{\"abilityId\":\"ability_a\",\"actionSequenceId\":\"action_a\",\"name\":\"A\"}]," + + "\"ACTIONS\":[{\"actionSequenceId\":\"action_a\",\"admissionTags\":[],\"cooldowns\":[],\"costs\":[]," + + "\"effects\":[],\"feedbackKeys\":[],\"name\":\"A\",\"targetSets\":[]}," + + "{\"actionSequenceId\":\"action_b\",\"admissionTags\":[],\"cooldowns\":[],\"costs\":[]," + + "\"effects\":[],\"feedbackKeys\":[],\"name\":\"B\",\"targetSets\":[]}]," + + EMPTY_FAMILIES.substring(EMPTY_FAMILIES.indexOf("\"ADMISSION_TAGS\"")) + + "},\"schema\":\"gameplay-ability-schema/v1\"}"; + + @Test + void frozenEmptyVectorIsDomainSeparatedAndDoesNotEstablishSourceAuthentication() { + var source = GameplayRuleManifest.explicitEmpty(); + assertThat(GameplayAbilitySchemaProjection.canonicalJson(source)).isEqualTo(EMPTY_VECTOR); + assertThat(GameplayAbilitySchemaProjection.digest(source)) + .isEqualTo("sha256:0207783645e944996b4f7589d2662d5b8309231769681e162ee05de51d34db2a"); + assertThat(GameplayAbilitySchemaProjection.digest(source)).isNotEqualTo(source.digest()); + // Content projection intentionally cannot manufacture a source operation or authenticated + // receipt. + assertThat(GameplayRuleManifest.tree(EMPTY_VECTOR).propertyNames()) + .containsExactly("families", "schema"); + assertThatThrownBy(() -> GameplayAbilitySchemaProjection.canonicalBytes(null)) + .isInstanceOf(NullPointerException.class); + } + + @Test + void frozenRootsVectorIncludesEveryActionEvenWithoutAnAbilityReference() { + var source = roots(); + assertThat(GameplayAbilitySchemaProjection.canonicalJson(source)).isEqualTo(ROOT_VECTOR); + assertThat(GameplayAbilitySchemaProjection.canonicalBytes(source)) + .isEqualTo(ROOT_VECTOR.getBytes(StandardCharsets.UTF_8)); + assertThat(GameplayAbilitySchemaProjection.digest(source)) + .isEqualTo("sha256:659a321a8fd1a02a4825a81568d67dee5039a1cb538756fb91c212aeaea1c536"); + } + + @Test + void allAbilityRootsAndOriginalFamilyOrderAffectTheProjection() { + var values = copy(roots()); + values + .get(Family.ABILITIES) + .add(new GameplayRuleManifest.Ability("ability_b", "B", "action_b")); + var both = new GameplayRuleManifest(values); + var reversed = copy(both); + java.util.Collections.reverse(reversed.get(Family.ABILITIES)); + assertThat(GameplayAbilitySchemaProjection.digest(both)) + .isNotEqualTo(GameplayAbilitySchemaProjection.digest(roots())); + assertThat(GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(reversed))) + .isNotEqualTo(GameplayAbilitySchemaProjection.digest(both)); + var actions = copy(both); + java.util.Collections.reverse(actions.get(Family.ACTIONS)); + assertThat(GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(actions))) + .isNotEqualTo(GameplayAbilitySchemaProjection.digest(both)); + } + + @Test + void followsTypedTransitivePredicateCostTargetEffectAndFeedbackEdgesIncludingCycles() { + var source = rich(); + var json = + GameplayRuleManifest.tree(GameplayAbilitySchemaProjection.canonicalJson(source)) + .path("families"); + for (Family family : + List.of( + Family.ABILITIES, + Family.ACTIONS, + Family.ADMISSION_TAGS, + Family.CONDITIONS, + Family.DISPOSITIONS, + Family.FEEDBACK, + Family.OBSERVATION_POLICIES, + Family.RESOURCES, + Family.SELECTION_POLICIES, + Family.STATS, + Family.TARGETING_POLICIES)) + assertThat(json.path(family.name()).size()).as(family.name()).isEqualTo(1); + assertThat(json.path("EFFECTS").size()).isEqualTo(2); + for (Family family : + List.of(Family.COMMANDS, Family.CONTINUOUS_OVERLAYS, Family.DEFAULT_BINDINGS)) + assertThat(json.path(family.name()).size()).as(family.name()).isZero(); + assertThat(json.path("EFFECTS").get(0).path("effectKey").textValue()).isEqualTo("drain"); + assertThat(json.path("EFFECTS").get(1).path("effectKey").textValue()).isEqualTo("mark_effect"); + assertThat(json.path("CONDITIONS").get(0).path("effectKeys").get(1).textValue()) + .isEqualTo("mark_effect"); + } + + @Test + void retainsCompleteTransitiveFieldsAndNestedArrayOrdering() { + var source = rich(); + var changed = copy(source); + var resource = (GameplayRuleManifest.Resource) changed.get(Family.RESOURCES).getFirst(); + changed + .get(Family.RESOURCES) + .set( + 0, + new GameplayRuleManifest.Resource( + resource.statKey(), + resource.defaultCurrent(), + resource.minimum(), + resource.defaultMaximum(), + resource.hardMaximum(), + resource.visibility(), + List.of("changed"))); + assertThat(GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(changed))) + .isNotEqualTo(GameplayAbilitySchemaProjection.digest(source)); + var reordered = copy(source); + var condition = (GameplayRuleManifest.Condition) reordered.get(Family.CONDITIONS).getFirst(); + reordered + .get(Family.CONDITIONS) + .set( + 0, + new GameplayRuleManifest.Condition( + condition.conditionKey(), + condition.reapplication(), + condition.durationPolicy(), + condition.durationTicks(), + condition.maximumStacks(), + condition.visibility(), + condition.tags(), + List.of("mark_effect", "drain"), + condition.removalPriority())); + assertThat(GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(reordered))) + .isNotEqualTo(GameplayAbilitySchemaProjection.digest(source)); + } + + @Test + void excludesUnreferencedCatalogAndCommandEditsButNotFromAggregate() { + var source = rich(); + var changed = copy(source); + changed + .get(Family.STATS) + .add( + new GameplayRuleManifest.Stat( + "unrelated", + GameplayRuleManifest.PrimitiveKind.NUMERIC, + BigDecimal.ONE, + null, + null, + null, + GameplayRuleManifest.Visibility.PUBLIC, + List.of())); + var command = (GameplayRuleManifest.Command) changed.get(Family.COMMANDS).getFirst(); + changed + .get(Family.COMMANDS) + .set( + 0, + new GameplayRuleManifest.Command( + command.commandId(), + command.actionSequenceId(), + command.semanticOwner(), + command.executionDiscipline(), + command.stageRequirement(), + command.promptPolicy(), + command.actionCategory(), + command.historyRecordable(), + List.of("different_alias"), + command.actionTags(), + command.admissionTags())); + var other = new GameplayRuleManifest(changed); + assertThat(GameplayAbilitySchemaProjection.digest(other)) + .isEqualTo(GameplayAbilitySchemaProjection.digest(source)); + assertThat(other.digest()).isNotEqualTo(source.digest()); + } + + @Test + void rejectsIncompleteUnsupportedAndUnresolvedInputsEvenOutsideClosure() { + var missing = copy(roots()); + missing.remove(Family.DEFAULT_BINDINGS); + assertThatThrownBy( + () -> GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(missing))) + .isInstanceOf(IllegalArgumentException.class); + var unresolved = copy(roots()); + unresolved + .get(Family.COMMANDS) + .add( + new GameplayRuleManifest.Command( + "unrelated", + "missing", + "GAME_LOGIC", + GameplayRuleManifest.ExecutionDiscipline.DURABLE_GAMEPLAY, + GameplayRuleManifest.Stage.GAMEPLAY, + GameplayRuleManifest.PromptPolicy.NEVER, + GameplayRuleManifest.ActionCategory.GAMEPLAY, + true, + List.of(), + List.of(), + List.of())); + assertThatThrownBy( + () -> GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(unresolved))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.fromStored( + roots() + .canonicalJson() + .replace("\"families\":", "\"unknown\":0,\"families\":"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.fromStored( + roots().canonicalJson().replace("gameplay-rule-manifest/v1", "unsupported/v1"))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void numericEffectAndComparatorEdgesResolveTheirExactDeclaredFamily() { + var values = copy(rich()); + var original = (GameplayRuleManifest.Condition) values.get(Family.CONDITIONS).getFirst(); + values + .get(Family.CONDITIONS) + .set( + 0, + new GameplayRuleManifest.Condition( + original.conditionKey(), + original.reapplication(), + original.durationPolicy(), + original.durationTicks(), + original.maximumStacks(), + original.visibility(), + original.tags(), + List.of("drain", "mark_effect", "boost", "capacity"), + original.removalPriority())); + values + .get(Family.EFFECTS) + .add( + new GameplayRuleManifest.Effect( + "capacity", + GameplayRuleManifest.Lifecycle.CONTINUOUS, + GameplayRuleManifest.EffectOperation.ADD, + "mana", + GameplayRuleManifest.StatField.MAXIMUM, + BigDecimal.ONE, + null, + GameplayRuleManifest.CapacityChangePolicy.CLAMP_ONLY)); + var json = + GameplayRuleManifest.tree( + GameplayAbilitySchemaProjection.canonicalJson(new GameplayRuleManifest(values))) + .path("families"); + assertThat(json.path("EFFECTS").size()).isEqualTo(4); + assertThat(json.path("STATS").get(0).path("statKey").textValue()).isEqualTo("power"); + assertThat(json.path("RESOURCES").get(0).path("statKey").textValue()).isEqualTo("mana"); + values + .get(Family.SELECTION_POLICIES) + .set( + 0, + new GameplayRuleManifest.SelectionPolicy( + "select", + GameplayRuleManifest.Cardinality.EXACTLY_ONE, + null, + null, + GameplayRuleManifest.SelectionStrategy.RANKED, + null, + List.of( + new GameplayRuleManifest.RankComparator( + "power", + GameplayRuleManifest.StatField.VALUE, + GameplayRuleManifest.Direction.ASCENDING)))); + var statComparison = new GameplayRuleManifest(values); + assertThat( + GameplayRuleManifest.tree(GameplayAbilitySchemaProjection.canonicalJson(statComparison)) + .path("families") + .path("SELECTION_POLICIES") + .get(0) + .path("comparators") + .get(0) + .path("statKey") + .textValue()) + .isEqualTo("power"); + } + + private static GameplayRuleManifest roots() { + return manifest( + new GameplayRuleManifest.Ability("ability_a", "A", "action_a"), + action("action_a", "A"), + action("action_b", "B")); + } + + private static GameplayRuleManifest.Action action(String id, String name) { + return new GameplayRuleManifest.Action( + id, name, List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + } + + private static GameplayRuleManifest rich() { + var target = + new GameplayRuleManifest.TargetSet("victim", "target", "select", false, "fb", null); + var truth = + new GameplayRuleManifest.Predicate( + GameplayRuleManifest.PredicateKind.TRUE, null, null, null, null, List.of()); + return manifest( + new GameplayRuleManifest.Ability("ability", "Ability", "act"), + new GameplayRuleManifest.Action( + "act", + "Action", + List.of("combat"), + List.of(target), + List.of( + new GameplayRuleManifest.Cost( + "mana", BigDecimal.ONE, GameplayRuleManifest.CommitPolicy.ON_EXECUTION)), + List.of( + new GameplayRuleManifest.Cooldown( + "cooldown", 3, GameplayRuleManifest.CommitPolicy.ON_EXECUTION)), + List.of(new GameplayRuleManifest.EffectBinding("mark_effect", "SOURCE")), + List.of("fb")), + new GameplayRuleManifest.Stat( + "power", + GameplayRuleManifest.PrimitiveKind.NUMERIC, + BigDecimal.ONE, + null, + null, + null, + GameplayRuleManifest.Visibility.PUBLIC, + List.of()), + new GameplayRuleManifest.Resource( + "mana", + BigDecimal.ONE, + BigDecimal.ZERO, + BigDecimal.TEN, + BigDecimal.TEN, + GameplayRuleManifest.Visibility.PUBLIC, + List.of()), + new GameplayRuleManifest.Condition( + "mark", + GameplayRuleManifest.Reapplication.REPLACE, + GameplayRuleManifest.DurationPolicy.RESET, + 2L, + null, + GameplayRuleManifest.Visibility.PUBLIC, + List.of(), + List.of("drain", "mark_effect"), + 1), + new GameplayRuleManifest.Effect( + "drain", + GameplayRuleManifest.Lifecycle.INSTANT, + GameplayRuleManifest.EffectOperation.ADJUST_RESOURCE, + "mana", + null, + BigDecimal.ONE.negate(), + null, + null), + new GameplayRuleManifest.Effect( + "mark_effect", + GameplayRuleManifest.Lifecycle.INSTANT, + GameplayRuleManifest.EffectOperation.APPLY_CONDITION, + null, + null, + null, + "mark", + null), + new GameplayRuleManifest.Effect( + "boost", + GameplayRuleManifest.Lifecycle.CONTINUOUS, + GameplayRuleManifest.EffectOperation.ADD, + "power", + GameplayRuleManifest.StatField.VALUE, + BigDecimal.ONE, + null, + null), + new GameplayRuleManifest.AdmissionTag("combat"), + new GameplayRuleManifest.Disposition("hostile", List.of("combat"), "fb"), + new GameplayRuleManifest.ObservationPolicy( + "observe", + new GameplayRuleManifest.Predicate( + GameplayRuleManifest.PredicateKind.CONDITION_PRESENT, + GameplayRuleManifest.ActorRole.TARGET, + "mark", + null, + null, + List.of())), + new GameplayRuleManifest.TargetingPolicy( + "target", + GameplayRuleManifest.CandidateSelector.DIRECT_ACTOR, + "observe", + new GameplayRuleManifest.Predicate( + GameplayRuleManifest.PredicateKind.ALL, + null, + null, + null, + null, + List.of( + new GameplayRuleManifest.Predicate( + GameplayRuleManifest.PredicateKind.STAT_COMPARE, + GameplayRuleManifest.ActorRole.TARGET, + "power", + GameplayRuleManifest.Comparison.GE, + BigDecimal.ONE, + List.of()), + new GameplayRuleManifest.Predicate( + GameplayRuleManifest.PredicateKind.DISPOSITION_EQUALS, + GameplayRuleManifest.ActorRole.TARGET, + "hostile", + null, + null, + List.of()))), + "fb"), + new GameplayRuleManifest.SelectionPolicy( + "select", + GameplayRuleManifest.Cardinality.EXACTLY_ONE, + null, + null, + GameplayRuleManifest.SelectionStrategy.RANKED, + null, + List.of( + new GameplayRuleManifest.RankComparator( + "mana", + GameplayRuleManifest.StatField.MAXIMUM, + GameplayRuleManifest.Direction.DESCENDING))), + new GameplayRuleManifest.Feedback( + "fb", + "outcome", + GameplayRuleManifest.Audience.SOURCE_ACTOR, + "message", + "Safe feedback", + List.of(), + GameplayRuleManifest.Visibility.PUBLIC, + GameplayRuleManifest.ReplayPolicy.EFFECT_IDEMPOTENT), + new GameplayRuleManifest.ContinuousOverlay( + "unrelated_overlay", truth, List.of("combat"), List.of("boost")), + new GameplayRuleManifest.DefaultBinding("unrelated_default", List.of(target)), + new GameplayRuleManifest.Command( + "unrelated_command", + "act", + "GAME_LOGIC", + GameplayRuleManifest.ExecutionDiscipline.DURABLE_GAMEPLAY, + GameplayRuleManifest.Stage.GAMEPLAY, + GameplayRuleManifest.PromptPolicy.NEVER, + GameplayRuleManifest.ActionCategory.GAMEPLAY, + true, + List.of("alias"), + List.of(), + List.of("combat"))); + } + + private static GameplayRuleManifest manifest(Definition... definitions) { + Map> families = copy(GameplayRuleManifest.explicitEmpty()); + for (Definition definition : definitions) families.get(definition.family()).add(definition); + return new GameplayRuleManifest(families); + } + + private static Map> copy(GameplayRuleManifest source) { + Map> families = new EnumMap<>(Family.class); + source.families().forEach((family, values) -> families.put(family, new ArrayList<>(values))); + return families; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java new file mode 100644 index 0000000000..ef12cebbbd --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java @@ -0,0 +1,419 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountGameLogicIntakeAuthorizationServiceGrpc; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.GameLogicIntakeAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Actual loopback mTLS and 24 MiB wire proof using synthetic authoring evidence. */ +class GrpcGameLogicIntakeAuthorizationClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String GD_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String CREDENTIAL = "unchanged.creator.credential"; + + @TempDir static Path tempDirectory; + private static GameLogicIntakeSourceReadTransportTest.TestPki pki; + private Server server; + private GrpcGameLogicIntakeAuthorizationClient client; + private final AtomicInteger calls = new AtomicInteger(); + private final AtomicReference callerPeer = new AtomicReference<>(); + private final AtomicReference observedCredential = new AtomicReference<>(); + private final AtomicReference observedMethod = new AtomicReference<>(); + private volatile GameLogicIntakeAuthorizationResponse authorizeResponseOverride; + private volatile boolean stall; + + @BeforeAll + static void certificates() throws Exception { + pki = GameLogicIntakeSourceReadTransportTest.TestPki.create(tempDirectory); + } + + @AfterEach + void closeTransport() throws Exception { + TransactionSynchronizationManager.clear(); + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void callsAuthorizeRecoverAndAbortWithExactPeerAndProtectedCredential() throws Exception { + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + var request = request(selected(1)); + var authorized = client.authorize(request, CREDENTIAL); + assertThat(authorized.outcome()) + .isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED); + assertThat(authorized.authorization().orElseThrow().intakeRequestId()) + .isEqualTo(request.intakeRequestId()); + var recovered = client.recover(request, CREDENTIAL); + assertThat(recovered.outcome()) + .isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED); + var aborted = client.abort(request, CREDENTIAL); + assertThat(aborted.outcome()).isEqualTo(GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED); + assertThat(calls).hasValue(3); + assertThat(callerPeer).hasValue(GD_URI); + assertThat(observedCredential).hasValue(CREDENTIAL); + assertThat(observedMethod.get()).contains("AbortIntake"); + } + + @Test + void pinsAccountServerAndRejectsWrongServerAndWrongAuthenticatedCaller() throws Exception { + start(pki.wrongServer()); + client = newClient(pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.authorize(request(selected(1)), CREDENTIAL)) + .isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(0); + closeTransport(); + + start(pki.gameLogicServer()); + var wrongClient = + GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + tempDirectory, + tempDirectory.resolve("terminal-test-ca.p12"), + tempDirectory.resolve("terminal-test-ca.crt"), + "wrong-game-design-client", + ACCOUNT_URI, + false); + client = newClient(wrongClient); + client.init(); + assertThatThrownBy(() -> client.authorize(request(selected(1)), CREDENTIAL)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(calls).hasValue(0); + } + + @Test + void rejectsWrongNamespaceAmbientSqlAndUnavailableDeadline() throws Exception { + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + var original = request(selected(1)); + var wrongNamespace = + new GameLogicIntakeAuthorizationEvidence.Request( + 1, "other", UUID.randomUUID(), UUID.randomUUID(), selected(1).canonicalBytes()); + assertThatThrownBy(() -> client.authorize(wrongNamespace, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.authorize(original, CREDENTIAL)) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + assertThat(calls).hasValue(0); + closeTransport(); + + stall = true; + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.authorize(original, CREDENTIAL)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + + @Test + void refusesPlaintextAndClasspathOrMissingTlsMaterial() { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, + new CommonGrpcClientProperties(), + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + var classpathMaterial = new CommonGrpcClientProperties(); + classpathMaterial.setCertChain("classpath:account.crt"); + classpathMaterial.setPrivateKey("classpath:account.key"); + classpathMaterial.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, classpathMaterial, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void sendsLargeSelectedAuthorizationEchoWithinTwentyFourMiBInsteadOfDefaultLimit() + throws Exception { + var largeRequest = request(selected(2_200_000)); + var response = response(largeRequest, "AuthorizeIntake"); + assertThat(response.getSerializedSize()).isGreaterThan(4 * 1024 * 1024); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES); + authorizeResponseOverride = response; + start(pki.gameLogicServer()); + client = newClient(pki.accountClient()); + client.init(); + var actual = client.authorize(largeRequest, CREDENTIAL); + assertThat(actual.authorization().orElseThrow().canonicalBytes()) + .containsExactly( + GameLogicIntakeAuthorizationGrpcCodec.fromResponse(largeRequest, response) + .authorization() + .orElseThrow() + .canonicalBytes()); + } + + private void start(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) + throws Exception { + var service = + new AccountGameLogicIntakeAuthorizationServiceGrpc + .AccountGameLogicIntakeAuthorizationServiceImplBase() { + @Override + public void authorizeIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + respond(request, observer, "AuthorizeIntake"); + } + + @Override + public void recoverIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + respond(request, observer, "RecoverIntake"); + } + + @Override + public void abortIntake( + GameLogicIntakeAuthorizationRequest request, + StreamObserver observer) { + respond(request, observer, "AbortIntake"); + } + + private void respond( + GameLogicIntakeAuthorizationRequest wire, + StreamObserver observer, + String method) { + calls.incrementAndGet(); + observedMethod.set(method); + callerPeer.set(GrpcPeerIdentity.current().uri()); + observedCredential.set( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get().value()); + assertThat(Context.current().getDeadline()).isNotNull(); + if (stall) return; + var request = GameLogicIntakeAuthorizationGrpcCodec.fromRequest(wire); + var override = "AuthorizeIntake".equals(method) ? authorizeResponseOverride : null; + if (override != null) { + assertThat(override.getRequest()).isEqualTo(wire); + observer.onNext(override); + } else { + observer.onNext(response(request, method)); + } + observer.onCompleted(); + } + }; + var credentialInterceptor = + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + Metadata headers, + io.grpc.ServerCallHandler next) { + if (!GD_URI.equals(GrpcPeerIdentity.current().uri())) { + call.close(Status.PERMISSION_DENIED, new Metadata()); + return new io.grpc.ServerCall.Listener<>() {}; + } + try { + var credential = + AccountGameLogicIntakeAuthorizationCredentials.readAuthenticated( + headers, call.getMethodDescriptor().getFullMethodName()); + return io.grpc.Contexts.interceptCall( + Context.current() + .withValue( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY, credential), + call, + headers, + next); + } catch (IllegalArgumentException malformed) { + call.close(Status.UNAUTHENTICATED, new Metadata()); + return new io.grpc.ServerCall.Listener<>() {}; + } + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(GameLogicIntakeAuthorizationGrpcCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, credentialInterceptor, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcGameLogicIntakeAuthorizationClient newClient( + GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new GrpcGameLogicIntakeAuthorizationClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static GameLogicIntakeAuthorizationEvidence.Request request(DraftCommitBinding selected) { + return GameLogicIntakeAuthorizationEvidence.Request.create( + NAMESPACE, UUID.randomUUID(), selected); + } + + private static GameLogicIntakeAuthorizationResponse response( + GameLogicIntakeAuthorizationEvidence.Request request, String method) { + return GameLogicIntakeAuthorizationGrpcCodec.toResponse(result(request, method)); + } + + private static GameLogicIntakeAuthorizationEvidence.Result result( + GameLogicIntakeAuthorizationEvidence.Request request, String method) { + if ("AuthorizeIntake".equals(method)) + return GameLogicIntakeAuthorizationEvidence.Result.authorized( + request, authorization(request)); + var scope = scope(request); + return new GameLogicIntakeAuthorizationEvidence.Result( + request, + "AbortIntake".equals(method) + ? GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED + : GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED, + java.util.Optional.of(scope), + java.util.Optional.empty()); + } + + private static GameLogicIntakeAuthorizationBinding authorization( + GameLogicIntakeAuthorizationEvidence.Request request) { + UUID actor = UUID.randomUUID(); + var selected = request.selected(); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + java.util.Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + UUID.randomUUID().toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + request.intakeRequestId(), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + } + + private static GameLogicIntakeSourceReadScope scope( + GameLogicIntakeAuthorizationEvidence.Request request) { + return new GameLogicIntakeSourceReadScope( + request.targetNamespace(), + UUID.randomUUID(), + UUID.randomUUID(), + request.intakeRequestId(), + UUID.randomUUID(), + request.selected(), + "spiffe://firemud/ns/" + request.targetNamespace() + "/sa/account-service", + GameLogicIntakeSourceReadScope.PURPOSE); + } + + private static DraftCommitBinding selected(int payloadSize) { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "x".repeat(payloadSize))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } +} From 84219d26cb5c7109d984bf9b7f0491ad35638417 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 19:38:31 +1300 Subject: [PATCH 045/129] Bind publication reads to exact retained Game Logic source --- .../game-design-service/version-control.md | 2 + .../game-logic-service/runtime-and-data.md | 8 +- ...ame-authoring-publishing-and-activation.md | 4 + protos/game-logic/v1/game_logic_service.proto | 10 + ...GameLogicPublicationSourceReadBinding.java | 247 +++++++++++ ...meLogicPublicationSourceReadGrpcCodec.java | 358 +++++++++++++++ ...LogicPublicationSourceReadBindingTest.java | 327 ++++++++++++++ ...gicPublicationSourceReadGrpcCodecTest.java | 411 ++++++++++++++++++ .../gamedesign/client/GameLogicClient.java | 181 ++++++-- ...tedDraftGameLogicIntakeCommandService.java | 178 ++++++++ ...lectedDraftGameLogicReceiptRepository.java | 73 ++++ .../service/PublishGateService.java | 7 + .../service/impl/PublishGateServiceImpl.java | 100 ++++- .../VersionPublishCommandServiceImpl.java | 30 +- ...meLogicReceiptPostgresIntegrationTest.java | 106 +++++ .../publication/GameLogicClientTest.java | 298 +++++++++++++ ...raftGameLogicIntakeCommandServiceTest.java | 318 ++++++++++++++ .../impl/PublishGateServiceImplTest.java | 161 ++++++- .../VersionPublishCommandServiceImplTest.java | 93 ++++ .../GameLogicDraftDesignDigestService.java | 13 +- ...GameLogicDraftDesignDigestServiceImpl.java | 30 +- .../service/impl/GameLogicGrpcService.java | 56 +-- ...GameLogicPublicationSourceReadService.java | 236 ++++++++++ ...playRuleIntakePostgresIntegrationTest.java | 176 ++++++++ ...LogicDraftDesignDigestServiceImplTest.java | 30 +- .../impl/GameLogicGrpcServiceTest.java | 256 +++++++++-- ...LogicPublicationSourceReadServiceTest.java | 375 ++++++++++++++++ 27 files changed, 3938 insertions(+), 146 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBinding.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java create mode 100644 services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java create mode 100644 services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadServiceTest.java diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index a53d234542..b9385e5810 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -140,6 +140,8 @@ Game Logic's retained selected-release manifest and source-operation provenance The authored gameplay configuration binds exact Game Design-owned input identities and revisions. It excludes Game Logic's final receipt, a final-commit digest, and any complete Draft commit binding derived from that same commit, so canonicalizing the authored request does not depend on its own result. After the original Game Design source operation settles and Game Logic's distinct intake authorization and immutable retention succeed, the full-version publication gate must join the genuine Game Logic evidence for the exact unchanged `(tenantId, versionId, commitId)`. That derived join and retained receipt are outside the authored request preimage. A changed authored input or selected commit, a missing receipt, or evidence for a different/latest commit fails closed; an exact retry returns the original retained result and cannot substitute another commit. The owner-defined receipt and intake fields remain governed by the [Game Logic Draft Digest Contract](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake), not duplicated here. Game Design consumes the distinct [dedicated ability-schema projection](../game-logic-service/runtime-and-data.md#dedicated-ability-schema-projection-v1) with the same exact commit and participant schema/canonicalization evidence; it neither recomputes a different closure nor substitutes the aggregate digest. Current construction, incomplete publication wiring and executed proof are recorded in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); standalone receipt retention does not make this publication boundary live. +For the Game Logic full-version read, Game Design derives the separate [exact retained-source selection binding](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) only from its immutable selected receipt. The unchanged publication request retains its canonical tenant UUID and actual numeric Game Design Version row; private tenant keys are not aliases for either. Game Design verifies the complete returned lookup and genuine terminal/source/commit evidence before consuming the aggregate and dedicated ability-schema digests. Missing receipt or binding cannot fall back to a tenant/version-only read. The Game Logic owner defines the frame and provenance contract; this local consequence does not authorize a new intake or make Game Logic a script-patch participant. + #### Launch and attestation read authorization (target state) Launch and release-attestation reads are owner-to-owner control-plane APIs, not a generic internal-service read class. Each RPC must have an explicit authenticated workload allowlist and bind the caller's authorized tenant/scope to the request before reading data; a bearer that merely declares `isInternalService` is insufficient. The target launch/read allowlist is: `ResolveLaunchDescriptor` — Game Session only; `GetTemplateReferencePhase` — Game Session for launch preflight and the explicitly named Game Design/retirement-control-plane workload for cutover tooling; `GetPublishedReleaseBundle` — Game Session, World Management, and Automation & Scripting; `GetVersionState` and `GetVersionAssetArtifactState` — Game Session and World Management for launch/activation reads. `GetVersionAssetArtifactState` also has a separate operator-diagnostic use: Logging & Admin may broker an authenticated read for operators, and CI/runbook automation may use only a dedicated named operator-read workload identity (or the Logging & Admin operator surface), never a generic internal-service bearer. That operator path is diagnostic evidence and does not grant launch or mutation authority. Each request must exact-bind its tenant and version/template/request scope (including source/target versions where present), and the owner must reject a wrong workload, cross-tenant scope, omitted scope, or changed replay identity before returning a descriptor, attestation, lifecycle state, or artifact state. Focused proof must exercise every allowlisted caller and a denied internal workload plus cross-tenant requests for each RPC, including the separate operator-read path where it is implemented. diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index dcdad5e278..9258dd63e4 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -38,7 +38,7 @@ Role classification: Game Logic is a digest-gate participant for full publishes, ## Draft Digest Contract -For full-version publish gating, this service is still a required digest participant even though it does not orchestrate publish-workflow steps. It must expose `GetDraftDesignDigest(tenantId, versionId)` and publish a service-local digest input manifest with: +For full-version publish gating, this service is still a required digest participant even though it does not orchestrate publish-workflow steps. Its authenticated `GetDraftDesignDigest` read binds the publication request and exact retained selection described below, rather than selecting content by tenant and version alone, and publishes a service-local digest input manifest with: - included objects and source ownership for the complete effective, version-scoped set of supported command inputs that affect runtime command behavior; - excluded objects such as runtime queues, caches, telemetry tables, and other non-launchability data; @@ -55,6 +55,12 @@ The retained input set must be complete for the supported command inputs effecti Intake is a separate, mutation-authorized source operation. `GetDraftDesignDigest` remains a read-only full-version publication read over the already retained, exact-version evidence; it does not populate or repair that evidence. An empty selected input set is attestable only when an authenticated source operation proves the complete owner inventory for the exact selected commit is empty. Missing storage, a missing producer, or absent rows are not evidence of an empty authored set. +The content-selection binding is distinct from the unchanged `publicationDigestRequest/v1` authorization/replay context. Its `game-logic-publication-source-read/v1` preimage consists of exactly three unsigned canonical ASCII byte-length frames, in order: the UTF-8 schema name, the exact existing publication request canonical preimage, and the complete original finalized Account Game Logic intake authorization bytes retained by Game Design's immutable selected receipt. Lengths use canonical decimal digits followed by `:` and exactly that many bytes; missing, extra, trailing or noncanonical frames deny. Segment and total limits, including framing and transport overhead, must be enforced before allocation. Hash the exact bytes using the existing SHA-256 representation and freeze executable preimage/hash vectors. This binding selects content; it creates no read or mutation authority and does not reinterpret the shared publication schema. + +Game Design derives that binding only from its immutable selected receipt, never from caller-selected historical authorization or latest state. Game Logic authenticates the exact Game Design workload and publication method before decoding, independently validates both bindings, then reads the exact genuine retained intake operation and its successful terminal. The complete authorization, canonical tenant/version, selected commit and source must agree byte-for-byte with retained owner evidence. Authorization bytes and digest alone prove neither Account issuance nor successful retention. The numeric Game Design Version row in the unchanged publication scope must agree with the original selected binding's persisted target; retain its canonical UUID and source-row provenance rather than inventing a UUID/numeric alias. + +The response binds the complete original lookup, source and commit provenance, positive participant schema/canonicalization evidence, aggregate digest and dedicated ability-schema digest. Game Design exact-checks each before recording an attestation. Missing or mismatched retained evidence denies; there is no tenant/version-only or latest fallback, read-side repair, fresh mutation reauthorization of historical intake, or reuse of the Account-only terminal-read permission for Game Design. Game Logic is not a script-patch participant. This selection plumbing does not establish complete source/settlement or final release-attestation proof; current construction and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + The original Game Design author operation settles before this intake. Game Logic obtains the complete synchronized source from Game Design's authenticated exact-commit owner read and verifies a distinct [Account intake authorization](../account-service/api-contracts.md#grpc-apis) for that same immutable source. That exact finalized authorization also accompanies its [operation-authorized source read](../game-design-service/api-contracts.md#operation-authorized-gameplay-source-read); Game Logic cannot reuse Account's preliminary read-only branch or omit independent Account readback. It does not retrospectively join the original Draft's participant vector or allocate another selected commit. Account source participation remains held through Game Logic's local commit and exact terminal settlement; a remote `HELD` sample alone is insufficient. Retained source, complete manifest/provenance and the immutable intake result commit atomically. A definitive abort uses the same operation serialization and prevents later retention; missing rows or expired waits do not prove abort. Identical recovery returns the original result, never a latest source or replacement manifest. These obligations do not make Game Logic a publication-workflow mutation participant. The standalone [`RetainGameplayRuleIntake`](../../../../protos/game-logic/v1/gameplay_rule_intake_service.proto) transport admits only verified same-namespace Game Design, authenticated before decoding. It invokes the existing distinct-order intake, not publication authorization. Exact namespace, independent transport correlation and complete original authorization bytes/digest are echoed with the immutable original terminal; both retained and definitive-abort retries preserve their original outcome. The client verifies Game Logic's workload and exact response binding. Game Design obtains the subsequent settlement receipt through the [Account-owned settlement transport](../account-service/api-contracts.md#grpc-apis), never by calling the Account-only terminal reader. These transports remain unregistered; their existence does not establish a fresh authorization producer or publication completion. 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 f481bb0382..5d0a09e5db 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The exact retained-source publication composition passes three-module gate R213: 947 unit cases execute without failures or skips (385 Common, 447 Game Design, 115 Game Logic), plus five non-PostgreSQL Game Logic integrations. All 130 PostgreSQL definitions compile but skip without Docker (126 Game Design and four Game Logic). Affected full checks, formatting, static analysis, coverage, two boot JARs, links and Markdown pass; unchanged outputs are reused. The separate selection binding preserves `publicationDigestRequest/v1`, bounds its three exact byte-length frames, and freezes a literal preimage digest. The receiver requires the actual retained Game Logic terminal and derives both aggregate and dedicated ability-schema evidence; its default deployment remains denied until explicit provider composition and activation proof. Game Design's strict receipt-bound consumer, exact immutable receipt lookup and canonical selected publish-gate are connected. Missing receipt evidence leaves publication pending; conflicts deny, and no tenant/version-only fallback returns a positive digest. The unregistered intake command invokes the real configured Account producer before Game Logic retention and Account settlement; its unit tests use mocks, not genuine cross-owner provenance. R206/R207 corrected binding fixture, decoder-boundary, constructor and formatting defects; R210 corrected two ambiguous fixture argument reads, and R211/R212 isolated the gate's constructor-finalizer safety issue before R213. Genuine authored-source-to-receipt physical proof, complete release/settlement and runtime activation remain open. + +Published `9bc14c9c2e376ca66c5fed7257116750a35ab806` [Validation run 37890757405](https://github.com/benhook1013/FireMUD/actions/runs/37890757405) executed 252 Account PostgreSQL cases with one admission-confirmation WAL-coverage denial and zero skips. The corrected intake environment-change and canonical post-abort cases passed. Game Design's 126 and World's 206 PostgreSQL cases passed with zero skips; Game Logic's job passed without accessible exact integration counts. Dev Tool Contract Checks separately failed the dev-demo waiter's expected missing-namespace-head diagnostic. Both failures are under focused adjudication; neither passing storage suites nor conservative denial establishes final handoff, deployment or activation proof. + The callable but unregistered Account intake producer and dedicated ability-schema projection pass consolidated gate R204: 2,569 unit cases (374 Common, 1,109 Account, 425 Game Design, 105 Game Logic and 556 World), plus 12 non-PostgreSQL integration cases. All 569 PostgreSQL definitions compile but skip locally without Docker. Five-module full checks, formatting, static analysis, coverage, four boot JARs, links and Markdown pass; unchanged outputs are reused. The projection's eight cases freeze content-only preimages and digests, complete typed closure, ordering and unsupported-input denial. The new producer transport exercises actual mutual TLS and a response exceeding 4 MiB using synthetic source evidence. Account captures trusted environment authority again after the remote Game Design read, while exact finalized recovery precedes capture. The corrected PostgreSQL regression and canonical post-abort source mutation still require corrected-head physical execution. Earlier R202 and R203 failures were corrected test metadata/interceptor/byte-sequence and randomly regenerated response fixtures; no production authentication guard was weakened. Selected-receipt publication composition, genuine authoring provenance and all four Gameplay handoffs remain open. Published `5bd869a20cb0b2f6f6315be17a2c06b069999822` [Validation run 37882677931](https://github.com/benhook1013/FireMUD/actions/runs/37882677931) executed 252 Account PostgreSQL cases with zero skips and two failures. One reveals stale environment evidence reused across the remote Game Design source read; the other bypasses the canonical Account security writer in the post-abort fixture. The prepared correction recaptures trusted environment evidence before finalization and uses the canonical writer without weakening its event guard. Corrected-head execution remains required. Game Design's 126 and World's 206 PostgreSQL cases passed with zero skips, including the previously corrected branding and inventory fixtures. Game Logic tasks passed without accessible exact integration counts. The Account WAL case did not fail in this run, but that does not establish the separately required deterministic target-COMMIT durability mechanism. The actual merge tree was `a0b6b9bfd8dbc4e79611d4480192b94d7038a56a`, with parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head; intended-parent alignment and all four genuine Gameplay handoffs remain open. diff --git a/protos/game-logic/v1/game_logic_service.proto b/protos/game-logic/v1/game_logic_service.proto index 78c2086459..f5d05f6725 100644 --- a/protos/game-logic/v1/game_logic_service.proto +++ b/protos/game-logic/v1/game_logic_service.proto @@ -259,6 +259,9 @@ message GetDraftDesignDigestRequest { string publish_request_id = 5; string derived_workflow_identity = 6; string request_digest = 7; + // Separate content-selection binding; does not change publicationDigestRequest/v1. + bytes source_read_binding = 8; + string source_read_binding_digest = 9; } message GetDraftDesignDigestResponse { @@ -274,4 +277,11 @@ message GetDraftDesignDigestResponse { string script_patch_version = 8; } string base_version_id = 9; + bytes source_read_binding = 10; + string source_read_binding_digest = 11; + // Exact genuine RETAINED owner evidence, not caller-supplied authorization alone. + bytes retained_intake_terminal = 12; + string retained_intake_terminal_digest = 13; + string ability_schema_digest = 14; + string canonicalization = 15; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBinding.java new file mode 100644 index 0000000000..6e0277554f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBinding.java @@ -0,0 +1,247 @@ +package net.firedevops.firemud.common.gamelogic; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; + +/** + * Exact bounded binding between a full-version publication read and its GL intake authorization. + * + *

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

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

{@link #MAX_WIRE_BYTES} bounds the serialized protobuf message itself. It does not include any + * transport envelope or future protocol framing. + */ +public final class GameLogicPublicationSourceReadGrpcCodec { + /** Maximum serialized size of this protobuf request or response. */ + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + /** Maximum source binding bytes, including its canonical frame overhead. */ + public static final int MAX_BINDING_BYTES = GameLogicPublicationSourceReadBinding.MAX_TOTAL_BYTES; + + /** Maximum canonical original retained-terminal bytes. */ + public static final int MAX_TERMINAL_BYTES = + GameLogicGameplayRuleIntakeTerminal.MAX_CANONICAL_BYTES; + + public static final int DIGEST_SCHEMA_VERSION = 1; + public static final String CANONICALIZATION = "RFC8785"; + + private GameLogicPublicationSourceReadGrpcCodec() {} + + /** Encodes a request for this binding's exact full-version publication selection. */ + public static GetDraftDesignDigestRequest toRequest( + GameLogicPublicationSourceReadBinding binding) { + Objects.requireNonNull(binding, "binding"); + requireFullVersion(binding); + byte[] bindingBytes = binding.canonicalBytes(); + requireBindingSize(bindingBytes.length); + PublicationDigestRequestBinding publication = binding.publicationRequest(); + int expectedWireSize = + stringFieldSize(1, publication.tenantId()) + + stringFieldSize(2, publication.versionId()) + + stringFieldSize(5, publication.publishRequestId()) + + stringFieldSize(6, publication.derivedWorkflowIdentity()) + + stringFieldSize(7, publication.requestDigest()) + + bytesFieldSize(8, bindingBytes.length) + + stringFieldSize(9, binding.digest()); + requireWireSize(expectedWireSize); + + GetDraftDesignDigestRequest request = + GetDraftDesignDigestRequest.newBuilder() + .setTenantId(publication.tenantId()) + .setVersionId(publication.versionId()) + .setBaseVersionId(publication.baseVersionId()) + .setPublishRequestId(publication.publishRequestId()) + .setDerivedWorkflowIdentity(publication.derivedWorkflowIdentity()) + .setRequestDigest(publication.requestDigest()) + .setSourceReadBinding(ByteString.copyFrom(bindingBytes)) + .setSourceReadBindingDigest(binding.digest()) + .build(); + requireWireSize(request.getSerializedSize()); + return request; + } + + /** Validates the unchanged publication request fields and reconstructs the exact binding. */ + public static GameLogicPublicationSourceReadBinding fromRequest( + GetDraftDesignDigestRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize(request.getSerializedSize()); + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Unknown publication digest request fields"); + } + requireBindingSize(request.getSourceReadBinding().size()); + if (request.getScopeCase() != GetDraftDesignDigestRequest.ScopeCase.VERSION_ID + || !request.getBaseVersionId().isEmpty()) { + throw new IllegalArgumentException("Only full-version publication reads are supported"); + } + + PublicationDigestRequestBinding publication = + PublicationDigestRequestBinding.forScope( + PublicationDigestRequestBinding.ScopeKind.FULL_VERSION, + request.getTenantId(), + request.getVersionId(), + request.getBaseVersionId(), + "", + request.getPublishRequestId()); + publication.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest()); + GameLogicPublicationSourceReadBinding binding = + GameLogicPublicationSourceReadBinding.fromStored( + publication, request.getSourceReadBinding().toByteArray()); + if (!binding.digest().equals(request.getSourceReadBindingDigest())) { + throw new IllegalArgumentException("Changed publication source-read binding digest"); + } + return binding; + } + + /** + * Encodes an owner-readback terminal. The caller must supply the genuine terminal returned by its + * Game Logic owner read; this codec verifies its retained content correlation but cannot + * establish storage provenance by inspecting a value. + */ + public static GetDraftDesignDigestResponse toResponse( + GameLogicPublicationSourceReadBinding binding, + GameLogicGameplayRuleIntakeTerminal genuineTerminal) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(genuineTerminal, "genuineTerminal"); + requireFullVersion(binding); + requireExactRetainedTerminal(binding, genuineTerminal, null); + + byte[] bindingBytes = binding.canonicalBytes(); + byte[] terminalBytes = genuineTerminal.canonicalBytes(); + requireBindingSize(bindingBytes.length); + requireTerminalSize(terminalBytes.length); + GameLogicIntakeAuthorizationBinding authorization = binding.authorization(); + byte[] manifestBytes = genuineTerminal.manifestBytes(); + String manifestDigest = GameplayRuleManifest.sha256(manifestBytes); + String abilitySchemaDigest = + GameplayAbilitySchemaProjection.digest(authorization.source().manifest()); + String tenantId = binding.publicationRequest().tenantId(); + String versionId = binding.publicationRequest().versionId(); + String commitId = authorization.source().binding().commitId().toString(); + String terminalDigest = genuineTerminal.digest(); + + int expectedWireSize = + stringFieldSize(1, tenantId) + + stringFieldSize(3, commitId) + + stringFieldSize(4, manifestDigest) + + CodedOutputStream.computeInt32Size(5, DIGEST_SCHEMA_VERSION) + + stringFieldSize(7, versionId) + + bytesFieldSize(10, bindingBytes.length) + + stringFieldSize(11, binding.digest()) + + bytesFieldSize(12, terminalBytes.length) + + stringFieldSize(13, terminalDigest) + + stringFieldSize(14, abilitySchemaDigest) + + stringFieldSize(15, CANONICALIZATION); + requireWireSize(expectedWireSize); + + GetDraftDesignDigestResponse response = + GetDraftDesignDigestResponse.newBuilder() + .setTenantId(tenantId) + .setAppliedCommitId(commitId) + .setContentDigest(manifestDigest) + .setDigestSchemaVersion(DIGEST_SCHEMA_VERSION) + .setVersionId(versionId) + .setBaseVersionId("") + .setSourceReadBinding(ByteString.copyFrom(bindingBytes)) + .setSourceReadBindingDigest(binding.digest()) + .setRetainedIntakeTerminal(ByteString.copyFrom(terminalBytes)) + .setRetainedIntakeTerminalDigest(terminalDigest) + .setAbilitySchemaDigest(abilitySchemaDigest) + .setCanonicalization(CANONICALIZATION) + .build(); + requireWireSize(response.getSerializedSize()); + return response; + } + + /** + * Decodes exact selection and retained-content evidence without authenticating its producer. For + * an authenticated caller namespace check, use the three-argument overload. + */ + public static Evidence fromResponse( + GameLogicPublicationSourceReadBinding expectedBinding, + GetDraftDesignDigestResponse response) { + return decodeResponse(expectedBinding, response, null); + } + + /** Decodes the response while also enforcing the caller's configured GL namespace. */ + public static Evidence fromResponse( + GameLogicPublicationSourceReadBinding expectedBinding, + GetDraftDesignDigestResponse response, + String expectedNamespace) { + Objects.requireNonNull(expectedNamespace, "expectedNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(expectedNamespace)) { + throw new IllegalArgumentException("Canonical expected Game Logic namespace required"); + } + return decodeResponse(expectedBinding, response, expectedNamespace); + } + + private static Evidence decodeResponse( + GameLogicPublicationSourceReadBinding expectedBinding, + GetDraftDesignDigestResponse response, + String expectedNamespace) { + Objects.requireNonNull(expectedBinding, "expectedBinding"); + Objects.requireNonNull(response, "response"); + requireFullVersion(expectedBinding); + requireWireSize(response.getSerializedSize()); + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Unknown publication digest response fields"); + } + rejectNonemptyError(response); + requireBindingSize(response.getSourceReadBinding().size()); + requireTerminalSize(response.getRetainedIntakeTerminal().size()); + requireResponseScope(expectedBinding, response); + requireExactBindingEcho(expectedBinding, response); + + GameLogicGameplayRuleIntakeTerminal terminal = + GameLogicGameplayRuleIntakeTerminal.fromStored( + response.getRetainedIntakeTerminal().toByteArray()); + requireExactRetainedTerminal(expectedBinding, terminal, expectedNamespace); + String terminalDigest = terminal.digest(); + if (!terminalDigest.equals(response.getRetainedIntakeTerminalDigest())) { + throw new IllegalArgumentException("Changed retained intake terminal digest"); + } + + byte[] manifestBytes = terminal.manifestBytes(); + String manifestDigest = GameplayRuleManifest.sha256(manifestBytes); + String abilitySchemaDigest = + GameplayAbilitySchemaProjection.digest(expectedBinding.authorization().source().manifest()); + if (!manifestDigest.equals(response.getContentDigest()) + || !abilitySchemaDigest.equals(response.getAbilitySchemaDigest()) + || response.getDigestSchemaVersion() != DIGEST_SCHEMA_VERSION + || !CANONICALIZATION.equals(response.getCanonicalization())) { + throw new IllegalArgumentException("Changed retained publication digest evidence"); + } + + return new Evidence( + expectedBinding, + terminal, + manifestDigest, + abilitySchemaDigest, + DIGEST_SCHEMA_VERSION, + CANONICALIZATION); + } + + private static void requireResponseScope( + GameLogicPublicationSourceReadBinding binding, GetDraftDesignDigestResponse response) { + PublicationDigestRequestBinding publication = binding.publicationRequest(); + GameLogicIntakeAuthorizationBinding authorization = binding.authorization(); + String selectedVersionRowId = + Long.toString(authorization.source().binding().target().gameDesignVersionRowId()); + if (response.getScopeCase() != GetDraftDesignDigestResponse.ScopeCase.VERSION_ID + || !response.getBaseVersionId().isEmpty() + || !publication.tenantId().equals(response.getTenantId()) + || !authorization.tenantId().toString().equals(response.getTenantId()) + || !publication.versionId().equals(response.getVersionId()) + || !selectedVersionRowId.equals(response.getVersionId()) + || !authorization + .source() + .binding() + .commitId() + .toString() + .equals(response.getAppliedCommitId())) { + throw new IllegalArgumentException("Changed typed publication source scope"); + } + } + + private static void requireExactBindingEcho( + GameLogicPublicationSourceReadBinding binding, GetDraftDesignDigestResponse response) { + if (!binding.digest().equals(response.getSourceReadBindingDigest())) { + throw new IllegalArgumentException("Changed publication source-read binding digest"); + } + byte[] expectedBytes = binding.canonicalBytes(); + byte[] suppliedBytes = response.getSourceReadBinding().toByteArray(); + if (!Arrays.equals(expectedBytes, suppliedBytes)) { + throw new IllegalArgumentException("Substituted publication source-read binding"); + } + } + + private static void requireExactRetainedTerminal( + GameLogicPublicationSourceReadBinding binding, + GameLogicGameplayRuleIntakeTerminal terminal, + String expectedNamespace) { + GameLogicIntakeAuthorizationBinding authorization = binding.authorization(); + if (terminal.outcome() != GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED + || !Arrays.equals(authorization.canonicalBytes(), terminal.authorizationBytes()) + || !Arrays.equals( + authorization.canonicalBytes(), terminal.operation().authorization().canonicalBytes()) + || !Arrays.equals( + authorization.source().canonicalBytes(), terminal.selectedSourceBytes())) { + throw new IllegalArgumentException( + "Terminal is not the exact retained source for this publication binding"); + } + if (expectedNamespace != null + && !expectedNamespace.equals(terminal.operation().targetNamespace())) { + throw new IllegalArgumentException("Retained terminal namespace differs from caller scope"); + } + } + + private static void requireFullVersion(GameLogicPublicationSourceReadBinding binding) { + if (binding.publicationRequest().scopeKind() + != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw new IllegalArgumentException("Only full-version publication reads are supported"); + } + } + + private static void rejectNonemptyError(GetDraftDesignDigestResponse response) { + if (!response.hasError()) return; + var error = response.getError(); + if (!error.getUnknownFields().asMap().isEmpty() + || !error.getCode().isEmpty() + || !error.getMessage().isEmpty()) { + throw new IllegalArgumentException("Publication digest response carries an error"); + } + } + + private static int stringFieldSize(int fieldNumber, String value) { + return CodedOutputStream.computeStringSize(fieldNumber, value); + } + + private static int bytesFieldSize(int fieldNumber, int length) { + return CodedOutputStream.computeTagSize(fieldNumber) + + CodedOutputStream.computeUInt32SizeNoTag(length) + + length; + } + + private static void requireBindingSize(int length) { + if (length <= 0 || length > MAX_BINDING_BYTES) { + throw new IllegalArgumentException("Invalid publication source-read binding size"); + } + } + + private static void requireTerminalSize(int length) { + if (length <= 0 || length > MAX_TERMINAL_BYTES) { + throw new IllegalArgumentException("Invalid retained intake terminal size"); + } + } + + private static void requireWireSize(int size) { + if (size < 0 || size > MAX_WIRE_BYTES) { + throw new IllegalArgumentException("Publication digest protobuf exceeds 24 MiB"); + } + } + + /** Closed immutable value containing exact retained-source and derived digest evidence. */ + public record Evidence( + GameLogicPublicationSourceReadBinding binding, + GameLogicGameplayRuleIntakeTerminal terminal, + String manifestDigest, + String abilitySchemaDigest, + int digestSchemaVersion, + String canonicalization) { + public Evidence { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(terminal, "terminal"); + Objects.requireNonNull(manifestDigest, "manifestDigest"); + Objects.requireNonNull(abilitySchemaDigest, "abilitySchemaDigest"); + Objects.requireNonNull(canonicalization, "canonicalization"); + requireFullVersion(binding); + requireExactRetainedTerminal(binding, terminal, null); + if (digestSchemaVersion != DIGEST_SCHEMA_VERSION + || !CANONICALIZATION.equals(canonicalization) + || !GameplayRuleManifest.sha256(terminal.manifestBytes()).equals(manifestDigest) + || !GameplayAbilitySchemaProjection.digest(binding.authorization().source().manifest()) + .equals(abilitySchemaDigest)) { + throw new IllegalArgumentException("Invalid retained publication digest evidence"); + } + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java new file mode 100644 index 0000000000..4863d947d4 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java @@ -0,0 +1,327 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.junit.jupiter.api.Test; + +class GameLogicPublicationSourceReadBindingTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID ACTOR = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID FENCE = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID INTAKE_REQUEST = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID COMMIT = uuid("77777777-7777-4777-8777-777777777777"); + private static final String EXPECTED_PUBLICATION_PREIMAGE_HEX = + "32373a7075626c69636174696f6e446967657374526571756573742f7631383a74656e616e74496433363a" + + "31313131313131312d313131312d343131312d383131312d313131313131313131313131393a73636f7065" + + "4b696e6431323a46554c4c5f56455253494f4e393a76657273696f6e4964323a343131333a626173655665" + + "7273696f6e4964303a31383a736372697074506174636856657273696f6e303a31363a7075626c69736852" + + "657175657374496432313a7075626c69636174696f6e2d726571756573742d3132333a6465726976656457" + + "6f726b666c6f774964656e7469747938323a7075626c6973683a31313131313131312d313131312d343131" + + "312d383131312d3131313131313131313131313a7075626c6973682d726571756573743a7075626c696361" + + "74696f6e2d726571756573742d31"; + private static final String EXPECTED_PREIMAGE_SHA256 = + "sha256:01107d5d37c8c9f721efc6cc0e530fbaeda1526d3889b2f00875249723d24c92"; + private static final String EXPECTED_AUTHORIZATION_SHA256 = + "sha256:808aaeb1127a83093afa0c025b5701fd3826f7e46f80512ab89aa89fc736db47"; + + @Test + void freezesExactThreeFramePreimageAndRoundTripsTheRetainedAuthorization() throws Exception { + var publicationRequest = publicationRequest(TENANT.toString(), "41"); + var authorization = authorization(OPERATION, FENCE, COMMIT, TENANT, 41); + var binding = new GameLogicPublicationSourceReadBinding(publicationRequest, authorization); + var fromAuthorizationBytes = + new GameLogicPublicationSourceReadBinding( + publicationRequest, authorization.canonicalBytes()); + byte[] publicationBytes = publicationRequest.canonicalPreimage(); + byte[] authorizationBytes = authorization.canonicalBytes(); + + assertThat(publicationBytes).hasSize(315); + assertThat(HexFormat.of().formatHex(publicationBytes)) + .isEqualTo(EXPECTED_PUBLICATION_PREIMAGE_HEX); + assertThat(authorizationBytes).hasSize(1946); + assertThat(authorization.digest()).isEqualTo(EXPECTED_AUTHORIZATION_SHA256); + byte[] authorizationPrefix = + HexFormat.of() + .parseHex( + "0000002a6163636f756e742d67616d652d6c6f6769632d696e74616b652d617574686f72697a6174696f6e2f7631"); + byte[] authorizationSuffix = + HexFormat.of() + .parseHex( + "0000000750524553454e540000000131000000013100000006414253454e5400000003010203"); + assertThat(java.util.Arrays.copyOf(authorizationBytes, authorizationPrefix.length)) + .containsExactly(authorizationPrefix); + assertThat( + java.util.Arrays.copyOfRange( + authorizationBytes, + authorizationBytes.length - authorizationSuffix.length, + authorizationBytes.length)) + .containsExactly(authorizationSuffix); + + byte[] expectedPreimage = + concat( + asciiFrame(GameLogicPublicationSourceReadBinding.SCHEMA), + asciiFrame(publicationBytes), + asciiFrame(authorizationBytes)); + assertThat(expectedPreimage).hasSize(2310); + assertThat(new String(expectedPreimage, 0, 40, StandardCharsets.US_ASCII)) + .isEqualTo("37:game-logic-publication-source-read/v1"); + assertThat(new String(expectedPreimage, 40, 4, StandardCharsets.US_ASCII)).isEqualTo("315:"); + assertThat(new String(expectedPreimage, 359, 5, StandardCharsets.US_ASCII)).isEqualTo("1946:"); + assertThat(binding.canonicalBytes()).containsExactly(expectedPreimage); + assertThat(sha256(expectedPreimage)).isEqualTo(EXPECTED_PREIMAGE_SHA256); + assertThat(binding.digest()).isEqualTo(EXPECTED_PREIMAGE_SHA256); + assertThat(fromAuthorizationBytes.canonicalBytes()).containsExactly(expectedPreimage); + + var decoded = + GameLogicPublicationSourceReadBinding.fromStored(publicationRequest, expectedPreimage); + assertThat(decoded.publicationRequest()).isSameAs(publicationRequest); + assertThat(decoded.authorization().canonicalBytes()) + .containsExactly(authorization.canonicalBytes()); + assertThat(decoded.canonicalBytes()).containsExactly(expectedPreimage); + assertThat(decoded.digest()).isEqualTo(binding.digest()); + byte[] returnedBytes = binding.canonicalBytes(); + returnedBytes[0] ^= 1; + assertThat(binding.canonicalBytes()).containsExactly(expectedPreimage); + } + + @Test + void rejectsMismatchedTenantVersionAndScriptPatchScope() { + var authorization = authorization(OPERATION, FENCE, COMMIT, TENANT, 41); + assertThatThrownBy( + () -> + new GameLogicPublicationSourceReadBinding( + publicationRequest("88888888-8888-4888-8888-888888888888", "41"), + authorization)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameLogicPublicationSourceReadBinding( + publicationRequest(TENANT.toString(), "42"), authorization)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding.patch( + TENANT.toString(), "41", "patch-1", "pub-1"), + authorization)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void bindsOperationFenceAndSelectedCommitBytesWithoutTreatingThemAsAuthority() { + var publicationRequest = publicationRequest(TENANT.toString(), "41"); + var original = + new GameLogicPublicationSourceReadBinding( + publicationRequest, authorization(OPERATION, FENCE, COMMIT, TENANT, 41)); + + var differentOperation = + new GameLogicPublicationSourceReadBinding( + publicationRequest, + authorization(uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), FENCE, COMMIT, TENANT, 41)); + var differentFence = + new GameLogicPublicationSourceReadBinding( + publicationRequest, + authorization( + OPERATION, uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), COMMIT, TENANT, 41)); + var differentCommit = + new GameLogicPublicationSourceReadBinding( + publicationRequest, + authorization( + OPERATION, FENCE, uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), TENANT, 41)); + + assertThat(differentOperation.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(differentOperation.digest()).isNotEqualTo(original.digest()); + assertThat(differentFence.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(differentFence.digest()).isNotEqualTo(original.digest()); + assertThat(differentCommit.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(differentCommit.digest()).isNotEqualTo(original.digest()); + } + + @Test + void rejectsMalformedNoncanonicalTruncatedTrailingAndOversizedFrames() { + var publicationRequest = publicationRequest(TENANT.toString(), "41"); + byte[] valid = + new GameLogicPublicationSourceReadBinding( + publicationRequest, authorization(OPERATION, FENCE, COMMIT, TENANT, 41)) + .canonicalBytes(); + + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, concat(bytes("0"), valid))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, concat(bytes("+"), valid))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, java.util.Arrays.copyOf(valid, valid.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + concat( + asciiFrame(GameLogicPublicationSourceReadBinding.SCHEMA), + asciiFrame(publicationRequest.canonicalPreimage())))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, concat(valid, asciiFrame(bytes("extra"))))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + concat( + asciiFrame(GameLogicPublicationSourceReadBinding.SCHEMA), + asciiFrame(publicationRequest.canonicalPreimage()), + bytes("4194305:")))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + new byte[GameLogicPublicationSourceReadBinding.MAX_TOTAL_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + + for (UUID identity : List.of(OPERATION, FENCE, COMMIT)) { + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + replaceFirst( + valid, + bytes(identity.toString()), + bytes("x" + identity.toString().substring(1))))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static PublicationDigestRequestBinding publicationRequest(String tenant, String version) { + return PublicationDigestRequestBinding.full(tenant, version, "publication-request-1"); + } + + private static GameLogicIntakeAuthorizationBinding authorization( + UUID operation, UUID fence, UUID commit, UUID tenant, long versionRowId) { + DraftCommitBinding selected = selectedBinding(tenant, commit, versionRowId); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + java.util.Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + "99999999-9999-4999-8999-999999999999", + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var evidence = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + ACTOR.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + operation, fence, INTAKE_REQUEST, ACTOR, source, List.of(evidence)); + } + + private static DraftCommitBinding selectedBinding(UUID tenant, UUID commit, long versionRowId) { + var target = + new DraftCommitBinding.TargetProof( + tenant, VERSION, versionRowId, "private-tenant", 7, "private-tenant", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + commit, + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + VERSION.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static byte[] asciiFrame(String value) { + return asciiFrame(value.getBytes(StandardCharsets.US_ASCII)); + } + + private static byte[] asciiFrame(byte[] value) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + output.writeBytes(Integer.toString(value.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(value); + return output.toByteArray(); + } + + private static byte[] concat(byte[]... values) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + for (byte[] value : values) output.writeBytes(value); + return output.toByteArray(); + } + + private static byte[] replaceFirst(byte[] original, byte[] find, byte[] replacement) { + if (find.length != replacement.length) { + throw new IllegalArgumentException("Replacement must preserve byte length"); + } + byte[] result = original.clone(); + for (int start = 0; start <= result.length - find.length; start++) { + int index = 0; + while (index < find.length && result[start + index] == find[index]) index++; + if (index == find.length) { + System.arraycopy(replacement, 0, result, start, replacement.length); + return result; + } + } + throw new IllegalArgumentException("Expected fixture bytes were not found"); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String sha256(byte[] value) throws Exception { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java new file mode 100644 index 0000000000..462218fe8c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java @@ -0,0 +1,411 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestResponse; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +class GameLogicPublicationSourceReadGrpcCodecTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID ACTOR = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID OPERATION = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID FENCE = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID INTAKE_REQUEST = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID COMMIT = uuid("77777777-7777-4777-8777-777777777777"); + private static final String NAMESPACE = "test"; + + @Test + void roundTripsExactFullVersionRequestAndRetainedResponse() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + + GetDraftDesignDigestRequest request = + GameLogicPublicationSourceReadGrpcCodec.toRequest(fixture.binding()); + assertThat(request.getTenantId()).isEqualTo(TENANT.toString()); + assertThat(request.getVersionId()).isEqualTo("41"); + assertThat(request.getBaseVersionId()).isEmpty(); + assertThat(request.getPublishRequestId()).isEqualTo("publication-request-1"); + assertThat(request.getDerivedWorkflowIdentity()) + .isEqualTo(fixture.binding().publicationRequest().derivedWorkflowIdentity()); + assertThat(request.getRequestDigest()) + .isEqualTo(fixture.binding().publicationRequest().requestDigest()); + assertThat(request.getSourceReadBinding().toByteArray()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(request.getSourceReadBindingDigest()).isEqualTo(fixture.binding().digest()); + assertThat(GameLogicPublicationSourceReadGrpcCodec.fromRequest(request).canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + + GetDraftDesignDigestResponse response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); + var evidence = + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), response, NAMESPACE); + assertThat(evidence.binding().canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(evidence.terminal().canonicalBytes()) + .containsExactly(fixture.terminal().canonicalBytes()); + assertThat(evidence.manifestDigest()).isEqualTo(response.getContentDigest()); + assertThat(evidence.abilitySchemaDigest()).isEqualTo(response.getAbilitySchemaDigest()); + assertThat(evidence.digestSchemaVersion()).isEqualTo(1); + assertThat(evidence.canonicalization()).isEqualTo("RFC8785"); + + assertThat( + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder().setError(ErrorDetail.getDefaultInstance()).build()) + .terminal() + .canonicalBytes()) + .containsExactly(fixture.terminal().canonicalBytes()); + } + + @Test + void rejectsChangedPublicationRequestIdentityScopeAndUnknownFields() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestRequest request = + GameLogicPublicationSourceReadGrpcCodec.toRequest(fixture.binding()); + + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setDerivedWorkflowIdentity("publish:wrong").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setRequestDigest("0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setScriptPatchVersion("patch-1").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setSourceReadBindingDigest("sha256:changed").build())) + .isInstanceOf(IllegalArgumentException.class); + byte[] substituted = request.getSourceReadBinding().toByteArray(); + substituted[0] ^= 1; + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder() + .setSourceReadBinding(ByteString.copyFrom(substituted)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + GetDraftDesignDigestRequest requestWithUnknown = + request.toBuilder().setUnknownFields(unknownField()).build(); + assertThatThrownBy( + () -> GameLogicPublicationSourceReadGrpcCodec.fromRequest(requestWithUnknown)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedResponseTenantVersionCommitAndBindingCorrelation() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestResponse response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); + + for (GetDraftDesignDigestResponse changed : + List.of( + response.toBuilder().setTenantId("88888888-8888-4888-8888-888888888888").build(), + response.toBuilder().setVersionId("42").build(), + response.toBuilder().setAppliedCommitId("88888888-8888-4888-8888-888888888888").build(), + response.toBuilder().setBaseVersionId("42").build(), + response.toBuilder().setScriptPatchVersion("patch-1").build(), + response.toBuilder().setSourceReadBindingDigest("sha256:changed").build())) { + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + byte[] substitutedBinding = response.getSourceReadBinding().toByteArray(); + substitutedBinding[substitutedBinding.length - 1] ^= 1; + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setSourceReadBinding(ByteString.copyFrom(substitutedBinding)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder().setUnknownFields(unknownField()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedTerminalDigestOperationFenceCommitAndNamespace() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestResponse response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); + + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder().setRetainedIntakeTerminalDigest("sha256:changed").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), response, "other")) + .isInstanceOf(IllegalArgumentException.class); + + List substitutedBindings = + List.of( + fixture( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), FENCE, COMMIT, TENANT, 41, NAMESPACE), + fixture( + OPERATION, + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + COMMIT, + TENANT, + 41, + NAMESPACE), + fixture( + OPERATION, + FENCE, + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + TENANT, + 41, + NAMESPACE)); + for (Fixture substituted : substitutedBindings) { + GetDraftDesignDigestResponse changed = + GameLogicPublicationSourceReadGrpcCodec.toResponse( + substituted.binding(), substituted.terminal()); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + for (Fixture substitutedTerminal : substitutedBindings) { + GetDraftDesignDigestResponse changedTerminal = + response.toBuilder() + .setRetainedIntakeTerminal( + ByteString.copyFrom(substitutedTerminal.terminal().canonicalBytes())) + .setRetainedIntakeTerminalDigest(substitutedTerminal.terminal().digest()) + .build(); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), changedTerminal)) + .isInstanceOf(IllegalArgumentException.class); + } + + Fixture wrongNamespace = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, "other"); + GetDraftDesignDigestResponse wrongNamespaceResponse = + GameLogicPublicationSourceReadGrpcCodec.toResponse( + wrongNamespace.binding(), wrongNamespace.terminal()); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + wrongNamespace.binding(), wrongNamespaceResponse, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMissingAbortedMalformedOrOversizedTerminalAndNonemptyErrors() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestResponse response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); + + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), response.toBuilder().clearRetainedIntakeTerminal().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setRetainedIntakeTerminal(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setRetainedIntakeTerminal( + ByteString.copyFrom( + new byte + [GameLogicPublicationSourceReadGrpcCodec.MAX_TERMINAL_BYTES + + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setError(ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.toResponse( + fixture.binding(), + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation( + NAMESPACE, fixture.binding().authorization())))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedManifestAbilitySchemaVersionAndCanonicalization() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestResponse response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); + + for (GetDraftDesignDigestResponse changed : + List.of( + response.toBuilder().setContentDigest("sha256:changed").build(), + response.toBuilder().setAbilitySchemaDigest("sha256:changed").build(), + response.toBuilder().setDigestSchemaVersion(2).build(), + response.toBuilder().setCanonicalization("OTHER").build())) { + assertThatThrownBy( + () -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void enforcesBindingByteLimitBeforeDecodingAndRejectsOversizedWireMessages() { + Fixture fixture = fixture(OPERATION, FENCE, COMMIT, TENANT, 41, NAMESPACE); + GetDraftDesignDigestRequest oversizedBinding = + GameLogicPublicationSourceReadGrpcCodec.toRequest(fixture.binding()).toBuilder() + .setSourceReadBinding( + ByteString.copyFrom( + new byte[GameLogicPublicationSourceReadGrpcCodec.MAX_BINDING_BYTES + 1])) + .build(); + assertThatThrownBy(() -> GameLogicPublicationSourceReadGrpcCodec.fromRequest(oversizedBinding)) + .isInstanceOf(IllegalArgumentException.class); + + GetDraftDesignDigestRequest oversizedWire = + GetDraftDesignDigestRequest.newBuilder() + .setTenantId("x".repeat(GameLogicPublicationSourceReadGrpcCodec.MAX_WIRE_BYTES)) + .build(); + assertThatThrownBy(() -> GameLogicPublicationSourceReadGrpcCodec.fromRequest(oversizedWire)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Fixture fixture( + UUID operationId, + UUID fenceId, + UUID commitId, + UUID tenantId, + long versionRowId, + String namespace) { + var publication = + PublicationDigestRequestBinding.full( + tenantId.toString(), Long.toString(versionRowId), "publication-request-1"); + var authorization = authorization(operationId, fenceId, commitId, tenantId, versionRowId); + var binding = new GameLogicPublicationSourceReadBinding(publication, authorization); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(namespace, authorization), + authorization.source().canonicalBytes(), + authorization + .source() + .manifest() + .canonicalJson() + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return new Fixture(binding, terminal); + } + + private static GameLogicIntakeAuthorizationBinding authorization( + UUID operation, UUID fence, UUID commit, UUID tenant, long versionRowId) { + DraftCommitBinding selected = selectedBinding(tenant, commit, versionRowId); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + "99999999-9999-4999-8999-999999999999", + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))); + var evidence = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + ACTOR.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + operation, fence, INTAKE_REQUEST, ACTOR, source, List.of(evidence)); + } + + private static DraftCommitBinding selectedBinding(UUID tenant, UUID commit, long versionRowId) { + var target = + new DraftCommitBinding.TargetProof( + tenant, VERSION, versionRowId, "private-tenant", 7, "private-tenant", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + commit, + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + VERSION.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + GameLogicPublicationSourceReadBinding binding, + GameLogicGameplayRuleIntakeTerminal terminal) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java index 534d5011b6..974c646ce7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java @@ -1,28 +1,49 @@ package net.firedevops.firemud.gamedesign.client; +import io.grpc.ManagedChannel; import jakarta.annotation.PostConstruct; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +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.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; 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.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; import net.firedevops.firemud.gamelogic.v1.GameLogicServiceGrpc; -import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; @Component public class GameLogicClient extends AbstractReloadingBlockingGrpcClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final CommonGrpcClientProperties tlsProps; + + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + public GameLogicClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, GrpcChannelFactory channelFactory, BlockingGrpcStubCustomizer stubCustomizer) { super(endpoints, tlsProps, channelFactory, stubCustomizer, GameLogicClient.class); + this.tlsProps = tlsProps.copy(); } @PostConstruct @@ -41,57 +62,145 @@ protected String defaultTarget() { } @Override - protected GameLogicServiceGrpc.GameLogicServiceBlockingStub buildStub( - io.grpc.ManagedChannel channel) { + protected GameLogicServiceGrpc.GameLogicServiceBlockingStub buildStub(ManagedChannel channel) { return applyStubCustomizer( GameLogicServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } + /** + * Legacy publication read cannot prove the selected Account authorization and is deliberately + * closed. Full-version publication must use the immutable-receipt overload below. + */ public PublishParticipantDigestDto getDraftDesignDigestForVersion( PublicationDigestRequestBinding binding) { + Objects.requireNonNull(binding, "binding"); + String versionId = requireFullVersionId(binding); + return failure( + versionId, + "SELECTED_GAME_LOGIC_RECEIPT_REQUIRED", + "exact retained Game Logic receipt is required for a full-version publication read"); + } + + /** Reads the retained full-version digest selected by the original Account receipt. */ + public PublishParticipantDigestDto getDraftDesignDigestForVersion( + PublicationDigestRequestBinding binding, SelectedDraftGameLogicReceipt receipt) { + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(receipt, "receipt"); + String versionId = requireFullVersionId(binding); + requireOutsideSql(); + if (!receipt.selection().intent().publishRequestId().equals(binding.publishRequestId()) + || !receipt.workflowIdentity().equals(binding.derivedWorkflowIdentity())) { + throw new IllegalArgumentException( + "publication request differs from immutable selected Game Logic receipt"); + } + + // The receipt constructor enforces the Account-finalized RETAINED terminal. Use its exact + // original authorization, never IDs or bytes from an ambient/latest source lookup. + GameLogicPublicationSourceReadBinding expectedBinding = + new GameLogicPublicationSourceReadBinding(binding, receipt.authorization()); + var request = GameLogicPublicationSourceReadGrpcCodec.toRequest(expectedBinding); var response = - stub() - .getDraftDesignDigest( - GetDraftDesignDigestRequest.newBuilder() - .setTenantId(binding.tenantId()) - .setVersionId(requireFullVersionId(binding)) - .setPublishRequestId(binding.publishRequestId()) - .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) - .setRequestDigest(binding.requestDigest()) - .build()); + requirePublicationReadStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getDraftDesignDigest(request); if (response.hasError() && !response.getError().getCode().isBlank()) { - return new PublishParticipantDigestDto( - "GAME_LOGIC", - binding.versionId(), - null, - null, - null, - response.getError().getCode(), - response.getError().getMessage()); + return failure(versionId, response.getError().getCode(), response.getError().getMessage()); } - if (!binding.tenantId().equals(response.getTenantId()) - || !response.hasVersionId() - || !binding.versionId().equals(response.getVersionId()) - || !response.getBaseVersionId().isEmpty()) { - return new PublishParticipantDigestDto( - "GAME_LOGIC", - binding.versionId(), - null, - null, - null, - "RESPONSE_BINDING_MISMATCH", - "owner returned tenant or typed full-version scope that does not match request"); + + GameLogicPublicationSourceReadGrpcCodec.Evidence evidence; + try { + evidence = + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + expectedBinding, response, workloadNamespace); + } catch (IllegalArgumentException invalid) { + return failure(versionId, "RESPONSE_BINDING_MISMATCH", invalid.getMessage()); + } + if (!Arrays.equals( + receipt.receipt().terminal().canonicalBytes(), evidence.terminal().canonicalBytes())) { + return failure( + versionId, + "RESPONSE_TERMINAL_MISMATCH", + "owner terminal differs from the immutable Account-finalized receipt"); } + return new PublishParticipantDigestDto( "GAME_LOGIC", - response.getVersionId(), - response.getAppliedCommitId(), - response.getContentDigest(), - response.getDigestSchemaVersion(), + versionId, + null, + receipt.authorization().source().binding().commitId().toString(), + evidence.manifestDigest(), + evidence.digestSchemaVersion(), + evidence.abilitySchemaDigest(), null, null); } + private GameLogicServiceGrpc.GameLogicServiceBlockingStub requirePublicationReadStub() { + requireFileBackedMtls(tlsProps); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalStateException( + "Game Logic publication reads require the configured workload namespace"); + } + var current = stub(); + if (current == null) { + throw new IllegalStateException("Game Logic publication client is not initialized"); + } + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-logic-service"; + return current + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withMaxInboundMessageSize(GameLogicPublicationSourceReadGrpcCodec.MAX_WIRE_BYTES); + } + + private static void requireOutsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Game Logic publication source reads require no ambient SQL transaction"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalStateException( + "Game Logic publication source reads require file-backed 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 IllegalStateException( + "Game Logic publication source reads require file-backed TLS certificate, key, and CA"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalStateException( + "Game Logic publication source reads require file-backed TLS certificate, key, and CA"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalStateException( + "Game Logic publication source-read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalStateException( + "Game Logic publication source-read " + label + " must be an existing readable file"); + } + } + + private static PublishParticipantDigestDto failure( + String versionId, String errorCode, String errorMessage) { + return new PublishParticipantDigestDto( + "GAME_LOGIC", versionId, null, null, null, null, errorCode, errorMessage); + } + private String requireFullVersionId(PublicationDigestRequestBinding binding) { if (binding.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { throw new IllegalArgumentException("full-version binding required"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java new file mode 100644 index 0000000000..c3e90c2837 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandService.java @@ -0,0 +1,178 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered composition of the original Account intake producer and the selected-release receipt + * owner. The caller supplies the stable intake identity for both first admission and exact + * recovery; this class does not create or replace that identity. + */ +public final class SelectedDraftGameLogicIntakeCommandService { + private final SelectionReader selections; + private final GameLogicIntakeAuthorizationClient account; + private final ReceiptRetainer receipts; + private final String namespace; + + public SelectedDraftGameLogicIntakeCommandService( + DSLContext dsl, + GameLogicIntakeAuthorizationClient account, + SelectedDraftGameLogicReceiptService receipts, + String namespace) { + this( + repositoryReader(dsl), + account, + Objects.requireNonNull(receipts, "receipts")::retain, + namespace); + } + + SelectedDraftGameLogicIntakeCommandService( + SelectionReader selections, + GameLogicIntakeAuthorizationClient account, + ReceiptRetainer receipts, + String namespace) { + this.selections = Objects.requireNonNull(selections, "selections"); + this.account = Objects.requireNonNull(account, "account"); + this.receipts = Objects.requireNonNull(receipts, "receipts"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + /** Obtains a fresh finalized Account authorization, then retains its exact selected receipt. */ + public SelectedDraftGameLogicReceipt authorizeAndRetain( + AuthoredDraftPublishSelection selection, + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential) { + return produce(selection, request, originalCreatorCredential, account::authorize); + } + + /** Recovers the caller's original intake identity after an uncertain acknowledgement. */ + public SelectedDraftGameLogicReceipt recoverAndRetain( + AuthoredDraftPublishSelection selection, + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential) { + return produce(selection, request, originalCreatorCredential, account::recover); + } + + private SelectedDraftGameLogicReceipt produce( + AuthoredDraftPublishSelection selection, + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential, + AuthorizationCall call) { + requireNoTransaction(); + requireRequestMatchesSelection(selection, request); + + var retainedSelection = + selections + .read(selection) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")); + if (!Arrays.equals(selection.canonicalBytes(), retainedSelection.canonicalBytes())) + throw new IllegalStateException("Selected publication differs from immutable selection"); + + // The durable owner read above is outside the ambient caller transaction. Account's producer + // must also remain outside any ambient SQL transaction. + requireNoTransaction(); + final GameLogicIntakeAuthorizationEvidence.Result result; + try { + result = call.invoke(request, originalCreatorCredential); + } catch (RuntimeException denied) { + // The protected original credential must never be reflected by an injected client error. + throw new IllegalStateException("Account intake authorization denied or unavailable"); + } + var authorization = requireFinalized(request, result); + return receipts.retain(selection, authorization); + } + + private void requireRequestMatchesSelection( + AuthoredDraftPublishSelection selection, + GameLogicIntakeAuthorizationEvidence.Request request) { + Objects.requireNonNull(selection, "selection"); + Objects.requireNonNull(request, "request"); + if (!namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Intake authorization namespace mismatch"); + byte[] selectionBytes = selection.canonicalBytes(); + if (selectionBytes.length > SelectedDraftGameLogicReceipt.MAX_SELECTION_BYTES + || !Arrays.equals( + selection.selectedCommit().canonicalBytes(), request.selectedDraftBinding())) + throw new IllegalArgumentException("Intake request differs from selected Draft binding"); + // Re-parse the caller's selection so only the canonical immutable representation proceeds. + var canonical = + AuthoredDraftPublishSelection.fromStored(selection.canonicalJson(), selection.digest()); + if (!Arrays.equals(selectionBytes, canonical.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical selected publication"); + } + + private static GameLogicIntakeAuthorizationBinding requireFinalized( + GameLogicIntakeAuthorizationEvidence.Request request, + GameLogicIntakeAuthorizationEvidence.Result result) { + if (result == null || !sameRequest(request, result.request())) + throw new IllegalStateException("Account intake authorization request readback conflict"); + if (result.outcome() != GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED + || result.authorization().isEmpty()) + throw new IllegalStateException("Account intake authorization is not finalized"); + + var authorization = result.authorization().orElseThrow(); + if (!request.intakeRequestId().equals(authorization.intakeRequestId()) + || !Arrays.equals( + request.selectedDraftBinding(), authorization.source().binding().canonicalBytes())) + throw new IllegalStateException("Account intake authorization differs from exact request"); + return authorization; + } + + private static boolean sameRequest( + GameLogicIntakeAuthorizationEvidence.Request expected, + GameLogicIntakeAuthorizationEvidence.Request actual) { + return actual != null + && expected.schemaVersion() == actual.schemaVersion() + && expected.targetNamespace().equals(actual.targetNamespace()) + && expected.transportRequestId().equals(actual.transportRequestId()) + && expected.intakeRequestId().equals(actual.intakeRequestId()) + && Arrays.equals(expected.selectedDraftBinding(), actual.selectedDraftBinding()); + } + + private static SelectionReader repositoryReader(DSLContext dsl) { + Objects.requireNonNull(dsl, "dsl"); + return selection -> + new AuthoredDraftPublishSelectionRepository(dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + selection.intent().publishRequestId()) + .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection); + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Account intake authorization requires no ambient SQL"); + } + + @FunctionalInterface + interface SelectionReader { + Optional read(AuthoredDraftPublishSelection selection); + } + + @FunctionalInterface + interface ReceiptRetainer { + SelectedDraftGameLogicReceipt retain( + AuthoredDraftPublishSelection selection, GameLogicIntakeAuthorizationBinding authorization); + } + + @FunctionalInterface + private interface AuthorizationCall { + GameLogicIntakeAuthorizationEvidence.Result invoke( + GameLogicIntakeAuthorizationEvidence.Request request, String originalCreatorCredential); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java index 410be0489f..9aeaf52828 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptRepository.java @@ -5,8 +5,11 @@ import java.util.Arrays; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; @@ -41,6 +44,76 @@ public Optional read( return Optional.of(retained); } + /** Reads the immutable receipt selected by the exact full-version publication request. */ + public Optional readForPublication( + PublicationDigestRequestBinding publicationRequest) { + Objects.requireNonNull(publicationRequest, "publicationRequest"); + if (publicationRequest.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw new IllegalArgumentException( + "Game Logic receipt publication read requires FULL_VERSION"); + } + UUID canonicalTenantId; + try { + canonicalTenantId = UUID.fromString(publicationRequest.tenantId()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException("Publication tenant must be a canonical UUID", malformed); + } + if (!canonicalTenantId.toString().equals(publicationRequest.tenantId())) { + throw new IllegalArgumentException("Publication tenant must be a canonical UUID"); + } + + // The immutable receipt's primary key is exactly the tenant and stable request identity. + // Version and workflow are verified against the decoded selection below; they are not fallback + // lookup dimensions and no latest or numeric-to-UUID inference is permitted. + Record row = + dsl.fetchOne( + "SELECT * FROM game_design_selected_game_logic_receipt WHERE canonical_tenant_id = ? AND publish_request_id = ?", + canonicalTenantId, + publicationRequest.publishRequestId()); + if (row == null) return Optional.empty(); + + var retained = decode(row); + var selection = retained.selection(); + var target = selection.target(); + if (!Long.toString(target.gameDesignVersionRowId()).equals(publicationRequest.versionId()) + || !retained.workflowIdentity().equals(publicationRequest.derivedWorkflowIdentity())) { + throw new IllegalStateException( + "Selected Game Logic receipt does not match publication request"); + } + + // Reconstruct the distinct publication-source binding from the complete original finalized + // Account authorization retained in this immutable receipt. This validates tenant, numeric + // Version row, selected commit and source correlation without creating read authority. + new GameLogicPublicationSourceReadBinding(publicationRequest, retained.authorization()); + + if (dsl.fetchOne( + "SELECT v.id FROM version v JOIN game g " + + "ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "AND g.tenant_identity_source_game_id = g.id " + + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + + "WHERE v.id = ? AND v.tenant_id = ? AND v.canonical_tenant_id = ? " + + "AND v.canonical_version_id = ? AND v.identity_source_game_row_id = ? " + + "AND v.identity_source_game_tenant_key = ? AND v.identity_source_provenance_kind = ? " + + "AND v.identity_source_game_row_id > 0 " + + "AND v.identity_source_game_tenant_key = v.tenant_id " + + "AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') " + + "AND v.version_state_epoch > 0", + Long.parseLong(publicationRequest.versionId()), + target.gameDesignVersionTenantKey(), + canonicalTenantId, + selection.intent().canonicalVersionId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()) + == null) { + throw new IllegalStateException("Selected Game Design Version row proof unavailable"); + } + return Optional.of(retained); + } + public SelectedDraftGameLogicReceipt retain(SelectedDraftGameLogicReceipt candidate) { requireTransaction(); var selection = candidate.selection(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java index 60c070ccad..7b80b50bce 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.service; import java.util.List; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; @@ -8,6 +9,12 @@ public interface PublishGateService { List collectFullVersionParticipantDigests( VersionDto version, String publishRequestId, String publishWorkflowId); + /** Collects owner digests using the canonical binding read from the exact selected operation. */ + List collectSelectedFullVersionParticipantDigests( + VersionDto version, + PublicationDigestRequestBinding canonicalBinding, + String publishWorkflowId); + List collectScriptPatchParticipantDigests( VersionDto version, String publishRequestId, String publishWorkflowId); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java index a70eb5a7f4..5a5d554fc9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java @@ -4,7 +4,9 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; +import java.util.UUID; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; import net.firedevops.firemud.gamedesign.client.EntityManagementClient; @@ -15,13 +17,17 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import net.firedevops.firemud.gamedesign.service.PublishGateService; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service -public class PublishGateServiceImpl implements PublishGateService { +public final class PublishGateServiceImpl implements PublishGateService { private static final Map SUPPORTED_DIGEST_SCHEMA_VERSIONS = Map.of( PublishParticipantKey.WORLD_MANAGEMENT.name(), 3, @@ -47,18 +53,39 @@ public class PublishGateServiceImpl implements PublishGateService { private final EntityManagementClient entityManagementClient; private final GameLogicClient gameLogicClient; private final AutomationScriptingClient automationScriptingClient; + private final SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository; + @Autowired public PublishGateServiceImpl( ControlPlaneDigestService controlPlaneDigestService, WorldManagementClient worldManagementClient, EntityManagementClient entityManagementClient, GameLogicClient gameLogicClient, - AutomationScriptingClient automationScriptingClient) { + AutomationScriptingClient automationScriptingClient, + DSLContext dsl) { + this( + controlPlaneDigestService, + worldManagementClient, + entityManagementClient, + gameLogicClient, + automationScriptingClient, + new SelectedDraftGameLogicReceiptRepository(dsl)); + } + + PublishGateServiceImpl( + ControlPlaneDigestService controlPlaneDigestService, + WorldManagementClient worldManagementClient, + EntityManagementClient entityManagementClient, + GameLogicClient gameLogicClient, + AutomationScriptingClient automationScriptingClient, + SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository) { this.controlPlaneDigestService = controlPlaneDigestService; this.worldManagementClient = worldManagementClient; this.entityManagementClient = entityManagementClient; this.gameLogicClient = gameLogicClient; this.automationScriptingClient = automationScriptingClient; + this.selectedGameLogicReceiptRepository = + Objects.requireNonNull(selectedGameLogicReceiptRepository); } @Override @@ -69,8 +96,43 @@ public List collectFullVersionParticipantDigests( PublicationDigestRequestBinding.full( version.tenantId(), String.valueOf(version.id()), publishRequestId); requireWorkflowIdentity(binding, publishWorkflowId); + return collectFullVersionParticipantDigests(version, binding, false); + } + + @Override + public List collectSelectedFullVersionParticipantDigests( + VersionDto version, + PublicationDigestRequestBinding canonicalBinding, + String publishWorkflowId) { + Objects.requireNonNull(version, "version must not be null"); + Objects.requireNonNull(canonicalBinding, "canonicalBinding must not be null"); + if (version.scriptOnly() + || version.id() == null + || canonicalBinding.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION + || !String.valueOf(version.id()).equals(canonicalBinding.versionId())) { + throw new IllegalArgumentException( + "selected publication requires the exact full-version Game Design row binding"); + } + UUID canonicalTenant; + try { + canonicalTenant = UUID.fromString(canonicalBinding.tenantId()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "selected publication tenant must be its canonical UUID", malformed); + } + if (!canonicalTenant.toString().equals(canonicalBinding.tenantId())) { + throw new IllegalArgumentException("selected publication tenant must be its canonical UUID"); + } + requireWorkflowIdentity(canonicalBinding, publishWorkflowId); + return collectFullVersionParticipantDigests(version, canonicalBinding, true); + } + + private List collectFullVersionParticipantDigests( + VersionDto version, PublicationDigestRequestBinding binding, boolean selectedPublication) { return FULL_VERSION_PARTICIPANTS.stream() - .map(participant -> observeFullVersionParticipant(version, binding, participant)) + .map( + participant -> + observeFullVersionParticipant(version, binding, participant, selectedPublication)) .toList(); } @@ -178,11 +240,15 @@ public void assertGatePassed( private PublishParticipantDigestDto observeFullVersionParticipant( VersionDto version, PublicationDigestRequestBinding binding, - PublishParticipantKey participantKey) { + PublishParticipantKey participantKey, + boolean selectedPublication) { return switch (participantKey) { case WORLD_MANAGEMENT -> worldManagementClient.getDraftDesignDigestForVersion(binding); case ENTITY_MANAGEMENT -> entityManagementClient.getDraftDesignDigestForVersion(binding); - case GAME_LOGIC -> gameLogicClient.getDraftDesignDigestForVersion(binding); + case GAME_LOGIC -> + selectedPublication + ? observeSelectedGameLogicParticipant(binding) + : gameLogicClient.getDraftDesignDigestForVersion(binding); case AUTOMATION_SCRIPTING -> automationScriptingClient.getDraftDesignDigestForVersion(binding); case GAME_DESIGN_CONTROL_PLANE -> @@ -191,6 +257,30 @@ private PublishParticipantDigestDto observeFullVersionParticipant( }; } + private PublishParticipantDigestDto observeSelectedGameLogicParticipant( + PublicationDigestRequestBinding binding) { + Optional receipt; + try { + receipt = selectedGameLogicReceiptRepository.readForPublication(binding); + } catch (org.jooq.exception.DataAccessException unavailable) { + return failedObservation( + PublishParticipantKey.GAME_LOGIC, + binding.versionId(), + null, + "UNAVAILABLE", + "immutable selected Game Logic receipt readback is temporarily unavailable"); + } + if (receipt.isEmpty()) { + return failedObservation( + PublishParticipantKey.GAME_LOGIC, + binding.versionId(), + null, + "PARTICIPANT_UNAVAILABLE", + "immutable selected Game Logic receipt is not available yet"); + } + return gameLogicClient.getDraftDesignDigestForVersion(binding, receipt.orElseThrow()); + } + private void requireWorkflowIdentity( PublicationDigestRequestBinding binding, String suppliedWorkflowIdentity) { if (!binding.derivedWorkflowIdentity().equals(suppliedWorkflowIdentity)) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index 3750aa16a0..f8b3bb52a2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -127,7 +127,7 @@ private PublishWorkflowSnapshot reconcileFullVersionPublish( emptyIfNull(attempt.getFailureMessage())); } attempt = backfillLegacyFullVersionRequestDigest(request, attempt); - validateFullVersionAttempt(attempt, request); + PublicationDigestRequestBinding selectedBinding = validateFullVersionAttempt(attempt, request); Version version = requireAttemptVersion(attempt, request); PublicationReadback existingPublication = readPublication(request, attempt); @@ -148,8 +148,11 @@ private PublishWorkflowSnapshot reconcileFullVersionPublish( try { dto = versionMapper.toDto(version); participantDigests = - publishGateService.collectFullVersionParticipantDigests( - dto, request.publishRequestId(), request.publishWorkflowId()); + selectedBinding == null + ? publishGateService.collectFullVersionParticipantDigests( + dto, request.publishRequestId(), request.publishWorkflowId()) + : publishGateService.collectSelectedFullVersionParticipantDigests( + dto, selectedBinding, request.publishWorkflowId()); } catch (RuntimeException ex) { if (PublicationFailureClassifier.isRetryableParticipantDependencyFailure(ex)) { throw pendingReconciliation( @@ -643,11 +646,11 @@ private PublishAttempt backfillLegacyFullVersionRequestDigest( .orElse(attempt); } - private void validateFullVersionAttempt(PublishAttempt attempt, PublishWorkflowRequest request) { + private PublicationDigestRequestBinding validateFullVersionAttempt( + PublishAttempt attempt, PublishWorkflowRequest request) { validateFullVersionAttemptIdentity(attempt, request); if (isSelectionDigest(attempt.getRequestDigest())) { - requireExactSelectedPublication(attempt, request); - return; + return requireExactSelectedPublication(attempt, request); } PublicationDigestRequestBinding binding = PublicationDigestRequestBinding.full( @@ -656,6 +659,7 @@ private void validateFullVersionAttempt(PublishAttempt attempt, PublishWorkflowR throw new IllegalStateException( "PUBLISH_ATTEMPT_IDENTITY_CONFLICT: full-version request digest does not match request"); } + return null; } /** @@ -684,7 +688,7 @@ private void validateTerminalFullVersionAttempt( } } - private void requireExactSelectedPublication( + private PublicationDigestRequestBinding requireExactSelectedPublication( PublishAttempt attempt, PublishWorkflowRequest request) { try { String expectedOutcome = @@ -697,21 +701,21 @@ private void requireExactSelectedPublication( publishAttemptRepository.requireSelectedPublicationReadback(attempt, expectedOutcome); var selection = operation.account().input().selection(); var intent = selection.intent(); - String expectedWorkflowId = + PublicationDigestRequestBinding canonicalBinding = PublicationDigestRequestBinding.full( - intent.canonicalTenantId().toString(), - Long.toString(operation.versionId()), - intent.publishRequestId()) - .derivedWorkflowIdentity(); + intent.canonicalTenantId().toString(), + Long.toString(operation.versionId()), + intent.publishRequestId()); if (!Objects.equals(operation.tenantKey(), request.tenantId()) || operation.versionId() != attempt.getVersionId() || !Objects.equals(operation.selectionDigest(), attempt.getRequestDigest()) - || !Objects.equals(operation.workflowId(), expectedWorkflowId) + || !Objects.equals(operation.workflowId(), canonicalBinding.derivedWorkflowIdentity()) || !Objects.equals(operation.workflowId(), request.publishWorkflowId()) || !Objects.equals(intent.publishRequestId(), request.publishRequestId()) || !Objects.equals(intent.notes(), request.notes())) { throw new IllegalStateException("SELECTED_PUBLICATION_REQUEST_IDENTITY_CHANGED"); } + return canonicalBinding; } catch (PendingReconciliationException unresolved) { throw unresolved; } catch (RuntimeException unresolved) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java index 758c0b3413..7ef9400b63 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java @@ -17,6 +17,7 @@ import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -61,6 +62,19 @@ void migrationPreservesHistoricalSelectionAndReceiptReadbackIsImmutableAndExact( .containsExactly(value.receipt().canonicalBytes()); assertThat(recovered.authorization().canonicalBytes()) .containsExactly(value.authorization().canonicalBytes()); + // Publication may advance the mutable lifecycle epoch. Exact retained content recovery uses + // the original authenticated epoch, not a new mutation authorization against current state. + dsl.execute( + "UPDATE version SET version_state_epoch = version_state_epoch + 1 WHERE id = ?", + value.selection().target().gameDesignVersionRowId()); + var publicationRead = repository.readForPublication(publicationBinding(value)); + assertThat(publicationRead).isPresent(); + assertThat(publicationRead.orElseThrow().receipt().canonicalBytes()) + .containsExactly(value.receipt().canonicalBytes()); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM game_design_selected_game_logic_receipt") + .get(0, Long.class)) + .isEqualTo(1L); assertThat( dsl.fetchSingle( "SELECT selection_json FROM game_design_authored_draft_publish_selection") @@ -94,6 +108,90 @@ void migrationPreservesHistoricalSelectionAndReceiptReadbackIsImmutableAndExact( .isInstanceOf(org.jooq.exception.DataAccessException.class); } + @Test + void publicationReadUsesExactTenantAndRequestAndRejectsChangedVersionOrPatchScope() { + var value = receiptFixture(); + var fixture = fixture(value); + var dsl = fixture.dsl(); + var repository = new SelectedDraftGameLogicReceiptRepository(dsl); + fixture.tx().executeWithoutResult(ignored -> repository.retain(value)); + + assertThat( + repository.readForPublication( + PublicationDigestRequestBinding.full( + value.selection().intent().canonicalTenantId().toString(), + Long.toString(value.selection().target().gameDesignVersionRowId()), + "different-request"))) + .isEmpty(); + assertThat( + repository.readForPublication( + PublicationDigestRequestBinding.full( + UUID.randomUUID().toString(), + Long.toString(value.selection().target().gameDesignVersionRowId()), + value.selection().intent().publishRequestId()))) + .isEmpty(); + assertThatThrownBy( + () -> + repository.readForPublication( + PublicationDigestRequestBinding.full( + value.selection().intent().canonicalTenantId().toString(), + Long.toString(value.selection().target().gameDesignVersionRowId() + 1), + value.selection().intent().publishRequestId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match publication request"); + assertThatThrownBy( + () -> + repository.readForPublication( + PublicationDigestRequestBinding.patch( + value.selection().intent().canonicalTenantId().toString(), + "1", + "patch-1", + value.selection().intent().publishRequestId()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("FULL_VERSION"); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM game_design_selected_game_logic_receipt") + .get(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void publicationReadFailsClosedWhenNumericVersionRowNoLongerMatchesSelection() { + var value = receiptFixture(); + var fixture = fixture(value); + var repository = new SelectedDraftGameLogicReceiptRepository(fixture.dsl()); + fixture.tx().executeWithoutResult(ignored -> repository.retain(value)); + fixture + .dsl() + .execute( + "UPDATE version SET canonical_version_id = ? WHERE id = ?", + UUID.randomUUID(), + value.selection().target().gameDesignVersionRowId()); + + assertThatThrownBy(() -> repository.readForPublication(publicationBinding(value))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Version row proof unavailable"); + } + + @Test + void publicationReadFailsClosedOnConflictingRetainedWorkflowField() { + var value = receiptFixture(); + var fixture = fixture(value); + var dsl = fixture.dsl(); + var repository = new SelectedDraftGameLogicReceiptRepository(dsl); + fixture.tx().executeWithoutResult(ignored -> repository.retain(value)); + // Fault injection bypasses the immutable-row trigger to model conflicting retained bytes. + dsl.execute( + "ALTER TABLE game_design_selected_game_logic_receipt DISABLE TRIGGER trg_gd_selected_game_logic_receipt"); + dsl.execute( + "UPDATE game_design_selected_game_logic_receipt SET workflow_identity = ?", + "publish:wrong-tenant:publish-request:publish-1"); + + assertThatThrownBy(() -> repository.readForPublication(publicationBinding(value))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("integrity conflict"); + } + @Test void missingReceiptIsAbsentAndChangedSelectionOrOversizedReceiptCannotInsert() { var value = receiptFixture(); @@ -322,5 +420,13 @@ private static SelectedDraftGameLogicReceipt receiptFixture() { new AccountGameLogicIntakeSettlementEvidence(terminal)); } + private static PublicationDigestRequestBinding publicationBinding( + SelectedDraftGameLogicReceipt value) { + return PublicationDigestRequestBinding.full( + value.selection().intent().canonicalTenantId().toString(), + Long.toString(value.selection().target().gameDesignVersionRowId()), + value.selection().intent().publishRequestId()); + } + private record Fixture(DSLContext dsl, TransactionTemplate tx) {} } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java new file mode 100644 index 0000000000..47a8bbf735 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java @@ -0,0 +1,298 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ClientInterceptor; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.client.GameLogicClient; +import net.firedevops.firemud.gamelogic.v1.GameLogicServiceGrpc; +import net.firedevops.firemud.gamelogic.v1.GetDraftDesignDigestRequest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameLogicClientTest { + private static final String WORKLOAD_NAMESPACE = "test"; + + @Test + void readsExactRetainedSelectionAndReturnsBothDigestProjections(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var publication = publicationBinding(receipt); + var sourceRead = + new GameLogicPublicationSourceReadBinding(publication, receipt.authorization()); + var response = + GameLogicPublicationSourceReadGrpcCodec.toResponse( + sourceRead, receipt.receipt().terminal()); + var clientAndStub = client(tlsDirectory); + var client = clientAndStub.client(); + var stub = clientAndStub.stub(); + when(stub.getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))).thenReturn(response); + + var result = client.getDraftDesignDigestForVersion(publication, receipt); + + assertThat(result.succeeded()).isTrue(); + assertThat(result.participantKey()).isEqualTo("GAME_LOGIC"); + assertThat(result.scopeValue()).isEqualTo(publication.versionId()); + assertThat(result.baseVersionId()).isNull(); + assertThat(result.appliedCommitId()) + .isEqualTo(receipt.authorization().source().binding().commitId().toString()); + assertThat(result.contentDigest()).isEqualTo(response.getContentDigest()); + assertThat(result.digestSchemaVersion()).isEqualTo(response.getDigestSchemaVersion()); + assertThat(result.abilitySchemaDigest()).isEqualTo(response.getAbilitySchemaDigest()); + + var request = org.mockito.ArgumentCaptor.forClass(GetDraftDesignDigestRequest.class); + verify(stub).getDraftDesignDigest(request.capture()); + assertThat(request.getValue().getTenantId()).isEqualTo(publication.tenantId()); + assertThat(request.getValue().getVersionId()).isEqualTo(publication.versionId()); + assertThat(request.getValue().getPublishRequestId()).isEqualTo(publication.publishRequestId()); + assertThat(request.getValue().getDerivedWorkflowIdentity()) + .isEqualTo(publication.derivedWorkflowIdentity()); + assertThat(request.getValue().getRequestDigest()).isEqualTo(publication.requestDigest()); + var decoded = GameLogicPublicationSourceReadGrpcCodec.fromRequest(request.getValue()); + assertThat(decoded.canonicalBytes()).containsExactly(sourceRead.canonicalBytes()); + assertThat(decoded.authorization().canonicalBytes()) + .containsExactly(receipt.authorization().canonicalBytes()); + verify(stub).withCallCredentials(any()); + verify(stub).withInterceptors(any(ClientInterceptor[].class)); + verify(stub).withMaxInboundMessageSize(GameLogicPublicationSourceReadGrpcCodec.MAX_WIRE_BYTES); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsAValidButDifferentTerminalFromTheImmutableReceipt(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var publication = publicationBinding(receipt); + var sourceRead = + new GameLogicPublicationSourceReadBinding(publication, receipt.authorization()); + var retained = receipt.receipt().terminal(); + var differentTerminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation("other", receipt.authorization()), + retained.selectedSourceBytes(), + retained.manifestBytes()); + assertThat(Arrays.equals(differentTerminal.canonicalBytes(), retained.canonicalBytes())) + .isFalse(); + var response = + GameLogicPublicationSourceReadGrpcCodec.toResponse(sourceRead, differentTerminal); + var clientAndStub = client(tlsDirectory); + ReflectionTestUtils.setField(clientAndStub.client(), "workloadNamespace", "other"); + when(clientAndStub.stub().getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenReturn(response); + + var result = clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt); + + assertThat(result.succeeded()).isFalse(); + assertThat(result.errorCode()).isEqualTo("RESPONSE_TERMINAL_MISMATCH"); + assertThat(result.contentDigest()).isNull(); + assertThat(result.abilitySchemaDigest()).isNull(); + } + + @Test + void missingReceiptLegacyPathFailsClosedWithoutCallingGameLogic(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var clientAndStub = client(tlsDirectory); + + var result = clientAndStub.client().getDraftDesignDigestForVersion(publicationBinding(receipt)); + + assertThat(result.succeeded()).isFalse(); + assertThat(result.errorCode()).isEqualTo("SELECTED_GAME_LOGIC_RECEIPT_REQUIRED"); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void rejectsPublicationRequestThatDoesNotMatchTheReceiptSelection(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var publication = publicationBinding(receipt); + var changedPublication = + PublicationDigestRequestBinding.full( + publication.tenantId(), + publication.versionId(), + publication.publishRequestId() + "-different"); + var clientAndStub = client(tlsDirectory); + + assertThatThrownBy( + () -> + clientAndStub.client().getDraftDesignDigestForVersion(changedPublication, receipt)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from immutable selected Game Logic receipt"); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void missingWorkloadNamespaceDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var clientAndStub = client(tlsDirectory); + ReflectionTestUtils.setField(clientAndStub.client(), "workloadNamespace", ""); + + assertThatThrownBy( + () -> + clientAndStub + .client() + .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void invalidWorkloadNamespaceDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var clientAndStub = client(tlsDirectory); + ReflectionTestUtils.setField(clientAndStub.client(), "workloadNamespace", "Not_A_Namespace"); + + assertThatThrownBy( + () -> + clientAndStub + .client() + .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void plaintextTlsConfigurationDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(true); + var clientAndStub = client(tlsDirectory, tls); + + assertThatThrownBy( + () -> + clientAndStub + .client() + .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("file-backed workload mTLS"); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void unreadableTlsMaterialDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var tls = fileBackedTls(tlsDirectory); + tls.setCaCert(tlsDirectory.resolve("missing-ca.crt").toString()); + var clientAndStub = client(tlsDirectory, tls); + + assertThatThrownBy( + () -> + clientAndStub + .client() + .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("CA certificate") + .hasMessageContaining("readable file"); + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void activeSqlTransactionDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var clientAndStub = client(tlsDirectory); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + clientAndStub + .client() + .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(clientAndStub.stub()); + } + + @Test + void activeSqlSynchronizationDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var clientAndStub = client(tlsDirectory); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy( + () -> + clientAndStub + .client() + .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL transaction"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(clientAndStub.stub()); + } + + private static PublicationDigestRequestBinding publicationBinding( + SelectedDraftGameLogicReceipt receipt) { + return PublicationDigestRequestBinding.full( + receipt.selection().intent().canonicalTenantId().toString(), + Long.toString(receipt.selection().target().gameDesignVersionRowId()), + receipt.selection().intent().publishRequestId()); + } + + private static ClientAndStub client(Path tlsDirectory) throws IOException { + return client(tlsDirectory, fileBackedTls(tlsDirectory)); + } + + private static ClientAndStub client(Path tlsDirectory, CommonGrpcClientProperties tls) { + var client = + new GameLogicClient( + new ServiceEndpointsProperties(), + tls, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop()); + ReflectionTestUtils.setField(client, "workloadNamespace", WORKLOAD_NAMESPACE); + + var stub = mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); + when(stub.withCallCredentials(any())).thenReturn(stub); + when(stub.withInterceptors(any(ClientInterceptor[].class))).thenReturn(stub); + when(stub.withMaxInboundMessageSize(GameLogicPublicationSourceReadGrpcCodec.MAX_WIRE_BYTES)) + .thenReturn(stub); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + clearInvocations(stub); + ReflectionTestUtils.setField(client, "stub", stub); + return new ClientAndStub(client, stub); + } + + private static CommonGrpcClientProperties fileBackedTls(Path tlsDirectory) throws IOException { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(write(tlsDirectory.resolve("client.crt"))); + tls.setPrivateKey(write(tlsDirectory.resolve("client.key"))); + tls.setCaCert(write(tlsDirectory.resolve("ca.crt"))); + return tls; + } + + private static String write(Path path) throws IOException { + Files.writeString(path, "test material"); + return path.toString(); + } + + private record ClientAndStub( + GameLogicClient client, GameLogicServiceGrpc.GameLogicServiceBlockingStub stub) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java new file mode 100644 index 0000000000..2ddf72cc8b --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java @@ -0,0 +1,318 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class SelectedDraftGameLogicIntakeCommandServiceTest { + private static final String CREDENTIAL = "original-creator-credential-never-persisted"; + + @Test + void verifiesImmutableSelectionThenAuthorizesAndRetainsOutsideSqlInOrder() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var request = request(value.selection()); + var authorization = authorizationFor(value, request); + var expectedReceipt = receiptFor(value.selection(), authorization); + var account = mock(GameLogicIntakeAuthorizationClient.class); + var events = new ArrayList(); + when(account.authorize(any(), anyString())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(call.getArgument(0, GameLogicIntakeAuthorizationEvidence.Request.class)) + .isSameAs(request); + assertThat(call.getArgument(1, String.class)).isEqualTo(CREDENTIAL); + events.add("account.authorize"); + return GameLogicIntakeAuthorizationEvidence.Result.authorized(request, authorization); + }); + var service = + new SelectedDraftGameLogicIntakeCommandService( + selected -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("selection.read"); + return Optional.of(value.selection()); + }, + account, + (selected, retainedAuthorization) -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(selected.canonicalBytes()) + .containsExactly(value.selection().canonicalBytes()); + assertThat(retainedAuthorization.canonicalBytes()) + .containsExactly(authorization.canonicalBytes()); + events.add("receipt.retain"); + return expectedReceipt; + }, + "test"); + + var receipt = service.authorizeAndRetain(value.selection(), request, CREDENTIAL); + + assertThat(receipt).isSameAs(expectedReceipt); + assertThat(events).containsExactly("selection.read", "account.authorize", "receipt.retain"); + verify(account, never()).recover(any(), anyString()); + } + + @Test + void rejectsMalformedRequestOrChangedDurableSelectionBeforeAccountRpc() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var account = mock(GameLogicIntakeAuthorizationClient.class); + var retainCalls = new AtomicInteger(); + var readerCalls = new AtomicInteger(); + var service = + new SelectedDraftGameLogicIntakeCommandService( + selected -> { + readerCalls.incrementAndGet(); + return Optional.of(selected); + }, + account, + (selected, authorization) -> { + retainCalls.incrementAndGet(); + return value; + }, + "test"); + + var wrongNamespace = + new GameLogicIntakeAuthorizationEvidence.Request( + 1, + "other", + UUID.randomUUID(), + UUID.randomUUID(), + value.selection().selectedCommit().canonicalBytes()); + assertThatThrownBy( + () -> service.authorizeAndRetain(value.selection(), wrongNamespace, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + var wrongSelectedBinding = request(SelectedDraftGameLogicReceiptTest.fixture().selection()); + assertThatThrownBy( + () -> service.authorizeAndRetain(value.selection(), wrongSelectedBinding, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("selected Draft binding"); + assertThat(readerCalls).hasValue(0); + + String alteredJson = + value.selection().canonicalJson().replace("\"notes\":\"\"", "\"notes\":\"changed\""); + var changedStoredSelection = + AuthoredDraftPublishSelection.fromStored( + alteredJson, + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.digest( + alteredJson.getBytes(StandardCharsets.UTF_8))); + var changedSelectionService = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(changedStoredSelection), + account, + (selected, authorization) -> { + retainCalls.incrementAndGet(); + return value; + }, + "test"); + assertThatThrownBy( + () -> + changedSelectionService.authorizeAndRetain( + value.selection(), request(value.selection()), CREDENTIAL)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("immutable selection"); + + assertThat(retainCalls).hasValue(0); + verifyNoInteractions(account); + } + + @Test + void rejectsChangedResponseTransportCorrelationBeforeReceiptRetention() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var request = request(value.selection()); + var changedResponseRequest = + new GameLogicIntakeAuthorizationEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + UUID.randomUUID(), + request.intakeRequestId(), + request.selectedDraftBinding()); + var account = mock(GameLogicIntakeAuthorizationClient.class); + when(account.authorize(any(), anyString())) + .thenReturn( + GameLogicIntakeAuthorizationEvidence.Result.authorized( + changedResponseRequest, authorizationFor(value, changedResponseRequest))); + var retainCalls = new AtomicInteger(); + var service = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(value.selection()), + account, + (selected, authorization) -> { + retainCalls.incrementAndGet(); + return value; + }, + "test"); + + assertThatThrownBy(() -> service.authorizeAndRetain(value.selection(), request, CREDENTIAL)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("request readback conflict"); + + assertThat(retainCalls).hasValue(0); + } + + @Test + void rejectsAuthorizationWhoseSourceDoesNotMatchExactRequest() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var other = SelectedDraftGameLogicReceiptTest.fixture(); + var request = request(value.selection()); + var changedAuthorization = authorizationFor(other, request); + var response = mock(GameLogicIntakeAuthorizationEvidence.Result.class); + when(response.request()).thenReturn(request); + when(response.outcome()).thenReturn(GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED); + when(response.authorization()).thenReturn(Optional.of(changedAuthorization)); + var account = mock(GameLogicIntakeAuthorizationClient.class); + when(account.recover(any(), anyString())).thenReturn(response); + var retainCalls = new AtomicInteger(); + var service = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(value.selection()), + account, + (selected, authorization) -> { + retainCalls.incrementAndGet(); + return value; + }, + "test"); + + assertThatThrownBy(() -> service.recoverAndRetain(value.selection(), request, CREDENTIAL)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from exact request"); + + assertThat(retainCalls).hasValue(0); + } + + @Test + void sanitizesProducerFailuresWithoutReflectingProtectedCredential() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var account = mock(GameLogicIntakeAuthorizationClient.class); + when(account.authorize(any(), anyString())).thenThrow(new IllegalStateException(CREDENTIAL)); + var service = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(value.selection()), + account, + (selected, authorization) -> value, + "test"); + + assertThatThrownBy( + () -> + service.authorizeAndRetain( + value.selection(), request(value.selection()), CREDENTIAL)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account intake authorization denied or unavailable") + .hasMessageNotContaining(CREDENTIAL); + } + + @Test + void reservedAndAbortedRecoveryNeverCreatesReceipt() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var request = request(value.selection()); + var account = mock(GameLogicIntakeAuthorizationClient.class); + var reserved = response(request, GameLogicIntakeAuthorizationEvidence.Outcome.RESERVED); + var aborted = response(request, GameLogicIntakeAuthorizationEvidence.Outcome.ABORTED); + when(account.recover(any(), anyString())).thenReturn(reserved, aborted); + var retainCalls = new AtomicInteger(); + var service = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(value.selection()), + account, + (selected, authorization) -> { + retainCalls.incrementAndGet(); + return value; + }, + "test"); + + for (int i = 0; i < 2; i++) { + assertThatThrownBy(() -> service.recoverAndRetain(value.selection(), request, CREDENTIAL)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not finalized"); + } + + assertThat(retainCalls).hasValue(0); + } + + @Test + void exactRecoveryUsesCallerIntakeIdentityWithoutIssuingAnotherAuthorization() { + var value = SelectedDraftGameLogicReceiptTest.fixture(); + var request = request(value.selection()); + var authorization = authorizationFor(value, request); + var expectedReceipt = receiptFor(value.selection(), authorization); + var account = mock(GameLogicIntakeAuthorizationClient.class); + when(account.recover(any(), anyString())) + .thenAnswer( + call -> { + assertThat(call.getArgument(0, GameLogicIntakeAuthorizationEvidence.Request.class)) + .isSameAs(request); + assertThat(call.getArgument(1, String.class)).isEqualTo(CREDENTIAL); + return GameLogicIntakeAuthorizationEvidence.Result.authorized(request, authorization); + }); + var service = + new SelectedDraftGameLogicIntakeCommandService( + ignored -> Optional.of(value.selection()), + account, + (selected, retainedAuthorization) -> expectedReceipt, + "test"); + + assertThat(service.recoverAndRetain(value.selection(), request, CREDENTIAL)) + .isSameAs(expectedReceipt); + assertThat(request.intakeRequestId()).isEqualTo(authorization.intakeRequestId()); + verify(account, never()).authorize(any(), anyString()); + } + + private static GameLogicIntakeAuthorizationEvidence.Result response( + GameLogicIntakeAuthorizationEvidence.Request request, + GameLogicIntakeAuthorizationEvidence.Outcome outcome) { + var result = mock(GameLogicIntakeAuthorizationEvidence.Result.class); + when(result.request()).thenReturn(request); + when(result.outcome()).thenReturn(outcome); + when(result.authorization()).thenReturn(Optional.empty()); + return result; + } + + private static GameLogicIntakeAuthorizationEvidence.Request request( + AuthoredDraftPublishSelection selection) { + return GameLogicIntakeAuthorizationEvidence.Request.create( + "test", UUID.randomUUID(), selection.selectedCommit()); + } + + private static GameLogicIntakeAuthorizationBinding authorizationFor( + SelectedDraftGameLogicReceipt fixture, GameLogicIntakeAuthorizationEvidence.Request request) { + var original = fixture.authorization(); + return new GameLogicIntakeAuthorizationBinding( + original.operationId(), + original.fenceId(), + request.intakeRequestId(), + original.actorAccountId(), + original.source(), + original.sources()); + } + + private static SelectedDraftGameLogicReceipt receiptFor( + AuthoredDraftPublishSelection selection, GameLogicIntakeAuthorizationBinding authorization) { + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation("test", authorization), + authorization.source().canonicalBytes(), + authorization.source().manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + return new SelectedDraftGameLogicReceipt( + selection, authorization, new AccountGameLogicIntakeSettlementEvidence(terminal)); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java index 31d2ff84fa..e9ee9c8665 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java @@ -5,11 +5,13 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.LocalDateTime; import java.util.List; +import java.util.Optional; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; @@ -21,7 +23,10 @@ import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; +import net.firedevops.firemud.gamedesign.service.PublicationFailureClassifier; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -37,6 +42,7 @@ class PublishGateServiceImplTest { @Mock private EntityManagementClient entityManagementClient; @Mock private GameLogicClient gameLogicClient; @Mock private AutomationScriptingClient automationScriptingClient; + @Mock private SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository; private PublishGateServiceImpl service; @@ -49,7 +55,8 @@ void setUp() { worldManagementClient, entityManagementClient, gameLogicClient, - automationScriptingClient); + automationScriptingClient, + selectedGameLogicReceiptRepository); } @Test @@ -109,6 +116,99 @@ void collectFullVersionParticipantDigestsPassesWhenParticipantsConverge() { assertBinding(captureVersionBinding(automationScriptingClient), expectedBinding); } + @Test + void selectedFullVersionGateUsesCanonicalBindingAndExactReceiptForOwnerReads() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + SelectedDraftGameLogicReceipt receipt = + org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals(5, digests.size()); + assertDoesNotThrow(() -> service.assertGatePassed(version, digests)); + assertBinding(captureVersionBinding(worldManagementClient), binding); + assertBinding(captureVersionBinding(entityManagementClient), binding); + ArgumentCaptor gameLogicBinding = + ArgumentCaptor.forClass(PublicationDigestRequestBinding.class); + verify(gameLogicClient) + .getDraftDesignDigestForVersion(gameLogicBinding.capture(), same(receipt)); + assertBinding(gameLogicBinding.getValue(), binding); + assertBinding(captureVersionBinding(automationScriptingClient), binding); + + var publicationOrder = + org.mockito.Mockito.inOrder(selectedGameLogicReceiptRepository, gameLogicClient); + publicationOrder.verify(selectedGameLogicReceiptRepository).readForPublication(binding); + publicationOrder.verify(gameLogicClient).getDraftDesignDigestForVersion(binding, receipt); + verify(gameLogicClient, org.mockito.Mockito.never()) + .getDraftDesignDigestForVersion(any(PublicationDigestRequestBinding.class)); + } + + @Test + void selectedFullVersionGateKeepsMissingReceiptPendingAndNeverUsesLegacyRead() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + when(selectedGameLogicReceiptRepository.readForPublication(binding)) + .thenReturn(Optional.empty()); + stubNonGameLogicParticipants(version, binding); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals("PARTICIPANT_UNAVAILABLE", digests.get(2).errorCode()); + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); + assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(thrown)); + verify(gameLogicClient, org.mockito.Mockito.never()) + .getDraftDesignDigestForVersion(any(PublicationDigestRequestBinding.class)); + verify(gameLogicClient, org.mockito.Mockito.never()) + .getDraftDesignDigestForVersion( + any(PublicationDigestRequestBinding.class), any(SelectedDraftGameLogicReceipt.class)); + } + + @Test + void selectedReceiptStorageInterruptionRemainsRetryable() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + when(selectedGameLogicReceiptRepository.readForPublication(binding)) + .thenThrow(new org.jooq.exception.DataAccessException("database unavailable")); + stubNonGameLogicParticipants(version, binding); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals("UNAVAILABLE", digests.get(2).errorCode()); + PublishGateFailureException thrown = + assertThrows( + PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); + assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(thrown)); + } + + @Test + void selectedFullVersionGateRejectsPrivateTenantKeyAsPublicationIdentity() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding privateTenantBinding = + PublicationDigestRequestBinding.full("private-tenant-key", "7", "selected-request-1"); + + assertThrows( + IllegalArgumentException.class, + () -> + service.collectSelectedFullVersionParticipantDigests( + version, privateTenantBinding, privateTenantBinding.derivedWorkflowIdentity())); + org.mockito.Mockito.verifyNoInteractions( + worldManagementClient, + entityManagementClient, + gameLogicClient, + automationScriptingClient, + selectedGameLogicReceiptRepository); + } + @Test void fullVersionGateRejectsUnavailableGameLogicManifest() { VersionDto version = @@ -464,6 +564,65 @@ void scriptPatchGatePassesWhenParticipantsConverge() { PublicationDigestRequestBinding.patch("tenant-1", "7", "patch-1", "publish-request-1")); } + private void stubSelectedParticipantDigests( + VersionDto version, + PublicationDigestRequestBinding binding, + SelectedDraftGameLogicReceipt receipt) { + stubNonGameLogicParticipants(version, binding); + when(selectedGameLogicReceiptRepository.readForPublication(binding)) + .thenReturn(Optional.of(receipt)); + when(gameLogicClient.getDraftDesignDigestForVersion(binding, receipt)) + .thenReturn( + new PublishParticipantDigestDto( + "GAME_LOGIC", "7", "selected-commit", "logic-digest", 1, null, null)); + } + + private void stubNonGameLogicParticipants( + VersionDto version, PublicationDigestRequestBinding binding) { + when(worldManagementClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", "7", "selected-commit", "world-digest", 3, null, null)); + when(entityManagementClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 1, null, null)); + when(automationScriptingClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + "7", + "selected-commit", + "automation-digest", + 5, + null, + null)); + when(controlPlaneDigestService.getDigestForVersion(version)) + .thenReturn( + new DesignControlPlaneDigestDto( + "private-tenant-key", "7", "selected-commit", "control-plane-digest", 1)); + } + + private static VersionDto selectedVersion() { + return new VersionDto( + 7L, + "private-tenant-key", + 8, + VersionLifecycleState.DRAFT, + 2L, + null, + null, + false, + "selected notes", + LocalDateTime.now(), + LocalDateTime.now()); + } + + private static PublicationDigestRequestBinding selectedBinding(VersionDto version) { + return PublicationDigestRequestBinding.full( + "11111111-1111-4111-8111-111111111111", String.valueOf(version.id()), "selected-request-1"); + } + private static PublicationDigestRequestBinding captureVersionBinding( WorldManagementClient client) { ArgumentCaptor captor = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index deb2f898cc..3b52c49e29 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; @@ -53,6 +54,7 @@ import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; import org.mapstruct.factory.Mappers; +import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -170,6 +172,97 @@ void selectedPublicationRejectsPrivateTenantDerivedWorkflowIdentity() { verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); } + @Test + void selectedPublicationPassesCanonicalOperationBindingAndKeepsMissingReceiptPending() + throws Exception { + String tenantId = "9002"; + long versionId = 10L; + int versionNumber = 8; + String publishRequestId = "selected-request-8"; + String notes = "selected draft notes"; + UUID canonicalTenantId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + PublicationDigestRequestBinding expectedBinding = + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(versionId), publishRequestId); + String workflowId = expectedBinding.derivedWorkflowIdentity(); + String selectionDigest = "sha256:" + "b".repeat(64); + PublishAttempt attempt = + fullAttempt(PublishAttemptStatus.PENDING, versionId, versionNumber, workflowId); + attempt.setTenantId(tenantId); + attempt.setRequestDigest(selectionDigest); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + + GameDesignPublicationOperation operation = + org.mockito.Mockito.mock(GameDesignPublicationOperation.class); + AccountPublicationAuthorizationBinding account = + org.mockito.Mockito.mock(AccountPublicationAuthorizationBinding.class); + AccountPublicationAuthorizationBinding.PreallocationInput input = + org.mockito.Mockito.mock(AccountPublicationAuthorizationBinding.PreallocationInput.class); + AuthoredDraftPublishSelectionBinding selection = + org.mockito.Mockito.mock(AuthoredDraftPublishSelectionBinding.class); + AuthoredDraftPublishSelectionBinding.PublishIntent intent = + org.mockito.Mockito.mock(AuthoredDraftPublishSelectionBinding.PublishIntent.class); + when(operation.account()).thenReturn(account); + when(account.input()).thenReturn(input); + when(input.selection()).thenReturn(selection); + when(selection.intent()).thenReturn(intent); + when(intent.canonicalTenantId()).thenReturn(canonicalTenantId); + when(intent.publishRequestId()).thenReturn(publishRequestId); + when(intent.notes()).thenReturn(notes); + when(operation.tenantKey()).thenReturn(tenantId); + when(operation.versionId()).thenReturn(versionId); + when(operation.selectionDigest()).thenReturn(selectionDigest); + when(operation.workflowId()).thenReturn(workflowId); + when(publishAttemptRepository.requireSelectedPublicationReadback(attempt, "PENDING")) + .thenReturn(operation); + + Version draft = fullVersion(versionId, versionNumber, VersionLifecycleState.DRAFT); + draft.setTenantId(tenantId); + when(versionRepository.findByTenantIdAndId(tenantId, versionId)).thenReturn(Optional.of(draft)); + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), eq(workflowId))) + .thenReturn( + List.of( + new PublishParticipantDigestDto( + "GAME_LOGIC", + String.valueOf(versionId), + null, + null, + null, + null, + "PARTICIPANT_UNAVAILABLE", + "immutable selected Game Logic receipt is not available yet"))); + org.mockito.Mockito.doThrow( + new PublishGateFailureException( + PublishGateFailureCode.PARTICIPANT_UNAVAILABLE, + "selected Game Logic receipt is missing", + "PARTICIPANT_UNAVAILABLE")) + .when(publishGateService) + .assertGatePassed(any(VersionDto.class), any(List.class)); + + assertThrows( + VersionPublishCommandServiceImpl.PendingReconciliationException.class, + () -> + service.reconcileSelectedDraftFullVersionPublish( + tenantId, versionId, notes, publishRequestId, workflowId)); + + ArgumentCaptor bindingCaptor = + ArgumentCaptor.forClass(PublicationDigestRequestBinding.class); + verify(publishGateService) + .collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), bindingCaptor.capture(), eq(workflowId)); + assertEquals(expectedBinding.tenantId(), bindingCaptor.getValue().tenantId()); + assertEquals(expectedBinding.versionId(), bindingCaptor.getValue().versionId()); + assertEquals(expectedBinding.requestDigest(), bindingCaptor.getValue().requestDigest()); + assertEquals( + expectedBinding.derivedWorkflowIdentity(), + bindingCaptor.getValue().derivedWorkflowIdentity()); + verify(publishAttemptService, never()) + .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); + verify(publishAttemptRepository, never()).sealPublication(attempt, false); + } + @Test void publishFullVersionUsesTenantScopedVersionSequence() { Game game = new Game(); diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java index 45de4c801c..019db94ed1 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/GameLogicDraftDesignDigestService.java @@ -1,7 +1,11 @@ package net.firedevops.firemud.gamelogic.service; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; + public interface GameLogicDraftDesignDigestService { - GameLogicDraftDesignDigest getDraftDesignDigest(String tenantId, String versionId); + GameLogicPublicationSourceReadService.Result getDraftDesignDigest( + GameLogicPublicationSourceReadBinding binding); final class UnsupportedDigestScopeException extends RuntimeException { private static final long serialVersionUID = 1L; @@ -10,11 +14,4 @@ public UnsupportedDigestScopeException(String message) { super(message); } } - - record GameLogicDraftDesignDigest( - String tenantId, - String scopeValue, - String appliedCommitId, - String contentDigest, - int digestSchemaVersion) {} } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java index c9e218a577..4c97c0a228 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImpl.java @@ -1,17 +1,35 @@ package net.firedevops.firemud.gamelogic.service.impl; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; import net.firedevops.firemud.gamelogic.service.GameLogicDraftDesignDigestService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; import org.springframework.stereotype.Service; @Service -public class GameLogicDraftDesignDigestServiceImpl implements GameLogicDraftDesignDigestService { +public final class GameLogicDraftDesignDigestServiceImpl + implements GameLogicDraftDesignDigestService { + private final GameLogicPublicationSourceReadService publicationSourceReadService; + + /** Spring's default owner keeps this route denied until explicit composition provides storage. */ + public GameLogicDraftDesignDigestServiceImpl() { + publicationSourceReadService = null; + } + + /** Explicit composition for owner-local proofs and tests; this constructor is not auto-wired. */ + public GameLogicDraftDesignDigestServiceImpl( + GameLogicPublicationSourceReadService publicationSourceReadService) { + this.publicationSourceReadService = + Objects.requireNonNull(publicationSourceReadService, "publicationSourceReadService"); + } @Override - public GameLogicDraftDesignDigest getDraftDesignDigest(String tenantId, String versionId) { - if (versionId == null || versionId.isBlank()) { - throw new IllegalArgumentException("version_id is required"); + public GameLogicPublicationSourceReadService.Result getDraftDesignDigest( + GameLogicPublicationSourceReadBinding binding) { + if (publicationSourceReadService == null) { + throw new UnsupportedDigestScopeException( + "Game Logic retained publication source reader is not configured"); } - throw new UnsupportedDigestScopeException( - "Game Logic owner-local manifest and provenance are unavailable"); + return publicationSourceReadService.read(binding); } } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java index fca017ad10..0a934af274 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcService.java @@ -6,8 +6,8 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcAppErrors; -import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.GameplaySessionAttestationException; import net.firedevops.firemud.common.security.GameplaySessionAttestationService; @@ -169,41 +169,10 @@ public void getDraftDesignDigest( StreamObserver responseObserver) { try { requirePublicationRead(); - if (request.getScopeCase() != GetDraftDesignDigestRequest.ScopeCase.VERSION_ID) { - responseObserver.onNext( - GetDraftDesignDigestResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "GetDraftDesignDigest", - "UNSUPPORTED_SCOPE", - "game logic supports version_id scope only")) - .build()); - responseObserver.onCompleted(); - return; - } - PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.forScope( - PublicationDigestRequestBinding.ScopeKind.FULL_VERSION, - request.getTenantId(), - request.getVersionId(), - request.getBaseVersionId(), - request.getScriptPatchVersion(), - request.getPublishRequestId()); - binding.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest()); - var digest = - gameLogicDraftDesignDigestService.getDraftDesignDigest( - request.getTenantId(), request.getVersionId()); - binding.requireOwnerScope(digest.tenantId(), digest.scopeValue()); + var binding = GameLogicPublicationSourceReadGrpcCodec.fromRequest(request); + var retainedRead = gameLogicDraftDesignDigestService.getDraftDesignDigest(binding); responseObserver.onNext( - GetDraftDesignDigestResponse.newBuilder() - .setTenantId(binding.tenantId()) - .setVersionId(binding.versionId()) - .setAppliedCommitId(digest.appliedCommitId()) - .setContentDigest(digest.contentDigest()) - .setDigestSchemaVersion(digest.digestSchemaVersion()) - .build()); + GameLogicPublicationSourceReadGrpcCodec.toResponse(binding, retainedRead.terminal())); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { responseObserver.onNext( @@ -241,6 +210,23 @@ public void getDraftDesignDigest( ex.getMessage())) .build()); responseObserver.onCompleted(); + } catch (StatusRuntimeException ex) { + Status status = ex.getStatus(); + String description = + status.getDescription() == null + ? "Exact retained publication source read was denied" + : status.getDescription(); + responseObserver.onNext( + GetDraftDesignDigestResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetDraftDesignDigest", + status.getCode().name(), + description)) + .build()); + responseObserver.onCompleted(); } catch (Exception ex) { responseObserver.onNext( GetDraftDesignDigestResponse.newBuilder() diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java new file mode 100644 index 0000000000..6f5265daaf --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java @@ -0,0 +1,236 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameplayAbilitySchemaProjection; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered read of the genuine retained Game Logic source for one exact publication lookup. + * This service does not create intake authority, read Account state, repair source, or activate a + * digest transport. + */ +public final class GameLogicPublicationSourceReadService { + public static final int DIGEST_SCHEMA_VERSION = 1; + public static final String CANONICALIZATION = "RFC8785"; + + private final GameLogicGameplayRuleIntakeRepository repository; + private final String workloadNamespace; + + public GameLogicPublicationSourceReadService( + GameLogicGameplayRuleIntakeRepository repository, String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Logic workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * Returns digests only after the exact operation's actual RETAINED terminal is read back. + * + *

The repository verifies the indexed operation identity and all stored bytes. This method + * additionally correlates that readback with the complete original authorization and exact + * publication selection before deriving either digest. + */ + public Result read(GameLogicPublicationSourceReadBinding binding) { + requirePeer(workloadNamespace); + if (binding == null) { + throw Status.INVALID_ARGUMENT + .withDescription("Exact full-version publication source-read binding required") + .asRuntimeException(); + } + requireNoActiveTransaction(); + + GameLogicIntakeAuthorizationBinding authorization = binding.authorization(); + GameLogicGameplayRuleIntakeOperation requestedOperation = + new GameLogicGameplayRuleIntakeOperation(workloadNamespace, authorization); + GameLogicGameplayRuleIntakeTerminal terminal = + repository + .findTerminal(authorization.operationId()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact retained Game Logic source is unavailable") + .asRuntimeException()); + + requireExactRetainedTerminal(terminal, requestedOperation, authorization); + GameplayRuleSelectedSource retainedSource = + new GameplayRuleSelectedSource( + new String(terminal.selectedSourceBytes(), StandardCharsets.UTF_8)); + byte[] manifestBytes = + retainedSource.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8); + if (!Arrays.equals(manifestBytes, terminal.manifestBytes())) { + throw Status.ALREADY_EXISTS + .withDescription("Retained Game Logic manifest differs from exact selected source") + .asRuntimeException(); + } + + String manifestDigest = GameplayRuleManifest.sha256(manifestBytes); + String abilitySchemaDigest = GameplayAbilitySchemaProjection.digest(retainedSource.manifest()); + return new Result( + binding, + terminal, + retainedSource, + manifestDigest, + abilitySchemaDigest, + DIGEST_SCHEMA_VERSION, + CANONICALIZATION); + } + + private static void requireExactRetainedTerminal( + GameLogicGameplayRuleIntakeTerminal terminal, + GameLogicGameplayRuleIntakeOperation requestedOperation, + GameLogicIntakeAuthorizationBinding authorization) { + if (!Arrays.equals(terminal.operation().canonicalBytes(), requestedOperation.canonicalBytes()) + || !Arrays.equals(terminal.authorizationBytes(), authorization.canonicalBytes())) { + throw Status.ALREADY_EXISTS + .withDescription("Retained Game Logic operation differs from exact publication source") + .asRuntimeException(); + } + if (terminal.outcome() != GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact Game Logic source operation did not retain source") + .asRuntimeException(); + } + if (!Arrays.equals(terminal.selectedSourceBytes(), authorization.source().canonicalBytes())) { + throw Status.ALREADY_EXISTS + .withDescription("Retained Game Logic source differs from Account authorization") + .asRuntimeException(); + } + if (!authorization + .source() + .binding() + .target() + .canonicalTenantId() + .equals(authorization.tenantId()) + || !authorization + .source() + .binding() + .target() + .canonicalVersionId() + .equals(authorization.versionId())) { + throw Status.ALREADY_EXISTS + .withDescription("Retained Game Logic commit scope differs from Account authorization") + .asRuntimeException(); + } + } + + private static void requirePeer(String namespace) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!peer.isInNamespace(namespace) + || !peer.isService("game-design-service") + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } + + private static void requireNoActiveTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Publication source reads must run outside SQL") + .asRuntimeException(); + } + } + + /** + * Immutable source-read result whose provenance is the exact object returned by owner storage. + */ + public static final class Result { + private final GameLogicPublicationSourceReadBinding binding; + private final GameLogicGameplayRuleIntakeTerminal terminal; + private final GameplayRuleSelectedSource selectedSource; + private final String manifestDigest; + private final String abilitySchemaDigest; + private final int digestSchemaVersion; + private final String canonicalization; + + private Result( + GameLogicPublicationSourceReadBinding binding, + GameLogicGameplayRuleIntakeTerminal terminal, + GameplayRuleSelectedSource selectedSource, + String manifestDigest, + String abilitySchemaDigest, + int digestSchemaVersion, + String canonicalization) { + this.binding = Objects.requireNonNull(binding, "binding"); + this.terminal = Objects.requireNonNull(terminal, "terminal"); + this.selectedSource = Objects.requireNonNull(selectedSource, "selectedSource"); + this.manifestDigest = Objects.requireNonNull(manifestDigest, "manifestDigest"); + this.abilitySchemaDigest = Objects.requireNonNull(abilitySchemaDigest, "abilitySchemaDigest"); + if (digestSchemaVersion <= 0) { + throw new IllegalArgumentException("Positive digest schema version required"); + } + this.digestSchemaVersion = digestSchemaVersion; + this.canonicalization = Objects.requireNonNull(canonicalization, "canonicalization"); + } + + public GameLogicPublicationSourceReadBinding binding() { + return binding; + } + + /** The genuine immutable terminal instance returned by the owner repository readback. */ + public GameLogicGameplayRuleIntakeTerminal terminal() { + return terminal; + } + + public GameLogicGameplayRuleIntakeOperation operation() { + return terminal.operation(); + } + + /** The exact selected source reconstructed from the terminal's defensive stored bytes. */ + public GameplayRuleSelectedSource selectedSource() { + return selectedSource; + } + + public byte[] terminalBytes() { + return terminal.canonicalBytes(); + } + + public byte[] authorizationBytes() { + return terminal.authorizationBytes(); + } + + public byte[] selectedSourceBytes() { + return terminal.selectedSourceBytes(); + } + + public byte[] manifestBytes() { + return terminal.manifestBytes(); + } + + public String manifestDigest() { + return manifestDigest; + } + + public String abilitySchemaDigest() { + return abilitySchemaDigest; + } + + public int digestSchemaVersion() { + return digestSchemaVersion; + } + + /** Canonicalization evidence for both the retained manifest and v1 ability projection. */ + public String canonicalization() { + return canonicalization; + } + } +} diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java index 4217698f8a..efe1be831c 100644 --- a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java @@ -4,9 +4,13 @@ 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.when; import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; @@ -21,11 +25,14 @@ import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameplayAbilitySchemaProjection; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.test.TestContainerImages; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -175,6 +182,127 @@ void explicitAbortWinsBeforeRetentionAndPreventsLaterSourceReadsAndCommit() thro .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); } + @Test + void publicationReadUsesCommittedTerminalAfterUpstreamReadersAreUnavailableAndNeverAttestsAbort() + throws Exception { + var fixture = fixture(); + var authorization = authorization(); + // These upstream collaborators are fixture stubs; this definition proves GL's committed local + // readback, not genuine cross-owner Account or Game Design producer issuance. + var accountReader = mock(GameLogicIntakeAuthorizationReadClient.class); + var gameDesignReader = mock(GameplayRuleSourceReadClient.class); + when(accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenAnswer( + invocation -> new GameLogicIntakeAuthorizationReadEvidence(invocation.getArgument(0))); + when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenAnswer( + invocation -> + new GameplayRuleSourceReadEvidence( + invocation.getArgument(0), authorization.source())); + + var retained = + asGameDesign(() -> fixture.service(accountReader, gameDesignReader).retain(authorization)); + var unavailableAccount = mock(GameLogicIntakeAuthorizationReadClient.class); + var unavailableDesign = mock(GameplayRuleSourceReadClient.class); + when(unavailableAccount.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) + .thenThrow(new AssertionError("Exact retained retry must not reread Account")); + when(unavailableDesign.read(any(GameplayRuleSourceReadEvidence.Request.class))) + .thenThrow(new AssertionError("Exact retained retry must not reread Game Design")); + + var exactRetry = + asGameDesign( + () -> fixture.service(unavailableAccount, unavailableDesign).retain(authorization)); + assertThat(exactRetry.canonicalBytes()).containsExactly(retained.canonicalBytes()); + verify(unavailableAccount, never()) + .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); + verify(unavailableDesign, never()).read(any(GameplayRuleSourceReadEvidence.Request.class)); + + var publicationReader = + new GameLogicPublicationSourceReadService(fixture.repository, NAMESPACE); + var publicationBinding = publicationBinding(authorization); + var publicationResult = asGameDesign(() -> publicationReader.read(publicationBinding)); + var publicationRetry = asGameDesign(() -> publicationReader.read(publicationBinding)); + assertThat(publicationResult.binding().canonicalBytes()) + .containsExactly(publicationBinding.canonicalBytes()); + assertThat(publicationResult.terminalBytes()).containsExactly(retained.canonicalBytes()); + assertThat(publicationRetry.terminalBytes()).containsExactly(publicationResult.terminalBytes()); + assertThat(publicationResult.manifestDigest()) + .isEqualTo(authorization.source().manifest().digest()); + assertThat(publicationResult.abilitySchemaDigest()) + .isEqualTo(GameplayAbilitySchemaProjection.digest(authorization.source().manifest())); + assertThat( + fixture + .repository + .findTerminal(authorization.operationId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(retained.canonicalBytes()); + + var changedOperationId = + copyAuthorization( + authorization, + UUID.randomUUID(), + authorization.fenceId(), + authorization.intakeRequestId(), + authorization.source()); + assertReadDenied( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> publicationReader.read(publicationBinding(changedOperationId)))); + + var changedOperation = + copyAuthorization( + authorization, + authorization.operationId(), + authorization.fenceId(), + UUID.randomUUID(), + authorization.source()); + assertReadDenied( + Status.Code.ALREADY_EXISTS, + () -> asGameDesign(() -> publicationReader.read(publicationBinding(changedOperation)))); + + var changedFence = + copyAuthorization( + authorization, + authorization.operationId(), + UUID.randomUUID(), + authorization.intakeRequestId(), + authorization.source()); + assertReadDenied( + Status.Code.ALREADY_EXISTS, + () -> asGameDesign(() -> publicationReader.read(publicationBinding(changedFence)))); + + var originalCommit = authorization.source().binding(); + var changedCommit = + DraftCommitBinding.create( + originalCommit.target(), + originalCommit.requestId(), + UUID.randomUUID(), + originalCommit.baseCommitId(), + originalCommit.revisions(), + originalCommit.affectedUnits()); + var changedCommitAuthorization = + copyAuthorization( + authorization, + authorization.operationId(), + authorization.fenceId(), + authorization.intakeRequestId(), + source(changedCommit)); + assertReadDenied( + Status.Code.ALREADY_EXISTS, + () -> + asGameDesign( + () -> publicationReader.read(publicationBinding(changedCommitAuthorization)))); + + var abortedAuthorization = authorization(); + var aborted = + asGameDesign( + () -> fixture.service(accountReader, gameDesignReader).abort(abortedAuthorization)); + assertThat(aborted.outcome()).isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.ABORTED); + assertReadDenied( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> publicationReader.read(publicationBinding(abortedAuthorization)))); + } + private static Fixture fixture() { String schema = "gl_intake_" + UUID.randomUUID().toString().replace("-", ""); var dataSource = new DriverManagerDataSource(); @@ -263,6 +391,54 @@ private static GameLogicIntakeAuthorizationBinding authorization() { List.of(accountSource)); } + private static GameLogicIntakeAuthorizationBinding copyAuthorization( + GameLogicIntakeAuthorizationBinding original, + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + GameplayRuleSelectedSource source) { + return new GameLogicIntakeAuthorizationBinding( + operationId, + fenceId, + intakeRequestId, + original.actorAccountId(), + source, + original.sources()); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding binding) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", "1", + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + } + + private static GameLogicPublicationSourceReadBinding publicationBinding( + GameLogicIntakeAuthorizationBinding authorization) { + var target = authorization.source().binding().target(); + return new GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding.full( + authorization.tenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + "publication-read"), + authorization); + } + + private static void assertReadDenied( + Status.Code expected, org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + private record Fixture( DSLContext dsl, DataSourceTransactionManager transactionManager, diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java index ef11de7c7d..7cdec12c0b 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicDraftDesignDigestServiceImplTest.java @@ -1,29 +1,41 @@ package net.firedevops.firemud.gamelogic.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; import net.firedevops.firemud.gamelogic.service.GameLogicDraftDesignDigestService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; import org.junit.jupiter.api.Test; class GameLogicDraftDesignDigestServiceImplTest { - private final GameLogicDraftDesignDigestServiceImpl service = - new GameLogicDraftDesignDigestServiceImpl(); - @Test - void getDraftDesignDigestFailsWhenOwnerManifestAndProvenanceAreUnavailable() { + void defaultSpringCompositionRemainsDeniedWithoutAConfiguredOwnerReader() { + var service = new GameLogicDraftDesignDigestServiceImpl(); + GameLogicDraftDesignDigestService.UnsupportedDigestScopeException thrown = assertThrows( GameLogicDraftDesignDigestService.UnsupportedDigestScopeException.class, - () -> service.getDraftDesignDigest("tenant-1", "7")); + () -> service.getDraftDesignDigest(null)); assertEquals( - "Game Logic owner-local manifest and provenance are unavailable", thrown.getMessage()); + "Game Logic retained publication source reader is not configured", thrown.getMessage()); } @Test - void getDraftDesignDigestRejectsMissingVersionBeforeManifestCheck() { - assertThrows( - IllegalArgumentException.class, () -> service.getDraftDesignDigest("tenant-1", " ")); + void explicitlyComposedServiceReturnsTheExactRetainedReadResultForTheLookupBinding() { + var sourceReader = mock(GameLogicPublicationSourceReadService.class); + var binding = mock(GameLogicPublicationSourceReadBinding.class); + var expected = mock(GameLogicPublicationSourceReadService.Result.class); + when(sourceReader.read(binding)).thenReturn(expected); + var service = new GameLogicDraftDesignDigestServiceImpl(sourceReader); + + assertSame(expected, service.getDraftDesignDigest(binding)); + + verify(sourceReader).read(binding); } } diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java index 1647d1925a..8d20c182d5 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java @@ -1,10 +1,12 @@ package net.firedevops.firemud.gamelogic.service.impl; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; +import com.google.protobuf.ByteString; import io.grpc.Context; import io.grpc.Status; import io.grpc.StatusRuntimeException; @@ -12,7 +14,18 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameplayAbilitySchemaProjection; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.security.GameplaySessionAttestationException; @@ -38,6 +51,8 @@ import net.firedevops.firemud.gamelogic.service.LookAggregationService; import net.firedevops.firemud.gamelogic.service.MoveAggregationService; import net.firedevops.firemud.gamelogic.service.PingService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeRepository; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; import net.firedevops.firemud.gamelogic.v1.DropCarriedItemRequest; import net.firedevops.firemud.gamelogic.v1.ExecuteCommandRequest; import net.firedevops.firemud.gamelogic.v1.ExecuteCommandResponse; @@ -57,6 +72,7 @@ class GameLogicGrpcServiceTest { private static final String TEST_NAMESPACE = "test"; + private static final UUID TEST_TENANT = UUID.fromString("00000000-0000-0000-0000-000000000001"); private static final GrpcPeerIdentity WRONG_PEER = new GrpcPeerIdentity( "spiffe://firemud/ns/test/sa/world-management-service", @@ -79,17 +95,105 @@ private static void runAsGameDesign(Runnable action) { } private static GetDraftDesignDigestRequest fullDigestRequest(String tenantId, String versionId) { - PublicationDigestRequestBinding binding = - PublicationDigestRequestBinding.full(tenantId, versionId, "request-7"); + var authorization = digestAuthorization(UUID.fromString(tenantId), Long.parseLong(versionId)); + return fullDigestRequest(publicationBinding(authorization, "request-7")); + } + + private static GetDraftDesignDigestRequest fullDigestRequest( + GameLogicPublicationSourceReadBinding binding) { + PublicationDigestRequestBinding publicationRequest = binding.publicationRequest(); return GetDraftDesignDigestRequest.newBuilder() - .setTenantId(binding.tenantId()) - .setVersionId(binding.versionId()) - .setPublishRequestId(binding.publishRequestId()) - .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) - .setRequestDigest(binding.requestDigest()) + .setTenantId(publicationRequest.tenantId()) + .setVersionId(publicationRequest.versionId()) + .setPublishRequestId(publicationRequest.publishRequestId()) + .setDerivedWorkflowIdentity(publicationRequest.derivedWorkflowIdentity()) + .setRequestDigest(publicationRequest.requestDigest()) + .setSourceReadBinding(ByteString.copyFrom(binding.canonicalBytes())) + .setSourceReadBindingDigest(binding.digest()) .build(); } + private static GameLogicPublicationSourceReadBinding publicationBinding( + GameLogicIntakeAuthorizationBinding authorization, String publishRequestId) { + var target = authorization.source().binding().target(); + return new GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding.full( + authorization.tenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + publishRequestId), + authorization); + } + + private static GameLogicIntakeAuthorizationBinding digestAuthorization( + UUID tenantId, long gameDesignVersionRowId) { + var actor = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenantId, + UUID.randomUUID(), + gameDesignVersionRowId, + "private", + 29, + "private", + "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + var source = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", commit.canonicalJson(), + "bindingDigest", commit.digest(), + "sourceEpoch", "1", + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var accountSource = + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + source, + List.of(accountSource)); + } + + private static GameLogicGameplayRuleIntakeTerminal retainedTerminal( + GameLogicIntakeAuthorizationBinding authorization) { + return GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(TEST_NAMESPACE, authorization), + authorization.source().canonicalBytes(), + authorization.source().manifest().canonicalBytes()); + } + private GameLogicDraftDesignDigestService mockDigestService() { return Mockito.mock(GameLogicDraftDesignDigestService.class); } @@ -257,7 +361,7 @@ public void onCompleted() {} } @Test - void getDraftDesignDigestMapsUnavailableManifestToErrorResponse() { + void getDraftDesignDigestMapsUnconfiguredRetainedSourceToErrorResponse() { PingService pingService = new PingServiceImpl(); var dispatcher = new EventDispatcher(); var processor = new SimpleCommandProcessor(dispatcher, new NoOpScriptingHook()); @@ -267,10 +371,11 @@ void getDraftDesignDigestMapsUnavailableManifestToErrorResponse() { Mockito.mock(CommunicationAggregationService.class); MoveAggregationService moveAggregationService = Mockito.mock(MoveAggregationService.class); GameLogicDraftDesignDigestService digestService = mockDigestService(); - Mockito.when(digestService.getDraftDesignDigest("1", "7")) + Mockito.when( + digestService.getDraftDesignDigest(any(GameLogicPublicationSourceReadBinding.class))) .thenThrow( new GameLogicDraftDesignDigestService.UnsupportedDigestScopeException( - "Game Logic owner-local manifest and provenance are unavailable")); + "Game Logic retained publication source reader is not configured")); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); GameLogicGrpcService service = @@ -290,7 +395,7 @@ void getDraftDesignDigestMapsUnavailableManifestToErrorResponse() { runAsGameDesign( () -> service.getDraftDesignDigest( - fullDigestRequest("1", "7"), + fullDigestRequest(TEST_TENANT.toString(), "7"), new StreamObserver<>() { @Override public void onNext(GetDraftDesignDigestResponse value) { @@ -316,17 +421,118 @@ public void onCompleted() {} assertEquals(0, ref.get().getDigestSchemaVersion()); } + @Test + void getDraftDesignDigestEchoesTheExactRetainedSourceAndCanonicalDigests() { + var authorization = digestAuthorization(TEST_TENANT, 7); + var binding = publicationBinding(authorization, "request-7"); + var terminal = retainedTerminal(authorization); + var repository = Mockito.mock(GameLogicGameplayRuleIntakeRepository.class); + Mockito.when(repository.findTerminal(authorization.operationId())) + .thenReturn(Optional.of(terminal)); + var digestService = + new GameLogicDraftDesignDigestServiceImpl( + new GameLogicPublicationSourceReadService(repository, TEST_NAMESPACE)); + var service = newDigestService(digestService); + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-design-service", "test-instance"); + + AtomicReference responseReference = new AtomicReference<>(); + runAsGameDesign(() -> responseReference.set(invokeDigest(service, fullDigestRequest(binding)))); + GetDraftDesignDigestResponse response = responseReference.get(); + + assertEquals("", response.getError().getCode()); + assertEquals(TEST_TENANT.toString(), response.getTenantId()); + assertEquals("7", response.getVersionId()); + assertEquals( + authorization.source().binding().commitId().toString(), response.getAppliedCommitId()); + assertEquals(authorization.source().manifest().digest(), response.getContentDigest()); + assertEquals(1, response.getDigestSchemaVersion()); + assertEquals( + GameplayAbilitySchemaProjection.digest(authorization.source().manifest()), + response.getAbilitySchemaDigest()); + assertEquals("RFC8785", response.getCanonicalization()); + assertEquals(binding.digest(), response.getSourceReadBindingDigest()); + assertArrayEquals(binding.canonicalBytes(), response.getSourceReadBinding().toByteArray()); + assertEquals(terminal.digest(), response.getRetainedIntakeTerminalDigest()); + assertArrayEquals( + terminal.canonicalBytes(), response.getRetainedIntakeTerminal().toByteArray()); + Mockito.verify(repository).findTerminal(authorization.operationId()); + } + + @Test + void getDraftDesignDigestRejectsMissingBindingAndUnversionedScopeBeforeServiceCall() { + var digestService = mockDigestService(); + var service = newDigestService(digestService); + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-design-service", "test-instance"); + var valid = fullDigestRequest(TEST_TENANT.toString(), "7"); + var missingBinding = + valid.toBuilder().clearSourceReadBinding().clearSourceReadBindingDigest().build(); + var unversionedScope = valid.toBuilder().clearScope().build(); + + runAsGameDesign( + () -> { + var missingResponse = invokeDigest(service, missingBinding); + assertEquals("INVALID_ARGUMENT", missingResponse.getError().getCode()); + assertEquals("", missingResponse.getContentDigest()); + assertEquals(0, missingResponse.getDigestSchemaVersion()); + var scopeResponse = invokeDigest(service, unversionedScope); + assertEquals("INVALID_ARGUMENT", scopeResponse.getError().getCode()); + assertEquals("", scopeResponse.getContentDigest()); + assertEquals(0, scopeResponse.getDigestSchemaVersion()); + }); + Mockito.verifyNoInteractions(digestService); + } + + @Test + void getDraftDesignDigestDeniesSourceBindingThatDiffersFromRetainedOperation() { + var authorization = digestAuthorization(TEST_TENANT, 7); + var stored = retainedTerminal(authorization); + var changedAuthorization = + new GameLogicIntakeAuthorizationBinding( + authorization.operationId(), + UUID.randomUUID(), + authorization.intakeRequestId(), + authorization.actorAccountId(), + authorization.source(), + authorization.sources()); + var changedBinding = publicationBinding(changedAuthorization, "request-7"); + var repository = Mockito.mock(GameLogicGameplayRuleIntakeRepository.class); + Mockito.when(repository.findTerminal(authorization.operationId())) + .thenReturn(Optional.of(stored)); + var service = + newDigestService( + new GameLogicDraftDesignDigestServiceImpl( + new GameLogicPublicationSourceReadService(repository, TEST_NAMESPACE))); + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-design-service", "test-instance"); + + AtomicReference responseReference = new AtomicReference<>(); + runAsGameDesign( + () -> responseReference.set(invokeDigest(service, fullDigestRequest(changedBinding)))); + GetDraftDesignDigestResponse response = responseReference.get(); + + assertEquals("ALREADY_EXISTS", response.getError().getCode()); + assertEquals("", response.getContentDigest()); + assertEquals("", response.getAbilitySchemaDigest()); + assertEquals(0, response.getDigestSchemaVersion()); + assertEquals(ByteString.EMPTY, response.getRetainedIntakeTerminal()); + Mockito.verify(repository).findTerminal(authorization.operationId()); + } + @Test void getDraftDesignDigestMapsUnexpectedUnsupportedOperationToInternalError() { GameLogicDraftDesignDigestService digestService = mockDigestService(); - Mockito.when(digestService.getDraftDesignDigest("1", "7")) + Mockito.when( + digestService.getDraftDesignDigest(any(GameLogicPublicationSourceReadBinding.class))) .thenThrow(new UnsupportedOperationException("unexpected implementation failure")); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); GameLogicGrpcService service = newDigestService(digestService); AtomicReference response = new AtomicReference<>(); - runAsGameDesign(() -> response.set(invokeDigest(service, fullDigestRequest("1", "7")))); + runAsGameDesign( + () -> response.set(invokeDigest(service, fullDigestRequest(TEST_TENANT.toString(), "7")))); assertTrue(response.get().hasError()); assertEquals("INTERNAL", response.get().getError().getCode()); @@ -358,7 +564,7 @@ void getDraftDesignDigestRejectsMissingPeerIdentityForInternalCaller() { .run( () -> service.getDraftDesignDigest( - fullDigestRequest("1", "7"), + fullDigestRequest(TEST_TENANT.toString(), "7"), new StreamObserver<>() { @Override public void onNext(GetDraftDesignDigestResponse value) { @@ -379,7 +585,7 @@ public void onCompleted() {} void getDraftDesignDigestRejectsWrongPeerAndUserOrAdminJwt() { GameLogicDraftDesignDigestService digestService = mockDigestService(); GameLogicGrpcService service = newDigestService(digestService); - GetDraftDesignDigestRequest request = fullDigestRequest("1", "7"); + GetDraftDesignDigestRequest request = fullDigestRequest(TEST_TENANT.toString(), "7"); SessionContext.setContext(null, List.of(), Map.of(), true, "game-design-service", "instance-1"); withPeer( @@ -435,25 +641,11 @@ void getDraftDesignDigestFailsClosedWhenWorkloadNamespaceIsMissingOrInvalid() { () -> assertEquals( "PERMISSION_DENIED", - invokeDigest(service, fullDigestRequest("1", "7")).getError().getCode())); + invokeDigest(service, fullDigestRequest(TEST_TENANT.toString(), "7")) + .getError() + .getCode())); } Mockito.verifyNoInteractions(digestService); - - GameLogicDraftDesignDigestService configuredDigestService = mockDigestService(); - Mockito.when(configuredDigestService.getDraftDesignDigest("1", "7")) - .thenReturn( - new GameLogicDraftDesignDigestService.GameLogicDraftDesignDigest( - "1", "7", "version:7", "digest-game-logic", 1)); - GameLogicGrpcService configuredService = - newDigestService(configuredDigestService, TEST_NAMESPACE); - AtomicReference configuredResponse = new AtomicReference<>(); - runAsGameDesign( - () -> configuredResponse.set(invokeDigest(configuredService, fullDigestRequest("1", "7")))); - - assertTrue(configuredResponse.get().getError().getCode().isEmpty()); - assertEquals("1", configuredResponse.get().getTenantId()); - assertEquals("7", configuredResponse.get().getVersionId()); - Mockito.verify(configuredDigestService).getDraftDesignDigest("1", "7"); } private GetDraftDesignDigestResponse invokeDigest( diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadServiceTest.java new file mode 100644 index 0000000000..a799f990ff --- /dev/null +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadServiceTest.java @@ -0,0 +1,375 @@ +package net.firedevops.firemud.gamelogic.sourceintake; + +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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameplayAbilitySchemaProjection; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Uses a repository stub to exercise the owner read boundary. It does not claim PostgreSQL storage + * provenance; the repository's existing physical readback is responsible for indexed-row proof. + */ +class GameLogicPublicationSourceReadServiceTest { + private static final String NAMESPACE = "test"; + + @AfterEach + void clearThreadState() { + if (TransactionSynchronizationManager.isSynchronizationActive()) + TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + @Test + void returnsExactStoredTerminalAndBothDistinctCanonicalDigests() { + var fixture = new Fixture(); + var authorization = authorization(); + var stored = retained(authorization); + fixture.store(stored); + var binding = request(authorization); + + var result = asGameDesign(() -> fixture.service.read(binding)); + + assertThat(result.binding()).isSameAs(binding); + assertThat(result.terminal()).isSameAs(stored); + assertThat(result.operation().canonicalBytes()) + .containsExactly(stored.operation().canonicalBytes()); + assertThat(result.authorizationBytes()).containsExactly(authorization.canonicalBytes()); + assertThat(result.selectedSourceBytes()) + .containsExactly(authorization.source().canonicalBytes()); + assertThat(result.manifestBytes()) + .containsExactly(authorization.source().manifest().canonicalBytes()); + assertThat(result.manifestDigest()).isEqualTo(authorization.source().manifest().digest()); + assertThat(result.abilitySchemaDigest()) + .isEqualTo(GameplayAbilitySchemaProjection.digest(authorization.source().manifest())) + .isNotEqualTo(result.manifestDigest()); + assertThat(result.digestSchemaVersion()).isEqualTo(1); + assertThat(result.canonicalization()).isEqualTo("RFC8785"); + assertThat(result.terminalBytes()).containsExactly(stored.canonicalBytes()); + + byte[] returnedSource = result.selectedSourceBytes(); + returnedSource[0] ^= 1; + assertThat(result.selectedSourceBytes()) + .containsExactly(authorization.source().canonicalBytes()); + verify(fixture.repository).findTerminal(authorization.operationId()); + } + + @Test + void exactRetryReadsTheOriginalTerminalWithoutAccountOrLatestSourceReads() { + var fixture = new Fixture(); + var authorization = authorization(); + var stored = retained(authorization); + fixture.store(stored); + var binding = request(authorization); + + var first = asGameDesign(() -> fixture.service.read(binding)); + var retry = asGameDesign(() -> fixture.service.read(binding)); + + assertThat(retry.terminal()).isSameAs(stored); + assertThat(retry.terminalBytes()).containsExactly(first.terminalBytes()); + assertThat(retry.binding().canonicalBytes()).containsExactly(binding.canonicalBytes()); + // This service has only the owner repository dependency, so settlement cannot trigger a HELD + // read and retry cannot resolve a newer source snapshot. + verify(fixture.repository, times(2)).findTerminal(authorization.operationId()); + } + + @Test + void absentAndAbortedOperationsFailClosed() { + var fixture = new Fixture(); + var authorization = authorization(); + var binding = request(authorization); + + assertCode( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> fixture.service.read(binding))); + + var aborted = + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization)); + fixture.store(aborted); + assertCode( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> fixture.service.read(binding))); + } + + @Test + void onlyExactSameNamespaceGameDesignCanReadAndAuthenticationPrecedesBindingInspection() { + var fixture = new Fixture(); + List deniedPeers = + List.of( + peer("test", "account-service"), + peer("test", "game-logic-service"), + peer("test", "world-management-service"), + peer("other", "game-design-service")); + + for (GrpcPeerIdentity peer : deniedPeers) { + assertCode( + Status.Code.PERMISSION_DENIED, () -> asPeer(peer, () -> fixture.service.read(null))); + } + assertCode(Status.Code.UNAUTHENTICATED, () -> fixture.service.read(null)); + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + + assertCode(Status.Code.INVALID_ARGUMENT, () -> asGameDesign(() -> fixture.service.read(null))); + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + } + + @Test + void ambientSqlOrSynchronizationIsRejectedBeforeStorageRead() { + var fixture = new Fixture(); + var authorization = authorization(); + var binding = request(authorization); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertCode( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> fixture.service.read(binding))); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertCode( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> fixture.service.read(binding))); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verify(fixture.repository, never()).findTerminal(any(UUID.class)); + } + + @Test + void changedOperationFenceCommitAndSelectedSourceAreRejected() { + var original = authorization(); + var stored = retained(original); + + var changedOperation = copy(original, UUID.randomUUID(), original.fenceId(), original.source()); + assertStoredMismatch(stored, changedOperation); + + var changedFence = copy(original, original.operationId(), UUID.randomUUID(), original.source()); + assertStoredMismatch(stored, changedFence); + + var originalCommit = original.source().binding(); + var changedCommit = + DraftCommitBinding.create( + originalCommit.target(), + originalCommit.requestId(), + UUID.randomUUID(), + originalCommit.baseCommitId(), + originalCommit.revisions(), + originalCommit.affectedUnits()); + var changedCommitAuthorization = + copy(original, original.operationId(), original.fenceId(), source(changedCommit, "1")); + assertStoredMismatch(stored, changedCommitAuthorization); + + var changedSource = + copy(original, original.operationId(), original.fenceId(), source(originalCommit, "2")); + assertStoredMismatch(stored, changedSource); + } + + @Test + void changedScopeAliasesAndManifestReadbackAreRejected() { + var authorization = authorization(); + var wrongNumericVersion = + PublicationDigestRequestBinding.full( + authorization.tenantId().toString(), + Long.toString(authorization.source().binding().target().gameDesignVersionRowId() + 1), + "publish-request"); + assertThatThrownBy( + () -> new GameLogicPublicationSourceReadBinding(wrongNumericVersion, authorization)) + .isInstanceOf(IllegalArgumentException.class); + + var patch = + PublicationDigestRequestBinding.patch( + authorization.tenantId().toString(), "1", "patch-v1", "publish-request"); + assertThatThrownBy(() -> new GameLogicPublicationSourceReadBinding(patch, authorization)) + .isInstanceOf(IllegalArgumentException.class); + + var fixture = new Fixture(); + var validTerminal = retained(authorization); + var corruptReadback = mock(GameLogicGameplayRuleIntakeTerminal.class); + when(corruptReadback.operation()).thenReturn(validTerminal.operation()); + when(corruptReadback.authorizationBytes()).thenReturn(validTerminal.authorizationBytes()); + when(corruptReadback.outcome()) + .thenReturn(GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED); + when(corruptReadback.selectedSourceBytes()).thenReturn(validTerminal.selectedSourceBytes()); + when(corruptReadback.manifestBytes()).thenReturn("{}".getBytes(StandardCharsets.UTF_8)); + fixture.store(corruptReadback); + + assertCode( + Status.Code.ALREADY_EXISTS, + () -> asGameDesign(() -> fixture.service.read(request(authorization)))); + } + + private static void assertStoredMismatch( + GameLogicGameplayRuleIntakeTerminal stored, + GameLogicIntakeAuthorizationBinding requestedAuthorization) { + var fixture = new Fixture(); + fixture.store(stored); + assertCode( + Status.Code.ALREADY_EXISTS, + () -> asGameDesign(() -> fixture.service.read(request(requestedAuthorization)))); + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(error -> assertThat(Status.fromThrowable(error).getCode()).isEqualTo(expected)); + } + + private static GameLogicIntakeAuthorizationBinding copy( + GameLogicIntakeAuthorizationBinding original, + UUID operationId, + UUID fenceId, + GameplayRuleSelectedSource source) { + return new GameLogicIntakeAuthorizationBinding( + operationId, + fenceId, + original.intakeRequestId(), + original.actorAccountId(), + source, + original.sources()); + } + + private static GameLogicIntakeAuthorizationBinding authorization() { + var actor = UUID.randomUUID(); + var selected = source(commitBinding(), "1"); + var accountSource = + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence( + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind + .ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + return new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + actor, + selected, + List.of(accountSource)); + } + + private static DraftCommitBinding commitBinding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 17, "private", 29, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "0", + "0"))); + } + + private static GameplayRuleSelectedSource source(DraftCommitBinding binding, String epoch) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", epoch, + "inheritedCommitId", "", + "genesisReceiptId", UUID.randomUUID().toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + } + + private static GameLogicPublicationSourceReadBinding request( + GameLogicIntakeAuthorizationBinding authorization) { + var target = authorization.source().binding().target(); + return new GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding.full( + authorization.tenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + "publish-request"), + authorization); + } + + private static GameLogicGameplayRuleIntakeTerminal retained( + GameLogicIntakeAuthorizationBinding authorization) { + return GameLogicGameplayRuleIntakeTerminal.retained( + new GameLogicGameplayRuleIntakeOperation(NAMESPACE, authorization), + authorization.source().canonicalBytes(), + authorization.source().manifest().canonicalBytes()); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static T asGameDesign(java.util.function.Supplier action) { + return asPeer(peer(NAMESPACE, "game-design-service"), action); + } + + private static T asPeer(GrpcPeerIdentity peer, java.util.function.Supplier action) { + return asContext(Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer), action); + } + + private static T asContext(Context context, java.util.function.Supplier action) { + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static final class Fixture { + private final GameLogicGameplayRuleIntakeRepository repository = + mock(GameLogicGameplayRuleIntakeRepository.class); + private final AtomicReference terminal = + new AtomicReference<>(); + private final GameLogicPublicationSourceReadService service = + new GameLogicPublicationSourceReadService(repository, NAMESPACE); + + private Fixture() { + when(repository.findTerminal(any(UUID.class))) + .thenAnswer(invocation -> Optional.ofNullable(terminal.get())); + } + + private void store(GameLogicGameplayRuleIntakeTerminal value) { + terminal.set(value); + } + } +} From 8e8b4c39ff1fc736f91f9034074c7c4f3ca77944 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 20:00:23 +1300 Subject: [PATCH 046/129] Add genuine selected source receipt and PostgreSQL module proof --- ...esWalModuleFeasibilityIntegrationTest.java | 210 +++++ .../AccountControlUiOriginalOrderFixture.java | 9 + services/game-design-service/build.gradle.kts | 1 + ...ameLogicIntakePostgresIntegrationTest.java | 873 ++++++++++++++++++ 4 files changed, 1093 insertions(+) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresWalModuleFeasibilityIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresWalModuleFeasibilityIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresWalModuleFeasibilityIntegrationTest.java new file mode 100644 index 0000000000..4550a3dcdf --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresWalModuleFeasibilityIntegrationTest.java @@ -0,0 +1,210 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Disposable-image feasibility probe for the pg_walinspect module and a restricted wrapper reader. + * + *

This verifies only server-major, packaged module, installation, and role-permission behavior + * in the selected images. It does not establish transaction durability, recover an original + * acknowledgement, or prove failover behavior. + */ +@Testcontainers(disabledWithoutDocker = true) +@Execution(ExecutionMode.SAME_THREAD) +class AccountPostgresWalModuleFeasibilityIntegrationTest { + private static final String POSTGRES_18_IMAGE = + "postgres:18@sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336"; + + @Container + static final PostgreSQLContainer POSTGRES_16 = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static final PostgreSQLContainer POSTGRES_18 = new PostgreSQLContainer<>(POSTGRES_18_IMAGE); + + @Test + void postgres16AlpineHasInstallableWalInspectAndRestrictedReaderWrapper() throws SQLException { + assertImageFeasibility(POSTGRES_16, 16); + } + + @Test + void pinnedPostgres18HasInstallableWalInspectAndRestrictedReaderWrapper() throws SQLException { + assertImageFeasibility(POSTGRES_18, 18); + } + + @SuppressFBWarnings( + value = "SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE", + justification = + "Only a canonical UUID generated for this disposable fixture is interpolated as its ephemeral reader password.") + private static void assertImageFeasibility(PostgreSQLContainer postgres, int expectedMajor) + throws SQLException { + String lowerLsn; + String upperLsn; + String readerPassword = UUID.randomUUID().toString(); + try (Connection admin = connect(postgres, postgres.getUsername(), postgres.getPassword())) { + assertThat(integer(admin, "SELECT current_setting('server_version_num')::integer")) + .isBetween(expectedMajor * 10_000, expectedMajor * 10_000 + 9_999); + assertThat( + string( + admin, + "SELECT default_version FROM pg_available_extensions " + + "WHERE name = 'pg_walinspect'")) + .isNotBlank(); + assertThat( + integer( + admin, + "SELECT count(*) FROM pg_available_extension_versions " + + "WHERE name = 'pg_walinspect' AND version = '1.1'")) + .isEqualTo(1); + + execute( + admin, + "CREATE ROLE wal_feasibility_owner NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT"); + execute( + admin, + "CREATE ROLE wal_feasibility_reader LOGIN PASSWORD '" + + readerPassword + + "' " + + "NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT"); + execute(admin, "CREATE SCHEMA wal_proof_extension"); + execute(admin, "REVOKE ALL ON SCHEMA wal_proof_extension FROM PUBLIC"); + execute(admin, "CREATE SCHEMA wal_feasibility"); + execute(admin, "GRANT USAGE, CREATE ON SCHEMA wal_feasibility TO wal_feasibility_owner"); + execute(admin, "GRANT USAGE ON SCHEMA wal_proof_extension TO wal_feasibility_owner"); + execute( + admin, "CREATE EXTENSION pg_walinspect WITH SCHEMA wal_proof_extension VERSION '1.1'"); + execute( + admin, + "REVOKE ALL ON FUNCTION " + + "wal_proof_extension.pg_get_wal_records_info(pg_lsn, pg_lsn) FROM PUBLIC"); + execute( + admin, + "GRANT EXECUTE ON FUNCTION " + + "wal_proof_extension.pg_get_wal_records_info(pg_lsn, pg_lsn) " + + "TO wal_feasibility_owner"); + assertThat( + string( + admin, + "SELECT extversion FROM pg_extension e JOIN pg_namespace n " + + "ON n.oid = e.extnamespace WHERE e.extname = 'pg_walinspect' " + + "AND n.nspname = 'wal_proof_extension'")) + .isEqualTo("1.1"); + + execute(admin, "CREATE TABLE wal_feasibility.probe (value text NOT NULL)"); + lowerLsn = string(admin, "SELECT pg_current_wal_insert_lsn()::text"); + execute(admin, "INSERT INTO wal_feasibility.probe VALUES ('module-feasibility-probe')"); + upperLsn = string(admin, "SELECT pg_current_wal_insert_lsn()::text"); + assertThat(bool(admin, "SELECT ?::pg_lsn < ?::pg_lsn", lowerLsn, upperLsn)).isTrue(); + + execute( + admin, + "CREATE FUNCTION wal_feasibility.read_records(start_lsn pg_lsn, end_lsn pg_lsn) " + + "RETURNS bigint LANGUAGE SQL SECURITY DEFINER SET search_path = pg_catalog " + + "AS $$ SELECT count(*) FROM " + + "wal_proof_extension.pg_get_wal_records_info(start_lsn, end_lsn) $$"); + execute( + admin, + "ALTER FUNCTION wal_feasibility.read_records(pg_lsn, pg_lsn) " + + "OWNER TO wal_feasibility_owner"); + execute( + admin, "REVOKE ALL ON FUNCTION wal_feasibility.read_records(pg_lsn, pg_lsn) FROM PUBLIC"); + execute( + admin, + "GRANT EXECUTE ON FUNCTION wal_feasibility.read_records(pg_lsn, pg_lsn) " + + "TO wal_feasibility_reader"); + execute(admin, "GRANT USAGE ON SCHEMA wal_feasibility TO wal_feasibility_reader"); + assertThat( + bool( + admin, + "SELECT has_function_privilege('wal_feasibility_reader', " + + "'wal_proof_extension.pg_get_wal_records_info(pg_lsn,pg_lsn)', 'EXECUTE')")) + .isFalse(); + assertThat( + bool( + admin, + "SELECT has_schema_privilege('wal_feasibility_reader', " + + "'wal_proof_extension', 'USAGE')")) + .isFalse(); + execute(admin, "GRANT USAGE ON SCHEMA wal_proof_extension TO wal_feasibility_reader"); + } + + try (Connection reader = connect(postgres, "wal_feasibility_reader", readerPassword)) { + assertThat(bool(reader, "SELECT pg_has_role(current_user, 'pg_read_server_files', 'MEMBER')")) + .isFalse(); + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> + integer( + reader, + "SELECT count(*) FROM " + + "wal_proof_extension.pg_get_wal_records_info(?::pg_lsn, ?::pg_lsn)", + lowerLsn, + upperLsn)) + .isInstanceOf(SQLException.class) + .hasMessageContaining("permission denied for function"); + assertThat( + integer( + reader, + "SELECT wal_feasibility.read_records(?::pg_lsn, ?::pg_lsn)::integer", + lowerLsn, + upperLsn)) + .isGreaterThan(0); + } + } + + private static Connection connect(PostgreSQLContainer postgres, String user, String password) + throws SQLException { + return DriverManager.getConnection(postgres.getJdbcUrl(), user, password); + } + + private static void execute(Connection connection, String sql) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } + + private static String string(Connection connection, String sql, Object... parameters) + throws SQLException { + try (var statement = connection.prepareStatement(sql)) { + for (int i = 0; i < parameters.length; i++) statement.setObject(i + 1, parameters[i]); + try (ResultSet result = statement.executeQuery()) { + if (!result.next()) throw new SQLException("Expected one PostgreSQL result row"); + return result.getString(1); + } + } + } + + private static int integer(Connection connection, String sql, Object... parameters) + throws SQLException { + try (var statement = connection.prepareStatement(sql)) { + for (int i = 0; i < parameters.length; i++) statement.setObject(i + 1, parameters[i]); + try (ResultSet result = statement.executeQuery()) { + if (!result.next()) throw new SQLException("Expected one PostgreSQL result row"); + return result.getInt(1); + } + } + } + + private static boolean bool(Connection connection, String sql, Object... parameters) + throws SQLException { + try (var statement = connection.prepareStatement(sql)) { + for (int i = 0; i < parameters.length; i++) statement.setObject(i + 1, parameters[i]); + try (ResultSet result = statement.executeQuery()) { + if (!result.next()) throw new SQLException("Expected one PostgreSQL result row"); + return result.getBoolean(1); + } + } + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 53930ddc50..b92080afbc 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -206,6 +206,15 @@ public UUID tenantId() { .create(namespace, original, originalCreator.compact()); } + /** Exact creator evidence retained by prepareOriginalDraftOrder, without issuing it twice. */ + IssuedCreator preparedOriginalCreator() { + if (originalCreator == null) { + throw new IllegalStateException( + "Prepare the original Draft order before reading its creator"); + } + return originalCreator; + } + /** Real unregistered Account producer, with Account-internal environment capture. */ public io.grpc.BindableService originalDraftOrderProducer(String namespace) { return new AccountOriginalDraftOrderGrpcService( diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index e15ab6624c..8f854a2324 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -25,6 +25,7 @@ testing { dependencies { integrationTestImplementation(project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof"))) + integrationTestImplementation(project(":game-logic-service")) compileOnly(libs.spotbugs.annotations) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java new file mode 100644 index 0000000000..a6b555d833 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java @@ -0,0 +1,873 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.BindableService; +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.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 java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GrpcAccountGameLogicIntakeSettlementReadClient; +import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeAuthorizationClient; +import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeRetainClient; +import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeSourceReadClient; +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.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOperation; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcomeRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.draft.GameDesignSourceCommitService; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadGrpcService; +import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadService; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; +import net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicIntakeCommandService; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptService; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeGrpcService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeRepository; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadGrpcService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadService; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real GD Account-ordered typed gameplay source through selection, Account intake, GL terminal, + * Account settlement and the immutable V61 GD receipt. The Account current actor and original + * terminal readback are real; only the fixture's exact current Redis registry bytes are replayed to + * the source-permission read owner. Loopback owner calls use test-only mutual TLS identities. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GenuineSelectedGameLogicIntakePostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer ACCOUNT_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("genuine-intake-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer REPLICA = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(REDIS) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "genuine-intake-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void genuineSourceSelectionIntakeSettlementAndExactRecoveryRetainOneReceipt() throws Exception { + var local = gameDesignLocal(); + var gameLogic = gameLogicStore(); + try (var account = + new AccountControlUiOriginalOrderFixture( + ACCOUNT_POSTGRES.getJdbcUrl(), + ACCOUNT_POSTGRES.getUsername(), + ACCOUNT_POSTGRES.getPassword(), + REDIS.getHost(), + REDIS.getMappedPort(6379), + temporary.resolve("account"), + local.target().canonicalTenantId())) { + var originalRequest = + account.prepareOriginalDraftOrder(binding(local, "genuine-admission"), NAMESPACE); + var accountAccess = account.preparedOriginalCreator(); + var original = originalRequest.original(); + var credential = originalRequest.originalCreatorCredential(); + var originalActor = + accountAccess + .actors() + .withCurrent( + credential, + local.target().canonicalTenantId(), + accountAccess.environment(), + current -> + new ActiveRegistry( + current.stored().tokenHash, current.stored().activeRegistry.clone())); + + var registry = mock(AccountControlUiCoordination.class); + when(registry.readActive(originalActor.tokenHash())).thenReturn(originalActor.bytes()); + var accountRepository = + new AccountGameLogicIntakeAuthorizationRepository(accountAccess.sources().dsl); + var accountSourcePermissionOwner = + new AccountGameLogicIntakeSourceReadService( + accountRepository, + registry, + accountAccess.sources().manager, + Clock.systemUTC(), + NAMESPACE); + var accountHeldReadOwner = + new AccountGameLogicIntakeAuthorizationReadService( + accountRepository, accountAccess.sources().manager, NAMESPACE); + + var endpoints = new ServiceEndpointsProperties(); + var pki = new TestPki(temporary.resolve("pki")); + var accountToGameDesignSource = + new GameplayRuleSourceReadClient( + endpoints, + pki.accountClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToAccountPermission = + new GrpcGameLogicIntakeSourceReadClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameLogicToAccountHeld = + new GameLogicIntakeAuthorizationReadClient( + endpoints, + pki.gameLogicClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameLogicToGameDesignSource = + new GameplayRuleSourceReadClient( + endpoints, + pki.gameLogicClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var accountToGameLogicTerminal = + new GameLogicIntakeTerminalReadClient( + endpoints, + pki.accountClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToAccountAuthorization = + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToGameLogicRetain = + new GrpcGameLogicIntakeRetainClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToAccountSettlement = + new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var originalOrderClient = + new AccountOriginalDraftOrderClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var originalTerminalClient = + new GameDesignDraftTerminalReadClient( + endpoints, + pki.accountClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + + var gameDesignSourceOwner = + new GameDesignGameplayRuleSourceReadService( + new GameplayRuleSourceRepository(local.dsl()), + local.transactions(), + gameDesignToAccountPermission, + NAMESPACE); + var gameDesignTerminalOwner = new GameDesignDraftTerminalOutcomeRepository(local.dsl()); + var gameDesignSourceReads = new AtomicInteger(); + var gameDesignTerminalReads = new AtomicInteger(); + Server accountServer = null; + Server gameDesignServer = null; + Server gameLogicServer = null; + try { + var accountAuthorizationOwner = + new AccountGameLogicIntakeAuthorizationService( + accountAccess.actors(), + accountAccess.sources().fences, + accountRepository, + accountToGameDesignSource, + accountAccess.sources().manager, + NAMESPACE); + var accountSettlementOwner = + new AccountGameLogicIntakeSettlementService( + accountRepository, + accountToGameLogicTerminal, + accountAccess.sources().manager, + NAMESPACE); + accountServer = + startServer( + pki, + pki.accountServer(), + Map.of(), + account.originalDraftOrderProducer(NAMESPACE), + new AccountGameLogicIntakeAuthorizationGrpcService( + accountAuthorizationOwner, accountAccess.sources().terms, NAMESPACE), + new AccountGameLogicIntakeSourceReadGrpcService( + accountSourcePermissionOwner, NAMESPACE), + new AccountGameLogicIntakeAuthorizationReadGrpcService( + accountHeldReadOwner, NAMESPACE), + new AccountGameLogicIntakeSettlementGrpcService(accountSettlementOwner, NAMESPACE)); + endpoints.setAccountService(loopback(accountServer)); + + gameDesignServer = + startServer( + pki, + pki.gameDesignServer(), + Map.of( + "readselectedgameplayrulesource", gameDesignSourceReads, + "readgamedesigndraftterminaloutcome", gameDesignTerminalReads), + new GameDesignGameplayRuleSourceReadGrpcService(gameDesignSourceOwner, NAMESPACE), + new GameDesignDraftTerminalReadGrpcService(gameDesignTerminalOwner, NAMESPACE)); + endpoints.setGameDesignService(loopback(gameDesignServer)); + + var gameLogicRepository = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); + var gameLogicOwner = + new GameLogicGameplayRuleIntakeService( + gameLogicRepository, + gameLogic.transactions(), + gameLogicToAccountHeld, + gameLogicToGameDesignSource, + NAMESPACE); + var gameLogicTerminalReads = new AtomicInteger(); + gameLogicServer = + startServer( + pki, + pki.gameLogicServer(), + Map.of("readgameplayruleintaketerminal", gameLogicTerminalReads), + new GameLogicGameplayRuleIntakeGrpcService(gameLogicOwner, NAMESPACE), + new GameLogicGameplayRuleIntakeTerminalReadGrpcService( + new GameLogicGameplayRuleIntakeTerminalReadService( + gameLogicRepository, NAMESPACE), + NAMESPACE)); + endpoints.setGameLogicService(loopback(gameLogicServer)); + + try (accountToGameDesignSource; + gameDesignToAccountPermission; + gameLogicToAccountHeld; + gameLogicToGameDesignSource; + accountToGameLogicTerminal; + gameDesignToAccountAuthorization; + gameDesignToGameLogicRetain; + gameDesignToAccountSettlement; + originalOrderClient; + originalTerminalClient) { + accountToGameDesignSource.init(); + gameDesignToAccountPermission.init(); + gameLogicToAccountHeld.init(); + gameLogicToGameDesignSource.init(); + accountToGameLogicTerminal.init(); + gameDesignToAccountAuthorization.init(); + gameDesignToGameLogicRetain.init(); + gameDesignToAccountSettlement.init(); + originalOrderClient.init(); + originalTerminalClient.init(); + + var commitService = + new GameDesignSourceCommitService( + originalOrderClient, + new DraftCommitCoordinatorRepository(local.dsl()), + new GameDesignDraftTerminalOutcomeRepository(local.dsl()), + new GameDesignSourceRepository(local.dsl()), + local.transactions(), + NAMESPACE); + var originalTerminal = commitService.commit(original, credential); + assertThat(originalTerminal.result()) + .isEqualTo( + net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcome.Result + .COMMITTED); + assertThat(originalTerminal.operation().accountBindingBytes()) + .containsExactly(originalRequest.originalAccountBinding()); + assertSynchronizedSource(local, original); + account.assertOriginalDraftOrderPending(original); + + account.reconcileOriginalDraft( + original, + originalTerminalClient, + mock(WorldDraftTerminalReadClient.class), + NAMESPACE); + assertThat(gameDesignTerminalReads).hasValue(1); + assertThat(gameDesignSourceReads).hasValue(0); + + var selection = reserveSelection(local, original); + var receiptOwner = + new SelectedDraftGameLogicReceiptService( + local.dsl(), + local.transactions(), + gameDesignToGameLogicRetain, + gameDesignToAccountSettlement, + NAMESPACE); + var authorizationCalls = new AtomicInteger(); + var lostFirstResponse = new AtomicBoolean(); + GameLogicIntakeAuthorizationClient lostResponseClient = + new GameLogicIntakeAuthorizationClient() { + @Override + public GameLogicIntakeAuthorizationEvidence.Result authorize( + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential) { + authorizationCalls.incrementAndGet(); + var response = + gameDesignToAccountAuthorization.authorize( + request, originalCreatorCredential); + if (lostFirstResponse.compareAndSet(false, true)) + throw new IllegalStateException( + "test-only lost Account authorization response"); + return response; + } + + @Override + public GameLogicIntakeAuthorizationEvidence.Result recover( + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential) { + return gameDesignToAccountAuthorization.recover( + request, originalCreatorCredential); + } + + @Override + public GameLogicIntakeAuthorizationEvidence.Result abort( + GameLogicIntakeAuthorizationEvidence.Request request, + String originalCreatorCredential) { + return gameDesignToAccountAuthorization.abort(request, originalCreatorCredential); + } + }; + var command = + new SelectedDraftGameLogicIntakeCommandService( + local.dsl(), lostResponseClient, receiptOwner, NAMESPACE); + var wrongSourceRequest = + GameLogicIntakeAuthorizationEvidence.Request.create( + NAMESPACE, UUID.randomUUID(), binding(local, "substituted-admission")); + assertThatThrownBy( + () -> command.authorizeAndRetain(selection, wrongSourceRequest, credential)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("selected Draft binding"); + assertThat(authorizationCalls).hasValue(0); + assertThat(gameDesignSourceReads).hasValue(0); + + var request = + GameLogicIntakeAuthorizationEvidence.Request.create( + NAMESPACE, UUID.randomUUID(), selection.selectedCommit()); + assertThatThrownBy(() -> command.authorizeAndRetain(selection, request, credential)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Account intake authorization denied or unavailable"); + assertThat(authorizationCalls).hasValue(1); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount(DSL.table("account_game_logic_intake_authorizations"))) + .isEqualTo(1); + assertThat(gameDesignSourceReads).hasValue(1); + + SelectedDraftGameLogicReceipt recovered = + command.recoverAndRetain(selection, request, credential); + assertThat(recovered.authorization().source().binding().canonicalBytes()) + .containsExactly(selection.selectedCommit().canonicalBytes()); + assertThat(recovered.receipt().terminal().outcome()) + .isEqualTo( + net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal + .Outcome.RETAINED); + assertThat(gameDesignSourceReads).hasValue(2); + assertThat(gameLogicTerminalReads).hasValue(1); + + var retry = command.recoverAndRetain(selection, request, credential); + assertThat(retry.selection().canonicalBytes()) + .containsExactly(recovered.selection().canonicalBytes()); + assertThat(retry.authorization().canonicalBytes()) + .containsExactly(recovered.authorization().canonicalBytes()); + assertThat(retry.receipt().canonicalBytes()) + .containsExactly(recovered.receipt().canonicalBytes()); + assertThat(gameDesignSourceReads).hasValue(2); + assertThat(gameLogicTerminalReads).hasValue(1); + var retainedReceipt = + new SelectedDraftGameLogicReceiptRepository(local.dsl()) + .read(selection, recovered.authorization()) + .orElseThrow(); + assertThat(retainedReceipt.selection().canonicalBytes()) + .containsExactly(recovered.selection().canonicalBytes()); + assertThat(retainedReceipt.authorization().canonicalBytes()) + .containsExactly(recovered.authorization().canonicalBytes()); + assertThat(retainedReceipt.receipt().canonicalBytes()) + .containsExactly(recovered.receipt().canonicalBytes()); + assertThat( + gameLogicRepository + .findTerminal(recovered.authorization().operationId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(recovered.receipt().terminal().canonicalBytes()); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount(DSL.table("account_game_logic_intake_settlements"))) + .isEqualTo(1); + assertThat( + gameLogic.dsl().fetchCount(DSL.table("game_logic_gameplay_rule_intake_terminal"))) + .isEqualTo(1); + assertThat(local.dsl().fetchCount(DSL.table("game_design_selected_game_logic_receipt"))) + .isEqualTo(1); + assertThat( + accountAccess + .sources() + .tx(() -> accountAccess.sources().fences.readSettlement(original))) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.COMMITTED); + } + } finally { + stop(gameLogicServer); + stop(gameDesignServer); + stop(accountServer); + } + } + } + + private AuthoredDraftPublishSelection reserveSelection( + Local local, DraftAuthorizationFenceBinding original) { + var tx = transaction(local); + var selected = new GameDesignDraftTerminalOperation(original).gameDesignBinding(); + return tx.execute( + ignored -> + new AuthoredDraftPublishSelectionRepository( + local.dsl(), new DraftCommitCoordinatorRepository(local.dsl())) + .reserve( + new AuthoredDraftPublishSelection.PublishIntent( + local.target().canonicalTenantId(), + local.target().canonicalVersionId(), + UUID.randomUUID().toString(), + "1", + "genuine source receipt proof", + selected.requestId(), + selected.commitId(), + selected.digest())) + .selection()); + } + + private static void assertSynchronizedSource( + Local local, DraftAuthorizationFenceBinding original) { + var snapshot = + new GameDesignSourceRepository(local.dsl()) + .readSynchronized(local.target(), original.commitId()) + .orElseThrow(); + assertThat( + snapshot + .gameplay() + .manifest() + .families() + .get(GameplayRuleManifest.Family.ADMISSION_TAGS)) + .hasSize(1); + assertThat(snapshot.gameplay().binding().canonicalBytes()) + .containsExactly(original.gameDesignBinding()); + } + + private Local gameDesignLocal() { + var schema = "game_design_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + data.setSchema(schema); + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design") + .placeholders(Map.of("serviceSchema", schema)) + .locations(migrationLocation("game-design")) + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(data); + var game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Genuine selected intake Game"); + game.setDescription("Persisted Game Design identity and source provenance"); + var savedGame = + java.util.Objects.requireNonNull( + transaction(manager).execute(ignored -> new GameRepository(dsl).save(game))); + var version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + var saved = + java.util.Objects.requireNonNull( + transaction(manager).execute(ignored -> new VersionRepository(dsl).save(version))); + var target = + new DraftCommitBinding.TargetProof( + saved.getCanonicalTenantId(), + saved.getCanonicalVersionId(), + saved.getId(), + saved.getTenantId(), + saved.getIdentitySourceGameRowId(), + saved.getIdentitySourceGameTenantKey(), + saved.getIdentitySourceProvenanceKind()); + assertThat(new GameplayRuleSourceRepository(dsl).readGenesis(target)).isPresent(); + return new Local(dsl, manager, target); + } + + private GameLogicStore gameLogicStore() { + var schema = "game_logic_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + data.setSchema(schema); + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_logic") + .placeholders(Map.of("serviceSchema", schema)) + .locations(migrationLocation("game-logic")) + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + return new GameLogicStore(dsl, new DataSourceTransactionManager(data)); + } + + private DraftCommitBinding binding(Local local, String admissionTag) { + return DraftCommitBinding.create( + local.target(), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload( + new GameplayRuleManifest.AdmissionTag(admissionTag)))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + local.target().canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + "effective", + "0"))); + } + + private static TransactionTemplate transaction(Local local) { + return transaction(local.transactions()); + } + + private static TransactionTemplate transaction(DataSourceTransactionManager manager) { + var tx = new TransactionTemplate(manager); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return tx; + } + + private static String migrationLocation(String service) { + var directoryName = service + "-service"; + var current = Path.of("").toAbsolutePath(); + while (current != null) { + var migrations = + current + .resolve("services") + .resolve(directoryName) + .resolve("src/main/resources/db/migration"); + if (Files.isDirectory(migrations)) return "filesystem:" + migrations; + current = current.getParent(); + } + throw new IllegalStateException("Service migration directory is unavailable: " + service); + } + + private static Server startServer( + TestPki pki, + TestIdentity identity, + Map methodCounts, + BindableService... services) + throws Exception { + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(20 * 1024 * 1024) + .maxInboundMetadataSize(AccountOriginalDraftOrderGrpcCodec.MAX_METADATA_BYTES) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + for (var service : services) + builder.addService( + ServerInterceptors.intercept( + service, new GrpcPeerIdentityInterceptor(), countingInterceptor(methodCounts))); + return builder.build().start(); + } + + private static ServerInterceptor countingInterceptor(Map methodCounts) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + String method = call.getMethodDescriptor().getFullMethodName().toLowerCase(Locale.ROOT); + methodCounts.forEach( + (fragment, count) -> { + if (method.contains(fragment)) count.incrementAndGet(); + }); + return next.startCall(call, headers); + } + }; + } + + private static String loopback(Server server) { + return "127.0.0.1:" + server.getPort(); + } + + private static void stop(Server server) throws InterruptedException { + if (server == null) return; + server.shutdownNow(); + if (!server.awaitTermination(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Test owner server did not stop"); + } + + private record Local( + DSLContext dsl, + DataSourceTransactionManager transactions, + DraftCommitBinding.TargetProof target) {} + + private record GameLogicStore(DSLContext dsl, DataSourceTransactionManager transactions) {} + + private record ActiveRegistry(String tokenHash, byte[] bytes) {} + + private record TestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var result = new CommonGrpcClientProperties(); + result.setPlaintext(false); + result.setCertChain(certificate.toString()); + result.setPrivateKey(key.toString()); + result.setCaCert(ca.toString()); + return result; + } + } + + /** Ephemeral test CA and same-namespace Account, Game Design and Game Logic identities only. */ + private static final class TestPki { + private final Path ca; + private final TestIdentity accountServer; + private final TestIdentity accountClient; + private final TestIdentity gameDesignServer; + private final TestIdentity gameDesignClient; + private final TestIdentity gameLogicServer; + private final TestIdentity gameLogicClient; + + TestPki(Path root) throws Exception { + Files.createDirectories(root); + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var caKeys = generator.generateKeyPair(); + var caName = new org.bouncycastle.asn1.x500.X500Name("CN=Test-only genuine intake proof CA"); + var now = java.time.Instant.now(); + var caBuilder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caName, + java.math.BigInteger.ONE, + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + caName, + caKeys.getPublic()); + caBuilder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(true)); + caBuilder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage(org.bouncycastle.asn1.x509.KeyUsage.keyCertSign)); + var caCertificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + caBuilder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + ca = pem(root.resolve("ca.pem"), caCertificate); + accountServer = issue(root, "account-service", true, caKeys, caCertificate); + accountClient = issue(root, "account-service", false, caKeys, caCertificate); + gameDesignServer = issue(root, "game-design-service", true, caKeys, caCertificate); + gameDesignClient = issue(root, "game-design-service", false, caKeys, caCertificate); + gameLogicServer = issue(root, "game-logic-service", true, caKeys, caCertificate); + gameLogicClient = issue(root, "game-logic-service", false, caKeys, caCertificate); + } + + Path ca() { + return ca; + } + + TestIdentity accountServer() { + return accountServer; + } + + TestIdentity accountClient() { + return accountClient; + } + + TestIdentity gameDesignServer() { + return gameDesignServer; + } + + TestIdentity gameDesignClient() { + return gameDesignClient; + } + + TestIdentity gameLogicServer() { + return gameLogicServer; + } + + TestIdentity gameLogicClient() { + return gameLogicClient; + } + + private static TestIdentity issue( + Path root, + String service, + boolean server, + java.security.KeyPair caKeys, + java.security.cert.X509Certificate caCertificate) + throws Exception { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var keys = generator.generateKeyPair(); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caCertificate, + new java.math.BigInteger(120, new java.security.SecureRandom()), + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + new org.bouncycastle.asn1.x500.X500Name("CN=" + service), + keys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(false)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + false, + new org.bouncycastle.asn1.x509.KeyUsage( + org.bouncycastle.asn1.x509.KeyUsage.digitalSignature + | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.extendedKeyUsage, + false, + new org.bouncycastle.asn1.x509.ExtendedKeyUsage( + server + ? org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_serverAuth + : org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_clientAuth)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, + false, + new org.bouncycastle.asn1.x509.GeneralNames( + new org.bouncycastle.asn1.x509.GeneralName[] { + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.uniformResourceIdentifier, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.dNSName, "localhost"), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.iPAddress, "127.0.0.1") + })); + var certificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + builder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + String prefix = service + (server ? "-server" : "-client"); + return new TestIdentity( + pem(root.resolve(prefix + ".crt"), certificate), + pem(root.resolve(prefix + ".key"), keys.getPrivate())); + } + + private static Path pem(Path path, Object value) throws Exception { + try (var writer = + new org.bouncycastle.openssl.jcajce.JcaPEMWriter(Files.newBufferedWriter(path))) { + writer.writeObject(value); + } + return path; + } + } +} From 985134c18b00b0ba742a6625d849f380267b56da Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 20:47:12 +1300 Subject: [PATCH 047/129] Expose exact World source and release owner reads; repair physical proof fixtures --- .../game-design-service/api-contracts.md | 6 +- .../game-design-service/version-control.md | 4 +- .../world-management-service/api-contracts.md | 1 + design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 4 + ...esWalModuleFeasibilityIntegrationTest.java | 5 +- .../AccountControlUiOriginalOrderFixture.java | 11 +- ...uthoredWorldLaunchDescriptorGrpcCodec.java | 75 +++++ .../tenant/AuthoredWorldSourceGrpcCodec.java | 51 +++- ...thoredWorldLaunchDescriptorClientTest.java | 75 +++++ .../tenant/AuthoredWorldSourceClientTest.java | 247 +++++++++++++++ .../AuthoredWorldSourceGrpcCodecTest.java | 149 +++++++++ services/game-design-service/build.gradle.kts | 3 +- .../service/impl/GameDesignGrpcService.java | 162 ++++++++++ .../impl/TenantIdentityGrpcService.java | 114 ++++++- .../src/main/resources/application-prod.yml | 2 + .../src/main/resources/application.yml | 2 + ...ameLogicIntakePostgresIntegrationTest.java | 266 ++++++++-------- ...meLogicReceiptPostgresIntegrationTest.java | 21 +- ...emptServiceTransactionIntegrationTest.java | 30 ++ .../TenantIdentityGrpcAuthWiringTest.java | 39 ++- .../impl/GameDesignGrpcServiceAuthTest.java | 287 ++++++++++++++++++ .../GameDesignGrpcServiceHelpTopicTest.java | 2 + ...esignGrpcServiceSettingsAuthorityTest.java | 2 + .../impl/GameDesignGrpcServiceTest.java | 4 + .../impl/TenantIdentityGrpcServiceTest.java | 216 ++++++++++++- services/game-logic-service/build.gradle.kts | 14 + 27 files changed, 1635 insertions(+), 163 deletions(-) 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/AuthoredWorldSourceGrpcCodecTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index bedc3cef5c..93071ae7ea 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -14,10 +14,14 @@ The owner-local fresh-creation repository and exact Account/Game Session mTLS re Game Design issues each new game row an opaque canonical tenant UUID and keeps exact row/key provenance in that owner row. V29 preserves only well-shaped retained source keys with `RETAINED_GAME_V29` provenance; new rows receive `NEW_GAME_ROW` provenance. V30 adds the immutable operation receipt for an exact fresh-creation request. Neither a legacy tenant string nor this owner evidence is an Account identity association, membership grant, JOIN decision, or caller authorization. -`TenantIdentityService.ResolveFreshTenantCreation` is a read-only receipt lookup for the exact same-namespace `account-service` or `game-session-service` mTLS peer. It accepts a canonical non-nil `creation_request_id` plus `expected_request_digest` and returns the exact persisted operation, request, UUID, source-row/key, provenance, and evidence digest, including the stored `request_digest`. The bearer-token bypass is limited to this read RPC and does not replace that peer check; an authenticated player caller context is rejected even on an otherwise permitted peer. Unknown request fields, absent or inconsistent evidence, and digest mismatches fail closed. +`TenantIdentityService.ResolveFreshTenantCreation` is a read-only receipt lookup for the exact same-namespace `account-service` or `game-session-service` mTLS peer. It accepts a canonical non-nil `creation_request_id` plus `expected_request_digest` and returns the exact persisted operation, request, UUID, source-row/key, provenance, and evidence digest, including the stored `request_digest`. The bearer-token bypass is explicitly allowlisted per owner-read method and does not replace this method's peer check; an authenticated player caller context is rejected even on an otherwise permitted peer. Unknown request fields, absent or inconsistent evidence, and digest mismatches fail closed. `GameTenantCreationDigest` binds request and receipt fields using domain-separated, length-prefixed UTF-8 segments before SHA-256. Optional descriptions have an explicit presence marker. Malformed Unicode, including unpaired surrogates, is rejected before digesting rather than replaced; changed fields change the digest, and values are not normalized into a guessed selector. +### Authored-World Source Readback + +`TenantIdentityService.ResolveAuthoredWorldSource` is a separate read-only owner lookup for the exact retained Game Design source operation used by World Management's authored-world intake construction. Its closed request contains a canonical non-nil read correlation UUID, source operation UUID, canonical tenant UUID, and exact canonical `world_slug`; the receiver supplies the trusted namespace from its own configuration. The handler authenticates the exact same-namespace `world-management-service` TLS peer and rejects authenticated caller context before parsing the request or reading storage. Unknown fields, malformed or nil identifiers, noncanonical selectors, and missing or inconsistent source evidence fail closed. Success echoes the read correlation and returns the complete retained registration receipt, including its request and evidence digests, canonical tenant and slugs, display name, and source-row provenance. The owner recomputes both digests from the full tuple and checks the source against the persisted Game Design tenant row; a read does not allocate, repair, register, or activate source state. World must authenticate the Game Design server and validate the full response echo, selector, immutable fields, and recomputed digests before retaining that exact evidence. This read is not creator authentication, World registration, source-write authorization, launch permission, or runtime admission. + `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. ## Official Hosted Creator Mutation Gate diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index b9385e5810..e189bd5f1a 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -144,7 +144,9 @@ For the Game Logic full-version read, Game Design derives the separate [exact re #### Launch and attestation read authorization (target state) -Launch and release-attestation reads are owner-to-owner control-plane APIs, not a generic internal-service read class. Each RPC must have an explicit authenticated workload allowlist and bind the caller's authorized tenant/scope to the request before reading data; a bearer that merely declares `isInternalService` is insufficient. The target launch/read allowlist is: `ResolveLaunchDescriptor` — Game Session only; `GetTemplateReferencePhase` — Game Session for launch preflight and the explicitly named Game Design/retirement-control-plane workload for cutover tooling; `GetPublishedReleaseBundle` — Game Session, World Management, and Automation & Scripting; `GetVersionState` and `GetVersionAssetArtifactState` — Game Session and World Management for launch/activation reads. `GetVersionAssetArtifactState` also has a separate operator-diagnostic use: Logging & Admin may broker an authenticated read for operators, and CI/runbook automation may use only a dedicated named operator-read workload identity (or the Logging & Admin operator surface), never a generic internal-service bearer. That operator path is diagnostic evidence and does not grant launch or mutation authority. Each request must exact-bind its tenant and version/template/request scope (including source/target versions where present), and the owner must reject a wrong workload, cross-tenant scope, omitted scope, or changed replay identity before returning a descriptor, attestation, lifecycle state, or artifact state. Focused proof must exercise every allowlisted caller and a denied internal workload plus cross-tenant requests for each RPC, including the separate operator-read path where it is implemented. +Launch and release-attestation reads are owner-to-owner control-plane APIs, not a generic internal-service read class. Each RPC must have an explicit authenticated workload allowlist and bind the caller's authorized tenant/scope to the request before reading data; a bearer that merely declares `isInternalService` is insufficient. The target launch/read allowlist is: `ResolveLaunchDescriptor` — Game Session only; `GetTemplateReferencePhase` — Game Session for launch preflight and the explicitly named Game Design/retirement-control-plane workload for cutover tooling; `GetPublishedReleaseBundle` — Game Session, World Management, and Automation & Scripting; `GetVersionState` and `GetVersionAssetArtifactState` — Game Session and World Management for launch/activation reads; `GetCompleteLaunchBinding` — World Management for the complete authored-world launch descriptor and immutable release-attestation read. `GetVersionAssetArtifactState` also has a separate operator-diagnostic use: Logging & Admin may broker an authenticated read for operators, and CI/runbook automation may use only a dedicated named operator-read workload identity (or the Logging & Admin operator surface), never a generic internal-service bearer. That operator path is diagnostic evidence and does not grant launch or mutation authority. Each request must exact-bind its tenant and version/template/request scope (including source/target versions where present), and the owner must reject a wrong workload, cross-tenant scope, omitted scope, or changed replay identity before returning a descriptor, attestation, lifecycle state, or artifact state. Focused proof must exercise every allowlisted caller and a denied internal workload plus cross-tenant requests for each RPC, including the separate operator-read path where it is implemented. + +The `GetCompleteLaunchBinding` transport dispatch does not authorize launch: its handler requires the exact same-namespace World Management TLS peer before parsing or owner reads. Genuine persisted-release, mounted-certificate and activation proof remain tracked in [authoring and activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). In addition to domain-service digests, publish safety requires a Game Design control-plane digest: diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 86fcd2d7fe..ec3dd87a79 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -11,6 +11,7 @@ This API contract is target-state canonical; implementation coverage is partial - The registered `ApplyWorldDesignMutation` handler fails closed before parsing or owner mutation until current Account commit authorization is verified. This denial does not implement the positive authenticated Game Design/Account commit boundary or repair the separate legacy REST generation-rule gap. - The registered `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, `FailPreparedWorldInstance` and `TerminateWorldInstance` handlers allow only verified same-namespace Game Session workload identity before request parsing or owner calls. Missing configuration, missing peer identity and other workloads are denied; shared bearer claims do not substitute. Other pre-admission consumers are not currently allowlisted. This caller guard does not supply the remaining canonical preparation, activation, cleanup or admission proofs. - The standalone canonical initial-placement adapter now defines an Entity Management-only historical terminal-result read. Its proto and handler remain unregistered; the read supplies settlement evidence for the exact immutable placement operation, without admitting gameplay or directly mutating any hold. +- The authored-world intake construction reads its complete immutable Game Design source through the exact authenticated owner-read contract in [Game Design API Contracts](../game-design-service/api-contracts.md#authored-world-source-readback). The intake transport remains unregistered and does not authorize source mutation, instance preparation, publication, or runtime admission. - 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. ## gRPC APIs diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8e63b37930..9d7ae3832a 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -144,3 +144,9 @@ Entry format: - Observation: Saying validation was underway did not consume its terminal result or advance the assigned correction. A process identifier is not a wake-capable handoff. - Expected pattern: Remain with local validation through terminal evidence, integrate failures and continue safe assigned work. If a genuine interruption requires yielding, preserve the exact pending process and next action without describing it as completed work. - Current status: The terminal result was consumed, disjoint Common and Account fixture/transport corrections were delegated, and the parent resumed integration. No proof or completion credit was assigned to the failed gate. + +- `2026-10-09`: Cross-owner test dependencies can import another service's Flyway migrations + - Context: Document added Game Logic's ordinary project dependency to Game Design integration tests for a genuine source-to-receipt composition. Local compilation and checks passed with Docker-dependent cases skipped; required CI then failed Spring fixture startup with duplicate V1 migrations from both service jars. + - Observation: Successful compilation and skipped database tests did not establish a safe resolved resource classpath. Account already provided a resource-isolated opt-in proof artifact for this same cross-owner testing boundary. + - Expected pattern: Consume an opt-in classes-only proof artifact when another service's owner classes are needed. Keep each owner migration directory explicit in composed fixtures; do not suppress Flyway checks or change production resource scanning to accommodate tests. + - Current status: Game Logic's resource-isolated proof artifact and its Game Design consumer are prepared. Resolved artifact inspection and corrected-head physical PostgreSQL execution remain required; no production migration or activation guard changed. 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 5d0a09e5db..9327e58b5b 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 @@ -108,12 +108,16 @@ The unregistered [selected-Draft owner](../../../services/game-design-service/sr Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. +Game Design now has a callable `GetCompleteLaunchBinding` handler and strict descriptor/release-attestation codec for the World Management read path. Its exact-method bearer-interceptor bypass is only transport dispatch: the handler still denies absent, wrong-service, or wrong-namespace TLS peers before parsing or owner reads. Corrected-state Common/Game Design checks, handler/auth-wiring and codec units, and the Game Design boot JAR pass locally; no genuine positive persisted release/attestation read, mounted-certificate transport proof, or launch activation is claimed. World Management owns exact binding persistence and preparation; Gameplay owns Game Session launch orchestration and its executable-front fixture. + Official-hosted creator-content acceptance remains partial under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Account's individual-party and hosted-terms repositories now retain exact catalog, affirmative-acceptance and environment-binding operations; `AccountHostedTermsService` can resolve the external environment observation before SQL work and reread locked currentness in a caller-owned writable `READ_COMMITTED` transaction. The service and its trusted publication, environment and affirmative-action participants remain unregistered; current creator authentication and original multi-owner commit enforcement are not supplied by these storage APIs. `HostedTermsEnvironmentBindingPostgresIntegrationTest` exercises explicitly test-only authorities, not a real agreement or operative hosted service. Composed-head PostgreSQL execution, live authority provisioning, creator UI, transfer and organization workflows remain separate proof or implementation gaps. These foundations do not upgrade the broader capability ratings or authorize content writes. ### Fresh-tenant identity prerequisite 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. +The adjacent authored-world source read now has an exact same-namespace World Management peer guard, closed request decoding, owner-local read of the retained operation, complete receipt/digest validation, and explicit Game Design auth-bypass wiring. Executed unit checks cover allowed and denied peers, caller-context denial, malformed/unknown fields, missing or substituted source, corrupt evidence and unavailable storage; Common client/codec checks cover exact echo and corruption denial. Corrected-state Common/Game Design checks pass locally, but PostgreSQL cases skip without Docker. No genuine end-to-end source registration, World intake, publication provenance, runtime registration, or activation proof is claimed. The canonical owner detail is in [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#authored-world-source-readback); World’s local consequence is in [World Management API contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status). + ### 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/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresWalModuleFeasibilityIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresWalModuleFeasibilityIntegrationTest.java index 4550a3dcdf..b463380c4b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresWalModuleFeasibilityIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresWalModuleFeasibilityIntegrationTest.java @@ -15,6 +15,7 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; /** * Disposable-image feasibility probe for the pg_walinspect module and a restricted wrapper reader. @@ -33,7 +34,9 @@ class AccountPostgresWalModuleFeasibilityIntegrationTest { static final PostgreSQLContainer POSTGRES_16 = new PostgreSQLContainer<>("postgres:16-alpine"); @Container - static final PostgreSQLContainer POSTGRES_18 = new PostgreSQLContainer<>(POSTGRES_18_IMAGE); + static final PostgreSQLContainer POSTGRES_18 = + new PostgreSQLContainer<>( + DockerImageName.parse(POSTGRES_18_IMAGE).asCompatibleSubstituteFor("postgres")); @Test void postgres16AlpineHasInstallableWalInspectAndRestrictedReaderWrapper() throws SQLException { diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index b92080afbc..e6af17e723 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -34,6 +34,7 @@ public final class AccountControlUiOriginalOrderFixture implements AutoCloseable private final AccountControlUiOwnerSourcesFixture f; private final AccountControlUiActorService actors; private final AccountControlUiIssuanceService issuance; + private final AccountControlUiCoordination coordination; private final RedisClient accountClient; private final Path temporary; private IssuedCreator originalCreator; @@ -139,7 +140,7 @@ public AccountControlUiOriginalOrderFixture( } finally { admin.shutdown(); } - var registry = + coordination = new AccountControlUiCoordination( () -> accountClient.connect(ByteArrayCodec.INSTANCE), new AccountGameplayDelegationRedisClient.AcknowledgementRequirements(1, 1, 5000), @@ -153,7 +154,7 @@ public AccountControlUiOriginalOrderFixture( operations, f.authority, lifecycle.signer, - registry, + coordination, publicSource, f.fences, f.manager, @@ -167,7 +168,7 @@ public AccountControlUiOriginalOrderFixture( lifecycle.signer, new AccountControlUiResponseCryptography( new AccountControlUiKeyring(temporary.resolve("custody")), Clock.systemUTC()), - registry, + coordination, actors, f.manager, Clock.systemUTC(), @@ -215,6 +216,10 @@ IssuedCreator preparedOriginalCreator() { return originalCreator; } + AccountControlUiCoordination coordination() { + return coordination; + } + /** Real unregistered Account producer, with Account-internal environment capture. */ public io.grpc.BindableService originalDraftOrderProducer(String namespace) { return new AccountOriginalDraftOrderGrpcService( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java index e60242dd9e..00d01b3410 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java @@ -179,6 +179,81 @@ public static CompleteLaunchBindingEvidence fromCompleteResponse( } } + /** Encodes and revalidates the exact immutable descriptor and release-attestation pair. */ + public static GetCompleteLaunchBindingResponse toCompleteResponse( + GetLaunchDescriptorRequest request, CompleteLaunchBindingEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + evidence.descriptor().requireValid(); + evidence.releaseAttestation().requireValid(evidence.descriptor()); + GetCompleteLaunchBindingResponse response = + GetCompleteLaunchBindingResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setLaunchDescriptor(toLaunchDescriptor(evidence.descriptor())) + .setReleaseAttestation(toReleaseAttestation(evidence.releaseAttestation())) + .build(); + fromCompleteResponse(request, response); + return response; + } + + private static LaunchDescriptor toLaunchDescriptor( + AuthoredWorldLaunchDescriptorEvidence evidence) { + evidence.requireValid(); + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.Builder binding = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setControlPlaneRequestId(evidence.controlPlaneRequestId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setWorldSlug(evidence.worldSlug()) + .setAuthoredWorldSourceOperationId(evidence.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()) + .setGameTemplateId(evidence.gameTemplateId()) + .setRequestDigest(evidence.requestDigest()) + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setVersionId(evidence.versionId()) + .setRuntimeFlagsJson(evidence.runtimeFlagsJson()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setReleaseBundleId(evidence.releaseBundleId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setResultDigest(evidence.resultDigest()); + if (evidence.requestedScriptPatchVersionPresent()) { + binding.setRequestedScriptPatchVersion(evidence.requestedScriptPatchVersion()); + } + if (evidence.sourceVersionIdPresent()) { + binding.setSourceVersionId(evidence.sourceVersionId()); + } + if (evidence.targetVersionIdPresent()) { + binding.setTargetVersionId(evidence.targetVersionId()); + } + if (evidence.requestedRuntimeFlagsJsonPresent()) { + binding.setRequestedRuntimeFlagsJson(evidence.requestedRuntimeFlagsJson()); + } + if (evidence.scriptPatchVersionPresent()) { + binding.setScriptPatchVersion(evidence.scriptPatchVersion()); + } + if (evidence.remapSetIdPresent()) { + binding.setRemapSetId(evidence.remapSetId()); + } + return LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setGameTemplateId(evidence.gameTemplateId()) + .setControlPlaneRequestId(evidence.controlPlaneRequestId()) + .setVersionId(evidence.versionId()) + .setScriptPatchVersion( + evidence.scriptPatchVersionPresent() ? evidence.scriptPatchVersion() : "") + .setRuntimeFlagsJson(evidence.runtimeFlagsJson()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setReleaseBundleId(evidence.releaseBundleId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setRemapSetId(evidence.remapSetIdPresent() ? evidence.remapSetId() : "") + .setAuthoredWorldBinding(binding.build()) + .build(); + } + /** Encodes the separate closed release attestation without changing descriptor/v1. */ public static net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence toReleaseAttestation(AuthoredWorldReleaseAttestationEvidence evidence) { 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 index a995782343..760f4f5351 100644 --- 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 @@ -40,6 +40,50 @@ public static ResolveAuthoredWorldSourceRequest toReadRequest(ReadRequest reques .build(); } + /** Decodes the exact owner-read selector using the receiver's locally configured namespace. */ + public static ReadRequest fromReadRequest( + String trustedNamespace, ResolveAuthoredWorldSourceRequest request) { + Objects.requireNonNull(request, "request"); + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Authored-world source request contains unsupported fields"); + } + try { + return new ReadRequest( + trustedNamespace, + parseCanonicalNonNilUuid(request.getRequestId(), "requestId"), + parseCanonicalNonNilUuid(request.getOperationId(), "operationId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Authored-world source request is invalid", exception); + } + } + + /** Encodes the exact immutable source receipt and the independent read identity. */ + public static ResolveAuthoredWorldSourceResponse toReadResponse( + ReadRequest request, AuthoredWorldSourceEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(evidence, "evidence"); + requireExactSelector(request, evidence); + return ResolveAuthoredWorldSourceResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setRequestId(request.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(); + } + /** Decodes the complete closed receipt and binds all echoed fields to the exact read request. */ public static AuthoredWorldSourceEvidence fromReadResponse( ReadRequest request, ResolveAuthoredWorldSourceResponse response) { @@ -73,6 +117,12 @@ public static AuthoredWorldSourceEvidence fromReadResponse( throw new IllegalArgumentException("Authored-world source response is invalid", exception); } + requireExactSelector(request, evidence); + return evidence; + } + + private static void requireExactSelector( + ReadRequest request, AuthoredWorldSourceEvidence evidence) { if (!request.targetNamespace().equals(evidence.targetNamespace()) || !request.operationId().equals(evidence.operationId()) || !request.canonicalTenantId().equals(evidence.canonicalTenantId()) @@ -80,7 +130,6 @@ public static AuthoredWorldSourceEvidence fromReadResponse( throw new IllegalArgumentException( "Authored-world source response does not match the exact request"); } - return evidence; } private static void requireNoUnknownFields(Message message) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java index d190339226..6f2e986271 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java @@ -11,6 +11,7 @@ import io.grpc.ManagedChannel; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.UUID; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; @@ -44,6 +45,80 @@ void canonicalDescriptorRejectsRetainedLegacyTenantSelector() { .hasMessageContaining("legacy tenant selector"); } + @Test + void completeBindingResponseRoundTripsTheExactDescriptorAndAttestationPair() { + AuthoredWorldLaunchDescriptorEvidence.Request sourceRequest = request(NAMESPACE); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + sourceRequest, + "launch-descriptor-7", + 7L, + false, + null, + "{}", + "generation-revision-1", + 3L, + 11L, + "release-ref-11", + false, + null); + String commitId = "commit-7"; + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + participantKey -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participantKey, + "7", + false, + null, + commitId, + "d".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey), + "GAME_LOGIC".equals(participantKey), + "GAME_LOGIC".equals(participantKey) ? "sha256:" + "e".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT_ID, + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + sourceRequest.worldSlug(), + SOURCE_OPERATION_ID, + sourceRequest.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish-workflow-7", + commitId, + participants, + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + CompleteLaunchBindingEvidence evidence = + new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + GetLaunchDescriptorRequest readRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(sourceRequest.worldSlug()) + .setControlPlaneRequestId(sourceRequest.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + + var response = AuthoredWorldLaunchDescriptorGrpcCodec.toCompleteResponse(readRequest, evidence); + + org.assertj.core.api.Assertions.assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(readRequest, response)) + .isEqualTo(evidence); + } + @Test void rejectsPlaintextMissingClasspathAndUnreadableTlsMaterialBeforeChannelCreation( @TempDir Path directory) throws Exception { 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..5a4cf0371d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceClientTest.java @@ -0,0 +1,247 @@ +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.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AuthoredWorldSourceClientTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_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 READ_REQUEST = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, READ_REQUEST_ID, OPERATION_ID, TENANT_ID, "silver-march"); + + @Test + void requiresFileBackedMtlsBeforeCreatingAChannel(@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"); + + CommonGrpcClientProperties classpath = fileBackedMtls(directory); + classpath.setPrivateKey("classpath:client.key"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missing = new CommonGrpcClientProperties(); + missing.setCertChain(directory.resolve("missing.crt").toString()); + missing.setPrivateKey(directory.resolve("missing.key").toString()); + missing.setCaCert(directory.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missing, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void requiresExplicitInitializationAndConfiguredNamespace(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AuthoredWorldSourceClient client = newClient(fileBackedMtls(directory), channelFactory); + try { + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + + AuthoredWorldSourceGrpcCodec.ReadRequest otherNamespace = + new AuthoredWorldSourceGrpcCodec.ReadRequest( + "other", READ_REQUEST_ID, OPERATION_ID, TENANT_ID, "silver-march"); + assertThatThrownBy(() -> client.read(otherNamespace)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void initializesTheConfiguredGameDesignTargetOnceAndCannotRestartAfterClose( + @TempDir Path directory) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("design.internal:7676"); + CommonGrpcClientProperties tls = fileBackedMtls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("design.internal:7676"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + AuthoredWorldSourceClient client = + new AuthoredWorldSourceClient(endpoints, tls, channelFactory, NAMESPACE); + + client.init(); + client.init(); + client.close(); + + verify(channelFactory) + .buildChannel( + eq("design.internal:7676"), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("is closed"); + } + + @Test + void readsAndReturnsOnlyTheExactValidatedSourceReceipt(@TempDir Path directory) throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = + mock(TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub.class); + AuthoredWorldSourceClient client = clientWithStub(directory, stub); + ResolveAuthoredWorldSourceResponse response = + AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, source()); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + when(stub.resolveAuthoredWorldSource(any())).thenReturn(response); + + AuthoredWorldSourceEvidence result = client.read(READ_REQUEST); + + assertThat(result).isEqualTo(source()); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub) + .resolveAuthoredWorldSource(AuthoredWorldSourceGrpcCodec.toReadRequest(READ_REQUEST)); + } + + @Test + void rejectsSubstitutedCorruptOrOpenResponsesAndPropagatesTransportFailure( + @TempDir Path directory) throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = + mock(TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub.class); + AuthoredWorldSourceClient client = clientWithStub(directory, stub); + when(stub.withDeadlineAfter(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(stub); + + when(stub.resolveAuthoredWorldSource(any())) + .thenReturn( + AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, source()).toBuilder() + .setWorldSlug("other-world") + .build()); + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-world source evidence"); + + when(stub.resolveAuthoredWorldSource(any())) + .thenReturn( + AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, source()).toBuilder() + .setUnknownFields(unknownField()) + .build()); + assertThatThrownBy(() -> client.read(READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-world source evidence"); + + when(stub.resolveAuthoredWorldSource(any())) + .thenThrow(new StatusRuntimeException(Status.UNAVAILABLE)); + StatusRuntimeException exception = + Assertions.assertThrows(StatusRuntimeException.class, () -> client.read(READ_REQUEST)); + assertThat(exception.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + } + + private static AuthoredWorldSourceClient clientWithStub( + Path directory, TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub) + throws Exception { + AuthoredWorldSourceClient client = + newClient(fileBackedMtls(directory), mock(GrpcChannelFactory.class)); + setField(AbstractReloadingBlockingGrpcClient.class, client, "stub", stub); + setField(AuthoredWorldSourceClient.class, client, "initialized", true); + return client; + } + + private static AuthoredWorldSourceClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new AuthoredWorldSourceClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws Exception { + Path certificate = Files.writeString(directory.resolve("client.crt"), "certificate"); + Path key = Files.writeString(directory.resolve("client.key"), "private-key"); + Path ca = Files.writeString(directory.resolve("ca.crt"), "authority"); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + + private static AuthoredWorldSourceEvidence source() { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + TENANT_ID, + "new-kingdom", + "silver-march", + "Silver March"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + "new-kingdom", + "silver-march", + "Silver March", + 17L, + "legacy-tenant-7", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + TENANT_ID, + "new-kingdom", + "silver-march", + "Silver March", + 17L, + "legacy-tenant-7", + "NEW_GAME_ROW", + evidenceDigest); + } + + 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); + } +} 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..8ccace27a6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceGrpcCodecTest.java @@ -0,0 +1,149 @@ +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.UUID; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceRequest; +import org.junit.jupiter.api.Test; + +class AuthoredWorldSourceGrpcCodecTest { + private static final String NAMESPACE = "test"; + private static final UUID READ_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 String TENANT_SLUG = "new-kingdom"; + private static final String WORLD_SLUG = "silver-march"; + private static final String WORLD_DISPLAY_NAME = "Silver March"; + private static final String SOURCE_KEY = "legacy-tenant-7"; + private static final AuthoredWorldSourceGrpcCodec.ReadRequest READ_REQUEST = + readRequest(NAMESPACE, TENANT_ID, WORLD_SLUG); + + @Test + void requestRoundTripCarriesOnlyReadCorrelationAndExactSourceSelector() { + ResolveAuthoredWorldSourceRequest encoded = + AuthoredWorldSourceGrpcCodec.toReadRequest(READ_REQUEST); + + assertThat(AuthoredWorldSourceGrpcCodec.fromReadRequest(NAMESPACE, encoded)) + .isEqualTo(READ_REQUEST); + assertThat(encoded.getDescriptorForType().getFields()) + .extracting(field -> field.getName()) + .containsExactly("request_id", "operation_id", "canonical_tenant_id", "world_slug"); + assertThat(encoded.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(encoded.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(encoded.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(encoded.getWorldSlug()).isEqualTo(WORLD_SLUG); + } + + @Test + void requestDecoderRejectsMalformedSelectorsAndUnknownFields() { + ResolveAuthoredWorldSourceRequest valid = + AuthoredWorldSourceGrpcCodec.toReadRequest(READ_REQUEST); + for (ResolveAuthoredWorldSourceRequest malformed : + new ResolveAuthoredWorldSourceRequest[] { + valid.toBuilder().setRequestId("not-a-uuid").build(), + valid.toBuilder().setOperationId("00000000-0000-0000-0000-000000000000").build(), + valid.toBuilder().setCanonicalTenantId("not-a-uuid").build(), + valid.toBuilder().setWorldSlug("Silver March").build(), + valid.toBuilder().setUnknownFields(unknownField()).build() + }) { + assertThatThrownBy(() -> AuthoredWorldSourceGrpcCodec.fromReadRequest(NAMESPACE, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> AuthoredWorldSourceGrpcCodec.fromReadRequest("Bad_Namespace", valid)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void responseRoundTripVerifiesCompleteImmutableReceiptAndSelector() { + AuthoredWorldSourceEvidence source = source(READ_REQUEST); + var response = AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, source); + + assertThat(AuthoredWorldSourceGrpcCodec.fromReadResponse(READ_REQUEST, response)) + .isEqualTo(source); + assertThat(response.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getRegistrationRequestId()).isEqualTo(REGISTRATION_REQUEST_ID.toString()); + assertThat(response.getOperationId()).isEqualTo(OPERATION_ID.toString()); + assertThat(response.getEvidenceDigest()).isEqualTo(source.evidenceDigest()); + } + + @Test + void responseDecoderRejectsChangedEchoReceiptDigestsAndUnknownFields() { + var response = AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, source(READ_REQUEST)); + for (var malformed : + new net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse[] { + response.toBuilder().setRequestId("52345678-1234-4234-8234-123456789abc").build(), + response.toBuilder().setOperationId("52345678-1234-4234-8234-123456789abc").build(), + response.toBuilder().setCanonicalTenantId("52345678-1234-4234-8234-123456789abc").build(), + response.toBuilder().setRequestDigest("0".repeat(64)).build(), + response.toBuilder().setEvidenceDigest("0".repeat(64)).build(), + response.toBuilder().setSourceGameRowId(0L).build(), + response.toBuilder().setProvenanceKind("GUESSED").build(), + response.toBuilder().setUnknownFields(unknownField()).build() + }) { + assertThatThrownBy( + () -> AuthoredWorldSourceGrpcCodec.fromReadResponse(READ_REQUEST, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + + AuthoredWorldSourceEvidence substituted = source(readRequest(NAMESPACE, TENANT_ID, "other")); + assertThatThrownBy(() -> AuthoredWorldSourceGrpcCodec.toReadResponse(READ_REQUEST, substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact request"); + } + + private static AuthoredWorldSourceGrpcCodec.ReadRequest readRequest( + String namespace, UUID canonicalTenantId, String worldSlug) { + return new AuthoredWorldSourceGrpcCodec.ReadRequest( + namespace, READ_REQUEST_ID, OPERATION_ID, canonicalTenantId, worldSlug); + } + + private static AuthoredWorldSourceEvidence source( + AuthoredWorldSourceGrpcCodec.ReadRequest request) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + request.canonicalTenantId(), + TENANT_SLUG, + request.worldSlug(), + WORLD_DISPLAY_NAME); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + request.canonicalTenantId(), + TENANT_SLUG, + request.worldSlug(), + WORLD_DISPLAY_NAME, + 17L, + SOURCE_KEY, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + request.canonicalTenantId(), + TENANT_SLUG, + request.worldSlug(), + WORLD_DISPLAY_NAME, + 17L, + SOURCE_KEY, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } +} diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 8f854a2324..117135c9f1 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -25,7 +25,8 @@ testing { dependencies { integrationTestImplementation(project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof"))) - integrationTestImplementation(project(":game-logic-service")) + integrationTestImplementation(project(mapOf("path" to ":game-logic-service", "configuration" to "gameLogicClassesProof"))) + integrationTestImplementation("io.grpc:grpc-util:${libs.versions.grpc.get()}") compileOnly(libs.spotbugs.annotations) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 6cdfb6c087..6feb429934 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -8,12 +8,18 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.UUID; +import java.util.regex.Pattern; import lombok.RequiredArgsConstructor; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.settings.GameDesignSettingsProtoMapper; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.HelpTopicDto; import net.firedevops.firemud.gamedesign.dto.PublishedPluginVersionDto; @@ -22,6 +28,7 @@ import net.firedevops.firemud.gamedesign.dto.TemplateRemapEntryDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -52,8 +59,10 @@ import net.firedevops.firemud.gamedesign.v1.FinalizePurgeVersionAssetsRequest; import net.firedevops.firemud.gamedesign.v1.FinalizePurgeVersionAssetsResponse; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; @@ -117,16 +126,20 @@ import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.grpc.server.service.GrpcService; @GrpcService @RequiredArgsConstructor public class GameDesignGrpcService extends GameDesignServiceGrpc.GameDesignServiceImplBase { private static final Logger logger = LoggerFactory.getLogger(GameDesignGrpcService.class); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); private final PingService pingService; private final RevisionService revisionService; private final VersionService versionService; private final LaunchDescriptorService launchDescriptorService; + private final CompleteLaunchBindingService completeLaunchBindingService; private final TemplateRemapSetService templateRemapSetService; private final VersionAssetArtifactService versionAssetArtifactService; private final SettingsAuthorityService settingsAuthorityService; @@ -138,6 +151,9 @@ public class GameDesignGrpcService extends GameDesignServiceGrpc.GameDesignServi justification = "MeterRegistry is injected and not exposed") private final MeterRegistry meterRegistry; + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + @Override @Timed(value = "gamedesignGrpc.ping") public void ping(PingRequest request, StreamObserver responseObserver) { @@ -919,6 +935,152 @@ public void resolveLaunchDescriptor( responseObserver.onCompleted(); } + @Override + @Timed(value = "gamedesignGrpc.getCompleteLaunchBinding") + public void getCompleteLaunchBinding( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + GetCompleteLaunchBindingResponse.Builder builder = + GetCompleteLaunchBindingResponse.newBuilder(); + + // Authenticate the exact workload before examining request fields or consulting owner data. + if (!isAuthenticatedWorldManagementPeer()) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + "PERMISSION_DENIED", + "Verified same-namespace World Management workload is required")); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + return; + } + + final CompleteLaunchBindingReadRequest readRequest; + try { + readRequest = parseCompleteLaunchBindingRequest(request, workloadNamespace); + } catch (IllegalArgumentException invalid) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + "INVALID_ARGUMENT", + "Canonical complete launch binding read request is required")); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + return; + } + + try { + CompleteLaunchBindingDto dto = + completeLaunchBindingService.getCompleteLaunchBinding( + readRequest.requestId(), + readRequest.canonicalTenantId(), + readRequest.worldSlug(), + readRequest.controlPlaneRequestId(), + readRequest.expectedRequestDigest(), + readRequest.expectedResultDigest()); + CompleteLaunchBindingEvidence evidence = + new CompleteLaunchBindingEvidence(dto.descriptor(), dto.releaseAttestation()); + GetCompleteLaunchBindingResponse response = + AuthoredWorldLaunchDescriptorGrpcCodec.toCompleteResponse(request, evidence); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (FrozenLaunchDescriptorDenialException denied) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + denied.failureCode(), + denied.getMessage())); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } catch (IllegalArgumentException | IllegalStateException inconsistent) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + "FAILED_PRECONDITION", + "Exact launch descriptor or release attestation is unavailable or inconsistent")); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } catch (Exception failure) { + builder.setError( + GrpcAppErrors.internal(meterRegistry, logger, "GetCompleteLaunchBinding", failure)); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + } + + private boolean isAuthenticatedWorldManagementPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && peer != null + && peer.isInNamespace(workloadNamespace) + && peer.isService("world-management-service"); + } + + private static CompleteLaunchBindingReadRequest parseCompleteLaunchBindingRequest( + GetLaunchDescriptorRequest request, String targetNamespace) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Unknown or missing request fields"); + } + UUID requestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID tenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest.validateReadSelector( + targetNamespace, tenantId, request.getWorldSlug()); + requireControlPlaneRequestId(request.getControlPlaneRequestId()); + requireRequestDigest(request.getExpectedRequestDigest()); + requireRequestDigest(request.getExpectedResultDigest()); + if (requestId.toString().equals(request.getControlPlaneRequestId())) { + throw new IllegalArgumentException("Read request ID must differ from the launch request ID"); + } + return new CompleteLaunchBindingReadRequest( + requestId, + tenantId, + request.getWorldSlug(), + request.getControlPlaneRequestId(), + request.getExpectedRequestDigest(), + request.getExpectedResultDigest()); + } + + private static UUID parseCanonicalNonNilUuid(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Canonical UUID is required"); + } + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil UUID is required"); + } + return parsed; + } + + private static void requireControlPlaneRequestId(String value) { + if (value == null + || value.isBlank() + || value.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 64) { + throw new IllegalArgumentException("Canonical control-plane request ID is required"); + } + } + + private static void requireRequestDigest(String value) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException("Canonical SHA-256 digest is required"); + } + } + + private record CompleteLaunchBindingReadRequest( + UUID requestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) {} + @Override @Timed(value = "gamedesignGrpc.createTemplateRemapSet") public void createTemplateRemapSet( 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 5927ccf6e3..e8619e7130 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 @@ -7,9 +7,14 @@ import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; 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.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.ResolveFreshTenantCreationResponse; import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; @@ -20,20 +25,119 @@ import org.springframework.dao.TransientDataAccessException; import org.springframework.grpc.server.service.GrpcService; -/** Read-only owner handoff for one exact, persisted fresh tenant creation. */ +/** Read-only owner handoffs for exact persisted tenant and authored-world source evidence. */ @GrpcService public class TenantIdentityGrpcService extends TenantIdentityServiceGrpc.TenantIdentityServiceImplBase { private final GameTenantCreationRepository creationRepository; + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private final String workloadNamespace; public TenantIdentityGrpcService( GameTenantCreationRepository creationRepository, + GameAuthoredWorldSourceRepository authoredWorldSourceRepository, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.creationRepository = creationRepository; + this.authoredWorldSourceRepository = authoredWorldSourceRepository; this.workloadNamespace = workloadNamespace; } + /** Read-only exact lookup of one Game Design-authored World source operation. */ + @Override + public void resolveAuthoredWorldSource( + ResolveAuthoredWorldSourceRequest request, + StreamObserver responseObserver) { + if (SessionContext.hasAuthenticatedCallerContext() || !isWorldManagementPeer()) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Verified same-namespace World Management workload identity without caller " + + "context is required") + .asRuntimeException()); + return; + } + + final AuthoredWorldSourceGrpcCodec.ReadRequest readRequest; + try { + readRequest = AuthoredWorldSourceGrpcCodec.fromReadRequest(workloadNamespace, request); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical exact authored-world source request is required") + .asRuntimeException()); + return; + } + + Optional resolved; + try { + resolved = + authoredWorldSourceRepository.read( + readRequest.operationId(), + readRequest.canonicalTenantId(), + readRequest.worldSlug(), + workloadNamespace); + } catch (GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException + | GameAuthoredWorldSourceRepository.RegistrationConflictException + | org.jooq.exception.TooManyRowsException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source evidence is incomplete or inconsistent") + .asRuntimeException()); + return; + } catch (DataAccessResourceFailureException + | TransientDataAccessException + | org.springframework.transaction.TransactionException exception) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Authored-world source evidence is temporarily unavailable") + .asRuntimeException()); + return; + } catch (org.springframework.dao.DataAccessException exception) { + Status.Code code = + hasConnectionFailureSqlState(exception) ? Status.Code.UNAVAILABLE : Status.Code.INTERNAL; + responseObserver.onError( + Status.fromCode(code) + .withDescription( + code == Status.Code.UNAVAILABLE + ? "Authored-world source evidence is temporarily unavailable" + : "Authored-world source evidence could not be read") + .asRuntimeException()); + return; + } catch (org.jooq.exception.DataAccessException exception) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Authored-world source storage could not complete the read") + .asRuntimeException()); + return; + } catch (RuntimeException exception) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Authored-world source evidence could not be read") + .asRuntimeException()); + return; + } + if (resolved.isEmpty()) { + responseObserver.onError( + Status.NOT_FOUND + .withDescription("No authored-world source matches the exact selector") + .asRuntimeException()); + return; + } + + final ResolveAuthoredWorldSourceResponse response; + try { + response = AuthoredWorldSourceGrpcCodec.toReadResponse(readRequest, resolved.orElseThrow()); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-world source readback does not match the exact request") + .asRuntimeException()); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + @Override public void resolveFreshTenantCreation( ResolveFreshTenantCreationRequest request, @@ -173,6 +277,14 @@ private boolean isAccountPeer() { && peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"); } + private boolean isWorldManagementPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/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 4c8251d4e5..9d6dce9e83 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -51,6 +51,8 @@ firemud: grpc: public-methods: - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding + - 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 cfa32714ea..75e69f13e6 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -62,6 +62,8 @@ firemud: grpc: public-methods: - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding + - gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource http: enabled: true role-requirement: PRIVILEGED diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java index a6b555d833..c7e35cf132 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java @@ -3,7 +3,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import io.grpc.BindableService; import io.grpc.Metadata; @@ -15,6 +14,7 @@ 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.util.MutableHandlerRegistry; import java.net.InetSocketAddress; import java.nio.file.Files; import java.nio.file.Path; @@ -93,9 +93,9 @@ /** * Real GD Account-ordered typed gameplay source through selection, Account intake, GL terminal, - * Account settlement and the immutable V61 GD receipt. The Account current actor and original - * terminal readback are real; only the fixture's exact current Redis registry bytes are replayed to - * the source-permission read owner. Loopback owner calls use test-only mutual TLS identities. + * Account settlement and the immutable V61 GD receipt. The Account current actor, Redis-backed + * registry check and original terminal readback are real. Loopback owner calls use test-only mutual + * TLS identities. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -167,25 +167,12 @@ void genuineSourceSelectionIntakeSettlementAndExactRecoveryRetainOneReceipt() th var accountAccess = account.preparedOriginalCreator(); var original = originalRequest.original(); var credential = originalRequest.originalCreatorCredential(); - var originalActor = - accountAccess - .actors() - .withCurrent( - credential, - local.target().canonicalTenantId(), - accountAccess.environment(), - current -> - new ActiveRegistry( - current.stored().tokenHash, current.stored().activeRegistry.clone())); - - var registry = mock(AccountControlUiCoordination.class); - when(registry.readActive(originalActor.tokenHash())).thenReturn(originalActor.bytes()); var accountRepository = new AccountGameLogicIntakeAuthorizationRepository(accountAccess.sources().dsl); var accountSourcePermissionOwner = new AccountGameLogicIntakeSourceReadService( accountRepository, - registry, + account.coordination(), accountAccess.sources().manager, Clock.systemUTC(), NAMESPACE); @@ -195,80 +182,91 @@ void genuineSourceSelectionIntakeSettlementAndExactRecoveryRetainOneReceipt() th var endpoints = new ServiceEndpointsProperties(); var pki = new TestPki(temporary.resolve("pki")); - var accountToGameDesignSource = - new GameplayRuleSourceReadClient( - endpoints, - pki.accountClient().properties(pki.ca()), - new GrpcChannelFactory(), - NAMESPACE); - var gameDesignToAccountPermission = - new GrpcGameLogicIntakeSourceReadClient( - endpoints, - pki.gameDesignClient().properties(pki.ca()), - new GrpcChannelFactory(), - NAMESPACE); - var gameLogicToAccountHeld = - new GameLogicIntakeAuthorizationReadClient( - endpoints, - pki.gameLogicClient().properties(pki.ca()), - new GrpcChannelFactory(), - NAMESPACE); - var gameLogicToGameDesignSource = - new GameplayRuleSourceReadClient( - endpoints, - pki.gameLogicClient().properties(pki.ca()), - new GrpcChannelFactory(), - NAMESPACE); - var accountToGameLogicTerminal = - new GameLogicIntakeTerminalReadClient( - endpoints, - pki.accountClient().properties(pki.ca()), - new GrpcChannelFactory(), - NAMESPACE); - var gameDesignToAccountAuthorization = - new GrpcGameLogicIntakeAuthorizationClient( - endpoints, - pki.gameDesignClient().properties(pki.ca()), - new GrpcChannelFactory(), - NAMESPACE); - var gameDesignToGameLogicRetain = - new GrpcGameLogicIntakeRetainClient( - endpoints, - pki.gameDesignClient().properties(pki.ca()), - new GrpcChannelFactory(), - NAMESPACE); - var gameDesignToAccountSettlement = - new GrpcAccountGameLogicIntakeSettlementReadClient( - endpoints, - pki.gameDesignClient().properties(pki.ca()), - new GrpcChannelFactory(), - NAMESPACE); - var originalOrderClient = - new AccountOriginalDraftOrderClient( - endpoints, - pki.gameDesignClient().properties(pki.ca()), - new GrpcChannelFactory(), - NAMESPACE); - var originalTerminalClient = - new GameDesignDraftTerminalReadClient( - endpoints, - pki.accountClient().properties(pki.ca()), - new GrpcChannelFactory(), - NAMESPACE); - - var gameDesignSourceOwner = - new GameDesignGameplayRuleSourceReadService( - new GameplayRuleSourceRepository(local.dsl()), - local.transactions(), - gameDesignToAccountPermission, - NAMESPACE); - var gameDesignTerminalOwner = new GameDesignDraftTerminalOutcomeRepository(local.dsl()); var gameDesignSourceReads = new AtomicInteger(); var gameDesignTerminalReads = new AtomicInteger(); + var gameLogicTerminalReads = new AtomicInteger(); + var accountHandlers = new MutableHandlerRegistry(); + var gameDesignHandlers = new MutableHandlerRegistry(); + var gameLogicHandlers = new MutableHandlerRegistry(); Server accountServer = null; Server gameDesignServer = null; Server gameLogicServer = null; try { + accountServer = startServer(pki, pki.accountServer(), accountHandlers); + endpoints.setAccountService(loopback(accountServer)); + gameDesignServer = startServer(pki, pki.gameDesignServer(), gameDesignHandlers); + endpoints.setGameDesignService(loopback(gameDesignServer)); + gameLogicServer = startServer(pki, pki.gameLogicServer(), gameLogicHandlers); + endpoints.setGameLogicService(loopback(gameLogicServer)); + + var accountToGameDesignSource = + new GameplayRuleSourceReadClient( + endpoints, + pki.accountClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToAccountPermission = + new GrpcGameLogicIntakeSourceReadClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameLogicToAccountHeld = + new GameLogicIntakeAuthorizationReadClient( + endpoints, + pki.gameLogicClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameLogicToGameDesignSource = + new GameplayRuleSourceReadClient( + endpoints, + pki.gameLogicClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var accountToGameLogicTerminal = + new GameLogicIntakeTerminalReadClient( + endpoints, + pki.accountClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToAccountAuthorization = + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToGameLogicRetain = + new GrpcGameLogicIntakeRetainClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var gameDesignToAccountSettlement = + new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var originalOrderClient = + new AccountOriginalDraftOrderClient( + endpoints, + pki.gameDesignClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + var originalTerminalClient = + new GameDesignDraftTerminalReadClient( + endpoints, + pki.accountClient().properties(pki.ca()), + new GrpcChannelFactory(), + NAMESPACE); + + var gameDesignSourceOwner = + new GameDesignGameplayRuleSourceReadService( + new GameplayRuleSourceRepository(local.dsl()), + local.transactions(), + gameDesignToAccountPermission, + NAMESPACE); + var gameDesignTerminalOwner = new GameDesignDraftTerminalOutcomeRepository(local.dsl()); var accountAuthorizationOwner = new AccountGameLogicIntakeAuthorizationService( accountAccess.actors(), @@ -283,32 +281,6 @@ void genuineSourceSelectionIntakeSettlementAndExactRecoveryRetainOneReceipt() th accountToGameLogicTerminal, accountAccess.sources().manager, NAMESPACE); - accountServer = - startServer( - pki, - pki.accountServer(), - Map.of(), - account.originalDraftOrderProducer(NAMESPACE), - new AccountGameLogicIntakeAuthorizationGrpcService( - accountAuthorizationOwner, accountAccess.sources().terms, NAMESPACE), - new AccountGameLogicIntakeSourceReadGrpcService( - accountSourcePermissionOwner, NAMESPACE), - new AccountGameLogicIntakeAuthorizationReadGrpcService( - accountHeldReadOwner, NAMESPACE), - new AccountGameLogicIntakeSettlementGrpcService(accountSettlementOwner, NAMESPACE)); - endpoints.setAccountService(loopback(accountServer)); - - gameDesignServer = - startServer( - pki, - pki.gameDesignServer(), - Map.of( - "readselectedgameplayrulesource", gameDesignSourceReads, - "readgamedesigndraftterminaloutcome", gameDesignTerminalReads), - new GameDesignGameplayRuleSourceReadGrpcService(gameDesignSourceOwner, NAMESPACE), - new GameDesignDraftTerminalReadGrpcService(gameDesignTerminalOwner, NAMESPACE)); - endpoints.setGameDesignService(loopback(gameDesignServer)); - var gameLogicRepository = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); var gameLogicOwner = new GameLogicGameplayRuleIntakeService( @@ -317,18 +289,30 @@ void genuineSourceSelectionIntakeSettlementAndExactRecoveryRetainOneReceipt() th gameLogicToAccountHeld, gameLogicToGameDesignSource, NAMESPACE); - var gameLogicTerminalReads = new AtomicInteger(); - gameLogicServer = - startServer( - pki, - pki.gameLogicServer(), - Map.of("readgameplayruleintaketerminal", gameLogicTerminalReads), - new GameLogicGameplayRuleIntakeGrpcService(gameLogicOwner, NAMESPACE), - new GameLogicGameplayRuleIntakeTerminalReadGrpcService( - new GameLogicGameplayRuleIntakeTerminalReadService( - gameLogicRepository, NAMESPACE), - NAMESPACE)); - endpoints.setGameLogicService(loopback(gameLogicServer)); + registerServices( + accountHandlers, + Map.of(), + account.originalDraftOrderProducer(NAMESPACE), + new AccountGameLogicIntakeAuthorizationGrpcService( + accountAuthorizationOwner, accountAccess.sources().terms, NAMESPACE), + new AccountGameLogicIntakeSourceReadGrpcService( + accountSourcePermissionOwner, NAMESPACE), + new AccountGameLogicIntakeAuthorizationReadGrpcService(accountHeldReadOwner, NAMESPACE), + new AccountGameLogicIntakeSettlementGrpcService(accountSettlementOwner, NAMESPACE)); + registerServices( + gameDesignHandlers, + Map.of( + "readselectedgameplayrulesource", gameDesignSourceReads, + "readgamedesigndraftterminaloutcome", gameDesignTerminalReads), + new GameDesignGameplayRuleSourceReadGrpcService(gameDesignSourceOwner, NAMESPACE), + new GameDesignDraftTerminalReadGrpcService(gameDesignTerminalOwner, NAMESPACE)); + registerServices( + gameLogicHandlers, + Map.of("readgameplayruleintaketerminal", gameLogicTerminalReads), + new GameLogicGameplayRuleIntakeGrpcService(gameLogicOwner, NAMESPACE), + new GameLogicGameplayRuleIntakeTerminalReadGrpcService( + new GameLogicGameplayRuleIntakeTerminalReadService(gameLogicRepository, NAMESPACE), + NAMESPACE)); try (accountToGameDesignSource; gameDesignToAccountPermission; @@ -500,9 +484,7 @@ public GameLogicIntakeAuthorizationEvidence.Result abort( .isEqualTo(DraftAuthorizationFenceRepository.Settlement.COMMITTED); } } finally { - stop(gameLogicServer); - stop(gameDesignServer); - stop(accountServer); + stopAll(gameLogicServer, gameDesignServer, accountServer); } } } @@ -658,13 +640,10 @@ private static String migrationLocation(String service) { } private static Server startServer( - TestPki pki, - TestIdentity identity, - Map methodCounts, - BindableService... services) - throws Exception { + TestPki pki, TestIdentity identity, MutableHandlerRegistry handlers) throws Exception { var builder = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .fallbackHandlerRegistry(handlers) .maxInboundMessageSize(20 * 1024 * 1024) .maxInboundMetadataSize(AccountOriginalDraftOrderGrpcCodec.MAX_METADATA_BYTES) .sslContext( @@ -672,11 +651,17 @@ private static Server startServer( .trustManager(pki.ca().toFile()) .clientAuth(ClientAuth.REQUIRE) .build()); + return builder.build().start(); + } + + private static void registerServices( + MutableHandlerRegistry handlers, + Map methodCounts, + BindableService... services) { for (var service : services) - builder.addService( + handlers.addService( ServerInterceptors.intercept( service, new GrpcPeerIdentityInterceptor(), countingInterceptor(methodCounts))); - return builder.build().start(); } private static ServerInterceptor countingInterceptor(Map methodCounts) { @@ -698,11 +683,12 @@ private static String loopback(Server server) { return "127.0.0.1:" + server.getPort(); } - private static void stop(Server server) throws InterruptedException { - if (server == null) return; - server.shutdownNow(); - if (!server.awaitTermination(5, TimeUnit.SECONDS)) - throw new IllegalStateException("Test owner server did not stop"); + private static void stopAll(Server... servers) throws InterruptedException { + for (var server : servers) if (server != null) server.shutdownNow(); + var terminated = true; + for (var server : servers) + if (server != null) terminated &= server.awaitTermination(5, TimeUnit.SECONDS); + if (!terminated) throw new IllegalStateException("Test owner server did not stop"); } private record Local( @@ -712,8 +698,6 @@ private record Local( private record GameLogicStore(DSLContext dsl, DataSourceTransactionManager transactions) {} - private record ActiveRegistry(String tokenHash, byte[] bytes) {} - private record TestIdentity(Path certificate, Path key) { CommonGrpcClientProperties properties(Path ca) { var result = new CommonGrpcClientProperties(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java index 7ef9400b63..5aa6c5dd94 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java @@ -174,22 +174,35 @@ void publicationReadFailsClosedWhenNumericVersionRowNoLongerMatchesSelection() { } @Test - void publicationReadFailsClosedOnConflictingRetainedWorkflowField() { + void publicationReadFailsClosedOnConflictingRetainedAuthorizationBytes() { var value = receiptFixture(); var fixture = fixture(value); var dsl = fixture.dsl(); var repository = new SelectedDraftGameLogicReceiptRepository(dsl); fixture.tx().executeWithoutResult(ignored -> repository.retain(value)); - // Fault injection bypasses the immutable-row trigger to model conflicting retained bytes. + var conflictingAuthorization = + new GameLogicIntakeAuthorizationBinding( + value.authorization().operationId(), + UUID.randomUUID(), + value.authorization().intakeRequestId(), + value.authorization().actorAccountId(), + value.authorization().source(), + value.authorization().sources()); + // The trigger is bypassed to inject a changed but valid authorization payload. The database + // CHECK constraints remain active; the repository must detect the digest mismatch on read. dsl.execute( "ALTER TABLE game_design_selected_game_logic_receipt DISABLE TRIGGER trg_gd_selected_game_logic_receipt"); dsl.execute( - "UPDATE game_design_selected_game_logic_receipt SET workflow_identity = ?", - "publish:wrong-tenant:publish-request:publish-1"); + "UPDATE game_design_selected_game_logic_receipt SET authorization_bytes = ?", + conflictingAuthorization.canonicalBytes()); assertThatThrownBy(() -> repository.readForPublication(publicationBinding(value))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("integrity conflict"); + assertThat( + dsl.fetchSingle("SELECT receipt_bytes FROM game_design_selected_game_logic_receipt") + .get(0, byte[].class)) + .containsExactly(value.receipt().canonicalBytes()); } @Test diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 298ecf341a..a5eaa69a26 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -491,6 +491,16 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth Mockito.eq(publishRequestId), Mockito.eq(publishWorkflowId))) .thenReturn(participantDigests); + Mockito.when( + publishGateService.collectSelectedFullVersionParticipantDigests( + Mockito.any(VersionDto.class), + Mockito.eq( + PublicationDigestRequestBinding.full( + candidate.getCanonicalTenantId().toString(), + Long.toString(candidate.getId()), + publishRequestId)), + Mockito.eq(publishWorkflowId))) + .thenReturn(participantDigests); Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(immutableEmptyManifest()); VersionDto publishedVersion = @@ -625,6 +635,16 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele Mockito.eq(publishRequestId), Mockito.eq(workflowId))) .thenReturn(participantDigests); + Mockito.when( + publishGateService.collectSelectedFullVersionParticipantDigests( + Mockito.any(VersionDto.class), + Mockito.eq( + PublicationDigestRequestBinding.full( + candidate.getCanonicalTenantId().toString(), + Long.toString(candidate.getId()), + publishRequestId)), + Mockito.eq(workflowId))) + .thenReturn(participantDigests); Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(immutableEmptyManifest()); var pki = new SelectionReadTestPki(Files.createDirectories(temporary.resolve("pki"))); @@ -1164,6 +1184,16 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( Mockito.eq(publishRequestId), Mockito.eq(publishWorkflowId))) .thenReturn(participantDigests); + Mockito.when( + publishGateService.collectSelectedFullVersionParticipantDigests( + Mockito.any(VersionDto.class), + Mockito.eq( + PublicationDigestRequestBinding.full( + candidate.getCanonicalTenantId().toString(), + Long.toString(candidate.getId()), + publishRequestId)), + Mockito.eq(publishWorkflowId))) + .thenReturn(participantDigests); Mockito.doAnswer( invocation -> { try { 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 bb5a58ce07..5254717b43 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 @@ -31,6 +31,7 @@ import net.firedevops.firemud.common.security.JwtUtil; 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.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; @@ -51,6 +52,10 @@ class TenantIdentityGrpcAuthWiringTest { private static final String FRESH_CREATION_METHOD = "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation"; + private static final String COMPLETE_LAUNCH_BINDING_METHOD = + "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding"; + private static final String AUTHORED_WORLD_SOURCE_METHOD = + "gamedesign.v1.TenantIdentityService/ResolveAuthoredWorldSource"; private static final String OTHER_METHOD = "gamedesign.v1.TenantIdentityService/UnlistedMethod"; private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; @@ -62,10 +67,13 @@ class TenantIdentityGrpcAuthWiringTest { GameTenantCreationDigest.requestDigest("test", REQUEST_ID, SOURCE_KEY, "Fresh Realm", null); @Test - void defaultAndProductionProfilesAllowOnlyFreshReadAndRequireClientTls() throws IOException { + void defaultAndProductionProfilesAllowOnlyExplicitOwnerReadsAndRequireClientTls() + throws IOException { for (String file : List.of("application.yml", "application-prod.yml")) { GrpcConfiguration config = load(file); - assertThat(config.publicMethods()).containsExactly(FRESH_CREATION_METHOD); + assertThat(config.publicMethods()) + .containsExactly( + FRESH_CREATION_METHOD, COMPLETE_LAUNCH_BINDING_METHOD, AUTHORED_WORLD_SOURCE_METHOD); assertThat(config.clientAuth()).isEqualTo("REQUIRE"); } } @@ -75,7 +83,9 @@ void allowlistedNoTokenReadStillRequiresExactOwnerPeerBeforeOwnerRead() { withConfiguredInterceptor( interceptor -> { GameTenantCreationRepository repository = mock(GameTenantCreationRepository.class); - TenantIdentityGrpcService service = new TenantIdentityGrpcService(repository, "test"); + TenantIdentityGrpcService service = + new TenantIdentityGrpcService( + repository, mock(GameAuthoredWorldSourceRepository.class), "test"); FreshTenantCreationEvidence evidence = evidence("test", REQUEST_DIGEST); when(repository.read(REQUEST_ID, "test")).thenReturn(Optional.of(evidence)); @@ -90,7 +100,8 @@ void allowlistedNoTokenReadStillRequiresExactOwnerPeerBeforeOwnerRead() { GameTenantCreationRepository gameSessionRepository = mock(GameTenantCreationRepository.class); TenantIdentityGrpcService gameSessionService = - new TenantIdentityGrpcService(gameSessionRepository, "test"); + new TenantIdentityGrpcService( + gameSessionRepository, mock(GameAuthoredWorldSourceRepository.class), "test"); when(gameSessionRepository.read(REQUEST_ID, "test")).thenReturn(Optional.of(evidence)); DispatchResult gameSession = dispatch(interceptor, gameSessionService, GAME_SESSION_URI); @@ -104,7 +115,8 @@ void allowlistedNoTokenReadStillRequiresExactOwnerPeerBeforeOwnerRead() { GameTenantCreationRepository unauthorizedRepository = mock(GameTenantCreationRepository.class); TenantIdentityGrpcService unauthorizedService = - new TenantIdentityGrpcService(unauthorizedRepository, "test"); + new TenantIdentityGrpcService( + unauthorizedRepository, mock(GameAuthoredWorldSourceRepository.class), "test"); DispatchResult unauthorized = dispatch( interceptor, @@ -119,7 +131,7 @@ void allowlistedNoTokenReadStillRequiresExactOwnerPeerBeforeOwnerRead() { } @Test - void jwtBypassAppliesOnlyToTheConfiguredFreshReadMethod() throws IOException { + void jwtBypassAppliesOnlyToTheConfiguredOwnerReadMethods() throws IOException { AuthTokenInterceptor interceptor = new AuthTokenInterceptor( mock(JwtUtil.class), Set.copyOf(load("application.yml").publicMethods())); @@ -128,6 +140,16 @@ void jwtBypassAppliesOnlyToTheConfiguredFreshReadMethod() throws IOException { assertThat(fresh.dispatched()).isTrue(); assertThat(fresh.closedStatus()).isNull(); + AuthDispatchResult completeLaunchBinding = + dispatchWithoutPeer(interceptor, COMPLETE_LAUNCH_BINDING_METHOD); + assertThat(completeLaunchBinding.dispatched()).isTrue(); + assertThat(completeLaunchBinding.closedStatus()).isNull(); + + AuthDispatchResult authoredWorldSource = + dispatchWithoutPeer(interceptor, AUTHORED_WORLD_SOURCE_METHOD); + assertThat(authoredWorldSource.dispatched()).isTrue(); + assertThat(authoredWorldSource.closedStatus()).isNull(); + AuthDispatchResult other = dispatchWithoutPeer(interceptor, OTHER_METHOD); assertThat(other.dispatched()).isFalse(); assertThat(other.closedStatus()).isEqualTo(Status.Code.UNAUTHENTICATED); @@ -180,7 +202,10 @@ private static void withConfiguredInterceptor(Consumer act context -> { assertThat(context).hasSingleBean(AuthTokenInterceptor.class); assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .containsExactly(FRESH_CREATION_METHOD); + .containsExactly( + FRESH_CREATION_METHOD, + COMPLETE_LAUNCH_BINDING_METHOD, + AUTHORED_WORLD_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/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index e642671375..191e32dc81 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -2,16 +2,26 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -20,6 +30,8 @@ import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import net.firedevops.firemud.gamedesign.service.VersionService; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.ListVersionsRequest; @@ -29,8 +41,19 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceAuthTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID VERSION_ID = UUID.fromString("82345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final String WORLD_SLUG = "copper-coast"; + private static final String CONTROL_PLANE_REQUEST_ID = "launch-operation-7"; + @AfterEach void tearDown() { SessionContext.clear(); @@ -45,6 +68,7 @@ void adminMethodsReturnPermissionDeniedErrorDetail() { Mockito.mock(RevisionService.class), Mockito.mock(VersionService.class), Mockito.mock(LaunchDescriptorService.class), + Mockito.mock(CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -118,6 +142,7 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { Mockito.mock(RevisionService.class), versionService, launchDescriptorService, + Mockito.mock(CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -170,4 +195,266 @@ public void onCompleted() {} assertEquals("", descriptorRef.get().getError().getCode()); assertEquals("ld-1", descriptorRef.get().getLaunchDescriptor().getLaunchDescriptorId()); } + + @Test + void completeLaunchBindingAllowsOnlySameNamespaceWorldManagementAndReturnsExactPair() { + CompleteLaunchBindingService completeService = Mockito.mock(CompleteLaunchBindingService.class); + CompleteLaunchBindingDto binding = completeBinding(CONTROL_PLANE_REQUEST_ID); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + sourceRequest(CONTROL_PLANE_REQUEST_ID), + "launch-descriptor-7", + 7L, + false, + null, + "{}", + "generation-revision-1", + 3L, + 11L, + "release-ref-11", + false, + null); + when(completeService.getCompleteLaunchBinding( + READ_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest())) + .thenReturn(binding); + GameDesignGrpcService grpcService = service(completeService); + GetLaunchDescriptorRequest request = readRequest(descriptor); + AtomicReference response = new AtomicReference<>(); + + withPeer( + "world-management-service", + NAMESPACE, + () -> grpcService.getCompleteLaunchBinding(request, observer(response))); + + assertNotNull(response.get()); + assertEquals(false, response.get().hasError()); + assertEquals( + "launch-descriptor-7", response.get().getLaunchDescriptor().getLaunchDescriptorId()); + assertEquals( + "release-ref-11", response.get().getReleaseAttestation().getPublishedReleaseBundleRef()); + verify(completeService) + .getCompleteLaunchBinding( + READ_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + @Test + void completeLaunchBindingDeniesBeforeParsingOrReadingForWrongOrMissingPeer() { + CompleteLaunchBindingService completeService = Mockito.mock(CompleteLaunchBindingService.class); + GameDesignGrpcService grpcService = service(completeService); + GetLaunchDescriptorRequest malformed = GetLaunchDescriptorRequest.getDefaultInstance(); + + AtomicReference wrongPeer = new AtomicReference<>(); + withPeer( + "game-session-service", + NAMESPACE, + () -> grpcService.getCompleteLaunchBinding(malformed, observer(wrongPeer))); + assertEquals("PERMISSION_DENIED", wrongPeer.get().getError().getCode()); + + AtomicReference wrongNamespace = new AtomicReference<>(); + withPeer( + "world-management-service", + "another-namespace", + () -> grpcService.getCompleteLaunchBinding(malformed, observer(wrongNamespace))); + assertEquals("PERMISSION_DENIED", wrongNamespace.get().getError().getCode()); + + AtomicReference noPeer = new AtomicReference<>(); + grpcService.getCompleteLaunchBinding(malformed, observer(noPeer)); + assertEquals("PERMISSION_DENIED", noPeer.get().getError().getCode()); + verifyNoInteractions(completeService); + + AtomicReference malformedRequest = new AtomicReference<>(); + withPeer( + "world-management-service", + NAMESPACE, + () -> grpcService.getCompleteLaunchBinding(malformed, observer(malformedRequest))); + assertEquals("INVALID_ARGUMENT", malformedRequest.get().getError().getCode()); + verifyNoInteractions(completeService); + } + + @Test + void completeLaunchBindingRejectsSubstitutedDescriptorEvidence() { + CompleteLaunchBindingService completeService = Mockito.mock(CompleteLaunchBindingService.class); + CompleteLaunchBindingDto substituted = completeBinding("different-launch-operation"); + AuthoredWorldLaunchDescriptorEvidence requestedDescriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + sourceRequest(CONTROL_PLANE_REQUEST_ID), + "launch-descriptor-7", + 7L, + false, + null, + "{}", + "generation-revision-1", + 3L, + 11L, + "release-ref-11", + false, + null); + when(completeService.getCompleteLaunchBinding( + READ_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + requestedDescriptor.requestDigest(), + requestedDescriptor.resultDigest())) + .thenReturn(substituted); + GameDesignGrpcService grpcService = service(completeService); + AtomicReference response = new AtomicReference<>(); + + withPeer( + "world-management-service", + NAMESPACE, + () -> + grpcService.getCompleteLaunchBinding( + readRequest(requestedDescriptor), observer(response))); + + assertEquals("FAILED_PRECONDITION", response.get().getError().getCode()); + verify(completeService) + .getCompleteLaunchBinding( + READ_REQUEST_ID, + TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + requestedDescriptor.requestDigest(), + requestedDescriptor.resultDigest()); + } + + private static GameDesignGrpcService service(CompleteLaunchBindingService completeService) { + GameDesignGrpcService grpcService = + new GameDesignGrpcService( + Mockito.mock(PingService.class), + Mockito.mock(RevisionService.class), + Mockito.mock(VersionService.class), + Mockito.mock(LaunchDescriptorService.class), + completeService, + Mockito.mock(TemplateRemapSetService.class), + Mockito.mock(VersionAssetArtifactService.class), + Mockito.mock(SettingsAuthorityService.class), + Mockito.mock(GameAuthoredHelpTopicService.class), + new TemporalVersionPublishWorkflowMetadataResolver(Optional.empty(), Optional.empty()), + new SimpleMeterRegistry()); + ReflectionTestUtils.setField(grpcService, "workloadNamespace", NAMESPACE); + return grpcService; + } + + private static CompleteLaunchBindingDto completeBinding(String controlPlaneRequestId) { + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + sourceRequest(controlPlaneRequestId), + "launch-descriptor-7", + 7L, + false, + null, + "{}", + "generation-revision-1", + 3L, + 11L, + "release-ref-11", + false, + null); + String commitId = "commit-7"; + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + participantKey -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participantKey, + "7", + false, + null, + commitId, + "d".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey), + "GAME_LOGIC".equals(participantKey), + "GAME_LOGIC".equals(participantKey) ? "sha256:" + "e".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT_ID, + VERSION_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish-workflow-7", + commitId, + participants, + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingDto(descriptor, releaseAttestation); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request sourceRequest( + String controlPlaneRequestId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static GetLaunchDescriptorRequest readRequest( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + } + + private static StreamObserver observer(AtomicReference reference) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + reference.set(value); + } + + @Override + public void onError(Throwable throwable) { + throw new AssertionError(throwable); + } + + @Override + public void onCompleted() {} + }; + } + + private static void withPeer(String service, String namespace, Runnable action) { + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(action); + } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java index 9c8499397d..c331104be2 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java @@ -11,6 +11,7 @@ import java.util.Optional; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.dto.HelpTopicDto; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -38,6 +39,7 @@ class GameDesignGrpcServiceHelpTopicTest { Mockito.mock(RevisionService.class), Mockito.mock(VersionService.class), Mockito.mock(LaunchDescriptorService.class), + Mockito.mock(CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java index 95018adc29..916edd9860 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.settings.ScopedSettingsOverrides; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -59,6 +60,7 @@ void setUp() { revisionService, versionService, launchDescriptorService, + Mockito.mock(CompleteLaunchBindingService.class), templateRemapSetService, versionAssetArtifactService, settingsAuthorityService, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 285de48841..f42394d139 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -24,6 +24,7 @@ import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; @@ -89,6 +90,8 @@ class GameDesignGrpcServiceTest { private final VersionService versionService = Mockito.mock(VersionService.class); private final LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); + private final CompleteLaunchBindingService completeLaunchBindingService = + Mockito.mock(CompleteLaunchBindingService.class); private final TemplateRemapSetService templateRemapSetService = Mockito.mock(TemplateRemapSetService.class); private final VersionAssetArtifactService versionAssetArtifactService = @@ -105,6 +108,7 @@ class GameDesignGrpcServiceTest { revisionService, versionService, launchDescriptorService, + completeLaunchBindingService, templateRemapSetService, versionAssetArtifactService, settingsAuthorityService, 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 c71906e386..2155ad1053 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 @@ -16,10 +16,16 @@ import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; 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.AuthoredWorldSourceGrpcCodec; 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.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; +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 org.junit.jupiter.api.Test; @@ -28,6 +34,7 @@ class TenantIdentityGrpcServiceTest { private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String WORLD_URI = "spiffe://firemud/ns/test/sa/world-management-service"; private static final UUID REQUEST_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); private static final UUID TENANT_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); @@ -35,10 +42,112 @@ class TenantIdentityGrpcServiceTest { private static final String NAME = "Fresh Realm"; private static final String REQUEST_DIGEST = GameTenantCreationDigest.requestDigest("test", REQUEST_ID, SOURCE_KEY, NAME, null); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID REGISTRATION_REQUEST_ID = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID WORLD_TENANT_ID = + UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final String WORLD_SLUG = "silver-march"; + private static final String WORLD_TENANT_SLUG = "new-kingdom"; + private static final String WORLD_DISPLAY_NAME = "Silver March"; private final GameTenantCreationRepository repository = mock(GameTenantCreationRepository.class); + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository = + mock(GameAuthoredWorldSourceRepository.class); private final TenantIdentityGrpcService service = - new TenantIdentityGrpcService(repository, "test"); + new TenantIdentityGrpcService(repository, authoredWorldSourceRepository, "test"); + + @Test + void resolvesExactPersistedWorldSourceOnlyForSameNamespaceWorldManagementPeer() { + AuthoredWorldSourceEvidence source = authoredWorldSource("test"); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test")) + .thenReturn(Optional.of(source)); + + WorldSourceObserver observer = callWorldSource(worldSourceRequest(), WORLD_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.response) + .isEqualTo(AuthoredWorldSourceGrpcCodec.toReadResponse(worldSourceReadRequest(), source)); + verify(authoredWorldSourceRepository) + .read(SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test"); + } + + @Test + void deniesNonWorldPeersCrossNamespaceAndCallerContextBeforeAuthoredSourceRead() { + for (String peer : + new String[] { + null, + ACCOUNT_URI, + GAME_SESSION_URI, + "spiffe://firemud/ns/test/sa/entity-management-service", + "spiffe://firemud/ns/other/sa/world-management-service" + }) { + assertThat(status(callWorldSource(worldSourceRequest(), peer))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + SessionContext.setContext("account-uuid", List.of("player"), Map.of()); + try { + assertThat(status(callWorldSource(worldSourceRequest(), WORLD_URI))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(authoredWorldSourceRepository); + } + + @Test + void rejectsMalformedOrOpenAuthoredSourceRequestsBeforeOwnerRead() { + for (ResolveAuthoredWorldSourceRequest malformed : + new ResolveAuthoredWorldSourceRequest[] { + worldSourceRequest().toBuilder().setRequestId("not-a-uuid").build(), + worldSourceRequest().toBuilder() + .setOperationId("00000000-0000-0000-0000-000000000000") + .build(), + worldSourceRequest().toBuilder().setCanonicalTenantId("not-a-uuid").build(), + worldSourceRequest().toBuilder().setWorldSlug("Not A Slug").build(), + worldSourceRequest().toBuilder().setUnknownFields(unknownField()).build() + }) { + assertThat(status(callWorldSource(malformed, WORLD_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(authoredWorldSourceRepository); + } + + @Test + void missingOrSubstitutedAuthoredSourceFailsClosed() { + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test")) + .thenReturn(Optional.empty()) + .thenReturn(Optional.of(authoredWorldSource("other"))) + .thenReturn(Optional.of(authoredWorldSource("test", WORLD_TENANT_ID, "other-world"))); + + assertThat(status(callWorldSource(worldSourceRequest(), WORLD_URI))) + .isEqualTo(Status.Code.NOT_FOUND); + assertThat(status(callWorldSource(worldSourceRequest(), WORLD_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status(callWorldSource(worldSourceRequest(), WORLD_URI))) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + @Test + void mapsCorruptAndUnavailableAuthoredSourceReadsWithoutReturningEvidence() { + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG, "test")) + .thenThrow(new GameAuthoredWorldSourceRepository.InvalidSourceEvidenceException("corrupt")) + .thenThrow(new DataAccessResourceFailureException("offline")); + + WorldSourceObserver corrupt = callWorldSource(worldSourceRequest(), WORLD_URI); + WorldSourceObserver offline = callWorldSource(worldSourceRequest(), WORLD_URI); + + assertThat(status(corrupt)).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(corrupt.response).isNull(); + assertThat(status(offline)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(offline.response).isNull(); + } @Test void returnsExactImmutableReceiptOnlyToSameNamespaceAccountPeer() { @@ -108,7 +217,8 @@ void deniesMissingWrongServiceWrongNamespaceAndUnconfiguredPeerBeforeRead() { .isEqualTo(Status.Code.PERMISSION_DENIED); } - TenantIdentityGrpcService unconfigured = new TenantIdentityGrpcService(repository, ""); + TenantIdentityGrpcService unconfigured = + new TenantIdentityGrpcService(repository, authoredWorldSourceRepository, ""); Observer observer = new Observer(); GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(ACCOUNT_URI).orElseThrow(); Context.current() @@ -181,6 +291,82 @@ private Observer call(ResolveFreshTenantCreationRequest request, String peerUri) return observer; } + private WorldSourceObserver callWorldSource( + ResolveAuthoredWorldSourceRequest request, String peerUri) { + WorldSourceObserver observer = new WorldSourceObserver(); + Runnable invocation = () -> service.resolveAuthoredWorldSource(request, observer); + if (peerUri == null) { + invocation.run(); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } + return observer; + } + + private static ResolveAuthoredWorldSourceRequest worldSourceRequest() { + return ResolveAuthoredWorldSourceRequest.newBuilder() + .setRequestId(REQUEST_ID.toString()) + .setOperationId(SOURCE_OPERATION_ID.toString()) + .setCanonicalTenantId(WORLD_TENANT_ID.toString()) + .setWorldSlug(WORLD_SLUG) + .build(); + } + + private static AuthoredWorldSourceGrpcCodec.ReadRequest worldSourceReadRequest() { + return new AuthoredWorldSourceGrpcCodec.ReadRequest( + "test", REQUEST_ID, SOURCE_OPERATION_ID, WORLD_TENANT_ID, WORLD_SLUG); + } + + private static AuthoredWorldSourceEvidence authoredWorldSource(String namespace) { + return authoredWorldSource(namespace, WORLD_TENANT_ID, WORLD_SLUG); + } + + private static AuthoredWorldSourceEvidence authoredWorldSource( + String namespace, UUID canonicalTenantId, String worldSlug) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, + REGISTRATION_REQUEST_ID, + canonicalTenantId, + WORLD_TENANT_SLUG, + worldSlug, + WORLD_DISPLAY_NAME); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + canonicalTenantId, + WORLD_TENANT_SLUG, + worldSlug, + WORLD_DISPLAY_NAME, + 91L, + SOURCE_KEY, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + REGISTRATION_REQUEST_ID, + SOURCE_OPERATION_ID, + requestDigest, + canonicalTenantId, + WORLD_TENANT_SLUG, + worldSlug, + WORLD_DISPLAY_NAME, + 91L, + SOURCE_KEY, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + private static ResolveFreshTenantCreationRequest request(String requestId, String digest) { return ResolveFreshTenantCreationRequest.newBuilder() .setCreationRequestId(requestId) @@ -225,6 +411,10 @@ private static Status.Code status(Observer observer) { return observer.failure; } + private static Status.Code status(WorldSourceObserver observer) { + return observer.failure; + } + private static final class Observer implements StreamObserver { private ResolveFreshTenantCreationResponse response; @@ -246,4 +436,26 @@ public void onCompleted() { completed = true; } } + + private static final class WorldSourceObserver + implements StreamObserver { + private ResolveAuthoredWorldSourceResponse response; + private Status.Code failure; + private boolean completed; + + @Override + public void onNext(ResolveAuthoredWorldSourceResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failure = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } } diff --git a/services/game-logic-service/build.gradle.kts b/services/game-logic-service/build.gradle.kts index ca414ad898..61132e3141 100644 --- a/services/game-logic-service/build.gradle.kts +++ b/services/game-logic-service/build.gradle.kts @@ -19,3 +19,17 @@ dependencies { implementation(project(":common-security")) annotationProcessor(libs.spring.boot.configuration.processor) } + +// Opt-in proof artifact: expose Game Logic classes to owner integration tests without its application resources. +val gameLogicClassesProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("classes-proof") + dependsOn(tasks.named("classes")) + from(sourceSets.main.get().output.classesDirs) +} + +val gameLogicClassesProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(gameLogicClassesProofJar) +} From be47226a97d2a945f767c8adf0c3a955834ed629 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 21:33:25 +1300 Subject: [PATCH 048/129] Compose exact original Game Design and World source application --- .../game-design-service/version-control.md | 2 + .../world-management-service/api-contracts.md | 8 + ...ame-authoring-publishing-and-activation.md | 2 + ...d_original_draft_graph_apply_service.proto | 21 + .../WorldOriginalDraftGraphApplyClient.java | 159 ++++ .../WorldOriginalDraftGraphApplyEvidence.java | 151 ++++ ...WorldOriginalDraftGraphApplyGrpcCodec.java | 83 ++ ...orldOriginalDraftGraphApplyClientTest.java | 152 ++++ ...dOriginalDraftGraphApplyGrpcCodecTest.java | 311 ++++++++ services/game-design-service/build.gradle.kts | 1 + .../GameDesignWorldSourceCommitService.java | 257 +++++++ ...ldSourceCommitPostgresIntegrationTest.java | 720 ++++++++++++++++++ .../account/GenuineWorldSourceProofPki.java | 139 ++++ ...meLogicReceiptPostgresIntegrationTest.java | 4 +- ...emptServiceTransactionIntegrationTest.java | 55 +- ...ameDesignWorldSourceCommitServiceTest.java | 448 +++++++++++ .../world-management-service/build.gradle.kts | 14 + ...orldAuthoredVersionIdentityRepository.java | 39 + ...dOriginalDraftGraphApplicationService.java | 187 +++++ ...rldOriginalDraftGraphApplyGrpcService.java | 77 ++ ...ersionIdentityCanonicalTargetReadTest.java | 94 +++ ...ginalDraftGraphApplicationServiceTest.java | 513 +++++++++++++ ...riginalDraftGraphApplyGrpcServiceTest.java | 283 +++++++ 23 files changed, 3703 insertions(+), 17 deletions(-) create mode 100644 protos/world-management/v1/world_original_draft_graph_apply_service.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitService.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineWorldSourceProofPki.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitServiceTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcService.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index e189bd5f1a..4a4b67baeb 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -64,6 +64,8 @@ The selected commit's template/config references and asset-source declarations a For an entirely Game Design-owned source commit, the local coordinator first durably claims the exact operation and application slot, then calls the [Account original-order producer](../account-service/api-contracts.md#grpc-apis) outside SQL. A second local transaction applies the source, records the owner result, advances the source-aware synchronized fence, and releases the slot. This path requires the complete owner vector to be Game Design-only at both bindings; it must reject, not filter out, World or other owner participation. An unsuccessful or uncertain Account acquisition does not prove Account abort: under the same local serialization, Game Design must prove its owner is still `NOT_ATTEMPTED`, persist the exact no-application rejection, definitive-abort terminal and tombstone, then release the slot so no late application can pass. If source application commits first, exact terminal recovery returns that committed result without applying revisions again. Version state, epoch advancement, and publication selection cannot pass an unresolved application slot. A local abort does not assert that Account never ordered the operation; any late Account completion must reconcile through the existing exact owner-terminal settlement. Internal exact readback is not a public creator-authentication surface, and local source completion is not Account settlement, Game Logic retention or publication proof. This standalone construction remains unregistered; implementation and executed proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The separate bounded Game Design-plus-World composition retains the complete original Account operation and application slot before ordering, stages the genuine typed Game Design source and its local `APPLIED` result, and durably marks World dispatch before calling the [World original graph application boundary](../world-management-service/api-contracts.md#original-authorized-draft-graph-application) outside SQL. It retains only World-authenticated, exact original result/epoch evidence. The source-aware synchronized fence and slot release commit together only after both complete durable owner outcomes are `APPLIED`; a World result alone does not establish the Game Design terminal or Account settlement. Exact retry reuses the unchanged original operation and recovers retained outcomes without applying the local source twice. Unknown or denied Account/World work remains unresolved with the slot held: the Game Design-only no-application abort cannot terminalize this multi-owner operation. A complete definitive-abort producer must independently exclude late application at every required owner before the generic final-abort/tombstone protocol may release it. This standalone construction is not a public creator API, runtime registration or an assertion that multi-owner failure recovery is complete. + #### Publication freeze and owner handoff (Target State) The [immutable selected-Draft owner read](api-contracts.md#immutable-selected-draft-publication-read) preserves Game Design's original reserved selection across the Account-order and World-freeze handoffs. Its `SELECTED` response is not current Draft-state or permission evidence; consumers must retain those separate lifecycle and Account checks. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index ec3dd87a79..8005266d36 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -33,6 +33,14 @@ This API contract is target-state canonical; implementation coverage is partial The gRPC contract for world operations is located in [../../../../protos/world-management/v1](../../../../protos/world-management/v1). Run `./gradlew generateProto` to regenerate sources after editing these files. +### Original authorized Draft graph application + +`WorldOriginalDraftGraphApplyService.ApplyOriginalDraftGraph` is a distinct Game Design-to-World application and exact-recovery boundary for the bounded fresh-graph path. Its closed version-1 request carries the trusted namespace and the unchanged complete original Account Draft-order binding. World authenticates the exact same-namespace Game Design workload, without authenticated end-user context, before decoding or consulting owner storage. The complete derived owner vectors must be exactly Game Design and World; a caller cannot filter a larger operation into this path. The original bytes are operation identity, not Account permission or caller-provided private owner keys. + +Before a new application, World resolves one exact retained authored-Version association for the canonical tenant, Version UUID and Game Design Version row. It independently reads the retained source intake and validates the complete Game Design row/key/provenance relationship against the original target. Missing, ambiguous or contradictory associations deny; the receiver never chooses a World slug, infers a numeric mapping or creates a source association on this read. World derives its complete private owner binding from those receipts, derives the topology plan from the unchanged original typed World revisions, and enters the existing Account held-order verification and atomic graph/epoch/result transaction. The complete fresh-family declaration and Account protection through the actual mutation remain required. This transport does not relax physical-deadline enforcement or supply unavailable currentness machinery. + +An exact committed retry recovers the original World result before recapturing mutable identity or creator authority. A successful response echoes the complete request and returns the canonical World `COMMITTED` owner readback containing the actual `APPLIED` graph, original operation, start-location evidence and complete resulting epoch vector. Game Design authenticates World and verifies that full binding before retaining its coordinator result. Unknown, missing, corrupt or unavailable evidence returns no successful result: it cannot assert definitive abort, release participation, advance the synchronized Draft fence or authorize a new operation. Account's separate World-terminal reader remains Account-only; this application transport grants no access to that method. The standalone construction remains unregistered and grants no publication, preparation or gameplay admission. Executed proof and remaining composition limits belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + ### Canonical initial-placement terminal readback `ReadCanonicalInitialPlayerLocationOutcome` is a narrow World-owned historical read for the standalone canonical placement operation. It is separate from `PlaceCanonicalInitialPlayerLocation` and `ReadCanonicalCurrentPlayerLocation`; it does not register or enable the standalone service at runtime. 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 9327e58b5b..cc30c10a1f 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 @@ -110,6 +110,8 @@ Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, b Game Design now has a callable `GetCompleteLaunchBinding` handler and strict descriptor/release-attestation codec for the World Management read path. Its exact-method bearer-interceptor bypass is only transport dispatch: the handler still denies absent, wrong-service, or wrong-namespace TLS peers before parsing or owner reads. Corrected-state Common/Game Design checks, handler/auth-wiring and codec units, and the Game Design boot JAR pass locally; no genuine positive persisted release/attestation read, mounted-certificate transport proof, or launch activation is claimed. World Management owns exact binding persistence and preparation; Gameplay owns Game Session launch orchestration and its executable-front fixture. +The original GD+World construction now implements the World-local retained-identity resolver, a distinct closed application/recovery transport and a Game Design composer that retains both exact owner outcomes before synchronized visibility. These components remain unregistered. Consolidated local gate R229 passed 1,441 unit cases (Common 404, Game Design 467, World 570), service/static checks and boot-JAR construction; 333 integration definitions skipped without Docker. R231 compiled and statically checked the new genuine three-case PostgreSQL/mTLS composition fixture, together with 15 existing publication cases; all 18 skipped locally. The new fixture covers original APPLIED/synchronization/Account settlement, lost World acknowledgement and an unavailable World owner, but physical execution is still required. Its fresh World version association uses the actual owner service under authenticated incoming Game Design context through a test-only handoff, not a production association RPC. The existing executed GD-only source proof does not prove this combined original. Genuine composed PostgreSQL/mTLS execution, the production fresh-version association handoff, complete multi-owner definitive-abort recovery and release composition remain open. Account WAL feasibility is a separate admission gate, not a dependency of this source/release handoff. The normative coordinator and receiver contracts belong to [Game Design version control](../../architecture/microservices/game-design-service/version-control.md#design-time-synchronization) and [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md#original-authorized-draft-graph-application). + Official-hosted creator-content acceptance remains partial under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Account's individual-party and hosted-terms repositories now retain exact catalog, affirmative-acceptance and environment-binding operations; `AccountHostedTermsService` can resolve the external environment observation before SQL work and reread locked currentness in a caller-owned writable `READ_COMMITTED` transaction. The service and its trusted publication, environment and affirmative-action participants remain unregistered; current creator authentication and original multi-owner commit enforcement are not supplied by these storage APIs. `HostedTermsEnvironmentBindingPostgresIntegrationTest` exercises explicitly test-only authorities, not a real agreement or operative hosted service. Composed-head PostgreSQL execution, live authority provisioning, creator UI, transfer and organization workflows remain separate proof or implementation gaps. These foundations do not upgrade the broader capability ratings or authorize content writes. ### Fresh-tenant identity prerequisite diff --git a/protos/world-management/v1/world_original_draft_graph_apply_service.proto b/protos/world-management/v1/world_original_draft_graph_apply_service.proto new file mode 100644 index 0000000000..5124f1fa23 --- /dev/null +++ b/protos/world-management/v1/world_original_draft_graph_apply_service.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; +package world_management.v1; +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Unregistered Game Design-only original operation apply/recovery construction. +service WorldOriginalDraftGraphApplyService { + rpc ApplyOriginalDraftGraph(ApplyOriginalDraftGraphRequest) returns (ApplyOriginalDraftGraphResponse); +} +message ApplyOriginalDraftGraphRequest { + int32 schema_version = 1; + string target_namespace = 2; + bytes original_account_binding = 3; +} +message ApplyOriginalDraftGraphResponse { + int32 schema_version = 1; + string target_namespace = 2; + bytes original_account_binding = 3; + // Canonical World COMMITTED owner readback with validated APPLIED result only. + bytes owner_readback_bytes = 4; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClient.java new file mode 100644 index 0000000000..d4bd021485 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClient.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.authoring; + +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.WorldOriginalDraftGraphApplyServiceGrpc; + +/** Opt-in file-backed mTLS client for exact original World graph apply/recovery. */ +public final class WorldOriginalDraftGraphApplyClient + extends AbstractReloadingBlockingGrpcClient< + WorldOriginalDraftGraphApplyServiceGrpc.WorldOriginalDraftGraphApplyServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldOriginalDraftGraphApplyClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldOriginalDraftGraphApplyClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Game Design service explicitly starts this opt-in client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World original graph apply client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World original graph apply client has no gRPC stub"); + } + initialized = true; + } + + /** + * Applies or recovers the unchanged original operation; transport failures propagate unchanged. + */ + public WorldOriginalDraftGraphApplyEvidence.Result apply( + WorldOriginalDraftGraphApplyEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World original graph apply request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .applyOriginalDraftGraph(WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request)); + try { + return WorldOriginalDraftGraphApplyGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned invalid original graph apply evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldOriginalDraftGraphApplyServiceGrpc.WorldOriginalDraftGraphApplyServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldOriginalDraftGraphApplyServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(WorldOriginalDraftGraphApplyGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + public String workloadNamespace() { + return workloadNamespace; + } + + private WorldOriginalDraftGraphApplyServiceGrpc.WorldOriginalDraftGraphApplyServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World original graph apply client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World original graph apply 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 original graph apply requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World original graph apply requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "World original graph apply " + label + " must be a readable file-backed path", + exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World original graph apply " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyEvidence.java new file mode 100644 index 0000000000..e0fa2305d5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyEvidence.java @@ -0,0 +1,151 @@ +package net.firedevops.firemud.common.authoring; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Immutable original apply/recovery values; decoding supplies no workload authorization. */ +public final class WorldOriginalDraftGraphApplyEvidence { + // Preserve the original Account producer's admitted byte boundary. + public static final int MAX_BINDING_BYTES = AccountOriginalDraftOrderGrpcCodec.MAX_BINDING_BYTES; + // World readback includes framed input, base64 operation material and the retained graph. + public static final int MAX_OWNER_READBACK_BYTES = 16 * 1024 * 1024; + + private WorldOriginalDraftGraphApplyEvidence() {} + + public record Request(int schemaVersion, String targetNamespace, byte[] originalAccountBinding) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException( + "Canonical original World apply schema and namespace required"); + } + requireBytes(originalAccountBinding, MAX_BINDING_BYTES); + originalAccountBinding = originalAccountBinding.clone(); + var account = DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + var draft = draftBinding(account); + if (!List.of( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD) + .equals(account.requiredOwners()) + || !List.of( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) + .equals(draft.requiredOwners()) + || !Arrays.equals(account.normalizedInput(), draft.canonicalBytes()) + || !account.requestId().equals(draft.requestId()) + || !account.commitId().equals(draft.commitId()) + || !account.tenantId().equals(draft.target().canonicalTenantId()) + || !account.versionId().equals(draft.target().canonicalVersionId())) { + throw new IllegalArgumentException( + "Original World apply requires the exact complete GD+World binding"); + } + } + + public static Request create(String namespace, byte[] binding) { + return new Request(SCHEMA_VERSION, namespace, binding); + } + + @Override + public byte[] originalAccountBinding() { + return originalAccountBinding.clone(); + } + + public DraftAuthorizationFenceBinding accountBinding() { + return DraftAuthorizationFenceBinding.fromStored(originalAccountBinding); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && Arrays.equals(originalAccountBinding, that.originalAccountBinding); + } + + @Override + public int hashCode() { + return 31 * Objects.hash(schemaVersion, targetNamespace) + + Arrays.hashCode(originalAccountBinding); + } + } + + public record Result( + Request request, DraftAuthorizationFenceBinding.OwnerReadback ownerReadback) { + public Result { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(ownerReadback, "ownerReadback"); + requireBytes(ownerReadback.canonicalBytes(), MAX_OWNER_READBACK_BYTES); + if (ownerReadback.owner() != DraftAuthorizationFenceBinding.Owner.WORLD + || ownerReadback.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED) { + throw new IllegalArgumentException( + "World original apply requires COMMITTED/APPLIED evidence"); + } + // Internal structural correlation only. This creates no Account read permission or RPC. + new WorldDraftTerminalReadEvidence( + WorldDraftTerminalReadEvidence.Request.create( + request.targetNamespace(), request.originalAccountBinding()), + Optional.of(ownerReadback)); + } + + public String resultIdentity() { + try { + // Schema has already passed the single normative committed-result validator above. + String schema = + new tools.jackson.databind.ObjectMapper() + .readTree(ownerReadback.result()) + .get("schema") + .textValue(); + return schema + ":" + request.accountBinding().operationId(); + } catch (RuntimeException invalid) { + throw new IllegalStateException("Validated World result could not be decoded", invalid); + } + } + + public List appliedEpochs() { + return draftBinding(request.accountBinding()) + .affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT) + .stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + } + + @Override + public boolean equals(Object other) { + return other instanceof Result that + && request.equals(that.request) + && Arrays.equals(ownerReadback.canonicalBytes(), that.ownerReadback.canonicalBytes()); + } + + @Override + public int hashCode() { + return 31 * request.hashCode() + Arrays.hashCode(ownerReadback.canonicalBytes()); + } + } + + private static DraftCommitBinding draftBinding(DraftAuthorizationFenceBinding account) { + return DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + } + + static void requireBytes(byte[] bytes, int maximum) { + if (bytes == null || bytes.length == 0 || bytes.length > maximum) { + throw new IllegalArgumentException( + "Bounded nonempty canonical original World apply bytes required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodec.java new file mode 100644 index 0000000000..ce524314f2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodec.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.common.authoring; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.worldmanagement.v1.ApplyOriginalDraftGraphRequest; +import net.firedevops.firemud.worldmanagement.v1.ApplyOriginalDraftGraphResponse; + +/** Closed original-operation transport; there is no UNKNOWN or abort success response. */ +public final class WorldOriginalDraftGraphApplyGrpcCodec { + // Allow bounded protobuf framing and namespace overhead in addition to retained bytes. + public static final int MAX_REQUEST_WIRE_BYTES = + WorldOriginalDraftGraphApplyEvidence.MAX_BINDING_BYTES + 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = + WorldOriginalDraftGraphApplyEvidence.MAX_BINDING_BYTES + + WorldOriginalDraftGraphApplyEvidence.MAX_OWNER_READBACK_BYTES + + 1024; + + private WorldOriginalDraftGraphApplyGrpcCodec() {} + + public static ApplyOriginalDraftGraphRequest toRequest( + WorldOriginalDraftGraphApplyEvidence.Request request) { + Objects.requireNonNull(request, "request"); + var wire = + ApplyOriginalDraftGraphRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setOriginalAccountBinding(ByteString.copyFrom(request.originalAccountBinding())) + .build(); + requireClosed(wire, MAX_REQUEST_WIRE_BYTES); + return wire; + } + + public static WorldOriginalDraftGraphApplyEvidence.Request fromRequest( + ApplyOriginalDraftGraphRequest wire) { + requireClosed(wire, MAX_REQUEST_WIRE_BYTES); + return new WorldOriginalDraftGraphApplyEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + wire.getOriginalAccountBinding().toByteArray()); + } + + public static ApplyOriginalDraftGraphResponse toResponse( + WorldOriginalDraftGraphApplyEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback ownerReadback) { + var result = new WorldOriginalDraftGraphApplyEvidence.Result(request, ownerReadback); + var wire = + ApplyOriginalDraftGraphResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setOriginalAccountBinding(ByteString.copyFrom(request.originalAccountBinding())) + .setOwnerReadbackBytes(ByteString.copyFrom(result.ownerReadback().canonicalBytes())) + .build(); + requireClosed(wire, MAX_RESPONSE_WIRE_BYTES); + return wire; + } + + public static WorldOriginalDraftGraphApplyEvidence.Result fromResponse( + WorldOriginalDraftGraphApplyEvidence.Request request, ApplyOriginalDraftGraphResponse wire) { + Objects.requireNonNull(request, "request"); + requireClosed(wire, MAX_RESPONSE_WIRE_BYTES); + if (wire.getSchemaVersion() != request.schemaVersion() + || !wire.getTargetNamespace().equals(request.targetNamespace()) + || !Arrays.equals( + wire.getOriginalAccountBinding().toByteArray(), request.originalAccountBinding())) { + throw new IllegalArgumentException("World original apply response changed the exact request"); + } + byte[] bytes = wire.getOwnerReadbackBytes().toByteArray(); + WorldOriginalDraftGraphApplyEvidence.requireBytes( + bytes, WorldOriginalDraftGraphApplyEvidence.MAX_OWNER_READBACK_BYTES); + return new WorldOriginalDraftGraphApplyEvidence.Result( + request, DraftAuthorizationFenceBinding.OwnerReadback.fromStored(bytes)); + } + + private static void requireClosed(Message wire, int maximum) { + Objects.requireNonNull(wire, "wire"); + if (!wire.getUnknownFields().asMap().isEmpty() || wire.getSerializedSize() > maximum) { + throw new IllegalArgumentException( + "World original apply message has unsupported fields or size"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClientTest.java new file mode 100644 index 0000000000..bb33396015 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClientTest.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.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 io.grpc.ManagedChannel; +import io.grpc.Status; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +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.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.worldmanagement.v1.WorldOriginalDraftGraphApplyServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class WorldOriginalDraftGraphApplyClientTest { + @Test + void refusesPlaintextMissingMaterialAndClasspathBeforeTransport(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var tls = tls(directory); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldOriginalDraftGraphApplyClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + tls.setPlaintext(false); + tls.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldOriginalDraftGraphApplyClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + tls.setCaCert(directory.resolve("missing.crt").toString()); + assertThatThrownBy( + () -> + new WorldOriginalDraftGraphApplyClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void refusesWrongNamespaceUninitializedAndClosedUse(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var client = + new WorldOriginalDraftGraphApplyClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + try { + assertThatThrownBy( + () -> client.apply(WorldOriginalDraftGraphApplyGrpcCodecTest.request("other"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> client.apply(WorldOriginalDraftGraphApplyGrpcCodecTest.request("test"))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(factory); + } finally { + client.close(); + } + assertThatThrownBy(client::init).isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> client.apply(WorldOriginalDraftGraphApplyGrpcCodecTest.request("test"))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void configuresWorldEndpointAndExactPeerAndDecodesOnlyClosedResults(@TempDir Path directory) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(mock(ManagedChannel.class)); + var client = new WorldOriginalDraftGraphApplyClient(endpoints, tls(directory), factory, "test"); + try { + client.init(); + var field = stubField(); + var actual = + (WorldOriginalDraftGraphApplyServiceGrpc.WorldOriginalDraftGraphApplyServiceBlockingStub) + field.get(client); + assertThat(actual.getCallOptions().getMaxInboundMessageSize()) + .isEqualTo(WorldOriginalDraftGraphApplyGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + assertThat(client.workloadNamespace()).isEqualTo("test"); + assertThat(actual.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + var peerField = + GrpcServerPeerIdentityCallCredentials.class.getDeclaredField("expectedPeerUri"); + peerField.setAccessible(true); + assertThat(peerField.get(actual.getCallOptions().getCredentials())) + .isEqualTo("spiffe://firemud/ns/test/sa/world-management-service"); + verify(factory) + .buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + var stub = + mock( + WorldOriginalDraftGraphApplyServiceGrpc + .WorldOriginalDraftGraphApplyServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + field.set(client, stub); + var request = WorldOriginalDraftGraphApplyGrpcCodecTest.request("test"); + var response = + WorldOriginalDraftGraphApplyGrpcCodec.toResponse( + request, WorldOriginalDraftGraphApplyGrpcCodecTest.committed(request)); + when(stub.applyOriginalDraftGraph(any())).thenReturn(response); + assertThat(client.apply(request).request()).isEqualTo(request); + verify(stub) + .applyOriginalDraftGraph(WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request)); + when(stub.applyOriginalDraftGraph(any())) + .thenReturn(response.toBuilder().clearOwnerReadbackBytes().build()); + assertThatThrownBy(() -> client.apply(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid original graph apply evidence"); + var unavailable = Status.UNAVAILABLE.withDescription("lost response").asRuntimeException(); + when(stub.applyOriginalDraftGraph(any())).thenThrow(unavailable); + assertThatThrownBy(() -> client.apply(request)).isSameAs(unavailable); + var lostAck = + Status.DEADLINE_EXCEEDED.withDescription("owner may have committed").asRuntimeException(); + doThrow(lostAck).when(stub).applyOriginalDraftGraph(any()); + assertThatThrownBy(() -> client.apply(request)).isSameAs(lostAck); + } finally { + client.close(); + } + } + + private static Field stubField() throws ReflectiveOperationException { + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return field; + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "fixture").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "fixture").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "fixture").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodecTest.java new file mode 100644 index 0000000000..eb19cd90cb --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodecTest.java @@ -0,0 +1,311 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +/** Structural transport fixtures only; these do not prove genuine source or owner persistence. */ +class WorldOriginalDraftGraphApplyGrpcCodecTest { + @Test + void admittedMaximumOriginalBindingAllowsSerializedEnvelopeOverhead() { + byte[] original = binding(true); + var account = DraftAuthorizationFenceBinding.fromStored(original); + var source = account.sources().get(0); + byte[] padding = + new byte + [WorldOriginalDraftGraphApplyEvidence.MAX_BINDING_BYTES + - original.length + + source.evidence().length]; + var padded = + new DraftAuthorizationFenceBinding( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.actorAccountId(), + account.tenantId(), + account.versionId(), + account.baseCommitId(), + account.expectedDraftEpoch(), + account.gameDesignBinding(), + account.normalizedInput(), + account.inputDigest(), + java.util.List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + padding))); + var request = + WorldOriginalDraftGraphApplyEvidence.Request.create("test", padded.canonicalBytes()); + assertThat(request.originalAccountBinding()) + .hasSize(WorldOriginalDraftGraphApplyEvidence.MAX_BINDING_BYTES); + var wire = WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request); + assertThat(wire.getSerializedSize()) + .isGreaterThan(WorldOriginalDraftGraphApplyEvidence.MAX_BINDING_BYTES) + .isLessThanOrEqualTo(WorldOriginalDraftGraphApplyGrpcCodec.MAX_REQUEST_WIRE_BYTES); + assertThat(WorldOriginalDraftGraphApplyGrpcCodec.fromRequest(wire)).isEqualTo(request); + var response = WorldOriginalDraftGraphApplyGrpcCodec.toResponse(request, committed(request)); + assertThat(response.getSerializedSize()) + .isGreaterThan(WorldOriginalDraftGraphApplyEvidence.MAX_BINDING_BYTES) + .isLessThanOrEqualTo(WorldOriginalDraftGraphApplyGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + assertThat(WorldOriginalDraftGraphApplyGrpcCodec.fromResponse(request, response).request()) + .isEqualTo(request); + } + + @Test + void ownerReadbackHasAnIndependentHardBound() { + var request = request("test"); + var response = + WorldOriginalDraftGraphApplyGrpcCodec.toResponse(request, committed(request)).toBuilder() + .setOwnerReadbackBytes( + ByteString.copyFrom( + new byte[WorldOriginalDraftGraphApplyEvidence.MAX_OWNER_READBACK_BYTES + 1])) + .build(); + assertThatThrownBy(() -> WorldOriginalDraftGraphApplyGrpcCodec.fromResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void exactBindingAndCommittedResultRoundTripWithOriginalIdentityAndCompleteEpochs() { + var request = request("test"); + var wire = WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request); + assertThat(WorldOriginalDraftGraphApplyGrpcCodec.fromRequest(wire)).isEqualTo(request); + var bytes = request.originalAccountBinding(); + bytes[0] ^= 1; + assertThat(request.originalAccountBinding()) + .containsExactly(wire.getOriginalAccountBinding().toByteArray()); + var response = WorldOriginalDraftGraphApplyGrpcCodec.toResponse(request, committed(request)); + var result = WorldOriginalDraftGraphApplyGrpcCodec.fromResponse(request, response); + assertThat(result) + .isEqualTo(new WorldOriginalDraftGraphApplyEvidence.Result(request, committed(request))); + assertThat(result.resultIdentity()) + .isEqualTo("world-draft-graph-applied/v1:" + request.accountBinding().operationId()); + assertThat(result.appliedEpochs()).hasSize(2); + assertThat(result.appliedEpochs()) + .extracting(value -> value.resultingEpoch()) + .containsExactly("8", "20"); + } + + @Test + void rejectsUnsupportedOwnersSchemasNamespaceAndUnboundedOrUnknownInput() { + assertThatThrownBy( + () -> WorldOriginalDraftGraphApplyEvidence.Request.create("test", binding(false))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new WorldOriginalDraftGraphApplyEvidence.Request(2, "test", binding(true))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> request("INVALID")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldOriginalDraftGraphApplyEvidence.Request.create( + "test", new byte[WorldOriginalDraftGraphApplyEvidence.MAX_BINDING_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + var wire = WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request("test")); + assertThatThrownBy( + () -> + WorldOriginalDraftGraphApplyGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsEveryEchoSubstitutionEmptyOutcomeAndUnknownResponse() { + var request = request("test"); + var response = WorldOriginalDraftGraphApplyGrpcCodec.toResponse(request, committed(request)); + for (var changed : + java.util.List.of( + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder() + .setOriginalAccountBinding(ByteString.copyFrom(new byte[] {1})) + .build(), + response.toBuilder().clearOwnerReadbackBytes().build(), + response.toBuilder().setUnknownFields(unknown()).build())) { + assertThatThrownBy(() -> WorldOriginalDraftGraphApplyGrpcCodec.fromResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsAbortOtherOwnerFullBindingAndAppliedEpochSubstitution() throws Exception { + var request = request("test"); + var committed = committed(request); + assertThatThrownBy( + () -> + WorldOriginalDraftGraphApplyGrpcCodec.toResponse( + request, + changed( + committed, + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED, + committed.result()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldOriginalDraftGraphApplyGrpcCodec.toResponse( + request, + changed( + committed, + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + committed.result()))) + .isInstanceOf(IllegalArgumentException.class); + var alternate = request("other"); + assertThatThrownBy(() -> WorldOriginalDraftGraphApplyGrpcCodec.toResponse(alternate, committed)) + .isInstanceOf(IllegalArgumentException.class); + var json = new tools.jackson.databind.ObjectMapper().readTree(committed.result()); + ((tools.jackson.databind.node.ObjectNode) json.get("appliedEpochs").get(0)) + .put("resultingEpoch", "9"); + var wrongEpoch = + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8(json.toString()); + assertThatThrownBy( + () -> + WorldOriginalDraftGraphApplyGrpcCodec.toResponse( + request, + changed(committed, committed.owner(), committed.outcome(), wrongEpoch))) + .isInstanceOf(IllegalArgumentException.class); + var otherBinding = request.accountBinding(); + var differentAccount = + new DraftAuthorizationFenceBinding( + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + otherBinding.requestId(), + otherBinding.commitId(), + otherBinding.fenceId(), + otherBinding.actorAccountId(), + otherBinding.tenantId(), + otherBinding.versionId(), + otherBinding.baseCommitId(), + otherBinding.expectedDraftEpoch(), + otherBinding.gameDesignBinding(), + otherBinding.normalizedInput(), + otherBinding.inputDigest(), + otherBinding.sources()); + assertThatThrownBy( + () -> + WorldOriginalDraftGraphApplyGrpcCodec.toResponse( + WorldOriginalDraftGraphApplyEvidence.Request.create( + "test", differentAccount.canonicalBytes()), + committed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback changed( + DraftAuthorizationFenceBinding.OwnerReadback original, + DraftAuthorizationFenceBinding.Owner owner, + DraftAuthorizationFenceBinding.Outcome outcome, + byte[] result) { + return new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + outcome, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.fullBinding(), + result); + } + + static DraftAuthorizationFenceBinding.OwnerReadback committed( + WorldOriginalDraftGraphApplyEvidence.Request request) { + return WorldDraftTerminalReadGrpcCodecTest.committedReadback( + WorldDraftTerminalReadEvidence.Request.create( + request.targetNamespace(), request.originalAccountBinding())); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + static WorldOriginalDraftGraphApplyEvidence.Request request(String namespace) { + return WorldOriginalDraftGraphApplyEvidence.Request.create(namespace, binding(true)); + } + + static byte[] binding(boolean includeGameDesign) { + var tenant = UUID.fromString("11111111-1111-4111-8111-111111111111"); + var version = UUID.fromString("22222222-2222-4222-8222-222222222222"); + var request = UUID.fromString("44444444-4444-4444-8444-444444444444"); + var commit = UUID.fromString("55555555-5555-4555-8555-555555555555"); + var revisions = new java.util.ArrayList(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("66666666-6666-4666-8666-666666666666"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{}")); + var units = new java.util.ArrayList(); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "7")); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ZONE_SCOPE", + "zone-1", + "19")); + if (includeGameDesign) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + "1", + UUID.fromString("77777777-7777-4777-8777-777777777777"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "DESIGN", + "design-1", + "REVISION", + "revision-1", + "0")); + } + var draft = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + "base-1", + revisions, + units); + return new DraftAuthorizationFenceBinding( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request, + commit, + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + tenant, + version, + "base-1", + "0", + draft.canonicalBytes(), + draft.canonicalBytes(), + draft.digest(), + java.util.List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.GLOBAL_ROLES, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + null, + "1", + null, + null, + new byte[] {1}))) + .canonicalBytes(); + } +} diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 117135c9f1..fb84c97252 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -26,6 +26,7 @@ testing { dependencies { integrationTestImplementation(project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof"))) integrationTestImplementation(project(mapOf("path" to ":game-logic-service", "configuration" to "gameLogicClassesProof"))) + integrationTestImplementation(project(mapOf("path" to ":world-management-service", "configuration" to "worldClassesProof"))) integrationTestImplementation("io.grpc:grpc-util:${libs.versions.grpc.get()}") compileOnly(libs.spotbugs.annotations) testCompileOnly(libs.spotbugs.annotations) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitService.java new file mode 100644 index 0000000000..903d6db2a4 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitService.java @@ -0,0 +1,257 @@ +package net.firedevops.firemud.gamedesign.draft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyClient; +import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.CoordinatorProof; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered exact GD+World source composition. Unknown or denied authority/application retains + * the reservation and application slot for exact recovery. This entry supplies no multi-owner + * definitive-abort producer, public creator recovery, Account settlement or runtime activation. + */ +public final class GameDesignWorldSourceCommitService { + private final AccountOriginalDraftOrderClient account; + private final WorldOriginalDraftGraphApplyClient world; + private final DraftCommitCoordinatorRepository coordinator; + private final GameDesignDraftTerminalOutcomeRepository terminals; + private final GameDesignSourceRepository sources; + private final TransactionTemplate write; + private final TransactionTemplate read; + private final String namespace; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories are intentionally shared service collaborators.") + public GameDesignWorldSourceCommitService( + AccountOriginalDraftOrderClient account, + WorldOriginalDraftGraphApplyClient world, + DraftCommitCoordinatorRepository coordinator, + GameDesignDraftTerminalOutcomeRepository terminals, + GameDesignSourceRepository sources, + PlatformTransactionManager transactions, + String namespace) { + this.account = Objects.requireNonNull(account); + this.world = Objects.requireNonNull(world); + this.coordinator = Objects.requireNonNull(coordinator); + this.terminals = Objects.requireNonNull(terminals); + this.sources = Objects.requireNonNull(sources); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + write = new TransactionTemplate(Objects.requireNonNull(transactions)); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + read = new TransactionTemplate(transactions); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + } + + /** Internal exact retry uses retained terminal evidence before mutable creator authority. */ + public GameDesignDraftTerminalOutcome commit( + DraftAuthorizationFenceBinding original, String originalCreatorCredential) { + outsideSql(); + var operation = new GameDesignDraftTerminalOperation(original); + var binding = operation.gameDesignBinding(); + if (!binding + .requiredOwners() + .equals(List.of(Owner.WORLD_MANAGEMENT, Owner.GAME_DESIGN_CONTROL_PLANE)) + || !original + .requiredOwners() + .equals( + List.of( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD))) + throw new IllegalArgumentException("Complete GD+World owner vector required"); + var request = + WorldOriginalDraftGraphApplyEvidence.Request.create( + namespace, operation.accountBindingBytes()); + var retained = Objects.requireNonNull(read.execute(ignored -> terminal(operation))); + if (retained.isPresent()) return retained.orElseThrow(); + retained = + Objects.requireNonNull( + write.execute( + ignored -> { + coordinator.lockVersionTarget(binding.target()); + var existing = terminal(operation); + if (existing.isPresent()) return existing; + coordinator.claim(binding, original); + coordinator.claimApplicationSlot(binding); + return Optional.empty(); + })); + if (retained.isPresent()) return retained.orElseThrow(); + outsideSql(); + var orderRequest = + AccountOriginalDraftOrderGrpcCodec.Request.create( + namespace, original, originalCreatorCredential); + var ordered = account.claim(orderRequest); + if (ordered == null || !ordered.matches(orderRequest)) + throw new IllegalStateException("Exact authenticated original Account order required"); + outsideSql(); + var staged = + Objects.requireNonNull( + write.execute( + ignored -> { + coordinator.lockVersionTarget(binding.target()); + var existing = terminal(operation); + if (existing.isPresent()) return new Staged(existing, Optional.empty()); + var claimed = coordinator.claim(binding, original); + coordinator.claimApplicationSlot(binding); + var local = claimed.ownerStates().get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (local == null) + throw new IllegalStateException("Complete GD owner state required"); + if (local.status() == OwnerStatus.NOT_ATTEMPTED) { + coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + requireApplied( + binding, + sources.apply(binding).ownerOutcome(), + Owner.GAME_DESIGN_CONTROL_PLANE); + } else if (local.status() == OwnerStatus.APPLIED) { + requireApplied( + binding, local.outcome().orElseThrow(), Owner.GAME_DESIGN_CONTROL_PLANE); + } else { + throw new IllegalStateException("Unresolved GD source requires exact recovery"); + } + var remote = claimed.ownerStates().get(Owner.WORLD_MANAGEMENT); + if (remote == null) + throw new IllegalStateException("Complete World owner state required"); + if (remote.status() == OwnerStatus.APPLIED) { + var outcome = remote.outcome().orElseThrow(); + requireApplied(binding, outcome, Owner.WORLD_MANAGEMENT); + return new Staged(Optional.empty(), Optional.of(outcome)); + } + if (remote.status() == OwnerStatus.NOT_ATTEMPTED) + coordinator.markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT); + else if (remote.status() != OwnerStatus.IN_PROGRESS + && remote.status() != OwnerStatus.UNKNOWN) + throw new IllegalStateException( + "World owner has no successful recoverable result"); + return new Staged(Optional.empty(), Optional.empty()); + })); + if (staged.terminal().isPresent()) return staged.terminal().orElseThrow(); + outsideSql(); + OwnerOutcome worldOutcome = + staged + .worldOutcome() + .orElseGet( + () -> { + var response = + Objects.requireNonNull( + world.apply(request), "Authenticated World result required"); + if (!request.equals(response.request())) + throw new IllegalArgumentException( + "World result changed the complete original request"); + // Revalidate even an injected client's returned value; the strict carrier checks + // the complete + // original binding, APPLIED bytes and every World expected/resulting epoch. + var verified = + new WorldOriginalDraftGraphApplyEvidence.Result( + request, response.ownerReadback()); + return new OwnerOutcome( + Owner.WORLD_MANAGEMENT, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + verified.resultIdentity(), + verified.ownerReadback().result(), + verified.appliedEpochs().stream() + .map( + epoch -> + new AppliedEpoch( + epoch.aggregateType(), + epoch.aggregateId(), + epoch.scopeType(), + epoch.scopeId(), + epoch.expectedEpoch(), + epoch.resultingEpoch())) + .toList()); + }); + outsideSql(); + write.executeWithoutResult( + ignored -> { + coordinator.lockVersionTarget(binding.target()); + if (terminal(operation).isPresent()) return; + requireApplied(binding, worldOutcome, Owner.WORLD_MANAGEMENT); + coordinator.recordOwnerOutcome(binding, worldOutcome); + var actual = coordinator.read(binding.target(), binding.requestId()).orElseThrow(); + if (!binding.equals(actual.binding())) + throw new IllegalStateException("Complete retained coordinator binding required"); + var outcomes = + binding.requiredOwners().stream() + .map( + owner -> { + var state = actual.ownerStates().get(owner); + if (state == null || state.status() != OwnerStatus.APPLIED) + throw new IllegalStateException( + "Every exact owner must be durably APPLIED"); + var outcome = state.outcome().orElseThrow(); + requireApplied(binding, outcome, owner); + return outcome; + }) + .toList(); + coordinator.advanceSourceVisibilityFence( + binding, new CoordinatorProof(binding, outcomes)); + coordinator.releaseApplicationSlot(binding); + terminal(operation) + .orElseThrow(() -> new IllegalStateException("Terminal source readback unavailable")); + }); + outsideSql(); + return Objects.requireNonNull(read.execute(ignored -> terminal(operation).orElseThrow())); + } + + private Optional terminal( + GameDesignDraftTerminalOperation operation) { + var retained = terminals.read(operation); + if (retained.isEmpty()) return retained; + var outcome = retained.orElseThrow(); + if (!operation.exactlyMatches(outcome.operation())) + throw new IllegalStateException("Terminal source operation conflict"); + if (outcome.result() == GameDesignDraftTerminalOutcome.Result.COMMITTED) { + var binding = operation.gameDesignBinding(); + var synchronizedSources = + sources + .readSynchronized(binding.target(), binding.commitId()) + .orElseThrow( + () -> new IllegalStateException("Synchronized source readback unavailable")); + if (!binding.equals(synchronizedSources.command().binding())) + throw new IllegalStateException("Synchronized source binding conflict"); + } + return retained; + } + + private static void requireApplied( + DraftCommitBinding binding, OwnerOutcome outcome, Owner owner) { + if (outcome.owner() != owner + || outcome.status() != OwnerStatus.APPLIED + || !binding.commitId().equals(outcome.commitId()) + || !binding.digest().equals(outcome.bindingDigest())) + throw new IllegalStateException("Exact APPLIED owner result required"); + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Original source commit requires no ambient transaction"); + } + + private record Staged( + Optional terminal, Optional worldOutcome) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java new file mode 100644 index 0000000000..5b2db2f9d0 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java @@ -0,0 +1,720 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.util.JsonFormat; +import io.grpc.BindableService; +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.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.util.MutableHandlerRegistry; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadClient; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyClient; +import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyGrpcCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOperation; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcome; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcomeRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.draft.GameDesignWorldSourceCommitService; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateService; +import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftCommitOrderVerifier; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphAppliedResult; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcomeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplicationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplyGrpcService; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** Actual owner mutations and strict loopback mTLS; no runtime registration or activation proof. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GenuineGameDesignWorldSourceCommitPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer GD = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer WORLD = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer ACCOUNT = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("genuine-world-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer REPLICA = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(REDIS) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "genuine-world-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void genuineBothOwnerApplicationAndAuthenticatedTerminalSettlement() throws Exception { + compose(Failure.NONE); + } + + @Test + void lostWorldAcknowledgementRecoversOriginalApplicationWithoutDuplicateMutation() + throws Exception { + compose(Failure.LOST_ACKNOWLEDGEMENT); + } + + @Test + void unknownWorldOutcomeRetainsSlotAndInvisibilityUntilExactRecovery() throws Exception { + compose(Failure.UNAVAILABLE); + } + + private void compose(Failure failure) throws Exception { + var gd = gameDesign(); + var world = store(WORLD, "world-management"); + var pki = new GenuineWorldSourceProofPki(temporary.resolve("pki")); + var gdHandlers = new MutableHandlerRegistry(); + var worldHandlers = new MutableHandlerRegistry(); + var accountHandlers = new MutableHandlerRegistry(); + // Bind all ports before any client captures endpoint addresses. + Server gdServer = server(pki, "game-design-service", gdHandlers); + Server worldServer = server(pki, "world-management-service", worldHandlers); + Server accountServer = server(pki, "account-service", accountHandlers); + try (var account = + new AccountControlUiOriginalOrderFixture( + ACCOUNT.getJdbcUrl(), + ACCOUNT.getUsername(), + ACCOUNT.getPassword(), + REDIS.getHost(), + REDIS.getMappedPort(6379), + temporary.resolve("account"), + gd.target().canonicalTenantId())) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + gdServer.getPort()); + endpoints.setWorldManagementService("localhost:" + worldServer.getPort()); + endpoints.setAccountService("localhost:" + accountServer.getPort()); + var factory = new GrpcChannelFactory(); + var sourceRepository = new GameAuthoredWorldSourceRepository(gd.store().dsl()); + register( + gdHandlers, + new TenantIdentityGrpcService( + new GameTenantCreationRepository( + gd.store().dsl(), new GameRepository(gd.store().dsl())), + sourceRepository, + NAMESPACE), + new AuthoredWorldVersionStateGrpcService( + new AuthoredWorldVersionStateService(gd.store().transactions(), sourceRepository), + NAMESPACE)); + var source = + Objects.requireNonNull( + transaction(gd.store()) + .execute( + ignored -> + sourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + gd.target().canonicalTenantId(), + "genuine-tenant", + "genuine-world", + "Genuine authored World"))); + var intakes = new WorldAuthoredSourceIntakeRepository(world.dsl()); + var identities = new WorldAuthoredVersionIdentityRepository(world.dsl()); + try (var sourceClient = + new AuthoredWorldSourceClient( + endpoints, pki.client("world-management-service"), factory, NAMESPACE); + var versionClient = + new AuthoredWorldVersionStateClient( + endpoints, pki.client("world-management-service"), factory, NAMESPACE); + var intakeClient = + new WorldAuthoredSourceIntakeClient( + endpoints, pki.client("game-design-service"), factory, NAMESPACE); + var accountClient = + new AccountOriginalDraftOrderClient( + endpoints, pki.client("game-design-service"), factory, NAMESPACE); + var heldClient = + new DraftCommitOrderReadClient( + endpoints, pki.client("world-management-service"), factory, NAMESPACE); + var worldClient = + new WorldOriginalDraftGraphApplyClient( + endpoints, pki.client("game-design-service"), factory, NAMESPACE); + var gdTerminalClient = + new GameDesignDraftTerminalReadClient( + endpoints, pki.client("account-service"), factory, NAMESPACE); + var worldTerminalClient = + new WorldDraftTerminalReadClient( + endpoints, pki.client("account-service"), factory, NAMESPACE)) { + sourceClient.init(); + versionClient.init(); + var intakeService = + new WorldAuthoredSourceIntakeService( + sourceClient, intakes, world.transactions(), NAMESPACE); + var identityService = + new WorldAuthoredVersionIdentityService( + versionClient, identities, intakes, world.transactions(), NAMESPACE); + // There is no production Version-association RPC. This test-only hook invokes the actual + // association service after real intake under that socket's certificate-derived GD peer. + // It neither injects a peer Context nor constructs source, Version or intake evidence. + var associationComplete = new AtomicBoolean(); + var associationHook = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + return next.startCall( + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + if (associationComplete.compareAndSet(false, true)) { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(NAMESPACE)) + throw new SecurityException( + "Actual authenticated GD socket peer required"); + identityService.associate( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gd.target().canonicalVersionId(), + gd.target().gameDesignVersionRowId(), + UUID.randomUUID()); + } + super.sendMessage(message); + } + }, + headers); + } + }; + worldHandlers.addService( + ServerInterceptors.intercept( + new WorldAuthoredSourceIntakeGrpcService(intakeService, NAMESPACE), + new GrpcPeerIdentityInterceptor(), + associationHook)); + intakeClient.init(); + var intakeRequest = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + var publicIntake = intakeClient.intake(intakeRequest); + var intake = intakes.read(NAMESPACE, intakeRequest.intakeRequestId()).orElseThrow(); + assertThat(publicIntake.receiptDigest()).isEqualTo(intake.receiptDigest()); + var identity = + identities + .readByCanonicalTarget( + NAMESPACE, + source.canonicalTenantId(), + gd.target().canonicalVersionId(), + gd.target().gameDesignVersionRowId()) + .orElseThrow(); + assertThat(identity.sourceIntakeReceipt()).isEqualTo(intake); + var binding = binding(gd.target()); + var request = account.prepareOriginalDraftOrder(binding, NAMESPACE); + var original = request.original(); + register( + accountHandlers, + account.originalDraftOrderProducer(NAMESPACE), + new AccountDraftCommitOrderReadGrpcService( + account.heldOrderOwner(NAMESPACE), NAMESPACE)); + var coordinator = new DraftCommitCoordinatorRepository(gd.store().dsl()); + var terminals = new GameDesignDraftTerminalOutcomeRepository(gd.store().dsl()); + var sources = new GameDesignSourceRepository(gd.store().dsl()); + var fence = new WorldDesignPublicationFenceRepository(world.dsl(), intakes); + var applications = + new WorldDraftGraphApplicationRepository(world.dsl(), fence, new ObjectMapper()); + var applicationService = + new WorldDraftGraphApplicationService( + applications, + world.transactions(), + new WorldDraftCommitOrderVerifier(heldClient, NAMESPACE)); + var entry = + new WorldOriginalDraftGraphApplicationService(identities, intakes, applicationService); + var failurePending = new AtomicBoolean(failure != Failure.NONE); + worldHandlers.addService( + ServerInterceptors.intercept( + new WorldOriginalDraftGraphApplyGrpcService(entry, NAMESPACE), + new GrpcPeerIdentityInterceptor(), + failureInterceptor(failure, failurePending))); + register( + worldHandlers, + new WorldDraftTerminalReadGrpcService( + new WorldDraftTerminalOutcomeRepository(world.dsl(), fence, new ObjectMapper()), + applications, + NAMESPACE)); + register(gdHandlers, new GameDesignDraftTerminalReadGrpcService(terminals, NAMESPACE)); + accountClient.init(); + heldClient.init(); + worldClient.init(); + gdTerminalClient.init(); + worldTerminalClient.init(); + var composer = + new GameDesignWorldSourceCommitService( + accountClient, + worldClient, + coordinator, + terminals, + sources, + gd.store().transactions(), + NAMESPACE); + Optional firstWorldApplication = Optional.empty(); + if (failure != Failure.NONE) { + assertThatThrownBy(() -> composer.commit(original, request.originalCreatorCredential())) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + account.assertOriginalDraftOrderPending(original); + assertThat(coordinator.readApplicationSlot(gd.target())).isPresent(); + assertThat(coordinator.readVisibilityFence(gd.target())).isEmpty(); + assertThat(sources.readSynchronized(gd.target(), binding.commitId())).isEmpty(); + assertThat(terminals.read(new GameDesignDraftTerminalOperation(original))).isEmpty(); + var partial = coordinator.read(gd.target(), binding.requestId()).orElseThrow(); + assertThat( + partial + .ownerStates() + .get(DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) + .status()) + .isEqualTo(DraftCommitCoordinatorRepository.OwnerStatus.APPLIED); + assertThat(partial.ownerStates().get(DraftCommitBinding.Owner.WORLD_MANAGEMENT).status()) + .isEqualTo(DraftCommitCoordinatorRepository.OwnerStatus.IN_PROGRESS); + firstWorldApplication = applications.readCommitted(NAMESPACE, original.canonicalBytes()); + assertThat(firstWorldApplication.isPresent()) + .isEqualTo(failure == Failure.LOST_ACKNOWLEDGEMENT); + failurePending.set(false); + } + var terminal = composer.commit(original, request.originalCreatorCredential()); + assertThat(terminal.result()).isEqualTo(GameDesignDraftTerminalOutcome.Result.COMMITTED); + assertThat(terminal.operation().accountBindingBytes()).isEqualTo(original.canonicalBytes()); + assertThat(coordinator.readApplicationSlot(gd.target())).isEmpty(); + assertThat(coordinator.readVisibilityFence(gd.target()).orElseThrow().commitId()) + .isEqualTo(binding.commitId()); + assertThat( + sources + .readSynchronized(gd.target(), binding.commitId()) + .orElseThrow() + .command() + .binding()) + .isEqualTo(binding); + var actualWorld = + applications.readCommitted(NAMESPACE, original.canonicalBytes()).orElseThrow(); + firstWorldApplication.ifPresent( + first -> assertThat(actualWorld.canonicalBytes()).isEqualTo(first.canonicalBytes())); + assertThat(actualWorld.status()).isEqualTo("APPLIED"); + assertThat(actualWorld.startLocationReceipt()).isPresent(); + assertThat(actualWorld.application().operation().accountBindingBytes()) + .isEqualTo(original.canonicalBytes()); + assertThat( + coordinator + .read(gd.target(), binding.requestId()) + .orElseThrow() + .ownerStates() + .values()) + .allMatch( + owner -> owner.status() == DraftCommitCoordinatorRepository.OwnerStatus.APPLIED); + long worldApplicationCount = + world.dsl().fetchCount(DSL.table("world_draft_graph_application")); + int gdRevisionCount = + gd.store().dsl().fetchCount(DSL.table("game_design_gameplay_rule_revision")); + assertThat(worldApplicationCount).isEqualTo(1); + assertThat(gdRevisionCount).isEqualTo(1); + assertThat(composer.commit(original, null).finalEvidenceBytes()) + .isEqualTo(terminal.finalEvidenceBytes()); + assertThat(world.dsl().fetchCount(DSL.table("world_draft_graph_application"))) + .isEqualTo(worldApplicationCount); + assertThat(gd.store().dsl().fetchCount(DSL.table("game_design_gameplay_rule_revision"))) + .isEqualTo(gdRevisionCount); + account.assertOriginalDraftOrderPending(original); + account.reconcileOriginalDraft(original, gdTerminalClient, worldTerminalClient, NAMESPACE); + account.reconcileOriginalDraft(original, gdTerminalClient, worldTerminalClient, NAMESPACE); + assertThatThrownBy( + () -> + heldClient.read( + DraftCommitOrderReadEvidence.Request.create( + NAMESPACE, original.canonicalBytes()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + } + } finally { + for (var server : List.of(accountServer, worldServer, gdServer)) { + server.shutdownNow(); + server.awaitTermination(5, TimeUnit.SECONDS); + } + } + } + + private static ServerInterceptor failureInterceptor(Failure failure, AtomicBoolean pending) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (failure == Failure.UNAVAILABLE && pending.get()) { + call.close( + Status.UNAVAILABLE.withDescription("Test-only unavailable World owner"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + if (failure == Failure.LOST_ACKNOWLEDGEMENT && pending.compareAndSet(true, false)) { + return next.startCall( + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(RespT message) { + // The real owner committed before producing this response; suppress its + // acknowledgement. + } + + @Override + public void close(Status status, Metadata trailers) { + super.close( + status.isOk() + ? Status.UNAVAILABLE.withDescription( + "Test-only lost World acknowledgement") + : status, + trailers); + } + }, + headers); + } + return next.startCall(call, headers); + } + }; + } + + private GameDesign gameDesign() { + var store = store(GD, "game-design"); + var game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Genuine GD+World source"); + game.setDescription("Real authoring source provenance"); + var savedGame = + Objects.requireNonNull( + transaction(store).execute(ignored -> new GameRepository(store.dsl()).save(game))); + var version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + var saved = + Objects.requireNonNull( + transaction(store) + .execute(ignored -> new VersionRepository(store.dsl()).save(version))); + var target = + new DraftCommitBinding.TargetProof( + saved.getCanonicalTenantId(), + saved.getCanonicalVersionId(), + saved.getId(), + saved.getTenantId(), + saved.getIdentitySourceGameRowId(), + saved.getIdentitySourceGameTenantKey(), + saved.getIdentitySourceProvenanceKind()); + assertThat(new GameDesignSourceRepository(store.dsl()).readGenesis(target)).isPresent(); + return new GameDesign(store, target); + } + + private static Store store(PostgreSQLContainer postgres, String service) { + String schema = service.replace('-', '_') + "_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + data.setSchema(schema); + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .placeholders(Map.of("serviceSchema", schema)) + .locations(migrations(service)) + .load() + .migrate(); + return new Store( + DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES), + new DataSourceTransactionManager(data)); + } + + private static String migrations(String service) { + for (Path current = Path.of("").toAbsolutePath(); + current != null; + current = current.getParent()) { + Path target = + current.resolve("services/" + service + "-service/src/main/resources/db/migration"); + if (Files.isDirectory(target)) return "filesystem:" + target; + } + throw new IllegalStateException("Owner migration directory unavailable"); + } + + private static TransactionTemplate transaction(Store store) { + var result = new TransactionTemplate(store.transactions()); + result.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return result; + } + + private static Server server( + GenuineWorldSourceProofPki pki, String service, MutableHandlerRegistry handlers) + throws Exception { + var identity = pki.server(service); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .fallbackHandlerRegistry(handlers) + .maxInboundMessageSize(WorldOriginalDraftGraphApplyGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .maxInboundMetadataSize(AccountOriginalDraftOrderGrpcCodec.MAX_METADATA_BYTES) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .build() + .start(); + } + + private static void register(MutableHandlerRegistry handlers, BindableService... services) { + for (var service : services) + handlers.addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + } + + private static DraftCommitBinding binding(DraftCommitBinding.TargetProof target) + throws Exception { + UUID commit = UUID.randomUUID(); + UUID region = UUID.randomUUID(); + UUID zone = UUID.randomUUID(); + UUID room = UUID.randomUUID(); + var familyCounts = new ArrayList(); + for (var family : + List.of( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) { + familyCounts.add( + WorldFreshGraphFamilyCount.newBuilder() + .setFamily(family) + .setCount( + family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + || family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE + || family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM + ? 1 + : 0) + .build()); + } + var declaration = + WorldFreshGraphDeclaration.newBuilder() + .setTenantId(target.canonicalTenantId().toString()) + .setVersionId(target.canonicalVersionId().toString()) + .addAllFamilyCounts(familyCounts) + .setStartLocation( + net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef.newBuilder() + .setTenantId(target.canonicalTenantId().toString()) + .setVersionId(target.canonicalVersionId().toString()) + .setRoomTemplateId(room.toString())) + .build(); + var mutations = + List.of( + mutation( + commit, room, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("Genuine room") + .setZoneId(zone.toString()) + .setDescription("Genuine room description")) + .build(), + mutation( + commit, zone, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("Genuine zone") + .setRegionId(region.toString())) + .build(), + mutation( + commit, + region, + region, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("Genuine region") + .setWeather("clear") + .setShardId(1)) + .setFreshGraphDeclaration(declaration) + .build()); + var revisions = new ArrayList(); + var units = new ArrayList(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload( + new GameplayRuleManifest.AdmissionTag("genuine-world-admission")))); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + target.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + "effective", + "0")); + for (var mutation : mutations) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(mutation.getLogicalRevisionId()), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(mutation))); + var family = mutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "AGGREGATE", + mutation.getAggregateId(), + "0")); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + mutation.getAggregateId(), + "REGION_SUBTREE", + mutation.getScopeId(), + "0")); + } + return DraftCommitBinding.create( + target, UUID.randomUUID(), commit, "base-commit-0", revisions, units); + } + + private static WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID id, UUID region, WorldDesignAggregateType type) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(id.toString()) + .setAggregateType(type) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(region.toString()); + } + + private enum Failure { + NONE, + LOST_ACKNOWLEDGEMENT, + UNAVAILABLE + } + + private record Store(DSLContext dsl, DataSourceTransactionManager transactions) {} + + private record GameDesign(Store store, DraftCommitBinding.TargetProof target) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineWorldSourceProofPki.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineWorldSourceProofPki.java new file mode 100644 index 0000000000..bd398bc3b8 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineWorldSourceProofPki.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.math.BigInteger; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +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.openssl.jcajce.JcaPEMWriter; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; + +/** Ephemeral same-namespace test identities, never production signer or author authorization. */ +final class GenuineWorldSourceProofPki { + private final Path ca; + private final Map servers = new HashMap<>(); + private final Map clients = new HashMap<>(); + + GenuineWorldSourceProofPki(Path root) throws Exception { + Files.createDirectories(root); + var keys = keys(); + var now = Instant.now(); + var name = new X500Name("CN=Genuine GD World source test CA"); + var builder = + new JcaX509v3CertificateBuilder( + name, + BigInteger.ONE, + Date.from(now.minusSeconds(60)), + Date.from(now.plusSeconds(3600)), + name, + keys.getPublic()); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); + builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign)); + var certificate = + new JcaX509CertificateConverter() + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA").build(keys.getPrivate()))); + ca = pem(root.resolve("ca.pem"), certificate); + for (var service : + java.util.List.of("account-service", "game-design-service", "world-management-service")) { + servers.put(service, issue(root, service, true, keys, certificate)); + clients.put(service, issue(root, service, false, keys, certificate)); + } + } + + Path ca() { + return ca; + } + + Identity server(String service) { + return java.util.Objects.requireNonNull(servers.get(service)); + } + + CommonGrpcClientProperties client(String service) { + var identity = java.util.Objects.requireNonNull(clients.get(service)); + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(identity.certificate().toString()); + properties.setPrivateKey(identity.key().toString()); + properties.setCaCert(ca.toString()); + return properties; + } + + private static Identity issue( + Path root, String service, boolean server, KeyPair caKeys, X509Certificate caCertificate) + throws Exception { + var keys = keys(); + var now = Instant.now(); + var builder = + new JcaX509v3CertificateBuilder( + caCertificate, + new BigInteger(120, new SecureRandom()), + Date.from(now.minusSeconds(60)), + Date.from(now.plusSeconds(3600)), + new X500Name("CN=" + service), + keys.getPublic()); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); + builder.addExtension( + Extension.keyUsage, + false, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + server ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth)); + builder.addExtension( + Extension.subjectAlternativeName, + false, + new GeneralNames( + new GeneralName[] { + new GeneralName( + GeneralName.uniformResourceIdentifier, + "spiffe://firemud/ns/firemud/sa/" + service), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + })); + var certificate = + new JcaX509CertificateConverter() + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA").build(caKeys.getPrivate()))); + var prefix = service + (server ? "-server" : "-client"); + return new Identity( + pem(root.resolve(prefix + ".crt"), certificate), + pem(root.resolve(prefix + ".key"), keys.getPrivate())); + } + + private static KeyPair keys() throws Exception { + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private static Path pem(Path path, Object value) throws Exception { + try (var writer = new JcaPEMWriter(Files.newBufferedWriter(path))) { + writer.writeObject(value); + } + return path; + } + + record Identity(Path certificate, Path key) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java index 5aa6c5dd94..34ec0ad18a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java @@ -197,8 +197,8 @@ void publicationReadFailsClosedOnConflictingRetainedAuthorizationBytes() { conflictingAuthorization.canonicalBytes()); assertThatThrownBy(() -> repository.readForPublication(publicationBinding(value))) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("integrity conflict"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Exact RETAINED Account settlement required"); assertThat( dsl.fetchSingle("SELECT receipt_bytes FROM game_design_selected_game_logic_receipt") .get(0, byte[].class)) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index a5eaa69a26..dd5f674ce5 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -484,6 +484,11 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth String publishWorkflowId = operation.workflowId(); var participantDigests = PublishedWorldSelectorFixtures.participants(candidate.getId(), operation.world()); + var expectedDigestBinding = + PublicationDigestRequestBinding.full( + candidate.getCanonicalTenantId().toString(), + Long.toString(candidate.getId()), + publishRequestId); Mockito.when( publishGateService.collectFullVersionParticipantDigests( @@ -494,11 +499,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth Mockito.when( publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq( - PublicationDigestRequestBinding.full( - candidate.getCanonicalTenantId().toString(), - Long.toString(candidate.getId()), - publishRequestId)), + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), Mockito.eq(publishWorkflowId))) .thenReturn(participantDigests); Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(immutableEmptyManifest()); @@ -510,6 +511,11 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth "successful transaction proof", publishRequestId, publishWorkflowId); + Mockito.verify(publishGateService, Mockito.atLeastOnce()) + .collectSelectedFullVersionParticipantDigests( + Mockito.any(VersionDto.class), + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), + Mockito.eq(publishWorkflowId)); VersionDto terminalReplay = versionPublishCommandService.publishSelectedDraftFullVersion( tenantId, @@ -629,6 +635,11 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele new String(operation.world().canonicalBytes(), StandardCharsets.UTF_8); var participantDigests = PublishedWorldSelectorFixtures.participants(candidate.getId(), operation.world()); + var expectedDigestBinding = + PublicationDigestRequestBinding.full( + candidate.getCanonicalTenantId().toString(), + Long.toString(candidate.getId()), + publishRequestId); Mockito.when( publishGateService.collectFullVersionParticipantDigests( Mockito.any(VersionDto.class), @@ -638,11 +649,7 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele Mockito.when( publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq( - PublicationDigestRequestBinding.full( - candidate.getCanonicalTenantId().toString(), - Long.toString(candidate.getId()), - publishRequestId)), + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), Mockito.eq(workflowId))) .thenReturn(participantDigests); Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(immutableEmptyManifest()); @@ -753,6 +760,11 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) VersionDto published = command.publishSelectedDraftFullVersion(selection.intent(), operation.account()); assertThat(published.id()).isEqualTo(candidate.getId()); + Mockito.verify(publishGateService, Mockito.atLeastOnce()) + .collectSelectedFullVersionParticipantDigests( + Mockito.any(VersionDto.class), + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), + Mockito.eq(workflowId)); assertThat(versionCountForTenant(tenantId)).isEqualTo(versionCountBeforePublish); assertThat(accountEndpoint.readCount()).isEqualTo(3); assertThat(worldEndpoint.readCount()).isEqualTo(2); @@ -1171,6 +1183,11 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( candidateVersionNumber.set(candidate.getVersionNumber()); var participantDigests = PublishedWorldSelectorFixtures.participants(candidate.getId(), operation.world()); + var expectedDigestBinding = + PublicationDigestRequestBinding.full( + candidate.getCanonicalTenantId().toString(), + Long.toString(candidate.getId()), + publishRequestId); AtomicReference exportedVersionNumber = new AtomicReference<>(); AtomicReference remapSetId = new AtomicReference<>(); AtomicReference recordedDigestFailure = new AtomicReference<>(); @@ -1187,11 +1204,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( Mockito.when( publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.eq( - PublicationDigestRequestBinding.full( - candidate.getCanonicalTenantId().toString(), - Long.toString(candidate.getId()), - publishRequestId)), + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), Mockito.eq(publishWorkflowId))) .thenReturn(participantDigests); Mockito.doAnswer( @@ -1256,6 +1269,11 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( publishWorkflowId)); assertThat(publishFailure).isInstanceOf(RuntimeException.class); + Mockito.verify(publishGateService, Mockito.atLeastOnce()) + .collectSelectedFullVersionParticipantDigests( + Mockito.any(VersionDto.class), + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), + Mockito.eq(publishWorkflowId)); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(publishWorkflowId).orElseThrow(); String failureContext = @@ -2153,6 +2171,13 @@ private static String firstStackFrame(Throwable failure) { return failure.getStackTrace()[0].toString(); } + private static boolean sameCanonicalPreimage( + PublicationDigestRequestBinding actual, PublicationDigestRequestBinding expected) { + return actual != null + && expected != null + && java.util.Arrays.equals(actual.canonicalPreimage(), expected.canonicalPreimage()); + } + private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation reserveSelectedDraft(Version version, String notes) { TargetProof target = targetProof(version); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitServiceTest.java new file mode 100644 index 0000000000..e0fd8fa043 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitServiceTest.java @@ -0,0 +1,448 @@ +package net.firedevops.firemud.gamedesign.draft; + +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.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.OffsetDateTime; +import java.util.EnumMap; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyClient; +import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyEvidence; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.CommitSnapshot; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerState; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.WorkflowState; +import net.firedevops.firemud.gamedesign.publication.CommandSnapshot; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Mock control-flow proof only; typed source, storage and concurrent execution need physical proof. + */ +class GameDesignWorldSourceCommitServiceTest { + private final AccountOriginalDraftOrderClient account = + mock(AccountOriginalDraftOrderClient.class); + private final WorldOriginalDraftGraphApplyClient world = + mock(WorldOriginalDraftGraphApplyClient.class); + private final DraftCommitCoordinatorRepository coordinator = + mock(DraftCommitCoordinatorRepository.class); + private final GameDesignDraftTerminalOutcomeRepository terminals = + mock(GameDesignDraftTerminalOutcomeRepository.class); + private final GameDesignSourceRepository sources = mock(GameDesignSourceRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final GameDesignWorldSourceCommitService service = + new GameDesignWorldSourceCommitService( + account, world, coordinator, terminals, sources, transactions, "test"); + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void missingAndExtraOwnersAreDeniedBeforeReservation() { + for (var owners : + List.of( + List.of(Owner.GAME_DESIGN_CONTROL_PLANE), + List.of(Owner.WORLD_MANAGEMENT), + List.of( + Owner.WORLD_MANAGEMENT, + Owner.ENTITY_MANAGEMENT, + Owner.GAME_DESIGN_CONTROL_PLANE))) { + assertThatThrownBy(() -> service.commit(original(owners), "creator.credential")) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(account, world, coordinator, terminals, sources, transactions); + } + + @Test + void historicalAccountOwnerVectorCannotBeSilentlyReplaced() { + var current = original(List.of(Owner.GAME_DESIGN_CONTROL_PLANE)); + var historical = + new DraftAuthorizationFenceBinding( + current.operationId(), + current.requestId(), + current.commitId(), + current.fenceId(), + current.actorAccountId(), + current.tenantId(), + current.versionId(), + current.baseCommitId(), + current.expectedDraftEpoch(), + current.gameDesignBinding(), + current.normalizedInput(), + current.inputDigest(), + current.sources()); + // Historical v1 requires both Account owners even though this Draft binding is local-only. + assertThat(historical.requiredOwners()) + .containsExactly( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Owner.WORLD); + assertThatThrownBy(() -> service.commit(historical, "creator.credential")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(account, world, coordinator, terminals, sources, transactions); + } + + @Test + void ambientTransactionOrSynchronizationDeniesBeforeAnyRemoteCall() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> service.commit(original(), "creator.credential")) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> service.commit(original(), "creator.credential")) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(account, world, coordinator, terminals, sources, transactions); + } + + @Test + void accountFailureRetainsReservationWithoutInventingAbort() { + var original = original(); + when(account.claim(any())).thenThrow(io.grpc.Status.UNAVAILABLE.asRuntimeException()); + assertThatThrownBy(() -> service.commit(original, "creator.credential")) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + var sequence = inOrder(coordinator, account); + sequence.verify(coordinator).lockVersionTarget(any()); + sequence.verify(coordinator).claim(any(), any()); + sequence.verify(coordinator).claimApplicationSlot(any()); + sequence.verify(account).claim(any()); + verify(coordinator, never()).abortUnattemptedLocalSource(any()); + verify(coordinator, never()).releaseApplicationSlot(any()); + verifyNoInteractions(sources, world); + } + + @Test + void occupiedSlotDeniesBeforeAccountOrSourceApplication() { + doThrow(new DraftCommitCoordinatorRepository.DraftCommitStateConflictException("slot denied")) + .when(coordinator) + .claimApplicationSlot(any()); + assertThatThrownBy(() -> service.commit(original(), "creator.credential")) + .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); + verifyNoInteractions(account, world, sources); + verify(coordinator, never()).releaseApplicationSlot(any()); + } + + @Test + void missingAccountEvidenceDoesNotAuthorizeLocalApplication() { + assertThatThrownBy(() -> service.commit(original(), "creator.credential")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("authenticated original Account order"); + verifyNoInteractions(world, sources); + verify(coordinator, never()).abortUnattemptedLocalSource(any()); + verify(coordinator, never()).releaseApplicationSlot(any()); + } + + @Test + void worldFailureKeepsLocalAppliedAndRetryDoesNotReapplyLocalSource() { + var original = original(); + var state = arrange(original, false); + when(world.apply(any())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); + }); + for (int retry = 0; retry < 2; retry++) { + assertThatThrownBy(() -> service.commit(original, "creator.credential")) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + } + assertThat(state.get(Owner.GAME_DESIGN_CONTROL_PLANE).status()).isEqualTo(OwnerStatus.APPLIED); + assertThat(state.get(Owner.WORLD_MANAGEMENT).status()).isEqualTo(OwnerStatus.IN_PROGRESS); + verify(sources).apply(any()); + verify(world, times(2)).apply(any()); + verify(coordinator, never()).advanceSourceVisibilityFence(any(), any()); + verify(coordinator, never()).releaseApplicationSlot(any()); + verify(coordinator, never()).abortUnattemptedLocalSource(any()); + var sequence = inOrder(sources, coordinator, world); + sequence.verify(sources).apply(any()); + sequence + .verify(coordinator) + .markOwnerInProgress(any(), org.mockito.ArgumentMatchers.eq(Owner.WORLD_MANAGEMENT)); + sequence.verify(world).apply(any()); + } + + @Test + void substitutedWorldRequestCannotAdvanceVisibility() { + var original = original(); + arrange(original, false); + var substituted = mock(WorldOriginalDraftGraphApplyEvidence.Result.class); + when(substituted.request()) + .thenReturn( + WorldOriginalDraftGraphApplyEvidence.Request.create( + "test", original().canonicalBytes())); + when(world.apply(any())).thenReturn(substituted); + assertThatThrownBy(() -> service.commit(original, "creator.credential")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete original request"); + verify(coordinator, never()).recordOwnerOutcome(any(), any()); + verify(coordinator, never()).advanceSourceVisibilityFence(any(), any()); + verify(coordinator, never()).releaseApplicationSlot(any()); + } + + @Test + void malformedWorldCommittedBytesAreRevalidatedEvenFromInjectedClient() { + var original = original(); + arrange(original, false); + var response = mock(WorldOriginalDraftGraphApplyEvidence.Result.class); + when(response.request()) + .thenReturn( + WorldOriginalDraftGraphApplyEvidence.Request.create("test", original.canonicalBytes())); + when(response.ownerReadback()) + .thenReturn( + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + when(world.apply(any())).thenReturn(response); + assertThatThrownBy(() -> service.commit(original, "creator.credential")) + .isInstanceOf(IllegalArgumentException.class); + verify(coordinator, never()).recordOwnerOutcome(any(), any()); + verify(coordinator, never()).releaseApplicationSlot(any()); + } + + @Test + void retainedWorldOutcomeCompletesFullFenceAndFinalRetrySkipsAuthorityAndWrites() { + var original = original(); + arrange(original, true); + var first = service.commit(original, "creator.credential"); + assertThat(first.result()).isEqualTo(GameDesignDraftTerminalOutcome.Result.COMMITTED); + assertThat(service.commit(original, null)).isSameAs(first); + verify(account).claim(any()); + verify(sources).apply(any()); + verify(coordinator).recordOwnerOutcome(any(), any()); + verify(coordinator).advanceSourceVisibilityFence(any(), any()); + verify(coordinator).releaseApplicationSlot(any()); + verifyNoInteractions(world); + } + + @Test + void exactAbortedTerminalIsReturnedBeforeCreatorOrRemoteAuthority() { + var original = original(); + var outcome = mock(GameDesignDraftTerminalOutcome.class); + when(outcome.operation()).thenReturn(new GameDesignDraftTerminalOperation(original)); + when(outcome.result()).thenReturn(GameDesignDraftTerminalOutcome.Result.DEFINITIVELY_ABORTED); + when(terminals.read(any(GameDesignDraftTerminalOperation.class))) + .thenReturn(Optional.of(outcome)); + assertThat(service.commit(original, null)).isSameAs(outcome); + verifyNoInteractions(account, world, coordinator, sources); + } + + @Test + void committedTerminalWithoutSynchronizedSourceBackingCannotReplaySuccess() { + var original = original(); + var outcome = mock(GameDesignDraftTerminalOutcome.class); + when(outcome.operation()).thenReturn(new GameDesignDraftTerminalOperation(original)); + when(outcome.result()).thenReturn(GameDesignDraftTerminalOutcome.Result.COMMITTED); + when(terminals.read(any(GameDesignDraftTerminalOperation.class))) + .thenReturn(Optional.of(outcome)); + assertThatThrownBy(() -> service.commit(original, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Synchronized source readback unavailable"); + verifyNoInteractions(account, world, coordinator); + } + + private EnumMap arrange( + DraftAuthorizationFenceBinding original, boolean worldApplied) { + var binding = new GameDesignDraftTerminalOperation(original).gameDesignBinding(); + var states = new EnumMap(Owner.class); + states.put( + Owner.GAME_DESIGN_CONTROL_PLANE, + state(Owner.GAME_DESIGN_CONTROL_PLANE, OwnerStatus.NOT_ATTEMPTED, null)); + var worldOutcome = outcome(binding, Owner.WORLD_MANAGEMENT); + states.put( + Owner.WORLD_MANAGEMENT, + state( + Owner.WORLD_MANAGEMENT, + worldApplied ? OwnerStatus.APPLIED : OwnerStatus.NOT_ATTEMPTED, + worldApplied ? worldOutcome : null)); + var completed = new AtomicBoolean(); + var terminal = mock(GameDesignDraftTerminalOutcome.class); + when(terminal.operation()).thenReturn(new GameDesignDraftTerminalOperation(original)); + when(terminal.result()).thenReturn(GameDesignDraftTerminalOutcome.Result.COMMITTED); + when(terminals.read(any(GameDesignDraftTerminalOperation.class))) + .thenAnswer(ignored -> completed.get() ? Optional.of(terminal) : Optional.empty()); + when(coordinator.claim(any(), any())).thenAnswer(ignored -> snapshot(binding, states)); + when(coordinator.read(any(), any())) + .thenAnswer(ignored -> Optional.of(snapshot(binding, states))); + when(coordinator.markOwnerInProgress(any(), any())) + .thenAnswer( + invocation -> { + Owner owner = invocation.getArgument(1); + var updated = state(owner, OwnerStatus.IN_PROGRESS, null); + states.put(owner, updated); + return updated; + }); + when(sources.apply(any())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + var local = outcome(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + states.put( + Owner.GAME_DESIGN_CONTROL_PLANE, state(local.owner(), local.status(), local)); + var applied = mock(GameDesignSourceRepository.Application.class); + when(applied.ownerOutcome()).thenReturn(local); + return applied; + }); + when(coordinator.recordOwnerOutcome(any(), any())) + .thenAnswer( + invocation -> { + OwnerOutcome actual = invocation.getArgument(1); + var retained = state(actual.owner(), actual.status(), actual); + states.put(actual.owner(), retained); + return retained; + }); + when(coordinator.advanceSourceVisibilityFence(any(), any())) + .thenAnswer( + ignored -> { + assertThat(states.values()).allMatch(value -> value.status() == OwnerStatus.APPLIED); + completed.set(true); + return null; + }); + var synchronizedSources = mock(GameDesignSourceRepository.SynchronizedSources.class); + var command = mock(CommandSnapshot.class); + when(command.binding()).thenReturn(binding); + when(synchronizedSources.command()).thenReturn(command); + when(sources.readSynchronized(any(), any())).thenReturn(Optional.of(synchronizedSources)); + var order = mock(AccountOriginalDraftOrderEvidence.class); + when(order.matches(any())).thenReturn(true); + when(account.claim(any())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return order; + }); + when(transactions.getTransaction(any())) + .thenAnswer( + ignored -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return mock(TransactionStatus.class); + }); + doAnswer( + ignored -> { + TransactionSynchronizationManager.setActualTransactionActive(false); + return null; + }) + .when(transactions) + .commit(any()); + doAnswer( + ignored -> { + TransactionSynchronizationManager.setActualTransactionActive(false); + return null; + }) + .when(transactions) + .rollback(any()); + return states; + } + + private static CommitSnapshot snapshot( + DraftCommitBinding binding, EnumMap states) { + var now = OffsetDateTime.now(); + return new CommitSnapshot(binding, WorkflowState.APPLYING, now, now, states); + } + + private static OwnerState state(Owner owner, OwnerStatus status, OwnerOutcome outcome) { + var now = OffsetDateTime.now(); + return new OwnerState(owner, status, Optional.ofNullable(outcome), now, now); + } + + private static OwnerOutcome outcome(DraftCommitBinding binding, Owner owner) { + return new OwnerOutcome( + owner, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "mock-owner-result", + new byte[] {1}, + binding.affectedUnits(owner).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + "1")) + .toList()); + } + + private static DraftAuthorizationFenceBinding original() { + return original(List.of(Owner.GAME_DESIGN_CONTROL_PLANE, Owner.WORLD_MANAGEMENT)); + } + + private static DraftAuthorizationFenceBinding original(List owners) { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"); + var revisions = new java.util.ArrayList(); + var units = new java.util.ArrayList(); + for (var owner : owners) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), UUID.randomUUID(), owner, "{}")); + units.add( + new DraftCommitBinding.AffectedUnit( + owner, + "MOCK_SCOPE", + target.canonicalVersionId().toString(), + "MOCK_SCOPE", + "mock", + "0")); + } + var binding = + DraftCommitBinding.create( + target, UUID.randomUUID(), UUID.randomUUID(), "base", revisions, units); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + binding.requestId(), + binding.commitId(), + UUID.randomUUID(), + UUID.randomUUID(), + target.canonicalTenantId(), + target.canonicalVersionId(), + "base", + "0", + binding.canonicalBytes(), + binding.canonicalBytes(), + binding.digest(), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + UUID.randomUUID().toString(), + "1", + "1", + "account", + "1", + new byte[] {1}))) + .withRequiredOwners(); + } +} diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index c124123251..47b07db156 100644 --- a/services/world-management-service/build.gradle.kts +++ b/services/world-management-service/build.gradle.kts @@ -19,3 +19,17 @@ dependencies { testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) } + +// Opt-in owner proof: expose compiled World classes without its application or Flyway resources. +val worldClassesProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("classes-proof") + dependsOn(tasks.named("classes")) + from(sourceSets.main.get().output.classesDirs) +} + +val worldClassesProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(worldClassesProofJar) +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java index a842eb9005..e6fafa944a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityRepository.java @@ -6,6 +6,7 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import org.jooq.DSLContext; @@ -124,6 +125,44 @@ public Optional readByGameDesignVersion( return row == null ? Optional.empty() : Optional.of(toReceipt(row)); } + /** + * Reads the unique immutable identity for an exact canonical target and Game Design row. + * + *

This selector deliberately does not infer or accept a World slug. Multiple rows for the same + * canonical target are conflicting source associations, not a choice to resolve. + */ + public Optional readByCanonicalTarget( + String namespace, + UUID canonicalTenantId, + UUID canonicalVersionId, + long gameDesignVersionRowId) { + requireNoActiveTransaction("World authored-Version identity read"); + if (namespace == null || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requirePositive(gameDesignVersionRowId, "gameDesignVersionRowId"); + + var rows = + dsl.selectFrom(VERSION_IDENTITY) + .where( + TARGET_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(CANONICAL_VERSION_ID.eq(canonicalVersionId)) + .and(GAME_DESIGN_VERSION_ID.eq(gameDesignVersionRowId))) + .fetch(); + if (rows.isEmpty()) { + return Optional.empty(); + } + if (rows.size() != 1) { + throw new InvalidIdentityEvidenceException( + "World authored-Version identity target has ambiguous World associations"); + } + return Optional.of(toReceipt(rows.getFirst())); + } + /** * Atomically claims the source-qualified Version identity with a World-allocated local key. * diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationService.java new file mode 100644 index 0000000000..496ee98394 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationService.java @@ -0,0 +1,187 @@ +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.List; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; + +/** + * Unregistered original-Account entry for applying a source-qualified fresh World graph. + * + *

The Account bytes are immutable input, not permission. An exact committed result is recovered + * before consulting mutable owner state; a new application still enters the held-COMMIT_ORDER + * verifier through {@link WorldDraftGraphApplicationService}. + */ +public final class WorldOriginalDraftGraphApplicationService { + private static final List DRAFT_OWNERS = + List.of( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + private static final List ACCOUNT_OWNERS = List.of(Owner.GAME_DESIGN, Owner.WORLD); + + private final WorldAuthoredVersionIdentityRepository versionIdentities; + private final WorldAuthoredSourceIntakeRepository sourceIntakes; + private final WorldDraftGraphApplicationService graphApplications; + + public WorldOriginalDraftGraphApplicationService( + WorldAuthoredVersionIdentityRepository versionIdentities, + WorldAuthoredSourceIntakeRepository sourceIntakes, + WorldDraftGraphApplicationService graphApplications) { + this.versionIdentities = Objects.requireNonNull(versionIdentities, "versionIdentities"); + this.sourceIntakes = Objects.requireNonNull(sourceIntakes, "sourceIntakes"); + this.graphApplications = Objects.requireNonNull(graphApplications, "graphApplications"); + } + + /** + * Resolves the complete World owner binding from committed World receipts, then applies the + * original Account operation. The only caller-supplied operation material is its receiver + * namespace and unchanged complete Account binding bytes. + */ + public WorldDraftGraphAppliedResult apply( + String receiverNamespace, byte[] originalAccountBindingBytes) { + if (receiverNamespace == null || !GrpcPeerIdentity.isValidNamespace(receiverNamespace)) { + throw new IllegalArgumentException("Receiver namespace must be one canonical DNS label"); + } + byte[] originalBytes = requireBytes(originalAccountBindingBytes); + DraftAuthorizationFenceBinding accountBinding = + DraftAuthorizationFenceBinding.fromStored(originalBytes); + byte[] completeBindingBytes = accountBinding.gameDesignBinding(); + DraftCommitBinding binding = + DraftCommitBinding.fromStored( + new String(completeBindingBytes, StandardCharsets.UTF_8), digest(completeBindingBytes)); + requireSupportedOwnerVectors(accountBinding, binding); + + var prior = graphApplications.readCommitted(receiverNamespace, originalBytes); + if (prior.isPresent()) { + return prior.orElseThrow(); + } + + DraftCommitBinding.TargetProof target = binding.target(); + if (!"NEW_GAME_ROW".equals(target.sourceProvenanceKind())) { + throw conflict("World original graph application requires retained fresh-source provenance"); + } + WorldAuthoredVersionIdentityReceipt identity = + versionIdentities + .readByCanonicalTarget( + receiverNamespace, + target.canonicalTenantId(), + target.canonicalVersionId(), + target.gameDesignVersionRowId()) + .orElseThrow( + () -> + new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Exact World authored-Version identity receipt is missing")); + + WorldAuthoredSourceIntakeReceipt retainedIntake = identity.sourceIntakeReceipt(); + WorldAuthoredSourceIntakeReceipt committedIntake = + sourceIntakes + .read(receiverNamespace, retainedIntake.intakeRequestId()) + .orElseThrow( + () -> + new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Exact World source intake association is missing")); + if (!retainedIntake.equals(committedIntake)) { + throw conflict("World Version identity differs from its independently read source intake"); + } + + requireExactSourceTarget(receiverNamespace, target, identity, committedIntake); + OwnerBinding ownerBinding = ownerBinding(receiverNamespace, identity, committedIntake); + WorldDraftTerminalOperation operation = + new WorldDraftTerminalOperation( + accountBinding.operationId(), + accountBinding.requestId(), + accountBinding.commitId(), + accountBinding.fenceId(), + accountBinding.tenantId(), + accountBinding.versionId(), + binding, + ownerBinding, + originalBytes); + WorldDraftTopologyCommitPlan plan = WorldDraftTopologyCommitPlan.create(binding, ownerBinding); + return graphApplications.apply(new WorldDraftGraphApplication(operation, plan)); + } + + private static void requireSupportedOwnerVectors( + DraftAuthorizationFenceBinding accountBinding, DraftCommitBinding binding) { + if (!DRAFT_OWNERS.equals(binding.requiredOwners()) + || !ACCOUNT_OWNERS.equals(accountBinding.requiredOwners())) { + throw conflict( + "World original graph application requires the exact supported GD+World owners"); + } + } + + private static void requireExactSourceTarget( + String receiverNamespace, + DraftCommitBinding.TargetProof target, + WorldAuthoredVersionIdentityReceipt identity, + WorldAuthoredSourceIntakeReceipt intake) { + var stateRequest = identity.versionStateEvidence().request(); + var source = intake.source(); + if (!"NEW_GAME_ROW".equals(source.provenanceKind()) + || !receiverNamespace.equals(identity.targetNamespace()) + || !receiverNamespace.equals(intake.targetNamespace()) + || !target.canonicalTenantId().equals(identity.canonicalTenantId()) + || !target.canonicalTenantId().equals(intake.canonicalTenantId()) + || !target.canonicalTenantId().equals(source.canonicalTenantId()) + || !target.canonicalVersionId().equals(identity.canonicalVersionId()) + || target.gameDesignVersionRowId() != identity.gameDesignVersionId() + || target.gameDesignVersionRowId() != stateRequest.versionId() + || !receiverNamespace.equals(stateRequest.targetNamespace()) + || !target.canonicalTenantId().equals(stateRequest.canonicalTenantId()) + || target.sourceGameRowId() != source.sourceGameRowId() + || !target.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !target.gameDesignVersionTenantKey().equals(source.sourceGameTenantKey()) + || !target.sourceProvenanceKind().equals(source.provenanceKind()) + || !intake.sourceOperationId().equals(source.operationId()) + || !intake.sourceEvidenceDigest().equals(source.evidenceDigest())) { + throw conflict( + "Original Draft target differs from the exact retained World source and Version receipt"); + } + } + + private static OwnerBinding ownerBinding( + String receiverNamespace, + WorldAuthoredVersionIdentityReceipt identity, + WorldAuthoredSourceIntakeReceipt intake) { + return new OwnerBinding( + receiverNamespace, + identity.canonicalTenantId(), + identity.canonicalVersionId(), + identity.operationId(), + identity.gameDesignVersionId(), + intake.intakeRequestId(), + intake.operationId(), + intake.requestDigest(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.receiptDigest()); + } + + private static byte[] requireBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0) { + throw new IllegalArgumentException("Complete original Account binding bytes are required"); + } + return bytes.clone(); + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static WorldAuthoredVersionIdentityRepository.RegistrationConflictException conflict( + String message) { + return new WorldAuthoredVersionIdentityRepository.RegistrationConflictException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcService.java new file mode 100644 index 0000000000..f4e65d9104 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcService.java @@ -0,0 +1,77 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.v1.ApplyOriginalDraftGraphRequest; +import net.firedevops.firemud.worldmanagement.v1.ApplyOriginalDraftGraphResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldOriginalDraftGraphApplyServiceGrpc; + +/** Unregistered Game Design-only original graph apply/recovery construction adapter. */ +public final class WorldOriginalDraftGraphApplyGrpcService + extends WorldOriginalDraftGraphApplyServiceGrpc.WorldOriginalDraftGraphApplyServiceImplBase { + private final WorldOriginalDraftGraphApplicationService applications; + private final String namespace; + + public WorldOriginalDraftGraphApplyGrpcService( + WorldOriginalDraftGraphApplicationService applications, String namespace) { + this.applications = Objects.requireNonNull(applications, "applications"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical World namespace required"); + } + this.namespace = namespace; + } + + @Override + public void applyOriginalDraftGraph( + ApplyOriginalDraftGraphRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext()) { + deny( + observer, + Status.PERMISSION_DENIED, + "Verified same-namespace Game Design workload required"); + return; + } + try { + var request = WorldOriginalDraftGraphApplyGrpcCodec.fromRequest(wire); + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED, "World original apply namespace mismatch"); + return; + } + var result = applications.apply(namespace, request.originalAccountBinding()); + var response = + WorldOriginalDraftGraphApplyGrpcCodec.toResponse(request, result.ownerReadback()); + observer.onNext(response); + observer.onCompleted(); + } catch (IllegalArgumentException invalid) { + deny(observer, Status.INVALID_ARGUMENT, "Canonical original World apply evidence required"); + } catch (SecurityException denied) { + deny(observer, Status.PERMISSION_DENIED, "World original apply authorization denied"); + } catch (WorldDesignPublicationFenceRepository.ConflictException conflict) { + deny( + observer, + Status.FAILED_PRECONDITION, + "World original apply conflicts with retained evidence"); + } catch (org.springframework.dao.DataAccessException + | org.jooq.exception.DataAccessException unavailable) { + deny(observer, Status.UNAVAILABLE, "World original apply storage unavailable"); + } catch (RuntimeException failure) { + deny( + observer, + Status.FAILED_PRECONDITION, + "World original apply could not establish committed evidence"); + } + } + + private static void deny(StreamObserver observer, Status status, String description) { + observer.onError(status.withDescription(description).asRuntimeException()); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java new file mode 100644 index 0000000000..6c7e5a0d73 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java @@ -0,0 +1,94 @@ +package unit.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.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import org.jooq.Condition; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.SelectConditionStep; +import org.jooq.SelectWhereStep; +import org.jooq.Table; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldAuthoredVersionIdentityCanonicalTargetReadTest { + private final DSLContext dsl = mock(DSLContext.class); + + @AfterEach + void clearTransactionFixture() { + TransactionSynchronizationManager.clear(); + } + + @Test + void canonicalTargetReadRejectsAmbientTransactionBeforeSql() { + TransactionSynchronizationManager.setActualTransactionActive(true); + var repository = new WorldAuthoredVersionIdentityRepository(dsl); + + assertThatThrownBy( + () -> + repository.readByCanonicalTarget( + "firemud", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 42L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent committed owner read"); + + verifyNoInteractions(dsl); + } + + @Test + @SuppressWarnings("unchecked") + void canonicalTargetReadRejectsMultipleWorldAssociationsAsAmbiguous() { + SelectWhereStep selectedTable = mock(SelectWhereStep.class); + SelectConditionStep selectedTarget = mock(SelectConditionStep.class); + Result rows = mock(Result.class); + doReturn(selectedTable).when(dsl).selectFrom(any(Table.class)); + when(selectedTable.where(any(Condition.class))).thenReturn(selectedTarget); + when(selectedTarget.fetch()).thenReturn(rows); + when(rows.isEmpty()).thenReturn(false); + when(rows.size()).thenReturn(2); + var repository = new WorldAuthoredVersionIdentityRepository(dsl); + + assertThatThrownBy( + () -> + repository.readByCanonicalTarget( + "firemud", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 42L)) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) + .hasMessageContaining("ambiguous World associations"); + } + + @Test + @SuppressWarnings("unchecked") + void canonicalTargetReadReturnsEmptyWhenNoExactAssociationExists() { + SelectWhereStep selectedTable = mock(SelectWhereStep.class); + SelectConditionStep selectedTarget = mock(SelectConditionStep.class); + Result rows = mock(Result.class); + doReturn(selectedTable).when(dsl).selectFrom(any(Table.class)); + when(selectedTable.where(any(Condition.class))).thenReturn(selectedTarget); + when(selectedTarget.fetch()).thenReturn(rows); + when(rows.isEmpty()).thenReturn(true); + var repository = new WorldAuthoredVersionIdentityRepository(dsl); + + assertThat( + repository.readByCanonicalTarget( + "firemud", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 42L)) + .isEmpty(); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationServiceTest.java new file mode 100644 index 0000000000..92f676d42b --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationServiceTest.java @@ -0,0 +1,513 @@ +package unit.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.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +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 com.google.protobuf.util.JsonFormat; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplication; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphAppliedResult; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplicationService; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class WorldOriginalDraftGraphApplicationServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID TENANT = id(1); + private static final UUID VERSION = id(2); + private static final UUID REGISTRATION_REQUEST = id(3); + private static final UUID SOURCE_OPERATION = id(4); + private static final UUID INTAKE_REQUEST = id(5); + private static final UUID INTAKE_OPERATION = id(6); + private static final UUID VERSION_READ_REQUEST = id(7); + private static final UUID VERSION_IDENTITY_OPERATION = id(8); + private static final UUID ACCOUNT_OPERATION = id(9); + private static final UUID REQUEST = id(10); + private static final UUID COMMIT = id(11); + private static final UUID FENCE = id(12); + private static final UUID ACTOR = id(13); + private static final UUID REGION = id(14); + private static final long GAME_DESIGN_VERSION_ROW = 42L; + private static final long SOURCE_GAME_ROW = 81L; + private static final String GAME_TENANT_KEY = "legacy-game-tenant-42"; + + private final WorldAuthoredVersionIdentityRepository identities = + mock(WorldAuthoredVersionIdentityRepository.class); + private final WorldAuthoredSourceIntakeRepository intakes = + mock(WorldAuthoredSourceIntakeRepository.class); + private final WorldDraftGraphApplicationService graphApplications = + mock(WorldDraftGraphApplicationService.class); + private final WorldOriginalDraftGraphApplicationService service = + new WorldOriginalDraftGraphApplicationService(identities, intakes, graphApplications); + + @Test + void derivesRealTerminalOperationAndTopologyFromExactCommittedReceipts() { + var source = source(); + var intake = intake(source); + var identity = identity(intake); + byte[] accountBytes = accountBinding(binding()).canonicalBytes(); + var result = mock(WorldDraftGraphAppliedResult.class); + when(graphApplications.readCommitted(eq(NAMESPACE), any(byte[].class))) + .thenReturn(Optional.empty()); + when(identities.readByCanonicalTarget(NAMESPACE, TENANT, VERSION, GAME_DESIGN_VERSION_ROW)) + .thenReturn(Optional.of(identity)); + when(intakes.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(intake)); + when(graphApplications.apply(any(WorldDraftGraphApplication.class))).thenReturn(result); + + assertThat(service.apply(NAMESPACE, accountBytes)).isSameAs(result); + + ArgumentCaptor application = + ArgumentCaptor.forClass(WorldDraftGraphApplication.class); + var order = inOrder(graphApplications, identities, intakes); + order.verify(graphApplications).readCommitted(eq(NAMESPACE), any(byte[].class)); + order + .verify(identities) + .readByCanonicalTarget(NAMESPACE, TENANT, VERSION, GAME_DESIGN_VERSION_ROW); + order.verify(intakes).read(NAMESPACE, INTAKE_REQUEST); + order.verify(graphApplications).apply(application.capture()); + var applied = application.getValue(); + assertThat(applied.operation().operationId()).isEqualTo(ACCOUNT_OPERATION); + assertThat(applied.operation().requestId()).isEqualTo(REQUEST); + assertThat(applied.operation().commitId()).isEqualTo(COMMIT); + assertThat(applied.operation().authorizationFenceId()).isEqualTo(FENCE); + assertThat(applied.operation().accountBindingBytes()).isEqualTo(accountBytes); + assertThat(applied.operation().ownerBinding()) + .isEqualTo( + new OwnerBinding( + NAMESPACE, + TENANT, + VERSION, + VERSION_IDENTITY_OPERATION, + GAME_DESIGN_VERSION_ROW, + INTAKE_REQUEST, + INTAKE_OPERATION, + intake.requestDigest(), + SOURCE_OPERATION, + source.evidenceDigest(), + intake.receiptDigest())); + assertThat(applied.plan().binding().target().sourceGameRowId()).isEqualTo(SOURCE_GAME_ROW); + assertThat(applied.plan().graph().nodes()).hasSize(1); + assertThat(applied.plan().graph().nodes().getFirst().templateId()).isEqualTo(REGION); + } + + @Test + void exactReplayIsRecoveredBeforeAnyMutableIdentityOrIntakeLookup() { + byte[] originalBytes = accountBinding(binding()).canonicalBytes(); + var prior = mock(WorldDraftGraphAppliedResult.class); + when(graphApplications.readCommitted(eq(NAMESPACE), any(byte[].class))) + .thenReturn(Optional.of(prior)); + + assertThat(service.apply(NAMESPACE, originalBytes)).isSameAs(prior); + + var order = inOrder(graphApplications, identities, intakes); + order.verify(graphApplications).readCommitted(eq(NAMESPACE), any(byte[].class)); + verifyNoInteractions(identities, intakes); + verify(graphApplications, never()).apply(any(WorldDraftGraphApplication.class)); + } + + @Test + void missingIdentityOrAmbiguousIdentityDeniesWithoutSourceLookupOrApply() { + byte[] originalBytes = accountBinding(binding()).canonicalBytes(); + when(graphApplications.readCommitted(eq(NAMESPACE), any(byte[].class))) + .thenReturn(Optional.empty()); + when(identities.readByCanonicalTarget(NAMESPACE, TENANT, VERSION, GAME_DESIGN_VERSION_ROW)) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.apply(NAMESPACE, originalBytes)) + .isInstanceOf(InvalidIdentityEvidenceException.class) + .hasMessageContaining("identity receipt is missing"); + verifyNoInteractions(intakes); + verify(graphApplications, never()).apply(any(WorldDraftGraphApplication.class)); + + when(identities.readByCanonicalTarget(NAMESPACE, TENANT, VERSION, GAME_DESIGN_VERSION_ROW)) + .thenThrow( + new InvalidIdentityEvidenceException( + "World authored-Version identity target has ambiguous World associations")); + assertThatThrownBy(() -> service.apply(NAMESPACE, originalBytes)) + .isInstanceOf(InvalidIdentityEvidenceException.class) + .hasMessageContaining("ambiguous"); + verifyNoInteractions(intakes); + verify(graphApplications, never()).apply(any(WorldDraftGraphApplication.class)); + } + + @Test + void missingOrSubstitutedSourceAssociationDeniesBeforeApplying() { + var source = source(); + var intake = intake(source); + var identity = identity(intake); + byte[] originalBytes = accountBinding(binding()).canonicalBytes(); + when(graphApplications.readCommitted(eq(NAMESPACE), any(byte[].class))) + .thenReturn(Optional.empty()); + when(identities.readByCanonicalTarget(NAMESPACE, TENANT, VERSION, GAME_DESIGN_VERSION_ROW)) + .thenReturn(Optional.of(identity)); + + when(intakes.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + assertThatThrownBy(() -> service.apply(NAMESPACE, originalBytes)) + .isInstanceOf(InvalidIdentityEvidenceException.class) + .hasMessageContaining("source intake association is missing"); + + var substituted = intake(source("other-world", SOURCE_OPERATION)); + when(intakes.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(substituted)); + assertThatThrownBy(() -> service.apply(NAMESPACE, originalBytes)) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("independently read source intake"); + verify(graphApplications, never()).apply(any(WorldDraftGraphApplication.class)); + } + + @Test + void sourceRowKeyProvenanceAndTargetScopeSubstitutionsAreDenied() { + var source = source(); + var intake = intake(source); + var identity = identity(intake); + when(graphApplications.readCommitted(anyString(), any(byte[].class))) + .thenReturn(Optional.empty()); + when(identities.readByCanonicalTarget(anyString(), any(UUID.class), any(UUID.class), anyLong())) + .thenReturn(Optional.of(identity)); + when(intakes.read(anyString(), eq(INTAKE_REQUEST))).thenReturn(Optional.of(intake)); + + byte[] wrongRow = + accountBinding(binding(SOURCE_GAME_ROW + 1, GAME_TENANT_KEY, "NEW_GAME_ROW")) + .canonicalBytes(); + assertThatThrownBy(() -> service.apply(NAMESPACE, wrongRow)) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("retained World source"); + + byte[] wrongKey = + accountBinding(binding(SOURCE_GAME_ROW, "substituted-key", "NEW_GAME_ROW")) + .canonicalBytes(); + assertThatThrownBy(() -> service.apply(NAMESPACE, wrongKey)) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("retained World source"); + + byte[] unsupportedProvenance = + accountBinding(binding(SOURCE_GAME_ROW, GAME_TENANT_KEY, "RETAINED_GAME_V29")) + .canonicalBytes(); + assertThatThrownBy(() -> service.apply(NAMESPACE, unsupportedProvenance)) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("requires retained fresh-source provenance"); + + assertThatThrownBy(() -> service.apply("other", accountBinding(binding()).canonicalBytes())) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("retained World source"); + + assertThatThrownBy( + () -> + service.apply( + NAMESPACE, + accountBinding( + binding( + id(22), + VERSION, + GAME_DESIGN_VERSION_ROW, + GAME_TENANT_KEY, + SOURCE_GAME_ROW, + GAME_TENANT_KEY, + "NEW_GAME_ROW")) + .canonicalBytes())) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("retained World source"); + + assertThatThrownBy( + () -> + service.apply( + NAMESPACE, + accountBinding( + binding( + TENANT, + id(23), + GAME_DESIGN_VERSION_ROW, + GAME_TENANT_KEY, + SOURCE_GAME_ROW, + GAME_TENANT_KEY, + "NEW_GAME_ROW")) + .canonicalBytes())) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("retained World source"); + + assertThatThrownBy( + () -> + service.apply( + NAMESPACE, + accountBinding( + binding( + TENANT, + VERSION, + GAME_DESIGN_VERSION_ROW + 1, + GAME_TENANT_KEY, + SOURCE_GAME_ROW, + GAME_TENANT_KEY, + "NEW_GAME_ROW")) + .canonicalBytes())) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("retained World source"); + verify(graphApplications, never()).apply(any(WorldDraftGraphApplication.class)); + } + + @Test + void accountAndDraftOwnerVectorsMustBeExactlyGameDesignAndWorld() { + DraftCommitBinding binding = bindingWithExtraOwner(); + byte[] accountBytes = accountBinding(binding).canonicalBytes(); + when(graphApplications.readCommitted(eq(NAMESPACE), any(byte[].class))) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.apply(NAMESPACE, accountBytes)) + .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) + .hasMessageContaining("exact supported GD+World owners"); + verifyNoInteractions(identities, intakes); + verify(graphApplications, never()).apply(any(WorldDraftGraphApplication.class)); + } + + private static DraftAuthorizationFenceBinding accountBinding(DraftCommitBinding binding) { + byte[] complete = binding.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + ACCOUNT_OPERATION, + REQUEST, + COMMIT, + FENCE, + ACTOR, + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.baseCommitId(), + "0", + complete, + complete, + binding.digest(), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, ACTOR.toString(), "1", "1", null, null, new byte[] {1})), + DraftAuthorizationFenceBinding.SCHEMA_V2, + accountOwners(binding)); + } + + private static List accountOwners(DraftCommitBinding binding) { + var owners = new java.util.ArrayList(); + owners.add(Owner.GAME_DESIGN); + for (DraftCommitBinding.Owner owner : binding.requiredOwners()) { + switch (owner) { + case WORLD_MANAGEMENT -> owners.add(Owner.WORLD); + case ENTITY_MANAGEMENT -> owners.add(Owner.ENTITY); + case GAME_LOGIC -> owners.add(Owner.GAME_LOGIC); + case AUTOMATION_SCRIPTING -> owners.add(Owner.AUTOMATION); + case GAME_DESIGN_CONTROL_PLANE -> {} + } + } + return List.copyOf(owners); + } + + private static DraftCommitBinding binding() { + return binding(SOURCE_GAME_ROW, GAME_TENANT_KEY, "NEW_GAME_ROW"); + } + + private static DraftCommitBinding binding(long sourceRow, String sourceKey, String provenance) { + return binding( + TENANT, VERSION, GAME_DESIGN_VERSION_ROW, sourceKey, sourceRow, sourceKey, provenance); + } + + private static DraftCommitBinding binding( + UUID canonicalTenantId, + UUID canonicalVersionId, + long gameDesignVersionRowId, + String gameDesignVersionTenantKey, + long sourceRow, + String sourceKey, + String provenance) { + var mutation = + WorldDesignMutationRevision.newBuilder() + .setCommitId(COMMIT.toString()) + .setLogicalRevisionId(id(15).toString()) + .setAggregateId(REGION.toString()) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setAggregateType(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(REGION.toString()) + .setRegion(RegionDesignMutation.newBuilder().setName("North")) + .build(); + try { + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + canonicalTenantId, + canonicalVersionId, + gameDesignVersionRowId, + gameDesignVersionTenantKey, + sourceRow, + sourceKey, + provenance), + REQUEST, + COMMIT, + "base-commit", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", id(16), DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, "gd-original"), + new DraftCommitBinding.RevisionPayload( + "1", + id(15), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + JsonFormat.printer().print(mutation))), + worldUnits()); + } catch (com.google.protobuf.InvalidProtocolBufferException exception) { + throw new IllegalStateException(exception); + } + } + + private static DraftCommitBinding bindingWithExtraOwner() { + DraftCommitBinding original = binding(); + var units = new java.util.ArrayList<>(original.affectedUnits()); + units.add( + new AffectedUnit( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + "ENTITY", + id(20).toString(), + "AGGREGATE", + id(20).toString(), + "0")); + var revisions = new java.util.ArrayList<>(original.revisions()); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "2", id(21), DraftCommitBinding.Owner.ENTITY_MANAGEMENT, "entity-original")); + return DraftCommitBinding.create( + original.target(), REQUEST, COMMIT, original.baseCommitId(), revisions, units); + } + + private static List worldUnits() { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "DRAFT", + VERSION.toString(), + "AGGREGATE", + VERSION.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "REGION", + REGION.toString(), + "AGGREGATE", + REGION.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "REGION", + REGION.toString(), + "REGION_SUBTREE", + REGION.toString(), + "0")); + } + + private static AuthoredWorldSourceEvidence source() { + return source("violet-wilds", SOURCE_OPERATION); + } + + private static AuthoredWorldSourceEvidence source(String worldSlug, UUID sourceOperationId) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_REQUEST, TENANT, "north-star", worldSlug, "Violet Wilds"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_REQUEST, + sourceOperationId, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Violet Wilds", + SOURCE_GAME_ROW, + GAME_TENANT_KEY, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_REQUEST, + sourceOperationId, + requestDigest, + TENANT, + "north-star", + worldSlug, + "Violet Wilds", + SOURCE_GAME_ROW, + GAME_TENANT_KEY, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static WorldAuthoredSourceIntakeReceipt intake(AuthoredWorldSourceEvidence source) { + String requestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, source); + return new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + INTAKE_OPERATION, + TENANT, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, INTAKE_OPERATION, requestDigest, source, 91L), + 91L, + source); + } + + private static WorldAuthoredVersionIdentityReceipt identity( + WorldAuthoredSourceIntakeReceipt intake) { + var stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + VERSION_READ_REQUEST, + TENANT, + intake.worldSlug(), + SOURCE_OPERATION, + intake.sourceEvidenceDigest(), + GAME_DESIGN_VERSION_ROW); + var state = + AuthoredWorldVersionStateEvidence.create( + stateRequest, + intake.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 3L); + return new WorldAuthoredVersionIdentityReceipt( + 1, VERSION_IDENTITY_OPERATION, 101L, intake, state); + } + + private static UUID id(int value) { + return UUID.fromString(String.format("%08d-0000-4000-8000-%012d", value, value)); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java new file mode 100644 index 0000000000..13b2c5a708 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java @@ -0,0 +1,283 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyEvidence; +import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphAppliedResult; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplicationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplyGrpcService; +import net.firedevops.firemud.worldmanagement.v1.ApplyOriginalDraftGraphRequest; +import net.firedevops.firemud.worldmanagement.v1.ApplyOriginalDraftGraphResponse; +import org.junit.jupiter.api.Test; + +/** + * Guard/dispatch structural proof only; authentic source/persistence is the owner's separate proof. + */ +class WorldOriginalDraftGraphApplyGrpcServiceTest { + @Test + void deniesMissingOtherAccountAndWrongNamespacePeersBeforeDecodingOrOwnerAccess() { + var owner = mock(WorldOriginalDraftGraphApplicationService.class); + var grpc = new WorldOriginalDraftGraphApplyGrpcService(owner, "test"); + var malformed = ApplyOriginalDraftGraphRequest.newBuilder().setSchemaVersion(-1).build(); + for (var service : + List.of("account-service", "world-management-service", "game-session-service")) { + var response = call(grpc, malformed, peer(service, "test")); + assertThat(response.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(call(grpc, malformed, null).code()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(grpc, malformed, peer("game-design-service", "other")).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } + + @Test + void rejectsPlayerContextEvenWithCorrectWorkloadBeforeDecode() { + var owner = mock(WorldOriginalDraftGraphApplicationService.class); + var grpc = new WorldOriginalDraftGraphApplyGrpcService(owner, "test"); + SessionContext.setContext("123", List.of(), Map.of()); + try { + var response = + call( + grpc, + ApplyOriginalDraftGraphRequest.getDefaultInstance(), + peer("game-design-service", "test")); + assertThat(response.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } finally { + SessionContext.clear(); + } + } + + @Test + void sameNamespaceGameDesignAuthenticatesButInvalidUnknownAndUnsupportedInputsNeverInvokeOwner() { + var owner = mock(WorldOriginalDraftGraphApplicationService.class); + var grpc = new WorldOriginalDraftGraphApplyGrpcService(owner, "test"); + var wire = WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request("test")); + var unknown = + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + List.of( + ApplyOriginalDraftGraphRequest.getDefaultInstance(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder() + .setOriginalAccountBinding(com.google.protobuf.ByteString.copyFrom(binding(false))) + .build())) { + var response = call(grpc, invalid, peer("game-design-service", "test")); + assertThat(response.code()).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + } + assertThat( + call( + grpc, + WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request("other")), + peer("game-design-service", "test")) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } + + @Test + void passesOnlyExactOriginalBytesAndPropagatesStorageFailureWithoutTerminalAbort() { + var owner = mock(WorldOriginalDraftGraphApplicationService.class); + var request = request("test"); + when(owner.apply(eq("test"), any(byte[].class))) + .thenThrow(new org.jooq.exception.DataAccessException("lost database connection")); + var grpc = new WorldOriginalDraftGraphApplyGrpcService(owner, "test"); + var response = + call( + grpc, + WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request), + peer("game-design-service", "test")); + verify(owner).apply("test", request.originalAccountBinding()); + assertThat(response.code()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + } + + @Test + void deniesOwnerConflictAndMalformedReadbackRatherThanEmittingSuccess() { + var owner = mock(WorldOriginalDraftGraphApplicationService.class); + var request = request("test"); + when(owner.apply(eq("test"), any(byte[].class))) + .thenThrow(new IllegalStateException("retained operation conflict")); + var grpc = new WorldOriginalDraftGraphApplyGrpcService(owner, "test"); + assertThat( + call( + grpc, + WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request), + peer("game-design-service", "test")) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + var result = mock(WorldDraftGraphAppliedResult.class); + var account = request.accountBinding(); + when(result.ownerReadback()) + .thenReturn( + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + new byte[] {1})); + when(owner.apply(eq("test"), any(byte[].class))).thenReturn(result); + var malformed = + call( + grpc, + WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request), + peer("game-design-service", "test")); + assertThat(malformed.code()).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(malformed.value).isNull(); + assertThat(malformed.completed).isFalse(); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static Collector call( + WorldOriginalDraftGraphApplyGrpcService grpc, + ApplyOriginalDraftGraphRequest wire, + GrpcPeerIdentity peer) { + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var previous = context.attach(); + var response = new Collector(); + try { + grpc.applyOriginalDraftGraph(wire, response); + } finally { + context.detach(previous); + } + return response; + } + + static WorldOriginalDraftGraphApplyEvidence.Request request(String namespace) { + return WorldOriginalDraftGraphApplyEvidence.Request.create(namespace, binding(true)); + } + + static byte[] binding(boolean includeGameDesign) { + var tenant = UUID.fromString("11111111-1111-4111-8111-111111111111"); + var version = UUID.fromString("22222222-2222-4222-8222-222222222222"); + var request = UUID.fromString("44444444-4444-4444-8444-444444444444"); + var commit = UUID.fromString("55555555-5555-4555-8555-555555555555"); + var revisions = new java.util.ArrayList(); + revisions.add( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("66666666-6666-4666-8666-666666666666"), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "{}")); + var units = new java.util.ArrayList(); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "7")); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ZONE_SCOPE", + "zone-1", + "19")); + if (includeGameDesign) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + "1", + UUID.fromString("77777777-7777-4777-8777-777777777777"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")); + units.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "DESIGN", + "design-1", + "REVISION", + "revision-1", + "0")); + } + var draft = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + "base-1", + revisions, + units); + return new DraftAuthorizationFenceBinding( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request, + commit, + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + tenant, + version, + "base-1", + "0", + draft.canonicalBytes(), + draft.canonicalBytes(), + draft.digest(), + java.util.List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.GLOBAL_ROLES, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + null, + "1", + null, + null, + new byte[] {1}))) + .canonicalBytes(); + } + + private static final class Collector implements StreamObserver { + private ApplyOriginalDraftGraphResponse value; + private Status.Code errorCode = Status.Code.OK; + private boolean completed; + + Status.Code code() { + return errorCode; + } + + @Override + public void onNext(ApplyOriginalDraftGraphResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + errorCode = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} From 183a243f6aacd41f391c10943ca18dc1b50dae7b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 22:43:58 +1300 Subject: [PATCH 049/129] Complete exact World source reads and selected publication digests --- .../game-design-service/version-control.md | 2 + .../world-management-service/api-contracts.md | 4 + design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 4 +- ...ld_authored_version_identity_service.proto | 31 ++ .../v1/world_management_service.proto | 52 +++ ...nAuthorizationPostgresIntegrationTest.java | 2 +- .../WorldAuthoredVersionIdentityClient.java | 161 +++++++++ .../WorldAuthoredVersionIdentityEvidence.java | 140 ++++++++ ...WorldAuthoredVersionIdentityGrpcCodec.java | 128 +++++++ ...thoredWorldReleaseAttestationEvidence.java | 22 +- ...GameDesignPublicationTerminalEvidence.java | 3 +- .../WorldAuthoredSourceIntakeClient.java | 18 + .../WorldAuthoredSourceIntakeGrpcCodec.java | 229 +++++++++++- ...orldAuthoredVersionIdentityClientTest.java | 152 ++++++++ ...dAuthoredVersionIdentityGrpcCodecTest.java | 212 +++++++++++ ...edWorldReleaseAttestationSelectorTest.java | 62 +++- ...nPublicationTerminalReadGrpcCodecTest.java | 40 ++- .../WorldAuthoredSourceIntakeClientTest.java | 209 +++++++++++ ...orldInstancePreparationClientMtlsTest.java | 2 +- ...WorldInstancePreparationGrpcCodecTest.java | 2 +- ...rldCanonicalInitialPlayerLocationTest.java | 2 +- ...anonicalInstanceLifecycleEvidenceTest.java | 24 +- ...blishedSpawnRequirementsGrpcCodecTest.java | 2 +- ...onicalPlayerAdmissionHoldEvidenceTest.java | 2 +- .../SelectedDraftControlPlaneDigest.java | 121 +++++++ ...ctedDraftPublicationDigestReadService.java | 336 ++++++++++++++++++ .../service/PublishGateService.java | 6 + .../CompleteLaunchBindingServiceImpl.java | 11 +- .../service/impl/PublishGateServiceImpl.java | 122 ++++++- .../impl/PublishedReleaseBundleContract.java | 3 +- .../VersionPublishCommandServiceImpl.java | 16 +- .../impl/PublishedWorldSelectorFixtures.java | 5 +- ...ldSourceCommitPostgresIntegrationTest.java | 116 +++--- .../SelectedDraftControlPlaneDigestTest.java | 215 +++++++++++ ...DraftPublicationDigestReadServiceTest.java | 324 +++++++++++++++++ .../CompleteLaunchBindingServiceImplTest.java | 48 +++ .../impl/PublishGateServiceImplTest.java | 202 ++++++++++- ...PublishedReleaseBundleServiceImplTest.java | 23 ++ .../VersionPublishCommandServiceImplTest.java | 2 +- .../WorldAuthoredSourceIntakeGrpcService.java | 102 ++++++ .../WorldAuthoredSourceIntakeService.java | 42 +++ ...rldAuthoredVersionIdentityGrpcService.java | 106 ++++++ .../WorldCanonicalInstancePreparation.java | 2 +- ...rldOriginalDraftGraphApplyGrpcService.java | 46 +++ ...aphApplicationPostgresIntegrationTest.java | 5 +- ...DesignPublicationTerminalVerifierTest.java | 2 +- ...ldAuthoredSourceIntakeGrpcServiceTest.java | 139 ++++++++ .../WorldAuthoredSourceIntakeServiceTest.java | 113 ++++++ ...uthoredVersionIdentityGrpcServiceTest.java | 243 +++++++++++++ ...anonicalPlayerLocationGrpcServiceTest.java | 2 +- ...riginalDraftGraphApplyGrpcServiceTest.java | 45 +++ 52 files changed, 3817 insertions(+), 91 deletions(-) create mode 100644 protos/world-management/v1/world_authored_version_identity_service.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcService.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcServiceTest.java diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 4a4b67baeb..f45a866a63 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -174,6 +174,8 @@ In addition to domain-service digests, publish safety requires a Game Design con Digest comparison rules: +For a new immutable selected-Draft full publication, the Game Design control-plane participant uses `digestSchemaVersion=2`, not the legacy mutable normalized-row digest. Its SHA-256 preimage uses ADR 0047-style canonical decimal ASCII byte-length framing: first the domain `game-design-selected-draft-control-plane-digest/v2`, then the exact canonical selected Draft binding, followed by each family label and its exact canonical synchronized snapshot bytes in the fixed order `COMMAND`, `REALM_POLICY`, `ASSET`, `GAMEPLAY_SOURCE`, `BRANDING`, `TEMPLATE_CONFIG`. All six snapshots must bind that same original Draft operation and commit. Branding and template/config absence is unknown, never an empty-family attestation. The immutable publication operation's five captured source families must match their synchronized selected snapshots byte-for-byte in one owner snapshot; the gameplay source is independently read from the same synchronized commit. The publication request binding and its digest are echoed and checked separately, not included in this content preimage. Mutable tenant-wide rows, notes, another request's selection or a `version:` marker cannot substitute. Actual asset bytes remain separately export-attested under [Asset Storage](asset-storage.md#complete-selected-release-asset-inventory). Selected publication consumes the World participant directly from its exact retained authenticated freeze evidence, not a fresh mutable Draft lookup. This local read does not create missing owner evidence or reduce the required participant matrix; retained earlier attestations and the separately scoped script-patch digest retain their explicitly declared schema semantics. + - The Game Design Service records the per-domain-service `{commitId, contentDigest, digestSchemaVersion}` it observed when a commit was last applied successfully. - Reconciliation and publish-time checks compare the current digest reported by each service against the recorded digest for the target commit. - If `digestSchemaVersion` differs, publish must fail fast and require an explicit migration of digest semantics (for example by bumping `digestSchemaVersion` and replaying commits to record new digests), rather than silently comparing incompatible hashes. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 8005266d36..cef50f2205 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -35,6 +35,10 @@ The gRPC contract for world operations is located in [../../../../protos/world-m ### Original authorized Draft graph application +The existing `WorldAuthoredSourceIntakeService.ReadAuthoredWorldSourceIntakeById` read accepts a closed version-1 namespace, canonical tenant UUID, exact retained intake request ID and distinct caller-owned read request ID. Only the verified same-namespace Game Design workload without end-user caller context may read it. World validates the stored immutable receipt and complete source evidence, returns those public fields with the exact request echo, and omits its private numeric owner keys. Missing or inconsistent receipts deny; this read cannot create an association, select a latest source or mutate content. Game Design must independently confirm the returned source identity, operation, digest and provenance against its own retained authored-source record before using the evidence for a template/source association. The existing complete-selector intake read remains distinct and unchanged; neither read alone supplies Account operation authority or authorizes a Game Session launch. + +The separate `WorldAuthoredVersionIdentityService.AssociateAuthoredWorldVersion` boundary automatically associates a fresh authored Version through the existing World identity owner. Its closed version-1 request carries namespace, canonical tenant UUID, `worldSlug`, exact authored-source operation/digest, expected canonical Version UUID, Game Design Version-row provenance and an independent Version-read request ID. The receiver requires the exact same-namespace Game Design mTLS peer and no end-user context before decoding or owner access. It independently reads the already retained source intake and the authenticated Game Design Version evidence, commits the association and reads it back. Missing or contradictory provenance denies; retained-row migration and guessed mappings cannot substitute. The response echoes the current request and returns the association operation identity plus complete public committed source-intake and original Version evidence, never private World numeric keys. Exact retries retain the original Version proof and its historical read correlation; the current echo is transport correlation, not fresh lifecycle or mutation authority. This standalone transport does not register or activate the service, materialize content or authorize a Draft write. + `WorldOriginalDraftGraphApplyService.ApplyOriginalDraftGraph` is a distinct Game Design-to-World application and exact-recovery boundary for the bounded fresh-graph path. Its closed version-1 request carries the trusted namespace and the unchanged complete original Account Draft-order binding. World authenticates the exact same-namespace Game Design workload, without authenticated end-user context, before decoding or consulting owner storage. The complete derived owner vectors must be exactly Game Design and World; a caller cannot filter a larger operation into this path. The original bytes are operation identity, not Account permission or caller-provided private owner keys. Before a new application, World resolves one exact retained authored-Version association for the canonical tenant, Version UUID and Game Design Version row. It independently reads the retained source intake and validates the complete Game Design row/key/provenance relationship against the original target. Missing, ambiguous or contradictory associations deny; the receiver never chooses a World slug, infers a numeric mapping or creates a source association on this read. World derives its complete private owner binding from those receipts, derives the topology plan from the unchanged original typed World revisions, and enters the existing Account held-order verification and atomic graph/epoch/result transaction. The complete fresh-family declaration and Account protection through the actual mutation remain required. This transport does not relax physical-deadline enforcement or supply unavailable currentness machinery. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 9d7ae3832a..00dc14a6f7 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -150,3 +150,9 @@ Entry format: - Observation: Successful compilation and skipped database tests did not establish a safe resolved resource classpath. Account already provided a resource-isolated opt-in proof artifact for this same cross-owner testing boundary. - Expected pattern: Consume an opt-in classes-only proof artifact when another service's owner classes are needed. Keep each owner migration directory explicit in composed fixtures; do not suppress Flyway checks or change production resource scanning to accommodate tests. - Current status: Game Logic's resource-isolated proof artifact and its Game Design consumer are prepared. Resolved artifact inspection and corrected-head physical PostgreSQL execution remain required; no production migration or activation guard changed. + +- `2026-10-09`: Verify CI job conclusions before assigning failures from watcher annotations + - Context: The initial observer summary for PR #3105 run 37901040926 attributed failure to Workflow Lint and World, but exact job and step conclusions showed both succeeded. The required gate failed because Account and Game Design Build/Test failed. + - Observation: A workflow-level failure or diagnostic annotation does not establish which owner failed. Misattribution would route unnecessary shared-workflow or World repairs while leaving the real fixture and admission-WAL failures unresolved. + - Expected pattern: Verify terminal job/step conclusions and originating owner artifacts before routing a failure; retain actual checkout provenance and distinguish missing artifacts from passed tests. + - Current status: The parent corrected the report using the completed job evidence and XML: World 206 passing PostgreSQL cases, Game Design four fixture failures and Account one admission-WAL failure. The fixture corrections were validated locally; no physical rerun or WAL completion credit follows. 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 cc30c10a1f..e5637baf47 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 @@ -110,7 +110,9 @@ Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, b Game Design now has a callable `GetCompleteLaunchBinding` handler and strict descriptor/release-attestation codec for the World Management read path. Its exact-method bearer-interceptor bypass is only transport dispatch: the handler still denies absent, wrong-service, or wrong-namespace TLS peers before parsing or owner reads. Corrected-state Common/Game Design checks, handler/auth-wiring and codec units, and the Game Design boot JAR pass locally; no genuine positive persisted release/attestation read, mounted-certificate transport proof, or launch activation is claimed. World Management owns exact binding persistence and preparation; Gameplay owns Game Session launch orchestration and its executable-front fixture. -The original GD+World construction now implements the World-local retained-identity resolver, a distinct closed application/recovery transport and a Game Design composer that retains both exact owner outcomes before synchronized visibility. These components remain unregistered. Consolidated local gate R229 passed 1,441 unit cases (Common 404, Game Design 467, World 570), service/static checks and boot-JAR construction; 333 integration definitions skipped without Docker. R231 compiled and statically checked the new genuine three-case PostgreSQL/mTLS composition fixture, together with 15 existing publication cases; all 18 skipped locally. The new fixture covers original APPLIED/synchronization/Account settlement, lost World acknowledgement and an unavailable World owner, but physical execution is still required. Its fresh World version association uses the actual owner service under authenticated incoming Game Design context through a test-only handoff, not a production association RPC. The existing executed GD-only source proof does not prove this combined original. Genuine composed PostgreSQL/mTLS execution, the production fresh-version association handoff, complete multi-owner definitive-abort recovery and release composition remain open. Account WAL feasibility is a separate admission gate, not a dependency of this source/release handoff. The normative coordinator and receiver contracts belong to [Game Design version control](../../architecture/microservices/game-design-service/version-control.md#design-time-synchronization) and [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md#original-authorized-draft-graph-application). +The original GD+World construction now implements the World-local retained-identity resolver, a distinct closed application/recovery transport and a Game Design composer that retains both exact owner outcomes before synchronized visibility. These components remain unregistered. CI run [37905710499](https://github.com/benhook1013/FireMUD/actions/runs/37905710499) for published `be47226a97d2a945f767c8adf0c3a955834ed629` executed all 133 Game Design integration cases, including the three new genuine PostgreSQL/mTLS composition cases, with no skips: those three failed establishing committed World evidence. All 206 World integration cases passed. This is an owned composition defect, not successful two-owner proof; its correction requires executed follow-up proof. The synthetic checkout used parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded construction parent `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`, so the run does not establish that recorded parent's alignment. The Account job's separate WAL-coverage failure remains an admission gate, not a dependency of this source/release handoff. + +The corrected local composition fixture uses the real distinct World authored-Version association mTLS client and receiver, with independently checked durable owner readback, instead of its earlier test-only incoming-context handoff. It also reads the World intake by its retained ID and independently compares its complete public source receipt with the Game Design owner record. Consolidated gate R240 passed Common, Common Security, Account, Game Design and World checks, formatting, static analysis, coverage, Game Design/World boot-JAR construction, links and Markdown. Its validated unit reports contain 2,722 green cases (Common 414, Common Security 138, Account 1,109, Game Design 480, World 581), including unchanged reused outputs; the standard Game Design/World integration reports contain 336 skipped definitions without Docker. The separately packaged genuine three-case composition fixture requires explicit physical execution; the green local aggregate is not that proof. Selected publication now consumes the exact retained paired World/GD digests with explicit attestation-schema context and a fixed six-family GD content vector. Unexpected World application failures retain strict denial and emit bounded message-free class/frame diagnostics, not credential or SQL payloads. The underlying physical failure remains unresolved. Genuine corrected-state two-owner execution, complete multi-owner definitive-abort recovery and release composition remain open. The existing executed GD-only source proof does not prove this combined original. The normative coordinator and receiver contracts belong to [Game Design version control](../../architecture/microservices/game-design-service/version-control.md#design-time-synchronization) and [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md#original-authorized-draft-graph-application). Official-hosted creator-content acceptance remains partial under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Account's individual-party and hosted-terms repositories now retain exact catalog, affirmative-acceptance and environment-binding operations; `AccountHostedTermsService` can resolve the external environment observation before SQL work and reread locked currentness in a caller-owned writable `READ_COMMITTED` transaction. The service and its trusted publication, environment and affirmative-action participants remain unregistered; current creator authentication and original multi-owner commit enforcement are not supplied by these storage APIs. `HostedTermsEnvironmentBindingPostgresIntegrationTest` exercises explicitly test-only authorities, not a real agreement or operative hosted service. Composed-head PostgreSQL execution, live authority provisioning, creator UI, transfer and organization workflows remain separate proof or implementation gaps. These foundations do not upgrade the broader capability ratings or authorize content writes. diff --git a/protos/world-management/v1/world_authored_version_identity_service.proto b/protos/world-management/v1/world_authored_version_identity_service.proto new file mode 100644 index 0000000000..62851921ea --- /dev/null +++ b/protos/world-management/v1/world_authored_version_identity_service.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; +package world_management.v1; +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +import "game-design/v1/game_design_service.proto"; +import "world-management/v1/world_management_service.proto"; + +// Standalone, unregistered, same-namespace Game Design association construction. +service WorldAuthoredVersionIdentityService { + rpc AssociateAuthoredWorldVersion(AssociateAuthoredWorldVersionRequest) + returns (AssociateAuthoredWorldVersionResponse); +} +message AssociateAuthoredWorldVersionRequest { + int32 schema_version = 1; + string target_namespace = 2; + string canonical_tenant_id = 3; + string world_slug = 4; + string source_operation_id = 5; + string source_evidence_digest = 6; + string expected_canonical_version_id = 7; + int64 game_design_version_id = 8; + string read_request_id = 9; +} +message AssociateAuthoredWorldVersionResponse { + AssociateAuthoredWorldVersionRequest request = 1; + string operation_id = 2; + IntakeAuthoredWorldSourceResponse source_intake_receipt = 3; + // Original committed proof, including its historical read correlation on retry. + gamedesign.v1.GetAuthoredWorldVersionStateResponse version_state_evidence = 4; +} diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index f7190a53ca..c324a41ace 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -42,6 +42,8 @@ service WorldAuthoredSourceIntakeService { returns (IntakeAuthoredWorldSourceResponse); rpc ReadAuthoredWorldSourceIntake(ReadAuthoredWorldSourceIntakeRequest) returns (ReadAuthoredWorldSourceIntakeResponse); + rpc ReadAuthoredWorldSourceIntakeById(ReadAuthoredWorldSourceIntakeByIdRequest) + returns (ReadAuthoredWorldSourceIntakeByIdResponse); } // Explicitly unwired Game Session-to-World canonical launch preparation transport. @@ -123,6 +125,56 @@ message ReadAuthoredWorldSourceIntakeResponse { string receipt_digest = 11; } +// Exact owner read of one retained intake, selected only by its immutable intake request ID. +message ReadAuthoredWorldSourceIntakeByIdRequest { + int32 schema_version = 1; + string target_namespace = 2; + // A distinct caller-owned identity for this read; it is not the stored receipt key. + string read_request_id = 3; + string intake_request_id = 4; + string canonical_tenant_id = 5; +} + +message AuthoredWorldSourceEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string registration_request_id = 3; + string operation_id = 4; + string request_digest = 5; + string canonical_tenant_id = 6; + string tenant_slug = 7; + string world_slug = 8; + string world_display_name = 9; + int64 source_game_row_id = 10; + string source_game_tenant_key = 11; + string provenance_kind = 12; + string evidence_digest = 13; +} + +// Public immutable receipt fields only. World-local tenant/version keys are deliberately omitted. +message AuthoredWorldSourceIntakePublicReceipt { + int32 schema_version = 1; + string target_namespace = 2; + string intake_request_id = 3; + string operation_id = 4; + string canonical_tenant_id = 5; + string world_slug = 6; + string source_operation_id = 7; + string source_evidence_digest = 8; + string request_digest = 9; + string receipt_digest = 10; + AuthoredWorldSourceEvidence source = 11; +} + +message ReadAuthoredWorldSourceIntakeByIdResponse { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intake_request_id = 4; + string canonical_tenant_id = 5; + AuthoredWorldSourceIntakePublicReceipt receipt = 6; +} + enum WorldInstanceLifecycleStatus { WORLD_INSTANCE_LIFECYCLE_STATUS_UNSPECIFIED = 0; WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING = 1; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index 915383ffc0..38b32f9d68 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -352,7 +352,7 @@ static GameDesignPublicationTerminalEvidence terminal( request.appliedCommitId(), request.contentDigest(), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner) ? "sha256:" + "a".repeat(64) : null, null, null)) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClient.java new file mode 100644 index 0000000000..038d1a37b2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClient.java @@ -0,0 +1,161 @@ +package net.firedevops.firemud.common.authoring; + +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.WorldAuthoredVersionIdentityServiceGrpc; + +/** Opt-in file-backed mTLS client for exact authored Version identity association. */ +public final class WorldAuthoredVersionIdentityClient + extends AbstractReloadingBlockingGrpcClient< + WorldAuthoredVersionIdentityServiceGrpc.WorldAuthoredVersionIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldAuthoredVersionIdentityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldAuthoredVersionIdentityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when the owning Game Design service explicitly starts this opt-in client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World authored Version association client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World authored Version association client has no gRPC stub"); + } + initialized = true; + } + + /** + * Applies or recovers the unchanged association request; transport failures propagate unchanged. + */ + public WorldAuthoredVersionIdentityEvidence.Result associate( + WorldAuthoredVersionIdentityEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World authored Version association request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .associateAuthoredWorldVersion( + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request)); + try { + return WorldAuthoredVersionIdentityGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned invalid authored Version association evidence", exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldAuthoredVersionIdentityServiceGrpc.WorldAuthoredVersionIdentityServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldAuthoredVersionIdentityServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(WorldAuthoredVersionIdentityGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + public String workloadNamespace() { + return workloadNamespace; + } + + private WorldAuthoredVersionIdentityServiceGrpc.WorldAuthoredVersionIdentityServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World authored Version association client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "World authored Version association 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 Version association requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World authored Version association requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "World authored Version association " + label + " must be a readable file-backed path", + exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World authored Version association " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityEvidence.java new file mode 100644 index 0000000000..284a68a9b8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityEvidence.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.common.authoring; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; + +/** + * Public committed association evidence; private World numeric identities never cross this + * boundary. + */ +public final class WorldAuthoredVersionIdentityEvidence { + private WorldAuthoredVersionIdentityEvidence() {} + + public record Request( + int schemaVersion, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + UUID expectedCanonicalVersionId, + long gameDesignVersionId, + UUID readRequestId) { + public Request { + new AuthoredWorldVersionStateEvidence.Request( + schemaVersion, + targetNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + gameDesignVersionId); + requireNonNil(expectedCanonicalVersionId); + if (expectedCanonicalVersionId.equals(readRequestId)) { + throw new IllegalArgumentException( + "Version read correlation must differ from Version identity"); + } + } + + public AuthoredWorldVersionStateEvidence.Request versionReadRequest() { + return new AuthoredWorldVersionStateEvidence.Request( + schemaVersion, + targetNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest, + gameDesignVersionId); + } + } + + public record Result( + Request request, + UUID operationId, + WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt sourceIntakeReceipt, + AuthoredWorldVersionStateEvidence versionStateEvidence) { + public Result { + Objects.requireNonNull(request, "request"); + requireNonNil(operationId); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(versionStateEvidence, "versionStateEvidence"); + versionStateEvidence.requireValid(); + var original = versionStateEvidence.request(); + var source = versionStateEvidence.sourceEvidence(); + if (sourceIntakeReceipt.schemaVersion() != request.schemaVersion() + || !sourceIntakeReceipt.targetNamespace().equals(request.targetNamespace()) + || !sourceIntakeReceipt.canonicalTenantId().equals(request.canonicalTenantId()) + || !sourceIntakeReceipt.worldSlug().equals(request.worldSlug()) + || !sourceIntakeReceipt.sourceOperationId().equals(request.sourceOperationId()) + || !sourceIntakeReceipt.sourceEvidenceDigest().equals(request.sourceEvidenceDigest()) + || original.schemaVersion() != request.schemaVersion() + || !original.targetNamespace().equals(request.targetNamespace()) + || !original.canonicalTenantId().equals(request.canonicalTenantId()) + || !original.worldSlug().equals(request.worldSlug()) + || !original.sourceOperationId().equals(request.sourceOperationId()) + || !original.expectedSourceEvidenceDigest().equals(request.sourceEvidenceDigest()) + || original.versionId() != request.gameDesignVersionId() + || !versionStateEvidence.canonicalVersionId().equals(request.expectedCanonicalVersionId()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new IllegalArgumentException( + "Association must retain the exact fresh source and Version"); + } + var state = versionStateEvidence.versionState(); + if (state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT + && state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && state != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE) { + throw new IllegalArgumentException( + "Association requires eligible original Version evidence"); + } + requireReadCorrelation( + original.readRequestId(), + request, + operationId, + sourceIntakeReceipt, + source.registrationRequestId()); + requireReadCorrelation( + request.readRequestId(), + request, + null, + sourceIntakeReceipt, + source.registrationRequestId()); + } + } + + private static void requireReadCorrelation( + UUID readId, + Request request, + UUID operationId, + WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt intake, + UUID registrationId) { + if (readId.equals(request.expectedCanonicalVersionId()) + || readId.equals(operationId) + || readId.equals(intake.operationId()) + || readId.equals(intake.intakeRequestId()) + || readId.equals(intake.sourceOperationId()) + || readId.equals(registrationId)) { + throw new IllegalArgumentException( + "Version read correlation overlaps owner/source identities"); + } + } + + static UUID parseUuid(String text) { + UUID value = UUID.fromString(text); + requireNonNil(value); + if (!value.toString().equals(text)) { + throw new IllegalArgumentException("Canonical UUID required"); + } + return value; + } + + private static void requireNonNil(UUID value) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Non-nil UUID required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodec.java new file mode 100644 index 0000000000..fd8a507fd2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodec.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.common.authoring; + +import com.google.protobuf.Message; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionRequest; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionResponse; + +/** Closed association transport reusing the immutable source and Version evidence codecs. */ +public final class WorldAuthoredVersionIdentityGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 4096; + public static final int MAX_RESPONSE_WIRE_BYTES = 32768; + + private WorldAuthoredVersionIdentityGrpcCodec() {} + + public static AssociateAuthoredWorldVersionRequest toRequest( + WorldAuthoredVersionIdentityEvidence.Request request) { + Objects.requireNonNull(request, "request"); + var wire = + AssociateAuthoredWorldVersionRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setSourceOperationId(request.sourceOperationId().toString()) + .setSourceEvidenceDigest(request.sourceEvidenceDigest()) + .setExpectedCanonicalVersionId(request.expectedCanonicalVersionId().toString()) + .setGameDesignVersionId(request.gameDesignVersionId()) + .setReadRequestId(request.readRequestId().toString()) + .build(); + requireClosed(wire, MAX_REQUEST_WIRE_BYTES); + return wire; + } + + public static WorldAuthoredVersionIdentityEvidence.Request fromRequest( + AssociateAuthoredWorldVersionRequest wire) { + requireClosed(wire, MAX_REQUEST_WIRE_BYTES); + return new WorldAuthoredVersionIdentityEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + WorldAuthoredVersionIdentityEvidence.parseUuid(wire.getCanonicalTenantId()), + wire.getWorldSlug(), + WorldAuthoredVersionIdentityEvidence.parseUuid(wire.getSourceOperationId()), + wire.getSourceEvidenceDigest(), + WorldAuthoredVersionIdentityEvidence.parseUuid(wire.getExpectedCanonicalVersionId()), + wire.getGameDesignVersionId(), + WorldAuthoredVersionIdentityEvidence.parseUuid(wire.getReadRequestId())); + } + + public static AssociateAuthoredWorldVersionResponse toResponse( + WorldAuthoredVersionIdentityEvidence.Result result) { + Objects.requireNonNull(result, "result"); + var intake = result.sourceIntakeReceipt(); + var binding = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + intake.schemaVersion(), + intake.targetNamespace(), + intake.intakeRequestId(), + intake.canonicalTenantId(), + intake.worldSlug(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest()); + var wire = + AssociateAuthoredWorldVersionResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setOperationId(result.operationId().toString()) + .setSourceIntakeReceipt( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeResponse(binding, intake)) + .setVersionStateEvidence( + AuthoredWorldVersionStateGrpcCodec.toResponse(result.versionStateEvidence())) + .build(); + requireClosed(wire, MAX_RESPONSE_WIRE_BYTES); + return wire; + } + + public static WorldAuthoredVersionIdentityEvidence.Result fromResponse( + WorldAuthoredVersionIdentityEvidence.Request request, + AssociateAuthoredWorldVersionResponse wire) { + Objects.requireNonNull(request, "request"); + requireClosed(wire, MAX_RESPONSE_WIRE_BYTES); + if (!wire.hasRequest() + || !request.equals(fromRequest(wire.getRequest())) + || !wire.hasSourceIntakeReceipt() + || !wire.hasVersionStateEvidence() + || !wire.getVersionStateEvidence().hasEvidence()) { + throw new IllegalArgumentException("Complete association and exact request echo required"); + } + var intakeWire = wire.getSourceIntakeReceipt(); + var intakeBinding = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + intakeWire.getSchemaVersion(), + intakeWire.getTargetNamespace(), + WorldAuthoredVersionIdentityEvidence.parseUuid(intakeWire.getIntakeRequestId()), + WorldAuthoredVersionIdentityEvidence.parseUuid(intakeWire.getCanonicalTenantId()), + intakeWire.getWorldSlug(), + WorldAuthoredVersionIdentityEvidence.parseUuid(intakeWire.getSourceOperationId()), + intakeWire.getExpectedSourceEvidenceDigest()); + var intake = WorldAuthoredSourceIntakeGrpcCodec.fromIntakeResponse(intakeBinding, intakeWire); + // On immutable retry, decode the ORIGINAL stored read correlation, never rewrite it. + var retained = wire.getVersionStateEvidence().getEvidence(); + var originalRequest = + new net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence.Request( + retained.getSchemaVersion(), + retained.getTargetNamespace(), + WorldAuthoredVersionIdentityEvidence.parseUuid(retained.getReadRequestId()), + WorldAuthoredVersionIdentityEvidence.parseUuid(retained.getCanonicalTenantId()), + retained.getWorldSlug(), + WorldAuthoredVersionIdentityEvidence.parseUuid(retained.getSourceOperationId()), + retained.getExpectedSourceEvidenceDigest(), + retained.getVersionId()); + var version = + AuthoredWorldVersionStateGrpcCodec.fromResponse( + originalRequest, wire.getVersionStateEvidence()); + return new WorldAuthoredVersionIdentityEvidence.Result( + request, + WorldAuthoredVersionIdentityEvidence.parseUuid(wire.getOperationId()), + intake, + version); + } + + private static void requireClosed(Message wire, int maximum) { + Objects.requireNonNull(wire, "wire"); + if (!wire.getUnknownFields().asMap().isEmpty() || wire.getSerializedSize() > maximum) { + throw new IllegalArgumentException("Unsupported association fields or size"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java index b58a5b34d1..41a344e41f 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java @@ -82,12 +82,25 @@ public static List requiredParticipantOrder() { /** Returns the one supported digest schema for a required participant owner. */ public static int supportedParticipantDigestSchema(String participantKey) { + return supportedParticipantDigestSchema(participantKey, SCHEMA_VERSION); + } + + /** Selects owner schemas from the explicit retained-v1 or selected-publication-v2 contract. */ + public static int supportedParticipantDigestSchema( + String participantKey, int attestationSchemaVersion) { + if (attestationSchemaVersion != SCHEMA_VERSION + && attestationSchemaVersion != SELECTOR_SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); + } Objects.requireNonNull(participantKey, "participantKey"); Integer version = SUPPORTED_PARTICIPANT_DIGEST_SCHEMAS.get(participantKey); if (version == null) { throw new IllegalArgumentException("Unsupported full-Version participant owner"); } - return version; + return attestationSchemaVersion == SELECTOR_SCHEMA_VERSION + && "GAME_DESIGN_CONTROL_PLANE".equals(participantKey) + ? 2 + : version; } /** One successful, immutable owner digest included in the release attestation. */ @@ -165,7 +178,7 @@ public record Artifact( requireText(commitId, "commitId"); participantDigests = List.copyOf(Objects.requireNonNull(participantDigests, "participantDigests")); - validateParticipants(participantDigests, commitId); + validateParticipants(participantDigests, commitId, schemaVersion); requireDigest(manifestHash, "manifestHash"); requireSupportedSchema(manifestSchemaVersion, "manifestSchemaVersion"); requiredManifestAssetKeys = @@ -526,7 +539,8 @@ public static byte[] evidencePreimage(AuthoredWorldReleaseAttestationEvidence ev fields.toArray(Field[]::new)); } - private static void validateParticipants(List participants, String commitId) { + private static void validateParticipants( + List participants, String commitId, int attestationSchemaVersion) { if (participants.size() != PARTICIPANT_ORDER.size()) { throw new IllegalArgumentException( "A complete attestation requires exactly five participants"); @@ -538,7 +552,7 @@ private static void validateParticipants(List participants, String if (!expectedKey.equals(participant.participantKey())) { throw new IllegalArgumentException("Participant digests are not in canonical owner order"); } - if (supportedParticipantDigestSchema(participant.participantKey()) + if (supportedParticipantDigestSchema(participant.participantKey(), attestationSchemaVersion) != participant.digestSchemaVersion()) { throw new IllegalArgumentException( "Participant digest schema is unsupported for its owner"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java index f83405fcb5..9f4fa09413 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -108,7 +108,8 @@ public record ReleaseContent( if (!owners.get(i).equals(p.participantKey()) || p.digestSchemaVersion() != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - p.participantKey()) + p.participantKey(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION) || p.baseVersionId() != null || !selected.appliedCommitId().equals(p.appliedCommitId()) || !p.scopeValue().matches("[1-9][0-9]*") 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 index 9bd4be4004..8055ac4dfc 100644 --- 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 @@ -93,6 +93,24 @@ public WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt read( } } + /** Reads a complete immutable source receipt by its retained intake identity. */ + public WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt readById( + WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readAuthoredWorldSourceIntakeById( + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(request)); + try { + return WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "World returned an invalid authored-source intake by-ID readback", exception); + } + } + @Override protected String configuredTarget(ServiceEndpointsProperties endpoints) { return endpoints.getWorldManagementService(); 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 index 577ccff3c1..8fe3d7f7d0 100644 --- 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 @@ -3,8 +3,11 @@ import com.google.protobuf.Message; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceRequest; import net.firedevops.firemud.worldmanagement.v1.IntakeAuthoredWorldSourceResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; @@ -14,7 +17,7 @@ public final class WorldAuthoredSourceIntakeGrpcCodec { 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. */ + /** Complete canonical binding accepted by intake and echoed by both complete-selector RPCs. */ public record IntakeRequest( int schemaVersion, String targetNamespace, @@ -77,6 +80,79 @@ public record CommittedReceipt( } } + /** Closed read selector that does not require caller-supplied source fields. */ + public record ByIdReadRequest( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + UUID intakeRequestId, + UUID canonicalTenantId) { + public ByIdReadRequest { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source intake version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical targetNamespace is required"); + } + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (readRequestId.equals(intakeRequestId)) { + throw new IllegalArgumentException("Read requestId must differ from intakeRequestId"); + } + } + } + + /** Full public portion of a retained World intake receipt and its immutable source evidence. */ + public record PublicReceipt( + int schemaVersion, + String targetNamespace, + UUID intakeRequestId, + UUID operationId, + UUID canonicalTenantId, + String worldSlug, + UUID sourceOperationId, + String sourceEvidenceDigest, + String requestDigest, + String receiptDigest, + AuthoredWorldSourceEvidence source) { + public PublicReceipt { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World authored-source intake version"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(operationId, "operationId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireDigest(sourceEvidenceDigest, "sourceEvidenceDigest"); + requireDigest(requestDigest, "requestDigest"); + requireDigest(receiptDigest, "receiptDigest"); + Objects.requireNonNull(source, "source"); + if (!"NEW_GAME_ROW".equals(source.provenanceKind()) + || !targetNamespace.equals(source.targetNamespace()) + || !canonicalTenantId.equals(source.canonicalTenantId()) + || !worldSlug.equals(source.worldSlug()) + || !sourceOperationId.equals(source.operationId()) + || !sourceEvidenceDigest.equals(source.evidenceDigest())) { + throw new IllegalArgumentException( + "World intake receipt differs from its complete fresh source evidence"); + } + IntakeRequest binding = + new IntakeRequest( + schemaVersion, + targetNamespace, + intakeRequestId, + canonicalTenantId, + worldSlug, + sourceOperationId, + sourceEvidenceDigest); + if (!WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding).equals(requestDigest)) { + throw new IllegalArgumentException("World intake requestDigest does not match its source"); + } + } + } + private WorldAuthoredSourceIntakeGrpcCodec() {} /** Encodes exactly the validated original intake binding. */ @@ -177,6 +253,157 @@ public static ReadAuthoredWorldSourceIntakeResponse toReadResponse( .build(); } + /** Encodes a closed exact source-receipt read selected only by retained intake identity. */ + public static ReadAuthoredWorldSourceIntakeByIdRequest toReadByIdRequest( + ByIdReadRequest request) { + Objects.requireNonNull(request, "request"); + return ReadAuthoredWorldSourceIntakeByIdRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .build(); + } + + /** Decodes the complete closed ID-based read before any owner access. */ + public static ByIdReadRequest fromReadByIdRequest( + ReadAuthoredWorldSourceIntakeByIdRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadAuthoredWorldSourceIntakeById request"); + return new ByIdReadRequest( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + parseCanonicalNonNilUuid(request.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId")); + } + + /** + * Encodes the exact read echo and complete public receipt; World-private keys are not emitted. + */ + public static ReadAuthoredWorldSourceIntakeByIdResponse toReadByIdResponse( + ByIdReadRequest request, PublicReceipt receipt) { + requireReceiptForByIdRequest(request, receipt); + return ReadAuthoredWorldSourceIntakeByIdResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setReceipt(toProtoReceipt(receipt)) + .build(); + } + + /** Validates exact echo, receipt identity and every source-evidence digest from the owner. */ + public static PublicReceipt fromReadByIdResponse( + ByIdReadRequest request, ReadAuthoredWorldSourceIntakeByIdResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadAuthoredWorldSourceIntakeById response"); + ByIdReadRequest echoed = + new ByIdReadRequest( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getReadRequestId(), "readRequestId"), + parseCanonicalNonNilUuid(response.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId")); + if (!request.equals(echoed)) { + throw new IllegalArgumentException( + "World authored-source intake by-ID response does not echo the exact request"); + } + if (!response.hasReceipt()) { + throw new IllegalArgumentException("World authored-source intake by-ID receipt is required"); + } + PublicReceipt receipt = fromProtoReceipt(response.getReceipt()); + requireReceiptForByIdRequest(request, receipt); + return receipt; + } + + private static void requireReceiptForByIdRequest(ByIdReadRequest request, PublicReceipt receipt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(receipt, "receipt"); + if (request.schemaVersion() != receipt.schemaVersion() + || !request.targetNamespace().equals(receipt.targetNamespace()) + || !request.intakeRequestId().equals(receipt.intakeRequestId()) + || !request.canonicalTenantId().equals(receipt.canonicalTenantId())) { + throw new IllegalArgumentException( + "World authored-source intake receipt differs from the exact by-ID request"); + } + } + + private static net.firedevops.firemud.worldmanagement.v1.AuthoredWorldSourceIntakePublicReceipt + toProtoReceipt(PublicReceipt receipt) { + var source = receipt.source(); + var sourceBuilder = + net.firedevops.firemud.worldmanagement.v1.AuthoredWorldSourceEvidence.newBuilder() + .setSchemaVersion(source.schemaVersion()) + .setTargetNamespace(source.targetNamespace()) + .setRegistrationRequestId(source.registrationRequestId().toString()) + .setOperationId(source.operationId().toString()) + .setRequestDigest(source.requestDigest()) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setTenantSlug(source.tenantSlug()) + .setWorldSlug(source.worldSlug()) + .setWorldDisplayName(source.worldDisplayName()) + .setSourceGameRowId(source.sourceGameRowId()) + .setSourceGameTenantKey(source.sourceGameTenantKey()) + .setProvenanceKind(source.provenanceKind()) + .setEvidenceDigest(source.evidenceDigest()); + return net.firedevops.firemud.worldmanagement.v1.AuthoredWorldSourceIntakePublicReceipt + .newBuilder() + .setSchemaVersion(receipt.schemaVersion()) + .setTargetNamespace(receipt.targetNamespace()) + .setIntakeRequestId(receipt.intakeRequestId().toString()) + .setOperationId(receipt.operationId().toString()) + .setCanonicalTenantId(receipt.canonicalTenantId().toString()) + .setWorldSlug(receipt.worldSlug()) + .setSourceOperationId(receipt.sourceOperationId().toString()) + .setSourceEvidenceDigest(receipt.sourceEvidenceDigest()) + .setRequestDigest(receipt.requestDigest()) + .setReceiptDigest(receipt.receiptDigest()) + .setSource(sourceBuilder) + .build(); + } + + private static PublicReceipt fromProtoReceipt( + net.firedevops.firemud.worldmanagement.v1.AuthoredWorldSourceIntakePublicReceipt receipt) { + Objects.requireNonNull(receipt, "receipt"); + requireNoUnknownFields(receipt, "AuthoredWorldSourceIntakePublicReceipt"); + if (!receipt.hasSource()) { + throw new IllegalArgumentException("Complete authored-world source evidence is required"); + } + var source = receipt.getSource(); + requireNoUnknownFields(source, "AuthoredWorldSourceEvidence"); + AuthoredWorldSourceEvidence evidence = + new AuthoredWorldSourceEvidence( + source.getSchemaVersion(), + source.getTargetNamespace(), + parseCanonicalNonNilUuid(source.getRegistrationRequestId(), "registrationRequestId"), + parseCanonicalNonNilUuid(source.getOperationId(), "sourceOperationId"), + source.getRequestDigest(), + parseCanonicalNonNilUuid(source.getCanonicalTenantId(), "canonicalTenantId"), + source.getTenantSlug(), + source.getWorldSlug(), + source.getWorldDisplayName(), + source.getSourceGameRowId(), + source.getSourceGameTenantKey(), + source.getProvenanceKind(), + source.getEvidenceDigest()); + return new PublicReceipt( + receipt.getSchemaVersion(), + receipt.getTargetNamespace(), + parseCanonicalNonNilUuid(receipt.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalNonNilUuid(receipt.getOperationId(), "operationId"), + parseCanonicalNonNilUuid(receipt.getCanonicalTenantId(), "canonicalTenantId"), + receipt.getWorldSlug(), + parseCanonicalNonNilUuid(receipt.getSourceOperationId(), "sourceOperationId"), + receipt.getSourceEvidenceDigest(), + receipt.getRequestDigest(), + receipt.getReceiptDigest(), + evidence); + } + /** Validates all echoed request fields and the public, owner-authenticated receipt fields. */ public static CommittedReceipt fromIntakeResponse( IntakeRequest request, IntakeAuthoredWorldSourceResponse response) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClientTest.java new file mode 100644 index 0000000000..b7ba3a3a01 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClientTest.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.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 io.grpc.ManagedChannel; +import io.grpc.Status; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +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.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredVersionIdentityServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class WorldAuthoredVersionIdentityClientTest { + @Test + void refusesPlaintextMissingMaterialAndClasspathBeforeTransport(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var tls = tls(directory); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldAuthoredVersionIdentityClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + tls.setPlaintext(false); + tls.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldAuthoredVersionIdentityClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + tls.setCaCert(directory.resolve("missing.crt").toString()); + assertThatThrownBy( + () -> + new WorldAuthoredVersionIdentityClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void refusesWrongNamespaceUninitializedAndClosedUse(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var client = + new WorldAuthoredVersionIdentityClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + try { + assertThatThrownBy( + () -> client.associate(WorldAuthoredVersionIdentityGrpcCodecTest.request("other"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> client.associate(WorldAuthoredVersionIdentityGrpcCodecTest.request("test"))) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(factory); + } finally { + client.close(); + } + assertThatThrownBy(client::init).isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> client.associate(WorldAuthoredVersionIdentityGrpcCodecTest.request("test"))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void configuresWorldEndpointAndExactPeerAndDecodesOnlyClosedResults(@TempDir Path directory) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(mock(ManagedChannel.class)); + var client = new WorldAuthoredVersionIdentityClient(endpoints, tls(directory), factory, "test"); + try { + client.init(); + var field = stubField(); + var actual = + (WorldAuthoredVersionIdentityServiceGrpc.WorldAuthoredVersionIdentityServiceBlockingStub) + field.get(client); + assertThat(actual.getCallOptions().getMaxInboundMessageSize()) + .isEqualTo(WorldAuthoredVersionIdentityGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + assertThat(client.workloadNamespace()).isEqualTo("test"); + assertThat(actual.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + var peerField = + GrpcServerPeerIdentityCallCredentials.class.getDeclaredField("expectedPeerUri"); + peerField.setAccessible(true); + assertThat(peerField.get(actual.getCallOptions().getCredentials())) + .isEqualTo("spiffe://firemud/ns/test/sa/world-management-service"); + verify(factory) + .buildChannel( + eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + var stub = + mock( + WorldAuthoredVersionIdentityServiceGrpc + .WorldAuthoredVersionIdentityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + field.set(client, stub); + var request = WorldAuthoredVersionIdentityGrpcCodecTest.request("test"); + var response = + WorldAuthoredVersionIdentityGrpcCodec.toResponse( + WorldAuthoredVersionIdentityGrpcCodecTest.committed(request)); + when(stub.associateAuthoredWorldVersion(any())).thenReturn(response); + assertThat(client.associate(request).request()).isEqualTo(request); + verify(stub) + .associateAuthoredWorldVersion(WorldAuthoredVersionIdentityGrpcCodec.toRequest(request)); + when(stub.associateAuthoredWorldVersion(any())) + .thenReturn(response.toBuilder().clearVersionStateEvidence().build()); + assertThatThrownBy(() -> client.associate(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored Version association evidence"); + var unavailable = Status.UNAVAILABLE.withDescription("lost response").asRuntimeException(); + when(stub.associateAuthoredWorldVersion(any())).thenThrow(unavailable); + assertThatThrownBy(() -> client.associate(request)).isSameAs(unavailable); + var lostAck = + Status.DEADLINE_EXCEEDED.withDescription("owner may have committed").asRuntimeException(); + doThrow(lostAck).when(stub).associateAuthoredWorldVersion(any()); + assertThatThrownBy(() -> client.associate(request)).isSameAs(lostAck); + } finally { + client.close(); + } + } + + private static Field stubField() throws ReflectiveOperationException { + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return field; + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "fixture").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "fixture").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "fixture").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodecTest.java new file mode 100644 index 0000000000..193fdd81f0 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityGrpcCodecTest.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.common.authoring; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +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.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionResponse; +import org.junit.jupiter.api.Test; + +/** Structural transport proof with synthetic valid values, not real owner storage proof. */ +class WorldAuthoredVersionIdentityGrpcCodecTest { + @Test + void roundTripsCompletePublicCommittedEvidenceAndPreservesHistoricalRetryRead() { + var request = request("test"); + var result = committed(request); + var wire = WorldAuthoredVersionIdentityGrpcCodec.toResponse(result); + assertThat(WorldAuthoredVersionIdentityGrpcCodec.fromResponse(request, wire)).isEqualTo(result); + assertThat(wire.getDescriptorForType().findFieldByName("local_version_key")).isNull(); + assertThat( + wire.getSourceIntakeReceipt() + .getDescriptorForType() + .findFieldByName("local_tenant_key")) + .isNull(); + var retry = + new WorldAuthoredVersionIdentityEvidence.Request( + 1, + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.sourceEvidenceDigest(), + request.expectedCanonicalVersionId(), + request.gameDesignVersionId(), + id(9)); + var retried = + new WorldAuthoredVersionIdentityEvidence.Result( + retry, + result.operationId(), + result.sourceIntakeReceipt(), + result.versionStateEvidence()); + var decoded = + WorldAuthoredVersionIdentityGrpcCodec.fromResponse( + retry, WorldAuthoredVersionIdentityGrpcCodec.toResponse(retried)); + assertThat(decoded.request().readRequestId()).isEqualTo(id(9)); + assertThat(decoded.versionStateEvidence()).isEqualTo(result.versionStateEvidence()); + assertThat(decoded.versionStateEvidence().request().readRequestId()) + .isEqualTo(request.readRequestId()); + } + + @Test + void rejectsUnknownMissingCorruptAndCrossBoundEvidence() { + var request = request("test"); + var wire = WorldAuthoredVersionIdentityGrpcCodec.toResponse(committed(request)); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + List.of( + AssociateAuthoredWorldVersionResponse.getDefaultInstance(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setWorldSlug("other")) + .build(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setReadRequestId(id(9).toString())) + .build(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setUnknownFields(unknown)) + .build(), + wire.toBuilder().clearSourceIntakeReceipt().build(), + wire.toBuilder().clearVersionStateEvidence().build(), + wire.toBuilder().setOperationId("00000000-0000-0000-0000-000000000000").build(), + wire.toBuilder() + .setSourceIntakeReceipt( + wire.getSourceIntakeReceipt().toBuilder().setUnknownFields(unknown)) + .build(), + wire.toBuilder() + .setVersionStateEvidence( + wire.getVersionStateEvidence().toBuilder().setUnknownFields(unknown)) + .build(), + wire.toBuilder() + .setVersionStateEvidence( + wire.getVersionStateEvidence().toBuilder() + .setEvidence( + wire.getVersionStateEvidence().getEvidence().toBuilder() + .setUnknownFields(unknown))) + .build(), + wire.toBuilder() + .setVersionStateEvidence( + wire.getVersionStateEvidence().toBuilder() + .setEvidence( + wire.getVersionStateEvidence().getEvidence().toBuilder() + .setEvidenceDigest("sha256:" + "0".repeat(64)))) + .build(), + wire.toBuilder() + .setVersionStateEvidence( + wire.getVersionStateEvidence().toBuilder() + .setEvidence( + wire.getVersionStateEvidence().getEvidence().toBuilder() + .setSourceEvidence( + wire + .getVersionStateEvidence() + .getEvidence() + .getSourceEvidence() + .toBuilder() + .setUnknownFields(unknown)))) + .build())) { + assertThatThrownBy(() -> WorldAuthoredVersionIdentityGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsUnsupportedOversizedAndNonCanonicalRequest() { + var wire = WorldAuthoredVersionIdentityGrpcCodec.toRequest(request("test")); + for (var invalid : + List.of( + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setGameDesignVersionId(0).build(), + wire.toBuilder().setCanonicalTenantId("1-1-1-1-1").build(), + wire.toBuilder() + .setExpectedCanonicalVersionId("00000000-0000-0000-0000-000000000000") + .build(), + wire.toBuilder().setReadRequestId(wire.getExpectedCanonicalVersionId()).build(), + wire.toBuilder().setWorldSlug("x".repeat(40000)).build())) { + assertThatThrownBy(() -> WorldAuthoredVersionIdentityGrpcCodec.fromRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + static WorldAuthoredVersionIdentityEvidence.Request request(String namespace) { + var source = source(namespace); + return new WorldAuthoredVersionIdentityEvidence.Request( + 1, namespace, id(1), "north-star", id(3), source.evidenceDigest(), id(4), 42L, id(5)); + } + + static WorldAuthoredVersionIdentityEvidence.Result committed( + WorldAuthoredVersionIdentityEvidence.Request request) { + var intakeBinding = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + request.targetNamespace(), + id(6), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.sourceEvidenceDigest()); + var intake = + new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( + 1, + request.targetNamespace(), + id(6), + id(7), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.sourceEvidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intakeBinding), + "sha256:" + "a".repeat(64)); + var version = + AuthoredWorldVersionStateEvidence.create( + request.versionReadRequest(), + source(request.targetNamespace()), + request.expectedCanonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + return new WorldAuthoredVersionIdentityEvidence.Result(request, id(8), intake, version); + } + + static AuthoredWorldSourceEvidence source(String namespace) { + var digest = + AuthoredWorldSourceDigest.requestDigest( + namespace, id(2), id(1), "north-star", "north-star", "North Star"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + id(2), + id(3), + digest, + id(1), + "north-star", + "north-star", + "North Star", + 42L, + "game-tenant-42", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + id(2), + id(3), + digest, + id(1), + "north-star", + "north-star", + "North Star", + 42L, + "game-tenant-42", + "NEW_GAME_ROW")); + } + + static UUID id(int suffix) { + return UUID.fromString("11111111-1111-4111-8111-" + String.format("%012d", suffix)); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java index f4fde9e072..58bec723ef 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java @@ -61,7 +61,7 @@ void v1BytesAndDigestRemainUnchangedAndCannotBePromotedBySupplyingASelector() th current.versionStateEpoch(), current.publishWorkflowId(), current.commitId(), - current.participantDigests(), + retainedV1Participants(current.participantDigests()), current.manifestHash(), current.manifestSchemaVersion(), current.requiredManifestAssetKeys(), @@ -138,6 +138,64 @@ void selectorSubstitutionAtAnOtherwiseValidCheckpointChangesTheDigest() throws E .isInstanceOf(IllegalArgumentException.class); } + @Test + void selectedAttestationRejectsRetainedSchemaOneControlPlaneEvidence() throws Exception { + var selector = selectorEvidence(); + var selected = release(descriptor(selector), selector); + var retained = retainedV1Participants(selected.participantDigests()); + assertThat(retained.getLast().digestSchemaVersion()).isEqualTo(1); + assertThat(selected.participantDigests().getLast().digestSchemaVersion()).isEqualTo(2); + assertThatThrownBy( + () -> + new AuthoredWorldReleaseAttestationEvidence( + selected.schemaVersion(), + selected.targetNamespace(), + selected.descriptorResultDigest(), + selected.canonicalTenantId(), + selected.canonicalVersionId(), + selected.worldSlug(), + selected.authoredWorldSourceOperationId(), + selected.authoredWorldSourceEvidenceDigest(), + selected.launchDescriptorId(), + selected.publishedReleaseBundleRef(), + selected.versionStateEpoch(), + selected.publishWorkflowId(), + selected.commitId(), + retained, + selected.manifestHash(), + selected.manifestSchemaVersion(), + selected.requiredManifestAssetKeys(), + selected.artifactDigests(), + selected.commandDefinitions(), + selected.generationConfigRevision(), + selected.evidenceDigest(), + selector)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + } + + private static List retainedV1Participants( + List selected) { + // Stipulated historical evidence, independently scoped to the retained-v1 contract. + return selected.stream() + .map( + p -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionIdPresent(), + p.baseVersionId(), + p.appliedCommitId(), + "GAME_DESIGN_CONTROL_PLANE".equals(p.participantKey()) + ? "e".repeat(64) + : p.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + p.participantKey(), AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION), + p.abilitySchemaDigestPresent(), + p.abilitySchemaDigest())) + .toList(); + } + static WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { var terminal = WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); @@ -232,7 +290,7 @@ static AuthoredWorldReleaseAttestationEvidence release( selector.request().appliedCommitId(), "b".repeat(64), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner), "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java index db30a362f8..5aad2a2d31 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java @@ -102,6 +102,44 @@ void rejectsEveryEchoSubstitutionUnknownAndMissingMalformedOrChangedTerminal() t .isInstanceOf(IllegalArgumentException.class); } + @Test + void selectedTerminalRejectsLegacyControlPlaneDigestSchema() throws Exception { + var selected = terminal(operation(), Outcome.PUBLISHED).releaseContent(); + var participants = new java.util.ArrayList<>(selected.participantDigests()); + var gd = participants.getLast(); + participants.set( + participants.size() - 1, + new GameDesignPublicationTerminalEvidence.Participant( + gd.participantKey(), + gd.scopeValue(), + gd.baseVersionId(), + gd.appliedCommitId(), + gd.contentDigest(), + 1, + gd.abilitySchemaDigest(), + gd.errorCode(), + gd.errorMessage())); + assertThatThrownBy( + () -> + new GameDesignPublicationTerminalEvidence.ReleaseContent( + selected.canonicalTenantId(), + selected.canonicalVersionId(), + selected.publishedReleaseBundleRef(), + selected.versionNumber(), + selected.attestationSchemaVersion(), + selected.publishWorkflowId(), + selected.manifestHash(), + selected.manifestSchemaVersion(), + selected.artifactDigests(), + selected.requiredManifestAssetKeys(), + participants, + selected.commandDefinitions(), + selected.generationConfigRevision(), + selected.worldStartLocationEvidence())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("required participant proof"); + } + private static UnknownFieldSet unknown() { return UnknownFieldSet.newBuilder() .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) @@ -240,7 +278,7 @@ static GameDesignPublicationTerminalEvidence terminal( world.appliedCommitId(), "WORLD_MANAGEMENT".equals(owner) ? world.contentDigest() : "c".repeat(64), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, null, null)) 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 index a30c142c85..c3504af025 100644 --- 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 @@ -25,6 +25,8 @@ 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.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; @@ -47,6 +49,13 @@ class WorldAuthoredSourceIntakeClientTest { private static final WorldAuthoredSourceIntakeGrpcCodec.ReadRequest READ_REQUEST = new WorldAuthoredSourceIntakeGrpcCodec.ReadRequest( INTAKE_REQUEST, UUID.fromString("42345678-1234-4234-8234-123456789abc")); + private static final WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest BY_ID_READ_REQUEST = + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + NAMESPACE, + UUID.fromString("52345678-1234-4234-8234-123456789abc"), + INTAKE_REQUEST.intakeRequestId(), + INTAKE_REQUEST.canonicalTenantId()); @Test void rejectsPlaintextClasspathAndUnreadableTlsMaterialBeforeChannelCreation(@TempDir Path dir) @@ -104,6 +113,20 @@ void requiresExplicitLifecycleAndExactConfiguredNamespace(@TempDir Path dir) thr assertThatThrownBy(() -> client.read(READ_REQUEST)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.readById(BY_ID_READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy( + () -> + client.readById( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + "other", + BY_ID_READ_REQUEST.readRequestId(), + BY_ID_READ_REQUEST.intakeRequestId(), + BY_ID_READ_REQUEST.canonicalTenantId()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); verifyNoInteractions(channelFactory); } finally { client.close(); @@ -230,6 +253,121 @@ void readRequiresAndReturnsTheSeparateExactReadIdentity(@TempDir Path dir) throw WorldAuthoredSourceIntakeGrpcCodec.toReadRequest(READ_REQUEST)); } + @Test + void byIdReadReturnsTheFullValidatedPublicReceiptWithBoundedDeadline(@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.readAuthoredWorldSourceIntakeById( + any(ReadAuthoredWorldSourceIntakeByIdRequest.class))) + .thenReturn(byIdReadResponse(BY_ID_READ_REQUEST)); + + var receipt = client.readById(BY_ID_READ_REQUEST); + + assertThat(receipt.intakeRequestId()).isEqualTo(BY_ID_READ_REQUEST.intakeRequestId()); + assertThat(receipt.canonicalTenantId()).isEqualTo(BY_ID_READ_REQUEST.canonicalTenantId()); + assertThat(receipt.worldSlug()).isEqualTo(INTAKE_REQUEST.worldSlug()); + assertThat(receipt.source()).isEqualTo(sourceEvidence()); + assertThat(receipt.receiptDigest()).isEqualTo(RECEIPT_DIGEST); + assertThat(byIdReadResponse(BY_ID_READ_REQUEST).getReceipt().getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "local_version_key", "world_tenant_key"); + assertThat( + byIdReadResponse(BY_ID_READ_REQUEST).getReceipt().getSource().getAllFields().keySet()) + .extracting(field -> field.getName()) + .containsExactlyInAnyOrder( + "schema_version", + "target_namespace", + "registration_request_id", + "operation_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") + .doesNotContain("world_tenant_key", "local_tenant_key", "local_version_key"); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub) + .readAuthoredWorldSourceIntakeById( + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(BY_ID_READ_REQUEST)); + assertThat( + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(BY_ID_READ_REQUEST) + .getDescriptorForType() + .getFields()) + .extracting(field -> field.getName()) + .containsExactly( + "schema_version", + "target_namespace", + "read_request_id", + "intake_request_id", + "canonical_tenant_id") + .doesNotContain("world_slug", "source_operation_id", "expected_source_evidence_digest"); + } + + @Test + void byIdReadRejectsChangedEchoUnknownFieldsAndCorruptFullSource(@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.readAuthoredWorldSourceIntakeById( + any(ReadAuthoredWorldSourceIntakeByIdRequest.class))) + .thenReturn( + byIdReadResponse(BY_ID_READ_REQUEST).toBuilder() + .setReadRequestId(BY_ID_READ_REQUEST.intakeRequestId().toString()) + .build()); + assertThatThrownBy(() -> client.readById(BY_ID_READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake by-ID readback"); + + when(stub.readAuthoredWorldSourceIntakeById( + any(ReadAuthoredWorldSourceIntakeByIdRequest.class))) + .thenReturn( + byIdReadResponse(BY_ID_READ_REQUEST).toBuilder() + .setUnknownFields(unknownField()) + .build()); + assertThatThrownBy(() -> client.readById(BY_ID_READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake by-ID readback"); + + var valid = byIdReadResponse(BY_ID_READ_REQUEST); + var corruptReceipt = + valid.getReceipt().toBuilder() + .setSource( + valid.getReceipt().getSource().toBuilder().setWorldDisplayName("substituted")) + .build(); + when(stub.readAuthoredWorldSourceIntakeById( + any(ReadAuthoredWorldSourceIntakeByIdRequest.class))) + .thenReturn(valid.toBuilder().setReceipt(corruptReceipt).build()); + assertThatThrownBy(() -> client.readById(BY_ID_READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake by-ID readback"); + + var unknownSource = + valid.getReceipt().getSource().toBuilder().setUnknownFields(unknownField()).build(); + when(stub.readAuthoredWorldSourceIntakeById( + any(ReadAuthoredWorldSourceIntakeByIdRequest.class))) + .thenReturn( + valid.toBuilder() + .setReceipt(valid.getReceipt().toBuilder().setSource(unknownSource)) + .build()); + assertThatThrownBy(() -> client.readById(BY_ID_READ_REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid authored-source intake by-ID readback"); + } + private static WorldAuthoredSourceIntakeClient clientWithStub( Path directory, WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceBlockingStub stub) @@ -251,6 +389,77 @@ private static ReadAuthoredWorldSourceIntakeResponse readResponse( return WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(request, receipt(request.binding())); } + private static ReadAuthoredWorldSourceIntakeByIdResponse byIdReadResponse( + WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest request) { + return WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse(request, publicReceipt()); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt publicReceipt() { + var source = sourceEvidence(); + var binding = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST.intakeRequestId(), + INTAKE_REQUEST.canonicalTenantId(), + INTAKE_REQUEST.worldSlug(), + INTAKE_REQUEST.sourceOperationId(), + source.evidenceDigest()); + return new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST.intakeRequestId(), + UUID.fromString("62345678-1234-4234-8234-123456789abc"), + INTAKE_REQUEST.canonicalTenantId(), + INTAKE_REQUEST.worldSlug(), + INTAKE_REQUEST.sourceOperationId(), + source.evidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(binding), + RECEIPT_DIGEST, + source); + } + + private static AuthoredWorldSourceEvidence sourceEvidence() { + UUID registrationRequestId = UUID.fromString("72345678-1234-4234-8234-123456789abc"); + String tenantSlug = "north-star"; + String worldDisplayName = "World One"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + INTAKE_REQUEST.canonicalTenantId(), + tenantSlug, + INTAKE_REQUEST.worldSlug(), + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + INTAKE_REQUEST.sourceOperationId(), + sourceRequestDigest, + INTAKE_REQUEST.canonicalTenantId(), + tenantSlug, + INTAKE_REQUEST.worldSlug(), + worldDisplayName, + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + INTAKE_REQUEST.sourceOperationId(), + sourceRequestDigest, + INTAKE_REQUEST.canonicalTenantId(), + tenantSlug, + INTAKE_REQUEST.worldSlug(), + worldDisplayName, + 42L, + "legacy-game-tenant-42", + "NEW_GAME_ROW", + evidenceDigest); + } + private static WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt receipt( WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest request) { return new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java index 8d2326aea5..48fd34429d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java @@ -413,7 +413,7 @@ private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Excepti selector.request().appliedCommitId(), selector.request().contentDigest(), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner), "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java index 19c79b3c44..a3d3156a73 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java @@ -295,7 +295,7 @@ private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Excepti selector.request().appliedCommitId(), selector.request().contentDigest(), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner), "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java index a51415438a..3c69d41a65 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialPlayerLocationTest.java @@ -380,7 +380,7 @@ private static WorldCanonicalInstanceLifecycleEvidence genuineLifecycleEvidence( selector.request().appliedCommitId(), selector.request().contentDigest(), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner), "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java index 50f80d4687..562e588825 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java @@ -333,6 +333,26 @@ void rejectsUnselectedV1ReleaseAndMalformedLifecycleCountersOrDigests() throws E var request = evidence.request(); var descriptor = evidence.launchBinding().descriptor(); var release = evidence.launchBinding().releaseAttestation(); + // Independent retained-v1 fixture; its GD digest is not the selected-v2 content hash. + var v1Participants = + release.participantDigests().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? "e".repeat(64) + : participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant.participantKey(), + AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) + .toList(); var v1Release = AuthoredWorldReleaseAttestationEvidence.create( release.targetNamespace(), @@ -347,7 +367,7 @@ void rejectsUnselectedV1ReleaseAndMalformedLifecycleCountersOrDigests() throws E release.versionStateEpoch(), release.publishWorkflowId(), release.commitId(), - release.participantDigests(), + v1Participants, release.manifestHash(), release.manifestSchemaVersion(), release.requiredManifestAssetKeys(), @@ -763,7 +783,7 @@ private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Excepti selector.request().appliedCommitId(), selector.request().contentDigest(), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner), "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java index fd3e886c9e..3b80faaa39 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java @@ -408,7 +408,7 @@ private static CompleteLaunchBindingEvidence completeBinding() { selection.appliedCommitId(), "b".repeat(64), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner), "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java index 4970705c72..8938a39176 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalPlayerAdmissionHoldEvidenceTest.java @@ -268,7 +268,7 @@ private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence() throw selector.request().appliedCommitId(), selector.request().contentDigest(), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner), "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java new file mode 100644 index 0000000000..adbffdeccb --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java @@ -0,0 +1,121 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; + +/** Schema-2 digest over every exact Game Design source family at one selected Draft commit. */ +public record SelectedDraftControlPlaneDigest( + String tenantId, + String scopeValue, + String appliedCommitId, + String contentDigest, + int digestSchemaVersion) { + public static final int SCHEMA_VERSION = 2; + private static final String DOMAIN = "game-design-selected-draft-control-plane-digest/v2"; + + public SelectedDraftControlPlaneDigest { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(scopeValue, "scopeValue"); + Objects.requireNonNull(appliedCommitId, "appliedCommitId"); + if (contentDigest == null + || !contentDigest.matches("[0-9a-f]{64}") + || digestSchemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Canonical schema-2 selected control-plane digest required"); + } + } + + /** Publication request identity is echoed separately and is not part of this content digest. */ + public static SelectedDraftControlPlaneDigest compute( + DraftCommitBinding selectedCommit, GameDesignSourceRepository.SynchronizedSources sources) { + Objects.requireNonNull(selectedCommit, "selectedCommit"); + Objects.requireNonNull(sources, "sources"); + BrandingSourceSnapshot branding = + sources + .branding() + .orElseThrow( + () -> new IllegalStateException("Selected branding source snapshot unavailable")); + TemplateConfigSourceSnapshot templateConfig = + sources + .templateConfig() + .orElseThrow( + () -> + new IllegalStateException( + "Selected template-config source snapshot unavailable")); + List snapshots = + List.of( + new Snapshot( + "COMMAND", sources.command().binding(), sources.command().canonicalBytes()), + new Snapshot( + "REALM_POLICY", sources.policy().binding(), sources.policy().canonicalBytes()), + new Snapshot("ASSET", sources.asset().binding(), sources.asset().canonicalBytes()), + new Snapshot( + "GAMEPLAY_SOURCE", + sources.gameplay().binding(), + sources.gameplay().canonicalBytes()), + new Snapshot("BRANDING", branding.binding(), branding.canonicalBytes()), + new Snapshot( + "TEMPLATE_CONFIG", templateConfig.binding(), templateConfig.canonicalBytes())); + + var preimage = new ByteArrayOutputStream(); + frame(preimage, DOMAIN); + frame(preimage, selectedCommit.canonicalBytes()); + for (Snapshot source : snapshots) { + if (!selectedCommit.equals(source.binding())) { + throw new IllegalStateException( + "Every selected Game Design source family must bind the exact Draft commit"); + } + frame(preimage, source.family()); + frame(preimage, source.canonicalBytes()); + } + return new SelectedDraftControlPlaneDigest( + selectedCommit.target().canonicalTenantId().toString(), + Long.toString(selectedCommit.target().gameDesignVersionRowId()), + selectedCommit.commitId().toString(), + sha256(preimage.toByteArray()), + SCHEMA_VERSION); + } + + public DesignControlPlaneDigestDto toDto() { + return new DesignControlPlaneDigestDto( + tenantId, scopeValue, appliedCommitId, contentDigest, digestSchemaVersion); + } + + private static void frame(ByteArrayOutputStream output, String value) { + frame(output, value.getBytes(StandardCharsets.UTF_8)); + } + + private static void frame(ByteArrayOutputStream output, byte[] value) { + output.writeBytes(Integer.toString(value.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(value); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new AssertionError("SHA-256 is required by the Java platform", impossible); + } + } + + private record Snapshot(String family, DraftCommitBinding binding, byte[] canonicalBytes) { + private Snapshot { + Objects.requireNonNull(family, "family"); + Objects.requireNonNull(binding, "binding"); + canonicalBytes = Objects.requireNonNull(canonicalBytes, "canonicalBytes").clone(); + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java new file mode 100644 index 0000000000..d983800489 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java @@ -0,0 +1,336 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered exact selected-publication source read; it does not authorize publication itself. + */ +public final class SelectedDraftPublicationDigestReadService { + private final OwnerRead owner; + private final TransactionTemplate snapshot; + private final String workloadNamespace; + + public SelectedDraftPublicationDigestReadService( + DSLContext dsl, PlatformTransactionManager transactions, String workloadNamespace) { + this( + new RepositoryOwnerRead( + new GameDesignPublicationOperationRepository(Objects.requireNonNull(dsl, "dsl")), + new GameDesignSourceRepository(dsl)), + transactions, + workloadNamespace); + } + + SelectedDraftPublicationDigestReadService( + OwnerRead owner, PlatformTransactionManager transactions, String workloadNamespace) { + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + snapshot = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + snapshot.setName("game-design-selected-publication-digest-read"); + snapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + snapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + snapshot.setReadOnly(true); + } + + /** Returns exact local GD and retained World digests for one canonical full-version request. */ + public ReadResult read( + String targetNamespace, PublicationDigestRequestBinding publicationRequest) { + if (!workloadNamespace.equals(targetNamespace)) { + throw Status.PERMISSION_DENIED + .withDescription("Selected publication namespace differs from configured owner") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent selected publication digest snapshot required") + .asRuntimeException(); + } + validateRequest(publicationRequest); + try { + return Objects.requireNonNull( + snapshot.execute(ignored -> readSnapshot(publicationRequest)), + "Selected publication digest snapshot returned no result"); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (DataAccessException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Selected publication source readback unavailable") + .withCause(unavailable) + .asRuntimeException(); + } catch (RuntimeException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact selected publication source evidence unavailable") + .withCause(invalid) + .asRuntimeException(); + } + } + + private ReadResult readSnapshot(PublicationDigestRequestBinding publicationRequest) { + GameDesignPublicationOperationRepository.Readback readback = + owner + .read(publicationRequest.derivedWorkflowIdentity()) + .orElseThrow( + () -> + Status.NOT_FOUND + .withDescription("Selected publication operation unavailable") + .asRuntimeException()); + GameDesignPublicationOperation operation = readback.operation(); + requireOperationCorrelation(operation, publicationRequest); + + // Exact durable selection comparison precedes any source snapshot read. + owner.requireExactSelection(operation); + GameDesignSourceRepository.Capture frozen = + owner + .readSourceCapture(operation) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Complete selected source capture unavailable") + .asRuntimeException()); + requireCapture(operation, frozen); + + DraftCommitBinding selected = operation.account().input().selection().selectedCommit(); + GameDesignSourceRepository.SynchronizedSources synchronizedSources = + owner + .readSynchronized(selected.target(), selected.commitId()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Complete synchronized selected sources unavailable") + .asRuntimeException()); + requireFrozenSources(selected, frozen, synchronizedSources); + + DesignControlPlaneDigestDto designDigest = + SelectedDraftControlPlaneDigest.compute(selected, synchronizedSources).toDto(); + var worldAcknowledgement = operation.inventory().freezeEvidence().acknowledgement(); + if (!selected.commitId().toString().equals(worldAcknowledgement.appliedCommitId())) { + throw new IllegalStateException("Retained World freeze differs from selected Draft commit"); + } + var worldDigest = + new PublishParticipantDigestDto( + PublishParticipantKey.WORLD_MANAGEMENT.name(), + publicationRequest.versionId(), + null, + worldAcknowledgement.appliedCommitId(), + worldAcknowledgement.contentDigest(), + worldAcknowledgement.digestSchemaVersion(), + null, + null, + null); + return new ReadResult( + publicationRequest, publicationRequest.requestDigest(), designDigest, worldDigest); + } + + private void requireOperationCorrelation( + GameDesignPublicationOperation operation, + PublicationDigestRequestBinding publicationRequest) { + var selection = operation.account().input().selection(); + var intent = selection.intent(); + TargetProof target = selection.target(); + DraftCommitBinding selected = selection.selectedCommit(); + var world = operation.world().request(); + UUID tenant; + long numericVersion; + try { + tenant = UUID.fromString(publicationRequest.tenantId()); + numericVersion = Long.parseLong(publicationRequest.versionId()); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Canonical tenant UUID and numeric version required", malformed); + } + if (!tenant.toString().equals(publicationRequest.tenantId()) + || numericVersion <= 0 + || !tenant.equals(target.canonicalTenantId()) + || !tenant.equals(intent.canonicalTenantId()) + || target.gameDesignVersionRowId() != numericVersion + || operation.versionId() != numericVersion + || !operation.tenantKey().equals(target.gameDesignVersionTenantKey()) + || !operation.selectionDigest().equals(selection.digest()) + || !intent.canonicalVersionId().equals(target.canonicalVersionId()) + || !intent.canonicalVersionId().equals(selected.target().canonicalVersionId()) + || !publicationRequest.publishRequestId().equals(intent.publishRequestId()) + || !publicationRequest.derivedWorkflowIdentity().equals(operation.workflowId()) + || !workloadNamespace.equals(world.targetNamespace()) + || !tenant.equals(world.canonicalTenantId()) + || !intent.canonicalVersionId().equals(world.canonicalVersionId()) + || !intent.publishRequestId().equals(world.publicationRequestId()) + || !publicationRequest.derivedWorkflowIdentity().equals(world.publishWorkflowId()) + || !selection.digest().substring("sha256:".length()).equals(world.requestDigest()) + || !intent.expectedVersionStateEpoch().equals(Long.toString(world.versionStateEpoch())) + || !selected.commitId().toString().equals(world.appliedCommitId())) { + throw new IllegalStateException( + "Publication operation differs from canonical selected request"); + } + } + + private static void requireCapture( + GameDesignPublicationOperation operation, GameDesignSourceRepository.Capture capture) { + byte[] operationBytes = operation.canonicalBytes(); + for (byte[] retainedOperation : + new byte[][] { + capture.command().operation().canonicalBytes(), + capture.policy().operation().canonicalBytes(), + capture.asset().operation().canonicalBytes(), + capture.branding().operation().canonicalBytes(), + capture.templateConfig().operation().canonicalBytes() + }) { + if (!Arrays.equals(operationBytes, retainedOperation)) { + throw new IllegalStateException("Frozen source capture differs from exact operation"); + } + } + } + + private static void requireFrozenSources( + DraftCommitBinding selected, + GameDesignSourceRepository.Capture frozen, + GameDesignSourceRepository.SynchronizedSources synchronizedSources) { + BrandingSourceSnapshot branding = + synchronizedSources + .branding() + .orElseThrow( + () -> new IllegalStateException("Selected branding source snapshot unavailable")); + TemplateConfigSourceSnapshot templateConfig = + synchronizedSources + .templateConfig() + .orElseThrow( + () -> + new IllegalStateException( + "Selected template-config source snapshot unavailable")); + if (!selected.equals(synchronizedSources.command().binding()) + || !selected.equals(synchronizedSources.policy().binding()) + || !selected.equals(synchronizedSources.asset().binding()) + || !selected.equals(synchronizedSources.gameplay().binding()) + || !selected.equals(branding.binding()) + || !selected.equals(templateConfig.binding()) + || !Arrays.equals( + frozen.command().snapshot().canonicalBytes(), + synchronizedSources.command().canonicalBytes()) + || !Arrays.equals( + frozen.policy().snapshot().canonicalBytes(), + synchronizedSources.policy().canonicalBytes()) + || !Arrays.equals( + frozen.asset().snapshot().canonicalBytes(), + synchronizedSources.asset().canonicalBytes()) + || !Arrays.equals(frozen.branding().snapshot().canonicalBytes(), branding.canonicalBytes()) + || !Arrays.equals( + frozen.templateConfig().snapshot().canonicalBytes(), templateConfig.canonicalBytes())) { + throw new IllegalStateException( + "Frozen and synchronized source snapshots differ from the complete selected commit"); + } + } + + private static void validateRequest(PublicationDigestRequestBinding request) { + if (request == null + || request.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw Status.INVALID_ARGUMENT + .withDescription("Canonical full-version publication binding required") + .asRuntimeException(); + } + try { + var canonical = + PublicationDigestRequestBinding.full( + request.tenantId(), request.versionId(), request.publishRequestId()); + UUID tenant = UUID.fromString(request.tenantId()); + if (!Arrays.equals(canonical.canonicalPreimage(), request.canonicalPreimage()) + || !canonical.requestDigest().equals(request.requestDigest()) + || !canonical.derivedWorkflowIdentity().equals(request.derivedWorkflowIdentity()) + || !tenant.toString().equals(request.tenantId())) { + throw new IllegalArgumentException("Publication request binding is not canonical"); + } + } catch (RuntimeException malformed) { + throw Status.INVALID_ARGUMENT + .withDescription("Canonical full-version publication binding required") + .withCause(malformed) + .asRuntimeException(); + } + } + + public record ReadResult( + PublicationDigestRequestBinding requestBinding, + String requestDigest, + DesignControlPlaneDigestDto gameDesignDigest, + PublishParticipantDigestDto worldManagementDigest) { + public ReadResult { + Objects.requireNonNull(requestBinding, "requestBinding"); + Objects.requireNonNull(gameDesignDigest, "gameDesignDigest"); + Objects.requireNonNull(worldManagementDigest, "worldManagementDigest"); + requestBinding.validateSupplied(requestBinding.derivedWorkflowIdentity(), requestDigest); + requestBinding.requireOwnerScope(gameDesignDigest.tenantId(), gameDesignDigest.scopeValue()); + if (!requestBinding.versionId().equals(worldManagementDigest.scopeValue()) + || !gameDesignDigest.appliedCommitId().equals(worldManagementDigest.appliedCommitId()) + || gameDesignDigest.digestSchemaVersion() + != SelectedDraftControlPlaneDigest.SCHEMA_VERSION + || !PublishParticipantKey.WORLD_MANAGEMENT + .name() + .equals(worldManagementDigest.participantKey()) + || worldManagementDigest.baseVersionId() != null + || worldManagementDigest.contentDigest() == null + || !worldManagementDigest.contentDigest().matches("[0-9a-f]{64}") + || worldManagementDigest.digestSchemaVersion() == null + || worldManagementDigest.digestSchemaVersion() <= 0 + || !worldManagementDigest.succeeded()) { + throw new IllegalArgumentException("Paired selected publication digest scopes differ"); + } + } + } + + interface OwnerRead { + Optional read(String workflowIdentity); + + void requireExactSelection(GameDesignPublicationOperation operation); + + Optional readSourceCapture( + GameDesignPublicationOperation operation); + + Optional readSynchronized( + TargetProof target, UUID selectedCommitId); + } + + private record RepositoryOwnerRead( + GameDesignPublicationOperationRepository operations, GameDesignSourceRepository sources) + implements OwnerRead { + @Override + public Optional read( + String workflowIdentity) { + return operations.read(workflowIdentity); + } + + @Override + public void requireExactSelection(GameDesignPublicationOperation operation) { + operations.requireExactSelection(operation); + } + + @Override + public Optional readSourceCapture( + GameDesignPublicationOperation operation) { + return operations.readSourceCapture(operation); + } + + @Override + public Optional readSynchronized( + TargetProof target, UUID selectedCommitId) { + return sources.readSynchronized(target, selectedCommitId); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java index 7b80b50bce..6f5f7b0911 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/PublishGateService.java @@ -19,4 +19,10 @@ List collectScriptPatchParticipantDigests( VersionDto version, String publishRequestId, String publishWorkflowId); void assertGatePassed(VersionDto version, List participantDigests); + + /** + * Requires the selected full-publication digest schemas, including all six GD source families. + */ + void assertSelectedGatePassed( + VersionDto version, List participantDigests); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java index d27efee5cf..e1022aa7a9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java @@ -338,6 +338,15 @@ private void requireFullVersion(Version version, PublishedReleaseBundleDto bundl private List requireParticipantEvidence( PublishedReleaseBundleDto bundle, long versionId) { + int attestationSchemaVersion = + switch (bundle.attestationSchemaVersion()) { + case "v1" -> AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION; + case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case null, default -> + throw deny( + "PARTICIPANT_EVIDENCE_INVALID", + "supported release attestation schema is required"); + }; List observed = bundle.participantDigests(); List requiredParticipantOrder = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); @@ -353,7 +362,7 @@ private List requirePartici String expectedParticipantKey = requiredParticipantOrder.get(index); int supportedDigestSchemaVersion = AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - expectedParticipantKey); + expectedParticipantKey, attestationSchemaVersion); PublishParticipantDigestDto digest = observed.get(index); if (digest == null || !expectedParticipantKey.equals(digest.participantKey()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java index 5a5d554fc9..144045ea62 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.gamedesign.service.impl; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -7,6 +9,8 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; import net.firedevops.firemud.gamedesign.client.EntityManagementClient; @@ -19,12 +23,15 @@ import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import net.firedevops.firemud.gamedesign.service.PublishGateService; import org.jooq.DSLContext; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; @Service public final class PublishGateServiceImpl implements PublishGateService { @@ -54,6 +61,8 @@ public final class PublishGateServiceImpl implements PublishGateService { private final GameLogicClient gameLogicClient; private final AutomationScriptingClient automationScriptingClient; private final SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository; + private final SelectedDraftPublicationDigestReadService selectedPublicationDigestReader; + private final String workloadNamespace; @Autowired public PublishGateServiceImpl( @@ -62,14 +71,20 @@ public PublishGateServiceImpl( EntityManagementClient entityManagementClient, GameLogicClient gameLogicClient, AutomationScriptingClient automationScriptingClient, - DSLContext dsl) { + DSLContext dsl, + PlatformTransactionManager transactions, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this( controlPlaneDigestService, worldManagementClient, entityManagementClient, gameLogicClient, automationScriptingClient, - new SelectedDraftGameLogicReceiptRepository(dsl)); + new SelectedDraftGameLogicReceiptRepository(dsl), + GrpcPeerIdentity.isValidNamespace(workloadNamespace) + ? new SelectedDraftPublicationDigestReadService(dsl, transactions, workloadNamespace) + : null, + workloadNamespace); } PublishGateServiceImpl( @@ -79,6 +94,26 @@ public PublishGateServiceImpl( GameLogicClient gameLogicClient, AutomationScriptingClient automationScriptingClient, SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository) { + this( + controlPlaneDigestService, + worldManagementClient, + entityManagementClient, + gameLogicClient, + automationScriptingClient, + selectedGameLogicReceiptRepository, + null, + null); + } + + PublishGateServiceImpl( + ControlPlaneDigestService controlPlaneDigestService, + WorldManagementClient worldManagementClient, + EntityManagementClient entityManagementClient, + GameLogicClient gameLogicClient, + AutomationScriptingClient automationScriptingClient, + SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository, + SelectedDraftPublicationDigestReadService selectedPublicationDigestReader, + String workloadNamespace) { this.controlPlaneDigestService = controlPlaneDigestService; this.worldManagementClient = worldManagementClient; this.entityManagementClient = entityManagementClient; @@ -86,6 +121,8 @@ public PublishGateServiceImpl( this.automationScriptingClient = automationScriptingClient; this.selectedGameLogicReceiptRepository = Objects.requireNonNull(selectedGameLogicReceiptRepository); + this.selectedPublicationDigestReader = selectedPublicationDigestReader; + this.workloadNamespace = workloadNamespace; } @Override @@ -124,7 +161,56 @@ public List collectSelectedFullVersionParticipantDi throw new IllegalArgumentException("selected publication tenant must be its canonical UUID"); } requireWorkflowIdentity(canonicalBinding, publishWorkflowId); - return collectFullVersionParticipantDigests(version, canonicalBinding, true); + SelectedDraftPublicationDigestReadService.ReadResult selected = null; + String failureCode = "PARTICIPANT_UNAVAILABLE"; + try { + if (selectedPublicationDigestReader == null + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalStateException("Selected publication digest reader unavailable"); + } + selected = selectedPublicationDigestReader.read(workloadNamespace, canonicalBinding); + if (selected == null + || !Arrays.equals( + canonicalBinding.canonicalPreimage(), selected.requestBinding().canonicalPreimage()) + || !canonicalBinding.requestDigest().equals(selected.requestDigest()) + || !canonicalBinding + .derivedWorkflowIdentity() + .equals(selected.requestBinding().derivedWorkflowIdentity())) { + throw new IllegalStateException("Selected publication digest request echo differs"); + } + } catch (RuntimeException unavailable) { + selected = null; + failureCode = + unavailable instanceof StatusRuntimeException grpcFailure + ? grpcFailure.getStatus().getCode().name() + : "FAILED_PRECONDITION"; + if (selectedPublicationDigestReader == null + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + failureCode = "PARTICIPANT_UNAVAILABLE"; + } + } + var snapshot = selected; + String snapshotFailureCode = failureCode; + return FULL_VERSION_PARTICIPANTS.stream() + .map( + participant -> { + if (participant == PublishParticipantKey.WORLD_MANAGEMENT + || participant == PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE) { + if (snapshot == null) { + return failedObservation( + participant, + canonicalBinding.versionId(), + null, + snapshotFailureCode, + "Exact selected publication source evidence unavailable"); + } + return participant == PublishParticipantKey.WORLD_MANAGEMENT + ? snapshot.worldManagementDigest() + : toParticipantDigest(participant, version, snapshot.gameDesignDigest()); + } + return observeFullVersionParticipant(version, canonicalBinding, participant, true); + }) + .toList(); } private List collectFullVersionParticipantDigests( @@ -158,6 +244,22 @@ public List collectScriptPatchParticipantDigests( @Override public void assertGatePassed( VersionDto version, List participantDigests) { + assertGatePassed(version, participantDigests, false); + } + + @Override + public void assertSelectedGatePassed( + VersionDto version, List participantDigests) { + if (version.scriptOnly()) { + throw new IllegalArgumentException("Selected publication requires a full version"); + } + assertGatePassed(version, participantDigests, true); + } + + private void assertGatePassed( + VersionDto version, + List participantDigests, + boolean selectedPublication) { List expectedParticipants = version.scriptOnly() ? SCRIPT_PATCH_PARTICIPANTS : FULL_VERSION_PARTICIPANTS; List expectedParticipantKeyList = @@ -206,8 +308,18 @@ public void assertGatePassed( "publish gate failed: wrong scope from " + digest.participantKey()); } String participantKey = digest.participantKey(); - Integer supportedSchemaVersion = - participantKey == null ? null : SUPPORTED_DIGEST_SCHEMA_VERSIONS.get(participantKey); + Integer supportedSchemaVersion; + if (selectedPublication) { + supportedSchemaVersion = + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + } else { + supportedSchemaVersion = + participantKey == null + ? null + : SUPPORTED_DIGEST_SCHEMA_VERSIONS.get(participantKey); + } if (digest.digestSchemaVersion() == null || !digest.digestSchemaVersion().equals(supportedSchemaVersion)) { throw new PublishGateFailureException( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java index 24f62bbc0c..e0bd7eef95 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java @@ -54,7 +54,8 @@ static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { || !Objects.equals( participant.digestSchemaVersion(), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant.participantKey()))) { + participant.participantKey(), + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION))) { throw new IllegalArgumentException( "World selector requires all exact successful release participants"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index f8b3bb52a2..a27e4daa28 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -162,7 +162,11 @@ private PublishWorkflowSnapshot reconcileFullVersionPublish( return failDefinitively(request, attempt, version, null, ex); } try { - publishGateService.assertGatePassed(dto, participantDigests); + if (selectedBinding == null) { + publishGateService.assertGatePassed(dto, participantDigests); + } else { + publishGateService.assertSelectedGatePassed(dto, participantDigests); + } } catch (RuntimeException ex) { if (PublicationFailureClassifier.isRetryableParticipantDependencyFailure(ex)) { throw pendingReconciliation( @@ -511,8 +515,14 @@ private void assertCommittedBundleMayMarkSuccess( "published release evidence is incomplete; readback/reconciliation is required"); } VersionDto versionDto = versionMapper.toDto(readback.version()); - PublishedReleaseBundleContract.requireSupportedSchemaForRead(readback.bundle()); - publishGateService.assertGatePassed(versionDto, readback.bundle().participantDigests()); + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(readback.bundle()); + if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + readback.bundle().attestationSchemaVersion())) { + publishGateService.assertSelectedGatePassed( + versionDto, readback.bundle().participantDigests()); + } else { + publishGateService.assertGatePassed(versionDto, readback.bundle().participantDigests()); + } recordedParticipantDigestService.assertMatchesRecordedDigests( request.tenantId(), PublishType.FULL_VERSION, readback.bundle().participantDigests()); } diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java index 54e173f5a4..a0a7d5d873 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -55,7 +55,10 @@ public static WorldPublishedStartLocationEvidence evidence(TargetProof target) t ? evidence.request().contentDigest() : "c".repeat(64), net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence - .supportedParticipantDigestSchema(owner), + .supportedParticipantDigestSchema( + owner, + net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, null, null)) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java index 5b2db2f9d0..e047276f7f 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java @@ -35,6 +35,8 @@ import net.firedevops.firemud.common.authoring.DraftCommitOrderReadClient; import net.firedevops.firemud.common.authoring.DraftCommitOrderReadEvidence; import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityClient; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityEvidence; import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyClient; import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyGrpcCodec; @@ -42,7 +44,6 @@ import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; @@ -70,6 +71,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; @@ -239,6 +241,9 @@ private void compose(Failure failure) throws Exception { var intakeClient = new WorldAuthoredSourceIntakeClient( endpoints, pki.client("game-design-service"), factory, NAMESPACE); + var associationClient = + new WorldAuthoredVersionIdentityClient( + endpoints, pki.client("game-design-service"), factory, NAMESPACE); var accountClient = new AccountOriginalDraftOrderClient( endpoints, pki.client("game-design-service"), factory, NAMESPACE); @@ -262,50 +267,12 @@ private void compose(Failure failure) throws Exception { var identityService = new WorldAuthoredVersionIdentityService( versionClient, identities, intakes, world.transactions(), NAMESPACE); - // There is no production Version-association RPC. This test-only hook invokes the actual - // association service after real intake under that socket's certificate-derived GD peer. - // It neither injects a peer Context nor constructs source, Version or intake evidence. - var associationComplete = new AtomicBoolean(); - var associationHook = - new ServerInterceptor() { - @Override - public ServerCall.Listener interceptCall( - ServerCall call, - Metadata headers, - ServerCallHandler next) { - return next.startCall( - new ForwardingServerCall.SimpleForwardingServerCall<>(call) { - @Override - public void sendMessage(RespT message) { - if (associationComplete.compareAndSet(false, true)) { - var peer = GrpcPeerIdentity.current(); - if (peer == null - || !peer.isService("game-design-service") - || !peer.isInNamespace(NAMESPACE)) - throw new SecurityException( - "Actual authenticated GD socket peer required"); - identityService.associate( - NAMESPACE, - source.canonicalTenantId(), - source.worldSlug(), - source.operationId(), - source.evidenceDigest(), - gd.target().canonicalVersionId(), - gd.target().gameDesignVersionRowId(), - UUID.randomUUID()); - } - super.sendMessage(message); - } - }, - headers); - } - }; - worldHandlers.addService( - ServerInterceptors.intercept( - new WorldAuthoredSourceIntakeGrpcService(intakeService, NAMESPACE), - new GrpcPeerIdentityInterceptor(), - associationHook)); + register( + worldHandlers, + new WorldAuthoredSourceIntakeGrpcService(intakeService, NAMESPACE), + new WorldAuthoredVersionIdentityGrpcService(identityService, NAMESPACE)); intakeClient.init(); + associationClient.init(); var intakeRequest = new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( 1, @@ -318,6 +285,62 @@ public void sendMessage(RespT message) { var publicIntake = intakeClient.intake(intakeRequest); var intake = intakes.read(NAMESPACE, intakeRequest.intakeRequestId()).orElseThrow(); assertThat(publicIntake.receiptDigest()).isEqualTo(intake.receiptDigest()); + UUID intakeReadRequestId = UUID.randomUUID(); + while (intakeReadRequestId.equals(intake.intakeRequestId())) { + intakeReadRequestId = UUID.randomUUID(); + } + var publicIntakeReadback = + intakeClient.readById( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + NAMESPACE, + intakeReadRequestId, + intake.intakeRequestId(), + intake.canonicalTenantId())); + var gameDesignSourceReadback = + sourceRepository + .read( + source.operationId(), source.canonicalTenantId(), source.worldSlug(), NAMESPACE) + .orElseThrow(); + assertThat(gameDesignSourceReadback).isEqualTo(source); + assertThat(publicIntakeReadback.source()).isEqualTo(gameDesignSourceReadback); + assertThat(publicIntakeReadback) + .isEqualTo( + new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + intake.schemaVersion(), + intake.targetNamespace(), + intake.intakeRequestId(), + intake.operationId(), + intake.canonicalTenantId(), + intake.worldSlug(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.requestDigest(), + intake.receiptDigest(), + gameDesignSourceReadback)); + var associationRequest = + new WorldAuthoredVersionIdentityEvidence.Request( + 1, + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gd.target().canonicalVersionId(), + gd.target().gameDesignVersionRowId(), + UUID.randomUUID()); + var publicAssociation = associationClient.associate(associationRequest); + assertThat(publicAssociation.request()).isEqualTo(associationRequest); + assertThat(publicAssociation.sourceIntakeReceipt()).isEqualTo(publicIntake); + assertThat(publicAssociation.versionStateEvidence().request()) + .isEqualTo(associationRequest.versionReadRequest()); + assertThat(publicAssociation.versionStateEvidence().sourceEvidence()).isEqualTo(source); + assertThat(publicAssociation.versionStateEvidence().canonicalVersionId()) + .isEqualTo(gd.target().canonicalVersionId()); + assertThat(publicAssociation.versionStateEvidence().versionState()) + .isEqualTo( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_DRAFT); var identity = identities .readByCanonicalTarget( @@ -326,7 +349,12 @@ public void sendMessage(RespT message) { gd.target().canonicalVersionId(), gd.target().gameDesignVersionRowId()) .orElseThrow(); + assertThat(identity.operationId()).isEqualTo(publicAssociation.operationId()); + assertThat(identity.canonicalVersionId()).isEqualTo(gd.target().canonicalVersionId()); + assertThat(identity.gameDesignVersionId()).isEqualTo(gd.target().gameDesignVersionRowId()); assertThat(identity.sourceIntakeReceipt()).isEqualTo(intake); + assertThat(identity.versionStateEvidence()) + .isEqualTo(publicAssociation.versionStateEvidence()); var binding = binding(gd.target()); var request = account.prepareOriginalDraftOrder(binding, NAMESPACE); var original = request.original(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java new file mode 100644 index 0000000000..78d5aa8633 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java @@ -0,0 +1,215 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.junit.jupiter.api.Test; + +/** Structural digest vectors only; synthetic source rows do not prove physical owner provenance. */ +class SelectedDraftControlPlaneDigestTest { + @Test + void exactSixFamilyPreimageIsDeterministicAndDoesNotIncludePublicationRequestIdentity() + throws Exception { + var selected = selectedBinding(); + var sources = sources(selected); + + var firstRequest = + PublicationDigestRequestBinding.full( + selected.target().canonicalTenantId().toString(), + Long.toString(selected.target().gameDesignVersionRowId()), + "publish-one"); + var retryRequest = + PublicationDigestRequestBinding.full( + selected.target().canonicalTenantId().toString(), + Long.toString(selected.target().gameDesignVersionRowId()), + "publish-two"); + + var first = SelectedDraftControlPlaneDigest.compute(selected, sources); + var replay = SelectedDraftControlPlaneDigest.compute(selected, sources); + var otherRequest = SelectedDraftControlPlaneDigest.compute(selected, sources); + + assertThat(first).isEqualTo(replay); + assertThat(first).isEqualTo(otherRequest); + assertThat(firstRequest.requestDigest()).isNotEqualTo(retryRequest.requestDigest()); + assertThat(first.digestSchemaVersion()).isEqualTo(2); + assertThat(first.tenantId()).isEqualTo(selected.target().canonicalTenantId().toString()); + assertThat(first.scopeValue()) + .isEqualTo(Long.toString(selected.target().gameDesignVersionRowId())); + assertThat(first.appliedCommitId()).isEqualTo(selected.commitId().toString()); + assertThat(first.contentDigest()) + .isEqualTo("08584ce89ee924b5d8b5b613ee60ccc0780716ba43cc7671fd5735b4b5e8015b"); + } + + @Test + void changedSnapshotOrSelectedBindingChangesContentDigest() throws Exception { + var selected = selectedBinding(); + var originalSources = sources(selected); + var original = SelectedDraftControlPlaneDigest.compute(selected, originalSources); + + var changedAsset = + new AssetSnapshot( + selected, + "1", + null, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + List.of()); + var changedSnapshot = + new GameDesignSourceRepository.SynchronizedSources( + originalSources.command(), + originalSources.policy(), + changedAsset, + originalSources.gameplay(), + originalSources.branding(), + originalSources.templateConfig()); + assertThat(SelectedDraftControlPlaneDigest.compute(selected, changedSnapshot).contentDigest()) + .isNotEqualTo(original.contentDigest()); + + var changedBinding = + DraftCommitBinding.create( + selected.target(), + selected.requestId(), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.baseCommitId(), + selected.revisions(), + selected.affectedUnits()); + var changedInput = + SelectedDraftControlPlaneDigest.compute(changedBinding, sources(changedBinding)); + assertThat(changedInput.contentDigest()).isNotEqualTo(original.contentDigest()); + } + + @Test + void missingBrandingOrTemplateFamilyCannotBeTreatedAsAnEmptySnapshot() throws Exception { + var selected = selectedBinding(); + var complete = sources(selected); + var missingBrand = + new GameDesignSourceRepository.SynchronizedSources( + complete.command(), + complete.policy(), + complete.asset(), + complete.gameplay(), + Optional.empty(), + complete.templateConfig()); + var missingTemplate = + new GameDesignSourceRepository.SynchronizedSources( + complete.command(), + complete.policy(), + complete.asset(), + complete.gameplay(), + complete.branding(), + Optional.empty()); + + assertThatThrownBy(() -> SelectedDraftControlPlaneDigest.compute(selected, missingBrand)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("branding"); + assertThatThrownBy(() -> SelectedDraftControlPlaneDigest.compute(selected, missingTemplate)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("template-config"); + } + + @Test + void sourceBindingMustExactlyEqualSelectedDraftBinding() throws Exception { + var selected = selectedBinding(); + var otherBinding = + DraftCommitBinding.create( + selected.target(), + selected.requestId(), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.baseCommitId(), + selected.revisions(), + selected.affectedUnits()); + + assertThatThrownBy( + () -> SelectedDraftControlPlaneDigest.compute(selected, sources(otherBinding))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact Draft commit"); + } + + private static GameDesignPublicationOperation operation() throws Exception { + return IsolatedPublicationOperationFixtures.fresh( + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW")); + } + + private static DraftCommitBinding selectedBinding() throws Exception { + var selected = operation().account().input().selection().selectedCommit(); + var policyRevisions = + selected.revisions().stream() + .filter( + revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) + .filter(RealmPolicySource::isPolicyRevision) + .toList(); + if (policyRevisions.size() != 1) { + throw new IllegalStateException("Expected exactly one selected policy revision"); + } + var policyRevision = policyRevisions.getFirst(); + var fixedRevisionId = UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + var oldRevisionId = policyRevision.revisionId().toString(); + var revisions = new java.util.ArrayList(); + for (var revision : selected.revisions()) { + var payload = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8(revision.payload()), + java.nio.charset.StandardCharsets.UTF_8); + var revisionId = revision.revisionId(); + if (revision == policyRevision) { + if (payload.indexOf(oldRevisionId) < 0 + || payload.indexOf(oldRevisionId) != payload.lastIndexOf(oldRevisionId)) { + throw new IllegalStateException( + "Expected policy revision identity exactly once in payload"); + } + payload = payload.replace(oldRevisionId, fixedRevisionId.toString()); + revisionId = fixedRevisionId; + } + revisions.add( + new RevisionPayload(revision.revisionOrder(), revisionId, revision.owner(), payload)); + } + return DraftCommitBinding.create( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.baseCommitId(), + revisions, + selected.affectedUnits()); + } + + private static GameDesignSourceRepository.SynchronizedSources sources( + DraftCommitBinding binding) { + var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of()); + var policies = + binding.revisions().stream() + .filter( + revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) + .filter(RealmPolicySource::isPolicyRevision) + .map(revision -> RealmPolicySource.revision(binding, revision)) + .toList(); + var policy = new RealmPolicySnapshot(binding, "1", policies); + var asset = + new AssetSnapshot( + binding, "0", null, UUID.fromString("33333333-3333-4333-8333-333333333333"), List.of()); + var gameplay = + new GameplayRuleSnapshot( + binding, "0", null, UUID.fromString("44444444-4444-4444-8444-444444444444"), List.of()); + var branding = + new BrandingSourceSnapshot( + binding, "0", null, UUID.fromString("55555555-5555-4555-8555-555555555555"), List.of()); + var template = + new TemplateConfigSourceSnapshot( + binding, "0", null, UUID.fromString("66666666-6666-4666-8666-666666666666"), List.of()); + return new GameDesignSourceRepository.SynchronizedSources( + command, policy, asset, gameplay, Optional.of(branding), Optional.of(template)); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java new file mode 100644 index 0000000000..dbc1aa9c40 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java @@ -0,0 +1,324 @@ +package net.firedevops.firemud.gamedesign.publication; + +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.inOrder; +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.Status; +import io.grpc.StatusRuntimeException; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Structural owner-read proof; mocks do not establish physical PostgreSQL source provenance. */ +class SelectedDraftPublicationDigestReadServiceTest { + private static final String NAMESPACE = "test"; + + private final SelectedDraftPublicationDigestReadService.OwnerRead owner = + mock(SelectedDraftPublicationDigestReadService.OwnerRead.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final TransactionStatus transactionStatus = mock(TransactionStatus.class); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void readsExactSelectionFrozenAndSynchronizedSourcesInOneReadOnlyRepeatableReadSnapshot() + throws Exception { + var fixture = fixture(); + var request = request(fixture.operation()); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(fixture.sources())); + + var result = + new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE) + .read(NAMESPACE, request); + + assertThat(result.requestBinding()).isSameAs(request); + assertThat(result.requestDigest()).isEqualTo(request.requestDigest()); + assertThat(result.gameDesignDigest().tenantId()).isEqualTo(request.tenantId()); + assertThat(result.gameDesignDigest().scopeValue()).isEqualTo(request.versionId()); + assertThat(result.gameDesignDigest().appliedCommitId()) + .isEqualTo(fixture.binding().commitId().toString()); + assertThat(result.gameDesignDigest().digestSchemaVersion()).isEqualTo(2); + assertThat(result.worldManagementDigest().participantKey()).isEqualTo("WORLD_MANAGEMENT"); + assertThat(result.worldManagementDigest().contentDigest()) + .isEqualTo(fixture.operation().world().request().contentDigest()); + assertThat(result.worldManagementDigest().digestSchemaVersion()) + .isEqualTo(fixture.operation().world().request().digestSchemaVersion()); + + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + var order = inOrder(transactions, owner); + order.verify(transactions).getTransaction(definition.capture()); + order.verify(owner).read(request.derivedWorkflowIdentity()); + order.verify(owner).requireExactSelection(fixture.operation()); + order.verify(owner).readSourceCapture(fixture.operation()); + order.verify(owner).readSynchronized(fixture.binding().target(), fixture.binding().commitId()); + order.verify(transactions).commit(transactionStatus); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(definition.getValue().isReadOnly()).isTrue(); + } + + @Test + void namespaceMalformedScopeAndAmbientSqlAreRejectedBeforeOwnerReads() throws Exception { + var fixture = fixture(); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + + assertCode( + Status.Code.PERMISSION_DENIED, () -> service.read("other", request(fixture.operation()))); + assertCode(Status.Code.INVALID_ARGUMENT, () -> service.read(NAMESPACE, null)); + assertCode( + Status.Code.INVALID_ARGUMENT, + () -> + service.read( + NAMESPACE, + PublicationDigestRequestBinding.patch( + UUID.randomUUID().toString(), "19", "patch", "publish-id"))); + assertCode( + Status.Code.INVALID_ARGUMENT, + () -> + service.read( + NAMESPACE, + PublicationDigestRequestBinding.full("not-a-canonical-uuid", "19", "publish-id"))); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> service.read(NAMESPACE, request(fixture.operation()))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> service.read(NAMESPACE, request(fixture.operation()))); + + verifyNoInteractions(owner, transactions); + } + + @Test + void wrongActualVersionOrPublicationRequestCannotReuseAnotherOriginalOperation() + throws Exception { + var fixture = fixture(); + var validRequest = request(fixture.operation()); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(any())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + + var wrongVersion = + PublicationDigestRequestBinding.full( + validRequest.tenantId(), "20", validRequest.publishRequestId()); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, wrongVersion)); + var wrongTenant = + PublicationDigestRequestBinding.full( + "33333333-3333-4333-8333-333333333333", + validRequest.versionId(), + validRequest.publishRequestId()); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, wrongTenant)); + var wrongRequest = + PublicationDigestRequestBinding.full( + validRequest.tenantId(), validRequest.versionId(), "different-request"); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, wrongRequest)); + + verify(owner, never()).requireExactSelection(any()); + verify(owner, never()).readSourceCapture(any()); + verify(owner, never()).readSynchronized(any(), any()); + } + + @Test + void missingOperationOrRetainedSelectionFailsBeforeSourceReads() throws Exception { + var fixture = fixture(); + var request = request(fixture.operation()); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(request.derivedWorkflowIdentity())).thenReturn(Optional.empty()); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + assertCode(Status.Code.NOT_FOUND, () -> service.read(NAMESPACE, request)); + verify(owner, never()).requireExactSelection(any()); + verify(owner, never()).readSourceCapture(any()); + + org.mockito.Mockito.reset(owner); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + org.mockito.Mockito.doThrow(new IllegalStateException("selection readback unavailable")) + .when(owner) + .requireExactSelection(fixture.operation()); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request)); + verify(owner, never()).readSourceCapture(any()); + } + + @Test + void missingSourceFamiliesAndFrozenSnapshotMismatchCannotProveAnEmptyOrDifferentSource() + throws Exception { + var fixture = fixture(); + var request = request(fixture.operation()); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + var missingBranding = + new GameDesignSourceRepository.SynchronizedSources( + fixture.sources().command(), + fixture.sources().policy(), + fixture.sources().asset(), + fixture.sources().gameplay(), + Optional.empty(), + fixture.sources().templateConfig()); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(missingBranding)); + var service = new SelectedDraftPublicationDigestReadService(owner, transactions, NAMESPACE); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request)); + + org.mockito.Mockito.reset(owner); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + var changedAsset = + new AssetSnapshot( + fixture.binding(), + "1", + null, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + List.of()); + var changedSources = + new GameDesignSourceRepository.SynchronizedSources( + fixture.sources().command(), + fixture.sources().policy(), + changedAsset, + fixture.sources().gameplay(), + fixture.sources().branding(), + fixture.sources().templateConfig()); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(changedSources)); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request)); + + org.mockito.Mockito.reset(owner); + when(owner.read(request.derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + var anotherCommit = + DraftCommitBinding.create( + fixture.binding().target(), + fixture.binding().requestId(), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + fixture.binding().baseCommitId(), + fixture.binding().revisions(), + fixture.binding().affectedUnits()); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(sources(anotherCommit))); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(NAMESPACE, request)); + } + + private static PublicationDigestRequestBinding request(GameDesignPublicationOperation operation) { + var selection = operation.account().input().selection(); + return PublicationDigestRequestBinding.full( + selection.intent().canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + selection.intent().publishRequestId()); + } + + private static Fixture fixture() throws Exception { + var operation = + IsolatedPublicationOperationFixtures.fresh( + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW")); + var binding = operation.account().input().selection().selectedCommit(); + var sources = sources(binding); + var capture = + new GameDesignSourceRepository.Capture( + new CommandSnapshot.Capture(operation, sources.command()), + new RealmPolicySnapshot.Capture(operation, sources.policy()), + new AssetSnapshot.Capture(operation, sources.asset()), + new BrandingSourceSnapshot.Capture(operation, sources.branding().orElseThrow()), + new TemplateConfigSourceSnapshot.Capture( + operation, sources.templateConfig().orElseThrow())); + return new Fixture(operation, binding, sources, capture); + } + + private static GameDesignSourceRepository.SynchronizedSources sources( + DraftCommitBinding binding) { + var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of()); + var policies = + binding.revisions().stream() + .filter( + revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) + .filter(RealmPolicySource::isPolicyRevision) + .map(revision -> RealmPolicySource.revision(binding, revision)) + .toList(); + var policy = new RealmPolicySnapshot(binding, "1", policies); + var asset = + new AssetSnapshot( + binding, "0", null, UUID.fromString("33333333-3333-4333-8333-333333333333"), List.of()); + var gameplay = + new GameplayRuleSnapshot( + binding, "0", null, UUID.fromString("44444444-4444-4444-8444-444444444444"), List.of()); + var branding = + new BrandingSourceSnapshot( + binding, "0", null, UUID.fromString("55555555-5555-4555-8555-555555555555"), List.of()); + var template = + new TemplateConfigSourceSnapshot( + binding, "0", null, UUID.fromString("66666666-6666-4666-8666-666666666666"), List.of()); + return new GameDesignSourceRepository.SynchronizedSources( + command, policy, asset, gameplay, Optional.of(branding), Optional.of(template)); + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private record Fixture( + GameDesignPublicationOperation operation, + DraftCommitBinding binding, + GameDesignSourceRepository.SynchronizedSources sources, + GameDesignSourceRepository.Capture capture) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java index 3917711ae3..84bdbf788a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -83,6 +83,54 @@ void selectorReleaseIsAssembledFromImmutableLocalBundleWithoutMutableOwnerReads( assertEquals(selector, result.releaseAttestation().worldStartLocationEvidence()); result.releaseAttestation().requireValid(descriptor); verifyReadOnlyCallsOnly(); + var obsolete = new java.util.ArrayList<>(selected.participantDigests()); + var gd = obsolete.getLast(); + obsolete.set( + obsolete.size() - 1, + new PublishParticipantDigestDto( + gd.participantKey(), + gd.scopeValue(), + gd.baseVersionId(), + gd.appliedCommitId(), + gd.contentDigest(), + 1, + gd.abilitySchemaDigest(), + gd.errorCode(), + gd.errorMessage())); + givenBundle( + new PublishedReleaseBundleDto( + selected.id(), + selected.tenantId(), + selected.versionId(), + selected.versionNumber(), + selected.attestationSchemaVersion(), + selected.publishWorkflowId(), + selected.manifestHash(), + selected.requiredManifestAssetKeys(), + obsolete, + selected.commandDefinitions(), + selected.generationConfigRevision(), + selected.scriptOnly(), + selected.scriptPatchVersion(), + selected.publishedAt(), + selected.canonicalTenantId(), + selected.canonicalVersionId(), + selected.publishedReleaseBundleRef(), + selected.manifestSchemaVersion(), + selected.artifactDigests(), + selector)); + var rejected = + assertThrows( + IllegalArgumentException.class, + () -> + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest())); + assertTrue(rejected.getMessage().contains("PARTICIPANT_EVIDENCE_INVALID")); } private static final String NAMESPACE = "test"; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java index e9ee9c8665..05b407fa71 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java @@ -25,6 +25,7 @@ import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService; import net.firedevops.firemud.gamedesign.service.ControlPlaneDigestService; import net.firedevops.firemud.gamedesign.service.PublicationFailureClassifier; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; @@ -43,6 +44,7 @@ class PublishGateServiceImplTest { @Mock private GameLogicClient gameLogicClient; @Mock private AutomationScriptingClient automationScriptingClient; @Mock private SelectedDraftGameLogicReceiptRepository selectedGameLogicReceiptRepository; + @Mock private SelectedDraftPublicationDigestReadService selectedPublicationDigestReader; private PublishGateServiceImpl service; @@ -56,7 +58,9 @@ void setUp() { entityManagementClient, gameLogicClient, automationScriptingClient, - selectedGameLogicReceiptRepository); + selectedGameLogicReceiptRepository, + selectedPublicationDigestReader, + "test"); } @Test @@ -129,8 +133,12 @@ void selectedFullVersionGateUsesCanonicalBindingAndExactReceiptForOwnerReads() { version, binding, binding.derivedWorkflowIdentity()); assertEquals(5, digests.size()); - assertDoesNotThrow(() -> service.assertGatePassed(version, digests)); - assertBinding(captureVersionBinding(worldManagementClient), binding); + assertDoesNotThrow(() -> service.assertSelectedGatePassed(version, digests)); + assertEquals(2, digests.get(4).digestSchemaVersion()); + assertEquals("b".repeat(64), digests.getFirst().contentDigest()); + assertEquals("c".repeat(64), digests.get(4).contentDigest()); + verify(selectedPublicationDigestReader).read("test", binding); + org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService); assertBinding(captureVersionBinding(entityManagementClient), binding); ArgumentCaptor gameLogicBinding = ArgumentCaptor.forClass(PublicationDigestRequestBinding.class); @@ -162,7 +170,8 @@ void selectedFullVersionGateKeepsMissingReceiptPendingAndNeverUsesLegacyRead() { assertEquals("PARTICIPANT_UNAVAILABLE", digests.get(2).errorCode()); PublishGateFailureException thrown = assertThrows( - PublishGateFailureException.class, () -> service.assertGatePassed(version, digests)); + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, digests)); assertTrue(PublicationFailureClassifier.isRetryableParticipantDependencyFailure(thrown)); verify(gameLogicClient, org.mockito.Mockito.never()) .getDraftDesignDigestForVersion(any(PublicationDigestRequestBinding.class)); @@ -564,6 +573,168 @@ void scriptPatchGatePassesWhenParticipantsConverge() { PublicationDigestRequestBinding.patch("tenant-1", "7", "patch-1", "publish-request-1")); } + @Test + void unavailableSelectedReaderFailsBothOwnersWithoutLegacyFallback() { + VersionDto version = selectedVersion(); + var binding = selectedBinding(version); + var receipt = org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + when(selectedPublicationDigestReader.read("test", binding)) + .thenThrow(io.grpc.Status.UNAVAILABLE.asRuntimeException()); + + var digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals(5, digests.size()); + assertEquals("UNAVAILABLE", digests.getFirst().errorCode()); + assertEquals("UNAVAILABLE", digests.get(4).errorCode()); + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, digests)); + org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService); + verify(gameLogicClient).getDraftDesignDigestForVersion(binding, receipt); + } + + @Test + void missingSelectedReaderFailsClosed() { + VersionDto version = selectedVersion(); + var binding = selectedBinding(version); + service = + new PublishGateServiceImpl( + controlPlaneDigestService, + worldManagementClient, + entityManagementClient, + gameLogicClient, + automationScriptingClient, + selectedGameLogicReceiptRepository); + when(selectedGameLogicReceiptRepository.readForPublication(binding)) + .thenReturn(Optional.empty()); + when(entityManagementClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", + "7", + null, + null, + null, + "UNSUPPORTED_SCOPE", + "selected Entity evidence unavailable")); + when(automationScriptingClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + "7", + null, + null, + null, + "UNSUPPORTED_SCOPE", + "selected Automation evidence unavailable")); + + var digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals(5, digests.size()); + assertEquals("PARTICIPANT_UNAVAILABLE", digests.getFirst().errorCode()); + assertEquals("PARTICIPANT_UNAVAILABLE", digests.get(4).errorCode()); + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, digests)); + org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService); + } + + @Test + void selectedSnapshotForAnotherRequestCannotSatisfyEitherOwner() { + VersionDto version = selectedVersion(); + var binding = selectedBinding(version); + var other = PublicationDigestRequestBinding.full(binding.tenantId(), "7", "other-request"); + when(selectedPublicationDigestReader.read("test", binding)).thenReturn(selectedSnapshot(other)); + when(selectedGameLogicReceiptRepository.readForPublication(binding)) + .thenReturn(Optional.empty()); + + var digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals("FAILED_PRECONDITION", digests.getFirst().errorCode()); + assertEquals("FAILED_PRECONDITION", digests.get(4).errorCode()); + org.mockito.Mockito.verifyNoInteractions(worldManagementClient, controlPlaneDigestService); + } + + @Test + void selectedGateRequiresSchemaTwoAndPreservesUnsupportedOwnerDenial() { + VersionDto version = selectedVersion(); + var binding = selectedBinding(version); + var receipt = org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + var digests = + new java.util.ArrayList<>( + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity())); + var selected = digests.get(4); + digests.set( + 4, + new PublishParticipantDigestDto( + selected.participantKey(), + selected.scopeValue(), + selected.appliedCommitId(), + selected.contentDigest(), + 1, + null, + null)); + var unsupported = + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, digests)); + assertEquals(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, unsupported.failureCode()); + assertTrue(unsupported.getMessage().contains("GAME_DESIGN_CONTROL_PLANE")); + + when(entityManagementClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", + "7", + null, + null, + null, + "UNSUPPORTED_SCOPE", + "selected owner evidence unavailable")); + var denied = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + assertEquals(5, denied.size()); + var failure = + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, denied)); + assertEquals(PublishGateFailureCode.PARTICIPANT_UNAVAILABLE, failure.failureCode()); + assertEquals("UNSUPPORTED_SCOPE", failure.participantFailureCode()); + + when(entityManagementClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 2, null, null)); + when(automationScriptingClient.getDraftDesignDigestForVersion(binding)) + .thenReturn( + new PublishParticipantDigestDto( + "AUTOMATION_SCRIPTING", + "7", + null, + null, + null, + "UNSUPPORTED_SCOPE", + "selected Automation evidence unavailable")); + var automationDenied = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + var automationFailure = + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, automationDenied)); + assertEquals("UNSUPPORTED_SCOPE", automationFailure.participantFailureCode()); + } + private void stubSelectedParticipantDigests( VersionDto version, PublicationDigestRequestBinding binding, @@ -579,14 +750,12 @@ private void stubSelectedParticipantDigests( private void stubNonGameLogicParticipants( VersionDto version, PublicationDigestRequestBinding binding) { - when(worldManagementClient.getDraftDesignDigestForVersion(binding)) - .thenReturn( - new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "selected-commit", "world-digest", 3, null, null)); + when(selectedPublicationDigestReader.read("test", binding)) + .thenReturn(selectedSnapshot(binding)); when(entityManagementClient.getDraftDesignDigestForVersion(binding)) .thenReturn( new PublishParticipantDigestDto( - "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 1, null, null)); + "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 2, null, null)); when(automationScriptingClient.getDraftDesignDigestForVersion(binding)) .thenReturn( new PublishParticipantDigestDto( @@ -597,10 +766,17 @@ private void stubNonGameLogicParticipants( 5, null, null)); - when(controlPlaneDigestService.getDigestForVersion(version)) - .thenReturn( - new DesignControlPlaneDigestDto( - "private-tenant-key", "7", "selected-commit", "control-plane-digest", 1)); + } + + private static SelectedDraftPublicationDigestReadService.ReadResult selectedSnapshot( + PublicationDigestRequestBinding binding) { + return new SelectedDraftPublicationDigestReadService.ReadResult( + binding, + binding.requestDigest(), + new DesignControlPlaneDigestDto( + binding.tenantId(), "7", "selected-commit", "c".repeat(64), 2), + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", "7", "selected-commit", "b".repeat(64), 3, null, null)); } private static VersionDto selectedVersion() { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index fabdc0d60f..9c7b8dccdf 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -117,6 +117,29 @@ void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorl throws Exception { var evidence = selectorEvidence(); var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + var obsolete = new java.util.ArrayList<>(participants); + var gd = obsolete.getLast(); + obsolete.set( + obsolete.size() - 1, + new PublishParticipantDigestDto( + gd.participantKey(), + gd.scopeValue(), + gd.appliedCommitId(), + gd.contentDigest(), + 1, + null, + null)); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + obsolete, + evidence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact successful release participants"); assertThatThrownBy( () -> service.createFullVersionBundle( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 3b52c49e29..5f1839895e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -239,7 +239,7 @@ void selectedPublicationPassesCanonicalOperationBindingAndKeepsMissingReceiptPen "selected Game Logic receipt is missing", "PARTICIPANT_UNAVAILABLE")) .when(publishGateService) - .assertGatePassed(any(VersionDto.class), any(List.class)); + .assertSelectedGatePassed(any(VersionDto.class), any(List.class)); assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, 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 index 78bb4d7ff5..5fa57379d4 100644 --- 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 @@ -7,12 +7,17 @@ import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; 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.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; @@ -165,6 +170,69 @@ public void readAuthoredWorldSourceIntake( responseObserver.onCompleted(); } + @Override + public void readAuthoredWorldSourceIntakeById( + ReadAuthoredWorldSourceIntakeByIdRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameDesignPeerWithoutCallerContext(responseObserver)) { + return; + } + ByIdReadRequest readRequest; + try { + readRequest = WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdRequest(request); + } catch (IllegalArgumentException exception) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical World intake by-ID read request is required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(readRequest.targetNamespace())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World intake target namespace must match the authenticated workload") + .asRuntimeException()); + return; + } + + Optional stored; + try { + stored = + intakeService.readCommittedReceiptById( + readRequest.schemaVersion(), + readRequest.targetNamespace(), + readRequest.readRequestId(), + readRequest.intakeRequestId(), + readRequest.canonicalTenantId()); + } 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; + } + + ReadAuthoredWorldSourceIntakeByIdResponse response; + try { + response = + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse( + readRequest, toPublicReceipt(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"); @@ -182,6 +250,24 @@ private static CommittedReceipt toCommittedReceipt(WorldAuthoredSourceIntakeRece receipt.receiptDigest()); } + private static PublicReceipt toPublicReceipt(WorldAuthoredSourceIntakeReceipt receipt) { + if (receipt == null) { + throw new IllegalArgumentException("World owner returned no committed intake receipt"); + } + return new PublicReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest(), + receipt.source()); + } + private boolean requireAuthenticatedGameDesignPeer(StreamObserver responseObserver) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer != null @@ -196,6 +282,22 @@ private boolean requireAuthenticatedGameDesignPeer(StreamObserver responseObs return false; } + private boolean requireAuthenticatedGameDesignPeerWithoutCallerContext( + StreamObserver responseObserver) { + if (!SessionContext.hasAuthenticatedCallerContext() + && GrpcPeerIdentity.current() != null + && GrpcPeerIdentity.current().isService("game-design-service") + && GrpcPeerIdentity.current().isInNamespace(trustedNamespace)) { + return true; + } + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "Verified same-namespace Game Design workload without caller context is required") + .asRuntimeException()); + return false; + } + private static void respondWithOwnerFailure( StreamObserver responseObserver, RuntimeException exception) { if (exception instanceof StatusRuntimeException statusException) { 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 index d32ecac3a6..873d90e4bd 100644 --- 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 @@ -5,6 +5,7 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; @@ -193,6 +194,39 @@ public Optional readCommittedReceipt( expectedSourceEvidenceDigest)); } + /** Reads one committed receipt using only its retained request identity and canonical tenant. */ + public Optional readCommittedReceiptById( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + UUID intakeRequestId, + UUID canonicalTenantId) { + requireAuthenticatedGameDesignCallerWithoutCallerContext(); + validateSchemaAndNamespace(schemaVersion, targetNamespace); + requireNoAmbientTransaction(); + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (readRequestId.equals(intakeRequestId)) { + throw new IllegalArgumentException("Read requestId must differ from intakeRequestId"); + } + + Optional receipt = + repository.read(targetNamespace, intakeRequestId); + if (receipt.isEmpty()) { + return Optional.empty(); + } + WorldAuthoredSourceIntakeReceipt stored = receipt.orElseThrow(); + return Optional.of( + requireReceiptForRequest( + stored, + intakeRequestId, + canonicalTenantId, + stored.worldSlug(), + stored.sourceOperationId(), + stored.sourceEvidenceDigest())); + } + private void requireAuthenticatedGameDesignCaller() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer == null @@ -203,6 +237,14 @@ private void requireAuthenticatedGameDesignCaller() { } } + private void requireAuthenticatedGameDesignCallerWithoutCallerContext() { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "World authored-source intake rejects authenticated end-user caller context"); + } + requireAuthenticatedGameDesignCaller(); + } + private static void requireNoAmbientTransaction() { if (TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcService.java new file mode 100644 index 0000000000..da28c7d253 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcService.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityEvidence; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionRequest; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredVersionIdentityServiceGrpc; + +/** Unregistered adapter to the existing immutable World authored-Version association owner. */ +public final class WorldAuthoredVersionIdentityGrpcService + extends WorldAuthoredVersionIdentityServiceGrpc.WorldAuthoredVersionIdentityServiceImplBase { + private final WorldAuthoredVersionIdentityService identities; + private final String namespace; + + public WorldAuthoredVersionIdentityGrpcService( + WorldAuthoredVersionIdentityService identities, String namespace) { + this.identities = Objects.requireNonNull(identities, "identities"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical World namespace required"); + } + this.namespace = namespace; + } + + @Override + public void associateAuthoredWorldVersion( + AssociateAuthoredWorldVersionRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !peer.isService("game-design-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext()) { + deny( + observer, + Status.PERMISSION_DENIED, + "Verified same-namespace Game Design workload required"); + return; + } + WorldAuthoredVersionIdentityEvidence.Request request; + try { + request = WorldAuthoredVersionIdentityGrpcCodec.fromRequest(wire); + } catch (IllegalArgumentException invalid) { + deny( + observer, + Status.INVALID_ARGUMENT, + "Canonical World Version association request required"); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED, "World Version association namespace mismatch"); + return; + } + try { + var receipt = + identities.associate( + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.sourceEvidenceDigest(), + request.expectedCanonicalVersionId(), + request.gameDesignVersionId(), + request.readRequestId()); + var intake = receipt.sourceIntakeReceipt(); + var publicIntake = + new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( + intake.schemaVersion(), + intake.targetNamespace(), + intake.intakeRequestId(), + intake.operationId(), + intake.canonicalTenantId(), + intake.worldSlug(), + intake.sourceOperationId(), + intake.sourceEvidenceDigest(), + intake.requestDigest(), + intake.receiptDigest()); + var result = + new WorldAuthoredVersionIdentityEvidence.Result( + request, receipt.operationId(), publicIntake, receipt.versionStateEvidence()); + observer.onNext(WorldAuthoredVersionIdentityGrpcCodec.toResponse(result)); + observer.onCompleted(); + } catch (SecurityException denied) { + deny(observer, Status.PERMISSION_DENIED, "World Version association authorization denied"); + } catch (IllegalArgumentException invalid) { + deny(observer, Status.INVALID_ARGUMENT, "World Version association input is invalid"); + } catch (org.springframework.dao.DataAccessException + | org.jooq.exception.DataAccessException unavailable) { + deny(observer, Status.UNAVAILABLE, "World Version association storage unavailable"); + } catch (RuntimeException failure) { + deny( + observer, + Status.FAILED_PRECONDITION, + "World Version association has no exact committed proof"); + } + } + + private static void deny(StreamObserver observer, Status status, String description) { + observer.onError(status.withDescription(description).asRuntimeException()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java index cb23eeebd9..dc53cdba9b 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java @@ -183,7 +183,7 @@ static void requireExactReleaseGraph( || !world.contentDigest().equals(freeze.contentDigest()) || world.digestSchemaVersion() != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - "WORLD_MANAGEMENT") + "WORLD_MANAGEMENT", release.schemaVersion()) || world.digestSchemaVersion() != freeze.digestSchemaVersion()) { throw new IllegalArgumentException( "Canonical preparation World participant differs from its exact frozen checkpoint"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcService.java index f4e65d9104..4b829d1456 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcService.java @@ -2,17 +2,27 @@ import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.util.Collections; +import java.util.IdentityHashMap; import java.util.Objects; +import java.util.Set; import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.worldmanagement.v1.ApplyOriginalDraftGraphRequest; import net.firedevops.firemud.worldmanagement.v1.ApplyOriginalDraftGraphResponse; import net.firedevops.firemud.worldmanagement.v1.WorldOriginalDraftGraphApplyServiceGrpc; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** Unregistered Game Design-only original graph apply/recovery construction adapter. */ public final class WorldOriginalDraftGraphApplyGrpcService extends WorldOriginalDraftGraphApplyServiceGrpc.WorldOriginalDraftGraphApplyServiceImplBase { + private static final int MAX_DIAGNOSTIC_CAUSES = 8; + private static final int MAX_DIAGNOSTIC_FRAMES_PER_CAUSE = 8; + private static final Logger LOGGER = + LoggerFactory.getLogger(WorldOriginalDraftGraphApplyGrpcService.class); + private final WorldOriginalDraftGraphApplicationService applications; private final String namespace; @@ -64,6 +74,11 @@ public void applyOriginalDraftGraph( | org.jooq.exception.DataAccessException unavailable) { deny(observer, Status.UNAVAILABLE, "World original apply storage unavailable"); } catch (RuntimeException failure) { + LOGGER.error( + "World original graph application failed to establish committed evidence; " + + "failureType={} trace={}", + failure.getClass().getName(), + diagnosticTrace(failure)); deny( observer, Status.FAILED_PRECONDITION, @@ -74,4 +89,35 @@ public void applyOriginalDraftGraph( private static void deny(StreamObserver observer, Status status, String description) { observer.onError(status.withDescription(description).asRuntimeException()); } + + private static String diagnosticTrace(Throwable failure) { + var trace = new StringBuilder(); + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + Throwable current = failure; + int causeCount = 0; + while (current != null && causeCount < MAX_DIAGNOSTIC_CAUSES && seen.add(current)) { + if (causeCount > 0) trace.append(" <- cause "); + trace.append(current.getClass().getName()).append(" at ["); + StackTraceElement[] frames = current.getStackTrace(); + int frameCount = Math.min(frames.length, MAX_DIAGNOSTIC_FRAMES_PER_CAUSE); + for (int index = 0; index < frameCount; index++) { + if (index > 0) trace.append(", "); + StackTraceElement frame = frames[index]; + trace + .append(frame.getClassName()) + .append('.') + .append(frame.getMethodName()) + .append('(') + .append(frame.getFileName() == null ? "unknown" : frame.getFileName()) + .append(':') + .append(frame.getLineNumber()) + .append(')'); + } + trace.append(']'); + causeCount++; + current = current.getCause(); + } + if (current != null) trace.append(" <- cause chain truncated"); + return trace.toString(); + } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index be69056f3e..3afd20d89c 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -4015,7 +4015,10 @@ private PreparationLaunchFixture preparationLaunchFixture( freeze.appliedCommitId(), "WORLD_MANAGEMENT".equals(owner) ? freeze.contentDigest() : "a".repeat(64), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, + selector == null + ? AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION + : AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner), "GAME_LOGIC".equals(owner) ? "sha256:" + "b".repeat(64) : null)) .toList(); diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java index 1cbc2bbd0a..3521d71571 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java @@ -328,7 +328,7 @@ private static GameDesignPublicationTerminalEvidence terminal( world.appliedCommitId(), "WORLD_MANAGEMENT".equals(owner) ? world.contentDigest() : "c".repeat(64), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, null, null)) 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 index 62c5b598c6..9920f7db0e 100644 --- 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 @@ -17,6 +17,7 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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.WorldAuthoredSourceIntakeGrpcCodec; @@ -24,6 +25,8 @@ 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.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeRequest; import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeResponse; import org.junit.jupiter.api.Test; @@ -131,6 +134,127 @@ void readReturnsCommittedReceiptAndEchoesSeparateRequestIdentity() { SOURCE_DIGEST); } + @Test + void readByIdReturnsFullPublicReceiptAndExactRequestEcho() { + AuthoredWorldSourceEvidence source = + source(NAMESPACE, TENANT_ID, SOURCE_OPERATION_ID, WORLD_SLUG); + WorldAuthoredSourceIntakeReceipt receipt = receipt(binding(), 9001L); + var request = readByIdRequest(); + when(intakeService.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST_ID, INTAKE_REQUEST_ID, TENANT_ID)) + .thenReturn(Optional.of(receipt)); + RecordingObserver observer = + new RecordingObserver<>(); + + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(request, observer)); + + assertThat(observer.error).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.values).hasSize(1); + var response = observer.values.get(0); + assertThat(response.getReadRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(response.getIntakeRequestId()).isEqualTo(INTAKE_REQUEST_ID.toString()); + var decoded = WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdResponse(readById(), response); + assertThat(decoded.source()).isEqualTo(source); + assertThat(decoded.operationId()).isEqualTo(OPERATION_ID); + assertThat(decoded.receiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(response.getReceipt().getAllFields().keySet()) + .extracting(field -> field.getName()) + .doesNotContain("local_tenant_key", "localTenantKey", "local_version_key"); + assertThat(response.getReceipt().getSource().getAllFields().keySet()) + .extracting(field -> field.getName()) + .contains("registration_request_id", "source_game_row_id", "source_game_tenant_key"); + verify(intakeService) + .readCommittedReceiptById(1, NAMESPACE, READ_REQUEST_ID, INTAKE_REQUEST_ID, TENANT_ID); + } + + @Test + void readByIdRejectsWrongPeerEndUserContextAndUnknownFieldsBeforeOwnerAccess() { + var request = readByIdRequest(); + RecordingObserver wrongPeer = + new RecordingObserver<>(); + withPeer( + NAMESPACE, + "game-session-service", + () -> grpcService.readAuthoredWorldSourceIntakeById(request, wrongPeer)); + assertThat(Status.fromThrowable(wrongPeer.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + RecordingObserver userContext = + new RecordingObserver<>(); + SessionContext.setContext("account", List.of(), java.util.Map.of()); + try { + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(request, userContext)); + } finally { + SessionContext.clear(); + } + assertThat(Status.fromThrowable(userContext.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + RecordingObserver unknown = + new RecordingObserver<>(); + ReadAuthoredWorldSourceIntakeByIdRequest withUnknown = + request.toBuilder().setUnknownFields(unknownField()).build(); + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(withUnknown, unknown)); + assertThat(Status.fromThrowable(unknown.error).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + RecordingObserver wrongNamespace = + new RecordingObserver<>(); + withGameDesign( + () -> + grpcService.readAuthoredWorldSourceIntakeById( + request.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + assertThat(Status.fromThrowable(wrongNamespace.error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + for (ReadAuthoredWorldSourceIntakeByIdRequest invalidRequest : + List.of( + request.toBuilder().setSchemaVersion(2).build(), + request.toBuilder().setReadRequestId(INTAKE_REQUEST_ID.toString()).build(), + request.toBuilder().setCanonicalTenantId("not-a-canonical-uuid").build())) { + RecordingObserver invalid = + new RecordingObserver<>(); + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(invalidRequest, invalid)); + assertThat(Status.fromThrowable(invalid.error).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(intakeService); + } + + @Test + void readByIdReportsMissingAndRejectsSubstitutedTenantReceipt() { + var request = readByIdRequest(); + when(intakeService.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST_ID, INTAKE_REQUEST_ID, TENANT_ID)) + .thenReturn(Optional.empty()); + RecordingObserver missing = + new RecordingObserver<>(); + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(request, missing)); + assertThat(Status.fromThrowable(missing.error).getCode()).isEqualTo(Status.Code.NOT_FOUND); + assertThat(missing.values).isEmpty(); + + UUID otherTenant = UUID.fromString("77777777-7777-4777-8777-777777777777"); + IntakeRequest otherBinding = + new IntakeRequest( + 1, + NAMESPACE, + INTAKE_REQUEST_ID, + otherTenant, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source(NAMESPACE, otherTenant, SOURCE_OPERATION_ID, WORLD_SLUG).evidenceDigest()); + when(intakeService.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST_ID, INTAKE_REQUEST_ID, TENANT_ID)) + .thenReturn(Optional.of(receipt(otherBinding, 9001L))); + RecordingObserver changed = + new RecordingObserver<>(); + withGameDesign(() -> grpcService.readAuthoredWorldSourceIntakeById(request, changed)); + assertThat(Status.fromThrowable(changed.error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(changed.values).isEmpty(); + } + @Test void rejectsUnknownWireFieldsBeforeCallingOwnerService() { IntakeAuthoredWorldSourceRequest request = @@ -329,6 +453,15 @@ private static ReadAuthoredWorldSourceIntakeRequest readRequest() { new WorldAuthoredSourceIntakeGrpcCodec.ReadRequest(binding(), READ_REQUEST_ID)); } + private static WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest readById() { + return new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, NAMESPACE, READ_REQUEST_ID, INTAKE_REQUEST_ID, TENANT_ID); + } + + private static ReadAuthoredWorldSourceIntakeByIdRequest readByIdRequest() { + return WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(readById()); + } + private static WorldAuthoredSourceIntakeReceipt receipt( IntakeRequest binding, long localTenantKey) { AuthoredWorldSourceEvidence source = @@ -394,6 +527,12 @@ private static AuthoredWorldSourceEvidence source( evidenceDigest); } + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + private static void withGameDesign(Runnable action) { withPeer(NAMESPACE, "game-design-service", action); } 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 index d978161ef6..b2196d41da 100644 --- 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 @@ -15,6 +15,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; @@ -207,6 +208,108 @@ void exactCommittedReadReturnsWorldReceiptWithoutSourceReadOrAllocation() { assertThat(transactionManager.startedWith).isNull(); } + @Test + void committedReadByIdReturnsFullExactReceiptWithoutSourceReadOrMutation() { + 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.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)); + + 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 committedReadByIdRejectsWrongPeerCallerContextAndInvalidScopeBeforeOwnerAccess() { + assertThatThrownBy( + () -> + withoutPeer( + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + withCallerContext( + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceiptById( + 1, "other", READ_REQUEST, INTAKE_REQUEST, TENANT))) + .isInstanceOf(SecurityException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceiptById( + 2, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, INTAKE_REQUEST, INTAKE_REQUEST, TENANT))) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(client, repository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void committedReadByIdReturnsAbsentAndRejectsSubstitutedTenantWithoutMutation() { + when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); + Optional missing = + withGameDesign( + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)); + assertThat(missing).isEmpty(); + + AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); + when(repository.read(NAMESPACE, INTAKE_REQUEST)) + .thenReturn(Optional.of(receipt(source, 9001L))); + assertThatThrownBy( + () -> + withGameDesign( + () -> + service.readCommittedReceiptById( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + UUID.fromString("77777777-7777-4777-8777-777777777777")))) + .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); + + verify(repository, org.mockito.Mockito.times(2)).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); @@ -612,6 +715,16 @@ private static T withoutPeer(Supplier action) { } } + private static T withCallerContext(Supplier action) { + SessionContext.setContext( + "22222222-2222-4222-8222-222222222222", java.util.List.of(), java.util.Map.of()); + try { + return action.get(); + } finally { + SessionContext.clear(); + } + } + private static final class RecordingTransactionManager implements org.springframework.transaction.PlatformTransactionManager { private TransactionDefinition startedWith; diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcServiceTest.java new file mode 100644 index 0000000000..987a76db0b --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityGrpcServiceTest.java @@ -0,0 +1,243 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityEvidence; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionRequest; +import net.firedevops.firemud.worldmanagement.v1.AssociateAuthoredWorldVersionResponse; +import org.junit.jupiter.api.Test; + +/** Authentication and dispatch proof only; physical owner persistence is separate. */ +class WorldAuthoredVersionIdentityGrpcServiceTest { + @Test + void deniesWrongMissingAndOtherNamespacePeersBeforeDecodingOrOwnerAccess() { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var malformed = AssociateAuthoredWorldVersionRequest.getDefaultInstance(); + for (var service : + List.of("account-service", "world-management-service", "game-session-service")) { + assertThat(call(grpc, malformed, peer(service, "test")).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(call(grpc, malformed, null).code).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(grpc, malformed, peer("game-design-service", "other")).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("123", List.of(), Map.of()); + try { + assertThat(call(grpc, malformed, peer("game-design-service", "test")).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(owner); + } + + @Test + void rejectsUnknownAndInvalidRequestsAndWrongTargetNamespaceWithoutOwnerAccess() { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var wire = WorldAuthoredVersionIdentityGrpcCodec.toRequest(request("test", id(5))); + var unknown = + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + for (var invalid : + List.of( + AssociateAuthoredWorldVersionRequest.getDefaultInstance(), + wire.toBuilder().setUnknownFields(unknown).build(), + wire.toBuilder().setGameDesignVersionId(0).build())) { + assertThat(call(grpc, invalid, peer("game-design-service", "test")).code) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + assertThat( + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request("other", id(5))), + peer("game-design-service", "test")) + .code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } + + @Test + void dispatchesExactAssociationParametersAndReturnsOriginalCommittedEvidenceOnRetry() { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var original = request("test", id(5)); + var retained = receipt(original); + var retry = request("test", id(9)); + when(owner.associate( + "test", id(1), "north-star", id(3), retry.sourceEvidenceDigest(), id(4), 42L, id(9))) + .thenReturn(retained); + var response = + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(retry), + peer("game-design-service", "test")); + assertThat(response.code).isEqualTo(Status.Code.OK); + assertThat(response.completed).isTrue(); + var result = WorldAuthoredVersionIdentityGrpcCodec.fromResponse(retry, response.value); + assertThat(result.operationId()).isEqualTo(retained.operationId()); + assertThat(result.versionStateEvidence()).isEqualTo(retained.versionStateEvidence()); + assertThat(result.versionStateEvidence().request().readRequestId()).isEqualTo(id(5)); + verify(owner) + .associate( + "test", id(1), "north-star", id(3), retry.sourceEvidenceDigest(), id(4), 42L, id(9)); + } + + @Test + void storageFailureAndOwnerConflictProduceNoSuccessfulEvidence() { + var owner = mock(WorldAuthoredVersionIdentityService.class); + var grpc = new WorldAuthoredVersionIdentityGrpcService(owner, "test"); + var request = request("test", id(5)); + when(owner.associate( + "test", id(1), "north-star", id(3), request.sourceEvidenceDigest(), id(4), 42L, id(5))) + .thenThrow(new org.jooq.exception.DataAccessException("storage unavailable")) + .thenThrow(new IllegalStateException("conflicting identity")); + for (var code : List.of(Status.Code.UNAVAILABLE, Status.Code.FAILED_PRECONDITION)) { + var response = + call( + grpc, + WorldAuthoredVersionIdentityGrpcCodec.toRequest(request), + peer("game-design-service", "test")); + assertThat(response.code).isEqualTo(code); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + } + } + + private static WorldAuthoredVersionIdentityEvidence.Request request(String namespace, UUID read) { + var source = source(namespace); + return new WorldAuthoredVersionIdentityEvidence.Request( + 1, namespace, id(1), "north-star", id(3), source.evidenceDigest(), id(4), 42L, read); + } + + private static WorldAuthoredVersionIdentityReceipt receipt( + WorldAuthoredVersionIdentityEvidence.Request request) { + var source = source(request.targetNamespace()); + var requestDigest = WorldAuthoredSourceIntakeDigest.requestDigest("test", id(6), source); + var intake = + new WorldAuthoredSourceIntakeReceipt( + 1, + "test", + id(6), + id(7), + id(1), + "north-star", + id(3), + source.evidenceDigest(), + requestDigest, + WorldAuthoredSourceIntakeDigest.receiptDigest( + "test", id(7), requestDigest, source, 900L), + 900L, + source); + var version = + AuthoredWorldVersionStateEvidence.create( + request.versionReadRequest(), + source, + id(4), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + return new WorldAuthoredVersionIdentityReceipt(1, id(8), 901L, intake, version); + } + + private static AuthoredWorldSourceEvidence source(String namespace) { + var digest = + AuthoredWorldSourceDigest.requestDigest( + namespace, id(2), id(1), "north-star", "north-star", "North Star"); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + id(2), + id(3), + digest, + id(1), + "north-star", + "north-star", + "North Star", + 42L, + "game-tenant-42", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + id(2), + id(3), + digest, + id(1), + "north-star", + "north-star", + "North Star", + 42L, + "game-tenant-42", + "NEW_GAME_ROW")); + } + + private static UUID id(int suffix) { + return UUID.fromString("11111111-1111-4111-8111-" + String.format("%012d", suffix)); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static Collector call( + WorldAuthoredVersionIdentityGrpcService grpc, + AssociateAuthoredWorldVersionRequest wire, + GrpcPeerIdentity peer) { + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var previous = context.attach(); + var result = new Collector(); + try { + grpc.associateAuthoredWorldVersion(wire, result); + } finally { + context.detach(previous); + } + return result; + } + + private static final class Collector + implements StreamObserver { + private AssociateAuthoredWorldVersionResponse value; + private Status.Code code = Status.Code.OK; + private boolean completed; + + @Override + public void onNext(AssociateAuthoredWorldVersionResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + code = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java index 440f1e5626..e0b2b73e35 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java @@ -1100,7 +1100,7 @@ private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence( selector.request().appliedCommitId(), selector.request().contentDigest(), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner), "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java index 13b2c5a708..ec8369a148 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java @@ -8,6 +8,10 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; @@ -26,6 +30,7 @@ import net.firedevops.firemud.worldmanagement.v1.ApplyOriginalDraftGraphRequest; import net.firedevops.firemud.worldmanagement.v1.ApplyOriginalDraftGraphResponse; import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; /** * Guard/dispatch structural proof only; authentic source/persistence is the owner's separate proof. @@ -153,6 +158,46 @@ void deniesOwnerConflictAndMalformedReadbackRatherThanEmittingSuccess() { assertThat(malformed.completed).isFalse(); } + @Test + void unexpectedOwnerFailureIsDeniedAndLogsOnlyFailureTypesAndFrameLocations() { + var owner = mock(WorldOriginalDraftGraphApplicationService.class); + var request = request("test"); + String outerMessage = "creatorCredential=outer-secret"; + String nestedMessage = "sqlParameter=nested-secret"; + var failure = + new IllegalStateException(outerMessage, new IllegalArgumentException(nestedMessage)); + when(owner.apply(eq("test"), any(byte[].class))).thenThrow(failure); + var grpc = new WorldOriginalDraftGraphApplyGrpcService(owner, "test"); + Logger logger = (Logger) LoggerFactory.getLogger(WorldOriginalDraftGraphApplyGrpcService.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + var response = + call( + grpc, + WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request), + peer("game-design-service", "test")); + assertThat(response.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + + assertThat(appender.list).hasSize(1); + var event = appender.list.getFirst(); + assertThat(event.getLevel()).isEqualTo(Level.ERROR); + assertThat(event.getFormattedMessage()) + .contains("failureType=java.lang.IllegalStateException") + .contains("WorldOriginalDraftGraphApplyGrpcServiceTest.java:") + .contains("cause java.lang.IllegalArgumentException") + .doesNotContain(outerMessage, nestedMessage); + assertThat(event.getThrowableProxy()).isNull(); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + verify(owner).apply("test", request.originalAccountBinding()); + } + private static GrpcPeerIdentity peer(String service, String namespace) { return new GrpcPeerIdentity( "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); From 2fb5253f9567660acfa73f35c15aa38071f84af3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 23:55:25 +1300 Subject: [PATCH 050/129] fix(publication): preserve exact source associations and owner transaction reads --- ...dmin-as-external-operator-write-ingress.md | 4 + .../account-service/api-contracts.md | 2 + .../account-service/runtime-and-data.md | 2 +- .../game-design-service/api-contracts.md | 2 + .../game-design-service/asset-storage.md | 8 + .../game-design-service/game-templates.md | 8 + ...ame-authoring-publishing-and-activation.md | 6 + ...start_session_operator_authorization.proto | 119 +++ ...sionRedeemedOperationProjectionClient.java | 330 +++++++++ .../common/operator/MutationDigestV1.java | 299 ++++++++ .../StartSessionAuthorityEvidenceBundle.java | 642 ++++++++++++++++ .../operator/StartSessionOperatorAction.java | 143 ++++ .../StartSessionOperatorActionCodec.java | 605 +++++++++++++++ ...essionPostAuthorizationExecutionTuple.java | 445 ++++++++++++ ...ssionPreAuthorizationReservationTuple.java | 381 ++++++++++ ...RedeemedOperationProjectionClientTest.java | 687 ++++++++++++++++++ .../StartSessionOperatorActionCodecTest.java | 225 ++++++ ...artSessionAuthorityEvidenceBundleTest.java | 359 +++++++++ ...onPostAuthorizationExecutionTupleTest.java | 223 ++++++ ...nPreAuthorizationReservationTupleTest.java | 134 ++++ ...rt-session-mutation-digest-v1-vectors.json | 167 +++++ .../SelectedDraftAssetInventory.java | 311 ++++++++ ...electedDraftAssetInventoryReadService.java | 523 +++++++++++++ ...ectedDraftPublicationAdmissionService.java | 98 ++- ...electedDraftPublicationCommandService.java | 19 +- .../SelectedDraftPublicationOwner.java | 32 +- ...edDraftTemplateWorldSourceAssociation.java | 293 ++++++++ ...plateWorldSourceAssociationRepository.java | 273 +++++++ ...cted_template_world_source_association.sql | 105 +++ ...ublication_control_plane_digest_schema.sql | 202 +++++ .../draft/IsolatedPublicationOwnerSetup.java | 110 ++- ...teConfigSourcePostgresIntegrationTest.java | 258 +++++++ ...leaseCanonicalIdentityIntegrationTest.java | 52 +- ...emptServiceTransactionIntegrationTest.java | 263 ++++++- ...tedDraftAssetInventoryReadServiceTest.java | 668 +++++++++++++++++ ...dDraftPublicationAdmissionServiceTest.java | 270 ++++++- .../WorldAuthoredSourceIntakeRepository.java | 15 +- ...WorldDesignPublicationFenceRepository.java | 35 +- ...nceAssociationPostgresIntegrationTest.java | 7 +- ...aphApplicationPostgresIntegrationTest.java | 97 +++ 40 files changed, 8368 insertions(+), 54 deletions(-) create mode 100644 protos/account/v1/start_session_operator_authorization.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java create mode 100644 services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java create mode 100644 services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventory.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociation.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociationRepository.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V62__selected_template_world_source_association.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V63__selected_publication_control_plane_digest_schema.sql create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadServiceTest.java diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 8620d0bbbc..2116d624c7 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -95,6 +95,10 @@ Both issuance paths use the same bounded typed-mutation admission contract befor `issuanceKind` is an enum with exactly `human_operator` and `automation_operator`; the example above shows the human value and the two values are never combined into one literal. +#### Redeemed StartSession Projection Read + +After Game Session has redeemed the original human StartSession reference and allocated its owner attempt and fence, Account may serve `ReadRedeemedOperationProjection` to the exact same-namespace `game-design-service` peer only to read the immutable template-selected source/descriptor for the same original tenant, template, and `controlPlaneRequestId`. The request is bound to the exact canonical pre-authorization tuple, Account-returned authorization-reference fingerprint, original reservation owner/fence, and actual Game Session `ownerAttemptId`/`ownerFence`; Account independently revalidates the original actor and `control-ui` token `jti`, current Account source and reference expiry, and the stored original reservation and redeemed Game Session attempt/fence before returning that projection. No forwarded JWT or opaque reference is sent on this read, and neither workload identity, fingerprint, nor authority-bundle integrity alone establishes authority. The read is credential-free and read-only: it does not renew or extend a reservation/reference, issue or redeem a credential, mutate source state, select a different template or policy, create another owner attempt, commit the owner mutation, or bootstrap/activate a runtime. Exact retries repeat the same binding and return the same operation projection without policy reselection; changed, stale, or ambiguous bindings fail closed. This read is not a commit-spanning CAS proof; owner commit and runtime activation remain separately fenced by their owners. + `authorityTuple` is copied without scalarization or field renaming from the complete canonical shape in the [JWT and token contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple). `membershipVersion` is the independently applicable Account membership-version map, including `{}` when no membership applies. `HumanAuthorityEvidence/v1` carries the Account-derived actor account, `control-ui` token `jti`, role, assurance, account generation, and applicable tenant or target-tenant generation. `AutomationAuthorityEvidence/v1` carries the exact authenticated workload, automation-policy identity/version, and applicable tenant generation. The tagged `issuanceEvidence` arm must agree with Account-derived `issuanceKind`; the inapplicable arm and inapplicable authority-scope identifiers are omitted rather than serialized as `null`, empty objects, or sentinels. `sourceEvidenceId` identifies the one Account authority snapshot and its linearization evidence, while `sourceEvidenceVersion` is the corresponding Account-issued source version; together they are the canonical source fence for the bundle and are carried unchanged with the existing `{bundleVersion, sourceVersion, sourceFence, linearization}` reference. Account derives every authority, generation, membership, freshness, and branch-decision member from that one atomic snapshot and stores the source pair with the issuance record. During redemption, Account exact-compares `sourceEvidenceId`, `sourceEvidenceVersion`, the bundle reference, and every snapshot-bound field against the stored issuance record and the current applicable authority evidence; a missing, changed, or mixed-version value rejects redemption. Consumers reject missing, extra, contradictory, separately sourced, stale, expired, wrongly tagged, or non-canonical bundle fields and must redeem the original reference with Account; a copied bundle never becomes a second authority. For every forwarded owner-mutation family, ADR 0048's canonical complete `postAuthorizationExecutionTuple` is the required post-authorization identity. It explicitly contains ADR 0048's stable `controlPlaneRequestId` for orchestration, reservation, lookup, and correlation across forwarding, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor/policy binding, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` defined above (whose issuance identity carries the tagged `actionFamilyRequestIdentity` for domain action/idempotency), and every schema-bound typed presence/absence value. `targetOwner` is distinct from `target`, immutable after reservation, and is never inferred from current routing or owner state. Reservation and pre-authorization Account issuance/recovery compare `preAuthorizationReservationTuple`; post-authorization tuple completion, owner idempotency, terminal/no-commit proof, result lookup, conflict handling, and any later fresh owner attempt carries and compares its own exact tuple; no participant may omit a required identity because it is unavailable locally. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index fe05228e03..a0f538818b 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -16,6 +16,8 @@ Changing a tenant's Creator Party is a distinct target-only Account transfer ope For official hosted deployments, Game Design owns creator content and must obtain a bounded Account currentness/evidence result before each creator-intent content-bearing write, including the first Draft. The exact party, evidence, and material-acceptance-generation authority must remain valid through Game Design's commit linearization point; a preflight read alone is insufficient, so the boundary requires commit-bound Account authorization/fence or equivalent validation without selecting its mechanism. Each committed covered mutation records `tenantId`, exact `creatorPartyId`, `acceptanceEvidenceId`, and material-acceptance `generation`; Game Design stores only this local binding and does not duplicate Account's party or terms catalogs. Missing, stale, mismatched, ambiguous, unavailable, or uncertain authority aborts the Game Design local transaction before any mutation or staged artifact becomes authoritative or externally reachable; staged bytes are cleanup/quarantine state, not success. Exact durably committed retries replay their stored result and evidence. An uncertain or not-durably-committed attempt first reconciles the original stable identity and obtains durable no-commit proof; it is not blindly redispatched or mutated while indeterminate. Only a permitted fresh attempt performs a fresh commit-bound currentness check. Reusing the same identity with changed normalized payload returns the target application outcome `IDEMPOTENCY_CONFLICT` before mutation. Account does not select a distributed transaction, public route, or future schema here. +Environment selection and Account authorization are separate. Account's trusted runtime environment input selects the actual server-owned deployed boundary and supplies its authenticated owner identity and exact deployment evidence; creator callers cannot select that boundary. Account uses that provider result only to resolve the persisted boundary-to-hosted-scope binding, then Account-owned operator, Creator Party, terms-catalog, and acceptance/currentness authority determines whether the result is current. Missing or unverifiable deployment evidence, or an absent or unverified binding, denies currentness. This is deployment-boundary selection, not an independent authorization observer or authority vector; it does not grant creator-write permission or replace the commit-bound Account authorization above. Provider implementation and registration remain tracked in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). + Account owns the changed-hosted-terms technical contract. It classifies each proposed terms change as material or nonmaterial through audited operator/legal review. A material change classified under [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) advances the monotonic material-acceptance generation and requires affirmative reacceptance; only a nonmaterial change may leave that generation unchanged. Account keeps operative and proposed versions distinct, gives reasonable notice through disclosed durable channels with a disclosed effective date, and records sufficient notice evidence. An explicit decline during the notice period records nonacceptance but does not end the previously accepted terms or freeze writes early. At the effective date, a declined or non-reaccepted material generation is stale; Account currentness fails closed and Game Design blocks each covered new content-bearing mutation before side effects. For any elective, not-yet-disclosed exact terms-source change that introduces an effective date, Account must own an authenticated, durable prepare-before-disclose handoff bound to the exact predecessor, candidate, and effective instant. It must serialize every applicable deadline-introduction path, including an environment-binding change that can expose a scope's deadline, against original `COMMIT_ORDER` acquisition and owner settlement; a one-time pending-order preflight is insufficient. Refuse introduction of a new deadline while an original applicable commit order remains unresolved, and preserve that fence through dispatch authorization, external disclosure and exact durable readback. No database lock may be held across an RPC. Once disclosed, the effective instant is immutable; exact retries and recovery use the same handoff identity and authenticated durable readback, and a notice reference or caller-supplied timestamp alone is not proof. Ordinary authoring under the previously operative terms continues until the disclosed effective instant: do not freeze it early, defer or rewrite a disclosed date, or delay existing security or restriction powers. A currentness observation is not write authorization; consumers of deadline-qualified creator-write authority remain denied until physical commit-time currentness and the complete handoff's focused proof exist. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index cf4a5c646f..a5d78feaf0 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -24,7 +24,7 @@ Account also performs a bounded sweep of public connect-scope evidence after its The current public registration path creates only a global Account row and a platform-scoped audit outbox record; it does not create a tenant membership or profile, and a legacy caller-supplied `tenantId` does not establish tenant authority. Explicit `JoinPublicProductionMembership` is the only public-production membership writer. It first commits a policy-independent `PENDING` intent containing the global request ID, verified caller binding, exact retained connect-scope evidence, and a version-1 intent digest. Only after authoritative entitlement evaluation succeeds does a separate Account transaction bind `allowPublicJoin`, the positive `entitlementVersion`, and the version-1 policy digest; that transaction revalidates the exact policy at the membership commit gate and atomically commits any membership transition, tenant-scoped audit outbox event, and terminal operation outcome. If entitlement authority is unavailable, the row remains `PENDING` with a typed last-attempt failure and availability but null policy values and null policy digest; an exact request retry may reconcile it after authority recovers. For a retained `PENDING` operation, an expired or malformed scope now fails terminally with `CONNECT_SCOPE_INVALID` before entitlement evaluation or membership mutation. Definitive pre-policy failures retain the intent digest and a durable terminal outcome rather than fabricating policy evidence. A definitive mismatch between the freshly evaluated policy digest and an already-bound digest fails terminally as `IDEMPOTENCY_CONFLICT`, retaining the original request digest, policy version, and policy result without membership or transition audit/outbox mutation; this applies both on a retry and at the immediate commit-gate reread. Unavailable or unsafe authority and uncertain commit outcomes remain `PENDING`. A post-transaction readback applies the terminal retry checks when a terminal row is present; otherwise Account returns retryable `AUTH_UNAVAILABLE` and the caller must retry the same request ID. No background PENDING-operation reconciler is claimed; recovery/reconciliation after an unknown database commit outcome remains open. An exact retry of a terminal JOIN replays its stored result only after the retained scope is still unexpired and current target/entitlement authority is available and matches the stored policy digest; expiry, unavailable authority, or changed policy fails closed without rewriting the terminal operation or membership. `ACTIVE` membership is idempotent, while only missing or inactive membership transitions to `ACTIVE`. PostgreSQL repository proof covers independent intent insertion and atomic policy-binding/membership/outbox/outcome persistence, while the service unit proof covers the separate transaction commit/rollback boundary; all PostgreSQL cases are skipped locally without Docker, so no live PostgreSQL execution is claimed. No direct text-client end-to-end proof is claimed. Legacy Account migrations still assign tenant defaults/backfills and retain prior memberships as unverified, non-admitting evidence. This remains a retained-data deployment blocker: before any affected deployment, Account must record either a verified no-data boundary or an explicit retained-row disposition/mapping, including exact readback and admission-isolation evidence. No recovery is implied for already-applied irreversible migrations, and this status does not choose a tenant-identity migration design. -Account has bounded owner-local storage for identified Creator Party/operator, terms catalog, acceptance/currentness evidence, and environment-binding/publication operations. These stores are not registered production authority and do not establish the authenticated notice handoff or physical World commit-time currentness boundary. No production acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved. The local retention/export treatment follows [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md); the normative contract is in [Account API Contracts](./api-contracts.md#account-owned-hosted-terms-and-creator-party), and implementation gaps are tracked in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. +Account has bounded owner-local storage for identified Creator Party/operator, terms catalog, acceptance/currentness evidence, and environment-binding/publication operations. Its trusted deployment-boundary selector remains unimplemented or unregistered; missing or unverified deployment evidence or a missing persisted binding denies currentness. The stores do not establish the authenticated notice handoff or physical World commit-time currentness boundary. No production acceptance/transfer route, creator UI, or Game Design evidence binding is implemented or proved. The local retention/export treatment follows [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md); the normative selector-versus-authorization contract is in [Account API Contracts](./api-contracts.md#account-owned-hosted-terms-and-creator-party), and implementation gaps are tracked in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md). Organization support, marketplace enrollment, and creator-player entitlement issuance remain disabled rather than implied by this data model. The live `GetTenantMembershipForRuntime` producer emits `accountId`, `tenantId`, `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`; `roles`, the complete `authorityTuple`, and `outboxCheckpoints` remain absent from the proto and producer. Current consumers still rely on only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and do not enforce the complete atomic-freshness contract or consume the emitted lifecycle/generation fields. Account-first bootstrap and credential-bearing gameplay `Authenticate` authenticate global Account identity before tenant selection and accept configured password or verified-email OTP modes. The gameplay authentication and challenge protos no longer carry `tenantId`, membership is not an authentication prerequisite, and the private delegation token uses the account-scoped legacy session record; Game Session may retain its bootstrap tenant only as local transport context. `GetTenantMembershipForRuntime(accountId, tenantId, requestId)`, `GetTenantEntitlementsForRuntime(tenantId, requestId)`, and `GetAdmissionPointer(tenantId, worldSlug, realmSlug)` are present. Current connect-token issuance and character discovery require membership after applicable target and entitlement checks; on an eligible public-production target only absent membership may return non-actionable `JOIN_REQUIRED`, while existing membership with `gameplayAdmissionAllowed=false` is denied as `CONNECT_TOKEN_REJECTED`. Current text `PLAY` can still return non-actionable `JOIN_REQUIRED` for missing or present non-admitting membership before fresh entitlement and public-target-policy ordering is established; this remains the AA-2.1 / Unit 1B ordering gap. These flows do not create or restore membership. The Account-owned public-production `JOIN` writer is implemented locally with a v1 policy-bound digest and atomic membership, operation-outcome, and audit-outbox evidence. Its HTTP exposure remains blocked by the Gateway route guard; Game Session text `JOIN`/`Join & Play` dispatch remains with #2898, while durable recovery after an unknown database commit and Logging receipt receiver/readback remain with #2848. Exact-final-head PostgreSQL runtime proof remains unavailable locally without Docker; no live PostgreSQL runtime proof or direct text-client end-to-end proof is claimed. See [Account API Contracts](./api-contracts.md) for the public and internal API boundary and [Authentication](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) for the canonical direct-text scope and JOIN contract. `GetAdmissionPointer` is a live `game_session.v1.GameSessionService` RPC served by the Game Session runtime owner and consumed by Account through `GameSessionClient`; its current response shape and the target routing semantics owned by Multi-Tenancy are described below. Broader reconnect/cutover consumption of admission-pointer truth and operator-facing pointer tooling remain incomplete. The entitlement producer returns retryable `ENTITLEMENT_UNAVAILABLE` (HTTP 503 and the gRPC error field) when a tenant has zero or multiple subscription rows; only one explicit row is projected through current status mapping. Explicit free/trial row creation, an authoritative current-row selector/constraint/history, and canonical snapshot fields/freshness remain unimplemented, including nullable `provisioningStatus`, opaque `tenantAuthorityGeneration`, caller/verified-target binding, source-event evidence, and event delivery. Focused zero-row, mixed-row, gRPC classification, and replay-after-recovery proof covers only that cardinality guard and retry boundary. `CommitTenantCapacityAdmission` has one synchronized target request/replay contract, including `mutationDigest`, but its proto RPC, callers, durable Account-owned authority/usage persistence, and reservation lifecycle remain unimplemented. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 93071ae7ea..1f92a2d2b9 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -22,6 +22,8 @@ Game Design issues each new game row an opaque canonical tenant UUID and keeps e `TenantIdentityService.ResolveAuthoredWorldSource` is a separate read-only owner lookup for the exact retained Game Design source operation used by World Management's authored-world intake construction. Its closed request contains a canonical non-nil read correlation UUID, source operation UUID, canonical tenant UUID, and exact canonical `world_slug`; the receiver supplies the trusted namespace from its own configuration. The handler authenticates the exact same-namespace `world-management-service` TLS peer and rejects authenticated caller context before parsing the request or reading storage. Unknown fields, malformed or nil identifiers, noncanonical selectors, and missing or inconsistent source evidence fail closed. Success echoes the read correlation and returns the complete retained registration receipt, including its request and evidence digests, canonical tenant and slugs, display name, and source-row provenance. The owner recomputes both digests from the full tuple and checks the source against the persisted Game Design tenant row; a read does not allocate, repair, register, or activate source state. World must authenticate the Game Design server and validate the full response echo, selector, immutable fields, and recomputed digests before retaining that exact evidence. This read is not creator authentication, World registration, source-write authorization, launch permission, or runtime admission. +The distinct Game Session-facing template source read follows the [immutable template-to-World association contract](game-templates.md#immutable-template-to-world-source-association), not this World-only registration-source lookup. Its receiver must authenticate the exact same-namespace Game Session caller and independently verify the Account original-operation projection before returning the exact selected association. Retry checks preserve the original operation and selection, and missing association evidence denies without read-side population. The current source, association and consumer proof limits are tracked in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); this API consequence does not establish an enabled method or broaden the existing `TenantIdentityService` allowlist. + `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. ## Official Hosted Creator Mutation Gate diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 645be105c9..8e2e4b6ae3 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -33,6 +33,14 @@ Derived runtime-consumed artifacts produced by domain services follow the same w - If those artifacts are exported for runtime consumption, Game Design publishes them on behalf of the owning service through the canonical [asset lifecycle and publish workflow](#asset-lifecycle-and-publish-workflow), not through a direct producer write or direct version-prefix export. - Domain services must not write directly to the shared object store used for published version assets. A direct domain-service object-store write would bypass the artifact lifecycle, release attestation, and purge controls defined here. +## Complete Selected Release Asset Inventory + +A selected-Draft publication obtains its ordinary and branding inventory from the exact retained Game Design publication operation, selected commit and immutable owner source captures. It verifies complete source-family declarations and original revision provenance, then obtains the actual bytes from the tenant-qualified retained asset source and checks each usage key, content type, byte count and SHA-256 digest. The ordinary version-asset snapshot alone cannot establish complete selected branding or template/config coverage. An empty family requires exact owner-authored empty source evidence; an absent capture, unknown family, unsupported optional reference or unresolved owner reference is not empty inventory. The closed source/reference grammar remains owned by [Game Templates](game-templates.md#closed-versioned-configuration-and-references-target-state). + +The Game Logic receipt is derived evidence joined to the exact unchanged selected source, not an authored field or permission to substitute another selection. Its full selection and source must match the original publication operation and synchronized gameplay snapshot. World-derived artifacts remain independently owned and bound to World's complete selected inventory; Game Design must obtain any required exact producer bytes rather than synthesizing them from its ordinary or branding sources. Usage keys must be unique across the assembled release inventory. + +Before any external object write, Game Design retains and independently reads back the exact selected inventory binding together with the durable private candidate. Candidate, actual-byte object readback, final manifest and immutable release evidence must agree under the [asset lifecycle and publish workflow](#asset-lifecycle-and-publish-workflow). Exact retry preserves that binding; changed or missing evidence denies or remains pending, never causing a version-prefix fallback, guessed complete inventory or cleanup of uncertain writes. Current construction and unexecuted proof remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); an inventory reader is not release completion or activation authority. + Canonical producer-to-publisher handoff for derived artifacts: - For the target producer handoff, a producer service that owns a derived runtime artifact must persist a version-scoped artifact record in its own database keyed by `(tenantId, versionId, usageKey)`. `usageKey` is stable and unique within that release scope; a collision or two records claiming the same usage key must fail closed rather than produce ambiguous manifest entries. `artifactKind` remains required metadata and does not replace the usage key. diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index c0b4837ac2..37aa7308cd 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -215,6 +215,14 @@ Required ordering: No service may create persistent instance rows before this preflight sequence completes successfully. Partial provisioning before attestation/reference validation is not an allowed first-slice behavior. +### Immutable Template-to-World Source Association + +Game Design owns the immutable association between the canonical tenant, its existing template identity, the exact selected version and Draft commit, and the original authored-world source. The association derives from the authenticated selected publication and its captured template/config entry; it is not another author-supplied selector. Retain the complete original source operation and evidence digest, canonical tenant and stored `worldSlug`, source provenance, exact World intake receipt and independent source-read correlation, and the original selection/publication identity. Game Design independently compares the authenticated World intake read with its own retained source and, when present, its exact delivery acknowledgement before retaining the association alongside the local publication reservation. A private numeric provenance key is not a public selector or permission. Multiple actual captured templates may have their own exact associations; do not invent a one-template restriction or infer associations for uncaptured or ambiguous retained rows. + +The immutable read is restricted to the exact same-namespace Game Session workload inside its unchanged Account-authorized `StartSession` operation. Before returning content, Game Design independently verifies Account's authenticated original-operation projection, including the original actor, workload, target and actual Game Session attempt/fence binding. A descriptor digest, forwarded JWT, source receipt or workload identity alone does not establish this read permission. Game Session binds the selected association, version and descriptor to its original `controlPlaneRequestId` before reuse. Exact retries preserve that selection and cannot silently choose a newer association, another commit or another release. Missing, ambiguous, substituted or mismatched scope/commit evidence denies; a read never repairs missing association rows or grants Game Design mutation, World application or runtime activation. The operator authority and read-applicability contract belongs to [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); source association does not replace release attestation or Game Session's launch ownership. + +The association producer, authenticated operation-bound read and Game Session pinning are distinct proof boundaries. Their current implementation and activation limits belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status), not to the presence of a template row or a structurally valid association object. + Required deterministic failure vocabulary for the first implementation slice: - `TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED` when `GetTemplateReferencePhase` is not `ENFORCED`. 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 e5637baf47..7edf4b17e7 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 @@ -110,8 +110,14 @@ Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, b Game Design now has a callable `GetCompleteLaunchBinding` handler and strict descriptor/release-attestation codec for the World Management read path. Its exact-method bearer-interceptor bypass is only transport dispatch: the handler still denies absent, wrong-service, or wrong-namespace TLS peers before parsing or owner reads. Corrected-state Common/Game Design checks, handler/auth-wiring and codec units, and the Game Design boot JAR pass locally; no genuine positive persisted release/attestation read, mounted-certificate transport proof, or launch activation is claimed. World Management owns exact binding persistence and preparation; Gameplay owns Game Session launch orchestration and its executable-front fixture. +The selected source construction now includes V62's immutable per-captured-template association to the original World source. Its admission producer reads the full authenticated World intake outside SQL, independently compares Game Design source and delivery evidence, and retains the relation with the selected publication reservation. Exact replay preserves the stored read correlation and association bytes; inherited template entries preserve their original revision provenance. The defined PostgreSQL cases cover substituted source denial, immutable readback and concurrent first reservation, but their corrected-head physical execution remains required. The shared Account redeemed-StartSession projection client and protocol are preserved from Gameplay commit `60daafc34`; importing them does not implement the separate Game Design receiver or Game Session's durable selection/descriptor pinning. Those remain open under the [template association owner contract](../../architecture/microservices/game-design-service/game-templates.md#immutable-template-to-world-source-association). + +The complete selected asset-inventory reader uses an independent read-only snapshot, exact retained publication/capture and Game Logic receipt, and actual tenant-qualified ordinary and branding bytes. Its explicit empty declarations come from genuine selected source history, never absence of evidence; unresolved World/Entity/Automation references deny completeness. Mock-based unit definitions cover present bytes, cross-family collisions, changed bytes, incomplete captures and substituted receipt selection. This reader is not the durable private candidate, object writer, final immutable manifest or authenticated end-to-end release proof; those integrations remain open under [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). + The original GD+World construction now implements the World-local retained-identity resolver, a distinct closed application/recovery transport and a Game Design composer that retains both exact owner outcomes before synchronized visibility. These components remain unregistered. CI run [37905710499](https://github.com/benhook1013/FireMUD/actions/runs/37905710499) for published `be47226a97d2a945f767c8adf0c3a955834ed629` executed all 133 Game Design integration cases, including the three new genuine PostgreSQL/mTLS composition cases, with no skips: those three failed establishing committed World evidence. All 206 World integration cases passed. This is an owned composition defect, not successful two-owner proof; its correction requires executed follow-up proof. The synthetic checkout used parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded construction parent `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`, so the run does not establish that recorded parent's alignment. The Account job's separate WAL-coverage failure remains an admission gate, not a dependency of this source/release handoff. +The subsequent [Validation run 37913210424](https://github.com/benhook1013/FireMUD/actions/runs/37913210424), source `183a243f6aacd41f391c10943ca18dc1b50dae7b`, executed Game Design 133, World 206 and Account 254 integration cases with zero skips and respectively nine, eleven and one failures. Credential-safe diagnostics established the genuine three-case source failure: World's publication fence used the committed-only intake read inside its writable owner transaction. The prepared repair keeps that public denial and selects a strict physical writable `READ_COMMITTED` accessor only for owner application/freeze; committed exact attempt reads retain their separate boundary. Six selected-release failures exposed V49's stale GD schema-1 guard; additive V63 converges selected schema-2 evidence without changing retained rows or other guard predicates. Eleven World failures require selected-schema fixture correction, not runtime guard relaxation. Account's separate WAL-coverage denial remains open. The artifact-bound synthetic checkout is `d9249b9350a0c8239a397309c718a10507c2dee1`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source head; the run title's older `1a8eefe` base token does not describe that actual first parent. Corrected-head physical execution, rather than prepared code or skipped local tests, is still required for the source handoff. + The corrected local composition fixture uses the real distinct World authored-Version association mTLS client and receiver, with independently checked durable owner readback, instead of its earlier test-only incoming-context handoff. It also reads the World intake by its retained ID and independently compares its complete public source receipt with the Game Design owner record. Consolidated gate R240 passed Common, Common Security, Account, Game Design and World checks, formatting, static analysis, coverage, Game Design/World boot-JAR construction, links and Markdown. Its validated unit reports contain 2,722 green cases (Common 414, Common Security 138, Account 1,109, Game Design 480, World 581), including unchanged reused outputs; the standard Game Design/World integration reports contain 336 skipped definitions without Docker. The separately packaged genuine three-case composition fixture requires explicit physical execution; the green local aggregate is not that proof. Selected publication now consumes the exact retained paired World/GD digests with explicit attestation-schema context and a fixed six-family GD content vector. Unexpected World application failures retain strict denial and emit bounded message-free class/frame diagnostics, not credential or SQL payloads. The underlying physical failure remains unresolved. Genuine corrected-state two-owner execution, complete multi-owner definitive-abort recovery and release composition remain open. The existing executed GD-only source proof does not prove this combined original. The normative coordinator and receiver contracts belong to [Game Design version control](../../architecture/microservices/game-design-service/version-control.md#design-time-synchronization) and [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md#original-authorized-draft-graph-application). Official-hosted creator-content acceptance remains partial under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Account's individual-party and hosted-terms repositories now retain exact catalog, affirmative-acceptance and environment-binding operations; `AccountHostedTermsService` can resolve the external environment observation before SQL work and reread locked currentness in a caller-owned writable `READ_COMMITTED` transaction. The service and its trusted publication, environment and affirmative-action participants remain unregistered; current creator authentication and original multi-owner commit enforcement are not supplied by these storage APIs. `HostedTermsEnvironmentBindingPostgresIntegrationTest` exercises explicitly test-only authorities, not a real agreement or operative hosted service. Composed-head PostgreSQL execution, live authority provisioning, creator UI, transfer and organization workflows remain separate proof or implementation gaps. These foundations do not upgrade the broader capability ratings or authorize content writes. diff --git a/protos/account/v1/start_session_operator_authorization.proto b/protos/account/v1/start_session_operator_authorization.proto new file mode 100644 index 0000000000..7f781d5515 --- /dev/null +++ b/protos/account/v1/start_session_operator_authorization.proto @@ -0,0 +1,119 @@ +syntax = "proto3"; + +package account.v1; + +import "google/protobuf/timestamp.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Internal mTLS-only Account boundary for the human tenant-admin StartSession authorization flow. +service StartSessionOperatorAuthorizationService { + rpc IssueHumanOperatorAuthorizationReference( + IssueHumanOperatorAuthorizationReferenceRequest) + returns (IssueHumanOperatorAuthorizationReferenceResponse); + rpc RecoverOperatorAuthorizationReference(RecoverOperatorAuthorizationReferenceRequest) + returns (RecoverOperatorAuthorizationReferenceResponse); + rpc RedeemOperatorAuthorization(RedeemOperatorAuthorizationRequest) + returns (RedeemOperatorAuthorizationResponse); + rpc ReadRedeemedOperationProjection(ReadRedeemedOperationProjectionRequest) + returns (ReadRedeemedOperationProjectionResponse); +} + +message IssueHumanOperatorAuthorizationReferenceRequest { + // Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. + bytes canonical_pre_authorization_tuple_bytes = 1; + // Forwarded control-ui token. It is consumed only by Account and is never returned. + string control_ui_jwt = 2; + string reservation_owner_id = 3; + uint64 reservation_claim_fence = 4; + string current_claim_owner_id = 5; + uint64 current_claim_fence = 6; +} + +message RecoverOperatorAuthorizationReferenceRequest { + // Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. + bytes canonical_pre_authorization_tuple_bytes = 1; + string reservation_owner_id = 2; + uint64 reservation_claim_fence = 3; + string current_claim_owner_id = 4; + uint64 current_claim_fence = 5; +} + +message RedeemOperatorAuthorizationRequest { + // Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. + bytes canonical_pre_authorization_tuple_bytes = 1; + // Transient only: sent over authenticated TLS and never persisted by Logging & Admin. + string operator_authorization_reference = 2; + string authorization_reference_fingerprint = 3; + string reservation_owner_id = 4; + uint64 reservation_claim_fence = 5; + string owner_attempt_id = 6; + uint64 owner_fence = 7; +} + +message IssueHumanOperatorAuthorizationReferenceResponse { + string operator_authorization_reference = 1; + string authorization_reference_fingerprint = 2; + google.protobuf.Timestamp expires_at = 3; + bytes authority_evidence_bundle = 4; + AuthorityEvidenceBundleReference bundle_reference = 5; + // Exact Logging/Admin SPIFFE identity verified from the authenticated request TLS peer. + string authenticated_logging_workload_identity = 6; +} + +message RecoverOperatorAuthorizationReferenceResponse { + string operator_authorization_reference = 1; + string authorization_reference_fingerprint = 2; + google.protobuf.Timestamp expires_at = 3; + bytes authority_evidence_bundle = 4; + AuthorityEvidenceBundleReference bundle_reference = 5; + // Exact Logging/Admin SPIFFE identity verified from the authenticated request TLS peer. + string authenticated_logging_workload_identity = 6; +} + +message RedeemOperatorAuthorizationResponse { + string authorization_reference_fingerprint = 1; + bytes authority_evidence_bundle = 2; + string issuance_operation_id = 3; + uint64 issuance_fence = 4; + bool replay = 5; +} + +// Read-only projection of the exact original operation after its owner redemption. +// It contains no JWT or opaque authorization reference. +message ReadRedeemedOperationProjectionRequest { + // Exact canonical preAuthorizationReservationTuple/v1 JSON bytes. + bytes canonical_pre_authorization_tuple_bytes = 1; + string authorization_reference_fingerprint = 2; + string reservation_owner_id = 3; + uint64 reservation_claim_fence = 4; + string owner_attempt_id = 5; + uint64 owner_fence = 6; +} + +message ReadRedeemedOperationProjectionResponse { + string control_plane_request_id = 1; + bytes canonical_pre_authorization_tuple_bytes = 2; + string mutation_digest = 3; + string authorization_reference_fingerprint = 4; + string reservation_owner_id = 5; + uint64 reservation_claim_fence = 6; + // The original redeemer identity authenticated and recorded by Account at redemption. + string authenticated_redeemer_workload_identity = 7; + string owner_attempt_id = 8; + uint64 owner_fence = 9; + google.protobuf.Timestamp reference_expires_at = 10; + google.protobuf.Timestamp redeemed_at = 11; + string issuance_operation_id = 12; + uint64 issuance_fence = 13; + AuthorityEvidenceBundleReference bundle_reference = 14; + bytes authority_evidence_bundle = 15; +} + +message AuthorityEvidenceBundleReference { + string bundle_version = 1; + string source_version = 2; + string source_fence = 3; + string linearization = 4; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java new file mode 100644 index 0000000000..b8e1f33c0d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClient.java @@ -0,0 +1,330 @@ +package net.firedevops.firemud.common.account; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +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.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; + +/** Explicit mTLS client for Account's read-only redeemed StartSession operation projection. */ +public final class StartSessionRedeemedOperationProjectionClient + extends AbstractReloadingBlockingGrpcClient< + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private final Clock clock; + private volatile boolean initialized; + private volatile boolean closed; + + public StartSessionRedeemedOperationProjectionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + this(endpoints, tlsProperties, channelFactory, workloadNamespace, Clock.systemUTC()); + } + + StartSessionRedeemedOperationProjectionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace, + Clock clock) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + StartSessionRedeemedOperationProjectionClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("StartSession projection client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("StartSession projection client has no gRPC stub"); + } + initialized = true; + } + + /** + * Reads Account's immutable projection for the exact previously redeemed owner attempt. + * + *

This call sends no JWT or opaque authorization reference and does not retry, renew, mutate, + * or authorize owner execution. + */ + public ReadRedeemedOperationProjectionResponse read( + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple, + UUID ownerAttemptId, + long ownerFence) { + Objects.requireNonNull(postAuthorizationTuple, "post-authorization tuple is required"); + requireNonNil(ownerAttemptId, "ownerAttemptId"); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + + StartSessionPreAuthorizationReservationTuple preTuple = + postAuthorizationTuple.preAuthorizationTuple(); + String targetNamespace = preTuple.action().scope().targetNamespace(); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "StartSession projection must use the configured workload namespace"); + } + + byte[] canonicalPreTuple = preTuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + ReadRedeemedOperationProjectionRequest request = + ReadRedeemedOperationProjectionRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(canonicalPreTuple)) + .setAuthorizationReferenceFingerprint( + postAuthorizationTuple.authorizationReferenceFingerprint()) + .setReservationOwnerId(postAuthorizationTuple.reservationOwnerId().toString()) + .setReservationClaimFence(postAuthorizationTuple.reservationClaimFence()) + .setOwnerAttemptId(ownerAttemptId.toString()) + .setOwnerFence(ownerFence) + .build(); + + ReadRedeemedOperationProjectionResponse response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readRedeemedOperationProjection(request); + try { + validateResponse( + postAuthorizationTuple, ownerAttemptId, ownerFence, canonicalPreTuple, response); + return response; + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned an invalid redeemed StartSession operation projection", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "StartSession projection client is not initialized and available"); + } + return currentStub; + } + + private void validateResponse( + StartSessionPostAuthorizationExecutionTuple postTuple, + UUID ownerAttemptId, + long ownerFence, + byte[] canonicalPreTuple, + ReadRedeemedOperationProjectionResponse response) { + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasBundleReference() + || !response.hasReferenceExpiresAt() + || !response.hasRedeemedAt() + || !response.getBundleReference().getUnknownFields().asMap().isEmpty() + || !response.getReferenceExpiresAt().getUnknownFields().asMap().isEmpty() + || !response.getRedeemedAt().getUnknownFields().asMap().isEmpty()) { + throw invalid("projection response contains unknown or missing fields"); + } + + StartSessionPreAuthorizationReservationTuple preTuple = postTuple.preAuthorizationTuple(); + if (!preTuple.controlPlaneRequestId().equals(response.getControlPlaneRequestId()) + || !MessageDigest.isEqual( + canonicalPreTuple, response.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + || !preTuple.mutationDigest().equals(response.getMutationDigest()) + || !postTuple + .authorizationReferenceFingerprint() + .equals(response.getAuthorizationReferenceFingerprint()) + || !postTuple.reservationOwnerId().toString().equals(response.getReservationOwnerId()) + || postTuple.reservationClaimFence() != response.getReservationClaimFence() + || !ownerAttemptId.toString().equals(response.getOwnerAttemptId()) + || ownerFence != response.getOwnerFence()) { + throw invalid("projection differs from the exact original operation or owner attempt"); + } + if (response.getReservationClaimFence() <= 0L || response.getOwnerFence() <= 0L) { + throw invalid("projection fences must be positive"); + } + + String expectedRedeemerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + GrpcPeerIdentity redeemer = + GrpcPeerIdentity.parseUri(response.getAuthenticatedRedeemerWorkloadIdentity()) + .orElseThrow(() -> invalid("projection redeemer identity is invalid")); + if (!expectedRedeemerUri.equals(redeemer.uri()) + || !workloadNamespace.equals(redeemer.namespace()) + || !"game-session-service".equals(redeemer.service())) { + throw invalid("projection redeemer is not the exact same-namespace Game Session workload"); + } + + UUID issuanceOperationId = requireCanonicalNonNilUuid(response.getIssuanceOperationId()); + if (response.getIssuanceFence() <= 0L) { + throw invalid("projection issuance fence must be positive"); + } + + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode( + response.getAuthorityEvidenceBundle().toByteArray()); + if (!MessageDigest.isEqual(postTuple.authorityEvidenceBundleBytes(), bundle.canonicalBytes())) { + throw invalid("projection authority bundle changed from the original Account response"); + } + bundle.requireTupleBinding(preTuple); + bundle.requireReferenceBinding(postTuple.bundleReference()); + if (!issuanceOperationId.equals(bundle.issuanceOperationId()) + || !Long.toString(response.getIssuanceFence()).equals(bundle.issuanceFence())) { + throw invalid("projection issuance identity differs from the original Account bundle"); + } + + var protoReference = response.getBundleReference(); + StartSessionAuthorityEvidenceBundle.BundleReference responseReference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + protoReference.getBundleVersion(), + protoReference.getSourceVersion(), + protoReference.getSourceFence(), + protoReference.getLinearization()); + if (!postTuple.bundleReference().equals(responseReference)) { + throw invalid("projection bundle reference differs from the original Account response"); + } + + Instant referenceExpiresAt = timestamp(response.getReferenceExpiresAt(), "referenceExpiresAt"); + Instant redeemedAt = timestamp(response.getRedeemedAt(), "redeemedAt"); + Instant originalExpiresAt; + try { + originalExpiresAt = Instant.parse(bundle.authorizationExpiresAt()); + } catch (RuntimeException malformed) { + throw invalid("original Account bundle expiry is invalid"); + } + if (!referenceExpiresAt.equals(originalExpiresAt) + || !referenceExpiresAt.isAfter(redeemedAt) + || !referenceExpiresAt.isAfter(clock.instant())) { + throw invalid("projection reference is expired or differs from the original Account expiry"); + } + } + + private static Instant timestamp(Timestamp value, String field) { + if (value.getSeconds() <= 0L || value.getNanos() < 0 || value.getNanos() >= 1_000_000_000) { + throw invalid(field + " timestamp is invalid"); + } + try { + return Instant.ofEpochSecond(value.getSeconds(), value.getNanos()); + } catch (RuntimeException malformed) { + throw invalid(field + " timestamp is outside the supported range"); + } + } + + private static UUID requireCanonicalNonNilUuid(String value) { + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (RuntimeException malformed) { + throw invalid("projection issuance operation ID is invalid"); + } + if (parsed.equals(new UUID(0L, 0L)) || !parsed.toString().equals(value)) { + throw invalid("projection issuance operation ID is not canonical and non-nil"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(field + " must not be nil"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("StartSession projection 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( + "StartSession projection reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "StartSession projection reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "StartSession projection " + label + " must be a readable file-backed path", malformed); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "StartSession projection " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java new file mode 100644 index 0000000000..1da36c7cbe --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/MutationDigestV1.java @@ -0,0 +1,299 @@ +package net.firedevops.firemud.common.operator; + +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.Normalizer; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; + +/** Package-private implementation of the ADR 0047 mutationDigest/v1 byte grammar. */ +final class MutationDigestV1 { + static final int MAX_NORMALIZED_STRING_BYTES = 4_096; + static final int MAX_NUMERIC_BYTES = 128; + static final int MAX_NUMERIC_SCALE = 128; + static final int MAX_SEGMENT_BYTES = 8_192; + static final int MAX_PREIMAGE_BYTES = 32 * 1_024; + + private static final String DOMAIN = "mutationDigest/v1"; + private static final Pattern NUMBER_SOURCE = Pattern.compile("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?"); + private static final Pattern NUMBER_CANONICAL = + Pattern.compile("0|-?(?:[1-9][0-9]*(?:\\.[0-9]*[1-9])?|0\\.[0-9]*[1-9])"); + + private MutationDigestV1() {} + + static byte[] preimage(StartSessionOperatorAction action) { + Objects.requireNonNull(action, "action is required"); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(DOMAIN)); + writeField(output, "actionFamilySchemaId", string(action.actionFamilySchemaId())); + writeField(output, "actionFamilySchemaVersion", string(action.actionFamilySchemaVersion())); + writeField( + output, + "scope", + object( + List.of( + member("tenantId", string(action.scope().tenantId().toString())), + member("targetNamespace", string(action.scope().targetNamespace()))))); + writeField( + output, + "target", + object( + List.of( + member("gameTemplateId", string(Long.toString(action.target().gameTemplateId()))), + member("ownerAccountId", string(action.target().ownerAccountId().toString()))))); + writeField(output, "expectedVersion", absent()); + Value clientIp = + action.mutation().clientIp() instanceof StartSessionOperatorAction.AbsentClientIp + ? absent() + : string( + ((StartSessionOperatorAction.StringClientIp) action.mutation().clientIp()).value()); + writeField(output, "mutation", object(List.of(member("clientIp", clientIp)))); + writeField(output, "auditReason", string(action.auditReason())); + byte[] preimage = output.toByteArray(); + if (preimage.length > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + return preimage; + } + + static String sha256Hex(byte[] preimage) { + Objects.requireNonNull(preimage, "preimage is required"); + if (preimage.length > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(preimage); + StringBuilder hex = new StringBuilder(digest.length * 2); + for (byte value : digest) { + hex.append(Character.forDigit((value >>> 4) & 0x0f, 16)); + hex.append(Character.forDigit(value & 0x0f, 16)); + } + return hex.toString(); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + static Value absent() { + return new ScalarValue("absent", false, new byte[0]); + } + + static Value nullValue() { + return new ScalarValue("null", true, new byte[0]); + } + + static Value string(String value) { + String normalized = normalize(value, MAX_NORMALIZED_STRING_BYTES, "string"); + return new ScalarValue("string", true, utf8(normalized)); + } + + static Value number(String rawLexeme) { + Objects.requireNonNull(rawLexeme, "number lexeme is required"); + byte[] rawBytes = utf8(rawLexeme); + if (rawBytes.length > MAX_NUMERIC_BYTES || !NUMBER_SOURCE.matcher(rawLexeme).matches()) { + throw invalid("number lexeme is invalid or exceeds its byte limit"); + } + int decimalPoint = rawLexeme.indexOf('.'); + if (decimalPoint >= 0 && rawLexeme.length() - decimalPoint - 1 > MAX_NUMERIC_SCALE) { + throw invalid("number scale exceeds its limit"); + } + BigDecimal decimal; + try { + decimal = new BigDecimal(rawLexeme); + } catch (NumberFormatException exception) { + throw invalid("number lexeme is invalid"); + } + String canonical = decimal.signum() == 0 ? "0" : decimal.stripTrailingZeros().toPlainString(); + byte[] canonicalBytes = utf8(canonical); + if (canonicalBytes.length > MAX_NUMERIC_BYTES + || !NUMBER_CANONICAL.matcher(canonical).matches()) { + throw invalid("canonical number exceeds its byte limit"); + } + return new ScalarValue("number", true, canonicalBytes); + } + + static Value bool(boolean value) { + return new ScalarValue("boolean", true, utf8(value ? "true" : "false")); + } + + static Value object(List members) { + return new ObjectValue(members); + } + + static Value array(List values) { + return new ArrayValue(values); + } + + static Member member(String key, Value value) { + return new Member(key, value); + } + + static byte[] encodedValue(Value value) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeValue(output, value); + return output.toByteArray(); + } + + static Value normalizeObject(List rawMembers) { + Objects.requireNonNull(rawMembers, "object members are required"); + if (rawMembers.size() > 16) { + throw invalid("object exceeds its member limit"); + } + List normalizedMembers = new ArrayList<>(rawMembers.size()); + List seenKeys = new ArrayList<>(rawMembers.size()); + for (Member member : rawMembers) { + String key = normalize(member.key(), MAX_NORMALIZED_STRING_BYTES, "object key"); + if (seenKeys.contains(key)) { + throw invalid("object contains a duplicate or normalized-colliding key"); + } + seenKeys.add(key); + normalizedMembers.add(new Member(key, member.value())); + } + return new ObjectValue(normalizedMembers); + } + + private static void writeField(ByteArrayOutputStream output, String name, Value value) { + writeSegment(output, utf8(name)); + writeValue(output, value); + if (output.size() > MAX_PREIMAGE_BYTES) { + throw invalid("canonical preimage exceeds its byte limit"); + } + } + + private static void writeValue(ByteArrayOutputStream output, Value value) { + Objects.requireNonNull(value, "typed value is required"); + String type; + boolean present; + byte[] payload; + if (value instanceof ScalarValue scalar) { + type = scalar.type(); + present = scalar.present(); + payload = scalar.payload(); + } else if (value instanceof ObjectValue object) { + type = "object"; + present = true; + payload = objectPayload(object.members()); + } else if (value instanceof ArrayValue array) { + type = "array"; + present = true; + payload = arrayPayload(array.values()); + } else { + throw invalid("unsupported typed value"); + } + writeSegment(output, utf8(type)); + output.write(present ? '1' : '0'); + writeSegment(output, payload); + } + + private static byte[] objectPayload(List members) { + if (members.size() > 16) { + throw invalid("object exceeds its member limit"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(Integer.toString(members.size()))); + for (Member member : members) { + writeSegment(output, utf8(member.key())); + writeValue(output, member.value()); + } + return boundedPayload(output); + } + + private static byte[] arrayPayload(List values) { + if (values.size() > 64) { + throw invalid("array exceeds its element limit"); + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + writeSegment(output, utf8(Integer.toString(values.size()))); + for (Value value : values) { + writeValue(output, value); + } + return boundedPayload(output); + } + + private static byte[] boundedPayload(ByteArrayOutputStream output) { + if (output.size() > MAX_SEGMENT_BYTES) { + throw invalid("canonical segment exceeds its byte limit"); + } + return output.toByteArray(); + } + + private static void writeSegment(ByteArrayOutputStream output, byte[] bytes) { + if (bytes.length > MAX_SEGMENT_BYTES) { + throw invalid("canonical segment exceeds its byte limit"); + } + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static String normalize(String value, int byteLimit, String label) { + Objects.requireNonNull(value, label + " is required"); + requireUnicodeScalars(value, label); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, label); + if (utf8(normalized).length > byteLimit) { + throw invalid(label + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String label) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid(label + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw invalid(label + " contains malformed Unicode"); + } + } + } + + private static byte[] utf8(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + sealed interface Value permits ScalarValue, ObjectValue, ArrayValue {} + + record ScalarValue(String type, boolean present, byte[] payload) implements Value { + ScalarValue { + Objects.requireNonNull(type); + payload = payload.clone(); + } + + @Override + public byte[] payload() { + return payload.clone(); + } + } + + record Member(String key, Value value) { + Member { + Objects.requireNonNull(key); + Objects.requireNonNull(value); + } + } + + record ObjectValue(List members) implements Value { + ObjectValue { + members = List.copyOf(members); + } + } + + record ArrayValue(List values) implements Value { + ArrayValue { + values = List.copyOf(values); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java new file mode 100644 index 0000000000..28d9252ee3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java @@ -0,0 +1,642 @@ +package net.firedevops.firemud.common.operator; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Integrity-only decoder for the closed StartSession human tenant-admin {@code + * authorityEvidenceBundle/v1} contract. + * + *

This value proves only that supplied bytes are canonical and structurally bound to a typed + * StartSession tuple and the separate Account source reference. It does not establish current + * Account authority, source freshness, a live reservation claim, or permission to dispatch. + */ +public final class StartSessionAuthorityEvidenceBundle { + public static final String BUNDLE_VERSION = "authorityEvidenceBundle/v1"; + public static final String HUMAN_EVIDENCE_TYPE = "HumanAuthorityEvidence/v1"; + public static final int MAX_BUNDLE_BYTES = 128 * 1024; + + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern SOURCE_EVIDENCE_ID = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern POSITIVE_U64 = Pattern.compile("[1-9][0-9]{0,19}"); + private static final BigInteger MAX_UNSIGNED_LONG = + BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Set ROOT_FIELDS = + Set.of( + "bundleVersion", + "authorityScope", + "accountProjectionEvidence", + "issuanceOperationIdentity", + "issuanceKind", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "issuanceEvidence"); + private static final Set AUTHORITY_SCOPE_FIELDS = + Set.of("scope", "actionFamily", "applicableAccountId", "applicableTenantId"); + private static final Set SCOPE_FIELDS = Set.of("tenantId", "targetNamespace"); + private static final Set PROJECTION_FIELDS = + Set.of( + "sourceType", + "sourceEvidenceId", + "sourceEvidenceVersion", + "projectionStatus", + "evaluatedAt", + "expiresAt"); + private static final Set OPERATION_FIELDS = + Set.of( + "issuanceOperationId", + "controlPlaneRequestId", + "actionFamilyRequestIdentity", + "mutationDigest"); + private static final Set REQUEST_IDENTITY_FIELDS = + Set.of("requestIdentityKind", "requestId"); + private static final Set HUMAN_TENANT_FIELDS = + Set.of( + "evidenceType", + "actorAccountId", + "controlUiTokenJti", + "role", + "accountGeneration", + "tenantGeneration"); + private static final Set REQUIRED_AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set ALLOWED_AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions", + "accountSecurityCutoff", + "tenantBillingCutoff"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final byte[] canonicalBytes; + private final Map value; + + private StartSessionAuthorityEvidenceBundle(byte[] canonicalBytes, Map value) { + this.canonicalBytes = canonicalBytes.clone(); + this.value = immutableObject(value); + } + + /** Strictly decodes one canonical, closed, bounded StartSession tenant-admin bundle. */ + public static StartSessionAuthorityEvidenceBundle decode(byte[] exactCanonicalBytes) { + if (exactCanonicalBytes == null + || exactCanonicalBytes.length == 0 + || exactCanonicalBytes.length > MAX_BUNDLE_BYTES) { + throw denied("Authority evidence bundle is empty or over the supported bound"); + } + try { + String json = strictUtf8(exactCanonicalBytes); + Map decoded = JSON.readValue(json, new TypeReference<>() {}); + requireFields(decoded, ROOT_FIELDS, "authorityEvidenceBundle/v1"); + if (!BUNDLE_VERSION.equals(string(decoded.get("bundleVersion"), "bundleVersion"))) { + throw denied("Unsupported authority evidence bundle version"); + } + validateAuthorityScope(object(decoded.get("authorityScope"), "authorityScope")); + validateProjection( + object(decoded.get("accountProjectionEvidence"), "accountProjectionEvidence")); + validateOperationIdentity( + object(decoded.get("issuanceOperationIdentity"), "issuanceOperationIdentity")); + if (!"human_operator".equals(string(decoded.get("issuanceKind"), "issuanceKind"))) { + throw denied("Only the human StartSession operator branch is supported"); + } + validateAuthorityTuple(object(decoded.get("authorityTuple"), "authorityTuple")); + validateMembershipVersion(object(decoded.get("membershipVersion"), "membershipVersion")); + positiveDecimal(string(decoded.get("issuanceFence"), "issuanceFence"), "issuanceFence"); + validateTenantHumanEvidence(object(decoded.get("issuanceEvidence"), "issuanceEvidence")); + + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!MessageDigest.isEqual(canonical, exactCanonicalBytes)) { + throw denied("Authority evidence bundle is not canonical UTF-8 JSON"); + } + return new StartSessionAuthorityEvidenceBundle(canonical, decoded); + } catch (IllegalArgumentException expected) { + throw expected; + } catch (IOException | RuntimeException malformed) { + throw denied("Authority evidence bundle is malformed"); + } + } + + /** Compares every tuple-bound identity and digest without granting authority or freshness. */ + public void requireTupleBinding(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + Map authorityScope = object(value.get("authorityScope"), "authorityScope"); + Map scope = object(authorityScope.get("scope"), "authorityScope.scope"); + Map operation = + object(value.get("issuanceOperationIdentity"), "issuanceOperationIdentity"); + Map identity = + object(operation.get("actionFamilyRequestIdentity"), "actionFamilyRequestIdentity"); + Map human = object(value.get("issuanceEvidence"), "issuanceEvidence"); + String tenantId = tuple.action().scope().tenantId().toString(); + String actorId = tuple.actor().accountId().toString(); + Map authorityTuple = object(value.get("authorityTuple"), "authorityTuple"); + Map tenantGenerations = + object(authorityTuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + Map membershipGenerations = + object( + authorityTuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + Map membershipVersion = + object(value.get("membershipVersion"), "membershipVersion"); + long accountGeneration = + positiveNumber( + authorityTuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + if (!tuple.actionFamily().equals(authorityScope.get("actionFamily")) + || !actorId.equals(authorityScope.get("applicableAccountId")) + || !tenantId.equals(authorityScope.get("applicableTenantId")) + || !tenantId.equals(scope.get("tenantId")) + || !tuple.action().scope().targetNamespace().equals(scope.get("targetNamespace")) + || !tuple.controlPlaneRequestId().equals(operation.get("controlPlaneRequestId")) + || !tuple.controlPlaneRequestId().equals(identity.get("requestId")) + || !"controlPlaneRequestId".equals(identity.get("requestIdentityKind")) + || !tuple.mutationDigest().equals(operation.get("mutationDigest")) + || !actorId.equals(human.get("actorAccountId")) + || !tenantGenerations.keySet().equals(Set.of(tenantId)) + || !membershipGenerations.keySet().equals(Set.of(tenantId)) + || !membershipVersion.keySet().equals(Set.of(tenantId)) + || accountGeneration + != parsePositiveDecimal( + string(human.get("accountGeneration"), "accountGeneration"), "accountGeneration") + || positiveNumber(tenantGenerations.get(tenantId), "tenantAuthorityGeneration") + != parsePositiveDecimal( + string(human.get("tenantGeneration"), "tenantGeneration"), "tenantGeneration")) { + throw denied("Authority evidence differs from the exact StartSession tuple"); + } + if (authorityTuple.containsKey("tenantBillingCutoff")) { + Map billingCutoffs = + object(authorityTuple.get("tenantBillingCutoff"), "tenantBillingCutoff"); + if (!billingCutoffs.isEmpty() && !billingCutoffs.keySet().equals(Set.of(tenantId))) { + throw denied("Tenant billing cutoff differs from the exact StartSession tenant"); + } + } + } + + /** Binds the separate Account source reference; this does not prove source freshness. */ + public void requireReferenceBinding(BundleReference reference) { + Objects.requireNonNull(reference, "Account bundle reference is required"); + Map projection = + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); + if (!BUNDLE_VERSION.equals(reference.bundleVersion()) + || !reference.sourceVersion().equals(projection.get("sourceEvidenceVersion")) + || !reference.sourceFence().equals(value.get("issuanceFence"))) { + throw denied("Account bundle reference differs from immutable authority evidence"); + } + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String bundleVersion() { + return BUNDLE_VERSION; + } + + public String actionFamily() { + return string( + object(value.get("authorityScope"), "authorityScope").get("actionFamily"), "actionFamily"); + } + + public UUID actorAccountId() { + return uuid( + object(value.get("authorityScope"), "authorityScope").get("applicableAccountId"), + "applicableAccountId"); + } + + public UUID tenantId() { + Map authorityScope = object(value.get("authorityScope"), "authorityScope"); + return uuid(object(authorityScope.get("scope"), "scope").get("tenantId"), "tenantId"); + } + + public String targetNamespace() { + Map authorityScope = object(value.get("authorityScope"), "authorityScope"); + return string( + object(authorityScope.get("scope"), "scope").get("targetNamespace"), "targetNamespace"); + } + + public String controlPlaneRequestId() { + return string( + object(value.get("issuanceOperationIdentity"), "issuanceOperationIdentity") + .get("controlPlaneRequestId"), + "controlPlaneRequestId"); + } + + public String mutationDigest() { + return string( + object(value.get("issuanceOperationIdentity"), "issuanceOperationIdentity") + .get("mutationDigest"), + "mutationDigest"); + } + + public UUID issuanceOperationId() { + return uuid( + object(value.get("issuanceOperationIdentity"), "issuanceOperationIdentity") + .get("issuanceOperationId"), + "issuanceOperationId"); + } + + public String sourceEvidenceId() { + return string( + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence") + .get("sourceEvidenceId"), + "sourceEvidenceId"); + } + + public String sourceEvidenceVersion() { + return string( + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence") + .get("sourceEvidenceVersion"), + "sourceEvidenceVersion"); + } + + public Instant evaluatedAt() { + return instant( + string( + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence") + .get("evaluatedAt"), + "evaluatedAt")); + } + + public Instant expiresAt() { + return instant( + string( + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence") + .get("expiresAt"), + "expiresAt")); + } + + public String issuanceFence() { + return string(value.get("issuanceFence"), "issuanceFence"); + } + + public String evidenceType() { + return string( + object(value.get("issuanceEvidence"), "issuanceEvidence").get("evidenceType"), + "evidenceType"); + } + + public String role() { + return string(object(value.get("issuanceEvidence"), "issuanceEvidence").get("role"), "role"); + } + + public UUID controlUiTokenJti() { + return uuid( + object(value.get("issuanceEvidence"), "issuanceEvidence").get("controlUiTokenJti"), + "controlUiTokenJti"); + } + + public String authorizationExpiresAt() { + return string( + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence") + .get("expiresAt"), + "expiresAt"); + } + + /** Returns the deeply immutable decoded JSON value for Account's exact current-source checks. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "The constructor recursively freezes nested maps and lists; " + + "JSON scalar leaves are immutable.") + public Map jsonValue() { + return value; + } + + public Map authorityTuple() { + return object(value.get("authorityTuple"), "authorityTuple"); + } + + public Map membershipVersion() { + return object(value.get("membershipVersion"), "membershipVersion"); + } + + private static void validateAuthorityScope(Map scopeValue) { + requireFields(scopeValue, AUTHORITY_SCOPE_FIELDS, "authorityScope"); + Map scope = object(scopeValue.get("scope"), "authorityScope.scope"); + requireFields(scope, SCOPE_FIELDS, "StartSession scope"); + uuid(scope.get("tenantId"), "scope.tenantId"); + if (!GrpcPeerIdentity.isValidNamespace( + string(scope.get("targetNamespace"), "targetNamespace"))) { + throw denied("StartSession target namespace is invalid"); + } + if (!"StartSession".equals(string(scopeValue.get("actionFamily"), "actionFamily"))) { + throw denied("Unsupported StartSession action family"); + } + uuid(scopeValue.get("applicableAccountId"), "applicableAccountId"); + uuid(scopeValue.get("applicableTenantId"), "applicableTenantId"); + if (!scope.get("tenantId").equals(scopeValue.get("applicableTenantId"))) { + throw denied("Tenant scope and applicable tenant must match"); + } + } + + private static void validateProjection(Map projection) { + requireFields(projection, PROJECTION_FIELDS, "accountProjectionEvidence"); + if (!"ACCOUNT".equals(string(projection.get("sourceType"), "sourceType")) + || !"CURRENT".equals(string(projection.get("projectionStatus"), "projectionStatus")) + || !SOURCE_EVIDENCE_ID + .matcher(string(projection.get("sourceEvidenceId"), "sourceEvidenceId")) + .matches()) { + throw denied("Current Account projection evidence is required"); + } + positiveDecimal( + string(projection.get("sourceEvidenceVersion"), "sourceEvidenceVersion"), + "sourceEvidenceVersion"); + Instant evaluatedAt = instant(string(projection.get("evaluatedAt"), "evaluatedAt")); + Instant expiresAt = instant(string(projection.get("expiresAt"), "expiresAt")); + if (!expiresAt.isAfter(evaluatedAt)) { + throw denied("Account projection evidence expiry must follow its evaluation"); + } + } + + private static void validateOperationIdentity(Map operation) { + requireFields(operation, OPERATION_FIELDS, "issuanceOperationIdentity"); + uuid(operation.get("issuanceOperationId"), "issuanceOperationId"); + String requestId = + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + string(operation.get("controlPlaneRequestId"), "controlPlaneRequestId")); + Map identity = + object(operation.get("actionFamilyRequestIdentity"), "actionFamilyRequestIdentity"); + requireFields(identity, REQUEST_IDENTITY_FIELDS, "actionFamilyRequestIdentity"); + if (!"controlPlaneRequestId".equals(identity.get("requestIdentityKind")) + || !requestId.equals(identity.get("requestId")) + || !DIGEST.matcher(string(operation.get("mutationDigest"), "mutationDigest")).matches()) { + throw denied("StartSession operation identity or digest is invalid"); + } + } + + private static void validateAuthorityTuple(Map authority) { + if (!authority.keySet().containsAll(REQUIRED_AUTHORITY_TUPLE_FIELDS) + || !ALLOWED_AUTHORITY_TUPLE_FIELDS.containsAll(authority.keySet())) { + throw denied("Authority tuple has missing or unsupported fields"); + } + positiveNumber(authority.get("issuerAuthGeneration"), "issuerAuthGeneration"); + positiveNumber(authority.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + mapOfPositiveNumbers(authority.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + mapOfPositiveNumbers( + authority.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + if (!(authority.get("privateRealmGrantVersions") instanceof List grants) + || !grants.isEmpty()) { + throw denied("StartSession control-plane authority must not acquire gameplay grants"); + } + if (authority.containsKey("accountSecurityCutoff")) { + validateAccountSecurityCutoff( + object(authority.get("accountSecurityCutoff"), "accountSecurityCutoff")); + } + if (authority.containsKey("tenantBillingCutoff")) { + validateTenantBillingCutoffs( + object(authority.get("tenantBillingCutoff"), "tenantBillingCutoff")); + } + } + + private static void validateAccountSecurityCutoff(Map cutoff) { + requireFields( + cutoff, + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"), + "accountSecurityCutoff"); + positiveNumber(cutoff.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + boundedText(cutoff.get("outboxStreamKey"), "outboxStreamKey", 256); + positiveNumber(cutoff.get("outboxSequence"), "outboxSequence"); + } + + private static void validateTenantBillingCutoffs(Map cutoffs) { + if (cutoffs.size() > 1) { + throw denied("StartSession bundle must not widen tenant billing scope"); + } + cutoffs.forEach( + (tenantId, raw) -> { + uuid(tenantId, "tenantBillingCutoff tenant ID"); + Map cutoff = object(raw, "tenantBillingCutoff entry"); + requireFields( + cutoff, + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence"), + "tenantBillingCutoff entry"); + positiveNumber(cutoff.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + positiveNumber(cutoff.get("tenantBillingSequence"), "tenantBillingSequence"); + boundedText(cutoff.get("outboxStreamKey"), "outboxStreamKey", 256); + positiveNumber(cutoff.get("outboxSequence"), "outboxSequence"); + }); + } + + private static void validateMembershipVersion(Map membership) { + if (membership.size() > 1) { + throw denied("StartSession bundle must not widen membership scope"); + } + membership.forEach( + (tenantId, version) -> { + uuid(tenantId, "membershipVersion tenant ID"); + positiveNumber(version, "membershipVersion"); + }); + } + + private static void validateTenantHumanEvidence(Map evidence) { + requireFields(evidence, HUMAN_TENANT_FIELDS, "HumanAuthorityEvidence/v1 tenant branch"); + if (!HUMAN_EVIDENCE_TYPE.equals(string(evidence.get("evidenceType"), "evidenceType")) + || !"tenantAdmin".equals(string(evidence.get("role"), "role"))) { + throw denied("Only the current tenantAdmin HumanAuthorityEvidence/v1 arm applies"); + } + uuid(evidence.get("actorAccountId"), "actorAccountId"); + uuid(evidence.get("controlUiTokenJti"), "controlUiTokenJti"); + positiveDecimal( + string(evidence.get("accountGeneration"), "accountGeneration"), "accountGeneration"); + positiveDecimal( + string(evidence.get("tenantGeneration"), "tenantGeneration"), "tenantGeneration"); + } + + private static Instant instant(String value) { + try { + Instant parsed = Instant.parse(value); + if (!parsed.toString().equals(value) || parsed.getNano() % 1_000_000 != 0) { + throw denied("Timestamp is not canonical exact-millisecond UTC text"); + } + return parsed; + } catch (RuntimeException malformed) { + throw denied("Timestamp is malformed"); + } + } + + private static void mapOfPositiveNumbers(Object raw, String field) { + Map values = object(raw, field); + if (values.size() > 1) { + throw denied(field + " must be limited to the selected tenant"); + } + values.forEach( + (key, value) -> { + uuid(key, field + " tenant ID"); + positiveNumber(value, field); + }); + } + + private static long positiveNumber(Object value, String field) { + try { + long parsed = value instanceof Number number ? Long.parseLong(number.toString()) : 0L; + if (parsed <= 0L) { + throw new NumberFormatException(); + } + return parsed; + } catch (RuntimeException malformed) { + throw denied(field + " must be a positive signed 64-bit integer"); + } + } + + private static void positiveDecimal(String value, String field) { + parsePositiveDecimal(value, field); + } + + private static long parsePositiveDecimal(String value, String field) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw denied(field + " must be a positive canonical signed 64-bit decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException malformed) { + throw denied(field + " is outside the supported signed 64-bit range"); + } + } + + private static void positiveU64(String value, String field) { + if (value == null || !POSITIVE_U64.matcher(value).matches()) { + throw denied(field + " must be a positive canonical unsigned 64-bit decimal"); + } + try { + if (new BigInteger(value).compareTo(MAX_UNSIGNED_LONG) > 0) { + throw new NumberFormatException(); + } + } catch (NumberFormatException malformed) { + throw denied(field + " is outside the supported unsigned 64-bit range"); + } + } + + private static UUID uuid(Object value, String field) { + String text = string(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || !CANONICAL_UUID.matcher(text).matches() + || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(); + } + return parsed; + } catch (RuntimeException malformed) { + throw denied(field + " must be a canonical lowercase non-nil UUID"); + } + } + + private static void boundedText(Object value, String field, int maxUtf8Bytes) { + String text = string(value, field); + if (text.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes) { + throw denied(field + " exceeds its supported bound"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw denied("Authority evidence bundle is not valid UTF-8"); + } + } + + @SuppressWarnings("unchecked") + private static Map object(Object value, String field) { + if (!(value instanceof Map map) + || map.keySet().stream().anyMatch(key -> !(key instanceof String))) { + throw denied(field + " must be an object"); + } + return (Map) map; + } + + private static void requireFields(Map value, Set fields, String field) { + if (value == null || !value.keySet().equals(fields)) { + throw denied(field + " has missing or unsupported fields"); + } + } + + private static String string(Object value, String field) { + if (!(value instanceof String text) || text.isEmpty()) { + throw denied(field + " must be a nonempty string"); + } + return text; + } + + private static Map immutableObject(Map source) { + Map copy = new LinkedHashMap<>(); + source.forEach((key, value) -> copy.put(key, immutableValue(value))); + return Map.copyOf(copy); + } + + private static Object immutableValue(Object value) { + if (value instanceof Map map) { + Map copy = new LinkedHashMap<>(); + map.forEach( + (key, nested) -> { + if (!(key instanceof String text)) { + throw denied("Object keys must be strings"); + } + copy.put(text, immutableValue(nested)); + }); + return Map.copyOf(copy); + } + if (value instanceof List list) { + return list.stream().map(StartSessionAuthorityEvidenceBundle::immutableValue).toList(); + } + return value; + } + + private static IllegalArgumentException denied(String message) { + return new IllegalArgumentException(message); + } + + /** Separate source provenance returned beside the original bundle bytes. */ + public record BundleReference( + String bundleVersion, String sourceVersion, String sourceFence, String linearization) { + public BundleReference { + if (!BUNDLE_VERSION.equals(bundleVersion)) { + throw denied("Unsupported Account bundle-reference version"); + } + positiveDecimal(sourceVersion, "bundle sourceVersion"); + positiveDecimal(sourceFence, "bundle sourceFence"); + positiveU64(linearization, "bundle linearization"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java new file mode 100644 index 0000000000..59a09e72da --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorAction.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.common.operator; + +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Immutable typed action covered by the StartSession operator schema. */ +public record StartSessionOperatorAction( + String actionFamilySchemaId, + String actionFamilySchemaVersion, + Scope scope, + Target target, + ExpectedVersion expectedVersion, + Mutation mutation, + String auditReason) { + + public static final String ACTION_FAMILY_SCHEMA_ID = "firemud.game-session.start-session"; + public static final String ACTION_FAMILY_SCHEMA_VERSION = "1"; + public static final String ACTION_FAMILY = "StartSession"; + public static final String OWNER_SERVICE = "game-session-service"; + + private static final Pattern WORKLOAD_NAMESPACE = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public StartSessionOperatorAction { + if (!ACTION_FAMILY_SCHEMA_ID.equals(actionFamilySchemaId)) { + throw new IllegalArgumentException("unsupported actionFamilySchemaId"); + } + if (!ACTION_FAMILY_SCHEMA_VERSION.equals(actionFamilySchemaVersion)) { + throw new IllegalArgumentException("unsupported actionFamilySchemaVersion"); + } + Objects.requireNonNull(scope, "scope is required"); + Objects.requireNonNull(target, "target is required"); + Objects.requireNonNull(expectedVersion, "expectedVersion is required"); + if (expectedVersion != ExpectedVersion.ABSENT) { + throw new IllegalArgumentException( + "expectedVersion must be absent for StartSession creation"); + } + Objects.requireNonNull(mutation, "mutation is required"); + auditReason = normalizedString(auditReason, "auditReason", 1_000); + if (isUnicodeBlank(auditReason)) { + throw new IllegalArgumentException("auditReason must not be blank"); + } + } + + public enum ExpectedVersion { + ABSENT + } + + public String actionFamily() { + return ACTION_FAMILY; + } + + /** Returns the immutable ADR 0048 target owner, which is compared outside the digest tuple. */ + public String targetOwner() { + return OWNER_SERVICE; + } + + public record Scope(UUID tenantId, String targetNamespace) { + public Scope { + Objects.requireNonNull(tenantId, "tenantId is required"); + if (NIL_UUID.equals(tenantId)) { + throw new IllegalArgumentException("tenantId must not be nil"); + } + Objects.requireNonNull(targetNamespace, "targetNamespace is required"); + if (targetNamespace.length() > 63 || !WORKLOAD_NAMESPACE.matcher(targetNamespace).matches()) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + } + } + + public record Target(long gameTemplateId, UUID ownerAccountId) { + public Target { + if (gameTemplateId <= 0) { + throw new IllegalArgumentException("gameTemplateId must be positive"); + } + Objects.requireNonNull(ownerAccountId, "ownerAccountId is required"); + if (NIL_UUID.equals(ownerAccountId)) { + throw new IllegalArgumentException("ownerAccountId must not be nil"); + } + } + } + + public record Mutation(ClientIp clientIp) { + public Mutation { + Objects.requireNonNull(clientIp, "clientIp presence is required"); + } + } + + /** The action schema accepts either an absent clientIp member or a string value. */ + public sealed interface ClientIp permits AbsentClientIp, StringClientIp { + static ClientIp absent() { + return new AbsentClientIp(); + } + + static ClientIp of(String value) { + return new StringClientIp(value); + } + } + + public record AbsentClientIp() implements ClientIp {} + + public record StringClientIp(String value) implements ClientIp { + public StringClientIp { + value = normalizedString(value, "clientIp", 128); + } + } + + private static String normalizedString(String value, String fieldName, int byteLimit) { + Objects.requireNonNull(value, fieldName + " is required"); + requireUnicodeScalars(value, fieldName); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, fieldName); + if (normalized.getBytes(StandardCharsets.UTF_8).length > byteLimit) { + throw new IllegalArgumentException(fieldName + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String fieldName) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + } + } + + private static boolean isUnicodeBlank(String value) { + return value + .codePoints() + .allMatch( + codePoint -> Character.isWhitespace(codePoint) || Character.isSpaceChar(codePoint)); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java new file mode 100644 index 0000000000..ed4552f151 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodec.java @@ -0,0 +1,605 @@ +package net.firedevops.firemud.common.operator; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Strict token-preserving JSON codec and digest entry point for StartSession operator actions. */ +public final class StartSessionOperatorActionCodec { + public static final int MAX_RAW_BYTES = 16 * 1_024; + public static final int MAX_NESTING_DEPTH = 8; + public static final int MAX_OBJECT_MEMBERS = 16; + public static final int MAX_ARRAY_ELEMENTS = 64; + public static final int MAX_NORMALIZED_STRING_BYTES = + MutationDigestV1.MAX_NORMALIZED_STRING_BYTES; + public static final int MAX_NUMERIC_BYTES = MutationDigestV1.MAX_NUMERIC_BYTES; + public static final int MAX_NUMERIC_SCALE = MutationDigestV1.MAX_NUMERIC_SCALE; + public static final int MAX_SEGMENT_BYTES = MutationDigestV1.MAX_SEGMENT_BYTES; + public static final int MAX_PREIMAGE_BYTES = MutationDigestV1.MAX_PREIMAGE_BYTES; + + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final List TOP_LEVEL_FIELDS = + List.of( + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "expectedVersion", + "mutation", + "auditReason"); + + private StartSessionOperatorActionCodec() {} + + /** Decodes only the declared StartSession schema and rejects every unsupported shape. */ + public static StartSessionOperatorAction decode(byte[] rawJson) { + JsonValue root = new StrictJsonParser(rawJson).parseDocument(); + if (!(root instanceof JsonObject object)) { + throw invalid("StartSession action must be a JSON object"); + } + Map members = + orderedMembers(object, TOP_LEVEL_FIELDS, Set.of("expectedVersion")); + String schemaId = requiredString(members.get("actionFamilySchemaId"), "actionFamilySchemaId"); + String schemaVersion = + requiredString(members.get("actionFamilySchemaVersion"), "actionFamilySchemaVersion"); + if (!StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID.equals(schemaId) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION.equals(schemaVersion)) { + throw invalid("unsupported StartSession action-family schema pair"); + } + if (members.containsKey("expectedVersion")) { + throw invalid("expectedVersion must be absent for StartSession creation"); + } + StartSessionOperatorAction.Scope scope = readScope(members.get("scope")); + StartSessionOperatorAction.Target target = readTarget(members.get("target")); + StartSessionOperatorAction.Mutation mutation = readMutation(members.get("mutation")); + String auditReason = requiredString(members.get("auditReason"), "auditReason"); + return new StartSessionOperatorAction( + schemaId, + schemaVersion, + scope, + target, + StartSessionOperatorAction.ExpectedVersion.ABSENT, + mutation, + auditReason); + } + + /** Returns the exact ADR 0047 mutationDigest/v1 preimage for one typed action. */ + public static byte[] canonicalPreimage(StartSessionOperatorAction action) { + return MutationDigestV1.preimage(Objects.requireNonNull(action, "action is required")); + } + + /** Decodes an action and returns its exact ADR 0047 mutationDigest/v1 preimage. */ + public static byte[] canonicalPreimage(byte[] rawJson) { + return canonicalPreimage(decode(rawJson)); + } + + /** Returns the lowercase hexadecimal SHA-256 digest for one typed action. */ + public static String mutationDigest(StartSessionOperatorAction action) { + return MutationDigestV1.sha256Hex(canonicalPreimage(action)); + } + + /** Decodes an action and returns its lowercase hexadecimal SHA-256 digest. */ + public static String mutationDigest(byte[] rawJson) { + return mutationDigest(decode(rawJson)); + } + + /* Test bridge for the recursive value grammar. It is not an action-schema decoder. */ + static byte[] canonicalGrammarValueForTest(byte[] rawJson) { + JsonValue parsed = new StrictJsonParser(rawJson).parseDocument(); + return MutationDigestV1.encodedValue(toGrammarValue(parsed)); + } + + static byte[] absentGrammarValueForTest() { + return MutationDigestV1.encodedValue(MutationDigestV1.absent()); + } + + static byte[] canonicalNumberLexemeForTest(String rawLexeme) { + return MutationDigestV1.encodedValue(MutationDigestV1.number(rawLexeme)); + } + + private static StartSessionOperatorAction.Scope readScope(JsonValue value) { + JsonObject object = requireObject(value, "scope"); + Map members = + orderedMembers(object, List.of("tenantId", "targetNamespace"), Set.of()); + UUID tenantId = canonicalUuid(requiredString(members.get("tenantId"), "tenantId"), "tenantId"); + String namespace = requiredString(members.get("targetNamespace"), "targetNamespace"); + return new StartSessionOperatorAction.Scope(tenantId, namespace); + } + + private static StartSessionOperatorAction.Target readTarget(JsonValue value) { + JsonObject object = requireObject(value, "target"); + Map members = + orderedMembers(object, List.of("gameTemplateId", "ownerAccountId"), Set.of()); + JsonValue templateValue = members.get("gameTemplateId"); + if (!(templateValue instanceof JsonString templateIdValue)) { + throw invalid("gameTemplateId must be a positive canonical decimal string"); + } + String templateIdText = + normalizeString(templateIdValue.value(), MAX_NORMALIZED_STRING_BYTES, "gameTemplateId"); + if (!templateIdText.matches("[1-9][0-9]*")) { + throw invalid("gameTemplateId must be a positive canonical decimal string"); + } + long gameTemplateId; + try { + gameTemplateId = Long.parseLong(templateIdText); + } catch (NumberFormatException exception) { + throw invalid("gameTemplateId exceeds the current owner long range"); + } + UUID ownerAccountId = + canonicalUuid( + requiredString(members.get("ownerAccountId"), "ownerAccountId"), "ownerAccountId"); + return new StartSessionOperatorAction.Target(gameTemplateId, ownerAccountId); + } + + private static StartSessionOperatorAction.Mutation readMutation(JsonValue value) { + JsonObject object = requireObject(value, "mutation"); + Map members = + orderedMembers(object, List.of("clientIp"), Set.of("clientIp")); + JsonValue clientIp = members.get("clientIp"); + if (clientIp == null) { + return new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()); + } + if (clientIp instanceof JsonNull) { + throw invalid("clientIp may be absent or a string, but not null"); + } + if (!(clientIp instanceof JsonString string)) { + throw invalid("clientIp must be a string"); + } + String normalized = normalizeString(string.value(), 128, "clientIp"); + return new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.of(normalized)); + } + + private static String requiredString(JsonValue value, String fieldName) { + if (!(value instanceof JsonString string)) { + throw invalid(fieldName + " must be a string"); + } + return normalizeString(string.value(), MAX_NORMALIZED_STRING_BYTES, fieldName); + } + + private static UUID canonicalUuid(String value, String fieldName) { + if (!UUID_PATTERN.matcher(value).matches()) { + throw invalid(fieldName + " must be a canonical lowercase UUID"); + } + UUID uuid; + try { + uuid = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw invalid(fieldName + " must be a canonical lowercase UUID"); + } + if (uuid.getMostSignificantBits() == 0L && uuid.getLeastSignificantBits() == 0L) { + throw invalid(fieldName + " must not be nil"); + } + return uuid; + } + + private static JsonObject requireObject(JsonValue value, String fieldName) { + if (!(value instanceof JsonObject object)) { + throw invalid(fieldName + " must be an object"); + } + return object; + } + + private static Map orderedMembers( + JsonObject object, List declaredOrder, Set optionalMembers) { + if (object.members().size() > MAX_OBJECT_MEMBERS) { + throw invalid("object exceeds its member limit"); + } + Map normalizedMembers = new LinkedHashMap<>(); + for (JsonMember member : object.members()) { + String key = normalizeString(member.key().value(), MAX_NORMALIZED_STRING_BYTES, "object key"); + if (normalizedMembers.putIfAbsent(key, member.value()) != null) { + throw invalid("object contains a duplicate or normalized-colliding member"); + } + if (!declaredOrder.contains(key)) { + throw invalid("object contains an unknown member"); + } + } + List expectedOrder = + declaredOrder.stream() + .filter(key -> normalizedMembers.containsKey(key) || !optionalMembers.contains(key)) + .toList(); + if (!new ArrayList<>(normalizedMembers.keySet()).equals(expectedOrder)) { + throw invalid("object members are missing or out of declared order"); + } + return normalizedMembers; + } + + private static MutationDigestV1.Value toGrammarValue(JsonValue value) { + if (value instanceof JsonString string) { + return MutationDigestV1.string(string.value()); + } + if (value instanceof JsonNumber number) { + return MutationDigestV1.number(number.lexeme()); + } + if (value instanceof JsonBoolean bool) { + return MutationDigestV1.bool(bool.value()); + } + if (value instanceof JsonNull) { + return MutationDigestV1.nullValue(); + } + if (value instanceof JsonArray array) { + return MutationDigestV1.array( + array.values().stream().map(StartSessionOperatorActionCodec::toGrammarValue).toList()); + } + if (value instanceof JsonObject object) { + List members = new ArrayList<>(object.members().size()); + for (JsonMember member : object.members()) { + String key = + normalizeString(member.key().value(), MAX_NORMALIZED_STRING_BYTES, "object key"); + members.add(MutationDigestV1.member(key, toGrammarValue(member.value()))); + } + return MutationDigestV1.normalizeObject(members); + } + throw invalid("unsupported JSON value"); + } + + private static String normalizeString(String value, int maxUtf8Bytes, String fieldName) { + requireUnicodeScalars(value, fieldName); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + requireUnicodeScalars(normalized, fieldName); + if (normalized.getBytes(StandardCharsets.UTF_8).length > maxUtf8Bytes) { + throw invalid(fieldName + " exceeds its normalized UTF-8 byte limit"); + } + return normalized; + } + + private static void requireUnicodeScalars(String value, String fieldName) { + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw invalid(fieldName + " contains malformed Unicode"); + } + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private sealed interface JsonValue + permits JsonString, JsonNumber, JsonBoolean, JsonNull, JsonObject, JsonArray { + byte[] rawToken(); + } + + private record JsonString(String value, byte[] rawToken) implements JsonValue { + private JsonString { + rawToken = rawToken.clone(); + } + } + + private record JsonNumber(String lexeme, byte[] rawToken) implements JsonValue { + private JsonNumber { + rawToken = rawToken.clone(); + } + } + + private record JsonBoolean(boolean value, byte[] rawToken) implements JsonValue { + private JsonBoolean { + rawToken = rawToken.clone(); + } + } + + private record JsonNull(byte[] rawToken) implements JsonValue { + private JsonNull { + rawToken = rawToken.clone(); + } + } + + private record JsonMember(JsonString key, JsonValue value) {} + + private record JsonObject(List members, byte[] rawToken) implements JsonValue { + private JsonObject { + members = List.copyOf(members); + rawToken = rawToken.clone(); + } + } + + private record JsonArray(List values, byte[] rawToken) implements JsonValue { + private JsonArray { + values = List.copyOf(values); + rawToken = rawToken.clone(); + } + } + + /** Small bounded parser that retains source tokens and object occurrence order. */ + private static final class StrictJsonParser { + private final byte[] input; + private final String source; + private final int[] byteOffsets; + private int position; + + private StrictJsonParser(byte[] input) { + Objects.requireNonNull(input, "raw JSON is required"); + if (input.length > MAX_RAW_BYTES) { + throw invalid("raw JSON exceeds its byte limit"); + } + this.input = input.clone(); + try { + CharBuffer decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(this.input)); + this.source = decoded.toString(); + } catch (CharacterCodingException exception) { + throw invalid("raw JSON is not valid UTF-8"); + } + this.byteOffsets = computeByteOffsets(this.source, this.input.length); + } + + private JsonValue parseDocument() { + skipWhitespace(); + JsonValue value = parseValue(0); + skipWhitespace(); + if (position != source.length()) { + throw invalid("raw JSON contains trailing tokens"); + } + return value; + } + + private JsonValue parseValue(int parentDepth) { + if (position >= source.length()) { + throw invalid("raw JSON ended before a value"); + } + char next = source.charAt(position); + if (next == '"') { + return parseString(); + } + if (next == '{') { + if (parentDepth + 1 > MAX_NESTING_DEPTH) { + throw invalid("raw JSON exceeds its nesting-depth limit"); + } + return parseObject(parentDepth + 1); + } + if (next == '[') { + if (parentDepth + 1 > MAX_NESTING_DEPTH) { + throw invalid("raw JSON exceeds its nesting-depth limit"); + } + return parseArray(parentDepth + 1); + } + if (next == 't') { + return parseLiteral("true", new JsonBoolean(true, new byte[0])); + } + if (next == 'f') { + return parseLiteral("false", new JsonBoolean(false, new byte[0])); + } + if (next == 'n') { + return parseLiteral("null", new JsonNull(new byte[0])); + } + return parseNumber(); + } + + private JsonValue parseLiteral(String literal, JsonValue placeholder) { + int start = position; + if (!source.startsWith(literal, position)) { + throw invalid("raw JSON contains an invalid token"); + } + position += literal.length(); + byte[] raw = rawToken(start, position); + if (placeholder instanceof JsonBoolean bool) { + return new JsonBoolean(bool.value(), raw); + } + return new JsonNull(raw); + } + + private JsonNumber parseNumber() { + int start = position; + while (position < source.length() && !isValueDelimiter(source.charAt(position))) { + position++; + } + if (start == position) { + throw invalid("raw JSON contains an invalid value token"); + } + byte[] raw = rawToken(start, position); + if (raw.length > MAX_NUMERIC_BYTES) { + throw invalid("numeric token exceeds its byte limit"); + } + return new JsonNumber(source.substring(start, position), raw); + } + + private JsonString parseString() { + int start = position; + position++; + StringBuilder value = new StringBuilder(); + while (position < source.length()) { + char current = source.charAt(position++); + if (current == '"') { + byte[] raw = rawToken(start, position); + String decoded = value.toString(); + requireUnicodeScalars(decoded, "string"); + return new JsonString(decoded, raw); + } + if (current == '\\') { + if (position >= source.length()) { + throw invalid("raw JSON ends inside a string escape"); + } + char escaped = source.charAt(position++); + switch (escaped) { + case '"' -> value.append('"'); + case '\\' -> value.append('\\'); + case '/' -> value.append('/'); + case 'b' -> value.append('\b'); + case 'f' -> value.append('\f'); + case 'n' -> value.append('\n'); + case 'r' -> value.append('\r'); + case 't' -> value.append('\t'); + case 'u' -> appendUnicodeEscape(value); + default -> throw invalid("raw JSON contains an invalid string escape"); + } + } else { + if (current < 0x20) { + throw invalid("raw JSON string contains an unescaped control character"); + } + value.append(current); + } + } + throw invalid("raw JSON string is unterminated"); + } + + private void appendUnicodeEscape(StringBuilder value) { + char first = readHexCodeUnit(); + if (Character.isHighSurrogate(first)) { + if (position + 1 >= source.length() + || source.charAt(position) != '\\' + || source.charAt(position + 1) != 'u') { + throw invalid("raw JSON string contains an unpaired surrogate"); + } + position += 2; + char second = readHexCodeUnit(); + if (!Character.isLowSurrogate(second)) { + throw invalid("raw JSON string contains an unpaired surrogate"); + } + value.append(first).append(second); + } else if (Character.isLowSurrogate(first)) { + throw invalid("raw JSON string contains an unpaired surrogate"); + } else { + value.append(first); + } + } + + private char readHexCodeUnit() { + if (position + 4 > source.length()) { + throw invalid("raw JSON string contains a short Unicode escape"); + } + int value = 0; + for (int index = 0; index < 4; index++) { + char digit = source.charAt(position++); + int hex = Character.digit(digit, 16); + if (hex < 0 || digit > 0x7f) { + throw invalid("raw JSON string contains an invalid Unicode escape"); + } + value = (value << 4) | hex; + } + return (char) value; + } + + private JsonObject parseObject(int depth) { + int start = position++; + skipWhitespace(); + List members = new ArrayList<>(); + if (consume('}')) { + return new JsonObject(members, rawToken(start, position)); + } + while (true) { + if (position >= source.length() || source.charAt(position) != '"') { + throw invalid("raw JSON object member key must be a string"); + } + if (members.size() >= MAX_OBJECT_MEMBERS) { + throw invalid("raw JSON object exceeds its member limit"); + } + JsonString key = parseString(); + skipWhitespace(); + require(':'); + skipWhitespace(); + JsonValue value = parseValue(depth); + members.add(new JsonMember(key, value)); + skipWhitespace(); + if (consume('}')) { + return new JsonObject(members, rawToken(start, position)); + } + require(','); + skipWhitespace(); + } + } + + private JsonArray parseArray(int depth) { + int start = position++; + skipWhitespace(); + List values = new ArrayList<>(); + if (consume(']')) { + return new JsonArray(values, rawToken(start, position)); + } + while (true) { + if (values.size() >= MAX_ARRAY_ELEMENTS) { + throw invalid("raw JSON array exceeds its element limit"); + } + values.add(parseValue(depth)); + skipWhitespace(); + if (consume(']')) { + return new JsonArray(values, rawToken(start, position)); + } + require(','); + skipWhitespace(); + } + } + + private byte[] rawToken(int start, int end) { + return Arrays.copyOfRange(input, byteOffsets[start], byteOffsets[end]); + } + + private void skipWhitespace() { + while (position < source.length()) { + char value = source.charAt(position); + if (value != ' ' && value != '\t' && value != '\r' && value != '\n') { + return; + } + position++; + } + } + + private boolean consume(char expected) { + if (position < source.length() && source.charAt(position) == expected) { + position++; + return true; + } + return false; + } + + private void require(char expected) { + if (!consume(expected)) { + throw invalid("raw JSON punctuation or member order is invalid"); + } + } + + private static boolean isValueDelimiter(char value) { + return value == ',' + || value == ']' + || value == '}' + || value == ' ' + || value == '\t' + || value == '\r' + || value == '\n'; + } + + private static int[] computeByteOffsets(String source, int expectedBytes) { + int[] offsets = new int[source.length() + 1]; + int characterIndex = 0; + int byteIndex = 0; + while (characterIndex < source.length()) { + int codePoint = source.codePointAt(characterIndex); + int characterCount = Character.charCount(codePoint); + int width = codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4; + offsets[characterIndex] = byteIndex; + if (characterCount == 2) { + offsets[characterIndex + 1] = byteIndex; + } + characterIndex += characterCount; + byteIndex += width; + offsets[characterIndex] = byteIndex; + } + if (byteIndex != expectedBytes) { + throw invalid("raw JSON UTF-8 framing is inconsistent"); + } + return offsets; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java new file mode 100644 index 0000000000..e4a0e3cf00 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java @@ -0,0 +1,445 @@ +package net.firedevops.firemud.common.operator; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable, integrity-only canonical post-authorization identity for human StartSession. + * + *

This value binds the complete pre-authorization tuple to Account's exact authorization + * projection and the original reservation claim. It does not authenticate its caller, make an + * Account redemption, or authorize a Game Session mutation. + */ +public final class StartSessionPostAuthorizationExecutionTuple { + public static final String TUPLE_SCHEMA_ID = "postAuthorizationExecutionTuple"; + public static final String TUPLE_SCHEMA_VERSION = "1"; + public static final int MAX_CANONICAL_TUPLE_BYTES = 256 * 1_024; + + private static final Pattern AUTHORIZATION_REFERENCE_FINGERPRINT = + Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); + private static final Set ROOT_FIELDS = + Set.of( + "tupleSchemaId", + "tupleSchemaVersion", + "preAuthorizationReservationTuple", + "controlPlaneRequestId", + "mutationDigest", + "issuanceKind", + "authorizationReferenceFingerprint", + "authenticatedWorkloadIdentity", + "actionFamilyRequestIdentity", + "actor", + "automationPolicy", + "actionFamily", + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "targetOwner", + "expectedVersion", + "mutation", + "auditReason", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "reservationOwnerId", + "reservationClaimFence", + "authorityEvidenceBundle", + "authorityEvidenceBundleReference"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final StartSessionPreAuthorizationReservationTuple preAuthorizationTuple; + private final String authenticatedWorkloadIdentity; + private final String authorizationReferenceFingerprint; + private final UUID reservationOwnerId; + private final long reservationClaimFence; + private final byte[] authorityEvidenceBundleBytes; + private final StartSessionAuthorityEvidenceBundle.BundleReference bundleReference; + private final byte[] canonicalBytes; + + private StartSessionPostAuthorizationExecutionTuple( + StartSessionPreAuthorizationReservationTuple preAuthorizationTuple, + String authenticatedWorkloadIdentity, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + byte[] authorityEvidenceBundleBytes, + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference, + byte[] canonicalBytes) { + this.preAuthorizationTuple = preAuthorizationTuple; + this.authenticatedWorkloadIdentity = authenticatedWorkloadIdentity; + this.authorizationReferenceFingerprint = authorizationReferenceFingerprint; + this.reservationOwnerId = reservationOwnerId; + this.reservationClaimFence = reservationClaimFence; + this.authorityEvidenceBundleBytes = authorityEvidenceBundleBytes.clone(); + this.bundleReference = bundleReference; + this.canonicalBytes = canonicalBytes.clone(); + } + + /** + * Creates the full human StartSession tuple from the exact pre-tuple and Account-returned + * evidence. The workload URI must be the same-namespace Logging & Admin mTLS identity. + */ + public static StartSessionPostAuthorizationExecutionTuple createHuman( + StartSessionPreAuthorizationReservationTuple preAuthorizationTuple, + String authenticatedWorkloadIdentity, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + byte[] exactCanonicalAuthorityEvidenceBundle, + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference) { + Objects.requireNonNull(preAuthorizationTuple, "pre-authorization tuple is required"); + Objects.requireNonNull(bundleReference, "original Account bundle reference is required"); + requireLoggingWorkload(authenticatedWorkloadIdentity, preAuthorizationTuple); + requireFingerprint(authorizationReferenceFingerprint); + requireNonNil(reservationOwnerId, "reservationOwnerId"); + if (reservationClaimFence <= 0L) { + throw new IllegalArgumentException("reservationClaimFence must be positive"); + } + + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(exactCanonicalAuthorityEvidenceBundle); + bundle.requireTupleBinding(preAuthorizationTuple); + bundle.requireReferenceBinding(bundleReference); + byte[] bundleBytes = bundle.canonicalBytes(); + byte[] canonical = + encode( + preAuthorizationTuple, + authenticatedWorkloadIdentity, + authorizationReferenceFingerprint, + reservationOwnerId, + reservationClaimFence, + bundle, + bundleReference); + return new StartSessionPostAuthorizationExecutionTuple( + preAuthorizationTuple, + authenticatedWorkloadIdentity, + authorizationReferenceFingerprint, + reservationOwnerId, + reservationClaimFence, + bundleBytes, + bundleReference, + canonical); + } + + /** Strictly decodes one complete canonical tuple; decoding does not establish authority. */ + public static StartSessionPostAuthorizationExecutionTuple decode(byte[] exactCanonicalBytes) { + if (exactCanonicalBytes == null + || exactCanonicalBytes.length == 0 + || exactCanonicalBytes.length > MAX_CANONICAL_TUPLE_BYTES) { + throw invalid("post-authorization tuple is empty or exceeds its byte limit"); + } + try { + String json = strictUtf8(exactCanonicalBytes); + byte[] canonicalInput = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!MessageDigest.isEqual(canonicalInput, exactCanonicalBytes)) { + throw invalid("post-authorization tuple is not canonical UTF-8 JSON"); + } + Map root = JSON.readValue(json, new TypeReference<>() {}); + requireExactFields(root, ROOT_FIELDS, "post-authorization tuple"); + if (!TUPLE_SCHEMA_ID.equals(string(root.get("tupleSchemaId"), "tupleSchemaId")) + || !TUPLE_SCHEMA_VERSION.equals( + string(root.get("tupleSchemaVersion"), "tupleSchemaVersion"))) { + throw invalid("unsupported post-authorization tuple schema"); + } + + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + canonicalObject( + root.get("preAuthorizationReservationTuple"), + "preAuthorizationReservationTuple")); + Map referenceValue = + object(root.get("authorityEvidenceBundleReference"), "authorityEvidenceBundleReference"); + requireExactFields( + referenceValue, + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization"), + "authorityEvidenceBundleReference"); + StartSessionAuthorityEvidenceBundle.BundleReference reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + string(referenceValue.get("bundleVersion"), "bundleVersion"), + string(referenceValue.get("sourceVersion"), "sourceVersion"), + string(referenceValue.get("sourceFence"), "sourceFence"), + string(referenceValue.get("linearization"), "linearization")); + Map workloadValue = + object(root.get("authenticatedWorkloadIdentity"), "authenticatedWorkloadIdentity"); + requireExactFields( + workloadValue, Set.of("identityKind", "uri"), "authenticatedWorkloadIdentity"); + if (!"MUTUAL_TLS_SPIFFE".equals(string(workloadValue.get("identityKind"), "identityKind"))) { + throw invalid("unsupported authenticated workload identity kind"); + } + byte[] bundleBytes = + canonicalObject(root.get("authorityEvidenceBundle"), "authorityEvidenceBundle") + .getBytes(StandardCharsets.UTF_8); + StartSessionPostAuthorizationExecutionTuple result = + createHuman( + preTuple, + string(workloadValue.get("uri"), "authenticatedWorkloadIdentity.uri"), + string( + root.get("authorizationReferenceFingerprint"), + "authorizationReferenceFingerprint"), + canonicalUuid(root.get("reservationOwnerId"), "reservationOwnerId"), + positiveLong(root.get("reservationClaimFence"), "reservationClaimFence"), + bundleBytes, + reference); + if (!TUPLE_SCHEMA_ID.equals(string(root.get("tupleSchemaId"), "tupleSchemaId")) + || !MessageDigest.isEqual(result.canonicalBytes, exactCanonicalBytes)) { + throw invalid("post-authorization tuple members are inconsistent or non-canonical"); + } + return result; + } catch (IllegalArgumentException expected) { + throw expected; + } catch (IOException | RuntimeException malformed) { + throw invalid("post-authorization tuple JSON is invalid"); + } + } + + public StartSessionPreAuthorizationReservationTuple preAuthorizationTuple() { + return preAuthorizationTuple; + } + + public String controlPlaneRequestId() { + return preAuthorizationTuple.controlPlaneRequestId(); + } + + public String mutationDigest() { + return preAuthorizationTuple.mutationDigest(); + } + + public String issuanceKind() { + return "human_operator"; + } + + public String authenticatedWorkloadIdentity() { + return authenticatedWorkloadIdentity; + } + + public String authorizationReferenceFingerprint() { + return authorizationReferenceFingerprint; + } + + public UUID reservationOwnerId() { + return reservationOwnerId; + } + + public long reservationClaimFence() { + return reservationClaimFence; + } + + public String issuanceFence() { + return StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundleBytes).issuanceFence(); + } + + public Map authorityTuple() { + return StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundleBytes) + .authorityTuple(); + } + + public Map membershipVersion() { + return StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundleBytes) + .membershipVersion(); + } + + public byte[] authorityEvidenceBundleBytes() { + return authorityEvidenceBundleBytes.clone(); + } + + public StartSessionAuthorityEvidenceBundle.BundleReference bundleReference() { + return bundleReference; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String canonicalJson() { + return new String(canonicalBytes, StandardCharsets.UTF_8); + } + + private static byte[] encode( + StartSessionPreAuthorizationReservationTuple preTuple, + String workloadIdentity, + String fingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + StartSessionAuthorityEvidenceBundle bundle, + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference) { + Map preValue = readCanonicalObject(preTuple.canonicalJson()); + Map root = new LinkedHashMap<>(); + root.put("tupleSchemaId", TUPLE_SCHEMA_ID); + root.put("tupleSchemaVersion", TUPLE_SCHEMA_VERSION); + root.put("preAuthorizationReservationTuple", preValue); + root.put("controlPlaneRequestId", preTuple.controlPlaneRequestId()); + root.put("mutationDigest", preTuple.mutationDigest()); + root.put("issuanceKind", "human_operator"); + root.put("authorizationReferenceFingerprint", fingerprint); + root.put( + "authenticatedWorkloadIdentity", + Map.of("identityKind", "MUTUAL_TLS_SPIFFE", "uri", workloadIdentity)); + root.put("actionFamilyRequestIdentity", preValue.get("actionFamilyRequestIdentity")); + root.put("actor", preValue.get("actor")); + root.put("automationPolicy", preValue.get("automationPolicy")); + root.put("actionFamily", preValue.get("actionFamily")); + root.put("actionFamilySchemaId", preValue.get("actionFamilySchemaId")); + root.put("actionFamilySchemaVersion", preValue.get("actionFamilySchemaVersion")); + root.put("scope", preValue.get("scope")); + root.put("target", preValue.get("target")); + root.put("targetOwner", preValue.get("targetOwner")); + root.put("expectedVersion", preValue.get("expectedVersion")); + root.put("mutation", preValue.get("mutation")); + root.put("auditReason", preValue.get("auditReason")); + root.put("authorityTuple", bundle.authorityTuple()); + root.put("membershipVersion", bundle.membershipVersion()); + root.put("issuanceFence", bundle.issuanceFence()); + root.put("reservationOwnerId", reservationOwnerId.toString()); + root.put("reservationClaimFence", reservationClaimFence); + root.put("authorityEvidenceBundle", bundle.jsonValue()); + root.put( + "authorityEvidenceBundleReference", + Map.of( + "bundleVersion", bundleReference.bundleVersion(), + "sourceVersion", bundleReference.sourceVersion(), + "sourceFence", bundleReference.sourceFence(), + "linearization", bundleReference.linearization())); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (bytes.length > MAX_CANONICAL_TUPLE_BYTES) { + throw invalid("post-authorization tuple exceeds its byte limit"); + } + return bytes; + } catch (IOException exception) { + throw new IllegalStateException("could not encode post-authorization tuple", exception); + } + } + + private static void requireLoggingWorkload( + String workloadIdentity, StartSessionPreAuthorizationReservationTuple preTuple) { + Objects.requireNonNull(workloadIdentity, "authenticated workload identity is required"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri(workloadIdentity) + .orElseThrow(() -> invalid("authenticated workload identity is invalid")); + if (!"logging-admin-service".equals(peer.service()) + || !peer.namespace().equals(preTuple.action().scope().targetNamespace())) { + throw invalid("StartSession requires the same-namespace Logging & Admin mTLS workload"); + } + } + + private static void requireFingerprint(String fingerprint) { + if (fingerprint == null + || !AUTHORIZATION_REFERENCE_FINGERPRINT.matcher(fingerprint).matches()) { + throw invalid("Account authorization-reference fingerprint is malformed"); + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (value.equals(new UUID(0L, 0L))) { + throw invalid(field + " must not be nil"); + } + } + + private static String canonicalObject(Object value, String field) { + Map object = object(value, field); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(object)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw invalid(field + " cannot be decoded as canonical JSON"); + } + } + + private static Map readCanonicalObject(String canonicalJson) { + return JSON.readValue(canonicalJson, new TypeReference<>() {}); + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException malformed) { + throw invalid("post-authorization tuple is not valid UTF-8"); + } + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map raw)) { + throw invalid(field + " must be an object"); + } + Map result = new LinkedHashMap<>(); + raw.forEach( + (key, member) -> { + if (!(key instanceof String text)) { + throw invalid(field + " has a non-string key"); + } + result.put(text, member); + }); + return result; + } + + private static void requireExactFields( + Map object, Set fields, String field) { + if (!object.keySet().equals(fields)) { + throw invalid(field + " has missing or unsupported fields"); + } + } + + private static String string(Object value, String field) { + if (!(value instanceof String text)) { + throw invalid(field + " must be a string"); + } + return text; + } + + private static UUID canonicalUuid(Object value, String field) { + String text = string(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + } + + private static long positiveLong(Object value, String field) { + if (!(value instanceof Number number)) { + throw invalid(field + " must be a positive integer"); + } + try { + long parsed = Long.parseLong(number.toString()); + if (parsed <= 0L || !Long.toString(parsed).equals(number.toString())) { + throw invalid(field + " must be a positive canonical integer"); + } + return parsed; + } catch (NumberFormatException malformed) { + throw invalid(field + " must be a positive signed 64-bit integer"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java new file mode 100644 index 0000000000..aec108b44d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java @@ -0,0 +1,381 @@ +package net.firedevops.firemud.common.operator; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.text.Normalizer; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable shared value and canonical codec for ADR 0048's StartSession {@code + * preAuthorizationReservationTuple/v1}. + * + *

This value describes tuple contents only. Constructing or rehydrating it does not establish + * authenticated actor authority, reservation ownership, a claim, or permission to dispatch. + */ +public final class StartSessionPreAuthorizationReservationTuple { + public static final String TUPLE_SCHEMA_ID = "preAuthorizationReservationTuple"; + public static final String TUPLE_SCHEMA_VERSION = "1"; + public static final int MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES = 128; + private static final int MAX_CANONICAL_TUPLE_UTF8_BYTES = 8 * 1_024; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Set ROOT_FIELDS = + Set.of( + "tupleSchemaId", + "tupleSchemaVersion", + "actionFamilyRequestIdentity", + "actor", + "automationPolicy", + "actionFamily", + "actionFamilySchemaId", + "actionFamilySchemaVersion", + "scope", + "target", + "targetOwner", + "expectedVersion", + "mutation", + "auditReason"); + + private final String controlPlaneRequestId; + private final HumanActor actor; + private final StartSessionOperatorAction action; + + private StartSessionPreAuthorizationReservationTuple( + String controlPlaneRequestId, HumanActor actor, StartSessionOperatorAction action) { + this.controlPlaneRequestId = requireCanonicalControlPlaneRequestId(controlPlaneRequestId); + this.actor = Objects.requireNonNull(actor, "actor is required"); + this.action = Objects.requireNonNull(action, "action is required"); + } + + /** Creates tuple contents from typed values; the actor argument is not authenticated evidence. */ + public static StartSessionPreAuthorizationReservationTuple createHuman( + String controlPlaneRequestId, UUID actorAccountId, StartSessionOperatorAction action) { + return new StartSessionPreAuthorizationReservationTuple( + controlPlaneRequestId, new HumanActor(actorAccountId), action); + } + + /** Rehydrates the exact canonical ADR 0048 tuple value. This does not establish authority. */ + public static StartSessionPreAuthorizationReservationTuple fromCanonicalJson(String json) { + Objects.requireNonNull(json, "tuple JSON is required"); + if (json.getBytes(StandardCharsets.UTF_8).length > MAX_CANONICAL_TUPLE_UTF8_BYTES) { + throw new IllegalArgumentException("pre-authorization tuple exceeds its byte limit"); + } + try { + String canonical = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + if (!canonical.equals(json)) { + throw new IllegalArgumentException("pre-authorization tuple is not canonical JSON"); + } + Object decoded = JSON.readValue(json, Map.class); + Map root = requireObject(decoded, "tuple"); + requireExactFields(root, ROOT_FIELDS, "tuple"); + if (!TUPLE_SCHEMA_ID.equals(requireString(root.get("tupleSchemaId"), "tupleSchemaId")) + || !TUPLE_SCHEMA_VERSION.equals( + requireString(root.get("tupleSchemaVersion"), "tupleSchemaVersion"))) { + throw new IllegalArgumentException("unsupported pre-authorization tuple schema"); + } + + Map identity = + requireObject(root.get("actionFamilyRequestIdentity"), "actionFamilyRequestIdentity"); + requireExactFields( + identity, Set.of("requestIdentityKind", "requestId"), "actionFamilyRequestIdentity"); + if (!"controlPlaneRequestId" + .equals(requireString(identity.get("requestIdentityKind"), "requestIdentityKind"))) { + throw new IllegalArgumentException( + "StartSession request identity must be controlPlaneRequestId"); + } + String controlPlaneRequestId = requireString(identity.get("requestId"), "requestId"); + + Map actorObject = requireObject(root.get("actor"), "actor"); + requireExactFields(actorObject, Set.of("kind", "accountId"), "actor"); + if (!"HUMAN".equals(requireString(actorObject.get("kind"), "actor.kind"))) { + throw new IllegalArgumentException("StartSession reservation actor must be human"); + } + HumanActor actor = + new HumanActor(requireCanonicalUuid(actorObject.get("accountId"), "actor.accountId")); + + Map automation = + requireObject(root.get("automationPolicy"), "automationPolicy"); + requireExactFields(automation, Set.of("presence"), "automationPolicy"); + if (!"ABSENT" + .equals(requireString(automation.get("presence"), "automationPolicy.presence"))) { + throw new IllegalArgumentException( + "human StartSession tuple must explicitly omit automation policy"); + } + + String actionFamily = requireString(root.get("actionFamily"), "actionFamily"); + String schemaId = requireString(root.get("actionFamilySchemaId"), "actionFamilySchemaId"); + String schemaVersion = + requireString(root.get("actionFamilySchemaVersion"), "actionFamilySchemaVersion"); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(actionFamily) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID.equals(schemaId) + || !StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION.equals(schemaVersion)) { + throw new IllegalArgumentException("unsupported StartSession action-family schema"); + } + + Map scopeObject = requireObject(root.get("scope"), "scope"); + requireExactFields(scopeObject, Set.of("tenantId", "targetNamespace"), "scope"); + StartSessionOperatorAction.Scope scope = + new StartSessionOperatorAction.Scope( + requireCanonicalUuid(scopeObject.get("tenantId"), "scope.tenantId"), + requireString(scopeObject.get("targetNamespace"), "scope.targetNamespace")); + + Map targetObject = requireObject(root.get("target"), "target"); + requireExactFields(targetObject, Set.of("gameTemplateId", "ownerAccountId"), "target"); + StartSessionOperatorAction.Target target = + new StartSessionOperatorAction.Target( + requirePositiveCanonicalLong(targetObject.get("gameTemplateId")), + requireCanonicalUuid(targetObject.get("ownerAccountId"), "target.ownerAccountId")); + + Map ownerObject = requireObject(root.get("targetOwner"), "targetOwner"); + requireExactFields(ownerObject, Set.of("ownerService"), "targetOwner"); + if (!StartSessionOperatorAction.OWNER_SERVICE.equals( + requireString(ownerObject.get("ownerService"), "targetOwner.ownerService"))) { + throw new IllegalArgumentException("StartSession targetOwner is immutable and unsupported"); + } + + Map expectedVersion = + requireObject(root.get("expectedVersion"), "expectedVersion"); + requireExactFields(expectedVersion, Set.of("presence"), "expectedVersion"); + if (!"ABSENT" + .equals(requireString(expectedVersion.get("presence"), "expectedVersion.presence"))) { + throw new IllegalArgumentException( + "StartSession expectedVersion must be explicitly absent"); + } + + Map mutationObject = requireObject(root.get("mutation"), "mutation"); + requireExactFields(mutationObject, Set.of("clientIp"), "mutation"); + Map clientIpObject = + requireObject(mutationObject.get("clientIp"), "mutation.clientIp"); + String clientIpPresence = + requireString(clientIpObject.get("presence"), "mutation.clientIp.presence"); + StartSessionOperatorAction.ClientIp clientIp; + if ("ABSENT".equals(clientIpPresence)) { + requireExactFields(clientIpObject, Set.of("presence"), "mutation.clientIp"); + clientIp = StartSessionOperatorAction.ClientIp.absent(); + } else if ("PRESENT".equals(clientIpPresence)) { + requireExactFields(clientIpObject, Set.of("presence", "value"), "mutation.clientIp"); + clientIp = + StartSessionOperatorAction.ClientIp.of( + requireString(clientIpObject.get("value"), "mutation.clientIp.value")); + } else { + throw new IllegalArgumentException("mutation.clientIp presence must be ABSENT or PRESENT"); + } + + StartSessionOperatorAction action = + new StartSessionOperatorAction( + schemaId, + schemaVersion, + scope, + target, + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + requireString(root.get("auditReason"), "auditReason")); + StartSessionPreAuthorizationReservationTuple tuple = + new StartSessionPreAuthorizationReservationTuple(controlPlaneRequestId, actor, action); + if (!tuple.canonicalJson().equals(json)) { + throw new IllegalArgumentException("pre-authorization tuple shape is not canonical"); + } + return tuple; + } catch (IOException exception) { + throw new IllegalArgumentException("pre-authorization tuple JSON is invalid", exception); + } + } + + public String actionFamily() { + return action.actionFamily(); + } + + public String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + public HumanActor actor() { + return actor; + } + + public NoAutomationPolicy automationPolicy() { + return NoAutomationPolicy.ABSENT; + } + + public StartSessionOperatorAction action() { + return action; + } + + /** Validate a stable request key without silently normalizing or changing its identity. */ + public static String requireCanonicalControlPlaneRequestId(String value) { + Objects.requireNonNull(value, "controlPlaneRequestId is required"); + if (!Normalizer.isNormalized(value, Normalizer.Form.NFC)) { + throw new IllegalArgumentException("controlPlaneRequestId must already be NFC-normalized"); + } + return requireBoundedText(value, "controlPlaneRequestId"); + } + + public String targetOwner() { + return action.targetOwner(); + } + + /** Returns ADR 0047's digest over the seven action-schema grammar fields. */ + public String mutationDigest() { + return StartSessionOperatorActionCodec.mutationDigest(action); + } + + /** Returns the complete canonical typed tuple, including explicit absence values. */ + public String canonicalJson() { + Map scope = + Map.of( + "tenantId", action.scope().tenantId().toString(), + "targetNamespace", action.scope().targetNamespace()); + Map target = + Map.of( + "gameTemplateId", Long.toString(action.target().gameTemplateId()), + "ownerAccountId", action.target().ownerAccountId().toString()); + Map clientIp = + action.mutation().clientIp() instanceof StartSessionOperatorAction.AbsentClientIp + ? Map.of("presence", "ABSENT") + : Map.of( + "presence", + "PRESENT", + "value", + ((StartSessionOperatorAction.StringClientIp) action.mutation().clientIp()).value()); + Map root = new LinkedHashMap<>(); + root.put("tupleSchemaId", TUPLE_SCHEMA_ID); + root.put("tupleSchemaVersion", TUPLE_SCHEMA_VERSION); + root.put( + "actionFamilyRequestIdentity", + Map.of("requestIdentityKind", "controlPlaneRequestId", "requestId", controlPlaneRequestId)); + root.put("actor", Map.of("kind", "HUMAN", "accountId", actor.accountId().toString())); + root.put("automationPolicy", Map.of("presence", automationPolicy().name())); + root.put("actionFamily", action.actionFamily()); + root.put("actionFamilySchemaId", action.actionFamilySchemaId()); + root.put("actionFamilySchemaVersion", action.actionFamilySchemaVersion()); + root.put("scope", scope); + root.put("target", target); + root.put("targetOwner", Map.of("ownerService", action.targetOwner())); + root.put("expectedVersion", Map.of("presence", action.expectedVersion().name())); + root.put("mutation", Map.of("clientIp", clientIp)); + root.put("auditReason", action.auditReason()); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)), + StandardCharsets.UTF_8); + } catch (IOException exception) { + throw new IllegalStateException("could not encode StartSession reservation tuple", exception); + } + } + + public record HumanActor(UUID accountId) { + public HumanActor { + Objects.requireNonNull(accountId, "actor accountId is required"); + if (accountId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("actor accountId must not be nil"); + } + } + } + + public enum NoAutomationPolicy { + ABSENT + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof StartSessionPreAuthorizationReservationTuple that)) { + return false; + } + return controlPlaneRequestId.equals(that.controlPlaneRequestId) + && actor.equals(that.actor) + && action.equals(that.action); + } + + @Override + public int hashCode() { + return Objects.hash(controlPlaneRequestId, actor, action); + } + + private static String requireBoundedText(String value, String fieldName) { + Objects.requireNonNull(value, fieldName + " is required"); + String normalized = Normalizer.normalize(value, Normalizer.Form.NFC); + if (normalized.isBlank() + || normalized.codePoints().anyMatch(Character::isISOControl) + || normalized.getBytes(StandardCharsets.UTF_8).length + > MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES) { + throw new IllegalArgumentException(fieldName + " is blank or exceeds its bound"); + } + for (int index = 0; index < normalized.length(); index++) { + char current = normalized.charAt(index); + if (Character.isHighSurrogate(current)) { + if (index + 1 >= normalized.length() + || !Character.isLowSurrogate(normalized.charAt(index + 1))) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + index++; + } else if (Character.isLowSurrogate(current)) { + throw new IllegalArgumentException(fieldName + " contains malformed Unicode"); + } + } + return normalized; + } + + private static UUID requireCanonicalUuid(Object value, String fieldName) { + String text = requireString(value, fieldName); + UUID parsed; + try { + parsed = UUID.fromString(text); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID", exception); + } + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID"); + } + return parsed; + } + + private static long requirePositiveCanonicalLong(Object value) { + String text = requireString(value, "target.gameTemplateId"); + if (!text.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException( + "target.gameTemplateId must be a positive canonical integer"); + } + try { + return Long.parseLong(text); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException( + "target.gameTemplateId exceeds its supported range", exception); + } + } + + private static String requireString(Object value, String fieldName) { + if (!(value instanceof String text)) { + throw new IllegalArgumentException(fieldName + " must be a string"); + } + return text; + } + + @SuppressWarnings("unchecked") + private static Map requireObject(Object value, String fieldName) { + if (!(value instanceof Map map)) { + throw new IllegalArgumentException(fieldName + " must be an object"); + } + for (Object key : map.keySet()) { + if (!(key instanceof String)) { + throw new IllegalArgumentException(fieldName + " contains a non-string field name"); + } + } + return (Map) map; + } + + private static void requireExactFields( + Map object, Set expectedFields, String fieldName) { + if (!object.keySet().equals(expectedFields)) { + throw new IllegalArgumentException(fieldName + " has missing or unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java new file mode 100644 index 0000000000..76c4839df2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java @@ -0,0 +1,687 @@ +package net.firedevops.firemud.common.account; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.Timestamp; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +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 tools.jackson.databind.json.JsonMapper; + +/** Physical mTLS proof for Game Design's read-only Account redeemed-operation projection client. */ +class StartSessionRedeemedOperationProjectionClientTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String OPAQUE_REFERENCE = "opaque-reference-never-sent"; + private static final String FORWARDED_JWT = "header.payload.signature"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID ACTOR_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("52345678-1234-4234-8234-123456789abc"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("62345678-1234-4234-8234-123456789abc"); + private static final UUID CONTROL_UI_JTI = + UUID.fromString("72345678-1234-4234-8234-123456789abc"); + private static final long RESERVATION_FENCE = 4L; + private static final long OWNER_FENCE = 9L; + private static final long ISSUANCE_FENCE = 23L; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final Instant CLOCK_NOW = Instant.parse("2035-01-01T00:00:00Z"); + private static final Clock FIXED_CLOCK = Clock.fixed(CLOCK_NOW, ZoneOffset.UTC); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private Server server; + private StartSessionRedeemedOperationProjectionClient client; + private AtomicInteger applicationCalls; + private AtomicReference receivedPeer; + private AtomicReference receivedRequest; + private CountDownLatch timeoutRelease; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (timeoutRelease != null) { + timeoutRelease.countDown(); + } + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void exactSameNamespaceWorkloadsReadTheOriginalProjectionOverPhysicalMtls() throws Exception { + Fixture fixture = fixture(CLOCK_NOW.plusSeconds(3_600L)); + startServer(fixture, ResponseMode.EXACT); + client = newClient(server); + client.init(); + + ReadRedeemedOperationProjectionResponse response = + client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE); + + assertThat(response.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly( + fixture + .postTuple() + .preAuthorizationTuple() + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)); + assertThat(response.getAuthorityEvidenceBundle().toByteArray()) + .containsExactly(fixture.postTuple().authorityEvidenceBundleBytes()); + assertThat(applicationCalls).hasValue(1); + assertThat(receivedPeer.get()) + .isNotNull() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(GAME_DESIGN_URI); + assertThat(receivedRequest.get().getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(receivedRequest.get().getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly( + fixture + .postTuple() + .preAuthorizationTuple() + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)); + assertThat(receivedRequest.get().getReservationOwnerId()) + .isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(receivedRequest.get().getReservationClaimFence()).isEqualTo(RESERVATION_FENCE); + assertThat(receivedRequest.get().getOwnerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID.toString()); + assertThat(receivedRequest.get().getOwnerFence()).isEqualTo(OWNER_FENCE); + assertThat(receivedRequest.get().toString()) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FORWARDED_JWT); + } + + @Test + void rejectsChangedOperationBindingAndUnknownResponseFields() throws Exception { + Fixture fixture = fixture(CLOCK_NOW.plusSeconds(3_600L)); + startServer(fixture, ResponseMode.CHANGED_DIGEST); + client = newClient(server); + client.init(); + + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid redeemed StartSession operation projection"); + assertThat(applicationCalls).hasValue(1); + + stopTransport(); + startServer(fixture, ResponseMode.UNKNOWN_FIELD); + client = newClient(server); + client.init(); + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid redeemed StartSession operation projection"); + } + + @Test + void rejectsExpiredAccountReferenceEvenWhenResponseEchoesOriginalBundle() throws Exception { + Fixture fixture = fixture(CLOCK_NOW.minusSeconds(60L)); + startServer(fixture, ResponseMode.EXACT); + client = newClient(server); + client.init(); + + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid redeemed StartSession operation projection"); + assertThat(applicationCalls).hasValue(1); + } + + @Test + void boundedDeadlineLeavesTransportUncertaintyAndDoesNotRetry() throws Exception { + Fixture fixture = fixture(CLOCK_NOW.plusSeconds(3_600L)); + startServer(fixture, ResponseMode.BLOCK_UNTIL_RELEASED); + client = newClient(server); + client.init(); + + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(applicationCalls).hasValue(1); + } + + @Test + void refusesReadOutsideConfiguredNamespaceAndBeforeExplicitInitialization() throws Exception { + Fixture fixture = fixture(CLOCK_NOW.plusSeconds(3_600L)); + Fixture otherNamespaceFixture = fixture(CLOCK_NOW.plusSeconds(3_600L), "other"); + client = newClientPropertiesOnly(); + + assertThatThrownBy( + () -> client.read(otherNamespaceFixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.read(fixture.postTuple(), new UUID(0L, 0L), OWNER_FENCE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not be nil"); + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be positive"); + } + + private void startServer(Fixture fixture, ResponseMode mode) throws Exception { + applicationCalls = new AtomicInteger(); + receivedPeer = new AtomicReference<>(); + receivedRequest = new AtomicReference<>(); + timeoutRelease = new CountDownLatch(1); + var service = + new StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceImplBase() { + @Override + public void readRedeemedOperationProjection( + ReadRedeemedOperationProjectionRequest request, + StreamObserver observer) { + applicationCalls.incrementAndGet(); + receivedPeer.set(GrpcPeerIdentity.current()); + receivedRequest.set(request); + if (mode == ResponseMode.BLOCK_UNTIL_RELEASED) { + try { + if (!timeoutRelease.await(10, TimeUnit.SECONDS)) { + observer.onError(Status.DEADLINE_EXCEEDED.asRuntimeException()); + return; + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + observer.onError(Status.CANCELLED.asRuntimeException()); + return; + } + } + + ReadRedeemedOperationProjectionResponse response = response(fixture); + if (mode == ResponseMode.CHANGED_DIGEST) { + response = response.toBuilder().setMutationDigest("0".repeat(64)).build(); + } else if (mode == ResponseMode.UNKNOWN_FIELD) { + response = + response.toBuilder() + .mergeUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.accountServer().privateKey(), pki.accountServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private StartSessionRedeemedOperationProjectionClient newClient(Server target) + throws IOException, CertificateEncodingException { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + target.getPort()); + return new StartSessionRedeemedOperationProjectionClient( + endpoints, + pki.clientProperties(tempDirectory), + new GrpcChannelFactory(), + NAMESPACE, + FIXED_CLOCK); + } + + private StartSessionRedeemedOperationProjectionClient newClientPropertiesOnly() throws Exception { + return new StartSessionRedeemedOperationProjectionClient( + new ServiceEndpointsProperties(), + pki.clientProperties(tempDirectory), + new GrpcChannelFactory(), + NAMESPACE, + FIXED_CLOCK); + } + + private static ReadRedeemedOperationProjectionResponse response(Fixture fixture) { + StartSessionPostAuthorizationExecutionTuple postTuple = fixture.postTuple(); + StartSessionAuthorityEvidenceBundle.BundleReference reference = postTuple.bundleReference(); + String targetNamespace = postTuple.preAuthorizationTuple().action().scope().targetNamespace(); + return ReadRedeemedOperationProjectionResponse.newBuilder() + .setControlPlaneRequestId(postTuple.controlPlaneRequestId()) + .setCanonicalPreAuthorizationTupleBytes( + com.google.protobuf.ByteString.copyFrom( + postTuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setMutationDigest(postTuple.mutationDigest()) + .setAuthorizationReferenceFingerprint(postTuple.authorizationReferenceFingerprint()) + .setReservationOwnerId(postTuple.reservationOwnerId().toString()) + .setReservationClaimFence(postTuple.reservationClaimFence()) + .setAuthenticatedRedeemerWorkloadIdentity( + "spiffe://firemud/ns/" + targetNamespace + "/sa/game-session-service") + .setOwnerAttemptId(OWNER_ATTEMPT_ID.toString()) + .setOwnerFence(OWNER_FENCE) + .setReferenceExpiresAt(timestamp(fixture.referenceExpiresAt())) + .setRedeemedAt(timestamp(fixture.redeemedAt())) + .setIssuanceOperationId(ISSUANCE_OPERATION_ID.toString()) + .setIssuanceFence(ISSUANCE_FENCE) + .setBundleReference( + net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference.newBuilder() + .setBundleVersion(reference.bundleVersion()) + .setSourceVersion(reference.sourceVersion()) + .setSourceFence(reference.sourceFence()) + .setLinearization(reference.linearization()) + .build()) + .setAuthorityEvidenceBundle( + com.google.protobuf.ByteString.copyFrom(postTuple.authorityEvidenceBundleBytes())) + .build(); + } + + private static Fixture fixture(Instant expiresAt) { + return fixture(expiresAt, NAMESPACE); + } + + private static Fixture fixture(Instant expiresAt, String targetNamespace) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, targetNamespace), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Read original StartSession source projection"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "redeemed-projection-request-β", ACTOR_ID, action); + StartSessionAuthorityEvidenceBundle.BundleReference reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + Long.toString(ISSUANCE_FENCE), + "18446744073709551615"); + byte[] bundle = authorityEvidenceBundle(preTuple, expiresAt, targetNamespace); + StartSessionPostAuthorizationExecutionTuple postTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + targetNamespace + "/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER_ID, + RESERVATION_FENCE, + bundle, + reference); + Instant redeemedAt = + expiresAt.isAfter(CLOCK_NOW) ? CLOCK_NOW.minusSeconds(60L) : expiresAt.minusSeconds(60L); + return new Fixture(postTuple, expiresAt, redeemedAt); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple tuple, + Instant expiresAt, + String targetNamespace) { + String tenantId = TENANT_ID.toString(); + Map value = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", targetNamespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + expiresAt.minusSeconds(600L).toString(), + "expiresAt", + expiresAt.toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_OPERATION_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", Long.toString(ISSUANCE_FENCE), + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + CONTROL_UI_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException malformed) { + throw new IllegalStateException("could not encode test Account authority bundle", malformed); + } + } + + private static Timestamp timestamp(Instant value) { + return Timestamp.newBuilder() + .setSeconds(value.getEpochSecond()) + .setNanos(value.getNano()) + .build(); + } + + private enum ResponseMode { + EXACT, + CHANGED_DIGEST, + UNKNOWN_FIELD, + BLOCK_UNTIL_RELEASED + } + + private record Fixture( + StartSessionPostAuthorizationExecutionTuple postTuple, + Instant referenceExpiresAt, + Instant redeemedAt) {} + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, TestIdentity accountServer, TestIdentity gameDesignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD Account projection test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) + throws IOException, CertificateEncodingException { + Path clientCertificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + gameDesignClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + gameDesignClient.privateKey().getEncoded()); + Path trustCa = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(trustCa.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + List command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java new file mode 100644 index 0000000000..de35ef6b9e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java @@ -0,0 +1,225 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class StartSessionOperatorActionCodecTest { + private static final String VECTOR_RESOURCE = + "/operator/start-session-mutation-digest-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + + @Test + void matchesSharedActionVectors() throws IOException { + JsonNode vectors = fixture().path("vectors"); + String baseDigest = null; + String changedTargetDigest = null; + String changedScopeDigest = null; + String changedReasonDigest = null; + String composedDigest = null; + String decomposedDigest = null; + String absentClientIpDigest = null; + String emptyClientIpDigest = null; + + for (JsonNode vector : vectors) { + byte[] raw = rawVectorBytes(vector); + String name = vector.path("name").asText(); + if (!vector.path("accepted").asBoolean()) { + assertThatThrownBy(() -> StartSessionOperatorActionCodec.decode(raw)) + .as("vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + + StartSessionOperatorAction action = StartSessionOperatorActionCodec.decode(raw); + byte[] preimage = StartSessionOperatorActionCodec.canonicalPreimage(action); + String digest = StartSessionOperatorActionCodec.mutationDigest(action); + assertThat(hex(preimage)) + .as("preimage for %s", name) + .isEqualTo(vector.path("preimageHex").asText()); + assertThat(digest).as("digest for %s", name).isEqualTo(vector.path("digest").asText()); + switch (name) { + case "base" -> baseDigest = digest; + case "changed-target" -> changedTargetDigest = digest; + case "changed-scope" -> changedScopeDigest = digest; + case "changed-audit-reason" -> changedReasonDigest = digest; + case "client-ip-absent" -> absentClientIpDigest = digest; + case "client-ip-empty" -> emptyClientIpDigest = digest; + case "unicode-composed" -> composedDigest = digest; + case "unicode-decomposed" -> decomposedDigest = digest; + default -> { + // Individual golden values above prove the remaining mutation vectors. + } + } + } + + assertThat(absentClientIpDigest).isNotEqualTo(emptyClientIpDigest); + assertThat(composedDigest).isEqualTo(decomposedDigest); + assertThat(baseDigest) + .isNotEqualTo(absentClientIpDigest) + .isNotEqualTo(changedTargetDigest) + .isNotEqualTo(changedScopeDigest) + .isNotEqualTo(changedReasonDigest); + } + + @Test + void matchesSharedGenericValueGrammarVectors() throws IOException { + java.util.Map encodings = new java.util.HashMap<>(); + for (JsonNode vector : fixture().path("grammarVectors")) { + String name = vector.path("name").asText(); + String kind = vector.path("kind").asText(); + if ("numberLexeme".equals(kind)) { + String rawLexeme = vector.path("rawLexeme").asText(); + if (!vector.path("accepted").asBoolean()) { + assertThatThrownBy( + () -> StartSessionOperatorActionCodec.canonicalNumberLexemeForTest(rawLexeme)) + .as("numeric lexeme vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + String encoded = + hex(StartSessionOperatorActionCodec.canonicalNumberLexemeForTest(rawLexeme)); + assertThat(encoded) + .as("numeric lexeme vector %s", name) + .isEqualTo(vector.path("canonicalValueHex").asText()); + encodings.put(name, encoded); + continue; + } + if ("reject".equals(kind)) { + byte[] raw = vector.path("rawValue").asText().getBytes(StandardCharsets.UTF_8); + assertThatThrownBy(() -> StartSessionOperatorActionCodec.canonicalGrammarValueForTest(raw)) + .as("grammar vector %s", name) + .isInstanceOf(IllegalArgumentException.class); + continue; + } + + byte[] encoded; + if ("absent".equals(kind)) { + encoded = StartSessionOperatorActionCodec.absentGrammarValueForTest(); + } else { + byte[] raw = vector.path("rawValue").asText().getBytes(StandardCharsets.UTF_8); + encoded = StartSessionOperatorActionCodec.canonicalGrammarValueForTest(raw); + } + String encodedHex = hex(encoded); + assertThat(encodedHex) + .as("canonical value for %s", name) + .isEqualTo(vector.path("canonicalValueHex").asText()); + encodings.put(name, encodedHex); + } + + assertThat(encodings.get("absent")).isNotEqualTo(encodings.get("null")); + assertThat(encodings.get("number-one")).isNotEqualTo(encodings.get("string-one")); + assertThat(encodings.get("number-signed-zero")).isEqualTo(encodings.get("number-zero")); + assertThat(encodings.get("unicode-key-composed")) + .isEqualTo(encodings.get("unicode-key-decomposed")); + } + + @Test + void exposesOnlyTypedImmutableStartSessionFields() throws IOException { + JsonNode base = findVector("base"); + StartSessionOperatorAction action = + StartSessionOperatorActionCodec.decode(rawVectorBytes(base)); + + assertThat(StartSessionOperatorAction.OWNER_SERVICE).isEqualTo("game-session-service"); + assertThat(action.targetOwner()).isEqualTo("game-session-service"); + assertThat(action.actionFamilySchemaId()).isEqualTo("firemud.game-session.start-session"); + assertThat(action.actionFamilySchemaVersion()).isEqualTo("1"); + assertThat(action.expectedVersion()) + .isEqualTo(StartSessionOperatorAction.ExpectedVersion.ABSENT); + assertThat(action.scope().tenantId().toString()) + .isEqualTo("22222222-2222-4222-8222-222222222222"); + assertThat(action.target().gameTemplateId()).isEqualTo(42L); + assertThat(action.mutation().clientIp()) + .isInstanceOf(StartSessionOperatorAction.StringClientIp.class); + assertThat(action.auditReason()).isEqualTo("scheduled launch"); + } + + @Test + void rejectsRawUtf8AndActionSpecificOversizeInputs() throws IOException { + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + new byte[] {'{', '"', (byte) 0xff, '"', ':', '1', '}'})) + .isInstanceOf(IllegalArgumentException.class); + + byte[] oversizedRaw = new byte[StartSessionOperatorActionCodec.MAX_RAW_BYTES + 1]; + assertThatThrownBy(() -> StartSessionOperatorActionCodec.decode(oversizedRaw)) + .isInstanceOf(IllegalArgumentException.class); + + String base = findVector("base").path("input").asText(); + String oversizedReason = base.replace("scheduled launch", "x".repeat(1_001)); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + oversizedReason.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String oversizedClientIp = base.replace("192.0.2.1", "x".repeat(129)); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.decode( + oversizedClientIp.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsObjectMemberAndArrayElementLimitViolations() { + String tooManyMembers = "{" + String.join(",", Collections.nCopies(17, "\"k\":0")) + "}"; + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooManyMembers.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String tooManyElements = "[" + String.join(",", Collections.nCopies(65, "0")) + "]"; + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooManyElements.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + String tooDeep = "[".repeat(9) + "0" + "]".repeat(9); + assertThatThrownBy( + () -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooDeep.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static JsonNode fixture() throws IOException { + try (InputStream stream = + StartSessionOperatorActionCodecTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (stream == null) { + throw new IOException("missing shared StartSession digest vector resource"); + } + return JSON.readTree(stream); + } + } + + private static JsonNode findVector(String name) throws IOException { + for (JsonNode vector : fixture().path("vectors")) { + if (name.equals(vector.path("name").asText())) { + return vector; + } + } + throw new IOException("missing vector: " + name); + } + + private static byte[] rawVectorBytes(JsonNode vector) { + if (vector.has("rawHex")) { + return java.util.HexFormat.of().parseHex(vector.path("rawHex").asText()); + } + return vector.path("input").asText().getBytes(StandardCharsets.UTF_8); + } + + private static String hex(byte[] bytes) { + return java.util.HexFormat.of().formatHex(bytes); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java new file mode 100644 index 0000000000..458f7004fb --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java @@ -0,0 +1,359 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionAuthorityEvidenceBundleTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String EVALUATED_AT = "2026-10-09T00:00:00Z"; + private static final String EXPIRES_AT = "2026-10-09T00:05:00Z"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void decodesCanonicalTenantAdminBundleAndBindsTupleAndSeparateReference() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-βeta"); + byte[] bytes = canonical(validValue(tuple)); + StartSessionAuthorityEvidenceBundle.BundleReference reference = reference(); + + StartSessionAuthorityEvidenceBundle decoded = StartSessionAuthorityEvidenceBundle.decode(bytes); + decoded.requireTupleBinding(tuple); + decoded.requireReferenceBinding(reference); + + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + assertThat(decoded.actionFamily()).isEqualTo("StartSession"); + assertThat(decoded.actorAccountId()).isEqualTo(ACTOR_ID); + assertThat(decoded.tenantId()).isEqualTo(TENANT_ID); + assertThat(decoded.targetNamespace()).isEqualTo("world-runtime"); + assertThat(decoded.controlPlaneRequestId()).isEqualTo("bundle-βeta"); + assertThat(decoded.mutationDigest()).isEqualTo(tuple.mutationDigest()).matches("[0-9a-f]{64}"); + assertThat(decoded.expiresAt()).isEqualTo(Instant.parse(EXPIRES_AT)); + assertThat(decoded.issuanceFence()).isEqualTo("23"); + assertThat(decoded.evidenceType()) + .isEqualTo(StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE); + assertThat(decoded.role()).isEqualTo("tenantAdmin"); + + byte[] exposed = decoded.canonicalBytes(); + exposed[0] = (byte) '!'; + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + } + + @Test + void exposesOnlyDeeplyImmutableJsonValue() throws Exception { + byte[] bytes = canonical(validValue(tuple("bundle-immutable-json"))); + StartSessionAuthorityEvidenceBundle decoded = StartSessionAuthorityEvidenceBundle.decode(bytes); + Map jsonValue = decoded.jsonValue(); + Map authorityTuple = object(jsonValue.get("authorityTuple")); + List grantVersions = (List) authorityTuple.get("privateRealmGrantVersions"); + + assertThatThrownBy(() -> jsonValue.put("unexpected", true)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> authorityTuple.put("unexpected", true)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(grantVersions::clear).isInstanceOf(UnsupportedOperationException.class); + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + } + + @Test + void rejectsChangedTupleActorScopeRequestOrRawMutationDigest() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-binding"); + byte[] bytes = canonical(validValue(tuple)); + StartSessionOperatorAction changedAction = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.of("203.0.113.19")), + "bundle codec contract"); + StartSessionPreAuthorizationReservationTuple changedDigest = + StartSessionPreAuthorizationReservationTuple.createHuman( + tuple.controlPlaneRequestId(), ACTOR_ID, changedAction); + StartSessionPreAuthorizationReservationTuple changedRequest = tuple("other-request"); + + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode(bytes) + .requireTupleBinding(changedDigest)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode(bytes) + .requireTupleBinding(changedRequest)) + .isInstanceOf(IllegalArgumentException.class); + + Map prefixedDigest = read(bytes); + object(prefixedDigest.get("issuanceOperationIdentity")) + .put("mutationDigest", "sha256:" + tuple.mutationDigest()); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(prefixedDigest))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresRawLowercaseSha256MutationDigestAndRejectsChangedIdentityFields() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-operation"); + Map changedIdentity = mutableValue(tuple); + object( + object(changedIdentity.get("issuanceOperationIdentity")) + .get("actionFamilyRequestIdentity")) + .put("requestId", "different-request"); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(changedIdentity))) + .isInstanceOf(IllegalArgumentException.class); + + Map uppercaseDigest = mutableValue(tuple); + object(uppercaseDigest.get("issuanceOperationIdentity")).put("mutationDigest", "A".repeat(64)); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(uppercaseDigest))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsAutomationGlobalRoleExtraAssuranceAndUnknownFields() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-closed"); + + Map automation = mutableValue(tuple); + automation.put("issuanceKind", "automation_operator"); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(automation))) + .isInstanceOf(IllegalArgumentException.class); + + Map globalRole = mutableValue(tuple); + object(globalRole.get("issuanceEvidence")).put("role", "platformAdmin"); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(globalRole))) + .isInstanceOf(IllegalArgumentException.class); + + Map assurance = mutableValue(tuple); + object(assurance.get("issuanceEvidence")).put("assurance", "not-applicable"); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(assurance))) + .isInstanceOf(IllegalArgumentException.class); + + Map unknown = mutableValue(tuple); + unknown.put("sourceReference", Map.of("unexpected", true)); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(unknown))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMalformedUtf8DuplicateKeysTrailingTokensAndNoncanonicalBytes() throws Exception { + byte[] valid = canonical(validValue(tuple("bundle-json"))); + byte[] malformedUtf8 = Arrays.copyOf(valid, valid.length + 1); + malformedUtf8[malformedUtf8.length - 1] = (byte) 0xff; + String duplicate = + new String(valid, StandardCharsets.UTF_8) + .replaceFirst("\\{", "{\"bundleVersion\":\"authorityEvidenceBundle/v1\","); + + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(malformedUtf8)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode( + duplicate.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode( + (new String(valid, StandardCharsets.UTF_8) + "{}") + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode( + (new String(valid, StandardCharsets.UTF_8) + " ") + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode(Arrays.copyOf(valid, valid.length - 1))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsInvalidExpiryAndReferenceOverflowOrMismatch() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-expiry"); + Map expiredAtEvaluation = mutableValue(tuple); + object(expiredAtEvaluation.get("accountProjectionEvidence")).put("expiresAt", EVALUATED_AT); + assertThatThrownBy( + () -> StartSessionAuthorityEvidenceBundle.decode(canonical(expiredAtEvaluation))) + .isInstanceOf(IllegalArgumentException.class); + + StartSessionAuthorityEvidenceBundle decoded = + StartSessionAuthorityEvidenceBundle.decode(canonical(validValue(tuple))); + assertThatThrownBy( + () -> + decoded.requireReferenceBinding( + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "18", "23", "17"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + decoded.requireReferenceBinding( + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "17"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "9223372036854775808", + "23", + "17")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551616")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsOversizedBundlesAndOutOfScopeTenantAuthority() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-bounds"); + assertThatThrownBy( + () -> + StartSessionAuthorityEvidenceBundle.decode( + new byte[StartSessionAuthorityEvidenceBundle.MAX_BUNDLE_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + + Map widened = mutableValue(tuple); + Map authority = object(widened.get("authorityTuple")); + authority.put( + "tenantAuthorityGeneration", + Map.of(TENANT_ID.toString(), 5L, UUID.randomUUID().toString(), 2L)); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(canonical(widened))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "bundle codec contract"); + return StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR_ID, action); + } + + private static Map validValue( + StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = TENANT_ID.toString(); + Map projection = + new LinkedHashMap<>( + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + EVALUATED_AT, + "expiresAt", + EXPIRES_AT)); + Map identity = + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + new LinkedHashMap<>( + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of())); + Map evidence = + new LinkedHashMap<>( + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + return new LinkedHashMap<>( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence)); + } + + private static Map mutableValue( + StartSessionPreAuthorizationReservationTuple tuple) throws Exception { + return read(canonical(validValue(tuple))); + } + + private static StartSessionAuthorityEvidenceBundle.BundleReference reference() { + return new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + } + + private static byte[] canonical(Object value) throws IOException { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static Map read(byte[] bytes) throws IOException { + return JSON.readValue(bytes, new TypeReference<>() {}); + } + + @SuppressWarnings("unchecked") + private static Map object(Object value) { + return (Map) value; + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java new file mode 100644 index 0000000000..067ace1439 --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java @@ -0,0 +1,223 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionPostAuthorizationExecutionTupleTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + + @Test + void retainsTheCompletePreTupleAndExactAuthorityEvidenceThroughCanonicalRoundTrip() + throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = create("post-tuple-roundtrip"); + byte[] bytes = tuple.canonicalBytes(); + StartSessionPostAuthorizationExecutionTuple decoded = + StartSessionPostAuthorizationExecutionTuple.decode(bytes); + + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + assertThat(decoded.preAuthorizationTuple().canonicalJson()) + .isEqualTo(tuple.preAuthorizationTuple().canonicalJson()); + assertThat(decoded.controlPlaneRequestId()).isEqualTo("post-tuple-roundtrip"); + assertThat(decoded.mutationDigest()).matches("[0-9a-f]{64}"); + assertThat(decoded.issuanceKind()).isEqualTo("human_operator"); + assertThat(decoded.authenticatedWorkloadIdentity()).isEqualTo(WORKLOAD); + assertThat(decoded.authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(decoded.reservationOwnerId()).isEqualTo(RESERVATION_OWNER); + assertThat(decoded.reservationClaimFence()).isEqualTo(19L); + assertThat(decoded.issuanceFence()).isEqualTo("23"); + assertJsonNumber(decoded.authorityTuple().get("accountAuthorityGeneration"), 2L); + assertJsonNumber(decoded.membershipVersion().get(TENANT.toString()), 5L); + } + + @Test + void rejectsWorkloadFingerprintReferenceAndDirectTupleSubstitution() throws Exception { + StartSessionPreAuthorizationReservationTuple pre = preTuple("post-tuple-substitution"); + byte[] bundle = bundle(pre, "17"); + StartSessionAuthorityEvidenceBundle.BundleReference reference = reference("17"); + + assertThatThrownBy( + () -> + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/another-runtime/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + bundle, + reference)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("same-namespace"); + assertThatThrownBy( + () -> + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + WORKLOAD, + "sha256:" + "b".repeat(64), + RESERVATION_OWNER, + 19L, + bundle, + reference)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("fingerprint"); + assertThatThrownBy( + () -> + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, WORKLOAD, FINGERPRINT, RESERVATION_OWNER, 19L, bundle, reference("18"))) + .isInstanceOf(IllegalArgumentException.class); + + Map changed = + JSON.readValue(tupleBytes(create("post-tuple-substitution")), Map.class); + changed.put("controlPlaneRequestId", "different-request"); + byte[] changedBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(changed)); + assertThatThrownBy(() -> StartSessionPostAuthorizationExecutionTuple.decode(changedBytes)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void returnsDefensiveEvidenceCopiesAndRejectsNonCanonicalOrUnknownTupleFields() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = create("post-tuple-defensive"); + byte[] exposedTuple = tuple.canonicalBytes(); + byte[] exposedBundle = tuple.authorityEvidenceBundleBytes(); + exposedTuple[0] = (byte) '!'; + exposedBundle[0] = (byte) '!'; + assertThat(tuple.canonicalBytes()[0]).isNotEqualTo((byte) '!'); + assertThat(tuple.authorityEvidenceBundleBytes()[0]).isNotEqualTo((byte) '!'); + + assertThatThrownBy( + () -> + StartSessionPostAuthorizationExecutionTuple.decode( + (tuple.canonicalJson() + " ") + .getBytes(java.nio.charset.StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + Map unknown = JSON.readValue(tuple.canonicalBytes(), Map.class); + unknown.put("authorizationReference", "not persisted here"); + byte[] unknownBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(unknown)); + assertThatThrownBy(() -> StartSessionPostAuthorizationExecutionTuple.decode(unknownBytes)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static StartSessionPostAuthorizationExecutionTuple create(String requestId) { + StartSessionPreAuthorizationReservationTuple pre = preTuple(requestId); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, WORKLOAD, FINGERPRINT, RESERVATION_OWNER, 19L, bundle(pre, "17"), reference("17")); + } + + private static StartSessionPreAuthorizationReservationTuple preTuple(String requestId) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt"); + return StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); + } + + private static byte[] bundle(StartSessionPreAuthorizationReservationTuple tuple, String version) { + String tenantId = TENANT.toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", version, + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map identity = + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException(exception); + } + } + + private static StartSessionAuthorityEvidenceBundle.BundleReference reference(String version) { + return new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, version, "23", "18446744073709551615"); + } + + private static byte[] tupleBytes(StartSessionPostAuthorizationExecutionTuple tuple) { + return tuple.canonicalBytes(); + } + + private static void assertJsonNumber(Object actual, long expected) { + assertThat(actual).isInstanceOf(Number.class); + assertThat(((Number) actual).longValue()).isEqualTo(expected); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java new file mode 100644 index 0000000000..3f881b6d5e --- /dev/null +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.common.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class StartSessionPreAuthorizationReservationTupleTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OTHER_ACTOR_ID = + UUID.fromString("a44b728e-b58f-4fc1-a891-7644baef6ddc"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + + @Test + void canonicalBytesMatchThePreAuthorizationReservationTupleV1Encoding() { + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-contract-01", ACTOR_ID, action(StartSessionOperatorAction.ClientIp.absent())); + String expected = + "{\"actionFamily\":\"StartSession\"," + + "\"actionFamilyRequestIdentity\":{\"requestId\":\"tuple-contract-01\"," + + "\"requestIdentityKind\":\"controlPlaneRequestId\"}," + + "\"actionFamilySchemaId\":\"firemud.game-session.start-session\"," + + "\"actionFamilySchemaVersion\":\"1\"," + + "\"actor\":{\"accountId\":\"a4f5f4eb-8243-4d42-903a-33495456a622\"," + + "\"kind\":\"HUMAN\"}," + + "\"auditReason\":\"tuple codec contract\"," + + "\"automationPolicy\":{\"presence\":\"ABSENT\"}," + + "\"expectedVersion\":{\"presence\":\"ABSENT\"}," + + "\"mutation\":{\"clientIp\":{\"presence\":\"ABSENT\"}}," + + "\"scope\":{\"targetNamespace\":\"world-runtime\"," + + "\"tenantId\":\"9f8f06b4-36e5-4d11-9c2a-5adfd7f41531\"}," + + "\"target\":{\"gameTemplateId\":\"91\"," + + "\"ownerAccountId\":\"36aa9ce5-0ebc-4c14-9f6b-d160edc6059a\"}," + + "\"targetOwner\":{\"ownerService\":\"game-session-service\"}," + + "\"tupleSchemaId\":\"preAuthorizationReservationTuple\"," + + "\"tupleSchemaVersion\":\"1\"}"; + + assertThat(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(expected.getBytes(StandardCharsets.UTF_8)); + assertThat( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(expected) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)) + .containsExactly(expected.getBytes(StandardCharsets.UTF_8)); + assertThat(tuple.mutationDigest()) + .isEqualTo(StartSessionOperatorActionCodec.mutationDigest(tuple.action())); + } + + @Test + void roundTripsTypedContentsAndSameRequestIdWithDifferentActorIsAConflict() { + StartSessionOperatorAction action = + action(StartSessionOperatorAction.ClientIp.of("203.0.113.8")); + StartSessionPreAuthorizationReservationTuple original = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-conflict-01", ACTOR_ID, action); + StartSessionPreAuthorizationReservationTuple rehydrated = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(original.canonicalJson()); + StartSessionPreAuthorizationReservationTuple changedActor = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-conflict-01", OTHER_ACTOR_ID, action); + + assertThat(rehydrated).isEqualTo(original); + assertThat(rehydrated.canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(rehydrated.mutationDigest()).isEqualTo(original.mutationDigest()); + assertThat(changedActor.controlPlaneRequestId()).isEqualTo(original.controlPlaneRequestId()); + assertThat(changedActor).isNotEqualTo(original); + assertThat(changedActor.canonicalJson()).isNotEqualTo(original.canonicalJson()); + // The action digest excludes reservation identity and actor; it cannot replace tuple + // comparison. + assertThat(changedActor.mutationDigest()).isEqualTo(original.mutationDigest()); + assertThat(original.canonicalJson()) + .contains("\"clientIp\":{\"presence\":\"PRESENT\",\"value\":\"203.0.113.8\"}"); + } + + @Test + void strictDecoderRejectsNoncanonicalAndUnsupportedTupleShapes() { + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "tuple-strict-01", ACTOR_ID, action(StartSessionOperatorAction.ClientIp.absent())); + String json = tuple.canonicalJson(); + String withUnknownRootField = + json.replace( + "\"tupleSchemaVersion\":\"1\"}", "\"tupleSchemaVersion\":\"1\",\"unexpected\":true}"); + String missingTargetOwner = + json.replace(",\"targetOwner\":{\"ownerService\":\"game-session-service\"}", ""); + String invalidExpectedVersion = + json.replace( + "\"expectedVersion\":{\"presence\":\"ABSENT\"}", + "\"expectedVersion\":{\"presence\":\"PRESENT\"}"); + String invalidActorKind = json.replace("\"kind\":\"HUMAN\"", "\"kind\":\"WORKLOAD\""); + + assertThatThrownBy( + () -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(" " + json)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical JSON"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + withUnknownRootField)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(missingTargetOwner)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + invalidExpectedVersion)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("expectedVersion"); + assertThatThrownBy( + () -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(invalidActorKind)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("actor must be human"); + } + + private static StartSessionOperatorAction action(StartSessionOperatorAction.ClientIp clientIp) { + return new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + "tuple codec contract"); + } +} diff --git a/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json b/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json new file mode 100644 index 0000000000..a1874220fa --- /dev/null +++ b/services/common-platform-core/src/test/resources/operator/start-session-mutation-digest-v1-vectors.json @@ -0,0 +1,167 @@ +{ + "schemaId": "firemud.game-session.start-session", + "schemaVersion": "1", + "vectors": [ + { + "name": "base", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "f81e35e943d51078a1d1c5eb7f3175bedbd7e704f55fe7b450050b852dd62e29" + }, + { + "name": "changed-target", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"43\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343331343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "5c736b3aa5c0772f0edef9fbf00a60b585ab99cccf774cb08196f7eb5cca346d" + }, + { + "name": "changed-scope", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"44444444-4444-4444-8444-444444444444\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a34343434343434342d343434342d343434342d383434342d34343434343434343434343431353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "cdb171f110e99654085d935f9dd0c9d0dd46877272976080b01f84320ec45008" + }, + { + "name": "changed-audit-reason", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"operator launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131353a6f70657261746f72206c61756e6368", + "digest": "43ac8a4e4c8618c090ed7cd298a223e42dffca4519c7a1c38509b8cc1eb16867" + }, + { + "name": "client-ip-absent", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743132343a313a31383a636c69656e744970363a616273656e7430303a31313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "01b67879242b7213c9dd9dafbed8a4ed5cbec72ba671d9a04c263bf3b52e3195" + }, + { + "name": "client-ip-empty", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"\"},\"auditReason\":\"scheduled launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743132343a313a31383a636c69656e744970363a737472696e6731303a31313a6175646974526561736f6e363a737472696e673131363a7363686564756c6564206c61756e6368", + "digest": "880d0f5718ce3f1150d559b6e1df62bbe22249cfb95774b3040715be29966ec1" + }, + { + "name": "unicode-composed", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"caf\\u00e9 launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131323a636166c3a9206c61756e6368", + "digest": "7dd8d54b05c485e62d580b1b31bbdc0d6e5634d0caaf234a643d1cc46a5dab09" + }, + { + "name": "unicode-decomposed", + "accepted": true, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"cafe\\u0301 launch\"}", + "preimageHex": "31373a6d75746174696f6e4469676573742f763132303a616374696f6e46616d696c79536368656d614964363a737472696e673133343a666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e32353a616374696f6e46616d696c79536368656d6156657273696f6e363a737472696e6731313a31353a73636f7065363a6f626a6563743139373a313a32383a74656e616e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231353a7461726765744e616d657370616365363a737472696e6731373a666972656d7564363a746172676574363a6f626a6563743139383a313a3231343a67616d6554656d706c6174654964363a737472696e6731323a343231343a6f776e65724163636f756e744964363a737472696e673133363a33333333333333332d333333332d343333332d383333332d33333333333333333333333331353a657870656374656456657273696f6e363a616273656e7430303a383a6d75746174696f6e363a6f626a6563743133333a313a31383a636c69656e744970363a737472696e6731393a3139322e302e322e3131313a6175646974526561736f6e363a737472696e673131323a636166c3a9206c61756e6368", + "digest": "7dd8d54b05c485e62d580b1b31bbdc0d6e5634d0caaf234a643d1cc46a5dab09" + }, + { + "name": "client-ip-null", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":null},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "expected-version-null", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"expectedVersion\":null,\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "expected-version-present", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"expectedVersion\":1,\"mutation\":{\"clientIp\":\"192.0.2.1\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "wrong-type-client-ip", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":7},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "duplicate-root-key", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "normalized-key-collision", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"t\\u00e9\":\"x\",\"te\\u0301\":\"y\"},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "unknown-member", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{\"clientIp\":\"192.0.2.1\",\"extra\":true},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "missing-audit-reason", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{}}" + }, + { + "name": "wrong-scope-member-order", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"targetNamespace\":\"firemud\",\"tenantId\":\"22222222-2222-4222-8222-222222222222\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "malformed-unicode", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"\\uD800\"}" + }, + { + "name": "invalid-utf8", + "accepted": false, + "rawHex": "7b22616374696f6e46616d696c79536368656d614964223a22666972656d75642e67616d652d73657373696f6e2e73746172742d73657373696f6e222c22616374696f6e46616d696c79536368656d6156657273696f6e223a2231222c2273636f7065223a7b2274656e616e744964223a2232323232323232322d323232322d343232322d383232322d323232323232323232323232222c227461726765744e616d657370616365223a22666972656d7564227d2c22746172676574223a7b2267616d6554656d706c6174654964223a223432222c226f776e65724163636f756e744964223a2233333333333333332d333333332d343333332d383333332d333333333333333333333333227d2c226d75746174696f6e223a7b22636c69656e744970223a223139322e302e322e31227d2c226175646974526561736f6e223a22ff227d" + }, + { + "name": "numeric-template-id-rejected", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":42,\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "non-canonical-template-id-string", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"042\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "template-id-overflow-rejected", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"9223372036854775808\",\"ownerAccountId\":\"33333333-3333-4333-8333-333333333333\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + }, + { + "name": "nil-owner-account-id", + "accepted": false, + "input": "{\"actionFamilySchemaId\":\"firemud.game-session.start-session\",\"actionFamilySchemaVersion\":\"1\",\"scope\":{\"tenantId\":\"22222222-2222-4222-8222-222222222222\",\"targetNamespace\":\"firemud\"},\"target\":{\"gameTemplateId\":\"42\",\"ownerAccountId\":\"00000000-0000-0000-0000-000000000000\"},\"mutation\":{},\"auditReason\":\"scheduled launch\"}" + } + ], + "grammarVectors": [ + {"name": "absent", "kind": "absent", "canonicalValueHex": "363a616273656e7430303a"}, + {"name": "null", "kind": "raw", "rawValue": "null", "canonicalValueHex": "343a6e756c6c31303a"}, + {"name": "number-one", "kind": "raw", "rawValue": "1", "canonicalValueHex": "363a6e756d62657231313a31"}, + {"name": "string-one", "kind": "raw", "rawValue": "\"1\"", "canonicalValueHex": "363a737472696e6731313a31"}, + {"name": "number-ten-trailing-zeroes", "kind": "raw", "rawValue": "10.000", "canonicalValueHex": "363a6e756d62657231323a3130"}, + {"name": "number-negative-decimal", "kind": "raw", "rawValue": "-12.3400", "canonicalValueHex": "363a6e756d62657231363a2d31322e3334"}, + {"name": "number-signed-zero", "kind": "raw", "rawValue": "-0.00", "canonicalValueHex": "363a6e756d62657231313a30"}, + {"name": "number-zero", "kind": "raw", "rawValue": "0", "canonicalValueHex": "363a6e756d62657231313a30"}, + {"name": "array-order", "kind": "raw", "rawValue": "[1,\"1\",null]", "canonicalValueHex": "353a61727261793133363a313a33363a6e756d62657231313a31363a737472696e6731313a31343a6e756c6c31303a"}, + {"name": "unicode-key-composed", "kind": "raw", "rawValue": "{\"\\u00e9\":\"x\"}", "canonicalValueHex": "363a6f626a6563743131393a313a31323ac3a9363a737472696e6731313a78"}, + {"name": "unicode-key-decomposed", "kind": "raw", "rawValue": "{\"e\\u0301\":\"x\"}", "canonicalValueHex": "363a6f626a6563743131393a313a31323ac3a9363a737472696e6731313a78"}, + {"name": "malformed-surrogate-rejected", "kind": "reject", "rawValue": "\"\\uD800\""}, + {"name": "nesting-depth-rejected", "kind": "reject", "rawValue": "[[[[[[[[[0]]]]]]]]]"}, + {"name": "duplicate-object-key-rejected", "kind": "reject", "rawValue": "{\"a\":1,\"a\":2}"}, + {"name": "normalized-object-key-collision-rejected", "kind": "reject", "rawValue": "{\"\\u00e9\":1,\"e\\u0301\":2}"}, + {"name": "number-space-prefix-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": " 1"}, + {"name": "number-space-suffix-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1 "}, + {"name": "number-trailing-point-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1."}, + {"name": "number-leading-point-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": ".5"}, + {"name": "number-nan-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "NaN"}, + {"name": "number-infinity-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "Infinity"}, + {"name": "number-negative-infinity-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "-Infinity"}, + {"name": "number-exponent-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "1e3"}, + {"name": "number-plus-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "+1"}, + {"name": "number-leading-zero-lexeme-rejected", "kind": "numberLexeme", "accepted": false, "rawLexeme": "01"}, + {"name": "number-exponent-rejected", "kind": "reject", "rawValue": "1e3"}, + {"name": "number-plus-rejected", "kind": "reject", "rawValue": "+1"}, + {"name": "number-leading-zero-rejected", "kind": "reject", "rawValue": "01"} + ] +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventory.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventory.java new file mode 100644 index 0000000000..66b7acc2b1 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventory.java @@ -0,0 +1,311 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; + +/** Closed exact Game Design source inventory; it does not export or attest release objects. */ +public final class SelectedDraftAssetInventory { + public static final String SCHEMA = "game-design-selected-draft-asset-inventory/v1"; + + private final PublicationDigestRequestBinding request; + private final GameDesignPublicationOperation operation; + private final GameDesignSourceRepository.Genesis sourceGenesis; + private final GameDesignSourceRepository.Capture sourceCapture; + private final GameDesignSourceRepository.SynchronizedSources selectedSources; + private final SelectedDraftGameLogicReceipt gameLogicReceipt; + private final Map sourceFamilyDeclarations; + private final List assets; + private final byte[] canonicalBytes; + private final String digest; + + SelectedDraftAssetInventory( + PublicationDigestRequestBinding request, + GameDesignPublicationOperation operation, + GameDesignSourceRepository.Genesis sourceGenesis, + GameDesignSourceRepository.Capture sourceCapture, + GameDesignSourceRepository.SynchronizedSources selectedSources, + SelectedDraftGameLogicReceipt gameLogicReceipt, + List assets) { + this.request = Objects.requireNonNull(request, "request"); + this.operation = Objects.requireNonNull(operation, "operation"); + this.sourceGenesis = Objects.requireNonNull(sourceGenesis, "sourceGenesis"); + this.sourceCapture = Objects.requireNonNull(sourceCapture, "sourceCapture"); + this.selectedSources = Objects.requireNonNull(selectedSources, "selectedSources"); + this.gameLogicReceipt = Objects.requireNonNull(gameLogicReceipt, "gameLogicReceipt"); + this.assets = List.copyOf(Objects.requireNonNull(assets, "assets")); + + var selected = operation.account().input().selection().selectedCommit(); + if (request.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION + || !request.derivedWorkflowIdentity().equals(operation.workflowId()) + || !selected.target().equals(sourceGenesis.policy().target()) + || !selected.target().equals(sourceGenesis.command().target()) + || !selected.target().equals(sourceGenesis.asset().target()) + || !selected.target().equals(sourceGenesis.gameplay().target()) + || !selected.target().equals(sourceGenesis.branding().target()) + || !selected.target().equals(sourceGenesis.templateConfig().target()) + || !selected.equals(selectedSources.command().binding()) + || !selected.equals(sourceCapture.command().snapshot().binding()) + || !Arrays.equals( + operation.canonicalBytes(), sourceCapture.command().operation().canonicalBytes()) + || !selected.equals(gameLogicReceipt.selection().selectedCommit())) { + throw new IllegalArgumentException( + "Inventory evidence differs from exact selected operation"); + } + + var branding = selectedSources.branding().orElseThrow(); + var template = selectedSources.templateConfig().orElseThrow(); + var declarations = new TreeMap(); + declarations.put("ORDINARY", state(selectedSources.asset().items().isEmpty())); + branding + .roleDeclarations() + .forEach((role, value) -> declarations.put("BRANDING:" + role, value)); + declarations.put("GAMEPLAY_RULE", state(selectedSources.gameplay().entries().isEmpty())); + declarations.put("TEMPLATE_CONFIG", state(template.entries().isEmpty())); + sourceFamilyDeclarations = Map.copyOf(declarations); + + var ordered = + this.assets.stream() + .sorted( + Comparator.comparing( + Asset::usageKey, + (String left, String right) -> + Arrays.compareUnsigned( + left.getBytes(StandardCharsets.UTF_8), + right.getBytes(StandardCharsets.UTF_8))) + .thenComparing(asset -> asset.family().name())) + .toList(); + if (!this.assets.equals(ordered)) { + throw new IllegalArgumentException("Selected asset entries must be in canonical key order"); + } + var keys = new java.util.HashSet(); + for (Asset asset : this.assets) { + if (!selected.target().equals(asset.sourceBinding().target()) + || !keys.add(asset.usageKey())) { + throw new IllegalArgumentException( + "Selected asset provenance or usage key collides across source families"); + } + } + canonicalBytes = canonicalJson().getBytes(StandardCharsets.UTF_8); + digest = CommandSource.sha256(canonicalBytes); + } + + private static String state(boolean empty) { + return empty ? "EMPTY" : "PRESENT"; + } + + public PublicationDigestRequestBinding request() { + return request; + } + + public GameDesignPublicationOperation operation() { + return operation; + } + + public DraftCommitBinding selectedCommit() { + return operation.account().input().selection().selectedCommit(); + } + + public GameDesignSourceRepository.Genesis sourceGenesis() { + return sourceGenesis; + } + + /** Retains the complete six-family frozen capture, including non-asset source families. */ + public GameDesignSourceRepository.Capture sourceCapture() { + return sourceCapture; + } + + /** Retains the complete selected synchronized snapshots; World artifacts remain in operation. */ + public GameDesignSourceRepository.SynchronizedSources selectedSources() { + return selectedSources; + } + + public SelectedDraftGameLogicReceipt gameLogicReceipt() { + return gameLogicReceipt; + } + + /** EMPTY values are derived only from exact captured and selected owner snapshots. */ + public Map sourceFamilyDeclarations() { + return sourceFamilyDeclarations; + } + + public List assets() { + return assets; + } + + public String canonicalJson() { + var capture = + Map.of( + "command", encoded(sourceCapture.command().canonicalBytes()), + "policy", encoded(sourceCapture.policy().canonicalBytes()), + "ordinary", encoded(sourceCapture.asset().canonicalBytes()), + "branding", encoded(sourceCapture.branding().canonicalBytes()), + "templateConfig", encoded(sourceCapture.templateConfig().canonicalBytes())); + var snapshots = + Map.of( + "command", selectedSources.command().canonicalJson(), + "policy", selectedSources.policy().canonicalJson(), + "ordinary", selectedSources.asset().canonicalJson(), + "gameplay", selectedSources.gameplay().canonicalJson(), + "branding", selectedSources.branding().orElseThrow().canonicalJson(), + "templateConfig", selectedSources.templateConfig().orElseThrow().canonicalJson()); + var receipt = + Map.of( + "selection", encoded(gameLogicReceipt.selection().canonicalBytes()), + "authorization", encoded(gameLogicReceipt.authorization().canonicalBytes()), + "terminal", encoded(gameLogicReceipt.receipt().canonicalBytes())); + return CommandSource.canonical( + Map.ofEntries( + Map.entry("schema", SCHEMA), + Map.entry("requestPreimageBase64", encoded(request.canonicalPreimage())), + Map.entry("requestDigest", request.requestDigest()), + Map.entry("operationBase64", encoded(operation.canonicalBytes())), + Map.entry("selectedCommitJson", selectedCommit().canonicalJson()), + Map.entry("selectedCommitDigest", selectedCommit().digest()), + Map.entry("sourceGenesis", genesisObject()), + Map.entry("sourceCapture", capture), + Map.entry("selectedSnapshots", snapshots), + Map.entry("gameLogicReceipt", receipt), + Map.entry("sourceFamilyDeclarations", new TreeMap<>(sourceFamilyDeclarations)), + Map.entry("assets", assets.stream().map(Asset::object).toList()))); + } + + private Map genesisObject() { + var target = selectedCommit().target(); + return Map.ofEntries( + Map.entry("canonicalTenantId", target.canonicalTenantId().toString()), + Map.entry("canonicalVersionId", target.canonicalVersionId().toString()), + Map.entry("gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId())), + Map.entry("gameDesignVersionTenantKey", target.gameDesignVersionTenantKey()), + Map.entry("sourceGameRowId", Long.toString(target.sourceGameRowId())), + Map.entry("sourceGameTenantKey", target.sourceGameTenantKey()), + Map.entry("sourceProvenanceKind", target.sourceProvenanceKind()), + Map.entry( + "command", + genesisRecord( + sourceGenesis.command().receiptId(), + sourceGenesis.command().creationTransactionId())), + Map.entry( + "policy", + genesisRecord( + sourceGenesis.policy().receiptId(), + sourceGenesis.policy().creationTransactionId())), + Map.entry( + "ordinary", + genesisRecord( + sourceGenesis.asset().receiptId(), sourceGenesis.asset().creationTransactionId())), + Map.entry( + "gameplay", + Map.of( + "receiptId", sourceGenesis.gameplay().receiptId().toString(), + "creationTransactionId", sourceGenesis.gameplay().creationTransactionId(), + "emptyInventoryJson", sourceGenesis.gameplay().inventory().canonicalJson())), + Map.entry( + "branding", + genesisRecord( + sourceGenesis.branding().receiptId(), + sourceGenesis.branding().creationTransactionId())), + Map.entry( + "templateConfig", + genesisRecord( + sourceGenesis.templateConfig().receiptId(), + sourceGenesis.templateConfig().creationTransactionId()))); + } + + private static Map genesisRecord(UUID receiptId, String creationTransactionId) { + return Map.of( + "receiptId", receiptId.toString(), "creationTransactionId", creationTransactionId); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + private static String encoded(byte[] bytes) { + return Base64.getEncoder().encodeToString(bytes); + } + + public enum Family { + ORDINARY, + BRANDING + } + + /** Exact original source provenance and actual tenant-qualified owner bytes. */ + public record Asset( + Family family, + String role, + String usageKey, + String assetRowId, + String requiredness, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId, + String contentType, + String contentDigest, + byte[] contentBytes) { + public Asset { + Objects.requireNonNull(family, "family"); + Objects.requireNonNull(sourceBinding, "sourceBinding"); + DraftAuthorizationFenceBinding.requireUuid(revisionId); + if (role == null + || role.isBlank() + || family == Family.ORDINARY && !AssetSource.ROLE.equals(role) + || family == Family.BRANDING + && Arrays.stream(BrandingSource.Role.values()) + .noneMatch(value -> value.name().equals(role)) + || usageKey == null + || usageKey.isBlank() + || "manifest.json".equals(usageKey) + || assetRowId == null + || !assetRowId.matches("[1-9][0-9]*") + || !"REQUIRED".equals(requiredness) + || revisionOrder == null + || !revisionOrder.matches("0|[1-9][0-9]*") + || contentType == null + || contentType.isBlank() + || contentDigest == null + || !contentDigest.matches("sha256:[0-9a-f]{64}") + || contentBytes == null + || !CommandSource.sha256(contentBytes).equals(contentDigest)) { + throw new IllegalArgumentException( + "Exact required source asset bytes and metadata required"); + } + contentBytes = contentBytes.clone(); + } + + @Override + public byte[] contentBytes() { + return contentBytes.clone(); + } + + private Map object() { + return Map.ofEntries( + Map.entry("family", family.name()), + Map.entry("role", role), + Map.entry("usageKey", usageKey), + Map.entry("assetRowId", assetRowId), + Map.entry("requiredness", requiredness), + Map.entry("sourceBindingJson", sourceBinding.canonicalJson()), + Map.entry("sourceBindingDigest", sourceBinding.digest()), + Map.entry("revisionOrder", revisionOrder), + Map.entry("revisionId", revisionId.toString()), + Map.entry("contentType", contentType), + Map.entry("contentDigest", contentDigest), + Map.entry("byteSize", Long.toString(contentBytes.length)), + Map.entry("contentBase64", encoded(contentBytes))); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadService.java new file mode 100644 index 0000000000..e917cbfed0 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadService.java @@ -0,0 +1,523 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Read-only selected source inventory producer; it neither writes release objects nor finalizes. + */ +public final class SelectedDraftAssetInventoryReadService { + private final OwnerRead owner; + private final TransactionTemplate snapshot; + + public SelectedDraftAssetInventoryReadService( + DSLContext dsl, PlatformTransactionManager transactions) { + this( + new RepositoryOwnerRead( + new GameDesignPublicationOperationRepository(Objects.requireNonNull(dsl, "dsl")), + new GameDesignSourceRepository(dsl), + new SelectedDraftGameLogicReceiptRepository(dsl), + dsl), + transactions); + } + + SelectedDraftAssetInventoryReadService(OwnerRead owner, PlatformTransactionManager transactions) { + this.owner = Objects.requireNonNull(owner, "owner"); + snapshot = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + snapshot.setName("game-design-selected-draft-asset-inventory-read"); + snapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + snapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + snapshot.setReadOnly(true); + } + + /** Reads one exact complete inventory inside an independent owner-local database snapshot. */ + public SelectedDraftAssetInventory read(PublicationDigestRequestBinding request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent selected asset inventory snapshot required") + .asRuntimeException(); + } + validateRequest(request); + try { + return Objects.requireNonNull( + snapshot.execute(ignored -> readSnapshot(request)), + "Selected asset inventory snapshot returned no result"); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (DataAccessException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Selected asset inventory readback unavailable") + .withCause(unavailable) + .asRuntimeException(); + } catch (RuntimeException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact selected asset inventory evidence unavailable") + .withCause(invalid) + .asRuntimeException(); + } + } + + private SelectedDraftAssetInventory readSnapshot(PublicationDigestRequestBinding request) { + var readback = + owner + .read(request.derivedWorkflowIdentity()) + .orElseThrow( + () -> + Status.NOT_FOUND + .withDescription("Selected publication operation unavailable") + .asRuntimeException()); + GameDesignPublicationOperation operation = readback.operation(); + requireOperationCorrelation(operation, request); + if (!"PENDING".equals(readback.outcome())) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected publication operation is no longer pending") + .asRuntimeException(); + } + + owner.requireExactSelection(operation); + TargetProof target = operation.account().input().selection().target(); + GameDesignSourceRepository.Genesis genesis = + owner + .readGenesis(target) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Complete actual Game Design source genesis unavailable") + .asRuntimeException()); + GameDesignSourceRepository.Capture capture = + owner + .readSourceCapture(operation) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Complete selected source capture unavailable") + .asRuntimeException()); + requireCapture(operation, capture); + + DraftCommitBinding selected = operation.account().input().selection().selectedCommit(); + GameDesignSourceRepository.SynchronizedSources sources = + owner + .readSynchronized(selected.target(), selected.commitId()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Complete synchronized selected sources unavailable") + .asRuntimeException()); + requireFrozenSources(selected, capture, sources); + requireGenesisMatches(target, genesis, sources); + + SelectedDraftGameLogicReceipt receipt = + owner + .readGameLogicReceipt(request) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact retained Game Logic source receipt unavailable") + .asRuntimeException()); + requireGameLogicConsumerEvidence(operation, selected, sources, receipt); + + List pendingAssets = pendingAssets(selected.target(), sources); + List assets = new ArrayList<>(); + for (PendingAsset pending : pendingAssets) { + AssetBytes actual = + owner + .readAssetBytes(selected.target().gameDesignVersionTenantKey(), pending.assetRowId()) + .orElseThrow( + () -> + new IllegalStateException( + "Exact tenant-qualified selected asset bytes unavailable")); + byte[] bytes = actual.contentBytes(); + if (!pending.usageKey().equals(actual.fileName()) + || !pending.contentType().equals(actual.contentType()) + || !pending.contentDigest().equals(CommandSource.sha256(bytes)) + || pending.byteSize() != bytes.length) { + throw new IllegalStateException("Selected asset bytes differ from owner source snapshot"); + } + assets.add( + new SelectedDraftAssetInventory.Asset( + pending.family(), + pending.role(), + pending.usageKey(), + pending.assetRowId(), + pending.requiredness(), + pending.sourceBinding(), + pending.revisionOrder(), + pending.revisionId(), + actual.contentType(), + pending.contentDigest(), + bytes)); + } + assets.sort( + (left, right) -> + Arrays.compareUnsigned( + left.usageKey().getBytes(java.nio.charset.StandardCharsets.UTF_8), + right.usageKey().getBytes(java.nio.charset.StandardCharsets.UTF_8))); + return new SelectedDraftAssetInventory( + request, operation, genesis, capture, sources, receipt, assets); + } + + private static void requireGenesisMatches( + TargetProof selectedTarget, + GameDesignSourceRepository.Genesis genesis, + GameDesignSourceRepository.SynchronizedSources sources) { + if (!selectedTarget.equals(genesis.policy().target()) + || !selectedTarget.equals(genesis.command().target()) + || !selectedTarget.equals(genesis.asset().target()) + || !selectedTarget.equals(genesis.gameplay().target()) + || !selectedTarget.equals(genesis.branding().target()) + || !selectedTarget.equals(genesis.templateConfig().target()) + || !genesis.asset().receiptId().equals(sources.asset().genesisReceiptId()) + || !genesis.gameplay().receiptId().equals(sources.gameplay().genesisReceiptId()) + || !genesis + .branding() + .receiptId() + .equals(sources.branding().orElseThrow().genesisReceiptId()) + || !genesis + .templateConfig() + .receiptId() + .equals(sources.templateConfig().orElseThrow().genesisReceiptId())) { + throw new IllegalStateException( + "Selected snapshots differ from actual source genesis history"); + } + } + + private static List pendingAssets( + TargetProof selectedTarget, GameDesignSourceRepository.SynchronizedSources sources) { + var pending = new ArrayList(); + var usageKeys = new HashSet(); + for (AssetSnapshot.Item item : sources.asset().items()) { + var reference = item.reference(); + requireAssetReference(selectedTarget, reference.sourceBinding(), reference.usageKey()); + if (reference.requiredness() != AssetSource.Requiredness.REQUIRED + || !usageKeys.add(reference.usageKey())) { + throw new IllegalStateException("Ordinary asset requiredness or usage key is unsupported"); + } + pending.add( + new PendingAsset( + SelectedDraftAssetInventory.Family.ORDINARY, + reference.role(), + reference.usageKey(), + reference.assetRowId(), + reference.requiredness().name(), + reference.sourceBinding(), + reference.revisionOrder(), + reference.revisionId(), + item.contentType(), + item.contentDigest(), + item.byteSize())); + } + BrandingSourceSnapshot branding = sources.branding().orElseThrow(); + for (BrandingSourceSnapshot.Item item : branding.items()) { + var reference = item.reference(); + requireAssetReference(selectedTarget, reference.sourceBinding(), reference.usageKey()); + if (reference.requiredness() != BrandingSource.Requiredness.REQUIRED + || !usageKeys.add(reference.usageKey())) { + throw new IllegalStateException("Branding requiredness or cross-family key is unsupported"); + } + pending.add( + new PendingAsset( + SelectedDraftAssetInventory.Family.BRANDING, + reference.role().name(), + reference.usageKey(), + reference.assetRowId(), + reference.requiredness().name(), + reference.sourceBinding(), + reference.revisionOrder(), + reference.revisionId(), + item.contentType(), + item.contentDigest(), + item.byteSize())); + } + return List.copyOf(pending); + } + + private static void requireAssetReference( + TargetProof selectedTarget, DraftCommitBinding sourceBinding, String usageKey) { + if (!selectedTarget.equals(sourceBinding.target()) + || usageKey == null + || usageKey.isBlank() + || "manifest.json".equals(usageKey)) { + throw new IllegalStateException("Asset provenance, reserved key, or source target conflict"); + } + } + + private static void requireGameLogicConsumerEvidence( + GameDesignPublicationOperation operation, + DraftCommitBinding selected, + GameDesignSourceRepository.SynchronizedSources sources, + SelectedDraftGameLogicReceipt receipt) { + var selection = receipt.selection(); + SelectedDraftGameLogicReceipt.requireExactSelection(selection, receipt.authorization()); + if (!Arrays.equals( + operation.account().input().selection().canonicalBytes(), selection.canonicalBytes()) + || !selected.equals(selection.selectedCommit()) + || !Arrays.equals( + sources.gameplay().canonicalBytes(), receipt.authorization().source().canonicalBytes()) + || !receipt + .workflowIdentity() + .equals( + PublicationDigestRequestBinding.full( + selection.intent().canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + selection.intent().publishRequestId()) + .derivedWorkflowIdentity())) { + throw new IllegalStateException("Retained Game Logic receipt differs from selected source"); + } + + Set selectedRules = new HashSet<>(); + for (GameplayRuleSource.Entry entry : sources.gameplay().entries()) { + selectedRules.add( + entry.family().name() + ":" + entry.definition().key() + ":" + entry.revisionId()); + } + TemplateConfigSourceSnapshot template = sources.templateConfig().orElseThrow(); + for (TemplateConfigSource.Entry entry : template.entries()) { + entry.config().requireAvailableOwnerReads(); + for (TemplateConfigSource.GameplayInput input : entry.config().gameplayInputs()) { + if (!selectedRules.contains( + input.family().name() + ":" + input.key() + ":" + input.revisionId())) { + throw new IllegalStateException( + "Template Game Logic input lacks exact selected owner source evidence"); + } + } + } + } + + private static void requireCapture( + GameDesignPublicationOperation operation, GameDesignSourceRepository.Capture capture) { + byte[] operationBytes = operation.canonicalBytes(); + for (byte[] retainedOperation : + new byte[][] { + capture.command().operation().canonicalBytes(), + capture.policy().operation().canonicalBytes(), + capture.asset().operation().canonicalBytes(), + capture.branding().operation().canonicalBytes(), + capture.templateConfig().operation().canonicalBytes() + }) { + if (!Arrays.equals(operationBytes, retainedOperation)) { + throw new IllegalStateException("Frozen source capture differs from exact operation"); + } + } + } + + private static void requireFrozenSources( + DraftCommitBinding selected, + GameDesignSourceRepository.Capture frozen, + GameDesignSourceRepository.SynchronizedSources synchronizedSources) { + BrandingSourceSnapshot branding = synchronizedSources.branding().orElseThrow(); + TemplateConfigSourceSnapshot templateConfig = + synchronizedSources.templateConfig().orElseThrow(); + if (!selected.equals(synchronizedSources.command().binding()) + || !selected.equals(synchronizedSources.policy().binding()) + || !selected.equals(synchronizedSources.asset().binding()) + || !selected.equals(synchronizedSources.gameplay().binding()) + || !selected.equals(branding.binding()) + || !selected.equals(templateConfig.binding()) + || !Arrays.equals( + frozen.command().snapshot().canonicalBytes(), + synchronizedSources.command().canonicalBytes()) + || !Arrays.equals( + frozen.policy().snapshot().canonicalBytes(), + synchronizedSources.policy().canonicalBytes()) + || !Arrays.equals( + frozen.asset().snapshot().canonicalBytes(), + synchronizedSources.asset().canonicalBytes()) + || !Arrays.equals(frozen.branding().snapshot().canonicalBytes(), branding.canonicalBytes()) + || !Arrays.equals( + frozen.templateConfig().snapshot().canonicalBytes(), templateConfig.canonicalBytes())) { + throw new IllegalStateException( + "Frozen and synchronized sources differ from complete selected commit"); + } + } + + private static void requireOperationCorrelation( + GameDesignPublicationOperation operation, PublicationDigestRequestBinding request) { + var selection = operation.account().input().selection(); + var intent = selection.intent(); + TargetProof target = selection.target(); + DraftCommitBinding selected = selection.selectedCommit(); + var world = operation.world().request(); + UUID tenant; + long numericVersion; + try { + tenant = UUID.fromString(request.tenantId()); + numericVersion = Long.parseLong(request.versionId()); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Canonical tenant and numeric version required", malformed); + } + if (!tenant.toString().equals(request.tenantId()) + || numericVersion <= 0 + || !tenant.equals(target.canonicalTenantId()) + || !tenant.equals(intent.canonicalTenantId()) + || target.gameDesignVersionRowId() != numericVersion + || operation.versionId() != numericVersion + || !operation.tenantKey().equals(target.gameDesignVersionTenantKey()) + || !operation.selectionDigest().equals(selection.digest()) + || !intent.canonicalVersionId().equals(target.canonicalVersionId()) + || !intent.canonicalVersionId().equals(selected.target().canonicalVersionId()) + || !request.publishRequestId().equals(intent.publishRequestId()) + || !request.derivedWorkflowIdentity().equals(operation.workflowId()) + || !request.derivedWorkflowIdentity().equals(world.publishWorkflowId()) + || !tenant.equals(world.canonicalTenantId()) + || !intent.canonicalVersionId().equals(world.canonicalVersionId()) + || !intent.publishRequestId().equals(world.publicationRequestId()) + || !selection.digest().substring("sha256:".length()).equals(world.requestDigest()) + || !intent.expectedVersionStateEpoch().equals(Long.toString(world.versionStateEpoch())) + || !selected.commitId().toString().equals(world.appliedCommitId())) { + throw new IllegalStateException( + "Publication operation differs from canonical selected request"); + } + } + + private static void validateRequest(PublicationDigestRequestBinding request) { + if (request == null + || request.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw Status.INVALID_ARGUMENT + .withDescription("Canonical full-version publication binding required") + .asRuntimeException(); + } + try { + var canonical = + PublicationDigestRequestBinding.full( + request.tenantId(), request.versionId(), request.publishRequestId()); + UUID tenant = UUID.fromString(request.tenantId()); + if (!Arrays.equals(canonical.canonicalPreimage(), request.canonicalPreimage()) + || !canonical.requestDigest().equals(request.requestDigest()) + || !canonical.derivedWorkflowIdentity().equals(request.derivedWorkflowIdentity()) + || !tenant.toString().equals(request.tenantId())) { + throw new IllegalArgumentException("Publication request binding is not canonical"); + } + } catch (RuntimeException malformed) { + throw Status.INVALID_ARGUMENT + .withDescription("Canonical full-version publication binding required") + .withCause(malformed) + .asRuntimeException(); + } + } + + interface OwnerRead { + Optional read(String workflowIdentity); + + void requireExactSelection(GameDesignPublicationOperation operation); + + Optional readSourceCapture( + GameDesignPublicationOperation operation); + + Optional readGenesis(TargetProof target); + + Optional readSynchronized( + TargetProof target, UUID selectedCommitId); + + Optional readGameLogicReceipt( + PublicationDigestRequestBinding request); + + Optional readAssetBytes(String tenantKey, String assetRowId); + } + + record AssetBytes(String fileName, String contentType, byte[] contentBytes) { + AssetBytes { + if (contentBytes == null) throw new IllegalArgumentException("Actual owner bytes required"); + contentBytes = contentBytes.clone(); + } + + @Override + public byte[] contentBytes() { + return contentBytes.clone(); + } + } + + private record PendingAsset( + SelectedDraftAssetInventory.Family family, + String role, + String usageKey, + String assetRowId, + String requiredness, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId, + String contentType, + String contentDigest, + long byteSize) {} + + private record RepositoryOwnerRead( + GameDesignPublicationOperationRepository operations, + GameDesignSourceRepository sources, + SelectedDraftGameLogicReceiptRepository gameLogicReceipts, + DSLContext dsl) + implements OwnerRead { + private RepositoryOwnerRead { + Objects.requireNonNull(operations, "operations"); + Objects.requireNonNull(sources, "sources"); + Objects.requireNonNull(gameLogicReceipts, "gameLogicReceipts"); + Objects.requireNonNull(dsl, "dsl"); + } + + @Override + public Optional read( + String workflowIdentity) { + return operations.read(workflowIdentity); + } + + @Override + public void requireExactSelection(GameDesignPublicationOperation operation) { + operations.requireExactSelection(operation); + } + + @Override + public Optional readSourceCapture( + GameDesignPublicationOperation operation) { + return operations.readSourceCapture(operation); + } + + @Override + public Optional readGenesis(TargetProof target) { + return sources.readGenesis(target); + } + + @Override + public Optional readSynchronized( + TargetProof target, UUID selectedCommitId) { + return sources.readSynchronized(target, selectedCommitId); + } + + @Override + public Optional readGameLogicReceipt( + PublicationDigestRequestBinding request) { + return gameLogicReceipts.readForPublication(request); + } + + @Override + public Optional readAssetBytes(String tenantKey, String assetRowId) { + Record row = + dsl.fetchOne( + "SELECT file_name, content_type, data FROM game_assets WHERE tenant_id = ? AND id = ?", + tenantKey, + Long.parseLong(assetRowId)); + if (row == null) return Optional.empty(); + return Optional.of( + new AssetBytes( + row.get("file_name", String.class), + row.get("content_type", String.class), + row.get("data", byte[].class))); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java index 3cf08e7cae..cda9f41a6b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java @@ -14,11 +14,17 @@ import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import org.jooq.DSLContext; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -36,6 +42,9 @@ public final class SelectedDraftPublicationAdmissionService { private final WorldSelectedPublicationArtifactInventoryClient inventoryClient; private final SelectionReader selectionReader; private final SelectedDraftPublicationOwner owner; + private final WorldAuthoredSourceIntakeClient worldSourceIntakeClient; + private final GameAuthoredWorldSourceRepository worldSourceRepository; + private final GameAuthoredWorldSourceDeliveryRepository worldSourceDeliveryRepository; private final TransactionTemplate reservationTransaction; private final String workloadNamespace; @@ -46,6 +55,7 @@ public SelectedDraftPublicationAdmissionService( WorldSelectedDraftPublicationFreezeClient freezeClient, WorldSelectedPublicationArtifactInventoryClient inventoryClient, WorldPublishedStartLocationClient worldClient, + WorldAuthoredSourceIntakeClient worldSourceIntakeClient, String workloadNamespace) { this( transactionManager, @@ -53,6 +63,9 @@ public SelectedDraftPublicationAdmissionService( freezeClient, inventoryClient, worldClient, + worldSourceIntakeClient, + new GameAuthoredWorldSourceRepository(Objects.requireNonNull(dsl, "dsl")), + new GameAuthoredWorldSourceDeliveryRepository(dsl), new SelectedDraftPublicationOwner(Objects.requireNonNull(dsl, "dsl")), intent -> new AuthoredDraftPublishSelectionRepository( @@ -71,6 +84,9 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) WorldSelectedDraftPublicationFreezeClient freezeClient, WorldSelectedPublicationArtifactInventoryClient inventoryClient, WorldPublishedStartLocationClient worldClient, + WorldAuthoredSourceIntakeClient worldSourceIntakeClient, + GameAuthoredWorldSourceRepository worldSourceRepository, + GameAuthoredWorldSourceDeliveryRepository worldSourceDeliveryRepository, SelectedDraftPublicationOwner owner, SelectionReader selectionReader, String workloadNamespace) { @@ -78,6 +94,12 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) this.worldClient = Objects.requireNonNull(worldClient, "worldClient"); this.freezeClient = Objects.requireNonNull(freezeClient, "freezeClient"); this.inventoryClient = Objects.requireNonNull(inventoryClient, "inventoryClient"); + this.worldSourceIntakeClient = + Objects.requireNonNull(worldSourceIntakeClient, "worldSourceIntakeClient"); + this.worldSourceRepository = + Objects.requireNonNull(worldSourceRepository, "worldSourceRepository"); + this.worldSourceDeliveryRepository = + Objects.requireNonNull(worldSourceDeliveryRepository, "worldSourceDeliveryRepository"); this.selectionReader = Objects.requireNonNull(selectionReader, "selectionReader"); this.owner = Objects.requireNonNull(owner, "owner"); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -93,8 +115,9 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) } /** - * Verifies the retained selection, authenticates Account HELD, freezes World, then reads its - * exact selector before reserving locally. All remote calls complete outside SQL. + * Verifies the retained selection, authenticates Account HELD, freezes World, and reads the exact + * selector and complete source receipt before reserving locally. All owner reads complete outside + * SQL. */ public SelectedDraftPublicationOwner.Reservation admitAndReserve( AuthoredDraftPublishSelection.PublishIntent intent, @@ -176,15 +199,84 @@ public SelectedDraftPublicationOwner.Reservation admitAndReserve( requireExactWorldReadback(worldRequest, worldEvidence); new GameDesignPublicationOperationBinding( accountEvidence.request().binding(), worldEvidence, inventory); + SelectedDraftTemplateWorldSourceAssociation.SourceRead worldSourceRead = + readAndVerifyWorldSource(worldEvidence, selection.target()); return Objects.requireNonNull( reservationTransaction.execute( status -> owner.reserve( - intent, accountEvidence.request().binding(), worldEvidence, inventory)), + intent, + accountEvidence.request().binding(), + worldEvidence, + inventory, + worldSourceRead)), "Selected Draft publication reservation returned no result"); } + private SelectedDraftTemplateWorldSourceAssociation.SourceRead readAndVerifyWorldSource( + WorldPublishedStartLocationEvidence worldEvidence, + DraftCommitBinding.TargetProof selectedTarget) { + var selected = worldEvidence.request(); + java.util.UUID readRequestId = java.util.UUID.randomUUID(); + while (readRequestId.equals(selected.intakeRequestId())) { + readRequestId = java.util.UUID.randomUUID(); + } + var request = + new ByIdReadRequest( + 1, + selected.targetNamespace(), + readRequestId, + selected.intakeRequestId(), + selected.canonicalTenantId()); + var receipt = worldSourceIntakeClient.readById(request); + var worldRead = new SelectedDraftTemplateWorldSourceAssociation.SourceRead(request, receipt); + var source = + worldSourceRepository + .read( + receipt.sourceOperationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + selected.targetNamespace()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_WORLD_SOURCE_GD_RECORD_UNAVAILABLE")); + var delivery = + worldSourceDeliveryRepository + .read(receipt.sourceOperationId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_WORLD_SOURCE_DELIVERY_UNAVAILABLE")); + var expectedReceipt = + new CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest()); + if (!source.equals(receipt.source()) + || !delivery.source().equals(source) + || !delivery.request().targetNamespace().equals(selected.targetNamespace()) + || !delivery.request().intakeRequestId().equals(selected.intakeRequestId()) + || !delivery.request().canonicalTenantId().equals(selected.canonicalTenantId()) + || !delivery.request().worldSlug().equals(receipt.worldSlug()) + || !delivery.request().sourceOperationId().equals(receipt.sourceOperationId()) + || !delivery.request().expectedSourceEvidenceDigest().equals(receipt.sourceEvidenceDigest()) + || source.sourceGameRowId() != selectedTarget.sourceGameRowId() + || !source.sourceGameTenantKey().equals(selectedTarget.sourceGameTenantKey()) + || !source.provenanceKind().equals(selectedTarget.sourceProvenanceKind()) + || !WorldAuthoredSourceIntakeGrpcCodec.requestDigest(delivery.request()) + .equals(receipt.requestDigest()) + || delivery.acknowledgedReceipt().filter(ack -> !ack.equals(expectedReceipt)).isPresent()) { + throw new IllegalStateException( + "SELECTED_WORLD_SOURCE_OWNER_READBACK_CONFLICT: World, retained source, and original delivery differ"); + } + return worldRead; + } + private void requireRequestIdentity( AuthoredDraftPublishSelection.PublishIntent intent, AccountPublicationAuthorizationBinding accountBinding, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java index 76bc30f219..069f45a048 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationCommandService.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; @@ -38,6 +39,7 @@ public SelectedDraftPublicationCommandService( WorldSelectedDraftPublicationFreezeClient freezeClient, WorldSelectedPublicationArtifactInventoryClient inventoryClient, WorldPublishedStartLocationClient worldClient, + WorldAuthoredSourceIntakeClient worldSourceIntakeClient, String workloadNamespace, VersionPublishCommandServiceImpl finalizer) { this( @@ -48,6 +50,7 @@ public SelectedDraftPublicationCommandService( freezeClient, inventoryClient, worldClient, + worldSourceIntakeClient, workloadNamespace), new DatabaseDurableStateReader(dsl), finalizer); @@ -280,6 +283,8 @@ static DurableState absent() { private static final class DatabaseDurableStateReader implements DurableStateReader { private final AuthoredDraftPublishSelectionRepository selections; private final GameDesignPublicationOperationRepository operations; + private final GameDesignSourceRepository sources; + private final SelectedDraftTemplateWorldSourceAssociationRepository templateWorldSources; private DatabaseDurableStateReader(DSLContext dsl) { Objects.requireNonNull(dsl, "dsl"); @@ -287,6 +292,8 @@ private DatabaseDurableStateReader(DSLContext dsl) { new AuthoredDraftPublishSelectionRepository( dsl, new DraftCommitCoordinatorRepository(dsl)); operations = new GameDesignPublicationOperationRepository(dsl); + sources = new GameDesignSourceRepository(dsl); + templateWorldSources = new SelectedDraftTemplateWorldSourceAssociationRepository(dsl); } @Override @@ -301,7 +308,17 @@ public DurableState read( selection .map(SelectedDraftPublicationCommandService::workflowId) .orElseGet(() -> workflowId(accountBinding)); - return new DurableState(selection, operations.read(retainedWorkflow)); + Optional operation = + operations.read(retainedWorkflow); + operation.ifPresent( + retained -> + sources + .readCapture(retained.operation()) + .ifPresent( + capture -> + templateWorldSources.readExact( + retained.operation(), capture.templateConfig()))); + return new DurableState(selection, operation); } } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java index 9ad418caeb..e0d4aa3f0b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java @@ -23,11 +23,11 @@ /** * Unregistered Game Design owner entry for reserving publication of one existing synchronized - * Draft. It persists exact local selection/attempt/source state; supplied Account and World binding - * objects are structured evidence, not proof that either remote owner authenticated its producer. A - * production caller must obtain them from the authenticated Account publication producer and the - * protected World selector read. Isolated fixtures may supply synthetic values only to test this - * owner-local boundary. + * Draft. It persists exact local selection/attempt/source state; supplied Account, World, and + * World-source objects are structured evidence, not proof that either remote owner authenticated + * its producer. A production caller must obtain them from the authenticated Account publication + * producer and protected World reads. Isolated fixtures may supply synthetic values only to test + * this owner-local boundary. */ public final class SelectedDraftPublicationOwner { private final GameRepository games; @@ -35,6 +35,7 @@ public final class SelectedDraftPublicationOwner { private final AuthoredDraftPublishSelectionRepository selections; private final PublishAttemptRepository attempts; private final GameDesignPublicationOperationRepository operations; + private final SelectedDraftTemplateWorldSourceAssociationRepository templateWorldSources; public SelectedDraftPublicationOwner(DSLContext dsl) { Objects.requireNonNull(dsl, "dsl"); @@ -44,22 +45,25 @@ public SelectedDraftPublicationOwner(DSLContext dsl) { selections = new AuthoredDraftPublishSelectionRepository(dsl, coordinator); attempts = new PublishAttemptRepository(dsl); operations = new GameDesignPublicationOperationRepository(dsl); + templateWorldSources = new SelectedDraftTemplateWorldSourceAssociationRepository(dsl); } /** - * Retains a first or exact-replay selection and the original external publication inputs in one - * caller-owned writable READ_COMMITTED transaction. The immutable selection determines attempt - * identity; an old full-publish digest is never rewritten or upgraded here. + * Retains a first selection and its original external publication inputs in one caller-owned + * writable READ_COMMITTED transaction. Existing operations only exact-read their original source + * relation; an old full-publish digest is never rewritten or upgraded here. */ public Reservation reserve( AuthoredDraftPublishSelection.PublishIntent intent, AccountPublicationAuthorizationBinding account, WorldPublishedStartLocationEvidence world, - WorldSelectedPublicationArtifactInventoryEvidence inventory) { + WorldSelectedPublicationArtifactInventoryEvidence inventory, + SelectedDraftTemplateWorldSourceAssociation.SourceRead worldSourceRead) { requireWritableReadCommittedTransaction(); Objects.requireNonNull(intent, "intent"); Objects.requireNonNull(account, "account"); Objects.requireNonNull(world, "world"); + Objects.requireNonNull(worldSourceRead, "worldSourceRead"); Version identityCandidate = versions @@ -106,6 +110,14 @@ public Reservation reserve( throw new IllegalStateException("SELECTED_PUBLICATION_OPERATION_BINDING_CHANGED"); } + var priorOperation = operations.read(operation.workflowId()); + if (priorOperation.isPresent() + && !Arrays.equals( + operation.canonicalBytes(), + priorOperation.orElseThrow().operation().canonicalBytes())) { + throw new IllegalStateException("SELECTED_PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + } + if (!tenantKey.equals(selection.target().gameDesignVersionTenantKey())) { throw new IllegalStateException("SELECTED_PUBLICATION_TENANT_KEY_CHANGED"); } @@ -135,6 +147,8 @@ public Reservation reserve( } var capture = operations.reserveSourceBacked(operation); + templateWorldSources.retainOrRead( + operation, capture.templateConfig(), worldSourceRead, priorOperation.isEmpty()); var retained = operations .read(operation.workflowId()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociation.java new file mode 100644 index 0000000000..4ec94a53b1 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociation.java @@ -0,0 +1,293 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; + +/** + * Immutable relation between one captured selected template and the exact World-authored source + * returned for the original publication freeze. Structured evidence is not producer authority; + * production admission obtains it from authenticated World and owner-local reads. + */ +public final class SelectedDraftTemplateWorldSourceAssociation { + private static final String SCHEMA = "game-design-selected-template-world-source-association/v1"; + + private SelectedDraftTemplateWorldSourceAssociation() {} + + /** + * Exact by-ID request and complete public World response, including the independent read echo. + */ + public record SourceRead(ByIdReadRequest request, PublicReceipt receipt) { + public SourceRead { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(receipt, "receipt"); + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse(request, receipt); + } + + public byte[] requestBytes() { + return WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(request).toByteArray(); + } + + public byte[] responseBytes() { + return WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse(request, receipt).toByteArray(); + } + } + + /** Canonical frozen row to retain; the public World response contains no World-private keys. */ + public static final class Association { + private final UUID canonicalTenantId; + private final UUID canonicalVersionId; + private final UUID selectedCommitId; + private final long templateId; + private final String publishWorkflowId; + private final String targetNamespace; + private final UUID intakeRequestId; + private final UUID worldOperationId; + private final UUID sourceOperationId; + private final String worldSlug; + private final String sourceEvidenceDigest; + private final byte[] operationBytes; + private final byte[] captureBytes; + private final byte[] templateSnapshotBytes; + private final byte[] templateEntryBytes; + private final byte[] worldReadRequestBytes; + private final byte[] worldReadResponseBytes; + private final byte[] canonicalBytes; + private final String digest; + + private Association( + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID selectedCommitId, + long templateId, + String publishWorkflowId, + String targetNamespace, + UUID intakeRequestId, + UUID worldOperationId, + UUID sourceOperationId, + String worldSlug, + String sourceEvidenceDigest, + byte[] operationBytes, + byte[] captureBytes, + byte[] templateSnapshotBytes, + byte[] templateEntryBytes, + byte[] worldReadRequestBytes, + byte[] worldReadResponseBytes) { + this.canonicalTenantId = Objects.requireNonNull(canonicalTenantId); + this.canonicalVersionId = Objects.requireNonNull(canonicalVersionId); + this.selectedCommitId = Objects.requireNonNull(selectedCommitId); + if (templateId <= 0) + throw new IllegalArgumentException("Positive template identity required"); + this.templateId = templateId; + this.publishWorkflowId = Objects.requireNonNull(publishWorkflowId); + this.targetNamespace = Objects.requireNonNull(targetNamespace); + this.intakeRequestId = Objects.requireNonNull(intakeRequestId); + this.worldOperationId = Objects.requireNonNull(worldOperationId); + this.sourceOperationId = Objects.requireNonNull(sourceOperationId); + this.worldSlug = Objects.requireNonNull(worldSlug); + this.sourceEvidenceDigest = Objects.requireNonNull(sourceEvidenceDigest); + this.operationBytes = copy(operationBytes); + this.captureBytes = copy(captureBytes); + this.templateSnapshotBytes = copy(templateSnapshotBytes); + this.templateEntryBytes = copy(templateEntryBytes); + this.worldReadRequestBytes = copy(worldReadRequestBytes); + this.worldReadResponseBytes = copy(worldReadResponseBytes); + this.canonicalBytes = buildCanonicalBytes(); + this.digest = CommandSource.sha256(this.canonicalBytes); + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public UUID canonicalVersionId() { + return canonicalVersionId; + } + + public UUID selectedCommitId() { + return selectedCommitId; + } + + public long templateId() { + return templateId; + } + + public String publishWorkflowId() { + return publishWorkflowId; + } + + public String targetNamespace() { + return targetNamespace; + } + + public UUID intakeRequestId() { + return intakeRequestId; + } + + public UUID worldOperationId() { + return worldOperationId; + } + + public UUID sourceOperationId() { + return sourceOperationId; + } + + public String worldSlug() { + return worldSlug; + } + + public String sourceEvidenceDigest() { + return sourceEvidenceDigest; + } + + public byte[] operationBytes() { + return copy(operationBytes); + } + + public byte[] captureBytes() { + return copy(captureBytes); + } + + public byte[] templateSnapshotBytes() { + return copy(templateSnapshotBytes); + } + + public byte[] templateEntryBytes() { + return copy(templateEntryBytes); + } + + public byte[] worldReadRequestBytes() { + return copy(worldReadRequestBytes); + } + + public byte[] worldReadResponseBytes() { + return copy(worldReadResponseBytes); + } + + public byte[] canonicalBytes() { + return copy(canonicalBytes); + } + + public String digest() { + return digest; + } + + public boolean sameStoredValue(Association other) { + return other != null + && canonicalTenantId.equals(other.canonicalTenantId) + && canonicalVersionId.equals(other.canonicalVersionId) + && selectedCommitId.equals(other.selectedCommitId) + && templateId == other.templateId + && publishWorkflowId.equals(other.publishWorkflowId) + && targetNamespace.equals(other.targetNamespace) + && intakeRequestId.equals(other.intakeRequestId) + && worldOperationId.equals(other.worldOperationId) + && sourceOperationId.equals(other.sourceOperationId) + && worldSlug.equals(other.worldSlug) + && sourceEvidenceDigest.equals(other.sourceEvidenceDigest) + && Arrays.equals(operationBytes, other.operationBytes) + && Arrays.equals(captureBytes, other.captureBytes) + && Arrays.equals(templateSnapshotBytes, other.templateSnapshotBytes) + && Arrays.equals(templateEntryBytes, other.templateEntryBytes) + && Arrays.equals(worldReadRequestBytes, other.worldReadRequestBytes) + && Arrays.equals(worldReadResponseBytes, other.worldReadResponseBytes) + && Arrays.equals(canonicalBytes, other.canonicalBytes) + && digest.equals(other.digest); + } + + private byte[] buildCanonicalBytes() { + var output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, canonicalTenantId.toString()); + DraftAuthorizationFenceBinding.frame(output, canonicalVersionId.toString()); + DraftAuthorizationFenceBinding.frame(output, selectedCommitId.toString()); + DraftAuthorizationFenceBinding.frame(output, Long.toString(templateId)); + DraftAuthorizationFenceBinding.frame(output, publishWorkflowId); + DraftAuthorizationFenceBinding.frame(output, targetNamespace); + DraftAuthorizationFenceBinding.frame(output, intakeRequestId.toString()); + DraftAuthorizationFenceBinding.frame(output, worldOperationId.toString()); + DraftAuthorizationFenceBinding.frame(output, sourceOperationId.toString()); + DraftAuthorizationFenceBinding.frame(output, worldSlug); + DraftAuthorizationFenceBinding.frame(output, sourceEvidenceDigest); + DraftAuthorizationFenceBinding.frame(output, operationBytes); + DraftAuthorizationFenceBinding.frame(output, captureBytes); + DraftAuthorizationFenceBinding.frame(output, templateSnapshotBytes); + DraftAuthorizationFenceBinding.frame(output, templateEntryBytes); + DraftAuthorizationFenceBinding.frame(output, worldReadRequestBytes); + DraftAuthorizationFenceBinding.frame(output, worldReadResponseBytes); + return output.toByteArray(); + } + } + + public static Association create( + GameDesignPublicationOperation operation, + TemplateConfigSourceSnapshot.Capture capture, + TemplateConfigSource.Entry entry, + SourceRead worldSourceRead) { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(capture, "capture"); + Objects.requireNonNull(entry, "entry"); + Objects.requireNonNull(worldSourceRead, "worldSourceRead"); + if (!Arrays.equals(operation.canonicalBytes(), capture.operation().canonicalBytes()) + || !capture + .snapshot() + .binding() + .equals(operation.account().input().selection().selectedCommit()) + || !capture.snapshot().entries().contains(entry)) { + throw new IllegalArgumentException("Association requires the exact captured template entry"); + } + var target = operation.account().input().selection().target(); + WorldPublishedStartLocationEvidence.Request selectedWorld = operation.world().request(); + ByIdReadRequest request = worldSourceRead.request(); + PublicReceipt receipt = worldSourceRead.receipt(); + if (!target.canonicalTenantId().equals(selectedWorld.canonicalTenantId()) + || receipt.source().sourceGameRowId() != target.sourceGameRowId() + || !receipt.source().sourceGameTenantKey().equals(target.sourceGameTenantKey()) + || !receipt.source().provenanceKind().equals(target.sourceProvenanceKind()) + || !selectedWorld.targetNamespace().equals(request.targetNamespace()) + || !selectedWorld.intakeRequestId().equals(request.intakeRequestId()) + || !selectedWorld.canonicalTenantId().equals(request.canonicalTenantId()) + || !selectedWorld.targetNamespace().equals(receipt.targetNamespace()) + || !selectedWorld.canonicalTenantId().equals(receipt.canonicalTenantId()) + || !selectedWorld.intakeRequestId().equals(receipt.intakeRequestId())) { + throw new IllegalArgumentException( + "World source receipt differs from the original selected publication freeze"); + } + long templateId; + try { + templateId = Long.parseLong(entry.templateId()); + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException( + "Captured template identity is not a stored row ID", invalid); + } + return new Association( + target.canonicalTenantId(), + target.canonicalVersionId(), + capture.snapshot().binding().commitId(), + templateId, + operation.workflowId(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.sourceOperationId(), + receipt.worldSlug(), + receipt.sourceEvidenceDigest(), + operation.canonicalBytes(), + capture.canonicalBytes(), + capture.snapshot().canonicalBytes(), + CommandSource.canonical(entry.object()).getBytes(StandardCharsets.UTF_8), + worldSourceRead.requestBytes(), + worldSourceRead.responseBytes()); + } + + private static byte[] copy(byte[] value) { + return Objects.requireNonNull(value, "value").clone(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociationRepository.java new file mode 100644 index 0000000000..fff0ef7fff --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociationRepository.java @@ -0,0 +1,273 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation.Association; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation.SourceRead; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Immutable per-template relation to the exact selected publication's original World source. */ +public final class SelectedDraftTemplateWorldSourceAssociationRepository { + private static final String TABLE = "game_design_selected_template_world_source_association"; + private final DSLContext dsl; + + public SelectedDraftTemplateWorldSourceAssociationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Persists first-time associations in the publication reservation transaction, or exact-reads + * them for an already retained operation. Replay never allocates a row or replaces its original + * read identity. + */ + public List retainOrRead( + GameDesignPublicationOperation operation, + TemplateConfigSourceSnapshot.Capture capture, + SourceRead currentSourceRead, + boolean allowCreate) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(currentSourceRead, "currentSourceRead"); + List expected = associations(operation, capture, currentSourceRead); + List rows = rows(operation, capture); + List inserted = new ArrayList<>(expected.size()); + if (allowCreate) { + if (!rows.isEmpty()) { + throw new IllegalStateException( + "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_PREEXISTS_WITHOUT_OPERATION"); + } + for (Association association : expected) inserted.add(insert(association)); + } + List retained = readExact(operation, capture); + if (retained.size() != expected.size()) { + throw new IllegalStateException("SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_INCOMPLETE"); + } + for (int index = 0; index < retained.size(); index++) { + Association old = retained.get(index); + Association current = expected.get(index); + // A competing exact first reservation may have committed the same durable operation from a + // separately authenticated by-ID read. Keep its original read correlation; only that + // correlation/echo may differ, never the receipt, selected capture, or source identity. + boolean matches = + allowCreate && inserted.get(index) + ? old.sameStoredValue(current) + : sameOriginalSource(old, current, currentSourceRead); + if (!matches) { + throw new IllegalStateException( + allowCreate + ? "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_READBACK_CONFLICT" + : "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_CONFLICT"); + } + } + return retained; + } + + /** Exact read-only completeness proof for an already retained source-backed operation. */ + public List readExact( + GameDesignPublicationOperation operation, TemplateConfigSourceSnapshot.Capture capture) { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(capture, "capture"); + if (!Arrays.equals(operation.canonicalBytes(), capture.operation().canonicalBytes())) { + throw new IllegalArgumentException("Association read requires its exact captured operation"); + } + List rows = rows(operation, capture); + List entries = capture.snapshot().entries(); + if (rows.size() != entries.size()) { + throw new IllegalStateException("SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_INCOMPLETE"); + } + List result = new ArrayList<>(entries.size()); + for (TemplateConfigSource.Entry entry : entries) { + long templateId = parseTemplateId(entry.templateId()); + Record row = + rows.stream() + .filter(value -> Objects.equals(value.get("template_id", Long.class), templateId)) + .findFirst() + .orElseThrow( + () -> + new IllegalStateException( + "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_ENTRY_MISSING")); + Association retained = decode(operation, capture, entry, row); + requireRowMatches(retained, row); + result.add(retained); + } + return List.copyOf(result); + } + + private List associations( + GameDesignPublicationOperation operation, + TemplateConfigSourceSnapshot.Capture capture, + SourceRead sourceRead) { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(capture, "capture"); + return capture.snapshot().entries().stream() + .map( + entry -> + SelectedDraftTemplateWorldSourceAssociation.create( + operation, capture, entry, sourceRead)) + .toList(); + } + + private boolean insert(Association value) { + return dsl.execute( + "INSERT INTO " + + TABLE + + " (canonical_tenant_id, canonical_version_id, commit_id, template_id, publish_workflow_id, " + + "target_namespace, intake_request_id, world_operation_id, source_operation_id, world_slug, " + + "source_evidence_digest, operation_bytes, capture_bytes, template_snapshot_bytes, template_entry_bytes, " + + "world_read_request_bytes, world_read_response_bytes, association_bytes, association_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + value.canonicalTenantId(), + value.canonicalVersionId(), + value.selectedCommitId(), + value.templateId(), + value.publishWorkflowId(), + value.targetNamespace(), + value.intakeRequestId(), + value.worldOperationId(), + value.sourceOperationId(), + value.worldSlug(), + value.sourceEvidenceDigest(), + value.operationBytes(), + value.captureBytes(), + value.templateSnapshotBytes(), + value.templateEntryBytes(), + value.worldReadRequestBytes(), + value.worldReadResponseBytes(), + value.canonicalBytes(), + value.digest()) + == 1; + } + + private List rows( + GameDesignPublicationOperation operation, TemplateConfigSourceSnapshot.Capture capture) { + var selection = operation.account().input().selection(); + return dsl.fetch( + "SELECT * FROM " + + TABLE + + " WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ? ORDER BY template_id", + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + capture.snapshot().binding().commitId()); + } + + private Association decode( + GameDesignPublicationOperation operation, + TemplateConfigSourceSnapshot.Capture capture, + TemplateConfigSource.Entry entry, + Record row) { + try { + byte[] requestBytes = row.get("world_read_request_bytes", byte[].class); + byte[] responseBytes = row.get("world_read_response_bytes", byte[].class); + var requestMessage = ReadAuthoredWorldSourceIntakeByIdRequest.parseFrom(requestBytes); + var request = WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdRequest(requestMessage); + var responseMessage = ReadAuthoredWorldSourceIntakeByIdResponse.parseFrom(responseBytes); + var receipt = + WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdResponse(request, responseMessage); + var sourceRead = new SourceRead(request, receipt); + if (!Arrays.equals(requestBytes, sourceRead.requestBytes()) + || !Arrays.equals(responseBytes, sourceRead.responseBytes())) { + throw new IllegalStateException("noncanonical retained World source read"); + } + return SelectedDraftTemplateWorldSourceAssociation.create( + operation, capture, entry, sourceRead); + } catch (IOException | IllegalArgumentException | IllegalStateException failure) { + throw new IllegalStateException( + "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_EVIDENCE_CORRUPT", failure); + } + } + + private static void requireRowMatches(Association value, Record row) { + if (!value.canonicalTenantId().equals(row.get("canonical_tenant_id", java.util.UUID.class)) + || !value.canonicalVersionId().equals(row.get("canonical_version_id", java.util.UUID.class)) + || !value.selectedCommitId().equals(row.get("commit_id", java.util.UUID.class)) + || value.templateId() != row.get("template_id", Long.class) + || !value.publishWorkflowId().equals(row.get("publish_workflow_id", String.class)) + || !value.targetNamespace().equals(row.get("target_namespace", String.class)) + || !value.intakeRequestId().equals(row.get("intake_request_id", java.util.UUID.class)) + || !value.worldOperationId().equals(row.get("world_operation_id", java.util.UUID.class)) + || !value.sourceOperationId().equals(row.get("source_operation_id", java.util.UUID.class)) + || !value.worldSlug().equals(row.get("world_slug", String.class)) + || !value.sourceEvidenceDigest().equals(row.get("source_evidence_digest", String.class)) + || !Arrays.equals(value.operationBytes(), row.get("operation_bytes", byte[].class)) + || !Arrays.equals(value.captureBytes(), row.get("capture_bytes", byte[].class)) + || !Arrays.equals( + value.templateSnapshotBytes(), row.get("template_snapshot_bytes", byte[].class)) + || !Arrays.equals(value.templateEntryBytes(), row.get("template_entry_bytes", byte[].class)) + || !Arrays.equals( + value.worldReadRequestBytes(), row.get("world_read_request_bytes", byte[].class)) + || !Arrays.equals( + value.worldReadResponseBytes(), row.get("world_read_response_bytes", byte[].class)) + || !Arrays.equals(value.canonicalBytes(), row.get("association_bytes", byte[].class)) + || !value.digest().equals(row.get("association_digest", String.class))) { + throw new IllegalStateException( + "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_READBACK_CONFLICT"); + } + } + + private static boolean sameOriginalSource( + Association retained, Association candidate, SourceRead currentRead) { + return retained.canonicalTenantId().equals(candidate.canonicalTenantId()) + && retained.canonicalVersionId().equals(candidate.canonicalVersionId()) + && retained.selectedCommitId().equals(candidate.selectedCommitId()) + && retained.templateId() == candidate.templateId() + && retained.publishWorkflowId().equals(candidate.publishWorkflowId()) + && retained.targetNamespace().equals(candidate.targetNamespace()) + && retained.intakeRequestId().equals(candidate.intakeRequestId()) + && retained.worldOperationId().equals(candidate.worldOperationId()) + && retained.sourceOperationId().equals(candidate.sourceOperationId()) + && retained.worldSlug().equals(candidate.worldSlug()) + && retained.sourceEvidenceDigest().equals(candidate.sourceEvidenceDigest()) + && Arrays.equals(retained.operationBytes(), candidate.operationBytes()) + && Arrays.equals(retained.captureBytes(), candidate.captureBytes()) + && Arrays.equals(retained.templateSnapshotBytes(), candidate.templateSnapshotBytes()) + && Arrays.equals(retained.templateEntryBytes(), candidate.templateEntryBytes()) + && currentRead.request().targetNamespace().equals(retained.targetNamespace()) + && currentRead.request().intakeRequestId().equals(retained.intakeRequestId()) + && currentRead.request().canonicalTenantId().equals(retained.canonicalTenantId()) + && currentRead.receipt().equals(retainedReceipt(retained)); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt retainedReceipt( + Association association) { + try { + var request = + WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdRequest( + ReadAuthoredWorldSourceIntakeByIdRequest.parseFrom( + association.worldReadRequestBytes())); + return WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdResponse( + request, + ReadAuthoredWorldSourceIntakeByIdResponse.parseFrom( + association.worldReadResponseBytes())); + } catch (IOException | IllegalArgumentException invalid) { + throw new IllegalStateException( + "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_EVIDENCE_CORRUPT", invalid); + } + } + + private static long parseTemplateId(String templateId) { + try { + return Long.parseLong(templateId); + } catch (NumberFormatException invalid) { + throw new IllegalStateException("TEMPLATE_CONFIG_CAPTURE_ID_INVALID", invalid); + } + } + + private static void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Template/world source association requires writable READ_COMMITTED transaction"); + } + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V62__selected_template_world_source_association.sql b/services/game-design-service/src/main/resources/db/migration/V62__selected_template_world_source_association.sql new file mode 100644 index 0000000000..fb9b54f847 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V62__selected_template_world_source_association.sql @@ -0,0 +1,105 @@ +-- One immutable World-source relation for every template actually present in the selected capture. +CREATE TABLE game_design_selected_template_world_source_association ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + commit_id UUID NOT NULL, + template_id BIGINT NOT NULL REFERENCES game_templates (id) ON DELETE RESTRICT, + publish_workflow_id VARCHAR(1024) NOT NULL + REFERENCES game_design_publication_operation (publish_workflow_id) ON DELETE RESTRICT, + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + world_operation_id UUID NOT NULL, + source_operation_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + source_evidence_digest VARCHAR(71) NOT NULL, + operation_bytes BYTEA NOT NULL, + capture_bytes BYTEA NOT NULL, + template_snapshot_bytes BYTEA NOT NULL, + template_entry_bytes BYTEA NOT NULL, + world_read_request_bytes BYTEA NOT NULL, + world_read_response_bytes BYTEA NOT NULL, + association_bytes BYTEA NOT NULL, + association_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, commit_id, template_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_template_config_source_snapshot + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_template_config_source_capture + (canonical_tenant_id, canonical_version_id) ON DELETE RESTRICT, + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND template_id > 0 + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), + CHECK (source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND association_digest ~ '^sha256:[0-9a-f]{64}$'), + CHECK (octet_length(operation_bytes) > 0 + AND octet_length(capture_bytes) > 0 + AND octet_length(template_snapshot_bytes) > 0 + AND octet_length(template_entry_bytes) > 0 + AND octet_length(world_read_request_bytes) > 0 + AND octet_length(world_read_response_bytes) > 0 + AND octet_length(association_bytes) > 0) +); + +-- [jooq ignore start] +CREATE FUNCTION enforce_gd_selected_template_world_source_association() RETURNS trigger AS $$ +DECLARE + op RECORD; + capture RECORD; + snapshot RECORD; + matching_entry BOOLEAN; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Selected template/world source associations are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO STRICT op + FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id + FOR UPDATE; + SELECT * INTO STRICT capture + FROM game_design_template_config_source_capture + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT snapshot + FROM game_design_template_config_source_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.commit_id; + + SELECT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot.snapshot_json::JSONB -> 'entries') entry + WHERE entry ->> 'templateId' = NEW.template_id::TEXT + AND entry = convert_from(NEW.template_entry_bytes, 'UTF8')::JSONB + ) INTO matching_entry; + + IF op.outcome <> 'PENDING' + OR op.request_bytes IS DISTINCT FROM NEW.operation_bytes + OR capture.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR capture.commit_id IS DISTINCT FROM NEW.commit_id + OR capture.operation_bytes IS DISTINCT FROM NEW.operation_bytes + OR capture.capture_bytes IS DISTINCT FROM NEW.capture_bytes + OR convert_to(snapshot.snapshot_json, 'UTF8') IS DISTINCT FROM NEW.template_snapshot_bytes + OR NOT matching_entry + OR NEW.association_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.association_bytes), 'hex') THEN + RAISE EXCEPTION 'Selected template/world source association differs from its exact pending capture' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_selected_template_world_source_association + BEFORE INSERT OR UPDATE OR DELETE ON game_design_selected_template_world_source_association + FOR EACH ROW EXECUTE FUNCTION enforce_gd_selected_template_world_source_association(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V63__selected_publication_control_plane_digest_schema.sql b/services/game-design-service/src/main/resources/db/migration/V63__selected_publication_control_plane_digest_schema.sql new file mode 100644 index 0000000000..34bd2cf9b9 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V63__selected_publication_control_plane_digest_schema.sql @@ -0,0 +1,202 @@ +-- Selected full publications use the immutable six-source control-plane digest schema. +-- Replacing this function keeps the retained V1 policy and all other V2 checks unchanged. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION enforce_published_world_start_location_evidence() RETURNS trigger AS $$ +DECLARE + evidence JSONB; + selection JSONB; + applied JSONB; + receipt JSONB; + participants JSONB; + item JSONB; + owner_key TEXT; + required_schema INTEGER; + field_name TEXT; + account_bytes BYTEA; + operation_bytes BYTEA; + draft JSONB; + affected JSONB; +BEGIN + IF NEW.attestation_schema_version <> 'v2' THEN + IF NEW.world_published_start_location_evidence_json IS NOT NULL THEN + RAISE EXCEPTION 'historical release schemas cannot carry a World selector' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + + IF NEW.world_published_start_location_evidence_json IS NULL + OR NEW.script_only OR NEW.script_patch_version IS NOT NULL + OR NEW.canonical_tenant_id IS NULL OR NEW.canonical_version_id IS NULL + OR NEW.manifest_schema_version IS NULL OR NEW.artifact_digests_json IS NULL THEN + RAISE EXCEPTION 'release v2 requires complete full-Version selector evidence' + USING ERRCODE = 'check_violation'; + END IF; + evidence := NEW.world_published_start_location_evidence_json::JSONB; + selection := evidence->'request'; + FOR field_name IN SELECT unnest(ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'publishWorkflowId','appliedCommitId','contentDigest']) + LOOP + IF jsonb_typeof(selection->field_name) IS DISTINCT FROM 'string' + OR coalesce(selection->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 has missing selection text binding' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + IF jsonb_typeof(evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR NOT evidence ?& ARRAY['schema','request','selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64'] + OR evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR jsonb_typeof(selection) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selection)) <> 13 + OR NOT selection ?& ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'versionStateEpoch','publishWorkflowId','appliedCommitId','contentDigest', + 'digestSchemaVersion','worldAffectedTuples'] + OR selection->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR selection->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR selection->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR selection->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR selection->>'intakeRequestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'intakeRequestId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'publicationFence' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'publicationFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'appliedCommitId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'appliedCommitId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR coalesce(selection->>'publicationRequestId','') = '' + OR selection->>'requestDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'versionStateEpoch' !~ '^[1-9][0-9]*$' + OR jsonb_typeof(selection->'versionStateEpoch') IS DISTINCT FROM 'string' + OR length(selection->>'versionStateEpoch') > 19 + OR (length(selection->>'versionStateEpoch') = 19 + AND selection->>'versionStateEpoch' > '9223372036854775807') + OR jsonb_typeof(selection->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR selection->>'digestSchemaVersion' IS DISTINCT FROM '3' + OR jsonb_typeof(selection->'worldAffectedTuples') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'release v2 World selection has missing, unsupported or mismatched bindings' + USING ERRCODE = 'check_violation'; + END IF; + IF jsonb_array_length(selection->'worldAffectedTuples') = 0 THEN + RAISE EXCEPTION 'release v2 requires the complete World affected set' USING ERRCODE = 'check_violation'; + END IF; + -- Binary Account and APPLIED bytes remain intact; Java independently checks their full relation. + IF jsonb_typeof(evidence->'originalAccountBindingBytesBase64') IS DISTINCT FROM 'string' + OR octet_length(decode(evidence->>'originalAccountBindingBytesBase64','base64')) = 0 + OR jsonb_typeof(evidence->'appliedResultBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(evidence->'selectorReceiptBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'release v2 requires complete original owner bytes' + USING ERRCODE = 'check_violation'; + END IF; + applied := convert_from(decode(evidence->>'appliedResultBytesBase64','base64'),'UTF8')::JSONB; + receipt := convert_from(decode(evidence->>'selectorReceiptBytesBase64','base64'),'UTF8')::JSONB; + FOR field_name IN SELECT unnest(ARRAY['selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64']) + LOOP + IF replace(encode(decode(evidence->>field_name,'base64'),'base64'), E'\n','') + IS DISTINCT FROM evidence->>field_name THEN + RAISE EXCEPTION 'release v2 owner bytes are not canonical base64' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest']) + LOOP + IF jsonb_typeof(applied->field_name) IS DISTINCT FROM 'string' + OR coalesce(applied->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 APPLIED result has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','graphDigest','receiptDigest']) + LOOP + IF jsonb_typeof(receipt->field_name) IS DISTINCT FROM 'string' + OR coalesce(receipt->>field_name,'') = '' THEN + RAISE EXCEPTION 'release v2 selector receipt has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + account_bytes := decode(evidence->>'originalAccountBindingBytesBase64','base64'); + operation_bytes := decode(applied->>'operationBytesBase64','base64'); + draft := convert_from(published_world_selector_frame(account_bytes, 11),'UTF8')::JSONB; + SELECT coalesce(jsonb_agg(unit ORDER BY unit->>'owner', unit->>'aggregateType', + unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId', unit->>'expectedEpoch'),'[]'::JSONB) + INTO affected FROM jsonb_array_elements(draft->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF applied->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR applied->>'status' IS DISTINCT FROM 'APPLIED' + OR applied->>'startLocationReceiptBase64' IS DISTINCT FROM evidence->>'selectorReceiptBytesBase64' + OR receipt->>'schema' IS DISTINCT FROM 'world-draft-start-location-receipt/v1' + OR receipt->>'targetNamespace' IS DISTINCT FROM selection->>'targetNamespace' + OR receipt->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR receipt->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR receipt->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR receipt->>'receiptDigest' IS DISTINCT FROM applied->>'startLocationReceiptDigest' + OR jsonb_typeof(applied) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(applied)) <> 8 + OR NOT applied ?& ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest','appliedEpochs'] + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 11 + OR NOT receipt ?& ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','startLocation','graphDigest','receiptDigest'] + OR jsonb_typeof(receipt->'startLocation') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt->'startLocation')) <> 3 + OR NOT (receipt->'startLocation') ?& ARRAY['tenantId','versionId','roomTemplateId'] + OR selection->'worldAffectedTuples' IS DISTINCT FROM affected + OR draft->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR draft->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR draft->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR draft->'target'->>'gameDesignVersionRowId' IS DISTINCT FROM NEW.version_id::TEXT + OR draft->'target'->>'gameDesignVersionTenantKey' IS DISTINCT FROM NEW.tenant_id + OR published_world_selector_frame(account_bytes, 11) IS DISTINCT FROM published_world_selector_frame(account_bytes, 12) + OR published_world_selector_frame(operation_bytes, 7) IS DISTINCT FROM published_world_selector_frame(account_bytes, 11) + OR convert_from(published_world_selector_frame(account_bytes, 13),'UTF8') IS DISTINCT FROM receipt->>'bindingDigest' + OR receipt->>'accountBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes),'hex') + OR applied->>'graphDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(applied->>'graphBytesBase64','base64')),'hex') + OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1' + OR convert_from(published_world_selector_frame(account_bytes, 1),'UTF8') IS DISTINCT FROM receipt->>'operationId' + OR convert_from(published_world_selector_frame(account_bytes, 2),'UTF8') IS DISTINCT FROM receipt->>'requestId' + OR convert_from(published_world_selector_frame(account_bytes, 3),'UTF8') IS DISTINCT FROM selection->>'appliedCommitId' + OR convert_from(published_world_selector_frame(account_bytes, 4),'UTF8') IS DISTINCT FROM receipt->>'authorizationFenceId' + OR convert_from(published_world_selector_frame(account_bytes, 6),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(account_bytes, 7),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 0),'UTF8') IS DISTINCT FROM 'world-draft-terminal-operation/v1' + OR published_world_selector_frame(operation_bytes, 20) IS DISTINCT FROM account_bytes + OR convert_from(published_world_selector_frame(operation_bytes, 13),'UTF8') IS DISTINCT FROM selection->>'intakeRequestId' + OR convert_from(published_world_selector_frame(operation_bytes, 8),'UTF8') IS DISTINCT FROM selection->>'targetNamespace' + OR convert_from(published_world_selector_frame(operation_bytes, 9),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 10),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->'startLocation'->>'roomTemplateId' IS NULL THEN + RAISE EXCEPTION 'release v2 selector differs from original selected APPLIED receipt' + USING ERRCODE = 'check_violation'; + END IF; + participants := NEW.participant_digests_json::JSONB; + IF jsonb_typeof(participants) IS DISTINCT FROM 'array' OR jsonb_array_length(participants) <> 5 THEN + RAISE EXCEPTION 'release v2 requires all five participant owners' USING ERRCODE = 'check_violation'; + END IF; + FOR owner_key, required_schema IN SELECT * FROM (VALUES + ('WORLD_MANAGEMENT',3),('ENTITY_MANAGEMENT',2),('GAME_LOGIC',1), + ('AUTOMATION_SCRIPTING',5),('GAME_DESIGN_CONTROL_PLANE',2)) owners(owner_key, required_schema) + LOOP + IF (SELECT count(*) FROM jsonb_array_elements(participants) p + WHERE p->>'participantKey' = owner_key) <> 1 THEN + RAISE EXCEPTION 'release v2 has missing or duplicate participant owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT p INTO item FROM jsonb_array_elements(participants) p WHERE p->>'participantKey' = owner_key; + IF item->>'scopeValue' IS DISTINCT FROM NEW.version_id::TEXT + OR item->>'baseVersionId' IS NOT NULL + OR item->>'appliedCommitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR item->>'digestSchemaVersion' IS DISTINCT FROM required_schema::TEXT + OR coalesce(item->>'contentDigest','') !~ '^[0-9a-f]{64}$' + OR coalesce(item->>'errorCode','') <> '' + OR (owner_key = 'WORLD_MANAGEMENT' AND item->>'contentDigest' IS DISTINCT FROM selection->>'contentDigest') + OR (owner_key = 'GAME_LOGIC' AND coalesce(item->>'abilitySchemaDigest','') !~ '^sha256:[0-9a-f]{64}$') THEN + RAISE EXCEPTION 'release v2 participant differs from selected commit/digest/schema' + USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index ec3ae01518..cf114080f1 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -1,10 +1,16 @@ package net.firedevops.firemud.gamedesign.draft; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.UUID; import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +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.ByIdReadRequest; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; @@ -19,6 +25,7 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; @@ -31,6 +38,102 @@ public final class IsolatedPublicationOwnerSetup { private IsolatedPublicationOwnerSetup() {} + /** + * Explicit owner-local synthetic World source evidence. It is structurally correlated to the + * operation's exact intake identity but does not represent World or Account producer authority. + */ + public static SelectedDraftTemplateWorldSourceAssociation.SourceRead syntheticWorldSourceRead( + GameDesignPublicationOperation operation) { + var world = operation.world().request(); + var selection = operation.account().input().selection(); + UUID sourceOperationId = fixtureId(operation, "source-operation"); + UUID registrationRequestId = fixtureId(operation, "source-registration"); + String tenantSlug = "synthetic-tenant"; + String worldSlug = "synthetic-world-" + world.canonicalTenantId().toString().substring(0, 8); + String displayName = "Synthetic owner-local authored world"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + world.targetNamespace(), + registrationRequestId, + world.canonicalTenantId(), + tenantSlug, + worldSlug, + displayName); + var source = + new AuthoredWorldSourceEvidence( + 1, + world.targetNamespace(), + registrationRequestId, + sourceOperationId, + requestDigest, + world.canonicalTenantId(), + tenantSlug, + worldSlug, + displayName, + selection.target().sourceGameRowId(), + selection.target().sourceGameTenantKey(), + selection.target().sourceProvenanceKind(), + AuthoredWorldSourceDigest.evidenceDigest( + world.targetNamespace(), + registrationRequestId, + sourceOperationId, + requestDigest, + world.canonicalTenantId(), + tenantSlug, + worldSlug, + displayName, + selection.target().sourceGameRowId(), + selection.target().sourceGameTenantKey(), + selection.target().sourceProvenanceKind())); + var intake = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + world.targetNamespace(), + world.intakeRequestId(), + world.canonicalTenantId(), + worldSlug, + sourceOperationId, + source.evidenceDigest()); + var readRequest = + new ByIdReadRequest( + 1, + world.targetNamespace(), + fixtureId(operation, "source-read"), + world.intakeRequestId(), + world.canonicalTenantId()); + var receipt = + new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + world.targetNamespace(), + world.intakeRequestId(), + fixtureId(operation, "world-operation"), + world.canonicalTenantId(), + worldSlug, + sourceOperationId, + source.evidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intake), + "sha256:" + "a".repeat(64), + source); + return new SelectedDraftTemplateWorldSourceAssociation.SourceRead(readRequest, receipt); + } + + private static UUID fixtureId(GameDesignPublicationOperation operation, String purpose) { + UUID value = + UUID.nameUUIDFromBytes( + (operation.workflowId() + ":synthetic-owner-local:" + purpose) + .getBytes(StandardCharsets.UTF_8)); + int salt = 0; + while (value.equals(new UUID(0L, 0L)) + || value.equals(operation.world().request().intakeRequestId())) { + salt++; + value = + UUID.nameUUIDFromBytes( + (operation.workflowId() + ":synthetic-owner-local:" + purpose + ":" + salt) + .getBytes(StandardCharsets.UTF_8)); + } + return value; + } + /** Actual ordinary source/coordinator transaction; does not stipulate complete inventory. */ public static DraftCommitBinding applyOrdinaryReferences( DSLContext dsl, DraftCommitBinding.TargetProof target, List payloads) { @@ -163,7 +266,12 @@ private static GameDesignPublicationOperation retain( if (captureSources) { operation = new SelectedDraftPublicationOwner(dsl) - .reserve(intent, operation.account(), operation.world(), operation.inventory()) + .reserve( + intent, + operation.account(), + operation.world(), + operation.inventory(), + syntheticWorldSourceRead(operation)) .operation(); } else { var attempt = new PublishAttempt(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java index 131836e485..e385f5180a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -3,18 +3,29 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.publication.CommandSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociationRepository; import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository; import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceSnapshot; @@ -311,6 +322,253 @@ void changedGameplayRevisionCannotLeaveStaleTemplateReferencesVisible() { assertThat(source(f, initial).entries()).hasSize(1); } + @Test + void selectedPublicationRetainsInheritedTemplateToOriginalWorldSourceAssociation() { + var f = fixture(); + UUID ruleRevision = UUID.randomUUID(); + var rule = + new DraftCommitBinding.RevisionPayload( + "0", + ruleRevision, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("ordinary"))); + var config = + config( + f, + "[{\"family\":\"ADMISSION_TAGS\",\"key\":\"ordinary\",\"revisionId\":\"" + + ruleRevision + + "\"}]"); + var create = + new DraftCommitBinding.RevisionPayload( + "1", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.createPayload("Starter", config)); + var initial = + binding( + f, + List.of(rule, create), + Map.of(GameplayRuleSource.SCOPE, "0", TemplateConfigSource.SCOPE, "0")); + apply(f, initial); + + // This owner-local fixture supplies structured synthetic World evidence; it is not a proof of + // the authenticated World or Account producer boundary. + var operation = + f.tx.execute( + ignored -> { + try { + return IsolatedPublicationOwnerSetup.retainSourceBacked( + f.dsl, f.target, 1L, "selected inherited template association"); + } catch (Exception e) { + throw new IllegalStateException("Unable to retain source-backed publication", e); + } + }); + var sourceCapture = new GameDesignSourceRepository(f.dsl).readCapture(operation).orElseThrow(); + var templateCapture = sourceCapture.templateConfig(); + assertThat(templateCapture.snapshot().entries()).hasSize(1); + assertThat(templateCapture.snapshot().binding().commitId()) + .isEqualTo(operation.account().input().selection().selectedCommit().commitId()); + assertThat(templateCapture.snapshot().entries().getFirst().sourceBinding().commitId()) + .isEqualTo(initial.commitId()); + + var associations = new SelectedDraftTemplateWorldSourceAssociationRepository(f.dsl); + var retained = associations.readExact(operation, templateCapture); + assertThat(retained).hasSize(1); + assertThat(retained.getFirst().selectedCommitId()) + .isEqualTo(operation.account().input().selection().selectedCommit().commitId()); + assertThat(retained.getFirst().sourceOperationId()).isNotNull(); + assertThat(retained.getFirst().worldOperationId()).isNotNull(); + assertThat(retained.getFirst().worldReadRequestBytes()).isNotEmpty(); + assertThat(retained.getFirst().worldReadResponseBytes()).isNotEmpty(); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_selected_template_world_source_association") + .get(0, Long.class)) + .isEqualTo(1L); + + var selection = + AuthoredDraftPublishSelection.fromStored( + operation.account().input().selection().canonicalJson(), + operation.account().input().selection().digest()); + var originalWorldSourceRead = IsolatedPublicationOwnerSetup.syntheticWorldSourceRead(operation); + UUID replayReadRequestId = UUID.randomUUID(); + while (replayReadRequestId.equals(originalWorldSourceRead.request().intakeRequestId())) { + replayReadRequestId = UUID.randomUUID(); + } + var replayWorldSourceRead = + new SelectedDraftTemplateWorldSourceAssociation.SourceRead( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + originalWorldSourceRead.request().targetNamespace(), + replayReadRequestId, + originalWorldSourceRead.request().intakeRequestId(), + originalWorldSourceRead.request().canonicalTenantId()), + originalWorldSourceRead.receipt()); + f.tx.executeWithoutResult( + ignored -> + new SelectedDraftPublicationOwner(f.dsl) + .reserve( + selection.intent(), + operation.account(), + operation.world(), + operation.inventory(), + replayWorldSourceRead)); + assertThat(associations.readExact(operation, templateCapture).getFirst().canonicalBytes()) + .containsExactly(retained.getFirst().canonicalBytes()); + var originalReceipt = originalWorldSourceRead.receipt(); + var substitutedReceipt = + new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + originalReceipt.schemaVersion(), + originalReceipt.targetNamespace(), + originalReceipt.intakeRequestId(), + UUID.randomUUID(), + originalReceipt.canonicalTenantId(), + originalReceipt.worldSlug(), + originalReceipt.sourceOperationId(), + originalReceipt.sourceEvidenceDigest(), + originalReceipt.requestDigest(), + originalReceipt.receiptDigest(), + originalReceipt.source()); + UUID substitutedReadRequestId = UUID.randomUUID(); + while (substitutedReadRequestId.equals(originalWorldSourceRead.request().intakeRequestId())) { + substitutedReadRequestId = UUID.randomUUID(); + } + var substitutedWorldSourceRead = + new SelectedDraftTemplateWorldSourceAssociation.SourceRead( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + originalWorldSourceRead.request().targetNamespace(), + substitutedReadRequestId, + originalWorldSourceRead.request().intakeRequestId(), + originalWorldSourceRead.request().canonicalTenantId()), + substitutedReceipt); + assertThatThrownBy( + () -> + f.tx.executeWithoutResult( + ignored -> + new SelectedDraftPublicationOwner(f.dsl) + .reserve( + selection.intent(), + operation.account(), + operation.world(), + operation.inventory(), + substitutedWorldSourceRead))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ASSOCIATION_CONFLICT"); + assertThat(associations.readExact(operation, templateCapture).getFirst().canonicalBytes()) + .containsExactly(retained.getFirst().canonicalBytes()); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE game_design_selected_template_world_source_association SET world_slug = 'substituted'")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + @Test + void concurrentExactFirstReservationsKeepTheWinningReadCorrelation() throws Exception { + var f = fixture(); + var initial = + binding( + f, + TemplateConfigSource.createPayload("Starter", config(f, "[]")), + TemplateConfigSource.SCOPE, + "0"); + apply(f, initial); + + var prepared = + f.tx.execute( + ignored -> { + try { + return IsolatedPublicationOwnerSetup.selectSourceBackedDraftWithWorld( + f.dsl, f.target, 1L, "concurrent selected template association"); + } catch (Exception e) { + throw new IllegalStateException("Unable to select source-backed publication", e); + } + }); + var authoredSelection = Objects.requireNonNull(prepared).selection().selection(); + var selection = + AuthoredDraftPublishSelectionBinding.fromStored( + authoredSelection.canonicalJson(), authoredSelection.digest()); + var operation = IsolatedPublicationOperationFixtures.forSelection(selection, prepared.world()); + var firstRead = IsolatedPublicationOwnerSetup.syntheticWorldSourceRead(operation); + UUID competingReadRequestId = UUID.randomUUID(); + while (competingReadRequestId.equals(firstRead.request().intakeRequestId()) + || competingReadRequestId.equals(firstRead.request().readRequestId())) { + competingReadRequestId = UUID.randomUUID(); + } + var competingRead = + new SelectedDraftTemplateWorldSourceAssociation.SourceRead( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + firstRead.request().schemaVersion(), + firstRead.request().targetNamespace(), + competingReadRequestId, + firstRead.request().intakeRequestId(), + firstRead.request().canonicalTenantId()), + firstRead.receipt()); + + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> concurrentReserve(f, operation, selection, firstRead, ready, start)); + var second = + executor.submit( + () -> concurrentReserve(f, operation, selection, competingRead, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var firstReservation = first.get(30, TimeUnit.SECONDS); + var secondReservation = second.get(30, TimeUnit.SECONDS); + assertThat(firstReservation.operation().canonicalBytes()) + .containsExactly(operation.canonicalBytes()); + assertThat(secondReservation.operation().canonicalBytes()) + .containsExactly(operation.canonicalBytes()); + } finally { + executor.shutdownNow(); + } + + var capture = new GameDesignSourceRepository(f.dsl).readCapture(operation).orElseThrow(); + var retained = + new SelectedDraftTemplateWorldSourceAssociationRepository(f.dsl) + .readExact(operation, capture.templateConfig()); + assertThat(retained).hasSize(1); + byte[] winnerRequest = retained.getFirst().worldReadRequestBytes(); + assertThat( + Arrays.equals(winnerRequest, firstRead.requestBytes()) + || Arrays.equals(winnerRequest, competingRead.requestBytes())) + .isTrue(); + assertThat(retained.getFirst().worldReadResponseBytes()).isNotEmpty(); + } + + private static SelectedDraftPublicationOwner.Reservation concurrentReserve( + Fixture f, + GameDesignPublicationOperation operation, + AuthoredDraftPublishSelectionBinding selection, + SelectedDraftTemplateWorldSourceAssociation.SourceRead sourceRead, + CountDownLatch ready, + CountDownLatch start) + throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to start concurrent owner reservation"); + } + return Objects.requireNonNull( + f.tx.execute( + ignored -> + new SelectedDraftPublicationOwner(f.dsl) + .reserve( + AuthoredDraftPublishSelection.fromStored( + selection.canonicalJson(), selection.digest()) + .intent(), + operation.account(), + operation.world(), + operation.inventory(), + sourceRead)), + "concurrent owner reservation returned no result"); + } + private TemplateConfigSourceSnapshot source(Fixture f, DraftCommitBinding binding) { return new GameDesignSourceRepository(f.dsl) .readSynchronized(f.target, binding.commitId()) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index bdf7f70b82..c47a67dcdb 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -10,6 +10,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Version; @@ -680,12 +681,33 @@ void sqlGuardRejectsMissingInjectedAndMismatchedSelectorBindingsWithoutAnyReleas WorldPublishedStartLocationEvidence evidence = operation.world(); var json = new ObjectMapper(); String original = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); - String participants = - json.writeValueAsString( - PublishedWorldSelectorFixtures.participants(version.getId(), evidence)); + String participants = json.writeValueAsString(selectedParticipants(version.getId(), evidence)); var originalRequest = json.readTree(original).path("request"); assertThat(originalRequest.path("versionStateEpoch").isTextual()).isTrue(); assertThat(originalRequest.path("versionStateEpoch").asText()).matches("[1-9][0-9]*"); + var selectedV1ControlPlaneParticipants = + (tools.jackson.databind.node.ArrayNode) json.readTree(participants); + boolean foundControlPlaneParticipant = false; + for (var participant : selectedV1ControlPlaneParticipants) { + if ("GAME_DESIGN_CONTROL_PLANE".equals(participant.path("participantKey").asText())) { + assertThat(participant.path("digestSchemaVersion").asInt()).isEqualTo(2); + ((tools.jackson.databind.node.ObjectNode) participant).put("digestSchemaVersion", 1); + foundControlPlaneParticipant = true; + break; + } + } + assertThat(foundControlPlaneParticipant).isTrue(); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, + version, + "v2", + original, + json.writeValueAsString(selectedV1ControlPlaneParticipants))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("release v2 participant differs from selected commit/digest/schema"); + assertThat(bundleCount(fixture.dsl())).isZero(); assertThatThrownBy(() -> insertRawSelector(fixture, version, "v2", null, participants)) .isInstanceOf(DataAccessException.class); assertThatThrownBy(() -> insertRawSelector(fixture, version, "v1", original, participants)) @@ -835,14 +857,32 @@ private PublishedReleaseBundle selectorBundle( bundle.setAttestationSchemaVersion("v2"); bundle.setPublishWorkflowId(evidence.request().publishWorkflowId()); bundle.setParticipantDigestsJson( - new ObjectMapper() - .writeValueAsString( - PublishedWorldSelectorFixtures.participants(version.getId(), evidence))); + new ObjectMapper().writeValueAsString(selectedParticipants(version.getId(), evidence))); bundle.setWorldPublishedStartLocationEvidenceJson( new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); return bundle; } + private List selectedParticipants( + long versionId, WorldPublishedStartLocationEvidence evidence) { + return PublishedWorldSelectorFixtures.participants(versionId, evidence).stream() + .map( + participant -> + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + 2, + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) + .toList(); + } + private void insertRawSelector( Fixture fixture, Version version, String schema, String evidence, String participants) { var operationRow = diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index dd5f674ce5..87bc78ddca 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -54,6 +54,11 @@ import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationGrpcCodec; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; @@ -63,6 +68,7 @@ import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import net.firedevops.firemud.gamedesign.draft.GameDesignSelectedDraftPublicationReadGrpcService; import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.PublishAttempt; @@ -82,6 +88,9 @@ import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationCommandService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; @@ -98,8 +107,11 @@ import net.firedevops.firemud.test.TestContainerImages; import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeRequest; import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationRequest; import net.firedevops.firemud.worldmanagement.v1.ReadWorldPublishedStartLocationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldAuthoredSourceIntakeServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.WorldPublishedStartLocationReadServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.WorldSelectedDraftPublicationFreezeServiceGrpc; import org.jooq.DSLContext; @@ -470,7 +482,8 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth selection.intent(), operation.account(), operation.world(), - operation.inventory())); + operation.inventory(), + IsolatedPublicationOwnerSetup.syntheticWorldSourceRead(operation))); assertThat(exactReservationRetry.selection()).isEqualTo(selection); assertThat(exactReservationRetry.operation().canonicalBytes()) .containsExactly(operation.canonicalBytes()); @@ -482,8 +495,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth .getId()); String publishRequestId = operation.account().publishRequestId(); String publishWorkflowId = operation.workflowId(); - var participantDigests = - PublishedWorldSelectorFixtures.participants(candidate.getId(), operation.world()); + var participantDigests = selectedParticipants(candidate.getId(), operation.world()); var expectedDigestBinding = PublicationDigestRequestBinding.full( candidate.getCanonicalTenantId().toString(), @@ -516,6 +528,10 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth Mockito.any(VersionDto.class), Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), Mockito.eq(publishWorkflowId)); + PublishedReleaseBundle bundleBeforeRetry = + publishedReleaseBundleRepository + .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) + .orElseThrow(); VersionDto terminalReplay = versionPublishCommandService.publishSelectedDraftFullVersion( tenantId, @@ -533,6 +549,9 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth publishedReleaseBundleRepository .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) .orElseThrow(); + assertThat(bundle.getId()).isEqualTo(bundleBeforeRetry.getId()); + assertThat(bundle.getPublishedReleaseBundleRef()) + .isEqualTo(bundleBeforeRetry.getPublishedReleaseBundleRef()); VersionAssetArtifact artifact = versionAssetArtifactRepository .findByTenantIdAndVersionId(tenantId, publishedVersion.id()) @@ -555,8 +574,8 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth /** * Exercises the real GD admission, owner reservation, and finalizer. The Account HELD response, - * World freeze/selector, original Draft outcomes, participant digests, and empty export are - * explicitly stipulated test fixtures; this is not genuine upstream production proof. + * World freeze/selector/source read, original Draft outcomes, participant digests, and empty + * export are stipulated test fixtures; this is not genuine upstream producer proof. */ @Test void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Release( @@ -593,6 +612,9 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele AuthoredDraftPublishSelectionBinding.fromStored( selection.canonicalJson(), selection.digest()), prepared.world()); + var stipulatedWorldSourceRead = + IsolatedPublicationOwnerSetup.syntheticWorldSourceRead(operation); + retainStipulatedWorldSourceAndDelivery(stipulatedWorldSourceRead); assertThat(operation.account().input().selection().canonicalBytes()) .containsExactly(selection.canonicalBytes()); assertThat(operation.world().selectorReceiptBytes()) @@ -633,8 +655,7 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele String publishRequestId = operation.account().publishRequestId(); String publishedWorldEvidenceJson = new String(operation.world().canonicalBytes(), StandardCharsets.UTF_8); - var participantDigests = - PublishedWorldSelectorFixtures.participants(candidate.getId(), operation.world()); + var participantDigests = selectedParticipants(candidate.getId(), operation.world()); var expectedDigestBinding = PublicationDigestRequestBinding.full( candidate.getCanonicalTenantId().toString(), @@ -661,11 +682,17 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele new StipulatedAccountPublicationReadEndpoint(operation.account(), heldDenied); var worldEndpoint = new StipulatedWorldPublicationReadEndpoint(operation.world()); var freezeEndpoint = new StipulatedWorldFreezeEndpoint(operation); + var worldSourceEndpoint = + new StipulatedWorldAuthoredSourceIntakeEndpoint(stipulatedWorldSourceRead.receipt()); Server accountServer = publicationOwnerServer(publicationReadIdentities.accountServer(), pki, accountEndpoint); Server worldServer = publicationOwnerServer( - publicationReadIdentities.worldManagementServer(), pki, worldEndpoint, freezeEndpoint); + publicationReadIdentities.worldManagementServer(), + pki, + worldEndpoint, + freezeEndpoint, + worldSourceEndpoint); var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService("127.0.0.1:" + accountServer.getPort()); endpoints.setWorldManagementService("127.0.0.1:" + worldServer.getPort()); @@ -689,6 +716,12 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele publicationReadIdentities.gameDesignClient().properties(pki.ca), new GrpcChannelFactory(), NAMESPACE); + var worldSourceIntakeClient = + new net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient( + endpoints, + publicationReadIdentities.gameDesignClient().properties(pki.ca), + new GrpcChannelFactory(), + NAMESPACE); var worldClient = new WorldPublishedStartLocationClient( endpoints, @@ -698,6 +731,7 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele accountClient.init(); freezeClient.init(); inventoryClient.init(); + worldSourceIntakeClient.init(); worldClient.init(); var command = new SelectedDraftPublicationCommandService( @@ -707,6 +741,7 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele freezeClient, inventoryClient, worldClient, + worldSourceIntakeClient, NAMESPACE, versionPublishCommandService); @@ -716,6 +751,7 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele assertThat(accountEndpoint.readCount()).isEqualTo(1); assertThat(worldEndpoint.readCount()).isZero(); assertThat(freezeEndpoint.beginCount()).isZero(); + assertThat(worldSourceEndpoint.readCount()).isZero(); assertThat(publishAttemptRepository.findByPublishWorkflowId(workflowId)).isEmpty(); assertThat(new GameDesignPublicationOperationRepository(dsl).read(workflowId)).isEmpty(); assertThat( @@ -753,6 +789,7 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) Status.Code.UNAVAILABLE, () -> command.publishSelectedDraftFullVersion(selection.intent(), operation.account())); assertThat(freezeEndpoint.beginCount()).isEqualTo(1); + assertThat(worldSourceEndpoint.readCount()).isZero(); assertThat(new GameDesignPublicationOperationRepository(dsl).read(workflowId)).isEmpty(); assertThat(publishAttemptRepository.findByPublishWorkflowId(workflowId)).isEmpty(); worldEndpoint.unavailable.set(false); @@ -770,6 +807,17 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) assertThat(worldEndpoint.readCount()).isEqualTo(2); assertThat(freezeEndpoint.beginCount()).isEqualTo(2); assertThat(freezeEndpoint.inventoryReadCount()).isEqualTo(2); + assertThat(worldSourceEndpoint.readCount()).isEqualTo(1); + assertThat(worldSourceEndpoint.lastReadRequest()) + .satisfies( + request -> { + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.intakeRequestId()) + .isEqualTo(operation.world().request().intakeRequestId()); + assertThat(request.canonicalTenantId()) + .isEqualTo(operation.world().request().canonicalTenantId()); + assertThat(request.readRequestId()).isNotEqualTo(request.intakeRequestId()); + }); PublishAttempt attempt = publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow(); @@ -811,6 +859,7 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) assertThat(freezeEndpoint.beginCount()).isEqualTo(2); assertThat(accountEndpoint.readCount()).isEqualTo(3); assertThat(worldEndpoint.readCount()).isEqualTo(2); + assertThat(worldSourceEndpoint.readCount()).isEqualTo(1); assertThat(exactRetry.id()).isEqualTo(published.id()); assertThat( publishAttemptRepository.findByPublishWorkflowId(workflowId).orElseThrow().getId()) @@ -848,6 +897,7 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) .isEqualTo(1L); assertThat(accountEndpoint.readCount()).isEqualTo(3); assertThat(worldEndpoint.readCount()).isEqualTo(2); + assertThat(worldSourceEndpoint.readCount()).isEqualTo(1); assertThat(freezeEndpoint.beginCount()).isEqualTo(2); assertThat(versionCountForTenant(tenantId)).isEqualTo(versionCountBeforePublish); @@ -867,6 +917,7 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) .containsExactly(terminalBeforeChangedRetry); assertThat(accountEndpoint.readCount()).isEqualTo(3); assertThat(worldEndpoint.readCount()).isEqualTo(2); + assertThat(worldSourceEndpoint.readCount()).isEqualTo(1); assertThat(freezeEndpoint.beginCount()).isEqualTo(2); assertThat(versionCountForTenant(tenantId)).isEqualTo(versionCountBeforePublish); } @@ -995,7 +1046,8 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( changedIntent, operation.account(), operation.world(), - operation.inventory()))) + operation.inventory(), + IsolatedPublicationOwnerSetup.syntheticWorldSourceRead(operation)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("changed notes"); @@ -1014,7 +1066,8 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( selection.intent(), changedAccount, operation.world(), - operation.inventory()))) + operation.inventory(), + IsolatedPublicationOwnerSetup.syntheticWorldSourceRead(operation)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("World public inventory differs from exact selected Account order"); @@ -1181,8 +1234,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( long selectedCandidateVersionId = candidate.getId(); candidateVersionId.set(selectedCandidateVersionId); candidateVersionNumber.set(candidate.getVersionNumber()); - var participantDigests = - PublishedWorldSelectorFixtures.participants(candidate.getId(), operation.world()); + var participantDigests = selectedParticipants(candidate.getId(), operation.world()); var expectedDigestBinding = PublicationDigestRequestBinding.full( candidate.getCanonicalTenantId().toString(), @@ -1653,6 +1705,112 @@ private static Server publicationOwnerServer( return builder.build().start(); } + private void retainStipulatedWorldSourceAndDelivery( + SelectedDraftTemplateWorldSourceAssociation.SourceRead worldSourceRead) { + var source = worldSourceRead.receipt().source(); + ByIdReadRequest byIdRequest = worldSourceRead.request(); + IntakeRequest intakeRequest = + new IntakeRequest( + source.schemaVersion(), + source.targetNamespace(), + byIdRequest.intakeRequestId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + String intakeRequestDigest = WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intakeRequest); + // Preserve the selected World intake identity exactly; the repository's normal registration + // allocates a different random delivery identity. SQL guards and canonical repository reads + // still validate the stipulated source and delivery tuples against this Game row. + inOwnerTransaction( + () -> { + 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()); + 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()); + dsl.execute( + "INSERT INTO game_design_authored_world_source_deliveries " + + "(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, " + + "intake_schema_version, intake_request_id, intake_request_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(), + intakeRequest.schemaVersion(), + intakeRequest.intakeRequestId(), + intakeRequestDigest); + return null; + }); + + var sourceRepository = new GameAuthoredWorldSourceRepository(dsl); + assertThat( + sourceRepository.read( + source.operationId(), + source.canonicalTenantId(), + source.worldSlug(), + source.targetNamespace())) + .contains(source); + var deliveryRepository = new GameAuthoredWorldSourceDeliveryRepository(dsl); + var pendingClaim = deliveryRepository.read(source.operationId()).orElseThrow(); + assertThat(pendingClaim.source()).isEqualTo(source); + assertThat(pendingClaim.request()).isEqualTo(intakeRequest); + assertThat(pendingClaim.acknowledgedReceipt()).isEmpty(); + PublicReceipt publicReceipt = worldSourceRead.receipt(); + CommittedReceipt committedReceipt = + new CommittedReceipt( + publicReceipt.schemaVersion(), + publicReceipt.targetNamespace(), + publicReceipt.intakeRequestId(), + publicReceipt.operationId(), + publicReceipt.canonicalTenantId(), + publicReceipt.worldSlug(), + publicReceipt.sourceOperationId(), + publicReceipt.sourceEvidenceDigest(), + publicReceipt.requestDigest(), + publicReceipt.receiptDigest()); + inOwnerTransaction(() -> deliveryRepository.acknowledge(pendingClaim, committedReceipt)); + assertThat(deliveryRepository.read(source.operationId()).orElseThrow().acknowledgedReceipt()) + .contains(committedReceipt); + } + private static boolean requireGameDesignPeer(StreamObserver observer) { var peer = GrpcPeerIdentity.current(); if (peer == null) { @@ -1887,6 +2045,67 @@ int readCount() { } } + /** Test-only authenticated source read; source evidence remains explicitly stipulated. */ + private static final class StipulatedWorldAuthoredSourceIntakeEndpoint + extends WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceImplBase { + private final PublicReceipt expectedReceipt; + private final AtomicInteger reads = new AtomicInteger(); + private final AtomicReference lastRequest = new AtomicReference<>(); + + private StipulatedWorldAuthoredSourceIntakeEndpoint(PublicReceipt expectedReceipt) { + this.expectedReceipt = expectedReceipt; + } + + @Override + public void readAuthoredWorldSourceIntakeById( + ReadAuthoredWorldSourceIntakeByIdRequest request, + StreamObserver observer) { + if (!requireGameDesignPeer(observer)) return; + reads.incrementAndGet(); + final ByIdReadRequest decoded; + try { + decoded = WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdRequest(request); + } catch (IllegalArgumentException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Invalid stipulated authored-source read request") + .asRuntimeException()); + return; + } + if (!NAMESPACE.equals(decoded.targetNamespace()) + || !expectedReceipt.intakeRequestId().equals(decoded.intakeRequestId()) + || !expectedReceipt.canonicalTenantId().equals(decoded.canonicalTenantId())) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Different stipulated authored-source selector") + .asRuntimeException()); + return; + } + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Authored-source owner read must precede local reservation") + .asRuntimeException()); + return; + } + lastRequest.set(decoded); + observer.onNext( + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse(decoded, expectedReceipt)); + observer.onCompleted(); + } + + int readCount() { + return reads.get(); + } + + ByIdReadRequest lastReadRequest() { + return lastRequest.get(); + } + } + private static GameDesignPublicationTerminalReadClient terminalReadClient( int port, SelectionReadTestIdentity identity, Path ca) throws Exception { var endpoints = new ServiceEndpointsProperties(); @@ -2171,6 +2390,26 @@ private static String firstStackFrame(Throwable failure) { return failure.getStackTrace()[0].toString(); } + private static List selectedParticipants( + long versionId, WorldPublishedStartLocationEvidence evidence) { + return PublishedWorldSelectorFixtures.participants(versionId, evidence).stream() + .map( + participant -> + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + 2, + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) + .toList(); + } + private static boolean sameCanonicalPreimage( PublicationDigestRequestBinding actual, PublicationDigestRequestBinding expected) { return actual != null diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadServiceTest.java new file mode 100644 index 0000000000..09ed793be6 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadServiceTest.java @@ -0,0 +1,668 @@ +package net.firedevops.firemud.gamedesign.publication; + +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.inOrder; +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.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.ObjectMapper; + +/** Structural owner-read proof; mocks do not establish physical PostgreSQL source provenance. */ +class SelectedDraftAssetInventoryReadServiceTest { + private final SelectedDraftAssetInventoryReadService.OwnerRead owner = + mock(SelectedDraftAssetInventoryReadService.OwnerRead.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final TransactionStatus transactionStatus = mock(TransactionStatus.class); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void readsExactCapturedFamiliesAndRetainedGameLogicInOneReadOnlySnapshot() throws Exception { + var fixture = fixture(); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(fixture.request().derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readGenesis(fixture.binding().target())).thenReturn(Optional.of(fixture.genesis())); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(fixture.sources())); + when(owner.readGameLogicReceipt(fixture.request())) + .thenReturn(Optional.of(fixture.gameLogicReceipt())); + + var inventory = + new SelectedDraftAssetInventoryReadService(owner, transactions).read(fixture.request()); + + assertThat(inventory.request()).isSameAs(fixture.request()); + assertThat(inventory.operation()).isEqualTo(fixture.operation()); + assertThat(inventory.selectedCommit()).isEqualTo(fixture.binding()); + assertThat(inventory.gameLogicReceipt()).isEqualTo(fixture.gameLogicReceipt()); + assertThat(inventory.assets()).isEmpty(); + assertThat(inventory.sourceFamilyDeclarations()) + .containsEntry("ORDINARY", "EMPTY") + .containsEntry("BRANDING:RESOURCE", "EMPTY") + .containsEntry("BRANDING:LOGO", "EMPTY") + .containsEntry("BRANDING:FAVICON", "EMPTY") + .containsEntry("BRANDING:THEME", "EMPTY") + .containsEntry("GAMEPLAY_RULE", "EMPTY") + .containsEntry("TEMPLATE_CONFIG", "EMPTY"); + assertThat(inventory.canonicalJson()).contains(SelectedDraftAssetInventory.SCHEMA); + byte[] canonical = inventory.canonicalBytes(); + canonical[0] ^= 1; + assertThat(inventory.canonicalBytes()).isNotEqualTo(canonical); + + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + var order = inOrder(transactions, owner); + order.verify(transactions).getTransaction(definition.capture()); + order.verify(owner).read(fixture.request().derivedWorkflowIdentity()); + order.verify(owner).requireExactSelection(fixture.operation()); + order.verify(owner).readGenesis(fixture.binding().target()); + order.verify(owner).readSourceCapture(fixture.operation()); + order.verify(owner).readSynchronized(fixture.binding().target(), fixture.binding().commitId()); + order.verify(owner).readGameLogicReceipt(fixture.request()); + order.verify(transactions).commit(transactionStatus); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(definition.getValue().isReadOnly()).isTrue(); + verify(owner, never()).readAssetBytes(any(), any()); + } + + @Test + void missingReceiptOrSelectedSourceFamilyCannotBeReclassifiedAsEmpty() throws Exception { + var fixture = fixture(); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(fixture.request().derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readGenesis(fixture.binding().target())).thenReturn(Optional.of(fixture.genesis())); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(fixture.sources())); + when(owner.readGameLogicReceipt(fixture.request())).thenReturn(Optional.empty()); + var service = new SelectedDraftAssetInventoryReadService(owner, transactions); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(fixture.request())); + verify(owner, never()).readAssetBytes(any(), any()); + + org.mockito.Mockito.reset(owner); + when(owner.read(fixture.request().derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readGenesis(fixture.binding().target())).thenReturn(Optional.empty()); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(fixture.request())); + verify(owner, never()).readSourceCapture(any()); + + org.mockito.Mockito.reset(owner); + when(owner.read(fixture.request().derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readGenesis(fixture.binding().target())).thenReturn(Optional.of(fixture.genesis())); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + var missingBranding = + new GameDesignSourceRepository.SynchronizedSources( + fixture.sources().command(), + fixture.sources().policy(), + fixture.sources().asset(), + fixture.sources().gameplay(), + Optional.empty(), + fixture.sources().templateConfig()); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(missingBranding)); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(fixture.request())); + verify(owner, never()).readGameLogicReceipt(any()); + } + + @Test + void rejectsAmbientTransactionBeforeAnyOwnerRead() throws Exception { + var fixture = fixture(); + var service = new SelectedDraftAssetInventoryReadService(owner, transactions); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, () -> service.read(fixture.request())); + verifyNoInteractions(owner, transactions); + } + + @Test + void inventoryAssetBytesAreDefensivelyCopiedAndOptionalIsUnsupported() throws Exception { + var fixture = fixture(); + byte[] bytes = "exact owner bytes".getBytes(StandardCharsets.UTF_8); + var asset = + new SelectedDraftAssetInventory.Asset( + SelectedDraftAssetInventory.Family.ORDINARY, + "RESOURCE", + "world/map.bin", + "42", + "REQUIRED", + fixture.binding(), + "0", + UUID.fromString("77777777-7777-4777-8777-777777777777"), + "application/octet-stream", + CommandSource.sha256(bytes), + bytes); + bytes[0] ^= 1; + byte[] exposed = asset.contentBytes(); + exposed[0] ^= 1; + assertThat(asset.contentBytes()) + .isEqualTo("exact owner bytes".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy( + () -> + new SelectedDraftAssetInventory.Asset( + SelectedDraftAssetInventory.Family.ORDINARY, + "RESOURCE", + "optional.bin", + "43", + "OPTIONAL", + fixture.binding(), + "0", + UUID.fromString("88888888-8888-4888-8888-888888888888"), + "application/octet-stream", + CommandSource.sha256(new byte[] {1}), + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void resolvesPresentOrdinaryAndBrandingReferencesToExactTenantQualifiedBytes() throws Exception { + var empty = fixture(); + byte[] ordinaryBytes = "ordinary map".getBytes(StandardCharsets.UTF_8); + byte[] brandingBytes = "branding logo".getBytes(StandardCharsets.UTF_8); + var fixture = + withAssets(empty, "world/map.bin", ordinaryBytes, "branding/logo.png", brandingBytes); + stubOperationAndSources(fixture); + when(owner.readGameLogicReceipt(fixture.request())) + .thenReturn(Optional.of(fixture.gameLogicReceipt())); + when(owner.readAssetBytes("tenant-key", "42")) + .thenReturn( + Optional.of( + new SelectedDraftAssetInventoryReadService.AssetBytes( + "world/map.bin", "application/octet-stream", ordinaryBytes))); + when(owner.readAssetBytes("tenant-key", "43")) + .thenReturn( + Optional.of( + new SelectedDraftAssetInventoryReadService.AssetBytes( + "branding/logo.png", "image/png", brandingBytes))); + + var inventory = + new SelectedDraftAssetInventoryReadService(owner, transactions).read(fixture.request()); + + assertThat(inventory.assets()).hasSize(2); + assertThat(inventory.assets()) + .extracting(SelectedDraftAssetInventory.Asset::usageKey) + .containsExactly("branding/logo.png", "world/map.bin"); + var branding = inventory.assets().getFirst(); + assertThat(branding.family()).isEqualTo(SelectedDraftAssetInventory.Family.BRANDING); + assertThat(branding.role()).isEqualTo("LOGO"); + assertThat(branding.requiredness()).isEqualTo("REQUIRED"); + assertThat(branding.contentBytes()).isEqualTo(brandingBytes); + assertThat(branding.contentDigest()).isEqualTo(CommandSource.sha256(brandingBytes)); + assertThat(branding.revisionId()) + .isEqualTo( + fixture.sources().branding().orElseThrow().items().getFirst().reference().revisionId()); + assertThat(branding.sourceBinding()).isNotEqualTo(fixture.binding()); + var ordinary = inventory.assets().getLast(); + assertThat(ordinary.family()).isEqualTo(SelectedDraftAssetInventory.Family.ORDINARY); + assertThat(ordinary.role()).isEqualTo("RESOURCE"); + assertThat(ordinary.contentBytes()).isEqualTo(ordinaryBytes); + assertThat(ordinary.contentDigest()).isEqualTo(CommandSource.sha256(ordinaryBytes)); + assertThat(ordinary.revisionId()) + .isEqualTo(fixture.sources().asset().items().getFirst().reference().revisionId()); + assertThat(ordinary.sourceBinding()).isNotEqualTo(fixture.binding()); + assertThat(inventory.sourceFamilyDeclarations()) + .containsEntry("ORDINARY", "PRESENT") + .containsEntry("BRANDING:LOGO", "PRESENT"); + var canonicalInventory = new ObjectMapper().readTree(inventory.canonicalJson()); + assertThat(canonicalInventory.path("assets").get(0).path("sourceBindingJson").textValue()) + .isEqualTo(branding.sourceBinding().canonicalJson()); + assertThat(canonicalInventory.path("assets").get(1).path("sourceBindingJson").textValue()) + .isEqualTo(ordinary.sourceBinding().canonicalJson()); + assertThat(canonicalInventory.path("assets").get(1).path("byteSize").textValue()) + .isEqualTo(Integer.toString(ordinaryBytes.length)); + verify(owner).readAssetBytes("tenant-key", "42"); + verify(owner).readAssetBytes("tenant-key", "43"); + } + + @Test + void rejectsActualByteMismatchAndCrossFamilyUsageKeyCollisionBeforeReturningInventory() + throws Exception { + var empty = fixture(); + byte[] ordinaryBytes = "ordinary map".getBytes(StandardCharsets.UTF_8); + byte[] brandingBytes = "branding logo".getBytes(StandardCharsets.UTF_8); + var fixture = + withAssets(empty, "shared.bin", ordinaryBytes, "branding/logo.png", brandingBytes); + stubOperationAndSources(fixture); + when(owner.readGameLogicReceipt(fixture.request())) + .thenReturn(Optional.of(fixture.gameLogicReceipt())); + when(owner.readAssetBytes("tenant-key", "42")) + .thenReturn( + Optional.of( + new SelectedDraftAssetInventoryReadService.AssetBytes( + "shared.bin", + "application/octet-stream", + "changed".getBytes(StandardCharsets.UTF_8)))); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + new SelectedDraftAssetInventoryReadService(owner, transactions) + .read(fixture.request())); + + org.mockito.Mockito.reset(owner); + var collision = + withAssets(empty, "duplicate.png", ordinaryBytes, "duplicate.png", brandingBytes); + stubOperationAndSources(collision); + when(owner.readGameLogicReceipt(collision.request())) + .thenReturn(Optional.of(collision.gameLogicReceipt())); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + new SelectedDraftAssetInventoryReadService(owner, transactions) + .read(collision.request())); + verify(owner, never()).readAssetBytes(any(), any()); + + org.mockito.Mockito.reset(owner); + assertThatThrownBy( + () -> + AssetSource.upsertPayload("44", "manifest.json", AssetSource.Requiredness.REQUIRED)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + BrandingSource.upsertPayload( + "45", + "manifest.json", + BrandingSource.Role.LOGO, + BrandingSource.Requiredness.REQUIRED)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void missingOrCorruptCaptureChangedSourceAndDifferentReceiptSelectionAreDenied() + throws Exception { + var fixture = fixture(); + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(fixture.request().derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readGenesis(fixture.binding().target())).thenReturn(Optional.of(fixture.genesis())); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.empty()); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + new SelectedDraftAssetInventoryReadService(owner, transactions) + .read(fixture.request())); + verify(owner, never()).readSynchronized(any(), any()); + + org.mockito.Mockito.reset(owner); + stubOperationAndSources(fixture); + var changedSelection = receiptWithChangedSelection(fixture).selection(); + var changedSelectionBinding = + AuthoredDraftPublishSelectionBinding.fromStored( + changedSelection.canonicalJson(), changedSelection.digest()); + var anotherOperation = + IsolatedPublicationOperationFixtures.forSelection( + changedSelectionBinding, fixture.operation().world()); + assertThat(anotherOperation.account().input().selection().canonicalJson()) + .isNotEqualTo(fixture.operation().account().input().selection().canonicalJson()); + when(owner.readSourceCapture(fixture.operation())) + .thenReturn(Optional.of(capture(anotherOperation, fixture.sources()))); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + new SelectedDraftAssetInventoryReadService(owner, transactions) + .read(fixture.request())); + verify(owner, never()).readSynchronized(any(), any()); + + org.mockito.Mockito.reset(owner); + stubOperationAndSources(fixture); + var changedAsset = + new AssetSnapshot( + fixture.binding(), "1", null, fixture.genesis().asset().receiptId(), List.of()); + var changedSources = + new GameDesignSourceRepository.SynchronizedSources( + fixture.sources().command(), + fixture.sources().policy(), + changedAsset, + fixture.sources().gameplay(), + fixture.sources().branding(), + fixture.sources().templateConfig()); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(changedSources)); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + new SelectedDraftAssetInventoryReadService(owner, transactions) + .read(fixture.request())); + verify(owner, never()).readGameLogicReceipt(any()); + + org.mockito.Mockito.reset(owner); + stubOperationAndSources(fixture); + var changedReceipt = receiptWithChangedSelection(fixture); + assertThat(changedReceipt.selection().selectedCommit()).isEqualTo(fixture.binding()); + assertThat(changedReceipt.selection().canonicalJson()) + .isNotEqualTo(fixture.operation().account().input().selection().canonicalJson()); + assertThat(changedReceipt.workflowIdentity()).isEqualTo(fixture.operation().workflowId()); + when(owner.readGameLogicReceipt(fixture.request())).thenReturn(Optional.of(changedReceipt)); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + new SelectedDraftAssetInventoryReadService(owner, transactions) + .read(fixture.request())); + verify(owner, never()).readAssetBytes(any(), any()); + } + + private static Fixture fixture() throws Exception { + var operation = + IsolatedPublicationOperationFixtures.fresh( + new TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW")); + var binding = operation.account().input().selection().selectedCommit(); + var gameplay = + new GameplayRuleSnapshot( + binding, "0", null, UUID.fromString("44444444-4444-4444-8444-444444444444"), List.of()); + var source = new GameplayRuleSelectedSource(gameplay.canonicalJson()); + UUID actor = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + var authorization = + new GameLogicIntakeAuthorizationBinding( + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + actor, + source, + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var intake = new GameLogicGameplayRuleIntakeOperation("test", authorization); + var terminal = + GameLogicGameplayRuleIntakeTerminal.retained( + intake, + source.canonicalBytes(), + gameplay.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var receipt = + new SelectedDraftGameLogicReceipt( + AuthoredDraftPublishSelection.fromStored( + operation.account().input().selection().canonicalJson(), + operation.account().input().selection().digest()), + authorization, + new AccountGameLogicIntakeSettlementEvidence(terminal)); + var sources = sources(binding, gameplay); + var genesis = genesis(binding.target()); + var capture = capture(operation, sources); + var request = + PublicationDigestRequestBinding.full( + operation.account().input().selection().intent().canonicalTenantId().toString(), + Long.toString(operation.versionId()), + operation.account().input().selection().intent().publishRequestId()); + return new Fixture(operation, binding, genesis, sources, capture, receipt, request); + } + + private Fixture withAssets( + Fixture base, + String ordinaryUsageKey, + byte[] ordinaryBytes, + String brandingUsageKey, + byte[] brandingBytes) { + var ordinarySource = + sourceBinding( + base.binding().target(), + AssetSource.SCOPE, + AssetSource.upsertPayload("42", ordinaryUsageKey, AssetSource.Requiredness.REQUIRED)); + var ordinaryReference = + new AssetSource.Reference( + ordinaryUsageKey, + "42", + AssetSource.Requiredness.REQUIRED, + ordinarySource, + "0", + ordinarySource.revisions().getFirst().revisionId()); + var ordinaryItem = + new AssetSnapshot.Item( + ordinaryReference, + "application/octet-stream", + CommandSource.sha256(ordinaryBytes), + ordinaryBytes.length); + + var brandingSource = + sourceBinding( + base.binding().target(), + BrandingSource.SCOPE, + BrandingSource.upsertPayload( + "43", + brandingUsageKey, + BrandingSource.Role.LOGO, + BrandingSource.Requiredness.REQUIRED)); + var brandingReference = + new BrandingSource.Reference( + brandingUsageKey, + "43", + BrandingSource.Role.LOGO, + BrandingSource.Requiredness.REQUIRED, + brandingSource, + "0", + brandingSource.revisions().getFirst().revisionId()); + var brandingItem = + new BrandingSourceSnapshot.Item( + brandingReference, + "image/png", + CommandSource.sha256(brandingBytes), + brandingBytes.length); + + var assetSnapshot = + new AssetSnapshot( + base.binding(), "1", null, base.genesis().asset().receiptId(), List.of(ordinaryItem)); + var brandingSnapshot = + new BrandingSourceSnapshot( + base.binding(), + "1", + null, + base.genesis().branding().receiptId(), + List.of(brandingItem)); + var sources = + new GameDesignSourceRepository.SynchronizedSources( + base.sources().command(), + base.sources().policy(), + assetSnapshot, + base.sources().gameplay(), + Optional.of(brandingSnapshot), + base.sources().templateConfig()); + return new Fixture( + base.operation(), + base.binding(), + base.genesis(), + sources, + capture(base.operation(), sources), + base.gameLogicReceipt(), + base.request()); + } + + private static DraftCommitBinding sourceBinding( + TargetProof target, String scope, String payload) { + UUID revisionId = UUID.randomUUID(); + String scopeId = "effective"; + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "source-parent", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", revisionId, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + scope, + target.canonicalVersionId().toString(), + scope, + scopeId, + "0"))); + } + + private static GameDesignSourceRepository.Capture capture( + GameDesignPublicationOperation operation, + GameDesignSourceRepository.SynchronizedSources sources) { + return new GameDesignSourceRepository.Capture( + new CommandSnapshot.Capture(operation, sources.command()), + new RealmPolicySnapshot.Capture(operation, sources.policy()), + new AssetSnapshot.Capture(operation, sources.asset()), + new BrandingSourceSnapshot.Capture(operation, sources.branding().orElseThrow()), + new TemplateConfigSourceSnapshot.Capture( + operation, sources.templateConfig().orElseThrow())); + } + + private void stubOperationAndSources(Fixture fixture) { + when(transactions.getTransaction(any())).thenReturn(transactionStatus); + when(owner.read(fixture.request().derivedWorkflowIdentity())) + .thenReturn( + Optional.of( + new GameDesignPublicationOperationRepository.Readback( + fixture.operation(), "PENDING", new byte[] {1}))); + when(owner.readGenesis(fixture.binding().target())).thenReturn(Optional.of(fixture.genesis())); + when(owner.readSourceCapture(fixture.operation())).thenReturn(Optional.of(fixture.capture())); + when(owner.readSynchronized(fixture.binding().target(), fixture.binding().commitId())) + .thenReturn(Optional.of(fixture.sources())); + } + + private static SelectedDraftGameLogicReceipt receiptWithChangedSelection(Fixture fixture) { + var original = fixture.operation().account().input().selection(); + var intent = original.intent(); + var changedIntent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes() + " changed", + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + var changed = + AuthoredDraftPublishSelectionBinding.capture( + changedIntent, + original.target(), + original.selectedCommit(), + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + original.target(), + original.fenceRequestId(), + original.fenceCommitId(), + original.fenceInputDigest(), + original.fenceResultVectorJson(), + OffsetDateTime.parse(original.fenceCreatedAt()))); + var selection = + AuthoredDraftPublishSelection.fromStored(changed.canonicalJson(), changed.digest()); + return new SelectedDraftGameLogicReceipt( + selection, + fixture.gameLogicReceipt().authorization(), + fixture.gameLogicReceipt().receipt()); + } + + private static GameDesignSourceRepository.Genesis genesis(TargetProof target) { + UUID commandPolicyReceipt = UUID.fromString("99999999-9999-4999-8999-999999999999"); + return new GameDesignSourceRepository.Genesis( + new RealmPolicyGenesis(target, commandPolicyReceipt, "1"), + new CommandSource.NewDraftGenesisReceipt(target, commandPolicyReceipt, "1"), + new AssetSnapshot.Genesis( + target, UUID.fromString("33333333-3333-4333-8333-333333333333"), "1"), + new GameplayRuleSnapshot.Genesis( + target, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "1", + GameplayRuleManifest.explicitEmpty()), + new BrandingSourceSnapshot.Genesis( + target, UUID.fromString("55555555-5555-4555-8555-555555555555"), "1"), + new TemplateConfigSourceSnapshot.Genesis( + target, UUID.fromString("66666666-6666-4666-8666-666666666666"), "1")); + } + + private static GameDesignSourceRepository.SynchronizedSources sources( + DraftCommitBinding binding, GameplayRuleSnapshot gameplay) { + var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of()); + var policies = + binding.revisions().stream() + .filter( + revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE) + .filter(RealmPolicySource::isPolicyRevision) + .map(revision -> RealmPolicySource.revision(binding, revision)) + .toList(); + var policy = new RealmPolicySnapshot(binding, "1", policies); + var asset = + new AssetSnapshot( + binding, "0", null, UUID.fromString("33333333-3333-4333-8333-333333333333"), List.of()); + var branding = + new BrandingSourceSnapshot( + binding, "0", null, UUID.fromString("55555555-5555-4555-8555-555555555555"), List.of()); + var template = + new TemplateConfigSourceSnapshot( + binding, "0", null, UUID.fromString("66666666-6666-4666-8666-666666666666"), List.of()); + return new GameDesignSourceRepository.SynchronizedSources( + command, policy, asset, gameplay, Optional.of(branding), Optional.of(template)); + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private record Fixture( + GameDesignPublicationOperation operation, + DraftCommitBinding binding, + GameDesignSourceRepository.Genesis genesis, + GameDesignSourceRepository.SynchronizedSources sources, + GameDesignSourceRepository.Capture capture, + SelectedDraftGameLogicReceipt gameLogicReceipt, + PublicationDigestRequestBinding request) {} +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java index 955909d95e..3244558b79 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java @@ -23,9 +23,15 @@ import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +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.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.PlatformTransactionManager; @@ -44,6 +50,28 @@ void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws var freeze = freezeClient(fixture); var inventory = inventoryClient(fixture); var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var sourceFixture = sourceFixture(fixture.worldRequest()); + when(sourceIntake.readById(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return sourceReceipt(invocation.getArgument(0), sourceFixture); + }); + when(sourceRepository.read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(sourceFixture.source())); + when(deliveryRepository.read(sourceFixture.source().operationId())) + .thenReturn( + Optional.of( + new GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim( + sourceFixture.source(), sourceFixture.intakeRequest(), Optional.empty()))); var owner = mock(SelectedDraftPublicationOwner.class); var reader = mock(SelectedDraftPublicationAdmissionService.SelectionReader.class); var transactions = mock(PlatformTransactionManager.class); @@ -78,20 +106,64 @@ void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws Arrays.equals( binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), same(fixture.operation().world()), - same(fixture.operation().inventory()))) + same(fixture.operation().inventory()), + any())) .thenReturn(reservation); var service = new SelectedDraftPublicationAdmissionService( - transactions, account, freeze, inventory, world, owner, reader, NAMESPACE); + transactions, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + reader, + NAMESPACE); assertThat(service.admitAndReserve(fixture.intent(), fixture.operation().account())) .isSameAs(reservation); - var order = inOrder(reader, account, freeze, inventory, world, transactions, owner); + var order = + inOrder( + reader, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + transactions, + owner); order.verify(reader).read(fixture.intent()); order.verify(account).read(any()); order.verify(freeze).begin(any()); order.verify(inventory).read(any()); order.verify(world).read(fixture.worldRequest()); + order + .verify(sourceIntake) + .readById( + argThat( + request -> + request.schemaVersion() == 1 + && request.targetNamespace().equals(NAMESPACE) + && request + .intakeRequestId() + .equals(fixture.worldRequest().intakeRequestId()) + && request + .canonicalTenantId() + .equals(fixture.worldRequest().canonicalTenantId()) + && !request.readRequestId().equals(request.intakeRequestId()))); + order + .verify(sourceRepository) + .read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE); + order.verify(deliveryRepository).read(sourceFixture.source().operationId()); order.verify(transactions).getTransaction(any()); order .verify(owner) @@ -102,7 +174,8 @@ void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws Arrays.equals( binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), same(fixture.operation().world()), - same(fixture.operation().inventory())); + same(fixture.operation().inventory()), + any()); } @Test @@ -112,6 +185,9 @@ void missingRetainedSelectionNeverReadsAccountFreezesWorldOrOpensSql() throws Ex var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); var owner = mock(SelectedDraftPublicationOwner.class); var transactions = mock(PlatformTransactionManager.class); var service = @@ -121,6 +197,9 @@ void missingRetainedSelectionNeverReadsAccountFreezesWorldOrOpensSql() throws Ex freeze, inventory, world, + sourceIntake, + sourceRepository, + deliveryRepository, owner, intent -> Optional.empty(), NAMESPACE); @@ -129,7 +208,96 @@ void missingRetainedSelectionNeverReadsAccountFreezesWorldOrOpensSql() throws Ex () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SELECTION_UNAVAILABLE"); - verifyNoInteractions(account, freeze, inventory, world, owner, transactions); + verifyNoInteractions( + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + transactions); + } + + @Test + void mismatchedRetainedDeliveryAcknowledgementDeniesBeforeReservation() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var sourceFixture = sourceFixture(fixture.worldRequest()); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + when(sourceIntake.readById(any())) + .thenAnswer(invocation -> sourceReceipt(invocation.getArgument(0), sourceFixture)); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + when(sourceRepository.read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(sourceFixture.source())); + var receipt = + sourceReceipt( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + NAMESPACE, + UUID.randomUUID(), + fixture.worldRequest().intakeRequestId(), + fixture.worldRequest().canonicalTenantId()), + sourceFixture); + var wrongAcknowledgement = + new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + "sha256:" + "b".repeat(64)); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + when(deliveryRepository.read(sourceFixture.source().operationId())) + .thenReturn( + Optional.of( + new GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim( + sourceFixture.source(), + sourceFixture.intakeRequest(), + Optional.of(wrongAcknowledgement)))); + var world = mock(WorldPublishedStartLocationClient.class); + when(world.read(fixture.worldRequest())).thenReturn(fixture.operation().world()); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freezeClient(fixture), + inventoryClient(fixture), + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest())), + NAMESPACE); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("OWNER_READBACK_CONFLICT"); + verifyNoInteractions(transactions, owner); } @Test @@ -139,6 +307,9 @@ void freezeFailureNeverReadsSelectorOrReserves() throws Exception { var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); var owner = mock(SelectedDraftPublicationOwner.class); var transactions = mock(PlatformTransactionManager.class); var selection = fixture.operation().account().input().selection(); @@ -149,6 +320,9 @@ void freezeFailureNeverReadsSelectorOrReserves() throws Exception { freeze, inventory, world, + sourceIntake, + sourceRepository, + deliveryRepository, owner, intent -> Optional.of( @@ -192,6 +366,9 @@ void missingInventoryAfterAcknowledgedFreezeNeverReadsSelectorOrOpensSql() throw }); var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); var owner = mock(SelectedDraftPublicationOwner.class); var transactions = mock(PlatformTransactionManager.class); var selection = fixture.operation().account().input().selection(); @@ -202,6 +379,9 @@ void missingInventoryAfterAcknowledgedFreezeNeverReadsSelectorOrOpensSql() throw freezeClient(fixture), inventory, world, + sourceIntake, + sourceRepository, + deliveryRepository, owner, intent -> Optional.of( @@ -213,7 +393,8 @@ void missingInventoryAfterAcknowledgedFreezeNeverReadsSelectorOrOpensSql() throw .isInstanceOf(IllegalStateException.class) .hasMessageContaining("inventory readback"); verify(inventory).read(any()); - verifyNoInteractions(world, owner, transactions); + verifyNoInteractions( + world, sourceIntake, sourceRepository, deliveryRepository, owner, transactions); } @Test @@ -337,6 +518,9 @@ private static SelectedDraftPublicationAdmissionService service( freezeClient(fixture), inventoryClient(fixture), worldClient, + mock(WorldAuthoredSourceIntakeClient.class), + mock(GameAuthoredWorldSourceRepository.class), + mock(GameAuthoredWorldSourceDeliveryRepository.class), owner, intent -> Optional.of( @@ -385,6 +569,76 @@ private static WorldSelectedDraftPublicationFreezeClient freezeClient(Fixture fi return client; } + private static SourceFixture sourceFixture(WorldPublishedStartLocationEvidence.Request selected) { + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "fixture-tenant"; + String worldSlug = "fixture-world"; + String worldDisplayName = "Fixture World"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + selected.targetNamespace(), + registrationRequestId, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + var source = + new AuthoredWorldSourceEvidence( + 1, + selected.targetNamespace(), + registrationRequestId, + sourceOperationId, + requestDigest, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + "tenant-key", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + selected.targetNamespace(), + registrationRequestId, + sourceOperationId, + requestDigest, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + "tenant-key", + "NEW_GAME_ROW")); + var intakeRequest = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + selected.targetNamespace(), + selected.intakeRequestId(), + selected.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + return new SourceFixture(source, intakeRequest); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt sourceReceipt( + WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest request, SourceFixture fixture) { + var source = fixture.source(); + return new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + request.targetNamespace(), + request.intakeRequestId(), + UUID.nameUUIDFromBytes( + "synthetic-world-operation".getBytes(java.nio.charset.StandardCharsets.UTF_8)), + request.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(fixture.intakeRequest()), + "sha256:" + "a".repeat(64), + source); + } + private static Fixture fixture() throws Exception { var target = new TargetProof( @@ -414,4 +668,8 @@ private record Fixture( GameDesignPublicationOperation operation, AuthoredDraftPublishSelection.PublishIntent intent, WorldPublishedStartLocationEvidence.Request worldRequest) {} + + private record SourceFixture( + AuthoredWorldSourceEvidence source, + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest intakeRequest) {} } 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 index 9ad35f6623..2e4857f0b3 100644 --- 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 @@ -208,7 +208,14 @@ Optional readInOwnerReadOnlyRepeatableRead( */ Optional readInOwnerActivationTransaction( String namespace, UUID intakeRequestId) { - requireWritableActivationTransaction(); + requireWritablePhysicalReadCommittedOwnerTransaction(); + return readValidated(namespace, intakeRequestId); + } + + /** Reads the same immutable intake inside the writable publication-owner transaction. */ + Optional readInOwnerPublicationTransaction( + String namespace, UUID intakeRequestId) { + requireWritablePhysicalReadCommittedOwnerTransaction(); return readValidated(namespace, intakeRequestId); } @@ -527,13 +534,13 @@ private void requireReadOnlyRepeatableReadOwnerTransaction() { } } - private void requireWritableActivationTransaction() { + private void requireWritablePhysicalReadCommittedOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly() || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { throw new IllegalStateException( - "World authored-source activation read requires a writable READ COMMITTED owner transaction"); + "World authored-source owner read requires a writable READ COMMITTED owner transaction"); } Record state = Objects.requireNonNull( @@ -544,7 +551,7 @@ private void requireWritableActivationTransaction() { if (!"read committed".equals(state.get("isolation", String.class)) || !"off".equals(state.get("read_only", String.class))) { throw new IllegalStateException( - "World authored-source activation read requires a writable READ COMMITTED owner transaction"); + "World authored-source owner read requires a writable READ COMMITTED owner transaction"); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java index bef80a1324..d10d51bae1 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java @@ -31,6 +31,11 @@ public class WorldDesignPublicationFenceRepository { private static final String FROZEN = "FROZEN"; private static final UUID NIL_UUID = new UUID(0L, 0L); + private enum IntakeReadIntent { + COMMITTED_READ, + WRITABLE_OWNER_TRANSACTION + } + private static final Table OWNER = DSL.table(DSL.name("world_design_publication_fence_owner")); private static final Table ATTEMPT = DSL.table(DSL.name("world_design_publication_fence_attempt")); @@ -143,7 +148,8 @@ long localTenantKey() { @Transactional(propagation = Propagation.MANDATORY) OpenOwner lockOpenAndResolve(OwnerBinding binding) { requireWritableReadCommittedOwnerTransaction(); - ResolvedVersion resolvedVersion = resolveVersion(binding); + ResolvedVersion resolvedVersion = + resolveVersion(binding, IntakeReadIntent.WRITABLE_OWNER_TRANSACTION); Record owner = createAndLockOwner(resolvedVersion); requireMatchingOwnerBinding(owner, resolvedVersion); if (!OPEN.equals(owner.get(OWNER_FREEZE_PHASE, String.class))) { @@ -169,7 +175,8 @@ public FrozenAttempt claimFreeze( requireWritableReadCommittedOwnerTransaction(); Objects.requireNonNull(checkpointSupplier, "checkpointSupplier"); OwnerBinding binding = evidence.ownerBinding(); - ResolvedVersion resolvedVersion = resolveVersion(binding); + ResolvedVersion resolvedVersion = + resolveVersion(binding, IntakeReadIntent.WRITABLE_OWNER_TRANSACTION); rejectLegacyAttempt(evidence, resolvedVersion.localVersionKey()); Record owner = createAndLockOwner(resolvedVersion); requireMatchingOwnerBinding(owner, resolvedVersion); @@ -231,7 +238,8 @@ public Optional readAttempt(WorldDesignPublicationFenceEvidence e if (TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException("World publication attempt read requires a committed read"); } - ResolvedVersion resolvedVersion = resolveVersion(evidence.ownerBinding()); + ResolvedVersion resolvedVersion = + resolveVersion(evidence.ownerBinding(), IntakeReadIntent.COMMITTED_READ); rejectLegacyAttempt(evidence, resolvedVersion.localVersionKey()); FrozenAttempt stored = findAttemptByRequest(evidence, resolvedVersion.localVersionKey()); if (stored == null) { @@ -260,15 +268,22 @@ public Optional readAttemptByFence(UUID publicationFence) { return Optional.ofNullable(stored); } - private ResolvedVersion resolveVersion(OwnerBinding binding) { + private ResolvedVersion resolveVersion(OwnerBinding binding, IntakeReadIntent readIntent) { Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(readIntent, "readIntent"); + Optional intake = + switch (readIntent) { + case COMMITTED_READ -> + intakeRepository.read(binding.targetNamespace(), binding.intakeRequestId()); + case WRITABLE_OWNER_TRANSACTION -> + intakeRepository.readInOwnerPublicationTransaction( + binding.targetNamespace(), binding.intakeRequestId()); + }; WorldAuthoredSourceIntakeReceipt receipt = - intakeRepository - .read(binding.targetNamespace(), binding.intakeRequestId()) - .orElseThrow( - () -> - new MissingIntakeException( - "World publication fence requires an already committed authored-source intake")); + intake.orElseThrow( + () -> + new MissingIntakeException( + "World publication fence requires an already committed authored-source intake")); requireExactIntake(binding, receipt); Record identity = diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index 7319452b2a..0a247441f9 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -2243,7 +2243,12 @@ private static AuthoredWorldReleaseAttestationEvidence attestation( participant("GAME_LOGIC", 1, "c", true, descriptor.versionId(), commit), participant("AUTOMATION_SCRIPTING", 5, "d", false, descriptor.versionId(), commit), participant( - "GAME_DESIGN_CONTROL_PLANE", 1, "e", false, descriptor.versionId(), commit)); + "GAME_DESIGN_CONTROL_PLANE", + selector == null ? 1 : 2, + "e", + false, + descriptor.versionId(), + commit)); if (selector == null) { return AuthoredWorldReleaseAttestationEvidence.create( NAMESPACE, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 3afd20d89c..ca0562ca0d 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -5300,6 +5300,103 @@ private PrepareCanonicalWorldInstanceResponse invokePreparationAsGameSession( return response.value; } + @Test + void publicationOwnerReadsIntakeOnlyInsideWritableReadCommittedTransaction() { + Fixture f = fixture(); + WorldAuthoredSourceIntakeRepository intakeReader = new WorldAuthoredSourceIntakeRepository(dsl); + OwnerBinding owner = f.owner(); + WorldDesignPublicationFenceEvidence freezeEvidence = + new WorldDesignPublicationFenceEvidence( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), + owner.sourceOperationId(), + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest(), + "transaction-dispatch-" + UUID.randomUUID(), + "a".repeat(64), + 1, + "publish:" + owner.canonicalTenantId() + ":transaction-dispatch"); + + assertThatThrownBy( + () -> + intakeReader.readInOwnerPublicationTransaction( + NAMESPACE, f.intake().intakeRequestId())) + .hasMessageContaining("writable READ COMMITTED owner transaction"); + + TransactionTemplate readOnlyOwner = new TransactionTemplate(manager); + readOnlyOwner.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readOnlyOwner.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readOnlyOwner.setReadOnly(true); + assertThatThrownBy( + () -> + readOnlyOwner.execute( + status -> + intakeReader.readInOwnerPublicationTransaction( + NAMESPACE, f.intake().intakeRequestId()))) + .hasMessageContaining("writable READ COMMITTED owner transaction"); + + TransactionTemplate repeatableReadOwner = new TransactionTemplate(manager); + repeatableReadOwner.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + repeatableReadOwner.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + repeatableReadOwner.execute( + status -> + intakeReader.readInOwnerPublicationTransaction( + NAMESPACE, f.intake().intakeRequestId()))) + .hasMessageContaining("writable READ COMMITTED owner transaction"); + + Boolean ownerResolutionSucceeded = + ownerTransaction() + .execute( + status -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_READ_COMMITTED); + Record physicalTransaction = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + assertThat(physicalTransaction.get("isolation", String.class)) + .isEqualTo("read committed"); + assertThat(physicalTransaction.get("read_only", String.class)).isEqualTo("off"); + + assertThat( + intakeReader.readInOwnerPublicationTransaction( + NAMESPACE, f.intake().intakeRequestId())) + .contains(f.intake()); + assertThatThrownBy( + () -> intakeReader.read(NAMESPACE, f.intake().intakeRequestId())) + .hasMessageContaining("committed-outcome owner read"); + assertThat(fence.lockOpenAndResolve(owner).receipt()).isEqualTo(f.intake()); + return true; + }); + assertThat(ownerResolutionSucceeded).isTrue(); + + var frozen = + ownerTransaction() + .execute( + status -> + fence.claimFreeze( + freezeEvidence, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "transaction-dispatch-commit", "b".repeat(64), 2))); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(fence.readAttempt(freezeEvidence)).contains(frozen); + } + @Test void publishedSelectorJoinsExactFrozenCheckpointToOriginalAppliedWithoutWrites() { Fixture f = fixture(); From c9bf6778fe21c39045af5e6bacde850272cc2d78 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:13:09 +1300 Subject: [PATCH 051/129] Build owner-proved template phase, selected export and StartSession association read --- .../game-design-service/api-contracts.md | 2 +- .../game-design-service/asset-storage.md | 3 +- .../game-design-service/game-templates.md | 4 +- ...ame-authoring-publishing-and-activation.md | 8 +- ...session_template_association_service.proto | 78 ++ ...essionTemplateAssociationReadEvidence.java | 365 ++++++++ ...ssionTemplateAssociationReadGrpcCodec.java | 203 +++++ ...nTemplateAssociationReadGrpcCodecTest.java | 295 +++++++ .../DraftCommitCoordinatorRepository.java | 34 +- ...ionTemplateAssociationReadGrpcService.java | 91 ++ ...SessionTemplateAssociationReadService.java | 669 ++++++++++++++ .../TemplateConfigSourceRepository.java | 4 + .../TemplateReferenceRepository.java | 590 +++++++++++++ .../GameTenantCreationRepository.java | 5 +- .../service/AssetExportService.java | 30 + .../VersionAssetExportCandidateService.java | 97 ++ .../service/impl/AssetExportServiceImpl.java | 344 +++++++- ...ersionAssetExportCandidateServiceImpl.java | 503 +++++++++++ .../VersionPublishCommandServiceImpl.java | 41 +- ...d_template_references_and_tenant_phase.sql | 410 +++++++++ ...ected_inventory_asset_export_candidate.sql | 122 +++ ...teConfigSourcePostgresIntegrationTest.java | 38 + ...ReferencePhasePostgresIntegrationTest.java | 300 +++++++ ...emptServiceTransactionIntegrationTest.java | 455 +++++++++- ...xportCandidatePostgresIntegrationTest.java | 833 ++++++++++++++++++ ...emplateAssociationReadGrpcServiceTest.java | 122 +++ ...ionTemplateAssociationReadServiceTest.java | 294 +++++++ .../impl/SelectedAssetExportServiceTest.java | 295 +++++++ ...onAssetExportCandidateServiceImplTest.java | 87 ++ .../VersionPublishCommandServiceImplTest.java | 366 +++++++- ...aphApplicationPostgresIntegrationTest.java | 12 +- 31 files changed, 6650 insertions(+), 50 deletions(-) create mode 100644 protos/game-design/v1/start_session_template_association_service.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V64__normalized_template_references_and_tenant_phase.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V65__selected_inventory_asset_export_candidate.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/TemplateReferencePhasePostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 1f92a2d2b9..a51ee83d87 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -22,7 +22,7 @@ Game Design issues each new game row an opaque canonical tenant UUID and keeps e `TenantIdentityService.ResolveAuthoredWorldSource` is a separate read-only owner lookup for the exact retained Game Design source operation used by World Management's authored-world intake construction. Its closed request contains a canonical non-nil read correlation UUID, source operation UUID, canonical tenant UUID, and exact canonical `world_slug`; the receiver supplies the trusted namespace from its own configuration. The handler authenticates the exact same-namespace `world-management-service` TLS peer and rejects authenticated caller context before parsing the request or reading storage. Unknown fields, malformed or nil identifiers, noncanonical selectors, and missing or inconsistent source evidence fail closed. Success echoes the read correlation and returns the complete retained registration receipt, including its request and evidence digests, canonical tenant and slugs, display name, and source-row provenance. The owner recomputes both digests from the full tuple and checks the source against the persisted Game Design tenant row; a read does not allocate, repair, register, or activate source state. World must authenticate the Game Design server and validate the full response echo, selector, immutable fields, and recomputed digests before retaining that exact evidence. This read is not creator authentication, World registration, source-write authorization, launch permission, or runtime admission. -The distinct Game Session-facing template source read follows the [immutable template-to-World association contract](game-templates.md#immutable-template-to-world-source-association), not this World-only registration-source lookup. Its receiver must authenticate the exact same-namespace Game Session caller and independently verify the Account original-operation projection before returning the exact selected association. Retry checks preserve the original operation and selection, and missing association evidence denies without read-side population. The current source, association and consumer proof limits are tracked in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); this API consequence does not establish an enabled method or broaden the existing `TenantIdentityService` allowlist. +The distinct Game Session-facing `GameDesignStartSessionTemplateAssociationReadService.ReadStartSessionTemplateAssociation` follows the [immutable template-to-World association contract](game-templates.md#immutable-template-to-world-source-association), not this World-only registration-source lookup. Its schema-1 wire definition is [start_session_template_association_service.proto](../../../../protos/game-design/v1/start_session_template_association_service.proto). The receiver authenticates the exact same-namespace Game Session caller before decoding and independently verifies the Account original-operation projection before reading content. Its initial/replay modes and complete response correlations preserve the original operation and selection; missing association evidence denies without read-side population. The current source, association and consumer proof limits are tracked in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); this standalone unregistered handler does not establish an enabled method or broaden the existing `TenantIdentityService` allowlist. `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. diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index 8e2e4b6ae3..d7921e2f7c 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -6,6 +6,7 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b ## Implementation Status +- **Selected export construction:** The development assembly adds an exact selected-inventory candidate-before-write path and a separate SQL-only finalization check. It does not establish complete release-to-launch proof, public delivery, or shared-object purge safety. Executed checks and unresolved producer/consumer limits belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle). - **Current first slice:** The ordinary exporter requires V37's durable version-scoped snapshot and verifies its mappings and retained `game_assets.data` bytes before each export or retry. There is no tenant-wide fallback or process-local selection cache. The published construction includes an `ASSET_REFERENCE` source repository with coordinator/history/genesis/snapshot writing and export agreement; this is not a registered production authoring ingress or proof of complete template/config and branding coverage. Missing evidence denies export rather than proving an empty release. Frozen source bytes are database-protected, while unreferenced Draft uploads remain mutable. Version-prefix object writes, numeric public asset identifiers and post-write repair comparison remain drift from the target immutable-candidate lifecycle. See the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#published-asset-lifecycle) for capability and proof limits. - **Selected source coverage:** The construction branch includes the World owner's typed selected-release inventory, retained authenticated read and artifact-export checkpoint, which cover World-owned topology and derived-artifact requiredness only. Game Design's ordinary `ASSET_REFERENCE` source participates in actual fresh-Draft genesis, coordinator application, immutable commit snapshots and export-selection agreement. The separate `BRANDING_ASSET_REFERENCE` construction now joins the same source pipeline through fresh genesis, exact ordered revision history, synchronized snapshots and selected-operation capture. It is not total Game Design `COMPLETE`: external template owner reads, complete inventory composition and immutable export remain open. Ordinary assets remain `RESOURCE/REQUIRED`; branding has no implemented owner/consumer fallback policy, so no branding role is currently authoritatively `OPTIONAL`. The complete Game Design source/export gate remains closed until all families have exact selected-commit evidence. The unregistered admission construction retains the authenticated World read in its complete original publication operation; executed local codec proof, skipped PostgreSQL definitions and genuine composed producer/consumer limits remain separate in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). - **Current upload admission gap:** The target upload guardrails (25 MiB maximum file size, 2 GiB per-tenant draft quota, and streaming/chunked transfer) are requirements, not current proof. `AssetController` accepts multipart uploads and `GameAssetServiceImpl` calls `MultipartFile.getBytes()` without size or quota enforcement; `AssetStoreProperties` has no matching limits. Upload admission and resource-safety readiness therefore remain incomplete and the route must not be treated as ready for external enablement. @@ -20,7 +21,7 @@ Target runtime architecture uses an approved public `/assets/**` origin as the b - **Current failed-candidate abandonment gap:** The target durable abandonment proof record and owner-local abandonment operation/read are not implemented. The live tombstone path checks only artifact state and epoch, so it does not enforce the required abandonment, caller-tenant `FAILED` authority, or no-release-reachability proof; no current implementation or focused proof claim is made for this path. - **Current purge eligibility gap:** `CanDeleteVersionAssets` rejects a non-retired version when a tenant-matching version row exists, but its `findById(versionId).filter(tenant match)` lookup treats a row owned by another tenant as absent. When no caller-tenant release bundle remains, either no row or only a wrong-tenant row can therefore fall through to `deletable=true`; this is fail-open drift for dangling artifact rows. Target eligibility must require an existing caller-tenant version authority in `RETIRED` state and fail closed for both absence and tenant mismatch. - **Current release attestation:** The current `GetPublishedReleaseBundle` response and `published_release_bundle` row preserve `manifestHash` and narrower current attestation fields, but do not provide the complete target mandatory actual-byte `artifactDigests[]`; consumers must not synthesize absent target fields, and target-dependent admission remains unproved and blocked. -- **Current publish-failure gap:** `VersionPublishCommandServiceImpl` catches downstream exceptions after `published_release_bundle` may already have been written, then unconditionally calls `markFailed`, performs best-effort object cleanup, and deletes the version without an exact attestation readback/reconciliation branch. Because `published_release_bundle.version_id` is a non-cascading foreign key, that delete can itself fail after bundle commit; the current path therefore has neither a truthful `FAILED` result nor guaranteed reconciliation to `PUBLISHED`/nonterminal state. Target recovery must read back committed bundle state and never delete Version as compensation. This is implementation/proof drift against the transition rules below and must not be advertised as target terminality. +- **Publication reconciliation:** The current full-version command checks exact release readback before failure marking, retains the Version, and leaves partial or ambiguous finalization pending. Selected-export infrastructure uncertainty also remains pending rather than authorizing terminal failure. This does not establish the separate durable cleanup or shared-object reachability/purge workflow; those limits remain in the owning tracker. - **Current delivery gap:** `AssetExportServiceImpl` currently constructs generated manifest URLs from the private `ASSET_STORE_ENDPOINT` plus bucket/key, while `AssetController` exposes only `POST /assets`. No client GET/download route, gateway rewrite, signed-fetch, or `ASSET_STORE_PUBLIC_BASE_URL` path is implemented; these generated URLs are private storage references and must not be exposed as usable client manifests. Canonical `/assets/**` delivery remains target-only pending a separate approved public origin/provisioner; the current Gateway has no `/assets/**` route and private MinIO is not public delivery. - **Identifier drift:** `game_assets.tenant_id` accepts a REST `tenantId` string without UUID-shape enforcement while Account Service still exposes numeric `Long` tenant identifiers. No authoritative numeric-to-UUID mapping exists, and the public asset row key is a `BIGSERIAL`; none of these numeric values is a canonical logical identity. - **Target convergence:** Account and downstream contracts migrate together to the opaque UUID tenant identity, and the public asset contract and `GameAssetDto.id` converge directly on an opaque UUID logical asset identifier while any numeric database key remains private. The numeric public field is removed rather than retained through compatibility translation; implementations must not invent a reversible numeric-to-UUID encoding. Draft bytes may move out of PostgreSQL only after an equivalent immutable repair source exists. diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 37aa7308cd..1a994ef7fb 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -17,7 +17,7 @@ creators can quickly spin up new projects without starting from scratch. - The launch plugin-selection presence modes remain target-only and unimplemented: a presence-capable selection wrapper/mode, fresh omission or explicit empty resolving to the same immutable empty selection, rollback omission reusing a named target, rollback explicit empty, and explicit non-empty selection are not yet represented in proto/generated clients, launch-descriptor persistence/response, the request digest, service logic, or focused proof. Launch-resolution APIs are live, but the current implementation does not yet persist, expose, or prove the complete `enabledPluginVersions[]` set for deterministic retry and rollback. The detailed target contract remains below. - Current script-patch resolution is not yet the target launch predicate: a full-version template/request can persist an arbitrary patch ID without proving a same-base `PUBLISHED` Game Design publication or Automation `READY` status. These are implementation gaps; the target validation and fail-before-instance-row rules remain below. - The target tenant-scoped `GetTemplateReferencePhase` cutover read is not implemented in the current proto or service. Current launch resolution checks only the per-template `templateReferencePhase` field (`ENFORCED`/`LEGACY`); it does not expose or consume the target durable tenant phase (`BACKFILLING`/`VALIDATED`/`ENFORCED`) required by launch and retirement tooling. -- The target `game_template_*_ref` projections and tenant-wide lifecycle/query authority remain unimplemented. The unregistered source writer's normalized base/gameplay references are local selected-commit evidence, not the tenant cutover marker, complete external-owner projections, or retirement/reference-query tooling; lifecycle consumers cannot treat them as that broader proof. +- The construction adds a current normalized single-base projection and fresh, creation-receipt-backed tenant phase with full-inventory validation. It does not establish complete external-owner projections, authenticated launch consumption, retained-tenant cutover, or retirement/reference-query tooling. Detailed implementation and executed-versus-unrun proof belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). - The unregistered selected-source construction adds closed config history, actual generated template-row provenance, normalized base/gameplay references and immutable snapshots. It is not total template or release completeness: nonempty World, Entity and Automation references remain denied without genuine exact owner readback, and publication still lacks the separate derived Game Logic receipt join. Newly qualified rows remain non-launchable; legacy opaque/unqualified config is not mapped or backfilled. See the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) for construction and proof limits. - REST `POST /templates` rejects a caller-supplied `id` before mapping or persistence. The repository save update path matches both `id` and `tenant_id`, leaves the tenant binding unchanged, and denies a tenant mismatch before tenant-qualified readback. Focused unit definitions cover create rejection and tenant-qualified update; production PostgreSQL proof remains open. This identity fix does not establish template configuration source completeness or the separate producer/readback gaps described above. - Current template-remap-set APIs persist tenant-scoped `DRAFT`/`APPROVED` sets and entries. When `ResolveLaunchDescriptor` receives a `sourceVersionId` that differs from the resolved target, it selects exactly one `APPROVED` set for the source/target pair and persists and returns that set's `remapSetId`; it does not collect or verify owning-domain attestations. The target attestation predicate remains below. @@ -221,6 +221,8 @@ Game Design owns the immutable association between the canonical tenant, its exi The immutable read is restricted to the exact same-namespace Game Session workload inside its unchanged Account-authorized `StartSession` operation. Before returning content, Game Design independently verifies Account's authenticated original-operation projection, including the original actor, workload, target and actual Game Session attempt/fence binding. A descriptor digest, forwarded JWT, source receipt or workload identity alone does not establish this read permission. Game Session binds the selected association, version and descriptor to its original `controlPlaneRequestId` before reuse. Exact retries preserve that selection and cannot silently choose a newer association, another commit or another release. Missing, ambiguous, substituted or mismatched scope/commit evidence denies; a read never repairs missing association rows or grants Game Design mutation, World application or runtime activation. The operator authority and read-applicability contract belongs to [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); source association does not replace release attestation or Game Session's launch ownership. +The closed schema-1 read request binds its correlation ID, complete canonical Account post-authorization execution tuple, and actual Game Session owner attempt and positive fence. Initial configured selection has no caller version override: Game Design selects through its exact normalized base reference and independently verifies the explicit tenant `ENFORCED` phase and retained publication. Exact replay instead names the originally pinned canonical version, selected commit, publication workflow and association digest; it does not reselect from current template configuration. Both modes require the original operation's independently verified current read authorization. The response echoes the complete request and returns the public association projection, complete original World source receipt and published release, original typed World published start-location evidence, and positive owner phase epoch from the same Game Design snapshot. Private source/capture bytes and numeric provenance selectors are not exposed. + The association producer, authenticated operation-bound read and Game Session pinning are distinct proof boundaries. Their current implementation and activation limits belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status), not to the presence of a template row or a structurally valid association object. Required deterministic failure vocabulary for the first implementation slice: 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 7edf4b17e7..864f332e13 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 @@ -110,15 +110,15 @@ Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, b Game Design now has a callable `GetCompleteLaunchBinding` handler and strict descriptor/release-attestation codec for the World Management read path. Its exact-method bearer-interceptor bypass is only transport dispatch: the handler still denies absent, wrong-service, or wrong-namespace TLS peers before parsing or owner reads. Corrected-state Common/Game Design checks, handler/auth-wiring and codec units, and the Game Design boot JAR pass locally; no genuine positive persisted release/attestation read, mounted-certificate transport proof, or launch activation is claimed. World Management owns exact binding persistence and preparation; Gameplay owns Game Session launch orchestration and its executable-front fixture. -The selected source construction now includes V62's immutable per-captured-template association to the original World source. Its admission producer reads the full authenticated World intake outside SQL, independently compares Game Design source and delivery evidence, and retains the relation with the selected publication reservation. Exact replay preserves the stored read correlation and association bytes; inherited template entries preserve their original revision provenance. The defined PostgreSQL cases cover substituted source denial, immutable readback and concurrent first reservation, but their corrected-head physical execution remains required. The shared Account redeemed-StartSession projection client and protocol are preserved from Gameplay commit `60daafc34`; importing them does not implement the separate Game Design receiver or Game Session's durable selection/descriptor pinning. Those remain open under the [template association owner contract](../../architecture/microservices/game-design-service/game-templates.md#immutable-template-to-world-source-association). +The selected source construction includes V62's immutable per-captured-template association to the original World source. Its admission producer reads the full authenticated World intake outside SQL, independently compares Game Design source and delivery evidence, and retains the relation with the selected publication reservation. Exact replay preserves the stored read correlation and association bytes; inherited template entries preserve their original revision provenance. Corrected source `2fb5253f9567660acfa73f35c15aa38071f84af3` physically executed the 135-case Game Design integration suite, including association substitution, readback and concurrency cases. The standalone schema-1 Game Session-facing read now composes the shared Account redeemed-StartSession projection client with one independent Game Design snapshot, explicit phase, normalized base, original terminal/capture, association and release. Its definition and receiver remain unregistered; positive authenticated Account transport, Game Session durable selection/descriptor pinning and corrected-head composed proof remain open under the [template association owner contract](../../architecture/microservices/game-design-service/game-templates.md#immutable-template-to-world-source-association). -The complete selected asset-inventory reader uses an independent read-only snapshot, exact retained publication/capture and Game Logic receipt, and actual tenant-qualified ordinary and branding bytes. Its explicit empty declarations come from genuine selected source history, never absence of evidence; unresolved World/Entity/Automation references deny completeness. Mock-based unit definitions cover present bytes, cross-family collisions, changed bytes, incomplete captures and substituted receipt selection. This reader is not the durable private candidate, object writer, final immutable manifest or authenticated end-to-end release proof; those integrations remain open under [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). +The complete selected asset-inventory reader uses an independent read-only snapshot, exact retained publication/capture and Game Logic receipt, and actual tenant-qualified ordinary and branding bytes. Its explicit empty declarations come from genuine selected source history, never absence of evidence; unresolved World/Entity/Automation references deny completeness. The V65 construction retains the exact immutable selected inventory and manifest candidate before conditional content-addressed object writes, verifies actual object bytes and metadata, and joins the same candidate inside the publication transaction before artifact/release writes. Uncertain write/readback stays pending; definitive selected failure retains candidate objects rather than invoking legacy prefix cleanup. Focused candidate, export and orchestration proofs still require corrected-head validation. Authenticated whole-release, delivery and purge/reachability proof remain open under [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#complete-selected-release-asset-inventory). The original GD+World construction now implements the World-local retained-identity resolver, a distinct closed application/recovery transport and a Game Design composer that retains both exact owner outcomes before synchronized visibility. These components remain unregistered. CI run [37905710499](https://github.com/benhook1013/FireMUD/actions/runs/37905710499) for published `be47226a97d2a945f767c8adf0c3a955834ed629` executed all 133 Game Design integration cases, including the three new genuine PostgreSQL/mTLS composition cases, with no skips: those three failed establishing committed World evidence. All 206 World integration cases passed. This is an owned composition defect, not successful two-owner proof; its correction requires executed follow-up proof. The synthetic checkout used parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded construction parent `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`, so the run does not establish that recorded parent's alignment. The Account job's separate WAL-coverage failure remains an admission gate, not a dependency of this source/release handoff. The subsequent [Validation run 37913210424](https://github.com/benhook1013/FireMUD/actions/runs/37913210424), source `183a243f6aacd41f391c10943ca18dc1b50dae7b`, executed Game Design 133, World 206 and Account 254 integration cases with zero skips and respectively nine, eleven and one failures. Credential-safe diagnostics established the genuine three-case source failure: World's publication fence used the committed-only intake read inside its writable owner transaction. The prepared repair keeps that public denial and selects a strict physical writable `READ_COMMITTED` accessor only for owner application/freeze; committed exact attempt reads retain their separate boundary. Six selected-release failures exposed V49's stale GD schema-1 guard; additive V63 converges selected schema-2 evidence without changing retained rows or other guard predicates. Eleven World failures require selected-schema fixture correction, not runtime guard relaxation. Account's separate WAL-coverage denial remains open. The artifact-bound synthetic checkout is `d9249b9350a0c8239a397309c718a10507c2dee1`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source head; the run title's older `1a8eefe` base token does not describe that actual first parent. Corrected-head physical execution, rather than prepared code or skipped local tests, is still required for the source handoff. -The corrected local composition fixture uses the real distinct World authored-Version association mTLS client and receiver, with independently checked durable owner readback, instead of its earlier test-only incoming-context handoff. It also reads the World intake by its retained ID and independently compares its complete public source receipt with the Game Design owner record. Consolidated gate R240 passed Common, Common Security, Account, Game Design and World checks, formatting, static analysis, coverage, Game Design/World boot-JAR construction, links and Markdown. Its validated unit reports contain 2,722 green cases (Common 414, Common Security 138, Account 1,109, Game Design 480, World 581), including unchanged reused outputs; the standard Game Design/World integration reports contain 336 skipped definitions without Docker. The separately packaged genuine three-case composition fixture requires explicit physical execution; the green local aggregate is not that proof. Selected publication now consumes the exact retained paired World/GD digests with explicit attestation-schema context and a fixed six-family GD content vector. Unexpected World application failures retain strict denial and emit bounded message-free class/frame diagnostics, not credential or SQL payloads. The underlying physical failure remains unresolved. Genuine corrected-state two-owner execution, complete multi-owner definitive-abort recovery and release composition remain open. The existing executed GD-only source proof does not prove this combined original. The normative coordinator and receiver contracts belong to [Game Design version control](../../architecture/microservices/game-design-service/version-control.md#design-time-synchronization) and [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md#original-authorized-draft-graph-application). +Corrected source `2fb5253f9567660acfa73f35c15aa38071f84af3` in [Validation run 37920594377](https://github.com/benhook1013/FireMUD/actions/runs/37920594377) executed all 135 Game Design integration cases with no failures or skips. All three genuine original GD+World source/APPLIED/terminal-settlement composition cases passed, including lost-acknowledgement recovery and retained unknown-outcome recovery. They use the real World authored-Version association mTLS client/receiver and exact durable source/intake readback; this is executed bounded two-owner source proof, not an enabled creator flow, complete release, launch or admission proof. The synthetic checkout was `fc43387ddc776076b67faf0fa202dea37a1382bc`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and that source, not the recorded construction parent `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`. World executed 207 integration cases with one malformed canonical-workflow fixture failure; its mechanical correction still needs executed follow-up proof. Account executed 254 integration cases with its separate confirmation-WAL failure. Complete multi-owner definitive-abort recovery, selected release composition, original-operation read transport and final activation/settlement remain open. The normative coordinator and receiver contracts belong to [Game Design version control](../../architecture/microservices/game-design-service/version-control.md#design-time-synchronization) and [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md#original-authorized-draft-graph-application). Official-hosted creator-content acceptance remains partial under [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). Account's individual-party and hosted-terms repositories now retain exact catalog, affirmative-acceptance and environment-binding operations; `AccountHostedTermsService` can resolve the external environment observation before SQL work and reread locked currentness in a caller-owned writable `READ_COMMITTED` transaction. The service and its trusted publication, environment and affirmative-action participants remain unregistered; current creator authentication and original multi-owner commit enforcement are not supplied by these storage APIs. `HostedTermsEnvironmentBindingPostgresIntegrationTest` exercises explicitly test-only authorities, not a real agreement or operative hosted service. Composed-head PostgreSQL execution, live authority provisioning, creator UI, transfer and organization workflows remain separate proof or implementation gaps. These foundations do not upgrade the broader capability ratings or authorize content writes. @@ -297,7 +297,7 @@ Game Design owns revision history, commits, version state, and publish orchestra - Asset lifecycle follow-through remains incomplete. The current implementation lacks the version-scoped asset mapping/authoring path and corresponding publication/export guard; purge and publication recovery also lack complete durable operation, CAS, and exact readback proof. The canonical lifecycle and operation contracts are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); this tracker records the status and proof gaps without repeating those normative details. - Closed config/reference production remains a separate gap from the committed World source checkpoint: World and Entity authored-template logical IDs use canonical UUID strings, but Game Design has no exact selected-commit reference writer/readback. Entity's current validator/read path covers only `ITEM`/`NPC` through a positive-decimal storage key, not the canonical UUID readback or owner proof that an `ITEM` is equippable; equipment-oriented input is that `ITEM` identity, while runtime equipment binding remains separate. Automation owns `SCRIPT`, event-binding, and `SCRIPT_PATCH`, using current exact script name/raw patch keys without a canonical base-UUID bridge; it has no `RULESET` family. Game Logic's exact owner-retained configuration/source receipt for the selected tenant/base/commit is not currently produced/read back, so it cannot be replaced by per-rule IDs, `latest`, or another participant digest. No non-authoritative settings member is registered; runtime flags remain launch-authoritative. These are producer/readback gaps, not evidence that any unavailable source family is empty. - Launch/activation follow-through includes broader cutover and retirement consumers, later runtime-state families, exact Entity target-template validation once version-scoped entity-template tables exist, and replacement of remaining placeholder runtime topology/state rows. -- Normalized-template cutover phase is target-only: no tenant-scoped `GetTemplateReferencePhase` RPC, durable phase authority, or `BACKFILLING`/`VALIDATED`/`ENFORCED` consumer contract exists in the current slice; live launch checks only the per-template `ENFORCED`/`LEGACY` field. The target API and fail-before-launch behavior remain unimplemented and unproved. +- V64's construction adds the exact current `game_template_version_ref` projection and durable fresh-tenant `BACKFILLING`/`VALIDATED`/`ENFORCED` phase. Genesis requires the completed `NEW_GAME_ROW` creation receipt, never retained-row inference. Source synchronization may promote a nonempty complete qualified inventory under the shared Game-row mutex; empty, unqualified, tombstoned or unsupported inventory cannot prove enforcement. The defined PostgreSQL cases and new authenticated association receiver still need corrected-head validation. The target tenant-scoped `GetTemplateReferencePhase` RPC and existing launch/retirement consumers remain unimplemented; the older live descriptor path still checks the per-template `ENFORCED`/`LEGACY` field. No positive launch or retained-tenant cutover proof is claimed. - StartSession still needs to validate same-base `PUBLISHED` patch identity and join Automation's tenant-scoped script-patch status, failing closed unless the pinned patch is runtime `READY`; current descriptor validation proves neither publication identity nor readiness. - World design authoring currently has the first typed revision-to-World handoff, including the transactional applied-revision ledger, idempotent replay, expected aggregate/scope epoch checks, and reference/scope validation for supported mutations. Broader editor callers and concrete mutation coverage, publish-reconciliation replay, and actual digest commit-token convergence remain outside the current seam. diff --git a/protos/game-design/v1/start_session_template_association_service.proto b/protos/game-design/v1/start_session_template_association_service.proto new file mode 100644 index 0000000000..ef90bce1d4 --- /dev/null +++ b/protos/game-design/v1/start_session_template_association_service.proto @@ -0,0 +1,78 @@ +syntax = "proto3"; + +package game_design.v1; + +import "game-design/v1/game_design_service.proto"; +import "world-management/v1/world_management_service.proto"; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Standalone read-only handoff. Authenticate the exact same-namespace Game Session +// peer before decoding, then independently verify the original redeemed Account +// operation before reading content. This does not authorize source mutation, +// descriptor mutation, World preparation, or admission. +service GameDesignStartSessionTemplateAssociationReadService { + rpc ReadStartSessionTemplateAssociation(ReadStartSessionTemplateAssociationRequest) + returns (ReadStartSessionTemplateAssociationResponse); +} + +message ReadStartSessionTemplateAssociationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical StartSessionPostAuthorizationExecutionTuple bytes. + // No JWT or opaque authorization reference is forwarded here. + bytes canonical_post_authorization_tuple = 4; + string owner_attempt_id = 5; + int64 owner_fence = 6; + // Initial selection has no caller-supplied version override. A retry checks the + // first immutable result already pinned by Game Session; it cannot reselect. + oneof selection { + StartSessionConfiguredTemplateSelection initial_configured = 7; + StartSessionExactTemplateAssociationSelection exact_replay = 8; + } +} + +message StartSessionConfiguredTemplateSelection {} + +message StartSessionExactTemplateAssociationSelection { + string canonical_version_id = 1; + string selected_commit_id = 2; + string publish_workflow_id = 3; + string association_digest = 4; +} + +message ReadStartSessionTemplateAssociationResponse { + // Echo the entire exact request. Missing, ambiguous, unavailable or conflicting + // owner evidence is a non-OK RPC, never a partial or repaired result. + ReadStartSessionTemplateAssociationRequest request = 1; + StartSessionTemplateWorldSourceAssociationEvidence association = 2; + gamedesign.v1.PublishedReleaseBundle release_bundle = 3; + // Canonical typed World selector evidence committed with the original release terminal. + // This is not a launch descriptor and is not reconstructed from the source-intake receipt. + bytes world_published_start_location_evidence = 4; + // Positive, same-owner-snapshot phase evidence; neither a runtime lifecycle + // epoch nor independent admission permission. + int64 reference_phase_epoch = 5; +} + +// Closed public projection of the immutable Game Design association. Private operation, +// capture, template snapshot, entry, and canonical-association bytes never cross this API. +message StartSessionTemplateWorldSourceAssociationEvidence { + string canonical_tenant_id = 1; + int64 template_id = 2; + string canonical_version_id = 3; + string selected_commit_id = 4; + string publish_workflow_id = 5; + string publication_selection_digest = 6; + string association_digest = 7; + string target_namespace = 8; + string intake_request_id = 9; + string world_operation_id = 10; + string source_operation_id = 11; + string world_slug = 12; + string source_evidence_digest = 13; + world_management.v1.ReadAuthoredWorldSourceIntakeByIdRequest world_read_request = 14; + world_management.v1.ReadAuthoredWorldSourceIntakeByIdResponse world_read_response = 15; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java new file mode 100644 index 0000000000..7658e47a9b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java @@ -0,0 +1,365 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Message; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; + +/** Closed, public evidence returned by the standalone StartSession template-association read. */ +public final class StartSessionTemplateAssociationReadEvidence { + public static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + private StartSessionTemplateAssociationReadEvidence() {} + + public sealed interface Selection permits InitialConfigured, ExactReplay {} + + /** Resolve only the owner-proved current configured reference, never a caller version. */ + public record InitialConfigured() implements Selection {} + + /** Reuse one exact selection already pinned by Game Session to the original control-plane ID. */ + public record ExactReplay( + UUID canonicalVersionId, + UUID selectedCommitId, + String publishWorkflowId, + String associationDigest) + implements Selection { + public ExactReplay { + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(selectedCommitId, "selectedCommitId"); + requireText(publishWorkflowId, "publishWorkflowId", 256); + requireDigest(associationDigest, "associationDigest"); + } + } + + /** Exact authenticated StartSession identity plus the actual Game Session owner attempt/fence. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + byte[] canonicalPostAuthorizationTuple, + UUID ownerAttemptId, + long ownerFence, + Selection selection) { + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported template association read schema version"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Game Session namespace is required"); + } + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(ownerAttemptId, "ownerAttemptId"); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + Objects.requireNonNull(selection, "selection"); + if (canonicalPostAuthorizationTuple == null + || canonicalPostAuthorizationTuple.length == 0 + || canonicalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException("Complete bounded StartSession tuple is required"); + } + canonicalPostAuthorizationTuple = canonicalPostAuthorizationTuple.clone(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(canonicalPostAuthorizationTuple); + if (!Arrays.equals(tuple.canonicalBytes(), canonicalPostAuthorizationTuple) + || !targetNamespace.equals( + tuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw new IllegalArgumentException( + "Exact canonical StartSession tuple and namespace are required"); + } + } + + @Override + public byte[] canonicalPostAuthorizationTuple() { + return canonicalPostAuthorizationTuple.clone(); + } + + public StartSessionPostAuthorizationExecutionTuple decodedTuple() { + return StartSessionPostAuthorizationExecutionTuple.decode(canonicalPostAuthorizationTuple); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && readRequestId.equals(that.readRequestId) + && Arrays.equals(canonicalPostAuthorizationTuple, that.canonicalPostAuthorizationTuple) + && ownerAttemptId.equals(that.ownerAttemptId) + && ownerFence == that.ownerFence + && selection.equals(that.selection); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + schemaVersion, + targetNamespace, + readRequestId, + ownerAttemptId, + ownerFence, + selection) + + Arrays.hashCode(canonicalPostAuthorizationTuple); + } + } + + /** Public projection only; the persisted canonical association bytes are deliberately private. */ + public record Association( + UUID canonicalTenantId, + long templateId, + UUID canonicalVersionId, + UUID selectedCommitId, + String publishWorkflowId, + String publicationSelectionDigest, + String associationDigest, + String targetNamespace, + UUID intakeRequestId, + UUID worldOperationId, + UUID sourceOperationId, + String worldSlug, + String sourceEvidenceDigest, + ByIdReadRequest worldReadRequest, + PublicReceipt worldReceipt) { + public Association { + requireNonNil(canonicalTenantId, "canonicalTenantId"); + if (templateId <= 0L) throw new IllegalArgumentException("templateId must be positive"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(selectedCommitId, "selectedCommitId"); + requireText(publishWorkflowId, "publishWorkflowId", 256); + requireDigest(publicationSelectionDigest, "publicationSelectionDigest"); + requireDigest(associationDigest, "associationDigest"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical target namespace is required"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(worldOperationId, "worldOperationId"); + requireNonNil(sourceOperationId, "sourceOperationId"); + requireText(worldSlug, "worldSlug", 128); + requireDigest(sourceEvidenceDigest, "sourceEvidenceDigest"); + Objects.requireNonNull(worldReadRequest, "worldReadRequest"); + Objects.requireNonNull(worldReceipt, "worldReceipt"); + if (worldReadRequest.schemaVersion() != SCHEMA_VERSION + || !targetNamespace.equals(worldReadRequest.targetNamespace()) + || !canonicalTenantId.equals(worldReadRequest.canonicalTenantId()) + || !intakeRequestId.equals(worldReadRequest.intakeRequestId()) + || !targetNamespace.equals(worldReceipt.targetNamespace()) + || !canonicalTenantId.equals(worldReceipt.canonicalTenantId()) + || !intakeRequestId.equals(worldReceipt.intakeRequestId()) + || !worldOperationId.equals(worldReceipt.operationId()) + || !sourceOperationId.equals(worldReceipt.sourceOperationId()) + || !worldSlug.equals(worldReceipt.worldSlug()) + || !sourceEvidenceDigest.equals(worldReceipt.sourceEvidenceDigest())) { + throw new IllegalArgumentException( + "Public World intake receipt differs from the exact stored association"); + } + // Re-encode through the established owner codec to ensure its complete public receipt stays + // closed and satisfies the original by-ID request correlation. + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse(worldReadRequest, worldReceipt); + } + + public static Association fromStoredProjection( + UUID canonicalTenantId, + long templateId, + UUID canonicalVersionId, + UUID selectedCommitId, + String publishWorkflowId, + String publicationSelectionDigest, + String associationDigest, + String targetNamespace, + UUID intakeRequestId, + UUID worldOperationId, + UUID sourceOperationId, + String worldSlug, + String sourceEvidenceDigest, + ReadAuthoredWorldSourceIntakeByIdRequest worldReadRequest, + ReadAuthoredWorldSourceIntakeByIdResponse worldReadResponse) { + ByIdReadRequest typedRequest = + WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdRequest(worldReadRequest); + PublicReceipt typedReceipt = + WorldAuthoredSourceIntakeGrpcCodec.fromReadByIdResponse(typedRequest, worldReadResponse); + return new Association( + canonicalTenantId, + templateId, + canonicalVersionId, + selectedCommitId, + publishWorkflowId, + publicationSelectionDigest, + associationDigest, + targetNamespace, + intakeRequestId, + worldOperationId, + sourceOperationId, + worldSlug, + sourceEvidenceDigest, + typedRequest, + typedReceipt); + } + } + + public record Result( + Request request, + Association association, + PublishedReleaseBundle releaseBundle, + WorldPublishedStartLocationEvidence worldPublishedStartLocationEvidence, + long phaseEpoch) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Generated protobuf release bundles are immutable value messages.") + public Result { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(association, "association"); + Objects.requireNonNull(releaseBundle, "releaseBundle"); + Objects.requireNonNull( + worldPublishedStartLocationEvidence, "worldPublishedStartLocationEvidence"); + if (phaseEpoch <= 0L) throw new IllegalArgumentException("Positive phase epoch is required"); + StartSessionPostAuthorizationExecutionTuple tuple = request.decodedTuple(); + var action = tuple.preAuthorizationTuple().action(); + if (!request.targetNamespace().equals(association.targetNamespace()) + || !action.scope().tenantId().equals(association.canonicalTenantId()) + || action.target().gameTemplateId() != association.templateId() + || !association + .canonicalTenantId() + .toString() + .equals(releaseBundle.getCanonicalTenantId()) + || !association + .canonicalVersionId() + .toString() + .equals(releaseBundle.getCanonicalVersionId()) + || !association.publishWorkflowId().equals(releaseBundle.getPublishWorkflowId())) { + throw new IllegalArgumentException( + "Association and release differ from the exact authorized StartSession target"); + } + var worldSelector = worldPublishedStartLocationEvidence.request(); + if (!request.targetNamespace().equals(worldSelector.targetNamespace()) + || !association.canonicalTenantId().equals(worldSelector.canonicalTenantId()) + || !association.canonicalVersionId().equals(worldSelector.canonicalVersionId()) + || !association.publishWorkflowId().equals(worldSelector.publishWorkflowId()) + || !association.selectedCommitId().toString().equals(worldSelector.appliedCommitId())) { + throw new IllegalArgumentException( + "World published selector differs from exact association and release identity"); + } + requireNoUnknownFields(releaseBundle, "PublishedReleaseBundle"); + requireCompleteRelease(releaseBundle, worldPublishedStartLocationEvidence); + if (request.selection() instanceof ExactReplay replay + && (!replay.canonicalVersionId().equals(association.canonicalVersionId()) + || !replay.selectedCommitId().equals(association.selectedCommitId()) + || !replay.publishWorkflowId().equals(association.publishWorkflowId()) + || !replay.associationDigest().equals(association.associationDigest()))) { + throw new IllegalArgumentException( + "Exact replay differs from the originally pinned result"); + } + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Generated protobuf release bundles are immutable value messages.") + public PublishedReleaseBundle releaseBundle() { + return releaseBundle; + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) throw new IllegalArgumentException(field + " must be non-nil"); + } + + private static void requireText(String value, String field, int maxLength) { + Objects.requireNonNull(value, field); + if (value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(field + " must be nonblank and bounded"); + } + } + + private static void requireDigest(String value, String field) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(field + " must be a canonical SHA-256 digest"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : + message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() + != com.google.protobuf.Descriptors.FieldDescriptor.JavaType.MESSAGE) continue; + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } + + private static void requireCompleteRelease( + PublishedReleaseBundle bundle, WorldPublishedStartLocationEvidence worldEvidence) { + if (bundle.getId() <= 0L + || bundle.getVersionId() <= 0L + || bundle.getVersionNumber() <= 0 + || !bundle.hasManifestSchemaVersion()) { + throw new IllegalArgumentException("Complete selector-bearing published release is required"); + } + List artifacts = + bundle.getArtifactDigestsList().stream() + .map( + value -> + new AuthoredWorldReleaseAttestationEvidence.Artifact( + value.getUsageKey(), + value.getArtifactKind(), + value.getImmutableObjectKey(), + value.getContentDigest(), + value.getContentType(), + value.getArtifactSchemaVersion())) + .toList(); + List participants = + bundle.getParticipantDigestsList().stream() + .map( + value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.getParticipantKey(), + value.getScopeValue(), + null, + value.getAppliedCommitId(), + value.getContentDigest(), + value.getDigestSchemaVersion(), + value.hasAbilitySchemaDigest() ? value.getAbilitySchemaDigest() : null, + null, + null)) + .toList(); + new GameDesignPublicationTerminalEvidence.ReleaseContent( + UUID.fromString(bundle.getCanonicalTenantId()), + UUID.fromString(bundle.getCanonicalVersionId()), + bundle.getPublishedReleaseBundleRef(), + bundle.getVersionNumber(), + bundle.getAttestationSchemaVersion(), + bundle.getPublishWorkflowId(), + bundle.getManifestHash(), + bundle.getManifestSchemaVersion(), + artifacts, + bundle.getRequiredManifestAssetKeysList(), + participants, + bundle.getCommandDefinitionsList(), + bundle.getGenerationConfigRevision(), + worldEvidence); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodec.java new file mode 100644 index 0000000000..f7a5255a4a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodec.java @@ -0,0 +1,203 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse; +import net.firedevops.firemud.gamedesign.v1.StartSessionExactTemplateAssociationSelection; +import net.firedevops.firemud.gamedesign.v1.StartSessionTemplateWorldSourceAssociationEvidence; + +/** Closed public request/response mapping for the authenticated StartSession owner read. */ +public final class StartSessionTemplateAssociationReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private StartSessionTemplateAssociationReadGrpcCodec() {} + + public static ReadStartSessionTemplateAssociationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var builder = + ReadStartSessionTemplateAssociationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalPostAuthorizationTuple( + ByteString.copyFrom(request.canonicalPostAuthorizationTuple())) + .setOwnerAttemptId(request.ownerAttemptId().toString()) + .setOwnerFence(request.ownerFence()); + if (request.selection() instanceof InitialConfigured) { + builder.setInitialConfigured( + net.firedevops.firemud.gamedesign.v1.StartSessionConfiguredTemplateSelection + .getDefaultInstance()); + } else if (request.selection() instanceof ExactReplay replay) { + builder.setExactReplay( + StartSessionExactTemplateAssociationSelection.newBuilder() + .setCanonicalVersionId(replay.canonicalVersionId().toString()) + .setSelectedCommitId(replay.selectedCommitId().toString()) + .setPublishWorkflowId(replay.publishWorkflowId()) + .setAssociationDigest(replay.associationDigest())); + } else { + throw new IllegalArgumentException("Unsupported template association selection mode"); + } + return builder.build(); + } + + /** Decode only after the receiver authenticated its exact same-namespace Game Session peer. */ + public static Request fromRequest(ReadStartSessionTemplateAssociationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadStartSessionTemplateAssociationRequest"); + try { + var selection = + switch (request.getSelectionCase()) { + case INITIAL_CONFIGURED -> new InitialConfigured(); + case EXACT_REPLAY -> + new ExactReplay( + parseCanonicalUuid( + request.getExactReplay().getCanonicalVersionId(), "canonicalVersionId"), + parseCanonicalUuid( + request.getExactReplay().getSelectedCommitId(), "selectedCommitId"), + request.getExactReplay().getPublishWorkflowId(), + request.getExactReplay().getAssociationDigest()); + case SELECTION_NOT_SET -> + throw new IllegalArgumentException( + "Explicit initial or exact replay mode required"); + }; + return new Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + parseCanonicalUuid(request.getReadRequestId(), "readRequestId"), + request.getCanonicalPostAuthorizationTuple().toByteArray(), + parseCanonicalUuid(request.getOwnerAttemptId(), "ownerAttemptId"), + request.getOwnerFence(), + selection); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Canonical StartSession template association request required", invalid); + } + } + + public static ReadStartSessionTemplateAssociationResponse toResponse(Result result) { + Objects.requireNonNull(result, "result"); + Association association = result.association(); + var worldRequest = + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdRequest(association.worldReadRequest()); + var worldResponse = + WorldAuthoredSourceIntakeGrpcCodec.toReadByIdResponse( + association.worldReadRequest(), association.worldReceipt()); + var associationMessage = + StartSessionTemplateWorldSourceAssociationEvidence.newBuilder() + .setCanonicalTenantId(association.canonicalTenantId().toString()) + .setTemplateId(association.templateId()) + .setCanonicalVersionId(association.canonicalVersionId().toString()) + .setSelectedCommitId(association.selectedCommitId().toString()) + .setPublishWorkflowId(association.publishWorkflowId()) + .setPublicationSelectionDigest(association.publicationSelectionDigest()) + .setAssociationDigest(association.associationDigest()) + .setTargetNamespace(association.targetNamespace()) + .setIntakeRequestId(association.intakeRequestId().toString()) + .setWorldOperationId(association.worldOperationId().toString()) + .setSourceOperationId(association.sourceOperationId().toString()) + .setWorldSlug(association.worldSlug()) + .setSourceEvidenceDigest(association.sourceEvidenceDigest()) + .setWorldReadRequest(worldRequest) + .setWorldReadResponse(worldResponse); + return ReadStartSessionTemplateAssociationResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setAssociation(associationMessage) + .setReleaseBundle(result.releaseBundle()) + .setWorldPublishedStartLocationEvidence( + ByteString.copyFrom(result.worldPublishedStartLocationEvidence().canonicalBytes())) + .setReferencePhaseEpoch(result.phaseEpoch()) + .build(); + } + + /** Validates the full exact request echo and every public release/source correlation. */ + public static Result fromResponse( + Request expectedRequest, ReadStartSessionTemplateAssociationResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadStartSessionTemplateAssociationResponse"); + if (!response.hasRequest() || !response.hasAssociation() || !response.hasReleaseBundle()) { + throw new IllegalArgumentException( + "Complete exact template association read response required"); + } + Request echoed = fromRequest(response.getRequest()); + if (!expectedRequest.equals(echoed)) { + throw new IllegalArgumentException("Game Design changed the exact read request echo"); + } + var wireAssociation = response.getAssociation(); + if (!wireAssociation.hasWorldReadRequest() || !wireAssociation.hasWorldReadResponse()) { + throw new IllegalArgumentException("Complete public World source receipt is required"); + } + Association association = + Association.fromStoredProjection( + parseCanonicalUuid(wireAssociation.getCanonicalTenantId(), "canonicalTenantId"), + wireAssociation.getTemplateId(), + parseCanonicalUuid(wireAssociation.getCanonicalVersionId(), "canonicalVersionId"), + parseCanonicalUuid(wireAssociation.getSelectedCommitId(), "selectedCommitId"), + wireAssociation.getPublishWorkflowId(), + wireAssociation.getPublicationSelectionDigest(), + wireAssociation.getAssociationDigest(), + wireAssociation.getTargetNamespace(), + parseCanonicalUuid(wireAssociation.getIntakeRequestId(), "intakeRequestId"), + parseCanonicalUuid(wireAssociation.getWorldOperationId(), "worldOperationId"), + parseCanonicalUuid(wireAssociation.getSourceOperationId(), "sourceOperationId"), + wireAssociation.getWorldSlug(), + wireAssociation.getSourceEvidenceDigest(), + wireAssociation.getWorldReadRequest(), + wireAssociation.getWorldReadResponse()); + WorldPublishedStartLocationEvidence worldEvidence = + WorldPublishedStartLocationEvidence.fromStored( + response.getWorldPublishedStartLocationEvidence().toByteArray()); + try { + return new Result( + expectedRequest, + association, + response.getReleaseBundle(), + worldEvidence, + response.getReferencePhaseEpoch()); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Game Design returned conflicting association, release, or phase evidence", invalid); + } + } + + private static UUID parseCanonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, field)); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) continue; + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java new file mode 100644 index 0000000000..acb7bce812 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java @@ -0,0 +1,295 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionTemplateAssociationReadGrpcCodecTest { + private static final int EXPECTED_TUPLE_BYTES = 4176; + private static final String EXPECTED_TUPLE_SHA256 = + "891de4fb1ae82664ffbe9837db71c19bbbe28e7db759836ddca0d4a2f7002807"; + private static final int EXPECTED_INITIAL_WIRE_BYTES = 4276; + private static final String EXPECTED_INITIAL_WIRE_SHA256 = + "593394efa9b972fce74beefbf23cd3ba3791f3b57fe4b86426f1dc3c2dcf71ab"; + private static final int EXPECTED_REPLAY_WIRE_BYTES = 4455; + private static final String EXPECTED_REPLAY_WIRE_SHA256 = + "38cfef3dc73b485e19618580e88ee545ac26f1857a91940cebd9cd5740d4add0"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID VERSION = uuid("03333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = uuid("04444444-4444-4444-8444-444444444444"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void initialAndExactReplayHaveClosedDeterministicRequestVectors() { + var initial = request(new InitialConfigured()); + var initialWire = StartSessionTemplateAssociationReadGrpcCodec.toRequest(initial); + assertThat(initial.canonicalPostAuthorizationTuple()).hasSize(EXPECTED_TUPLE_BYTES); + assertThat(sha256(initial.canonicalPostAuthorizationTuple())).isEqualTo(EXPECTED_TUPLE_SHA256); + assertThat(initialWire.toByteArray()).hasSize(EXPECTED_INITIAL_WIRE_BYTES); + assertThat(sha256(initialWire.toByteArray())).isEqualTo(EXPECTED_INITIAL_WIRE_SHA256); + assertThat(initialWire.getSelectionCase()) + .isEqualTo(ReadStartSessionTemplateAssociationRequest.SelectionCase.INITIAL_CONFIGURED); + assertThat(StartSessionTemplateAssociationReadGrpcCodec.fromRequest(initialWire)) + .isEqualTo(initial); + assertThat(StartSessionTemplateAssociationReadGrpcCodec.toRequest(initial).toByteArray()) + .containsExactly(initialWire.toByteArray()); + + var replay = + request(new ExactReplay(VERSION, COMMIT, "template-publish-workflow-1", digest('a'))); + var replayWire = StartSessionTemplateAssociationReadGrpcCodec.toRequest(replay); + assertThat(replayWire.toByteArray()).hasSize(EXPECTED_REPLAY_WIRE_BYTES); + assertThat(sha256(replayWire.toByteArray())).isEqualTo(EXPECTED_REPLAY_WIRE_SHA256); + assertThat(replayWire.getSelectionCase()) + .isEqualTo(ReadStartSessionTemplateAssociationRequest.SelectionCase.EXACT_REPLAY); + assertThat(StartSessionTemplateAssociationReadGrpcCodec.fromRequest(replayWire)) + .isEqualTo(replay); + assertThat(replayWire.getExactReplay().getCanonicalVersionId()).isEqualTo(VERSION.toString()); + assertThat(replayWire.getExactReplay().getSelectedCommitId()).isEqualTo(COMMIT.toString()); + assertThat(replayWire.getExactReplay().getAssociationDigest()).isEqualTo(digest('a')); + } + + @Test + void rejectsMissingSelectionUnknownFieldsNoncanonicalIdsAndChangedNamespace() { + var valid = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(request(new InitialConfigured())); + assertThatThrownBy( + () -> + StartSessionTemplateAssociationReadGrpcCodec.fromRequest( + valid.toBuilder().clearSelection().build())) + .isInstanceOf(IllegalArgumentException.class); + + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy(() -> StartSessionTemplateAssociationReadGrpcCodec.fromRequest(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var uppercaseId = + valid.toBuilder() + .setReadRequestId(TENANT.toString().toUpperCase(java.util.Locale.ROOT)) + .build(); + assertThatThrownBy(() -> StartSessionTemplateAssociationReadGrpcCodec.fromRequest(uppercaseId)) + .isInstanceOf(IllegalArgumentException.class); + + var tuple = postTuple("codec-namespace"); + assertThatThrownBy( + () -> + StartSessionTemplateAssociationReadGrpcCodec.toRequest( + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + "another-runtime", + READ_ID, + tuple.canonicalBytes(), + ATTEMPT, + 8L, + new InitialConfigured()))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsReplaySelectorsWithoutCanonicalPinnedDigestOrIds() { + assertThatThrownBy(() -> new ExactReplay(VERSION, COMMIT, "workflow", "A" + "a".repeat(70))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ExactReplay(new UUID(0L, 0L), COMMIT, "workflow", digest('b'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ExactReplay(VERSION, COMMIT, "", digest('b'))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void preservesChangedAttemptFieldsAndRejectsOversizedOrUnknownNestedFields() { + var valid = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(request(new InitialConfigured())); + var changedFence = valid.toBuilder().setOwnerFence(valid.getOwnerFence() + 1L).build(); + assertThat(StartSessionTemplateAssociationReadGrpcCodec.fromRequest(changedFence).ownerFence()) + .isEqualTo(valid.getOwnerFence() + 1L); + assertThat(StartSessionTemplateAssociationReadGrpcCodec.fromRequest(changedFence)) + .isNotEqualTo(request(new InitialConfigured())); + + byte[] oversized = + new byte + [net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple + .MAX_CANONICAL_TUPLE_BYTES + + 1]; + assertThatThrownBy( + () -> + new StartSessionTemplateAssociationReadEvidence.Request( + 1, "world-runtime", READ_ID, oversized, ATTEMPT, 8L, new InitialConfigured())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bounded"); + + var replay = + StartSessionTemplateAssociationReadGrpcCodec.toRequest( + request(new ExactReplay(VERSION, COMMIT, "template-publish-workflow-1", digest('a')))); + var nestedUnknown = + replay.toBuilder() + .setExactReplay( + replay.getExactReplay().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(77, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> StartSessionTemplateAssociationReadGrpcCodec.fromRequest(nestedUnknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + private static StartSessionTemplateAssociationReadEvidence.Request request( + StartSessionTemplateAssociationReadEvidence.Selection selection) { + return new StartSessionTemplateAssociationReadEvidence.Request( + 1, + "world-runtime", + READ_ID, + postTuple("codec-request").canonicalBytes(), + ATTEMPT, + 8L, + selection); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple(String requestId) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + WORKLOAD, + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static String sha256(byte[] bytes) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + StringBuilder result = new StringBuilder(digest.length * 2); + for (byte value : digest) result.append(String.format("%02x", value)); + return result.toString(); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is required by the Java runtime", impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java index 2996747af9..27e2a0e3f0 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.TemplateReferenceRepository; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; @@ -384,7 +385,17 @@ public VisibilityFence advanceSourceVisibilityFence( throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_UNAVAILABLE"); } VisibilityFence fence = advanceVisibilityFence(binding, coordinatorProof); - sources.captureSynchronized(binding); + var synchronizedSources = sources.captureSynchronized(binding); + var references = new TemplateReferenceRepository(dsl); + // Only an explicitly enrolled fresh tenant can advance its cutover phase. Empty initial + // captures and retained tenants remain non-launchable, never inferred to be ENFORCED. + if (references.readPhase(binding.target().canonicalTenantId()).isPresent() + && synchronizedSources + .templateConfig() + .filter(value -> !value.entries().isEmpty()) + .isPresent()) { + references.validateAndEnforce(binding.target().canonicalTenantId()); + } return fence; } @@ -1248,6 +1259,23 @@ LockedVersion lockVersionTarget(UUID canonicalTenantId, UUID canonicalVersionId) requireWritableReadCommittedTransaction(); requireNonNil(canonicalTenantId, "canonicalTenantId"); requireNonNil(canonicalVersionId, "canonicalVersionId"); + Record game = + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id " + + "FROM game WHERE canonical_tenant_id = ? FOR UPDATE", + canonicalTenantId); + if (game == null + || game.get("id", Long.class) == null + || game.get("id", Long.class) <= 0 + || !canonicalTenantId.equals(game.get("canonical_tenant_id", UUID.class)) + || !game.get("id", Long.class) + .equals(game.get("tenant_identity_source_game_id", Long.class)) + || !game.get("tenant_id", String.class) + .equals(game.get("tenant_identity_source_legacy_tenant_id", String.class))) { + throw new DraftCommitNotFoundException( + "Exact canonical Game tenant and immutable source provenance were not found"); + } Record row = dsl.fetchOne( "SELECT v.id AS version_row_id, v.tenant_id AS version_tenant_key, " @@ -1263,12 +1291,14 @@ LockedVersion lockVersionTarget(UUID canonicalTenantId, UUID canonicalVersionId) + "AND g.tenant_identity_source_game_id = g.id " + "AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id " + "WHERE v.canonical_tenant_id = ? AND v.canonical_version_id = ? " + + "AND g.id = ? " + "AND v.identity_source_game_row_id > 0 " + "AND v.identity_source_game_tenant_key = v.tenant_id " + "AND v.identity_source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') " + "FOR UPDATE OF v", canonicalTenantId, - canonicalVersionId); + canonicalVersionId, + game.get("id", Long.class)); if (row == null) { throw new DraftCommitNotFoundException( "Exact canonical Version and immutable Game source provenance were not found"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcService.java new file mode 100644 index 0000000000..43b1487aba --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcService.java @@ -0,0 +1,91 @@ +package net.firedevops.firemud.gamedesign.draft; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; +import net.firedevops.firemud.gamedesign.v1.GameDesignStartSessionTemplateAssociationReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse; + +/** Standalone, deliberately unregistered authenticated Game Session association read endpoint. */ +public final class GameDesignStartSessionTemplateAssociationReadGrpcService + extends GameDesignStartSessionTemplateAssociationReadServiceGrpc + .GameDesignStartSessionTemplateAssociationReadServiceImplBase { + private final StartSessionTemplateAssociationReadService service; + private final String workloadNamespace; + + public GameDesignStartSessionTemplateAssociationReadGrpcService( + StartSessionTemplateAssociationReadService service, String workloadNamespace) { + this.service = Objects.requireNonNull(service, "service"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readStartSessionTemplateAssociation( + ReadStartSessionTemplateAssociationRequest request, + StreamObserver observer) { + try { + requirePeer(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final StartSessionTemplateAssociationReadEvidence.Request decoded; + try { + decoded = StartSessionTemplateAssociationReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical StartSession template association read required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("StartSession association namespace differs from peer") + .asRuntimeException()); + return; + } + + try { + observer.onNext( + StartSessionTemplateAssociationReadGrpcCodec.toResponse(service.read(decoded))); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError( + Status.fromCode(Status.fromThrowable(failure).getCode()) + .withDescription("Exact StartSession association read denied or unavailable") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Design template association owner read unavailable") + .asRuntimeException()); + } + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java new file mode 100644 index 0000000000..20d09e6140 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java @@ -0,0 +1,669 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadAuthoredWorldSourceIntakeByIdResponse; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Standalone, unregistered exact StartSession template-association read. It verifies Account's + * original redeemed operation before any local query and returns only immutable public evidence. + */ +public final class StartSessionTemplateAssociationReadService { + private final DSLContext dsl; + private final TemplateReferenceRepository templateReferences; + private final TemplateConfigSourceRepository templateSources; + private final VersionRepository versions; + private final GameDesignPublicationOperationRepository publicationOperations; + private final GameDesignSourceRepository sourceRepository; + private final SelectedDraftTemplateWorldSourceAssociationRepository associations; + private final PublishedReleaseBundleService releases; + private final TransactionTemplate snapshot; + private final String workloadNamespace; + private final AccountProjectionReader accountProjectionReader; + + /** + * Production construction always delegates to the explicit same-namespace Account mTLS client. + */ + public StartSessionTemplateAssociationReadService( + DSLContext dsl, + PlatformTransactionManager transactions, + String workloadNamespace, + StartSessionRedeemedOperationProjectionClient accountProjectionClient, + PublishedReleaseBundleService releases) { + this( + dsl, + transactions, + workloadNamespace, + Objects.requireNonNull(accountProjectionClient, "accountProjectionClient")::read, + releases); + } + + StartSessionTemplateAssociationReadService( + DSLContext dsl, + PlatformTransactionManager transactions, + String workloadNamespace, + AccountProjectionReader accountProjectionReader, + PublishedReleaseBundleService releases) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.templateReferences = new TemplateReferenceRepository(dsl); + this.templateSources = new TemplateConfigSourceRepository(dsl); + this.versions = new VersionRepository(dsl); + this.publicationOperations = new GameDesignPublicationOperationRepository(dsl); + this.sourceRepository = new GameDesignSourceRepository(dsl); + this.associations = new SelectedDraftTemplateWorldSourceAssociationRepository(dsl); + this.releases = Objects.requireNonNull(releases, "releases"); + this.accountProjectionReader = + Objects.requireNonNull(accountProjectionReader, "accountProjectionReader"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + snapshot = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + snapshot.setName("game-design-start-session-template-association-read"); + snapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + snapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + snapshot.setReadOnly(true); + } + + /** + * The typed request is untrusted. This checks the peer, independently verifies Account's exact + * operation/attempt projection, and only then opens a new local repeatable-read snapshot. + */ + public Result read(Request request) { + requirePeer(); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("StartSession association namespace differs from peer") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent StartSession association snapshot required") + .asRuntimeException(); + } + + final StartSessionPostAuthorizationExecutionTuple tuple; + try { + tuple = request.decodedTuple(); + requireAuthorizedTarget(request, tuple); + ReadRedeemedOperationProjectionResponse projection = + accountProjectionReader.read(tuple, request.ownerAttemptId(), request.ownerFence()); + requireAccountProjection(request, tuple, projection); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (RuntimeException unavailableOrInvalid) { + throw Status.UNAVAILABLE + .withDescription("Exact redeemed StartSession projection unavailable") + .withCause(unavailableOrInvalid) + .asRuntimeException(); + } + + try { + return Objects.requireNonNull( + snapshot.execute(ignored -> readSnapshot(request, tuple)), + "StartSession association snapshot returned no result"); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (DataAccessException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Game Design association owner storage unavailable") + .withCause(unavailable) + .asRuntimeException(); + } catch (RuntimeException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact StartSession template association is unavailable or conflicting") + .withCause(invalid) + .asRuntimeException(); + } + } + + private Result readSnapshot(Request request, StartSessionPostAuthorizationExecutionTuple tuple) { + var preTuple = tuple.preAuthorizationTuple(); + UUID canonicalTenantId = preTuple.action().scope().tenantId(); + long templateId = preTuple.action().target().gameTemplateId(); + + var phase = + templateReferences + .readPhase(canonicalTenantId) + .filter(value -> value.phase() == TemplateReferenceRepository.Phase.ENFORCED) + .filter(value -> value.phaseEpoch() > 0L) + .filter( + value -> + value.inventoryTemplateCount() != null && value.inventoryTemplateCount() > 0L) + .filter(value -> value.inventoryDigest() != null) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Explicit enforced template reference phase unavailable") + .asRuntimeException()); + + UUID canonicalVersionId; + UUID selectedCommitId = null; + TemplateReferenceRepository.BaseReference configuredReference = null; + TemplateConfigSource.Entry configuredEntry = null; + if (request.selection() instanceof InitialConfigured) { + configuredReference = + templateReferences + .readExactBaseReference(canonicalTenantId, templateId) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Current normalized template reference unavailable") + .asRuntimeException()); + canonicalVersionId = configuredReference.canonicalVersionId(); + if (!canonicalTenantId.equals(configuredReference.canonicalTenantId()) + || templateId != configuredReference.templateId()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INITIAL_SELECTOR_SCOPE_CONFLICT"); + } + } else if (request.selection() instanceof ExactReplay replay) { + canonicalVersionId = replay.canonicalVersionId(); + selectedCommitId = replay.selectedCommitId(); + } else { + throw Status.INVALID_ARGUMENT + .withDescription("Explicit initial or exact replay selection required") + .asRuntimeException(); + } + + Version version = + versions + .findByCanonicalTenantIdAndCanonicalVersionId(canonicalTenantId, canonicalVersionId) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact canonical published Version unavailable") + .asRuntimeException()); + requireLaunchableVersion(version, canonicalTenantId, canonicalVersionId, phase); + if (configuredReference != null) { + configuredEntry = + readCurrentConfiguredEntry( + configuredReference, targetProof(version), version, templateId); + } + StartSessionTemplateAssociationReadEvidence.ExactReplay replay = + request.selection() instanceof ExactReplay value ? value : null; + String workflowId = replay == null ? null : replay.publishWorkflowId(); + if (workflowId == null) { + // The canonical version has one exact immutable release row; its workflow ID, not a + // workflow-list/latest query, selects the original publication operation. + PublishedReleaseBundleDto configuredRelease = + releases + .findPublishedReleaseBundle(version.getTenantId(), version.getId()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact published release bundle unavailable") + .asRuntimeException()); + if (!canonicalTenantId.equals(configuredRelease.canonicalTenantId()) + || !canonicalVersionId.equals(configuredRelease.canonicalVersionId()) + || !"v2".equals(configuredRelease.attestationSchemaVersion())) { + throw new IllegalStateException("START_SESSION_CONFIGURED_RELEASE_IDENTITY_CONFLICT"); + } + workflowId = configuredRelease.publishWorkflowId(); + } + return readExactPublication( + request, + canonicalTenantId, + templateId, + canonicalVersionId, + selectedCommitId, + workflowId, + replay, + configuredEntry, + version, + phase.phaseEpoch()); + } + + private Result readExactPublication( + Request request, + UUID canonicalTenantId, + long templateId, + UUID canonicalVersionId, + UUID selectedCommitId, + String workflowId, + ExactReplay replay, + TemplateConfigSource.Entry configuredEntry, + Version version, + long phaseEpoch) { + GameDesignPublicationOperationRepository.Readback operationReadback = + publicationOperations + .read(workflowId) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact original publication operation unavailable") + .asRuntimeException()); + GameDesignPublicationOperation operation = operationReadback.operation(); + if (!"PUBLISHED".equals(operationReadback.outcome()) + || operationReadback.terminalEvidenceBytes() == null + || !workflowId.equals(operation.workflowId()) + || !version.getTenantId().equals(operation.tenantKey()) + || !Objects.equals(version.getId(), operation.versionId())) { + throw new IllegalStateException("START_SESSION_PUBLICATION_OPERATION_NOT_PUBLISHED"); + } + GameDesignPublicationOperation exactOperation = + publicationOperations.requireOutcome( + operation.tenantKey(), + workflowId, + operation.versionId(), + operation.selectionDigest(), + "PUBLISHED"); + if (!Arrays.equals(exactOperation.canonicalBytes(), operation.canonicalBytes())) { + throw new IllegalStateException("START_SESSION_PUBLICATION_SELECTION_CHANGED"); + } + + GameDesignPublicationTerminalEvidence terminal = + GameDesignPublicationTerminalEvidence.fromStored(operationReadback.terminalEvidenceBytes()); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operation.canonicalBytes()) + || terminal.releaseContent() == null + || terminal.publicationVersionStateEpoch() <= 0L) { + throw new IllegalStateException("START_SESSION_PUBLICATION_TERMINAL_CONFLICT"); + } + var selected = operation.account().input().selection(); + UUID actualSelectedCommitId = selected.selectedCommit().commitId(); + if (selectedCommitId != null && !selectedCommitId.equals(actualSelectedCommitId)) { + throw new IllegalStateException("START_SESSION_REPLAY_SELECTION_CONFLICT"); + } + selectedCommitId = actualSelectedCommitId; + if (!canonicalTenantId.equals(selected.target().canonicalTenantId()) + || !canonicalVersionId.equals(selected.target().canonicalVersionId()) + || !Objects.equals(version.getId(), selected.target().gameDesignVersionRowId()) + || !targetProof(version).equals(selected.target()) + || !selectedCommitId.equals(selected.selectedCommit().commitId()) + || !workflowId.equals(operation.world().request().publishWorkflowId()) + || !canonicalTenantId.equals(operation.world().request().canonicalTenantId()) + || !canonicalVersionId.equals(operation.world().request().canonicalVersionId()) + || !request.targetNamespace().equals(operation.world().request().targetNamespace())) { + throw new IllegalStateException("START_SESSION_OPERATION_COMMON_COMMIT_CONFLICT"); + } + + GameDesignSourceRepository.Capture capture = + sourceRepository + .readCapture(operation) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Complete original selected source capture unavailable") + .asRuntimeException()); + TemplateConfigSourceSnapshot.Capture templateCapture = capture.templateConfig(); + if (!templateCapture.snapshot().binding().equals(selected.selectedCommit())) { + throw new IllegalStateException("START_SESSION_CAPTURE_SOURCE_ENTRY_CONFLICT"); + } + List capturedTemplateEntries = + templateCapture.snapshot().entries().stream() + .filter(entry -> Long.parseLong(entry.templateId()) == templateId) + .toList(); + if (capturedTemplateEntries.size() != 1) { + throw new IllegalStateException("START_SESSION_CAPTURE_TEMPLATE_ENTRY_UNAVAILABLE"); + } + TemplateConfigSource.Entry selectedTemplateEntry = capturedTemplateEntries.getFirst(); + if (!selectedTemplateEntry.config().baseVersionId().equals(canonicalVersionId) + || replay == null + && (configuredEntry == null || !configuredEntry.equals(selectedTemplateEntry))) { + throw new IllegalStateException("START_SESSION_CAPTURE_SOURCE_ENTRY_CONFLICT"); + } + var retainedAssociations = associations.readExact(operation, templateCapture); + List templateAssociations = + retainedAssociations.stream().filter(value -> value.templateId() == templateId).toList(); + if (templateAssociations.size() != 1) { + throw new IllegalStateException("START_SESSION_TEMPLATE_ASSOCIATION_NOT_UNIQUE"); + } + var retained = templateAssociations.getFirst(); + if (!canonicalTenantId.equals(retained.canonicalTenantId()) + || !canonicalVersionId.equals(retained.canonicalVersionId()) + || !selectedCommitId.equals(retained.selectedCommitId()) + || !workflowId.equals(retained.publishWorkflowId()) + || !retained.targetNamespace().equals(request.targetNamespace())) { + throw new IllegalStateException("START_SESSION_TEMPLATE_ASSOCIATION_SELECTION_CONFLICT"); + } + + ReadAuthoredWorldSourceIntakeByIdRequest worldRequest; + ReadAuthoredWorldSourceIntakeByIdResponse worldResponse; + try { + worldRequest = + ReadAuthoredWorldSourceIntakeByIdRequest.parseFrom(retained.worldReadRequestBytes()); + worldResponse = + ReadAuthoredWorldSourceIntakeByIdResponse.parseFrom(retained.worldReadResponseBytes()); + } catch (IOException malformed) { + throw new IllegalStateException("START_SESSION_WORLD_SOURCE_RECEIPT_CORRUPT", malformed); + } + Association association = + Association.fromStoredProjection( + retained.canonicalTenantId(), + retained.templateId(), + retained.canonicalVersionId(), + retained.selectedCommitId(), + retained.publishWorkflowId(), + operation.selectionDigest(), + retained.digest(), + retained.targetNamespace(), + retained.intakeRequestId(), + retained.worldOperationId(), + retained.sourceOperationId(), + retained.worldSlug(), + retained.sourceEvidenceDigest(), + worldRequest, + worldResponse); + + if (replay != null + && (!replay.canonicalVersionId().equals(association.canonicalVersionId()) + || !replay.selectedCommitId().equals(association.selectedCommitId()) + || !replay.publishWorkflowId().equals(association.publishWorkflowId()) + || !replay.associationDigest().equals(association.associationDigest()))) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact retry differs from the first pinned association") + .asRuntimeException(); + } + + PublishedReleaseBundleDto release = + releases + .findPublishedReleaseBundle(version.getTenantId(), version.getId()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Exact published release bundle unavailable") + .asRuntimeException()); + if (!workflowId.equals(release.publishWorkflowId()) + || !canonicalTenantId.equals(release.canonicalTenantId()) + || !canonicalVersionId.equals(release.canonicalVersionId()) + || !release.worldPublishedStartLocationEvidence().equals(operation.world())) { + throw new IllegalStateException("START_SESSION_RELEASE_OWNER_EVIDENCE_CONFLICT"); + } + var releaseContent = releaseContent(release); + if (!Arrays.equals( + terminal.releaseContent().canonicalBytes(), releaseContent.canonicalBytes())) { + throw new IllegalStateException("START_SESSION_RELEASE_TERMINAL_CONTENT_CONFLICT"); + } + WorldPublishedStartLocationEvidence worldEvidence = + WorldPublishedStartLocationEvidence.fromStored( + terminal.releaseContent().worldStartLocationEvidence().canonicalBytes()); + return new Result( + request, association, toPublishedReleaseBundle(release), worldEvidence, phaseEpoch); + } + + private TemplateConfigSource.Entry readCurrentConfiguredEntry( + TemplateReferenceRepository.BaseReference ref, + DraftCommitBinding.TargetProof target, + Version version, + long templateId) { + if (ref == null + || !ref.canonicalTenantId().equals(version.getCanonicalTenantId()) + || !ref.canonicalVersionId().equals(version.getCanonicalVersionId()) + || ref.templateId() != templateId) { + throw new IllegalStateException("TEMPLATE_REFERENCE_ENTRY_PROJECTION_CONFLICT"); + } + Record head = + dsl.fetchOne( + "SELECT visible_commit_id FROM game_design_template_config_source_head " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + ref.canonicalTenantId(), + ref.canonicalVersionId()); + UUID visibleCommitId = head == null ? null : head.get("visible_commit_id", UUID.class); + if (visibleCommitId == null) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_HEAD_PROJECTION_CONFLICT"); + } + TemplateConfigSourceSnapshot currentSource = + templateSources + .readSnapshot(target, visibleCommitId) + .orElseThrow( + () -> new IllegalStateException("TEMPLATE_REFERENCE_CURRENT_SOURCE_UNAVAILABLE")); + List currentEntries = + currentSource.entries().stream() + .filter(entry -> Long.parseLong(entry.templateId()) == templateId) + .toList(); + if (!currentSource.binding().commitId().equals(visibleCommitId) || currentEntries.size() != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_CURRENT_SOURCE_CONFLICT"); + } + TemplateConfigSource.Entry currentEntry = currentEntries.getFirst(); + if (!currentEntry.sourceBinding().target().equals(target) + || !currentEntry.sourceBinding().commitId().equals(ref.sourceCommitId()) + || !currentEntry.revisionId().equals(ref.sourceRevisionId()) + || !currentEntry.config().baseVersionId().equals(ref.canonicalVersionId())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_ENTRY_PROJECTION_CONFLICT"); + } + var privateTemplate = + dsl.fetchOne( + "SELECT tenant_id, default_version_id, config::TEXT AS config_json " + + "FROM game_templates WHERE id = ?", + templateId); + if (privateTemplate == null + || !version.getTenantId().equals(privateTemplate.get("tenant_id", String.class)) + || !Objects.equals(version.getId(), privateTemplate.get("default_version_id", Long.class)) + || !currentEntry + .config() + .canonicalJson() + .equals( + new TemplateConfigSource.Config(privateTemplate.get("config_json", String.class)) + .canonicalJson())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_CURRENT_SOURCE_PROJECTION_CONFLICT"); + } + return currentEntry; + } + + private void requireLaunchableVersion( + Version version, + UUID canonicalTenantId, + UUID canonicalVersionId, + TemplateReferenceRepository.PhaseSnapshot phase) { + if (!Objects.equals(version.getCanonicalTenantId(), canonicalTenantId) + || !Objects.equals(version.getCanonicalVersionId(), canonicalVersionId) + || !(version.getVersionState() == VersionLifecycleState.PUBLISHED + || version.getVersionState() == VersionLifecycleState.ACTIVE) + || !"NEW_GAME_ROW".equals(phase.provenanceKind()) + || !Objects.equals(version.getIdentitySourceGameRowId(), phase.sourceGameRowId()) + || !Objects.equals(version.getIdentitySourceGameTenantKey(), phase.sourceGameTenantKey()) + || !Objects.equals(version.getIdentitySourceProvenanceKind(), phase.provenanceKind()) + || !Objects.equals(version.getTenantId(), phase.sourceGameTenantKey())) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact fresh published or active template Version unavailable") + .asRuntimeException(); + } + } + + private DraftCommitBinding.TargetProof targetProof(Version version) { + return new DraftCommitBinding.TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + } + + private void requireAuthorizedTarget( + Request request, StartSessionPostAuthorizationExecutionTuple tuple) { + var action = tuple.preAuthorizationTuple().action(); + if (!request.targetNamespace().equals(action.scope().targetNamespace()) + || !workloadNamespace.equals(action.scope().targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("StartSession target namespace differs from verified owner") + .asRuntimeException(); + } + } + + private void requireAccountProjection( + Request request, + StartSessionPostAuthorizationExecutionTuple tuple, + ReadRedeemedOperationProjectionResponse projection) { + byte[] canonicalPreTuple = + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8); + String expectedRedeemer = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + if (projection == null + || !tuple.controlPlaneRequestId().equals(projection.getControlPlaneRequestId()) + || !MessageDigest.isEqual( + canonicalPreTuple, projection.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + || !tuple.preAuthorizationTuple().mutationDigest().equals(projection.getMutationDigest()) + || !request.ownerAttemptId().toString().equals(projection.getOwnerAttemptId()) + || request.ownerFence() != projection.getOwnerFence() + || !expectedRedeemer.equals(projection.getAuthenticatedRedeemerWorkloadIdentity())) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Account projection differs from the exact original StartSession attempt") + .asRuntimeException(); + } + } + + private GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent( + PublishedReleaseBundleDto dto) { + if (dto.manifestSchemaVersion() == null || dto.artifactDigests() == null) { + throw new IllegalStateException("START_SESSION_IMMUTABLE_RELEASE_ARTIFACT_PROOF_MISSING"); + } + List participants = + dto.participantDigests().stream() + .map( + value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.participantKey(), + value.scopeValue(), + value.baseVersionId(), + value.appliedCommitId(), + value.contentDigest(), + Objects.requireNonNull(value.digestSchemaVersion()), + value.abilitySchemaDigest(), + value.errorCode(), + value.errorMessage())) + .toList(); + List + artifacts = + dto.artifactDigests().stream() + .map( + value -> + new net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence.Artifact( + value.usageKey(), + value.artifactKind(), + value.immutableObjectKey(), + value.contentDigest(), + value.contentType(), + value.artifactSchemaVersion())) + .toList(); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + dto.canonicalTenantId(), + dto.canonicalVersionId(), + dto.publishedReleaseBundleRef(), + dto.versionNumber(), + dto.attestationSchemaVersion(), + dto.publishWorkflowId(), + dto.manifestHash(), + dto.manifestSchemaVersion(), + artifacts, + dto.requiredManifestAssetKeys(), + participants, + dto.commandDefinitions(), + dto.generationConfigRevision(), + dto.worldPublishedStartLocationEvidence()); + } + + private net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle toPublishedReleaseBundle( + PublishedReleaseBundleDto dto) { + var builder = + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() + .setId(dto.id()) + .setVersionId(dto.versionId()) + .setVersionNumber(dto.versionNumber()) + .setAttestationSchemaVersion(dto.attestationSchemaVersion()) + .setPublishWorkflowId(dto.publishWorkflowId()) + .setManifestHash(dto.manifestHash()) + .addAllRequiredManifestAssetKeys(dto.requiredManifestAssetKeys()) + .setIsScriptOnly(dto.scriptOnly()) + .setScriptPatchVersion(Objects.requireNonNullElse(dto.scriptPatchVersion(), "")) + .setPublishedAt(dto.publishedAt().toString()) + .setGenerationConfigRevision(dto.generationConfigRevision()) + .addAllCommandDefinitions(dto.commandDefinitions()) + .setPublishedReleaseBundleRef(dto.publishedReleaseBundleRef()) + .setCanonicalTenantId(dto.canonicalTenantId().toString()) + .setCanonicalVersionId(dto.canonicalVersionId().toString()); + for (PublishParticipantDigestDto participant : dto.participantDigests()) { + if (!participant.succeeded()) { + throw new IllegalStateException("START_SESSION_PUBLISHED_PARTICIPANT_FAILURE"); + } + var value = + net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(Objects.requireNonNull(participant.appliedCommitId())) + .setContentDigest(Objects.requireNonNull(participant.contentDigest())) + .setDigestSchemaVersion(Objects.requireNonNull(participant.digestSchemaVersion())); + if (participant.abilitySchemaDigest() != null) { + value.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + } + builder.addParticipantDigests(value); + } + if (dto.manifestSchemaVersion() != null) { + builder.setManifestSchemaVersion(dto.manifestSchemaVersion()); + } + if (dto.artifactDigests() != null) { + for (PublishedArtifactDigest artifact : dto.artifactDigests()) { + builder.addArtifactDigests( + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey(artifact.usageKey()) + .setArtifactKind(artifact.artifactKind()) + .setImmutableObjectKey(artifact.immutableObjectKey()) + .setContentDigest(artifact.contentDigest()) + .setContentType(artifact.contentType()) + .setArtifactSchemaVersion(artifact.artifactSchemaVersion())); + } + } + // Workflow run/status/family are mutable Temporal metadata, not part of the committed bundle. + return builder.build(); + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + } + + @FunctionalInterface + interface AccountProjectionReader { + ReadRedeemedOperationProjectionResponse read( + StartSessionPostAuthorizationExecutionTuple tuple, UUID ownerAttemptId, long ownerFence); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java index 79a2143135..aae7bdc88a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java @@ -23,10 +23,12 @@ public final class TemplateConfigSourceRepository { private final DSLContext dsl; private final DraftCommitCoordinatorRepository coordinator; + private final TemplateReferenceRepository templateReferences; public TemplateConfigSourceRepository(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl); coordinator = new DraftCommitCoordinatorRepository(dsl); + templateReferences = new TemplateReferenceRepository(dsl); } public TemplateConfigSourceSnapshot.Genesis enrollFreshDraft(TargetProof target) { @@ -225,6 +227,8 @@ public Optional apply(DraftCommitBindi epoch, inherited) != 1) throw new IllegalStateException("TEMPLATE_CONFIG_EPOCH_CONFLICT"); + templateReferences.synchronizeCurrentProjection( + binding.target(), binding, snapshot, mutations, createdRows); return Optional.of(application(binding).orElseThrow()); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java new file mode 100644 index 0000000000..105ccf2720 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java @@ -0,0 +1,590 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local normalized template base references and explicit tenant cutover authority. */ +public final class TemplateReferenceRepository { + private final DSLContext dsl; + + public TemplateReferenceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Creates the non-launchable initial phase only from the exact completed fresh Game operation. + * Retained tenants and rows discovered by inventory scans are never initialized here. + */ + public PhaseSnapshot initializeFreshTenant(FreshTenantCreationEvidence evidence) { + requireWritableTransaction(); + Objects.requireNonNull(evidence, "evidence"); + if (!"NEW_GAME_ROW".equals(evidence.provenanceKind())) { + throw new IllegalArgumentException("Fresh Game tenant creation evidence is required"); + } + Record owner = + dsl.fetchOne( + "SELECT g.id AS game_row_id, g.tenant_id, g.canonical_tenant_id, " + + "g.tenant_identity_provenance_kind, c.target_namespace, c.request_digest, " + + "c.operation_id, c.creation_request_id, " + + "c.status, c.source_game_row_id, c.source_game_tenant_key, c.provenance_kind, " + + "c.evidence_digest FROM game_tenant_creation_operations c JOIN game g " + + "ON g.id = c.source_game_row_id AND g.tenant_id = c.source_game_tenant_key " + + "AND g.canonical_tenant_id = c.canonical_tenant_id " + + "WHERE c.operation_id = ? FOR UPDATE OF g", + evidence.operationId()); + Long sourceGameRowId = owner == null ? null : owner.get("source_game_row_id", Long.class); + if (owner == null + || !"COMPLETED".equals(owner.get("status", String.class)) + || !evidence.operationId().equals(owner.get("operation_id", UUID.class)) + || !evidence.targetNamespace().equals(owner.get("target_namespace", String.class)) + || !evidence.creationRequestId().equals(owner.get("creation_request_id", UUID.class)) + || !evidence.requestDigest().equals(owner.get("request_digest", String.class)) + || !evidence.canonicalTenantId().equals(owner.get("canonical_tenant_id", UUID.class)) + || sourceGameRowId == null + || evidence.sourceGameRowId() != sourceGameRowId + || !evidence.sourceGameTenantKey().equals(owner.get("source_game_tenant_key", String.class)) + || !evidence.sourceGameTenantKey().equals(owner.get("tenant_id", String.class)) + || !"NEW_GAME_ROW".equals(owner.get("provenance_kind", String.class)) + || !"NEW_GAME_ROW".equals(owner.get("tenant_identity_provenance_kind", String.class)) + || !evidence.evidenceDigest().equals(owner.get("evidence_digest", String.class))) { + throw new IllegalStateException("TEMPLATE_REFERENCE_FRESH_CREATION_EVIDENCE_UNAVAILABLE"); + } + + Record existing = + dsl.fetchOne( + "SELECT * FROM game_template_reference_phase WHERE canonical_tenant_id = ? FOR UPDATE", + evidence.canonicalTenantId()); + if (existing != null) { + PhaseSnapshot snapshot = phaseSnapshot(existing); + requireSameCreation(snapshot, evidence); + return snapshot; + } + + if (dsl.execute( + "INSERT INTO game_template_reference_phase (canonical_tenant_id, source_game_row_id, " + + "source_game_tenant_key, creation_operation_id, creation_request_id, " + + "creation_evidence_digest, phase, phase_epoch) " + + "VALUES (?, ?, ?, ?, ?, ?, 'BACKFILLING', 1)", + evidence.canonicalTenantId(), + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.operationId(), + evidence.creationRequestId(), + evidence.evidenceDigest()) + != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_GENESIS_WRITE_CONFLICT"); + } + PhaseSnapshot persisted = readPhaseForUpdate(evidence.canonicalTenantId()).orElseThrow(); + requireSameCreation(persisted, evidence); + if (persisted.phase() != Phase.BACKFILLING || persisted.phaseEpoch() != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_GENESIS_READBACK_CONFLICT"); + } + return persisted; + } + + /** + * Reads explicit phase state. An absent row remains absent and is never interpreted as ENFORCED. + */ + public Optional readPhase(UUID canonicalTenantId) { + requireCanonicalTenantId(canonicalTenantId); + Record row = + dsl.fetchOne( + "SELECT * FROM game_template_reference_phase WHERE canonical_tenant_id = ?", + canonicalTenantId); + return row == null ? Optional.empty() : Optional.of(phaseSnapshot(row)); + } + + public PhaseSnapshot requireEnforced(UUID canonicalTenantId) { + return readPhase(canonicalTenantId) + .filter(snapshot -> snapshot.phase() == Phase.ENFORCED) + .orElseThrow(() -> new IllegalStateException("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED")); + } + + /** + * Validates the complete physical tenant inventory under the Game-row mutex, then performs both + * monotonic CAS transitions using the same exact inventory/source digest. This is an internal + * owner primitive, not a public or read-side repair operation. + */ + public PhaseSnapshot validateAndEnforce(UUID canonicalTenantId) { + requireWritableReadCommittedTransaction(); + requireCanonicalTenantId(canonicalTenantId); + GameOwner owner = lockGameOwner(canonicalTenantId); + PhaseSnapshot phase = + readPhaseForUpdate(canonicalTenantId) + .orElseThrow( + () -> new IllegalStateException("TEMPLATE_REFERENCE_PHASE_NOT_INITIALIZED")); + requirePhaseOwnerMatches(phase, owner); + if (phase.phase() == Phase.ENFORCED) return phase; + + InventoryEvidence evidence = readCompleteInventory(owner); + if (phase.phase() == Phase.BACKFILLING) { + if (dsl.execute( + "UPDATE game_template_reference_phase SET phase = 'VALIDATED', phase_epoch = phase_epoch + 1, " + + "inventory_digest = ?, inventory_template_count = ? " + + "WHERE canonical_tenant_id = ? AND phase = 'BACKFILLING' AND phase_epoch = ?", + evidence.digest(), + evidence.templateCount(), + canonicalTenantId, + phase.phaseEpoch()) + != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_CAS_CONFLICT"); + } + phase = readPhaseForUpdate(canonicalTenantId).orElseThrow(); + if (phase.phase() != Phase.VALIDATED + || !evidence.digest().equals(phase.inventoryDigest()) + || evidence.templateCount() != phase.inventoryTemplateCount()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_VALIDATION_READBACK_CONFLICT"); + } + } else if (phase.phase() == Phase.VALIDATED + && (!evidence.digest().equals(phase.inventoryDigest()) + || evidence.templateCount() != phase.inventoryTemplateCount())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_VALIDATION_EVIDENCE_STALE"); + } + + if (phase.phase() != Phase.VALIDATED + || dsl.execute( + "UPDATE game_template_reference_phase SET phase = 'ENFORCED', phase_epoch = phase_epoch + 1 " + + "WHERE canonical_tenant_id = ? AND phase = 'VALIDATED' AND phase_epoch = ? " + + "AND inventory_digest = ? AND inventory_template_count = ?", + canonicalTenantId, + phase.phaseEpoch(), + evidence.digest(), + evidence.templateCount()) + != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_CAS_CONFLICT"); + } + PhaseSnapshot enforced = readPhaseForUpdate(canonicalTenantId).orElseThrow(); + if (enforced.phase() != Phase.ENFORCED + || enforced.phaseEpoch() != phase.phaseEpoch() + 1 + || !evidence.digest().equals(enforced.inventoryDigest()) + || evidence.templateCount() != enforced.inventoryTemplateCount()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_ENFORCEMENT_READBACK_CONFLICT"); + } + return enforced; + } + + /** Applies one authorized source mutation to the current canonical base projection. */ + void synchronizeCurrentProjection( + TargetProof target, + DraftCommitBinding binding, + TemplateConfigSourceSnapshot snapshot, + List mutations, + Map createdRows) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(snapshot, "snapshot"); + if (!binding.target().equals(target) || !snapshot.binding().equals(binding)) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_BINDING_CONFLICT"); + } + Map finalMutationByTemplate = + new java.util.LinkedHashMap<>(); + for (TemplateConfigSource.Mutation mutation : mutations) { + String templateId = + mutation.operation() == TemplateConfigSource.OperationKind.CREATE + ? createdRows.get(mutation.revisionId()) + : mutation.templateId(); + if (templateId == null) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_TEMPLATE_ID_UNAVAILABLE"); + } + finalMutationByTemplate.put(templateId, mutation); + } + for (var mutationEntry : finalMutationByTemplate.entrySet()) { + String templateId = mutationEntry.getKey(); + TemplateConfigSource.Mutation mutation = mutationEntry.getValue(); + TemplateConfigSource.Entry current = + snapshot.entries().stream() + .filter(entry -> entry.templateId().equals(templateId)) + .findFirst() + .orElse(null); + if (current == null) { + if (mutation.operation() != TemplateConfigSource.OperationKind.DELETE) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_ENTRY_MISSING"); + } + dsl.execute( + "DELETE FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + target.canonicalTenantId(), + Long.parseLong(templateId)); + continue; + } + if (mutation.operation() == TemplateConfigSource.OperationKind.DELETE + || !current.sourceBinding().equals(binding) + || !current.config().baseVersionId().equals(target.canonicalVersionId())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_ENTRY_PROVENANCE_CONFLICT"); + } + int written = + dsl.execute( + "INSERT INTO game_template_version_ref (canonical_tenant_id, template_id, canonical_version_id, " + + "source_commit_id, source_revision_id) VALUES (?, ?, ?, ?, ?) " + + "ON CONFLICT (canonical_tenant_id, template_id) DO UPDATE SET " + + "source_commit_id = EXCLUDED.source_commit_id, " + + "source_revision_id = EXCLUDED.source_revision_id", + target.canonicalTenantId(), + Long.parseLong(templateId), + target.canonicalVersionId(), + current.sourceBinding().commitId(), + current.revisionId()); + if (written != 1) { + throw new IllegalStateException("TEMPLATE_REFERENCE_BASE_PROJECTION_WRITE_CONFLICT"); + } + Record readback = + dsl.fetchOne( + "SELECT canonical_version_id, source_commit_id, source_revision_id " + + "FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + target.canonicalTenantId(), + Long.parseLong(templateId)); + if (readback == null + || !target.canonicalVersionId().equals(readback.get("canonical_version_id", UUID.class)) + || !current + .sourceBinding() + .commitId() + .equals(readback.get("source_commit_id", UUID.class)) + || !current.revisionId().equals(readback.get("source_revision_id", UUID.class))) { + throw new IllegalStateException("TEMPLATE_REFERENCE_BASE_PROJECTION_READBACK_CONFLICT"); + } + } + } + + /** + * Exact current projection read for later launch-consumer integration; no fallback is provided. + */ + public Optional readExactBaseReference(UUID canonicalTenantId, long templateId) { + requireCanonicalTenantId(canonicalTenantId); + if (templateId <= 0) throw new IllegalArgumentException("Positive template row id required"); + Record row = + dsl.fetchOne( + "SELECT r.canonical_tenant_id, r.template_id, r.canonical_version_id, " + + "r.source_commit_id, r.source_revision_id, t.tenant_id " + + "FROM game_template_version_ref r JOIN game_templates t ON t.id = r.template_id " + + "JOIN game g ON g.tenant_id = t.tenant_id AND g.canonical_tenant_id = r.canonical_tenant_id " + + "WHERE r.canonical_tenant_id = ? AND r.template_id = ?", + canonicalTenantId, + templateId); + if (row == null) return Optional.empty(); + if (!canonicalTenantId.equals(row.get("canonical_tenant_id", UUID.class)) + || templateId != row.get("template_id", Long.class)) { + throw new IllegalStateException("TEMPLATE_REFERENCE_BASE_READBACK_SCOPE_CONFLICT"); + } + return Optional.of( + new BaseReference( + canonicalTenantId, + templateId, + row.get("canonical_version_id", UUID.class), + row.get("source_commit_id", UUID.class), + row.get("source_revision_id", UUID.class))); + } + + private InventoryEvidence readCompleteInventory(GameOwner owner) { + List rows = + dsl.fetch( + "SELECT t.id, t.tenant_id, t.config::TEXT AS config_json, t.default_version_id, " + + "q.canonical_tenant_id, q.canonical_version_id " + + "FROM game_templates t LEFT JOIN game_design_template_config_source_qualification q " + + "ON q.template_id = t.id WHERE t.tenant_id = ? ORDER BY t.id", + owner.tenantKey()); + if (rows.isEmpty()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_EMPTY"); + } + + Map scopes = new TreeMap<>(); + Map> templatesByVersion = new HashMap<>(); + List completeTemplates = new ArrayList<>(); + for (Record row : rows) { + Long templateId = row.get("id", Long.class); + Long privateVersionId = row.get("default_version_id", Long.class); + UUID rowTenantId = row.get("canonical_tenant_id", UUID.class); + UUID canonicalVersionId = row.get("canonical_version_id", UUID.class); + if (templateId == null + || privateVersionId == null + || !owner.canonicalTenantId().equals(rowTenantId) + || canonicalVersionId == null) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_UNQUALIFIED"); + } + VersionScope scope = scopes.get(canonicalVersionId); + if (scope == null) { + scope = findVersionScope(owner, canonicalVersionId, privateVersionId); + scopes.put(canonicalVersionId, scope); + } else if (scope.privateVersionId() != privateVersionId) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_VERSION_CONFLICT"); + } + TemplateRow template = + new TemplateRow( + templateId, + privateVersionId, + canonicalVersionId, + row.get("config_json", String.class)); + completeTemplates.add(template); + if (templatesByVersion + .computeIfAbsent(canonicalVersionId, ignored -> new HashMap<>()) + .put(templateId, template) + != null) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_DUPLICATE_TEMPLATE"); + } + } + + List> evidenceTemplates = new ArrayList<>(); + Set sourceEntryTemplateIds = new HashSet<>(); + TemplateConfigSourceRepository sourceRepository = new TemplateConfigSourceRepository(dsl); + for (var scopeEntry : scopes.entrySet()) { + UUID canonicalVersionId = scopeEntry.getKey(); + VersionScope scope = scopeEntry.getValue(); + Record head = + dsl.fetchOne( + "SELECT visible_commit_id FROM game_design_template_config_source_head " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + owner.canonicalTenantId(), + canonicalVersionId); + UUID visibleCommitId = head == null ? null : head.get("visible_commit_id", UUID.class); + if (visibleCommitId == null) { + throw new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_SNAPSHOT_UNAVAILABLE"); + } + TemplateConfigSourceSnapshot snapshot = + sourceRepository + .readSnapshot(scope.target(), visibleCommitId) + .orElseThrow( + () -> + new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_SNAPSHOT_UNAVAILABLE")); + Map versionTemplates = templatesByVersion.get(canonicalVersionId); + if (snapshot.entries().size() != versionTemplates.size()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_SOURCE_SET_CONFLICT"); + } + for (TemplateConfigSource.Entry entry : snapshot.entries()) { + long templateId = Long.parseLong(entry.templateId()); + TemplateRow template = versionTemplates.get(templateId); + if (template == null + || !entry.sourceBinding().target().equals(scope.target()) + || !entry.config().baseVersionId().equals(canonicalVersionId) + || !new TemplateConfigSource.Config(template.configJson()) + .canonicalJson() + .equals(entry.config().canonicalJson()) + || !sourceEntryTemplateIds.add(templateId)) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_SOURCE_SET_CONFLICT"); + } + entry.config().requireAvailableOwnerReads(); + requireExactProjection(owner.canonicalTenantId(), template, snapshot, entry); + evidenceTemplates.add( + Map.of( + "templateId", Long.toString(templateId), + "canonicalVersionId", canonicalVersionId.toString(), + "sourceCommitId", entry.sourceBinding().commitId().toString(), + "sourceRevisionId", entry.revisionId().toString(), + "sourceSnapshotDigest", snapshot.digest(), + "configJson", entry.config().canonicalJson())); + } + } + if (sourceEntryTemplateIds.size() != completeTemplates.size()) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_SOURCE_SET_CONFLICT"); + } + String canonicalEvidence = + CommandSource.canonical( + Map.of( + "schema", "game-design-template-reference-inventory/v1", + "canonicalTenantId", owner.canonicalTenantId().toString(), + "sourceGameRowId", Long.toString(owner.gameRowId()), + "sourceGameTenantKey", owner.tenantKey(), + "templates", evidenceTemplates)); + return new InventoryEvidence( + CommandSource.sha256(canonicalEvidence.getBytes(StandardCharsets.UTF_8)), + completeTemplates.size()); + } + + private VersionScope findVersionScope( + GameOwner owner, UUID canonicalVersionId, long expectedPrivateVersionId) { + Record version = + dsl.fetchOne( + "SELECT v.id, v.tenant_id, v.canonical_tenant_id, v.canonical_version_id, " + + "v.identity_source_game_row_id, v.identity_source_game_tenant_key, " + + "v.identity_source_provenance_kind FROM version v JOIN game g " + + "ON g.id = v.identity_source_game_row_id " + + "AND g.tenant_id = v.identity_source_game_tenant_key " + + "AND g.canonical_tenant_id = v.canonical_tenant_id " + + "AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind " + + "WHERE v.canonical_tenant_id = ? AND v.canonical_version_id = ?", + owner.canonicalTenantId(), + canonicalVersionId); + if (version == null + || expectedPrivateVersionId != version.get("id", Long.class) + || !owner.tenantKey().equals(version.get("tenant_id", String.class)) + || owner.gameRowId() != version.get("identity_source_game_row_id", Long.class) + || !owner.tenantKey().equals(version.get("identity_source_game_tenant_key", String.class)) + || !owner + .provenanceKind() + .equals(version.get("identity_source_provenance_kind", String.class))) { + throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_VERSION_PROVENANCE_CONFLICT"); + } + TargetProof target = + new TargetProof( + version.get("canonical_tenant_id", UUID.class), + version.get("canonical_version_id", UUID.class), + version.get("id", Long.class), + version.get("tenant_id", String.class), + version.get("identity_source_game_row_id", Long.class), + version.get("identity_source_game_tenant_key", String.class), + version.get("identity_source_provenance_kind", String.class)); + return new VersionScope(target, expectedPrivateVersionId); + } + + private void requireExactProjection( + UUID canonicalTenantId, + TemplateRow template, + TemplateConfigSourceSnapshot snapshot, + TemplateConfigSource.Entry entry) { + Record projection = + dsl.fetchOne( + "SELECT canonical_version_id, source_commit_id, source_revision_id " + + "FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + canonicalTenantId, + template.templateId()); + if (projection == null + || !template.canonicalVersionId().equals(projection.get("canonical_version_id", UUID.class)) + || !entry.sourceBinding().commitId().equals(projection.get("source_commit_id", UUID.class)) + || !entry.revisionId().equals(projection.get("source_revision_id", UUID.class)) + || !snapshot.binding().target().canonicalTenantId().equals(canonicalTenantId)) { + throw new IllegalStateException("TEMPLATE_REFERENCE_BASE_PROJECTION_UNAVAILABLE"); + } + } + + private GameOwner lockGameOwner(UUID canonicalTenantId) { + Record game = + dsl.fetchOne( + "SELECT id, tenant_id, canonical_tenant_id, tenant_identity_provenance_kind, " + + "tenant_identity_source_game_id, tenant_identity_source_legacy_tenant_id " + + "FROM game WHERE canonical_tenant_id = ? FOR UPDATE", + canonicalTenantId); + if (game == null + || game.get("id", Long.class) == null + || game.get("id", Long.class) <= 0 + || !canonicalTenantId.equals(game.get("canonical_tenant_id", UUID.class)) + || !game.get("id", Long.class) + .equals(game.get("tenant_identity_source_game_id", Long.class)) + || !game.get("tenant_id", String.class) + .equals(game.get("tenant_identity_source_legacy_tenant_id", String.class))) { + throw new IllegalStateException("TEMPLATE_REFERENCE_GAME_OWNER_UNAVAILABLE"); + } + return new GameOwner( + game.get("id", Long.class), + game.get("tenant_id", String.class), + canonicalTenantId, + game.get("tenant_identity_provenance_kind", String.class)); + } + + private void requirePhaseOwnerMatches(PhaseSnapshot phase, GameOwner owner) { + if (phase.sourceGameRowId() != owner.gameRowId() + || !phase.sourceGameTenantKey().equals(owner.tenantKey()) + || !"NEW_GAME_ROW".equals(owner.provenanceKind()) + || !"NEW_GAME_ROW".equals(phase.provenanceKind())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_GAME_OWNER_CONFLICT"); + } + } + + private Optional readPhaseForUpdate(UUID canonicalTenantId) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_template_reference_phase WHERE canonical_tenant_id = ? FOR UPDATE", + canonicalTenantId); + return row == null ? Optional.empty() : Optional.of(phaseSnapshot(row)); + } + + private PhaseSnapshot phaseSnapshot(Record row) { + return new PhaseSnapshot( + row.get("canonical_tenant_id", UUID.class), + Phase.valueOf(row.get("phase", String.class)), + row.get("phase_epoch", Long.class), + row.get("inventory_digest", String.class), + row.get("inventory_template_count", Long.class), + row.get("creation_operation_id", UUID.class), + row.get("creation_request_id", UUID.class), + row.get("source_game_row_id", Long.class), + row.get("source_game_tenant_key", String.class), + row.get("creation_evidence_digest", String.class), + "NEW_GAME_ROW"); + } + + private void requireSameCreation(PhaseSnapshot phase, FreshTenantCreationEvidence evidence) { + if (!phase.canonicalTenantId().equals(evidence.canonicalTenantId()) + || !phase.creationOperationId().equals(evidence.operationId()) + || !phase.creationRequestId().equals(evidence.creationRequestId()) + || phase.sourceGameRowId() != evidence.sourceGameRowId() + || !phase.sourceGameTenantKey().equals(evidence.sourceGameTenantKey()) + || !phase.creationEvidenceDigest().equals(evidence.evidenceDigest())) { + throw new IllegalStateException("TEMPLATE_REFERENCE_PHASE_CREATION_READBACK_CONFLICT"); + } + } + + private void requireCanonicalTenantId(UUID canonicalTenantId) { + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + if (canonicalTenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical tenant identity is required"); + } + } + + private static void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Template reference writes require a writable READ_COMMITTED owner transaction"); + } + } + + private static void requireWritableTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Template reference creation requires a writable Game Design owner transaction"); + } + } + + public enum Phase { + BACKFILLING, + VALIDATED, + ENFORCED + } + + public record PhaseSnapshot( + UUID canonicalTenantId, + Phase phase, + long phaseEpoch, + String inventoryDigest, + Long inventoryTemplateCount, + UUID creationOperationId, + UUID creationRequestId, + long sourceGameRowId, + String sourceGameTenantKey, + String creationEvidenceDigest, + String provenanceKind) {} + + public record BaseReference( + UUID canonicalTenantId, + long templateId, + UUID canonicalVersionId, + UUID sourceCommitId, + UUID sourceRevisionId) {} + + private record GameOwner( + long gameRowId, String tenantKey, UUID canonicalTenantId, String provenanceKind) {} + + private record VersionScope(TargetProof target, long privateVersionId) {} + + private record TemplateRow( + long templateId, long privateVersionId, UUID canonicalVersionId, String configJson) {} + + private record InventoryEvidence(String digest, long templateCount) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java index 06dce12e46..7fcccddab1 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.publication.TemplateReferenceRepository; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; @@ -156,7 +157,9 @@ public FreshTenantCreationEvidence createCandidate( if (completedRecord == null) { throw new IllegalStateException("Completed fresh tenant creation operation is missing"); } - return toReceipt(completedRecord); + FreshTenantCreationEvidence evidence = toReceipt(completedRecord); + new TemplateReferenceRepository(dsl).initializeFreshTenant(evidence); + return evidence; } /** Reads only a complete operation whose persisted source tuple still matches its game row. */ diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportService.java index 2f31689d91..f3f4828cad 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/AssetExportService.java @@ -1,7 +1,37 @@ package net.firedevops.firemud.gamedesign.service; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; + public interface AssetExportService { ExportedAssetManifest exportAssets(String tenantId, int version); + /** + * Exports the exact retained complete selected-Draft inventory and returns its readback proof. + */ + SelectedExportResult exportSelectedAssets(PublicationDigestRequestBinding request); + + /** Revalidates the exact retained candidate inside the caller's finalization transaction. */ + void requireSelectedCandidateForFinalization( + PublicationDigestRequestBinding request, SelectedExportResult exportResult); + void deleteExportedAssets(String tenantId, int version, java.util.List manifestAssetKeys); + + record SelectedExportResult( + ExportedAssetManifest manifest, + VersionAssetExportCandidateService.CandidateBinding candidateBinding) { + public SelectedExportResult { + java.util.Objects.requireNonNull(manifest, "manifest"); + java.util.Objects.requireNonNull(candidateBinding, "candidateBinding"); + if (!manifest.equals(candidateBinding.manifest())) { + throw new IllegalArgumentException("Selected export candidate manifest differs"); + } + } + } + + /** Signals an ambiguous selected-export boundary that must retain the publication as pending. */ + final class SelectedExportOutcomePendingException extends IllegalStateException { + public SelectedExportOutcomePendingException(String message, RuntimeException cause) { + super(message, cause); + } + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java new file mode 100644 index 0000000000..c07f62ad4f --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/VersionAssetExportCandidateService.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamedesign.service; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; + +/** Durable selected-inventory candidate evidence committed before any object-store write. */ +public interface VersionAssetExportCandidateService { + void recordSelectedCandidate( + SelectedDraftAssetInventory inventory, ExportedAssetManifest candidate, byte[] manifestBytes); + + CandidateBinding readSelectedCandidate(PublicationDigestRequestBinding request); + + /** SQL-only retained-candidate comparison inside the caller-owned finalization transaction. */ + void requireSelectedCandidateForFinalization( + PublicationDigestRequestBinding request, CandidateBinding expected); + + /** Exact source and output bindings independently read back from the immutable candidate row. */ + record CandidateBinding( + String requestDigest, + String operationDigest, + String selectedCommitDigest, + String inventorySchema, + String inventoryDigest, + ExportedAssetManifest manifest, + byte[] requestPreimage, + byte[] inventoryBytes, + byte[] manifestBytes) { + public CandidateBinding { + if (requestDigest == null || !requestDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("candidate request digest is invalid"); + } + requireSha256(operationDigest, "operationDigest"); + requireSha256(selectedCommitDigest, "selectedCommitDigest"); + if (!SelectedDraftAssetInventory.SCHEMA.equals(inventorySchema)) { + throw new IllegalArgumentException("candidate inventory schema is unsupported"); + } + requireSha256(inventoryDigest, "inventoryDigest"); + Objects.requireNonNull(manifest, "manifest").requireImmutableArtifactEvidence(); + requestPreimage = Objects.requireNonNull(requestPreimage, "requestPreimage").clone(); + inventoryBytes = Objects.requireNonNull(inventoryBytes, "inventoryBytes").clone(); + manifestBytes = Objects.requireNonNull(manifestBytes, "manifestBytes").clone(); + } + + @Override + public byte[] requestPreimage() { + return requestPreimage.clone(); + } + + @Override + public byte[] inventoryBytes() { + return inventoryBytes.clone(); + } + + @Override + public byte[] manifestBytes() { + return manifestBytes.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof CandidateBinding binding + && requestDigest.equals(binding.requestDigest) + && operationDigest.equals(binding.operationDigest) + && selectedCommitDigest.equals(binding.selectedCommitDigest) + && inventorySchema.equals(binding.inventorySchema) + && inventoryDigest.equals(binding.inventoryDigest) + && manifest.equals(binding.manifest) + && Arrays.equals(requestPreimage, binding.requestPreimage) + && Arrays.equals(inventoryBytes, binding.inventoryBytes) + && Arrays.equals(manifestBytes, binding.manifestBytes); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + requestDigest, + operationDigest, + selectedCommitDigest, + inventorySchema, + inventoryDigest, + manifest); + result = 31 * result + Arrays.hashCode(requestPreimage); + result = 31 * result + Arrays.hashCode(inventoryBytes); + result = 31 * result + Arrays.hashCode(manifestBytes); + return result; + } + + private static void requireSha256(String value, String field) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("candidate " + field + " is invalid"); + } + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java index cf8f9cd665..0caf67466e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java @@ -1,50 +1,94 @@ package net.firedevops.firemud.gamedesign.service.impl; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; import io.micrometer.core.annotation.Timed; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventoryReadService; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import tools.jackson.databind.ObjectMapper; @Service -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected collaborators remain internal service dependencies") public class AssetExportServiceImpl implements AssetExportService { private static final String MANIFEST_OBJECT_KEY = "manifest.json"; private final VersionAssetPublicationRepository publicationRepository; - @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "S3Client is thread-safe") private final S3Client s3Client; private final AssetStoreProperties properties; private final ObjectMapper objectMapper; + private final SelectedDraftAssetInventoryReadService selectedInventoryReader; + private final VersionAssetExportCandidateService candidateService; public AssetExportServiceImpl( VersionAssetPublicationRepository publicationRepository, S3Client s3Client, AssetStoreProperties properties, ObjectMapper objectMapper) { + this(publicationRepository, s3Client, properties, objectMapper, null, null); + } + + @Autowired + public AssetExportServiceImpl( + VersionAssetPublicationRepository publicationRepository, + S3Client s3Client, + AssetStoreProperties properties, + ObjectMapper objectMapper, + DSLContext dsl, + PlatformTransactionManager transactionManager, + VersionAssetExportCandidateService candidateService) { + this( + publicationRepository, + s3Client, + properties, + objectMapper, + new SelectedDraftAssetInventoryReadService(dsl, transactionManager), + candidateService); + } + + AssetExportServiceImpl( + VersionAssetPublicationRepository publicationRepository, + S3Client s3Client, + AssetStoreProperties properties, + ObjectMapper objectMapper, + SelectedDraftAssetInventoryReadService selectedInventoryReader, + VersionAssetExportCandidateService candidateService) { this.publicationRepository = publicationRepository; this.s3Client = s3Client; this.properties = copyProperties(properties); this.objectMapper = objectMapper; + this.selectedInventoryReader = selectedInventoryReader; + this.candidateService = candidateService; } private static AssetStoreProperties copyProperties(AssetStoreProperties source) { @@ -99,6 +143,296 @@ public ExportedAssetManifest exportAssets(String tenantId, int version) { } } + @Override + @Timed("gamedesign.asset.export.selected") + public SelectedExportResult exportSelectedAssets(PublicationDigestRequestBinding request) { + if (selectedInventoryReader == null || candidateService == null) { + throw new IllegalStateException("SELECTED_ASSET_EXPORT_ADAPTER_UNAVAILABLE"); + } + if (properties.getBucket() == null || properties.getBucket().isBlank()) { + throw new IllegalStateException("ASSET_STORE_BUCKET_INVALID"); + } + SelectedDraftAssetInventory inventory; + try { + inventory = selectedInventoryReader.read(request); + } catch (RuntimeException failure) { + throw inventoryReadFailure(failure); + } + if (!request.requestDigest().equals(inventory.request().requestDigest()) + || !Arrays.equals(request.canonicalPreimage(), inventory.request().canonicalPreimage())) { + throw new IllegalStateException("SELECTED_ASSET_INVENTORY_REQUEST_MISMATCH"); + } + + List assets = prepareSelectedAssets(inventory); + byte[] manifestBytes = serializeSelectedManifest(inventory, assets); + byte[] inventoryBytes = inventory.canonicalBytes(); + SelectedInventoryIdentity identity = selectedInventoryIdentity(inventoryBytes); + String manifestHash = "sha256:" + sha256(manifestBytes); + List artifactDigests = + assets.stream().map(PreparedSelectedAsset::digest).toList(); + ExportedAssetManifest manifest = + new ExportedAssetManifest( + manifestHash, + 1, + artifactDigests.stream().map(PublishedArtifactDigest::usageKey).toList(), + artifactDigests); + VersionAssetExportCandidateService.CandidateBinding expectedBinding = + new VersionAssetExportCandidateService.CandidateBinding( + request.requestDigest(), + identity.operationDigest(), + identity.selectedCommitDigest(), + SelectedDraftAssetInventory.SCHEMA, + inventory.digest(), + manifest, + request.canonicalPreimage(), + inventoryBytes, + manifestBytes); + + // The owner candidate commits before any object write. Both candidate and complete selected + // inventory are then independently read back before the immutable store is touched. + try { + candidateService.recordSelectedCandidate(inventory, manifest, manifestBytes); + } catch (RuntimeException failure) { + throw candidateBoundaryFailure("record", failure); + } + VersionAssetExportCandidateService.CandidateBinding storedCandidate; + try { + storedCandidate = candidateService.readSelectedCandidate(request); + } catch (RuntimeException failure) { + throw candidateBoundaryFailure("read", failure); + } + if (!expectedBinding.equals(storedCandidate)) { + throw new IllegalStateException("SELECTED_ASSET_EXPORT_CANDIDATE_READBACK_MISMATCH"); + } + SelectedDraftAssetInventory independentlyRead; + try { + independentlyRead = selectedInventoryReader.read(request); + } catch (RuntimeException failure) { + throw inventoryReadFailure(failure); + } + if (!inventory.digest().equals(independentlyRead.digest()) + || !Arrays.equals(inventoryBytes, independentlyRead.canonicalBytes())) { + throw new IllegalStateException("SELECTED_ASSET_INVENTORY_READBACK_MISMATCH"); + } + + for (PreparedSelectedAsset asset : assets) { + writeAndVerifyImmutableObject( + asset.digest().immutableObjectKey(), asset.bytes(), asset.digest().contentType()); + } + String manifestObjectKey = "manifests/sha256/" + manifestHash.substring("sha256:".length()); + writeAndVerifyImmutableObject(manifestObjectKey, manifestBytes, "application/json"); + return new SelectedExportResult(manifest, storedCandidate); + } + + @Override + public void requireSelectedCandidateForFinalization( + PublicationDigestRequestBinding request, SelectedExportResult exportResult) { + Objects.requireNonNull(exportResult, "exportResult"); + if (!exportResult.manifest().equals(exportResult.candidateBinding().manifest())) { + throw new IllegalStateException("SELECTED_ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + if (candidateService == null) { + throw new IllegalStateException("SELECTED_ASSET_EXPORT_ADAPTER_UNAVAILABLE"); + } + candidateService.requireSelectedCandidateForFinalization( + request, exportResult.candidateBinding()); + } + + private RuntimeException inventoryReadFailure(RuntimeException failure) { + if (isInfrastructureUnavailable(failure)) { + return new SelectedExportOutcomePendingException( + "selected asset inventory read outcome is unavailable", failure); + } + return failure; + } + + private RuntimeException candidateBoundaryFailure(String operation, RuntimeException failure) { + for (Throwable current = failure; current != null; current = current.getCause()) { + if ("SELECTED_ASSET_EXPORT_CANDIDATE_CONFLICT".equals(current.getMessage()) + || "SELECTED_ASSET_EXPORT_CANDIDATE_NOT_FOUND".equals(current.getMessage()) + || "SELECTED_ASSET_EXPORT_CANDIDATE_WRITE_READBACK_MISMATCH" + .equals(current.getMessage())) { + return failure; + } + } + if (isInfrastructureUnavailable(failure)) { + return new SelectedExportOutcomePendingException( + "selected asset candidate " + operation + " outcome is unresolved", failure); + } + return failure; + } + + private static boolean isInfrastructureUnavailable(Throwable failure) { + if (Status.fromThrowable(failure).getCode() == Status.Code.UNAVAILABLE) { + return true; + } + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current instanceof DataAccessException + || current instanceof org.jooq.exception.DataAccessException + || current instanceof SdkClientException) { + return true; + } + if (current instanceof software.amazon.awssdk.awscore.exception.AwsServiceException service) { + int status = service.statusCode(); + if (status == 401 + || status == 403 + || status == 404 + || status == 408 + || status == 429 + || status >= 500) { + return true; + } + } + } + return false; + } + + private SelectedInventoryIdentity selectedInventoryIdentity(byte[] inventoryBytes) { + try { + var inventory = objectMapper.readTree(inventoryBytes); + String operationBase64 = inventory.path("operationBase64").textValue(); + String commitDigest = inventory.path("selectedCommitDigest").textValue(); + if (!SelectedDraftAssetInventory.SCHEMA.equals(inventory.path("schema").textValue()) + || operationBase64 == null + || commitDigest == null + || !commitDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalStateException("SELECTED_ASSET_INVENTORY_BINDING_INVALID"); + } + byte[] operationBytes = java.util.Base64.getDecoder().decode(operationBase64); + return new SelectedInventoryIdentity("sha256:" + sha256(operationBytes), commitDigest); + } catch (RuntimeException invalid) { + if ("SELECTED_ASSET_INVENTORY_BINDING_INVALID".equals(invalid.getMessage())) { + throw invalid; + } + throw new IllegalStateException("SELECTED_ASSET_INVENTORY_BINDING_INVALID", invalid); + } + } + + private List prepareSelectedAssets(SelectedDraftAssetInventory inventory) { + ArrayList result = new ArrayList<>(); + for (SelectedDraftAssetInventory.Asset asset : inventory.assets()) { + byte[] bytes = asset.contentBytes(); + String actualDigest = "sha256:" + sha256(bytes); + if (!actualDigest.equals(asset.contentDigest())) { + throw new IllegalStateException("SELECTED_ASSET_SOURCE_BYTES_MISMATCH"); + } + PublishedArtifactDigest proof = + new PublishedArtifactDigest( + asset.usageKey(), + "BINARY", + "artifacts/sha256/" + actualDigest.substring("sha256:".length()), + actualDigest, + asset.contentType(), + 1); + result.add(new PreparedSelectedAsset(asset, bytes, proof)); + } + return List.copyOf(result); + } + + private byte[] serializeSelectedManifest( + SelectedDraftAssetInventory inventory, List assets) { + List> entries = + assets.stream() + .map( + asset -> { + var source = asset.source(); + var proof = asset.digest(); + return Map.ofEntries( + Map.entry("usageKey", source.usageKey()), + Map.entry("family", source.family().name()), + Map.entry("role", source.role()), + Map.entry("requiredness", source.requiredness()), + Map.entry("artifactKind", proof.artifactKind()), + Map.entry("objectKey", proof.immutableObjectKey()), + Map.entry("contentDigest", proof.contentDigest()), + Map.entry("contentType", proof.contentType()), + Map.entry("artifactSchemaVersion", proof.artifactSchemaVersion()), + Map.entry("byteSize", asset.bytes().length)); + }) + .toList(); + Map manifest = + Map.ofEntries( + Map.entry("schema", "game-design-selected-asset-manifest/v1"), + Map.entry("manifestSchemaVersion", 1), + Map.entry("selectedInventorySchema", SelectedDraftAssetInventory.SCHEMA), + Map.entry("selectedInventoryDigest", inventory.digest()), + Map.entry("artifacts", entries)); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(objectMapper.writeValueAsString(manifest)); + } catch (Exception invalid) { + throw new IllegalStateException("SELECTED_ASSET_MANIFEST_SERIALIZATION_FAILED", invalid); + } + } + + private void writeAndVerifyImmutableObject(String key, byte[] bytes, String contentType) { + RuntimeException putFailure = null; + try { + s3Client.putObject( + PutObjectRequest.builder() + .bucket(properties.getBucket()) + .key(key) + .contentType(contentType) + .ifNoneMatch("*") + .build(), + RequestBody.fromBytes(bytes)); + } catch (RuntimeException failure) { + // A conditional collision or lost response is resolved only by an exact subsequent GET. + putFailure = failure; + } + + final ResponseBytes observed; + try { + observed = + s3Client.getObjectAsBytes( + GetObjectRequest.builder().bucket(properties.getBucket()).key(key).build()); + } catch (RuntimeException unavailable) { + if (unavailable + instanceof software.amazon.awssdk.awscore.exception.AwsServiceException service + && service.statusCode() >= 400 + && service.statusCode() < 500 + && !isInfrastructureUnavailable(service)) { + throw new IllegalStateException("SELECTED_ASSET_OBJECT_READBACK_FAILED", unavailable); + } + if (!isInfrastructureUnavailable(unavailable)) { + throw new IllegalStateException("SELECTED_ASSET_OBJECT_READBACK_FAILED", unavailable); + } + SelectedExportOutcomePendingException pending = + new SelectedExportOutcomePendingException( + "selected asset object readback is unresolved", unavailable); + if (putFailure != null) { + pending.addSuppressed(putFailure); + } + throw pending; + } + byte[] actual = observed.asByteArray(); + GetObjectResponse response = observed.response(); + if (actual.length != bytes.length + || !Arrays.equals(actual, bytes) + || !Objects.equals(response.contentLength(), (long) bytes.length) + || !Objects.equals(response.contentType(), contentType) + || !("sha256:" + sha256(actual)).equals("sha256:" + sha256(bytes))) { + throw new IllegalStateException( + putFailure == null + ? "SELECTED_ASSET_OBJECT_READBACK_MISMATCH" + : "SELECTED_ASSET_IMMUTABLE_OBJECT_CONFLICT", + putFailure); + } + } + + private record PreparedSelectedAsset( + SelectedDraftAssetInventory.Asset source, byte[] bytes, PublishedArtifactDigest digest) { + private PreparedSelectedAsset { + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } + } + + private record SelectedInventoryIdentity(String operationDigest, String selectedCommitDigest) {} + @Override @Timed("gamedesign.asset.delete") public void deleteExportedAssets(String tenantId, int version, List manifestAssetKeys) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java new file mode 100644 index 0000000000..d0082dea34 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java @@ -0,0 +1,503 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; +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.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.ObjectMapper; + +/** Commits exact selected inventory and manifest candidates before immutable object writes. */ +@Service +public final class VersionAssetExportCandidateServiceImpl + implements VersionAssetExportCandidateService { + private static final String CONFLICT = "SELECTED_ASSET_EXPORT_CANDIDATE_CONFLICT"; + private static final Table CANDIDATE = DSL.table(DSL.name("version_asset_export_candidate")); + private static final Field TENANT_ID = field("tenant_id", String.class); + private static final Field VERSION_ID = field("version_id", Long.class); + private static final Field CANONICAL_TENANT_ID = field("canonical_tenant_id", UUID.class); + private static final Field CANONICAL_VERSION_ID = field("canonical_version_id", UUID.class); + private static final Field EXPECTED_VERSION_STATE_EPOCH = + field("expected_version_state_epoch", Long.class); + private static final Field WORKFLOW_ID = field("workflow_id", String.class); + private static final Field REQUEST_DIGEST = field("request_digest", String.class); + private static final Field REQUEST_PREIMAGE = field("request_preimage", byte[].class); + private static final Field OPERATION_DIGEST = field("operation_digest", String.class); + private static final Field SELECTED_COMMIT_DIGEST = + field("selected_commit_digest", String.class); + private static final Field INVENTORY_SCHEMA = field("inventory_schema", String.class); + private static final Field INVENTORY_DIGEST = field("inventory_digest", String.class); + private static final Field INVENTORY_BYTES = field("inventory_bytes", byte[].class); + private static final Field MANIFEST_SCHEMA_VERSION = + field("manifest_schema_version", Integer.class); + private static final Field MANIFEST_HASH = field("manifest_hash", String.class); + private static final Field MANIFEST_BYTES = field("manifest_bytes", byte[].class); + private static final Field ARTIFACT_DIGESTS_JSON = + field("artifact_digests_json", String.class); + private static final Field REQUIRED_USAGE_KEYS_JSON = + field("required_usage_keys_json", String.class); + + private final DSLContext dsl; + private final GameRepository gameRepository; + private final VersionRepository versionRepository; + private final ObjectMapper objectMapper; + private final TransactionTemplate ownerWrite; + private final TransactionTemplate ownerRead; + + public VersionAssetExportCandidateServiceImpl( + DSLContext dsl, + GameRepository gameRepository, + VersionRepository versionRepository, + PlatformTransactionManager transactionManager, + ObjectMapper objectMapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.gameRepository = Objects.requireNonNull(gameRepository, "gameRepository"); + this.versionRepository = Objects.requireNonNull(versionRepository, "versionRepository"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + var transactions = Objects.requireNonNull(transactionManager, "transactionManager"); + ownerWrite = new TransactionTemplate(transactions); + ownerWrite.setName("selected-asset-export-candidate-write"); + ownerWrite.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerWrite.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerWrite.setTimeout(15); + ownerRead = new TransactionTemplate(transactions); + ownerRead.setName("selected-asset-export-candidate-readback"); + ownerRead.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownerRead.setReadOnly(true); + ownerRead.setTimeout(15); + } + + @Override + public void recordSelectedCandidate( + SelectedDraftAssetInventory inventory, + ExportedAssetManifest candidate, + byte[] manifestBytes) { + Objects.requireNonNull(inventory, "inventory"); + Objects.requireNonNull(candidate, "candidate").requireImmutableArtifactEvidence(); + Objects.requireNonNull(manifestBytes, "manifestBytes"); + CandidateBinding expected = binding(inventory, candidate, manifestBytes); + ownerWrite.executeWithoutResult(ignored -> recordInOwnerTransaction(inventory, expected)); + } + + @Override + public CandidateBinding readSelectedCandidate(PublicationDigestRequestBinding request) { + requireCanonicalRequest(request); + CandidateBinding result = ownerRead.execute(ignored -> readInOwnerTransaction(request)); + if (result == null) { + throw new IllegalStateException("SELECTED_ASSET_EXPORT_CANDIDATE_NOT_FOUND"); + } + return result; + } + + @Override + public void requireSelectedCandidateForFinalization( + PublicationDigestRequestBinding request, CandidateBinding expected) { + requireCanonicalRequest(request); + Objects.requireNonNull(expected, "expected").manifest().requireImmutableArtifactEvidence(); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Selected candidate finalization requires caller-owned writable READ_COMMITTED transaction"); + } + if (!request.requestDigest().equals(expected.requestDigest()) + || !Arrays.equals(request.canonicalPreimage(), expected.requestPreimage())) { + throw new IllegalStateException(CONFLICT); + } + CandidateBinding retained = readInOwnerTransaction(request); + if (!expected.equals(retained)) { + throw new IllegalStateException(CONFLICT); + } + } + + private void recordInOwnerTransaction( + SelectedDraftAssetInventory inventory, CandidateBinding expected) { + var request = inventory.request(); + var target = inventory.selectedCommit().target(); + String tenantKey = target.gameDesignVersionTenantKey(); + long versionId = target.gameDesignVersionRowId(); + requireOwnerRows(inventory, tenantKey, versionId); + + Record retained = + dsl.selectFrom(CANDIDATE) + .where(TENANT_ID.eq(tenantKey).and(VERSION_ID.eq(versionId))) + .forUpdate() + .fetchOne(); + if (retained != null) { + CandidateBinding actual = bindingFromRecord(retained); + if (!expected.equals(actual)) { + throw new IllegalStateException(CONFLICT); + } + return; + } + + int inserted = + dsl.insertInto(CANDIDATE) + .set(TENANT_ID, tenantKey) + .set(VERSION_ID, versionId) + .set(CANONICAL_TENANT_ID, target.canonicalTenantId()) + .set(CANONICAL_VERSION_ID, target.canonicalVersionId()) + .set(EXPECTED_VERSION_STATE_EPOCH, expectedVersionEpoch(inventory)) + .set(WORKFLOW_ID, request.derivedWorkflowIdentity()) + .set(REQUEST_DIGEST, request.requestDigest()) + .set(REQUEST_PREIMAGE, expected.requestPreimage()) + .set(OPERATION_DIGEST, expected.operationDigest()) + .set(SELECTED_COMMIT_DIGEST, expected.selectedCommitDigest()) + .set(INVENTORY_SCHEMA, expected.inventorySchema()) + .set(INVENTORY_DIGEST, expected.inventoryDigest()) + .set(INVENTORY_BYTES, expected.inventoryBytes()) + .set(MANIFEST_SCHEMA_VERSION, expected.manifest().manifestSchemaVersion()) + .set(MANIFEST_HASH, expected.manifest().manifestHash()) + .set(MANIFEST_BYTES, expected.manifestBytes()) + .set(ARTIFACT_DIGESTS_JSON, writeJson(expected.manifest().artifactDigests())) + .set( + REQUIRED_USAGE_KEYS_JSON, + writeJson(expected.manifest().requiredManifestAssetKeys())) + .execute(); + if (inserted != 1) { + throw new IllegalStateException(CONFLICT); + } + Record readback = + dsl.selectFrom(CANDIDATE) + .where(TENANT_ID.eq(tenantKey).and(VERSION_ID.eq(versionId))) + .fetchOne(); + if (readback == null || !expected.equals(bindingFromRecord(readback))) { + throw new IllegalStateException("SELECTED_ASSET_EXPORT_CANDIDATE_WRITE_READBACK_MISMATCH"); + } + } + + private void requireOwnerRows( + SelectedDraftAssetInventory inventory, String tenantKey, long versionId) { + var target = inventory.selectedCommit().target(); + Game game = gameRepository.findByTenantIdForUpdate(tenantKey); + Version version = + versionRepository + .findByTenantIdAndIdForUpdate(tenantKey, versionId) + .orElseThrow(() -> new IllegalStateException(CONFLICT)); + var provenance = gameRepository.findRuntimeTenantIdentityByTenantKey(tenantKey).orElse(null); + if (game == null + || game.getId() == null + || provenance == null + || !Objects.equals(game.getId(), target.sourceGameRowId()) + || !Objects.equals(game.getTenantId(), target.sourceGameTenantKey()) + || !Objects.equals(provenance.canonicalTenantId(), target.canonicalTenantId()) + || !Objects.equals(provenance.sourceGameId(), target.sourceGameRowId()) + || !Objects.equals(provenance.sourceLegacyTenantId(), target.sourceGameTenantKey()) + || !Objects.equals(version.getId(), target.gameDesignVersionRowId()) + || !Objects.equals(version.getTenantId(), tenantKey) + || !Objects.equals(version.getCanonicalTenantId(), target.canonicalTenantId()) + || !Objects.equals(version.getCanonicalVersionId(), target.canonicalVersionId()) + || !Objects.equals(version.getIdentitySourceGameRowId(), target.sourceGameRowId()) + || !Objects.equals(version.getIdentitySourceGameTenantKey(), target.sourceGameTenantKey()) + || !Objects.equals(version.getIdentitySourceProvenanceKind(), target.sourceProvenanceKind()) + || version.getVersionState() != VersionLifecycleState.DRAFT + || !Objects.equals(version.getVersionStateEpoch(), expectedVersionEpoch(inventory)) + || version.getVersionNumber() <= 0) { + throw new IllegalStateException(CONFLICT); + } + } + + private CandidateBinding readInOwnerTransaction(PublicationDigestRequestBinding request) { + long versionId = Long.parseLong(request.versionId()); + UUID tenantId = UUID.fromString(request.tenantId()); + List matches = + dsl.selectFrom(CANDIDATE) + .where( + CANONICAL_TENANT_ID + .eq(tenantId) + .and(VERSION_ID.eq(versionId)) + .and(REQUEST_DIGEST.eq(request.requestDigest())) + .and(WORKFLOW_ID.eq(request.derivedWorkflowIdentity()))) + .fetch(); + if (matches.size() != 1) { + throw new IllegalStateException("SELECTED_ASSET_EXPORT_CANDIDATE_NOT_FOUND"); + } + CandidateBinding binding = bindingFromRecord(matches.getFirst()); + if (!binding.requestDigest().equals(request.requestDigest()) + || !Arrays.equals(binding.requestPreimage(), request.canonicalPreimage())) { + throw new IllegalStateException(CONFLICT); + } + return binding; + } + + private CandidateBinding binding( + SelectedDraftAssetInventory inventory, ExportedAssetManifest manifest, byte[] manifestBytes) { + requireCanonicalRequest(inventory.request()); + byte[] inventoryBytes = inventory.canonicalBytes(); + byte[] operationBytes = inventory.operation().canonicalBytes(); + if (!sha256(inventoryBytes).equals(inventory.digest()) + || !sha256(operationBytes).equals(operationDigest(inventory)) + || !sha256(manifestBytes).equals(manifest.manifestHash()) + || !requestMatchesOperation(inventory)) { + throw new IllegalStateException(CONFLICT); + } + List expectedDigests = + inventory.assets().stream() + .map( + asset -> + new PublishedArtifactDigest( + asset.usageKey(), + "BINARY", + "artifacts/sha256/" + asset.contentDigest().substring("sha256:".length()), + asset.contentDigest(), + asset.contentType(), + 1)) + .toList(); + if (manifest.manifestSchemaVersion() != 1 + || !manifest.artifactDigests().equals(expectedDigests) + || !manifest + .requiredManifestAssetKeys() + .equals(expectedDigests.stream().map(PublishedArtifactDigest::usageKey).toList())) { + throw new IllegalStateException(CONFLICT); + } + var inventoryJson = objectMapper.readTree(inventoryBytes); + requireCanonicalJson(inventoryBytes, inventoryJson); + if (!inventory.request().requestDigest().equals(inventoryJson.path("requestDigest").textValue()) + || !Base64.getEncoder() + .encodeToString(inventory.request().canonicalPreimage()) + .equals(inventoryJson.path("requestPreimageBase64").textValue())) { + throw new IllegalStateException(CONFLICT); + } + requireManifestMatchesInventory( + inventoryJson, inventory.digest(), manifestBytes, expectedDigests); + return new CandidateBinding( + inventory.request().requestDigest(), + operationDigest(inventory), + inventory.selectedCommit().digest(), + SelectedDraftAssetInventory.SCHEMA, + inventory.digest(), + manifest, + inventory.request().canonicalPreimage(), + inventoryBytes, + manifestBytes); + } + + private CandidateBinding bindingFromRecord(Record record) { + byte[] requestPreimage = record.get(REQUEST_PREIMAGE); + byte[] inventoryBytes = record.get(INVENTORY_BYTES); + byte[] manifestBytes = record.get(MANIFEST_BYTES); + if (requestPreimage == null + || inventoryBytes == null + || manifestBytes == null + || !sha256(inventoryBytes).equals(record.get(INVENTORY_DIGEST)) + || !sha256(manifestBytes).equals(record.get(MANIFEST_HASH))) { + throw new IllegalStateException(CONFLICT); + } + String requestDigest = record.get(REQUEST_DIGEST); + if (!sha256Hex(requestPreimage).equals(requestDigest)) { + throw new IllegalStateException(CONFLICT); + } + var inventoryJson = objectMapper.readTree(inventoryBytes); + if (!SelectedDraftAssetInventory.SCHEMA.equals(inventoryJson.path("schema").textValue()) + || !Base64.getEncoder() + .encodeToString(requestPreimage) + .equals(inventoryJson.path("requestPreimageBase64").textValue()) + || !record + .get(OPERATION_DIGEST) + .equals(sha256(decodeBase64(inventoryJson.path("operationBase64").textValue()))) + || !record + .get(SELECTED_COMMIT_DIGEST) + .equals(inventoryJson.path("selectedCommitDigest").textValue()) + || !record.get(REQUEST_DIGEST).equals(inventoryJson.path("requestDigest").textValue())) { + throw new IllegalStateException(CONFLICT); + } + List digests = + objectMapper.readValue( + record.get(ARTIFACT_DIGESTS_JSON), + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, PublishedArtifactDigest.class)); + List keys = + objectMapper.readValue(record.get(REQUIRED_USAGE_KEYS_JSON), new TypeReference<>() {}); + requireCanonicalJson(inventoryBytes, inventoryJson); + requireManifestMatchesInventory( + inventoryJson, record.get(INVENTORY_DIGEST), manifestBytes, digests); + ExportedAssetManifest manifest = + new ExportedAssetManifest( + record.get(MANIFEST_HASH), record.get(MANIFEST_SCHEMA_VERSION), keys, digests); + return new CandidateBinding( + requestDigest, + record.get(OPERATION_DIGEST), + record.get(SELECTED_COMMIT_DIGEST), + record.get(INVENTORY_SCHEMA), + record.get(INVENTORY_DIGEST), + manifest, + requestPreimage, + inventoryBytes, + manifestBytes); + } + + private static byte[] decodeBase64(String value) { + try { + return Base64.getDecoder().decode(value); + } catch (RuntimeException invalid) { + throw new IllegalStateException(CONFLICT, invalid); + } + } + + private void requireManifestMatchesInventory( + tools.jackson.databind.JsonNode inventoryJson, + String inventoryDigest, + byte[] manifestBytes, + List digests) { + try { + var manifestJson = objectMapper.readTree(manifestBytes); + requireCanonicalJson(manifestBytes, manifestJson); + var sourceAssets = inventoryJson.path("assets"); + var manifestAssets = manifestJson.path("artifacts"); + if (!"game-design-selected-asset-manifest/v1".equals(manifestJson.path("schema").textValue()) + || manifestJson.path("manifestSchemaVersion").asInt(-1) != 1 + || !SelectedDraftAssetInventory.SCHEMA.equals( + manifestJson.path("selectedInventorySchema").textValue()) + || !inventoryDigest.equals(manifestJson.path("selectedInventoryDigest").textValue()) + || !sourceAssets.isArray() + || !manifestAssets.isArray() + || sourceAssets.size() != digests.size() + || manifestAssets.size() != digests.size()) { + throw new IllegalStateException(CONFLICT); + } + for (int index = 0; index < digests.size(); index++) { + var source = sourceAssets.get(index); + var observed = manifestAssets.get(index); + var proof = digests.get(index); + if (!proof.usageKey().equals(source.path("usageKey").textValue()) + || !proof.usageKey().equals(observed.path("usageKey").textValue()) + || !source.path("family").textValue().equals(observed.path("family").textValue()) + || !source.path("role").textValue().equals(observed.path("role").textValue()) + || !source + .path("requiredness") + .textValue() + .equals(observed.path("requiredness").textValue()) + || !"BINARY".equals(proof.artifactKind()) + || !proof.artifactKind().equals(observed.path("artifactKind").textValue()) + || !proof.immutableObjectKey().equals(observed.path("objectKey").textValue()) + || !proof.contentDigest().equals(source.path("contentDigest").textValue()) + || !proof.contentDigest().equals(observed.path("contentDigest").textValue()) + || !proof.contentType().equals(source.path("contentType").textValue()) + || !proof.contentType().equals(observed.path("contentType").textValue()) + || proof.artifactSchemaVersion() != observed.path("artifactSchemaVersion").asInt(-1) + || !source + .path("byteSize") + .textValue() + .equals(Long.toString(observed.path("byteSize").asLong(-1L)))) { + throw new IllegalStateException(CONFLICT); + } + } + } catch (RuntimeException invalid) { + if (CONFLICT.equals(invalid.getMessage())) { + throw invalid; + } + throw new IllegalStateException(CONFLICT, invalid); + } + } + + private void requireCanonicalJson(byte[] bytes, tools.jackson.databind.JsonNode value) { + try { + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8(objectMapper.writeValueAsString(value)); + if (!Arrays.equals(bytes, canonical)) { + throw new IllegalStateException(CONFLICT); + } + } catch (IOException invalid) { + throw new IllegalStateException(CONFLICT, invalid); + } catch (RuntimeException invalid) { + if (CONFLICT.equals(invalid.getMessage())) { + throw invalid; + } + throw new IllegalStateException(CONFLICT, invalid); + } + } + + private static String operationDigest(SelectedDraftAssetInventory inventory) { + return sha256(inventory.operation().canonicalBytes()); + } + + private static boolean requestMatchesOperation(SelectedDraftAssetInventory inventory) { + var request = inventory.request(); + var operation = inventory.operation(); + var target = operation.account().input().selection().target(); + var intent = operation.account().input().selection().intent(); + return request.tenantId().equals(target.canonicalTenantId().toString()) + && request.versionId().equals(Long.toString(target.gameDesignVersionRowId())) + && request.publishRequestId().equals(intent.publishRequestId()) + && request.derivedWorkflowIdentity().equals(operation.workflowId()); + } + + private static long expectedVersionEpoch(SelectedDraftAssetInventory inventory) { + try { + return Long.parseLong( + inventory.operation().account().input().selection().intent().expectedVersionStateEpoch()); + } catch (RuntimeException invalid) { + throw new IllegalStateException(CONFLICT, invalid); + } + } + + private void requireCanonicalRequest(PublicationDigestRequestBinding request) { + if (request == null + || request.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw new IllegalArgumentException("Canonical full-version request required"); + } + var canonical = + PublicationDigestRequestBinding.full( + request.tenantId(), request.versionId(), request.publishRequestId()); + if (!Arrays.equals(request.canonicalPreimage(), canonical.canonicalPreimage()) + || !request.requestDigest().equals(canonical.requestDigest()) + || !request.derivedWorkflowIdentity().equals(canonical.derivedWorkflowIdentity()) + || !UUID.fromString(request.tenantId()).toString().equals(request.tenantId())) { + throw new IllegalArgumentException("Noncanonical selected publication request"); + } + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception invalid) { + throw new IllegalStateException( + "SELECTED_ASSET_EXPORT_CANDIDATE_SERIALIZATION_FAILED", invalid); + } + } + + private static String sha256(byte[] bytes) { + return "sha256:" + sha256Hex(bytes); + } + + private static String sha256Hex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private static Field field(String name, Class type) { + return DSL.field(DSL.name(name), type); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index a27e4daa28..4d9a0d1143 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -182,8 +182,22 @@ private PublishWorkflowSnapshot reconcileFullVersionPublish( return failDefinitively(request, attempt, version, null, ex); } ExportedAssetManifest exportedManifest; + AssetExportService.SelectedExportResult selectedExportResult; try { - exportedManifest = assetExportService.exportAssets(request.tenantId(), dto.versionNumber()); + if (selectedBinding == null) { + selectedExportResult = null; + exportedManifest = assetExportService.exportAssets(request.tenantId(), dto.versionNumber()); + } else { + selectedExportResult = + Objects.requireNonNull( + assetExportService.exportSelectedAssets(selectedBinding), + "Exact selected asset candidate and object readback required"); + exportedManifest = selectedExportResult.manifest(); + } + } catch (AssetExportService.SelectedExportOutcomePendingException unresolved) { + throw pendingReconciliation( + "selected asset candidate or object readback is unresolved; retry exact publish request", + unresolved); } catch (RuntimeException ex) { return failDefinitively(request, attempt, version, null, ex); } @@ -191,7 +205,9 @@ private PublishWorkflowSnapshot reconcileFullVersionPublish( PublishWorkflowRequest effectiveRequest = request; try { return publishAttemptService.executeFullVersionTransaction( - () -> finalizeFullVersion(effectiveRequest, participantDigests, exportedManifest)); + () -> + finalizeFullVersion( + effectiveRequest, participantDigests, exportedManifest, selectedExportResult)); } catch (PublishAttemptService.FullVersionTransactionException ex) { RuntimeException operationFailure = ex.causeException(); if (operationFailure instanceof PendingReconciliationException) { @@ -327,7 +343,8 @@ private PublishAttempt createDraftAttempt(PublishWorkflowRequest request) { private PublishWorkflowSnapshot finalizeFullVersion( PublishWorkflowRequest request, List participantDigests, - ExportedAssetManifest exportedManifest) { + ExportedAssetManifest exportedManifest, + AssetExportService.SelectedExportResult selectedExportResult) { if (gameRepository.findByTenantIdForUpdate(request.tenantId()) == null) { throw new IllegalArgumentException("game not found"); } @@ -381,6 +398,19 @@ private PublishWorkflowSnapshot finalizeFullVersion( "original World publication evidence requires exact reconciliation", unresolved); } VersionDto dto = versionMapper.toDto(version); + PublicationDigestRequestBinding selectedBinding = validateFullVersionAttempt(attempt, request); + if (selectedBinding != null) { + if (selectedExportResult == null + || !exportedManifest.equals(selectedExportResult.manifest())) { + throw pendingReconciliation("exact selected asset export candidate is unavailable"); + } + // SQL-only exact readback joins the immutable candidate before any final release writes. + // Object-store calls and selected inventory export occurred outside this transaction. + assetExportService.requireSelectedCandidateForFinalization( + selectedBinding, selectedExportResult); + } else if (selectedExportResult != null) { + throw pendingReconciliation("selected asset candidate cannot finalize a generic publication"); + } publishAttemptService.recordFullVersionParticipantDigests( request.publishWorkflowId(), participantDigests); VersionAssetArtifactStateDto exportedState = @@ -583,7 +613,10 @@ private PublishWorkflowSnapshot failDefinitively( "full-version failure marking commit outcome is unknown; readback/reconciliation is required", ambiguousFailure); } - cleanupExportedAssets(request.tenantId(), version.getVersionNumber(), exportedManifest); + if (!isSelectionDigest(attempt.getRequestDigest())) { + // Selected outputs are immutable/shared; only a separate reachability proof may purge them. + cleanupExportedAssets(request.tenantId(), version.getVersionNumber(), exportedManifest); + } return new PublishWorkflowSnapshot( attempt.getVersionId(), attempt.getVersionNumber(), diff --git a/services/game-design-service/src/main/resources/db/migration/V64__normalized_template_references_and_tenant_phase.sql b/services/game-design-service/src/main/resources/db/migration/V64__normalized_template_references_and_tenant_phase.sql new file mode 100644 index 0000000000..4bc3c533e7 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V64__normalized_template_references_and_tenant_phase.sql @@ -0,0 +1,410 @@ +ALTER TABLE game_design_template_config_source_revision + ADD CONSTRAINT uq_template_config_revision_source_binding + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_id, template_id); + +CREATE TABLE game_template_version_ref ( + canonical_tenant_id UUID NOT NULL, + template_id BIGINT NOT NULL, + canonical_version_id UUID NOT NULL, + source_commit_id UUID NOT NULL, + source_revision_id UUID NOT NULL, + PRIMARY KEY (canonical_tenant_id, template_id), + FOREIGN KEY (template_id) + REFERENCES game_design_template_config_source_qualification (template_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id) + REFERENCES game_design_template_config_source_genesis (canonical_tenant_id, canonical_version_id) + ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, source_commit_id) + REFERENCES game_design_template_config_source_application + (canonical_tenant_id, canonical_version_id, commit_id) ON DELETE RESTRICT, + FOREIGN KEY (canonical_tenant_id, canonical_version_id, source_commit_id, source_revision_id, template_id) + REFERENCES game_design_template_config_source_revision + (canonical_tenant_id, canonical_version_id, commit_id, revision_id, template_id) + ON DELETE RESTRICT, + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID) +); +CREATE INDEX ix_game_template_version_ref_version + ON game_template_version_ref (canonical_tenant_id, canonical_version_id, template_id); + +CREATE TABLE game_template_reference_phase ( + canonical_tenant_id UUID PRIMARY KEY REFERENCES game (canonical_tenant_id) ON DELETE RESTRICT, + source_game_row_id BIGINT NOT NULL REFERENCES game (id) ON DELETE RESTRICT, + source_game_tenant_key VARCHAR(36) NOT NULL, + creation_operation_id UUID NOT NULL UNIQUE + REFERENCES game_tenant_creation_operations (operation_id) ON DELETE RESTRICT, + creation_request_id UUID NOT NULL, + creation_evidence_digest VARCHAR(71) NOT NULL, + phase VARCHAR(16) NOT NULL, + phase_epoch BIGINT NOT NULL, + inventory_digest VARCHAR(71), + inventory_template_count BIGINT, + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (source_game_row_id > 0), + CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36), + CHECK (creation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (creation_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CHECK (phase IN ('BACKFILLING', 'VALIDATED', 'ENFORCED')), + CHECK (phase_epoch > 0), + CHECK ( + (phase = 'BACKFILLING' AND inventory_digest IS NULL AND inventory_template_count IS NULL) + OR (phase IN ('VALIDATED', 'ENFORCED') + AND inventory_digest IS NOT NULL + AND inventory_digest ~ '^sha256:[0-9a-f]{64}$' + AND inventory_template_count IS NOT NULL + AND inventory_template_count > 0) + ) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_game_template_reference_phase() RETURNS TRIGGER AS $$ +DECLARE creation game_tenant_creation_operations%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'template reference phase authority is retained' USING ERRCODE = '23514'; + END IF; + + IF TG_OP = 'INSERT' THEN + SELECT * INTO STRICT creation + FROM game_tenant_creation_operations + WHERE operation_id = NEW.creation_operation_id; + IF NEW.phase <> 'BACKFILLING' OR NEW.phase_epoch <> 1 + OR NEW.inventory_digest IS NOT NULL OR NEW.inventory_template_count IS NOT NULL + OR creation.status <> 'COMPLETED' + OR creation.operation_id <> NEW.creation_operation_id + OR creation.creation_request_id <> NEW.creation_request_id + OR creation.canonical_tenant_id <> NEW.canonical_tenant_id + OR creation.source_game_row_id <> NEW.source_game_row_id + OR creation.source_game_tenant_key <> NEW.source_game_tenant_key + OR creation.provenance_kind <> 'NEW_GAME_ROW' + OR creation.evidence_digest <> NEW.creation_evidence_digest + OR NOT 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_GAME_ROW' + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + ) THEN + RAISE EXCEPTION 'template reference phase requires exact fresh Game creation evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.source_game_row_id IS DISTINCT FROM OLD.source_game_row_id + OR NEW.source_game_tenant_key IS DISTINCT FROM OLD.source_game_tenant_key + OR NEW.creation_operation_id IS DISTINCT FROM OLD.creation_operation_id + OR NEW.creation_request_id IS DISTINCT FROM OLD.creation_request_id + OR NEW.creation_evidence_digest IS DISTINCT FROM OLD.creation_evidence_digest + OR NEW.phase_epoch <> OLD.phase_epoch + 1 + OR NOT ( + (OLD.phase = 'BACKFILLING' AND NEW.phase = 'VALIDATED' + AND NEW.inventory_digest ~ '^sha256:[0-9a-f]{64}$' + AND NEW.inventory_template_count > 0) + OR (OLD.phase = 'VALIDATED' AND NEW.phase = 'ENFORCED' + AND NEW.inventory_digest = OLD.inventory_digest + AND NEW.inventory_template_count = OLD.inventory_template_count) + ) THEN + RAISE EXCEPTION 'template reference phase requires a monotonic evidence-backed CAS transition' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_template_reference_phase_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_template_reference_phase + FOR EACH ROW EXECUTE FUNCTION guard_game_template_reference_phase(); + +CREATE FUNCTION reject_game_template_reference_phase_truncate() RETURNS TRIGGER AS $$ +BEGIN + RAISE EXCEPTION 'template reference phase authority cannot be truncated' USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER game_template_reference_phase_no_truncate + BEFORE TRUNCATE ON game_template_reference_phase + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_template_reference_phase_truncate(); + +CREATE FUNCTION lock_and_guard_game_template_reference_write() RETURNS TRIGGER AS $$ +DECLARE owner game%ROWTYPE; old_phase game_template_reference_phase%ROWTYPE; + new_phase game_template_reference_phase%ROWTYPE; + active_create BOOLEAN; active_upsert BOOLEAN; +BEGIN + IF TG_OP = 'UPDATE' AND NEW.tenant_id IS DISTINCT FROM OLD.tenant_id THEN + PERFORM id FROM game WHERE tenant_id IN (OLD.tenant_id, NEW.tenant_id) ORDER BY id FOR UPDATE; + SELECT p.* INTO old_phase FROM game_template_reference_phase p + JOIN game g ON g.canonical_tenant_id = p.canonical_tenant_id + WHERE g.tenant_id = OLD.tenant_id; + SELECT p.* INTO new_phase FROM game_template_reference_phase p + JOIN game g ON g.canonical_tenant_id = p.canonical_tenant_id + WHERE g.tenant_id = NEW.tenant_id; + IF old_phase.canonical_tenant_id IS NOT NULL OR new_phase.canonical_tenant_id IS NOT NULL THEN + RAISE EXCEPTION 'template tenant cannot change after reference phase authority exists' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + SELECT * INTO owner FROM game WHERE tenant_id = OLD.tenant_id FOR UPDATE; + ELSE + SELECT * INTO owner FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + END IF; + IF NOT FOUND OR owner.canonical_tenant_id IS NULL THEN + IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; + END IF; + + SELECT * INTO new_phase FROM game_template_reference_phase + WHERE canonical_tenant_id = owner.canonical_tenant_id; + IF NOT FOUND OR new_phase.phase = 'BACKFILLING' THEN + IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; + END IF; + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'validated template rows require an owner source tombstone' + USING ERRCODE = '23514'; + END IF; + + active_create := FALSE; + active_upsert := FALSE; + IF TG_OP = 'INSERT' THEN + SELECT EXISTS ( + SELECT 1 + FROM version v + JOIN game_design_draft_commit c + ON c.canonical_tenant_id = v.canonical_tenant_id + AND c.canonical_version_id = v.canonical_version_id + JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = c.canonical_tenant_id + AND slot.canonical_version_id = c.canonical_version_id + AND slot.request_id = c.request_id AND slot.commit_id = c.commit_id + JOIN game_design_draft_commit_owner_result result + ON result.canonical_tenant_id = c.canonical_tenant_id + AND result.canonical_version_id = c.canonical_version_id + AND result.request_id = c.request_id AND result.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND result.status IN ('IN_PROGRESS', 'UNKNOWN') + CROSS JOIN LATERAL jsonb_array_elements(c.binding_json::JSONB->'revisions') revision + WHERE v.id = NEW.default_version_id AND v.tenant_id = NEW.tenant_id + AND v.canonical_tenant_id = owner.canonical_tenant_id + AND c.canonical_tenant_id = owner.canonical_tenant_id + AND revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND (revision->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG' + AND (revision->>'payload')::JSONB->>'operation' = 'CREATE' + AND (revision->>'payload')::JSONB->>'templateName' = NEW.name + AND ((revision->>'payload')::JSONB->>'configJson')::JSONB = NEW.config + ) INTO active_create; + IF NOT active_create THEN + RAISE EXCEPTION 'validated template create requires exact active owner source binding' + USING ERRCODE = '23514'; + END IF; + ELSE + SELECT EXISTS ( + SELECT 1 + FROM game_design_template_config_source_qualification q + JOIN game_design_draft_commit c + ON c.canonical_tenant_id = q.canonical_tenant_id + AND c.canonical_version_id = q.canonical_version_id + JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = c.canonical_tenant_id + AND slot.canonical_version_id = c.canonical_version_id + AND slot.request_id = c.request_id AND slot.commit_id = c.commit_id + JOIN game_design_draft_commit_owner_result result + ON result.canonical_tenant_id = c.canonical_tenant_id + AND result.canonical_version_id = c.canonical_version_id + AND result.request_id = c.request_id AND result.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND result.status IN ('IN_PROGRESS', 'UNKNOWN') + CROSS JOIN LATERAL jsonb_array_elements(c.binding_json::JSONB->'revisions') revision + WHERE q.template_id = OLD.id AND q.canonical_tenant_id = owner.canonical_tenant_id + AND c.canonical_tenant_id = owner.canonical_tenant_id + AND revision->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND (revision->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG' + AND (revision->>'payload')::JSONB->>'operation' = 'UPSERT' + AND (revision->>'payload')::JSONB->>'templateId' = OLD.id::TEXT + AND ((revision->>'payload')::JSONB->>'configJson')::JSONB = NEW.config + ) INTO active_upsert; + IF NEW.id IS DISTINCT FROM OLD.id OR NEW.name IS DISTINCT FROM OLD.name + OR NEW.default_version_id IS DISTINCT FROM OLD.default_version_id + OR NEW.default_script_patch_version IS DISTINCT FROM OLD.default_script_patch_version + OR NEW.default_runtime_flags_json IS DISTINCT FROM OLD.default_runtime_flags_json + OR NEW.template_reference_phase IS DISTINCT FROM OLD.template_reference_phase + OR NOT active_upsert THEN + RAISE EXCEPTION 'validated template update requires exact active owner source binding' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_template_reference_tenant_mutex_and_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_templates + FOR EACH ROW EXECUTE FUNCTION lock_and_guard_game_template_reference_write(); + +CREATE FUNCTION guard_game_template_version_ref() RETURNS TRIGGER AS $$ +DECLARE owner game%ROWTYPE; template game_templates%ROWTYPE; target version%ROWTYPE; + revision game_design_template_config_source_revision%ROWTYPE; +BEGIN + SELECT * INTO owner FROM game WHERE canonical_tenant_id = + CASE WHEN TG_OP = 'DELETE' THEN OLD.canonical_tenant_id ELSE NEW.canonical_tenant_id END FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'normalized template reference lacks exact Game owner' USING ERRCODE = '23514'; + END IF; + + IF TG_OP = 'INSERT' THEN + SELECT * INTO STRICT template FROM game_templates WHERE id = NEW.template_id; + SELECT * INTO STRICT target FROM version + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT revision FROM game_design_template_config_source_revision + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.source_commit_id + AND revision_id = NEW.source_revision_id + AND template_id = NEW.template_id; + IF template.tenant_id <> owner.tenant_id + OR template.default_version_id <> target.id + OR target.tenant_id <> owner.tenant_id + OR target.identity_source_game_row_id <> owner.id + OR target.identity_source_game_tenant_key <> owner.tenant_id + OR target.identity_source_provenance_kind <> owner.tenant_identity_provenance_kind + OR revision.operation_kind NOT IN ('CREATE', 'UPSERT') + OR NOT EXISTS ( + SELECT 1 FROM game_design_template_config_source_ref ref + WHERE ref.canonical_tenant_id = NEW.canonical_tenant_id + AND ref.canonical_version_id = NEW.canonical_version_id + AND ref.revision_id = NEW.source_revision_id + AND ref.ref_kind = 'BASE_VERSION' + AND ref.ref_key = NEW.canonical_version_id::TEXT + AND ref.referenced_revision_id IS NULL + ) + OR NOT EXISTS ( + SELECT 1 + FROM game_design_draft_commit c + JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = c.canonical_tenant_id + AND slot.canonical_version_id = c.canonical_version_id + AND slot.request_id = c.request_id AND slot.commit_id = c.commit_id + JOIN game_design_draft_commit_owner_result result + ON result.canonical_tenant_id = c.canonical_tenant_id + AND result.canonical_version_id = c.canonical_version_id + AND result.request_id = c.request_id + AND result.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND result.status IN ('IN_PROGRESS', 'UNKNOWN') + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = revision.request_id + AND c.commit_id = NEW.source_commit_id + ) + OR ((revision.payload_json::JSONB)->>'configJson')::JSONB IS DISTINCT FROM template.config THEN + RAISE EXCEPTION 'normalized template base reference differs from exact authorized source' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF OLD.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR OLD.template_id IS DISTINCT FROM NEW.template_id + OR OLD.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id THEN + RAISE EXCEPTION 'normalized template base identity is immutable' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT template FROM game_templates WHERE id = NEW.template_id; + SELECT * INTO STRICT target FROM version + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT revision FROM game_design_template_config_source_revision + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.source_commit_id + AND revision_id = NEW.source_revision_id + AND template_id = NEW.template_id; + IF template.tenant_id <> owner.tenant_id + OR template.default_version_id <> target.id + OR target.tenant_id <> owner.tenant_id + OR target.identity_source_game_row_id <> owner.id + OR target.identity_source_game_tenant_key <> owner.tenant_id + OR target.identity_source_provenance_kind <> owner.tenant_identity_provenance_kind + OR revision.operation_kind <> 'UPSERT' + OR NOT EXISTS ( + SELECT 1 FROM game_design_template_config_source_ref ref + WHERE ref.canonical_tenant_id = NEW.canonical_tenant_id + AND ref.canonical_version_id = NEW.canonical_version_id + AND ref.revision_id = NEW.source_revision_id + AND ref.ref_kind = 'BASE_VERSION' + AND ref.ref_key = NEW.canonical_version_id::TEXT + AND ref.referenced_revision_id IS NULL + ) + OR NOT EXISTS ( + SELECT 1 + FROM game_design_draft_commit c + JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = c.canonical_tenant_id + AND slot.canonical_version_id = c.canonical_version_id + AND slot.request_id = c.request_id AND slot.commit_id = c.commit_id + JOIN game_design_draft_commit_owner_result result + ON result.canonical_tenant_id = c.canonical_tenant_id + AND result.canonical_version_id = c.canonical_version_id + AND result.request_id = c.request_id + AND result.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND result.status IN ('IN_PROGRESS', 'UNKNOWN') + WHERE c.canonical_tenant_id = NEW.canonical_tenant_id + AND c.canonical_version_id = NEW.canonical_version_id + AND c.request_id = revision.request_id + AND c.commit_id = NEW.source_commit_id + ) + OR ((revision.payload_json::JSONB)->>'configJson')::JSONB IS DISTINCT FROM template.config THEN + RAISE EXCEPTION 'normalized template base update differs from exact owner upsert' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + SELECT r.* INTO STRICT revision + FROM game_design_draft_commit_application_slot slot + JOIN game_design_template_config_source_revision r + ON r.canonical_tenant_id = slot.canonical_tenant_id + AND r.canonical_version_id = slot.canonical_version_id + AND r.request_id = slot.request_id AND r.commit_id = slot.commit_id + WHERE slot.canonical_tenant_id = OLD.canonical_tenant_id + AND slot.canonical_version_id = OLD.canonical_version_id + AND r.template_id = OLD.template_id AND r.operation_kind = 'DELETE'; + IF NOT EXISTS ( + SELECT 1 + FROM game_design_draft_commit c + JOIN game_design_draft_commit_application_slot slot + ON slot.canonical_tenant_id = c.canonical_tenant_id + AND slot.canonical_version_id = c.canonical_version_id + AND slot.request_id = c.request_id AND slot.commit_id = c.commit_id + JOIN game_design_draft_commit_owner_result result + ON result.canonical_tenant_id = c.canonical_tenant_id + AND result.canonical_version_id = c.canonical_version_id + AND result.request_id = c.request_id AND result.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND result.status IN ('IN_PROGRESS', 'UNKNOWN') + WHERE c.canonical_tenant_id = OLD.canonical_tenant_id + AND c.canonical_version_id = OLD.canonical_version_id + AND c.commit_id = revision.commit_id + AND c.request_id = revision.request_id + ) THEN + RAISE EXCEPTION 'normalized template base removal requires exact active source tombstone' + USING ERRCODE = '23514'; + END IF; + RETURN OLD; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_template_version_ref_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_template_version_ref + FOR EACH ROW EXECUTE FUNCTION guard_game_template_version_ref(); + +CREATE FUNCTION reject_game_template_version_ref_truncate() RETURNS TRIGGER AS $$ +BEGIN + RAISE EXCEPTION 'normalized template references cannot be truncated' USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER game_template_version_ref_no_truncate + BEFORE TRUNCATE ON game_template_version_ref + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_template_version_ref_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/main/resources/db/migration/V65__selected_inventory_asset_export_candidate.sql b/services/game-design-service/src/main/resources/db/migration/V65__selected_inventory_asset_export_candidate.sql new file mode 100644 index 0000000000..f37fb911a9 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V65__selected_inventory_asset_export_candidate.sql @@ -0,0 +1,122 @@ +CREATE TABLE version_asset_export_candidate ( + tenant_id VARCHAR(36) NOT NULL, + version_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + expected_version_state_epoch BIGINT NOT NULL, + workflow_id VARCHAR(1024) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + request_preimage BYTEA NOT NULL, + operation_digest VARCHAR(71) NOT NULL, + selected_commit_digest VARCHAR(71) NOT NULL, + inventory_schema VARCHAR(128) NOT NULL, + inventory_digest VARCHAR(71) NOT NULL, + inventory_bytes BYTEA NOT NULL, + manifest_schema_version INTEGER NOT NULL, + manifest_hash VARCHAR(71) NOT NULL, + manifest_bytes BYTEA NOT NULL, + artifact_digests_json TEXT NOT NULL, + required_usage_keys_json TEXT NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_version_asset_export_candidate PRIMARY KEY (tenant_id, version_id), + CONSTRAINT fk_version_asset_export_candidate_version + FOREIGN KEY (tenant_id, version_id) + REFERENCES version (tenant_id, id) ON DELETE RESTRICT, + CONSTRAINT chk_version_asset_export_candidate_scope CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_version_state_epoch > 0 + AND char_length(workflow_id) > 0 + AND request_digest ~ '^[0-9a-f]{64}$' + AND operation_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_commit_digest ~ '^sha256:[0-9a-f]{64}$' + AND inventory_schema = 'game-design-selected-draft-asset-inventory/v1' + AND inventory_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(request_preimage) > 0 + AND octet_length(inventory_bytes) > 0 + AND manifest_schema_version = 1 + AND manifest_hash ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(manifest_bytes) > 0 + AND artifact_digests_json::JSONB IS NOT NULL + AND required_usage_keys_json::JSONB IS NOT NULL + ) +); + +CREATE INDEX idx_version_asset_export_candidate_request + ON version_asset_export_candidate (canonical_tenant_id, version_id, request_digest); + +-- Candidate rows are the additive selected-inventory shape. V37 snapshot candidates remain +-- untouched and no retained V37 data is synthesized into this new evidence table. +-- [jooq ignore start] +CREATE FUNCTION guard_version_asset_export_candidate() RETURNS TRIGGER AS $$ +DECLARE + version_state_value VARCHAR(32); + version_epoch_value BIGINT; + version_canonical_tenant UUID; + version_canonical_version UUID; + source_game_id BIGINT; + source_game_tenant VARCHAR(36); + source_provenance VARCHAR(64); + game_canonical_tenant UUID; + game_provenance VARCHAR(64); + game_source_id BIGINT; + game_source_tenant VARCHAR(36); +BEGIN + IF TG_OP = 'UPDATE' OR TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'SELECTED_ASSET_EXPORT_CANDIDATE_IMMUTABLE'; + END IF; + + SELECT v.version_state, v.version_state_epoch, v.canonical_tenant_id, + v.canonical_version_id, v.identity_source_game_row_id, + v.identity_source_game_tenant_key, v.identity_source_provenance_kind, + g.canonical_tenant_id, g.tenant_identity_provenance_kind, + g.tenant_identity_source_game_id, g.tenant_identity_source_legacy_tenant_id + INTO version_state_value, version_epoch_value, version_canonical_tenant, + version_canonical_version, source_game_id, source_game_tenant, + source_provenance, game_canonical_tenant, game_provenance, + game_source_id, game_source_tenant + FROM version v + JOIN game g ON g.id = v.identity_source_game_row_id + AND g.tenant_id = v.identity_source_game_tenant_key + AND g.tenant_id = v.tenant_id + AND g.canonical_tenant_id = v.canonical_tenant_id + AND g.tenant_identity_provenance_kind = v.identity_source_provenance_kind + AND g.tenant_identity_source_game_id = g.id + AND g.tenant_identity_source_legacy_tenant_id = g.tenant_id + WHERE v.tenant_id = NEW.tenant_id AND v.id = NEW.version_id + FOR UPDATE OF v, g; + + IF NOT FOUND OR version_state_value <> 'DRAFT' + OR version_epoch_value IS DISTINCT FROM NEW.expected_version_state_epoch + OR version_canonical_tenant IS DISTINCT FROM NEW.canonical_tenant_id + OR version_canonical_version IS DISTINCT FROM NEW.canonical_version_id + OR source_game_id IS NULL OR source_game_tenant IS DISTINCT FROM NEW.tenant_id + OR source_provenance IS NULL + OR game_canonical_tenant IS DISTINCT FROM NEW.canonical_tenant_id + OR game_provenance IS DISTINCT FROM source_provenance + OR game_source_id IS DISTINCT FROM source_game_id + OR game_source_tenant IS DISTINCT FROM source_game_tenant THEN + RAISE EXCEPTION 'SELECTED_ASSET_EXPORT_CANDIDATE_SCOPE_CONFLICT'; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_export_candidate_immutable + BEFORE INSERT OR UPDATE OR DELETE ON version_asset_export_candidate + FOR EACH ROW EXECUTE FUNCTION guard_version_asset_export_candidate(); + +CREATE FUNCTION guard_version_asset_export_candidate_truncate() RETURNS TRIGGER AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM version_asset_export_candidate) THEN + RAISE EXCEPTION 'SELECTED_ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_version_asset_export_candidate_no_truncate + BEFORE TRUNCATE ON version_asset_export_candidate + FOR EACH STATEMENT EXECUTE FUNCTION guard_version_asset_export_candidate_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java index e385f5180a..fbbce4ef4c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -87,6 +87,19 @@ void actualCreateAndSameCommitGameplayInputHaveDurableGeneratedIdentityAndExactR var first = source(f, binding); String templateId = first.entries().getFirst().templateId(); assertThat(first.entries().getFirst().sourceBinding()).isEqualTo(binding); + var initialBaseReference = + f.dsl.fetchOne( + "SELECT canonical_tenant_id, template_id, canonical_version_id, source_commit_id, source_revision_id " + + "FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + f.target.canonicalTenantId(), + Long.parseLong(templateId)); + assertThat(initialBaseReference).isNotNull(); + assertThat(initialBaseReference.get("canonical_version_id", UUID.class)) + .isEqualTo(f.target.canonicalVersionId()); + assertThat(initialBaseReference.get("source_commit_id", UUID.class)) + .isEqualTo(binding.commitId()); + assertThat(initialBaseReference.get("source_revision_id", UUID.class)) + .isEqualTo(create.revisionId()); assertThat( f.dsl .fetchSingle( @@ -127,11 +140,36 @@ void actualCreateAndSameCommitGameplayInputHaveDurableGeneratedIdentityAndExactR "1"); apply(f, update); assertThat(source(f, update).entries().getFirst().sourceBinding()).isEqualTo(update); + var updatedBaseReference = + f.dsl.fetchOne( + "SELECT canonical_version_id, source_commit_id, source_revision_id " + + "FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + f.target.canonicalTenantId(), + Long.parseLong(templateId)); + assertThat(updatedBaseReference).isNotNull(); + assertThat(updatedBaseReference.get("canonical_version_id", UUID.class)) + .isEqualTo(f.target.canonicalVersionId()); + assertThat(updatedBaseReference.get("source_commit_id", UUID.class)) + .isEqualTo(update.commitId()); + assertThat(updatedBaseReference.get("source_revision_id", UUID.class)) + .isEqualTo(TemplateConfigSource.mutations(update).getFirst().revisionId()); assertThat(source(f, binding)).isEqualTo(first); var delete = binding(f, TemplateConfigSource.deletePayload(templateId), TemplateConfigSource.SCOPE, "2"); apply(f, delete); assertThat(source(f, delete).entries()).isEmpty(); + assertThat( + f.dsl.fetchOne( + "SELECT 1 FROM game_template_version_ref WHERE canonical_tenant_id = ? AND template_id = ?", + f.target.canonicalTenantId(), + Long.parseLong(templateId))) + .isNull(); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_templates WHERE id = ?", Long.parseLong(templateId)) + .get(0, Long.class)) + .isEqualTo(1L); assertThat(source(f, binding)).isEqualTo(first); assertThatThrownBy( () -> diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/TemplateReferencePhasePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/TemplateReferencePhasePostgresIntegrationTest.java new file mode 100644 index 0000000000..154f3c50d4 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/TemplateReferencePhasePostgresIntegrationTest.java @@ -0,0 +1,300 @@ +package integration.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; +import net.firedevops.firemud.gamedesign.publication.TemplateReferenceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Focused proof for fresh phase authority, exact current refs, and full-inventory denial. */ +@Testcontainers(disabledWithoutDocker = true) +class TemplateReferencePhasePostgresIntegrationTest { + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void freshOwnerCreationStartsBackfillingAndEmptyInventoryCannotAdvance() { + Fixture fixture = fixture(); + TemplateReferenceRepository references = new TemplateReferenceRepository(fixture.dsl()); + + var phase = references.readPhase(fixture.target().canonicalTenantId()).orElseThrow(); + assertThat(phase.phase()).isEqualTo(TemplateReferenceRepository.Phase.BACKFILLING); + assertThat(phase.phaseEpoch()).isEqualTo(1L); + assertThat(phase.creationOperationId()).isEqualTo(fixture.creation().operationId()); + assertThat(phase.creationRequestId()).isEqualTo(fixture.creation().creationRequestId()); + assertThat(phase.sourceGameRowId()).isEqualTo(fixture.creation().sourceGameRowId()); + assertThat(phase.sourceGameTenantKey()).isEqualTo(fixture.creation().sourceGameTenantKey()); + + assertThatThrownBy( + () -> + fixture + .tx() + .execute( + ignored -> + references.validateAndEnforce(fixture.target().canonicalTenantId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_REFERENCE_INVENTORY_EMPTY"); + assertThat(references.readPhase(fixture.target().canonicalTenantId()).orElseThrow()) + .isEqualTo(phase); + } + + @Test + void qualifiedCurrentSourceCanEnforcePhaseAndRawCreateIsThenDenied() { + Fixture fixture = fixture(); + DraftCommitBinding binding = createTemplate(fixture, "Starter"); + var currentReference = + fixture + .dsl() + .fetchOne( + "SELECT canonical_version_id, source_commit_id, source_revision_id " + + "FROM game_template_version_ref WHERE canonical_tenant_id = ?", + fixture.target().canonicalTenantId()); + assertThat(currentReference).isNotNull(); + assertThat(currentReference.get("canonical_version_id", UUID.class)) + .isEqualTo(fixture.target().canonicalVersionId()); + assertThat(currentReference.get("source_commit_id", UUID.class)).isEqualTo(binding.commitId()); + assertThat(currentReference.get("source_revision_id", UUID.class)) + .isEqualTo(binding.revisions().getFirst().revisionId()); + + TemplateReferenceRepository references = new TemplateReferenceRepository(fixture.dsl()); + var enforced = + fixture + .tx() + .execute( + ignored -> references.validateAndEnforce(fixture.target().canonicalTenantId())); + assertThat(enforced).isNotNull(); + assertThat(enforced.phase()).isEqualTo(TemplateReferenceRepository.Phase.ENFORCED); + assertThat(enforced.phaseEpoch()).isEqualTo(3L); + assertThat(enforced.inventoryTemplateCount()).isEqualTo(1L); + assertThat(enforced.inventoryDigest()).startsWith("sha256:"); + + assertThatThrownBy( + () -> + fixture + .tx() + .executeWithoutResult( + ignored -> + fixture + .dsl() + .execute( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, 'Raw bypass', '{}'::JSONB)", + fixture.creation().sourceGameTenantKey()))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "validated template create requires exact active owner source binding"); + assertThat(references.readPhase(fixture.target().canonicalTenantId()).orElseThrow()) + .isEqualTo(enforced); + } + + @Test + void normalSourceSynchronizationAutomaticallyEnforcesFreshCompleteInventory() { + Fixture fixture = fixture(); + DraftCommitBinding binding = createTemplate(fixture, "Automatic", true); + var references = new TemplateReferenceRepository(fixture.dsl()); + var phase = references.readPhase(fixture.target().canonicalTenantId()).orElseThrow(); + assertThat(phase.phase()).isEqualTo(TemplateReferenceRepository.Phase.ENFORCED); + assertThat(phase.phaseEpoch()).isEqualTo(3L); + assertThat(phase.inventoryTemplateCount()).isEqualTo(1L); + var configuredTemplateRow = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT id FROM game_templates WHERE tenant_id = ?", + fixture.creation().sourceGameTenantKey()), + "Automatically synchronized template row is missing"); + Long configuredTemplateId = + Objects.requireNonNull( + configuredTemplateRow.get("id", Long.class), + "Automatically synchronized template row has no id"); + assertThat( + references + .readExactBaseReference(fixture.target().canonicalTenantId(), configuredTemplateId) + .orElseThrow() + .sourceCommitId()) + .isEqualTo(binding.commitId()); + } + + @Test + void unqualifiedPhysicalTemplatePreventsTenantPromotion() { + Fixture fixture = fixture(); + createTemplate(fixture, "Qualified"); + fixture + .tx() + .executeWithoutResult( + ignored -> + fixture + .dsl() + .execute( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, 'Unqualified', '{}'::JSONB)", + fixture.creation().sourceGameTenantKey())); + + assertThatThrownBy( + () -> + fixture + .tx() + .execute( + ignored -> + new TemplateReferenceRepository(fixture.dsl()) + .validateAndEnforce(fixture.target().canonicalTenantId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("TEMPLATE_REFERENCE_INVENTORY_UNQUALIFIED"); + assertThat( + new TemplateReferenceRepository(fixture.dsl()) + .readPhase(fixture.target().canonicalTenantId()) + .orElseThrow() + .phase()) + .isEqualTo(TemplateReferenceRepository.Phase.BACKFILLING); + } + + private DraftCommitBinding createTemplate(Fixture fixture, String name) { + return createTemplate(fixture, name, false); + } + + private DraftCommitBinding createTemplate(Fixture fixture, String name, boolean automaticPhase) { + var config = + new TemplateConfigSource.Config( + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + fixture.target().canonicalVersionId() + + "\",\"world\":{\"regions\":[],\"rooms\":[]}," + + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]}," + + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}}," + + "\"supportedSettings\":[]}"); + UUID revisionId = UUID.randomUUID(); + DraftCommitBinding binding = + DraftCommitBinding.create( + fixture.target(), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + revisionId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.createPayload(name, config))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.SCOPE, + fixture.target().canonicalVersionId().toString(), + TemplateConfigSource.SCOPE, + TemplateConfigSource.SCOPE_ID, + "0"))); + fixture + .tx() + .executeWithoutResult( + ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(fixture.dsl()); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + GameDesignSourceRepository sources = new GameDesignSourceRepository(fixture.dsl()); + var applied = sources.apply(binding); + if (automaticPhase) { + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .advanceSourceVisibility( + fixture.dsl(), binding, List.of(applied.ownerOutcome())); + } else { + // These primitive-level cases deliberately leave promotion to the explicit + // validator. + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .advanceIsolatedVisibility( + fixture.dsl(), binding, List.of(applied.ownerOutcome())); + sources.captureSynchronized(binding); + } + coordinator.releaseApplicationSlot(binding); + }); + return binding; + } + + private Fixture fixture() { + String schema = "template_reference_phase_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate tx = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + UUID requestId = UUID.randomUUID(); + String tenantKey = UUID.randomUUID().toString(); + FreshTenantCreationEvidence creation = + Objects.requireNonNull( + tx.execute( + ignored -> + new GameTenantCreationRepository(dsl, new GameRepository(dsl)) + .createCandidate( + "template-phase-test", + requestId, + tenantKey, + "Template reference phase fixture", + null))); + Version version = new Version(); + version.setTenantId(tenantKey); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + Version savedVersion = + Objects.requireNonNull(tx.execute(ignored -> new VersionRepository(dsl).save(version))); + DraftCommitBinding.TargetProof target = + new DraftCommitBinding.TargetProof( + savedVersion.getCanonicalTenantId(), + savedVersion.getCanonicalVersionId(), + savedVersion.getId(), + savedVersion.getTenantId(), + savedVersion.getIdentitySourceGameRowId(), + savedVersion.getIdentitySourceGameTenantKey(), + savedVersion.getIdentitySourceProvenanceKind()); + return new Fixture(dsl, tx, creation, target); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate tx, + FreshTenantCreationEvidence creation, + DraftCommitBinding.TargetProof target) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 87bc78ddca..f8e344ffa6 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.catchThrowable; import io.grpc.BindableService; +import io.grpc.Context; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; @@ -13,15 +14,19 @@ import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.stub.StreamObserver; +import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyStore; +import java.time.Instant; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Base64; import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -30,14 +35,24 @@ import net.firedevops.firemud.account.v1.AccountPublicationAuthorizationReadServiceGrpc; import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationRequest; import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; @@ -54,6 +69,7 @@ import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; import net.firedevops.firemud.common.temporal.FiremudWorkflowIds; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; @@ -85,13 +101,18 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadGrpcService; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadService; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationCommandService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation; +import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; +import net.firedevops.firemud.gamedesign.publication.TemplateReferenceRepository; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; @@ -131,6 +152,7 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; /** PostgreSQL proof for full-version publication transactions and failure retention. */ @Testcontainers(disabledWithoutDocker = true) @@ -152,6 +174,7 @@ class PublishAttemptServiceTransactionIntegrationTest { private static final String NAMESPACE = "test"; private static final String TENANT_ID = "9001"; private static final String WORKFLOW_ID = "full-version-transaction-integration-test"; + private static final JsonMapper START_SESSION_JSON = JsonMapper.builder().build(); @Container static PostgreSQLContainer postgres = @@ -170,6 +193,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; @Autowired private VersionAssetArtifactRepository versionAssetArtifactRepository; @Autowired private VersionRepository versionRepository; + @Autowired private PublishedReleaseBundleService publishedReleaseBundleService; @Autowired private VersionTemplateRemapSetRepository templateRemapSetRepository; @Autowired private DSLContext dsl; @Autowired private PlatformTransactionManager transactionManager; @@ -573,18 +597,25 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth } /** - * Exercises the real GD admission, owner reservation, and finalizer. The Account HELD response, - * World freeze/selector/source read, original Draft outcomes, participant digests, and empty - * export are stipulated test fixtures; this is not genuine upstream producer proof. + * Exercises the real GD tenant creation, source/coordinator, selected publication, capture, + * immutable association, release, and receiver storage joins. Account authorization/projection, + * World freeze/selector/source intake, Draft owner outcomes, participant digests, and selected + * export candidate remain stipulated test fixtures; this is not whole-chain transport proof. */ @Test void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Release( @TempDir Path temporary) throws Exception { String tenantId = "9010"; - Game game = new Game(); - game.setTenantId(tenantId); - game.setName("selected-command-composition-proof-game"); - gameRepository.save(game); + FreshTenantCreationEvidence creation = + inOwnerTransaction( + () -> + new GameTenantCreationRepository(dsl, gameRepository) + .createCandidate( + NAMESPACE, + UUID.randomUUID(), + tenantId, + "selected-command-composition-proof-game", + null)); Version candidate = new Version(); candidate.setTenantId(tenantId); @@ -592,8 +623,28 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele candidate.setVersionState(VersionLifecycleState.DRAFT); candidate.setVersionStateEpoch(1L); candidate.setNotes("selected command composition proof"); - candidate = versionRepository.save(candidate); + Version draftCandidate = candidate; + candidate = inOwnerTransaction(() -> versionRepository.save(draftCandidate)); TargetProof target = targetProof(candidate); + DraftCommitBinding templateCreate = applyTemplateCreate(target); + var phaseAfterCreate = + new TemplateReferenceRepository(dsl).readPhase(target.canonicalTenantId()).orElseThrow(); + assertThat(phaseAfterCreate.phase()).isEqualTo(TemplateReferenceRepository.Phase.ENFORCED); + assertThat(phaseAfterCreate.inventoryTemplateCount()).isEqualTo(1L); + assertThat(phaseAfterCreate.creationOperationId()).isEqualTo(creation.operationId()); + var configuredTemplateRow = + Objects.requireNonNull( + dsl.fetchOne("SELECT id FROM game_templates WHERE tenant_id = ?", tenantId), + "Configured template row is missing"); + Long configuredTemplateId = + Objects.requireNonNull( + configuredTemplateRow.get("id", Long.class), "Configured template row has no id"); + assertThat( + new TemplateReferenceRepository(dsl) + .readExactBaseReference(target.canonicalTenantId(), configuredTemplateId) + .orElseThrow() + .sourceCommitId()) + .isEqualTo(templateCreate.commitId()); long candidateEpoch = candidate.getVersionStateEpoch(); var prepared = inOwnerTransaction( @@ -673,7 +724,24 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), Mockito.eq(workflowId))) .thenReturn(participantDigests); - Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(immutableEmptyManifest()); + var selectedManifest = immutableEmptyManifest(); + var selectedCandidate = + new VersionAssetExportCandidateService.CandidateBinding( + expectedDigestBinding.requestDigest(), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64), + net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory.SCHEMA, + "sha256:" + "d".repeat(64), + selectedManifest, + expectedDigestBinding.canonicalPreimage(), + "stipulated selected inventory".getBytes(StandardCharsets.UTF_8), + "stipulated empty manifest".getBytes(StandardCharsets.UTF_8)); + var selectedExport = + new AssetExportService.SelectedExportResult(selectedManifest, selectedCandidate); + Mockito.when( + assetExportService.exportSelectedAssets( + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)))) + .thenReturn(selectedExport); var pki = new SelectionReadTestPki(Files.createDirectories(temporary.resolve("pki"))); var publicationReadIdentities = pki.publicationReadIdentities(); @@ -802,6 +870,13 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) Mockito.any(VersionDto.class), Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), Mockito.eq(workflowId)); + Mockito.verify(assetExportService) + .exportSelectedAssets( + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding))); + Mockito.verify(assetExportService) + .requireSelectedCandidateForFinalization( + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), + Mockito.same(selectedExport)); assertThat(versionCountForTenant(tenantId)).isEqualTo(versionCountBeforePublish); assertThat(accountEndpoint.readCount()).isEqualTo(3); assertThat(worldEndpoint.readCount()).isEqualTo(2); @@ -847,6 +922,151 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) assertThat(retainedOperation.terminalEvidenceBytes()).isNotEmpty(); publishAttemptRepository.requirePublishedOperation(attempt); + var startSessionTuple = startSessionTuple(target.canonicalTenantId(), configuredTemplateId); + UUID gameSessionAttemptId = UUID.randomUUID(); + long gameSessionFence = 12L; + var accountProjectionClient = + Mockito.mock(StartSessionRedeemedOperationProjectionClient.class); + Mockito.when( + accountProjectionClient.read( + Mockito.any(StartSessionPostAuthorizationExecutionTuple.class), + Mockito.eq(gameSessionAttemptId), + Mockito.eq(gameSessionFence))) + .thenAnswer( + invocation -> + startSessionAccountProjection( + invocation.getArgument(0), gameSessionAttemptId, gameSessionFence)); + var associationReadService = + new StartSessionTemplateAssociationReadService( + dsl, + transactionManager, + NAMESPACE, + accountProjectionClient, + publishedReleaseBundleService); + var initialReadRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + startSessionTuple.canonicalBytes(), + gameSessionAttemptId, + gameSessionFence, + new StartSessionTemplateAssociationReadEvidence.InitialConfigured()); + List receiverStorageBefore = + startSessionAssociationStorageCounts(target.canonicalTenantId()); + var initialAssociationResult = + withGameSessionPeer(() -> associationReadService.read(initialReadRequest)); + assertThat(initialAssociationResult.association().canonicalTenantId()) + .isEqualTo(target.canonicalTenantId()); + assertThat(initialAssociationResult.association().templateId()) + .isEqualTo(configuredTemplateId); + assertThat(initialAssociationResult.association().canonicalVersionId()) + .isEqualTo(target.canonicalVersionId()); + assertThat(initialAssociationResult.association().selectedCommitId()) + .isEqualTo(selection.selectedCommit().commitId()); + assertThat(initialAssociationResult.association().publishWorkflowId()) + .isEqualTo(workflowId); + assertThat(initialAssociationResult.phaseEpoch()).isEqualTo(phaseAfterCreate.phaseEpoch()); + var initialWireResponse = + StartSessionTemplateAssociationReadGrpcCodec.toResponse(initialAssociationResult); + assertThat( + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + initialReadRequest, initialWireResponse)) + .isEqualTo(initialAssociationResult); + + var exactReplayRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + startSessionTuple.canonicalBytes(), + gameSessionAttemptId, + gameSessionFence, + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + initialAssociationResult.association().canonicalVersionId(), + initialAssociationResult.association().selectedCommitId(), + initialAssociationResult.association().publishWorkflowId(), + initialAssociationResult.association().associationDigest())); + var exactReplayResult = + withGameSessionPeer(() -> associationReadService.read(exactReplayRequest)); + assertThat(exactReplayResult.association()) + .isEqualTo(initialAssociationResult.association()); + assertThat(exactReplayResult.releaseBundle()) + .isEqualTo(initialAssociationResult.releaseBundle()); + assertThat(exactReplayResult.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly( + initialAssociationResult.worldPublishedStartLocationEvidence().canonicalBytes()); + var replayWireResponse = + StartSessionTemplateAssociationReadGrpcCodec.toResponse(exactReplayResult); + assertThat( + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + exactReplayRequest, replayWireResponse)) + .isEqualTo(exactReplayResult); + assertThatThrownBy( + () -> + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + exactReplayRequest, + replayWireResponse.toBuilder() + .setAssociation( + replayWireResponse.getAssociation().toBuilder() + .setAssociationDigest("sha256:" + "f".repeat(64)) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + exactReplayRequest, + replayWireResponse.toBuilder() + .setReleaseBundle( + replayWireResponse.getReleaseBundle().toBuilder() + .setPublishWorkflowId("changed-workflow") + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + exactReplayRequest, + replayWireResponse.toBuilder() + .setAssociation( + replayWireResponse.getAssociation().toBuilder() + .setWorldSlug("changed-world") + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + exactReplayRequest, + replayWireResponse.toBuilder().setReferencePhaseEpoch(0L).build())) + .isInstanceOf(IllegalArgumentException.class); + var changedReplayRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + startSessionTuple.canonicalBytes(), + gameSessionAttemptId, + gameSessionFence, + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + exactReplayResult.association().canonicalVersionId(), + exactReplayResult.association().selectedCommitId(), + exactReplayResult.association().publishWorkflowId(), + "sha256:" + "f".repeat(64))); + assertThatThrownBy( + () -> withGameSessionPeer(() -> associationReadService.read(changedReplayRequest))) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(startSessionAssociationStorageCounts(target.canonicalTenantId())) + .isEqualTo(receiverStorageBefore); + Mockito.verify(accountProjectionClient, Mockito.times(3)) + .read( + Mockito.any(StartSessionPostAuthorizationExecutionTuple.class), + Mockito.eq(gameSessionAttemptId), + Mockito.eq(gameSessionFence)); + assertTerminalOwnerReadOverMtls(operation, Outcome.PUBLISHED, pki); byte[] terminalBeforeChangedRetry = retainedOperation.terminalEvidenceBytes(); long attemptIdBeforeRetry = attempt.getId(); @@ -2444,6 +2664,223 @@ private static TargetProof targetProof(Version version) { version.getIdentitySourceProvenanceKind()); } + private static StartSessionPostAuthorizationExecutionTuple startSessionTuple( + UUID canonicalTenantId, long templateId) { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "start-session-receiver-" + UUID.randomUUID(), + UUID.randomUUID(), + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(canonicalTenantId, NAMESPACE), + new StartSessionOperatorAction.Target(templateId, UUID.randomUUID()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "bounded PostgreSQL receiver proof")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + UUID.randomUUID(), + 19L, + startSessionAuthorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] startSessionAuthorityBundle( + StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = tuple.action().scope().tenantId().toString(); + String actor = tuple.actor().accountId().toString(); + String now = Instant.now().toString(); + String expires = Instant.now().plusSeconds(300).toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenant, "targetNamespace", NAMESPACE), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actor, + "applicableTenantId", + tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + now, + "expiresAt", + expires), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", UUID.randomUUID().toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actor, + "controlUiTokenJti", + UUID.randomUUID().toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(START_SESSION_JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException( + "Unable to create stipulated Account tuple evidence", invalid); + } + } + + private static ReadRedeemedOperationProjectionResponse startSessionAccountProjection( + StartSessionPostAuthorizationExecutionTuple tuple, UUID attemptId, long ownerFence) { + return ReadRedeemedOperationProjectionResponse.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setCanonicalPreAuthorizationTupleBytes( + com.google.protobuf.ByteString.copyFrom( + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setMutationDigest(tuple.preAuthorizationTuple().mutationDigest()) + .setOwnerAttemptId(attemptId.toString()) + .setOwnerFence(ownerFence) + .setAuthenticatedRedeemerWorkloadIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service") + .build(); + } + + private T withGameSessionPeer(java.util.function.Supplier action) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service", + NAMESPACE, + "game-session-service"); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private List startSessionAssociationStorageCounts(UUID canonicalTenantId) { + return List.of( + dsl.fetchSingle( + "SELECT COUNT(*) FROM game_template_version_ref WHERE canonical_tenant_id = ?", + canonicalTenantId) + .get(0, Long.class), + dsl.fetchSingle( + "SELECT COUNT(*) FROM game_design_template_config_source_capture WHERE canonical_tenant_id = ?", + canonicalTenantId) + .get(0, Long.class), + dsl.fetchSingle( + "SELECT COUNT(*) FROM game_design_selected_template_world_source_association WHERE canonical_tenant_id = ?", + canonicalTenantId) + .get(0, Long.class), + dsl.fetchSingle( + "SELECT COUNT(*) FROM published_release_bundle WHERE tenant_id = ?", + tenantKeyFor(canonicalTenantId)) + .get(0, Long.class), + dsl.fetchSingle( + "SELECT COUNT(*) FROM game_template_reference_phase WHERE canonical_tenant_id = ?", + canonicalTenantId) + .get(0, Long.class)); + } + + private String tenantKeyFor(UUID canonicalTenantId) { + return dsl.fetchSingle( + "SELECT tenant_id FROM game WHERE canonical_tenant_id = ?", canonicalTenantId) + .get(0, String.class); + } + + /** + * Applies an owner-authorized fresh TemplateConfig CREATE through the real source coordinator. + */ + private DraftCommitBinding applyTemplateCreate(TargetProof target) { + var config = + new TemplateConfigSource.Config( + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + target.canonicalVersionId() + + "\",\"world\":{\"regions\":[],\"rooms\":[]}," + + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]}," + + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}}," + + "\"supportedSettings\":[]}"); + UUID revisionId = UUID.randomUUID(); + DraftCommitBinding binding = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "template-genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + revisionId, + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.createPayload("Starter", config))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.SCOPE, + target.canonicalVersionId().toString(), + TemplateConfigSource.SCOPE, + TemplateConfigSource.SCOPE_ID, + "0"))); + return inOwnerTransaction( + () -> { + var coordinator = new DraftCommitCoordinatorRepository(dsl); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = new GameDesignSourceRepository(dsl).apply(binding); + IsolatedPublicationOwnerSetup.advanceSourceVisibility( + dsl, binding, List.of(applied.ownerOutcome())); + coordinator.releaseApplicationSlot(binding); + return binding; + }); + } + private T inOwnerTransaction(java.util.function.Supplier action) { TransactionTemplate transaction = new TransactionTemplate(transactionManager); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java new file mode 100644 index 0000000000..ecf084229a --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java @@ -0,0 +1,833 @@ +package integration.net.firedevops.firemud.gamedesign.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.AssetSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService.CandidateBinding; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** + * PostgreSQL proof of V65 candidate persistence and SQL owner/finalization boundaries. The exact + * authenticated Account/World operation and complete selected source capture are stipulated fixture + * inputs here; this test is not a composed-authorship or whole-release proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class SelectedAssetExportCandidatePostgresIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final String CONFLICT = "SELECTED_ASSET_EXPORT_CANDIDATE_CONFLICT"; + private static final byte[] ASSET_BYTES = + "retained ordinary source bytes".getBytes(StandardCharsets.UTF_8); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void commitsCandidateBeforeIndependentExactReadbackAndExactRetryIsIdempotent() { + Fixture fixture = fixture(VersionLifecycleState.DRAFT); + CandidateCase candidate = candidateCase(fixture, null, "source-a", ASSET_BYTES, null); + + fixture + .candidates() + .recordSelectedCandidate( + candidate.inventory(), candidate.manifest(), candidate.manifestBytes()); + CandidateBinding independentlyRead = + fixture.candidates().readSelectedCandidate(candidate.request()); + + assertThat(independentlyRead).isEqualTo(candidate.expectedBinding()); + assertThat(storedBytes(fixture, "inventory_bytes")).containsExactly(candidate.inventoryBytes()); + assertThat(storedBytes(fixture, "manifest_bytes")).containsExactly(candidate.manifestBytes()); + + fixture + .candidates() + .recordSelectedCandidate( + candidate.inventory(), candidate.manifest(), candidate.manifestBytes()); + + assertThat(fixture.candidates().readSelectedCandidate(candidate.request())) + .isEqualTo(candidate.expectedBinding()); + assertThat(candidateCount(fixture)).isOne(); + } + + @Test + void changedSourceManifestOrRequestIsDeniedWithoutRewritingRetainedCandidate() { + Fixture fixture = fixture(VersionLifecycleState.DRAFT); + CandidateCase original = candidateCase(fixture, null, "source-a", ASSET_BYTES, null); + fixture + .candidates() + .recordSelectedCandidate( + original.inventory(), original.manifest(), original.manifestBytes()); + byte[] retainedInventory = storedBytes(fixture, "inventory_bytes"); + byte[] retainedManifest = storedBytes(fixture, "manifest_bytes"); + + CandidateCase changedSource = + candidateCase( + fixture, + original.request(), + "source-b", + "changed retained bytes".getBytes(StandardCharsets.UTF_8), + null); + CandidateCase changedManifest = + candidateCase(fixture, original.request(), "source-a", ASSET_BYTES, "changed-manifest"); + CandidateCase changedRequest = + candidateCaseWithRequest( + fixture, + PublicationDigestRequestBinding.full( + original.request().tenantId(), + original.request().versionId(), + "different-publish-request"), + "source-a", + ASSET_BYTES, + null); + + assertConflict( + () -> + fixture + .candidates() + .recordSelectedCandidate( + changedSource.inventory(), + changedSource.manifest(), + changedSource.manifestBytes())); + assertConflict( + () -> + fixture + .candidates() + .recordSelectedCandidate( + changedManifest.inventory(), + changedManifest.manifest(), + changedManifest.manifestBytes())); + assertConflict( + () -> + fixture + .candidates() + .recordSelectedCandidate( + changedRequest.inventory(), + changedRequest.manifest(), + changedRequest.manifestBytes())); + + assertThat(candidateCount(fixture)).isOne(); + assertThat(storedBytes(fixture, "inventory_bytes")).containsExactly(retainedInventory); + assertThat(storedBytes(fixture, "manifest_bytes")).containsExactly(retainedManifest); + assertThat(fixture.candidates().readSelectedCandidate(original.request())) + .isEqualTo(original.expectedBinding()); + } + + @Test + void missingCandidateAndMismatchedOwnerOrNonDraftStateAreDenied() { + Fixture missing = fixture(VersionLifecycleState.DRAFT); + CandidateCase valid = candidateCase(missing, null, "source-a", ASSET_BYTES, null); + assertThatThrownBy(() -> missing.candidates().readSelectedCandidate(valid.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_ASSET_EXPORT_CANDIDATE_NOT_FOUND"); + + TargetProof wrongCanonicalVersion = + new TargetProof( + valid.target().canonicalTenantId(), + UUID.randomUUID(), + valid.target().gameDesignVersionRowId(), + valid.target().gameDesignVersionTenantKey(), + valid.target().sourceGameRowId(), + valid.target().sourceGameTenantKey(), + valid.target().sourceProvenanceKind()); + CandidateCase mismatched = + candidateCase( + missing, valid.request(), "source-a", ASSET_BYTES, null, wrongCanonicalVersion); + assertConflict( + () -> + missing + .candidates() + .recordSelectedCandidate( + mismatched.inventory(), mismatched.manifest(), mismatched.manifestBytes())); + assertThat(candidateCount(missing)).isZero(); + + PublicationDigestRequestBinding missingVersionRequest = + PublicationDigestRequestBinding.full( + valid.request().tenantId(), "999999", "candidate-missing-version"); + TargetProof missingVersionTarget = + new TargetProof( + valid.target().canonicalTenantId(), + UUID.randomUUID(), + 999999, + valid.target().gameDesignVersionTenantKey(), + valid.target().sourceGameRowId(), + valid.target().sourceGameTenantKey(), + valid.target().sourceProvenanceKind()); + CandidateCase missingVersion = + candidateCase( + missing, missingVersionRequest, "source-a", ASSET_BYTES, null, missingVersionTarget); + assertConflict( + () -> + missing + .candidates() + .recordSelectedCandidate( + missingVersion.inventory(), + missingVersion.manifest(), + missingVersion.manifestBytes())); + assertThat(candidateCount(missing)).isZero(); + + Fixture failedOwner = fixture(VersionLifecycleState.FAILED); + CandidateCase failed = candidateCase(failedOwner, null, "source-a", ASSET_BYTES, null); + assertConflict( + () -> + failedOwner + .candidates() + .recordSelectedCandidate( + failed.inventory(), failed.manifest(), failed.manifestBytes())); + assertThat(candidateCount(failedOwner)).isZero(); + } + + @Test + void v65OwnerTriggerRejectsWrongEpochOrCanonicalVersionAndRowsCannotBeMutated() { + Fixture fixture = fixture(VersionLifecycleState.DRAFT); + CandidateCase candidate = candidateCase(fixture, null, "source-a", ASSET_BYTES, null); + + assertThatThrownBy( + () -> + insertCandidateDirectly( + fixture, candidate, 2L, candidate.target().canonicalVersionId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("SELECTED_ASSET_EXPORT_CANDIDATE_SCOPE_CONFLICT"); + assertThatThrownBy(() -> insertCandidateDirectly(fixture, candidate, 1L, UUID.randomUUID())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("SELECTED_ASSET_EXPORT_CANDIDATE_SCOPE_CONFLICT"); + assertThat(candidateCount(fixture)).isZero(); + + Fixture failedOwner = fixture(VersionLifecycleState.FAILED); + CandidateCase failedCandidate = candidateCase(failedOwner, null, "source-a", ASSET_BYTES, null); + assertThatThrownBy( + () -> + insertCandidateDirectly( + failedOwner, + failedCandidate, + 1L, + failedCandidate.target().canonicalVersionId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("SELECTED_ASSET_EXPORT_CANDIDATE_SCOPE_CONFLICT"); + assertThat(candidateCount(failedOwner)).isZero(); + + fixture + .candidates() + .recordSelectedCandidate( + candidate.inventory(), candidate.manifest(), candidate.manifestBytes()); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE version_asset_export_candidate SET manifest_hash = ? WHERE tenant_id = ? AND version_id = ?", + "sha256:" + "f".repeat(64), + fixture.owner().getTenantId(), + fixture.version().getId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("SELECTED_ASSET_EXPORT_CANDIDATE_IMMUTABLE"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM version_asset_export_candidate WHERE tenant_id = ? AND version_id = ?", + fixture.owner().getTenantId(), + fixture.version().getId())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("SELECTED_ASSET_EXPORT_CANDIDATE_IMMUTABLE"); + assertThatThrownBy(() -> fixture.dsl().execute("TRUNCATE version_asset_export_candidate")) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("SELECTED_ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED"); + assertThat(candidateCount(fixture)).isOne(); + } + + @Test + void finalizationComparisonUsesExactCandidateInCallerWritableReadCommittedTransaction() { + Fixture fixture = fixture(VersionLifecycleState.DRAFT); + CandidateCase candidate = candidateCase(fixture, null, "source-a", ASSET_BYTES, null); + fixture + .candidates() + .recordSelectedCandidate( + candidate.inventory(), candidate.manifest(), candidate.manifestBytes()); + + assertThatThrownBy( + () -> + fixture + .candidates() + .requireSelectedCandidateForFinalization( + candidate.request(), candidate.expectedBinding())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("caller-owned writable READ_COMMITTED transaction"); + + TransactionTemplate readOnly = + transaction(fixture, true, TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThatThrownBy( + () -> + readOnly.executeWithoutResult( + ignored -> + fixture + .candidates() + .requireSelectedCandidateForFinalization( + candidate.request(), candidate.expectedBinding()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("caller-owned writable READ_COMMITTED transaction"); + TransactionTemplate repeatableRead = + transaction(fixture, false, TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + repeatableRead.executeWithoutResult( + ignored -> + fixture + .candidates() + .requireSelectedCandidateForFinalization( + candidate.request(), candidate.expectedBinding()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("caller-owned writable READ_COMMITTED transaction"); + + CandidateBinding altered = + new CandidateBinding( + candidate.expectedBinding().requestDigest(), + candidate.expectedBinding().operationDigest(), + candidate.expectedBinding().selectedCommitDigest(), + candidate.expectedBinding().inventorySchema(), + candidate.expectedBinding().inventoryDigest(), + candidate.expectedBinding().manifest(), + candidate.expectedBinding().requestPreimage(), + "altered-inventory".getBytes(StandardCharsets.UTF_8), + candidate.expectedBinding().manifestBytes()); + assertThatThrownBy( + () -> + transaction(fixture, false, TransactionDefinition.ISOLATION_READ_COMMITTED) + .executeWithoutResult( + ignored -> + fixture + .candidates() + .requireSelectedCandidateForFinalization( + candidate.request(), altered))) + .isInstanceOf(IllegalStateException.class) + .hasMessage(CONFLICT); + assertThatThrownBy( + () -> + transaction(fixture, false, TransactionDefinition.ISOLATION_READ_COMMITTED) + .executeWithoutResult( + ignored -> + fixture + .candidates() + .requireSelectedCandidateForFinalization( + PublicationDigestRequestBinding.full( + candidate.request().tenantId(), + candidate.request().versionId(), + "changed-finalization-request"), + candidate.expectedBinding()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage(CONFLICT); + + transaction(fixture, false, TransactionDefinition.ISOLATION_READ_COMMITTED) + .executeWithoutResult( + ignored -> { + assertThat(fixture.games().findByTenantIdForUpdate(fixture.owner().getTenantId())) + .isNotNull(); + var beforeRow = + Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT txid_current()::text"), + "transaction ID query must return a row"); + String before = + Objects.requireNonNull( + beforeRow.get(0, String.class), "transaction ID query must return a value"); + fixture + .candidates() + .requireSelectedCandidateForFinalization( + candidate.request(), candidate.expectedBinding()); + var afterRow = + Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT txid_current()::text"), + "transaction ID query must return a row"); + String after = + Objects.requireNonNull( + afterRow.get(0, String.class), "transaction ID query must return a value"); + assertThat(after).isEqualTo(before); + }); + } + + @Test + void concurrentExactCandidateWritersConvergeOnOneCommittedReadback() throws Exception { + Fixture fixture = fixture(VersionLifecycleState.DRAFT); + CandidateCase candidate = candidateCase(fixture, null, "source-a", ASSET_BYTES, null); + ExecutorService writers = Executors.newFixedThreadPool(2); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + try { + var first = + writers.submit( + () -> { + ready.countDown(); + start.await(); + fixture + .candidates() + .recordSelectedCandidate( + candidate.inventory(), candidate.manifest(), candidate.manifestBytes()); + return null; + }); + var second = + writers.submit( + () -> { + ready.countDown(); + start.await(); + fixture + .candidates() + .recordSelectedCandidate( + candidate.inventory(), candidate.manifest(), candidate.manifestBytes()); + return null; + }); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + first.get(20, TimeUnit.SECONDS); + second.get(20, TimeUnit.SECONDS); + } finally { + writers.shutdownNow(); + } + + assertThat(candidateCount(fixture)).isOne(); + assertThat(fixture.candidates().readSelectedCandidate(candidate.request())) + .isEqualTo(candidate.expectedBinding()); + } + + private static Fixture fixture(VersionLifecycleState state) { + String schema = "asset_candidate_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource admin = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + DSL.using(admin, SQLDialect.POSTGRES).execute("CREATE SCHEMA " + schema); + DriverManagerDataSource dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl() + "?currentSchema=" + schema, + POSTGRES.getUsername(), + POSTGRES.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate ownerWrite = transactionManagerTemplate(transactionManager); + GameRepository games = new GameRepository(dsl); + VersionRepository versions = new VersionRepository(dsl); + Game game = + ownerWrite.execute( + ignored -> { + Game value = new Game(); + value.setTenantId(UUID.randomUUID().toString()); + value.setName("Selected asset candidate owner fixture"); + value.setDescription("Persisted Game owner for V65 candidate SQL proof"); + return games.save(value); + }); + Version version = + ownerWrite.execute( + ignored -> { + Version value = new Version(); + value.setTenantId(game.getTenantId()); + value.setVersionNumber(1); + value.setVersionState(state); + value.setVersionStateEpoch(1L); + value.setNotes("Persisted Version owner for V65 candidate SQL proof"); + return versions.save(value); + }); + var candidates = + new VersionAssetExportCandidateServiceImpl( + dsl, games, versions, transactionManager, new ObjectMapper()); + return new Fixture( + schema, dataSource, dsl, transactionManager, games, versions, game, version, candidates); + } + + private static TransactionTemplate transaction(Fixture fixture, boolean readOnly, int isolation) { + TransactionTemplate template = new TransactionTemplate(fixture.transactionManager()); + template.setIsolationLevel(isolation); + template.setReadOnly(readOnly); + return template; + } + + private static TransactionTemplate transactionManagerTemplate( + DataSourceTransactionManager manager) { + TransactionTemplate template = new TransactionTemplate(manager); + template.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return template; + } + + private static CandidateCase candidateCase( + Fixture fixture, + PublicationDigestRequestBinding request, + String sourceMarker, + byte[] assetBytes, + String manifestMarker) { + return candidateCase( + fixture, request, sourceMarker, assetBytes, manifestMarker, target(fixture)); + } + + private static CandidateCase candidateCase( + Fixture fixture, + PublicationDigestRequestBinding request, + String sourceMarker, + byte[] assetBytes, + String manifestMarker, + TargetProof target) { + if (request == null) { + request = + PublicationDigestRequestBinding.full( + fixture.owner().getCanonicalTenantId().toString(), + Long.toString(fixture.version().getId()), + "candidate-request-" + UUID.randomUUID()); + } + String contentDigest = sha256(assetBytes); + UUID sourceRevisionId = stableUuid(target, "source-revision:" + sourceMarker); + UUID sourceRequestId = stableUuid(target, "source-request:" + sourceMarker); + UUID sourceCommitId = stableUuid(target, "source-commit:" + sourceMarker); + DraftCommitBinding sourceBinding = + DraftCommitBinding.create( + target, + sourceRequestId, + sourceCommitId, + "genesis", + List.of( + new RevisionPayload("0", sourceRevisionId, Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "ASSET_REFERENCE", + target.canonicalVersionId().toString(), + "VERSION", + target.canonicalVersionId().toString(), + "0"))); + UUID assetRevisionId = stableUuid(target, "asset-revision:" + sourceMarker); + SelectedDraftAssetInventory.Asset asset = + new SelectedDraftAssetInventory.Asset( + SelectedDraftAssetInventory.Family.ORDINARY, + AssetSource.ROLE, + "resource.bin", + "1", + "REQUIRED", + sourceBinding, + "0", + assetRevisionId, + "application/octet-stream", + contentDigest, + assetBytes); + String commitDigest = sourceBinding.digest(); + var operationBytes = + ("stipulated-operation:" + request.derivedWorkflowIdentity()) + .getBytes(StandardCharsets.UTF_8); + UUID actorId = stableUuid(target, "stipulated-actor"); + AuthoredDraftPublishSelectionBinding.PublishIntent intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + request.publishRequestId(), + "1", + "stipulated authenticated intent", + sourceRequestId, + sourceBinding.commitId(), + commitDigest); + AuthoredDraftPublishSelectionBinding selection = + AuthoredDraftPublishSelectionBinding.capture( + intent, + target, + sourceBinding, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + sourceRequestId, + sourceBinding.commitId(), + commitDigest, + "[]", + OffsetDateTime.parse("2026-10-09T00:00:00Z"))); + AccountPublicationAuthorizationBinding account = + new AccountPublicationAuthorizationBinding( + stableUuid(target, "stipulated-account-operation"), + stableUuid(target, "stipulated-account-fence"), + new AccountPublicationAuthorizationBinding.PreallocationInput(actorId, selection), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, actorId.toString(), "1", "1", null, null, new byte[] {1}))); + GameDesignPublicationOperation operation = mock(GameDesignPublicationOperation.class); + when(operation.account()).thenReturn(account); + when(operation.workflowId()).thenReturn(request.derivedWorkflowIdentity()); + when(operation.canonicalBytes()).thenReturn(operationBytes); + + byte[] inventoryBytes = + canonicalJson( + Map.ofEntries( + Map.entry("schema", SelectedDraftAssetInventory.SCHEMA), + Map.entry( + "requestPreimageBase64", + Base64.getEncoder().encodeToString(request.canonicalPreimage())), + Map.entry("requestDigest", request.requestDigest()), + Map.entry("operationBase64", Base64.getEncoder().encodeToString(operationBytes)), + Map.entry("selectedCommitDigest", commitDigest), + Map.entry("sourceCapture", Map.of("stipulatedFixtureMarker", sourceMarker)), + Map.entry("assets", List.of(assetObject(asset))))); + String inventoryDigest = sha256(inventoryBytes); + List digests = + List.of( + new PublishedArtifactDigest( + asset.usageKey(), + "BINARY", + "artifacts/sha256/" + contentDigest.substring("sha256:".length()), + contentDigest, + asset.contentType(), + 1)); + Map manifestObject = + new java.util.LinkedHashMap<>( + Map.ofEntries( + Map.entry("schema", "game-design-selected-asset-manifest/v1"), + Map.entry("manifestSchemaVersion", 1), + Map.entry("selectedInventorySchema", SelectedDraftAssetInventory.SCHEMA), + Map.entry("selectedInventoryDigest", inventoryDigest), + Map.entry("artifacts", List.of(artifactObject(asset, digests.getFirst()))))); + if (manifestMarker != null) { + manifestObject.put("fixtureExtension", manifestMarker); + } + byte[] manifestBytes = canonicalJson(manifestObject); + ExportedAssetManifest manifest = + new ExportedAssetManifest( + sha256(manifestBytes), + 1, + digests.stream().map(PublishedArtifactDigest::usageKey).toList(), + digests); + SelectedDraftAssetInventory inventory = mock(SelectedDraftAssetInventory.class); + when(inventory.request()).thenReturn(request); + when(inventory.operation()).thenReturn(operation); + when(inventory.selectedCommit()).thenReturn(sourceBinding); + when(inventory.assets()).thenReturn(List.of(asset)); + when(inventory.digest()).thenReturn(inventoryDigest); + when(inventory.canonicalBytes()).thenReturn(inventoryBytes.clone()); + CandidateBinding expected = + new CandidateBinding( + request.requestDigest(), + sha256(operationBytes), + commitDigest, + SelectedDraftAssetInventory.SCHEMA, + inventoryDigest, + manifest, + request.canonicalPreimage(), + inventoryBytes, + manifestBytes); + return new CandidateCase( + request, target, inventory, manifest, manifestBytes, inventoryBytes, expected); + } + + private static CandidateCase candidateCaseWithRequest( + Fixture fixture, + PublicationDigestRequestBinding request, + String sourceMarker, + byte[] assetBytes, + String manifestMarker) { + return candidateCase( + fixture, request, sourceMarker, assetBytes, manifestMarker, target(fixture)); + } + + private static TargetProof target(Fixture fixture) { + return new TargetProof( + fixture.owner().getCanonicalTenantId(), + fixture.version().getCanonicalVersionId(), + fixture.version().getId(), + fixture.owner().getTenantId(), + fixture.owner().getId(), + fixture.owner().getTenantId(), + "NEW_GAME_ROW"); + } + + private static UUID stableUuid(TargetProof target, String purpose) { + return UUID.nameUUIDFromBytes( + (target.canonicalVersionId() + ":" + purpose).getBytes(StandardCharsets.UTF_8)); + } + + private static Map assetObject(SelectedDraftAssetInventory.Asset asset) { + return Map.ofEntries( + Map.entry("family", asset.family().name()), + Map.entry("role", asset.role()), + Map.entry("usageKey", asset.usageKey()), + Map.entry("assetRowId", asset.assetRowId()), + Map.entry("requiredness", asset.requiredness()), + Map.entry("sourceBindingJson", asset.sourceBinding().canonicalJson()), + Map.entry("sourceBindingDigest", asset.sourceBinding().digest()), + Map.entry("revisionOrder", asset.revisionOrder()), + Map.entry("revisionId", asset.revisionId().toString()), + Map.entry("contentType", asset.contentType()), + Map.entry("contentDigest", asset.contentDigest()), + Map.entry("byteSize", Long.toString(asset.contentBytes().length)), + Map.entry("contentBase64", Base64.getEncoder().encodeToString(asset.contentBytes()))); + } + + private static Map artifactObject( + SelectedDraftAssetInventory.Asset asset, PublishedArtifactDigest proof) { + return Map.ofEntries( + Map.entry("usageKey", asset.usageKey()), + Map.entry("family", asset.family().name()), + Map.entry("role", asset.role()), + Map.entry("requiredness", asset.requiredness()), + Map.entry("artifactKind", proof.artifactKind()), + Map.entry("objectKey", proof.immutableObjectKey()), + Map.entry("contentDigest", proof.contentDigest()), + Map.entry("contentType", proof.contentType()), + Map.entry("artifactSchemaVersion", proof.artifactSchemaVersion()), + Map.entry("byteSize", asset.contentBytes().length)); + } + + private static void insertCandidateDirectly( + Fixture fixture, CandidateCase candidate, long expectedEpoch, UUID canonicalVersionId) { + fixture + .dsl() + .execute( + "INSERT INTO version_asset_export_candidate (tenant_id, version_id, canonical_tenant_id, canonical_version_id, expected_version_state_epoch, workflow_id, request_digest, request_preimage, operation_digest, selected_commit_digest, inventory_schema, inventory_digest, inventory_bytes, manifest_schema_version, manifest_hash, manifest_bytes, artifact_digests_json, required_usage_keys_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + candidate.target().gameDesignVersionTenantKey(), + candidate.target().gameDesignVersionRowId(), + candidate.target().canonicalTenantId(), + canonicalVersionId, + expectedEpoch, + candidate.request().derivedWorkflowIdentity(), + candidate.request().requestDigest(), + candidate.request().canonicalPreimage(), + candidate.expectedBinding().operationDigest(), + candidate.expectedBinding().selectedCommitDigest(), + candidate.expectedBinding().inventorySchema(), + candidate.expectedBinding().inventoryDigest(), + candidate.expectedBinding().inventoryBytes(), + candidate.manifest().manifestSchemaVersion(), + candidate.manifest().manifestHash(), + candidate.manifestBytes(), + "[]", + "[]"); + } + + private static byte[] storedBytes(Fixture fixture, String column) { + var row = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT " + + column + + " FROM version_asset_export_candidate WHERE tenant_id = ? AND version_id = ?", + fixture.owner().getTenantId(), + fixture.version().getId()), + "candidate bytes query must return a row"); + return Objects.requireNonNull(row.get(0, byte[].class), "candidate bytes query returned null"); + } + + private static long candidateCount(Fixture fixture) { + var row = + Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT count(*) FROM version_asset_export_candidate"), + "candidate count query must return a row"); + return Objects.requireNonNull(row.get(0, Long.class), "candidate count query returned null"); + } + + private static void assertConflict(org.assertj.core.api.ThrowableAssert.ThrowingCallable call) { + assertThatThrownBy(call).isInstanceOf(IllegalStateException.class).hasMessage(CONFLICT); + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(new ObjectMapper().writeValueAsString(value)); + } catch (Exception invalid) { + throw new IllegalStateException( + "Candidate integration fixture did not canonicalize", invalid); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 unavailable", impossible); + } + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager transactionManager, + GameRepository games, + VersionRepository versions, + Game owner, + Version version, + VersionAssetExportCandidateService candidates) {} + + private record CandidateCase( + PublicationDigestRequestBinding request, + TargetProof target, + SelectedDraftAssetInventory inventory, + ExportedAssetManifest manifest, + byte[] manifestBytes, + byte[] inventoryBytes, + CandidateBinding expectedBinding) { + private CandidateCase { + manifestBytes = manifestBytes.clone(); + inventoryBytes = inventoryBytes.clone(); + } + + @Override + public byte[] manifestBytes() { + return manifestBytes.clone(); + } + + @Override + public byte[] inventoryBytes() { + return inventoryBytes.clone(); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcServiceTest.java new file mode 100644 index 0000000000..b12aebbea9 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionTemplateAssociationReadGrpcServiceTest.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +class GameDesignStartSessionTemplateAssociationReadGrpcServiceTest { + private final StartSessionTemplateAssociationReadService owner = + mock(StartSessionTemplateAssociationReadService.class); + private final GameDesignStartSessionTemplateAssociationReadGrpcService service = + new GameDesignStartSessionTemplateAssociationReadGrpcService(owner, "world-runtime"); + + @Test + void authenticatesExactGameSessionPeerBeforeDecodingRequest() { + var observer = new Collector(); + service.readStartSessionTemplateAssociation( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), observer); + assertThat(observer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(owner); + } + + @Test + void rejectsDifferentWorkloadBeforeDecodingRequest() { + var observer = + invokeAs( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), "account-service"); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(owner); + } + + @Test + void exactPeerIsAuthenticatedBeforeMalformedRequestIsRejected() { + var observer = + invokeAs( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), + "game-session-service"); + assertThat(observer.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(owner); + } + + @Test + void completesAfterDeliveringSuccessfulAssociationRead() { + var request = ReadStartSessionTemplateAssociationRequest.getDefaultInstance(); + var decoded = mock(StartSessionTemplateAssociationReadEvidence.Request.class); + var result = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + var response = ReadStartSessionTemplateAssociationResponse.getDefaultInstance(); + Mockito.when(decoded.targetNamespace()).thenReturn("world-runtime"); + + try (MockedStatic codec = + Mockito.mockStatic(StartSessionTemplateAssociationReadGrpcCodec.class)) { + codec + .when(() -> StartSessionTemplateAssociationReadGrpcCodec.fromRequest(request)) + .thenReturn(decoded); + codec + .when(() -> StartSessionTemplateAssociationReadGrpcCodec.toResponse(result)) + .thenReturn(response); + Mockito.when(owner.read(decoded)).thenReturn(result); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isNull(); + assertThat(observer.value).isEqualTo(response); + assertThat(observer.completed).isTrue(); + } + } + + private Collector invokeAs(ReadStartSessionTemplateAssociationRequest request, String workload) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/world-runtime/sa/" + workload, "world-runtime", workload); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + var observer = new Collector(); + service.readStartSessionTemplateAssociation(request, observer); + return observer; + } finally { + context.detach(previous); + } + } + + private static final class Collector + implements StreamObserver { + private ReadStartSessionTemplateAssociationResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadStartSessionTemplateAssociationResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java new file mode 100644 index 0000000000..b403b6aae1 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java @@ -0,0 +1,294 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionTemplateAssociationReadServiceTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID ATTEMPT = UUID.fromString("02222222-2222-4222-8222-222222222222"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final long FENCE = 8L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final DSLContext dsl = mock(DSLContext.class); + private final PublishedReleaseBundleService releases = mock(PublishedReleaseBundleService.class); + + @Test + void independentlyChecksExactAccountAttemptBeforeOpeningAnyLocalSnapshot() { + var tuple = postTuple("account-before-local-snapshot"); + var request = request(tuple); + var accountCalled = new AtomicBoolean(); + PlatformTransactionManager transactions = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + if (!accountCalled.get()) { + throw new AssertionError("Local snapshot opened before Account projection"); + } + throw new IllegalStateException("test stops at the first local transaction boundary"); + } + + @Override + public void commit(TransactionStatus status) { + throw new AssertionError("No transaction should be committed"); + } + + @Override + public void rollback(TransactionStatus status) { + throw new AssertionError("No transaction should be rolled back"); + } + }; + var service = + new StartSessionTemplateAssociationReadService( + dsl, + transactions, + "world-runtime", + (actualTuple, attempt, fence) -> { + accountCalled.set(true); + if (!tuple.controlPlaneRequestId().equals(actualTuple.controlPlaneRequestId()) + || !ATTEMPT.equals(attempt) + || FENCE != fence) { + throw new AssertionError("Changed exact Account projection selector"); + } + return projection(tuple, ATTEMPT, FENCE); + }, + releases); + + assertThatThrownBy(() -> withPeer(service, request, "game-session-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(dsl); + verifyNoInteractions(releases); + } + + @Test + void deniesWrongWorkloadBeforeCallingAccountOrOpeningLocalStorage() { + var tuple = postTuple("wrong-peer"); + var service = + new StartSessionTemplateAssociationReadService( + dsl, + unusedTransactionManager(), + "world-runtime", + (ignored, attempt, fence) -> { + throw new AssertionError("Account must not be called for a different workload"); + }, + releases); + assertThatThrownBy(() -> withPeer(service, request(tuple), "account-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(dsl); + verifyNoInteractions(releases); + } + + @Test + void rejectsMismatchedAccountAttemptFenceBeforeLocalRead() { + var tuple = postTuple("changed-account-fence"); + var service = + new StartSessionTemplateAssociationReadService( + dsl, + unusedTransactionManager(), + "world-runtime", + (actual, attempt, fence) -> projection(actual, attempt, fence + 1L), + releases); + assertThatThrownBy(() -> withPeer(service, request(tuple), "game-session-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(dsl); + verifyNoInteractions(releases); + } + + private static void withPeer( + StartSessionTemplateAssociationReadService service, + StartSessionTemplateAssociationReadEvidence.Request request, + String workload) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/world-runtime/sa/" + workload, "world-runtime", workload); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.read(request); + } finally { + context.detach(previous); + } + } + + private static StartSessionTemplateAssociationReadEvidence.Request request( + StartSessionPostAuthorizationExecutionTuple tuple) { + return new StartSessionTemplateAssociationReadEvidence.Request( + 1, + "world-runtime", + UUID.fromString("01111111-1111-4111-8111-111111111111"), + tuple.canonicalBytes(), + ATTEMPT, + FENCE, + new StartSessionTemplateAssociationReadEvidence.InitialConfigured()); + } + + private static ReadRedeemedOperationProjectionResponse projection( + StartSessionPostAuthorizationExecutionTuple tuple, UUID attempt, long fence) { + return ReadRedeemedOperationProjectionResponse.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setCanonicalPreAuthorizationTupleBytes( + ByteString.copyFrom( + tuple + .preAuthorizationTuple() + .canonicalJson() + .getBytes(java.nio.charset.StandardCharsets.UTF_8))) + .setMutationDigest(tuple.preAuthorizationTuple().mutationDigest()) + .setOwnerAttemptId(attempt.toString()) + .setOwnerFence(fence) + .setAuthenticatedRedeemerWorkloadIdentity( + "spiffe://firemud/ns/world-runtime/sa/game-session-service") + .build(); + } + + private static PlatformTransactionManager unusedTransactionManager() { + return new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + throw new AssertionError("Local storage must not be reached"); + } + + @Override + public void commit(TransactionStatus status) { + throw new AssertionError("No transaction should be committed"); + } + + @Override + public void rollback(TransactionStatus status) { + throw new AssertionError("No transaction should be rolled back"); + } + }; + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple(String requestId) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact StartSession account projection")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportServiceTest.java new file mode 100644 index 0000000000..5befba8be6 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportServiceTest.java @@ -0,0 +1,295 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventoryReadService; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.service.AssetExportService; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService.CandidateBinding; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import tools.jackson.databind.ObjectMapper; + +/** The selected source and durable candidate readbacks must gate every immutable object write. */ +class SelectedAssetExportServiceTest { + private final VersionAssetPublicationRepository legacy = + mock(VersionAssetPublicationRepository.class); + private final S3Client s3 = mock(S3Client.class); + private final SelectedDraftAssetInventoryReadService inventoryReader = + mock(SelectedDraftAssetInventoryReadService.class); + private final VersionAssetExportCandidateService candidateService = + mock(VersionAssetExportCandidateService.class); + private final ObjectMapper mapper = new ObjectMapper(); + private final PublicationDigestRequestBinding request = + PublicationDigestRequestBinding.full( + "11111111-1111-4111-8111-111111111111", "19", "selected-export-request"); + private AssetExportServiceImpl exporter; + private SelectedDraftAssetInventory inventory; + private byte[] inventoryBytes; + private byte[] manifestBytes; + private ExportedAssetManifest manifest; + private CandidateBinding candidate; + + @BeforeEach + void setUp() throws Exception { + byte[] operationBytes = "selected-operation".getBytes(StandardCharsets.UTF_8); + String commitDigest = "sha256:" + "a".repeat(64); + inventoryBytes = + Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString( + Map.ofEntries( + Map.entry("schema", SelectedDraftAssetInventory.SCHEMA), + Map.entry( + "requestPreimageBase64", + Base64.getEncoder().encodeToString(request.canonicalPreimage())), + Map.entry("requestDigest", request.requestDigest()), + Map.entry( + "operationBase64", Base64.getEncoder().encodeToString(operationBytes)), + Map.entry("selectedCommitDigest", commitDigest)))); + String inventoryDigest = sha256(inventoryBytes); + inventory = mock(SelectedDraftAssetInventory.class); + when(inventory.request()).thenReturn(request); + when(inventory.digest()).thenReturn(inventoryDigest); + when(inventory.canonicalBytes()).thenReturn(inventoryBytes.clone()); + when(inventory.assets()).thenReturn(List.of()); + when(inventoryReader.read(request)).thenReturn(inventory); + + manifestBytes = + Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString( + Map.ofEntries( + Map.entry("schema", "game-design-selected-asset-manifest/v1"), + Map.entry("manifestSchemaVersion", 1), + Map.entry("selectedInventorySchema", SelectedDraftAssetInventory.SCHEMA), + Map.entry("selectedInventoryDigest", inventoryDigest), + Map.entry("artifacts", List.of())))); + manifest = new ExportedAssetManifest(sha256(manifestBytes), 1, List.of(), List.of()); + candidate = + new CandidateBinding( + request.requestDigest(), + sha256(operationBytes), + commitDigest, + SelectedDraftAssetInventory.SCHEMA, + inventoryDigest, + manifest, + request.canonicalPreimage(), + inventoryBytes, + manifestBytes); + when(candidateService.readSelectedCandidate(request)).thenReturn(candidate); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))) + .thenReturn(objectBytes(manifestBytes, "application/json")); + exporter = + new AssetExportServiceImpl( + legacy, s3, properties(), mapper, inventoryReader, candidateService); + } + + @Test + void durableCandidateAndIndependentInventoryReadbacksPrecedeConditionalWrite() { + var result = exporter.exportSelectedAssets(request); + + assertEquals(manifest, result.manifest()); + assertEquals(candidate, result.candidateBinding()); + verifyRecordedCandidate(org.mockito.Mockito.times(1)); + verify(inventoryReader, org.mockito.Mockito.times(2)).read(request); + verify(s3) + .putObject( + argThat( + (PutObjectRequest put) -> + put.key().equals("manifests/sha256/" + manifest.manifestHash().substring(7)) + && "*".equals(put.ifNoneMatch())), + any(RequestBody.class)); + InOrder order = inOrder(candidateService, s3); + order + .verify(candidateService) + .recordSelectedCandidate( + eq(inventory), + eq(manifest), + argThat(bytes -> java.util.Arrays.equals(bytes, manifestBytes))); + order.verify(candidateService).readSelectedCandidate(request); + order.verify(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void missingCompleteInventoryDeniesBeforeCandidateOrObjectWrites() { + when(inventoryReader.read(request)) + .thenThrow(new IllegalStateException("complete inventory unavailable")); + + assertThrows(IllegalStateException.class, () -> exporter.exportSelectedAssets(request)); + + verifyNoInteractions(candidateService, s3); + } + + @Test + void changedIndependentInventoryReadbackDeniesBeforeObjectWrites() { + byte[] changedBytes = inventoryBytes.clone(); + changedBytes[changedBytes.length - 2] = (byte) (changedBytes[changedBytes.length - 2] ^ 1); + SelectedDraftAssetInventory changed = mock(SelectedDraftAssetInventory.class); + when(changed.digest()).thenReturn(sha256(changedBytes)); + when(changed.canonicalBytes()).thenReturn(changedBytes); + when(inventoryReader.read(request)).thenReturn(inventory, changed); + + assertThrows(IllegalStateException.class, () -> exporter.exportSelectedAssets(request)); + + verifyRecordedCandidate(org.mockito.Mockito.times(1)); + verifyNoInteractions(s3); + } + + @Test + void candidateMismatchDeniesBeforeObjectWrites() { + CandidateBinding changed = + new CandidateBinding( + "b".repeat(64), + candidate.operationDigest(), + candidate.selectedCommitDigest(), + candidate.inventorySchema(), + candidate.inventoryDigest(), + candidate.manifest(), + candidate.requestPreimage(), + candidate.inventoryBytes(), + candidate.manifestBytes()); + when(candidateService.readSelectedCandidate(request)).thenReturn(changed); + + assertThrows(IllegalStateException.class, () -> exporter.exportSelectedAssets(request)); + + verifyRecordedCandidate(org.mockito.Mockito.times(1)); + verify(inventoryReader, org.mockito.Mockito.times(1)).read(request); + verifyNoInteractions(s3); + } + + @Test + void finalizationGuardDelegatesTheExactReadbackCandidateAndManifest() { + var result = exporter.exportSelectedAssets(request); + + exporter.requireSelectedCandidateForFinalization(request, result); + + verify(candidateService).requireSelectedCandidateForFinalization(request, candidate); + } + + @Test + void exactConditionalCollisionIsResolvedByExactObjectReadbackAndRetry() { + doThrow(S3Exception.builder().statusCode(412).message("precondition failed").build()) + .when(s3) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + + var first = exporter.exportSelectedAssets(request); + var retry = exporter.exportSelectedAssets(request); + + assertEquals(first, retry); + verify(s3, org.mockito.Mockito.times(2)).getObjectAsBytes(any(GetObjectRequest.class)); + verifyRecordedCandidate(org.mockito.Mockito.times(2)); + } + + @Test + void missingObjectReadbackAfterLostConditionalPutRemainsPendingAndRetryUsesSameCandidate() { + when(s3.putObject(any(PutObjectRequest.class), any(RequestBody.class))) + .thenThrow( + S3Exception.builder().statusCode(503).message("conditional put response lost").build()) + .thenReturn(null); + when(s3.getObjectAsBytes(any(GetObjectRequest.class))) + .thenThrow(S3Exception.builder().statusCode(404).message("object not visible yet").build()) + .thenReturn(objectBytes(manifestBytes, "application/json")); + + assertThrows( + AssetExportService.SelectedExportOutcomePendingException.class, + () -> exporter.exportSelectedAssets(request)); + var retry = exporter.exportSelectedAssets(request); + + assertEquals(manifest, retry.manifest()); + assertEquals(candidate, retry.candidateBinding()); + verifyRecordedCandidate(org.mockito.Mockito.times(2)); + verify(s3, org.mockito.Mockito.times(2)) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void deniedObjectReadbackRemainsPendingRatherThanClaimingByteConflict() { + when(s3.getObjectAsBytes(any(GetObjectRequest.class))) + .thenThrow(S3Exception.builder().statusCode(403).message("readback denied").build()); + + assertThrows( + AssetExportService.SelectedExportOutcomePendingException.class, + () -> exporter.exportSelectedAssets(request)); + + verifyRecordedCandidate(org.mockito.Mockito.times(1)); + verify(s3).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void objectReadbackMismatchLeavesCandidatePendingAndFailsClosed() { + when(s3.getObjectAsBytes(any(GetObjectRequest.class))) + .thenReturn(objectBytes("different".getBytes(StandardCharsets.UTF_8), "application/json")); + + var failure = + assertThrows(IllegalStateException.class, () -> exporter.exportSelectedAssets(request)); + + assertEquals("SELECTED_ASSET_OBJECT_READBACK_MISMATCH", failure.getMessage()); + verifyRecordedCandidate(org.mockito.Mockito.times(1)); + } + + private void verifyRecordedCandidate(org.mockito.verification.VerificationMode mode) { + verify(candidateService, mode) + .recordSelectedCandidate( + org.mockito.ArgumentMatchers.eq(inventory), + org.mockito.ArgumentMatchers.eq(manifest), + argThat(bytes -> java.util.Arrays.equals(bytes, manifestBytes))); + } + + private static AssetStoreProperties properties() { + AssetStoreProperties result = new AssetStoreProperties(); + result.setBucket("private-assets"); + result.setEndpoint("http://localhost:9000"); + result.setRegion("ap-southeast-2"); + result.setAccessKey("test"); + result.setSecretKey("test"); + return result; + } + + private static ResponseBytes objectBytes(byte[] bytes, String contentType) { + return ResponseBytes.fromByteArray( + GetObjectResponse.builder() + .contentLength((long) bytes.length) + .contentType(contentType) + .build(), + bytes); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java new file mode 100644 index 0000000000..b290c4ec92 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java @@ -0,0 +1,87 @@ +package unit.net.firedevops.firemud.gamedesign.service.impl; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.List; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService.CandidateBinding; +import org.junit.jupiter.api.Test; + +/** Candidate values retain exact readback bytes and never collapse to digest-only equality. */ +class VersionAssetExportCandidateServiceImplTest { + @Test + void candidateBindingDefensivelyRetainsEveryExactReadbackByteArray() { + byte[] request = new byte[] {1, 2}; + byte[] inventory = new byte[] {3, 4}; + byte[] manifest = new byte[] {5, 6}; + CandidateBinding candidate = candidate(request, inventory, manifest); + request[0] = 9; + inventory[0] = 9; + manifest[0] = 9; + + assertArrayEquals(new byte[] {1, 2}, candidate.requestPreimage()); + assertArrayEquals(new byte[] {3, 4}, candidate.inventoryBytes()); + assertArrayEquals(new byte[] {5, 6}, candidate.manifestBytes()); + byte[] returned = candidate.inventoryBytes(); + returned[0] = 8; + assertArrayEquals(new byte[] {3, 4}, candidate.inventoryBytes()); + } + + @Test + void candidateEqualityIncludesExactInventoryAndManifestBytes() { + CandidateBinding original = candidate(new byte[] {1}, new byte[] {2}, new byte[] {3}); + + assertFalse(original.equals(candidate(new byte[] {1}, new byte[] {8}, new byte[] {3}))); + assertFalse(original.equals(candidate(new byte[] {1}, new byte[] {2}, new byte[] {8}))); + assertEquals(original, candidate(new byte[] {1}, new byte[] {2}, new byte[] {3})); + } + + @Test + void candidateRequiresCompleteSelectedInventorySchemaAndImmutableManifestEvidence() { + var manifest = new ExportedAssetManifest("sha256:" + "a".repeat(64), List.of()); + + assertThrows( + IllegalStateException.class, + () -> + new CandidateBinding( + "b".repeat(64), + "sha256:" + "c".repeat(64), + "sha256:" + "d".repeat(64), + SelectedDraftAssetInventory.SCHEMA, + "sha256:" + "e".repeat(64), + manifest, + new byte[] {1}, + new byte[] {2}, + new byte[] {3})); + assertThrows( + IllegalArgumentException.class, + () -> + new CandidateBinding( + "b".repeat(64), + "sha256:" + "c".repeat(64), + "sha256:" + "d".repeat(64), + "unsupported-inventory", + "sha256:" + "e".repeat(64), + new ExportedAssetManifest("sha256:" + "a".repeat(64), 1, List.of(), List.of()), + new byte[] {1}, + new byte[] {2}, + new byte[] {3})); + } + + private static CandidateBinding candidate(byte[] request, byte[] inventory, byte[] manifest) { + return new CandidateBinding( + "b".repeat(64), + "sha256:" + "c".repeat(64), + "sha256:" + "d".repeat(64), + SelectedDraftAssetInventory.SCHEMA, + "sha256:" + "e".repeat(64), + new ExportedAssetManifest("sha256:" + "a".repeat(64), 1, List.of(), List.of()), + request, + inventory, + manifest); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 5f1839895e..56387a0568 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -18,6 +18,7 @@ import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; @@ -45,9 +46,11 @@ import net.firedevops.firemud.gamedesign.service.PublishAttemptService; import net.firedevops.firemud.gamedesign.service.PublishGateFailureException; import net.firedevops.firemud.gamedesign.service.PublishGateService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.RecordedParticipantDigestService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -172,9 +175,10 @@ void selectedPublicationRejectsPrivateTenantDerivedWorkflowIdentity() { verify(versionRepository, never()).findByTenantIdAndId(any(String.class), any(Long.class)); } - @Test - void selectedPublicationPassesCanonicalOperationBindingAndKeepsMissingReceiptPending() - throws Exception { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void selectedPublicationPassesCanonicalOperationBindingAndKeepsUnresolvedDependenciesPending( + boolean assetReadbackPending) throws Exception { String tenantId = "9002"; long versionId = 10L; int versionNumber = 8; @@ -223,23 +227,33 @@ void selectedPublicationPassesCanonicalOperationBindingAndKeepsMissingReceiptPen when(publishGateService.collectSelectedFullVersionParticipantDigests( any(VersionDto.class), any(PublicationDigestRequestBinding.class), eq(workflowId))) .thenReturn( - List.of( - new PublishParticipantDigestDto( - "GAME_LOGIC", - String.valueOf(versionId), - null, - null, - null, - null, - "PARTICIPANT_UNAVAILABLE", - "immutable selected Game Logic receipt is not available yet"))); - org.mockito.Mockito.doThrow( - new PublishGateFailureException( - PublishGateFailureCode.PARTICIPANT_UNAVAILABLE, - "selected Game Logic receipt is missing", - "PARTICIPANT_UNAVAILABLE")) - .when(publishGateService) - .assertSelectedGatePassed(any(VersionDto.class), any(List.class)); + assetReadbackPending + ? List.of() + : List.of( + new PublishParticipantDigestDto( + "GAME_LOGIC", + String.valueOf(versionId), + null, + null, + null, + null, + "PARTICIPANT_UNAVAILABLE", + "immutable selected Game Logic receipt is not available yet"))); + if (assetReadbackPending) { + when(assetExportService.exportSelectedAssets(any(PublicationDigestRequestBinding.class))) + .thenThrow( + new AssetExportService.SelectedExportOutcomePendingException( + "Exact immutable object readback unavailable", + new IllegalStateException("unavailable"))); + } else { + org.mockito.Mockito.doThrow( + new PublishGateFailureException( + PublishGateFailureCode.PARTICIPANT_UNAVAILABLE, + "selected Game Logic receipt is missing", + "PARTICIPANT_UNAVAILABLE")) + .when(publishGateService) + .assertSelectedGatePassed(any(VersionDto.class), any(List.class)); + } assertThrows( VersionPublishCommandServiceImpl.PendingReconciliationException.class, @@ -261,8 +275,320 @@ void selectedPublicationPassesCanonicalOperationBindingAndKeepsMissingReceiptPen verify(publishAttemptService, never()) .markFullVersionFailed(any(String.class), any(String.class), any(String.class)); verify(publishAttemptRepository, never()).sealPublication(attempt, false); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + if (assetReadbackPending) { + var exportBindingCaptor = ArgumentCaptor.forClass(PublicationDigestRequestBinding.class); + verify(assetExportService).exportSelectedAssets(exportBindingCaptor.capture()); + org.junit.jupiter.api.Assertions.assertArrayEquals( + expectedBinding.canonicalPreimage(), exportBindingCaptor.getValue().canonicalPreimage()); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + } + } + + @Test + void selectedPublicationRechecksExactCandidateUnderGameLockBeforeReleaseWrites() { + SelectedPublicationFixture fixture = selectedPublicationFixture(); + AtomicBoolean transactionOpen = new AtomicBoolean(); + AtomicBoolean gameLockObserved = new AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> { + transactionOpen.set(true); + try { + return ((java.util.function.Supplier) invocation.getArgument(0)).get(); + } catch (RuntimeException ex) { + throw new PublishAttemptService.FullVersionTransactionException(ex); + } finally { + transactionOpen.set(false); + } + }) + .when(publishAttemptService) + .executeFullVersionTransaction(any()); + when(gameRepository.findByTenantIdForUpdate(fixture.tenantId())) + .thenAnswer( + invocation -> { + assertTrue( + transactionOpen.get(), "Game row lock must be acquired in the transaction"); + gameLockObserved.set(true); + return fixture.game(); + }); + org.mockito.Mockito.doAnswer( + invocation -> { + assertTrue(transactionOpen.get(), "candidate readback must be transaction-local"); + assertTrue( + gameLockObserved.get(), "candidate readback must follow the Game row lock"); + PublicationDigestRequestBinding actual = invocation.getArgument(0); + org.junit.jupiter.api.Assertions.assertArrayEquals( + fixture.request().canonicalPreimage(), actual.canonicalPreimage()); + assertEquals(fixture.exportResult(), invocation.getArgument(1)); + return null; + }) + .when(assetExportService) + .requireSelectedCandidateForFinalization(any(PublicationDigestRequestBinding.class), any()); + + var snapshot = + service.reconcileSelectedDraftFullVersionPublish( + fixture.tenantId(), + fixture.versionId(), + fixture.notes(), + fixture.publishRequestId(), + fixture.workflowId()); + + assertEquals("SUCCEEDED", snapshot.status(), snapshot.failureMessage()); + ArgumentCaptor exportBindingCaptor = + ArgumentCaptor.forClass(PublicationDigestRequestBinding.class); + verify(assetExportService).exportSelectedAssets(exportBindingCaptor.capture()); + org.junit.jupiter.api.Assertions.assertArrayEquals( + fixture.request().canonicalPreimage(), exportBindingCaptor.getValue().canonicalPreimage()); + verify(assetExportService, never()).exportAssets(any(String.class), any(Integer.class)); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); + + InOrder finalizationOrder = + inOrder( + assetExportService, + versionAssetArtifactService, + publishedReleaseBundleService, + versionRepository); + finalizationOrder.verify(assetExportService).exportSelectedAssets(any()); + finalizationOrder + .verify(assetExportService) + .requireSelectedCandidateForFinalization(any(), same(fixture.exportResult())); + finalizationOrder + .verify(versionAssetArtifactService) + .markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + same(fixture.exportResult().manifest())); + finalizationOrder + .verify(publishedReleaseBundleService) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + same(fixture.exportResult().manifest()), + any(String.class), + any(List.class), + same(originalWorldEvidence)); + finalizationOrder.verify(versionRepository).save(same(fixture.version())); + } + + @Test + void selectedCandidateMismatchCannotCreateOrPublishReleaseBundle() { + SelectedPublicationFixture fixture = selectedPublicationFixture(); + org.mockito.Mockito.doThrow(new IllegalStateException("SELECTED_EXPORT_CANDIDATE_MISMATCH")) + .when(assetExportService) + .requireSelectedCandidateForFinalization(any(PublicationDigestRequestBinding.class), any()); + + var snapshot = + service.reconcileSelectedDraftFullVersionPublish( + fixture.tenantId(), + fixture.versionId(), + fixture.notes(), + fixture.publishRequestId(), + fixture.workflowId()); + + assertEquals("FAILED", snapshot.status()); + assertEquals(VersionLifecycleState.DRAFT, fixture.version().getVersionState()); + verify(assetExportService) + .requireSelectedCandidateForFinalization(any(PublicationDigestRequestBinding.class), any()); + verify(versionAssetArtifactService, never()) + .markExportedUnattested( + any(String.class), + any(Long.class), + any(Integer.class), + any(String.class), + any(ExportedAssetManifest.class)); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle( + any(VersionDto.class), + any(String.class), + any(ExportedAssetManifest.class), + any(String.class), + any(List.class), + any(WorldPublishedStartLocationEvidence.class)); + verify(publishAttemptService, never()).markFullVersionSucceeded(any(String.class)); + verify(publishAttemptService) + .markFullVersionFailed( + eq(fixture.workflowId()), + eq("PUBLISH_FAILED"), + eq("SELECTED_EXPORT_CANDIDATE_MISMATCH")); + verify(publishAttemptRepository).sealPublication(any(PublishAttempt.class), eq(false)); + verify(versionAssetArtifactService) + .markFailed( + eq(fixture.tenantId()), + eq(fixture.versionId()), + eq(fixture.version().getVersionNumber()), + eq(fixture.workflowId()), + same(fixture.exportResult().manifest()), + eq("PUBLISH_FAILED"), + eq("SELECTED_EXPORT_CANDIDATE_MISMATCH")); + verify(assetExportService, never()) + .deleteExportedAssets(any(String.class), any(Integer.class), any(List.class)); } + /** + * Isolated orchestration fixture: the retained operation/World owner reads are explicit Mockito + * doubles; this unit proof does not claim authenticated Account or cross-service release proof. + */ + private SelectedPublicationFixture selectedPublicationFixture() { + String tenantId = "9002"; + long versionId = 10L; + int versionNumber = 8; + String publishRequestId = "selected-request-finalize"; + String notes = "selected draft notes"; + UUID canonicalTenantId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + PublicationDigestRequestBinding request = + PublicationDigestRequestBinding.full( + canonicalTenantId.toString(), Long.toString(versionId), publishRequestId); + String workflowId = request.derivedWorkflowIdentity(); + String selectionDigest = "sha256:" + "c".repeat(64); + PublishAttempt attempt = + fullAttempt(PublishAttemptStatus.PENDING, versionId, versionNumber, workflowId); + attempt.setTenantId(tenantId); + attempt.setRequestDigest(selectionDigest); + when(publishAttemptRepository.findByPublishWorkflowId(workflowId)) + .thenReturn(Optional.of(attempt)); + + GameDesignPublicationOperation operation = + org.mockito.Mockito.mock(GameDesignPublicationOperation.class); + AccountPublicationAuthorizationBinding account = + org.mockito.Mockito.mock(AccountPublicationAuthorizationBinding.class); + AccountPublicationAuthorizationBinding.PreallocationInput input = + org.mockito.Mockito.mock(AccountPublicationAuthorizationBinding.PreallocationInput.class); + AuthoredDraftPublishSelectionBinding selection = + org.mockito.Mockito.mock(AuthoredDraftPublishSelectionBinding.class); + AuthoredDraftPublishSelectionBinding.PublishIntent intent = + org.mockito.Mockito.mock(AuthoredDraftPublishSelectionBinding.PublishIntent.class); + when(operation.account()).thenReturn(account); + when(account.input()).thenReturn(input); + when(input.selection()).thenReturn(selection); + when(selection.intent()).thenReturn(intent); + when(intent.canonicalTenantId()).thenReturn(canonicalTenantId); + when(intent.publishRequestId()).thenReturn(publishRequestId); + when(intent.notes()).thenReturn(notes); + when(operation.tenantKey()).thenReturn(tenantId); + when(operation.versionId()).thenReturn(versionId); + when(operation.selectionDigest()).thenReturn(selectionDigest); + when(operation.workflowId()).thenReturn(workflowId); + when(publishAttemptRepository.requireSelectedPublicationReadback(attempt, "PENDING")) + .thenReturn(operation); + + Version version = fullVersion(versionId, versionNumber, VersionLifecycleState.DRAFT); + version.setTenantId(tenantId); + version.setNotes(notes); + when(versionRepository.findByTenantIdAndId(tenantId, versionId)) + .thenReturn(Optional.of(version)); + Game game = new Game(); + game.setTenantId(tenantId); + when(gameRepository.findByTenantIdForUpdate(tenantId)).thenReturn(game); + + List participantDigests = participantDigests(); + when(publishGateService.collectSelectedFullVersionParticipantDigests( + any(VersionDto.class), any(PublicationDigestRequestBinding.class), eq(workflowId))) + .thenReturn(participantDigests); + when(controlPlaneDigestService.getDigestForVersion(any(VersionDto.class))) + .thenReturn( + new DesignControlPlaneDigestDto( + tenantId, Long.toString(versionId), "version:" + versionId, "digest-selected", 1)); + + String artifactDigest = "sha256:" + "a".repeat(64); + PublishedArtifactDigest artifact = + new PublishedArtifactDigest( + "logo.png", + "ORDINARY", + "artifacts/sha256/" + "a".repeat(64), + artifactDigest, + "image/png", + 1); + ExportedAssetManifest manifest = + new ExportedAssetManifest( + "sha256:" + "b".repeat(64), 1, List.of("logo.png"), List.of(artifact)); + VersionAssetExportCandidateService.CandidateBinding candidate = + new VersionAssetExportCandidateService.CandidateBinding( + request.requestDigest(), + "sha256:" + "d".repeat(64), + "sha256:" + "e".repeat(64), + net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory.SCHEMA, + "sha256:" + "f".repeat(64), + manifest, + request.canonicalPreimage(), + "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8), + "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + AssetExportService.SelectedExportResult exportResult = + new AssetExportService.SelectedExportResult(manifest, candidate); + when(assetExportService.exportSelectedAssets( + org.mockito.ArgumentMatchers.argThat( + binding -> + binding != null + && java.util.Arrays.equals( + request.canonicalPreimage(), binding.canonicalPreimage())))) + .thenReturn(exportResult); + + when(versionAssetArtifactService.markExportedUnattested( + eq(tenantId), eq(versionId), eq(versionNumber), eq(workflowId), same(manifest))) + .thenReturn( + new VersionAssetArtifactStateDto( + tenantId, + versionId, + versionNumber, + "EXPORTED_UNATTESTED", + 1L, + manifest.manifestHash(), + workflowId, + null, + null, + LocalDateTime.now(), + manifest.requiredManifestAssetKeys())); + when(publishedReleaseBundleService.createFullVersionBundle( + any(VersionDto.class), + eq(workflowId), + same(manifest), + any(String.class), + same(participantDigests), + same(originalWorldEvidence))) + .thenReturn( + new PublishedReleaseBundleDto( + 1L, + tenantId, + versionId, + versionNumber, + "v1", + workflowId, + manifest.manifestHash(), + manifest.requiredManifestAssetKeys(), + participantDigests, + "generation-revision", + false, + null, + LocalDateTime.now())); + when(versionRepository.save(any(Version.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + return new SelectedPublicationFixture( + tenantId, + versionId, + notes, + publishRequestId, + workflowId, + request, + exportResult, + version, + game); + } + + private record SelectedPublicationFixture( + String tenantId, + long versionId, + String notes, + String publishRequestId, + String workflowId, + PublicationDigestRequestBinding request, + AssetExportService.SelectedExportResult exportResult, + Version version, + Game game) {} + @Test void publishFullVersionUsesTenantScopedVersionSequence() { Game game = new Game(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index ca0562ca0d..789c6a907d 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -67,6 +67,7 @@ import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; @@ -5305,6 +5306,13 @@ void publicationOwnerReadsIntakeOnlyInsideWritableReadCommittedTransaction() { Fixture f = fixture(); WorldAuthoredSourceIntakeRepository intakeReader = new WorldAuthoredSourceIntakeRepository(dsl); OwnerBinding owner = f.owner(); + String publicationRequestId = "transaction-dispatch-" + UUID.randomUUID(); + String publishWorkflowId = + PublicationDigestRequestBinding.full( + owner.canonicalTenantId().toString(), + Long.toString(owner.gameDesignVersionId()), + publicationRequestId) + .derivedWorkflowIdentity(); WorldDesignPublicationFenceEvidence freezeEvidence = new WorldDesignPublicationFenceEvidence( owner.targetNamespace(), @@ -5318,10 +5326,10 @@ void publicationOwnerReadsIntakeOnlyInsideWritableReadCommittedTransaction() { owner.sourceOperationId(), owner.sourceEvidenceDigest(), owner.intakeReceiptDigest(), - "transaction-dispatch-" + UUID.randomUUID(), + publicationRequestId, "a".repeat(64), 1, - "publish:" + owner.canonicalTenantId() + ":transaction-dispatch"); + publishWorkflowId); assertThatThrownBy( () -> From 0eacc39ff5602a64d8e170421b392123a2dda2c9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 02:11:56 +1300 Subject: [PATCH 052/129] Bind StartSession descriptors to exact published source associations --- .../game-design-service/README.md | 6 +- .../game-design-service/api-contracts.md | 2 + .../game-design-service/asset-storage.md | 2 +- .../game-design-service/game-templates.md | 8 +- .../system-architecture-versioning-runtime.md | 2 +- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 6 +- ...session_template_association_service.proto | 23 + ...uthoredWorldLaunchDescriptorGrpcCodec.java | 14 + ...StartSessionLaunchDescriptorGrpcCodec.java | 239 ++ ...tSessionLaunchDescriptorGrpcCodecTest.java | 527 +++++ ...artSessionLaunchDescriptorGrpcService.java | 144 ++ .../StartSessionLaunchDescriptorProducer.java | 1112 ++++++++++ ...tartSessionLaunchDescriptorRepository.java | 201 ++ ..._launch_descriptor_association_binding.sql | 219 ++ ...licationExportPostgresIntegrationTest.java | 1975 +++++++++++++++++ ...emptServiceTransactionIntegrationTest.java | 121 +- ...xportCandidatePostgresIntegrationTest.java | 5 +- ...essionLaunchDescriptorGrpcServiceTest.java | 380 ++++ ...rtSessionLaunchDescriptorProducerTest.java | 235 ++ 20 files changed, 5201 insertions(+), 26 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionLaunchDescriptorRepository.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V66__start_session_launch_descriptor_association_binding.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 598505a693..3575b27ab1 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -26,7 +26,7 @@ Current capability and proof gaps remain: Game Session's exact pin/epoch persist - **Current hosted-route consequence:** the Gateway's coarse `/api/design/**` route currently forwards `/api/design/assets` through `StripPrefix=2` to the live `POST /assets` controller. Because Game Design has no Account hosted-terms/currentness gate, official-hosted asset-upload readiness remains blocked until Gateway denies the route or the exact Account-owned gate is implemented and proved. - Act as the sole owner of game asset publishing to the S3-compatible object store; **target state:** downstream services and clients read published assets via approved configured delivery URLs and do not write directly to the asset store. In the current first slice, private MinIO/object-store URLs are not public client delivery. Logical world and entity templates remain in PostgreSQL schemas owned by World Management, Entity Management, and related domain services and are not stored as blobs in the asset store. - When publish workflows need to expose derived domain artifacts outside their owning service storage (for example world navmesh/path graph bundles), Game Design remains the sole object-store writer. Owning domain services hand those artifacts to the publish workflow as explicit inputs; they do not bypass the publish workflow with direct object-store writes. -- **Target state:** Runtime discovery of derived artifacts uses the version `manifest.json` attested by `published_release_bundle`. The target canonical attestation shape includes `artifactDigests[]`, `requiredManifestAssetKeys[]`, and `manifestHash`; the current persisted bundle is narrower and lacks those complete target fields, so consumers must not treat current output as complete release proof or depend on undocumented bucket key conventions. +- **Target state:** Runtime discovery of derived artifacts uses the version `manifest.json` attested by `published_release_bundle`. The selected-release construction carries the manifest and artifact evidence, but carriers alone are not complete source-to-release or runtime-delivery proof. See the [release owner contract](../../system-architecture-versioning-runtime.md#launch-descriptor-version-resolution-rules) and [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); consumers must not depend on undocumented bucket key conventions. - Own version lifecycle state and CAS epoch metadata (`versionState`, `versionStateEpoch`) and expose control-plane APIs; target activation/retirement-safe transition guards remain unimplemented, as recorded in the implementation status. - Expose control-plane integrity APIs such as `GetDesignControlPlaneDigest` and `CanDeleteVersionAssets` used by publish gating and asset-retention workflows. - **Target state:** Expose CAS-guarded asset purge APIs (`BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`) so purge eligibility re-check and artifact-state transitions are race-safe. The current repositories update by row ID after service-memory epoch checks without database epoch predicates or affected-row proof; current lifecycle APIs are not race-safe. @@ -143,9 +143,9 @@ source of truth for world and entity history. Domain services (World Management, Entity Management, etc.) store the versioned templates they consume at runtime, but commit and revision history remains anchored in the Game Design Service. -The Game Design Service must also persist an immutable `published_release_bundle` record per `(tenantId, versionId)` after publish gates and asset export succeed. This record is the canonical release attestation consumed by activation, rollback-preflight, and repair tooling. **Target state:** It contains the publish workflow identity, target `commitId`, required participant digests, `manifestHash`, and `generationConfigRevision` for that release. **Current status:** The persisted row and response do not yet include target `commitId`, `manifestSchemaVersion`, or complete `artifactDigests[]`; current schema/validator status is recorded in the [API contract implementation status](api-contracts.md#implementation-status) and [version-control digest contract](version-control.md#digest-participants-by-publish-type). **Target state (currently unproved):** The record also contains the dedicated Game Logic-owned `abilitySchemaDigest`. +The Game Design Service must persist the immutable `published_release_bundle` after publish gates and asset export succeed. Its complete canonical fields and selected-commit binding belong to the [release owner contract](../../system-architecture-versioning-runtime.md#launch-descriptor-version-resolution-rules). The selected-release construction carries dedicated Game Logic ability-schema evidence, manifest schema and artifact digests; it does not establish complete authenticated production, launch or activation. Detailed implementation and executed-proof limits belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). -**Target state:** For releases that export derived artifacts outside participant-owned databases, `published_release_bundle` must also include `artifactDigests[]` entries for each exported artifact family. For world bundles such as navmesh/path graph payloads, these entries are mandatory rather than optional metadata. The current release bundle does not persist this complete field. +For releases that export derived artifacts outside participant-owned databases, the release attestation must include each required artifact family's actual-byte evidence. World navmesh/path graph consumers must follow [Asset Storage](./asset-storage.md#complete-selected-release-asset-inventory); a populated artifact carrier cannot substitute for an unavailable producer or authenticated exact readback. ### Design Workflow diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index a51ee83d87..89365720b4 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -24,6 +24,8 @@ Game Design issues each new game row an opaque canonical tenant UUID and keeps e The distinct Game Session-facing `GameDesignStartSessionTemplateAssociationReadService.ReadStartSessionTemplateAssociation` follows the [immutable template-to-World association contract](game-templates.md#immutable-template-to-world-source-association), not this World-only registration-source lookup. Its schema-1 wire definition is [start_session_template_association_service.proto](../../../../protos/game-design/v1/start_session_template_association_service.proto). The receiver authenticates the exact same-namespace Game Session caller before decoding and independently verifies the Account original-operation projection before reading content. Its initial/replay modes and complete response correlations preserve the original operation and selection; missing association evidence denies without read-side population. The current source, association and consumer proof limits are tracked in [Game Authoring, Publishing, and Activation](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); this standalone unregistered handler does not establish an enabled method or broaden the existing `TenantIdentityService` allowlist. +The separate `GameDesignStartSessionLaunchDescriptorService.ResolveStartSessionLaunchDescriptor` uses the same wire file and the owner's [exact-replay descriptor projection](game-templates.md#immutable-template-to-world-source-association). It accepts only the exact pinned association mode, not initial selection or a caller version override. Its schema-1 response includes the complete association read and exactly one descriptor or committed application-failure outcome. Authentication and unavailable-owner failures remain non-OK RPC statuses. Its standalone adapter is also unregistered; it does not broaden an existing allowlist or authorize World preparation or admission. + `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. ## Official Hosted Creator Mutation Gate diff --git a/design/architecture/microservices/game-design-service/asset-storage.md b/design/architecture/microservices/game-design-service/asset-storage.md index d7921e2f7c..56c78b7b2f 100644 --- a/design/architecture/microservices/game-design-service/asset-storage.md +++ b/design/architecture/microservices/game-design-service/asset-storage.md @@ -114,7 +114,7 @@ Target initial-slice discovery rule for derived world artifacts: - In the target first implementation slice, exported world navmesh/path graph artifacts must be discoverable through the same attested release surfaces as other version assets. - In the target first implementation slice, Game Design must publish a `manifest.json` entry keyed by a stable usage name for each exported world navmesh/path graph artifact. -- `GetPublishedReleaseBundle(tenantId, versionId)` is the canonical attestation surface. **Target contract:** it exposes both `artifactDigests[]` for exported derived-world-artifact bytes and `requiredManifestAssetKeys[]` for launch-required manifest usage keys, together with the attested `manifestHash`. The current row/response lacks the complete target fields, so this is not current implementation proof. +- `GetPublishedReleaseBundle(tenantId, versionId)` is the canonical attestation surface. **Target contract:** it exposes both `artifactDigests[]` for exported derived-world-artifact bytes and `requiredManifestAssetKeys[]` for launch-required manifest usage keys, together with the attested `manifestHash`. The selected-release construction carries these fields, but complete source, actual-byte export and authenticated consumer proof remain separate requirements; see the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). - The attested release contract must also declare which stable usage keys are required for launch of that specific release. Manifest integrity alone is not sufficient to infer whether an omitted key is valid or a launch-blocking defect. - Runtime consumers must treat those attested references as canonical and must not construct object-store paths by convention. diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 1a994ef7fb..7cddf4975d 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -14,7 +14,7 @@ creators can quickly spin up new projects without starting from scratch. ## Implementation Status -- The launch plugin-selection presence modes remain target-only and unimplemented: a presence-capable selection wrapper/mode, fresh omission or explicit empty resolving to the same immutable empty selection, rollback omission reusing a named target, rollback explicit empty, and explicit non-empty selection are not yet represented in proto/generated clients, launch-descriptor persistence/response, the request digest, service logic, or focused proof. Launch-resolution APIs are live, but the current implementation does not yet persist, expose, or prove the complete `enabledPluginVersions[]` set for deterministic retry and rollback. The detailed target contract remains below. +- The launch plugin-selection presence modes remain target-only and unimplemented: a presence-capable selection wrapper/mode, fresh omission or explicit empty resolving to the same immutable empty selection, rollback omission reusing a named target, rollback explicit empty, and explicit non-empty selection are not yet represented in proto/generated clients, launch-descriptor persistence/response, the request digest, service logic, or focused proof. The registered legacy launch-resolution adapter denies requests without the complete canonical source binding; an owner-local source-bound descriptor implementation is not proof of authenticated positive launch ingress. The current implementation does not yet persist, expose, or prove the complete `enabledPluginVersions[]` set for deterministic retry and rollback. The detailed target contract remains below. - Current script-patch resolution is not yet the target launch predicate: a full-version template/request can persist an arbitrary patch ID without proving a same-base `PUBLISHED` Game Design publication or Automation `READY` status. These are implementation gaps; the target validation and fail-before-instance-row rules remain below. - The target tenant-scoped `GetTemplateReferencePhase` cutover read is not implemented in the current proto or service. Current launch resolution checks only the per-template `templateReferencePhase` field (`ENFORCED`/`LEGACY`); it does not expose or consume the target durable tenant phase (`BACKFILLING`/`VALIDATED`/`ENFORCED`) required by launch and retirement tooling. - The construction adds a current normalized single-base projection and fresh, creation-receipt-backed tenant phase with full-inventory validation. It does not establish complete external-owner projections, authenticated launch consumption, retained-tenant cutover, or retirement/reference-query tooling. Detailed implementation and executed-versus-unrun proof belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). @@ -221,9 +221,11 @@ Game Design owns the immutable association between the canonical tenant, its exi The immutable read is restricted to the exact same-namespace Game Session workload inside its unchanged Account-authorized `StartSession` operation. Before returning content, Game Design independently verifies Account's authenticated original-operation projection, including the original actor, workload, target and actual Game Session attempt/fence binding. A descriptor digest, forwarded JWT, source receipt or workload identity alone does not establish this read permission. Game Session binds the selected association, version and descriptor to its original `controlPlaneRequestId` before reuse. Exact retries preserve that selection and cannot silently choose a newer association, another commit or another release. Missing, ambiguous, substituted or mismatched scope/commit evidence denies; a read never repairs missing association rows or grants Game Design mutation, World application or runtime activation. The operator authority and read-applicability contract belongs to [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); source association does not replace release attestation or Game Session's launch ownership. -The closed schema-1 read request binds its correlation ID, complete canonical Account post-authorization execution tuple, and actual Game Session owner attempt and positive fence. Initial configured selection has no caller version override: Game Design selects through its exact normalized base reference and independently verifies the explicit tenant `ENFORCED` phase and retained publication. Exact replay instead names the originally pinned canonical version, selected commit, publication workflow and association digest; it does not reselect from current template configuration. Both modes require the original operation's independently verified current read authorization. The response echoes the complete request and returns the public association projection, complete original World source receipt and published release, original typed World published start-location evidence, and positive owner phase epoch from the same Game Design snapshot. Private source/capture bytes and numeric provenance selectors are not exposed. +The closed schema-1 read request binds its correlation ID, complete canonical Account post-authorization execution tuple, and actual Game Session owner attempt and positive fence. Initial configured selection has no caller version override: Game Design selects through its exact normalized base reference and independently verifies the explicit tenant `ENFORCED` phase and retained publication. Exact replay instead names the originally pinned canonical version, selected commit, publication workflow and association digest; it does not reselect from current template configuration. Both modes require the original operation's independently verified current read authorization. The response echoes the complete request and returns the public association projection, complete original World source receipt and published release, original typed World published start-location evidence, and positive owner phase epoch from the same Game Design snapshot. Private publication operation/capture bytes are not exposed. Numeric provenance retained inside the original World source receipt remains owner evidence, not a caller-selectable identity or permission. -The association producer, authenticated operation-bound read and Game Session pinning are distinct proof boundaries. Their current implementation and activation limits belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status), not to the presence of a template row or a structurally valid association object. +The separate exact-replay descriptor projection accepts only the association already pinned by Game Session, under the same original authorization tuple, attempt and fence. Game Design independently verifies the authorized association read before its local descriptor transaction, then joins the exact selected source capture, genuine retained Game Logic receipt, published terminal and immutable release. It persists the descriptor and their complete binding atomically; the observation's read correlation ID is not a new launch operation. Exact retries preserve the stored outcome and reject changed operation or selection evidence. Unavailable authorization or owner evidence remains a non-OK dependency failure, not an invented terminal business result. A supported deterministic business denial becomes an application outcome only after its exact immutable receipt commits. This projection does not enable instance creation or replace downstream held-authority checks. + +The association producer, authenticated operation-bound read, descriptor projection and Game Session pinning are distinct proof boundaries. Their current implementation and activation limits belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status), not to the presence of a template row or a structurally valid association object. Required deterministic failure vocabulary for the first implementation slice: diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index b14e4f8fd0..51918f92b1 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -314,7 +314,7 @@ Tooling in the Game Design and Logging & Admin services should surface these rel - `manifestSchemaVersion` - `requiredManifestAssetKeys[]` for stable manifest usage keys that are mandatory for launch/cutover validation of that release - `generationConfigRevision` -- The current release-bundle schema omits the dedicated `abilitySchemaDigest`, target `commitId`, `manifestSchemaVersion`, and complete `artifactDigests[]`; plugin compatibility paths also incorrectly reuse the Automation & Scripting participant digest. Those current paths are implementation drift and do not prove the target release or ability-schema attestation. +- The selected-release construction carries the dedicated Game Logic `abilitySchemaDigest` with its participant evidence, the manifest schema and complete artifact digests, canonical tenant/version identity, and original World selector evidence. Participant `appliedCommitId` remains the explicit selected-commit binding; it is not a separate top-level `commitId` field. These carriers do not establish complete source-to-export production, authenticated launch consumption or runtime activation. Remaining implementation and executed-proof gaps belong to the [authoring tracker](../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); unsupported legacy or partial evidence cannot satisfy this predicate. - `artifactDigests[]` is authoritative for mandatory actual-byte object digests. `requiredManifestAssetKeys[]` is complementary: every required usage key must select exactly one bundle artifact digest and exactly one manifest entry whose `usageKey`, `immutableObjectKey`, and `contentDigest` are byte-for-byte equal. - `manifestHash` attests the canonical manifest bytes containing those usage-key/object-key/digest bindings; it does not replace per-object byte verification. - The contract intentionally does not introduce a separate top-level artifact-path reference field outside this attested bundle shape. Runtime consumers still discover artifact locations through the attested `manifest.json`, not through ad hoc object-store path reconstruction. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 00dc14a6f7..acf492fc21 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -156,3 +156,9 @@ Entry format: - Observation: A workflow-level failure or diagnostic annotation does not establish which owner failed. Misattribution would route unnecessary shared-workflow or World repairs while leaving the real fixture and admission-WAL failures unresolved. - Expected pattern: Verify terminal job/step conclusions and originating owner artifacts before routing a failure; retain actual checkout provenance and distinguish missing artifacts from passed tests. - Current status: The parent corrected the report using the completed job evidence and XML: World 206 passing PostgreSQL cases, Game Design four fixture failures and Account one admission-WAL failure. The fixture corrections were validated locally; no physical rerun or WAL completion credit follows. + +- `2026-10-10`: Newer metadata CI can obscure an active same-head substantive run + - Context: A six-result branch query after PR #3105's body update showed only metadata-preservation runs. Their dependency-deferred failures were initially mistaken for the complete current-head CI state. + - Observation: The separate substantive Validation run 37928625721 was still executing on the same head; metadata and required runs use distinct concurrency groups. The body edit had not cancelled it. A pending-proof metadata failure is neither a runtime failure nor evidence that no physical validation was dispatched. + - Expected pattern: Before requesting replacement CI or routing a dispatch failure, inspect enough same-head runs to distinguish substantive execution from newer metadata preservation, then assign one observer to the actual execution transition. + - Current status: Wider read-only inspection established the active run, and the parent corrected the Overseer request. A sole sentinel owns its outcome; no replacement run or workflow/topology change was made. 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 864f332e13..743daae33d 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 @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The exact retained-source publication composition passes three-module gate R213: 947 unit cases execute without failures or skips (385 Common, 447 Game Design, 115 Game Logic), plus five non-PostgreSQL Game Logic integrations. All 130 PostgreSQL definitions compile but skip without Docker (126 Game Design and four Game Logic). Affected full checks, formatting, static analysis, coverage, two boot JARs, links and Markdown pass; unchanged outputs are reused. The separate selection binding preserves `publicationDigestRequest/v1`, bounds its three exact byte-length frames, and freezes a literal preimage digest. The receiver requires the actual retained Game Logic terminal and derives both aggregate and dedicated ability-schema evidence; its default deployment remains denied until explicit provider composition and activation proof. Game Design's strict receipt-bound consumer, exact immutable receipt lookup and canonical selected publish-gate are connected. Missing receipt evidence leaves publication pending; conflicts deny, and no tenant/version-only fallback returns a positive digest. The unregistered intake command invokes the real configured Account producer before Game Logic retention and Account settlement; its unit tests use mocks, not genuine cross-owner provenance. R206/R207 corrected binding fixture, decoder-boundary, constructor and formatting defects; R210 corrected two ambiguous fixture argument reads, and R211/R212 isolated the gate's constructor-finalizer safety issue before R213. Genuine authored-source-to-receipt physical proof, complete release/settlement and runtime activation remain open. +The bounded GD+World source/APPLIED/original terminal-settlement path has executed PostgreSQL proof, including lost acknowledgement and unknown-outcome recovery, as recorded below. The later construction adds fresh creation-receipt-backed normalized template phase, immutable selected export candidates with actual-byte object readback, the closed Account-gated Game Session association read and exact descriptor projection. Corrected gate R278 passes Common/Game Design full checks, canonical formatting, Checkstyle, SpotBugs, coverage, the Game Design boot JAR and documentation checks. Its reports contain 966 passing units (Common 446, Game Design 520); all 143 Game Design integration cases compile and skip locally without Docker, including the new genuine-source-to-selected-export/descriptor definition. V66 passes schema generation, not physical migration proof. No physical execution credit follows for the new descriptor/export composition from these local runs. + +The selection binding preserves `publicationDigestRequest/v1`; exact retained Game Logic terminal/receipt evidence supplies aggregate and dedicated ability-schema evidence without a tenant/version-only fallback. The next construction composes genuine GD+World source settlement and Account/Game Logic receipt retention with the real selected inventory, candidate/export and Game Design-local publication finalizer, followed by exact association-derived descriptor storage and replay. Its PostgreSQL definition still stipulates selected-publication Account/freeze/inventory admission and participant collection; S3 transport and the StartSession Account projection are explicit test doubles. It is not complete four-owner publication or authenticated positive runtime launch proof. V66 retains the original operation tuple, attempt/fence, exact association, selected Game Logic receipt and release alongside the descriptor. The separate protected exact-replay adapter remains unregistered, as does the earlier association reader. Complete release/settlement, authenticated descriptor/consumer and World held-authority handoffs, and runtime activation remain open. Account's separate confirmation-WAL denial is an admission proof gap, not grounds to weaken source or release guards. + +Published `c9bf6778fe21c39045af5e6bacde850272cc2d78` [Validation run 37928625721](https://github.com/benhook1013/FireMUD/actions/runs/37928625721) executed Game Design's 510 units and 145 PostgreSQL cases, with nine PostgreSQL fixture failures and zero skips. All four template-phase cases, the selected template/source association case and all three genuine GD+World source/APPLIED/original-settlement cases passed. World executed 207 PostgreSQL cases successfully with zero skips, including its corrected workflow fixture. Account's 1,109 units passed; its 254 PostgreSQL cases executed with one separate confirmation-WAL coverage denial and zero skips, and its dedicated 31 Draft-fence cases passed. The bounded Game Design corrections fix an isolated-schema JDBC delimiter, missing request-bound export fixture candidates and noncanonical timestamp precision without weakening guards. Corrected-head PostgreSQL execution remains required. The confirmed synthetic checkout is `061ae1ba1d4594166dee426fe2c0c7ca6ea5b3f0`; retained artifacts do not establish its tree or ordered parents, so this is not intended-parent alignment proof. Published `9bc14c9c2e376ca66c5fed7257116750a35ab806` [Validation run 37890757405](https://github.com/benhook1013/FireMUD/actions/runs/37890757405) executed 252 Account PostgreSQL cases with one admission-confirmation WAL-coverage denial and zero skips. The corrected intake environment-change and canonical post-abort cases passed. Game Design's 126 and World's 206 PostgreSQL cases passed with zero skips; Game Logic's job passed without accessible exact integration counts. Dev Tool Contract Checks separately failed the dev-demo waiter's expected missing-namespace-head diagnostic. Both failures are under focused adjudication; neither passing storage suites nor conservative denial establishes final handoff, deployment or activation proof. diff --git a/protos/game-design/v1/start_session_template_association_service.proto b/protos/game-design/v1/start_session_template_association_service.proto index ef90bce1d4..c183cf045a 100644 --- a/protos/game-design/v1/start_session_template_association_service.proto +++ b/protos/game-design/v1/start_session_template_association_service.proto @@ -17,6 +17,14 @@ service GameDesignStartSessionTemplateAssociationReadService { returns (ReadStartSessionTemplateAssociationResponse); } +// Standalone exact-replay descriptor projection for the existing authorized StartSession flow. +// The server authenticates the same-namespace Game Session workload before decoding or invoking +// the producer. This service is deliberately separate from the read-only association service. +service GameDesignStartSessionLaunchDescriptorService { + rpc ResolveStartSessionLaunchDescriptor(ReadStartSessionTemplateAssociationRequest) + returns (ResolveStartSessionLaunchDescriptorResponse); +} + message ReadStartSessionTemplateAssociationRequest { int32 schema_version = 1; string target_namespace = 2; @@ -57,6 +65,21 @@ message ReadStartSessionTemplateAssociationResponse { int64 reference_phase_epoch = 5; } +// Closed versioned result for one exact Game Session-pinned association replay. The association +// read is included unchanged as the source binding for either outcome. Exactly one of +// launch_descriptor and application_failure must be present. +message ResolveStartSessionLaunchDescriptorResponse { + int32 schema_version = 1; + ReadStartSessionTemplateAssociationResponse association_read = 2; + gamedesign.v1.LaunchDescriptor launch_descriptor = 3; + StartSessionLaunchDescriptorApplicationFailure application_failure = 4; +} + +message StartSessionLaunchDescriptorApplicationFailure { + string code = 1; + string message = 2; +} + // Closed public projection of the immutable Game Design association. Private operation, // capture, template snapshot, entry, and canonical-association bytes never cross this API. message StartSessionTemplateWorldSourceAssociationEvidence { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java index 00d01b3410..ac1740309d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java @@ -254,6 +254,20 @@ private static LaunchDescriptor toLaunchDescriptor( .build(); } + /** Public closed wrapper for contracts that carry the canonical launch descriptor message. */ + public static LaunchDescriptor toLaunchDescriptorMessage( + AuthoredWorldLaunchDescriptorEvidence evidence) { + return toLaunchDescriptor(Objects.requireNonNull(evidence, "evidence")); + } + + /** Decodes the existing closed descriptor grammar and binds it to an exact resolve request. */ + public static AuthoredWorldLaunchDescriptorEvidence fromLaunchDescriptorMessage( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, LaunchDescriptor descriptor) { + return decodeDescriptor( + Objects.requireNonNull(expectedRequest, "expectedRequest"), + Objects.requireNonNull(descriptor, "descriptor")); + } + /** Encodes the separate closed release attestation without changing descriptor/v1. */ public static net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence toReleaseAttestation(AuthoredWorldReleaseAttestationEvidence evidence) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java new file mode 100644 index 0000000000..0445572e45 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java @@ -0,0 +1,239 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.StartSessionLaunchDescriptorApplicationFailure; + +/** Closed request/result mapping for the exact-replay StartSession descriptor projection. */ +public final class StartSessionLaunchDescriptorGrpcCodec { + public static final int RESPONSE_SCHEMA_VERSION = 1; + private static final String EMPTY_RUNTIME_FLAGS = "{}"; + private static final Set FAILURE_CODES = + Set.of( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", + "INVALID_TEMPLATE_CONFIGURATION", + "SCRIPT_PATCH_OVERRIDE_CONFLICT", + "SCRIPT_PATCH_NOT_READY", + "RELEASE_BUNDLE_NOT_FOUND", + "RELEASE_ATTESTATION_MISMATCH", + "VERSION_STATE_EPOCH_STALE", + "LAUNCH_REMAP_REQUIRED"); + + private StartSessionLaunchDescriptorGrpcCodec() {} + + public sealed interface Outcome permits DescriptorOutcome, ApplicationFailure {} + + public record DescriptorOutcome(AuthoredWorldLaunchDescriptorEvidence descriptor) + implements Outcome { + public DescriptorOutcome { + Objects.requireNonNull(descriptor, "descriptor"); + } + } + + /** A persisted domain denial; transport and dependency failures are not represented here. */ + public record ApplicationFailure(String code, String message) implements Outcome { + public ApplicationFailure { + Objects.requireNonNull(code, "code"); + Objects.requireNonNull(message, "message"); + if (!FAILURE_CODES.contains(code) + || message.length() > 1024 + || !message.startsWith(code + ": ")) { + throw new IllegalArgumentException("Known deterministic StartSession failure required"); + } + } + } + + /** Validated association evidence paired with exactly one descriptor outcome. */ + public record Resolved(Result associationRead, Outcome outcome) { + public Resolved { + Objects.requireNonNull(associationRead, "associationRead"); + Objects.requireNonNull(outcome, "outcome"); + } + } + + /** + * The descriptor endpoint accepts exact replay only; initial selection remains a separate read. + */ + public static ReadStartSessionTemplateAssociationRequest toRequest(Request request) { + requireExactReplay(request); + return StartSessionTemplateAssociationReadGrpcCodec.toRequest(request); + } + + /** Decode the reused association request and reject initial or absent selection modes. */ + public static Request fromRequest(ReadStartSessionTemplateAssociationRequest request) { + Request decoded = StartSessionTemplateAssociationReadGrpcCodec.fromRequest(request); + requireExactReplay(decoded); + return decoded; + } + + public static ResolveStartSessionLaunchDescriptorResponse toDescriptorResponse( + Request expectedRequest, + Result associationRead, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return toResponse( + expectedRequest, + associationRead, + new DescriptorOutcome(Objects.requireNonNull(descriptor))); + } + + public static ResolveStartSessionLaunchDescriptorResponse toFailureResponse( + Request expectedRequest, Result associationRead, String code, String message) { + return toResponse(expectedRequest, associationRead, new ApplicationFailure(code, message)); + } + + /** Encodes one complete result and runs the same closed decoder used by receiving callers. */ + public static ResolveStartSessionLaunchDescriptorResponse toResponse( + Request expectedRequest, Result associationRead, Outcome outcome) { + requireAssociationBinding(expectedRequest, associationRead); + Objects.requireNonNull(outcome, "outcome"); + var builder = + ResolveStartSessionLaunchDescriptorResponse.newBuilder() + .setSchemaVersion(RESPONSE_SCHEMA_VERSION) + .setAssociationRead( + StartSessionTemplateAssociationReadGrpcCodec.toResponse(associationRead)); + if (outcome instanceof DescriptorOutcome descriptorOutcome) { + requireDescriptorBinding(expectedRequest, associationRead, descriptorOutcome.descriptor()); + builder.setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + descriptorOutcome.descriptor())); + } else if (outcome instanceof ApplicationFailure failure) { + builder.setApplicationFailure( + StartSessionLaunchDescriptorApplicationFailure.newBuilder() + .setCode(failure.code()) + .setMessage(failure.message())); + } else { + throw new IllegalArgumentException("Unsupported StartSession descriptor outcome"); + } + ResolveStartSessionLaunchDescriptorResponse response = builder.build(); + fromResponse(expectedRequest, response); + return response; + } + + /** Validates the complete nested association read and exact descriptor or stored denial. */ + public static Resolved fromResponse( + Request expectedRequest, ResolveStartSessionLaunchDescriptorResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireExactReplay(expectedRequest); + requireNoUnknownFields(response, "ResolveStartSessionLaunchDescriptorResponse"); + if (response.getSchemaVersion() != RESPONSE_SCHEMA_VERSION + || !response.hasAssociationRead() + || response.hasLaunchDescriptor() == response.hasApplicationFailure()) { + throw new IllegalArgumentException( + "Versioned StartSession descriptor response must contain one complete outcome"); + } + Result associationRead = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + expectedRequest, response.getAssociationRead()); + requireAssociationBinding(expectedRequest, associationRead); + Outcome outcome; + if (response.hasLaunchDescriptor()) { + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + expectedDescriptorRequest(expectedRequest, associationRead.association()), + response.getLaunchDescriptor()); + requireDescriptorBinding(expectedRequest, associationRead, descriptor); + outcome = new DescriptorOutcome(descriptor); + } else { + var failure = response.getApplicationFailure(); + requireNoUnknownFields(failure, "StartSessionLaunchDescriptorApplicationFailure"); + outcome = new ApplicationFailure(failure.getCode(), failure.getMessage()); + } + return new Resolved(associationRead, outcome); + } + + private static void requireAssociationBinding(Request expectedRequest, Result associationRead) { + requireExactReplay(expectedRequest); + Objects.requireNonNull(associationRead, "associationRead"); + if (!expectedRequest.equals(associationRead.request())) { + throw new IllegalArgumentException( + "Association read differs from the exact StartSession request"); + } + } + + private static void requireDescriptorBinding( + Request request, Result associationRead, AuthoredWorldLaunchDescriptorEvidence descriptor) { + Objects.requireNonNull(descriptor, "descriptor"); + descriptor.requireValid(); + var association = associationRead.association(); + if (!expectedDescriptorRequest(request, association).equals(descriptor.request())) { + throw new IllegalArgumentException( + "Launch descriptor request differs from the original StartSession tuple and association"); + } + var release = associationRead.releaseBundle(); + if (release.getIsScriptOnly() + || !release.getScriptPatchVersion().isEmpty() + || descriptor.scriptPatchVersionPresent() + || descriptor.remapSetIdPresent() + || !EMPTY_RUNTIME_FLAGS.equals(descriptor.runtimeFlagsJson()) + || descriptor.versionId() != release.getVersionId() + || descriptor.releaseBundleId() != release.getId() + || !descriptor.publishedReleaseBundleRef().equals(release.getPublishedReleaseBundleRef()) + || !descriptor.generationConfigRevision().equals(release.getGenerationConfigRevision()) + || !descriptor.canonicalTenantId().toString().equals(release.getCanonicalTenantId()) + || !association.canonicalVersionId().toString().equals(release.getCanonicalVersionId()) + || !association.publishWorkflowId().equals(release.getPublishWorkflowId())) { + throw new IllegalArgumentException( + "Launch descriptor version or release differs from the exact association response"); + } + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request expectedDescriptorRequest( + Request request, StartSessionTemplateAssociationReadEvidence.Association association) { + var action = request.decodedTuple().preAuthorizationTuple().action(); + if (!action.scope().tenantId().equals(association.canonicalTenantId()) + || action.target().gameTemplateId() != association.templateId() + || !request.targetNamespace().equals(association.targetNamespace())) { + throw new IllegalArgumentException( + "Association differs from the original authorized StartSession target"); + } + return new AuthoredWorldLaunchDescriptorEvidence.Request( + request.targetNamespace(), + request.decodedTuple().controlPlaneRequestId(), + association.canonicalTenantId(), + association.worldSlug(), + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.templateId(), + false, + null, + false, + null, + false, + null, + true, + EMPTY_RUNTIME_FLAGS); + } + + private static void requireExactReplay(Request request) { + Objects.requireNonNull(request, "request"); + if (!(request.selection() instanceof ExactReplay)) { + throw new IllegalArgumentException("Exact Game Session-pinned association replay required"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) continue; + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java new file mode 100644 index 0000000000..2be666331d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java @@ -0,0 +1,527 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +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.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.StartSessionLaunchDescriptorApplicationFailure; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionLaunchDescriptorGrpcCodecTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID REGISTRATION_ID = uuid("03333333-3333-4333-8333-333333333333"); + private static final UUID INTAKE_ID = uuid("04444444-4444-4444-8444-444444444444"); + private static final UUID WORLD_OPERATION_ID = uuid("05555555-5555-4555-8555-555555555555"); + private static final UUID SOURCE_OPERATION_ID = uuid("06666666-6666-4666-8666-666666666666"); + private static final UUID WORLD_READ_ID = uuid("07777777-7777-4777-8777-777777777777"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "test"; + private static final String WORLD_SLUG = "synthetic-world"; + private static final String CONTROL_PLANE_REQUEST_ID = "original-control-plane-request"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void exactReplayCarriesItsOriginalAssociationAndDescriptorWithoutUsingReadIdAsOperationId() + throws Exception { + Fixture fixture = fixture(); + var wireRequest = StartSessionLaunchDescriptorGrpcCodec.toRequest(fixture.request()); + var response = + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), fixture.descriptor()); + + var decoded = StartSessionLaunchDescriptorGrpcCodec.fromResponse(fixture.request(), response); + + assertThat(StartSessionLaunchDescriptorGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(fixture.request()); + assertThat(decoded.associationRead().request()).isEqualTo(fixture.request()); + assertThat(decoded.associationRead().request().readRequestId()) + .isNotEqualTo(fixture.descriptor().controlPlaneRequestId()); + assertThat( + ((StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome) decoded.outcome()) + .descriptor()) + .isEqualTo(fixture.descriptor()); + assertThat(response.getAssociationRead().getRequest().getExactReplay().getAssociationDigest()) + .isEqualTo(fixture.associationRead().association().associationDigest()); + } + + @Test + void rejectsInitialSelectionPartialMixedUnknownAndWrongVersionResponses() throws Exception { + Fixture fixture = fixture(); + var exact = StartSessionLaunchDescriptorGrpcCodec.toRequest(fixture.request()); + var initial = + exact.toBuilder() + .clearSelection() + .setInitialConfigured( + net.firedevops.firemud.gamedesign.v1.StartSessionConfiguredTemplateSelection + .getDefaultInstance()) + .build(); + assertThatThrownBy(() -> StartSessionLaunchDescriptorGrpcCodec.fromRequest(initial)) + .isInstanceOf(IllegalArgumentException.class); + + var complete = + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), fixture.descriptor()); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), complete.toBuilder().clearLaunchDescriptor().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), + complete.toBuilder() + .setApplicationFailure( + StartSessionLaunchDescriptorApplicationFailure.newBuilder() + .setCode("INVALID_TEMPLATE_CONFIGURATION") + .setMessage( + "INVALID_TEMPLATE_CONFIGURATION: captured source unavailable")) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), complete.toBuilder().setSchemaVersion(2).build())) + .isInstanceOf(IllegalArgumentException.class); + + var unknown = + complete.toBuilder() + .setAssociationRead( + complete.getAssociationRead().toBuilder() + .setAssociation( + complete.getAssociationRead().getAssociation().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 88, + UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> StartSessionLaunchDescriptorGrpcCodec.fromResponse(fixture.request(), unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var unknownDescriptorBinding = + complete.toBuilder() + .setLaunchDescriptor( + complete.getLaunchDescriptor().toBuilder() + .setAuthoredWorldBinding( + complete.getLaunchDescriptor().getAuthoredWorldBinding().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 89, + UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), unknownDescriptorBinding)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + @Test + void roundTripsAClosedCorrelatedApplicationFailureWireOutcome() throws Exception { + // Codec evidence only; constructing this value does not prove a producer persisted it. + Fixture fixture = fixture(); + String code = "INVALID_TEMPLATE_CONFIGURATION"; + String message = code + ": captured template has unsupported owner references"; + var response = + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + fixture.request(), fixture.associationRead(), code, message); + + var decoded = StartSessionLaunchDescriptorGrpcCodec.fromResponse(fixture.request(), response); + + assertThat(decoded.associationRead().request()).isEqualTo(fixture.request()); + assertThat(decoded.outcome()) + .isEqualTo(new StartSessionLaunchDescriptorGrpcCodec.ApplicationFailure(code, message)); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + fixture.request(), fixture.associationRead(), "UNAVAILABLE", "unavailable")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsDescriptorFieldsThatDoNotMatchTheOriginalAssociationAndRelease() throws Exception { + Fixture fixture = fixture(); + var original = fixture.descriptor(); + var alteredRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + original.targetNamespace(), + original.controlPlaneRequestId(), + original.canonicalTenantId(), + "substituted-world", + original.authoredWorldSourceOperationId(), + original.authoredWorldSourceEvidenceDigest(), + original.gameTemplateId(), + false, + null, + false, + null, + false, + null, + true, + "{}"); + var substituted = + AuthoredWorldLaunchDescriptorEvidence.create( + alteredRequest, + original.launchDescriptorId(), + original.versionId(), + false, + null, + "{}", + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + false, + null); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("original StartSession tuple and association"); + + var substitutedVersion = + AuthoredWorldLaunchDescriptorEvidence.create( + original.request(), + original.launchDescriptorId(), + original.versionId() + 1L, + false, + null, + "{}", + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + false, + null); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), substitutedVersion)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("version or release"); + + var changedRuntimeFlags = + AuthoredWorldLaunchDescriptorEvidence.create( + original.request(), + original.launchDescriptorId(), + original.versionId(), + false, + null, + "{\"runtime\":true}", + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + false, + null); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), changedRuntimeFlags)) + .isInstanceOf(IllegalArgumentException.class); + + var response = + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), original); + var changedFlatVersion = + response.toBuilder() + .setLaunchDescriptor( + response.getLaunchDescriptor().toBuilder() + .setVersionId(response.getLaunchDescriptor().getVersionId() + 1L) + .build()) + .build(); + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), changedFlatVersion)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Fixture fixture() throws Exception { + var worldEvidence = AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); + UUID canonicalVersion = worldEvidence.request().canonicalVersionId(); + UUID selectedCommit = uuid(worldEvidence.request().appliedCommitId()); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, REGISTRATION_ID, TENANT, "tenant-key", WORLD_SLUG, "Synthetic World"); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + REGISTRATION_ID, + SOURCE_OPERATION_ID, + sourceRequestDigest, + TENANT, + "tenant-key", + WORLD_SLUG, + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + var source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + REGISTRATION_ID, + SOURCE_OPERATION_ID, + sourceRequestDigest, + TENANT, + "tenant-key", + WORLD_SLUG, + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW", + sourceEvidenceDigest); + var intake = + new IntakeRequest( + 1, NAMESPACE, INTAKE_ID, TENANT, WORLD_SLUG, SOURCE_OPERATION_ID, sourceEvidenceDigest); + var receipt = + new PublicReceipt( + 1, + NAMESPACE, + INTAKE_ID, + WORLD_OPERATION_ID, + TENANT, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidenceDigest, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intake), + digest('e'), + source); + var association = + new StartSessionTemplateAssociationReadEvidence.Association( + TENANT, + 91L, + canonicalVersion, + selectedCommit, + worldEvidence.request().publishWorkflowId(), + digest('c'), + digest('a'), + NAMESPACE, + INTAKE_ID, + WORLD_OPERATION_ID, + SOURCE_OPERATION_ID, + WORLD_SLUG, + sourceEvidenceDigest, + new ByIdReadRequest(1, NAMESPACE, WORLD_READ_ID, INTAKE_ID, TENANT), + receipt); + Request request = + new Request( + 1, + NAMESPACE, + READ_ID, + postTuple().canonicalBytes(), + ATTEMPT, + 8L, + new ExactReplay( + canonicalVersion, + selectedCommit, + worldEvidence.request().publishWorkflowId(), + association.associationDigest())); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + CONTROL_PLANE_REQUEST_ID, + TENANT, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidenceDigest, + 91L, + false, + null, + false, + null, + false, + null, + true, + "{}"); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "descriptor-1", + 42L, + false, + null, + "{}", + "generation", + 9L, + 7L, + "release-1", + false, + null); + var releaseEvidence = + AuthoredWorldReleaseAttestationSelectorTest.release(descriptor, worldEvidence); + PublishedReleaseBundle.Builder release = + PublishedReleaseBundle.newBuilder() + .setId(7L) + .setVersionId(42L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v2") + .setPublishWorkflowId(worldEvidence.request().publishWorkflowId()) + .setManifestHash(releaseEvidence.manifestHash()) + .setManifestSchemaVersion(releaseEvidence.manifestSchemaVersion()) + .addAllRequiredManifestAssetKeys(releaseEvidence.requiredManifestAssetKeys()) + .setGenerationConfigRevision(releaseEvidence.generationConfigRevision()) + .setPublishedReleaseBundleRef(releaseEvidence.publishedReleaseBundleRef()) + .setCanonicalTenantId(TENANT.toString()) + .setCanonicalVersionId(canonicalVersion.toString()) + .addAllCommandDefinitions(releaseEvidence.commandDefinitions()); + for (var participant : releaseEvidence.participantDigests()) { + ParticipantDigest.Builder participantMessage = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigestPresent()) { + participantMessage.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + } + release.addParticipantDigests(participantMessage); + } + Result associationRead = new Result(request, association, release.build(), worldEvidence, 23L); + return new Fixture(request, associationRead, descriptor); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple() { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + CONTROL_PLANE_REQUEST_ID, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact StartSession descriptor selection")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", TENANT.toString(), "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", TENANT.toString()), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(TENANT.toString(), 3L), + "membershipAuthorityGeneration", Map.of(TENANT.toString(), 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(TENANT.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + Request request, Result associationRead, AuthoredWorldLaunchDescriptorEvidence descriptor) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcService.java new file mode 100644 index 0000000000..ec1f4dcb56 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcService.java @@ -0,0 +1,144 @@ +package net.firedevops.firemud.gamedesign.draft; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.publication.StartSessionLaunchDescriptorProducer; +import net.firedevops.firemud.gamedesign.v1.GameDesignStartSessionLaunchDescriptorServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; + +/** Standalone authenticated StartSession descriptor adapter; deliberately not registered. */ +public final class GameDesignStartSessionLaunchDescriptorGrpcService + extends GameDesignStartSessionLaunchDescriptorServiceGrpc + .GameDesignStartSessionLaunchDescriptorServiceImplBase { + private final StartSessionLaunchDescriptorProducer producer; + private final String workloadNamespace; + + public GameDesignStartSessionLaunchDescriptorGrpcService( + StartSessionLaunchDescriptorProducer producer, String workloadNamespace) { + this.producer = Objects.requireNonNull(producer, "producer"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void resolveStartSessionLaunchDescriptor( + ReadStartSessionTemplateAssociationRequest request, + StreamObserver observer) { + try { + requirePeer(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final Request decoded; + try { + decoded = StartSessionLaunchDescriptorGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Exact StartSession template association replay required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("StartSession target namespace differs from the Game Design peer") + .asRuntimeException()); + return; + } + + try { + StartSessionLaunchDescriptorProducer.ResolvedBinding binding = producer.resolve(decoded); + if (!decoded.equals(binding.request())) { + throw new IllegalArgumentException("Producer changed the exact StartSession request"); + } + ResolvedLaunchDescriptorDto descriptor = binding.descriptor(); + AuthoredWorldLaunchDescriptorEvidence evidence = descriptor.authoredWorldBinding(); + requireDtoMatchesEvidence(descriptor, evidence); + observer.onNext( + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + decoded, binding.associationRead(), evidence)); + observer.onCompleted(); + } catch (StartSessionLaunchDescriptorProducer.StoredBusinessDenial denied) { + try { + observer.onNext( + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + decoded, denied.associationRead(), denied.failureCode(), denied.getMessage())); + observer.onCompleted(); + } catch (RuntimeException invalidDenial) { + observer.onError( + Status.INTERNAL + .withDescription("Stored StartSession denial did not match its exact request") + .asRuntimeException()); + } + } catch (StatusRuntimeException failure) { + Status status = Status.fromThrowable(failure); + observer.onError( + Status.fromCode(status.getCode()) + .withDescription("StartSession launch descriptor owner read denied or unavailable") + .asRuntimeException()); + } catch (IllegalArgumentException invalidResult) { + observer.onError( + Status.INTERNAL + .withDescription("Game Design returned an invalid StartSession launch descriptor") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Design StartSession launch descriptor is unavailable") + .asRuntimeException()); + } + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + } + + private static void requireDtoMatchesEvidence( + ResolvedLaunchDescriptorDto descriptor, AuthoredWorldLaunchDescriptorEvidence evidence) { + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(evidence, "authoredWorldBinding"); + if (!Objects.equals(descriptor.launchDescriptorId(), evidence.launchDescriptorId()) + || !Objects.equals(descriptor.canonicalTenantId(), evidence.canonicalTenantId().toString()) + || descriptor.gameTemplateId() != evidence.gameTemplateId() + || !Objects.equals(descriptor.controlPlaneRequestId(), evidence.controlPlaneRequestId()) + || descriptor.versionId() != evidence.versionId() + || !Objects.equals( + descriptor.scriptPatchVersion(), + evidence.scriptPatchVersionPresent() ? evidence.scriptPatchVersion() : null) + || !Objects.equals(descriptor.runtimeFlagsJson(), evidence.runtimeFlagsJson()) + || !Objects.equals( + descriptor.generationConfigRevision(), evidence.generationConfigRevision()) + || descriptor.versionStateEpoch() != evidence.versionStateEpoch() + || descriptor.releaseBundleId() != evidence.releaseBundleId() + || !Objects.equals( + descriptor.publishedReleaseBundleRef(), evidence.publishedReleaseBundleRef()) + || !Objects.equals( + descriptor.remapSetId(), evidence.remapSetIdPresent() ? evidence.remapSetId() : null)) { + throw new IllegalArgumentException("Resolved descriptor DTO differs from closed evidence"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java new file mode 100644 index 0000000000..6efe988911 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java @@ -0,0 +1,1112 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository.Binding; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.ObjectMapper; + +/** + * Standalone fresh StartSession descriptor producer. It is intentionally not a Spring bean or a + * runtime selector: the only accepted input is an exact association replay already pinned by Game + * Session, and the Account-gated owner reader runs before the descriptor write transaction. + */ +public final class StartSessionLaunchDescriptorProducer { + private static final String RUNTIME_SURFACE_EMPTY_V1 = "EMPTY_V1"; + private static final String RUNTIME_SURFACE_UNSUPPORTED_CAPTURE_V1 = "UNSUPPORTED_CAPTURE_V1"; + private static final String EMPTY_RUNTIME_FLAGS = "{}"; + private static final String INVALID_TEMPLATE_CONFIGURATION = "INVALID_TEMPLATE_CONFIGURATION"; + private static final String UNSUPPORTED_CAPTURE_MESSAGE = + "INVALID_TEMPLATE_CONFIGURATION: captured template has unsupported World, Entity, or Automation references"; + + private final DSLContext dsl; + private final String workloadNamespace; + private final StartSessionTemplateAssociationReadService associationReader; + private final GameAuthoredWorldSourceRepository authoredWorldSources; + private final LaunchDescriptorRepository descriptors; + private final StartSessionLaunchDescriptorRepository bindings; + private final VersionRepository versions; + private final TemplateReferenceRepository templateReferences; + private final GameDesignPublicationOperationRepository publicationOperations; + private final GameDesignSourceRepository sourceRepository; + private final SelectedDraftTemplateWorldSourceAssociationRepository associations; + private final PublishedReleaseBundleService releases; + private final ObjectMapper objectMapper; + private final TransactionTemplate writeTransaction; + + /** + * Production construction accepts only the concrete Account-gated same-namespace owner reader. No + * caller-supplied association, Version, or release can enter this path. + */ + public StartSessionLaunchDescriptorProducer( + DSLContext dsl, + PlatformTransactionManager transactions, + String workloadNamespace, + StartSessionTemplateAssociationReadService associationReader, + PublishedReleaseBundleService releases, + ObjectMapper objectMapper) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + this.associationReader = Objects.requireNonNull(associationReader, "associationReader"); + this.releases = Objects.requireNonNull(releases, "releases"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + authoredWorldSources = new GameAuthoredWorldSourceRepository(dsl); + descriptors = new LaunchDescriptorRepository(dsl); + bindings = new StartSessionLaunchDescriptorRepository(dsl); + versions = new VersionRepository(dsl); + templateReferences = new TemplateReferenceRepository(dsl); + publicationOperations = new GameDesignPublicationOperationRepository(dsl); + sourceRepository = new GameDesignSourceRepository(dsl); + associations = new SelectedDraftTemplateWorldSourceAssociationRepository(dsl); + writeTransaction = + new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + writeTransaction.setName("game-design-start-session-launch-descriptor"); + writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + writeTransaction.setReadOnly(false); + } + + /** Reads the current Account projection, then stores or exactly replays one pinned descriptor. */ + public ResolvedBinding resolve(Request request) { + requirePeer(); + Objects.requireNonNull(request, "request"); + if (!(request.selection() instanceof ExactReplay)) { + throw Status.INVALID_ARGUMENT + .withDescription("An exact Game Session-pinned association replay is required") + .asRuntimeException(); + } + if (!workloadNamespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("StartSession target namespace differs from the Game Design peer") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Account projection and owner descriptor writes require independent transactions") + .asRuntimeException(); + } + + // This call performs the independent Account projection read before any local write + // transaction. + Result exact = associationReader.read(request); + requireExactAssociationRead(request, exact); + StartSessionPostAuthorizationExecutionTuple tuple = request.decodedTuple(); + var action = tuple.preAuthorizationTuple().action(); + UUID canonicalTenantId = action.scope().tenantId(); + long templateId = action.target().gameTemplateId(); + Association association = exact.association(); + AuthoredWorldSourceEvidence source = + authoredWorldSources + .read( + association.sourceOperationId(), + canonicalTenantId, + association.worldSlug(), + request.targetNamespace()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Exact registered Game Design source for the association is unavailable") + .asRuntimeException()); + requireSourceMatches(association, source); + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = + descriptorRequest(tuple, association); + String requestJson = writeJson(descriptorRequest); + String sourceJson = writeJson(source); + + OwnerOutcome outcome = + Objects.requireNonNull( + writeTransaction.execute( + ignored -> + writeOrRead( + request, + exact, + descriptorRequest, + requestJson, + source, + sourceJson, + canonicalTenantId, + templateId)), + "StartSession launch descriptor transaction returned no binding"); + if (outcome.failure() != null) { + throw new StoredBusinessDenial(exact, outcome.failure()); + } + return Objects.requireNonNull( + outcome.resolvedBinding(), "Successful descriptor binding is missing"); + } + + private OwnerOutcome writeOrRead( + Request exactRequest, + Result exact, + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest, + String requestJson, + AuthoredWorldSourceEvidence source, + String sourceJson, + UUID canonicalTenantId, + long templateId) { + String controlPlaneRequestId = descriptorRequest.controlPlaneRequestId(); + descriptors.lockBoundRequest(workloadNamespace, canonicalTenantId, controlPlaneRequestId); + Optional storedDescriptor = + descriptors.findBoundByRequest(workloadNamespace, canonicalTenantId, controlPlaneRequestId); + Optional storedBinding = + bindings.find(workloadNamespace, canonicalTenantId, controlPlaneRequestId); + if (storedDescriptor.isPresent() || storedBinding.isPresent()) { + if (storedDescriptor.isEmpty() || storedBinding.isEmpty()) { + throw conflict("Stored descriptor is missing its exact StartSession association binding"); + } + LaunchDescriptor descriptor = storedDescriptor.orElseThrow(); + CapturedTemplate capturedTemplate = requireCapturedTemplate(exact, templateId); + requireBindingMatches( + storedBinding.orElseThrow(), + descriptor, + exactRequest, + exact, + descriptorRequest, + source, + capturedTemplate.gameLogicReceipt()); + if (LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus())) { + if (capturedTemplate.failureMessage() == null) { + throw conflict( + "Stored failed descriptor no longer matches its immutable captured configuration"); + } + FrozenFailure failure = + requireStoredFailure(descriptor, descriptorRequest, requestJson, source, sourceJson); + return OwnerOutcome.failed(failure); + } + if (capturedTemplate.failureMessage() != null) { + throw conflict( + "Stored successful descriptor differs from its immutable captured configuration"); + } + requireSuccessfulDescriptor(descriptor); + ResolvedLaunchDescriptorDto resolved = + readStored(descriptor, descriptorRequest, requestJson, source, sourceJson); + return OwnerOutcome.succeeded(new ResolvedBinding(exactRequest, exact, resolved)); + } + + if (descriptors + .findByPrivateRequest(source.sourceGameTenantKey(), controlPlaneRequestId) + .isPresent()) { + throw conflict( + "Retained private-owner descriptor history is unbound or bound to another canonical identity"); + } + + TemplateReferenceRepository.PhaseSnapshot phase = + templateReferences + .readPhase(canonicalTenantId) + .filter(value -> value.phase() == TemplateReferenceRepository.Phase.ENFORCED) + .filter(value -> value.phaseEpoch() == exact.phaseEpoch()) + .filter( + value -> value.inventoryDigest() != null && value.inventoryTemplateCount() != null) + .filter(value -> value.inventoryTemplateCount() > 0L) + .orElseThrow( + () -> conflict("Current explicit enforced template-reference phase changed")); + if (phase.sourceGameRowId() != source.sourceGameRowId() + || !phase.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !"NEW_GAME_ROW".equals(phase.provenanceKind()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw conflict("Exact source and fresh tenant phase provenance differ"); + } + + Version selectedVersion = + versions + .findByCanonicalTenantIdAndCanonicalVersionId( + canonicalTenantId, exact.association().canonicalVersionId()) + .orElseThrow(() -> conflict("Exact selected canonical Version is unavailable")); + lockAndReloadSelectedVersion( + selectedVersion, canonicalTenantId, exact.association().canonicalVersionId()); + Version version = + versions + .findByCanonicalTenantIdAndCanonicalVersionId( + canonicalTenantId, exact.association().canonicalVersionId()) + .orElseThrow( + () -> conflict("Exact selected canonical Version disappeared after locking")); + if (!Objects.equals(selectedVersion.getId(), version.getId())) { + throw conflict("Canonical Version row identity changed while locking the exact selection"); + } + requireLaunchableVersion(version, source, phase, exact.association()); + PublishedReleaseBundleDto release = + releases + .findPublishedReleaseBundle(version.getTenantId(), version.getId()) + .orElseThrow(() -> conflict("Exact selected immutable release bundle is unavailable")); + requireReleaseMatches(exact, release, version); + CapturedTemplate capturedTemplate = requireCapturedTemplate(exact, templateId); + String unsupportedCapture = capturedTemplate.failureMessage(); + long versionStateEpoch = + Objects.requireNonNull(version.getVersionStateEpoch(), "versionStateEpoch"); + + boolean deterministicFailure = unsupportedCapture != null; + LaunchDescriptor candidate; + if (deterministicFailure) { + candidate = + frozenFailure( + descriptorRequest, + source, + requestJson, + sourceJson, + INVALID_TEMPLATE_CONFIGURATION, + UNSUPPORTED_CAPTURE_MESSAGE); + } else { + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "ld-" + UUID.randomUUID(), + version.getId(), + false, + null, + EMPTY_RUNTIME_FLAGS, + release.generationConfigRevision(), + versionStateEpoch, + release.id(), + release.publishedReleaseBundleRef(), + false, + null); + candidate = descriptorRow(evidence, source, requestJson, sourceJson); + } + LaunchDescriptor persisted = descriptors.insertImmutable(candidate); + if (deterministicFailure) { + requireStoredFailure(persisted, descriptorRequest, requestJson, source, sourceJson); + } else { + requireSuccessfulDescriptor(persisted); + } + String runtimeSurface = + deterministicFailure ? RUNTIME_SURFACE_UNSUPPORTED_CAPTURE_V1 : RUNTIME_SURFACE_EMPTY_V1; + Binding inserted = + binding( + exactRequest, + exact, + persisted.getId(), + Objects.requireNonNull(release.id(), "release.id"), + versionStateEpoch, + runtimeSurface, + capturedTemplate.gameLogicReceipt()); + Binding persistedBinding = bindings.insertImmutable(inserted); + requireBindingMatches( + persistedBinding, + persisted, + exactRequest, + exact, + descriptorRequest, + source, + capturedTemplate.gameLogicReceipt()); + if (deterministicFailure) { + return OwnerOutcome.failed( + new FrozenFailure(INVALID_TEMPLATE_CONFIGURATION, UNSUPPORTED_CAPTURE_MESSAGE)); + } + ResolvedLaunchDescriptorDto resolved = + readStored(persisted, descriptorRequest, requestJson, source, sourceJson); + return OwnerOutcome.succeeded(new ResolvedBinding(exactRequest, exact, resolved)); + } + + private CapturedTemplate requireCapturedTemplate(Result exact, long templateId) { + var readback = + publicationOperations + .read(exact.association().publishWorkflowId()) + .orElseThrow(() -> conflict("Exact selected publication operation is unavailable")); + var operation = readback.operation(); + var selection = operation.account().input().selection(); + if (!"PUBLISHED".equals(readback.outcome()) + || !operation.workflowId().equals(exact.association().publishWorkflowId()) + || !operation.tenantKey().equals(selection.target().gameDesignVersionTenantKey()) + || operation.versionId() != selection.target().gameDesignVersionRowId() + || !selection.target().canonicalTenantId().equals(exact.association().canonicalTenantId()) + || !selection.target().canonicalVersionId().equals(exact.association().canonicalVersionId()) + || !selection.selectedCommit().commitId().equals(exact.association().selectedCommitId()) + || readback.terminalEvidenceBytes() == null) { + throw conflict("Published owner operation differs from the pinned association"); + } + GameDesignPublicationTerminalEvidence terminal = + GameDesignPublicationTerminalEvidence.fromStored(readback.terminalEvidenceBytes()); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operation.canonicalBytes()) + || terminal.releaseContent() == null + || terminal.publicationVersionStateEpoch() <= 0L) { + throw conflict("Exact selected publication terminal evidence is incomplete"); + } + GameDesignSourceRepository.Capture capture = + sourceRepository + .readCapture(operation) + .orElseThrow( + () -> conflict("Complete exact publication source capture is unavailable")); + var templateCapture = capture.templateConfig(); + if (!templateCapture.snapshot().binding().equals(selection.selectedCommit())) { + throw conflict("Selected template capture differs from the original committed source"); + } + List entries = + templateCapture.snapshot().entries().stream() + .filter(entry -> Long.parseLong(entry.templateId()) == templateId) + .toList(); + if (entries.size() != 1) { + throw conflict("Exact selected template is missing or duplicated in the committed capture"); + } + GameLogicReceiptBinding gameLogicReceipt = requireSelectedGameLogicReceipt(operation); + TemplateConfigSource.Entry entry = entries.getFirst(); + if (!entry.config().baseVersionId().equals(exact.association().canonicalVersionId())) { + throw conflict("Original captured template base differs from the pinned selected Version"); + } + String unsupported = null; + try { + entry.config().requireAvailableOwnerReads(); + } catch (IllegalStateException unavailableOwner) { + if (!List.of( + "TEMPLATE_CONFIG_WORLD_EXACT_OWNER_READ_UNAVAILABLE", + "TEMPLATE_CONFIG_ENTITY_EXACT_OWNER_READ_UNAVAILABLE", + "TEMPLATE_CONFIG_AUTOMATION_EXACT_OWNER_READ_UNAVAILABLE") + .contains(unavailableOwner.getMessage())) { + throw conflict("Captured template owner-reference validation is unavailable"); + } + unsupported = UNSUPPORTED_CAPTURE_MESSAGE; + } + + List exactRows = + associations.readExact(operation, templateCapture).stream() + .filter(value -> value.templateId() == templateId) + .toList(); + if (exactRows.size() != 1) { + throw conflict("Exact immutable selected template/source association is unavailable"); + } + var row = exactRows.getFirst(); + Association publicAssociation = exact.association(); + if (!row.canonicalTenantId().equals(publicAssociation.canonicalTenantId()) + || row.templateId() != publicAssociation.templateId() + || !row.canonicalVersionId().equals(publicAssociation.canonicalVersionId()) + || !row.selectedCommitId().equals(publicAssociation.selectedCommitId()) + || !row.publishWorkflowId().equals(publicAssociation.publishWorkflowId()) + || !row.digest().equals(publicAssociation.associationDigest()) + || !row.targetNamespace().equals(publicAssociation.targetNamespace()) + || !row.sourceOperationId().equals(publicAssociation.sourceOperationId()) + || !row.sourceEvidenceDigest().equals(publicAssociation.sourceEvidenceDigest()) + || !row.worldSlug().equals(publicAssociation.worldSlug())) { + throw conflict("Retained association row differs from the public pinned association"); + } + return new CapturedTemplate(unsupported, gameLogicReceipt); + } + + /** + * Exact Game Logic receipt/source join already required by the selected-publication inventory. + */ + private GameLogicReceiptBinding requireSelectedGameLogicReceipt( + GameDesignPublicationOperation operation) { + var selection = operation.account().input().selection(); + var target = selection.target(); + var publicationRequest = + PublicationDigestRequestBinding.full( + selection.intent().canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + selection.intent().publishRequestId()); + SelectedDraftGameLogicReceipt receipt = + new SelectedDraftGameLogicReceiptRepository(dsl) + .readForPublication(publicationRequest) + .orElseThrow(() -> conflict("Exact retained Game Logic source receipt is unavailable")); + GameplayRuleSnapshot selectedRules = + new GameplayRuleSourceRepository(dsl) + .readSnapshot(target, selection.selectedCommit().commitId()) + .orElseThrow( + () -> conflict("Exact selected Game Logic source snapshot is unavailable")); + if (!Arrays.equals(selection.canonicalBytes(), receipt.selection().canonicalBytes()) + || !selection.selectedCommit().equals(selectedRules.binding()) + || !Arrays.equals( + selectedRules.canonicalBytes(), receipt.authorization().source().canonicalBytes())) { + throw conflict("Retained Game Logic receipt differs from the exact selected source"); + } + return new GameLogicReceiptBinding( + selection.intent().publishRequestId(), + selection.digest(), + receipt.authorization().digest(), + receipt.receipt().digest()); + } + + private void requireReleaseMatches( + Result exact, PublishedReleaseBundleDto release, Version version) { + var selected = exact.releaseBundle(); + var current = toPublishedReleaseBundle(release); + if (!selected.equals(current) + || release.id() == null + || release.id() <= 0L + || !Objects.equals(release.id(), selected.getId()) + || !Objects.equals(release.versionId(), version.getId()) + || !Objects.equals(release.canonicalTenantId(), exact.association().canonicalTenantId()) + || !Objects.equals(release.canonicalVersionId(), exact.association().canonicalVersionId()) + || !Objects.equals(release.publishWorkflowId(), exact.association().publishWorkflowId()) + || !"v2".equals(release.attestationSchemaVersion()) + || !Objects.equals( + release.worldPublishedStartLocationEvidence(), + exact.worldPublishedStartLocationEvidence()) + || release.scriptOnly() + || release.scriptPatchVersion() != null && !release.scriptPatchVersion().isBlank()) { + throw conflict("Current release row differs from the exact committed published release"); + } + var releaseContent = releaseContent(release); + var readback = + publicationOperations.read(exact.association().publishWorkflowId()).orElseThrow(); + if (readback.terminalEvidenceBytes() == null) { + throw conflict("Exact published terminal evidence is unavailable"); + } + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(readback.terminalEvidenceBytes()); + if (terminal.releaseContent() == null + || terminal.publicationVersionStateEpoch() > version.getVersionStateEpoch() + || !Arrays.equals( + terminal.releaseContent().canonicalBytes(), releaseContent.canonicalBytes())) { + throw conflict( + "Current release content differs from the original published terminal evidence"); + } + } + + private void lockAndReloadSelectedVersion( + Version version, UUID canonicalTenantId, UUID canonicalVersionId) { + Record row = + dsl.fetchOne( + "SELECT id FROM version WHERE id = ? AND canonical_tenant_id = ? " + + "AND canonical_version_id = ? FOR UPDATE", + version.getId(), + canonicalTenantId, + canonicalVersionId); + if (row == null || !Objects.equals(row.get("id", Long.class), version.getId())) { + throw conflict("Exact canonical Version row could not be locked for descriptor creation"); + } + } + + private void requireLaunchableVersion( + Version version, + AuthoredWorldSourceEvidence source, + TemplateReferenceRepository.PhaseSnapshot phase, + Association association) { + if (!Objects.equals(version.getCanonicalTenantId(), association.canonicalTenantId()) + || !Objects.equals(version.getCanonicalVersionId(), association.canonicalVersionId()) + || !Objects.equals(version.getTenantId(), source.sourceGameTenantKey()) + || !Objects.equals(version.getIdentitySourceGameRowId(), phase.sourceGameRowId()) + || !Objects.equals(version.getIdentitySourceGameTenantKey(), phase.sourceGameTenantKey()) + || !Objects.equals(version.getIdentitySourceProvenanceKind(), phase.provenanceKind()) + || version.getVersionStateEpoch() == null + || version.getVersionStateEpoch() <= 0L + || !(version.getVersionState() == VersionLifecycleState.PUBLISHED + || version.getVersionState() == VersionLifecycleState.ACTIVE) + || version.isScriptOnly() + || version.getBaseVersionId() != null + || version.getScriptPatchVersion() != null) { + throw conflict("Exact fresh published full Version is not launchable"); + } + } + + private void requireSourceMatches(Association association, AuthoredWorldSourceEvidence source) { + if (!workloadNamespace.equals(source.targetNamespace()) + || !association.targetNamespace().equals(source.targetNamespace()) + || !association.canonicalTenantId().equals(source.canonicalTenantId()) + || !association.sourceOperationId().equals(source.operationId()) + || !association.sourceEvidenceDigest().equals(source.evidenceDigest()) + || !association.worldSlug().equals(source.worldSlug()) + || !"NEW_GAME_ROW".equals(source.provenanceKind()) + || source.sourceGameRowId() <= 0L + || source.sourceGameTenantKey() == null + || source.sourceGameTenantKey().isBlank()) { + throw conflict("Exact association source does not match fresh Game Design source evidence"); + } + } + + private void requireExactAssociationRead(Request request, Result result) { + if (result == null + || !request.equals(result.request()) + || !(result.request().selection() instanceof ExactReplay replay) + || !replay.canonicalVersionId().equals(result.association().canonicalVersionId()) + || !replay.selectedCommitId().equals(result.association().selectedCommitId()) + || !replay.publishWorkflowId().equals(result.association().publishWorkflowId()) + || !replay.associationDigest().equals(result.association().associationDigest())) { + throw conflict("Account-gated association read differs from the exact Game Session replay"); + } + var tuple = request.decodedTuple(); + var action = tuple.preAuthorizationTuple().action(); + if (!action.scope().tenantId().equals(result.association().canonicalTenantId()) + || action.target().gameTemplateId() != result.association().templateId() + || !request.targetNamespace().equals(result.association().targetNamespace())) { + throw conflict( + "Exact association read differs from the original authorized StartSession target"); + } + } + + private AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest( + StartSessionPostAuthorizationExecutionTuple tuple, Association association) { + var action = tuple.preAuthorizationTuple().action(); + if (!action.scope().tenantId().equals(association.canonicalTenantId()) + || action.target().gameTemplateId() != association.templateId()) { + throw conflict("Association source differs from the original StartSession tenant/template"); + } + return new AuthoredWorldLaunchDescriptorEvidence.Request( + workloadNamespace, + tuple.controlPlaneRequestId(), + association.canonicalTenantId(), + association.worldSlug(), + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.templateId(), + false, + null, + false, + null, + false, + null, + true, + EMPTY_RUNTIME_FLAGS); + } + + private LaunchDescriptor descriptorRow( + AuthoredWorldLaunchDescriptorEvidence evidence, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setGameTemplateId(evidence.gameTemplateId()); + descriptor.setControlPlaneRequestId(evidence.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(evidence.versionId()); + descriptor.setScriptPatchVersion(null); + descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); + descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); + descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); + descriptor.setReleaseBundleId(evidence.releaseBundleId()); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); + descriptor.setRemapSetId(null); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(evidence.targetNamespace()); + descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + return descriptor; + } + + private Binding binding( + Request request, + Result result, + Long descriptorRowId, + Long releaseBundleId, + Long versionStateEpoch, + String runtimeSurface, + GameLogicReceiptBinding gameLogicReceipt) { + Association association = result.association(); + var tuple = request.decodedTuple(); + return new Binding( + workloadNamespace, + association.canonicalTenantId(), + tuple.controlPlaneRequestId(), + descriptorRowId, + releaseBundleId, + versionStateEpoch, + request.canonicalPostAuthorizationTuple(), + request.ownerAttemptId(), + request.ownerFence(), + association.templateId(), + association.canonicalVersionId(), + association.selectedCommitId(), + association.publishWorkflowId(), + association.publicationSelectionDigest(), + association.associationDigest(), + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.worldSlug(), + result.phaseEpoch(), + runtimeSurface, + gameLogicReceipt.publishRequestId(), + gameLogicReceipt.selectionDigest(), + gameLogicReceipt.authorizationDigest(), + gameLogicReceipt.receiptDigest(), + StartSessionTemplateAssociationReadGrpcCodec.toResponse(result).toByteArray(), + java.time.LocalDateTime.now()); + } + + private void requireBindingMatches( + Binding binding, + LaunchDescriptor descriptor, + Request request, + Result result, + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest, + AuthoredWorldSourceEvidence source, + GameLogicReceiptBinding gameLogicReceipt) { + Association association = result.association(); + if (!Objects.equals(binding.targetNamespace(), workloadNamespace) + || !Objects.equals(binding.canonicalTenantId(), association.canonicalTenantId()) + || !Objects.equals( + binding.controlPlaneRequestId(), descriptorRequest.controlPlaneRequestId()) + || !Objects.equals(binding.descriptorRowId(), descriptor.getId()) + || !Objects.equals(binding.releaseBundleId(), result.releaseBundle().getId()) + || (LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + && !Objects.equals(binding.versionStateEpoch(), descriptor.getVersionStateEpoch())) + || !Arrays.equals( + binding.canonicalPostAuthorizationTuple(), request.canonicalPostAuthorizationTuple()) + || !Objects.equals(binding.ownerAttemptId(), request.ownerAttemptId()) + || !Objects.equals(binding.ownerFence(), request.ownerFence()) + || !Objects.equals(binding.gameTemplateId(), association.templateId()) + || !Objects.equals(binding.canonicalVersionId(), association.canonicalVersionId()) + || !Objects.equals(binding.selectedCommitId(), association.selectedCommitId()) + || !Objects.equals(binding.publishWorkflowId(), association.publishWorkflowId()) + || !Objects.equals( + binding.publicationSelectionDigest(), association.publicationSelectionDigest()) + || !Objects.equals(binding.associationDigest(), association.associationDigest()) + || !Objects.equals(binding.sourceOperationId(), association.sourceOperationId()) + || !Objects.equals(binding.sourceEvidenceDigest(), association.sourceEvidenceDigest()) + || !Objects.equals(binding.worldSlug(), association.worldSlug()) + || !Objects.equals(binding.referencePhaseEpoch(), result.phaseEpoch()) + || !Objects.equals(binding.gameLogicPublishRequestId(), gameLogicReceipt.publishRequestId()) + || !Objects.equals(binding.gameLogicSelectionDigest(), gameLogicReceipt.selectionDigest()) + || !Objects.equals( + binding.gameLogicAuthorizationDigest(), gameLogicReceipt.authorizationDigest()) + || !Objects.equals(binding.gameLogicReceiptDigest(), gameLogicReceipt.receiptDigest()) + || !(LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + && Objects.equals(binding.runtimeSurface(), RUNTIME_SURFACE_EMPTY_V1) + || LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()) + && Objects.equals(binding.runtimeSurface(), RUNTIME_SURFACE_UNSUPPORTED_CAPTURE_V1)) + || !source.operationId().equals(binding.sourceOperationId()) + || !source.evidenceDigest().equals(binding.sourceEvidenceDigest()) + || !sameAssociationReadResponse(binding.associationReadResponseBytes(), request, result)) { + throw conflict("Immutable StartSession descriptor association binding changed or conflicts"); + } + } + + private boolean sameAssociationReadResponse( + byte[] storedBytes, Request currentRequest, Result current) { + try { + var stored = + net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse + .parseFrom(storedBytes); + Request storedRequest = + StartSessionTemplateAssociationReadGrpcCodec.fromRequest(stored.getRequest()); + Result previous = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse(storedRequest, stored); + return sameLogicalRequest(storedRequest, currentRequest) + && previous.association().equals(current.association()) + && previous.releaseBundle().equals(current.releaseBundle()) + && previous + .worldPublishedStartLocationEvidence() + .equals(current.worldPublishedStartLocationEvidence()) + && previous.phaseEpoch() == current.phaseEpoch(); + } catch (IOException | IllegalArgumentException invalid) { + throw conflict("Stored exact StartSession association evidence is corrupt"); + } + } + + private boolean sameLogicalRequest(Request left, Request right) { + return left.schemaVersion() == right.schemaVersion() + && left.targetNamespace().equals(right.targetNamespace()) + && Arrays.equals( + left.canonicalPostAuthorizationTuple(), right.canonicalPostAuthorizationTuple()) + && left.ownerAttemptId().equals(right.ownerAttemptId()) + && left.ownerFence() == right.ownerFence() + && left.selection().equals(right.selection()); + } + + private ResolvedLaunchDescriptorDto readStored( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + AuthoredWorldSourceEvidence source, + String sourceJson) { + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || descriptor.getDescriptorSchemaVersion() == null + || descriptor.getDescriptorSchemaVersion() + != AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !Objects.equals(descriptor.getTenantId(), source.sourceGameTenantKey()) + || request.gameTemplateId() != descriptor.getGameTemplateId() + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !request.requestDigest().equals(descriptor.getRequestDigest())) { + throw conflict("Stored descriptor is not the exact immutable StartSession request"); + } + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptor.getLaunchDescriptorId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion() != null, + descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getVersionStateEpoch(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getRemapSetId() != null, + descriptor.getRemapSetId()); + evidence.requireValid(); + if (!evidence.resultDigest().equals(descriptor.getResultDigest())) { + throw conflict("Stored launch descriptor result digest is inconsistent"); + } + if (descriptor.getScriptPatchVersion() != null + || descriptor.getRemapSetId() != null + || !EMPTY_RUNTIME_FLAGS.equals(descriptor.getRuntimeFlagsJson())) { + throw conflict("Stored descriptor exceeds the explicitly empty launch runtime surface"); + } + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private void requireSuccessfulDescriptor(LaunchDescriptor descriptor) { + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || descriptor.getDescriptorSchemaVersion() == null) { + throw conflict("Retained descriptor history is not an exact successful bound descriptor"); + } + } + + private FrozenFailure requireStoredFailure( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + AuthoredWorldSourceEvidence source, + String sourceJson) { + if (!LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()) + || !Objects.equals( + descriptor.getDescriptorSchemaVersion(), + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !Objects.equals(source.sourceGameTenantKey(), descriptor.getTenantId()) + || descriptor.getLaunchDescriptorId() != null + || descriptor.getGameTemplateId() != null + || descriptor.getVersionId() != null + || descriptor.getScriptPatchVersion() != null + || descriptor.getRuntimeFlagsJson() != null + || descriptor.getGenerationConfigRevision() != null + || descriptor.getVersionStateEpoch() != null + || descriptor.getReleaseBundleId() != null + || descriptor.getPublishedReleaseBundleRef() != null + || descriptor.getRemapSetId() != null + || descriptor.getResultDigest() != null + || !INVALID_TEMPLATE_CONFIGURATION.equals(descriptor.getFailureCode()) + || !UNSUPPORTED_CAPTURE_MESSAGE.equals(descriptor.getFailureMessage())) { + throw conflict( + "Stored failed descriptor is not the exact immutable unsupported-capture outcome"); + } + return new FrozenFailure(descriptor.getFailureCode(), descriptor.getFailureMessage()); + } + + private LaunchDescriptor frozenFailure( + AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson, + String failureCode, + String failureMessage) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(request.requestDigest()); + descriptor.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); + descriptor.setTargetNamespace(workloadNamespace); + descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); + descriptor.setWorldSlug(request.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + request.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(request.requestDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + descriptor.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); + descriptor.setFailureCode(failureCode); + descriptor.setFailureMessage(failureMessage); + return descriptor; + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception failure) { + throw new IllegalStateException("Could not encode exact immutable owner evidence", failure); + } + } + + private net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle toPublishedReleaseBundle( + PublishedReleaseBundleDto dto) { + var builder = + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() + .setId(dto.id()) + .setVersionId(dto.versionId()) + .setVersionNumber(dto.versionNumber()) + .setAttestationSchemaVersion(dto.attestationSchemaVersion()) + .setPublishWorkflowId(dto.publishWorkflowId()) + .setManifestHash(dto.manifestHash()) + .addAllRequiredManifestAssetKeys(dto.requiredManifestAssetKeys()) + .setIsScriptOnly(dto.scriptOnly()) + .setScriptPatchVersion(Objects.requireNonNullElse(dto.scriptPatchVersion(), "")) + .setPublishedAt(dto.publishedAt().toString()) + .setGenerationConfigRevision(dto.generationConfigRevision()) + .addAllCommandDefinitions(dto.commandDefinitions()) + .setPublishedReleaseBundleRef(dto.publishedReleaseBundleRef()) + .setCanonicalTenantId(dto.canonicalTenantId().toString()) + .setCanonicalVersionId(dto.canonicalVersionId().toString()); + for (PublishParticipantDigestDto participant : dto.participantDigests()) { + if (!participant.succeeded()) throw conflict("Published release participant did not succeed"); + var value = + net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(Objects.requireNonNull(participant.appliedCommitId())) + .setContentDigest(Objects.requireNonNull(participant.contentDigest())) + .setDigestSchemaVersion(Objects.requireNonNull(participant.digestSchemaVersion())); + if (participant.abilitySchemaDigest() != null) + value.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + builder.addParticipantDigests(value); + } + if (dto.manifestSchemaVersion() != null) + builder.setManifestSchemaVersion(dto.manifestSchemaVersion()); + if (dto.artifactDigests() != null) { + for (PublishedArtifactDigest artifact : dto.artifactDigests()) { + builder.addArtifactDigests( + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey(artifact.usageKey()) + .setArtifactKind(artifact.artifactKind()) + .setImmutableObjectKey(artifact.immutableObjectKey()) + .setContentDigest(artifact.contentDigest()) + .setContentType(artifact.contentType()) + .setArtifactSchemaVersion(artifact.artifactSchemaVersion())); + } + } + return builder.build(); + } + + private GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent( + PublishedReleaseBundleDto dto) { + if (dto.manifestSchemaVersion() == null || dto.artifactDigests() == null) { + throw conflict("Immutable release content evidence is incomplete"); + } + List participants = + dto.participantDigests().stream() + .map( + value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.participantKey(), + value.scopeValue(), + value.baseVersionId(), + value.appliedCommitId(), + value.contentDigest(), + Objects.requireNonNull(value.digestSchemaVersion()), + value.abilitySchemaDigest(), + value.errorCode(), + value.errorMessage())) + .toList(); + List + artifacts = + dto.artifactDigests().stream() + .map( + value -> + new net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence.Artifact( + value.usageKey(), + value.artifactKind(), + value.immutableObjectKey(), + value.contentDigest(), + value.contentType(), + value.artifactSchemaVersion())) + .toList(); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + dto.canonicalTenantId(), + dto.canonicalVersionId(), + dto.publishedReleaseBundleRef(), + dto.versionNumber(), + dto.attestationSchemaVersion(), + dto.publishWorkflowId(), + dto.manifestHash(), + dto.manifestSchemaVersion(), + artifacts, + dto.requiredManifestAssetKeys(), + participants, + dto.commandDefinitions(), + dto.generationConfigRevision(), + dto.worldPublishedStartLocationEvidence()); + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified same-namespace Game Session workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + } + + private static StatusRuntimeException conflict(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } + + /** + * Returned to the caller so Game Session can atomically pin this descriptor with the association. + */ + public record ResolvedBinding( + Request request, Result associationRead, ResolvedLaunchDescriptorDto descriptor) { + public ResolvedBinding { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(associationRead, "associationRead"); + Objects.requireNonNull(descriptor, "descriptor"); + if (!request.equals(associationRead.request()) + || !request + .decodedTuple() + .controlPlaneRequestId() + .equals(descriptor.controlPlaneRequestId()) + || !request + .decodedTuple() + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .toString() + .equals(descriptor.canonicalTenantId()) + || request.decodedTuple().preAuthorizationTuple().action().target().gameTemplateId() + != descriptor.gameTemplateId()) { + throw new IllegalArgumentException( + "Resolved descriptor differs from exact StartSession binding"); + } + } + } + + /** + * A proved immutable business result, exposed only after its owner transaction commits. RPC + * failures and missing evidence never become this type, so transport adapters need not guess + * whether a FAILED_PRECONDITION represents a retained result. + */ + public static final class StoredBusinessDenial extends RuntimeException { + private static final long serialVersionUID = 1L; + private final Result associationRead; + private final String failureCode; + + private StoredBusinessDenial(Result associationRead, FrozenFailure failure) { + super(failure.message()); + this.associationRead = Objects.requireNonNull(associationRead, "associationRead"); + this.failureCode = failure.code(); + } + + public Result associationRead() { + return associationRead; + } + + public String failureCode() { + return failureCode; + } + } + + private record FrozenFailure(String code, String message) { + private FrozenFailure { + Objects.requireNonNull(code, "code"); + Objects.requireNonNull(message, "message"); + } + } + + private record CapturedTemplate(String failureMessage, GameLogicReceiptBinding gameLogicReceipt) { + private CapturedTemplate { + Objects.requireNonNull(gameLogicReceipt, "gameLogicReceipt"); + } + } + + private record GameLogicReceiptBinding( + String publishRequestId, + String selectionDigest, + String authorizationDigest, + String receiptDigest) { + private GameLogicReceiptBinding { + Objects.requireNonNull(publishRequestId, "publishRequestId"); + Objects.requireNonNull(selectionDigest, "selectionDigest"); + Objects.requireNonNull(authorizationDigest, "authorizationDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + } + } + + private record OwnerOutcome(ResolvedBinding resolvedBinding, FrozenFailure failure) { + private OwnerOutcome { + if ((resolvedBinding == null) == (failure == null)) { + throw new IllegalArgumentException("Exactly one descriptor outcome is required"); + } + } + + static OwnerOutcome succeeded(ResolvedBinding binding) { + return new OwnerOutcome(Objects.requireNonNull(binding), null); + } + + static OwnerOutcome failed(FrozenFailure failure) { + return new OwnerOutcome(null, Objects.requireNonNull(failure)); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionLaunchDescriptorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionLaunchDescriptorRepository.java new file mode 100644 index 0000000000..a5495578ae --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionLaunchDescriptorRepository.java @@ -0,0 +1,201 @@ +package net.firedevops.firemud.gamedesign.repository; + +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; + +/** Immutable binding from an owner-produced descriptor to its original StartSession evidence. */ +public final class StartSessionLaunchDescriptorRepository { + private static final Table TABLE = + DSL.table(DSL.name("game_design_start_session_launch_descriptor_binding")); + 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 CONTROL_PLANE_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + private static final Field DESCRIPTOR_ROW_ID = + DSL.field(DSL.name("launch_descriptor_row_id"), Long.class); + private static final Field RELEASE_BUNDLE_ID = + DSL.field(DSL.name("release_bundle_id"), Long.class); + private static final Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + private static final Field CANONICAL_TUPLE = + DSL.field(DSL.name("canonical_post_authorization_tuple"), byte[].class); + private static final Field OWNER_ATTEMPT_ID = + DSL.field(DSL.name("owner_attempt_id"), UUID.class); + private static final Field OWNER_FENCE = DSL.field(DSL.name("owner_fence"), Long.class); + private static final Field GAME_TEMPLATE_ID = + DSL.field(DSL.name("game_template_id"), Long.class); + private static final Field CANONICAL_VERSION_ID = + DSL.field(DSL.name("canonical_version_id"), UUID.class); + private static final Field SELECTED_COMMIT_ID = + DSL.field(DSL.name("selected_commit_id"), UUID.class); + private static final Field PUBLISH_WORKFLOW_ID = + DSL.field(DSL.name("publish_workflow_id"), String.class); + private static final Field PUBLICATION_SELECTION_DIGEST = + DSL.field(DSL.name("publication_selection_digest"), String.class); + private static final Field ASSOCIATION_DIGEST = + DSL.field(DSL.name("association_digest"), String.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field REFERENCE_PHASE_EPOCH = + DSL.field(DSL.name("reference_phase_epoch"), Long.class); + private static final Field RUNTIME_SURFACE = + DSL.field(DSL.name("runtime_surface"), String.class); + private static final Field GAME_LOGIC_PUBLISH_REQUEST_ID = + DSL.field(DSL.name("game_logic_publish_request_id"), String.class); + private static final Field GAME_LOGIC_SELECTION_DIGEST = + DSL.field(DSL.name("game_logic_selection_digest"), String.class); + private static final Field GAME_LOGIC_AUTHORIZATION_DIGEST = + DSL.field(DSL.name("game_logic_authorization_digest"), String.class); + private static final Field GAME_LOGIC_RECEIPT_DIGEST = + DSL.field(DSL.name("game_logic_receipt_digest"), String.class); + private static final Field ASSOCIATION_READ_RESPONSE = + DSL.field(DSL.name("association_read_response_bytes"), byte[].class); + private static final Field CREATED_AT = + DSL.field(DSL.name("created_at"), Timestamp.class); + + private final DSLContext dsl; + + public StartSessionLaunchDescriptorRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + public Optional find(String targetNamespace, UUID canonicalTenantId, String requestId) { + return Optional.ofNullable( + dsl.selectFrom(TABLE) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(CONTROL_PLANE_REQUEST_ID.eq(requestId))) + .fetchOne(this::toBinding)); + } + + /** Insert-only; the caller must compare the complete readback before returning it. */ + public Binding insertImmutable(Binding binding) { + Objects.requireNonNull(binding, "binding"); + dsl.insertInto(TABLE) + .set(TARGET_NAMESPACE, binding.targetNamespace()) + .set(CANONICAL_TENANT_ID, binding.canonicalTenantId()) + .set(CONTROL_PLANE_REQUEST_ID, binding.controlPlaneRequestId()) + .set(DESCRIPTOR_ROW_ID, binding.descriptorRowId()) + .set(RELEASE_BUNDLE_ID, binding.releaseBundleId()) + .set(VERSION_STATE_EPOCH, binding.versionStateEpoch()) + .set(CANONICAL_TUPLE, binding.canonicalPostAuthorizationTuple()) + .set(OWNER_ATTEMPT_ID, binding.ownerAttemptId()) + .set(OWNER_FENCE, binding.ownerFence()) + .set(GAME_TEMPLATE_ID, binding.gameTemplateId()) + .set(CANONICAL_VERSION_ID, binding.canonicalVersionId()) + .set(SELECTED_COMMIT_ID, binding.selectedCommitId()) + .set(PUBLISH_WORKFLOW_ID, binding.publishWorkflowId()) + .set(PUBLICATION_SELECTION_DIGEST, binding.publicationSelectionDigest()) + .set(ASSOCIATION_DIGEST, binding.associationDigest()) + .set(SOURCE_OPERATION_ID, binding.sourceOperationId()) + .set(SOURCE_EVIDENCE_DIGEST, binding.sourceEvidenceDigest()) + .set(WORLD_SLUG, binding.worldSlug()) + .set(REFERENCE_PHASE_EPOCH, binding.referencePhaseEpoch()) + .set(RUNTIME_SURFACE, binding.runtimeSurface()) + .set(GAME_LOGIC_PUBLISH_REQUEST_ID, binding.gameLogicPublishRequestId()) + .set(GAME_LOGIC_SELECTION_DIGEST, binding.gameLogicSelectionDigest()) + .set(GAME_LOGIC_AUTHORIZATION_DIGEST, binding.gameLogicAuthorizationDigest()) + .set(GAME_LOGIC_RECEIPT_DIGEST, binding.gameLogicReceiptDigest()) + .set(ASSOCIATION_READ_RESPONSE, binding.associationReadResponseBytes()) + .set(CREATED_AT, Timestamp.valueOf(binding.createdAt())) + .onConflictDoNothing() + .execute(); + return find( + binding.targetNamespace(), binding.canonicalTenantId(), binding.controlPlaneRequestId()) + .orElseThrow( + () -> new IllegalStateException("START_SESSION_DESCRIPTOR_BINDING_READBACK_MISSING")); + } + + private Binding toBinding(Record row) { + Timestamp createdAt = row.get(CREATED_AT, Timestamp.class); + return new Binding( + row.get(TARGET_NAMESPACE), + row.get(CANONICAL_TENANT_ID), + row.get(CONTROL_PLANE_REQUEST_ID), + row.get(DESCRIPTOR_ROW_ID), + row.get(RELEASE_BUNDLE_ID), + row.get(VERSION_STATE_EPOCH), + row.get(CANONICAL_TUPLE), + row.get(OWNER_ATTEMPT_ID), + row.get(OWNER_FENCE), + row.get(GAME_TEMPLATE_ID), + row.get(CANONICAL_VERSION_ID), + row.get(SELECTED_COMMIT_ID), + row.get(PUBLISH_WORKFLOW_ID), + row.get(PUBLICATION_SELECTION_DIGEST), + row.get(ASSOCIATION_DIGEST), + row.get(SOURCE_OPERATION_ID), + row.get(SOURCE_EVIDENCE_DIGEST), + row.get(WORLD_SLUG), + row.get(REFERENCE_PHASE_EPOCH), + row.get(RUNTIME_SURFACE), + row.get(GAME_LOGIC_PUBLISH_REQUEST_ID), + row.get(GAME_LOGIC_SELECTION_DIGEST), + row.get(GAME_LOGIC_AUTHORIZATION_DIGEST), + row.get(GAME_LOGIC_RECEIPT_DIGEST), + row.get(ASSOCIATION_READ_RESPONSE), + createdAt == null ? null : createdAt.toLocalDateTime()); + } + + public record Binding( + String targetNamespace, + UUID canonicalTenantId, + String controlPlaneRequestId, + Long descriptorRowId, + Long releaseBundleId, + Long versionStateEpoch, + byte[] canonicalPostAuthorizationTuple, + UUID ownerAttemptId, + Long ownerFence, + Long gameTemplateId, + UUID canonicalVersionId, + UUID selectedCommitId, + String publishWorkflowId, + String publicationSelectionDigest, + String associationDigest, + UUID sourceOperationId, + String sourceEvidenceDigest, + String worldSlug, + Long referencePhaseEpoch, + String runtimeSurface, + String gameLogicPublishRequestId, + String gameLogicSelectionDigest, + String gameLogicAuthorizationDigest, + String gameLogicReceiptDigest, + byte[] associationReadResponseBytes, + LocalDateTime createdAt) { + public Binding { + canonicalPostAuthorizationTuple = cloneBytes(canonicalPostAuthorizationTuple); + associationReadResponseBytes = cloneBytes(associationReadResponseBytes); + } + + @Override + public byte[] canonicalPostAuthorizationTuple() { + return cloneBytes(canonicalPostAuthorizationTuple); + } + + @Override + public byte[] associationReadResponseBytes() { + return cloneBytes(associationReadResponseBytes); + } + + private static byte[] cloneBytes(byte[] value) { + return value == null ? null : value.clone(); + } + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V66__start_session_launch_descriptor_association_binding.sql b/services/game-design-service/src/main/resources/db/migration/V66__start_session_launch_descriptor_association_binding.sql new file mode 100644 index 0000000000..52af26bd9b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V66__start_session_launch_descriptor_association_binding.sql @@ -0,0 +1,219 @@ +-- A new exact StartSession descriptor is inseparable from the original Account/GS execution and +-- the immutable selected template/source association that authorized its launch target. +CREATE TABLE game_design_start_session_launch_descriptor_binding ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + control_plane_request_id VARCHAR(255) NOT NULL, + launch_descriptor_row_id BIGINT NOT NULL UNIQUE + REFERENCES launch_descriptor (id) ON DELETE RESTRICT, + release_bundle_id BIGINT NOT NULL + REFERENCES published_release_bundle (id) ON DELETE RESTRICT, + version_state_epoch BIGINT NOT NULL, + canonical_post_authorization_tuple BYTEA NOT NULL, + owner_attempt_id UUID NOT NULL, + owner_fence BIGINT NOT NULL, + game_template_id BIGINT NOT NULL, + canonical_version_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL, + publication_selection_digest VARCHAR(71) NOT NULL, + association_digest VARCHAR(71) NOT NULL, + source_operation_id UUID NOT NULL + REFERENCES game_design_authored_world_source_operations (operation_id) ON DELETE RESTRICT, + source_evidence_digest VARCHAR(71) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + reference_phase_epoch BIGINT NOT NULL, + runtime_surface VARCHAR(32) NOT NULL, + game_logic_publish_request_id VARCHAR(1024) NOT NULL, + game_logic_selection_digest VARCHAR(71) NOT NULL, + game_logic_authorization_digest VARCHAR(71) NOT NULL, + game_logic_receipt_digest VARCHAR(71) NOT NULL, + association_read_response_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_start_session_launch_descriptor_binding PRIMARY KEY ( + target_namespace, + canonical_tenant_id, + control_plane_request_id + ), + CONSTRAINT fk_gd_start_session_launch_association FOREIGN KEY ( + canonical_tenant_id, + canonical_version_id, + selected_commit_id, + game_template_id + ) REFERENCES game_design_selected_template_world_source_association ( + canonical_tenant_id, + canonical_version_id, + commit_id, + template_id + ) ON DELETE RESTRICT, + CONSTRAINT fk_gd_start_session_launch_game_logic_receipt FOREIGN KEY ( + canonical_tenant_id, + game_logic_publish_request_id + ) REFERENCES game_design_selected_game_logic_receipt ( + canonical_tenant_id, + publish_request_id + ) ON DELETE RESTRICT, + CONSTRAINT ck_gd_start_session_launch_binding_identity CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND control_plane_request_id !~ '^[[:space:]]*$' + AND release_bundle_id > 0 + AND version_state_epoch > 0 + AND octet_length(canonical_post_authorization_tuple) BETWEEN 1 AND 262144 + AND owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_fence > 0 + AND game_template_id > 0 + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND char_length(publish_workflow_id) BETWEEN 1 AND 1024 + AND publication_selection_digest ~ '^sha256:[0-9a-f]{64}$' + AND association_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND reference_phase_epoch > 0 + AND runtime_surface IN ('EMPTY_V1', 'UNSUPPORTED_CAPTURE_V1') + AND char_length(game_logic_publish_request_id) BETWEEN 1 AND 1024 + AND game_logic_selection_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_logic_authorization_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_logic_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(association_read_response_bytes) > 0 + ) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_gd_start_session_launch_descriptor_binding() RETURNS trigger AS $$ +DECLARE descriptor launch_descriptor%ROWTYPE; + association game_design_selected_template_world_source_association%ROWTYPE; + current_version version%ROWTYPE; + current_phase game_template_reference_phase%ROWTYPE; + publication game_design_publication_operation%ROWTYPE; + owner_source game_design_authored_world_source_operations%ROWTYPE; + release published_release_bundle%ROWTYPE; + game_logic_receipt game_design_selected_game_logic_receipt%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'StartSession launch descriptor bindings are immutable and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO STRICT descriptor + FROM launch_descriptor + WHERE id = NEW.launch_descriptor_row_id; + SELECT * INTO STRICT association + FROM game_design_selected_template_world_source_association + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.selected_commit_id + AND template_id = NEW.game_template_id; + SELECT * INTO STRICT current_version + FROM version + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT current_phase + FROM game_template_reference_phase + WHERE canonical_tenant_id = NEW.canonical_tenant_id; + SELECT * INTO STRICT publication + FROM game_design_publication_operation + WHERE publish_workflow_id = NEW.publish_workflow_id; + SELECT * INTO STRICT owner_source + FROM game_design_authored_world_source_operations + WHERE operation_id = NEW.source_operation_id; + SELECT * INTO STRICT release + FROM published_release_bundle + WHERE id = NEW.release_bundle_id; + SELECT * INTO STRICT game_logic_receipt + FROM game_design_selected_game_logic_receipt + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND publish_request_id = NEW.game_logic_publish_request_id; + + IF descriptor.outcome_status NOT IN ('SUCCESS', 'FAILED') + OR descriptor.descriptor_schema_version <> 1 + OR descriptor.target_namespace IS DISTINCT FROM NEW.target_namespace + OR descriptor.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR descriptor.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR descriptor.tenant_id IS DISTINCT FROM owner_source.source_game_tenant_key + OR current_version.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch + OR current_version.version_state NOT IN ('PUBLISHED', 'ACTIVE') + OR current_version.is_script_only IS DISTINCT FROM FALSE + OR current_version.script_patch_version IS NOT NULL + OR current_phase.phase IS DISTINCT FROM 'ENFORCED' + OR current_phase.phase_epoch IS DISTINCT FROM NEW.reference_phase_epoch + OR publication.outcome IS DISTINCT FROM 'PUBLISHED' + OR publication.selection_digest IS DISTINCT FROM NEW.publication_selection_digest + OR owner_source.target_namespace IS DISTINCT FROM NEW.target_namespace + OR owner_source.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR owner_source.world_slug IS DISTINCT FROM NEW.world_slug + OR owner_source.evidence_digest IS DISTINCT FROM NEW.source_evidence_digest + OR owner_source.provenance_kind IS DISTINCT FROM 'NEW_GAME_ROW' + OR owner_source.source_game_row_id IS DISTINCT FROM current_phase.source_game_row_id + OR owner_source.source_game_tenant_key IS DISTINCT FROM current_phase.source_game_tenant_key + OR release.tenant_id IS DISTINCT FROM current_version.tenant_id + OR release.version_id IS DISTINCT FROM current_version.id + OR release.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR game_logic_receipt.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR game_logic_receipt.selection_digest IS DISTINCT FROM NEW.game_logic_selection_digest + OR game_logic_receipt.selection_digest IS DISTINCT FROM NEW.publication_selection_digest + OR game_logic_receipt.authorization_digest IS DISTINCT FROM NEW.game_logic_authorization_digest + OR game_logic_receipt.receipt_digest IS DISTINCT FROM NEW.game_logic_receipt_digest + OR game_logic_receipt.workflow_identity IS DISTINCT FROM NEW.publish_workflow_id + OR descriptor.authored_world_source_operation_id IS DISTINCT FROM NEW.source_operation_id + OR descriptor.authored_world_source_evidence_digest IS DISTINCT FROM NEW.source_evidence_digest + OR descriptor.world_slug IS DISTINCT FROM NEW.world_slug + OR association.publish_workflow_id IS DISTINCT FROM NEW.publish_workflow_id + OR association.target_namespace IS DISTINCT FROM NEW.target_namespace + OR association.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR association.commit_id IS DISTINCT FROM NEW.selected_commit_id + OR association.source_operation_id IS DISTINCT FROM NEW.source_operation_id + OR association.source_evidence_digest IS DISTINCT FROM NEW.source_evidence_digest + OR association.world_slug IS DISTINCT FROM NEW.world_slug + OR association.association_digest IS DISTINCT FROM NEW.association_digest + OR (descriptor.outcome_status = 'SUCCESS' AND ( + NEW.runtime_surface IS DISTINCT FROM 'EMPTY_V1' + OR descriptor.game_template_id IS DISTINCT FROM NEW.game_template_id + OR descriptor.version_id IS DISTINCT FROM current_version.id + OR descriptor.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch + OR descriptor.release_bundle_id IS DISTINCT FROM NEW.release_bundle_id + OR descriptor.published_release_bundle_ref IS DISTINCT FROM release.published_release_bundle_ref + OR descriptor.generation_config_revision IS DISTINCT FROM release.generation_config_revision + OR descriptor.failure_code IS NOT NULL + OR descriptor.failure_message IS NOT NULL + OR descriptor.result_digest IS NULL + )) + OR (descriptor.outcome_status = 'FAILED' AND ( + NEW.runtime_surface IS DISTINCT FROM 'UNSUPPORTED_CAPTURE_V1' + OR descriptor.failure_code IS DISTINCT FROM 'INVALID_TEMPLATE_CONFIGURATION' + OR descriptor.failure_message IS DISTINCT FROM + 'INVALID_TEMPLATE_CONFIGURATION: captured template has unsupported World, Entity, or Automation references' + OR descriptor.game_template_id IS NOT NULL + OR descriptor.version_id IS NOT NULL + OR descriptor.script_patch_version IS NOT NULL + OR descriptor.runtime_flags_json IS NOT NULL + OR descriptor.generation_config_revision IS NOT NULL + OR descriptor.version_state_epoch IS NOT NULL + OR descriptor.release_bundle_id IS NOT NULL + OR descriptor.published_release_bundle_ref IS NOT NULL + OR descriptor.remap_set_id IS NOT NULL + OR descriptor.result_digest IS NOT NULL + )) THEN + RAISE EXCEPTION 'StartSession launch descriptor binding differs from exact immutable owner evidence' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_start_session_launch_descriptor_binding + BEFORE INSERT OR UPDATE OR DELETE ON game_design_start_session_launch_descriptor_binding + FOR EACH ROW EXECUTE FUNCTION guard_gd_start_session_launch_descriptor_binding(); + +CREATE FUNCTION reject_gd_start_session_launch_descriptor_binding_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'StartSession launch descriptor bindings are retained' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_start_session_launch_descriptor_binding_no_truncate + BEFORE TRUNCATE ON game_design_start_session_launch_descriptor_binding + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_start_session_launch_descriptor_binding_truncate(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java new file mode 100644 index 0000000000..07b5f33260 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -0,0 +1,1975 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import com.google.protobuf.util.JsonFormat; +import io.grpc.BindableService; +import io.grpc.Context; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +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.stub.StreamObserver; +import io.grpc.util.MutableHandlerRegistry; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.DraftCommitOrderReadClient; +import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityClient; +import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; +import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyClient; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadClient; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; +import net.firedevops.firemud.common.gamelogic.GrpcAccountGameLogicIntakeSettlementReadClient; +import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeAuthorizationClient; +import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeRetainClient; +import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeSourceReadClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcomeRepository; +import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.draft.GameDesignWorldSourceCommitService; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.entity.GameAsset; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.mapper.VersionMapper; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.AssetSource; +import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadGrpcService; +import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadService; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventoryReadService; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicIntakeCommandService; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptService; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation.SourceRead; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociationRepository; +import net.firedevops.firemud.gamedesign.publication.StartSessionLaunchDescriptorProducer; +import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; +import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository; +import net.firedevops.firemud.gamedesign.publication.TemplateReferenceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptParticipantDigestRepository; +import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.RevisionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; +import net.firedevops.firemud.gamedesign.repository.VersionAssetPurgeWorkflowRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; +import net.firedevops.firemud.gamedesign.service.AssetExportService.SelectedExportResult; +import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.PublishAttemptService; +import net.firedevops.firemud.gamedesign.service.PublishGateService; +import net.firedevops.firemud.gamedesign.service.RecordedParticipantDigestService; +import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; +import net.firedevops.firemud.gamedesign.service.impl.AssetExportServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateService; +import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.PublishedReleaseBundleServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeGrpcService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeRepository; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadGrpcService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadService; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftCommitOrderVerifier; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphAppliedResult; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcomeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplicationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplyGrpcService; +import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; +import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mapstruct.factory.Mappers; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import software.amazon.awssdk.core.ResponseBytes; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; +import tools.jackson.databind.ObjectMapper; + +/** + * Real original GD+World source settlement and Account/GL intake-to-GD-receipt, followed by actual + * selected inventory/export, the owner-local publication finalizer, and descriptor SQL storage. + * Selected-publication Account/freeze/inventory admission and release participant collection are + * stipulated; in-memory S3 and StartSession Account projection are test doubles. This is not a + * four-owner authenticated release, runtime launch, activation, or registration proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GenuineSelectedPublicationExportPostgresIntegrationTest { + private static final String NAMESPACE = "firemud"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + private static final PostgreSQLContainer GAME_DESIGN_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final PostgreSQLContainer WORLD_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final PostgreSQLContainer ACCOUNT_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final PostgreSQLContainer GAME_LOGIC_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("selected-export-account-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + private static final GenericContainer REDIS_REPLICA = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(REDIS) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "selected-export-account-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Exception { + var gd = gameDesignStore(); + var world = serviceStore(WORLD_POSTGRES, "world-management"); + var gameLogic = serviceStore(GAME_LOGIC_POSTGRES, "game-logic"); + var pki = new TestPki(temporary.resolve("pki")); + var gdHandlers = new MutableHandlerRegistry(); + var worldHandlers = new MutableHandlerRegistry(); + var accountHandlers = new MutableHandlerRegistry(); + var gameLogicHandlers = new MutableHandlerRegistry(); + Map startSessionProjections = new ConcurrentHashMap<>(); + + Server gdServer = startServer(pki, "game-design-service", gdHandlers); + Server worldServer = startServer(pki, "world-management-service", worldHandlers); + Server accountServer = startServer(pki, "account-service", accountHandlers); + Server gameLogicServer = startServer(pki, "game-logic-service", gameLogicHandlers); + try (var account = + new AccountControlUiOriginalOrderFixture( + ACCOUNT_POSTGRES.getJdbcUrl(), + ACCOUNT_POSTGRES.getUsername(), + ACCOUNT_POSTGRES.getPassword(), + REDIS.getHost(), + REDIS.getMappedPort(6379), + temporary.resolve("account"), + gd.target().canonicalTenantId())) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService(loopback(accountServer)); + endpoints.setGameDesignService(loopback(gdServer)); + endpoints.setWorldManagementService(loopback(worldServer)); + endpoints.setGameLogicService(loopback(gameLogicServer)); + var channels = new GrpcChannelFactory(); + + var sourceRepository = new GameAuthoredWorldSourceRepository(gd.dsl()); + register( + gdHandlers, + new TenantIdentityGrpcService( + new GameTenantCreationRepository(gd.dsl(), new GameRepository(gd.dsl())), + sourceRepository, + NAMESPACE), + new AuthoredWorldVersionStateGrpcService( + new AuthoredWorldVersionStateService(gd.transactions(), sourceRepository), + NAMESPACE)); + + var worldIntakes = new WorldAuthoredSourceIntakeRepository(world.dsl()); + var worldIdentities = new WorldAuthoredVersionIdentityRepository(world.dsl()); + var accountRepository = + new AccountGameLogicIntakeAuthorizationRepository( + account.preparedOriginalCreator().sources().dsl); + var accountAccess = account.preparedOriginalCreator(); + + try (var sourceClient = + new AuthoredWorldSourceClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var versionClient = + new net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var worldIntakeClient = + new WorldAuthoredSourceIntakeClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var worldIdentityClient = + new WorldAuthoredVersionIdentityClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var accountOriginalOrderClient = + new AccountOriginalDraftOrderClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var accountHeldOrderClient = + new DraftCommitOrderReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var worldApplyClient = + new WorldOriginalDraftGraphApplyClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var gdTerminalClient = + new GameDesignDraftTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var worldTerminalClient = + new WorldDraftTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var accountToGdSource = + new GameplayRuleSourceReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var gdToAccountPermission = + new GrpcGameLogicIntakeSourceReadClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var glToAccountHeld = + new GameLogicIntakeAuthorizationReadClient( + endpoints, pki.client("game-logic-service"), channels, NAMESPACE); + var glToGdSource = + new GameplayRuleSourceReadClient( + endpoints, pki.client("game-logic-service"), channels, NAMESPACE); + var accountToGlTerminal = + new GameLogicIntakeTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var gdToAccountIntakeAuthorization = + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var gdToGlRetain = + new GrpcGameLogicIntakeRetainClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var gdToAccountSettlement = + new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + sourceClient.init(); + versionClient.init(); + var worldIntakeOwner = + new WorldAuthoredSourceIntakeService( + sourceClient, worldIntakes, world.transactions(), NAMESPACE); + var worldIdentityOwner = + new WorldAuthoredVersionIdentityService( + versionClient, worldIdentities, worldIntakes, world.transactions(), NAMESPACE); + register( + worldHandlers, + new WorldAuthoredSourceIntakeGrpcService(worldIntakeOwner, NAMESPACE), + new WorldAuthoredVersionIdentityGrpcService(worldIdentityOwner, NAMESPACE)); + worldIntakeClient.init(); + worldIdentityClient.init(); + + var worldSource = + gd.transaction( + () -> + sourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + gd.target().canonicalTenantId(), + "genuine-selected-export-tenant", + "genuine-selected-export-world", + "Genuine selected export source")); + var worldIntakeRequest = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + UUID.randomUUID(), + worldSource.canonicalTenantId(), + worldSource.worldSlug(), + worldSource.operationId(), + worldSource.evidenceDigest()); + var worldIntakeReceipt = worldIntakeClient.intake(worldIntakeRequest); + var worldIdentityRequest = + new WorldAuthoredVersionIdentityEvidence.Request( + 1, + NAMESPACE, + worldSource.canonicalTenantId(), + worldSource.worldSlug(), + worldSource.operationId(), + worldSource.evidenceDigest(), + gd.target().canonicalVersionId(), + gd.target().gameDesignVersionRowId(), + UUID.randomUUID()); + var worldIdentityReceipt = worldIdentityClient.associate(worldIdentityRequest); + assertThat(worldIdentityReceipt.sourceIntakeReceipt()).isEqualTo(worldIntakeReceipt); + + var assetBytes = "actual selected resource bytes".getBytes(StandardCharsets.UTF_8); + GameAsset assetToSave = new GameAsset(); + assetToSave.setTenantId(gd.target().gameDesignVersionTenantKey()); + assetToSave.setFileName("selected-resource.txt"); + assetToSave.setContentType("text/plain"); + assetToSave.setData(assetBytes); + GameAsset sourceAsset = + gd.transaction(() -> new GameAssetRepository(gd.dsl()).save(assetToSave)); + var selectedCommit = binding(gd.target(), sourceAsset.getId(), sourceAsset.getFileName()); + var originalOrder = account.prepareOriginalDraftOrder(selectedCommit, NAMESPACE); + var original = originalOrder.original(); + + register( + accountHandlers, + account.originalDraftOrderProducer(NAMESPACE), + new AccountDraftCommitOrderReadGrpcService( + account.heldOrderOwner(NAMESPACE), NAMESPACE)); + + var coordinator = new DraftCommitCoordinatorRepository(gd.dsl()); + var gdTerminals = new GameDesignDraftTerminalOutcomeRepository(gd.dsl()); + var gdSources = new GameDesignSourceRepository(gd.dsl()); + var worldFence = new WorldDesignPublicationFenceRepository(world.dsl(), worldIntakes); + var worldApplications = + new WorldDraftGraphApplicationRepository(world.dsl(), worldFence, new ObjectMapper()); + var worldApplicationService = + new WorldDraftGraphApplicationService( + worldApplications, + world.transactions(), + new WorldDraftCommitOrderVerifier(accountHeldOrderClient, NAMESPACE)); + var worldOriginalApply = + new WorldOriginalDraftGraphApplicationService( + worldIdentities, worldIntakes, worldApplicationService); + register( + worldHandlers, + new WorldOriginalDraftGraphApplyGrpcService(worldOriginalApply, NAMESPACE), + new WorldDraftTerminalReadGrpcService( + new WorldDraftTerminalOutcomeRepository( + world.dsl(), worldFence, new ObjectMapper()), + worldApplications, + NAMESPACE)); + + register( + gdHandlers, + new GameDesignDraftTerminalReadGrpcService(gdTerminals, NAMESPACE), + new GameDesignGameplayRuleSourceReadGrpcService( + new GameDesignGameplayRuleSourceReadService( + new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository( + gd.dsl()), + gd.transactions(), + gdToAccountPermission, + NAMESPACE), + NAMESPACE)); + + var glRepository = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); + var accountAuthorizationOwner = + new AccountGameLogicIntakeAuthorizationService( + accountAccess.actors(), + accountAccess.sources().fences, + accountRepository, + accountToGdSource, + accountAccess.sources().manager, + NAMESPACE); + var accountSourcePermissionOwner = + new AccountGameLogicIntakeSourceReadService( + accountRepository, + account.coordination(), + accountAccess.sources().manager, + Clock.systemUTC(), + NAMESPACE); + var accountHeldAuthorizationOwner = + new AccountGameLogicIntakeAuthorizationReadService( + accountRepository, accountAccess.sources().manager, NAMESPACE); + var accountSettlementOwner = + new AccountGameLogicIntakeSettlementService( + accountRepository, accountToGlTerminal, accountAccess.sources().manager, NAMESPACE); + register( + accountHandlers, + new AccountGameLogicIntakeAuthorizationGrpcService( + accountAuthorizationOwner, accountAccess.sources().terms, NAMESPACE), + new AccountGameLogicIntakeSourceReadGrpcService( + accountSourcePermissionOwner, NAMESPACE), + new AccountGameLogicIntakeAuthorizationReadGrpcService( + accountHeldAuthorizationOwner, NAMESPACE), + new AccountGameLogicIntakeSettlementGrpcService(accountSettlementOwner, NAMESPACE)); + register(accountHandlers, accountProjectionDouble(startSessionProjections)); + + var glOwner = + new GameLogicGameplayRuleIntakeService( + glRepository, gameLogic.transactions(), glToAccountHeld, glToGdSource, NAMESPACE); + register( + gameLogicHandlers, + new GameLogicGameplayRuleIntakeGrpcService(glOwner, NAMESPACE), + new GameLogicGameplayRuleIntakeTerminalReadGrpcService( + new GameLogicGameplayRuleIntakeTerminalReadService(glRepository, NAMESPACE), + NAMESPACE)); + + accountOriginalOrderClient.init(); + accountHeldOrderClient.init(); + worldApplyClient.init(); + gdTerminalClient.init(); + worldTerminalClient.init(); + accountToGdSource.init(); + gdToAccountPermission.init(); + glToAccountHeld.init(); + glToGdSource.init(); + accountToGlTerminal.init(); + gdToAccountIntakeAuthorization.init(); + gdToGlRetain.init(); + gdToAccountSettlement.init(); + + var sourceCommit = + new GameDesignWorldSourceCommitService( + accountOriginalOrderClient, + worldApplyClient, + coordinator, + gdTerminals, + gdSources, + gd.transactions(), + NAMESPACE); + var originalTerminal = + sourceCommit.commit(original, originalOrder.originalCreatorCredential()); + assertThat(originalTerminal.result()) + .isEqualTo( + net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcome.Result + .COMMITTED); + account.assertOriginalDraftOrderPending(original); + account.reconcileOriginalDraft(original, gdTerminalClient, worldTerminalClient, NAMESPACE); + account.reconcileOriginalDraft(original, gdTerminalClient, worldTerminalClient, NAMESPACE); + assertThat( + accountAccess + .sources() + .tx(() -> accountAccess.sources().fences.readSettlement(original))) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.COMMITTED); + var appliedWorld = + worldApplications.readCommitted(NAMESPACE, original.canonicalBytes()).orElseThrow(); + assertThat(appliedWorld.status()).isEqualTo("APPLIED"); + assertThat(appliedWorld.startLocationReceipt()).isPresent(); + assertThat(world.dsl().fetchCount(DSL.table("world_draft_graph_application"))).isOne(); + + var templateSource = + new TemplateConfigSourceRepository(gd.dsl()) + .readSnapshot(gd.target(), selectedCommit.commitId()) + .orElseThrow(); + assertThat(templateSource.entries()).hasSize(1); + long templateId = Long.parseLong(templateSource.entries().getFirst().templateId()); + var enforcedPhase = + new TemplateReferenceRepository(gd.dsl()) + .readPhase(gd.target().canonicalTenantId()) + .orElseThrow(); + assertThat(enforcedPhase.phase()).isEqualTo(TemplateReferenceRepository.Phase.ENFORCED); + assertThat(enforcedPhase.inventoryTemplateCount()).isEqualTo(1L); + var normalizedBase = + new TemplateReferenceRepository(gd.dsl()) + .readExactBaseReference(gd.target().canonicalTenantId(), templateId) + .orElseThrow(); + assertThat(normalizedBase.canonicalVersionId()).isEqualTo(gd.target().canonicalVersionId()); + assertThat(normalizedBase.sourceCommitId()).isEqualTo(selectedCommit.commitId()); + assertThat(normalizedBase.sourceRevisionId()) + .isEqualTo(templateSource.entries().getFirst().revisionId()); + + String publishRequestId = UUID.randomUUID().toString(); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + gd.target().canonicalTenantId(), + gd.target().canonicalVersionId(), + publishRequestId, + Long.toString(gd.version().getVersionStateEpoch()), + "genuine selected inventory and export proof", + selectedCommit.requestId(), + selectedCommit.commitId(), + selectedCommit.digest()); + var selection = + gd.transaction( + () -> + new AuthoredDraftPublishSelectionRepository(gd.dsl(), coordinator) + .reserve(intent) + .selection()); + var intakeRequest = + GameLogicIntakeAuthorizationEvidence.Request.create( + NAMESPACE, UUID.randomUUID(), selection.selectedCommit()); + var receiptService = + new SelectedDraftGameLogicReceiptService( + gd.dsl(), gd.transactions(), gdToGlRetain, gdToAccountSettlement, NAMESPACE); + var intakeCommand = + new SelectedDraftGameLogicIntakeCommandService( + gd.dsl(), gdToAccountIntakeAuthorization, receiptService, NAMESPACE); + SelectedDraftGameLogicReceipt retainedReceipt = + intakeCommand.authorizeAndRetain( + selection, intakeRequest, originalOrder.originalCreatorCredential()); + SelectedDraftGameLogicReceipt exactRetry = + intakeCommand.recoverAndRetain( + selection, intakeRequest, originalOrder.originalCreatorCredential()); + assertThat(exactRetry.selection().canonicalBytes()) + .containsExactly(retainedReceipt.selection().canonicalBytes()); + assertThat(exactRetry.authorization().canonicalBytes()) + .containsExactly(retainedReceipt.authorization().canonicalBytes()); + assertThat(exactRetry.receipt().canonicalBytes()) + .containsExactly(retainedReceipt.receipt().canonicalBytes()); + assertThat(retainedReceipt.selection().canonicalBytes()) + .containsExactly(selection.canonicalBytes()); + assertThat(retainedReceipt.authorization().source().binding().canonicalBytes()) + .containsExactly(selection.selectedCommit().canonicalBytes()); + assertThat(retainedReceipt.receipt().terminal().outcome()) + .isEqualTo(GameLogicGameplayRuleIntakeTerminal.Outcome.RETAINED); + assertThat( + glRepository + .findTerminal(retainedReceipt.authorization().operationId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(retainedReceipt.receipt().terminal().canonicalBytes()); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount(DSL.table("account_game_logic_intake_settlements"))) + .isOne(); + assertThat(gd.dsl().fetchCount(DSL.table("game_design_selected_game_logic_receipt"))) + .isOne(); + + var selectorEvidence = + selectedPublicationWorldEvidence( + original, appliedWorld, selectedCommit, selection, intent, publishRequestId); + GameDesignPublicationOperation publicationOperation = + IsolatedPublicationOperationFixtures.forSelection( + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + selectorEvidence); + var selectedWorldSourceRequest = + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + NAMESPACE, + UUID.randomUUID(), + appliedWorld.application().operation().ownerBinding().intakeRequestId(), + gd.target().canonicalTenantId()); + var selectedWorldSourceRead = + new SourceRead( + selectedWorldSourceRequest, worldIntakeClient.readById(selectedWorldSourceRequest)); + var publicationReservation = + gd.transaction( + () -> + new SelectedDraftPublicationOwner(gd.dsl()) + .reserve( + intent, + publicationOperation.account(), + publicationOperation.world(), + publicationOperation.inventory(), + selectedWorldSourceRead)); + var retainedTemplateAssociations = + new SelectedDraftTemplateWorldSourceAssociationRepository(gd.dsl()) + .readExact( + publicationReservation.operation(), + publicationReservation.sourceCapture().templateConfig()); + assertThat(retainedTemplateAssociations).hasSize(1); + assertThat(retainedTemplateAssociations.getFirst().templateId()).isEqualTo(templateId); + + var publicationRequest = + PublicationDigestRequestBinding.full( + gd.target().canonicalTenantId().toString(), + Long.toString(gd.target().gameDesignVersionRowId()), + publishRequestId); + var inventoryReader = + new SelectedDraftAssetInventoryReadService(gd.dsl(), gd.transactions()); + SelectedDraftAssetInventory actualInventory = inventoryReader.read(publicationRequest); + assertThat(actualInventory.assets()).hasSize(1); + assertThat(actualInventory.assets().getFirst().usageKey()) + .isEqualTo("selected-resource.txt"); + assertThat(actualInventory.assets().getFirst().contentBytes()).containsExactly(assetBytes); + assertThat(actualInventory.sourceFamilyDeclarations()) + .containsEntry("ORDINARY", "PRESENT") + .containsEntry("GAMEPLAY_RULE", "PRESENT") + .containsEntry("TEMPLATE_CONFIG", "PRESENT"); + assertThat(actualInventory.gameLogicReceipt().selection().canonicalBytes()) + .containsExactly(retainedReceipt.selection().canonicalBytes()); + assertThat(actualInventory.gameLogicReceipt().authorization().canonicalBytes()) + .containsExactly(retainedReceipt.authorization().canonicalBytes()); + assertThat(actualInventory.gameLogicReceipt().receipt().canonicalBytes()) + .containsExactly(retainedReceipt.receipt().canonicalBytes()); + + var candidateService = + new VersionAssetExportCandidateServiceImpl( + gd.dsl(), + new GameRepository(gd.dsl()), + new VersionRepository(gd.dsl()), + gd.transactions(), + new ObjectMapper()); + var objectStore = new InMemoryConditionalObjectStore(candidateService, publicationRequest); + objectStore.requireCandidateBeforeWrites(actualInventory); + var properties = new AssetStoreProperties(); + properties.setEndpoint("https://objects.invalid"); + properties.setBucket("genuine-selected-export-test"); + var exporter = + new AssetExportServiceImpl( + new VersionAssetPublicationRepository(gd.dsl()), + objectStore.client(), + properties, + new ObjectMapper(), + gd.dsl(), + gd.transactions(), + candidateService); + + SelectedExportResult first = exporter.exportSelectedAssets(publicationRequest); + assertThat(first.candidateBinding().inventoryBytes()) + .containsExactly(actualInventory.canonicalBytes()); + assertThat(first.candidateBinding().inventoryDigest()).isEqualTo(actualInventory.digest()); + assertThat(first.candidateBinding().selectedCommitDigest()) + .isEqualTo(selectedCommit.digest()); + assertThat(first.manifest().artifactDigests()).hasSize(1); + assertThat(first.manifest().artifactDigests().getFirst().contentDigest()) + .isEqualTo(actualInventory.assets().getFirst().contentDigest()); + assertThat(first.manifest().artifactDigests().getFirst().contentDigest()) + .isEqualTo("sha256:" + sha256(assetBytes)); + assertThat(objectStore.objects()).hasSize(2); + assertThat(objectStore.bytesAt("artifacts/sha256/" + sha256(assetBytes))) + .containsExactly(assetBytes); + assertThat(objectStore.contentTypeAt("artifacts/sha256/" + sha256(assetBytes))) + .isEqualTo("text/plain"); + assertThat( + objectStore.bytesAt( + "manifests/sha256/" + first.manifest().manifestHash().substring(7))) + .containsExactly(first.candidateBinding().manifestBytes()); + + SelectedExportResult retry = exporter.exportSelectedAssets(publicationRequest); + assertThat(retry).isEqualTo(first); + assertThat(objectStore.putCalls()).isEqualTo(4); + assertThat(objectStore.getCalls()).isEqualTo(4); + assertThat(candidateService.readSelectedCandidate(publicationRequest)) + .isEqualTo(first.candidateBinding()); + assertThat(gd.dsl().fetchCount(DSL.table("version_asset_export_candidate"))).isOne(); + + byte[] alteredManifestBytes = alteredManifest(first.candidateBinding().manifestBytes()); + var alteredManifest = + new ExportedAssetManifest( + "sha256:" + sha256(alteredManifestBytes), + 1, + first.manifest().requiredManifestAssetKeys(), + first.manifest().artifactDigests()); + assertThatThrownBy( + () -> + candidateService.recordSelectedCandidate( + actualInventory, alteredManifest, alteredManifestBytes)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("SELECTED_ASSET_EXPORT_CANDIDATE_CONFLICT"); + assertThat(candidateService.readSelectedCandidate(publicationRequest)) + .isEqualTo(first.candidateBinding()); + + int writesBeforeSubstitution = objectStore.putCalls(); + var changedPublicationRequest = + PublicationDigestRequestBinding.full( + publicationRequest.tenantId(), + publicationRequest.versionId(), + "different-selected-publication-request"); + assertThatThrownBy(() -> exporter.exportSelectedAssets(changedPublicationRequest)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.NOT_FOUND)); + assertThat(objectStore.putCalls()).isEqualTo(writesBeforeSubstitution); + assertThat(candidateService.readSelectedCandidate(publicationRequest)) + .isEqualTo(first.candidateBinding()); + assertThat(gd.dsl().fetchCount(DSL.table("game_design_selected_game_logic_receipt"))) + .isOne(); + + var mapper = Mappers.getMapper(VersionMapper.class); + var publishAttemptRepository = new PublishAttemptRepository(gd.dsl()); + var releaseRepository = new PublishedReleaseBundleRepository(gd.dsl()); + var releaseService = + new PublishedReleaseBundleServiceImpl( + releaseRepository, + new RevisionRepository(gd.dsl()), + new VersionRepository(gd.dsl()), + new ObjectMapper()); + var artifactService = + new VersionAssetArtifactServiceImpl( + new VersionAssetArtifactRepository(gd.dsl()), + new VersionAssetPurgeWorkflowRepository(gd.dsl()), + new VersionRepository(gd.dsl()), + releaseRepository, + new LaunchDescriptorRepository(gd.dsl()), + new VersionTemplateRemapSetRepository(gd.dsl()), + exporter, + releaseService, + new ObjectMapper()); + var participantDigests = + stipulatedSelectorParticipantDigests( + publicationOperation.world(), selectedCommit, gd.target().gameDesignVersionRowId()); + var gate = mock(PublishGateService.class); + when(gate.collectSelectedFullVersionParticipantDigests(any(), any(), any())) + .thenReturn(participantDigests); + var controlPlaneDigests = + new net.firedevops.firemud.gamedesign.service.impl.ControlPlaneDigestServiceImpl( + new net.firedevops.firemud.gamedesign.repository.GameTemplateRepository(gd.dsl()), + new GameAssetRepository(gd.dsl()), + new RevisionRepository(gd.dsl()), + new ObjectMapper()); + var realAttemptPersistence = + new PublishAttemptServiceImpl( + publishAttemptRepository, new PublishAttemptParticipantDigestRepository(gd.dsl())); + var publisher = + new VersionPublishCommandServiceImpl( + new VersionRepository(gd.dsl()), + new GameRepository(gd.dsl()), + publishAttemptRepository, + mapper, + exporter, + transactionBoundPublishAttempts(gd, realAttemptPersistence), + gate, + controlPlaneDigests, + artifactService, + releaseService, + mock(RecordedParticipantDigestService.class)); + var published = + publisher.publishSelectedDraftFullVersion( + gd.target().gameDesignVersionTenantKey(), + gd.target().gameDesignVersionRowId(), + intent.notes(), + publishRequestId, + publicationRequest.derivedWorkflowIdentity()); + assertThat(published.versionState()).isEqualTo(VersionLifecycleState.PUBLISHED); + assertThat( + new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository(gd.dsl()) + .findByPublishWorkflowId(publicationRequest.derivedWorkflowIdentity()) + .orElseThrow() + .getStatus()) + .isEqualTo(net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); + var release = + releaseService.getPublishedReleaseBundle( + gd.target().gameDesignVersionTenantKey(), gd.target().gameDesignVersionRowId()); + assertThat(release.attestationSchemaVersion()).isEqualTo("v2"); + assertThat(release.worldPublishedStartLocationEvidence()) + .isEqualTo(publicationOperation.world()); + assertThat(gd.dsl().fetchCount(DSL.table("published_release_bundle"))).isOne(); + assertThat( + gd.dsl() + .fetchCount(DSL.table("game_design_start_session_launch_descriptor_binding"))) + .isZero(); + + var association = retainedTemplateAssociations.getFirst(); + var pinnedSelection = + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + gd.target().canonicalVersionId(), + selectedCommit.commitId(), + publicationRequest.derivedWorkflowIdentity(), + association.digest()); + String controlPlaneRequestId = "genuine-start-session-" + UUID.randomUUID(); + UUID ownerAttemptId = UUID.randomUUID(); + long ownerFence = 19L; + var startSessionTuple = + startSessionTuple( + controlPlaneRequestId, + gd.target().canonicalTenantId(), + templateId, + "Genuine selected descriptor storage proof"); + startSessionProjections.put( + controlPlaneRequestId, + new StartSessionProjectionBinding(startSessionTuple, ownerAttemptId, ownerFence)); + try (var projectionClient = + new StartSessionRedeemedOperationProjectionClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + projectionClient.init(); + var associationReader = + new StartSessionTemplateAssociationReadService( + gd.dsl(), gd.transactions(), NAMESPACE, projectionClient, releaseService); + var descriptorProducer = + new StartSessionLaunchDescriptorProducer( + gd.dsl(), + gd.transactions(), + NAMESPACE, + associationReader, + releaseService, + new ObjectMapper()); + var firstDescriptorBinding = + withGameSessionPeer( + () -> + descriptorProducer.resolve( + startSessionReadRequest( + startSessionTuple, + ownerAttemptId, + ownerFence, + pinnedSelection, + UUID.randomUUID()))); + assertThat(firstDescriptorBinding.descriptor().versionId()) + .isEqualTo(gd.target().gameDesignVersionRowId()); + assertThat(firstDescriptorBinding.descriptor().launchDescriptorId()).isNotBlank(); + assertThat(firstDescriptorBinding.associationRead().association().associationDigest()) + .isEqualTo(association.digest()); + + var replay = + withGameSessionPeer( + () -> + descriptorProducer.resolve( + startSessionReadRequest( + startSessionTuple, + ownerAttemptId, + ownerFence, + pinnedSelection, + UUID.randomUUID()))); + assertThat(replay.descriptor()).isEqualTo(firstDescriptorBinding.descriptor()); + assertThat(replay.associationRead().request().readRequestId()) + .isNotEqualTo(firstDescriptorBinding.associationRead().request().readRequestId()); + + var changedTuple = + startSessionTuple( + controlPlaneRequestId, + gd.target().canonicalTenantId(), + templateId, + "Changed original StartSession tuple"); + // The fixed Account projection double returns the original operation; these altered + // tuple/attempt/fence requests are rejected before Game Design opens its SQL snapshot. + assertProjectionUnavailable( + "original operation tuple", + () -> + withGameSessionPeer( + () -> + descriptorProducer.resolve( + startSessionReadRequest( + changedTuple, + ownerAttemptId, + ownerFence, + pinnedSelection, + UUID.randomUUID())))); + + assertProjectionUnavailable( + "owner attempt", + () -> + withGameSessionPeer( + () -> + descriptorProducer.resolve( + startSessionReadRequest( + startSessionTuple, + UUID.randomUUID(), + ownerFence, + pinnedSelection, + UUID.randomUUID())))); + assertProjectionUnavailable( + "owner fence", + () -> + withGameSessionPeer( + () -> + descriptorProducer.resolve( + startSessionReadRequest( + startSessionTuple, + ownerAttemptId, + ownerFence + 1L, + pinnedSelection, + UUID.randomUUID())))); + var changedSelection = + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + gd.target().canonicalVersionId(), + selectedCommit.commitId(), + publicationRequest.derivedWorkflowIdentity(), + "sha256:" + "0".repeat(64)); + assertFailedPrecondition( + () -> + withGameSessionPeer( + () -> + descriptorProducer.resolve( + startSessionReadRequest( + startSessionTuple, + ownerAttemptId, + ownerFence, + changedSelection, + UUID.randomUUID())))); + } + assertThat(gd.dsl().fetchCount(DSL.table("launch_descriptor"))).isOne(); + assertThat( + gd.dsl() + .fetchCount(DSL.table("game_design_start_session_launch_descriptor_binding"))) + .isOne(); + assertThat(gd.dsl().fetchCount(DSL.table("published_release_bundle"))).isOne(); + assertThat(candidateService.readSelectedCandidate(publicationRequest)) + .isEqualTo(first.candidateBinding()); + } + } finally { + stopAll(gameLogicServer, accountServer, worldServer, gdServer); + } + } + + /** + * Release participant rows are structurally valid test inputs, not authenticated owner digests. + * World source application and the selected Game Logic receipt are separately retained above; + * this fixture does not claim complete participant collection or a four-owner publication. + */ + private static List stipulatedSelectorParticipantDigests( + WorldPublishedStartLocationEvidence worldEvidence, + DraftCommitBinding selectedCommit, + long versionRowId) { + var world = worldEvidence.request(); + return AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + participant -> { + String contentDigest = + "WORLD_MANAGEMENT".equals(participant) ? world.contentDigest() : "c".repeat(64); + String abilityDigest = + "GAME_LOGIC".equals(participant) ? "sha256:" + "d".repeat(64) : null; + return new PublishParticipantDigestDto( + participant, + Long.toString(versionRowId), + null, + selectedCommit.commitId().toString(), + contentDigest, + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + abilityDigest, + null, + null); + }) + .toList(); + } + + /** Uses the real owner persistence service inside the fixture's explicit READ_COMMITTED tx. */ + private static PublishAttemptService transactionBoundPublishAttempts( + Store store, PublishAttemptServiceImpl delegate) { + return new PublishAttemptService() { + @Override + public T executeScriptPatchTransaction(Supplier operation) { + return delegate.executeScriptPatchTransaction(() -> store.transaction(operation)); + } + + @Override + public T executeFullVersionTransaction(Supplier operation) { + return delegate.executeFullVersionTransaction(() -> store.transaction(operation)); + } + + @Override + public void createFullVersionAttempt( + net.firedevops.firemud.gamedesign.dto.VersionDto version, + String workflowId, + String requestDigest) { + delegate.createFullVersionAttempt(version, workflowId, requestDigest); + } + + @Override + public void createScriptPatchAttempt( + net.firedevops.firemud.gamedesign.dto.VersionDto version, + String workflowId, + Long baseVersionId, + String requestDigest) { + delegate.createScriptPatchAttempt(version, workflowId, baseVersionId, requestDigest); + } + + @Override + public void recordScriptPatchParticipantDigests( + String workflowId, List digests) { + delegate.recordScriptPatchParticipantDigests(workflowId, digests); + } + + @Override + public void markScriptPatchSucceeded(String workflowId) { + delegate.markScriptPatchSucceeded(workflowId); + } + + @Override + public void markScriptPatchFailed(String workflowId, String code, String message) { + delegate.markScriptPatchFailed(workflowId, code, message); + } + + @Override + public java.util.Optional + findByPublishWorkflowId(String workflowId) { + return delegate.findByPublishWorkflowId(workflowId); + } + + @Override + public void recordFullVersionParticipantDigests( + String workflowId, List digests) { + delegate.recordFullVersionParticipantDigests(workflowId, digests); + } + + @Override + public void markFullVersionSucceeded(String workflowId) { + delegate.markFullVersionSucceeded(workflowId); + } + + @Override + public void markFullVersionFailed(String workflowId, String code, String message) { + delegate.markFullVersionFailed(workflowId, code, message); + } + }; + } + + /** Test-only Account projection responder that replays a fixed original tuple and fence. */ + private static BindableService accountProjectionDouble( + Map projections) { + return new StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceImplBase() { + @Override + public void readRedeemedOperationProjection( + ReadRedeemedOperationProjectionRequest request, + StreamObserver responseObserver) { + try { + var requestedPreTuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + request + .getCanonicalPreAuthorizationTupleBytes() + .toString(StandardCharsets.UTF_8)); + var original = + Objects.requireNonNull( + projections.get(requestedPreTuple.controlPlaneRequestId()), + "No stipulated Account projection was registered for this logical operation"); + var tuple = original.tuple(); + var preTuple = tuple.preAuthorizationTuple(); + var bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + var reference = tuple.bundleReference(); + Instant redeemedAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); + var response = + ReadRedeemedOperationProjectionResponse.newBuilder() + .setControlPlaneRequestId(preTuple.controlPlaneRequestId()) + .setCanonicalPreAuthorizationTupleBytes( + ByteString.copyFrom(preTuple.canonicalJson(), StandardCharsets.UTF_8)) + .setMutationDigest(preTuple.mutationDigest()) + .setAuthorizationReferenceFingerprint(tuple.authorizationReferenceFingerprint()) + .setReservationOwnerId(tuple.reservationOwnerId().toString()) + .setReservationClaimFence(tuple.reservationClaimFence()) + .setAuthenticatedRedeemerWorkloadIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service") + .setOwnerAttemptId(original.ownerAttemptId().toString()) + .setOwnerFence(original.ownerFence()) + .setReferenceExpiresAt(timestamp(Instant.parse(bundle.authorizationExpiresAt()))) + .setRedeemedAt(timestamp(redeemedAt)) + .setIssuanceOperationId(bundle.issuanceOperationId().toString()) + .setIssuanceFence(Long.parseLong(bundle.issuanceFence())) + .setBundleReference( + AuthorityEvidenceBundleReference.newBuilder() + .setBundleVersion(reference.bundleVersion()) + .setSourceVersion(reference.sourceVersion()) + .setSourceFence(reference.sourceFence()) + .setLinearization(reference.linearization())) + .setAuthorityEvidenceBundle( + ByteString.copyFrom(tuple.authorityEvidenceBundleBytes())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (RuntimeException invalid) { + responseObserver.onError(invalid); + } + } + }; + } + + private static StartSessionPostAuthorizationExecutionTuple startSessionTuple( + String controlPlaneRequestId, UUID canonicalTenantId, long templateId, String auditReason) { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(canonicalTenantId, NAMESPACE), + new StartSessionOperatorAction.Target(templateId, UUID.randomUUID()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + controlPlaneRequestId, UUID.randomUUID(), action); + var reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + var now = Instant.now().minusSeconds(1).truncatedTo(ChronoUnit.MILLIS); + var authority = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", canonicalTenantId.toString(), "targetNamespace", NAMESPACE), + "actionFamily", + preTuple.actionFamily(), + "applicableAccountId", + preTuple.actor().accountId().toString(), + "applicableTenantId", + canonicalTenantId.toString()), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + now.toString(), + "expiresAt", + now.plusSeconds(300).toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + UUID.randomUUID().toString(), + "controlPlaneRequestId", + preTuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + preTuple.controlPlaneRequestId()), + "mutationDigest", + preTuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 2L, + "tenantAuthorityGeneration", + Map.of(canonicalTenantId.toString(), 3L), + "membershipAuthorityGeneration", + Map.of(canonicalTenantId.toString(), 4L), + "privateRealmGrantVersions", + List.of()), + "membershipVersion", + Map.of(canonicalTenantId.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + preTuple.actor().accountId().toString(), + "controlUiTokenJti", + UUID.randomUUID().toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + byte[] authorityBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(new ObjectMapper().writeValueAsString(authority)); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + UUID.randomUUID(), + 19L, + authorityBytes, + reference); + } catch (IOException invalid) { + throw new IllegalStateException("Could not construct stipulated Account tuple", invalid); + } + } + + private static StartSessionTemplateAssociationReadEvidence.Request startSessionReadRequest( + StartSessionPostAuthorizationExecutionTuple tuple, + UUID attemptId, + long fence, + StartSessionTemplateAssociationReadEvidence.Selection selection, + UUID observationId) { + return new StartSessionTemplateAssociationReadEvidence.Request( + StartSessionTemplateAssociationReadEvidence.SCHEMA_VERSION, + NAMESPACE, + observationId, + tuple.canonicalBytes(), + attemptId, + fence, + selection); + } + + private static Timestamp timestamp(Instant value) { + return Timestamp.newBuilder() + .setSeconds(value.getEpochSecond()) + .setNanos(value.getNano()) + .build(); + } + + private static T withGameSessionPeer(Supplier operation) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service", + NAMESPACE, + "game-session-service"); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return operation.get(); + } finally { + context.detach(previous); + } + } + + private static void assertFailedPrecondition(Runnable operation) { + assertThatThrownBy(operation::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + } + + private static void assertProjectionUnavailable(String rejectedEvidence, Runnable operation) { + assertThatThrownBy(operation::run) + .as( + "Account projection rejects changed %s before the Game Design SQL snapshot", + rejectedEvidence) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> { + var status = ((io.grpc.StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(io.grpc.Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("Exact redeemed StartSession projection unavailable"); + }); + } + + private Store gameDesignStore() { + var store = serviceStore(GAME_DESIGN_POSTGRES, "game-design"); + String tenantKey = UUID.randomUUID().toString(); + UUID creationRequestId = UUID.randomUUID(); + var creation = + Objects.requireNonNull( + store.transaction( + () -> + new GameTenantCreationRepository(store.dsl(), new GameRepository(store.dsl())) + .createCandidate( + NAMESPACE, + creationRequestId, + tenantKey, + "Genuine selected export Game", + "Persisted Game Design source and publication identity"))); + assertThat( + new GameTenantCreationRepository(store.dsl(), new GameRepository(store.dsl())) + .read(creationRequestId, NAMESPACE)) + .contains(creation); + assertThat( + new TemplateReferenceRepository(store.dsl()) + .readPhase(creation.canonicalTenantId()) + .orElseThrow() + .phase()) + .isEqualTo(TemplateReferenceRepository.Phase.BACKFILLING); + var version = new Version(); + version.setTenantId(tenantKey); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + var savedVersion = + Objects.requireNonNull( + store.transaction(() -> new VersionRepository(store.dsl()).save(version))); + var target = + new TargetProof( + savedVersion.getCanonicalTenantId(), + savedVersion.getCanonicalVersionId(), + savedVersion.getId(), + savedVersion.getTenantId(), + savedVersion.getIdentitySourceGameRowId(), + savedVersion.getIdentitySourceGameTenantKey(), + savedVersion.getIdentitySourceProvenanceKind()); + assertThat(new GameDesignSourceRepository(store.dsl()).readGenesis(target)).isPresent(); + return store.withIdentity(target, savedVersion); + } + + private static Store serviceStore(PostgreSQLContainer postgres, String service) { + var schema = service.replace('-', '_') + "_" + UUID.randomUUID().toString().replace("-", ""); + var data = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + data.setSchema(schema); + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_" + service.replace('-', '_')) + .placeholders(Map.of("serviceSchema", schema)) + .locations(migrationLocation(service)) + .load() + .migrate(); + return new Store( + DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES), + new DataSourceTransactionManager(data), + null, + null); + } + + private static String migrationLocation(String service) { + var directoryName = service + "-service"; + for (Path current = Path.of("").toAbsolutePath(); + current != null; + current = current.getParent()) { + Path migrations = + current + .resolve("services") + .resolve(directoryName) + .resolve("src/main/resources/db/migration"); + if (Files.isDirectory(migrations)) return "filesystem:" + migrations; + } + throw new IllegalStateException("Service migration directory is unavailable: " + service); + } + + private static DraftCommitBinding binding(TargetProof target, long assetId, String fileName) + throws Exception { + UUID commit = UUID.randomUUID(); + UUID region = UUID.randomUUID(); + UUID zone = UUID.randomUUID(); + UUID room = UUID.randomUUID(); + var familyCounts = new ArrayList(); + for (var family : + List.of( + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) { + familyCounts.add( + WorldFreshGraphFamilyCount.newBuilder() + .setFamily(family) + .setCount( + family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION + || family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE + || family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM + ? 1 + : 0) + .build()); + } + var declaration = + WorldFreshGraphDeclaration.newBuilder() + .setTenantId(target.canonicalTenantId().toString()) + .setVersionId(target.canonicalVersionId().toString()) + .addAllFamilyCounts(familyCounts) + .setStartLocation( + net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef.newBuilder() + .setTenantId(target.canonicalTenantId().toString()) + .setVersionId(target.canonicalVersionId().toString()) + .setRoomTemplateId(room.toString())) + .build(); + var mutations = + List.of( + mutation( + commit, room, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .setRoom( + RoomDesignMutation.newBuilder() + .setName("Genuine selected room") + .setZoneId(zone.toString()) + .setDescription("Selected export source room")) + .build(), + mutation( + commit, zone, region, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ZONE) + .setZone( + ZoneDesignMutation.newBuilder() + .setName("Genuine selected zone") + .setRegionId(region.toString())) + .build(), + mutation( + commit, + region, + region, + WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_REGION) + .setRegion( + RegionDesignMutation.newBuilder() + .setName("Genuine selected region") + .setWeather("clear") + .setShardId(1)) + .setFreshGraphDeclaration(declaration) + .build()); + + var revisions = new ArrayList(); + var units = new ArrayList(); + UUID gameplayRuleRevisionId = UUID.randomUUID(); + revisions.add( + new RevisionPayload( + "0", + gameplayRuleRevisionId, + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload( + new GameplayRuleManifest.AdmissionTag("genuine-selected-export")))); + units.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + target.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0")); + revisions.add( + new RevisionPayload( + "1", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.upsertPayload( + Long.toString(assetId), fileName, AssetSource.Requiredness.REQUIRED))); + units.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + target.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + "0")); + var templateConfig = + new TemplateConfigSource.Config( + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + target.canonicalVersionId() + + "\",\"world\":{\"regions\":[],\"rooms\":[]}," + + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[{" + + "\"family\":\"ADMISSION_TAGS\",\"key\":\"genuine-selected-export\"," + + "\"revisionId\":\"" + + gameplayRuleRevisionId + + "\"}]},\"automation\":{\"scripts\":[]," + + "\"scriptPatch\":{\"presence\":\"ABSENT\"}},\"supportedSettings\":[]}"); + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.createPayload( + "Genuine selected export template", templateConfig))); + units.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.SCOPE, + target.canonicalVersionId().toString(), + TemplateConfigSource.SCOPE, + TemplateConfigSource.SCOPE_ID, + "0")); + for (var worldMutation : mutations) { + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.fromString(worldMutation.getLogicalRevisionId()), + Owner.WORLD_MANAGEMENT, + JsonFormat.printer().omittingInsignificantWhitespace().print(worldMutation))); + String family = + worldMutation.getAggregateType().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + worldMutation.getAggregateId(), + "AGGREGATE", + worldMutation.getAggregateId(), + "0")); + units.add( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + family, + worldMutation.getAggregateId(), + "REGION_SUBTREE", + worldMutation.getScopeId(), + "0")); + } + return DraftCommitBinding.create( + target, UUID.randomUUID(), commit, "base-commit-0", revisions, units); + } + + private static WorldDesignMutationRevision.Builder mutation( + UUID commit, UUID aggregate, UUID region, WorldDesignAggregateType type) { + return WorldDesignMutationRevision.newBuilder() + .setCommitId(commit.toString()) + .setLogicalRevisionId(UUID.randomUUID().toString()) + .setAggregateId(aggregate.toString()) + .setAggregateType(type) + .setOperation(WorldDesignMutationOperation.WORLD_DESIGN_MUTATION_OPERATION_UPSERT) + .setScopeType(WorldDesignScopeType.WORLD_DESIGN_SCOPE_TYPE_REGION_SUBTREE) + .setScopeId(region.toString()); + } + + private static WorldPublishedStartLocationEvidence selectedPublicationWorldEvidence( + DraftAuthorizationFenceBinding original, + WorldDraftGraphAppliedResult applied, + DraftCommitBinding selectedCommit, + AuthoredDraftPublishSelection selection, + AuthoredDraftPublishSelection.PublishIntent intent, + String publishRequestId) { + var retained = applied.startLocationReceipt().orElseThrow(); + var selectorReceipt = + WorldDraftStartLocationEvidence.create( + retained.targetNamespace(), + retained.operationId(), + retained.requestId(), + retained.commitId(), + retained.authorizationFenceId(), + retained.accountBindingDigest(), + retained.bindingDigest(), + retained.startLocation(), + retained.graphDigest()) + .canonicalBytes(); + var tuples = + selectedCommit.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + NAMESPACE, + selectedCommit.target().canonicalTenantId(), + selectedCommit.target().canonicalVersionId(), + applied.application().operation().ownerBinding().intakeRequestId(), + UUID.randomUUID(), + publishRequestId, + selection.digest().substring("sha256:".length()), + Long.parseLong(intent.expectedVersionStateEpoch()), + PublicationDigestRequestBinding.full( + selectedCommit.target().canonicalTenantId().toString(), + Long.toString(selectedCommit.target().gameDesignVersionRowId()), + publishRequestId) + .derivedWorkflowIdentity(), + selectedCommit.commitId().toString(), + retained.graphDigest(), + 3, + tuples); + return new WorldPublishedStartLocationEvidence( + request, selectorReceipt, original.canonicalBytes(), applied.canonicalBytes()); + } + + private static Server startServer(TestPki pki, String service, MutableHandlerRegistry handlers) + throws Exception { + var identity = pki.server(service); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .fallbackHandlerRegistry(handlers) + .maxInboundMessageSize(20 * 1024 * 1024) + .maxInboundMetadataSize(AccountOriginalDraftOrderGrpcCodec.MAX_METADATA_BYTES) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .build() + .start(); + } + + private static void register(MutableHandlerRegistry handlers, BindableService... services) { + for (var service : services) + handlers.addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + } + + private static String loopback(Server server) { + return "127.0.0.1:" + server.getPort(); + } + + private static void stopAll(Server... servers) throws InterruptedException { + for (var server : servers) if (server != null) server.shutdownNow(); + var terminated = true; + for (var server : servers) + if (server != null) terminated &= server.awaitTermination(5, TimeUnit.SECONDS); + if (!terminated) throw new IllegalStateException("Test owner server did not stop"); + } + + private static byte[] alteredManifest(byte[] original) { + String json = new String(original, StandardCharsets.UTF_8); + String marker = "\"selectedInventoryDigest\":\""; + int valueStart = json.indexOf(marker); + if (valueStart < 0) throw new IllegalStateException("Selected digest field is missing"); + valueStart += marker.length(); + int valueEnd = json.indexOf('"', valueStart); + if (valueEnd < 0) throw new IllegalStateException("Selected digest value is malformed"); + String previous = json.substring(valueStart, valueEnd); + String changed = previous.charAt(0) == '0' ? "1".repeat(64) : "0".repeat(64); + return (json.substring(0, valueStart) + changed + json.substring(valueEnd)) + .getBytes(StandardCharsets.UTF_8); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private record Store( + DSLContext dsl, + DataSourceTransactionManager transactions, + TargetProof target, + Version version) { + T transaction(Supplier operation) { + var transaction = new TransactionTemplate(transactions); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return transaction.execute(ignored -> operation.get()); + } + + Store withIdentity(TargetProof target, Version version) { + return new Store(dsl, transactions, target, version); + } + } + + private record TestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var result = new CommonGrpcClientProperties(); + result.setPlaintext(false); + result.setCertChain(certificate.toString()); + result.setPrivateKey(key.toString()); + result.setCaCert(ca.toString()); + return result; + } + } + + private record StartSessionProjectionBinding( + StartSessionPostAuthorizationExecutionTuple tuple, UUID ownerAttemptId, long ownerFence) {} + + /** Ephemeral same-namespace mTLS identities for the four real owner boundaries. */ + private static final class TestPki { + private final Path ca; + private final Map servers = new ConcurrentHashMap<>(); + private final Map clients = new ConcurrentHashMap<>(); + + TestPki(Path root) throws Exception { + Files.createDirectories(root); + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var caKeys = generator.generateKeyPair(); + var caName = new org.bouncycastle.asn1.x500.X500Name("CN=Test-only selected export proof CA"); + var now = java.time.Instant.now(); + var caBuilder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caName, + java.math.BigInteger.ONE, + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + caName, + caKeys.getPublic()); + caBuilder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(true)); + caBuilder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage(org.bouncycastle.asn1.x509.KeyUsage.keyCertSign)); + var caCertificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + caBuilder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + ca = pem(root.resolve("ca.pem"), caCertificate); + for (String service : + List.of( + "account-service", + "game-design-service", + "world-management-service", + "game-logic-service")) { + servers.put(service, issue(root, service, true, caKeys, caCertificate)); + clients.put(service, issue(root, service, false, caKeys, caCertificate)); + } + } + + Path ca() { + return ca; + } + + TestIdentity server(String service) { + return Objects.requireNonNull(servers.get(service), "unknown test server identity"); + } + + CommonGrpcClientProperties client(String service) { + return Objects.requireNonNull(clients.get(service), "unknown test client identity") + .properties(ca); + } + + private static TestIdentity issue( + Path root, + String service, + boolean server, + java.security.KeyPair caKeys, + java.security.cert.X509Certificate caCertificate) + throws Exception { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + var keys = generator.generateKeyPair(); + var now = java.time.Instant.now(); + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + caCertificate, + new java.math.BigInteger(120, new java.security.SecureRandom()), + java.util.Date.from(now.minusSeconds(60)), + java.util.Date.from(now.plusSeconds(3600)), + new org.bouncycastle.asn1.x500.X500Name("CN=" + service), + keys.getPublic()); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(false)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + false, + new org.bouncycastle.asn1.x509.KeyUsage( + org.bouncycastle.asn1.x509.KeyUsage.digitalSignature + | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.extendedKeyUsage, + false, + new org.bouncycastle.asn1.x509.ExtendedKeyUsage( + server + ? org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_serverAuth + : org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_clientAuth)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, + false, + new org.bouncycastle.asn1.x509.GeneralNames( + new org.bouncycastle.asn1.x509.GeneralName[] { + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.uniformResourceIdentifier, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.dNSName, "localhost"), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.iPAddress, "127.0.0.1") + })); + var certificate = + new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .getCertificate( + builder.build( + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .build(caKeys.getPrivate()))); + String prefix = service + (server ? "-server" : "-client"); + return new TestIdentity( + pem(root.resolve(prefix + ".crt"), certificate), + pem(root.resolve(prefix + ".key"), keys.getPrivate())); + } + + private static Path pem(Path path, Object value) throws Exception { + try (var writer = + new org.bouncycastle.openssl.jcajce.JcaPEMWriter(Files.newBufferedWriter(path))) { + writer.writeObject(value); + } + return path; + } + } + + /** + * Object IO only; every put still observes the committed candidate through the real GD reader. + */ + private static final class InMemoryConditionalObjectStore { + private final VersionAssetExportCandidateService candidates; + private final PublicationDigestRequestBinding request; + private final Map stored = new ConcurrentHashMap<>(); + private final AtomicInteger puts = new AtomicInteger(); + private final AtomicInteger gets = new AtomicInteger(); + private final S3Client client = mock(S3Client.class); + private byte[] inventoryBytes; + + InMemoryConditionalObjectStore( + VersionAssetExportCandidateService candidates, PublicationDigestRequestBinding request) { + this.candidates = candidates; + this.request = request; + doAnswer( + invocation -> { + PutObjectRequest put = invocation.getArgument(0); + RequestBody body = invocation.getArgument(1); + puts.incrementAndGet(); + if (!"*".equals(put.ifNoneMatch())) { + throw new AssertionError("Selected object PUT was not conditional"); + } + var retained = candidates.readSelectedCandidate(request); + if (inventoryBytes == null + || !request.requestDigest().equals(retained.requestDigest()) + || !Arrays.equals(request.canonicalPreimage(), retained.requestPreimage()) + || !Arrays.equals(inventoryBytes, retained.inventoryBytes()) + || !("sha256:" + sha256(retained.inventoryBytes())) + .equals(retained.inventoryDigest()) + || !("sha256:" + sha256(retained.manifestBytes())) + .equals(retained.manifest().manifestHash())) { + throw new AssertionError( + "Exact durable candidate, inventory and manifest were not readable before object PUT"); + } + byte[] bytes; + try (var stream = body.contentStreamProvider().newStream()) { + bytes = stream.readAllBytes(); + } + String key = put.key(); + StoredObject prior = + stored.putIfAbsent(key, new StoredObject(bytes, put.contentType())); + if (prior != null) { + throw S3Exception.builder() + .statusCode(412) + .message("conditional collision") + .build(); + } + return PutObjectResponse.builder().build(); + }) + .when(client) + .putObject(any(PutObjectRequest.class), any(RequestBody.class)); + when(client.getObjectAsBytes(any(GetObjectRequest.class))) + .thenAnswer( + invocation -> { + gets.incrementAndGet(); + GetObjectRequest get = invocation.getArgument(0); + StoredObject object = stored.get(get.key()); + if (object == null) { + throw S3Exception.builder() + .statusCode(404) + .message("missing test object") + .build(); + } + return ResponseBytes.fromByteArray( + GetObjectResponse.builder() + .contentLength((long) object.bytes().length) + .contentType(object.contentType()) + .build(), + object.bytes()); + }); + } + + void requireCandidateBeforeWrites(SelectedDraftAssetInventory inventory) { + inventoryBytes = inventory.canonicalBytes(); + if (!stored.isEmpty()) + throw new IllegalStateException("Test object store is already populated"); + } + + S3Client client() { + return client; + } + + Map objects() { + return Map.copyOf(stored); + } + + byte[] bytesAt(String key) { + return Objects.requireNonNull(stored.get(key), "missing selected test object").bytes(); + } + + String contentTypeAt(String key) { + return Objects.requireNonNull(stored.get(key), "missing selected test object").contentType(); + } + + int putCalls() { + return puts.get(); + } + + int getCalls() { + return gets.get(); + } + } + + private record StoredObject(byte[] bytes, String contentType) { + StoredObject { + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index f8e344ffa6..e801dfc348 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -22,6 +22,7 @@ import java.security.KeyStore; import java.time.Instant; import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Base64; import java.util.List; @@ -103,9 +104,11 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationCommandService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation; +import net.firedevops.firemud.gamedesign.publication.StartSessionLaunchDescriptorProducer; import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; import net.firedevops.firemud.gamedesign.publication.TemplateReferenceRepository; @@ -525,6 +528,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth candidate.getCanonicalTenantId().toString(), Long.toString(candidate.getId()), publishRequestId); + var selectedExport = selectedExport(expectedDigestBinding); Mockito.when( publishGateService.collectFullVersionParticipantDigests( @@ -538,6 +542,10 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), Mockito.eq(publishWorkflowId))) .thenReturn(participantDigests); + Mockito.when( + assetExportService.exportSelectedAssets( + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)))) + .thenReturn(selectedExport); Mockito.when(assetExportService.exportAssets(tenantId, 1)).thenReturn(immutableEmptyManifest()); VersionDto publishedVersion = @@ -712,6 +720,7 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele candidate.getCanonicalTenantId().toString(), Long.toString(candidate.getId()), publishRequestId); + var selectedExport = selectedExport(expectedDigestBinding); Mockito.when( publishGateService.collectFullVersionParticipantDigests( Mockito.any(VersionDto.class), @@ -724,20 +733,6 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), Mockito.eq(workflowId))) .thenReturn(participantDigests); - var selectedManifest = immutableEmptyManifest(); - var selectedCandidate = - new VersionAssetExportCandidateService.CandidateBinding( - expectedDigestBinding.requestDigest(), - "sha256:" + "b".repeat(64), - "sha256:" + "c".repeat(64), - net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory.SCHEMA, - "sha256:" + "d".repeat(64), - selectedManifest, - expectedDigestBinding.canonicalPreimage(), - "stipulated selected inventory".getBytes(StandardCharsets.UTF_8), - "stipulated empty manifest".getBytes(StandardCharsets.UTF_8)); - var selectedExport = - new AssetExportService.SelectedExportResult(selectedManifest, selectedCandidate); Mockito.when( assetExportService.exportSelectedAssets( Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)))) @@ -1067,6 +1062,78 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) Mockito.eq(gameSessionAttemptId), Mockito.eq(gameSessionFence)); + // This legacy selected-publication fixture has a real GD/World association and release, + // but intentionally no retained Game Logic source receipt. The producer must not turn + // its synthetic aggregate participant digest into that missing owner evidence. + var operationSelection = operation.account().input().selection(); + var gameLogicPublicationRequest = + PublicationDigestRequestBinding.full( + operationSelection.intent().canonicalTenantId().toString(), + Long.toString(operationSelection.target().gameDesignVersionRowId()), + operationSelection.intent().publishRequestId()); + assertThat( + new SelectedDraftGameLogicReceiptRepository(dsl) + .readForPublication(gameLogicPublicationRequest)) + .isEmpty(); + var descriptorProducer = + new StartSessionLaunchDescriptorProducer( + dsl, + transactionManager, + NAMESPACE, + associationReadService, + publishedReleaseBundleService, + START_SESSION_JSON); + long descriptorRowsBeforeRead = + dsl.fetchSingle( + "SELECT COUNT(*) FROM launch_descriptor WHERE canonical_tenant_id = ? AND control_plane_request_id = ?", + target.canonicalTenantId(), + startSessionTuple.controlPlaneRequestId()) + .get(0, Long.class); + long descriptorBindingRowsBeforeRead = + dsl.fetchSingle( + "SELECT COUNT(*) FROM game_design_start_session_launch_descriptor_binding WHERE canonical_tenant_id = ? AND control_plane_request_id = ?", + target.canonicalTenantId(), + startSessionTuple.controlPlaneRequestId()) + .get(0, Long.class); + assertThatThrownBy( + () -> withGameSessionPeer(() -> descriptorProducer.resolve(exactReplayRequest))) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + var descriptorRetryRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + startSessionTuple.canonicalBytes(), + gameSessionAttemptId, + gameSessionFence, + exactReplayRequest.selection()); + assertThatThrownBy( + () -> withGameSessionPeer(() -> descriptorProducer.resolve(descriptorRetryRequest))) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat( + dsl.fetchSingle( + "SELECT COUNT(*) FROM launch_descriptor WHERE canonical_tenant_id = ? AND control_plane_request_id = ?", + target.canonicalTenantId(), + startSessionTuple.controlPlaneRequestId()) + .get(0, Long.class)) + .isEqualTo(descriptorRowsBeforeRead); + assertThat( + dsl.fetchSingle( + "SELECT COUNT(*) FROM game_design_start_session_launch_descriptor_binding WHERE canonical_tenant_id = ? AND control_plane_request_id = ?", + target.canonicalTenantId(), + startSessionTuple.controlPlaneRequestId()) + .get(0, Long.class)) + .isEqualTo(descriptorBindingRowsBeforeRead); + Mockito.verify(accountProjectionClient, Mockito.times(5)) + .read( + Mockito.any(StartSessionPostAuthorizationExecutionTuple.class), + Mockito.eq(gameSessionAttemptId), + Mockito.eq(gameSessionFence)); + assertTerminalOwnerReadOverMtls(operation, Outcome.PUBLISHED, pki); byte[] terminalBeforeChangedRetry = retainedOperation.terminalEvidenceBytes(); long attemptIdBeforeRetry = attempt.getId(); @@ -1479,6 +1546,10 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), Mockito.eq(publishWorkflowId))) .thenReturn(participantDigests); + Mockito.when( + assetExportService.exportSelectedAssets( + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)))) + .thenReturn(selectedExport(expectedDigestBinding)); Mockito.doAnswer( invocation -> { try { @@ -2697,8 +2768,9 @@ private static byte[] startSessionAuthorityBundle( StartSessionPreAuthorizationReservationTuple tuple) { String tenant = tuple.action().scope().tenantId().toString(); String actor = tuple.actor().accountId().toString(); - String now = Instant.now().toString(); - String expires = Instant.now().plusSeconds(300).toString(); + Instant issuedAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); + String now = issuedAt.toString(); + String expires = issuedAt.plusSeconds(300).toString(); Map value = Map.of( "bundleVersion", @@ -2890,4 +2962,21 @@ private T inOwnerTransaction(java.util.function.Supplier action) { private static ExportedAssetManifest immutableEmptyManifest() { return new ExportedAssetManifest("sha256:" + "a".repeat(64), 1, List.of(), List.of()); } + + private static AssetExportService.SelectedExportResult selectedExport( + PublicationDigestRequestBinding request) { + var manifest = immutableEmptyManifest(); + var candidate = + new VersionAssetExportCandidateService.CandidateBinding( + request.requestDigest(), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64), + net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory.SCHEMA, + "sha256:" + "d".repeat(64), + manifest, + request.canonicalPreimage(), + "stipulated selected inventory".getBytes(StandardCharsets.UTF_8), + "stipulated empty manifest".getBytes(StandardCharsets.UTF_8)); + return new AssetExportService.SelectedExportResult(manifest, candidate); + } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java index ecf084229a..78b6c806ce 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java @@ -447,7 +447,10 @@ private static Fixture fixture(VersionLifecycleState state) { DSL.using(admin, SQLDialect.POSTGRES).execute("CREATE SCHEMA " + schema); DriverManagerDataSource dataSource = new DriverManagerDataSource( - POSTGRES.getJdbcUrl() + "?currentSchema=" + schema, + POSTGRES.getJdbcUrl() + + (POSTGRES.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema, POSTGRES.getUsername(), POSTGRES.getPassword()); Flyway.configure() diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcServiceTest.java new file mode 100644 index 0000000000..2f514b0fe7 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcServiceTest.java @@ -0,0 +1,380 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamedesign.publication.StartSessionLaunchDescriptorProducer; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import tools.jackson.databind.json.JsonMapper; + +/** Callback and codec tests with an injected peer context; not mTLS or persisted-owner proof. */ +class GameDesignStartSessionLaunchDescriptorGrpcServiceTest { + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "world-runtime"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final StartSessionLaunchDescriptorProducer producer = + mock(StartSessionLaunchDescriptorProducer.class); + private final GameDesignStartSessionLaunchDescriptorGrpcService service = + new GameDesignStartSessionLaunchDescriptorGrpcService(producer, NAMESPACE); + + @Test + void authenticatesExactPeerBeforeDecodingOrCallingTheProducer() { + var observer = new Collector(); + service.resolveStartSessionLaunchDescriptor( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), observer); + assertThat(observer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(producer); + } + + @Test + void rejectsWrongWorkloadBeforeDecodingOrCallingTheProducer() { + var observer = + invokeAs( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), "account-service"); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + verifyNoInteractions(producer); + } + + @Test + void rejectsWrongNamespacePeerBeforeDecodingOrCallingTheProducer() { + var observer = + invokeAsNamespace( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), + "another-runtime", + "game-session-service"); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(producer); + } + + @Test + void rejectsMalformedAndInitialRequestsBeforeCallingTheProducer() { + var malformed = + invokeAs( + ReadStartSessionTemplateAssociationRequest.getDefaultInstance(), + "game-session-service"); + assertThat(malformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + + var initial = invokeAs(request(new InitialConfigured()), "game-session-service"); + assertThat(initial.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(producer); + } + + @Test + void rejectsDifferentTargetNamespaceBeforeCallingTheProducer() { + var otherNamespace = + request( + "other-runtime", + new ExactReplay( + uuid("03333333-3333-4333-8333-333333333333"), + uuid("04444444-4444-4444-8444-444444444444"), + "selected-workflow", + digest('a'))); + var observer = invokeAs(otherNamespace, "game-session-service"); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(producer); + } + + @Test + void typedStoredDenialUsesItsExactAssociationBindingAndMessage() { + // This mocked callback exercises status-to-response mapping only; it does not prove storage. + var request = + request( + new ExactReplay( + uuid("03333333-3333-4333-8333-333333333333"), + uuid("04444444-4444-4444-8444-444444444444"), + "selected-workflow", + digest('a'))); + var decoded = + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .fromRequest(request); + var association = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + var denial = mock(StartSessionLaunchDescriptorProducer.StoredBusinessDenial.class); + when(denial.associationRead()).thenReturn(association); + when(denial.failureCode()).thenReturn("INVALID_TEMPLATE_CONFIGURATION"); + when(denial.getMessage()) + .thenReturn("INVALID_TEMPLATE_CONFIGURATION: captured source is unsupported"); + when(producer.resolve(decoded)).thenThrow(denial); + var response = + ResolveStartSessionLaunchDescriptorResponse.newBuilder() + .setSchemaVersion(StartSessionLaunchDescriptorGrpcCodec.RESPONSE_SCHEMA_VERSION) + .build(); + + try (MockedStatic codec = + Mockito.mockStatic(StartSessionLaunchDescriptorGrpcCodec.class)) { + codec + .when(() -> StartSessionLaunchDescriptorGrpcCodec.fromRequest(request)) + .thenReturn(decoded); + codec + .when( + () -> + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + decoded, + association, + "INVALID_TEMPLATE_CONFIGURATION", + "INVALID_TEMPLATE_CONFIGURATION: captured source is unsupported")) + .thenReturn(response); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isNull(); + assertThat(observer.value).isEqualTo(response); + assertThat(observer.completed).isTrue(); + verify(producer).resolve(decoded); + codec.verify( + () -> + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + decoded, + association, + "INVALID_TEMPLATE_CONFIGURATION", + "INVALID_TEMPLATE_CONFIGURATION: captured source is unsupported")); + } + } + + @Test + void ordinaryFailedPreconditionOwnerFailureRemainsANonOkRpcError() { + var request = + request( + new ExactReplay( + uuid("03333333-3333-4333-8333-333333333333"), + uuid("04444444-4444-4444-8444-444444444444"), + "selected-workflow", + digest('a'))); + var decoded = + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .fromRequest(request); + when(producer.resolve(decoded)) + .thenThrow( + Status.FAILED_PRECONDITION + .withDescription("owner evidence changed") + .asRuntimeException()); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verify(producer).resolve(decoded); + } + + @Test + void ordinaryUnavailableOwnerFailureRemainsANonOkRpcError() { + var request = + request( + new ExactReplay( + uuid("03333333-3333-4333-8333-333333333333"), + uuid("04444444-4444-4444-8444-444444444444"), + "selected-workflow", + digest('a'))); + var decoded = + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .fromRequest(request); + when(producer.resolve(decoded)) + .thenThrow(Status.UNAVAILABLE.withDescription("owner unavailable").asRuntimeException()); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verify(producer).resolve(decoded); + } + + private Collector invokeAs(ReadStartSessionTemplateAssociationRequest request, String workload) { + return invokeAsNamespace(request, NAMESPACE, workload); + } + + private Collector invokeAsNamespace( + ReadStartSessionTemplateAssociationRequest request, String namespace, String workload) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + workload, namespace, workload); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + var observer = new Collector(); + service.resolveStartSessionLaunchDescriptor(request, observer); + return observer; + } finally { + context.detach(previous); + } + } + + private static ReadStartSessionTemplateAssociationRequest request( + StartSessionTemplateAssociationReadEvidence.Selection selection) { + return request(NAMESPACE, selection); + } + + private static ReadStartSessionTemplateAssociationRequest request( + String namespace, StartSessionTemplateAssociationReadEvidence.Selection selection) { + var request = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + namespace, + uuid("01111111-1111-4111-8111-111111111111"), + postTuple(namespace).canonicalBytes(), + ATTEMPT, + 8L, + selection); + return net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .toRequest(request); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple(String namespace) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "start-session-launch-descriptor-test", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact StartSession descriptor selection")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + RESERVATION_OWNER, + 19L, + authorityBundle(pre, namespace), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, String namespace) { + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", TENANT.toString(), "targetNamespace", namespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", TENANT.toString()), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(TENANT.toString(), 3L), + "membershipAuthorityGeneration", Map.of(TENANT.toString(), 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(TENANT.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Collector + implements StreamObserver { + private ResolveStartSessionLaunchDescriptorResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ResolveStartSessionLaunchDescriptorResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java new file mode 100644 index 0000000000..130fd3e083 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java @@ -0,0 +1,235 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionLaunchDescriptorProducerTest { + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final UUID VERSION = uuid("03333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = uuid("04444444-4444-4444-8444-444444444444"); + private static final String NAMESPACE = "world-runtime"; + private static final long FENCE = 8L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void requiresExactReplayAndSameNamespacePeerBeforeOwnerWork() { + var associationReader = mock(StartSessionTemplateAssociationReadService.class); + var transactions = mock(PlatformTransactionManager.class); + var producer = + new StartSessionLaunchDescriptorProducer( + mock(DSLContext.class), + transactions, + NAMESPACE, + associationReader, + mock(PublishedReleaseBundleService.class), + JSON); + var initial = request(new InitialConfigured()); + + assertThatThrownBy(() -> withPeer(() -> producer.resolve(initial), "game-session-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(associationReader, transactions); + + assertThatThrownBy(() -> withPeer(() -> producer.resolve(null), "game-session-service")) + .isInstanceOf(NullPointerException.class); + verifyNoInteractions(associationReader, transactions); + + assertThatThrownBy( + () -> + withPeer( + () -> + producer.resolve( + request( + new ExactReplay( + VERSION, COMMIT, "selected-workflow", digest('a')))), + "account-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(associationReader, transactions); + } + + @Test + void delegatesExactReplayToAssociationReaderBeforeOpeningLocalWriteTransaction() { + // This is an explicit upstream boundary double, not Account/mTLS or owner-storage proof. + var associationReader = mock(StartSessionTemplateAssociationReadService.class); + var transactions = mock(PlatformTransactionManager.class); + var producer = + new StartSessionLaunchDescriptorProducer( + mock(DSLContext.class), + transactions, + NAMESPACE, + associationReader, + mock(PublishedReleaseBundleService.class), + JSON); + var request = request(new ExactReplay(VERSION, COMMIT, "selected-workflow", digest('a'))); + when(associationReader.read(request)) + .thenThrow( + Status.UNAVAILABLE + .withDescription("test seam: independent Account projection unavailable") + .asRuntimeException()); + + assertThatThrownBy(() -> withPeer(() -> producer.resolve(request), "game-session-service")) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + verifyNoInteractions(transactions); + } + + private static void withPeer(Runnable action, String workload) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + workload, NAMESPACE, workload); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } + + private static StartSessionTemplateAssociationReadEvidence.Request request( + StartSessionTemplateAssociationReadEvidence.Selection selection) { + return new StartSessionTemplateAssociationReadEvidence.Request( + 1, + NAMESPACE, + uuid("01111111-1111-4111-8111-111111111111"), + postTuple("launch-descriptor-test").canonicalBytes(), + ATTEMPT, + FENCE, + selection); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple(String requestId) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact StartSession descriptor selection")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} From 9f287e05e06b87adc3db79984b2e047e5d5b819f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 02:44:46 +1300 Subject: [PATCH 053/129] Compose genuine selected publication digests and repair exact CI fixtures --- .../game-design-service/version-control.md | 1 + ...ame-authoring-publishing-and-activation.md | 8 +- .../gamedesign/client/GameLogicClient.java | 4 +- ...licationExportPostgresIntegrationTest.java | 213 ++++++++++++++++-- ...emptServiceTransactionIntegrationTest.java | 26 ++- .../publication/GameLogicClientTest.java | 62 ++++- 6 files changed, 275 insertions(+), 39 deletions(-) diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index f45a866a63..b652a34be9 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -182,6 +182,7 @@ For a new immutable selected-Draft full publication, the Game Design control-pla - For one publish attempt, every required participant must attest the same target commit scope. Publish must fail closed if required participants report different `appliedCommitId` values for the same requested publish target, even if no individual digest payload is malformed. - The Automation full-version participant must select only the script definitions and event bindings mapped to the requested `(tenantId, versionId)`. Including `versionId` only as a field in a digest over tenant-wide rows is not version-scoped attestation. If the live data model cannot map the requested version to an exact script/binding set, the participant must fail closed rather than return a tenant-wide digest. Proof must show two versions with disjoint script/binding inputs produce isolated digests and that a cross-version row cannot satisfy either publish gate. - The dedicated `abilitySchemaDigest` is compared exactly with the Game Logic-owned digest for the same target commit and its existing participant `digestSchemaVersion`/canonicalization contract; missing, unsupported, stale, or mismatched evidence fails closed. +- Immutable release participant `contentDigest` values use lowercase 64-character hexadecimal SHA-256. The selected Game Logic read carries its aggregate manifest hash with the owner protocol's `sha256:` prefix; only after authenticating and exact-checking the complete response and retained terminal does Game Design remove that encoding prefix for the release participant. The hashed bytes and original owner evidence are unchanged. The dedicated `abilitySchemaDigest` retains its `sha256:` encoding and must not be substituted with the aggregate hash. - Digest request/response payloads are canonical across participants: - `GetDraftDesignDigestRequest { tenantId, scope: oneof {versionId, scriptPatchVersion}, baseVersionId (required when scriptPatchVersion is selected), publishRequestId, derivedWorkflowIdentity, requestDigest }`; the binding fields may instead be carried in authenticated owner metadata only when the receiver validates them as part of the same typed request contract. - `GetDraftDesignDigestResponse { tenantId, scope, baseVersionId (when scriptPatchVersion is selected), appliedCommitId, contentDigest, digestSchemaVersion }` 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 743daae33d..c492887886 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 @@ -6,9 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The bounded GD+World source/APPLIED/original terminal-settlement path has executed PostgreSQL proof, including lost acknowledgement and unknown-outcome recovery, as recorded below. The later construction adds fresh creation-receipt-backed normalized template phase, immutable selected export candidates with actual-byte object readback, the closed Account-gated Game Session association read and exact descriptor projection. Corrected gate R278 passes Common/Game Design full checks, canonical formatting, Checkstyle, SpotBugs, coverage, the Game Design boot JAR and documentation checks. Its reports contain 966 passing units (Common 446, Game Design 520); all 143 Game Design integration cases compile and skip locally without Docker, including the new genuine-source-to-selected-export/descriptor definition. V66 passes schema generation, not physical migration proof. No physical execution credit follows for the new descriptor/export composition from these local runs. +The bounded GD+World source/APPLIED/original terminal-settlement path has executed PostgreSQL proof, including lost acknowledgement and unknown-outcome recovery, as recorded below. The later construction adds fresh creation-receipt-backed normalized template phase, immutable selected export candidates with actual-byte object readback, the closed Account-gated Game Session association read and exact descriptor projection. Corrected gates R281 and R283 pass Game Design full checks, canonical formatting, Checkstyle, SpotBugs, coverage, the boot JAR and documentation checks: the unit reports contain 522 passes, while all 143 integration cases compile and skip locally without Docker; unchanged outputs are reused. R282's missing integration-fixture imports were corrected before the successful R283 gate. The earlier composed R278 gate also passed Common's 446 units. These local runs do not establish physical descriptor/export composition. V66 passes schema generation and the originating physical candidate-suite migration proof below, not successful descriptor creation/readback. -The selection binding preserves `publicationDigestRequest/v1`; exact retained Game Logic terminal/receipt evidence supplies aggregate and dedicated ability-schema evidence without a tenant/version-only fallback. The next construction composes genuine GD+World source settlement and Account/Game Logic receipt retention with the real selected inventory, candidate/export and Game Design-local publication finalizer, followed by exact association-derived descriptor storage and replay. Its PostgreSQL definition still stipulates selected-publication Account/freeze/inventory admission and participant collection; S3 transport and the StartSession Account projection are explicit test doubles. It is not complete four-owner publication or authenticated positive runtime launch proof. V66 retains the original operation tuple, attempt/fence, exact association, selected Game Logic receipt and release alongside the descriptor. The separate protected exact-replay adapter remains unregistered, as does the earlier association reader. Complete release/settlement, authenticated descriptor/consumer and World held-authority handoffs, and runtime activation remain open. Account's separate confirmation-WAL denial is an admission proof gap, not grounds to weaken source or release guards. +The selection binding preserves `publicationDigestRequest/v1`; exact retained Game Logic terminal/receipt evidence supplies aggregate and dedicated ability-schema evidence without a tenant/version-only fallback. The next construction composes genuine GD+World source settlement and Account/Game Logic receipt retention with the real selected inventory, candidate/export and Game Design-local publication finalizer, followed by exact association-derived descriptor storage and replay. Its PostgreSQL definition now uses the actual mutual-TLS Game Logic selected-source read and Game Design's selected control-plane digest, retained unchanged in release readback; the narrow client conversion preserves the original wire hash and emits the release's bare-hex aggregate representation. Selected-publication Account/freeze/inventory admission and Entity/Automation participants remain stipulated; the World participant reads retained fixture freeze evidence, and S3 transport and the StartSession Account projection are explicit test doubles. It is not complete four-owner publication or authenticated positive runtime launch proof. V66 retains the original operation tuple, attempt/fence, exact association, selected Game Logic receipt and release alongside the descriptor. The separate protected exact-replay adapter remains unregistered, as does the earlier association reader. Complete release/settlement, authenticated descriptor/consumer and World held-authority handoffs, and runtime activation remain open. Account's separate confirmation-WAL denial is an admission proof gap, not grounds to weaken source or release guards. + +Published `0eacc39ff5602a64d8e170421b392123a2dda2c9` [Validation run 37935183958](https://github.com/benhook1013/FireMUD/actions/runs/37935183958) completed red with originating Game Design integration XML for 146 cases, two failures and zero skips. All three genuine GD+World source/settlement cases and the genuine Game Logic intake/settlement case passed, as did the six selected export candidates, four reference-phase cases, six selected Game Logic receipt cases and 23 asset-publication cases. V66 applied successfully in the isolated candidate schemas. The new genuine export/descriptor fixture failed before source mutation because it read the prepared Account creator before preparing the original order; that ordering is corrected without changing Account issuance. The other failure attached remap creation to the obsolete legacy export callback instead of the selected-export call; the correction preserves the strict request binding and retention assertions. World passed all 207 PostgreSQL cases with zero skips. Account executed 254 cases with one conservative confirmation-WAL coverage failure and zero skips; its separate 31-case Draft-fence artifact duplicates the passing suite already included in that total. The two PostgreSQL 16/pinned-18 module probes passed, establishing restricted module capability only, not original-COMMIT durability or failover proof. Common jobs and Dev Tool Contract Checks passed. The actual synthetic checkout is `b802c02ac99a3217202bbe9297a21f83dd523e8f`, tree `c84e0e3c5ce4fb03b683b30fd3f7cc58d179bfe7`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head, not the recorded integration parent. These results do not establish successful corrected-head export/descriptor execution or intended-parent alignment. Published `c9bf6778fe21c39045af5e6bacde850272cc2d78` [Validation run 37928625721](https://github.com/benhook1013/FireMUD/actions/runs/37928625721) executed Game Design's 510 units and 145 PostgreSQL cases, with nine PostgreSQL fixture failures and zero skips. All four template-phase cases, the selected template/source association case and all three genuine GD+World source/APPLIED/original-settlement cases passed. World executed 207 PostgreSQL cases successfully with zero skips, including its corrected workflow fixture. Account's 1,109 units passed; its 254 PostgreSQL cases executed with one separate confirmation-WAL coverage denial and zero skips, and its dedicated 31 Draft-fence cases passed. The bounded Game Design corrections fix an isolated-schema JDBC delimiter, missing request-bound export fixture candidates and noncanonical timestamp precision without weakening guards. Corrected-head PostgreSQL execution remains required. The confirmed synthetic checkout is `061ae1ba1d4594166dee426fe2c0c7ca6ea5b3f0`; retained artifacts do not establish its tree or ordered parents, so this is not intended-parent alignment proof. @@ -26,7 +28,7 @@ The selected-release inventory contract is explicit in the [World owner](../../a Game Design's published synchronized source repository covers commands, realm policy, ordinary `ASSET_REFERENCE` and closed `GAMEPLAY_RULE` history, with actual fresh-Version genesis, coordinator application, immutable selected-commit snapshots and exact readback. The unregistered original-order producer connects Account's current creator transaction to the Game Design-only coordinator, source-aware fence and terminal readback; public creator ingress, deployed environment authority and physical composed proof remain pending. Generic `SaveRevision` cannot substitute for that producer, and retained generic rule rows remain denied rather than guessed into complete inventory. -The current source-completeness construction adds the separate branding writer, required asset-byte qualification, original history and selected snapshots/captures under V59. The V60 template-config writer uses actual generated template rows with original operation/revision provenance, normalized authored references and immutable readback, not legacy row-ID or tenant-key inference. Its closed input contract remains owned by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state). Nonempty World, Entity and Automation references stay denied until their genuine selected-base owner reads exist. Game Design-authored gameplay references are separate from Game Logic's derived receipt; the exact immutable publication join remains unimplemented. Newly qualified templates remain non-launchable, not proof of tenant reference cutover. Retained original terminals preserve their known bytes; absent new-family genesis remains unknown and cannot supply an empty family or fresh complete publication capture. An explicit-target legacy template cannot be silently omitted from new completeness evidence: deferred row guards require genuine CREATE qualification, and new snapshot/freeze inventory checks deny unresolved rows while preserving qualified DELETE tombstones. +The current source-completeness construction adds the separate branding writer, required asset-byte qualification, original history and selected snapshots/captures under V59. The V60 template-config writer uses actual generated template rows with original operation/revision provenance, normalized authored references and immutable readback, not legacy row-ID or tenant-key inference. Its closed input contract remains owned by [Game Templates](../../architecture/microservices/game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state). Nonempty World, Entity and Automation references stay denied until their genuine selected-base owner reads exist. Game Design-authored gameplay references are separate from Game Logic's derived receipt; the exact immutable publication join now has bounded receipt, inventory, read and descriptor components, with the composed proof limits recorded above. Normalization alone is not launch eligibility or proof of tenant reference cutover. Retained original terminals preserve their known bytes; absent new-family genesis remains unknown and cannot supply an empty family or fresh complete publication capture. An explicit-target legacy template cannot be silently omitted from new completeness evidence: deferred row guards require genuine CREATE qualification, and new snapshot/freeze inventory checks deny unresolved rows while preserving qualified DELETE tombstones. The composed V59/V60 local gate R183 passed Game Design schema generation, full service checks, boot JAR, formatting, Checkstyle, SpotBugs, coverage, links and Markdown: 416 unit cases executed with no failures, errors or skips. All 120 PostgreSQL definitions compiled but skipped without Docker, including three branding and six template-config cases. Two preceding runs failed only on new fixture compilation: package-private coordinator proof access and a checked fixture exception; production visibility was not widened. A separate legacy descriptor-retry fixture now models retained historical default drift without inventing new source qualification, preserving its original replay assertions. These results are not physical migration, source/freeze, authenticated producer-to-release or activation proof. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java index 974c646ce7..040bb66cc3 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/client/GameLogicClient.java @@ -123,12 +123,14 @@ public PublishParticipantDigestDto getDraftDesignDigestForVersion( "owner terminal differs from the immutable Account-finalized receipt"); } + // The authenticated owner response remains sha256:-prefixed. Release participants carry the + // same aggregate hash as bare hex; keep the separately scoped ability digest unchanged. return new PublishParticipantDigestDto( "GAME_LOGIC", versionId, null, receipt.authorization().source().binding().commitId().toString(), - evidence.manifestDigest(), + evidence.manifestDigest().substring("sha256:".length()), evidence.digestSchemaVersion(), evidence.abilitySchemaDigest(), null, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 07b5f33260..70b23bac49 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -19,6 +19,7 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.stub.StreamObserver; import io.grpc.util.MutableHandlerRegistry; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; @@ -37,6 +38,7 @@ import java.util.Objects; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; @@ -68,12 +70,15 @@ import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeTerminalReadClient; +import net.firedevops.firemud.common.gamelogic.GameLogicPublicationSourceReadBinding; +import net.firedevops.firemud.common.gamelogic.GameplayAbilitySchemaProjection; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadClient; import net.firedevops.firemud.common.gamelogic.GrpcAccountGameLogicIntakeSettlementReadClient; import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeAuthorizationClient; import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeRetainClient; import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeSourceReadClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -85,11 +90,13 @@ import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.PublicationReadGuard; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.client.GameLogicClient; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; @@ -97,6 +104,7 @@ import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcomeRepository; import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalReadGrpcService; import net.firedevops.firemud.gamedesign.draft.GameDesignWorldSourceCommitService; +import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.entity.Version; @@ -111,9 +119,11 @@ import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventoryReadService; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftControlPlaneDigest; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicIntakeCommandService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptService; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation.SourceRead; import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociationRepository; @@ -152,11 +162,14 @@ import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.gamelogic.service.GameLogicDraftDesignDigestService; +import net.firedevops.firemud.gamelogic.service.impl.GameLogicGrpcService; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeGrpcService; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeRepository; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeService; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadGrpcService; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadService; +import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; import net.firedevops.firemud.test.TestContainerImages; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; @@ -191,6 +204,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; @@ -211,9 +225,10 @@ /** * Real original GD+World source settlement and Account/GL intake-to-GD-receipt, followed by actual * selected inventory/export, the owner-local publication finalizer, and descriptor SQL storage. - * Selected-publication Account/freeze/inventory admission and release participant collection are - * stipulated; in-memory S3 and StartSession Account projection are test doubles. This is not a - * four-owner authenticated release, runtime launch, activation, or registration proof. + * Selected-publication Account/freeze/inventory admission and Entity/Automation participant digests + * are stipulated; the World participant uses only retained fixture freeze evidence. In-memory S3 + * and StartSession Account projection are test doubles. This is not a four-owner authenticated + * release, runtime launch, activation, or registration proof. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -320,10 +335,6 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var worldIntakes = new WorldAuthoredSourceIntakeRepository(world.dsl()); var worldIdentities = new WorldAuthoredVersionIdentityRepository(world.dsl()); - var accountRepository = - new AccountGameLogicIntakeAuthorizationRepository( - account.preparedOriginalCreator().sources().dsl); - var accountAccess = account.preparedOriginalCreator(); try (var sourceClient = new AuthoredWorldSourceClient( @@ -436,6 +447,9 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var selectedCommit = binding(gd.target(), sourceAsset.getId(), sourceAsset.getFileName()); var originalOrder = account.prepareOriginalDraftOrder(selectedCommit, NAMESPACE); var original = originalOrder.original(); + var accountAccess = account.preparedOriginalCreator(); + var accountRepository = + new AccountGameLogicIntakeAuthorizationRepository(accountAccess.sources().dsl); register( accountHandlers, @@ -479,6 +493,19 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex NAMESPACE)); var glRepository = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); + var glPublicationSourceReader = + new GameLogicPublicationSourceReadService(glRepository, NAMESPACE); + var glPublicationReadBindings = + new CopyOnWriteArrayList(); + var glPublicationReadResults = + new CopyOnWriteArrayList(); + GameLogicDraftDesignDigestService observingGlPublicationReader = + binding -> { + glPublicationReadBindings.add(binding); + var result = glPublicationSourceReader.read(binding); + glPublicationReadResults.add(result); + return result; + }; var accountAuthorizationOwner = new AccountGameLogicIntakeAuthorizationService( accountAccess.actors(), @@ -519,7 +546,18 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new GameLogicGameplayRuleIntakeGrpcService(glOwner, NAMESPACE), new GameLogicGameplayRuleIntakeTerminalReadGrpcService( new GameLogicGameplayRuleIntakeTerminalReadService(glRepository, NAMESPACE), - NAMESPACE)); + NAMESPACE), + new GameLogicGrpcService( + null, + null, + null, + null, + null, + null, + observingGlPublicationReader, + null, + new SimpleMeterRegistry(), + new PublicationReadGuard(NAMESPACE))); accountOriginalOrderClient.init(); accountHeldOrderClient.init(); @@ -685,6 +723,34 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex gd.target().canonicalTenantId().toString(), Long.toString(gd.target().gameDesignVersionRowId()), publishRequestId); + var selectedPublicationDigests = + new SelectedDraftPublicationDigestReadService(gd.dsl(), gd.transactions(), NAMESPACE) + .read(NAMESPACE, publicationRequest); + assertThat(selectedPublicationDigests.requestBinding().canonicalPreimage()) + .containsExactly(publicationRequest.canonicalPreimage()); + assertThat(selectedPublicationDigests.requestDigest()) + .isEqualTo(publicationRequest.requestDigest()); + DesignControlPlaneDigestDto actualDesignDigest = + selectedPublicationDigests.gameDesignDigest(); + assertThat(actualDesignDigest.tenantId()) + .isEqualTo(gd.target().canonicalTenantId().toString()); + assertThat(actualDesignDigest.scopeValue()).isEqualTo(publicationRequest.versionId()); + assertThat(actualDesignDigest.appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + assertThat(actualDesignDigest.digestSchemaVersion()) + .isEqualTo(SelectedDraftControlPlaneDigest.SCHEMA_VERSION); + assertThat(actualDesignDigest.contentDigest()).matches("[0-9a-f]{64}"); + var retainedWorldDigest = selectedPublicationDigests.worldManagementDigest(); + assertThat(retainedWorldDigest.participantKey()).isEqualTo("WORLD_MANAGEMENT"); + assertThat(retainedWorldDigest.succeeded()).isTrue(); + assertThat(retainedWorldDigest.baseVersionId()).isNull(); + assertThat(retainedWorldDigest.scopeValue()).isEqualTo(publicationRequest.versionId()); + assertThat(retainedWorldDigest.appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + assertThat(retainedWorldDigest.contentDigest()) + .isEqualTo(publicationOperation.world().request().contentDigest()); + assertThat(retainedWorldDigest.digestSchemaVersion()) + .isEqualTo(publicationOperation.world().request().digestSchemaVersion()); var inventoryReader = new SelectedDraftAssetInventoryReadService(gd.dsl(), gd.transactions()); SelectedDraftAssetInventory actualInventory = inventoryReader.read(publicationRequest); @@ -703,6 +769,65 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(actualInventory.gameLogicReceipt().receipt().canonicalBytes()) .containsExactly(retainedReceipt.receipt().canonicalBytes()); + var gameLogicDigestClient = + new GameLogicClient( + endpoints, + pki.client("game-design-service"), + channels, + BlockingGrpcStubCustomizer.noop()); + ReflectionTestUtils.setField(gameLogicDigestClient, "workloadNamespace", NAMESPACE); + ReflectionTestUtils.invokeMethod(gameLogicDigestClient, "init"); + PublishParticipantDigestDto actualGameLogicDigest; + try (gameLogicDigestClient) { + actualGameLogicDigest = + gameLogicDigestClient.getDraftDesignDigestForVersion( + publicationRequest, retainedReceipt); + var exactRetryDigest = + gameLogicDigestClient.getDraftDesignDigestForVersion( + publicationRequest, retainedReceipt); + assertThat(exactRetryDigest).isEqualTo(actualGameLogicDigest); + } + var expectedGlSourceReadBinding = + new GameLogicPublicationSourceReadBinding( + publicationRequest, retainedReceipt.authorization()); + assertThat(actualGameLogicDigest.succeeded()).isTrue(); + assertThat(actualGameLogicDigest.participantKey()).isEqualTo("GAME_LOGIC"); + assertThat(actualGameLogicDigest.scopeValue()).isEqualTo(publicationRequest.versionId()); + assertThat(actualGameLogicDigest.appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + assertThat(actualGameLogicDigest.contentDigest()).matches("[0-9a-f]{64}"); + assertThat("sha256:" + actualGameLogicDigest.contentDigest()) + .isEqualTo( + GameplayRuleManifest.sha256(retainedReceipt.receipt().terminal().manifestBytes())); + assertThat(actualGameLogicDigest.digestSchemaVersion()) + .isEqualTo(GameLogicPublicationSourceReadService.DIGEST_SCHEMA_VERSION); + assertThat(actualGameLogicDigest.abilitySchemaDigest()) + .isEqualTo( + GameplayAbilitySchemaProjection.digest( + retainedReceipt.authorization().source().manifest())); + assertThat(glPublicationReadBindings).hasSize(2); + for (GameLogicPublicationSourceReadBinding observed : glPublicationReadBindings) { + assertThat(observed.canonicalBytes()) + .containsExactly(expectedGlSourceReadBinding.canonicalBytes()); + assertThat(observed.authorization().canonicalBytes()) + .containsExactly(retainedReceipt.authorization().canonicalBytes()); + assertThat(observed.publicationRequest().canonicalPreimage()) + .containsExactly(publicationRequest.canonicalPreimage()); + } + assertThat(glPublicationReadResults).hasSize(2); + for (GameLogicPublicationSourceReadService.Result observed : glPublicationReadResults) { + assertThat(observed.binding().canonicalBytes()) + .containsExactly(expectedGlSourceReadBinding.canonicalBytes()); + assertThat(observed.terminalBytes()) + .containsExactly(retainedReceipt.receipt().terminal().canonicalBytes()); + assertThat(observed.selectedSourceBytes()) + .containsExactly(retainedReceipt.authorization().source().canonicalBytes()); + assertThat(observed.manifestDigest()) + .isEqualTo("sha256:" + actualGameLogicDigest.contentDigest()); + assertThat(observed.abilitySchemaDigest()) + .isEqualTo(actualGameLogicDigest.abilitySchemaDigest()); + } + var candidateService = new VersionAssetExportCandidateServiceImpl( gd.dsl(), @@ -809,8 +934,12 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex releaseService, new ObjectMapper()); var participantDigests = - stipulatedSelectorParticipantDigests( - publicationOperation.world(), selectedCommit, gd.target().gameDesignVersionRowId()); + selectedSelectorParticipantDigests( + selectedCommit, + gd.target().gameDesignVersionRowId(), + retainedWorldDigest, + actualDesignDigest, + actualGameLogicDigest); var gate = mock(PublishGateService.class); when(gate.collectSelectedFullVersionParticipantDigests(any(), any(), any())) .thenReturn(participantDigests); @@ -856,6 +985,32 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(release.attestationSchemaVersion()).isEqualTo("v2"); assertThat(release.worldPublishedStartLocationEvidence()) .isEqualTo(publicationOperation.world()); + var retainedGameLogicParticipant = + release.participantDigests().stream() + .filter(digest -> "GAME_LOGIC".equals(digest.participantKey())) + .findFirst() + .orElseThrow(); + assertThat(retainedGameLogicParticipant.contentDigest()) + .isEqualTo(actualGameLogicDigest.contentDigest()); + assertThat(retainedGameLogicParticipant.abilitySchemaDigest()) + .isEqualTo(actualGameLogicDigest.abilitySchemaDigest()); + assertThat(retainedGameLogicParticipant.appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + assertThat(retainedGameLogicParticipant.digestSchemaVersion()) + .isEqualTo(actualGameLogicDigest.digestSchemaVersion()); + var retainedDesignParticipant = + release.participantDigests().stream() + .filter(digest -> "GAME_DESIGN_CONTROL_PLANE".equals(digest.participantKey())) + .findFirst() + .orElseThrow(); + assertThat(retainedDesignParticipant.scopeValue()) + .isEqualTo(actualDesignDigest.scopeValue()); + assertThat(retainedDesignParticipant.appliedCommitId()) + .isEqualTo(actualDesignDigest.appliedCommitId()); + assertThat(retainedDesignParticipant.contentDigest()) + .isEqualTo(actualDesignDigest.contentDigest()); + assertThat(retainedDesignParticipant.digestSchemaVersion()) + .isEqualTo(actualDesignDigest.digestSchemaVersion()); assertThat(gd.dsl().fetchCount(DSL.table("published_release_bundle"))).isOne(); assertThat( gd.dsl() @@ -1004,31 +1159,43 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex } /** - * Release participant rows are structurally valid test inputs, not authenticated owner digests. - * World source application and the selected Game Logic receipt are separately retained above; - * this fixture does not claim complete participant collection or a four-owner publication. + * Entity and Automation participant rows remain stipulated test inputs. The World digest comes + * only from the retained fixture freeze; Game Design and Game Logic use their actual owner-local + * selected-source reads. This does not prove authenticated fresh World freeze admission or a + * complete four-owner publication. */ - private static List stipulatedSelectorParticipantDigests( - WorldPublishedStartLocationEvidence worldEvidence, + private static List selectedSelectorParticipantDigests( DraftCommitBinding selectedCommit, - long versionRowId) { - var world = worldEvidence.request(); + long versionRowId, + PublishParticipantDigestDto worldManagementDigest, + DesignControlPlaneDigestDto gameDesignDigest, + PublishParticipantDigestDto gameLogicDigest) { return AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() .map( participant -> { - String contentDigest = - "WORLD_MANAGEMENT".equals(participant) ? world.contentDigest() : "c".repeat(64); - String abilityDigest = - "GAME_LOGIC".equals(participant) ? "sha256:" + "d".repeat(64) : null; + if ("WORLD_MANAGEMENT".equals(participant)) return worldManagementDigest; + if ("GAME_LOGIC".equals(participant)) return gameLogicDigest; + if ("GAME_DESIGN_CONTROL_PLANE".equals(participant)) { + return new PublishParticipantDigestDto( + participant, + gameDesignDigest.scopeValue(), + null, + gameDesignDigest.appliedCommitId(), + gameDesignDigest.contentDigest(), + gameDesignDigest.digestSchemaVersion(), + null, + null, + null); + } return new PublishParticipantDigestDto( participant, Long.toString(versionRowId), null, selectedCommit.commitId().toString(), - contentDigest, + "c".repeat(64), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( participant, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - abilityDigest, + null, null, null); }) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index e801dfc348..cfef436166 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -1527,6 +1527,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( candidate.getCanonicalTenantId().toString(), Long.toString(candidate.getId()), publishRequestId); + var selectedExportResult = selectedExport(expectedDigestBinding); AtomicReference exportedVersionNumber = new AtomicReference<>(); AtomicReference remapSetId = new AtomicReference<>(); AtomicReference recordedDigestFailure = new AtomicReference<>(); @@ -1546,10 +1547,6 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)), Mockito.eq(publishWorkflowId))) .thenReturn(participantDigests); - Mockito.when( - assetExportService.exportSelectedAssets( - Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)))) - .thenReturn(selectedExport(expectedDigestBinding)); Mockito.doAnswer( invocation -> { try { @@ -1563,17 +1560,24 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( .when(recordedParticipantDigestService) .assertMatchesRecordedDigests( Mockito.eq(tenantId), Mockito.eq(PublishType.FULL_VERSION), Mockito.anyList()); - ExportedAssetManifest exportedManifest = immutableEmptyManifest(); - Mockito.when(assetExportService.exportAssets(Mockito.eq(tenantId), Mockito.anyInt())) + Mockito.when( + assetExportService.exportSelectedAssets( + Mockito.argThat(actual -> sameCanonicalPreimage(actual, expectedDigestBinding)))) .thenAnswer( invocation -> { - exportedVersionNumber.set(invocation.getArgument(1)); + var request = invocation.getArgument(0); + assertThat(sameCanonicalPreimage(request, expectedDigestBinding)).isTrue(); + Version boundVersion = + versionRepository + .findByTenantIdAndId(tenantId, selectedCandidateVersionId) + .orElseThrow(); + exportedVersionNumber.set(boundVersion.getVersionNumber()); try { VersionTemplateRemapSet approvedRemapSet = new VersionTemplateRemapSet(); approvedRemapSet.setRemapSetId("failed-candidate-approved-remap"); approvedRemapSet.setTenantId(tenantId); approvedRemapSet.setSourceVersionId(sourceVersionId); - approvedRemapSet.setTargetVersionId(candidateVersionId.get()); + approvedRemapSet.setTargetVersionId(selectedCandidateVersionId); approvedRemapSet.setStatus(TemplateRemapSetStatus.APPROVED); approvedRemapSet.setCreatedReason( "approved remap references publication candidate"); @@ -1582,7 +1586,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( templateRemapSetRepository.save(approvedRemapSet); remapSetId.set(approvedRemapSet.getRemapSetId()); exportCompleted.set(true); - return exportedManifest; + return selectedExportResult; } catch (Throwable failure) { exportCallbackFailure.set(failure); throw failure; @@ -1599,7 +1603,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( Mockito.anyLong(), Mockito.anyLong(), Mockito.eq(publishWorkflowId), - Mockito.eq(exportedManifest.manifestHash())); + Mockito.eq(selectedExportResult.manifest().manifestHash())); Throwable publishFailure = catchThrowable( @@ -1646,7 +1650,7 @@ void finalizationFailureAfterExportRetainsCandidateReferencedByApprovedRemapSet( assertThat(exportCompleted.get()).as(failureContext).isTrue(); assertThat(finalizationFailureInjected.get()).as(failureContext).isTrue(); assertThat(exportedVersionNumber.get()) - .as("asset export uses the candidate's persisted version number") + .as("selected export observes the exact bound candidate's persisted version number") .isEqualTo(candidateVersionNumber.get()); assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); assertThat(attempt.getRevision()).isGreaterThan(1L); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java index 47a8bbf735..eb7e95bca3 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java @@ -58,9 +58,14 @@ void readsExactRetainedSelectionAndReturnsBothDigestProjections(@TempDir Path tl assertThat(result.baseVersionId()).isNull(); assertThat(result.appliedCommitId()) .isEqualTo(receipt.authorization().source().binding().commitId().toString()); - assertThat(result.contentDigest()).isEqualTo(response.getContentDigest()); + assertThat(response.getContentDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(result.contentDigest()) + .isEqualTo(response.getContentDigest().substring("sha256:".length())) + .matches("[0-9a-f]{64}") + .isNotEqualTo(response.getContentDigest()); assertThat(result.digestSchemaVersion()).isEqualTo(response.getDigestSchemaVersion()); assertThat(result.abilitySchemaDigest()).isEqualTo(response.getAbilitySchemaDigest()); + assertThat(result.abilitySchemaDigest()).matches("sha256:[0-9a-f]{64}"); var request = org.mockito.ArgumentCaptor.forClass(GetDraftDesignDigestRequest.class); verify(stub).getDraftDesignDigest(request.capture()); @@ -110,6 +115,61 @@ void rejectsAValidButDifferentTerminalFromTheImmutableReceipt(@TempDir Path tlsD assertThat(result.abilitySchemaDigest()).isNull(); } + @Test + void rejectsMalformedManifestDigestFromPublicationResponse(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var publication = publicationBinding(receipt); + var sourceRead = + new GameLogicPublicationSourceReadBinding(publication, receipt.authorization()); + var validResponse = + GameLogicPublicationSourceReadGrpcCodec.toResponse( + sourceRead, receipt.receipt().terminal()); + var response = + validResponse.toBuilder() + .setContentDigest(validResponse.getContentDigest().substring("sha256:".length())) + .build(); + var clientAndStub = client(tlsDirectory); + when(clientAndStub.stub().getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenReturn(response); + + var result = clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt); + + assertThat(result.succeeded()).isFalse(); + assertThat(result.errorCode()).isEqualTo("RESPONSE_BINDING_MISMATCH"); + assertThat(result.contentDigest()).isNull(); + assertThat(result.abilitySchemaDigest()).isNull(); + } + + @Test + void rejectsSwappedManifestAndAbilityDigestsFromPublicationResponse(@TempDir Path tlsDirectory) + throws IOException { + var receipt = SelectedDraftGameLogicReceiptTest.fixture(); + var publication = publicationBinding(receipt); + var sourceRead = + new GameLogicPublicationSourceReadBinding(publication, receipt.authorization()); + var validResponse = + GameLogicPublicationSourceReadGrpcCodec.toResponse( + sourceRead, receipt.receipt().terminal()); + assertThat(validResponse.getContentDigest()) + .isNotEqualTo(validResponse.getAbilitySchemaDigest()); + var response = + validResponse.toBuilder() + .setContentDigest(validResponse.getAbilitySchemaDigest()) + .setAbilitySchemaDigest(validResponse.getContentDigest()) + .build(); + var clientAndStub = client(tlsDirectory); + when(clientAndStub.stub().getDraftDesignDigest(any(GetDraftDesignDigestRequest.class))) + .thenReturn(response); + + var result = clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt); + + assertThat(result.succeeded()).isFalse(); + assertThat(result.errorCode()).isEqualTo("RESPONSE_BINDING_MISMATCH"); + assertThat(result.contentDigest()).isNull(); + assertThat(result.abilitySchemaDigest()).isNull(); + } + @Test void missingReceiptLegacyPathFailsClosedWithoutCallingGameLogic(@TempDir Path tlsDirectory) throws IOException { From 97174b31be2ed08440be1a271cc00359614abaf6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 03:38:11 +1300 Subject: [PATCH 054/129] Capture canonical World selection in the genuine publication owner --- .../api-contracts.md | 2 +- .../game-design-service/game-templates.md | 2 +- .../world-management-service/api-contracts.md | 2 +- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 12 +- ...issionLeasePersistenceIntegrationTest.java | 448 +++++++++++++++++- ...licationExportPostgresIntegrationTest.java | 267 ++++++----- ...eWorldSelectedPublicationProofFactory.java | 105 ++++ ...SelectedDraftPublicationFreezeService.java | 38 +- ...rldSelectedPublicationSelectorCapture.java | 100 ++++ ...uthorizedDraftPostgresIntegrationTest.java | 4 + ...ctedDraftPublicationFreezeRequestTest.java | 86 +++- ...electedPublicationSelectorCaptureTest.java | 96 ++++ 13 files changed, 1032 insertions(+), 136 deletions(-) create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/GenuineWorldSelectedPublicationProofFactory.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCapture.java create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCaptureTest.java diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 47464c1037..35a0a887fb 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -71,7 +71,7 @@ Entity Management must also expose a read-only design-time synchronization surfa - `GetDraftDesignDigest(GetDraftDesignDigestRequest)` uses request shape `{tenantId, scope: oneof {versionId, scriptPatchVersion}}`. Entity Management supports `versionId` scope only and returns `UNSUPPORTED_SCOPE` otherwise. - Response returns `{tenantId, scope, appliedCommitId, contentDigest, digestSchemaVersion}` as described in [`world-editing-tools.md`](../game-design-service/world-editing-tools.md). -- Current drift: the digest handler has no owner/method authorization or exact Game Design publication binding beyond shared bearer parsing. The target workload, tenant/scope/request/workflow/digest context and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). +- Current boundary: `GetDraftDesignDigest` requires a configured trusted namespace and an authenticated same-namespace Game Design workload peer, and rejects forwarded end-user context. The handler validates the supplied publication request binding and returned tenant/scope. Its synthetic `appliedCommitId = "version:"` and current digest do not establish selected-commit evidence; the target binding and proof remain canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). ## Digest Input Manifest diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 7cddf4975d..7940d77b04 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -18,7 +18,7 @@ creators can quickly spin up new projects without starting from scratch. - Current script-patch resolution is not yet the target launch predicate: a full-version template/request can persist an arbitrary patch ID without proving a same-base `PUBLISHED` Game Design publication or Automation `READY` status. These are implementation gaps; the target validation and fail-before-instance-row rules remain below. - The target tenant-scoped `GetTemplateReferencePhase` cutover read is not implemented in the current proto or service. Current launch resolution checks only the per-template `templateReferencePhase` field (`ENFORCED`/`LEGACY`); it does not expose or consume the target durable tenant phase (`BACKFILLING`/`VALIDATED`/`ENFORCED`) required by launch and retirement tooling. - The construction adds a current normalized single-base projection and fresh, creation-receipt-backed tenant phase with full-inventory validation. It does not establish complete external-owner projections, authenticated launch consumption, retained-tenant cutover, or retirement/reference-query tooling. Detailed implementation and executed-versus-unrun proof belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). -- The unregistered selected-source construction adds closed config history, actual generated template-row provenance, normalized base/gameplay references and immutable snapshots. It is not total template or release completeness: nonempty World, Entity and Automation references remain denied without genuine exact owner readback, and publication still lacks the separate derived Game Logic receipt join. Newly qualified rows remain non-launchable; legacy opaque/unqualified config is not mapped or backfilled. See the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) for construction and proof limits. +- The unregistered selected-source construction adds closed config history, actual generated template-row provenance, normalized base/gameplay references, immutable snapshots, and an independently authorized, retained Game Logic receipt joined to the exact selected source. This does not establish complete publication or release composition: nonempty Entity and Automation references still lack genuine exact owner readback, and World and Account publication composition remain unproved. Newly qualified rows remain non-launchable; legacy opaque/unqualified config is not mapped or backfilled. See the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) for construction and proof limits. - REST `POST /templates` rejects a caller-supplied `id` before mapping or persistence. The repository save update path matches both `id` and `tenant_id`, leaves the tenant binding unchanged, and denies a tenant mismatch before tenant-qualified readback. Focused unit definitions cover create rejection and tenant-qualified update; production PostgreSQL proof remains open. This identity fix does not establish template configuration source completeness or the separate producer/readback gaps described above. - Current template-remap-set APIs persist tenant-scoped `DRAFT`/`APPROVED` sets and entries. When `ResolveLaunchDescriptor` receives a `sourceVersionId` that differs from the resolved target, it selects exactly one `APPROVED` set for the source/target pair and persists and returns that set's `remapSetId`; it does not collect or verify owning-domain attestations. The target attestation predicate remains below. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index cef50f2205..2855bb95a3 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -98,7 +98,7 @@ World Management exposes design-time APIs used by Game Design to write Draft tem ### Publication freeze and terminal handoff (target state) -The publication-freeze operations below remain unregistered target contract surfaces. Current construction includes owner-lock/freeze persistence, immutable terminal storage, a selected-fresh-graph checkpoint callback and a standalone selected-publication composition; these do not supply a registered publication-freeze RPC or complete owner handoff. The closed standalone freeze transport authenticates the exact same-namespace Game Design workload before decoding and resolves the complete private World owner binding from the immutable retained selected `APPLIED` application, never from caller-supplied private IDs or a topology plan. The callback rechecks the complete retained graph against current topology and epochs under the shared owner lock. The composition additionally obtains authenticated Game Design selection/current-Draft and Account held-order reads, retaining the original Account correlation with the first freeze. Its acknowledgement is the committed freeze event, not the current terminal phase or admission authority; exact replay preserves the original fence and owner-observed epoch without recapturing mutable remote authority. It does not establish the generic highest-applied-commit digest contract. No current caller may infer a public freeze, publication, or terminal owner result from internal storage, a digest, a remote `GetVersionState` read, or a Temporal run identity. Current capability and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The publication-freeze operations below remain unregistered target contract surfaces. Current construction includes owner-lock/freeze persistence, immutable terminal storage, a selected-fresh-graph checkpoint callback and a standalone selected-publication composition; these do not supply a registered publication-freeze RPC or complete owner handoff. The closed standalone freeze transport authenticates the exact same-namespace Game Design workload before decoding and resolves the complete private World owner binding from the immutable retained selected `APPLIED` application, never from caller-supplied private IDs or a topology plan. The callback rechecks the complete retained graph against current topology and epochs under the shared owner lock. `WorldSelectedDraftPublicationFreezeService.begin` obtains the actual Account held-publication authority and exact checkpoint, commits and reads back the freeze result, then invokes `WorldSelectedPublicationSelectorCapture` to capture canonical topology before returning the original freeze acknowledgement. A capture failure leaves the freeze in place; exact retry reuses immutable owner records without fresh mutable Account or Game Design reads. The owner binding and authority exchanges follow [Game Design Version Control](../game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state). The acknowledgement is the committed freeze event, not the current terminal phase or admission authority. This construction does not establish the generic highest-applied-commit digest contract. No current caller may infer a public freeze, publication, or terminal owner result from internal storage, a digest, a remote `GetVersionState` read, or a Temporal run identity. Current capability and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). `BeginVersionPublicationFreeze` accepts exactly: diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index acf492fc21..7fcfc5fc4f 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -162,3 +162,9 @@ Entry format: - Observation: The separate substantive Validation run 37928625721 was still executing on the same head; metadata and required runs use distinct concurrency groups. The body edit had not cancelled it. A pending-proof metadata failure is neither a runtime failure nor evidence that no physical validation was dispatched. - Expected pattern: Before requesting replacement CI or routing a dispatch failure, inspect enough same-head runs to distinguish substantive execution from newer metadata preservation, then assign one observer to the actual execution transition. - Current status: Wider read-only inspection established the active run, and the parent corrected the Overseer request. A sole sentinel owns its outcome; no replacement run or workflow/topology change was made. + +- `2026-10-10`: Validate required controller fields before replacing a standing brief + - Context: Document read the absent JSON field `body` instead of the required `brief` field when appending an accepted disposition through guarded `jobs revise`. + - Observation: The revision guard prevented concurrent replacement but did not prevent a semantically incomplete payload; the standing brief was briefly replaced by the addendum alone. + - Expected pattern: Require a string-valued `brief`, preserve it without a missing-field fallback, and read back both the original mandate and the appended instruction after revision. A revision guard is not content validation. + - Current status: Restored the complete revision-302 brief from controller history and appended the disposition in revision 304; readback confirmed 66,031 characters and the original mandate. Overseer was informed and preserved the correction in revision 305. No repository behavior or controller policy changed. 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 c492887886..4fd55fbbc6 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 @@ -6,9 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The bounded GD+World source/APPLIED/original terminal-settlement path has executed PostgreSQL proof, including lost acknowledgement and unknown-outcome recovery, as recorded below. The later construction adds fresh creation-receipt-backed normalized template phase, immutable selected export candidates with actual-byte object readback, the closed Account-gated Game Session association read and exact descriptor projection. Corrected gates R281 and R283 pass Game Design full checks, canonical formatting, Checkstyle, SpotBugs, coverage, the boot JAR and documentation checks: the unit reports contain 522 passes, while all 143 integration cases compile and skip locally without Docker; unchanged outputs are reused. R282's missing integration-fixture imports were corrected before the successful R283 gate. The earlier composed R278 gate also passed Common's 446 units. These local runs do not establish physical descriptor/export composition. V66 passes schema generation and the originating physical candidate-suite migration proof below, not successful descriptor creation/readback. +Published `9f287e05e06b87adc3db79984b2e047e5d5b819f` [Validation run 37939078493](https://github.com/benhook1013/FireMUD/actions/runs/37939078493) executed 146 Game Design PostgreSQL cases with one failure, 254 Account cases with one failure, and 207 World cases with no failures; all three suites report zero skips and errors. The three genuine GD+World source/settlement cases, genuine Game Logic intake case, approved-remap retention correction and eight legacy descriptor persistence/retry/migration cases passed. The genuine selected export/descriptor case failed before export because its stipulated World evidence supplied a prefixed content hash to a bare-hex field. Since that run, the local construction has replaced the stipulated Account publication-order and World freeze/inventory/selector evidence with the actual owner reads and adds canonical topology capture after freeze. This new composition has no physical proof yet. Account's failure moved to the physical-confirmation/independent-read case and again denied at V90's conservative coverage prerequisite: insert `0/7EDFE48` exceeded initial/final flush `0/7EDFE08` while the original bound remained unchanged. A bounded fixture diagnosis is separate from source/release construction. Overseer deferred production WAL-locator adoption; the prototype, original JVM acknowledgement/time bounds, V90/V92 recovery semantics and PostgreSQL-version guards remain unchanged. The actual synthetic checkout is `1822fbae8dc9f6c4409ccc9515a99ee5e5f42e99`, tree `dc3142f6c4284288a43ed71d97632c35ee4afe09`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published source. This is exact-source execution, not intended-parent alignment, a genuine complete release or activation. -The selection binding preserves `publicationDigestRequest/v1`; exact retained Game Logic terminal/receipt evidence supplies aggregate and dedicated ability-schema evidence without a tenant/version-only fallback. The next construction composes genuine GD+World source settlement and Account/Game Logic receipt retention with the real selected inventory, candidate/export and Game Design-local publication finalizer, followed by exact association-derived descriptor storage and replay. Its PostgreSQL definition now uses the actual mutual-TLS Game Logic selected-source read and Game Design's selected control-plane digest, retained unchanged in release readback; the narrow client conversion preserves the original wire hash and emits the release's bare-hex aggregate representation. Selected-publication Account/freeze/inventory admission and Entity/Automation participants remain stipulated; the World participant reads retained fixture freeze evidence, and S3 transport and the StartSession Account projection are explicit test doubles. It is not complete four-owner publication or authenticated positive runtime launch proof. V66 retains the original operation tuple, attempt/fence, exact association, selected Game Logic receipt and release alongside the descriptor. The separate protected exact-replay adapter remains unregistered, as does the earlier association reader. Complete release/settlement, authenticated descriptor/consumer and World held-authority handoffs, and runtime activation remain open. Account's separate confirmation-WAL denial is an admission proof gap, not grounds to weaken source or release guards. +The bounded GD+World source/APPLIED/original terminal-settlement path has executed PostgreSQL proof, including lost acknowledgement and unknown-outcome recovery, as recorded below. Later construction adds fresh creation-receipt-backed normalized template phase, immutable selected export candidates with actual-byte object readback, the closed Account-gated Game Session association read and exact descriptor projection. The corrected local World/Game Design gate passes full checks, formatting, Checkstyle, SpotBugs, coverage and both boot JARs in 2m 7s, with 585 World unit cases executed and 522 unchanged Game Design unit results reused. All 207 World and 143 Game Design integration cases compile/discover but skip without Docker. Account's separate full check passes in 2m 11s with 1,109 unit cases executed; its integration reports contain seven executed non-container cases and 239 skips. This includes a test-only coordinator for the two affected V90 confirmation fixtures: it observes the actual backend's coverage wait, then commits and independently reads one synchronous logged marker without changing production guards or original expiry bounds. Corrected-head physical confirmation and descriptor/export composition remain unproved. V66 passes schema generation and the originating physical candidate-suite migration proof below, not successful descriptor creation/readback. + +The selection binding preserves `publicationDigestRequest/v1`; exact retained Game Logic terminal/receipt evidence supplies aggregate and dedicated ability-schema evidence without a tenant/version-only fallback. The current construction composes genuine GD+World source settlement and Account/Game Logic receipt retention with actual Account publication authority and World freeze/inventory/selector capture, canonical topology capture, the selected export, and the Game Design-local publication finalizer, followed by exact association-derived descriptor storage and replay. Its PostgreSQL definition uses the actual mutual-TLS Game Logic selected-source read and Game Design's selected control-plane digest, retained unchanged in release readback; the narrow client conversion preserves the original wire hash and emits the release's bare-hex aggregate representation. Entity/Automation participants remain stipulated; S3 transport and the StartSession Account projection are explicit test doubles. The World participant digest and authenticated positive runtime launch are not proved by this composition. V66 retains the original operation tuple, attempt/fence, exact association, selected Game Logic receipt and release alongside the descriptor. The separate protected exact-replay adapter remains unregistered, as does the earlier association reader. Complete release/settlement, authenticated descriptor/consumer and World held-authority handoffs, and runtime activation remain open. Account's separate confirmation-WAL denial is an admission proof gap, not grounds to weaken source or release guards. Published `0eacc39ff5602a64d8e170421b392123a2dda2c9` [Validation run 37935183958](https://github.com/benhook1013/FireMUD/actions/runs/37935183958) completed red with originating Game Design integration XML for 146 cases, two failures and zero skips. All three genuine GD+World source/settlement cases and the genuine Game Logic intake/settlement case passed, as did the six selected export candidates, four reference-phase cases, six selected Game Logic receipt cases and 23 asset-publication cases. V66 applied successfully in the isolated candidate schemas. The new genuine export/descriptor fixture failed before source mutation because it read the prepared Account creator before preparing the original order; that ordering is corrected without changing Account issuance. The other failure attached remap creation to the obsolete legacy export callback instead of the selected-export call; the correction preserves the strict request binding and retention assertions. World passed all 207 PostgreSQL cases with zero skips. Account executed 254 cases with one conservative confirmation-WAL coverage failure and zero skips; its separate 31-case Draft-fence artifact duplicates the passing suite already included in that total. The two PostgreSQL 16/pinned-18 module probes passed, establishing restricted module capability only, not original-COMMIT durability or failover proof. Common jobs and Dev Tool Contract Checks passed. The actual synthetic checkout is `b802c02ac99a3217202bbe9297a21f83dd523e8f`, tree `c84e0e3c5ce4fb03b683b30fd3f7cc58d179bfe7`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published head, not the recorded integration parent. These results do not establish successful corrected-head export/descriptor execution or intended-parent alignment. @@ -157,7 +159,7 @@ The live `CompareAndSetVersionState` path has an additional transition-safety ga - `AR-1.3`: [ADR 0127](../../architecture/decisions/adr-0127-game-authored-equipment-layouts-with-fail-closed-publication.md) makes the complete game-authored equipment vocabulary/body-layout publication gate a target obligation. [ADR 0130](../../architecture/decisions/adr-0130-historical-equipment-body-layout-authority.md) is superseded by it. Existing equipment/editor and publication caveats remain unchanged. - `AR-1.3`: [ADR 0128](../../architecture/decisions/adr-0128-game-design-plugin-trust-provenance.md) records Game Design's accepted local provenance record under [ADR 0111](../../architecture/decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md); it does not upgrade current signed intake, runtime readiness, compatibility, or activation proof. - `AR-1.5`: [ADR 0129](../../architecture/decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) records exact-base/digest Draft proposals and owner-local CAS/read-fence obligations. The current implementation and focused proof remain partial, with no silent-merge or distributed-transaction claim. -- `AR-1.5`: The unregistered selected-Draft construction now retains a World owner-local publication freeze and exposes an exact authenticated acknowledgement consumed by Game Design admission. Legacy publication and ordinary mutation ingress do not thereby acquire that boundary. Genuine producer composition, owner-terminal settlement and corrected-head physical retry/race proof remain incomplete. The target handoff remains canonical in [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff). +- `AR-1.5`: The unregistered selected-Draft construction now obtains actual Account held-publication authority, freezes from the retained `APPLIED` owner record, captures the canonical selector/topology, and exposes the committed freeze acknowledgement to Game Design admission. Capture failure preserves the freeze and exact retry reuses immutable owner records without fresh mutable Account/Game Design reads. Legacy publication and ordinary mutation ingress do not thereby acquire that boundary. Owner-terminal settlement and corrected-head physical retry/race proof remain incomplete. The target handoff remains canonical in [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff). - `AR-1.5`: Publish participant authorization and identity remain blocked across the owner seam. Automation is currently admin-role-only while WMS, Entity, and Game Logic digest handlers are bearer-only; the live Game Design participant DTO/client/gate omit and do not compare `tenantId`, and Game Logic accepts a blank tenant with a tenant/version-independent empty manifest. The shared target owner allowlist, exact publication binding, tenant comparison, and wrong-workload/cross-tenant/identity proof are canonical in [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). - `AR-1.5`: The typed WMS `ApplyWorldDesignMutation` write path has the same unrecorded owner-boundary gap: its live gRPC handler accepts any shared-JWT bearer and does not enforce the target tenant or an allowlisted Game Design caller before mutation. This is distinct from participant digest authorization and the legacy REST generation-rule ingress; cross-tenant/wrong-workload denial remains unimplemented and unproved, while the target Game Design caller/tenant authorization remains canonical in the WMS API contract. @@ -280,7 +282,7 @@ Design-time revoke is explicit through `RevokePluginVersion`. Upload verificatio ### World Design Authoring Handoff -Game Design owns revision history, commits, version state, and publish orchestration; World Management owns authoritative Draft and Published world template rows. `SaveRevision` is version-scoped and carries typed `worldDesignMutation` payloads, including `WORLD_GENERATION_SUBTREE`, through the canonical World Management API. The first caller path saves revision history and applies the concrete change through that API rather than directly mutating World tables or treating opaque revision JSON as the authoritative world graph. The current seam permits only Draft version design-time writes; Published, Active, Failed, and Retired scopes are rejected. Standalone selected-publication freeze and terminal components now exist, but are unregistered and do not establish genuine multi-owner production handoff. Their target behavior remains owned by the [World Management contract](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state); remaining producer and proof gaps are recorded above. +Game Design owns revision history, commits, version state, and publish orchestration; World Management owns authoritative Draft and Published world template rows. `SaveRevision` is version-scoped and carries typed `worldDesignMutation` payloads, including `WORLD_GENERATION_SUBTREE`, through the canonical World Management API. The first caller path saves revision history and applies the concrete change through that API rather than directly mutating World tables or treating opaque revision JSON as the authoritative world graph. The current seam permits only Draft version design-time writes; Published, Active, Failed, and Retired scopes are rejected. Standalone selected-publication freeze, selector capture and terminal components now exist, but remain unregistered and do not establish genuine multi-owner production handoff. Their target behavior remains owned by the [World Management contract](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state); remaining producer and proof gaps are recorded above. ### Validation and Proof @@ -301,7 +303,7 @@ Game Design owns revision history, commits, version state, and publish orchestra - The broader authoring and publication domain remains in progress. Participant digests still need actual target-commit provenance and coordinated schema adoption, and the release bundle still needs canonical target-commit, manifest-schema, and applicable artifact-digest fields. Future domain-template families must join the version-scoped digest gate; future release-bundle consumers must apply missing-attestation, unsupported-schema, and exact-asset-proof hard failures. - Publish/version synchronization remains incomplete across downstream domain-owned schemas. Game Design owns revision history, version metadata, and publish orchestration, while Entity Management and World Management retain authoritative entity and world rows; the current participant observations and first World mutation handoff do not yet establish actual same-commit convergence or cover every future editor caller or template family. - Asset lifecycle follow-through remains incomplete. The current implementation lacks the version-scoped asset mapping/authoring path and corresponding publication/export guard; purge and publication recovery also lack complete durable operation, CAS, and exact readback proof. The canonical lifecycle and operation contracts are owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); this tracker records the status and proof gaps without repeating those normative details. -- Closed config/reference production remains a separate gap from the committed World source checkpoint: World and Entity authored-template logical IDs use canonical UUID strings, but Game Design has no exact selected-commit reference writer/readback. Entity's current validator/read path covers only `ITEM`/`NPC` through a positive-decimal storage key, not the canonical UUID readback or owner proof that an `ITEM` is equippable; equipment-oriented input is that `ITEM` identity, while runtime equipment binding remains separate. Automation owns `SCRIPT`, event-binding, and `SCRIPT_PATCH`, using current exact script name/raw patch keys without a canonical base-UUID bridge; it has no `RULESET` family. Game Logic's exact owner-retained configuration/source receipt for the selected tenant/base/commit is not currently produced/read back, so it cannot be replaced by per-rule IDs, `latest`, or another participant digest. No non-authoritative settings member is registered; runtime flags remain launch-authoritative. These are producer/readback gaps, not evidence that any unavailable source family is empty. +- Closed config/reference production remains a separate gap from the committed World source checkpoint: World and Entity authored-template logical IDs use canonical UUID strings, but Game Design has no exact selected-commit reference writer/readback. Entity's current validator/read path covers only `ITEM`/`NPC` through a positive-decimal storage key, not the canonical UUID readback or owner proof that an `ITEM` is equippable; equipment-oriented input is that `ITEM` identity, while runtime equipment binding remains separate. Automation owns `SCRIPT`, event-binding, and `SCRIPT_PATCH`, using current exact script name/raw patch keys without a canonical base-UUID bridge; it has no `RULESET` family. The selected construction now retains and reads back Game Logic's exact owner receipt/intake for the selected tenant/base/commit; this does not complete the other owner reference producers or establish full publication proof. No non-authoritative settings member is registered; runtime flags remain launch-authoritative. These are producer/readback gaps, not evidence that any unavailable source family is empty. - Launch/activation follow-through includes broader cutover and retirement consumers, later runtime-state families, exact Entity target-template validation once version-scoped entity-template tables exist, and replacement of remaining placeholder runtime topology/state rows. - V64's construction adds the exact current `game_template_version_ref` projection and durable fresh-tenant `BACKFILLING`/`VALIDATED`/`ENFORCED` phase. Genesis requires the completed `NEW_GAME_ROW` creation receipt, never retained-row inference. Source synchronization may promote a nonempty complete qualified inventory under the shared Game-row mutex; empty, unqualified, tombstoned or unsupported inventory cannot prove enforcement. The defined PostgreSQL cases and new authenticated association receiver still need corrected-head validation. The target tenant-scoped `GetTemplateReferencePhase` RPC and existing launch/retirement consumers remain unimplemented; the older live descriptor path still checks the per-template `ENFORCED`/`LEGACY` field. No positive launch or retained-tenant cutover proof is claimed. - StartSession still needs to validate same-base `PUBLISHED` patch identity and join Automation's tenant-scoped script-patch status, failing closed unless the pinned patch is runtime `READY`; current descriptor validation proves neither publication identity nor readiness. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index ce97064c2f..d017ddc2a9 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -21,15 +21,22 @@ import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; import java.util.function.Supplier; import javax.sql.DataSource; import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionCommitConfirmation; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; @@ -101,6 +108,8 @@ class AccountGameplayAdmissionLeasePersistenceIntegrationTest { private static final String TENANT = "22222222-2222-4222-8222-222222222222"; private static final String OTHER = "33333333-3333-4333-8333-333333333333"; + private static final long V90_WAL_COORDINATOR_TIMEOUT_SECONDS = 3; + private static final String V90_WAL_MARKER_TABLE = "account_v90_wal_coverage_markers"; @BeforeAll static void start() { @@ -1133,13 +1142,25 @@ void receiptPhysicalCommitPrecedesIndependentV90ReadOnAnotherConnection() throws UUID decision = UUID.randomUUID(); new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) .execute(original, decision); + createV90WalCoverageMarkerTable(context); + String applicationName = v90ApplicationName(); var trace = new ReceiptCommitTrace(); var owner = new AccountGameplayAdmissionCommitConfirmationOwner( - receiptCommitDataSource(context.dataSource(), ReceiptCommitFault.NONE, trace), "test"); + receiptCommitDataSource( + applicationNamedDataSource(context.dataSource(), applicationName), + ReceiptCommitFault.NONE, + trace), + "test"); var receipt = - syntheticReadPeer().call(() -> owner.confirm(confirmationRequest(original, decision))); + withV90WalCoverageCoordinator( + context, + applicationName, + () -> + callWithSyntheticReadPeer( + () -> owner.confirm(confirmationRequest(original, decision))), + AccountGameplayAdmissionCommitConfirmation::walInsertLsn); assertThat(trace.count("physical-commit")).isEqualTo(2); assertThat(trace.count("v90-read")).isEqualTo(1); @@ -1656,6 +1677,7 @@ void sameTransactionReceiptReadAndRolledBackConfirmationCannotProveDurability() var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); UUID decision = UUID.randomUUID(); tx(context, () -> repository.recordCommitted(original, decision)); + createV90WalCoverageMarkerTable(context); for (boolean subtransaction : List.of(false, true)) { assertThatThrownBy( () -> @@ -1663,7 +1685,21 @@ void sameTransactionReceiptReadAndRolledBackConfirmationCannotProveDurability() context, () -> { if (subtransaction) context.dsl().execute("SAVEPOINT receipt_creation"); - confirm(context, original, decision); + String applicationName = v90ApplicationName(); + var receipt = + withV90WalCoverageCoordinator( + context, + applicationName, + () -> { + setLocalApplicationName(context.dsl(), applicationName); + return confirm(context, original, decision); + }, + row -> row.get("wal_insert_lsn", String.class)); + assertThat(receipt.get("committed_before_ms", Long.class)) + .isPositive() + .isLessThan(expiresAt(original)); + assertThat(receipt.get("expires_at_ms", Long.class)) + .isEqualTo(expiresAt(original)); if (subtransaction) context.dsl().execute("RELEASE SAVEPOINT receipt_creation"); assertDeniedInSavepoint( @@ -1679,7 +1715,20 @@ void sameTransactionReceiptReadAndRolledBackConfirmationCannotProveDurability() .isZero(); assertThatThrownBy(() -> tx(context, () -> readConfirmation(context, original, decision))) .hasMessageContaining("exact durable receipt required"); - var receipt = tx(context, () -> confirm(context, original, decision)); + var receipt = + tx( + context, + () -> { + String applicationName = v90ApplicationName(); + return withV90WalCoverageCoordinator( + context, + applicationName, + () -> { + setLocalApplicationName(context.dsl(), applicationName); + return confirm(context, original, decision); + }, + row -> row.get("wal_insert_lsn", String.class)); + }); assertThat(tx(context, () -> readConfirmation(context, original, decision))).isEqualTo(receipt); } @@ -2307,6 +2356,397 @@ private static Record confirm( decision)); } + private static T withV90WalCoverageCoordinator( + Context context, + String applicationName, + Supplier confirmation, + Function insertFence) { + var actionFinished = new AtomicBoolean(); + var coordinatorLock = new Object(); + var monitorReady = new CountDownLatch(1); + var coordinatorConnection = new AtomicReference(); + ExecutorService executor = + Executors.newSingleThreadExecutor( + task -> { + Thread thread = new Thread(task, "account-v90-wal-coordinator-" + applicationName); + thread.setDaemon(true); + return thread; + }); + Future future = + executor.submit( + () -> + observeV90WalCoverage( + context, + applicationName, + actionFinished, + coordinatorLock, + monitorReady, + coordinatorConnection)); + + T result = null; + Throwable actionFailure = null; + try { + if (!monitorReady.await(2, TimeUnit.SECONDS)) { + actionFailure = + new IllegalStateException( + "Account V90 WAL coverage coordinator could not open its observation connection"); + } else { + result = confirmation.get(); + } + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + actionFailure = new IllegalStateException("Interrupted before Account confirmation", failure); + } catch (RuntimeException | Error failure) { + actionFailure = failure; + } finally { + synchronized (coordinatorLock) { + actionFinished.set(true); + } + } + + executor.shutdown(); + V90WalCoverageObservation observation = null; + Throwable coordinatorFailure = null; + try { + observation = future.get(2, TimeUnit.SECONDS); + } catch (ExecutionException failure) { + coordinatorFailure = failure.getCause(); + } catch (TimeoutException failure) { + coordinatorFailure = failure; + future.cancel(true); + executor.shutdownNow(); + closeCoordinatorConnection(coordinatorConnection, coordinatorFailure); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + coordinatorFailure = failure; + future.cancel(true); + executor.shutdownNow(); + closeCoordinatorConnection(coordinatorConnection, coordinatorFailure); + } + + try { + if (!executor.awaitTermination(2, TimeUnit.SECONDS)) { + executor.shutdownNow(); + var cleanupFailure = + new IllegalStateException("Account V90 WAL coverage coordinator did not terminate"); + closeCoordinatorConnection(coordinatorConnection, cleanupFailure); + if (!executor.awaitTermination(2, TimeUnit.SECONDS)) { + if (coordinatorFailure == null) coordinatorFailure = cleanupFailure; + else coordinatorFailure.addSuppressed(cleanupFailure); + } + } + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + executor.shutdownNow(); + if (coordinatorFailure == null) coordinatorFailure = failure; + else coordinatorFailure.addSuppressed(failure); + closeCoordinatorConnection(coordinatorConnection, coordinatorFailure); + } + + if (actionFailure != null) { + if (coordinatorFailure != null) actionFailure.addSuppressed(coordinatorFailure); + actionFailure.addSuppressed( + new IllegalStateException( + describeV90WalCoordinatorOutcome(applicationName, observation))); + if (actionFailure instanceof RuntimeException runtimeFailure) throw runtimeFailure; + throw (Error) actionFailure; + } + + if (coordinatorFailure != null) { + throw new IllegalStateException( + "Account V90 confirmation succeeded, but its bounded WAL coordinator failed", + coordinatorFailure); + } + if (observation != null && observation.marker() != null) { + String fence = Objects.requireNonNull(insertFence.apply(result)); + Boolean covered = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT ?::pg_lsn >= ?::pg_lsn AS covered", + observation.marker().flushLsn(), + fence)) + .get("covered", Boolean.class); + assertThat(covered) + .as( + "independent marker COMMIT flush covers V90 fence %s from backend %s", + fence, observation.backendPid()) + .isTrue(); + } + return result; + } + + private static V90WalCoverageObservation observeV90WalCoverage( + Context context, + String applicationName, + AtomicBoolean actionFinished, + Object coordinatorLock, + CountDownLatch monitorReady, + AtomicReference coordinatorConnection) + throws SQLException { + Integer backendPid = null; + String lastWaitEventType = null; + String lastWaitEvent = null; + long deadline = + System.nanoTime() + TimeUnit.SECONDS.toNanos(V90_WAL_COORDINATOR_TIMEOUT_SECONDS); + try (Connection connection = context.dataSource().getConnection(); + PreparedStatement activity = + connection.prepareStatement( + "SELECT pid, wait_event_type, wait_event FROM pg_stat_activity " + + "WHERE application_name = ? AND state = 'active' " + + "AND strpos(query, 'account_gameplay_admission_confirm_committed') > 0 " + + "AND (?::integer IS NULL OR pid = ?)")) { + coordinatorConnection.set(connection); + activity.setQueryTimeout(1); + monitorReady.countDown(); + while (System.nanoTime() < deadline) { + activity.setString(1, applicationName); + if (backendPid == null) { + activity.setNull(2, java.sql.Types.INTEGER); + activity.setNull(3, java.sql.Types.INTEGER); + } else { + activity.setInt(2, backendPid); + activity.setInt(3, backendPid); + } + try (ResultSet rows = activity.executeQuery()) { + if (rows.next()) { + int currentPid = rows.getInt("pid"); + if (backendPid != null && backendPid != currentPid) { + throw new SQLException( + "Account V90 confirmation backend changed during WAL coordination"); + } + backendPid = currentPid; + lastWaitEventType = rows.getString("wait_event_type"); + lastWaitEvent = rows.getString("wait_event"); + if (rows.next()) { + throw new SQLException( + "Multiple Account V90 confirmation backends matched unique application name"); + } + if ("Timeout".equals(lastWaitEventType) && "PgSleep".equals(lastWaitEvent)) { + synchronized (coordinatorLock) { + if (actionFinished.get()) { + return new V90WalCoverageObservation( + backendPid, lastWaitEventType, lastWaitEvent, null, false); + } + connection.close(); + coordinatorConnection.compareAndSet(connection, null); + V90WalCoverageMarker marker = + commitV90WalCoverageMarker(context, coordinatorConnection); + return new V90WalCoverageObservation( + backendPid, lastWaitEventType, lastWaitEvent, marker, false); + } + } + } + } + synchronized (coordinatorLock) { + if (actionFinished.get()) { + return new V90WalCoverageObservation( + backendPid, lastWaitEventType, lastWaitEvent, null, false); + } + } + Thread.yield(); + } + return new V90WalCoverageObservation( + backendPid, lastWaitEventType, lastWaitEvent, null, true); + } finally { + monitorReady.countDown(); + } + } + + private static V90WalCoverageMarker commitV90WalCoverageMarker( + Context context, AtomicReference coordinatorConnection) throws SQLException { + UUID markerId = UUID.randomUUID(); + String markerValue = UUID.randomUUID().toString(); + int writerBackendPid; + try (Connection writer = context.dataSource().getConnection()) { + coordinatorConnection.set(writer); + writer.setAutoCommit(false); + try { + try (Statement statement = writer.createStatement()) { + statement.setQueryTimeout(1); + statement.execute("SET LOCAL synchronous_commit = on"); + try (ResultSet settings = + statement.executeQuery( + "SELECT pg_backend_pid(), current_setting('synchronous_commit')")) { + if (!settings.next() || !"on".equals(settings.getString(2))) { + throw new SQLException("Account V90 marker writer did not retain synchronous COMMIT"); + } + writerBackendPid = settings.getInt(1); + if (settings.next()) { + throw new SQLException( + "Account V90 marker writer settings query returned multiple rows"); + } + } + } + try (PreparedStatement insert = + writer.prepareStatement( + "INSERT INTO " + + V90_WAL_MARKER_TABLE + + " (marker_id, marker_value) VALUES (?, ?)")) { + insert.setQueryTimeout(1); + insert.setObject(1, markerId); + insert.setString(2, markerValue); + if (insert.executeUpdate() != 1) { + throw new SQLException("Account V90 marker INSERT did not write exactly one row"); + } + } + writer.commit(); + } catch (SQLException | RuntimeException | Error failure) { + try { + writer.rollback(); + } catch (SQLException rollbackFailure) { + failure.addSuppressed(rollbackFailure); + } + throw failure; + } finally { + coordinatorConnection.compareAndSet(writer, null); + } + } + + int readerBackendPid; + try (Connection reader = context.dataSource().getConnection(); + PreparedStatement readback = + reader.prepareStatement( + "SELECT marker_value, pg_backend_pid() FROM " + + V90_WAL_MARKER_TABLE + + " WHERE marker_id = ?")) { + coordinatorConnection.set(reader); + readback.setQueryTimeout(1); + readback.setObject(1, markerId); + try (ResultSet row = readback.executeQuery()) { + if (!row.next() || !markerValue.equals(row.getString(1))) { + throw new SQLException("Committed Account V90 WAL marker was not independently readable"); + } + readerBackendPid = row.getInt(2); + if (readerBackendPid == writerBackendPid || row.next()) { + throw new SQLException("Account V90 WAL marker readback was not exact and independent"); + } + } + String flushLsn; + try (Statement statement = reader.createStatement()) { + statement.setQueryTimeout(1); + try (ResultSet result = statement.executeQuery("SELECT pg_current_wal_flush_lsn()::text")) { + if (!result.next()) + throw new SQLException("Account V90 marker flush location unavailable"); + flushLsn = result.getString(1); + } + } + return new V90WalCoverageMarker(flushLsn); + } finally { + coordinatorConnection.set(null); + } + } + + private static void createV90WalCoverageMarkerTable(Context context) { + context + .dsl() + .execute( + "CREATE TABLE " + + V90_WAL_MARKER_TABLE + + " (marker_id UUID PRIMARY KEY, marker_value TEXT NOT NULL)"); + } + + private static DataSource applicationNamedDataSource(DataSource source, String applicationName) { + return new DelegatingDataSource(source) { + @Override + public Connection getConnection() throws SQLException { + return setApplicationName(super.getConnection(), applicationName); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return setApplicationName(super.getConnection(username, password), applicationName); + } + }; + } + + private static Connection setApplicationName(Connection connection, String applicationName) + throws SQLException { + try (PreparedStatement statement = + connection.prepareStatement("SELECT set_config('application_name', ?, false)")) { + statement.setString(1, applicationName); + try (ResultSet result = statement.executeQuery()) { + if (!result.next() || !applicationName.equals(result.getString(1)) || result.next()) { + throw new SQLException("Account V90 application name could not be verified"); + } + return connection; + } + } catch (SQLException failure) { + try { + connection.close(); + } catch (SQLException closeFailure) { + failure.addSuppressed(closeFailure); + } + throw failure; + } + } + + private static void setLocalApplicationName(DSLContext dsl, String applicationName) { + String configured = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT set_config('application_name', ?, true) AS application_name", + applicationName)) + .get("application_name", String.class); + assertThat(configured).isEqualTo(applicationName); + } + + private static String v90ApplicationName() { + return "account-v90-" + UUID.randomUUID().toString().replace("-", ""); + } + + private static T callWithSyntheticReadPeer(Callable action) { + try { + return syntheticReadPeer().call(action); + } catch (RuntimeException | Error failure) { + throw failure; + } catch (Exception failure) { + throw new IllegalStateException("Synthetic Account confirmation call failed", failure); + } + } + + private static String describeV90WalCoordinatorOutcome( + String applicationName, V90WalCoverageObservation observation) { + if (observation == null) { + return "Account V90 coordinator produced no observation for application_name=" + + applicationName; + } + return "Account V90 coordinator outcome" + + ": application_name=" + + applicationName + + " backend_pid=" + + observation.backendPid() + + " last_wait_event_type=" + + observation.waitEventType() + + " last_wait_event=" + + observation.waitEvent() + + " timed_out=" + + observation.timedOut() + + " marker_independently_read=" + + (observation.marker() != null); + } + + private static void closeCoordinatorConnection( + AtomicReference connectionReference, Throwable failure) { + Connection connection = connectionReference.getAndSet(null); + if (connection == null) return; + try { + connection.close(); + } catch (SQLException closeFailure) { + failure.addSuppressed(closeFailure); + } + } + + private record V90WalCoverageMarker(String flushLsn) {} + + private record V90WalCoverageObservation( + Integer backendPid, + String waitEventType, + String waitEvent, + V90WalCoverageMarker marker, + boolean timedOut) {} + private static FinalizeGameplayAdmissionLeaseRequest confirmationRequest( AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { return FinalizeGameplayAdmissionLeaseRequest.newBuilder() diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 70b23bac49..974614273f 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -51,7 +51,6 @@ import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -88,21 +87,28 @@ import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; import net.firedevops.firemud.common.security.PublicationReadGuard; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; -import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; -import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.client.GameLogicClient; +import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcomeRepository; import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.draft.GameDesignSelectedDraftPublicationReadGrpcService; import net.firedevops.firemud.gamedesign.draft.GameDesignWorldSourceCommitService; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; @@ -113,19 +119,16 @@ import net.firedevops.firemud.gamedesign.publication.AssetSource; import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadGrpcService; import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadService; -import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; -import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventoryReadService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftControlPlaneDigest; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicIntakeCommandService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptService; +import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationAdmissionService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService; -import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; -import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation.SourceRead; import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociationRepository; import net.firedevops.firemud.gamedesign.publication.StartSessionLaunchDescriptorProducer; import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; @@ -171,6 +174,7 @@ import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadService; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.tenant.GenuineWorldSelectedPublicationProofFactory; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeService; @@ -181,7 +185,6 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldDraftCommitOrderVerifier; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationService; -import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphAppliedResult; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalOutcomeRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalReadGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplicationService; @@ -224,11 +227,15 @@ /** * Real original GD+World source settlement and Account/GL intake-to-GD-receipt, followed by actual - * selected inventory/export, the owner-local publication finalizer, and descriptor SQL storage. - * Selected-publication Account/freeze/inventory admission and Entity/Automation participant digests - * are stipulated; the World participant uses only retained fixture freeze evidence. In-memory S3 - * and StartSession Account projection are test doubles. This is not a four-owner authenticated - * release, runtime launch, activation, or registration proof. + * selected inventory/export, the owner-local publication finalizer, and descriptor SQL storage. The + * distinct Account publication order comes from the actual Account owner fixture; its inbound Game + * Design peer and upstream selection/platform/legal evidence are supplied by test context. The + * immutable selection read and held-order reads use loopback mTLS. World freeze, immutable + * inventory and published selector use their actual owner services over loopback mTLS, with the + * canonical frozen selector captured owner-locally from the committed freeze and retained APPLIED + * graph. Entity/Automation participant digests, in-memory S3 and the StartSession Account + * projection remain test doubles. This is not a complete four-owner authenticated release, runtime + * launch, activation or registration proof. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -386,6 +393,27 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex endpoints, pki.client("game-design-service"), channels, NAMESPACE); var gdToAccountSettlement = new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var accountSelectionReadClient = + new AuthoredDraftPublishSelectionReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var worldSelectionReadClient = + new AuthoredDraftPublishSelectionReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var worldAccountReadClient = + new AccountPublicationAuthorizationReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var gdAccountPublicationReadClient = + new AccountPublicationAuthorizationReadClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var selectedPublicationFreezeClient = + new WorldSelectedDraftPublicationFreezeClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var selectedPublicationInventoryClient = + new WorldSelectedPublicationArtifactInventoryClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var publishedStartLocationClient = + new WorldPublishedStartLocationClient( endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { sourceClient.init(); versionClient.init(); @@ -455,14 +483,37 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex accountHandlers, account.originalDraftOrderProducer(NAMESPACE), new AccountDraftCommitOrderReadGrpcService( - account.heldOrderOwner(NAMESPACE), NAMESPACE)); + account.heldOrderOwner(NAMESPACE), NAMESPACE), + new AccountPublicationAuthorizationReadGrpcService( + account.heldPublicationOwner(NAMESPACE), NAMESPACE)); var coordinator = new DraftCommitCoordinatorRepository(gd.dsl()); var gdTerminals = new GameDesignDraftTerminalOutcomeRepository(gd.dsl()); var gdSources = new GameDesignSourceRepository(gd.dsl()); + var selectionRepository = + new AuthoredDraftPublishSelectionRepository(gd.dsl(), coordinator); + register( + gdHandlers, + new GameDesignSelectedDraftPublicationReadGrpcService(selectionRepository, NAMESPACE)); var worldFence = new WorldDesignPublicationFenceRepository(world.dsl(), worldIntakes); var worldApplications = new WorldDraftGraphApplicationRepository(world.dsl(), worldFence, new ObjectMapper()); + var worldPublicationProof = + new GenuineWorldSelectedPublicationProofFactory( + NAMESPACE, + world.dsl(), + world.transactions(), + worldIntakes, + worldFence, + worldApplications, + worldSelectionReadClient, + versionClient, + worldAccountReadClient, + new ObjectMapper()); + register( + worldHandlers, + worldPublicationProof.freezeAndInventoryService(), + worldPublicationProof.publishedStartLocationReadService()); var worldApplicationService = new WorldDraftGraphApplicationService( worldApplications, @@ -572,6 +623,13 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex gdToAccountIntakeAuthorization.init(); gdToGlRetain.init(); gdToAccountSettlement.init(); + accountSelectionReadClient.init(); + worldSelectionReadClient.init(); + worldAccountReadClient.init(); + gdAccountPublicationReadClient.init(); + selectedPublicationFreezeClient.init(); + selectedPublicationInventoryClient.init(); + publishedStartLocationClient.init(); var sourceCommit = new GameDesignWorldSourceCommitService( @@ -634,12 +692,17 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex selectedCommit.requestId(), selectedCommit.commitId(), selectedCommit.digest()); - var selection = - gd.transaction( - () -> - new AuthoredDraftPublishSelectionRepository(gd.dsl(), coordinator) - .reserve(intent) - .selection()); + var selection = gd.transaction(() -> selectionRepository.reserve(intent).selection()); + var selectionBinding = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + var accountPublicationOrder = + account.authorizePublication(selectionBinding, accountSelectionReadClient, NAMESPACE); + assertThat(accountPublicationOrder.input().selection().canonicalBytes()) + .containsExactly(selection.canonicalBytes()); + assertThat(accountPublicationOrder.operationId()).isNotEqualTo(original.operationId()); + assertThat(accountPublicationOrder.fenceId()).isNotEqualTo(original.fenceId()); + account.assertPublicationSourcesHeld(accountPublicationOrder); var intakeRequest = GameLogicIntakeAuthorizationEvidence.Request.create( NAMESPACE, UUID.randomUUID(), selection.selectedCommit()); @@ -682,34 +745,78 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(gd.dsl().fetchCount(DSL.table("game_design_selected_game_logic_receipt"))) .isOne(); - var selectorEvidence = - selectedPublicationWorldEvidence( - original, appliedWorld, selectedCommit, selection, intent, publishRequestId); - GameDesignPublicationOperation publicationOperation = - IsolatedPublicationOperationFixtures.forSelection( - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson(), selection.digest()), - selectorEvidence); - var selectedWorldSourceRequest = - new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( - 1, + var publicationAdmission = + new SelectedDraftPublicationAdmissionService( + gd.dsl(), + gd.transactions(), + gdAccountPublicationReadClient, + selectedPublicationFreezeClient, + selectedPublicationInventoryClient, + publishedStartLocationClient, + worldIntakeClient, + NAMESPACE); + var publicationReservation = + publicationAdmission.admitAndReserve(intent, accountPublicationOrder); + var exactAdmissionRetry = + publicationAdmission.admitAndReserve(intent, accountPublicationOrder); + assertThat(exactAdmissionRetry.operation().canonicalBytes()) + .containsExactly(publicationReservation.operation().canonicalBytes()); + assertThat(exactAdmissionRetry.attemptId()).isEqualTo(publicationReservation.attemptId()); + assertThat(publicationReservation.operation().account().canonicalBytes()) + .containsExactly(accountPublicationOrder.canonicalBytes()); + + var exactFreezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + selection.digest().substring("sha256:".length()), + accountPublicationOrder); + var actualFreeze = selectedPublicationFreezeClient.begin(exactFreezeRequest); + assertThat(actualFreeze.acknowledgement().publicationFence().toString()) + .isEqualTo(publicationReservation.operation().world().request().publicationFence()); + assertThat(actualFreeze.acknowledgement().appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + var changedAccountOrder = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + accountPublicationOrder.fenceId(), + accountPublicationOrder.input(), + accountPublicationOrder.sources()); + var selectedFreezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( NAMESPACE, + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + selection.digest().substring("sha256:".length()), + changedAccountOrder); + assertFailedPrecondition( + () -> selectedPublicationFreezeClient.begin(selectedFreezeRequest)); + var substitutedFreezeAcknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + actualFreeze.request(), + actualFreeze.acknowledgement().intakeRequestId(), + actualFreeze.acknowledgement().versionStateEpoch(), UUID.randomUUID(), - appliedWorld.application().operation().ownerBinding().intakeRequestId(), - gd.target().canonicalTenantId()); - var selectedWorldSourceRead = - new SourceRead( - selectedWorldSourceRequest, worldIntakeClient.readById(selectedWorldSourceRequest)); - var publicationReservation = - gd.transaction( - () -> - new SelectedDraftPublicationOwner(gd.dsl()) - .reserve( - intent, - publicationOperation.account(), - publicationOperation.world(), - publicationOperation.inventory(), - selectedWorldSourceRead)); + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + actualFreeze.acknowledgement().appliedCommitId(), + actualFreeze.acknowledgement().contentDigest(), + actualFreeze.acknowledgement().digestSchemaVersion()); + var substitutedFreeze = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + actualFreeze.request(), + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse( + substitutedFreezeAcknowledgement)); + assertFailedPrecondition(() -> selectedPublicationInventoryClient.read(substitutedFreeze)); + assertThat(world.dsl().fetchCount(DSL.table("world_design_publication_fence_attempt"))) + .isOne(); + assertThat( + world.dsl().fetchCount(DSL.table("world_selected_publication_artifact_inventory"))) + .isOne(); var retainedTemplateAssociations = new SelectedDraftTemplateWorldSourceAssociationRepository(gd.dsl()) .readExact( @@ -748,9 +855,9 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(retainedWorldDigest.appliedCommitId()) .isEqualTo(selectedCommit.commitId().toString()); assertThat(retainedWorldDigest.contentDigest()) - .isEqualTo(publicationOperation.world().request().contentDigest()); + .isEqualTo(publicationReservation.operation().world().request().contentDigest()); assertThat(retainedWorldDigest.digestSchemaVersion()) - .isEqualTo(publicationOperation.world().request().digestSchemaVersion()); + .isEqualTo(publicationReservation.operation().world().request().digestSchemaVersion()); var inventoryReader = new SelectedDraftAssetInventoryReadService(gd.dsl(), gd.transactions()); SelectedDraftAssetInventory actualInventory = inventoryReader.read(publicationRequest); @@ -984,7 +1091,7 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex gd.target().gameDesignVersionTenantKey(), gd.target().gameDesignVersionRowId()); assertThat(release.attestationSchemaVersion()).isEqualTo("v2"); assertThat(release.worldPublishedStartLocationEvidence()) - .isEqualTo(publicationOperation.world()); + .isEqualTo(publicationReservation.operation().world()); var retainedGameLogicParticipant = release.participantDigests().stream() .filter(digest -> "GAME_LOGIC".equals(digest.participantKey())) @@ -1159,10 +1266,9 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex } /** - * Entity and Automation participant rows remain stipulated test inputs. The World digest comes - * only from the retained fixture freeze; Game Design and Game Logic use their actual owner-local - * selected-source reads. This does not prove authenticated fresh World freeze admission or a - * complete four-owner publication. + * Entity and Automation participant rows remain stipulated test inputs. World freeze, inventory, + * selector and Game Design and Game Logic source reads come from their actual owner compositions. + * This does not prove complete four-owner publication or activation. */ private static List selectedSelectorParticipantDigests( DraftCommitBinding selectedCommit, @@ -1754,61 +1860,6 @@ private static WorldDesignMutationRevision.Builder mutation( .setScopeId(region.toString()); } - private static WorldPublishedStartLocationEvidence selectedPublicationWorldEvidence( - DraftAuthorizationFenceBinding original, - WorldDraftGraphAppliedResult applied, - DraftCommitBinding selectedCommit, - AuthoredDraftPublishSelection selection, - AuthoredDraftPublishSelection.PublishIntent intent, - String publishRequestId) { - var retained = applied.startLocationReceipt().orElseThrow(); - var selectorReceipt = - WorldDraftStartLocationEvidence.create( - retained.targetNamespace(), - retained.operationId(), - retained.requestId(), - retained.commitId(), - retained.authorizationFenceId(), - retained.accountBindingDigest(), - retained.bindingDigest(), - retained.startLocation(), - retained.graphDigest()) - .canonicalBytes(); - var tuples = - selectedCommit.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) - .toList(); - var request = - new WorldPublishedStartLocationEvidence.Request( - NAMESPACE, - selectedCommit.target().canonicalTenantId(), - selectedCommit.target().canonicalVersionId(), - applied.application().operation().ownerBinding().intakeRequestId(), - UUID.randomUUID(), - publishRequestId, - selection.digest().substring("sha256:".length()), - Long.parseLong(intent.expectedVersionStateEpoch()), - PublicationDigestRequestBinding.full( - selectedCommit.target().canonicalTenantId().toString(), - Long.toString(selectedCommit.target().gameDesignVersionRowId()), - publishRequestId) - .derivedWorkflowIdentity(), - selectedCommit.commitId().toString(), - retained.graphDigest(), - 3, - tuples); - return new WorldPublishedStartLocationEvidence( - request, selectorReceipt, original.canonicalBytes(), applied.canonicalBytes()); - } - private static Server startServer(TestPki pki, String service, MutableHandlerRegistry handlers) throws Exception { var identity = pki.server(service); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/GenuineWorldSelectedPublicationProofFactory.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/GenuineWorldSelectedPublicationProofFactory.java new file mode 100644 index 0000000000..9fd78a2de9 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/GenuineWorldSelectedPublicationProofFactory.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.BindableService; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.worldmanagement.repository.GenerationRuleRepository; +import net.firedevops.firemud.worldmanagement.repository.RegionRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.service.impl.WorldDraftDesignDigestServiceImpl; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import tools.jackson.databind.ObjectMapper; + +/** Test-only composition of the existing unregistered World selected-publication owners. */ +public final class GenuineWorldSelectedPublicationProofFactory { + private final BindableService freezeAndInventoryService; + private final BindableService publishedStartLocationReadService; + + public GenuineWorldSelectedPublicationProofFactory( + String workloadNamespace, + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldAuthoredSourceIntakeRepository intakeRepository, + WorldDesignPublicationFenceRepository fence, + WorldDraftGraphApplicationRepository graphApplications, + AuthoredDraftPublishSelectionReadClient selectionReadClient, + AuthoredWorldVersionStateClient versionStateClient, + AccountPublicationAuthorizationReadClient accountReadClient, + ObjectMapper objectMapper) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(transactionManager, "transactionManager"); + Objects.requireNonNull(fence, "fence"); + Objects.requireNonNull(graphApplications, "graphApplications"); + Objects.requireNonNull(intakeRepository, "intakeRepository"); + Objects.requireNonNull(objectMapper, "objectMapper"); + + var topology = new WorldDraftTopologyCommitRepository(dsl, fence, objectMapper); + var digestService = createDigestService(dsl, objectMapper); + var frozenTopologyRepository = + new WorldCanonicalFrozenTopologyRepository( + dsl, new WorldAuthoredGraphSnapshotRepository(dsl), topology, digestService); + var canonicalFrozenTopology = + new WorldCanonicalFrozenTopologyService(frozenTopologyRepository, transactionManager); + var selectorCapture = + new WorldSelectedPublicationSelectorCapture(workloadNamespace, canonicalFrozenTopology); + var authorizationRepository = new WorldSelectedDraftPublicationAuthorizationRepository(dsl); + var artifactInventoryRepository = new WorldSelectedPublicationArtifactInventoryRepository(dsl); + var freezeService = + new WorldSelectedDraftPublicationFreezeService( + workloadNamespace, + Objects.requireNonNull(selectionReadClient, "selectionReadClient"), + Objects.requireNonNull(versionStateClient, "versionStateClient"), + Objects.requireNonNull(accountReadClient, "accountReadClient"), + intakeRepository, + fence, + new WorldSelectedDraftPublicationCheckpointRepository( + fence, graphApplications, topology, digestService), + authorizationRepository, + artifactInventoryRepository, + graphApplications, + selectorCapture, + transactionManager); + var inventoryReadService = + new WorldSelectedPublicationArtifactInventoryReadService( + workloadNamespace, fence, authorizationRepository, artifactInventoryRepository); + freezeAndInventoryService = + new WorldSelectedDraftPublicationFreezeGrpcService( + freezeService, inventoryReadService, workloadNamespace); + var publishedSelectorRepository = + new WorldPublishedStartLocationRepository(dsl, frozenTopologyRepository, graphApplications); + publishedStartLocationReadService = + new WorldPublishedStartLocationReadGrpcService( + publishedSelectorRepository, workloadNamespace); + } + + public BindableService freezeAndInventoryService() { + return freezeAndInventoryService; + } + + public BindableService publishedStartLocationReadService() { + return publishedStartLocationReadService; + } + + private static WorldDraftDesignDigestService createDigestService( + DSLContext dsl, ObjectMapper objectMapper) { + return new WorldDraftDesignDigestServiceImpl( + new RegionRepository(dsl), + new ZoneRepository(dsl), + new RoomRepository(dsl), + new RoomExitRepository(dsl), + new GenerationRuleRepository(dsl), + new WorldEntitySpawnBindingRepository(dsl), + objectMapper); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java index 7961888702..2b5b65ccc9 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java @@ -47,6 +47,7 @@ final class WorldSelectedDraftPublicationFreezeService { private final WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository; private final WorldSelectedPublicationArtifactInventoryRepository artifactInventoryRepository; private final WorldDraftGraphApplicationRepository graphApplicationRepository; + private final WorldSelectedPublicationSelectorCapture selectorCapture; private final TransactionTemplate ownerTransaction; WorldSelectedDraftPublicationFreezeService( @@ -71,6 +72,7 @@ final class WorldSelectedDraftPublicationFreezeService { authorizationRepository, artifactInventoryRepository, null, + null, transactionManager); } @@ -85,6 +87,7 @@ final class WorldSelectedDraftPublicationFreezeService { WorldSelectedDraftPublicationAuthorizationRepository authorizationRepository, WorldSelectedPublicationArtifactInventoryRepository artifactInventoryRepository, WorldDraftGraphApplicationRepository graphApplicationRepository, + WorldSelectedPublicationSelectorCapture selectorCapture, PlatformTransactionManager transactionManager) { if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { throw new IllegalArgumentException("World workload namespace is invalid"); @@ -101,7 +104,12 @@ final class WorldSelectedDraftPublicationFreezeService { Objects.requireNonNull(authorizationRepository, "authorizationRepository"); this.artifactInventoryRepository = Objects.requireNonNull(artifactInventoryRepository, "artifactInventoryRepository"); + if ((graphApplicationRepository == null) != (selectorCapture == null)) { + throw new IllegalArgumentException( + "World selected-publication begin requires both APPLIED resolution and selector capture"); + } this.graphApplicationRepository = graphApplicationRepository; + this.selectorCapture = selectorCapture; this.ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); @@ -112,8 +120,9 @@ final class WorldSelectedDraftPublicationFreezeService { * Owner-resolves the exact selected APPLIED graph before deriving private World freeze evidence. * *

The caller supplies no plan or private World identity. A committed retry resolves the same - * immutable APPLIED carrier, then returns the retained freeze and Account correlation before any - * mutable Game Design or Account remote read is repeated. + * immutable APPLIED carrier, then replays the retained freeze and Account correlation before any + * mutable Game Design or Account remote read is repeated. The canonical selector is captured only + * after the exact committed freeze readback succeeds. */ Acknowledgement begin(Request request) { requireAuthenticatedGameDesignCaller(); @@ -123,9 +132,9 @@ Acknowledgement begin(Request request) { throw new SecurityException( "World selected-publication freeze target namespace differs from this workload"); } - if (graphApplicationRepository == null) { + if (graphApplicationRepository == null || selectorCapture == null) { throw new IllegalStateException( - "World selected-publication freeze requires its committed APPLIED resolver"); + "World selected-publication begin requires committed APPLIED resolution and selector capture"); } AccountPublicationAuthorizationBinding accountBinding = request.accountBinding(); @@ -183,15 +192,18 @@ Acknowledgement begin(Request request) { request.publicationRequestId()) .derivedWorkflowIdentity()); FrozenAttempt attempt = freeze(evidence, selectedPlan, accountBinding); - return new Acknowledgement( - request, - owner.intakeRequestId(), - attempt.request().versionStateEpoch(), - attempt.publicationFence(), - OwnerFreezePhase.FROZEN, - attempt.checkpoint().appliedCommitId(), - attempt.checkpoint().contentDigest(), - attempt.checkpoint().digestSchemaVersion()); + Acknowledgement acknowledgement = + new Acknowledgement( + request, + owner.intakeRequestId(), + attempt.request().versionStateEpoch(), + attempt.publicationFence(), + OwnerFreezePhase.FROZEN, + attempt.checkpoint().appliedCommitId(), + attempt.checkpoint().contentDigest(), + attempt.checkpoint().digestSchemaVersion()); + selectorCapture.capture(application, acknowledgement); + return acknowledgement; } /** diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCapture.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCapture.java new file mode 100644 index 0000000000..c2d6cee814 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCapture.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; + +/** Owner-local selector capture for one exact committed selected-publication freeze. */ +final class WorldSelectedPublicationSelectorCapture { + private final String workloadNamespace; + private final WorldCanonicalFrozenTopologyService canonicalFrozenTopology; + + WorldSelectedPublicationSelectorCapture( + String workloadNamespace, WorldCanonicalFrozenTopologyService canonicalFrozenTopology) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.canonicalFrozenTopology = + Objects.requireNonNull(canonicalFrozenTopology, "canonicalFrozenTopology"); + } + + /** + * Captures through WorldCanonicalFrozenTopologyService.capture() from the exact owner records. + */ + WorldCanonicalFrozenTopology capture( + WorldDraftGraphApplication application, Acknowledgement acknowledgement) { + Objects.requireNonNull(application, "application"); + Objects.requireNonNull(acknowledgement, "acknowledgement"); + var request = acknowledgement.request(); + var accountBinding = request.accountBinding(); + var selection = accountBinding.input().selection(); + var plan = application.plan(); + var operation = application.operation(); + var binding = plan.binding(); + var owner = operation.ownerBinding(); + if (!workloadNamespace.equals(request.targetNamespace()) + || !workloadNamespace.equals(owner.targetNamespace()) + || !plan.ownerBinding().equals(owner) + || !selection.selectedCommit().equals(binding) + || !Arrays.equals(selection.selectedCommit().canonicalBytes(), binding.canonicalBytes()) + || !operation.binding().equals(binding) + || !Arrays.equals(operation.binding().canonicalBytes(), binding.canonicalBytes()) + || !operation.commitId().equals(binding.commitId()) + || !request.canonicalTenantId().equals(operation.canonicalTenantId()) + || !request.canonicalVersionId().equals(operation.canonicalVersionId()) + || !request.canonicalTenantId().equals(owner.canonicalTenantId()) + || !request.canonicalVersionId().equals(owner.canonicalVersionId()) + || selection.target().gameDesignVersionRowId() != owner.gameDesignVersionId() + || !acknowledgement.intakeRequestId().equals(owner.intakeRequestId()) + || !acknowledgement.appliedCommitId().equals(binding.commitId().toString()) + || acknowledgement.versionStateEpoch() != request.expectedVersionStateEpoch() + || !plan.graph().freshGraphDeclaration().isPresent()) { + throw conflict( + "Committed World freeze differs from the exact retained selected APPLIED application"); + } + + var tuples = + binding.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var captureRequest = + new CaptureRequest( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + acknowledgement.intakeRequestId(), + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + acknowledgement.versionStateEpoch(), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(binding.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity(), + acknowledgement.appliedCommitId(), + acknowledgement.contentDigest(), + acknowledgement.digestSchemaVersion(), + tuples); + return canonicalFrozenTopology.capture( + new WorldCanonicalFrozenTopology.Request(plan, captureRequest)); + } + + private static ConflictException conflict(String message) { + return new ConflictException(message); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 6459dd886f..6e42ab93c8 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -1529,6 +1529,9 @@ private WorldSelectedDraftPublicationFreezeService selectedPublicationFreezeServ AuthoredDraftPublishSelectionReadClient selectionRead, AuthoredWorldVersionStateClient versionStateRead, AccountPublicationAuthorizationReadClient accountRead) { + var selectorCapture = + new WorldSelectedPublicationSelectorCapture( + NAMESPACE, new WorldCanonicalFrozenTopologyService(frozenRepository(), manager)); return new WorldSelectedDraftPublicationFreezeService( NAMESPACE, selectionRead, @@ -1540,6 +1543,7 @@ private WorldSelectedDraftPublicationFreezeService selectedPublicationFreezeServ publicationAuthorizationRepository(), artifactInventoryRepository(), appliedRepository(), + selectorCapture, manager); } diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java index 54c58c4817..0f9bbcac08 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeRequestTest.java @@ -3,9 +3,11 @@ 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.doAnswer; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -14,6 +16,7 @@ import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; @@ -95,7 +98,8 @@ void ownerResolvesAppliedBeforeExactRetryAndRetrySkipsMutableRemoteReads() { collaborators.applications, collaborators.fence, collaborators.authorizationRepository, - collaborators.artifactInventoryRepository); + collaborators.artifactInventoryRepository, + collaborators.selectorCapture); order .verify(collaborators.applications) .readSelectedPublicationApplication(NAMESPACE, TENANT, VERSION, fixture.selection()); @@ -104,6 +108,7 @@ void ownerResolvesAppliedBeforeExactRetryAndRetrySkipsMutableRemoteReads() { order .verify(collaborators.artifactInventoryRepository) .readCommitted(prior, fixture.accountBinding()); + order.verify(collaborators.selectorCapture).capture(fixture.application(), acknowledgement); verifyNoInteractions( collaborators.selectionClient, collaborators.versionStateClient, @@ -132,7 +137,8 @@ void missingAppliedSelectionIsDeniedBeforeFreezeHistoryOrRemoteReads() { collaborators.versionStateClient, collaborators.accountClient, collaborators.authorizationRepository, - collaborators.checkpointRepository); + collaborators.checkpointRepository, + collaborators.selectorCapture); assertThat(collaborators.transactionManager.commits).isZero(); } @@ -172,6 +178,75 @@ void exactSelectionRetryCannotAttachChangedAccountOrder() { collaborators.versionStateClient, collaborators.accountClient); verify(collaborators.fence, never()).claimFreeze(any(), any()); + verify(collaborators.selectorCapture, never()).capture(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void committedFreezeCaptureFailureRetriesWithoutFreshMutableAuthorityReads() { + Fixture fixture = fixture(); + Collaborators collaborators = new Collaborators(); + FrozenAttempt prior = frozen(fixture.evidence(), fixture.binding()); + when(collaborators.applications.readSelectedPublicationApplication( + NAMESPACE, TENANT, VERSION, fixture.selection())) + .thenReturn(Optional.of(fixture.application())); + when(collaborators.fence.readAttempt(fixture.evidence())).thenReturn(Optional.of(prior)); + when(collaborators.authorizationRepository.readCommitted(prior)) + .thenReturn(Optional.of(fixture.accountBinding())); + var captureCalls = new AtomicInteger(); + var unavailable = + new WorldDesignPublicationFenceRepository.ConflictException( + "canonical selector capture is temporarily unavailable"); + doAnswer( + invocation -> { + if (captureCalls.getAndIncrement() == 0) throw unavailable; + return null; + }) + .when(collaborators.selectorCapture) + .capture(any(), any()); + var service = service(fixture, collaborators); + + assertThatThrownBy(() -> withGameDesign(() -> service.begin(fixture.request()))) + .isSameAs(unavailable); + var acknowledgement = withGameDesign(() -> service.begin(fixture.request())); + + assertThat(acknowledgement.publicationFence()).isEqualTo(prior.publicationFence()); + assertThat(acknowledgement.appliedCommitId()) + .isEqualTo(fixture.binding().commitId().toString()); + verify(collaborators.fence, times(2)).readAttempt(fixture.evidence()); + verify(collaborators.selectorCapture, times(2)).capture(any(), any()); + verifyNoInteractions( + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient, + collaborators.intakeRepository, + collaborators.checkpointRepository); + verify(collaborators.fence, never()).claimFreeze(any(), any()); + assertThat(collaborators.transactionManager.commits).isZero(); + } + + @Test + void freezeOnlyPrimitiveCannotBeginWithoutAppliedResolverAndSelectorCapture() { + Fixture fixture = fixture(); + Collaborators collaborators = new Collaborators(); + var service = + new WorldSelectedDraftPublicationFreezeService( + NAMESPACE, + collaborators.selectionClient, + collaborators.versionStateClient, + collaborators.accountClient, + collaborators.intakeRepository, + collaborators.fence, + collaborators.checkpointRepository, + collaborators.authorizationRepository, + collaborators.artifactInventoryRepository, + collaborators.transactionManager); + + assertThatThrownBy(() -> withGameDesign(() -> service.begin(fixture.request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("APPLIED resolution and selector capture"); + + collaborators.verifyNoReadsOrWrites(); assertThat(collaborators.transactionManager.commits).isZero(); } @@ -188,6 +263,7 @@ private static WorldSelectedDraftPublicationFreezeService service( collaborators.authorizationRepository, collaborators.artifactInventoryRepository, collaborators.applications, + collaborators.selectorCapture, collaborators.transactionManager); } @@ -276,6 +352,7 @@ TENANT, VERSION, uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd")), List.of()))); var operation = mock(WorldDraftTerminalOperation.class); when(operation.binding()).thenReturn(binding); + when(operation.commitId()).thenReturn(commitId); when(operation.ownerBinding()).thenReturn(owner); when(operation.canonicalTenantId()).thenReturn(TENANT); when(operation.canonicalVersionId()).thenReturn(VERSION); @@ -387,6 +464,8 @@ private static final class Collaborators { mock(WorldSelectedPublicationArtifactInventoryRepository.class); final WorldDraftGraphApplicationRepository applications = mock(WorldDraftGraphApplicationRepository.class); + final WorldSelectedPublicationSelectorCapture selectorCapture = + mock(WorldSelectedPublicationSelectorCapture.class); final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); void verifyNoReadsOrWrites() { @@ -399,7 +478,8 @@ void verifyNoReadsOrWrites() { checkpointRepository, authorizationRepository, artifactInventoryRepository, - applications); + applications, + selectorCapture); } } diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCaptureTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCaptureTest.java new file mode 100644 index 0000000000..92906dc4c5 --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCaptureTest.java @@ -0,0 +1,96 @@ +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.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class WorldSelectedPublicationSelectorCaptureTest { + private static final String NAMESPACE = "firemud"; + private static final UUID FENCE = UUID.fromString("abababab-abab-4bab-8bab-abababababab"); + + @Test + void capturesExactFenceCheckpointAndTuplesFromRetainedApplicationAndAcknowledgement() { + var fixture = WorldSelectedDraftPublicationFreezeRequestTest.fixture(); + var acknowledgement = acknowledgement(fixture, fixture.owner().intakeRequestId()); + var canonicalFrozenTopology = mock(WorldCanonicalFrozenTopologyService.class); + var capture = new WorldSelectedPublicationSelectorCapture(NAMESPACE, canonicalFrozenTopology); + + capture.capture(fixture.application(), acknowledgement); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(WorldCanonicalFrozenTopology.Request.class); + verify(canonicalFrozenTopology).capture(requestCaptor.capture()); + var request = requestCaptor.getValue(); + var frozen = request.freeze(); + assertThat(request.plan()).isSameAs(fixture.application().plan()); + assertThat(frozen.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(frozen.canonicalTenantId()).isEqualTo(fixture.request().canonicalTenantId()); + assertThat(frozen.canonicalVersionId()).isEqualTo(fixture.request().canonicalVersionId()); + assertThat(frozen.intakeRequestId()).isEqualTo(acknowledgement.intakeRequestId()); + assertThat(frozen.publicationFence()).isEqualTo(acknowledgement.publicationFence()); + assertThat(frozen.publicationRequestId()).isEqualTo(fixture.request().publicationRequestId()); + assertThat(frozen.requestDigest()).isEqualTo(fixture.request().requestDigest()); + assertThat(frozen.versionStateEpoch()).isEqualTo(acknowledgement.versionStateEpoch()); + assertThat(frozen.publishWorkflowId()) + .isEqualTo( + PublicationDigestRequestBinding.full( + fixture.request().canonicalTenantId().toString(), + Long.toString(fixture.binding().target().gameDesignVersionRowId()), + fixture.request().publicationRequestId()) + .derivedWorkflowIdentity()); + assertThat(frozen.appliedCommitId()).isEqualTo(acknowledgement.appliedCommitId()); + assertThat(frozen.contentDigest()).isEqualTo(acknowledgement.contentDigest()); + assertThat(frozen.digestSchemaVersion()).isEqualTo(acknowledgement.digestSchemaVersion()); + var expectedTuples = + fixture.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + assertThat(frozen.suppliedOwnedAffectedTuples()).containsExactlyElementsOf(expectedTuples); + } + + @Test + void changedOwnerIntakeCorrelationIsRejectedBeforeCanonicalCapture() { + var fixture = WorldSelectedDraftPublicationFreezeRequestTest.fixture(); + var acknowledgement = + acknowledgement(fixture, UUID.fromString("cdcdcdcd-cdcd-4dcd-8dcd-cdcdcdcdcdcd")); + var canonicalFrozenTopology = mock(WorldCanonicalFrozenTopologyService.class); + var capture = new WorldSelectedPublicationSelectorCapture(NAMESPACE, canonicalFrozenTopology); + + assertThatThrownBy(() -> capture.capture(fixture.application(), acknowledgement)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("retained selected APPLIED application"); + + verifyNoInteractions(canonicalFrozenTopology); + } + + private static WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement acknowledgement( + WorldSelectedDraftPublicationFreezeRequestTest.Fixture fixture, UUID intakeRequestId) { + return new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + fixture.request(), + intakeRequestId, + fixture.request().expectedVersionStateEpoch(), + FENCE, + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + fixture.binding().commitId().toString(), + "a".repeat(64), + 3); + } +} From f580093d113630e8335c301a7ecb31d6a4bf4acd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:24:58 +1300 Subject: [PATCH 055/129] Retain authored owner inventory and original World delivery evidence --- .../runtime-and-data.md | 23 ++ .../runtime-and-data.md | 10 + .../game-design-service/game-templates.md | 2 + ...ame-authoring-publishing-and-activation.md | 4 + ...ionAuthoredSourceInventoryDeclaration.java | 145 +++++++ ...ityAuthoredSourceInventoryDeclaration.java | 174 +++++++++ ...uthoredSourceInventoryDeclarationTest.java | 119 ++++++ ...uthoredSourceInventoryDeclarationTest.java | 146 +++++++ ...ConfigOwnerSourceInventoryDeclaration.java | 69 ++++ .../publication/TemplateConfigSource.java | 149 ++++++- .../TemplateConfigSourceRepository.java | 186 ++++++++- .../TemplateConfigSourceSnapshot.java | 115 ++++-- ...template_config_owner_source_inventory.sql | 365 ++++++++++++++++++ ...teConfigSourcePostgresIntegrationTest.java | 150 +++++++ ...licationExportPostgresIntegrationTest.java | 294 +++++++++++++- .../publication/TemplateConfigSourceTest.java | 118 ++++++ 16 files changed, 1996 insertions(+), 73 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclaration.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclaration.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclarationTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclarationTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V67__template_config_owner_source_inventory.sql diff --git a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md index 0048d2555f..12a6292a05 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -39,6 +39,29 @@ The current dry-run and readiness capacity reservations also are not idempotent The current queue consumer has an additional bounded-drain limitation that must remain explicit: `drainWorkItems` and `drainIndexedWorkItemPointers` consume pointers with atomic Redis `LPOP`, so a producer's concurrent `RPUSH` is not discarded by a range/read followed by deletion. The indexed path still uses database-wide `KEYS("automation:queue:*")`, and the current lists have no pointer TTL or maximum-length bound, so the path is not a cluster-safe discovery or retention proof. Durable claim fallback can process pending PostgreSQL rows independently, but it does not establish a reset/rebuild recovery gate. Target enqueue/rebuild must atomically apply `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`, preserve or durably account for unreturned tails and concurrent appends, use an owner-maintained/cursor-based cluster-safe queue index rather than database-wide `KEYS`, and trigger bounded durable re-drive with exact identity/readback before reset-gate release. The two settings remain environment/service configuration (currently `TBD`); no target support claim is valid until each environment supplies validated positive bounds and focused concurrent-drain, truncation/expiry, cluster, and re-drive proof. +## Authored Template Source Inventory + +Automation owns the source inventory declaration schema carried as authored content by a new versioned Game Design `TEMPLATE_CONFIG` source ([closed schema and reference rules](../game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state)). The Automation value schema is `automation-authored-source-inventory/v1` with exactly three required family arrays: `SCRIPT_DEFINITIONS`, `EVENT_BINDINGS`, and `SCRIPT_PATCH_SOURCES`. The current shared value accepts only explicitly authored empty arrays; omitted, null, unknown, malformed, duplicate, trailing, oversized, or nonempty input is rejected. Its canonical RFC 8785 bytes preserve the authored declaration deterministically. This declaration is content only: it is not an owner receipt, source readback, authorization, provenance, or proof of owner completeness, and cannot qualify a publication on its own. Existing `TEMPLATE_CONFIG` schema-version content is not reinterpreted as this declaration. + +The authored shape is: + +```json +{ + "schema": "automation-authored-source-inventory/v1", + "families": { + "SCRIPT_DEFINITIONS": [], + "EVENT_BINDINGS": [], + "SCRIPT_PATCH_SOURCES": [] + } +} +``` + +Script schedule definitions remain derived from script source and are not another authored family. The optional template `automation.scriptPatch` is a separate default selection of one exact patch for the same base version; its absence means no template default and does not establish an empty patch-source inventory. The declaration producer, Automation owner intake/readback, and physical proof remain incomplete; publication must continue to deny where that evidence is unavailable. + +An Automation selected-source intake is a distinct Account-authorized operation, not participation inferred from a Game Design-only commit. Account must first authorize the exact immutable source read; after the read, Automation must retain the original content and outcome while holding revalidated current Account authority through its local commit. The declaration must originate in a genuine authored revision of the exact selected Game Design commit. Its inventory covers script roots, every event binding and patch source, and all dependent or inbound behavior/hook references from the complete selected World and other authored inputs. An explicit empty declaration is supported only when authenticated owner evidence closes that whole selected input set and rejects conflicting or unqualified existing content. Missing producers, omitted families, unavailable rows and a tenant-wide script query are not absence proof; an unsupported nonempty input denies instead of being discarded. + +The immutable intake result retains the canonical tenant/version and selected commit, original source revision and operation, complete inventory bytes, exact Account authorization binding, original owner terminal and their digests. The result and authenticated readback are derived after the authored source commit, outside its preimage. An identical retry reads the original result; changed scope, selection, content or authorization binding conflicts rather than manufacturing a new receipt. A workload identity, creator declaration or matching digest alone is insufficient. Until the required selected-input producers and held-authority proof exist, the owner receipt remains unavailable and publication must not substitute an empty or synthetic version marker. + ## Architecture and Design Notes - Executes scripts in response to world or player events received via gRPC callbacks from Game Session and other domain services. Standard lifecycle events (`onSpawn`, `onEnterRegion`, `onCommand`, and similar) are delivered as unary gRPC calls via `TriggerScriptEvent`, while tick-derived scheduling signals are driven by a gRPC streaming tick heartbeat originating from Game Session. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index b9eaa2b9eb..6ac3196dc7 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -57,6 +57,16 @@ Entity Management maintains a clear separation between template/design data and Template identifiers are stable within each version: a given template ID must not be repurposed to represent a different conceptual entity while any non-Retired version still references it. When switching a game instance to a new `runtime_version`, the Game Session Service and Entity Management treat missing or incompatible templates as a fatal configuration error for that launch; the version selection must be corrected rather than silently substituting defaults or partial data. +### Selected Entity Authored Source Inventory (Empty-Only v1) + +The versioned `TEMPLATE_CONFIG` source must carry an explicitly authored, empty-only Entity inventory declaration for this supported subset. This is creator-authored content, not an assertion that Entity has no rows, an owner readback, authorization, source provenance, or a publication receipt. Publication still requires the distinct Account authorization, exact immutable Game Design selected-source read, held revalidation through retention commit, and the complete selected World population/item/loot/behavior/hook closure and original receipt. Missing or unavailable evidence denies publication; this declaration manufactures none of it. + +`EntityAuthoredSourceInventoryDeclaration` accepts the exact closed `entity-authored-source-inventory/v1` shape: `schema`, `equipmentApplicability: "NOT_APPLICABLE"`, and `families` containing every required family below as an explicit empty array. Unknown, missing, null, malformed, duplicate, conflicting, oversized, or nonempty input is rejected. Nonempty entity definitions remain unsupported by this declaration; an unsupported family is never treated as empty. Legacy `inventoryEnabled=false`, a `DEFAULT` body layout, an absent table, or an omitted config member cannot establish equipment non-applicability or source absence. + +The complete required family coverage is `ITEM_TEMPLATE_ROOTS`, `NPC_TEMPLATE_ROOTS`, `OTHER_ACTOR_TEMPLATE_ROOTS`, `CRAFTING_RECIPE_ROOTS`, `CRAFTING_RECIPE_RESULT_BINDINGS`, `CRAFTING_INGREDIENT_BINDINGS`, `EQUIPMENT_CAPABILITIES`, `EQUIPMENT_SLOT_ROOTS`, `EQUIPMENT_SLOT_GROUPS`, `EQUIPMENT_ATTACHMENT_RULES`, `EQUIPMENT_COMPATIBILITY_RULES`, `EQUIPMENT_OCCUPANCY_RULES`, `BODY_LAYOUT_ROOTS`, `BODY_LAYOUT_MEMBERSHIPS`, `ACTOR_BODY_LAYOUT_ASSIGNMENTS`, `LOOT_TABLE_ROOTS`, `LOOT_ITEM_MAPPINGS`, `INBOUND_LOOT_BINDINGS`, `BALANCE_CURVE_ROOTS`, `BALANCE_CURVE_ATTACHMENTS`, `ARCHETYPE_ROOTS`, `ARCHETYPE_CONSTRAINTS`, and `ARCHETYPE_ASSIGNMENTS`. These family names close the empty declaration only; they do not define nonempty identifiers or element grammars. In particular, there is no separate equipment-template identity: equipment remains item-owned, while equipment bindings are separate runtime state. + +This empty-only declaration is a valid authored claim only when it is present in a genuinely new versioned source and survives the authorized commit/application/snapshot path. It must be read back exactly from the selected source and revalidated while held through retention commit. Its presence alone does not prove that the selected Entity source, selected World graph, or their inbound references are empty or complete. Existing `TEMPLATE_CONFIG` v1 item/NPC references are not reinterpreted or backfilled as this declaration. See [ADR 0127](../../decisions/adr-0127-game-authored-equipment-layouts-with-fail-closed-publication.md) for equipment applicability and complete-schema requirements. + ### Target-State Replacement-Instance State Classification Entity Management must classify its runtime persistence surface for cutover and migration tooling: diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 7940d77b04..10d6a3f7b2 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -63,6 +63,8 @@ World `regions[]` entries carry `regionTemplateId`; `rooms[]` carry `roomTemplat Automation's supported template sources are `SCRIPT` (including its owner-managed event bindings) and `SCRIPT_PATCH`; it has no `RULESET` identity. A script reference carries the current exact owner key `scriptId` (the persisted `name` string) under the template's selected tenant/base-version scope. The optional pinned `scriptPatchVersion` is the exact persisted nonblank patch string, paired with the same `baseVersionId`; it is not a UUID. These raw strings describe current owner keys, not proof of same-base publication or exact selected-version readback. The [Automation runtime/data contract](../automation-scripting-service/runtime-and-data.md) and [API contract](../automation-scripting-service/api-contracts.md) own script identity and patch semantics. Current code does not establish the canonical-UUID-to-owner-version binding or all required publication/readiness predicates; unsupported or unreadable entries deny selected-release completeness rather than implying an empty script family. +Automation's authored source inventory is a separate versioned `TEMPLATE_CONFIG` source operation, `DECLARE_OWNER_SOURCE_INVENTORY`, bound to the actual Draft commit. The revision remains owned by `GAME_DESIGN_CONTROL_PLANE`; its `AUTOMATION_SCRIPTING` declaration identifies the content owner, not an Automation commit participant. It carries no `templateId` and creates no `game_templates` row. Game Design retains its original request, commit, revision ID/order, content owner, and binding provenance in template source snapshot v2 and publication capture. The declaration remains authored content only; absence is unavailable evidence, and the declaration does not replace Automation owner readback or qualify publication. Its family schema and empty-only acceptance are owned by [Automation](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory). + Game Logic owns the version-scoped gameplay rules/configuration, not Automation. The authored `gameLogic.inputs[]` entries select Game Design-owned gameplay inputs by exact `{family, key, revisionId}` from the supported authored gameplay source families. They do not serialize Game Logic's derived receipt or invent per-rule IDs. For publication, Game Logic's genuine owner-retained receipt must be independently joined to the exact unchanged tenant, `baseVersionId`, and selected commit after source settlement and authorized intake. A missing receipt, changed input or commit, or merely latest receipt cannot satisfy the join; exact retries recover the original retained result. [Game Logic runtime/data](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) defines the owner boundary and receipt semantics; this document does not define a receipt schema. Retaining and resolving authored input references does not establish that separate receipt or join, so no complete publishable config is claimed yet. `supportedSettings` is the explicitly non-authoritative settings subset accepted by this schema; it is closed and owner-defined, not arbitrary runtime configuration. No concrete non-authoritative setting members are currently registered. An explicitly authored empty collection is representable, but still requires the same authorized source-creation, selected-commit history and durable readback proof; missing settings storage or producers cannot supply it. `defaultRuntimeFlagsJson` and any other setting that changes launch/runtime behavior are authoritative inputs, not presentation settings, and must not be placed in this subset or marked optional. Adding a supported setting requires its owner, exact accepted member/value schema, and absence/fallback semantics to be defined before it can be authored. 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 4fd55fbbc6..8df3db0c3d 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Published `97174b31be2ed08440be1a271cc00359614abaf6` [Validation run 37945686843](https://github.com/benhook1013/FireMUD/actions/runs/37945686843) executed 254 Account and 207 World PostgreSQL cases with no failures, errors or skips. Both previously failing Account receipt-confirmation fixtures passed with the production V90/V92 guards and original acknowledgement bounds unchanged. Game Design executed 146 PostgreSQL cases with one failure and no errors or skips: the genuine export fixture invented a new World intake request ID instead of using the original durable Game Design delivery claim. The local correction uses that original request, World’s actual receipt and Game Design’s actual acknowledgement, without weakening the selected-source readback guard. Separate legacy descriptor (8), complete launch-binding (6), and genuine GD+World source-settlement (3) cases passed; they do not establish success of the failed genuine export. The actual CI checkout is synthetic merge `421b0196ccffff96405aab1c687d2455c52ede60`, tree `62188ebd390fdd8d4ed71d4a245c5195a30eae3a`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact published source, not the intended integration parent. + +The current source-inventory batch adds an actual authored Automation `TEMPLATE_CONFIG` revision, immutable original revision provenance and snapshot v2; it creates no template row or Automation commit participation. Entity's mandatory 23-family empty-only declaration and explicit equipment non-applicability have a shared parser and canonical owner contract, but are not yet integrated into the Game Design source operation. Common's full check executes 457 unit cases successfully. Game Design's schema generation, affected full check, boot JAR and documentation validation pass in 1m 40s with 524 unit cases executed; all 145 local integration cases compile/discover but skip without Docker. The new declaration migration and source/retry/inheritance cases therefore have no physical PostgreSQL proof yet. Neither declaration is an owner receipt. Separate Entity/Automation Account-authorized intake, held current-authority retention, and authenticated full selected World/inbound closure remain missing. World's exact frozen six-family topology inventory exposes typed ITEM/NPC spawn inputs, but does not supply the required selected loot/behavior/hook closure; a zero topology count cannot certify those missing producers. The genuine fixture also adds exact owner-local complete-launch-binding readback and substitution/no-mutation assertions; it does not exercise the authenticated transport or enable launch. All four Gameplay handoffs and activation remain open. + Published `9f287e05e06b87adc3db79984b2e047e5d5b819f` [Validation run 37939078493](https://github.com/benhook1013/FireMUD/actions/runs/37939078493) executed 146 Game Design PostgreSQL cases with one failure, 254 Account cases with one failure, and 207 World cases with no failures; all three suites report zero skips and errors. The three genuine GD+World source/settlement cases, genuine Game Logic intake case, approved-remap retention correction and eight legacy descriptor persistence/retry/migration cases passed. The genuine selected export/descriptor case failed before export because its stipulated World evidence supplied a prefixed content hash to a bare-hex field. Since that run, the local construction has replaced the stipulated Account publication-order and World freeze/inventory/selector evidence with the actual owner reads and adds canonical topology capture after freeze. This new composition has no physical proof yet. Account's failure moved to the physical-confirmation/independent-read case and again denied at V90's conservative coverage prerequisite: insert `0/7EDFE48` exceeded initial/final flush `0/7EDFE08` while the original bound remained unchanged. A bounded fixture diagnosis is separate from source/release construction. Overseer deferred production WAL-locator adoption; the prototype, original JVM acknowledgement/time bounds, V90/V92 recovery semantics and PostgreSQL-version guards remain unchanged. The actual synthetic checkout is `1822fbae8dc9f6c4409ccc9515a99ee5e5f42e99`, tree `dc3142f6c4284288a43ed71d97632c35ee4afe09`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published source. This is exact-source execution, not intended-parent alignment, a genuine complete release or activation. The bounded GD+World source/APPLIED/original terminal-settlement path has executed PostgreSQL proof, including lost acknowledgement and unknown-outcome recovery, as recorded below. Later construction adds fresh creation-receipt-backed normalized template phase, immutable selected export candidates with actual-byte object readback, the closed Account-gated Game Session association read and exact descriptor projection. The corrected local World/Game Design gate passes full checks, formatting, Checkstyle, SpotBugs, coverage and both boot JARs in 2m 7s, with 585 World unit cases executed and 522 unchanged Game Design unit results reused. All 207 World and 143 Game Design integration cases compile/discover but skip without Docker. Account's separate full check passes in 2m 11s with 1,109 unit cases executed; its integration reports contain seven executed non-container cases and 239 skips. This includes a test-only coordinator for the two affected V90 confirmation fixtures: it observes the actual backend's coverage wait, then commits and independently reads one synchronous logged marker without changing production guards or original expiry bounds. Corrected-head physical confirmation and descriptor/export composition remain unproved. V66 passes schema generation and the originating physical candidate-suite migration proof below, not successful descriptor creation/readback. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclaration.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclaration.java new file mode 100644 index 0000000000..aecb1ad178 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclaration.java @@ -0,0 +1,145 @@ +package net.firedevops.firemud.common.automation; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Explicit empty-only authored Automation source inventory for the versioned Game Design config. + * + *

This value is authored content only. It is not owner readback, authorization, provenance, a + * receipt, or proof that an Automation owner has no source rows. A separate authorized owner intake + * and immutable readback must establish those facts before publication can use them. + */ +public final class AutomationAuthoredSourceInventoryDeclaration { + public static final String SCHEMA = "automation-authored-source-inventory/v1"; + public static final int MAX_JSON_BYTES = 4 * 1024; + + private static final Set ROOT_FIELDS = Set.of("schema", "families"); + private static final List FAMILY_ORDER = + List.of("SCRIPT_DEFINITIONS", "EVENT_BINDINGS", "SCRIPT_PATCH_SOURCES"); + private static final Set FAMILY_FIELDS = Set.copyOf(FAMILY_ORDER); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final byte[] canonicalBytes; + + private AutomationAuthoredSourceInventoryDeclaration(byte[] canonicalBytes) { + this.canonicalBytes = canonicalBytes.clone(); + } + + /** + * Parses explicitly authored inventory content, accepting only its exact empty-only v1 form. + * Nonempty families are rejected as unsupported rather than interpreted as empty. + */ + public static AutomationAuthoredSourceInventoryDeclaration parse(String authoredJson) { + if (authoredJson == null) { + throw new IllegalArgumentException("Automation source inventory declaration is required"); + } + validateBoundedUtf8(authoredJson); + + final JsonNode root; + try { + root = JSON.readTree(authoredJson); + } catch (RuntimeException invalidJson) { + throw new IllegalArgumentException( + "Automation source inventory declaration is not valid closed JSON", invalidJson); + } + requireObjectFields(root, ROOT_FIELDS, "declaration"); + JsonNode schema = root.get("schema"); + if (schema == null || !schema.isTextual() || !SCHEMA.equals(schema.textValue())) { + throw new IllegalArgumentException("Unsupported Automation source inventory schema"); + } + + JsonNode families = root.get("families"); + requireObjectFields(families, FAMILY_FIELDS, "families"); + for (String family : FAMILY_ORDER) { + JsonNode entries = families.get(family); + if (entries == null || !entries.isArray()) { + throw new IllegalArgumentException("Automation source family must be an array: " + family); + } + if (entries.size() != 0) { + throw new IllegalArgumentException( + "Nonempty Automation source family is unsupported: " + family); + } + } + + try { + return new AutomationAuthoredSourceInventoryDeclaration( + Rfc8785CanonicalJson.canonicalizeUtf8(authoredJson)); + } catch (IOException invalidCanonicalJson) { + throw new IllegalArgumentException( + "Automation source inventory declaration could not be canonicalized", + invalidCanonicalJson); + } + } + + /** Returns the exact deterministic RFC 8785 JSON text retained by this value. */ + public String canonicalJson() { + return new String(canonicalBytes, StandardCharsets.UTF_8); + } + + /** Returns a defensive copy of the exact deterministic RFC 8785 bytes. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof AutomationAuthoredSourceInventoryDeclaration declaration + && Arrays.equals(canonicalBytes, declaration.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + private static void validateBoundedUtf8(String value) { + if (value.length() > MAX_JSON_BYTES) { + throw new IllegalArgumentException("Automation source inventory declaration is too large"); + } + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + if (encoded.remaining() > MAX_JSON_BYTES) { + throw new IllegalArgumentException("Automation source inventory declaration is too large"); + } + } catch (CharacterCodingException invalidUnicode) { + throw new IllegalArgumentException( + "Automation source inventory declaration contains malformed Unicode", invalidUnicode); + } + } + + private static void requireObjectFields(JsonNode value, Set expected, String name) { + if (value == null || !value.isObject()) { + throw new IllegalArgumentException( + "Automation source inventory " + name + " must be an object"); + } + Set actual = new HashSet<>(); + value.properties().forEach(property -> actual.add(property.getKey())); + if (!actual.equals(expected)) { + throw new IllegalArgumentException( + "Automation source inventory " + name + " has missing or unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclaration.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclaration.java new file mode 100644 index 0000000000..03e8ed1b34 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclaration.java @@ -0,0 +1,174 @@ +package net.firedevops.firemud.common.entity; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Explicit empty-only authored Entity source inventory for the versioned Game Design config. + * + *

This value is authored content only. It is not owner readback, authorization, provenance, a + * receipt, or proof that Entity has no source rows. A separate authorized owner intake and + * immutable readback must establish those facts before publication can use them. + */ +public final class EntityAuthoredSourceInventoryDeclaration { + public static final String SCHEMA = "entity-authored-source-inventory/v1"; + public static final int MAX_JSON_BYTES = 4 * 1024; + + private static final Set ROOT_FIELDS = + Set.of("schema", "equipmentApplicability", "families"); + private static final List FAMILY_ORDER = + List.of( + "ACTOR_BODY_LAYOUT_ASSIGNMENTS", + "ARCHETYPE_ASSIGNMENTS", + "ARCHETYPE_CONSTRAINTS", + "ARCHETYPE_ROOTS", + "BALANCE_CURVE_ATTACHMENTS", + "BALANCE_CURVE_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS", + "BODY_LAYOUT_ROOTS", + "CRAFTING_INGREDIENT_BINDINGS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_RECIPE_ROOTS", + "EQUIPMENT_ATTACHMENT_RULES", + "EQUIPMENT_CAPABILITIES", + "EQUIPMENT_COMPATIBILITY_RULES", + "EQUIPMENT_OCCUPANCY_RULES", + "EQUIPMENT_SLOT_GROUPS", + "EQUIPMENT_SLOT_ROOTS", + "INBOUND_LOOT_BINDINGS", + "ITEM_TEMPLATE_ROOTS", + "LOOT_ITEM_MAPPINGS", + "LOOT_TABLE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "OTHER_ACTOR_TEMPLATE_ROOTS"); + private static final Set FAMILY_FIELDS = Set.copyOf(FAMILY_ORDER); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final byte[] canonicalBytes; + + private EntityAuthoredSourceInventoryDeclaration(byte[] canonicalBytes) { + this.canonicalBytes = canonicalBytes.clone(); + } + + /** + * Parses explicitly authored inventory content, accepting only its exact empty-only v1 form. + * Nonempty families are rejected as unsupported rather than interpreted as empty. + */ + public static EntityAuthoredSourceInventoryDeclaration parse(String authoredJson) { + if (authoredJson == null) { + throw new IllegalArgumentException("Entity source inventory declaration is required"); + } + validateBoundedUtf8(authoredJson); + + final JsonNode root; + try { + root = JSON.readTree(authoredJson); + } catch (RuntimeException invalidJson) { + throw new IllegalArgumentException( + "Entity source inventory declaration is not valid closed JSON", invalidJson); + } + requireObjectFields(root, ROOT_FIELDS, "declaration"); + JsonNode schema = root.get("schema"); + if (schema == null || !schema.isTextual() || !SCHEMA.equals(schema.textValue())) { + throw new IllegalArgumentException("Unsupported Entity source inventory schema"); + } + JsonNode equipmentApplicability = root.get("equipmentApplicability"); + if (equipmentApplicability == null + || !equipmentApplicability.isTextual() + || !"NOT_APPLICABLE".equals(equipmentApplicability.textValue())) { + throw new IllegalArgumentException( + "Empty Entity source inventory requires explicit equipment non-applicability"); + } + + JsonNode families = root.get("families"); + requireObjectFields(families, FAMILY_FIELDS, "families"); + for (String family : FAMILY_ORDER) { + JsonNode entries = families.get(family); + if (entries == null || !entries.isArray()) { + throw new IllegalArgumentException("Entity source family must be an array: " + family); + } + if (entries.size() != 0) { + throw new IllegalArgumentException( + "Nonempty Entity source family is unsupported: " + family); + } + } + + try { + return new EntityAuthoredSourceInventoryDeclaration( + Rfc8785CanonicalJson.canonicalizeUtf8(authoredJson)); + } catch (IOException invalidCanonicalJson) { + throw new IllegalArgumentException( + "Entity source inventory declaration could not be canonicalized", invalidCanonicalJson); + } + } + + /** Returns the exact deterministic RFC 8785 JSON text retained by this value. */ + public String canonicalJson() { + return new String(canonicalBytes, StandardCharsets.UTF_8); + } + + /** Returns a defensive copy of the exact deterministic RFC 8785 bytes. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof EntityAuthoredSourceInventoryDeclaration declaration + && Arrays.equals(canonicalBytes, declaration.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + private static void validateBoundedUtf8(String value) { + if (value.length() > MAX_JSON_BYTES) { + throw new IllegalArgumentException("Entity source inventory declaration is too large"); + } + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + if (encoded.remaining() > MAX_JSON_BYTES) { + throw new IllegalArgumentException("Entity source inventory declaration is too large"); + } + } catch (CharacterCodingException invalidUnicode) { + throw new IllegalArgumentException( + "Entity source inventory declaration contains malformed Unicode", invalidUnicode); + } + } + + private static void requireObjectFields(JsonNode value, Set expected, String name) { + if (value == null || !value.isObject()) { + throw new IllegalArgumentException("Entity source inventory " + name + " must be an object"); + } + Set actual = new HashSet<>(); + value.properties().forEach(property -> actual.add(property.getKey())); + if (!actual.equals(expected)) { + throw new IllegalArgumentException( + "Entity source inventory " + name + " has missing or unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclarationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclarationTest.java new file mode 100644 index 0000000000..c3219fe5bf --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclarationTest.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.common.automation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +class AutomationAuthoredSourceInventoryDeclarationTest { + private static final String CANONICAL_EMPTY_DECLARATION = + "{\"families\":{\"EVENT_BINDINGS\":[],\"SCRIPT_DEFINITIONS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]},\"schema\":\"automation-authored-source-inventory/v1\"}"; + + @Test + void acceptsExplicitEmptyFamiliesAndRetainsCanonicalBytes() { + var declaration = + AutomationAuthoredSourceInventoryDeclaration.parse( + "{ \"schema\": \"automation-authored-source-inventory/v1\"," + + " \"families\": { \"SCRIPT_PATCH_SOURCES\": []," + + " \"SCRIPT_DEFINITIONS\": [], \"EVENT_BINDINGS\": [] } }"); + + assertThat(declaration.canonicalJson()).isEqualTo(CANONICAL_EMPTY_DECLARATION); + assertThat(declaration.canonicalBytes()) + .containsExactly(CANONICAL_EMPTY_DECLARATION.getBytes(StandardCharsets.UTF_8)); + assertThat(declaration) + .isEqualTo(AutomationAuthoredSourceInventoryDeclaration.parse(CANONICAL_EMPTY_DECLARATION)); + + byte[] exposed = declaration.canonicalBytes(); + exposed[0] = 'x'; + assertThat(declaration.canonicalJson()).isEqualTo(CANONICAL_EMPTY_DECLARATION); + } + + @Test + void rejectsMissingNullUnknownAndMalformedFields() { + assertInvalid("{}"); + assertInvalid( + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]}}"); + assertInvalid("{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":null}"); + assertInvalid( + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":null,\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"); + assertInvalid( + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":{},\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"); + assertInvalid( + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[],\"UNSUPPORTED\":[]}}"); + assertInvalid( + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]},\"unsupported\":true}"); + assertInvalid( + "{\"schema\":\"automation-authored-source-inventory/v2\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"); + } + + @Test + void rejectsDuplicateFieldsAndTrailingJson() { + assertInvalid( + "{\"schema\":\"automation-authored-source-inventory/v1\"," + + "\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"); + assertInvalid( + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"EVENT_BINDINGS\":[],\"SCRIPT_PATCH_SOURCES\":[]}}"); + assertInvalid(CANONICAL_EMPTY_DECLARATION + " {}"); + } + + @Test + void rejectsEveryNonemptyFamilyAsUnsupported() { + assertUnsupported("SCRIPT_DEFINITIONS", "{}", "SCRIPT_DEFINITIONS"); + assertUnsupported("EVENT_BINDINGS", "{}", "EVENT_BINDINGS"); + assertUnsupported("SCRIPT_PATCH_SOURCES", "{}", "SCRIPT_PATCH_SOURCES"); + } + + @Test + void rejectsNullInputMalformedUnicodeAndOversizedInput() { + assertThatThrownBy(() -> AutomationAuthoredSourceInventoryDeclaration.parse(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationAuthoredSourceInventoryDeclaration.parse( + "\"" + String.valueOf((char) 0xD800) + "\"")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationAuthoredSourceInventoryDeclaration.parse( + " ".repeat(AutomationAuthoredSourceInventoryDeclaration.MAX_JSON_BYTES + 1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("too large"); + } + + private static void assertInvalid(String json) { + assertThatThrownBy(() -> AutomationAuthoredSourceInventoryDeclaration.parse(json)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertUnsupported(String field, String entry, String family) { + String json = + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":" + + (field.equals("SCRIPT_DEFINITIONS") ? "[" + entry + "]" : "[]") + + ",\"EVENT_BINDINGS\":" + + (field.equals("EVENT_BINDINGS") ? "[" + entry + "]" : "[]") + + ",\"SCRIPT_PATCH_SOURCES\":" + + (field.equals("SCRIPT_PATCH_SOURCES") ? "[" + entry + "]" : "[]") + + "}}"; + assertThatThrownBy(() -> AutomationAuthoredSourceInventoryDeclaration.parse(json)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Nonempty Automation source family is unsupported: " + family); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclarationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclarationTest.java new file mode 100644 index 0000000000..5c34ee6e17 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclarationTest.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.common.entity; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +class EntityAuthoredSourceInventoryDeclarationTest { + private static final String FAMILIES = + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[]," + + "\"EQUIPMENT_SLOT_GROUPS\":[],\"EQUIPMENT_SLOT_ROOTS\":[]," + + "\"INBOUND_LOOT_BINDINGS\":[],\"ITEM_TEMPLATE_ROOTS\":[]," + + "\"LOOT_ITEM_MAPPINGS\":[],\"LOOT_TABLE_ROOTS\":[]," + + "\"NPC_TEMPLATE_ROOTS\":[],\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]"; + private static final String CANONICAL_EMPTY_DECLARATION = + "{\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + FAMILIES + + "},\"schema\":\"entity-authored-source-inventory/v1\"}"; + + @Test + void acceptsExplicitEmptyFamiliesAndRetainsCanonicalBytes() { + var declaration = + EntityAuthoredSourceInventoryDeclaration.parse( + "{ \"schema\": \"entity-authored-source-inventory/v1\"," + + " \"equipmentApplicability\": \"NOT_APPLICABLE\", \"families\": {" + + FAMILIES + + " } }"); + + assertThat(declaration.canonicalJson()).isEqualTo(CANONICAL_EMPTY_DECLARATION); + assertThat(declaration.canonicalBytes()) + .containsExactly(CANONICAL_EMPTY_DECLARATION.getBytes(StandardCharsets.UTF_8)); + assertThat(declaration) + .isEqualTo(EntityAuthoredSourceInventoryDeclaration.parse(CANONICAL_EMPTY_DECLARATION)); + + byte[] exposed = declaration.canonicalBytes(); + exposed[0] = 'x'; + assertThat(declaration.canonicalJson()).isEqualTo(CANONICAL_EMPTY_DECLARATION); + } + + @Test + void rejectsMissingNullUnknownAndMalformedFields() { + assertInvalid("{}"); + assertInvalid( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{}}"); + assertInvalid(CANONICAL_EMPTY_DECLARATION.replace(",\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]", "")); + assertInvalid( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":null}"); + assertInvalid( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + FAMILIES.replace("\"ITEM_TEMPLATE_ROOTS\":[]", "\"ITEM_TEMPLATE_ROOTS\":null") + + "}}"); + assertInvalid( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + FAMILIES.replace("\"ITEM_TEMPLATE_ROOTS\":[]", "\"ITEM_TEMPLATE_ROOTS\":{}") + + "}}"); + assertInvalid( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + FAMILIES + + ",\"UNSUPPORTED\":[]}}"); + assertInvalid( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + FAMILIES + + "},\"unsupported\":true}"); + assertInvalid( + "{\"schema\":\"entity-authored-source-inventory/v2\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + FAMILIES + + "}}"); + } + + @Test + void requiresExplicitEquipmentNonApplicability() { + assertInvalid( + "{\"schema\":\"entity-authored-source-inventory/v1\",\"families\":{" + FAMILIES + "}}"); + assertInvalid( + CANONICAL_EMPTY_DECLARATION.replace( + "\"equipmentApplicability\":\"NOT_APPLICABLE\"", + "\"equipmentApplicability\":\"APPLICABLE\"")); + assertInvalid( + CANONICAL_EMPTY_DECLARATION.replace( + "\"equipmentApplicability\":\"NOT_APPLICABLE\"", "\"equipmentApplicability\":false")); + } + + @Test + void rejectsDuplicateFieldsAndTrailingJson() { + assertInvalid( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + FAMILIES + + "}}"); + assertInvalid( + CANONICAL_EMPTY_DECLARATION.replace( + "\"ITEM_TEMPLATE_ROOTS\":[]", "\"ITEM_TEMPLATE_ROOTS\":[],\"ITEM_TEMPLATE_ROOTS\":[]")); + assertInvalid(CANONICAL_EMPTY_DECLARATION + " {}"); + } + + @Test + void rejectsEveryNonemptyFamilyAsUnsupported() { + for (String family : FAMILIES.split(",")) { + String familyName = family.substring(1, family.indexOf('"', 1)); + String json = + CANONICAL_EMPTY_DECLARATION.replace( + "\"" + familyName + "\":[]", "\"" + familyName + "\":[null]"); + assertThatThrownBy(() -> EntityAuthoredSourceInventoryDeclaration.parse(json)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Nonempty Entity source family is unsupported: " + familyName); + } + } + + @Test + void rejectsNullInputMalformedUnicodeAndOversizedInput() { + assertThatThrownBy(() -> EntityAuthoredSourceInventoryDeclaration.parse(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntityAuthoredSourceInventoryDeclaration.parse( + "\"" + String.valueOf((char) 0xD800) + "\"")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntityAuthoredSourceInventoryDeclaration.parse( + " ".repeat(EntityAuthoredSourceInventoryDeclaration.MAX_JSON_BYTES + 1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("too large"); + } + + private static void assertInvalid(String json) { + assertThatThrownBy(() -> EntityAuthoredSourceInventoryDeclaration.parse(json)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java new file mode 100644 index 0000000000..b41606fca6 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import tools.jackson.databind.JsonNode; + +/** Automation's actual authored inventory content and its immutable original Draft provenance. */ +public record TemplateConfigOwnerSourceInventoryDeclaration( + Owner owner, + AutomationAuthoredSourceInventoryDeclaration inventory, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId) { + public TemplateConfigOwnerSourceInventoryDeclaration { + if (owner != Owner.AUTOMATION_SCRIPTING) + throw new IllegalArgumentException("Only Automation source inventory is supported"); + Objects.requireNonNull(inventory); + Objects.requireNonNull(sourceBinding); + if (revisionOrder == null || !revisionOrder.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Exact owner source inventory revision order required"); + TemplateConfigSource.uuid(Objects.requireNonNull(revisionId).toString()); + var revision = + sourceBinding.revisions().stream() + .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .filter( + r -> r.revisionId().equals(revisionId) && r.revisionOrder().equals(revisionOrder)) + .findFirst() + .orElseThrow(); + if (!TemplateConfigSource.ownerInventoryPayload(owner, inventory) + .equals(CommandSource.canonical(CommandSource.tree(revision.payload())))) + throw new IllegalArgumentException( + "Owner inventory differs from its exact original source revision"); + } + + Map object() { + return Map.of( + "owner", owner.name(), + "inventoryJson", inventory.canonicalJson(), + "sourceBindingJson", sourceBinding.canonicalJson(), + "sourceBindingDigest", sourceBinding.digest(), + "revisionOrder", revisionOrder, + "revisionId", revisionId.toString()); + } + + static TemplateConfigOwnerSourceInventoryDeclaration fromStored(JsonNode node) { + CommandSource.requireStoredFields( + node, + "owner", + "inventoryJson", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId"); + Owner owner = Owner.valueOf(CommandSource.requiredStoredText(node, "owner")); + return new TemplateConfigOwnerSourceInventoryDeclaration( + owner, + AutomationAuthoredSourceInventoryDeclaration.parse( + CommandSource.requiredStoredText(node, "inventoryJson")), + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(node, "sourceBindingJson"), + CommandSource.requiredStoredText(node, "sourceBindingDigest")), + CommandSource.requiredStoredText(node, "revisionOrder"), + TemplateConfigSource.uuid(CommandSource.requiredStoredText(node, "revisionId"))); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java index d708940075..367bf6c17a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java @@ -11,6 +11,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; import tools.jackson.databind.JsonNode; @@ -26,7 +27,8 @@ private TemplateConfigSource() {} public enum OperationKind { CREATE, UPSERT, - DELETE + DELETE, + DECLARE_OWNER_SOURCE_INVENTORY } public record GameplayInput(Family family, String key, UUID revisionId) { @@ -144,11 +146,45 @@ public record Mutation( OperationKind operation, String templateId, String templateName, - Config config) { + Config config, + Owner declaredOwner, + AutomationAuthoredSourceInventoryDeclaration inventory) { + public Mutation( + DraftCommitBinding binding, + String revisionOrder, + UUID revisionId, + OperationKind operation, + String templateId, + String templateName, + Config config) { + this( + binding, + revisionOrder, + revisionId, + operation, + templateId, + templateName, + config, + null, + null); + } + public Mutation { Objects.requireNonNull(binding); Objects.requireNonNull(operation); - if (operation == OperationKind.CREATE) { + if (operation == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { + if (templateId != null + || templateName != null + || config != null + || declaredOwner != Owner.AUTOMATION_SCRIPTING + || inventory == null) + throw new IllegalArgumentException( + "Owner inventory declaration carries only Automation authored content"); + new TemplateConfigOwnerSourceInventoryDeclaration( + declaredOwner, inventory, binding, revisionOrder, revisionId); + } else if (declaredOwner != null || inventory != null) { + throw new IllegalArgumentException("Template row mutations carry no owner inventory"); + } else if (operation == OperationKind.CREATE) { if (templateId != null || templateName == null || templateName.isBlank() @@ -160,12 +196,13 @@ public record Mutation( if (templateName != null) throw new IllegalArgumentException("Only CREATE carries a display name"); } - if (operation != OperationKind.DELETE) { + if (operation != OperationKind.DELETE + && operation != OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { Objects.requireNonNull(config); if (!binding.target().canonicalVersionId().equals(config.baseVersionId())) throw new IllegalArgumentException( "Template config base differs from its exact source version"); - } else if (config != null) + } else if (operation == OperationKind.DELETE && config != null) throw new IllegalArgumentException("Template DELETE carries no config"); var revision = binding.revisions().stream() @@ -175,22 +212,25 @@ public record Mutation( .findFirst() .orElseThrow(); String expected = - operation == OperationKind.CREATE - ? createPayload(templateName, config) - : operation == OperationKind.UPSERT - ? upsertPayload(templateId, config) - : deletePayload(templateId); + payloadFor(operation, templateId, templateName, config, declaredOwner, inventory); if (!expected.equals(CommandSource.canonical(CommandSource.tree(revision.payload())))) throw new IllegalArgumentException( "Template config differs from its exact original revision"); } public String payload() { - return operation == OperationKind.CREATE - ? createPayload(templateName, config) - : operation == OperationKind.UPSERT - ? upsertPayload(templateId, config) - : deletePayload(templateId); + return payloadFor(operation, templateId, templateName, config, declaredOwner, inventory); + } + + public boolean changesTemplateRow() { + return operation != OperationKind.DECLARE_OWNER_SOURCE_INVENTORY; + } + + public TemplateConfigOwnerSourceInventoryDeclaration ownerInventoryDeclaration() { + return operation == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY + ? new TemplateConfigOwnerSourceInventoryDeclaration( + declaredOwner, inventory, binding, revisionOrder, revisionId) + : null; } } @@ -234,6 +274,7 @@ Map object() { public static List mutations(DraftCommitBinding binding) { List result = new ArrayList<>(); + Set declaredOwners = new HashSet<>(); for (var revision : binding.revisions()) { if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; JsonNode root = CommandSource.tree(revision.payload()); @@ -248,6 +289,31 @@ public static List mutations(DraftCommitBinding binding) { if (!REVISION_KIND.equals(kind)) throw new IllegalArgumentException("Unknown Game Design revision kind"); OperationKind operation = OperationKind.valueOf(text(root, "operation")); + int schemaVersion = + root.path("schemaVersion").isInt() ? root.path("schemaVersion").intValue() : -1; + if (operation == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { + if (schemaVersion != 2) + throw new IllegalArgumentException("Unsupported owner inventory source schemaVersion"); + fields(root, "schemaVersion", "revisionKind", "operation", "owner", "inventory"); + Owner owner = Owner.valueOf(text(root, "owner")); + if (owner != Owner.AUTOMATION_SCRIPTING || !declaredOwners.add(owner)) + throw new IllegalArgumentException("Only one Automation owner inventory is supported"); + result.add( + new Mutation( + binding, + revision.revisionOrder(), + revision.revisionId(), + operation, + null, + null, + null, + owner, + AutomationAuthoredSourceInventoryDeclaration.parse( + CommandSource.canonical(root.path("inventory"))))); + continue; + } + if (schemaVersion != 1) + throw new IllegalArgumentException("Unsupported template source schemaVersion"); fields( root, operation == OperationKind.CREATE @@ -259,8 +325,6 @@ public static List mutations(DraftCommitBinding binding) { "schemaVersion", "revisionKind", "operation", "templateId", "configJson" } : new String[] {"schemaVersion", "revisionKind", "operation", "templateId"}); - if (!root.path("schemaVersion").isInt() || root.path("schemaVersion").intValue() != 1) - throw new IllegalArgumentException("Unsupported template source schemaVersion"); result.add( new Mutation( binding, @@ -321,6 +385,56 @@ public static String deletePayload(String templateId) { templateId)); } + public static String ownerInventoryPayload( + Owner owner, AutomationAuthoredSourceInventoryDeclaration inventory) { + if (owner != Owner.AUTOMATION_SCRIPTING) + throw new IllegalArgumentException("Only Automation source inventory is supported"); + Objects.requireNonNull(inventory); + return CommandSource.canonical( + Map.of( + "schemaVersion", 2, + "revisionKind", REVISION_KIND, + "operation", OperationKind.DECLARE_OWNER_SOURCE_INVENTORY.name(), + "owner", owner.name(), + "inventory", CommandSource.tree(inventory.canonicalJson()))); + } + + public static List + replayOwnerInventoryDeclarations( + List inherited, + DraftCommitBinding binding) { + Map declarations = + new java.util.EnumMap<>(Owner.class); + for (var declaration : inherited) { + if (!binding.target().equals(declaration.sourceBinding().target()) + || declarations.put(declaration.owner(), declaration) != null) + throw new IllegalArgumentException("Invalid inherited owner inventory declarations"); + } + for (Mutation mutation : mutations(binding)) { + if (mutation.operation() == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { + declarations.put(mutation.declaredOwner(), mutation.ownerInventoryDeclaration()); + } + } + return declarations.values().stream() + .sorted(Comparator.comparing(value -> value.owner().name())) + .toList(); + } + + private static String payloadFor( + OperationKind operation, + String templateId, + String templateName, + Config config, + Owner declaredOwner, + AutomationAuthoredSourceInventoryDeclaration inventory) { + return switch (operation) { + case CREATE -> createPayload(templateName, config); + case UPSERT -> upsertPayload(templateId, config); + case DELETE -> deletePayload(templateId); + case DECLARE_OWNER_SOURCE_INVENTORY -> ownerInventoryPayload(declaredOwner, inventory); + }; + } + public static List replay( List inherited, DraftCommitBinding binding, Map createdRows) { Map entries = new java.util.HashMap<>(); @@ -330,6 +444,7 @@ public static List replay( throw new IllegalArgumentException("Invalid inherited template config inventory"); } for (Mutation mutation : mutations(binding)) { + if (!mutation.changesTemplateRow()) continue; if (mutation.operation() == OperationKind.DELETE) { if (entries.remove(mutation.templateId()) == null) throw new IllegalArgumentException("Template DELETE requires an authored entry"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java index aae7bdc88a..d16cd071f8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java @@ -122,12 +122,36 @@ public Optional apply(DraftCommitBindi ? fence.isPresent() || !"0".equals(epoch) : fence.isEmpty() || !inherited.equals(fence.orElseThrow().commitId())) throw new IllegalStateException("TEMPLATE_CONFIG_PREVIOUS_FENCE_CHANGED"); - List previous = + var previousSnapshot = inherited == null - ? List.of() - : readSnapshot(binding.target(), inherited).orElseThrow().entries(); + ? Optional.empty() + : Optional.of(readSnapshot(binding.target(), inherited).orElseThrow()); + List previous = + previousSnapshot.map(TemplateConfigSourceSnapshot::entries).orElseGet(List::of); + List previousDeclarations = + previousSnapshot + .map(TemplateConfigSourceSnapshot::ownerSourceInventoryDeclarations) + .orElseGet(List::of); var createdRows = new java.util.HashMap(); for (var mutation : mutations) { + if (mutation.operation() + == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { + var declaration = mutation.ownerInventoryDeclaration(); + dsl.execute( + "INSERT INTO game_design_template_config_owner_source_inventory_declaration " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, owner, inventory_json, payload_json) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId(), + mutation.revisionId(), + Integer.parseInt(mutation.revisionOrder()), + mutation.declaredOwner().name(), + mutation.inventory().canonicalJson(), + mutation.payload()); + continue; + } if (mutation.config() != null) { mutation.config().requireAvailableOwnerReads(); requireGameplayInputs(binding, mutation.config()); @@ -205,7 +229,8 @@ public Optional apply(DraftCommitBindi new BigInteger(epoch).add(BigInteger.ONE).toString(), inherited, head.get("genesis_receipt_id", UUID.class), - TemplateConfigSource.replay(previous, binding, createdRows)); + TemplateConfigSource.replay(previous, binding, createdRows), + TemplateConfigSource.replayOwnerInventoryDeclarations(previousDeclarations, binding)); var result = new TemplateConfigSourceSnapshot.Application(binding, epoch, snapshot); dsl.execute( "INSERT INTO game_design_template_config_source_application (canonical_tenant_id, canonical_version_id, request_id, commit_id, " @@ -228,7 +253,11 @@ public Optional apply(DraftCommitBindi inherited) != 1) throw new IllegalStateException("TEMPLATE_CONFIG_EPOCH_CONFLICT"); templateReferences.synchronizeCurrentProjection( - binding.target(), binding, snapshot, mutations, createdRows); + binding.target(), + binding, + snapshot, + mutations.stream().filter(TemplateConfigSource.Mutation::changesTemplateRow).toList(), + createdRows); return Optional.of(application(binding).orElseThrow()); } @@ -255,10 +284,16 @@ public TemplateConfigSourceSnapshot captureSynchronized(DraftCommitBinding bindi } else { if (applied.isPresent()) throw new IllegalStateException("TEMPLATE_CONFIG_UNDECLARED_APPLICATION"); - var entries = + var inheritedSnapshot = inherited == null - ? List.of() - : readSnapshot(binding.target(), inherited).orElseThrow().entries(); + ? Optional.empty() + : Optional.of(readSnapshot(binding.target(), inherited).orElseThrow()); + var entries = + inheritedSnapshot.map(TemplateConfigSourceSnapshot::entries).orElseGet(List::of); + var declarations = + inheritedSnapshot + .map(TemplateConfigSourceSnapshot::ownerSourceInventoryDeclarations) + .orElseGet(List::of); if (inherited == null && !"0".equals(head.get("source_epoch", String.class))) throw new IllegalStateException("TEMPLATE_CONFIG_GENESIS_NOT_CURRENT"); snapshot = @@ -267,7 +302,8 @@ public TemplateConfigSourceSnapshot captureSynchronized(DraftCommitBinding bindi head.get("source_epoch", String.class), inherited, head.get("genesis_receipt_id", UUID.class), - entries); + entries, + declarations); } requireSelectedReferences(snapshot); requireCurrentInventory(snapshot); @@ -323,6 +359,7 @@ public Optional readSnapshot(TargetProof target, U if (fence == null || !snapshot.binding().digest().equals(fence.get(0, String.class))) throw new IllegalStateException("TEMPLATE_CONFIG_SNAPSHOT_FENCE_CONFLICT"); verifyEntries(snapshot); + verifyOwnerInventoryDeclarations(snapshot); requireSelectedReferences(snapshot); return Optional.of(snapshot); } @@ -468,13 +505,144 @@ private Optional application( .getValues("payload_json", String.class); if (!stored.equals( TemplateConfigSource.mutations(binding).stream() + .filter(TemplateConfigSource.Mutation::changesTemplateRow) .map(TemplateConfigSource.Mutation::payload) .toList())) throw new IllegalStateException("TEMPLATE_CONFIG_REVISION_READBACK_CONFLICT"); + verifyOwnerInventoryApplication(binding); verifyEntries(result.snapshot()); + verifyOwnerInventoryDeclarations(result.snapshot()); return Optional.of(result); } + private void verifyOwnerInventoryApplication(DraftCommitBinding binding) { + var expected = + TemplateConfigSource.mutations(binding).stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .toList(); + var rows = + dsl.fetch( + "SELECT revision_id, revision_order, owner, inventory_json, payload_json " + + "FROM game_design_template_config_owner_source_inventory_declaration " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? AND commit_id = ? " + + "ORDER BY revision_order", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.requestId(), + binding.commitId()); + if (rows.size() != expected.size()) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_READBACK_CONFLICT"); + for (int i = 0; i < expected.size(); i++) { + var mutation = expected.get(i); + var row = rows.get(i); + if (!mutation.revisionId().equals(row.get("revision_id", UUID.class)) + || Integer.parseInt(mutation.revisionOrder()) != row.get("revision_order", Integer.class) + || !mutation.declaredOwner().name().equals(row.get("owner", String.class)) + || !mutation.inventory().canonicalJson().equals(row.get("inventory_json", String.class)) + || !mutation.payload().equals(row.get("payload_json", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_READBACK_CONFLICT"); + } + } + + private void verifyOwnerInventoryDeclarations(TemplateConfigSourceSnapshot snapshot) { + var target = snapshot.binding().target(); + var effectiveRows = + dsl.fetch( + "SELECT DISTINCT ON (d.owner) d.request_id, d.commit_id, d.revision_id, d.revision_order, " + + "d.owner, d.inventory_json, d.payload_json, c.binding_json, c.input_digest " + + "FROM game_design_template_config_owner_source_inventory_declaration d " + + "JOIN game_design_template_config_source_application a ON a.canonical_tenant_id = d.canonical_tenant_id " + + "AND a.canonical_version_id = d.canonical_version_id AND a.request_id = d.request_id AND a.commit_id = d.commit_id " + + "JOIN game_design_draft_commit c ON c.canonical_tenant_id = d.canonical_tenant_id " + + "AND c.canonical_version_id = d.canonical_version_id AND c.request_id = d.request_id AND c.commit_id = d.commit_id " + + "WHERE d.canonical_tenant_id = ? AND d.canonical_version_id = ? AND a.expected_epoch::NUMERIC < CAST(? AS NUMERIC) " + + "ORDER BY d.owner, a.expected_epoch::NUMERIC DESC, d.revision_order DESC", + target.canonicalTenantId(), + target.canonicalVersionId(), + snapshot.sourceEpoch()); + var effectiveDeclarations = + new java.util.ArrayList(); + for (var row : effectiveRows) { + var sourceBinding = + DraftCommitBinding.fromStored( + row.get("binding_json", String.class), row.get("input_digest", String.class)); + exact(sourceBinding); + var mutation = + TemplateConfigSource.mutations(sourceBinding).stream() + .filter(m -> m.revisionId().equals(row.get("revision_id", UUID.class))) + .filter( + m -> + Integer.parseInt(m.revisionOrder()) + == row.get("revision_order", Integer.class)) + .filter( + m -> + m.operation() + == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .findFirst() + .orElseThrow( + () -> + new IllegalStateException( + "TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_UNAVAILABLE")); + if (!sourceBinding.requestId().equals(row.get("request_id", UUID.class)) + || !sourceBinding.commitId().equals(row.get("commit_id", UUID.class)) + || !mutation.declaredOwner().name().equals(row.get("owner", String.class)) + || !mutation.inventory().canonicalJson().equals(row.get("inventory_json", String.class)) + || !mutation.payload().equals(row.get("payload_json", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_CHANGED"); + effectiveDeclarations.add(mutation.ownerInventoryDeclaration()); + } + if (!effectiveDeclarations.equals(snapshot.ownerSourceInventoryDeclarations())) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SNAPSHOT_CONFLICT"); + + for (var declaration : snapshot.ownerSourceInventoryDeclarations()) { + exact(declaration.sourceBinding()); + var mutation = + TemplateConfigSource.mutations(declaration.sourceBinding()).stream() + .filter(m -> m.revisionId().equals(declaration.revisionId())) + .filter(m -> m.revisionOrder().equals(declaration.revisionOrder())) + .filter( + m -> + m.operation() + == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .findFirst() + .orElseThrow( + () -> + new IllegalStateException( + "TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_UNAVAILABLE")); + var row = + dsl.fetchOne( + "SELECT request_id, commit_id, owner, inventory_json, payload_json " + + "FROM game_design_template_config_owner_source_inventory_declaration " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ? " + + "AND commit_id = ? AND revision_id = ? AND revision_order = ? AND owner = ?", + snapshot.binding().target().canonicalTenantId(), + snapshot.binding().target().canonicalVersionId(), + declaration.sourceBinding().requestId(), + declaration.sourceBinding().commitId(), + declaration.revisionId(), + Integer.parseInt(declaration.revisionOrder()), + declaration.owner().name()); + if (row == null + || !declaration.sourceBinding().requestId().equals(row.get("request_id", UUID.class)) + || !declaration.sourceBinding().commitId().equals(row.get("commit_id", UUID.class)) + || !declaration.owner().name().equals(row.get("owner", String.class)) + || !declaration + .inventory() + .canonicalJson() + .equals(row.get("inventory_json", String.class)) + || !mutation.payload().equals(row.get("payload_json", String.class))) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_CHANGED"); + } + for (var mutation : TemplateConfigSource.mutations(snapshot.binding())) + if (mutation.operation() == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY + && snapshot.ownerSourceInventoryDeclarations().stream() + .noneMatch(d -> d.revisionId().equals(mutation.revisionId()))) + throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SNAPSHOT_MISSING"); + } + private void verifyEntries(TemplateConfigSourceSnapshot snapshot) { for (var entry : snapshot.entries()) { exact(entry.sourceBinding()); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java index ed596ee480..4f2f65c097 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java @@ -18,8 +18,19 @@ public record TemplateConfigSourceSnapshot( String sourceEpoch, UUID inheritedCommitId, UUID genesisReceiptId, - List entries) { + List entries, + List ownerSourceInventoryDeclarations) { public static final String SCHEMA = "game-design-template-config-source-snapshot/v1"; + public static final String SCHEMA_V2 = "game-design-template-config-source-snapshot/v2"; + + public TemplateConfigSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List entries) { + this(binding, sourceEpoch, inheritedCommitId, genesisReceiptId, entries, List.of()); + } public TemplateConfigSourceSnapshot { Objects.requireNonNull(binding); @@ -36,25 +47,46 @@ public record TemplateConfigSourceSnapshot( entries.stream() .sorted(java.util.Comparator.comparing(e -> new BigInteger(e.templateId()))) .toList())) throw new IllegalArgumentException("Canonical template row order required"); + ownerSourceInventoryDeclarations = List.copyOf(ownerSourceInventoryDeclarations); + var owners = + new java.util.HashSet(); + for (var declaration : ownerSourceInventoryDeclarations) { + if (!declaration.sourceBinding().target().equals(binding.target()) + || !owners.add(declaration.owner())) + throw new IllegalArgumentException("Template owner inventory target or identity conflict"); + } + if (!ownerSourceInventoryDeclarations.equals( + ownerSourceInventoryDeclarations.stream() + .sorted(java.util.Comparator.comparing(value -> value.owner().name())) + .toList())) + throw new IllegalArgumentException("Canonical owner inventory order required"); } public String canonicalJson() { - return CommandSource.canonical( - Map.of( - "schema", - SCHEMA, - "bindingJson", - binding.canonicalJson(), - "bindingDigest", - binding.digest(), - "sourceEpoch", - sourceEpoch, - "inheritedCommitId", - inheritedCommitId == null ? "" : inheritedCommitId.toString(), - "genesisReceiptId", - genesisReceiptId.toString(), - "entries", - entries.stream().map(TemplateConfigSource.Entry::object).toList())); + Map value = + new java.util.LinkedHashMap<>( + Map.of( + "schema", + ownerSourceInventoryDeclarations.isEmpty() ? SCHEMA : SCHEMA_V2, + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptId", + genesisReceiptId.toString(), + "entries", + entries.stream().map(TemplateConfigSource.Entry::object).toList())); + if (!ownerSourceInventoryDeclarations.isEmpty()) + value.put( + "ownerSourceInventoryDeclarations", + ownerSourceInventoryDeclarations.stream() + .map(TemplateConfigOwnerSourceInventoryDeclaration::object) + .toList()); + return CommandSource.canonical(value); } public byte[] canonicalBytes() { @@ -67,18 +99,35 @@ public String digest() { public static TemplateConfigSourceSnapshot fromStored(String json) { var root = CommandSource.tree(json); - CommandSource.requireStoredFields( - root, - "schema", - "bindingJson", - "bindingDigest", - "sourceEpoch", - "inheritedCommitId", - "genesisReceiptId", - "entries"); - if (!SCHEMA.equals(CommandSource.requiredStoredText(root, "schema")) - || !root.path("entries").isArray()) + String schema = CommandSource.requiredStoredText(root, "schema"); + if (SCHEMA.equals(schema)) { + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "entries"); + } else if (SCHEMA_V2.equals(schema)) { + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "entries", + "ownerSourceInventoryDeclarations"); + } else { throw new IllegalArgumentException("Unsupported template config source snapshot"); + } + if (!root.path("entries").isArray() + || (SCHEMA_V2.equals(schema) && !root.path("ownerSourceInventoryDeclarations").isArray())) + throw new IllegalArgumentException( + "Template config source snapshot collections are required"); var binding = DraftCommitBinding.fromStored( CommandSource.requiredStoredText(root, "bindingJson"), @@ -108,6 +157,10 @@ public static TemplateConfigSourceSnapshot fromStored(String json) { TemplateConfigSource.uuid(CommandSource.requiredStoredText(node, "revisionId")), name.isEmpty() ? null : name)); } + List declarations = new ArrayList<>(); + if (SCHEMA_V2.equals(schema)) + for (var node : root.path("ownerSourceInventoryDeclarations")) + declarations.add(TemplateConfigOwnerSourceInventoryDeclaration.fromStored(node)); if (!root.path("inheritedCommitId").isTextual()) throw new IllegalArgumentException("Explicit predecessor required"); String inherited = root.path("inheritedCommitId").textValue(); @@ -117,7 +170,11 @@ public static TemplateConfigSourceSnapshot fromStored(String json) { CommandSource.requiredStoredText(root, "sourceEpoch"), inherited.isEmpty() ? null : TemplateConfigSource.uuid(inherited), TemplateConfigSource.uuid(CommandSource.requiredStoredText(root, "genesisReceiptId")), - entries); + entries, + declarations); + if ((SCHEMA.equals(schema) && !result.ownerSourceInventoryDeclarations().isEmpty()) + || (SCHEMA_V2.equals(schema) && result.ownerSourceInventoryDeclarations().isEmpty())) + throw new IllegalArgumentException("Template config source snapshot schema mismatch"); if (!json.equals(result.canonicalJson())) throw new IllegalArgumentException("Noncanonical template config snapshot"); return result; diff --git a/services/game-design-service/src/main/resources/db/migration/V67__template_config_owner_source_inventory.sql b/services/game-design-service/src/main/resources/db/migration/V67__template_config_owner_source_inventory.sql new file mode 100644 index 0000000000..1dd3eb066d --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V67__template_config_owner_source_inventory.sql @@ -0,0 +1,365 @@ +CREATE TABLE game_design_template_config_owner_source_inventory_declaration ( + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + request_id UUID NOT NULL, + commit_id UUID NOT NULL, + revision_id UUID NOT NULL, + revision_order INTEGER NOT NULL CHECK (revision_order >= 0), + owner VARCHAR(32) NOT NULL CHECK (owner = 'AUTOMATION_SCRIPTING'), + inventory_json TEXT NOT NULL, + payload_json TEXT NOT NULL, + PRIMARY KEY (canonical_tenant_id, canonical_version_id, revision_id), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, owner), + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id, revision_order), + UNIQUE (canonical_tenant_id, canonical_version_id, request_id, commit_id, owner), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, request_id, commit_id) + REFERENCES game_design_draft_commit (canonical_tenant_id, canonical_version_id, request_id, commit_id), + FOREIGN KEY (canonical_tenant_id, canonical_version_id, commit_id) + REFERENCES game_design_template_config_source_application + (canonical_tenant_id, canonical_version_id, commit_id) + DEFERRABLE INITIALLY DEFERRED, + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (commit_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (revision_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (octet_length(inventory_json) BETWEEN 1 AND 4096), + CHECK (octet_length(payload_json) > 0) +); + +-- [jooq ignore start] +CREATE FUNCTION automation_authored_source_inventory_supported(value JSONB) RETURNS BOOLEAN AS $$ +BEGIN + IF jsonb_typeof(value) IS DISTINCT FROM 'object' THEN RETURN FALSE; END IF; + IF (SELECT count(*) FROM jsonb_object_keys(value)) <> 2 + OR value->>'schema' IS DISTINCT FROM 'automation-authored-source-inventory/v1' + OR jsonb_typeof(value->'schema') IS DISTINCT FROM 'string' + OR jsonb_typeof(value->'families') IS DISTINCT FROM 'object' THEN RETURN FALSE; END IF; + IF (SELECT count(*) FROM jsonb_object_keys(value->'families')) <> 3 + OR jsonb_typeof(value->'families'->'SCRIPT_DEFINITIONS') IS DISTINCT FROM 'array' + OR jsonb_typeof(value->'families'->'EVENT_BINDINGS') IS DISTINCT FROM 'array' + OR jsonb_typeof(value->'families'->'SCRIPT_PATCH_SOURCES') IS DISTINCT FROM 'array' THEN RETURN FALSE; END IF; + IF jsonb_array_length(value->'families'->'SCRIPT_DEFINITIONS') <> 0 + OR jsonb_array_length(value->'families'->'EVENT_BINDINGS') <> 0 + OR jsonb_array_length(value->'families'->'SCRIPT_PATCH_SOURCES') <> 0 THEN RETURN FALSE; END IF; + RETURN TRUE; +END; +$$ LANGUAGE plpgsql IMMUTABLE; + +CREATE FUNCTION guard_template_config_owner_source_inventory_declaration() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; c game_design_draft_commit%ROWTYPE; revision JSONB; payload JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'template owner source inventory history is immutable' USING ERRCODE = '23514'; + END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id + AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL + OR v.script_patch_version IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM game_design_template_config_source_genesis g + WHERE g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.canonical_version_id = NEW.canonical_version_id AND g.version_id = v.id) THEN + RAISE EXCEPTION 'template owner inventory requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x + WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id) THEN + RAISE EXCEPTION 'template owner inventory is frozen by selected publication or export' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT c FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF NOT EXISTS (SELECT 1 FROM game_design_draft_commit_application_slot slot + WHERE slot.canonical_tenant_id = NEW.canonical_tenant_id AND slot.canonical_version_id = NEW.canonical_version_id + AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id + AND r.request_id = NEW.request_id AND r.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'template owner inventory requires active coordinator application' USING ERRCODE = '23514'; + END IF; + SELECT r INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r + WHERE r->>'revisionId' = NEW.revision_id::TEXT AND r->>'revisionOrder' = NEW.revision_order::TEXT + AND r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + payload := (revision->>'payload')::JSONB; + IF jsonb_typeof(payload) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'template owner inventory requires exact supported Automation declaration' USING ERRCODE = '23514'; + END IF; + IF NOT template_config_unique_json((revision->>'payload')::JSON) + OR (SELECT count(*) FROM jsonb_object_keys(payload)) <> 5 + OR payload->'schemaVersion' IS DISTINCT FROM '2'::JSONB + OR payload->>'revisionKind' IS DISTINCT FROM 'TEMPLATE_CONFIG' + OR payload->>'operation' IS DISTINCT FROM 'DECLARE_OWNER_SOURCE_INVENTORY' + OR payload->>'owner' IS DISTINCT FROM 'AUTOMATION_SCRIPTING' + OR jsonb_typeof(payload->'inventory') IS DISTINCT FROM 'object' + OR NEW.owner IS DISTINCT FROM payload->>'owner' + OR NEW.inventory_json::JSONB IS DISTINCT FROM payload->'inventory' + OR NOT template_config_unique_json(NEW.inventory_json::JSON) + OR NOT automation_authored_source_inventory_supported(NEW.inventory_json::JSONB) + OR NEW.payload_json IS DISTINCT FROM revision->>'payload' + OR NEW.payload_json::JSONB IS DISTINCT FROM payload THEN + RAISE EXCEPTION 'template owner inventory requires exact supported Automation declaration' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_template_config_v1_snapshot_declaration_presence() RETURNS TRIGGER AS $$ +DECLARE source_epoch TEXT; +BEGIN + IF TG_OP <> 'INSERT' THEN RETURN NEW; END IF; + IF NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v1' THEN + RETURN NEW; + END IF; + source_epoch := NEW.snapshot_json::JSONB->>'sourceEpoch'; + IF EXISTS (SELECT 1 FROM game_design_template_config_owner_source_inventory_declaration d + JOIN game_design_template_config_source_application a ON a.canonical_tenant_id = d.canonical_tenant_id + AND a.canonical_version_id = d.canonical_version_id AND a.request_id = d.request_id AND a.commit_id = d.commit_id + WHERE d.canonical_tenant_id = NEW.canonical_tenant_id AND d.canonical_version_id = NEW.canonical_version_id + AND a.expected_epoch::NUMERIC < source_epoch::NUMERIC) THEN + RAISE EXCEPTION 'template config v1 snapshot cannot omit retained owner declaration' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_template_config_source_v2() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; g game_design_template_config_source_genesis%ROWTYPE; + h game_design_template_config_source_head%ROWTYPE; c game_design_draft_commit%ROWTYPE; + a game_design_template_config_source_application%ROWTYPE; snapshot JSONB; prior JSONB; + expected_items JSONB; expected_declarations JSONB; declared BIGINT; predecessor_commit_id UUID; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'template config source history is immutable' USING ERRCODE = '23514'; + END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id + AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL + OR v.script_patch_version IS NOT NULL THEN + RAISE EXCEPTION 'template config source requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT g FROM game_design_template_config_source_genesis + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT * INTO STRICT h FROM game_design_template_config_source_head + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id FOR UPDATE; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x + WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id) THEN + RAISE EXCEPTION 'template config source is frozen by selected publication or export' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT c FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + snapshot := NEW.snapshot_json::JSONB; + IF jsonb_typeof(snapshot) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'template config v2 snapshot binding invalid' USING ERRCODE = '23514'; + END IF; + IF NOT template_config_unique_json(NEW.snapshot_json::JSON) + OR snapshot->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v2' + OR snapshot->>'bindingJson' IS DISTINCT FROM c.binding_json + OR snapshot->>'bindingDigest' IS DISTINCT FROM c.input_digest + OR snapshot->>'genesisReceiptId' IS DISTINCT FROM g.receipt_id::TEXT + OR (SELECT count(*) FROM jsonb_object_keys(snapshot)) <> 8 THEN + RAISE EXCEPTION 'template config v2 snapshot binding invalid' USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(snapshot->'entries') IS DISTINCT FROM 'array' + OR jsonb_typeof(snapshot->'ownerSourceInventoryDeclarations') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot->'ownerSourceInventoryDeclarations') = 0 THEN + RAISE EXCEPTION 'template config v2 snapshot declarations are required' USING ERRCODE = '23514'; + END IF; + + -- The application is checked against the pre-application head; its later synchronized + -- snapshot inherits from that immutable application, not a head pointer that may advance. + IF TG_TABLE_NAME = 'game_design_template_config_source_application' THEN + predecessor_commit_id := h.visible_commit_id; + ELSE + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r + WHERE r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND (r->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG'; + SELECT * INTO a FROM game_design_template_config_source_application + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + IF (declared > 0) IS DISTINCT FROM (a.commit_id IS NOT NULL) + OR (a.commit_id IS NOT NULL AND a.snapshot_json IS DISTINCT FROM NEW.snapshot_json) THEN + RAISE EXCEPTION 'template config v2 snapshot differs from its validated application' USING ERRCODE = '23514'; + END IF; + IF a.commit_id IS NOT NULL THEN + predecessor_commit_id := NULLIF(a.snapshot_json::JSONB->>'inheritedCommitId', '')::UUID; + ELSE + predecessor_commit_id := h.visible_commit_id; + END IF; + END IF; + IF snapshot->>'inheritedCommitId' IS DISTINCT FROM coalesce(predecessor_commit_id::TEXT, '') THEN + RAISE EXCEPTION 'template config v2 predecessor binding invalid' USING ERRCODE = '23514'; + END IF; + SELECT s0.snapshot_json::JSONB INTO prior + FROM (SELECT 1) seed + LEFT JOIN game_design_template_config_source_snapshot s0 ON s0.canonical_tenant_id = NEW.canonical_tenant_id + AND s0.canonical_version_id = NEW.canonical_version_id + AND s0.commit_id = predecessor_commit_id; + IF predecessor_commit_id IS NOT NULL AND prior IS NULL THEN + RAISE EXCEPTION 'template config v2 predecessor snapshot is unavailable' USING ERRCODE = '23514'; + END IF; + IF prior IS NULL THEN + prior := jsonb_build_object( + 'entries', '[]'::JSONB, + 'ownerSourceInventoryDeclarations', '[]'::JSONB); + END IF; + + IF TG_TABLE_NAME = 'game_design_template_config_source_application' THEN + IF NOT EXISTS (SELECT 1 FROM game_design_draft_commit_application_slot slot + WHERE slot.canonical_tenant_id = NEW.canonical_tenant_id AND slot.canonical_version_id = NEW.canonical_version_id + AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id + AND r.request_id = NEW.request_id AND r.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) + OR NEW.expected_epoch IS DISTINCT FROM h.source_epoch + OR snapshot->>'sourceEpoch' IS DISTINCT FROM (h.source_epoch::NUMERIC + 1)::TEXT + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') unit + WHERE unit->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND unit->>'aggregateType' = 'TEMPLATE_CONFIG_SET' + AND unit->>'aggregateId' = NEW.canonical_version_id::TEXT + AND unit->>'scopeType' = 'TEMPLATE_CONFIG_SET' + AND unit->>'scopeId' = 'effective' + AND unit->>'expectedEpoch' = NEW.expected_epoch) <> 1 THEN + RAISE EXCEPTION 'template config v2 application lacks coordinator scope epoch' USING ERRCODE = '23514'; + END IF; + WITH choices AS ( + SELECT (item->>'templateId')::BIGINT AS key, -1 AS ord, FALSE AS deleted, item + FROM jsonb_array_elements(prior->'entries') item + UNION ALL + SELECT r.template_id, r.revision_order, r.operation_kind = 'DELETE', template_config_revision_item(r) + FROM game_design_template_config_source_revision r + WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id + AND r.commit_id = NEW.commit_id + ), final AS (SELECT DISTINCT ON (key) * FROM choices ORDER BY key, ord DESC) + SELECT coalesce(jsonb_agg(item ORDER BY key) FILTER (WHERE NOT deleted), '[]'::JSONB) + INTO expected_items FROM final; + WITH choices AS ( + SELECT item->>'owner' AS owner, -1 AS ord, item + FROM jsonb_array_elements(prior->'ownerSourceInventoryDeclarations') item + UNION ALL + SELECT d.owner, d.revision_order, + jsonb_build_object('owner', d.owner, 'inventoryJson', d.inventory_json, + 'sourceBindingJson', source.binding_json, 'sourceBindingDigest', source.input_digest, + 'revisionOrder', d.revision_order::TEXT, 'revisionId', d.revision_id::TEXT) + FROM game_design_template_config_owner_source_inventory_declaration d + JOIN game_design_draft_commit source ON source.canonical_tenant_id = d.canonical_tenant_id + AND source.canonical_version_id = d.canonical_version_id + AND source.request_id = d.request_id AND source.commit_id = d.commit_id + WHERE d.canonical_tenant_id = NEW.canonical_tenant_id AND d.canonical_version_id = NEW.canonical_version_id + AND d.commit_id = NEW.commit_id + ), final AS (SELECT DISTINCT ON (owner) owner, ord, item FROM choices ORDER BY owner, ord DESC) + SELECT coalesce(jsonb_agg(item ORDER BY owner), '[]'::JSONB) + INTO expected_declarations FROM final; + IF expected_items IS DISTINCT FROM snapshot->'entries' + OR expected_declarations IS DISTINCT FROM snapshot->'ownerSourceInventoryDeclarations' + OR NEW.expected_epoch IS DISTINCT FROM h.source_epoch THEN + RAISE EXCEPTION 'template config v2 application must replay exact source and declarations' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF snapshot->>'sourceEpoch' IS DISTINCT FROM h.source_epoch + OR (a.commit_id IS NULL AND snapshot->'entries' IS DISTINCT FROM prior->'entries') + OR (a.commit_id IS NULL AND snapshot->'ownerSourceInventoryDeclarations' IS DISTINCT FROM prior->'ownerSourceInventoryDeclarations') + OR NEW.snapshot_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(NEW.snapshot_json, 'UTF8')), 'hex') + OR NOT template_config_selected_inputs(snapshot, NEW.canonical_tenant_id, NEW.canonical_version_id, NEW.commit_id) + OR NOT template_config_current_inventory(NEW.canonical_tenant_id, NEW.canonical_version_id, v.id, v.tenant_id, snapshot) + OR c.workflow_state <> 'SYNCHRONIZED' + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_visibility f + WHERE f.canonical_tenant_id = NEW.canonical_tenant_id AND f.canonical_version_id = NEW.canonical_version_id + AND f.request_id = NEW.request_id AND f.commit_id = NEW.commit_id AND f.input_digest = c.input_digest) THEN + RAISE EXCEPTION 'template config v2 snapshot requires exact synchronized source inheritance' USING ERRCODE = '23514'; + END IF; + WITH choices AS ( + SELECT item->>'owner' AS owner, -1::NUMERIC AS source_epoch, -1 AS ord, item + FROM jsonb_array_elements(prior->'ownerSourceInventoryDeclarations') item + UNION ALL + SELECT d.owner, owner_application.expected_epoch::NUMERIC, d.revision_order, + jsonb_build_object('owner', d.owner, 'inventoryJson', d.inventory_json, + 'sourceBindingJson', source.binding_json, 'sourceBindingDigest', source.input_digest, + 'revisionOrder', d.revision_order::TEXT, 'revisionId', d.revision_id::TEXT) + FROM game_design_template_config_owner_source_inventory_declaration d + JOIN game_design_draft_commit source ON source.canonical_tenant_id = d.canonical_tenant_id + AND source.canonical_version_id = d.canonical_version_id + AND source.request_id = d.request_id AND source.commit_id = d.commit_id + JOIN game_design_template_config_source_application owner_application + ON owner_application.canonical_tenant_id = d.canonical_tenant_id + AND owner_application.canonical_version_id = d.canonical_version_id + AND owner_application.request_id = d.request_id AND owner_application.commit_id = d.commit_id + WHERE d.canonical_tenant_id = NEW.canonical_tenant_id AND d.canonical_version_id = NEW.canonical_version_id + AND owner_application.expected_epoch::NUMERIC < (snapshot->>'sourceEpoch')::NUMERIC + ), final AS ( + SELECT DISTINCT ON (owner) owner, source_epoch, ord, item + FROM choices ORDER BY owner, source_epoch DESC, ord DESC + ) + SELECT coalesce(jsonb_agg(item ORDER BY owner), '[]'::JSONB) INTO expected_declarations FROM final; + IF expected_declarations IS DISTINCT FROM snapshot->'ownerSourceInventoryDeclarations' THEN + RAISE EXCEPTION 'template config v2 snapshot omits or changes authored owner inventory' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION deny_template_config_owner_inventory_truncate() RETURNS TRIGGER AS $$ +BEGIN + RAISE EXCEPTION 'template owner source inventory history is immutable' USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER template_config_owner_inventory_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_design_template_config_owner_source_inventory_declaration + FOR EACH ROW EXECUTE FUNCTION guard_template_config_owner_source_inventory_declaration(); +CREATE TRIGGER template_config_owner_inventory_no_truncate + BEFORE TRUNCATE ON game_design_template_config_owner_source_inventory_declaration + FOR EACH STATEMENT EXECUTE FUNCTION deny_template_config_owner_inventory_truncate(); + +DROP TRIGGER template_config_application_guard ON game_design_template_config_source_application; +CREATE TRIGGER template_config_application_v1_guard + BEFORE INSERT ON game_design_template_config_source_application + FOR EACH ROW WHEN (NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v2') + EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_application_v2_guard + BEFORE INSERT ON game_design_template_config_source_application + FOR EACH ROW WHEN (NEW.snapshot_json::JSONB->>'schema' = 'game-design-template-config-source-snapshot/v2') + EXECUTE FUNCTION guard_template_config_source_v2(); +CREATE TRIGGER template_config_application_immutable_guard + BEFORE UPDATE OR DELETE ON game_design_template_config_source_application + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); + +DROP TRIGGER template_config_snapshot_guard ON game_design_template_config_source_snapshot; +CREATE TRIGGER template_config_snapshot_v1_guard + BEFORE INSERT ON game_design_template_config_source_snapshot + FOR EACH ROW WHEN (NEW.snapshot_json::JSONB->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v2') + EXECUTE FUNCTION guard_template_config_source(); +CREATE TRIGGER template_config_snapshot_v2_guard + BEFORE INSERT ON game_design_template_config_source_snapshot + FOR EACH ROW WHEN (NEW.snapshot_json::JSONB->>'schema' = 'game-design-template-config-source-snapshot/v2') + EXECUTE FUNCTION guard_template_config_source_v2(); +CREATE TRIGGER template_config_snapshot_immutable_guard + BEFORE UPDATE OR DELETE ON game_design_template_config_source_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_template_config_source(); + +CREATE TRIGGER template_config_application_v1_declaration_presence_guard + BEFORE INSERT ON game_design_template_config_source_application + FOR EACH ROW EXECUTE FUNCTION guard_template_config_v1_snapshot_declaration_presence(); +CREATE TRIGGER template_config_snapshot_v1_declaration_presence_guard + BEFORE INSERT ON game_design_template_config_source_snapshot + FOR EACH ROW EXECUTE FUNCTION guard_template_config_v1_snapshot_declaration_presence(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java index fbbce4ef4c..4caafdd4a1 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -12,6 +12,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; @@ -56,6 +57,149 @@ class TemplateConfigSourcePostgresIntegrationTest { static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void authoredAutomationInventoryHasExactRetryInheritanceAndFrozenOriginalProvenance() { + var f = fixture(); + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + var declaration = + binding( + f, + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, inventory), + TemplateConfigSource.SCOPE, + "0"); + apply(f, declaration); + + var first = source(f, declaration); + assertThat(first.sourceEpoch()).isEqualTo("1"); + assertThat(first.entries()).isEmpty(); + assertThat(first.ownerSourceInventoryDeclarations()).hasSize(1); + assertThat(first.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(declaration); + assertThat(first.ownerSourceInventoryDeclarations().getFirst().revisionOrder()).isEqualTo("0"); + assertThat(first.ownerSourceInventoryDeclarations().getFirst().revisionId()) + .isEqualTo(declaration.revisions().getFirst().revisionId()); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isZero(); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_owner_source_inventory_declaration") + .get(0, Long.class)) + .isEqualTo(1L); + + f.tx.executeWithoutResult( + ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(declaration).orElseThrow()) + .isEqualTo(new TemplateConfigSourceSnapshot.Application(declaration, "0", first))); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isZero(); + + var unrelated = + binding( + f, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("unrelated")), + GameplayRuleSource.SCOPE, + "0"); + apply(f, unrelated); + var inherited = source(f, unrelated); + assertThat(inherited.sourceEpoch()).isEqualTo("1"); + assertThat(inherited.ownerSourceInventoryDeclarations()) + .containsExactly(first.ownerSourceInventoryDeclarations().getFirst()); + assertThat(inherited.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(declaration); + + var actualTemplate = + binding( + f, + TemplateConfigSource.createPayload("Starter", config(f, "[]")), + TemplateConfigSource.SCOPE, + "1"); + apply(f, actualTemplate); + assertThat(source(f, actualTemplate).entries()).hasSize(1); + assertThat(source(f, actualTemplate).ownerSourceInventoryDeclarations()) + .containsExactly(first.ownerSourceInventoryDeclarations().getFirst()); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isEqualTo(1L); + + var operation = + f.tx.execute( + ignored -> { + try { + return IsolatedPublicationOwnerSetup.retainSourceBacked( + f.dsl, f.target, 1L, "Automation inventory declaration source freeze"); + } catch (Exception e) { + throw new IllegalStateException("Unable to retain source-backed publication", e); + } + }); + var capture = + new GameDesignSourceRepository(f.dsl) + .readCapture(operation) + .orElseThrow() + .templateConfig() + .snapshot(); + assertThat(capture.ownerSourceInventoryDeclarations()) + .containsExactly(first.ownerSourceInventoryDeclarations().getFirst()); + assertThat(capture.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(declaration); + assertThat(capture.binding()).isEqualTo(actualTemplate); + } + + @Test + void latestSameOrderAutomationDeclarationRetainsItsExactBindingAcrossRetryAndInheritance() { + var f = fixture(); + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String identicalContent = + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, inventory); + var first = binding(f, identicalContent, TemplateConfigSource.SCOPE, "0"); + apply(f, first); + var firstSnapshot = source(f, first); + assertThat(firstSnapshot.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(first); + assertThat(firstSnapshot.ownerSourceInventoryDeclarations().getFirst().revisionOrder()) + .isEqualTo("0"); + + var second = binding(f, identicalContent, TemplateConfigSource.SCOPE, "1"); + assertThat(second.revisions().getFirst().revisionOrder()).isEqualTo("0"); + assertThat(second.revisions().getFirst().payload()).isEqualTo(identicalContent); + apply(f, second); + var secondSnapshot = source(f, second); + var latest = secondSnapshot.ownerSourceInventoryDeclarations().getFirst(); + assertThat(secondSnapshot.sourceEpoch()).isEqualTo("2"); + assertThat(secondSnapshot.ownerSourceInventoryDeclarations()).hasSize(1); + assertThat(latest.sourceBinding()).isEqualTo(second); + assertThat(latest.revisionOrder()).isEqualTo("0"); + assertThat(latest.revisionId()).isEqualTo(second.revisions().getFirst().revisionId()); + assertThat(latest.inventory()).isEqualTo(inventory); + + f.tx.executeWithoutResult( + ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(second).orElseThrow()) + .isEqualTo( + new TemplateConfigSourceSnapshot.Application(second, "1", secondSnapshot))); + var unrelated = + binding( + f, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("unrelated")), + GameplayRuleSource.SCOPE, + "0"); + apply(f, unrelated); + var inherited = source(f, unrelated); + assertThat(inherited.sourceEpoch()).isEqualTo("2"); + assertThat(inherited.ownerSourceInventoryDeclarations()).containsExactly(latest); + assertThat(inherited.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(second); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_owner_source_inventory_declaration") + .get(0, Long.class)) + .isEqualTo(2L); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isZero(); + } + @Test void actualCreateAndSameCommitGameplayInputHaveDurableGeneratedIdentityAndExactRetry() { var f = fixture(); @@ -643,6 +787,12 @@ private static TemplateConfigSource.Config config(Fixture f, String inputs) { + "},\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}},\"supportedSettings\":[]}"); } + private static String automationInventory() { + return "{\"schema\":\"automation-authored-source-inventory/v1\"," + + "\"families\":{\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"; + } + private DraftCommitBinding binding(Fixture f, String payload, String scope, String epoch) { return binding( f, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 974614273f..83608d7396 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -110,6 +110,7 @@ import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalReadGrpcService; import net.firedevops.firemud.gamedesign.draft.GameDesignSelectedDraftPublicationReadGrpcService; import net.firedevops.firemud.gamedesign.draft.GameDesignWorldSourceCommitService; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.entity.GameAsset; @@ -136,8 +137,10 @@ import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository; import net.firedevops.firemud.gamedesign.publication.TemplateReferenceRepository; import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptParticipantDigestRepository; @@ -150,16 +153,21 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.repository.VersionTemplateRemapSetRepository; import net.firedevops.firemud.gamedesign.service.AssetExportService.SelectedExportResult; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; import net.firedevops.firemud.gamedesign.service.PublishAttemptService; import net.firedevops.firemud.gamedesign.service.PublishGateService; import net.firedevops.firemud.gamedesign.service.RecordedParticipantDigestService; +import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; import net.firedevops.firemud.gamedesign.service.impl.AssetExportServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateGrpcService; import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateService; +import net.firedevops.firemud.gamedesign.service.impl.CompleteLaunchBindingServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.LaunchDescriptorServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.PublishedReleaseBundleServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.TemplateRemapSetServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; import net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; @@ -227,15 +235,17 @@ /** * Real original GD+World source settlement and Account/GL intake-to-GD-receipt, followed by actual - * selected inventory/export, the owner-local publication finalizer, and descriptor SQL storage. The - * distinct Account publication order comes from the actual Account owner fixture; its inbound Game - * Design peer and upstream selection/platform/legal evidence are supplied by test context. The - * immutable selection read and held-order reads use loopback mTLS. World freeze, immutable - * inventory and published selector use their actual owner services over loopback mTLS, with the - * canonical frozen selector captured owner-locally from the committed freeze and retained APPLIED - * graph. Entity/Automation participant digests, in-memory S3 and the StartSession Account - * projection remain test doubles. This is not a complete four-owner authenticated release, runtime - * launch, activation or registration proof. + * selected inventory/export, the owner-local publication finalizer, descriptor SQL storage, and the + * owner-local complete launch-binding read. The distinct Account publication order comes from the + * actual Account owner fixture; its inbound Game Design peer and upstream selection/platform/legal + * evidence are supplied by test context. The immutable selection read and held-order reads use + * loopback mTLS. World freeze, immutable inventory and published selector use their actual owner + * services over loopback mTLS, with the canonical frozen selector captured owner-locally from the + * committed freeze and retained APPLIED graph. Entity/Automation participant digests, in-memory S3 + * and the StartSession Account projection remain test doubles. The complete launch-binding read + * uses the actual owner implementation in an explicitly established read-only repeatable-read + * snapshot, but does not exercise the authenticated GetCompleteLaunchBinding transport. This is not + * a complete four-owner authenticated release, runtime launch, activation or registration proof. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -440,16 +450,36 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex "genuine-selected-export-tenant", "genuine-selected-export-world", "Genuine selected export source")); - var worldIntakeRequest = - new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( - 1, - NAMESPACE, - UUID.randomUUID(), - worldSource.canonicalTenantId(), - worldSource.worldSlug(), - worldSource.operationId(), - worldSource.evidenceDigest()); + assertThat(worldSource.canonicalTenantId()).isEqualTo(gd.target().canonicalTenantId()); + assertThat(worldSource.sourceGameRowId()).isEqualTo(gd.target().sourceGameRowId()); + assertThat(worldSource.sourceGameTenantKey()).isEqualTo(gd.target().sourceGameTenantKey()); + assertThat(worldSource.provenanceKind()).isEqualTo(gd.target().sourceProvenanceKind()); + var worldSourceDeliveryRepository = new GameAuthoredWorldSourceDeliveryRepository(gd.dsl()); + var originalWorldSourceDelivery = + worldSourceDeliveryRepository.read(worldSource.operationId()).orElseThrow(); + assertThat(originalWorldSourceDelivery.source()).isEqualTo(worldSource); + assertThat(originalWorldSourceDelivery.acknowledgedReceipt()).isEmpty(); + assertThat(originalWorldSourceDelivery.request().intakeRequestId()) + .isNotEqualTo(worldSource.operationId()); + assertThat(originalWorldSourceDelivery.request().sourceOperationId()) + .isEqualTo(worldSource.operationId()); + assertThat(originalWorldSourceDelivery.request().expectedSourceEvidenceDigest()) + .isEqualTo(worldSource.evidenceDigest()); + var worldIntakeRequest = originalWorldSourceDelivery.request(); var worldIntakeReceipt = worldIntakeClient.intake(worldIntakeRequest); + assertThat(worldIntakeReceipt.intakeRequestId()) + .isEqualTo(originalWorldSourceDelivery.request().intakeRequestId()); + assertThat(worldIntakeReceipt.requestDigest()) + .isEqualTo(WorldAuthoredSourceIntakeGrpcCodec.requestDigest(worldIntakeRequest)); + var acknowledgedWorldSourceDelivery = + gd.transaction( + () -> + worldSourceDeliveryRepository.acknowledge( + originalWorldSourceDelivery, worldIntakeReceipt)); + assertThat(acknowledgedWorldSourceDelivery.acknowledgedReceipt()) + .contains(worldIntakeReceipt); + assertThat(worldSourceDeliveryRepository.read(worldSource.operationId()).orElseThrow()) + .isEqualTo(acknowledgedWorldSourceDelivery); var worldIdentityRequest = new WorldAuthoredVersionIdentityEvidence.Request( 1, @@ -1173,6 +1203,170 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(firstDescriptorBinding.descriptor().launchDescriptorId()).isNotBlank(); assertThat(firstDescriptorBinding.associationRead().association().associationDigest()) .isEqualTo(association.digest()); + var expectedAuthoredWorldBinding = + firstDescriptorBinding.descriptor().authoredWorldBinding(); + + var versionRepository = new VersionRepository(gd.dsl()); + var launchDescriptorRepository = new LaunchDescriptorRepository(gd.dsl()); + TemplateRemapSetService remapSetService = + new TemplateRemapSetServiceImpl( + new VersionTemplateRemapSetRepository(gd.dsl()), versionRepository); + var launchDescriptorService = + new LaunchDescriptorServiceImpl( + new GameTemplateRepository(gd.dsl()), + launchDescriptorRepository, + versionRepository, + releaseService, + remapSetService, + sourceRepository, + new ObjectMapper()); + ReflectionTestUtils.setField(launchDescriptorService, "workloadNamespace", NAMESPACE); + CompleteLaunchBindingService completeLaunchBindingService = + new CompleteLaunchBindingServiceImpl( + launchDescriptorService, sourceRepository, releaseService, versionRepository); + ReflectionTestUtils.setField( + completeLaunchBindingService, "workloadNamespace", NAMESPACE); + UUID completeBindingReadRequestId = UUID.randomUUID(); + var persistedLaunchDescriptor = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, gd.target().canonicalTenantId(), controlPlaneRequestId) + .orElseThrow(); + List completeBindingOwnerRowsBefore = + completeBindingOwnerRowVersions( + gd.dsl(), + persistedLaunchDescriptor.getId(), + release.id(), + gd.target().gameDesignVersionRowId(), + worldSource.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId); + var completeBinding = + readCompleteLaunchBindingInOwnerSnapshot( + gd, + completeLaunchBindingService, + completeBindingReadRequestId, + gd.target().canonicalTenantId(), + worldSource.worldSlug(), + controlPlaneRequestId, + expectedAuthoredWorldBinding.requestDigest(), + expectedAuthoredWorldBinding.resultDigest()); + assertThat(completeBinding.descriptor()).isEqualTo(expectedAuthoredWorldBinding); + completeBinding.releaseAttestation().requireValid(completeBinding.descriptor()); + assertThat(completeBinding.releaseAttestation().descriptorResultDigest()) + .isEqualTo(expectedAuthoredWorldBinding.resultDigest()); + assertThat(completeBinding.releaseAttestation().worldStartLocationEvidence()) + .isEqualTo(release.worldPublishedStartLocationEvidence()); + var completeWorldSelector = + completeBinding.releaseAttestation().worldStartLocationEvidence(); + assertThat(completeWorldSelector.request().canonicalTenantId()) + .isEqualTo(gd.target().canonicalTenantId()); + assertThat(completeWorldSelector.request().canonicalVersionId()) + .isEqualTo(gd.target().canonicalVersionId()); + assertThat(completeWorldSelector.request().publicationRequestId()) + .isEqualTo(intent.publishRequestId()); + assertThat(completeWorldSelector.request().publicationFence()) + .isEqualTo(actualFreeze.acknowledgement().publicationFence()); + assertThat(completeWorldSelector.request().appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + assertThat(completeWorldSelector.request().contentDigest()) + .isEqualTo(retainedWorldDigest.contentDigest()); + assertThat(completeWorldSelector.request().digestSchemaVersion()) + .isEqualTo(retainedWorldDigest.digestSchemaVersion()); + assertThat(completeWorldSelector.request().worldAffectedTuples()).isNotEmpty(); + var completeWorldParticipant = + completeBinding.releaseAttestation().participantDigests().getFirst(); + assertThat(completeWorldParticipant.participantKey()).isEqualTo("WORLD_MANAGEMENT"); + assertThat(completeWorldParticipant.appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + assertThat(completeWorldParticipant.contentDigest()) + .isEqualTo(retainedWorldDigest.contentDigest()); + assertThat(completeWorldParticipant.digestSchemaVersion()) + .isEqualTo(retainedWorldDigest.digestSchemaVersion()); + var completeGameLogicParticipant = + completeBinding.releaseAttestation().participantDigests().stream() + .filter(participant -> "GAME_LOGIC".equals(participant.participantKey())) + .findFirst() + .orElseThrow(); + assertThat(completeGameLogicParticipant.appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + assertThat(completeGameLogicParticipant.contentDigest()) + .isEqualTo(actualGameLogicDigest.contentDigest()); + assertThat(completeGameLogicParticipant.digestSchemaVersion()) + .isEqualTo(actualGameLogicDigest.digestSchemaVersion()); + assertThat(completeGameLogicParticipant.abilitySchemaDigest()) + .isEqualTo(actualGameLogicDigest.abilitySchemaDigest()); + + var completeBindingRetry = + readCompleteLaunchBindingInOwnerSnapshot( + gd, + completeLaunchBindingService, + completeBindingReadRequestId, + gd.target().canonicalTenantId(), + worldSource.worldSlug(), + controlPlaneRequestId, + expectedAuthoredWorldBinding.requestDigest(), + expectedAuthoredWorldBinding.resultDigest()); + assertThat(completeBindingRetry).isEqualTo(completeBinding); + + assertThatThrownBy( + () -> + readCompleteLaunchBindingInOwnerSnapshot( + gd, + completeLaunchBindingService, + completeBindingReadRequestId, + gd.target().canonicalTenantId(), + worldSource.worldSlug(), + controlPlaneRequestId, + changedDigest(expectedAuthoredWorldBinding.requestDigest()), + expectedAuthoredWorldBinding.resultDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + readCompleteLaunchBindingInOwnerSnapshot( + gd, + completeLaunchBindingService, + completeBindingReadRequestId, + gd.target().canonicalTenantId(), + worldSource.worldSlug(), + controlPlaneRequestId, + expectedAuthoredWorldBinding.requestDigest(), + changedDigest(expectedAuthoredWorldBinding.resultDigest()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + readCompleteLaunchBindingInOwnerSnapshot( + gd, + completeLaunchBindingService, + completeBindingReadRequestId, + UUID.randomUUID(), + worldSource.worldSlug(), + controlPlaneRequestId, + expectedAuthoredWorldBinding.requestDigest(), + expectedAuthoredWorldBinding.resultDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + readCompleteLaunchBindingInOwnerSnapshot( + gd, + completeLaunchBindingService, + completeBindingReadRequestId, + gd.target().canonicalTenantId(), + "genuine-selected-export-world-substitute", + controlPlaneRequestId, + expectedAuthoredWorldBinding.requestDigest(), + expectedAuthoredWorldBinding.resultDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + completeBindingOwnerRowVersions( + gd.dsl(), + persistedLaunchDescriptor.getId(), + release.id(), + gd.target().gameDesignVersionRowId(), + worldSource.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId)) + .containsExactlyElementsOf(completeBindingOwnerRowsBefore); var replay = withGameSessionPeer( @@ -1915,6 +2109,70 @@ private static String sha256(byte[] bytes) { } } + private static String changedDigest(String digest) { + if (digest == null || !digest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Expected a sha256-prefixed digest"); + } + char replacement = digest.charAt(digest.length() - 1) == '0' ? '1' : '0'; + return digest.substring(0, digest.length() - 1) + replacement; + } + + private static CompleteLaunchBindingDto readCompleteLaunchBindingInOwnerSnapshot( + Store owner, + CompleteLaunchBindingService service, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + TransactionTemplate ownerSnapshot = new TransactionTemplate(owner.transactions()); + ownerSnapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerSnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + ownerSnapshot.setReadOnly(true); + return Objects.requireNonNull( + ownerSnapshot.execute( + ignored -> + service.getCompleteLaunchBinding( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest))); + } + + private static List completeBindingOwnerRowVersions( + DSLContext dsl, + long launchDescriptorRowId, + long releaseBundleId, + long versionRowId, + UUID sourceOperationId, + UUID canonicalTenantId, + String controlPlaneRequestId) { + return List.of( + dsl.fetchSingle( + "select xmin::text from launch_descriptor where id = ?", launchDescriptorRowId) + .get(0, String.class), + dsl.fetchSingle( + "select xmin::text from published_release_bundle where id = ?", releaseBundleId) + .get(0, String.class), + dsl.fetchSingle("select xmin::text from version where id = ?", versionRowId) + .get(0, String.class), + dsl.fetchSingle( + "select xmin::text from game_design_authored_world_source_operations where operation_id = ?", + sourceOperationId) + .get(0, String.class), + dsl.fetchSingle( + "select xmin::text from game_design_start_session_launch_descriptor_binding " + + "where target_namespace = ? and canonical_tenant_id = ? " + + "and control_plane_request_id = ?", + NAMESPACE, + canonicalTenantId, + controlPlaneRequestId) + .get(0, String.class)); + } + private record Store( DSLContext dsl, DataSourceTransactionManager transactions, diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java index 43cb4cb5fb..dffb88d230 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java @@ -8,6 +8,7 @@ import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; import org.junit.jupiter.api.Test; class TemplateConfigSourceTest { @@ -138,12 +139,129 @@ void siblingDispatchDoesNotInventUnknownSourceKindsOrChangeOriginalBinding() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void automationInventoryUsesItsExactVersionedOperationAndPreservesLegacySnapshotBytes() { + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String payload = + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, inventory); + assertThat(CommandSource.tree(payload).path("inventory").isObject()).isTrue(); + assertThat(payload).doesNotContain("inventoryJson"); + var authored = binding(payload); + var mutation = TemplateConfigSource.mutations(authored).getFirst(); + assertThat(mutation.operation()) + .isEqualTo(TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY); + assertThat(mutation.templateId()).isNull(); + assertThat(mutation.templateName()).isNull(); + assertThat(mutation.config()).isNull(); + + var declarations = TemplateConfigSource.replayOwnerInventoryDeclarations(List.of(), authored); + var inherited = + TemplateConfigSource.replayOwnerInventoryDeclarations( + declarations, binding(CommandSource.deletePayload("absent"))); + assertThat(inherited).containsExactly(declarations.getFirst()); + assertThat(inherited.getFirst().sourceBinding()).isSameAs(authored); + + var oldBinding = + binding( + TemplateConfigSource.createPayload( + "Starter", new TemplateConfigSource.Config(config()))); + var oldEntries = + TemplateConfigSource.replay( + List.of(), oldBinding, Map.of(oldBinding.revisions().getFirst().revisionId(), "7")); + var oldSnapshot = + new TemplateConfigSourceSnapshot(oldBinding, "1", null, UUID.randomUUID(), oldEntries); + String legacySnapshotBytes = + CommandSource.canonical( + Map.of( + "schema", + TemplateConfigSourceSnapshot.SCHEMA, + "bindingJson", + oldBinding.canonicalJson(), + "bindingDigest", + oldBinding.digest(), + "sourceEpoch", + "1", + "inheritedCommitId", + "", + "genesisReceiptId", + oldSnapshot.genesisReceiptId().toString(), + "entries", + oldEntries.stream().map(TemplateConfigSource.Entry::object).toList())); + assertThat(oldSnapshot.canonicalJson()).isEqualTo(legacySnapshotBytes); + assertThat(oldSnapshot.canonicalJson()) + .contains("\"schema\":\"game-design-template-config-source-snapshot/v1\"") + .doesNotContain("ownerSourceInventoryDeclarations"); + assertThat(TemplateConfigSourceSnapshot.fromStored(oldSnapshot.canonicalJson())) + .isEqualTo(oldSnapshot); + + var v2Snapshot = + new TemplateConfigSourceSnapshot( + authored, "1", null, UUID.randomUUID(), List.of(), declarations); + assertThat(v2Snapshot.canonicalJson()) + .contains("\"schema\":\"game-design-template-config-source-snapshot/v2\"") + .contains("ownerSourceInventoryDeclarations") + .contains(authored.requestId().toString()) + .contains(authored.commitId().toString()); + assertThat(TemplateConfigSourceSnapshot.fromStored(v2Snapshot.canonicalJson())) + .isEqualTo(v2Snapshot); + } + + @Test + void ownerInventoryOperationRejectsMissingUnknownAndUnsupportedContent() { + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String valid = + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, inventory); + String missingInventory = + CommandSource.canonical( + Map.of( + "schemaVersion", + 2, + "revisionKind", + TemplateConfigSource.REVISION_KIND, + "operation", + "DECLARE_OWNER_SOURCE_INVENTORY", + "owner", + "AUTOMATION_SCRIPTING")); + assertThatThrownBy(() -> TemplateConfigSource.mutations(binding(missingInventory))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + TemplateConfigSource.mutations( + binding(valid.replace("AUTOMATION_SCRIPTING", "ENTITY_MANAGEMENT")))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationAuthoredSourceInventoryDeclaration.parse( + automationInventory() + .replace("\"SCRIPT_DEFINITIONS\":[]", "\"SCRIPT_DEFINITIONS\":[{}]"))) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + TemplateConfigSourceSnapshot.fromStored( + new TemplateConfigSourceSnapshot( + binding(CommandSource.deletePayload("absent")), + "0", + null, + UUID.randomUUID(), + List.of()) + .canonicalJson()) + .ownerSourceInventoryDeclarations()) + .isEmpty(); + } + private static String config() { return "{\"schemaVersion\":1,\"baseVersionId\":\"" + VERSION + "\",\"world\":{\"regions\":[],\"rooms\":[]},\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]},\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}},\"supportedSettings\":[]}"; } + private static String automationInventory() { + return "{\"schema\":\"automation-authored-source-inventory/v1\"," + + "\"families\":{\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"; + } + private static DraftCommitBinding binding(String... payloads) { var revisions = new ArrayList(); for (int i = 0; i < payloads.length; i++) From 0020e63ad8f617e5957f15e7d1d2fea599abc5eb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 04:48:15 +1300 Subject: [PATCH 056/129] Integrate typed Entity authored inventory and authenticated binding proof --- .../game-design-service/game-templates.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 +- ...ConfigOwnerSourceInventoryDeclaration.java | 79 ++++- .../publication/TemplateConfigSource.java | 114 +++++-- .../TemplateConfigSourceRepository.java | 12 +- ...template_config_owner_source_inventory.sql | 149 +++++++++ ...teConfigSourcePostgresIntegrationTest.java | 290 +++++++++++++++++- ...licationExportPostgresIntegrationTest.java | 146 ++++++++- .../publication/TemplateConfigSourceTest.java | 105 +++++++ 9 files changed, 833 insertions(+), 66 deletions(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V68__entity_template_config_owner_source_inventory.sql diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 10d6a3f7b2..0898a3bca0 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -63,7 +63,7 @@ World `regions[]` entries carry `regionTemplateId`; `rooms[]` carry `roomTemplat Automation's supported template sources are `SCRIPT` (including its owner-managed event bindings) and `SCRIPT_PATCH`; it has no `RULESET` identity. A script reference carries the current exact owner key `scriptId` (the persisted `name` string) under the template's selected tenant/base-version scope. The optional pinned `scriptPatchVersion` is the exact persisted nonblank patch string, paired with the same `baseVersionId`; it is not a UUID. These raw strings describe current owner keys, not proof of same-base publication or exact selected-version readback. The [Automation runtime/data contract](../automation-scripting-service/runtime-and-data.md) and [API contract](../automation-scripting-service/api-contracts.md) own script identity and patch semantics. Current code does not establish the canonical-UUID-to-owner-version binding or all required publication/readiness predicates; unsupported or unreadable entries deny selected-release completeness rather than implying an empty script family. -Automation's authored source inventory is a separate versioned `TEMPLATE_CONFIG` source operation, `DECLARE_OWNER_SOURCE_INVENTORY`, bound to the actual Draft commit. The revision remains owned by `GAME_DESIGN_CONTROL_PLANE`; its `AUTOMATION_SCRIPTING` declaration identifies the content owner, not an Automation commit participant. It carries no `templateId` and creates no `game_templates` row. Game Design retains its original request, commit, revision ID/order, content owner, and binding provenance in template source snapshot v2 and publication capture. The declaration remains authored content only; absence is unavailable evidence, and the declaration does not replace Automation owner readback or qualify publication. Its family schema and empty-only acceptance are owned by [Automation](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory). +Automation and Entity authored source inventories are separate versioned `TEMPLATE_CONFIG` source operations, `DECLARE_OWNER_SOURCE_INVENTORY`, bound to the actual Draft commit. Automation retains its authored operation payload at `schemaVersion: 2`; Entity uses `schemaVersion: 3` so the existing Automation revision bytes keep their established meaning. Each revision remains owned by `GAME_DESIGN_CONTROL_PLANE`; `AUTOMATION_SCRIPTING` or `ENTITY_MANAGEMENT` identifies the content owner, not an owner commit participant. These operations carry no `templateId` and create no `game_templates` row. Game Design retains each declaration's original request, commit, revision ID/order, content owner, typed inventory content, and binding provenance in template source snapshot v2 and publication capture. A missing declaration remains unavailable evidence. Neither declaration replaces its owner's exact source readback, proves completeness of any inbound selected-source closure, or qualifies publication. The family schema and empty-only acceptance remain owned by [Automation](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) and [Entity Management](../entity-management-service/runtime-and-data.md#selected-entity-authored-source-inventory-empty-only-v1). Game Logic owns the version-scoped gameplay rules/configuration, not Automation. The authored `gameLogic.inputs[]` entries select Game Design-owned gameplay inputs by exact `{family, key, revisionId}` from the supported authored gameplay source families. They do not serialize Game Logic's derived receipt or invent per-rule IDs. For publication, Game Logic's genuine owner-retained receipt must be independently joined to the exact unchanged tenant, `baseVersionId`, and selected commit after source settlement and authorized intake. A missing receipt, changed input or commit, or merely latest receipt cannot satisfy the join; exact retries recover the original retained result. [Game Logic runtime/data](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) defines the owner boundary and receipt semantics; this document does not define a receipt schema. Retaining and resolving authored input references does not establish that separate receipt or join, so no complete publishable config is claimed yet. 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 8df3db0c3d..856d91fd1f 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 @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a Published `97174b31be2ed08440be1a271cc00359614abaf6` [Validation run 37945686843](https://github.com/benhook1013/FireMUD/actions/runs/37945686843) executed 254 Account and 207 World PostgreSQL cases with no failures, errors or skips. Both previously failing Account receipt-confirmation fixtures passed with the production V90/V92 guards and original acknowledgement bounds unchanged. Game Design executed 146 PostgreSQL cases with one failure and no errors or skips: the genuine export fixture invented a new World intake request ID instead of using the original durable Game Design delivery claim. The local correction uses that original request, World’s actual receipt and Game Design’s actual acknowledgement, without weakening the selected-source readback guard. Separate legacy descriptor (8), complete launch-binding (6), and genuine GD+World source-settlement (3) cases passed; they do not establish success of the failed genuine export. The actual CI checkout is synthetic merge `421b0196ccffff96405aab1c687d2455c52ede60`, tree `62188ebd390fdd8d4ed71d4a245c5195a30eae3a`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact published source, not the intended integration parent. -The current source-inventory batch adds an actual authored Automation `TEMPLATE_CONFIG` revision, immutable original revision provenance and snapshot v2; it creates no template row or Automation commit participation. Entity's mandatory 23-family empty-only declaration and explicit equipment non-applicability have a shared parser and canonical owner contract, but are not yet integrated into the Game Design source operation. Common's full check executes 457 unit cases successfully. Game Design's schema generation, affected full check, boot JAR and documentation validation pass in 1m 40s with 524 unit cases executed; all 145 local integration cases compile/discover but skip without Docker. The new declaration migration and source/retry/inheritance cases therefore have no physical PostgreSQL proof yet. Neither declaration is an owner receipt. Separate Entity/Automation Account-authorized intake, held current-authority retention, and authenticated full selected World/inbound closure remain missing. World's exact frozen six-family topology inventory exposes typed ITEM/NPC spawn inputs, but does not supply the required selected loot/behavior/hook closure; a zero topology count cannot certify those missing producers. The genuine fixture also adds exact owner-local complete-launch-binding readback and substitution/no-mutation assertions; it does not exercise the authenticated transport or enable launch. All four Gameplay handoffs and activation remain open. +The current source-inventory construction retains genuinely authored Automation and Entity `TEMPLATE_CONFIG` declarations, immutable original revision provenance and snapshot v2; it creates no template row or Entity/Automation commit participation. Automation's published operation bytes remain schema version 2; Entity's new closed operation uses version 3 and its mandatory 23-family empty-only declaration with explicit equipment non-applicability. Forward migration V68 extends the owner guard without rewriting V67 or historical source bytes. The added PostgreSQL definition checks original Automation content, binding, application bytes and v1/v2 snapshot readback through that upgrade, then genuine Entity application, inheritance and exact retry. Common's preceding full check executed 457 unit cases successfully. The combined Game Design schema generation, full check, boot JAR and documentation gate passes in 2m 3s with 525 unit cases executed; all 146 local integration cases compile/discover but skip without Docker. The new migration and transport definitions therefore have no physical execution proof yet. Neither declaration is an owner receipt. Separate Entity/Automation Account-authorized intake, held current-authority retention, and authenticated full selected World/inbound closure remain missing. World's exact frozen six-family topology inventory exposes typed ITEM/NPC spawn inputs, but does not supply selected loot/behavior/hook closure; a zero topology count cannot certify those missing producers. The genuine fixture now invokes the real complete-launch-binding handler and World mTLS client, with exact readback/retry, peer-first denial, substitution and no-mutation assertions. Its Account StartSession projection, Entity/Automation participation and object-store transport remain explicit test doubles; production certificate mounting, current Game Session `STARTING` evidence and World held commit-authority verification remain unproved. All four Gameplay handoffs and activation remain open. Published `9f287e05e06b87adc3db79984b2e047e5d5b819f` [Validation run 37939078493](https://github.com/benhook1013/FireMUD/actions/runs/37939078493) executed 146 Game Design PostgreSQL cases with one failure, 254 Account cases with one failure, and 207 World cases with no failures; all three suites report zero skips and errors. The three genuine GD+World source/settlement cases, genuine Game Logic intake case, approved-remap retention correction and eight legacy descriptor persistence/retry/migration cases passed. The genuine selected export/descriptor case failed before export because its stipulated World evidence supplied a prefixed content hash to a bare-hex field. Since that run, the local construction has replaced the stipulated Account publication-order and World freeze/inventory/selector evidence with the actual owner reads and adds canonical topology capture after freeze. This new composition has no physical proof yet. Account's failure moved to the physical-confirmation/independent-read case and again denied at V90's conservative coverage prerequisite: insert `0/7EDFE48` exceeded initial/final flush `0/7EDFE08` while the original bound remained unchanged. A bounded fixture diagnosis is separate from source/release construction. Overseer deferred production WAL-locator adoption; the prototype, original JVM acknowledgement/time bounds, V90/V92 recovery semantics and PostgreSQL-version guards remain unchanged. The actual synthetic checkout is `1822fbae8dc9f6c4409ccc9515a99ee5e5f42e99`, tree `dc3142f6c4284288a43ed71d97632c35ee4afe09`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published source. This is exact-source execution, not intended-parent alignment, a genuine complete release or activation. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java index b41606fca6..9e296291d6 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java @@ -6,19 +6,45 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; import tools.jackson.databind.JsonNode; -/** Automation's actual authored inventory content and its immutable original Draft provenance. */ +/** Typed owner-authored inventory content and its immutable original Draft provenance. */ public record TemplateConfigOwnerSourceInventoryDeclaration( Owner owner, AutomationAuthoredSourceInventoryDeclaration inventory, + EntityAuthoredSourceInventoryDeclaration entityInventory, DraftCommitBinding sourceBinding, String revisionOrder, UUID revisionId) { + public TemplateConfigOwnerSourceInventoryDeclaration( + Owner owner, + AutomationAuthoredSourceInventoryDeclaration inventory, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId) { + this(owner, inventory, null, sourceBinding, revisionOrder, revisionId); + } + + public TemplateConfigOwnerSourceInventoryDeclaration( + Owner owner, + EntityAuthoredSourceInventoryDeclaration inventory, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId) { + this(owner, null, inventory, sourceBinding, revisionOrder, revisionId); + } + public TemplateConfigOwnerSourceInventoryDeclaration { - if (owner != Owner.AUTOMATION_SCRIPTING) - throw new IllegalArgumentException("Only Automation source inventory is supported"); - Objects.requireNonNull(inventory); + if (owner == Owner.AUTOMATION_SCRIPTING) { + if (inventory == null || entityInventory != null) + throw new IllegalArgumentException("Automation owner requires its typed inventory"); + } else if (owner == Owner.ENTITY_MANAGEMENT) { + if (entityInventory == null || inventory != null) + throw new IllegalArgumentException("Entity owner requires its typed inventory"); + } else { + throw new IllegalArgumentException("Unsupported owner source inventory content"); + } Objects.requireNonNull(sourceBinding); if (revisionOrder == null || !revisionOrder.matches("0|[1-9][0-9]*")) throw new IllegalArgumentException("Exact owner source inventory revision order required"); @@ -30,8 +56,11 @@ public record TemplateConfigOwnerSourceInventoryDeclaration( r -> r.revisionId().equals(revisionId) && r.revisionOrder().equals(revisionOrder)) .findFirst() .orElseThrow(); - if (!TemplateConfigSource.ownerInventoryPayload(owner, inventory) - .equals(CommandSource.canonical(CommandSource.tree(revision.payload())))) + String expectedPayload = + owner == Owner.AUTOMATION_SCRIPTING + ? TemplateConfigSource.ownerInventoryPayload(owner, inventory) + : TemplateConfigSource.ownerInventoryPayload(owner, entityInventory); + if (!expectedPayload.equals(CommandSource.canonical(CommandSource.tree(revision.payload())))) throw new IllegalArgumentException( "Owner inventory differs from its exact original source revision"); } @@ -39,7 +68,7 @@ public record TemplateConfigOwnerSourceInventoryDeclaration( Map object() { return Map.of( "owner", owner.name(), - "inventoryJson", inventory.canonicalJson(), + "inventoryJson", inventoryJson(), "sourceBindingJson", sourceBinding.canonicalJson(), "sourceBindingDigest", sourceBinding.digest(), "revisionOrder", revisionOrder, @@ -56,14 +85,36 @@ static TemplateConfigOwnerSourceInventoryDeclaration fromStored(JsonNode node) { "revisionOrder", "revisionId"); Owner owner = Owner.valueOf(CommandSource.requiredStoredText(node, "owner")); - return new TemplateConfigOwnerSourceInventoryDeclaration( - owner, - AutomationAuthoredSourceInventoryDeclaration.parse( - CommandSource.requiredStoredText(node, "inventoryJson")), + String inventoryJson = CommandSource.requiredStoredText(node, "inventoryJson"); + var binding = DraftCommitBinding.fromStored( CommandSource.requiredStoredText(node, "sourceBindingJson"), - CommandSource.requiredStoredText(node, "sourceBindingDigest")), - CommandSource.requiredStoredText(node, "revisionOrder"), - TemplateConfigSource.uuid(CommandSource.requiredStoredText(node, "revisionId"))); + CommandSource.requiredStoredText(node, "sourceBindingDigest")); + String revisionOrder = CommandSource.requiredStoredText(node, "revisionOrder"); + UUID revisionId = + TemplateConfigSource.uuid(CommandSource.requiredStoredText(node, "revisionId")); + return switch (owner) { + case AUTOMATION_SCRIPTING -> + new TemplateConfigOwnerSourceInventoryDeclaration( + owner, + AutomationAuthoredSourceInventoryDeclaration.parse(inventoryJson), + binding, + revisionOrder, + revisionId); + case ENTITY_MANAGEMENT -> + new TemplateConfigOwnerSourceInventoryDeclaration( + owner, + EntityAuthoredSourceInventoryDeclaration.parse(inventoryJson), + binding, + revisionOrder, + revisionId); + default -> throw new IllegalArgumentException("Unsupported owner source inventory content"); + }; + } + + String inventoryJson() { + return owner == Owner.AUTOMATION_SCRIPTING + ? inventory.canonicalJson() + : entityInventory.canonicalJson(); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java index 367bf6c17a..df3e36e8f9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; import tools.jackson.databind.JsonNode; @@ -148,7 +149,8 @@ public record Mutation( String templateName, Config config, Owner declaredOwner, - AutomationAuthoredSourceInventoryDeclaration inventory) { + AutomationAuthoredSourceInventoryDeclaration inventory, + EntityAuthoredSourceInventoryDeclaration entityInventory) { public Mutation( DraftCommitBinding binding, String revisionOrder, @@ -166,6 +168,7 @@ public Mutation( templateName, config, null, + null, null); } @@ -176,13 +179,16 @@ public Mutation( if (templateId != null || templateName != null || config != null - || declaredOwner != Owner.AUTOMATION_SCRIPTING - || inventory == null) + || declaredOwner == null + || !Set.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT).contains(declaredOwner) + || (declaredOwner == Owner.AUTOMATION_SCRIPTING + ? inventory == null || entityInventory != null + : entityInventory == null || inventory != null)) throw new IllegalArgumentException( - "Owner inventory declaration carries only Automation authored content"); + "Owner inventory declaration carries only its supported owner's authored content"); new TemplateConfigOwnerSourceInventoryDeclaration( - declaredOwner, inventory, binding, revisionOrder, revisionId); - } else if (declaredOwner != null || inventory != null) { + declaredOwner, inventory, entityInventory, binding, revisionOrder, revisionId); + } else if (declaredOwner != null || inventory != null || entityInventory != null) { throw new IllegalArgumentException("Template row mutations carry no owner inventory"); } else if (operation == OperationKind.CREATE) { if (templateId != null @@ -212,14 +218,22 @@ public Mutation( .findFirst() .orElseThrow(); String expected = - payloadFor(operation, templateId, templateName, config, declaredOwner, inventory); + payloadFor( + operation, + templateId, + templateName, + config, + declaredOwner, + inventory, + entityInventory); if (!expected.equals(CommandSource.canonical(CommandSource.tree(revision.payload())))) throw new IllegalArgumentException( "Template config differs from its exact original revision"); } public String payload() { - return payloadFor(operation, templateId, templateName, config, declaredOwner, inventory); + return payloadFor( + operation, templateId, templateName, config, declaredOwner, inventory, entityInventory); } public boolean changesTemplateRow() { @@ -229,9 +243,15 @@ public boolean changesTemplateRow() { public TemplateConfigOwnerSourceInventoryDeclaration ownerInventoryDeclaration() { return operation == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY ? new TemplateConfigOwnerSourceInventoryDeclaration( - declaredOwner, inventory, binding, revisionOrder, revisionId) + declaredOwner, inventory, entityInventory, binding, revisionOrder, revisionId) : null; } + + public String inventoryJson() { + if (inventory != null) return inventory.canonicalJson(); + if (entityInventory != null) return entityInventory.canonicalJson(); + throw new IllegalStateException("Mutation has no owner inventory content"); + } } public record Entry( @@ -292,24 +312,46 @@ public static List mutations(DraftCommitBinding binding) { int schemaVersion = root.path("schemaVersion").isInt() ? root.path("schemaVersion").intValue() : -1; if (operation == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { - if (schemaVersion != 2) - throw new IllegalArgumentException("Unsupported owner inventory source schemaVersion"); fields(root, "schemaVersion", "revisionKind", "operation", "owner", "inventory"); Owner owner = Owner.valueOf(text(root, "owner")); - if (owner != Owner.AUTOMATION_SCRIPTING || !declaredOwners.add(owner)) - throw new IllegalArgumentException("Only one Automation owner inventory is supported"); - result.add( - new Mutation( - binding, - revision.revisionOrder(), - revision.revisionId(), - operation, - null, - null, - null, - owner, - AutomationAuthoredSourceInventoryDeclaration.parse( - CommandSource.canonical(root.path("inventory"))))); + if (!Set.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT).contains(owner) + || !declaredOwners.add(owner)) + throw new IllegalArgumentException("Only one declaration per supported owner is allowed"); + if (owner == Owner.AUTOMATION_SCRIPTING) { + if (schemaVersion != 2) + throw new IllegalArgumentException( + "Unsupported Automation owner inventory source schemaVersion"); + result.add( + new Mutation( + binding, + revision.revisionOrder(), + revision.revisionId(), + operation, + null, + null, + null, + owner, + AutomationAuthoredSourceInventoryDeclaration.parse( + CommandSource.canonical(root.path("inventory"))), + null)); + } else { + if (schemaVersion != 3) + throw new IllegalArgumentException( + "Unsupported Entity owner inventory source schemaVersion"); + result.add( + new Mutation( + binding, + revision.revisionOrder(), + revision.revisionId(), + operation, + null, + null, + null, + owner, + null, + EntityAuthoredSourceInventoryDeclaration.parse( + CommandSource.canonical(root.path("inventory"))))); + } continue; } if (schemaVersion != 1) @@ -399,6 +441,20 @@ public static String ownerInventoryPayload( "inventory", CommandSource.tree(inventory.canonicalJson()))); } + public static String ownerInventoryPayload( + Owner owner, EntityAuthoredSourceInventoryDeclaration inventory) { + if (owner != Owner.ENTITY_MANAGEMENT) + throw new IllegalArgumentException("Only Entity source inventory is supported"); + Objects.requireNonNull(inventory); + return CommandSource.canonical( + Map.of( + "schemaVersion", 3, + "revisionKind", REVISION_KIND, + "operation", OperationKind.DECLARE_OWNER_SOURCE_INVENTORY.name(), + "owner", owner.name(), + "inventory", CommandSource.tree(inventory.canonicalJson()))); + } + public static List replayOwnerInventoryDeclarations( List inherited, @@ -426,12 +482,16 @@ private static String payloadFor( String templateName, Config config, Owner declaredOwner, - AutomationAuthoredSourceInventoryDeclaration inventory) { + AutomationAuthoredSourceInventoryDeclaration inventory, + EntityAuthoredSourceInventoryDeclaration entityInventory) { return switch (operation) { case CREATE -> createPayload(templateName, config); case UPSERT -> upsertPayload(templateId, config); case DELETE -> deletePayload(templateId); - case DECLARE_OWNER_SOURCE_INVENTORY -> ownerInventoryPayload(declaredOwner, inventory); + case DECLARE_OWNER_SOURCE_INVENTORY -> + inventory != null + ? ownerInventoryPayload(declaredOwner, inventory) + : ownerInventoryPayload(declaredOwner, entityInventory); }; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java index d16cd071f8..52dac9b2eb 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java @@ -136,7 +136,6 @@ public Optional apply(DraftCommitBindi for (var mutation : mutations) { if (mutation.operation() == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { - var declaration = mutation.ownerInventoryDeclaration(); dsl.execute( "INSERT INTO game_design_template_config_owner_source_inventory_declaration " + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, revision_id, revision_order, owner, inventory_json, payload_json) " @@ -148,7 +147,7 @@ public Optional apply(DraftCommitBindi mutation.revisionId(), Integer.parseInt(mutation.revisionOrder()), mutation.declaredOwner().name(), - mutation.inventory().canonicalJson(), + mutation.inventoryJson(), mutation.payload()); continue; } @@ -541,7 +540,7 @@ private void verifyOwnerInventoryApplication(DraftCommitBinding binding) { if (!mutation.revisionId().equals(row.get("revision_id", UUID.class)) || Integer.parseInt(mutation.revisionOrder()) != row.get("revision_order", Integer.class) || !mutation.declaredOwner().name().equals(row.get("owner", String.class)) - || !mutation.inventory().canonicalJson().equals(row.get("inventory_json", String.class)) + || !mutation.inventoryJson().equals(row.get("inventory_json", String.class)) || !mutation.payload().equals(row.get("payload_json", String.class))) throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_READBACK_CONFLICT"); } @@ -589,7 +588,7 @@ private void verifyOwnerInventoryDeclarations(TemplateConfigSourceSnapshot snaps if (!sourceBinding.requestId().equals(row.get("request_id", UUID.class)) || !sourceBinding.commitId().equals(row.get("commit_id", UUID.class)) || !mutation.declaredOwner().name().equals(row.get("owner", String.class)) - || !mutation.inventory().canonicalJson().equals(row.get("inventory_json", String.class)) + || !mutation.inventoryJson().equals(row.get("inventory_json", String.class)) || !mutation.payload().equals(row.get("payload_json", String.class))) throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_CHANGED"); effectiveDeclarations.add(mutation.ownerInventoryDeclaration()); @@ -629,10 +628,7 @@ private void verifyOwnerInventoryDeclarations(TemplateConfigSourceSnapshot snaps || !declaration.sourceBinding().requestId().equals(row.get("request_id", UUID.class)) || !declaration.sourceBinding().commitId().equals(row.get("commit_id", UUID.class)) || !declaration.owner().name().equals(row.get("owner", String.class)) - || !declaration - .inventory() - .canonicalJson() - .equals(row.get("inventory_json", String.class)) + || !declaration.inventoryJson().equals(row.get("inventory_json", String.class)) || !mutation.payload().equals(row.get("payload_json", String.class))) throw new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_CHANGED"); } diff --git a/services/game-design-service/src/main/resources/db/migration/V68__entity_template_config_owner_source_inventory.sql b/services/game-design-service/src/main/resources/db/migration/V68__entity_template_config_owner_source_inventory.sql new file mode 100644 index 0000000000..bc132b0ba8 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V68__entity_template_config_owner_source_inventory.sql @@ -0,0 +1,149 @@ +-- Extend the typed owner declaration from Automation to the approved empty-only Entity content. +-- Existing Automation records and payloads are retained without rewriting their original bytes. +-- [jooq ignore start] +DO $$ +DECLARE owner_constraint TEXT; +BEGIN + SELECT conname INTO STRICT owner_constraint + FROM pg_constraint + WHERE conrelid = 'game_design_template_config_owner_source_inventory_declaration'::REGCLASS + AND contype = 'c' + AND pg_get_constraintdef(oid) LIKE '%AUTOMATION_SCRIPTING%'; + EXECUTE format( + 'ALTER TABLE game_design_template_config_owner_source_inventory_declaration DROP CONSTRAINT %I', + owner_constraint); +END; +$$; + +CREATE FUNCTION entity_authored_source_inventory_supported(value JSONB) RETURNS BOOLEAN AS $$ +DECLARE family_name TEXT; +BEGIN + IF jsonb_typeof(value) IS DISTINCT FROM 'object' THEN + RETURN FALSE; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(value)) <> 3 THEN + RETURN FALSE; + END IF; + IF value->>'schema' IS DISTINCT FROM 'entity-authored-source-inventory/v1' + OR jsonb_typeof(value->'schema') IS DISTINCT FROM 'string' + OR value->>'equipmentApplicability' IS DISTINCT FROM 'NOT_APPLICABLE' + OR jsonb_typeof(value->'equipmentApplicability') IS DISTINCT FROM 'string' + OR jsonb_typeof(value->'families') IS DISTINCT FROM 'object' THEN + RETURN FALSE; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(value->'families')) <> 23 THEN + RETURN FALSE; + END IF; + FOREACH family_name IN ARRAY ARRAY[ + 'ACTOR_BODY_LAYOUT_ASSIGNMENTS', + 'ARCHETYPE_ASSIGNMENTS', + 'ARCHETYPE_CONSTRAINTS', + 'ARCHETYPE_ROOTS', + 'BALANCE_CURVE_ATTACHMENTS', + 'BALANCE_CURVE_ROOTS', + 'BODY_LAYOUT_MEMBERSHIPS', + 'BODY_LAYOUT_ROOTS', + 'CRAFTING_INGREDIENT_BINDINGS', + 'CRAFTING_RECIPE_RESULT_BINDINGS', + 'CRAFTING_RECIPE_ROOTS', + 'EQUIPMENT_ATTACHMENT_RULES', + 'EQUIPMENT_CAPABILITIES', + 'EQUIPMENT_COMPATIBILITY_RULES', + 'EQUIPMENT_OCCUPANCY_RULES', + 'EQUIPMENT_SLOT_GROUPS', + 'EQUIPMENT_SLOT_ROOTS', + 'INBOUND_LOOT_BINDINGS', + 'ITEM_TEMPLATE_ROOTS', + 'LOOT_ITEM_MAPPINGS', + 'LOOT_TABLE_ROOTS', + 'NPC_TEMPLATE_ROOTS', + 'OTHER_ACTOR_TEMPLATE_ROOTS' + ] LOOP + IF jsonb_typeof(value->'families'->family_name) IS DISTINCT FROM 'array' THEN + RETURN FALSE; + END IF; + IF jsonb_array_length(value->'families'->family_name) <> 0 THEN + RETURN FALSE; + END IF; + END LOOP; + RETURN TRUE; +END; +$$ LANGUAGE plpgsql IMMUTABLE; +-- [jooq ignore stop] + +ALTER TABLE game_design_template_config_owner_source_inventory_declaration + ADD CONSTRAINT game_design_template_config_owner_source_inventory_owner_supported_check + CHECK (owner IN ('AUTOMATION_SCRIPTING', 'ENTITY_MANAGEMENT')); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION guard_template_config_owner_source_inventory_declaration() RETURNS TRIGGER AS $$ +DECLARE v version%ROWTYPE; c game_design_draft_commit%ROWTYPE; revision JSONB; payload JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'template owner source inventory history is immutable' USING ERRCODE = '23514'; + END IF; + SELECT owner.* INTO STRICT v FROM version owner JOIN game game_source + ON game_source.id = owner.identity_source_game_row_id + AND game_source.tenant_id = owner.identity_source_game_tenant_key AND game_source.tenant_id = owner.tenant_id + AND game_source.canonical_tenant_id = owner.canonical_tenant_id + AND game_source.tenant_identity_provenance_kind = owner.identity_source_provenance_kind + AND game_source.tenant_identity_source_game_id = game_source.id + AND game_source.tenant_identity_source_legacy_tenant_id = game_source.tenant_id + WHERE owner.canonical_tenant_id = NEW.canonical_tenant_id + AND owner.canonical_version_id = NEW.canonical_version_id FOR UPDATE OF owner; + IF v.version_state <> 'DRAFT' OR v.is_script_only OR v.base_version_id IS NOT NULL + OR v.script_patch_version IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM game_design_template_config_source_genesis g + WHERE g.canonical_tenant_id = NEW.canonical_tenant_id + AND g.canonical_version_id = NEW.canonical_version_id AND g.version_id = v.id) THEN + RAISE EXCEPTION 'template owner inventory requires exact canonical full Draft' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection x + WHERE x.canonical_tenant_id = NEW.canonical_tenant_id AND x.canonical_version_id = NEW.canonical_version_id) + OR EXISTS (SELECT 1 FROM version_asset_export_snapshot x WHERE x.tenant_id = v.tenant_id AND x.version_id = v.id) THEN + RAISE EXCEPTION 'template owner inventory is frozen by selected publication or export' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT c FROM game_design_draft_commit + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF NOT EXISTS (SELECT 1 FROM game_design_draft_commit_application_slot slot + WHERE slot.canonical_tenant_id = NEW.canonical_tenant_id AND slot.canonical_version_id = NEW.canonical_version_id + AND slot.request_id = NEW.request_id AND slot.commit_id = NEW.commit_id) + OR NOT EXISTS (SELECT 1 FROM game_design_draft_commit_owner_result r + WHERE r.canonical_tenant_id = NEW.canonical_tenant_id AND r.canonical_version_id = NEW.canonical_version_id + AND r.request_id = NEW.request_id AND r.owner = 'GAME_DESIGN_CONTROL_PLANE' + AND r.status IN ('IN_PROGRESS', 'UNKNOWN')) THEN + RAISE EXCEPTION 'template owner inventory requires active coordinator application' USING ERRCODE = '23514'; + END IF; + SELECT r INTO STRICT revision FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') r + WHERE r->>'revisionId' = NEW.revision_id::TEXT AND r->>'revisionOrder' = NEW.revision_order::TEXT + AND r->>'owner' = 'GAME_DESIGN_CONTROL_PLANE'; + payload := (revision->>'payload')::JSONB; + IF jsonb_typeof(payload) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'template owner inventory requires exact supported owner declaration' USING ERRCODE = '23514'; + END IF; + IF NOT template_config_unique_json((revision->>'payload')::JSON) + OR (SELECT count(*) FROM jsonb_object_keys(payload)) <> 5 + OR payload->>'revisionKind' IS DISTINCT FROM 'TEMPLATE_CONFIG' + OR payload->>'operation' IS DISTINCT FROM 'DECLARE_OWNER_SOURCE_INVENTORY' + OR NEW.owner IS DISTINCT FROM payload->>'owner' + OR jsonb_typeof(payload->'inventory') IS DISTINCT FROM 'object' + OR NEW.inventory_json::JSONB IS DISTINCT FROM payload->'inventory' + OR NOT template_config_unique_json(NEW.inventory_json::JSON) + OR NEW.payload_json IS DISTINCT FROM revision->>'payload' + OR NEW.payload_json::JSONB IS DISTINCT FROM payload + OR NEW.owner NOT IN ('AUTOMATION_SCRIPTING', 'ENTITY_MANAGEMENT') + OR (NEW.owner = 'AUTOMATION_SCRIPTING' + AND (payload->'schemaVersion' IS DISTINCT FROM '2'::JSONB + OR payload->>'owner' IS DISTINCT FROM 'AUTOMATION_SCRIPTING' + OR NOT automation_authored_source_inventory_supported(NEW.inventory_json::JSONB))) + OR (NEW.owner = 'ENTITY_MANAGEMENT' + AND (payload->'schemaVersion' IS DISTINCT FROM '3'::JSONB + OR payload->>'owner' IS DISTINCT FROM 'ENTITY_MANAGEMENT' + OR NOT entity_authored_source_inventory_supported(NEW.inventory_json::JSONB))) THEN + RAISE EXCEPTION 'template owner inventory requires exact supported owner declaration' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java index 4caafdd4a1..c4fa936be8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -13,6 +13,7 @@ import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; @@ -34,6 +35,7 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -200,6 +202,234 @@ void latestSameOrderAutomationDeclarationRetainsItsExactBindingAcrossRetryAndInh .isZero(); } + @Test + void v68AddsEntityWithoutRewritingV67AutomationOrSnapshotHistory() { + var f = fixture("67"); + var initialTemplate = + binding( + f, + TemplateConfigSource.createPayload("Starter", config(f, "[]")), + TemplateConfigSource.SCOPE, + "0"); + apply(f, initialTemplate); + String v1SnapshotJson = + f.dsl + .fetchSingle( + "SELECT snapshot_json FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + initialTemplate.commitId()) + .get("snapshot_json", String.class); + String v1SnapshotDigest = + f.dsl + .fetchSingle( + "SELECT snapshot_digest FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + initialTemplate.commitId()) + .get("snapshot_digest", String.class); + + var automationInventory = + AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String automationPayload = + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, automationInventory); + var automation = binding(f, automationPayload, TemplateConfigSource.SCOPE, "1"); + apply(f, automation); + var automationSource = source(f, automation); + assertThat(automationSource.ownerSourceInventoryDeclarations()).hasSize(1); + assertThat(automationSource.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(automation); + + var retainedDeclaration = + f.dsl.fetchSingle( + "SELECT request_id, commit_id, revision_order, owner, inventory_json, payload_json FROM " + + "game_design_template_config_owner_source_inventory_declaration " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.revisions().getFirst().revisionId()); + String originalInventoryJson = retainedDeclaration.get("inventory_json", String.class); + String originalPayloadJson = retainedDeclaration.get("payload_json", String.class); + assertThat(retainedDeclaration.get("request_id", UUID.class)).isEqualTo(automation.requestId()); + assertThat(retainedDeclaration.get("commit_id", UUID.class)).isEqualTo(automation.commitId()); + assertThat(retainedDeclaration.get("revision_order", Integer.class)).isZero(); + assertThat(retainedDeclaration.get("owner", String.class)).isEqualTo("AUTOMATION_SCRIPTING"); + var originalCommit = + f.dsl.fetchSingle( + "SELECT binding_json, input_digest FROM game_design_draft_commit " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.requestId(), + automation.commitId()); + String originalBindingJson = originalCommit.get("binding_json", String.class); + String originalBindingDigest = originalCommit.get("input_digest", String.class); + var originalAutomationApplication = + f.dsl.fetchSingle( + "SELECT snapshot_json, result_bytes FROM game_design_template_config_source_application " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()); + String v2SnapshotJson = originalAutomationApplication.get("snapshot_json", String.class); + byte[] originalApplicationBytes = + originalAutomationApplication.get("result_bytes", byte[].class); + String v2SnapshotDigest = + f.dsl + .fetchSingle( + "SELECT snapshot_digest FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()) + .get("snapshot_digest", String.class); + assertThat(v2SnapshotJson) + .contains("AUTOMATION_SCRIPTING") + .contains(automation.requestId().toString()) + .contains(automation.commitId().toString()); + + f.tx.executeWithoutResult( + ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(automation).orElseThrow()) + .isEqualTo( + new TemplateConfigSourceSnapshot.Application( + automation, "1", automationSource))); + migrateToLatest(f); + + var migratedDeclaration = + f.dsl.fetchSingle( + "SELECT request_id, commit_id, revision_order, owner, inventory_json, payload_json FROM " + + "game_design_template_config_owner_source_inventory_declaration " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.revisions().getFirst().revisionId()); + assertThat(migratedDeclaration.get("request_id", UUID.class)) + .isEqualTo(retainedDeclaration.get("request_id", UUID.class)); + assertThat(migratedDeclaration.get("commit_id", UUID.class)) + .isEqualTo(retainedDeclaration.get("commit_id", UUID.class)); + assertThat(migratedDeclaration.get("revision_order", Integer.class)) + .isEqualTo(retainedDeclaration.get("revision_order", Integer.class)); + assertThat(migratedDeclaration.get("owner", String.class)) + .isEqualTo(retainedDeclaration.get("owner", String.class)); + assertThat(migratedDeclaration.get("inventory_json", String.class)) + .isEqualTo(originalInventoryJson); + assertThat(migratedDeclaration.get("payload_json", String.class)) + .isEqualTo(originalPayloadJson); + var migratedCommit = + f.dsl.fetchSingle( + "SELECT binding_json, input_digest FROM game_design_draft_commit " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.requestId(), + automation.commitId()); + assertThat(migratedCommit.get("binding_json", String.class)).isEqualTo(originalBindingJson); + assertThat(migratedCommit.get("input_digest", String.class)).isEqualTo(originalBindingDigest); + var migratedApplication = + f.dsl.fetchSingle( + "SELECT snapshot_json, result_bytes FROM game_design_template_config_source_application " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()); + assertThat(migratedApplication.get("snapshot_json", String.class)).isEqualTo(v2SnapshotJson); + assertThat(migratedApplication.get("result_bytes", byte[].class)) + .isEqualTo(originalApplicationBytes); + assertThat( + f.dsl + .fetchSingle( + "SELECT snapshot_digest FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()) + .get("snapshot_digest", String.class)) + .isEqualTo(v2SnapshotDigest); + assertThat( + f.dsl + .fetchSingle( + "SELECT snapshot_json FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + initialTemplate.commitId()) + .get("snapshot_json", String.class)) + .isEqualTo(v1SnapshotJson); + assertThat( + f.dsl + .fetchSingle( + "SELECT snapshot_digest FROM game_design_template_config_source_snapshot " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + initialTemplate.commitId()) + .get("snapshot_digest", String.class)) + .isEqualTo(v1SnapshotDigest); + var upgradedTemplateSources = new TemplateConfigSourceRepository(f.dsl); + assertThat( + upgradedTemplateSources + .readSnapshot(f.target, initialTemplate.commitId()) + .orElseThrow() + .canonicalJson()) + .isEqualTo(v1SnapshotJson); + assertThat( + upgradedTemplateSources + .readSnapshot(f.target, automation.commitId()) + .orElseThrow() + .canonicalJson()) + .isEqualTo(v2SnapshotJson); + + var entityInventory = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + var entity = + binding( + f, + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, entityInventory), + TemplateConfigSource.SCOPE, + "2"); + apply(f, entity); + var entitySource = source(f, entity); + assertThat(entitySource.sourceEpoch()).isEqualTo("3"); + assertThat(entitySource.ownerSourceInventoryDeclarations()).hasSize(2); + assertThat(entitySource.ownerSourceInventoryDeclarations().get(0).owner()) + .isEqualTo(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + assertThat(entitySource.ownerSourceInventoryDeclarations().get(0).sourceBinding()) + .isEqualTo(automation); + assertThat(entitySource.ownerSourceInventoryDeclarations().get(1).owner()) + .isEqualTo(DraftCommitBinding.Owner.ENTITY_MANAGEMENT); + assertThat(entitySource.ownerSourceInventoryDeclarations().get(1).sourceBinding()) + .isEqualTo(entity); + assertThat(entitySource.entries()).hasSize(1); + assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) + .isEqualTo(1L); + f.tx.executeWithoutResult( + ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(entity).orElseThrow()) + .isEqualTo( + new TemplateConfigSourceSnapshot.Application(entity, "2", entitySource))); + + var unrelated = + binding( + f, + GameplayRuleSource.upsertPayload(new GameplayRuleManifest.AdmissionTag("after-entity")), + GameplayRuleSource.SCOPE, + "0"); + apply(f, unrelated); + var inherited = source(f, unrelated); + assertThat(inherited.ownerSourceInventoryDeclarations()) + .containsExactlyElementsOf(entitySource.ownerSourceInventoryDeclarations()); + assertThat(inherited.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) + .isEqualTo(automation); + assertThat(inherited.ownerSourceInventoryDeclarations().get(1).sourceBinding()) + .isEqualTo(entity); + } + @Test void actualCreateAndSameCommitGameplayInputHaveDurableGeneratedIdentityAndExactRetry() { var f = fixture(); @@ -793,6 +1023,23 @@ private static String automationInventory() { + "\"SCRIPT_PATCH_SOURCES\":[]}}"; } + private static String entityInventory() { + return "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"; + } + private DraftCommitBinding binding(Fixture f, String payload, String scope, String epoch) { return binding( f, @@ -824,20 +1071,25 @@ private DraftCommitBinding binding( } private Fixture fixture() { + return fixture(null); + } + + private Fixture fixture(String migrationTarget) { String schema = "template_config_" + UUID.randomUUID().toString().replace("-", ""); var data = new DriverManagerDataSource( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); data.setSchema(schema); - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history_game_design_service") - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); + var flyway = + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (migrationTarget != null) flyway.target(MigrationVersion.fromVersion(migrationTarget)); + flyway.load().migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); var tx = new TransactionTemplate(new DataSourceTransactionManager(data)); tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); @@ -862,9 +1114,25 @@ private Fixture fixture() { saved.getIdentitySourceGameRowId(), saved.getIdentitySourceGameTenantKey(), saved.getIdentitySourceProvenanceKind()); - return new Fixture(dsl, tx, target); + return new Fixture(dsl, tx, target, data, schema); + } + + private static void migrateToLatest(Fixture f) { + Flyway.configure() + .dataSource(f.dataSource()) + .schemas(f.schema()) + .defaultSchema(f.schema()) + .table("flyway_schema_history_game_design_service") + .placeholders(Map.of("serviceSchema", f.schema())) + .locations("classpath:db/migration") + .load() + .migrate(); } private record Fixture( - DSLContext dsl, TransactionTemplate tx, DraftCommitBinding.TargetProof target) {} + DSLContext dsl, + TransactionTemplate tx, + DraftCommitBinding.TargetProof target, + DriverManagerDataSource dataSource, + String schema) {} } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 83608d7396..b0f4967993 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -63,7 +63,9 @@ import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; @@ -155,23 +157,33 @@ import net.firedevops.firemud.gamedesign.service.AssetExportService.SelectedExportResult; import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.ExportedAssetManifest; +import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptService; import net.firedevops.firemud.gamedesign.service.PublishGateService; import net.firedevops.firemud.gamedesign.service.RecordedParticipantDigestService; +import net.firedevops.firemud.gamedesign.service.RevisionService; +import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; import net.firedevops.firemud.gamedesign.service.VersionAssetExportCandidateService; +import net.firedevops.firemud.gamedesign.service.VersionService; import net.firedevops.firemud.gamedesign.service.impl.AssetExportServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateGrpcService; import net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldVersionStateService; import net.firedevops.firemud.gamedesign.service.impl.CompleteLaunchBindingServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.GameDesignGrpcService; import net.firedevops.firemud.gamedesign.service.impl.LaunchDescriptorServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.PublishedReleaseBundleServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.TemplateRemapSetServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflowMetadataResolver; import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; import net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; import net.firedevops.firemud.gamelogic.service.GameLogicDraftDesignDigestService; import net.firedevops.firemud.gamelogic.service.impl.GameLogicGrpcService; @@ -242,10 +254,13 @@ * loopback mTLS. World freeze, immutable inventory and published selector use their actual owner * services over loopback mTLS, with the canonical frozen selector captured owner-locally from the * committed freeze and retained APPLIED graph. Entity/Automation participant digests, in-memory S3 - * and the StartSession Account projection remain test doubles. The complete launch-binding read - * uses the actual owner implementation in an explicitly established read-only repeatable-read - * snapshot, but does not exercise the authenticated GetCompleteLaunchBinding transport. This is not - * a complete four-owner authenticated release, runtime launch, activation or registration proof. + * and the StartSession Account projection remain test doubles. The complete launch-binding case + * wires the actual Game Design handler and World Management mTLS client on this fixture's loopback + * server to the actual owner implementation in an explicitly established read-only repeatable-read + * snapshot; unrelated handler dependencies are isolated. This fixture does not provide + * production-mounted certificates or full application server wiring, Account-projection-backed + * StartSession admission, a complete four-owner authenticated release, runtime launch, activation + * or registration. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -1226,6 +1241,12 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex launchDescriptorService, sourceRepository, releaseService, versionRepository); ReflectionTestUtils.setField( completeLaunchBindingService, "workloadNamespace", NAMESPACE); + AtomicInteger completeBindingOwnerReadCalls = new AtomicInteger(); + CompleteLaunchBindingService transportCompleteLaunchBindingService = + readCompleteLaunchBindingInOwnerSnapshot( + gd, completeLaunchBindingService, completeBindingOwnerReadCalls); + register( + gdHandlers, completeLaunchBindingGrpcService(transportCompleteLaunchBindingService)); UUID completeBindingReadRequestId = UUID.randomUUID(); var persistedLaunchDescriptor = launchDescriptorRepository @@ -1297,6 +1318,79 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(completeGameLogicParticipant.abilitySchemaDigest()) .isEqualTo(actualGameLogicDigest.abilitySchemaDigest()); + var completeBindingRpcRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(completeBindingReadRequestId.toString()) + .setCanonicalTenantId(gd.target().canonicalTenantId().toString()) + .setWorldSlug(worldSource.worldSlug()) + .setControlPlaneRequestId(controlPlaneRequestId) + .setExpectedRequestDigest(expectedAuthoredWorldBinding.requestDigest()) + .setExpectedResultDigest(expectedAuthoredWorldBinding.resultDigest()) + .build(); + try (var worldToGameDesignCompleteBindingClient = + new AuthoredWorldLaunchDescriptorClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + worldToGameDesignCompleteBindingClient.init(); + CompleteLaunchBindingEvidence transportedCompleteBinding = + worldToGameDesignCompleteBindingClient.getComplete(completeBindingRpcRequest); + assertThat(transportedCompleteBinding.descriptor()) + .isEqualTo(completeBinding.descriptor()); + assertThat(transportedCompleteBinding.releaseAttestation()) + .isEqualTo(completeBinding.releaseAttestation()); + assertThat( + worldToGameDesignCompleteBindingClient.getComplete(completeBindingRpcRequest)) + .isEqualTo(transportedCompleteBinding); + } + + try (var unauthorizedAccountToGameDesignClient = + new AuthoredWorldLaunchDescriptorClient( + endpoints, pki.client("account-service"), channels, NAMESPACE)) { + unauthorizedAccountToGameDesignClient.init(); + int ownerReadsBeforeDeniedPeer = completeBindingOwnerReadCalls.get(); + assertThatThrownBy( + () -> + unauthorizedAccountToGameDesignClient.getComplete( + GetLaunchDescriptorRequest.getDefaultInstance())) + .isInstanceOf(IllegalStateException.class); + assertThat(completeBindingOwnerReadCalls.get()).isEqualTo(ownerReadsBeforeDeniedPeer); + } + + try (var worldToGameDesignCompleteBindingClient = + new AuthoredWorldLaunchDescriptorClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + worldToGameDesignCompleteBindingClient.init(); + assertThatThrownBy( + () -> + worldToGameDesignCompleteBindingClient.getComplete( + completeBindingRpcRequest.toBuilder() + .setExpectedRequestDigest( + changedDigest(expectedAuthoredWorldBinding.requestDigest())) + .build())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + worldToGameDesignCompleteBindingClient.getComplete( + completeBindingRpcRequest.toBuilder() + .setExpectedResultDigest( + changedDigest(expectedAuthoredWorldBinding.resultDigest())) + .build())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + worldToGameDesignCompleteBindingClient.getComplete( + completeBindingRpcRequest.toBuilder() + .setCanonicalTenantId(UUID.randomUUID().toString()) + .build())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + worldToGameDesignCompleteBindingClient.getComplete( + completeBindingRpcRequest.toBuilder() + .setWorldSlug("genuine-selected-export-world-substitute") + .build())) + .isInstanceOf(IllegalStateException.class); + } + var completeBindingRetry = readCompleteLaunchBindingInOwnerSnapshot( gd, @@ -2142,6 +2236,50 @@ private static CompleteLaunchBindingDto readCompleteLaunchBindingInOwnerSnapshot expectedResultDigest))); } + /** + * Applies the owner's declared transaction boundary to the directly composed handler service; the + * fixture does not use Spring AOP on the gRPC worker thread. + */ + private static CompleteLaunchBindingService readCompleteLaunchBindingInOwnerSnapshot( + Store owner, CompleteLaunchBindingService service, AtomicInteger readCalls) { + return (readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest) -> { + readCalls.incrementAndGet(); + return readCompleteLaunchBindingInOwnerSnapshot( + owner, + service, + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + }; + } + + private static GameDesignGrpcService completeLaunchBindingGrpcService( + CompleteLaunchBindingService completeLaunchBindingService) { + GameDesignGrpcService grpcService = + new GameDesignGrpcService( + mock(PingService.class), + mock(RevisionService.class), + mock(VersionService.class), + mock(LaunchDescriptorService.class), + completeLaunchBindingService, + mock(TemplateRemapSetService.class), + mock(VersionAssetArtifactService.class), + mock(SettingsAuthorityService.class), + mock(GameAuthoredHelpTopicService.class), + mock(TemporalVersionPublishWorkflowMetadataResolver.class), + new SimpleMeterRegistry()); + ReflectionTestUtils.setField(grpcService, "workloadNamespace", NAMESPACE); + return grpcService; + } + private static List completeBindingOwnerRowVersions( DSLContext dsl, long launchDescriptorRowId, diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java index dffb88d230..dbd021c3aa 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java @@ -9,6 +9,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; import org.junit.jupiter.api.Test; class TemplateConfigSourceTest { @@ -145,6 +146,7 @@ void automationInventoryUsesItsExactVersionedOperationAndPreservesLegacySnapshot String payload = TemplateConfigSource.ownerInventoryPayload( DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, inventory); + assertThat(CommandSource.tree(payload).path("schemaVersion").intValue()).isEqualTo(2); assertThat(CommandSource.tree(payload).path("inventory").isObject()).isTrue(); assertThat(payload).doesNotContain("inventoryJson"); var authored = binding(payload); @@ -250,6 +252,77 @@ void ownerInventoryOperationRejectsMissingUnknownAndUnsupportedContent() { .isEmpty(); } + @Test + void entityInventoryUsesClosedTypedOperationAndRejectsOwnerContentSubstitution() { + var entity = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + String payload = + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, entity); + assertThat(CommandSource.tree(payload).path("schemaVersion").intValue()).isEqualTo(3); + assertThat(CommandSource.tree(payload).path("inventory").isObject()).isTrue(); + var authored = binding(payload); + var mutation = TemplateConfigSource.mutations(authored).getFirst(); + assertThat(mutation.declaredOwner()).isEqualTo(DraftCommitBinding.Owner.ENTITY_MANAGEMENT); + assertThat(mutation.inventory()).isNull(); + assertThat(mutation.entityInventory()).isEqualTo(entity); + assertThat(mutation.templateId()).isNull(); + assertThat(mutation.config()).isNull(); + + var automation = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String autoContentUnderEntity = + typedInventoryPayload(3, "ENTITY_MANAGEMENT", automation.canonicalJson()); + String entityContentUnderAutomation = + typedInventoryPayload(2, "AUTOMATION_SCRIPTING", entity.canonicalJson()); + for (String substituted : List.of(autoContentUnderEntity, entityContentUnderAutomation)) + assertThatThrownBy(() -> TemplateConfigSource.mutations(binding(substituted))) + .isInstanceOf(IllegalArgumentException.class); + String missingEntityInventory = + CommandSource.canonical( + Map.of( + "schemaVersion", + 3, + "revisionKind", + TemplateConfigSource.REVISION_KIND, + "operation", + "DECLARE_OWNER_SOURCE_INVENTORY", + "owner", + "ENTITY_MANAGEMENT")); + assertThatThrownBy(() -> TemplateConfigSource.mutations(binding(missingEntityInventory))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntityAuthoredSourceInventoryDeclaration.parse( + entityInventory() + .replace("\"ITEM_TEMPLATE_ROOTS\":[]", "\"ITEM_TEMPLATE_ROOTS\":[{}]"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntityAuthoredSourceInventoryDeclaration.parse( + entityInventory().replace("\"families\":{", "\"families\":{\"UNKNOWN\":[],"))) + .isInstanceOf(IllegalArgumentException.class); + + var declarations = TemplateConfigSource.replayOwnerInventoryDeclarations(List.of(), authored); + var bothOwners = + TemplateConfigSource.replayOwnerInventoryDeclarations( + declarations, + binding( + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, automation))); + assertThat(bothOwners) + .extracting(TemplateConfigOwnerSourceInventoryDeclaration::owner) + .containsExactly( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + DraftCommitBinding.Owner.ENTITY_MANAGEMENT); + assertThat(bothOwners.get(1).entityInventory()).isEqualTo(entity); + assertThat(bothOwners.get(1).sourceBinding()).isEqualTo(authored); + var snapshot = + new TemplateConfigSourceSnapshot( + authored, "1", null, UUID.randomUUID(), List.of(), declarations); + assertThat(TemplateConfigSourceSnapshot.fromStored(snapshot.canonicalJson())) + .isEqualTo(snapshot); + assertThat(snapshot.canonicalJson()).contains("ITEM_TEMPLATE_ROOTS"); + } + private static String config() { return "{\"schemaVersion\":1,\"baseVersionId\":\"" + VERSION @@ -262,6 +335,38 @@ private static String automationInventory() { + "\"SCRIPT_PATCH_SOURCES\":[]}}"; } + private static String entityInventory() { + return "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"; + } + + private static String typedInventoryPayload(int schemaVersion, String owner, String inventory) { + return CommandSource.canonical( + Map.of( + "schemaVersion", + schemaVersion, + "revisionKind", + TemplateConfigSource.REVISION_KIND, + "operation", + "DECLARE_OWNER_SOURCE_INVENTORY", + "owner", + owner, + "inventory", + CommandSource.tree(inventory))); + } + private static DraftCommitBinding binding(String... payloads) { var revisions = new ArrayList(); for (int i = 0; i < payloads.length; i++) From d10bcf5f7edd462a248ea1fa57dff5d3627c4550 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 05:06:29 +1300 Subject: [PATCH 057/129] Correct atomic inventory results and genuine selected realm policy proof --- ...ame-authoring-publishing-and-activation.md | 4 +- ...template_config_owner_source_inventory.sql | 89 +++++++++ ...teConfigSourcePostgresIntegrationTest.java | 182 +++++++++++++++++- ...licationExportPostgresIntegrationTest.java | 75 +++++++- 4 files changed, 345 insertions(+), 5 deletions(-) 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 856d91fd1f..401fd73b66 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 @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for game authoring, publishing, a Published `97174b31be2ed08440be1a271cc00359614abaf6` [Validation run 37945686843](https://github.com/benhook1013/FireMUD/actions/runs/37945686843) executed 254 Account and 207 World PostgreSQL cases with no failures, errors or skips. Both previously failing Account receipt-confirmation fixtures passed with the production V90/V92 guards and original acknowledgement bounds unchanged. Game Design executed 146 PostgreSQL cases with one failure and no errors or skips: the genuine export fixture invented a new World intake request ID instead of using the original durable Game Design delivery claim. The local correction uses that original request, World’s actual receipt and Game Design’s actual acknowledgement, without weakening the selected-source readback guard. Separate legacy descriptor (8), complete launch-binding (6), and genuine GD+World source-settlement (3) cases passed; they do not establish success of the failed genuine export. The actual CI checkout is synthetic merge `421b0196ccffff96405aab1c687d2455c52ede60`, tree `62188ebd390fdd8d4ed71d4a245c5195a30eae3a`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact published source, not the intended integration parent. -The current source-inventory construction retains genuinely authored Automation and Entity `TEMPLATE_CONFIG` declarations, immutable original revision provenance and snapshot v2; it creates no template row or Entity/Automation commit participation. Automation's published operation bytes remain schema version 2; Entity's new closed operation uses version 3 and its mandatory 23-family empty-only declaration with explicit equipment non-applicability. Forward migration V68 extends the owner guard without rewriting V67 or historical source bytes. The added PostgreSQL definition checks original Automation content, binding, application bytes and v1/v2 snapshot readback through that upgrade, then genuine Entity application, inheritance and exact retry. Common's preceding full check executed 457 unit cases successfully. The combined Game Design schema generation, full check, boot JAR and documentation gate passes in 2m 3s with 525 unit cases executed; all 146 local integration cases compile/discover but skip without Docker. The new migration and transport definitions therefore have no physical execution proof yet. Neither declaration is an owner receipt. Separate Entity/Automation Account-authorized intake, held current-authority retention, and authenticated full selected World/inbound closure remain missing. World's exact frozen six-family topology inventory exposes typed ITEM/NPC spawn inputs, but does not supply selected loot/behavior/hook closure; a zero topology count cannot certify those missing producers. The genuine fixture now invokes the real complete-launch-binding handler and World mTLS client, with exact readback/retry, peer-first denial, substitution and no-mutation assertions. Its Account StartSession projection, Entity/Automation participation and object-store transport remain explicit test doubles; production certificate mounting, current Game Session `STARTING` evidence and World held commit-authority verification remain unproved. All four Gameplay handoffs and activation remain open. +Published `f580093d113630e8335c301a7ecb31d6a4bf4acd` [Validation run 37951600583](https://github.com/benhook1013/FireMUD/actions/runs/37951600583) executed 254 Account and 207 World PostgreSQL cases successfully with no failures, errors or skips. Game Design executed 524 unit cases successfully and 148 PostgreSQL cases with three failures and no skips: two authored Automation declarations reached the deferred atomic-result guard, which counted all template-config operations only against ordinary template rows; the genuine export progressed beyond the original World-delivery correction but had no authored realm policy. The current correction extends that guard in forward V68 to count exact declaration rows separately while retaining complete coordinator-result, epoch and sibling-source checks. The export fixture now authors and reads back its required realm policy in the original selected commit. The actual CI checkout is synthetic merge `0744b12a806c8a484df3e15c796e9f76532dc64d`, tree `c784e788550a4ae61f0b3df84a711cecc79933b0`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published source; this is exact-source execution, not intended-parent alignment or proof of the corrected state. + +The current source-inventory construction retains genuinely authored Automation and Entity `TEMPLATE_CONFIG` declarations, immutable original revision provenance and snapshot v2; it creates no template row or Entity/Automation commit participation. Automation's published operation bytes remain schema version 2; Entity's new closed operation uses version 3 and its mandatory 23-family empty-only declaration with explicit equipment non-applicability. Forward migration V68 extends the owner guard without rewriting V67 or historical source bytes. The PostgreSQL definitions preserve the genuine V67 ordinary-template v1 snapshot, demonstrate a complete Automation transaction rejected and rolled back by the V67 guard, then retry that same binding after V68. They verify actual V68 Automation content, binding, application bytes and provenance through later Entity application, inheritance and exact retry, plus missing or altered coordinator-result denial. Common's preceding full check executed 457 unit cases successfully. The final affected Game Design schema generation, full check, boot JAR and documentation gate passes in 37s with 525 unit cases executed; all 147 local integration cases compile/discover but skip without Docker. The complete-transaction upgrade assertion and new migration and transport definitions therefore have no physical execution proof yet. Neither declaration is an owner receipt. Separate Entity/Automation Account-authorized intake, held current-authority retention, and authenticated full selected World/inbound closure remain missing. World's exact frozen six-family topology inventory exposes typed ITEM/NPC spawn inputs, but does not supply selected loot/behavior/hook closure; a zero topology count cannot certify those missing producers. The genuine fixture now invokes the real complete-launch-binding handler and World mTLS client, with exact readback/retry, peer-first denial, substitution and no-mutation assertions. Its Account StartSession projection, Entity/Automation participation and object-store transport remain explicit test doubles; production certificate mounting, current Game Session `STARTING` evidence and World held commit-authority verification remain unproved. All four Gameplay handoffs and activation remain open. Published `9f287e05e06b87adc3db79984b2e047e5d5b819f` [Validation run 37939078493](https://github.com/benhook1013/FireMUD/actions/runs/37939078493) executed 146 Game Design PostgreSQL cases with one failure, 254 Account cases with one failure, and 207 World cases with no failures; all three suites report zero skips and errors. The three genuine GD+World source/settlement cases, genuine Game Logic intake case, approved-remap retention correction and eight legacy descriptor persistence/retry/migration cases passed. The genuine selected export/descriptor case failed before export because its stipulated World evidence supplied a prefixed content hash to a bare-hex field. Since that run, the local construction has replaced the stipulated Account publication-order and World freeze/inventory/selector evidence with the actual owner reads and adds canonical topology capture after freeze. This new composition has no physical proof yet. Account's failure moved to the physical-confirmation/independent-read case and again denied at V90's conservative coverage prerequisite: insert `0/7EDFE48` exceeded initial/final flush `0/7EDFE08` while the original bound remained unchanged. A bounded fixture diagnosis is separate from source/release construction. Overseer deferred production WAL-locator adoption; the prototype, original JVM acknowledgement/time bounds, V90/V92 recovery semantics and PostgreSQL-version guards remain unchanged. The actual synthetic checkout is `1822fbae8dc9f6c4409ccc9515a99ee5e5f42e99`, tree `dc3142f6c4284288a43ed71d97632c35ee4afe09`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published source. This is exact-source execution, not intended-parent alignment, a genuine complete release or activation. diff --git a/services/game-design-service/src/main/resources/db/migration/V68__entity_template_config_owner_source_inventory.sql b/services/game-design-service/src/main/resources/db/migration/V68__entity_template_config_owner_source_inventory.sql index bc132b0ba8..8829c8380c 100644 --- a/services/game-design-service/src/main/resources/db/migration/V68__entity_template_config_owner_source_inventory.sql +++ b/services/game-design-service/src/main/resources/db/migration/V68__entity_template_config_owner_source_inventory.sql @@ -147,3 +147,92 @@ BEGIN END; $$ LANGUAGE plpgsql; -- [jooq ignore stop] + +-- Keep the deferred atomic Game Design result check, but count owner-inventory operations in their +-- own exact retained table instead of requiring a fabricated template row revision. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION verify_template_config_application_commit() RETURNS TRIGGER AS $$ +DECLARE branding_bytes BYTEA; c game_design_draft_commit%ROWTYPE; r game_design_draft_commit_owner_result%ROWTYPE; + h game_design_template_config_source_head%ROWTYPE; expected BYTEA; bytes BYTEA; components BYTEA; + gameplay_bytes BYTEA; command_bytes BYTEA; asset_bytes BYTEA; policy_bytes BYTEA; + declared BIGINT; retained BIGINT; declared_inventory BIGINT; retained_inventory BIGINT; + epochs JSONB := '[]'::JSONB; unit JSONB; kind TEXT; expected_scope TEXT; scope_count BIGINT := 0; +BEGIN + SELECT result_bytes INTO branding_bytes FROM game_design_branding_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT c FROM game_design_draft_commit WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT * INTO STRICT r FROM game_design_draft_commit_owner_result WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND owner = 'GAME_DESIGN_CONTROL_PLANE'; + SELECT * INTO STRICT h FROM game_design_template_config_source_head WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id; + SELECT count(*) INTO declared FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG'; + SELECT count(*) INTO declared_inventory FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + AND (x->>'payload')::JSONB->>'revisionKind' = 'TEMPLATE_CONFIG' + AND (x->>'payload')::JSONB->>'operation' = 'DECLARE_OWNER_SOURCE_INVENTORY'; + SELECT count(*) INTO retained FROM game_design_template_config_source_revision WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + SELECT count(*) INTO retained_inventory FROM game_design_template_config_owner_source_inventory_declaration + WHERE canonical_tenant_id = NEW.canonical_tenant_id AND canonical_version_id = NEW.canonical_version_id + AND request_id = NEW.request_id AND commit_id = NEW.commit_id; + bytes := convert_to('game-design-template-config-source-application/v1', 'UTF8'); expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.expected_epoch, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + bytes := convert_to(NEW.snapshot_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF declared = 0 OR declared <> retained + retained_inventory OR declared_inventory <> retained_inventory + OR NEW.result_bytes IS DISTINCT FROM expected OR r.status <> 'APPLIED' + OR r.result_commit_id <> NEW.commit_id OR r.result_binding_digest <> c.input_digest + OR h.applied_commit_id IS DISTINCT FROM NEW.commit_id OR h.source_epoch <> (NEW.expected_epoch::NUMERIC + 1)::TEXT THEN + RAISE EXCEPTION 'branding application requires exact atomic owner result' USING ERRCODE = '23514'; END IF; + SELECT result_bytes INTO command_bytes FROM game_design_command_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO asset_bytes FROM game_design_asset_source_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO policy_bytes FROM game_design_realm_policy_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + SELECT result_bytes INTO gameplay_bytes FROM game_design_gameplay_rule_application WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id AND commit_id = NEW.commit_id; + FOR kind IN SELECT DISTINCT (x->>'payload')::JSONB->>'revisionKind' FROM jsonb_array_elements(c.binding_json::JSONB->'revisions') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' LOOP + expected_scope := CASE kind WHEN 'COMMAND_DEFINITION' THEN 'COMMAND_DEFINITION_SET' + WHEN 'ASSET_REFERENCE' THEN 'ASSET_REFERENCE_SET' WHEN 'REALM_ENTRY_POLICY' THEN 'REALM_ENTRY_POLICY_SET' + WHEN 'TEMPLATE_CONFIG' THEN 'TEMPLATE_CONFIG_SET' WHEN 'GAMEPLAY_RULE' THEN 'GAMEPLAY_RULE_SET' WHEN 'BRANDING_ASSET_REFERENCE' THEN 'BRANDING_ASSET_REFERENCE_SET' ELSE NULL END; + IF expected_scope IS NULL OR (kind = 'BRANDING_ASSET_REFERENCE' AND branding_bytes IS NULL) OR (kind = 'GAMEPLAY_RULE' AND gameplay_bytes IS NULL) OR (kind = 'COMMAND_DEFINITION' AND command_bytes IS NULL) + OR (kind = 'ASSET_REFERENCE' AND asset_bytes IS NULL) OR (kind = 'REALM_ENTRY_POLICY' AND policy_bytes IS NULL) + OR (SELECT count(*) FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x + WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' AND x->>'aggregateType' = expected_scope) <> 1 THEN + RAISE EXCEPTION 'branding mixed application requires all declared sibling sources' USING ERRCODE = '23514'; END IF; + scope_count := scope_count + 1; + END LOOP; + FOR unit IN SELECT x FROM jsonb_array_elements(c.binding_json::JSONB->'affectedUnits') x WHERE x->>'owner' = 'GAME_DESIGN_CONTROL_PLANE' + ORDER BY x->>'aggregateType', x->>'aggregateId', x->>'scopeType', x->>'scopeId' LOOP + IF unit->>'aggregateType' NOT IN ('COMMAND_DEFINITION_SET', 'ASSET_REFERENCE_SET', 'REALM_ENTRY_POLICY_SET', 'GAMEPLAY_RULE_SET', 'TEMPLATE_CONFIG_SET', 'BRANDING_ASSET_REFERENCE_SET') + OR unit->>'aggregateType' IS DISTINCT FROM unit->>'scopeType' OR unit->>'scopeId' IS DISTINCT FROM 'effective' + OR unit->>'aggregateId' IS DISTINCT FROM NEW.canonical_version_id::TEXT THEN + RAISE EXCEPTION 'branding combined scope mismatch' USING ERRCODE = '23514'; END IF; + epochs := epochs || jsonb_build_array((unit - 'owner') || jsonb_build_object('resultingEpoch', ((unit->>'expectedEpoch')::NUMERIC + 1)::TEXT)); + END LOOP; + IF jsonb_array_length(epochs) <> scope_count THEN RAISE EXCEPTION 'branding scope vector incomplete' USING ERRCODE = '23514'; END IF; + bytes := convert_to('game-design-control-plane-sibling-components/v1', 'UTF8'); components := int4send(octet_length(bytes)) || bytes; + IF command_bytes IS NOT NULL THEN bytes := convert_to('COMMAND', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(command_bytes)) || command_bytes; END IF; + IF asset_bytes IS NOT NULL THEN bytes := convert_to('ASSET', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(asset_bytes)) || asset_bytes; END IF; + IF gameplay_bytes IS NOT NULL THEN bytes := convert_to('GAMEPLAY', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(gameplay_bytes)) || gameplay_bytes; END IF; + IF branding_bytes IS NOT NULL THEN bytes := convert_to('BRANDING', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(branding_bytes)) || branding_bytes; END IF; + bytes := convert_to('TEMPLATE_CONFIG', 'UTF8'); + components := components || int4send(octet_length(bytes)) || bytes || int4send(octet_length(NEW.result_bytes)) || NEW.result_bytes; + IF policy_bytes IS NULL THEN bytes := convert_to('game-design-control-plane-ordinary-source-application/v1', 'UTF8'); + ELSE bytes := convert_to('game-design-control-plane-source-application/v1', 'UTF8'); END IF; + expected := int4send(octet_length(bytes)) || bytes; + bytes := convert_to(c.binding_json, 'UTF8'); expected := expected || int4send(octet_length(bytes)) || bytes; + IF policy_bytes IS NOT NULL THEN expected := expected || int4send(octet_length(policy_bytes)) || policy_bytes; END IF; + expected := expected || int4send(octet_length(components)) || components; + IF r.result_bytes IS DISTINCT FROM expected OR r.applied_units_json::JSONB IS DISTINCT FROM epochs THEN + RAISE EXCEPTION 'branding owner result must contain exact complete tagged source bytes' USING ERRCODE = '23514'; END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java index c4fa936be8..b0595f299f 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -203,7 +203,7 @@ void latestSameOrderAutomationDeclarationRetainsItsExactBindingAcrossRetryAndInh } @Test - void v68AddsEntityWithoutRewritingV67AutomationOrSnapshotHistory() { + void v67RejectsOwnerDeclarationThenV68RetriesExactBindingWithoutRewritingV67History() { var f = fixture("67"); var initialTemplate = binding( @@ -230,6 +230,12 @@ void v68AddsEntityWithoutRewritingV67AutomationOrSnapshotHistory() { f.target.canonicalVersionId(), initialTemplate.commitId()) .get("snapshot_digest", String.class); + var originalV1Snapshot = + new TemplateConfigSourceRepository(f.dsl) + .readSnapshot(f.target, initialTemplate.commitId()) + .orElseThrow(); + assertThat(originalV1Snapshot.canonicalJson()).isEqualTo(v1SnapshotJson); + assertThat(originalV1Snapshot.digest()).isEqualTo(v1SnapshotDigest); var automationInventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); @@ -237,6 +243,68 @@ void v68AddsEntityWithoutRewritingV67AutomationOrSnapshotHistory() { TemplateConfigSource.ownerInventoryPayload( DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, automationInventory); var automation = binding(f, automationPayload, TemplateConfigSource.SCOPE, "1"); + var priorHead = + f.dsl.fetchSingle( + "SELECT source_epoch, applied_commit_id, visible_commit_id " + + "FROM game_design_template_config_source_head " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId()); + assertThatThrownBy(() -> apply(f, automation)) + .isInstanceOf(org.springframework.transaction.TransactionSystemException.class) + .hasStackTraceContaining("branding application requires exact atomic owner result"); + var unchangedHead = + f.dsl.fetchSingle( + "SELECT source_epoch, applied_commit_id, visible_commit_id " + + "FROM game_design_template_config_source_head " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId()); + assertThat(unchangedHead.get("source_epoch", String.class)) + .isEqualTo(priorHead.get("source_epoch", String.class)); + assertThat(unchangedHead.get("applied_commit_id", UUID.class)) + .isEqualTo(priorHead.get("applied_commit_id", UUID.class)); + assertThat(unchangedHead.get("visible_commit_id", UUID.class)) + .isEqualTo(priorHead.get("visible_commit_id", UUID.class)); + assertThat(unchangedHead.get("source_epoch", String.class)).isEqualTo("1"); + assertThat(unchangedHead.get("applied_commit_id", UUID.class)) + .isEqualTo(initialTemplate.commitId()); + assertThat(unchangedHead.get("visible_commit_id", UUID.class)) + .isEqualTo(initialTemplate.commitId()); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_owner_source_inventory_declaration " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()) + .get(0, Long.class)) + .isZero(); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_template_config_source_application " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()) + .get(0, Long.class)) + .isZero(); + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM game_design_draft_commit " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.requestId(), + automation.commitId()) + .get(0, Long.class)) + .isZero(); + + migrateToLatest(f); apply(f, automation); var automationSource = source(f, automation); assertThat(automationSource.ownerSourceInventoryDeclarations()).hasSize(1); @@ -298,7 +366,6 @@ void v68AddsEntityWithoutRewritingV67AutomationOrSnapshotHistory() { .isEqualTo( new TemplateConfigSourceSnapshot.Application( automation, "1", automationSource))); - migrateToLatest(f); var migratedDeclaration = f.dsl.fetchSingle( @@ -397,6 +464,8 @@ void v68AddsEntityWithoutRewritingV67AutomationOrSnapshotHistory() { var entitySource = source(f, entity); assertThat(entitySource.sourceEpoch()).isEqualTo("3"); assertThat(entitySource.ownerSourceInventoryDeclarations()).hasSize(2); + assertThat(entitySource.ownerSourceInventoryDeclarations().get(0)) + .isEqualTo(automationSource.ownerSourceInventoryDeclarations().getFirst()); assertThat(entitySource.ownerSourceInventoryDeclarations().get(0).owner()) .isEqualTo(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); assertThat(entitySource.ownerSourceInventoryDeclarations().get(0).sourceBinding()) @@ -428,6 +497,106 @@ void v68AddsEntityWithoutRewritingV67AutomationOrSnapshotHistory() { .isEqualTo(automation); assertThat(inherited.ownerSourceInventoryDeclarations().get(1).sourceBinding()) .isEqualTo(entity); + var postEntityReadback = new TemplateConfigSourceRepository(f.dsl); + var retainedV1 = + postEntityReadback.readSnapshot(f.target, initialTemplate.commitId()).orElseThrow(); + assertThat(retainedV1.canonicalJson()).isEqualTo(v1SnapshotJson); + assertThat(retainedV1.digest()).isEqualTo(v1SnapshotDigest); + var retainedAutomation = + postEntityReadback.readSnapshot(f.target, automation.commitId()).orElseThrow(); + assertThat(retainedAutomation.canonicalJson()).isEqualTo(v2SnapshotJson); + assertThat(retainedAutomation.digest()).isEqualTo(v2SnapshotDigest); + var retainedInherited = + postEntityReadback.readSnapshot(f.target, unrelated.commitId()).orElseThrow(); + assertThat(retainedInherited.ownerSourceInventoryDeclarations()) + .containsExactlyElementsOf(entitySource.ownerSourceInventoryDeclarations()); + var postEntityAutomationApplication = + f.dsl.fetchSingle( + "SELECT snapshot_json, result_bytes FROM game_design_template_config_source_application " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.commitId()); + assertThat(postEntityAutomationApplication.get("snapshot_json", String.class)) + .isEqualTo(v2SnapshotJson); + assertThat(postEntityAutomationApplication.get("result_bytes", byte[].class)) + .isEqualTo(originalApplicationBytes); + var postEntityAutomationDeclaration = + f.dsl.fetchSingle( + "SELECT request_id, commit_id, revision_order, owner, inventory_json, payload_json FROM " + + "game_design_template_config_owner_source_inventory_declaration " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND revision_id = ?", + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + automation.revisions().getFirst().revisionId()); + assertThat(postEntityAutomationDeclaration.get("request_id", UUID.class)) + .isEqualTo(automation.requestId()); + assertThat(postEntityAutomationDeclaration.get("commit_id", UUID.class)) + .isEqualTo(automation.commitId()); + assertThat(postEntityAutomationDeclaration.get("revision_order", Integer.class)).isZero(); + assertThat(postEntityAutomationDeclaration.get("owner", String.class)) + .isEqualTo("AUTOMATION_SCRIPTING"); + assertThat(postEntityAutomationDeclaration.get("inventory_json", String.class)) + .isEqualTo(originalInventoryJson); + assertThat(postEntityAutomationDeclaration.get("payload_json", String.class)) + .isEqualTo(originalPayloadJson); + } + + @Test + void deferredTemplateApplicationGuardRejectsMissingOrChangedAtomicOwnerResult() { + var f = fixture(); + var automationInventory = + AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + var missingResult = + binding( + f, + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, automationInventory), + TemplateConfigSource.SCOPE, + "0"); + assertThatThrownBy( + () -> + f.tx.executeWithoutResult( + ignored -> { + stageInProgressTemplateApplication(f, missingResult); + f.dsl.execute( + "SET CONSTRAINTS template_config_application_commit_guard IMMEDIATE"); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("branding application requires exact atomic owner result"); + + var entityInventory = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + var changedResult = + binding( + f, + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, entityInventory), + TemplateConfigSource.SCOPE, + "0"); + assertThatThrownBy( + () -> + f.tx.executeWithoutResult( + ignored -> { + var application = stageInProgressTemplateApplication(f, changedResult); + byte[] alteredResultBytes = application.canonicalBytes(); + alteredResultBytes[0] ^= 1; + new DraftCommitCoordinatorRepository(f.dsl) + .recordOwnerOutcome( + changedResult, + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + changedResult.commitId(), + changedResult.digest(), + "ordinary-source:" + changedResult.commitId(), + alteredResultBytes, + List.of(application.appliedEpoch()))); + f.dsl.execute( + "SET CONSTRAINTS template_config_application_commit_guard IMMEDIATE"); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining( + "branding owner result must contain exact complete tagged source bytes"); } @Test @@ -1008,6 +1177,15 @@ private void apply(Fixture f, DraftCommitBinding binding) { }); } + private static TemplateConfigSourceSnapshot.Application stageInProgressTemplateApplication( + Fixture f, DraftCommitBinding binding) { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + coordinator.claim(binding); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + return new TemplateConfigSourceRepository(f.dsl).apply(binding).orElseThrow(); + } + private static TemplateConfigSource.Config config(Fixture f, String inputs) { return new TemplateConfigSource.Config( "{\"schemaVersion\":1,\"baseVersionId\":\"" diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index b0f4967993..7153299c3e 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -94,6 +94,7 @@ import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; @@ -124,6 +125,7 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventoryReadService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftControlPlaneDigest; @@ -517,7 +519,13 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assetToSave.setData(assetBytes); GameAsset sourceAsset = gd.transaction(() -> new GameAssetRepository(gd.dsl()).save(assetToSave)); - var selectedCommit = binding(gd.target(), sourceAsset.getId(), sourceAsset.getFileName()); + var selectedCommit = + binding( + gd.target(), + sourceAsset.getId(), + sourceAsset.getFileName(), + worldSource.worldSlug(), + worldSource.worldDisplayName()); var originalOrder = account.prepareOriginalDraftOrder(selectedCommit, NAMESPACE); var original = originalOrder.original(); var accountAccess = account.preparedOriginalCreator(); @@ -704,6 +712,19 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(appliedWorld.status()).isEqualTo("APPLIED"); assertThat(appliedWorld.startLocationReceipt()).isPresent(); assertThat(world.dsl().fetchCount(DSL.table("world_draft_graph_application"))).isOne(); + var selectedPolicyRevision = + selectedCommit.revisions().stream() + .filter(RealmPolicySource::isPolicyRevision) + .findFirst() + .orElseThrow(); + var expectedPolicy = RealmPolicySource.revision(selectedCommit, selectedPolicyRevision); + var selectedSources = + new GameDesignSourceRepository(gd.dsl()) + .readSynchronized(gd.target(), selectedCommit.commitId()) + .orElseThrow(); + assertThat(selectedSources.policy().binding()).isEqualTo(selectedCommit); + assertThat(RealmPolicySource.ordered(selectedSources.policy().policies())) + .containsExactly(expectedPolicy); var templateSource = new TemplateConfigSourceRepository(gd.dsl()) @@ -1980,7 +2001,8 @@ private static String migrationLocation(String service) { throw new IllegalStateException("Service migration directory is unavailable: " + service); } - private static DraftCommitBinding binding(TargetProof target, long assetId, String fileName) + private static DraftCommitBinding binding( + TargetProof target, long assetId, String fileName, String worldSlug, String worldDisplayName) throws Exception { UUID commit = UUID.randomUUID(); UUID region = UUID.randomUUID(); @@ -2080,6 +2102,21 @@ private static DraftCommitBinding binding(TargetProof target, long assetId, Stri AssetSource.SCOPE, AssetSource.SCOPE_ID, "0")); + UUID realmPolicyRevisionId = UUID.randomUUID(); + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + realmPolicyRevisionId, + Owner.GAME_DESIGN_CONTROL_PLANE, + realmPolicyRevisionPayload(worldSlug, worldDisplayName, realmPolicyRevisionId))); + units.add( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + target.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0")); var templateConfig = new TemplateConfigSource.Config( "{\"schemaVersion\":1,\"baseVersionId\":\"" @@ -2136,6 +2173,40 @@ private static DraftCommitBinding binding(TargetProof target, long assetId, Stri target, UUID.randomUUID(), commit, "base-commit-0", revisions, units); } + private static String realmPolicyRevisionPayload( + String worldSlug, String worldDisplayName, UUID revisionId) throws Exception { + var mapper = new ObjectMapper(); + var policyInput = + Map.of( + "schemaVersion", + 1, + "worldSlug", + worldSlug, + "worldDisplayName", + worldDisplayName, + "realmSlug", + "genuine-selected-export", + "realmDisplayName", + "Genuine Selected Export", + "visible", + true, + "publicProduction", + true, + "stateScope", + RealmEntryPolicy.StateScope.SHARED.name(), + "entryPolicy", + RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY.name()); + var policy = RealmEntryPolicy.parse(mapper.writeValueAsString(policyInput), mapper); + var revision = + Map.of( + "revisionKind", RealmEntryPolicy.REVISION_KIND, + "logicalRevisionId", revisionId.toString(), + "policy", mapper.readTree(policy.canonicalJson())); + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(mapper.writeValueAsString(revision)), + StandardCharsets.UTF_8); + } + private static WorldDesignMutationRevision.Builder mutation( UUID commit, UUID aggregate, UUID region, WorldDesignAggregateType type) { return WorldDesignMutationRevision.newBuilder() From b436920367ef19bd30e7620513eefcb7bb9f2e79 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 06:10:47 +1300 Subject: [PATCH 058/129] Bind selected World publication to original inbound source closure --- ...dmin-as-external-operator-write-ingress.md | 10 + .../account-service/api-contracts.md | 2 + .../game-design-service/game-templates.md | 2 + .../world-management-service/api-contracts.md | 6 +- .../runtime-and-data.md | 4 +- ...ame-authoring-publishing-and-activation.md | 4 +- .../v1/world_management_service.proto | 25 ++ .../WorldDraftTerminalReadGrpcCodec.java | 78 ++++- ...thoredWorldReleaseAttestationEvidence.java | 140 ++++++++- ...GameDesignPublicationTerminalEvidence.java | 17 +- ...dPublicationArtifactInventoryEvidence.java | 114 +++++++- ...rldCanonicalInstanceLifecycleEvidence.java | 5 +- ...rldPublishedSpawnRequirementsEvidence.java | 5 +- .../WorldPublishedStartLocationEvidence.java | 2 +- .../WorldDraftTerminalReadGrpcCodecTest.java | 178 +++++++++++- ...edWorldReleaseAttestationSelectorTest.java | 108 ++++++- ...icationArtifactInventoryGrpcCodecTest.java | 157 ++++++++++ ...anonicalInstanceLifecycleEvidenceTest.java | 2 +- ...atedWorldPublicationInventoryFixtures.java | 48 +++- .../dto/PublishedReleaseBundleDto.java | 8 +- .../StartSessionLaunchDescriptorProducer.java | 3 +- ...SessionTemplateAssociationReadService.java | 3 +- .../PublishedReleaseBundleRepository.java | 16 +- .../CompleteLaunchBindingServiceImpl.java | 30 +- .../service/impl/GameDesignGrpcService.java | 2 +- .../service/impl/PublishGateServiceImpl.java | 31 +- .../impl/PublishedReleaseBundleContract.java | 46 ++- .../PublishedReleaseBundleServiceImpl.java | 9 +- .../VersionPublishCommandServiceImpl.java | 4 +- ...ified_selected_publication_attestation.sql | 269 ++++++++++++++++++ .../draft/IsolatedPublicationOwnerSetup.java | 39 ++- .../IsolatedPublicationOperationFixtures.java | 18 +- .../impl/PublishedWorldSelectorFixtures.java | 21 +- ...teConfigSourcePostgresIntegrationTest.java | 4 +- ...licationExportPostgresIntegrationTest.java | 149 +++++++++- ...emptServiceTransactionIntegrationTest.java | 25 +- .../CompleteLaunchBindingServiceImplTest.java | 53 ++++ .../impl/GameDesignGrpcServiceTest.java | 59 ++++ .../impl/PublishGateServiceImplTest.java | 26 ++ ...PublishedReleaseBundleServiceImplTest.java | 46 ++- .../WorldDraftDesignDigestService.java | 6 + .../WorldDraftDesignDigestServiceImpl.java | 214 ++++++++------ .../tenant/WorldAuthoredGraphSnapshot.java | 4 +- .../tenant/WorldCanonicalAuthoredGraph.java | 26 +- .../WorldCanonicalAuthoredGraphReader.java | 38 ++- ...orldCanonicalFrozenTopologyRepository.java | 20 +- ...onicalInstanceLifecycleReadRepository.java | 5 +- .../WorldCanonicalInstancePreparation.java | 7 +- ...calInstancePreparationAssemblyService.java | 5 +- ...anonicalInstancePreparationRepository.java | 4 +- .../WorldCompleteLaunchBindingService.java | 6 +- .../WorldDraftGraphApplicationRepository.java | 18 +- .../tenant/WorldDraftTopologyCommitPlan.java | 44 ++- .../WorldDraftTopologyCommitRepository.java | 32 ++- .../tenant/WorldDraftTopologyInputGraph.java | 66 ++++- ...ldPublishedSpawnRequirementsReadOwner.java | 4 +- ...dDraftPublicationCheckpointRepository.java | 19 +- ...dSelectedPublicationArtifactInventory.java | 109 ++++++- ...ublicationArtifactInventoryRepository.java | 6 +- ...d_selected_inbound_closure_declaration.sql | 115 ++++++++ ...lected_publication_inventory_schema_v2.sql | 63 ++++ ..._world_selected_closure_schema4_guards.sql | 265 +++++++++++++++++ ...dGraphSnapshotPostgresIntegrationTest.java | 31 +- ...uthorizedDraftPostgresIntegrationTest.java | 31 ++ ...FrozenTopologyPostgresIntegrationTest.java | 197 +++++++++---- ...nceAssociationPostgresIntegrationTest.java | 31 ++ ...aphApplicationPostgresIntegrationTest.java | 162 ++++++++++- ...DesignPublicationTerminalVerifierTest.java | 29 +- ...ectedPublicationArtifactInventoryTest.java | 98 +++++++ ...WorldDraftDesignDigestServiceImplTest.java | 91 ++++++ .../WorldAuthoredGraphSnapshotTest.java | 6 +- ...nstancePreparationAssemblyServiceTest.java | 2 +- ...WorldCompleteLaunchBindingServiceTest.java | 2 +- .../WorldDraftTopologyCommitPlanTest.java | 80 ++++++ ...blishedSpawnRequirementsReadOwnerTest.java | 6 +- 75 files changed, 3277 insertions(+), 333 deletions(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V69__closure_qualified_selected_publication_attestation.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V59__world_selected_inbound_closure_declaration.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V60__world_selected_publication_inventory_schema_v2.sql create mode 100644 services/world-management-service/src/main/resources/db/migration/V61__world_selected_closure_schema4_guards.sql diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 2116d624c7..c6108f138f 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -99,6 +99,16 @@ Both issuance paths use the same bounded typed-mutation admission contract befor After Game Session has redeemed the original human StartSession reference and allocated its owner attempt and fence, Account may serve `ReadRedeemedOperationProjection` to the exact same-namespace `game-design-service` peer only to read the immutable template-selected source/descriptor for the same original tenant, template, and `controlPlaneRequestId`. The request is bound to the exact canonical pre-authorization tuple, Account-returned authorization-reference fingerprint, original reservation owner/fence, and actual Game Session `ownerAttemptId`/`ownerFence`; Account independently revalidates the original actor and `control-ui` token `jti`, current Account source and reference expiry, and the stored original reservation and redeemed Game Session attempt/fence before returning that projection. No forwarded JWT or opaque reference is sent on this read, and neither workload identity, fingerprint, nor authority-bundle integrity alone establishes authority. The read is credential-free and read-only: it does not renew or extend a reservation/reference, issue or redeem a credential, mutate source state, select a different template or policy, create another owner attempt, commit the owner mutation, or bootstrap/activate a runtime. Exact retries repeat the same binding and return the same operation projection without policy reselection; changed, stale, or ambiguous bindings fail closed. This read is not a commit-spanning CAS proof; owner commit and runtime activation remain separately fenced by their owners. +#### StartSession World Receiving Participation + +For the human StartSession flow, Account owns a separate same-namespace World receiving-participation lifecycle for protecting the exact source through World execution. Only the exact authenticated same-namespace `world-management-service` workload may receive and use this participation for its canonical World target. The original Account-issued StartSession authorization and immutable typed `targetOwner=game-session-service` remain unchanged. Account binds its distinct World participation purpose, stable participation ID, and positive participation fence to the exact original canonical complete `postAuthorizationExecutionTuple` and issuance record, including the original reservation owner and claim fence; the actual redeemed Game Session `ownerAttemptId` and `ownerFence`; the exact authenticated Game Design descriptor, release, and source association; and the canonical World target. This participation is not a replacement issuance or a second authority record. It does not issue, renew, or re-redeem the original authorization reference, change its target owner, create another Game Session attempt, or turn the Game Design projection into permission. Neither the `Redeemed StartSession Projection Read` above nor settled publication hold/settlement evidence authorizes StartSession execution in World or substitutes for this participation. + +Acquisition of the World participation and each fresh World execution admission must revalidate the original actor and `control-ui` token `jti`, the exact original reference and its issuance, current Account source, current role and trusted environment, the exact complete original `authorityTuple` and independent applicable `membershipVersion`, and every applicable validity bound through the existing human StartSession authorization/currentness path, including `withCurrentCommitted`. This reuses the original Account authorization boundary; it does not repeat issuance or redemption, add a duplicate issuer, or renew the reference. Unavailable, stale, mismatched, or uncertain Account evidence denies admission before World SQL. Account continuously retains source protection until authenticated readback proves the exact World operation `COMMITTED` or a durable, fenced `ABORTED` that excludes every in-flight or later commit. A `HELD` sample, timeout, absence, or ambiguous result is not settlement, cannot release participation, and cannot authorize execution or redispatch. This StartSession participation does not alter the separate hosted-terms or creator-write deadline contracts; deadline-qualified creator writes remain unavailable until their own commit-time authority and proof requirements are met. + +World owns a durable operation row and a separate monotonic execution fence that serialize execution admission, abort, and terminal outcome for this exact tuple, source association, participation ID/fence, and canonical target. The World execution fence is distinct from the Account issuance fence, source-participation fence, reservation claim fence, and membership version. Account and Game Design network calls and all other network work occur outside World SQL. World obtains authenticated Account admission evidence before SQL, then admits the exact operation under its durable row and checks the source, participation, original owner claim, authorization, and all validity bounds at that admission point inside one uninterrupted atomic SQL transaction. Unavailable, stale, mismatched, or uncertain evidence denies admission. Once admitted while the original participation, owner claim, authorization, and all validity bounds are current, the transaction may finish after the original token or reference expires; this contract does not require physical `COMMIT` before ingress expiry. World must also enforce a bounded operational transaction timeout and cancellation mechanism, with its duration selected by implementation/runtime policy rather than this ADR. Cancellation or timeout is not terminal proof until the World row and database outcome serialize to show that no transaction remains in flight and no later commit can occur. + +Expiry forbids dispatch of a new owner attempt, opening or restarting the World SQL transaction, reacquiring or renewing participation, renewing or reissuing the reference, or re-redeeming it. After a crash or unknown outcome following expiry, World may perform only an exact read-only lookup of the original durable operation: return `COMMITTED` only for the exact stored tuple, or record/return `ABORTED` only through the serialized fence after proving no in-flight or later commit; otherwise remain unresolved, retain source protection, and deny mutation retry. The original operation cannot be retried as a new mutation after expiry or uncertainty. Account's distinct World participation, World admission/abort/terminal serialization, exact source binding, and focused recovery proofs remain unimplemented. This target contract grants no positive StartSession admission or runtime-activation approval; execution must remain unavailable until those boundaries and proofs exist. + `authorityTuple` is copied without scalarization or field renaming from the complete canonical shape in the [JWT and token contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple). `membershipVersion` is the independently applicable Account membership-version map, including `{}` when no membership applies. `HumanAuthorityEvidence/v1` carries the Account-derived actor account, `control-ui` token `jti`, role, assurance, account generation, and applicable tenant or target-tenant generation. `AutomationAuthorityEvidence/v1` carries the exact authenticated workload, automation-policy identity/version, and applicable tenant generation. The tagged `issuanceEvidence` arm must agree with Account-derived `issuanceKind`; the inapplicable arm and inapplicable authority-scope identifiers are omitted rather than serialized as `null`, empty objects, or sentinels. `sourceEvidenceId` identifies the one Account authority snapshot and its linearization evidence, while `sourceEvidenceVersion` is the corresponding Account-issued source version; together they are the canonical source fence for the bundle and are carried unchanged with the existing `{bundleVersion, sourceVersion, sourceFence, linearization}` reference. Account derives every authority, generation, membership, freshness, and branch-decision member from that one atomic snapshot and stores the source pair with the issuance record. During redemption, Account exact-compares `sourceEvidenceId`, `sourceEvidenceVersion`, the bundle reference, and every snapshot-bound field against the stored issuance record and the current applicable authority evidence; a missing, changed, or mixed-version value rejects redemption. Consumers reject missing, extra, contradictory, separately sourced, stale, expired, wrongly tagged, or non-canonical bundle fields and must redeem the original reference with Account; a copied bundle never becomes a second authority. For every forwarded owner-mutation family, ADR 0048's canonical complete `postAuthorizationExecutionTuple` is the required post-authorization identity. It explicitly contains ADR 0048's stable `controlPlaneRequestId` for orchestration, reservation, lookup, and correlation across forwarding, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor/policy binding, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` defined above (whose issuance identity carries the tagged `actionFamilyRequestIdentity` for domain action/idempotency), and every schema-bound typed presence/absence value. `targetOwner` is distinct from `target`, immutable after reservation, and is never inferred from current routing or owner state. Reservation and pre-authorization Account issuance/recovery compare `preAuthorizationReservationTuple`; post-authorization tuple completion, owner idempotency, terminal/no-commit proof, result lookup, conflict handling, and any later fresh owner attempt carries and compares its own exact tuple; no participant may omit a required identity because it is unavailable locally. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index a0f538818b..ecdf83314b 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -181,6 +181,8 @@ Error precedence is canonical: (1) Account authenticates the exact immediate mTL These RPCs and schemas are accepted target state but are not present in the current Account proto or implementation. Logging & Admin remains the external operator ingress and durable intent/audit coordinator, Account remains the authorization authority and owner of original-reference retention, and the domain service remains the mutation owner. +For StartSession, Account's existing human authorization-reference issuer remains the sole issuer and the original reference retains `targetOwner=game-session-service`. The distinct Account-owned same-namespace World receiving-participation and source-protection lifecycle is defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation); this API contract adds no replacement issuer, reference-renewal, or re-redemption path. The Game Design projection read and publication hold/settlement producers remain separate and grant no StartSession World permission. StartSession participation acquisition, World admission, terminal settlement, and their proof remain unimplemented. + ## REST APIs | Method | Path | Description | diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 0898a3bca0..18af0c617a 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -65,6 +65,8 @@ Automation's supported template sources are `SCRIPT` (including its owner-manage Automation and Entity authored source inventories are separate versioned `TEMPLATE_CONFIG` source operations, `DECLARE_OWNER_SOURCE_INVENTORY`, bound to the actual Draft commit. Automation retains its authored operation payload at `schemaVersion: 2`; Entity uses `schemaVersion: 3` so the existing Automation revision bytes keep their established meaning. Each revision remains owned by `GAME_DESIGN_CONTROL_PLANE`; `AUTOMATION_SCRIPTING` or `ENTITY_MANAGEMENT` identifies the content owner, not an owner commit participant. These operations carry no `templateId` and create no `game_templates` row. Game Design retains each declaration's original request, commit, revision ID/order, content owner, typed inventory content, and binding provenance in template source snapshot v2 and publication capture. A missing declaration remains unavailable evidence. Neither declaration replaces its owner's exact source readback, proves completeness of any inbound selected-source closure, or qualifies publication. The family schema and empty-only acceptance remain owned by [Automation](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) and [Entity Management](../entity-management-service/runtime-and-data.md#selected-entity-authored-source-inventory-empty-only-v1). +The World-authored selected-inbound closure is a separate declaration in the original World `freshGraphDeclaration`, not an inference from these Game Design template inventories. Its version-1 fixed family vector names loot-reference roots/attachments, behavior selections/bindings, and Automation hooks/script references/target bindings. The currently supported form is a source-authored zero for every family; unknown or nonempty members remain unsupported until their owner-specific identity, reference, dependency, and exact readback contracts exist. Missing old declarations do not qualify as empty, and a World APPLIED graph or publication inventory must retain the declaration from the original selected revision rather than synthesize it later. That closure changes the selected World participant digest to schema 4 and the release attestation to its separate schema-3 domain; the older release-attestation/v2 remains bound to World digest schema 3 and is never rewritten on retry. + Game Logic owns the version-scoped gameplay rules/configuration, not Automation. The authored `gameLogic.inputs[]` entries select Game Design-owned gameplay inputs by exact `{family, key, revisionId}` from the supported authored gameplay source families. They do not serialize Game Logic's derived receipt or invent per-rule IDs. For publication, Game Logic's genuine owner-retained receipt must be independently joined to the exact unchanged tenant, `baseVersionId`, and selected commit after source settlement and authorized intake. A missing receipt, changed input or commit, or merely latest receipt cannot satisfy the join; exact retries recover the original retained result. [Game Logic runtime/data](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake) defines the owner boundary and receipt semantics; this document does not define a receipt schema. Retaining and resolving authored input references does not establish that separate receipt or join, so no complete publishable config is claimed yet. `supportedSettings` is the explicitly non-authoritative settings subset accepted by this schema; it is closed and owner-defined, not arbitrary runtime configuration. No concrete non-authoritative setting members are currently registered. An explicitly authored empty collection is representable, but still requires the same authorized source-creation, selected-commit history and durable readback proof; missing settings storage or producers cannot supply it. `defaultRuntimeFlagsJson` and any other setting that changes launch/runtime behavior are authoritative inputs, not presentation settings, and must not be placed in this subset or marked optional. Adding a supported setting requires its owner, exact accepted member/value schema, and absence/fallback semantics to be defined before it can be authored. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 2855bb95a3..ad8fb94208 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -8,7 +8,7 @@ This API contract is target-state canonical; implementation coverage is partial - The bridge, cross-service callers, examples, and focused proof have not migrated together to the scoped decimal `roomInstanceId` contract. The checked-in proof still exercises the legacy encoding. - The typed `ApplyRoomAmbientStatePatch` contract below is target-state: the current service has no complete handler or durable operation/digest-bound guard, so player-significant ambient mutations remain on the fenced Game Session admission/reconciliation path and are not direct table writes. - `GetDraftDesignDigest` checks the exact Game Design workload/method boundary and validates the typed tenant/version, publication request, derived workflow identity and request digest before returning owner-matching scope. Missing authorization configuration denies the read. This read binding is not Account authoring authorization, release attestation or proof of the complete publication transaction. The canonical owner remains [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). -- The registered `ApplyWorldDesignMutation` handler fails closed before parsing or owner mutation until current Account commit authorization is verified. This denial does not implement the positive authenticated Game Design/Account commit boundary or repair the separate legacy REST generation-rule gap. +- The registered `ApplyWorldDesignMutation` handler fails closed before parsing or owner mutation until current Account commit authorization is verified. This denial does not implement the positive authenticated Game Design/Account commit boundary. V24 and V35 database guards also deny unqualified canonical generation-rule writes; no canonical production bypass through the legacy REST route is established by those guards. - The registered `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, `FailPreparedWorldInstance` and `TerminateWorldInstance` handlers allow only verified same-namespace Game Session workload identity before request parsing or owner calls. Missing configuration, missing peer identity and other workloads are denied; shared bearer claims do not substitute. Other pre-admission consumers are not currently allowlisted. This caller guard does not supply the remaining canonical preparation, activation, cleanup or admission proofs. - The standalone canonical initial-placement adapter now defines an Entity Management-only historical terminal-result read. Its proto and handler remain unregistered; the read supplies settlement evidence for the exact immutable placement operation, without admitting gameplay or directly mutating any hold. - The authored-world intake construction reads its complete immutable Game Design source through the exact authenticated owner-read contract in [Game Design API Contracts](../game-design-service/api-contracts.md#authored-world-source-readback). The intake transport remains unregistered and does not authorize source mutation, instance preparation, publication, or runtime admission. @@ -41,6 +41,10 @@ The separate `WorldAuthoredVersionIdentityService.AssociateAuthoredWorldVersion` `WorldOriginalDraftGraphApplyService.ApplyOriginalDraftGraph` is a distinct Game Design-to-World application and exact-recovery boundary for the bounded fresh-graph path. Its closed version-1 request carries the trusted namespace and the unchanged complete original Account Draft-order binding. World authenticates the exact same-namespace Game Design workload, without authenticated end-user context, before decoding or consulting owner storage. The complete derived owner vectors must be exactly Game Design and World; a caller cannot filter a larger operation into this path. The original bytes are operation identity, not Account permission or caller-provided private owner keys. +A new APPLIED fresh graph additionally requires the original World revision's versioned `freshGraphDeclaration.inboundSourceClosure`. Declaration schema 1 closes these seven selected-inbound families: loot-reference roots and attachments; behavior selections and bindings; Automation hooks, script references, and target bindings. The current supported subset contains only an explicit zero for every family in the fixed order. Nonzero, missing, unknown, malformed, or opaque input is unsupported and denies before graph persistence; omission in retained older history is not an empty declaration and cannot be promoted to a new APPLIED result or selected publication inventory. The canonical graph copies the declaration from the exact original source preimage, while the immutable APPLIED binding continues to retain the original revision bytes, under the existing same-transaction World owner/fence guards. No member grammar or nonempty producer is defined here. + +For a new selected-publication checkpoint, World computes selected-only digest schema `4` over the unchanged ordered six-family digest input plus that exact original closure. The generic `GetDraftDesignDigest` response remains schema `3`; the selected checkpoint is recomputed under the same owner lock from the APPLIED graph and declared closure. Release-attestation/v2 remains paired with World/3, while closure-qualified selected release-attestation/v3 is paired only with World/4. Older immutable freeze, graph, snapshot, inventory, and attestation bytes keep their original schemas and exact replay behavior; absence of the new declaration never qualifies an old graph as empty and no retry recaptures newer source state. + Before a new application, World resolves one exact retained authored-Version association for the canonical tenant, Version UUID and Game Design Version row. It independently reads the retained source intake and validates the complete Game Design row/key/provenance relationship against the original target. Missing, ambiguous or contradictory associations deny; the receiver never chooses a World slug, infers a numeric mapping or creates a source association on this read. World derives its complete private owner binding from those receipts, derives the topology plan from the unchanged original typed World revisions, and enters the existing Account held-order verification and atomic graph/epoch/result transaction. The complete fresh-family declaration and Account protection through the actual mutation remain required. This transport does not relax physical-deadline enforcement or supply unavailable currentness machinery. An exact committed retry recovers the original World result before recapturing mutable identity or creator authority. A successful response echoes the complete request and returns the canonical World `COMMITTED` owner readback containing the actual `APPLIED` graph, original operation, start-location evidence and complete resulting epoch vector. Game Design authenticates World and verifies that full binding before retaining its coordinator result. Unknown, missing, corrupt or unavailable evidence returns no successful result: it cannot assert definitive abort, release participation, advance the synchronized Draft fence or authorize a new operation. Account's separate World-terminal reader remains Account-only; this application transport grants no access to that method. The standalone construction remains unregistered and grants no publication, preparation or gameplay admission. Executed proof and remaining composition limits belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 9aa1c4800e..0556d04e48 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -184,7 +184,7 @@ Implementation Notes: - stable table ordering; - primary-key ordering within each table; - deterministic encoding for included semantic fields. -- Current implementation note: the concrete first-slice table order is `regions`, `zones`, `rooms`, `roomExits`, `generationRules`, then `worldEntitySpawnBindings`, each ordered by ascending primary key. Nested object fields are sorted by key, and null string values are canonicalized as empty strings before hashing. The current World digest schema version is `3`, superseding schema `2` because spawn references now use the tagged `entityReference` serialization. Previously retained schema-2 evidence must not be relabeled as schema 3; schema adoption requires recomputation and replay or re-recording under the publication digest migration rules in [Game Design Version Control](../game-design-service/version-control.md#digest-schema-migration). This serialization change does not close the generic digest's synthetic applied-commit gap described above. +- Current implementation note: the concrete first-slice table order is `regions`, `zones`, `rooms`, `roomExits`, `generationRules`, then `worldEntitySpawnBindings`, each ordered by ascending primary key. Nested object fields are sorted by key, and null string values are canonicalized as empty strings before hashing. Generic World digest schema `3` supersedes schema `2` because spawn references use the tagged `entityReference` serialization. New selected-publication checkpoints use schema `4`, which binds that same ordered six-family manifest plus the exact version-1 selected-inbound closure copied from the original fresh World revision. Schema `4` is selected-only; the generic `GetDraftDesignDigest` contract remains schema `3`. A release-attestation/v2 retains the exact World/3 pair, while new closure-qualified selected releases use release-attestation/v3 and World/4. Previously retained schema-2/3 evidence is never relabeled or recaptured; exact retries return original immutable bytes under the publication digest migration rules in [Game Design Version Control](../game-design-service/version-control.md#digest-schema-migration). The selected closure adds no physical table to the six-family manifest. This semantic versioning does not close the generic digest's synthetic applied-commit gap described above. - `digestSchemaVersion` must increment whenever included tables, field-selection rules, or canonical serialization semantics change. Publish gating fails closed if World Management cannot attest a digest consistent with this manifest. @@ -197,7 +197,7 @@ World owns a typed, authenticated, immutable `COMPLETE` inventory for the exact The authenticated owner read takes the exact original freeze request and committed acknowledgement as lookup identity, verifies them against the retained attempt and original Account order, and returns only the closed canonical public inventory and its public-view digest. Its same-namespace Game Design workload check precedes parsing and storage access; end-user context and ambient owner transactions are rejected. Private numeric owner/source keys and raw Account binding bytes remain outside the public inventory. Public region-generator and spawn-binding inputs use unique canonical UUID-string order, independently of the retained private envelope's source order. This projection never rewrites private history. Byte/digest validation alone does not authenticate the producer; the client must verify the concrete World workload identity over mTLS. -The inventory identifies a versioned, closed source model and enumerates all six current topology families from the digest manifest, including explicit zero counts. Its requiredness evaluation covers the complete typed topology, region generator type/parameters, generation-rule name/scope/value, and typed spawn bindings. Unknown schemas, fields, families, omitted requiredness inputs, or unrepresentable generation semantics deny `COMPLETE`; missing producer rows or runtime consumers never establish that an artifact is unnecessary. The direct-authored room/exit model uses its persisted directed edges and does not require a separate generated navigation bundle; typed room-bound spawn references alone do not change that rule. Opaque generation inputs cannot inherit this classification without a defined, proved requiredness interpretation. +The inventory identifies a versioned, closed source model and enumerates all six current topology families from the digest manifest, including explicit zero counts. Its requiredness evaluation covers the complete typed topology, region generator type/parameters, generation-rule name/scope/value, and typed spawn bindings. The public inventory schema v2 also carries the exact original graph's version-1 selected-inbound declaration for loot-reference roots and attachments, behavior selections and bindings, and Automation hooks, script references, and target bindings. Its checkpoint must be World digest schema `4`; legacy inventory/v1 remains paired with World/3 and is read only from its exact retained history. Only the complete fixed-order all-zero inbound vector is supported; nonempty or opaque values are rejected because no member grammar or producer/readback contract is established. A missing declaration in older graph/inventory bytes remains unavailable evidence and is never normalized to empty. New graph/3 and inventory/v2 bytes retain the source-authored declaration; exact retries preserve the original bytes and do not recapture mutable source state. Unknown schemas, fields, families, omitted requiredness inputs, or unrepresentable generation semantics deny `COMPLETE`; missing producer rows or runtime consumers never establish that an artifact is unnecessary. The direct-authored room/exit model uses its persisted directed edges and does not require a separate generated navigation bundle; typed room-bound spawn references alone do not change that rule. Opaque generation inputs cannot inherit this classification without a defined, proved requiredness interpretation. The complete derived-family enumeration includes `NAVMESH` and `PATH_GRAPH`, each with an explicit decision bound to those source inputs. If the selected source requires either family, publication requires the actual finalized producer record and byte digest under the [Game Design asset handoff](../game-design-service/asset-storage.md#complete-selected-release-asset-inventory); an absent producer denies that release, rather than changing its requiredness or omitting the family. A supported release must not be relabeled empty or unsupported merely to avoid producing its required artifacts. 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 401fd73b66..1e026fb708 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 @@ -10,7 +10,9 @@ Published `97174b31be2ed08440be1a271cc00359614abaf6` [Validation run 37945686843 Published `f580093d113630e8335c301a7ecb31d6a4bf4acd` [Validation run 37951600583](https://github.com/benhook1013/FireMUD/actions/runs/37951600583) executed 254 Account and 207 World PostgreSQL cases successfully with no failures, errors or skips. Game Design executed 524 unit cases successfully and 148 PostgreSQL cases with three failures and no skips: two authored Automation declarations reached the deferred atomic-result guard, which counted all template-config operations only against ordinary template rows; the genuine export progressed beyond the original World-delivery correction but had no authored realm policy. The current correction extends that guard in forward V68 to count exact declaration rows separately while retaining complete coordinator-result, epoch and sibling-source checks. The export fixture now authors and reads back its required realm policy in the original selected commit. The actual CI checkout is synthetic merge `0744b12a806c8a484df3e15c796e9f76532dc64d`, tree `c784e788550a4ae61f0b3df84a711cecc79933b0`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published source; this is exact-source execution, not intended-parent alignment or proof of the corrected state. -The current source-inventory construction retains genuinely authored Automation and Entity `TEMPLATE_CONFIG` declarations, immutable original revision provenance and snapshot v2; it creates no template row or Entity/Automation commit participation. Automation's published operation bytes remain schema version 2; Entity's new closed operation uses version 3 and its mandatory 23-family empty-only declaration with explicit equipment non-applicability. Forward migration V68 extends the owner guard without rewriting V67 or historical source bytes. The PostgreSQL definitions preserve the genuine V67 ordinary-template v1 snapshot, demonstrate a complete Automation transaction rejected and rolled back by the V67 guard, then retry that same binding after V68. They verify actual V68 Automation content, binding, application bytes and provenance through later Entity application, inheritance and exact retry, plus missing or altered coordinator-result denial. Common's preceding full check executed 457 unit cases successfully. The final affected Game Design schema generation, full check, boot JAR and documentation gate passes in 37s with 525 unit cases executed; all 147 local integration cases compile/discover but skip without Docker. The complete-transaction upgrade assertion and new migration and transport definitions therefore have no physical execution proof yet. Neither declaration is an owner receipt. Separate Entity/Automation Account-authorized intake, held current-authority retention, and authenticated full selected World/inbound closure remain missing. World's exact frozen six-family topology inventory exposes typed ITEM/NPC spawn inputs, but does not supply selected loot/behavior/hook closure; a zero topology count cannot certify those missing producers. The genuine fixture now invokes the real complete-launch-binding handler and World mTLS client, with exact readback/retry, peer-first denial, substitution and no-mutation assertions. Its Account StartSession projection, Entity/Automation participation and object-store transport remain explicit test doubles; production certificate mounting, current Game Session `STARTING` evidence and World held commit-authority verification remain unproved. All four Gameplay handoffs and activation remain open. +Published `d10bcf5f7edd462a248ea1fa57dff5d3627c4550` [Validation run 37956697790](https://github.com/benhook1013/FireMUD/actions/runs/37956697790) physically executed 254 Account and 207 World PostgreSQL cases successfully and 150 Game Design cases with two assertion failures, no errors or skips. The V67-to-V68 complete-transaction upgrade, immutable original declaration provenance, and missing or altered coordinator-result negatives passed. The genuine selected export compared a UUID string with a UUID value; the Automation inheritance case compared the selected capture with the preceding template commit instead of checking selected identity and original declaration provenance separately. Both corrections are included in the next local batch; neither is evidence of a production serialization or object-identity defect. The synthetic checkout `e693cc61cad15839f697f522f46fc4d13e227884`, tree `653e76a45375b278100ec65bf7efce3e49866472`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published source, not the intended integration parent. The Account Draft artifact's 31 passing cases are a subset of Account's 254, not additional proof. + +The source-inventory construction retains genuinely authored Automation and Entity `TEMPLATE_CONFIG` declarations, immutable original revision provenance and snapshot v2; these are not Entity/Automation participation or receipts. Automation operation bytes remain schema version 2; the new Entity operation uses version 3. The closure-qualified batch adds an explicitly authored World inbound-closure declaration, graph schema 3, selected participant digest schema 4, inventory v2 and release attestation v3, with forward World V59–V61 and Game Design V69 guards. The shared terminal-read codec derives the graph schema from the original Account-bound declaration and rejects missing, substituted, downgraded or result-only closure even when result digests are rebound. Consolidated local validation passed: 464 Common, 589 World and 529 Game Design cases executed without failures, errors or skips; 208 World and 147 Game Design PostgreSQL cases compiled/discovered but skipped without Docker. Schema generation, formatting, Checkstyle, SpotBugs, coverage, both service boot JARs, links and Markdown passed. Physical PostgreSQL execution of this changed batch remains required. Historical immutable bytes remain distinct and cannot be promoted into empty-source proof. Separate Entity/Automation Account-authorized intake and held current-authority retention remain missing. The genuine fixture invokes the real complete-launch-binding handler and World mTLS client, but its Account StartSession projection, Entity/Automation participation and object-store transport remain explicit test doubles. Production certificate mounting, authenticated current Game Session `STARTING` attempt/fence evidence, and the distinct Account/World execution-participation and terminal-serialization protocol remain unproved. All four Gameplay handoffs and activation remain open. Published `9f287e05e06b87adc3db79984b2e047e5d5b819f` [Validation run 37939078493](https://github.com/benhook1013/FireMUD/actions/runs/37939078493) executed 146 Game Design PostgreSQL cases with one failure, 254 Account cases with one failure, and 207 World cases with no failures; all three suites report zero skips and errors. The three genuine GD+World source/settlement cases, genuine Game Logic intake case, approved-remap retention correction and eight legacy descriptor persistence/retry/migration cases passed. The genuine selected export/descriptor case failed before export because its stipulated World evidence supplied a prefixed content hash to a bare-hex field. Since that run, the local construction has replaced the stipulated Account publication-order and World freeze/inventory/selector evidence with the actual owner reads and adds canonical topology capture after freeze. This new composition has no physical proof yet. Account's failure moved to the physical-confirmation/independent-read case and again denied at V90's conservative coverage prerequisite: insert `0/7EDFE48` exceeded initial/final flush `0/7EDFE08` while the original bound remained unchanged. A bounded fixture diagnosis is separate from source/release construction. Overseer deferred production WAL-locator adoption; the prototype, original JVM acknowledgement/time bounds, V90/V92 recovery semantics and PostgreSQL-version guards remain unchanged. The actual synthetic checkout is `1822fbae8dc9f6c4409ccc9515a99ee5e5f42e99`, tree `dc3142f6c4284288a43ed71d97632c35ee4afe09`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published source. This is exact-source execution, not intended-parent alignment, a genuine complete release or activation. diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index c324a41ace..4ca2622d1a 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -504,12 +504,37 @@ message WorldFreshGraphFamilyCount { optional int32 count = 2; } +enum WorldInboundSourceFamily { + WORLD_INBOUND_SOURCE_FAMILY_UNSPECIFIED = 0; + WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT = 1; + WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT = 2; + WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION = 3; + WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING = 4; + WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK = 5; + WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE = 6; + WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING = 7; +} + +message WorldInboundSourceFamilyCount { + WorldInboundSourceFamily family = 1; + // Presence is carried by this repeated entry; only a source-authored zero is currently supported. + optional int32 count = 2; +} + +// Versioned, closed selected-inbound declaration. This schema defines family identities and +// counts only; nonempty member grammar remains unsupported and must be rejected by consumers. +message WorldInboundSourceClosureDeclaration { + uint32 schema_version = 1; + repeated WorldInboundSourceFamilyCount family_counts = 2; +} + // Complete fresh graph declaration bound into the original Game Design revision payload. message WorldFreshGraphDeclaration { string tenant_id = 1; string version_id = 2; RoomTemplateRef start_location = 3; repeated WorldFreshGraphFamilyCount family_counts = 4; + WorldInboundSourceClosureDeclaration inbound_source_closure = 5; } enum WorldDesignMutationResult { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java index a826e79d17..45be5d4317 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodec.java @@ -60,6 +60,17 @@ public final class WorldDraftTerminalReadGrpcCodec { "appliedEpochs"); private static final Set FRESH_GRAPH_DECLARATION_FIELDS = Set.of("tenantId", "versionId", "startLocation", "familyCounts"); + private static final Set CLOSED_FRESH_GRAPH_DECLARATION_FIELDS = + Set.of("tenantId", "versionId", "startLocation", "familyCounts", "inboundSourceClosure"); + private static final List INBOUND_SOURCE_FAMILIES = + List.of( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING"); private static final Set ROOM_TEMPLATE_REF_FIELDS = Set.of("tenantId", "versionId", "roomTemplateId"); private static final Set FAMILY_COUNT_FIELDS = Set.of("family", "count"); @@ -316,9 +327,27 @@ static void requireCommittedResult( String graphDigest = sha256(graph); exactText(result, "graphDigest", graphDigest); JsonNode graphValue = JSON.readTree(graph); - fields( - graphValue, Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows")); - exactText(graphValue, "schemaVersion", "2"); + JsonNode originalClosure = + originalGraph == null ? null : originalGraph.inboundSourceClosure(); + if (originalClosure == null) { + fields( + graphValue, Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows")); + exactText(graphValue, "schemaVersion", "2"); + } else { + fields( + graphValue, + Set.of( + "schemaVersion", + "canonicalTenantId", + "canonicalVersionId", + "inboundSourceClosure", + "rows")); + exactText(graphValue, "schemaVersion", "3"); + if (!originalClosure.equals(graphValue.get("inboundSourceClosure"))) { + throw new IllegalArgumentException( + "World applied graph closure differs from its original Account-bound source"); + } + } exactText(graphValue, "canonicalTenantId", account.tenantId().toString()); exactText(graphValue, "canonicalVersionId", account.versionId().toString()); if (!graphValue.get("rows").isArray() || graphValue.get("rows").isEmpty()) @@ -428,7 +457,13 @@ private static OriginalFreshGraph readOriginalFreshGraph( private static OriginalFreshGraph parseOriginalFreshGraph( JsonNode declaration, Map nodes, DraftCommitBinding draft) { - fields(declaration, FRESH_GRAPH_DECLARATION_FIELDS); + JsonNode inboundSourceClosure = declaration.get("inboundSourceClosure"); + fields( + declaration, + inboundSourceClosure == null + ? FRESH_GRAPH_DECLARATION_FIELDS + : CLOSED_FRESH_GRAPH_DECLARATION_FIELDS); + if (inboundSourceClosure != null) requireEmptyInboundSourceClosure(inboundSourceClosure); UUID tenantId = parseCanonicalNonNilUuid(text(declaration, "tenantId"), "declaration tenantId"); UUID versionId = parseCanonicalNonNilUuid(text(declaration, "versionId"), "declaration versionId"); @@ -483,7 +518,37 @@ private static OriginalFreshGraph parseOriginalFreshGraph( roomTemplateId, selectedRoom, Map.copyOf(nodes), - List.copyOf(nodes.values())); + List.copyOf(nodes.values()), + inboundSourceClosure); + } + + private static void requireEmptyInboundSourceClosure(JsonNode closure) { + fields(closure, Set.of("schemaVersion", "familyCounts")); + JsonNode schemaVersion = closure.get("schemaVersion"); + JsonNode counts = closure.get("familyCounts"); + if (schemaVersion == null + || !schemaVersion.isIntegralNumber() + || !schemaVersion.canConvertToInt() + || schemaVersion.intValue() != 1 + || counts == null + || !counts.isArray() + || counts.size() != INBOUND_SOURCE_FAMILIES.size()) { + throw new IllegalArgumentException( + "Original World inbound closure requires the complete version-1 family vector"); + } + for (int index = 0; index < INBOUND_SOURCE_FAMILIES.size(); index++) { + JsonNode entry = counts.get(index); + fields(entry, FAMILY_COUNT_FIELDS); + exactText(entry, "family", INBOUND_SOURCE_FAMILIES.get(index)); + JsonNode count = entry.get("count"); + if (count == null + || !count.isIntegralNumber() + || !count.canConvertToInt() + || count.intValue() != 0) { + throw new IllegalArgumentException( + "Original World inbound closure is outside the supported explicit empty-only subset"); + } + } } private static void validateDeclaredGraphRows( @@ -626,7 +691,8 @@ private record OriginalFreshGraph( UUID roomTemplateId, OriginalGraphNode selectedRoom, Map nodes, - List orderedNodes) {} + List orderedNodes, + JsonNode inboundSourceClosure) {} private static void fields(JsonNode value, Set fields) { if (value == null diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java index 41a344e41f..8533583c91 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java @@ -49,9 +49,12 @@ public record AuthoredWorldReleaseAttestationEvidence( WorldPublishedStartLocationEvidence worldStartLocationEvidence) { public static final int SCHEMA_VERSION = 1; public static final int SELECTOR_SCHEMA_VERSION = 2; + public static final int CLOSURE_SELECTOR_SCHEMA_VERSION = 3; private static final String EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v1"; private static final String SELECTOR_EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v2"; + private static final String CLOSURE_SELECTOR_EVIDENCE_DOMAIN = + "game-design-authored-world-release-attestation/v3"; private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); private static final Pattern PARTICIPANT_CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); @@ -85,11 +88,12 @@ public static int supportedParticipantDigestSchema(String participantKey) { return supportedParticipantDigestSchema(participantKey, SCHEMA_VERSION); } - /** Selects owner schemas from the explicit retained-v1 or selected-publication-v2 contract. */ + /** Selects owner schemas from the retained-v1, selected-v2, or closure-selected-v3 contract. */ public static int supportedParticipantDigestSchema( String participantKey, int attestationSchemaVersion) { if (attestationSchemaVersion != SCHEMA_VERSION - && attestationSchemaVersion != SELECTOR_SCHEMA_VERSION) { + && attestationSchemaVersion != SELECTOR_SCHEMA_VERSION + && attestationSchemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION) { throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); } Objects.requireNonNull(participantKey, "participantKey"); @@ -97,12 +101,25 @@ public static int supportedParticipantDigestSchema( if (version == null) { throw new IllegalArgumentException("Unsupported full-Version participant owner"); } - return attestationSchemaVersion == SELECTOR_SCHEMA_VERSION + if (attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION + && "WORLD_MANAGEMENT".equals(participantKey)) { + return 4; + } + return isSelectedSchema(attestationSchemaVersion) && "GAME_DESIGN_CONTROL_PLANE".equals(participantKey) ? 2 : version; } + public static boolean requiresWorldStartLocationEvidence(int attestationSchemaVersion) { + return isSelectedSchema(attestationSchemaVersion); + } + + private static boolean isSelectedSchema(int attestationSchemaVersion) { + return attestationSchemaVersion == SELECTOR_SCHEMA_VERSION + || attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION; + } + /** One successful, immutable owner digest included in the release attestation. */ public record Participant( String participantKey, @@ -156,7 +173,9 @@ public record Artifact( } public AuthoredWorldReleaseAttestationEvidence { - if (schemaVersion != SCHEMA_VERSION && schemaVersion != SELECTOR_SCHEMA_VERSION) { + if (schemaVersion != SCHEMA_VERSION + && schemaVersion != SELECTOR_SCHEMA_VERSION + && schemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION) { throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); } Objects.requireNonNull(targetNamespace, "targetNamespace"); @@ -193,9 +212,9 @@ public record Artifact( } requireText(generationConfigRevision, "generationConfigRevision"); requireDigest(evidenceDigest, "evidenceDigest"); - if ((schemaVersion == SELECTOR_SCHEMA_VERSION) != (worldStartLocationEvidence != null)) { + if (requiresWorldStartLocationEvidence(schemaVersion) != (worldStartLocationEvidence != null)) { throw new IllegalArgumentException( - "Only release-attestation/v2 requires World selector evidence"); + "Selected release-attestation schemas require World selector evidence"); } if (worldStartLocationEvidence != null) { WorldPublishedStartLocationEvidence.fromStored(worldStartLocationEvidence.canonicalBytes()); @@ -284,10 +303,102 @@ public static AuthoredWorldReleaseAttestationEvidence create( List commandDefinitions, String generationConfigRevision, WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + return createSelected( + SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + worldStartLocationEvidence); + } + + /** Creates v3 for a selected World closure-qualified schema-4 participant digest. */ + public static AuthoredWorldReleaseAttestationEvidence createClosureSelector( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + return createSelected( + CLOSURE_SELECTOR_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + worldStartLocationEvidence); + } + + private static AuthoredWorldReleaseAttestationEvidence createSelected( + int schemaVersion, + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { Objects.requireNonNull(worldStartLocationEvidence, "worldStartLocationEvidence"); var provisional = new AuthoredWorldReleaseAttestationEvidence( - SELECTOR_SCHEMA_VERSION, + schemaVersion, targetNamespace, descriptorResultDigest, canonicalTenantId, @@ -310,7 +421,7 @@ public static AuthoredWorldReleaseAttestationEvidence create( "sha256:" + "0".repeat(64), worldStartLocationEvidence); return new AuthoredWorldReleaseAttestationEvidence( - SELECTOR_SCHEMA_VERSION, + schemaVersion, targetNamespace, descriptorResultDigest, canonicalTenantId, @@ -527,16 +638,21 @@ public static byte[] evidencePreimage(AuthoredWorldReleaseAttestationEvidence ev field("commandDefinitions[" + index + "]", evidence.commandDefinitions().get(index))); } fields.add(field("generationConfigRevision", evidence.generationConfigRevision())); - if (evidence.schemaVersion() == SELECTOR_SCHEMA_VERSION) { + if (requiresWorldStartLocationEvidence(evidence.schemaVersion())) { fields.add( field( "worldStartLocationEvidence.canonicalBytesBase64", Base64.getEncoder() .encodeToString(evidence.worldStartLocationEvidence().canonicalBytes()))); } - return preimage( - evidence.schemaVersion() == SCHEMA_VERSION ? EVIDENCE_DOMAIN : SELECTOR_EVIDENCE_DOMAIN, - fields.toArray(Field[]::new)); + String domain = + switch (evidence.schemaVersion()) { + case SCHEMA_VERSION -> EVIDENCE_DOMAIN; + case SELECTOR_SCHEMA_VERSION -> SELECTOR_EVIDENCE_DOMAIN; + case CLOSURE_SELECTOR_SCHEMA_VERSION -> CLOSURE_SELECTOR_EVIDENCE_DOMAIN; + default -> throw new IllegalArgumentException("Unsupported release-attestation schema"); + }; + return preimage(domain, fields.toArray(Field[]::new)); } private static void validateParticipants( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java index 9f4fa09413..c538b6d30b 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -79,10 +79,16 @@ public record ReleaseContent( text(publishedReleaseBundleRef); text(publishWorkflowId); text(generationConfigRevision); - if (versionNumber <= 0 - || !"v2".equals(attestationSchemaVersion) - || manifestSchemaVersion != 1) { - throw new IllegalArgumentException("Complete full-Version bundle/v2 required"); + int selectedAttestationSchema = + switch (attestationSchemaVersion) { + case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case "v3" -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + default -> + throw new IllegalArgumentException( + "Complete full-Version bundle/v2 or bundle/v3 required"); + }; + if (versionNumber <= 0 || manifestSchemaVersion != 1) { + throw new IllegalArgumentException("Complete full-Version bundle/v2 or bundle/v3 required"); } digest(manifestHash); artifactDigests = List.copyOf(artifactDigests); @@ -108,8 +114,7 @@ public record ReleaseContent( if (!owners.get(i).equals(p.participantKey()) || p.digestSchemaVersion() != AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - p.participantKey(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION) + p.participantKey(), selectedAttestationSchema) || p.baseVersionId() != null || !selected.appliedCommitId().equals(p.appliedCommitId()) || !p.scopeValue().matches("[1-9][0-9]*") diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java index 43df3884ca..b682cb12c5 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.common.publication; +import com.fasterxml.jackson.annotation.JsonInclude; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; @@ -33,6 +34,12 @@ public final class WorldSelectedPublicationArtifactInventoryEvidence { public static final String SCHEMA = "world-selected-publication-artifact-inventory/v1"; public static final String SOURCE_MODEL = "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1"; public static final int SCHEMA_VERSION = 1; + public static final String INBOUND_CLOSURE_SCHEMA = + "world-selected-publication-artifact-inventory/v2"; + public static final String INBOUND_CLOSURE_SOURCE_MODEL = + "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1"; + public static final int INBOUND_CLOSURE_SCHEMA_VERSION = 2; + public static final int INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION = 3; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); @@ -41,6 +48,15 @@ public final class WorldSelectedPublicationArtifactInventoryEvidence { private static final List FAMILY_ORDER = List.of( "REGION", "ZONE", "ROOM", "ROOM_EXIT", "GENERATION_RULE", "WORLD_ENTITY_SPAWN_BINDING"); + private static final List INBOUND_SOURCE_FAMILY_ORDER = + List.of( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING"); private static final List REGION_FIELDS = List.of( "id", @@ -411,8 +427,10 @@ private static void requireSupportedProfile( Checkpoint checkpoint, SourceModel model, List artifactDecisions) { - if (!SCHEMA.equals(schema) - || schemaVersion != SCHEMA_VERSION + boolean legacyProfile = SCHEMA.equals(schema) && schemaVersion == SCHEMA_VERSION; + boolean inboundClosureProfile = + INBOUND_CLOSURE_SCHEMA.equals(schema) && schemaVersion == INBOUND_CLOSURE_SCHEMA_VERSION; + if ((!legacyProfile && !inboundClosureProfile) || !"COMPLETE".equals(completeness) || artifactDecisions.size() != ARTIFACT_DECISIONS.size() || !artifactDecisions.equals(ARTIFACT_DECISIONS)) { @@ -465,9 +483,21 @@ private static void requireSupportedProfile( || checkpoint.digestSchemaVersion() <= 0) { throw new IllegalArgumentException("World checkpoint is incomplete or malformed"); } + int requiredCheckpointSchema = inboundClosureProfile ? 4 : 3; + if (checkpoint.digestSchemaVersion() != requiredCheckpointSchema) { + throw new IllegalArgumentException( + "World inventory profile differs from the exact participant digest schema"); + } - if (!SOURCE_MODEL.equals(model.modelId()) - || model.graphSchemaVersion() != 2 + boolean sourceModelMatches = + legacyProfile + ? SOURCE_MODEL.equals(model.modelId()) + && model.graphSchemaVersion() == 2 + && model.inboundSourceClosure() == null + : INBOUND_CLOSURE_SOURCE_MODEL.equals(model.modelId()) + && model.graphSchemaVersion() == INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION + && model.inboundSourceClosure() != null; + if (!sourceModelMatches || !isSha256(model.graphDigest()) || !isSha256(model.topologyResultDigest()) || model.generationRuleInputCount() != 0 @@ -480,6 +510,9 @@ private static void requireSupportedProfile( || model.familyCounts().size() != FAMILY_ORDER.size()) { throw new IllegalArgumentException("World source model is unsupported or incomplete"); } + if (inboundClosureProfile) { + requireEmptyInboundClosure(model.inboundSourceClosure()); + } for (int index = 0; index < FAMILY_ORDER.size(); index++) { FamilyCount count = model.familyCounts().get(index); if (!FAMILY_ORDER.get(index).equals(count.family()) || count.rowCount() < 0) { @@ -594,6 +627,22 @@ public record SpawnBindingInput( int spawnCount, int respawnDelaySeconds) {} + public record InboundSourceFamilyCount(String family, int count) { + public InboundSourceFamilyCount { + Objects.requireNonNull(family, "family"); + if (count < 0) { + throw new IllegalArgumentException("World inbound source count must be nonnegative"); + } + } + } + + public record InboundSourceClosureDeclaration( + int schemaVersion, List familyCounts) { + public InboundSourceClosureDeclaration { + familyCounts = List.copyOf(Objects.requireNonNull(familyCounts, "familyCounts")); + } + } + public record SelectedApplication( UUID applicationOperationId, UUID applicationRequestId, @@ -656,7 +705,46 @@ public record SourceModel( List spawnBindingInputs, int generationRuleInputCount, int spawnBindingCount, - List appliedEpochs) { + List appliedEpochs, + @JsonInclude(JsonInclude.Include.NON_NULL) + InboundSourceClosureDeclaration inboundSourceClosure) { + public SourceModel( + String modelId, + int graphSchemaVersion, + String graphDigest, + String topologyResultDigest, + List familyCounts, + List regionGeneratorInputs, + List generationRuleFields, + List regionFields, + List zoneFields, + List roomFields, + List roomExitFields, + List spawnBindingFields, + List spawnBindingInputs, + int generationRuleInputCount, + int spawnBindingCount, + List appliedEpochs) { + this( + modelId, + graphSchemaVersion, + graphDigest, + topologyResultDigest, + familyCounts, + regionGeneratorInputs, + generationRuleFields, + regionFields, + zoneFields, + roomFields, + roomExitFields, + spawnBindingFields, + spawnBindingInputs, + generationRuleInputCount, + spawnBindingCount, + appliedEpochs, + null); + } + public SourceModel { familyCounts = List.copyOf(Objects.requireNonNull(familyCounts, "familyCounts")); regionGeneratorInputs = @@ -674,4 +762,20 @@ public record SourceModel( appliedEpochs = List.copyOf(Objects.requireNonNull(appliedEpochs, "appliedEpochs")); } } + + private static void requireEmptyInboundClosure(InboundSourceClosureDeclaration declaration) { + if (declaration == null + || declaration.schemaVersion() != 1 + || declaration.familyCounts().size() != INBOUND_SOURCE_FAMILY_ORDER.size()) { + throw new IllegalArgumentException( + "World inbound source closure is not the complete supported version-1 family vector"); + } + for (int index = 0; index < INBOUND_SOURCE_FAMILY_ORDER.size(); index++) { + var count = declaration.familyCounts().get(index); + if (!INBOUND_SOURCE_FAMILY_ORDER.get(index).equals(count.family()) || count.count() != 0) { + throw new IllegalArgumentException( + "World inbound source closure is not canonical or contains unsupported nonempty input"); + } + } + } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java index 6ad7be6478..cef01812bf 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java @@ -204,10 +204,11 @@ private static void requireExactBinding( throw new IllegalArgumentException( "World lifecycle request differs from the complete launch binding"); } - if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + if (!AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + release.schemaVersion()) || release.worldStartLocationEvidence() == null) { throw new IllegalArgumentException( - "World lifecycle evidence requires the complete selector/v2 release attestation"); + "World lifecycle evidence requires complete selected-release selector evidence"); } WorldDraftStartLocationEvidence selectorReceipt = WorldDraftStartLocationEvidence.fromStored( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java index 4cfb655ea6..ca96738448 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidence.java @@ -187,10 +187,11 @@ public record GenerationRequirement( throw new IllegalArgumentException( "Release attestation digest differs from the exact source-read selector"); } - if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + if (!AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + release.schemaVersion()) || release.worldStartLocationEvidence() == null) { throw new IllegalArgumentException( - "Published spawn requirements require the schema-2 release World selector"); + "Published spawn requirements require selected release World selector evidence"); } String boundGraphDigest = WorldDraftStartLocationEvidence.fromStored( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java index 2db322fe14..c4a6cac26c 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java @@ -485,7 +485,7 @@ public record Request( requireText(publishWorkflowId, "publishWorkflowId"); requireText(appliedCommitId, "appliedCommitId"); requireSha256(contentDigest, "contentDigest"); - if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + if (digestSchemaVersion != 2 && digestSchemaVersion != 3 && digestSchemaVersion != 4) { throw new IllegalArgumentException("Unsupported World digest schema version"); } Objects.requireNonNull(worldAffectedTuples, "worldAffectedTuples"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java index 35bf6e7387..b793de1d90 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java @@ -311,6 +311,120 @@ void exactDeclaredV2CarrierRoundTripsWithItsOriginalRoomAndCompleteGraphDeclarat .containsExactly(committed.canonicalBytes()); } + @Test + void closureQualifiedGraph3RoundTripsWithoutChangingTheAppliedV2Envelope() throws Exception { + var request = freshGraphRequest(emptyInboundSourceClosure()); + var committed = committedReadback(request, true); + var result = object(committed.result()); + var graph = object(Base64.getDecoder().decode(result.get("graphBytesBase64").textValue())); + assertThat(result.get("schema").textValue()).isEqualTo("world-draft-graph-applied/v2"); + assertThat(graph.get("schemaVersion").textValue()).isEqualTo("3"); + assertThat(graph.get("inboundSourceClosure")).isEqualTo(emptyInboundSourceClosure()); + + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed)); + assertThat( + WorldDraftTerminalReadGrpcCodec.fromResponse(request, response) + .ownerReadback() + .orElseThrow() + .canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + } + + @Test + void graph3RejectsMissingSubstitutedOrDowngradedOriginalClosureDespiteReboundDigests() + throws Exception { + var request = freshGraphRequest(emptyInboundSourceClosure()); + var committed = committedReadback(request, true); + for (java.util.function.Consumer change : + List.>of( + graph -> graph.remove("inboundSourceClosure"), + graph -> graph.put("schemaVersion", "2"), + graph -> { + graph.put("schemaVersion", "2"); + graph.remove("inboundSourceClosure"); + }, + graph -> + ((tools.jackson.databind.node.ObjectNode) graph.get("inboundSourceClosure")) + .put("schemaVersion", 2), + graph -> + ((tools.jackson.databind.node.ObjectNode) + graph.get("inboundSourceClosure").get("familyCounts").get(0)) + .put("count", 1), + graph -> graph.put("inboundSourceClosure", "opaque"))) { + assertResultRejected(request, committed, changedGraphResult(request, committed, change)); + } + } + + @Test + void closureMustBeExplicitCompleteOrderedAndEmptyInOriginalAccountBoundSource() throws Exception { + for (java.util.function.Consumer change : + List.>of( + closure -> closure.put("schemaVersion", 2), + closure -> closure.put("schemaVersion", "1"), + closure -> closure.put("unsupported", "opaque"), + closure -> closure.put("familyCounts", "opaque"), + closure -> + ((tools.jackson.databind.node.ArrayNode) closure.get("familyCounts")).remove(0), + closure -> + ((tools.jackson.databind.node.ObjectNode) closure.get("familyCounts").get(0)) + .put("family", "WORLD_INBOUND_SOURCE_FAMILY_UNKNOWN"), + closure -> + ((tools.jackson.databind.node.ObjectNode) closure.get("familyCounts").get(0)) + .put("family", "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT"), + closure -> + ((tools.jackson.databind.node.ObjectNode) closure.get("familyCounts").get(0)) + .put("count", 1), + closure -> + ((tools.jackson.databind.node.ObjectNode) closure.get("familyCounts").get(0)) + .put("count", -1), + closure -> + ((tools.jackson.databind.node.ObjectNode) closure.get("familyCounts").get(0)) + .put("count", "0"), + closure -> + ((tools.jackson.databind.node.ObjectNode) closure.get("familyCounts").get(0)) + .remove("count"), + closure -> + ((tools.jackson.databind.node.ObjectNode) closure.get("familyCounts").get(0)) + .put("members", "opaque"))) { + var closure = emptyInboundSourceClosure(); + change.accept(closure); + var request = freshGraphRequest(closure); + var committed = committedReadback(request, true); + assertThatThrownBy( + () -> WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("substituted canonical APPLIED result"); + } + for (tools.jackson.databind.JsonNode closure : + List.of(JSON.getNodeFactory().nullNode(), JSON.getNodeFactory().textNode("opaque"))) { + var request = freshGraphRequest(closure); + var committed = committedReadback(request, true); + assertThatThrownBy( + () -> WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(committed))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void retainedGraph2CannotAcquireResultOnlyClosureInEitherAppliedEnvelope() throws Exception { + for (boolean fresh : List.of(false, true)) { + var request = fresh ? freshGraphRequest() : request(); + var committed = committedReadback(request, fresh); + for (String graphSchema : List.of("2", "3")) { + assertResultRejected( + request, + committed, + changedGraphResult( + request, + committed, + graph -> { + graph.put("schemaVersion", graphSchema); + graph.set("inboundSourceClosure", emptyInboundSourceClosure()); + })); + } + } + } + @Test void v2RejectsMalformedOrDigestSubstitutedOriginalOwnerGraphBytes() throws Exception { var request = freshGraphRequest(); @@ -584,12 +698,18 @@ private static byte[] originalBinding() { } private static WorldDraftTerminalReadEvidence.Request freshGraphRequest() throws Exception { - DraftCommitBinding draft = freshGraphBinding(); + return freshGraphRequest(null); + } + + private static WorldDraftTerminalReadEvidence.Request freshGraphRequest( + tools.jackson.databind.JsonNode closure) throws Exception { + DraftCommitBinding draft = freshGraphBinding(closure); return new WorldDraftTerminalReadEvidence.Request( 1, "test", uuid("33333333-3333-4333-8333-333333333333"), accountBinding(draft)); } - private static DraftCommitBinding freshGraphBinding() throws Exception { + private static DraftCommitBinding freshGraphBinding(tools.jackson.databind.JsonNode closure) + throws Exception { String declaration = JSON.writeValueAsString( Map.of( @@ -612,6 +732,11 @@ private static DraftCommitBinding freshGraphBinding() throws Exception { "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", "count", 0)))); + if (closure != null) { + var declared = object(declaration.getBytes(StandardCharsets.UTF_8)); + declared.set("inboundSourceClosure", closure); + declaration = JSON.writeValueAsString(declared); + } return DraftCommitBinding.create( new TargetProof( TENANT_ID, VERSION_ID, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), @@ -727,6 +852,11 @@ private static byte[] graphBytes( for (RevisionPayload revision : draft.revisions()) { if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; var mutation = JSON.readTree(revision.payload()); + var declaration = mutation.get("freshGraphDeclaration"); + if (declaration != null && declaration.has("inboundSourceClosure")) { + root.put("schemaVersion", "3"); + root.put("inboundSourceClosure", declaration.get("inboundSourceClosure")); + } String family = mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); var mapping = new java.util.LinkedHashMap(); @@ -828,6 +958,50 @@ private static tools.jackson.databind.node.ObjectNode selector( return (tools.jackson.databind.node.ObjectNode) receipt.get("startLocation"); } + private static tools.jackson.databind.node.ObjectNode emptyInboundSourceClosure() { + var closure = JSON.createObjectNode(); + closure.put("schemaVersion", 1); + var counts = closure.putArray("familyCounts"); + for (String family : + List.of( + "LOOT_REFERENCE_ROOT", + "LOOT_REFERENCE_ATTACHMENT", + "BEHAVIOR_SELECTION", + "BEHAVIOR_BINDING", + "AUTOMATION_HOOK", + "AUTOMATION_SCRIPT_REFERENCE", + "AUTOMATION_TARGET_BINDING")) { + counts.addObject().put("family", "WORLD_INBOUND_SOURCE_FAMILY_" + family).put("count", 0); + } + return closure; + } + + private static byte[] changedGraphResult( + WorldDraftTerminalReadEvidence.Request request, + DraftAuthorizationFenceBinding.OwnerReadback committed, + java.util.function.Consumer change) + throws Exception { + var result = object(committed.result()); + var graph = object(Base64.getDecoder().decode(result.get("graphBytesBase64").textValue())); + change.accept(graph); + byte[] graphBytes = canonical(graph); + String graphDigest = sha256(graphBytes); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graphBytes)); + result.put("graphDigest", graphDigest); + if (result.has("startLocationReceiptBase64")) { + var binding = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(binding.gameDesignBinding(), StandardCharsets.UTF_8), + binding.inputDigest()); + var receipt = receipt(request, draft, graphDigest); + result.put( + "startLocationReceiptBase64", Base64.getEncoder().encodeToString(canonical(receipt))); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + } + return canonical(result); + } + private static void assertReceiptChangeRejected( WorldDraftTerminalReadEvidence.Request request, DraftAuthorizationFenceBinding.OwnerReadback committed, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java index 58bec723ef..6e81e870cf 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java @@ -42,6 +42,73 @@ void v2BindsCompleteOriginalEvidenceInItsOwnDomainAndSurvivesStoredReadback() th .containsExactly(selector.appliedResultBytes()); } + @Test + void v3BindsClosureQualifiedWorldSchema4InItsOwnDomainAndSurvivesStoredReadback() + throws Exception { + var selector = selectorEvidence(4); + var descriptor = descriptor(selector); + var release = release(descriptor, selector, 3); + var stored = JSON.writeValueAsString(release); + var readback = JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class); + + assertThat(release.schemaVersion()) + .isEqualTo(AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION); + assertThat(release.participantDigests().getFirst().digestSchemaVersion()).isEqualTo(4); + assertThat(release.participantDigests().getLast().digestSchemaVersion()).isEqualTo(2); + assertThat(readback).isEqualTo(release); + readback.requireValid(descriptor); + assertThat( + new String( + AuthoredWorldReleaseAttestationEvidence.evidencePreimage(release), + StandardCharsets.UTF_8)) + .startsWith("49:game-design-authored-world-release-attestation/v3") + .contains("worldStartLocationEvidence.canonicalBytesBase64") + .endsWith(Base64.getEncoder().encodeToString(selector.canonicalBytes())); + + var wrongWorldSchema = + release.participantDigests().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + "WORLD_MANAGEMENT".equals(participant.participantKey()) + ? 3 + : participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) + .toList(); + assertThatThrownBy( + () -> + AuthoredWorldReleaseAttestationEvidence.createClosureSelector( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + release.publishWorkflowId(), + release.commitId(), + wrongWorldSchema, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision(), + selector)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + } + @Test void v1BytesAndDigestRemainUnchangedAndCannotBePromotedBySupplyingASelector() throws Exception { var selector = selectorEvidence(); @@ -197,6 +264,11 @@ private static List retaine } static WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + return selectorEvidence(3); + } + + private static WorldPublishedStartLocationEvidence selectorEvidence(int digestSchemaVersion) + throws Exception { var terminal = WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); var applied = @@ -231,7 +303,7 @@ static WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { "publish-workflow", account.commitId().toString(), "b".repeat(64), - 3, + digestSchemaVersion, tuples); var result = JSON.readTree(applied.result()); return new WorldPublishedStartLocationEvidence( @@ -278,6 +350,14 @@ static AuthoredWorldLaunchDescriptorEvidence descriptor( static AuthoredWorldReleaseAttestationEvidence release( AuthoredWorldLaunchDescriptorEvidence descriptor, WorldPublishedStartLocationEvidence selector) { + return release( + descriptor, selector, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + } + + private static AuthoredWorldReleaseAttestationEvidence release( + AuthoredWorldLaunchDescriptorEvidence descriptor, + WorldPublishedStartLocationEvidence selector, + int attestationSchemaVersion) { var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() .map( @@ -290,10 +370,34 @@ static AuthoredWorldReleaseAttestationEvidence release( selector.request().appliedCommitId(), "b".repeat(64), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner, attestationSchemaVersion), "GAME_LOGIC".equals(owner), "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); + if (attestationSchemaVersion + == AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION) { + return AuthoredWorldReleaseAttestationEvidence.createClosureSelector( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + selector); + } return AuthoredWorldReleaseAttestationEvidence.create( descriptor.targetNamespace(), descriptor.resultDigest(), diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java index 999ee9253a..b77ddf4ea6 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java @@ -18,6 +18,8 @@ import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; @@ -54,6 +56,87 @@ void roundTripsTypedPublicInventoryBoundToTheExactFreezeWithoutPrivateOwnerKeys( .isEqualTo(fixture.freezeEvidence().acknowledgement()); } + @Test + void roundTripsVersionedAuthoredEmptyInboundClosureThroughPublicCodec() { + var fixture = closureFixture(); + var publicEvidence = fixture.publicEvidence(); + var evidence = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + fixture.freezeEvidence(), publicEvidence); + var response = WorldSelectedPublicationArtifactInventoryGrpcCodec.toResponse(evidence); + var decoded = + WorldSelectedPublicationArtifactInventoryGrpcCodec.fromResponse( + fixture.freezeEvidence(), response); + + assertThat(decoded.publicEvidence()).isEqualTo(publicEvidence); + assertThat(decoded.publicEvidence().schema()) + .isEqualTo(WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA); + assertThat(decoded.publicEvidence().sourceModel().graphSchemaVersion()).isEqualTo(3); + assertThat(decoded.publicEvidence().sourceModel().inboundSourceClosure().familyCounts()) + .extracting(InboundSourceFamilyCount::count) + .containsExactly(0, 0, 0, 0, 0, 0, 0); + assertThat(new String(decoded.canonicalBytes(), StandardCharsets.UTF_8)) + .contains("inboundSourceClosure", "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING") + .doesNotContain("localTenantKey", "localVersionKey", "sourceGameRowId"); + String opaqueClosure = + new String(decoded.canonicalBytes(), StandardCharsets.UTF_8) + .replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"members\":[]"); + assertRejectedPublicJson(fixture, opaqueClosure); + } + + @Test + void versionedInboundClosureRejectsMissingUnknownAndNonemptyFamilies() { + var fixture = closureFixture(); + var original = fixture.publicEvidence(); + var inbound = original; + var model = inbound.sourceModel(); + + var nonempty = + new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 1), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + var unknown = + new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("UNKNOWN_FAMILY", 0), + model.inboundSourceClosure().familyCounts().get(1), + model.inboundSourceClosure().familyCounts().get(2), + model.inboundSourceClosure().familyCounts().get(3), + model.inboundSourceClosure().familyCounts().get(4), + model.inboundSourceClosure().familyCounts().get(5), + model.inboundSourceClosure().familyCounts().get(6))); + + assertThatThrownBy( + () -> + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + fixture.freezeEvidence(), withInboundClosure(inbound, nonempty))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported nonempty"); + assertThatThrownBy( + () -> + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + fixture.freezeEvidence(), withInboundClosure(inbound, unknown))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not canonical"); + assertThatThrownBy( + () -> + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + fixture.freezeEvidence(), withInboundClosure(inbound, null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source model is unsupported or incomplete"); + } + @Test void rejectsChangedFreezeDigestUnknownFieldsAndNoncanonicalOrOpenPublicBytes() { var fixture = fixture(); @@ -356,6 +439,80 @@ static Fixture fixture() { return new Fixture(freezeEvidence, publicEvidence); } + private static PublicEvidence inboundClosureEvidence(PublicEvidence original) { + return withInboundClosure( + original, + new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0)))); + } + + private static Fixture closureFixture() { + var base = fixture(); + var prior = base.freezeEvidence().acknowledgement(); + var acknowledgement = + new Acknowledgement( + prior.request(), + prior.intakeRequestId(), + prior.versionStateEpoch(), + prior.publicationFence(), + prior.ownerFreezePhase(), + prior.appliedCommitId(), + prior.contentDigest(), + 4); + var freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + prior.request(), + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + return new Fixture(freezeEvidence, inboundClosureEvidence(base.publicEvidence())); + } + + private static PublicEvidence withInboundClosure( + PublicEvidence original, InboundSourceClosureDeclaration inboundClosure) { + var prior = original.sourceModel(); + var source = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + prior.graphDigest(), + prior.topologyResultDigest(), + prior.familyCounts(), + prior.regionGeneratorInputs(), + prior.generationRuleFields(), + prior.regionFields(), + prior.zoneFields(), + prior.roomFields(), + prior.roomExitFields(), + prior.spawnBindingFields(), + prior.spawnBindingInputs(), + prior.generationRuleInputCount(), + prior.spawnBindingCount(), + prior.appliedEpochs(), + inboundClosure); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + original.completeness(), + original.ownerScope(), + original.selectedApplication(), + original.accountOrder(), + original.freeze(), + new Checkpoint( + original.checkpoint().appliedCommitId(), original.checkpoint().contentDigest(), 4), + source, + original.artifactDecisions()); + } + private static void assertRejectedPublicJson(Fixture fixture, String json) { byte[] bytes = json.getBytes(StandardCharsets.UTF_8); assertThatThrownBy( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java index 562e588825..247b555611 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java @@ -403,7 +403,7 @@ void rejectsUnselectedV1ReleaseAndMalformedLifecycleCountersOrDigests() throws E evidence.graphSha256(), evidence.preparationInputDigest())) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("selector/v2"); + .hasMessageContaining("complete selected-release selector evidence"); assertInvalid(evidence, evidence.runtimeRoomInstanceId(), evidence.lifecycleEpoch(), -1); assertInvalid(evidence, evidence.runtimeRoomInstanceId(), 0, evidence.rowVersion()); diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java index f7aeb7ae1b..d529ad025a 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java @@ -41,12 +41,49 @@ public static WorldSelectedPublicationArtifactInventoryEvidence stipulated( var original = DraftAuthorizationFenceBinding.fromStored(world.originalAccountBindingBytes()); var graph = WorldDraftStartLocationEvidence.fromStored(world.selectorReceiptBytes()).graphDigest(); + boolean closureQualified = request.digestSchemaVersion() == 4; + String inventorySchema = + closureQualified + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA + : WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA; + int inventorySchemaVersion = + closureQualified + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION + : WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA_VERSION; + String sourceModel = + closureQualified + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL + : WorldSelectedPublicationArtifactInventoryEvidence.SOURCE_MODEL; + int graphSchemaVersion = + closureQualified + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION + : 2; + var inboundClosure = + closureQualified + ? new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration( + 1, + List.of( + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))) + : null; UUID fixtureId = UUID.nameUUIDFromBytes("ISOLATED World inventory input".getBytes(StandardCharsets.UTF_8)); var evidence = new PublicEvidence( - WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA, - 1, + inventorySchema, + inventorySchemaVersion, "COMPLETE", new PublicOwnerScope( request.targetNamespace(), @@ -82,8 +119,8 @@ public static WorldSelectedPublicationArtifactInventoryEvidence stipulated( new Checkpoint( request.appliedCommitId(), request.contentDigest(), request.digestSchemaVersion()), new SourceModel( - WorldSelectedPublicationArtifactInventoryEvidence.SOURCE_MODEL, - 2, + sourceModel, + graphSchemaVersion, graph, sha256("ISOLATED topology result".getBytes(StandardCharsets.UTF_8)), List.of( @@ -138,7 +175,8 @@ public static WorldSelectedPublicationArtifactInventoryEvidence stipulated( new BigInteger(unit.expectedEpoch()) .add(BigInteger.ONE) .toString())) - .toList()), + .toList(), + inboundClosure), List.of( new ArtifactDecision( "NAVMESH", diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java index e694d7fba7..c6fd97f517 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java @@ -37,13 +37,15 @@ public record PublishedReleaseBundleDto( "Manifest schema and artifact proof must be present together"); } artifactDigests = artifactDigests == null ? null : List.copyOf(artifactDigests); - if ("v2".equals(attestationSchemaVersion) != (worldPublishedStartLocationEvidence != null)) { + boolean selectorSchema = + "v2".equals(attestationSchemaVersion) || "v3".equals(attestationSchemaVersion); + if (selectorSchema != (worldPublishedStartLocationEvidence != null)) { throw new IllegalArgumentException( - "Selector evidence requires bundle v2 and is mandatory for v2"); + "Selector evidence is mandatory for selected release schemas and forbidden historically"); } } - /** Original retained bundle construction shape; cannot construct a selector-bearing v2 bundle. */ + /** Original retained bundle construction shape; cannot construct a selector-bearing release. */ public PublishedReleaseBundleDto( Long id, String tenantId, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java index 6efe988911..0bfaeda361 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java @@ -466,7 +466,8 @@ private void requireReleaseMatches( || !Objects.equals(release.canonicalTenantId(), exact.association().canonicalTenantId()) || !Objects.equals(release.canonicalVersionId(), exact.association().canonicalVersionId()) || !Objects.equals(release.publishWorkflowId(), exact.association().publishWorkflowId()) - || !"v2".equals(release.attestationSchemaVersion()) + || !("v2".equals(release.attestationSchemaVersion()) + || "v3".equals(release.attestationSchemaVersion())) || !Objects.equals( release.worldPublishedStartLocationEvidence(), exact.worldPublishedStartLocationEvidence()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java index 20d09e6140..da6136d1f8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java @@ -231,7 +231,8 @@ private Result readSnapshot(Request request, StartSessionPostAuthorizationExecut .asRuntimeException()); if (!canonicalTenantId.equals(configuredRelease.canonicalTenantId()) || !canonicalVersionId.equals(configuredRelease.canonicalVersionId()) - || !"v2".equals(configuredRelease.attestationSchemaVersion())) { + || !("v2".equals(configuredRelease.attestationSchemaVersion()) + || "v3".equals(configuredRelease.attestationSchemaVersion()))) { throw new IllegalStateException("START_SESSION_CONFIGURED_RELEASE_IDENTITY_CONFLICT"); } workflowId = configuredRelease.publishWorkflowId(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index 516dfa2a06..925e7f2314 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java @@ -181,7 +181,7 @@ private PublishedReleaseBundle insertNewBundle( CanonicalSource source = findExactCanonicalSource(tx, bundle); rejectCallerIdentitySubstitution(bundle, source); verifySelectorSource(bundle, source); - if ("v2".equals(bundle.getAttestationSchemaVersion())) { + if (isSelectorSchema(bundle.getAttestationSchemaVersion())) { PublishedReleaseBundle existing = tx.selectFrom(TABLE_REF) .where(TENANT_ID.eq(bundle.getTenantId()).and(VERSION_ID.eq(bundle.getVersionId()))) @@ -357,7 +357,7 @@ private PublishedReleaseBundle toEntity(Record record) { private static void verifySelectorSource(PublishedReleaseBundle bundle, CanonicalSource source) { String bytes = bundle.getWorldPublishedStartLocationEvidenceJson(); - if (!"v2".equals(bundle.getAttestationSchemaVersion())) { + if (!isSelectorSchema(bundle.getAttestationSchemaVersion())) { if (bytes != null) { throw new IllegalArgumentException( "Selector evidence is forbidden on historical release schemas"); @@ -365,18 +365,26 @@ private static void verifySelectorSource(PublishedReleaseBundle bundle, Canonica return; } if (bytes == null) { - throw new IllegalArgumentException("World selector evidence is mandatory for release v2"); + throw new IllegalArgumentException( + "World selector evidence is mandatory for selected releases"); } var request = WorldPublishedStartLocationEvidence.fromStored(bytes.getBytes(StandardCharsets.UTF_8)) .request(); if (!request.canonicalTenantId().equals(source.canonicalTenantId()) || !request.canonicalVersionId().equals(source.canonicalVersionId()) - || !request.publishWorkflowId().equals(bundle.getPublishWorkflowId())) { + || !request.publishWorkflowId().equals(bundle.getPublishWorkflowId()) + || ("v2".equals(bundle.getAttestationSchemaVersion()) && request.digestSchemaVersion() != 3) + || ("v3".equals(bundle.getAttestationSchemaVersion()) + && request.digestSchemaVersion() != 4)) { throw new IllegalArgumentException( "World selector differs from exact Version source/workflow"); } } + private static boolean isSelectorSchema(String schemaVersion) { + return "v2".equals(schemaVersion) || "v3".equals(schemaVersion); + } + private record CanonicalSource(UUID canonicalTenantId, UUID canonicalVersionId) {} } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java index e1022aa7a9..92998f033a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java @@ -136,7 +136,32 @@ public CompleteLaunchBindingDto getCompleteLaunchBinding( requireManifestAndArtifactEvidence(bundle); AuthoredWorldReleaseAttestationEvidence releaseAttestation; - if ("v2".equals(bundle.attestationSchemaVersion())) { + if (PublishedReleaseBundleContract.CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + bundle.attestationSchemaVersion())) { + releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.createClosureSelector( + descriptor.targetNamespace(), + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersion.getCanonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + bundle.publishWorkflowId(), + commitId, + participants, + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + artifacts, + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.worldPublishedStartLocationEvidence()); + } else if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + bundle.attestationSchemaVersion())) { releaseAttestation = AuthoredWorldReleaseAttestationEvidence.create( descriptor.targetNamespace(), @@ -275,7 +300,7 @@ private void requireExactBundleBinding( || !Objects.equals(snapshotCanonicalVersionId, bundle.canonicalVersionId()) || !("v1".equals(bundle.attestationSchemaVersion()) && bundle.worldPublishedStartLocationEvidence() == null - || "v2".equals(bundle.attestationSchemaVersion()) + || PublishedReleaseBundleContract.isSelectorSchema(bundle.attestationSchemaVersion()) && bundle.worldPublishedStartLocationEvidence() != null) || !Objects.equals(bundle.id(), descriptor.releaseBundleId()) || !Objects.equals(bundle.versionId(), descriptor.versionId()) @@ -342,6 +367,7 @@ private List requirePartici switch (bundle.attestationSchemaVersion()) { case "v1" -> AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION; case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case "v3" -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; case null, default -> throw deny( "PARTICIPANT_EVIDENCE_INVALID", diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 6feb429934..f89ab10bd4 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -721,7 +721,7 @@ public void getPublishedReleaseBundle( requireLaunchAttestationReadAccess(); PublishedReleaseBundleDto bundle = versionService.getPublishedReleaseBundle(request.getTenantId(), request.getVersionId()); - PublishedReleaseBundleContract.requireSupportedSchemaForRead(bundle); + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(bundle); TemporalVersionPublishWorkflowMetadataResolver.WorkflowMetadata workflowMetadata = publishWorkflowMetadataResolver.resolve(bundle.publishWorkflowId()); builder.setBundle( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java index 144045ea62..7a236e1c59 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java @@ -244,7 +244,7 @@ public List collectScriptPatchParticipantDigests( @Override public void assertGatePassed( VersionDto version, List participantDigests) { - assertGatePassed(version, participantDigests, false); + assertGatePassed(version, participantDigests, null); } @Override @@ -253,13 +253,33 @@ public void assertSelectedGatePassed( if (version.scriptOnly()) { throw new IllegalArgumentException("Selected publication requires a full version"); } - assertGatePassed(version, participantDigests, true); + List worldDigests = + participantDigests == null + ? List.of() + : participantDigests.stream() + .filter(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey())) + .toList(); + if (worldDigests.size() != 1 || worldDigests.getFirst().digestSchemaVersion() == null) { + throw new PublishGateFailureException( + PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, + "publish gate failed: exact selected World digest schema is required"); + } + int selectedAttestationSchema = + switch (worldDigests.getFirst().digestSchemaVersion()) { + case 3 -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case 4 -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + default -> + throw new PublishGateFailureException( + PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, + "publish gate failed: unsupported selected World digest schema"); + }; + assertGatePassed(version, participantDigests, selectedAttestationSchema); } private void assertGatePassed( VersionDto version, List participantDigests, - boolean selectedPublication) { + Integer selectedAttestationSchema) { List expectedParticipants = version.scriptOnly() ? SCRIPT_PATCH_PARTICIPANTS : FULL_VERSION_PARTICIPANTS; List expectedParticipantKeyList = @@ -309,11 +329,10 @@ private void assertGatePassed( } String participantKey = digest.participantKey(); Integer supportedSchemaVersion; - if (selectedPublication) { + if (selectedAttestationSchema != null) { supportedSchemaVersion = AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participantKey, - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + participantKey, selectedAttestationSchema); } else { supportedSchemaVersion = participantKey == null diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java index e0bd7eef95..481be5f442 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java @@ -14,6 +14,7 @@ final class PublishedReleaseBundleContract { static final String SUPPORTED_ATTESTATION_SCHEMA_VERSION = "v1"; static final String SELECTOR_ATTESTATION_SCHEMA_VERSION = "v2"; + static final String CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION = "v3"; static final String SCHEMA_VERSION_UNSUPPORTED = "SCHEMA_VERSION_UNSUPPORTED"; static final String REPAIR_ATTESTATION_MISMATCH = "REPAIR_ATTESTATION_MISMATCH"; static final String REPAIR_ATTESTED_ASSET_KEY_MISMATCH = "REPAIR_ATTESTED_ASSET_KEY_MISMATCH"; @@ -29,14 +30,28 @@ static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { var evidence = Objects.requireNonNull(bundle.worldPublishedStartLocationEvidence(), "World evidence"); var request = evidence.request(); - if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion()) - || bundle.scriptOnly() + int selectorSchemaVersion = + switch (bundle.attestationSchemaVersion()) { + case SELECTOR_ATTESTATION_SCHEMA_VERSION -> + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION -> + AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + default -> + throw new IllegalArgumentException( + "World selector requires a selected publication release schema"); + }; + int expectedWorldDigestSchema = + selectorSchemaVersion == AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + ? 3 + : 4; + if (bundle.scriptOnly() || bundle.scriptPatchVersion() != null || !request.canonicalTenantId().equals(bundle.canonicalTenantId()) || !request.canonicalVersionId().equals(bundle.canonicalVersionId()) || !request.publishWorkflowId().equals(bundle.publishWorkflowId()) || bundle.manifestSchemaVersion() == null - || bundle.artifactDigests() == null) { + || bundle.artifactDigests() == null + || request.digestSchemaVersion() != expectedWorldDigestSchema) { throw new IllegalArgumentException( "World selector differs from complete immutable release binding"); } @@ -54,8 +69,7 @@ static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { || !Objects.equals( participant.digestSchemaVersion(), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant.participantKey(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION))) { + participant.participantKey(), selectorSchemaVersion))) { throw new IllegalArgumentException( "World selector requires all exact successful release participants"); } @@ -85,11 +99,22 @@ static void requireExactSelectorRetry( String generationRevision, List participants, WorldPublishedStartLocationEvidence evidence) { - if (!SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(stored.attestationSchemaVersion())) { + if (!isSelectorSchema(stored.attestationSchemaVersion())) { throw new IllegalStateException( "IDEMPOTENCY_CONFLICT: historical release is selector-ineligible"); } requireSelectorBinding(stored); + String requestedSchema = + switch (evidence.request().digestSchemaVersion()) { + case 3 -> SELECTOR_ATTESTATION_SCHEMA_VERSION; + case 4 -> CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION; + default -> + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: unsupported retained World selector schema"); + }; + if (!requestedSchema.equals(stored.attestationSchemaVersion())) { + throw new IllegalStateException("IDEMPOTENCY_CONFLICT: changed immutable selector schema"); + } if (stored.versionNumber() != version.versionNumber() || version.scriptOnly() || version.scriptPatchVersion() != null @@ -121,7 +146,7 @@ static void requireSupportedSchemaForRead(PublishedReleaseBundleDto bundle) { * Publication reconciliation only; does not widen launch or repair authorization/schema support. */ static void requireSupportedSchemaForPublicationRead(PublishedReleaseBundleDto bundle) { - if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + if (isSelectorSchema(bundle.attestationSchemaVersion())) { requireSelectorBinding(bundle); return; } @@ -141,7 +166,7 @@ static void requireSupportedSchemaForLaunch(PublishedReleaseBundleDto bundle) { * Descriptor resolution only; descriptor/v1 remains separate from the complete release carrier. */ static void requireSupportedSchemaForLaunchDescriptor(PublishedReleaseBundleDto bundle) { - if (SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(bundle.attestationSchemaVersion())) { + if (isSelectorSchema(bundle.attestationSchemaVersion())) { requireSelectorBinding(bundle); return; } @@ -168,4 +193,9 @@ static void requireExactRepairMatch( + ": repair could not reproduce the attested manifest asset key set"); } } + + static boolean isSelectorSchema(String schemaVersion) { + return SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(schemaVersion) + || CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(schemaVersion); + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index cabb5d10ce..1453e04bc3 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -124,6 +124,10 @@ private PublishedReleaseBundleDto createBundle( } return stored; } + if (worldEvidence != null && worldEvidence.request().digestSchemaVersion() != 4) { + throw new IllegalStateException( + "New selected publication requires closure-qualified World digest schema 4"); + } var identitySource = versionRepository .findByTenantIdAndId(version.tenantId(), version.id()) @@ -148,7 +152,7 @@ private PublishedReleaseBundleDto createBundle( entity.setAttestationSchemaVersion( worldEvidence == null ? PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION - : PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION); + : PublishedReleaseBundleContract.CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION); entity.setWorldPublishedStartLocationEvidenceJson( worldEvidence == null ? null @@ -228,8 +232,7 @@ private PublishedReleaseBundleDto toDto(PublishedReleaseBundle entity) { entity .getWorldPublishedStartLocationEvidenceJson() .getBytes(StandardCharsets.UTF_8))); - if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( - dto.attestationSchemaVersion())) { + if (PublishedReleaseBundleContract.isSelectorSchema(dto.attestationSchemaVersion())) { PublishedReleaseBundleContract.requireSelectorBinding(dto); } return dto; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index 4d9a0d1143..3daaa9bb80 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -546,7 +546,7 @@ private void assertCommittedBundleMayMarkSuccess( } VersionDto versionDto = versionMapper.toDto(readback.version()); PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(readback.bundle()); - if (PublishedReleaseBundleContract.SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + if (PublishedReleaseBundleContract.isSelectorSchema( readback.bundle().attestationSchemaVersion())) { publishGateService.assertSelectedGatePassed( versionDto, readback.bundle().participantDigests()); @@ -818,7 +818,7 @@ private PublicationReadback readPublication( return PublicationReadback.partial(); } try { - PublishedReleaseBundleContract.requireSupportedSchemaForRead(bundle); + PublishedReleaseBundleContract.requireSupportedSchemaForPublicationRead(bundle); requireExactBundleEvidence(request, attempt, version.get(), bundle); requireExactArtifactEvidence(request, attempt, bundle, artifact); } catch (RuntimeException ex) { diff --git a/services/game-design-service/src/main/resources/db/migration/V69__closure_qualified_selected_publication_attestation.sql b/services/game-design-service/src/main/resources/db/migration/V69__closure_qualified_selected_publication_attestation.sql new file mode 100644 index 0000000000..d1cae029a1 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V69__closure_qualified_selected_publication_attestation.sql @@ -0,0 +1,269 @@ +-- Add closure-qualified selected releases without reclassifying or rewriting retained v1/v2 rows. +-- New selected releases bind World digest schema 4; exact historical v2 evidence still parses. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION enforce_published_world_start_location_evidence() RETURNS trigger AS $$ +DECLARE + evidence JSONB; + selection JSONB; + applied JSONB; + receipt JSONB; + participants JSONB; + item JSONB; + owner_key TEXT; + required_schema INTEGER; + required_world_schema INTEGER; + field_name TEXT; + account_bytes BYTEA; + operation_bytes BYTEA; + draft JSONB; + affected JSONB; +BEGIN + IF NEW.attestation_schema_version NOT IN ('v2', 'v3') THEN + IF NEW.world_published_start_location_evidence_json IS NOT NULL THEN + RAISE EXCEPTION 'historical release schemas cannot carry a World selector' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + required_world_schema := CASE NEW.attestation_schema_version WHEN 'v2' THEN 3 ELSE 4 END; + + IF NEW.world_published_start_location_evidence_json IS NULL + OR NEW.script_only OR NEW.script_patch_version IS NOT NULL + OR NEW.canonical_tenant_id IS NULL OR NEW.canonical_version_id IS NULL + OR NEW.manifest_schema_version IS NULL OR NEW.artifact_digests_json IS NULL THEN + RAISE EXCEPTION 'selected release requires complete full-Version selector evidence' + USING ERRCODE = 'check_violation'; + END IF; + evidence := NEW.world_published_start_location_evidence_json::JSONB; + selection := evidence->'request'; + FOR field_name IN SELECT unnest(ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'publishWorkflowId','appliedCommitId','contentDigest']) + LOOP + IF jsonb_typeof(selection->field_name) IS DISTINCT FROM 'string' + OR coalesce(selection->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected release has missing selection text binding' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + IF jsonb_typeof(evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR NOT evidence ?& ARRAY['schema','request','selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64'] + OR evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR jsonb_typeof(selection) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selection)) <> 13 + OR NOT selection ?& ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'versionStateEpoch','publishWorkflowId','appliedCommitId','contentDigest', + 'digestSchemaVersion','worldAffectedTuples'] + OR selection->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR selection->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR selection->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR selection->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR selection->>'intakeRequestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'intakeRequestId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'publicationFence' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'publicationFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'appliedCommitId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'appliedCommitId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR coalesce(selection->>'publicationRequestId','') = '' + OR selection->>'requestDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'versionStateEpoch' !~ '^[1-9][0-9]*$' + OR jsonb_typeof(selection->'versionStateEpoch') IS DISTINCT FROM 'string' + OR length(selection->>'versionStateEpoch') > 19 + OR (length(selection->>'versionStateEpoch') = 19 + AND selection->>'versionStateEpoch' > '9223372036854775807') + OR jsonb_typeof(selection->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR selection->>'digestSchemaVersion' IS DISTINCT FROM required_world_schema::TEXT + OR jsonb_typeof(selection->'worldAffectedTuples') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'selected World selection has missing, unsupported or mismatched bindings' + USING ERRCODE = 'check_violation'; + END IF; + IF jsonb_array_length(selection->'worldAffectedTuples') = 0 THEN + RAISE EXCEPTION 'selected release requires the complete World affected set' USING ERRCODE = 'check_violation'; + END IF; + -- Binary Account and APPLIED bytes remain intact; Java independently checks their full relation. + IF jsonb_typeof(evidence->'originalAccountBindingBytesBase64') IS DISTINCT FROM 'string' + OR octet_length(decode(evidence->>'originalAccountBindingBytesBase64','base64')) = 0 + OR jsonb_typeof(evidence->'appliedResultBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(evidence->'selectorReceiptBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'selected release requires complete original owner bytes' + USING ERRCODE = 'check_violation'; + END IF; + applied := convert_from(decode(evidence->>'appliedResultBytesBase64','base64'),'UTF8')::JSONB; + receipt := convert_from(decode(evidence->>'selectorReceiptBytesBase64','base64'),'UTF8')::JSONB; + FOR field_name IN SELECT unnest(ARRAY['selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64']) + LOOP + IF replace(encode(decode(evidence->>field_name,'base64'),'base64'), E'\n','') + IS DISTINCT FROM evidence->>field_name THEN + RAISE EXCEPTION 'selected release owner bytes are not canonical base64' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest']) + LOOP + IF jsonb_typeof(applied->field_name) IS DISTINCT FROM 'string' + OR coalesce(applied->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected APPLIED result has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','graphDigest','receiptDigest']) + LOOP + IF jsonb_typeof(receipt->field_name) IS DISTINCT FROM 'string' + OR coalesce(receipt->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected selector receipt has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + account_bytes := decode(evidence->>'originalAccountBindingBytesBase64','base64'); + operation_bytes := decode(applied->>'operationBytesBase64','base64'); + draft := convert_from(published_world_selector_frame(account_bytes, 11),'UTF8')::JSONB; + SELECT coalesce(jsonb_agg(unit ORDER BY unit->>'owner', unit->>'aggregateType', + unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId', unit->>'expectedEpoch'),'[]'::JSONB) + INTO affected FROM jsonb_array_elements(draft->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF applied->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR applied->>'status' IS DISTINCT FROM 'APPLIED' + OR applied->>'startLocationReceiptBase64' IS DISTINCT FROM evidence->>'selectorReceiptBytesBase64' + OR receipt->>'schema' IS DISTINCT FROM 'world-draft-start-location-receipt/v1' + OR receipt->>'targetNamespace' IS DISTINCT FROM selection->>'targetNamespace' + OR receipt->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR receipt->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR receipt->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR receipt->>'receiptDigest' IS DISTINCT FROM applied->>'startLocationReceiptDigest' + OR jsonb_typeof(applied) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(applied)) <> 8 + OR NOT applied ?& ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest','appliedEpochs'] + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 11 + OR NOT receipt ?& ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','startLocation','graphDigest','receiptDigest'] + OR jsonb_typeof(receipt->'startLocation') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt->'startLocation')) <> 3 + OR NOT (receipt->'startLocation') ?& ARRAY['tenantId','versionId','roomTemplateId'] + OR selection->'worldAffectedTuples' IS DISTINCT FROM affected + OR draft->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR draft->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR draft->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR draft->'target'->>'gameDesignVersionRowId' IS DISTINCT FROM NEW.version_id::TEXT + OR draft->'target'->>'gameDesignVersionTenantKey' IS DISTINCT FROM NEW.tenant_id + OR published_world_selector_frame(account_bytes, 11) IS DISTINCT FROM published_world_selector_frame(account_bytes, 12) + OR published_world_selector_frame(operation_bytes, 7) IS DISTINCT FROM published_world_selector_frame(account_bytes, 11) + OR convert_from(published_world_selector_frame(account_bytes, 13),'UTF8') IS DISTINCT FROM receipt->>'bindingDigest' + OR receipt->>'accountBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes),'hex') + OR applied->>'graphDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(applied->>'graphBytesBase64','base64')),'hex') + OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1' + OR convert_from(published_world_selector_frame(account_bytes, 1),'UTF8') IS DISTINCT FROM receipt->>'operationId' + OR convert_from(published_world_selector_frame(account_bytes, 2),'UTF8') IS DISTINCT FROM receipt->>'requestId' + OR convert_from(published_world_selector_frame(account_bytes, 3),'UTF8') IS DISTINCT FROM selection->>'appliedCommitId' + OR convert_from(published_world_selector_frame(account_bytes, 4),'UTF8') IS DISTINCT FROM receipt->>'authorizationFenceId' + OR convert_from(published_world_selector_frame(account_bytes, 6),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(account_bytes, 7),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 0),'UTF8') IS DISTINCT FROM 'world-draft-terminal-operation/v1' + OR published_world_selector_frame(operation_bytes, 20) IS DISTINCT FROM account_bytes + OR convert_from(published_world_selector_frame(operation_bytes, 13),'UTF8') IS DISTINCT FROM selection->>'intakeRequestId' + OR convert_from(published_world_selector_frame(operation_bytes, 8),'UTF8') IS DISTINCT FROM selection->>'targetNamespace' + OR convert_from(published_world_selector_frame(operation_bytes, 9),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 10),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->'startLocation'->>'roomTemplateId' IS NULL THEN + RAISE EXCEPTION 'selected selector differs from original APPLIED receipt' + USING ERRCODE = 'check_violation'; + END IF; + participants := NEW.participant_digests_json::JSONB; + IF jsonb_typeof(participants) IS DISTINCT FROM 'array' OR jsonb_array_length(participants) <> 5 THEN + RAISE EXCEPTION 'selected release requires all five participant owners' USING ERRCODE = 'check_violation'; + END IF; + FOR owner_key, required_schema IN SELECT * FROM (VALUES + ('WORLD_MANAGEMENT',required_world_schema),('ENTITY_MANAGEMENT',2),('GAME_LOGIC',1), + ('AUTOMATION_SCRIPTING',5),('GAME_DESIGN_CONTROL_PLANE',2)) owners(owner_key, required_schema) + LOOP + IF (SELECT count(*) FROM jsonb_array_elements(participants) p + WHERE p->>'participantKey' = owner_key) <> 1 THEN + RAISE EXCEPTION 'selected release has missing or duplicate participant owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT p INTO item FROM jsonb_array_elements(participants) p WHERE p->>'participantKey' = owner_key; + IF item->>'scopeValue' IS DISTINCT FROM NEW.version_id::TEXT + OR item->>'baseVersionId' IS NOT NULL + OR item->>'appliedCommitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR item->>'digestSchemaVersion' IS DISTINCT FROM required_schema::TEXT + OR coalesce(item->>'contentDigest','') !~ '^[0-9a-f]{64}$' + OR coalesce(item->>'errorCode','') <> '' + OR (owner_key = 'WORLD_MANAGEMENT' AND item->>'contentDigest' IS DISTINCT FROM selection->>'contentDigest') + OR (owner_key = 'GAME_LOGIC' AND coalesce(item->>'abilitySchemaDigest','') !~ '^sha256:[0-9a-f]{64}$') THEN + RAISE EXCEPTION 'selected participant differs from commit/digest/schema' + USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION guard_selected_publication_release() RETURNS trigger AS $$ +DECLARE attempt publish_attempt%ROWTYPE; operation game_design_publication_operation%ROWTYPE; +BEGIN + IF NEW.script_only THEN RETURN NEW; END IF; + -- Old unselected history keeps its original read semantics; no operation is backfilled. + IF NEW.attestation_schema_version NOT IN ('v2', 'v3') AND NOT EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = NEW.tenant_id AND game_design_version_row_id = NEW.version_id) THEN + RETURN NEW; + END IF; + PERFORM 1 FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM publish_attempt WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + PERFORM 1 FROM version WHERE id = NEW.version_id AND tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF attempt.status <> 'PENDING' OR operation.outcome <> 'PENDING' + OR operation.tenant_id <> NEW.tenant_id OR operation.version_id <> NEW.version_id + OR attempt.request_digest IS DISTINCT FROM operation.selection_digest + OR NEW.attestation_schema_version NOT IN ('v2', 'v3') + OR convert_to(NEW.world_published_start_location_evidence_json, 'UTF8') + IS DISTINCT FROM published_world_selector_frame(operation.request_bytes, 2) THEN + RAISE EXCEPTION 'selected publication is absent, sealed, or changed' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION publication_release_content(release published_release_bundle) RETURNS BYTEA AS $$ +DECLARE result BYTEA; entry BYTEA; item JSONB; +BEGIN + IF release.script_only OR release.script_patch_version IS NOT NULL + OR release.attestation_schema_version NOT IN ('v2', 'v3') THEN + RAISE EXCEPTION 'terminal publication requires complete full-version selected content' USING ERRCODE = 'check_violation'; + END IF; + result := publication_content_text('game-design-published-release-bundle/v1') + || publication_content_text(release.canonical_tenant_id::TEXT) + || publication_content_text(release.canonical_version_id::TEXT) + || publication_content_text(release.published_release_bundle_ref) + || publication_content_text(release.version_number::TEXT) + || publication_content_text(release.attestation_schema_version) + || publication_content_text(release.publish_workflow_id) + || publication_content_text(release.manifest_hash) + || publication_content_text(release.manifest_schema_version::TEXT) + || publication_content_text(jsonb_array_length(release.artifact_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.artifact_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'usageKey') || publication_content_text(item->>'artifactKind') + || publication_content_text(item->>'immutableObjectKey') || publication_content_text(item->>'contentDigest') + || publication_content_text(item->>'contentType') || publication_content_text(item->>'artifactSchemaVersion'); + result := result || publication_content_frame(entry); + END LOOP; + result := result || publication_content_strings(release.required_manifest_asset_keys_json::JSONB) + || publication_content_text(jsonb_array_length(release.participant_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.participant_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'participantKey') || publication_content_text(item->>'scopeValue') + || publication_content_optional(item->>'baseVersionId') || publication_content_text(item->>'appliedCommitId') + || publication_content_text(item->>'contentDigest') || publication_content_text(item->>'digestSchemaVersion') + || publication_content_optional(item->>'abilitySchemaDigest') || publication_content_optional(item->>'errorCode') + || publication_content_optional(item->>'errorMessage'); + result := result || publication_content_frame(entry); + END LOOP; + RETURN result || publication_content_strings(release.command_definitions_json::JSONB) + || publication_content_text(release.generation_config_revision) + || publication_content_text(release.world_published_start_location_evidence_json) + || publication_content_text('false') || publication_content_optional(NULL); +END; +$$ LANGUAGE plpgsql STABLE STRICT; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index cf114080f1..bf26a6fce1 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -229,6 +229,13 @@ public static GameDesignPublicationOperation retainSourceBacked( return retain(dsl, target, draftEpoch, notes, true); } + /** Isolated upstream inputs use the closure-qualified selector profile for selected release. */ + public static GameDesignPublicationOperation retainSourceBackedClosureQualified( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + return retain(dsl, target, draftEpoch, notes, true, true); + } + /** Creates actual synchronized source rows and selection, without any publication operation. */ public static AuthoredDraftPublishSelectionRepository.SelectionSnapshot selectSourceBackedDraft( DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) @@ -244,7 +251,15 @@ public static AuthoredDraftPublishSelectionRepository.SelectionSnapshot selectSo public static SourceBackedSelection selectSourceBackedDraftWithWorld( DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) throws Exception { - PreparedSelection prepared = prepareSelection(dsl, target, draftEpoch, notes, true); + PreparedSelection prepared = prepareSelection(dsl, target, draftEpoch, notes, true, false); + return new SourceBackedSelection(prepared.selection(), prepared.world()); + } + + /** Isolated closure-qualified World selector seed for the new selected-release profile. */ + public static SourceBackedSelection selectSourceBackedDraftWithClosureQualifiedWorld( + DSLContext dsl, DraftCommitBinding.TargetProof target, long draftEpoch, String notes) + throws Exception { + PreparedSelection prepared = prepareSelection(dsl, target, draftEpoch, notes, true, true); return new SourceBackedSelection(prepared.selection(), prepared.world()); } @@ -255,7 +270,19 @@ private static GameDesignPublicationOperation retain( String notes, boolean captureSources) throws Exception { - PreparedSelection prepared = prepareSelection(dsl, target, draftEpoch, notes, captureSources); + return retain(dsl, target, draftEpoch, notes, captureSources, false); + } + + private static GameDesignPublicationOperation retain( + DSLContext dsl, + DraftCommitBinding.TargetProof target, + long draftEpoch, + String notes, + boolean captureSources, + boolean closureQualified) + throws Exception { + PreparedSelection prepared = + prepareSelection(dsl, target, draftEpoch, notes, captureSources, closureQualified); var selection = prepared.selection().selection(); var intent = selection.intent(); var operation = @@ -299,9 +326,13 @@ private static PreparedSelection prepareSelection( DraftCommitBinding.TargetProof target, long draftEpoch, String notes, - boolean captureSources) + boolean captureSources, + boolean closureQualified) throws Exception { - var seed = IsolatedPublicationOperationFixtures.fresh(target); + var seed = + closureQualified + ? IsolatedPublicationOperationFixtures.freshClosureQualifiedSelection(target) + : IsolatedPublicationOperationFixtures.fresh(target); var draft = seed.account().input().selection().selectedCommit(); var coordinator = new DraftCommitCoordinatorRepository(dsl); // The original Draft Account/World result is stipulated upstream fixture evidence, not a new diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java index 3e416710bc..c96e8de619 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -28,7 +28,21 @@ private IsolatedPublicationOperationFixtures() {} */ public static GameDesignPublicationOperation fresh(DraftCommitBinding.TargetProof target) throws Exception { - var seed = PublishedWorldSelectorFixtures.evidence(target); + return fresh(target, false); + } + + /** Test-only closure-qualified fixture; upstream Account/APPLIED evidence remains stipulated. */ + public static GameDesignPublicationOperation freshClosureQualifiedSelection( + DraftCommitBinding.TargetProof target) throws Exception { + return fresh(target, true); + } + + private static GameDesignPublicationOperation fresh( + DraftCommitBinding.TargetProof target, boolean closureQualified) throws Exception { + var seed = + closureQualified + ? PublishedWorldSelectorFixtures.closureEvidence(target) + : PublishedWorldSelectorFixtures.evidence(target); var originalDraftAccount = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); var draft = @@ -152,7 +166,7 @@ public static GameDesignPublicationOperation forSelection( intent.publishRequestId()), draft.commitId().toString(), seed.request().contentDigest(), - 3, + seed.request().digestSchemaVersion(), seed.request().worldAffectedTuples()), seed.selectorReceiptBytes(), seed.originalAccountBindingBytes(), diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java index a0a7d5d873..ea2710977f 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -31,7 +31,13 @@ private PublishedWorldSelectorFixtures(TargetProof target) { } public static WorldPublishedStartLocationEvidence evidence(TargetProof target) throws Exception { - return new PublishedWorldSelectorFixtures(target).build(); + return new PublishedWorldSelectorFixtures(target).build(3); + } + + /** Test-only closure-qualified evidence; its Account/APPLIED bytes remain stipulated fixtures. */ + public static WorldPublishedStartLocationEvidence closureEvidence(TargetProof target) + throws Exception { + return new PublishedWorldSelectorFixtures(target).build(4); } public static List @@ -57,15 +63,20 @@ public static WorldPublishedStartLocationEvidence evidence(TargetProof target) t net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence .supportedParticipantDigestSchema( owner, - net.firedevops.firemud.common.gamedesign - .AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + evidence.request().digestSchemaVersion() == 4 + ? net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence + .CLOSURE_SELECTOR_SCHEMA_VERSION + : net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence + .SELECTOR_SCHEMA_VERSION), "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, null, null)) .toList(); } - private WorldPublishedStartLocationEvidence build() throws Exception { + private WorldPublishedStartLocationEvidence build(int digestSchemaVersion) throws Exception { var draft = freshGraphBinding(); var terminal = WorldDraftTerminalReadEvidence.Request.create("test", accountBinding(draft)); var result = committedReadback(terminal, true); @@ -95,7 +106,7 @@ private WorldPublishedStartLocationEvidence build() throws Exception { "publish-workflow", draft.commitId().toString(), "b".repeat(64), - 3, + digestSchemaVersion, tuples); return new WorldPublishedStartLocationEvidence( request, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java index b0595f299f..5575c90193 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -144,7 +144,9 @@ void authoredAutomationInventoryHasExactRetryInheritanceAndFrozenOriginalProvena .containsExactly(first.ownerSourceInventoryDeclarations().getFirst()); assertThat(capture.ownerSourceInventoryDeclarations().getFirst().sourceBinding()) .isEqualTo(declaration); - assertThat(capture.binding()).isEqualTo(actualTemplate); + assertThat(capture.binding()) + .isEqualTo(operation.account().input().selection().selectedCommit()); + assertThat(capture.entries().getFirst().sourceBinding()).isEqualTo(actualTemplate); } @Test diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 7153299c3e..48ba4dc0be 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -62,7 +62,9 @@ import net.firedevops.firemud.common.authoring.WorldAuthoredVersionIdentityEvidence; import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyClient; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; @@ -218,6 +220,9 @@ import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceClosureDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -526,6 +531,35 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex sourceAsset.getFileName(), worldSource.worldSlug(), worldSource.worldDisplayName()); + var originalWorldDeclarations = + selectedCommit.revisions().stream() + .filter(revision -> revision.owner() == Owner.WORLD_MANAGEMENT) + .map(GenuineSelectedPublicationExportPostgresIntegrationTest::worldMutation) + .filter(WorldDesignMutationRevision::hasFreshGraphDeclaration) + .map(WorldDesignMutationRevision::getFreshGraphDeclaration) + .toList(); + assertThat(originalWorldDeclarations) + .singleElement() + .satisfies( + declaration -> { + assertThat(declaration.hasInboundSourceClosure()).isTrue(); + assertThat(declaration.getInboundSourceClosure()) + .isEqualTo(authoredEmptyInboundSourceClosure()); + }); + var templateConfigUnits = + selectedCommit.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE).stream() + .filter(unit -> TemplateConfigSource.SCOPE.equals(unit.aggregateType())) + .toList(); + assertThat(templateConfigUnits) + .singleElement() + .satisfies( + unit -> { + assertThat(unit.aggregateId()) + .isEqualTo(gd.target().canonicalVersionId().toString()); + assertThat(unit.scopeType()).isEqualTo(TemplateConfigSource.SCOPE); + assertThat(unit.scopeId()).isEqualTo(TemplateConfigSource.SCOPE_ID); + assertThat(unit.expectedEpoch()).isEqualTo("0"); + }); var originalOrder = account.prepareOriginalDraftOrder(selectedCommit, NAMESPACE); var original = originalOrder.original(); var accountAccess = account.preparedOriginalCreator(); @@ -730,7 +764,29 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new TemplateConfigSourceRepository(gd.dsl()) .readSnapshot(gd.target(), selectedCommit.commitId()) .orElseThrow(); + assertThat(templateSource.binding()).isEqualTo(selectedCommit); + assertThat(templateSource.canonicalJson()) + .contains("\"schema\":\"game-design-template-config-source-snapshot/v2\""); assertThat(templateSource.entries()).hasSize(1); + var selectedTemplateMutations = TemplateConfigSource.mutations(selectedCommit); + var authoredAutomationInventory = automationSourceInventory(); + var authoredEntityInventory = entitySourceInventory(); + var automationInventoryMutation = + selectedTemplateMutations.stream() + .filter(mutation -> mutation.declaredOwner() == Owner.AUTOMATION_SCRIPTING) + .findFirst() + .orElseThrow(); + var entityInventoryMutation = + selectedTemplateMutations.stream() + .filter(mutation -> mutation.declaredOwner() == Owner.ENTITY_MANAGEMENT) + .findFirst() + .orElseThrow(); + assertThat(automationInventoryMutation.inventory()).isEqualTo(authoredAutomationInventory); + assertThat(entityInventoryMutation.entityInventory()).isEqualTo(authoredEntityInventory); + assertThat(templateSource.ownerSourceInventoryDeclarations()) + .containsExactly( + automationInventoryMutation.ownerInventoryDeclaration(), + entityInventoryMutation.ownerInventoryDeclaration()); long templateId = Long.parseLong(templateSource.entries().getFirst().templateId()); var enforcedPhase = new TemplateReferenceRepository(gd.dsl()) @@ -841,7 +897,7 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex selection.digest().substring("sha256:".length()), accountPublicationOrder); var actualFreeze = selectedPublicationFreezeClient.begin(exactFreezeRequest); - assertThat(actualFreeze.acknowledgement().publicationFence().toString()) + assertThat(actualFreeze.acknowledgement().publicationFence()) .isEqualTo(publicationReservation.operation().world().request().publicationFence()); assertThat(actualFreeze.acknowledgement().appliedCommitId()) .isEqualTo(selectedCommit.commitId().toString()); @@ -1155,9 +1211,12 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var release = releaseService.getPublishedReleaseBundle( gd.target().gameDesignVersionTenantKey(), gd.target().gameDesignVersionRowId()); - assertThat(release.attestationSchemaVersion()).isEqualTo("v2"); + assertThat(release.attestationSchemaVersion()).isEqualTo("v3"); assertThat(release.worldPublishedStartLocationEvidence()) .isEqualTo(publicationReservation.operation().world()); + assertThat(release.worldPublishedStartLocationEvidence().request().digestSchemaVersion()) + .isEqualTo(4); + assertThat(release.participantDigests().getFirst().digestSchemaVersion()).isEqualTo(4); var retainedGameLogicParticipant = release.participantDigests().stream() .filter(digest -> "GAME_LOGIC".equals(digest.participantKey())) @@ -1295,6 +1354,7 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex expectedAuthoredWorldBinding.resultDigest()); assertThat(completeBinding.descriptor()).isEqualTo(expectedAuthoredWorldBinding); completeBinding.releaseAttestation().requireValid(completeBinding.descriptor()); + assertThat(completeBinding.releaseAttestation().schemaVersion()).isEqualTo(3); assertThat(completeBinding.releaseAttestation().descriptorResultDigest()) .isEqualTo(expectedAuthoredWorldBinding.resultDigest()); assertThat(completeBinding.releaseAttestation().worldStartLocationEvidence()) @@ -2033,6 +2093,7 @@ private static DraftCommitBinding binding( .setTenantId(target.canonicalTenantId().toString()) .setVersionId(target.canonicalVersionId().toString()) .addAllFamilyCounts(familyCounts) + .setInboundSourceClosure(authoredEmptyInboundSourceClosure()) .setStartLocation( net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef.newBuilder() .setTenantId(target.canonicalTenantId().toString()) @@ -2143,6 +2204,22 @@ private static DraftCommitBinding binding( TemplateConfigSource.SCOPE, TemplateConfigSource.SCOPE_ID, "0")); + // These are authored inventory declarations only, not Entity/Automation owner receipts. + var automationInventory = automationSourceInventory(); + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.ownerInventoryPayload( + Owner.AUTOMATION_SCRIPTING, automationInventory))); + var entityInventory = entitySourceInventory(); + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSource.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, entityInventory))); for (var worldMutation : mutations) { revisions.add( new RevisionPayload( @@ -2207,6 +2284,74 @@ private static String realmPolicyRevisionPayload( StandardCharsets.UTF_8); } + private static AutomationAuthoredSourceInventoryDeclaration automationSourceInventory() { + return AutomationAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"automation-authored-source-inventory/v1\"," + + "\"families\":{\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"); + } + + private static EntityAuthoredSourceInventoryDeclaration entitySourceInventory() { + return EntityAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"); + } + + private static WorldInboundSourceClosureDeclaration authoredEmptyInboundSourceClosure() { + return WorldInboundSourceClosureDeclaration.newBuilder() + .setSchemaVersion(1) + .addFamilyCounts( + inboundSourceFamilyCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT)) + .addFamilyCounts( + inboundSourceFamilyCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT)) + .addFamilyCounts( + inboundSourceFamilyCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION)) + .addFamilyCounts( + inboundSourceFamilyCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING)) + .addFamilyCounts( + inboundSourceFamilyCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK)) + .addFamilyCounts( + inboundSourceFamilyCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE)) + .addFamilyCounts( + inboundSourceFamilyCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING)) + .build(); + } + + private static WorldInboundSourceFamilyCount inboundSourceFamilyCount( + WorldInboundSourceFamily family) { + return WorldInboundSourceFamilyCount.newBuilder().setFamily(family).setCount(0).build(); + } + + private static WorldDesignMutationRevision worldMutation(RevisionPayload revision) { + try { + var mutation = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(revision.payload(), mutation); + return mutation.build(); + } catch (com.google.protobuf.InvalidProtocolBufferException exception) { + throw new AssertionError( + "Selected World source revision is not valid protobuf JSON", exception); + } + } + private static WorldDesignMutationRevision.Builder mutation( UUID commit, UUID aggregate, UUID region, WorldDesignAggregateType type) { return WorldDesignMutationRevision.newBuilder() diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index cfef436166..0a9a470ec0 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -486,6 +486,11 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth candidate.setNotes("successful transaction proof"); candidate = versionRepository.save(candidate); var operation = reserveSelectedDraft(candidate, "successful transaction proof"); + assertThat(operation.world().request().digestSchemaVersion()).isEqualTo(4); + assertThat(operation.inventory().publicEvidence().schema()) + .isEqualTo("world-selected-publication-artifact-inventory/v2"); + assertThat(operation.inventory().publicEvidence().sourceModel().graphSchemaVersion()) + .isEqualTo(3); var terminalPki = new SelectionReadTestPki(Files.createDirectories(temporary.resolve("pki"))); assertTerminalOwnerReadOverMtls(operation, null, terminalPki); assertThat(candidate.getTenantId()).isEqualTo(tenantId); @@ -611,7 +616,7 @@ void reconciledFullVersionPublicationCommitsAttemptVersionAndReleaseBundleTogeth * export candidate remain stipulated test fixtures; this is not whole-chain transport proof. */ @Test - void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Release( + void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV3Release( @TempDir Path temporary) throws Exception { String tenantId = "9010"; FreshTenantCreationEvidence creation = @@ -658,8 +663,9 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele inOwnerTransaction( () -> { try { - return IsolatedPublicationOwnerSetup.selectSourceBackedDraftWithWorld( - dsl, target, candidateEpoch, "selected command composition proof"); + return IsolatedPublicationOwnerSetup + .selectSourceBackedDraftWithClosureQualifiedWorld( + dsl, target, candidateEpoch, "selected command composition proof"); } catch (Exception failure) { throw new IllegalStateException(failure); } @@ -671,6 +677,9 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele AuthoredDraftPublishSelectionBinding.fromStored( selection.canonicalJson(), selection.digest()), prepared.world()); + assertThat(operation.world().request().digestSchemaVersion()).isEqualTo(4); + assertThat(operation.inventory().publicEvidence().schema()) + .isEqualTo("world-selected-publication-artifact-inventory/v2"); var stipulatedWorldSourceRead = IsolatedPublicationOwnerSetup.syntheticWorldSourceRead(operation); retainStipulatedWorldSourceAndDelivery(stipulatedWorldSourceRead); @@ -707,6 +716,7 @@ void selectedDraftCompositionUsesAuthenticatedOwnerReadsAndReconcilesExactV2Rele .isEqualTo(selection.intent().selectedCommitId().toString()); assertThat(projectedWorldRequest.contentDigest()) .isEqualTo(prepared.world().request().contentDigest()); + assertThat(projectedWorldRequest.digestSchemaVersion()).isEqualTo(4); assertThat(projectedWorldRequest.worldAffectedTuples()) .isEqualTo(prepared.world().request().worldAffectedTuples()); @@ -906,7 +916,7 @@ dsl, new DraftCommitCoordinatorRepository(dsl)) assertThat(attempt.getStatus()).isEqualTo(PublishAttemptStatus.SUCCEEDED); assertThat(attempt.getVersionId()).isEqualTo(candidate.getId()); assertThat(storedVersion.getVersionState()).isEqualTo(VersionLifecycleState.PUBLISHED); - assertThat(bundle.getAttestationSchemaVersion()).isEqualTo("v2"); + assertThat(bundle.getAttestationSchemaVersion()).isEqualTo("v3"); assertThat(bundle.getWorldPublishedStartLocationEvidenceJson()) .isEqualTo(publishedWorldEvidenceJson); assertThat(bundle.getPublishWorkflowId()).isEqualTo(workflowId); @@ -2718,9 +2728,10 @@ private static boolean sameCanonicalPreimage( return inOwnerTransaction( () -> { try { - // Account/World values produced by this helper are isolated external fixtures; the GD - // selection, command/policy source, attempt and publication reservation are real. - return IsolatedPublicationOwnerSetup.retainSourceBacked( + // Account, APPLIED, and closure-v2 inventory values remain isolated external + // fixtures; only the GD selection, command/policy source, attempt and publication + // reservation are real. This is not World owner-production evidence. + return IsolatedPublicationOwnerSetup.retainSourceBackedClosureQualified( dsl, target, version.getVersionStateEpoch(), notes); } catch (Exception failure) { throw new IllegalStateException(failure); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java index 84bdbf788a..e5653a1757 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -230,6 +230,59 @@ void returnsImmutableFullBindingUsingTheDescriptorEpochAfterCurrentVersionStateA verifyReadOnlyCallsOnly(); } + @Test + void closureQualifiedSelectorV3AssemblesWorld4ParticipantFromImmutableBundle() throws Exception { + var selector = + PublishedWorldSelectorFixtures.closureEvidence( + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_ID, + PRIVATE_TENANT_KEY, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); + var selected = + new PublishedReleaseBundleDto( + bundle.id(), + bundle.tenantId(), + bundle.versionId(), + bundle.versionNumber(), + "v3", + selector.request().publishWorkflowId(), + bundle.manifestHash(), + bundle.requiredManifestAssetKeys(), + PublishedWorldSelectorFixtures.participants(VERSION_ID, selector), + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.scriptOnly(), + bundle.scriptPatchVersion(), + bundle.publishedAt(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.publishedReleaseBundleRef(), + bundle.manifestSchemaVersion(), + bundle.artifactDigests(), + selector); + givenBundle(selected); + + var result = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + + assertEquals(3, result.releaseAttestation().schemaVersion()); + assertEquals(selector, result.releaseAttestation().worldStartLocationEvidence()); + assertEquals( + 4, result.releaseAttestation().participantDigests().getFirst().digestSchemaVersion()); + result.releaseAttestation().requireValid(descriptor); + verifyReadOnlyCallsOnly(); + } + @Test void rejectsMissingOrSubstitutedSourceEvidence() { when(authoredWorldSourceRepository.readVersionStateSnapshot( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index f42394d139..c68aeaa92a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -7,7 +7,9 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.gamedesign.dto.AppliedWorldDesignMutationDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; @@ -212,6 +214,63 @@ void getPublishedReleaseBundleReturnsCanonicalAttestation() { assertEquals("TEMPORAL_DISABLED", ref.get().getBundle().getWorkflowStatus()); } + @Test + void getPublishedReleaseBundleTransportsClosureQualifiedWorld4Participant() throws Exception { + var target = + new TargetProof( + UUID.fromString("67d7b75b-42d1-4ac6-9572-684c5e633cda"), + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"), + 7L, + "tenant-1", + 42L, + "tenant-1", + "NEW_GAME_ROW"); + var evidence = + net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures + .closureEvidence(target); + var participants = + net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures.participants( + 7L, evidence); + Mockito.when(versionService.getPublishedReleaseBundle("tenant-1", 7L)) + .thenReturn( + new PublishedReleaseBundleDto( + 11L, + "tenant-1", + 7L, + 8, + "v3", + "publish-workflow", + "sha256:" + "a".repeat(64), + List.of(), + participants, + List.of("{\"commandId\":\"block\",\"schemaVersion\":1}"), + "genrev-1", + false, + null, + LocalDateTime.parse("2026-04-14T12:00:00"), + target.canonicalTenantId(), + target.canonicalVersionId(), + "bundle-ref-v3", + 1, + List.of(), + evidence)); + + AtomicReference ref = new AtomicReference<>(); + try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { + service.getPublishedReleaseBundle( + GetPublishedReleaseBundleRequest.newBuilder() + .setTenantId("tenant-1") + .setVersionId(7L) + .build(), + observerFor(ref)); + } + + assertEquals("", ref.get().getError().getCode()); + assertEquals("v3", ref.get().getBundle().getAttestationSchemaVersion()); + assertEquals(5, ref.get().getBundle().getParticipantDigestsCount()); + assertEquals(4, ref.get().getBundle().getParticipantDigests(0).getDigestSchemaVersion()); + } + @Test void getPublishedScriptPatchVersionReturnsPublicationReadModel() { Mockito.when(versionService.getPublishedScriptPatchVersion("tenant-1", 7L, "patch-1")) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java index 05b407fa71..4d396e0b46 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java @@ -155,6 +155,32 @@ void selectedFullVersionGateUsesCanonicalBindingAndExactReceiptForOwnerReads() { .getDraftDesignDigestForVersion(any(PublicationDigestRequestBinding.class)); } + @Test + void closureQualifiedSelectedGateRequiresWorldDigestSchemaFour() { + VersionDto version = selectedVersion(); + PublicationDigestRequestBinding binding = selectedBinding(version); + SelectedDraftGameLogicReceipt receipt = + org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + when(selectedPublicationDigestReader.read("test", binding)) + .thenReturn( + new SelectedDraftPublicationDigestReadService.ReadResult( + binding, + binding.requestDigest(), + new DesignControlPlaneDigestDto( + binding.tenantId(), "7", "selected-commit", "c".repeat(64), 2), + new PublishParticipantDigestDto( + "WORLD_MANAGEMENT", "7", "selected-commit", "b".repeat(64), 4, null, null))); + + List digests = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + + assertEquals(4, digests.getFirst().digestSchemaVersion()); + assertEquals(2, digests.getLast().digestSchemaVersion()); + assertDoesNotThrow(() -> service.assertSelectedGatePassed(version, digests)); + } + @Test void selectedFullVersionGateKeepsMissingReceiptPendingAndNeverUsesLegacyRead() { VersionDto version = selectedVersion(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 9c7b8dccdf..770190f353 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -45,9 +45,9 @@ class PublishedReleaseBundleServiceImplTest { private PublishedReleaseBundleServiceImpl service; @Test - void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults() + void closureSelectorV3PersistsOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults() throws Exception { - var evidence = selectorEvidence(); + var evidence = closureSelectorEvidence(); var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); // ISOLATED source-repository response; this test covers service assembly only. when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) @@ -70,7 +70,7 @@ void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutRe "genrev-1", participants, evidence); - assertEquals("v2", first.attestationSchemaVersion()); + assertEquals("v3", first.attestationSchemaVersion()); assertThat(first.worldPublishedStartLocationEvidence().canonicalBytes()) .containsExactly(evidence.canonicalBytes()); assertThat(first.commandDefinitions()).containsExactly(validCommandDefinition()); @@ -113,9 +113,9 @@ void selectorV2PersistsActualOriginalBytesAndRetryReturnsStoredEvidenceWithoutRe } @Test - void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest() + void closureSelectorV3RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest() throws Exception { - var evidence = selectorEvidence(); + var evidence = closureSelectorEvidence(); var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); var obsolete = new java.util.ArrayList<>(participants); var gd = obsolete.getLast(); @@ -180,7 +180,7 @@ void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorl null, world.appliedCommitId(), "e".repeat(64), - 3, + world.digestSchemaVersion(), null, null, null)); @@ -198,8 +198,8 @@ void selectorV2RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorl } @Test - void selectorV2RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception { - var evidence = selectorEvidence(); + void closureSelectorV3RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception { + var evidence = closureSelectorEvidence(); when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenThrow(new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); @@ -218,6 +218,24 @@ void selectorV2RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception org.mockito.Mockito.verifyNoInteractions(revisionRepository); } + @Test + void newSelectedReleaseCannotBeCreatedFromRetainedWorldDigestSchema3() throws Exception { + var evidence = selectorEvidence(); + + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants(7L, evidence), + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("World digest schema 4"); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + } + @Test void historicalReleaseNeverGainsSelectorAndCorruptedStoredCarrierFailsReadback() throws Exception { @@ -262,6 +280,18 @@ private WorldPublishedStartLocationEvidence selectorEvidence() throws Exception "NEW_GAME_ROW")); } + private WorldPublishedStartLocationEvidence closureSelectorEvidence() throws Exception { + return PublishedWorldSelectorFixtures.closureEvidence( + new TargetProof( + sourceIdentity().getCanonicalTenantId(), + sourceIdentity().getCanonicalVersionId(), + 7L, + "tenant-1", + 42L, + "tenant-1", + "NEW_GAME_ROW")); + } + private VersionDto selectorVersion() { return new VersionDto( 7L, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/WorldDraftDesignDigestService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/WorldDraftDesignDigestService.java index 7dcdc129c5..70a55aebd7 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/WorldDraftDesignDigestService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/WorldDraftDesignDigestService.java @@ -1,8 +1,14 @@ package net.firedevops.firemud.worldmanagement.service; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.InboundSourceClosureDeclaration; + public interface WorldDraftDesignDigestService { WorldDraftDesignDigest getDraftDesignDigest(String tenantId, String versionId); + /** Selected-publication participant digest, bound to the exact retained source declaration. */ + WorldDraftDesignDigest getSelectedDraftDesignDigest( + String tenantId, String versionId, InboundSourceClosureDeclaration inboundSourceClosure); + record WorldDraftDesignDigest( String tenantId, String scopeValue, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java index 491f70ea1f..19f9498f7c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java @@ -19,6 +19,9 @@ import net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.WorldDraftDesignDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.InboundSourceClosureDeclaration; import org.springframework.stereotype.Service; import tools.jackson.databind.ObjectMapper; @@ -28,6 +31,7 @@ justification = "Spring-managed repositories and mapper are stored internally for digesting") public final class WorldDraftDesignDigestServiceImpl implements WorldDraftDesignDigestService { private static final int DIGEST_SCHEMA_VERSION = 3; + private static final int SELECTED_DIGEST_SCHEMA_VERSION = 4; private final RegionRepository regionRepository; private final ZoneRepository zoneRepository; @@ -58,109 +62,137 @@ public WorldDraftDesignDigestServiceImpl( @Override public WorldDraftDesignDigest getDraftDesignDigest(String tenantId, String versionId) { + return getDraftDesignDigest(tenantId, versionId, null); + } + + @Override + public WorldDraftDesignDigest getSelectedDraftDesignDigest( + String tenantId, String versionId, InboundSourceClosureDeclaration inboundSourceClosure) { + Objects.requireNonNull(inboundSourceClosure, "inboundSourceClosure"); + WorldDraftTopologyInputGraph.requireEmptyInboundSourceClosure(inboundSourceClosure); + return getDraftDesignDigest(tenantId, versionId, inboundSourceClosure); + } + + private WorldDraftDesignDigest getDraftDesignDigest( + String tenantId, String versionId, InboundSourceClosureDeclaration inboundSourceClosure) { if (versionId == null || versionId.isBlank()) { throw new IllegalArgumentException("version_id is required"); } long tenantKey = RequestIdValidation.requirePositiveLong(tenantId, "tenantId"); long versionKey = RequestIdValidation.requirePositiveLong(versionId, "versionId"); try { - String canonicalJson = - objectMapper.writeValueAsString( - tables( - "regions", - regionRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - region -> - Map.of( - "id", region.getId(), - "shardId", region.getShardId(), - "name", region.getName(), - "weather", value(region.getWeather()), - "generationSeed", region.getGenerationSeed(), - "generatorType", value(region.getGeneratorType()), - "generatorParams", value(region.getGeneratorParams()), - "spacingMultiplier", region.getSpacingMultiplier())) - .toList(), - "zones", - zoneRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - zone -> - Map.of( - "id", zone.getId(), - "regionId", zone.getRegion().getId(), - "name", zone.getName())) - .toList(), - "rooms", - roomRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - room -> - Map.of( - "id", room.getId(), - "zoneId", room.getZone().getId(), - "name", room.getName(), - "description", value(room.getDescription()), - "nameLocalizedVariantsJson", - value(room.getNameLocalizedVariantsJson()), - "descriptionLocalizedVariantsJson", - value(room.getDescriptionLocalizedVariantsJson()))) - .toList(), - "roomExits", - roomExitRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - roomExit -> - Map.of( - "id", roomExit.getId(), - "fromRoomId", roomExit.getFromRoom().getId(), - "toRoomId", roomExit.getToRoom().getId(), - "direction", roomExit.getDirection(), - "cost", roomExit.getCost())) - .toList(), - "generationRules", - generationRuleRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - rule -> - Map.of( - "id", rule.getId(), - "name", rule.getName(), - "scopeType", value(rule.getScopeType()), - "scopeId", value(rule.getScopeId()), - "value", value(rule.getValue()))) - .toList(), - "worldEntitySpawnBindings", - worldEntitySpawnBindingRepository - .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) - .stream() - .map( - binding -> - Map.of( - "id", binding.getId(), - "roomId", binding.getRoom().getId(), - "entityTemplateType", binding.getEntityTemplateType(), - "entityReference", entityReference(binding), - "spawnCount", binding.getSpawnCount(), - "respawnDelaySeconds", binding.getRespawnDelaySeconds())) - .toList())); + Map digestInput = + tables( + "regions", + regionRepository + .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) + .stream() + .map( + region -> + Map.of( + "id", region.getId(), + "shardId", region.getShardId(), + "name", region.getName(), + "weather", value(region.getWeather()), + "generationSeed", region.getGenerationSeed(), + "generatorType", value(region.getGeneratorType()), + "generatorParams", value(region.getGeneratorParams()), + "spacingMultiplier", region.getSpacingMultiplier())) + .toList(), + "zones", + zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey).stream() + .map( + zone -> + Map.of( + "id", zone.getId(), + "regionId", zone.getRegion().getId(), + "name", zone.getName())) + .toList(), + "rooms", + roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey).stream() + .map( + room -> + Map.of( + "id", room.getId(), + "zoneId", room.getZone().getId(), + "name", room.getName(), + "description", value(room.getDescription()), + "nameLocalizedVariantsJson", + value(room.getNameLocalizedVariantsJson()), + "descriptionLocalizedVariantsJson", + value(room.getDescriptionLocalizedVariantsJson()))) + .toList(), + "roomExits", + roomExitRepository + .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) + .stream() + .map( + roomExit -> + Map.of( + "id", roomExit.getId(), + "fromRoomId", roomExit.getFromRoom().getId(), + "toRoomId", roomExit.getToRoom().getId(), + "direction", roomExit.getDirection(), + "cost", roomExit.getCost())) + .toList(), + "generationRules", + generationRuleRepository + .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) + .stream() + .map( + rule -> + Map.of( + "id", rule.getId(), + "name", rule.getName(), + "scopeType", value(rule.getScopeType()), + "scopeId", value(rule.getScopeId()), + "value", value(rule.getValue()))) + .toList(), + "worldEntitySpawnBindings", + worldEntitySpawnBindingRepository + .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) + .stream() + .map( + binding -> + Map.of( + "id", binding.getId(), + "roomId", binding.getRoom().getId(), + "entityTemplateType", binding.getEntityTemplateType(), + "entityReference", entityReference(binding), + "spawnCount", binding.getSpawnCount(), + "respawnDelaySeconds", binding.getRespawnDelaySeconds())) + .toList()); + int schemaVersion = DIGEST_SCHEMA_VERSION; + if (inboundSourceClosure != null) { + digestInput.put("inboundSourceClosure", inboundSourceClosureContent(inboundSourceClosure)); + schemaVersion = SELECTED_DIGEST_SCHEMA_VERSION; + } + String canonicalJson = objectMapper.writeValueAsString(digestInput); return new WorldDraftDesignDigest( - tenantId, - versionId, - "version:" + versionId, - sha256(canonicalJson), - DIGEST_SCHEMA_VERSION); + tenantId, versionId, "version:" + versionId, sha256(canonicalJson), schemaVersion); } catch (Exception ex) { throw new IllegalStateException("failed to compute world draft design digest", ex); } } + private Map inboundSourceClosureContent( + InboundSourceClosureDeclaration declaration) { + Map content = new LinkedHashMap<>(); + content.put("schemaVersion", declaration.schemaVersion()); + content.put( + "familyCounts", + declaration.familyCounts().stream() + .map( + family -> { + Map entry = new LinkedHashMap<>(); + entry.put("family", family.family().name()); + entry.put("count", family.count()); + return entry; + }) + .toList()); + return content; + } + private String value(String value) { return value == null ? "" : value; } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java index a3065249e6..2ad1c4a82e 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshot.java @@ -154,9 +154,9 @@ public record CaptureRequest( requireText(publishWorkflowId, "publishWorkflowId"); requireText(appliedCommitId, "appliedCommitId"); requireSha256(contentDigest, "contentDigest"); - if (digestSchemaVersion != 2 && digestSchemaVersion != 3) { + if (digestSchemaVersion != 2 && digestSchemaVersion != 3 && digestSchemaVersion != 4) { throw new IllegalArgumentException( - "World graph snapshot requires retained schema 2 or current schema 3"); + "World graph capture request requires retained schema 2, schema 3 or selected schema 4"); } Objects.requireNonNull(suppliedOwnedAffectedTuples, "suppliedOwnedAffectedTuples"); List ordered = new ArrayList<>(suppliedOwnedAffectedTuples); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java index 854495eb61..3a540c92e1 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraph.java @@ -3,12 +3,16 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.EntityTemplateReference; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.InboundSourceClosureDeclaration; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; -/** Owner-private, validated graph/2 storage view, never synchronized or released content. */ +/** + * Owner-private, validated graph/2 or graph/3 storage view, never synchronized or released content. + */ public final class WorldCanonicalAuthoredGraph { public enum Family { REGION, @@ -62,14 +66,27 @@ public EntityTemplateReference entityReference() { private final long localTenantKey; private final long localVersionKey; private final List rows; + private final Optional inboundSourceClosure; WorldCanonicalAuthoredGraph( - UUID tenantId, UUID versionId, long localTenantKey, long localVersionKey, List rows) { + UUID tenantId, + UUID versionId, + long localTenantKey, + long localVersionKey, + List rows, + Optional inboundSourceClosure) { this.tenantId = tenantId; this.versionId = versionId; this.localTenantKey = localTenantKey; this.localVersionKey = localVersionKey; this.rows = List.copyOf(rows); + this.inboundSourceClosure = + Objects.requireNonNull(inboundSourceClosure, "inboundSourceClosure"); + } + + WorldCanonicalAuthoredGraph( + UUID tenantId, UUID versionId, long localTenantKey, long localVersionKey, List rows) { + this(tenantId, versionId, localTenantKey, localVersionKey, rows, Optional.empty()); } public UUID tenantId() { @@ -95,4 +112,9 @@ public List rows() { public List family(Family family) { return rows.stream().filter(row -> row.template().family() == family).toList(); } + + /** Exact source declaration; absence remains legacy history and never means empty. */ + public Optional inboundSourceClosure() { + return inboundSourceClosure; + } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java index 4c4ac48632..61cae19456 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java @@ -5,6 +5,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Row; @@ -16,7 +17,7 @@ import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.json.JsonMapper; -/** Closed graph/2 decoder. Retained numeric graph/1 remains a separate explicit reader. */ +/** Closed graph/2 legacy and graph/3 inbound-closure decoder. Numeric graph/1 stays separate. */ public final class WorldCanonicalAuthoredGraphReader { private static final ObjectMapper JSON = JsonMapper.builder() @@ -43,8 +44,32 @@ public final class WorldCanonicalAuthoredGraphReader { /** Complete original input supplies typed hierarchy/scope/Entity closure, never authority. */ public WorldCanonicalAuthoredGraph read(WorldDraftTopologyCommitPlan plan, byte[] bytes) { JsonNode root = JSON.readTree(bytes); - fields(root, Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows")); - text(root, "schemaVersion", "2"); + Optional inboundClosure = + plan.graph() + .freshGraphDeclaration() + .flatMap(WorldDraftTopologyInputGraph.FreshGraphDeclaration::inboundSourceClosure); + if (inboundClosure.isPresent()) { + fields( + root, + Set.of( + "schemaVersion", + "canonicalTenantId", + "canonicalVersionId", + "inboundSourceClosure", + "rows")); + text(root, "schemaVersion", "3"); + JsonNode retainedClosure = root.get("inboundSourceClosure"); + fields(retainedClosure, Set.of("schemaVersion", "familyCounts")); + if (!retainedClosure.equals( + JSON.valueToTree( + WorldDraftTopologyCommitRepository.inboundSourceClosureContent( + inboundClosure.orElseThrow())))) { + throw invalid("Canonical graph inbound declaration differs from original source bytes"); + } + } else { + fields(root, Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows")); + text(root, "schemaVersion", "2"); + } text(root, "canonicalTenantId", plan.graph().tenantId().toString()); text(root, "canonicalVersionId", plan.graph().versionId().toString()); JsonNode rows = root.get("rows"); @@ -140,7 +165,12 @@ public WorldCanonicalAuthoredGraph read(WorldDraftTopologyCommitPlan plan, byte[ content.build())); } return new WorldCanonicalAuthoredGraph( - plan.graph().tenantId(), plan.graph().versionId(), tenant, version, decoded); + plan.graph().tenantId(), + plan.graph().versionId(), + tenant, + version, + decoded, + inboundClosure); } private static void fields(JsonNode node, Set expected) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java index 3055518042..1bc464dc6b 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java @@ -106,8 +106,8 @@ WorldCanonicalFrozenTopology capture(Request request) { var provenance = owner.lockAndResolve(request.freeze()); WorldCanonicalFrozenTopology prior = find(request); if (prior != null) return prior; - if (request.freeze().digestSchemaVersion() != 3) { - throw new ConflictException("New canonical graph capture requires digest schema 3"); + if (request.freeze().digestSchemaVersion() != 4) { + throw new ConflictException("New canonical graph capture requires selected digest schema 4"); } if (!"FROZEN".equals(provenance.ownerFreezePhase())) { throw new ConflictException( @@ -129,16 +129,24 @@ WorldCanonicalFrozenTopology capture(Request request) { var graph = topology.verifyImmutableBytes(request.plan(), stored.graphBytes(), stored.resultBytes()); requirePrivateKeys(graph, identity); + var inboundClosure = + graph + .inboundSourceClosure() + .orElseThrow( + () -> + new ConflictException( + "New canonical graph capture requires its exact original inbound closure")); var digest = - digestService.getDraftDesignDigest( + digestService.getSelectedDraftDesignDigest( Long.toString(provenance.localTenantKey()), - Long.toString(provenance.localVersionKey())); + Long.toString(provenance.localVersionKey()), + inboundClosure); if (!Long.toString(provenance.localTenantKey()).equals(digest.tenantId()) || !Long.toString(provenance.localVersionKey()).equals(digest.scopeValue()) - || digest.digestSchemaVersion() != 3 + || digest.digestSchemaVersion() != 4 || !request.freeze().contentDigest().equals(digest.contentDigest())) { throw new ConflictException( - "Canonical graph capture differs from exact schema-3 frozen content checkpoint"); + "Canonical graph capture differs from exact selected schema-4 frozen content checkpoint"); } UUID captureId = UUID.randomUUID(); String freezeJson = JSON.writeValueAsString(request.freeze()); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index 07560e5121..878631961b 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -178,9 +178,8 @@ private WorldCanonicalInstanceLifecycleEvidence readMaterialized( readOperationalRegionAssignments(association, preparation, expectedRegionTemplates); var release = association.completeLaunchBinding().evidence().releaseAttestation(); - if (release.schemaVersion() - != net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence - .SELECTOR_SCHEMA_VERSION + if (!net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence + .requiresWorldStartLocationEvidence(release.schemaVersion()) || release.worldStartLocationEvidence() == null) { throw invalid("Receipt-less retained V1 preparation cannot produce lifecycle evidence"); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java index dc53cdba9b..6cbb1e5145 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java @@ -193,11 +193,16 @@ static void requireExactReleaseGraph( requireExactSelector(release, topologyPlan); } - /** V1 remains inert history; v2 must carry the complete original selector and frozen request. */ + /** V1 remains inert history; selected v2/v3 must carry the exact original World selector. */ static void requireExactSelector( AuthoredWorldReleaseAttestationEvidence release, WorldCanonicalInstanceTopologyPlan topologyPlan) { if (release.schemaVersion() == AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION) return; + if (!AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + release.schemaVersion())) { + throw new IllegalArgumentException( + "Canonical preparation requires a selected release schema"); + } var selector = Objects.requireNonNull(release.worldStartLocationEvidence(), "World selector evidence"); var freeze = topologyPlan.sourceBinding().freeze(); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java index bbe3963271..6ace8ac482 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java @@ -81,10 +81,11 @@ public WorldCanonicalInstancePreparation.Input assemble(Selector selector) { var descriptor = launchBinding.descriptor(); var release = launchBinding.evidence().releaseAttestation(); - if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + if (!AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + release.schemaVersion()) || release.worldStartLocationEvidence() == null) { throw new AssemblyRejectedException( - "Canonical preparation requires the stored v2 release selector and original frozen request"); + "Canonical preparation requires the stored selected release selector and original frozen request"); } // The UUID is the canonical selector. Never resolve the Game Design numeric Version ID here. diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java index cf3c5fc20f..d4750e0601 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -523,9 +523,11 @@ private static void requireExactPublishedRelease( GameDesignPublicationTerminalEvidence terminal, AuthoredWorldReleaseAttestationEvidence release) { var bundle = terminal.releaseContent(); - if (release.schemaVersion() != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + if (!AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + release.schemaVersion()) || !bundle.canonicalTenantId().equals(release.canonicalTenantId()) || !bundle.canonicalVersionId().equals(release.canonicalVersionId()) + || !bundle.attestationSchemaVersion().equals("v" + release.schemaVersion()) || !bundle.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef()) || terminal.publicationVersionStateEpoch() > release.versionStateEpoch() || !bundle.publishWorkflowId().equals(release.publishWorkflowId()) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java index 7074f6c0f8..1880e98f2b 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java @@ -484,11 +484,11 @@ private void requireCommittedLaunchEvidence( throw new WorldCompleteLaunchBindingRepository.RegistrationConflictException( "Game Design complete launch pair differs from the exact committed association selector"); } - if (evidence.releaseAttestation().schemaVersion() - != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + if (!AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + evidence.releaseAttestation().schemaVersion()) || evidence.releaseAttestation().worldStartLocationEvidence() == null) { throw new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( - "Committed launch binding requires the full selector-bearing release attestation v2"); + "Committed launch binding requires full selected-release selector evidence"); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java index 6318b9dd48..b459226828 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java @@ -103,7 +103,12 @@ Optional readSelectedPublicationApplication( || !selectedCommit.requestId().equals(application.operation().requestId()) || !selectedCommit.commitId().equals(application.operation().commitId()) || !selection.target().equals(application.operation().binding().target()) - || application.plan().graph().freshGraphDeclaration().isEmpty() + || application + .plan() + .graph() + .freshGraphDeclaration() + .flatMap(WorldDraftTopologyInputGraph.FreshGraphDeclaration::inboundSourceClosure) + .isEmpty() || !targetNamespace.equals(application.operation().ownerBinding().targetNamespace()) || !canonicalTenantId.equals(application.operation().canonicalTenantId()) || !canonicalVersionId.equals(application.operation().canonicalVersionId()) @@ -182,9 +187,16 @@ WorldDraftGraphAppliedResult apply( fence.lockOpenAndResolve(application.operation().ownerBinding()); prior = find(application.operation()); if (!prior.isEmpty()) return readUnique(application, prior); - if (application.plan().graph().freshGraphDeclaration().isEmpty()) { + if (application.plan().graph().freshGraphDeclaration().isEmpty() + || application + .plan() + .graph() + .freshGraphDeclaration() + .orElseThrow() + .inboundSourceClosure() + .isEmpty()) { throw new ConflictException( - "New World graph applications require the complete original fresh-graph declaration"); + "New World graph applications require the original versioned selected-inbound closure declaration"); } var operation = application.operation(); if (dsl.fetchOne( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java index ab565785ce..e0bdfcb274 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlan.java @@ -20,12 +20,15 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.EntityTemplateReference; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.FamilyCount; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.FreshGraphDeclaration; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.InboundSourceClosureDeclaration; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.InboundSourceFamilyCount; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeMutationPolicy; import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; import tools.jackson.core.StreamReadFeature; import tools.jackson.databind.DeserializationFeature; import tools.jackson.databind.ObjectMapper; @@ -37,9 +40,11 @@ *

This does not authenticate source or Entity evidence, authorize Account commits, allocate or * read storage, report APPLIED, expose a public handler, capture released content, or establish * lifecycle/runtime readiness. Existing numeric REGION plans and historical graph bytes are - * separate. Free-text and localized JSON fields are preserved, not semantically validated. Zero - * spacing, exit cost and spawn count preserve the existing owner-default input convention; a future - * writer must apply those defaults without changing the original binding. + * separate. A present selected-inbound closure must be the exact version-1 seven-family empty-only + * vector; absence remains legacy input and does not qualify new APPLIED or selected inventory. + * Free-text and localized JSON fields are preserved, not semantically validated. Zero spacing, exit + * cost and spawn count preserve the existing owner-default input convention; a future writer must + * apply those defaults without changing the original binding. */ public final class WorldDraftTopologyCommitPlan { private static final ObjectMapper STRICT_JSON = @@ -57,6 +62,8 @@ public final class WorldDraftTopologyCommitPlan { WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING); + static final List INBOUND_SOURCE_FAMILY_ORDER = + WorldDraftTopologyInputGraph.INBOUND_SOURCE_FAMILY_ORDER; private record ObjectReference(WorldDesignAggregateType kind, UUID templateId) {} @@ -370,7 +377,36 @@ private static FreshGraphDeclaration parseFreshGraphDeclaration( } counts.add(new FamilyCount(entry.getFamily(), entry.getCount())); } - return new FreshGraphDeclaration(tenantId, versionId, startLocation, counts); + return new FreshGraphDeclaration( + tenantId, + versionId, + startLocation, + counts, + declaration.hasInboundSourceClosure() + ? java.util.Optional.of( + parseInboundSourceClosure(declaration.getInboundSourceClosure())) + : java.util.Optional.empty()); + } + + private static InboundSourceClosureDeclaration parseInboundSourceClosure( + net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceClosureDeclaration declaration) { + if (declaration.getSchemaVersion() != 1 + || declaration.getFamilyCountsCount() != INBOUND_SOURCE_FAMILY_ORDER.size()) { + throw invalid( + "Fresh World source closure requires the complete supported version-1 family vector"); + } + List counts = new ArrayList<>(); + for (int index = 0; index < INBOUND_SOURCE_FAMILY_ORDER.size(); index++) { + var entry = declaration.getFamilyCounts(index); + if (entry.getFamily() != INBOUND_SOURCE_FAMILY_ORDER.get(index) + || !entry.hasCount() + || entry.getCount() != 0) { + throw invalid( + "Fresh World source closure must be canonical, explicit and empty-only; nonempty families are unsupported"); + } + counts.add(new InboundSourceFamilyCount(entry.getFamily(), entry.getCount())); + } + return new InboundSourceClosureDeclaration(declaration.getSchemaVersion(), counts); } private static void validateDeclaredFamilies( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java index 5d3842330e..187dec4636 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java @@ -21,6 +21,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.ConflictException; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository.OpenOwner; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.InboundSourceClosureDeclaration; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.Node; import org.jooq.DSLContext; import org.jooq.Record; @@ -28,7 +29,7 @@ import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; -/** Actual fresh six-family storage; explicitly unwired, with owner-internal private keys. */ +/** Actual fresh six-family storage and source closure; explicitly unwired, with private keys. */ public class WorldDraftTopologyCommitRepository { private final DSLContext dsl; private final WorldDesignPublicationFenceRepository fence; @@ -460,13 +461,40 @@ private byte[] readAndVerifyGraph(WorldDraftTopologyCommitPlan plan, long tenant } } Map graph = new LinkedHashMap<>(); - graph.put("schemaVersion", "2"); + boolean hasInboundSourceClosure = + plan.graph() + .freshGraphDeclaration() + .flatMap(WorldDraftTopologyInputGraph.FreshGraphDeclaration::inboundSourceClosure) + .isPresent(); + graph.put("schemaVersion", hasInboundSourceClosure ? "3" : "2"); graph.put("canonicalTenantId", plan.graph().tenantId().toString()); graph.put("canonicalVersionId", plan.graph().versionId().toString()); + plan.graph() + .freshGraphDeclaration() + .flatMap(WorldDraftTopologyInputGraph.FreshGraphDeclaration::inboundSourceClosure) + .ifPresent( + closure -> graph.put("inboundSourceClosure", inboundSourceClosureContent(closure))); graph.put("rows", rows); return mapper.writeValueAsBytes(graph); } + static Map inboundSourceClosureContent(InboundSourceClosureDeclaration closure) { + Map content = new LinkedHashMap<>(); + content.put("schemaVersion", closure.schemaVersion()); + content.put( + "familyCounts", + closure.familyCounts().stream() + .map( + family -> { + Map entry = new LinkedHashMap<>(); + entry.put("family", family.family().name()); + entry.put("count", family.count()); + return entry; + }) + .toList()); + return content; + } + static Map expectedContent( Node node, Map keys, long tenant, long version) { Map row = new LinkedHashMap<>(); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java index 3f7ecf4446..6cd5e83182 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java @@ -3,11 +3,13 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.world.RoomTemplateRef; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; /** * Immutable PURE_UNVERIFIED logical input, never a stored or released World graph. @@ -19,6 +21,32 @@ */ public final class WorldDraftTopologyInputGraph { public static final String STATUS = "PURE_UNVERIFIED"; + public static final List INBOUND_SOURCE_FAMILY_ORDER = + List.of( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING); + + /** Validates the only digest-supported inbound subset against the source-authored declaration. */ + public static void requireEmptyInboundSourceClosure(InboundSourceClosureDeclaration declaration) { + Objects.requireNonNull(declaration, "declaration"); + if (declaration.schemaVersion() != 1 + || declaration.familyCounts().size() != INBOUND_SOURCE_FAMILY_ORDER.size()) { + throw new IllegalArgumentException( + "World inbound source closure requires the complete supported version-1 family vector"); + } + for (int index = 0; index < INBOUND_SOURCE_FAMILY_ORDER.size(); index++) { + InboundSourceFamilyCount count = declaration.familyCounts().get(index); + if (count.family() != INBOUND_SOURCE_FAMILY_ORDER.get(index) || count.count() != 0) { + throw new IllegalArgumentException( + "World inbound source closure is noncanonical or outside the supported empty-only subset"); + } + } + } /** One explicit member of the complete six-family declaration; zero is meaningful. */ public record FamilyCount(WorldDesignAggregateType family, int count) { @@ -30,17 +58,51 @@ public record FamilyCount(WorldDesignAggregateType family, int count) { } } - /** Typed start selector and exhaustive family counts from the original Account-bound input. */ + /** One explicitly named selected-inbound source family; only zero counts are currently closed. */ + public record InboundSourceFamilyCount(WorldInboundSourceFamily family, int count) { + public InboundSourceFamilyCount { + Objects.requireNonNull(family, "family"); + if (count < 0) { + throw new IllegalArgumentException("World inbound source count must be nonnegative"); + } + } + } + + /** Versioned family enumeration copied from the exact original World revision payload. */ + public record InboundSourceClosureDeclaration( + int schemaVersion, List familyCounts) { + public InboundSourceClosureDeclaration { + if (schemaVersion <= 0) { + throw new IllegalArgumentException("World inbound source schema version must be positive"); + } + familyCounts = List.copyOf(Objects.requireNonNull(familyCounts, "familyCounts")); + } + } + + /** Typed start selector and source declarations from the original Account-bound input. */ public record FreshGraphDeclaration( UUID tenantId, UUID versionId, RoomTemplateRef startLocation, - List familyCounts) { + List familyCounts, + Optional inboundSourceClosure) { public FreshGraphDeclaration { Objects.requireNonNull(tenantId, "tenantId"); Objects.requireNonNull(versionId, "versionId"); Objects.requireNonNull(startLocation, "startLocation"); familyCounts = List.copyOf(familyCounts); + inboundSourceClosure = Objects.requireNonNull(inboundSourceClosure, "inboundSourceClosure"); + } + + /** + * Retains exact pre-closure source values without treating their omission as an empty value. + */ + public FreshGraphDeclaration( + UUID tenantId, + UUID versionId, + RoomTemplateRef startLocation, + List familyCounts) { + this(tenantId, versionId, startLocation, familyCounts, Optional.empty()); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java index 545ef3f6ab..a3972ac7be 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java @@ -80,8 +80,8 @@ WorldPublishedSpawnRequirementsEvidence read( if (!workloadNamespace.equals(launchBinding.descriptor().targetNamespace()) || !workloadNamespace.equals(release.targetNamespace()) || !request.expectedReleaseAttestationDigest().equals(release.evidenceDigest()) - || release.schemaVersion() - != AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION + || !AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence( + release.schemaVersion()) || release.worldStartLocationEvidence() == null) { throw rejected( Status.Code.FAILED_PRECONDITION, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java index ff212ca939..b5cdee2783 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java @@ -14,7 +14,7 @@ * or a public freeze route, and it does not change the generic digest's highest-commit contract. */ final class WorldSelectedDraftPublicationCheckpointRepository { - private static final int REQUIRED_DIGEST_SCHEMA_VERSION = 3; + private static final int REQUIRED_DIGEST_SCHEMA_VERSION = 4; private final WorldDesignPublicationFenceRepository fence; private final WorldDraftGraphApplicationRepository applications; @@ -49,7 +49,7 @@ CapturedCheckpoint captureWithSource( } // Reacquiring this exact row inside claimFreeze's callback is reentrant and keeps the same - // owner lock held while APPLIED history, current rows/epochs, and the schema-3 digest are read. + // owner lock held while APPLIED history, current rows/epochs, and the schema-4 digest are read. var owner = fence.lockOpenAndResolve(freeze.ownerBinding()); var applied = applications.readAppliedForPublicationCheckpoint(freeze, selectedPlan); var stored = topology.readUnderFrozenLock(selectedPlan); @@ -62,14 +62,23 @@ CapturedCheckpoint captureWithSource( var graph = topology.verifyImmutableBytes(selectedPlan, stored.graphBytes(), stored.resultBytes()); + var inboundClosure = + graph + .inboundSourceClosure() + .orElseThrow( + () -> + new ConflictException( + "World selected digest requires the exact original inbound source closure")); var digest = - digestService.getDraftDesignDigest( - Long.toString(owner.localTenantKey()), Long.toString(owner.localVersionKey())); + digestService.getSelectedDraftDesignDigest( + Long.toString(owner.localTenantKey()), + Long.toString(owner.localVersionKey()), + inboundClosure); if (!Long.toString(owner.localTenantKey()).equals(digest.tenantId()) || !Long.toString(owner.localVersionKey()).equals(digest.scopeValue()) || digest.digestSchemaVersion() != REQUIRED_DIGEST_SCHEMA_VERSION) { throw new ConflictException( - "World selected graph digest differs from the exact local schema-3 Draft scope"); + "World selected graph digest differs from the exact local schema-4 Draft scope"); } return new CapturedCheckpoint( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java index 50d72c44d4..61a480486f 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java @@ -13,6 +13,7 @@ import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; @@ -35,12 +36,23 @@ * Immutable, owner-derived complete inventory for the closed logical room/exit source model. * *

This is not an artifact payload or an Asset Storage manifest. It is derived from the exact - * retained APPLIED graph/2 and the World-owned freeze checkpoint. The supported room/exit profile - * uses authored edges directly and has no separate NAVMESH or PATH_GRAPH bundle requirement. + * retained APPLIED graph/3 and the World-owned freeze checkpoint. Its inbound source declaration is + * original authored input and currently supports only seven explicitly declared empty families; + * legacy graph/2 bytes remain a separate exact-read path and never imply an empty declaration. The + * supported room/exit profile uses authored edges directly and has no separate NAVMESH or + * PATH_GRAPH bundle requirement. */ public final class WorldSelectedPublicationArtifactInventory { static final String SCHEMA = "world-selected-publication-artifact-inventory/v1"; + static final String INBOUND_CLOSURE_SCHEMA = + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA; + private static final int SCHEMA_VERSION = + WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA_VERSION; + private static final int INBOUND_CLOSURE_SCHEMA_VERSION = + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION; private static final String SOURCE_MODEL = "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1"; + private static final String INBOUND_CLOSURE_SOURCE_MODEL = + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL; private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); private static final Pattern HEX_DIGEST = Pattern.compile("[0-9a-f]{64}"); private static final ObjectMapper JSON = @@ -57,6 +69,15 @@ public final class WorldSelectedPublicationArtifactInventory { WorldCanonicalAuthoredGraph.Family.ROOM_EXIT, WorldCanonicalAuthoredGraph.Family.GENERATION_RULE, WorldCanonicalAuthoredGraph.Family.WORLD_ENTITY_SPAWN_BINDING); + private static final List INBOUND_SOURCE_FAMILY_ORDER = + List.of( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", + "WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING"); private static final List REGION_FIELDS = List.of( "id", @@ -234,6 +255,13 @@ static WorldSelectedPublicationArtifactInventory capture( WorldCanonicalAuthoredGraph graph = captured.graph(); requireSupportedFamilySchema(); + var inboundClosure = + graph + .inboundSourceClosure() + .orElseThrow( + () -> + new ConflictException( + "World selected inventory requires the exact original inbound source closure declaration")); List counts = new ArrayList<>(); for (WorldCanonicalAuthoredGraph.Family family : SUPPORTED_FAMILY_ORDER) { counts.add(new FamilyCount(family.name(), graph.family(family).size())); @@ -292,8 +320,8 @@ static WorldSelectedPublicationArtifactInventory capture( var owner = request.ownerBinding(); var sourceModel = new SourceModel( - SOURCE_MODEL, - 2, + INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, WorldDraftGraphAppliedResult.digest(captured.application().graphBytes()), WorldDraftGraphAppliedResult.digest(captured.topology().resultBytes()), counts, @@ -308,12 +336,20 @@ static WorldSelectedPublicationArtifactInventory capture( generationRuleCount, familyCount( counts, WorldCanonicalAuthoredGraph.Family.WORLD_ENTITY_SPAWN_BINDING.name()), - captured.application().appliedEpochs()); + captured.application().appliedEpochs(), + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration( + inboundClosure.schemaVersion(), + inboundClosure.familyCounts().stream() + .map( + family -> + new WorldSelectedPublicationArtifactInventoryEvidence + .InboundSourceFamilyCount(family.family().name(), family.count())) + .toList())); var bindingBytes = accountBinding.canonicalBytes(); var envelope = new Envelope( - SCHEMA, - 1, + INBOUND_CLOSURE_SCHEMA, + INBOUND_CLOSURE_SCHEMA_VERSION, "COMPLETE", new OwnerScope( owner.targetNamespace(), @@ -467,7 +503,8 @@ private static SourceModel publicSourceModel(SourceModel model) { spawnBindings, model.generationRuleInputCount(), model.spawnBindingCount(), - model.appliedEpochs()); + model.appliedEpochs(), + model.inboundSourceClosure()); } /** Canonical bytes for the safe public projection; private owner keys are never serialized. */ @@ -509,8 +546,12 @@ private static void requireEnvelopeBinding( var application = envelope.selectedApplication(); var source = envelope.sourceIntake(); var sourceModel = envelope.sourceModel(); - if (!SCHEMA.equals(envelope.schema()) - || envelope.schemaVersion() != 1 + boolean legacyEnvelope = + SCHEMA.equals(envelope.schema()) && envelope.schemaVersion() == SCHEMA_VERSION; + boolean inboundClosureEnvelope = + INBOUND_CLOSURE_SCHEMA.equals(envelope.schema()) + && envelope.schemaVersion() == INBOUND_CLOSURE_SCHEMA_VERSION; + if ((!legacyEnvelope && !inboundClosureEnvelope) || !"COMPLETE".equals(envelope.completeness()) || !nonNil(identity.canonicalTenantId()) || !nonNil(identity.canonicalVersionId()) @@ -580,9 +621,30 @@ private static void requireEnvelopeBinding( } private static void requireCompleteSupportedModel(Envelope envelope) { + if (envelope.sourceModel() == null) { + throw new ConflictException( + "Stored World artifact inventory does not declare the complete supported source model"); + } + SourceModel sourceModel = envelope.sourceModel(); + boolean legacyEnvelope = + SCHEMA.equals(envelope.schema()) && envelope.schemaVersion() == SCHEMA_VERSION; + boolean inboundClosureEnvelope = + INBOUND_CLOSURE_SCHEMA.equals(envelope.schema()) + && envelope.schemaVersion() == INBOUND_CLOSURE_SCHEMA_VERSION; + boolean legacyModel = + legacyEnvelope + && SOURCE_MODEL.equals(sourceModel.modelId()) + && sourceModel.graphSchemaVersion() == 2 + && sourceModel.inboundSourceClosure() == null; + boolean inboundClosureModel = + inboundClosureEnvelope + && INBOUND_CLOSURE_SOURCE_MODEL.equals(sourceModel.modelId()) + && sourceModel.graphSchemaVersion() + == WorldSelectedPublicationArtifactInventoryEvidence + .INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION + && sourceModel.inboundSourceClosure() != null; if (envelope.sourceModel() == null - || !SOURCE_MODEL.equals(envelope.sourceModel().modelId()) - || envelope.sourceModel().graphSchemaVersion() != 2 + || (!legacyModel && !inboundClosureModel) || envelope.sourceModel().generationRuleInputCount() != 0 || envelope.sourceModel().familyCounts().size() != SUPPORTED_FAMILY_ORDER.size() || !envelope.sourceModel().regionFields().equals(REGION_FIELDS) @@ -596,10 +658,13 @@ private static void requireCompleteSupportedModel(Envelope envelope) { || !isSha256(envelope.sourceModel().graphDigest()) || !isSha256(envelope.sourceModel().topologyResultDigest()) || !isHexDigest(envelope.checkpoint().contentDigest()) - || envelope.checkpoint().digestSchemaVersion() != 3) { + || envelope.checkpoint().digestSchemaVersion() != (inboundClosureModel ? 4 : 3)) { throw new ConflictException( "Stored World artifact inventory does not declare the complete supported source model"); } + if (inboundClosureModel) { + requireEmptyInboundClosure(sourceModel.inboundSourceClosure()); + } for (int index = 0; index < SUPPORTED_FAMILY_ORDER.size(); index++) { var familyCount = envelope.sourceModel().familyCounts().get(index); if (!SUPPORTED_FAMILY_ORDER.get(index).name().equals(familyCount.family()) @@ -648,6 +713,24 @@ private static void requireSupportedFamilySchema() { } } + private static void requireEmptyInboundClosure( + WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration + declaration) { + if (declaration == null + || declaration.schemaVersion() != 1 + || declaration.familyCounts().size() != INBOUND_SOURCE_FAMILY_ORDER.size()) { + throw new ConflictException( + "Stored World inventory omits the complete version-1 inbound source declaration"); + } + for (int index = 0; index < INBOUND_SOURCE_FAMILY_ORDER.size(); index++) { + var count = declaration.familyCounts().get(index); + if (!INBOUND_SOURCE_FAMILY_ORDER.get(index).equals(count.family()) || count.count() != 0) { + throw new ConflictException( + "Stored World inventory has unknown or unsupported nonempty inbound source input"); + } + } + } + static void requireSupportedRequiredness( UUID canonicalTenantId, UUID canonicalVersionId, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryRepository.java index 0aea6cb8a8..e27b5816bb 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryRepository.java @@ -124,7 +124,7 @@ private WorldSelectedPublicationArtifactInventory readExact( || !appliedCommitId.equals(attempt.checkpoint().appliedCommitId()) || !accountOperationId.equals(accountBinding.operationId()) || !accountFenceId.equals(accountBinding.fenceId()) - || schemaVersion != 1 + || (schemaVersion != 1 && schemaVersion != 2) || !Arrays.equals(retainedAccountBytes, accountBinding.canonicalBytes()) || !DraftAuthorizationFenceBinding.digest(retainedAccountBytes) .equals(retainedAccountDigest)) { @@ -147,6 +147,10 @@ private WorldSelectedPublicationArtifactInventory readExact( accountBinding, localTenantKey, localVersionKey); + if (schemaVersion != inventory.envelope().schemaVersion()) { + throw conflict( + "Stored World artifact inventory schema column differs from exact retained bytes"); + } var scope = inventory.envelope().ownerScope(); if (!scope.targetNamespace().equals(targetNamespace) || !scope.canonicalTenantId().equals(tenantId) diff --git a/services/world-management-service/src/main/resources/db/migration/V59__world_selected_inbound_closure_declaration.sql b/services/world-management-service/src/main/resources/db/migration/V59__world_selected_inbound_closure_declaration.sql new file mode 100644 index 0000000000..c0fac99d26 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V59__world_selected_inbound_closure_declaration.sql @@ -0,0 +1,115 @@ +-- Additive guard for the versioned selected-inbound source declaration. Existing V24/V30/V35 +-- canonical-key, mapped-identity and execution-manifest guards remain authoritative; this guard +-- binds the explicit empty-only closure to the exact original graph written under the OPEN owner. +-- [jooq ignore start] +CREATE FUNCTION world_guard_selected_inbound_closure() RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + graph_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + declaration JSONB; + closure JSONB; + graph_json JSONB; + family_entry JSONB; + family_names TEXT[] := ARRAY[ + 'WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT', + 'WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT', + 'WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION', + 'WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING', + 'WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK', + 'WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE', + 'WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING']; + declaration_count BIGINT; + mapping_count BIGINT; + family_index INTEGER; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World selected-inbound APPLIED evidence is immutable and retained' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO graph_row FROM "${serviceSchema}".world_topology_draft_commit + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id; + IF NOT FOUND OR graph_row.application_transaction_id IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'Selected-inbound closure requires a genuinely fresh graph in this transaction' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO owner_row FROM "${serviceSchema}".world_design_publication_fence_owner + WHERE target_namespace = graph_row.target_namespace + AND canonical_tenant_id = graph_row.canonical_tenant_id + AND local_tenant_key = graph_row.local_tenant_key + AND version_id = graph_row.local_version_key FOR UPDATE; + IF NOT FOUND OR owner_row.owner_freeze_phase <> 'OPEN' + OR owner_row.current_publication_fence IS NOT NULL THEN + RAISE EXCEPTION 'Selected-inbound closure requires the exact OPEN World owner lock' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*) INTO declaration_count + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND (((value->>'payload')::JSONB)->'freshGraphDeclaration') IS NOT NULL; + IF declaration_count <> 1 THEN + RAISE EXCEPTION 'Selected-inbound closure requires one exact original World declaration' + USING ERRCODE = '23514'; + END IF; + SELECT ((value->>'payload')::JSONB)->'freshGraphDeclaration' INTO declaration + FROM jsonb_array_elements(graph_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE value->>'owner' = 'WORLD_MANAGEMENT' + AND (((value->>'payload')::JSONB)->'freshGraphDeclaration') ? 'inboundSourceClosure'; + closure := declaration->'inboundSourceClosure'; + IF jsonb_typeof(closure) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(closure) = 'object' THEN closure ELSE '{}'::JSONB END)) <> 2 + OR NOT (closure ? 'schemaVersion') + OR jsonb_typeof(closure->'schemaVersion') IS DISTINCT FROM 'number' + OR closure->>'schemaVersion' IS DISTINCT FROM '1' + OR jsonb_typeof(closure->'familyCounts') IS DISTINCT FROM 'array' + OR jsonb_array_length(closure->'familyCounts') <> array_length(family_names, 1) THEN + RAISE EXCEPTION 'Selected-inbound source closure is unknown, incomplete or unversioned' + USING ERRCODE = '23514'; + END IF; + + graph_json := convert_from(graph_row.graph_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(graph_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(graph_json) = 'object' THEN graph_json ELSE '{}'::JSONB END)) <> 5 + OR graph_json->>'schemaVersion' IS DISTINCT FROM '3' + OR graph_json->>'canonicalTenantId' IS DISTINCT FROM graph_row.canonical_tenant_id::TEXT + OR graph_json->>'canonicalVersionId' IS DISTINCT FROM graph_row.canonical_version_id::TEXT + OR graph_json->'inboundSourceClosure' IS DISTINCT FROM closure + OR jsonb_typeof(graph_json->'rows') IS DISTINCT FROM 'array' + OR jsonb_array_length(graph_json->'rows') < 1 THEN + RAISE EXCEPTION 'Canonical graph does not retain the exact original inbound closure' + USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO mapping_count + FROM "${serviceSchema}".world_authored_topology_identity + WHERE request_id = NEW.request_id AND commit_id = NEW.commit_id + AND tenant_id = graph_row.local_tenant_key AND version_id = graph_row.local_version_key; + IF mapping_count <> jsonb_array_length(graph_json->'rows') THEN + RAISE EXCEPTION 'Selected-inbound closure lacks complete same-scope fresh mapped World rows' + USING ERRCODE = '23514'; + END IF; + + FOR family_index IN 1..array_length(family_names, 1) LOOP + family_entry := closure->'familyCounts'->(family_index - 1); + IF jsonb_typeof(family_entry) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(family_entry) = 'object' THEN family_entry ELSE '{}'::JSONB END)) <> 2 + OR family_entry->>'family' IS DISTINCT FROM family_names[family_index] + OR NOT (family_entry ? 'count') + OR jsonb_typeof(family_entry->'count') IS DISTINCT FROM 'number' + OR family_entry->>'count' IS DISTINCT FROM '0' THEN + RAISE EXCEPTION 'Selected-inbound family vector is noncanonical or outside the empty-only subset' + USING ERRCODE = '23514'; + END IF; + END LOOP; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_graph_inbound_closure_guard BEFORE INSERT + ON world_draft_graph_application FOR EACH ROW + EXECUTE FUNCTION world_guard_selected_inbound_closure(); +REVOKE ALL ON FUNCTION world_guard_selected_inbound_closure() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V60__world_selected_publication_inventory_schema_v2.sql b/services/world-management-service/src/main/resources/db/migration/V60__world_selected_publication_inventory_schema_v2.sql new file mode 100644 index 0000000000..890be52f65 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V60__world_selected_publication_inventory_schema_v2.sql @@ -0,0 +1,63 @@ +-- Preserve exact schema-1 inventory rows and permit only the additive closure inventory profile. +-- [jooq ignore start] +DO $migration$ +DECLARE + target_schema TEXT := '${serviceSchema}'; + target_table TEXT := 'world_selected_publication_artifact_inventory'; + target_relation OID; + target_column SMALLINT; + matching_guard_count BIGINT; + guard_names TEXT[]; + guard_name TEXT; + guard_is_expected BOOLEAN; + replacement_guard TEXT := 'ck_world_selected_pub_inv_schema_v2'; +BEGIN + SELECT c.oid INTO target_relation + FROM pg_catalog.pg_class c + JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = target_schema + AND c.relname = target_table + AND c.relkind = 'r'; + IF target_relation IS NULL THEN + RAISE EXCEPTION 'Expected exact World selected inventory owner table %.%', + target_schema, target_table; + END IF; + + SELECT a.attnum INTO target_column + FROM pg_catalog.pg_attribute a + WHERE a.attrelid = target_relation + AND a.attname = 'inventory_schema_version' + AND NOT a.attisdropped; + IF target_column IS NULL THEN + RAISE EXCEPTION 'Expected inventory_schema_version on exact World inventory owner table'; + END IF; + + SELECT count(*), array_agg(c.conname::TEXT), bool_and( + c.conislocal + AND c.convalidated + AND c.conkey = ARRAY[target_column]::SMALLINT[] + AND pg_catalog.regexp_replace( + pg_catalog.lower(pg_catalog.pg_get_expr(c.conbin, c.conrelid)), + '[[:space:]()]', '', 'g') = 'inventory_schema_version=1') + INTO matching_guard_count, guard_names, guard_is_expected + FROM pg_catalog.pg_constraint c + WHERE c.conrelid = target_relation + AND c.contype = 'c' + AND target_column = ANY(c.conkey); + + IF matching_guard_count <> 1 OR guard_is_expected IS DISTINCT FROM TRUE THEN + RAISE EXCEPTION + 'Expected exactly one single-column inventory_schema_version = 1 check on %.%', + target_schema, target_table; + END IF; + guard_name := guard_names[1]; + + EXECUTE pg_catalog.format( + 'ALTER TABLE %I.%I DROP CONSTRAINT %s', + target_schema, target_table, pg_catalog.quote_ident(guard_name)); + EXECUTE pg_catalog.format( + 'ALTER TABLE %I.%I ADD CONSTRAINT %s CHECK (inventory_schema_version IN (1, 2))', + target_schema, target_table, pg_catalog.quote_ident(replacement_guard)); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/main/resources/db/migration/V61__world_selected_closure_schema4_guards.sql b/services/world-management-service/src/main/resources/db/migration/V61__world_selected_closure_schema4_guards.sql new file mode 100644 index 0000000000..8806de25d9 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V61__world_selected_closure_schema4_guards.sql @@ -0,0 +1,265 @@ +-- A selected World digest/4 is valid only for a newly applied graph/3 carrying the exact original +-- seven-family empty declaration. Historical schema-2/3 rows and V27 bytes are not rewritten. +-- [jooq ignore start] +DROP TRIGGER trg_world_canonical_frozen_00_schema3 ON world_canonical_frozen_topology; + +CREATE FUNCTION world_require_new_selected_digest_capture() RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + request JSONB; + attempt "${serviceSchema}".world_design_publication_fence_attempt%ROWTYPE; + owner_row "${serviceSchema}".world_design_publication_fence_owner%ROWTYPE; + commit_row "${serviceSchema}".world_topology_draft_commit%ROWTYPE; + graph_json JSONB; + closure JSONB; + declaration_count BIGINT; + matching_declaration_count BIGINT; + mapping_count BIGINT; + applied_count BIGINT; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR current_setting('transaction_read_only') <> 'off' THEN + RAISE EXCEPTION 'Canonical frozen capture requires writable READ COMMITTED' + USING ERRCODE = '23514'; + END IF; + + request := NEW.freeze_request_json::JSONB; + IF request->>'digestSchemaVersion' IS DISTINCT FROM '4' THEN + RAISE EXCEPTION 'New canonical graph capture requires selected closure schema 4' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT commit_row + FROM "${serviceSchema}".world_topology_draft_commit c + WHERE c.request_id = NEW.request_id AND c.commit_id = NEW.commit_id; + SELECT * INTO STRICT attempt + FROM "${serviceSchema}".world_design_publication_fence_attempt a + WHERE a.publication_fence = NEW.publication_fence; + SELECT * INTO STRICT owner_row + FROM "${serviceSchema}".world_design_publication_fence_owner o + WHERE o.target_namespace = commit_row.target_namespace + AND o.canonical_tenant_id = commit_row.canonical_tenant_id + AND o.local_tenant_key = commit_row.local_tenant_key + AND o.version_id = commit_row.local_version_key + FOR UPDATE; + + IF owner_row.owner_freeze_phase IS DISTINCT FROM 'FROZEN' + OR owner_row.current_publication_fence IS DISTINCT FROM NEW.publication_fence + OR attempt.owner_binding_schema_version IS DISTINCT FROM 1 + OR attempt.publication_fence IS DISTINCT FROM NEW.publication_fence + OR attempt.target_namespace IS DISTINCT FROM request->>'targetNamespace' + OR attempt.canonical_tenant_id::TEXT IS DISTINCT FROM request->>'canonicalTenantId' + OR attempt.canonical_version_id::TEXT IS DISTINCT FROM request->>'canonicalVersionId' + OR attempt.applied_commit_id IS DISTINCT FROM request->>'appliedCommitId' + OR attempt.content_digest IS DISTINCT FROM request->>'contentDigest' + OR attempt.digest_schema_version IS DISTINCT FROM 4 + OR commit_row.target_namespace IS DISTINCT FROM request->>'targetNamespace' + OR commit_row.canonical_tenant_id::TEXT IS DISTINCT FROM request->>'canonicalTenantId' + OR commit_row.canonical_version_id::TEXT IS DISTINCT FROM request->>'canonicalVersionId' + OR commit_row.graph_bytes IS DISTINCT FROM NEW.graph_bytes + OR commit_row.result_bytes IS DISTINCT FROM NEW.storage_result_bytes THEN + RAISE EXCEPTION 'Selected graph/4 capture differs from exact FROZEN source and checkpoint' + USING ERRCODE = '23514'; + END IF; + + closure := '{"schemaVersion":1,"familyCounts":[{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING","count":0}]}'::JSONB; + graph_json := convert_from(commit_row.graph_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(graph_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(graph_json) = 'object' THEN graph_json ELSE '{}'::JSONB END)) <> 5 + OR graph_json->>'schemaVersion' IS DISTINCT FROM '3' + OR graph_json->>'canonicalTenantId' IS DISTINCT FROM commit_row.canonical_tenant_id::TEXT + OR graph_json->>'canonicalVersionId' IS DISTINCT FROM commit_row.canonical_version_id::TEXT + OR graph_json->'inboundSourceClosure' IS DISTINCT FROM closure + OR jsonb_typeof(graph_json->'rows') IS DISTINCT FROM 'array' + OR jsonb_array_length(graph_json->'rows') < 1 THEN + RAISE EXCEPTION 'Selected digest/4 requires the exact original graph/3 closure declaration' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*) INTO declaration_count + FROM jsonb_array_elements(commit_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE revision.value->>'owner' = 'WORLD_MANAGEMENT' + AND (((revision.value->>'payload')::JSONB)->'freshGraphDeclaration') IS NOT NULL; + SELECT count(*) INTO matching_declaration_count + FROM jsonb_array_elements(commit_row.binding_json::JSONB->'revisions') AS revision(value) + WHERE revision.value->>'owner' = 'WORLD_MANAGEMENT' + AND (((revision.value->>'payload')::JSONB)->'freshGraphDeclaration'->'inboundSourceClosure') + IS NOT DISTINCT FROM closure; + IF declaration_count <> 1 OR matching_declaration_count <> 1 THEN + RAISE EXCEPTION 'Selected digest/4 requires one exact original authored closure declaration' + USING ERRCODE = '23514'; + END IF; + + SELECT count(*) INTO mapping_count + FROM "${serviceSchema}".world_authored_topology_identity m + WHERE m.request_id = commit_row.request_id AND m.commit_id = commit_row.commit_id + AND m.tenant_id = commit_row.local_tenant_key + AND m.version_id = commit_row.local_version_key; + SELECT count(*) INTO applied_count + FROM "${serviceSchema}".world_draft_graph_application a + WHERE a.request_id = commit_row.request_id AND a.commit_id = commit_row.commit_id + AND a.application_transaction_id = commit_row.application_transaction_id + AND a.result_digest = 'sha256:' || encode(sha256(a.result_bytes), 'hex') + AND convert_from(a.result_bytes, 'UTF8')::JSONB->>'status' = 'APPLIED' + AND convert_from(a.result_bytes, 'UTF8')::JSONB->>'graphDigest' + = 'sha256:' || encode(sha256(commit_row.graph_bytes), 'hex'); + IF mapping_count <> jsonb_array_length(graph_json->'rows') OR mapping_count = 0 + OR applied_count <> 1 THEN + RAISE EXCEPTION 'Selected digest/4 requires complete same-scope fresh mappings and exact APPLIED result' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_world_canonical_frozen_00_selected_digest + BEFORE INSERT ON world_canonical_frozen_topology + FOR EACH ROW EXECUTE FUNCTION world_require_new_selected_digest_capture(); +REVOKE ALL ON FUNCTION world_require_new_selected_digest_capture() FROM PUBLIC; + +-- Advance the release join without changing its v1/v2 evidence or preparation behavior. Selected +-- attestation/2 remains World/3; only attestation/3 may carry World/4 and its exact selector. +DO $migration$ +DECLARE + preparation_function REGPROCEDURE := + '"${serviceSchema}".world_prepare_canonical_instance(text,text)'::REGPROCEDURE; + original_definition TEXT; + anchor TEXT := $anchor$ AND participant->>'digestSchemaVersion' = '3'$anchor$; + replacement TEXT := $replacement$ AND binding_row.release_attestation_json::JSONB->>'schemaVersion' IN ('2', '3') + AND participant->>'digestSchemaVersion' = CASE + binding_row.release_attestation_json::JSONB->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' ELSE NULL END + AND binding_row.release_attestation_json::JSONB->'worldStartLocationEvidence'->'request'->>'digestSchemaVersion' + = capture_row.freeze_request_json::JSONB->>'digestSchemaVersion'$replacement$; +BEGIN + SELECT pg_get_functiondef(preparation_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, anchor, ''))) + / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V40 World digest-3 participant guard'; + END IF; + EXECUTE replace(original_definition, anchor, replacement); +END; +$migration$; + +-- Keep preparation input schema 2 and all V1 retries exact. Its release selector pair is either +-- the retained attestation/2 + World/3 pair or new attestation/3 + World/4 pair. +DO $migration$ +DECLARE + selector_function REGPROCEDURE := + '"${serviceSchema}".world_require_preparation_start_location(jsonb,jsonb,uuid)'::REGPROCEDURE; + original_definition TEXT; + schema_anchor TEXT := $anchor$ IF input->>'schemaVersion' IS DISTINCT FROM '2' OR binding->>'schemaVersion' IS DISTINCT FROM '2' + OR input->>'worldStartLocationEvidenceBase64' IS NULL$anchor$; + schema_replacement TEXT := $replacement$ IF input->>'schemaVersion' IS DISTINCT FROM '2' + OR binding->>'schemaVersion' IS NULL + OR binding->>'schemaVersion' NOT IN ('2', '3') + OR input->>'worldStartLocationEvidenceBase64' IS NULL$replacement$; + digest_anchor TEXT := $anchor$ OR selected->>'digestSchemaVersion' IS DISTINCT FROM '3'$anchor$; + digest_replacement TEXT := $replacement$ OR selected->>'digestSchemaVersion' IS DISTINCT FROM CASE binding->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' ELSE NULL END$replacement$; +BEGIN + SELECT pg_get_functiondef(selector_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, schema_anchor, ''))) + / length(schema_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, digest_anchor, ''))) + / length(digest_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V42 selected World schema-3 selector guards'; + END IF; + original_definition := replace(original_definition, schema_anchor, schema_replacement); + original_definition := replace(original_definition, digest_anchor, digest_replacement); +EXECUTE original_definition; +END; +$migration$; + +-- The immutable operation/public projection accepts only legacy inventory/1 + World/3 or the +-- explicit closure inventory/2 + World/4 pair. It never promotes an absent declaration. +DO $migration$ +DECLARE + inventory_function REGPROCEDURE := + '"${serviceSchema}".require_selected_inventory_operation_v2(bytea)'::REGPROCEDURE; + original_definition TEXT; + anchor TEXT := $anchor$ IF inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$anchor$; + replacement TEXT := $replacement$ IF (( + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v1' + AND inventory->'schemaVersion' = '1'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + AND model->'graphSchemaVersion' = '2'::JSONB + AND checkpoint->'digestSchemaVersion' = '3'::JSONB + AND selector->'request'->'digestSchemaVersion' = '3'::JSONB + AND NOT (model ? 'inboundSourceClosure') + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 16) + OR + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1' + AND model->'graphSchemaVersion' = '3'::JSONB + AND checkpoint->'digestSchemaVersion' = '4'::JSONB + AND selector->'request'->'digestSchemaVersion' = '4'::JSONB + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 17 + AND model ?& ARRAY['modelId', 'graphSchemaVersion', 'graphDigest', + 'topologyResultDigest', 'familyCounts', 'regionGeneratorInputs', + 'generationRuleFields', 'regionFields', 'zoneFields', 'roomFields', + 'roomExitFields', 'spawnBindingFields', 'spawnBindingInputs', + 'generationRuleInputCount', 'spawnBindingCount', 'appliedEpochs', + 'inboundSourceClosure'] + AND model->'inboundSourceClosure' IS NOT DISTINCT FROM + '{"schemaVersion":1,"familyCounts":[{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING","count":0}]}'::JSONB) + ) IS NOT TRUE) OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$replacement$; + legacy_model_anchor TEXT := $anchor$ OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB$anchor$; + legacy_model_replacement TEXT := ''; +BEGIN + SELECT pg_get_functiondef(inventory_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, anchor, ''))) + / length(anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, legacy_model_anchor, ''))) + / length(legacy_model_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V56 selected inventory schema-1 profile guard'; + END IF; + original_definition := replace(original_definition, anchor, replacement); + -- Model id and graph version are validated as exact paired profiles above; retain the + -- generation-rule and artifact-decision restrictions below for both profiles. + original_definition := replace(original_definition, legacy_model_anchor, legacy_model_replacement); + EXECUTE original_definition; +END; +$migration$; + +-- Correlate the additive database discriminator with immutable bytes on the SQL owner path too. +DO $migration$ +DECLARE + operation_function REGPROCEDURE := + '"${serviceSchema}".world_require_publication_operation_account_binding(bytea,uuid,bytea)'::REGPROCEDURE; + original_definition TEXT; + declaration_anchor TEXT := $anchor$ public_inventory BYTEA; public_digest BYTEA; private_inventory JSONB; expected_public JSONB; model JSONB;$anchor$; + declaration_replacement TEXT := $replacement$ public_inventory BYTEA; public_digest BYTEA; private_inventory JSONB; expected_public JSONB; model JSONB; + inventory_schema_version SMALLINT;$replacement$; + select_anchor TEXT := $anchor$ SELECT convert_from(i.inventory_bytes, 'UTF8')::JSONB INTO STRICT private_inventory + FROM "${serviceSchema}".world_selected_publication_artifact_inventory i$anchor$; + select_replacement TEXT := $replacement$ SELECT i.inventory_schema_version, convert_from(i.inventory_bytes, 'UTF8')::JSONB + INTO STRICT inventory_schema_version, private_inventory + FROM "${serviceSchema}".world_selected_publication_artifact_inventory i$replacement$; + projection_anchor TEXT := $anchor$ IF jsonb_typeof(private_inventory) IS DISTINCT FROM 'object'$anchor$; + projection_replacement TEXT := $replacement$ IF private_inventory->'schemaVersion' IS DISTINCT FROM to_jsonb(inventory_schema_version) + OR jsonb_typeof(private_inventory) IS DISTINCT FROM 'object'$replacement$; +BEGIN + SELECT pg_get_functiondef(operation_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, declaration_anchor, ''))) + / length(declaration_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, select_anchor, ''))) + / length(select_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, projection_anchor, ''))) + / length(projection_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V56 World inventory discriminator/readback guards'; + END IF; + original_definition := replace(original_definition, declaration_anchor, declaration_replacement); + original_definition := replace(original_definition, select_anchor, select_replacement); + original_definition := replace(original_definition, projection_anchor, projection_replacement); + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java index 50dfc77c87..fdb64befaf 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredGraphSnapshotPostgresIntegrationTest.java @@ -55,6 +55,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionCommitPlan; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionGraphStager.UnverifiedStagedContent; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftRegionStagingService; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.InboundSourceClosureDeclaration; import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; @@ -914,13 +915,24 @@ void mismatchedReturnedPrivateVersionDigestCannotCreateSnapshot() { var capture = new WorldAuthoredGraphSnapshotCapture( dsl, - (tenant, version) -> - new WorldDraftDesignDigest( + new WorldDraftDesignDigestService() { + @Override + public WorldDraftDesignDigest getDraftDesignDigest(String tenant, String version) { + return new WorldDraftDesignDigest( tenant, Long.toString(fixture.localVersionKey() + 1), fixture.request().appliedCommitId(), fixture.request().contentDigest(), - 3), + 3); + } + + @Override + public WorldDraftDesignDigest getSelectedDraftDesignDigest( + String tenant, String version, InboundSourceClosureDeclaration closure) { + throw new AssertionError( + "Graph snapshot mismatch fixture must not request selected digest"); + } + }, snapshotRepository, objectMapper); assertThatThrownBy( @@ -1065,8 +1077,17 @@ void v32PreservesOriginalSchema2SnapshotBytesAndExactRetry() throws Exception { var capture = new WorldAuthoredGraphSnapshotCapture( retained, - (tenant, version) -> { - throw new AssertionError("Historical retry must never recompute content digest"); + new WorldDraftDesignDigestService() { + @Override + public WorldDraftDesignDigest getDraftDesignDigest(String tenant, String version) { + throw new AssertionError("Historical retry must never recompute content digest"); + } + + @Override + public WorldDraftDesignDigest getSelectedDraftDesignDigest( + String tenant, String version, InboundSourceClosureDeclaration closure) { + throw new AssertionError("Historical retry must never recompute content digest"); + } }, repo, objectMapper); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java index 6e42ab93c8..6ea98c44e2 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAccountAuthorizedDraftPostgresIntegrationTest.java @@ -90,6 +90,9 @@ import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceClosureDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.jooq.DSLContext; import org.jooq.exception.DataAccessException; @@ -1410,6 +1413,7 @@ private WorldDraftTopologyCommitPlan plan(Fixture f) { values, WorldDesignAggregateType .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) + .setInboundSourceClosure(emptyInboundClosure()) .build(); values.set(0, values.getFirst().toBuilder().setFreshGraphDeclaration(declaration).build()); List revisions = new ArrayList<>(); @@ -1477,6 +1481,33 @@ private WorldFreshGraphFamilyCount count( return WorldFreshGraphFamilyCount.newBuilder().setFamily(family).setCount(count).build(); } + private WorldInboundSourceClosureDeclaration emptyInboundClosure() { + return WorldInboundSourceClosureDeclaration.newBuilder() + .setSchemaVersion(1) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING)) + .build(); + } + + private WorldInboundSourceFamilyCount inboundCount(WorldInboundSourceFamily family) { + return WorldInboundSourceFamilyCount.newBuilder().setFamily(family).setCount(0).build(); + } + private WorldDesignMutationRevision.Builder mutation( UUID commit, UUID id, UUID scope, WorldDesignAggregateType type) { return WorldDesignMutationRevision.newBuilder() diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java index e57ad5895b..711ea658f7 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyPostgresIntegrationTest.java @@ -30,6 +30,8 @@ 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.service.WorldDraftDesignDigestService; +import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService.WorldDraftDesignDigest; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.CaptureRequest; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredGraphSnapshot.OwnedAffectedTuple; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalAuthoredGraph.Family; @@ -65,13 +67,18 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; /** - * Actual V30 rows and V31/V32 capture, with synthetic source/permission and computed schema-3 V25 - * content checkpoints. Selected commit identities remain synthetic complete-application evidence. - * Fixture-only trigger bypasses model terminal/corrupt storage unavailable through the current - * owner API; origin triggers are restored before every tested capture/read boundary. + * Synthetic retained schema-3 frozen-topology history and exact readback against actual V30 rows. + * These graph fixtures predate the explicit inbound closure and APPLIED source, so this suite does + * not qualify new selected capture. Positive schema-4 qualification belongs to the genuine + * graph-application integration fixture. Fixture-only trigger bypasses model terminal/corrupt + * storage unavailable through the current owner API; origin triggers are restored before every + * tested read boundary. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -81,6 +88,12 @@ class WorldCanonicalFrozenTopologyPostgresIntegrationTest { private static final String NAMESPACE = "firemud"; private static final long GAME_DESIGN_VERSION = 9_000_000_000_000_001L; + private static final ObjectMapper RETAINED_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -121,12 +134,12 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private EntityManagementClient entityManagementClient; @Test - void capturesActualSixFamilyGraphAndOriginalFullInputWithExactRetry() { + void retainedSyntheticSchema3SixFamilyGraphAndOriginalInputReplayWithoutQualification() { Fixture f = fixture(); var p = plan(f); var stored = component().store(p); - Request request = freeze(p); - var capture = frozen().capture(request); + Request request = freeze(p, 3); + var capture = seedRetainedLegacySchema3(request); assertThat(capture.status()).isEqualTo("CAPTURED_UNVERIFIED"); assertThat(capture.request().freeze().digestSchemaVersion()).isEqualTo(3); assertThat(capture.graphBytes()).containsExactly(stored.graphBytes()); @@ -187,21 +200,21 @@ void canonicalSpawnSqlMappingIsLosslessAndProducesSchema3DigestWithoutWriteBypas } @Test - void freshSchema2CaptureIsDeniedByApplicationAndDatabase() { + void freshLegacySchemaCaptureIsDeniedByApplicationAndDatabase() { Fixture f = fixture(); var p = plan(f); component().store(p); Request request = freeze(p, 2); assertThat(frozen().readCommitted(request)).isEmpty(); assertThatThrownBy(() -> frozen().capture(request)) - .hasMessageContaining("requires digest schema 3"); + .hasMessageContaining("requires selected digest schema 4"); assertThat(countCaptures(request)).isZero(); var templatePlan = plan(fixture()); component().store(templatePlan); - Request template = freeze(templatePlan); - // Supply a complete otherwise-valid insertion from an existing schema-3 journal. - frozen().capture(template); - for (int denied : new int[] {2, 4}) { + Request template = freeze(templatePlan, 3); + // This is retained-history fixture material, not a fresh selected-capture producer. + seedRetainedLegacySchema3(template); + for (int denied : new int[] {2, 3, 4}) { assertThatThrownBy( () -> dsl.execute( @@ -211,43 +224,24 @@ void freshSchema2CaptureIsDeniedByApplicationAndDatabase() { + "FROM world_canonical_frozen_topology t WHERE publication_fence=?", UUID.randomUUID(), "\"digestSchemaVersion\":" + denied, template.freeze().publicationFence())) - .hasStackTraceContaining("requires digest schema 3"); + .hasStackTraceContaining( + denied != 4 + ? "requires selected closure schema 4" + : "exact FROZEN source and checkpoint"); } assertOrigin(); } @Test - void newSchema3CaptureRejectsChangedContentDigestAndEveryReturnedScopeField() { + void newCaptureCannotPromoteUnqualifiedSyntheticGraphToSelectedClosureSchema4() { Fixture f = fixture(); var p = plan(f); component().store(p); Request request = freeze(p); - for (int changed = 0; changed < 4; changed++) { - int field = changed; - var bad = - frozen( - (tenant, version) -> - new net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService - .WorldDraftDesignDigest( - field == 0 ? "999999999" : tenant, - field == 1 ? "999999999" : version, - "version:" + version, - field == 2 ? "c".repeat(64) : request.freeze().contentDigest(), - field == 3 ? 2 : 3)); - assertThatThrownBy(() -> bad.capture(request)) - .hasMessageContaining("differs from exact schema-3 frozen content checkpoint"); - assertThat(countCaptures(request)).isZero(); - } - var captured = frozen().capture(request); - assertThat(captured.request().freeze().digestSchemaVersion()).isEqualTo(3); - assertThat( - frozen( - (tenant, version) -> { - throw new AssertionError("Exact retry must use retained journal"); - }) - .capture(request) - .resultBytes()) - .containsExactly(captured.resultBytes()); + assertThat(request.freeze().digestSchemaVersion()).isEqualTo(4); + assertThatThrownBy(() -> frozen().capture(request)) + .hasMessageContaining("requires its exact original inbound closure"); + assertThat(countCaptures(request)).isZero(); } @Test @@ -255,8 +249,8 @@ void changedCompleteBindingOrAnyFreezeCheckpointFieldCannotReplayCapture() { Fixture f = fixture(); var p = plan(f); component().store(p); - Request original = freeze(p); - frozen().capture(original); + Request original = freeze(p, 3); + seedRetainedLegacySchema3(original); var b = p.binding(); var changed = WorldDraftTopologyCommitPlan.create( @@ -313,8 +307,8 @@ void historicalReadAndExactRetryAfterEveryTerminalPhaseUseOnlyOriginalJournal() Fixture f = fixture(); var p = plan(f); component().store(p); - Request request = freeze(p); - byte[] original = frozen().capture(request).resultBytes(); + Request request = freeze(p, 3); + byte[] original = seedRetainedLegacySchema3(request).resultBytes(); bypass( "UPDATE world_design_publication_fence_owner SET owner_freeze_phase=? WHERE local_tenant_key=?", phase, @@ -593,8 +587,8 @@ void immutableJournalDeniesWritesAndHistoricalReadRejectsEveryTamperedField() { Fixture f = fixture(); var p = plan(f); component().store(p); - Request request = freeze(p); - frozen().capture(request); + Request request = freeze(p, 3); + seedRetainedLegacySchema3(request); String set = mutation.getValue(); if (set == null) { String originalDigest = request.freeze().contentDigest(); @@ -657,8 +651,8 @@ void recomputedGraphChecksumCannotHideTypedEndpointOrCanonicalEntityTampering() Fixture f = fixture(); var p = plan(f); component().store(p); - Request request = freeze(p); - var captured = frozen().capture(request); + Request request = freeze(p, 3); + var captured = seedRetainedLegacySchema3(request); String graph = new String(captured.graphBytes(), StandardCharsets.UTF_8); String bad = replacement.startsWith("\"to_room_id\"") @@ -681,7 +675,8 @@ void twoConcurrentCapturesReturnOneOriginalImmutableResult() throws Exception { Fixture f = fixture(); var p = plan(f); component().store(p); - Request request = freeze(p); + Request request = freeze(p, 3); + seedRetainedLegacySchema3(request); CountDownLatch start = new CountDownLatch(1); try (var pool = Executors.newFixedThreadPool(2)) { var first = @@ -721,8 +716,8 @@ void v32PreservesOriginalSchema2FrozenJournalAndExactHistoricalRetries() throws Fixture f = fixture(); var p = plan(f); component().store(p); - Request current = freeze(p); - var captured = frozen().capture(current); + Request current = freeze(p, 3); + var captured = seedRetainedLegacySchema3(current); CaptureRequest r = current.freeze(); Request historical = new Request( @@ -831,8 +826,19 @@ void v32PreservesOriginalSchema2FrozenJournalAndExactHistoricalRetries() throws new WorldDesignPublicationFenceRepository( retained, new WorldAuthoredSourceIntakeRepository(retained)), mapper), - (tenant, version) -> { - throw new AssertionError("Historical retry must never recompute content"); + new WorldDraftDesignDigestService() { + @Override + public WorldDraftDesignDigest getDraftDesignDigest(String tenant, String version) { + throw new AssertionError("Historical retry must never recompute content"); + } + + @Override + public WorldDraftDesignDigest getSelectedDraftDesignDigest( + String tenant, + String version, + WorldDraftTopologyInputGraph.InboundSourceClosureDeclaration closure) { + throw new AssertionError("Historical retry must never recompute content"); + } }); var service = new WorldCanonicalFrozenTopologyService(repo, manager); assertThat(service.readCommitted(historical).orElseThrow().resultBytes()) @@ -847,8 +853,89 @@ retained, new WorldAuthoredSourceIntakeRepository(retained)), } } + /** + * Installs a structurally exact schema-3 journal row as retained history for compatibility tests. + * The synthetic graph has no inbound declaration or APPLIED application result; it must never be + * used to demonstrate a fresh selected capture. Repository readback verifies the exact owner, + * fence, checkpoint, commit bytes, and immutable source. The fixture bypasses current insert + * guards only because schema 3 is retained data now; current fresh inserts require selected + * schema 4. + */ + private WorldCanonicalFrozenTopology seedRetainedLegacySchema3(Request request) { + if (request.freeze().digestSchemaVersion() != 3) { + throw new IllegalArgumentException("Retained legacy fixture requires exact schema 3"); + } + var original = + dsl.resultQuery( + "SELECT to_jsonb(v)::text AS identity_json, to_jsonb(i)::text AS intake_json, " + + "c.owner_binding_json, c.graph_bytes, c.graph_sha256, c.result_bytes " + + "FROM world_authored_version_identity v " + + "JOIN world_authored_source_intake i ON i.operation_id=v.intake_operation_id " + + "JOIN world_topology_draft_commit c ON c.version_identity_operation_id=v.operation_id " + + "WHERE v.operation_id=? AND c.request_id=? AND c.commit_id=?", + request.plan().ownerBinding().versionIdentityOperationId(), + request.plan().binding().requestId(), + request.plan().binding().commitId()) + .fetchOne(); + if (original == null) { + throw new AssertionError("Expected exact original rows for the retained schema-3 fixture"); + } + String identityJson = Objects.requireNonNull(original.get("identity_json", String.class)); + String intakeJson = Objects.requireNonNull(original.get("intake_json", String.class)); + String ownerBindingJson = + Objects.requireNonNull(original.get("owner_binding_json", String.class)); + byte[] graphBytes = Objects.requireNonNull(original.get("graph_bytes", byte[].class)); + String graphSha256 = Objects.requireNonNull(original.get("graph_sha256", String.class)); + byte[] storageResultBytes = Objects.requireNonNull(original.get("result_bytes", byte[].class)); + UUID captureId = UUID.randomUUID(); + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", "1"); + result.put("status", WorldCanonicalFrozenTopology.STATUS); + result.put( + "missingProof", + List.of( + "ACCOUNT_AUTHORIZATION", + "COMPLETE_PARTICIPANT_COMMIT", + "PUBLICATION_CHECKPOINT_DIGEST")); + result.put("captureId", captureId.toString()); + result.put("freeze", request.freeze()); + result.put("ownerBinding", request.plan().ownerBinding()); + result.put("bindingJson", request.plan().binding().canonicalJson()); + result.put("bindingDigest", request.plan().binding().digest()); + result.put("identityJson", identityJson); + result.put("intakeJson", intakeJson); + result.put("graphBytes", graphBytes); + result.put("storageResultBytes", storageResultBytes); + byte[] resultBytes = RETAINED_JSON.writeValueAsBytes(result); + + bypass( + "INSERT INTO world_canonical_frozen_topology (capture_id,publication_fence,request_id," + + "commit_id,version_identity_operation_id,freeze_request_json,owner_binding_json," + + "binding_json,binding_digest,identity_json,intake_json,graph_bytes,graph_sha256," + + "storage_result_bytes,result_bytes,capture_status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + captureId, + request.freeze().publicationFence(), + request.plan().binding().requestId(), + request.plan().binding().commitId(), + request.plan().ownerBinding().versionIdentityOperationId(), + RETAINED_JSON.writeValueAsString(request.freeze()), + ownerBindingJson, + request.plan().binding().canonicalJson(), + request.plan().binding().digest(), + identityJson, + intakeJson, + graphBytes, + graphSha256, + storageResultBytes, + resultBytes, + WorldCanonicalFrozenTopology.STATUS); + return frozen() + .readCommitted(request) + .orElseThrow(() -> new AssertionError("Retained schema-3 fixture did not read back")); + } + private Request freeze(WorldDraftTopologyCommitPlan p) { - return freeze(p, 3); + return freeze(p, 4); } private Request freeze(WorldDraftTopologyCommitPlan p, int schema) { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index 0a247441f9..faf7bde733 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -68,6 +68,9 @@ import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceClosureDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -1855,6 +1858,7 @@ private WorldDraftTopologyCommitPlan topologyPlan(Fixture fixture) { mutations, WorldDesignAggregateType .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) + .setInboundSourceClosure(emptyInboundClosure()) .build(); mutations.set( 0, mutations.getFirst().toBuilder().setFreshGraphDeclaration(declaration).build()); @@ -1947,6 +1951,33 @@ private static WorldFreshGraphFamilyCount familyCount( return WorldFreshGraphFamilyCount.newBuilder().setFamily(family).setCount(count).build(); } + private static WorldInboundSourceClosureDeclaration emptyInboundClosure() { + return WorldInboundSourceClosureDeclaration.newBuilder() + .setSchemaVersion(1) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING)) + .build(); + } + + private static WorldInboundSourceFamilyCount inboundCount(WorldInboundSourceFamily family) { + return WorldInboundSourceFamilyCount.newBuilder().setFamily(family).setCount(0).build(); + } + private static WorldDesignMutationRevision.Builder mutation( UUID commit, UUID aggregateId, WorldDesignAggregateType type, UUID containingRegionId) { return WorldDesignMutationRevision.newBuilder() diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 789c6a907d..bdbca14d76 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -122,6 +122,9 @@ import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceClosureDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount; import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.flywaydb.core.Flyway; @@ -5694,12 +5697,28 @@ void publishedSpawnRequirementsOwnerPreservesExplicitZeroOptionalFamilies() { } @Test - void permissionUnverifiedGraphAndFrozenHistoryCannotSupplyPublishedSelector() { + void retainedFrozenHistoryCannotSupplyPublishedSelectorAfterAppliedSourceIsMissing() { var plan = plan(fixture()); - component().store(plan); - var capture = capture(plan); + var application = application(plan); + appliedComponent().apply(application); + var capture = capture(application.plan()); + var request = capture.request().freeze(); assertThat(frozenRepository().readCommitted(capture.request().freeze())).isPresent(); - assertThatThrownBy(() -> publishedSelectors().readCommitted(capture.request().freeze())) + ownerTransaction() + .execute( + status -> { + dsl.execute("SET LOCAL session_replication_role='replica'"); + try { + dsl.execute( + "DELETE FROM world_draft_graph_application WHERE request_id=? AND commit_id=?", + application.plan().binding().requestId(), + application.plan().binding().commitId()); + } finally { + dsl.execute("SET LOCAL session_replication_role='origin'"); + } + return null; + }); + assertThatThrownBy(() -> publishedSelectors().readCommitted(request)) .hasMessageContaining("lacks original APPLIED application"); TransactionTemplate ownedSnapshot = new TransactionTemplate(manager); ownedSnapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); @@ -5707,8 +5726,7 @@ void permissionUnverifiedGraphAndFrozenHistoryCannotSupplyPublishedSelector() { ownedSnapshot.setReadOnly(true); assertThatThrownBy( () -> - ownedSnapshot.execute( - status -> publishedSelectors().readInOwnedSnapshot(capture.request().freeze()))) + ownedSnapshot.execute(status -> publishedSelectors().readInOwnedSnapshot(request))) .hasMessageContaining("lacks original APPLIED application"); assertOrigin(); } @@ -5768,7 +5786,20 @@ private WorldPublishedStartLocationRepository publishedSelectors() { private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) { String publicationRequest = "selector-" + UUID.randomUUID(); var selection = publicationSelection(plan, publicationRequest, 1L); - return capture(plan, publicationRequest, selection, null); + Record applied = + dsl.fetchOne( + "SELECT account_binding_bytes FROM world_draft_graph_application " + + "WHERE request_id=? AND commit_id=?", + plan.binding().requestId(), + plan.binding().commitId()); + if (applied == null) { + throw new IllegalStateException( + "Selected World capture fixture requires the exact original APPLIED Account binding"); + } + var accountBinding = + isolatedPublicationAccountBinding( + applied.get("account_binding_bytes", byte[].class), selection, publicationRequest); + return capture(plan, publicationRequest, selection, accountBinding); } private WorldCanonicalFrozenTopology captureForTerminal( @@ -5889,6 +5920,12 @@ void freshApplicationRetainsCompleteExactGraphAndOriginalAccountReadbackAndRetri var application = application(f); var result = appliedComponent().apply(application); assertThat(result.status()).isEqualTo("APPLIED"); + var retainedGraph = + new WorldCanonicalAuthoredGraphReader().read(application.plan(), result.graphBytes()); + assertThat(retainedGraph.inboundSourceClosure()).isPresent(); + assertThat(retainedGraph.inboundSourceClosure().orElseThrow().familyCounts()) + .extracting(WorldDraftTopologyInputGraph.InboundSourceFamilyCount::count) + .containsExactly(0, 0, 0, 0, 0, 0, 0); assertThat(result.appliedEpochs()) .hasSize(application.operation().binding().affectedUnits(Owner.WORLD_MANAGEMENT).size()); assertThat(result.appliedEpochs()) @@ -5999,7 +6036,8 @@ void newAccountBoundGraphRequiresCompleteOriginalDeclaration() { var application = application(historicalPlan); assertThatThrownBy(() -> appliedComponent().apply(application)) - .hasMessageContaining("require the complete original fresh-graph declaration"); + .hasMessageContaining( + "require the original versioned selected-inbound closure declaration"); for (String table : List.of( "region", @@ -6016,6 +6054,29 @@ void newAccountBoundGraphRequiresCompleteOriginalDeclaration() { } } + @Test + void newAccountBoundGraphRequiresExplicitInboundClosureAndDoesNotInferEmptyFromOmission() { + Fixture f = fixture(); + var missingClosure = withoutInboundSourceClosure(plan(f)); + var application = application(missingClosure); + + assertThat(missingClosure.graph().freshGraphDeclaration().orElseThrow().inboundSourceClosure()) + .isEmpty(); + assertThatThrownBy(() -> appliedComponent().apply(application)) + .hasMessageContaining( + "require the original versioned selected-inbound closure declaration"); + for (String table : + List.of( + "region", + "zone", + "room", + "world_authored_topology_identity", + "world_topology_draft_commit", + "world_draft_graph_application")) { + assertThat(count(f, table)).isZero(); + } + } + @Test void authenticatedReceiverReadsGenuineCommittedReceiptAndReplaysAfterFreeze() { Fixture f = fixture(); @@ -6289,6 +6350,8 @@ void v39AppliedV1HistoryRemainsByteExactAndRetryableAfterV41() throws Exception WorldAuthoredSourceIntakeRepository retainedIntake = proxiedIntakeRepository(retainedDsl, retainedManager); Fixture f = fixture(retainedIntake, retainedManager, retainedDsl); + // Reconstruct the pre-closure graph/2 input explicitly; the shared current plan factory emits + // graph/3 only after its original fresh-graph declaration is retained. WorldDraftTopologyCommitPlan historicalPlan = withoutFreshGraphDeclaration(plan(f)); WorldDraftGraphApplication historicalApplication = application(historicalPlan); TransactionTemplate retainedTransaction = ownerTransaction(retainedManager); @@ -6904,6 +6967,61 @@ private WorldDraftTopologyCommitPlan withoutFreshGraphDeclaration( return WorldDraftTopologyCommitPlan.create(historicalBinding, original.ownerBinding()); } + private WorldDraftTopologyCommitPlan withoutInboundSourceClosure( + WorldDraftTopologyCommitPlan original) { + List revisions = new ArrayList<>(); + boolean clearedOriginalDeclaration = false; + for (var revision : original.binding().revisions()) { + if (revision.owner() != Owner.WORLD_MANAGEMENT) { + revisions.add(revision); + continue; + } + try { + var mutation = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(revision.payload(), mutation); + if (!mutation.hasFreshGraphDeclaration()) { + revisions.add(revision); + continue; + } + if (clearedOriginalDeclaration) { + throw new IllegalArgumentException( + "Missing-closure fixture requires one original World graph declaration"); + } + revisions.add( + new DraftCommitBinding.RevisionPayload( + revision.revisionOrder(), + revision.revisionId(), + revision.owner(), + JsonFormat.printer() + .omittingInsignificantWhitespace() + .print( + mutation + .setFreshGraphDeclaration( + mutation.getFreshGraphDeclaration().toBuilder() + .clearInboundSourceClosure() + .build()) + .build()))); + clearedOriginalDeclaration = true; + } catch (InvalidProtocolBufferException exception) { + throw new IllegalStateException(exception); + } + } + if (!clearedOriginalDeclaration) { + throw new IllegalArgumentException( + "Missing-closure fixture requires one original World graph declaration"); + } + var binding = original.binding(); + return WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + revisions, + binding.affectedUnits()), + original.ownerBinding()); + } + private Map retainedV39ApplicationBytes( DSLContext retained, WorldDraftGraphApplication application) { var operation = application.operation(); @@ -7286,6 +7404,7 @@ private WorldDraftTopologyCommitPlan plan( values, WorldDesignAggregateType .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) + .setInboundSourceClosure(emptyInboundClosure()) .build(); values.set(0, values.getFirst().toBuilder().setFreshGraphDeclaration(declaration).build()); List revisions = new ArrayList<>(); @@ -7367,6 +7486,33 @@ private WorldFreshGraphFamilyCount count( return WorldFreshGraphFamilyCount.newBuilder().setFamily(family).setCount(count).build(); } + private WorldInboundSourceClosureDeclaration emptyInboundClosure() { + return WorldInboundSourceClosureDeclaration.newBuilder() + .setSchemaVersion(1) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING)) + .build(); + } + + private WorldInboundSourceFamilyCount inboundCount(WorldInboundSourceFamily family) { + return WorldInboundSourceFamilyCount.newBuilder().setFamily(family).setCount(0).build(); + } + private WorldDesignMutationRevision.Builder mutation( UUID commit, UUID id, UUID scope, WorldDesignAggregateType type) { return WorldDesignMutationRevision.newBuilder() diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java index 3521d71571..f810ca21fa 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java @@ -389,7 +389,8 @@ private static DraftCommitBinding freshGraphBinding() throws Exception { "family", "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", "count", - 0)))); + 0)), + "inboundSourceClosure", inboundSourceClosure())); UUID regionRevision = uuid("12345678-1234-4234-8234-123456789001"); UUID zoneRevision = uuid("12345678-1234-4234-8234-123456789002"); UUID roomRevision = uuid("12345678-1234-4234-8234-123456789003"); @@ -458,6 +459,25 @@ private static String worldRevisionPayload( return json.writeValueAsString(payload); } + private static Map inboundSourceClosure() { + return Map.of( + "schemaVersion", + 1, + "familyCounts", + List.of( + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING"))); + } + + private static Map inboundFamily(String family) { + return Map.of("family", family, "count", 0); + } + private static List affected( String family, UUID templateId, String scopeType, UUID scopeId) { return List.of( @@ -590,13 +610,18 @@ private static DraftAuthorizationFenceBinding.OwnerReadback committedFreshGraphR private static byte[] graphBytes( WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { var root = new LinkedHashMap(); - root.put("schemaVersion", "2"); + root.put("schemaVersion", "3"); root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); var rows = new ArrayList>(); int mappingId = 1; long privateRowKey = 101; var json = JsonMapper.builder().build(); + root.put( + "inboundSourceClosure", + json.readTree(draft.revisions().getFirst().payload()) + .get("freshGraphDeclaration") + .get("inboundSourceClosure")); for (RevisionPayload revision : draft.revisions()) { if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; JsonNode mutation = json.readTree(revision.payload()); diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java index b4d206d8a1..1b47dcbb07 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java @@ -226,6 +226,104 @@ void publicProjectionSortsTypedInputKeysWithoutRewritingRetainedPrivateEnvelope( assertThat(inventory.canonicalBytes()).containsExactly(storedBytes); } + @Test + void closureProfileRetainsExplicitSourceAndRequiresSelectedDigestSchema4() { + var envelope = envelopeWithInboundClosure(); + var inventory = + new WorldSelectedPublicationArtifactInventory( + envelope, WorldSelectedPublicationArtifactInventory.encode(envelope)); + + assertThat(inventory.envelope().schema()) + .isEqualTo(WorldSelectedPublicationArtifactInventory.INBOUND_CLOSURE_SCHEMA); + assertThat(inventory.envelope().sourceModel().inboundSourceClosure().familyCounts()) + .extracting( + WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount::count) + .containsExactly(0, 0, 0, 0, 0, 0, 0); + assertThat(inventory.publicEvidence().checkpoint().digestSchemaVersion()).isEqualTo(4); + assertThat(new String(inventory.publicCanonicalBytes(), StandardCharsets.UTF_8)) + .contains( + "world-selected-publication-artifact-inventory/v2", + "WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1", + "inboundSourceClosure"); + + var wrongCheckpoint = + new WorldSelectedPublicationArtifactInventory.Envelope( + envelope.schema(), + envelope.schemaVersion(), + envelope.completeness(), + envelope.ownerScope(), + envelope.sourceIntake(), + envelope.selectedApplication(), + envelope.accountOrder(), + envelope.freeze(), + new WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint( + envelope.checkpoint().appliedCommitId(), envelope.checkpoint().contentDigest(), 3), + envelope.sourceModel(), + envelope.artifactDecisions()); + assertThatThrownBy( + () -> + new WorldSelectedPublicationArtifactInventory( + wrongCheckpoint, + WorldSelectedPublicationArtifactInventory.encode(wrongCheckpoint)) + .publicEvidence()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("participant digest schema"); + } + + private static WorldSelectedPublicationArtifactInventory.Envelope envelopeWithInboundClosure() { + var prior = envelopeWithReversePublicInputOrder(); + var model = prior.sourceModel(); + var closure = + new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration( + 1, + List.of( + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE"), + inboundFamily("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING"))); + var source = + new WorldSelectedPublicationArtifactInventoryEvidence.SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + model.graphDigest(), + model.topologyResultDigest(), + model.familyCounts(), + model.regionGeneratorInputs(), + model.generationRuleFields(), + model.regionFields(), + model.zoneFields(), + model.roomFields(), + model.roomExitFields(), + model.spawnBindingFields(), + model.spawnBindingInputs(), + model.generationRuleInputCount(), + model.spawnBindingCount(), + model.appliedEpochs(), + closure); + return new WorldSelectedPublicationArtifactInventory.Envelope( + WorldSelectedPublicationArtifactInventory.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + prior.completeness(), + prior.ownerScope(), + prior.sourceIntake(), + prior.selectedApplication(), + prior.accountOrder(), + prior.freeze(), + new WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint( + prior.checkpoint().appliedCommitId(), prior.checkpoint().contentDigest(), 4), + source, + prior.artifactDecisions()); + } + + private static WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount + inboundFamily(String family) { + return new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount( + family, 0); + } + private static WorldSelectedPublicationArtifactInventory.Envelope envelopeWithReversePublicInputOrder() { var sourceModel = diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java index ec02a0e2bb..cd4dddde4a 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java @@ -16,6 +16,10 @@ import net.firedevops.firemud.worldmanagement.repository.RoomRepository; import net.firedevops.firemud.worldmanagement.repository.WorldEntitySpawnBindingRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.InboundSourceClosureDeclaration; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph.InboundSourceFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import tools.jackson.databind.ObjectMapper; @@ -125,6 +129,45 @@ void computesDigestFromVersionScopedTemplateRows() { Mockito.verify(regionRepository, Mockito.never()).findByTenantIdOrderByIdAsc(Mockito.anyLong()); } + @Test + void selectedDigestSchema4BindsTheExactExplicitInboundClosureWithoutChangingGenericSchema3() + throws Exception { + var service = emptyDigestService(); + + var generic = service.getDraftDesignDigest("1", "7"); + var selected = service.getSelectedDraftDesignDigest("1", "7", emptyInboundClosure()); + + assertEquals(3, generic.digestSchemaVersion()); + assertEquals(4, selected.digestSchemaVersion()); + assertEquals(selectedEmptyDigestVector(), selected.contentDigest()); + org.junit.jupiter.api.Assertions.assertNotEquals( + generic.contentDigest(), selected.contentDigest()); + } + + @Test + void selectedDigestRejectsNonemptyUnknownAndUnorderedInboundClosure() { + var service = emptyDigestService(); + var empty = emptyInboundClosure(); + var families = new java.util.ArrayList<>(empty.familyCounts()); + var nonempty = new java.util.ArrayList<>(families); + nonempty.set(0, new InboundSourceFamilyCount(nonempty.getFirst().family(), 1)); + var unknown = new java.util.ArrayList<>(families); + unknown.set( + 0, + new InboundSourceFamilyCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_UNSPECIFIED, 0)); + var unordered = new java.util.ArrayList<>(families); + java.util.Collections.swap(unordered, 0, 1); + + for (var counts : List.of(nonempty, unknown, unordered)) { + assertThrows( + IllegalArgumentException.class, + () -> + service.getSelectedDraftDesignDigest( + "1", "7", new InboundSourceClosureDeclaration(1, counts))); + } + } + @Test void canonicalEntityReferenceMatchesExactSortedSerializationVector() throws Exception { WorldEntitySpawnBinding binding = binding(); @@ -208,6 +251,54 @@ private String digest(WorldEntitySpawnBinding binding) { return digest(binding, new ObjectMapper()); } + private WorldDraftDesignDigestServiceImpl emptyDigestService() { + var regions = Mockito.mock(RegionRepository.class); + var zones = Mockito.mock(ZoneRepository.class); + var rooms = Mockito.mock(RoomRepository.class); + var exits = Mockito.mock(RoomExitRepository.class); + var rules = Mockito.mock(GenerationRuleRepository.class); + var spawns = Mockito.mock(WorldEntitySpawnBindingRepository.class); + Mockito.when(regions.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)).thenReturn(List.of()); + Mockito.when(zones.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)).thenReturn(List.of()); + Mockito.when(rooms.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)).thenReturn(List.of()); + Mockito.when(exits.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)).thenReturn(List.of()); + Mockito.when(rules.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)).thenReturn(List.of()); + Mockito.when(spawns.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)).thenReturn(List.of()); + return new WorldDraftDesignDigestServiceImpl( + regions, zones, rooms, exits, rules, spawns, new ObjectMapper()); + } + + private InboundSourceClosureDeclaration emptyInboundClosure() { + return new InboundSourceClosureDeclaration( + 1, + WorldDraftTopologyInputGraph.INBOUND_SOURCE_FAMILY_ORDER.stream() + .map(family -> new InboundSourceFamilyCount(family, 0)) + .toList()); + } + + private String digestJson(String json) throws Exception { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(json.getBytes(StandardCharsets.UTF_8))); + } + + private String selectedEmptyDigestVector() throws Exception { + String familyCounts = + "{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT\",\"count\":0}," + + "{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT\",\"count\":0}," + + "{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION\",\"count\":0}," + + "{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING\",\"count\":0}," + + "{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK\",\"count\":0}," + + "{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE\",\"count\":0}," + + "{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING\",\"count\":0}"; + return digestJson( + "{\"regions\":[],\"zones\":[],\"rooms\":[],\"roomExits\":[]," + + "\"generationRules\":[],\"worldEntitySpawnBindings\":[]," + + "\"inboundSourceClosure\":{\"schemaVersion\":1,\"familyCounts\":[" + + familyCounts + + "]}}"); + } + private String digest(WorldEntitySpawnBinding binding, ObjectMapper mapper) { var spawns = Mockito.mock(WorldEntitySpawnBindingRepository.class); Mockito.when(spawns.findByTenantIdAndVersionIdOrderByIdAsc(1L, 7L)) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java index 15bbf0f2e0..c4d143f1d9 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java @@ -13,10 +13,10 @@ class WorldAuthoredGraphSnapshotTest { private static final String DIGEST = "a".repeat(64); @Test - void acceptsRetainedSchema2AndCurrentSchema3ButRejectsUnsupportedSchemas() { - for (int schema : new int[] {2, 3}) + void acceptsRetainedSchemas2And3AndSelectedSchema4ButRejectsUnsupportedSchemas() { + for (int schema : new int[] {2, 3, 4}) assertThat(request(schema).digestSchemaVersion()).isEqualTo(schema); - for (int schema : new int[] {0, 1, 4}) { + for (int schema : new int[] {0, 1, 5}) { assertThatThrownBy(() -> request(schema)).isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java index 9fe9669457..acb2b19a45 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java @@ -193,7 +193,7 @@ void rejectsLegacyReleaseWithoutStoredTypedWorldSelectorBeforeRemoteReads() { assertThatThrownBy(() -> service.assemble(selector)) .isInstanceOf( WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) - .hasMessageContaining("stored v2 release selector"); + .hasMessageContaining("stored selected release selector"); verifyNoInteractions(versionIdentities, frozenTopologies, gameSession, gameDesign); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java index 9a8c7b41a7..cd587cd7a8 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java @@ -192,7 +192,7 @@ void committedLaunchRejectsChangedDigestAndV1ReleaseBeforeWorldOwnerWrite() { var v1Request = committedAssociationRequest(v1Binding); assertThatThrownBy(() -> withGameSession(() -> committedService.bindCommittedLaunch(v1Request))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) - .hasMessageContaining("release attestation v2"); + .hasMessageContaining("full selected-release selector evidence"); verify(gameSessionClient, never()).read(any()); verifyNoInteractions(repository, sourceRepository); verify(repository, never()).acceptFresh(any(), any(), any()); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java index 36990573da..a5a7278027 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java @@ -30,6 +30,9 @@ import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; import net.firedevops.firemud.worldmanagement.v1.WorldGenerationSubtreeDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceClosureDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.junit.jupiter.api.Test; @@ -134,6 +137,11 @@ void completeDeclarationPreservesTypedStartRoomAndExplicitZeroOptionalFamilies() assertThat(declaration.familyCounts()) .extracting(WorldDraftTopologyInputGraph.FamilyCount::count) .containsExactly(1, 1, 1, 0, 0, 0); + assertThat(declaration.inboundSourceClosure()).isPresent(); + assertThat(declaration.inboundSourceClosure().orElseThrow().schemaVersion()).isEqualTo(1); + assertThat(declaration.inboundSourceClosure().orElseThrow().familyCounts()) + .extracting(WorldDraftTopologyInputGraph.InboundSourceFamilyCount::count) + .containsExactly(0, 0, 0, 0, 0, 0, 0); assertThat(plan.graph().nodes()) .extracting(node -> node.mutation().getAggregateType()) .containsExactly( @@ -142,6 +150,50 @@ void completeDeclarationPreservesTypedStartRoomAndExplicitZeroOptionalFamilies() WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM); } + @Test + void missingInboundDeclarationNeverQualifiesEmptyAndNonemptyOrUnknownFamiliesAreRejected() { + DraftCommitBinding original = binding(new ArrayList<>(fresh().subList(0, 3))); + var legacyWithoutClosure = + WorldDraftTopologyCommitPlan.create( + changeDeclaration( + original, WorldFreshGraphDeclaration.Builder::clearInboundSourceClosure), + owner()); + assertThat( + legacyWithoutClosure + .graph() + .freshGraphDeclaration() + .orElseThrow() + .inboundSourceClosure()) + .isEmpty(); + + rejected( + changeDeclaration( + original, + declaration -> + declaration.setInboundSourceClosure( + declaration.getInboundSourceClosure().toBuilder() + .setFamilyCounts( + 0, + declaration.getInboundSourceClosure().getFamilyCounts(0).toBuilder() + .setCount(1) + .build()) + .build()))); + rejected( + changeDeclaration( + original, + declaration -> + declaration.setInboundSourceClosure( + declaration.getInboundSourceClosure().toBuilder() + .setFamilyCounts( + 0, + declaration.getInboundSourceClosure().getFamilyCounts(0).toBuilder() + .setFamily( + WorldInboundSourceFamily + .WORLD_INBOUND_SOURCE_FAMILY_UNSPECIFIED) + .build()) + .build()))); + } + @Test void rejectsAbsentZeroCountDuplicateDeclarationAndChangedSelectorIdentity() { List mutations = new ArrayList<>(fresh().subList(0, 3)); @@ -746,9 +798,37 @@ private static WorldFreshGraphDeclaration declaration( count( mutations, WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) + .setInboundSourceClosure(inboundSourceClosure()) .build(); } + private static WorldInboundSourceClosureDeclaration inboundSourceClosure() { + return WorldInboundSourceClosureDeclaration.newBuilder() + .setSchemaVersion(1) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING)) + .addFamilyCounts( + inboundCount(WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE)) + .addFamilyCounts( + inboundCount( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING)) + .build(); + } + + private static WorldInboundSourceFamilyCount inboundCount(WorldInboundSourceFamily family) { + return WorldInboundSourceFamilyCount.newBuilder().setFamily(family).setCount(0).build(); + } + private static WorldFreshGraphFamilyCount count( List mutations, WorldDesignAggregateType family) { int count = diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java index 9accb19a81..12636544c6 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java @@ -166,7 +166,7 @@ void changedReleaseAttestationDigestFailsBeforeWorldRead() { when(release.targetNamespace()).thenReturn(NAMESPACE); when(release.evidenceDigest()).thenReturn("sha256:" + "f".repeat(64)); when(release.schemaVersion()) - .thenReturn(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + .thenReturn(AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION); when(release.worldStartLocationEvidence()) .thenReturn(mock(WorldPublishedStartLocationEvidence.class)); try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { @@ -197,7 +197,7 @@ void malformedFrozenSourceFailsClosedAfterTheOwnedRead() { when(release.targetNamespace()).thenReturn(NAMESPACE); when(release.evidenceDigest()).thenReturn(wire.getExpectedReleaseAttestationDigest()); when(release.schemaVersion()) - .thenReturn(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + .thenReturn(AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION); when(release.worldStartLocationEvidence()).thenReturn(selector); var source = mock(WorldPublishedStartLocationSource.class); @@ -429,7 +429,7 @@ private static WorldPublishedStartLocationEvidence.Request selectorRequest() { "workflow", uuid(6).toString(), "e".repeat(64), - 3, + 4, List.of()); } From 4505ec9940d9bb66f6ef36799c24a94bebfa709d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:02:22 +1300 Subject: [PATCH 059/129] Fence original World execution and repair selected closure SQL profiles --- ...dmin-as-external-operator-write-ingress.md | 2 +- .../world-management-service/api-contracts.md | 1 + .../runtime-and-data.md | 8 + ...ame-authoring-publishing-and-activation.md | 4 + ...70__selected_inventory_closure_profile.sql | 66 ++ ...leaseCanonicalIdentityIntegrationTest.java | 2 +- ...emptServiceTransactionIntegrationTest.java | 30 +- ...rldCanonicalInstanceExecutionIdentity.java | 207 +++++ ...anonicalInstancePreparationRepository.java | 432 ++++++++- ...ldCanonicalInstancePreparationService.java | 23 +- ..._world_selected_closure_schema4_guards.sql | 6 +- ...start_session_execution_terminal_fence.sql | 817 ++++++++++++++++++ ...nceAssociationPostgresIntegrationTest.java | 771 ++++++++++++++++- ...anonicalInstanceExecutionTestFixtures.java | 156 ++++ ...ncePreparationPostgresIntegrationTest.java | 10 +- ...aphApplicationPostgresIntegrationTest.java | 133 ++- 16 files changed, 2596 insertions(+), 72 deletions(-) create mode 100644 services/game-design-service/src/main/resources/db/migration/V70__selected_inventory_closure_profile.sql create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentity.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V62__world_start_session_execution_terminal_fence.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index c6108f138f..2f8e0ec2b5 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -107,7 +107,7 @@ Acquisition of the World participation and each fresh World execution admission World owns a durable operation row and a separate monotonic execution fence that serialize execution admission, abort, and terminal outcome for this exact tuple, source association, participation ID/fence, and canonical target. The World execution fence is distinct from the Account issuance fence, source-participation fence, reservation claim fence, and membership version. Account and Game Design network calls and all other network work occur outside World SQL. World obtains authenticated Account admission evidence before SQL, then admits the exact operation under its durable row and checks the source, participation, original owner claim, authorization, and all validity bounds at that admission point inside one uninterrupted atomic SQL transaction. Unavailable, stale, mismatched, or uncertain evidence denies admission. Once admitted while the original participation, owner claim, authorization, and all validity bounds are current, the transaction may finish after the original token or reference expires; this contract does not require physical `COMMIT` before ingress expiry. World must also enforce a bounded operational transaction timeout and cancellation mechanism, with its duration selected by implementation/runtime policy rather than this ADR. Cancellation or timeout is not terminal proof until the World row and database outcome serialize to show that no transaction remains in flight and no later commit can occur. -Expiry forbids dispatch of a new owner attempt, opening or restarting the World SQL transaction, reacquiring or renewing participation, renewing or reissuing the reference, or re-redeeming it. After a crash or unknown outcome following expiry, World may perform only an exact read-only lookup of the original durable operation: return `COMMITTED` only for the exact stored tuple, or record/return `ABORTED` only through the serialized fence after proving no in-flight or later commit; otherwise remain unresolved, retain source protection, and deny mutation retry. The original operation cannot be retried as a new mutation after expiry or uncertainty. Account's distinct World participation, World admission/abort/terminal serialization, exact source binding, and focused recovery proofs remain unimplemented. This target contract grants no positive StartSession admission or runtime-activation approval; execution must remain unavailable until those boundaries and proofs exist. +Expiry forbids dispatch of a new owner attempt, opening or restarting the World SQL transaction, reacquiring or renewing participation, renewing or reissuing the reference, or re-redeeming it. After a crash or unknown outcome following expiry, World may perform only an exact read-only lookup of the original durable operation: return `COMMITTED` only for the exact stored tuple, or record/return `ABORTED` only through the serialized fence after proving no in-flight or later commit; otherwise remain unresolved, retain source protection, and deny mutation retry. The original operation cannot be retried as a new mutation after expiry or uncertainty. The [implementation tracker](../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) distinguishes World-local execution storage from the still-missing genuine Account participation and authenticated recovery producer. This target contract grants no positive StartSession admission or runtime-activation approval; execution must remain unavailable until those boundaries and proofs exist. `authorityTuple` is copied without scalarization or field renaming from the complete canonical shape in the [JWT and token contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple). `membershipVersion` is the independently applicable Account membership-version map, including `{}` when no membership applies. `HumanAuthorityEvidence/v1` carries the Account-derived actor account, `control-ui` token `jti`, role, assurance, account generation, and applicable tenant or target-tenant generation. `AutomationAuthorityEvidence/v1` carries the exact authenticated workload, automation-policy identity/version, and applicable tenant generation. The tagged `issuanceEvidence` arm must agree with Account-derived `issuanceKind`; the inapplicable arm and inapplicable authority-scope identifiers are omitted rather than serialized as `null`, empty objects, or sentinels. `sourceEvidenceId` identifies the one Account authority snapshot and its linearization evidence, while `sourceEvidenceVersion` is the corresponding Account-issued source version; together they are the canonical source fence for the bundle and are carried unchanged with the existing `{bundleVersion, sourceVersion, sourceFence, linearization}` reference. Account derives every authority, generation, membership, freshness, and branch-decision member from that one atomic snapshot and stores the source pair with the issuance record. During redemption, Account exact-compares `sourceEvidenceId`, `sourceEvidenceVersion`, the bundle reference, and every snapshot-bound field against the stored issuance record and the current applicable authority evidence; a missing, changed, or mixed-version value rejects redemption. Consumers reject missing, extra, contradictory, separately sourced, stale, expired, wrongly tagged, or non-canonical bundle fields and must redeem the original reference with Account; a copied bundle never becomes a second authority. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index ad8fb94208..12dbbb36ff 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -12,6 +12,7 @@ This API contract is target-state canonical; implementation coverage is partial - The registered `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, `FailPreparedWorldInstance` and `TerminateWorldInstance` handlers allow only verified same-namespace Game Session workload identity before request parsing or owner calls. Missing configuration, missing peer identity and other workloads are denied; shared bearer claims do not substitute. Other pre-admission consumers are not currently allowlisted. This caller guard does not supply the remaining canonical preparation, activation, cleanup or admission proofs. - The standalone canonical initial-placement adapter now defines an Entity Management-only historical terminal-result read. Its proto and handler remain unregistered; the read supplies settlement evidence for the exact immutable placement operation, without admitting gameplay or directly mutating any hold. - The authored-world intake construction reads its complete immutable Game Design source through the exact authenticated owner-read contract in [Game Design API Contracts](../game-design-service/api-contracts.md#authored-world-source-readback). The intake transport remains unregistered and does not authorize source mutation, instance preparation, publication, or runtime admission. +- The separate canonical StartSession preparation construction must use the distinct Account World receiving participation and World-local terminal serialization described in [World runtime/data](runtime-and-data.md#original-startsession-execution-storage). Its typed execution identity is binding data, not authenticated authorization. No runtime RPC or positive producer is registered by these storage seams; the ordinary lifecycle handler's Game Session peer guard does not complete this canonical path. - 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. ## gRPC APIs diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 0556d04e48..f9624b1675 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -27,6 +27,14 @@ World Management owns both version-scoped template topology and runtime world-in World Management instances are intended to be replaceable workers over authoritative runtime storage. Target owner rule: runtime room/location/ambient state that matters after process loss belongs in the service-owned database rows and documented caches, not as the sole authoritative copy in one JVM. Another World Management instance of the same type should therefore be able to continue serving and mutating runtime world state after restart without that restart itself becoming the player-visible event. +### Original StartSession execution storage + +[ADR 0047's World receiving participation](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation) owns the authorization and expiry contract. World's local consequence is a durable execution record bound to the complete original StartSession post-authorization tuple, the distinct Account World participation ID/fence, the actual Game Session owner attempt/fence, the canonical target and the exact preparation input. The input retains the original authenticated source, immutable launch descriptor, release and selected publication evidence; neither a publication receipt nor a Game Design projection is a launch permission. World allocates its own positive monotonic execution fence, not an alias of any supplied fence. + +Execution admission, materialization, canonical association and `COMMITTED` publication share one uninterrupted local SQL transaction. The operation/request and canonical-target serialization precede the existing publication and topology locks; the database checks actual current time after lock waits before admitting execution. Network calls occur before SQL, never under these locks. Operational transaction timeouts and cancellation bound resource use, not the physical instant of commit. An execution admitted while the original authorization and owner claim are valid may finish after ingress expiry; expiry never permits another execution transaction, renewed participation or a replacement attempt. + +Exact recovery compares the retained full identity and immutable terminal preparation result. A separate `ABORTED` transaction takes the same operation and target serialization, excludes a live execution and permanently fences later materialization and canonical association. Missing rows, timeouts and rolled-back intermediate states are not abort proof. An unknown outcome remains unresolved until exact `COMMITTED` readback or serialized `ABORTED` proof; Account retains its source protection until authenticated terminal settlement. These storage rules do not supply the missing genuine Account participation producer or authenticated terminal transport. The canonical preparation service remains unavailable for runtime use until that producer, consumer and physical concurrency/recovery proof are complete. + ### Template Identifier Invariants World templates follow the same stability rules as entity templates: 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 1e026fb708..e9e8205814 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The corrected World construction adds V62 durable original-operation, one-shot claim, independent execution fence, atomic V35 materialization/V34 association/`COMMITTED`, and same-lock `ABORTED` settlement. Its identity binds the full original StartSession tuple, distinct Account World participation ID/fence, actual Game Session attempt/fence, target and exact immutable preparation input; observational read metadata does not become a new operation. Local consolidated checks passed after repairing typed jOOQ reads and fixture accessors: World's 589 unit cases executed successfully, while Common's 464 and Game Design's 529 passing unit results were reused by Gradle. All 364 PostgreSQL definitions compiled but skipped without Docker (217 World, 147 Game Design). World V62 and Game Design V70 schema generation, formatting, Checkstyle, SpotBugs, coverage, boot JARs, links, Markdown and Flyway sanity (12 sets, 276 files) passed. This does not prove corrected PostgreSQL migrations, concurrency, cancellation or authenticated recovery. The expiry case covers repository-only exact terminal readback, not an authenticated service recovery path; genuine Account World participation, held-source producer, terminal transport and composed launch remain unavailable. Fresh Entity/Automation source qualification must cover the complete owner families and exact World closure; their authored empty declarations are not receipts or proof of absent source rows. + +Published `b436920367ef19bd30e7620513eefcb7bb9f2e79` [Validation run 37964440628](https://github.com/benhook1013/FireMUD/actions/runs/37964440628) completed red. Account physically executed 254 PostgreSQL cases with no failures, errors or skips; its separate 31-case Draft artifact is a byte-identical subset and is not counted twice. World executed 207 cases with 203 failures: 20 report the V61 selector-function syntax failure directly and 183 are application-context cascades. Game Design executed 150 cases with nine failures: four hit that same World migration, four expose the unchanged V56 SQL consumer rejecting the new inventory-v2 profile, and one expects the obsolete release-guard message. The bounded correction parenthesizes V61's SQL `CASE` inside the PL/pgSQL condition, adds a forward Game Design V70 exact paired-profile guard and negative cases, and corrects only the stale message assertion. Corrected PostgreSQL execution remains required; explicit retained-v1-to-V70 upgrade/readback proof is still open. V67-to-V68 history/retry proof passed, but neither it nor Account's passing suite proves the failed genuine selected export. The synthetic checkout `f586077b0a1f3bdbbcda18bb2a9537572490f71a`, tree `02675bc280cc2601311e667b668230dbcdae0512`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source head, not the intended integration parent. World execution-fence construction and genuine Entity/Automation source intake remain active, not completed handoffs or activation permission. + Published `97174b31be2ed08440be1a271cc00359614abaf6` [Validation run 37945686843](https://github.com/benhook1013/FireMUD/actions/runs/37945686843) executed 254 Account and 207 World PostgreSQL cases with no failures, errors or skips. Both previously failing Account receipt-confirmation fixtures passed with the production V90/V92 guards and original acknowledgement bounds unchanged. Game Design executed 146 PostgreSQL cases with one failure and no errors or skips: the genuine export fixture invented a new World intake request ID instead of using the original durable Game Design delivery claim. The local correction uses that original request, World’s actual receipt and Game Design’s actual acknowledgement, without weakening the selected-source readback guard. Separate legacy descriptor (8), complete launch-binding (6), and genuine GD+World source-settlement (3) cases passed; they do not establish success of the failed genuine export. The actual CI checkout is synthetic merge `421b0196ccffff96405aab1c687d2455c52ede60`, tree `62188ebd390fdd8d4ed71d4a245c5195a30eae3a`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact published source, not the intended integration parent. Published `f580093d113630e8335c301a7ecb31d6a4bf4acd` [Validation run 37951600583](https://github.com/benhook1013/FireMUD/actions/runs/37951600583) executed 254 Account and 207 World PostgreSQL cases successfully with no failures, errors or skips. Game Design executed 524 unit cases successfully and 148 PostgreSQL cases with three failures and no skips: two authored Automation declarations reached the deferred atomic-result guard, which counted all template-config operations only against ordinary template rows; the genuine export progressed beyond the original World-delivery correction but had no authored realm policy. The current correction extends that guard in forward V68 to count exact declaration rows separately while retaining complete coordinator-result, epoch and sibling-source checks. The export fixture now authors and reads back its required realm policy in the original selected commit. The actual CI checkout is synthetic merge `0744b12a806c8a484df3e15c796e9f76532dc64d`, tree `c784e788550a4ae61f0b3df84a711cecc79933b0`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published source; this is exact-source execution, not intended-parent alignment or proof of the corrected state. diff --git a/services/game-design-service/src/main/resources/db/migration/V70__selected_inventory_closure_profile.sql b/services/game-design-service/src/main/resources/db/migration/V70__selected_inventory_closure_profile.sql new file mode 100644 index 0000000000..b1a997384a --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V70__selected_inventory_closure_profile.sql @@ -0,0 +1,66 @@ +-- Preserve the original v1 inventory profile and admit only the explicit closure-qualified v2 +-- profile. Publication-operation bytes and historical migration definitions remain immutable. +-- [jooq ignore start] +DO $migration$ +DECLARE + inventory_function REGPROCEDURE := + '"${serviceSchema}".require_selected_inventory_operation_v2(bytea)'::REGPROCEDURE; + original_definition TEXT; + model_shape_anchor TEXT := $anchor$ (model, ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'])$anchor$; + model_shape_replacement TEXT := $replacement$ (model, CASE + WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + THEN ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs','inboundSourceClosure'] + ELSE ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'] + END)$replacement$; + profile_anchor TEXT := $anchor$ IF inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$anchor$; + profile_replacement TEXT := $replacement$ IF (( + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v1' + AND inventory->'schemaVersion' = '1'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + AND model->'graphSchemaVersion' = '2'::JSONB + AND checkpoint->'digestSchemaVersion' = '3'::JSONB + AND selector->'request'->'digestSchemaVersion' = '3'::JSONB + AND NOT (model ? 'inboundSourceClosure') + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 16) + OR + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1' + AND model->'graphSchemaVersion' = '3'::JSONB + AND checkpoint->'digestSchemaVersion' = '4'::JSONB + AND selector->'request'->'digestSchemaVersion' = '4'::JSONB + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 17 + AND model ?& ARRAY['modelId', 'graphSchemaVersion', 'graphDigest', + 'topologyResultDigest', 'familyCounts', 'regionGeneratorInputs', + 'generationRuleFields', 'regionFields', 'zoneFields', 'roomFields', + 'roomExitFields', 'spawnBindingFields', 'spawnBindingInputs', + 'generationRuleInputCount', 'spawnBindingCount', 'appliedEpochs', + 'inboundSourceClosure'] + AND model->'inboundSourceClosure' IS NOT DISTINCT FROM + '{"schemaVersion":1,"familyCounts":[{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING","count":0}]}'::JSONB) + ) IS NOT TRUE) OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$replacement$; + legacy_model_anchor TEXT := $anchor$ OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB$anchor$; +BEGIN + SELECT pg_get_functiondef(inventory_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, model_shape_anchor, ''))) + / length(model_shape_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, profile_anchor, ''))) + / length(profile_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, legacy_model_anchor, ''))) + / length(legacy_model_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V56 selected inventory v1 profile guards'; + END IF; + original_definition := replace(original_definition, model_shape_anchor, model_shape_replacement); + original_definition := replace(original_definition, profile_anchor, profile_replacement); + -- The paired profile guard above checks both model identifiers and graph schemas. Keep the + -- generation-rule and artifact-decision restrictions below unchanged for both profiles. + original_definition := replace(original_definition, legacy_model_anchor, ''); + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index c47a67dcdb..9842b12d46 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -706,7 +706,7 @@ void sqlGuardRejectsMissingInjectedAndMismatchedSelectorBindingsWithoutAnyReleas original, json.writeValueAsString(selectedV1ControlPlaneParticipants))) .isInstanceOf(DataAccessException.class) - .hasMessageContaining("release v2 participant differs from selected commit/digest/schema"); + .hasMessageContaining("selected participant differs from commit/digest/schema"); assertThat(bundleCount(fixture.dsl())).isZero(); assertThatThrownBy(() -> insertRawSelector(fixture, version, "v2", null, participants)) .isInstanceOf(DataAccessException.class); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index 0a9a470ec0..d2377b4126 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -1377,7 +1377,7 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( // Real owner SQL rejects partial/unknown profiles even when the forged payload has a fresh // matching digest. Upstream inventory authority is still expressly stipulated in this fixture. var mapper = tools.jackson.databind.json.JsonMapper.builder().build(); - for (int mutation = 0; mutation < 5; mutation++) { + for (int mutation = 0; mutation < 10; mutation++) { var publicJson = (tools.jackson.databind.node.ObjectNode) mapper.readTree(operation.inventory().canonicalBytes()); @@ -1407,6 +1407,34 @@ void selectedDraftReservationRejectsChangedSelectionAndAccountOperationEvidence( .put("rowCount", 0); expectedRejectionMessage = "Source inventory counts differ from explicit inputs"; } + case 5 -> { + model.remove("inboundSourceClosure"); + expectedRejectionMessage = "Incomplete or unknown public inventory members"; + } + case 6 -> { + ((tools.jackson.databind.node.ObjectNode) model.get("inboundSourceClosure")) + .put("unknownClosureMember", true); + expectedRejectionMessage = + "Inventory differs from exact original selected Account, APPLIED graph or freeze"; + } + case 7 -> { + ((tools.jackson.databind.node.ObjectNode) + model.get("inboundSourceClosure").get("familyCounts").get(0)) + .put("count", 1); + expectedRejectionMessage = + "Inventory differs from exact original selected Account, APPLIED graph or freeze"; + } + case 8 -> { + publicJson.put("schema", "world-selected-publication-artifact-inventory/v1"); + publicJson.put("schemaVersion", 1); + expectedRejectionMessage = "Incomplete or unknown public inventory members"; + } + case 9 -> { + ((tools.jackson.databind.node.ObjectNode) publicJson.get("checkpoint")) + .put("digestSchemaVersion", 3); + expectedRejectionMessage = + "Inventory differs from exact original selected Account, APPLIED graph or freeze"; + } default -> throw new AssertionError(); } byte[] changedInventory = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentity.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentity.java new file mode 100644 index 0000000000..9d66b20f10 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentity.java @@ -0,0 +1,207 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; + +/** + * Exact World-local execution identity for one original human StartSession operation. + * + *

This is an integrity value, not authenticated Account or Game Session evidence. The only + * production-safe preparation service still denies because no producer supplies it. Its World + * execution fence is allocated and retained by the World repository, independently of the two + * supplied source fences. + */ +public final class WorldCanonicalInstanceExecutionIdentity { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final byte[] originalPostAuthorizationTuple; + private final StartSessionPostAuthorizationExecutionTuple decodedTuple; + private final UUID accountWorldParticipationId; + private final long accountWorldParticipationFence; + private final UUID gameSessionOwnerAttemptId; + private final long gameSessionOwnerFence; + private final UUID canonicalGameInstanceId; + private final String preparationInputJson; + private final String preparationInputDigest; + private final Instant originalAuthorizationExpiry; + + public WorldCanonicalInstanceExecutionIdentity( + byte[] originalPostAuthorizationTuple, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + UUID canonicalGameInstanceId, + String exactPreparationInputJson) { + if (originalPostAuthorizationTuple == null || originalPostAuthorizationTuple.length == 0) { + throw new IllegalArgumentException("Exact original StartSession tuple is required"); + } + this.originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + decodedTuple = + StartSessionPostAuthorizationExecutionTuple.decode(this.originalPostAuthorizationTuple); + requireNonNil(accountWorldParticipationId, "accountWorldParticipationId"); + if (accountWorldParticipationFence <= 0L) { + throw new IllegalArgumentException("accountWorldParticipationFence must be positive"); + } + requireNonNil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + if (gameSessionOwnerFence <= 0L) { + throw new IllegalArgumentException("gameSessionOwnerFence must be positive"); + } + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + if (exactPreparationInputJson == null || exactPreparationInputJson.isBlank()) { + throw new IllegalArgumentException("Exact canonical World preparation input is required"); + } + this.accountWorldParticipationId = accountWorldParticipationId; + this.accountWorldParticipationFence = accountWorldParticipationFence; + this.gameSessionOwnerAttemptId = gameSessionOwnerAttemptId; + this.gameSessionOwnerFence = gameSessionOwnerFence; + this.canonicalGameInstanceId = canonicalGameInstanceId; + this.preparationInputJson = exactPreparationInputJson; + this.preparationInputDigest = digest(exactPreparationInputJson); + + StartSessionPreAuthorizationReservationTuple original = decodedTuple.preAuthorizationTuple(); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals( + decodedTuple.preAuthorizationTuple().actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals(original.targetOwner())) { + throw new IllegalArgumentException( + "World execution requires the original Game Session StartSession tuple"); + } + originalAuthorizationExpiry = + StartSessionAuthorityEvidenceBundle.decode(decodedTuple.authorityEvidenceBundleBytes()) + .expiresAt(); + } + + /** Compares this held identity to the exact existing World preparation input before any SQL. */ + public void requireMatches(Input input, String exactPreparationInputJson) { + Objects.requireNonNull(input, "input"); + Objects.requireNonNull(exactPreparationInputJson, "exactPreparationInputJson"); + StartSessionPreAuthorizationReservationTuple original = decodedTuple.preAuthorizationTuple(); + StartSessionOperatorAction action = original.action(); + var world = input.gameSessionReadEvidence(); + if (!MessageDigest.isEqual( + preparationInputJson.getBytes(java.nio.charset.StandardCharsets.UTF_8), + exactPreparationInputJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)) + || !canonicalGameInstanceId.equals(world.canonicalGameInstanceId()) + || !world.targetNamespace().equals(action.scope().targetNamespace()) + || !world.canonicalTenantId().equals(action.scope().tenantId()) + || !world.controlPlaneRequestId().equals(decodedTuple.controlPlaneRequestId()) + || !world.controlPlaneRequestId().equals(original.controlPlaneRequestId()) + || action.target().gameTemplateId() + != input.completeLaunchBinding().evidence().descriptor().gameTemplateId()) { + throw new IllegalArgumentException( + "World execution identity differs from the exact original tuple, target, or preparation input"); + } + } + + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + public StartSessionPostAuthorizationExecutionTuple decodedTuple() { + return decodedTuple; + } + + public UUID accountWorldParticipationId() { + return accountWorldParticipationId; + } + + public long accountWorldParticipationFence() { + return accountWorldParticipationFence; + } + + public UUID gameSessionOwnerAttemptId() { + return gameSessionOwnerAttemptId; + } + + public long gameSessionOwnerFence() { + return gameSessionOwnerFence; + } + + public UUID canonicalGameInstanceId() { + return canonicalGameInstanceId; + } + + public String targetNamespace() { + return decodedTuple.preAuthorizationTuple().action().scope().targetNamespace(); + } + + public UUID canonicalTenantId() { + return decodedTuple.preAuthorizationTuple().action().scope().tenantId(); + } + + public String controlPlaneRequestId() { + return decodedTuple.controlPlaneRequestId(); + } + + public long gameTemplateId() { + return decodedTuple.preAuthorizationTuple().action().target().gameTemplateId(); + } + + public String preparationInputDigest() { + return preparationInputDigest; + } + + public String preparationInputJson() { + return preparationInputJson; + } + + /** + * Original bound expiry from the canonical Account evidence bundle; no World TTL is introduced. + */ + public Instant originalAuthorizationExpiry() { + return originalAuthorizationExpiry; + } + + boolean exactlyMatches(WorldCanonicalInstanceExecutionIdentity other) { + return other != null + && MessageDigest.isEqual( + originalPostAuthorizationTuple, other.originalPostAuthorizationTuple) + && accountWorldParticipationId.equals(other.accountWorldParticipationId) + && accountWorldParticipationFence == other.accountWorldParticipationFence + && gameSessionOwnerAttemptId.equals(other.gameSessionOwnerAttemptId) + && gameSessionOwnerFence == other.gameSessionOwnerFence + && canonicalGameInstanceId.equals(other.canonicalGameInstanceId) + && preparationInputJson.equals(other.preparationInputJson); + } + + @Override + public boolean equals(Object other) { + return other instanceof WorldCanonicalInstanceExecutionIdentity that && exactlyMatches(that); + } + + @Override + public int hashCode() { + return Objects.hash( + Arrays.hashCode(originalPostAuthorizationTuple), + accountWorldParticipationId, + accountWorldParticipationFence, + gameSessionOwnerAttemptId, + gameSessionOwnerFence, + canonicalGameInstanceId, + preparationInputJson); + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) throw new IllegalArgumentException(field + " must not be nil"); + } + + private static String digest(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java index d4750e0601..dc843b0542 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -4,6 +4,8 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; +import java.time.Duration; +import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; @@ -51,17 +53,24 @@ public final class WorldCanonicalInstancePreparationRepository { private final DSLContext dsl; private final TransactionTemplate transaction; + private final TransactionTemplate intentTransaction; + private final TransactionTemplate readTransaction; + private final TransactionTemplate abortTransaction; + private final int transactionTimeoutSeconds; private final WorldCanonicalInstanceAssociationRepository associationRepository; private final WorldCanonicalFrozenTopologyRepository frozenTopologyRepository; private final WorldAuthoredSourceIntakeRepository sourceIntakeRepository; private final WorldCompleteLaunchBindingRepository launchBindingRepository; private final WorldAuthoredVersionIdentityRepository versionIdentityRepository; + private final PlatformTransactionManager transactionManager; + private final long transactionTimeoutMillis; public WorldCanonicalInstancePreparationRepository( DSLContext dsl, PlatformTransactionManager transactionManager, WorldCanonicalInstanceAssociationRepository associationRepository, - WorldCanonicalFrozenTopologyRepository frozenTopologyRepository) { + WorldCanonicalFrozenTopologyRepository frozenTopologyRepository, + Duration transactionTimeout) { this.dsl = Objects.requireNonNull(dsl, "dsl"); this.associationRepository = Objects.requireNonNull(associationRepository, "associationRepository"); @@ -70,10 +79,32 @@ public WorldCanonicalInstancePreparationRepository( sourceIntakeRepository = new WorldAuthoredSourceIntakeRepository(dsl); launchBindingRepository = new WorldCompleteLaunchBindingRepository(dsl); versionIdentityRepository = new WorldAuthoredVersionIdentityRepository(dsl); - transaction = - new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + Objects.requireNonNull(transactionTimeout, "transactionTimeout"); + if (transactionTimeout.compareTo(Duration.ofSeconds(1)) < 0 + || transactionTimeout.compareTo(Duration.ofMinutes(5)) > 0) { + throw new IllegalArgumentException( + "World execution transaction timeout must be selected from 1 second through 5 minutes"); + } + transactionTimeoutSeconds = Math.toIntExact(transactionTimeout.toSeconds()); + transactionTimeoutMillis = transactionTimeout.toMillis(); + this.transactionManager = Objects.requireNonNull(transactionManager, "transactionManager"); + transaction = new TransactionTemplate(this.transactionManager); transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setTimeout(transactionTimeoutSeconds); + intentTransaction = new TransactionTemplate(this.transactionManager); + intentTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + intentTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + intentTransaction.setTimeout(transactionTimeoutSeconds); + abortTransaction = new TransactionTemplate(this.transactionManager); + abortTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + abortTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + abortTransaction.setTimeout(transactionTimeoutSeconds); + readTransaction = new TransactionTemplate(this.transactionManager); + readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readTransaction.setReadOnly(true); + readTransaction.setTimeout(transactionTimeoutSeconds); } /** @@ -86,40 +117,113 @@ public Result materialize( Objects.requireNonNull(input, "input"); Objects.requireNonNull(authority, "authority"); requireNoActiveTransaction("Canonical World preparation"); - requireExactOriginalBindings(input); - requireExactFrozenSource(input); + WorldCanonicalInstanceExecutionIdentity executionIdentity = + Objects.requireNonNull( + authority.executionIdentity(), + "Canonical preparation authority returned no typed World execution identity"); String inputJson = inputJson(input); String inputDigest = digest(inputJson.getBytes(StandardCharsets.UTF_8)); + executionIdentity.requireMatches(input, inputJson); - MaterializedInstance committed = - Objects.requireNonNull( - transaction.execute( - status -> { - requireWritableReadCommittedTransaction(); - authority.requireHeld(); - Record row = - Objects.requireNonNull( - fetchCanonicalPreparation(inputJson, inputDigest), - "V35 canonical preparation function returned no row"); - MaterializedInstance materialized = - new MaterializedInstance( - required(row, "world_instance_id", Long.class), - required(row, "private_game_instance_key", Long.class)); - WorldCanonicalInstanceAssociation.Claim claim = - new WorldCanonicalInstanceAssociation.Claim( - input.gameSessionReadRequest(), - input.gameSessionReadEvidence(), - materialized.worldInstanceId(), - input.completeLaunchBinding(), - input.versionIdentity()); - associationRepository.retainClaimInOwnerTransaction(claim); - authority.requireHeld(); - return materialized; - }), - "Canonical World preparation transaction did not commit"); + ExecutionLookup lookup = readExactExecution(executionIdentity); + Optional retained = lookup.operation(); + if (retained.isPresent()) { + ExecutionOperation operation = retained.orElseThrow(); + if (operation.state() == ExecutionState.COMMITTED) { + return readCommittedResult(input, operation); + } + if (operation.state() == ExecutionState.ABORTED) { + throw new ConflictingPreparationException( + "Exact original World execution is durably ABORTED and cannot be restarted"); + } + throw new ConflictingPreparationException( + "Exact original World execution has a retained PENDING intent; only serialized ABORTED recovery may resolve it"); + } - // The authority handle is still open here: TransactionTemplate returned only after commit. + if (!lookup.originalAuthorizationValidAtRead()) { + throw new WorldCanonicalInstancePreparationService.PreparationDeniedException( + "Original StartSession authorization expired; World may only read the exact operation or serialize ABORTED"); + } + + requireExactOriginalBindings(input); + requireExactFrozenSource(input); authority.requireHeld(); + MaterializedInstance committed; + try { + long intentFence = + persistExecutionIntent(inputJson, inputDigest, executionIdentity, authority); + if (intentFence <= 0L) { + return recoverSerializedExecution(input, executionIdentity); + } + + Long claimedFence = claimExecutionIntent(executionIdentity, authority); + if (claimedFence == null || claimedFence <= 0L || claimedFence != intentFence) { + return recoverSerializedExecution(input, executionIdentity); + } + + committed = + transaction.execute( + status -> { + requireWritableReadCommittedTransaction(); + applyDatabaseTimeouts(); + authority.requireHeld(); + Record beginRow = + dsl.fetchOne( + "SELECT world_begin_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?, ?)", + inputJson, + inputDigest, + executionIdentity.originalPostAuthorizationTuple(), + executionIdentity.accountWorldParticipationId(), + executionIdentity.accountWorldParticipationFence(), + executionIdentity.gameSessionOwnerAttemptId(), + executionIdentity.gameSessionOwnerFence(), + executionIdentity.canonicalGameInstanceId(), + intentFence); + Long worldExecutionFence = beginRow == null ? null : beginRow.get(0, Long.class); + if (worldExecutionFence == null || worldExecutionFence <= 0L) { + return null; + } + Record row = + Objects.requireNonNull( + fetchCanonicalPreparation(inputJson, inputDigest), + "V35 canonical preparation function returned no row"); + MaterializedInstance materialized = + new MaterializedInstance( + required(row, "world_instance_id", Long.class), + required(row, "private_game_instance_key", Long.class)); + WorldCanonicalInstanceAssociation.Claim claim = + new WorldCanonicalInstanceAssociation.Claim( + input.gameSessionReadRequest(), + input.gameSessionReadEvidence(), + materialized.worldInstanceId(), + input.completeLaunchBinding(), + input.versionIdentity()); + associationRepository.retainClaimInOwnerTransaction(claim); + authority.requireHeld(); + dsl.fetch( + "SELECT world_commit_canonical_instance_execution(?)", + materialized.worldInstanceId()); + return materialized; + }); + } catch (RuntimeException outcomeUncertain) { + return recoverAfterUncertainWrite(input, executionIdentity, outcomeUncertain); + } + + if (committed == null) { + ExecutionOperation terminal = + readExactExecution(executionIdentity) + .operation() + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "A serialized World execution disappeared before terminal readback")); + if (terminal.state() == ExecutionState.COMMITTED) { + return readCommittedResult(input, terminal); + } + throw new ConflictingPreparationException( + "World execution reached a non-committed terminal state before materialization"); + } + Result result = readOwnerPreparation(input) .orElseThrow( @@ -133,6 +237,264 @@ public Result materialize( return result; } + /** + * Retains the full immutable operation identity in a short transaction before materialization. + * The record is not permission: every new writer still needs a fresh held verifier and must pass + * the DB-clock check after all V35 locks have been acquired. + */ + private long persistExecutionIntent( + String inputJson, + String inputDigest, + WorldCanonicalInstanceExecutionIdentity identity, + WorldCanonicalInstancePreparationService.HeldCommitAuthority authority) { + Long fence = + intentTransaction.execute( + status -> { + requireWritableReadCommittedTransaction(); + applyDatabaseTimeouts(); + authority.requireHeld(); + Record intentRow = + dsl.fetchOne( + "SELECT world_persist_canonical_instance_execution_intent(?, ?, ?, ?, ?, ?, ?, ?)", + inputJson, + inputDigest, + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId()); + return intentRow == null ? null : intentRow.get(0, Long.class); + }); + if (fence == null) { + throw new InvalidPreparationEvidenceException( + "World execution intent transaction returned no fence result"); + } + authority.requireHeld(); + return fence; + } + + private Long claimExecutionIntent( + WorldCanonicalInstanceExecutionIdentity identity, + WorldCanonicalInstancePreparationService.HeldCommitAuthority authority) { + Long fence = + intentTransaction.execute( + status -> { + requireWritableReadCommittedTransaction(); + applyDatabaseTimeouts(); + authority.requireHeld(); + Record claimRow = + dsl.fetchOne( + "SELECT world_claim_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?)", + identity.preparationInputJson(), + identity.preparationInputDigest(), + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId()); + return claimRow == null ? null : claimRow.get(0, Long.class); + }); + authority.requireHeld(); + return fence; + } + + /** Exact read-only recovery lookup; it never invokes V35 or reassembles external source data. */ + public ExecutionLookup readExactExecution(WorldCanonicalInstanceExecutionIdentity identity) { + Objects.requireNonNull(identity, "identity"); + requireNoActiveTransaction("World execution terminal read"); + Record row = + readTransaction.execute( + status -> { + applyDatabaseTimeouts(); + return dsl.fetchOne( + "SELECT clock.database_now, e.canonical_game_instance_id, original_post_authorization_tuple, " + + "original_post_authorization_tuple_sha256, account_world_participation_id, " + + "account_world_participation_fence, game_session_owner_attempt_id, " + + "game_session_owner_fence, preparation_input_digest, preparation_input_json, " + + "world_execution_fence, operation_state, world_instance_id " + + "FROM (SELECT clock_timestamp() AS database_now) clock " + + "LEFT JOIN world_canonical_instance_execution e ON e.target_namespace=? " + + "AND e.canonical_tenant_id=? AND e.control_plane_request_id=?", + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.controlPlaneRequestId()); + }); + if (row == null) { + throw new InvalidPreparationEvidenceException( + "World exact-operation read returned no database-clock result"); + } + boolean originalAuthorizationValidAtRead = + identity + .originalAuthorizationExpiry() + .isAfter(required(row, "database_now", OffsetDateTime.class).toInstant()); + if (row.get("canonical_game_instance_id", UUID.class) == null) { + return new ExecutionLookup(Optional.empty(), originalAuthorizationValidAtRead); + } + + byte[] tupleBytes = required(row, "original_post_authorization_tuple", byte[].class); + String tupleDigest = required(row, "original_post_authorization_tuple_sha256", String.class); + if (!identity + .canonicalGameInstanceId() + .equals(required(row, "canonical_game_instance_id", UUID.class)) + || !MessageDigest.isEqual(tupleBytes, identity.originalPostAuthorizationTuple()) + || !HexFormat.of().formatHex(sha256(tupleBytes)).equals(tupleDigest) + || !identity + .accountWorldParticipationId() + .equals(required(row, "account_world_participation_id", UUID.class)) + || identity.accountWorldParticipationFence() + != required(row, "account_world_participation_fence", Long.class) + || !identity + .gameSessionOwnerAttemptId() + .equals(required(row, "game_session_owner_attempt_id", UUID.class)) + || identity.gameSessionOwnerFence() != required(row, "game_session_owner_fence", Long.class) + || !identity + .preparationInputDigest() + .equals(required(row, "preparation_input_digest", String.class)) + || !identity + .preparationInputJson() + .equals(required(row, "preparation_input_json", String.class))) { + throw new ConflictingPreparationException( + "World execution lookup differs from the exact original full identity"); + } + long fence = required(row, "world_execution_fence", Long.class); + String state = required(row, "operation_state", String.class); + Long worldInstanceId = row.get("world_instance_id", Long.class); + ExecutionState executionState; + try { + executionState = ExecutionState.valueOf(state); + } catch (IllegalArgumentException unsupported) { + throw new InvalidPreparationEvidenceException( + "World execution row has an unsupported durable state", unsupported); + } + if ((executionState == ExecutionState.COMMITTED) != (worldInstanceId != null) || fence <= 0L) { + throw new InvalidPreparationEvidenceException( + "World execution terminal row has an incomplete result or fence"); + } + return new ExecutionLookup( + Optional.of(new ExecutionOperation(executionState, fence, worldInstanceId)), + originalAuthorizationValidAtRead); + } + + private Result recoverSerializedExecution( + Input input, WorldCanonicalInstanceExecutionIdentity identity) { + ExecutionOperation terminal = + readExactExecution(identity) + .operation() + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Serialized World execution disappeared before terminal readback")); + if (terminal.state() == ExecutionState.ABORTED) { + throw new ConflictingPreparationException( + "Exact original World execution is durably ABORTED and cannot be restarted"); + } + if (terminal.state() != ExecutionState.COMMITTED) { + throw new ConflictingPreparationException( + "Exact original World execution remains PENDING and requires durable serialized ABORTED recovery"); + } + return readCommittedResult(input, terminal); + } + + private Result recoverAfterUncertainWrite( + Input input, + WorldCanonicalInstanceExecutionIdentity identity, + RuntimeException outcomeUncertain) { + ExecutionOperation operation; + try { + operation = readExactExecution(identity).operation().orElse(null); + } catch (RuntimeException readFailure) { + outcomeUncertain.addSuppressed(readFailure); + throw outcomeUncertain; + } + if (operation == null || operation.state() == ExecutionState.PENDING) { + // Exact readback is not permission to restart. The caller may only resolve this row through + // the same-lock durable-abort operation. + throw outcomeUncertain; + } + if (operation.state() == ExecutionState.ABORTED) { + throw new ConflictingPreparationException( + "Exact original World execution is durably ABORTED after the uncertain write", + outcomeUncertain); + } + return readCommittedResult(input, operation); + } + + private Result readCommittedResult(Input input, ExecutionOperation terminal) { + Result result = + readOwnerPreparation(input) + .orElseThrow( + () -> + new InvalidPreparationEvidenceException( + "Exact COMMITTED World execution has no immutable preparation readback")); + if (result.association().worldInstanceId() != terminal.worldInstanceId()) { + throw new InvalidPreparationEvidenceException( + "Exact COMMITTED World execution differs from its retained terminal result"); + } + return result; + } + + /** + * Serializes an ABORTED terminal against the same request/target execution locks. Lock timeout + * and transaction uncertainty propagate unchanged and are never converted to ABORTED. + */ + public ExecutionOperation recordDurableAbort(WorldCanonicalInstanceExecutionIdentity identity) { + Objects.requireNonNull(identity, "identity"); + requireNoActiveTransaction("World execution abort"); + Record row = + Objects.requireNonNull( + abortTransaction.execute( + status -> { + requireWritableReadCommittedTransaction(); + applyDatabaseTimeouts(); + return dsl.fetchOne( + "SELECT operation_state, world_execution_fence, world_instance_id " + + "FROM world_abort_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.controlPlaneRequestId(), + identity.canonicalGameInstanceId(), + identity.preparationInputJson(), + identity.preparationInputDigest(), + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence()); + }), + "World abort transaction did not complete"); + String state = required(row, "operation_state", String.class); + ExecutionState executionState = ExecutionState.valueOf(state); + Long worldInstanceId = row.get("world_instance_id", Long.class); + return new ExecutionOperation( + executionState, required(row, "world_execution_fence", Long.class), worldInstanceId); + } + + public enum ExecutionState { + PENDING, + COMMITTED, + ABORTED + } + + public record ExecutionOperation( + ExecutionState state, long worldExecutionFence, Long worldInstanceId) { + public ExecutionOperation { + Objects.requireNonNull(state, "state"); + if (worldExecutionFence <= 0L + || (state == ExecutionState.COMMITTED) != (worldInstanceId != null)) { + throw new IllegalArgumentException("World execution operation state is incomplete"); + } + } + } + + public record ExecutionLookup( + Optional operation, boolean originalAuthorizationValidAtRead) { + public ExecutionLookup { + Objects.requireNonNull(operation, "operation"); + } + } + /** * Calls the V35 writer inside its owner transaction and translates only its explicit * canonical-identity conflict signals. Throwing the domain exception here keeps the transaction @@ -790,6 +1152,12 @@ private void requireWritableReadCommittedTransaction() { } } + private void applyDatabaseTimeouts() { + String timeout = transactionTimeoutMillis + "ms"; + dsl.fetchValue("SELECT set_config('statement_timeout', ?, TRUE)", timeout); + dsl.fetchValue("SELECT set_config('lock_timeout', ?, TRUE)", timeout); + } + private static void requireNoActiveTransaction(String label) { if (TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException(label + " must not join an ambient transaction"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java index d9437201b9..1a56f6ad2c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java @@ -68,14 +68,29 @@ public interface CommitAuthorityVerifier { /** * A verifier-owned, continuously held producer-evidence handle. It stays open throughout the * World transaction and its commit; implementations must fail closed from {@link #requireHeld()} - * if the evidence they verified is no longer effective. Remote/current-state checks happen before - * the World transaction; {@code requireHeld()} is a local fence/effective-state assertion and - * must never perform RPC while World holds database locks. It is not a new Account creator - * permission. + * if the source participation/fence they verified is no longer continuously held. + * Remote/current-state checks happen before the World transaction; {@code requireHeld()} is a + * local fence/effective-state assertion and must never perform RPC while World holds database + * locks. It must not reapply the original ingress-authority expiry after the V35 SQL admission + * check: an uninterrupted admitted transaction may finish after that bound while the source + * participation remains protected through exact World COMMITTED or durable ABORTED settlement. + * {@link #close()} may release only local resources; it must never release durable Account + * participation merely because this call returned, timed out, or has an uncertain outcome. That + * participation remains protected until an authenticated exact World COMMITTED result or fenced + * durable ABORTED settlement is known. It is not a new Account creator permission. */ public interface HeldCommitAuthority extends AutoCloseable { void requireHeld(); + /** + * Returns the exact typed identity this continuously held verifier authenticated. There is no + * default identity: old generic no-op handles cannot authorize the new World SQL path. + */ + default WorldCanonicalInstanceExecutionIdentity executionIdentity() { + throw new PreparationDeniedException( + "Canonical World preparation requires a complete typed StartSession execution identity"); + } + @Override void close(); } diff --git a/services/world-management-service/src/main/resources/db/migration/V61__world_selected_closure_schema4_guards.sql b/services/world-management-service/src/main/resources/db/migration/V61__world_selected_closure_schema4_guards.sql index 8806de25d9..512155f3f0 100644 --- a/services/world-management-service/src/main/resources/db/migration/V61__world_selected_closure_schema4_guards.sql +++ b/services/world-management-service/src/main/resources/db/migration/V61__world_selected_closure_schema4_guards.sql @@ -157,8 +157,10 @@ DECLARE OR binding->>'schemaVersion' NOT IN ('2', '3') OR input->>'worldStartLocationEvidenceBase64' IS NULL$replacement$; digest_anchor TEXT := $anchor$ OR selected->>'digestSchemaVersion' IS DISTINCT FROM '3'$anchor$; - digest_replacement TEXT := $replacement$ OR selected->>'digestSchemaVersion' IS DISTINCT FROM CASE binding->>'schemaVersion' - WHEN '2' THEN '3' WHEN '3' THEN '4' ELSE NULL END$replacement$; + -- Parentheses keep the CASE's THEN tokens inside the SQL expression rather than terminating + -- PL/pgSQL's outer IF condition while the rewritten function is compiled. + digest_replacement TEXT := $replacement$ OR selected->>'digestSchemaVersion' IS DISTINCT FROM (CASE binding->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' ELSE NULL END)$replacement$; BEGIN SELECT pg_get_functiondef(selector_function) INTO STRICT original_definition; IF (length(original_definition) - length(replace(original_definition, schema_anchor, ''))) diff --git a/services/world-management-service/src/main/resources/db/migration/V62__world_start_session_execution_terminal_fence.sql b/services/world-management-service/src/main/resources/db/migration/V62__world_start_session_execution_terminal_fence.sql new file mode 100644 index 0000000000..63a1e4bf82 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V62__world_start_session_execution_terminal_fence.sql @@ -0,0 +1,817 @@ +-- A World preparation operation is retained before its execution transaction so that a later +-- serialized abort can name the exact original tuple and source binding without re-reading remote +-- sources. EXECUTING is visible only inside the one materialization transaction and may never +-- commit; COMMITTED includes both the V35 rows and V34 association, while ABORTED fences retries. +-- Historical V35/V34 rows are deliberately not backfilled into this operation ledger. +CREATE SEQUENCE world_canonical_instance_execution_fence_seq AS BIGINT MINVALUE 1; + +CREATE TABLE world_canonical_instance_execution ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_game_instance_id UUID NOT NULL, + canonical_world_slug VARCHAR(120) NOT NULL, + game_template_id BIGINT NOT NULL, + original_post_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + original_post_authorization_tuple_sha256 VARCHAR(64) NOT NULL + CHECK (original_post_authorization_tuple_sha256 ~ '^[0-9a-f]{64}$'), + account_world_participation_id UUID NOT NULL, + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + game_session_owner_attempt_id UUID NOT NULL, + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + preparation_input_digest VARCHAR(71) NOT NULL + CHECK (preparation_input_digest ~ '^sha256:[0-9a-f]{64}$'), + preparation_input_json TEXT NOT NULL CHECK (length(preparation_input_json) > 0), + world_execution_fence BIGINT NOT NULL UNIQUE CHECK (world_execution_fence > 0), + operation_state VARCHAR(16) NOT NULL + CHECK (operation_state IN ('PENDING', 'EXECUTING', 'COMMITTED', 'ABORTED')), + execution_claimed BOOLEAN NOT NULL DEFAULT FALSE, + active_transaction_id BIGINT, + world_instance_id BIGINT REFERENCES world_instance(id) ON DELETE RESTRICT + DEFERRABLE INITIALLY DEFERRED, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + terminal_at TIMESTAMPTZ, + PRIMARY KEY (target_namespace, canonical_tenant_id, control_plane_request_id), + UNIQUE (canonical_game_instance_id), + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (account_world_participation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (game_template_id > 0), + CHECK ( + (operation_state = 'PENDING' AND active_transaction_id IS NULL + AND world_instance_id IS NULL AND terminal_at IS NULL) + OR (operation_state = 'EXECUTING' AND execution_claimed IS TRUE + AND active_transaction_id > 0 + AND world_instance_id IS NULL AND terminal_at IS NULL) + OR (operation_state = 'COMMITTED' AND execution_claimed IS TRUE + AND active_transaction_id IS NULL + AND world_instance_id > 0 AND terminal_at IS NOT NULL) + OR (operation_state = 'ABORTED' AND active_transaction_id IS NULL + AND world_instance_id IS NULL AND terminal_at IS NOT NULL) + ) +); +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_execution FROM PUBLIC; +REVOKE ALL ON SEQUENCE world_canonical_instance_execution_fence_seq FROM PUBLIC; + +CREATE FUNCTION world_validate_canonical_instance_execution_input( + p_input_json TEXT, + p_input_digest TEXT, + p_original_tuple BYTEA, + p_account_participation_id UUID, + p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, + p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID +) RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + input JSONB; + tuple_value JSONB; + original JSONB; + descriptor JSONB; + action_scope JSONB; + target JSONB; + target_owner JSONB; +BEGIN + IF p_input_json IS NULL OR length(p_input_json) = 0 + OR p_input_digest IS NULL OR p_input_digest !~ '^sha256:[0-9a-f]{64}$' + OR p_input_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(p_input_json, 'UTF8')), 'hex') + OR p_original_tuple IS NULL OR octet_length(p_original_tuple) NOT BETWEEN 1 AND 262144 + OR p_account_participation_id IS NULL + OR p_account_participation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_account_participation_fence IS NULL OR p_account_participation_fence <= 0 + OR p_game_session_attempt_id IS NULL + OR p_game_session_attempt_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_game_session_fence IS NULL OR p_game_session_fence <= 0 + OR p_canonical_game_instance_id IS NULL + OR p_canonical_game_instance_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'World execution identity or preparation input is malformed' + USING ERRCODE = '23514'; + END IF; + + input := p_input_json::JSONB; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + original := tuple_value->'preAuthorizationReservationTuple'; + action_scope := tuple_value->'scope'; + target := tuple_value->'target'; + target_owner := tuple_value->'targetOwner'; + descriptor := (input->'gameSessionReadEvidence'->>'descriptorJson')::JSONB; + IF tuple_value->>'tupleSchemaId' IS DISTINCT FROM 'postAuthorizationExecutionTuple' + OR tuple_value->>'tupleSchemaVersion' IS DISTINCT FROM '1' + OR tuple_value->>'issuanceKind' IS DISTINCT FROM 'human_operator' + OR tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM original->'actionFamilyRequestIdentity'->>'requestId' + OR action_scope->>'targetNamespace' IS DISTINCT FROM input->'identity'->>'targetNamespace' + OR action_scope->>'tenantId' IS DISTINCT FROM input->'identity'->>'canonicalTenantId' + OR tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM input->'identity'->>'controlPlaneRequestId' + OR target_owner->>'ownerService' IS DISTINCT FROM 'game-session-service' + OR original->>'actionFamily' IS DISTINCT FROM 'StartSession' + OR (target->>'gameTemplateId')::BIGINT IS DISTINCT FROM (descriptor->>'gameTemplateId')::BIGINT + OR input->'identity'->>'canonicalGameInstanceId' IS DISTINCT FROM p_canonical_game_instance_id::TEXT + OR input->'gameSessionReadEvidence'->>'canonicalGameInstanceId' IS DISTINCT FROM p_canonical_game_instance_id::TEXT + OR input->'gameSessionReadRequest'->>'canonicalGameInstanceId' IS DISTINCT FROM p_canonical_game_instance_id::TEXT + OR input->'identity'->>'targetNamespace' IS DISTINCT FROM input->'gameSessionReadEvidence'->>'targetNamespace' + OR input->'identity'->>'canonicalTenantId' IS DISTINCT FROM input->'gameSessionReadEvidence'->>'canonicalTenantId' + OR input->'identity'->>'worldSlug' IS DISTINCT FROM input->'gameSessionReadEvidence'->>'worldSlug' + OR input->'identity'->>'controlPlaneRequestId' IS DISTINCT FROM input->'gameSessionReadEvidence'->>'controlPlaneRequestId' + OR tuple_value->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt' IS NULL THEN + RAISE EXCEPTION 'World execution identity differs from the exact StartSession tuple or World target' + USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_validate_canonical_instance_execution_input(TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID) FROM PUBLIC; + +CREATE FUNCTION world_lock_canonical_instance_execution( + p_target_namespace TEXT, p_canonical_tenant_id UUID, + p_control_plane_request_id TEXT, p_canonical_game_instance_id UUID +) RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + -- The request lock comes first so a substituted canonical target cannot race the original + -- request. The target lock then serializes different requests aimed at the same World target. + PERFORM pg_advisory_xact_lock(hashtextextended( + 'world-canonical-execution-request:' || p_target_namespace || ':' + || p_canonical_tenant_id::TEXT || ':' || p_control_plane_request_id, 0)); + PERFORM pg_advisory_xact_lock(hashtextextended( + 'world-canonical-execution-target:' || p_canonical_game_instance_id::TEXT, 0)); +END; +$$; +REVOKE ALL ON FUNCTION world_lock_canonical_instance_execution(TEXT, UUID, TEXT, UUID) FROM PUBLIC; + +CREATE FUNCTION world_persist_canonical_instance_execution_intent( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + input JSONB; + tuple_value JSONB; + projection_expiry TIMESTAMPTZ; + v_target_namespace TEXT; + v_canonical_tenant_id UUID; + v_request_id TEXT; + v_world_slug TEXT; + v_game_template_id BIGINT; + prior "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + input := p_input_json::JSONB; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + v_target_namespace := input->'identity'->>'targetNamespace'; + v_canonical_tenant_id := (input->'identity'->>'canonicalTenantId')::UUID; + v_request_id := input->'identity'->>'controlPlaneRequestId'; + v_world_slug := input->'identity'->>'worldSlug'; + v_game_template_id := (((input->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT; + projection_expiry := (tuple_value->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt')::TIMESTAMPTZ; + + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + v_target_namespace, v_canonical_tenant_id, v_request_id, p_canonical_game_instance_id); + -- Use the database wall clock after both shared identity locks; transaction-start timestamps + -- would admit a transaction that waited past the original Account bound. + IF projection_expiry <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession authorization expired before World intent retention' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO prior FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = v_target_namespace + AND e.canonical_tenant_id = v_canonical_tenant_id + AND e.control_plane_request_id = v_request_id + FOR UPDATE; + IF FOUND THEN + IF prior.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR prior.canonical_world_slug IS DISTINCT FROM v_world_slug + OR prior.game_template_id IS DISTINCT FROM v_game_template_id + OR prior.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR prior.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR prior.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR prior.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR prior.game_session_owner_fence IS DISTINCT FROM p_game_session_fence + OR prior.preparation_input_digest IS DISTINCT FROM p_input_digest + OR prior.preparation_input_json IS DISTINCT FROM p_input_json THEN + RAISE EXCEPTION 'World execution request is already bound to a different full identity' + USING ERRCODE = '23505'; + END IF; + -- A previously retained intent is never automatically restarted. The caller performs an + -- exact terminal read; PENDING requires the shared-lock durable-abort path. + RETURN 0; + END IF; + + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = p_canonical_game_instance_id + OR (p.target_namespace = v_target_namespace + AND p.canonical_tenant_id = v_canonical_tenant_id + AND p.control_plane_request_id = v_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = p_canonical_game_instance_id + OR (a.canonical_target_namespace = v_target_namespace + AND a.canonical_tenant_id = v_canonical_tenant_id + AND a.control_plane_request_id = v_request_id)) THEN + RAISE EXCEPTION 'Historical World materialization has no exact execution identity' + USING ERRCODE = '23514'; + END IF; + + INSERT INTO "${serviceSchema}".world_canonical_instance_execution ( + target_namespace, canonical_tenant_id, control_plane_request_id, + canonical_game_instance_id, canonical_world_slug, game_template_id, + original_post_authorization_tuple, original_post_authorization_tuple_sha256, + account_world_participation_id, account_world_participation_fence, + game_session_owner_attempt_id, game_session_owner_fence, + preparation_input_digest, preparation_input_json, world_execution_fence, + operation_state) + VALUES ( + v_target_namespace, v_canonical_tenant_id, v_request_id, + p_canonical_game_instance_id, v_world_slug, v_game_template_id, + p_original_tuple, encode(sha256(p_original_tuple), 'hex'), + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, + p_input_digest, p_input_json, + nextval('"${serviceSchema}".world_canonical_instance_execution_fence_seq'), + 'PENDING') + RETURNING world_execution_fence INTO prior.world_execution_fence; + RETURN prior.world_execution_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_persist_canonical_instance_execution_intent(TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID) FROM PUBLIC; + +CREATE FUNCTION world_claim_canonical_instance_execution( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + input JSONB; + tuple_value JSONB; + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; + v_target_namespace TEXT; + v_canonical_tenant_id UUID; + v_request_id TEXT; + original_expiry TIMESTAMPTZ; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + input := p_input_json::JSONB; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + v_target_namespace := input->'identity'->>'targetNamespace'; + v_canonical_tenant_id := (input->'identity'->>'canonicalTenantId')::UUID; + v_request_id := input->'identity'->>'controlPlaneRequestId'; + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + v_target_namespace, v_canonical_tenant_id, v_request_id, p_canonical_game_instance_id); + original_expiry := (tuple_value->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt')::TIMESTAMPTZ; + IF original_expiry <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession authorization expired before World execution claim' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = v_target_namespace + AND e.canonical_tenant_id = v_canonical_tenant_id + AND e.control_plane_request_id = v_request_id + FOR UPDATE; + IF NOT FOUND + OR operation.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR operation.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR operation.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR operation.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR operation.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR operation.game_session_owner_fence IS DISTINCT FROM p_game_session_fence + OR operation.preparation_input_digest IS DISTINCT FROM p_input_digest + OR operation.preparation_input_json IS DISTINCT FROM p_input_json THEN + RAISE EXCEPTION 'World execution claim differs from the exact original full identity' + USING ERRCODE = '23514'; + END IF; + IF operation.operation_state = 'COMMITTED' THEN + RETURN 0; + END IF; + IF operation.operation_state <> 'PENDING' OR operation.execution_claimed THEN + RETURN 0; + END IF; + PERFORM set_config('world.canonical_claim_namespace', operation.target_namespace, TRUE); + PERFORM set_config('world.canonical_claim_tenant', operation.canonical_tenant_id::TEXT, TRUE); + PERFORM set_config('world.canonical_claim_request', operation.control_plane_request_id, TRUE); + PERFORM set_config('world.canonical_claim_target', operation.canonical_game_instance_id::TEXT, TRUE); + PERFORM set_config('world.canonical_claim_fence', operation.world_execution_fence::TEXT, TRUE); + UPDATE "${serviceSchema}".world_canonical_instance_execution e + SET execution_claimed = TRUE + WHERE e.target_namespace = operation.target_namespace + AND e.canonical_tenant_id = operation.canonical_tenant_id + AND e.control_plane_request_id = operation.control_plane_request_id; + RETURN operation.world_execution_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_claim_canonical_instance_execution(TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID) FROM PUBLIC; + +CREATE FUNCTION world_begin_canonical_instance_execution( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID, p_world_execution_fence BIGINT +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + input JSONB; + v_target_namespace TEXT; + v_canonical_tenant_id UUID; + v_request_id TEXT; + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + input := p_input_json::JSONB; + v_target_namespace := input->'identity'->>'targetNamespace'; + v_canonical_tenant_id := (input->'identity'->>'canonicalTenantId')::UUID; + v_request_id := input->'identity'->>'controlPlaneRequestId'; + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + v_target_namespace, v_canonical_tenant_id, v_request_id, p_canonical_game_instance_id); + + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = v_target_namespace + AND e.canonical_tenant_id = v_canonical_tenant_id + AND e.control_plane_request_id = v_request_id + FOR UPDATE; + IF NOT FOUND + OR operation.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR operation.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR operation.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR operation.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR operation.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR operation.game_session_owner_fence IS DISTINCT FROM p_game_session_fence + OR operation.preparation_input_digest IS DISTINCT FROM p_input_digest + OR operation.preparation_input_json IS DISTINCT FROM p_input_json + OR operation.world_execution_fence IS DISTINCT FROM p_world_execution_fence THEN + RAISE EXCEPTION 'World execution intent does not match the exact original full identity' + USING ERRCODE = '23514'; + END IF; + IF operation.operation_state = 'COMMITTED' THEN + -- The caller must perform a separate read-only exact terminal readback. No V35 call or + -- operation update occurs on this branch. + RETURN 0; + END IF; + IF operation.operation_state <> 'PENDING' OR NOT operation.execution_claimed THEN + RAISE EXCEPTION 'World execution intent is terminal or already in flight' + USING ERRCODE = '23514'; + END IF; + + PERFORM set_config('world.canonical_execution_namespace', operation.target_namespace, TRUE); + PERFORM set_config('world.canonical_execution_tenant', operation.canonical_tenant_id::TEXT, TRUE); + PERFORM set_config('world.canonical_execution_request', operation.control_plane_request_id, TRUE); + PERFORM set_config('world.canonical_execution_target', operation.canonical_game_instance_id::TEXT, TRUE); + PERFORM set_config('world.canonical_execution_fence', operation.world_execution_fence::TEXT, TRUE); + PERFORM set_config('world.canonical_execution_input_digest', operation.preparation_input_digest, TRUE); + UPDATE "${serviceSchema}".world_canonical_instance_execution e + SET operation_state = 'EXECUTING', active_transaction_id = txid_current() + WHERE e.target_namespace = operation.target_namespace + AND e.canonical_tenant_id = operation.canonical_tenant_id + AND e.control_plane_request_id = operation.control_plane_request_id; + RETURN operation.world_execution_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_begin_canonical_instance_execution(TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID, BIGINT) FROM PUBLIC; + +CREATE FUNCTION world_require_active_canonical_instance_execution( + p_input_json TEXT, p_input_digest TEXT +) RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; + original_tuple JSONB; + original_expiry TIMESTAMPTZ; +BEGIN + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = current_setting('world.canonical_execution_namespace', TRUE) + AND e.canonical_tenant_id::TEXT = current_setting('world.canonical_execution_tenant', TRUE) + AND e.control_plane_request_id = current_setting('world.canonical_execution_request', TRUE) + AND e.canonical_game_instance_id::TEXT = current_setting('world.canonical_execution_target', TRUE) + AND e.world_execution_fence::TEXT = current_setting('world.canonical_execution_fence', TRUE) + AND e.preparation_input_digest = p_input_digest + AND e.preparation_input_json = p_input_json + AND e.operation_state = 'EXECUTING' + AND e.active_transaction_id = txid_current(); + IF NOT FOUND THEN + RAISE EXCEPTION 'V35 requires the exact current World execution identity and fence' + USING ERRCODE = '23514'; + END IF; + original_tuple := convert_from(operation.original_post_authorization_tuple, 'UTF8')::JSONB; + original_expiry := (original_tuple->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt')::TIMESTAMPTZ; + -- This hook is inserted after V35's publication-owner, canonical-target, and request locks. + IF original_expiry <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession authorization expired before World execution admission' + USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_require_active_canonical_instance_execution(TEXT, TEXT) FROM PUBLIC; + +-- Preserve the reviewed V35/V40/V42/V61 source guards as an owner-private inner implementation. +ALTER FUNCTION world_prepare_canonical_instance(TEXT, TEXT) + RENAME TO world_prepare_canonical_instance_v61_impl; + +CREATE FUNCTION world_prepare_canonical_instance(p_input_json TEXT, p_input_digest TEXT) +RETURNS TABLE(world_instance_id BIGINT, private_game_instance_key BIGINT) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RETURN QUERY SELECT * + FROM "${serviceSchema}".world_prepare_canonical_instance_v61_impl(p_input_json, p_input_digest); +END; +$$; +REVOKE ALL ON FUNCTION world_prepare_canonical_instance(TEXT, TEXT) FROM PUBLIC; +REVOKE ALL ON FUNCTION world_prepare_canonical_instance_v61_impl(TEXT, TEXT) FROM PUBLIC; + +-- The ordinary application call path enters the operation lock before the V35 owner/publication +-- locks; the expiry hook above rechecks only after V35 has acquired all of its own locks. +DO $migration$ +DECLARE + preparation_function REGPROCEDURE := + '"${serviceSchema}".world_prepare_canonical_instance_v61_impl(text,text)'::REGPROCEDURE; + original_definition TEXT; + lock_anchor TEXT := $anchor$ SELECT * INTO prior FROM "${serviceSchema}".world_canonical_instance_preparation$anchor$; + lock_replacement TEXT := $replacement$ PERFORM "${serviceSchema}".world_require_active_canonical_instance_execution( + p_input_json, p_input_digest); + + SELECT * INTO prior FROM "${serviceSchema}".world_canonical_instance_preparation$replacement$; +BEGIN + SELECT pg_get_functiondef(preparation_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, lock_anchor, ''))) + / length(lock_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected one post-V61 canonical preparation prior-row lookup'; + END IF; + EXECUTE replace(original_definition, lock_anchor, lock_replacement); +END; +$migration$; + +CREATE FUNCTION world_execution_has_exact_materialized_result( + p_operation "${serviceSchema}".world_canonical_instance_execution, + p_world_instance_id BIGINT +) RETURNS BOOLEAN +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ + SELECT p_world_instance_id IS NOT NULL AND p_world_instance_id > 0 AND EXISTS ( + SELECT 1 + FROM world_canonical_instance_preparation p + JOIN world_canonical_instance_association a + ON a.canonical_game_instance_id = p.canonical_game_instance_id + AND a.world_instance_id = p.world_instance_id + WHERE p.canonical_game_instance_id = (p_operation).canonical_game_instance_id + AND p.target_namespace = (p_operation).target_namespace + AND p.canonical_tenant_id = (p_operation).canonical_tenant_id + AND p.control_plane_request_id = (p_operation).control_plane_request_id + AND p.input_digest = (p_operation).preparation_input_digest + AND p.input_json = (p_operation).preparation_input_json + AND p.world_instance_id = p_world_instance_id + AND a.canonical_target_namespace = (p_operation).target_namespace + AND a.canonical_tenant_id = (p_operation).canonical_tenant_id + AND a.control_plane_request_id = (p_operation).control_plane_request_id + AND a.game_template_id = (p_operation).game_template_id) +$$; +REVOKE ALL ON FUNCTION world_execution_has_exact_materialized_result("${serviceSchema}".world_canonical_instance_execution, BIGINT) FROM PUBLIC; + +CREATE FUNCTION world_commit_canonical_instance_execution(p_world_instance_id BIGINT) +RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = current_setting('world.canonical_execution_namespace', TRUE) + AND e.canonical_tenant_id::TEXT = current_setting('world.canonical_execution_tenant', TRUE) + AND e.control_plane_request_id = current_setting('world.canonical_execution_request', TRUE) + AND e.canonical_game_instance_id::TEXT = current_setting('world.canonical_execution_target', TRUE) + AND e.world_execution_fence::TEXT = current_setting('world.canonical_execution_fence', TRUE) + AND e.preparation_input_digest = current_setting('world.canonical_execution_input_digest', TRUE) + AND e.operation_state = 'EXECUTING' + AND e.active_transaction_id = txid_current() + FOR UPDATE; + IF NOT FOUND OR p_world_instance_id IS NULL OR p_world_instance_id <= 0 + OR NOT "${serviceSchema}".world_execution_has_exact_materialized_result( + operation, p_world_instance_id) THEN + RAISE EXCEPTION 'World execution cannot commit without its exact V35 preparation and V34 association' + USING ERRCODE = '23514'; + END IF; + UPDATE "${serviceSchema}".world_canonical_instance_execution e + SET operation_state = 'COMMITTED', active_transaction_id = NULL, + world_instance_id = p_world_instance_id, terminal_at = clock_timestamp() + WHERE e.target_namespace = operation.target_namespace + AND e.canonical_tenant_id = operation.canonical_tenant_id + AND e.control_plane_request_id = operation.control_plane_request_id; +END; +$$; +REVOKE ALL ON FUNCTION world_commit_canonical_instance_execution(BIGINT) FROM PUBLIC; + +CREATE FUNCTION world_abort_canonical_instance_execution( + p_target_namespace TEXT, p_canonical_tenant_id UUID, p_control_plane_request_id TEXT, + p_canonical_game_instance_id UUID, p_preparation_input_json TEXT, p_preparation_input_digest TEXT, + p_original_tuple BYTEA, p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT +) RETURNS TABLE(operation_state TEXT, world_execution_fence BIGINT, world_instance_id BIGINT) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; + tuple_value JSONB; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_preparation_input_json, p_preparation_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + IF p_original_tuple IS NULL OR p_preparation_input_digest !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Exact original identity is required for World abort' + USING ERRCODE = '23514'; + END IF; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + IF tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM p_control_plane_request_id + OR tuple_value->'scope'->>'targetNamespace' IS DISTINCT FROM p_target_namespace + OR tuple_value->'scope'->>'tenantId' IS DISTINCT FROM p_canonical_tenant_id::TEXT THEN + RAISE EXCEPTION 'World abort identity differs from the original scoped StartSession tuple' + USING ERRCODE = '23514'; + END IF; + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + p_target_namespace, p_canonical_tenant_id, p_control_plane_request_id, + p_canonical_game_instance_id); + PERFORM set_config('world.canonical_abort_namespace', p_target_namespace, TRUE); + PERFORM set_config('world.canonical_abort_tenant', p_canonical_tenant_id::TEXT, TRUE); + PERFORM set_config('world.canonical_abort_request', p_control_plane_request_id, TRUE); + PERFORM set_config('world.canonical_abort_target', p_canonical_game_instance_id::TEXT, TRUE); + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = p_target_namespace + AND e.canonical_tenant_id = p_canonical_tenant_id + AND e.control_plane_request_id = p_control_plane_request_id + FOR UPDATE; + IF NOT FOUND THEN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.canonical_game_instance_id = p_canonical_game_instance_id) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = p_canonical_game_instance_id + OR (p.target_namespace = p_target_namespace + AND p.canonical_tenant_id = p_canonical_tenant_id + AND p.control_plane_request_id = p_control_plane_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = p_canonical_game_instance_id + OR (a.canonical_target_namespace = p_target_namespace + AND a.canonical_tenant_id = p_canonical_tenant_id + AND a.control_plane_request_id = p_control_plane_request_id)) THEN + RAISE EXCEPTION 'Historical or conflicting World rows make missing-operation abort unresolved' + USING ERRCODE = '23514'; + END IF; + INSERT INTO "${serviceSchema}".world_canonical_instance_execution ( + target_namespace, canonical_tenant_id, control_plane_request_id, + canonical_game_instance_id, canonical_world_slug, game_template_id, + original_post_authorization_tuple, original_post_authorization_tuple_sha256, + account_world_participation_id, account_world_participation_fence, + game_session_owner_attempt_id, game_session_owner_fence, + preparation_input_digest, preparation_input_json, world_execution_fence, + operation_state, terminal_at) + VALUES ( + p_target_namespace, p_canonical_tenant_id, p_control_plane_request_id, + p_canonical_game_instance_id, + (p_preparation_input_json::JSONB->'identity'->>'worldSlug'), + (((p_preparation_input_json::JSONB->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT, + p_original_tuple, encode(sha256(p_original_tuple), 'hex'), + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, + p_preparation_input_digest, p_preparation_input_json, + nextval('"${serviceSchema}".world_canonical_instance_execution_fence_seq'), + 'ABORTED', clock_timestamp()) + RETURNING * INTO operation; + END IF; + IF operation.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR operation.canonical_world_slug IS DISTINCT FROM p_preparation_input_json::JSONB->'identity'->>'worldSlug' + OR operation.game_template_id IS DISTINCT FROM (((p_preparation_input_json::JSONB->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT + OR operation.preparation_input_digest IS DISTINCT FROM p_preparation_input_digest + OR operation.preparation_input_json IS DISTINCT FROM p_preparation_input_json + OR operation.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR operation.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR operation.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR operation.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR operation.game_session_owner_fence IS DISTINCT FROM p_game_session_fence THEN + RAISE EXCEPTION 'World abort differs from the exact original full execution identity' + USING ERRCODE = '23514'; + END IF; + IF operation.operation_state = 'PENDING' THEN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = operation.canonical_game_instance_id + OR (p.target_namespace = operation.target_namespace + AND p.canonical_tenant_id = operation.canonical_tenant_id + AND p.control_plane_request_id = operation.control_plane_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = operation.canonical_game_instance_id + OR (a.canonical_target_namespace = operation.target_namespace + AND a.canonical_tenant_id = operation.canonical_tenant_id + AND a.control_plane_request_id = operation.control_plane_request_id)) THEN + RAISE EXCEPTION 'World has unbound materialization rows; operation remains unresolved' + USING ERRCODE = '23514'; + END IF; + UPDATE "${serviceSchema}".world_canonical_instance_execution e + SET operation_state = 'ABORTED', terminal_at = clock_timestamp() + WHERE e.target_namespace = operation.target_namespace + AND e.canonical_tenant_id = operation.canonical_tenant_id + AND e.control_plane_request_id = operation.control_plane_request_id; + operation.operation_state := 'ABORTED'; + ELSIF operation.operation_state NOT IN ('COMMITTED', 'ABORTED') THEN + RAISE EXCEPTION 'World execution is not in a durable terminal state' + USING ERRCODE = '23514'; + END IF; + operation_state := operation.operation_state; + world_execution_fence := operation.world_execution_fence; + world_instance_id := operation.world_instance_id; + RETURN NEXT; +END; +$$; +REVOKE ALL ON FUNCTION world_abort_canonical_instance_execution(TEXT, UUID, TEXT, UUID, TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT) FROM PUBLIC; + +CREATE FUNCTION world_enforce_canonical_instance_execution_transition() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF TG_OP = 'UPDATE' THEN + IF NEW.target_namespace IS DISTINCT FROM OLD.target_namespace + OR NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.control_plane_request_id IS DISTINCT FROM OLD.control_plane_request_id + OR NEW.canonical_game_instance_id IS DISTINCT FROM OLD.canonical_game_instance_id + OR NEW.canonical_world_slug IS DISTINCT FROM OLD.canonical_world_slug + OR NEW.game_template_id IS DISTINCT FROM OLD.game_template_id + OR NEW.original_post_authorization_tuple IS DISTINCT FROM OLD.original_post_authorization_tuple + OR NEW.original_post_authorization_tuple_sha256 IS DISTINCT FROM OLD.original_post_authorization_tuple_sha256 + OR NEW.account_world_participation_id IS DISTINCT FROM OLD.account_world_participation_id + OR NEW.account_world_participation_fence IS DISTINCT FROM OLD.account_world_participation_fence + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM OLD.game_session_owner_attempt_id + OR NEW.game_session_owner_fence IS DISTINCT FROM OLD.game_session_owner_fence + OR NEW.preparation_input_digest IS DISTINCT FROM OLD.preparation_input_digest + OR NEW.preparation_input_json IS DISTINCT FROM OLD.preparation_input_json + OR NEW.world_execution_fence IS DISTINCT FROM OLD.world_execution_fence + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'World execution identity is immutable and terminal states cannot be reopened' + USING ERRCODE = '23514'; + END IF; + IF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'PENDING' THEN + IF OLD.execution_claimed OR NOT NEW.execution_claimed + OR OLD.active_transaction_id IS DISTINCT FROM NEW.active_transaction_id + OR OLD.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR OLD.terminal_at IS DISTINCT FROM NEW.terminal_at + OR current_setting('world.canonical_claim_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_claim_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_claim_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_claim_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_claim_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT THEN + RAISE EXCEPTION 'World execution intent may be claimed only once by its exact serialization fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'EXECUTING' THEN + IF NOT OLD.execution_claimed OR NOT NEW.execution_claimed + OR NEW.active_transaction_id IS DISTINCT FROM txid_current() + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NOT NULL + OR current_setting('world.canonical_execution_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_execution_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_execution_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_execution_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_execution_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT + OR current_setting('world.canonical_execution_input_digest', TRUE) IS DISTINCT FROM NEW.preparation_input_digest THEN + RAISE EXCEPTION 'World EXECUTING state requires its exact current transaction and execution fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'ABORTED' THEN + IF NEW.execution_claimed IS DISTINCT FROM OLD.execution_claimed + OR NEW.active_transaction_id IS NOT NULL OR NEW.world_instance_id IS NOT NULL + OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_abort_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_abort_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_abort_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_abort_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'World ABORTED state requires its exact serialized terminal fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'EXECUTING' AND NEW.operation_state = 'COMMITTED' THEN + IF OLD.active_transaction_id IS DISTINCT FROM txid_current() + OR NEW.execution_claimed IS DISTINCT FROM TRUE + OR NEW.active_transaction_id IS NOT NULL + OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_execution_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_execution_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_execution_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_execution_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_execution_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT + OR current_setting('world.canonical_execution_input_digest', TRUE) IS DISTINCT FROM NEW.preparation_input_digest + OR NOT "${serviceSchema}".world_execution_has_exact_materialized_result(NEW, NEW.world_instance_id) THEN + RAISE EXCEPTION 'World COMMITTED state requires the current exact V35 preparation and V34 association' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'World execution state transition is not permitted' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.operation_state = 'PENDING' THEN + IF NEW.execution_claimed OR NEW.active_transaction_id IS NOT NULL + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'World execution intent must be born unclaimed and PENDING' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.operation_state = 'ABORTED' THEN + IF NEW.execution_claimed OR NEW.active_transaction_id IS NOT NULL + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_abort_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_abort_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_abort_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_abort_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'A born-ABORTED World operation requires its exact serialized abort fence' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'World execution rows must be born PENDING or terminally ABORTED' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_canonical_instance_execution_transition + BEFORE INSERT OR UPDATE ON world_canonical_instance_execution + FOR EACH ROW EXECUTE FUNCTION world_enforce_canonical_instance_execution_transition(); +REVOKE ALL ON FUNCTION world_enforce_canonical_instance_execution_transition() FROM PUBLIC; + +CREATE FUNCTION world_require_canonical_instance_execution_terminal() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + final_state TEXT; +BEGIN + SELECT operation_state INTO final_state + FROM world_canonical_instance_execution + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND control_plane_request_id = NEW.control_plane_request_id; + IF final_state IS NULL OR final_state = 'EXECUTING' THEN + RAISE EXCEPTION 'World EXECUTING state cannot commit without exact terminal settlement' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER trg_world_canonical_instance_execution_no_inflight_commit + AFTER INSERT OR UPDATE ON world_canonical_instance_execution + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_canonical_instance_execution_terminal(); +REVOKE ALL ON FUNCTION world_require_canonical_instance_execution_terminal() FROM PUBLIC; + +CREATE FUNCTION world_guard_canonical_instance_association_execution() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = current_setting('world.canonical_execution_namespace', TRUE) + AND e.canonical_tenant_id::TEXT = current_setting('world.canonical_execution_tenant', TRUE) + AND e.control_plane_request_id = current_setting('world.canonical_execution_request', TRUE) + AND e.canonical_game_instance_id::TEXT = current_setting('world.canonical_execution_target', TRUE) + AND e.world_execution_fence::TEXT = current_setting('world.canonical_execution_fence', TRUE) + AND e.operation_state = 'EXECUTING' + AND e.active_transaction_id = txid_current() + FOR KEY SHARE; + IF NOT FOUND OR NEW.canonical_game_instance_id IS DISTINCT FROM operation.canonical_game_instance_id + OR NEW.canonical_target_namespace IS DISTINCT FROM operation.target_namespace + OR NEW.canonical_tenant_id IS DISTINCT FROM operation.canonical_tenant_id + OR NEW.control_plane_request_id IS DISTINCT FROM operation.control_plane_request_id + OR NEW.game_template_id IS DISTINCT FROM operation.game_template_id + OR NEW.world_instance_id IS NULL + OR NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = operation.canonical_game_instance_id + AND p.target_namespace = operation.target_namespace + AND p.canonical_tenant_id = operation.canonical_tenant_id + AND p.control_plane_request_id = operation.control_plane_request_id + AND p.input_digest = operation.preparation_input_digest + AND p.input_json = operation.preparation_input_json + AND p.world_instance_id = NEW.world_instance_id) THEN + RAISE EXCEPTION 'V34 association requires the exact active World execution identity and fence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_world_canonical_instance_association_00_execution + BEFORE INSERT ON world_canonical_instance_association + FOR EACH ROW EXECUTE FUNCTION world_guard_canonical_instance_association_execution(); +REVOKE ALL ON FUNCTION world_guard_canonical_instance_association_execution() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index faf7bde733..cb6e63dea1 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -14,6 +14,8 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.time.Duration; +import java.time.Instant; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; @@ -29,6 +31,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; @@ -155,6 +158,8 @@ static void configure(DynamicPropertyRegistry registry) { private WorldCanonicalInstanceAssociationRepository associationRepository; private final Map frozenPlans = new java.util.HashMap<>(); + private final Map executionIdentities = + new java.util.HashMap<>(); @BeforeEach void createRepositories() { @@ -504,9 +509,11 @@ void exactRetryReusesOriginalAssociationAfterReadMetadataChangeWithoutLifecycleM Fixture fixture = fixture(); UUID canonicalGameInstanceId = UUID.randomUUID(); UUID playableStateNamespaceId = UUID.randomUUID(); - WorldCanonicalInstancePreparation.Result originalPreparation = - prepareCanonicalWorldRow( + WorldCanonicalInstancePreparation.Input originalInput = + preparationInput( fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); + WorldCanonicalInstancePreparation.Result originalPreparation = + preparationService(() -> {}).prepare(originalInput); long worldInstanceId = originalPreparation.association().worldInstanceId(); WorldCanonicalInstanceAssociation.Claim originalClaim = claim( @@ -522,9 +529,8 @@ void exactRetryReusesOriginalAssociationAfterReadMetadataChangeWithoutLifecycleM WorldCanonicalInstanceAssociation original = associationRepository.readOwnerAssociation(canonicalGameInstanceId).orElseThrow(); - // This is only a fresh, synthetic Game Session observation/read correlation. No World - // lifecycle owner operation is forged; the current guarded lifecycle transition remains a - // separate unimplemented execution path. + // These request/status/version fields are observation-only and intentionally omitted from the + // canonical immutable preparation input. Re-reading them cannot mutate the retained World row. WorldCanonicalInstancePreparation.Result changedObservation = prepareCanonicalWorldRow( fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_RETRIED_FIXTURE", 2L); @@ -1008,12 +1014,20 @@ void rollsBackCompletePreparationWhenHeldCommitAuthorityIsLostBeforeCommit() { preparationInput( fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); AtomicInteger heldChecks = new AtomicInteger(); + AtomicReference executionIdentity = + new AtomicReference<>(); WorldCanonicalInstancePreparationService service = preparationService( () -> { - if (heldChecks.incrementAndGet() == 3) { + if (heldChecks.incrementAndGet() == 8) { throw new IllegalStateException("synthetic held authority lost before commit"); } + }, + exactInput -> { + WorldCanonicalInstanceExecutionIdentity created = + WorldCanonicalInstanceExecutionTestFixtures.identity(exactInput); + executionIdentity.set(created); + return created; }); assertThatThrownBy(() -> service.prepare(input)) @@ -1028,6 +1042,572 @@ void rollsBackCompletePreparationWhenHeldCommitAuthorityIsLostBeforeCommit() { "SELECT id FROM world_instance WHERE canonical_game_instance_id = ?", canonicalGameInstanceId)) .isNull(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_state FROM world_canonical_instance_execution " + + "WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)) + .get("operation_state", String.class)) + .isEqualTo("PENDING"); + + WorldCanonicalInstanceExecutionIdentity retainedIdentity = executionIdentity.get(); + assertThatThrownBy( + () -> preparationService(() -> {}, ignored -> retainedIdentity).prepare(input)) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class) + .hasMessageContaining("PENDING"); + assertThat(preparationCount(canonicalGameInstanceId)).isZero(); + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + assertThat(preparationRepository().recordDurableAbort(retainedIdentity).state()) + .isEqualTo(WorldCanonicalInstancePreparationRepository.ExecutionState.ABORTED); + assertThat(preparationRepository().readExactExecution(retainedIdentity).operation()) + .hasValueSatisfying( + operation -> + assertThat(operation.state()) + .isEqualTo(WorldCanonicalInstancePreparationRepository.ExecutionState.ABORTED)); + assertThatThrownBy( + () -> preparationService(() -> {}, ignored -> retainedIdentity).prepare(input)) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class) + .hasMessageContaining("ABORTED"); + } + + @Test + void exactIdentitySubstitutionIsRejectedBeforeAnyNewSourceOrWriterWork() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Input input = + preparationInput(fixture, canonicalGameInstanceId, UUID.randomUUID(), "GS_FIXTURE", 1L); + WorldCanonicalInstanceExecutionIdentity exactIdentity = + WorldCanonicalInstanceExecutionTestFixtures.identity(input); + WorldCanonicalInstancePreparation.Result committed = + preparationService(() -> {}, ignored -> exactIdentity).prepare(input); + + WorldCanonicalInstanceExecutionIdentity substitutedIdentity = + new WorldCanonicalInstanceExecutionIdentity( + exactIdentity.originalPostAuthorizationTuple(), + UUID.randomUUID(), + exactIdentity.accountWorldParticipationFence(), + exactIdentity.gameSessionOwnerAttemptId(), + exactIdentity.gameSessionOwnerFence(), + exactIdentity.canonicalGameInstanceId(), + exactIdentity.preparationInputJson()); + WorldCanonicalInstanceExecutionIdentity changedTupleIdentity = + new WorldCanonicalInstanceExecutionIdentity( + WorldCanonicalInstanceExecutionTestFixtures.identity(input) + .originalPostAuthorizationTuple(), + exactIdentity.accountWorldParticipationId(), + exactIdentity.accountWorldParticipationFence(), + exactIdentity.gameSessionOwnerAttemptId(), + exactIdentity.gameSessionOwnerFence(), + exactIdentity.canonicalGameInstanceId(), + exactIdentity.preparationInputJson()); + WorldCanonicalInstanceExecutionIdentity changedAccountFence = + new WorldCanonicalInstanceExecutionIdentity( + exactIdentity.originalPostAuthorizationTuple(), + exactIdentity.accountWorldParticipationId(), + exactIdentity.accountWorldParticipationFence() + 1L, + exactIdentity.gameSessionOwnerAttemptId(), + exactIdentity.gameSessionOwnerFence(), + exactIdentity.canonicalGameInstanceId(), + exactIdentity.preparationInputJson()); + WorldCanonicalInstanceExecutionIdentity changedGameSessionAttempt = + new WorldCanonicalInstanceExecutionIdentity( + exactIdentity.originalPostAuthorizationTuple(), + exactIdentity.accountWorldParticipationId(), + exactIdentity.accountWorldParticipationFence(), + UUID.randomUUID(), + exactIdentity.gameSessionOwnerFence(), + exactIdentity.canonicalGameInstanceId(), + exactIdentity.preparationInputJson()); + WorldCanonicalInstanceExecutionIdentity changedGameSessionFence = + new WorldCanonicalInstanceExecutionIdentity( + exactIdentity.originalPostAuthorizationTuple(), + exactIdentity.accountWorldParticipationId(), + exactIdentity.accountWorldParticipationFence(), + exactIdentity.gameSessionOwnerAttemptId(), + exactIdentity.gameSessionOwnerFence() + 1L, + exactIdentity.canonicalGameInstanceId(), + exactIdentity.preparationInputJson()); + for (WorldCanonicalInstanceExecutionIdentity substituted : + List.of( + substitutedIdentity, + changedTupleIdentity, + changedAccountFence, + changedGameSessionAttempt, + changedGameSessionFence)) { + assertThatThrownBy(() -> preparationService(() -> {}, ignored -> substituted).prepare(input)) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class) + .hasMessageContaining("full identity"); + } + + WorldCanonicalInstancePreparation.Input substitutedInput = + preparationInput(fixture, canonicalGameInstanceId, UUID.randomUUID(), "GS_FIXTURE", 1L); + WorldCanonicalInstanceExecutionIdentity substitutedInputIdentity = + new WorldCanonicalInstanceExecutionIdentity( + exactIdentity.originalPostAuthorizationTuple(), + exactIdentity.accountWorldParticipationId(), + exactIdentity.accountWorldParticipationFence(), + exactIdentity.gameSessionOwnerAttemptId(), + exactIdentity.gameSessionOwnerFence(), + exactIdentity.canonicalGameInstanceId(), + WorldCanonicalInstancePreparationRepository.inputJson(substitutedInput)); + assertThatThrownBy( + () -> + preparationService(() -> {}, ignored -> substitutedInputIdentity) + .prepare(substitutedInput)) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class) + .hasMessageContaining("full identity"); + + assertThat(committed.association().identity().canonicalGameInstanceId()) + .isEqualTo(canonicalGameInstanceId); + } + + @Test + void worldExecutionFenceIsMonotonicAndDistinctFromSyntheticSourceFences() { + Fixture fixture = fixture(); + WorldCanonicalInstancePreparation.Input firstInput = + preparationInput(fixture, UUID.randomUUID(), UUID.randomUUID(), "GS_FENCE_ONE", 1L); + WorldCanonicalInstancePreparation.Input secondInput = + preparationInput(fixture, UUID.randomUUID(), UUID.randomUUID(), "GS_FENCE_TWO", 1L); + WorldCanonicalInstanceExecutionIdentity firstIdentity = + withLargeSyntheticSourceFences( + WorldCanonicalInstanceExecutionTestFixtures.identity(firstInput)); + WorldCanonicalInstanceExecutionIdentity secondIdentity = + withLargeSyntheticSourceFences( + WorldCanonicalInstanceExecutionTestFixtures.identity(secondInput)); + + preparationService(() -> {}, ignored -> firstIdentity).prepare(firstInput); + preparationService(() -> {}, ignored -> secondIdentity).prepare(secondInput); + long firstWorldFence = + preparationRepository() + .readExactExecution(firstIdentity) + .operation() + .orElseThrow() + .worldExecutionFence(); + long secondWorldFence = + preparationRepository() + .readExactExecution(secondIdentity) + .operation() + .orElseThrow() + .worldExecutionFence(); + + assertThat(secondWorldFence).isGreaterThan(firstWorldFence); + assertThat(firstWorldFence) + .isNotEqualTo(firstIdentity.accountWorldParticipationFence()) + .isNotEqualTo(firstIdentity.gameSessionOwnerFence()); + assertThat(secondWorldFence) + .isNotEqualTo(secondIdentity.accountWorldParticipationFence()) + .isNotEqualTo(secondIdentity.gameSessionOwnerFence()); + } + + @Test + void durableAbortBlocksFreshServiceV35AndV34Writers() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Input input = + preparationInput( + fixture, canonicalGameInstanceId, UUID.randomUUID(), "GS_ABORT_FIXTURE", 1L); + WorldCanonicalInstanceExecutionIdentity identity = + WorldCanonicalInstanceExecutionTestFixtures.identity(input); + + assertThat(preparationRepository().recordDurableAbort(identity).state()) + .isEqualTo(WorldCanonicalInstancePreparationRepository.ExecutionState.ABORTED); + assertThatThrownBy(() -> preparationService(() -> {}, ignored -> identity).prepare(input)) + .isInstanceOf( + WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class) + .hasMessageContaining("ABORTED"); + + String inputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + String inputDigest = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT 'sha256:' || encode(sha256(convert_to(?, 'UTF8')), 'hex')", inputJson)) + .get(0, String.class); + assertThatThrownBy( + () -> + dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?, ?)", inputJson, inputDigest)) + .isInstanceOf(DataAccessException.class) + .rootCause() + .hasMessageContaining("exact current World execution identity and fence"); + assertThatThrownBy( + () -> dsl.execute("INSERT INTO world_canonical_instance_association DEFAULT VALUES")) + .isInstanceOf(DataAccessException.class) + .rootCause() + .hasMessageContaining("exact active World execution identity and fence"); + assertThat(preparationCount(canonicalGameInstanceId)).isZero(); + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + assertThat( + dsl.fetchOne( + "SELECT id FROM world_instance WHERE canonical_game_instance_id = ?", + canonicalGameInstanceId)) + .isNull(); + } + + @Test + void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { + Fixture fixture = fixture(); + WorldCanonicalInstancePreparation.Input input = + preparationInput(fixture, UUID.randomUUID(), UUID.randomUUID(), "GS_DIRECT_FIXTURE", 1L); + WorldCanonicalInstanceExecutionIdentity identity = + WorldCanonicalInstanceExecutionTestFixtures.identity(input); + String inputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + String inputDigest = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT 'sha256:' || encode(sha256(convert_to(?, 'UTF8')), 'hex')", inputJson)) + .get(0, String.class); + + assertThatThrownBy( + () -> + dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?, ?)", inputJson, inputDigest)) + .isInstanceOf(DataAccessException.class) + .rootCause() + .hasMessageContaining("exact current World execution identity and fence"); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + Record intentRow = + dsl.fetchOne( + "SELECT world_persist_canonical_instance_execution_intent(?, ?, ?, ?, ?, ?, ?, ?)", + inputJson, + inputDigest, + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId()); + Long intentFence = + intentRow == null ? null : intentRow.get(0, Long.class); + Record claimRow = + dsl.fetchOne( + "SELECT world_claim_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?)", + inputJson, + inputDigest, + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId()); + Long claimFence = claimRow == null ? null : claimRow.get(0, Long.class); + Record executionRow = + dsl.fetchOne( + "SELECT world_begin_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?, ?)", + inputJson, + inputDigest, + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId(), + intentFence); + Long executionFence = + executionRow == null ? null : executionRow.get(0, Long.class); + assertThat(claimFence).isEqualTo(intentFence); + assertThat(executionFence).isEqualTo(intentFence); + dsl.fetchValue( + "SELECT set_config('world.canonical_execution_fence', ?, TRUE)", + Long.toString(intentFence + 1L)); + return dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?, ?)", + inputJson, + inputDigest); + })) + .isInstanceOf(DataAccessException.class) + .rootCause() + .hasMessageContaining("exact current World execution identity and fence"); + assertThat(preparationCount(identity.canonicalGameInstanceId())).isZero(); + assertThat(associationCount(identity.canonicalGameInstanceId())).isZero(); + } + + @Test + void executingCannotCommitInflightOrBeForgedCommittedWithoutExactV35AndV34Rows() { + Fixture fixture = fixture(); + WorldCanonicalInstancePreparation.Input input = + preparationInput(fixture, UUID.randomUUID(), UUID.randomUUID(), "GS_TERMINAL_FIXTURE", 1L); + WorldCanonicalInstanceExecutionIdentity identity = + WorldCanonicalInstanceExecutionTestFixtures.identity(input); + String inputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + String inputDigest = executionInputDigest(inputJson); + long executionFence = retainAndClaimExecutionIntent(inputJson, inputDigest, identity); + long unrelatedWorldRow = insertLegacyWorldRow(fixture, positiveLong()); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + beginExecution(inputJson, inputDigest, identity, executionFence); + return null; + })) + .rootCause() + .hasMessageContaining("EXECUTING state cannot commit without exact terminal settlement"); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + beginExecution(inputJson, inputDigest, identity, executionFence); + dsl.execute( + "UPDATE world_canonical_instance_execution " + + "SET operation_state='COMMITTED', active_transaction_id=NULL, " + + "world_instance_id=?, terminal_at=clock_timestamp() " + + "WHERE target_namespace=? AND canonical_tenant_id=? " + + "AND control_plane_request_id=?", + unrelatedWorldRow, + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.controlPlaneRequestId()); + return null; + })) + .rootCause() + .hasMessageContaining("exact V35 preparation and V34 association"); + + assertThat(preparationRepository().recordDurableAbort(identity).state()) + .isEqualTo(WorldCanonicalInstancePreparationRepository.ExecutionState.ABORTED); + } + + @Test + void admittedExecutionMayFinishAfterIngressExpiryAndThenUsesReadOnlyTerminalRecovery() { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Input input = + preparationInput( + fixture, canonicalGameInstanceId, UUID.randomUUID(), "GS_EXPIRY_FIXTURE", 1L); + Instant originalExpiry = Instant.now().plusSeconds(15); + WorldCanonicalInstanceExecutionIdentity identity = + WorldCanonicalInstanceExecutionTestFixtures.identity(input, originalExpiry); + AtomicInteger heldChecks = new AtomicInteger(); + WorldCanonicalInstancePreparationService service = + preparationService( + () -> { + if (heldChecks.incrementAndGet() == 8) { + // V35 has passed its post-lock DB-clock admission check and V34 has been inserted. + // Keep the one admitted SQL transaction uninterrupted across ingress expiry. + awaitInstant(originalExpiry.plusMillis(100)); + } + }, + ignored -> identity); + + WorldCanonicalInstancePreparation.Result committed = service.prepare(input); + + assertThat(Instant.now()).isAfter(originalExpiry); + assertThat(committed.association().identity().canonicalGameInstanceId()) + .isEqualTo(canonicalGameInstanceId); + long retainedFence = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT world_execution_fence FROM world_canonical_instance_execution " + + "WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)) + .get("world_execution_fence", Long.class); + WorldCanonicalInstancePreparationRepository repository = preparationRepository(); + WorldCanonicalInstancePreparationRepository.ExecutionLookup exactTerminal = + repository.readExactExecution(identity); + assertThat(exactTerminal.originalAuthorizationValidAtRead()).isFalse(); + assertThat(exactTerminal.operation()) + .hasValueSatisfying( + operation -> + assertThat(operation.state()) + .isEqualTo( + WorldCanonicalInstancePreparationRepository.ExecutionState.COMMITTED)); + WorldCanonicalInstancePreparation.Result recovered = + repository.readOwnerPreparation(input).orElseThrow(); + assertThat(recovered).isEqualTo(committed); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT world_execution_fence, operation_state " + + "FROM world_canonical_instance_execution WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)) + .get("world_execution_fence", Long.class)) + .isEqualTo(retainedFence); + } + + @Test + void expiryIsRecheckedByDatabaseClockAfterWaitingOnV35PublicationOwnerLock() throws Exception { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Input input = + preparationInput( + fixture, canonicalGameInstanceId, UUID.randomUUID(), "GS_WAIT_FIXTURE", 1L); + Instant originalExpiry = Instant.now().plusSeconds(10); + WorldCanonicalInstanceExecutionIdentity identity = + WorldCanonicalInstanceExecutionTestFixtures.identity(input, originalExpiry); + CountDownLatch ownerRowLocked = new CountDownLatch(1); + CountDownLatch releaseOwnerRow = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future blocker = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + dsl.fetch( + "SELECT 1 FROM world_design_publication_fence_owner " + + "WHERE local_tenant_key=? AND version_id=? FOR UPDATE", + fixture.source().receipt().localTenantKey(), + fixture.versionIdentity().localVersionKey()); + ownerRowLocked.countDown(); + await(releaseOwnerRow); + return null; + })); + assertThat(ownerRowLocked.await(10, TimeUnit.SECONDS)).isTrue(); + Future attempt = + executor.submit( + () -> + preparationService(Duration.ofSeconds(30), () -> {}, ignored -> identity) + .prepare(input)); + awaitWorldPreparationLockWait(); + awaitInstant(originalExpiry.plusMillis(100)); + releaseOwnerRow.countDown(); + + assertThatThrownBy(attempt::get) + .rootCause() + .hasMessageContaining("expired before World execution admission"); + blocker.get(10, TimeUnit.SECONDS); + } finally { + releaseOwnerRow.countDown(); + } + + assertThat(preparationCount(canonicalGameInstanceId)).isZero(); + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_state FROM world_canonical_instance_execution " + + "WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)) + .get("operation_state", String.class)) + .isEqualTo("PENDING"); + assertThat(preparationRepository().recordDurableAbort(identity).state()) + .isEqualTo(WorldCanonicalInstancePreparationRepository.ExecutionState.ABORTED); + } + + @Test + void databaseLockTimeoutCancelsExecutionWithoutInventingAbortOrRetry() throws Exception { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Input input = + preparationInput( + fixture, canonicalGameInstanceId, UUID.randomUUID(), "GS_TIMEOUT_FIXTURE", 1L); + WorldCanonicalInstanceExecutionIdentity identity = + WorldCanonicalInstanceExecutionTestFixtures.identity(input, Instant.now().plusSeconds(60)); + CountDownLatch ownerRowLocked = new CountDownLatch(1); + CountDownLatch releaseOwnerRow = new CountDownLatch(1); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future blocker = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + dsl.fetch( + "SELECT 1 FROM world_design_publication_fence_owner " + + "WHERE local_tenant_key=? AND version_id=? FOR UPDATE", + fixture.source().receipt().localTenantKey(), + fixture.versionIdentity().localVersionKey()); + ownerRowLocked.countDown(); + await(releaseOwnerRow); + return null; + })); + assertThat(ownerRowLocked.await(10, TimeUnit.SECONDS)).isTrue(); + Future attempt = + executor.submit( + () -> + preparationService(Duration.ofSeconds(2), () -> {}, ignored -> identity) + .prepare(input)); + awaitWorldPreparationLockWait(); + assertThatThrownBy(attempt::get) + .satisfies( + failure -> + assertThat(sqlState(failure)) + .as("database-local lock/statement timeout must cancel the blocked writer") + .isIn("55P03", "57014")); + releaseOwnerRow.countDown(); + blocker.get(10, TimeUnit.SECONDS); + } finally { + releaseOwnerRow.countDown(); + } + + assertThat(preparationCount(canonicalGameInstanceId)).isZero(); + assertThat(associationCount(canonicalGameInstanceId)).isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_state FROM world_canonical_instance_execution " + + "WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)) + .get("operation_state", String.class)) + .isEqualTo("PENDING"); + assertThat(preparationRepository().recordDurableAbort(identity).state()) + .isEqualTo(WorldCanonicalInstancePreparationRepository.ExecutionState.ABORTED); + } + + @Test + void concurrentExecutionAndDurableAbortSerializeToCommittedResult() throws Exception { + Fixture fixture = fixture(); + UUID canonicalGameInstanceId = UUID.randomUUID(); + WorldCanonicalInstancePreparation.Input input = + preparationInput( + fixture, canonicalGameInstanceId, UUID.randomUUID(), "GS_RACE_FIXTURE", 1L); + WorldCanonicalInstanceExecutionIdentity identity = + WorldCanonicalInstanceExecutionTestFixtures.identity(input); + AtomicInteger heldChecks = new AtomicInteger(); + CountDownLatch associated = new CountDownLatch(1); + CountDownLatch releaseExecution = new CountDownLatch(1); + WorldCanonicalInstancePreparationService service = + preparationService( + () -> { + if (heldChecks.incrementAndGet() == 8) { + associated.countDown(); + await(releaseExecution); + } + }, + ignored -> identity); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future execution = + executor.submit(() -> service.prepare(input)); + assertThat(associated.await(10, TimeUnit.SECONDS)).isTrue(); + CountDownLatch abortStarted = new CountDownLatch(1); + Future abort = + executor.submit( + () -> { + abortStarted.countDown(); + return preparationRepository().recordDurableAbort(identity); + }); + assertThat(abortStarted.await(10, TimeUnit.SECONDS)).isTrue(); + Thread.sleep(150); + assertThat(abort).isNotDone(); + releaseExecution.countDown(); + + assertThat( + execution + .get(20, TimeUnit.SECONDS) + .association() + .identity() + .canonicalGameInstanceId()) + .isEqualTo(canonicalGameInstanceId); + assertThat(abort.get(20, TimeUnit.SECONDS).state()) + .isEqualTo(WorldCanonicalInstancePreparationRepository.ExecutionState.COMMITTED); + } finally { + releaseExecution.countDown(); + } } @Test @@ -1039,8 +1619,12 @@ void concurrentExactPreparationsForTheSameCanonicalGameInstanceRetainOneOwnerRes WorldCanonicalInstancePreparation.Input exactInput = preparationInput( fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); - WorldCanonicalInstancePreparationService firstService = preparationService(() -> {}); - WorldCanonicalInstancePreparationService secondService = preparationService(() -> {}); + WorldCanonicalInstanceExecutionIdentity exactIdentity = + WorldCanonicalInstanceExecutionTestFixtures.identity(exactInput); + WorldCanonicalInstancePreparationService firstService = + preparationService(() -> {}, ignored -> exactIdentity); + WorldCanonicalInstancePreparationService secondService = + preparationService(() -> {}, ignored -> exactIdentity); CountDownLatch ready = new CountDownLatch(2); CountDownLatch start = new CountDownLatch(1); @@ -1353,21 +1937,53 @@ private WorldCanonicalInstancePreparation.Input preparationInput( } private WorldCanonicalInstancePreparationService preparationService(Runnable heldCheck) { - WorldCanonicalFrozenTopologyRepository frozenRepository = - new WorldCanonicalFrozenTopologyRepository( - dsl, - graphSnapshots, - new WorldDraftTopologyCommitRepository(dsl, publicationFence, objectMapper), - digestService); + return preparationService(heldCheck, this::executionIdentity); + } + + private WorldCanonicalInstancePreparationService preparationService( + Runnable heldCheck, + Function + identityFactory) { + return preparationService(Duration.ofSeconds(30), heldCheck, identityFactory); + } + + private WorldCanonicalInstanceExecutionIdentity executionIdentity( + WorldCanonicalInstancePreparation.Input input) { + return executionIdentities.computeIfAbsent( + WorldCanonicalInstancePreparationRepository.inputJson(input), + ignored -> WorldCanonicalInstanceExecutionTestFixtures.identity(input)); + } + + private WorldCanonicalInstanceExecutionIdentity withLargeSyntheticSourceFences( + WorldCanonicalInstanceExecutionIdentity identity) { + return new WorldCanonicalInstanceExecutionIdentity( + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + Long.MAX_VALUE - 2, + identity.gameSessionOwnerAttemptId(), + Long.MAX_VALUE - 1, + identity.canonicalGameInstanceId(), + identity.preparationInputJson()); + } + + private WorldCanonicalInstancePreparationService preparationService( + Duration transactionTimeout, + Runnable heldCheck, + Function + identityFactory) { WorldCanonicalInstancePreparationRepository preparationRepository = - new WorldCanonicalInstancePreparationRepository( - dsl, transactionManager, associationRepository, frozenRepository); + preparationRepository(transactionTimeout); // Synthetic fixture handle only. This does not authenticate GS/GD source or delivery, prove // APPLIED/IN_SYNC, or supply Account authority. return new WorldCanonicalInstancePreparationService( preparationRepository, input -> new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + @Override + public WorldCanonicalInstanceExecutionIdentity executionIdentity() { + return identityFactory.apply(input); + } + @Override public void requireHeld() { heldCheck.run(); @@ -1378,6 +1994,88 @@ public void close() {} }); } + private WorldCanonicalInstancePreparationRepository preparationRepository() { + return preparationRepository(Duration.ofSeconds(30)); + } + + private long retainAndClaimExecutionIntent( + String inputJson, String inputDigest, WorldCanonicalInstanceExecutionIdentity identity) { + Long fence = + ownerTransaction() + .execute( + status -> { + Record intentRow = + dsl.fetchOne( + "SELECT world_persist_canonical_instance_execution_intent(?, ?, ?, ?, ?, ?, ?, ?)", + inputJson, + inputDigest, + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId()); + Long retainedFence = intentRow == null ? null : intentRow.get(0, Long.class); + Record claimRow = + dsl.fetchOne( + "SELECT world_claim_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?)", + inputJson, + inputDigest, + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId()); + Long claimedFence = claimRow == null ? null : claimRow.get(0, Long.class); + assertThat(claimedFence).isEqualTo(retainedFence); + return retainedFence; + }); + return Objects.requireNonNull(fence, "Synthetic execution intent returned no World fence"); + } + + private void beginExecution( + String inputJson, + String inputDigest, + WorldCanonicalInstanceExecutionIdentity identity, + long executionFence) { + Record begunRow = + dsl.fetchOne( + "SELECT world_begin_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?, ?)", + inputJson, + inputDigest, + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId(), + executionFence); + Long begunFence = begunRow == null ? null : begunRow.get(0, Long.class); + assertThat(begunFence).isEqualTo(executionFence); + } + + private String executionInputDigest(String inputJson) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT 'sha256:' || encode(sha256(convert_to(?, 'UTF8')), 'hex')", inputJson)) + .get(0, String.class); + } + + private WorldCanonicalInstancePreparationRepository preparationRepository( + Duration transactionTimeout) { + WorldCanonicalFrozenTopologyRepository frozenRepository = + new WorldCanonicalFrozenTopologyRepository( + dsl, + graphSnapshots, + new WorldDraftTopologyCommitRepository(dsl, publicationFence, objectMapper), + digestService); + WorldCanonicalInstancePreparationRepository preparationRepository = + new WorldCanonicalInstancePreparationRepository( + dsl, transactionManager, associationRepository, frozenRepository, transactionTimeout); + return preparationRepository; + } + private WorldCanonicalInstanceTopologyPlan frozenPlan(Fixture fixture) { return frozenPlans.computeIfAbsent( fixture.versionIdentity().operationId(), @@ -2477,6 +3175,47 @@ private static void await(CountDownLatch latch) { } } + private void awaitWorldPreparationLockWait() { + Instant deadline = Instant.now().plusSeconds(10); + do { + Record waitingRow = + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity " + + "WHERE datname=current_database() AND wait_event_type='Lock' " + + "AND query ILIKE '%world_prepare_canonical_instance%')"); + Boolean waiting = waitingRow == null ? null : waitingRow.get(0, Boolean.class); + if (Boolean.TRUE.equals(waiting)) return; + try { + Thread.sleep(25); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for the World SQL lock", exception); + } + } while (Instant.now().isBefore(deadline)); + throw new IllegalStateException("World V35 function never reached the expected owner-row lock"); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) return sqlException.getSQLState(); + } + return null; + } + + private static void awaitInstant(Instant target) { + while (Instant.now().isBefore(target)) { + long remainingMillis = Duration.between(Instant.now(), target).toMillis(); + try { + Thread.sleep(Math.max(1L, Math.min(100L, remainingMillis))); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while holding the World execution fixture", exception); + } + } + } + private static void migrateFixture(String schema, MigrationVersion target) { var configuration = Flyway.configure() diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java new file mode 100644 index 0000000000..fd4418e3a1 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; +import tools.jackson.databind.json.JsonMapper; + +/** Explicitly synthetic World-only fixture identity; it is not Account or Game Session proof. */ +final class WorldCanonicalInstanceExecutionTestFixtures { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private WorldCanonicalInstanceExecutionTestFixtures() {} + + static WorldCanonicalInstanceExecutionIdentity identity(Input input) { + return identity(input, Instant.now().plusSeconds(900)); + } + + static WorldCanonicalInstanceExecutionIdentity identity(Input input, Instant expiresAt) { + var world = input.gameSessionReadEvidence(); + var descriptor = input.completeLaunchBinding().evidence().descriptor(); + UUID actor = UUID.randomUUID(); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope( + world.canonicalTenantId(), world.targetNamespace()), + new StartSessionOperatorAction.Target(descriptor.gameTemplateId(), actor), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "synthetic World execution fixture"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + world.controlPlaneRequestId(), actor, action); + byte[] bundle = authorityBundle(preTuple, actor, expiresAt); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + world.targetNamespace() + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + UUID.randomUUID(), + 19L, + bundle, + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + return new WorldCanonicalInstanceExecutionIdentity( + tuple.canonicalBytes(), + UUID.randomUUID(), + 31L, + UUID.randomUUID(), + 37L, + world.canonicalGameInstanceId(), + WorldCanonicalInstancePreparationRepository.inputJson(input)); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, UUID actor, Instant expiresAt) { + String tenantId = tuple.action().scope().tenantId().toString(); + Instant now = Instant.now(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + now.minusSeconds(30).toString(), + "expiresAt", + expiresAt.toString()); + Map operation = + Map.of( + "issuanceOperationId", UUID.randomUUID().toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actor.toString(), + "controlUiTokenJti", + UUID.randomUUID().toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actor.toString(), + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + } catch (IOException exception) { + throw new IllegalStateException( + "Could not encode synthetic World authority fixture", exception); + } + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java index 93ab4006d1..4b238acf38 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java @@ -116,7 +116,7 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private EntityManagementClient entityManagementClient; @Test - void v35PreservesReservedTenantDenialAndDoesNotExposePrepareFunctionToPublic() { + void v35PreservesReservedTenantDenialAndExecutionEntrypointsRemainOwnerPrivate() { AuthoredWorldSourceEvidence source = source(UUID.randomUUID()); WorldAuthoredSourceIntakeReceipt receipt = Objects.requireNonNull( @@ -159,7 +159,13 @@ void v35PreservesReservedTenantDenialAndDoesNotExposePrepareFunctionToPublic() { + "JOIN pg_namespace n ON n.oid = p.pronamespace " + "CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) acl " + "WHERE n.nspname = 'world_management_service' " - + "AND p.proname = 'world_prepare_canonical_instance' " + + "AND p.proname IN ('world_prepare_canonical_instance', " + + "'world_prepare_canonical_instance_v61_impl', " + + "'world_persist_canonical_instance_execution_intent', " + + "'world_claim_canonical_instance_execution', " + + "'world_begin_canonical_instance_execution', " + + "'world_commit_canonical_instance_execution', " + + "'world_abort_canonical_instance_execution') " + "AND acl.grantee = 0 AND acl.privilege_type = 'EXECUTE')"), "Prepare-function access query returned no result") .get(0, Boolean.class)) diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index bdbca14d76..7c4c1dc318 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -3469,16 +3469,19 @@ void releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeW "worldStartLocationEvidenceBase64", java.util.Base64.getEncoder().encodeToString(changed.canonicalBytes())); String substituted = mapper.writeValueAsString(encoded); + var substitutedExecution = syntheticExecutionWithInput(input, substituted); assertThatThrownBy( () -> ownerTransaction() .execute( - status -> - dsl.fetchOne( - "SELECT * FROM world_prepare_canonical_instance(?,?)", - substituted, - WorldDraftGraphAppliedResult.digest( - substituted.getBytes(StandardCharsets.UTF_8))))) + status -> { + beginSyntheticExecution(substitutedExecution); + return dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?,?)", + substituted, + WorldDraftGraphAppliedResult.digest( + substituted.getBytes(StandardCharsets.UTF_8))); + })) .hasMessageContaining("complete frozen request"); var changedEpoch = @@ -3507,16 +3510,19 @@ void releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeW "worldStartLocationEvidenceBase64", java.util.Base64.getEncoder().encodeToString(changedEpoch.canonicalBytes())); String substitutedEpoch = mapper.writeValueAsString(changedEpochInput); + var substitutedEpochExecution = syntheticExecutionWithInput(input, substitutedEpoch); assertThatThrownBy( () -> ownerTransaction() .execute( - status -> - dsl.fetchOne( - "SELECT * FROM world_prepare_canonical_instance(?,?)", - substitutedEpoch, - WorldDraftGraphAppliedResult.digest( - substitutedEpoch.getBytes(StandardCharsets.UTF_8))))) + status -> { + beginSyntheticExecution(substitutedEpochExecution); + return dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?,?)", + substitutedEpoch, + WorldDraftGraphAppliedResult.digest( + substitutedEpoch.getBytes(StandardCharsets.UTF_8))); + })) .hasMessageContaining("complete frozen request"); assertThat( Objects.requireNonNull( @@ -3599,6 +3605,7 @@ void selectorPreparationLateFenceLossRollsBackSelectorRuntimeAndAssociationToget publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); var input = preparationInput(f, frozen, selector); completeIsolatedPublicationTerminal(input); + var executionIdentity = WorldCanonicalInstanceExecutionTestFixtures.identity(input); var component = new WorldCanonicalInstancePreparationService( preparationRepository(), @@ -3622,6 +3629,11 @@ public void requireHeld() { } } + @Override + public WorldCanonicalInstanceExecutionIdentity executionIdentity() { + return executionIdentity; + } + public void close() {} }); assertThatThrownBy(() -> component.prepare(input)) @@ -3791,6 +3803,74 @@ private void migrateHistoricalSchema(String schema, String version) { .migrate(); } + private WorldCanonicalInstanceExecutionIdentity syntheticExecutionWithInput( + WorldCanonicalInstancePreparation.Input input, String exactInputJson) { + var fixture = WorldCanonicalInstanceExecutionTestFixtures.identity(input); + return new WorldCanonicalInstanceExecutionIdentity( + fixture.originalPostAuthorizationTuple(), + fixture.accountWorldParticipationId(), + fixture.accountWorldParticipationFence(), + fixture.gameSessionOwnerAttemptId(), + fixture.gameSessionOwnerFence(), + fixture.canonicalGameInstanceId(), + exactInputJson); + } + + private long beginSyntheticExecution(WorldCanonicalInstanceExecutionIdentity identity) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + Record persisted = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT world_persist_canonical_instance_execution_intent(?,?,?,?,?,?,?,?) " + + "AS world_execution_fence", + identity.preparationInputJson(), + identity.preparationInputDigest(), + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId()), + "Synthetic World execution intent returned no fence"); + Long retainedFence = + Objects.requireNonNull( + persisted.get("world_execution_fence", Long.class), + "Synthetic World execution intent omitted its fence"); + Record claimed = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT world_claim_canonical_instance_execution(?,?,?,?,?,?,?,?) " + + "AS world_execution_fence", + identity.preparationInputJson(), + identity.preparationInputDigest(), + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId()), + "Synthetic World execution claim returned no fence"); + assertThat(claimed.get("world_execution_fence", Long.class)).isEqualTo(retainedFence); + Record begun = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT world_begin_canonical_instance_execution(?,?,?,?,?,?,?,?,?) " + + "AS world_execution_fence", + identity.preparationInputJson(), + identity.preparationInputDigest(), + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId(), + retainedFence), + "Synthetic World execution begin returned no fence"); + return Objects.requireNonNull( + begun.get("world_execution_fence", Long.class), + "Synthetic World execution begin omitted its fence"); + } + /** Executes the real V35/V42 owner SQL path for selector-null V1 migration history. */ private WorldCanonicalInstancePreparation.Result prepareV1ThroughOwnerFunction( WorldCanonicalInstancePreparation.Input input) { @@ -4198,7 +4278,8 @@ private WorldCanonicalInstancePreparationRepository preparationRepository() { new WorldCompleteLaunchBindingRepository(dsl), new WorldAuthoredSourceIntakeRepository(dsl), new WorldAuthoredVersionIdentityRepository(dsl)), - frozenRepository()); + frozenRepository(), + java.time.Duration.ofSeconds(30)); } private WorldCanonicalInstanceAssociationRepository associationRepository() { @@ -4422,10 +4503,18 @@ private WorldCanonicalInstancePreparationService preparationComponent( WorldCanonicalInstancePreparationRepository repository) { // Isolated GD-terminal fixture proves the actual World V44 transaction and released gate only. // It does not prove authenticated GD production or cross-service transport/currentness. + // Reuse the synthetic identity for exact retries; it is not an authorization producer. + Map executionIdentities = + new LinkedHashMap<>(); return new WorldCanonicalInstancePreparationService( repository, input -> { completeIsolatedPublicationTerminal(input); + String inputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + var executionIdentity = + executionIdentities.computeIfAbsent( + inputJson, + ignored -> WorldCanonicalInstanceExecutionTestFixtures.identity(input)); return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { private boolean open = true; @@ -4433,6 +4522,11 @@ public void requireHeld() { if (!open) throw new IllegalStateException("closed fixture authority"); } + @Override + public WorldCanonicalInstanceExecutionIdentity executionIdentity() { + return executionIdentity; + } + public void close() { open = false; } @@ -4455,6 +4549,9 @@ private WorldCanonicalInstancePreparationService preparationComponentWithRetaine GameDesignPublicationTerminalEvidence originalTerminal, AtomicInteger verifierInvocations) { byte[] expectedTerminal = originalTerminal.canonicalBytes(); + // Reuse the synthetic identity for exact retries; it is not an authorization producer. + Map executionIdentities = + new LinkedHashMap<>(); return new WorldCanonicalInstancePreparationService( repository, input -> { @@ -4472,6 +4569,11 @@ private WorldCanonicalInstancePreparationService preparationComponentWithRetaine throw new IllegalStateException( "isolated fixture World terminal differs from original publication result"); } + String inputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + var executionIdentity = + executionIdentities.computeIfAbsent( + inputJson, + ignored -> WorldCanonicalInstanceExecutionTestFixtures.identity(input)); return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { private boolean open = true; @@ -4479,6 +4581,11 @@ public void requireHeld() { if (!open) throw new IllegalStateException("closed fixture authority"); } + @Override + public WorldCanonicalInstanceExecutionIdentity executionIdentity() { + return executionIdentity; + } + public void close() { open = false; } From d0ce6c512e59b7432e6bebc90454cfde5d019b82 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:27:42 +1300 Subject: [PATCH 060/129] Share canonical template source decoding and preserve inventory upgrade proof --- ...ame-authoring-publishing-and-activation.md | 2 + ...ConfigOwnerSourceInventoryDeclaration.java | 122 +++++ .../gamedesign/TemplateConfigSourceJson.java | 58 ++ .../TemplateConfigSourceSnapshot.java | 183 +++++++ .../TemplateConfigSourceValues.java | 517 ++++++++++++++++++ .../TemplateConfigSourceSnapshotTest.java | 456 +++++++++++++++ ...ConfigOwnerSourceInventoryDeclaration.java | 97 +--- .../publication/TemplateConfigSource.java | 470 ++++------------ .../TemplateConfigSourceSnapshot.java | 177 ++---- ...nventoryProfileUpgradeIntegrationTest.java | 243 ++++++++ .../publication/TemplateConfigSourceTest.java | 238 ++++++++ 11 files changed, 1981 insertions(+), 582 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigOwnerSourceInventoryDeclaration.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceJson.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshot.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceValues.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshotTest.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java 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 e9e8205814..08f03579fc 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The canonical closed template-config source decoder now lives in Common, with field-preserving Game Design adapters. Config, mutation, declaration and v1/v2 snapshot bytes, digests, application/capture frames and inherited original revision provenance are preserved; reference predicates inspect content and do not qualify an owner source. The composed local gate passed with 472 Common, 532 Game Design and 589 World unit cases executed, no failures, errors or skips. All 365 PostgreSQL definitions compiled/discovered but skipped without Docker (148 Game Design, 217 World). Formatting, Checkstyle, SpotBugs, coverage, both service boot JARs, links and Markdown passed. A new isolated V69-to-V70 upgrade definition stores a historical inventory-v1/graph-2/digest-3 operation through the actual V56 validator, then checks byte-exact readback/retry and the closed v2 profile negatives after upgrade; it has not executed against PostgreSQL. Its upstream Account/World evidence is explicitly synthetic. Shared decoding and this test definition are not genuine Entity/Automation receipts, authenticated through-commit authority or activation proof. + The corrected World construction adds V62 durable original-operation, one-shot claim, independent execution fence, atomic V35 materialization/V34 association/`COMMITTED`, and same-lock `ABORTED` settlement. Its identity binds the full original StartSession tuple, distinct Account World participation ID/fence, actual Game Session attempt/fence, target and exact immutable preparation input; observational read metadata does not become a new operation. Local consolidated checks passed after repairing typed jOOQ reads and fixture accessors: World's 589 unit cases executed successfully, while Common's 464 and Game Design's 529 passing unit results were reused by Gradle. All 364 PostgreSQL definitions compiled but skipped without Docker (217 World, 147 Game Design). World V62 and Game Design V70 schema generation, formatting, Checkstyle, SpotBugs, coverage, boot JARs, links, Markdown and Flyway sanity (12 sets, 276 files) passed. This does not prove corrected PostgreSQL migrations, concurrency, cancellation or authenticated recovery. The expiry case covers repository-only exact terminal readback, not an authenticated service recovery path; genuine Account World participation, held-source producer, terminal transport and composed launch remain unavailable. Fresh Entity/Automation source qualification must cover the complete owner families and exact World closure; their authored empty declarations are not receipts or proof of absent source rows. Published `b436920367ef19bd30e7620513eefcb7bb9f2e79` [Validation run 37964440628](https://github.com/benhook1013/FireMUD/actions/runs/37964440628) completed red. Account physically executed 254 PostgreSQL cases with no failures, errors or skips; its separate 31-case Draft artifact is a byte-identical subset and is not counted twice. World executed 207 cases with 203 failures: 20 report the V61 selector-function syntax failure directly and 183 are application-context cascades. Game Design executed 150 cases with nine failures: four hit that same World migration, four expose the unchanged V56 SQL consumer rejecting the new inventory-v2 profile, and one expects the obsolete release-guard message. The bounded correction parenthesizes V61's SQL `CASE` inside the PL/pgSQL condition, adds a forward Game Design V70 exact paired-profile guard and negative cases, and corrects only the stale message assertion. Corrected PostgreSQL execution remains required; explicit retained-v1-to-V70 upgrade/readback proof is still open. V67-to-V68 history/retry proof passed, but neither it nor Account's passing suite proves the failed genuine selected export. The synthetic checkout `f586077b0a1f3bdbbcda18bb2a9537572490f71a`, tree `02675bc280cc2601311e667b668230dbcdae0512`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source head, not the intended integration parent. World execution-fence construction and genuine Entity/Automation source intake remain active, not completed handoffs or activation permission. diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigOwnerSourceInventoryDeclaration.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigOwnerSourceInventoryDeclaration.java new file mode 100644 index 0000000000..b8556fcc11 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigOwnerSourceInventoryDeclaration.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import tools.jackson.databind.JsonNode; + +/** Typed owner-authored inventory content and its immutable original Draft provenance. */ +public record TemplateConfigOwnerSourceInventoryDeclaration( + Owner owner, + AutomationAuthoredSourceInventoryDeclaration inventory, + EntityAuthoredSourceInventoryDeclaration entityInventory, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId) { + public TemplateConfigOwnerSourceInventoryDeclaration( + Owner owner, + AutomationAuthoredSourceInventoryDeclaration inventory, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId) { + this(owner, inventory, null, sourceBinding, revisionOrder, revisionId); + } + + public TemplateConfigOwnerSourceInventoryDeclaration( + Owner owner, + EntityAuthoredSourceInventoryDeclaration inventory, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId) { + this(owner, null, inventory, sourceBinding, revisionOrder, revisionId); + } + + public TemplateConfigOwnerSourceInventoryDeclaration { + if (owner == Owner.AUTOMATION_SCRIPTING) { + if (inventory == null || entityInventory != null) + throw new IllegalArgumentException("Automation owner requires its typed inventory"); + } else if (owner == Owner.ENTITY_MANAGEMENT) { + if (entityInventory == null || inventory != null) + throw new IllegalArgumentException("Entity owner requires its typed inventory"); + } else { + throw new IllegalArgumentException("Unsupported owner source inventory content"); + } + Objects.requireNonNull(sourceBinding); + if (revisionOrder == null || !revisionOrder.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Exact owner source inventory revision order required"); + TemplateConfigSourceValues.uuid(Objects.requireNonNull(revisionId).toString()); + var revision = + sourceBinding.revisions().stream() + .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .filter( + r -> r.revisionId().equals(revisionId) && r.revisionOrder().equals(revisionOrder)) + .findFirst() + .orElseThrow(); + String expectedPayload = + owner == Owner.AUTOMATION_SCRIPTING + ? TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory) + : TemplateConfigSourceValues.ownerInventoryPayload(owner, entityInventory); + if (!expectedPayload.equals( + TemplateConfigSourceJson.canonical(TemplateConfigSourceJson.tree(revision.payload())))) + throw new IllegalArgumentException( + "Owner inventory differs from its exact original source revision"); + } + + public Map object() { + return Map.of( + "owner", owner.name(), + "inventoryJson", inventoryJson(), + "sourceBindingJson", sourceBinding.canonicalJson(), + "sourceBindingDigest", sourceBinding.digest(), + "revisionOrder", revisionOrder, + "revisionId", revisionId.toString()); + } + + public static TemplateConfigOwnerSourceInventoryDeclaration fromStored(JsonNode node) { + TemplateConfigSourceJson.requireStoredFields( + node, + "owner", + "inventoryJson", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId"); + Owner owner = Owner.valueOf(TemplateConfigSourceJson.requiredStoredText(node, "owner")); + String inventoryJson = TemplateConfigSourceJson.requiredStoredText(node, "inventoryJson"); + var binding = + DraftCommitBinding.fromStored( + TemplateConfigSourceJson.requiredStoredText(node, "sourceBindingJson"), + TemplateConfigSourceJson.requiredStoredText(node, "sourceBindingDigest")); + String revisionOrder = TemplateConfigSourceJson.requiredStoredText(node, "revisionOrder"); + UUID revisionId = + TemplateConfigSourceValues.uuid( + TemplateConfigSourceJson.requiredStoredText(node, "revisionId")); + return switch (owner) { + case AUTOMATION_SCRIPTING -> + new TemplateConfigOwnerSourceInventoryDeclaration( + owner, + AutomationAuthoredSourceInventoryDeclaration.parse(inventoryJson), + binding, + revisionOrder, + revisionId); + case ENTITY_MANAGEMENT -> + new TemplateConfigOwnerSourceInventoryDeclaration( + owner, + EntityAuthoredSourceInventoryDeclaration.parse(inventoryJson), + binding, + revisionOrder, + revisionId); + default -> throw new IllegalArgumentException("Unsupported owner source inventory content"); + }; + } + + public String inventoryJson() { + return owner == Owner.AUTOMATION_SCRIPTING + ? inventory.canonicalJson() + : entityInventory.canonicalJson(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceJson.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceJson.java new file mode 100644 index 0000000000..17156fc612 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceJson.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Existing template source JSON grammar, shared by data decoding and GD adapters. */ +final class TemplateConfigSourceJson { + private static final ObjectMapper JSON = new ObjectMapper(); + + private TemplateConfigSourceJson() {} + + static void requireStoredFields(JsonNode node, String... names) { + if (!node.isObject() || node.size() != names.length) + throw new IllegalArgumentException("Closed command source operation fields are required"); + for (String name : names) + if (node.get(name) == null) + throw new IllegalArgumentException("Missing command source field " + name); + } + + static String requiredStoredText(JsonNode source, String field) { + JsonNode value = source.get(field); + if (value == null || !value.isTextual() || value.asText().isBlank()) + throw new IllegalArgumentException("Command definition text is required: " + field); + return value.asText(); + } + + static String canonical(Object value) { + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } catch (IOException failure) { + throw new IllegalArgumentException("Canonical command source encoding failed", failure); + } + } + + static JsonNode tree(String json) { + try { + return JSON.readTree(Rfc8785CanonicalJson.canonicalizeUtf8(json)); + } catch (IOException | RuntimeException failure) { + throw new IllegalArgumentException("Unambiguous command source JSON required", failure); + } + } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 unavailable", failure); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshot.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshot.java new file mode 100644 index 0000000000..0f8cd847cb --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshot.java @@ -0,0 +1,183 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Actual template wiring history only; no Game Logic receipt or total-release completeness. */ +public record TemplateConfigSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List entries, + List ownerSourceInventoryDeclarations) { + public static final String SCHEMA = "game-design-template-config-source-snapshot/v1"; + public static final String SCHEMA_V2 = "game-design-template-config-source-snapshot/v2"; + + public TemplateConfigSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List entries) { + this(binding, sourceEpoch, inheritedCommitId, genesisReceiptId, entries, List.of()); + } + + public TemplateConfigSourceSnapshot { + Objects.requireNonNull(binding); + if (sourceEpoch == null || !sourceEpoch.matches("0|[1-9][0-9]*")) + throw new IllegalArgumentException("Exact template source epoch required"); + DraftAuthorizationFenceBinding.requireUuid(genesisReceiptId); + if (inheritedCommitId != null) DraftAuthorizationFenceBinding.requireUuid(inheritedCommitId); + entries = List.copyOf(entries); + var keys = new java.util.HashSet(); + for (var entry : entries) + if (!entry.sourceBinding().target().equals(binding.target()) || !keys.add(entry.templateId())) + throw new IllegalArgumentException("Template source target or identity conflict"); + if (!entries.equals( + entries.stream() + .sorted(java.util.Comparator.comparing(e -> new BigInteger(e.templateId()))) + .toList())) throw new IllegalArgumentException("Canonical template row order required"); + ownerSourceInventoryDeclarations = List.copyOf(ownerSourceInventoryDeclarations); + var owners = + new java.util.HashSet(); + for (var declaration : ownerSourceInventoryDeclarations) { + if (!declaration.sourceBinding().target().equals(binding.target()) + || !owners.add(declaration.owner())) + throw new IllegalArgumentException("Template owner inventory target or identity conflict"); + } + if (!ownerSourceInventoryDeclarations.equals( + ownerSourceInventoryDeclarations.stream() + .sorted(java.util.Comparator.comparing(value -> value.owner().name())) + .toList())) + throw new IllegalArgumentException("Canonical owner inventory order required"); + } + + public String canonicalJson() { + Map value = + new java.util.LinkedHashMap<>( + Map.of( + "schema", + ownerSourceInventoryDeclarations.isEmpty() ? SCHEMA : SCHEMA_V2, + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptId", + genesisReceiptId.toString(), + "entries", + entries.stream().map(TemplateConfigSourceValues.Entry::object).toList())); + if (!ownerSourceInventoryDeclarations.isEmpty()) + value.put( + "ownerSourceInventoryDeclarations", + ownerSourceInventoryDeclarations.stream() + .map(TemplateConfigOwnerSourceInventoryDeclaration::object) + .toList()); + return TemplateConfigSourceJson.canonical(value); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return TemplateConfigSourceJson.sha256(canonicalBytes()); + } + + public static TemplateConfigSourceSnapshot fromStored(String json) { + var root = TemplateConfigSourceJson.tree(json); + String schema = TemplateConfigSourceJson.requiredStoredText(root, "schema"); + if (SCHEMA.equals(schema)) { + TemplateConfigSourceJson.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "entries"); + } else if (SCHEMA_V2.equals(schema)) { + TemplateConfigSourceJson.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "entries", + "ownerSourceInventoryDeclarations"); + } else { + throw new IllegalArgumentException("Unsupported template config source snapshot"); + } + if (!root.path("entries").isArray() + || (SCHEMA_V2.equals(schema) && !root.path("ownerSourceInventoryDeclarations").isArray())) + throw new IllegalArgumentException( + "Template config source snapshot collections are required"); + var binding = + DraftCommitBinding.fromStored( + TemplateConfigSourceJson.requiredStoredText(root, "bindingJson"), + TemplateConfigSourceJson.requiredStoredText(root, "bindingDigest")); + List entries = new ArrayList<>(); + for (var node : root.path("entries")) { + TemplateConfigSourceJson.requireStoredFields( + node, + "templateId", + "configJson", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId", + "createdName"); + if (!node.path("createdName").isTextual()) + throw new IllegalArgumentException("Explicit source operation identity required"); + String name = node.path("createdName").textValue(); + entries.add( + new TemplateConfigSourceValues.Entry( + TemplateConfigSourceJson.requiredStoredText(node, "templateId"), + new TemplateConfigSourceValues.Config( + TemplateConfigSourceJson.requiredStoredText(node, "configJson")), + DraftCommitBinding.fromStored( + TemplateConfigSourceJson.requiredStoredText(node, "sourceBindingJson"), + TemplateConfigSourceJson.requiredStoredText(node, "sourceBindingDigest")), + TemplateConfigSourceJson.requiredStoredText(node, "revisionOrder"), + TemplateConfigSourceValues.uuid( + TemplateConfigSourceJson.requiredStoredText(node, "revisionId")), + name.isEmpty() ? null : name)); + } + List declarations = new ArrayList<>(); + if (SCHEMA_V2.equals(schema)) + for (var node : root.path("ownerSourceInventoryDeclarations")) + declarations.add(TemplateConfigOwnerSourceInventoryDeclaration.fromStored(node)); + if (!root.path("inheritedCommitId").isTextual()) + throw new IllegalArgumentException("Explicit predecessor required"); + String inherited = root.path("inheritedCommitId").textValue(); + var result = + new TemplateConfigSourceSnapshot( + binding, + TemplateConfigSourceJson.requiredStoredText(root, "sourceEpoch"), + inherited.isEmpty() ? null : TemplateConfigSourceValues.uuid(inherited), + TemplateConfigSourceValues.uuid( + TemplateConfigSourceJson.requiredStoredText(root, "genesisReceiptId")), + entries, + declarations); + if ((SCHEMA.equals(schema) && !result.ownerSourceInventoryDeclarations().isEmpty()) + || (SCHEMA_V2.equals(schema) && result.ownerSourceInventoryDeclarations().isEmpty())) + throw new IllegalArgumentException("Template config source snapshot schema mismatch"); + if (!json.equals(result.canonicalJson())) + throw new IllegalArgumentException("Noncanonical template config snapshot"); + return result; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceValues.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceValues.java new file mode 100644 index 0000000000..2b2e2e7f13 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceValues.java @@ -0,0 +1,517 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import tools.jackson.databind.JsonNode; + +/** Closed authored wiring. Syntax validation never qualifies an external owner's reference. */ +public final class TemplateConfigSourceValues { + public static final String REVISION_KIND = "TEMPLATE_CONFIG"; + public static final String SCOPE = "TEMPLATE_CONFIG_SET"; + public static final String SCOPE_ID = "effective"; + + private TemplateConfigSourceValues() {} + + public enum OperationKind { + CREATE, + UPSERT, + DELETE, + DECLARE_OWNER_SOURCE_INVENTORY + } + + public record GameplayInput(Family family, String key, UUID revisionId) { + public GameplayInput { + Objects.requireNonNull(family); + GameplayRuleManifest.identifier(key); + uuid(revisionId.toString()); + } + } + + /** Canonical config remains the actual authored document, without derived commit evidence. */ + public record Config(String canonicalJson) { + public Config { + JsonNode root = TemplateConfigSourceJson.tree(canonicalJson); + fields( + root, + "schemaVersion", + "baseVersionId", + "world", + "entity", + "gameLogic", + "automation", + "supportedSettings"); + if (!root.path("schemaVersion").isInt() || root.path("schemaVersion").intValue() != 1) + throw new IllegalArgumentException("Unsupported template config schemaVersion"); + uuid(text(root, "baseVersionId")); + fields(root.path("world"), "regions", "rooms"); + ownerIds(root.path("world"), "regions", "regionTemplateId"); + ownerIds(root.path("world"), "rooms", "roomTemplateId"); + fields(root.path("entity"), "items", "npcs"); + ownerIds(root.path("entity"), "items", "entityTemplateId"); + ownerIds(root.path("entity"), "npcs", "entityTemplateId"); + fields(root.path("gameLogic"), "inputs"); + Set rules = new HashSet<>(); + for (JsonNode node : array(root.path("gameLogic"), "inputs")) { + fields(node, "family", "key", "revisionId"); + Family family = Family.valueOf(text(node, "family")); + String key = text(node, "key"); + GameplayRuleManifest.identifier(key); + uuid(text(node, "revisionId")); + if (!rules.add(family.name() + ":" + key)) + throw new IllegalArgumentException("Duplicate template gameplay input"); + } + fields(root.path("automation"), "scripts", "scriptPatch"); + Set scripts = new HashSet<>(); + for (JsonNode node : array(root.path("automation"), "scripts")) { + fields(node, "scriptId", "eventBindings"); + if (!scripts.add(text(node, "scriptId"))) + throw new IllegalArgumentException("Duplicate template script name"); + Set bindings = new HashSet<>(); + for (JsonNode event : array(node, "eventBindings")) { + fields( + event, + "eventType", + "eventSchemaVersion", + "bindingId", + "targetScopeType", + "targetScopeId"); + text(event, "eventType"); + text(event, "eventSchemaVersion"); + for (String key : List.of("bindingId", "targetScopeType", "targetScopeId")) + if (!event.path(key).isTextual()) + throw new IllegalArgumentException("Exact Automation binding key required"); + if (!bindings.add(TemplateConfigSourceJson.canonical(event))) + throw new IllegalArgumentException("Duplicate template event binding"); + } + } + JsonNode patch = root.path("automation").path("scriptPatch"); + String presence = text(patch, "presence"); + if ("ABSENT".equals(presence)) fields(patch, "presence"); + else if ("PRESENT".equals(presence)) { + fields(patch, "presence", "scriptPatchVersion"); + text(patch, "scriptPatchVersion"); + } else throw new IllegalArgumentException("Explicit template script-patch presence required"); + if (!array(root, "supportedSettings").isEmpty()) + throw new IllegalArgumentException( + "No supported non-authoritative settings are registered"); + canonicalJson = TemplateConfigSourceJson.canonical(root); + } + + public UUID baseVersionId() { + return uuid(text(TemplateConfigSourceJson.tree(canonicalJson), "baseVersionId")); + } + + public List gameplayInputs() { + List inputs = new ArrayList<>(); + for (JsonNode node : + TemplateConfigSourceJson.tree(canonicalJson).path("gameLogic").path("inputs")) + inputs.add( + new GameplayInput( + Family.valueOf(text(node, "family")), + text(node, "key"), + uuid(text(node, "revisionId")))); + return List.copyOf(inputs); + } + + /** Data inspection only; these predicates do not qualify owner source. */ + public boolean hasWorldReferences() { + var root = TemplateConfigSourceJson.tree(canonicalJson).path("world"); + return !root.path("regions").isEmpty() || !root.path("rooms").isEmpty(); + } + + public boolean hasEntityReferences() { + var root = TemplateConfigSourceJson.tree(canonicalJson).path("entity"); + return !root.path("items").isEmpty() || !root.path("npcs").isEmpty(); + } + + public boolean hasAutomationReferences() { + var root = TemplateConfigSourceJson.tree(canonicalJson).path("automation"); + return !root.path("scripts").isEmpty() + || "PRESENT".equals(text(root.path("scriptPatch"), "presence")); + } + } + + public record Mutation( + DraftCommitBinding binding, + String revisionOrder, + UUID revisionId, + OperationKind operation, + String templateId, + String templateName, + Config config, + Owner declaredOwner, + AutomationAuthoredSourceInventoryDeclaration inventory, + EntityAuthoredSourceInventoryDeclaration entityInventory) { + public Mutation( + DraftCommitBinding binding, + String revisionOrder, + UUID revisionId, + OperationKind operation, + String templateId, + String templateName, + Config config) { + this( + binding, + revisionOrder, + revisionId, + operation, + templateId, + templateName, + config, + null, + null, + null); + } + + public Mutation { + Objects.requireNonNull(binding); + Objects.requireNonNull(operation); + if (operation == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { + if (templateId != null + || templateName != null + || config != null + || declaredOwner == null + || !Set.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT).contains(declaredOwner) + || (declaredOwner == Owner.AUTOMATION_SCRIPTING + ? inventory == null || entityInventory != null + : entityInventory == null || inventory != null)) + throw new IllegalArgumentException( + "Owner inventory declaration carries only its supported owner's authored content"); + new TemplateConfigOwnerSourceInventoryDeclaration( + declaredOwner, inventory, entityInventory, binding, revisionOrder, revisionId); + } else if (declaredOwner != null || inventory != null || entityInventory != null) { + throw new IllegalArgumentException("Template row mutations carry no owner inventory"); + } else if (operation == OperationKind.CREATE) { + if (templateId != null + || templateName == null + || templateName.isBlank() + || templateName.length() > 100) + throw new IllegalArgumentException( + "CREATE requires a display name and no caller template id"); + } else { + requireTemplateId(templateId); + if (templateName != null) + throw new IllegalArgumentException("Only CREATE carries a display name"); + } + if (operation != OperationKind.DELETE + && operation != OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { + Objects.requireNonNull(config); + if (!binding.target().canonicalVersionId().equals(config.baseVersionId())) + throw new IllegalArgumentException( + "Template config base differs from its exact source version"); + } else if (operation == OperationKind.DELETE && config != null) + throw new IllegalArgumentException("Template DELETE carries no config"); + var revision = + binding.revisions().stream() + .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) + .filter( + r -> r.revisionId().equals(revisionId) && r.revisionOrder().equals(revisionOrder)) + .findFirst() + .orElseThrow(); + String expected = + payloadFor( + operation, + templateId, + templateName, + config, + declaredOwner, + inventory, + entityInventory); + if (!expected.equals( + TemplateConfigSourceJson.canonical(TemplateConfigSourceJson.tree(revision.payload())))) + throw new IllegalArgumentException( + "Template config differs from its exact original revision"); + } + + public String payload() { + return payloadFor( + operation, templateId, templateName, config, declaredOwner, inventory, entityInventory); + } + + public boolean changesTemplateRow() { + return operation != OperationKind.DECLARE_OWNER_SOURCE_INVENTORY; + } + + public TemplateConfigOwnerSourceInventoryDeclaration ownerInventoryDeclaration() { + return operation == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY + ? new TemplateConfigOwnerSourceInventoryDeclaration( + declaredOwner, inventory, entityInventory, binding, revisionOrder, revisionId) + : null; + } + + public String inventoryJson() { + if (inventory != null) return inventory.canonicalJson(); + if (entityInventory != null) return entityInventory.canonicalJson(); + throw new IllegalStateException("Mutation has no owner inventory content"); + } + } + + public record Entry( + String templateId, + Config config, + DraftCommitBinding sourceBinding, + String revisionOrder, + UUID revisionId, + String createdName) { + public Entry { + requireTemplateId(templateId); + new Mutation( + sourceBinding, + revisionOrder, + revisionId, + createdName == null ? OperationKind.UPSERT : OperationKind.CREATE, + createdName == null ? templateId : null, + createdName, + config); + } + + public Map object() { + return Map.of( + "templateId", + templateId, + "configJson", + config.canonicalJson(), + "sourceBindingJson", + sourceBinding.canonicalJson(), + "sourceBindingDigest", + sourceBinding.digest(), + "revisionOrder", + revisionOrder, + "revisionId", + revisionId.toString(), + "createdName", + createdName == null ? "" : createdName); + } + } + + public static List mutations(DraftCommitBinding binding) { + List result = new ArrayList<>(); + Set declaredOwners = new HashSet<>(); + for (var revision : binding.revisions()) { + if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; + JsonNode root = TemplateConfigSourceJson.tree(revision.payload()); + String kind = text(root, "revisionKind"); + if (Set.of( + "COMMAND_DEFINITION", + "REALM_ENTRY_POLICY", + "ASSET_REFERENCE", + "GAMEPLAY_RULE", + "BRANDING_ASSET_REFERENCE") + .contains(kind)) continue; + if (!REVISION_KIND.equals(kind)) + throw new IllegalArgumentException("Unknown Game Design revision kind"); + OperationKind operation = OperationKind.valueOf(text(root, "operation")); + int schemaVersion = + root.path("schemaVersion").isInt() ? root.path("schemaVersion").intValue() : -1; + if (operation == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { + fields(root, "schemaVersion", "revisionKind", "operation", "owner", "inventory"); + Owner owner = Owner.valueOf(text(root, "owner")); + if (!Set.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT).contains(owner) + || !declaredOwners.add(owner)) + throw new IllegalArgumentException("Only one declaration per supported owner is allowed"); + if (owner == Owner.AUTOMATION_SCRIPTING) { + if (schemaVersion != 2) + throw new IllegalArgumentException( + "Unsupported Automation owner inventory source schemaVersion"); + result.add( + new Mutation( + binding, + revision.revisionOrder(), + revision.revisionId(), + operation, + null, + null, + null, + owner, + AutomationAuthoredSourceInventoryDeclaration.parse( + TemplateConfigSourceJson.canonical(root.path("inventory"))), + null)); + } else { + if (schemaVersion != 3) + throw new IllegalArgumentException( + "Unsupported Entity owner inventory source schemaVersion"); + result.add( + new Mutation( + binding, + revision.revisionOrder(), + revision.revisionId(), + operation, + null, + null, + null, + owner, + null, + EntityAuthoredSourceInventoryDeclaration.parse( + TemplateConfigSourceJson.canonical(root.path("inventory"))))); + } + continue; + } + if (schemaVersion != 1) + throw new IllegalArgumentException("Unsupported template source schemaVersion"); + fields( + root, + operation == OperationKind.CREATE + ? new String[] { + "schemaVersion", "revisionKind", "operation", "templateName", "configJson" + } + : operation == OperationKind.UPSERT + ? new String[] { + "schemaVersion", "revisionKind", "operation", "templateId", "configJson" + } + : new String[] {"schemaVersion", "revisionKind", "operation", "templateId"}); + result.add( + new Mutation( + binding, + revision.revisionOrder(), + revision.revisionId(), + operation, + operation == OperationKind.CREATE ? null : text(root, "templateId"), + operation == OperationKind.CREATE ? text(root, "templateName") : null, + operation != OperationKind.DELETE ? new Config(text(root, "configJson")) : null)); + } + return List.copyOf(result); + } + + public static String upsertPayload(String templateId, Config config) { + requireTemplateId(templateId); + return TemplateConfigSourceJson.canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + REVISION_KIND, + "operation", + "UPSERT", + "templateId", + templateId, + "configJson", + config.canonicalJson())); + } + + public static String createPayload(String templateName, Config config) { + if (templateName == null || templateName.isBlank() || templateName.length() > 100) + throw new IllegalArgumentException("Template display name required"); + return TemplateConfigSourceJson.canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + REVISION_KIND, + "operation", + "CREATE", + "templateName", + templateName, + "configJson", + config.canonicalJson())); + } + + public static String deletePayload(String templateId) { + requireTemplateId(templateId); + return TemplateConfigSourceJson.canonical( + Map.of( + "schemaVersion", + 1, + "revisionKind", + REVISION_KIND, + "operation", + "DELETE", + "templateId", + templateId)); + } + + public static String ownerInventoryPayload( + Owner owner, AutomationAuthoredSourceInventoryDeclaration inventory) { + if (owner != Owner.AUTOMATION_SCRIPTING) + throw new IllegalArgumentException("Only Automation source inventory is supported"); + Objects.requireNonNull(inventory); + return TemplateConfigSourceJson.canonical( + Map.of( + "schemaVersion", 2, + "revisionKind", REVISION_KIND, + "operation", OperationKind.DECLARE_OWNER_SOURCE_INVENTORY.name(), + "owner", owner.name(), + "inventory", TemplateConfigSourceJson.tree(inventory.canonicalJson()))); + } + + public static String ownerInventoryPayload( + Owner owner, EntityAuthoredSourceInventoryDeclaration inventory) { + if (owner != Owner.ENTITY_MANAGEMENT) + throw new IllegalArgumentException("Only Entity source inventory is supported"); + Objects.requireNonNull(inventory); + return TemplateConfigSourceJson.canonical( + Map.of( + "schemaVersion", 3, + "revisionKind", REVISION_KIND, + "operation", OperationKind.DECLARE_OWNER_SOURCE_INVENTORY.name(), + "owner", owner.name(), + "inventory", TemplateConfigSourceJson.tree(inventory.canonicalJson()))); + } + + private static String payloadFor( + OperationKind operation, + String templateId, + String templateName, + Config config, + Owner declaredOwner, + AutomationAuthoredSourceInventoryDeclaration inventory, + EntityAuthoredSourceInventoryDeclaration entityInventory) { + return switch (operation) { + case CREATE -> createPayload(templateName, config); + case UPSERT -> upsertPayload(templateId, config); + case DELETE -> deletePayload(templateId); + case DECLARE_OWNER_SOURCE_INVENTORY -> + inventory != null + ? ownerInventoryPayload(declaredOwner, inventory) + : ownerInventoryPayload(declaredOwner, entityInventory); + }; + } + + private static void requireTemplateId(String value) { + if (value == null + || !value.matches("[1-9][0-9]*") + || new BigInteger(value).compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) + throw new IllegalArgumentException("Exact Game Design template row identity required"); + } + + public static UUID uuid(String value) { + UUID result = UUID.fromString(value); + if (!result.toString().equals(value) || new UUID(0, 0).equals(result)) + throw new IllegalArgumentException("Canonical nonzero owner UUID required"); + return result; + } + + private static void ownerIds(JsonNode root, String collection, String key) { + Set ids = new HashSet<>(); + for (JsonNode node : array(root, collection)) { + fields(node, key); + if (!ids.add(uuid(text(node, key)))) + throw new IllegalArgumentException("Duplicate owner template reference"); + } + } + + private static JsonNode array(JsonNode root, String key) { + if (!root.path(key).isArray()) + throw new IllegalArgumentException("Explicit template config collection required: " + key); + return root.path(key); + } + + private static void fields(JsonNode node, String... fields) { + TemplateConfigSourceJson.requireStoredFields(node, fields); + } + + private static String text(JsonNode node, String key) { + return TemplateConfigSourceJson.requiredStoredText(node, key); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshotTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshotTest.java new file mode 100644 index 0000000000..f32b9d6e13 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceSnapshotTest.java @@ -0,0 +1,456 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; + +class TemplateConfigSourceSnapshotTest { + private static final UUID TENANT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID GENESIS = UUID.fromString("33333333-3333-4333-8333-333333333333"); + + @Test + void directDecoderPreservesV1BytesAndMissingDeclarationEvidence() throws Exception { + var config = new TemplateConfigSourceValues.Config(config()); + var original = binding(TemplateConfigSourceValues.createPayload("Starter", config)); + var entry = entry(original, "7", "Starter", config); + var selected = binding(); + String json = canonical(snapshotObject(selected, List.of(entry.object()), null)); + var decoded = TemplateConfigSourceSnapshot.fromStored(json); + assertThat(decoded.binding()).isEqualTo(selected); + assertThat(decoded.entries().getFirst().sourceBinding()).isEqualTo(original); + assertThat(decoded.ownerSourceInventoryDeclarations()).isEmpty(); + assertThat(decoded.canonicalJson()).isEqualTo(json); + assertThat(decoded.canonicalBytes()).isEqualTo(json.getBytes(StandardCharsets.UTF_8)); + assertThat(decoded.digest()).isEqualTo(digest(json)); + } + + @Test + void directV2DecoderKeepsOriginalDeclarationsSeparateFromSelectedIdentity() throws Exception { + var automation = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + var entity = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + var authored = + binding( + TemplateConfigSourceValues.ownerInventoryPayload( + Owner.AUTOMATION_SCRIPTING, automation), + TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, entity)); + var declarations = + TemplateConfigSourceValues.mutations(authored).stream() + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .toList(); + var selected = binding(); + String json = + canonical( + snapshotObject( + selected, + List.of(), + declarations.stream() + .map(TemplateConfigOwnerSourceInventoryDeclaration::object) + .toList())); + var decoded = TemplateConfigSourceSnapshot.fromStored(json); + assertThat(decoded.binding()).isEqualTo(selected); + assertThat(decoded.ownerSourceInventoryDeclarations()).hasSize(2); + assertThat(decoded.ownerSourceInventoryDeclarations()) + .extracting(TemplateConfigOwnerSourceInventoryDeclaration::sourceBinding) + .containsExactly(authored, authored); + assertThat(decoded.ownerSourceInventoryDeclarations().get(0).inventory()).isEqualTo(automation); + assertThat(decoded.ownerSourceInventoryDeclarations().get(1).entityInventory()) + .isEqualTo(entity); + assertThat(decoded.canonicalJson()).isEqualTo(json); + assertThat(decoded.digest()).isEqualTo(digest(json)); + } + + @Test + void configRejectsIncompleteAmbiguousAndUnsupportedGrammar() { + String valid = config(); + for (String invalid : + List.of( + valid.replace("\"rooms\":[]", "\"rooms\":null"), + valid.replace("\"rooms\":[]", "\"unknown\":[]"), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"receipt\":{}"), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"commitDigest\":\"recursive\""), + valid.replace("\"inputs\":[]", "\"inputs\":[],\"bindingJson\":\"recursive\""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":2"), + valid.replace(VERSION.toString(), "00000000-0000-0000-0000-000000000000"), + valid.replace("\"items\":[]", "\"items\":[{\"entityTemplateId\":\"7\"}]"), + valid.replace("\"supportedSettings\":[]", "\"supportedSettings\":[{}]"), + valid.replace("\"presence\":\"ABSENT\"", "\"presence\":\"UNKNOWN\""), + valid.replace("\"presence\":\"ABSENT\"", "\"presence\":\"PRESENT\""), + valid + "{}")) { + assertThatThrownBy(() -> new TemplateConfigSourceValues.Config(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void ownerReferencePredicatesInspectEveryCollectionAndPresentPatchWithoutQualification() { + var empty = new TemplateConfigSourceValues.Config(config()); + assertThat(empty.hasWorldReferences()).isFalse(); + assertThat(empty.hasEntityReferences()).isFalse(); + assertThat(empty.hasAutomationReferences()).isFalse(); + for (String collection : List.of("regions", "rooms")) { + String key = collection.equals("regions") ? "regionTemplateId" : "roomTemplateId"; + assertThat( + new TemplateConfigSourceValues.Config( + config() + .replace( + "\"" + collection + "\":[]", + "\"" + collection + "\":[{\"" + key + "\":\"" + GENESIS + "\"}]")) + .hasWorldReferences()) + .isTrue(); + } + for (String collection : List.of("items", "npcs")) + assertThat( + new TemplateConfigSourceValues.Config( + config() + .replace( + "\"" + collection + "\":[]", + "\"" + + collection + + "\":[{\"entityTemplateId\":\"" + + GENESIS + + "\"}]")) + .hasEntityReferences()) + .isTrue(); + assertThat( + new TemplateConfigSourceValues.Config( + config() + .replace( + "\"scripts\":[]", + "\"scripts\":[{\"scriptId\":\"raw-script\",\"eventBindings\":[]}]")) + .hasAutomationReferences()) + .isTrue(); + assertThat( + new TemplateConfigSourceValues.Config( + config() + .replace( + "\"presence\":\"ABSENT\"", + "\"presence\":\"PRESENT\",\"scriptPatchVersion\":\" raw-patch \"")) + .hasAutomationReferences()) + .isTrue(); + } + + @Test + void configRejectsDuplicateReferencesInputsScriptsAndBindings() { + String item = "{\"entityTemplateId\":\"" + GENESIS + "\"}"; + String region = "{\"regionTemplateId\":\"" + GENESIS + "\"}"; + String input = + "{\"family\":\"ADMISSION_TAGS\",\"key\":\"entry\",\"revisionId\":\"" + GENESIS + "\"}"; + String event = + "{\"eventType\":\"onEnter\",\"eventSchemaVersion\":\"1\"," + + "\"bindingId\":\"\",\"targetScopeType\":\"\",\"targetScopeId\":\"\"}"; + String script = "{\"scriptId\":\"onEnter\",\"eventBindings\":[]}"; + String duplicateEvents = + "{\"scriptId\":\"onEnter\",\"eventBindings\":[" + event + "," + event + "]}"; + for (String invalid : + List.of( + config().replace("\"items\":[]", "\"items\":[" + item + "," + item + "]"), + config().replace("\"regions\":[]", "\"regions\":[" + region + "," + region + "]"), + config().replace("\"inputs\":[]", "\"inputs\":[" + input + "," + input + "]"), + config().replace("\"scripts\":[]", "\"scripts\":[" + script + "," + script + "]"), + config().replace("\"scripts\":[]", "\"scripts\":[" + duplicateEvents + "]"), + config() + .replace( + "\"scripts\":[]", "\"scripts\":[{\"scriptId\":\"x\",\"eventBindings\":null}]"), + config() + .replace( + "\"inputs\":[]", + "\"inputs\":[{\"family\":\"UNKNOWN\",\"key\":\"entry\",\"revisionId\":\"" + + GENESIS + + "\"}]"))) { + assertThatThrownBy(() -> new TemplateConfigSourceValues.Config(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + // Empty raw binding keys remain accepted exactly as in the existing GD grammar. + var valid = + new TemplateConfigSourceValues.Config( + config() + .replace( + "\"scripts\":[]", + "\"scripts\":[{\"scriptId\":\"onEnter\",\"eventBindings\":[" + event + "]}]")); + assertThat(valid.hasAutomationReferences()).isTrue(); + } + + @Test + void storedSnapshotRejectsClosedFieldsCollectionsCanonicalFormAndSchemaMismatch() + throws Exception { + var selected = binding(); + var value = snapshotObject(selected, List.of(), null); + String valid = canonical(value); + List invalid = + new ArrayList<>( + List.of( + valid + "{}", + " " + valid, + valid.replace("\"sourceEpoch\":\"1\"", "\"sourceEpoch\":\"01\""), + valid.replace("\"entries\":[]", "\"entries\":null"), + valid.replace("\"inheritedCommitId\":\"\"", "\"inheritedCommitId\":null"), + valid.replace(GENESIS.toString(), "00000000-0000-0000-0000-000000000000"), + valid.replace(TemplateConfigSourceSnapshot.SCHEMA, "unknown/v1"), + valid.replace("\"schema\":", "\"unknown\":0,\"schema\":"), + valid.replace( + "\"sourceEpoch\":\"1\"", "\"sourceEpoch\":\"1\",\"sourceEpoch\":\"1\""))); + var missing = new LinkedHashMap<>(value); + missing.remove("genesisReceiptId"); + invalid.add(canonical(missing)); + var emptyV2 = snapshotObject(selected, List.of(), List.of()); + invalid.add(canonical(emptyV2)); + var malformedV2 = new LinkedHashMap<>(emptyV2); + malformedV2.put("ownerSourceInventoryDeclarations", Map.of()); + invalid.add(canonical(malformedV2)); + var v1WithDeclarations = new LinkedHashMap<>(emptyV2); + v1WithDeclarations.put("schema", TemplateConfigSourceSnapshot.SCHEMA); + invalid.add(canonical(v1WithDeclarations)); + var wrongDigest = new LinkedHashMap<>(value); + wrongDigest.put("bindingDigest", "sha256:" + "0".repeat(64)); + String corruptBinding = canonical(wrongDigest); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(corruptBinding)) + .isInstanceOf(IllegalStateException.class); + for (String json : invalid) + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(json)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void storedEntryRejectsOrderingDuplicatesTargetAndRevisionSubstitution() throws Exception { + var config = new TemplateConfigSourceValues.Config(config()); + var original = binding(TemplateConfigSourceValues.createPayload("Starter", config)); + var first = entry(original, "7", "Starter", config); + var second = entry(original, "8", "Starter", config); + var selected = binding(); + for (List> entries : + List.of( + List.of(first.object(), first.object()), List.of(second.object(), first.object()))) { + String json = canonical(snapshotObject(selected, entries, null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(json)) + .isInstanceOf(IllegalArgumentException.class); + } + var altered = new LinkedHashMap<>(first.object()); + altered.put("revisionId", GENESIS.toString()); + String wrongRevision = canonical(snapshotObject(selected, List.of(altered), null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(wrongRevision)) + .isInstanceOf(java.util.NoSuchElementException.class); + altered.put("revisionId", first.revisionId().toString()); + altered.put("createdName", "Substituted"); + String wrongPayload = canonical(snapshotObject(selected, List.of(altered), null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(wrongPayload)) + .isInstanceOf(IllegalArgumentException.class); + for (String key : + List.of( + "templateId", + "configJson", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId", + "createdName")) { + var missing = new LinkedHashMap<>(first.object()); + missing.remove(key); + String missingField = canonical(snapshotObject(selected, List.of(missing), null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(missingField)) + .isInstanceOf(IllegalArgumentException.class); + } + var missingOperation = new LinkedHashMap<>(first.object()); + missingOperation.put("createdName", 1); + String nontextOperation = canonical(snapshotObject(selected, List.of(missingOperation), null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(nontextOperation)) + .isInstanceOf(IllegalArgumentException.class); + var foreign = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + GENESIS, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + original.revisions(), + original.affectedUnits()); + altered = new LinkedHashMap<>(first.object()); + altered.put("sourceBindingJson", foreign.canonicalJson()); + altered.put("sourceBindingDigest", foreign.digest()); + String wrongTarget = canonical(snapshotObject(selected, List.of(altered), null)); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(wrongTarget)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void declarationsRejectOwnerSchemaContentRevisionAndOrderSubstitution() throws Exception { + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + String payload = + TemplateConfigSourceValues.ownerInventoryPayload(Owner.AUTOMATION_SCRIPTING, inventory); + var authored = binding(payload); + var declaration = + TemplateConfigSourceValues.mutations(authored).getFirst().ownerInventoryDeclaration(); + var selected = binding(); + for (String invalid : + List.of( + payload.replace("\"schemaVersion\":2", "\"schemaVersion\":3"), + payload.replace("AUTOMATION_SCRIPTING", "ENTITY_MANAGEMENT"), + payload.replace("\"inventory\":", "\"unknown\":"), + payload.replace("\"SCRIPT_DEFINITIONS\":[]", "\"SCRIPT_DEFINITIONS\":[{}]"), + payload.replace( + "\"operation\":\"DECLARE_OWNER_SOURCE_INVENTORY\"", "\"operation\":\"UNKNOWN\""))) { + assertThatThrownBy(() -> TemplateConfigSourceValues.mutations(binding(invalid))) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy(() -> TemplateConfigSourceValues.mutations(binding(payload, payload))) + .isInstanceOf(IllegalArgumentException.class); + String duplicate = + canonical( + snapshotObject( + selected, List.of(), List.of(declaration.object(), declaration.object()))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(duplicate)) + .isInstanceOf(IllegalArgumentException.class); + var changed = new LinkedHashMap<>(declaration.object()); + changed.put("inventoryJson", entityInventory()); + String substituted = canonical(snapshotObject(selected, List.of(), List.of(changed))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(substituted)) + .isInstanceOf(IllegalArgumentException.class); + changed = new LinkedHashMap<>(declaration.object()); + changed.put("revisionOrder", "01"); + String wrongOrder = canonical(snapshotObject(selected, List.of(), List.of(changed))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(wrongOrder)) + .isInstanceOf(IllegalArgumentException.class); + changed = new LinkedHashMap<>(declaration.object()); + changed.put("revisionId", GENESIS.toString()); + String wrongRevision = canonical(snapshotObject(selected, List.of(), List.of(changed))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(wrongRevision)) + .isInstanceOf(java.util.NoSuchElementException.class); + for (String key : + List.of( + "owner", + "inventoryJson", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId")) { + var missing = new LinkedHashMap<>(declaration.object()); + missing.remove(key); + String missingField = canonical(snapshotObject(selected, List.of(), List.of(missing))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(missingField)) + .isInstanceOf(IllegalArgumentException.class); + } + var entity = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + var both = + binding( + payload, + TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, entity)); + var declarations = + TemplateConfigSourceValues.mutations(both).stream() + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .toList(); + String reversed = + canonical( + snapshotObject( + selected, + List.of(), + List.of(declarations.get(1).object(), declarations.get(0).object()))); + assertThatThrownBy(() -> TemplateConfigSourceSnapshot.fromStored(reversed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static TemplateConfigSourceValues.Entry entry( + DraftCommitBinding source, String id, String name, TemplateConfigSourceValues.Config config) { + var revision = source.revisions().getFirst(); + return new TemplateConfigSourceValues.Entry( + id, config, source, revision.revisionOrder(), revision.revisionId(), name); + } + + private static Map snapshotObject( + DraftCommitBinding selected, + List> entries, + List> declarations) { + var value = new LinkedHashMap(); + value.put( + "schema", + declarations == null + ? TemplateConfigSourceSnapshot.SCHEMA + : TemplateConfigSourceSnapshot.SCHEMA_V2); + value.put("bindingJson", selected.canonicalJson()); + value.put("bindingDigest", selected.digest()); + value.put("sourceEpoch", "1"); + value.put("inheritedCommitId", ""); + value.put("genesisReceiptId", GENESIS.toString()); + value.put("entries", entries); + if (declarations != null) value.put("ownerSourceInventoryDeclarations", declarations); + return value; + } + + private static String canonical(Object value) throws Exception { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(new ObjectMapper().writeValueAsString(value)), + StandardCharsets.UTF_8); + } + + private static String digest(String json) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(json.getBytes(StandardCharsets.UTF_8))); + } + + private static String config() { + return "{\"schemaVersion\":1,\"baseVersionId\":\"" + + VERSION + + "\",\"world\":{\"regions\":[],\"rooms\":[]},\"entity\":{\"items\":[],\"npcs\":[]}," + + "\"gameLogic\":{\"inputs\":[]},\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}},\"supportedSettings\":[]}"; + } + + private static String automationInventory() { + return "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":" + + "{\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[],\"SCRIPT_PATCH_SOURCES\":[]}}"; + } + + private static String entityInventory() { + return "{\"schema\":\"entity-authored-source-inventory/v1\",\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[],\"ARCHETYPE_CONSTRAINTS\":[]," + + "\"ARCHETYPE_ROOTS\":[],\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[],\"CRAFTING_INGREDIENT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_RESULT_BINDINGS\":[],\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[],\"EQUIPMENT_OCCUPANCY_RULES\":[]," + + "\"EQUIPMENT_SLOT_GROUPS\":[],\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[],\"LOOT_TABLE_ROOTS\":[]," + + "\"NPC_TEMPLATE_ROOTS\":[],\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"; + } + + private static DraftCommitBinding binding(String... payloads) { + if (payloads.length == 0) payloads = new String[] {"{\"revisionKind\":\"COMMAND_DEFINITION\"}"}; + var revisions = new ArrayList(); + for (int i = 0; i < payloads.length; i++) + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[i])); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + VERSION.toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java index 9e296291d6..3dcadeaf9d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigOwnerSourceInventoryDeclaration.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.gamedesign.publication; import java.util.Map; -import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -36,85 +35,39 @@ public TemplateConfigOwnerSourceInventoryDeclaration( } public TemplateConfigOwnerSourceInventoryDeclaration { - if (owner == Owner.AUTOMATION_SCRIPTING) { - if (inventory == null || entityInventory != null) - throw new IllegalArgumentException("Automation owner requires its typed inventory"); - } else if (owner == Owner.ENTITY_MANAGEMENT) { - if (entityInventory == null || inventory != null) - throw new IllegalArgumentException("Entity owner requires its typed inventory"); - } else { - throw new IllegalArgumentException("Unsupported owner source inventory content"); - } - Objects.requireNonNull(sourceBinding); - if (revisionOrder == null || !revisionOrder.matches("0|[1-9][0-9]*")) - throw new IllegalArgumentException("Exact owner source inventory revision order required"); - TemplateConfigSource.uuid(Objects.requireNonNull(revisionId).toString()); - var revision = - sourceBinding.revisions().stream() - .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) - .filter( - r -> r.revisionId().equals(revisionId) && r.revisionOrder().equals(revisionOrder)) - .findFirst() - .orElseThrow(); - String expectedPayload = - owner == Owner.AUTOMATION_SCRIPTING - ? TemplateConfigSource.ownerInventoryPayload(owner, inventory) - : TemplateConfigSource.ownerInventoryPayload(owner, entityInventory); - if (!expectedPayload.equals(CommandSource.canonical(CommandSource.tree(revision.payload())))) - throw new IllegalArgumentException( - "Owner inventory differs from its exact original source revision"); + new net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration( + owner, inventory, entityInventory, sourceBinding, revisionOrder, revisionId); } Map object() { - return Map.of( - "owner", owner.name(), - "inventoryJson", inventoryJson(), - "sourceBindingJson", sourceBinding.canonicalJson(), - "sourceBindingDigest", sourceBinding.digest(), - "revisionOrder", revisionOrder, - "revisionId", revisionId.toString()); + return shared().object(); } static TemplateConfigOwnerSourceInventoryDeclaration fromStored(JsonNode node) { - CommandSource.requireStoredFields( - node, - "owner", - "inventoryJson", - "sourceBindingJson", - "sourceBindingDigest", - "revisionOrder", - "revisionId"); - Owner owner = Owner.valueOf(CommandSource.requiredStoredText(node, "owner")); - String inventoryJson = CommandSource.requiredStoredText(node, "inventoryJson"); - var binding = - DraftCommitBinding.fromStored( - CommandSource.requiredStoredText(node, "sourceBindingJson"), - CommandSource.requiredStoredText(node, "sourceBindingDigest")); - String revisionOrder = CommandSource.requiredStoredText(node, "revisionOrder"); - UUID revisionId = - TemplateConfigSource.uuid(CommandSource.requiredStoredText(node, "revisionId")); - return switch (owner) { - case AUTOMATION_SCRIPTING -> - new TemplateConfigOwnerSourceInventoryDeclaration( - owner, - AutomationAuthoredSourceInventoryDeclaration.parse(inventoryJson), - binding, - revisionOrder, - revisionId); - case ENTITY_MANAGEMENT -> - new TemplateConfigOwnerSourceInventoryDeclaration( - owner, - EntityAuthoredSourceInventoryDeclaration.parse(inventoryJson), - binding, - revisionOrder, - revisionId); - default -> throw new IllegalArgumentException("Unsupported owner source inventory content"); - }; + return fromShared( + net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration + .fromStored(node)); } String inventoryJson() { - return owner == Owner.AUTOMATION_SCRIPTING - ? inventory.canonicalJson() - : entityInventory.canonicalJson(); + return shared().inventoryJson(); + } + + net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration shared() { + return new net.firedevops.firemud.common.gamedesign + .TemplateConfigOwnerSourceInventoryDeclaration( + owner, inventory, entityInventory, sourceBinding, revisionOrder, revisionId); + } + + static TemplateConfigOwnerSourceInventoryDeclaration fromShared( + net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration + value) { + return new TemplateConfigOwnerSourceInventoryDeclaration( + value.owner(), + value.inventory(), + value.entityInventory(), + value.sourceBinding(), + value.revisionOrder(), + value.revisionId()); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java index df3e36e8f9..0d757ec07b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSource.java @@ -1,27 +1,23 @@ package net.firedevops.firemud.gamedesign.publication; import java.math.BigInteger; -import java.util.ArrayList; import java.util.Comparator; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; -import tools.jackson.databind.JsonNode; /** Closed authored wiring. Syntax validation never qualifies an external owner's reference. */ public final class TemplateConfigSource { - public static final String REVISION_KIND = "TEMPLATE_CONFIG"; - public static final String SCOPE = "TEMPLATE_CONFIG_SET"; - public static final String SCOPE_ID = "effective"; + public static final String REVISION_KIND = TemplateConfigSourceValues.REVISION_KIND; + public static final String SCOPE = TemplateConfigSourceValues.SCOPE; + public static final String SCOPE_ID = TemplateConfigSourceValues.SCOPE_ID; private TemplateConfigSource() {} @@ -34,108 +30,38 @@ public enum OperationKind { public record GameplayInput(Family family, String key, UUID revisionId) { public GameplayInput { - Objects.requireNonNull(family); - GameplayRuleManifest.identifier(key); - uuid(revisionId.toString()); + new TemplateConfigSourceValues.GameplayInput(family, key, revisionId); } } /** Canonical config remains the actual authored document, without derived commit evidence. */ public record Config(String canonicalJson) { public Config { - JsonNode root = CommandSource.tree(canonicalJson); - fields( - root, - "schemaVersion", - "baseVersionId", - "world", - "entity", - "gameLogic", - "automation", - "supportedSettings"); - if (!root.path("schemaVersion").isInt() || root.path("schemaVersion").intValue() != 1) - throw new IllegalArgumentException("Unsupported template config schemaVersion"); - uuid(text(root, "baseVersionId")); - fields(root.path("world"), "regions", "rooms"); - ownerIds(root.path("world"), "regions", "regionTemplateId"); - ownerIds(root.path("world"), "rooms", "roomTemplateId"); - fields(root.path("entity"), "items", "npcs"); - ownerIds(root.path("entity"), "items", "entityTemplateId"); - ownerIds(root.path("entity"), "npcs", "entityTemplateId"); - fields(root.path("gameLogic"), "inputs"); - Set rules = new HashSet<>(); - for (JsonNode node : array(root.path("gameLogic"), "inputs")) { - fields(node, "family", "key", "revisionId"); - Family family = Family.valueOf(text(node, "family")); - String key = text(node, "key"); - GameplayRuleManifest.identifier(key); - uuid(text(node, "revisionId")); - if (!rules.add(family.name() + ":" + key)) - throw new IllegalArgumentException("Duplicate template gameplay input"); - } - fields(root.path("automation"), "scripts", "scriptPatch"); - Set scripts = new HashSet<>(); - for (JsonNode node : array(root.path("automation"), "scripts")) { - fields(node, "scriptId", "eventBindings"); - if (!scripts.add(text(node, "scriptId"))) - throw new IllegalArgumentException("Duplicate template script name"); - Set bindings = new HashSet<>(); - for (JsonNode event : array(node, "eventBindings")) { - fields( - event, - "eventType", - "eventSchemaVersion", - "bindingId", - "targetScopeType", - "targetScopeId"); - text(event, "eventType"); - text(event, "eventSchemaVersion"); - for (String key : List.of("bindingId", "targetScopeType", "targetScopeId")) - if (!event.path(key).isTextual()) - throw new IllegalArgumentException("Exact Automation binding key required"); - if (!bindings.add(CommandSource.canonical(event))) - throw new IllegalArgumentException("Duplicate template event binding"); - } - } - JsonNode patch = root.path("automation").path("scriptPatch"); - String presence = text(patch, "presence"); - if ("ABSENT".equals(presence)) fields(patch, "presence"); - else if ("PRESENT".equals(presence)) { - fields(patch, "presence", "scriptPatchVersion"); - text(patch, "scriptPatchVersion"); - } else throw new IllegalArgumentException("Explicit template script-patch presence required"); - if (!array(root, "supportedSettings").isEmpty()) - throw new IllegalArgumentException( - "No supported non-authoritative settings are registered"); - canonicalJson = CommandSource.canonical(root); + canonicalJson = new TemplateConfigSourceValues.Config(canonicalJson).canonicalJson(); + } + + TemplateConfigSourceValues.Config shared() { + return new TemplateConfigSourceValues.Config(canonicalJson); } public UUID baseVersionId() { - return uuid(text(CommandSource.tree(canonicalJson), "baseVersionId")); + return shared().baseVersionId(); } public List gameplayInputs() { - List inputs = new ArrayList<>(); - for (JsonNode node : CommandSource.tree(canonicalJson).path("gameLogic").path("inputs")) - inputs.add( - new GameplayInput( - Family.valueOf(text(node, "family")), - text(node, "key"), - uuid(text(node, "revisionId")))); - return List.copyOf(inputs); + return shared().gameplayInputs().stream() + .map(value -> new GameplayInput(value.family(), value.key(), value.revisionId())) + .toList(); } /** These missing authenticated owner boundaries deliberately prevent qualification. */ public void requireAvailableOwnerReads() { - var root = CommandSource.tree(canonicalJson); - if (!root.path("world").path("regions").isEmpty() - || !root.path("world").path("rooms").isEmpty()) + var value = shared(); + if (value.hasWorldReferences()) throw new IllegalStateException("TEMPLATE_CONFIG_WORLD_EXACT_OWNER_READ_UNAVAILABLE"); - if (!root.path("entity").path("items").isEmpty() - || !root.path("entity").path("npcs").isEmpty()) + if (value.hasEntityReferences()) throw new IllegalStateException("TEMPLATE_CONFIG_ENTITY_EXACT_OWNER_READ_UNAVAILABLE"); - if (!root.path("automation").path("scripts").isEmpty() - || "PRESENT".equals(text(root.path("automation").path("scriptPatch"), "presence"))) + if (value.hasAutomationReferences()) throw new IllegalStateException("TEMPLATE_CONFIG_AUTOMATION_EXACT_OWNER_READ_UNAVAILABLE"); } } @@ -173,84 +99,66 @@ public Mutation( } public Mutation { - Objects.requireNonNull(binding); - Objects.requireNonNull(operation); - if (operation == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { - if (templateId != null - || templateName != null - || config != null - || declaredOwner == null - || !Set.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT).contains(declaredOwner) - || (declaredOwner == Owner.AUTOMATION_SCRIPTING - ? inventory == null || entityInventory != null - : entityInventory == null || inventory != null)) - throw new IllegalArgumentException( - "Owner inventory declaration carries only its supported owner's authored content"); - new TemplateConfigOwnerSourceInventoryDeclaration( - declaredOwner, inventory, entityInventory, binding, revisionOrder, revisionId); - } else if (declaredOwner != null || inventory != null || entityInventory != null) { - throw new IllegalArgumentException("Template row mutations carry no owner inventory"); - } else if (operation == OperationKind.CREATE) { - if (templateId != null - || templateName == null - || templateName.isBlank() - || templateName.length() > 100) - throw new IllegalArgumentException( - "CREATE requires a display name and no caller template id"); - } else { - requireTemplateId(templateId); - if (templateName != null) - throw new IllegalArgumentException("Only CREATE carries a display name"); - } - if (operation != OperationKind.DELETE - && operation != OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { - Objects.requireNonNull(config); - if (!binding.target().canonicalVersionId().equals(config.baseVersionId())) - throw new IllegalArgumentException( - "Template config base differs from its exact source version"); - } else if (operation == OperationKind.DELETE && config != null) - throw new IllegalArgumentException("Template DELETE carries no config"); - var revision = - binding.revisions().stream() - .filter(r -> r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE) - .filter( - r -> r.revisionId().equals(revisionId) && r.revisionOrder().equals(revisionOrder)) - .findFirst() - .orElseThrow(); - String expected = - payloadFor( - operation, - templateId, - templateName, - config, - declaredOwner, - inventory, - entityInventory); - if (!expected.equals(CommandSource.canonical(CommandSource.tree(revision.payload())))) - throw new IllegalArgumentException( - "Template config differs from its exact original revision"); + new TemplateConfigSourceValues.Mutation( + binding, + revisionOrder, + revisionId, + operation == null + ? null + : TemplateConfigSourceValues.OperationKind.valueOf(operation.name()), + templateId, + templateName, + config == null ? null : config.shared(), + declaredOwner, + inventory, + entityInventory); } public String payload() { - return payloadFor( - operation, templateId, templateName, config, declaredOwner, inventory, entityInventory); + return shared().payload(); } public boolean changesTemplateRow() { - return operation != OperationKind.DECLARE_OWNER_SOURCE_INVENTORY; + return shared().changesTemplateRow(); } public TemplateConfigOwnerSourceInventoryDeclaration ownerInventoryDeclaration() { - return operation == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY - ? new TemplateConfigOwnerSourceInventoryDeclaration( - declaredOwner, inventory, entityInventory, binding, revisionOrder, revisionId) - : null; + var declaration = shared().ownerInventoryDeclaration(); + return declaration == null + ? null + : TemplateConfigOwnerSourceInventoryDeclaration.fromShared(declaration); } public String inventoryJson() { - if (inventory != null) return inventory.canonicalJson(); - if (entityInventory != null) return entityInventory.canonicalJson(); - throw new IllegalStateException("Mutation has no owner inventory content"); + return shared().inventoryJson(); + } + + TemplateConfigSourceValues.Mutation shared() { + return new TemplateConfigSourceValues.Mutation( + binding, + revisionOrder, + revisionId, + TemplateConfigSourceValues.OperationKind.valueOf(operation.name()), + templateId, + templateName, + config == null ? null : config.shared(), + declaredOwner, + inventory, + entityInventory); + } + + static Mutation fromShared(TemplateConfigSourceValues.Mutation value) { + return new Mutation( + value.binding(), + value.revisionOrder(), + value.revisionId(), + OperationKind.valueOf(value.operation().name()), + value.templateId(), + value.templateName(), + value.config() == null ? null : new Config(value.config().canonicalJson()), + value.declaredOwner(), + value.inventory(), + value.entityInventory()); } } @@ -262,197 +170,61 @@ public record Entry( UUID revisionId, String createdName) { public Entry { - requireTemplateId(templateId); - new Mutation( + new TemplateConfigSourceValues.Entry( + templateId, + config == null ? null : config.shared(), sourceBinding, revisionOrder, revisionId, - createdName == null ? OperationKind.UPSERT : OperationKind.CREATE, - createdName == null ? templateId : null, - createdName, - config); + createdName); } Map object() { - return Map.of( - "templateId", - templateId, - "configJson", - config.canonicalJson(), - "sourceBindingJson", - sourceBinding.canonicalJson(), - "sourceBindingDigest", - sourceBinding.digest(), - "revisionOrder", - revisionOrder, - "revisionId", - revisionId.toString(), - "createdName", - createdName == null ? "" : createdName); + return shared().object(); + } + + TemplateConfigSourceValues.Entry shared() { + return new TemplateConfigSourceValues.Entry( + templateId, config.shared(), sourceBinding, revisionOrder, revisionId, createdName); + } + + static Entry fromShared(TemplateConfigSourceValues.Entry value) { + return new Entry( + value.templateId(), + new Config(value.config().canonicalJson()), + value.sourceBinding(), + value.revisionOrder(), + value.revisionId(), + value.createdName()); } } public static List mutations(DraftCommitBinding binding) { - List result = new ArrayList<>(); - Set declaredOwners = new HashSet<>(); - for (var revision : binding.revisions()) { - if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; - JsonNode root = CommandSource.tree(revision.payload()); - String kind = text(root, "revisionKind"); - if (Set.of( - "COMMAND_DEFINITION", - "REALM_ENTRY_POLICY", - "ASSET_REFERENCE", - "GAMEPLAY_RULE", - "BRANDING_ASSET_REFERENCE") - .contains(kind)) continue; - if (!REVISION_KIND.equals(kind)) - throw new IllegalArgumentException("Unknown Game Design revision kind"); - OperationKind operation = OperationKind.valueOf(text(root, "operation")); - int schemaVersion = - root.path("schemaVersion").isInt() ? root.path("schemaVersion").intValue() : -1; - if (operation == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) { - fields(root, "schemaVersion", "revisionKind", "operation", "owner", "inventory"); - Owner owner = Owner.valueOf(text(root, "owner")); - if (!Set.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT).contains(owner) - || !declaredOwners.add(owner)) - throw new IllegalArgumentException("Only one declaration per supported owner is allowed"); - if (owner == Owner.AUTOMATION_SCRIPTING) { - if (schemaVersion != 2) - throw new IllegalArgumentException( - "Unsupported Automation owner inventory source schemaVersion"); - result.add( - new Mutation( - binding, - revision.revisionOrder(), - revision.revisionId(), - operation, - null, - null, - null, - owner, - AutomationAuthoredSourceInventoryDeclaration.parse( - CommandSource.canonical(root.path("inventory"))), - null)); - } else { - if (schemaVersion != 3) - throw new IllegalArgumentException( - "Unsupported Entity owner inventory source schemaVersion"); - result.add( - new Mutation( - binding, - revision.revisionOrder(), - revision.revisionId(), - operation, - null, - null, - null, - owner, - null, - EntityAuthoredSourceInventoryDeclaration.parse( - CommandSource.canonical(root.path("inventory"))))); - } - continue; - } - if (schemaVersion != 1) - throw new IllegalArgumentException("Unsupported template source schemaVersion"); - fields( - root, - operation == OperationKind.CREATE - ? new String[] { - "schemaVersion", "revisionKind", "operation", "templateName", "configJson" - } - : operation == OperationKind.UPSERT - ? new String[] { - "schemaVersion", "revisionKind", "operation", "templateId", "configJson" - } - : new String[] {"schemaVersion", "revisionKind", "operation", "templateId"}); - result.add( - new Mutation( - binding, - revision.revisionOrder(), - revision.revisionId(), - operation, - operation == OperationKind.CREATE ? null : text(root, "templateId"), - operation == OperationKind.CREATE ? text(root, "templateName") : null, - operation != OperationKind.DELETE ? new Config(text(root, "configJson")) : null)); - } - return List.copyOf(result); + return TemplateConfigSourceValues.mutations(binding).stream() + .map(Mutation::fromShared) + .toList(); } public static String upsertPayload(String templateId, Config config) { - requireTemplateId(templateId); - return CommandSource.canonical( - Map.of( - "schemaVersion", - 1, - "revisionKind", - REVISION_KIND, - "operation", - "UPSERT", - "templateId", - templateId, - "configJson", - config.canonicalJson())); + return TemplateConfigSourceValues.upsertPayload(templateId, config.shared()); } public static String createPayload(String templateName, Config config) { - if (templateName == null || templateName.isBlank() || templateName.length() > 100) - throw new IllegalArgumentException("Template display name required"); - return CommandSource.canonical( - Map.of( - "schemaVersion", - 1, - "revisionKind", - REVISION_KIND, - "operation", - "CREATE", - "templateName", - templateName, - "configJson", - config.canonicalJson())); + return TemplateConfigSourceValues.createPayload(templateName, config.shared()); } public static String deletePayload(String templateId) { - requireTemplateId(templateId); - return CommandSource.canonical( - Map.of( - "schemaVersion", - 1, - "revisionKind", - REVISION_KIND, - "operation", - "DELETE", - "templateId", - templateId)); + return TemplateConfigSourceValues.deletePayload(templateId); } public static String ownerInventoryPayload( Owner owner, AutomationAuthoredSourceInventoryDeclaration inventory) { - if (owner != Owner.AUTOMATION_SCRIPTING) - throw new IllegalArgumentException("Only Automation source inventory is supported"); - Objects.requireNonNull(inventory); - return CommandSource.canonical( - Map.of( - "schemaVersion", 2, - "revisionKind", REVISION_KIND, - "operation", OperationKind.DECLARE_OWNER_SOURCE_INVENTORY.name(), - "owner", owner.name(), - "inventory", CommandSource.tree(inventory.canonicalJson()))); + return TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory); } public static String ownerInventoryPayload( Owner owner, EntityAuthoredSourceInventoryDeclaration inventory) { - if (owner != Owner.ENTITY_MANAGEMENT) - throw new IllegalArgumentException("Only Entity source inventory is supported"); - Objects.requireNonNull(inventory); - return CommandSource.canonical( - Map.of( - "schemaVersion", 3, - "revisionKind", REVISION_KIND, - "operation", OperationKind.DECLARE_OWNER_SOURCE_INVENTORY.name(), - "owner", owner.name(), - "inventory", CommandSource.tree(inventory.canonicalJson()))); + return TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory); } public static List @@ -476,25 +248,6 @@ public static String ownerInventoryPayload( .toList(); } - private static String payloadFor( - OperationKind operation, - String templateId, - String templateName, - Config config, - Owner declaredOwner, - AutomationAuthoredSourceInventoryDeclaration inventory, - EntityAuthoredSourceInventoryDeclaration entityInventory) { - return switch (operation) { - case CREATE -> createPayload(templateName, config); - case UPSERT -> upsertPayload(templateId, config); - case DELETE -> deletePayload(templateId); - case DECLARE_OWNER_SOURCE_INVENTORY -> - inventory != null - ? ownerInventoryPayload(declaredOwner, inventory) - : ownerInventoryPayload(declaredOwner, entityInventory); - }; - } - public static List replay( List inherited, DraftCommitBinding binding, Map createdRows) { Map entries = new java.util.HashMap<>(); @@ -541,40 +294,7 @@ public static boolean isScope(DraftCommitBinding.AffectedUnit unit) { && SCOPE_ID.equals(unit.scopeId()); } - private static void requireTemplateId(String value) { - if (value == null - || !value.matches("[1-9][0-9]*") - || new BigInteger(value).compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) - throw new IllegalArgumentException("Exact Game Design template row identity required"); - } - static UUID uuid(String value) { - UUID result = UUID.fromString(value); - if (!result.toString().equals(value) || new UUID(0, 0).equals(result)) - throw new IllegalArgumentException("Canonical nonzero owner UUID required"); - return result; - } - - private static void ownerIds(JsonNode root, String collection, String key) { - Set ids = new HashSet<>(); - for (JsonNode node : array(root, collection)) { - fields(node, key); - if (!ids.add(uuid(text(node, key)))) - throw new IllegalArgumentException("Duplicate owner template reference"); - } - } - - private static JsonNode array(JsonNode root, String key) { - if (!root.path(key).isArray()) - throw new IllegalArgumentException("Explicit template config collection required: " + key); - return root.path(key); - } - - private static void fields(JsonNode node, String... fields) { - CommandSource.requireStoredFields(node, fields); - } - - private static String text(JsonNode node, String key) { - return CommandSource.requiredStoredText(node, key); + return TemplateConfigSourceValues.uuid(value); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java index 4f2f65c097..d5768c2a94 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java @@ -1,10 +1,7 @@ package net.firedevops.firemud.gamedesign.publication; import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; @@ -20,8 +17,10 @@ public record TemplateConfigSourceSnapshot( UUID genesisReceiptId, List entries, List ownerSourceInventoryDeclarations) { - public static final String SCHEMA = "game-design-template-config-source-snapshot/v1"; - public static final String SCHEMA_V2 = "game-design-template-config-source-snapshot/v2"; + public static final String SCHEMA = + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot.SCHEMA; + public static final String SCHEMA_V2 = + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot.SCHEMA_V2; public TemplateConfigSourceSnapshot( DraftCommitBinding binding, @@ -33,151 +32,59 @@ public TemplateConfigSourceSnapshot( } public TemplateConfigSourceSnapshot { - Objects.requireNonNull(binding); - if (sourceEpoch == null || !sourceEpoch.matches("0|[1-9][0-9]*")) - throw new IllegalArgumentException("Exact template source epoch required"); - DraftAuthorizationFenceBinding.requireUuid(genesisReceiptId); - if (inheritedCommitId != null) DraftAuthorizationFenceBinding.requireUuid(inheritedCommitId); entries = List.copyOf(entries); - var keys = new java.util.HashSet(); - for (var entry : entries) - if (!entry.sourceBinding().target().equals(binding.target()) || !keys.add(entry.templateId())) - throw new IllegalArgumentException("Template source target or identity conflict"); - if (!entries.equals( - entries.stream() - .sorted(java.util.Comparator.comparing(e -> new BigInteger(e.templateId()))) - .toList())) throw new IllegalArgumentException("Canonical template row order required"); ownerSourceInventoryDeclarations = List.copyOf(ownerSourceInventoryDeclarations); - var owners = - new java.util.HashSet(); - for (var declaration : ownerSourceInventoryDeclarations) { - if (!declaration.sourceBinding().target().equals(binding.target()) - || !owners.add(declaration.owner())) - throw new IllegalArgumentException("Template owner inventory target or identity conflict"); - } - if (!ownerSourceInventoryDeclarations.equals( + new net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot( + binding, + sourceEpoch, + inheritedCommitId, + genesisReceiptId, + entries.stream().map(TemplateConfigSource.Entry::shared).toList(), ownerSourceInventoryDeclarations.stream() - .sorted(java.util.Comparator.comparing(value -> value.owner().name())) - .toList())) - throw new IllegalArgumentException("Canonical owner inventory order required"); + .map(TemplateConfigOwnerSourceInventoryDeclaration::shared) + .toList()); } public String canonicalJson() { - Map value = - new java.util.LinkedHashMap<>( - Map.of( - "schema", - ownerSourceInventoryDeclarations.isEmpty() ? SCHEMA : SCHEMA_V2, - "bindingJson", - binding.canonicalJson(), - "bindingDigest", - binding.digest(), - "sourceEpoch", - sourceEpoch, - "inheritedCommitId", - inheritedCommitId == null ? "" : inheritedCommitId.toString(), - "genesisReceiptId", - genesisReceiptId.toString(), - "entries", - entries.stream().map(TemplateConfigSource.Entry::object).toList())); - if (!ownerSourceInventoryDeclarations.isEmpty()) - value.put( - "ownerSourceInventoryDeclarations", - ownerSourceInventoryDeclarations.stream() - .map(TemplateConfigOwnerSourceInventoryDeclaration::object) - .toList()); - return CommandSource.canonical(value); + return shared().canonicalJson(); } public byte[] canonicalBytes() { - return canonicalJson().getBytes(StandardCharsets.UTF_8); + return shared().canonicalBytes(); } public String digest() { - return CommandSource.sha256(canonicalBytes()); + return shared().digest(); } public static TemplateConfigSourceSnapshot fromStored(String json) { - var root = CommandSource.tree(json); - String schema = CommandSource.requiredStoredText(root, "schema"); - if (SCHEMA.equals(schema)) { - CommandSource.requireStoredFields( - root, - "schema", - "bindingJson", - "bindingDigest", - "sourceEpoch", - "inheritedCommitId", - "genesisReceiptId", - "entries"); - } else if (SCHEMA_V2.equals(schema)) { - CommandSource.requireStoredFields( - root, - "schema", - "bindingJson", - "bindingDigest", - "sourceEpoch", - "inheritedCommitId", - "genesisReceiptId", - "entries", - "ownerSourceInventoryDeclarations"); - } else { - throw new IllegalArgumentException("Unsupported template config source snapshot"); - } - if (!root.path("entries").isArray() - || (SCHEMA_V2.equals(schema) && !root.path("ownerSourceInventoryDeclarations").isArray())) - throw new IllegalArgumentException( - "Template config source snapshot collections are required"); - var binding = - DraftCommitBinding.fromStored( - CommandSource.requiredStoredText(root, "bindingJson"), - CommandSource.requiredStoredText(root, "bindingDigest")); - List entries = new ArrayList<>(); - for (var node : root.path("entries")) { - CommandSource.requireStoredFields( - node, - "templateId", - "configJson", - "sourceBindingJson", - "sourceBindingDigest", - "revisionOrder", - "revisionId", - "createdName"); - if (!node.path("createdName").isTextual()) - throw new IllegalArgumentException("Explicit source operation identity required"); - String name = node.path("createdName").textValue(); - entries.add( - new TemplateConfigSource.Entry( - CommandSource.requiredStoredText(node, "templateId"), - new TemplateConfigSource.Config(CommandSource.requiredStoredText(node, "configJson")), - DraftCommitBinding.fromStored( - CommandSource.requiredStoredText(node, "sourceBindingJson"), - CommandSource.requiredStoredText(node, "sourceBindingDigest")), - CommandSource.requiredStoredText(node, "revisionOrder"), - TemplateConfigSource.uuid(CommandSource.requiredStoredText(node, "revisionId")), - name.isEmpty() ? null : name)); - } - List declarations = new ArrayList<>(); - if (SCHEMA_V2.equals(schema)) - for (var node : root.path("ownerSourceInventoryDeclarations")) - declarations.add(TemplateConfigOwnerSourceInventoryDeclaration.fromStored(node)); - if (!root.path("inheritedCommitId").isTextual()) - throw new IllegalArgumentException("Explicit predecessor required"); - String inherited = root.path("inheritedCommitId").textValue(); - var result = - new TemplateConfigSourceSnapshot( - binding, - CommandSource.requiredStoredText(root, "sourceEpoch"), - inherited.isEmpty() ? null : TemplateConfigSource.uuid(inherited), - TemplateConfigSource.uuid(CommandSource.requiredStoredText(root, "genesisReceiptId")), - entries, - declarations); - if ((SCHEMA.equals(schema) && !result.ownerSourceInventoryDeclarations().isEmpty()) - || (SCHEMA_V2.equals(schema) && result.ownerSourceInventoryDeclarations().isEmpty())) - throw new IllegalArgumentException("Template config source snapshot schema mismatch"); - if (!json.equals(result.canonicalJson())) - throw new IllegalArgumentException("Noncanonical template config snapshot"); - return result; + return fromShared( + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot.fromStored(json)); + } + + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot shared() { + return new net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot( + binding, + sourceEpoch, + inheritedCommitId, + genesisReceiptId, + entries.stream().map(TemplateConfigSource.Entry::shared).toList(), + ownerSourceInventoryDeclarations.stream() + .map(TemplateConfigOwnerSourceInventoryDeclaration::shared) + .toList()); + } + + static TemplateConfigSourceSnapshot fromShared( + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot value) { + return new TemplateConfigSourceSnapshot( + value.binding(), + value.sourceEpoch(), + value.inheritedCommitId(), + value.genesisReceiptId(), + value.entries().stream().map(TemplateConfigSource.Entry::fromShared).toList(), + value.ownerSourceInventoryDeclarations().stream() + .map(TemplateConfigOwnerSourceInventoryDeclaration::fromShared) + .toList()); } public record Genesis(TargetProof target, UUID receiptId, String creationTransactionId) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java new file mode 100644 index 0000000000..f77ca86f4e --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java @@ -0,0 +1,243 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.SQLException; +import java.util.HexFormat; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** Physical V69-to-V70 upgrade proof using isolated, explicitly synthetic upstream evidence. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class SelectedInventoryProfileUpgradeIntegrationTest { + private static final ObjectMapper JSON = new ObjectMapper(); + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void forwardUpgradePreservesRetainedV1OperationAndAdmitsOnlyPairedProfiles() throws Exception { + String schema = "gd_inventory_upgrade_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = + new DriverManagerDataSource( + POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); + dataSource.setSchema(schema); + + flyway(dataSource, schema, "69").migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var transactions = new DataSourceTransactionManager(dataSource); + var transaction = new TransactionTemplate(transactions); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + Version version = + transaction.execute( + status -> { + Game game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("synthetic historical inventory owner"); + new GameRepository(dsl).save(game); + + Version draft = new Version(); + draft.setTenantId(game.getTenantId()); + draft.setVersionNumber(1); + draft.setVersionState(VersionLifecycleState.DRAFT); + draft.setVersionStateEpoch(1L); + draft.setNotes("synthetic V69 inventory upgrade fixture"); + return new VersionRepository(dsl).save(draft); + }); + TargetProof target = targetProof(version); + + // This shared fixture creates the historical inventory/v1 + graph/2 + digest/3 profile. + // The owner setup writes real GD selection, attempt and operation rows; Account and World + // source/receipt authority remains stipulated test evidence, not a production claim. + GameDesignPublicationOperation historicalV1 = + transaction.execute( + status -> { + try { + return IsolatedPublicationOwnerSetup.retain( + dsl, target, version.getVersionStateEpoch(), "synthetic V69 history"); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + assertThat(historicalV1.inventory().publicEvidence().schema()) + .isEqualTo("world-selected-publication-artifact-inventory/v1"); + assertThat(historicalV1.world().request().digestSchemaVersion()).isEqualTo(3); + assertThat(historicalV1.inventory().publicEvidence().sourceModel().graphSchemaVersion()) + .isEqualTo(2); + + byte[] originalOperationBytes = historicalV1.canonicalBytes(); + assertThat(readOperationBytes(dsl, historicalV1.workflowId())) + .containsExactly(originalOperationBytes); + // The actual V56 validator is still installed at V69 and must accept the historical bytes. + dsl.fetch("SELECT require_selected_inventory_operation_v2(?)", originalOperationBytes); + + flyway(dataSource, schema, null).migrate(); + + assertThat(readOperationBytes(dsl, historicalV1.workflowId())) + .containsExactly(originalOperationBytes); + var repository = new GameDesignPublicationOperationRepository(dsl); + assertThat( + repository.read(historicalV1.workflowId()).orElseThrow().operation().canonicalBytes()) + .containsExactly(originalOperationBytes); + + transaction.executeWithoutResult(status -> repository.reserve(historicalV1)); + assertThat(readOperationBytes(dsl, historicalV1.workflowId())) + .containsExactly(originalOperationBytes); + + GameDesignPublicationOperation closureV2 = + IsolatedPublicationOperationFixtures.freshClosureQualifiedSelection(target); + assertThat(closureV2.inventory().publicEvidence().schema()) + .isEqualTo("world-selected-publication-artifact-inventory/v2"); + assertThat(closureV2.world().request().digestSchemaVersion()).isEqualTo(4); + dsl.fetch("SELECT require_selected_inventory_operation_v2(?)", closureV2.canonicalBytes()); + + assertRejected( + dsl, + rebindInventory( + closureV2, + inventory -> { + inventory.put("schema", "world-selected-publication-artifact-inventory/v1"); + inventory.put("schemaVersion", 1); + }), + "Incomplete or unknown public inventory members"); + assertRejected( + dsl, + rebindInventory( + closureV2, + inventory -> + ((tools.jackson.databind.node.ObjectNode) inventory.get("checkpoint")) + .put("digestSchemaVersion", 3)), + "Inventory differs from exact original selected Account, APPLIED graph or freeze"); + assertRejected( + dsl, + rebindInventory( + closureV2, + inventory -> + ((tools.jackson.databind.node.ObjectNode) inventory.get("sourceModel")) + .put("unknownSourceFamily", true)), + "Incomplete or unknown public inventory members"); + assertRejected( + dsl, + rebindInventory( + closureV2, + inventory -> + ((tools.jackson.databind.node.ObjectNode) + inventory + .get("sourceModel") + .get("inboundSourceClosure") + .get("familyCounts") + .get(0)) + .put("count", 1)), + "Inventory differs from exact original selected Account, APPLIED graph or freeze"); + } + + private static Flyway flyway(DriverManagerDataSource dataSource, String schema, String target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .placeholders(Map.of("serviceSchema", schema)) + .locations(migrations()); + if (target != null) configuration.target(target); + return configuration.load(); + } + + private static String migrations() { + for (Path current = Path.of("").toAbsolutePath(); + current != null; + current = current.getParent()) { + Path target = current.resolve("services/game-design-service/src/main/resources/db/migration"); + if (Files.isDirectory(target)) return "filesystem:" + target; + } + throw new IllegalStateException("Game Design migration directory unavailable"); + } + + private static TargetProof targetProof(Version version) { + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + } + + private static byte[] readOperationBytes(DSLContext dsl, String workflowId) { + var row = + dsl.fetchOne( + "SELECT request_bytes FROM game_design_publication_operation WHERE publish_workflow_id = ?", + workflowId); + if (row == null) throw new AssertionError("Retained publication operation is absent"); + return row.get("request_bytes", byte[].class); + } + + private static byte[] rebindInventory( + GameDesignPublicationOperation operation, + java.util.function.Consumer mutation) + throws Exception { + var inventory = + (tools.jackson.databind.node.ObjectNode) + JSON.readTree(operation.inventory().canonicalBytes()); + mutation.accept(inventory); + byte[] changedInventory = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(inventory)); + var bytes = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(bytes, GameDesignPublicationOperation.SCHEMA); + DraftAuthorizationFenceBinding.frame(bytes, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(bytes, operation.world().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(bytes, changedInventory); + DraftAuthorizationFenceBinding.frame(bytes, sha256(changedInventory)); + return bytes.toByteArray(); + } + + private static String sha256(byte[] value) throws Exception { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static void assertRejected(DSLContext dsl, byte[] operationBytes, String message) { + assertThatThrownBy( + () -> dsl.fetch("SELECT require_selected_inventory_operation_v2(?)", operationBytes)) + .rootCause() + .isInstanceOf(SQLException.class) + .hasMessageContaining(message) + .satisfies( + failure -> assertThat(((SQLException) failure).getSQLState()).isEqualTo("23514")); + } +} diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java index dbd021c3aa..a462cd4ee9 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java @@ -323,6 +323,244 @@ void entityInventoryUsesClosedTypedOperationAndRejectsOwnerContentSubstitution() assertThat(snapshot.canonicalJson()).contains("ITEM_TEMPLATE_ROOTS"); } + @Test + void sharedAndGdPayloadsMatchIndependentExistingEncodings() throws Exception { + var gd = new TemplateConfigSource.Config(config()); + var shared = + new net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.Config(config()); + String expectedConfig = independentCanonical(CommandSource.tree(config())); + assertThat(gd.canonicalJson()).isEqualTo(expectedConfig); + assertThat(shared.canonicalJson()).isEqualTo(expectedConfig); + for (String operation : List.of("CREATE", "UPSERT", "DELETE")) { + Map expected = new java.util.LinkedHashMap<>(); + expected.put("schemaVersion", 1); + expected.put("revisionKind", "TEMPLATE_CONFIG"); + expected.put("operation", operation); + expected.put( + operation.equals("CREATE") ? "templateName" : "templateId", + operation.equals("CREATE") ? "Starter" : "7"); + if (!operation.equals("DELETE")) expected.put("configJson", expectedConfig); + String expectedPayload = independentCanonical(expected); + String gdPayload = + switch (operation) { + case "CREATE" -> TemplateConfigSource.createPayload("Starter", gd); + case "UPSERT" -> TemplateConfigSource.upsertPayload("7", gd); + default -> TemplateConfigSource.deletePayload("7"); + }; + String sharedPayload = + switch (operation) { + case "CREATE" -> + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.createPayload( + "Starter", shared); + case "UPSERT" -> + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.upsertPayload( + "7", shared); + default -> + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.deletePayload( + "7"); + }; + assertThat(gdPayload).isEqualTo(expectedPayload); + assertThat(sharedPayload).isEqualTo(expectedPayload); + } + var automation = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + var entity = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + for (var owner : + List.of( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + DraftCommitBinding.Owner.ENTITY_MANAGEMENT)) { + boolean isAutomation = owner == DraftCommitBinding.Owner.AUTOMATION_SCRIPTING; + String json = isAutomation ? automation.canonicalJson() : entity.canonicalJson(); + String expected = + independentCanonical( + Map.of( + "schemaVersion", + isAutomation ? 2 : 3, + "revisionKind", + "TEMPLATE_CONFIG", + "operation", + "DECLARE_OWNER_SOURCE_INVENTORY", + "owner", + owner.name(), + "inventory", + CommandSource.tree(json))); + String gdPayload = + isAutomation + ? TemplateConfigSource.ownerInventoryPayload(owner, automation) + : TemplateConfigSource.ownerInventoryPayload(owner, entity); + String sharedPayload = + isAutomation + ? net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues + .ownerInventoryPayload(owner, automation) + : net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues + .ownerInventoryPayload(owner, entity); + assertThat(gdPayload).isEqualTo(expected); + assertThat(sharedPayload).isEqualTo(expected); + } + } + + @Test + void adaptersPreserveIndependentV1V2BytesDigestsAndOriginalInheritedProvenance() + throws Exception { + var config = new TemplateConfigSource.Config(config()); + var automation = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + var entity = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + var original = + binding( + TemplateConfigSource.createPayload("Starter", config), + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, automation), + TemplateConfigSource.ownerInventoryPayload( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, entity)); + var entries = + TemplateConfigSource.replay( + List.of(), original, Map.of(original.revisions().getFirst().revisionId(), "7")); + var declarations = TemplateConfigSource.replayOwnerInventoryDeclarations(List.of(), original); + var selected = binding(CommandSource.deletePayload("unrelated")); + for (boolean v2 : List.of(false, true)) { + var retainedDeclarations = + v2 ? declarations : List.of(); + var snapshot = + new TemplateConfigSourceSnapshot( + selected, "1", original.commitId(), UUID.randomUUID(), entries, retainedDeclarations); + var entry = entries.getFirst(); + Map entryObject = + Map.of( + "templateId", + "7", + "configJson", + config.canonicalJson(), + "sourceBindingJson", + original.canonicalJson(), + "sourceBindingDigest", + original.digest(), + "revisionOrder", + entry.revisionOrder(), + "revisionId", + entry.revisionId().toString(), + "createdName", + "Starter"); + var declarationObjects = new ArrayList>(); + for (var declaration : retainedDeclarations) { + var object = + Map.of( + "owner", + declaration.owner().name(), + "inventoryJson", + declaration.inventoryJson(), + "sourceBindingJson", + original.canonicalJson(), + "sourceBindingDigest", + original.digest(), + "revisionOrder", + declaration.revisionOrder(), + "revisionId", + declaration.revisionId().toString()); + declarationObjects.add(object); + assertThat(declaration.object()).isEqualTo(object); + assertThat(declaration.shared().object()).isEqualTo(object); + } + var expected = new java.util.LinkedHashMap(); + expected.put( + "schema", + v2 + ? "game-design-template-config-source-snapshot/v2" + : "game-design-template-config-source-snapshot/v1"); + expected.put("bindingJson", selected.canonicalJson()); + expected.put("bindingDigest", selected.digest()); + expected.put("sourceEpoch", "1"); + expected.put("inheritedCommitId", original.commitId().toString()); + expected.put("genesisReceiptId", snapshot.genesisReceiptId().toString()); + expected.put("entries", List.of(entryObject)); + if (v2) expected.put("ownerSourceInventoryDeclarations", declarationObjects); + String json = independentCanonical(expected); + byte[] bytes = json.getBytes(java.nio.charset.StandardCharsets.UTF_8); + String digest = independentDigest(bytes); + var common = + net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot.fromStored(json); + assertThat(entry.object()).isEqualTo(entryObject); + assertThat(snapshot.canonicalJson()).isEqualTo(json); + assertThat(snapshot.canonicalBytes()).isEqualTo(bytes); + assertThat(snapshot.digest()).isEqualTo(digest); + assertThat(common.canonicalBytes()).isEqualTo(bytes); + assertThat(common.digest()).isEqualTo(digest); + assertThat(TemplateConfigSourceSnapshot.fromStored(json)).isEqualTo(snapshot); + assertThat(TemplateConfigSourceSnapshot.fromShared(common)).isEqualTo(snapshot); + assertThat(common.binding()).isEqualTo(selected); + assertThat(common.entries().getFirst().sourceBinding()).isEqualTo(original); + if (v2) + assertThat(common.ownerSourceInventoryDeclarations()) + .extracting( + net.firedevops.firemud.common.gamedesign + .TemplateConfigOwnerSourceInventoryDeclaration + ::sourceBinding) + .containsExactly(original, original); + } + } + + @Test + void applicationAndCaptureFramesRemainExactIndependentLengthPrefixedBytes() throws Exception { + var authored = + binding( + TemplateConfigSource.createPayload( + "Starter", new TemplateConfigSource.Config(config()))); + var entries = + TemplateConfigSource.replay( + List.of(), authored, Map.of(authored.revisions().getFirst().revisionId(), "7")); + var snapshot = + new TemplateConfigSourceSnapshot(authored, "1", null, UUID.randomUUID(), entries); + byte[] applicationBytes = + independentFrames( + "game-design-template-config-source-application/v1" + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + "0".getBytes(java.nio.charset.StandardCharsets.UTF_8), + snapshot.shared().canonicalBytes()); + assertThat( + new TemplateConfigSourceSnapshot.Application(authored, "0", snapshot).canonicalBytes()) + .isEqualTo(applicationBytes); + + // Stipulated upstream fixture tests encoding only, not owner participation or publication + // proof. + var operation = IsolatedPublicationOperationFixtures.fresh(authored.target()); + var selected = operation.account().input().selection().selectedCommit(); + var inherited = + new TemplateConfigSourceSnapshot( + selected, "1", authored.commitId(), snapshot.genesisReceiptId(), entries); + var capture = new TemplateConfigSourceSnapshot.Capture(operation, inherited); + byte[] captureBytes = + independentFrames( + "game-design-template-config-source-capture/v1" + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + operation.canonicalBytes(), + inherited.shared().canonicalBytes()); + assertThat(capture.canonicalBytes()).isEqualTo(captureBytes); + assertThat(capture.digest()).isEqualTo(independentDigest(captureBytes)); + assertThat(inherited.entries().getFirst().sourceBinding()).isEqualTo(authored); + assertThat(inherited.binding()).isEqualTo(selected); + } + + private static String independentCanonical(Object value) throws Exception { + return new String( + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + new tools.jackson.databind.ObjectMapper().writeValueAsString(value)), + java.nio.charset.StandardCharsets.UTF_8); + } + + private static String independentDigest(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static byte[] independentFrames(byte[]... fields) throws Exception { + var bytes = new java.io.ByteArrayOutputStream(); + var output = new java.io.DataOutputStream(bytes); + for (byte[] field : fields) { + output.writeInt(field.length); + output.write(field); + } + return bytes.toByteArray(); + } + private static String config() { return "{\"schemaVersion\":1,\"baseVersionId\":\"" + VERSION From 3976704464d193e56aa27111724ffdc192c6cef6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 07:40:32 +1300 Subject: [PATCH 061/129] Preserve original publication profiles in genuine and historical proof fixtures --- ...ame-authoring-publishing-and-activation.md | 4 + ...ldSourceCommitPostgresIntegrationTest.java | 49 +++++ ...licationExportPostgresIntegrationTest.java | 13 ++ ...nceAssociationPostgresIntegrationTest.java | 61 +++++- ...aphApplicationPostgresIntegrationTest.java | 189 ++++++++++++------ ...gionAssignmentPostgresIntegrationTest.java | 46 +++-- 6 files changed, 283 insertions(+), 79 deletions(-) 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 08f03579fc..9ce893f5dd 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The scoped correction preserves each synthetic fixture's original digest/attestation profile, removes unsupported generation-rule inputs from unrelated positive inventory cases while adding an explicit requiredness-denial case, and keeps V41/V42 historical capture at its actual schema boundary. Operational-region proof now follows V62's wrapper to the retained implementation and checks both PUBLIC execution boundaries. The genuine GD+World fixture authors all seven inbound-closure counts before Account authorization and asserts exact original binding readback. The selected-export fixture invokes the real control-plane digest before finalization solely to expose the missing exception cause on the next physical execution; that root is not yet fixed. The composed local gate passed in 1m 12s: 532 Game Design unit cases executed successfully, Common's 472 and World's 589 passing unit outputs were reused, and all 366 PostgreSQL cases skipped without Docker (148 Game Design, 218 World). Formatting, static checks, coverage, boot JARs, links and Markdown passed. Corrected PostgreSQL behavior and authenticated handoffs remain unproved. + +Published `4505ec9940d9bb66f6ef36799c24a94bebfa709d` [Validation run 37970520470](https://github.com/benhook1013/FireMUD/actions/runs/37970520470) completed red. Account physically executed 254 PostgreSQL cases successfully; World executed 217 with 74 failures and Game Design executed 150 with four failures. All three suites have zero errors and skips; the byte-identical Account authorization-fence subset is counted once. World failures cluster in synthetic selector/checkpoint and participant-digest-profile fixtures, unsupported generation-rule inputs, historical-table assumptions and three assertions. Game Design's genuine source fixture omitted the explicitly authored inbound closure and therefore failed original World apply, including its lost-acknowledgement case. The genuine selected export separately failed computation of the design control-plane digest; its underlying cause was not retained in the originating failure and nearby connection-refused logs do not establish that cause. Corrections and focused diagnostic proof are in progress, not physically verified. CI ran synthetic checkout `ce79309368c5563361b6888746d9939a97e0dffe`, tree `c15a5256fbad57b77c4a2c507d6dbb33620c40d1`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source; this does not prove alignment with the recorded integration parent. All four Gameplay handoffs and activation remain open. + The canonical closed template-config source decoder now lives in Common, with field-preserving Game Design adapters. Config, mutation, declaration and v1/v2 snapshot bytes, digests, application/capture frames and inherited original revision provenance are preserved; reference predicates inspect content and do not qualify an owner source. The composed local gate passed with 472 Common, 532 Game Design and 589 World unit cases executed, no failures, errors or skips. All 365 PostgreSQL definitions compiled/discovered but skipped without Docker (148 Game Design, 217 World). Formatting, Checkstyle, SpotBugs, coverage, both service boot JARs, links and Markdown passed. A new isolated V69-to-V70 upgrade definition stores a historical inventory-v1/graph-2/digest-3 operation through the actual V56 validator, then checks byte-exact readback/retry and the closed v2 profile negatives after upgrade; it has not executed against PostgreSQL. Its upstream Account/World evidence is explicitly synthetic. Shared decoding and this test definition are not genuine Entity/Automation receipts, authenticated through-commit authority or activation proof. The corrected World construction adds V62 durable original-operation, one-shot claim, independent execution fence, atomic V35 materialization/V34 association/`COMMITTED`, and same-lock `ABORTED` settlement. Its identity binds the full original StartSession tuple, distinct Account World participation ID/fence, actual Game Session attempt/fence, target and exact immutable preparation input; observational read metadata does not become a new operation. Local consolidated checks passed after repairing typed jOOQ reads and fixture accessors: World's 589 unit cases executed successfully, while Common's 464 and Game Design's 529 passing unit results were reused by Gradle. All 364 PostgreSQL definitions compiled but skipped without Docker (217 World, 147 Game Design). World V62 and Game Design V70 schema generation, formatting, Checkstyle, SpotBugs, coverage, boot JARs, links, Markdown and Flyway sanity (12 sets, 276 files) passed. This does not prove corrected PostgreSQL migrations, concurrency, cancellation or authenticated recovery. The expiry case covers repository-only exact terminal readback, not an authenticated service recovery path; genuine Account World participation, held-source producer, terminal transport and composed launch remain unavailable. Fresh Entity/Automation source qualification must cover the complete owner families and exact World closure; their authored empty declarations are not receipts or proof of absent source rows. diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java index e047276f7f..bd9a662702 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java @@ -90,6 +90,9 @@ import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphDeclaration; import net.firedevops.firemud.worldmanagement.v1.WorldFreshGraphFamilyCount; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceClosureDeclaration; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -356,6 +359,21 @@ private void compose(Failure failure) throws Exception { assertThat(identity.versionStateEvidence()) .isEqualTo(publicAssociation.versionStateEvidence()); var binding = binding(gd.target()); + var originalDeclaration = + binding.revisions().stream() + .filter(revision -> revision.owner() == DraftCommitBinding.Owner.WORLD_MANAGEMENT) + .map(GenuineGameDesignWorldSourceCommitPostgresIntegrationTest::worldMutation) + .filter(WorldDesignMutationRevision::hasFreshGraphDeclaration) + .map(WorldDesignMutationRevision::getFreshGraphDeclaration) + .toList(); + assertThat(originalDeclaration) + .singleElement() + .satisfies( + declaration -> { + assertThat(declaration.hasInboundSourceClosure()).isTrue(); + assertThat(declaration.getInboundSourceClosure()) + .isEqualTo(authoredEmptyInboundSourceClosure()); + }); var request = account.prepareOriginalDraftOrder(binding, NAMESPACE); var original = request.original(); register( @@ -447,6 +465,8 @@ private void compose(Failure failure) throws Exception { assertThat(actualWorld.startLocationReceipt()).isPresent(); assertThat(actualWorld.application().operation().accountBindingBytes()) .isEqualTo(original.canonicalBytes()); + assertThat(actualWorld.application().operation().binding().canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); assertThat( coordinator .read(gd.target(), binding.requestId()) @@ -643,6 +663,7 @@ private static DraftCommitBinding binding(DraftCommitBinding.TargetProof target) .setTenantId(target.canonicalTenantId().toString()) .setVersionId(target.canonicalVersionId().toString()) .addAllFamilyCounts(familyCounts) + .setInboundSourceClosure(authoredEmptyInboundSourceClosure()) .setStartLocation( net.firedevops.firemud.worldmanagement.v1.RoomTemplateRef.newBuilder() .setTenantId(target.canonicalTenantId().toString()) @@ -736,6 +757,34 @@ private static WorldDesignMutationRevision.Builder mutation( .setScopeId(region.toString()); } + private static WorldInboundSourceClosureDeclaration authoredEmptyInboundSourceClosure() { + var declaration = WorldInboundSourceClosureDeclaration.newBuilder().setSchemaVersion(1); + for (var family : + List.of( + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE, + WorldInboundSourceFamily.WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING)) { + declaration.addFamilyCounts( + WorldInboundSourceFamilyCount.newBuilder().setFamily(family).setCount(0)); + } + return declaration.build(); + } + + private static WorldDesignMutationRevision worldMutation( + DraftCommitBinding.RevisionPayload revision) { + try { + var mutation = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(revision.payload(), mutation); + return mutation.build(); + } catch (com.google.protobuf.InvalidProtocolBufferException invalid) { + throw new AssertionError("Original World revision must be typed", invalid); + } + } + private enum Failure { NONE, LOST_ACKNOWLEDGEMENT, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 48ba4dc0be..2d5d79f22c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -1178,6 +1178,19 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new GameAssetRepository(gd.dsl()), new RevisionRepository(gd.dsl()), new ObjectMapper()); + // Exercise the actual finalizer dependency before it records a message-only failure. + // Keep its original exception chain visible if an authored input cannot be digested. + var finalizerDesignDigest = + gd.transaction( + () -> + controlPlaneDigests.getDigestForVersion( + mapper.toDto( + new VersionRepository(gd.dsl()) + .findByTenantIdAndId( + gd.target().gameDesignVersionTenantKey(), + gd.target().gameDesignVersionRowId()) + .orElseThrow()))); + assertThat(finalizerDesignDigest.contentDigest()).matches("[0-9a-f]{64}"); var realAttemptPersistence = new PublishAttemptServiceImpl( publishAttemptRepository, new PublishAttemptParticipantDigestRepository(gd.dsl())); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index cb6e63dea1..d1b384186a 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -2952,6 +2952,16 @@ private static AuthoredWorldReleaseAttestationEvidence attestation( String commit, WorldPublishedStartLocationEvidence selector, char manifestHashDigit) { + int attestationSchemaVersion = + selector == null + ? AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION + : switch (selector.request().digestSchemaVersion()) { + case 3 -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case 4 -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + default -> + throw new IllegalArgumentException( + "World selector has no paired release-attestation profile"); + }; AuthoredWorldReleaseAttestationEvidence.Participant worldParticipant = selector == null ? participant("WORLD_MANAGEMENT", 3, "a", false, descriptor.versionId(), commit) @@ -2973,7 +2983,8 @@ private static AuthoredWorldReleaseAttestationEvidence attestation( participant("AUTOMATION_SCRIPTING", 5, "d", false, descriptor.versionId(), commit), participant( "GAME_DESIGN_CONTROL_PLANE", - selector == null ? 1 : 2, + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + "GAME_DESIGN_CONTROL_PLANE", attestationSchemaVersion), "e", false, descriptor.versionId(), @@ -3000,6 +3011,30 @@ private static AuthoredWorldReleaseAttestationEvidence attestation( List.of("look"), descriptor.generationConfigRevision()); } + if (attestationSchemaVersion + == AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION) { + return AuthoredWorldReleaseAttestationEvidence.createClosureSelector( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersionId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + digest(manifestHashDigit), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision(), + selector); + } return AuthoredWorldReleaseAttestationEvidence.create( NAMESPACE, descriptor.resultDigest(), @@ -3066,6 +3101,30 @@ private static AuthoredWorldReleaseAttestationEvidence releaseWithWorldCheckpoin release.commandDefinitions(), release.generationConfigRevision()); } + if (release.schemaVersion() + == AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION) { + return AuthoredWorldReleaseAttestationEvidence.createClosureSelector( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + checkpoint.publishWorkflowId(), + checkpoint.appliedCommitId(), + participants, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision(), + release.worldStartLocationEvidence()); + } return AuthoredWorldReleaseAttestationEvidence.create( release.targetNamespace(), release.descriptorResultDigest(), diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 7c4c1dc318..4fc51e1039 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -3460,7 +3460,7 @@ void releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeW selector.originalAccountBindingBytes(), selector.appliedResultBytes()); assertThatThrownBy(() -> preparationInput(f, frozen, changed)) - .hasMessageContaining("exact frozen request"); + .hasMessageContaining("World selector differs from the exact attested release checkpoint"); var input = preparationInput(f, frozen, selector); var encoded = (tools.jackson.databind.node.ObjectNode) @@ -3542,7 +3542,7 @@ void inertV1PreparationRetainsOriginalBytesAndCannotGainSelectorOnRetry() throws Fixture f = historical.fixture(); var application = historical.application(historical.generationFreePlan(f)); historical.appliedComponent().apply(application); - var frozen = historical.capture(application.plan()); + var frozen = historical.captureHistoricalUnqualified(application.plan()); var input = historical.preparationInput(f, frozen, null); var first = historical.prepareV1ThroughOwnerFunction(input); assertThat(first.startLocation()).isNull(); @@ -3658,6 +3658,15 @@ public void close() {} } private WorldDraftTopologyCommitPlan generationFreePlan(Fixture f) { + return inventorySupportedPlan(f, false); + } + + private WorldDraftTopologyCommitPlan supportedInventoryPlan(Fixture f) { + return inventorySupportedPlan(f, true); + } + + private WorldDraftTopologyCommitPlan inventorySupportedPlan( + Fixture f, boolean preserveSpawnBindings) { var original = plan(f); var binding = original.binding(); List revisions = new ArrayList<>(); @@ -3674,7 +3683,8 @@ private WorldDraftTopologyCommitPlan generationFreePlan(Fixture f) { try { var value = WorldDesignMutationRevision.newBuilder(); JsonFormat.parser().merge(revision.payload(), value); - if (value.hasGenerationRule() || value.hasWorldEntitySpawnBinding()) continue; + if (value.hasGenerationRule() + || (!preserveSpawnBindings && value.hasWorldEntitySpawnBinding())) continue; if (value.hasRegion()) value.setRegion( value.getRegion().toBuilder() @@ -3686,9 +3696,10 @@ private WorldDraftTopologyCommitPlan generationFreePlan(Fixture f) { for (int index = 0; index < declaration.getFamilyCountsCount(); index++) { var family = declaration.getFamilyCounts(index).getFamily(); if (family == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE - || family - == WorldDesignAggregateType - .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING) { + || (!preserveSpawnBindings + && family + == WorldDesignAggregateType + .WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING)) { declaration.setFamilyCounts( index, declaration.getFamilyCounts(index).toBuilder().setCount(0)); } @@ -3716,7 +3727,8 @@ private WorldDraftTopologyCommitPlan generationFreePlan(Fixture f) { .filter( unit -> !unit.aggregateType().equals("GENERATION_RULE") - && !unit.aggregateType().equals("WORLD_ENTITY_SPAWN_BINDING")) + && (preserveSpawnBindings + || !unit.aggregateType().equals("WORLD_ENTITY_SPAWN_BINDING"))) .toList()), original.ownerBinding()); } @@ -3728,7 +3740,7 @@ void v41MaterializedV1HistoryRemainsByteExactAndRetryableAfterV42WithoutSelector Fixture f = historical.fixture(); var application = historical.application(historical.generationFreePlan(f)); var applied = historical.appliedComponent().apply(application); - var frozen = historical.capture(application.plan()); + var frozen = historical.captureHistoricalUnqualified(application.plan()); var input = historical.preparationInput(f, frozen, null); var first = historical.prepareV1ThroughOwnerFunction(input); Map before = historical.preparationHistoryRows(); @@ -4087,6 +4099,16 @@ private PreparationLaunchFixture preparationLaunchFixture( false, null); var freeze = frozen.request().freeze(); + int attestationSchemaVersion = + selector == null + ? AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION + : switch (selector.request().digestSchemaVersion()) { + case 3 -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case 4 -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + default -> + throw new IllegalArgumentException( + "World selector has no paired release-attestation profile"); + }; var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() .map( @@ -4099,56 +4121,81 @@ private PreparationLaunchFixture preparationLaunchFixture( freeze.appliedCommitId(), "WORLD_MANAGEMENT".equals(owner) ? freeze.contentDigest() : "a".repeat(64), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, - selector == null - ? AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION - : AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner, attestationSchemaVersion), "GAME_LOGIC".equals(owner), "GAME_LOGIC".equals(owner) ? "sha256:" + "b".repeat(64) : null)) .toList(); - AuthoredWorldReleaseAttestationEvidence release = - selector == null - ? AuthoredWorldReleaseAttestationEvidence.create( - NAMESPACE, - descriptor.resultDigest(), - source.canonicalTenantId(), - f.version().canonicalVersionId(), - source.worldSlug(), - source.operationId(), - source.evidenceDigest(), - descriptor.launchDescriptorId(), - descriptor.publishedReleaseBundleRef(), - descriptor.versionStateEpoch(), - freeze.publishWorkflowId(), - freeze.appliedCommitId(), - participants, - "sha256:" + "c".repeat(64), - 1, - List.of(), - List.of(), - commandDefinitions, - descriptor.generationConfigRevision()) - : AuthoredWorldReleaseAttestationEvidence.create( - NAMESPACE, - descriptor.resultDigest(), - source.canonicalTenantId(), - f.version().canonicalVersionId(), - source.worldSlug(), - source.operationId(), - source.evidenceDigest(), - descriptor.launchDescriptorId(), - descriptor.publishedReleaseBundleRef(), - descriptor.versionStateEpoch(), - freeze.publishWorkflowId(), - freeze.appliedCommitId(), - participants, - "sha256:" + "c".repeat(64), - 1, - List.of(), - List.of(), - commandDefinitions, - descriptor.generationConfigRevision(), - selector); + AuthoredWorldReleaseAttestationEvidence release; + if (selector == null) { + release = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + f.version().canonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + participants, + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + commandDefinitions, + descriptor.generationConfigRevision()); + } else if (attestationSchemaVersion + == AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION) { + release = + AuthoredWorldReleaseAttestationEvidence.createClosureSelector( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + f.version().canonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + participants, + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + commandDefinitions, + descriptor.generationConfigRevision(), + selector); + } else { + release = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + f.version().canonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + freeze.publishWorkflowId(), + freeze.appliedCommitId(), + participants, + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + commandDefinitions, + descriptor.generationConfigRevision(), + selector); + } var evidence = new CompleteLaunchBindingEvidence(descriptor, release); UUID instance = UUID.randomUUID(); UUID read = UUID.randomUUID(); @@ -5518,7 +5565,7 @@ void publicationOwnerReadsIntakeOnlyInsideWritableReadCommittedTransaction() { @Test void publishedSelectorJoinsExactFrozenCheckpointToOriginalAppliedWithoutWrites() { Fixture f = fixture(); - var application = application(f); + var application = application(generationFreePlan(f)); var applied = appliedComponent().apply(application); var capture = capture(application.plan()); var request = capture.request().freeze(); @@ -5593,7 +5640,7 @@ dsl, frozenRepository(), substitutedApplications) @Test void publishedSelectorOwnedReadUsesOneActualReadOnlyRepeatableReadSnapshot() { Fixture f = fixture(); - var application = application(f); + var application = application(generationFreePlan(f)); var applied = appliedComponent().apply(application); var capture = capture(application.plan()); var request = capture.request().freeze(); @@ -5664,7 +5711,7 @@ void publishedSelectorOwnedReadUsesOneActualReadOnlyRepeatableReadSnapshot() { @Test void publishedSpawnRequirementsOwnerProjectsOnlyRealFrozenAndAppliedSource() { Fixture f = fixture(); - var application = application(f); + var application = application(supportedInventoryPlan(f)); appliedComponent().apply(application); var capture = capture(application.plan()); var frozen = capture.request().freeze(); @@ -5724,14 +5771,25 @@ void publishedSpawnRequirementsOwnerProjectsOnlyRealFrozenAndAppliedSource() { assertThat(evidence.spawnRequirements().getFirst().respawnDelaySeconds()).isEqualTo(17); assertThat(evidence.spawnRequirements().getFirst().entityTemplate().kind()) .isEqualTo(EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC); - assertThat(evidence.generationRequirements()).hasSize(1); - assertThat(evidence.generationRequirements().getFirst().name()).isEqualTo("rule"); - assertThat(evidence.generationRequirements().getFirst().value()).isEqualTo("seeded"); + assertThat(evidence.generationRequirements()).isEmpty(); assertThat(preparationHistoryRows()).isEqualTo(before); Mockito.verify(gameDesign).getComplete(launchRequest); assertOrigin(); } + @Test + void selectedInventoryRejectsGenerationRulesWithoutRequirednessRegistry() { + Fixture f = fixture(); + var application = application(plan(f, true, true)); + appliedComponent().apply(application); + + assertThatThrownBy(() -> capture(application.plan())) + .isInstanceOf( + WorldSelectedPublicationArtifactInventory.UnrepresentableRequirednessException.class) + .hasMessageContaining( + "GENERATION_RULE name/scope/value inputs without a closed requiredness registry"); + } + @Test void publishedSpawnRequirementsOwnerPreservesExplicitZeroOptionalFamilies() { Fixture f = fixture(); @@ -5805,7 +5863,7 @@ void publishedSpawnRequirementsOwnerPreservesExplicitZeroOptionalFamilies() { @Test void retainedFrozenHistoryCannotSupplyPublishedSelectorAfterAppliedSourceIsMissing() { - var plan = plan(fixture()); + var plan = generationFreePlan(fixture()); var application = application(plan); appliedComponent().apply(application); var capture = capture(application.plan()); @@ -5909,6 +5967,13 @@ private WorldCanonicalFrozenTopology capture(WorldDraftTopologyCommitPlan plan) return capture(plan, publicationRequest, selection, accountBinding); } + private WorldCanonicalFrozenTopology captureHistoricalUnqualified( + WorldDraftTopologyCommitPlan plan) { + String publicationRequest = "historical-selector-" + UUID.randomUUID(); + var selection = publicationSelection(plan, publicationRequest, 1L); + return capture(plan, publicationRequest, selection, null); + } + private WorldCanonicalFrozenTopology captureForTerminal( WorldDraftTopologyCommitPlan plan, byte[] originalDraftAccountBinding) { String publicationRequest = "selector-" + UUID.randomUUID(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java index 2f4e025238..dfe2ca69e2 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java @@ -149,13 +149,14 @@ void nullAssignmentIsNotRepairedAndV45KeepsPreparationFunctionClosed() { + "WHERE version IN ('44', '45') AND success")) .get(0, Long.class)) .isEqualTo(2); - String prepareDefinition = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT pg_get_functiondef('world_management_service." - + "world_prepare_canonical_instance(text,text)'::regprocedure)")) - .get(0, String.class); - assertThat(prepareDefinition).contains("'operational_region_id', operational_runtime_uuid"); + String prepareDefinition = preparationFunction(dsl, "world_management_service").body(); + assertThat(prepareDefinition).contains("world_prepare_canonical_instance_v61_impl"); + String prepareImplementationDefinition = + preparationFunction( + dsl, "world_management_service", "world_prepare_canonical_instance_v61_impl") + .body(); + assertThat(prepareImplementationDefinition) + .contains("'operational_region_id', operational_runtime_uuid"); assertThat( Objects.requireNonNull( dsl.fetchOne( @@ -163,7 +164,8 @@ void nullAssignmentIsNotRepairedAndV45KeepsPreparationFunctionClosed() { + "JOIN pg_namespace n ON n.oid = p.pronamespace " + "CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) acl " + "WHERE n.nspname = 'world_management_service' " - + "AND p.proname = 'world_prepare_canonical_instance' " + + "AND p.proname IN ('world_prepare_canonical_instance'," + + "'world_prepare_canonical_instance_v61_impl') " + "AND acl.grantee = 0 AND acl.privilege_type = 'EXECUTE')")) .get(0, Boolean.class)) .isFalse(); @@ -260,23 +262,29 @@ void v44ToV45RetainsLegacyRegionAndPreparationOwnerFunctionIdentity() throws Exc .load() .migrate(); - var functionAfter = preparationFunction(retained, schema); - assertThat(functionAfter.oid()).isEqualTo(functionBefore.oid()); - assertThat(functionAfter.acl()).isEqualTo(functionBefore.acl()); - assertThat(functionAfter.body()) + var wrapperAfter = preparationFunction(retained, schema); + var implementationAfter = + preparationFunction(retained, schema, "world_prepare_canonical_instance_v61_impl"); + assertThat(implementationAfter.oid()).isEqualTo(functionBefore.oid()); + assertThat(implementationAfter.acl()).isEqualTo(functionBefore.acl()); + assertThat(wrapperAfter.body()).contains("world_prepare_canonical_instance_v61_impl"); + assertThat(implementationAfter.body()) .contains( "Canonical preparation release differs from the exact selected frozen World graph", "world_require_preparation_start_location", "Canonical preparation requires the exact published V44 terminal", "'operational_region_id', operational_runtime_uuid"); - assertThat(functionAfter.body()).isNotEqualTo(functionBefore.body()); + assertThat(implementationAfter.body()).isNotEqualTo(functionBefore.body()); assertThat( Objects.requireNonNull( retained.fetchOne( "SELECT EXISTS (SELECT 1 FROM pg_proc p " + "CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) acl " - + "WHERE p.oid = to_regprocedure(? || '.world_prepare_canonical_instance(text,text)') " + + "WHERE p.oid IN (" + + "to_regprocedure(? || '.world_prepare_canonical_instance(text,text)')," + + "to_regprocedure(? || '.world_prepare_canonical_instance_v61_impl(text,text)')) " + "AND acl.grantee = 0 AND acl.privilege_type = 'EXECUTE')", + schema, schema)) .get(0, Boolean.class)) .isFalse(); @@ -319,13 +327,19 @@ void v44ToV45RetainsLegacyRegionAndPreparationOwnerFunctionIdentity() throws Exc } private PreparationFunction preparationFunction(DSLContext dsl, String schema) { + return preparationFunction(dsl, schema, "world_prepare_canonical_instance"); + } + + private PreparationFunction preparationFunction( + DSLContext dsl, String schema, String functionName) { var function = Objects.requireNonNull( dsl.fetchOne( "SELECT p.oid::bigint AS function_oid, p.proacl::text AS function_acl, " + "pg_get_functiondef(p.oid) AS function_body FROM pg_proc p " - + "WHERE p.oid = to_regprocedure(? || '.world_prepare_canonical_instance(text,text)')", - schema)); + + "WHERE p.oid = to_regprocedure(? || '.' || ? || '(text,text)')", + schema, + functionName)); return new PreparationFunction( function.get("function_oid", Long.class), function.get("function_acl", String.class), From f5530b39c27d60299d4f00306b1b0c4ee9a4027e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 08:38:26 +1300 Subject: [PATCH 062/129] Fix genuine source projections and retain exact owner proof boundaries --- .../firemud/FiremudJooqConventionsPlugin.kt | 18 +- .../account-service/api-contracts.md | 4 + ...ame-authoring-publishing-and-activation.md | 4 +- dev-tools/README.md | 2 + .../tests/account-jooq-projection-contract.sh | 177 ++++++++ .../AccountControlUiAuthority.java | 23 + .../AccountControlUiAuthorityTest.java | 65 ++- .../SelectedOwnerIntakeSourceReadScope.java | 125 ++++++ ...electedOwnerIntakeSourceReadScopeTest.java | 405 ++++++++++++++++++ .../repository/GameAssetRepository.java | 2 +- ...nventoryProfileUpgradeIntegrationTest.java | 7 +- .../repository/GameAssetRepositoryTest.java | 49 +++ ...dSelectedPublicationArtifactInventory.java | 62 ++- ...aphApplicationPostgresIntegrationTest.java | 165 ++++++- ...ectedPublicationArtifactInventoryTest.java | 128 ++++++ 15 files changed, 1181 insertions(+), 55 deletions(-) create mode 100644 dev-tools/tests/account-jooq-projection-contract.sh create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScope.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java diff --git a/buildSrc/src/main/kotlin/net/firedevops/firemud/FiremudJooqConventionsPlugin.kt b/buildSrc/src/main/kotlin/net/firedevops/firemud/FiremudJooqConventionsPlugin.kt index 55abeb20ba..ec275bcd9c 100644 --- a/buildSrc/src/main/kotlin/net/firedevops/firemud/FiremudJooqConventionsPlugin.kt +++ b/buildSrc/src/main/kotlin/net/firedevops/firemud/FiremudJooqConventionsPlugin.kt @@ -123,6 +123,15 @@ abstract class PrepareAccountJooqMigrationProjectionTask : DefaultTask() { if (!sourceRoot.isDirectory) { throw GradleException("Account Flyway migration source directory is unavailable") } + val migrations = sourceRoot.walkTopDown().filter { it.isFile }.toList() + val inventoryMigrations = migrations.filter { INVENTORY_MIGRATION_PATTERN.matches(it.name) } + if (inventoryMigrations.size != 1) { + throw GradleException( + "Expected exactly one correctly versioned Account validator-inventory migration" + ) + } + val inventoryMigration = inventoryMigrations.single() + if (outputRoot.exists() && !outputRoot.deleteRecursively()) { throw GradleException("Account jOOQ migration projection could not be refreshed") } @@ -130,16 +139,12 @@ abstract class PrepareAccountJooqMigrationProjectionTask : DefaultTask() { throw GradleException("Account jOOQ migration projection directory is unavailable") } - val migrations = sourceRoot.walkTopDown().filter { it.isFile }.toList() - if (migrations.none { it.name == INVENTORY_MIGRATION }) { - throw GradleException("Expected Account validator-inventory migration is missing") - } migrations.forEach { source -> val destination = outputRoot.resolve(source.relativeTo(sourceRoot).path) if (!destination.parentFile.mkdirs() && !destination.parentFile.isDirectory) { throw GradleException("Account jOOQ migration projection path is unavailable") } - if (source.name == INVENTORY_MIGRATION) { + if (source == inventoryMigration) { destination.writeBytes(projectInventoryMigration(source.readBytes())) } else { // Every other migration remains a byte-for-byte copy of Flyway's authority. @@ -168,7 +173,8 @@ abstract class PrepareAccountJooqMigrationProjectionTask : DefaultTask() { private fun String.countOccurrences(value: String): Int = split(value).size - 1 private companion object { - const val INVENTORY_MIGRATION = "V52__account_jwt_validator_inventory_snapshots.sql" + val INVENTORY_MIGRATION_PATTERN = + Regex("""V[0-9]+(?:\.[0-9]+)*__account_jwt_validator_inventory_snapshots\.sql""") const val IGNORE_END = "-- [jooq ignore end]" const val IGNORE_STOP = "-- [jooq ignore stop]" const val INVENTORY_ALTER = diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index ecdf83314b..3c069e9582 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -104,6 +104,10 @@ Only the verified same-namespace Game Logic workload may call [`ReadHeldGameLogi The standalone [`SettleGameLogicIntake`](../../../../protos/account/v1/game_logic_intake_settlement_service.proto) transport is restricted to the verified same-namespace Game Design workload, authenticated before request decoding. Its closed request carries schema version, namespace, a separate transport correlation, and the complete original intake authorization bytes and digest; its response echoes that exact request and the immutable `account-game-logic-intake-settlement/v1` receipt bytes and digest. The receipt frames its schema and complete original Game Logic terminal, preserving retained and definitive-abort outcomes. A correlation change cannot change settlement identity. The client verifies Account's exact workload identity, requires file-backed mutual TLS, uses a bounded deadline and rejects ambient SQL. Unavailable or changed evidence fails closed. The receipt has its own bounded terminal envelope and is not embedded in the smaller publication operation or authored configuration. This transport supplies neither a fresh intake order nor public or runtime registration; implementation and proof remain in the linked tracker. +Entity and Automation's selected-source intake use the same two-phase ownership boundary, with distinct Account operations and proof domains, not Game Logic grants. The preliminary scope schema is `account-entity-intake-source-read/v1` with purpose `ENTITY_INTAKE_SOURCE`, or `account-automation-intake-source-read/v1` with purpose `AUTOMATION_INTAKE_SOURCE`. Its canonical preimage uses the existing byte-length framing in this fixed order: schema, closed owner (`ENTITY_MANAGEMENT` or `AUTOMATION_SCRIPTING`), namespace, original Account operation UUID, original fence UUID, stable intake request UUID, acting account UUID, complete canonical selected Draft binding bytes, that binding's digest, derived same-namespace Account workload reader, and the corresponding purpose. UUIDs are canonical and nonzero; unknown owners, substituted domains/readers, malformed or noncanonical frames, trailing bytes and scopes over 4 MiB deny. The SHA-256 digest covers the complete preimage. The reader and purpose derive from the owner and namespace, never caller-selected aliases. + +That scope is preliminary integrity input, not authenticated authorization, finalized owner retention permission or evidence that any source family is empty. Account must authenticate and retain the distinct reservation before Game Design returns source content; it must then obtain the complete immutable selected inputs and finalize the owner-specific authorization with revalidated held sources. Original revision provenance is retained separately from the selected capture and must not be rewritten to manufacture a World association. Entity's [complete authored inventory](../entity-management-service/runtime-and-data.md) and Automation's [source inventory and inbound closure](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) remain owner-validated obligations. Both owners retain their original terminal under continuously protected Account authority; only authenticated exact terminal settlement can release participation. A decoded scope or sampled `HELD` response proves none of those obligations. The reservation, held-retention producers and executed proof remain open in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); these domains do not register or enable a runtime path. + `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. 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 9ce893f5dd..d2242c3ffe 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 @@ -6,7 +6,9 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The scoped correction preserves each synthetic fixture's original digest/attestation profile, removes unsupported generation-rule inputs from unrelated positive inventory cases while adding an explicit requiredness-denial case, and keeps V41/V42 historical capture at its actual schema boundary. Operational-region proof now follows V62's wrapper to the retained implementation and checks both PUBLIC execution boundaries. The genuine GD+World fixture authors all seven inbound-closure counts before Account authorization and asserts exact original binding readback. The selected-export fixture invokes the real control-plane digest before finalization solely to expose the missing exception cause on the next physical execution; that root is not yet fixed. The composed local gate passed in 1m 12s: 532 Game Design unit cases executed successfully, Common's 472 and World's 589 passing unit outputs were reused, and all 366 PostgreSQL cases skipped without Docker (148 Game Design, 218 World). Formatting, static checks, coverage, boot JARs, links and Markdown passed. Corrected PostgreSQL behavior and authenticated handoffs remain unproved. +The distinct Entity/Automation preliminary source-read value now binds closed owner-specific schema and purpose, exact Account operation/fence/request/actor, unchanged complete selected Draft evidence and the derived same-namespace Account reader. Six focused integrity cases and all 478 Common unit cases pass locally; this value does not authenticate a reservation or finalize owner retention. The complete authenticated selected-input export, distinct Account reservation/finalization and source-writer/disclosure exclusion, actual owner census/retention and exact terminal settlement remain open. Gameplay's V74–V97 forward-stage source reservation is being compared before overlapping Account publication; later stages must preserve its baseline and dependency order without duplicate owner DDL or weaker guards. World service-level authenticated recovery after ingress expiry remains open even though repository-only terminal recovery is defined; authenticated original Account participation and Game Session attempt/fence evidence remain prerequisites, not optional verifier checks. + +Published `3976704464d193e56aa27111724ffdc192c6cef6` [Validation run 37974939607](https://github.com/benhook1013/FireMUD/actions/runs/37974939607) completed red: Account executed 254 PostgreSQL cases successfully, World executed 218 with 68 failures, and Game Design executed 151 with two failures; all have zero errors and skips. Genuine original GD+World application, authenticated terminal settlement and original lost-acknowledgement recovery passed, but do not complete the release or runtime handoffs. Most World failures occur before assertions because the shared release fixture declares an old profile for a new closure-qualified release; five remaining cases expose historical-profile fixtures, an incorrect typed spawn projection and stale assertions. Game Design's real selected-export diagnostic exposed a JDBC `Timestamp` mapped as `LocalDateTime` without conversion; its retained-profile upgrade setup omits a required owner outcome before reaching the upgrade. The local corrections preserve historical graph/digest bytes, use actual source-backed Game Design outcomes and validate canonical typed spawn identities before assigning their representation. Three asset repository and eleven inventory regression cases executed locally without skips or failures. Full composed checks and corrected PostgreSQL execution remain required. The actual CI checkout was synthetic merge `5257af32b810218f704ab2aad1d5f3a04881d4ab`, tree `5ad3fdcb295c1ffe014e6364d97113ea09e0493e`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published source, not the recorded integration parent. V62 execution/abort/concurrency cases failed in setup and are not proved by the separate passing Draft application cases. All four Gameplay handoffs and activation remain open. Published `4505ec9940d9bb66f6ef36799c24a94bebfa709d` [Validation run 37970520470](https://github.com/benhook1013/FireMUD/actions/runs/37970520470) completed red. Account physically executed 254 PostgreSQL cases successfully; World executed 217 with 74 failures and Game Design executed 150 with four failures. All three suites have zero errors and skips; the byte-identical Account authorization-fence subset is counted once. World failures cluster in synthetic selector/checkpoint and participant-digest-profile fixtures, unsupported generation-rule inputs, historical-table assumptions and three assertions. Game Design's genuine source fixture omitted the explicitly authored inbound closure and therefore failed original World apply, including its lost-acknowledgement case. The genuine selected export separately failed computation of the design control-plane digest; its underlying cause was not retained in the originating failure and nearby connection-refused logs do not establish that cause. Corrections and focused diagnostic proof are in progress, not physically verified. CI ran synthetic checkout `ce79309368c5563361b6888746d9939a97e0dffe`, tree `c15a5256fbad57b77c4a2c507d6dbb33620c40d1`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source; this does not prove alignment with the recorded integration parent. All four Gameplay handoffs and activation remain open. diff --git a/dev-tools/README.md b/dev-tools/README.md index 1a4b91e74f..1c97b6a607 100644 --- a/dev-tools/README.md +++ b/dev-tools/README.md @@ -53,6 +53,8 @@ The `pr-review`, `report-worktree-pr-topology.sh`, and `maintenance/cloc-report. - `tests/` – contract tests for repo-owned tooling. - `validation/` – repo policy and static validation scripts used by Gradle and CI. +The focused [Account jOOQ projection contract](tests/account-jooq-projection-contract.sh) executes the registered projection task with original and forward-versioned inventory migration fixtures. It checks byte-preserving projection and rejects missing or ambiguous semantic migration identities before touching existing output; it is not PostgreSQL migration proof. + The documentation lock is sourced from the unpinned direct roots in `config/docs/requirements.in` and generated into `config/docs/requirements.txt` with the repository Python version and `pip-compile --allow-unsafe --generate-hashes --index-url=https://pypi.org/simple --output-file=config/docs/requirements.txt config/docs/requirements.in`. The existing lock seeds compilation and preserves satisfying package pins unless you explicitly request an upgrade. When the installed pip-tools version mis-serializes its default index options into an unsupported header, set `CUSTOM_COMPILE_COMMAND` to that exact command so the generated header remains parseable. Keep the source roots and lock hashes in sync; do not edit lock hashes manually. ## Placement guidance diff --git a/dev-tools/tests/account-jooq-projection-contract.sh b/dev-tools/tests/account-jooq-projection-contract.sh new file mode 100644 index 0000000000..74519894a9 --- /dev/null +++ b/dev-tools/tests/account-jooq-projection-contract.sh @@ -0,0 +1,177 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)" +cd "$ROOT_DIR" + +fail() { + printf 'account jOOQ projection contract: %s\n' "$1" >&2 + exit 1 +} + +TEMP_PARENT="$(cd "${TMPDIR:-/tmp}" && pwd -P)" +TEMP_DIR="$(mktemp -d "$TEMP_PARENT/account-jooq-projection.XXXXXXXX")" +case "$TEMP_DIR" in + "$TEMP_PARENT"/account-jooq-projection.*) ;; + *) fail 'temporary directory did not use the expected private prefix' ;; +esac +[[ -d "$TEMP_DIR" && ! -L "$TEMP_DIR" ]] || fail 'temporary directory is not a real directory' + +cleanup() { + local resolved + if [[ -n "${TEMP_DIR:-}" && -d "$TEMP_DIR" && ! -L "$TEMP_DIR" ]]; then + resolved="$(cd "$TEMP_DIR" && pwd -P)" || return + case "$resolved" in + "$TEMP_PARENT"/account-jooq-projection.*) rm -rf -- "$resolved" ;; + *) printf 'account jOOQ projection contract: refusing unvalidated cleanup path\n' >&2 ;; + esac + fi +} +trap cleanup EXIT + +BASE_COMMIT=3976704464d193e56aa27111724ffdc192c6cef6 +BASE_MIGRATION=services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql +BASELINE="$TEMP_DIR/original-migration.sql" +EXPECTED="$TEMP_DIR/expected-projection.sql" +INIT_SCRIPT="$TEMP_DIR/override-projection-directories.gradle" +git show "$BASE_COMMIT:$BASE_MIGRATION" > "$BASELINE" \ + || fail 'could not read the original migration fixture from the delegated base commit' +[[ -s "$BASELINE" ]] || fail 'original migration fixture is empty' + +python3 - "$BASELINE" "$EXPECTED" <<'PY' +from pathlib import Path +import sys + +source_path, expected_path = map(Path, sys.argv[1:]) +source_bytes = source_path.read_bytes() +source = source_bytes.decode("utf-8") +ignore_end = "-- [jooq ignore end]" +ignore_stop = "-- [jooq ignore stop]" +inventory_alter = """ALTER TABLE account_jwt_readiness_probe_plans + ADD COLUMN inventory_snapshot_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_digest_check + CHECK (inventory_snapshot_digest IS NULL + OR inventory_snapshot_digest ~ '^[0-9a-f]{64}$'), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, + kubernetes_namespace, expected_cluster_incarnation_uid, expected_namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT;""" +projected_inventory_alters = """ALTER TABLE account_jwt_readiness_probe_plans + ADD COLUMN inventory_snapshot_digest VARCHAR(64); +ALTER TABLE account_jwt_readiness_probe_plans + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_digest_check + CHECK (inventory_snapshot_digest IS NULL + OR inventory_snapshot_digest ~ '^[0-9a-f]{64}$'); +ALTER TABLE account_jwt_readiness_probe_plans + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, + kubernetes_namespace, expected_cluster_incarnation_uid, expected_namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT;""" + +if source.count(ignore_end) != 1 or source.count(inventory_alter) != 1: + raise SystemExit("original migration fixture does not match the approved projection shape") +expected = source.replace(ignore_end, ignore_stop).replace( + inventory_alter, projected_inventory_alters +) +expected_path.write_bytes(expected.encode("utf-8")) +PY + +cat > "$INIT_SCRIPT" <<'GROOVY' +gradle.projectsEvaluated { + def account = gradle.rootProject.findProject(":account-service") + if (account == null) { + return + } + def properties = gradle.startParameter.projectProperties + def source = properties.get("firemudProjectionSource") + def output = properties.get("firemudProjectionOutput") + if (!source || !output) { + throw new GradleException("temporary Account projection source/output properties are required") + } + account.tasks.named("projectAccountJooqMigrations").configure { task -> + task.sourceDirectory.set(new File(source)) + task.outputDirectory.set(new File(output)) + } +} +GROOVY + +run_projection() { + local source_dir="$1" + local output_dir="$2" + bash dev-tools/validation/run-locked-gradle.sh \ + -I "$INIT_SCRIPT" \ + -PfiremudProjectionSource="$source_dir" \ + -PfiremudProjectionOutput="$output_dir" \ + :account-service:projectAccountJooqMigrations +} + +write_noninventory_fixtures() { + local source_dir="$1" + mkdir -p "$source_dir" + printf 'SELECT 7;\r\n-- byte-exact fixture without final newline' \ + > "$source_dir/V300__unrelated_projection_contract.sql" + printf 'SELECT 8;\n' > "$source_dir/prefix_V301__account_jwt_validator_inventory_snapshots.sql" +} + +verify_success_case() { + local version="$1" + local source_dir="$TEMP_DIR/source-$version" + local output_dir="$TEMP_DIR/output-$version" + local migration_name="${version}__account_jwt_validator_inventory_snapshots.sql" + mkdir -p "$source_dir" + cp -- "$BASELINE" "$source_dir/$migration_name" + write_noninventory_fixtures "$source_dir" + + run_projection "$source_dir" "$output_dir" \ + || fail "registered Gradle task rejected $migration_name" + cmp -s "$source_dir/$migration_name" "$BASELINE" \ + || fail "registered Gradle task modified $migration_name" + cmp -s "$output_dir/$migration_name" "$EXPECTED" \ + || fail "registered Gradle task produced an unexpected projection for $migration_name" + cmp -s "$source_dir/V300__unrelated_projection_contract.sql" \ + "$output_dir/V300__unrelated_projection_contract.sql" \ + || fail 'noninventory migration was not copied byte-for-byte' + cmp -s "$source_dir/prefix_V301__account_jwt_validator_inventory_snapshots.sql" \ + "$output_dir/prefix_V301__account_jwt_validator_inventory_snapshots.sql" \ + || fail 'nonmigration lookalike was not copied byte-for-byte' +} + +verify_rejected_case() { + local label="$1" + local source_dir="$2" + local output_dir="$TEMP_DIR/rejected-output-$label" + mkdir -p "$output_dir" + printf 'preserve-before-selection\n' > "$output_dir/sentinel.txt" + if run_projection "$source_dir" "$output_dir" > "$TEMP_DIR/$label.log" 2>&1; then + fail "registered Gradle task unexpectedly accepted $label inventory migrations" + fi + rg -q 'Expected exactly one correctly versioned Account validator-inventory migration' \ + "$TEMP_DIR/$label.log" \ + || fail "registered Gradle task failed for an unrelated reason in $label case" + cmp -s "$output_dir/sentinel.txt" <(printf 'preserve-before-selection\n') \ + || fail "registered Gradle task changed output before rejecting $label inventory migrations" + [[ ! -e "$output_dir/V52__account_jwt_validator_inventory_snapshots.sql" ]] \ + || fail "registered Gradle task wrote projected output before rejecting $label inventory migrations" +} + +verify_success_case V52 +verify_success_case V100 +verify_success_case V108 + +ZERO_SOURCE="$TEMP_DIR/source-zero" +write_noninventory_fixtures "$ZERO_SOURCE" +verify_rejected_case zero "$ZERO_SOURCE" + +AMBIGUOUS_SOURCE="$TEMP_DIR/source-ambiguous" +mkdir -p "$AMBIGUOUS_SOURCE" +cp -- "$BASELINE" "$AMBIGUOUS_SOURCE/V52__account_jwt_validator_inventory_snapshots.sql" +cp -- "$BASELINE" "$AMBIGUOUS_SOURCE/V100__account_jwt_validator_inventory_snapshots.sql" +verify_rejected_case ambiguous "$AMBIGUOUS_SOURCE" + +printf 'account jOOQ projection contract: passed\n' diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java index 1eccd236ae..c70b7ac97d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java @@ -9,6 +9,8 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; @@ -108,6 +110,7 @@ private Snapshot snapshot( authority.put("tenantBillingCutoff", Map.copyOf(values)); }); var upstream = existing.issuerAccount(); + var issuanceFenceSource = requireIssuanceFenceSource(member); byte[] issuer = upstream.canonicalIssuerProjection().toJson().getBytes(StandardCharsets.UTF_8); byte[] account = upstream.canonicalAccountProjection().toJson().getBytes(StandardCharsets.UTF_8); @@ -222,12 +225,25 @@ private Snapshot snapshot( Map.copyOf(authority), numeric(member.membershipVersion()), Long.parseLong(member.issuanceFence()), + issuanceFenceSource.sourceVersion(), List.copyOf(vector), evidence, checkpoints, identity); } + static IssuanceFence requireIssuanceFenceSource(CreatorControlCaptureSources member) { + var source = + Objects.requireNonNull( + Objects.requireNonNull(member).authoritySnapshot().issuanceFence(), + "Authenticated Account issuance fence source required"); + if (source.sourceVersion() <= 0L + || !Long.toString(source.value()).equals(member.issuanceFence())) { + throw new IllegalStateException("Authenticated Account issuance fence source required"); + } + return source; + } + private static Map numeric(Map values) { Map result = new LinkedHashMap<>(); values.forEach((key, value) -> result.put(key, Long.parseLong(value))); @@ -285,6 +301,7 @@ public static final class Snapshot { private final Map tuple; private final Map membership; private final long fence; + private final long issuanceFenceSourceVersion; private final List vector; private final byte[] evidence; private final List> checkpoints; @@ -296,6 +313,7 @@ private Snapshot( Map tuple, Map membership, long fence, + long issuanceFenceSourceVersion, List vector, byte[] evidence, List> checkpoints, @@ -305,6 +323,7 @@ private Snapshot( this.tuple = Map.copyOf(tuple); this.membership = Map.copyOf(membership); this.fence = fence; + this.issuanceFenceSourceVersion = issuanceFenceSourceVersion; this.vector = List.copyOf(vector); this.evidence = evidence.clone(); this.checkpoints = List.copyOf(checkpoints); @@ -331,6 +350,10 @@ public long issuanceFence() { return fence; } + public long issuanceFenceSourceVersion() { + return issuanceFenceSourceVersion; + } + public List sources() { return vector; } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java index 41a8fb5d01..3fa03a6257 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java @@ -1,4 +1,4 @@ -package unit.net.firedevops.firemud.accountservice.authordraft; +package net.firedevops.firemud.accountservice.authordraft; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -12,14 +12,73 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; -import net.firedevops.firemud.accountservice.authordraft.AccountDraftSourceCompositionService; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CurrentnessEvidence; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.EnvironmentBoundCurrentness; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources; import org.junit.jupiter.api.Test; class AccountControlUiAuthorityTest { + @Test + void retainsFenceSourceVersionIndependentlyFromActualFenceValue() { + UUID account = UUID.randomUUID(); + var first = AccountControlUiAuthority.requireIssuanceFenceSource(member(account, 4L, 12L)); + var advanced = AccountControlUiAuthority.requireIssuanceFenceSource(member(account, 4L, 13L)); + + assertThat(first.value()).isEqualTo(4L); + assertThat(first.sourceVersion()).isEqualTo(12L); + assertThat(advanced.value()).isEqualTo(first.value()); + assertThat(advanced.sourceVersion()).isEqualTo(13L); + } + + @Test + void rejectsFenceSourceThatDoesNotMatchTheAuthenticatedMemberValue() { + UUID account = UUID.randomUUID(); + var member = member(account, 4L, 12L, 5L); + + assertThatThrownBy(() -> AccountControlUiAuthority.requireIssuanceFenceSource(member)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("issuance fence source"); + } + + @Test + void typedIssuanceFenceRejectsNonPositiveSourceVersion() { + assertThatThrownBy(() -> new IssuanceFence(UUID.randomUUID(), 4L, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be positive"); + } + + private static CreatorControlCaptureSources member(UUID account, long fence, long sourceVersion) { + return member(account, fence, sourceVersion, fence); + } + + private static CreatorControlCaptureSources member( + UUID account, long fence, long sourceVersion, long authenticatedMemberFence) { + var issuerFence = new IssuanceFence(account, fence, sourceVersion); + var issuer = new ScopeState(AuthorityScope.issuer("firemud-account-service"), 1L, 1L, null); + var accountState = new ScopeState(AuthorityScope.account(account), 1L, 1L, issuerFence); + var snapshot = new CompositeSnapshot(issuer, accountState, List.of(), List.of(), issuerFence); + return new CreatorControlCaptureSources( + account, + UUID.randomUUID(), + snapshot, + Map.of(), + null, + Long.toString(authenticatedMemberFence), + null, + null, + null, + null, + null, + List.of(), + List.of(), + Instant.EPOCH); + } + @Test void explicitTypedNoDeadlineReadbackPermitsExistingCompositionToContinue() { var sources = mock(AccountDraftSourceCompositionService.class); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScope.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScope.java new file mode 100644 index 0000000000..c78a9a468a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScope.java @@ -0,0 +1,125 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** + * Integrity input for a distinct preliminary Account source reservation. Decoding establishes no + * Account authentication, source completeness, or finalized owner retention permission. + */ +public record SelectedOwnerIntakeSourceReadScope( + Owner owner, + String targetNamespace, + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + UUID actorAccountId, + DraftCommitBinding selected) { + public static final int MAX_BYTES = 4194304; + + public SelectedOwnerIntakeSourceReadScope { + schemaFor(owner); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) + throw new IllegalArgumentException("Canonical scope namespace required"); + for (var id : List.of(operationId, fenceId, intakeRequestId, actorAccountId)) + DraftAuthorizationFenceBinding.requireUuid(id); + Objects.requireNonNull(selected, "selected"); + encode(owner, targetNamespace, operationId, fenceId, intakeRequestId, actorAccountId, selected); + } + + public String schema() { + return schemaFor(owner); + } + + public String purpose() { + return purposeFor(owner); + } + + public String intendedReader() { + return accountReader(targetNamespace); + } + + public byte[] canonicalBytes() { + return encode( + owner, targetNamespace, operationId, fenceId, intakeRequestId, actorAccountId, selected); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + public static SelectedOwnerIntakeSourceReadScope fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) + throw new IllegalArgumentException("Invalid owner source scope size"); + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + String schema = reader.text(); + Owner owner = Owner.valueOf(reader.text()); + if (!schemaFor(owner).equals(schema)) + throw new IllegalArgumentException("Owner source scope schema differs"); + String namespace = reader.text(); + UUID operation = uuid(reader.text()); + UUID fence = uuid(reader.text()); + UUID request = uuid(reader.text()); + UUID actor = uuid(reader.text()); + var selected = DraftCommitBinding.fromStored(reader.text(), reader.text()); + var result = + new SelectedOwnerIntakeSourceReadScope( + owner, namespace, operation, fence, request, actor, selected); + reader.expect(result.intendedReader()); + reader.expect(result.purpose()); + reader.requireEnd(); + if (!Arrays.equals(bytes, result.canonicalBytes())) + throw new IllegalArgumentException("Noncanonical owner source scope"); + return result; + } + + private static byte[] encode( + Owner owner, + String namespace, + UUID operation, + UUID fence, + UUID request, + UUID actor, + DraftCommitBinding selected) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, schemaFor(owner)); + DraftAuthorizationFenceBinding.frame(out, owner.name()); + DraftAuthorizationFenceBinding.frame(out, namespace); + for (var id : List.of(operation, fence, request, actor)) + DraftAuthorizationFenceBinding.frame(out, id.toString()); + DraftAuthorizationFenceBinding.frame(out, selected.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, selected.digest()); + DraftAuthorizationFenceBinding.frame(out, accountReader(namespace)); + DraftAuthorizationFenceBinding.frame(out, purposeFor(owner)); + if (out.size() > MAX_BYTES) + throw new IllegalArgumentException("Owner source scope exceeds 4 MiB"); + return out.toByteArray(); + } + + private static String schemaFor(Owner owner) { + if (owner == Owner.ENTITY_MANAGEMENT) return "account-entity-intake-source-read/v1"; + if (owner == Owner.AUTOMATION_SCRIPTING) return "account-automation-intake-source-read/v1"; + throw new IllegalArgumentException("Unsupported selected source intake owner"); + } + + private static String purposeFor(Owner owner) { + schemaFor(owner); + return owner == Owner.ENTITY_MANAGEMENT ? "ENTITY_INTAKE_SOURCE" : "AUTOMATION_INTAKE_SOURCE"; + } + + private static String accountReader(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + } + + private static UUID uuid(String value) { + DraftAuthorizationFenceBinding.canonicalUuid(value); + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java new file mode 100644 index 0000000000..534f448d55 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java @@ -0,0 +1,405 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Stipulated immutable fixtures prove integrity only, never genuine Account or owner authority. */ +class SelectedOwnerIntakeSourceReadScopeTest { + private static final UUID TENANT = id(1); + private static final UUID VERSION = id(2); + private static final UUID OPERATION = id(3); + private static final UUID FENCE = id(4); + private static final UUID INTAKE = id(5); + private static final UUID ACTOR = id(6); + private static final UUID REQUEST = id(7); + private static final UUID COMMIT = id(8); + private static final UUID REVISION = id(9); + private static final String PAYLOAD = "{\"originalRevision\":\"retained exactly\"}"; + + @Test + void frozenDirectPreimageAndDigestRoundTripBothOwnerDomains() throws Exception { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var scope = scope(owner); + String schema = + owner == Owner.ENTITY_MANAGEMENT + ? "account-entity-intake-source-read/v1" + : "account-automation-intake-source-read/v1"; + String purpose = + owner == Owner.ENTITY_MANAGEMENT ? "ENTITY_INTAKE_SOURCE" : "AUTOMATION_INTAKE_SOURCE"; + // Independent, fixed-field preimage: no production scope encoder or framing helper. + byte[] expected = + frames( + schema, + owner.name(), + "test", + OPERATION.toString(), + FENCE.toString(), + INTAKE.toString(), + ACTOR.toString(), + frozenSelectedJson(), + digest(frozenSelectedJson().getBytes(StandardCharsets.UTF_8)), + "spiffe://firemud/ns/test/sa/account-service", + purpose); + assertThat(scope.selected().canonicalJson()).isEqualTo(frozenSelectedJson()); + assertThat(scope.canonicalBytes()).isEqualTo(expected); + assertThat(scope.digest()).isEqualTo(digest(expected)); + var restored = SelectedOwnerIntakeSourceReadScope.fromStored(expected); + assertThat(restored).isEqualTo(scope); + assertThat(restored.canonicalBytes()).isEqualTo(expected); + assertThat(restored.schema()).isEqualTo(schema); + assertThat(restored.purpose()).isEqualTo(purpose); + assertThat(restored.intendedReader()) + .isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + } + } + + @Test + void everyIdentityAndTheCompleteSelectedBindingAffectIntegrity() { + var original = scope(Owner.ENTITY_MANAGEMENT); + var selected = original.selected(); + for (var changed : + List.of( + scope(Owner.AUTOMATION_SCRIPTING), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), "other", OPERATION, FENCE, INTAKE, ACTOR, selected), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), "test", id(10), FENCE, INTAKE, ACTOR, selected), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), "test", OPERATION, id(10), INTAKE, ACTOR, selected), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), "test", OPERATION, FENCE, id(10), ACTOR, selected), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), "test", OPERATION, FENCE, INTAKE, id(10), selected), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), + "test", + OPERATION, + FENCE, + INTAKE, + ACTOR, + binding(id(10), COMMIT, PAYLOAD)), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), + "test", + OPERATION, + FENCE, + INTAKE, + ACTOR, + binding(REQUEST, id(10), PAYLOAD)), + new SelectedOwnerIntakeSourceReadScope( + original.owner(), + "test", + OPERATION, + FENCE, + INTAKE, + ACTOR, + binding(REQUEST, COMMIT, PAYLOAD + " ")))) { + assertThat(changed.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(changed.digest()).isNotEqualTo(original.digest()); + assertThat(SelectedOwnerIntakeSourceReadScope.fromStored(changed.canonicalBytes())) + .isEqualTo(changed); + } + } + + @Test + void preservesEntireOriginalRevisionAndBaseWithoutInventingWorldAssociation() { + var original = scope(Owner.ENTITY_MANAGEMENT); + var decoded = SelectedOwnerIntakeSourceReadScope.fromStored(original.canonicalBytes()); + assertThat(decoded.selected()).isEqualTo(original.selected()); + assertThat(decoded.selected().baseCommitId()).isEqualTo("base-commit-0"); + assertThat(decoded.selected().revisions()) + .containsExactly( + new DraftCommitBinding.RevisionPayload( + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, PAYLOAD)); + assertThat(decoded.selected().requiredOwners()) + .containsExactly(Owner.GAME_DESIGN_CONTROL_PLANE); + } + + @Test + void deniesUnknownOwnersAndCrossOwnerSchemaPurposeOrReader() throws Exception { + var scope = scope(Owner.ENTITY_MANAGEMENT); + for (Owner owner : + List.of(Owner.WORLD_MANAGEMENT, Owner.GAME_LOGIC, Owner.GAME_DESIGN_CONTROL_PLANE)) + assertThatThrownBy( + () -> + new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, INTAKE, ACTOR, scope.selected())) + .isInstanceOf(IllegalArgumentException.class); + for (String[] changed : + List.of( + new String[] { + "account-automation-intake-source-read/v1", + "ENTITY_MANAGEMENT", + "ENTITY_INTAKE_SOURCE", + scope.intendedReader() + }, + new String[] { + scope.schema(), "AUTOMATION_SCRIPTING", scope.purpose(), scope.intendedReader() + }, + new String[] {scope.schema(), "UNKNOWN", scope.purpose(), scope.intendedReader()}, + new String[] { + "account-entity-intake-source-read/v2", + "ENTITY_MANAGEMENT", + scope.purpose(), + scope.intendedReader() + }, + new String[] { + scope.schema(), "GAME_LOGIC", "GAME_LOGIC_INTAKE_SOURCE", scope.intendedReader() + }, + new String[] { + "account-game-logic-intake-source-read/v1", + "ENTITY_MANAGEMENT", + scope.purpose(), + scope.intendedReader() + }, + new String[] { + scope.schema(), + "ENTITY_MANAGEMENT", + "AUTOMATION_INTAKE_SOURCE", + scope.intendedReader() + }, + new String[] { + scope.schema(), + "ENTITY_MANAGEMENT", + scope.purpose(), + "spiffe://firemud/ns/test/sa/entity-management-service" + }, + new String[] { + scope.schema(), + "ENTITY_MANAGEMENT", + scope.purpose(), + "spiffe://firemud/ns/other/sa/account-service" + })) { + byte[] bytes = + wire( + changed[0], + changed[1], + "test", + ACTOR.toString(), + scope.selected().canonicalJson(), + scope.selected().digest(), + changed[3], + changed[2]); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void deniesMalformedTruncatedTrailingOversizedAndNoncanonicalInput() throws Exception { + var scope = scope(Owner.ENTITY_MANAGEMENT); + byte[] bytes = scope.canonicalBytes(); + byte[] invalidUtf8 = bytes.clone(); + invalidUtf8[4] = (byte) 0xc0; + for (byte[] invalid : + List.of( + new byte[0], + new byte[] {-1, -1, -1, -1}, + invalidUtf8, + Arrays.copyOf(bytes, bytes.length - 1), + Arrays.copyOf(bytes, bytes.length + 1), + new byte[SelectedOwnerIntakeSourceReadScope.MAX_BYTES + 1])) + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(null)) + .isInstanceOf(IllegalArgumentException.class); + for (String actor : + List.of("00000000-0000-0000-0000-000000000000", "1-1-1-1-1", "NOT-A-UUID")) { + byte[] invalid = + wire( + scope.schema(), + scope.owner().name(), + "test", + actor, + scope.selected().canonicalJson(), + scope.selected().digest(), + scope.intendedReader(), + scope.purpose()); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + for (String namespace : List.of("Test", "test/other", " test", "")) { + byte[] invalid = + wire( + scope.schema(), + scope.owner().name(), + namespace, + ACTOR.toString(), + scope.selected().canonicalJson(), + scope.selected().digest(), + scope.intendedReader(), + scope.purpose()); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + byte[] wrongDigest = + wire( + scope.schema(), + scope.owner().name(), + "test", + ACTOR.toString(), + scope.selected().canonicalJson(), + "sha256:" + "0".repeat(64), + scope.intendedReader(), + scope.purpose()); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(wrongDigest)) + .isInstanceOf(RuntimeException.class); + String noncanonical = " " + scope.selected().canonicalJson(); + byte[] padded = + wire( + scope.schema(), + scope.owner().name(), + "test", + ACTOR.toString(), + noncanonical, + digest(noncanonical.getBytes(StandardCharsets.UTF_8)), + scope.intendedReader(), + scope.purpose()); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(padded)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + new SelectedOwnerIntakeSourceReadScope( + scope.owner(), + "test", + OPERATION, + FENCE, + INTAKE, + ACTOR, + binding( + REQUEST, COMMIT, "x".repeat(SelectedOwnerIntakeSourceReadScope.MAX_BYTES)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsNilReservationIdentitiesAndUnsupportedNullOwner() { + var selected = scope(Owner.ENTITY_MANAGEMENT).selected(); + UUID nil = new UUID(0, 0); + for (var ids : + List.of( + List.of(nil, FENCE, INTAKE, ACTOR), + List.of(OPERATION, nil, INTAKE, ACTOR), + List.of(OPERATION, FENCE, nil, ACTOR), + List.of(OPERATION, FENCE, INTAKE, nil))) + assertThatThrownBy( + () -> + new SelectedOwnerIntakeSourceReadScope( + Owner.ENTITY_MANAGEMENT, + "test", + ids.get(0), + ids.get(1), + ids.get(2), + ids.get(3), + selected)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new SelectedOwnerIntakeSourceReadScope( + null, "test", OPERATION, FENCE, INTAKE, ACTOR, selected)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SelectedOwnerIntakeSourceReadScope scope(Owner owner) { + return new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, INTAKE, ACTOR, binding(REQUEST, COMMIT, PAYLOAD)); + } + + private static DraftCommitBinding binding(UUID request, UUID commit, String payload) { + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + request, + commit, + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static String frozenSelectedJson() { + return "{\"affectedUnits\":[{\"aggregateId\":\"" + + VERSION + + "\",\"aggregateType\":\"TEMPLATE_CONFIG\",\"expectedEpoch\":\"0\"," + + "\"owner\":\"GAME_DESIGN_CONTROL_PLANE\",\"scopeId\":\"ALL\"," + + "\"scopeType\":\"TEMPLATE_CONFIG\"}],\"baseCommitId\":\"base-commit-0\"," + + "\"canonicalTenantId\":\"" + + TENANT + + "\",\"canonicalVersionId\":\"" + + VERSION + + "\",\"commitId\":\"" + + COMMIT + + "\",\"requestId\":\"" + + REQUEST + + "\",\"requiredOwners\":[\"GAME_DESIGN_CONTROL_PLANE\"]," + + "\"revisions\":[{\"owner\":\"GAME_DESIGN_CONTROL_PLANE\"," + + "\"payload\":\"{\\\"originalRevision\\\":\\\"retained exactly\\\"}\",\"revisionId\":\"" + + REVISION + + "\",\"revisionOrder\":\"0\"}],\"schemaVersion\":\"1\"," + + "\"target\":{\"gameDesignVersionRowId\":\"23\",\"gameDesignVersionTenantKey\":\"tenant\"," + + "\"sourceGameRowId\":\"42\",\"sourceGameTenantKey\":\"tenant\"," + + "\"sourceProvenanceKind\":\"NEW_GAME_ROW\"}}"; + } + + private static byte[] wire( + String schema, + String owner, + String namespace, + String actor, + String selected, + String selectedDigest, + String reader, + String purpose) + throws Exception { + return frames( + schema, + owner, + namespace, + OPERATION.toString(), + FENCE.toString(), + INTAKE.toString(), + actor, + selected, + selectedDigest, + reader, + purpose); + } + + private static byte[] frames(String... fields) throws Exception { + var output = new ByteArrayOutputStream(); + var data = new DataOutputStream(output); + for (String field : fields) { + byte[] bytes = field.getBytes(StandardCharsets.UTF_8); + data.writeInt(bytes.length); + data.write(bytes); + } + return output.toByteArray(); + } + + private static String digest(byte[] bytes) throws Exception { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID id(int value) { + return UUID.fromString("00000000-0000-4000-8000-" + String.format("%012d", value)); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java index 16e14be596..2c53543671 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAssetRepository.java @@ -78,7 +78,7 @@ private GameAsset toEntity(Record record) { asset.setFileName(record.get(FILE_NAME)); asset.setContentType(record.get(CONTENT_TYPE)); asset.setData(record.get(DATA)); - asset.setCreatedAt(record.get(CREATED_AT)); + asset.setCreatedAt(record.get(CREATED_AT.getName(), LocalDateTime.class)); return asset; } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java index f77ca86f4e..5695f44208 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java @@ -81,13 +81,14 @@ void forwardUpgradePreservesRetainedV1OperationAndAdmitsOnlyPairedProfiles() thr TargetProof target = targetProof(version); // This shared fixture creates the historical inventory/v1 + graph/2 + digest/3 profile. - // The owner setup writes real GD selection, attempt and operation rows; Account and World - // source/receipt authority remains stipulated test evidence, not a production claim. + // The owner setup applies the required GD owner and writes real source, selection, attempt and + // operation rows; Account and World source/receipt authority remains stipulated test evidence, + // not a production claim. GameDesignPublicationOperation historicalV1 = transaction.execute( status -> { try { - return IsolatedPublicationOwnerSetup.retain( + return IsolatedPublicationOwnerSetup.retainSourceBacked( dsl, target, version.getVersionStateEpoch(), "synthetic V69 history"); } catch (Exception failure) { throw new IllegalStateException(failure); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java index f8c151d283..e425e20c04 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.Locale; import java.util.concurrent.atomic.AtomicReference; @@ -24,6 +25,8 @@ class GameAssetRepositoryTest { private static final Field DATA = DSL.field(DSL.name("data"), byte[].class); private static final Field CREATED_AT = DSL.field(DSL.name("created_at"), LocalDateTime.class); + private static final Field JDBC_CREATED_AT = + DSL.field(DSL.name("created_at"), Timestamp.class); @Test void insertUsesPostgresReturningFieldsAndMapsThePersistedRow() { @@ -71,6 +74,52 @@ void insertUsesPostgresReturningFieldsAndMapsThePersistedRow() { assertThat(saved.getCreatedAt()).isEqualTo(LocalDateTime.of(2026, 10, 9, 12, 30)); } + @Test + void tenantReadConvertsJdbcTimestampFromUntypedSelectAndPreservesData() { + AtomicReference executedSql = new AtomicReference<>(); + LocalDateTime createdAt = LocalDateTime.of(2026, 10, 9, 12, 30, 45, 123_456_789); + byte[] data = new byte[] {4, 5, 6}; + DSLContext dsl = + DSL.using( + new MockConnection( + context -> { + executedSql.set(context.sql()); + var result = + DSL.using(SQLDialect.POSTGRES) + .newResult(ID, TENANT_ID, FILE_NAME, CONTENT_TYPE, DATA, JDBC_CREATED_AT); + var row = + DSL.using(SQLDialect.POSTGRES) + .newRecord(ID, TENANT_ID, FILE_NAME, CONTENT_TYPE, DATA, JDBC_CREATED_AT); + row.set(ID, 74L); + row.set(TENANT_ID, "tenant-1"); + row.set(FILE_NAME, "room.bin"); + row.set(CONTENT_TYPE, "application/octet-stream"); + row.set(DATA, data); + row.set(JDBC_CREATED_AT, Timestamp.valueOf(createdAt)); + result.add(row); + return new MockResult[] {new MockResult(1, result)}; + }), + SQLDialect.POSTGRES); + + var assets = new GameAssetRepository(dsl).findByTenantId("tenant-1"); + + assertThat(executedSql.get().toLowerCase(Locale.ROOT)) + .contains( + "select * from \"game_assets\"", "where \"tenant_id\" = ?", "order by \"id\" asc"); + assertThat(assets) + .singleElement() + .satisfies( + asset -> { + assertThat(asset.getId()).isEqualTo(74L); + assertThat(asset.getTenantId()).isEqualTo("tenant-1"); + assertThat(asset.getFileName()).isEqualTo("room.bin"); + assertThat(asset.getContentType()).isEqualTo("application/octet-stream"); + assertThat(asset.getData()).containsExactly(4, 5, 6); + assertThat(asset.getCreatedAt()).isEqualTo(createdAt); + assertThat(asset.getCreatedAt().getNano()).isEqualTo(123_456_789); + }); + } + @Test void insertFailsClearlyWhenPostgresReturnsNoPersistedRow() { DSLContext dsl = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java index 61a480486f..7893bfe0e1 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java @@ -292,24 +292,7 @@ static WorldSelectedPublicationArtifactInventory capture( List spawnInputs = new ArrayList<>(); for (var row : graph.family(WorldCanonicalAuthoredGraph.Family.WORLD_ENTITY_SPAWN_BINDING)) { - if (!row.content().hasWorldEntitySpawnBinding() || row.entityReference() == null) { - throw unrepresentable( - UnrepresentableReason.UNKNOWN_GRAPH_FAMILY, - "World selected graph spawn binding lacks its closed typed Entity reference"); - } - var spawn = row.content().getWorldEntitySpawnBinding(); - var reference = row.entityReference(); - spawnInputs.add( - new SpawnBindingInput( - row.template().templateId(), - UUID.fromString(spawn.getRoomId()), - spawn.getEntityTemplateType().name(), - reference.kind().name(), - reference.tenantId(), - reference.versionId(), - reference.templateId(), - spawn.getSpawnCount(), - spawn.getRespawnDelaySeconds())); + spawnInputs.add(projectSpawnBinding(graph.tenantId(), graph.versionId(), row)); } requireSupportedRequiredness( graph.tenantId(), graph.versionId(), generatorInputs, generationRuleCount, spawnInputs); @@ -401,6 +384,49 @@ static WorldSelectedPublicationArtifactInventory capture( return new WorldSelectedPublicationArtifactInventory(envelope, encode(envelope)); } + static SpawnBindingInput projectSpawnBinding( + UUID tenantId, UUID versionId, WorldCanonicalAuthoredGraph.Row row) { + if (row.template().family() != WorldCanonicalAuthoredGraph.Family.WORLD_ENTITY_SPAWN_BINDING + || !row.content().hasWorldEntitySpawnBinding() + || row.entityReference() == null) { + throw unrepresentable( + UnrepresentableReason.SPAWN_BINDING_INPUT, + "World selected graph spawn binding lacks its closed typed Entity reference"); + } + var spawn = row.content().getWorldEntitySpawnBinding(); + var reference = row.entityReference(); + String templateType = + switch (spawn.getEntityTemplateType()) { + case ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM -> "ITEM"; + case ENTITY_TEMPLATE_REFERENCE_TYPE_NPC -> "NPC"; + default -> + throw unrepresentable( + UnrepresentableReason.SPAWN_BINDING_INPUT, + "World selected graph spawn binding has an unsupported Entity subtype"); + }; + if (reference.kind() != spawn.getEntityTemplateType() + || !tenantId.equals(reference.tenantId()) + || !versionId.equals(reference.versionId()) + || reference.templateId().equals(new UUID(0L, 0L)) + || !reference.templateId().toString().equals(spawn.getEntityTemplateId())) { + throw unrepresentable( + UnrepresentableReason.SPAWN_BINDING_INPUT, + "World selected graph spawn binding differs from its same-scope canonical Entity reference"); + } + // The subtype and identity representation are distinct fields. This tag follows validation of + // the original typed UUID reference; it is neither a proto enum nor Entity owner authority. + return new SpawnBindingInput( + row.template().templateId(), + UUID.fromString(spawn.getRoomId()), + templateType, + "ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID", + reference.tenantId(), + reference.versionId(), + reference.templateId(), + spawn.getSpawnCount(), + spawn.getRespawnDelaySeconds()); + } + static WorldSelectedPublicationArtifactInventory fromStored( byte[] canonicalBytes, String storedDigest, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 4fc51e1039..a63d917bc8 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -1009,37 +1009,43 @@ void worldTerminalReadUsesIndependentQualifiedOwnerAndRequiredMtls() throws Exce @Test void terminalRejectsUnqualifiedHistoricalFreezeWithoutInventingAccountOrder() { - Fixture f = fixture(); - var graphApplication = application(generationFreePlan(f)); - appliedComponent().apply(graphApplication); - var frozen = capture(graphApplication.plan()); + HistoricalSchemaFixture schema = historicalSchemaAt("world_v52_unqualified_freeze", "52"); + var historical = schema.database(); + Fixture f = historical.fixture(); + var graphApplication = + historical.application( + historical.withoutInboundSourceClosure(historical.generationFreePlan(f))); + historical.retainHistoricalApplication(graphApplication); + var frozen = historical.captureHistoricalUnqualified(graphApplication.plan()); + historical.migrateHistoricalSchema(schema.schema(), "62"); var selector = - publishedEvidence( - publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); - var input = preparationInput(f, frozen, selector); + historical.publishedEvidence( + historical.publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = historical.preparationInput(f, frozen, selector); UUID fence = selector.request().publicationFence(); - var ownerBefore = ownerSnapshot(f, graphApplication.plan()); + var ownerBefore = historical.ownerSnapshot(f, graphApplication.plan()); var artifactInventoryRowsBefore = - rowJson( + historical.rowJson( "SELECT to_jsonb(i)::text FROM world_selected_publication_artifact_inventory i " + "WHERE publication_fence=? ORDER BY publication_fence", fence); - assertThat(publicationAccountQualificationCount(fence)).isZero(); + assertThat(historical.publicationAccountQualificationCount(fence)).isZero(); assertThat(artifactInventoryRowsBefore).isEmpty(); - assertThatThrownBy(() -> isolatedTerminalEvidence(input)) + assertThatThrownBy(() -> historical.isolatedTerminalEvidence(input)) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessage("Exact frozen World publication has no complete artifact inventory"); - assertThat(ownerSnapshot(f, graphApplication.plan())).isEqualTo(ownerBefore); + assertThat(historical.ownerSnapshot(f, graphApplication.plan())).isEqualTo(ownerBefore); assertThat( - rowJson( + historical.rowJson( "SELECT to_jsonb(i)::text FROM world_selected_publication_artifact_inventory i " + "WHERE publication_fence=? ORDER BY publication_fence", fence)) .isEqualTo(artifactInventoryRowsBefore); - assertThat(publicationOwnerPhase(fence)).isEqualTo("FROZEN"); - assertThat(publicationTerminalCount(fence)).isZero(); - assertThat(publicationAccountQualificationCount(fence)).isZero(); + assertThat(historical.publicationOwnerPhase(fence)).isEqualTo("FROZEN"); + assertThat(historical.publicationTerminalCount(fence)).isZero(); + assertThat(historical.publicationAccountQualificationCount(fence)).isZero(); + historical.assertOrigin(); } @Test @@ -3460,7 +3466,8 @@ void releaseSelectorRejectsChangedFrozenRequestAndSqlSubstitutionWithoutRuntimeW selector.originalAccountBindingBytes(), selector.appliedResultBytes()); assertThatThrownBy(() -> preparationInput(f, frozen, changed)) - .hasMessageContaining("World selector differs from the exact attested release checkpoint"); + .hasMessageContaining( + "Release selector differs from the exact frozen request, declaration or ROOM"); var input = preparationInput(f, frozen, selector); var encoded = (tools.jackson.databind.node.ObjectNode) @@ -3540,8 +3547,10 @@ void inertV1PreparationRetainsOriginalBytesAndCannotGainSelectorOnRetry() throws HistoricalSchemaFixture schema = historicalSchemaAt("world_v42_inert_v1", "42"); WorldDraftGraphApplicationPostgresIntegrationTest historical = schema.database(); Fixture f = historical.fixture(); - var application = historical.application(historical.generationFreePlan(f)); - historical.appliedComponent().apply(application); + var application = + historical.application( + historical.withoutInboundSourceClosure(historical.generationFreePlan(f))); + historical.retainHistoricalApplication(application); var frozen = historical.captureHistoricalUnqualified(application.plan()); var input = historical.preparationInput(f, frozen, null); var first = historical.prepareV1ThroughOwnerFunction(input); @@ -3738,8 +3747,10 @@ void v41MaterializedV1HistoryRemainsByteExactAndRetryableAfterV42WithoutSelector HistoricalSchemaFixture schema = historicalSchemaAt("world_v41_preparation", "41"); WorldDraftGraphApplicationPostgresIntegrationTest historical = schema.database(); Fixture f = historical.fixture(); - var application = historical.application(historical.generationFreePlan(f)); - var applied = historical.appliedComponent().apply(application); + var application = + historical.application( + historical.withoutInboundSourceClosure(historical.generationFreePlan(f))); + var applied = historical.retainHistoricalApplication(application); var frozen = historical.captureHistoricalUnqualified(application.plan()); var input = historical.preparationInput(f, frozen, null); var first = historical.prepareV1ThroughOwnerFunction(input); @@ -4701,7 +4712,12 @@ private ReleaseContent isolatedReleaseContent(CompleteLaunchBindingEvidence laun release.canonicalVersionId(), release.publishedReleaseBundleRef(), 1, - "v2", + switch (release.schemaVersion()) { + case AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION -> "v2"; + case AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION -> "v3"; + default -> + throw new IllegalArgumentException("Release has no paired terminal content profile"); + }, release.publishWorkflowId(), release.manifestHash(), release.manifestSchemaVersion(), @@ -5974,6 +5990,105 @@ private WorldCanonicalFrozenTopology captureHistoricalUnqualified( return capture(plan, publicationRequest, selection, null); } + /** Synthetic pre-closure application, inserted under the actual V41/V42/V52 owner guards. */ + private WorldDraftGraphAppliedResult retainHistoricalApplication( + WorldDraftGraphApplication application) { + assertThat(application.plan().graph().freshGraphDeclaration()).isPresent(); + assertThat( + application.plan().graph().freshGraphDeclaration().orElseThrow().inboundSourceClosure()) + .isEmpty(); + var result = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> { + var retained = + new WorldDraftTopologyCommitRepository(dsl, fence, mapper) + .store(application.plan()); + var applied = + WorldDraftGraphAppliedResult.create(application, retained.graphBytes()); + new WorldDraftStartLocationReceiptRepository(dsl) + .store( + applied.startLocationReceipt().orElseThrow(), + application.operation().accountBindingBytes()); + insertReceipt(application, applied.canonicalBytes()); + return applied; + })); + assertThat(mapper.readTree(result.graphBytes()).get("schemaVersion").asText()).isEqualTo("2"); + assertThat(appliedRepository().readCommitted(application).orElseThrow().canonicalBytes()) + .containsExactly(result.canonicalBytes()); + return result; + } + + /** + * Synthetic retained V31 graph/2 capture with digest/3; SQL validates the original FROZEN + * checkpoint and source rows. No Account publication qualification is supplied or inferred. + */ + private WorldCanonicalFrozenTopology retainHistoricalFrozenTopology( + WorldCanonicalFrozenTopology.Request request) { + assertThat(request.freeze().digestSchemaVersion()).isEqualTo(3); + ownerTransaction() + .executeWithoutResult( + status -> { + snapshots.lockAndResolve(request.freeze()); + var retained = + new WorldDraftTopologyCommitRepository(dsl, fence, mapper) + .readUnderFrozenLock(request.plan()); + assertThat(mapper.readTree(retained.graphBytes()).get("schemaVersion").asText()) + .isEqualTo("2"); + var source = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(v)::text AS identity_json, to_jsonb(i)::text AS intake_json " + + "FROM world_authored_version_identity v JOIN world_authored_source_intake i " + + "ON i.operation_id=v.intake_operation_id WHERE v.operation_id=?", + request.plan().ownerBinding().versionIdentityOperationId())); + String identityJson = source.get("identity_json", String.class); + String intakeJson = source.get("intake_json", String.class); + UUID captureId = UUID.randomUUID(); + Map result = new LinkedHashMap<>(); + result.put("schemaVersion", "1"); + result.put("status", WorldCanonicalFrozenTopology.STATUS); + result.put( + "missingProof", + List.of( + "ACCOUNT_AUTHORIZATION", + "COMPLETE_PARTICIPANT_COMMIT", + "PUBLICATION_CHECKPOINT_DIGEST")); + result.put("captureId", captureId.toString()); + result.put("freeze", request.freeze()); + result.put("ownerBinding", request.plan().ownerBinding()); + result.put("bindingJson", request.plan().binding().canonicalJson()); + result.put("bindingDigest", request.plan().binding().digest()); + result.put("identityJson", identityJson); + result.put("intakeJson", intakeJson); + result.put("graphBytes", retained.graphBytes()); + result.put("storageResultBytes", retained.resultBytes()); + dsl.execute( + "INSERT INTO world_canonical_frozen_topology (capture_id,publication_fence," + + "request_id,commit_id,version_identity_operation_id,freeze_request_json,owner_binding_json," + + "binding_json,binding_digest,identity_json,intake_json,graph_bytes,graph_sha256," + + "storage_result_bytes,result_bytes,capture_status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + captureId, + request.freeze().publicationFence(), + request.plan().binding().requestId(), + request.plan().binding().commitId(), + request.plan().ownerBinding().versionIdentityOperationId(), + mapper.writeValueAsString(request.freeze()), + mapper.writeValueAsString(request.plan().ownerBinding()), + request.plan().binding().canonicalJson(), + request.plan().binding().digest(), + identityJson, + intakeJson, + retained.graphBytes(), + WorldAuthoredGraphSnapshotCapture.sha256(retained.graphBytes()), + retained.resultBytes(), + mapper.writeValueAsBytes(result), + WorldCanonicalFrozenTopology.STATUS); + }); + return frozenRepository().readCommitted(request).orElseThrow(); + } + private WorldCanonicalFrozenTopology captureForTerminal( WorldDraftTopologyCommitPlan plan, byte[] originalDraftAccountBinding) { String publicationRequest = "selector-" + UUID.randomUUID(); @@ -6082,8 +6197,12 @@ private WorldCanonicalFrozenTopology capture( attempt.checkpoint().contentDigest(), attempt.checkpoint().digestSchemaVersion(), tuples); + var canonicalRequest = new WorldCanonicalFrozenTopology.Request(plan, request); + if (accountBinding == null) { + return retainHistoricalFrozenTopology(canonicalRequest); + } return new WorldCanonicalFrozenTopologyService(frozenRepository(), manager) - .capture(new WorldCanonicalFrozenTopology.Request(plan, request)); + .capture(canonicalRequest); } @Test diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java index 1b47dcbb07..0d77a6b099 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java @@ -10,12 +10,140 @@ import java.util.UUID; import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; +import net.firedevops.firemud.worldmanagement.v1.EntityTemplateReferenceType; +import net.firedevops.firemud.worldmanagement.v1.WorldEntitySpawnBindingDesignMutation; import org.junit.jupiter.api.Test; class WorldSelectedPublicationArtifactInventoryTest { private static final UUID TENANT = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); private static final UUID VERSION = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + @Test + void projectsOriginalTypedItemAndNpcSourcesWithCanonicalUuidRepresentation() { + for (var subtype : + List.of( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC)) { + var row = typedSpawnRow(subtype, subtype, TENANT, VERSION); + var projected = + WorldSelectedPublicationArtifactInventory.projectSpawnBinding(TENANT, VERSION, row); + + assertThat(projected.entityTemplateType()) + .isEqualTo( + subtype == EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM + ? "ITEM" + : "NPC"); + assertThat(projected.entityReferenceKind()) + .isEqualTo("ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID"); + assertThat(projected.entityTenantId()).isEqualTo(TENANT); + assertThat(projected.entityVersionId()).isEqualTo(VERSION); + assertThat(projected.entityTemplateId()).isEqualTo(row.entityReference().templateId()); + assertThat(projected.spawnCount()).isEqualTo(2); + assertThatCode( + () -> + WorldSelectedPublicationArtifactInventory.requireSupportedRequiredness( + TENANT, VERSION, List.of(), 0, List.of(projected))) + .doesNotThrowAnyException(); + } + } + + @Test + void rejectsUnknownUnspecifiedOrMismatchedOriginalSpawnSubtype() { + var npc = EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC; + for (var row : + List.of( + typedSpawnRow( + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_UNSPECIFIED, + npc, + TENANT, + VERSION), + typedSpawnRow(EntityTemplateReferenceType.UNRECOGNIZED, npc, TENANT, VERSION), + typedSpawnRow( + npc, + EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_ITEM, + TENANT, + VERSION))) { + assertReason( + () -> WorldSelectedPublicationArtifactInventory.projectSpawnBinding(TENANT, VERSION, row), + WorldSelectedPublicationArtifactInventory.UnrepresentableReason.SPAWN_BINDING_INPUT); + } + } + + @Test + void rejectsTypedSpawnReferenceOutsideOriginalTenantOrVersion() { + var npc = EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC; + for (var row : + List.of( + typedSpawnRow(npc, npc, UUID.randomUUID(), VERSION), + typedSpawnRow(npc, npc, TENANT, UUID.randomUUID()))) { + assertReason( + () -> WorldSelectedPublicationArtifactInventory.projectSpawnBinding(TENANT, VERSION, row), + WorldSelectedPublicationArtifactInventory.UnrepresentableReason.SPAWN_BINDING_INPUT); + } + } + + @Test + void rejectsNilOrSubstitutedTypedEntityIdentityBeforeAssigningRepresentation() { + var npc = EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC; + var original = typedSpawnRow(npc, npc, TENANT, VERSION); + var authored = original.authored(); + for (UUID templateId : List.of(new UUID(0L, 0L), UUID.randomUUID())) { + var changed = + new WorldCanonicalAuthoredGraph.Row( + original.template(), + original.mappingKey(), + original.privateRowKey(), + new WorldDraftTopologyInputGraph.Node( + authored.revisionOrder(), + authored.revisionId(), + authored.templateId(), + authored.scopeId(), + authored.mutation(), + new WorldDraftTopologyInputGraph.EntityTemplateReference( + npc, TENANT, VERSION, templateId)), + original.content()); + assertReason( + () -> + WorldSelectedPublicationArtifactInventory.projectSpawnBinding( + TENANT, VERSION, changed), + WorldSelectedPublicationArtifactInventory.UnrepresentableReason.SPAWN_BINDING_INPUT); + } + } + + private static WorldCanonicalAuthoredGraph.Row typedSpawnRow( + EntityTemplateReferenceType subtype, + EntityTemplateReferenceType referenceSubtype, + UUID referenceTenant, + UUID referenceVersion) { + UUID bindingId = UUID.randomUUID(); + UUID entityId = UUID.randomUUID(); + var mutation = + WorldDesignMutationRevision.newBuilder() + .setWorldEntitySpawnBinding( + WorldEntitySpawnBindingDesignMutation.newBuilder() + .setRoomId(UUID.randomUUID().toString()) + .setEntityTemplateTypeValue( + subtype == EntityTemplateReferenceType.UNRECOGNIZED + ? 99 + : subtype.getNumber()) + .setEntityTemplateId(entityId.toString()) + .setSpawnCount(2) + .setRespawnDelaySeconds(30)) + .build(); + var reference = + new WorldDraftTopologyInputGraph.EntityTemplateReference( + referenceSubtype, referenceTenant, referenceVersion, entityId); + return new WorldCanonicalAuthoredGraph.Row( + new WorldCanonicalAuthoredGraph.Template( + WorldCanonicalAuthoredGraph.Family.WORLD_ENTITY_SPAWN_BINDING, bindingId), + 1L, + 2L, + new WorldDraftTopologyInputGraph.Node( + "0", UUID.randomUUID(), bindingId, UUID.randomUUID(), mutation, reference), + mutation); + } + @Test void acceptsExplicitEmptyRegionInputsAndClosedCanonicalSpawnBinding() { var region = From 0a8d434eb8bd82381bd814ec129defd6b1ac0103 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 09:12:33 +1300 Subject: [PATCH 063/129] Preserve original Account schema in selected release and repair World proof fixtures --- .../game-design-service/api-contracts.md | 2 + ...ame-authoring-publishing-and-activation.md | 4 +- .../GameDesignSourceRepository.java | 17 ++ .../SelectedOwnerIntakeSourceExport.java | 117 +++++++++++ ..._release_original_account_owner_schema.sql | 23 +++ ...licationExportPostgresIntegrationTest.java | 2 + ...nventoryProfileUpgradeIntegrationTest.java | 16 +- .../SelectedOwnerIntakeSourceExportTest.java | 195 ++++++++++++++++++ ...CanonicalInstanceExecutionFixtureTest.java | 59 ++++++ ...anonicalInstanceExecutionTestFixtures.java | 10 +- 10 files changed, 440 insertions(+), 5 deletions(-) create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V71__selected_release_original_account_owner_schema.sql create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionFixtureTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 89365720b4..1e62b93540 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -73,6 +73,8 @@ The source-read transport has an explicit 24 MiB request/response wire budget be After that confirmation, Game Design reads only the complete immutable source for the proof's exact selected target and commit and compares the complete synchronized binding. Its response echoes the complete request, proof and independent read correlation unchanged. It cannot choose a newer commit, infer an absent family as empty, or turn this source read into permission for mutation, publication or admission. This construction remains unregistered; complete producer, consumer and executed proof status belongs to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +For distinct Entity and Automation intake, the complete Game Design selected-source content binds the owner-specific preliminary scope unchanged and includes all six synchronized families: command, realm policy, asset, gameplay rule, branding and template configuration. Each family retains its original canonical snapshot bytes and provenance for the exact same selected Draft binding; unavailable branding or template history is unknown, not empty. The bounded owner-local construction uses `game-design-selected-owner-intake-source/v1` byte-length framing: domain, complete scope bytes and digest, then `COMMAND`, `REALM_POLICY`, `ASSET`, `GAMEPLAY_RULE`, `BRANDING` and `TEMPLATE_CONFIG` in that fixed order, each followed by its exact snapshot bytes and digest. The complete framed content is limited to 8 MiB. This source value is not authenticated disclosure, an Account reservation or finalization, an Entity/Automation completeness judgment, or an owner receipt. The distinct authenticated permission, source-read transport and held owner retention remain required before any content can be disclosed or accepted through those boundaries; the owner-local constructor does not add a registered RPC or expand the Gameplay Rule method's allowlist. + ## Exact Publication Terminal Read `GameDesignPublicationTerminalReadService.ReadPublicationTerminal` reads the original immutable terminal result, not current permission or a new publication attempt. Its closed version-1 request binds the canonical workload namespace, a non-nil canonical read-request UUID and the complete original `game-design-publication-operation/v1` bytes. The receiver authenticates the exact same-namespace Account or World Management workload before decoding input or accessing storage. 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 d2242c3ffe..2ff4089831 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 @@ -6,7 +6,9 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The distinct Entity/Automation preliminary source-read value now binds closed owner-specific schema and purpose, exact Account operation/fence/request/actor, unchanged complete selected Draft evidence and the derived same-namespace Account reader. Six focused integrity cases and all 478 Common unit cases pass locally; this value does not authenticate a reservation or finalize owner retention. The complete authenticated selected-input export, distinct Account reservation/finalization and source-writer/disclosure exclusion, actual owner census/retention and exact terminal settlement remain open. Gameplay's V74–V97 forward-stage source reservation is being compared before overlapping Account publication; later stages must preserve its baseline and dependency order without duplicate owner DDL or weaker guards. World service-level authenticated recovery after ingress expiry remains open even though repository-only terminal recovery is defined; authenticated original Account participation and Game Session attempt/fence evidence remain prerequisites, not optional verifier checks. +The distinct Entity/Automation preliminary source-read value now binds closed owner-specific schema and purpose, exact Account operation/fence/request/actor, unchanged complete selected Draft evidence and the derived same-namespace Account reader. Six focused integrity cases and all 478 Common unit cases pass locally; this value does not authenticate a reservation or finalize owner retention. The owner-local six-family selected-source export constructor and exact repository accessor now retain all original snapshot bytes, reject missing branding/template history and enforce the complete-content bound; five focused structural cases pass locally. This is not authenticated disclosure or an owner receipt. The authenticated selected-input transport, distinct Account reservation/finalization and source-writer/disclosure exclusion, actual owner census/retention and exact terminal settlement remain open. The unpublished Account migration assembly preserves Gameplay's exact `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` V74–V97 source, all 43 protected baseline migrations and the unique later SQL. Local Account checks pass. Gameplay's newly reserved V98 disclosure journal is already byte-identical to one retained later migration; its final published source must be incorporated once, with the intervening stages shifted coherently, before publishing this assembly. Physical execution of the resulting composed ordering remains required. World service-level authenticated recovery after ingress expiry remains open even though repository-only terminal recovery is defined; authenticated original Account participation and Game Session attempt/fence evidence remain prerequisites, not optional verifier checks. + +Published `f5530b39c27d60299d4f00306b1b0c4ee9a4027e` [Validation run 37981606468](https://github.com/benhook1013/FireMUD/actions/runs/37981606468) completed red. By originating owner artifact, Account executed 254 cases without failures, Game Design executed 151 with one failure and World executed 218 with 60 failures; all have zero errors and skips. Repeated parameterized display names in Account are separate executions, and Account-package source-composition fixtures in the Game Design artifact are not reattributed to Account. The actual V69-to-V70 retained-profile migration case and genuine original GD+World application/settlement/recovery cases passed; several World operation races and retained-history cases passed too. Remaining World failures use sub-millisecond synthetic StartSession timestamps, rejected by the unchanged strict decoder; the corrected test-only emitter has one executed non-container regression. The genuine selected-export failure reaches the real release insertion: its original Account producer emits the canonical v2 required-owner frame, but Game Design V69's selector guard admits only v1. Forward V71 admits those two original schema tags without changing any other complete original Account/APPLIED/selector checks or rewriting retained evidence; its physical upgrade and corrected full export still require execution. CI checked out `e3cc7f09c59459a6dfed7b2ba8d9766327e791ac`, merging this source into `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded `1a8eefe6824c20b8b07a6d6adadda2ad154476e0` integration parent. All four Gameplay handoffs and activation remain open. Published `3976704464d193e56aa27111724ffdc192c6cef6` [Validation run 37974939607](https://github.com/benhook1013/FireMUD/actions/runs/37974939607) completed red: Account executed 254 PostgreSQL cases successfully, World executed 218 with 68 failures, and Game Design executed 151 with two failures; all have zero errors and skips. Genuine original GD+World application, authenticated terminal settlement and original lost-acknowledgement recovery passed, but do not complete the release or runtime handoffs. Most World failures occur before assertions because the shared release fixture declares an old profile for a new closure-qualified release; five remaining cases expose historical-profile fixtures, an incorrect typed spawn projection and stale assertions. Game Design's real selected-export diagnostic exposed a JDBC `Timestamp` mapped as `LocalDateTime` without conversion; its retained-profile upgrade setup omits a required owner outcome before reaching the upgrade. The local corrections preserve historical graph/digest bytes, use actual source-backed Game Design outcomes and validate canonical typed spawn identities before assigning their representation. Three asset repository and eleven inventory regression cases executed locally without skips or failures. Full composed checks and corrected PostgreSQL execution remain required. The actual CI checkout was synthetic merge `5257af32b810218f704ab2aad1d5f3a04881d4ab`, tree `5ad3fdcb295c1ffe014e6364d97113ea09e0493e`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the published source, not the recorded integration parent. V62 execution/abort/concurrency cases failed in setup and are not proved by the separate passing Draft application cases. All four Gameplay handoffs and activation remain open. diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java index e0876b5bc1..0185fdcf60 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java @@ -6,6 +6,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; @@ -358,6 +359,22 @@ public Optional readSynchronized(TargetProof target, UUID c template)); } + /** + * Reads complete synchronized source for the exact distinct owner intake scope. This read and + * export do not authenticate a caller, establish an Account reservation or finalization, or prove + * owner emptiness, owner receipt, or retention authority. + */ + public SelectedOwnerIntakeSourceExport requireSelectedOwnerIntakeSource( + SelectedOwnerIntakeSourceReadScope scope) { + Objects.requireNonNull(scope, "scope"); + var selected = scope.selected(); + var sources = + readSynchronized(selected.target(), selected.commitId()) + .orElseThrow( + () -> new IllegalStateException("Selected Game Design source is unavailable")); + return SelectedOwnerIntakeSourceExport.create(scope, sources); + } + private void requireGenesis(TargetProof target) { if (readGenesis(target).isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_UNAVAILABLE"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java new file mode 100644 index 0000000000..244d9b2208 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExport.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** + * Complete selected six-family Game Design source content for a distinct owner intake read. + * + *

This value proves only that the supplied immutable snapshots are complete and bound to the + * exact selected Draft scope. Constructing it does not authenticate a caller, establish an Account + * reservation or finalization, or prove owner emptiness, owner receipt, or retention authority. + */ +public final class SelectedOwnerIntakeSourceExport { + public static final String DOMAIN = "game-design-selected-owner-intake-source/v1"; + public static final int MAX_BYTES = 8 * 1024 * 1024; + + private final SelectedOwnerIntakeSourceReadScope scope; + private final GameDesignSourceRepository.SynchronizedSources sources; + private final byte[] canonicalBytes; + private final String digest; + + private SelectedOwnerIntakeSourceExport( + SelectedOwnerIntakeSourceReadScope scope, + GameDesignSourceRepository.SynchronizedSources sources, + byte[] canonicalBytes) { + this.scope = scope; + this.sources = sources; + this.canonicalBytes = canonicalBytes.clone(); + this.digest = DraftAuthorizationFenceBinding.digest(this.canonicalBytes); + } + + public static SelectedOwnerIntakeSourceExport create( + SelectedOwnerIntakeSourceReadScope scope, + GameDesignSourceRepository.SynchronizedSources sources) { + Objects.requireNonNull(scope, "scope"); + Objects.requireNonNull(sources, "sources"); + + DraftCommitBinding selected = scope.selected(); + requireSelected(selected, sources.command().binding(), "COMMAND"); + requireSelected(selected, sources.policy().binding(), "REALM_POLICY"); + requireSelected(selected, sources.asset().binding(), "ASSET"); + requireSelected(selected, sources.gameplay().binding(), "GAMEPLAY_RULE"); + var branding = + sources + .branding() + .orElseThrow(() -> new IllegalStateException("Selected branding source is incomplete")); + var templateConfig = + sources + .templateConfig() + .orElseThrow( + () -> new IllegalStateException("Selected template-config source is incomplete")); + requireSelected(selected, branding.binding(), "BRANDING"); + requireSelected(selected, templateConfig.binding(), "TEMPLATE_CONFIG"); + + var out = new ByteArrayOutputStream(); + frame(out, DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + addFamily(out, "COMMAND", sources.command().canonicalBytes()); + addFamily(out, "REALM_POLICY", sources.policy().canonicalBytes()); + addFamily(out, "ASSET", sources.asset().canonicalBytes()); + addFamily(out, "GAMEPLAY_RULE", sources.gameplay().canonicalBytes()); + addFamily(out, "BRANDING", branding.canonicalBytes()); + addFamily(out, "TEMPLATE_CONFIG", templateConfig.canonicalBytes()); + return new SelectedOwnerIntakeSourceExport(scope, sources, out.toByteArray()); + } + + public SelectedOwnerIntakeSourceReadScope scope() { + return scope; + } + + /** The immutable family snapshot values used to construct this export. */ + public GameDesignSourceRepository.SynchronizedSources sources() { + return sources; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + private static void addFamily(ByteArrayOutputStream out, String family, byte[] bytes) { + frame(out, family); + frame(out, bytes); + frame(out, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static void frame(ByteArrayOutputStream out, byte[] bytes) { + DraftAuthorizationFenceBinding.frame(out, bytes); + requireWithinLimit(out); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + requireWithinLimit(out); + } + + private static void requireWithinLimit(ByteArrayOutputStream out) { + if (out.size() > MAX_BYTES) { + throw new IllegalArgumentException("Selected owner intake source exceeds 8 MiB"); + } + } + + private static void requireSelected( + DraftCommitBinding selected, DraftCommitBinding family, String familyName) { + if (!selected.equals(family)) { + throw new IllegalStateException( + "Selected " + familyName + " source differs from the original Draft binding"); + } + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V71__selected_release_original_account_owner_schema.sql b/services/game-design-service/src/main/resources/db/migration/V71__selected_release_original_account_owner_schema.sql new file mode 100644 index 0000000000..cb14c5dba0 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V71__selected_release_original_account_owner_schema.sql @@ -0,0 +1,23 @@ +-- Admit both canonical original Account fence versions for selected releases. +-- Keep the complete binary binding and all exact selector/readback checks unchanged. +-- [jooq ignore start] +DO $migration$ +DECLARE + evidence_function REGPROCEDURE := '"${serviceSchema}".enforce_published_world_start_location_evidence()'::REGPROCEDURE; + original_definition TEXT; + schema_anchor TEXT := $anchor$ OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1'$anchor$; + schema_replacement TEXT := $replacement$ OR (convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') + IS DISTINCT FROM 'account-draft-authorization-fence/v1' + AND convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') + IS DISTINCT FROM 'account-draft-authorization-fence/v2')$replacement$; +BEGIN + SELECT pg_get_functiondef(evidence_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, schema_anchor, ''))) + / length(schema_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V69 original Account schema guard'; + END IF; + original_definition := replace(original_definition, schema_anchor, schema_replacement); + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 2d5d79f22c..28fe3c30ae 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -51,6 +51,7 @@ import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -562,6 +563,7 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex }); var originalOrder = account.prepareOriginalDraftOrder(selectedCommit, NAMESPACE); var original = originalOrder.original(); + assertThat(original.schemaVersion()).isEqualTo(DraftAuthorizationFenceBinding.SCHEMA_V2); var accountAccess = account.preparedOriginalCreator(); var accountRepository = new AccountGameLogicIntakeAuthorizationRepository(accountAccess.sources().dsl); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java index 5695f44208..337d8c5828 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java @@ -37,7 +37,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; import tools.jackson.databind.ObjectMapper; -/** Physical V69-to-V70 upgrade proof using isolated, explicitly synthetic upstream evidence. */ +/** Physical V69-to-V71 upgrade proof using isolated, explicitly synthetic upstream evidence. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class SelectedInventoryProfileUpgradeIntegrationTest { @@ -61,6 +61,7 @@ void forwardUpgradePreservesRetainedV1OperationAndAdmitsOnlyPairedProfiles() thr var transactions = new DataSourceTransactionManager(dataSource); var transaction = new TransactionTemplate(transactions); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + Map originalMigrationChecksums = migrationChecksums(dsl); Version version = transaction.execute( @@ -108,6 +109,9 @@ void forwardUpgradePreservesRetainedV1OperationAndAdmitsOnlyPairedProfiles() thr flyway(dataSource, schema, null).migrate(); + Map upgradedMigrationChecksums = migrationChecksums(dsl); + assertThat(upgradedMigrationChecksums).containsAllEntriesOf(originalMigrationChecksums); + assertThat(upgradedMigrationChecksums).containsKeys("70", "71"); assertThat(readOperationBytes(dsl, historicalV1.workflowId())) .containsExactly(originalOperationBytes); var repository = new GameDesignPublicationOperationRepository(dsl); @@ -209,6 +213,16 @@ private static byte[] readOperationBytes(DSLContext dsl, String workflowId) { return row.get("request_bytes", byte[].class); } + private static Map migrationChecksums(DSLContext dsl) { + Map checksums = new java.util.HashMap<>(); + dsl.fetch("SELECT version, checksum FROM flyway_schema_history WHERE version IS NOT NULL") + .forEach( + row -> + checksums.put( + row.get("version", String.class), row.get("checksum", Integer.class))); + return checksums; + } + private static byte[] rebindInventory( GameDesignPublicationOperation operation, java.util.function.Consumer mutation) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java new file mode 100644 index 0000000000..4113f9a3ab --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java @@ -0,0 +1,195 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; + +class SelectedOwnerIntakeSourceExportTest { + private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST = id("33333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = id("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID OPERATION = id("66666666-6666-4666-8666-666666666666"); + private static final UUID FENCE = id("77777777-7777-4777-8777-777777777777"); + private static final UUID INTAKE = id("88888888-8888-4888-8888-888888888888"); + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final UUID GENESIS = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + @Test + void framesTheScopeAndAllSixFamiliesInFixedOrder() { + var selected = binding(COMMIT, "{}"); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected); + var sources = sources(selected, "0"); + var export = SelectedOwnerIntakeSourceExport.create(scope, sources); + + var expected = new ByteArrayOutputStream(); + frame(expected, SelectedOwnerIntakeSourceExport.DOMAIN); + frame(expected, scope.canonicalBytes()); + frame(expected, scope.digest()); + frameFamily(expected, "COMMAND", sources.command().canonicalBytes()); + frameFamily(expected, "REALM_POLICY", sources.policy().canonicalBytes()); + frameFamily(expected, "ASSET", sources.asset().canonicalBytes()); + frameFamily(expected, "GAMEPLAY_RULE", sources.gameplay().canonicalBytes()); + frameFamily(expected, "BRANDING", sources.branding().orElseThrow().canonicalBytes()); + frameFamily( + expected, "TEMPLATE_CONFIG", sources.templateConfig().orElseThrow().canonicalBytes()); + + assertThat(export.canonicalBytes()).isEqualTo(expected.toByteArray()); + assertThat(export.digest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(expected.toByteArray())); + assertThat(export.sources()).isSameAs(sources); + assertThat(export.scope()).isEqualTo(scope); + } + + @Test + void contentIsDeterministicAndCanonicalBytesAreDefensivelyExposed() { + var selected = binding(COMMIT, "{}"); + var first = + SelectedOwnerIntakeSourceExport.create( + scope(Owner.AUTOMATION_SCRIPTING, selected), sources(selected, "0")); + var replay = + SelectedOwnerIntakeSourceExport.create( + scope(Owner.AUTOMATION_SCRIPTING, selected), sources(selected, "0")); + byte[] exposed = first.canonicalBytes(); + exposed[0] ^= 0x7f; + + assertThat(first.canonicalBytes()).isEqualTo(replay.canonicalBytes()); + assertThat(first.digest()).isEqualTo(replay.digest()); + } + + @Test + void rejectsDifferentSelectedBindingAndChangedFamilyContent() { + var selected = binding(COMMIT, "{}"); + var sources = sources(selected, "0"); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceExport.create( + scope( + Owner.ENTITY_MANAGEMENT, + binding(id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), "{}")), + sources)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("COMMAND"); + + var original = + SelectedOwnerIntakeSourceExport.create(scope(Owner.ENTITY_MANAGEMENT, selected), sources); + var changed = + SelectedOwnerIntakeSourceExport.create( + scope(Owner.ENTITY_MANAGEMENT, selected), sources(selected, "1")); + assertThat(changed.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(changed.digest()).isNotEqualTo(original.digest()); + } + + @Test + void missingBrandingOrTemplateSourceIsNotAnEmptyFamily() { + var selected = binding(COMMIT, "{}"); + var complete = sources(selected, "0"); + var missingBranding = + new GameDesignSourceRepository.SynchronizedSources( + complete.command(), + complete.policy(), + complete.asset(), + complete.gameplay(), + Optional.empty(), + complete.templateConfig()); + var missingTemplate = + new GameDesignSourceRepository.SynchronizedSources( + complete.command(), + complete.policy(), + complete.asset(), + complete.gameplay(), + complete.branding(), + Optional.empty()); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceExport.create( + scope(Owner.ENTITY_MANAGEMENT, selected), missingBranding)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("branding"); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceExport.create( + scope(Owner.AUTOMATION_SCRIPTING, selected), missingTemplate)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("template-config"); + } + + @Test + void rejectsExportLargerThanEightMib() { + var selected = binding(COMMIT, "x".repeat(1_400_000)); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceExport.create( + scope(Owner.ENTITY_MANAGEMENT, selected), sources(selected, "0"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("8 MiB"); + } + + private static GameDesignSourceRepository.SynchronizedSources sources( + DraftCommitBinding binding, String commandEpoch) { + var command = + new CommandSnapshot(binding, commandEpoch, null, "sha256:" + "a".repeat(64), List.of()); + var policy = new RealmPolicySnapshot(binding, "0", List.of()); + var asset = new AssetSnapshot(binding, "0", null, GENESIS, List.of()); + var gameplay = new GameplayRuleSnapshot(binding, "0", null, GENESIS, List.of()); + var branding = new BrandingSourceSnapshot(binding, "0", null, GENESIS, List.of()); + var template = new TemplateConfigSourceSnapshot(binding, "0", null, GENESIS, List.of()); + return new GameDesignSourceRepository.SynchronizedSources( + command, policy, asset, gameplay, Optional.of(branding), Optional.of(template)); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + Owner owner, DraftCommitBinding selected) { + return new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, INTAKE, ACTOR, selected); + } + + private static DraftCommitBinding binding(UUID commitId, String payload) { + return DraftCommitBinding.create( + new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + REQUEST, + commitId, + "base-commit-0", + List.of(new RevisionPayload("0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static void frameFamily(ByteArrayOutputStream out, String family, byte[] bytes) { + frame(out, family); + frame(out, bytes); + frame(out, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionFixtureTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionFixtureTest.java new file mode 100644 index 0000000000..e2960e881b --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionFixtureTest.java @@ -0,0 +1,59 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInstanceExecutionFixtureTest { + private static final UUID TENANT_ID = UUID.fromString("41d2b16d-1fb7-4e74-9c54-7c647ee0c36a"); + private static final UUID ACTOR_ID = UUID.fromString("9e52a861-bcfd-4f27-a6d2-1782749c8989"); + private static final UUID TEMPLATE_OWNER_ID = + UUID.fromString("5265c943-44c6-4b34-a629-86f0575cf4bf"); + + @Test + void emittedBundleUsesCanonicalMillisecondsAndStrictDecoderStillRejectsNanoseconds() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + Instant originalExpiry = + Instant.now().truncatedTo(ChronoUnit.MILLIS).plusSeconds(86_400L).plusNanos(987_654L); + + byte[] bytes = + WorldCanonicalInstanceExecutionTestFixtures.authorityBundle( + tuple, ACTOR_ID, originalExpiry); + StartSessionAuthorityEvidenceBundle decoded = StartSessionAuthorityEvidenceBundle.decode(bytes); + + assertThat(decoded.expiresAt()).isEqualTo(Instant.ofEpochMilli(originalExpiry.toEpochMilli())); + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + + String canonicalExpiry = decoded.expiresAt().toString(); + String nanosecondExpiry = originalExpiry.toString(); + byte[] malformed = + new String(bytes, StandardCharsets.UTF_8) + .replace(canonicalExpiry, nanosecondExpiry) + .getBytes(StandardCharsets.UTF_8); + assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(malformed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Timestamp is malformed"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple() { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, TEMPLATE_OWNER_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "synthetic World execution fixture regression"); + return StartSessionPreAuthorizationReservationTuple.createHuman( + "world-fixture-canonical-timestamp", ACTOR_ID, action); + } +} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java index fd4418e3a1..1669e35fa1 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java @@ -64,7 +64,7 @@ static WorldCanonicalInstanceExecutionIdentity identity(Input input, Instant exp WorldCanonicalInstancePreparationRepository.inputJson(input)); } - private static byte[] authorityBundle( + static byte[] authorityBundle( StartSessionPreAuthorizationReservationTuple tuple, UUID actor, Instant expiresAt) { String tenantId = tuple.action().scope().tenantId().toString(); Instant now = Instant.now(); @@ -79,9 +79,9 @@ private static byte[] authorityBundle( "projectionStatus", "CURRENT", "evaluatedAt", - now.minusSeconds(30).toString(), + canonicalTimestamp(now.minusSeconds(30)), "expiresAt", - expiresAt.toString()); + canonicalTimestamp(expiresAt)); Map operation = Map.of( "issuanceOperationId", UUID.randomUUID().toString(), @@ -153,4 +153,8 @@ private static byte[] authorityBundle( "Could not encode synthetic World authority fixture", exception); } } + + private static String canonicalTimestamp(Instant instant) { + return Instant.ofEpochMilli(instant.toEpochMilli()).toString(); + } } From 2cb445617f584d25c805f5c08e9dde67fff4efc4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 10:20:42 +1300 Subject: [PATCH 064/129] Preserve frozen Account stages and durable StartSession capture --- .../account-service/api-contracts.md | 4 +- .../account-service/operations.md | 2 +- ...ame-authoring-publishing-and-activation.md | 10 +- .../session/AccountControlUiActorService.java | 244 +++++++++ .../AccountControlUiIssuanceRepository.java | 68 +++ ...untPublicationAuthorizationRepository.java | 4 +- .../AccountStartSessionAuthorityCapture.java | 316 +++++++++++ ...tartSessionAuthorityCaptureRepository.java | 499 +++++++++++++++++ ...t_jwt_signer_materialization_readback.sql} | 0 ...V101__account_jwt_jwks_prepublication.sql} | 0 ..._account_gameplay_delegation_issuance.sql} | 0 ...=> V103__account_jwt_readiness_probes.sql} | 0 ...> V104__account_auth_evidence_bundles.sql} | 0 ...ameplay_delegation_encrypted_response.sql} | 0 ...ccount_jwt_signer_promotion_lifecycle.sql} | 0 ..._jwt_readiness_single_delivery_claims.sql} | 0 ...ameplay_delegation_committed_issuance.sql} | 0 ...unt_jwt_validator_inventory_snapshots.sql} | 0 ...ccount_gameplay_token_identity_fences.sql} | 0 ...play_login_credential_request_binding.sql} | 0 ...ay_delegation_decimal_source_versions.sql} | 0 ...nt_auth_evidence_checkpoint_key_count.sql} | 0 ...unt_auth_evidence_shared_issuer_guard.sql} | 0 ...t_gameplay_commit_bundle_source_fence.sql} | 0 ...ameplay_authority_shared_issuer_guard.sql} | 0 ..._account_lifecycle_serving_operations.sql} | 0 ...t_gameplay_admission_lease_operations.sql} | 0 ...ount_admission_unknown_decision_abort.sql} | 0 ...admission_durable_commit_confirmation.sql} | 0 ...count_global_pending_admission_fences.sql} | 0 ...ccount_admission_original_ack_receipt.sql} | 0 ...account_jwt_readiness_per_pod_closure.sql} | 0 ...ss_version_aware_delivery_claim_guard.sql} | 0 ..._jwt_signer_promotion_receipt_binding.sql} | 0 ...__start_session_operator_authorization.sql | 142 +++++ ...V127__selected_inventory_empty_arrays.sql} | 0 ...count_start_session_authority_captures.sql | 253 +++++++++ ...ql => V74__account_global_role_source.sql} | 0 ...75__draft_commit_authorization_fences.sql} | 0 ...6__account_draft_required_owner_fence.sql} | 0 ...unt_password_reset_operation_receipts.sql} | 2 +- ...account_logout_all_operation_receipts.sql} | 2 +- ...79__account_security_state_operations.sql} | 0 ...__account_security_event_source_guard.sql} | 181 ++++++- ...nt_platform_restriction_birth_sources.sql} | 0 ...=> V82__creator_membership_provenance.sql} | 0 ...83__account_tenant_creation_bootstrap.sql} | 0 ...V84__individual_creator_party_sources.sql} | 0 ...ount_hosted_terms_acceptance_workflow.sql} | 0 ...ount_hosted_terms_environment_binding.sql} | 61 +++ ...ccount_control_ui_owner_source_guards.sql} | 106 +--- ...ogout_all_pending_draft_source_changes.sql | 295 +++++++++++ ...ord_reset_pending_draft_source_changes.sql | 381 +++++++++++++ ..._account_control_ui_committed_issuance.sql | 119 +++++ ...nt_selected_publication_authorization.sql} | 0 ..._account_publication_pre_freeze_order.sql} | 2 +- ...count_selected_publication_settlement.sql} | 4 +- ...94__selected_publication_inventory_v2.sql} | 0 ... V95__game_logic_intake_authorization.sql} | 0 ...game_logic_intake_terminal_settlement.sql} | 0 ..._logic_intake_source_read_reservation.sql} | 0 ...ount_hosted_terms_disclosure_handoffs.sql} | 6 + ...V99__account_jwt_signer_desired_state.sql} | 0 ...ommitOrderReadPostgresIntegrationTest.java | 4 +- ...orizationFencePostgresIntegrationTest.java | 11 +- ...alCreatorPartyPostgresIntegrationTest.java | 12 +- ...untHostedTermsPostgresIntegrationTest.java | 4 +- ...issionLeasePersistenceIntegrationTest.java | 154 +++--- ...issionWalBoundaryProofIntegrationTest.java | 7 +- .../PreRestrictionBirthAccountFixture.java | 20 +- ...iPositiveOwnerPostgresIntegrationTest.java | 183 ++++++- ...eAuthorizationPostgresIntegrationTest.java | 4 +- ...thorityCapturePostgresIntegrationTest.java | 124 +++++ .../AccountControlUiActorServiceTest.java | 501 ++++++++++++++++++ ...countStartSessionAuthorityCaptureTest.java | 139 +++++ .../StartSessionAuthorityEvidenceBundle.java | 12 +- ...RedeemedOperationProjectionClientTest.java | 28 +- ...artSessionAuthorityEvidenceBundleTest.java | 22 +- .../VersionPublishCommandServiceImpl.java | 58 +- ...licationExportPostgresIntegrationTest.java | 102 ++++ .../VersionPublishCommandServiceImplTest.java | 17 + ...onicalInstanceLifecycleReadRepository.java | 108 +++- ...nceAssociationPostgresIntegrationTest.java | 10 +- ...aphApplicationPostgresIntegrationTest.java | 74 ++- ...alInstanceLifecycleReadRepositoryTest.java | 61 +++ 85 files changed, 4090 insertions(+), 266 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapture.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java rename services/account-service/src/main/resources/db/migration/{V42__account_jwt_signer_materialization_readback.sql => V100__account_jwt_signer_materialization_readback.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V43__account_jwt_jwks_prepublication.sql => V101__account_jwt_jwks_prepublication.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V44__account_gameplay_delegation_issuance.sql => V102__account_gameplay_delegation_issuance.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V45__account_jwt_readiness_probes.sql => V103__account_jwt_readiness_probes.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V46__account_auth_evidence_bundles.sql => V104__account_auth_evidence_bundles.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V47__account_gameplay_delegation_encrypted_response.sql => V105__account_gameplay_delegation_encrypted_response.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V49__account_jwt_signer_promotion_lifecycle.sql => V106__account_jwt_signer_promotion_lifecycle.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V50__account_jwt_readiness_single_delivery_claims.sql => V107__account_jwt_readiness_single_delivery_claims.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V51__account_gameplay_delegation_committed_issuance.sql => V108__account_gameplay_delegation_committed_issuance.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V52__account_jwt_validator_inventory_snapshots.sql => V109__account_jwt_validator_inventory_snapshots.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V74__account_gameplay_token_identity_fences.sql => V110__account_gameplay_token_identity_fences.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V81__account_gameplay_login_credential_request_binding.sql => V111__account_gameplay_login_credential_request_binding.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V84__account_gameplay_delegation_decimal_source_versions.sql => V112__account_gameplay_delegation_decimal_source_versions.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V84.1__account_auth_evidence_checkpoint_key_count.sql => V113__account_auth_evidence_checkpoint_key_count.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V84.2__account_auth_evidence_shared_issuer_guard.sql => V114__account_auth_evidence_shared_issuer_guard.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V84.3__account_gameplay_commit_bundle_source_fence.sql => V115__account_gameplay_commit_bundle_source_fence.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V84.4__account_gameplay_authority_shared_issuer_guard.sql => V116__account_gameplay_authority_shared_issuer_guard.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V86__account_lifecycle_serving_operations.sql => V117__account_lifecycle_serving_operations.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V87__account_gameplay_admission_lease_operations.sql => V118__account_gameplay_admission_lease_operations.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V89__account_admission_unknown_decision_abort.sql => V119__account_admission_unknown_decision_abort.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V90__account_admission_durable_commit_confirmation.sql => V120__account_admission_durable_commit_confirmation.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V91__account_global_pending_admission_fences.sql => V121__account_global_pending_admission_fences.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V92__account_admission_original_ack_receipt.sql => V122__account_admission_original_ack_receipt.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V100__account_jwt_readiness_per_pod_closure.sql => V123__account_jwt_readiness_per_pod_closure.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V102__account_jwt_readiness_version_aware_delivery_claim_guard.sql => V124__account_jwt_readiness_version_aware_delivery_claim_guard.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V104__account_jwt_signer_promotion_receipt_binding.sql => V125__account_jwt_signer_promotion_receipt_binding.sql} (100%) create mode 100644 services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql rename services/account-service/src/main/resources/db/migration/{V110__selected_inventory_empty_arrays.sql => V127__selected_inventory_empty_arrays.sql} (100%) create mode 100644 services/account-service/src/main/resources/db/migration/V128__account_start_session_authority_captures.sql rename services/account-service/src/main/resources/db/migration/{V74.1__account_global_role_source.sql => V74__account_global_role_source.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V76__draft_commit_authorization_fences.sql => V75__draft_commit_authorization_fences.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V93__account_draft_required_owner_fence.sql => V76__account_draft_required_owner_fence.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V75__account_password_reset_operation_receipts.sql => V77__account_password_reset_operation_receipts.sql} (99%) rename services/account-service/src/main/resources/db/migration/{V77__account_logout_all_operation_receipts.sql => V78__account_logout_all_operation_receipts.sql} (99%) rename services/account-service/src/main/resources/db/migration/{V78__account_security_state_operations.sql => V79__account_security_state_operations.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V83__account_security_event_source_guard.sql => V80__account_security_event_source_guard.sql} (64%) rename services/account-service/src/main/resources/db/migration/{V88__account_platform_restriction_birth_sources.sql => V81__account_platform_restriction_birth_sources.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V98__creator_membership_provenance.sql => V82__creator_membership_provenance.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V94__account_tenant_creation_bootstrap.sql => V83__account_tenant_creation_bootstrap.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V95__individual_creator_party_sources.sql => V84__individual_creator_party_sources.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V96__account_hosted_terms_acceptance_workflow.sql => V85__account_hosted_terms_acceptance_workflow.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V97__account_hosted_terms_environment_binding.sql => V86__account_hosted_terms_environment_binding.sql} (82%) rename services/account-service/src/main/resources/db/migration/{V99__account_control_ui_owner_and_source_guards.sql => V87__account_control_ui_owner_source_guards.sql} (56%) create mode 100644 services/account-service/src/main/resources/db/migration/V88__account_logout_all_pending_draft_source_changes.sql create mode 100644 services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql create mode 100644 services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql rename services/account-service/src/main/resources/db/migration/{V103__account_selected_publication_authorization.sql => V91__account_selected_publication_authorization.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V106__account_publication_pre_freeze_order.sql => V92__account_publication_pre_freeze_order.sql} (72%) rename services/account-service/src/main/resources/db/migration/{V107__account_selected_publication_settlement.sql => V93__account_selected_publication_settlement.sql} (98%) rename services/account-service/src/main/resources/db/migration/{V108__selected_publication_inventory_v2.sql => V94__selected_publication_inventory_v2.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V109__game_logic_intake_authorization.sql => V95__game_logic_intake_authorization.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V111__game_logic_intake_terminal_settlement.sql => V96__game_logic_intake_terminal_settlement.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V112__game_logic_intake_source_read_reservation.sql => V97__game_logic_intake_source_read_reservation.sql} (100%) rename services/account-service/src/main/resources/db/migration/{V101__account_hosted_terms_disclosure_handoffs.sql => V98__account_hosted_terms_disclosure_handoffs.sql} (94%) rename services/account-service/src/main/resources/db/migration/{V41__account_jwt_signer_desired_state.sql => V99__account_jwt_signer_desired_state.sql} (100%) create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3c069e9582..5a6ccccd7e 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -58,13 +58,15 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status +The standalone StartSession capture primitive retains the complete Account source snapshot, independent issuance fence and its source version, original committed ControlUI identity, exact typed request, verified Logging workload and supplied reservation binding in one immutable owner record. Capture version and fence are separate owner allocations; the PostgreSQL transaction identity and database-observed capture timestamp remain exact readback evidence. Workload authentication does not prove the supplied reservation owner/fence. This primitive supplies neither an issuer nor permission: authenticated original-reservation readback, committed capture-before-private-cryptography, final currentness/retry composition and physical repository proof remain open in the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). The runtime paths remain denied. + This Account source-currentness and first-JOIN persistence prerequisite builds on the authority-storage and retention-safety stage. V40 adds owner-proven fresh issuer/Account source baselines and complete transactional source-event hooks; the owner-local first-JOIN producer/coordinator composes immutable membership, event, audit, and terminal operation evidence. These primitives do not authenticate callers, supply the cross-service target-through-commit gate, add a public route, or wire current LOGIN/public JOIN/Game Session text JOIN. Validation of the reconciled source-currentness stage remains pending; inherited storage proof is not proof of these additions. #2898 and #2848 retain their runtime and recovery gaps. Current explicit JOIN status: the local `/auth/bootstrap/join` controller and operation are implemented, but the exact Gateway path is blocked by its route guard and the route is absent from `publicOpenAPI`. Local policy-digest revalidation does not prove that the exact target remains valid through Account commit; the strict ADR 0025 commit gate remains incomplete. The canonical owner is [Runtime & Data](./runtime-and-data.md#membership-and-entitlement-authority), with the target contract in [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. -Bounded hosted Creator Party, terms-catalog, acceptance/currentness and environment-binding owner storage exists, but no registered hosted-terms API or complete creator-authorized commit path is enabled. The unregistered backend control-ui construction adds primary-authenticated issuance, exact protected recovery and a current-actor Draft ordering entry for one existing initial creator; neither that entry nor the standalone held-order read enables a public route or supplies an authenticated end-to-end commit by itself. `ReadHeldOriginalCommitOrder` accepts exact same-namespace World, and same-namespace Game Logic only when the canonical original binding's required-owner vector includes `GAME_LOGIC`; it reads the retained original bytes, order and pending settlement in an independent Account transaction and grants no order-creation or settlement authority. Deadline-qualified authorizations remain denied without physical commit enforcement. The [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md) records the implemented boundary and remaining proof. Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. +Bounded hosted Creator Party, terms-catalog, acceptance/currentness and environment-binding owner storage exists, but no registered hosted-terms API or complete creator-authorized commit path is enabled. The unregistered backend control-ui construction adds primary-authenticated issuance, exact protected recovery and a current-actor Draft ordering entry for one existing initial creator; neither that entry nor the standalone held-order read enables a public route or supplies an authenticated end-to-end commit by itself. Its Account-local committed-JTI currentness entry resolves the exact original account/tenant/token operation and checks its committed owner state, active registry, original signer and current source before the callback; UUID possession is only a lookup key. Both currentness entries compare the independent actual issuance fence with retained claims and recheck token validity after owner lock/read waits. This is an internal prerequisite, not a registered StartSession issuer or World participation producer; complete capture-reference and independent fence-source-version retention still require their owning producer. `ReadHeldOriginalCommitOrder` accepts exact same-namespace World, and same-namespace Game Logic only when the canonical original binding's required-owner vector includes `GAME_LOGIC`; it reads the retained original bytes, order and pending settlement in an independent Account transaction and grants no order-creation or settlement authority. Deadline-qualified authorizations remain denied without physical commit enforcement. The [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md) records the implemented boundary and remaining proof. Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. diff --git a/design/architecture/microservices/account-service/operations.md b/design/architecture/microservices/account-service/operations.md index f8d768e488..f3af6592d2 100644 --- a/design/architecture/microservices/account-service/operations.md +++ b/design/architecture/microservices/account-service/operations.md @@ -8,7 +8,7 @@ This document collects the Account Service operational behavior, readiness model - `liveness` is process-local only. - `readiness` is truthful local readiness for the currently implemented authentication/account slice and must fail when the service cannot safely satisfy new authentication traffic with its required local persistence/session infrastructure. - Logging, metrics, and tracing follow the standard [Logging & Monitoring](../../system-architecture-logging-monitoring.md) pipeline. -- Expired connect-scope cleanup requires PostgreSQL 16 or later because its deletion predicate uses `pg_input_is_valid`; local Docker Compose uses PostgreSQL 18. The shared test-image resource selects the digest-pinned PostgreSQL 18 baseline in [Testing Architecture's shared container image references](../../system-architecture-testing.md#shared-container-image-references), but Account's current `AccountPostgresIntegrationFixture` explicitly selects `postgres:16-alpine`. The admission original/receipt commit executors and V92 guards support PostgreSQL 16 only and deny other major versions; the shared image baseline does not widen that supported physical-COMMIT boundary. Fixture selection alone proves no Docker-backed execution. Keep the guarded delete predicate and do not add a pre-16 compatibility query. +- Expired connect-scope cleanup requires PostgreSQL 16 or later because its deletion predicate uses `pg_input_is_valid`; local Docker Compose uses PostgreSQL 18. The shared test-image resource selects the digest-pinned PostgreSQL 18 baseline in [Testing Architecture's shared container image references](../../system-architecture-testing.md#shared-container-image-references), but Account's current `AccountPostgresIntegrationFixture` explicitly selects `postgres:16-alpine`. The admission original/receipt commit executors and original-acknowledgement receipt guards support PostgreSQL 16 only and deny other major versions; the shared image baseline does not widen that supported physical-COMMIT boundary. Fixture selection alone proves no Docker-backed execution. Keep the guarded delete predicate and do not add a pre-16 compatibility query. ### V26 membership migration preflight 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 2ff4089831..6ce6237ec1 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 @@ -6,7 +6,15 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The distinct Entity/Automation preliminary source-read value now binds closed owner-specific schema and purpose, exact Account operation/fence/request/actor, unchanged complete selected Draft evidence and the derived same-namespace Account reader. Six focused integrity cases and all 478 Common unit cases pass locally; this value does not authenticate a reservation or finalize owner retention. The owner-local six-family selected-source export constructor and exact repository accessor now retain all original snapshot bytes, reject missing branding/template history and enforce the complete-content bound; five focused structural cases pass locally. This is not authenticated disclosure or an owner receipt. The authenticated selected-input transport, distinct Account reservation/finalization and source-writer/disclosure exclusion, actual owner census/retention and exact terminal settlement remain open. The unpublished Account migration assembly preserves Gameplay's exact `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` V74–V97 source, all 43 protected baseline migrations and the unique later SQL. Local Account checks pass. Gameplay's newly reserved V98 disclosure journal is already byte-identical to one retained later migration; its final published source must be incorporated once, with the intervening stages shifted coherently, before publishing this assembly. Physical execution of the resulting composed ordering remains required. World service-level authenticated recovery after ingress expiry remains open even though repository-only terminal recovery is defined; authenticated original Account participation and Game Session attempt/fence evidence remain prerequisites, not optional verifier checks. +The standalone Account StartSession capture primitive adds V128 immutable full-snapshot retention and independent positive signed-64 capture-version/fence allocators, while retaining the actual PostgreSQL transaction identity and database-observed millisecond capture time. The stored snapshot includes the original committed ControlUI operation/JTI/token hash/signer, complete source vector and checkpoints, authority tuple, membership evidence, independent issuance fence and its source version, canonical typed request and exact supplied Logging reservation identity. Its repository requires a current committed-actor callback and verified same-namespace Logging peer; those checks do not prove the upstream reservation claim. Three executed unit cases cover canonical bytes, defensive readback and independent fences. The database definitions cover allocator/immutability installation, the canonical tuple's separately derived digest, and capture insert/exact retry/final readback/conflicts through the real committed ControlUI owner fixture. That fixture explicitly stipulates the upstream Logging reservation; it is not genuine claim or end-to-end authorization proof. The PostgreSQL precision constraint remains active and is excluded narrowly from jOOQ's unsupported simulator rendering. Genuine original-reservation verification, committed capture-before-private-crypto issuer wiring, final issuer currentness/retry and physical repository execution remain open. The composed migration set now has 98 unique versions; no runtime path is activated. + +The corrected composed local gate passed all four service full checks, formatting, Checkstyle, SpotBugs, coverage, schema generation, links and Markdown: Common 479, Account 1,125, Game Design 539 and World 594 unit cases (2,737 total), with zero failures/errors/skips. Eight non-container integration cases executed; 606 integration cases skipped without Docker (240 Account, 148 Game Design, 218 World, including Redis definitions). These results do not replace corrected-head physical PostgreSQL execution. Flyway sanity passed 12 sets and 282 versioned files. Independent body-level preservation verified all 43 protected baseline and 25 frozen Gameplay migrations; the creator-party preservation test now isolates the actual V83-to-V84 upgrade. Parent review removed a nonexistent tuple-digest extraction that would have denied every genuine capture, retaining the separately derived snapshot/row digest binding. World paired graph/2 and graph/3 readback, phase-driven late-fence proof and Game Design safe commit diagnostics are included; the finalization root cause still needs executed physical diagnostics. + +The distinct Entity/Automation preliminary source-read value binds closed owner-specific schema and purpose, exact Account operation/fence/request/actor, unchanged complete selected Draft evidence and the derived same-namespace Account reader. The six-family selected-source export constructor and exact repository accessor retain the original snapshot bytes, reject missing branding/template history and enforce the complete-content bound. Their focused structural proof does not authenticate disclosure, prove owner census/retention or create an owner receipt. A genuine selected-source repository test expansion is prepared; its PostgreSQL execution remains required. The authenticated selected-input transport, distinct Account reservation/finalization and source-writer/disclosure exclusion, actual owner census/retention and exact terminal settlement remain open. + +The local Account migration assembly preserves all 43 protected baseline files and the exact frozen V74–V98 source from Gameplay `1f074314528fef08bc552cab973ccfd1989c7051`, including both V98 disclosure TRUNCATE guards. Its former V98–V122 stages shift byte-exactly to V99–V123; the duplicate later disclosure creation is removed and V124–V127 remain preserved. The resulting 97 versions are unique, but fresh/upgrade physical execution of this composed ordering remains required. The current-committed-JTI actor prerequisite has ten executed local unit cases; Account's 1,122 unit cases and Common's 479 unit cases passed during a broader run that stopped on a duplicate fixture variable in Game Design, subsequently corrected. The integrity decoder and dormant StartSession storage no longer equate the capture source fence with the independent issuance fence; the consumer still exact-compares the complete reference. Full durable capture-before-private-crypto and genuine issuer/participation wiring remain open. World service-level authenticated recovery after ingress expiry remains open: authenticated original Account participation and Game Session attempt/fence evidence remain prerequisites, not optional verifier checks. + +Exact source `0a8d434eb8bd82381bd814ec129defd6b1ac0103` [Validation run 37985441636](https://github.com/benhook1013/FireMUD/actions/runs/37985441636) completed red. Originating artifacts executed Account 254 cases with no failures, Game Design 151 with one failure and World 219 with 57 failures, with zero errors and skips. V69-to-V71 retained-profile upgrade passed; the genuine selected export progressed to finalization but its terminal error discarded the underlying commit cause. Bounded stage/JDBC-status diagnostics are prepared without logging exception messages or credentials. World failures comprise 35 frozen-graph readback rejections, 20 mismatched synthetic participant profiles, one stale late-fence fixture and one mapped preparation denial. The current World reader incorrectly assumes graph/2 despite the canonical closure writer producing graph/3; the corrected closed profile-paired reader and fixture proof are under validation. These corrections are not yet physical proof. The actual checkout `42781f8cd07e2316538bb6e425ab8f8899d1fe14` merges the source into `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded integration parent. All four Gameplay handoffs and activation remain open. Published `f5530b39c27d60299d4f00306b1b0c4ee9a4027e` [Validation run 37981606468](https://github.com/benhook1013/FireMUD/actions/runs/37981606468) completed red. By originating owner artifact, Account executed 254 cases without failures, Game Design executed 151 with one failure and World executed 218 with 60 failures; all have zero errors and skips. Repeated parameterized display names in Account are separate executions, and Account-package source-composition fixtures in the Game Design artifact are not reattributed to Account. The actual V69-to-V70 retained-profile migration case and genuine original GD+World application/settlement/recovery cases passed; several World operation races and retained-history cases passed too. Remaining World failures use sub-millisecond synthetic StartSession timestamps, rejected by the unchanged strict decoder; the corrected test-only emitter has one executed non-container regression. The genuine selected-export failure reaches the real release insertion: its original Account producer emits the canonical v2 required-owner frame, but Game Design V69's selector guard admits only v1. Forward V71 admits those two original schema tags without changing any other complete original Account/APPLIED/selector checks or rewriting retained evidence; its physical upgrade and corrected full export still require execution. CI checked out `e3cc7f09c59459a6dfed7b2ba8d9766327e791ac`, merging this source into `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the recorded `1a8eefe6824c20b8b07a6d6adadda2ad154476e0` integration parent. All four Gameplay handoffs and activation remain open. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java index 5296b902ac..c0f04f581c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -157,14 +157,258 @@ T withCurrent( if (!Arrays.equals(current.evidence(), stored.sources)) { throw denied(); } + requireCurrentSnapshot(stored, current); var committed = operations.requireCommitted(stored); if (!committed.tokenHash().equals(tokenHash)) { throw denied(); } + requireControlUiClaims( + AccountControlUiIssuanceRepository.object(stored.claims), + stored, + stored.accountId, + stored.tenantId, + stored.jti, + clock.instant()); return action.apply(new Current(stored, current)); }); } + /** + * Revalidates the actor from Account's original committed token row when the caller has only its + * token identity. A supplied UUID is only a lookup key; the retained signed issuance, active + * registry, original signer receipt, and current Account source must all agree before use. + */ + T withCurrentCommitted( + UUID accountId, + UUID selectedTenant, + UUID tokenJti, + CapturedEnvironmentBoundary environment, + Function action) { + outsideSql(); + requireNonnil(accountId, "accountId"); + requireNonnil(selectedTenant, "tenantId"); + requireNonnil(tokenJti, "control-ui token jti"); + Objects.requireNonNull(environment, "current Account environment is required"); + Objects.requireNonNull(action, "current Account action is required"); + + AccountControlUiIssuanceRepository.Stored original = + transaction.execute( + ignored -> operations.findCommittedByTokenJti(accountId, selectedTenant, tokenJti)); + if (original == null) { + throw denied(); + } + requireCommittedIdentity(original, accountId, selectedTenant, tokenJti); + + // Both external observations must complete outside the SQL owner transaction. The final + // transaction compares their exact values to the immutable Account issuance row. + byte[] exactRegistry = registry.readActive(original.tokenHash); + AccountPublicJwksCache.SourceIdentity currentPublicSource = publicSource.sourceIdentity(); + + return transaction.execute( + ignored -> { + var stored = operations.lockCommittedByTokenJti(original); + requireCommittedIdentity(stored, accountId, selectedTenant, tokenJti); + if (!sameCommittedIssuance(original, stored) + || !Arrays.equals(stored.activeRegistry, exactRegistry)) { + throw denied(); + } + var active = AccountControlUiIssuanceRepository.object(exactRegistry); + if (!stored.tokenHash.equals(active.get("tokenHash")) + || !stored.jti.toString().equals(active.get("jti")) + || !stored.operationId.toString().equals(active.get("operationId")) + || !stored.accountId.toString().equals(active.get("accountId")) + || !Long.toString(stored.expiryMillis() / 1000L) + .equals(numberText(active.get("exp")))) { + throw denied(); + } + + Map originalClaims = + AccountControlUiIssuanceRepository.object(stored.claims); + requireControlUiClaims( + originalClaims, stored, accountId, selectedTenant, tokenJti, clock.instant()); + requireSignerReceiptIdentity( + stored, currentPublicSource, String.valueOf(active.get("kid"))); + var originalSigner = signers.requireOriginal(stored.signerReceipt); + if (!originalSigner.kid().equals(active.get("kid")) + || !originalSigner.generation().equals(active.get("signerGeneration"))) { + throw denied(); + } + + var current = authority.capture(accountId, selectedTenant, environment); + requireCurrentSnapshot(stored, current); + var committed = operations.requireCommitted(stored); + if (!stored.tokenHash.equals(committed.tokenHash())) { + throw denied(); + } + // Recovery and source locks may wait. Recheck expiry after those waits, at the final + // owner-currentness boundary immediately before exposing the actor to its caller. + requireControlUiClaims( + AccountControlUiIssuanceRepository.object(stored.claims), + stored, + accountId, + selectedTenant, + tokenJti, + clock.instant()); + return action.apply(new Current(stored, current)); + }); + } + + private void requireCurrentSnapshot( + AccountControlUiIssuanceRepository.Stored stored, + AccountControlUiAuthority.Snapshot current) { + if (!stored.accountId.equals(current.actor()) + || !stored.tenantId.equals(current.tenant()) + || !Arrays.equals(current.evidence(), stored.sources)) { + throw denied(); + } + Map claims = AccountControlUiIssuanceRepository.object(stored.claims); + try { + ControlUiJwtProfileValidator.validateClaims(claims, 1); + } catch (RuntimeException malformed) { + throw denied(); + } + if (!Arrays.equals(stored.claims, AccountControlUiAuthority.canonical(claims)) + || !canonicalEquals(claims.get("authorityTuple"), current.authorityTuple()) + || !canonicalEquals(claims.get("membershipVersion"), current.membershipVersion()) + || !Long.toString(current.issuanceFence()) + .equals(numberText(claims.get("issuanceFence")))) { + throw denied(); + } + } + + private void requireCommittedIdentity( + AccountControlUiIssuanceRepository.Stored stored, + UUID accountId, + UUID tenantId, + UUID tokenJti) { + if (!"COMMITTED".equals(stored.status) + || !accountId.equals(stored.accountId) + || !tenantId.equals(stored.tenantId) + || !tokenJti.equals(stored.jti) + || stored.tokenHash == null + || stored.tokenHash.isBlank() + || stored.claims == null + || stored.sources == null + || stored.signerReceipt == null + || stored.activeRegistry == null) { + throw denied(); + } + } + + private static boolean sameCommittedIssuance( + AccountControlUiIssuanceRepository.Stored original, + AccountControlUiIssuanceRepository.Stored current) { + return Objects.equals(original.requestId, current.requestId) + && Objects.equals(original.operationId, current.operationId) + && Objects.equals(original.jti, current.jti) + && Objects.equals(original.accountId, current.accountId) + && Objects.equals(original.tenantId, current.tenantId) + && Objects.equals(original.status, current.status) + && Objects.equals(original.tokenHash, current.tokenHash) + && Arrays.equals(original.claims, current.claims) + && Arrays.equals(original.sources, current.sources) + && Arrays.equals(original.bundle, current.bundle) + && Arrays.equals(original.signerReceipt, current.signerReceipt) + && Arrays.equals(original.pendingRegistry, current.pendingRegistry) + && Arrays.equals(original.activeRegistry, current.activeRegistry) + && Objects.equals(original.issuedAt, current.issuedAt) + && Objects.equals(original.expiresAt, current.expiresAt) + && Objects.equals(original.recoveryExpiry, current.recoveryExpiry); + } + + private void requireControlUiClaims( + Map claims, + AccountControlUiIssuanceRepository.Stored stored, + UUID accountId, + UUID tenantId, + UUID tokenJti, + java.time.Instant now) { + try { + ControlUiJwtProfileValidator.validateClaims(claims, 1); + } catch (RuntimeException malformed) { + throw denied(); + } + long issuedAt = epochSecond(claims.get("iat")); + long notBefore = epochSecond(claims.get("nbf")); + long expiresAt = epochSecond(claims.get("exp")); + java.time.Instant storedIssuedAt = stored.issuedAt; + java.time.Instant storedExpiresAt = stored.expiresAt; + java.time.Instant notBeforeInstant; + java.time.Instant expiresAtInstant; + try { + notBeforeInstant = java.time.Instant.ofEpochSecond(notBefore); + expiresAtInstant = java.time.Instant.ofEpochSecond(expiresAt); + } catch (RuntimeException outOfRange) { + throw denied(); + } + if (!Arrays.equals(stored.claims, AccountControlUiAuthority.canonical(claims)) + || !accountId.toString().equals(claims.get("accountId")) + || !accountId.toString().equals(claims.get("sub")) + || !tokenJti.toString().equals(claims.get("jti")) + || claims.containsKey("globalRoles") + || !Map.of(tenantId.toString(), List.of("tenantAdmin")).equals(claims.get("scopedRoles")) + || !"1".equals(numberText(claims.get("tokenGeneration"))) + || issuedAt != notBefore + || issuedAt != storedIssuedAt.getEpochSecond() + || expiresAt != storedExpiresAt.getEpochSecond() + || expiresAt <= issuedAt + || expiresAt - issuedAt > 300 + || now.isBefore(notBeforeInstant) + || !now.isBefore(expiresAtInstant)) { + throw denied(); + } + } + + private void requireSignerReceiptIdentity( + AccountControlUiIssuanceRepository.Stored stored, + AccountPublicJwksCache.SourceIdentity pin, + String keyId) { + var receipt = AccountControlUiIssuanceRepository.object(stored.signerReceipt); + if (!keyId.equals(receipt.get("kid")) + || !pin.environmentId().equals(receipt.get("environmentId")) + || !pin.clusterId().equals(receipt.get("clusterId")) + || !pin.clusterIncarnationUid().equals(receipt.get("clusterIncarnationUid")) + || !pin.namespace().equals(receipt.get("namespace")) + || !pin.namespaceUid().equals(receipt.get("namespaceUid")) + || !pin.configMapUid().equals(receipt.get("publicConfigMapUid")) + || !pin.bindingRevision().equals(receipt.get("apiConfigRevision"))) { + throw denied(); + } + } + + private static boolean canonicalEquals(Object first, Object second) { + if (first == null || second == null) { + return first == second; + } + return Arrays.equals( + AccountControlUiAuthority.canonical(first), AccountControlUiAuthority.canonical(second)); + } + + private static String numberText(Object value) { + if (!(value instanceof Number number)) { + throw denied(); + } + String text = number.toString(); + if (!text.matches("0|[1-9][0-9]{0,18}")) { + throw denied(); + } + return text; + } + + private static long epochSecond(Object value) { + try { + return Long.parseLong(numberText(value)); + } catch (NumberFormatException malformed) { + throw denied(); + } + } + + private static void requireNonnil(UUID value, String name) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalStateException("Exact committed control-ui " + name + " required"); + } + } + /** Production asymmetric/profile verification, also used before any candidate is persisted. */ SignedObservation verifySigned(String compactJwt) { outsideSql(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java index e8c7c2a20e..7ca8845563 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java @@ -48,6 +48,74 @@ Stored findToken(String tokenHash) { return row == null ? null : new Stored(row); } + /** Finds the one committed original control-ui issuance for an exact actor and token identity. */ + Stored findCommittedByTokenJti(UUID accountId, UUID tenantId, UUID tokenJti) { + requireTransaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE account_uuid = ? AND tenant_uuid = ? AND token_jti = ?" + + " AND status = 'COMMITTED'", + accountId, + tenantId, + tokenJti); + if (row == null) { + return null; + } + Stored stored = new Stored(row); + if (!accountId.equals(stored.accountId) + || !tenantId.equals(stored.tenantId) + || !tokenJti.equals(stored.jti) + || !"COMMITTED".equals(stored.status)) { + throw denied(); + } + return stored; + } + + /** Locks and exact-compares the original committed operation after external evidence reads. */ + Stored lockCommittedByTokenJti(Stored original) { + requireTransaction(); + Objects.requireNonNull(original, "original committed control-ui issuance is required"); + Record row = + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE operation_id = ? AND request_id = ? FOR UPDATE", + original.operationId, + original.requestId); + if (row == null) { + throw denied(); + } + Stored current = new Stored(row); + if (!sameCommittedOperation(original, current)) { + throw denied(); + } + return current; + } + + private static boolean sameCommittedOperation(Stored original, Stored current) { + return "COMMITTED".equals(original.status) + && "COMMITTED".equals(current.status) + && Objects.equals(original.requestId, current.requestId) + && Objects.equals(original.operationId, current.operationId) + && Objects.equals(original.jti, current.jti) + && Objects.equals(original.accountId, current.accountId) + && Objects.equals(original.tenantId, current.tenantId) + && Objects.equals(original.caller, current.caller) + && Objects.equals(original.callerContextId, current.callerContextId) + && Objects.equals(original.requestMacKeyId, current.requestMacKeyId) + && Objects.equals(original.requestDigest, current.requestDigest) + && Objects.equals(original.tokenHash, current.tokenHash) + && Arrays.equals(original.claims, current.claims) + && Arrays.equals(original.sources, current.sources) + && Arrays.equals(original.bundle, current.bundle) + && Arrays.equals(original.signerReceipt, current.signerReceipt) + && Arrays.equals(original.pendingRegistry, current.pendingRegistry) + && Arrays.equals(original.activeRegistry, current.activeRegistry) + && Objects.equals(original.issuedAt, current.issuedAt) + && Objects.equals(original.expiresAt, current.expiresAt) + && Objects.equals(original.recoveryExpiry, current.recoveryExpiry); + } + Stored prepare( UUID requestId, String caller, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java index f583c222a5..148de988bc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java @@ -308,7 +308,9 @@ private void requireExact( } } - /** Historical V103 World evidence remains immutable and is checked when a row contains it. */ + /** + * Historical pre-freeze World evidence remains immutable and is checked when a row contains it. + */ private static void validateRetainedWorldIfPresent( Record row, AccountPublicationAuthorizationBinding binding) { byte[] worldEvidence = row == null ? null : row.get("world_evidence", byte[].class); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapture.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapture.java new file mode 100644 index 0000000000..55037841b9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapture.java @@ -0,0 +1,316 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.Objects; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Immutable full Account source capture retained before StartSession private cryptography. */ +public final class AccountStartSessionAuthorityCapture { + public static final String SCHEMA = "account-start-session-authority-capture/v1"; + public static final int MAX_CAPTURE_BYTES = 256 * 1024; + public static final int MAX_SNAPSHOT_BYTES = 240 * 1024; + + private static final Pattern POSITIVE_U64 = Pattern.compile("[1-9][0-9]{0,19}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final DateTimeFormatter CAPTURED_AT_FORMAT = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final String controlPlaneRequestId; + private final long sourceVersion; + private final long sourceFence; + private final String linearization; + private final String capturedAt; + private final byte[] snapshotBytes; + private final String snapshotSha256; + private final byte[] canonicalBytes; + private final String canonicalSha256; + + private AccountStartSessionAuthorityCapture( + String controlPlaneRequestId, + long sourceVersion, + long sourceFence, + String linearization, + String capturedAt, + byte[] snapshotBytes, + String snapshotSha256, + byte[] canonicalBytes, + String canonicalSha256) { + this.controlPlaneRequestId = + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + this.sourceVersion = positive(sourceVersion, "capture sourceVersion"); + this.sourceFence = positive(sourceFence, "capture sourceFence"); + this.linearization = requireU64(linearization, "capture linearization"); + this.capturedAt = requireCapturedAt(capturedAt); + this.snapshotBytes = bounded(snapshotBytes, MAX_SNAPSHOT_BYTES, "source snapshot"); + this.snapshotSha256 = requireDigest(snapshotSha256, "source snapshot SHA-256"); + this.canonicalBytes = bounded(canonicalBytes, MAX_CAPTURE_BYTES, "capture reference"); + this.canonicalSha256 = requireDigest(canonicalSha256, "capture SHA-256"); + if (!this.snapshotSha256.equals(sha256(this.snapshotBytes)) + || !this.canonicalSha256.equals(sha256(this.canonicalBytes))) { + throw invalid("Capture bytes do not match their retained digests"); + } + requireCanonicalJson(this.snapshotBytes, "source snapshot"); + requireCanonicalJson(this.canonicalBytes, "capture reference"); + var reference = bundleReference(); + requireReferenceEnvelope( + this.canonicalBytes, + this.controlPlaneRequestId, + this.capturedAt, + reference, + this.snapshotSha256); + } + + static AccountStartSessionAuthorityCapture create( + String controlPlaneRequestId, + long sourceVersion, + long sourceFence, + String linearization, + String capturedAt, + byte[] snapshotBytes) { + String snapshotDigest = sha256(snapshotBytes); + BundleReference reference = + new BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + Long.toString(sourceVersion), + Long.toString(sourceFence), + linearization); + byte[] referenceBytes = + AccountControlUiAuthority.canonical( + java.util.Map.of( + "schema", SCHEMA, + "controlPlaneRequestId", controlPlaneRequestId, + "capturedAt", capturedAt, + "bundleReference", + java.util.Map.of( + "bundleVersion", reference.bundleVersion(), + "sourceVersion", reference.sourceVersion(), + "sourceFence", reference.sourceFence(), + "linearization", reference.linearization()), + "snapshotSha256", snapshotDigest)); + return new AccountStartSessionAuthorityCapture( + controlPlaneRequestId, + sourceVersion, + sourceFence, + linearization, + capturedAt, + snapshotBytes, + snapshotDigest, + referenceBytes, + sha256(referenceBytes)); + } + + static AccountStartSessionAuthorityCapture fromStorage( + String controlPlaneRequestId, + Long sourceVersion, + Long sourceFence, + String linearization, + String capturedAt, + byte[] snapshotBytes, + String snapshotSha256, + byte[] canonicalBytes, + String canonicalSha256) { + if (sourceVersion == null || sourceFence == null) { + throw invalid("Stored capture version or fence is absent"); + } + return new AccountStartSessionAuthorityCapture( + controlPlaneRequestId, + sourceVersion, + sourceFence, + linearization, + capturedAt, + snapshotBytes, + snapshotSha256, + canonicalBytes, + canonicalSha256); + } + + public String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + public long sourceVersion() { + return sourceVersion; + } + + public long sourceFence() { + return sourceFence; + } + + public String linearization() { + return linearization; + } + + public String capturedAt() { + return capturedAt; + } + + public BundleReference bundleReference() { + return new BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + Long.toString(sourceVersion), + Long.toString(sourceFence), + linearization); + } + + public byte[] snapshotBytes() { + return snapshotBytes.clone(); + } + + public String snapshotSha256() { + return snapshotSha256; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String canonicalSha256() { + return canonicalSha256; + } + + boolean sameSnapshot(AccountStartSessionAuthorityCapture other) { + return other != null + && controlPlaneRequestId.equals(other.controlPlaneRequestId) + && MessageDigest.isEqual(snapshotBytes, other.snapshotBytes) + && snapshotSha256.equals(other.snapshotSha256); + } + + boolean sameStoredValue(AccountStartSessionAuthorityCapture other) { + return sameSnapshot(other) + && sourceVersion == other.sourceVersion + && sourceFence == other.sourceFence + && linearization.equals(other.linearization) + && capturedAt.equals(other.capturedAt) + && MessageDigest.isEqual(canonicalBytes, other.canonicalBytes) + && canonicalSha256.equals(other.canonicalSha256); + } + + private static void requireReferenceEnvelope( + byte[] bytes, + String requestId, + String capturedAt, + BundleReference reference, + String snapshotSha256) { + try { + String text = new String(bytes, StandardCharsets.UTF_8); + Object value = JSON.readValue(text, Object.class); + if (!(value instanceof java.util.Map root) + || !root.keySet() + .equals( + java.util.Set.of( + "schema", + "controlPlaneRequestId", + "capturedAt", + "bundleReference", + "snapshotSha256")) + || !SCHEMA.equals(root.get("schema")) + || !requestId.equals(root.get("controlPlaneRequestId")) + || !capturedAt.equals(root.get("capturedAt")) + || !snapshotSha256.equals(root.get("snapshotSha256")) + || !(root.get("bundleReference") instanceof java.util.Map ref) + || !ref.keySet() + .equals( + java.util.Set.of( + "bundleVersion", "sourceVersion", "sourceFence", "linearization")) + || !reference.bundleVersion().equals(ref.get("bundleVersion")) + || !reference.sourceVersion().equals(ref.get("sourceVersion")) + || !reference.sourceFence().equals(ref.get("sourceFence")) + || !reference.linearization().equals(ref.get("linearization"))) { + throw invalid("Capture reference does not bind the full source snapshot"); + } + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException expected) throw expected; + throw invalid("Capture reference is malformed"); + } + } + + private static void requireCanonicalJson(byte[] bytes, String name) { + try { + String original = new String(bytes, StandardCharsets.UTF_8); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(original))) { + throw invalid(name + " is not canonical JSON"); + } + JSON.readValue(original, Object.class); + } catch (java.io.IOException | RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException expected) throw expected; + throw invalid(name + " is malformed"); + } + } + + private static byte[] bounded(byte[] value, int maximum, String field) { + Objects.requireNonNull(value, field + " bytes are required"); + if (value.length == 0 || value.length > maximum) { + throw invalid(field + " bytes are absent or over the supported bound"); + } + return value.clone(); + } + + private static long positive(long value, String field) { + if (value <= 0L) throw invalid(field + " must be positive"); + return value; + } + + private static String requireU64(String value, String field) { + if (value == null + || !POSITIVE_U64.matcher(value).matches() + || new java.math.BigInteger(value) + .compareTo( + java.math.BigInteger.ONE.shiftLeft(64).subtract(java.math.BigInteger.ONE)) + > 0) { + throw invalid(field + " is malformed"); + } + return value; + } + + private static String requireDigest(String value, String field) { + if (value == null || !SHA256.matcher(value).matches()) throw invalid(field + " is malformed"); + return value; + } + + private static String requireCapturedAt(String value) { + if (value == null) throw invalid("Database capture timestamp is absent"); + try { + Instant parsed = Instant.parse(value); + String canonical = CAPTURED_AT_FORMAT.format(parsed); + if (!canonical.equals(value) || parsed.getNano() % 1_000_000 != 0) { + throw invalid("Database capture timestamp must use canonical millisecond precision"); + } + return canonical; + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException expected) throw expected; + throw invalid("Database capture timestamp is malformed"); + } + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java new file mode 100644 index 0000000000..e1611254f4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java @@ -0,0 +1,499 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.Snapshot; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Account-local immutable capture of the complete current ControlUI source for StartSession. + * + *

This repository has no transport or crypto responsibilities. Call it only inside the callback + * of AccountControlUiActorService.withCurrent or withCurrentCommitted, before creating or + * fingerprinting the operator reference or encrypting its response. A capture is non-authorizing: + * the actor must be current again when the issuer locks it for finalization or redemption. + */ +public final class AccountStartSessionAuthorityCaptureRepository { + private static final String TABLE = "account_start_session_authority_captures"; + private static final String SOURCE_VERSION_ALLOCATOR = + "account_start_session_capture_source_version_allocator"; + private static final String SOURCE_FENCE_ALLOCATOR = + "account_start_session_capture_source_fence_allocator"; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern LOGGING_WORKLOAD = + Pattern.compile( + "^spiffe://firemud/ns/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)/sa/logging-admin-service$"); + + private final DSLContext dsl; + + public AccountStartSessionAuthorityCaptureRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Persists the current source snapshot before private issuance work, or returns the exact + * original capture when every source and request binding is unchanged. + */ + public AccountStartSessionAuthorityCapture prepareOrReadExact( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence) { + requireOwnerTransaction(); + Objects.requireNonNull(current, "current committed ControlUI actor is required"); + RequestSnapshot candidate = + requestSnapshot( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence); + + Record prior = lockByRequestId(candidate.requestId()); + if (prior != null) { + AccountStartSessionAuthorityCapture stored = decode(prior); + requireSameRequestAndSnapshot(candidate, stored, prior); + return stored; + } + + Allocation allocation = allocate(candidate.requestId()); + AccountStartSessionAuthorityCapture proposed = + AccountStartSessionAuthorityCapture.create( + candidate.requestId(), + allocation.sourceVersion(), + allocation.sourceFence(), + allocation.linearization(), + allocation.capturedAt(), + candidate.snapshotBytes()); + int inserted = insert(candidate, proposed); + Record row = lockByRequestId(candidate.requestId()); + if (row == null) throw unavailable(); + AccountStartSessionAuthorityCapture stored = decode(row); + requireSameRequestAndSnapshot(candidate, stored, row); + if (inserted == 1 && !proposed.sameStoredValue(stored)) { + throw unavailable(); + } + return stored; + } + + /** Locks the immutable original capture and requires the exact current source and tuple again. */ + public AccountStartSessionAuthorityCapture lockExactCurrent( + AccountStartSessionAuthorityCapture expected, + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence) { + requireOwnerTransaction(); + Objects.requireNonNull(expected, "original Account source capture is required"); + Objects.requireNonNull(current, "current committed ControlUI actor is required"); + RequestSnapshot observed = + requestSnapshot( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence); + Record row = lockByRequestId(expected.controlPlaneRequestId()); + if (row == null) throw unavailable(); + AccountStartSessionAuthorityCapture stored = decode(row); + requireSameRequestAndSnapshot(observed, stored, row); + if (!expected.sameStoredValue(stored)) throw unavailable(); + return stored; + } + + private int insert(RequestSnapshot request, AccountStartSessionAuthorityCapture capture) { + byte[] tupleBytes = request.tupleBytes(); + byte[] snapshotBytes = capture.snapshotBytes(); + byte[] captureBytes = capture.canonicalBytes(); + return dsl.execute( + "INSERT INTO " + + TABLE + + " (control_plane_request_id, account_uuid, tenant_uuid, target_owner, " + + "logging_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "pre_authorization_tuple, mutation_digest, control_ui_operation_id, " + + "control_ui_token_jti, control_ui_token_hash, control_ui_signer_receipt_sha256, " + + "issuance_fence, issuance_fence_source_version, captured_at, snapshot_sha256, " + + "canonical_snapshot_bytes, source_version, source_fence, linearization, " + + "canonical_sha256, canonical_capture_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (control_plane_request_id) DO NOTHING", + request.requestId(), + request.accountId(), + request.tenantId(), + request.targetOwner(), + request.loggingWorkloadUri(), + request.reservationOwnerId(), + request.reservationClaimFence(), + tupleBytes, + request.mutationDigest(), + request.controlUiOperationId(), + request.controlUiTokenJti(), + request.controlUiTokenHash(), + request.controlUiSignerReceiptSha256(), + request.issuanceFence(), + request.issuanceFenceSourceVersion(), + capture.capturedAt(), + capture.snapshotSha256(), + snapshotBytes, + capture.sourceVersion(), + capture.sourceFence(), + capture.linearization(), + capture.canonicalSha256(), + captureBytes); + } + + private Allocation allocate(String requestId) { + Record sourceVersion = + dsl.fetchOne( + "UPDATE " + + SOURCE_VERSION_ALLOCATOR + + " SET last_source_version = last_source_version + 1, " + + "last_control_plane_request_id = ?, " + + "last_transaction_id = pg_current_xact_id()::text " + + "WHERE allocator_id = TRUE AND last_source_version < 9223372036854775807 " + + "RETURNING last_source_version, last_control_plane_request_id, last_transaction_id", + requestId); + Record sourceFence = + dsl.fetchOne( + "UPDATE " + + SOURCE_FENCE_ALLOCATOR + + " SET last_source_fence = last_source_fence + 1, " + + "last_control_plane_request_id = ?, " + + "last_transaction_id = pg_current_xact_id()::text " + + "WHERE allocator_id = TRUE AND last_source_fence < 9223372036854775807 " + + "RETURNING last_source_fence, last_control_plane_request_id, last_transaction_id", + requestId); + Record observedAt = + dsl.fetchOne( + "SELECT to_char(date_trunc('milliseconds', clock_timestamp()) AT TIME ZONE 'UTC', " + + "'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"') AS captured_at"); + if (sourceVersion == null || sourceFence == null || observedAt == null) throw unavailable(); + String versionTransaction = sourceVersion.get("last_transaction_id", String.class); + String fenceTransaction = sourceFence.get("last_transaction_id", String.class); + if (!requestId.equals(sourceVersion.get("last_control_plane_request_id", String.class)) + || !requestId.equals(sourceFence.get("last_control_plane_request_id", String.class)) + || versionTransaction == null + || !versionTransaction.equals(fenceTransaction)) { + throw unavailable(); + } + Long version = sourceVersion.get("last_source_version", Long.class); + Long fence = sourceFence.get("last_source_fence", Long.class); + if (version == null || version <= 0L || fence == null || fence <= 0L) throw unavailable(); + String capturedAt = observedAt.get("captured_at", String.class); + if (capturedAt == null) throw unavailable(); + return new Allocation(version, fence, versionTransaction, capturedAt); + } + + private Record lockByRequestId(String requestId) { + return dsl.fetchOne( + "SELECT control_plane_request_id, account_uuid, tenant_uuid, target_owner, " + + "logging_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "pre_authorization_tuple, mutation_digest, control_ui_operation_id, " + + "control_ui_token_jti, control_ui_token_hash, control_ui_signer_receipt_sha256, " + + "issuance_fence, issuance_fence_source_version, " + + "to_char(captured_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.MS\"Z\"') AS captured_at, snapshot_sha256, " + + "canonical_snapshot_bytes, source_version, source_fence, linearization, " + + "canonical_sha256, canonical_capture_bytes FROM " + + TABLE + + " WHERE control_plane_request_id = ? FOR UPDATE", + requestId); + } + + private AccountStartSessionAuthorityCapture decode(Record row) { + try { + String requestId = row.get("control_plane_request_id", String.class); + Long version = row.get("source_version", Long.class); + Long fence = row.get("source_fence", Long.class); + String linearization = row.get("linearization", String.class); + byte[] snapshot = row.get("canonical_snapshot_bytes", byte[].class); + String snapshotDigest = row.get("snapshot_sha256", String.class); + byte[] captureBytes = row.get("canonical_capture_bytes", byte[].class); + String captureDigest = row.get("canonical_sha256", String.class); + var capture = + AccountStartSessionAuthorityCapture.fromStorage( + requestId, + version, + fence, + linearization, + row.get("captured_at", String.class), + snapshot, + snapshotDigest, + captureBytes, + captureDigest); + requireStoredColumnsMatchPayload(row, capture); + return capture; + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static void requireStoredColumnsMatchPayload( + Record row, AccountStartSessionAuthorityCapture capture) { + Map snapshot = parseObject(capture.snapshotBytes()); + Map reference = parseObject(capture.canonicalBytes()); + Map bundleReference = (Map) reference.get("bundleReference"); + if (!capture.controlPlaneRequestId().equals(row.get("control_plane_request_id", String.class)) + || !Long.toString(capture.sourceVersion()).equals(bundleReference.get("sourceVersion")) + || !Long.toString(capture.sourceFence()).equals(bundleReference.get("sourceFence")) + || !capture.linearization().equals(bundleReference.get("linearization")) + || !capture.capturedAt().equals(reference.get("capturedAt")) + || !capture.capturedAt().equals(row.get("captured_at", String.class)) + || !capture.snapshotSha256().equals(row.get("snapshot_sha256", String.class)) + || !Objects.equals(snapshot.get("accountId"), uuid(row, "account_uuid")) + || !Objects.equals(snapshot.get("tenantId"), uuid(row, "tenant_uuid")) + || !Objects.equals(snapshot.get("targetOwner"), row.get("target_owner", String.class)) + || !Objects.equals( + snapshot.get("loggingWorkloadUri"), row.get("logging_workload_uri", String.class)) + || !Objects.equals(snapshot.get("reservationOwnerId"), uuid(row, "reservation_owner_id")) + || !Objects.equals( + snapshot.get("reservationClaimFence"), + Long.toString(number(row, "reservation_claim_fence"))) + || !Objects.equals(snapshot.get("mutationDigest"), row.get("mutation_digest", String.class)) + || !Objects.equals( + snapshot.get("controlUiOperationId"), uuid(row, "control_ui_operation_id")) + || !Objects.equals(snapshot.get("controlUiTokenJti"), uuid(row, "control_ui_token_jti")) + || !Objects.equals( + snapshot.get("controlUiTokenHash"), row.get("control_ui_token_hash", String.class)) + || !Objects.equals( + snapshot.get("controlUiSignerReceiptSha256"), + row.get("control_ui_signer_receipt_sha256", String.class)) + || !Objects.equals( + snapshot.get("issuanceFence"), Long.toString(number(row, "issuance_fence"))) + || !Objects.equals( + snapshot.get("issuanceFenceSourceVersion"), + Long.toString(number(row, "issuance_fence_source_version")))) { + throw unavailable(); + } + } + + private static RequestSnapshot requestSnapshot( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence) { + Objects.requireNonNull(tuple, "exact typed StartSession tuple is required"); + Objects.requireNonNull(current.stored(), "original committed ControlUI issuance is required"); + Snapshot source = + Objects.requireNonNull(current.source(), "current Account snapshot is required"); + var stored = current.stored(); + byte[] tupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + if (!tuple.actor().accountId().equals(stored.accountId) + || !tuple.actor().accountId().equals(source.actor()) + || !tuple.action().scope().tenantId().equals(stored.tenantId) + || !tuple.action().scope().tenantId().equals(source.tenant()) + || !"game-session-service".equals(tuple.targetOwner()) + || !"COMMITTED".equals(stored.status) + || !canonicalTuple(tupleBytes, tuple) + || !canonicalLoggingWorkload(loggingWorkloadUri, tuple.action().scope().targetNamespace()) + || reservationOwnerId == null + || reservationOwnerId.equals(new UUID(0L, 0L)) + || reservationClaimFence <= 0L + || stored.operationId == null + || stored.jti == null + || stored.tokenHash == null + || !SHA256.matcher(stored.tokenHash).matches() + || stored.signerReceipt == null + || stored.signerReceipt.length == 0 + || source.issuanceFence() <= 0L + || source.issuanceFenceSourceVersion() <= 0L + || source.evidence() == null + || source.evidence().length == 0 + || source.sources() == null + || source.sources().isEmpty() + || source.outboxCheckpoints() == null) { + throw unavailable(); + } + byte[] signerReceipt = stored.signerReceipt.clone(); + Map snapshot = new LinkedHashMap<>(); + snapshot.put("schema", "account-start-session-authority-snapshot/v1"); + snapshot.put("controlPlaneRequestId", tuple.controlPlaneRequestId()); + snapshot.put("preAuthorizationTuple", Base64.getEncoder().encodeToString(tupleBytes)); + snapshot.put("mutationDigest", tuple.mutationDigest()); + snapshot.put("accountId", stored.accountId.toString()); + snapshot.put("tenantId", stored.tenantId.toString()); + snapshot.put("targetOwner", tuple.targetOwner()); + snapshot.put("loggingWorkloadUri", loggingWorkloadUri); + snapshot.put("reservationOwnerId", reservationOwnerId.toString()); + snapshot.put("reservationClaimFence", Long.toString(reservationClaimFence)); + snapshot.put("controlUiOperationId", stored.operationId.toString()); + snapshot.put("controlUiTokenJti", stored.jti.toString()); + snapshot.put("controlUiTokenHash", stored.tokenHash); + snapshot.put("controlUiSignerReceipt", Base64.getEncoder().encodeToString(signerReceipt)); + snapshot.put("controlUiSignerReceiptSha256", sha256(signerReceipt)); + snapshot.put("sourceVectorEvidence", Base64.getEncoder().encodeToString(source.evidence())); + List sourceVector = new ArrayList<>(); + for (SourceEvidence evidence : source.sources()) { + if (evidence == null || evidence.canonicalBytes().length == 0) throw unavailable(); + sourceVector.add(Base64.getEncoder().encodeToString(evidence.canonicalBytes())); + } + snapshot.put("sourceVector", List.copyOf(sourceVector)); + snapshot.put("outboxCheckpoints", source.outboxCheckpoints()); + snapshot.put("authorityTuple", source.authorityTuple()); + snapshot.put("membershipVersion", source.membershipVersion()); + snapshot.put("accountIdentitySource", source.accountIdentitySource()); + snapshot.put("issuanceFence", Long.toString(source.issuanceFence())); + snapshot.put("issuanceFenceSourceVersion", Long.toString(source.issuanceFenceSourceVersion())); + byte[] snapshotBytes = AccountControlUiAuthority.canonical(Map.copyOf(snapshot)); + if (snapshotBytes.length > AccountStartSessionAuthorityCapture.MAX_SNAPSHOT_BYTES) { + throw unavailable(); + } + return new RequestSnapshot( + tuple.controlPlaneRequestId(), + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + tuple.targetOwner(), + loggingWorkloadUri, + reservationOwnerId, + reservationClaimFence, + tupleBytes, + tuple.mutationDigest(), + stored.operationId, + stored.jti, + stored.tokenHash, + sha256(signerReceipt), + source.issuanceFence(), + source.issuanceFenceSourceVersion(), + snapshotBytes); + } + + private static void requireSameRequestAndSnapshot( + RequestSnapshot request, AccountStartSessionAuthorityCapture capture, Record storedRow) { + requireStoredColumnsMatchPayload(storedRow, capture); + Map snapshot = parseObject(capture.snapshotBytes()); + if (!request.requestId().equals(capture.controlPlaneRequestId()) + || !MessageDigest.isEqual(request.snapshotBytes(), capture.snapshotBytes()) + || !Objects.equals( + snapshot.get("preAuthorizationTuple"), + Base64.getEncoder().encodeToString(request.tupleBytes())) + || !Objects.equals( + snapshot.get("controlUiOperationId"), request.controlUiOperationId().toString()) + || !Objects.equals( + snapshot.get("controlUiTokenJti"), request.controlUiTokenJti().toString()) + || !Objects.equals(snapshot.get("controlUiTokenHash"), request.controlUiTokenHash()) + || !Objects.equals( + snapshot.get("controlUiSignerReceiptSha256"), request.controlUiSignerReceiptSha256()) + || !Objects.equals( + snapshot.get("reservationOwnerId"), request.reservationOwnerId().toString()) + || !Objects.equals( + snapshot.get("reservationClaimFence"), + Long.toString(request.reservationClaimFence()))) { + throw unavailable(); + } + } + + private static boolean canonicalTuple( + byte[] tupleBytes, StartSessionPreAuthorizationReservationTuple tuple) { + try { + String json = new String(tupleBytes, StandardCharsets.UTF_8); + var parsed = StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(json); + return MessageDigest.isEqual( + tupleBytes, parsed.canonicalJson().getBytes(StandardCharsets.UTF_8)) + && parsed.controlPlaneRequestId().equals(tuple.controlPlaneRequestId()) + && parsed.mutationDigest().equals(tuple.mutationDigest()); + } catch (RuntimeException malformed) { + return false; + } + } + + private static boolean canonicalLoggingWorkload(String uri, String targetNamespace) { + if (uri == null) return false; + var match = LOGGING_WORKLOAD.matcher(uri); + if (!match.matches() || !match.group(1).equals(targetNamespace)) return false; + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && uri.equals(peer.uri()) + && "logging-admin-service".equals(peer.service()) + && targetNamespace.equals(peer.namespace()); + } + + private static Map parseObject(byte[] bytes) { + try { + Object value = + tools.jackson.databind.json.JsonMapper.builder() + .enable(tools.jackson.core.StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build() + .readValue(new String(bytes, StandardCharsets.UTF_8), Object.class); + if (value instanceof Map map) return map; + throw unavailable(); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + return value == null ? null : value; + } + + private static long number(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) throw unavailable(); + return value; + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("A writable Account owner transaction is required"); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Account StartSession source capture is unavailable"); + } + + private record Allocation( + long sourceVersion, long sourceFence, String linearization, String capturedAt) {} + + private record RequestSnapshot( + String requestId, + UUID accountId, + UUID tenantId, + String targetOwner, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + byte[] tupleBytes, + String mutationDigest, + UUID controlUiOperationId, + UUID controlUiTokenJti, + String controlUiTokenHash, + String controlUiSignerReceiptSha256, + long issuanceFence, + long issuanceFenceSourceVersion, + byte[] snapshotBytes) { + private RequestSnapshot { + tupleBytes = tupleBytes.clone(); + snapshotBytes = snapshotBytes.clone(); + } + + @Override + public byte[] tupleBytes() { + return tupleBytes.clone(); + } + + @Override + public byte[] snapshotBytes() { + return snapshotBytes.clone(); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql b/services/account-service/src/main/resources/db/migration/V100__account_jwt_signer_materialization_readback.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V42__account_jwt_signer_materialization_readback.sql rename to services/account-service/src/main/resources/db/migration/V100__account_jwt_signer_materialization_readback.sql diff --git a/services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql b/services/account-service/src/main/resources/db/migration/V101__account_jwt_jwks_prepublication.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V43__account_jwt_jwks_prepublication.sql rename to services/account-service/src/main/resources/db/migration/V101__account_jwt_jwks_prepublication.sql diff --git a/services/account-service/src/main/resources/db/migration/V44__account_gameplay_delegation_issuance.sql b/services/account-service/src/main/resources/db/migration/V102__account_gameplay_delegation_issuance.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V44__account_gameplay_delegation_issuance.sql rename to services/account-service/src/main/resources/db/migration/V102__account_gameplay_delegation_issuance.sql diff --git a/services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql b/services/account-service/src/main/resources/db/migration/V103__account_jwt_readiness_probes.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V45__account_jwt_readiness_probes.sql rename to services/account-service/src/main/resources/db/migration/V103__account_jwt_readiness_probes.sql diff --git a/services/account-service/src/main/resources/db/migration/V46__account_auth_evidence_bundles.sql b/services/account-service/src/main/resources/db/migration/V104__account_auth_evidence_bundles.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V46__account_auth_evidence_bundles.sql rename to services/account-service/src/main/resources/db/migration/V104__account_auth_evidence_bundles.sql diff --git a/services/account-service/src/main/resources/db/migration/V47__account_gameplay_delegation_encrypted_response.sql b/services/account-service/src/main/resources/db/migration/V105__account_gameplay_delegation_encrypted_response.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V47__account_gameplay_delegation_encrypted_response.sql rename to services/account-service/src/main/resources/db/migration/V105__account_gameplay_delegation_encrypted_response.sql diff --git a/services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql b/services/account-service/src/main/resources/db/migration/V106__account_jwt_signer_promotion_lifecycle.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V49__account_jwt_signer_promotion_lifecycle.sql rename to services/account-service/src/main/resources/db/migration/V106__account_jwt_signer_promotion_lifecycle.sql diff --git a/services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql b/services/account-service/src/main/resources/db/migration/V107__account_jwt_readiness_single_delivery_claims.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V50__account_jwt_readiness_single_delivery_claims.sql rename to services/account-service/src/main/resources/db/migration/V107__account_jwt_readiness_single_delivery_claims.sql diff --git a/services/account-service/src/main/resources/db/migration/V51__account_gameplay_delegation_committed_issuance.sql b/services/account-service/src/main/resources/db/migration/V108__account_gameplay_delegation_committed_issuance.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V51__account_gameplay_delegation_committed_issuance.sql rename to services/account-service/src/main/resources/db/migration/V108__account_gameplay_delegation_committed_issuance.sql diff --git a/services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql b/services/account-service/src/main/resources/db/migration/V109__account_jwt_validator_inventory_snapshots.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V52__account_jwt_validator_inventory_snapshots.sql rename to services/account-service/src/main/resources/db/migration/V109__account_jwt_validator_inventory_snapshots.sql diff --git a/services/account-service/src/main/resources/db/migration/V74__account_gameplay_token_identity_fences.sql b/services/account-service/src/main/resources/db/migration/V110__account_gameplay_token_identity_fences.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V74__account_gameplay_token_identity_fences.sql rename to services/account-service/src/main/resources/db/migration/V110__account_gameplay_token_identity_fences.sql diff --git a/services/account-service/src/main/resources/db/migration/V81__account_gameplay_login_credential_request_binding.sql b/services/account-service/src/main/resources/db/migration/V111__account_gameplay_login_credential_request_binding.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V81__account_gameplay_login_credential_request_binding.sql rename to services/account-service/src/main/resources/db/migration/V111__account_gameplay_login_credential_request_binding.sql diff --git a/services/account-service/src/main/resources/db/migration/V84__account_gameplay_delegation_decimal_source_versions.sql b/services/account-service/src/main/resources/db/migration/V112__account_gameplay_delegation_decimal_source_versions.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V84__account_gameplay_delegation_decimal_source_versions.sql rename to services/account-service/src/main/resources/db/migration/V112__account_gameplay_delegation_decimal_source_versions.sql diff --git a/services/account-service/src/main/resources/db/migration/V84.1__account_auth_evidence_checkpoint_key_count.sql b/services/account-service/src/main/resources/db/migration/V113__account_auth_evidence_checkpoint_key_count.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V84.1__account_auth_evidence_checkpoint_key_count.sql rename to services/account-service/src/main/resources/db/migration/V113__account_auth_evidence_checkpoint_key_count.sql diff --git a/services/account-service/src/main/resources/db/migration/V84.2__account_auth_evidence_shared_issuer_guard.sql b/services/account-service/src/main/resources/db/migration/V114__account_auth_evidence_shared_issuer_guard.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V84.2__account_auth_evidence_shared_issuer_guard.sql rename to services/account-service/src/main/resources/db/migration/V114__account_auth_evidence_shared_issuer_guard.sql diff --git a/services/account-service/src/main/resources/db/migration/V84.3__account_gameplay_commit_bundle_source_fence.sql b/services/account-service/src/main/resources/db/migration/V115__account_gameplay_commit_bundle_source_fence.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V84.3__account_gameplay_commit_bundle_source_fence.sql rename to services/account-service/src/main/resources/db/migration/V115__account_gameplay_commit_bundle_source_fence.sql diff --git a/services/account-service/src/main/resources/db/migration/V84.4__account_gameplay_authority_shared_issuer_guard.sql b/services/account-service/src/main/resources/db/migration/V116__account_gameplay_authority_shared_issuer_guard.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V84.4__account_gameplay_authority_shared_issuer_guard.sql rename to services/account-service/src/main/resources/db/migration/V116__account_gameplay_authority_shared_issuer_guard.sql diff --git a/services/account-service/src/main/resources/db/migration/V86__account_lifecycle_serving_operations.sql b/services/account-service/src/main/resources/db/migration/V117__account_lifecycle_serving_operations.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V86__account_lifecycle_serving_operations.sql rename to services/account-service/src/main/resources/db/migration/V117__account_lifecycle_serving_operations.sql diff --git a/services/account-service/src/main/resources/db/migration/V87__account_gameplay_admission_lease_operations.sql b/services/account-service/src/main/resources/db/migration/V118__account_gameplay_admission_lease_operations.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V87__account_gameplay_admission_lease_operations.sql rename to services/account-service/src/main/resources/db/migration/V118__account_gameplay_admission_lease_operations.sql diff --git a/services/account-service/src/main/resources/db/migration/V89__account_admission_unknown_decision_abort.sql b/services/account-service/src/main/resources/db/migration/V119__account_admission_unknown_decision_abort.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V89__account_admission_unknown_decision_abort.sql rename to services/account-service/src/main/resources/db/migration/V119__account_admission_unknown_decision_abort.sql diff --git a/services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql b/services/account-service/src/main/resources/db/migration/V120__account_admission_durable_commit_confirmation.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V90__account_admission_durable_commit_confirmation.sql rename to services/account-service/src/main/resources/db/migration/V120__account_admission_durable_commit_confirmation.sql diff --git a/services/account-service/src/main/resources/db/migration/V91__account_global_pending_admission_fences.sql b/services/account-service/src/main/resources/db/migration/V121__account_global_pending_admission_fences.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V91__account_global_pending_admission_fences.sql rename to services/account-service/src/main/resources/db/migration/V121__account_global_pending_admission_fences.sql diff --git a/services/account-service/src/main/resources/db/migration/V92__account_admission_original_ack_receipt.sql b/services/account-service/src/main/resources/db/migration/V122__account_admission_original_ack_receipt.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V92__account_admission_original_ack_receipt.sql rename to services/account-service/src/main/resources/db/migration/V122__account_admission_original_ack_receipt.sql diff --git a/services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql b/services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V100__account_jwt_readiness_per_pod_closure.sql rename to services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql diff --git a/services/account-service/src/main/resources/db/migration/V102__account_jwt_readiness_version_aware_delivery_claim_guard.sql b/services/account-service/src/main/resources/db/migration/V124__account_jwt_readiness_version_aware_delivery_claim_guard.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V102__account_jwt_readiness_version_aware_delivery_claim_guard.sql rename to services/account-service/src/main/resources/db/migration/V124__account_jwt_readiness_version_aware_delivery_claim_guard.sql diff --git a/services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql b/services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V104__account_jwt_signer_promotion_receipt_binding.sql rename to services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql diff --git a/services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql b/services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql new file mode 100644 index 0000000000..3137668d21 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql @@ -0,0 +1,142 @@ +CREATE TABLE account_start_session_operator_authorizations ( + control_plane_request_id VARCHAR(128) PRIMARY KEY + CHECK (octet_length(control_plane_request_id) BETWEEN 1 AND 128), + pre_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(pre_authorization_tuple) BETWEEN 1 AND 8192), + mutation_digest VARCHAR(64) NOT NULL + CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + issuance_workload_uri VARCHAR(256) NOT NULL + CHECK (issuance_workload_uri ~ '^spiffe://firemud/ns/([a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])/sa/logging-admin-service$'), + reservation_owner_id UUID NOT NULL, + reservation_claim_fence BIGINT NOT NULL CHECK (reservation_claim_fence > 0), + issuance_operation_id UUID NOT NULL UNIQUE, + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + bundle_version VARCHAR(32) NOT NULL + CHECK (bundle_version = 'authorityEvidenceBundle/v1'), + bundle_source_version VARCHAR(19) NOT NULL + CHECK (bundle_source_version ~ '^[1-9][0-9]{0,18}$' + AND bundle_source_version::NUMERIC <= 9223372036854775807), + bundle_source_fence VARCHAR(19) NOT NULL + CHECK (bundle_source_fence ~ '^[1-9][0-9]{0,18}$' + AND bundle_source_fence::NUMERIC <= 9223372036854775807), + bundle_linearization VARCHAR(20) NOT NULL + CHECK (bundle_linearization ~ '^[1-9][0-9]{0,19}$' + AND bundle_linearization::NUMERIC <= 18446744073709551615), + authority_evidence_bundle BYTEA NOT NULL + CHECK (octet_length(authority_evidence_bundle) BETWEEN 1 AND 131072), + authorization_reference_fingerprint VARCHAR(137) NOT NULL UNIQUE + CHECK (authorization_reference_fingerprint ~ '^arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}$'), + encrypted_response_envelope BYTEA NOT NULL + CHECK (octet_length(encrypted_response_envelope) BETWEEN 1 AND 65536), + issued_at TIMESTAMPTZ NOT NULL, + reference_expires_at TIMESTAMPTZ NOT NULL, + response_envelope_expires_at TIMESTAMPTZ NOT NULL, + status VARCHAR(16) NOT NULL CHECK (status IN ('ISSUED', 'REDEEMED')), + redemption_redeemer_workload_uri VARCHAR(256) + CHECK (redemption_redeemer_workload_uri IS NULL OR + redemption_redeemer_workload_uri ~ '^spiffe://firemud/ns/([a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])/sa/game-session-service$'), + redemption_owner_attempt_id UUID, + redemption_owner_fence BIGINT CHECK (redemption_owner_fence IS NULL OR redemption_owner_fence > 0), + redeemed_at TIMESTAMPTZ, + redemption_reference_fingerprint VARCHAR(137) + CHECK (redemption_reference_fingerprint IS NULL OR + redemption_reference_fingerprint ~ '^arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}$'), + redemption_authority_evidence_bundle BYTEA + CHECK (redemption_authority_evidence_bundle IS NULL OR + octet_length(redemption_authority_evidence_bundle) BETWEEN 1 AND 131072), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (reservation_owner_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (issuance_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (issued_at > CAST('1970-01-01 00:00:00+00:00' AS TIMESTAMPTZ)), + CHECK (reference_expires_at > issued_at + AND reference_expires_at <= issued_at + INTERVAL '5' MINUTE), + CHECK (response_envelope_expires_at > reference_expires_at + AND response_envelope_expires_at <= reference_expires_at + INTERVAL '1' MINUTE), + CHECK ( + (status = 'ISSUED' + AND redemption_redeemer_workload_uri IS NULL + AND redemption_owner_attempt_id IS NULL + AND redemption_owner_fence IS NULL + AND redeemed_at IS NULL + AND redemption_reference_fingerprint IS NULL + AND redemption_authority_evidence_bundle IS NULL) + OR + (status = 'REDEEMED' + AND redemption_redeemer_workload_uri IS NOT NULL + AND redemption_owner_attempt_id IS NOT NULL + AND redemption_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND redemption_owner_fence IS NOT NULL + AND redeemed_at IS NOT NULL + AND redeemed_at > issued_at + AND redeemed_at < reference_expires_at + AND redemption_reference_fingerprint = authorization_reference_fingerprint + AND redemption_authority_evidence_bundle = authority_evidence_bundle) + ) +); + +-- [jooq ignore start] +CREATE FUNCTION account_start_session_operator_authorization_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'ISSUED' + OR NEW.redemption_redeemer_workload_uri IS NOT NULL + OR NEW.redemption_owner_attempt_id IS NOT NULL + OR NEW.redemption_owner_fence IS NOT NULL + OR NEW.redeemed_at IS NOT NULL + OR NEW.redemption_reference_fingerprint IS NOT NULL + OR NEW.redemption_authority_evidence_bundle IS NOT NULL THEN + RAISE EXCEPTION 'StartSession authorization rows must begin unredeemed' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'StartSession operator authorization evidence cannot be deleted' + USING ERRCODE = '23514'; + END IF; + + IF (to_jsonb(NEW) - ARRAY['status','redemption_redeemer_workload_uri', + 'redemption_owner_attempt_id','redemption_owner_fence','redeemed_at', + 'redemption_reference_fingerprint','redemption_authority_evidence_bundle']) IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['status','redemption_redeemer_workload_uri', + 'redemption_owner_attempt_id','redemption_owner_fence','redeemed_at', + 'redemption_reference_fingerprint','redemption_authority_evidence_bundle']) + OR OLD.status <> 'ISSUED' + OR NEW.status <> 'REDEEMED' + OR OLD.redemption_redeemer_workload_uri IS NOT NULL + OR OLD.redemption_owner_attempt_id IS NOT NULL + OR OLD.redemption_owner_fence IS NOT NULL + OR OLD.redeemed_at IS NOT NULL + OR OLD.redemption_reference_fingerprint IS NOT NULL + OR OLD.redemption_authority_evidence_bundle IS NOT NULL + OR NEW.redemption_redeemer_workload_uri IS NULL + OR NEW.redemption_owner_attempt_id IS NULL + OR NEW.redemption_owner_fence IS NULL + OR NEW.redeemed_at IS NULL + OR NEW.redemption_reference_fingerprint IS DISTINCT FROM NEW.authorization_reference_fingerprint + OR NEW.redemption_authority_evidence_bundle IS DISTINCT FROM NEW.authority_evidence_bundle + OR NEW.redemption_redeemer_workload_uri IS DISTINCT FROM + regexp_replace(OLD.issuance_workload_uri, '/sa/logging-admin-service$', '/sa/game-session-service') THEN + RAISE EXCEPTION 'StartSession authorization evidence is immutable except one exact redemption' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_operator_authorization_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'StartSession operator authorization evidence cannot be truncated' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_start_session_operator_authorization_immutable + BEFORE INSERT OR UPDATE OR DELETE ON account_start_session_operator_authorizations + FOR EACH ROW EXECUTE FUNCTION account_start_session_operator_authorization_guard(); +CREATE TRIGGER account_start_session_operator_authorization_no_truncate + BEFORE TRUNCATE ON account_start_session_operator_authorizations + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_operator_authorization_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V110__selected_inventory_empty_arrays.sql b/services/account-service/src/main/resources/db/migration/V127__selected_inventory_empty_arrays.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V110__selected_inventory_empty_arrays.sql rename to services/account-service/src/main/resources/db/migration/V127__selected_inventory_empty_arrays.sql diff --git a/services/account-service/src/main/resources/db/migration/V128__account_start_session_authority_captures.sql b/services/account-service/src/main/resources/db/migration/V128__account_start_session_authority_captures.sql new file mode 100644 index 0000000000..7986eb96bf --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V128__account_start_session_authority_captures.sql @@ -0,0 +1,253 @@ +CREATE TABLE account_start_session_capture_source_version_allocator ( + allocator_id BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (allocator_id), + last_source_version BIGINT NOT NULL DEFAULT 0 CHECK (last_source_version >= 0), + last_control_plane_request_id VARCHAR(128), + last_transaction_id VARCHAR(20), + CHECK ((last_source_version = 0 AND last_control_plane_request_id IS NULL AND last_transaction_id IS NULL) + OR (last_source_version > 0 AND last_control_plane_request_id IS NOT NULL + AND last_transaction_id IS NOT NULL + AND last_transaction_id ~ '^[1-9][0-9]{0,19}$' + AND last_transaction_id::NUMERIC <= 18446744073709551615)) +); +INSERT INTO account_start_session_capture_source_version_allocator (allocator_id) VALUES (TRUE); + +CREATE TABLE account_start_session_capture_source_fence_allocator ( + allocator_id BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (allocator_id), + last_source_fence BIGINT NOT NULL DEFAULT 0 CHECK (last_source_fence >= 0), + last_control_plane_request_id VARCHAR(128), + last_transaction_id VARCHAR(20), + CHECK ((last_source_fence = 0 AND last_control_plane_request_id IS NULL AND last_transaction_id IS NULL) + OR (last_source_fence > 0 AND last_control_plane_request_id IS NOT NULL + AND last_transaction_id IS NOT NULL + AND last_transaction_id ~ '^[1-9][0-9]{0,19}$' + AND last_transaction_id::NUMERIC <= 18446744073709551615)) +); +INSERT INTO account_start_session_capture_source_fence_allocator (allocator_id) VALUES (TRUE); + +CREATE TABLE account_start_session_authority_captures ( + control_plane_request_id VARCHAR(128) PRIMARY KEY + CHECK (octet_length(control_plane_request_id) BETWEEN 1 AND 128), + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id) + ON DELETE RESTRICT, + target_owner VARCHAR(64) NOT NULL CHECK (target_owner = 'game-session-service'), + logging_workload_uri VARCHAR(256) NOT NULL + CHECK (logging_workload_uri ~ '^spiffe://firemud/ns/[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?/sa/logging-admin-service$'), + reservation_owner_id UUID NOT NULL CHECK (reservation_owner_id <> '00000000-0000-0000-0000-000000000000'::UUID), + reservation_claim_fence BIGINT NOT NULL CHECK (reservation_claim_fence > 0), + pre_authorization_tuple BYTEA NOT NULL CHECK (octet_length(pre_authorization_tuple) BETWEEN 1 AND 8192), + mutation_digest VARCHAR(64) NOT NULL CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + control_ui_operation_id UUID NOT NULL + REFERENCES account_control_ui_issuance_operations(operation_id) ON DELETE RESTRICT, + control_ui_token_jti UUID NOT NULL CHECK (control_ui_token_jti <> '00000000-0000-0000-0000-000000000000'::UUID), + control_ui_token_hash VARCHAR(64) NOT NULL CHECK (control_ui_token_hash ~ '^[0-9a-f]{64}$'), + control_ui_signer_receipt_sha256 VARCHAR(64) NOT NULL + CHECK (control_ui_signer_receipt_sha256 ~ '^[0-9a-f]{64}$'), + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + issuance_fence_source_version BIGINT NOT NULL CHECK (issuance_fence_source_version > 0), + captured_at TIMESTAMPTZ NOT NULL, + snapshot_sha256 VARCHAR(64) NOT NULL CHECK (snapshot_sha256 ~ '^[0-9a-f]{64}$'), + canonical_snapshot_bytes BYTEA NOT NULL + CHECK (octet_length(canonical_snapshot_bytes) BETWEEN 1 AND 245760), + source_version BIGINT NOT NULL CHECK (source_version > 0), + source_fence BIGINT NOT NULL CHECK (source_fence > 0), + linearization VARCHAR(20) NOT NULL + CHECK (linearization ~ '^[1-9][0-9]{0,19}$' + AND linearization::NUMERIC <= 18446744073709551615), + canonical_sha256 VARCHAR(64) NOT NULL CHECK (canonical_sha256 ~ '^[0-9a-f]{64}$'), + canonical_capture_bytes BYTEA NOT NULL + CHECK (octet_length(canonical_capture_bytes) BETWEEN 1 AND 16384), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_start_session_capture_total_size_check + CHECK (octet_length(canonical_snapshot_bytes) + octet_length(canonical_capture_bytes) <= 262144), + CONSTRAINT account_start_session_capture_source_version_unique UNIQUE (source_version), + CONSTRAINT account_start_session_capture_source_fence_unique UNIQUE (source_fence), + CONSTRAINT account_start_session_capture_snapshot_digest + CHECK (snapshot_sha256 = encode(sha256(canonical_snapshot_bytes), 'hex')), + CONSTRAINT account_start_session_capture_reference_digest + CHECK (canonical_sha256 = encode(sha256(canonical_capture_bytes), 'hex')) +); + +-- [jooq ignore start] +ALTER TABLE account_start_session_authority_captures + ADD CONSTRAINT account_start_session_capture_captured_at_millis + CHECK (date_trunc('milliseconds', captured_at) = captured_at); +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE FUNCTION account_start_session_authority_capture_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + snapshot JSONB; + reference JSONB; + tuple JSONB; + control_ui RECORD; + allocated_version BIGINT; + allocated_version_request VARCHAR(128); + allocated_version_transaction VARCHAR(20); + allocated_fence BIGINT; + allocated_fence_request VARCHAR(128); + allocated_fence_transaction VARCHAR(20); + capture_transaction VARCHAR(20); +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'StartSession Account source captures are immutable and cannot be deleted' + USING ERRCODE = '23514'; + END IF; + + capture_transaction := pg_current_xact_id()::TEXT; + IF NEW.linearization IS DISTINCT FROM capture_transaction THEN + RAISE EXCEPTION 'StartSession capture linearization must identify its inserting transaction' + USING ERRCODE = '23514'; + END IF; + + SELECT last_source_version, last_control_plane_request_id, last_transaction_id + INTO allocated_version, allocated_version_request, allocated_version_transaction + FROM account_start_session_capture_source_version_allocator + WHERE allocator_id = TRUE FOR UPDATE; + SELECT last_source_fence, last_control_plane_request_id, last_transaction_id + INTO allocated_fence, allocated_fence_request, allocated_fence_transaction + FROM account_start_session_capture_source_fence_allocator + WHERE allocator_id = TRUE FOR UPDATE; + IF allocated_version IS DISTINCT FROM NEW.source_version + OR allocated_fence IS DISTINCT FROM NEW.source_fence + OR allocated_version_request IS DISTINCT FROM NEW.control_plane_request_id + OR allocated_fence_request IS DISTINCT FROM NEW.control_plane_request_id + OR allocated_version_transaction IS DISTINCT FROM capture_transaction + OR allocated_fence_transaction IS DISTINCT FROM capture_transaction THEN + RAISE EXCEPTION 'StartSession capture reference is not the exact durable source allocation' + USING ERRCODE = '23514'; + END IF; + + snapshot := convert_from(NEW.canonical_snapshot_bytes, 'UTF8')::JSONB; + reference := convert_from(NEW.canonical_capture_bytes, 'UTF8')::JSONB; + tuple := convert_from(NEW.pre_authorization_tuple, 'UTF8')::JSONB; + IF jsonb_typeof(snapshot) IS DISTINCT FROM 'object' + OR jsonb_typeof(reference) IS DISTINCT FROM 'object' + OR jsonb_typeof(tuple) IS DISTINCT FROM 'object' + OR reference->>'schema' IS DISTINCT FROM 'account-start-session-authority-capture/v1' + OR reference->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR reference->>'capturedAt' IS DISTINCT FROM + to_char(NEW.captured_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') + OR reference->>'snapshotSha256' IS DISTINCT FROM NEW.snapshot_sha256 + OR reference#>>'{bundleReference,bundleVersion}' IS DISTINCT FROM 'authorityEvidenceBundle/v1' + OR reference#>>'{bundleReference,sourceVersion}' IS DISTINCT FROM NEW.source_version::TEXT + OR reference#>>'{bundleReference,sourceFence}' IS DISTINCT FROM NEW.source_fence::TEXT + OR reference#>>'{bundleReference,linearization}' IS DISTINCT FROM NEW.linearization + OR snapshot->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR snapshot->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR snapshot->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR snapshot->>'targetOwner' IS DISTINCT FROM NEW.target_owner + OR snapshot->>'loggingWorkloadUri' IS DISTINCT FROM NEW.logging_workload_uri + OR snapshot->>'reservationOwnerId' IS DISTINCT FROM NEW.reservation_owner_id::TEXT + OR snapshot->>'reservationClaimFence' IS DISTINCT FROM NEW.reservation_claim_fence::TEXT + OR snapshot->>'mutationDigest' IS DISTINCT FROM NEW.mutation_digest + OR snapshot->>'controlUiOperationId' IS DISTINCT FROM NEW.control_ui_operation_id::TEXT + OR snapshot->>'controlUiTokenJti' IS DISTINCT FROM NEW.control_ui_token_jti::TEXT + OR snapshot->>'controlUiTokenHash' IS DISTINCT FROM NEW.control_ui_token_hash + OR snapshot->>'controlUiSignerReceiptSha256' IS DISTINCT FROM NEW.control_ui_signer_receipt_sha256 + OR snapshot->>'issuanceFence' IS DISTINCT FROM NEW.issuance_fence::TEXT + OR snapshot->>'issuanceFenceSourceVersion' IS DISTINCT FROM NEW.issuance_fence_source_version::TEXT + OR decode(snapshot->>'preAuthorizationTuple', 'base64') IS DISTINCT FROM NEW.pre_authorization_tuple THEN + RAISE EXCEPTION 'StartSession capture payload differs from its exact row identity' + USING ERRCODE = '23514'; + END IF; + + IF tuple#>>'{actor,accountId}' IS DISTINCT FROM NEW.account_uuid::TEXT + OR tuple#>>'{scope,tenantId}' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR tuple#>>'{targetOwner,ownerService}' IS DISTINCT FROM 'game-session-service' + OR tuple#>>'{actionFamilyRequestIdentity,requestId}' IS DISTINCT FROM NEW.control_plane_request_id + OR tuple->>'tupleSchemaId' IS DISTINCT FROM 'preAuthorizationReservationTuple' + OR tuple->>'tupleSchemaVersion' IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'StartSession capture tuple scope or identity is inconsistent' + USING ERRCODE = '23514'; + END IF; + + SELECT operation_id, account_uuid, tenant_uuid, token_jti, token_hash, signer_receipt, status + INTO control_ui + FROM account_control_ui_issuance_operations + WHERE operation_id = NEW.control_ui_operation_id + FOR SHARE; + IF control_ui.operation_id IS NULL + OR control_ui.status IS DISTINCT FROM 'COMMITTED' + OR control_ui.account_uuid IS DISTINCT FROM NEW.account_uuid + OR control_ui.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR control_ui.token_jti IS DISTINCT FROM NEW.control_ui_token_jti + OR control_ui.token_hash IS DISTINCT FROM NEW.control_ui_token_hash + OR encode(sha256(control_ui.signer_receipt), 'hex') IS DISTINCT FROM NEW.control_ui_signer_receipt_sha256 THEN + RAISE EXCEPTION 'StartSession capture is not bound to its original committed ControlUI operation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_authority_capture_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'StartSession Account source captures cannot be truncated' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_start_session_authority_capture_immutable + BEFORE INSERT OR UPDATE OR DELETE ON account_start_session_authority_captures + FOR EACH ROW EXECUTE FUNCTION account_start_session_authority_capture_guard(); +CREATE TRIGGER account_start_session_authority_capture_no_truncate + BEFORE TRUNCATE ON account_start_session_authority_captures + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_authority_capture_no_truncate(); + +CREATE FUNCTION account_start_session_capture_allocator_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'TRUNCATE' THEN + RAISE EXCEPTION 'StartSession capture allocators cannot be deleted or truncated' + USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['last_source_version','last_control_plane_request_id','last_transaction_id']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['last_source_version','last_control_plane_request_id','last_transaction_id']) + OR NEW.last_source_version <> OLD.last_source_version + 1 + OR NEW.last_control_plane_request_id IS NULL + OR NEW.last_transaction_id IS DISTINCT FROM pg_current_xact_id()::TEXT THEN + RAISE EXCEPTION 'StartSession capture sourceVersion allocator must advance once in its owner transaction' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_capture_fence_allocator_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' OR TG_OP = 'TRUNCATE' THEN + RAISE EXCEPTION 'StartSession capture allocators cannot be deleted or truncated' + USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['last_source_fence','last_control_plane_request_id','last_transaction_id']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['last_source_fence','last_control_plane_request_id','last_transaction_id']) + OR NEW.last_source_fence <> OLD.last_source_fence + 1 + OR NEW.last_control_plane_request_id IS NULL + OR NEW.last_transaction_id IS DISTINCT FROM pg_current_xact_id()::TEXT THEN + RAISE EXCEPTION 'StartSession capture sourceFence allocator must advance once in its owner transaction' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_start_session_capture_source_version_allocator_guard + BEFORE UPDATE OR DELETE ON account_start_session_capture_source_version_allocator + FOR EACH ROW EXECUTE FUNCTION account_start_session_capture_allocator_no_mutation(); +CREATE TRIGGER account_start_session_capture_source_version_allocator_no_truncate + BEFORE TRUNCATE ON account_start_session_capture_source_version_allocator + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_authority_capture_no_truncate(); +CREATE TRIGGER account_start_session_capture_source_fence_allocator_guard + BEFORE UPDATE OR DELETE ON account_start_session_capture_source_fence_allocator + FOR EACH ROW EXECUTE FUNCTION account_start_session_capture_fence_allocator_no_mutation(); +CREATE TRIGGER account_start_session_capture_source_fence_allocator_no_truncate + BEFORE TRUNCATE ON account_start_session_capture_source_fence_allocator + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_authority_capture_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V74.1__account_global_role_source.sql b/services/account-service/src/main/resources/db/migration/V74__account_global_role_source.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V74.1__account_global_role_source.sql rename to services/account-service/src/main/resources/db/migration/V74__account_global_role_source.sql diff --git a/services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql b/services/account-service/src/main/resources/db/migration/V75__draft_commit_authorization_fences.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V76__draft_commit_authorization_fences.sql rename to services/account-service/src/main/resources/db/migration/V75__draft_commit_authorization_fences.sql diff --git a/services/account-service/src/main/resources/db/migration/V93__account_draft_required_owner_fence.sql b/services/account-service/src/main/resources/db/migration/V76__account_draft_required_owner_fence.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V93__account_draft_required_owner_fence.sql rename to services/account-service/src/main/resources/db/migration/V76__account_draft_required_owner_fence.sql diff --git a/services/account-service/src/main/resources/db/migration/V75__account_password_reset_operation_receipts.sql b/services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql similarity index 99% rename from services/account-service/src/main/resources/db/migration/V75__account_password_reset_operation_receipts.sql rename to services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql index 33b0cb2992..718850abf2 100644 --- a/services/account-service/src/main/resources/db/migration/V75__account_password_reset_operation_receipts.sql +++ b/services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql @@ -88,4 +88,4 @@ $$; CREATE TRIGGER account_password_reset_operation_immutable BEFORE UPDATE OR DELETE ON account_password_reset_operation_receipts FOR EACH ROW EXECUTE FUNCTION account_password_reset_operation_immutable_guard(); --- [jooq ignore end] +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V77__account_logout_all_operation_receipts.sql b/services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql similarity index 99% rename from services/account-service/src/main/resources/db/migration/V77__account_logout_all_operation_receipts.sql rename to services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql index 09ae1789ae..00ab9cc390 100644 --- a/services/account-service/src/main/resources/db/migration/V77__account_logout_all_operation_receipts.sql +++ b/services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql @@ -87,4 +87,4 @@ $$; CREATE TRIGGER account_logout_all_operation_immutable BEFORE UPDATE OR DELETE ON account_logout_all_operation_receipts FOR EACH ROW EXECUTE FUNCTION account_logout_all_operation_immutable_guard(); --- [jooq ignore end] +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V78__account_security_state_operations.sql b/services/account-service/src/main/resources/db/migration/V79__account_security_state_operations.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V78__account_security_state_operations.sql rename to services/account-service/src/main/resources/db/migration/V79__account_security_state_operations.sql diff --git a/services/account-service/src/main/resources/db/migration/V83__account_security_event_source_guard.sql b/services/account-service/src/main/resources/db/migration/V80__account_security_event_source_guard.sql similarity index 64% rename from services/account-service/src/main/resources/db/migration/V83__account_security_event_source_guard.sql rename to services/account-service/src/main/resources/db/migration/V80__account_security_event_source_guard.sql index 59aadb67c7..1e0906da9a 100644 --- a/services/account-service/src/main/resources/db/migration/V83__account_security_event_source_guard.sql +++ b/services/account-service/src/main/resources/db/migration/V80__account_security_event_source_guard.sql @@ -1,5 +1,5 @@ --- Extend the V40 source-head guard for the immutable V78 security-state event without changing --- historical migrations or treating the legacy scalar Account role as canonical role authority. +-- Extend the V40 source-head and Account security guards for the immutable V77/V78 operation +-- receipts without changing historical migrations or treating scalar Account role as authority. -- [jooq ignore start] CREATE OR REPLACE FUNCTION account_authority_source_record_update_guard() RETURNS TRIGGER @@ -14,8 +14,11 @@ DECLARE fence_row RECORD; role_source_row RECORD; operation_row RECORD; + reset_row RECORD; + logout_row RECORD; account_state JSONB; security_request_id UUID; + logout_request_id UUID; BEGIN IF NEW.outbox_stream_key IS DISTINCT FROM OLD.outbox_stream_key OR NEW.scope_kind IS DISTINCT FROM OLD.scope_kind @@ -71,8 +74,8 @@ BEGIN USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; END IF; ELSIF NEW.scope_kind = 'ACCOUNT' THEN - SELECT id, account_uuid_provenance, account_uuid_source_numeric_id, email_verified, - login_auth_modes, role, lifecycle_state + SELECT id, account_uuid_provenance, account_uuid_source_numeric_id, email, + username, password_hash, email_verified, login_auth_modes, role, lifecycle_state INTO account_row FROM accounts WHERE account_uuid = NEW.account_uuid; SELECT COALESCE(jsonb_agg(to_jsonb(login_mode) ORDER BY login_mode), '[]'::JSONB) INTO expected_modes @@ -84,6 +87,14 @@ BEGIN RAISE EXCEPTION 'Account source event has no exact Account identity/provenance' USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_account_state'; END IF; + SELECT issuance_fence, source_version INTO fence_row + FROM account_authority_issuance_fences + WHERE account_uuid = NEW.account_uuid; + IF fence_row.issuance_fence IS DISTINCT FROM NEW.current_issuance_fence + OR fence_row.source_version IS DISTINCT FROM NEW.current_issuance_fence_source_version THEN + RAISE EXCEPTION 'Account source event does not match the exact current shared issuance fence' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_fence_consistent'; + END IF; IF event_payload->>'eventType' = 'ACCOUNT_AUTHORITY_CHANGED' THEN -- Preserve the pre-V78 Account source event contract exactly. @@ -174,6 +185,75 @@ BEGIN RAISE EXCEPTION 'Security-state source event has no exact committed owner receipt' USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; END IF; + ELSIF event_payload->>'eventType' = 'PASSWORD_RESET_COMMITTED' THEN + SELECT * INTO reset_row FROM account_password_reset_operation_receipts + WHERE request_id = event_payload->>'requestId'; + IF event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-password-reset-event/v1' + OR event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR event_payload->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT + OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.current_generation::TEXT + OR event_payload->>'sourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT + OR event_payload#>>'{accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM NEW.cutoff_generation::TEXT + OR event_payload#>>'{accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM NEW.cutoff_stream_key + OR event_payload#>>'{accountSecurityCutoff,outboxSequence}' IS DISTINCT FROM NEW.cutoff_sequence::TEXT + OR reset_row.token_hash IS NULL + OR reset_row.account_id IS DISTINCT FROM account_row.id + OR reset_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR reset_row.operation_kind IS DISTINCT FROM 'PASSWORD_RESET' + OR reset_row.request_digest_version IS DISTINCT FROM 1 + OR reset_row.request_id IS DISTINCT FROM 'account-password-reset-request-v1:' || encode(reset_row.token_hash, 'hex') + OR reset_row.request_id IS DISTINCT FROM event_payload->>'requestId' + OR reset_row.outbox_stream_key IS DISTINCT FROM NEW.outbox_stream_key + OR reset_row.outbox_sequence IS DISTINCT FROM NEW.last_outbox_sequence + OR reset_row.event_id IS DISTINCT FROM NEW.last_event_id + OR reset_row.event_id IS DISTINCT FROM 'account-password-reset-event-v1:' || encode(reset_row.token_hash, 'hex') + OR reset_row.event_digest IS DISTINCT FROM NEW.last_event_digest + OR reset_row.event_digest IS DISTINCT FROM event_row.event_digest + OR reset_row.account_authority_generation IS DISTINCT FROM NEW.current_generation + OR reset_row.account_source_version IS DISTINCT FROM NEW.current_source_version + OR reset_row.issuance_fence IS DISTINCT FROM NEW.current_issuance_fence + OR reset_row.issuance_fence_source_version IS DISTINCT FROM NEW.current_issuance_fence_source_version + OR reset_row.password_verifier_digest + IS DISTINCT FROM sha256(convert_to(account_row.password_hash, 'UTF8')) THEN + RAISE EXCEPTION 'Password-reset source event has no exact immutable Account operation receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF; + ELSIF event_payload->>'eventType' = 'LOGOUT_ALL_COMMITTED' THEN + IF event_payload->>'requestId' IS NULL + OR event_payload->>'requestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN + RAISE EXCEPTION 'Logout-all source event request identity is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF; + logout_request_id := (event_payload->>'requestId')::UUID; + SELECT * INTO logout_row FROM account_logout_all_operation_receipts + WHERE request_id = logout_request_id; + IF event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-logout-all-event/v1' + OR event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR event_payload->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT + OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM NEW.current_generation::TEXT + OR event_payload->>'sourceVersion' IS DISTINCT FROM NEW.current_source_version::TEXT + OR event_payload#>>'{accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM NEW.cutoff_generation::TEXT + OR event_payload#>>'{accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM NEW.cutoff_stream_key + OR event_payload#>>'{accountSecurityCutoff,outboxSequence}' IS DISTINCT FROM NEW.cutoff_sequence::TEXT + OR logout_row.request_id IS DISTINCT FROM logout_request_id + OR logout_row.account_id IS DISTINCT FROM account_row.id + OR logout_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR logout_row.operation_kind IS DISTINCT FROM 'ACCOUNT_LOGOUT_ALL' + OR logout_row.request_digest_version IS DISTINCT FROM 1 + OR logout_row.lifecycle_result IS DISTINCT FROM 'LOGOUT_ALL_COMMITTED' + OR event_payload->>'eventId' IS DISTINCT FROM 'account-logout-all-event-v1:' || logout_request_id::TEXT + OR logout_row.event_id IS DISTINCT FROM event_payload->>'eventId' + OR logout_row.outbox_stream_key IS DISTINCT FROM NEW.outbox_stream_key + OR logout_row.outbox_sequence IS DISTINCT FROM NEW.last_outbox_sequence + OR logout_row.event_digest IS DISTINCT FROM NEW.last_event_digest + OR logout_row.event_digest IS DISTINCT FROM event_row.event_digest + OR logout_row.account_authority_generation IS DISTINCT FROM NEW.current_generation + OR logout_row.account_source_version IS DISTINCT FROM NEW.current_source_version + OR logout_row.issuance_fence IS DISTINCT FROM NEW.current_issuance_fence + OR logout_row.issuance_fence_source_version IS DISTINCT FROM NEW.current_issuance_fence_source_version THEN + RAISE EXCEPTION 'Logout-all source event has no exact immutable Account operation receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; + END IF; ELSE RAISE EXCEPTION 'Unsupported Account source event type' USING ERRCODE = '23514', CONSTRAINT = 'account_authority_source_event_values'; @@ -198,12 +278,15 @@ DECLARE fence_row RECORD; role_source_row RECORD; operation_row RECORD; + reset_row RECORD; + logout_row RECORD; before_state JSONB; after_state JSONB; expected_before_state JSONB; expected_after_state JSONB; changed_kinds TEXT[] := ARRAY[]::TEXT[]; security_request_id UUID; + logout_request_id UUID; BEGIN IF OLD.password_hash IS NOT DISTINCT FROM NEW.password_hash AND OLD.email_verified IS NOT DISTINCT FROM NEW.email_verified @@ -223,7 +306,7 @@ BEGIN USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_required'; END IF; - SELECT payload INTO event_row + SELECT event_id, event_digest, payload INTO event_row FROM account_authority_outbox_events WHERE outbox_stream_key = source_row.outbox_stream_key AND outbox_sequence = source_row.last_outbox_sequence @@ -232,7 +315,93 @@ BEGIN event_payload := convert_from(event_row.payload, 'UTF8')::JSONB; SELECT COALESCE(jsonb_agg(to_jsonb(login_mode) ORDER BY login_mode), '[]'::JSONB) INTO expected_modes - FROM unnest(string_to_array(NEW.login_auth_modes, ',')) AS modes(login_mode); + FROM unnest(string_to_array(NEW.login_auth_modes, ',')) AS modes(login_mode); + + IF event_payload->>'eventType' = 'PASSWORD_RESET_COMMITTED' THEN + SELECT * INTO reset_row FROM account_password_reset_operation_receipts + WHERE request_id = event_payload->>'requestId'; + IF OLD.password_hash IS NOT DISTINCT FROM NEW.password_hash + OR (to_jsonb(OLD) - 'password_hash') IS DISTINCT FROM + (to_jsonb(NEW) - 'password_hash') + OR event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-password-reset-event/v1' + OR event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR event_payload->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT + OR event_payload->>'outboxStreamKey' IS DISTINCT FROM source_row.outbox_stream_key + OR event_payload->>'outboxSequence' IS DISTINCT FROM source_row.last_outbox_sequence::TEXT + OR event_payload->>'eventId' IS DISTINCT FROM source_row.last_event_id + OR event_payload->>'eventDigest' IS DISTINCT FROM source_row.last_event_digest + OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM source_row.current_generation::TEXT + OR event_payload->>'sourceVersion' IS DISTINCT FROM source_row.current_source_version::TEXT + OR event_payload#>>'{accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM source_row.cutoff_generation::TEXT + OR event_payload#>>'{accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM source_row.cutoff_stream_key + OR event_payload#>>'{accountSecurityCutoff,outboxSequence}' IS DISTINCT FROM source_row.cutoff_sequence::TEXT + OR reset_row.token_hash IS NULL + OR reset_row.account_id IS DISTINCT FROM NEW.id + OR reset_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR reset_row.operation_kind IS DISTINCT FROM 'PASSWORD_RESET' + OR reset_row.request_digest_version IS DISTINCT FROM 1 + OR reset_row.request_id IS DISTINCT FROM 'account-password-reset-request-v1:' || encode(reset_row.token_hash, 'hex') + OR reset_row.request_id IS DISTINCT FROM event_payload->>'requestId' + OR reset_row.outbox_stream_key IS DISTINCT FROM source_row.outbox_stream_key + OR reset_row.outbox_sequence IS DISTINCT FROM source_row.last_outbox_sequence + OR reset_row.event_id IS DISTINCT FROM source_row.last_event_id + OR reset_row.event_id IS DISTINCT FROM 'account-password-reset-event-v1:' || encode(reset_row.token_hash, 'hex') + OR reset_row.event_digest IS DISTINCT FROM source_row.last_event_digest + OR reset_row.event_digest IS DISTINCT FROM event_row.event_digest + OR reset_row.account_authority_generation IS DISTINCT FROM source_row.current_generation + OR reset_row.account_source_version IS DISTINCT FROM source_row.current_source_version + OR reset_row.issuance_fence IS DISTINCT FROM source_row.current_issuance_fence + OR reset_row.issuance_fence_source_version IS DISTINCT FROM source_row.current_issuance_fence_source_version + OR reset_row.password_verifier_digest IS DISTINCT FROM sha256(convert_to(NEW.password_hash, 'UTF8')) THEN + RAISE EXCEPTION 'Password-reset source event does not authorize the exact Account password update' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + RETURN NULL; + END IF; + + IF event_payload->>'eventType' = 'LOGOUT_ALL_COMMITTED' THEN + IF event_payload->>'requestId' IS NULL + OR event_payload->>'requestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN + RAISE EXCEPTION 'Logout-all source event request identity is malformed' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + logout_request_id := (event_payload->>'requestId')::UUID; + SELECT * INTO logout_row FROM account_logout_all_operation_receipts + WHERE request_id = logout_request_id; + IF event_payload->>'schemaVersion' IS DISTINCT FROM 'account-auth-logout-all-event/v1' + OR event_payload->>'accountId' IS DISTINCT FROM NEW.account_uuid::TEXT + OR event_payload->>'sourceScope' IS DISTINCT FROM 'account/' || NEW.account_uuid::TEXT + OR event_payload->>'outboxStreamKey' IS DISTINCT FROM source_row.outbox_stream_key + OR event_payload->>'outboxSequence' IS DISTINCT FROM source_row.last_outbox_sequence::TEXT + OR event_payload->>'eventId' IS DISTINCT FROM source_row.last_event_id + OR event_payload->>'eventDigest' IS DISTINCT FROM source_row.last_event_digest + OR event_payload->>'accountAuthorityGeneration' IS DISTINCT FROM source_row.current_generation::TEXT + OR event_payload->>'sourceVersion' IS DISTINCT FROM source_row.current_source_version::TEXT + OR event_payload#>>'{accountSecurityCutoff,accountAuthorityGeneration}' IS DISTINCT FROM source_row.cutoff_generation::TEXT + OR event_payload#>>'{accountSecurityCutoff,outboxStreamKey}' IS DISTINCT FROM source_row.cutoff_stream_key + OR event_payload#>>'{accountSecurityCutoff,outboxSequence}' IS DISTINCT FROM source_row.cutoff_sequence::TEXT + OR logout_row.request_id IS DISTINCT FROM logout_request_id + OR logout_row.account_id IS DISTINCT FROM NEW.id + OR logout_row.account_uuid IS DISTINCT FROM NEW.account_uuid + OR logout_row.operation_kind IS DISTINCT FROM 'ACCOUNT_LOGOUT_ALL' + OR logout_row.request_digest_version IS DISTINCT FROM 1 + OR logout_row.lifecycle_result IS DISTINCT FROM 'LOGOUT_ALL_COMMITTED' + OR event_payload->>'eventId' IS DISTINCT FROM 'account-logout-all-event-v1:' || logout_request_id::TEXT + OR logout_row.event_id IS DISTINCT FROM source_row.last_event_id + OR logout_row.outbox_stream_key IS DISTINCT FROM source_row.outbox_stream_key + OR logout_row.outbox_sequence IS DISTINCT FROM source_row.last_outbox_sequence + OR logout_row.event_digest IS DISTINCT FROM source_row.last_event_digest + OR logout_row.event_digest IS DISTINCT FROM event_row.event_digest + OR logout_row.account_authority_generation IS DISTINCT FROM source_row.current_generation + OR logout_row.account_source_version IS DISTINCT FROM source_row.current_source_version + OR logout_row.issuance_fence IS DISTINCT FROM source_row.current_issuance_fence + OR logout_row.issuance_fence_source_version IS DISTINCT FROM source_row.current_issuance_fence_source_version THEN + RAISE EXCEPTION 'Logout-all source event has no exact immutable Account operation receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; + RAISE EXCEPTION 'Logout-all source events cannot authorize Account security state changes' + USING ERRCODE = '23514', CONSTRAINT = 'account_authority_account_security_event_mismatch'; + END IF; IF event_payload->>'eventType' = 'ACCOUNT_SECURITY_STATE_CHANGED' THEN SELECT generation, source_version INTO authority_row diff --git a/services/account-service/src/main/resources/db/migration/V88__account_platform_restriction_birth_sources.sql b/services/account-service/src/main/resources/db/migration/V81__account_platform_restriction_birth_sources.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V88__account_platform_restriction_birth_sources.sql rename to services/account-service/src/main/resources/db/migration/V81__account_platform_restriction_birth_sources.sql diff --git a/services/account-service/src/main/resources/db/migration/V98__creator_membership_provenance.sql b/services/account-service/src/main/resources/db/migration/V82__creator_membership_provenance.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V98__creator_membership_provenance.sql rename to services/account-service/src/main/resources/db/migration/V82__creator_membership_provenance.sql diff --git a/services/account-service/src/main/resources/db/migration/V94__account_tenant_creation_bootstrap.sql b/services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V94__account_tenant_creation_bootstrap.sql rename to services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql diff --git a/services/account-service/src/main/resources/db/migration/V95__individual_creator_party_sources.sql b/services/account-service/src/main/resources/db/migration/V84__individual_creator_party_sources.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V95__individual_creator_party_sources.sql rename to services/account-service/src/main/resources/db/migration/V84__individual_creator_party_sources.sql diff --git a/services/account-service/src/main/resources/db/migration/V96__account_hosted_terms_acceptance_workflow.sql b/services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V96__account_hosted_terms_acceptance_workflow.sql rename to services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql diff --git a/services/account-service/src/main/resources/db/migration/V97__account_hosted_terms_environment_binding.sql b/services/account-service/src/main/resources/db/migration/V86__account_hosted_terms_environment_binding.sql similarity index 82% rename from services/account-service/src/main/resources/db/migration/V97__account_hosted_terms_environment_binding.sql rename to services/account-service/src/main/resources/db/migration/V86__account_hosted_terms_environment_binding.sql index 35c21bb8a9..7b2862e2b7 100644 --- a/services/account-service/src/main/resources/db/migration/V97__account_hosted_terms_environment_binding.sql +++ b/services/account-service/src/main/resources/db/migration/V86__account_hosted_terms_environment_binding.sql @@ -285,4 +285,65 @@ CREATE CONSTRAINT TRIGGER account_hosted_terms_environment_binding_complete AFTER UPDATE ON account_hosted_terms_environment_binding_heads DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_complete_guard(); + +CREATE FUNCTION account_hosted_terms_environment_binding_fence_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE predecessor UUID; +DECLARE predecessor_scope UUID; +DECLARE candidate_scope UUID; +BEGIN + IF NEW.status = 'COMMITTED' THEN + SELECT candidate.predecessor_binding_id, prior.hosted_scope_id, candidate.hosted_scope_id + INTO predecessor, predecessor_scope, candidate_scope + FROM account_hosted_terms_environment_bindings candidate + LEFT JOIN account_hosted_terms_environment_bindings prior + ON prior.environment_boundary = candidate.environment_boundary + AND prior.binding_id = candidate.predecessor_binding_id + WHERE candidate.environment_boundary = NEW.environment_boundary + AND candidate.binding_id = NEW.candidate_binding_id; + IF predecessor IS NOT NULL AND ( + NEW.source_change_binding IS NULL + OR NOT EXISTS ( + SELECT 1 FROM account_draft_authorization_source_changes change + JOIN account_draft_authorization_changed_scopes changed USING (change_id) + WHERE change.change_id = NEW.request_id + AND change.binding = NEW.source_change_binding + AND change.status = 'SOURCE_COMMITTED' + AND changed.source_key = + 'HOSTED_TERMS:environment-boundary/' || NEW.environment_boundary) + OR predecessor_scope IS NULL OR candidate_scope IS NULL + OR EXISTS ( + SELECT 1 FROM account_hosted_terms_scopes scope + WHERE scope.hosted_scope_id IN (predecessor_scope, candidate_scope) + AND scope.current_version_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + WHERE changed.change_id = NEW.request_id + AND changed.source_key = 'HOSTED_TERMS:' || scope.hosted_scope_id::TEXT)) + OR (SELECT count(*) FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.request_id) <> 1 + ( + SELECT count(DISTINCT scope.hosted_scope_id) + FROM account_hosted_terms_scopes scope + WHERE scope.hosted_scope_id IN (predecessor_scope, candidate_scope) + AND scope.current_version_id IS NOT NULL) + OR EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + WHERE changed.change_id = NEW.request_id + AND changed.source_key <> + 'HOSTED_TERMS:environment-boundary/' || NEW.environment_boundary + AND changed.source_key NOT IN ( + SELECT 'HOSTED_TERMS:' || scope.hosted_scope_id::TEXT + FROM account_hosted_terms_scopes scope + WHERE scope.hosted_scope_id IN (predecessor_scope, candidate_scope) + AND scope.current_version_id IS NOT NULL))) THEN + RAISE EXCEPTION 'Updated environment binding requires fully settled exact Draft source change'; + END IF; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_hosted_terms_environment_binding_fence_complete + AFTER INSERT OR UPDATE ON account_hosted_terms_environment_binding_publications + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_fence_complete_guard(); -- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V99__account_control_ui_owner_and_source_guards.sql b/services/account-service/src/main/resources/db/migration/V87__account_control_ui_owner_source_guards.sql similarity index 56% rename from services/account-service/src/main/resources/db/migration/V99__account_control_ui_owner_and_source_guards.sql rename to services/account-service/src/main/resources/db/migration/V87__account_control_ui_owner_source_guards.sql index 758957cbfa..5321fd5b97 100644 --- a/services/account-service/src/main/resources/db/migration/V99__account_control_ui_owner_and_source_guards.sql +++ b/services/account-service/src/main/resources/db/migration/V87__account_control_ui_owner_source_guards.sql @@ -1,108 +1,6 @@ --- Backend preparation only: no route, mounted secret, issuer bean or production activation. --- Credentials belong only to the separate encrypted response table, never to owner evidence. -CREATE SEQUENCE account_control_ui_source_fence START WITH 1; -CREATE TABLE account_control_ui_issuance_operations ( - request_id UUID PRIMARY KEY, - operation_id UUID NOT NULL UNIQUE, - token_jti UUID NOT NULL UNIQUE, - account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), - tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), - caller_workload VARCHAR(256) NOT NULL, - caller_context_id UUID NOT NULL, - request_mac_key_id VARCHAR(32) NOT NULL, - request_digest VARCHAR(64) NOT NULL CHECK (request_digest ~ '^[0-9a-f]{64}$'), - claims_payload BYTEA NOT NULL CHECK (octet_length(claims_payload) BETWEEN 1 AND 16384), - source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), - bundle_payload BYTEA NOT NULL CHECK (octet_length(bundle_payload) BETWEEN 1 AND 131072), - signer_receipt BYTEA NOT NULL CHECK (octet_length(signer_receipt) BETWEEN 1 AND 65536), - issued_at_epoch_second BIGINT NOT NULL CHECK (issued_at_epoch_second > 0), - expires_at_epoch_second BIGINT NOT NULL, - recovery_expires_at TIMESTAMPTZ NOT NULL, - status VARCHAR(16) NOT NULL CHECK (status IN ('PREPARED', 'CANDIDATE', 'COMMITTED', 'FAILED', 'REVOKING', 'REVOKED')), - token_hash VARCHAR(64) UNIQUE CHECK (token_hash ~ '^[0-9a-f]{64}$'), - pending_registry BYTEA, - active_registry BYTEA, - pending_receipt BYTEA, - committed_at TIMESTAMPTZ, - recovery_failed_at TIMESTAMPTZ, - revocation_receipt BYTEA, - created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, - CHECK (expires_at_epoch_second > issued_at_epoch_second - AND expires_at_epoch_second <= issued_at_epoch_second + 300), - CHECK ((status IN ('PREPARED','FAILED') AND token_hash IS NULL AND pending_registry IS NULL - AND active_registry IS NULL AND pending_receipt IS NULL AND committed_at IS NULL) - OR (status = 'CANDIDATE' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL - AND active_registry IS NOT NULL AND pending_receipt IS NULL AND committed_at IS NULL) - OR (status = 'COMMITTED' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL - AND active_registry IS NOT NULL AND pending_receipt IS NOT NULL AND committed_at IS NOT NULL) - OR (status IN ('REVOKING','REVOKED') AND token_hash IS NOT NULL AND pending_registry IS NOT NULL - AND active_registry IS NOT NULL - AND ((pending_receipt IS NULL AND committed_at IS NULL) - OR (pending_receipt IS NOT NULL AND committed_at IS NOT NULL)))), - CHECK ((status IN ('FAILED','REVOKING','REVOKED')) = (recovery_failed_at IS NOT NULL)), - CHECK ((status = 'REVOKED') = (revocation_receipt IS NOT NULL)) -); - -CREATE TABLE account_control_ui_response_envelopes ( - operation_id UUID PRIMARY KEY REFERENCES account_control_ui_issuance_operations(operation_id), - encrypted_response BYTEA NOT NULL CHECK (octet_length(encrypted_response) BETWEEN 1 AND 65536), - owner_binding BYTEA NOT NULL CHECK (octet_length(owner_binding) BETWEEN 1 AND 8192), - recovery_expires_at TIMESTAMPTZ NOT NULL -); - +-- Forward-only source serialization guards for the existing Account Control UI schema. +-- These guards derive exact owner source keys and do not create or backfill authority. -- [jooq ignore start] -ALTER TABLE account_control_ui_issuance_operations - ADD CONSTRAINT account_control_ui_recovery_expiry_bound CHECK ( - recovery_expires_at > to_timestamp(issued_at_epoch_second) - AND recovery_expires_at <= to_timestamp(issued_at_epoch_second + 60) - AND recovery_expires_at <= to_timestamp(expires_at_epoch_second)); - -CREATE FUNCTION account_control_ui_issuance_guard() -RETURNS TRIGGER LANGUAGE plpgsql AS $$ -BEGIN - IF TG_OP = 'DELETE' THEN - RAISE EXCEPTION 'Control-ui issuance evidence cannot be deleted' USING ERRCODE = '23514'; - END IF; - IF (to_jsonb(NEW) - ARRAY['status','token_hash','pending_registry','active_registry', - 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) IS DISTINCT FROM - (to_jsonb(OLD) - ARRAY['status','token_hash','pending_registry','active_registry', - 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) - OR NOT ((OLD.status = 'PREPARED' AND NEW.status = 'CANDIDATE') - OR (OLD.status = 'CANDIDATE' AND NEW.status = 'COMMITTED') - OR (OLD.status = 'PREPARED' AND NEW.status = 'FAILED') - OR (OLD.status IN ('CANDIDATE','COMMITTED') AND NEW.status = 'REVOKING') - OR (OLD.status = 'REVOKING' AND NEW.status = 'REVOKED')) - OR (OLD.status <> 'PREPARED' AND - (NEW.token_hash IS DISTINCT FROM OLD.token_hash - OR NEW.pending_registry IS DISTINCT FROM OLD.pending_registry - OR NEW.active_registry IS DISTINCT FROM OLD.active_registry)) - OR (NEW.status IN ('REVOKING','REVOKED') AND - (NEW.pending_receipt IS DISTINCT FROM OLD.pending_receipt - OR NEW.committed_at IS DISTINCT FROM OLD.committed_at)) - OR (OLD.status = 'REVOKING' AND NEW.recovery_failed_at IS DISTINCT FROM OLD.recovery_failed_at) THEN - RAISE EXCEPTION 'Control-ui original operation or candidate cannot change' USING ERRCODE = '23514'; - END IF; - IF NEW.status = 'COMMITTED' AND NOT EXISTS ( - SELECT 1 FROM account_control_ui_response_envelopes e - WHERE e.operation_id = NEW.operation_id AND e.recovery_expires_at = NEW.recovery_expires_at) THEN - RAISE EXCEPTION 'Protected original control-ui response is absent' USING ERRCODE = '23514'; - END IF; - RETURN NEW; -END; -$$; -CREATE TRIGGER account_control_ui_issuance_immutable - BEFORE UPDATE OR DELETE ON account_control_ui_issuance_operations - FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_guard(); -CREATE TRIGGER account_control_ui_response_immutable - BEFORE UPDATE OR DELETE ON account_control_ui_response_envelopes - FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); -CREATE TRIGGER account_control_ui_issuance_no_truncate - BEFORE TRUNCATE ON account_control_ui_issuance_operations - FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); -CREATE TRIGGER account_control_ui_response_no_truncate - BEFORE TRUNCATE ON account_control_ui_response_envelopes - FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); - -- Derive exact source keys from owner rows, not from caller assertions or broad tenant matching. -- These keys identify serialization only and do not provision authority/baselines. CREATE FUNCTION account_control_ui_source_keys(table_name TEXT, row_value JSONB) diff --git a/services/account-service/src/main/resources/db/migration/V88__account_logout_all_pending_draft_source_changes.sql b/services/account-service/src/main/resources/db/migration/V88__account_logout_all_pending_draft_source_changes.sql new file mode 100644 index 0000000000..e2c34a085d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V88__account_logout_all_pending_draft_source_changes.sql @@ -0,0 +1,295 @@ +-- Logout-all has a richer immutable caller binding than the issuer/tenant V59 journal. +CREATE TABLE account_logout_all_draft_source_changes ( + request_id UUID PRIMARY KEY CHECK (request_id <> '00000000-0000-0000-0000-000000000000'), + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + request_digest_version INTEGER NOT NULL CHECK (request_digest_version = 1), + request_digest BYTEA NOT NULL CHECK (octet_length(request_digest) = 32), + token_profile VARCHAR(32) NOT NULL CHECK (token_profile IN ('control-ui', 'player-bootstrap')), + presented_token_hash BYTEA NOT NULL CHECK (octet_length(presented_token_hash) = 32), + expected_generation BIGINT NOT NULL CHECK (expected_generation > 0), + expected_source_version BIGINT NOT NULL CHECK (expected_source_version > 0), + expected_issuance_fence BIGINT NOT NULL CHECK (expected_issuance_fence > 0), + expected_issuance_fence_source_version BIGINT NOT NULL + CHECK (expected_issuance_fence_source_version > 0), + checkpoint_stream VARCHAR(2048) NOT NULL, + checkpoint_sequence BIGINT NOT NULL CHECK (checkpoint_sequence >= 0), + capture_evidence BYTEA NOT NULL CHECK (octet_length(capture_evidence) > 0), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), + source_change_id UUID NOT NULL UNIQUE + REFERENCES account_draft_authorization_source_changes(change_id) + CHECK (source_change_id <> '00000000-0000-0000-0000-000000000000'), + source_change_request BYTEA NOT NULL CHECK (octet_length(source_change_request) > 0), + source_change_binding BYTEA NOT NULL CHECK (octet_length(source_change_binding) > 0), + status VARCHAR(16) NOT NULL CHECK (status IN ('WAITING', 'SOURCE_COMMITTED')), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + event_stream VARCHAR(2048), + event_sequence BIGINT CHECK (event_sequence > 0), + event_id VARCHAR(128), + event_digest VARCHAR(71), + event_payload BYTEA, + CONSTRAINT account_logout_all_draft_scope_check + CHECK (checkpoint_stream = 'account:auth-authority:v1:account/' || account_uuid::TEXT), + CONSTRAINT account_logout_all_draft_status_check + CHECK ((status = 'WAITING' AND committed_at IS NULL AND event_stream IS NULL + AND event_sequence IS NULL AND event_id IS NULL AND event_digest IS NULL + AND event_payload IS NULL) + OR (status = 'SOURCE_COMMITTED' AND committed_at IS NOT NULL + AND event_stream IS NOT NULL AND event_sequence IS NOT NULL + AND event_id IS NOT NULL AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND event_payload IS NOT NULL AND octet_length(event_payload) > 0)) +); + +-- [jooq ignore start] +-- jOOQ's H2 DDL interpreter maps BYTEA to BLOB, which cannot be indexed there. +-- PostgreSQL still enforces the exact token identity once across pending requests. +CREATE UNIQUE INDEX account_logout_all_draft_source_token_hash_unique + ON account_logout_all_draft_source_changes (presented_token_hash); + +CREATE FUNCTION account_logout_all_draft_frame(value BYTEA) +RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT int4send(octet_length(value)) || value; +$$; + +CREATE FUNCTION account_logout_all_draft_journal_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + expected_request BYTEA; + expected_mutation BYTEA; + expected_evidence BYTEA; + expected_baseline BYTEA; + expected_change BYTEA; + expected_key TEXT; + persisted_uuid UUID; + current_generation BIGINT; + current_source_version BIGINT; + current_fence BIGINT; + current_fence_source_version BIGINT; + current_sequence BIGINT; +BEGIN + IF TG_OP = 'UPDATE' THEN + IF OLD.status <> 'WAITING' OR NEW.status <> 'SOURCE_COMMITTED' + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.token_profile IS DISTINCT FROM OLD.token_profile + OR NEW.presented_token_hash IS DISTINCT FROM OLD.presented_token_hash + OR NEW.expected_generation IS DISTINCT FROM OLD.expected_generation + OR NEW.expected_source_version IS DISTINCT FROM OLD.expected_source_version + OR NEW.expected_issuance_fence IS DISTINCT FROM OLD.expected_issuance_fence + OR NEW.expected_issuance_fence_source_version IS DISTINCT FROM OLD.expected_issuance_fence_source_version + OR NEW.checkpoint_stream IS DISTINCT FROM OLD.checkpoint_stream + OR NEW.checkpoint_sequence IS DISTINCT FROM OLD.checkpoint_sequence + OR NEW.capture_evidence IS DISTINCT FROM OLD.capture_evidence + OR NEW.request_payload IS DISTINCT FROM OLD.request_payload + OR NEW.source_evidence IS DISTINCT FROM OLD.source_evidence + OR NEW.source_change_id IS DISTINCT FROM OLD.source_change_id + OR NEW.source_change_request IS DISTINCT FROM OLD.source_change_request + OR NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Logout-all Draft source intent and original capture are immutable' + USING ERRCODE = '23514'; + END IF; + NEW.committed_at = CURRENT_TIMESTAMP; + ELSE + IF NEW.status <> 'WAITING' THEN + RAISE EXCEPTION 'Logout-all Draft source intent must begin WAITING' + USING ERRCODE = '23514'; + END IF; + SELECT account_uuid INTO persisted_uuid FROM accounts WHERE id = NEW.account_id; + IF persisted_uuid IS DISTINCT FROM NEW.account_uuid THEN + RAISE EXCEPTION 'Logout-all Draft intent Account association does not match' + USING ERRCODE = '23514'; + END IF; + + expected_request := account_logout_all_draft_frame(convert_to('account-logout-all-draft-source-request/v1', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.request_id::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.account_id::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.request_digest_version::TEXT, 'UTF8')) + || account_logout_all_draft_frame(NEW.request_digest) + || account_logout_all_draft_frame(convert_to(NEW.token_profile, 'UTF8')) + || account_logout_all_draft_frame(NEW.presented_token_hash); + expected_evidence := account_logout_all_draft_frame(convert_to('account-draft-source-evidence/v1', 'UTF8')) + || account_logout_all_draft_frame(convert_to('ACCOUNT', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to('PRESENT', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.expected_generation::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.expected_source_version::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to('PRESENT', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.checkpoint_stream, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.checkpoint_sequence::TEXT, 'UTF8')) + || account_logout_all_draft_frame(NEW.capture_evidence); + expected_mutation := account_logout_all_draft_frame(convert_to('account-logout-all-draft-source-mutation/v1', 'UTF8')) + || account_logout_all_draft_frame(NEW.request_payload) + || account_logout_all_draft_frame(convert_to(NEW.expected_generation::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.expected_source_version::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.expected_issuance_fence::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.expected_issuance_fence_source_version::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.checkpoint_sequence::TEXT, 'UTF8')) + || account_logout_all_draft_frame(NEW.source_evidence); + expected_change := account_logout_all_draft_frame(convert_to('account-draft-source-change/v1', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.source_change_id::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to('1', 'UTF8')) + || account_logout_all_draft_frame(NEW.source_evidence) + || account_logout_all_draft_frame(NEW.source_change_request); + expected_key := 'ACCOUNT:' || NEW.account_uuid::TEXT; + IF NEW.request_payload IS DISTINCT FROM expected_request + OR NEW.source_evidence IS DISTINCT FROM expected_evidence + OR NEW.source_change_request IS DISTINCT FROM expected_mutation + OR NEW.source_change_binding IS DISTINCT FROM expected_change + OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_source_changes + WHERE change_id = NEW.source_change_id AND status = 'WAITING' + AND binding = expected_change) + OR (SELECT count(*) FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.source_change_id) <> 1 + OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.source_change_id AND source_key = expected_key) THEN + RAISE EXCEPTION 'Logout-all request must bind its exact V57 Account source intent' + USING ERRCODE = '23514'; + END IF; + + SELECT generation, source_version INTO current_generation, current_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid; + SELECT issuance_fence, source_version INTO current_fence, current_fence_source_version + FROM account_authority_issuance_fences WHERE account_uuid = NEW.account_uuid; + IF current_generation IS DISTINCT FROM NEW.expected_generation + OR current_source_version IS DISTINCT FROM NEW.expected_source_version + OR current_fence IS DISTINCT FROM NEW.expected_issuance_fence + OR current_fence_source_version IS DISTINCT FROM NEW.expected_issuance_fence_source_version THEN + RAISE EXCEPTION 'Logout-all Draft capture differs from current Account source counters' + USING ERRCODE = '23514'; + END IF; + SELECT last_sequence INTO current_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.checkpoint_stream; + IF NEW.checkpoint_sequence = 0 THEN + expected_baseline := account_logout_all_draft_frame(convert_to('account-draft-source-baseline/v1', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8')) + || account_logout_all_draft_frame(convert_to('1', 'UTF8')) + || account_logout_all_draft_frame(convert_to('1', 'UTF8')) + || account_logout_all_draft_frame(convert_to(NEW.checkpoint_stream, 'UTF8')) + || account_logout_all_draft_frame(convert_to('0', 'UTF8')); + IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1 + OR NEW.capture_evidence IS DISTINCT FROM expected_baseline + OR (current_sequence IS NOT NULL AND current_sequence <> 0) + OR EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.checkpoint_stream) THEN + RAISE EXCEPTION 'Logout-all zero checkpoint lacks exact pristine source evidence' + USING ERRCODE = '23514'; + END IF; + ELSIF current_sequence IS DISTINCT FROM NEW.checkpoint_sequence + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.checkpoint_stream + AND outbox_sequence = NEW.checkpoint_sequence + AND payload = NEW.capture_evidence) THEN + RAISE EXCEPTION 'Logout-all capture does not bind the exact current Account event' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_logout_all_draft_link_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + journal account_logout_all_draft_source_changes%ROWTYPE; + source_status TEXT; + source_binding BYTEA; + selected_change UUID; + persisted_generation BIGINT; + persisted_source_version BIGINT; + persisted_fence BIGINT; + persisted_fence_source_version BIGINT; +BEGIN + IF TG_TABLE_NAME = 'account_logout_all_draft_source_changes' THEN + selected_change := NEW.source_change_id; + ELSE + selected_change := NEW.change_id; + END IF; + SELECT * INTO journal FROM account_logout_all_draft_source_changes + WHERE source_change_id = selected_change; + IF NOT FOUND THEN + RETURN NULL; + END IF; + SELECT status, binding INTO source_status, source_binding + FROM account_draft_authorization_source_changes WHERE change_id = selected_change; + IF source_status IS DISTINCT FROM journal.status + OR source_binding IS DISTINCT FROM journal.source_change_binding THEN + RAISE EXCEPTION 'Logout-all journal and V57 Account source transition must commit together' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'WAITING' AND EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = journal.checkpoint_stream + AND request_id = journal.request_id::TEXT) THEN + RAISE EXCEPTION 'A WAITING logout-all request cannot publish its source event' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'SOURCE_COMMITTED' AND ( + journal.event_stream IS DISTINCT FROM journal.checkpoint_stream + OR journal.event_id IS DISTINCT FROM 'account-logout-all-event-v1:' || journal.request_id::TEXT + OR journal.event_sequence IS DISTINCT FROM journal.checkpoint_sequence + 1 + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = journal.event_stream AND outbox_sequence = journal.event_sequence + AND request_id = journal.request_id::TEXT AND event_id = journal.event_id + AND event_digest = journal.event_digest AND payload = journal.event_payload) + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_streams + WHERE outbox_stream_key = journal.event_stream AND last_sequence = journal.event_sequence) + OR NOT EXISTS (SELECT 1 FROM account_logout_all_operation_receipts + WHERE request_id = journal.request_id AND account_id = journal.account_id + AND account_uuid = journal.account_uuid + AND request_digest_version = journal.request_digest_version + AND request_digest = journal.request_digest AND token_profile = journal.token_profile + AND presented_token_hash = journal.presented_token_hash + AND outbox_stream_key = journal.event_stream + AND outbox_sequence = journal.event_sequence + AND event_id = journal.event_id AND event_digest = journal.event_digest + AND account_authority_generation = journal.expected_generation + 1 + AND account_source_version = journal.expected_source_version + 1 + AND issuance_fence = journal.expected_issuance_fence + 1 + AND issuance_fence_source_version = journal.expected_issuance_fence_source_version + 1)) THEN + RAISE EXCEPTION 'Committed logout-all intent lacks its exact receipt, event, or checkpoint' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'SOURCE_COMMITTED' THEN + SELECT generation, source_version INTO persisted_generation, persisted_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = journal.account_uuid; + SELECT issuance_fence, source_version INTO persisted_fence, persisted_fence_source_version + FROM account_authority_issuance_fences WHERE account_uuid = journal.account_uuid; + IF persisted_generation IS DISTINCT FROM journal.expected_generation + 1 + OR persisted_source_version IS DISTINCT FROM journal.expected_source_version + 1 + OR persisted_fence IS DISTINCT FROM journal.expected_issuance_fence + 1 + OR persisted_fence_source_version + IS DISTINCT FROM journal.expected_issuance_fence_source_version + 1 THEN + RAISE EXCEPTION 'Logout-all Account authority counters did not advance once from capture' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_logout_all_draft_source_request_guard + BEFORE INSERT OR UPDATE ON account_logout_all_draft_source_changes + FOR EACH ROW EXECUTE FUNCTION account_logout_all_draft_journal_guard(); +CREATE TRIGGER account_logout_all_draft_source_delete_guard + BEFORE DELETE ON account_logout_all_draft_source_changes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_logout_all_draft_source_truncate_guard + BEFORE TRUNCATE ON account_logout_all_draft_source_changes + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE CONSTRAINT TRIGGER account_logout_all_draft_source_complete_guard + AFTER INSERT OR UPDATE ON account_logout_all_draft_source_changes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_logout_all_draft_link_guard(); +CREATE CONSTRAINT TRIGGER account_logout_all_draft_source_v57_link_guard + AFTER INSERT OR UPDATE ON account_draft_authorization_source_changes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_logout_all_draft_link_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql b/services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql new file mode 100644 index 0000000000..3ea00737b6 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql @@ -0,0 +1,381 @@ +-- V89 persists exact password-reset source intent while V76 owner outcomes settle. +CREATE TABLE account_password_reset_draft_source_changes ( + token_hash BYTEA NOT NULL CHECK (octet_length(token_hash) = 32), + account_id BIGINT NOT NULL REFERENCES accounts(id) ON DELETE RESTRICT, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid) ON DELETE RESTRICT, + account_uuid_provenance VARCHAR(40) NOT NULL, + account_uuid_source_numeric_id BIGINT NOT NULL CHECK (account_uuid_source_numeric_id > 0), + token_id BIGINT NOT NULL CHECK (token_id > 0), + request_id VARCHAR(128) NOT NULL UNIQUE, + event_id VARCHAR(128) NOT NULL UNIQUE, + request_digest_version INTEGER NOT NULL CHECK (request_digest_version = 1), + request_digest BYTEA NOT NULL CHECK (octet_length(request_digest) = 32), + password_verifier VARCHAR(255) CHECK (password_verifier IS NULL OR length(btrim(password_verifier)) > 0), + password_verifier_digest BYTEA NOT NULL CHECK (octet_length(password_verifier_digest) = 32), + token_expires_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, + token_expires_epoch_nanos BIGINT NOT NULL CHECK (token_expires_epoch_nanos > 0), + expected_generation BIGINT NOT NULL CHECK (expected_generation > 0), + expected_source_version BIGINT NOT NULL CHECK (expected_source_version > 0), + expected_issuance_fence BIGINT NOT NULL CHECK (expected_issuance_fence > 0), + expected_issuance_fence_source_version BIGINT NOT NULL + CHECK (expected_issuance_fence_source_version > 0), + checkpoint_stream VARCHAR(2048) NOT NULL, + checkpoint_sequence BIGINT NOT NULL CHECK (checkpoint_sequence >= 0), + capture_evidence BYTEA NOT NULL CHECK (octet_length(capture_evidence) > 0), + request_payload BYTEA NOT NULL CHECK (octet_length(request_payload) > 0), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), + source_change_id UUID NOT NULL UNIQUE + REFERENCES account_draft_authorization_source_changes(change_id) + CHECK (source_change_id <> '00000000-0000-0000-0000-000000000000'::UUID), + source_change_request BYTEA NOT NULL CHECK (octet_length(source_change_request) > 0), + source_change_binding BYTEA NOT NULL CHECK (octet_length(source_change_binding) > 0), + status VARCHAR(16) NOT NULL CHECK (status IN ('WAITING', 'SOURCE_COMMITTED', 'SOURCE_ABORTED')), + abort_reason VARCHAR(32) CHECK (abort_reason IN ('EXPIRED', 'DEFINITIVE_ABORT')), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + committed_at TIMESTAMPTZ, + aborted_at TIMESTAMPTZ, + event_stream VARCHAR(2048), + event_sequence BIGINT CHECK (event_sequence > 0), + event_digest VARCHAR(71), + event_payload BYTEA, + CONSTRAINT account_password_reset_draft_identity_check + CHECK (account_id > 0 AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_uuid_source_numeric_id = account_id + AND request_id = 'account-password-reset-request-v1:' || encode(token_hash, 'hex') + AND event_id = 'account-password-reset-event-v1:' || encode(token_hash, 'hex')), + CONSTRAINT account_password_reset_draft_scope_check + CHECK (checkpoint_stream = 'account:auth-authority:v1:account/' || account_uuid::TEXT), + CONSTRAINT account_password_reset_draft_status_check + CHECK ((status = 'WAITING' AND abort_reason IS NULL AND committed_at IS NULL + AND aborted_at IS NULL AND event_stream IS NULL AND event_sequence IS NULL + AND event_digest IS NULL AND event_payload IS NULL AND password_verifier IS NOT NULL) + OR (status = 'SOURCE_COMMITTED' AND abort_reason IS NULL AND committed_at IS NOT NULL + AND aborted_at IS NULL AND event_stream IS NOT NULL AND event_sequence IS NOT NULL + AND event_digest ~ '^sha256:[0-9a-f]{64}$' + AND event_payload IS NOT NULL AND octet_length(event_payload) > 0 + AND password_verifier IS NULL) + OR (status = 'SOURCE_ABORTED' AND abort_reason IS NOT NULL AND committed_at IS NULL + AND aborted_at IS NOT NULL AND event_stream IS NULL AND event_sequence IS NULL + AND event_digest IS NULL AND event_payload IS NULL AND password_verifier IS NULL)) +); + +-- [jooq ignore start] +-- PostgreSQL supports the BYTEA key; jOOQ's H2 DDL interpreter cannot index its BLOB mapping. +ALTER TABLE account_password_reset_draft_source_changes + ADD CONSTRAINT account_password_reset_draft_source_changes_pk PRIMARY KEY (token_hash); + +CREATE FUNCTION account_password_reset_draft_frame(value BYTEA) +RETURNS BYTEA LANGUAGE SQL IMMUTABLE STRICT AS $$ + SELECT int4send(octet_length(value)) || value; +$$; + +CREATE FUNCTION account_password_reset_draft_journal_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + expected_request BYTEA; + expected_mutation BYTEA; + expected_evidence BYTEA; + expected_baseline BYTEA; + expected_change BYTEA; + expected_key TEXT; + persisted_uuid UUID; + persisted_provenance TEXT; + persisted_source_id BIGINT; + token_account BIGINT; + token_deadline TIMESTAMP WITHOUT TIME ZONE; + current_generation BIGINT; + current_source_version BIGINT; + current_fence BIGINT; + current_fence_source_version BIGINT; + current_sequence BIGINT; +BEGIN + IF TG_OP = 'UPDATE' THEN + IF OLD.status <> 'WAITING' OR NEW.status NOT IN ('SOURCE_COMMITTED', 'SOURCE_ABORTED') + OR NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.account_id IS DISTINCT FROM OLD.account_id + OR NEW.account_uuid IS DISTINCT FROM OLD.account_uuid + OR NEW.account_uuid_provenance IS DISTINCT FROM OLD.account_uuid_provenance + OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM OLD.account_uuid_source_numeric_id + OR NEW.token_id IS DISTINCT FROM OLD.token_id + OR NEW.request_id IS DISTINCT FROM OLD.request_id + OR NEW.event_id IS DISTINCT FROM OLD.event_id + OR NEW.request_digest_version IS DISTINCT FROM OLD.request_digest_version + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.password_verifier IS DISTINCT FROM OLD.password_verifier + OR NEW.password_verifier_digest IS DISTINCT FROM OLD.password_verifier_digest + OR NEW.token_expires_at IS DISTINCT FROM OLD.token_expires_at + OR NEW.token_expires_epoch_nanos IS DISTINCT FROM OLD.token_expires_epoch_nanos + OR NEW.expected_generation IS DISTINCT FROM OLD.expected_generation + OR NEW.expected_source_version IS DISTINCT FROM OLD.expected_source_version + OR NEW.expected_issuance_fence IS DISTINCT FROM OLD.expected_issuance_fence + OR NEW.expected_issuance_fence_source_version IS DISTINCT FROM OLD.expected_issuance_fence_source_version + OR NEW.checkpoint_stream IS DISTINCT FROM OLD.checkpoint_stream + OR NEW.checkpoint_sequence IS DISTINCT FROM OLD.checkpoint_sequence + OR NEW.capture_evidence IS DISTINCT FROM OLD.capture_evidence + OR NEW.request_payload IS DISTINCT FROM OLD.request_payload + OR NEW.source_evidence IS DISTINCT FROM OLD.source_evidence + OR NEW.source_change_id IS DISTINCT FROM OLD.source_change_id + OR NEW.source_change_request IS DISTINCT FROM OLD.source_change_request + OR NEW.source_change_binding IS DISTINCT FROM OLD.source_change_binding + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'Password-reset Draft source intent and original capture are immutable' + USING ERRCODE = '23514'; + END IF; + IF NEW.status = 'SOURCE_COMMITTED' THEN + IF NEW.abort_reason IS NOT NULL OR NEW.aborted_at IS NOT NULL + OR NEW.event_stream IS NULL OR NEW.event_sequence IS NULL + OR NEW.event_id IS DISTINCT FROM OLD.event_id + OR NEW.event_digest IS NULL OR NEW.event_payload IS NULL THEN + RAISE EXCEPTION 'Committed password-reset source result is incomplete' + USING ERRCODE = '23514'; + END IF; + NEW.committed_at = CURRENT_TIMESTAMP; + ELSE + IF NEW.abort_reason NOT IN ('EXPIRED', 'DEFINITIVE_ABORT') + OR NEW.event_stream IS NOT NULL OR NEW.event_sequence IS NOT NULL + OR NEW.event_digest IS NOT NULL OR NEW.event_payload IS NOT NULL THEN + RAISE EXCEPTION 'Aborted password-reset source result must contain no mutation' + USING ERRCODE = '23514'; + END IF; + NEW.aborted_at = CURRENT_TIMESTAMP; + END IF; + NEW.password_verifier = NULL; + RETURN NEW; + END IF; + + IF NEW.status <> 'WAITING' OR NEW.abort_reason IS NOT NULL + OR NEW.committed_at IS NOT NULL OR NEW.aborted_at IS NOT NULL + OR NEW.event_stream IS NOT NULL OR NEW.event_sequence IS NOT NULL + OR NEW.event_digest IS NOT NULL OR NEW.event_payload IS NOT NULL THEN + RAISE EXCEPTION 'Password-reset Draft source intent must begin WAITING' + USING ERRCODE = '23514'; + END IF; + + SELECT account_uuid, account_uuid_provenance, account_uuid_source_numeric_id + INTO persisted_uuid, persisted_provenance, persisted_source_id + FROM accounts WHERE id = NEW.account_id; + IF persisted_uuid IS DISTINCT FROM NEW.account_uuid + OR persisted_provenance IS DISTINCT FROM NEW.account_uuid_provenance + OR persisted_source_id IS DISTINCT FROM NEW.account_uuid_source_numeric_id + OR NEW.account_uuid_source_numeric_id IS DISTINCT FROM NEW.account_id THEN + RAISE EXCEPTION 'Password-reset Draft intent Account identity differs from persisted source' + USING ERRCODE = '23514'; + END IF; + SELECT account_id, expires_at INTO token_account, token_deadline + FROM password_reset_token WHERE id = NEW.token_id; + IF token_account IS DISTINCT FROM NEW.account_id OR token_deadline IS DISTINCT FROM NEW.token_expires_at + OR NEW.token_expires_epoch_nanos IS DISTINCT FROM + ((extract(epoch FROM (NEW.token_expires_at AT TIME ZONE 'UTC')) * 1000000000)::numeric)::bigint THEN + RAISE EXCEPTION 'Password-reset Draft intent does not bind its exact token row and deadline' + USING ERRCODE = '23514'; + END IF; + + expected_request := account_password_reset_draft_frame(convert_to('account-password-reset-draft-source-request/v1', 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.request_id, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.account_id::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.token_id::TEXT, 'UTF8')) + || account_password_reset_draft_frame(NEW.token_hash) + || account_password_reset_draft_frame(convert_to(NEW.token_expires_epoch_nanos::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to('1', 'UTF8')) + || account_password_reset_draft_frame(NEW.request_digest) + || account_password_reset_draft_frame(NEW.password_verifier_digest) + || account_password_reset_draft_frame(convert_to(NEW.account_uuid_provenance, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.account_uuid_source_numeric_id::TEXT, 'UTF8')); + expected_evidence := account_password_reset_draft_frame(convert_to('account-draft-source-evidence/v1', 'UTF8')) + || account_password_reset_draft_frame(convert_to('ACCOUNT', 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to('PRESENT', 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.expected_generation::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.expected_source_version::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to('PRESENT', 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.checkpoint_stream, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.checkpoint_sequence::TEXT, 'UTF8')) + || account_password_reset_draft_frame(NEW.capture_evidence); + expected_mutation := account_password_reset_draft_frame(convert_to('account-password-reset-draft-source-mutation/v1', 'UTF8')) + || account_password_reset_draft_frame(NEW.request_payload) + || account_password_reset_draft_frame(convert_to(NEW.expected_generation::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.expected_source_version::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.expected_issuance_fence::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.expected_issuance_fence_source_version::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.checkpoint_sequence::TEXT, 'UTF8')) + || account_password_reset_draft_frame(NEW.source_evidence) + || account_password_reset_draft_frame(convert_to((NEW.expected_generation + 1)::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to((NEW.expected_source_version + 1)::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to((NEW.expected_issuance_fence + 1)::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to((NEW.expected_issuance_fence_source_version + 1)::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to((NEW.checkpoint_sequence + 1)::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.request_id, 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.event_id, 'UTF8')); + expected_change := account_password_reset_draft_frame(convert_to('account-draft-source-change/v1', 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.source_change_id::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to('1', 'UTF8')) + || account_password_reset_draft_frame(NEW.source_evidence) + || account_password_reset_draft_frame(NEW.source_change_request); + expected_key := 'ACCOUNT:' || NEW.account_uuid::TEXT; + IF NEW.request_id IS DISTINCT FROM 'account-password-reset-request-v1:' || encode(NEW.token_hash, 'hex') + OR NEW.event_id IS DISTINCT FROM 'account-password-reset-event-v1:' || encode(NEW.token_hash, 'hex') + OR NEW.checkpoint_stream IS DISTINCT FROM 'account:auth-authority:v1:account/' || NEW.account_uuid::TEXT + OR NEW.request_payload IS DISTINCT FROM expected_request + OR NEW.source_evidence IS DISTINCT FROM expected_evidence + OR NEW.source_change_request IS DISTINCT FROM expected_mutation + OR NEW.source_change_binding IS DISTINCT FROM expected_change + OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_source_changes + WHERE change_id = NEW.source_change_id AND status = 'WAITING' AND binding = expected_change) + OR (SELECT count(*) FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.source_change_id) <> 1 + OR NOT EXISTS (SELECT 1 FROM account_draft_authorization_changed_scopes + WHERE change_id = NEW.source_change_id AND source_key = expected_key) THEN + RAISE EXCEPTION 'Password-reset request must bind its exact V76 Account source intent' + USING ERRCODE = '23514'; + END IF; + + SELECT generation, source_version INTO current_generation, current_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = NEW.account_uuid; + SELECT issuance_fence, source_version INTO current_fence, current_fence_source_version + FROM account_authority_issuance_fences WHERE account_uuid = NEW.account_uuid; + IF current_generation IS DISTINCT FROM NEW.expected_generation + OR current_source_version IS DISTINCT FROM NEW.expected_source_version + OR current_fence IS DISTINCT FROM NEW.expected_issuance_fence + OR current_fence_source_version IS DISTINCT FROM NEW.expected_issuance_fence_source_version THEN + RAISE EXCEPTION 'Password-reset Draft capture differs from current Account source counters' + USING ERRCODE = '23514'; + END IF; + SELECT last_sequence INTO current_sequence FROM account_authority_outbox_streams + WHERE outbox_stream_key = NEW.checkpoint_stream; + IF NEW.checkpoint_sequence = 0 THEN + expected_baseline := account_password_reset_draft_frame(convert_to('account-draft-source-baseline/v1', 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.account_uuid::TEXT, 'UTF8')) + || account_password_reset_draft_frame(convert_to('1', 'UTF8')) + || account_password_reset_draft_frame(convert_to('1', 'UTF8')) + || account_password_reset_draft_frame(convert_to(NEW.checkpoint_stream, 'UTF8')) + || account_password_reset_draft_frame(convert_to('0', 'UTF8')); + IF NEW.expected_generation <> 1 OR NEW.expected_source_version <> 1 + OR NEW.capture_evidence IS DISTINCT FROM expected_baseline + OR (current_sequence IS NOT NULL AND current_sequence <> 0) + OR EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.checkpoint_stream) THEN + RAISE EXCEPTION 'Password-reset zero checkpoint lacks exact pristine source evidence' + USING ERRCODE = '23514'; + END IF; + ELSIF current_sequence IS DISTINCT FROM NEW.checkpoint_sequence + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = NEW.checkpoint_stream + AND outbox_sequence = NEW.checkpoint_sequence + AND payload = NEW.capture_evidence) THEN + RAISE EXCEPTION 'Password-reset capture does not bind the exact current Account event' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_password_reset_draft_link_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + journal account_password_reset_draft_source_changes%ROWTYPE; + source_status TEXT; + source_binding BYTEA; + selected_change UUID; + persisted_generation BIGINT; + persisted_source_version BIGINT; + persisted_fence BIGINT; + persisted_fence_source_version BIGINT; +BEGIN + IF TG_TABLE_NAME = 'account_password_reset_draft_source_changes' THEN + selected_change := NEW.source_change_id; + ELSE + selected_change := NEW.change_id; + END IF; + SELECT * INTO journal FROM account_password_reset_draft_source_changes + WHERE source_change_id = selected_change; + IF NOT FOUND THEN + RETURN NULL; + END IF; + SELECT status, binding INTO source_status, source_binding + FROM account_draft_authorization_source_changes WHERE change_id = selected_change; + IF source_status IS DISTINCT FROM journal.status OR source_binding IS DISTINCT FROM journal.source_change_binding THEN + RAISE EXCEPTION 'Password-reset journal and V76 source transition must commit together' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'WAITING' AND ( + EXISTS (SELECT 1 FROM account_password_reset_operation_receipts WHERE token_hash = journal.token_hash) + OR EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = journal.checkpoint_stream AND request_id = journal.request_id)) THEN + RAISE EXCEPTION 'WAITING password-reset intent cannot publish or complete its receipt' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'SOURCE_ABORTED' AND ( + EXISTS (SELECT 1 FROM account_password_reset_operation_receipts WHERE token_hash = journal.token_hash) + OR EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = journal.checkpoint_stream AND request_id = journal.request_id)) THEN + RAISE EXCEPTION 'Aborted password-reset intent cannot contain a source mutation' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'SOURCE_COMMITTED' AND ( + journal.event_stream IS DISTINCT FROM journal.checkpoint_stream + OR journal.event_id IS DISTINCT FROM 'account-password-reset-event-v1:' || encode(journal.token_hash, 'hex') + OR journal.event_sequence IS DISTINCT FROM journal.checkpoint_sequence + 1 + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_events + WHERE outbox_stream_key = journal.event_stream AND outbox_sequence = journal.event_sequence + AND request_id = journal.request_id AND event_id = journal.event_id + AND event_digest = journal.event_digest AND payload = journal.event_payload) + OR NOT EXISTS (SELECT 1 FROM account_authority_outbox_streams + WHERE outbox_stream_key = journal.event_stream AND last_sequence = journal.event_sequence) + OR NOT EXISTS (SELECT 1 FROM account_password_reset_operation_receipts + WHERE token_hash = journal.token_hash AND account_id = journal.account_id + AND account_uuid = journal.account_uuid AND request_id = journal.request_id + AND request_digest_version = journal.request_digest_version + AND request_digest = journal.request_digest + AND token_expires_at = journal.token_expires_at + AND password_verifier_digest = journal.password_verifier_digest + AND outbox_stream_key = journal.event_stream AND outbox_sequence = journal.event_sequence + AND event_id = journal.event_id AND event_digest = journal.event_digest + AND account_authority_generation = journal.expected_generation + 1 + AND account_source_version = journal.expected_source_version + 1 + AND issuance_fence = journal.expected_issuance_fence + 1 + AND issuance_fence_source_version = journal.expected_issuance_fence_source_version + 1) + OR EXISTS (SELECT 1 FROM password_reset_token WHERE id = journal.token_id) + OR NOT EXISTS (SELECT 1 FROM accounts WHERE id = journal.account_id + AND account_uuid = journal.account_uuid + AND sha256(convert_to(password_hash, 'UTF8')) = journal.password_verifier_digest)) THEN + RAISE EXCEPTION 'Committed password-reset intent lacks exact receipt, event, token, or Account readback' + USING ERRCODE = '23514'; + END IF; + IF journal.status = 'SOURCE_COMMITTED' THEN + SELECT generation, source_version INTO persisted_generation, persisted_source_version + FROM account_authority_generations + WHERE scope_kind = 'ACCOUNT' AND account_uuid = journal.account_uuid; + SELECT issuance_fence, source_version INTO persisted_fence, persisted_fence_source_version + FROM account_authority_issuance_fences WHERE account_uuid = journal.account_uuid; + IF persisted_generation IS DISTINCT FROM journal.expected_generation + 1 + OR persisted_source_version IS DISTINCT FROM journal.expected_source_version + 1 + OR persisted_fence IS DISTINCT FROM journal.expected_issuance_fence + 1 + OR persisted_fence_source_version IS DISTINCT FROM journal.expected_issuance_fence_source_version + 1 THEN + RAISE EXCEPTION 'Password-reset Account authority counters did not advance once from capture' + USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_password_reset_draft_journal_guard + BEFORE INSERT OR UPDATE ON account_password_reset_draft_source_changes + FOR EACH ROW EXECUTE FUNCTION account_password_reset_draft_journal_guard(); +CREATE TRIGGER account_password_reset_draft_delete_guard + BEFORE DELETE ON account_password_reset_draft_source_changes + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_password_reset_draft_truncate_guard + BEFORE TRUNCATE ON account_password_reset_draft_source_changes + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE CONSTRAINT TRIGGER account_password_reset_draft_complete_guard + AFTER INSERT OR UPDATE ON account_password_reset_draft_source_changes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_password_reset_draft_link_guard(); +CREATE CONSTRAINT TRIGGER account_password_reset_draft_v76_link_guard + AFTER INSERT OR UPDATE ON account_draft_authorization_source_changes + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_password_reset_draft_link_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql b/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql new file mode 100644 index 0000000000..3371d9d86a --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql @@ -0,0 +1,119 @@ +CREATE SEQUENCE account_control_ui_source_fence START WITH 1; + +CREATE TABLE account_control_ui_issuance_operations ( + request_id UUID PRIMARY KEY, + operation_id UUID NOT NULL UNIQUE, + token_jti UUID NOT NULL UNIQUE, + account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + caller_workload VARCHAR(256) NOT NULL, + caller_context_id UUID NOT NULL, + request_mac_key_id VARCHAR(32) NOT NULL, + request_digest VARCHAR(64) NOT NULL CHECK (request_digest ~ '^[0-9a-f]{64}$'), + claims_payload BYTEA NOT NULL CHECK (octet_length(claims_payload) BETWEEN 1 AND 16384), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + bundle_payload BYTEA NOT NULL CHECK (octet_length(bundle_payload) BETWEEN 1 AND 131072), + signer_receipt BYTEA NOT NULL CHECK (octet_length(signer_receipt) BETWEEN 1 AND 65536), + issued_at_epoch_second BIGINT NOT NULL CHECK (issued_at_epoch_second > 0), + expires_at_epoch_second BIGINT NOT NULL, + recovery_expires_at TIMESTAMPTZ NOT NULL, + status VARCHAR(16) NOT NULL CHECK (status IN ('PREPARED', 'CANDIDATE', 'COMMITTED', 'FAILED', 'REVOKING', 'REVOKED')), + token_hash VARCHAR(64) UNIQUE CHECK (token_hash ~ '^[0-9a-f]{64}$'), + pending_registry BYTEA, + active_registry BYTEA, + pending_receipt BYTEA, + committed_at TIMESTAMPTZ, + recovery_failed_at TIMESTAMPTZ, + revocation_receipt BYTEA, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (expires_at_epoch_second > issued_at_epoch_second + AND expires_at_epoch_second <= issued_at_epoch_second + 300), + CHECK ((status IN ('PREPARED','FAILED') AND token_hash IS NULL AND pending_registry IS NULL + AND active_registry IS NULL AND pending_receipt IS NULL AND committed_at IS NULL) + OR (status = 'CANDIDATE' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL AND pending_receipt IS NULL AND committed_at IS NULL) + OR (status = 'COMMITTED' AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL AND pending_receipt IS NOT NULL AND committed_at IS NOT NULL) + OR (status IN ('REVOKING','REVOKED') AND token_hash IS NOT NULL AND pending_registry IS NOT NULL + AND active_registry IS NOT NULL + AND ((pending_receipt IS NULL AND committed_at IS NULL) + OR (pending_receipt IS NOT NULL AND committed_at IS NOT NULL)))), + CHECK ((status IN ('FAILED','REVOKING','REVOKED')) = (recovery_failed_at IS NOT NULL)), + CHECK ((status = 'REVOKED') = (revocation_receipt IS NOT NULL)) +); + +CREATE TABLE account_control_ui_response_envelopes ( + operation_id UUID PRIMARY KEY REFERENCES account_control_ui_issuance_operations(operation_id), + encrypted_response BYTEA NOT NULL CHECK (octet_length(encrypted_response) BETWEEN 1 AND 65536), + owner_binding BYTEA NOT NULL CHECK (octet_length(owner_binding) BETWEEN 1 AND 8192), + recovery_expires_at TIMESTAMPTZ NOT NULL +); + +-- [jooq ignore start] +ALTER TABLE account_control_ui_issuance_operations + ADD CONSTRAINT account_control_ui_recovery_expiry_bound CHECK ( + recovery_expires_at > to_timestamp(issued_at_epoch_second) + AND recovery_expires_at <= to_timestamp(issued_at_epoch_second + 60) + AND recovery_expires_at <= to_timestamp(expires_at_epoch_second)); + +CREATE FUNCTION account_control_ui_issuance_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Control-ui issuance evidence cannot be deleted' USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['status','token_hash','pending_registry','active_registry', + 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['status','token_hash','pending_registry','active_registry', + 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) + OR NOT ((OLD.status = 'PREPARED' AND NEW.status = 'CANDIDATE') + OR (OLD.status = 'CANDIDATE' AND NEW.status = 'COMMITTED') + OR (OLD.status = 'PREPARED' AND NEW.status = 'FAILED') + OR (OLD.status IN ('CANDIDATE','COMMITTED') AND NEW.status = 'REVOKING') + OR (OLD.status = 'REVOKING' AND NEW.status = 'REVOKED')) + OR (OLD.status <> 'PREPARED' AND + (NEW.token_hash IS DISTINCT FROM OLD.token_hash + OR NEW.pending_registry IS DISTINCT FROM OLD.pending_registry + OR NEW.active_registry IS DISTINCT FROM OLD.active_registry)) + OR (NEW.status IN ('REVOKING','REVOKED') AND + (NEW.pending_receipt IS DISTINCT FROM OLD.pending_receipt + OR NEW.committed_at IS DISTINCT FROM OLD.committed_at)) + OR (OLD.status = 'REVOKING' AND NEW.recovery_failed_at IS DISTINCT FROM OLD.recovery_failed_at) THEN + RAISE EXCEPTION 'Control-ui original operation or candidate cannot change' USING ERRCODE = '23514'; + END IF; + IF NEW.status = 'COMMITTED' AND NOT EXISTS ( + SELECT 1 FROM account_control_ui_response_envelopes e + WHERE e.operation_id = NEW.operation_id AND e.recovery_expires_at = NEW.recovery_expires_at) THEN + RAISE EXCEPTION 'Protected original control-ui response is absent' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_control_ui_issuance_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-ui issuance evidence cannot be truncated' USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION account_control_ui_response_immutable_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Control-ui response evidence is immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_control_ui_issuance_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_guard(); +CREATE TRIGGER account_control_ui_issuance_no_truncate + BEFORE TRUNCATE ON account_control_ui_issuance_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_issuance_no_truncate(); +CREATE TRIGGER account_control_ui_response_immutable + BEFORE UPDATE OR DELETE ON account_control_ui_response_envelopes + FOR EACH ROW EXECUTE FUNCTION account_control_ui_response_immutable_guard(); +CREATE TRIGGER account_control_ui_response_no_truncate + BEFORE TRUNCATE ON account_control_ui_response_envelopes + FOR EACH STATEMENT EXECUTE FUNCTION account_control_ui_response_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V103__account_selected_publication_authorization.sql b/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V103__account_selected_publication_authorization.sql rename to services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql diff --git a/services/account-service/src/main/resources/db/migration/V106__account_publication_pre_freeze_order.sql b/services/account-service/src/main/resources/db/migration/V92__account_publication_pre_freeze_order.sql similarity index 72% rename from services/account-service/src/main/resources/db/migration/V106__account_publication_pre_freeze_order.sql rename to services/account-service/src/main/resources/db/migration/V92__account_publication_pre_freeze_order.sql index e92e4ea5dd..dd79acb039 100644 --- a/services/account-service/src/main/resources/db/migration/V106__account_publication_pre_freeze_order.sql +++ b/services/account-service/src/main/resources/db/migration/V92__account_publication_pre_freeze_order.sql @@ -1,5 +1,5 @@ -- The Account publication order is acquired from the authenticated immutable Draft selection --- before World capture. Existing V103 World evidence remains retained and immutable; new orders +-- before World capture. Existing World evidence remains retained and immutable; new orders -- leave the optional later-correlation evidence absent. ALTER TABLE account_selected_publication_authorizations ALTER COLUMN world_evidence DROP NOT NULL; diff --git a/services/account-service/src/main/resources/db/migration/V107__account_selected_publication_settlement.sql b/services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql similarity index 98% rename from services/account-service/src/main/resources/db/migration/V107__account_selected_publication_settlement.sql rename to services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql index 661d7c34c7..d324037ee3 100644 --- a/services/account-service/src/main/resources/db/migration/V107__account_selected_publication_settlement.sql +++ b/services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql @@ -148,7 +148,7 @@ RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ WHERE s.operation_id = operation_value AND s.account_binding = a.binding AND s.fence_id = a.fence_id); $$; --- Keep every V103 Draft/order/source/terms guard and change only publication pending detection. +-- Keep every V107 Draft/order/source/terms guard and change only publication pending detection. DO $migration$ DECLARE original TEXT; @@ -157,7 +157,7 @@ BEGIN SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN - RAISE EXCEPTION 'Expected exactly one V103 pending publication guard'; + RAISE EXCEPTION 'Expected exactly one V107 pending publication guard'; END IF; EXECUTE replace(original, anchor, ' IF NOT account_selected_publication_is_settled(operation_value) THEN' || chr(10) diff --git a/services/account-service/src/main/resources/db/migration/V108__selected_publication_inventory_v2.sql b/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V108__selected_publication_inventory_v2.sql rename to services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql diff --git a/services/account-service/src/main/resources/db/migration/V109__game_logic_intake_authorization.sql b/services/account-service/src/main/resources/db/migration/V95__game_logic_intake_authorization.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V109__game_logic_intake_authorization.sql rename to services/account-service/src/main/resources/db/migration/V95__game_logic_intake_authorization.sql diff --git a/services/account-service/src/main/resources/db/migration/V111__game_logic_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V111__game_logic_intake_terminal_settlement.sql rename to services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql diff --git a/services/account-service/src/main/resources/db/migration/V112__game_logic_intake_source_read_reservation.sql b/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V112__game_logic_intake_source_read_reservation.sql rename to services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql diff --git a/services/account-service/src/main/resources/db/migration/V101__account_hosted_terms_disclosure_handoffs.sql b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql similarity index 94% rename from services/account-service/src/main/resources/db/migration/V101__account_hosted_terms_disclosure_handoffs.sql rename to services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql index cc90a0c8f7..115b0f57ba 100644 --- a/services/account-service/src/main/resources/db/migration/V101__account_hosted_terms_disclosure_handoffs.sql +++ b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql @@ -148,4 +148,10 @@ CREATE TRIGGER account_hosted_terms_disclosure_sources_immutable CREATE TRIGGER account_hosted_terms_disclosure_sources_insert_phase BEFORE INSERT ON account_hosted_terms_disclosure_sources FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_disclosure_source_insert_guard(); +CREATE TRIGGER account_hosted_terms_disclosure_handoffs_no_truncate + BEFORE TRUNCATE ON account_hosted_terms_disclosure_handoffs + FOR EACH STATEMENT EXECUTE FUNCTION account_hosted_terms_disclosure_immutable_guard(); +CREATE TRIGGER account_hosted_terms_disclosure_sources_no_truncate + BEFORE TRUNCATE ON account_hosted_terms_disclosure_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_hosted_terms_disclosure_immutable_guard(); -- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql b/services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql similarity index 100% rename from services/account-service/src/main/resources/db/migration/V41__account_jwt_signer_desired_state.sql rename to services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java index c1a75820d4..b5bb3e01a3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java @@ -49,7 +49,7 @@ /** * Real Flyway/PostgreSQL owner-read proof over explicitly stipulated test-only original bindings. - * The database rows, separate Account owner transaction, immutable order/readback state, and V99 + * The database rows, separate Account owner transaction, immutable order/readback state, and V87 * source guards are real. The creator/source capture and workload Context are test fixtures only; * this proves neither authenticated creator issuance nor physical mTLS or a production caller. */ @@ -87,7 +87,7 @@ void acceptsOnlyExactCommittedHeldOrderInSeparateWritableReadCommittedTransactio assertThat(fixture.tx(() -> fixture.repository.readSettlement(binding))) .isEqualTo(Settlement.PENDING); - // V99's real source guard remains effective while this original owner result is unresolved. + // V87's real source guard remains effective while this original owner result is unresolved. String passwordBefore = accountPassword(fixture, binding.actorAccountId()); assertThatThrownBy( () -> diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java index 3352055270..acba68026d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -1413,9 +1413,10 @@ void v2MixedResultsHoldBothSourceTransitionsAndPreserveAppliedBytes() { @Test void forwardMigrationRetainsV1BindingReadbackAndFlywayChecksumsExactly() { - // Seed the retained V92 row with an ACCOUNT-only source vector, then advance through V93 + // Seed the retained pre-owner-fence row with an ACCOUNT-only source vector at V75, then + // advance through the required-owner fence at V76 // explicitly before using the current runtime repository against this historical fixture. - Context context = context("92"); + Context context = context("75"); DraftAuthorizationFenceBinding base = binding(context); SourceEvidence legacy512 = new SourceEvidence( @@ -1438,19 +1439,19 @@ void forwardMigrationRetainsV1BindingReadbackAndFlywayChecksumsExactly() { .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)) .locations("classpath:db/migration") - .target("93") + .target("76") .load() .migrate(); assertThat( context .dsl() - .fetch("SELECT version, checksum FROM flyway_schema_history WHERE version = '93'")) + .fetch("SELECT version, checksum FROM flyway_schema_history WHERE version = '76'")) .hasSize(1); assertThat( context .dsl() .fetch( - "SELECT version, checksum FROM flyway_schema_history WHERE version IS DISTINCT FROM '93' ORDER BY installed_rank")) + "SELECT version, checksum FROM flyway_schema_history WHERE version IS DISTINCT FROM '76' ORDER BY installed_rank")) .isEqualTo(checksums); Flyway.configure() .dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java index 4acdb991f1..c35fecdba6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/creatorparty/IndividualCreatorPartyPostgresIntegrationTest.java @@ -40,7 +40,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Real owner-row and PostgreSQL guard definitions. Verification/policy and receiving V94 creation + * Real owner-row and PostgreSQL guard definitions. Verification/policy and receiving V83 creation * qualification are explicit SQL fixtures, not authentication, legal provisioning or launch proof. */ @Testcontainers(disabledWithoutDocker = true) @@ -53,8 +53,8 @@ class IndividualCreatorPartyPostgresIntegrationTest { @Test void migrationPreservesExistingAccountAndMembershipAndEnrollsNoParty() throws Exception { - // V94 is the receiving tree's last existing migration before the V95 creator-party schema. - Database db = database("94"); + // V83 is the receiving tree's last existing migration before the V84 creator-party schema. + Database db = database("83"); UUID account = insertAccount(db); long accountKey = Objects.requireNonNull( @@ -82,7 +82,7 @@ void migrationPreservesExistingAccountAndMembershipAndEnrollsNoParty() throws Ex "SELECT * FROM account_tenant_membership WHERE account_id = ?", accountKey), "Baseline membership row is missing") .intoMap(); - migrate(db, "95"); + migrate(db, "84"); assertThat( Objects.requireNonNull( db.dsl().fetchOne("SELECT * FROM accounts WHERE account_uuid = ?", account), @@ -494,7 +494,7 @@ void databaseRejectsSourceAndReceiptRewritesAndOrphanInitialHistory() throws Exc } private static Fixture fixture() throws Exception { - Database db = database("95"); + Database db = database("84"); UUID account = insertAccount(db); UUID request = UUID.randomUUID(); UUID operation = UUID.randomUUID(); @@ -584,7 +584,7 @@ private static void insertHistory(Fixture fixture, String origin, long version) } private static void insertBootstrapFixture(Database db, FreshTenantCreatorEvidence creator) { - // Stipulated original qualification, using the real guarded V94 lifecycle; no guard is + // Stipulated original qualification, using the real guarded V83 lifecycle; no guard is // disabled. var creation = creator.creationEvidence(); UUID authorization = creator.accountAuthorizationOperationId(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java index 0f78d567de..be3b53133a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsPostgresIntegrationTest.java @@ -70,7 +70,7 @@ class AccountHostedTermsPostgresIntegrationTest { @Test void migrationRetainsExistingPartyAndBackfillsNoCatalogOrAcceptance() throws Exception { - Database db = database("95"); + Database db = database("84"); UUID accountId = insertAccount(db); IndividualCreatorPartySource party = party(UUID.randomUUID(), accountId, 1, "test-id-evidence-v1"); @@ -89,7 +89,7 @@ void migrationRetainsExistingPartyAndBackfillsNoCatalogOrAcceptance() throws Exc .intoMap()); byte[] partySourceBefore = (byte[]) partyBefore.remove("source_payload"); - migrate(db, "96"); + migrate(db, "85"); assertThat( Objects.requireNonNull( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index d017ddc2a9..418e25ebd4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -108,8 +108,8 @@ class AccountGameplayAdmissionLeasePersistenceIntegrationTest { private static final String TENANT = "22222222-2222-4222-8222-222222222222"; private static final String OTHER = "33333333-3333-4333-8333-333333333333"; - private static final long V90_WAL_COORDINATOR_TIMEOUT_SECONDS = 3; - private static final String V90_WAL_MARKER_TABLE = "account_v90_wal_coverage_markers"; + private static final long V120_WAL_COORDINATOR_TIMEOUT_SECONDS = 3; + private static final String V120_WAL_MARKER_TABLE = "account_v120_wal_coverage_markers"; @BeforeAll static void start() { @@ -791,7 +791,7 @@ void freshMigrationStoresExactReplayAndRejectsChangedBaselineDigestOrAllocation( @Test void retainedAccountMigrationPreservesAccountAndAddsIndependentFenceDomain() { - var context = context("84.4"); + var context = context("116"); UUID account = tx( context, @@ -876,7 +876,7 @@ void commitsExactDecisionAndAtomicallyRetainsAbortedOrphanIntentWithTerminalConf @Test void forwardMigrationPreservesRetainedReceiptsAndAllowsUnknownDecisionAbort() { - var context = context("88"); + var context = context("118"); UUID account = account(context); var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); var retainedPending = pending(context, account); @@ -913,7 +913,7 @@ void forwardMigrationPreservesRetainedReceiptsAndAllowsUnknownDecisionAbort() { context, () -> repository.recordAborted(retainedPending, null, UUID.randomUUID()))) .hasMessageContaining("identity conflict"); - // The unchanged V87 trigger prevents a direct rewrite of the unknown terminal observation. + // The unchanged V118 trigger prevents a direct rewrite of the unknown terminal observation. assertThatThrownBy( () -> tx( @@ -1136,14 +1136,14 @@ void durableConfirmationStoresOriginalCommitProofAndRecoversLostResponseAfterExp } @Test - void receiptPhysicalCommitPrecedesIndependentV90ReadOnAnotherConnection() throws Exception { + void receiptPhysicalCommitPrecedesIndependentV120ReadOnAnotherConnection() throws Exception { var context = context(null); var original = pending(context, account(context)); UUID decision = UUID.randomUUID(); new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) .execute(original, decision); - createV90WalCoverageMarkerTable(context); - String applicationName = v90ApplicationName(); + createV120WalCoverageMarkerTable(context); + String applicationName = v120ApplicationName(); var trace = new ReceiptCommitTrace(); var owner = new AccountGameplayAdmissionCommitConfirmationOwner( @@ -1154,7 +1154,7 @@ void receiptPhysicalCommitPrecedesIndependentV90ReadOnAnotherConnection() throws "test"); var receipt = - withV90WalCoverageCoordinator( + withV120WalCoverageCoordinator( context, applicationName, () -> @@ -1163,9 +1163,9 @@ void receiptPhysicalCommitPrecedesIndependentV90ReadOnAnotherConnection() throws AccountGameplayAdmissionCommitConfirmation::walInsertLsn); assertThat(trace.count("physical-commit")).isEqualTo(2); - assertThat(trace.count("v90-read")).isEqualTo(1); + assertThat(trace.count("v120-read")).isEqualTo(1); var receiptCommit = firstEvent(trace, "physical-commit"); - var independentRead = firstEvent(trace, "v90-read"); + var independentRead = firstEvent(trace, "v120-read"); assertThat(trace.events().indexOf(receiptCommit)) .isLessThan(trace.events().indexOf(independentRead)); assertThat(independentRead.connectionId()).isNotEqualTo(receiptCommit.connectionId()); @@ -1183,7 +1183,7 @@ void receiptPhysicalCommitPrecedesIndependentV90ReadOnAnotherConnection() throws } @Test - void lostReceiptCommitAcknowledgementDeniesThenRecoversOnlyThroughIndependentV90Read() + void lostReceiptCommitAcknowledgementDeniesThenRecoversOnlyThroughIndependentV120Read() throws Exception { var context = context(null); var original = pending(context, account(context)); @@ -1205,7 +1205,7 @@ void lostReceiptCommitAcknowledgementDeniesThenRecoversOnlyThroughIndependentV90 assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.UNAVAILABLE)); assertThat(trace.count("physical-commit")).isEqualTo(1); - assertThat(trace.count("v90-read")).isZero(); + assertThat(trace.count("v120-read")).isZero(); var retainedRow = confirmationRow(context, original); assertThat(retainedRow.get("request_id", UUID.class)).isEqualTo(requestId(original)); @@ -1220,12 +1220,12 @@ void lostReceiptCommitAcknowledgementDeniesThenRecoversOnlyThroughIndependentV90 assertThat(retainedRow.get("confirmation_xid", String.class)) .isNotEqualTo(retainedRow.get("finalization_xid", String.class)); - // Recovery is an explicit fresh owner read, which invokes the existing V90 independent WAL + // Recovery is an explicit fresh owner read, which invokes the existing V120 independent WAL // coverage observer. No confirm retry can mint or acknowledge the lost receipt COMMIT. var recovered = syntheticReadPeer().call(() -> owner.read(request)); - assertThat(trace.count("v90-read")).isEqualTo(1); + assertThat(trace.count("v120-read")).isEqualTo(1); var lostAckCommit = firstEvent(trace, "physical-commit"); - var independentRead = firstEvent(trace, "v90-read"); + var independentRead = firstEvent(trace, "v120-read"); assertThat(trace.events().indexOf(lostAckCommit)) .isLessThan(trace.events().indexOf(independentRead)); assertThat(independentRead.connectionId()).isNotEqualTo(lostAckCommit.connectionId()); @@ -1277,7 +1277,7 @@ void receiptCommitFailureOrPriorWalDenialRollsBackWithoutReceiptOrIndependentRea failure, "Test failed before physical receipt COMMIT"); }); assertThat(trace.count("physical-commit")).isZero(); - assertThat(trace.count("v90-read")).isZero(); + assertThat(trace.count("v120-read")).isZero(); assertThat( context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) .isZero(); @@ -1404,7 +1404,7 @@ void staleSerializableConfirmationInsertRetriesInsteadOfLeakingUniqueViolation() assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("40001"); }); assertThat(tx(context, () -> confirm(context, original, decision))).isEqualTo(retained); - // This case proves serialization and exact retained storage, not the distinct V90 WAL + // This case proves serialization and exact retained storage, not the distinct V120 WAL // durability observation. Dedicated independent-read/receipt-COMMIT cases cover that gate; // a global insert-frontier denial remains an open durability limitation, never a bypass. assertThat(tx(context, () -> confirmationRow(context, original)).intoMap()) @@ -1488,7 +1488,7 @@ void sameTransactionAndReleasedSubtransactionCannotConfirmOriginalFinalization() @Test void missingPendingRolledBackAbortedAndRetainedUnstampedCommitsStayUnproved() { - var context = context("89"); + var context = context("119"); UUID account = account(context); var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); var retained = pending(context, account); @@ -1677,7 +1677,7 @@ void sameTransactionReceiptReadAndRolledBackConfirmationCannotProveDurability() var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); UUID decision = UUID.randomUUID(); tx(context, () -> repository.recordCommitted(original, decision)); - createV90WalCoverageMarkerTable(context); + createV120WalCoverageMarkerTable(context); for (boolean subtransaction : List.of(false, true)) { assertThatThrownBy( () -> @@ -1685,9 +1685,9 @@ void sameTransactionReceiptReadAndRolledBackConfirmationCannotProveDurability() context, () -> { if (subtransaction) context.dsl().execute("SAVEPOINT receipt_creation"); - String applicationName = v90ApplicationName(); + String applicationName = v120ApplicationName(); var receipt = - withV90WalCoverageCoordinator( + withV120WalCoverageCoordinator( context, applicationName, () -> { @@ -1719,8 +1719,8 @@ void sameTransactionReceiptReadAndRolledBackConfirmationCannotProveDurability() tx( context, () -> { - String applicationName = v90ApplicationName(); - return withV90WalCoverageCoordinator( + String applicationName = v120ApplicationName(); + return withV120WalCoverageCoordinator( context, applicationName, () -> { @@ -1783,8 +1783,8 @@ void concurrentConfirmationsRetainOneOriginalReceiptWithoutAdvancingSources() th } @Test - void originalAckReceiptMigrationPreservesV91HistoryWithoutInventingAcknowledgement() { - var context = context("91"); + void originalAckReceiptMigrationPreservesV121HistoryWithoutInventingAcknowledgement() { + var context = context("121"); UUID committedAccount = account(context); var retainedCommittedEvidence = pending(context, committedAccount); UUID retainedDecision = UUID.randomUUID(); @@ -1799,15 +1799,15 @@ void originalAckReceiptMigrationPreservesV91HistoryWithoutInventingAcknowledgeme UUID pendingAccount = account(context); var retainedPendingEvidence = pending(context, pendingAccount); var pendingBefore = operation(context, retainedPendingEvidence).intoMap(); - var v91Checksums = flywayChecksums(context); - assertThat(v91Checksums).containsKey("91").doesNotContainKey("92"); + var v121Checksums = flywayChecksums(context); + assertThat(v121Checksums).containsKey("121").doesNotContainKey("122"); migrate(context, null); var latestChecksums = flywayChecksums(context); - for (var entry : v91Checksums.entrySet()) + for (var entry : v121Checksums.entrySet()) assertThat(latestChecksums).containsEntry(entry.getKey(), entry.getValue()); - assertThat(latestChecksums.get("92")).isNotNull(); + assertThat(latestChecksums.get("122")).isNotNull(); assertThat(operation(context, retainedCommittedEvidence).intoMap()).isEqualTo(committedBefore); assertThat(operation(context, retainedPendingEvidence).intoMap()).isEqualTo(pendingBefore); assertThat( @@ -2319,7 +2319,7 @@ void concurrentOriginalAckReceiptRecoveriesRetainExactProofBeforeAndAfterExpiry( assertThat(operation(context, original).intoMap()).isEqualTo(operationBeforeRecovery); assertThat(storageSnapshot(context)).isEqualTo(sourcesBeforeRecovery); - // The V92 receipt is immutable historical proof; expiry does not restamp or renew it. + // The V122 receipt is immutable historical proof; expiry does not restamp or renew it. waitPastDeadline(context, original); var recoveredAfterExpiry = receiptExecutor.read(original, decision); assertThat(recoveredAfterExpiry).isEqualTo(leftReceipt); @@ -2356,7 +2356,7 @@ private static Record confirm( decision)); } - private static T withV90WalCoverageCoordinator( + private static T withV120WalCoverageCoordinator( Context context, String applicationName, Supplier confirmation, @@ -2368,14 +2368,14 @@ private static T withV90WalCoverageCoordinator( ExecutorService executor = Executors.newSingleThreadExecutor( task -> { - Thread thread = new Thread(task, "account-v90-wal-coordinator-" + applicationName); + Thread thread = new Thread(task, "account-v120-wal-coordinator-" + applicationName); thread.setDaemon(true); return thread; }); - Future future = + Future future = executor.submit( () -> - observeV90WalCoverage( + observeV120WalCoverage( context, applicationName, actionFinished, @@ -2389,7 +2389,7 @@ private static T withV90WalCoverageCoordinator( if (!monitorReady.await(2, TimeUnit.SECONDS)) { actionFailure = new IllegalStateException( - "Account V90 WAL coverage coordinator could not open its observation connection"); + "Account V120 WAL coverage coordinator could not open its observation connection"); } else { result = confirmation.get(); } @@ -2405,7 +2405,7 @@ private static T withV90WalCoverageCoordinator( } executor.shutdown(); - V90WalCoverageObservation observation = null; + V120WalCoverageObservation observation = null; Throwable coordinatorFailure = null; try { observation = future.get(2, TimeUnit.SECONDS); @@ -2428,7 +2428,7 @@ private static T withV90WalCoverageCoordinator( if (!executor.awaitTermination(2, TimeUnit.SECONDS)) { executor.shutdownNow(); var cleanupFailure = - new IllegalStateException("Account V90 WAL coverage coordinator did not terminate"); + new IllegalStateException("Account V120 WAL coverage coordinator did not terminate"); closeCoordinatorConnection(coordinatorConnection, cleanupFailure); if (!executor.awaitTermination(2, TimeUnit.SECONDS)) { if (coordinatorFailure == null) coordinatorFailure = cleanupFailure; @@ -2447,14 +2447,14 @@ private static T withV90WalCoverageCoordinator( if (coordinatorFailure != null) actionFailure.addSuppressed(coordinatorFailure); actionFailure.addSuppressed( new IllegalStateException( - describeV90WalCoordinatorOutcome(applicationName, observation))); + describeV120WalCoordinatorOutcome(applicationName, observation))); if (actionFailure instanceof RuntimeException runtimeFailure) throw runtimeFailure; throw (Error) actionFailure; } if (coordinatorFailure != null) { throw new IllegalStateException( - "Account V90 confirmation succeeded, but its bounded WAL coordinator failed", + "Account V120 confirmation succeeded, but its bounded WAL coordinator failed", coordinatorFailure); } if (observation != null && observation.marker() != null) { @@ -2470,14 +2470,14 @@ private static T withV90WalCoverageCoordinator( .get("covered", Boolean.class); assertThat(covered) .as( - "independent marker COMMIT flush covers V90 fence %s from backend %s", + "independent marker COMMIT flush covers V120 fence %s from backend %s", fence, observation.backendPid()) .isTrue(); } return result; } - private static V90WalCoverageObservation observeV90WalCoverage( + private static V120WalCoverageObservation observeV120WalCoverage( Context context, String applicationName, AtomicBoolean actionFinished, @@ -2489,7 +2489,7 @@ private static V90WalCoverageObservation observeV90WalCoverage( String lastWaitEventType = null; String lastWaitEvent = null; long deadline = - System.nanoTime() + TimeUnit.SECONDS.toNanos(V90_WAL_COORDINATOR_TIMEOUT_SECONDS); + System.nanoTime() + TimeUnit.SECONDS.toNanos(V120_WAL_COORDINATOR_TIMEOUT_SECONDS); try (Connection connection = context.dataSource().getConnection(); PreparedStatement activity = connection.prepareStatement( @@ -2514,26 +2514,26 @@ private static V90WalCoverageObservation observeV90WalCoverage( int currentPid = rows.getInt("pid"); if (backendPid != null && backendPid != currentPid) { throw new SQLException( - "Account V90 confirmation backend changed during WAL coordination"); + "Account V120 confirmation backend changed during WAL coordination"); } backendPid = currentPid; lastWaitEventType = rows.getString("wait_event_type"); lastWaitEvent = rows.getString("wait_event"); if (rows.next()) { throw new SQLException( - "Multiple Account V90 confirmation backends matched unique application name"); + "Multiple Account V120 confirmation backends matched unique application name"); } if ("Timeout".equals(lastWaitEventType) && "PgSleep".equals(lastWaitEvent)) { synchronized (coordinatorLock) { if (actionFinished.get()) { - return new V90WalCoverageObservation( + return new V120WalCoverageObservation( backendPid, lastWaitEventType, lastWaitEvent, null, false); } connection.close(); coordinatorConnection.compareAndSet(connection, null); - V90WalCoverageMarker marker = - commitV90WalCoverageMarker(context, coordinatorConnection); - return new V90WalCoverageObservation( + V120WalCoverageMarker marker = + commitV120WalCoverageMarker(context, coordinatorConnection); + return new V120WalCoverageObservation( backendPid, lastWaitEventType, lastWaitEvent, marker, false); } } @@ -2541,20 +2541,20 @@ private static V90WalCoverageObservation observeV90WalCoverage( } synchronized (coordinatorLock) { if (actionFinished.get()) { - return new V90WalCoverageObservation( + return new V120WalCoverageObservation( backendPid, lastWaitEventType, lastWaitEvent, null, false); } } Thread.yield(); } - return new V90WalCoverageObservation( + return new V120WalCoverageObservation( backendPid, lastWaitEventType, lastWaitEvent, null, true); } finally { monitorReady.countDown(); } } - private static V90WalCoverageMarker commitV90WalCoverageMarker( + private static V120WalCoverageMarker commitV120WalCoverageMarker( Context context, AtomicReference coordinatorConnection) throws SQLException { UUID markerId = UUID.randomUUID(); String markerValue = UUID.randomUUID().toString(); @@ -2570,25 +2570,26 @@ private static V90WalCoverageMarker commitV90WalCoverageMarker( statement.executeQuery( "SELECT pg_backend_pid(), current_setting('synchronous_commit')")) { if (!settings.next() || !"on".equals(settings.getString(2))) { - throw new SQLException("Account V90 marker writer did not retain synchronous COMMIT"); + throw new SQLException( + "Account V120 marker writer did not retain synchronous COMMIT"); } writerBackendPid = settings.getInt(1); if (settings.next()) { throw new SQLException( - "Account V90 marker writer settings query returned multiple rows"); + "Account V120 marker writer settings query returned multiple rows"); } } } try (PreparedStatement insert = writer.prepareStatement( "INSERT INTO " - + V90_WAL_MARKER_TABLE + + V120_WAL_MARKER_TABLE + " (marker_id, marker_value) VALUES (?, ?)")) { insert.setQueryTimeout(1); insert.setObject(1, markerId); insert.setString(2, markerValue); if (insert.executeUpdate() != 1) { - throw new SQLException("Account V90 marker INSERT did not write exactly one row"); + throw new SQLException("Account V120 marker INSERT did not write exactly one row"); } } writer.commit(); @@ -2609,18 +2610,19 @@ private static V90WalCoverageMarker commitV90WalCoverageMarker( PreparedStatement readback = reader.prepareStatement( "SELECT marker_value, pg_backend_pid() FROM " - + V90_WAL_MARKER_TABLE + + V120_WAL_MARKER_TABLE + " WHERE marker_id = ?")) { coordinatorConnection.set(reader); readback.setQueryTimeout(1); readback.setObject(1, markerId); try (ResultSet row = readback.executeQuery()) { if (!row.next() || !markerValue.equals(row.getString(1))) { - throw new SQLException("Committed Account V90 WAL marker was not independently readable"); + throw new SQLException( + "Committed Account V120 WAL marker was not independently readable"); } readerBackendPid = row.getInt(2); if (readerBackendPid == writerBackendPid || row.next()) { - throw new SQLException("Account V90 WAL marker readback was not exact and independent"); + throw new SQLException("Account V120 WAL marker readback was not exact and independent"); } } String flushLsn; @@ -2628,22 +2630,22 @@ private static V90WalCoverageMarker commitV90WalCoverageMarker( statement.setQueryTimeout(1); try (ResultSet result = statement.executeQuery("SELECT pg_current_wal_flush_lsn()::text")) { if (!result.next()) - throw new SQLException("Account V90 marker flush location unavailable"); + throw new SQLException("Account V120 marker flush location unavailable"); flushLsn = result.getString(1); } } - return new V90WalCoverageMarker(flushLsn); + return new V120WalCoverageMarker(flushLsn); } finally { coordinatorConnection.set(null); } } - private static void createV90WalCoverageMarkerTable(Context context) { + private static void createV120WalCoverageMarkerTable(Context context) { context .dsl() .execute( "CREATE TABLE " - + V90_WAL_MARKER_TABLE + + V120_WAL_MARKER_TABLE + " (marker_id UUID PRIMARY KEY, marker_value TEXT NOT NULL)"); } @@ -2668,7 +2670,7 @@ private static Connection setApplicationName(Connection connection, String appli statement.setString(1, applicationName); try (ResultSet result = statement.executeQuery()) { if (!result.next() || !applicationName.equals(result.getString(1)) || result.next()) { - throw new SQLException("Account V90 application name could not be verified"); + throw new SQLException("Account V120 application name could not be verified"); } return connection; } @@ -2692,8 +2694,8 @@ private static void setLocalApplicationName(DSLContext dsl, String applicationNa assertThat(configured).isEqualTo(applicationName); } - private static String v90ApplicationName() { - return "account-v90-" + UUID.randomUUID().toString().replace("-", ""); + private static String v120ApplicationName() { + return "account-v120-" + UUID.randomUUID().toString().replace("-", ""); } private static T callWithSyntheticReadPeer(Callable action) { @@ -2706,13 +2708,13 @@ private static T callWithSyntheticReadPeer(Callable action) { } } - private static String describeV90WalCoordinatorOutcome( - String applicationName, V90WalCoverageObservation observation) { + private static String describeV120WalCoordinatorOutcome( + String applicationName, V120WalCoverageObservation observation) { if (observation == null) { - return "Account V90 coordinator produced no observation for application_name=" + return "Account V120 coordinator produced no observation for application_name=" + applicationName; } - return "Account V90 coordinator outcome" + return "Account V120 coordinator outcome" + ": application_name=" + applicationName + " backend_pid=" @@ -2738,13 +2740,13 @@ private static void closeCoordinatorConnection( } } - private record V90WalCoverageMarker(String flushLsn) {} + private record V120WalCoverageMarker(String flushLsn) {} - private record V90WalCoverageObservation( + private record V120WalCoverageObservation( Integer backendPid, String waitEventType, String waitEvent, - V90WalCoverageMarker marker, + V120WalCoverageMarker marker, boolean timedOut) {} private static FinalizeGameplayAdmissionLeaseRequest confirmationRequest( @@ -2976,8 +2978,8 @@ private static PreparedStatement tracedStatement( PreparedStatement.class.getClassLoader(), new Class[] {PreparedStatement.class}, (proxy, method, arguments) -> { - if (method.getName().startsWith("execute") && isV90IndependentRead(sql)) - trace.record("v90-read", connectionId); + if (method.getName().startsWith("execute") && isV120IndependentRead(sql)) + trace.record("v120-read", connectionId); try { return method.invoke(physical, arguments); } catch (InvocationTargetException failure) { @@ -2986,7 +2988,7 @@ private static PreparedStatement tracedStatement( }); } - private static boolean isV90IndependentRead(String sql) { + private static boolean isV120IndependentRead(String sql) { return sql.toLowerCase(java.util.Locale.ROOT) .contains("account_gameplay_admission_read_commit_confirmation"); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java index 12e48f989a..86b3d442fa 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionWalBoundaryProofIntegrationTest.java @@ -45,13 +45,14 @@ * *

Actual unchanged original/receipt transactions retain test-only lower search locators. * Synthetic classifier cases explicitly do not prove physical wraparound, promotion, recycle, - * unrelated unflushed tails or insufficient-flush behavior. Production V92 remains unchanged. + * unrelated unflushed tails or insufficient-flush behavior. Production original-acknowledgement + * receipt guards remain unchanged. */ @Testcontainers(disabledWithoutDocker = true) @Execution(ExecutionMode.SAME_THREAD) class AccountGameplayAdmissionWalBoundaryProofIntegrationTest { // Deliberately owns its container: never honors the shared fixture's external database override. - // PG18 is rejected by the unchanged production executors and V92. + // PG18 is rejected by the unchanged production executors and original-acknowledgement guards. @Container static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine") @@ -157,7 +158,7 @@ void freshConnectionLocatesExactReceiptCommitAfterLostAcknowledgementWithoutRest assertThat(locator(context, evidence, "receipt").get("target_xid", String.class)) .isEqualTo(receiptBefore.get("receipt_xid")) .isNotEqualTo(acknowledgement.finalizationXid()); - // The probe uses its restricted independent connection, not V92 or a fresh confirming write. + // The probe uses its restricted connection, not the receipt guard or a fresh confirming write. var receiptProof = read(context, evidence, decision, "receipt"); var originalProof = read(context, evidence, decision, "original"); assertCovered(context, receiptProof); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java index 7cc0220fb2..71609b5e7f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/PreRestrictionBirthAccountFixture.java @@ -14,10 +14,10 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * Seeds the canonical pre-V88 repository-created Account image in historical migration fixtures. + * Seeds the canonical pre-V81 repository-created Account image in historical migration fixtures. * - *

This reproduces the V40 sequence-zero Account source setup, including the immutable V74.1 - * empty-role source inserted by its Account trigger. It deliberately does not create V88 + *

This reproduces the V40 sequence-zero Account source setup, including the immutable V74 + * empty-role source inserted by its Account trigger. It deliberately does not create V81 * restriction-birth evidence, enroll a retained Account, or establish admission authority. */ public final class PreRestrictionBirthAccountFixture { @@ -27,10 +27,10 @@ public final class PreRestrictionBirthAccountFixture { private PreRestrictionBirthAccountFixture() {} /** - * Inserts an Account and its pre-V88 fresh-source rows in one test transaction. + * Inserts an Account and its pre-V81 fresh-source rows in one test transaction. * - *

The target schema must already include V40 and V74.1. Use only when a test intentionally - * starts from a historical schema before V88 and then verifies forward migration preservation. + *

The target schema must already include V40 and V74. Use only when a test intentionally + * starts from a historical schema before V81 and then verifies forward migration preservation. */ public static Account create( DSLContext dsl, String username, String email, String passwordHash, String loginAuthModes) { @@ -53,7 +53,7 @@ public static Account create( "Restriction-birth schema guard readback is required"); if (Boolean.TRUE.equals(restrictionBirthSchemaInstalled)) { throw new IllegalStateException( - "Pre-V88 Account fixture cannot run after restriction-birth schema installation"); + "Pre-V81 Account fixture cannot run after restriction-birth schema installation"); } Objects.requireNonNull(username, "username is required"); Objects.requireNonNull(passwordHash, "password hash is required"); @@ -69,16 +69,16 @@ public static Account create( new AccountAuthorityGenerationRepository(dsl); AccountAuthorityOutboxRepository outbox = new AccountAuthorityOutboxRepository(dsl); AccountAuthoritySourceEvidenceRepository sources = - new PreV88SourceEvidence(dsl, generations, outbox); + new PreV81SourceEvidence(dsl, generations, outbox); sources.initializeIssuerIfAbsent(ACCOUNT_ISSUER); return new AccountRepository(dsl, sources).save(account); } - private static final class PreV88SourceEvidence extends AccountAuthoritySourceEvidenceRepository { + private static final class PreV81SourceEvidence extends AccountAuthoritySourceEvidenceRepository { private final DSLContext dsl; private final AccountAuthorityGenerationRepository generations; - private PreV88SourceEvidence( + private PreV81SourceEvidence( DSLContext dsl, AccountAuthorityGenerationRepository generations, AccountAuthorityOutboxRepository outbox) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java index 009aec292e..f3e66fc765 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -16,9 +16,12 @@ import java.util.Base64; import java.util.Collection; import java.util.List; +import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; @@ -231,6 +234,183 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isEqualTo(1); var actor = actors.authenticate(compact, f.tenant, environment); assertThat(actor.accountId()).isEqualTo(f.account.getAccountUuid()); + String tokenHash = + AccountControlUiIssuanceRepository.hash(compact.getBytes(StandardCharsets.US_ASCII)); + var retained = f.tx(() -> operations.findToken(tokenHash)); + assertThat(retained.status).isEqualTo("COMMITTED"); + + // This is Account capture/readback proof only. The original Logging reservation owner and + // claim fence are stipulated upstream inputs here; this fixture does not prove a genuine + // Logging claim, StartSession authorization, or issuer activation. + UUID reservationOwnerId = UUID.randomUUID(); + long reservationClaimFence = 1L; + String controlPlaneRequestId = "start-session-capture-" + UUID.randomUUID(); + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(f.tenant, "control-ui-owner-proof"), + new StartSessionOperatorAction.Target(42L, f.account.getAccountUuid()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "test-only StartSession Account capture"); + var tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + controlPlaneRequestId, actor.accountId(), action); + var captureRepository = new AccountStartSessionAuthorityCaptureRepository(f.dsl); + AccountStartSessionAuthorityCapture firstCapture; + AccountStartSessionAuthorityCapture exactRetry; + AccountStartSessionAuthorityCapture finalReadback; + try (var peer = + AccountControlUiOwnerWorkflowPostgresIntegrationTest.withPeer( + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER)) { + firstCapture = + actors.withCurrentCommitted( + actor.accountId(), + f.tenant, + retained.jti, + environment, + current -> + captureRepository.prepareOrReadExact( + current, + tuple, + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER, + reservationOwnerId, + reservationClaimFence)); + assertThat(f.dsl.fetchCount(DSL.table("account_start_session_authority_captures"))) + .isEqualTo(1); + assertThat(firstCapture.snapshotSha256()).hasSize(64); + assertThat(firstCapture.canonicalSha256()).hasSize(64); + assertThat(firstCapture.capturedAt()) + .matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"); + + exactRetry = + actors.withCurrentCommitted( + actor.accountId(), + f.tenant, + retained.jti, + environment, + current -> + captureRepository.prepareOrReadExact( + current, + tuple, + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER, + reservationOwnerId, + reservationClaimFence)); + assertThat(exactRetry.sameStoredValue(firstCapture)).isTrue(); + assertThat(exactRetry.canonicalBytes()).isEqualTo(firstCapture.canonicalBytes()); + assertThat(exactRetry.bundleReference()).isEqualTo(firstCapture.bundleReference()); + + finalReadback = + actors.withCurrentCommitted( + actor.accountId(), + f.tenant, + retained.jti, + environment, + current -> + captureRepository.lockExactCurrent( + firstCapture, + current, + tuple, + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER, + reservationOwnerId, + reservationClaimFence)); + assertThat(finalReadback.sameStoredValue(firstCapture)).isTrue(); + + var changedAction = + new StartSessionOperatorAction( + action.actionFamilySchemaId(), + action.actionFamilySchemaVersion(), + action.scope(), + action.target(), + action.expectedVersion(), + action.mutation(), + "changed typed action under original request ID"); + var changedTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + controlPlaneRequestId, actor.accountId(), changedAction); + assertThatThrownBy( + () -> + actors.withCurrentCommitted( + actor.accountId(), + f.tenant, + retained.jti, + environment, + current -> + captureRepository.prepareOrReadExact( + current, + changedTuple, + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER, + reservationOwnerId, + reservationClaimFence))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account StartSession source capture is unavailable"); + assertThatThrownBy( + () -> + actors.withCurrentCommitted( + actor.accountId(), + f.tenant, + retained.jti, + environment, + current -> + captureRepository.prepareOrReadExact( + current, + tuple, + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER, + UUID.randomUUID(), + reservationClaimFence))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account StartSession source capture is unavailable"); + assertThatThrownBy( + () -> + actors.withCurrentCommitted( + actor.accountId(), + f.tenant, + retained.jti, + environment, + current -> + captureRepository.prepareOrReadExact( + current, + tuple, + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER, + reservationOwnerId, + reservationClaimFence + 1L))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account StartSession source capture is unavailable"); + + var unchanged = + actors.withCurrentCommitted( + actor.accountId(), + f.tenant, + retained.jti, + environment, + current -> + captureRepository.lockExactCurrent( + firstCapture, + current, + tuple, + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER, + reservationOwnerId, + reservationClaimFence)); + assertThat(unchanged.canonicalBytes()).isEqualTo(firstCapture.canonicalBytes()); + assertThat(f.dsl.fetchCount(DSL.table("account_start_session_authority_captures"))) + .isEqualTo(1); + assertThat( + Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT last_source_version FROM account_start_session_capture_source_version_allocator"), + "capture sourceVersion allocator row must exist") + .get(0, Long.class)) + .isEqualTo(firstCapture.sourceVersion()); + assertThat( + Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT last_source_fence FROM account_start_session_capture_source_fence_allocator"), + "capture sourceFence allocator row must exist") + .get(0, Long.class)) + .isEqualTo(firstCapture.sourceFence()); + } + var snapshot = f.tx(() -> f.authority.captureInitial(f.tenant, environment)); var binding = originalBinding(f, snapshot.sources()); var claimed = actors.claimOriginalDraft(compact, binding, environment); @@ -240,9 +420,6 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))) .isEqualTo(1); assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isEqualTo(1); - String tokenHash = - AccountControlUiIssuanceRepository.hash(compact.getBytes(StandardCharsets.US_ASCII)); - var retained = f.tx(() -> operations.findToken(tokenHash)); assertThat(retained.status).isEqualTo("COMMITTED"); assertThat(retained.signerReceipt).isEqualTo(originalSigner.receipt()); var active = registry.readActive(tokenHash); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java index 83b701156f..d71f9a3888 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java @@ -39,8 +39,8 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Real creator issuance/currentness, Account transactions, V109/V112 and source guards. GD source - * transport and the original author's terminal are explicit upstream fixtures, not composed + * Real creator issuance/currentness, Account transactions, intake/reservation and source guards. GD + * source transport and the original author's terminal are explicit upstream fixtures, not composed * production or mTLS proof. No GL terminal, settlement, digest or activation is claimed. */ @Testcontainers(disabledWithoutDocker = true) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java new file mode 100644 index 0000000000..5ed190a10a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof of V128 allocator ownership and capture-table statement protection. */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionAuthorityCapturePostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void migrationInstallsIndependentAllocatorsAndRejectsUnownedMutationAndTruncate() { + String schema = "start_session_capture_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(source, SQLDialect.POSTGRES); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_source_version FROM account_start_session_capture_source_version_allocator"), + "capture sourceVersion allocator row must exist") + .get(0, Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_source_fence FROM account_start_session_capture_source_fence_allocator"), + "capture sourceFence allocator row must exist") + .get(0, Long.class)) + .isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal " + + "AND tgname IN ('account_start_session_authority_capture_immutable', " + + "'account_start_session_authority_capture_no_truncate', " + + "'account_start_session_capture_source_version_allocator_guard', " + + "'account_start_session_capture_source_fence_allocator_guard')"), + "V128 protection trigger query must return a row") + .get(0, Long.class)) + .isEqualTo(4L); + + var actorId = UUID.fromString("11111111-1111-4111-8111-111111111111"); + var tuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "capture-integration-request", + actorId, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope( + UUID.fromString("22222222-2222-4222-8222-222222222222"), "operator-test"), + new StartSessionOperatorAction.Target( + 42L, UUID.fromString("33333333-3333-4333-8333-333333333333")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "capture tuple guard regression")); + String tupleJson = tuple.canonicalJson(); + String tupleMutationDigest = tuple.mutationDigest(); + assertThat(tupleJson).doesNotContain("mutationDigest"); + assertThat(tupleMutationDigest).matches("[0-9a-f]{64}"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT (?::jsonb)->>'mutationDigest' AS tuple_digest", tupleJson), + "canonical pretuple query must return a row") + .get("tuple_digest", String.class)) + .isNull(); + String captureGuard = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT pg_get_functiondef('account_start_session_authority_capture_guard()'::regprocedure)"), + "V128 capture guard function must exist") + .get(0, String.class); + assertThat(captureGuard) + .contains("snapshot->>'mutationDigest' IS DISTINCT FROM NEW.mutation_digest") + .doesNotContain("tuple->>'mutationDigest'"); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_start_session_capture_source_version_allocator " + + "SET last_source_version = last_source_version + 1")) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> dsl.execute("DELETE FROM account_start_session_capture_source_fence_allocator")) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE account_start_session_authority_captures")) + .isInstanceOf(RuntimeException.class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM account_start_session_authority_captures"), + "V128 capture count query must return a row") + .get(0, Long.class)) + .isZero(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorServiceTest.java new file mode 100644 index 0000000000..2770283c4e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorServiceTest.java @@ -0,0 +1,501 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountControlUiActorServiceTest { + private static final Instant NOW = Instant.parse("2026-10-08T11:00:00Z"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactCommittedTokenIdentityRevalidatesAndRunsCallbackInsideFinalOwnerTransaction() { + Fixture f = new Fixture(); + f.stubCommitted(); + AtomicBoolean called = new AtomicBoolean(); + + String result = + f.actors.withCurrentCommitted( + f.accountId, + f.tenantId, + f.tokenJti, + f.environment, + current -> { + called.set(true); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(current.stored()).isSameAs(f.stored); + assertThat(current.source()).isSameAs(f.snapshot); + return "current"; + }); + + assertThat(result).isEqualTo("current"); + assertThat(called).isTrue(); + verify(f.operations).findCommittedByTokenJti(f.accountId, f.tenantId, f.tokenJti); + verify(f.operations).lockCommittedByTokenJti(f.stored); + verify(f.operations).requireCommitted(f.stored); + verify(f.signers).requireOriginal(f.stored.signerReceipt); + } + + @Test + void absentOrNoncommittedOriginalNeverReadsExternalEvidenceOrCallsBack() { + Fixture f = new Fixture(); + AtomicBoolean called = new AtomicBoolean(); + when(f.operations.findCommittedByTokenJti(f.accountId, f.tenantId, f.tokenJti)) + .thenReturn(null); + + assertDeniedWithoutCallback(f, called); + verify(f.registry, never()).readActive(anyString()); + verify(f.publicSource, never()).sourceIdentity(); + verify(f.operations, never()).lockCommittedByTokenJti(any()); + + Fixture noncommitted = new Fixture(); + noncommitted.stubCommitted(); + var noncommittedRecord = + noncommitted.recordWithIdentity( + noncommitted.accountId, noncommitted.tenantId, noncommitted.tokenJti, "CANDIDATE"); + when(noncommitted.operations.findCommittedByTokenJti( + noncommitted.accountId, noncommitted.tenantId, noncommitted.tokenJti)) + .thenReturn(noncommittedRecord); + assertDeniedWithoutCallback(noncommitted, new AtomicBoolean()); + } + + @Test + void mismatchedActorTenantOrJtiReturnedByExactLookupFailsClosed() { + Fixture f = new Fixture(); + f.stubCommitted(); + var actorMismatchRecord = + f.recordWithIdentity(UUID.randomUUID(), f.tenantId, f.tokenJti, "COMMITTED"); + when(f.operations.findCommittedByTokenJti(f.accountId, f.tenantId, f.tokenJti)) + .thenReturn(actorMismatchRecord); + AtomicBoolean called = new AtomicBoolean(); + + assertDeniedWithoutCallback(f, called); + verify(f.registry, never()).readActive(anyString()); + + Fixture tenantMismatch = new Fixture(); + tenantMismatch.stubCommitted(); + var tenantMismatchRecord = + tenantMismatch.recordWithIdentity( + tenantMismatch.accountId, UUID.randomUUID(), tenantMismatch.tokenJti, "COMMITTED"); + when(tenantMismatch.operations.findCommittedByTokenJti( + tenantMismatch.accountId, tenantMismatch.tenantId, tenantMismatch.tokenJti)) + .thenReturn(tenantMismatchRecord); + assertDeniedWithoutCallback(tenantMismatch, new AtomicBoolean()); + + Fixture jtiMismatch = new Fixture(); + jtiMismatch.stubCommitted(); + var jtiMismatchRecord = + jtiMismatch.recordWithIdentity( + jtiMismatch.accountId, jtiMismatch.tenantId, UUID.randomUUID(), "COMMITTED"); + when(jtiMismatch.operations.findCommittedByTokenJti( + jtiMismatch.accountId, jtiMismatch.tenantId, jtiMismatch.tokenJti)) + .thenReturn(jtiMismatchRecord); + assertDeniedWithoutCallback(jtiMismatch, new AtomicBoolean()); + } + + @Test + void expiredAndFutureCommittedTokenClaimsAreRejected() { + for (Instant issuedAt : List.of(NOW.minusSeconds(400), NOW.plusSeconds(30))) { + Fixture f = new Fixture(issuedAt, issuedAt.plusSeconds(300)); + f.stubCommitted(); + AtomicBoolean called = new AtomicBoolean(); + + assertDeniedWithoutCallback(f, called); + } + } + + @Test + void expiryReachedDuringCurrentSourceCaptureIsRejectedBeforeCallback() { + Fixture f = new Fixture(); + f.stubCommitted(); + when(f.authority.capture(f.accountId, f.tenantId, f.environment)) + .thenAnswer( + ignored -> { + f.clock.set(f.expiresAt); + return f.snapshot; + }); + + assertDeniedWithoutCallback(f, new AtomicBoolean()); + } + + @Test + void expiryReachedDuringCommittedRecoveryIsRejectedBeforeCallback() { + Fixture f = new Fixture(); + f.stubCommitted(); + var committed = mock(AccountControlUiIssuanceRepository.Committed.class); + when(committed.tokenHash()).thenReturn(f.stored.tokenHash); + when(f.operations.requireCommitted(f.stored)) + .thenAnswer( + ignored -> { + f.clock.set(f.expiresAt); + return committed; + }); + + assertDeniedWithoutCallback(f, new AtomicBoolean()); + } + + @Test + void missingOrChangedActiveRegistryIsRejectedBeforeCallback() { + Fixture missing = new Fixture(); + missing.stubCommitted(); + when(missing.registry.readActive(missing.stored.tokenHash)) + .thenThrow(new IllegalStateException("test-only missing active registry")); + assertDeniedWithoutCallback(missing, new AtomicBoolean()); + + Fixture changed = new Fixture(); + changed.stubCommitted(); + when(changed.registry.readActive(changed.stored.tokenHash)).thenReturn(new byte[] {99}); + assertDeniedWithoutCallback(changed, new AtomicBoolean()); + } + + @Test + void stalePublicPinOrOriginalSignerReceiptIsRejected() { + Fixture pinChanged = new Fixture(); + pinChanged.stubCommitted(); + when(pinChanged.publicSource.sourceIdentity()).thenReturn(pinChanged.differentPin()); + assertDeniedWithoutCallback(pinChanged, new AtomicBoolean()); + + Fixture signerChanged = new Fixture(); + signerChanged.stubCommitted(); + when(signerChanged.signers.requireOriginal(signerChanged.stored.signerReceipt)) + .thenThrow(new IllegalStateException("test-only original signer unavailable")); + assertDeniedWithoutCallback(signerChanged, new AtomicBoolean()); + } + + @Test + void currentSourceEvidenceTupleMembershipAndActualFenceMustMatchOriginalClaims() { + Fixture sourceChanged = new Fixture(); + sourceChanged.stubCommitted(); + when(sourceChanged.snapshot.evidence()).thenReturn(new byte[] {8}); + assertDeniedWithoutCallback(sourceChanged, new AtomicBoolean()); + + Fixture tupleChanged = new Fixture(); + tupleChanged.stubCommitted(); + when(tupleChanged.snapshot.authorityTuple()) + .thenReturn(Map.of("accountAuthorityGeneration", 2L)); + assertDeniedWithoutCallback(tupleChanged, new AtomicBoolean()); + + Fixture membershipChanged = new Fixture(); + membershipChanged.stubCommitted(); + when(membershipChanged.snapshot.membershipVersion()) + .thenReturn(Map.of(membershipChanged.tenantId.toString(), 3L)); + assertDeniedWithoutCallback(membershipChanged, new AtomicBoolean()); + + Fixture fenceChanged = new Fixture(); + fenceChanged.stubCommitted(); + when(fenceChanged.snapshot.issuanceFence()).thenReturn(2L); + assertDeniedWithoutCallback(fenceChanged, new AtomicBoolean()); + } + + @Test + void concurrentCommittedRowChangeAndAmbientSqlTransactionDenyWithoutCallback() { + Fixture changed = new Fixture(); + changed.stubCommitted(); + var changedCommittedRecord = + changed.recordWithIdentity( + changed.accountId, changed.tenantId, changed.tokenJti, "COMMITTED", UUID.randomUUID()); + when(changed.operations.lockCommittedByTokenJti(changed.stored)) + .thenReturn(changedCommittedRecord); + assertDeniedWithoutCallback(changed, new AtomicBoolean()); + + Fixture ambient = new Fixture(); + ambient.stubCommitted(); + TransactionSynchronizationManager.setActualTransactionActive(true); + AtomicBoolean called = new AtomicBoolean(); + assertDeniedWithoutCallback(ambient, called); + verify(ambient.operations, never()) + .findCommittedByTokenJti(ambient.accountId, ambient.tenantId, ambient.tokenJti); + } + + private static void assertDeniedWithoutCallback(Fixture fixture, AtomicBoolean called) { + assertThatThrownBy( + () -> + fixture.actors.withCurrentCommitted( + fixture.accountId, + fixture.tenantId, + fixture.tokenJti, + fixture.environment, + current -> { + called.set(true); + return "unexpected"; + })) + .isInstanceOf(RuntimeException.class); + assertThat(called).isFalse(); + } + + private static final class Fixture { + final UUID accountId = UUID.randomUUID(); + final UUID tenantId = UUID.randomUUID(); + final UUID tokenJti = UUID.randomUUID(); + final UUID requestId = UUID.randomUUID(); + final UUID operationId = UUID.randomUUID(); + final AccountControlUiAuthority.Snapshot snapshot = + mock(AccountControlUiAuthority.Snapshot.class); + final AccountControlUiAuthority authority = mock(AccountControlUiAuthority.class); + final AccountControlUiIssuanceRepository operations = + mock(AccountControlUiIssuanceRepository.class); + final AccountControlUiSignerOwner signers = mock(AccountControlUiSignerOwner.class); + final AccountControlUiCoordination registry = mock(AccountControlUiCoordination.class); + final AccountJwtJwksTrustedSource publicSource = mock(AccountJwtJwksTrustedSource.class); + final CapturedEnvironmentBoundary environment = mock(CapturedEnvironmentBoundary.class); + final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + final AccountPublicJwksCache.SourceIdentity pin = + new AccountPublicJwksCache.SourceIdentity( + "test-control", + "test-cluster", + UUID.randomUUID().toString(), + "test-control", + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + "test-revision", + "https://test-api.example.test:6443", + "a".repeat(64)); + final MutableClock clock = new MutableClock(NOW); + final AccountControlUiActorService actors; + final Instant issuedAt; + final Instant expiresAt; + final byte[] signerReceipt; + final Map claims; + final byte[] activeRegistry; + AccountControlUiIssuanceRepository.Stored stored; + + Fixture() { + this(NOW.minusSeconds(1), NOW.plusSeconds(299)); + } + + Fixture(Instant issuedAt, Instant expiresAt) { + this.issuedAt = issuedAt; + this.expiresAt = expiresAt; + when(snapshot.actor()).thenReturn(accountId); + when(snapshot.tenant()).thenReturn(tenantId); + when(snapshot.authorityTuple()) + .thenReturn( + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 1L, + "tenantAuthorityGeneration", + Map.of(tenantId.toString(), 1L), + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), 1L), + "privateRealmGrantVersions", + List.of())); + when(snapshot.membershipVersion()).thenReturn(Map.of(tenantId.toString(), 2L)); + when(snapshot.issuanceFence()).thenReturn(1L); + when(snapshot.evidence()).thenReturn(new byte[] {7}); + when(snapshot.issuanceFenceSourceVersion()).thenReturn(4L); + claims = + new AccountControlUiSigningSpec( + operationId, requestId, tokenJti, snapshot, issuedAt, expiresAt) + .claims(); + signerReceipt = + AccountControlUiAuthority.canonical( + Map.ofEntries( + Map.entry("schema", "account-control-ui-committed-signer/v1"), + Map.entry("kid", "test-only-control"), + Map.entry("signerGeneration", "1"), + Map.entry("environmentId", pin.environmentId()), + Map.entry("clusterId", pin.clusterId()), + Map.entry("clusterIncarnationUid", pin.clusterIncarnationUid()), + Map.entry("namespace", pin.namespace()), + Map.entry("namespaceUid", pin.namespaceUid()), + Map.entry("publicConfigMapUid", pin.configMapUid()), + Map.entry("apiConfigRevision", pin.bindingRevision()))); + String tokenHash = "b".repeat(64); + activeRegistry = + AccountControlUiAuthority.canonical( + Map.ofEntries( + Map.entry("profile", "control-ui"), + Map.entry("type", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry("state", "active"), + Map.entry("tokenHash", tokenHash), + Map.entry("jti", tokenJti.toString()), + Map.entry("operationId", operationId.toString()), + Map.entry("requestId", requestId.toString()), + Map.entry("accountId", accountId.toString()), + Map.entry("exp", expiresAt.getEpochSecond()), + Map.entry("kid", "test-only-control"), + Map.entry("signerGeneration", "1"))); + stored = + recordWithIdentity(accountId, tenantId, tokenJti, "COMMITTED", operationId, tokenHash); + AccountControlUiSignerOwner.Capture currentSigner = + mock(AccountControlUiSignerOwner.Capture.class); + when(currentSigner.kid()).thenReturn("test-only-control"); + when(currentSigner.generation()).thenReturn("1"); + when(signers.requireOriginal(signerReceipt)).thenReturn(currentSigner); + when(publicSource.sourceIdentity()).thenReturn(pin); + when(registry.readActive(tokenHash)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return activeRegistry.clone(); + }); + when(authority.capture(accountId, tenantId, environment)).thenReturn(snapshot); + when(transactions.getTransaction(any())) + .thenAnswer( + ignored -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + }); + doAnswer( + ignored -> { + TransactionSynchronizationManager.clear(); + return null; + }) + .when(transactions) + .commit(any()); + doAnswer( + ignored -> { + TransactionSynchronizationManager.clear(); + return null; + }) + .when(transactions) + .rollback(any()); + actors = + new AccountControlUiActorService( + operations, + authority, + signers, + registry, + publicSource, + mock(DraftAuthorizationFenceRepository.class), + transactions, + clock); + } + + void stubCommitted() { + when(operations.findCommittedByTokenJti(accountId, tenantId, tokenJti)).thenReturn(stored); + when(operations.lockCommittedByTokenJti(stored)).thenReturn(stored); + var committed = mock(AccountControlUiIssuanceRepository.Committed.class); + when(committed.tokenHash()).thenReturn(stored.tokenHash); + when(operations.requireCommitted(stored)).thenReturn(committed); + } + + AccountPublicJwksCache.SourceIdentity differentPin() { + return new AccountPublicJwksCache.SourceIdentity( + "other-control", + pin.clusterId(), + pin.clusterIncarnationUid(), + pin.namespace(), + pin.namespaceUid(), + pin.configMapUid(), + pin.bindingRevision(), + pin.apiServerOrigin(), + pin.servingCaSha256()); + } + + AccountControlUiIssuanceRepository.Stored recordWithIdentity( + UUID rowAccountId, UUID rowTenantId, UUID rowJti, String status) { + return recordWithIdentity(rowAccountId, rowTenantId, rowJti, status, operationId); + } + + AccountControlUiIssuanceRepository.Stored recordWithIdentity( + UUID rowAccountId, UUID rowTenantId, UUID rowJti, String status, UUID rowOperationId) { + return recordWithIdentity( + rowAccountId, rowTenantId, rowJti, status, rowOperationId, "b".repeat(64)); + } + + private AccountControlUiIssuanceRepository.Stored recordWithIdentity( + UUID rowAccountId, + UUID rowTenantId, + UUID rowJti, + String status, + UUID rowOperationId, + String tokenHash) { + Map values = new HashMap<>(); + values.put("request_id", requestId); + values.put("operation_id", rowOperationId); + values.put("token_jti", rowJti); + values.put("account_uuid", rowAccountId); + values.put("tenant_uuid", rowTenantId); + values.put("caller_context_id", UUID.randomUUID()); + values.put("caller_workload", "test-only-peer"); + values.put("request_mac_key_id", "test-only-mac"); + values.put("request_digest", "a".repeat(64)); + values.put("status", status); + values.put("token_hash", tokenHash); + values.put("claims_payload", AccountControlUiAuthority.canonical(claims)); + values.put("source_payload", new byte[] {7}); + values.put("bundle_payload", new byte[] {8}); + values.put("signer_receipt", signerReceipt); + values.put("pending_registry", new byte[] {11}); + values.put("active_registry", activeRegistry); + values.put("issued_at_epoch_second", issuedAt.getEpochSecond()); + values.put("expires_at_epoch_second", expiresAt.getEpochSecond()); + values.put( + "recovery_expires_at", + OffsetDateTime.ofInstant(expiresAt.plusSeconds(60), ZoneOffset.UTC)); + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(invocation -> values.get(invocation.getArgument(0))); + return new AccountControlUiIssuanceRepository.Stored(row); + } + } + + private static final class MutableClock extends Clock { + private final AtomicReference instant; + private final ZoneId zone; + + MutableClock(Instant initial) { + this(initial, ZoneOffset.UTC); + } + + private MutableClock(Instant initial, ZoneId zone) { + instant = new AtomicReference<>(initial); + this.zone = zone; + } + + void set(Instant value) { + instant.set(value); + } + + @Override + public ZoneId getZone() { + return zone; + } + + @Override + public Clock withZone(ZoneId requestedZone) { + return new MutableClock(instant(), requestedZone); + } + + @Override + public Instant instant() { + return instant.get(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java new file mode 100644 index 0000000000..4ad82f5835 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import org.junit.jupiter.api.Test; + +class AccountStartSessionAuthorityCaptureTest { + @Test + void referenceIdentifiesTheDurableCaptureAndRetainsIndependentFenceValues() { + byte[] snapshot = + AccountControlUiAuthority.canonical( + Map.of( + "accountSourceVersion", "41", + "issuanceFence", "9", + "issuanceFenceSourceVersion", "12", + "sourceVector", java.util.List.of("vector-entry"), + "outboxCheckpoints", java.util.List.of(Map.of("stream", "account/one", "seq", "7")), + "tuple", "exact-tuple")); + + // The two independent numeric domains may coincide; the bundle reference still denotes the + // durable capture allocations and never substitutes them for the actual Account fence. + var capture = + AccountStartSessionAuthorityCapture.create( + "control-plane-request-1", + 9L, + 9L, + "18446744073709551615", + "2026-10-10T12:34:56.789Z", + snapshot); + + assertThat(capture.bundleReference().sourceVersion()).isEqualTo("9"); + assertThat(capture.bundleReference().sourceFence()).isEqualTo("9"); + assertThat(capture.bundleReference().linearization()).isEqualTo("18446744073709551615"); + assertThat(capture.capturedAt()).isEqualTo("2026-10-10T12:34:56.789Z"); + assertThat(capture.snapshotSha256()).hasSize(64); + assertThat(capture.canonicalSha256()).hasSize(64); + assertThat(capture.canonicalBytes()) + .contains("account-start-session-authority-capture/v1".getBytes(StandardCharsets.UTF_8)); + + var readBack = + AccountStartSessionAuthorityCapture.fromStorage( + capture.controlPlaneRequestId(), + capture.sourceVersion(), + capture.sourceFence(), + capture.linearization(), + capture.capturedAt(), + capture.snapshotBytes(), + capture.snapshotSha256(), + capture.canonicalBytes(), + capture.canonicalSha256()); + assertThat(readBack.sameStoredValue(capture)).isTrue(); + assertThat(readBack.bundleReference()).isEqualTo(capture.bundleReference()); + } + + @Test + void snapshotBytesAndReferenceBytesAreDefensiveAndChangingFenceSourceChangesCapture() { + byte[] originalSnapshot = + AccountControlUiAuthority.canonical( + Map.of( + "issuanceFence", + "25", + "issuanceFenceSourceVersion", + "31", + "sourceVector", + java.util.List.of("same-vector"), + "checkpoints", + java.util.List.of("same-checkpoint"))); + var original = + AccountStartSessionAuthorityCapture.create( + "control-plane-request-2", + 44L, + 57L, + "812", + "2026-10-10T12:34:56.789Z", + originalSnapshot); + + byte[] returnedSnapshot = original.snapshotBytes(); + byte[] returnedReference = original.canonicalBytes(); + returnedSnapshot[0] ^= 1; + returnedReference[0] ^= 1; + assertThat(original.snapshotBytes()).isEqualTo(originalSnapshot); + assertThat(original.canonicalBytes()) + .contains("account-start-session-authority-capture/v1".getBytes(StandardCharsets.UTF_8)); + + byte[] changedFenceVersion = + AccountControlUiAuthority.canonical( + Map.of( + "issuanceFence", + "25", + "issuanceFenceSourceVersion", + "32", + "sourceVector", + java.util.List.of("same-vector"), + "checkpoints", + java.util.List.of("same-checkpoint"))); + var changed = + AccountStartSessionAuthorityCapture.create( + "control-plane-request-2", + 45L, + 58L, + "813", + "2026-10-10T12:34:56.790Z", + changedFenceVersion); + + assertThat(original.sameSnapshot(changed)).isFalse(); + assertThat(original.bundleReference()).isNotEqualTo(changed.bundleReference()); + } + + @Test + void rejectsMismatchedRetainedCaptureDigestAndNonPositiveCaptureAllocations() { + byte[] snapshot = AccountControlUiAuthority.canonical(Map.of("source", "owner")); + var capture = + AccountStartSessionAuthorityCapture.create( + "control-plane-request-3", 1L, 2L, "3", "2026-10-10T12:34:56.789Z", snapshot); + + assertThatThrownBy( + () -> + AccountStartSessionAuthorityCapture.fromStorage( + capture.controlPlaneRequestId(), + 1L, + 2L, + "3", + capture.capturedAt(), + snapshot, + "0".repeat(64), + capture.canonicalBytes(), + capture.canonicalSha256())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionAuthorityCapture.create( + "control-plane-request-3", 0L, 2L, "3", "2026-10-10T12:34:56.789Z", snapshot)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java index 28d9252ee3..34783ee2c6 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java @@ -204,14 +204,20 @@ public void requireTupleBinding(StartSessionPreAuthorizationReservationTuple tup } } - /** Binds the separate Account source reference; this does not prove source freshness. */ + /** + * Checks the bundle schema and capture source version against the separate Account reference. + * + *

The caller must independently match every field of this reference to the exact complete + * owner-stored reference/readback. This integrity-only check cannot derive the capture source + * fence from the bundle's independent issuance fence, and grants neither permission nor + * freshness. + */ public void requireReferenceBinding(BundleReference reference) { Objects.requireNonNull(reference, "Account bundle reference is required"); Map projection = object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); if (!BUNDLE_VERSION.equals(reference.bundleVersion()) - || !reference.sourceVersion().equals(projection.get("sourceEvidenceVersion")) - || !reference.sourceFence().equals(value.get("issuanceFence"))) { + || !reference.sourceVersion().equals(projection.get("sourceEvidenceVersion"))) { throw denied("Account bundle reference differs from immutable authority evidence"); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java index 76c4839df2..7932504ed1 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java @@ -177,6 +177,22 @@ void rejectsChangedOperationBindingAndUnknownResponseFields() throws Exception { .hasMessageContaining("invalid redeemed StartSession operation projection"); } + @Test + void rejectsChangedCompleteReferenceWhileSourceFenceIsIndependentOfIssuanceFence() + throws Exception { + Fixture fixture = fixture(CLOCK_NOW.plusSeconds(3_600L)); + startServer(fixture, ResponseMode.CHANGED_SOURCE_FENCE); + client = newClient(server); + client.init(); + + assertThat(fixture.postTuple().bundleReference().sourceFence()) + .isNotEqualTo(Long.toString(ISSUANCE_FENCE)); + assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid redeemed StartSession operation projection"); + assertThat(applicationCalls).hasValue(1); + } + @Test void rejectsExpiredAccountReferenceEvenWhenResponseEchoesOriginalBundle() throws Exception { Fixture fixture = fixture(CLOCK_NOW.minusSeconds(60L)); @@ -258,6 +274,12 @@ public void readRedeemedOperationProjection( ReadRedeemedOperationProjectionResponse response = response(fixture); if (mode == ResponseMode.CHANGED_DIGEST) { response = response.toBuilder().setMutationDigest("0".repeat(64)).build(); + } else if (mode == ResponseMode.CHANGED_SOURCE_FENCE) { + response = + response.toBuilder() + .setBundleReference( + response.getBundleReference().toBuilder().setSourceFence("18").build()) + .build(); } else if (mode == ResponseMode.UNKNOWN_FIELD) { response = response.toBuilder() @@ -359,10 +381,7 @@ private static Fixture fixture(Instant expiresAt, String targetNamespace) { "redeemed-projection-request-β", ACTOR_ID, action); StartSessionAuthorityEvidenceBundle.BundleReference reference = new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "17", - Long.toString(ISSUANCE_FENCE), - "18446744073709551615"); + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "17", "18446744073709551615"); byte[] bundle = authorityEvidenceBundle(preTuple, expiresAt, targetNamespace); StartSessionPostAuthorizationExecutionTuple postTuple = StartSessionPostAuthorizationExecutionTuple.createHuman( @@ -458,6 +477,7 @@ private static Timestamp timestamp(Instant value) { private enum ResponseMode { EXACT, CHANGED_DIGEST, + CHANGED_SOURCE_FENCE, UNKNOWN_FIELD, BLOCK_UNTIL_RELEASED } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java index 458f7004fb..44e50344fc 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.operator; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; @@ -199,20 +200,33 @@ void rejectsInvalidExpiryAndReferenceOverflowOrMismatch() throws Exception { () -> decoded.requireReferenceBinding( new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "18", "23", "17"))) + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "18", "17", "17"))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( + assertThatCode( () -> decoded.requireReferenceBinding( new StartSessionAuthorityEvidenceBundle.BundleReference( StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "17"))) + .doesNotThrowAnyException(); + assertThatThrownBy( + () -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + "authorityEvidenceBundle/v2", "17", "17", "17")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> new StartSessionAuthorityEvidenceBundle.BundleReference( StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "9223372036854775808", - "23", + "17", + "17")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "9223372036854775808", "17")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( @@ -341,7 +355,7 @@ private static Map mutableValue( private static StartSessionAuthorityEvidenceBundle.BundleReference reference() { return new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "17", "18446744073709551615"); } private static byte[] canonical(Object value) throws IOException { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index 3daaa9bb80..57ff2dcce2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamedesign.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.SQLException; import java.time.LocalDateTime; import java.util.List; import java.util.Objects; @@ -159,7 +160,7 @@ private PublishWorkflowSnapshot reconcileFullVersionPublish( "participant digest dependency is temporarily unavailable; retry exact publish request", ex); } - return failDefinitively(request, attempt, version, null, ex); + return failDefinitively(request, attempt, version, null, "PARTICIPANT_DIGEST_COLLECTION", ex); } try { if (selectedBinding == null) { @@ -173,13 +174,13 @@ private PublishWorkflowSnapshot reconcileFullVersionPublish( "participant digest dependency is temporarily unavailable; retry exact publish request", ex); } - return failDefinitively(request, attempt, version, null, ex); + return failDefinitively(request, attempt, version, null, "PUBLICATION_GATE", ex); } try { recordedParticipantDigestService.assertMatchesRecordedDigests( dto.tenantId(), PublishType.FULL_VERSION, participantDigests); } catch (RuntimeException ex) { - return failDefinitively(request, attempt, version, null, ex); + return failDefinitively(request, attempt, version, null, "RECORDED_DIGEST_CHECK", ex); } ExportedAssetManifest exportedManifest; AssetExportService.SelectedExportResult selectedExportResult; @@ -199,7 +200,7 @@ private PublishWorkflowSnapshot reconcileFullVersionPublish( "selected asset candidate or object readback is unresolved; retry exact publish request", unresolved); } catch (RuntimeException ex) { - return failDefinitively(request, attempt, version, null, ex); + return failDefinitively(request, attempt, version, null, "ASSET_EXPORT", ex); } PublishWorkflowRequest effectiveRequest = request; @@ -229,7 +230,8 @@ private PublishWorkflowSnapshot reconcileFullVersionPublish( "full-version finalization left incomplete evidence; readback/reconciliation is required", operationFailure); } - return failDefinitively(request, attempt, version, exportedManifest, operationFailure); + return failDefinitively( + request, attempt, version, exportedManifest, "RELEASE_FINALIZATION", operationFailure); } catch (RuntimeException ambiguousCommit) { PublicationReadback readback; try { @@ -562,9 +564,14 @@ private PublishWorkflowSnapshot failDefinitively( PublishAttempt attempt, Version version, ExportedAssetManifest exportedManifest, + String failureStage, RuntimeException failure) { String failureCode = publishFailureCode(failure); String failureMessage = publishFailureMessage(failure); + logger.warn( + "Definitive full-version publication failure workflowId={} {}", + request.publishWorkflowId(), + safeFailureDiagnostic(failureStage, failure)); try { publishAttemptService.executeFullVersionTransaction( () -> { @@ -605,10 +612,18 @@ private PublishWorkflowSnapshot failDefinitively( return Boolean.TRUE; }); } catch (PublishAttemptService.FullVersionTransactionException ex) { + logger.warn( + "Full-version publication failure settlement unresolved workflowId={} {}", + request.publishWorkflowId(), + safeFailureDiagnostic("FAILURE_SETTLEMENT", ex.causeException())); throw pendingReconciliation( "full-version failure marking commit outcome is unknown; readback/reconciliation is required", ex.causeException()); } catch (RuntimeException ambiguousFailure) { + logger.warn( + "Full-version publication failure settlement unresolved workflowId={} {}", + request.publishWorkflowId(), + safeFailureDiagnostic("FAILURE_SETTLEMENT", ambiguousFailure)); throw pendingReconciliation( "full-version failure marking commit outcome is unknown; readback/reconciliation is required", ambiguousFailure); @@ -1027,4 +1042,37 @@ private Version requireTenantVersion(String tenantId, long versionId) { private String emptyIfNull(String value) { return value == null ? "" : value; } + + /** + * Returns bounded exception type and JDBC status diagnostics without including exception text. + */ + static String safeFailureDiagnostic(String stage, Throwable failure) { + StringBuilder diagnostic = new StringBuilder("stage=").append(stage).append(" causeTypes="); + Throwable current = failure; + int depth = 0; + while (current != null && depth < 5) { + if (depth > 0) { + diagnostic.append(" <- "); + } + diagnostic.append(current.getClass().getName()); + if (current instanceof SQLException sqlException) { + diagnostic + .append("[sqlState=") + .append(emptyIfNullStatic(sqlException.getSQLState())) + .append(",vendorCode=") + .append(sqlException.getErrorCode()) + .append(']'); + } + current = current.getCause(); + depth++; + } + if (current != null) { + diagnostic.append(" <- ..."); + } + return diagnostic.toString(); + } + + private static String emptyIfNullStatic(String value) { + return value == null ? "" : value; + } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 28fe3c30ae..7af93d68db 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -49,6 +49,7 @@ import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; @@ -138,6 +139,7 @@ import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationAdmissionService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociationRepository; +import net.firedevops.firemud.gamedesign.publication.SelectedOwnerIntakeSourceExport; import net.firedevops.firemud.gamedesign.publication.StartSessionLaunchDescriptorProducer; import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; @@ -762,6 +764,78 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(RealmPolicySource.ordered(selectedSources.policy().policies())) .containsExactly(expectedPolicy); + var ownerIntakeSourceRepository = new GameDesignSourceRepository(gd.dsl()); + var sourceRowsBeforeExport = selectedOwnerSourceRowCounts(gd.dsl()); + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + // This scope is only the export's integrity input. No Account authorization or owner + // retention receipt exists for these domains in this composed fixture. + var scope = selectedOwnerSourceScope(owner, selectedCommit); + SelectedOwnerIntakeSourceExport exportedSource = + ownerIntakeSourceRepository.requireSelectedOwnerIntakeSource(scope); + SelectedOwnerIntakeSourceExport exactRetry = + ownerIntakeSourceRepository.requireSelectedOwnerIntakeSource(scope); + + assertThat(exportedSource.scope().selected().canonicalBytes()) + .containsExactly(selectedCommit.canonicalBytes()); + assertThat(exportedSource.sources().command().binding()).isEqualTo(selectedCommit); + assertThat(exportedSource.sources().policy().binding()).isEqualTo(selectedCommit); + assertThat(exportedSource.sources().asset().binding()).isEqualTo(selectedCommit); + assertThat(exportedSource.sources().gameplay().binding()).isEqualTo(selectedCommit); + assertThat(exportedSource.sources().branding().orElseThrow().binding()) + .isEqualTo(selectedCommit); + assertThat(exportedSource.sources().templateConfig().orElseThrow().binding()) + .isEqualTo(selectedCommit); + assertThat(exactRetry.canonicalBytes()).containsExactly(exportedSource.canonicalBytes()); + assertThat(exactRetry.digest()).isEqualTo(exportedSource.digest()); + } + var wrongTarget = + new TargetProof( + gd.target().canonicalTenantId(), + gd.target().canonicalVersionId(), + gd.target().gameDesignVersionRowId() + 1, + gd.target().gameDesignVersionTenantKey(), + gd.target().sourceGameRowId() + 1, + gd.target().sourceGameTenantKey(), + gd.target().sourceProvenanceKind()); + var wrongSelectedBinding = + DraftCommitBinding.create( + wrongTarget, + selectedCommit.requestId(), + selectedCommit.commitId(), + selectedCommit.baseCommitId(), + selectedCommit.revisions(), + selectedCommit.affectedUnits()); + assertThatThrownBy( + () -> + ownerIntakeSourceRepository.requireSelectedOwnerIntakeSource( + selectedOwnerSourceScope(Owner.ENTITY_MANAGEMENT, wrongSelectedBinding))) + .isInstanceOf(IllegalStateException.class); + var missingTarget = + new TargetProof( + UUID.randomUUID(), + gd.target().canonicalVersionId(), + gd.target().gameDesignVersionRowId(), + gd.target().gameDesignVersionTenantKey(), + gd.target().sourceGameRowId(), + gd.target().sourceGameTenantKey(), + gd.target().sourceProvenanceKind()); + var missingSelectedBinding = + DraftCommitBinding.create( + missingTarget, + selectedCommit.requestId(), + selectedCommit.commitId(), + selectedCommit.baseCommitId(), + selectedCommit.revisions(), + selectedCommit.affectedUnits()); + assertThatThrownBy( + () -> + ownerIntakeSourceRepository.requireSelectedOwnerIntakeSource( + selectedOwnerSourceScope( + Owner.AUTOMATION_SCRIPTING, missingSelectedBinding))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Selected Game Design source is unavailable"); + assertThat(selectedOwnerSourceRowCounts(gd.dsl())).isEqualTo(sourceRowsBeforeExport); + var templateSource = new TemplateConfigSourceRepository(gd.dsl()) .readSnapshot(gd.target(), selectedCommit.commitId()) @@ -2039,6 +2113,34 @@ private Store gameDesignStore() { return store.withIdentity(target, savedVersion); } + private static SelectedOwnerIntakeSourceReadScope selectedOwnerSourceScope( + Owner owner, DraftCommitBinding selected) { + return new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + selected); + } + + private static Map selectedOwnerSourceRowCounts(DSLContext dsl) { + return Map.of( + "command", + dsl.fetchCount(DSL.table("game_design_command_source_snapshot")), + "realm-policy", + dsl.fetchCount(DSL.table("game_design_realm_policy_snapshot")), + "asset", + dsl.fetchCount(DSL.table("game_design_asset_source_snapshot")), + "gameplay-rule", + dsl.fetchCount(DSL.table("game_design_gameplay_rule_snapshot")), + "branding", + dsl.fetchCount(DSL.table("game_design_branding_source_snapshot")), + "template-config", + dsl.fetchCount(DSL.table("game_design_template_config_source_snapshot"))); + } + private static Store serviceStore(PostgreSQLContainer postgres, String service) { var schema = service.replace('-', '_') + "_" + UUID.randomUUID().toString().replace("-", ""); var data = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 56387a0568..8551e98c43 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -14,6 +14,7 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; +import java.sql.SQLException; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; @@ -79,6 +80,22 @@ class VersionPublishCommandServiceImplTest { private VersionPublishCommandServiceImpl service; + @Test + void failureDiagnosticsNameStageAndJdbcStateWithoutExceptionMessages() { + SQLException sqlFailure = new SQLException("secret-auth-bytes", "23505", 7); + IllegalStateException failure = new IllegalStateException("credential payload", sqlFailure); + + String diagnostic = + VersionPublishCommandServiceImpl.safeFailureDiagnostic("RELEASE_FINALIZATION", failure); + + assertEquals( + "stage=RELEASE_FINALIZATION causeTypes=java.lang.IllegalStateException" + + " <- java.sql.SQLException[sqlState=23505,vendorCode=7]", + diagnostic); + assertTrue(!diagnostic.contains("secret-auth-bytes")); + assertTrue(!diagnostic.contains("credential payload")); + } + @BeforeEach void setup() { MockitoAnnotations.openMocks(this); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index 878631961b..24bc82d15a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -4,20 +4,24 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Connection; +import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.HexFormat; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.world.RoomTemplateRef; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.exception.DataAccessException; @@ -172,12 +176,17 @@ private WorldCanonicalInstanceLifecycleEvidence readMaterialized( JsonNode input = parseInput(inputJson); requireInputIdentity(input, request, association, captureId); requirePreparationCounts(input, preparation); + var release = association.completeLaunchBinding().evidence().releaseAttestation(); Set expectedRegionTemplates = - requireFrozenGraphIdentity(input, preparation, graphBytes, graphSha256); + requireFrozenGraphIdentity( + input, + preparation, + graphBytes, + graphSha256, + expectedFrozenGraphSchemaVersion(release)); Map operationalRegionAssignments = readOperationalRegionAssignments(association, preparation, expectedRegionTemplates); - var release = association.completeLaunchBinding().evidence().releaseAttestation(); if (!net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence .requiresWorldStartLocationEvidence(release.schemaVersion()) || release.worldStartLocationEvidence() == null) { @@ -358,7 +367,11 @@ private void requirePreparationCounts(JsonNode input, Record preparation) { /** Proves the preparation graph is the immutable graph retained by the exact frozen capture. */ private Set requireFrozenGraphIdentity( - JsonNode input, Record preparation, byte[] graphBytes, String graphSha256) { + JsonNode input, + Record preparation, + byte[] graphBytes, + String graphSha256, + int expectedGraphSchemaVersion) { JsonNode topology = requiredObject(input, "topology"); UUID captureId = required(preparation, "capture_id", UUID.class); Record frozen = @@ -386,11 +399,7 @@ private Set requireFrozenGraphIdentity( try { JsonNode graph = CLOSED_JSON.readTree(graphBytes); - requireFields( - graph, - Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows"), - "Frozen canonical graph"); - requireText(graph, "schemaVersion", "2"); + requireFrozenGraphProfile(graph, expectedGraphSchemaVersion); requireText( graph, "canonicalTenantId", text(requiredObject(input, "identity"), "canonicalTenantId")); requireText(graph, "canonicalVersionId", text(topology, "canonicalVersionId")); @@ -439,6 +448,89 @@ private Set requireFrozenGraphIdentity( } } + private static int expectedFrozenGraphSchemaVersion( + AuthoredWorldReleaseAttestationEvidence release) { + int expectedWorldDigestSchema = + switch (release.schemaVersion()) { + case AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION -> 3; + case AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION -> 4; + default -> + throw invalid("Retained release has no supported selected World graph profile"); + }; + var worldParticipants = + release.participantDigests().stream() + .filter(participant -> "WORLD_MANAGEMENT".equals(participant.participantKey())) + .toList(); + if (worldParticipants.size() != 1 + || worldParticipants.getFirst().digestSchemaVersion() != expectedWorldDigestSchema) { + throw invalid("Retained release World participant differs from its selected graph profile"); + } + return switch (expectedWorldDigestSchema) { + case 3 -> 2; + case 4 -> 3; + default -> throw invalid("Retained release has an unsupported selected World digest schema"); + }; + } + + private static void requireFrozenGraphProfile(JsonNode graph, int expectedSchemaVersion) { + Set expectedFields = + switch (expectedSchemaVersion) { + case 2 -> Set.of("schemaVersion", "canonicalTenantId", "canonicalVersionId", "rows"); + case 3 -> + Set.of( + "schemaVersion", + "canonicalTenantId", + "canonicalVersionId", + "inboundSourceClosure", + "rows"); + default -> throw invalid("Frozen canonical graph has an unsupported schema profile"); + }; + requireFields(graph, expectedFields, "Frozen canonical graph"); + requireText(graph, "schemaVersion", Integer.toString(expectedSchemaVersion)); + if (expectedSchemaVersion == 3) { + requireFrozenGraphInboundClosure(graph); + } + } + + private static void requireFrozenGraphInboundClosure(JsonNode graph) { + JsonNode closure = requiredObject(graph, "inboundSourceClosure"); + requireFields( + closure, + Set.of("schemaVersion", "familyCounts"), + "Frozen canonical graph inbound-source closure"); + requireInteger(closure, "schemaVersion", 1); + JsonNode familyCounts = closure.get("familyCounts"); + List decodedCounts = new ArrayList<>(); + List familyOrder = + WorldDraftTopologyInputGraph.INBOUND_SOURCE_FAMILY_ORDER; + if (familyCounts == null + || !familyCounts.isArray() + || familyCounts.size() != familyOrder.size()) { + throw invalid("Frozen canonical graph inbound-source family vector is incomplete"); + } + for (int index = 0; index < familyOrder.size(); index++) { + JsonNode familyCount = familyCounts.get(index); + requireFields( + familyCount, + Set.of("family", "count"), + "Frozen canonical graph inbound-source family count"); + var expectedFamily = familyOrder.get(index); + requireText(familyCount, "family", expectedFamily.name()); + decodedCounts.add( + new WorldDraftTopologyInputGraph.InboundSourceFamilyCount( + expectedFamily, intValue(familyCount, "count"))); + } + try { + WorldDraftTopologyInputGraph.requireEmptyInboundSourceClosure( + new WorldDraftTopologyInputGraph.InboundSourceClosureDeclaration( + intValue(closure, "schemaVersion"), decodedCounts)); + } catch (IllegalArgumentException unsupportedClosure) { + throw new InvalidLifecycleEvidenceException( + "Frozen canonical graph inbound-source closure is outside the supported profile", + unsupportedClosure); + } + } + /** * Reads every scoped region row together with its REGION topology identity in this same owner * snapshot. The immutable graph's template set and persisted materialization count must match diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index d1b384186a..021c67ea44 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -2393,6 +2393,14 @@ private AccountPublicationAuthorizationBinding isolatedPublicationAccountBinding private ReleaseContent isolatedReleaseContent(WorldCanonicalInstancePreparation.Input input) { var release = input.completeLaunchBinding().evidence().releaseAttestation(); var world = Objects.requireNonNull(release.worldStartLocationEvidence()); + String attestationSchemaVersion = + switch (release.schemaVersion()) { + case AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION -> "v2"; + case AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION -> "v3"; + default -> + throw new IllegalStateException( + "Selected World fixture has no matching release-content schema"); + }; var participants = release.participantDigests().stream() .map( @@ -2415,7 +2423,7 @@ private ReleaseContent isolatedReleaseContent(WorldCanonicalInstancePreparation. release.canonicalVersionId(), release.publishedReleaseBundleRef(), 1, - "v2", + attestationSchemaVersion, release.publishWorkflowId(), release.manifestHash(), release.manifestSchemaVersion(), diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index a63d917bc8..6269704b30 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -3615,27 +3615,67 @@ void selectorPreparationLateFenceLossRollsBackSelectorRuntimeAndAssociationToget var input = preparationInput(f, frozen, selector); completeIsolatedPublicationTerminal(input); var executionIdentity = WorldCanonicalInstanceExecutionTestFixtures.identity(input); + var initialPreallocationAccepted = new AtomicBoolean(); var component = new WorldCanonicalInstancePreparationService( preparationRepository(), ignored -> new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { - private int calls; - public void requireHeld() { - calls++; - if (calls == 3) { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - assertThat( - Objects.requireNonNull( - dsl.fetchOne( - "SELECT count(*) FROM world_canonical_preparation_start_location WHERE canonical_game_instance_id=?", - input.canonicalGameInstanceId())) - .get(0, Long.class)) - .isEqualTo(1L); + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + var intent = + dsl.fetchOne( + "SELECT operation_state FROM world_canonical_instance_execution WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId()); + if (intent != null) { + assertThat(intent.get("operation_state", String.class)) + .isEqualTo("PENDING"); + for (String table : + List.of( + "world_canonical_instance_association", + "world_canonical_instance_preparation", + "world_canonical_preparation_start_location")) { + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM " + + table + + " WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class)) + .isZero(); + } + initialPreallocationAccepted.set(true); + } + return; + } + long selectorRows = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_preparation_start_location WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class); + long associationRows = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_association WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class); + long preparationRows = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_preparation WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, Long.class); + if (selectorRows == 1L) { + assertThat(initialPreallocationAccepted.get()).isTrue(); + assertThat(associationRows).isEqualTo(1L); + assertThat(preparationRows).isEqualTo(1L); throw new IllegalStateException("stipulated late Account fence loss"); } + assertThat(selectorRows).isZero(); + assertThat(associationRows).isZero(); + assertThat(preparationRows).isZero(); } @Override @@ -3647,6 +3687,7 @@ public void close() {} }); assertThatThrownBy(() -> component.prepare(input)) .hasMessageContaining("late Account fence loss"); + assertThat(initialPreallocationAccepted.get()).isTrue(); for (String table : List.of( "world_instance", @@ -3661,6 +3702,13 @@ public void close() {} .get(0, Long.class)) .isZero(); } + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_state FROM world_canonical_instance_execution WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get("operation_state", String.class)) + .isEqualTo("PENDING"); assertThat(appliedRepository().readCommitted(application).orElseThrow().canonicalBytes()) .containsExactly(selector.appliedResultBytes()); assertOrigin(); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java index 6fed725aeb..d886387c74 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java @@ -1,20 +1,29 @@ package unit.net.firedevops.firemud.worldmanagement.tenant; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.UUID; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph; import org.jooq.DSLContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; class WorldCanonicalInstanceLifecycleReadRepositoryTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + @AfterEach void clearTransactionState() { TransactionSynchronizationManager.setActualTransactionActive(false); @@ -34,6 +43,58 @@ void rejectsAmbientTransactionBeforeOpeningIndependentOwnerSnapshot() { verifyNoInteractions(dsl, manager, association); } + @Test + void acceptsOnlyClosedFrozenGraphProfilesAndSupportedInboundClosure() { + assertThatCode(() -> validateFrozenGraphProfile(graphV2(), 2)).doesNotThrowAnyException(); + assertThatThrownBy(() -> validateFrozenGraphProfile(graphV2(), 3)) + .hasMessageContaining("missing or unsupported fields"); + assertThatCode(() -> validateFrozenGraphProfile(graphV3(), 3)).doesNotThrowAnyException(); + + ObjectNode unsupportedClosure = graphV3(); + JsonNode familyCounts = unsupportedClosure.get("inboundSourceClosure").get("familyCounts"); + ((ObjectNode) familyCounts.get(0)).put("count", 1); + assertThatThrownBy(() -> validateFrozenGraphProfile(unsupportedClosure, 3)) + .hasMessageContaining("outside the supported profile"); + } + + private static void validateFrozenGraphProfile(JsonNode graph, int expectedSchemaVersion) { + try { + Method validator = + WorldCanonicalInstanceLifecycleReadRepository.class.getDeclaredMethod( + "requireFrozenGraphProfile", JsonNode.class, int.class); + validator.setAccessible(true); + validator.invoke(null, graph, expectedSchemaVersion); + } catch (InvocationTargetException failure) { + if (failure.getCause() instanceof RuntimeException runtime) throw runtime; + throw new IllegalStateException("Frozen graph profile validation failed", failure.getCause()); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException("Frozen graph profile validator is unavailable", failure); + } + } + + private static ObjectNode graphV2() { + ObjectNode graph = JSON.createObjectNode(); + graph.put("schemaVersion", "2"); + graph.put("canonicalTenantId", "11111111-1111-4111-8111-111111111111"); + graph.put("canonicalVersionId", "22222222-2222-4222-8222-222222222222"); + graph.putArray("rows"); + return graph; + } + + private static ObjectNode graphV3() { + ObjectNode graph = graphV2(); + graph.put("schemaVersion", "3"); + ObjectNode closure = graph.putObject("inboundSourceClosure"); + closure.put("schemaVersion", 1); + var familyCounts = closure.putArray("familyCounts"); + for (var family : WorldDraftTopologyInputGraph.INBOUND_SOURCE_FAMILY_ORDER) { + ObjectNode familyCount = familyCounts.addObject(); + familyCount.put("family", family.name()); + familyCount.put("count", 0); + } + return graph; + } + private static WorldCanonicalInstanceLifecycleEvidence.Request request() { return new WorldCanonicalInstanceLifecycleEvidence.Request( 1, From 47078d56b668dfd4ec74163c40f8b5fe6e2ca2af Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 11:56:53 +1300 Subject: [PATCH 065/129] Compose sole StartSession issuer with durable capture and exact recovery --- ...dmin-as-external-operator-write-ingress.md | 4 +- .../account-service/api-contracts.md | 6 +- .../logging-admin-service/api-contracts.md | 1 + .../runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 10 +- .../v1/logging_admin_service.proto | 35 + services/account-service/build.gradle.kts | 1 + ...StartSessionReservationEvidenceClient.java | 205 ++ ...ionOperatorAuthorizationConfiguration.java | 143 ++ ...essionOperatorAuthorizationRepository.java | 814 +++++++ ...ssionOperatorAuthorizationGrpcService.java | 601 ++++++ ...eratorAuthorizationFingerprintKeyring.java | 221 ++ ...atorAuthorizationReferenceFingerprint.java | 102 + ...tartSessionAuthorityCaptureRepository.java | 19 + ...ntStartSessionOperatorAuthorityBundle.java | 685 ++++++ ...rtSessionOperatorAuthorizationService.java | 1435 +++++++++++++ .../src/main/resources/application.yml | 2 + .../V84__individual_creator_party_sources.sql | 9 + ..._account_control_ui_committed_issuance.sql | 16 +- ...unt_selected_publication_authorization.sql | 23 +- ..._game_logic_intake_terminal_settlement.sql | 3 +- ...count_hosted_terms_disclosure_handoffs.sql | 22 +- ...orizationFencePostgresIntegrationTest.java | 47 +- ...uthorizationRepositoryIntegrationTest.java | 820 +++++++ ...iPositiveOwnerPostgresIntegrationTest.java | 37 + ...tSessionReservationEvidenceClientTest.java | 478 +++++ ...peratorAuthorizationConfigurationTest.java | 268 +++ ...onOperatorAuthorizationRepositoryTest.java | 880 ++++++++ ...JwtReadinessProbeOwnerGrpcServiceTest.java | 2 +- ...nOperatorAuthorizationGrpcServiceTest.java | 581 +++++ ...orAuthorizationFingerprintKeyringTest.java | 173 ++ ...artSessionOperatorAuthorityBundleTest.java | 386 ++++ ...ssionOperatorAuthorizationServiceTest.java | 1883 +++++++++++++++++ .../grpc/GrpcPeerCertificateEvidence.java | 77 + .../grpc/GrpcPeerIdentityInterceptor.java | 13 +- ...ssionPreAuthorizationReservationTuple.java | 2 +- ...nPreAuthorizationReservationTupleTest.java | 9 + .../logging-admin-service/build.gradle.kts | 10 + ...ionPreAuthorizationReservationService.java | 727 +++++++ ...ssionPreAuthorizationReservationTuple.java | 140 ++ ...PreAuthorizationReservationRepository.java | 977 +++++++++ ...SessionReservationEvidenceGrpcService.java | 265 +++ ...essionReservationEvidenceLeafApproval.java | 115 + .../src/main/resources/application.yml | 6 + ...session_pre_authorization_reservations.sql | 29 + ...t_session_post_authorization_execution.sql | 173 ++ ...rt_session_state_scoped_claim_recovery.sql | 207 ++ ...ionReservationPostgresIntegrationTest.java | 1358 ++++++++++++ ...nEvidenceGrpcMutualTlsIntegrationTest.java | 977 +++++++++ ...reAuthorizationReservationServiceTest.java | 639 ++++++ ...nPreAuthorizationReservationTupleTest.java | 171 ++ ...essionReservationMutationBoundaryTest.java | 200 ++ ...ionReservationEvidenceGrpcServiceTest.java | 641 ++++++ ...onReservationEvidenceLeafApprovalTest.java | 151 ++ ...essionReservationMutationTestFixtures.java | 159 ++ ...ldCanonicalInstancePreparationService.java | 55 +- ...nonicalInstancePreparationServiceTest.java | 163 ++ 58 files changed, 17152 insertions(+), 32 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyring.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprint.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerCertificateEvidence.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcService.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApproval.java create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V3__start_session_post_authorization_execution.sql create mode 100644 services/logging-admin-service/src/main/resources/db/migration/V4__start_session_state_scoped_claim_recovery.sql create mode 100644 services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java create mode 100644 services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionReservationMutationBoundaryTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApprovalTest.java create mode 100644 services/logging-admin-service/src/testFixtures/java/net/firedevops/firemud/loggingadmin/StartSessionReservationMutationTestFixtures.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 2f8e0ec2b5..3af5a58919 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -97,7 +97,9 @@ Both issuance paths use the same bounded typed-mutation admission contract befor #### Redeemed StartSession Projection Read -After Game Session has redeemed the original human StartSession reference and allocated its owner attempt and fence, Account may serve `ReadRedeemedOperationProjection` to the exact same-namespace `game-design-service` peer only to read the immutable template-selected source/descriptor for the same original tenant, template, and `controlPlaneRequestId`. The request is bound to the exact canonical pre-authorization tuple, Account-returned authorization-reference fingerprint, original reservation owner/fence, and actual Game Session `ownerAttemptId`/`ownerFence`; Account independently revalidates the original actor and `control-ui` token `jti`, current Account source and reference expiry, and the stored original reservation and redeemed Game Session attempt/fence before returning that projection. No forwarded JWT or opaque reference is sent on this read, and neither workload identity, fingerprint, nor authority-bundle integrity alone establishes authority. The read is credential-free and read-only: it does not renew or extend a reservation/reference, issue or redeem a credential, mutate source state, select a different template or policy, create another owner attempt, commit the owner mutation, or bootstrap/activate a runtime. Exact retries repeat the same binding and return the same operation projection without policy reselection; changed, stale, or ambiguous bindings fail closed. This read is not a commit-spanning CAS proof; owner commit and runtime activation remain separately fenced by their owners. +After Game Session has redeemed the original human StartSession reference and allocated its owner attempt and fence, Account may serve `ReadRedeemedOperationProjection` to the exact same-namespace `game-design-service` peer to read the immutable template-selected source/descriptor for the same original tenant, template, and `controlPlaneRequestId`. The request is bound to the exact canonical pre-authorization tuple, Account-returned authorization-reference fingerprint, original reservation owner/fence, and actual Game Session `ownerAttemptId`/`ownerFence`; Account independently revalidates the original actor and `control-ui` token `jti`, current Account source and reference expiry, and the stored original reservation and redeemed Game Session attempt/fence before returning that projection. No forwarded JWT or opaque reference is sent on this read, and neither workload identity, fingerprint, nor authority-bundle integrity alone establishes authority. The read is credential-free and read-only: it does not renew or extend a reservation/reference, issue or redeem a credential, mutate source state, select a different template or policy, create another owner attempt, commit the owner mutation, or bootstrap/activate a runtime. Exact retries repeat the same binding and return the same operation projection without policy reselection; changed, stale, or ambiguous bindings fail closed. This read is not a commit-spanning CAS proof; owner commit and runtime activation remain separately fenced by their owners. + +The sole additional reader is the exact configured original same-namespace Game Session redeemer, for restricted owner-internal continuation under the same stored, unexpired `PENDING` claim, original attempt/fence and complete tuple. Game Session must read remotely outside SQL, then lock and recheck its original owner operation and database-clock claim expiry at the actual association statement. Only exact replay of an existing immutable selection pin is permitted; this read cannot create a new pin, expose a general replay-created claim, renew or transfer a claim, create another attempt/fence/reference, mutate a domain or authorize admission. Expired, unattached or ambiguous operations remain reconciliation-only. This exception does not widen the distinct World receiving participation or change the original `targetOwner=game-session-service`. #### StartSession World Receiving Participation diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 5a6ccccd7e..b1e7508623 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -58,7 +58,7 @@ This target contract is not complete in the current service. The existing `secur ## Implementation Status -The standalone StartSession capture primitive retains the complete Account source snapshot, independent issuance fence and its source version, original committed ControlUI identity, exact typed request, verified Logging workload and supplied reservation binding in one immutable owner record. Capture version and fence are separate owner allocations; the PostgreSQL transaction identity and database-observed capture timestamp remain exact readback evidence. Workload authentication does not prove the supplied reservation owner/fence. This primitive supplies neither an issuer nor permission: authenticated original-reservation readback, committed capture-before-private-cryptography, final currentness/retry composition and physical repository proof remain open in the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). The runtime paths remain denied. +The sole StartSession issuer composition remains disabled by default. Its post-crypto owner check captures trusted environment evidence again outside SQL before revalidating the exact current actor, retained capture and complete source; the earlier observation cannot substitute after encryption or stored-response decryption. Changed evidence denies issuance or recovery, including a concurrent issuance winner's stored response. These samples, durable source capture and exact original-result recovery do not establish external environment continuity, live reservation mutation authority, commit-spanning foreign claim protection, key custody or physical producer/consumer proof. The [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records the implemented boundary and remaining gates; runtime paths remain denied. This Account source-currentness and first-JOIN persistence prerequisite builds on the authority-storage and retention-safety stage. V40 adds owner-proven fresh issuer/Account source baselines and complete transactional source-event hooks; the owner-local first-JOIN producer/coordinator composes immutable membership, event, audit, and terminal operation evidence. These primitives do not authenticate callers, supply the cross-service target-through-commit gate, add a public route, or wire current LOGIN/public JOIN/Game Session text JOIN. Validation of the reconciled source-currentness stage remains pending; inherited storage proof is not proof of these additions. #2898 and #2848 retain their runtime and recovery gaps. @@ -66,7 +66,7 @@ Current explicit JOIN status: the local `/auth/bootstrap/join` controller and op Explicit playtest grants remain partial: current Account persistence and internal lookup can support a grant-backed admission read, but expiry bounded by fork lifecycle, tenant-admin create/extend/list/revoke, distinct audited platform break-glass, stable request-idempotent outcomes, retained revocation tombstones, and active-binding ejection are not implemented or end-to-end proved. The target owner contract is [Account-Owned Playtest Grant Contract](#account-owned-playtest-grant-contract); the links in authentication, session behavior, journeys, and trackers retain only their local consequences. -Bounded hosted Creator Party, terms-catalog, acceptance/currentness and environment-binding owner storage exists, but no registered hosted-terms API or complete creator-authorized commit path is enabled. The unregistered backend control-ui construction adds primary-authenticated issuance, exact protected recovery and a current-actor Draft ordering entry for one existing initial creator; neither that entry nor the standalone held-order read enables a public route or supplies an authenticated end-to-end commit by itself. Its Account-local committed-JTI currentness entry resolves the exact original account/tenant/token operation and checks its committed owner state, active registry, original signer and current source before the callback; UUID possession is only a lookup key. Both currentness entries compare the independent actual issuance fence with retained claims and recheck token validity after owner lock/read waits. This is an internal prerequisite, not a registered StartSession issuer or World participation producer; complete capture-reference and independent fence-source-version retention still require their owning producer. `ReadHeldOriginalCommitOrder` accepts exact same-namespace World, and same-namespace Game Logic only when the canonical original binding's required-owner vector includes `GAME_LOGIC`; it reads the retained original bytes, order and pending settlement in an independent Account transaction and grants no order-creation or settlement authority. Deadline-qualified authorizations remain denied without physical commit enforcement. The [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md) records the implemented boundary and remaining proof. Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. +Bounded hosted Creator Party, terms-catalog, acceptance/currentness and environment-binding owner storage exists, but no registered hosted-terms API or complete creator-authorized commit path is enabled. The unregistered backend control-ui construction adds primary-authenticated issuance, exact protected recovery and a current-actor Draft ordering entry for one existing initial creator; neither that entry nor the standalone held-order read enables a public route or supplies an authenticated end-to-end commit by itself. Its Account-local committed-JTI currentness entry resolves the exact original account/tenant/token operation and checks its committed owner state, active registry, original signer and current source before the callback; UUID possession is only a lookup key. Both currentness entries compare the independent actual issuance fence with retained claims and recheck token validity after owner lock/read waits. These prerequisites do not enable the disabled StartSession issuer or supply a World participation producer; genuine original-claim protection, protected custody and physical producer/consumer proof remain required. `ReadHeldOriginalCommitOrder` accepts exact same-namespace World, and same-namespace Game Logic only when the canonical original binding's required-owner vector includes `GAME_LOGIC`; it reads the retained original bytes, order and pending settlement in an independent Account transaction and grants no order-creation or settlement authority. Deadline-qualified authorizations remain denied without physical commit enforcement. The [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md) records the implemented boundary and remaining proof. Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. @@ -189,6 +189,8 @@ These RPCs and schemas are accepted target state but are not present in the curr For StartSession, Account's existing human authorization-reference issuer remains the sole issuer and the original reference retains `targetOwner=game-session-service`. The distinct Account-owned same-namespace World receiving-participation and source-protection lifecycle is defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation); this API contract adds no replacement issuer, reference-renewal, or re-redemption path. The Game Design projection read and publication hold/settlement producers remain separate and grant no StartSession World permission. StartSession participation acquisition, World admission, terminal settlement, and their proof remain unimplemented. +The credential-free `ReadRedeemedOperationProjection` receiver accepts the exact configured same-namespace Game Design peer and the exact original Game Session redeemer under [ADR 0047's restricted original-operation read](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). Before returning the retained projection, Account compares the original request/reservation and redeemed workload/attempt/fence, then revalidates the original actor/JTI, current source and reference expiry. The response contains no credential or renewed permission. Game Session must separately prove its original claim and immutable pin under the owner-local checks required by that contract; this Account read is not World participation or admission. + ## REST APIs | Method | Path | Description | diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 7ca506ddb7..a69e13d2ef 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -26,6 +26,7 @@ Routine rollback is expected to leave ordinary gameplay available while scoped A ## Implementation Status +- The passive `StartSessionReservationEvidenceService/ReadCurrentClaimEvidence` receiver requires the exact same-namespace Account workload, no authenticated end-user caller context and an approved actual TLS leaf instance. It validates the complete canonical original reservation and current claim, purpose, fences and expiry before returning read evidence. `ISSUE` and `RECOVER` are read purposes, not mutation capabilities. Production reservation acquisition and transitions remain denied; test-only mutation fixtures do not enable ingress, establish live certificate custody or prove a commit-spanning claim handoff. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records the composed producer, physical proof and activation gaps. - Account-to-Logging audit delivery remains partial in this reconstruction: typed `CreateLogEvent` returns gRPC `UNIMPLEMENTED` and never invokes the legacy generic `log_events` writer. The typed receipt receiver implementation and focused proof are owned by [#2848](https://github.com/benhook1013/FireMUD/pull/2848) and are not integrated in this revision; the target contract above is unchanged. Account's post-commit best-effort delivery path does not establish receiver durability or receipt confirmation. - Feature-flag toggles and scoped tick-remediation pause/resume ingress routes now hard fail closed as unavailable operator mutations until the minimum three-part schema/authorization gate exists: their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus redemption by the receiving authoritative owner. This minimum gate is necessary but not sufficient for live-success support; supported execution also requires the complete durable, idempotent, fenced owner-mutation contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md), including durable intent/audit, stable digest-bound request identity, authoritative-owner state, safety/recovery gates, and durable acknowledgement. The HTTP entrypoints preserve authentication, authorization, and basic request validation, then return `503 Service Unavailable` with stable action-specific unavailable error codes (`FEATURE_FLAG_TOGGLE_UNAVAILABLE` or `TICK_REMEDIATION_UNAVAILABLE`) without invoking a service, owner, or audit dependency. The internal `ToggleFeatureFlag` gRPC entrypoint preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without dispatch. No Logging & Admin feature-flag or tick forwarding method remains callable internally. Admission-pointer reads, audit, and prepared-upgrade proof reads remain live. The current-pointer list forwards only the caller's authorized tenant scopes; an empty owner request remains reserved for global platform administrators and moderators. Each current pointer in the selected scope requires exact latest-audit identity/catalog evidence, and unavailable authority in that scope returns `503`. Public POST/operator mutation routes under `/admission-pointers`, `/cutover`, or `/version-upgrades` are target-only absent: no public HTTP handlers or Gateway write forwarding exist. Internal preparation/cutover service and control-plane implementation remains behind internal trust boundaries, and there is no current UI control. - Availability vocabulary is explicit: **implemented-but-externally-gated** means an executable public controller/owner path exists but the shared mutation gate is incomplete; **target-only absent** means no executable public route exists. Admission-pointer mutation, version-upgrade preparation, and prepared cutover use the latter classification at public HTTP ingress even though internal preparation/cutover implementation remains. Quota-override ingress is also target-only absent. No generic tick-remediation payload or reserved `remediate` route is part of the target; each future recovery operation requires a named typed contract implemented by its authoritative workflow owner. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index f9624b1675..bcee5df2a8 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -33,7 +33,7 @@ World Management instances are intended to be replaceable workers over authorita Execution admission, materialization, canonical association and `COMMITTED` publication share one uninterrupted local SQL transaction. The operation/request and canonical-target serialization precede the existing publication and topology locks; the database checks actual current time after lock waits before admitting execution. Network calls occur before SQL, never under these locks. Operational transaction timeouts and cancellation bound resource use, not the physical instant of commit. An execution admitted while the original authorization and owner claim are valid may finish after ingress expiry; expiry never permits another execution transaction, renewed participation or a replacement attempt. -Exact recovery compares the retained full identity and immutable terminal preparation result. A separate `ABORTED` transaction takes the same operation and target serialization, excludes a live execution and permanently fences later materialization and canonical association. Missing rows, timeouts and rolled-back intermediate states are not abort proof. An unknown outcome remains unresolved until exact `COMMITTED` readback or serialized `ABORTED` proof; Account retains its source protection until authenticated terminal settlement. These storage rules do not supply the missing genuine Account participation producer or authenticated terminal transport. The canonical preparation service remains unavailable for runtime use until that producer, consumer and physical concurrency/recovery proof are complete. +Exact recovery compares the retained full identity and immutable terminal preparation result. Its service read path authenticates the original operation outside SQL, separately from fresh-admission verification, and reads only that stored operation; ingress expiry cannot turn it into renewed execution. Existing constructors deny recovery unless an explicit original-operation verifier is supplied. A separate `ABORTED` transaction takes the same operation and target serialization, excludes a live execution and permanently fences later materialization and canonical association. Missing rows, timeouts and rolled-back intermediate states are not abort proof. An unknown outcome remains unresolved until exact `COMMITTED` readback or serialized `ABORTED` proof; Account retains its source protection until authenticated terminal settlement. These storage rules do not supply the missing genuine Account participation producer or authenticated terminal transport. The canonical preparation service remains unavailable for runtime use until that producer, consumer and physical concurrency/recovery proof are complete. ### Template Identifier Invariants diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 7fcfc5fc4f..53ea233465 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -168,3 +168,9 @@ Entry format: - Observation: The revision guard prevented concurrent replacement but did not prevent a semantically incomplete payload; the standing brief was briefly replaced by the addendum alone. - Expected pattern: Require a string-valued `brief`, preserve it without a missing-field fallback, and read back both the original mandate and the appended instruction after revision. A revision guard is not content validation. - Current status: Restored the complete revision-302 brief from controller history and appended the disposition in revision 304; readback confirmed 66,031 characters and the original mandate. Overseer was informed and preserved the correction in revision 305. No repository behavior or controller policy changed. + +- `2026-10-10`: Service timeouts can erase complete PostgreSQL execution evidence + - Context: PR #3105 run 37992891243 hit all three service job limits after container-fetch errors. Its logs showed an Account historical-fixture SQL failure, but no originating service JUnit/HTML artifacts were available. + - Observation: Cancellation text did not establish concurrency cancellation; configured job limits caused termination. Missing reports prevent complete executed/failed/skipped counts and positive corrected-head proof even when individual failure names appear in logs. + - Expected pattern: Distinguish job timeout, container initialization and assertion failures; retain exact checkout provenance and never turn absent artifacts into passing or skipped totals. Diagnose reproducible fixture causes independently without weakening production guards or inferring provisioning authority. + - Current status: The source and synthetic merge are recorded in the owning tracker/controller. The historical V75 fixture incorrectly called the current initializer requiring V81 tables; its test-only seed is corrected, with physical execution still required. No workflow timeout or infrastructure change was made. 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 6ce6237ec1..5def168536 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 @@ -6,9 +6,15 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The standalone Account StartSession capture primitive adds V128 immutable full-snapshot retention and independent positive signed-64 capture-version/fence allocators, while retaining the actual PostgreSQL transaction identity and database-observed millisecond capture time. The stored snapshot includes the original committed ControlUI operation/JTI/token hash/signer, complete source vector and checkpoints, authority tuple, membership evidence, independent issuance fence and its source version, canonical typed request and exact supplied Logging reservation identity. Its repository requires a current committed-actor callback and verified same-namespace Logging peer; those checks do not prove the upstream reservation claim. Three executed unit cases cover canonical bytes, defensive readback and independent fences. The database definitions cover allocator/immutability installation, the canonical tuple's separately derived digest, and capture insert/exact retry/final readback/conflicts through the real committed ControlUI owner fixture. That fixture explicitly stipulates the upstream Logging reservation; it is not genuine claim or end-to-end authorization proof. The PostgreSQL precision constraint remains active and is excluded narrowly from jOOQ's unsupported simulator rendering. Genuine original-reservation verification, committed capture-before-private-crypto issuer wiring, final issuer currentness/retry and physical repository execution remain open. The composed migration set now has 98 unique versions; no runtime path is activated. +The disabled-by-default sole Account StartSession issuer now composes the original committed ControlUI owner with V128 full source capture. It commits capture before private reference generation, fingerprinting or response encryption, captures trusted environment evidence again outside SQL after private crypto, then rechecks the original actor/JTI, complete current source and exact capture under the final owner transaction before retaining issuance. Capture version/fence and the actual issuance fence remain independent; the one original capture reference is retained unchanged. Exact issue retry, recovery and concurrent-winner recovery use lookup-only capture readback and post-decryption currentness checks before returning the original encrypted result, without allocation, reminting or expiry extension. Original Logging claim expiry is checked before capture, before private crypto and through the final issuance callback; these samples do not establish external environment continuity or commit-spanning foreign claim protection. The passive Logging evidence dependency comes from merged #3132: exact same-namespace Account identity and actual approved certificate leaf, no authenticated end-user context, complete original claim readback, and production reservation mutation still denied. The original configured Game Session redeemer is allowed only the restricted credential-free current projection read; consumer claim/pin proof remains separately owned. Physical PostgreSQL, genuine live reservation authority, custody and activation remain open. -The corrected composed local gate passed all four service full checks, formatting, Checkstyle, SpotBugs, coverage, schema generation, links and Markdown: Common 479, Account 1,125, Game Design 539 and World 594 unit cases (2,737 total), with zero failures/errors/skips. Eight non-container integration cases executed; 606 integration cases skipped without Docker (240 Account, 148 Game Design, 218 World, including Redis definitions). These results do not replace corrected-head physical PostgreSQL execution. Flyway sanity passed 12 sets and 282 versioned files. Independent body-level preservation verified all 43 protected baseline and 25 frozen Gameplay migrations; the creator-party preservation test now isolates the actual V83-to-V84 upgrade. Parent review removed a nonexistent tuple-digest extraction that would have denied every genuine capture, retaining the separately derived snapshot/row digest binding. World paired graph/2 and graph/3 readback, phase-driven late-fence proof and Game Design safe commit diagnostics are included; the finalization root cause still needs executed physical diagnostics. +The corrected sole-issuer/Logging/World recovery composition passes the full affected local checks: 479 Common, 1,178 Account, 224 Logging and 600 World unit cases (2,481 total), without failures, errors or skips. Nine non-container integration cases execute; 489 integration definitions skip without Docker (248 Account, 23 Logging, 218 World, including Redis definitions). Unchanged successful tasks reuse their local results; this is composed working-tree proof, not a fresh physical end-to-end run. Schema generation, affected boot JARs, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass. Flyway sanity passes 12 sets and 285 versioned files. Fourteen issuer-service cases cover mocked owner ordering, exact retry/recovery, changed-source denial and concurrent winner recovery; six World service cases cover explicitly synthetic recovery verification and read-only behavior. The genuine original-operation verifier, expired-operation Game Session producer, World terminal transport and continuously protected Account participation remain missing, not proved by these tests. Parent review also corrected the historical V75 upgrade fixture to use its actual database UUID-provenance insertion path rather than a later V81-dependent repository initializer; physical execution remains required. + +V128 retains the complete source vector/checkpoints, original committed operation/JTI/token hash/signer, authority tuple, membership evidence, independent issuance fence/source version, typed request and exact original reservation binding, plus PostgreSQL transaction identity and millisecond capture time. The real committed ControlUI fixture explicitly stipulates upstream Logging claim evidence; it defines capture insert/retry/lock/conflicts and lookup-only denial without allocator growth, not genuine upstream or end-to-end authorization proof. The composed Account set has 98 unique versions. Gameplay's final V84 TRUNCATE and V98 SHA256 payload guards are preserved byte-exactly from `c69fa3645`, alongside its V90/V91/V96 guards; their new physical execution remains pending. No runtime path is activated. + +Exact-source [Validation run 37992891243](https://github.com/benhook1013/FireMUD/actions/runs/37992891243) at `2cb445617f584d25c805f5c08e9dde67fff4efc4` failed when Game Design, Account and World hit their configured 20/30/30-minute job limits. Container-fetch initialization errors and one Account historical forward-migration SQL failure appear in logs, but no originating service JUnit/HTML artifacts were published; complete counts and positive corrected physical proof are unavailable. The actual checkout `85c8bc99296a687aef221cee1ada99ed702db63a` merges that source into `fe15a31f274b1c9850dd388e83faf540916ee8a3`, not the intended `1a8eefe6824c20b8b07a6d6adadda2ad154476e0` parent. The separate metadata run skips service execution and supplies no runtime credit. Diagnosis and independent construction continue without treating aggregate red CI as a lane-wide stop. + +The previous capture/profile-only composed local gate passed Common, Account, Game Design and World checks, formatting, Checkstyle, SpotBugs, coverage, schema generation, links and Markdown: Common 479, Account 1,125, Game Design 539 and World 594 unit cases (2,737 total), with zero failures/errors/skips. Eight non-container integration cases executed; 606 integration cases skipped without Docker (240 Account, 148 Game Design, 218 World, including Redis definitions). These results do not replace the later sole-issuer composition or corrected-head physical PostgreSQL execution. Flyway sanity then passed 12 sets and 282 versioned files. Independent body-level preservation verified all 43 protected baseline and 25 frozen Gameplay migrations; the creator-party preservation test now isolates the actual V83-to-V84 upgrade. Parent review removed a nonexistent tuple-digest extraction that would have denied every genuine capture, retaining the separately derived snapshot/row digest binding. World paired graph/2 and graph/3 readback, phase-driven late-fence proof and Game Design safe commit diagnostics are included; the finalization root cause still needs executed physical diagnostics. The distinct Entity/Automation preliminary source-read value binds closed owner-specific schema and purpose, exact Account operation/fence/request/actor, unchanged complete selected Draft evidence and the derived same-namespace Account reader. The six-family selected-source export constructor and exact repository accessor retain the original snapshot bytes, reject missing branding/template history and enforce the complete-content bound. Their focused structural proof does not authenticate disclosure, prove owner census/retention or create an owner receipt. A genuine selected-source repository test expansion is prepared; its PostgreSQL execution remains required. The authenticated selected-input transport, distinct Account reservation/finalization and source-writer/disclosure exclusion, actual owner census/retention and exact terminal settlement remain open. diff --git a/protos/logging-admin/v1/logging_admin_service.proto b/protos/logging-admin/v1/logging_admin_service.proto index 210539837f..cb2e04713c 100644 --- a/protos/logging-admin/v1/logging_admin_service.proto +++ b/protos/logging-admin/v1/logging_admin_service.proto @@ -19,6 +19,41 @@ service LoggingAdminService { rpc ToggleFeatureFlag(ToggleFeatureFlagRequest) returns (ToggleFeatureFlagResponse); } +// Read-only Account evidence for the current Logging/Admin StartSession reservation claim. +service StartSessionReservationEvidenceService { + rpc ReadCurrentClaimEvidence(ReadCurrentClaimEvidenceRequest) + returns (ReadCurrentClaimEvidenceResponse); +} + +enum StartSessionReservationEvidencePurpose { + START_SESSION_RESERVATION_EVIDENCE_PURPOSE_UNSPECIFIED = 0; + START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE = 1; + START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER = 2; +} + +message ReadCurrentClaimEvidenceRequest { + string control_plane_request_id = 1; + bytes pre_authorization_tuple_json = 2; + string reservation_owner_id = 3; + int64 reservation_claim_fence = 4; + string claim_owner_id = 5; + int64 claim_fence = 6; + StartSessionReservationEvidencePurpose purpose = 7; +} + +message ReadCurrentClaimEvidenceResponse { + string control_plane_request_id = 1; + bytes pre_authorization_tuple_json = 2; + string mutation_digest = 3; + string reservation_owner_id = 4; + int64 reservation_claim_fence = 5; + string claim_owner_id = 6; + int64 claim_fence = 7; + int64 claim_expires_at_epoch_millis = 8; + int64 observed_at_epoch_millis = 9; + StartSessionReservationEvidencePurpose purpose = 10; +} + message PingRequest {} message PingResponse { diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index ba39d41887..ef84a5547e 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -43,6 +43,7 @@ dependencies { implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) + testImplementation(libs.grpc.inprocess) testImplementation(testFixtures(project(":account-service"))) integrationTestImplementation(testFixtures(project(":account-service"))) } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java new file mode 100644 index 0000000000..5f57a577e3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java @@ -0,0 +1,205 @@ +package net.firedevops.firemud.accountservice.client; + +import com.google.protobuf.ByteString; +import jakarta.annotation.PostConstruct; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +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.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * Reads and validates Logging/Admin's current StartSession reservation claim snapshot. + * + *

The result is fresh read evidence only. It does not authorize a mutation and is not a + * commit-spanning compare-and-set proof. + */ +@Component +public final class StartSessionReservationEvidenceClient + extends AbstractReloadingBlockingGrpcClient< + StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final Clock clock; + + @Autowired + public StartSessionReservationEvidenceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer) { + this(endpoints, tlsProperties, channelFactory, stubCustomizer, Clock.systemUTC()); + } + + StartSessionReservationEvidenceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + Clock clock) { + super( + endpoints, + tlsProperties, + channelFactory, + stubCustomizer, + StartSessionReservationEvidenceClient.class); + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + @PostConstruct + void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getLoggingAdminService(); + } + + @Override + protected String defaultTarget() { + return "logging-admin-service:6565"; + } + + @Override + protected StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + buildStub(io.grpc.ManagedChannel channel) { + return applyStubCustomizer( + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .withCompression("gzip")); + } + + /** Reads the exact active claim for ISSUE or RECOVER and validates every returned binding. */ + public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + Purpose purpose) { + Objects.requireNonNull(tuple, "reservation tuple is required"); + requireNonNilUuid(reservationOwnerId, "reservationOwnerId"); + requireNonNilUuid(currentClaimOwnerId, "currentClaimOwnerId"); + Objects.requireNonNull(purpose, "read purpose is required"); + if (reservationClaimFence <= 0L || currentClaimFence <= 0L) { + throw new IllegalArgumentException("reservation claim fences must be positive"); + } + requirePurposeOwnership( + purpose, reservationOwnerId, reservationClaimFence, currentClaimOwnerId, currentClaimFence); + + byte[] tupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + ReadCurrentClaimEvidenceRequest request = + ReadCurrentClaimEvidenceRequest.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson(ByteString.copyFrom(tupleBytes)) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setClaimOwnerId(currentClaimOwnerId.toString()) + .setClaimFence(currentClaimFence) + .setPurpose(toWirePurpose(purpose)) + .build(); + + var currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException("Logging/Admin reservation evidence client is unavailable"); + } + ReadCurrentClaimEvidenceResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readCurrentClaimEvidence(request); + validateResponse( + response, + tuple, + tupleBytes, + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + purpose); + return response; + } + + private void validateResponse( + ReadCurrentClaimEvidenceResponse response, + StartSessionPreAuthorizationReservationTuple tuple, + byte[] tupleBytes, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + Purpose purpose) { + long localNowEpochMillis = clock.millis(); + if (!response.getUnknownFields().asMap().isEmpty() + || !tuple.controlPlaneRequestId().equals(response.getControlPlaneRequestId()) + || !Arrays.equals(tupleBytes, response.getPreAuthorizationTupleJson().toByteArray()) + || !tuple.mutationDigest().equals(response.getMutationDigest()) + || !reservationOwnerId.toString().equals(response.getReservationOwnerId()) + || response.getReservationClaimFence() != reservationClaimFence + || !currentClaimOwnerId.toString().equals(response.getClaimOwnerId()) + || response.getClaimFence() != currentClaimFence + || response.getPurpose() != toWirePurpose(purpose) + || response.getObservedAtEpochMillis() <= 0L + || response.getObservedAtEpochMillis() > localNowEpochMillis + || response.getClaimExpiresAtEpochMillis() <= response.getObservedAtEpochMillis() + || response.getClaimExpiresAtEpochMillis() <= localNowEpochMillis) { + throw new IllegalStateException( + "Logging/Admin returned stale or mismatched StartSession reservation evidence"); + } + } + + private static void requirePurposeOwnership( + Purpose purpose, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + if (purpose == Purpose.ISSUE + && (!reservationOwnerId.equals(currentClaimOwnerId) + || reservationClaimFence != currentClaimFence)) { + throw new IllegalArgumentException("ISSUE requires the original reservation owner and fence"); + } + if (purpose == Purpose.RECOVER + && (reservationOwnerId.equals(currentClaimOwnerId) + || currentClaimFence <= reservationClaimFence)) { + throw new IllegalArgumentException("RECOVER requires a fresh recovery owner and fence"); + } + } + + private static void requireNonNilUuid(UUID value, String fieldName) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID"); + } + } + + private static StartSessionReservationEvidencePurpose toWirePurpose(Purpose purpose) { + return switch (purpose) { + case ISSUE -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE; + case RECOVER -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER; + }; + } + + public enum Purpose { + ISSUE, + RECOVER + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java new file mode 100644 index 0000000000..eb24bb394c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.accountservice.config; + +import java.nio.file.Path; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCaptureRepository; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +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.transaction.PlatformTransactionManager; + +/** + * Explicit, disabled-by-default composition for Account's human StartSession authorization owner. + * + *

Enabling this composition requires real Account owner sources, trusted key custody, and + * configured bounded timing. This configuration supplies no actor, hosted-terms, fingerprint-key, + * or response-encryption defaults. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = AccountStartSessionOperatorAuthorizationConfiguration.PROPERTY_PREFIX, + name = "enabled", + havingValue = "true", + matchIfMissing = false) +public class AccountStartSessionOperatorAuthorizationConfiguration { + static final String PROPERTY_PREFIX = "firemud.account.start-session-operator-authorization"; + static final String OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN = + "startSessionOperatorResponseEnvelopeCryptography"; + + /** Keeps capture repository registration inside this disabled-by-default feature boundary. */ + @Bean + public AccountStartSessionAuthorityCaptureRepository + accountStartSessionAuthorityCaptureRepository(DSLContext accountDsl) { + return new AccountStartSessionAuthorityCaptureRepository(accountDsl); + } + + /** Creates Account's explicit active/retained HMAC calculator from an owner-supplied source. */ + @Bean + public AccountOperatorAuthorizationFingerprintKeyring + accountStartSessionOperatorFingerprintKeyring( + OwnerKeySource ownerKeySource, + @Value( + "${firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention}") + Duration requiredPostExpiryRetention) { + return new AccountOperatorAuthorizationFingerprintKeyring( + ownerKeySource, Clock.systemUTC(), requiredPostExpiryRetention); + } + + /** + * Creates a separate response-envelope cryptography instance from the operator-only mount. + * + *

The generic Account envelope bean and control-ui cryptography are deliberately not injected + * or reused. Deployment remains responsible for supplying a distinct protected key mount. + */ + @Bean(name = OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN) + @Qualifier(OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN) + public AccountResponseEnvelopeCryptography + accountStartSessionOperatorResponseEnvelopeCryptography( + @Value( + "${firemud.account.start-session-operator-authorization.response-envelope.keyring-path}") + String operatorKeyringPath, + @Value("${firemud.account.response-envelope.keyring-path:}") + String generalAccountKeyringPath) { + Path operatorMount = requiredAbsoluteMount(operatorKeyringPath, "operator response keyring"); + if (generalAccountKeyringPath != null && !generalAccountKeyringPath.isBlank()) { + Path generalMount = Path.of(generalAccountKeyringPath).toAbsolutePath().normalize(); + if (operatorMount.equals(generalMount)) { + throw new IllegalArgumentException( + "Operator response keyring must use its separately supplied mount"); + } + } + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(operatorMount.toString())); + } + + /** Wires only genuine owner collaborators and a same-namespace workload policy. */ + @Bean + public AccountStartSessionOperatorAuthorizationService + accountStartSessionOperatorAuthorizationService( + AccountControlUiActorService actors, + AccountControlUiIssuanceRepository issuanceOperations, + AccountStartSessionAuthorityCaptureRepository captureRepository, + StartSessionReservationEvidenceClient reservationEvidence, + AccountStartSessionOperatorAuthorizationRepository repository, + AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, + @Qualifier(OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN) + AccountResponseEnvelopeCryptography operatorResponseCryptography, + AccountHostedTermsService hostedTerms, + PlatformTransactionManager transactions, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace, + @Value("${firemud.account.start-session-operator-authorization.reference-lifetime}") + Duration referenceLifetime, + @Value("${firemud.account.start-session-operator-authorization.response-recovery-window}") + Duration responseRecoveryWindow) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "A valid configured workload namespace is required for operator authorization"); + } + String peerPrefix = "spiffe://firemud/ns/" + workloadNamespace + "/sa/"; + return new AccountStartSessionOperatorAuthorizationService( + actors, + issuanceOperations, + captureRepository, + reservationEvidence, + repository, + fingerprintKeys, + operatorResponseCryptography, + hostedTerms, + transactions, + Clock.systemUTC(), + new SecureRandom(), + peerPrefix + "logging-admin-service", + peerPrefix + "game-session-service", + referenceLifetime, + responseRecoveryWindow); + } + + private static Path requiredAbsoluteMount(String configuredPath, String field) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException("Explicit " + field + " mount is required"); + } + Path path = Path.of(configuredPath); + if (!path.isAbsolute()) { + throw new IllegalArgumentException("Absolute " + field + " mount is required"); + } + return path.normalize(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java new file mode 100644 index 0000000000..aa34607a0a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java @@ -0,0 +1,814 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Permanent Account-owned issuance and one-time redemption storage for StartSession operator + * authorization. + * + *

Callers must authenticate the immediate workload peer and establish current Account authority + * before invoking this repository. This storage is not authority evidence and a returned record is + * not a source-snapshot guarantee. Callers enforce the immutable response-envelope expiry before + * recovering or decrypting that envelope. All methods require the caller's ambient Account + * transaction; this repository performs no network calls and creates no credentials, references, or + * keys. + */ +@Repository +public class AccountStartSessionOperatorAuthorizationRepository { + private static final String TABLE = "account_start_session_operator_authorizations"; + private static final String SELECT_COLUMNS = + "control_plane_request_id, pre_authorization_tuple, mutation_digest, " + + "issuance_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "issuance_operation_id, issuance_fence, bundle_version, bundle_source_version, " + + "bundle_source_fence, bundle_linearization, authority_evidence_bundle, " + + "authorization_reference_fingerprint, encrypted_response_envelope, issued_at, " + + "reference_expires_at, response_envelope_expires_at, status, " + + "redemption_redeemer_workload_uri, redemption_owner_attempt_id, " + + "redemption_owner_fence, redeemed_at, redemption_reference_fingerprint, " + + "redemption_authority_evidence_bundle"; + private static final int MAX_TUPLE_BYTES = 8 * 1024; + private static final int MAX_AUTHORITY_BUNDLE_BYTES = 128 * 1024; + private static final int MAX_ENCRYPTED_ENVELOPE_BYTES = 64 * 1024; + private static final Duration MAX_REFERENCE_LIFETIME = Duration.ofMinutes(5); + private static final Duration MAX_RESPONSE_RECOVERY_WINDOW = Duration.ofMinutes(1); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern FINGERPRINT = + Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); + private static final Pattern SPIFFE_WORKLOAD_URI = + Pattern.compile( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/" + + "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Constructor validates the injected DSL collaborator without acquiring resources or exposing a partially initialized repository.") + public AccountStartSessionOperatorAuthorizationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Inserts the one permanent issuance row or returns its exact original output on duplicate. + * + *

The stable canonical control-plane request ID is the unique key. Duplicate comparison covers + * every original pre-authorization binding; candidate output fields are deliberately not compared + * or substituted when a row already exists. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CreateOrReadResult createOrReadExact(IssuanceCandidate candidate) { + requireOwnerTransaction(); + validateCandidate(candidate); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (control_plane_request_id, pre_authorization_tuple, mutation_digest, " + + "issuance_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "issuance_operation_id, issuance_fence, bundle_version, bundle_source_version, " + + "bundle_source_fence, bundle_linearization, authority_evidence_bundle, " + + "authorization_reference_fingerprint, encrypted_response_envelope, issued_at, " + + "reference_expires_at, response_envelope_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ISSUED') " + + "ON CONFLICT (control_plane_request_id) DO NOTHING", + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.mutationDigest(), + candidate.issuanceWorkloadUri(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + candidate.issuanceOperationId(), + candidate.issuanceFence(), + candidate.bundleReference().bundleVersion(), + candidate.bundleReference().sourceVersion(), + candidate.bundleReference().sourceFence(), + candidate.bundleReference().linearization(), + candidate.authorityEvidenceBundle(), + candidate.authorizationReferenceFingerprint(), + candidate.encryptedResponseEnvelope(), + utc(candidate.issuedAt()), + utc(candidate.referenceExpiresAt()), + utc(candidate.responseEnvelopeExpiresAt())); + + Record row = lockByRequestId(candidate.controlPlaneRequestId()); + IssuanceRecord original = toIssuanceRecord(row); + requireSameOriginalBinding(candidate, original); + return new CreateOrReadResult(inserted == 1, original); + } + + /** Reads the permanent issuance record by its stable canonical request ID. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByControlPlaneRequestId(String controlPlaneRequestId) { + requireOwnerTransaction(); + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE control_plane_request_id = ?", + controlPlaneRequestId); + return Optional.ofNullable(row == null ? null : toIssuanceRecord(row)); + } + + /** + * Atomically consumes an unexpired exact reference binding for one owner attempt. + * + *

The stored redemption projection contains only the immutable fingerprint and the exact + * source-bound authority bundle. An exact retry returns that same projection with {@code + * replay=true}; it does not authorize a different owner attempt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public RedemptionResult redeemExact(RedemptionRequest request) { + requireOwnerTransaction(); + validateRedemptionRequest(request); + Record row = lockByRequestId(request.controlPlaneRequestId()); + if (row == null) { + throw unavailable(); + } + IssuanceRecord issuance = toIssuanceRecord(row); + requireSameRedemptionBinding(request, issuance); + + if (issuance.status() == Status.REDEEMED) { + if (!request.redeemerWorkloadUri().equals(issuance.redemptionRedeemerWorkloadUri()) + || !request.ownerAttemptId().equals(issuance.redemptionOwnerAttemptId()) + || request.ownerFence() != issuance.redemptionOwnerFence()) { + throw conflict(); + } + return redemptionResult(issuance, true); + } + if (issuance.referenceExpiresAt().compareTo(request.now()) <= 0) { + throw new ReferenceExpiredException(); + } + + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'REDEEMED', redemption_redeemer_workload_uri = ?, " + + "redemption_owner_attempt_id = ?, redemption_owner_fence = ?, redeemed_at = ?, " + + "redemption_reference_fingerprint = ?, " + + "redemption_authority_evidence_bundle = ? " + + "WHERE control_plane_request_id = ? AND status = 'ISSUED' " + + "AND reference_expires_at > ?", + request.redeemerWorkloadUri(), + request.ownerAttemptId(), + request.ownerFence(), + utc(request.now()), + request.authorizationReferenceFingerprint(), + request.authorityEvidenceBundle(), + request.controlPlaneRequestId(), + utc(request.now())); + if (changed != 1) { + throw unavailable(); + } + + Record redeemedRow = lockByRequestId(request.controlPlaneRequestId()); + IssuanceRecord redeemed = toIssuanceRecord(redeemedRow); + return redemptionResult(redeemed, false); + } + + private Record lockByRequestId(String requestId) { + return dsl.fetchOne( + "SELECT " + + SELECT_COLUMNS + + " FROM " + + TABLE + + " WHERE control_plane_request_id = ? FOR UPDATE", + requestId); + } + + private IssuanceRecord toIssuanceRecord(Record row) { + if (row == null) { + throw unavailable(); + } + IssuanceRecord issuance = + new IssuanceRecord( + requiredControlPlaneRequestId(row.get("control_plane_request_id", String.class)), + requiredBytes(row, "pre_authorization_tuple", MAX_TUPLE_BYTES), + requiredDigest(row.get("mutation_digest", String.class)), + requiredWorkloadUri(row.get("issuance_workload_uri", String.class)), + requiredUuid(row.get("reservation_owner_id", UUID.class), "reservation owner ID"), + requiredPositive( + row.get("reservation_claim_fence", Long.class), "reservation claim fence"), + requiredUuid(row.get("issuance_operation_id", UUID.class), "issuance operation ID"), + requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"), + bundleReference(row), + requiredBytes(row, "authority_evidence_bundle", MAX_AUTHORITY_BUNDLE_BYTES), + requiredFingerprint(row.get("authorization_reference_fingerprint", String.class)), + requiredBytes(row, "encrypted_response_envelope", MAX_ENCRYPTED_ENVELOPE_BYTES), + requiredInstant(row.get("issued_at", OffsetDateTime.class), "issue time"), + requiredInstant( + row.get("reference_expires_at", OffsetDateTime.class), "reference expiry"), + requiredInstant( + row.get("response_envelope_expires_at", OffsetDateTime.class), + "response-envelope expiry"), + parseStatus(row.get("status", String.class)), + optionalWorkloadUri(row.get("redemption_redeemer_workload_uri", String.class)), + optionalUuid(row.get("redemption_owner_attempt_id", UUID.class), "owner attempt ID"), + optionalPositive(row.get("redemption_owner_fence", Long.class), "owner fence"), + optionalInstant(row.get("redeemed_at", OffsetDateTime.class), "redemption time"), + optionalFingerprint(row.get("redemption_reference_fingerprint", String.class)), + optionalBytes(row, "redemption_authority_evidence_bundle", MAX_AUTHORITY_BUNDLE_BYTES)); + validateDurableRecord(issuance); + return issuance; + } + + private static void validateDurableRecord(IssuanceRecord issuance) { + try { + StartSessionPreAuthorizationReservationTuple tuple = + decodeTuple(issuance.preAuthorizationTuple()); + if (!issuance.controlPlaneRequestId().equals(tuple.controlPlaneRequestId()) + || !tuple.mutationDigest().equals(issuance.mutationDigest()) + || !issuance.issuanceWorkloadUri().endsWith("/sa/logging-admin-service") + || issuance.reservationClaimFence() <= 0L + || issuance.issuanceFence() <= 0L + || !issuance.referenceExpiresAt().isAfter(issuance.issuedAt()) + || issuance.referenceExpiresAt().isAfter(issuance.issuedAt().plus(MAX_REFERENCE_LIFETIME)) + || !issuance.responseEnvelopeExpiresAt().isAfter(issuance.referenceExpiresAt()) + || issuance + .responseEnvelopeExpiresAt() + .isAfter(issuance.referenceExpiresAt().plus(MAX_RESPONSE_RECOVERY_WINDOW))) { + throw unavailable(); + } + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(issuance.authorityEvidenceBundle()); + bundle.requireReferenceBinding(issuance.bundleReference()); + if (!Long.toString(issuance.issuanceFence()).equals(bundle.issuanceFence()) + || !issuance.bundleReference().sourceVersion().equals(bundle.sourceEvidenceVersion())) { + throw unavailable(); + } + if (issuance.status() == Status.REDEEMED + && (!ownerWorkloadUri(issuance.issuanceWorkloadUri(), issuance.preAuthorizationTuple()) + .equals(issuance.redemptionRedeemerWorkloadUri()) + || !issuance + .authorizationReferenceFingerprint() + .equals(issuance.redemptionReferenceFingerprint()) + || !Arrays.equals( + issuance.authorityEvidenceBundle(), + issuance.redemptionAuthorityEvidenceBundle()))) { + throw unavailable(); + } + } catch (IllegalStateException stateFailure) { + throw stateFailure; + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static void validateCandidate(IssuanceCandidate candidate) { + Objects.requireNonNull(candidate, "issuance candidate is required"); + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + candidate.controlPlaneRequestId()); + byte[] tupleBytes = requireBytes(candidate.preAuthorizationTuple(), MAX_TUPLE_BYTES, "tuple"); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(tupleBytes); + if (!candidate.controlPlaneRequestId().equals(tuple.controlPlaneRequestId()) + || !tuple.mutationDigest().equals(candidate.mutationDigest())) { + throw new IllegalArgumentException("pre-authorization tuple identity or digest mismatches"); + } + requireDigest(candidate.mutationDigest()); + String issuer = requireWorkloadUri(candidate.issuanceWorkloadUri()); + if (!issuer.endsWith("/sa/logging-admin-service")) { + throw new IllegalArgumentException("StartSession issuer must be Logging/Admin workload"); + } + requireNonNilUuid(candidate.reservationOwnerId(), "reservationOwnerId"); + requirePositive(candidate.reservationClaimFence(), "reservationClaimFence"); + requireNonNilUuid(candidate.issuanceOperationId(), "issuanceOperationId"); + requirePositive(candidate.issuanceFence(), "issuanceFence"); + requireBundleReference(candidate.bundleReference()); + requireBytes( + candidate.authorityEvidenceBundle(), MAX_AUTHORITY_BUNDLE_BYTES, "authority bundle"); + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(candidate.authorityEvidenceBundle()); + bundle.requireReferenceBinding(candidate.bundleReference()); + if (!Long.toString(candidate.issuanceFence()).equals(bundle.issuanceFence()) + || !candidate.bundleReference().sourceVersion().equals(bundle.sourceEvidenceVersion())) { + throw new IllegalArgumentException( + "bundle reference or Account issuance fence differs from the candidate"); + } + requireFingerprint(candidate.authorizationReferenceFingerprint()); + requireBytes( + candidate.encryptedResponseEnvelope(), + MAX_ENCRYPTED_ENVELOPE_BYTES, + "encrypted response envelope"); + Objects.requireNonNull(candidate.issuedAt(), "issue time is required"); + Objects.requireNonNull(candidate.referenceExpiresAt(), "reference expiry is required"); + Objects.requireNonNull( + candidate.responseEnvelopeExpiresAt(), "response-envelope expiry is required"); + if (!candidate.issuedAt().isAfter(Instant.EPOCH) + || !candidate.referenceExpiresAt().isAfter(candidate.issuedAt()) + || candidate.referenceExpiresAt().isAfter(candidate.issuedAt().plus(MAX_REFERENCE_LIFETIME)) + || !candidate.responseEnvelopeExpiresAt().isAfter(candidate.referenceExpiresAt()) + || candidate + .responseEnvelopeExpiresAt() + .isAfter(candidate.referenceExpiresAt().plus(MAX_RESPONSE_RECOVERY_WINDOW))) { + throw new IllegalArgumentException("authorization reference lifetime is outside its bound"); + } + } + + private static void validateRedemptionRequest(RedemptionRequest request) { + Objects.requireNonNull(request, "redemption request is required"); + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + request.controlPlaneRequestId()); + byte[] tupleBytes = requireBytes(request.preAuthorizationTuple(), MAX_TUPLE_BYTES, "tuple"); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(tupleBytes); + if (!request.controlPlaneRequestId().equals(tuple.controlPlaneRequestId())) { + throw new IllegalArgumentException("pre-authorization tuple request ID mismatches"); + } + requireDigest(tuple.mutationDigest()); + requireFingerprint(request.authorizationReferenceFingerprint()); + requireNonNilUuid(request.reservationOwnerId(), "reservationOwnerId"); + requirePositive(request.reservationClaimFence(), "reservationClaimFence"); + String redeemer = requireWorkloadUri(request.redeemerWorkloadUri()); + if (!redeemer.endsWith("/sa/" + tuple.targetOwner())) { + throw new IllegalArgumentException("redeemer workload does not match the typed target owner"); + } + requireNonNilUuid(request.ownerAttemptId(), "ownerAttemptId"); + requirePositive(request.ownerFence(), "ownerFence"); + requireBytes(request.authorityEvidenceBundle(), MAX_AUTHORITY_BUNDLE_BYTES, "authority bundle"); + Objects.requireNonNull(request.now(), "redemption time is required"); + if (!request.now().isAfter(Instant.EPOCH)) { + throw new IllegalArgumentException("redemption time must be after the Unix epoch"); + } + } + + private static void requireSameOriginalBinding( + IssuanceCandidate candidate, IssuanceRecord original) { + if (!Arrays.equals(candidate.preAuthorizationTuple(), original.preAuthorizationTuple()) + || !candidate.mutationDigest().equals(original.mutationDigest()) + || !candidate.issuanceWorkloadUri().equals(original.issuanceWorkloadUri()) + || !candidate.reservationOwnerId().equals(original.reservationOwnerId()) + || candidate.reservationClaimFence() != original.reservationClaimFence()) { + throw conflict(); + } + } + + private static BundleReference bundleReference(Record row) { + return new BundleReference( + row.get("bundle_version", String.class), + row.get("bundle_source_version", String.class), + row.get("bundle_source_fence", String.class), + row.get("bundle_linearization", String.class)); + } + + private static void requireBundleReference(BundleReference reference) { + Objects.requireNonNull(reference, "original authority bundle reference is required"); + } + + private static void requireSameRedemptionBinding( + RedemptionRequest request, IssuanceRecord issuance) { + if (!Arrays.equals(request.preAuthorizationTuple(), issuance.preAuthorizationTuple()) + || !request + .authorizationReferenceFingerprint() + .equals(issuance.authorizationReferenceFingerprint()) + || !request.reservationOwnerId().equals(issuance.reservationOwnerId()) + || request.reservationClaimFence() != issuance.reservationClaimFence() + || !Arrays.equals(request.authorityEvidenceBundle(), issuance.authorityEvidenceBundle()) + || !request + .redeemerWorkloadUri() + .equals( + ownerWorkloadUri( + issuance.issuanceWorkloadUri(), request.preAuthorizationTuple()))) { + throw conflict(); + } + } + + private static String ownerWorkloadUri(String issuerWorkloadUri, byte[] tupleBytes) { + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(tupleBytes); + int serviceSeparator = issuerWorkloadUri.lastIndexOf("/sa/"); + if (serviceSeparator < 0) { + throw unavailable(); + } + return issuerWorkloadUri.substring(0, serviceSeparator) + "/sa/" + tuple.targetOwner(); + } + + private static RedemptionResult redemptionResult(IssuanceRecord issuance, boolean replay) { + if (issuance.status() != Status.REDEEMED + || !issuance + .authorizationReferenceFingerprint() + .equals(issuance.redemptionReferenceFingerprint()) + || !Arrays.equals( + issuance.authorityEvidenceBundle(), issuance.redemptionAuthorityEvidenceBundle())) { + throw unavailable(); + } + return new RedemptionResult( + issuance.authorizationReferenceFingerprint(), + issuance.redemptionAuthorityEvidenceBundle(), + issuance.issuanceOperationId(), + issuance.issuanceFence(), + replay); + } + + private static StartSessionPreAuthorizationReservationTuple decodeTuple(byte[] bytes) { + String json = new String(bytes, StandardCharsets.UTF_8); + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(json); + if (!Arrays.equals(bytes, tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("pre-authorization tuple bytes are not canonical UTF-8"); + } + return tuple; + } + + private static String requiredControlPlaneRequestId(String value) { + try { + return StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + value); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static String requireWorkloadUri(String value) { + if (value == null + || value.length() > 256 + || !SPIFFE_WORKLOAD_URI.matcher(value).matches() + || !URI.create(value).toASCIIString().equals(value)) { + throw new IllegalArgumentException("authenticated SPIFFE workload URI is malformed"); + } + return value; + } + + private static String requiredWorkloadUri(String value) { + try { + return requireWorkloadUri(value); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static String optionalWorkloadUri(String value) { + return value == null ? null : requiredWorkloadUri(value); + } + + private static String requireDigest(String value) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException("mutation digest is malformed"); + } + return value; + } + + private static String requiredDigest(String value) { + try { + return requireDigest(value); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static String requireFingerprint(String value) { + if (value == null || !FINGERPRINT.matcher(value).matches()) { + throw new IllegalArgumentException("authorization-reference fingerprint is malformed"); + } + return value; + } + + private static String requiredFingerprint(String value) { + try { + return requireFingerprint(value); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static String optionalFingerprint(String value) { + return value == null ? null : requiredFingerprint(value); + } + + private static byte[] requireBytes(byte[] value, int maximum, String field) { + if (value == null || value.length == 0 || value.length > maximum) { + throw new IllegalArgumentException(field + " bytes are missing or exceed their bound"); + } + return value; + } + + private static byte[] requiredBytes(Record row, String field, int maximum) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0 || value.length > maximum) { + throw unavailable(); + } + return value; + } + + private static byte[] optionalBytes(Record row, String field, int maximum) { + byte[] value = row.get(field, byte[].class); + if (value == null) { + return null; + } + if (value.length == 0 || value.length > maximum) { + throw unavailable(); + } + return value; + } + + private static UUID requiredUuid(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw unavailable(); + } + return value; + } + + private static UUID optionalUuid(UUID value, String field) { + return value == null ? null : requiredUuid(value, field); + } + + private static long requiredPositive(Long value, String field) { + if (value == null || value <= 0L) { + throw unavailable(); + } + return value; + } + + private static Long optionalPositive(Long value, String field) { + if (value == null) { + return null; + } + if (value <= 0L) { + throw unavailable(); + } + return value; + } + + private static Instant requiredInstant(OffsetDateTime value, String field) { + if (value == null || !value.toInstant().isAfter(Instant.EPOCH)) { + throw unavailable(); + } + return value.toInstant(); + } + + private static Instant optionalInstant(OffsetDateTime value, String field) { + return value == null ? null : requiredInstant(value, field); + } + + private static Status parseStatus(String value) { + try { + return Status.valueOf(value); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "StartSession operator authorization storage requires an active Account transaction"); + } + } + + private static UUID requireNonNilUuid(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical nonnil UUID"); + } + return value; + } + + private static long requirePositive(long value, String field) { + if (value <= 0L) { + throw new IllegalArgumentException(field + " must be positive"); + } + return value; + } + + private static OffsetDateTime utc(Instant instant) { + return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); + } + + private static IllegalStateException conflict() { + return new IllegalStateException( + "StartSession operator authorization request conflicts with its immutable binding"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Exact StartSession operator authorization evidence unavailable"); + } + + public enum Status { + ISSUED, + REDEEMED + } + + public record CreateOrReadResult(boolean created, IssuanceRecord issuance) { + public CreateOrReadResult { + Objects.requireNonNull(issuance, "issuance record is required"); + } + } + + /** Candidate output fields must be created by the Account authority service, never this store. */ + public record IssuanceCandidate( + String controlPlaneRequestId, + byte[] preAuthorizationTuple, + String mutationDigest, + String issuanceWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + UUID issuanceOperationId, + long issuanceFence, + BundleReference bundleReference, + byte[] authorityEvidenceBundle, + String authorizationReferenceFingerprint, + byte[] encryptedResponseEnvelope, + Instant issuedAt, + Instant referenceExpiresAt, + Instant responseEnvelopeExpiresAt) { + public IssuanceCandidate { + Objects.requireNonNull(bundleReference, "original authority bundle reference is required"); + preAuthorizationTuple = copy(preAuthorizationTuple); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + encryptedResponseEnvelope = copy(encryptedResponseEnvelope); + } + + @Override + public byte[] preAuthorizationTuple() { + return copy(preAuthorizationTuple); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public byte[] encryptedResponseEnvelope() { + return copy(encryptedResponseEnvelope); + } + + @Override + public String toString() { + return "IssuanceCandidate[controlPlaneRequestId=" + + controlPlaneRequestId + + ", tuple/evidence/envelope redacted]"; + } + } + + /** Immutable durable row view; raw references appear only inside its encrypted envelope. */ + public record IssuanceRecord( + String controlPlaneRequestId, + byte[] preAuthorizationTuple, + String mutationDigest, + String issuanceWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + UUID issuanceOperationId, + long issuanceFence, + BundleReference bundleReference, + byte[] authorityEvidenceBundle, + String authorizationReferenceFingerprint, + byte[] encryptedResponseEnvelope, + Instant issuedAt, + Instant referenceExpiresAt, + Instant responseEnvelopeExpiresAt, + Status status, + String redemptionRedeemerWorkloadUri, + UUID redemptionOwnerAttemptId, + Long redemptionOwnerFence, + Instant redeemedAt, + String redemptionReferenceFingerprint, + byte[] redemptionAuthorityEvidenceBundle) { + public IssuanceRecord { + preAuthorizationTuple = copy(preAuthorizationTuple); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + encryptedResponseEnvelope = copy(encryptedResponseEnvelope); + redemptionAuthorityEvidenceBundle = copy(redemptionAuthorityEvidenceBundle); + Objects.requireNonNull(status, "status is required"); + if (issuanceFence <= 0L) throw unavailable(); + requireBundleReference(bundleReference); + if (status == Status.ISSUED + && (redemptionRedeemerWorkloadUri != null + || redemptionOwnerAttemptId != null + || redemptionOwnerFence != null + || redeemedAt != null + || redemptionReferenceFingerprint != null + || redemptionAuthorityEvidenceBundle != null)) { + throw unavailable(); + } + if (status == Status.REDEEMED + && (redemptionRedeemerWorkloadUri == null + || redemptionOwnerAttemptId == null + || redemptionOwnerFence == null + || redeemedAt == null + || redemptionReferenceFingerprint == null + || redemptionAuthorityEvidenceBundle == null)) { + throw unavailable(); + } + } + + @Override + public byte[] preAuthorizationTuple() { + return copy(preAuthorizationTuple); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public byte[] encryptedResponseEnvelope() { + return copy(encryptedResponseEnvelope); + } + + @Override + public byte[] redemptionAuthorityEvidenceBundle() { + return copy(redemptionAuthorityEvidenceBundle); + } + + @Override + public String toString() { + return "IssuanceRecord[controlPlaneRequestId=" + + controlPlaneRequestId + + ", status=" + + status + + ", tuple/evidence/envelope redacted]"; + } + } + + public record RedemptionRequest( + String controlPlaneRequestId, + byte[] preAuthorizationTuple, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + String redeemerWorkloadUri, + UUID ownerAttemptId, + long ownerFence, + byte[] authorityEvidenceBundle, + Instant now) { + public RedemptionRequest { + preAuthorizationTuple = copy(preAuthorizationTuple); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + } + + @Override + public byte[] preAuthorizationTuple() { + return copy(preAuthorizationTuple); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public String toString() { + return "RedemptionRequest[controlPlaneRequestId=" + + controlPlaneRequestId + + ", tuple/evidence redacted]"; + } + } + + /** The one-time result contains authority projection only; it never contains the opaque ref. */ + public record RedemptionResult( + String authorizationReferenceFingerprint, + byte[] authorityEvidenceBundle, + UUID issuanceOperationId, + long issuanceFence, + boolean replay) { + public RedemptionResult { + authorityEvidenceBundle = copy(authorityEvidenceBundle); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public String toString() { + return "RedemptionResult[issuanceOperationId=" + + issuanceOperationId + + ", replay=" + + replay + + ", authority bundle redacted]"; + } + } + + public static final class ReferenceExpiredException extends IllegalStateException { + private ReferenceExpiredException() { + super("StartSession operator authorization reference is expired"); + } + } + + private static byte[] copy(byte[] value) { + return value == null ? null : value.clone(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java new file mode 100644 index 0000000000..416a7328d8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java @@ -0,0 +1,601 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorityBundle.BundleReference; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.AuthorizationResponse; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.IssueRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RecoverRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.exception.DataAccessException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.CannotCreateTransactionException; + +/** Disabled-by-default, same-namespace mTLS receiver for human StartSession authorization. */ +@GrpcService +@ConditionalOnProperty( + prefix = "firemud.account.start-session-operator-authorization", + name = "enabled", + havingValue = "true", + matchIfMissing = false) +public final class StartSessionOperatorAuthorizationGrpcService + extends StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceImplBase { + private static final int MAX_TUPLE_BYTES = 8 * 1024; + private static final int MAX_CONTROL_UI_JWT_BYTES = 16 * 1024; + private static final int MAX_AUTHORIZATION_REFERENCE_BYTES = 128; + private static final int MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES = 128 * 1024; + private static final int MAX_FINGERPRINT_BYTES = 137; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String AUTHORIZATION_REFERENCE = "[A-Za-z0-9_-]{43}"; + private static final String AUTHORIZATION_REFERENCE_FINGERPRINT = + "arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"; + private static final String MUTATION_DIGEST = "[0-9a-f]{64}"; + + private final AccountStartSessionOperatorAuthorizationService authorizationService; + private final String workloadNamespace; + + public StartSessionOperatorAuthorizationGrpcService( + AccountStartSessionOperatorAuthorizationService authorizationService, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.authorizationService = Objects.requireNonNull(authorizationService); + this.workloadNamespace = workloadNamespace; + } + + @Override + public void issueHumanOperatorAuthorizationReference( + IssueHumanOperatorAuthorizationReferenceRequest request, + StreamObserver responseObserver) { + if (!isAllowedPeer("logging-admin-service")) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Logging/Admin workload identity is required"); + return; + } + + final IssueRequest parsed; + try { + parsed = parseIssueRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical StartSession issue input is required"); + return; + } + + invoke( + responseObserver, + () -> { + AuthorizationResponse authorization = authorizationService.issue(parsed); + return toIssueResponse(authorization, verifiedLoggingPeerUri()); + }); + } + + @Override + public void recoverOperatorAuthorizationReference( + RecoverOperatorAuthorizationReferenceRequest request, + StreamObserver responseObserver) { + if (!isAllowedPeer("logging-admin-service")) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Logging/Admin workload identity is required"); + return; + } + + final RecoverRequest parsed; + try { + parsed = parseRecoverRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical StartSession recovery input is required"); + return; + } + + invoke( + responseObserver, + () -> { + AuthorizationResponse authorization = authorizationService.recover(parsed); + return toRecoverResponse(authorization, verifiedLoggingPeerUri()); + }); + } + + @Override + public void redeemOperatorAuthorization( + RedeemOperatorAuthorizationRequest request, + StreamObserver responseObserver) { + if (!isAllowedPeer("game-session-service")) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Game Session workload identity is required"); + return; + } + + final RedeemRequest parsed; + try { + parsed = parseRedeemRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical StartSession redemption input is required"); + return; + } + + invoke(responseObserver, () -> toRedeemResponse(authorizationService.redeem(parsed))); + } + + @Override + public void readRedeemedOperationProjection( + ReadRedeemedOperationProjectionRequest request, + StreamObserver responseObserver) { + if (!isAllowedPeer("game-design-service") && !isAllowedPeer("game-session-service")) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Game Design or Game Session workload identity is required"); + return; + } + + final AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest + parsed; + try { + parsed = parseReadRedeemedOperationProjectionRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical StartSession operation projection input is required"); + return; + } + + invoke( + responseObserver, + () -> + toReadRedeemedOperationProjectionResponse( + authorizationService.readRedeemedOperationProjection(parsed), parsed)); + } + + private IssueRequest parseIssueRequest(IssueHumanOperatorAuthorizationReferenceRequest request) { + rejectUnknownFields(request.getUnknownFields().asMap().isEmpty()); + byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes()); + decodeCanonicalTuple(tupleBytes); + String token = requireControlUiJwt(request.getControlUiJwt()); + UUID reservationOwnerId = + canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId"); + long reservationFence = + positiveFence(request.getReservationClaimFence(), "reservationClaimFence"); + UUID claimOwnerId = + canonicalNonNilUuid(request.getCurrentClaimOwnerId(), "currentClaimOwnerId"); + long claimFence = positiveFence(request.getCurrentClaimFence(), "currentClaimFence"); + return new IssueRequest( + token, tupleBytes, reservationOwnerId, reservationFence, claimOwnerId, claimFence); + } + + private RecoverRequest parseRecoverRequest(RecoverOperatorAuthorizationReferenceRequest request) { + rejectUnknownFields(request.getUnknownFields().asMap().isEmpty()); + byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes()); + decodeCanonicalTuple(tupleBytes); + UUID reservationOwnerId = + canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId"); + long reservationFence = + positiveFence(request.getReservationClaimFence(), "reservationClaimFence"); + UUID claimOwnerId = + canonicalNonNilUuid(request.getCurrentClaimOwnerId(), "currentClaimOwnerId"); + long claimFence = positiveFence(request.getCurrentClaimFence(), "currentClaimFence"); + return new RecoverRequest( + tupleBytes, reservationOwnerId, reservationFence, claimOwnerId, claimFence); + } + + private RedeemRequest parseRedeemRequest(RedeemOperatorAuthorizationRequest request) { + rejectUnknownFields(request.getUnknownFields().asMap().isEmpty()); + byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes()); + decodeCanonicalTuple(tupleBytes); + String authorizationReference = + requireAuthorizationReference(request.getOperatorAuthorizationReference()); + String fingerprint = requireFingerprint(request.getAuthorizationReferenceFingerprint()); + UUID reservationOwnerId = + canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId"); + long reservationFence = + positiveFence(request.getReservationClaimFence(), "reservationClaimFence"); + UUID ownerAttemptId = canonicalNonNilUuid(request.getOwnerAttemptId(), "ownerAttemptId"); + long ownerFence = positiveFence(request.getOwnerFence(), "ownerFence"); + return new RedeemRequest( + tupleBytes, + authorizationReference, + fingerprint, + reservationOwnerId, + reservationFence, + ownerAttemptId, + ownerFence); + } + + private AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest + parseReadRedeemedOperationProjectionRequest(ReadRedeemedOperationProjectionRequest request) { + rejectUnknownFields(request.getUnknownFields().asMap().isEmpty()); + byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes()); + decodeCanonicalTuple(tupleBytes); + String fingerprint = requireFingerprint(request.getAuthorizationReferenceFingerprint()); + UUID reservationOwnerId = + canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId"); + long reservationFence = + positiveFence(request.getReservationClaimFence(), "reservationClaimFence"); + UUID ownerAttemptId = canonicalNonNilUuid(request.getOwnerAttemptId(), "ownerAttemptId"); + long ownerFence = positiveFence(request.getOwnerFence(), "ownerFence"); + return new AccountStartSessionOperatorAuthorizationService + .ReadRedeemedOperationProjectionRequest( + tupleBytes, fingerprint, reservationOwnerId, reservationFence, ownerAttemptId, ownerFence); + } + + private boolean isAllowedPeer(String serviceAccount) { + if (SessionContext.hasAuthenticatedCallerContext() + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return false; + } + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && workloadNamespace.equals(peer.namespace()) + && peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/" + serviceAccount); + } + + /** Returns only the exact peer identity authenticated on this successful RPC's TLS context. */ + private String verifiedLoggingPeerUri() { + if (SessionContext.hasAuthenticatedCallerContext() + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalStateException("verified Logging/Admin peer is unavailable"); + } + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !workloadNamespace.equals(peer.namespace()) + || !"logging-admin-service".equals(peer.service()) + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/logging-admin-service")) { + throw new IllegalStateException("verified Logging/Admin peer is unavailable"); + } + return peer.uri(); + } + + private static byte[] boundedTuple(ByteString tuple) { + if (tuple.isEmpty() || tuple.size() > MAX_TUPLE_BYTES) { + throw new IllegalArgumentException("bounded canonical tuple bytes are required"); + } + return tuple.toByteArray(); + } + + private static StartSessionPreAuthorizationReservationTuple decodeCanonicalTuple( + byte[] exactBytes) { + final String json; + try { + json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(exactBytes)) + .toString(); + } catch (CharacterCodingException malformedUtf8) { + throw new IllegalArgumentException("tuple is not strict UTF-8", malformedUtf8); + } + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(json); + if (!Arrays.equals(exactBytes, tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("tuple bytes are not the exact canonical encoding"); + } + return tuple; + } + + private static String requireControlUiJwt(String value) { + if (value == null + || value.isBlank() + || value.length() > MAX_CONTROL_UI_JWT_BYTES + || value.chars().anyMatch(character -> character < 0x21 || character > 0x7e)) { + throw new IllegalArgumentException("bounded compact control-ui JWT is required"); + } + return value; + } + + private static UUID canonicalNonNilUuid(String value, String fieldName) { + if (value == null || value.length() > 36) { + throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID"); + } + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID", malformed); + } + } + + private static long positiveFence(long value, String fieldName) { + // A protobuf uint64 above Long.MAX_VALUE is exposed as a negative Java long and is rejected. + if (value <= 0L) { + throw new IllegalArgumentException(fieldName + " must be a positive supported uint64"); + } + return value; + } + + private static String requireAuthorizationReference(String value) { + if (value == null + || value.getBytes(StandardCharsets.UTF_8).length > MAX_AUTHORIZATION_REFERENCE_BYTES + || !value.matches(AUTHORIZATION_REFERENCE)) { + throw new IllegalArgumentException("canonical authorization reference is required"); + } + return value; + } + + private static String requireFingerprint(String value) { + if (value == null + || value.getBytes(StandardCharsets.UTF_8).length > MAX_FINGERPRINT_BYTES + || !value.matches(AUTHORIZATION_REFERENCE_FINGERPRINT)) { + throw new IllegalArgumentException("canonical authorization fingerprint is required"); + } + return value; + } + + private static void rejectUnknownFields(boolean requestHasNoUnknownFields) { + if (!requestHasNoUnknownFields) { + throw new IllegalArgumentException("unknown request fields are not supported"); + } + } + + private static IssueHumanOperatorAuthorizationReferenceResponse toIssueResponse( + AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) { + requireResponse(response); + return IssueHumanOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(response.operatorAuthorizationReference()) + .setAuthorizationReferenceFingerprint(response.authorizationReferenceFingerprint()) + .setExpiresAt(timestamp(response.expiresAt())) + .setAuthorityEvidenceBundle(ByteString.copyFrom(response.authorityEvidenceBundle())) + .setBundleReference(toWireBundleReference(response.bundleReference())) + .setAuthenticatedLoggingWorkloadIdentity(authenticatedLoggingWorkloadIdentity) + .build(); + } + + private static RecoverOperatorAuthorizationReferenceResponse toRecoverResponse( + AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) { + requireResponse(response); + return RecoverOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(response.operatorAuthorizationReference()) + .setAuthorizationReferenceFingerprint(response.authorizationReferenceFingerprint()) + .setExpiresAt(timestamp(response.expiresAt())) + .setAuthorityEvidenceBundle(ByteString.copyFrom(response.authorityEvidenceBundle())) + .setBundleReference(toWireBundleReference(response.bundleReference())) + .setAuthenticatedLoggingWorkloadIdentity(authenticatedLoggingWorkloadIdentity) + .build(); + } + + private static void requireResponse(AuthorizationResponse response) { + if (response == null + || response.operatorAuthorizationReference() == null + || response.operatorAuthorizationReference().getBytes(StandardCharsets.UTF_8).length + > MAX_AUTHORIZATION_REFERENCE_BYTES + || !response.operatorAuthorizationReference().matches(AUTHORIZATION_REFERENCE) + || response.authorizationReferenceFingerprint() == null + || response.authorizationReferenceFingerprint().getBytes(StandardCharsets.UTF_8).length + > MAX_FINGERPRINT_BYTES + || !response + .authorizationReferenceFingerprint() + .matches(AUTHORIZATION_REFERENCE_FINGERPRINT) + || response.expiresAt() == null + || !response.expiresAt().isAfter(Instant.EPOCH) + || response.authorityEvidenceBundle() == null + || response.authorityEvidenceBundle().length == 0 + || response.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES + || response.bundleReference() == null) { + throw new IllegalStateException( + "Account produced an invalid StartSession authorization result"); + } + } + + private static AuthorityEvidenceBundleReference toWireBundleReference(BundleReference reference) { + if (reference == null) { + throw new IllegalStateException("Account bundle reference is missing"); + } + return AuthorityEvidenceBundleReference.newBuilder() + .setBundleVersion(reference.bundleVersion()) + .setSourceVersion(reference.sourceVersion()) + .setSourceFence(reference.sourceFence()) + .setLinearization(reference.linearization()) + .build(); + } + + private static RedeemOperatorAuthorizationResponse toRedeemResponse(RedemptionResult result) { + if (result == null + || result.authorizationReferenceFingerprint() == null + || result.authorizationReferenceFingerprint().getBytes(StandardCharsets.UTF_8).length + > MAX_FINGERPRINT_BYTES + || !result.authorizationReferenceFingerprint().matches(AUTHORIZATION_REFERENCE_FINGERPRINT) + || result.authorityEvidenceBundle() == null + || result.authorityEvidenceBundle().length == 0 + || result.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES + || result.issuanceOperationId() == null + || NIL_UUID.equals(result.issuanceOperationId()) + || result.issuanceFence() <= 0L) { + throw new IllegalStateException("Account produced an invalid StartSession redemption result"); + } + return RedeemOperatorAuthorizationResponse.newBuilder() + .setAuthorizationReferenceFingerprint(result.authorizationReferenceFingerprint()) + .setAuthorityEvidenceBundle(ByteString.copyFrom(result.authorityEvidenceBundle())) + .setIssuanceOperationId(result.issuanceOperationId().toString()) + .setIssuanceFence(result.issuanceFence()) + .setReplay(result.replay()) + .build(); + } + + private ReadRedeemedOperationProjectionResponse toReadRedeemedOperationProjectionResponse( + RedeemedOperationProjection projection, + AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest + request) { + if (projection == null) { + throw new IllegalStateException("Account produced an invalid redeemed operation projection"); + } + byte[] requestTupleBytes = request.canonicalPreAuthorizationTuple(); + byte[] projectionTupleBytes = projection.canonicalPreAuthorizationTuple(); + StartSessionPreAuthorizationReservationTuple tuple = decodeCanonicalTuple(requestTupleBytes); + String expectedRedeemerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + if (!StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + projection.controlPlaneRequestId()) + .equals(tuple.controlPlaneRequestId()) + || !Arrays.equals(projectionTupleBytes, requestTupleBytes) + || projection.mutationDigest() == null + || !projection.mutationDigest().matches(MUTATION_DIGEST) + || !tuple.mutationDigest().equals(projection.mutationDigest()) + || !request + .authorizationReferenceFingerprint() + .equals(projection.authorizationReferenceFingerprint()) + || !request.reservationOwnerId().equals(projection.reservationOwnerId()) + || request.reservationClaimFence() != projection.reservationClaimFence() + || !request.ownerAttemptId().equals(projection.ownerAttemptId()) + || request.ownerFence() != projection.ownerFence() + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !expectedRedeemerUri.equals(projection.redeemerWorkloadUri()) + || projection.referenceExpiresAt() == null + || projection.redeemedAt() == null + || !projection.referenceExpiresAt().isAfter(projection.redeemedAt()) + || projection.issuanceOperationId() == null + || NIL_UUID.equals(projection.issuanceOperationId()) + || projection.issuanceFence() <= 0L + || projection.bundleReference() == null + || projection.authorityEvidenceBundle() == null + || projection.authorityEvidenceBundle().length == 0 + || projection.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES) { + throw new IllegalStateException("Account produced an invalid redeemed operation projection"); + } + return ReadRedeemedOperationProjectionResponse.newBuilder() + .setControlPlaneRequestId(projection.controlPlaneRequestId()) + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(projectionTupleBytes)) + .setMutationDigest(projection.mutationDigest()) + .setAuthorizationReferenceFingerprint(projection.authorizationReferenceFingerprint()) + .setReservationOwnerId(projection.reservationOwnerId().toString()) + .setReservationClaimFence(projection.reservationClaimFence()) + .setAuthenticatedRedeemerWorkloadIdentity(projection.redeemerWorkloadUri()) + .setOwnerAttemptId(projection.ownerAttemptId().toString()) + .setOwnerFence(projection.ownerFence()) + .setReferenceExpiresAt(timestamp(projection.referenceExpiresAt())) + .setRedeemedAt(timestamp(projection.redeemedAt())) + .setIssuanceOperationId(projection.issuanceOperationId().toString()) + .setIssuanceFence(projection.issuanceFence()) + .setBundleReference(toWireBundleReference(projection.bundleReference())) + .setAuthorityEvidenceBundle(ByteString.copyFrom(projection.authorityEvidenceBundle())) + .build(); + } + + private static Timestamp timestamp(Instant instant) { + return Timestamp.newBuilder() + .setSeconds(instant.getEpochSecond()) + .setNanos(instant.getNano()) + .build(); + } + + private static void invoke(StreamObserver observer, Supplier operation) { + try { + observer.onNext(operation.get()); + observer.onCompleted(); + } catch (AccountStartSessionOperatorAuthorizationService.NotFoundException missing) { + fail(observer, Status.NOT_FOUND, "No original StartSession authorization exists"); + } catch (CannotCreateTransactionException unavailable) { + fail( + observer, + Status.UNAVAILABLE, + "Account operator authorization is temporarily unavailable"); + } catch (DataAccessException failure) { + Status status = hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL; + fail( + observer, + status, + status.getCode() == Status.Code.UNAVAILABLE + ? "Account operator authorization is temporarily unavailable" + : "Account operator authorization could not be completed"); + } catch (StatusRuntimeException upstream) { + Status mapped = mapUpstreamStatus(Status.fromThrowable(upstream).getCode()); + fail(observer, mapped, descriptionFor(mapped)); + } catch (IllegalArgumentException malformed) { + fail(observer, Status.INVALID_ARGUMENT, "StartSession authorization input is invalid"); + } catch (IllegalStateException rejected) { + fail( + observer, + Status.FAILED_PRECONDITION, + "Current Account authorization evidence is unavailable"); + } catch (RuntimeException failure) { + fail(observer, Status.INTERNAL, "Account operator authorization could not be completed"); + } + } + + 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; + } + + private static Status mapUpstreamStatus(Status.Code code) { + return switch (code) { + case INVALID_ARGUMENT -> Status.INVALID_ARGUMENT; + case NOT_FOUND -> Status.NOT_FOUND; + case PERMISSION_DENIED -> Status.PERMISSION_DENIED; + case FAILED_PRECONDITION, ABORTED -> Status.FAILED_PRECONDITION; + case UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED -> Status.UNAVAILABLE; + default -> Status.INTERNAL; + }; + } + + private static String descriptionFor(Status status) { + return switch (status.getCode()) { + case INVALID_ARGUMENT -> "StartSession authorization input is invalid"; + case NOT_FOUND -> "No original StartSession authorization exists"; + case PERMISSION_DENIED -> "Account rejected the authenticated StartSession caller"; + case FAILED_PRECONDITION -> "Current Account authorization evidence is unavailable"; + case UNAVAILABLE -> "Account operator authorization is temporarily unavailable"; + default -> "Account operator authorization could not be completed"; + }; + } + + private static void fail(StreamObserver observer, Status status, String description) { + observer.onError(status.withDescription(description).asRuntimeException()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyring.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyring.java new file mode 100644 index 0000000000..1772d03532 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyring.java @@ -0,0 +1,221 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationReferenceFingerprint.ReferenceKind; + +/** + * Explicit Account-owned active/retained key snapshot for operator-reference fingerprints. + * + *

This class has no key source implementation, default key, or provisioning behavior. The caller + * supplies an owner-controlled source and an explicit post-expiry reconciliation window; every + * fingerprint operation reloads that source and fails closed for a missing, withdrawn, or + * insufficiently retained key. + */ +public final class AccountOperatorAuthorizationFingerprintKeyring { + private static final int MAX_RETAINED_KEYS = 8; + private static final Pattern FINGERPRINT = + Pattern.compile("arfp/v1/([A-Za-z0-9_-]{1,64})/([0-9a-f]{64})"); + private static final String HMAC_ALGORITHM = "HmacSHA256"; + + private final OwnerKeySource source; + private final Clock clock; + private final Duration requiredPostExpiryRetention; + + public AccountOperatorAuthorizationFingerprintKeyring( + OwnerKeySource source, Clock clock, Duration requiredPostExpiryRetention) { + this.source = Objects.requireNonNull(source, "explicit Account operator key source required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + this.requiredPostExpiryRetention = + Objects.requireNonNull(requiredPostExpiryRetention, "retention policy is required"); + if (requiredPostExpiryRetention.isNegative() || requiredPostExpiryRetention.isZero()) { + throw new IllegalArgumentException("Explicit positive reconciliation retention is required"); + } + } + + /** Computes a new issuance fingerprint only with the currently declared active key. */ + public String fingerprintForIssue(ReferenceKind referenceKind, byte[] exactReferenceBytes) { + Objects.requireNonNull(referenceKind, "reference kind is required"); + Snapshot current = requireSnapshot(); + return current.activeKey().calculator().fingerprint(referenceKind, exactReferenceBytes); + } + + /** + * Recomputes the original fingerprint using its exact stored key ID and verifies the supplied + * value in constant time. Retired keys must remain available past both immutable expiries and the + * explicitly configured reconciliation window. + */ + public boolean matchesOriginal( + ReferenceKind referenceKind, + byte[] exactReferenceBytes, + String originalFingerprint, + Instant referenceExpiresAt, + Instant responseEnvelopeExpiresAt) { + Objects.requireNonNull(referenceKind, "reference kind is required"); + Objects.requireNonNull(referenceExpiresAt, "reference expiry is required"); + Objects.requireNonNull(responseEnvelopeExpiresAt, "response expiry is required"); + if (!responseEnvelopeExpiresAt.isAfter(referenceExpiresAt)) { + throw new IllegalArgumentException("Original response expiry must follow reference expiry"); + } + Matcher matcher = originalFingerprint == null ? null : FINGERPRINT.matcher(originalFingerprint); + if (matcher == null || !matcher.matches()) { + throw new IllegalArgumentException("Original Account reference fingerprint is malformed"); + } + + Snapshot current = requireSnapshot(); + String keyId = matcher.group(1); + KeyMaterial key = current.keyFor(keyId); + if (key == null) { + throw new KeyUnavailableException(); + } + if (key != current.activeKey()) { + Instant now = clock.instant(); + if (!now.isBefore(key.retainedUntil())) { + throw new KeyUnavailableException(); + } + Instant requiredUntil; + try { + requiredUntil = responseEnvelopeExpiresAt.plus(requiredPostExpiryRetention); + } catch (RuntimeException invalidHorizon) { + throw new KeyUnavailableException(); + } + if (!key.retainedUntil().isAfter(requiredUntil)) { + throw new KeyUnavailableException(); + } + } + String actual = key.calculator().fingerprint(referenceKind, exactReferenceBytes); + return MessageDigest.isEqual( + actual.getBytes(StandardCharsets.US_ASCII), + originalFingerprint.getBytes(StandardCharsets.US_ASCII)); + } + + private Snapshot requireSnapshot() { + try { + return Objects.requireNonNull(source.readCurrent(), "owner key snapshot is required"); + } catch (KeyUnavailableException unavailable) { + throw unavailable; + } catch (RuntimeException unavailable) { + throw new KeyUnavailableException(); + } + } + + @FunctionalInterface + public interface OwnerKeySource { + /** Reads the owner-controlled active and retained key snapshot afresh for this operation. */ + Snapshot readCurrent(); + } + + /** One active key and at most eight explicitly retained prior keys. */ + public record Snapshot(KeyMaterial activeKey, List retainedKeys) { + public Snapshot { + Objects.requireNonNull(activeKey, "one active Account operator key is required"); + if (activeKey.retainedUntil() != null) { + throw new IllegalArgumentException("Active Account operator key cannot be marked retained"); + } + retainedKeys = + List.copyOf(Objects.requireNonNull(retainedKeys, "retained keys are required")); + if (retainedKeys.size() > MAX_RETAINED_KEYS) { + throw new IllegalArgumentException("Retained Account operator keys exceed their bound"); + } + Set keyIds = new HashSet<>(); + if (!keyIds.add(activeKey.keyId())) { + throw new IllegalArgumentException("Active Account operator key ID is duplicated"); + } + for (KeyMaterial retained : retainedKeys) { + Objects.requireNonNull(retained, "retained Account operator key is required"); + if (retained.retainedUntil() == null || !keyIds.add(retained.keyId())) { + throw new IllegalArgumentException("Retained Account operator key is malformed"); + } + } + } + + private KeyMaterial keyFor(String keyId) { + if (activeKey.keyId().equals(keyId)) { + return activeKey; + } + return retainedKeys.stream() + .filter(value -> value.keyId().equals(keyId)) + .findFirst() + .orElse(null); + } + + @Override + public String toString() { + return "AccountOperatorAuthorizationFingerprintKeyring.Snapshot[key material redacted]"; + } + } + + /** Secret material remains private; only its bounded identifier is exposed. */ + public static final class KeyMaterial { + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + + private final String keyId; + private final AccountOperatorAuthorizationReferenceFingerprint calculator; + private final Instant retainedUntil; + + public KeyMaterial(String keyId, SecretKey secretKey) { + this(keyId, secretKey, null); + } + + public KeyMaterial(String keyId, SecretKey secretKey, Instant retainedUntil) { + if (keyId == null || !KEY_ID.matcher(keyId).matches()) { + throw new IllegalArgumentException("Unsupported Account operator key ID"); + } + Objects.requireNonNull(secretKey, "explicit Account operator key material is required"); + if (!HMAC_ALGORITHM.equalsIgnoreCase(secretKey.getAlgorithm())) { + throw new IllegalArgumentException("Unsupported Account operator key algorithm"); + } + byte[] encoded = secretKey.getEncoded(); + if (encoded == null || encoded.length == 0 || encoded.length > 4096) { + throw new IllegalArgumentException("Unsupported Account operator key material"); + } + byte[] copy = encoded.clone(); + try { + SecretKey immutableCopy = new SecretKeySpec(copy, HMAC_ALGORITHM); + calculator = new AccountOperatorAuthorizationReferenceFingerprint(keyId, immutableCopy); + } finally { + java.util.Arrays.fill(copy, (byte) 0); + } + if (retainedUntil != null && retainedUntil.toEpochMilli() <= 0L) { + throw new IllegalArgumentException("Retained Account operator key expiry is invalid"); + } + this.keyId = keyId; + this.retainedUntil = retainedUntil; + } + + public String keyId() { + return keyId; + } + + private AccountOperatorAuthorizationReferenceFingerprint calculator() { + return calculator; + } + + private Instant retainedUntil() { + return retainedUntil; + } + + @Override + public String toString() { + return "AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial[key material redacted]"; + } + } + + /** Fail-closed result for an absent, withdrawn, expired, or insufficiently retained key. */ + public static final class KeyUnavailableException extends RuntimeException { + public KeyUnavailableException() { + super("Account operator authorization fingerprint key is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprint.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprint.java new file mode 100644 index 0000000000..588b7bc6b2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprint.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.regex.Pattern; +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +/** Account-owned HMAC identity for the exact bytes of an operator authorization reference. */ +public final class AccountOperatorAuthorizationReferenceFingerprint { + private static final String HMAC_ALGORITHM = "HmacSHA256"; + private static final String DOMAIN = "FireMUD/authorizationReferenceFingerprint/v1"; + private static final String OUTPUT_PREFIX = "arfp/v1/"; + private static final int MAX_KEY_ID_BYTES = 64; + private static final int MAX_KEY_BYTES = 4096; + private static final int MAX_REFERENCE_BYTES = 4096; + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + + private final String keyId; + private final SecretKey key; + + /** + * Creates a calculator with an explicitly supplied HMAC key and its bounded public identifier. + * + *

No key is generated, discovered, or loaded implicitly by this class. + */ + public AccountOperatorAuthorizationReferenceFingerprint(String keyId, SecretKey key) { + if (keyId == null || keyId.length() > MAX_KEY_ID_BYTES || !KEY_ID.matcher(keyId).matches()) { + throw new IllegalArgumentException("Unsupported authorization-reference fingerprint key ID"); + } + if (key == null || !HMAC_ALGORITHM.equalsIgnoreCase(key.getAlgorithm())) { + throw new IllegalArgumentException("Unsupported authorization-reference fingerprint key"); + } + + byte[] encoded = key.getEncoded(); + if (encoded == null || encoded.length == 0 || encoded.length > MAX_KEY_BYTES) { + throw new IllegalArgumentException("Unsupported authorization-reference fingerprint key"); + } + + byte[] keyCopy = encoded.clone(); + try { + this.key = new SecretKeySpec(keyCopy, HMAC_ALGORITHM); + } finally { + Arrays.fill(keyCopy, (byte) 0); + } + this.keyId = keyId; + } + + /** Returns the canonical fingerprint for the supplied exact opaque reference bytes. */ + public String fingerprint(ReferenceKind referenceKind, byte[] referenceBytes) { + if (referenceKind == null) { + throw new IllegalArgumentException("Unsupported operator authorization-reference kind"); + } + if (referenceBytes == null + || referenceBytes.length == 0 + || referenceBytes.length > MAX_REFERENCE_BYTES) { + throw new IllegalArgumentException("Invalid operator authorization-reference bytes"); + } + + byte[] referenceCopy = referenceBytes.clone(); + try { + Mac mac = Mac.getInstance(HMAC_ALGORITHM); + mac.init(key); + updateSegment(mac, DOMAIN.getBytes(StandardCharsets.UTF_8)); + updateSegment(mac, keyId.getBytes(StandardCharsets.UTF_8)); + updateSegment(mac, referenceKind.wireValue.getBytes(StandardCharsets.UTF_8)); + updateSegment(mac, referenceCopy); + return OUTPUT_PREFIX + keyId + "/" + HexFormat.of().formatHex(mac.doFinal()); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("HMAC-SHA-256 is unavailable", exception); + } finally { + Arrays.fill(referenceCopy, (byte) 0); + } + } + + private static void updateSegment(Mac mac, byte[] value) { + byte[] prefix = (Integer.toString(value.length) + ":").getBytes(StandardCharsets.US_ASCII); + mac.update(prefix); + mac.update(value); + } + + @Override + public String toString() { + return "AccountOperatorAuthorizationReferenceFingerprint"; + } + + /** The only reference kinds accepted by ADR 0047. */ + public enum ReferenceKind { + HUMAN_OPERATOR("human_operator"), + AUTOMATION_OPERATOR("automation_operator"); + + private final String wireValue; + + ReferenceKind(String wireValue) { + this.wireValue = Objects.requireNonNull(wireValue); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java index e1611254f4..57d0ded2f8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java @@ -88,6 +88,25 @@ public AccountStartSessionAuthorityCapture prepareOrReadExact( return stored; } + /** Locks and reads an existing exact capture without allocating or inserting one. */ + public AccountStartSessionAuthorityCapture lockReadExactCurrent( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence) { + requireOwnerTransaction(); + Objects.requireNonNull(current, "current committed ControlUI actor is required"); + RequestSnapshot observed = + requestSnapshot( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence); + Record row = lockByRequestId(observed.requestId()); + if (row == null) throw unavailable(); + AccountStartSessionAuthorityCapture stored = decode(row); + requireSameRequestAndSnapshot(observed, stored, row); + return stored; + } + /** Locks the immutable original capture and requires the exact current source and tuple again. */ public AccountStartSessionAuthorityCapture lockExactCurrent( AccountStartSessionAuthorityCapture expected, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java new file mode 100644 index 0000000000..18e4729b0c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java @@ -0,0 +1,685 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.Snapshot; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.Stored; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Exact ADR 0047 Account authority evidence for the tenantAdmin StartSession branch. */ +public final class AccountStartSessionOperatorAuthorityBundle { + public static final String BUNDLE_VERSION = StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION; + public static final String HUMAN_EVIDENCE_TYPE = + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE; + private static final Pattern DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set CAPTURE_SNAPSHOT_FIELDS = + Set.of( + "schema", + "controlPlaneRequestId", + "preAuthorizationTuple", + "mutationDigest", + "accountId", + "tenantId", + "targetOwner", + "loggingWorkloadUri", + "reservationOwnerId", + "reservationClaimFence", + "controlUiOperationId", + "controlUiTokenJti", + "controlUiTokenHash", + "controlUiSignerReceipt", + "controlUiSignerReceiptSha256", + "sourceVectorEvidence", + "sourceVector", + "outboxCheckpoints", + "authorityTuple", + "membershipVersion", + "accountIdentitySource", + "issuanceFence", + "issuanceFenceSourceVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final StartSessionAuthorityEvidenceBundle decoded; + private final byte[] canonicalBytes; + private final Map value; + + private AccountStartSessionOperatorAuthorityBundle(StartSessionAuthorityEvidenceBundle decoded) { + this.decoded = Objects.requireNonNull(decoded, "shared authority bundle is required"); + this.canonicalBytes = decoded.canonicalBytes(); + this.value = decoded.jsonValue(); + } + + /** + * Builds the one supported human branch only from Account's already committed immutable capture + * and the original control-ui token row proven by {@link AccountControlUiActorService}. + */ + public static AccountStartSessionOperatorAuthorityBundle create( + StartSessionPreAuthorizationReservationTuple tuple, + AccountStartSessionAuthorityCapture capture, + Stored controlUiIssuance, + UUID issuanceOperationId, + Instant issuedAt, + Instant referenceExpiresAt) { + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + Objects.requireNonNull(capture, "durable Account authority capture is required"); + Objects.requireNonNull(controlUiIssuance, "original control-ui issuance is required"); + Objects.requireNonNull(issuanceOperationId, "issuance operation identity is required"); + requireTimeWindow(issuedAt, referenceExpiresAt); + + Map snapshot = captureSnapshot(capture); + UUID actor = canonicalUuid(snapshot.get("accountId"), "captured accountId"); + UUID tenant = canonicalUuid(snapshot.get("tenantId"), "captured tenantId"); + UUID controlUiJti = canonicalUuid(snapshot.get("controlUiTokenJti"), "captured token jti"); + Map authorityTuple = object(snapshot.get("authorityTuple"), "authorityTuple"); + Map membershipVersion = + object(snapshot.get("membershipVersion"), "membershipVersion"); + Map claims = + AccountControlUiIssuanceRepository.object(controlUiIssuance.claims); + requireCapturedTenantClaims( + tuple, actor, tenant, authorityTuple, membershipVersion, controlUiIssuance, claims); + if (!tuple.controlPlaneRequestId().equals(snapshot.get("controlPlaneRequestId")) + || !tuple.targetOwner().equals(snapshot.get("targetOwner")) + || !tuple.mutationDigest().equals(snapshot.get("mutationDigest")) + || !Base64.getEncoder() + .encodeToString(tuple.canonicalJson().getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .equals(snapshot.get("preAuthorizationTuple")) + || !controlUiIssuance.operationId.toString().equals(snapshot.get("controlUiOperationId")) + || !controlUiIssuance.tokenHash.equals(snapshot.get("controlUiTokenHash")) + || !controlUiIssuance.jti.equals(controlUiJti)) { + throw denied("Retained Account capture differs from the original request or credential"); + } + + BundleReference reference = referenceForCaptureValue(capture); + Map typedScope = + Map.of( + "tenantId", tuple.action().scope().tenantId().toString(), + "targetNamespace", tuple.action().scope().targetNamespace()); + Map authorityScope = + Map.of( + "scope", typedScope, + "actionFamily", tuple.actionFamily(), + "applicableAccountId", actor.toString(), + "applicableTenantId", tenant.toString()); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", + sourceEvidenceId( + Base64.getDecoder() + .decode( + string(snapshot.get("sourceVectorEvidence"), "sourceVectorEvidence")), + reference, + positiveNumber(snapshot.get("issuanceFence"), "captured issuanceFence"), + positiveNumber( + snapshot.get("issuanceFenceSourceVersion"), + "captured issuanceFenceSourceVersion")), + "sourceEvidenceVersion", reference.sourceVersion(), + "projectionStatus", "CURRENT", + "evaluatedAt", canonicalCaptureTimestamp(capture), + "expiresAt", referenceExpiresAt.toString()); + Map operationIdentity = + Map.of( + "issuanceOperationId", issuanceOperationId.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map humanEvidence = + humanTenantEvidence(actor, tenant, authorityTuple, controlUiJti, claims); + + Map bundle = new LinkedHashMap<>(); + bundle.put("bundleVersion", BUNDLE_VERSION); + bundle.put("authorityScope", authorityScope); + bundle.put("accountProjectionEvidence", projection); + bundle.put("issuanceOperationIdentity", operationIdentity); + bundle.put("issuanceKind", "human_operator"); + bundle.put("authorityTuple", authorityTuple); + bundle.put("membershipVersion", membershipVersion); + bundle.put( + "issuanceFence", + positiveDecimalString(snapshot.get("issuanceFence"), "captured issuanceFence")); + bundle.put("issuanceEvidence", humanEvidence); + AccountStartSessionOperatorAuthorityBundle result = + decode(AccountControlUiAuthority.canonical(bundle)); + result.requireTupleBinding(tuple); + result.requireCaptureBinding(capture, tuple, reference); + return result; + } + + /** Strictly decodes one closed canonical authorityEvidenceBundle/v1 value. */ + public static AccountStartSessionOperatorAuthorityBundle decode(byte[] exactCanonicalBytes) { + return new AccountStartSessionOperatorAuthorityBundle( + StartSessionAuthorityEvidenceBundle.decode(exactCanonicalBytes)); + } + + /** Compares every snapshot-bound authority projection and the exact original source reference. */ + public void requireCurrent( + Snapshot currentSource, + Stored currentControlUiIssuance, + StartSessionPreAuthorizationReservationTuple tuple, + BundleReference originalReference, + Instant now) { + Objects.requireNonNull(currentSource, "current Account source is required"); + Objects.requireNonNull(currentControlUiIssuance, "current control-ui issuance is required"); + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + Objects.requireNonNull(originalReference, "original Account source reference is required"); + Objects.requireNonNull(now, "current time is required"); + decoded.requireTupleBinding(tuple); + decoded.requireReferenceBinding(toSharedReference(originalReference)); + Map projection = + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); + if (!now.isBefore(originalReferenceExpiresAt()) + || !now.isBefore(instant(string(projection.get("expiresAt"), "projection expiry")))) { + throw denied("Original Account authority evidence is expired"); + } + if (!tuple.actor().accountId().equals(currentSource.actor()) + || !tuple.action().scope().tenantId().equals(currentSource.tenant()) + || !currentControlUiIssuance.accountId.equals(currentSource.actor()) + || !currentControlUiIssuance.tenantId.equals(currentSource.tenant())) { + throw denied("Current Account actor or tenant changed"); + } + Map claims = + AccountControlUiIssuanceRepository.object(currentControlUiIssuance.claims); + requireCurrentTenantClaims(tuple, currentSource, currentControlUiIssuance, claims); + if (!canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) + || !canonicalEquals(currentSource.membershipVersion(), value.get("membershipVersion"))) { + throw denied("Current Account source, generation, or membership changed"); + } + requireCurrentSourceEvidence(currentSource, originalReference); + Map expectedEvidence = + humanTenantEvidence(currentSource, currentControlUiIssuance.jti, claims); + if (!canonicalEquals(expectedEvidence, value.get("issuanceEvidence"))) { + throw denied("Current human authority evidence changed"); + } + } + + /** Current-state proof for a same-attempt replay after the exact response envelope horizon. */ + public void requireCurrentSnapshotForExactReplay( + Snapshot currentSource, + Stored currentControlUiIssuance, + StartSessionPreAuthorizationReservationTuple tuple, + BundleReference originalReference) { + Objects.requireNonNull(currentSource, "current Account source is required"); + Objects.requireNonNull(currentControlUiIssuance, "current control-ui issuance is required"); + Objects.requireNonNull(originalReference, "original Account source reference is required"); + decoded.requireTupleBinding(tuple); + decoded.requireReferenceBinding(toSharedReference(originalReference)); + if (!tuple.actor().accountId().equals(currentSource.actor()) + || !tuple.action().scope().tenantId().equals(currentSource.tenant()) + || !currentControlUiIssuance.accountId.equals(currentSource.actor()) + || !currentControlUiIssuance.tenantId.equals(currentSource.tenant())) { + throw denied("Current Account actor or tenant changed"); + } + Map claims = + AccountControlUiIssuanceRepository.object(currentControlUiIssuance.claims); + requireCurrentTenantClaims(tuple, currentSource, currentControlUiIssuance, claims); + if (!canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) + || !canonicalEquals(currentSource.membershipVersion(), value.get("membershipVersion")) + || !currentSourceMatchesEvidence(currentSource, originalReference) + || !canonicalEquals( + humanTenantEvidence(currentSource, currentControlUiIssuance.jti, claims), + value.get("issuanceEvidence"))) { + throw denied("Current Account source differs from the consumed authorization"); + } + } + + /** Enforces request tuple equality separately from the authority projection. */ + public void requireTupleBinding(StartSessionPreAuthorizationReservationTuple tuple) { + decoded.requireTupleBinding(tuple); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public BundleReference referenceForCapture(AccountStartSessionAuthorityCapture capture) { + Objects.requireNonNull(capture, "original Account source capture is required"); + BundleReference reference = referenceForCaptureValue(capture); + requireCaptureBinding(capture, null, reference); + return reference; + } + + /** Requires the bundle and immutable source reference to identify the same stored capture. */ + public void requireCaptureBinding( + AccountStartSessionAuthorityCapture capture, + StartSessionPreAuthorizationReservationTuple tuple, + BundleReference expectedReference) { + Objects.requireNonNull(capture, "original Account source capture is required"); + Objects.requireNonNull(expectedReference, "original Account bundle reference is required"); + Map projection = + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); + Map snapshot = captureSnapshot(capture); + String expectedEvidenceId = + sourceEvidenceId( + Base64.getDecoder() + .decode(string(snapshot.get("sourceVectorEvidence"), "sourceVectorEvidence")), + expectedReference, + positiveNumber(snapshot.get("issuanceFence"), "captured issuanceFence"), + positiveNumber( + snapshot.get("issuanceFenceSourceVersion"), "captured issuanceFenceSourceVersion")); + if (!referenceForCaptureValue(capture).equals(expectedReference) + || !expectedEvidenceId.equals(projection.get("sourceEvidenceId")) + || !Long.toString(capture.sourceVersion()).equals(projection.get("sourceEvidenceVersion")) + || !canonicalCaptureTimestamp(capture).equals(projection.get("evaluatedAt")) + || !capture.controlPlaneRequestId().equals(controlPlaneRequestId()) + || (tuple != null && !tuple.controlPlaneRequestId().equals(controlPlaneRequestId())) + || !canonicalEquals(snapshot.get("authorityTuple"), value.get("authorityTuple")) + || !canonicalEquals(snapshot.get("membershipVersion"), value.get("membershipVersion"))) { + throw denied("Authority bundle does not bind the exact retained Account capture"); + } + if (!Long.toString(positiveNumber(snapshot.get("issuanceFence"), "captured issuanceFence")) + .equals(decoded.issuanceFence())) { + throw denied("Account issuance fence differs from the retained source snapshot"); + } + } + + public Map authorityTuple() { + return decoded.authorityTuple(); + } + + public Map membershipVersion() { + return decoded.membershipVersion(); + } + + public UUID issuanceOperationId() { + return decoded.issuanceOperationId(); + } + + public String controlPlaneRequestId() { + return decoded.controlPlaneRequestId(); + } + + public String authorizationExpiresAt() { + return decoded.authorizationExpiresAt(); + } + + public String sourceEvidenceId() { + return decoded.sourceEvidenceId(); + } + + public String sourceEvidenceVersion() { + return decoded.sourceEvidenceVersion(); + } + + public long issuanceFence() { + return positiveNumber(decoded.issuanceFence(), "Account issuance fence"); + } + + public UUID controlUiTokenJti() { + return decoded.controlUiTokenJti(); + } + + public Map jsonValue() { + return decoded.jsonValue(); + } + + private Instant originalReferenceExpiresAt() { + return decoded.expiresAt(); + } + + static StartSessionAuthorityEvidenceBundle.BundleReference toSharedReference( + BundleReference reference) { + Objects.requireNonNull(reference, "original Account source reference is required"); + return new StartSessionAuthorityEvidenceBundle.BundleReference( + reference.bundleVersion(), + reference.sourceVersion(), + reference.sourceFence(), + reference.linearization()); + } + + static BundleReference fromSharedReference( + StartSessionAuthorityEvidenceBundle.BundleReference reference) { + Objects.requireNonNull(reference, "original Account source reference is required"); + return new BundleReference( + reference.bundleVersion(), + reference.sourceVersion(), + reference.sourceFence(), + reference.linearization()); + } + + private static BundleReference referenceForCaptureValue( + AccountStartSessionAuthorityCapture capture) { + return fromSharedReference(capture.bundleReference()); + } + + private static Map captureSnapshot(AccountStartSessionAuthorityCapture capture) { + try { + byte[] bytes = capture.snapshotBytes(); + Map snapshot = + JSON.readValue( + new String(bytes, java.nio.charset.StandardCharsets.UTF_8), new TypeReference<>() {}); + if (!CAPTURE_SNAPSHOT_FIELDS.equals(snapshot.keySet()) + || !"account-start-session-authority-snapshot/v1".equals(snapshot.get("schema")) + || !MessageDigest.isEqual(bytes, AccountControlUiAuthority.canonical(snapshot))) { + throw denied("Retained Account source snapshot is not exact canonical data"); + } + return snapshot; + } catch (RuntimeException malformed) { + throw denied("Retained Account source snapshot is malformed"); + } + } + + private static UUID canonicalUuid(Object value, String field) { + String text = string(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text)) throw new IllegalArgumentException(); + return parsed; + } catch (RuntimeException malformed) { + throw denied(field + " must be a canonical UUID"); + } + } + + private static String positiveDecimalString(Object value, String field) { + return Long.toString(positiveNumber(value, field)); + } + + private static long positive(long value, String field) { + if (value <= 0L) throw denied(field + " must be positive"); + return value; + } + + private static void requireCapturedTenantClaims( + StartSessionPreAuthorizationReservationTuple tuple, + UUID actor, + UUID tenant, + Map authorityTuple, + Map membershipVersion, + Stored stored, + Map claims) { + if (!tuple.actor().accountId().equals(actor) + || !tuple.actor().accountId().equals(stored.accountId) + || !tuple.action().scope().tenantId().equals(tenant) + || !tuple.action().scope().tenantId().equals(stored.tenantId) + || !"COMMITTED".equals(stored.status) + || stored.jti == null + || !stored.jti.toString().equals(claims.get("jti")) + || !actor.toString().equals(claims.get("sub")) + || !actor.toString().equals(claims.get("accountId")) + || !"control-ui".equals(claims.get("aud")) + || positiveNumber(claims.get("tokenGeneration"), "tokenGeneration") != 1L + || claims.containsKey("assurance") + || claims.containsKey("globalRoles") + || !Map.of(tenant.toString(), List.of("tenantAdmin")).equals(claims.get("scopedRoles")) + || !canonicalEquals(authorityTuple, claims.get("authorityTuple")) + || !canonicalEquals(membershipVersion, claims.get("membershipVersion"))) { + throw denied("Captured tenantAdmin control-ui evidence is required"); + } + } + + private static Map humanTenantEvidence( + UUID actor, + UUID tenant, + Map authorityTuple, + UUID tokenJti, + Map claims) { + if (claims.containsKey("assurance") || claims.containsKey("globalRoles")) { + throw denied("Tenant authority must omit assurance and global-role evidence"); + } + long accountGeneration = + positiveNumber( + authorityTuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + Map tenantGenerations = + object(authorityTuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + if (!tenantGenerations.keySet().equals(Set.of(tenant.toString()))) { + throw denied("Exact selected tenant authority generation is required"); + } + long tenantGeneration = + positiveNumber(tenantGenerations.get(tenant.toString()), "tenantAuthorityGeneration"); + Map evidence = new LinkedHashMap<>(); + evidence.put("evidenceType", HUMAN_EVIDENCE_TYPE); + evidence.put("actorAccountId", actor.toString()); + evidence.put("controlUiTokenJti", tokenJti.toString()); + evidence.put("role", "tenantAdmin"); + evidence.put("accountGeneration", Long.toString(accountGeneration)); + evidence.put("tenantGeneration", Long.toString(tenantGeneration)); + return Map.copyOf(evidence); + } + + private static void requireCurrentTenantClaims( + StartSessionPreAuthorizationReservationTuple tuple, + Snapshot source, + Stored stored, + Map claims) { + if (!tuple.actor().accountId().equals(stored.accountId) + || !tuple.actor().accountId().equals(source.actor()) + || !tuple.action().scope().tenantId().equals(stored.tenantId) + || !tuple.action().scope().tenantId().equals(source.tenant()) + || !stored.jti.toString().equals(claims.get("jti")) + || !stored.accountId.toString().equals(claims.get("sub")) + || !stored.accountId.toString().equals(claims.get("accountId")) + || !"control-ui".equals(claims.get("aud")) + || positiveNumber(claims.get("tokenGeneration"), "tokenGeneration") != 1L + || claims.containsKey("assurance") + || claims.containsKey("globalRoles") + || !Map.of(stored.tenantId.toString(), List.of("tenantAdmin")) + .equals(claims.get("scopedRoles")) + || !canonicalEquals(source.authorityTuple(), claims.get("authorityTuple")) + || !canonicalEquals(source.membershipVersion(), claims.get("membershipVersion"))) { + throw denied("Current tenantAdmin control-ui evidence is required"); + } + } + + private static Map humanTenantEvidence( + Snapshot source, UUID tokenJti, Map claims) { + if (claims.containsKey("assurance") || claims.containsKey("globalRoles")) { + throw denied("Tenant authority must omit assurance and global-role evidence"); + } + Map tuple = source.authorityTuple(); + long accountGeneration = + positiveNumber(tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + Map tenantGenerations = + object(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + if (!tenantGenerations.keySet().equals(Set.of(source.tenant().toString()))) { + throw denied("Exact selected tenant authority generation is required"); + } + long tenantGeneration = + positiveNumber( + tenantGenerations.get(source.tenant().toString()), "tenantAuthorityGeneration"); + Map evidence = new LinkedHashMap<>(); + evidence.put("evidenceType", HUMAN_EVIDENCE_TYPE); + evidence.put("actorAccountId", source.actor().toString()); + evidence.put("controlUiTokenJti", tokenJti.toString()); + evidence.put("role", "tenantAdmin"); + evidence.put("accountGeneration", Long.toString(accountGeneration)); + evidence.put("tenantGeneration", Long.toString(tenantGeneration)); + return Map.copyOf(evidence); + } + + private static String sourceEvidenceId( + byte[] sourceEvidence, + BundleReference reference, + long accountIssuanceFence, + long accountIssuanceFenceSourceVersion) { + Map value = + Map.of( + "schema", + "account-start-session-source-capture-evidence/v1", + "sourceType", + "ACCOUNT", + "sourceEvidenceBytesBase64", + Base64.getEncoder().encodeToString(sourceEvidence), + "sourceVersion", + reference.sourceVersion(), + "sourceFence", + reference.sourceFence(), + "linearization", + reference.linearization(), + "accountIssuanceFence", + Long.toString(positive(accountIssuanceFence, "Account issuance fence")), + "accountIssuanceFenceSourceVersion", + Long.toString( + positive( + accountIssuanceFenceSourceVersion, "Account issuance fence source version"))); + try { + byte[] digest = + MessageDigest.getInstance("SHA-256").digest(AccountControlUiAuthority.canonical(value)); + return "sha256:" + java.util.HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private void requireCurrentSourceEvidence(Snapshot source, BundleReference reference) { + if (!currentSourceMatchesEvidence(source, reference)) { + throw denied( + "Current Account source evidence or issuance fence differs from the original capture"); + } + } + + private boolean currentSourceMatchesEvidence(Snapshot source, BundleReference reference) { + Map projection = + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); + if (source.issuanceFence() <= 0L || source.issuanceFenceSourceVersion() <= 0L) return false; + return Long.toString(source.issuanceFence()).equals(decoded.issuanceFence()) + && sourceEvidenceId( + source.evidence(), + reference, + source.issuanceFence(), + source.issuanceFenceSourceVersion()) + .equals(projection.get("sourceEvidenceId")); + } + + private static void requireTimeWindow(Instant issuedAt, Instant expiresAt) { + Objects.requireNonNull(issuedAt, "issue time is required"); + Objects.requireNonNull(expiresAt, "reference expiry is required"); + if (!issuedAt.isAfter(Instant.EPOCH) + || !expiresAt.isAfter(issuedAt) + || issuedAt.getNano() % 1_000_000 != 0 + || expiresAt.getNano() % 1_000_000 != 0) { + throw denied("Operator evidence timestamps must be positive exact milliseconds"); + } + } + + /** + * V128 stores a fixed-width UTC millisecond timestamp, while the shared bundle contract uses the + * canonical {@link Instant#toString()} representation. Preserve the captured instant and + * precision while normalizing only that textual representation (notably, dropping .000). + */ + private static String canonicalCaptureTimestamp(AccountStartSessionAuthorityCapture capture) { + final Instant capturedAt; + try { + capturedAt = Instant.parse(capture.capturedAt()); + } catch (RuntimeException malformed) { + throw denied("Capture timestamp is malformed"); + } + if (capturedAt.getNano() % 1_000_000 != 0) { + throw denied("Capture timestamp must use exact millisecond precision"); + } + return capturedAt.toString(); + } + + private static Instant instant(String value) { + try { + Instant parsed = Instant.parse(value); + if (!parsed.toString().equals(value)) { + throw denied("Timestamp is not canonical UTC text"); + } + return parsed; + } catch (RuntimeException malformed) { + throw denied("Timestamp is malformed"); + } + } + + private static boolean canonicalEquals(Object first, Object second) { + if (first == null || second == null) return false; + return MessageDigest.isEqual( + AccountControlUiAuthority.canonical(first), AccountControlUiAuthority.canonical(second)); + } + + @SuppressWarnings("unchecked") + private static Map object(Object value, String field) { + if (!(value instanceof Map map) + || map.keySet().stream().anyMatch(key -> !(key instanceof String))) { + throw denied(field + " must be an object"); + } + return (Map) map; + } + + private static void requireFields(Map value, Set fields, String field) { + if (value == null || !value.keySet().equals(fields)) { + throw denied(field + " has missing or unsupported fields"); + } + } + + private static String string(Object value, String field) { + if (!(value instanceof String text) || text.isEmpty()) { + throw denied(field + " must be a nonempty string"); + } + return text; + } + + private static long positiveNumber(Object value, String field) { + try { + long parsed; + if (value instanceof Number number) { + parsed = Long.parseLong(number.toString()); + } else if (value instanceof String text && DECIMAL.matcher(text).matches()) { + parsed = Long.parseLong(text); + } else { + throw new NumberFormatException(); + } + if (parsed <= 0) throw new NumberFormatException(); + return parsed; + } catch (RuntimeException malformed) { + throw denied(field + " must be a positive canonical integer"); + } + } + + private static IllegalArgumentException denied(String message) { + return new IllegalArgumentException(message); + } + + /** Original source reference is a separate typed object, not an extra bundle member. */ + public record BundleReference( + String bundleVersion, String sourceVersion, String sourceFence, String linearization) { + public BundleReference { + new StartSessionAuthorityEvidenceBundle.BundleReference( + bundleVersion, sourceVersion, sourceFence, linearization); + } + + public Map asJsonValue() { + return Map.of( + "bundleVersion", bundleVersion, + "sourceVersion", sourceVersion, + "sourceFence", sourceFence, + "linearization", linearization); + } + + public static BundleReference fromJsonValue(Object raw) { + Map value = object(raw, "bundleReference"); + requireFields( + value, + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization"), + "bundleReference"); + return new BundleReference( + string(value.get("bundleVersion"), "bundleVersion"), + string(value.get("sourceVersion"), "sourceVersion"), + string(value.get("sourceFence"), "sourceFence"), + string(value.get("linearization"), "linearization")); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java new file mode 100644 index 0000000000..80a00a7a86 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java @@ -0,0 +1,1435 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient.Purpose; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceRecord; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.Status; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService.Current; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.Stored; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationReferenceFingerprint.ReferenceKind; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Conditionally composed Account owner service for the approved human StartSession path. Its Spring + * composition and receiving transport are disabled by default; every public operation authenticates + * the immediate certificate-derived peer before parsing request data or opening Account storage. + */ +public final class AccountStartSessionOperatorAuthorizationService { + private static final String ENVELOPE_OPERATION = "human-start-session-authorization/v1"; + private static final int REFERENCE_RANDOM_BYTES = 32; + private static final int MAX_REFERENCE_TEXT_BYTES = 128; + private static final Pattern REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final Set RESPONSE_FIELDS = + Set.of( + "operatorAuthorizationReference", + "authorizationReferenceFingerprint", + "expiresAt", + "authorityEvidenceBundle", + "bundleReference"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountControlUiActorService actors; + private final AccountControlUiIssuanceRepository issuanceOperations; + private final AccountStartSessionAuthorityCaptureRepository captureRepository; + private final StartSessionReservationEvidenceClient reservationEvidence; + private final AccountStartSessionOperatorAuthorizationRepository repository; + private final AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys; + private final AccountResponseEnvelopeCryptography responseCryptography; + private final AccountHostedTermsService hostedTerms; + private final TransactionTemplate lookupTransaction; + private final Clock clock; + private final SecureRandom secureRandom; + private final String loggingPeerUri; + private final String gameSessionPeerUri; + private final String gameDesignPeerUri; + private final long referenceLifetimeMillis; + private final long responseRecoveryWindowMillis; + + /** + * All custody and timing inputs are explicit. In particular, this service does not reuse the + * control-ui envelope instance, create or discover HMAC keys, or provide policy defaults. + */ + public AccountStartSessionOperatorAuthorizationService( + AccountControlUiActorService actors, + AccountControlUiIssuanceRepository issuanceOperations, + AccountStartSessionAuthorityCaptureRepository captureRepository, + StartSessionReservationEvidenceClient reservationEvidence, + AccountStartSessionOperatorAuthorizationRepository repository, + AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, + AccountResponseEnvelopeCryptography dedicatedOperatorResponseCryptography, + AccountHostedTermsService hostedTerms, + PlatformTransactionManager transactions, + Clock clock, + SecureRandom secureRandom, + String exactLoggingPeerUri, + String exactGameSessionPeerUri, + Duration referenceLifetime, + Duration responseRecoveryWindow) { + this.actors = Objects.requireNonNull(actors, "current Account actor service is required"); + this.issuanceOperations = + Objects.requireNonNull(issuanceOperations, "Account control-ui issuance owner is required"); + this.captureRepository = + Objects.requireNonNull( + captureRepository, "durable Account source capture owner is required"); + this.reservationEvidence = + Objects.requireNonNull(reservationEvidence, "Logging claim evidence client is required"); + this.repository = Objects.requireNonNull(repository, "Account owner repository is required"); + this.fingerprintKeys = + Objects.requireNonNull(fingerprintKeys, "explicit Account fingerprint keyring is required"); + responseCryptography = + Objects.requireNonNull( + dedicatedOperatorResponseCryptography, + "separate operator response-envelope cryptography is required"); + this.hostedTerms = + Objects.requireNonNull(hostedTerms, "Account environment source is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + this.secureRandom = Objects.requireNonNull(secureRandom, "secure random is required"); + loggingPeerUri = exactPeer(exactLoggingPeerUri, "logging-admin-service"); + gameSessionPeerUri = exactPeer(exactGameSessionPeerUri, "game-session-service"); + gameDesignPeerUri = sameNamespacePeer(gameSessionPeerUri, "game-design-service"); + referenceLifetimeMillis = policyMillis(referenceLifetime, "reference lifetime", 5 * 60_000L); + responseRecoveryWindowMillis = + policyMillis(responseRecoveryWindow, "response recovery window", 60_000L); + lookupTransaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + lookupTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * ISSUE: exact Logging peer and current original claim; committed capture precedes final owner + * issuance with current actor and capture revalidation. + */ + public AuthorizationResponse issue(IssueRequest request) { + requirePeer(loggingPeerUri); + Objects.requireNonNull(request, "issue request is required"); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(request.canonicalTupleBytes()); + requirePositiveFence(request.reservationClaimFence(), "reservationClaimFence"); + requireNonNilUuid(request.reservationOwnerId(), "reservationOwnerId"); + ReadCurrentClaimEvidenceResponse claim = + reservationEvidence.readCurrentClaimEvidence( + tuple, + request.reservationOwnerId(), + request.reservationClaimFence(), + request.claimOwnerId(), + request.claimFence(), + Purpose.ISSUE); + requireClaimEcho( + claim, + tuple, + request.reservationOwnerId(), + request.reservationClaimFence(), + request.claimOwnerId(), + request.claimFence()); + requireFreshClaimEvidence(claim); + + var environment = hostedTerms.captureCurrentEnvironmentBoundary(); + IssuePreparation preparation = + actors.withCurrent( + request.controlUiJwt(), + tuple.action().scope().tenantId(), + environment, + current -> { + requireFreshClaimEvidence(claim); + IssuanceRecord existing = findRecord(tuple.controlPlaneRequestId()).orElse(null); + if (existing != null) { + requireOriginalBinding( + existing, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + } + AccountStartSessionAuthorityCapture capture = + existing == null + ? captureRepository.prepareOrReadExact( + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()) + : captureRepository.lockReadExactCurrent( + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + if (existing != null) { + var originalBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + existing.authorityEvidenceBundle()); + var originalReference = + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + existing.bundleReference()); + originalBundle.requireCaptureBinding(capture, tuple, originalReference); + originalBundle.requireCurrent( + current.source(), current.stored(), tuple, originalReference, clock.instant()); + } + return new IssuePreparation(current, capture, existing); + }); + + requireFreshClaimEvidence(claim); + if (preparation.existing() != null) { + IssuanceRecord original = preparation.existing(); + requireOriginalBinding( + original, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AuthorizationResponse response = openOriginalResponse(tuple, original); + var finalEnvironment = hostedTerms.captureCurrentEnvironmentBoundary(); + AuthorizationResponse currentResponse = + actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + preparation.current().stored().jti, + finalEnvironment, + current -> { + requireSameCurrent(preparation.current(), current); + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(original, exact); + requireOriginalBinding( + exact, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionAuthorityCapture lockedCapture = + captureRepository.lockExactCurrent( + preparation.capture(), + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + var exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + exact.authorityEvidenceBundle()); + var originalReference = + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + original.bundleReference()); + exactBundle.requireCaptureBinding(lockedCapture, tuple, originalReference); + exactBundle.requireCurrent( + current.source(), current.stored(), tuple, originalReference, clock.instant()); + requireFreshClaimEvidence(claim); + return response; + }); + requireFreshClaimEvidence(claim); + return currentResponse; + } + + PreparedIssuance candidate = + prepareIssuance(preparation.current().stored(), preparation.capture(), tuple, request); + var finalEnvironment = hostedTerms.captureCurrentEnvironmentBoundary(); + IssueOutcome outcome = + actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + preparation.current().stored().jti, + finalEnvironment, + current -> { + requireSameCurrent(preparation.current(), current); + AccountStartSessionAuthorityCapture lockedCapture = + captureRepository.lockExactCurrent( + preparation.capture(), + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + candidate + .bundle() + .requireCaptureBinding( + lockedCapture, tuple, candidate.bundle().referenceForCapture(lockedCapture)); + candidate + .bundle() + .requireCurrent( + current.source(), + current.stored(), + tuple, + candidate.bundle().referenceForCapture(lockedCapture), + clock.instant()); + requireFreshClaimEvidence(claim); + var created = repository.createOrReadExact(candidate.candidate()); + requireOriginalBinding( + created.issuance(), + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + if (created.created()) { + requireCandidateRecord(candidate.candidate(), created.issuance()); + } else { + var originalBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + created.issuance().authorityEvidenceBundle()); + originalBundle.requireCaptureBinding( + lockedCapture, + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + created.issuance().bundleReference())); + } + requireFreshClaimEvidence(claim); + return new IssueOutcome(created.created(), created.issuance()); + }); + if (outcome.created()) return candidate.response(); + + AuthorizationResponse originalResponse = openOriginalResponse(tuple, outcome.issuance()); + var winnerEnvironment = hostedTerms.captureCurrentEnvironmentBoundary(); + AuthorizationResponse currentResponse = + actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + preparation.current().stored().jti, + winnerEnvironment, + current -> { + requireSameCurrent(preparation.current(), current); + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(outcome.issuance(), exact); + requireOriginalBinding( + exact, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionAuthorityCapture lockedCapture = + captureRepository.lockExactCurrent( + preparation.capture(), + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + var exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + exact.authorityEvidenceBundle()); + var exactReference = + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()); + exactBundle.requireCaptureBinding(lockedCapture, tuple, exactReference); + exactBundle.requireCurrent( + current.source(), current.stored(), tuple, exactReference, clock.instant()); + requireFreshClaimEvidence(claim); + return originalResponse; + }); + requireFreshClaimEvidence(claim); + return currentResponse; + } + + /** + * RECOVER: lookup-only, fresh recovery claim, current original actor, exact original response. + */ + public AuthorizationResponse recover(RecoverRequest request) { + requirePeer(loggingPeerUri); + Objects.requireNonNull(request, "recovery request is required"); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(request.canonicalTupleBytes()); + requireNonNilUuid(request.reservationOwnerId(), "reservationOwnerId"); + requirePositiveFence(request.reservationClaimFence(), "reservationClaimFence"); + requireNonNilUuid(request.claimOwnerId(), "claimOwnerId"); + requirePositiveFence(request.claimFence(), "claimFence"); + ReadCurrentClaimEvidenceResponse claim = + reservationEvidence.readCurrentClaimEvidence( + tuple, + request.reservationOwnerId(), + request.reservationClaimFence(), + request.claimOwnerId(), + request.claimFence(), + Purpose.RECOVER); + requireClaimEcho( + claim, + tuple, + request.reservationOwnerId(), + request.reservationClaimFence(), + request.claimOwnerId(), + request.claimFence()); + requireFreshClaimEvidence(claim); + + IssuanceRecord observed = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireOriginalBinding( + observed, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle bundle = + AccountStartSessionOperatorAuthorityBundle.decode(observed.authorityEvidenceBundle()); + bundle.requireTupleBinding(tuple); + UUID tokenJti = bundle.controlUiTokenJti(); + var environment = hostedTerms.captureCurrentEnvironmentBoundary(); + IssuePreparation preparation = + actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + tokenJti, + environment, + current -> { + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(observed, exact); + requireOriginalBinding( + exact, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionAuthorityCapture capture = + captureRepository.lockReadExactCurrent( + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + var exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + exact.authorityEvidenceBundle()); + var exactReference = + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()); + exactBundle.requireCaptureBinding(capture, tuple, exactReference); + exactBundle.requireCurrent( + current.source(), current.stored(), tuple, exactReference, clock.instant()); + requireFreshClaimEvidence(claim); + return new IssuePreparation(current, capture, exact); + }); + AuthorizationResponse response = openOriginalResponse(tuple, observed); + var finalEnvironment = hostedTerms.captureCurrentEnvironmentBoundary(); + AuthorizationResponse currentResponse = + actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + tokenJti, + finalEnvironment, + current -> { + requireSameCurrent(preparation.current(), current); + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(preparation.existing(), exact); + requireOriginalBinding( + exact, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionAuthorityCapture lockedCapture = + captureRepository.lockExactCurrent( + preparation.capture(), + current, + tuple, + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence()); + var exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + exact.authorityEvidenceBundle()); + var exactReference = + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()); + exactBundle.requireCaptureBinding(lockedCapture, tuple, exactReference); + exactBundle.requireCurrent( + current.source(), current.stored(), tuple, exactReference, clock.instant()); + requireFreshClaimEvidence(claim); + return response; + }); + requireFreshClaimEvidence(claim); + return currentResponse; + } + + /** REDEEM: exact Game Session peer before tuple parsing or durable reference lookup. */ + public RedemptionResult redeem(RedeemRequest request) { + requirePeer(gameSessionPeerUri); + Objects.requireNonNull(request, "redemption request is required"); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(request.canonicalTupleBytes()); + String reference = requireReference(request.operatorAuthorizationReference()); + byte[] referenceBytes = reference.getBytes(StandardCharsets.US_ASCII); + try { + requireFingerprint(request.authorizationReferenceFingerprint()); + requireNonNilUuid(request.reservationOwnerId(), "reservationOwnerId"); + requirePositiveFence(request.reservationClaimFence(), "reservationClaimFence"); + requireNonNilUuid(request.ownerAttemptId(), "ownerAttemptId"); + requirePositiveFence(request.ownerFence(), "ownerFence"); + + IssuanceRecord observed = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireOriginalBinding( + observed, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + boolean sameAttemptReplay = + observed.status() == Status.REDEEMED + && gameSessionPeerUri.equals(observed.redemptionRedeemerWorkloadUri()) + && request.ownerAttemptId().equals(observed.redemptionOwnerAttemptId()) + && Objects.equals( + Long.valueOf(request.ownerFence()), observed.redemptionOwnerFence()); + if (observed.status() == Status.REDEEMED && !sameAttemptReplay) { + throw denied("A consumed StartSession reference cannot authorize another owner attempt"); + } + if (!fingerprintKeys.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + referenceBytes, + observed.authorizationReferenceFingerprint(), + observed.referenceExpiresAt(), + observed.responseEnvelopeExpiresAt())) { + throw denied("Original Account authorization reference does not match"); + } + if (!constantTimeEquals( + observed.authorizationReferenceFingerprint(), + request.authorizationReferenceFingerprint())) { + throw denied("Forwarded Account authorization fingerprint changed"); + } + + AccountStartSessionOperatorAuthorityBundle bundle = + AccountStartSessionOperatorAuthorityBundle.decode(observed.authorityEvidenceBundle()); + bundle.requireTupleBinding(tuple); + var originalResponse = tryOpenOriginalResponse(observed, bundle, tuple); + if (originalResponse.isEmpty() && !sameAttemptReplay) { + throw denied("Original Account issuance response is no longer recoverable"); + } + if (originalResponse.isPresent() + && !constantTimeEquals( + reference, originalResponse.orElseThrow().operatorAuthorizationReference())) { + throw denied("Redeemed opaque reference differs from the original Account response"); + } + var environment = hostedTerms.captureCurrentEnvironmentBoundary(); + return actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + bundle.controlUiTokenJti(), + environment, + current -> { + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(observed, exact); + requireOriginalBinding( + exact, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + if (sameAttemptReplay && originalResponse.isEmpty()) { + bundle.requireCurrentSnapshotForExactReplay( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + observed.bundleReference())); + } else { + bundle.requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + observed.bundleReference()), + clock.instant()); + } + RedemptionResult result = + repository.redeemExact( + new RedemptionRequest( + tuple.controlPlaneRequestId(), + request.canonicalTupleBytes(), + observed.authorizationReferenceFingerprint(), + observed.reservationOwnerId(), + observed.reservationClaimFence(), + gameSessionPeerUri, + request.ownerAttemptId(), + request.ownerFence(), + observed.authorityEvidenceBundle(), + Instant.ofEpochMilli(clock.millis()))); + requireRedemptionProjection(result, observed); + if (sameAttemptReplay != result.replay()) { + throw denied("Account returned a changed one-time redemption outcome"); + } + return result; + }); + } finally { + Arrays.fill(referenceBytes, (byte) 0); + } + } + + /** + * Returns only the immutable original projection of an already-redeemed operation to the exact + * same-namespace Game Design peer or the exact original Game Session redeemer. This read neither + * exposes a credential nor changes owner state; Account independently revalidates the original + * committed actor and source. + */ + public RedeemedOperationProjection readRedeemedOperationProjection( + ReadRedeemedOperationProjectionRequest request) { + requireRedeemedProjectionReadPeer(); + Objects.requireNonNull(request, "redeemed operation projection request is required"); + byte[] exactTupleBytes = request.canonicalPreAuthorizationTuple(); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(exactTupleBytes); + requireFingerprint(request.authorizationReferenceFingerprint()); + requireNonNilUuid(request.reservationOwnerId(), "reservationOwnerId"); + requirePositiveFence(request.reservationClaimFence(), "reservationClaimFence"); + requireNonNilUuid(request.ownerAttemptId(), "ownerAttemptId"); + requirePositiveFence(request.ownerFence(), "ownerFence"); + if (!"game-session-service".equals(tuple.targetOwner())) { + throw denied("Operation projection is limited to the Game Session owner"); + } + + IssuanceRecord observed = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireOriginalBinding( + observed, + tuple, + exactTupleBytes, + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle bundle = + AccountStartSessionOperatorAuthorityBundle.decode(observed.authorityEvidenceBundle()); + bundle.requireTupleBinding(tuple); + requireRedeemedProjectionBinding(observed, tuple, request, bundle, clock.instant()); + + var environment = hostedTerms.captureCurrentEnvironmentBoundary(); + return actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + bundle.controlUiTokenJti(), + environment, + current -> { + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredRedemption(observed, exact); + requireOriginalBinding( + exact, + tuple, + exactTupleBytes, + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()); + exactBundle.requireTupleBinding(tuple); + requireRedeemedProjectionBinding(exact, tuple, request, exactBundle, clock.instant()); + exactBundle.requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()), + clock.instant()); + return projection(exact); + }); + } + + private PreparedIssuance prepareIssuance( + Stored controlUiIssuance, + AccountStartSessionAuthorityCapture capture, + StartSessionPreAuthorizationReservationTuple tuple, + IssueRequest request) { + Objects.requireNonNull(controlUiIssuance, "original ControlUI issuance is required"); + Objects.requireNonNull(capture, "committed Account source capture is required"); + byte[] exactTuple = request.canonicalTupleBytes(); + Instant issuedAt = Instant.ofEpochMilli(clock.millis()); + Instant referenceExpiresAt = addMillis(issuedAt, referenceLifetimeMillis); + Instant responseExpiresAt = addMillis(referenceExpiresAt, responseRecoveryWindowMillis); + UUID issuanceOperationId = UUID.randomUUID(); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + tuple, capture, controlUiIssuance, issuanceOperationId, issuedAt, referenceExpiresAt); + var bundleReference = bundle.referenceForCapture(capture); + + byte[] random = new byte[REFERENCE_RANDOM_BYTES]; + secureRandom.nextBytes(random); + String authorizationReference = Base64.getUrlEncoder().withoutPadding().encodeToString(random); + Arrays.fill(random, (byte) 0); + byte[] referenceBytes = authorizationReference.getBytes(StandardCharsets.US_ASCII); + byte[] responseBytes = null; + try { + String fingerprint = + fingerprintKeys.fingerprintForIssue(ReferenceKind.HUMAN_OPERATOR, referenceBytes); + AuthorizationResponse response = + new AuthorizationResponse( + authorizationReference, + fingerprint, + referenceExpiresAt, + bundle.canonicalBytes(), + bundleReference); + responseBytes = encodeResponse(response); + EncryptedResponseEnvelope envelope = + responseCryptography.encrypt( + responseBinding( + issuanceOperationId, + tuple, + exactTuple, + loggingPeerUri, + bundle.issuanceFence(), + bundle), + responseBytes, + responseExpiresAt); + IssuanceCandidate candidate = + new IssuanceCandidate( + tuple.controlPlaneRequestId(), + exactTuple, + tuple.mutationDigest(), + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence(), + issuanceOperationId, + bundle.issuanceFence(), + AccountStartSessionOperatorAuthorityBundle.toSharedReference(bundleReference), + bundle.canonicalBytes(), + fingerprint, + envelope.bytes(), + issuedAt, + referenceExpiresAt, + responseExpiresAt); + return new PreparedIssuance(bundle, response, candidate); + } finally { + Arrays.fill(referenceBytes, (byte) 0); + if (responseBytes != null) Arrays.fill(responseBytes, (byte) 0); + } + } + + private AuthorizationResponse openOriginalResponse( + StartSessionPreAuthorizationReservationTuple tuple, IssuanceRecord record) { + AccountStartSessionOperatorAuthorityBundle bundle = + AccountStartSessionOperatorAuthorityBundle.decode(record.authorityEvidenceBundle()); + bundle.requireTupleBinding(tuple); + byte[] plaintext = null; + try { + plaintext = + responseCryptography.decrypt( + new EncryptedResponseEnvelope(record.encryptedResponseEnvelope()), + responseBinding( + record.issuanceOperationId(), + tuple, + record.preAuthorizationTuple(), + record.issuanceWorkloadUri(), + record.issuanceFence(), + bundle), + record.responseEnvelopeExpiresAt()); + AuthorizationResponse response = decodeResponse(plaintext); + requireResponseMatchesRecord(response, record); + return response; + } finally { + if (plaintext != null) Arrays.fill(plaintext, (byte) 0); + } + } + + private Optional tryOpenOriginalResponse( + IssuanceRecord record, + AccountStartSessionOperatorAuthorityBundle bundle, + StartSessionPreAuthorizationReservationTuple tuple) { + if (!clock.instant().isBefore(record.responseEnvelopeExpiresAt())) { + return Optional.empty(); + } + byte[] plaintext = null; + try { + plaintext = + responseCryptography.decrypt( + new EncryptedResponseEnvelope(record.encryptedResponseEnvelope()), + responseBinding( + record.issuanceOperationId(), + tuple, + record.preAuthorizationTuple(), + record.issuanceWorkloadUri(), + record.issuanceFence(), + bundle), + record.responseEnvelopeExpiresAt()); + AuthorizationResponse response = decodeResponse(plaintext); + requireResponseMatchesRecord(response, record); + return Optional.of(response); + } catch (AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException expired) { + return Optional.empty(); + } finally { + if (plaintext != null) Arrays.fill(plaintext, (byte) 0); + } + } + + private Binding responseBinding( + UUID operationId, + StartSessionPreAuthorizationReservationTuple tuple, + byte[] exactTuple, + String callerWorkload, + long issuanceFence, + AccountStartSessionOperatorAuthorityBundle bundle) { + return new Binding( + ENVELOPE_OPERATION, + tuple.controlPlaneRequestId(), + sha256(exactTuple), + callerWorkload, + operationId.toString(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + issuanceFence, + AccountControlUiAuthority.canonical(bundle.authorityTuple()), + AccountControlUiAuthority.canonical(bundle.membershipVersion()), + bundle.canonicalBytes()); + } + + private static byte[] encodeResponse(AuthorizationResponse response) { + return AccountControlUiAuthority.canonical( + Map.of( + "operatorAuthorizationReference", response.operatorAuthorizationReference(), + "authorizationReferenceFingerprint", response.authorizationReferenceFingerprint(), + "expiresAt", response.expiresAt().toString(), + "authorityEvidenceBundle", + AccountStartSessionOperatorAuthorityBundle.decode( + response.authorityEvidenceBundle()) + .jsonValue(), + "bundleReference", response.bundleReference().asJsonValue())); + } + + private static AuthorizationResponse decodeResponse(byte[] exactBytes) { + try { + String json = new String(exactBytes, StandardCharsets.UTF_8); + Map root = JSON.readValue(json, new TypeReference<>() {}); + if (!root.keySet().equals(RESPONSE_FIELDS)) { + throw denied("Original response envelope has changed fields"); + } + String reference = requireReference(root.get("operatorAuthorizationReference")); + String fingerprint = requireFingerprint(root.get("authorizationReferenceFingerprint")); + Instant expiresAt = canonicalInstant(root.get("expiresAt")); + byte[] bundleBytes = AccountControlUiAuthority.canonical(root.get("authorityEvidenceBundle")); + AccountStartSessionOperatorAuthorityBundle.decode(bundleBytes); + var sourceReference = + AccountStartSessionOperatorAuthorityBundle.BundleReference.fromJsonValue( + root.get("bundleReference")); + byte[] canonical = + encodeResponse( + new AuthorizationResponse( + reference, fingerprint, expiresAt, bundleBytes, sourceReference)); + if (!MessageDigest.isEqual(canonical, exactBytes)) { + throw denied("Original response envelope is not canonical"); + } + return new AuthorizationResponse( + reference, fingerprint, expiresAt, bundleBytes, sourceReference); + } catch (IllegalStateException failure) { + throw failure; + } catch (RuntimeException malformed) { + throw denied("Original response envelope is malformed"); + } + } + + private void requireResponseMatchesRecord(AuthorizationResponse response, IssuanceRecord record) { + var bundle = + AccountStartSessionOperatorAuthorityBundle.decode(record.authorityEvidenceBundle()); + if (!response + .authorizationReferenceFingerprint() + .equals(record.authorizationReferenceFingerprint()) + || !response.expiresAt().equals(record.referenceExpiresAt()) + || !Arrays.equals(response.authorityEvidenceBundle(), record.authorityEvidenceBundle()) + || !response + .bundleReference() + .bundleVersion() + .equals(AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION) + || !response.bundleReference().sourceVersion().equals(bundleSourceVersion(bundle)) + || !AccountStartSessionOperatorAuthorityBundle.toSharedReference(response.bundleReference()) + .equals(record.bundleReference()) + || bundle.issuanceFence() != record.issuanceFence()) { + throw denied("Original issuance response differs from the immutable Account record"); + } + byte[] referenceBytes = + response.operatorAuthorizationReference().getBytes(StandardCharsets.US_ASCII); + try { + if (!fingerprintKeys.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + referenceBytes, + record.authorizationReferenceFingerprint(), + record.referenceExpiresAt(), + record.responseEnvelopeExpiresAt())) { + throw denied("Original Account response reference does not match its stored fingerprint"); + } + } finally { + Arrays.fill(referenceBytes, (byte) 0); + } + } + + private static void requireSameCurrent(Current expected, Current observed) { + if (!sameCurrentSource(expected.source(), observed.source()) + || !sameControlUiIssuance(expected.stored(), observed.stored())) { + throw denied("Account actor or source changed between preparation and owner commit"); + } + } + + private static boolean sameCurrentSource( + AccountControlUiAuthority.Snapshot first, AccountControlUiAuthority.Snapshot second) { + return first.actor().equals(second.actor()) + && first.tenant().equals(second.tenant()) + && Arrays.equals(first.evidence(), second.evidence()) + && Arrays.equals( + AccountControlUiAuthority.canonical(first.authorityTuple()), + AccountControlUiAuthority.canonical(second.authorityTuple())) + && Arrays.equals( + AccountControlUiAuthority.canonical(first.membershipVersion()), + AccountControlUiAuthority.canonical(second.membershipVersion())); + } + + private static boolean sameControlUiIssuance( + AccountControlUiIssuanceRepository.Stored first, + AccountControlUiIssuanceRepository.Stored second) { + return first != null + && second != null + && Objects.equals(first.requestId, second.requestId) + && Objects.equals(first.operationId, second.operationId) + && Objects.equals(first.jti, second.jti) + && Objects.equals(first.accountId, second.accountId) + && Objects.equals(first.tenantId, second.tenantId) + && Objects.equals(first.callerContextId, second.callerContextId) + && Objects.equals(first.caller, second.caller) + && Objects.equals(first.requestMacKeyId, second.requestMacKeyId) + && Objects.equals(first.requestDigest, second.requestDigest) + && Objects.equals(first.status, second.status) + && Objects.equals(first.tokenHash, second.tokenHash) + && Arrays.equals(first.claims, second.claims) + && Arrays.equals(first.sources, second.sources) + && Arrays.equals(first.bundle, second.bundle) + && Arrays.equals(first.signerReceipt, second.signerReceipt) + && Arrays.equals(first.pendingRegistry, second.pendingRegistry) + && Arrays.equals(first.activeRegistry, second.activeRegistry) + && Objects.equals(first.issuedAt, second.issuedAt) + && Objects.equals(first.expiresAt, second.expiresAt) + && Objects.equals(first.recoveryExpiry, second.recoveryExpiry); + } + + private static void requireCandidateRecord(IssuanceCandidate candidate, IssuanceRecord record) { + if (record.status() != Status.ISSUED + || !candidate.controlPlaneRequestId().equals(record.controlPlaneRequestId()) + || !Arrays.equals(candidate.preAuthorizationTuple(), record.preAuthorizationTuple()) + || !candidate.mutationDigest().equals(record.mutationDigest()) + || !candidate.issuanceWorkloadUri().equals(record.issuanceWorkloadUri()) + || !candidate.reservationOwnerId().equals(record.reservationOwnerId()) + || candidate.reservationClaimFence() != record.reservationClaimFence() + || !candidate.issuanceOperationId().equals(record.issuanceOperationId()) + || candidate.issuanceFence() != record.issuanceFence() + || !candidate.bundleReference().equals(record.bundleReference()) + || !Arrays.equals(candidate.authorityEvidenceBundle(), record.authorityEvidenceBundle()) + || !candidate + .authorizationReferenceFingerprint() + .equals(record.authorizationReferenceFingerprint()) + || !Arrays.equals(candidate.encryptedResponseEnvelope(), record.encryptedResponseEnvelope()) + || !candidate.issuedAt().equals(record.issuedAt()) + || !candidate.referenceExpiresAt().equals(record.referenceExpiresAt()) + || !candidate.responseEnvelopeExpiresAt().equals(record.responseEnvelopeExpiresAt())) { + throw denied("New Account issuance differs from its exact durable candidate"); + } + } + + private static String bundleSourceVersion(AccountStartSessionOperatorAuthorityBundle bundle) { + return bundle.sourceEvidenceVersion(); + } + + private static void requireRedemptionProjection( + RedemptionResult result, IssuanceRecord issuance) { + if (!issuance + .authorizationReferenceFingerprint() + .equals(result.authorizationReferenceFingerprint()) + || !Arrays.equals(issuance.authorityEvidenceBundle(), result.authorityEvidenceBundle()) + || !issuance.issuanceOperationId().equals(result.issuanceOperationId()) + || issuance.issuanceFence() != result.issuanceFence()) { + throw denied("Account redemption returned a changed authority projection"); + } + } + + private Optional findRecord(String controlPlaneRequestId) { + return Objects.requireNonNull( + lookupTransaction.execute( + ignored -> repository.findByControlPlaneRequestId(controlPlaneRequestId)), + "Account lookup transaction result"); + } + + private static void requireClaimEcho( + ReadCurrentClaimEvidenceResponse evidence, + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + if (!tuple.controlPlaneRequestId().equals(evidence.getControlPlaneRequestId()) + || !Arrays.equals( + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + evidence.getPreAuthorizationTupleJson().toByteArray()) + || !tuple.mutationDigest().equals(evidence.getMutationDigest()) + || !reservationOwnerId.toString().equals(evidence.getReservationOwnerId()) + || reservationClaimFence != evidence.getReservationClaimFence() + || !currentClaimOwnerId.toString().equals(evidence.getClaimOwnerId()) + || currentClaimFence != evidence.getClaimFence()) { + throw denied("Logging/Admin current reservation claim differs from the exact request"); + } + } + + private void requireFreshClaimEvidence(ReadCurrentClaimEvidenceResponse evidence) { + Objects.requireNonNull(evidence, "Logging/Admin claim evidence is required"); + long observedAt = evidence.getObservedAtEpochMillis(); + long expiresAt = evidence.getClaimExpiresAtEpochMillis(); + long now = clock.millis(); + if (observedAt <= 0L || expiresAt <= observedAt || now < observedAt || now >= expiresAt) { + throw denied("Logging/Admin StartSession claim evidence is stale or contradictory"); + } + } + + private static StartSessionPreAuthorizationReservationTuple decodeTuple(byte[] exactTupleBytes) { + if (exactTupleBytes == null || exactTupleBytes.length == 0) { + throw new IllegalArgumentException("Canonical StartSession reservation tuple is required"); + } + String json = new String(exactTupleBytes, StandardCharsets.UTF_8); + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(json); + if (!Arrays.equals(exactTupleBytes, tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("StartSession reservation tuple bytes are not canonical"); + } + return tuple; + } + + private void requireOriginalBinding( + IssuanceRecord record, + StartSessionPreAuthorizationReservationTuple tuple, + byte[] exactTuple, + UUID reservationOwnerId, + long reservationClaimFence) { + if (!tuple.controlPlaneRequestId().equals(record.controlPlaneRequestId()) + || !Arrays.equals(exactTuple, record.preAuthorizationTuple()) + || !tuple.mutationDigest().equals(record.mutationDigest()) + || !loggingPeerUri.equals(record.issuanceWorkloadUri()) + || !reservationOwnerId.equals(record.reservationOwnerId()) + || reservationClaimFence != record.reservationClaimFence()) { + throw denied("StartSession request conflicts with the original Account issuance"); + } + } + + private void requireRedeemedProjectionBinding( + IssuanceRecord record, + StartSessionPreAuthorizationReservationTuple tuple, + ReadRedeemedOperationProjectionRequest request, + AccountStartSessionOperatorAuthorityBundle bundle, + Instant now) { + if (record.status() != Status.REDEEMED + || !gameSessionPeerUri.equals(record.redemptionRedeemerWorkloadUri()) + || !request.ownerAttemptId().equals(record.redemptionOwnerAttemptId()) + || !Objects.equals(Long.valueOf(request.ownerFence()), record.redemptionOwnerFence()) + || !constantTimeEquals( + record.authorizationReferenceFingerprint(), request.authorizationReferenceFingerprint()) + || !constantTimeEquals( + record.authorizationReferenceFingerprint(), record.redemptionReferenceFingerprint()) + || !Arrays.equals( + record.authorityEvidenceBundle(), record.redemptionAuthorityEvidenceBundle()) + || !tuple.controlPlaneRequestId().equals(bundle.controlPlaneRequestId()) + || !tuple.mutationDigest().equals(record.mutationDigest()) + || !bundle.issuanceOperationId().equals(record.issuanceOperationId()) + || !bundle.sourceEvidenceVersion().equals(record.bundleReference().sourceVersion()) + || !bundle.authorizationExpiresAt().equals(record.referenceExpiresAt().toString()) + || record.redeemedAt().isBefore(record.issuedAt()) + || now.isBefore(record.redeemedAt()) + || !record.redeemedAt().isBefore(record.referenceExpiresAt()) + || !now.isBefore(record.referenceExpiresAt())) { + throw denied("Stored redeemed operation does not match the exact current read request"); + } + } + + private static RedeemedOperationProjection projection(IssuanceRecord record) { + return new RedeemedOperationProjection( + record.controlPlaneRequestId(), + record.preAuthorizationTuple(), + record.mutationDigest(), + record.authorizationReferenceFingerprint(), + record.reservationOwnerId(), + record.reservationClaimFence(), + record.redemptionRedeemerWorkloadUri(), + record.redemptionOwnerAttemptId(), + record.redemptionOwnerFence(), + record.referenceExpiresAt(), + record.redeemedAt(), + record.issuanceOperationId(), + record.issuanceFence(), + AccountStartSessionOperatorAuthorityBundle.fromSharedReference(record.bundleReference()), + record.authorityEvidenceBundle()); + } + + private static void requireSameStoredIssuance(IssuanceRecord original, IssuanceRecord observed) { + if (!original.controlPlaneRequestId().equals(observed.controlPlaneRequestId()) + || !Arrays.equals(original.preAuthorizationTuple(), observed.preAuthorizationTuple()) + || !original.mutationDigest().equals(observed.mutationDigest()) + || !original.issuanceWorkloadUri().equals(observed.issuanceWorkloadUri()) + || !original.reservationOwnerId().equals(observed.reservationOwnerId()) + || original.reservationClaimFence() != observed.reservationClaimFence() + || !original.issuanceOperationId().equals(observed.issuanceOperationId()) + || original.issuanceFence() != observed.issuanceFence() + || !original.bundleReference().equals(observed.bundleReference()) + || !Arrays.equals(original.authorityEvidenceBundle(), observed.authorityEvidenceBundle()) + || !original + .authorizationReferenceFingerprint() + .equals(observed.authorizationReferenceFingerprint()) + || !Arrays.equals( + original.encryptedResponseEnvelope(), observed.encryptedResponseEnvelope()) + || !original.issuedAt().equals(observed.issuedAt()) + || !original.referenceExpiresAt().equals(observed.referenceExpiresAt()) + || !original.responseEnvelopeExpiresAt().equals(observed.responseEnvelopeExpiresAt())) { + throw denied("Immutable Account StartSession issuance changed during owner revalidation"); + } + } + + private static void requireSameStoredRedemption( + IssuanceRecord original, IssuanceRecord observed) { + requireSameStoredIssuance(original, observed); + if (original.status() != Status.REDEEMED + || observed.status() != Status.REDEEMED + || !Objects.equals( + original.redemptionRedeemerWorkloadUri(), observed.redemptionRedeemerWorkloadUri()) + || !Objects.equals(original.redemptionOwnerAttemptId(), observed.redemptionOwnerAttemptId()) + || !Objects.equals(original.redemptionOwnerFence(), observed.redemptionOwnerFence()) + || !Objects.equals(original.redeemedAt(), observed.redeemedAt()) + || !constantTimeEquals( + original.redemptionReferenceFingerprint(), observed.redemptionReferenceFingerprint()) + || !Arrays.equals( + original.redemptionAuthorityEvidenceBundle(), + observed.redemptionAuthorityEvidenceBundle())) { + throw denied("Original Account redemption changed during current-source revalidation"); + } + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static Instant canonicalInstant(Object value) { + if (!(value instanceof String text)) throw denied("Original response expiry must be text"); + Instant instant; + try { + instant = Instant.parse(text); + } catch (RuntimeException malformed) { + throw denied("Original response expiry is malformed"); + } + if (!instant.toString().equals(text)) throw denied("Original response expiry is not canonical"); + return instant; + } + + private static String requireReference(Object value) { + if (!(value instanceof String text) + || text.getBytes(StandardCharsets.US_ASCII).length > MAX_REFERENCE_TEXT_BYTES + || !REFERENCE.matcher(text).matches()) { + throw denied("Opaque StartSession authorization reference is malformed"); + } + byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(text); + } catch (RuntimeException malformed) { + throw denied("Opaque StartSession authorization reference is malformed"); + } + try { + if (decoded.length != REFERENCE_RANDOM_BYTES + || !Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(text)) { + throw denied("Opaque StartSession authorization reference is not canonical"); + } + } finally { + Arrays.fill(decoded, (byte) 0); + } + return text; + } + + private static String requireFingerprint(Object value) { + if (!(value instanceof String text) + || !text.matches("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}")) { + throw denied("Account authorization-reference fingerprint is malformed"); + } + return text; + } + + private static boolean constantTimeEquals(String first, String second) { + return second != null + && MessageDigest.isEqual( + first.getBytes(StandardCharsets.US_ASCII), second.getBytes(StandardCharsets.US_ASCII)); + } + + private static void requirePeer(String exactUri) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !exactUri.equals(peer.uri())) { + throw denied("Exact authenticated internal workload identity is required"); + } + } + + private void requireRedeemedProjectionReadPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || (!gameDesignPeerUri.equals(peer.uri()) && !gameSessionPeerUri.equals(peer.uri()))) { + throw denied("Exact authenticated Game Design or Game Session workload identity is required"); + } + } + + private static String exactPeer(String value, String expectedService) { + return GrpcPeerIdentity.parseUri(value) + .map(GrpcPeerIdentity::uri) + .filter(value::equals) + .filter(uri -> uri.endsWith("/sa/" + expectedService)) + .orElseThrow( + () -> new IllegalArgumentException("Exact configured workload URI is required")); + } + + private static String sameNamespacePeer(String exactPeerUri, String service) { + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri(exactPeerUri) + .orElseThrow( + () -> new IllegalArgumentException("Exact configured workload URI is required")); + return exactPeer("spiffe://firemud/ns/" + peer.namespace() + "/sa/" + service, service); + } + + private static long policyMillis(Duration value, String field, long maximum) { + Objects.requireNonNull(value, field + " policy is required"); + long millis; + try { + millis = value.toMillis(); + } catch (ArithmeticException outOfRange) { + throw new IllegalArgumentException(field + " is outside the supported range"); + } + if (millis <= 0 || millis > maximum || !Duration.ofMillis(millis).equals(value)) { + throw new IllegalArgumentException( + field + " must be an explicit bounded millisecond duration"); + } + return millis; + } + + private static Instant addMillis(Instant value, long millis) { + try { + return Instant.ofEpochMilli(Math.addExact(value.toEpochMilli(), millis)); + } catch (RuntimeException overflow) { + throw new IllegalArgumentException( + "Operator reference expiry is outside the supported range"); + } + } + + private static void requireNonNilUuid(UUID value, String field) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical nonnil UUID"); + } + } + + private static void requirePositiveFence(long value, String field) { + if (value <= 0) throw new IllegalArgumentException(field + " must be positive"); + } + + private static IllegalStateException denied(String reason) { + return new IllegalStateException(reason); + } + + private record IssuePreparation( + Current current, AccountStartSessionAuthorityCapture capture, IssuanceRecord existing) { + private IssuePreparation { + Objects.requireNonNull(current, "current Account actor is required"); + Objects.requireNonNull(capture, "durable Account source capture is required"); + } + } + + private record PreparedIssuance( + AccountStartSessionOperatorAuthorityBundle bundle, + AuthorizationResponse response, + IssuanceCandidate candidate) { + private PreparedIssuance { + Objects.requireNonNull(bundle, "authority bundle is required"); + Objects.requireNonNull(response, "exact response is required"); + Objects.requireNonNull(candidate, "durable issuance candidate is required"); + } + } + + private record IssueOutcome(boolean created, IssuanceRecord issuance) { + private IssueOutcome { + Objects.requireNonNull(issuance, "durable issuance result is required"); + } + } + + public record IssueRequest( + String controlUiJwt, + byte[] canonicalTupleBytes, + UUID reservationOwnerId, + long reservationClaimFence, + UUID claimOwnerId, + long claimFence) { + public IssueRequest { + canonicalTupleBytes = copy(canonicalTupleBytes); + } + + @Override + public byte[] canonicalTupleBytes() { + return copy(canonicalTupleBytes); + } + + @Override + public String toString() { + return "IssueRequest[control-ui JWT and tuple redacted]"; + } + } + + public record RecoverRequest( + byte[] canonicalTupleBytes, + UUID reservationOwnerId, + long reservationClaimFence, + UUID claimOwnerId, + long claimFence) { + public RecoverRequest { + canonicalTupleBytes = copy(canonicalTupleBytes); + } + + @Override + public byte[] canonicalTupleBytes() { + return copy(canonicalTupleBytes); + } + + @Override + public String toString() { + return "RecoverRequest[tuple redacted]"; + } + } + + public record RedeemRequest( + byte[] canonicalTupleBytes, + String operatorAuthorizationReference, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + UUID ownerAttemptId, + long ownerFence) { + public RedeemRequest { + canonicalTupleBytes = copy(canonicalTupleBytes); + } + + @Override + public byte[] canonicalTupleBytes() { + return copy(canonicalTupleBytes); + } + + @Override + public String toString() { + return "RedeemRequest[tuple, reference, fingerprint redacted]"; + } + } + + /** The exact original tuple, fingerprint and owner bindings; contains no JWT or opaque ref. */ + public record ReadRedeemedOperationProjectionRequest( + byte[] canonicalPreAuthorizationTuple, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + UUID ownerAttemptId, + long ownerFence) { + public ReadRedeemedOperationProjectionRequest { + canonicalPreAuthorizationTuple = copy(canonicalPreAuthorizationTuple); + } + + @Override + public byte[] canonicalPreAuthorizationTuple() { + return copy(canonicalPreAuthorizationTuple); + } + + @Override + public String toString() { + return "ReadRedeemedOperationProjectionRequest[tuple and fingerprint redacted]"; + } + } + + /** Immutable, credential-free Account projection of the original exact redeemed operation. */ + public record RedeemedOperationProjection( + String controlPlaneRequestId, + byte[] canonicalPreAuthorizationTuple, + String mutationDigest, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + String redeemerWorkloadUri, + UUID ownerAttemptId, + long ownerFence, + Instant referenceExpiresAt, + Instant redeemedAt, + UUID issuanceOperationId, + long issuanceFence, + AccountStartSessionOperatorAuthorityBundle.BundleReference bundleReference, + byte[] authorityEvidenceBundle) { + public RedeemedOperationProjection { + canonicalPreAuthorizationTuple = copy(canonicalPreAuthorizationTuple); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + Objects.requireNonNull(bundleReference, "original bundle reference is required"); + } + + @Override + public byte[] canonicalPreAuthorizationTuple() { + return copy(canonicalPreAuthorizationTuple); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public String toString() { + return "RedeemedOperationProjection[authority evidence redacted]"; + } + } + + /** Exact response bytes are only stored in the encrypted owner envelope. */ + public record AuthorizationResponse( + String operatorAuthorizationReference, + String authorizationReferenceFingerprint, + Instant expiresAt, + byte[] authorityEvidenceBundle, + AccountStartSessionOperatorAuthorityBundle.BundleReference bundleReference) { + public AuthorizationResponse { + requireReference(operatorAuthorizationReference); + requireFingerprint(authorizationReferenceFingerprint); + Objects.requireNonNull(expiresAt, "reference expiry is required"); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + Objects.requireNonNull(bundleReference, "source bundle reference is required"); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public String toString() { + return "AuthorizationResponse[reference, bundle, and fingerprint redacted]"; + } + } + + public static final class NotFoundException extends RuntimeException { + public NotFoundException() { + super("No original StartSession operator authorization exists"); + } + } + + private static byte[] copy(byte[] value) { + return value == null ? null : value.clone(); + } +} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 526520c5d0..69d339ddb8 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -41,6 +41,8 @@ firemud: private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} account: + start-session-operator-authorization: + enabled: ${FIREMUD_ACCOUNT_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED:false} credentials: cleanup: batch-size: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_BATCH_SIZE:100} diff --git a/services/account-service/src/main/resources/db/migration/V84__individual_creator_party_sources.sql b/services/account-service/src/main/resources/db/migration/V84__individual_creator_party_sources.sql index d717b24762..1485f13b03 100644 --- a/services/account-service/src/main/resources/db/migration/V84__individual_creator_party_sources.sql +++ b/services/account-service/src/main/resources/db/migration/V84__individual_creator_party_sources.sql @@ -73,6 +73,15 @@ CREATE TRIGGER account_creator_party_history_immutable CREATE TRIGGER account_creator_party_operation_immutable BEFORE UPDATE OR DELETE ON account_fresh_creator_party_association_operations FOR EACH ROW EXECUTE FUNCTION account_creator_party_immutable_guard(); +CREATE TRIGGER account_individual_creator_party_no_truncate + BEFORE TRUNCATE ON account_individual_creator_party_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard(); +CREATE TRIGGER account_creator_party_history_no_truncate + BEFORE TRUNCATE ON account_tenant_creator_party_history + FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard(); +CREATE TRIGGER account_creator_party_operation_no_truncate + BEFORE TRUNCATE ON account_fresh_creator_party_association_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard(); CREATE FUNCTION account_creator_party_history_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN diff --git a/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql b/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql index 3371d9d86a..d1da3e468f 100644 --- a/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql +++ b/services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql @@ -62,6 +62,20 @@ BEGIN IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Control-ui issuance evidence cannot be deleted' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.status IS DISTINCT FROM 'PREPARED' + OR NEW.token_hash IS NOT NULL + OR NEW.pending_registry IS NOT NULL + OR NEW.active_registry IS NOT NULL + OR NEW.pending_receipt IS NOT NULL + OR NEW.committed_at IS NOT NULL + OR NEW.recovery_failed_at IS NOT NULL + OR NEW.revocation_receipt IS NOT NULL THEN + RAISE EXCEPTION 'Control-ui issuance must begin in its empty prepared state' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; IF (to_jsonb(NEW) - ARRAY['status','token_hash','pending_registry','active_registry', 'pending_receipt','committed_at','recovery_failed_at','revocation_receipt']) IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status','token_hash','pending_registry','active_registry', @@ -105,7 +119,7 @@ END; $$; CREATE TRIGGER account_control_ui_issuance_immutable - BEFORE UPDATE OR DELETE ON account_control_ui_issuance_operations + BEFORE INSERT OR UPDATE OR DELETE ON account_control_ui_issuance_operations FOR EACH ROW EXECUTE FUNCTION account_control_ui_issuance_guard(); CREATE TRIGGER account_control_ui_issuance_no_truncate BEFORE TRUNCATE ON account_control_ui_issuance_operations diff --git a/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql b/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql index 30afe17861..9dce268109 100644 --- a/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql +++ b/services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql @@ -21,7 +21,9 @@ CREATE TABLE account_selected_publication_authorizations ( CREATE TABLE account_selected_publication_sources ( operation_id UUID NOT NULL REFERENCES account_selected_publication_authorizations(operation_id), - source_key VARCHAR(512) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_key VARCHAR(2048) NOT NULL + CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048) + REFERENCES account_draft_authorization_source_locks(source_key), source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), PRIMARY KEY (operation_id, source_key) ); @@ -58,12 +60,12 @@ BEGIN IF issuer.status IS DISTINCT FROM 'COMMITTED' OR issuer.account_uuid <> NEW.actor_account_uuid OR issuer.tenant_uuid <> NEW.tenant_uuid OR issuer.source_payload <> NEW.source_payload OR issuer.bundle_payload <> NEW.issuance_bundle - OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT <> NEW.issuance_fence + OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT IS DISTINCT FROM NEW.issuance_fence OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB OR NEW.producer_xid <> txid_current() - OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'accountId' <> NEW.actor_account_uuid::TEXT - OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'tenantId' <> NEW.tenant_uuid::TEXT THEN + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'accountId' IS DISTINCT FROM NEW.actor_account_uuid::TEXT + OR convert_from(NEW.source_payload, 'UTF8')::JSONB->>'tenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT THEN RAISE EXCEPTION 'Publication requires exact original committed issuance evidence' USING ERRCODE = '23514'; END IF; SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); @@ -91,19 +93,22 @@ BEGIN RAISE EXCEPTION 'Changed publication actor' USING ERRCODE = '23514'; END IF; SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(input_bytes, source_position); - IF convert_from(parsed, 'UTF8')::JSONB->'intent'->>'canonicalTenantId' <> NEW.tenant_uuid::TEXT - OR convert_from(parsed, 'UTF8')::JSONB->'intent'->>'publishRequestId' <> NEW.publish_request_id THEN + IF convert_from(parsed, 'UTF8')::JSONB->'intent'->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR convert_from(parsed, 'UTF8')::JSONB->'intent'->>'publishRequestId' IS DISTINCT FROM NEW.publish_request_id THEN RAISE EXCEPTION 'Changed publication selection identity' USING ERRCODE = '23514'; END IF; SELECT frame_value, next_position INTO parsed, p FROM account_publication_authorization_read_frame(NEW.binding, p); source_count := convert_from(parsed, 'UTF8')::INTEGER; - IF source_count < 1 OR source_count <> (SELECT count(*) FROM account_selected_publication_sources WHERE operation_id = NEW.operation_id) - OR source_count <> jsonb_array_length(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources') THEN + IF source_count < 1 OR source_count IS DISTINCT FROM + (SELECT count(*)::INTEGER FROM account_selected_publication_sources WHERE operation_id = NEW.operation_id) + OR source_count IS DISTINCT FROM + jsonb_array_length(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources') THEN RAISE EXCEPTION 'Incomplete publication sources' USING ERRCODE = '23514'; END IF; FOR i IN 1..source_count LOOP SELECT frame_value, next_position INTO source_bytes, p FROM account_publication_authorization_read_frame(NEW.binding, p); - IF source_bytes <> decode(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'->>(i - 1), 'base64') THEN + IF source_bytes IS DISTINCT FROM + decode(convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'->>(i - 1), 'base64') THEN RAISE EXCEPTION 'Publication source differs from original complete issuance vector' USING ERRCODE = '23514'; END IF; SELECT frame_value, next_position INTO parsed, source_position FROM account_publication_authorization_read_frame(source_bytes, 1); diff --git a/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql index e1bcb15889..bb9059cf44 100644 --- a/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql +++ b/services/account-service/src/main/resources/db/migration/V96__game_logic_intake_terminal_settlement.sql @@ -28,7 +28,8 @@ BEGIN SELECT * INTO STRICT original FROM account_game_logic_intake_authorizations WHERE operation_id = NEW.operation_id; PERFORM l.source_key FROM account_draft_authorization_source_locks l JOIN account_game_logic_intake_sources s ON s.source_key = l.source_key - WHERE s.operation_id = NEW.operation_id ORDER BY l.source_key FOR UPDATE OF l; + WHERE s.operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(l.source_key) FOR UPDATE OF l; PERFORM operation_id FROM account_game_logic_intake_authorizations WHERE operation_id = NEW.operation_id FOR UPDATE; IF NEW.terminal_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') OR NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') THEN diff --git a/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql index 115b0f57ba..42942353d8 100644 --- a/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql +++ b/services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql @@ -4,7 +4,7 @@ CREATE TABLE account_hosted_terms_disclosure_handoffs ( handoff_id UUID PRIMARY KEY, request_id UUID NOT NULL UNIQUE, kind VARCHAR(32) NOT NULL CHECK (kind IN ('CATALOG', 'ENVIRONMENT_BINDING')), - source_key VARCHAR(512) NOT NULL CHECK (length(source_key) > 0 AND octet_length(source_key) <= 512), + source_key VARCHAR(2048) NOT NULL CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048), predecessor_digest VARCHAR(71) NOT NULL CHECK (predecessor_digest ~ '^sha256:[0-9a-f]{64}$'), candidate_digest VARCHAR(71) NOT NULL CHECK (candidate_digest ~ '^sha256:[0-9a-f]{64}$'), effective_at TIMESTAMPTZ NOT NULL, @@ -34,12 +34,14 @@ CREATE TABLE account_hosted_terms_disclosure_handoffs ( AND result_payload IS NOT NULL AND octet_length(result_payload) > 0 AND result_digest IS NOT NULL AND result_recorded_at IS NOT NULL) - ) + ), + CHECK (result_digest IS NULL OR result_digest = 'sha256:' || encode(sha256(result_payload), 'hex')) ); CREATE TABLE account_hosted_terms_disclosure_sources ( handoff_id UUID NOT NULL REFERENCES account_hosted_terms_disclosure_handoffs(handoff_id), - source_key VARCHAR(512) NOT NULL + source_key VARCHAR(2048) NOT NULL + CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048) REFERENCES account_draft_authorization_source_locks(source_key), source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) > 0), source_evidence_digest VARCHAR(71) NOT NULL @@ -57,6 +59,18 @@ BEGIN RAISE EXCEPTION 'Hosted terms disclosure handoff cannot be deleted' USING ERRCODE = '23514'; END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.status IS DISTINCT FROM 'PREPARED' + OR NEW.dispatch_attempts IS DISTINCT FROM 0 + OR NEW.result_outcome IS NOT NULL + OR NEW.result_payload IS NOT NULL + OR NEW.result_digest IS NOT NULL + OR NEW.result_recorded_at IS NOT NULL THEN + RAISE EXCEPTION 'Hosted terms disclosure handoff must begin in its empty prepared state' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; IF NEW.handoff_id IS DISTINCT FROM OLD.handoff_id OR NEW.request_id IS DISTINCT FROM OLD.request_id OR NEW.kind IS DISTINCT FROM OLD.kind @@ -140,7 +154,7 @@ END; $$; CREATE TRIGGER account_hosted_terms_disclosure_handoff_immutable - BEFORE UPDATE OR DELETE ON account_hosted_terms_disclosure_handoffs + BEFORE INSERT OR UPDATE OR DELETE ON account_hosted_terms_disclosure_handoffs FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_disclosure_handoff_guard(); CREATE TRIGGER account_hosted_terms_disclosure_sources_immutable BEFORE UPDATE OR DELETE ON account_hosted_terms_disclosure_sources diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java index acba68026d..e292ee1d60 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFencePostgresIntegrationTest.java @@ -1413,11 +1413,11 @@ void v2MixedResultsHoldBothSourceTransitionsAndPreserveAppliedBytes() { @Test void forwardMigrationRetainsV1BindingReadbackAndFlywayChecksumsExactly() { - // Seed the retained pre-owner-fence row with an ACCOUNT-only source vector at V75, then - // advance through the required-owner fence at V76 - // explicitly before using the current runtime repository against this historical fixture. + // Seed the retained pre-owner-fence row at V75 with an ACCOUNT-only source vector. This + // historical account uses the V75 schema-level UUID insert path; current AccountRepository + // initialization depends on restriction-birth tables introduced later at V81. Context context = context("75"); - DraftAuthorizationFenceBinding base = binding(context); + DraftAuthorizationFenceBinding base = binding(context, seedHistoricalV75Account(context)); SourceEvidence legacy512 = new SourceEvidence( SourceKind.ISSUER, "x".repeat(505), "3", "5", "stream/legacy512", "2", new byte[] {9}); @@ -1706,6 +1706,41 @@ private static SourceEvidence issuerSource(String scopeId) { return new SourceEvidence(SourceKind.ISSUER, scopeId, null, "5", null, null, new byte[] {7}); } + private UUID seedHistoricalV75Account(Context context) { + String suffix = UUID.randomUUID().toString(); + UUID expectedUuid = UUID.randomUUID(); + return tx( + context, + () -> { + var inserted = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "INSERT INTO accounts (username, email, password_hash, role, " + + "email_verified, login_auth_modes, lifecycle_state, account_uuid, " + + "account_uuid_provenance) " + + "VALUES (?, ?, ?, 'player', FALSE, 'PASSWORD,EMAIL_OTP', 'active', " + + "?, 'ACCOUNT_DATABASE_INSERT') " + + "RETURNING id, account_uuid, account_uuid_provenance, " + + "account_uuid_source_numeric_id, " + + "account_repository_insert_transaction_id", + "draft-" + suffix, + suffix + "@example.test", + "synthetic-verifier", + expectedUuid), + "Expected V75 historical Account insert readback"); + Long sourceNumericId = inserted.get("account_uuid_source_numeric_id", Long.class); + assertThat(inserted.get("id", Long.class)).isPositive(); + assertThat(inserted.get("account_uuid", UUID.class)).isEqualTo(expectedUuid); + assertThat(inserted.get("account_uuid_provenance", String.class)) + .isEqualTo("ACCOUNT_DATABASE_INSERT"); + assertThat(sourceNumericId).isEqualTo(inserted.get("id", Long.class)); + assertThat(inserted.get("account_repository_insert_transaction_id", Long.class)).isNull(); + return expectedUuid; + }); + } + private DraftAuthorizationFenceBinding binding(Context context) { UUID account = tx( @@ -1718,6 +1753,10 @@ private DraftAuthorizationFenceBinding binding(Context context) { row.setPasswordHash("synthetic-verifier"); return new AccountRepository(context.dsl()).save(row).getAccountUuid(); }); + return binding(context, account); + } + + private DraftAuthorizationFenceBinding binding(Context context, UUID account) { SourceEvidence source = new SourceEvidence( SourceKind.ACCOUNT, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..6781d57aec --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java @@ -0,0 +1,820 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.HashSet; +import java.util.List; +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.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private final Set schemas = new HashSet<>(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @AfterEach + void dropTestOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.matches("account_start_session_authorization_[a-f0-9]{32}")) { + throw new IllegalStateException("Refusing to dispose an unowned PostgreSQL schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + schemas.clear(); + } + + @Test + void realPostgresCreateRetryAndRedemptionRetainTheOriginalAuthorityRecord() { + Context context = context(); + IssuanceCandidate candidate = candidate(tuple()); + assertThat(candidate.issuanceFence()) + .isNotEqualTo(Long.parseLong(candidate.bundleReference().sourceFence())); + + var created = context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + IssuanceCandidate differentOutput = withDifferentOutputs(candidate); + var duplicate = + context.inTransaction(() -> context.repository.createOrReadExact(differentOutput)); + + assertThat(created.created()).isTrue(); + assertThat(duplicate.created()).isFalse(); + assertThat(duplicate.issuance().issuanceOperationId()) + .isEqualTo(candidate.issuanceOperationId()); + assertThat(duplicate.issuance().encryptedResponseEnvelope()) + .containsExactly(candidate.encryptedResponseEnvelope()); + assertThat(duplicate.issuance().bundleReference()).isEqualTo(candidate.bundleReference()); + var persistedBeforeRedemption = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(persistedBeforeRedemption.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.ISSUED); + + RedemptionRequest request = redemption(candidate, OWNER_ATTEMPT_ID, 11L); + var redeemed = context.inTransaction(() -> context.repository.redeemExact(request)); + var replay = context.inTransaction(() -> context.repository.redeemExact(request)); + assertThat(redeemed.replay()).isFalse(); + assertThat(replay.replay()).isTrue(); + assertThat(replay.authorityEvidenceBundle()) + .containsExactly(candidate.authorityEvidenceBundle()); + var retainedAfterRedemption = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(retainedAfterRedemption.bundleReference()).isEqualTo(candidate.bundleReference()); + assertThat(retainedAfterRedemption.bundleReference().linearization()).isEqualTo("123456789"); + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET bundle_linearization = ? WHERE control_plane_request_id = ?", + "123456788", + REQUEST_ID))) + .isInstanceOf(DataAccessException.class); + assertThat( + context.inTransaction( + () -> + context + .repository + .findByControlPlaneRequestId(REQUEST_ID) + .orElseThrow() + .status())) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + } + + @Test + void realPostgresAcceptsCanonicalNfcRequestIdAt128Utf8BytesAndRejectsOversizeBeforeInsert() { + Context context = context(); + String boundedRequestId = "é".repeat(64); + StartSessionPreAuthorizationReservationTuple boundaryTuple = + tuple(boundedRequestId, "128-byte NFC request ID boundary"); + IssuanceCandidate candidate = candidate(boundaryTuple, boundedRequestId); + + var created = context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + var retry = context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + assertThat(created.created()).isTrue(); + assertThat(retry.created()).isFalse(); + assertThat(retry.issuance().controlPlaneRequestId()).isEqualTo(boundedRequestId); + assertThat( + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(boundedRequestId))) + .isPresent(); + + String oversizedRequestId = "é".repeat(65); + String malformedTupleJson = + boundaryTuple + .canonicalJson() + .replace( + "\"requestId\":\"" + boundedRequestId + "\"", + "\"requestId\":\"" + oversizedRequestId + "\""); + assertThat(malformedTupleJson).contains(oversizedRequestId); + IssuanceCandidate boundaryCandidate = candidate(boundaryTuple, boundedRequestId); + IssuanceCandidate oversized = + new IssuanceCandidate( + boundedRequestId, + bytes(malformedTupleJson), + boundaryTuple.mutationDigest(), + boundaryCandidate.issuanceWorkloadUri(), + boundaryCandidate.reservationOwnerId(), + boundaryCandidate.reservationClaimFence(), + boundaryCandidate.issuanceOperationId(), + boundaryCandidate.issuanceFence(), + boundaryCandidate.bundleReference(), + boundaryCandidate.authorityEvidenceBundle(), + boundaryCandidate.authorizationReferenceFingerprint(), + boundaryCandidate.encryptedResponseEnvelope(), + boundaryCandidate.issuedAt(), + boundaryCandidate.referenceExpiresAt(), + boundaryCandidate.responseEnvelopeExpiresAt()); + int before = context.countRows(); + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.createOrReadExact(oversized))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(context.countRows()).isEqualTo(before); + } + + @Test + void realPostgresAcceptsSharedRaw64DigestAndRejectsPrefixedMalformedOrChangedDigests() { + Context context = context(); + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + IssuanceCandidate canonical = candidate(tuple); + + assertThat(canonical.mutationDigest()).matches("[0-9a-f]{64}"); + assertThat(canonical.mutationDigest()).doesNotStartWith("sha256:"); + var created = context.inTransaction(() -> context.repository.createOrReadExact(canonical)); + assertThat(created.created()).isTrue(); + assertThat(created.issuance().mutationDigest()).isEqualTo(tuple.mutationDigest()); + + String digest = canonical.mutationDigest(); + String changedDigest = (digest.charAt(0) == '0' ? "1" : "0") + digest.substring(1); + for (String invalidDigest : new String[] {"sha256:" + digest, "not-a-digest", changedDigest}) { + IssuanceCandidate invalid = + candidate( + canonical.controlPlaneRequestId(), canonical.preAuthorizationTuple(), invalidDigest); + int rowsBeforeInvalidDigest = context.countRows(); + + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.createOrReadExact(invalid))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(context.countRows()).isEqualTo(rowsBeforeInvalidDigest); + } + } + + @Test + void realPostgresFingerprintConstraintAllowsMaximumKeyIdAndRejectsDot() { + Context context = context(); + IssuanceCandidate maximumKeyId = + withFingerprint( + candidate(tuple()), + "arfp/v1/" + "k".repeat(64) + "/" + "a".repeat(64), + ISSUANCE_OPERATION_ID); + + assertThat(maximumKeyId.authorizationReferenceFingerprint()).hasSize(137); + assertThat( + context + .inTransaction(() -> context.repository.createOrReadExact(maximumKeyId)) + .created()) + .isTrue(); + assertThat( + context + .inTransaction( + () -> + context.repository.redeemExact( + redemption(maximumKeyId, OWNER_ATTEMPT_ID, 11L))) + .replay()) + .isFalse(); + + String dottedRequestId = REQUEST_ID + "-dot-key"; + StartSessionPreAuthorizationReservationTuple dottedTuple = + tuple(dottedRequestId, "invalid fingerprint key ID database constraint"); + IssuanceCandidate dottedKeyId = + withFingerprint( + candidate(dottedTuple, dottedRequestId), + "arfp/v1/key.with.dot/" + "b".repeat(64), + UUID.randomUUID()); + + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "INSERT INTO account_start_session_operator_authorizations " + + "(control_plane_request_id, pre_authorization_tuple, " + + "mutation_digest, issuance_workload_uri, reservation_owner_id, " + + "reservation_claim_fence, " + + "issuance_operation_id, issuance_fence, bundle_version, " + + "bundle_source_version, bundle_source_fence, " + + "bundle_linearization, authority_evidence_bundle, " + + "authorization_reference_fingerprint, " + + "encrypted_response_envelope, issued_at, reference_expires_at, " + + "response_envelope_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "'ISSUED')", + dottedKeyId.controlPlaneRequestId(), + dottedKeyId.preAuthorizationTuple(), + dottedKeyId.mutationDigest(), + dottedKeyId.issuanceWorkloadUri(), + dottedKeyId.reservationOwnerId(), + dottedKeyId.reservationClaimFence(), + dottedKeyId.issuanceOperationId(), + dottedKeyId.issuanceFence(), + dottedKeyId.bundleReference().bundleVersion(), + dottedKeyId.bundleReference().sourceVersion(), + dottedKeyId.bundleReference().sourceFence(), + dottedKeyId.bundleReference().linearization(), + dottedKeyId.authorityEvidenceBundle(), + dottedKeyId.authorizationReferenceFingerprint(), + dottedKeyId.encryptedResponseEnvelope(), + OffsetDateTime.ofInstant(dottedKeyId.issuedAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant( + dottedKeyId.referenceExpiresAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant( + dottedKeyId.responseEnvelopeExpiresAt(), ZoneOffset.UTC)))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(context.countRows()).isEqualTo(1); + } + + @Test + void concurrentExactIssuanceRetriesReturnOneOriginalOutput() throws Exception { + Context context = context(); + IssuanceCandidate firstCandidate = candidate(tuple()); + IssuanceCandidate secondCandidate = withDifferentOutputs(firstCandidate); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to race exact issuance retry"); + } + return context.inTransaction( + () -> context.repository.createOrReadExact(firstCandidate)); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to race exact issuance retry"); + } + return context.inTransaction( + () -> context.repository.createOrReadExact(secondCandidate)); + }); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var firstResult = first.get(10, TimeUnit.SECONDS); + var secondResult = second.get(10, TimeUnit.SECONDS); + + assertThat( + List.of(firstResult, secondResult).stream() + .filter( + AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult + ::created) + .toList()) + .hasSize(1); + assertThat(firstResult.issuance().issuanceOperationId()) + .isEqualTo(secondResult.issuance().issuanceOperationId()); + assertThat(firstResult.issuance().encryptedResponseEnvelope()) + .containsExactly(secondResult.issuance().encryptedResponseEnvelope()); + assertThat(firstResult.issuance().issuanceOperationId()) + .isIn(firstCandidate.issuanceOperationId(), secondCandidate.issuanceOperationId()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void changedTupleOrReservationBindingConflictsAndMalformedTupleNeverWrites() { + Context context = context(); + IssuanceCandidate candidate = candidate(tuple()); + context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + StartSessionPreAuthorizationReservationTuple changedTuple = tuple("changed audit reason"); + IssuanceCandidate changedTupleCandidate = + copyCandidate( + candidate, + canonicalBytes(changedTuple), + changedTuple.mutationDigest(), + RESERVATION_OWNER_ID, + candidate.reservationClaimFence()); + IssuanceCandidate changedClaim = + copyCandidate( + candidate, + candidate.preAuthorizationTuple(), + candidate.mutationDigest(), + RESERVATION_OWNER_ID, + candidate.reservationClaimFence() + 1L); + + assertThatThrownBy( + () -> + context.inTransaction( + () -> context.repository.createOrReadExact(changedTupleCandidate))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.createOrReadExact(changedClaim))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + + int beforeMalformed = context.countRows(); + IssuanceCandidate malformed = + copyCandidate( + candidate, + bytes("{malformed"), + candidate.mutationDigest(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence()); + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.createOrReadExact(malformed))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(context.countRows()).isEqualTo(beforeMalformed); + } + + @Test + void twoConcurrentDifferentOwnerAttemptsCanConsumeOnlyOneReference() throws Exception { + Context context = context(); + IssuanceCandidate candidate = candidate(tuple()); + context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> raceRedemption(context, candidate, ready, start, 12L)); + Future second = + executor.submit(() -> raceRedemption(context, candidate, ready, start, 13L)); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + Object firstResult = first.get(10, TimeUnit.SECONDS); + Object secondResult = second.get(10, TimeUnit.SECONDS); + List results = List.of(firstResult, secondResult); + assertThat( + results.stream() + .filter( + AccountStartSessionOperatorAuthorizationRepository.RedemptionResult.class + ::isInstance) + .toList()) + .hasSize(1); + assertThat(results.stream().filter(IllegalStateException.class::isInstance).toList()) + .hasSize(1); + var retained = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(retained.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + assertThat(retained.redemptionOwnerAttemptId()) + .isIn( + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"), + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef8")); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void expiredReferenceCannotBeConsumedAndSqlGuardsRetainEvidence() { + Context context = context(); + IssuanceCandidate candidate = candidate(tuple()); + context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + RedemptionRequest expired = + new RedemptionRequest( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.authorizationReferenceFingerprint(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + OWNER_URI, + OWNER_ATTEMPT_ID, + 11L, + candidate.authorityEvidenceBundle(), + candidate.referenceExpiresAt()); + assertThatThrownBy(() -> context.inTransaction(() -> context.repository.redeemExact(expired))) + .isInstanceOf( + AccountStartSessionOperatorAuthorizationRepository.ReferenceExpiredException.class); + + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET authority_evidence_bundle = ? WHERE control_plane_request_id = ?", + bytes("rewritten"), + REQUEST_ID))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "DELETE FROM account_start_session_operator_authorizations " + + "WHERE control_plane_request_id = ?", + REQUEST_ID))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "TRUNCATE account_start_session_operator_authorizations"))) + .isInstanceOf(DataAccessException.class); + + var retained = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(retained.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.ISSUED); + assertThat(retained.authorityEvidenceBundle()) + .containsExactly(candidate.authorityEvidenceBundle()); + } + + private Context context() { + String schema = + "account_start_session_authorization_" + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("126") + .load() + .migrate(); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DSLContext adminDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context( + transactionDsl, + adminDsl, + transaction, + new AccountStartSessionOperatorAuthorizationRepository(transactionDsl)); + } + + private static Object raceRedemption( + Context context, + IssuanceCandidate candidate, + CountDownLatch ready, + CountDownLatch start, + long ownerFence) { + ready.countDown(); + try { + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to race redemption"); + } + UUID attemptId = + ownerFence == 12L + ? UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7") + : UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef8"); + return context.inTransaction( + () -> context.repository.redeemExact(redemption(candidate, attemptId, ownerFence))); + } catch (IllegalStateException conflictOrUnavailable) { + return conflictOrUnavailable; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return new IllegalStateException("Interrupted while waiting to race redemption", interrupted); + } + } + + private static IssuanceCandidate withDifferentOutputs(IssuanceCandidate original) { + UUID operationId = UUID.randomUUID(); + BundleReference reference = + bundleReference(Long.parseLong(original.bundleReference().sourceFence()) + 1L); + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(original.preAuthorizationTuple(), StandardCharsets.UTF_8)); + Instant expiresAt = original.referenceExpiresAt().plusSeconds(1); + long issuanceFence = original.issuanceFence() + 1L; + return new IssuanceCandidate( + original.controlPlaneRequestId(), + original.preAuthorizationTuple(), + original.mutationDigest(), + original.issuanceWorkloadUri(), + original.reservationOwnerId(), + original.reservationClaimFence(), + operationId, + issuanceFence, + reference, + authorityBundle(tuple, operationId, issuanceFence, expiresAt, reference), + "arfp/v1/key-2/" + "b".repeat(64), + bytes("different encrypted response"), + original.issuedAt().plusSeconds(1), + expiresAt, + original.responseEnvelopeExpiresAt().plusSeconds(1)); + } + + private static IssuanceCandidate withFingerprint( + IssuanceCandidate original, String fingerprint, UUID operationId) { + return new IssuanceCandidate( + original.controlPlaneRequestId(), + original.preAuthorizationTuple(), + original.mutationDigest(), + original.issuanceWorkloadUri(), + original.reservationOwnerId(), + original.reservationClaimFence(), + operationId, + original.issuanceFence(), + original.bundleReference(), + original.authorityEvidenceBundle(), + fingerprint, + original.encryptedResponseEnvelope(), + original.issuedAt(), + original.referenceExpiresAt(), + original.responseEnvelopeExpiresAt()); + } + + private static IssuanceCandidate copyCandidate( + IssuanceCandidate original, + byte[] tuple, + String digest, + UUID reservationOwner, + long reservationFence) { + return new IssuanceCandidate( + original.controlPlaneRequestId(), + tuple, + digest, + original.issuanceWorkloadUri(), + reservationOwner, + reservationFence, + original.issuanceOperationId(), + original.issuanceFence(), + original.bundleReference(), + original.authorityEvidenceBundle(), + original.authorizationReferenceFingerprint(), + original.encryptedResponseEnvelope(), + original.issuedAt(), + original.referenceExpiresAt(), + original.responseEnvelopeExpiresAt()); + } + + private static IssuanceCandidate candidate(StartSessionPreAuthorizationReservationTuple tuple) { + return candidate(tuple, REQUEST_ID); + } + + private static IssuanceCandidate candidate( + StartSessionPreAuthorizationReservationTuple tuple, String requestId) { + return candidate(requestId, canonicalBytes(tuple), tuple.mutationDigest()); + } + + private static IssuanceCandidate candidate(String requestId, byte[] tupleBytes, String digest) { + return new IssuanceCandidate( + requestId, + tupleBytes, + digest, + ISSUER_URI, + RESERVATION_OWNER_ID, + 3L, + ISSUANCE_OPERATION_ID, + 7L, + bundleReference(31L), + authorityBundle( + tupleFromBytes(tupleBytes), + ISSUANCE_OPERATION_ID, + 7L, + Instant.parse("2026-10-09T00:03:00Z"), + bundleReference(31L)), + "arfp/v1/key-1/" + "a".repeat(64), + bytes("encrypted-original-response-envelope"), + Instant.parse("2026-10-09T00:00:00Z"), + Instant.parse("2026-10-09T00:03:00Z"), + Instant.parse("2026-10-09T00:03:30Z")); + } + + private static RedemptionRequest redemption( + IssuanceCandidate candidate, UUID ownerAttemptId, long ownerFence) { + return new RedemptionRequest( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.authorizationReferenceFingerprint(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + OWNER_URI, + ownerAttemptId, + ownerFence, + candidate.authorityEvidenceBundle(), + Instant.parse("2026-10-09T00:00:01Z")); + } + + private static StartSessionPreAuthorizationReservationTuple tuple() { + return tuple("StartSession Account authorization repository integration test"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String auditReason) { + return tuple(REQUEST_ID, auditReason); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + String controlPlaneRequestId, String auditReason) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + return StartSessionPreAuthorizationReservationTuple.createHuman( + controlPlaneRequestId, ACTOR_ID, action); + } + + private static byte[] canonicalBytes(StartSessionPreAuthorizationReservationTuple tuple) { + return tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static BundleReference bundleReference(long sourceFence) { + return new BundleReference( + "authorityEvidenceBundle/v1", "12", Long.toString(sourceFence), "123456789"); + } + + private static StartSessionPreAuthorizationReservationTuple tupleFromBytes(byte[] tupleBytes) { + return StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(tupleBytes, StandardCharsets.UTF_8)); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, + UUID operationId, + long issuanceFence, + Instant expiresAt, + BundleReference reference) { + String tenantId = tuple.action().scope().tenantId().toString(); + String actorId = tuple.actor().accountId().toString(); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 1L, + "tenantAuthorityGeneration", Map.of(tenantId, 1L), + "membershipAuthorityGeneration", Map.of(tenantId, 1L), + "privateRealmGrantVersions", List.of()); + Map bundle = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + reference.sourceVersion(), + "projectionStatus", + "CURRENT", + "evaluatedAt", + Instant.parse("2026-10-09T00:00:00Z").toString(), + "expiresAt", + expiresAt.toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", operationId.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", authorityTuple, + "membershipVersion", Map.of(tenantId, 2L), + "issuanceFence", Long.toString(issuanceFence), + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actorId, + "controlUiTokenJti", + UUID.fromString("2e19f788-10d2-4f33-aed6-9a46db136dcc").toString(), + "role", + "tenantAdmin", + "accountGeneration", + "1", + "tenantGeneration", + "1")); + return AccountControlUiAuthority.canonical(bundle); + } + + private static final UUID TENANT_ID = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); + private static final UUID ACTOR_ID = UUID.fromString("d888ddc4-4a62-4b25-9bab-c4f94860c2ca"); + private static final String REQUEST_ID = + "start-session/operator/2355f292-ab9c-458c-8d52-aef18b9254e8"; + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("ca1b63bf-f09f-4a55-96bf-a1fd2e22349e"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("37b1f37d-05d2-4aab-8ed9-c01acbf6606e"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"); + private static final String ISSUER_URI = "spiffe://firemud/ns/prod/sa/logging-admin-service"; + private static final String OWNER_URI = "spiffe://firemud/ns/prod/sa/game-session-service"; + + private static final class Context { + private final DSLContext transactionDsl; + private final DSLContext adminDsl; + private final TransactionTemplate transaction; + private final AccountStartSessionOperatorAuthorizationRepository repository; + + Context( + DSLContext transactionDsl, + DSLContext adminDsl, + TransactionTemplate transaction, + AccountStartSessionOperatorAuthorizationRepository repository) { + this.transactionDsl = transactionDsl; + this.adminDsl = adminDsl; + this.transaction = transaction; + this.repository = repository; + } + + T inTransaction(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + + void inTransactionWithoutResult(Runnable action) { + transaction.executeWithoutResult(ignored -> action.run()); + } + + int countRows() { + var row = + Objects.requireNonNull( + adminDsl.fetchOne( + "SELECT count(*) FROM account_start_session_operator_authorizations"), + "COUNT query must return a row"); + return Objects.requireNonNull(row.get(0, Integer.class), "COUNT query must return a value"); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java index f3e66fc765..6b8d15fc4e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -301,6 +301,22 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() assertThat(exactRetry.canonicalBytes()).isEqualTo(firstCapture.canonicalBytes()); assertThat(exactRetry.bundleReference()).isEqualTo(firstCapture.bundleReference()); + var lookupOnlyRetry = + actors.withCurrentCommitted( + actor.accountId(), + f.tenant, + retained.jti, + environment, + current -> + captureRepository.lockReadExactCurrent( + current, + tuple, + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER, + reservationOwnerId, + reservationClaimFence)); + assertThat(lookupOnlyRetry.sameStoredValue(firstCapture)).isTrue(); + assertThat(lookupOnlyRetry.bundleReference()).isEqualTo(firstCapture.bundleReference()); + finalReadback = actors.withCurrentCommitted( actor.accountId(), @@ -378,6 +394,27 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() .isInstanceOf(IllegalStateException.class) .hasMessage("Account StartSession source capture is unavailable"); + String missingRequestId = "start-session-capture-missing-" + UUID.randomUUID(); + var missingTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + missingRequestId, actor.accountId(), action); + assertThatThrownBy( + () -> + actors.withCurrentCommitted( + actor.accountId(), + f.tenant, + retained.jti, + environment, + current -> + captureRepository.lockReadExactCurrent( + current, + missingTuple, + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER, + reservationOwnerId, + reservationClaimFence))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account StartSession source capture is unavailable"); + var unchanged = actors.withCurrentCommitted( actor.accountId(), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java new file mode 100644 index 0000000000..fbdffb7bb8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java @@ -0,0 +1,478 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class StartSessionReservationEvidenceClientTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final String REQUEST_ID = "start-session-βeta"; + private static final UUID ACTOR_ID = UUID.fromString("1ea6eb2c-e211-4f4f-a812-14909b9a72b8"); + private static final UUID TENANT_ID = UUID.fromString("5212125e-7d89-4c51-b3a0-bef10e04ccda"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("b2a1a560-5e62-4f61-98bf-dae49ba37a38"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("44997fae-a4c4-45de-8d4f-5e75ad233f0f"); + private static final UUID RECOVERY_OWNER_ID = + UUID.fromString("c8190808-e325-4d8a-9702-fbf5a53d436d"); + private static final Clock CLOCK = + Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC); + private static final String LOGGING_ADMIN_TARGET = "logging-admin.internal:6565"; + + @Test + void repeatedInProcessReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + List requests = new ArrayList<>(); + try (InProcessFixture fixture = + inProcessFixture( + request -> { + requests.add(request); + assertThat(io.grpc.Context.current().getDeadline()).isNotNull(); + return validResponse(request, tuple.mutationDigest()); + })) { + StartSessionReservationEvidenceClient client = client(fixture.stub()); + + ReadCurrentClaimEvidenceResponse issueFirst = + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE); + ReadCurrentClaimEvidenceResponse issueRetry = + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE); + ReadCurrentClaimEvidenceResponse recoveryFirst = + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RECOVERY_OWNER_ID, + 3L, + StartSessionReservationEvidenceClient.Purpose.RECOVER); + ReadCurrentClaimEvidenceResponse recoveryRetry = + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RECOVERY_OWNER_ID, + 3L, + StartSessionReservationEvidenceClient.Purpose.RECOVER); + + assertThat(issueFirst).isEqualTo(issueRetry); + assertThat(recoveryFirst).isEqualTo(recoveryRetry); + assertThat(requests).hasSize(4); + assertThat(requests) + .allSatisfy( + request -> { + assertThat(request.getControlPlaneRequestId()).isEqualTo(REQUEST_ID); + assertThat(request.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(request.getReservationOwnerId()) + .isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(request.getReservationClaimFence()).isEqualTo(1L); + }); + assertThat(requests.get(0).getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(requests.get(1)).isEqualTo(requests.get(0)); + assertThat(requests.get(2).getClaimOwnerId()).isEqualTo(RECOVERY_OWNER_ID.toString()); + assertThat(requests.get(2).getClaimFence()).isEqualTo(3L); + assertThat(requests.get(2).getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER); + assertThat(requests.get(3)).isEqualTo(requests.get(2)); + } + } + + @Test + void rejectsEveryResponseIdentityFieldUnknownFieldsAndStaleTimes() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + AtomicReference response = new AtomicReference<>(); + try (InProcessFixture fixture = inProcessFixture(request -> response.get())) { + StartSessionReservationEvidenceClient client = client(fixture.stub()); + ReadCurrentClaimEvidenceResponse valid = + validResponse( + request(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE), + tuple.mutationDigest()); + List invalid = + List.of( + valid.toBuilder().setControlPlaneRequestId(UUID.randomUUID().toString()).build(), + valid.toBuilder() + .setPreAuthorizationTupleJson(ByteString.copyFromUtf8("different tuple")) + .build(), + valid.toBuilder().setMutationDigest("sha256:" + "0".repeat(64)).build(), + valid.toBuilder().setReservationOwnerId(UUID.randomUUID().toString()).build(), + valid.toBuilder().setReservationClaimFence(2L).build(), + valid.toBuilder().setClaimOwnerId(UUID.randomUUID().toString()).build(), + valid.toBuilder().setClaimFence(2L).build(), + valid.toBuilder() + .setPurpose( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER) + .build(), + valid.toBuilder().setObservedAtEpochMillis(0L).build(), + valid.toBuilder().setObservedAtEpochMillis(NOW_EPOCH_MILLIS + 1L).build(), + valid.toBuilder() + .setClaimExpiresAtEpochMillis(valid.getObservedAtEpochMillis()) + .build(), + valid.toBuilder().setClaimExpiresAtEpochMillis(NOW_EPOCH_MILLIS).build(), + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()); + + for (ReadCurrentClaimEvidenceResponse invalidResponse : invalid) { + response.set(invalidResponse); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or mismatched"); + } + } + } + + @Test + void invalidInputIsRejectedBeforeAnyRpc() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + AtomicInteger calls = new AtomicInteger(); + try (InProcessFixture fixture = + inProcessFixture( + request -> { + calls.incrementAndGet(); + return validResponse(request, tuple.mutationDigest()); + })) { + StartSessionReservationEvidenceClient client = client(fixture.stub()); + + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + null, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 0L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RECOVERY_OWNER_ID, + 3L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.RECOVER)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(calls).hasValue(0); + } + } + + @Test + void propagatesUnavailableAndStaleOwnerStatusesWithoutInterpretingThemAsEvidence() + throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + AtomicReference status = new AtomicReference<>(Status.UNAVAILABLE); + try (InProcessFixture fixture = + inProcessFixture( + request -> { + throw status.get().asRuntimeException(); + })) { + StartSessionReservationEvidenceClient client = client(fixture.stub()); + + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + + status.set(Status.FAILED_PRECONDITION); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + } + + @Test + void usesConfiguredLoggingEndpointTlsChannelAndStubCustomizer(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService(LOGGING_ADMIN_TARGET); + CommonGrpcClientProperties tls = tlsProperties(directory); + GrpcChannelFactory channelFactory = spy(new GrpcChannelFactory()); + AtomicInteger customizerCalls = new AtomicInteger(); + BlockingGrpcStubCustomizer customizer = + new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T stub) { + customizerCalls.incrementAndGet(); + return stub; + } + }; + StartSessionReservationEvidenceClient client = + new StartSessionReservationEvidenceClient( + endpoints, tls, channelFactory, customizer, CLOCK); + + try { + client.init(); + + verify(channelFactory) + .buildChannel( + eq(LOGGING_ADMIN_TARGET), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + assertThat(customizerCalls).hasValue(1); + } finally { + client.close(); + } + } + + private static StartSessionReservationEvidenceClient client( + StartSessionReservationEvidenceServiceGrpc.StartSessionReservationEvidenceServiceBlockingStub + stub) + throws Exception { + StartSessionReservationClientTestAccess client = newClient(); + client.installStub(stub); + return client.client(); + } + + private static StartSessionReservationClientTestAccess newClient() { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setPlaintext(true); + StartSessionReservationEvidenceClient client = + new StartSessionReservationEvidenceClient( + endpoints, + tls, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + CLOCK); + return new StartSessionReservationClientTestAccess(client); + } + + private static InProcessFixture inProcessFixture(EvidenceHandler handler) throws Exception { + String serverName = InProcessServerBuilder.generateName(); + Server server = + InProcessServerBuilder.forName(serverName) + .directExecutor() + .addService( + new StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceImplBase() { + @Override + public void readCurrentClaimEvidence( + ReadCurrentClaimEvidenceRequest request, + StreamObserver responseObserver) { + try { + responseObserver.onNext(handler.read(request)); + responseObserver.onCompleted(); + } catch (StatusRuntimeException exception) { + responseObserver.onError(exception); + } + } + }) + .build() + .start(); + ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); + return new InProcessFixture(server, channel); + } + + private static ReadCurrentClaimEvidenceRequest request( + StartSessionPreAuthorizationReservationTuple tuple, + StartSessionReservationEvidenceClient.Purpose purpose) { + return ReadCurrentClaimEvidenceRequest.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(1L) + .setClaimOwnerId( + purpose == StartSessionReservationEvidenceClient.Purpose.ISSUE + ? RESERVATION_OWNER_ID.toString() + : RECOVERY_OWNER_ID.toString()) + .setClaimFence(purpose == StartSessionReservationEvidenceClient.Purpose.ISSUE ? 1L : 3L) + .setPurpose(toWirePurpose(purpose)) + .build(); + } + + private static ReadCurrentClaimEvidenceResponse validResponse( + ReadCurrentClaimEvidenceRequest request, String mutationDigest) { + return ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(request.getControlPlaneRequestId()) + .setPreAuthorizationTupleJson(request.getPreAuthorizationTupleJson()) + .setMutationDigest(mutationDigest) + .setReservationOwnerId(request.getReservationOwnerId()) + .setReservationClaimFence(request.getReservationClaimFence()) + .setClaimOwnerId(request.getClaimOwnerId()) + .setClaimFence(request.getClaimFence()) + .setClaimExpiresAtEpochMillis(NOW_EPOCH_MILLIS + 30_000L) + .setObservedAtEpochMillis(NOW_EPOCH_MILLIS - 1_000L) + .setPurpose(request.getPurpose()) + .build(); + } + + private static StartSessionReservationEvidencePurpose toWirePurpose( + StartSessionReservationEvidenceClient.Purpose purpose) { + return switch (purpose) { + case ISSUE -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE; + case RECOVER -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER; + }; + } + + private static StartSessionPreAuthorizationReservationTuple tuple() { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "reservation evidence client test"); + return StartSessionPreAuthorizationReservationTuple.createHuman(REQUEST_ID, ACTOR_ID, action); + } + + private static CommonGrpcClientProperties tlsProperties(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(copyCertificateResource("dev-cert.pem", directory).toString()); + tls.setPrivateKey(copyCertificateResource("dev-key.pem", directory).toString()); + tls.setCaCert(copyCertificateResource("dev-ca.pem", directory).toString()); + return tls; + } + + private static Path copyCertificateResource(String fileName, Path directory) throws Exception { + Path destination = directory.resolve(fileName); + try (InputStream source = + StartSessionReservationEvidenceClientTest.class.getResourceAsStream("/certs/" + fileName)) { + if (source == null) { + throw new IllegalStateException("Missing shared TLS test resource: " + fileName); + } + Files.copy(source, destination); + } + return destination; + } + + @FunctionalInterface + private interface EvidenceHandler { + ReadCurrentClaimEvidenceResponse read(ReadCurrentClaimEvidenceRequest request); + } + + private record InProcessFixture(Server server, ManagedChannel channel) implements AutoCloseable { + private StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + stub() { + return StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel); + } + + @Override + public void close() throws Exception { + channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + private record StartSessionReservationClientTestAccess( + StartSessionReservationEvidenceClient client) { + private void installStub( + StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + stub) + throws Exception { + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java new file mode 100644 index 0000000000..ca2ac65b39 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java @@ -0,0 +1,268 @@ +package unit.net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import java.util.List; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.config.AccountStartSessionOperatorAuthorizationConfiguration; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.Snapshot; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCaptureRepository; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.convert.ApplicationConversionService; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Wiring-only test: the supplied mocks and fixed test key do not prove authority or runtime use. + */ +class AccountStartSessionOperatorAuthorizationConfigurationTest { + private static final String OPT_IN = + "firemud.account.start-session-operator-authorization.enabled"; + private static final String OPERATOR_KEYRING_PATH = + "firemud.account.start-session-operator-authorization.response-envelope.keyring-path"; + private static final String GENERAL_KEYRING_PATH = + "firemud.account.response-envelope.keyring-path"; + private static final String REFERENCE_LIFETIME = + "firemud.account.start-session-operator-authorization.reference-lifetime"; + private static final String RESPONSE_RECOVERY_WINDOW = + "firemud.account.start-session-operator-authorization.response-recovery-window"; + private static final String OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN = + "startSessionOperatorResponseEnvelopeCryptography"; + + @Test + void ownerCompositionIsAbsentWhenTheOptInIsMissingOrFalse() { + contextRunner() + .withUserConfiguration(AccountStartSessionOperatorAuthorizationConfiguration.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(AccountStartSessionOperatorAuthorizationService.class); + assertThat(context) + .doesNotHaveBean(AccountOperatorAuthorizationFingerprintKeyring.class); + assertThat(context).doesNotHaveBean(AccountResponseEnvelopeCryptography.class); + assertThat(context) + .doesNotHaveBean(AccountStartSessionAuthorityCaptureRepository.class); + }); + + contextRunner() + .withUserConfiguration(AccountStartSessionOperatorAuthorizationConfiguration.class) + .withPropertyValues(OPT_IN + "=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(AccountStartSessionOperatorAuthorizationService.class); + assertThat(context) + .doesNotHaveBean(AccountStartSessionAuthorityCaptureRepository.class); + }); + } + + @Test + void explicitOptInFailsClosedWhenOwnerAndKeySourcesAreUnavailable() { + contextRunner() + .withUserConfiguration(AccountStartSessionOperatorAuthorizationConfiguration.class) + .withPropertyValues( + OPT_IN + "=true", + "firemud.grpc.workload-namespace=gameplay", + "firemud.account.start-session-operator-authorization.reference-lifetime=PT2M", + "firemud.account.start-session-operator-authorization.response-recovery-window=PT30S", + "firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention=PT24H", + "firemud.account.start-session-operator-authorization.response-envelope.keyring-path=" + + "/run/secrets/account-operator-response") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void explicitOptInUsesSuppliedCollaboratorsAndQualifiedOperatorCryptography() { + enabledContext() + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .hasSingleBean(AccountStartSessionOperatorAuthorizationService.class); + assertThat(context).hasSingleBean(DSLContext.class); + assertThat(context) + .hasSingleBean(AccountStartSessionAuthorityCaptureRepository.class); + assertThat(context) + .hasSingleBean(AccountOperatorAuthorizationFingerprintKeyring.class); + assertThat(context.getBeansOfType(AccountResponseEnvelopeCryptography.class)) + .hasSize(2) + .containsKeys( + "genericAccountResponseEnvelopeCryptography", + OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN); + assertThat( + ReflectionTestUtils.getField( + context.getBean(AccountStartSessionAuthorityCaptureRepository.class), + "dsl")) + .isSameAs(context.getBean(DSLContext.class)); + + AccountResponseEnvelopeCryptography genericCryptography = + context.getBean( + "genericAccountResponseEnvelopeCryptography", + AccountResponseEnvelopeCryptography.class); + AccountResponseEnvelopeCryptography operatorCryptography = + context.getBean( + OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN, + AccountResponseEnvelopeCryptography.class); + assertThat(operatorCryptography).isNotSameAs(genericCryptography); + assertThat(ReflectionTestUtils.getField(operatorCryptography, "keyring")) + .isNotSameAs(ReflectionTestUtils.getField(genericCryptography, "keyring")); + assertThat( + ReflectionTestUtils.getField( + context.getBean(AccountStartSessionOperatorAuthorizationService.class), + "responseCryptography")) + .isSameAs(operatorCryptography); + }); + } + + @Test + void invalidNamespaceOrUnboundedTimingPreventsOwnerComposition() { + enabledContext("", "PT2M", "PT30S", "/run/test/operator-response", "/run/test/general-response") + .run(context -> assertThat(context).hasFailed()); + + enabledContext( + "gameplay", + "PT6M", + "PT30S", + "/run/test/operator-response", + "/run/test/general-response") + .run(context -> assertThat(context).hasFailed()); + + enabledContext( + "gameplay", "PT2M", "PT2M", "/run/test/operator-response", "/run/test/general-response") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void missingOrReusedOperatorResponseMountPreventsOwnerComposition() { + contextRunner() + .withUserConfiguration( + AccountStartSessionOperatorAuthorizationConfiguration.class, + OwnerDependencies.class, + GeneralResponseCryptography.class) + .withPropertyValues( + OPT_IN + "=true", + "firemud.grpc.workload-namespace=gameplay", + REFERENCE_LIFETIME + "=PT2M", + RESPONSE_RECOVERY_WINDOW + "=PT30S", + "firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention=PT24H") + .run(context -> assertThat(context).hasFailed()); + + enabledContext( + "gameplay", "PT2M", "PT30S", "/run/test/shared-response", "/run/test/shared-response") + .run(context -> assertThat(context).hasFailed()); + } + + private static ApplicationContextRunner enabledContext() { + return enabledContext( + "gameplay", "PT2M", "PT30S", "/run/test/operator-response", "/run/test/general-response"); + } + + private static ApplicationContextRunner enabledContext( + String namespace, + String referenceLifetime, + String responseRecoveryWindow, + String operatorKeyringPath, + String generalKeyringPath) { + return contextRunner() + .withUserConfiguration( + AccountStartSessionOperatorAuthorizationConfiguration.class, + OwnerDependencies.class, + GeneralResponseCryptography.class) + .withPropertyValues( + OPT_IN + "=true", + "firemud.grpc.workload-namespace=" + namespace, + REFERENCE_LIFETIME + "=" + referenceLifetime, + RESPONSE_RECOVERY_WINDOW + "=" + responseRecoveryWindow, + "firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention=PT24H", + OPERATOR_KEYRING_PATH + "=" + operatorKeyringPath, + GENERAL_KEYRING_PATH + "=" + generalKeyringPath); + } + + private static ApplicationContextRunner contextRunner() { + return new ApplicationContextRunner() + .withInitializer( + context -> + context.getBeanFactory().setConversionService(new ApplicationConversionService())); + } + + @TestConfiguration(proxyBeanMethods = false) + static class OwnerDependencies { + @Bean + AccountControlUiActorService actors() { + return mock(AccountControlUiActorService.class); + } + + @Bean + AccountControlUiIssuanceRepository issuanceOperations() { + return mock(AccountControlUiIssuanceRepository.class); + } + + @Bean + DSLContext accountDsl() { + return mock(DSLContext.class); + } + + @Bean + StartSessionReservationEvidenceClient reservationEvidence() { + return mock(StartSessionReservationEvidenceClient.class); + } + + @Bean + AccountStartSessionOperatorAuthorizationRepository repository() { + return mock(AccountStartSessionOperatorAuthorizationRepository.class); + } + + @Bean + OwnerKeySource fingerprintOwnerKeySource() { + // Fixed synthetic test bytes; no production or runtime key material is read or provisioned. + return () -> + new Snapshot( + new KeyMaterial("test-active", new SecretKeySpec(new byte[32], "HmacSHA256")), + List.of()); + } + + @Bean + AccountHostedTermsService hostedTerms() { + return mock(AccountHostedTermsService.class); + } + + @Bean + PlatformTransactionManager transactions() { + return mock(PlatformTransactionManager.class); + } + } + + @TestConfiguration(proxyBeanMethods = false) + static class GeneralResponseCryptography { + @Bean + AccountResponseEnvelopeKeyring generalAccountResponseEnvelopeKeyring( + @Value("${firemud.account.response-envelope.keyring-path:}") String keyringPath) { + return new AccountResponseEnvelopeKeyring(keyringPath); + } + + @Bean(name = "genericAccountResponseEnvelopeCryptography") + AccountResponseEnvelopeCryptography genericAccountResponseEnvelopeCryptography( + AccountResponseEnvelopeKeyring generalAccountResponseEnvelopeKeyring) { + return new AccountResponseEnvelopeCryptography(generalAccountResponseEnvelopeKeyring); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java new file mode 100644 index 0000000000..48a2958fa8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java @@ -0,0 +1,880 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.SQLException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockExecuteContext; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountStartSessionOperatorAuthorizationRepositoryTest { + private static final String REQUEST_ID = + "start-session/operator/2355f292-ab9c-458c-8d52-aef18b9254e8"; + private static final UUID ACTOR_ID = UUID.fromString("d888ddc4-4a62-4b25-9bab-c4f94860c2ca"); + private static final UUID TENANT_ID = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("ca1b63bf-f09f-4a55-96bf-a1fd2e22349e"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("37b1f37d-05d2-4aab-8ed9-c01acbf6606e"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"); + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final String ISSUER_URI = "spiffe://firemud/ns/prod/sa/logging-admin-service"; + private static final String OWNER_URI = "spiffe://firemud/ns/prod/sa/game-session-service"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactDuplicateReturnsOriginalOutputAndNeverReplacesIt() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate first = candidate(tuple()); + UUID changedOperationId = UUID.randomUUID(); + long changedIssuanceFence = first.issuanceFence() + 1L; + long changedSourceFence = Long.parseLong(first.bundleReference().sourceFence()) + 1L; + BundleReference changedReference = bundleReference(changedSourceFence); + IssuanceCandidate changedOutput = + new IssuanceCandidate( + first.controlPlaneRequestId(), + first.preAuthorizationTuple(), + first.mutationDigest(), + first.issuanceWorkloadUri(), + first.reservationOwnerId(), + first.reservationClaimFence(), + changedOperationId, + changedIssuanceFence, + changedReference, + authorityBundle( + tuple(), + changedOperationId, + changedIssuanceFence, + first.referenceExpiresAt().plusSeconds(1), + changedReference), + fingerprint("e"), + bytes("different encrypted envelope"), + first.issuedAt().plusSeconds(1), + first.referenceExpiresAt().plusSeconds(1), + first.responseEnvelopeExpiresAt().plusSeconds(1)); + + AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult created = + inTransaction(() -> repository.createOrReadExact(first)); + AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult duplicate = + inTransaction(() -> repository.createOrReadExact(changedOutput)); + + assertThat(created.created()).isTrue(); + assertThat(duplicate.created()).isFalse(); + assertThat(first.issuanceFence()) + .isNotEqualTo(Long.parseLong(first.bundleReference().sourceFence())); + assertThat(duplicate.issuance().issuanceOperationId()).isEqualTo(ISSUANCE_OPERATION_ID); + assertThat(duplicate.issuance().issuanceFence()).isEqualTo(4L); + assertThat(duplicate.issuance().bundleReference()).isEqualTo(first.bundleReference()); + assertThat(duplicate.issuance().authorizationReferenceFingerprint()) + .isEqualTo(fingerprint("a")); + assertThat(duplicate.issuance().authorityEvidenceBundle()) + .containsExactly(first.authorityEvidenceBundle()); + assertThat(duplicate.issuance().encryptedResponseEnvelope()) + .containsExactly(bytes("ciphertext-envelope")); + assertThat(store.insertCount.get()).isEqualTo(1); + assertThat(store.lastLockSql).contains("for update"); + + byte[] exposedTuple = duplicate.issuance().preAuthorizationTuple(); + exposedTuple[0] ^= 0x01; + assertThat(duplicate.issuance().preAuthorizationTuple()) + .containsExactly(first.preAuthorizationTuple()); + assertThat(duplicate.issuance().toString()) + .doesNotContain("tuple-v1", "authorityEvidenceBundle/v1", "ciphertext-envelope"); + } + + @Test + void fingerprintKeyIdUsesCanonicalAlphabetAndAllowsMaximumLength() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + String maximumKeyId = "k".repeat(64); + String maximumFingerprint = "arfp/v1/" + maximumKeyId + "/" + "a".repeat(64); + IssuanceCandidate maximumKeyIdCandidate = + withFingerprint(candidate(tuple()), maximumFingerprint); + + assertThat(maximumKeyIdCandidate.authorizationReferenceFingerprint()).hasSize(137); + assertThat(inTransaction(() -> repository.createOrReadExact(maximumKeyIdCandidate)).created()) + .isTrue(); + + int callsBeforeMalformed = store.databaseCallCount.get(); + String dottedFingerprint = "arfp/v1/key.with.dot/" + "a".repeat(64); + IssuanceCandidate dottedKeyIdCandidate = withFingerprint(candidate(tuple()), dottedFingerprint); + assertThatThrownBy( + () -> inTransaction(() -> repository.createOrReadExact(dottedKeyIdCandidate))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("fingerprint is malformed"); + assertThat(store.databaseCallCount.get()).isEqualTo(callsBeforeMalformed); + } + + @Test + void bundleSourceVersionMustMatchWhileSourceFenceRemainsIndependentOfIssuanceFence() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate valid = candidate(tuple()); + IssuanceCandidate mismatchedReference = + new IssuanceCandidate( + valid.controlPlaneRequestId(), + valid.preAuthorizationTuple(), + valid.mutationDigest(), + valid.issuanceWorkloadUri(), + valid.reservationOwnerId(), + valid.reservationClaimFence(), + valid.issuanceOperationId(), + valid.issuanceFence(), + new BundleReference( + valid.bundleReference().bundleVersion(), + "13", + valid.bundleReference().sourceFence(), + valid.bundleReference().linearization()), + valid.authorityEvidenceBundle(), + valid.authorizationReferenceFingerprint(), + valid.encryptedResponseEnvelope(), + valid.issuedAt(), + valid.referenceExpiresAt(), + valid.responseEnvelopeExpiresAt()); + + assertThat(valid.issuanceFence()) + .isNotEqualTo(Long.parseLong(valid.bundleReference().sourceFence())); + assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(mismatchedReference))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bundle reference"); + assertThat(store.databaseCallCount.get()).isZero(); + } + + @Test + void changedCanonicalTupleConflictsWithoutReplacingTheOriginal() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate original = candidate(tuple()); + inTransaction(() -> repository.createOrReadExact(original)); + + StartSessionPreAuthorizationReservationTuple changedTuple = tuple("different reason"); + IssuanceCandidate changedBinding = + new IssuanceCandidate( + original.controlPlaneRequestId(), + canonicalBytes(changedTuple), + changedTuple.mutationDigest(), + original.issuanceWorkloadUri(), + original.reservationOwnerId(), + original.reservationClaimFence(), + UUID.randomUUID(), + original.issuanceFence(), + original.bundleReference(), + original.authorityEvidenceBundle(), + original.authorizationReferenceFingerprint(), + original.encryptedResponseEnvelope(), + original.issuedAt(), + original.referenceExpiresAt(), + original.responseEnvelopeExpiresAt()); + + assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(changedBinding))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + assertThat(store.insertCount.get()).isEqualTo(1); + assertThat(store.row.tuple).containsExactly(original.preAuthorizationTuple()); + } + + @Test + void acceptsSharedRaw64DigestAndRejectsPrefixedMalformedOrChangedDigestsBeforeSql() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + IssuanceCandidate canonical = candidate(tuple); + + assertThat(canonical.mutationDigest()).matches("[0-9a-f]{64}"); + assertThat(canonical.mutationDigest()).doesNotStartWith("sha256:"); + var created = inTransaction(() -> repository.createOrReadExact(canonical)); + assertThat(created.created()).isTrue(); + assertThat(created.issuance().mutationDigest()).isEqualTo(tuple.mutationDigest()); + + String digest = canonical.mutationDigest(); + String changedDigest = (digest.charAt(0) == '0' ? "1" : "0") + digest.substring(1); + for (String invalidDigest : new String[] {"sha256:" + digest, "not-a-digest", changedDigest}) { + IssuanceCandidate invalid = + candidate( + canonical.controlPlaneRequestId(), canonical.preAuthorizationTuple(), invalidDigest); + int callsBeforeInvalidDigest = store.databaseCallCount.get(); + + assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(invalid))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(store.databaseCallCount.get()).isEqualTo(callsBeforeInvalidDigest); + } + assertThat(store.insertCount.get()).isEqualTo(1); + } + + @Test + void canonicalNonUuidRequestIdRetriesAtExactMultibyteUtf8Bound() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + String boundedRequestId = "é".repeat(64); + StartSessionPreAuthorizationReservationTuple boundaryTuple = + tuple(boundedRequestId, "128-byte NFC request ID boundary"); + IssuanceCandidate candidate = candidate(boundaryTuple, boundedRequestId); + + AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult created = + inTransaction(() -> repository.createOrReadExact(candidate)); + AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult retry = + inTransaction(() -> repository.createOrReadExact(candidate)); + java.util.Optional read = + inTransaction(() -> repository.findByControlPlaneRequestId(boundedRequestId)); + + assertThat(created.created()).isTrue(); + assertThat(retry.created()).isFalse(); + assertThat(read).isPresent(); + assertThat(read.orElseThrow().controlPlaneRequestId()).isEqualTo(boundedRequestId); + assertThat(store.insertCount.get()).isEqualTo(1); + + String oversizedRequestId = "é".repeat(65); + String malformedTupleJson = + boundaryTuple + .canonicalJson() + .replace( + "\"requestId\":\"" + boundedRequestId + "\"", + "\"requestId\":\"" + oversizedRequestId + "\""); + assertThat(malformedTupleJson).contains(oversizedRequestId); + IssuanceCandidate boundaryCandidate = candidate(boundaryTuple, boundedRequestId); + IssuanceCandidate oversized = + new IssuanceCandidate( + boundedRequestId, + bytes(malformedTupleJson), + boundaryTuple.mutationDigest(), + boundaryCandidate.issuanceWorkloadUri(), + boundaryCandidate.reservationOwnerId(), + boundaryCandidate.reservationClaimFence(), + boundaryCandidate.issuanceOperationId(), + boundaryCandidate.issuanceFence(), + boundaryCandidate.bundleReference(), + boundaryCandidate.authorityEvidenceBundle(), + boundaryCandidate.authorizationReferenceFingerprint(), + boundaryCandidate.encryptedResponseEnvelope(), + boundaryCandidate.issuedAt(), + boundaryCandidate.referenceExpiresAt(), + boundaryCandidate.responseEnvelopeExpiresAt()); + int callsBeforeMalformedTuple = store.databaseCallCount.get(); + assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(oversized))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(store.databaseCallCount.get()).isEqualTo(callsBeforeMalformedTuple); + } + + @Test + void redemptionConsumesOnceAndExactRetryReturnsSameAuthorityOnlyResult() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate candidate = candidate(tuple()); + inTransaction(() -> repository.createOrReadExact(candidate)); + RedemptionRequest request = redemption(candidate, OWNER_ATTEMPT_ID, 8L, OWNER_URI); + + var first = inTransaction(() -> repository.redeemExact(request)); + var retry = inTransaction(() -> repository.redeemExact(request)); + + assertThat(first.replay()).isFalse(); + assertThat(retry.replay()).isTrue(); + assertThat(first.authorizationReferenceFingerprint()).isEqualTo(fingerprint("a")); + assertThat(retry.authorizationReferenceFingerprint()) + .isEqualTo(first.authorizationReferenceFingerprint()); + assertThat(first.authorityEvidenceBundle()) + .containsExactly(candidate.authorityEvidenceBundle()); + assertThat(retry.authorityEvidenceBundle()).containsExactly(first.authorityEvidenceBundle()); + assertThat(first.issuanceOperationId()).isEqualTo(ISSUANCE_OPERATION_ID); + assertThat(store.redemptionUpdateCount.get()).isEqualTo(1); + assertThat(first.toString()).doesNotContain("ciphertext-envelope"); + } + + @Test + void aDifferentAttemptFenceOrRedeemerCannotReplayConsumedReference() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate candidate = candidate(tuple()); + inTransaction(() -> repository.createOrReadExact(candidate)); + RedemptionRequest first = redemption(candidate, OWNER_ATTEMPT_ID, 8L, OWNER_URI); + inTransaction(() -> repository.redeemExact(first)); + + RedemptionRequest changedAttempt = redemption(candidate, UUID.randomUUID(), 8L, OWNER_URI); + RedemptionRequest changedFence = redemption(candidate, OWNER_ATTEMPT_ID, 9L, OWNER_URI); + RedemptionRequest changedRedeemer = + redemption( + candidate, OWNER_ATTEMPT_ID, 8L, "spiffe://firemud/ns/staging/sa/game-session-service"); + + for (RedemptionRequest changed : + new RedemptionRequest[] {changedAttempt, changedFence, changedRedeemer}) { + assertThatThrownBy(() -> inTransaction(() -> repository.redeemExact(changed))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + assertThat(store.redemptionUpdateCount.get()).isEqualTo(1); + } + + @Test + void expiredReferenceIsNotConsumedAndMalformedTupleOrFencesFailBeforeSql() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate candidate = candidate(tuple()); + inTransaction(() -> repository.createOrReadExact(candidate)); + + RedemptionRequest expired = + new RedemptionRequest( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.authorizationReferenceFingerprint(), + RESERVATION_OWNER_ID, + 2L, + OWNER_URI, + OWNER_ATTEMPT_ID, + 8L, + candidate.authorityEvidenceBundle(), + candidate.referenceExpiresAt()); + assertThatThrownBy(() -> inTransaction(() -> repository.redeemExact(expired))) + .isInstanceOf( + AccountStartSessionOperatorAuthorizationRepository.ReferenceExpiredException.class); + assertThat(store.row.status).isEqualTo("ISSUED"); + + int operationsBeforeInvalidInput = store.databaseCallCount.get(); + RedemptionRequest invalidFence = + new RedemptionRequest( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.authorizationReferenceFingerprint(), + RESERVATION_OWNER_ID, + 0L, + OWNER_URI, + OWNER_ATTEMPT_ID, + 8L, + candidate.authorityEvidenceBundle(), + NOW); + assertThatThrownBy(() -> inTransaction(() -> repository.redeemExact(invalidFence))) + .isInstanceOf(IllegalArgumentException.class); + + byte[] malformedTuple = bytes("not canonical tuple"); + RedemptionRequest invalidTuple = + new RedemptionRequest( + candidate.controlPlaneRequestId(), + malformedTuple, + candidate.authorizationReferenceFingerprint(), + RESERVATION_OWNER_ID, + 2L, + OWNER_URI, + OWNER_ATTEMPT_ID, + 8L, + candidate.authorityEvidenceBundle(), + NOW); + assertThatThrownBy(() -> inTransaction(() -> repository.redeemExact(invalidTuple))) + .isInstanceOf(IllegalArgumentException.class); + + String unsupportedTupleJson = + new String(candidate.preAuthorizationTuple(), java.nio.charset.StandardCharsets.UTF_8) + .replace("\"tupleSchemaVersion\":\"1\"", "\"tupleSchemaVersion\":\"2\""); + RedemptionRequest unsupportedTuple = + new RedemptionRequest( + candidate.controlPlaneRequestId(), + bytes(unsupportedTupleJson), + candidate.authorizationReferenceFingerprint(), + RESERVATION_OWNER_ID, + 2L, + OWNER_URI, + OWNER_ATTEMPT_ID, + 8L, + candidate.authorityEvidenceBundle(), + NOW); + assertThatThrownBy(() -> inTransaction(() -> repository.redeemExact(unsupportedTuple))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(store.databaseCallCount.get()).isEqualTo(operationsBeforeInvalidInput); + } + + @Test + void ownerTransactionIsMandatoryBeforeAnySql() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + + assertThatThrownBy(() -> repository.createOrReadExact(candidate(tuple()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Account transaction"); + assertThat(store.databaseCallCount.get()).isZero(); + } + + private static AccountStartSessionOperatorAuthorizationRepository repository(MockStore store) { + return new AccountStartSessionOperatorAuthorizationRepository( + DSL.using(new MockConnection(store), SQLDialect.POSTGRES)); + } + + private static IssuanceCandidate candidate(StartSessionPreAuthorizationReservationTuple tuple) { + return candidate(tuple, REQUEST_ID); + } + + private static IssuanceCandidate candidate( + StartSessionPreAuthorizationReservationTuple tuple, String requestId) { + return candidate(requestId, canonicalBytes(tuple), tuple.mutationDigest()); + } + + private static IssuanceCandidate candidate(String requestId, byte[] tupleBytes, String digest) { + return new IssuanceCandidate( + requestId, + tupleBytes, + digest, + ISSUER_URI, + RESERVATION_OWNER_ID, + 2L, + ISSUANCE_OPERATION_ID, + 4L, + bundleReference(31L), + authorityBundle( + tupleFromBytes(tupleBytes), + ISSUANCE_OPERATION_ID, + 4L, + NOW.plusSeconds(180), + bundleReference(31L)), + fingerprint("a"), + bytes("ciphertext-envelope"), + NOW, + NOW.plusSeconds(180), + NOW.plusSeconds(210)); + } + + private static IssuanceCandidate withFingerprint(IssuanceCandidate original, String fingerprint) { + return new IssuanceCandidate( + original.controlPlaneRequestId(), + original.preAuthorizationTuple(), + original.mutationDigest(), + original.issuanceWorkloadUri(), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.issuanceOperationId(), + original.issuanceFence(), + original.bundleReference(), + original.authorityEvidenceBundle(), + fingerprint, + original.encryptedResponseEnvelope(), + original.issuedAt(), + original.referenceExpiresAt(), + original.responseEnvelopeExpiresAt()); + } + + private static RedemptionRequest redemption( + IssuanceCandidate candidate, UUID attemptId, long ownerFence, String redeemerUri) { + return new RedemptionRequest( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.authorizationReferenceFingerprint(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + redeemerUri, + attemptId, + ownerFence, + candidate.authorityEvidenceBundle(), + NOW.plusSeconds(1)); + } + + private static StartSessionPreAuthorizationReservationTuple tuple() { + return tuple("StartSession durable operator authorization test"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String auditReason) { + return tuple(REQUEST_ID, auditReason); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + String controlPlaneRequestId, String auditReason) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + return StartSessionPreAuthorizationReservationTuple.createHuman( + controlPlaneRequestId, ACTOR_ID, action); + } + + private static byte[] canonicalBytes(StartSessionPreAuthorizationReservationTuple tuple) { + return tuple.canonicalJson().getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + + private static byte[] bytes(String value) { + return value.getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + + private static String fingerprint(String hexStart) { + return "arfp/v1/key-1/" + hexStart + "0".repeat(63); + } + + private static BundleReference bundleReference(long sourceFence) { + return new BundleReference( + "authorityEvidenceBundle/v1", "12", Long.toString(sourceFence), "123456789"); + } + + private static StartSessionPreAuthorizationReservationTuple tupleFromBytes(byte[] tupleBytes) { + return StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(tupleBytes, java.nio.charset.StandardCharsets.UTF_8)); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, + UUID operationId, + long issuanceFence, + Instant expiresAt, + BundleReference reference) { + String tenantId = tuple.action().scope().tenantId().toString(); + String actorId = tuple.actor().accountId().toString(); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 1L, + "tenantAuthorityGeneration", Map.of(tenantId, 1L), + "membershipAuthorityGeneration", Map.of(tenantId, 1L), + "privateRealmGrantVersions", List.of()); + Map bundle = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + reference.sourceVersion(), + "projectionStatus", + "CURRENT", + "evaluatedAt", + NOW.toString(), + "expiresAt", + expiresAt.toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", operationId.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", authorityTuple, + "membershipVersion", Map.of(tenantId, 2L), + "issuanceFence", Long.toString(issuanceFence), + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actorId, + "controlUiTokenJti", + UUID.fromString("2e19f788-10d2-4f33-aed6-9a46db136dcc").toString(), + "role", + "tenantAdmin", + "accountGeneration", + "1", + "tenantGeneration", + "1")); + return AccountControlUiAuthority.canonical(bundle); + } + + private static T inTransaction(java.util.function.Supplier action) { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + return action.get(); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private static OffsetDateTime timestampBinding(Object value) { + if (!(value instanceof String timestamp)) { + throw new IllegalArgumentException("Mock SQL timestamp binding must be text"); + } + if (timestamp.length() <= 10 || timestamp.charAt(10) != ' ') { + throw new IllegalArgumentException( + "Mock SQL timestamp binding must use its date-time separator"); + } + return OffsetDateTime.parse(timestamp.substring(0, 10) + "T" + timestamp.substring(11)); + } + + private static final class MockStore implements MockDataProvider { + private static final Field REQUEST_ID = + DSL.field("control_plane_request_id", String.class); + private static final Field TUPLE = DSL.field("pre_authorization_tuple", byte[].class); + private static final Field DIGEST = DSL.field("mutation_digest", String.class); + private static final Field ISSUER = DSL.field("issuance_workload_uri", String.class); + private static final Field RESERVATION_OWNER = + DSL.field("reservation_owner_id", UUID.class); + private static final Field RESERVATION_FENCE = + DSL.field("reservation_claim_fence", Long.class); + private static final Field OPERATION_ID = DSL.field("issuance_operation_id", UUID.class); + private static final Field ISSUANCE_FENCE = DSL.field("issuance_fence", Long.class); + private static final Field BUNDLE_VERSION = DSL.field("bundle_version", String.class); + private static final Field BUNDLE_SOURCE_VERSION = + DSL.field("bundle_source_version", String.class); + private static final Field BUNDLE_SOURCE_FENCE = + DSL.field("bundle_source_fence", String.class); + private static final Field BUNDLE_LINEARIZATION = + DSL.field("bundle_linearization", String.class); + private static final Field BUNDLE = + DSL.field("authority_evidence_bundle", byte[].class); + private static final Field FINGERPRINT = + DSL.field("authorization_reference_fingerprint", String.class); + private static final Field ENVELOPE = + DSL.field("encrypted_response_envelope", byte[].class); + private static final Field ISSUED_AT = + DSL.field("issued_at", OffsetDateTime.class); + private static final Field REFERENCE_EXPIRY = + DSL.field("reference_expires_at", OffsetDateTime.class); + private static final Field ENVELOPE_EXPIRY = + DSL.field("response_envelope_expires_at", OffsetDateTime.class); + private static final Field STATUS = DSL.field("status", String.class); + private static final Field REDEEMER = + DSL.field("redemption_redeemer_workload_uri", String.class); + private static final Field OWNER_ATTEMPT = + DSL.field("redemption_owner_attempt_id", UUID.class); + private static final Field OWNER_FENCE = DSL.field("redemption_owner_fence", Long.class); + private static final Field REDEEMED_AT = + DSL.field("redeemed_at", OffsetDateTime.class); + private static final Field REDEMPTION_FINGERPRINT = + DSL.field("redemption_reference_fingerprint", String.class); + private static final Field REDEMPTION_BUNDLE = + DSL.field("redemption_authority_evidence_bundle", byte[].class); + + private final AtomicInteger databaseCallCount = new AtomicInteger(); + private final AtomicInteger insertCount = new AtomicInteger(); + private final AtomicInteger redemptionUpdateCount = new AtomicInteger(); + private String lastLockSql = ""; + private StoredRow row; + + @Override + public MockResult[] execute(MockExecuteContext context) throws SQLException { + databaseCallCount.incrementAndGet(); + String sql = context.sql().stripLeading().toLowerCase(java.util.Locale.ROOT); + Object[] bind = context.bindings(); + if (sql.startsWith("insert into account_start_session_operator_authorizations")) { + if (row == null) { + row = StoredRow.fromInsert(bind); + insertCount.incrementAndGet(); + return new MockResult[] {new MockResult(1)}; + } + return new MockResult[] {new MockResult(0)}; + } + if (sql.startsWith("update account_start_session_operator_authorizations")) { + if (row == null || !"ISSUED".equals(row.status)) { + return new MockResult[] {new MockResult(0)}; + } + OffsetDateTime now = timestampBinding(bind[7]); + if (!row.referenceExpiresAt.isAfter(now)) { + return new MockResult[] {new MockResult(0)}; + } + row.redeemer = (String) bind[0]; + row.ownerAttempt = (UUID) bind[1]; + row.ownerFence = (Long) bind[2]; + row.redeemedAt = timestampBinding(bind[3]); + row.redemptionFingerprint = (String) bind[4]; + row.redemptionBundle = ((byte[]) bind[5]).clone(); + row.status = "REDEEMED"; + redemptionUpdateCount.incrementAndGet(); + return new MockResult[] {new MockResult(1)}; + } + if (sql.startsWith("select ")) { + if (sql.contains("for update")) { + lastLockSql = sql; + } + return new MockResult[] {row == null ? emptyResult() : rowResult(row)}; + } + throw new SQLException("Unexpected SQL in MockStore: " + sql); + } + + private static MockResult emptyResult() { + return new MockResult(0, result(null)); + } + + private static MockResult rowResult(StoredRow row) { + return new MockResult(1, result(row)); + } + + private static Result result(StoredRow value) { + Result result = + DSL.using(SQLDialect.POSTGRES) + .newResult( + REQUEST_ID, + TUPLE, + DIGEST, + ISSUER, + RESERVATION_OWNER, + RESERVATION_FENCE, + OPERATION_ID, + ISSUANCE_FENCE, + BUNDLE_VERSION, + BUNDLE_SOURCE_VERSION, + BUNDLE_SOURCE_FENCE, + BUNDLE_LINEARIZATION, + BUNDLE, + FINGERPRINT, + ENVELOPE, + ISSUED_AT, + REFERENCE_EXPIRY, + ENVELOPE_EXPIRY, + STATUS, + REDEEMER, + OWNER_ATTEMPT, + OWNER_FENCE, + REDEEMED_AT, + REDEMPTION_FINGERPRINT, + REDEMPTION_BUNDLE); + if (value == null) { + return result; + } + Record record = DSL.using(SQLDialect.POSTGRES).newRecord(result.fields()); + record.setValue(REQUEST_ID, value.requestId); + record.setValue(TUPLE, value.tuple.clone()); + record.setValue(DIGEST, value.digest); + record.setValue(ISSUER, value.issuer); + record.setValue(RESERVATION_OWNER, value.reservationOwner); + record.setValue(RESERVATION_FENCE, value.reservationFence); + record.setValue(OPERATION_ID, value.operationId); + record.setValue(ISSUANCE_FENCE, value.issuanceFence); + record.setValue(BUNDLE_VERSION, value.bundleReference.bundleVersion()); + record.setValue(BUNDLE_SOURCE_VERSION, value.bundleReference.sourceVersion()); + record.setValue(BUNDLE_SOURCE_FENCE, value.bundleReference.sourceFence()); + record.setValue(BUNDLE_LINEARIZATION, value.bundleReference.linearization()); + record.setValue(BUNDLE, value.bundle.clone()); + record.setValue(FINGERPRINT, value.fingerprint); + record.setValue(ENVELOPE, value.envelope.clone()); + record.setValue(ISSUED_AT, value.issuedAt); + record.setValue(REFERENCE_EXPIRY, value.referenceExpiresAt); + record.setValue(ENVELOPE_EXPIRY, value.envelopeExpiresAt); + record.setValue(STATUS, value.status); + record.setValue(REDEEMER, value.redeemer); + record.setValue(OWNER_ATTEMPT, value.ownerAttempt); + record.setValue(OWNER_FENCE, value.ownerFence); + record.setValue(REDEEMED_AT, value.redeemedAt); + record.setValue(REDEMPTION_FINGERPRINT, value.redemptionFingerprint); + record.setValue( + REDEMPTION_BUNDLE, + value.redemptionBundle == null ? null : value.redemptionBundle.clone()); + result.add(record); + return result; + } + } + + private static final class StoredRow { + private final String requestId; + private final byte[] tuple; + private final String digest; + private final String issuer; + private final UUID reservationOwner; + private final Long reservationFence; + private final UUID operationId; + private final Long issuanceFence; + private final BundleReference bundleReference; + private final byte[] bundle; + private final String fingerprint; + private final byte[] envelope; + private final OffsetDateTime issuedAt; + private final OffsetDateTime referenceExpiresAt; + private final OffsetDateTime envelopeExpiresAt; + private String status = "ISSUED"; + private String redeemer; + private UUID ownerAttempt; + private Long ownerFence; + private OffsetDateTime redeemedAt; + private String redemptionFingerprint; + private byte[] redemptionBundle; + + private StoredRow( + String requestId, + byte[] tuple, + String digest, + String issuer, + UUID reservationOwner, + Long reservationFence, + UUID operationId, + Long issuanceFence, + BundleReference bundleReference, + byte[] bundle, + String fingerprint, + byte[] envelope, + OffsetDateTime issuedAt, + OffsetDateTime referenceExpiresAt, + OffsetDateTime envelopeExpiresAt) { + this.requestId = requestId; + this.tuple = tuple.clone(); + this.digest = digest; + this.issuer = issuer; + this.reservationOwner = reservationOwner; + this.reservationFence = reservationFence; + this.operationId = operationId; + this.issuanceFence = issuanceFence; + this.bundleReference = bundleReference; + this.bundle = bundle.clone(); + this.fingerprint = fingerprint; + this.envelope = envelope.clone(); + this.issuedAt = issuedAt; + this.referenceExpiresAt = referenceExpiresAt; + this.envelopeExpiresAt = envelopeExpiresAt; + } + + private static StoredRow fromInsert(Object[] bind) { + return new StoredRow( + (String) bind[0], + (byte[]) bind[1], + (String) bind[2], + (String) bind[3], + (UUID) bind[4], + (Long) bind[5], + (UUID) bind[6], + (Long) bind[7], + new BundleReference( + (String) bind[8], (String) bind[9], (String) bind[10], (String) bind[11]), + (byte[]) bind[12], + (String) bind[13], + (byte[]) bind[14], + timestampBinding(bind[15]), + timestampBinding(bind[16]), + timestampBinding(bind[17])); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java index 6f28101952..8e7b259501 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtReadinessProbeOwnerGrpcServiceTest.java @@ -132,7 +132,7 @@ void ownerLookupIsIndependentlyDefaultDeniedAndUsesTheExactPeerIdentityIntercept assertThat(context.getBean(GlobalPeerIdentityMarker.class).invocations()).hasValue(0); assertThat(observedPeer.get()).isEqualTo(GrpcPeerIdentity.parseUri(peerUri).orElseThrow()); - verify(sslSession, times(1)).getPeerCertificates(); + verify(sslSession, times(2)).getPeerCertificates(); var metadataMethodDefinition = serviceDefinition.getMethods().stream() diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java new file mode 100644 index 0000000000..4cb252a6ab --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java @@ -0,0 +1,581 @@ +package unit.net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; +import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorityBundle; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.AuthorizationResponse; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.IssueRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RecoverRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.io.FileSystemResource; +import org.springframework.util.StreamUtils; + +class StartSessionOperatorAuthorizationGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String LOGGING_URI = "spiffe://firemud/ns/test/sa/logging-admin-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String CONTROL_UI_JWT = "eyJhbGciOiJub25lIn0.eyJzdWIiOiJ0ZXN0In0.signature"; + private static final String AUTHORIZATION_REFERENCE = "A".repeat(43); + private static final String FINGERPRINT = "arfp/v1/key-1/" + "a".repeat(64); + private static final UUID ACTOR_ID = UUID.fromString("6bbab35c-06fd-41f8-b340-989305201e49"); + private static final UUID TENANT_ID = UUID.fromString("37e21e06-af7e-4241-9c24-6dff3501d242"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("f806636f-792b-4a23-a736-92ea1f48340b"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("e6c28d8f-775c-4ea4-af84-fd53a03b0a32"); + private static final UUID RECOVERY_OWNER_ID = + UUID.fromString("5e377426-603e-4bfb-a1a0-3f784881aab4"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("43221254-3728-47a4-b15d-37542871e685"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("4fa8b657-c6ed-4797-b61d-66083f582198"); + private final AccountStartSessionOperatorAuthorizationService ownerService = + mock(AccountStartSessionOperatorAuthorizationService.class); + private final StartSessionOperatorAuthorizationGrpcService service = + new StartSessionOperatorAuthorizationGrpcService(ownerService, NAMESPACE); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void grpcRegistrationIsExplicitlyOptIn() throws IOException { + ConditionalOnProperty condition = + StartSessionOperatorAuthorizationGrpcService.class.getAnnotation( + ConditionalOnProperty.class); + + assertThat(condition).isNotNull(); + assertThat(condition.prefix()) + .isEqualTo("firemud.account.start-session-operator-authorization"); + assertThat(condition.name()).containsExactly("enabled"); + assertThat(condition.havingValue()).isEqualTo("true"); + assertThat(condition.matchIfMissing()).isFalse(); + + try (InputStream input = + new FileSystemResource("src/main/resources/application.yml").getInputStream()) { + String applicationConfiguration = StreamUtils.copyToString(input, StandardCharsets.UTF_8); + assertThat(applicationConfiguration) + .contains( + "start-session-operator-authorization:\n" + + " enabled: " + + "${FIREMUD_ACCOUNT_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED:false}"); + } + } + + @Test + void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { + byte[] tupleBytes = canonicalTupleBytes(); + AuthorizationResponse authorization = authorizationResponse(); + when(ownerService.issue(any())).thenReturn(authorization); + when(ownerService.recover(any())).thenReturn(authorization); + when(ownerService.redeem(any())) + .thenReturn( + new RedemptionResult( + FINGERPRINT, bytes("redemption-bundle"), ISSUANCE_OPERATION_ID, 9L, true)); + + TestObserver issueObserver = + callIssue(issueRequest(tupleBytes), LOGGING_URI); + assertThat(issueObserver.failure).isNull(); + assertThat(issueObserver.completed).isTrue(); + assertThat(issueObserver.value.getOperatorAuthorizationReference()) + .isEqualTo(AUTHORIZATION_REFERENCE); + assertThat(issueObserver.value.getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(issueObserver.value.getExpiresAt().getSeconds()) + .isEqualTo(Instant.parse("2026-10-09T00:03:00Z").getEpochSecond()); + assertThat(issueObserver.value.getAuthorityEvidenceBundle().toByteArray()) + .containsExactly(bytes("authority-bundle")); + assertThat(issueObserver.value.getBundleReference().getBundleVersion()) + .isEqualTo(AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION); + assertThat(issueObserver.value.getBundleReference().getSourceVersion()).isEqualTo("17"); + assertThat(issueObserver.value.getBundleReference().getSourceFence()).isEqualTo("4"); + assertThat(issueObserver.value.getBundleReference().getLinearization()).isEqualTo("3"); + assertThat(issueObserver.value.getAuthenticatedLoggingWorkloadIdentity()) + .isEqualTo(LOGGING_URI); + + var issueCaptor = org.mockito.ArgumentCaptor.forClass(IssueRequest.class); + verify(ownerService).issue(issueCaptor.capture()); + assertThat(issueCaptor.getValue().controlUiJwt()).isEqualTo(CONTROL_UI_JWT); + assertThat(issueCaptor.getValue().canonicalTupleBytes()).containsExactly(tupleBytes); + assertThat(issueCaptor.getValue().reservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID); + assertThat(issueCaptor.getValue().reservationClaimFence()).isEqualTo(3L); + assertThat(issueCaptor.getValue().claimOwnerId()).isEqualTo(RESERVATION_OWNER_ID); + assertThat(issueCaptor.getValue().claimFence()).isEqualTo(3L); + assertThat(issueCaptor.getValue().toString()).doesNotContain(CONTROL_UI_JWT); + + TestObserver recoverObserver = + callRecover(recoverRequest(tupleBytes), LOGGING_URI); + assertThat(recoverObserver.failure).isNull(); + assertThat(recoverObserver.value.getOperatorAuthorizationReference()) + .isEqualTo(AUTHORIZATION_REFERENCE); + assertThat(recoverObserver.value.getAuthenticatedLoggingWorkloadIdentity()) + .isEqualTo(LOGGING_URI); + var recoverCaptor = org.mockito.ArgumentCaptor.forClass(RecoverRequest.class); + verify(ownerService).recover(recoverCaptor.capture()); + assertThat(recoverCaptor.getValue().canonicalTupleBytes()).containsExactly(tupleBytes); + assertThat(recoverCaptor.getValue().reservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID); + assertThat(recoverCaptor.getValue().reservationClaimFence()).isEqualTo(3L); + assertThat(recoverCaptor.getValue().claimOwnerId()).isEqualTo(RECOVERY_OWNER_ID); + assertThat(recoverCaptor.getValue().claimFence()).isEqualTo(5L); + + TestObserver redeemObserver = + callRedeem(redeemRequest(tupleBytes), GAME_SESSION_URI); + assertThat(redeemObserver.failure).isNull(); + assertThat(redeemObserver.value.getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(redeemObserver.value.getAuthorityEvidenceBundle().toByteArray()) + .containsExactly(bytes("redemption-bundle")); + assertThat(redeemObserver.value.getIssuanceOperationId()) + .isEqualTo(ISSUANCE_OPERATION_ID.toString()); + assertThat(redeemObserver.value.getIssuanceFence()).isEqualTo(9L); + assertThat(redeemObserver.value.getReplay()).isTrue(); + var redeemCaptor = org.mockito.ArgumentCaptor.forClass(RedeemRequest.class); + verify(ownerService).redeem(redeemCaptor.capture()); + assertThat(redeemCaptor.getValue().canonicalTupleBytes()).containsExactly(tupleBytes); + assertThat(redeemCaptor.getValue().operatorAuthorizationReference()) + .isEqualTo(AUTHORIZATION_REFERENCE); + assertThat(redeemCaptor.getValue().authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(redeemCaptor.getValue().reservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID); + assertThat(redeemCaptor.getValue().reservationClaimFence()).isEqualTo(3L); + assertThat(redeemCaptor.getValue().ownerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID); + assertThat(redeemCaptor.getValue().ownerFence()).isEqualTo(11L); + assertThat(redeemCaptor.getValue().toString()) + .doesNotContain(AUTHORIZATION_REFERENCE, FINGERPRINT); + } + + @Test + void readsExactRedeemedOperationProjectionWithoutCredentialMaterial() { + byte[] tupleBytes = canonicalTupleBytes(); + when(ownerService.readRedeemedOperationProjection(any())) + .thenReturn(redeemedOperationProjection(tupleBytes)); + + TestObserver observer = + callReadProjection(readProjectionRequest(tupleBytes), GAME_DESIGN_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + ReadRedeemedOperationProjectionResponse response = observer.value; + assertThat(response.getControlPlaneRequestId()).isEqualTo("start-session/operator/βeta"); + assertThat(response.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(tupleBytes); + assertThat(response.getMutationDigest()) + .isEqualTo( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(tupleBytes, StandardCharsets.UTF_8)) + .mutationDigest()); + assertThat(response.getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(response.getReservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(response.getReservationClaimFence()).isEqualTo(3L); + assertThat(response.getAuthenticatedRedeemerWorkloadIdentity()).isEqualTo(GAME_SESSION_URI); + assertThat(response.getOwnerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID.toString()); + assertThat(response.getOwnerFence()).isEqualTo(11L); + assertThat(response.getReferenceExpiresAt().getSeconds()) + .isEqualTo(Instant.parse("2026-10-09T00:03:00Z").getEpochSecond()); + assertThat(response.getRedeemedAt().getSeconds()) + .isEqualTo(Instant.parse("2026-10-09T00:02:00Z").getEpochSecond()); + assertThat(response.getIssuanceOperationId()).isEqualTo(ISSUANCE_OPERATION_ID.toString()); + assertThat(response.getIssuanceFence()).isEqualTo(9L); + assertThat(response.getBundleReference().getBundleVersion()) + .isEqualTo(AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION); + assertThat(response.getBundleReference().getSourceVersion()).isEqualTo("17"); + assertThat(response.getBundleReference().getSourceFence()).isEqualTo("4"); + assertThat(response.getBundleReference().getLinearization()).isEqualTo("3"); + assertThat(response.getAuthorityEvidenceBundle().toByteArray()) + .containsExactly(bytes("authority-bundle")); + assertThat(response.toString()).doesNotContain(CONTROL_UI_JWT, AUTHORIZATION_REFERENCE); + + var readCaptor = + org.mockito.ArgumentCaptor.forClass( + AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest + .class); + verify(ownerService).readRedeemedOperationProjection(readCaptor.capture()); + assertThat(readCaptor.getValue().canonicalPreAuthorizationTuple()).containsExactly(tupleBytes); + assertThat(readCaptor.getValue().authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(readCaptor.getValue().reservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID); + assertThat(readCaptor.getValue().reservationClaimFence()).isEqualTo(3L); + assertThat(readCaptor.getValue().ownerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID); + assertThat(readCaptor.getValue().ownerFence()).isEqualTo(11L); + verifyNoMoreInteractions(ownerService); + } + + @Test + void exactOriginalGameSessionRedeemerCanReadItsCredentialFreeProjection() { + byte[] tupleBytes = canonicalTupleBytes(); + when(ownerService.readRedeemedOperationProjection(any())) + .thenReturn(redeemedOperationProjection(tupleBytes)); + + TestObserver observer = + callReadProjection(readProjectionRequest(tupleBytes), GAME_SESSION_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getAuthenticatedRedeemerWorkloadIdentity()) + .isEqualTo(GAME_SESSION_URI); + assertThat(observer.value.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(tupleBytes); + assertThat(observer.value.getOwnerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID.toString()); + assertThat(observer.value.getOwnerFence()).isEqualTo(11L); + assertThat(observer.value.toString()).doesNotContain(CONTROL_UI_JWT, AUTHORIZATION_REFERENCE); + + verify(ownerService).readRedeemedOperationProjection(any()); + verifyNoMoreInteractions(ownerService); + } + + @Test + void deniesWrongPeerBeforeParsingAndRejectsMalformedProjectionRead() { + ReadRedeemedOperationProjectionRequest malformed = + readProjectionRequest(new byte[] {(byte) 0xc3, 0x28}); + for (String peerUri : + new String[] { + null, + "spiffe://firemud/ns/other/sa/game-design-service", + "spiffe://firemud/ns/other/sa/game-session-service", + LOGGING_URI, + ACCOUNT_URI + }) { + assertThat(status(callReadProjection(malformed, peerUri))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + assertThat(status(callReadProjection(malformed, GAME_DESIGN_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(status(callReadProjection(malformed, GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + callReadProjection( + readProjectionRequest(canonicalTupleBytes()).toBuilder() + .setUnknownFields(unknownFields()) + .build(), + GAME_DESIGN_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + callReadProjection( + readProjectionRequest(canonicalTupleBytes()).toBuilder() + .setOwnerFence(0L) + .build(), + GAME_DESIGN_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(ownerService); + } + + @Test + void rejectsWrongOrMissingPeersBeforeParsingOrInvokingOwnerService() { + IssueHumanOperatorAuthorizationReferenceRequest malformedIssue = + issueRequest(new byte[] {(byte) 0xc3, 0x28}); + for (String peerUri : + new String[] { + null, + "spiffe://firemud/ns/other/sa/logging-admin-service", + "spiffe://firemud/ns/test/sa/game-session-service", + ACCOUNT_URI + }) { + assertThat(status(callIssue(malformedIssue, peerUri))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat( + status( + callRecover( + recoverRequest(canonicalTupleBytes()), + "spiffe://firemud/ns/other/sa/logging-admin-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + callRedeem( + redeemRequest(canonicalTupleBytes()), + "spiffe://firemud/ns/test/sa/logging-admin-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + StartSessionOperatorAuthorizationGrpcService unconfigured = + new StartSessionOperatorAuthorizationGrpcService(ownerService, ""); + TestObserver unconfiguredObserver = + callIssue(unconfigured, malformedIssue, LOGGING_URI); + assertThat(status(unconfiguredObserver)).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(ownerService); + } + + @Test + void rejectsAuthenticatedCallerContextBeforeParsingOrInvokingOwnerService() { + SessionContext.setContext(ACTOR_ID.toString(), List.of("tenantAdmin"), Map.of()); + + assertThat(status(callIssue(issueRequest(new byte[] {0x01}), LOGGING_URI))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(ownerService); + } + + @Test + void sanitizesUnavailableOwnerFailureWithoutExposingItsDetails() { + when(ownerService.issue(any())) + .thenThrow( + Status.UNAVAILABLE.withDescription("private downstream detail").asRuntimeException()); + + TestObserver observer = + callIssue(issueRequest(canonicalTupleBytes()), LOGGING_URI); + + assertThat(status(observer)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(observer.failure.getDescription()) + .isEqualTo("Account operator authorization is temporarily unavailable") + .doesNotContain("private downstream detail"); + } + + @Test + void rejectsMalformedUnknownAndOverBoundRequestsBeforeInvokingOwnerService() { + byte[] tupleBytes = canonicalTupleBytes(); + List invalidIssues = + List.of( + issueRequest(tupleBytes).toBuilder().setUnknownFields(unknownFields()).build(), + issueRequest(new byte[] {(byte) 0xc3, 0x28}), + issueRequest(new byte[8 * 1024 + 1]), + issueRequest(tupleBytes).toBuilder().setControlUiJwt("x".repeat(16 * 1024 + 1)).build(), + issueRequest(tupleBytes).toBuilder().setReservationOwnerId("not-a-uuid").build(), + issueRequest(tupleBytes).toBuilder() + .setReservationOwnerId("00000000-0000-0000-0000-000000000000") + .build(), + issueRequest(tupleBytes).toBuilder().setReservationClaimFence(0L).build(), + issueRequest(tupleBytes).toBuilder().setCurrentClaimFence(-1L).build()); + for (IssueHumanOperatorAuthorizationReferenceRequest invalid : invalidIssues) { + assertThat(status(callIssue(invalid, LOGGING_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + } + + List invalidRecoveries = + List.of( + recoverRequest(tupleBytes).toBuilder().setUnknownFields(unknownFields()).build(), + recoverRequest(new byte[] {(byte) 0xc3, 0x28}), + recoverRequest(tupleBytes).toBuilder().setCurrentClaimOwnerId("not-a-uuid").build(), + recoverRequest(tupleBytes).toBuilder().setCurrentClaimFence(-1L).build()); + for (RecoverOperatorAuthorizationReferenceRequest invalid : invalidRecoveries) { + assertThat(status(callRecover(invalid, LOGGING_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + } + + List invalidRedemptions = + List.of( + redeemRequest(tupleBytes).toBuilder().setUnknownFields(unknownFields()).build(), + redeemRequest(new byte[] {(byte) 0xc3, 0x28}), + redeemRequest(tupleBytes).toBuilder() + .setOperatorAuthorizationReference("x".repeat(129)) + .build(), + redeemRequest(tupleBytes).toBuilder() + .setAuthorizationReferenceFingerprint("changed") + .build(), + redeemRequest(tupleBytes).toBuilder().setOwnerAttemptId("not-a-uuid").build(), + redeemRequest(tupleBytes).toBuilder().setOwnerFence(-1L).build()); + for (RedeemOperatorAuthorizationRequest invalid : invalidRedemptions) { + assertThat(status(callRedeem(invalid, GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(ownerService); + } + + private TestObserver callIssue( + IssueHumanOperatorAuthorizationReferenceRequest request, String peerUri) { + return callIssue(service, request, peerUri); + } + + private TestObserver callIssue( + StartSessionOperatorAuthorizationGrpcService receiver, + IssueHumanOperatorAuthorizationReferenceRequest request, + String peerUri) { + TestObserver observer = new TestObserver<>(); + runWithPeer( + peerUri, () -> receiver.issueHumanOperatorAuthorizationReference(request, observer)); + return observer; + } + + private TestObserver callRecover( + RecoverOperatorAuthorizationReferenceRequest request, String peerUri) { + TestObserver observer = new TestObserver<>(); + runWithPeer(peerUri, () -> service.recoverOperatorAuthorizationReference(request, observer)); + return observer; + } + + private TestObserver callRedeem( + RedeemOperatorAuthorizationRequest request, String peerUri) { + TestObserver observer = new TestObserver<>(); + runWithPeer(peerUri, () -> service.redeemOperatorAuthorization(request, observer)); + return observer; + } + + private TestObserver callReadProjection( + ReadRedeemedOperationProjectionRequest request, String peerUri) { + TestObserver observer = new TestObserver<>(); + runWithPeer(peerUri, () -> service.readRedeemedOperationProjection(request, observer)); + return observer; + } + + private static void runWithPeer(String peerUri, Runnable invocation) { + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(invocation); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } + } + + private static IssueHumanOperatorAuthorizationReferenceRequest issueRequest(byte[] tupleBytes) { + return IssueHumanOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setControlUiJwt(CONTROL_UI_JWT) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(3L) + .setCurrentClaimOwnerId(RESERVATION_OWNER_ID.toString()) + .setCurrentClaimFence(3L) + .build(); + } + + private static RecoverOperatorAuthorizationReferenceRequest recoverRequest(byte[] tupleBytes) { + return RecoverOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(3L) + .setCurrentClaimOwnerId(RECOVERY_OWNER_ID.toString()) + .setCurrentClaimFence(5L) + .build(); + } + + private static RedeemOperatorAuthorizationRequest redeemRequest(byte[] tupleBytes) { + return RedeemOperatorAuthorizationRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setOperatorAuthorizationReference(AUTHORIZATION_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(3L) + .setOwnerAttemptId(OWNER_ATTEMPT_ID.toString()) + .setOwnerFence(11L) + .build(); + } + + private static ReadRedeemedOperationProjectionRequest readProjectionRequest(byte[] tupleBytes) { + return ReadRedeemedOperationProjectionRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(3L) + .setOwnerAttemptId(OWNER_ATTEMPT_ID.toString()) + .setOwnerFence(11L) + .build(); + } + + private static RedeemedOperationProjection redeemedOperationProjection(byte[] tupleBytes) { + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(tupleBytes, StandardCharsets.UTF_8)); + return new RedeemedOperationProjection( + tuple.controlPlaneRequestId(), + tupleBytes, + tuple.mutationDigest(), + FINGERPRINT, + RESERVATION_OWNER_ID, + 3L, + GAME_SESSION_URI, + OWNER_ATTEMPT_ID, + 11L, + Instant.parse("2026-10-09T00:03:00Z"), + Instant.parse("2026-10-09T00:02:00Z"), + ISSUANCE_OPERATION_ID, + 9L, + new AccountStartSessionOperatorAuthorityBundle.BundleReference( + AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION, "17", "4", "3"), + bytes("authority-bundle")); + } + + private static byte[] canonicalTupleBytes() { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "tenant-runtime"), + new StartSessionOperatorAction.Target(42L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "unit test StartSession authorization"); + return StartSessionPreAuthorizationReservationTuple.createHuman( + "start-session/operator/βeta", ACTOR_ID, action) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8); + } + + private static AuthorizationResponse authorizationResponse() { + return new AuthorizationResponse( + AUTHORIZATION_REFERENCE, + FINGERPRINT, + Instant.parse("2026-10-09T00:03:00Z"), + bytes("authority-bundle"), + new AccountStartSessionOperatorAuthorityBundle.BundleReference( + AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION, "17", "4", "3")); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static Status.Code status(TestObserver observer) { + assertThat(observer.failure).isNotNull(); + return observer.failure.getCode(); + } + + private static final class TestObserver implements StreamObserver { + private T value; + private Status failure; + private boolean completed; + + @Override + public void onNext(T response) { + value = response; + } + + @Override + public void onError(Throwable throwable) { + failure = Status.fromThrowable(throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java new file mode 100644 index 0000000000..4e515e2997 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.KeyUnavailableException; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.Snapshot; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationReferenceFingerprint.ReferenceKind; +import org.junit.jupiter.api.Test; + +class AccountOperatorAuthorizationFingerprintKeyringTest { + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final Duration RETENTION_WINDOW = Duration.ofMinutes(3); + private static final byte[] REFERENCE = + "opaque-reference".getBytes(java.nio.charset.StandardCharsets.US_ASCII); + private static final Instant REFERENCE_EXPIRY = NOW.plusSeconds(60); + private static final Instant RESPONSE_EXPIRY = REFERENCE_EXPIRY.plusSeconds(30); + + @Test + void reloadsOwnerSnapshotForEachOperationAndUsesOnlyItsActiveKeyForIssue() { + AtomicInteger reads = new AtomicInteger(); + AccountOperatorAuthorizationFingerprintKeyring keyring = + new AccountOperatorAuthorizationFingerprintKeyring( + () -> { + reads.incrementAndGet(); + return snapshot("active", "active-secret", List.of()); + }, + CLOCK, + RETENTION_WINDOW); + String expected = + calculator("active", "active-secret").fingerprint(ReferenceKind.HUMAN_OPERATOR, REFERENCE); + + assertThat(keyring.fingerprintForIssue(ReferenceKind.HUMAN_OPERATOR, REFERENCE)) + .isEqualTo(expected); + assertThat( + keyring.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + REFERENCE, + expected, + REFERENCE_EXPIRY, + RESPONSE_EXPIRY)) + .isTrue(); + assertThat(reads).hasValue(2); + } + + @Test + void retainedOriginalKeyMustCoverTheImmutableExpiryAndExplicitRecoveryWindow() { + Instant retainedUntil = RESPONSE_EXPIRY.plus(RETENTION_WINDOW).plusNanos(1); + AccountOperatorAuthorizationFingerprintKeyring keyring = + keyring( + snapshot( + "new-active", + "active-secret", + List.of(new KeyMaterial("original", key("original-secret"), retainedUntil)))); + String original = + calculator("original", "original-secret") + .fingerprint(ReferenceKind.HUMAN_OPERATOR, REFERENCE); + + assertThat( + keyring.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + REFERENCE, + original, + REFERENCE_EXPIRY, + RESPONSE_EXPIRY)) + .isTrue(); + } + + @Test + void missingWithdrawnExpiredOrInsufficientlyRetainedOriginalKeyFailsClosed() { + String original = + calculator("original", "original-secret") + .fingerprint(ReferenceKind.HUMAN_OPERATOR, REFERENCE); + List unavailableSnapshots = + List.of( + snapshot("new-active", "active-secret", List.of()), + snapshot( + "new-active", + "active-secret", + List.of(new KeyMaterial("original", key("original-secret"), NOW))), + snapshot( + "new-active", + "active-secret", + List.of( + new KeyMaterial( + "original", + key("original-secret"), + RESPONSE_EXPIRY.plus(RETENTION_WINDOW))))); + + for (Snapshot snapshot : unavailableSnapshots) { + AccountOperatorAuthorizationFingerprintKeyring keyring = keyring(snapshot); + assertThatThrownBy( + () -> + keyring.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + REFERENCE, + original, + REFERENCE_EXPIRY, + RESPONSE_EXPIRY)) + .isInstanceOf(KeyUnavailableException.class); + } + } + + @Test + void rejectsMalformedFingerprintBeforeReadingTheOwnerKeySource() { + AtomicInteger reads = new AtomicInteger(); + AccountOperatorAuthorizationFingerprintKeyring keyring = + new AccountOperatorAuthorizationFingerprintKeyring( + () -> { + reads.incrementAndGet(); + return snapshot("active", "active-secret", List.of()); + }, + CLOCK, + RETENTION_WINDOW); + + assertThatThrownBy( + () -> + keyring.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + REFERENCE, + "arfp/v1/invalid/not-a-digest", + REFERENCE_EXPIRY, + RESPONSE_EXPIRY)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(reads).hasValue(0); + } + + @Test + void rejectsAmbiguousKeySnapshotsAndMissingRetentionPolicy() { + assertThatThrownBy( + () -> + new Snapshot( + new KeyMaterial("duplicate", key("active-secret")), + List.of( + new KeyMaterial( + "duplicate", key("retained-secret"), NOW.plusSeconds(600))))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountOperatorAuthorizationFingerprintKeyring( + () -> snapshot("active", "active-secret", List.of()), CLOCK, Duration.ZERO)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AccountOperatorAuthorizationFingerprintKeyring keyring(Snapshot snapshot) { + return new AccountOperatorAuthorizationFingerprintKeyring( + () -> snapshot, CLOCK, RETENTION_WINDOW); + } + + private static Snapshot snapshot( + String activeId, String activeSecret, List retainedKeys) { + return new Snapshot(new KeyMaterial(activeId, key(activeSecret)), retainedKeys); + } + + private static AccountOperatorAuthorizationReferenceFingerprint calculator( + String keyId, String secret) { + return new AccountOperatorAuthorizationReferenceFingerprint(keyId, key(secret)); + } + + private static SecretKeySpec key(String value) { + return new SecretKeySpec( + value.getBytes(java.nio.charset.StandardCharsets.US_ASCII), "HmacSHA256"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java new file mode 100644 index 0000000000..5af7ca1e4b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java @@ -0,0 +1,386 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.jooq.Record; +import org.junit.jupiter.api.Test; + +class AccountStartSessionOperatorAuthorityBundleTest { + private static final Instant ISSUED_AT = Instant.parse("2026-10-08T11:00:00Z"); + + @Test + void encodesClosedHumanTenantArmAndBindsCaptureReferenceSeparatelyFromAccountFence() { + Fixture fixture = new Fixture(Map.of()); + var capture = fixture.capture(); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + fixture.tuple, + capture, + fixture.issuance, + UUID.randomUUID(), + ISSUED_AT, + ISSUED_AT.plusSeconds(60)); + Map evidence = object(bundle.jsonValue().get("issuanceEvidence")); + var reference = bundle.referenceForCapture(capture); + + assertThat(bundle.jsonValue()) + .containsEntry("bundleVersion", "authorityEvidenceBundle/v1") + .containsEntry("issuanceKind", "human_operator") + .containsEntry("issuanceFence", Long.toString(fixture.source.issuanceFence())) + .doesNotContainKeys("sourceReference", "captureReference"); + assertThat(object(bundle.jsonValue().get("accountProjectionEvidence"))) + .containsEntry("evaluatedAt", ISSUED_AT.toString()); + assertThat(bundle.jsonValue().keySet()) + .containsExactlyInAnyOrder( + "bundleVersion", + "authorityScope", + "accountProjectionEvidence", + "issuanceOperationIdentity", + "issuanceKind", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "issuanceEvidence"); + assertThat(evidence) + .containsEntry("evidenceType", "HumanAuthorityEvidence/v1") + .containsEntry("actorAccountId", fixture.actorId.toString()) + .containsEntry("controlUiTokenJti", fixture.tokenJti.toString()) + .containsEntry("role", "tenantAdmin") + .doesNotContainKeys("assurance", "globalRoles"); + assertThat(evidence.keySet()) + .containsExactlyInAnyOrder( + "evidenceType", + "actorAccountId", + "controlUiTokenJti", + "role", + "accountGeneration", + "tenantGeneration"); + assertThat(reference.asJsonValue()) + .containsEntry("bundleVersion", "authorityEvidenceBundle/v1") + .containsEntry("sourceVersion", "7") + .containsEntry("sourceFence", "31") + .containsEntry("linearization", "123456"); + assertThat(reference.sourceFence()).isNotEqualTo(Long.toString(fixture.source.issuanceFence())); + assertThat(new String(capture.snapshotBytes(), StandardCharsets.UTF_8)) + .contains("\"issuanceFence\":\"70\"") + .contains("\"issuanceFenceSourceVersion\":\"107\""); + + var decoded = AccountStartSessionOperatorAuthorityBundle.decode(bundle.canonicalBytes()); + decoded.requireTupleBinding(fixture.tuple); + decoded.requireCurrent( + fixture.source, fixture.issuance, fixture.tuple, reference, ISSUED_AT.plusSeconds(1)); + } + + @Test + void rejectsAssuranceAdditionGlobalRoleSubstitutionAndTupleSubstitution() { + Fixture assurance = new Fixture(Map.of("assurance", Map.of("level", "step-up"))); + assertThatThrownBy(() -> assurance.create()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenantAdmin"); + + Fixture globalRole = new Fixture(Map.of("globalRoles", List.of("platformAdmin"))); + assertThatThrownBy(() -> globalRole.create()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenantAdmin"); + + Fixture valid = new Fixture(Map.of()); + var bundle = valid.create(); + var substituted = tuple(UUID.randomUUID(), valid.tenantId, "different-request"); + assertThatThrownBy(() -> bundle.requireTupleBinding(substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact StartSession tuple"); + } + + @Test + void strictDecoderRejectsTenantAssuranceAndGlobalBranchEvidence() { + Fixture fixture = new Fixture(Map.of()); + var valid = fixture.create(); + Map withAssurance = new LinkedHashMap<>(valid.jsonValue()); + Map assuranceArm = + new LinkedHashMap<>(object(withAssurance.get("issuanceEvidence"))); + assuranceArm.put("assurance", Map.of("level", "step-up")); + withAssurance.put("issuanceEvidence", assuranceArm); + assertThatThrownBy( + () -> + AccountStartSessionOperatorAuthorityBundle.decode( + AccountControlUiAuthority.canonical(withAssurance))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing or unsupported fields"); + + Map globalArm = new LinkedHashMap<>(valid.jsonValue()); + Map substituted = + new LinkedHashMap<>(object(globalArm.get("issuanceEvidence"))); + substituted.put("role", "platformAdmin"); + globalArm.put("issuanceEvidence", substituted); + assertThatThrownBy( + () -> + AccountStartSessionOperatorAuthorityBundle.decode( + AccountControlUiAuthority.canonical(globalArm))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenantAdmin"); + } + + @Test + void currentSourceMustRetainExactActorGenerationAndSelectedTenant() { + Fixture fixture = new Fixture(Map.of()); + var capture = fixture.capture(); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + fixture.tuple, + capture, + fixture.issuance, + UUID.randomUUID(), + ISSUED_AT, + ISSUED_AT.plusSeconds(60)); + var substitutedSource = + fixture.source(fixture.actorId, fixture.tenantId, 8L, new byte[] {8}, 2L); + + assertThatThrownBy( + () -> + bundle.requireCurrent( + substitutedSource, + fixture.issuance, + fixture.tuple, + bundle.referenceForCapture(capture), + ISSUED_AT.plusSeconds(1))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void sameAttemptReplayAfterEnvelopeHorizonRetainsOriginalSourceLinearization() { + Fixture fixture = new Fixture(Map.of()); + var capture = fixture.capture(); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + fixture.tuple, + capture, + fixture.issuance, + UUID.randomUUID(), + ISSUED_AT, + ISSUED_AT.plusSeconds(60)); + var originalReference = bundle.referenceForCapture(capture); + + bundle.requireCurrentSnapshotForExactReplay( + fixture.source, fixture.issuance, fixture.tuple, originalReference); + + var substitutedTransaction = + new AccountStartSessionOperatorAuthorityBundle.BundleReference( + originalReference.bundleVersion(), + originalReference.sourceVersion(), + originalReference.sourceFence(), + "123457"); + assertThatThrownBy( + () -> + bundle.requireCurrentSnapshotForExactReplay( + fixture.source, fixture.issuance, fixture.tuple, substitutedTransaction)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source differs"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + UUID actorId, UUID tenantId, String requestId) { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, "test"), + new StartSessionOperatorAction.Target(1L, actorId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "authority bundle test"); + return StartSessionPreAuthorizationReservationTuple.createHuman(requestId, actorId, action); + } + + private static Map object(Object value) { + @SuppressWarnings("unchecked") + Map result = (Map) value; + return result; + } + + private static final class Fixture { + final UUID actorId = UUID.randomUUID(); + final UUID tenantId = UUID.randomUUID(); + final UUID tokenJti = UUID.randomUUID(); + final StartSessionPreAuthorizationReservationTuple tuple = + tuple(actorId, tenantId, "request-" + UUID.randomUUID()); + final AccountControlUiAuthority.Snapshot source; + final AccountControlUiIssuanceRepository.Stored issuance; + final UUID reservationOwnerId = UUID.randomUUID(); + + Fixture(Map additionalClaims) { + source = source(actorId, tenantId, 7L, new byte[] {7}, 1L); + issuance = stored(actorId, tenantId, tokenJti, source, additionalClaims); + } + + AccountStartSessionOperatorAuthorityBundle create() { + return AccountStartSessionOperatorAuthorityBundle.create( + tuple, capture(), issuance, UUID.randomUUID(), ISSUED_AT, ISSUED_AT.plusSeconds(60)); + } + + AccountStartSessionAuthorityCapture capture() { + byte[] signerReceipt = issuance.signerReceipt.clone(); + Map snapshot = + Map.ofEntries( + Map.entry("schema", "account-start-session-authority-snapshot/v1"), + Map.entry("controlPlaneRequestId", tuple.controlPlaneRequestId()), + Map.entry( + "preAuthorizationTuple", + Base64.getEncoder() + .encodeToString(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))), + Map.entry("mutationDigest", tuple.mutationDigest()), + Map.entry("accountId", actorId.toString()), + Map.entry("tenantId", tenantId.toString()), + Map.entry("targetOwner", tuple.targetOwner()), + Map.entry("loggingWorkloadUri", "spiffe://firemud/ns/test/sa/logging-admin-service"), + Map.entry("reservationOwnerId", reservationOwnerId.toString()), + Map.entry("reservationClaimFence", "3"), + Map.entry("controlUiOperationId", issuance.operationId.toString()), + Map.entry("controlUiTokenJti", issuance.jti.toString()), + Map.entry("controlUiTokenHash", issuance.tokenHash), + Map.entry( + "controlUiSignerReceipt", Base64.getEncoder().encodeToString(signerReceipt)), + Map.entry("controlUiSignerReceiptSha256", sha256(signerReceipt)), + Map.entry( + "sourceVectorEvidence", Base64.getEncoder().encodeToString(source.evidence())), + Map.entry( + "sourceVector", + source.sources().stream() + .map( + evidence -> Base64.getEncoder().encodeToString(evidence.canonicalBytes())) + .toList()), + Map.entry("outboxCheckpoints", source.outboxCheckpoints()), + Map.entry("authorityTuple", source.authorityTuple()), + Map.entry("membershipVersion", source.membershipVersion()), + Map.entry("accountIdentitySource", source.accountIdentitySource()), + Map.entry("issuanceFence", Long.toString(source.issuanceFence())), + Map.entry( + "issuanceFenceSourceVersion", + Long.toString(source.issuanceFenceSourceVersion()))); + return AccountStartSessionAuthorityCapture.create( + tuple.controlPlaneRequestId(), + 7L, + 31L, + "123456", + "2026-10-08T11:00:00.000Z", + AccountControlUiAuthority.canonical(snapshot)); + } + + AccountControlUiAuthority.Snapshot source( + UUID actor, UUID tenant, long sourceVersion, byte[] evidence, long accountGeneration) { + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + accountGeneration, + "tenantAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "membershipAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "privateRealmGrantVersions", + List.of()); + when(snapshot.actor()).thenReturn(actor); + when(snapshot.tenant()).thenReturn(tenant); + when(snapshot.authorityTuple()).thenReturn(authorityTuple); + when(snapshot.membershipVersion()).thenReturn(Map.of(tenant.toString(), 2L)); + when(snapshot.issuanceFence()).thenReturn(sourceVersion * 10L); + when(snapshot.issuanceFenceSourceVersion()).thenReturn(sourceVersion + 100L); + when(snapshot.evidence()).thenReturn(evidence.clone()); + when(snapshot.outboxCheckpoints()) + .thenReturn(List.of(Map.of("stream", "account", "sequence", 1L))); + when(snapshot.accountIdentitySource()) + .thenReturn(Map.of("accountId", actor.toString(), "sourceVersion", sourceVersion)); + when(snapshot.sources()) + .thenReturn( + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + actor.toString(), + Long.toString(accountGeneration), + Long.toString(sourceVersion), + null, + null, + evidence))); + return snapshot; + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static AccountControlUiIssuanceRepository.Stored stored( + UUID actorId, + UUID tenantId, + UUID tokenJti, + AccountControlUiAuthority.Snapshot source, + Map additionalClaims) { + Map claims = new LinkedHashMap<>(); + claims.put("jti", tokenJti.toString()); + claims.put("sub", actorId.toString()); + claims.put("accountId", actorId.toString()); + claims.put("aud", "control-ui"); + claims.put("tokenGeneration", 1L); + claims.put("authorityTuple", source.authorityTuple()); + claims.put("membershipVersion", source.membershipVersion()); + claims.put("scopedRoles", Map.of(tenantId.toString(), List.of("tenantAdmin"))); + claims.putAll(additionalClaims); + + Map rowValues = + Map.ofEntries( + Map.entry("request_id", UUID.randomUUID()), + Map.entry("operation_id", UUID.randomUUID()), + Map.entry("token_jti", tokenJti), + Map.entry("account_uuid", actorId), + Map.entry("tenant_uuid", tenantId), + Map.entry("caller_context_id", UUID.randomUUID()), + Map.entry("caller_workload", "spiffe://firemud/ns/test/sa/account-service"), + Map.entry("request_mac_key_id", "test-key"), + Map.entry("request_digest", "b".repeat(64)), + Map.entry("status", "COMMITTED"), + Map.entry("token_hash", "c".repeat(64)), + Map.entry("claims_payload", AccountControlUiAuthority.canonical(claims)), + Map.entry("source_payload", source.evidence()), + Map.entry("bundle_payload", AccountControlUiAuthority.canonical(Map.of("version", 1))), + Map.entry("signer_receipt", AccountControlUiAuthority.canonical(Map.of("version", 1))), + Map.entry("pending_registry", new byte[] {1}), + Map.entry("active_registry", new byte[] {2}), + Map.entry("issued_at_epoch_second", ISSUED_AT.minusSeconds(1).getEpochSecond()), + Map.entry("expires_at_epoch_second", ISSUED_AT.plusSeconds(300).getEpochSecond()), + Map.entry( + "recovery_expires_at", + OffsetDateTime.ofInstant(ISSUED_AT.plusSeconds(300), ZoneOffset.UTC))); + Record row = mock(Record.class); + doAnswer(invocation -> rowValues.get(invocation.getArgument(0))) + .when(row) + .get(anyString(), any(Class.class)); + return new AccountControlUiIssuanceRepository.Stored(row); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java new file mode 100644 index 0000000000..787941a593 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java @@ -0,0 +1,1883 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient.Purpose; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceRecord; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.Status; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService.Current; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationReferenceFingerprint.ReferenceKind; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Focused flow proof; JWT validation/source locking remain owned by the real actor service. */ +class AccountStartSessionOperatorAuthorizationServiceTest { + private static final Instant NOW = Instant.parse("2026-10-08T11:00:00Z"); + private static final DateTimeFormatter CAPTURED_AT_FORMAT = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); + private static final String LOGGING_PEER = "spiffe://firemud/ns/test/sa/logging-admin-service"; + private static final String GAME_SESSION_PEER = + "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String GAME_DESIGN_PEER = "spiffe://firemud/ns/test/sa/game-design-service"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void issuePerformsCryptoOutsideSqlAndRejectsSourceChangeBeforeDurableInsert() { + UUID actorId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID requestOwnerId = UUID.randomUUID(); + UUID issuerOperationId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + StartSessionPreAuthorizationReservationTuple tuple = tuple(actorId, tenantId); + AccountControlUiAuthority.Snapshot originalSource = + source(actorId, tenantId, 7L, new byte[] {1}); + AccountControlUiAuthority.Snapshot changedSource = + source(actorId, tenantId, 8L, new byte[] {2}); + AccountControlUiIssuanceRepository.Stored stored = + stored(actorId, tenantId, tokenJti, issuerOperationId, originalSource); + Current original = new Current(stored, originalSource); + Current changed = new Current(stored, changedSource); + List events = new java.util.ArrayList<>(); + + var actors = org.mockito.Mockito.mock(AccountControlUiActorService.class); + var issuanceOperations = org.mockito.Mockito.mock(AccountControlUiIssuanceRepository.class); + var captureRepository = + org.mockito.Mockito.mock(AccountStartSessionAuthorityCaptureRepository.class); + var claims = org.mockito.Mockito.mock(StartSessionReservationEvidenceClient.class); + var repository = + org.mockito.Mockito.mock(AccountStartSessionOperatorAuthorizationRepository.class); + var fingerprintKeys = + org.mockito.Mockito.mock(AccountOperatorAuthorizationFingerprintKeyring.class); + var responseCrypto = org.mockito.Mockito.mock(AccountResponseEnvelopeCryptography.class); + var hostedTerms = org.mockito.Mockito.mock(AccountHostedTermsService.class); + var transactions = org.mockito.Mockito.mock(PlatformTransactionManager.class); + List environmentCaptures = + new java.util.ArrayList<>(); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + when(hostedTerms.captureCurrentEnvironmentBoundary()) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("environment-capture"); + var environment = + org.mockito.Mockito.mock( + AccountHostedTermsService.CapturedEnvironmentBoundary.class); + environmentCaptures.add(environment); + return environment; + }); + AccountStartSessionAuthorityCapture capture = + capture(tuple, originalSource, stored, requestOwnerId, 10L); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(invocation.getArgument(0)).isSameAs(original); + assertThat(invocation.getArgument(2)).isEqualTo(LOGGING_PEER); + events.add("capture-persisted"); + return capture; + }) + .when(captureRepository) + .prepareOrReadExact(any(), eq(tuple), eq(LOGGING_PEER), eq(requestOwnerId), eq(10L)); + when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(claims.readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) + .thenAnswer( + ignored -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + events.add("claim-read"); + return claimEvidence(tuple, requestOwnerId); + }); + doAnswer( + invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + events.add("fingerprint"); + return "arfp/v1/test-key/" + "a".repeat(64); + }) + .when(fingerprintKeys) + .fingerprintForIssue(any(), any()); + when(responseCrypto.encrypt(any(), any(), any())) + .thenAnswer( + invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + events.add("encrypt"); + return new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + new byte[] {3, 4, 5}); + }); + + AtomicInteger ownerPass = new AtomicInteger(); + var secureRandom = + new java.security.SecureRandom() { + @Override + public void nextBytes(byte[] bytes) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("random"); + java.util.Arrays.fill(bytes, (byte) 0x5a); + } + }; + doAnswer( + invocation -> { + int pass = ownerPass.getAndIncrement(); + Current current = pass == 0 ? original : changed; + assertThat( + invocation.getArgument( + 2)) + .isSameAs(environmentCaptures.get(environmentCaptures.size() - 1)); + TransactionSynchronizationManager.setActualTransactionActive(true); + Object result; + try { + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(3); + result = action.apply(current); + } finally { + TransactionSynchronizationManager.clear(); + } + events.add("current-preparation-committed"); + return result; + }) + .when(actors) + .withCurrent(anyString(), any(), any(), any()); + doAnswer( + invocation -> { + events.add("final-current"); + assertThat( + invocation.getArgument( + 3)) + .isSameAs(environmentCaptures.get(environmentCaptures.size() - 1)); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(4); + return action.apply(changed); + } finally { + TransactionSynchronizationManager.clear(); + } + }) + .when(actors) + .withCurrentCommitted(any(), any(), any(), any(), any()); + + var service = + new AccountStartSessionOperatorAuthorizationService( + actors, + issuanceOperations, + captureRepository, + claims, + repository, + fingerprintKeys, + responseCrypto, + hostedTerms, + transactions, + Clock.fixed(NOW, ZoneOffset.UTC), + secureRandom, + LOGGING_PEER, + GAME_SESSION_PEER, + java.time.Duration.ofSeconds(60), + java.time.Duration.ofSeconds(20)); + var request = + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + "test-only-forwarded-control-ui-credential", + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + requestOwnerId, + 10L, + requestOwnerId, + 10L); + + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(LOGGING_PEER).orElseThrow()) + .run( + () -> + assertThatThrownBy(() -> service.issue(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source changed")); + + verify(repository, never()).createOrReadExact(any()); + verify(captureRepository) + .prepareOrReadExact(any(), eq(tuple), eq(LOGGING_PEER), eq(requestOwnerId), eq(10L)); + verify(captureRepository, never()) + .lockExactCurrent(any(), any(), any(), anyString(), any(), anyLong()); + assertThat(events.indexOf("claim-read")).isLessThan(events.indexOf("capture-persisted")); + assertThat(events.indexOf("capture-persisted")) + .isLessThan(events.indexOf("current-preparation-committed")); + assertThat(events.indexOf("current-preparation-committed")) + .isLessThan(events.indexOf("random")); + assertThat(events.indexOf("random")).isLessThan(events.indexOf("fingerprint")); + assertThat(events.indexOf("fingerprint")).isLessThan(events.indexOf("encrypt")); + assertThat(environmentCaptures).hasSize(2); + assertThat(events.indexOf("encrypt")).isLessThan(events.lastIndexOf("environment-capture")); + assertThat(events.lastIndexOf("environment-capture")) + .isLessThan(events.indexOf("final-current")); + } + + @Test + void successfulIssueLocksTheSameCommittedCaptureBeforeWritingIssuedRecord() { + IssueHarness harness = issueHarness(false, false); + AtomicReference + response = new AtomicReference<>(); + + loggingContext().run(() -> response.set(harness.service().issue(harness.issueRequest()))); + + assertThat(harness.events()) + .containsSubsequence( + "claim-read", + "capture-persisted", + "initial-current-returned", + "random", + "fingerprint", + "encrypt", + "final-current", + "capture-lock", + "issuance-row-insert"); + assertThat(harness.environmentCaptures()).hasSize(2); + assertThat(harness.events().indexOf("encrypt")) + .isLessThan(harness.events().indexOf("environment-capture-2")); + assertThat(harness.events().indexOf("environment-capture-2")) + .isLessThan(harness.events().indexOf("final-current")); + assertThat(harness.randomCalls()).hasValue(1); + assertThat(response.get().operatorAuthorizationReference()) + .isEqualTo(Base64.getUrlEncoder().withoutPadding().encodeToString(fill(32, (byte) 0x5a))); + assertThat(response.get().expiresAt()).isEqualTo(NOW.plusSeconds(60)); + assertThat(response.get().bundleReference()) + .isEqualTo( + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + harness.capture().bundleReference())); + + var candidateCaptor = + org.mockito.ArgumentCaptor.forClass( + AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate.class); + verify(harness.repository()).createOrReadExact(candidateCaptor.capture()); + var candidate = candidateCaptor.getValue(); + assertThat(candidate.issuanceFence()).isEqualTo(70L); + assertThat(candidate.bundleReference().sourceVersion()).isEqualTo("17"); + assertThat(candidate.bundleReference().sourceFence()).isEqualTo("31"); + assertThat(candidate.issuanceFence()) + .isNotEqualTo(Long.parseLong(candidate.bundleReference().sourceFence())); + verify(harness.actors()) + .withCurrentCommitted( + eq(harness.tuple().actor().accountId()), + eq(harness.tuple().action().scope().tenantId()), + eq(harness.current().stored().jti), + any(), + any()); + verify(harness.captureRepository()) + .prepareOrReadExact( + eq(harness.current()), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.reservationOwnerId()), + eq(10L)); + verify(harness.captureRepository()) + .lockExactCurrent( + eq(harness.capture()), + eq(harness.current()), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.reservationOwnerId()), + eq(10L)); + } + + @Test + void failedCaptureStopsBeforeRandomFingerprintEncryptionOrIssuanceInsert() { + IssueHarness harness = issueHarness(true, false); + + loggingContext() + .run( + () -> + assertThatThrownBy(() -> harness.service().issue(harness.issueRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("capture unavailable")); + + assertThat(harness.randomCalls()).hasValue(0); + verifyNoInteractions(harness.fingerprintKeys(), harness.responseCrypto()); + verify(harness.repository(), never()).createOrReadExact(any()); + verify(harness.captureRepository()) + .prepareOrReadExact( + any(), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.reservationOwnerId()), + eq(10L)); + verify(harness.captureRepository(), never()) + .lockExactCurrent(any(), any(), any(), anyString(), any(), anyLong()); + } + + @Test + void exactIssueRetryAndRecoveryReturnStoredResponseWithoutReminting() { + IssueHarness harness = issueHarness(false, true); + AtomicReference + issueRetry = new AtomicReference<>(); + AtomicReference + recovery = new AtomicReference<>(); + + loggingContext().run(() -> issueRetry.set(harness.service().issue(harness.issueRequest()))); + loggingContext().run(() -> recovery.set(harness.service().recover(harness.recoverRequest()))); + + assertThat(harness.environmentCaptures()).hasSize(4); + assertThat(harness.events().indexOf("decrypt")) + .isLessThan(harness.events().indexOf("environment-capture-2")); + assertThat(harness.events().indexOf("environment-capture-2")) + .isLessThan(harness.events().indexOf("final-current")); + assertThat(harness.events().lastIndexOf("decrypt")) + .isLessThan(harness.events().indexOf("environment-capture-4")); + assertThat(harness.events().indexOf("environment-capture-4")) + .isLessThan(harness.events().lastIndexOf("final-current")); + + for (var response : List.of(issueRetry.get(), recovery.get())) { + assertThat(response.operatorAuthorizationReference()).isEqualTo("A".repeat(43)); + assertThat(response.authorizationReferenceFingerprint()) + .isEqualTo(harness.originalResponse().authorizationReferenceFingerprint()); + assertThat(response.expiresAt()).isEqualTo(harness.originalResponse().expiresAt()); + assertThat(response.authorityEvidenceBundle()) + .containsExactly(harness.originalResponse().authorityEvidenceBundle()); + assertThat(response.bundleReference()) + .isEqualTo(harness.originalResponse().bundleReference()); + } + assertThat(harness.randomCalls()).hasValue(0); + verify(harness.repository(), never()).createOrReadExact(any()); + verify(harness.fingerprintKeys(), never()).fingerprintForIssue(any(), any()); + verify(harness.fingerprintKeys(), times(2)) + .matchesOriginal( + eq(ReferenceKind.HUMAN_OPERATOR), + any(byte[].class), + eq(harness.originalResponse().authorizationReferenceFingerprint()), + eq(NOW.plusSeconds(60)), + eq(NOW.plusSeconds(80))); + verify(harness.responseCrypto(), never()).encrypt(any(), any(), any()); + verify(harness.responseCrypto(), times(2)).decrypt(any(), any(), any()); + verify(harness.captureRepository(), never()) + .prepareOrReadExact(any(), any(), anyString(), any(), anyLong()); + verify(harness.claims(), times(1)) + .readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), eq(Purpose.ISSUE)); + verify(harness.claims(), times(1)) + .readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), eq(Purpose.RECOVER)); + verify(harness.captureRepository(), times(2)) + .lockReadExactCurrent( + any(), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.reservationOwnerId()), + eq(10L)); + verify(harness.captureRepository(), times(2)) + .lockExactCurrent( + eq(harness.capture()), + eq(harness.current()), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.reservationOwnerId()), + eq(10L)); + } + + @Test + void storedRetryAndRecoveryRejectCurrentSourceChangeDuringResponseDecryption() { + for (boolean recovery : List.of(false, true)) { + IssueHarness harness = issueHarness(false, true); + AccountControlUiAuthority.Snapshot changedSource = + source( + harness.tuple().actor().accountId(), + harness.tuple().action().scope().tenantId(), + 8L, + new byte[] {2}); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + harness.events().add("decrypt"); + harness.finalCurrent().set(new Current(harness.current().stored(), changedSource)); + return harness.originalResponseBytes(); + }) + .when(harness.responseCrypto()) + .decrypt(any(), any(), any()); + + loggingContext() + .run( + () -> + assertThatThrownBy( + () -> { + if (recovery) { + harness.service().recover(harness.recoverRequest()); + } else { + harness.service().issue(harness.issueRequest()); + } + }) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source changed")); + + assertThat(harness.environmentCaptures()).hasSize(2); + assertThat(harness.events().indexOf("decrypt")) + .isLessThan(harness.events().indexOf("environment-capture-2")); + assertThat(harness.events().indexOf("environment-capture-2")) + .isLessThan(harness.events().lastIndexOf("final-current")); + assertThat(harness.randomCalls()).hasValue(0); + verify(harness.repository(), never()).createOrReadExact(any()); + verify(harness.fingerprintKeys(), never()).fingerprintForIssue(any(), any()); + verify(harness.responseCrypto(), never()).encrypt(any(), any(), any()); + verify(harness.captureRepository(), never()) + .lockExactCurrent(any(), any(), any(), anyString(), any(), anyLong()); + verify(harness.responseCrypto()).decrypt(any(), any(), any()); + } + } + + @Test + void createOrReadRaceLoserRevalidatesOriginalAfterDecryptBeforeReturningIt() { + for (boolean sourceChanges : List.of(false, true)) { + IssueHarness harness = issueHarness(false, false); + when(harness + .repository() + .findByControlPlaneRequestId(harness.tuple().controlPlaneRequestId())) + .thenReturn(Optional.empty(), Optional.of(harness.originalRecord())); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + harness.events().add("issuance-race-lost"); + return new AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult( + false, harness.originalRecord()); + }) + .when(harness.repository()) + .createOrReadExact(any()); + AccountControlUiAuthority.Snapshot changedSource = + source( + harness.tuple().actor().accountId(), + harness.tuple().action().scope().tenantId(), + 8L, + new byte[] {2}); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + harness.events().add("decrypt"); + if (sourceChanges) { + harness + .finalCurrent() + .set(new Current(harness.current().stored(), changedSource)); + } + return harness.originalResponseBytes(); + }) + .when(harness.responseCrypto()) + .decrypt(any(), any(), any()); + + if (sourceChanges) { + loggingContext() + .run( + () -> + assertThatThrownBy(() -> harness.service().issue(harness.issueRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source changed")); + } else { + AtomicReference + response = new AtomicReference<>(); + loggingContext().run(() -> response.set(harness.service().issue(harness.issueRequest()))); + assertThat(response.get().operatorAuthorizationReference()).isEqualTo("A".repeat(43)); + assertThat(response.get().authorizationReferenceFingerprint()) + .isEqualTo(harness.originalResponse().authorizationReferenceFingerprint()); + assertThat(response.get().expiresAt()).isEqualTo(harness.originalResponse().expiresAt()); + assertThat(response.get().authorityEvidenceBundle()) + .containsExactly(harness.originalResponse().authorityEvidenceBundle()); + assertThat(response.get().bundleReference()) + .isEqualTo(harness.originalResponse().bundleReference()); + } + + assertThat(harness.environmentCaptures()).hasSize(3); + assertThat(harness.events().indexOf("encrypt")) + .isLessThan(harness.events().indexOf("environment-capture-2")); + assertThat(harness.events().indexOf("environment-capture-2")) + .isLessThan(harness.events().indexOf("issuance-race-lost")); + assertThat(harness.events().indexOf("issuance-race-lost")) + .isLessThan(harness.events().indexOf("decrypt")); + assertThat(harness.events().indexOf("decrypt")) + .isLessThan(harness.events().indexOf("environment-capture-3")); + assertThat(harness.events().indexOf("environment-capture-3")) + .isLessThan(harness.events().lastIndexOf("final-current")); + assertThat(harness.randomCalls()).hasValue(1); + verify(harness.repository()).createOrReadExact(any()); + verify(harness.responseCrypto()).encrypt(any(), any(), any()); + verify(harness.responseCrypto()).decrypt(any(), any(), any()); + verify(harness.captureRepository(), times(sourceChanges ? 1 : 2)) + .lockExactCurrent( + eq(harness.capture()), + any(), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.reservationOwnerId()), + eq(10L)); + } + } + + @Test + void exactRepeatedReadReturnsOriginalRedeemedProjectionAfterCurrentnessRevalidation() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + allowCurrent(harness, harness.source()); + AtomicReference first = new AtomicReference<>(); + AtomicReference retry = new AtomicReference<>(); + AtomicReference gameSessionRead = new AtomicReference<>(); + + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(GAME_DESIGN_PEER).orElseThrow()) + .run( + () -> { + first.set(harness.service().readRedeemedOperationProjection(harness.request())); + retry.set(harness.service().readRedeemedOperationProjection(harness.request())); + }); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri(GAME_SESSION_PEER).orElseThrow()) + .run( + () -> + gameSessionRead.set( + harness.service().readRedeemedOperationProjection(harness.request()))); + + RedeemedOperationProjection original = first.get(); + RedeemedOperationProjection exactRetry = retry.get(); + assertThat(original.controlPlaneRequestId()).isEqualTo(harness.tuple().controlPlaneRequestId()); + assertThat(original.canonicalPreAuthorizationTuple()) + .isEqualTo(harness.record().preAuthorizationTuple()); + assertThat(original.mutationDigest()).isEqualTo(harness.record().mutationDigest()); + assertThat(original.authorizationReferenceFingerprint()) + .isEqualTo(harness.record().authorizationReferenceFingerprint()); + assertThat(original.reservationOwnerId()).isEqualTo(harness.record().reservationOwnerId()); + assertThat(original.reservationClaimFence()) + .isEqualTo(harness.record().reservationClaimFence()); + assertThat(original.redeemerWorkloadUri()).isEqualTo(GAME_SESSION_PEER); + assertThat(original.ownerAttemptId()).isEqualTo(harness.record().redemptionOwnerAttemptId()); + assertThat(original.ownerFence()).isEqualTo(harness.record().redemptionOwnerFence()); + assertThat(original.referenceExpiresAt()).isEqualTo(harness.record().referenceExpiresAt()); + assertThat(original.redeemedAt()).isEqualTo(harness.record().redeemedAt()); + assertThat(original.issuanceOperationId()).isEqualTo(harness.record().issuanceOperationId()); + assertThat(original.issuanceFence()).isEqualTo(harness.record().issuanceFence()); + assertThat(original.bundleReference()) + .isEqualTo( + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + harness.record().bundleReference())); + assertThat(original.authorityEvidenceBundle()) + .isEqualTo(harness.record().authorityEvidenceBundle()); + assertThat(exactRetry.controlPlaneRequestId()).isEqualTo(original.controlPlaneRequestId()); + assertThat(exactRetry.canonicalPreAuthorizationTuple()) + .isEqualTo(original.canonicalPreAuthorizationTuple()); + assertThat(exactRetry.authorityEvidenceBundle()).isEqualTo(original.authorityEvidenceBundle()); + assertThat(gameSessionRead.get().controlPlaneRequestId()) + .isEqualTo(original.controlPlaneRequestId()); + assertThat(gameSessionRead.get().canonicalPreAuthorizationTuple()) + .isEqualTo(original.canonicalPreAuthorizationTuple()); + assertThat(gameSessionRead.get().ownerAttemptId()).isEqualTo(original.ownerAttemptId()); + assertThat(gameSessionRead.get().ownerFence()).isEqualTo(original.ownerFence()); + assertThat(gameSessionRead.get().authorityEvidenceBundle()) + .isEqualTo(original.authorityEvidenceBundle()); + + byte[] mutatedCopy = original.authorityEvidenceBundle(); + mutatedCopy[0] ^= 0x01; + assertThat(original.authorityEvidenceBundle()) + .isEqualTo(harness.record().authorityEvidenceBundle()); + assertThat(original.toString()).doesNotContain("operatorAuthorizationReference"); + assertThat(original.toString()).doesNotContain("controlUiJwt"); + verify(harness.actors(), times(3)) + .withCurrentCommitted( + eq(harness.actorId()), + eq(harness.tenantId()), + eq(harness.tokenJti()), + eq(harness.environment()), + any()); + verify(harness.repository(), times(6)) + .findByControlPlaneRequestId(harness.tuple().controlPlaneRequestId()); + verify(harness.repository(), never()).createOrReadExact(any()); + verify(harness.repository(), never()).redeemExact(any()); + verifyNoInteractions( + harness.claims(), + harness.fingerprintKeys(), + harness.responseCrypto(), + harness.captureRepository()); + } + + @Test + void projectionRequiresExactSameNamespaceGameDesignOrOriginalGameSessionPeerBeforeLookup() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + ReadRedeemedOperationProjectionRequest malformed = + new ReadRedeemedOperationProjectionRequest( + "not canonical tuple".getBytes(StandardCharsets.UTF_8), + harness.request().authorizationReferenceFingerprint(), + harness.request().reservationOwnerId(), + harness.request().reservationClaimFence(), + harness.request().ownerAttemptId(), + harness.request().ownerFence()); + + for (String wrongPeerUri : + List.of( + "spiffe://firemud/ns/other/sa/game-design-service", + "spiffe://firemud/ns/other/sa/game-session-service", + "spiffe://firemud/ns/test/sa/account-service", + LOGGING_PEER)) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(wrongPeerUri).orElseThrow()) + .run( + () -> + assertThatThrownBy( + () -> harness.service().readRedeemedOperationProjection(malformed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Exact authenticated Game Design or Game Session workload identity")); + } + Context.ROOT.run( + () -> + assertThatThrownBy(() -> harness.service().readRedeemedOperationProjection(malformed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Exact authenticated Game Design or Game Session workload identity")); + + verify(harness.repository(), never()).findByControlPlaneRequestId(anyString()); + verify(harness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); + verify(harness.hostedTerms(), never()).captureCurrentEnvironmentBoundary(); + } + + @Test + void projectionRejectsMissingUnredeemedAndWrongRedeemerRecords() { + Context gameDesignContext = gameDesignContext(); + + ReadHarness missingHarness = readHarness(NOW.plusSeconds(30)); + when(missingHarness + .repository() + .findByControlPlaneRequestId(missingHarness.tuple().controlPlaneRequestId())) + .thenReturn(Optional.empty()); + gameDesignContext.run( + () -> + assertThatThrownBy( + () -> + missingHarness + .service() + .readRedeemedOperationProjection(missingHarness.request())) + .isInstanceOf( + AccountStartSessionOperatorAuthorizationService.NotFoundException.class)); + verify(missingHarness.actors(), never()) + .withCurrentCommitted(any(), any(), any(), any(), any()); + + ReadHarness issuedHarness = readHarness(NOW.plusSeconds(30)); + IssuanceRecord issued = asIssued(issuedHarness.record()); + when(issuedHarness + .repository() + .findByControlPlaneRequestId(issuedHarness.tuple().controlPlaneRequestId())) + .thenReturn(Optional.of(issued)); + gameDesignContext.run( + () -> + assertThatThrownBy( + () -> + issuedHarness + .service() + .readRedeemedOperationProjection(issuedHarness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); + verify(issuedHarness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); + + ReadHarness wrongRedeemerHarness = readHarness(NOW.plusSeconds(30)); + IssuanceRecord wrongRedeemer = + withRedeemer( + wrongRedeemerHarness.record(), "spiffe://firemud/ns/other/sa/game-session-service"); + when(wrongRedeemerHarness + .repository() + .findByControlPlaneRequestId(wrongRedeemerHarness.tuple().controlPlaneRequestId())) + .thenReturn(Optional.of(wrongRedeemer)); + gameDesignContext.run( + () -> + assertThatThrownBy( + () -> + wrongRedeemerHarness + .service() + .readRedeemedOperationProjection(wrongRedeemerHarness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); + gameSessionContext() + .run( + () -> + assertThatThrownBy( + () -> + wrongRedeemerHarness + .service() + .readRedeemedOperationProjection(wrongRedeemerHarness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); + verify(wrongRedeemerHarness.actors(), never()) + .withCurrentCommitted(any(), any(), any(), any(), any()); + } + + @Test + void projectionRejectsTupleOwnerAttemptFenceAndFingerprintSubstitutionBeforeCurrentActorLookup() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + ReadRedeemedOperationProjectionRequest original = harness.request(); + UUID substitutedActorId = UUID.randomUUID(); + StartSessionOperatorAction originalAction = harness.tuple().action(); + StartSessionOperatorAction substitutedAction = + new StartSessionOperatorAction( + originalAction.actionFamilySchemaId(), + originalAction.actionFamilySchemaVersion(), + originalAction.scope(), + new StartSessionOperatorAction.Target( + originalAction.target().gameTemplateId(), substitutedActorId), + originalAction.expectedVersion(), + originalAction.mutation(), + originalAction.auditReason()); + byte[] substitutedTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + harness.tuple().controlPlaneRequestId(), substitutedActorId, substitutedAction) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8); + var requests = + List.of( + new ReadRedeemedOperationProjectionRequest( + substitutedTuple, + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.ownerAttemptId(), + original.ownerFence()), + new ReadRedeemedOperationProjectionRequest( + original.canonicalPreAuthorizationTuple(), + original.authorizationReferenceFingerprint(), + UUID.randomUUID(), + original.reservationClaimFence(), + original.ownerAttemptId(), + original.ownerFence()), + new ReadRedeemedOperationProjectionRequest( + original.canonicalPreAuthorizationTuple(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence() + 1, + original.ownerAttemptId(), + original.ownerFence()), + new ReadRedeemedOperationProjectionRequest( + original.canonicalPreAuthorizationTuple(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + UUID.randomUUID(), + original.ownerFence()), + new ReadRedeemedOperationProjectionRequest( + original.canonicalPreAuthorizationTuple(), + "arfp/v1/test-key/" + "b".repeat(64), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.ownerAttemptId(), + original.ownerFence()), + new ReadRedeemedOperationProjectionRequest( + original.canonicalPreAuthorizationTuple(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.ownerAttemptId(), + original.ownerFence() + 1)); + for (Context peerContext : List.of(gameDesignContext(), gameSessionContext())) { + for (ReadRedeemedOperationProjectionRequest request : requests) { + peerContext.run( + () -> + assertThatThrownBy(() -> harness.service().readRedeemedOperationProjection(request)) + .isInstanceOf(IllegalStateException.class)); + } + } + + verify(harness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); + + ReadHarness expiredHarness = readHarness(NOW.minusSeconds(10)); + for (Context peerContext : List.of(gameDesignContext(), gameSessionContext())) { + peerContext.run( + () -> + assertThatThrownBy( + () -> + expiredHarness + .service() + .readRedeemedOperationProjection(expiredHarness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); + } + verify(expiredHarness.actors(), never()) + .withCurrentCommitted(any(), any(), any(), any(), any()); + } + + @Test + void projectionRejectsRevokedOrChangedCurrentAccountSource() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + AccountControlUiAuthority.Snapshot changedSource = + source(harness.actorId(), harness.tenantId(), 8L, new byte[] {2}); + allowCurrent(harness, changedSource); + + for (Context peerContext : List.of(gameDesignContext(), gameSessionContext())) { + peerContext.run( + () -> + assertThatThrownBy( + () -> harness.service().readRedeemedOperationProjection(harness.request())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Current Account source")); + } + + verify(harness.actors(), times(2)) + .withCurrentCommitted( + eq(harness.actorId()), + eq(harness.tenantId()), + eq(harness.tokenJti()), + eq(harness.environment()), + any()); + verifyNoInteractions( + harness.claims(), + harness.fingerprintKeys(), + harness.responseCrypto(), + harness.captureRepository()); + } + + @Test + void expiredOrFutureOriginalClaimEvidenceStopsBeforeCaptureAndPrivateCrypto() { + MutableClock expiredClock = new MutableClock(NOW); + IssueHarness expired = issueHarness(false, false, expiredClock, NOW.minusSeconds(1), NOW); + loggingContext() + .run( + () -> + assertThatThrownBy(() -> expired.service().issue(expired.issueRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("claim evidence is stale or contradictory")); + + assertThat(expired.randomCalls()).hasValue(0); + verify(expired.captureRepository(), never()) + .prepareOrReadExact(any(), any(), anyString(), any(), anyLong()); + verifyNoInteractions(expired.fingerprintKeys(), expired.responseCrypto()); + verify(expired.claims(), times(1)) + .readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), eq(Purpose.ISSUE)); + + MutableClock futureClock = new MutableClock(NOW); + IssueHarness future = + issueHarness(false, false, futureClock, NOW.plusSeconds(1), NOW.plusSeconds(30)); + loggingContext() + .run( + () -> + assertThatThrownBy(() -> future.service().issue(future.issueRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("claim evidence is stale or contradictory")); + + assertThat(future.randomCalls()).hasValue(0); + verify(future.captureRepository(), never()) + .prepareOrReadExact(any(), any(), anyString(), any(), anyLong()); + verifyNoInteractions(future.fingerprintKeys(), future.responseCrypto()); + verify(future.claims(), times(1)) + .readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), eq(Purpose.ISSUE)); + + IssueHarness contradictory = + issueHarness(false, false, new MutableClock(NOW), NOW.minusSeconds(1), NOW.minusSeconds(1)); + loggingContext() + .run( + () -> + assertThatThrownBy( + () -> contradictory.service().issue(contradictory.issueRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("claim evidence is stale or contradictory")); + + assertThat(contradictory.randomCalls()).hasValue(0); + verify(contradictory.captureRepository(), never()) + .prepareOrReadExact(any(), any(), anyString(), any(), anyLong()); + verifyNoInteractions(contradictory.fingerprintKeys(), contradictory.responseCrypto()); + verify(contradictory.claims(), times(1)) + .readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), eq(Purpose.ISSUE)); + } + + @Test + void originalClaimExpiryDuringEncryptionDeniesAtFinalCaptureLockBeforeInsert() { + MutableClock clock = new MutableClock(NOW); + IssueHarness harness = + issueHarness(false, false, clock, NOW.minusSeconds(1), NOW.plusSeconds(30)); + doAnswer( + invocation -> { + harness.events().add("encrypt"); + clock.set(NOW.plusSeconds(30)); + return new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + new byte[] {3, 4, 5}); + }) + .when(harness.responseCrypto()) + .encrypt(any(), any(), any()); + + loggingContext() + .run( + () -> + assertThatThrownBy(() -> harness.service().issue(harness.issueRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("claim evidence is stale or contradictory")); + + assertThat(harness.randomCalls()).hasValue(1); + verify(harness.captureRepository()) + .prepareOrReadExact( + any(), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.reservationOwnerId()), + eq(10L)); + verify(harness.captureRepository()) + .lockExactCurrent( + eq(harness.capture()), + eq(harness.current()), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.reservationOwnerId()), + eq(10L)); + verify(harness.repository(), never()).createOrReadExact(any()); + assertThat(harness.events()).contains("capture-lock").doesNotContain("issuance-row-insert"); + verify(harness.claims(), times(1)) + .readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), eq(Purpose.ISSUE)); + } + + @Test + void claimExpiryDuringCapturePreparationStopsBeforeRandomFingerprintOrEncryption() { + MutableClock clock = new MutableClock(NOW); + IssueHarness harness = + issueHarness(false, false, clock, NOW.minusSeconds(1), NOW.plusSeconds(30)); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + harness.events().add("capture-persisted"); + clock.set(NOW.plusSeconds(30)); + return harness.capture(); + }) + .when(harness.captureRepository()) + .prepareOrReadExact( + any(), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.reservationOwnerId()), + eq(10L)); + + loggingContext() + .run( + () -> + assertThatThrownBy(() -> harness.service().issue(harness.issueRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("claim evidence is stale or contradictory")); + + assertThat(harness.randomCalls()).hasValue(0); + verify(harness.captureRepository()) + .prepareOrReadExact( + any(), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.reservationOwnerId()), + eq(10L)); + verify(harness.captureRepository(), never()) + .lockExactCurrent(any(), any(), any(), anyString(), any(), anyLong()); + verify(harness.repository(), never()).createOrReadExact(any()); + verifyNoInteractions(harness.fingerprintKeys(), harness.responseCrypto()); + verify(harness.claims(), times(1)) + .readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), eq(Purpose.ISSUE)); + } + + private static IssueHarness issueHarness(boolean captureFails, boolean existing) { + return issueHarness( + captureFails, existing, new MutableClock(NOW), NOW.minusSeconds(1), NOW.plusSeconds(30)); + } + + private static IssueHarness issueHarness( + boolean captureFails, + boolean existing, + MutableClock clock, + Instant observedAt, + Instant claimExpiresAt) { + UUID actorId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID reservationOwnerId = UUID.randomUUID(); + UUID claimOwnerId = reservationOwnerId; + UUID tokenJti = UUID.randomUUID(); + UUID originalOperationId = UUID.randomUUID(); + StartSessionPreAuthorizationReservationTuple tuple = tuple(actorId, tenantId); + AccountControlUiAuthority.Snapshot source = source(actorId, tenantId, 7L, new byte[] {1}); + AccountControlUiIssuanceRepository.Stored stored = + stored(actorId, tenantId, tokenJti, originalOperationId, source); + Current current = new Current(stored, source); + AccountStartSessionAuthorityCapture capture = + capture(tuple, source, stored, reservationOwnerId, 10L); + var actors = org.mockito.Mockito.mock(AccountControlUiActorService.class); + var issuanceOperations = org.mockito.Mockito.mock(AccountControlUiIssuanceRepository.class); + var captureRepository = + org.mockito.Mockito.mock(AccountStartSessionAuthorityCaptureRepository.class); + var claims = org.mockito.Mockito.mock(StartSessionReservationEvidenceClient.class); + var repository = + org.mockito.Mockito.mock(AccountStartSessionOperatorAuthorizationRepository.class); + var fingerprintKeys = + org.mockito.Mockito.mock(AccountOperatorAuthorizationFingerprintKeyring.class); + var responseCrypto = org.mockito.Mockito.mock(AccountResponseEnvelopeCryptography.class); + var hostedTerms = org.mockito.Mockito.mock(AccountHostedTermsService.class); + var transactions = org.mockito.Mockito.mock(PlatformTransactionManager.class); + List environmentCaptures = + new java.util.ArrayList<>(); + AtomicReference finalCurrent = new AtomicReference<>(current); + List events = new java.util.ArrayList<>(); + AtomicInteger randomCalls = new AtomicInteger(); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + when(hostedTerms.captureCurrentEnvironmentBoundary()) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var environment = + org.mockito.Mockito.mock( + AccountHostedTermsService.CapturedEnvironmentBoundary.class); + environmentCaptures.add(environment); + events.add("environment-capture-" + environmentCaptures.size()); + return environment; + }); + + AccountStartSessionOperatorAuthorityBundle originalBundle = + AccountStartSessionOperatorAuthorityBundle.create( + tuple, capture, stored, originalOperationId, NOW.minusSeconds(1), NOW.plusSeconds(60)); + String originalFingerprint = "arfp/v1/test-key/" + "a".repeat(64); + when(fingerprintKeys.matchesOriginal( + any(ReferenceKind.class), + any(byte[].class), + anyString(), + any(Instant.class), + any(Instant.class))) + .thenAnswer( + invocation -> { + assertThat(invocation.getArgument(0)) + .isEqualTo(ReferenceKind.HUMAN_OPERATOR); + assertThat(invocation.getArgument(1)) + .containsExactly("A".repeat(43).getBytes(StandardCharsets.US_ASCII)); + assertThat(invocation.getArgument(2)).isEqualTo(originalFingerprint); + assertThat(invocation.getArgument(3)).isEqualTo(NOW.plusSeconds(60)); + assertThat(invocation.getArgument(4)).isEqualTo(NOW.plusSeconds(80)); + return true; + }); + AuthorizationFixture original = + originalAuthorizationFixture( + tuple, + reservationOwnerId, + originalOperationId, + capture, + originalBundle, + originalFingerprint); + when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) + .thenReturn(existing ? Optional.of(original.record()) : Optional.empty()); + when(claims.readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("claim-read"); + return claimEvidence( + tuple, + reservationOwnerId, + claimOwnerId, + 11L, + (Purpose) invocation.getArgument(5), + observedAt, + claimExpiresAt); + }); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(invocation.getArgument(0)).isSameAs(current); + events.add("capture-persisted"); + if (captureFails) throw new IllegalStateException("capture unavailable"); + return capture; + }) + .when(captureRepository) + .prepareOrReadExact(any(), eq(tuple), eq(LOGGING_PEER), eq(reservationOwnerId), eq(10L)); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + events.add("capture-read-lock"); + return capture; + }) + .when(captureRepository) + .lockReadExactCurrent(any(), eq(tuple), eq(LOGGING_PEER), eq(reservationOwnerId), eq(10L)); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(invocation.getArgument(0)) + .isEqualTo(capture); + events.add("capture-lock"); + return capture; + }) + .when(captureRepository) + .lockExactCurrent( + any(), any(), eq(tuple), eq(LOGGING_PEER), eq(reservationOwnerId), eq(10L)); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("fingerprint"); + return "arfp/v1/test-key/" + "b".repeat(64); + }) + .when(fingerprintKeys) + .fingerprintForIssue(any(), any()); + when(responseCrypto.encrypt(any(), any(), any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("encrypt"); + return new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + new byte[] {3, 4, 5}); + }); + when(responseCrypto.decrypt(any(), any(), any())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("decrypt"); + return original.responseBytes(); + }); + // The supplied RNG is kept concrete so the test observes the private random call boundary. + var secureRandom = + new java.security.SecureRandom() { + @Override + public void nextBytes(byte[] bytes) { + randomCalls.incrementAndGet(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("random"); + java.util.Arrays.fill(bytes, (byte) 0x5a); + } + }; + doAnswer( + invocation -> { + assertThat( + invocation.getArgument( + 2)) + .isSameAs(environmentCaptures.get(environmentCaptures.size() - 1)); + TransactionSynchronizationManager.setActualTransactionActive(true); + Object result; + try { + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(3); + result = action.apply(current); + } finally { + TransactionSynchronizationManager.clear(); + } + events.add("initial-current-returned"); + return result; + }) + .when(actors) + .withCurrent(anyString(), any(), any(), any()); + doAnswer( + invocation -> { + assertThat( + invocation.getArgument( + 3)) + .isSameAs(environmentCaptures.get(environmentCaptures.size() - 1)); + events.add("final-current"); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(4); + return action.apply(finalCurrent.get()); + } finally { + TransactionSynchronizationManager.clear(); + } + }) + .when(actors) + .withCurrentCommitted(any(), any(), any(), any(), any()); + + var service = + new AccountStartSessionOperatorAuthorizationService( + actors, + issuanceOperations, + captureRepository, + claims, + repository, + fingerprintKeys, + responseCrypto, + hostedTerms, + transactions, + clock, + secureRandom, + LOGGING_PEER, + GAME_SESSION_PEER, + java.time.Duration.ofSeconds(60), + java.time.Duration.ofSeconds(20)); + var issueRequest = + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + "test-only-control-ui-credential", + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + reservationOwnerId, + 10L, + claimOwnerId, + 11L); + var recoverRequest = + new AccountStartSessionOperatorAuthorizationService.RecoverRequest( + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + reservationOwnerId, + 10L, + claimOwnerId, + 11L); + + if (!existing) { + when(repository.createOrReadExact(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + events.add("issuance-row-insert"); + var candidate = + (AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate) + invocation.getArgument(0); + return new AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult( + true, issuedRecord(candidate)); + }); + } + return new IssueHarness( + service, + actors, + issueRequest, + recoverRequest, + events, + randomCalls, + claims, + repository, + captureRepository, + fingerprintKeys, + responseCrypto, + capture, + current, + finalCurrent, + environmentCaptures, + tuple, + reservationOwnerId, + original.response(), + original.responseBytes(), + original.record()); + } + + private static AuthorizationFixture originalAuthorizationFixture( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + UUID operationId, + AccountStartSessionAuthorityCapture capture, + AccountStartSessionOperatorAuthorityBundle bundle, + String fingerprint) { + Instant issuedAt = NOW.minusSeconds(1); + Instant referenceExpiresAt = NOW.plusSeconds(60); + Instant recoveryExpiresAt = NOW.plusSeconds(80); + String reference = "A".repeat(43); + Map responseValue = + Map.of( + "operatorAuthorizationReference", reference, + "authorizationReferenceFingerprint", fingerprint, + "expiresAt", referenceExpiresAt.toString(), + "authorityEvidenceBundle", bundle.jsonValue(), + "bundleReference", bundle.referenceForCapture(capture).asJsonValue()); + byte[] responseBytes = AccountControlUiAuthority.canonical(responseValue); + var response = + new AccountStartSessionOperatorAuthorizationService.AuthorizationResponse( + reference, + fingerprint, + referenceExpiresAt, + bundle.canonicalBytes(), + bundle.referenceForCapture(capture)); + var record = + new IssuanceRecord( + tuple.controlPlaneRequestId(), + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + tuple.mutationDigest(), + LOGGING_PEER, + reservationOwnerId, + 10L, + operationId, + bundle.issuanceFence(), + AccountStartSessionOperatorAuthorityBundle.toSharedReference( + bundle.referenceForCapture(capture)), + bundle.canonicalBytes(), + fingerprint, + new byte[] {1, 2, 3}, + issuedAt, + referenceExpiresAt, + recoveryExpiresAt, + Status.ISSUED, + null, + null, + null, + null, + null, + null); + return new AuthorizationFixture(response, responseBytes, record); + } + + private static IssuanceRecord issuedRecord( + AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate candidate) { + return new IssuanceRecord( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.mutationDigest(), + candidate.issuanceWorkloadUri(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + candidate.issuanceOperationId(), + candidate.issuanceFence(), + candidate.bundleReference(), + candidate.authorityEvidenceBundle(), + candidate.authorizationReferenceFingerprint(), + candidate.encryptedResponseEnvelope(), + candidate.issuedAt(), + candidate.referenceExpiresAt(), + candidate.responseEnvelopeExpiresAt(), + Status.ISSUED, + null, + null, + null, + null, + null, + null); + } + + private record AuthorizationFixture( + AccountStartSessionOperatorAuthorizationService.AuthorizationResponse response, + byte[] responseBytes, + IssuanceRecord record) { + private AuthorizationFixture { + responseBytes = responseBytes.clone(); + } + + @Override + public byte[] responseBytes() { + return responseBytes.clone(); + } + } + + private record IssueHarness( + AccountStartSessionOperatorAuthorizationService service, + AccountControlUiActorService actors, + AccountStartSessionOperatorAuthorizationService.IssueRequest issueRequest, + AccountStartSessionOperatorAuthorizationService.RecoverRequest recoverRequest, + List events, + AtomicInteger randomCalls, + StartSessionReservationEvidenceClient claims, + AccountStartSessionOperatorAuthorizationRepository repository, + AccountStartSessionAuthorityCaptureRepository captureRepository, + AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, + AccountResponseEnvelopeCryptography responseCrypto, + AccountStartSessionAuthorityCapture capture, + Current current, + AtomicReference finalCurrent, + List environmentCaptures, + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + AccountStartSessionOperatorAuthorizationService.AuthorizationResponse originalResponse, + byte[] originalResponseBytes, + IssuanceRecord originalRecord) { + private IssueHarness { + originalResponseBytes = originalResponseBytes.clone(); + } + + @Override + public byte[] originalResponseBytes() { + return originalResponseBytes.clone(); + } + } + + private static final class MutableClock extends Clock { + private final AtomicReference current; + + private MutableClock(Instant initial) { + current = new AtomicReference<>(initial); + } + + void set(Instant next) { + current.set(next); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return current.get(); + } + + @Override + public long millis() { + return current.get().toEpochMilli(); + } + } + + private static byte[] fill(int length, byte value) { + byte[] bytes = new byte[length]; + java.util.Arrays.fill(bytes, value); + return bytes; + } + + private static ReadHarness readHarness(Instant referenceExpiresAt) { + UUID actorId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID reservationOwnerId = UUID.randomUUID(); + UUID ownerAttemptId = UUID.randomUUID(); + UUID issuanceOperationId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + StartSessionPreAuthorizationReservationTuple tuple = tuple(actorId, tenantId); + AccountControlUiAuthority.Snapshot source = source(actorId, tenantId, 7L, new byte[] {1}); + AccountControlUiIssuanceRepository.Stored stored = + stored(actorId, tenantId, tokenJti, issuanceOperationId, source); + Instant issuedAt = referenceExpiresAt.minusSeconds(50); + Instant redeemedAt = + referenceExpiresAt.isAfter(NOW) ? NOW.minusSeconds(1) : referenceExpiresAt.minusSeconds(1); + var capture = capture(tuple, source, stored, reservationOwnerId, 10L, issuedAt.minusSeconds(1)); + assertThat(Instant.parse(capture.capturedAt())).isBefore(issuedAt).isBefore(referenceExpiresAt); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + tuple, capture, stored, issuanceOperationId, issuedAt, referenceExpiresAt); + var bundleReference = bundle.referenceForCapture(capture); + String fingerprint = "arfp/v1/test-key/" + "a".repeat(64); + IssuanceRecord record = + new IssuanceRecord( + tuple.controlPlaneRequestId(), + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + tuple.mutationDigest(), + LOGGING_PEER, + reservationOwnerId, + 10L, + issuanceOperationId, + bundle.issuanceFence(), + AccountStartSessionOperatorAuthorityBundle.toSharedReference(bundleReference), + bundle.canonicalBytes(), + fingerprint, + new byte[] {9, 8, 7}, + issuedAt, + referenceExpiresAt, + referenceExpiresAt.plusSeconds(20), + Status.REDEEMED, + GAME_SESSION_PEER, + ownerAttemptId, + 18L, + redeemedAt, + fingerprint, + bundle.canonicalBytes()); + + var actors = org.mockito.Mockito.mock(AccountControlUiActorService.class); + var issuanceOperations = org.mockito.Mockito.mock(AccountControlUiIssuanceRepository.class); + var captureRepository = + org.mockito.Mockito.mock(AccountStartSessionAuthorityCaptureRepository.class); + var claims = org.mockito.Mockito.mock(StartSessionReservationEvidenceClient.class); + var repository = + org.mockito.Mockito.mock(AccountStartSessionOperatorAuthorizationRepository.class); + var fingerprintKeys = + org.mockito.Mockito.mock(AccountOperatorAuthorizationFingerprintKeyring.class); + var responseCrypto = org.mockito.Mockito.mock(AccountResponseEnvelopeCryptography.class); + var hostedTerms = org.mockito.Mockito.mock(AccountHostedTermsService.class); + var transactions = org.mockito.Mockito.mock(PlatformTransactionManager.class); + var environment = + org.mockito.Mockito.mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); + when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) + .thenReturn(Optional.of(record)); + var service = + new AccountStartSessionOperatorAuthorizationService( + actors, + issuanceOperations, + captureRepository, + claims, + repository, + fingerprintKeys, + responseCrypto, + hostedTerms, + transactions, + Clock.fixed(NOW, ZoneOffset.UTC), + new java.security.SecureRandom(), + LOGGING_PEER, + GAME_SESSION_PEER, + java.time.Duration.ofSeconds(60), + java.time.Duration.ofSeconds(20)); + ReadRedeemedOperationProjectionRequest request = + new ReadRedeemedOperationProjectionRequest( + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + fingerprint, + reservationOwnerId, + 10L, + ownerAttemptId, + 18L); + return new ReadHarness( + service, + actors, + claims, + repository, + captureRepository, + fingerprintKeys, + responseCrypto, + hostedTerms, + environment, + tuple, + source, + stored, + record, + request, + actorId, + tenantId, + tokenJti); + } + + private static void allowCurrent( + ReadHarness harness, AccountControlUiAuthority.Snapshot currentSource) { + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(4); + return action.apply(new Current(harness.stored(), currentSource)); + } finally { + TransactionSynchronizationManager.clear(); + } + }) + .when(harness.actors()) + .withCurrentCommitted(any(), any(), any(), any(), any()); + } + + private static IssuanceRecord asIssued(IssuanceRecord record) { + return new IssuanceRecord( + record.controlPlaneRequestId(), + record.preAuthorizationTuple(), + record.mutationDigest(), + record.issuanceWorkloadUri(), + record.reservationOwnerId(), + record.reservationClaimFence(), + record.issuanceOperationId(), + record.issuanceFence(), + record.bundleReference(), + record.authorityEvidenceBundle(), + record.authorizationReferenceFingerprint(), + record.encryptedResponseEnvelope(), + record.issuedAt(), + record.referenceExpiresAt(), + record.responseEnvelopeExpiresAt(), + Status.ISSUED, + null, + null, + null, + null, + null, + null); + } + + private static IssuanceRecord withRedeemer(IssuanceRecord record, String redeemerWorkloadUri) { + return new IssuanceRecord( + record.controlPlaneRequestId(), + record.preAuthorizationTuple(), + record.mutationDigest(), + record.issuanceWorkloadUri(), + record.reservationOwnerId(), + record.reservationClaimFence(), + record.issuanceOperationId(), + record.issuanceFence(), + record.bundleReference(), + record.authorityEvidenceBundle(), + record.authorizationReferenceFingerprint(), + record.encryptedResponseEnvelope(), + record.issuedAt(), + record.referenceExpiresAt(), + record.responseEnvelopeExpiresAt(), + Status.REDEEMED, + redeemerWorkloadUri, + record.redemptionOwnerAttemptId(), + record.redemptionOwnerFence(), + record.redeemedAt(), + record.redemptionReferenceFingerprint(), + record.redemptionAuthorityEvidenceBundle()); + } + + private static Context gameDesignContext() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri(GAME_DESIGN_PEER).orElseThrow()); + } + + private static Context loggingContext() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(LOGGING_PEER).orElseThrow()); + } + + private static Context gameSessionContext() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri(GAME_SESSION_PEER).orElseThrow()); + } + + private record ReadHarness( + AccountStartSessionOperatorAuthorizationService service, + AccountControlUiActorService actors, + StartSessionReservationEvidenceClient claims, + AccountStartSessionOperatorAuthorizationRepository repository, + AccountStartSessionAuthorityCaptureRepository captureRepository, + AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, + AccountResponseEnvelopeCryptography responseCrypto, + AccountHostedTermsService hostedTerms, + AccountHostedTermsService.CapturedEnvironmentBoundary environment, + StartSessionPreAuthorizationReservationTuple tuple, + AccountControlUiAuthority.Snapshot source, + AccountControlUiIssuanceRepository.Stored stored, + IssuanceRecord record, + ReadRedeemedOperationProjectionRequest request, + UUID actorId, + UUID tenantId, + UUID tokenJti) {} + + private static StartSessionPreAuthorizationReservationTuple tuple(UUID actorId, UUID tenantId) { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, "test"), + new StartSessionOperatorAction.Target(1L, actorId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "authorization test"); + return StartSessionPreAuthorizationReservationTuple.createHuman( + "request-" + UUID.randomUUID(), actorId, action); + } + + private static AccountStartSessionAuthorityCapture capture( + StartSessionPreAuthorizationReservationTuple tuple, + AccountControlUiAuthority.Snapshot source, + AccountControlUiIssuanceRepository.Stored stored, + UUID reservationOwnerId, + long reservationClaimFence) { + return capture(tuple, source, stored, reservationOwnerId, reservationClaimFence, NOW); + } + + private static AccountStartSessionAuthorityCapture capture( + StartSessionPreAuthorizationReservationTuple tuple, + AccountControlUiAuthority.Snapshot source, + AccountControlUiIssuanceRepository.Stored stored, + UUID reservationOwnerId, + long reservationClaimFence, + Instant capturedAt) { + byte[] signerReceipt = stored.signerReceipt.clone(); + Map snapshot = + Map.ofEntries( + Map.entry("schema", "account-start-session-authority-snapshot/v1"), + Map.entry("controlPlaneRequestId", tuple.controlPlaneRequestId()), + Map.entry( + "preAuthorizationTuple", + Base64.getEncoder() + .encodeToString(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))), + Map.entry("mutationDigest", tuple.mutationDigest()), + Map.entry("accountId", tuple.actor().accountId().toString()), + Map.entry("tenantId", tuple.action().scope().tenantId().toString()), + Map.entry("targetOwner", tuple.targetOwner()), + Map.entry("loggingWorkloadUri", LOGGING_PEER), + Map.entry("reservationOwnerId", reservationOwnerId.toString()), + Map.entry("reservationClaimFence", Long.toString(reservationClaimFence)), + Map.entry("controlUiOperationId", stored.operationId.toString()), + Map.entry("controlUiTokenJti", stored.jti.toString()), + Map.entry("controlUiTokenHash", stored.tokenHash), + Map.entry("controlUiSignerReceipt", Base64.getEncoder().encodeToString(signerReceipt)), + Map.entry("controlUiSignerReceiptSha256", sha256(signerReceipt)), + Map.entry( + "sourceVectorEvidence", Base64.getEncoder().encodeToString(source.evidence())), + Map.entry( + "sourceVector", + source.sources().stream() + .map(evidence -> Base64.getEncoder().encodeToString(evidence.canonicalBytes())) + .toList()), + Map.entry("outboxCheckpoints", source.outboxCheckpoints()), + Map.entry("authorityTuple", source.authorityTuple()), + Map.entry("membershipVersion", source.membershipVersion()), + Map.entry("accountIdentitySource", source.accountIdentitySource()), + Map.entry("issuanceFence", Long.toString(source.issuanceFence())), + Map.entry( + "issuanceFenceSourceVersion", Long.toString(source.issuanceFenceSourceVersion()))); + return AccountStartSessionAuthorityCapture.create( + tuple.controlPlaneRequestId(), + 17L, + 31L, + "123456", + CAPTURED_AT_FORMAT.format(capturedAt), + AccountControlUiAuthority.canonical(snapshot)); + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException unavailable) { + throw new IllegalStateException(unavailable); + } + } + + private static AccountControlUiAuthority.Snapshot source( + UUID actorId, UUID tenantId, long sourceVersion, byte[] evidence) { + var source = org.mockito.Mockito.mock(AccountControlUiAuthority.Snapshot.class); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 1L, + "tenantAuthorityGeneration", + Map.of(tenantId.toString(), 1L), + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), 1L), + "privateRealmGrantVersions", + List.of()); + Map membershipVersion = Map.of(tenantId.toString(), 2L); + when(source.actor()).thenReturn(actorId); + when(source.tenant()).thenReturn(tenantId); + when(source.authorityTuple()).thenReturn(authorityTuple); + when(source.membershipVersion()).thenReturn(membershipVersion); + when(source.issuanceFence()).thenReturn(sourceVersion * 10L); + when(source.issuanceFenceSourceVersion()).thenReturn(sourceVersion + 100L); + when(source.evidence()).thenReturn(evidence.clone()); + when(source.outboxCheckpoints()) + .thenReturn(List.of(Map.of("stream", "account", "sequence", 1L))); + when(source.accountIdentitySource()) + .thenReturn(Map.of("accountId", actorId.toString(), "sourceVersion", sourceVersion)); + when(source.sources()) + .thenReturn( + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + actorId.toString(), + "1", + Long.toString(sourceVersion), + null, + null, + evidence))); + return source; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static AccountControlUiIssuanceRepository.Stored stored( + UUID actorId, + UUID tenantId, + UUID tokenJti, + UUID operationId, + AccountControlUiAuthority.Snapshot source) { + UUID requestId = UUID.randomUUID(); + Map claims = + Map.of( + "jti", + tokenJti.toString(), + "sub", + actorId.toString(), + "accountId", + actorId.toString(), + "aud", + "control-ui", + "tokenGeneration", + 1L, + "authorityTuple", + source.authorityTuple(), + "membershipVersion", + source.membershipVersion(), + "scopedRoles", + Map.of(tenantId.toString(), List.of("tenantAdmin"))); + Map values = + Map.ofEntries( + Map.entry("request_id", requestId), + Map.entry("operation_id", operationId), + Map.entry("token_jti", tokenJti), + Map.entry("account_uuid", actorId), + Map.entry("tenant_uuid", tenantId), + Map.entry("caller_context_id", UUID.randomUUID()), + Map.entry("caller_workload", "spiffe://firemud/ns/test/sa/account-service"), + Map.entry("request_mac_key_id", "test-key"), + Map.entry("request_digest", "b".repeat(64)), + Map.entry("status", "COMMITTED"), + Map.entry("token_hash", "c".repeat(64)), + Map.entry("claims_payload", AccountControlUiAuthority.canonical(claims)), + Map.entry("source_payload", source.evidence()), + Map.entry("bundle_payload", AccountControlUiAuthority.canonical(Map.of("v", 1))), + Map.entry("signer_receipt", AccountControlUiAuthority.canonical(Map.of("v", 1))), + Map.entry("pending_registry", new byte[] {1}), + Map.entry("active_registry", new byte[] {2}), + Map.entry("issued_at_epoch_second", NOW.minusSeconds(10).getEpochSecond()), + Map.entry("expires_at_epoch_second", NOW.plusSeconds(300).getEpochSecond()), + Map.entry( + "recovery_expires_at", + OffsetDateTime.ofInstant(NOW.plusSeconds(300), ZoneOffset.UTC))); + Record row = org.mockito.Mockito.mock(Record.class); + org.mockito.Mockito.doAnswer(invocation -> values.get(invocation.getArgument(0))) + .when(row) + .get(anyString(), any(Class.class)); + return new AccountControlUiIssuanceRepository.Stored(row); + } + + private static ReadCurrentClaimEvidenceResponse claimEvidence( + StartSessionPreAuthorizationReservationTuple tuple, UUID ownerId) { + return claimEvidence( + tuple, ownerId, ownerId, 10L, Purpose.ISSUE, NOW.minusSeconds(1), NOW.plusSeconds(30)); + } + + private static ReadCurrentClaimEvidenceResponse claimEvidence( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + UUID claimOwnerId, + long claimFence, + Purpose purpose, + Instant observedAt, + Instant claimExpiresAt) { + return ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson(), StandardCharsets.UTF_8)) + .setMutationDigest(tuple.mutationDigest()) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(10L) + .setClaimOwnerId(claimOwnerId.toString()) + .setClaimFence(claimFence) + .setObservedAtEpochMillis(observedAt.toEpochMilli()) + .setClaimExpiresAtEpochMillis(claimExpiresAt.toEpochMilli()) + .setPurpose( + purpose == Purpose.ISSUE + ? StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE + : StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER) + .build(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerCertificateEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerCertificateEvidence.java new file mode 100644 index 0000000000..b70e020634 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerCertificateEvidence.java @@ -0,0 +1,77 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.Context; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.HexFormat; +import java.util.Optional; +import java.util.regex.Pattern; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLSession; + +/** The SHA-256 evidence for the leaf presented by the serving gRPC TLS peer. */ +public final class GrpcPeerCertificateEvidence { + public static final Context.Key CONTEXT_KEY = + Context.key("firemud-grpc-peer-certificate-evidence"); + + private static final Pattern SHA256_PATTERN = Pattern.compile("[0-9a-f]{64}"); + + private final String leafSha256; + + private GrpcPeerCertificateEvidence(String leafSha256) { + if (leafSha256 == null || !SHA256_PATTERN.matcher(leafSha256).matches()) { + throw new IllegalArgumentException("Leaf SHA-256 fingerprint must be lowercase hexadecimal"); + } + this.leafSha256 = leafSha256; + } + + /** Returns the evidence currently attached to the serving gRPC context, if verified. */ + public static GrpcPeerCertificateEvidence current() { + return CONTEXT_KEY.get(); + } + + /** Extracts the presented leaf's DER SHA-256 fingerprint from the authenticated TLS session. */ + public static Optional fromSslSession(SSLSession sslSession) { + if (sslSession == null) { + return Optional.empty(); + } + try { + Certificate[] peerCertificates = sslSession.getPeerCertificates(); + if (peerCertificates == null + || peerCertificates.length == 0 + || !(peerCertificates[0] instanceof X509Certificate leaf)) { + return Optional.empty(); + } + return fromCertificate(leaf); + } catch (SSLPeerUnverifiedException | RuntimeException exception) { + return Optional.empty(); + } + } + + /** Extracts only leaf-instance evidence; this fingerprint is not a workload principal. */ + public static Optional fromCertificate(X509Certificate leaf) { + if (leaf == null) { + return Optional.empty(); + } + try { + byte[] encoded = leaf.getEncoded(); + if (encoded == null || encoded.length == 0) { + return Optional.empty(); + } + return Optional.of(new GrpcPeerCertificateEvidence(sha256(encoded))); + } catch (CertificateEncodingException | NoSuchAlgorithmException | RuntimeException exception) { + return Optional.empty(); + } + } + + public String leafSha256() { + return leafSha256; + } + + private static String sha256(byte[] certificateDer) throws NoSuchAlgorithmException { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(certificateDer)); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityInterceptor.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityInterceptor.java index 6664b5d2b9..8651d8dc30 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityInterceptor.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcPeerIdentityInterceptor.java @@ -7,6 +7,7 @@ import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.ServerInterceptor; +import javax.net.ssl.SSLSession; /** * Makes the authenticated TLS peer identity available to gRPC handlers. @@ -19,10 +20,14 @@ public final class GrpcPeerIdentityInterceptor implements ServerInterceptor { @Override public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { - GrpcPeerIdentity peerIdentity = - GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) - .orElse(null); - Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peerIdentity); + SSLSession sslSession = call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.fromSslSession(sslSession).orElse(null); + GrpcPeerCertificateEvidence certificateEvidence = + GrpcPeerCertificateEvidence.fromSslSession(sslSession).orElse(null); + Context context = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peerIdentity) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificateEvidence); return Contexts.interceptCall(context, call, headers, next); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java index aec108b44d..33c02da7f2 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTuple.java @@ -71,7 +71,7 @@ public static StartSessionPreAuthorizationReservationTuple fromCanonicalJson(Str if (!canonical.equals(json)) { throw new IllegalArgumentException("pre-authorization tuple is not canonical JSON"); } - Object decoded = JSON.readValue(json, Map.class); + Object decoded = JSON.readValue(json, Object.class); Map root = requireObject(decoded, "tuple"); requireExactFields(root, ROOT_FIELDS, "tuple"); if (!TUPLE_SCHEMA_ID.equals(requireString(root.get("tupleSchemaId"), "tupleSchemaId")) diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java index 3f881b6d5e..681f295bb0 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java @@ -119,6 +119,15 @@ void strictDecoderRejectsNoncanonicalAndUnsupportedTupleShapes() { () -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(invalidActorKind)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("actor must be human"); + assertThatThrownBy(() -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson("[]")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tuple must be an object"); + assertThatThrownBy(() -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson("null")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tuple JSON is invalid"); + assertThatThrownBy(() -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson("{}")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing or unsupported fields"); } private static StartSessionOperatorAction action(StartSessionOperatorAction.ClientIp clientIp) { diff --git a/services/logging-admin-service/build.gradle.kts b/services/logging-admin-service/build.gradle.kts index 3f355d19a2..c3da9c94a7 100644 --- a/services/logging-admin-service/build.gradle.kts +++ b/services/logging-admin-service/build.gradle.kts @@ -2,6 +2,7 @@ apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { + `java-test-fixtures` id("net.firedevops.firemud.secured-sql-aop-service-conventions") id("net.firedevops.firemud.openapi-conventions") id("net.firedevops.firemud.jooq-conventions") @@ -12,4 +13,13 @@ firemudJooq { } dependencies { + testImplementation(libs.grpc.inprocess) + testImplementation(libs.grpc.netty.shaded) + testImplementation(testFixtures(project(":logging-admin-service"))) + testCompileOnly(libs.spotbugs.annotations) + testFixturesApi(libs.testcontainers.postgresql) + testFixturesImplementation(libs.jooq) + testFixturesImplementation(libs.postgresql) + testFixturesImplementation(libs.spring.boot.starter.test) + testFixturesImplementation(libs.testcontainers.postgresql) } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java new file mode 100644 index 0000000000..a72aee9a6c --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java @@ -0,0 +1,727 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** Durable, bounded Logging/Admin claim lifecycle for StartSession authorization and handoff. */ +@Service +public final class StartSessionPreAuthorizationReservationService { + public static final Duration CLAIM_TTL = Duration.ofSeconds(30); + + private final StartSessionPreAuthorizationReservationRepository repository; + private final Clock clock; + private final MutationCapability mutationCapability; + + @Autowired + public StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository) { + this(repository, Clock.systemUTC(), null); + } + + StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository, Clock clock) { + this(repository, clock, null); + } + + private StartSessionPreAuthorizationReservationService( + StartSessionPreAuthorizationReservationRepository repository, + Clock clock, + MutationCapability mutationCapability) { + this.repository = Objects.requireNonNull(repository, "repository is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + this.mutationCapability = mutationCapability; + } + + /** + * Atomically creates one reservation or returns the exact existing reservation as a duplicate. + * Only the first caller receives a claim capability; an exact duplicate cannot dispatch work. + */ + public Acquisition acquire(StartSessionPreAuthorizationReservationTuple tuple) { + requireMutationCapability(); + Objects.requireNonNull(tuple, "tuple is required"); + if (!tuple.isAuthorityDerived()) { + throw new IllegalArgumentException( + "initial reservation requires an actor derived from the authenticated request context"); + } + Instant now = clock.instant(); + UUID ownerId = UUID.randomUUID(); + StartSessionPreAuthorizationReservationRepository.AcquireResult result = + repository.acquire(tuple, ownerId, epochMillis(now), epochMillis(now.plus(CLAIM_TTL))); + ClaimHandle claim = + result.created() + ? new ClaimHandle( + tuple, + tuple.mutationDigest(), + ownerId, + ownerId, + result.snapshot().reservationClaimFence(), + result.snapshot().claimFence(), + ClaimPurpose.ORIGINAL) + : null; + return new Acquisition(result.snapshot(), claim); + } + + /** Read-only lookup by the one stable orchestration key. */ + public Optional find(String controlPlaneRequestId) { + return repository.find(controlPlaneRequestId); + } + + /** Read-only exact lookup; a reused key with any tuple difference conflicts. */ + public Optional findExact(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + return repository.findExact(tuple); + } + + /** + * Reads one exact active Account evidence claim. Issue evidence is available only after the + * reservation is pending and only for an original or reserved-state recovery claim. Recovery + * evidence is read-only and may inspect the pending or already-authorized original response. + */ + public Optional readCurrentClaimEvidence( + String controlPlaneRequestId, + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + ReadPurpose purpose) { + if (controlPlaneRequestId == null) { + throw new IllegalArgumentException("controlPlaneRequestId is required"); + } + String canonicalControlPlaneRequestId = + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + Objects.requireNonNull(tuple, "tuple is required"); + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + Objects.requireNonNull(currentClaimOwnerId, "currentClaimOwnerId is required"); + Objects.requireNonNull(purpose, "purpose is required"); + if (!canonicalControlPlaneRequestId.equals(tuple.controlPlaneRequestId()) + || reservationOwnerId.equals(new UUID(0L, 0L)) + || currentClaimOwnerId.equals(new UUID(0L, 0L)) + || reservationClaimFence <= 0L + || currentClaimFence <= 0L) { + throw new IllegalArgumentException("exact reservation claim identity is required"); + } + if (purpose == ReadPurpose.ISSUE && currentClaimFence < reservationClaimFence) { + throw new StaleReservationClaimException(tuple.controlPlaneRequestId()); + } + if (purpose == ReadPurpose.RECOVER + && (reservationOwnerId.equals(currentClaimOwnerId) + || currentClaimFence <= reservationClaimFence)) { + throw new StaleReservationClaimException(tuple.controlPlaneRequestId()); + } + + Optional read = + repository.readCurrentClaim( + tuple, + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + purpose, + epochMillis(clock.instant())); + if (read.isEmpty()) { + return Optional.empty(); + } + StartSessionPreAuthorizationReservationRepository.CurrentClaimResult result = + read.orElseThrow(); + long observedAtEpochMillis = epochMillis(clock.instant()); + Snapshot snapshot = result.snapshot(); + boolean allowedState = + purpose == ReadPurpose.ISSUE + ? snapshot.state() == State.AUTHORIZATION_PENDING + : snapshot.state() == State.AUTHORIZATION_PENDING + || snapshot.state() == State.AUTHORIZED; + if (snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || !allowedState + || snapshot.claimState() != ClaimState.ACTIVE + || snapshot.reservationClaimFence() != reservationClaimFence + || snapshot.claimFence() != currentClaimFence + || !snapshot.tuple().canonicalJson().equals(tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(tuple.mutationDigest()) + || !result.reservationOwnerId().equals(reservationOwnerId) + || !result.currentClaimOwnerId().equals(currentClaimOwnerId) + || !claimPurposeAllowsRead(snapshot, purpose, reservationOwnerId, currentClaimOwnerId) + || snapshot.claimExpiresAtEpochMillis() <= observedAtEpochMillis) { + throw new StaleReservationClaimException(tuple.controlPlaneRequestId()); + } + return Optional.of( + new CurrentClaimEvidence( + snapshot, + result.reservationOwnerId(), + result.currentClaimOwnerId(), + purpose, + observedAtEpochMillis)); + } + + /** + * Durably enters AUTHORIZATION_PENDING before the Account call is dispatched by a later + * integration. Only the first successful transition returns {@code mayDispatch=true}; observing + * the pending state again never authorizes another issuance call. + */ + public PendingTransition markAuthorizationPending(ClaimHandle claim) { + requireMutationCapability(); + requireClaim(claim); + if (!isIssueClaimPurpose(claim.purpose)) { + throw new StaleReservationClaimException(claim.controlPlaneRequestId()); + } + StartSessionPreAuthorizationReservationRepository.TransitionResult result = + repository.markAuthorizationPending( + claim.tuple, + claim.mutationDigest, + claim.reservationOwnerId, + claim.reservationFence, + claim.ownerId, + claim.fence, + epochMillis(clock.instant())); + return new PendingTransition(result.snapshot(), result.transitioned()); + } + + /** Renew only the exact current, active claim before its expiry. */ + public Snapshot renew(ClaimHandle claim, Phase expectedPhase, State expectedState) { + requireMutationCapability(); + requireClaim(claim); + Instant now = clock.instant(); + return repository.renew( + claim.tuple, + claim.mutationDigest, + claim.ownerId, + claim.fence, + expectedPhase, + expectedState, + epochMillis(now), + epochMillis(now.plus(CLAIM_TTL))); + } + + /** + * Advance the current fence after the exact claim expires. Expiry leaves the phase and state + * unchanged; it is not evidence that Account authorization did not happen. + */ + public Snapshot expireClaim(ClaimHandle claim, Phase expectedPhase, State expectedState) { + requireMutationCapability(); + requireClaim(claim); + return repository.expireClaim( + claim.tuple, + claim.mutationDigest, + claim.ownerId, + claim.fence, + expectedPhase, + expectedState, + epochMillis(clock.instant())); + } + + /** + * Acquire one fresh state-scoped recovery claim after expiry. A RESERVED claim can only finish + * the first pending transition and issue once; a pending claim can only recover Account's + * original response; an authorized claim can only look up that same response and record the + * original bounded owner handoff. Original reservation owner/fence evidence remains immutable. + */ + public Optional acquireAuthorizationRecoveryClaim( + StartSessionPreAuthorizationReservationTuple tuple) { + requireMutationCapability(); + Objects.requireNonNull(tuple, "tuple is required"); + Instant now = clock.instant(); + UUID recoveryOwnerId = UUID.randomUUID(); + Optional acquired = + repository.acquireRecoveryClaim( + tuple, recoveryOwnerId, epochMillis(now), epochMillis(now.plus(CLAIM_TTL))); + return acquired.map( + result -> + new RecoveryAcquisition( + result.snapshot(), + new ClaimHandle( + tuple, + tuple.mutationDigest(), + result.reservationOwnerId(), + recoveryOwnerId, + result.snapshot().reservationClaimFence(), + result.snapshot().claimFence(), + result.snapshot().claimPurpose()))); + } + + /** + * Enriches the exact live authorization-pending reservation with the original response returned + * by the authenticated Account client. Callers must not derive this value from caller assertions; + * the shared tuple validates structure but does not establish Account authority or source + * freshness. Only its canonical post-authorization tuple is persisted; the opaque reference is + * not. + */ + public AuthorizationCompletion completeAuthorization( + ClaimHandle claim, StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple) { + requireMutationCapability(); + requirePostAuthorizationBinding(claim, postAuthorizationTuple); + long now = epochMillis(clock.instant()); + if (StartSessionAuthorityEvidenceBundle.decode( + postAuthorizationTuple.authorityEvidenceBundleBytes()) + .expiresAt() + .toEpochMilli() + <= now) { + throw new StaleReservationClaimException(claim.controlPlaneRequestId()); + } + StartSessionPreAuthorizationReservationRepository.AuthorizationTransitionResult result = + repository.completeAuthorization( + claim.tuple, + claim.mutationDigest, + claim.reservationOwnerId, + claim.reservationFence, + claim.ownerId, + claim.fence, + postAuthorizationTuple.canonicalJson(), + now); + return new AuthorizationCompletion(result.snapshot(), result.transitioned()); + } + + /** + * Persists the exact owner handoff before any external forward call. Only the first successful + * exact transition returns {@code mayDispatch=true}; duplicates only observe the pending row. + */ + public OwnerExecutionTransition beginOwnerExecution( + ClaimHandle claim, + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple, + OwnerExecutionHandoff handoff) { + requireMutationCapability(); + requirePostAuthorizationBinding(claim, postAuthorizationTuple); + Objects.requireNonNull(handoff, "owner execution handoff is required"); + long now = epochMillis(clock.instant()); + if (StartSessionAuthorityEvidenceBundle.decode( + postAuthorizationTuple.authorityEvidenceBundleBytes()) + .expiresAt() + .toEpochMilli() + <= now) { + throw new StaleReservationClaimException(claim.controlPlaneRequestId()); + } + StartSessionPreAuthorizationReservationRepository.OwnerExecutionTransitionResult result = + repository.beginOwnerExecution( + claim.tuple, + claim.mutationDigest, + claim.reservationOwnerId, + claim.reservationFence, + claim.ownerId, + claim.fence, + postAuthorizationTuple.canonicalJson(), + handoff.handoffId(), + now); + return new OwnerExecutionTransition(result.snapshot(), result.mayDispatch()); + } + + /** + * Read-only exact post-authorization snapshot; it does not revalidate authority or claim + * freshness and is not a commit-spanning compare-and-set proof. + */ + public Optional findAuthorizedExact( + StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + return repository.findAuthorizedExact(tuple); + } + + private static void requirePostAuthorizationBinding( + ClaimHandle claim, StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple) { + requireClaim(claim); + Objects.requireNonNull(postAuthorizationTuple, "post-authorization tuple is required"); + if (!claim + .tuple + .canonicalJson() + .equals(postAuthorizationTuple.preAuthorizationTuple().canonicalJson()) + || !claim.mutationDigest.equals(postAuthorizationTuple.mutationDigest()) + || !claim.reservationOwnerId.equals(postAuthorizationTuple.reservationOwnerId()) + || claim.reservationFence != postAuthorizationTuple.reservationClaimFence()) { + throw new IdempotencyConflictException(claim.controlPlaneRequestId()); + } + } + + private static void requireClaim(ClaimHandle claim) { + Objects.requireNonNull(claim, "claim is required"); + } + + private static long epochMillis(Instant instant) { + long millis = instant.toEpochMilli(); + if (millis <= 0) { + throw new IllegalArgumentException("reservation time must be after the Unix epoch"); + } + return millis; + } + + public enum Phase { + ACCOUNT_AUTHORIZATION, + OWNER_EXECUTION + } + + public enum State { + RESERVED, + AUTHORIZATION_PENDING, + AUTHORIZED, + OWNER_EXECUTION_PENDING + } + + public enum ClaimState { + ACTIVE, + EXPIRED + } + + public enum ReadPurpose { + ISSUE, + RECOVER + } + + public enum ClaimPurpose { + ORIGINAL, + RESERVED_RECOVERY_ISSUE, + AUTHORIZATION_RECOVERY, + AUTHORIZED_RESPONSE_RECOVERY + } + + public record Snapshot( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + Phase phase, + State state, + long reservationClaimFence, + long claimFence, + long claimExpiresAtEpochMillis, + ClaimState claimState, + ClaimPurpose claimPurpose) { + public Snapshot { + Objects.requireNonNull(tuple, "tuple is required"); + Objects.requireNonNull(mutationDigest, "mutationDigest is required"); + Objects.requireNonNull(phase, "phase is required"); + Objects.requireNonNull(state, "state is required"); + Objects.requireNonNull(claimState, "claimState is required"); + if (reservationClaimFence != 1 || claimFence < reservationClaimFence) { + throw new IllegalArgumentException("reservation claim fences are invalid"); + } + if (claimExpiresAtEpochMillis <= 0) { + throw new IllegalArgumentException("claim expiry must be positive"); + } + if (!tuple.mutationDigest().equals(mutationDigest)) { + throw new IllegalArgumentException("stored mutationDigest does not match the typed tuple"); + } + if ((phase == Phase.ACCOUNT_AUTHORIZATION && state == State.OWNER_EXECUTION_PENDING) + || (phase == Phase.OWNER_EXECUTION && state != State.OWNER_EXECUTION_PENDING)) { + throw new IllegalArgumentException("reservation phase and state are inconsistent"); + } + if (claimState == ClaimState.EXPIRED + ? claimPurpose != null + : !purposeAllowedForState(state, claimPurpose)) { + throw new IllegalArgumentException("reservation claim purpose and state are inconsistent"); + } + if (claimState == ClaimState.ACTIVE + && ((claimPurpose == ClaimPurpose.ORIGINAL && claimFence != reservationClaimFence) + || (claimPurpose != ClaimPurpose.ORIGINAL && claimFence <= reservationClaimFence))) { + throw new IllegalArgumentException("reservation claim purpose and fence are inconsistent"); + } + } + } + + /** Exact immutable post-authorization state; no raw or encrypted opaque reference is included. */ + public record AuthorizedSnapshot( + Snapshot reservationSnapshot, + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple, + UUID reservationOwnerId, + UUID currentClaimOwnerId, + OwnerExecutionHandoff handoff) { + public AuthorizedSnapshot { + Objects.requireNonNull(reservationSnapshot, "reservationSnapshot is required"); + Objects.requireNonNull(postAuthorizationTuple, "postAuthorizationTuple is required"); + requireNonNil(reservationOwnerId, "reservationOwnerId"); + if (reservationSnapshot.claimState() == ClaimState.ACTIVE) { + requireNonNil(currentClaimOwnerId, "currentClaimOwnerId"); + } else if (currentClaimOwnerId != null) { + throw new IllegalArgumentException( + "expired reservation cannot retain a current claim owner"); + } + if (!reservationSnapshot + .tuple() + .canonicalJson() + .equals(postAuthorizationTuple.preAuthorizationTuple().canonicalJson()) + || !reservationOwnerId.equals(postAuthorizationTuple.reservationOwnerId()) + || reservationSnapshot.reservationClaimFence() + != postAuthorizationTuple.reservationClaimFence() + || (reservationSnapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && reservationSnapshot.state() == State.AUTHORIZED + && handoff != null) + || (reservationSnapshot.phase() == Phase.OWNER_EXECUTION + && reservationSnapshot.state() == State.OWNER_EXECUTION_PENDING + && handoff == null) + || (reservationSnapshot.state() != State.AUTHORIZED + && reservationSnapshot.state() != State.OWNER_EXECUTION_PENDING)) { + throw new IllegalArgumentException("post-authorization snapshot is inconsistent"); + } + } + } + + /** Immutable handoff identity written before the owner allocates its attempt and fence. */ + public record OwnerExecutionHandoff(UUID handoffId) { + public OwnerExecutionHandoff { + requireNonNil(handoffId, "handoffId"); + } + } + + public record AuthorizationCompletion(AuthorizedSnapshot snapshot, boolean transitioned) { + public AuthorizationCompletion { + Objects.requireNonNull(snapshot, "snapshot is required"); + } + } + + public record OwnerExecutionTransition(AuthorizedSnapshot snapshot, boolean mayDispatch) { + public OwnerExecutionTransition { + Objects.requireNonNull(snapshot, "snapshot is required"); + if (mayDispatch + && (snapshot.reservationSnapshot().phase() != Phase.OWNER_EXECUTION + || snapshot.reservationSnapshot().state() != State.OWNER_EXECUTION_PENDING + || snapshot.handoff() == null)) { + throw new IllegalArgumentException("dispatch requires the durable exact owner handoff"); + } + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(field + " must not be nil"); + } + } + + private void requireMutationCapability() { + if (mutationCapability == null) { + throw new UnsupportedOperationException( + "StartSession reservation mutations are disabled for production construction"); + } + } + + private static final class MutationCapability { + private MutationCapability() {} + } + + private static boolean purposeAllowedForState(State state, ClaimPurpose purpose) { + if (purpose == null) { + return false; + } + return switch (state) { + case RESERVED -> + purpose == ClaimPurpose.ORIGINAL || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE; + case AUTHORIZATION_PENDING -> + purpose == ClaimPurpose.ORIGINAL + || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE + || purpose == ClaimPurpose.AUTHORIZATION_RECOVERY; + case AUTHORIZED, OWNER_EXECUTION_PENDING -> + purpose == ClaimPurpose.ORIGINAL + || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE + || purpose == ClaimPurpose.AUTHORIZATION_RECOVERY + || purpose == ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY; + }; + } + + private static boolean isIssueClaimPurpose(ClaimPurpose purpose) { + return purpose == ClaimPurpose.ORIGINAL || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE; + } + + public static boolean claimPurposeAllowsRead( + Snapshot snapshot, ReadPurpose purpose, UUID reservationOwnerId, UUID currentClaimOwnerId) { + Objects.requireNonNull(purpose, "purpose is required"); + if (purpose == ReadPurpose.ISSUE) { + return snapshot.state() == State.AUTHORIZATION_PENDING + && ((snapshot.claimPurpose() == ClaimPurpose.ORIGINAL + && reservationOwnerId.equals(currentClaimOwnerId) + && snapshot.claimFence() == snapshot.reservationClaimFence()) + || (snapshot.claimPurpose() == ClaimPurpose.RESERVED_RECOVERY_ISSUE + && !reservationOwnerId.equals(currentClaimOwnerId) + && snapshot.claimFence() > snapshot.reservationClaimFence())); + } + return !reservationOwnerId.equals(currentClaimOwnerId) + && snapshot.claimFence() > snapshot.reservationClaimFence() + && (snapshot.state() == State.AUTHORIZATION_PENDING + && snapshot.claimPurpose() == ClaimPurpose.AUTHORIZATION_RECOVERY + || snapshot.state() == State.AUTHORIZED + && (snapshot.claimPurpose() == ClaimPurpose.AUTHORIZATION_RECOVERY + || snapshot.claimPurpose() == ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY)); + } + + /** Opaque capability returned only to the caller that acquired a new claim. */ + public static final class ClaimHandle { + private final StartSessionPreAuthorizationReservationTuple tuple; + private final String mutationDigest; + private final UUID reservationOwnerId; + private final UUID ownerId; + private final long reservationFence; + private final long fence; + private final ClaimPurpose purpose; + + private ClaimHandle( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + UUID ownerId, + long reservationFence, + long fence, + ClaimPurpose purpose) { + this.tuple = Objects.requireNonNull(tuple, "tuple is required"); + this.mutationDigest = Objects.requireNonNull(mutationDigest, "mutationDigest is required"); + this.reservationOwnerId = + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + this.ownerId = Objects.requireNonNull(ownerId, "ownerId is required"); + this.reservationFence = reservationFence; + this.fence = fence; + this.purpose = Objects.requireNonNull(purpose, "claim purpose is required"); + if (reservationOwnerId.equals(new UUID(0L, 0L)) + || ownerId.equals(new UUID(0L, 0L)) + || reservationFence <= 0 + || fence < reservationFence + || (purpose == ClaimPurpose.ORIGINAL + && (!reservationOwnerId.equals(ownerId) || fence != reservationFence)) + || (purpose != ClaimPurpose.ORIGINAL + && (reservationOwnerId.equals(ownerId) || fence <= reservationFence))) { + throw new IllegalArgumentException("reservation claim fences are invalid"); + } + } + + public String controlPlaneRequestId() { + return tuple.controlPlaneRequestId(); + } + + public long claimFence() { + return fence; + } + + public StartSessionPreAuthorizationReservationTuple tuple() { + return tuple; + } + + public String mutationDigest() { + return mutationDigest; + } + + /** Original tuple owner/fence and current fenced claim, kept distinct during recovery. */ + public ClaimEvidence claimEvidence() { + return new ClaimEvidence(reservationOwnerId, reservationFence, ownerId, fence); + } + + public boolean isRecoveryLookupOnly() { + return purpose == ClaimPurpose.AUTHORIZATION_RECOVERY + || purpose == ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY; + } + + public ClaimPurpose purpose() { + return purpose; + } + } + + public record Acquisition(Snapshot snapshot, ClaimHandle claim) { + public Acquisition { + Objects.requireNonNull(snapshot, "snapshot is required"); + if (claim != null + && (claim.purpose != ClaimPurpose.ORIGINAL + || snapshot.claimPurpose() != ClaimPurpose.ORIGINAL + || snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() != State.RESERVED + || snapshot.claimState() != ClaimState.ACTIVE + || snapshot.claimFence() != claim.fence + || !snapshot.tuple().canonicalJson().equals(claim.tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(claim.mutationDigest))) { + throw new IllegalArgumentException("initial claim does not match its reservation"); + } + } + + public boolean newlyAcquired() { + return claim != null; + } + } + + public static final class PendingTransition { + private final Snapshot snapshot; + private final boolean mayDispatchAccountAuthorization; + + private PendingTransition(Snapshot snapshot, boolean mayDispatchAccountAuthorization) { + this.snapshot = Objects.requireNonNull(snapshot, "snapshot is required"); + this.mayDispatchAccountAuthorization = mayDispatchAccountAuthorization; + if (snapshot.state() != State.AUTHORIZATION_PENDING && mayDispatchAccountAuthorization) { + throw new IllegalArgumentException("dispatch requires durable AUTHORIZATION_PENDING state"); + } + } + + public Snapshot snapshot() { + return snapshot; + } + + public boolean mayDispatchAccountAuthorization() { + return mayDispatchAccountAuthorization; + } + } + + public record RecoveryAcquisition(Snapshot snapshot, ClaimHandle claim) { + public RecoveryAcquisition { + Objects.requireNonNull(snapshot, "snapshot is required"); + Objects.requireNonNull(claim, "claim is required"); + if (snapshot.phase() != Phase.ACCOUNT_AUTHORIZATION + || snapshot.state() == State.OWNER_EXECUTION_PENDING + || snapshot.claimState() != ClaimState.ACTIVE + || claim.purpose == ClaimPurpose.ORIGINAL + || snapshot.claimPurpose() != claim.purpose + || snapshot.claimFence() != claim.fence + || !snapshot.tuple().canonicalJson().equals(claim.tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(claim.mutationDigest)) { + throw new IllegalArgumentException("recovery claim is not a valid state-scoped claim"); + } + } + } + + public record ClaimEvidence( + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + public ClaimEvidence { + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + Objects.requireNonNull(currentClaimOwnerId, "currentClaimOwnerId is required"); + if (reservationClaimFence != 1 || currentClaimFence < reservationClaimFence) { + throw new IllegalArgumentException("reservation claim evidence is invalid"); + } + } + } + + public record CurrentClaimEvidence( + Snapshot snapshot, + UUID reservationOwnerId, + UUID currentClaimOwnerId, + ReadPurpose purpose, + long observedAtEpochMillis) { + public CurrentClaimEvidence { + Objects.requireNonNull(snapshot, "snapshot is required"); + Objects.requireNonNull(reservationOwnerId, "reservationOwnerId is required"); + Objects.requireNonNull(currentClaimOwnerId, "currentClaimOwnerId is required"); + Objects.requireNonNull(purpose, "purpose is required"); + if (observedAtEpochMillis <= 0L + || snapshot.claimExpiresAtEpochMillis() <= observedAtEpochMillis) { + throw new IllegalArgumentException("current claim evidence must be fresh and unexpired"); + } + } + } + + public static class IdempotencyConflictException extends RuntimeException { + public IdempotencyConflictException(String controlPlaneRequestId) { + super( + "controlPlaneRequestId is already bound to a different StartSession tuple: " + + controlPlaneRequestId); + } + } + + public static class StaleReservationClaimException extends RuntimeException { + public StaleReservationClaimException(String controlPlaneRequestId) { + super("StartSession reservation claim is stale: " + controlPlaneRequestId); + } + } + + public static class ReservationClaimNotExpiredException extends RuntimeException { + public ReservationClaimNotExpiredException(String controlPlaneRequestId) { + super("StartSession reservation claim has not expired: " + controlPlaneRequestId); + } + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java new file mode 100644 index 0000000000..145f53b78d --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTuple.java @@ -0,0 +1,140 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.SessionContext; + +/** Logging/Admin authority wrapper around the shared immutable StartSession tuple value. */ +public final class StartSessionPreAuthorizationReservationTuple { + public static final String TUPLE_SCHEMA_ID = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .TUPLE_SCHEMA_ID; + public static final String TUPLE_SCHEMA_VERSION = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .TUPLE_SCHEMA_VERSION; + public static final int MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .MAX_CONTROL_PLANE_REQUEST_ID_UTF8_BYTES; + public static final int MAX_CANONICAL_TUPLE_UTF8_BYTES = 8 * 1_024; + + private final net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + value; + private final boolean authorityDerived; + + private StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple value, + boolean authorityDerived) { + this.value = Objects.requireNonNull(value, "tuple value is required"); + this.authorityDerived = authorityDerived; + } + + /** Builds the tuple from the current authenticated tenant-admin request context. */ + public static StartSessionPreAuthorizationReservationTuple fromCurrentTenantAdmin( + String controlPlaneRequestId, StartSessionOperatorAction action) { + Objects.requireNonNull(action, "action is required"); + if (SessionContext.isInternalService() || !SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalArgumentException("a human control-ui identity is required"); + } + String tenantId = action.scope().tenantId().toString(); + if (!SessionContext.getScopedRoles(tenantId).contains("tenantAdmin")) { + throw new IllegalArgumentException("tenantAdmin authority is required for the target tenant"); + } + UUID actorAccountId = requireCanonicalUuid(SessionContext.getAccountId(), "actor accountId"); + return new StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .createHuman(controlPlaneRequestId, actorAccountId, action), + true); + } + + /** Rehydrates only tuple contents; persisted bytes do not establish request authority. */ + public static StartSessionPreAuthorizationReservationTuple fromCanonicalJson(String json) { + return new StartSessionPreAuthorizationReservationTuple( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(json), + false); + } + + public String actionFamily() { + return value.actionFamily(); + } + + public String controlPlaneRequestId() { + return value.controlPlaneRequestId(); + } + + public HumanActor actor() { + return new HumanActor(value.actor().accountId()); + } + + public NoAutomationPolicy automationPolicy() { + return NoAutomationPolicy.ABSENT; + } + + public StartSessionOperatorAction action() { + return value.action(); + } + + public boolean isAuthorityDerived() { + return authorityDerived; + } + + /** Validate a stable request key without silently normalizing or changing its identity. */ + public static String requireCanonicalControlPlaneRequestId(String value) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .requireCanonicalControlPlaneRequestId(value); + } + + public String targetOwner() { + return value.targetOwner(); + } + + /** Returns ADR 0047's digest over the seven action-schema grammar fields. */ + public String mutationDigest() { + return value.mutationDigest(); + } + + /** Returns the single shared canonical encoding for ADR 0048's typed tuple. */ + public String canonicalJson() { + return value.canonicalJson(); + } + + public record HumanActor(UUID accountId) { + public HumanActor { + Objects.requireNonNull(accountId, "actor accountId is required"); + if (accountId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("actor accountId must not be nil"); + } + } + } + + public enum NoAutomationPolicy { + ABSENT + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof StartSessionPreAuthorizationReservationTuple that + && value.equals(that.value); + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + private static UUID requireCanonicalUuid(String value, String fieldName) { + Objects.requireNonNull(value, fieldName + " is required"); + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID", exception); + } + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID"); + } + return parsed; + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java new file mode 100644 index 0000000000..458ec5c22d --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java @@ -0,0 +1,977 @@ +package net.firedevops.firemud.loggingadmin.repository; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations.START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; + +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizedSnapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +/** jOOQ persistence for the single-key StartSession ADR 0048 reservation phase. */ +@Repository +public class StartSessionPreAuthorizationReservationRepository { + private static final StartSessionPreAuthorizationReservations TABLE = + START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; + private static final Field POST_AUTHORIZATION_TUPLE_JSON = + DSL.field(DSL.name("post_authorization_execution_tuple_json"), String.class); + private static final Field OWNER_EXECUTION_HANDOFF_ID = + DSL.field(DSL.name("owner_execution_handoff_id"), UUID.class); + private static final Field CLAIM_PURPOSE = + DSL.field(DSL.name("claim_purpose"), String.class); + private static final Field[] FULL_ROW_FIELDS = { + TABLE.CONTROL_PLANE_REQUEST_ID, + TABLE.PRE_AUTHORIZATION_TUPLE_JSON, + TABLE.MUTATION_DIGEST, + TABLE.PHASE, + TABLE.STATE, + TABLE.RESERVATION_OWNER_ID, + TABLE.RESERVATION_CLAIM_FENCE, + TABLE.CLAIM_OWNER_ID, + TABLE.CLAIM_FENCE, + TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, + TABLE.CLAIM_STATE, + TABLE.CREATED_AT_EPOCH_MS, + TABLE.UPDATED_AT_EPOCH_MS, + POST_AUTHORIZATION_TUPLE_JSON, + OWNER_EXECUTION_HANDOFF_ID, + CLAIM_PURPOSE + }; + + private final DSLContext dsl; + private final MutationCapability mutationCapability; + + @Autowired + public StartSessionPreAuthorizationReservationRepository(DSLContext dsl) { + this(dsl, null); + } + + private StartSessionPreAuthorizationReservationRepository( + DSLContext dsl, MutationCapability mutationCapability) { + this.dsl = dsl; + this.mutationCapability = mutationCapability; + } + + public AcquireResult acquire( + StartSessionPreAuthorizationReservationTuple tuple, + UUID ownerId, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireMutationCapability(); + requireBoundedClaim(ownerId, nowEpochMillis, expiresAtEpochMillis); + if (!tuple.isAuthorityDerived()) { + throw new IllegalArgumentException( + "initial reservation requires an authority-derived StartSession tuple"); + } + String tupleJson = tuple.canonicalJson(); + String mutationDigest = tuple.mutationDigest(); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int inserted = + tx.insertInto(TABLE) + .set(TABLE.CONTROL_PLANE_REQUEST_ID, tuple.controlPlaneRequestId()) + .set(TABLE.PRE_AUTHORIZATION_TUPLE_JSON, tupleJson) + .set(TABLE.MUTATION_DIGEST, mutationDigest) + .set(TABLE.PHASE, Phase.ACCOUNT_AUTHORIZATION.name()) + .set(TABLE.STATE, State.RESERVED.name()) + .set(TABLE.RESERVATION_OWNER_ID, ownerId) + .set(TABLE.RESERVATION_CLAIM_FENCE, 1L) + .set(TABLE.CLAIM_OWNER_ID, ownerId) + .set(TABLE.CLAIM_FENCE, 1L) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) + .set(CLAIM_PURPOSE, ClaimPurpose.ORIGINAL.name()) + .set(TABLE.CREATED_AT_EPOCH_MS, nowEpochMillis) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .onConflict(TABLE.CONTROL_PLANE_REQUEST_ID) + .doNothing() + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new IllegalStateException("reservation row was not visible after acquire"); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + return new AcquireResult(snapshot, inserted == 1); + }); + } + + public Optional find(String controlPlaneRequestId) { + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + Record row = selectFullRowByRequestId(dsl, controlPlaneRequestId, false); + return Optional.ofNullable(row).map(this::toSnapshot); + } + + public Optional findExact(StartSessionPreAuthorizationReservationTuple tuple) { + return find(tuple.controlPlaneRequestId()) + .map( + snapshot -> { + if (!snapshot.tuple().canonicalJson().equals(tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(tuple.mutationDigest())) { + throw new StartSessionPreAuthorizationReservationService + .IdempotencyConflictException(tuple.controlPlaneRequestId()); + } + return snapshot; + }); + } + + /** Reads an exact, current Account-authorization claim without locking or changing the row. */ + public Optional readCurrentClaim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + StartSessionPreAuthorizationReservationService.ReadPurpose purpose, + long observedAtEpochMillis) { + Objects.requireNonNull(tuple, "tuple is required"); + Objects.requireNonNull(purpose, "purpose is required"); + requireClaimOwner(currentClaimOwnerId, currentClaimFence, observedAtEpochMillis); + if (reservationOwnerId == null + || reservationOwnerId.equals(new UUID(0L, 0L)) + || reservationClaimFence <= 0L) { + throw new IllegalArgumentException("original reservation claim identity must be positive"); + } + + Record row = selectFullRowByRequestId(dsl, tuple.controlPlaneRequestId(), false); + if (row == null) { + return Optional.empty(); + } + + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, tuple.mutationDigest()); + UUID storedReservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); + UUID storedClaimOwnerId = row.get(TABLE.CLAIM_OWNER_ID); + boolean exactCurrentClaim = + reservationOwnerId.equals(storedReservationOwnerId) + && reservationClaimFence == snapshot.reservationClaimFence() + && currentClaimOwnerId.equals(storedClaimOwnerId) + && currentClaimFence == snapshot.claimFence() + && snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.claimState() == ClaimState.ACTIVE + && snapshot.claimExpiresAtEpochMillis() > observedAtEpochMillis + && StartSessionPreAuthorizationReservationService.claimPurposeAllowsRead( + snapshot, purpose, reservationOwnerId, currentClaimOwnerId); + if (!exactCurrentClaim) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + if (purpose == StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER + && snapshot.state() == State.AUTHORIZED) { + toAuthorizedSnapshot(row); + } + return Optional.of( + new CurrentClaimResult(snapshot, storedReservationOwnerId, storedClaimOwnerId)); + } + + public TransitionResult markAuthorizationPending( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + long nowEpochMillis) { + requireMutationCapability(); + requireCurrentClaimIdentity( + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .set(TABLE.STATE, State.AUTHORIZATION_PENDING.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.RESERVED.name())) + .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) + .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) + .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and( + CLAIM_PURPOSE.in( + ClaimPurpose.ORIGINAL.name(), + ClaimPurpose.RESERVED_RECOVERY_ISSUE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated == 1) { + return new TransitionResult(snapshot, true); + } + if (isCurrentClaim(row, currentClaimOwnerId, currentClaimFence, nowEpochMillis) + && snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING + && isIssueClaimPurpose(snapshot.claimPurpose())) { + return new TransitionResult(snapshot, false); + } + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + }); + } + + /** Original-claim overload retained for focused repository tests and original callers. */ + public TransitionResult markAuthorizationPending( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + long nowEpochMillis) { + requireMutationCapability(); + return markAuthorizationPending( + tuple, mutationDigest, ownerId, claimFence, ownerId, claimFence, nowEpochMillis); + } + + /** + * Atomically stores Account's full post-authorization identity on the exact live claim. The + * post-tuple is structural evidence only and contains no opaque authorization reference. + */ + public AuthorizationTransitionResult completeAuthorization( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + String postAuthorizationTupleJson, + long nowEpochMillis) { + requireMutationCapability(); + requireCurrentClaimIdentity( + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + Objects.requireNonNull(tuple, "tuple is required"); + StartSessionPostAuthorizationExecutionTuple postTuple = + decodePostAuthorizationTuple(postAuthorizationTupleJson); + requirePostTupleBinding( + tuple, mutationDigest, reservationOwnerId, reservationClaimFence, postTuple); + if (StartSessionAuthorityEvidenceBundle.decode(postTuple.authorityEvidenceBundleBytes()) + .expiresAt() + .toEpochMilli() + <= nowEpochMillis) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw stale(tuple); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + requireExactLiveClaim( + row, + snapshot, + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + + if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING) { + if (!isPendingAuthorizationClaimPurpose(snapshot.claimPurpose())) { + throw stale(tuple); + } + int updated = + tx.update(TABLE) + .set(TABLE.STATE, State.AUTHORIZED.name()) + .set(POST_AUTHORIZATION_TUPLE_JSON, postAuthorizationTupleJson) + .set(OWNER_EXECUTION_HANDOFF_ID, (UUID) null) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.AUTHORIZATION_PENDING.name())) + .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) + .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) + .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .and(POST_AUTHORIZATION_TUPLE_JSON.isNull()) + .execute(); + if (updated != 1) { + throw stale(tuple); + } + return new AuthorizationTransitionResult( + toAuthorizedSnapshot( + selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true)), + true); + } + + if ((snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZED) + || (snapshot.phase() == Phase.OWNER_EXECUTION + && snapshot.state() == State.OWNER_EXECUTION_PENDING)) { + if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && !isAuthorizedResponseClaimPurpose(snapshot.claimPurpose())) { + throw stale(tuple); + } + String persistedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); + if (!postAuthorizationTupleJson.equals(persistedTuple)) { + throw conflict(tuple); + } + return new AuthorizationTransitionResult(toAuthorizedSnapshot(row), false); + } + throw stale(tuple); + }); + } + + /** + * Atomically records the immutable owner handoff. A duplicate exact observation never grants a + * second dispatch; the first successful AUTHORIZED-to-pending transition does. + */ + public OwnerExecutionTransitionResult beginOwnerExecution( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + String postAuthorizationTupleJson, + UUID handoffId, + long nowEpochMillis) { + requireMutationCapability(); + requireCurrentClaimIdentity( + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + requireNonNil(handoffId, "handoffId"); + Objects.requireNonNull(tuple, "tuple is required"); + StartSessionPostAuthorizationExecutionTuple postTuple = + decodePostAuthorizationTuple(postAuthorizationTupleJson); + requirePostTupleBinding( + tuple, mutationDigest, reservationOwnerId, reservationClaimFence, postTuple); + if (StartSessionAuthorityEvidenceBundle.decode(postTuple.authorityEvidenceBundleBytes()) + .expiresAt() + .toEpochMilli() + <= nowEpochMillis) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw stale(tuple); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + requireExactLiveClaim( + row, + snapshot, + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + boolean mayBeginOwnerExecution = + snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZED; + boolean mayReplayOwnerExecution = + snapshot.phase() == Phase.OWNER_EXECUTION + && snapshot.state() == State.OWNER_EXECUTION_PENDING; + if (!mayBeginOwnerExecution && !mayReplayOwnerExecution) { + throw stale(tuple); + } + if (mayBeginOwnerExecution && !isOwnerHandoffClaimPurpose(snapshot.claimPurpose())) { + throw stale(tuple); + } + String persistedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); + if (!postAuthorizationTupleJson.equals(persistedTuple)) { + throw conflict(tuple); + } + + if (mayBeginOwnerExecution) { + int updated = + tx.update(TABLE) + .set(TABLE.PHASE, Phase.OWNER_EXECUTION.name()) + .set(TABLE.STATE, State.OWNER_EXECUTION_PENDING.name()) + .set(OWNER_EXECUTION_HANDOFF_ID, handoffId) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.AUTHORIZED.name())) + .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) + .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) + .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .and(POST_AUTHORIZATION_TUPLE_JSON.eq(postAuthorizationTupleJson)) + .and(OWNER_EXECUTION_HANDOFF_ID.isNull()) + .execute(); + if (updated != 1) { + throw stale(tuple); + } + return new OwnerExecutionTransitionResult( + toAuthorizedSnapshot( + selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true)), + true); + } + + if (mayReplayOwnerExecution) { + if (!handoffId.equals(row.get(OWNER_EXECUTION_HANDOFF_ID))) { + throw conflict(tuple); + } + return new OwnerExecutionTransitionResult(toAuthorizedSnapshot(row), false); + } + throw stale(tuple); + }); + } + + /** Read-only storage snapshot of the exact full post-authorization tuple and any handoff. */ + public Optional findAuthorizedExact( + StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "tuple is required"); + Record row = selectFullRowByRequestId(dsl, tuple.controlPlaneRequestId(), false); + if (row == null) { + return Optional.empty(); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, tuple.mutationDigest()); + if (snapshot.state() != State.AUTHORIZED && snapshot.state() != State.OWNER_EXECUTION_PENDING) { + return Optional.empty(); + } + return Optional.of(toAuthorizedSnapshot(row)); + } + + public Snapshot renew( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + Phase expectedPhase, + State expectedState, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireMutationCapability(); + requireClaimOwner(ownerId, claimFence, nowEpochMillis); + Objects.requireNonNull(expectedPhase, "expectedPhase is required"); + Objects.requireNonNull(expectedState, "expectedState is required"); + requireBoundedClaim(ownerId, nowEpochMillis, expiresAtEpochMillis); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(expectedPhase.name())) + .and(TABLE.STATE.eq(expectedState.name())) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated != 1) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + return snapshot; + }); + } + + public Snapshot expireClaim( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID ownerId, + long claimFence, + Phase expectedPhase, + State expectedState, + long nowEpochMillis) { + requireMutationCapability(); + requireClaimOwner(ownerId, claimFence, nowEpochMillis); + Objects.requireNonNull(expectedPhase, "expectedPhase is required"); + Objects.requireNonNull(expectedState, "expectedState is required"); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .setNull(TABLE.CLAIM_OWNER_ID) + .set(TABLE.CLAIM_FENCE, TABLE.CLAIM_FENCE.add(1L)) + .set(TABLE.CLAIM_STATE, ClaimState.EXPIRED.name()) + .set(CLAIM_PURPOSE, (String) null) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(expectedPhase.name())) + .and(TABLE.STATE.eq(expectedState.name())) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated == 1) { + return snapshot; + } + if (isCurrentClaim(row, ownerId, claimFence, nowEpochMillis)) { + throw new StartSessionPreAuthorizationReservationService + .ReservationClaimNotExpiredException(tuple.controlPlaneRequestId()); + } + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + }); + } + + public Optional acquireRecoveryClaim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID recoveryOwnerId, + long nowEpochMillis, + long expiresAtEpochMillis) { + requireMutationCapability(); + requireBoundedClaim(recoveryOwnerId, nowEpochMillis, expiresAtEpochMillis); + String mutationDigest = tuple.mutationDigest(); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + return Optional.empty(); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + ClaimPurpose recoveryPurpose = recoveryPurpose(snapshot.phase(), snapshot.state()); + if (recoveryPurpose == null) { + return Optional.empty(); + } + UUID reservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); + UUID previousOwnerId = row.get(TABLE.CLAIM_OWNER_ID); + String previousClaimState = row.get(TABLE.CLAIM_STATE); + long previousFence = row.get(TABLE.CLAIM_FENCE); + long previousExpiry = row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS); + if (!ClaimState.EXPIRED.name().equals(previousClaimState) + && !(ClaimState.ACTIVE.name().equals(previousClaimState) + && previousExpiry <= nowEpochMillis)) { + return Optional.empty(); + } + if (reservationOwnerId.equals(recoveryOwnerId) + || recoveryOwnerId.equals(previousOwnerId)) { + return Optional.empty(); + } + if (snapshot.state() == State.AUTHORIZED) { + toAuthorizedSnapshot(row); + } + long recoveryFence = Math.addExact(previousFence, 1L); + int updated = + tx.update(TABLE) + .set(TABLE.CLAIM_OWNER_ID, recoveryOwnerId) + .set(TABLE.CLAIM_FENCE, recoveryFence) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) + .set(CLAIM_PURPOSE, recoveryPurpose.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(snapshot.state().name())) + .and(TABLE.CLAIM_FENCE.eq(previousFence)) + .and(TABLE.CLAIM_STATE.eq(previousClaimState)) + .and( + previousOwnerId == null + ? TABLE.CLAIM_OWNER_ID.isNull() + : TABLE.CLAIM_OWNER_ID.eq(previousOwnerId)) + .and( + snapshot.claimPurpose() == null + ? CLAIM_PURPOSE.isNull() + : CLAIM_PURPOSE.eq(snapshot.claimPurpose().name())) + .and( + ClaimState.EXPIRED.name().equals(previousClaimState) + ? DSL.trueCondition() + : TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) + .execute(); + if (updated != 1) { + return Optional.empty(); + } + Record updatedRow = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (updatedRow == null) { + throw new IllegalStateException("recovery claim row disappeared after update"); + } + return Optional.of(new RecoveryClaimResult(toSnapshot(updatedRow), reservationOwnerId)); + }); + } + + private StartSessionPostAuthorizationExecutionTuple decodePostAuthorizationTuple(String json) { + if (json == null || json.isEmpty()) { + throw new IllegalArgumentException("post-authorization tuple is required"); + } + StartSessionPostAuthorizationExecutionTuple decoded = + StartSessionPostAuthorizationExecutionTuple.decode(json.getBytes(StandardCharsets.UTF_8)); + if (!decoded.canonicalJson().equals(json)) { + throw new IllegalArgumentException("post-authorization tuple must be canonical JSON"); + } + return decoded; + } + + private void requirePostTupleBinding( + StartSessionPreAuthorizationReservationTuple tuple, + String mutationDigest, + UUID reservationOwnerId, + long reservationClaimFence, + StartSessionPostAuthorizationExecutionTuple postTuple) { + if (!tuple.controlPlaneRequestId().equals(postTuple.controlPlaneRequestId()) + || !tuple.canonicalJson().equals(postTuple.preAuthorizationTuple().canonicalJson()) + || !tuple.mutationDigest().equals(mutationDigest) + || !postTuple.mutationDigest().equals(mutationDigest) + || !reservationOwnerId.equals(postTuple.reservationOwnerId()) + || reservationClaimFence != postTuple.reservationClaimFence()) { + throw conflict(tuple); + } + } + + private static ClaimPurpose recoveryPurpose(Phase phase, State state) { + if (phase != Phase.ACCOUNT_AUTHORIZATION) { + return null; + } + return switch (state) { + case RESERVED -> ClaimPurpose.RESERVED_RECOVERY_ISSUE; + case AUTHORIZATION_PENDING -> ClaimPurpose.AUTHORIZATION_RECOVERY; + case AUTHORIZED -> ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY; + case OWNER_EXECUTION_PENDING -> null; + }; + } + + private static boolean isIssueClaimPurpose(ClaimPurpose purpose) { + return purpose == ClaimPurpose.ORIGINAL || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE; + } + + private static boolean isPendingAuthorizationClaimPurpose(ClaimPurpose purpose) { + return purpose == ClaimPurpose.ORIGINAL + || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE + || purpose == ClaimPurpose.AUTHORIZATION_RECOVERY; + } + + private static boolean isAuthorizedResponseClaimPurpose(ClaimPurpose purpose) { + return purpose == ClaimPurpose.ORIGINAL + || purpose == ClaimPurpose.RESERVED_RECOVERY_ISSUE + || purpose == ClaimPurpose.AUTHORIZATION_RECOVERY + || purpose == ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY; + } + + private static boolean isOwnerHandoffClaimPurpose(ClaimPurpose purpose) { + return isAuthorizedResponseClaimPurpose(purpose); + } + + private void requireCurrentClaimIdentity( + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + long nowEpochMillis) { + requireNonNil(reservationOwnerId, "reservationOwnerId"); + requireNonNil(currentClaimOwnerId, "currentClaimOwnerId"); + if (reservationClaimFence <= 0L + || currentClaimFence < reservationClaimFence + || nowEpochMillis <= 0L) { + throw new IllegalArgumentException("reservation owner claim identity must be positive"); + } + } + + private void requireExactLiveClaim( + Record row, + Snapshot snapshot, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + long nowEpochMillis) { + if (!reservationOwnerId.equals(row.get(TABLE.RESERVATION_OWNER_ID)) + || reservationClaimFence != snapshot.reservationClaimFence() + || !currentClaimOwnerId.equals(row.get(TABLE.CLAIM_OWNER_ID)) + || currentClaimFence != snapshot.claimFence() + || snapshot.claimState() != ClaimState.ACTIVE + || snapshot.claimExpiresAtEpochMillis() <= nowEpochMillis) { + throw stale(snapshot.tuple()); + } + } + + private AuthorizedSnapshot toAuthorizedSnapshot(Record row) { + if (row == null) { + throw new IllegalStateException( + "StartSession row disappeared after post-authorization write"); + } + Snapshot snapshot = toSnapshot(row); + String storedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); + if (storedTuple == null) { + throw new IllegalStateException("authorized StartSession row is missing its post-tuple"); + } + StartSessionPostAuthorizationExecutionTuple postTuple; + try { + postTuple = decodePostAuthorizationTuple(storedTuple); + } catch (RuntimeException malformed) { + throw new IllegalStateException("stored StartSession post-authorization tuple is malformed"); + } + if (!snapshot.tuple().canonicalJson().equals(postTuple.preAuthorizationTuple().canonicalJson()) + || !snapshot.mutationDigest().equals(postTuple.mutationDigest()) + || !row.get(TABLE.RESERVATION_OWNER_ID).equals(postTuple.reservationOwnerId()) + || snapshot.reservationClaimFence() != postTuple.reservationClaimFence()) { + throw new IllegalStateException("stored StartSession post-tuple binding is inconsistent"); + } + + UUID handoffId = row.get(OWNER_EXECUTION_HANDOFF_ID); + OwnerExecutionHandoff handoff = null; + if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION && snapshot.state() == State.AUTHORIZED) { + if (handoffId != null) { + throw new IllegalStateException("authorized StartSession row has premature handoff fields"); + } + } else if (snapshot.phase() == Phase.OWNER_EXECUTION + && snapshot.state() == State.OWNER_EXECUTION_PENDING) { + if (handoffId == null) { + throw new IllegalStateException("owner-pending StartSession row is missing handoff fields"); + } + try { + handoff = new OwnerExecutionHandoff(handoffId); + } catch (RuntimeException malformed) { + throw new IllegalStateException("stored StartSession owner handoff is malformed"); + } + } else { + throw new IllegalStateException("StartSession row is not in a post-authorization state"); + } + return new AuthorizedSnapshot( + snapshot, + postTuple, + row.get(TABLE.RESERVATION_OWNER_ID), + row.get(TABLE.CLAIM_OWNER_ID), + handoff); + } + + private Record selectFullRowByRequestId( + DSLContext context, String controlPlaneRequestId, boolean forUpdate) { + var query = + context + .select(FULL_ROW_FIELDS) + .from(TABLE) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId)); + return forUpdate ? query.forUpdate().fetchOne() : query.fetchOne(); + } + + private static void requireNonNil(UUID value, String fieldName) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(fieldName + " must be a non-nil UUID"); + } + } + + private static StartSessionPreAuthorizationReservationService.StaleReservationClaimException + stale(StartSessionPreAuthorizationReservationTuple tuple) { + return new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + + private static StartSessionPreAuthorizationReservationService.IdempotencyConflictException + conflict(StartSessionPreAuthorizationReservationTuple tuple) { + return new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + + private void requireMutationCapability() { + if (mutationCapability == null) { + throw new UnsupportedOperationException( + "StartSession reservation writes are disabled for production construction"); + } + } + + private static final class MutationCapability { + private MutationCapability() {} + } + + private void requireBoundedClaim(UUID ownerId, long nowEpochMillis, long expiresAtEpochMillis) { + requireClaimOwner(ownerId, 1L, nowEpochMillis); + if (expiresAtEpochMillis <= nowEpochMillis + || expiresAtEpochMillis - nowEpochMillis + > StartSessionPreAuthorizationReservationService.CLAIM_TTL.toMillis()) { + throw new IllegalArgumentException("reservation claim must have a bounded positive expiry"); + } + } + + private void requireClaimOwner(UUID ownerId, long claimFence, long nowEpochMillis) { + if (ownerId == null + || ownerId.equals(new UUID(0L, 0L)) + || claimFence <= 0L + || nowEpochMillis <= 0L) { + throw new IllegalArgumentException("reservation claim identity and time must be positive"); + } + } + + private Snapshot toSnapshot(Record row) { + String requestId = row.get(TABLE.CONTROL_PLANE_REQUEST_ID); + String tupleJson = row.get(TABLE.PRE_AUTHORIZATION_TUPLE_JSON); + String storedDigest = row.get(TABLE.MUTATION_DIGEST); + StartSessionPreAuthorizationReservationTuple tuple; + try { + tuple = StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(tupleJson); + } catch (RuntimeException exception) { + throw new IllegalStateException( + "stored StartSession pre-authorization tuple is malformed for " + requestId, exception); + } + if (!requestId.equals(tuple.controlPlaneRequestId())) { + throw new IllegalStateException( + "stored StartSession tuple key does not match reservation key " + requestId); + } + String recomputedDigest = tuple.mutationDigest(); + if (!recomputedDigest.equals(storedDigest)) { + throw new IllegalStateException( + "stored StartSession mutationDigest does not match its full tuple for " + requestId); + } + Phase phase = enumValue(Phase.class, row.get(TABLE.PHASE), "phase", requestId); + State state = enumValue(State.class, row.get(TABLE.STATE), "state", requestId); + ClaimState claimState = + enumValue(ClaimState.class, row.get(TABLE.CLAIM_STATE), "claimState", requestId); + String storedClaimPurpose = row.get(CLAIM_PURPOSE); + ClaimPurpose claimPurpose = + storedClaimPurpose == null + ? null + : enumValue(ClaimPurpose.class, storedClaimPurpose, "claimPurpose", requestId); + UUID reservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); + UUID currentClaimOwnerId = row.get(TABLE.CLAIM_OWNER_ID); + long originalFence = row.get(TABLE.RESERVATION_CLAIM_FENCE); + long currentFence = row.get(TABLE.CLAIM_FENCE); + long createdAt = row.get(TABLE.CREATED_AT_EPOCH_MS); + long updatedAt = row.get(TABLE.UPDATED_AT_EPOCH_MS); + boolean supportedPhaseState = + (phase == Phase.ACCOUNT_AUTHORIZATION + && (state == State.RESERVED + || state == State.AUTHORIZATION_PENDING + || state == State.AUTHORIZED)) + || (phase == Phase.OWNER_EXECUTION && state == State.OWNER_EXECUTION_PENDING); + if (!supportedPhaseState + || reservationOwnerId == null + || reservationOwnerId.equals(new UUID(0L, 0L)) + || originalFence != 1L + || currentFence < originalFence + || createdAt <= 0L + || updatedAt <= 0L + || (claimState == ClaimState.ACTIVE + && (currentClaimOwnerId == null + || currentClaimOwnerId.equals(new UUID(0L, 0L)) + || claimPurpose == null + || (claimPurpose == ClaimPurpose.ORIGINAL + && (!reservationOwnerId.equals(currentClaimOwnerId) + || currentFence != originalFence)) + || (claimPurpose != ClaimPurpose.ORIGINAL + && (reservationOwnerId.equals(currentClaimOwnerId) + || currentFence <= originalFence)))) + || (claimState == ClaimState.EXPIRED + && (currentClaimOwnerId != null + || currentFence <= originalFence + || claimPurpose != null))) { + throw new IllegalStateException("stored StartSession reservation lifecycle is malformed"); + } + return new Snapshot( + tuple, + storedDigest, + phase, + state, + originalFence, + currentFence, + row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS), + claimState, + claimPurpose); + } + + private void requireExactTuple( + Record row, StartSessionPreAuthorizationReservationTuple tuple, String mutationDigest) { + if (!tuple.controlPlaneRequestId().equals(row.get(TABLE.CONTROL_PLANE_REQUEST_ID)) + || !tuple.canonicalJson().equals(row.get(TABLE.PRE_AUTHORIZATION_TUPLE_JSON)) + || !tuple.mutationDigest().equals(mutationDigest) + || !mutationDigest.equals(row.get(TABLE.MUTATION_DIGEST))) { + throw new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + } + + private boolean isCurrentClaim(Record row, UUID ownerId, long claimFence, long nowEpochMillis) { + return ownerId.equals(row.get(TABLE.CLAIM_OWNER_ID)) + && claimFence == row.get(TABLE.CLAIM_FENCE) + && ClaimState.ACTIVE.name().equals(row.get(TABLE.CLAIM_STATE)) + && row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS) > nowEpochMillis; + } + + private > T enumValue( + Class enumClass, String value, String fieldName, String requestId) { + try { + return Enum.valueOf(enumClass, value); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "stored StartSession reservation " + fieldName + " is invalid for " + requestId, + exception); + } + } + + public record AcquireResult(Snapshot snapshot, boolean created) {} + + public record TransitionResult(Snapshot snapshot, boolean transitioned) {} + + public record AuthorizationTransitionResult(AuthorizedSnapshot snapshot, boolean transitioned) {} + + public record OwnerExecutionTransitionResult(AuthorizedSnapshot snapshot, boolean mayDispatch) {} + + public record RecoveryClaimResult(Snapshot snapshot, UUID reservationOwnerId) {} + + public record CurrentClaimResult( + Snapshot snapshot, UUID reservationOwnerId, UUID currentClaimOwnerId) {} +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcService.java new file mode 100644 index 0000000000..0c785a911a --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcService.java @@ -0,0 +1,265 @@ +package net.firedevops.firemud.loggingadmin.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.sql.SQLTransientException; +import java.util.Arrays; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.CurrentClaimEvidence; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ReadPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.grpc.server.service.GrpcService; + +/** Read-only Account handoff for the exact current StartSession reservation claim. */ +@GrpcService +public class StartSessionReservationEvidenceGrpcService + extends StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceImplBase { + private final StartSessionPreAuthorizationReservationService reservationService; + private final StartSessionReservationEvidenceLeafApproval leafApproval; + private final String workloadNamespace; + + public StartSessionReservationEvidenceGrpcService( + StartSessionPreAuthorizationReservationService reservationService, + StartSessionReservationEvidenceLeafApproval leafApproval, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.reservationService = reservationService; + this.leafApproval = leafApproval; + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readCurrentClaimEvidence( + ReadCurrentClaimEvidenceRequest request, + StreamObserver responseObserver) { + if (SessionContext.hasAuthenticatedCallerContext() + || !isAccountPeer() + || !leafApproval.isApproved(GrpcPeerCertificateEvidence.current())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Account workload identity without caller context is required"); + return; + } + + ParsedRequest parsed; + try { + parsed = parseRequest(request); + } catch (IllegalArgumentException exception) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical StartSession reservation claim evidence is required"); + return; + } + + Optional current; + try { + current = + reservationService.readCurrentClaimEvidence( + parsed.controlPlaneRequestId(), + parsed.tuple(), + parsed.reservationOwnerId(), + parsed.reservationClaimFence(), + parsed.claimOwnerId(), + parsed.claimFence(), + parsed.purpose()); + } catch (IllegalArgumentException exception) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "StartSession reservation claim evidence is invalid"); + return; + } catch (StartSessionPreAuthorizationReservationService.IdempotencyConflictException + | StartSessionPreAuthorizationReservationService.StaleReservationClaimException exception) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "The exact active StartSession reservation claim is unavailable"); + return; + } catch (DataAccessResourceFailureException | TransientDataAccessException exception) { + fail( + responseObserver, + Status.UNAVAILABLE, + "StartSession reservation evidence is temporarily unavailable"); + return; + } catch (DataAccessException exception) { + boolean unavailable = isTransientDatabaseFailure(exception); + fail( + responseObserver, + unavailable ? Status.UNAVAILABLE : Status.INTERNAL, + unavailable + ? "StartSession reservation evidence is temporarily unavailable" + : "StartSession reservation evidence could not be read"); + return; + } catch (RuntimeException exception) { + fail( + responseObserver, Status.INTERNAL, "StartSession reservation evidence could not be read"); + return; + } + + if (current.isEmpty()) { + fail( + responseObserver, + Status.NOT_FOUND, + "No StartSession reservation exists for the exact request ID"); + return; + } + + CurrentClaimEvidence evidence = current.orElseThrow(); + var snapshot = evidence.snapshot(); + ReadCurrentClaimEvidenceResponse response = + ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(snapshot.tuple().controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + com.google.protobuf.ByteString.copyFrom( + snapshot.tuple().canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setMutationDigest(snapshot.mutationDigest()) + .setReservationOwnerId(evidence.reservationOwnerId().toString()) + .setReservationClaimFence(snapshot.reservationClaimFence()) + .setClaimOwnerId(evidence.currentClaimOwnerId().toString()) + .setClaimFence(snapshot.claimFence()) + .setClaimExpiresAtEpochMillis(snapshot.claimExpiresAtEpochMillis()) + .setObservedAtEpochMillis(evidence.observedAtEpochMillis()) + .setPurpose(toWirePurpose(evidence.purpose())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private static boolean isTransientDatabaseFailure(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLTransientException) { + return true; + } + if (cause instanceof SQLException sqlException) { + String sqlState = sqlException.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } + + private ParsedRequest parseRequest(ReadCurrentClaimEvidenceRequest request) { + if (!request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("unknown request fields are not supported"); + } + String requestId = + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + request.getControlPlaneRequestId()); + UUID reservationOwnerId = parseCanonicalNonNilUuid(request.getReservationOwnerId()); + UUID claimOwnerId = parseCanonicalNonNilUuid(request.getClaimOwnerId()); + long reservationClaimFence = request.getReservationClaimFence(); + long claimFence = request.getClaimFence(); + if (reservationOwnerId == null + || claimOwnerId == null + || reservationClaimFence <= 0L + || claimFence <= 0L + || request.getPreAuthorizationTupleJson().isEmpty() + || request.getPreAuthorizationTupleJson().size() + > StartSessionPreAuthorizationReservationTuple.MAX_CANONICAL_TUPLE_UTF8_BYTES) { + throw new IllegalArgumentException("reservation claim identity is malformed"); + } + + byte[] tupleBytes = request.getPreAuthorizationTupleJson().toByteArray(); + String tupleJson = decodeStrictUtf8(tupleBytes); + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(tupleJson); + if (!Arrays.equals(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), tupleBytes) + || !requestId.equals(tuple.controlPlaneRequestId())) { + throw new IllegalArgumentException("request key does not match the exact canonical tuple"); + } + + ReadPurpose purpose = + switch (request.getPurpose()) { + case START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE -> ReadPurpose.ISSUE; + case START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER -> ReadPurpose.RECOVER; + default -> throw new IllegalArgumentException("read purpose is required"); + }; + return new ParsedRequest( + requestId, + tuple, + reservationOwnerId, + reservationClaimFence, + claimOwnerId, + claimFence, + purpose); + } + + private boolean isAccountPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && GrpcPeerIdentity.isValidNamespace(workloadNamespace) + && peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"); + } + + private static UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return !parsed.equals(new UUID(0L, 0L)) && parsed.toString().equals(value) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } + + private static String decodeStrictUtf8(byte[] value) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("tuple JSON is not valid UTF-8", exception); + } + } + + private static StartSessionReservationEvidencePurpose toWirePurpose(ReadPurpose purpose) { + return switch (purpose) { + case ISSUE -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE; + case RECOVER -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER; + }; + } + + private static void fail( + StreamObserver responseObserver, + Status status, + String description) { + responseObserver.onError(status.withDescription(description).asRuntimeException()); + } + + private record ParsedRequest( + String controlPlaneRequestId, + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID claimOwnerId, + long claimFence, + ReadPurpose purpose) {} +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApproval.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApproval.java new file mode 100644 index 0000000000..91ec6342f8 --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApproval.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.loggingadmin.service.impl; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** Method-scoped approved leaf instances for ReadCurrentClaimEvidence. */ +@Component +public final class StartSessionReservationEvidenceLeafApproval { + private static final int MAX_POLICY_BYTES = 180; + private static final Pattern ACTIVE_ENTRY = Pattern.compile("active=([0-9a-f]{64})"); + private static final Pattern OVERLAP_ENTRY = + Pattern.compile("overlap=([0-9a-f]{64});expires-at=([0-9]{1,19})"); + + private final String approvalFile; + + public StartSessionReservationEvidenceLeafApproval( + @Value("${firemud.grpc.account-reservation-evidence.approved-leaf-file:}") + String approvalFile) { + this.approvalFile = approvalFile; + } + + /** Reads the trusted policy on every request; missing or invalid policy denies the peer. */ + public boolean isApproved(GrpcPeerCertificateEvidence certificateEvidence) { + if (certificateEvidence == null || approvalFile == null || approvalFile.isBlank()) { + return false; + } + + Optional approvalSet = readApprovalSet(); + if (approvalSet.isEmpty()) { + return false; + } + + String presentedFingerprint = certificateEvidence.leafSha256(); + ApprovalSet approval = approvalSet.orElseThrow(); + if (approval.activeFingerprint().equals(presentedFingerprint)) { + return true; + } + return approval.overlapFingerprint() != null + && approval.overlapFingerprint().equals(presentedFingerprint) + && Instant.now().toEpochMilli() < approval.overlapExpiresAtEpochMillis(); + } + + private Optional readApprovalSet() { + try { + Path path = Path.of(approvalFile); + if (!path.isAbsolute() || !Files.isRegularFile(path)) { + return Optional.empty(); + } + byte[] content; + try (InputStream input = Files.newInputStream(path)) { + content = input.readNBytes(MAX_POLICY_BYTES + 1); + } + if (content.length == 0 || content.length > MAX_POLICY_BYTES) { + return Optional.empty(); + } + String text = decodeStrictUtf8(content); + List lines = text.lines().toList(); + if (lines.isEmpty() || lines.size() > 2) { + return Optional.empty(); + } + + Matcher active = ACTIVE_ENTRY.matcher(lines.getFirst()); + if (!active.matches()) { + return Optional.empty(); + } + String activeFingerprint = active.group(1); + if (lines.size() == 1) { + return Optional.of(new ApprovalSet(activeFingerprint, null, 0L)); + } + + Matcher overlap = OVERLAP_ENTRY.matcher(lines.get(1)); + if (!overlap.matches() || activeFingerprint.equals(overlap.group(1))) { + return Optional.empty(); + } + long expiresAt; + try { + expiresAt = Long.parseLong(overlap.group(2)); + } catch (NumberFormatException exception) { + return Optional.empty(); + } + if (expiresAt <= 0L) { + return Optional.empty(); + } + return Optional.of(new ApprovalSet(activeFingerprint, overlap.group(1), expiresAt)); + } catch (IOException | RuntimeException exception) { + return Optional.empty(); + } + } + + private static String decodeStrictUtf8(byte[] value) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } + + private record ApprovalSet( + String activeFingerprint, String overlapFingerprint, long overlapExpiresAtEpochMillis) {} +} diff --git a/services/logging-admin-service/src/main/resources/application.yml b/services/logging-admin-service/src/main/resources/application.yml index bae9c9dcf0..6a39443553 100644 --- a/services/logging-admin-service/src/main/resources/application.yml +++ b/services/logging-admin-service/src/main/resources/application.yml @@ -62,7 +62,13 @@ firemud: http: enabled: true role-requirement: PRIVILEGED + grpc: + public-methods: + - logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} + workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} + account-reservation-evidence: + approved-leaf-file: ${FIREMUD_GRPC_ACCOUNT_RESERVATION_EVIDENCE_APPROVED_LEAF_FILE:} diff --git a/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql b/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql new file mode 100644 index 0000000000..9b70577808 --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V2__start_session_pre_authorization_reservations.sql @@ -0,0 +1,29 @@ +CREATE TABLE start_session_pre_authorization_reservations ( + control_plane_request_id VARCHAR(128) PRIMARY KEY, + pre_authorization_tuple_json VARCHAR(8192) NOT NULL, + mutation_digest VARCHAR(64) NOT NULL, + phase VARCHAR(32) NOT NULL + CONSTRAINT start_session_pre_authorization_reservations_phase_check + CHECK (phase = 'ACCOUNT_AUTHORIZATION'), + state VARCHAR(40) NOT NULL + CONSTRAINT start_session_pre_authorization_reservations_state_check + CHECK (state IN ('RESERVED', 'AUTHORIZATION_PENDING')), + reservation_owner_id UUID NOT NULL, + reservation_claim_fence BIGINT NOT NULL + CHECK (reservation_claim_fence = 1), + claim_owner_id UUID, + claim_fence BIGINT NOT NULL + CHECK (claim_fence >= reservation_claim_fence), + claim_expires_at_epoch_ms BIGINT NOT NULL + CHECK (claim_expires_at_epoch_ms > 0), + claim_state VARCHAR(16) NOT NULL + CHECK (claim_state IN ('ACTIVE', 'EXPIRED')), + created_at_epoch_ms BIGINT NOT NULL + CHECK (created_at_epoch_ms > 0), + updated_at_epoch_ms BIGINT NOT NULL + CHECK (updated_at_epoch_ms > 0), + CHECK ( + (claim_state = 'ACTIVE' AND claim_owner_id IS NOT NULL) + OR (claim_state = 'EXPIRED' AND claim_owner_id IS NULL) + ) +); diff --git a/services/logging-admin-service/src/main/resources/db/migration/V3__start_session_post_authorization_execution.sql b/services/logging-admin-service/src/main/resources/db/migration/V3__start_session_post_authorization_execution.sql new file mode 100644 index 0000000000..4a0007811b --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V3__start_session_post_authorization_execution.sql @@ -0,0 +1,173 @@ +ALTER TABLE start_session_pre_authorization_reservations + ADD COLUMN post_authorization_execution_tuple_json TEXT, + ADD COLUMN owner_execution_handoff_id UUID; + +ALTER TABLE start_session_pre_authorization_reservations + DROP CONSTRAINT start_session_pre_authorization_reservations_phase_check; + +ALTER TABLE start_session_pre_authorization_reservations + DROP CONSTRAINT start_session_pre_authorization_reservations_state_check; + +ALTER TABLE start_session_pre_authorization_reservations + ADD CONSTRAINT start_session_pre_authorization_reservations_phase_check + CHECK (phase IN ('ACCOUNT_AUTHORIZATION', 'OWNER_EXECUTION')), + ADD CONSTRAINT start_session_pre_authorization_reservations_state_check + CHECK ( + (phase = 'ACCOUNT_AUTHORIZATION' + AND state IN ('RESERVED', 'AUTHORIZATION_PENDING', 'AUTHORIZED')) + OR (phase = 'OWNER_EXECUTION' AND state = 'OWNER_EXECUTION_PENDING') + ), + ADD CONSTRAINT start_session_pre_authorization_reservations_reservation_owner_non_nil_check + CHECK (reservation_owner_id <> '00000000-0000-0000-0000-000000000000'::UUID), + ADD CONSTRAINT start_session_pre_authorization_reservations_claim_owner_non_nil_check + CHECK ( + claim_owner_id IS NULL + OR claim_owner_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + ADD CONSTRAINT start_session_pre_authorization_reservations_handoff_non_nil_check + CHECK ( + owner_execution_handoff_id IS NULL + OR owner_execution_handoff_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + ADD CONSTRAINT start_session_pre_authorization_reservations_post_tuple_bound_check + CHECK ( + post_authorization_execution_tuple_json IS NULL + OR octet_length(post_authorization_execution_tuple_json) BETWEEN 1 AND 262144 + ), + ADD CONSTRAINT start_session_pre_authorization_reservations_post_state_shape_check + CHECK ( + (phase = 'ACCOUNT_AUTHORIZATION' + AND state IN ('RESERVED', 'AUTHORIZATION_PENDING') + AND post_authorization_execution_tuple_json IS NULL + AND owner_execution_handoff_id IS NULL) + OR (phase = 'ACCOUNT_AUTHORIZATION' + AND state = 'AUTHORIZED' + AND post_authorization_execution_tuple_json IS NOT NULL + AND owner_execution_handoff_id IS NULL) + OR (phase = 'OWNER_EXECUTION' + AND state = 'OWNER_EXECUTION_PENDING' + AND post_authorization_execution_tuple_json IS NOT NULL + AND owner_execution_handoff_id IS NOT NULL) + ); + +-- jOOQ's H2 DDL parser cannot model PostgreSQL trigger functions; PostgreSQL still applies the +-- complete immutable-evidence and phase-transition guards below. +-- [jooq ignore start] +CREATE FUNCTION guard_start_session_reservation_insert() +RETURNS trigger AS $$ +BEGIN + IF NEW.phase <> 'ACCOUNT_AUTHORIZATION' + OR NEW.state <> 'RESERVED' + OR NEW.reservation_owner_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.reservation_claim_fence <> 1 + OR NEW.claim_owner_id IS DISTINCT FROM NEW.reservation_owner_id + OR NEW.claim_fence <> 1 + OR NEW.claim_state <> 'ACTIVE' + OR NEW.post_authorization_execution_tuple_json IS NOT NULL + OR NEW.owner_execution_handoff_id IS NOT NULL THEN + RAISE EXCEPTION 'StartSession reservation must begin in the exact reserved state'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER start_session_reservation_insert_guard + BEFORE INSERT ON start_session_pre_authorization_reservations + FOR EACH ROW + EXECUTE FUNCTION guard_start_session_reservation_insert(); + +CREATE FUNCTION guard_start_session_post_authorization_execution() +RETURNS trigger AS $$ +BEGIN + IF NEW.control_plane_request_id IS DISTINCT FROM OLD.control_plane_request_id + OR NEW.pre_authorization_tuple_json IS DISTINCT FROM OLD.pre_authorization_tuple_json + OR NEW.mutation_digest IS DISTINCT FROM OLD.mutation_digest + OR NEW.reservation_owner_id IS DISTINCT FROM OLD.reservation_owner_id + OR NEW.reservation_claim_fence IS DISTINCT FROM OLD.reservation_claim_fence + OR NEW.created_at_epoch_ms IS DISTINCT FROM OLD.created_at_epoch_ms THEN + RAISE EXCEPTION 'StartSession reservation identity is immutable'; + END IF; + + IF OLD.post_authorization_execution_tuple_json IS NOT NULL + AND NEW.post_authorization_execution_tuple_json + IS DISTINCT FROM OLD.post_authorization_execution_tuple_json THEN + RAISE EXCEPTION 'StartSession post-authorization tuple is immutable'; + END IF; + IF OLD.owner_execution_handoff_id IS NOT NULL + AND NEW.owner_execution_handoff_id IS DISTINCT FROM OLD.owner_execution_handoff_id THEN + RAISE EXCEPTION 'StartSession owner handoff is immutable'; + END IF; + + IF NOT ( + (NEW.phase = OLD.phase AND NEW.state = OLD.state) + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'RESERVED' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZATION_PENDING') + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZATION_PENDING' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZED') + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZED' + AND NEW.phase = 'OWNER_EXECUTION' AND NEW.state = 'OWNER_EXECUTION_PENDING') + ) THEN + RAISE EXCEPTION 'StartSession phase-qualified transition is not permitted'; + END IF; + + IF OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZATION_PENDING' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZED' THEN + IF OLD.post_authorization_execution_tuple_json IS NOT NULL + OR NEW.post_authorization_execution_tuple_json IS NULL + OR NEW.owner_execution_handoff_id IS NOT NULL + OR NEW.claim_owner_id IS DISTINCT FROM OLD.claim_owner_id + OR NEW.claim_fence IS DISTINCT FROM OLD.claim_fence + OR NEW.claim_expires_at_epoch_ms IS DISTINCT FROM OLD.claim_expires_at_epoch_ms + OR NEW.claim_state IS DISTINCT FROM OLD.claim_state THEN + RAISE EXCEPTION 'StartSession authorization enrichment must preserve the exact claim'; + END IF; + END IF; + + IF OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZED' + AND NEW.phase = 'OWNER_EXECUTION' AND NEW.state = 'OWNER_EXECUTION_PENDING' THEN + IF OLD.post_authorization_execution_tuple_json IS NULL + OR NEW.post_authorization_execution_tuple_json + IS DISTINCT FROM OLD.post_authorization_execution_tuple_json + OR NEW.owner_execution_handoff_id IS NULL + OR OLD.owner_execution_handoff_id IS NOT NULL + OR NEW.claim_owner_id IS DISTINCT FROM OLD.claim_owner_id + OR NEW.claim_fence IS DISTINCT FROM OLD.claim_fence + OR NEW.claim_expires_at_epoch_ms IS DISTINCT FROM OLD.claim_expires_at_epoch_ms + OR NEW.claim_state IS DISTINCT FROM OLD.claim_state THEN + RAISE EXCEPTION 'StartSession owner handoff must preserve the exact claim and tuple'; + END IF; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER start_session_post_authorization_execution_guard + BEFORE UPDATE ON start_session_pre_authorization_reservations + FOR EACH ROW + EXECUTE FUNCTION guard_start_session_post_authorization_execution(); + +CREATE FUNCTION reject_start_session_reservation_delete() +RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'StartSession reservation evidence cannot be deleted'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER start_session_reservation_no_delete + BEFORE DELETE ON start_session_pre_authorization_reservations + FOR EACH ROW + EXECUTE FUNCTION reject_start_session_reservation_delete(); + +CREATE FUNCTION reject_start_session_reservation_truncate() +RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'StartSession reservation evidence cannot be truncated'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER start_session_reservation_no_truncate + BEFORE TRUNCATE ON start_session_pre_authorization_reservations + FOR EACH STATEMENT + EXECUTE FUNCTION reject_start_session_reservation_truncate(); +-- [jooq ignore stop] diff --git a/services/logging-admin-service/src/main/resources/db/migration/V4__start_session_state_scoped_claim_recovery.sql b/services/logging-admin-service/src/main/resources/db/migration/V4__start_session_state_scoped_claim_recovery.sql new file mode 100644 index 0000000000..02acd9a291 --- /dev/null +++ b/services/logging-admin-service/src/main/resources/db/migration/V4__start_session_state_scoped_claim_recovery.sql @@ -0,0 +1,207 @@ +ALTER TABLE start_session_pre_authorization_reservations + ADD COLUMN claim_purpose VARCHAR(40); + +UPDATE start_session_pre_authorization_reservations +SET claim_purpose = CASE + WHEN claim_state = 'EXPIRED' THEN NULL + WHEN claim_owner_id = reservation_owner_id + AND claim_fence = reservation_claim_fence THEN 'ORIGINAL' + WHEN state = 'RESERVED' THEN 'RESERVED_RECOVERY_ISSUE' + ELSE 'AUTHORIZATION_RECOVERY' +END; + +ALTER TABLE start_session_pre_authorization_reservations + ADD CONSTRAINT start_session_pre_authorization_reservations_claim_purpose_shape_check + CHECK ( + (claim_state = 'EXPIRED' + AND claim_owner_id IS NULL + AND claim_purpose IS NULL) + OR (claim_state = 'ACTIVE' + AND claim_owner_id IS NOT NULL + AND claim_purpose IS NOT NULL + AND claim_purpose IN ( + 'ORIGINAL', + 'RESERVED_RECOVERY_ISSUE', + 'AUTHORIZATION_RECOVERY', + 'AUTHORIZED_RESPONSE_RECOVERY' + ) + AND ( + (claim_purpose = 'ORIGINAL' + AND claim_owner_id = reservation_owner_id + AND claim_fence = reservation_claim_fence) + OR (claim_purpose <> 'ORIGINAL' + AND claim_owner_id <> reservation_owner_id + AND claim_fence > reservation_claim_fence) + ) + AND ( + claim_purpose = 'ORIGINAL' + OR (claim_purpose = 'RESERVED_RECOVERY_ISSUE' + AND state IN ( + 'RESERVED', + 'AUTHORIZATION_PENDING', + 'AUTHORIZED', + 'OWNER_EXECUTION_PENDING' + )) + OR (claim_purpose = 'AUTHORIZATION_RECOVERY' + AND state IN ( + 'AUTHORIZATION_PENDING', + 'AUTHORIZED', + 'OWNER_EXECUTION_PENDING' + )) + OR (claim_purpose = 'AUTHORIZED_RESPONSE_RECOVERY' + AND state IN ('AUTHORIZED', 'OWNER_EXECUTION_PENDING')) + ) + ) + ); + +-- jOOQ's H2 DDL parser cannot model PostgreSQL trigger functions; PostgreSQL still applies the +-- complete claim-purpose provenance and same-state recovery guards below. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION guard_start_session_reservation_insert() +RETURNS trigger AS $$ +BEGIN + IF NEW.phase <> 'ACCOUNT_AUTHORIZATION' + OR NEW.state <> 'RESERVED' + OR NEW.reservation_owner_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.reservation_claim_fence <> 1 + OR NEW.claim_owner_id IS DISTINCT FROM NEW.reservation_owner_id + OR NEW.claim_fence <> 1 + OR NEW.claim_state <> 'ACTIVE' + OR NEW.claim_purpose IS DISTINCT FROM 'ORIGINAL' + OR NEW.claim_expires_at_epoch_ms <= NEW.created_at_epoch_ms + OR NEW.claim_expires_at_epoch_ms - NEW.created_at_epoch_ms > 30000 + OR NEW.post_authorization_execution_tuple_json IS NOT NULL + OR NEW.owner_execution_handoff_id IS NOT NULL THEN + RAISE EXCEPTION 'StartSession reservation must begin in the exact reserved state'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION guard_start_session_post_authorization_execution() +RETURNS trigger AS $$ +DECLARE + state_transition BOOLEAN; + claim_unchanged BOOLEAN; +BEGIN + IF NEW.control_plane_request_id IS DISTINCT FROM OLD.control_plane_request_id + OR NEW.pre_authorization_tuple_json IS DISTINCT FROM OLD.pre_authorization_tuple_json + OR NEW.mutation_digest IS DISTINCT FROM OLD.mutation_digest + OR NEW.reservation_owner_id IS DISTINCT FROM OLD.reservation_owner_id + OR NEW.reservation_claim_fence IS DISTINCT FROM OLD.reservation_claim_fence + OR NEW.created_at_epoch_ms IS DISTINCT FROM OLD.created_at_epoch_ms THEN + RAISE EXCEPTION 'StartSession reservation identity is immutable'; + END IF; + IF NEW.updated_at_epoch_ms < OLD.updated_at_epoch_ms THEN + RAISE EXCEPTION 'StartSession reservation update time cannot move backwards'; + END IF; + + IF OLD.post_authorization_execution_tuple_json IS NOT NULL + AND NEW.post_authorization_execution_tuple_json + IS DISTINCT FROM OLD.post_authorization_execution_tuple_json THEN + RAISE EXCEPTION 'StartSession post-authorization tuple is immutable'; + END IF; + IF OLD.owner_execution_handoff_id IS NOT NULL + AND NEW.owner_execution_handoff_id IS DISTINCT FROM OLD.owner_execution_handoff_id THEN + RAISE EXCEPTION 'StartSession owner handoff is immutable'; + END IF; + + state_transition := NEW.phase IS DISTINCT FROM OLD.phase OR NEW.state IS DISTINCT FROM OLD.state; + claim_unchanged := + NEW.claim_owner_id IS NOT DISTINCT FROM OLD.claim_owner_id + AND NEW.claim_fence = OLD.claim_fence + AND NEW.claim_expires_at_epoch_ms = OLD.claim_expires_at_epoch_ms + AND NEW.claim_state = OLD.claim_state + AND NEW.claim_purpose IS NOT DISTINCT FROM OLD.claim_purpose; + + IF NOT ( + (NEW.phase = OLD.phase AND NEW.state = OLD.state) + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'RESERVED' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZATION_PENDING') + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZATION_PENDING' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZED') + OR (OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZED' + AND NEW.phase = 'OWNER_EXECUTION' AND NEW.state = 'OWNER_EXECUTION_PENDING') + ) THEN + RAISE EXCEPTION 'StartSession phase-qualified transition is not permitted'; + END IF; + + IF state_transition THEN + IF NOT claim_unchanged THEN + RAISE EXCEPTION 'StartSession phase transition must preserve claim provenance'; + END IF; + IF OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZATION_PENDING' + AND NEW.phase = 'ACCOUNT_AUTHORIZATION' AND NEW.state = 'AUTHORIZED' THEN + IF OLD.post_authorization_execution_tuple_json IS NOT NULL + OR NEW.post_authorization_execution_tuple_json IS NULL + OR NEW.owner_execution_handoff_id IS NOT NULL THEN + RAISE EXCEPTION 'StartSession authorization enrichment shape is invalid'; + END IF; + ELSIF OLD.phase = 'ACCOUNT_AUTHORIZATION' AND OLD.state = 'AUTHORIZED' + AND NEW.phase = 'OWNER_EXECUTION' AND NEW.state = 'OWNER_EXECUTION_PENDING' THEN + IF OLD.post_authorization_execution_tuple_json IS NULL + OR NEW.post_authorization_execution_tuple_json + IS DISTINCT FROM OLD.post_authorization_execution_tuple_json + OR NEW.owner_execution_handoff_id IS NULL + OR OLD.owner_execution_handoff_id IS NOT NULL THEN + RAISE EXCEPTION 'StartSession owner handoff shape is invalid'; + END IF; + END IF; + RETURN NEW; + END IF; + + IF claim_unchanged THEN + RETURN NEW; + END IF; + + -- A live claim may be renewed only by its holder before expiry, preserving its state-scoped + -- purpose and extending it by no more than the bounded 30-second lease. + IF OLD.claim_state = 'ACTIVE' + AND NEW.claim_state = 'ACTIVE' + AND NEW.claim_owner_id = OLD.claim_owner_id + AND NEW.claim_fence = OLD.claim_fence + AND NEW.claim_purpose = OLD.claim_purpose + AND OLD.claim_expires_at_epoch_ms > NEW.updated_at_epoch_ms + AND NEW.claim_expires_at_epoch_ms > OLD.claim_expires_at_epoch_ms + AND NEW.claim_expires_at_epoch_ms > NEW.updated_at_epoch_ms + AND NEW.claim_expires_at_epoch_ms - NEW.updated_at_epoch_ms <= 30000 THEN + RETURN NEW; + END IF; + + -- Expiration advances the fence and clears only the current owner and claim purpose. + IF OLD.claim_state = 'ACTIVE' + AND OLD.claim_expires_at_epoch_ms <= NEW.updated_at_epoch_ms + AND NEW.claim_state = 'EXPIRED' + AND NEW.claim_owner_id IS NULL + AND NEW.claim_fence = OLD.claim_fence + 1 + AND NEW.claim_expires_at_epoch_ms = OLD.claim_expires_at_epoch_ms + AND NEW.claim_purpose IS NULL THEN + RETURN NEW; + END IF; + + -- Recovery may reassign only an expired lease, for a purpose determined by the durable state. + IF (OLD.claim_state = 'EXPIRED' + OR (OLD.claim_state = 'ACTIVE' + AND OLD.claim_expires_at_epoch_ms <= NEW.updated_at_epoch_ms)) + AND OLD.state <> 'OWNER_EXECUTION_PENDING' + AND NEW.claim_state = 'ACTIVE' + AND NEW.claim_owner_id IS NOT NULL + AND NEW.claim_owner_id <> OLD.reservation_owner_id + AND NEW.claim_owner_id IS DISTINCT FROM OLD.claim_owner_id + AND NEW.claim_fence = OLD.claim_fence + 1 + AND NEW.claim_expires_at_epoch_ms > NEW.updated_at_epoch_ms + AND NEW.claim_expires_at_epoch_ms - NEW.updated_at_epoch_ms <= 30000 + AND ( + (OLD.state = 'RESERVED' AND NEW.claim_purpose = 'RESERVED_RECOVERY_ISSUE') + OR (OLD.state = 'AUTHORIZATION_PENDING' + AND NEW.claim_purpose = 'AUTHORIZATION_RECOVERY') + OR (OLD.state = 'AUTHORIZED' + AND NEW.claim_purpose = 'AUTHORIZED_RESPONSE_RECOVERY') + ) THEN + RETURN NEW; + END IF; + + RAISE EXCEPTION 'StartSession same-state claim transition is not permitted'; +END; +$$ LANGUAGE plpgsql; +-- [jooq ignore stop] diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java new file mode 100644 index 0000000000..b795b7f886 --- /dev/null +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java @@ -0,0 +1,1358 @@ +package net.firedevops.firemud.loggingadmin; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations.START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +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.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ReadPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class StartSessionPreAuthorizationReservationPostgresIntegrationTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final Map FLYWAY_PLACEHOLDERS = Map.of("serviceSchema", "public"); + private static final UUID TENANT_ID = UUID.fromString("ffbe29e3-a8d2-4b7d-a046-cf1af57ae904"); + private static final UUID ACTOR_ID = UUID.fromString("4c5b3e92-f60d-4e3d-8b8f-6d89b28495d8"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private DriverManagerDataSource dataSource; + private DSLContext dsl; + private StartSessionPreAuthorizationReservationRepository repository; + + @BeforeEach + void migrateAndCreateRepository() { + dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .cleanDisabled(false) + .load() + .clean(); + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .target(MigrationVersion.fromVersion("4")) + .load() + .migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + repository = + StartSessionReservationMutationTestFixtures.forRunOwnedPostgres(postgres).repository(); + } + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void concurrentExactAcquiresPersistOneDurableReservationOwner() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-concurrent-01", "same action"); + int callerCount = 8; + ExecutorService executor = Executors.newFixedThreadPool(callerCount); + CountDownLatch ready = new CountDownLatch(callerCount); + CountDownLatch start = new CountDownLatch(1); + List> futures = + new ArrayList<>(); + try { + for (int index = 0; index < callerCount; index++) { + futures.add( + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent acquire gate timed out"); + } + return acquire(tuple, UUID.randomUUID()); + })); + } + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + List results = + new ArrayList<>(); + for (Future future : + futures) { + results.add(future.get(10, TimeUnit.SECONDS)); + } + + assertThat(results) + .filteredOn(StartSessionPreAuthorizationReservationRepository.AcquireResult::created) + .hasSize(1); + assertThat(results) + .allSatisfy(result -> assertThat(result.snapshot().tuple()).isEqualTo(tuple)); + assertThat(dsl.fetchCount(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)).isEqualTo(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void upgradeFromV1RetainsExistingLogEventsThroughV4() { + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .cleanDisabled(false) + .target(MigrationVersion.fromVersion("1")) + .load() + .clean(); + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .target(MigrationVersion.fromVersion("1")) + .load() + .migrate(); + + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + long existingLogEventId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO log_events (tenant_id, type, message, timestamp, account_id) " + + "VALUES (?, ?, ?, ?, ?) RETURNING id", + 42L, + "audit", + "existing row before reservation migrations", + java.sql.Timestamp.valueOf("2026-10-10 12:00:00"), + 7L), + "The V1 log row must be inserted before the reservation migrations") + .get(0, Long.class); + + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .target(MigrationVersion.fromVersion("3")) + .load() + .migrate(); + + StartSessionPreAuthorizationReservationTuple originalTuple = + tuple("postgres-v3-original-backfill", "V3 original claim backfill fixture"); + StartSessionPreAuthorizationReservationTuple expiredTuple = + tuple("postgres-v3-expired-backfill", "V3 expired claim backfill fixture"); + StartSessionPreAuthorizationReservationTuple reservedRecoveryTuple = + tuple("postgres-v3-reserved-recovery-backfill", "V3 reserved recovery backfill fixture"); + StartSessionPreAuthorizationReservationTuple pendingTuple = + tuple("postgres-v3-authorization-recovery-backfill", "V3 authorization recovery fixture"); + UUID originalOwner = UUID.fromString("39a96323-f6e0-4a64-a3c3-7a3a346f2696"); + UUID recoveryOwner = UUID.fromString("05bd6075-3e08-4a83-97c2-9af3481a9492"); + insertV3OriginalReservation(originalTuple, originalOwner); + insertV3OriginalReservation(expiredTuple, originalOwner); + expireV3Claim(expiredTuple, NOW_EPOCH_MILLIS + 30_000L); + insertV3OriginalReservation(reservedRecoveryTuple, originalOwner); + expireV3Claim(reservedRecoveryTuple, NOW_EPOCH_MILLIS + 30_000L); + recoverV3Claim( + reservedRecoveryTuple, + recoveryOwner, + NOW_EPOCH_MILLIS + 60_000L, + NOW_EPOCH_MILLIS + 30_001L); + insertV3OriginalReservation(pendingTuple, originalOwner); + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET state = 'AUTHORIZATION_PENDING', " + + "updated_at_epoch_ms = ? WHERE control_plane_request_id = ?", + NOW_EPOCH_MILLIS + 1_000L, + pendingTuple.controlPlaneRequestId()); + expireV3Claim(pendingTuple, NOW_EPOCH_MILLIS + 30_000L); + recoverV3Claim( + pendingTuple, recoveryOwner, NOW_EPOCH_MILLIS + 60_000L, NOW_EPOCH_MILLIS + 30_001L); + + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(FLYWAY_PLACEHOLDERS) + .target(MigrationVersion.fromVersion("4")) + .load() + .migrate(); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT message FROM log_events WHERE id = ?", existingLogEventId), + "The V1 log row must remain after the reservation migrations") + .get(0, String.class)) + .isEqualTo("existing row before reservation migrations"); + assertThat(repository.findExact(pendingTuple).orElseThrow().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZATION_RECOVERY); + assertThat(claimPurpose(originalTuple.controlPlaneRequestId())).isEqualTo("ORIGINAL"); + assertThat(claimPurpose(expiredTuple.controlPlaneRequestId())).isNull(); + assertThat(claimPurpose(reservedRecoveryTuple.controlPlaneRequestId())) + .isEqualTo("RESERVED_RECOVERY_ISSUE"); + assertThat(claimPurpose(pendingTuple.controlPlaneRequestId())) + .isEqualTo("AUTHORIZATION_RECOVERY"); + assertThat(repository.findExact(pendingTuple).orElseThrow().reservationClaimFence()) + .isEqualTo(1L); + assertThat(repository.findExact(pendingTuple).orElseThrow().claimFence()).isEqualTo(3L); + assertThat( + dsl.fetch( + "SELECT version FROM flyway_schema_history WHERE success ORDER BY installed_rank") + .getValues("version", String.class)) + .containsExactly("1", "2", "3", "4"); + } + + @Test + void activeClaimsRequirePurposeWhileExpiredClaimsKeepNullPurpose() { + StartSessionPreAuthorizationReservationTuple rejectedInsertTuple = + tuple("postgres-null-purpose-insert", "active claim purpose insert guard"); + UUID rejectedOwner = UUID.fromString("cd2900f9-2a8b-4dd3-a495-15180eb78f67"); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO start_session_pre_authorization_reservations (" + + "control_plane_request_id, pre_authorization_tuple_json, mutation_digest, phase, state, " + + "reservation_owner_id, reservation_claim_fence, claim_owner_id, claim_fence, " + + "claim_expires_at_epoch_ms, claim_state, claim_purpose, created_at_epoch_ms, " + + "updated_at_epoch_ms, post_authorization_execution_tuple_json, owner_execution_handoff_id) " + + "VALUES (?, ?, ?, 'ACCOUNT_AUTHORIZATION', 'RESERVED', ?, 1, ?, 1, ?, 'ACTIVE', NULL, ?, ?, NULL, NULL)", + rejectedInsertTuple.controlPlaneRequestId(), + rejectedInsertTuple.canonicalJson(), + rejectedInsertTuple.mutationDigest(), + rejectedOwner, + rejectedOwner, + NOW_EPOCH_MILLIS + 30_000L, + NOW_EPOCH_MILLIS, + NOW_EPOCH_MILLIS)); + assertThat(dsl.fetchCount(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)).isZero(); + + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-null-purpose-update", "active claim purpose update guard"); + UUID owner = UUID.fromString("dd58a5f2-c3b9-4b95-b9f8-396dece825b8"); + repository.acquire(tuple, owner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET claim_purpose = NULL " + + "WHERE control_plane_request_id = ?", + tuple.controlPlaneRequestId())) + .isInstanceOf(RuntimeException.class); + assertThat(repository.findExact(tuple).orElseThrow().claimPurpose()) + .isEqualTo(ClaimPurpose.ORIGINAL); + + var expired = + repository.expireClaim( + tuple, + tuple.mutationDigest(), + owner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.RESERVED, + NOW_EPOCH_MILLIS + 30_000L); + assertThat(expired.claimState()).isEqualTo(ClaimState.EXPIRED); + assertThat(expired.claimPurpose()).isNull(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT claim_purpose FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + tuple.controlPlaneRequestId()), + "The expired reservation row must remain readable") + .get(0, String.class)) + .isNull(); + } + + @Test + void sameRequestIdWithChangedTupleConflictsAndFullTupleIsPersisted() { + StartSessionPreAuthorizationReservationTuple original = + tuple("postgres-conflict-02", "same action"); + acquire(original, UUID.randomUUID()); + StartSessionPreAuthorizationReservationTuple changed = + tuple("postgres-conflict-02", "changed audit reason"); + + assertThatThrownBy(() -> acquire(changed, UUID.randomUUID())) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + + String storedTuple = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT pre_authorization_tuple_json FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + original.controlPlaneRequestId()), + "The original committed reservation must remain readable") + .get(0, String.class); + assertThat(storedTuple) + .contains(ACTOR_ID.toString()) + .contains("\"ownerService\":\"game-session-service\"") + .contains("\"expectedVersion\":{\"presence\":\"ABSENT\"}") + .contains("\"clientIp\":{\"presence\":\"ABSENT\"}"); + } + + @Test + void expiryRecoveryFencesStaleOwnerAndCannotInventTerminalOutcome() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-recovery-03", "recovery fixture"); + UUID originalOwner = UUID.randomUUID(); + repository.acquire(tuple, originalOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + + var firstTransition = + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), originalOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + assertThat(firstTransition.transitioned()).isTrue(); + assertThat(firstTransition.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + var duplicateTransition = + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), originalOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + assertThat(duplicateTransition.transitioned()).isFalse(); + + var expired = + repository.expireClaim( + tuple, + tuple.mutationDigest(), + originalOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_000L); + assertThat(expired.claimState()).isEqualTo(ClaimState.EXPIRED); + assertThat(expired.claimFence()).isEqualTo(2L); + assertThat(expired.reservationClaimFence()).isEqualTo(1L); + assertThat(expired.state()).isEqualTo(State.AUTHORIZATION_PENDING); + + assertThatThrownBy( + () -> + repository.renew( + tuple, + tuple.mutationDigest(), + originalOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_001L, + NOW_EPOCH_MILLIS + 60_001L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + UUID recoveryOwner = UUID.randomUUID(); + var recovery = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + assertThat(recovery.reservationOwnerId()).isEqualTo(originalOwner); + assertThat(recovery.snapshot().claimFence()).isEqualTo(3L); + assertThat(recovery.snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(recovery.snapshot().claimState()).isEqualTo(ClaimState.ACTIVE); + assertThat(recovery.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(recovery.snapshot().claimPurpose()).isEqualTo(ClaimPurpose.AUTHORIZATION_RECOVERY); + assertThat( + repository.acquireRecoveryClaim( + tuple, UUID.randomUUID(), NOW_EPOCH_MILLIS + 30_002L, NOW_EPOCH_MILLIS + 60_002L)) + .isEmpty(); + + var recoveredRecord = repository.findExact(tuple).orElseThrow(); + assertThat(recoveredRecord.phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(recoveredRecord.state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(recoveredRecord.reservationClaimFence()).isEqualTo(1L); + assertThat(recoveredRecord.claimFence()).isEqualTo(3L); + assertThat(State.values()) + .containsExactly( + State.RESERVED, + State.AUTHORIZATION_PENDING, + State.AUTHORIZED, + State.OWNER_EXECUTION_PENDING); + } + + @Test + void expiredReservedRecoveryMayIssueOnlyAfterSameReservationBecomesPending() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-reserved-recovery-03a", "reserved recovery fixture"); + UUID reservationOwner = UUID.fromString("bbf0aa73-6aeb-48d5-b4b6-2c454a6732ad"); + UUID recoveryOwner = UUID.fromString("109b9916-f068-4d49-944b-ae4b0ae95ee2"); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + var expired = + repository.expireClaim( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.RESERVED, + NOW_EPOCH_MILLIS + 30_000L); + assertThat(expired.claimPurpose()).isNull(); + var recovery = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + assertThat(recovery.snapshot().claimPurpose()).isEqualTo(ClaimPurpose.RESERVED_RECOVERY_ISSUE); + assertThat(recovery.snapshot().state()).isEqualTo(State.RESERVED); + assertThat(recovery.reservationOwnerId()).isEqualTo(reservationOwner); + assertThat(recovery.snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(recovery.snapshot().claimFence()).isEqualTo(3L); + + var pending = + repository.markAuthorizationPending( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + 3L, + NOW_EPOCH_MILLIS + 30_002L); + assertThat(pending.transitioned()).isTrue(); + assertThat(pending.snapshot().claimPurpose()).isEqualTo(ClaimPurpose.RESERVED_RECOVERY_ISSUE); + var issueEvidence = + repository + .readCurrentClaim( + tuple, + reservationOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 30_003L) + .orElseThrow(); + assertThat(issueEvidence.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(issueEvidence.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.RESERVED_RECOVERY_ISSUE); + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, + reservationOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 30_003L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThat( + repository + .markAuthorizationPending( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + 3L, + NOW_EPOCH_MILLIS + 30_004L) + .transitioned()) + .isFalse(); + } + + @Test + void concurrentExpiredPendingRecoveryClaimsHaveOneFenceWinner() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-concurrent-recovery-03aa", "concurrent recovery fixture"); + UUID reservationOwner = UUID.fromString("444a3c54-4c0d-4157-9d57-e0dfc7746552"); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + repository.expireClaim( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_000L); + + int contenders = 2; + ExecutorService executor = Executors.newFixedThreadPool(contenders); + CountDownLatch ready = new CountDownLatch(contenders); + CountDownLatch start = new CountDownLatch(1); + List>> + futures = new ArrayList<>(); + try { + for (int index = 0; index < contenders; index++) { + UUID recoveryOwner = UUID.randomUUID(); + futures.add( + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent recovery gate timed out"); + } + return repository.acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L); + })); + } + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + List> + results = new ArrayList<>(); + for (Future> + future : futures) { + results.add(future.get(10, TimeUnit.SECONDS)); + } + assertThat(results).filteredOn(Optional::isPresent).hasSize(1); + assertThat(results).filteredOn(Optional::isEmpty).hasSize(1); + assertThat(repository.findExact(tuple).orElseThrow().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZATION_RECOVERY); + } finally { + executor.shutdownNow(); + } + } + + @Test + void expiredAuthorizedRecoveryReadsOnlyOriginalResponseAndHandsOffOnce() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-authorized-recovery-03b", "authorized recovery fixture"); + UUID reservationOwner = UUID.fromString("55ca8360-6f05-4f3a-8a9a-5cd78899b311"); + UUID recoveryOwner = UUID.fromString("8d57aaea-2ceb-4c87-a673-30d5cc83c86e"); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, reservationOwner, 1L, FINGERPRINT); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 2_000L); + repository.expireClaim( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZED, + NOW_EPOCH_MILLIS + 30_000L); + + var recovery = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + assertThat(recovery.snapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(recovery.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY); + var originalResponseLookup = + repository + .readCurrentClaim( + tuple, + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 30_002L) + .orElseThrow(); + assertThat(originalResponseLookup.snapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(originalResponseLookup.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY); + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 30_002L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThatThrownBy( + () -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + postTuple(tuple, reservationOwner, 1L, "arfp/v1/other-key/" + "c".repeat(64)) + .canonicalJson(), + NOW_EPOCH_MILLIS + 30_003L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + + UUID handoffId = UUID.fromString("5d751e16-5637-4ea9-a8a2-4dc61b9f1325"); + var handoff = + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + postTuple.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 30_004L); + assertThat(handoff.mayDispatch()).isTrue(); + assertThat(handoff.snapshot().reservationOwnerId()).isEqualTo(reservationOwner); + assertThat(handoff.snapshot().currentClaimOwnerId()).isEqualTo(recoveryOwner); + assertThat(handoff.snapshot().postAuthorizationTuple().canonicalJson()) + .isEqualTo(postTuple.canonicalJson()); + assertThat( + repository + .beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + postTuple.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 30_005L) + .mayDispatch()) + .isFalse(); + + repository.expireClaim( + tuple, + tuple.mutationDigest(), + recoveryOwner, + recovery.snapshot().claimFence(), + Phase.OWNER_EXECUTION, + State.OWNER_EXECUTION_PENDING, + NOW_EPOCH_MILLIS + 60_001L); + assertThat( + repository.acquireRecoveryClaim( + tuple, + UUID.fromString("a2b6aafd-5598-4c99-8f36-b51b1ea47c6e"), + NOW_EPOCH_MILLIS + 60_002L, + NOW_EPOCH_MILLIS + 90_002L)) + .isEmpty(); + assertThat(repository.findAuthorizedExact(tuple).orElseThrow().handoff().handoffId()) + .isEqualTo(handoffId); + assertThat(dsl.fetchCount(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)).isEqualTo(1); + } + + @Test + void exactAuthorizationEnrichmentAndOwnerHandoffAreDurableBeforeDispatch() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-post-authorization-05", "post-authorization fixture"); + UUID reservationOwner = UUID.fromString("6641ea9e-dc0a-4f5d-80d0-6d87104a2fe7"); + UUID handoffId = UUID.fromString("dcb77e1f-e82a-4e07-a74a-1a4c92d1640c"); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, reservationOwner, 1L, FINGERPRINT); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + + var authorized = + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 2_000L); + assertThat(authorized.transitioned()).isTrue(); + assertThat(authorized.snapshot().reservationSnapshot().phase()) + .isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(authorized.snapshot().reservationSnapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(authorized.snapshot().reservationSnapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(authorized.snapshot().postAuthorizationTuple().canonicalBytes()) + .containsExactly(postTuple.canonicalBytes()); + assertThat(authorized.snapshot().handoff()).isNull(); + + var duplicateAuthorization = + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 3_000L); + assertThat(duplicateAuthorization.transitioned()).isFalse(); + + var firstHandoff = + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 4_000L); + assertThat(firstHandoff.mayDispatch()).isTrue(); + assertThat(firstHandoff.snapshot().reservationSnapshot().phase()) + .isEqualTo(Phase.OWNER_EXECUTION); + assertThat(firstHandoff.snapshot().reservationSnapshot().state()) + .isEqualTo(State.OWNER_EXECUTION_PENDING); + assertThat(firstHandoff.snapshot().reservationSnapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(firstHandoff.snapshot().handoff().handoffId()).isEqualTo(handoffId); + + var duplicateHandoff = + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 5_000L); + assertThat(duplicateHandoff.mayDispatch()).isFalse(); + assertThat(repository.findAuthorizedExact(tuple)) + .isPresent() + .get() + .satisfies( + snapshot -> { + assertThat(snapshot.postAuthorizationTuple().canonicalBytes()) + .containsExactly(postTuple.canonicalBytes()); + assertThat(snapshot.handoff()).isEqualTo(firstHandoff.snapshot().handoff()); + assertThat(snapshot.reservationOwnerId()).isEqualTo(reservationOwner); + assertThat(snapshot.currentClaimOwnerId()).isEqualTo(reservationOwner); + }); + + assertThatThrownBy( + () -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + UUID.fromString("53d31d97-a8c3-48a1-9815-b3e3228bb6f2"), + NOW_EPOCH_MILLIS + 5_500L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + StartSessionPostAuthorizationExecutionTuple changedFingerprint = + postTuple(tuple, reservationOwner, 1L, "arfp/v1/other-key/" + "c".repeat(64)); + assertThatThrownBy( + () -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + changedFingerprint.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 6_000L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE start_session_pre_authorization_reservations " + + "SET post_authorization_execution_tuple_json = ? " + + "WHERE control_plane_request_id = ?", + postTuple.canonicalJson() + " ", + tuple.controlPlaneRequestId())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + tuple.controlPlaneRequestId())) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE TABLE start_session_pre_authorization_reservations")) + .isInstanceOf(RuntimeException.class); + } + + @Test + void phaseMismatchExpiredClaimAndChangedTupleCannotEnrichOrDispatch() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-post-stale-08", "post-authorization stale fixture"); + UUID reservationOwner = UUID.fromString("fb2827eb-6614-4cec-9e4a-e6c653ab827e"); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, reservationOwner, 1L, FINGERPRINT); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + + assertThatThrownBy( + () -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 1_000L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 2_000L); + assertThatThrownBy( + () -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 30_000L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + StartSessionPreAuthorizationReservationTuple changedTuple = + tuple(tuple.controlPlaneRequestId(), "changed action tuple"); + StartSessionPostAuthorizationExecutionTuple changedPostTuple = + postTuple(changedTuple, reservationOwner, 1L, FINGERPRINT); + assertThatThrownBy( + () -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + changedPostTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 3_000L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + assertThatThrownBy( + () -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + UUID.fromString("f80cc7af-327c-44ab-96cc-23a84ff0ab4a"), + NOW_EPOCH_MILLIS + 4_000L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThat(repository.findExact(tuple).orElseThrow().state()) + .isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(repository.findAuthorizedExact(tuple)).isEmpty(); + } + + @Test + void recoveryClaimMayEnrichTheOriginalResponseButCannotReplaceOriginalFence() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-post-recovery-06", "post-authorization recovery fixture"); + UUID reservationOwner = UUID.fromString("06126c36-e190-43cb-932c-0f585ae2f795"); + UUID recoveryOwner = UUID.fromString("66369c32-4c13-4108-8cbc-e8c6103780b2"); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, reservationOwner, 1L, FINGERPRINT); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + repository.expireClaim( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_000L); + var recovery = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + + var enriched = + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 30_002L); + assertThat(enriched.transitioned()).isTrue(); + assertThat(enriched.snapshot().reservationSnapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(enriched.snapshot().reservationSnapshot().claimFence()).isEqualTo(3L); + assertThat(enriched.snapshot().postAuthorizationTuple().reservationOwnerId()) + .isEqualTo(reservationOwner); + assertThat(enriched.snapshot().postAuthorizationTuple().reservationClaimFence()).isEqualTo(1L); + + var recoveryHandoff = + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + postTuple.canonicalJson(), + UUID.fromString("d3f21a41-f718-4d82-9438-411377a10852"), + NOW_EPOCH_MILLIS + 30_004L); + assertThat(recoveryHandoff.mayDispatch()).isTrue(); + assertThat(recoveryHandoff.snapshot().reservationOwnerId()).isEqualTo(reservationOwner); + assertThat(recoveryHandoff.snapshot().currentClaimOwnerId()).isEqualTo(recoveryOwner); + assertThat(recoveryHandoff.snapshot().reservationSnapshot().reservationClaimFence()) + .isEqualTo(1L); + assertThat(recoveryHandoff.snapshot().reservationSnapshot().claimFence()).isEqualTo(3L); + + assertThatThrownBy( + () -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + UUID.fromString("d3f21a41-f718-4d82-9438-411377a10852"), + NOW_EPOCH_MILLIS + 30_003L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThatThrownBy( + () -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence() - 1L, + postTuple.canonicalJson(), + UUID.fromString("d3f21a41-f718-4d82-9438-411377a10852"), + NOW_EPOCH_MILLIS + 30_005L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + } + + @Test + void concurrentExactOwnerHandoffCasReturnsOnlyOneDispatchWinner() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-post-concurrent-07", "concurrent handoff fixture"); + UUID reservationOwner = UUID.fromString("8a320d67-5c29-4671-a29e-21ac2bb93c71"); + UUID handoffId = UUID.fromString("7e1604ee-0a58-4fc5-a7ef-302ce18b53d0"); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, reservationOwner, 1L, FINGERPRINT); + repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 2_000L); + + int contenders = 2; + ExecutorService executor = Executors.newFixedThreadPool(contenders); + CountDownLatch ready = new CountDownLatch(contenders); + CountDownLatch start = new CountDownLatch(1); + List> + futures = new ArrayList<>(); + try { + for (int index = 0; index < contenders; index++) { + futures.add( + executor.submit( + () -> { + ready.countDown(); + try { + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("owner handoff gate timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } + return repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 3_000L); + })); + } + boolean allReady; + try { + allReady = ready.await(5, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } + assertThat(allReady).isTrue(); + start.countDown(); + List + results = new ArrayList<>(); + try { + for (Future< + StartSessionPreAuthorizationReservationRepository.OwnerExecutionTransitionResult> + future : futures) { + results.add(future.get(10, TimeUnit.SECONDS)); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } + assertThat(results) + .filteredOn( + StartSessionPreAuthorizationReservationRepository.OwnerExecutionTransitionResult + ::mayDispatch) + .hasSize(1); + assertThat(results).filteredOn(result -> !result.mayDispatch()).hasSize(1); + } finally { + executor.shutdownNow(); + } + } + + @Test + void currentClaimReadReturnsExactIssueAndRecoverySnapshotsAndRejectsStaleInputs() { + String requestId = "13c00ed3-c8e7-4fac-9d0b-129b3a7d09dc"; + StartSessionPreAuthorizationReservationTuple tuple = + tuple(requestId, "current-claim read fixture"); + UUID originalOwner = UUID.fromString("a5b1f46b-e8e4-420a-b904-226f941d1f19"); + UUID recoveryOwner = UUID.fromString("510c4b0e-fb34-43fb-839a-7cb641d0419e"); + repository.acquire(tuple, originalOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + repository.markAuthorizationPending( + tuple, tuple.mutationDigest(), originalOwner, 1L, NOW_EPOCH_MILLIS + 1_000L); + + var issueRead = + repository + .readCurrentClaim( + tuple, + originalOwner, + 1L, + originalOwner, + 1L, + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 2_000L) + .orElseThrow(); + assertThat(issueRead.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(issueRead.snapshot().tuple().canonicalJson()).isEqualTo(tuple.canonicalJson()); + assertThat(issueRead.snapshot().mutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(issueRead.reservationOwnerId()).isEqualTo(originalOwner); + assertThat(issueRead.currentClaimOwnerId()).isEqualTo(originalOwner); + + repository.expireClaim( + tuple, + tuple.mutationDigest(), + originalOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_000L); + var recoveredClaim = + repository + .acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L) + .orElseThrow(); + assertThat(recoveredClaim.snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(recoveredClaim.snapshot().claimFence()).isEqualTo(3L); + + var recoveryRead = + repository + .readCurrentClaim( + tuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 30_002L) + .orElseThrow(); + assertThat(recoveryRead.snapshot().tuple().canonicalJson()).isEqualTo(tuple.canonicalJson()); + assertThat(recoveryRead.snapshot().mutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(recoveryRead.reservationOwnerId()).isEqualTo(originalOwner); + assertThat(recoveryRead.currentClaimOwnerId()).isEqualTo(recoveryOwner); + assertThat(recoveryRead.snapshot().claimFence()).isEqualTo(3L); + assertThat(recoveryRead.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZATION_RECOVERY); + + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 30_003L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, + originalOwner, + 1L, + originalOwner, + 1L, + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 30_002L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 60_001L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + + StartSessionPreAuthorizationReservationTuple tamperedTuple = + tuple(requestId, "tampered tuple fixture"); + assertThatThrownBy( + () -> + repository.readCurrentClaim( + tamperedTuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 30_002L)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + } + + @Test + void immutableDigestGuardRejectsMutationAndReservationEvidenceRemainsReadable() { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("postgres-integrity-04", "integrity fixture"); + acquire(tuple, UUID.randomUUID()); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET mutation_digest = ? " + + "WHERE control_plane_request_id = ?", + "0".repeat(64), + tuple.controlPlaneRequestId())) + .isInstanceOf(RuntimeException.class); + assertThat(repository.find(tuple.controlPlaneRequestId()).orElseThrow().mutationDigest()) + .isEqualTo(tuple.mutationDigest()); + } + + private StartSessionPreAuthorizationReservationRepository.AcquireResult acquire( + StartSessionPreAuthorizationReservationTuple tuple, UUID ownerId) { + return repository.acquire(tuple, ownerId, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); + } + + private void insertV3OriginalReservation( + StartSessionPreAuthorizationReservationTuple tuple, UUID reservationOwner) { + dsl.execute( + "INSERT INTO start_session_pre_authorization_reservations (" + + "control_plane_request_id, pre_authorization_tuple_json, mutation_digest, phase, state, " + + "reservation_owner_id, reservation_claim_fence, claim_owner_id, claim_fence, " + + "claim_expires_at_epoch_ms, claim_state, created_at_epoch_ms, updated_at_epoch_ms, " + + "post_authorization_execution_tuple_json, owner_execution_handoff_id) " + + "VALUES (?, ?, ?, 'ACCOUNT_AUTHORIZATION', 'RESERVED', ?, 1, ?, 1, ?, 'ACTIVE', ?, ?, NULL, NULL)", + tuple.controlPlaneRequestId(), + tuple.canonicalJson(), + tuple.mutationDigest(), + reservationOwner, + reservationOwner, + NOW_EPOCH_MILLIS + 30_000L, + NOW_EPOCH_MILLIS, + NOW_EPOCH_MILLIS); + } + + private void expireV3Claim(StartSessionPreAuthorizationReservationTuple tuple, long expiredAt) { + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET claim_owner_id = NULL, " + + "claim_fence = claim_fence + 1, claim_state = 'EXPIRED', updated_at_epoch_ms = ? " + + "WHERE control_plane_request_id = ?", + expiredAt, + tuple.controlPlaneRequestId()); + } + + private void recoverV3Claim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID recoveryOwner, + long expiresAt, + long updatedAt) { + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET claim_owner_id = ?, " + + "claim_fence = claim_fence + 1, claim_expires_at_epoch_ms = ?, claim_state = 'ACTIVE', " + + "updated_at_epoch_ms = ? WHERE control_plane_request_id = ?", + recoveryOwner, + expiresAt, + updatedAt, + tuple.controlPlaneRequestId()); + } + + private String claimPurpose(String controlPlaneRequestId) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT claim_purpose FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + controlPlaneRequestId), + "The migrated reservation row must remain readable") + .get("claim_purpose", String.class); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + String requestId, String auditReason) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 29L, UUID.fromString("be78a8de-a113-48c4-a247-39e3505aed8c")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwner, + long reservationFence, + String fingerprint) { + return StartSessionPostAuthorizationExecutionTuple.createHuman( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(tuple.canonicalJson()), + WORKLOAD, + fingerprint, + reservationOwner, + reservationFence, + authorityEvidenceBundle(tuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = TENANT_ID.toString(); + Map value = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + Instant.ofEpochMilli(NOW_EPOCH_MILLIS - 1_000L).toString(), + "expiresAt", + Instant.ofEpochMilli(NOW_EPOCH_MILLIS + 300_000L).toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException("could not encode test authority bundle", exception); + } + } +} diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java new file mode 100644 index 0000000000..030398a20e --- /dev/null +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java @@ -0,0 +1,977 @@ +package net.firedevops.firemud.loggingadmin; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.google.protobuf.ByteString; +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.netty.shaded.io.netty.handler.ssl.SslProvider; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyFactory; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.Principal; +import java.security.PrivateKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509ExtendedKeyManager; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceGrpcService; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceLeafApproval; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.test.TlsTestSupport; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@SuppressWarnings("resource") +class StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest { + private static final String PUBLIC_METHOD = + "logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence"; + private static final UUID TENANT_ID = UUID.fromString("f03e136b-522b-4ea1-b8a1-4a9f0811ea1d"); + private static final UUID ACTOR_ID = UUID.fromString("4cc8c9f1-45e6-4c9b-b22e-94c27e3dc91f"); + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_SERVICE_URI = + "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String WRONG_NAMESPACE_URI = "spiffe://firemud/ns/other/sa/account-service"; + + @Test + void socketMtlsCertificateChecksDoNotRequirePersistence(@TempDir Path temporaryDirectory) + throws Exception { + TestWorkloadPki pki = TestWorkloadPki.create(temporaryDirectory); + assertThat(GrpcPeerIdentity.fromCertificate(readCertificate(pki.serverCertificate()))) + .get() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo("spiffe://firemud/ns/test/sa/logging-admin-service"); + + Server server = + startTransport(pki, Mockito.mock(StartSessionPreAuthorizationReservationService.class)); + try { + assertTlsHandshakeAccepted(server, pki, pki.accountClient()); + assertHandshakeRejected( + server, pki, pki.clientWithoutCertificate(), "missing client certificate"); + assertHandshakeRejected( + server, pki, pki.untrustedAccountClient(), "untrusted client certificate chain"); + } finally { + server.shutdownNow(); + } + } + + @Nested + @Testcontainers(disabledWithoutDocker = true) + @SuppressWarnings("resource") + class DatabaseBackedReservationEvidenceTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void socketMtlsUsesTheVerifiedAccountPeerAndExactJwtExemption(@TempDir Path temporaryDirectory) + throws Exception { + DriverManagerDataSource dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Flyway.configure() + .dataSource(dataSource) + .locations("classpath:db/migration") + .placeholders(Map.of("serviceSchema", "public")) + .load() + .migrate(); + StartSessionPreAuthorizationReservationService reservationService = + StartSessionReservationMutationTestFixtures.forRunOwnedPostgres(postgres).service(); + TestWorkloadPki pki = TestWorkloadPki.create(temporaryDirectory); + assertThat(GrpcPeerIdentity.fromCertificate(readCertificate(pki.serverCertificate()))) + .get() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo("spiffe://firemud/ns/test/sa/logging-admin-service"); + StartSessionPreAuthorizationReservationTuple tuple = + tuple("grpc-mtls-reservation-evidence-01"); + var acquisition = reservationService.acquire(tuple); + assertThat(acquisition.newlyAcquired()).isTrue(); + assertThat( + reservationService + .markAuthorizationPending(acquisition.claim()) + .mayDispatchAccountAuthorization()) + .isTrue(); + var claim = acquisition.claim().claimEvidence(); + ReadCurrentClaimEvidenceRequest request = + ReadCurrentClaimEvidenceRequest.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setReservationOwnerId(claim.reservationOwnerId().toString()) + .setReservationClaimFence(claim.reservationClaimFence()) + .setClaimOwnerId(claim.currentClaimOwnerId().toString()) + .setClaimFence(claim.currentClaimFence()) + .setPurpose( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) + .build(); + + Path approvedLeaves = temporaryDirectory.resolve("account-reservation-evidence-leaves.txt"); + String originalLeaf = certificateSha256(pki.accountClient().certificate()); + String replacementLeaf = certificateSha256(pki.replacementAccountClient().certificate()); + writeApprovedLeaves(approvedLeaves, "active=" + originalLeaf + "\n"); + + Server server = startTransport(pki, reservationService, true, approvedLeaves); + try { + ReadCurrentClaimEvidenceResponse response = read(server, pki, pki.accountClient(), request); + assertThat(response.getControlPlaneRequestId()).isEqualTo(tuple.controlPlaneRequestId()); + assertThat(response.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(response.getMutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(response.getReservationOwnerId()) + .isEqualTo(claim.reservationOwnerId().toString()); + assertThat(response.getReservationClaimFence()).isEqualTo(claim.reservationClaimFence()); + assertThat(response.getClaimOwnerId()).isEqualTo(claim.currentClaimOwnerId().toString()); + assertThat(response.getClaimFence()).isEqualTo(claim.currentClaimFence()); + assertThat(response.getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(reservationService.findExact(tuple)).isPresent(); + + assertTlsHandshakeAccepted(server, pki, pki.accountClient()); + assertHandshakeRejected( + server, pki, pki.clientWithoutCertificate(), "missing client certificate"); + assertHandshakeRejected( + server, pki, pki.untrustedAccountClient(), "untrusted client certificate chain"); + assertThat(readStatus(server, pki, pki.wrongServiceClient(), request)) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(readStatus(server, pki, pki.wrongNamespaceClient(), request)) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(readStatus(server, pki, pki.replacementAccountClient(), request)) + .as("a CA-trusted same-URI leaf without instance approval must be denied") + .isEqualTo(Status.Code.PERMISSION_DENIED); + + long overlapExpiresAt = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(2); + writeApprovedLeaves( + approvedLeaves, + "active=" + + replacementLeaf + + "\noverlap=" + + originalLeaf + + ";expires-at=" + + overlapExpiresAt + + "\n"); + assertThat(read(server, pki, pki.accountClient(), request).getControlPlaneRequestId()) + .isEqualTo(tuple.controlPlaneRequestId()); + assertThat( + read(server, pki, pki.replacementAccountClient(), request) + .getControlPlaneRequestId()) + .isEqualTo(tuple.controlPlaneRequestId()); + + writeApprovedLeaves(approvedLeaves, "active=" + replacementLeaf + "\n"); + assertThat(readStatus(server, pki, pki.accountClient(), request)) + .as("trusted replacement must revoke the previous leaf") + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + read(server, pki, pki.replacementAccountClient(), request) + .getControlPlaneRequestId()) + .isEqualTo(tuple.controlPlaneRequestId()); + } finally { + server.shutdownNow(); + } + } + } + + private static Server startTransport( + TestWorkloadPki pki, StartSessionPreAuthorizationReservationService reservationService) + throws Exception { + return startTransport(pki, reservationService, false); + } + + private static Server startTransport( + TestWorkloadPki pki, + StartSessionPreAuthorizationReservationService reservationService, + boolean seedStaleThreadLocalCallerContext) + throws Exception { + return startTransport(pki, reservationService, seedStaleThreadLocalCallerContext, null); + } + + private static Server startTransport( + TestWorkloadPki pki, + StartSessionPreAuthorizationReservationService reservationService, + boolean seedStaleThreadLocalCallerContext, + Path approvedLeafFile) + throws Exception { + var serverTls = + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.serverCertificate().toFile(), pki.serverPrivateKey().toFile()), + SslProvider.JDK) + .trustManager(pki.trustedCaCertificate().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .protocols("TLSv1.3") + .build(); + StartSessionReservationEvidenceGrpcService receiver = + new StartSessionReservationEvidenceGrpcService( + reservationService, + new StartSessionReservationEvidenceLeafApproval( + approvedLeafFile == null ? "" : approvedLeafFile.toString()), + "test"); + ServerInterceptor staleThreadLocalCallerContextSeeder = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (seedStaleThreadLocalCallerContext + && PUBLIC_METHOD.equals(call.getMethodDescriptor().getFullMethodName())) { + SessionContext.setContext("stale-account", List.of("platformAdmin"), Map.of()); + } + return next.startCall(call, headers); + } + }; + var authenticatedReceiver = + ServerInterceptors.intercept( + receiver, + new AuthTokenInterceptor( + new JwtUtil("a".repeat(64), 3_600_000L), Set.of(PUBLIC_METHOD)), + new GrpcPeerIdentityInterceptor()); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(serverTls) + .addService( + ServerInterceptors.intercept( + authenticatedReceiver, staleThreadLocalCallerContextSeeder)) + .build() + .start(); + } + + private static ReadCurrentClaimEvidenceResponse read( + Server server, + TestWorkloadPki pki, + TestWorkloadPki.ClientIdentity clientIdentity, + ReadCurrentClaimEvidenceRequest request) + throws Exception { + ManagedChannel channel = clientChannel(server, pki, clientIdentity); + try { + return StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .readCurrentClaimEvidence(request); + } finally { + channel.shutdownNow(); + } + } + + private static Status.Code readStatus( + Server server, + TestWorkloadPki pki, + TestWorkloadPki.ClientIdentity clientIdentity, + ReadCurrentClaimEvidenceRequest request) + throws Exception { + try { + read(server, pki, clientIdentity, request); + return Status.Code.OK; + } catch (StatusRuntimeException ex) { + return ex.getStatus().getCode(); + } + } + + private static void assertHandshakeRejected( + Server server, + TestWorkloadPki pki, + TestWorkloadPki.ClientIdentity clientIdentity, + String description) + throws Exception { + RawClientTls clientTls = rawClientTls(pki, clientIdentity); + Throwable failure = + catchThrowable( + () -> { + try (SSLSocket socket = clientSocket(server, clientTls.context())) { + socket.startHandshake(); + socket.getInputStream().read(); + } + }); + assertThat(failure).as(description).isNotNull(); + assertThat(failure) + .as("%s must surface a TLS handshake exception", description) + .isInstanceOf(SSLHandshakeException.class); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "%s must fail during the TLS certificate handshake; failure chain: %s", + description, throwableChain(failure)) + .isTrue(); + if (clientIdentity.certificate() != null) { + clientTls.assertIdentitySelected(clientIdentity, ACCOUNT_URI); + assertThat(clientTls.keyManager().requestedIssuers()) + .as("%s server issuer hints must exclude the selected account chain issuer", description) + .isNotEmpty() + .doesNotContain(clientTls.keyManager().selectedChain()[0].getIssuerX500Principal()); + } + } + + private static String throwableChain(Throwable failure) { + List causes = new ArrayList<>(); + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + causes.add(cause.getClass().getName() + ": " + cause.getMessage()); + } + return String.join(" -> ", causes); + } + + private static void assertTlsHandshakeAccepted( + Server server, TestWorkloadPki pki, TestWorkloadPki.ClientIdentity clientIdentity) + throws Exception { + RawClientTls clientTls = rawClientTls(pki, clientIdentity); + try (SSLSocket socket = clientSocket(server, clientTls.context())) { + socket.startHandshake(); + assertThat(socket.getSession().getProtocol()).isEqualTo("TLSv1.3"); + assertThat(socket.getApplicationProtocol()).isEqualTo("h2"); + } + clientTls.assertIdentitySelected(clientIdentity, ACCOUNT_URI); + } + + private static SSLSocket clientSocket(Server server, SSLContext context) throws Exception { + SSLSocket socket = + (SSLSocket) context.getSocketFactory().createSocket("127.0.0.1", server.getPort()); + socket.setSoTimeout(10_000); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + parameters.setProtocols(new String[] {"TLSv1.3"}); + parameters.setApplicationProtocols(new String[] {"h2"}); + socket.setSSLParameters(parameters); + return socket; + } + + private static RawClientTls rawClientTls( + TestWorkloadPki pki, TestWorkloadPki.ClientIdentity clientIdentity) throws Exception { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + trustStore.setCertificateEntry( + "logging-admin-test-ca", readCertificate(pki.trustedCaCertificate())); + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + + ExplicitClientIdentityKeyManager explicitClientIdentity = null; + KeyManager[] keyManagers = null; + if (clientIdentity.certificate() != null) { + KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + char[] password = TestWorkloadPki.STORE_PASSWORD.toCharArray(); + clientKeyStore.load(null, password); + clientKeyStore.setKeyEntry( + "logging-admin-test-client", + readPrivateKey(clientIdentity.privateKey()), + password, + new Certificate[] {readCertificate(clientIdentity.certificate())}); + KeyManagerFactory clientKeyManagers = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + clientKeyManagers.init(clientKeyStore, password); + explicitClientIdentity = + new ExplicitClientIdentityKeyManager( + (X509ExtendedKeyManager) clientKeyManagers.getKeyManagers()[0], + "logging-admin-test-client"); + keyManagers = new KeyManager[] {explicitClientIdentity}; + } + + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keyManagers, trustManagers.getTrustManagers(), null); + return new RawClientTls(context, explicitClientIdentity); + } + + private record RawClientTls(SSLContext context, ExplicitClientIdentityKeyManager keyManager) { + void assertIdentitySelected(TestWorkloadPki.ClientIdentity clientIdentity, String expectedUri) + throws Exception { + assertThat(keyManager) + .as("raw TLS probe must have a client identity key manager") + .isNotNull(); + X509Certificate expectedCertificate = readCertificate(clientIdentity.certificate()); + assertThat(keyManager.selectedAlias()).isEqualTo("logging-admin-test-client"); + assertThat(keyManager.selectedChain()).containsExactly(expectedCertificate); + assertThat(GrpcPeerIdentity.fromCertificate(keyManager.selectedChain()[0])) + .get() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(expectedUri); + } + } + + /** + * Test-only key manager that selects its one explicit identity even when the server's issuer hint + * excludes that identity's issuer; this makes the untrusted-chain probe exercise rejection of the + * presented certificate rather than omission of a client certificate. + */ + private static final class ExplicitClientIdentityKeyManager extends X509ExtendedKeyManager { + private final X509ExtendedKeyManager delegate; + private final String explicitAlias; + private String selectedAlias; + private X509Certificate[] selectedChain; + private List requestedIssuers = List.of(); + + private ExplicitClientIdentityKeyManager( + X509ExtendedKeyManager delegate, String explicitAlias) { + this.delegate = delegate; + this.explicitAlias = explicitAlias; + } + + @Override + public String[] getClientAliases(String keyType, Principal[] issuers) { + return supports(keyType) ? new String[] {explicitAlias} : null; + } + + @Override + public String chooseClientAlias( + String[] keyTypes, Principal[] issuers, java.net.Socket socket) { + captureIssuers(issuers); + return supports(keyTypes) ? selectExplicitAlias() : null; + } + + @Override + public String[] getServerAliases(String keyType, Principal[] issuers) { + return delegate.getServerAliases(keyType, issuers); + } + + @Override + public String chooseServerAlias(String keyType, Principal[] issuers, java.net.Socket socket) { + return delegate.chooseServerAlias(keyType, issuers, socket); + } + + @Override + public X509Certificate[] getCertificateChain(String alias) { + X509Certificate[] chain = delegate.getCertificateChain(alias); + if (explicitAlias.equals(alias)) { + selectedChain = chain == null ? null : chain.clone(); + } + return chain; + } + + @Override + public PrivateKey getPrivateKey(String alias) { + return delegate.getPrivateKey(alias); + } + + @Override + public String chooseEngineClientAlias( + String[] keyTypes, Principal[] issuers, SSLEngine engine) { + captureIssuers(issuers); + return supports(keyTypes) ? selectExplicitAlias() : null; + } + + @Override + public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) { + return delegate.chooseEngineServerAlias(keyType, issuers, engine); + } + + private boolean supports(String keyType) { + PrivateKey key = delegate.getPrivateKey(explicitAlias); + return key != null && key.getAlgorithm().equalsIgnoreCase(keyType); + } + + private boolean supports(String[] keyTypes) { + return keyTypes != null && Arrays.stream(keyTypes).anyMatch(this::supports); + } + + private String selectExplicitAlias() { + selectedAlias = explicitAlias; + return explicitAlias; + } + + private void captureIssuers(Principal[] issuers) { + requestedIssuers = issuers == null ? List.of() : List.copyOf(Arrays.asList(issuers.clone())); + } + + private String selectedAlias() { + return selectedAlias; + } + + private X509Certificate[] selectedChain() { + return selectedChain == null ? new X509Certificate[0] : selectedChain.clone(); + } + + private List requestedIssuers() { + return requestedIssuers; + } + } + + private static PrivateKey readPrivateKey(Path privateKey) throws Exception { + String encoded = + Files.readString(privateKey) + .replace("-----BEGIN PRIVATE KEY-----", "") + .replace("-----END PRIVATE KEY-----", "") + .replaceAll("\\s", ""); + return KeyFactory.getInstance("RSA") + .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(encoded))); + } + + private static ManagedChannel clientChannel( + Server server, TestWorkloadPki pki, TestWorkloadPki.ClientIdentity clientIdentity) + throws Exception { + var clientTls = + GrpcSslContexts.configure(GrpcSslContexts.forClient(), SslProvider.JDK) + .trustManager(pki.trustedCaCertificate().toFile()) + .protocols("TLSv1.3"); + if (clientIdentity.certificate() != null) { + clientTls.keyManager( + clientIdentity.certificate().toFile(), clientIdentity.privateKey().toFile()); + } + return NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()) + .overrideAuthority("localhost") + .sslContext(clientTls.build()) + .build(); + } + + private static X509Certificate readCertificate(Path certificate) throws Exception { + try (var input = Files.newInputStream(certificate)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static String certificateSha256(Path certificate) throws Exception { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(readCertificate(certificate).getEncoded())); + } + + private static void writeApprovedLeaves(Path target, String policy) throws IOException { + Path targetParent = + Objects.requireNonNull(target.getParent(), "approval policy target must have a parent"); + Path replacement = Files.createTempFile(targetParent, "approved-leaves-", ".txt"); + try { + Files.writeString(replacement, policy, StandardCharsets.US_ASCII); + Files.move( + replacement, + target, + java.nio.file.StandardCopyOption.ATOMIC_MOVE, + java.nio.file.StandardCopyOption.REPLACE_EXISTING); + } finally { + Files.deleteIfExists(replacement); + } + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 29L, UUID.fromString("4ecbb112-6962-4df5-87d0-9271f982a614")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "socket mTLS Account evidence integration test"); + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + try { + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } finally { + SessionContext.clear(); + } + } + + /** + * Test-only keytool material, issued into a temporary directory and never shared or activated. + */ + private static final class TestWorkloadPki { + private static final String STORE_PASSWORD = "logging-reservation-test-only"; + + private final Path trustedCaCertificate; + private final Path serverCertificate; + private final Path serverPrivateKey; + private final ClientIdentity accountClient; + private final ClientIdentity replacementAccountClient; + private final ClientIdentity wrongServiceClient; + private final ClientIdentity wrongNamespaceClient; + private final ClientIdentity untrustedAccountClient; + + private TestWorkloadPki( + Path trustedCaCertificate, + Path serverCertificate, + Path serverPrivateKey, + ClientIdentity accountClient, + ClientIdentity replacementAccountClient, + ClientIdentity wrongServiceClient, + ClientIdentity wrongNamespaceClient, + ClientIdentity untrustedAccountClient) { + this.trustedCaCertificate = trustedCaCertificate; + this.serverCertificate = serverCertificate; + this.serverPrivateKey = serverPrivateKey; + this.accountClient = accountClient; + this.replacementAccountClient = replacementAccountClient; + this.wrongServiceClient = wrongServiceClient; + this.wrongNamespaceClient = wrongNamespaceClient; + this.untrustedAccountClient = untrustedAccountClient; + } + + static TestWorkloadPki create(Path directory) throws Exception { + Files.createDirectories(directory); + Path trustedCaStore = createCa(directory, "trusted-ca"); + Path trustedCaCertificate = exportCa(directory, trustedCaStore, "trusted-ca"); + Path untrustedCaStore = createCa(directory, "untrusted-ca"); + Path untrustedCaCertificate = exportCa(directory, untrustedCaStore, "untrusted-ca"); + Identity server = + issueIdentity( + directory, + trustedCaStore, + trustedCaCertificate, + "logging-admin-server", + "spiffe://firemud/ns/test/sa/logging-admin-service", + true); + ClientIdentity account = + asClient( + issueIdentity( + directory, + trustedCaStore, + trustedCaCertificate, + "account-service", + ACCOUNT_URI, + false)); + ClientIdentity wrongService = + asClient( + issueIdentity( + directory, + trustedCaStore, + trustedCaCertificate, + "wrong-service", + WRONG_SERVICE_URI, + false)); + ClientIdentity replacementAccount = + asClient( + issueIdentity( + directory, + trustedCaStore, + trustedCaCertificate, + "account-service-renewed", + ACCOUNT_URI, + false)); + ClientIdentity wrongNamespace = + asClient( + issueIdentity( + directory, + trustedCaStore, + trustedCaCertificate, + "wrong-namespace", + WRONG_NAMESPACE_URI, + false)); + ClientIdentity untrustedAccount = + asClient( + issueIdentity( + directory, + untrustedCaStore, + untrustedCaCertificate, + "untrusted-account", + ACCOUNT_URI, + false)); + return new TestWorkloadPki( + trustedCaCertificate, + server.certificate(), + server.privateKey(), + account, + replacementAccount, + wrongService, + wrongNamespace, + untrustedAccount); + } + + Path trustedCaCertificate() { + return trustedCaCertificate; + } + + Path serverCertificate() { + return serverCertificate; + } + + Path serverPrivateKey() { + return serverPrivateKey; + } + + ClientIdentity accountClient() { + return accountClient; + } + + ClientIdentity replacementAccountClient() { + return replacementAccountClient; + } + + ClientIdentity wrongServiceClient() { + return wrongServiceClient; + } + + ClientIdentity wrongNamespaceClient() { + return wrongNamespaceClient; + } + + ClientIdentity untrustedAccountClient() { + return untrustedAccountClient; + } + + ClientIdentity clientWithoutCertificate() { + return new ClientIdentity(null, null); + } + + private static Path createCa(Path directory, String alias) throws Exception { + Path store = directory.resolve(alias + ".p12"); + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD Logging reservation " + alias + " test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + return store; + } + + private static Path exportCa(Path directory, Path store, String alias) throws Exception { + Path certificate = directory.resolve(alias + ".crt"); + runKeytool( + "-exportcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-rfc"); + return certificate; + } + + private static Identity issueIdentity( + Path directory, + Path caStore, + Path caCertificate, + String alias, + String workloadUri, + boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + Path privateKey = directory.resolve(alias + ".key"); + String san = "URI:" + workloadUri + (server ? ",DNS:localhost,IP:127.0.0.1" : ""); + String extendedKeyUsage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + caStoreAlias(caStore), + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + caStoreAlias(caStore), + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caCertificate.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + var key = (java.security.PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()); + byte[] certBytes = keyStore.getCertificate(alias).getEncoded(); + writePem(certificate, "CERTIFICATE", certBytes); + writePem(privateKey, "PRIVATE KEY", key.getEncoded()); + return new Identity(certificate, privateKey); + } + + private static ClientIdentity asClient(Identity identity) { + return new ClientIdentity(identity.certificate(), identity.privateKey()); + } + + private static String caStoreAlias(Path caStore) { + Objects.requireNonNull( + caStore.getParent(), "CA store must have a test-owned parent directory"); + Path fileName = Objects.requireNonNull(caStore.getFileName(), "CA store must name a file"); + return fileName.toString().replace(".p12", ""); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + List command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Path outputFile = Files.createTempFile("firemud-logging-reservation-keytool-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(outputFile.toFile()) + .start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(5, TimeUnit.SECONDS); + throw new IllegalStateException("keytool exceeded its 30-second test-fixture timeout"); + } + String output = Files.readString(outputFile, StandardCharsets.UTF_8); + if (process.exitValue() != 0) { + throw new IllegalStateException("keytool failed: " + output); + } + } finally { + Files.deleteIfExists(outputFile); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + private record Identity(Path certificate, Path privateKey) {} + + private record ClientIdentity(Path certificate, Path privateKey) {} + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java new file mode 100644 index 0000000000..163abcea2a --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java @@ -0,0 +1,639 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Acquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizedSnapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.RecoveryAcquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionPreAuthorizationReservationServiceTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final UUID TENANT_ID = UUID.fromString("3d3c5ca5-6d43-4db6-821d-8a0de883a467"); + private static final UUID ACTOR_ID = UUID.fromString("863843ee-f00a-4905-a9ad-11f706f1b693"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private final StartSessionPreAuthorizationReservationRepository repository = + mock(StartSessionPreAuthorizationReservationRepository.class); + private final Clock clock = Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC); + private final StartSessionPreAuthorizationReservationService service = + StartSessionReservationMutationTestFixtures.forMockBackedUnitTest(repository, clock); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void firstAcquisitionGetsOneBoundedClaimAndExactDuplicateGetsNoClaim() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-unit-01"); + Snapshot initial = snapshot(tuple, State.RESERVED, 1L, 1L, ClaimState.ACTIVE); + when(repository.acquire(any(), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(initial, true)) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(initial, false)); + + Acquisition first = service.acquire(tuple); + Acquisition duplicate = service.acquire(tuple); + + assertThat(first.newlyAcquired()).isTrue(); + assertThat(first.claim()).isNotNull(); + assertThat(first.claim().claimFence()).isEqualTo(1L); + assertThat(duplicate.newlyAcquired()).isFalse(); + assertThat(duplicate.claim()).isNull(); + verify(repository, org.mockito.Mockito.times(2)) + .acquire(any(), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L)); + } + + @Test + void parsedTupleCannotBeUsedAsAnInitialReservationAuthorityAssertion() { + StartSessionPreAuthorizationReservationTuple parsed = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + tuple("service-unit-02").canonicalJson()); + + assertThat(parsed.isAuthorityDerived()).isFalse(); + assertThatThrownBy(() -> service.acquire(parsed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("actor derived"); + } + + @Test + void expiredPendingClaimCanOnlyBeReacquiredAsReadOnlyRecoveryClaim() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-unit-03"); + Snapshot recovered = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L, ClaimState.ACTIVE); + when(repository.acquireRecoveryClaim( + eq(tuple), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + recovered, UUID.fromString("6e0ef777-8661-4139-80eb-904b75de5860")))); + + Optional acquisition = service.acquireAuthorizationRecoveryClaim(tuple); + + assertThat(acquisition).isPresent(); + assertThat(acquisition.orElseThrow().claim().isRecoveryLookupOnly()).isTrue(); + assertThat(acquisition.orElseThrow().snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(acquisition.orElseThrow().snapshot().claimFence()).isEqualTo(3L); + assertThat(acquisition.orElseThrow().snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(acquisition.orElseThrow().claim().claimEvidence().reservationClaimFence()) + .isEqualTo(1L); + assertThat(acquisition.orElseThrow().claim().claimEvidence().currentClaimFence()).isEqualTo(3L); + assertThatThrownBy(() -> service.markAuthorizationPending(acquisition.orElseThrow().claim())) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + } + + @Test + void expiredReservedClaimMayAdvanceOnceButDoesNotBecomeLookupOnly() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-unit-reserved-recovery"); + UUID reservationOwnerId = UUID.fromString("c962ffad-5621-47a2-a38a-87d5d2ce96e1"); + Snapshot recovered = snapshot(tuple, State.RESERVED, 1L, 3L, ClaimState.ACTIVE); + Snapshot pending = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + 1L, + 3L, + NOW_EPOCH_MILLIS + 30_000L, + ClaimState.ACTIVE, + ClaimPurpose.RESERVED_RECOVERY_ISSUE); + when(repository.acquireRecoveryClaim( + eq(tuple), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + recovered, reservationOwnerId))); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + eq(reservationOwnerId), + eq(1L), + any(), + eq(3L), + eq(NOW_EPOCH_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); + + RecoveryAcquisition acquisition = + service.acquireAuthorizationRecoveryClaim(tuple).orElseThrow(); + + assertThat(acquisition.claim().purpose()).isEqualTo(ClaimPurpose.RESERVED_RECOVERY_ISSUE); + assertThat(acquisition.claim().isRecoveryLookupOnly()).isFalse(); + var transition = service.markAuthorizationPending(acquisition.claim()); + assertThat(transition.mayDispatchAccountAuthorization()).isTrue(); + assertThat(transition.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.RESERVED_RECOVERY_ISSUE); + } + + @Test + void currentClaimReadEchoesExactIssueAndRecoveryOwnershipWithoutMutation() { + String requestId = "start-session/operator/βeta"; + UUID reservationOwnerId = UUID.fromString("3bacbd32-12e5-46d2-9504-51aab74052bd"); + UUID recoveryOwnerId = UUID.fromString("a7bf2688-9f75-4ad8-ab45-7f65c7adbd97"); + StartSessionPreAuthorizationReservationTuple tuple = tuple(requestId); + Snapshot issueSnapshot = + snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L, ClaimState.ACTIVE); + Snapshot recoverySnapshot = + snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L, ClaimState.ACTIVE); + Snapshot authorizedRecoverySnapshot = + snapshot(tuple, State.AUTHORIZED, 1L, 5L, ClaimState.ACTIVE); + when(repository.readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + issueSnapshot, reservationOwnerId, reservationOwnerId))); + when(repository.readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + recoverySnapshot, reservationOwnerId, recoveryOwnerId))); + when(repository.readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 5L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + authorizedRecoverySnapshot, reservationOwnerId, recoveryOwnerId))); + + var issue = + service + .readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE) + .orElseThrow(); + var recovery = + service + .readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER) + .orElseThrow(); + var authorizedRecovery = + service + .readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 5L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER) + .orElseThrow(); + + assertThat(issue.snapshot().tuple().canonicalJson()).isEqualTo(tuple.canonicalJson()); + assertThat(issue.snapshot().mutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(issue.reservationOwnerId()).isEqualTo(reservationOwnerId); + assertThat(issue.currentClaimOwnerId()).isEqualTo(reservationOwnerId); + assertThat(issue.snapshot().claimFence()).isEqualTo(1L); + assertThat(issue.purpose()) + .isEqualTo(StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE); + assertThat(issue.observedAtEpochMillis()).isEqualTo(NOW_EPOCH_MILLIS); + assertThat(recovery.reservationOwnerId()).isEqualTo(reservationOwnerId); + assertThat(recovery.currentClaimOwnerId()).isEqualTo(recoveryOwnerId); + assertThat(recovery.snapshot().reservationClaimFence()).isEqualTo(1L); + assertThat(recovery.snapshot().claimFence()).isEqualTo(3L); + assertThat(recovery.purpose()) + .isEqualTo(StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER); + assertThat(authorizedRecovery.snapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(authorizedRecovery.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY); + verify(repository) + .readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS); + verify(repository) + .readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS); + } + + @Test + void currentClaimReadRejectsWrongPurposeFreshnessAndExpiredSnapshots() { + String requestId = "start-session/operator/expiry"; + UUID reservationOwnerId = UUID.fromString("871ec253-4fe6-4e9f-9584-c74f9795f78a"); + UUID recoveryOwnerId = UUID.fromString("ec1e7980-e05a-4200-bde8-66cd314b0930"); + StartSessionPreAuthorizationReservationTuple tuple = tuple(requestId); + Snapshot lookupOnlyRecovery = + snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L, ClaimState.ACTIVE); + when(repository.readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + lookupOnlyRecovery, reservationOwnerId, recoveryOwnerId))); + + assertThatThrownBy( + () -> + service.readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + assertThatThrownBy( + () -> + service.readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + verify(repository) + .readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS); + + Snapshot expired = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + 1L, + 1L, + NOW_EPOCH_MILLIS, + ClaimState.ACTIVE, + ClaimPurpose.ORIGINAL); + when(repository.readCurrentClaim( + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS)) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( + expired, reservationOwnerId, reservationOwnerId))); + + assertThatThrownBy( + () -> + service.readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + } + + @Test + void durableAuthorizationAndOwnerTransitionExposeOnlyTheFirstHandoffForDispatch() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("service-post-authorization"); + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L, ClaimState.ACTIVE); + when(repository.acquire(any(), any(), eq(NOW_EPOCH_MILLIS), eq(NOW_EPOCH_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true)); + Acquisition acquired = service.acquire(tuple); + var claim = acquired.claim(); + UUID owner = claim.claimEvidence().reservationOwnerId(); + StartSessionPostAuthorizationExecutionTuple postTuple = + postTuple(tuple, owner, Instant.ofEpochMilli(NOW_EPOCH_MILLIS + 300_000L)); + + AuthorizedSnapshot authorizedSnapshot = + new AuthorizedSnapshot( + snapshot(tuple, State.AUTHORIZED, 1L, 1L, ClaimState.ACTIVE), + postTuple, + owner, + owner, + null); + when(repository.completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + eq(owner), + eq(1L), + eq(owner), + eq(1L), + eq(postTuple.canonicalJson()), + eq(NOW_EPOCH_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AuthorizationTransitionResult( + authorizedSnapshot, true)); + + var completed = service.completeAuthorization(claim, postTuple); + + assertThat(completed.transitioned()).isTrue(); + assertThat(completed.snapshot().reservationSnapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(completed.snapshot().postAuthorizationTuple().canonicalBytes()) + .containsExactly(postTuple.canonicalBytes()); + + OwnerExecutionHandoff handoff = + new OwnerExecutionHandoff(UUID.fromString("dcb77e1f-e82a-4e07-a74a-1a4c92d1640c")); + AuthorizedSnapshot pendingSnapshot = + new AuthorizedSnapshot( + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.OWNER_EXECUTION, + State.OWNER_EXECUTION_PENDING, + 1L, + 1L, + NOW_EPOCH_MILLIS + 30_000L, + ClaimState.ACTIVE, + ClaimPurpose.ORIGINAL), + postTuple, + owner, + owner, + handoff); + when(repository.beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + eq(owner), + eq(1L), + eq(owner), + eq(1L), + eq(postTuple.canonicalJson()), + eq(handoff.handoffId()), + eq(NOW_EPOCH_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.OwnerExecutionTransitionResult( + pendingSnapshot, true)) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.OwnerExecutionTransitionResult( + pendingSnapshot, false)); + + var first = service.beginOwnerExecution(claim, postTuple, handoff); + var duplicate = service.beginOwnerExecution(claim, postTuple, handoff); + + assertThat(first.mayDispatch()).isTrue(); + assertThat(first.snapshot().handoff()).isEqualTo(handoff); + assertThat(duplicate.mayDispatch()).isFalse(); + verify(repository) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + eq(owner), + eq(1L), + eq(owner), + eq(1L), + eq(postTuple.canonicalJson()), + eq(NOW_EPOCH_MILLIS)); + verify(repository, org.mockito.Mockito.times(2)) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + eq(owner), + eq(1L), + eq(owner), + eq(1L), + eq(postTuple.canonicalJson()), + eq(handoff.handoffId()), + eq(NOW_EPOCH_MILLIS)); + } + + @Test + void phaseQualifiedStateModelHasNoSyntheticTerminalOutcome() { + assertThat(State.values()) + .containsExactly( + State.RESERVED, + State.AUTHORIZATION_PENDING, + State.AUTHORIZED, + State.OWNER_EXECUTION_PENDING); + assertThat(Phase.values()).containsExactly(Phase.ACCOUNT_AUTHORIZATION, Phase.OWNER_EXECUTION); + } + + @Test + void annotationConfigContextSelectsRepositoryConstructorWithoutDatabase() { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.registerBean(StartSessionPreAuthorizationReservationRepository.class, () -> repository); + context.register(StartSessionPreAuthorizationReservationService.class); + + try { + context.refresh(); + + assertThat(context.getBean(StartSessionPreAuthorizationReservationService.class)).isNotNull(); + } finally { + context.close(); + } + } + + private static Snapshot snapshot( + StartSessionPreAuthorizationReservationTuple tuple, + State state, + long reservationFence, + long currentFence, + ClaimState claimState) { + return new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + state, + reservationFence, + currentFence, + NOW_EPOCH_MILLIS + 30_000L, + claimState, + claimState == ClaimState.EXPIRED + ? null + : currentFence == reservationFence + ? ClaimPurpose.ORIGINAL + : state == State.RESERVED + ? ClaimPurpose.RESERVED_RECOVERY_ISSUE + : state == State.AUTHORIZATION_PENDING + ? ClaimPurpose.AUTHORIZATION_RECOVERY + : ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 17L, UUID.fromString("2a9a4d47-a544-4984-bbc4-8e85f84116e4")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "unit-test StartSession prerequisite"); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwner, + Instant expiresAt) { + return StartSessionPostAuthorizationExecutionTuple.createHuman( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(tuple.canonicalJson()), + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + FINGERPRINT, + reservationOwner, + 1L, + authorityEvidenceBundle(tuple, expiresAt), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple tuple, Instant expiresAt) { + String tenantId = TENANT_ID.toString(); + Map value = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + Instant.ofEpochMilli(NOW_EPOCH_MILLIS - 1_000L).toString(), + "expiresAt", + expiresAt.toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException("could not encode test authority bundle", exception); + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java new file mode 100644 index 0000000000..85c8e3a164 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionOperatorActionCodec; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class StartSessionPreAuthorizationReservationTupleTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void createsCanonicalHumanOnlyTupleFromCurrentTenantAdminAndPreservesAbsence() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-01", action); + String canonicalJson = tuple.canonicalJson(); + + assertThat(tuple.actor().accountId()).isEqualTo(ACTOR_ID); + assertThat(tuple.isAuthorityDerived()).isTrue(); + assertThat(tuple.automationPolicy()) + .isEqualTo(StartSessionPreAuthorizationReservationTuple.NoAutomationPolicy.ABSENT); + assertThat(tuple.targetOwner()).isEqualTo(StartSessionOperatorAction.OWNER_SERVICE); + assertThat(tuple.mutationDigest()) + .isEqualTo(StartSessionOperatorActionCodec.mutationDigest(action)); + assertThat(canonicalJson) + .contains("\"requestIdentityKind\":\"controlPlaneRequestId\"") + .contains("\"targetOwner\":{\"ownerService\":\"game-session-service\"}") + .contains("\"expectedVersion\":{\"presence\":\"ABSENT\"}") + .contains("\"clientIp\":{\"presence\":\"ABSENT\"}") + .contains("\"automationPolicy\":{\"presence\":\"ABSENT\"}") + .doesNotContain("authorityDerived"); + StartSessionPreAuthorizationReservationTuple rehydrated = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(canonicalJson); + assertThat(rehydrated).isEqualTo(tuple); + assertThat(rehydrated.isAuthorityDerived()).isFalse(); + assertThat( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(canonicalJson) + .canonicalJson()) + .isEqualTo(canonicalJson); + } + + @Test + void preservesPresentClientIpAsASeparateTypedPresenceValue() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + StartSessionOperatorAction action = + action(StartSessionOperatorAction.ClientIp.of("203.0.113.8")); + + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-02", action); + + assertThat(tuple.canonicalJson()) + .contains("\"clientIp\":{\"presence\":\"PRESENT\",\"value\":\"203.0.113.8\"}"); + assertThat( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(tuple.canonicalJson())) + .isEqualTo(tuple); + } + + @Test + void rejectsMissingHumanAuthorityAndDoesNotAcceptOtherRoleAsTenantAdmin() { + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + SessionContext.setContext(ACTOR_ID.toString(), List.of(), Map.of(), false, null, null); + + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-03", action)) + .isInstanceOf(IllegalArgumentException.class); + + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("moderator")), + false, + null, + null); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-03", action)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsInternalOrWrongTenantAuthority() { + StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + true, + "logging-admin-service", + "instance-1"); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-04", action)) + .isInstanceOf(IllegalArgumentException.class); + + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(UUID.randomUUID().toString(), List.of("tenantAdmin")), + false, + null, + null); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-04", action)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsNonCanonicalAndUnsupportedPersistedTupleShapes() { + setTenantAdminContext(TENANT_ID, ACTOR_ID); + String canonicalJson = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-05", action(StartSessionOperatorAction.ClientIp.absent())) + .canonicalJson(); + + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(" " + canonicalJson)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + canonicalJson.replace("\"presence\":\"ABSENT\"", "\"presence\":\"NULL\""))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void setTenantAdminContext(UUID tenantId, UUID actorId) { + SessionContext.setContext( + actorId.toString(), + List.of(), + Map.of(tenantId.toString(), List.of("tenantAdmin")), + false, + null, + null); + } + + private static StartSessionOperatorAction action(StartSessionOperatorAction.ClientIp clientIp) { + return new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target( + 91L, UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(clientIp), + "approved StartSession prerequisite"); + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionReservationMutationBoundaryTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionReservationMutationBoundaryTest.java new file mode 100644 index 0000000000..c9bcc30c58 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionReservationMutationBoundaryTest.java @@ -0,0 +1,200 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import static net.firedevops.firemud.loggingadmin.jooq.tables.StartSessionPreAuthorizationReservations.START_SESSION_PRE_AUTHORIZATION_RESERVATIONS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ReadPurpose; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +class StartSessionReservationMutationBoundaryTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final UUID TENANT_ID = UUID.fromString("86376245-2491-41c1-b87f-322a486f74d9"); + private static final UUID ACTOR_ID = UUID.fromString("0f11d69b-334d-42de-a844-2d557ba4e9a4"); + private static final UUID TARGET_ID = UUID.fromString("b2800980-9e55-4c62-a07d-d10f53bcfb22"); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void productionServiceDeniesEveryMutationBeforeRepositoryCallsButLeavesReadsAvailable() { + StartSessionPreAuthorizationReservationRepository repository = + mock(StartSessionPreAuthorizationReservationRepository.class); + StartSessionPreAuthorizationReservationService service = + new StartSessionPreAuthorizationReservationService( + repository, Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC)); + + assertThatThrownBy(() -> service.acquire(null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.acquireAuthorizationRecoveryClaim(null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.markAuthorizationPending(null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.renew(null, null, null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.expireClaim(null, null, null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.completeAuthorization(null, null)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> service.beginOwnerExecution(null, null, null)) + .isInstanceOf(UnsupportedOperationException.class); + verifyNoInteractions(repository); + + StartSessionPreAuthorizationReservationTuple tuple = tuple("passive-service-read"); + when(repository.find(tuple.controlPlaneRequestId())).thenReturn(Optional.empty()); + when(repository.findExact(tuple)).thenReturn(Optional.empty()); + when(repository.findAuthorizedExact(tuple)).thenReturn(Optional.empty()); + when(repository.readCurrentClaim( + tuple, ACTOR_ID, 1L, ACTOR_ID, 1L, ReadPurpose.ISSUE, NOW_EPOCH_MILLIS)) + .thenReturn(Optional.empty()); + + assertThat(service.find(tuple.controlPlaneRequestId())).isEmpty(); + assertThat(service.findExact(tuple)).isEmpty(); + assertThat(service.findAuthorizedExact(tuple)).isEmpty(); + assertThat( + service.readCurrentClaimEvidence( + tuple.controlPlaneRequestId(), + tuple, + ACTOR_ID, + 1L, + ACTOR_ID, + 1L, + ReadPurpose.ISSUE)) + .isEmpty(); + verify(repository).find(tuple.controlPlaneRequestId()); + verify(repository).findExact(tuple); + verify(repository).findAuthorizedExact(tuple); + verify(repository) + .readCurrentClaim(tuple, ACTOR_ID, 1L, ACTOR_ID, 1L, ReadPurpose.ISSUE, NOW_EPOCH_MILLIS); + } + + @Test + void productionRepositoryDeniesEveryMutationBeforeDslCallsButLeavesFindAvailable() { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + AtomicInteger executions = new AtomicInteger(); + MockDataProvider provider = + context -> { + executions.incrementAndGet(); + return new MockResult[] { + new MockResult(0, resultDsl.newResult(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)) + }; + }; + DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); + StartSessionPreAuthorizationReservationRepository repository = + new StartSessionPreAuthorizationReservationRepository(dsl); + + assertThatThrownBy(() -> repository.acquire(null, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> repository.acquireRecoveryClaim(null, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> repository.markAuthorizationPending(null, null, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> repository.markAuthorizationPending(null, null, null, 0L, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> repository.renew(null, null, null, 0L, null, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy(() -> repository.expireClaim(null, null, null, 0L, null, null, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> repository.completeAuthorization(null, null, null, 0L, null, 0L, null, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> repository.beginOwnerExecution(null, null, null, 0L, null, 0L, null, null, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + + assertThat(executions).hasValue(0); + StartSessionPreAuthorizationReservationTuple tuple = tuple("passive-repository-read"); + assertThat(repository.find(tuple.controlPlaneRequestId())).isEmpty(); + assertThat(repository.findExact(tuple)).isEmpty(); + assertThat(repository.findAuthorizedExact(tuple)).isEmpty(); + assertThat( + repository.readCurrentClaim( + tuple, + ACTOR_ID, + 1L, + UUID.fromString("36c9365a-5411-4e20-981c-a5b2a97e224e"), + 2L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS)) + .isEmpty(); + assertThat(executions).hasValue(4); + } + + @Test + void springConstructsPassiveRepositoryAndKeepsWritesDeniedBeforeSql() { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + AtomicInteger executions = new AtomicInteger(); + MockDataProvider provider = + context -> { + executions.incrementAndGet(); + return new MockResult[] { + new MockResult(0, resultDsl.newResult(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)) + }; + }; + DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.registerBean(DSLContext.class, () -> dsl); + context.registerBean(StartSessionPreAuthorizationReservationRepository.class); + + try { + context.refresh(); + StartSessionPreAuthorizationReservationRepository repository = + context.getBean(StartSessionPreAuthorizationReservationRepository.class); + StartSessionPreAuthorizationReservationTuple tuple = tuple("spring-passive-repository"); + + assertThatThrownBy(() -> repository.acquire(null, null, 0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(executions).hasValue(0); + assertThat(repository.find(tuple.controlPlaneRequestId())).isEmpty(); + assertThat(executions).hasValue(1); + } finally { + context.close(); + } + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(19L, TARGET_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "unit-test passive read"); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java new file mode 100644 index 0000000000..c503a3a8c9 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java @@ -0,0 +1,641 @@ +package unit.net.firedevops.firemud.loggingadmin.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +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.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.MetadataUtils; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.sql.SQLException; +import java.sql.SQLTransientException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.CurrentClaimEvidence; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ReadPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceGrpcService; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceLeafApproval; +import net.firedevops.firemud.loggingadmin.v1.LoggingAdminServiceGrpc; +import net.firedevops.firemud.loggingadmin.v1.PingRequest; +import net.firedevops.firemud.loggingadmin.v1.PingResponse; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.TransientDataAccessResourceException; + +class StartSessionReservationEvidenceGrpcServiceTest { + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String REQUEST_ID = "start-session/evidence/βeta"; + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("c207c44a-92b8-4460-b8f1-53b52d5339f0"); + private static final UUID RECOVERY_OWNER_ID = + UUID.fromString("160c30d2-4912-4c8d-8957-0538d9462d08"); + private static final long OBSERVED_AT = 1_800_000_000_000L; + private static final byte[] APPROVED_LEAF_DER = + "test account leaf certificate".getBytes(StandardCharsets.US_ASCII); + private static final byte[] UNAPPROVED_LEAF_DER = + "other same-uri leaf certificate".getBytes(StandardCharsets.US_ASCII); + private static final String APPROVED_LEAF_SHA256 = sha256(APPROVED_LEAF_DER); + private final StartSessionPreAuthorizationReservationService reservationService = + mock(StartSessionPreAuthorizationReservationService.class); + @TempDir private Path temporaryDirectory; + private StartSessionReservationEvidenceGrpcService service; + + @BeforeEach + void configureApprovedAccountLeaf() throws Exception { + Path approvalFile = temporaryDirectory.resolve("approved-leaves.txt"); + Files.writeString( + approvalFile, "active=" + APPROVED_LEAF_SHA256 + "\n", StandardCharsets.US_ASCII); + service = + new StartSessionReservationEvidenceGrpcService( + reservationService, + new StartSessionReservationEvidenceLeafApproval(approvalFile.toString()), + "test"); + } + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void returnsExactIssueAndRecoveryEvidenceToSameNamespaceAccountPeer() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + for (StartSessionReservationEvidencePurpose purpose : + List.of( + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE, + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER)) { + UUID currentOwner = + purpose + == StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE + ? RESERVATION_OWNER_ID + : RECOVERY_OWNER_ID; + long currentFence = currentOwner.equals(RESERVATION_OWNER_ID) ? 1L : 3L; + when(reservationService.readCurrentClaimEvidence( + eq(REQUEST_ID), + eq(tuple), + eq(RESERVATION_OWNER_ID), + eq(1L), + eq(currentOwner), + eq(currentFence), + eq(toPurpose(purpose)))) + .thenReturn(Optional.of(evidence(tuple, currentOwner, currentFence, toPurpose(purpose)))); + + Observer observer = call(request(tuple, currentOwner, currentFence, purpose), ACCOUNT_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.response.getControlPlaneRequestId()).isEqualTo(REQUEST_ID); + assertThat(observer.response.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(observer.response.getMutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(observer.response.getReservationOwnerId()) + .isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(observer.response.getReservationClaimFence()).isEqualTo(1L); + assertThat(observer.response.getClaimOwnerId()).isEqualTo(currentOwner.toString()); + assertThat(observer.response.getClaimFence()).isEqualTo(currentFence); + assertThat(observer.response.getClaimExpiresAtEpochMillis()).isEqualTo(OBSERVED_AT + 30_000L); + assertThat(observer.response.getObservedAtEpochMillis()).isEqualTo(OBSERVED_AT); + assertThat(observer.response.getPurpose()).isEqualTo(purpose); + verify(reservationService) + .readCurrentClaimEvidence( + REQUEST_ID, + tuple, + RESERVATION_OWNER_ID, + 1L, + currentOwner, + currentFence, + toPurpose(purpose)); + } + } + + @Test + void deniesMissingUnknownWrongServiceCrossNamespaceAndUnconfiguredPeersBeforeRead() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + for (String peer : + new String[] { + null, + "spiffe://firemud/ns/other/sa/account-service", + "spiffe://firemud/ns/test/sa/game-session-service", + "spiffe://firemud/ns/test/sa/unknown-service" + }) { + assertThat(status(call(request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), peer))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + assertThat( + status( + call( + request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), + ACCOUNT_URI, + UNAPPROVED_LEAF_DER))) + .as("a same-URI certificate without leaf-instance approval must be denied") + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + callWithoutCertificateEvidence( + request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), ACCOUNT_URI))) + .as("a URI principal without presented-leaf evidence must be denied") + .isEqualTo(Status.Code.PERMISSION_DENIED); + + StartSessionReservationEvidenceGrpcService unconfigured = + new StartSessionReservationEvidenceGrpcService( + reservationService, new StartSessionReservationEvidenceLeafApproval(""), ""); + Observer observer = new Observer(); + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(ACCOUNT_URI).orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + unconfigured.readCurrentClaimEvidence( + request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), observer)); + assertThat(status(observer)).isEqualTo(Status.Code.PERMISSION_DENIED); + + StartSessionReservationEvidenceGrpcService missingApprovalFile = + new StartSessionReservationEvidenceGrpcService( + reservationService, + new StartSessionReservationEvidenceLeafApproval( + temporaryDirectory.resolve("missing-approval.txt").toString()), + "test"); + assertThat( + status( + call( + missingApprovalFile, + request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), + ACCOUNT_URI, + APPROVED_LEAF_DER))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(reservationService); + } + + @Test + void deniesHumanCallerContextBeforeOwnerRead() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + SessionContext.setContext("account-uuid", List.of("player"), Map.of()); + + assertThat(status(call(request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), ACCOUNT_URI))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(reservationService); + } + + @Test + void acceptsCanonicalNfcUnicodeRequestIdAtExactUtf8ByteBound() { + String requestId = "é".repeat(64); + StartSessionPreAuthorizationReservationTuple tuple = tuple(requestId); + when(reservationService.readCurrentClaimEvidence( + eq(requestId), + eq(tuple), + eq(RESERVATION_OWNER_ID), + eq(1L), + eq(RESERVATION_OWNER_ID), + eq(1L), + eq(ReadPurpose.ISSUE))) + .thenReturn(Optional.of(evidence(tuple, RESERVATION_OWNER_ID, 1L, ReadPurpose.ISSUE))); + + Observer observer = call(request(tuple), ACCOUNT_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.response.getControlPlaneRequestId()).isEqualTo(requestId); + verify(reservationService) + .readCurrentClaimEvidence( + requestId, + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + ReadPurpose.ISSUE); + } + + @Test + void rejectsNonCanonicalOrTamperedRequestsBeforeOwnerRead() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + List malformed = + List.of( + request(tuple).toBuilder() + .setControlPlaneRequestId("start-session/e\u0301vidence") + .build(), + request(tuple).toBuilder().setControlPlaneRequestId("").build(), + request(tuple).toBuilder().setReservationOwnerId("not-a-uuid").build(), + request(tuple).toBuilder().setReservationClaimFence(0L).build(), + request(tuple).toBuilder().setClaimFence(-1L).build(), + request(tuple).toBuilder() + .setPreAuthorizationTupleJson(ByteString.copyFrom(new byte[] {(byte) 0xc3, 0x28})) + .build(), + request(tuple).toBuilder() + .setPreAuthorizationTupleJson(ByteString.copyFromUtf8(tuple.canonicalJson() + " ")) + .build(), + request(tuple).toBuilder() + .setPurpose( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_UNSPECIFIED) + .build(), + request(tuple).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()); + malformed = new ArrayList<>(malformed); + String overLimitRequestId = "é".repeat(65); + String tupleLimitRequestId = "start-session/overlimit"; + StartSessionPreAuthorizationReservationTuple tupleForLimit = tuple(tupleLimitRequestId); + String overLimitTupleJson = + tupleForLimit + .canonicalJson() + .replace( + "\"requestId\":\"" + tupleLimitRequestId + "\"", + "\"requestId\":\"" + overLimitRequestId + "\""); + assertThat(overLimitTupleJson).isNotEqualTo(tupleForLimit.canonicalJson()); + malformed.add( + request(tupleForLimit).toBuilder() + .setPreAuthorizationTupleJson( + ByteString.copyFrom(overLimitTupleJson.getBytes(StandardCharsets.UTF_8))) + .build()); + malformed.add(request(tuple).toBuilder().setControlPlaneRequestId(overLimitRequestId).build()); + ReadCurrentClaimEvidenceRequest tupleKeyMismatch = + request(tuple).toBuilder().setControlPlaneRequestId("start-session/evidence/other").build(); + malformed.add(tupleKeyMismatch); + for (String nonObjectRoot : List.of("[]", "\"tuple\"", "1", "true", "null")) { + malformed.add( + request(tuple).toBuilder() + .setPreAuthorizationTupleJson(ByteString.copyFromUtf8(nonObjectRoot)) + .build()); + } + + for (ReadCurrentClaimEvidenceRequest request : malformed) { + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(reservationService); + } + + @Test + void failsClosedForAbsentStaleMismatchedOrUnavailableOwnerEvidence() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + ReadCurrentClaimEvidenceRequest request = + request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()); + when(reservationService.readCurrentClaimEvidence( + any(), any(), any(), anyLong(), any(), anyLong(), any())) + .thenReturn(Optional.empty()) + .thenThrow( + new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + REQUEST_ID)) + .thenThrow( + new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + REQUEST_ID)) + .thenThrow(new DataAccessResourceFailureException("offline")) + .thenThrow(new TransientDataAccessResourceException("retry the read")); + + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.NOT_FOUND); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.UNAVAILABLE); + } + + @Test + void mapsOnlyConnectionAndTransientSqlFailuresToUnavailable() { + StartSessionPreAuthorizationReservationTuple tuple = tuple(REQUEST_ID); + ReadCurrentClaimEvidenceRequest request = request(tuple); + when(reservationService.readCurrentClaimEvidence( + any(), any(), any(), anyLong(), any(), anyLong(), any())) + .thenThrow( + new DataAccessException("connection failure", new SQLException("offline", "08006"))) + .thenThrow( + new DataAccessException( + "transient failure", new SQLTransientException("retry the transaction"))) + .thenThrow( + new DataAccessException("syntax failure", new SQLException("syntax error", "42601"))) + .thenThrow( + new DataAccessException( + "constraint failure", new SQLException("unique constraint", "23505"))) + .thenThrow( + new DataAccessException("type failure", new SQLException("type mismatch", "42804"))) + .thenThrow( + new DataAccessException( + "nested connection failure", + new IllegalStateException( + "driver wrapper", new SQLException("connection reset", "08001")))); + + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.INTERNAL); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.INTERNAL); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.INTERNAL); + assertThat(status(call(request, ACCOUNT_URI))).isEqualTo(Status.Code.UNAVAILABLE); + } + + @Test + void canonicalTupleTamperingReachesOwnerComparisonAndConflicts() { + StartSessionPreAuthorizationReservationTuple tamperedTuple = + tuple(REQUEST_ID, "changed audit reason"); + when(reservationService.readCurrentClaimEvidence( + eq(REQUEST_ID), + eq(tamperedTuple), + eq(RESERVATION_OWNER_ID), + eq(1L), + eq(RESERVATION_OWNER_ID), + eq(1L), + eq(ReadPurpose.ISSUE))) + .thenThrow( + new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + REQUEST_ID)); + + Observer observer = call(request(tamperedTuple), ACCOUNT_URI); + + assertThat(status(observer)).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.response).isNull(); + verify(reservationService) + .readCurrentClaimEvidence( + REQUEST_ID, + tamperedTuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + ReadPurpose.ISSUE); + } + + @Test + void exactPublicMethodTraversesJwtAndPeerInterceptorsOverGrpcTransport() throws Exception { + String serverName = InProcessServerBuilder.generateName(); + Server server = + InProcessServerBuilder.forName(serverName) + .directExecutor() + .intercept( + new AuthTokenInterceptor( + new JwtUtil("a".repeat(64), 3_600_000L), + Set.of( + "logging_admin.v1.StartSessionReservationEvidenceService/" + + "ReadCurrentClaimEvidence"))) + .intercept(new GrpcPeerIdentityInterceptor()) + .addService(service) + .addService( + new LoggingAdminServiceGrpc.LoggingAdminServiceImplBase() { + @Override + public void ping(PingRequest request, StreamObserver observer) { + observer.onNext(PingResponse.newBuilder().setMessage("pong").build()); + observer.onCompleted(); + } + }) + .build() + .start(); + ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); + try { + ReadCurrentClaimEvidenceRequest evidenceRequest = request(tuple(REQUEST_ID)); + assertThat( + transportStatus( + () -> + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .readCurrentClaimEvidence(evidenceRequest))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + Metadata invalidJwtHeader = new Metadata(); + invalidJwtHeader.put( + Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer deliberately-invalid"); + assertThat( + transportStatus( + () -> + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .withInterceptors( + MetadataUtils.newAttachHeadersInterceptor(invalidJwtHeader)) + .readCurrentClaimEvidence(evidenceRequest))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + assertThat( + transportStatus( + () -> + LoggingAdminServiceGrpc.newBlockingStub(channel) + .ping(PingRequest.getDefaultInstance()))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(reservationService); + } finally { + channel.shutdownNow(); + server.shutdownNow(); + } + } + + private Observer call(ReadCurrentClaimEvidenceRequest request, String peerUri) { + return call(service, request, peerUri, APPROVED_LEAF_DER); + } + + private Observer call( + ReadCurrentClaimEvidenceRequest request, String peerUri, byte[] leafCertificateDer) { + return call(service, request, peerUri, leafCertificateDer); + } + + private Observer call( + StartSessionReservationEvidenceGrpcService receiver, + ReadCurrentClaimEvidenceRequest request, + String peerUri, + byte[] leafCertificateDer) { + Observer observer = new Observer(); + Runnable invocation = () -> receiver.readCurrentClaimEvidence(request, observer); + Optional peer = + peerUri == null ? Optional.empty() : GrpcPeerIdentity.parseUri(peerUri); + if (peer.isEmpty()) { + invocation.run(); + } else { + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer.orElseThrow()) + .withValue( + GrpcPeerCertificateEvidence.CONTEXT_KEY, certificateEvidence(leafCertificateDer)) + .run(invocation); + } + return observer; + } + + private Observer callWithoutCertificateEvidence( + ReadCurrentClaimEvidenceRequest request, String peerUri) { + Observer observer = new Observer(); + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> service.readCurrentClaimEvidence(request, observer)); + return observer; + } + + private static GrpcPeerCertificateEvidence certificateEvidence(byte[] certificateDer) { + X509Certificate leaf = mock(X509Certificate.class); + try { + when(leaf.getEncoded()).thenReturn(certificateDer); + } catch (CertificateEncodingException exception) { + throw new AssertionError(exception); + } + return GrpcPeerCertificateEvidence.fromCertificate(leaf).orElseThrow(); + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new AssertionError(exception); + } + } + + private static ReadCurrentClaimEvidenceRequest request( + StartSessionPreAuthorizationReservationTuple tuple, + UUID currentOwner, + long currentFence, + StartSessionReservationEvidencePurpose purpose) { + return ReadCurrentClaimEvidenceRequest.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(1L) + .setClaimOwnerId(currentOwner.toString()) + .setClaimFence(currentFence) + .setPurpose(purpose) + .build(); + } + + private static ReadCurrentClaimEvidenceRequest request( + StartSessionPreAuthorizationReservationTuple tuple) { + return request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()); + } + + private static StartSessionReservationEvidencePurpose issuePurpose() { + return StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE; + } + + private static ReadPurpose toPurpose(StartSessionReservationEvidencePurpose purpose) { + return switch (purpose) { + case START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE -> ReadPurpose.ISSUE; + case START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER -> ReadPurpose.RECOVER; + default -> throw new IllegalArgumentException("unsupported purpose"); + }; + } + + private static CurrentClaimEvidence evidence( + StartSessionPreAuthorizationReservationTuple tuple, + UUID currentOwner, + long currentFence, + ReadPurpose purpose) { + Snapshot snapshot = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + 1L, + currentFence, + OBSERVED_AT + 30_000L, + ClaimState.ACTIVE, + currentFence == 1L ? ClaimPurpose.ORIGINAL : ClaimPurpose.AUTHORIZATION_RECOVERY); + return new CurrentClaimEvidence( + snapshot, RESERVATION_OWNER_ID, currentOwner, purpose, OBSERVED_AT); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + return tuple(requestId, "evidence read test"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + String requestId, String auditReason) { + SessionContext.setContext( + "863843ee-f00a-4905-a9ad-11f706f1b693", + List.of(), + Map.of("3d3c5ca5-6d43-4db6-821d-8a0de883a467", List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope( + UUID.fromString("3d3c5ca5-6d43-4db6-821d-8a0de883a467"), "world-runtime"), + new StartSessionOperatorAction.Target( + 29L, UUID.fromString("be78a8de-a113-48c4-a247-39e3505aed8c")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + SessionContext.clear(); + return tuple; + } + + private static Status.Code status(Observer observer) { + return observer.failure; + } + + private static Status.Code transportStatus(Runnable call) { + try { + call.run(); + return Status.Code.OK; + } catch (StatusRuntimeException ex) { + return ex.getStatus().getCode(); + } + } + + private static final class Observer implements StreamObserver { + private ReadCurrentClaimEvidenceResponse response; + private Status.Code failure; + private boolean completed; + + @Override + public void onNext(ReadCurrentClaimEvidenceResponse value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failure = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApprovalTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApprovalTest.java new file mode 100644 index 0000000000..24d5e737c5 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceLeafApprovalTest.java @@ -0,0 +1,151 @@ +package unit.net.firedevops.firemud.loggingadmin.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.HexFormat; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceLeafApproval; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class StartSessionReservationEvidenceLeafApprovalTest { + private static final byte[] ACTIVE_LEAF_DER = + "active account leaf".getBytes(StandardCharsets.US_ASCII); + private static final byte[] OVERLAP_LEAF_DER = + "renewing account leaf".getBytes(StandardCharsets.US_ASCII); + private static final String ACTIVE_FINGERPRINT = sha256(ACTIVE_LEAF_DER); + private static final String OVERLAP_FINGERPRINT = sha256(OVERLAP_LEAF_DER); + + @TempDir Path temporaryDirectory; + + @Test + void matchesOnlyTheCurrentLeafAndReadsTrustedReplacementOnEachCall() throws Exception { + Path policy = temporaryDirectory.resolve("approved-leaves.txt"); + write(policy, "active=" + ACTIVE_FINGERPRINT + "\n"); + StartSessionReservationEvidenceLeafApproval approval = approval(policy); + + assertThat(approval.isApproved(evidence(ACTIVE_LEAF_DER))).isTrue(); + assertThat(approval.isApproved(evidence(OVERLAP_LEAF_DER))).isFalse(); + + write(policy, "active=" + OVERLAP_FINGERPRINT + "\n"); + + assertThat(approval.isApproved(evidence(ACTIVE_LEAF_DER))).isFalse(); + assertThat(approval.isApproved(evidence(OVERLAP_LEAF_DER))).isTrue(); + } + + @Test + void acceptsOneExplicitOverlapOnlyUntilItsAbsoluteExpiry() throws Exception { + Path policy = temporaryDirectory.resolve("approved-leaves.txt"); + long expiresAt = System.currentTimeMillis() + 60_000L; + write( + policy, + "active=" + + ACTIVE_FINGERPRINT + + "\noverlap=" + + OVERLAP_FINGERPRINT + + ";expires-at=" + + expiresAt + + "\n"); + StartSessionReservationEvidenceLeafApproval approval = approval(policy); + + assertThat(approval.isApproved(evidence(ACTIVE_LEAF_DER))).isTrue(); + assertThat(approval.isApproved(evidence(OVERLAP_LEAF_DER))).isTrue(); + + write( + policy, + "active=" + + ACTIVE_FINGERPRINT + + "\noverlap=" + + OVERLAP_FINGERPRINT + + ";expires-at=" + + (System.currentTimeMillis() - 1L) + + "\n"); + + assertThat(approval.isApproved(evidence(ACTIVE_LEAF_DER))).isTrue(); + assertThat(approval.isApproved(evidence(OVERLAP_LEAF_DER))).isFalse(); + } + + @Test + void missingUnreadableMalformedOrAmbiguousPolicyDenies() throws Exception { + Path missing = temporaryDirectory.resolve("missing.txt"); + assertThat(approval(missing).isApproved(evidence(ACTIVE_LEAF_DER))).isFalse(); + + Path directory = Files.createDirectory(temporaryDirectory.resolve("directory-policy")); + assertThat(approval(directory).isApproved(evidence(ACTIVE_LEAF_DER))).isFalse(); + + Path malformed = temporaryDirectory.resolve("malformed.txt"); + for (String content : + new String[] { + "", + "active=" + ACTIVE_FINGERPRINT.toUpperCase() + "\n", + "active=" + ACTIVE_FINGERPRINT + "\nactive=" + OVERLAP_FINGERPRINT + "\n", + "active=" + + ACTIVE_FINGERPRINT + + "\noverlap=" + + ACTIVE_FINGERPRINT + + ";expires-at=9999999999999\n", + "active=" + + ACTIVE_FINGERPRINT + + "\noverlap=" + + OVERLAP_FINGERPRINT + + ";expires-at=not-a-time\n", + "active=" + + ACTIVE_FINGERPRINT + + "\nactive=" + + OVERLAP_FINGERPRINT + + "\nactive=" + + ACTIVE_FINGERPRINT + + "\n" + }) { + write(malformed, content); + assertThat(approval(malformed).isApproved(evidence(ACTIVE_LEAF_DER))) + .as("policy content must fail closed: %s", content) + .isFalse(); + } + } + + @Test + void rejectsMissingEvidenceAndRelativePolicyPaths() throws Exception { + Path policy = temporaryDirectory.resolve("approved-leaves.txt"); + write(policy, "active=" + ACTIVE_FINGERPRINT + "\n"); + assertThat(approval(policy).isApproved(null)).isFalse(); + assertThat( + new StartSessionReservationEvidenceLeafApproval("relative-policy.txt") + .isApproved(evidence(ACTIVE_LEAF_DER))) + .isFalse(); + } + + private static StartSessionReservationEvidenceLeafApproval approval(Path path) { + return new StartSessionReservationEvidenceLeafApproval(path.toString()); + } + + private static GrpcPeerCertificateEvidence evidence(byte[] der) { + X509Certificate leaf = mock(X509Certificate.class); + try { + when(leaf.getEncoded()).thenReturn(der); + } catch (CertificateEncodingException exception) { + throw new AssertionError(exception); + } + return GrpcPeerCertificateEvidence.fromCertificate(leaf).orElseThrow(); + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new AssertionError(exception); + } + } + + private static void write(Path path, String value) throws Exception { + Files.writeString(path, value, StandardCharsets.US_ASCII); + } +} diff --git a/services/logging-admin-service/src/testFixtures/java/net/firedevops/firemud/loggingadmin/StartSessionReservationMutationTestFixtures.java b/services/logging-admin-service/src/testFixtures/java/net/firedevops/firemud/loggingadmin/StartSessionReservationMutationTestFixtures.java new file mode 100644 index 0000000000..6f4e357b00 --- /dev/null +++ b/services/logging-admin-service/src/testFixtures/java/net/firedevops/firemud/loggingadmin/StartSessionReservationMutationTestFixtures.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.loggingadmin; + +import java.lang.reflect.Constructor; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Clock; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.jooq.ConnectionProvider; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.mockito.Mockito; +import org.postgresql.ds.PGSimpleDataSource; +import org.testcontainers.containers.PostgreSQLContainer; + +/** Test-fixture-only constructors for isolated reservation mutation proofs. */ +public final class StartSessionReservationMutationTestFixtures { + private static final String MUTATION_CAPABILITY = "MutationCapability"; + private static final String DEFAULT_SCHEMA = "public"; + + private StartSessionReservationMutationTestFixtures() {} + + public static TestcontainersScope forRunOwnedPostgres(PostgreSQLContainer container) { + return forRunOwnedPostgres(container, DEFAULT_SCHEMA); + } + + public static TestcontainersScope forRunOwnedPostgres( + PostgreSQLContainer container, String schema) { + requireRunOwnedPostgres(container, schema); + String jdbcUrl = container.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + PGSimpleDataSource dataSource = new PGSimpleDataSource(); + dataSource.setURL(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUser(container.getUsername()); + dataSource.setPassword(container.getPassword()); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + verifyRunOwnedSchema(dsl, container, schema); + StartSessionPreAuthorizationReservationRepository repository = instantiateRepository(dsl); + StartSessionPreAuthorizationReservationService service = + instantiateService(repository, Clock.systemUTC()); + return new TestcontainersScope(repository, service); + } + + public static StartSessionPreAuthorizationReservationService forMockBackedUnitTest( + StartSessionPreAuthorizationReservationRepository repository, Clock clock) { + Objects.requireNonNull(repository, "repository is required"); + Objects.requireNonNull(clock, "clock is required"); + if (!Mockito.mockingDetails(repository).isMock()) { + throw new IllegalArgumentException("unit-test mutation scope requires a mocked repository"); + } + return instantiateService(repository, clock); + } + + private static void requireRunOwnedPostgres(PostgreSQLContainer container, String schema) { + Objects.requireNonNull(container, "run-owned PostgreSQL container is required"); + if (!container.isRunning()) { + throw new IllegalArgumentException("run-owned PostgreSQL container must already be running"); + } + if (schema == null || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalArgumentException("run-owned PostgreSQL schema name is invalid"); + } + } + + private static void verifyRunOwnedSchema( + DSLContext dsl, PostgreSQLContainer container, String expectedSchema) { + ConnectionProvider connectionProvider = + Objects.requireNonNull( + dsl.configuration().connectionProvider(), "DSLContext connection provider is required"); + try { + Connection connection = + Objects.requireNonNull( + connectionProvider.acquire(), "run-owned PostgreSQL connection is required"); + try { + String actualUrl = connection.getMetaData().getURL(); + if (!databaseEndpoint(actualUrl).equals(databaseEndpoint(container.getJdbcUrl()))) { + throw new IllegalArgumentException( + "mutation scope must use the exact run-owned PostgreSQL container database"); + } + } finally { + connectionProvider.release(connection); + } + String actualSchema = + dsl.select(DSL.field("current_schema()", String.class)).fetchOne(0, String.class); + if (!expectedSchema.equals(actualSchema)) { + throw new IllegalArgumentException( + "mutation scope must use the exact run-owned PostgreSQL schema"); + } + } catch (SQLException exception) { + throw new IllegalArgumentException( + "run-owned PostgreSQL mutation scope could not be verified", exception); + } + } + + private static String databaseEndpoint(String jdbcUrl) { + int queryStart = jdbcUrl.indexOf('?'); + return queryStart < 0 ? jdbcUrl : jdbcUrl.substring(0, queryStart); + } + + private static StartSessionPreAuthorizationReservationRepository instantiateRepository( + DSLContext dsl) { + Class capabilityType = + capabilityType(StartSessionPreAuthorizationReservationRepository.class); + Object capability = instantiateCapability(capabilityType); + return instantiate( + StartSessionPreAuthorizationReservationRepository.class, + new Class[] {DSLContext.class, capabilityType}, + dsl, + capability); + } + + private static StartSessionPreAuthorizationReservationService instantiateService( + StartSessionPreAuthorizationReservationRepository repository, Clock clock) { + Class capabilityType = capabilityType(StartSessionPreAuthorizationReservationService.class); + Object capability = instantiateCapability(capabilityType); + return instantiate( + StartSessionPreAuthorizationReservationService.class, + new Class[] { + StartSessionPreAuthorizationReservationRepository.class, Clock.class, capabilityType + }, + repository, + clock, + capability); + } + + private static Class capabilityType(Class owner) { + return Arrays.stream(owner.getDeclaredClasses()) + .filter(candidate -> candidate.getSimpleName().equals(MUTATION_CAPABILITY)) + .findFirst() + .orElseThrow( + () -> + new IllegalStateException("private mutation capability is missing from " + owner)); + } + + private static Object instantiateCapability(Class capabilityType) { + return instantiate(capabilityType, new Class[0]); + } + + private static T instantiate(Class type, Class[] parameterTypes, Object... arguments) { + try { + Constructor constructor = type.getDeclaredConstructor(parameterTypes); + constructor.setAccessible(true); + return constructor.newInstance(arguments); + } catch (ReflectiveOperationException exception) { + throw new IllegalStateException("test-only mutation fixture construction failed", exception); + } + } + + public record TestcontainersScope( + StartSessionPreAuthorizationReservationRepository repository, + StartSessionPreAuthorizationReservationService service) { + public TestcontainersScope { + Objects.requireNonNull(repository, "repository is required"); + Objects.requireNonNull(service, "service is required"); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java index 1a56f6ad2c..536fb0bd68 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java @@ -18,18 +18,34 @@ public final class WorldCanonicalInstancePreparationService { private final WorldCanonicalInstancePreparationRepository repository; private final CommitAuthorityVerifier verifier; + private final OriginalOperationRecoveryVerifier recoveryVerifier; /** Constructs the production-safe default: all attempts fail closed. */ public WorldCanonicalInstancePreparationService( WorldCanonicalInstancePreparationRepository repository) { - this(repository, WorldCanonicalInstancePreparationService::denyByDefault); + this( + repository, + WorldCanonicalInstancePreparationService::denyByDefault, + WorldCanonicalInstancePreparationService::denyRecoveryByDefault); } /** Constructor for an explicitly supplied owner verifier, including labeled synthetic tests. */ public WorldCanonicalInstancePreparationService( WorldCanonicalInstancePreparationRepository repository, CommitAuthorityVerifier verifier) { + this(repository, verifier, WorldCanonicalInstancePreparationService::denyRecoveryByDefault); + } + + /** + * Constructor for explicit fresh-execution and original-operation recovery verifiers. No + * production verifier is supplied in this slice. + */ + public WorldCanonicalInstancePreparationService( + WorldCanonicalInstancePreparationRepository repository, + CommitAuthorityVerifier verifier, + OriginalOperationRecoveryVerifier recoveryVerifier) { this.repository = Objects.requireNonNull(repository, "repository"); this.verifier = Objects.requireNonNull(verifier, "verifier"); + this.recoveryVerifier = Objects.requireNonNull(recoveryVerifier, "recoveryVerifier"); } /** @@ -54,17 +70,54 @@ public Result prepare(Input input) { } } + /** + * Authenticates and reads only the exact retained World operation. This path deliberately does + * not obtain a held commit authority, reassemble external sources, materialize, or abort. It is + * available after original authorization expiry without granting a mutation retry. An absent or + * PENDING lookup is unresolved evidence, not an abort, settlement, or admission. The separate + * serialized durable-abort boundary remains distinct from this read-only lookup. + */ + public WorldCanonicalInstancePreparationRepository.ExecutionLookup recoverExact( + WorldCanonicalInstanceExecutionIdentity originalIdentity) { + Objects.requireNonNull(originalIdentity, "original World execution identity is required"); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Exact World execution recovery must authenticate outside an ambient transaction"); + } + + recoveryVerifier.verifyOriginalOperation(originalIdentity); + return repository.readExactExecution(originalIdentity); + } + private static HeldCommitAuthority denyByDefault(Input input) { throw new PreparationDeniedException( "Canonical World preparation has no authenticated source/release terminal verifier"); } + private static void denyRecoveryByDefault(WorldCanonicalInstanceExecutionIdentity identity) { + throw new PreparationDeniedException( + "Canonical World execution recovery has no authenticated original-operation verifier"); + } + /** Performs authenticated producer checks before returning a continuously held local fence. */ @FunctionalInterface public interface CommitAuthorityVerifier { HeldCommitAuthority verifyAndHold(Input input); } + /** + * Authenticates the exact configured same-namespace Game Session producer and verifies the + * retained original Account participation, actual Game Session attempt/fence, and immutable + * descriptor, release, source association, and canonical World target in {@code + * originalIdentity}. The typed identity is integrity input, not permission. Implementations must + * not reacquire, refresh, or renew participation or authorization, and must perform all remote + * checks before the exact read-only repository lookup. + */ + @FunctionalInterface + public interface OriginalOperationRecoveryVerifier { + void verifyOriginalOperation(WorldCanonicalInstanceExecutionIdentity originalIdentity); + } + /** * A verifier-owned, continuously held producer-evidence handle. It stays open throughout the * World transaction and its commit; implementations must fail closed from {@link #requireHeld()} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java new file mode 100644 index 0000000000..50815f5f2b --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java @@ -0,0 +1,163 @@ +package unit.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.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +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 java.util.Optional; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceExecutionIdentity; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionLookup; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionOperation; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionState; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInstancePreparationServiceTest { + @AfterEach + void clearAmbientTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void defaultConstructorsDenyRecoveryWithoutTouchingRepository() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var identity = mock(WorldCanonicalInstanceExecutionIdentity.class); + + assertThatThrownBy( + () -> new WorldCanonicalInstancePreparationService(repository).recoverExact(identity)) + .isInstanceOf(WorldCanonicalInstancePreparationService.PreparationDeniedException.class) + .hasMessageContaining("no authenticated original-operation verifier"); + + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + assertThatThrownBy( + () -> + new WorldCanonicalInstancePreparationService(repository, commitVerifier) + .recoverExact(identity)) + .isInstanceOf(WorldCanonicalInstancePreparationService.PreparationDeniedException.class) + .hasMessageContaining("no authenticated original-operation verifier"); + + verifyNoInteractions(repository, commitVerifier); + } + + @Test + void recoveryVerifierDenialPrecedesTheExactRepositoryRead() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var recoveryVerifier = + mock(WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier.class); + var identity = mock(WorldCanonicalInstanceExecutionIdentity.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + doThrow(new WorldCanonicalInstancePreparationService.PreparationDeniedException("denied")) + .when(recoveryVerifier) + .verifyOriginalOperation(identity); + var service = + new WorldCanonicalInstancePreparationService(repository, commitVerifier, recoveryVerifier); + + assertThatThrownBy(() -> service.recoverExact(identity)) + .isInstanceOf(WorldCanonicalInstancePreparationService.PreparationDeniedException.class) + .hasMessage("denied"); + + verifyNoInteractions(repository, commitVerifier); + } + + @Test + void ambientTransactionIsDeniedBeforeRecoveryAuthenticationOrStorage() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var recoveryVerifier = + mock(WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier.class); + var identity = mock(WorldCanonicalInstanceExecutionIdentity.class); + var service = + new WorldCanonicalInstancePreparationService( + repository, + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class), + recoveryVerifier); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> service.recoverExact(identity)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must authenticate outside an ambient transaction"); + + verifyNoInteractions(repository, recoveryVerifier); + } + + @Test + void exactRecoveryAuthenticatesThenReturnsTheUnchangedReadOnlyLookup() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var recoveryVerifier = + mock(WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier.class); + var identity = mock(WorldCanonicalInstanceExecutionIdentity.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + var operation = new ExecutionOperation(ExecutionState.COMMITTED, 73L, 991L); + var lookup = new ExecutionLookup(Optional.of(operation), true); + when(repository.readExactExecution(identity)).thenReturn(lookup); + var service = + new WorldCanonicalInstancePreparationService(repository, commitVerifier, recoveryVerifier); + + ExecutionLookup result = service.recoverExact(identity); + + assertThat(result).isSameAs(lookup); + var order = inOrder(recoveryVerifier, repository); + order.verify(recoveryVerifier).verifyOriginalOperation(identity); + order.verify(repository).readExactExecution(identity); + verifyNoMoreInteractions(repository); + verifyNoInteractions(commitVerifier); + } + + @Test + void expiredOriginalOperationCanBeReadWithoutStartingFreshExecution() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var recoveryVerifier = + mock(WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier.class); + var identity = mock(WorldCanonicalInstanceExecutionIdentity.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + var lookup = + new ExecutionLookup( + Optional.of(new ExecutionOperation(ExecutionState.COMMITTED, 74L, 992L)), false); + when(repository.readExactExecution(identity)).thenReturn(lookup); + var service = + new WorldCanonicalInstancePreparationService(repository, commitVerifier, recoveryVerifier); + + assertThat(service.recoverExact(identity)).isSameAs(lookup); + assertThat(lookup.originalAuthorizationValidAtRead()).isFalse(); + verify(recoveryVerifier).verifyOriginalOperation(identity); + verify(repository).readExactExecution(identity); + verifyNoMoreInteractions(repository); + verifyNoInteractions(commitVerifier); + } + + @Test + void missingExpiredOperationRemainsUnresolvedAndIsNotAbortedOrAdmitted() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var recoveryVerifier = + mock(WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier.class); + var identity = mock(WorldCanonicalInstanceExecutionIdentity.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + var lookup = new ExecutionLookup(Optional.empty(), false); + when(repository.readExactExecution(identity)).thenReturn(lookup); + var service = + new WorldCanonicalInstancePreparationService(repository, commitVerifier, recoveryVerifier); + + ExecutionLookup result = service.recoverExact(identity); + + assertThat(result).isSameAs(lookup); + assertThat(result.operation()).isEmpty(); + assertThat(result.originalAuthorizationValidAtRead()).isFalse(); + verify(recoveryVerifier).verifyOriginalOperation(identity); + verify(repository).readExactExecution(identity); + verifyNoMoreInteractions(repository); + verifyNoInteractions(commitVerifier); + } +} From 1a860a9468f2ce571de10e3a23e054f702f55e3f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:29:29 +1300 Subject: [PATCH 066/129] Add exact World initial-admission hold-state readback and terminal carrier --- .../world-management-service/api-contracts.md | 2 + .../runtime-and-data.md | 12 + .../world-runtime-and-movement.md | 4 + ...rld_canonical_initial_admission_hold.proto | 21 + ...rldCanonicalInitialAdmissionHoldState.java | 205 ++++++ .../WorldStartSessionExecutionTerminal.java | 515 ++++++++++++++ ...anonicalInitialAdmissionHoldStateTest.java | 309 ++++++++ ...orldStartSessionExecutionTerminalTest.java | 667 ++++++++++++++++++ ...onicalInitialAdmissionHoldGrpcService.java | 166 ++++- ...nonicalInitialAdmissionHoldRepository.java | 104 +++ ...nHoldMigrationPostgresIntegrationTest.java | 76 ++ ...alInitialAdmissionHoldGrpcServiceTest.java | 188 +++++ ...calInitialAdmissionHoldRepositoryTest.java | 159 +++++ 13 files changed, 2423 insertions(+), 5 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminal.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.java diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 12dbbb36ff..6fd6ee61fd 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -13,6 +13,7 @@ This API contract is target-state canonical; implementation coverage is partial - The standalone canonical initial-placement adapter now defines an Entity Management-only historical terminal-result read. Its proto and handler remain unregistered; the read supplies settlement evidence for the exact immutable placement operation, without admitting gameplay or directly mutating any hold. - The authored-world intake construction reads its complete immutable Game Design source through the exact authenticated owner-read contract in [Game Design API Contracts](../game-design-service/api-contracts.md#authored-world-source-readback). The intake transport remains unregistered and does not authorize source mutation, instance preparation, publication, or runtime admission. - The separate canonical StartSession preparation construction must use the distinct Account World receiving participation and World-local terminal serialization described in [World runtime/data](runtime-and-data.md#original-startsession-execution-storage). Its typed execution identity is binding data, not authenticated authorization. No runtime RPC or positive producer is registered by these storage seams; the ordinary lifecycle handler's Game Session peer guard does not complete this canonical path. +- The unregistered canonical initial-admission hold adapter includes a separate exact hold-state/lifecycle read. The repository reads actual status and current lifecycle in one read-only snapshot; historical identity readback remains unchanged. Focused mock/unit definitions and a synthetic legacy-row PostgreSQL definition are not genuine database-to-RPC or continuous-protection proof. - 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. ## gRPC APIs @@ -30,6 +31,7 @@ This API contract is target-state canonical; implementation coverage is partial - `ActivatePreparedWorldInstance` – performs the fenced `PREPARING -> ACTIVE` lifecycle transition after Game Session has finished local start-up work for the same `gameInstanceId`. - `FailPreparedWorldInstance` – performs the fenced `PREPARING -> FAILED_PRE_ACTIVATION` transition when Game Session or another pre-admission consumer must roll back a prepared instance before admission opens. - `GetWorldInstanceLifecycle` – returns the current fenced lifecycle snapshot for an existing `(tenantId, gameInstanceId)` so stop/cutover consumers can retry against fresh lifecycle truth instead of cached guesses. +- `ReadCanonicalInitialAdmissionHoldState` – the unregistered canonical hold adapter accepts a fresh canonical non-nil `readRequestId`, complete immutable hold identity bytes and a complete canonical lifecycle read request with that same read UUID. Only verified same-namespace Game Session without end-user caller context may read; authentication and ambient-transaction denial precede parsing or owner queries. The response echoes the exact read UUID and returns the [closed same-snapshot state carrier](./runtime-and-data.md#canonical-initial-admission-hold-state-snapshot). Unknown protobuf fields, mixed scope or correlation, substituted identity/fence and incomplete owner evidence deny. This is distinct from historical `ReadCanonicalInitialAdmissionHoldIdentity` and StartSession execution-terminal recovery; it neither acquires nor resolves a hold. - `TerminateWorldInstance` – requests or resumes fenced termination from `PREPARING`, `FAILED_PRE_ACTIVATION`, or `ACTIVE`; it reports `TERMINATED` only after every owner in the frozen required cleanup-owner snapshot captured for `terminationRequestId`, together with its ownership-registry revision, acknowledges cleanup and the final lifecycle CAS commits against that same snapshot. The gRPC contract for world operations is located in [../../../../protos/world-management/v1](../../../../protos/world-management/v1). Run `./gradlew generateProto` to regenerate sources after editing these files. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index bcee5df2a8..ab3530959e 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -35,6 +35,18 @@ Execution admission, materialization, canonical association and `COMMITTED` publ Exact recovery compares the retained full identity and immutable terminal preparation result. Its service read path authenticates the original operation outside SQL, separately from fresh-admission verification, and reads only that stored operation; ingress expiry cannot turn it into renewed execution. Existing constructors deny recovery unless an explicit original-operation verifier is supplied. A separate `ABORTED` transaction takes the same operation and target serialization, excludes a live execution and permanently fences later materialization and canonical association. Missing rows, timeouts and rolled-back intermediate states are not abort proof. An unknown outcome remains unresolved until exact `COMMITTED` readback or serialized `ABORTED` proof; Account retains its source protection until authenticated terminal settlement. These storage rules do not supply the missing genuine Account participation producer or authenticated terminal transport. The canonical preparation service remains unavailable for runtime use until that producer, consumer and physical concurrency/recovery proof are complete. +The immutable integrity carrier is `world-start-session-execution-terminal/v1`. Its closed RFC 8785 UTF-8 object contains exactly `schema`, `originalPostAuthorizationTupleBase64`, `accountWorldParticipationId`, `accountWorldParticipationFence`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `targetNamespace`, `canonicalTenantId`, `controlPlaneRequestId`, `canonicalGameInstanceId`, `preparationInputDigest`, `preparationInputJson`, `worldExecutionFence`, and `outcome`. The original post-authorization tuple remains byte-exact with `targetOwner=game-session-service`; the duplicated namespace, tenant and request must match it. UUIDs are canonical and non-nil. Each fence is an independently owned positive BIGINT represented as a canonical decimal string; equal numeric values across owners are permitted, not evidence of an alias. Outcomes are only `COMMITTED` or `ABORTED`. + +`preparationInputJson` retains the exact original World preparation-input string, including the complete authenticated source, descriptor and release binding; its `preparationInputDigest` is `sha256:` followed by lowercase SHA-256 hex of that exact UTF-8 string, without reparsing or normalization. The terminal digest covers the complete canonical carrier in the same prefixed form. Closed decoding rejects unknown, duplicate, malformed, noncanonical and substituted fields and checks the 24 MiB envelope bound before parsing. Fresh read correlation, observation time and private World numeric row keys are not immutable terminal fields. This codec proves integrity only: producer authentication, exact durable owner readback and Account settlement must be proved separately before it can release source protection. + +### Canonical initial-admission hold-state snapshot + +The immutable canonical initial-admission hold identity is historical acquisition evidence and is never a live protection status. A separate read uses one read-only `REPEATABLE_READ` World transaction to resolve the persisted association, compare the complete supplied immutable identity including hold ID/fence, and read the actual hold status together with complete current lifecycle evidence for that exact target. Missing identity is not abort proof; detached, incomplete or contradictory association, identity or lifecycle evidence denies the read. It performs no acquisition, materialization, hold settlement or other mutation. + +The closed RFC 8785 carrier `world-canonical-initial-admission-hold-state/v1` has exactly `schema`, `holdIdentityBytesBase64`, `holdStatus`, and `lifecycleEvidenceBytesBase64`. Both nested records retain their existing canonical bytes; status is `PENDING`, `RECONCILIATION_REQUIRED`, `COMMITTED`, or `ABORTED`. The complete namespace, tenant, world, instance, playable-state namespace/scope and version must match across identity and lifecycle. The original preparation request and the initial-admission request remain distinct identities. Decode limits are 4 MiB for the state, 64 KiB for hold identity and 2 MiB for lifecycle evidence. + +Only a sampled `PENDING` status with `ACTIVE` lifecycle and the exact expected lifecycle epoch qualifies the current hold observation. Terminal, reconciling, changed-epoch or non-ACTIVE observations do not qualify; their actual state is not rewritten into `PENDING`. Even a qualifying observation is not continuous commit protection or an admission grant. The owner serialization and exact terminal-resolution rules in the [initial-admission hold contract](./api-contracts.md#initial-admission-bind-hold-contract) remain required. + ### Template Identifier Invariants World templates follow the same stability rules as entity templates: 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 07a68d4469..7510d6e4e9 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -12,6 +12,10 @@ The initial-admission implementation now includes the typed Game Session workloa The unregistered [canonical initial-placement terminal read](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-placement-terminal-readback) returns exact historical operation evidence without current placement authorization. Its [socket mTLS proof](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlacementOutcomeMtlsTest.java) executes against the real handler and a mock owner; it is not database-to-socket or live settlement proof. The [PostgreSQL definition](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java) checks retained `APPLIED`/`CONFLICT` bytes and no mutation when new placement authority is denied; corrected physical execution remains pending. Physical readback after canonical termination remains an explicit World lifecycle/cleanup obligation: the legacy numeric-key termination writer is correctly rejected by the canonical execution-manifest guard and cannot manufacture that test state. Revisit the post-termination proof when the canonical owner transition and required cleanup acknowledgements are implemented; do not bypass the guard or infer termination from missing state. +The unregistered [canonical initial-admission hold-state snapshot](../../architecture/microservices/world-management-service/runtime-and-data.md#canonical-initial-admission-hold-state-snapshot) now has a closed Common carrier, method-specific Game Session peer guard and one read-only `REPEATABLE_READ` repository read of exact immutable identity, actual hold status and current lifecycle. Existing hold identity and acquisition bytes are unchanged. Executed Common and mock-owner unit cases cover peer-first/no-query denial, independent request IDs, exact target/fence, all hold statuses, lifecycle advancement and no mutation. The corrected composed Common/World full checks pass with 489 Common and 609 World unit cases, zero failures/errors/skips; unchanged successful World tasks reuse their local results. Of 220 World integration definitions, one non-container case executes and 219 skip without Docker. The new PostgreSQL definition reads synthetic legacy migration rows only; it does not exercise the canonical repository or genuine lifecycle evidence through the RPC and has not executed locally. Physical producer/consumer proof remains required; no runtime registration or continuous-protection credit follows from the sampled read. + +The [original StartSession terminal integrity carrier](../../architecture/microservices/world-management-service/runtime-and-data.md#original-startsession-execution-storage) preserves the complete original tuple, independent Account/Game Session/World identities and fences, exact preparation bytes and terminal outcome. Its six executed codec cases, including the corrected frozen canonical vector, do not authenticate a producer or settle Account source protection. Genuine Account World participation, authenticated original-operation terminal transport and physical expiry/abort/crash/recovery proof 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/world-management/v1/world_canonical_initial_admission_hold.proto b/protos/world-management/v1/world_canonical_initial_admission_hold.proto index f33c447ac0..2f48ee952d 100644 --- a/protos/world-management/v1/world_canonical_initial_admission_hold.proto +++ b/protos/world-management/v1/world_canonical_initial_admission_hold.proto @@ -12,6 +12,8 @@ service WorldCanonicalInitialAdmissionHoldService { returns (AcquireCanonicalInitialAdmissionHoldResponse); rpc ReadCanonicalInitialAdmissionHoldIdentity(ReadCanonicalInitialAdmissionHoldIdentityRequest) returns (ReadCanonicalInitialAdmissionHoldIdentityResponse); + rpc ReadCanonicalInitialAdmissionHoldState(ReadCanonicalInitialAdmissionHoldStateRequest) + returns (ReadCanonicalInitialAdmissionHoldStateResponse); } message AcquireCanonicalInitialAdmissionHoldRequest { @@ -43,3 +45,22 @@ message ReadCanonicalInitialAdmissionHoldIdentityResponse { // admission, or an absence checkpoint. bytes hold_identity_bytes = 2; } + +message ReadCanonicalInitialAdmissionHoldStateRequest { + // Fresh non-nil UUID correlation for this read, in canonical lowercase form. + string read_request_id = 1; + + // Complete immutable World-issued hold identity bytes, not merely the acquisition request. + bytes hold_identity_bytes = 2; + + // Complete closed canonical World lifecycle read request for the same target and read UUID. + bytes canonical_lifecycle_read_request_bytes = 3; +} + +message ReadCanonicalInitialAdmissionHoldStateResponse { + // Exact correlation echoed from this read request. + string read_request_id = 1; + + // Closed canonical same-snapshot hold status and complete lifecycle evidence. + bytes hold_state_bytes = 2; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java new file mode 100644 index 0000000000..4c72e7064d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java @@ -0,0 +1,205 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed same-snapshot readback of a canonical initial-admission hold and its current lifecycle. + * + *

This is evidence of one observed owner snapshot, not a continuous hold, an admission grant, or + * authorization to mutate either owner's state. + */ +public record WorldCanonicalInitialAdmissionHoldState( + WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity, + HoldStatus holdStatus, + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence) { + public static final String SCHEMA = "world-canonical-initial-admission-hold-state/v1"; + public static final int MAX_CANONICAL_BYTES = 4 * 1024 * 1024; + private static final int MAX_HOLD_IDENTITY_BYTES = 64 * 1024; + private static final int MAX_LIFECYCLE_EVIDENCE_BYTES = 2 * 1024 * 1024; + private static final Set FIELDS = + Set.of("schema", "holdIdentityBytesBase64", "holdStatus", "lifecycleEvidenceBytesBase64"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + public WorldCanonicalInitialAdmissionHoldState { + Objects.requireNonNull(holdIdentity, "holdIdentity"); + Objects.requireNonNull(holdStatus, "holdStatus"); + Objects.requireNonNull(lifecycleEvidence, "lifecycleEvidence"); + requireTargetBinding(holdIdentity, lifecycleEvidence); + if (holdIdentity.canonicalBytes().length > MAX_HOLD_IDENTITY_BYTES + || lifecycleEvidence.canonicalBytes().length > MAX_LIFECYCLE_EVIDENCE_BYTES) { + throw new IllegalArgumentException("Canonical World hold-state evidence exceeds its limit"); + } + } + + /** + * Exact canonical readback bytes, including immutable identity and complete current lifecycle. + */ + public byte[] canonicalBytes() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put( + "holdIdentityBytesBase64", + Base64.getEncoder().encodeToString(holdIdentity.canonicalBytes())); + value.put("holdStatus", holdStatus.name()); + value.put( + "lifecycleEvidenceBytesBase64", + Base64.getEncoder().encodeToString(lifecycleEvidence.canonicalBytes())); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (canonical.length > MAX_CANONICAL_BYTES) { + throw new IllegalStateException("Canonical World hold-state evidence exceeds its limit"); + } + return canonical; + } catch (IOException impossible) { + throw new IllegalStateException( + "Canonical World hold-state evidence cannot be encoded", impossible); + } + } + + /** + * This one read can identify the currently pending hold at its expected active epoch. It does not + * prove that protection remains continuous after this snapshot or authorize a commit. + */ + public boolean isPendingAtExpectedActiveEpoch() { + return holdStatus == HoldStatus.PENDING + && "ACTIVE".equals(lifecycleEvidence.lifecycleStatus()) + && lifecycleEvidence.lifecycleEpoch() == holdIdentity.request().activeLifecycleEpoch(); + } + + /** Decodes only complete, canonical, bounded state and both exact nested owner records. */ + public static WorldCanonicalInitialAdmissionHoldState fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + if (stored.length == 0 || stored.length > MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Canonical World hold-state evidence exceeds its limit"); + } + try { + JsonNode root = JSON.readTree(strictUtf8(stored)); + requireFields(root); + if (!SCHEMA.equals(text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported canonical World hold-state schema"); + } + byte[] identityBytes = decodeBase64(root, "holdIdentityBytesBase64"); + byte[] lifecycleBytes = decodeBase64(root, "lifecycleEvidenceBytesBase64"); + if (identityBytes.length == 0 + || identityBytes.length > MAX_HOLD_IDENTITY_BYTES + || lifecycleBytes.length == 0 + || lifecycleBytes.length > MAX_LIFECYCLE_EVIDENCE_BYTES) { + throw new IllegalArgumentException( + "Canonical World hold-state component exceeds its limit"); + } + WorldCanonicalInitialAdmissionHold.HoldIdentity identity = + WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(identityBytes); + WorldCanonicalInstanceLifecycleEvidence lifecycle = + WorldCanonicalInstanceLifecycleEvidence.fromStored(lifecycleBytes); + WorldCanonicalInitialAdmissionHoldState state = + new WorldCanonicalInitialAdmissionHoldState( + identity, parseStatus(text(root, "holdStatus")), lifecycle); + if (!Arrays.equals(stored, state.canonicalBytes())) { + throw new IllegalArgumentException("Canonical World hold-state evidence is not canonical"); + } + return state; + } catch (tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Canonical World hold-state evidence is invalid", invalid); + } + } + + private static void requireTargetBinding( + WorldCanonicalInitialAdmissionHold.HoldIdentity identity, + WorldCanonicalInstanceLifecycleEvidence lifecycle) { + var hold = identity.request(); + var current = lifecycle.request(); + if (!hold.targetNamespace().equals(current.targetNamespace()) + || !hold.canonicalTenantId().equals(current.canonicalTenantId()) + || !hold.worldSlug().equals(current.worldSlug()) + || !hold.canonicalGameInstanceId().equals(current.canonicalGameInstanceId()) + || !hold.playableStateNamespaceId().equals(current.playableStateNamespaceId()) + || !hold.playableStateScope().equals(current.playableStateScope()) + || !hold.canonicalVersionId().equals(current.canonicalVersionId()) + || !current.publicProduction()) { + throw new IllegalArgumentException( + "Canonical World hold state differs from the complete lifecycle target scope"); + } + } + + private static HoldStatus parseStatus(String status) { + try { + return HoldStatus.valueOf(status); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Unsupported canonical World initial-admission hold status", invalid); + } + } + + private static byte[] decodeBase64(JsonNode object, String field) { + String encoded = text(object, field); + try { + byte[] decoded = Base64.getDecoder().decode(encoded); + if (!Base64.getEncoder().encodeToString(decoded).equals(encoded)) { + throw new IllegalArgumentException(field + " must use canonical base64"); + } + return decoded; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must use canonical base64", invalid); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException invalid) { + throw new IllegalArgumentException( + "Canonical World hold-state bytes are not strict UTF-8", invalid); + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException(field + " must be text"); + } + return value.textValue(); + } + + private static void requireFields(JsonNode object) { + if (object == null || !object.isObject()) { + throw new IllegalArgumentException("Canonical World hold-state evidence must be an object"); + } + Set actual = new java.util.HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(FIELDS)) { + throw new IllegalArgumentException( + "Canonical World hold-state evidence has missing or unsupported fields"); + } + } + + public enum HoldStatus { + PENDING, + RECONCILIATION_REQUIRED, + COMMITTED, + ABORTED + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminal.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminal.java new file mode 100644 index 0000000000..8bf6437567 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminal.java @@ -0,0 +1,515 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable integrity carrier for one durable World StartSession execution outcome. + * + *

This value binds the original post-authorization tuple to the exact World execution scope, + * independent source fences, retained preparation input, and one durable terminal outcome. It does + * not authenticate a producer, admit execution, or settle or release Account participation. + */ +public final class WorldStartSessionExecutionTerminal { + public static final String SCHEMA = "world-start-session-execution-terminal/v1"; + public static final int MAX_CANONICAL_BYTES = 24 * 1_024 * 1_024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final int MAX_TUPLE_BASE64_CHARS = + ((StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + 2) / 3) * 4; + private static final Set FIELDS = + Set.of( + "schema", + "originalPostAuthorizationTupleBase64", + "accountWorldParticipationId", + "accountWorldParticipationFence", + "gameSessionOwnerAttemptId", + "gameSessionOwnerFence", + "targetNamespace", + "canonicalTenantId", + "controlPlaneRequestId", + "canonicalGameInstanceId", + "preparationInputDigest", + "preparationInputJson", + "worldExecutionFence", + "outcome"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + + private final byte[] originalPostAuthorizationTuple; + private final String originalPostAuthorizationTupleBase64; + private final UUID accountWorldParticipationId; + private final long accountWorldParticipationFence; + private final UUID gameSessionOwnerAttemptId; + private final long gameSessionOwnerFence; + private final String targetNamespace; + private final UUID canonicalTenantId; + private final String controlPlaneRequestId; + private final UUID canonicalGameInstanceId; + private final String preparationInputDigest; + private final String preparationInputJson; + private final long worldExecutionFence; + private final Outcome outcome; + private final byte[] canonicalBytes; + private final String digest; + + public WorldStartSessionExecutionTerminal( + byte[] originalPostAuthorizationTuple, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + String targetNamespace, + UUID canonicalTenantId, + String controlPlaneRequestId, + UUID canonicalGameInstanceId, + String preparationInputDigest, + String preparationInputJson, + long worldExecutionFence, + Outcome outcome) { + this.preparationInputJson = requirePreparationInput(preparationInputJson); + jsonStringValueUtf8Length(this.preparationInputJson); + Objects.requireNonNull(originalPostAuthorizationTuple, "originalPostAuthorizationTuple"); + if (originalPostAuthorizationTuple.length == 0 + || originalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw invalid("Original post-authorization tuple exceeds its byte limit"); + } + this.originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + StartSessionPostAuthorizationExecutionTuple originalTuple = + StartSessionPostAuthorizationExecutionTuple.decode(this.originalPostAuthorizationTuple); + requireStartSessionGameSessionTarget(originalTuple); + + this.accountWorldParticipationId = + requireNonNil(accountWorldParticipationId, "accountWorldParticipationId"); + this.accountWorldParticipationFence = + requirePositive(accountWorldParticipationFence, "accountWorldParticipationFence"); + this.gameSessionOwnerAttemptId = + requireNonNil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + this.gameSessionOwnerFence = requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + this.worldExecutionFence = requirePositive(worldExecutionFence, "worldExecutionFence"); + + this.targetNamespace = requireNamespace(targetNamespace); + this.canonicalTenantId = requireNonNil(canonicalTenantId, "canonicalTenantId"); + this.controlPlaneRequestId = + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + this.canonicalGameInstanceId = + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + this.preparationInputDigest = requireDigest(preparationInputDigest); + this.outcome = Objects.requireNonNull(outcome, "outcome"); + this.originalPostAuthorizationTupleBase64 = + Base64.getEncoder().encodeToString(this.originalPostAuthorizationTuple); + + var original = originalTuple.preAuthorizationTuple(); + if (!this.targetNamespace.equals(original.action().scope().targetNamespace()) + || !this.canonicalTenantId.equals(original.action().scope().tenantId()) + || !this.controlPlaneRequestId.equals(originalTuple.controlPlaneRequestId())) { + throw invalid("World terminal scope differs from the original StartSession tuple"); + } + + requireCanonicalSize(); + byte[] preparationBytes = strictUtf8Bytes(this.preparationInputJson); + if (!sha256Prefixed(preparationBytes).equals(this.preparationInputDigest)) { + throw invalid("preparationInputDigest does not match the exact retained preparation input"); + } + this.canonicalBytes = encodeCanonicalBytes(); + this.digest = sha256Prefixed(this.canonicalBytes); + } + + /** Returns a defensive copy of the exact original post-authorization tuple bytes. */ + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + public String originalPostAuthorizationTupleBase64() { + return originalPostAuthorizationTupleBase64; + } + + public UUID accountWorldParticipationId() { + return accountWorldParticipationId; + } + + public long accountWorldParticipationFence() { + return accountWorldParticipationFence; + } + + public UUID gameSessionOwnerAttemptId() { + return gameSessionOwnerAttemptId; + } + + public long gameSessionOwnerFence() { + return gameSessionOwnerFence; + } + + public String targetNamespace() { + return targetNamespace; + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + public UUID canonicalGameInstanceId() { + return canonicalGameInstanceId; + } + + public String preparationInputDigest() { + return preparationInputDigest; + } + + /** Returns the original preparation-input string without parsing or reformatting it. */ + public String preparationInputJson() { + return preparationInputJson; + } + + public long worldExecutionFence() { + return worldExecutionFence; + } + + public Outcome outcome() { + return outcome; + } + + /** Returns a defensive copy of the closed RFC 8785 UTF-8 representation. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** SHA-256 digest of the complete canonical terminal, in the shared prefixed form. */ + public String digest() { + return digest; + } + + /** Strictly decodes one complete, closed, canonical World terminal value. */ + public static WorldStartSessionExecutionTerminal fromStored(byte[] stored) { + Objects.requireNonNull(stored, "stored"); + if (stored.length == 0 || stored.length > MAX_CANONICAL_BYTES) { + throw invalid("Canonical World StartSession terminal exceeds its byte limit"); + } + try { + String json = strictUtf8(stored); + byte[] canonicalInput = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!Arrays.equals(stored, canonicalInput)) { + throw invalid("Canonical World StartSession terminal is not RFC 8785 JSON"); + } + + JsonNode root = JSON.readTree(json); + requireExactFields(root); + if (!SCHEMA.equals(text(root, "schema"))) { + throw invalid("Unsupported World StartSession terminal schema"); + } + + WorldStartSessionExecutionTerminal terminal = + new WorldStartSessionExecutionTerminal( + decodeTuple(root), + canonicalUuid(root, "accountWorldParticipationId"), + positiveLong(root, "accountWorldParticipationFence"), + canonicalUuid(root, "gameSessionOwnerAttemptId"), + positiveLong(root, "gameSessionOwnerFence"), + text(root, "targetNamespace"), + canonicalUuid(root, "canonicalTenantId"), + text(root, "controlPlaneRequestId"), + canonicalUuid(root, "canonicalGameInstanceId"), + text(root, "preparationInputDigest"), + text(root, "preparationInputJson"), + positiveLong(root, "worldExecutionFence"), + parseOutcome(text(root, "outcome"))); + if (!Arrays.equals(stored, terminal.canonicalBytes)) { + throw invalid("Canonical World StartSession terminal has a noncanonical re-encoding"); + } + return terminal; + } catch (IllegalArgumentException invalid) { + throw invalid; + } catch (IOException | RuntimeException malformed) { + throw invalid("Canonical World StartSession terminal is invalid", malformed); + } + } + + private byte[] encodeCanonicalBytes() { + byte[] encoded = encodeCanonical(canonicalValue(preparationInputJson)); + if (encoded.length > MAX_CANONICAL_BYTES) { + throw invalid("Canonical World StartSession terminal exceeds its byte limit"); + } + return encoded; + } + + private void requireCanonicalSize() { + byte[] emptyStringPreimage = encodeCanonical(canonicalValue("")); + long expectedLength = + emptyStringPreimage.length + jsonStringValueUtf8Length(preparationInputJson); + if (expectedLength > MAX_CANONICAL_BYTES) { + throw invalid("Canonical World StartSession terminal exceeds its byte limit"); + } + } + + private Map canonicalValue(String exactPreparationInputJson) { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("originalPostAuthorizationTupleBase64", originalPostAuthorizationTupleBase64); + value.put("accountWorldParticipationId", accountWorldParticipationId.toString()); + value.put("accountWorldParticipationFence", Long.toString(accountWorldParticipationFence)); + value.put("gameSessionOwnerAttemptId", gameSessionOwnerAttemptId.toString()); + value.put("gameSessionOwnerFence", Long.toString(gameSessionOwnerFence)); + value.put("targetNamespace", targetNamespace); + value.put("canonicalTenantId", canonicalTenantId.toString()); + value.put("controlPlaneRequestId", controlPlaneRequestId); + value.put("canonicalGameInstanceId", canonicalGameInstanceId.toString()); + value.put("preparationInputDigest", preparationInputDigest); + value.put("preparationInputJson", exactPreparationInputJson); + value.put("worldExecutionFence", Long.toString(worldExecutionFence)); + value.put("outcome", outcome.name()); + return value; + } + + private static byte[] encodeCanonical(Map value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException("World StartSession terminal cannot be encoded", impossible); + } + } + + private static long jsonStringValueUtf8Length(String value) { + long length = 0L; + for (int index = 0; index < value.length(); index++) { + char current = value.charAt(index); + if (current == '\b' + || current == '\t' + || current == '\n' + || current == '\f' + || current == '\r' + || current == '"' + || current == '\\') { + length += 2L; + } else if (current <= 0x1f) { + length += 6L; + } else if (current <= 0x7f) { + length++; + } else if (current <= 0x7ff) { + length += 2L; + } else if (Character.isHighSurrogate(current)) { + if (index + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(index + 1))) { + throw invalid("preparationInputJson is not valid Unicode"); + } + length += 4L; + index++; + } else if (Character.isLowSurrogate(current)) { + throw invalid("preparationInputJson is not valid Unicode"); + } else { + length += 3L; + } + if (length > MAX_CANONICAL_BYTES) { + throw invalid("Canonical World StartSession terminal exceeds its byte limit"); + } + } + return length; + } + + private static byte[] strictUtf8Bytes(String value) { + jsonStringValueUtf8Length(value); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(java.nio.CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (java.nio.charset.CharacterCodingException malformed) { + throw invalid("preparationInputJson is not valid UTF-8", malformed); + } + } + + private static byte[] decodeTuple(JsonNode root) { + String encoded = text(root, "originalPostAuthorizationTupleBase64"); + if (encoded.isEmpty() || encoded.length() > MAX_TUPLE_BASE64_CHARS) { + throw invalid("Original post-authorization tuple exceeds its byte limit"); + } + try { + byte[] decoded = Base64.getDecoder().decode(encoded); + if (decoded.length == 0 + || decoded.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || !Base64.getEncoder().encodeToString(decoded).equals(encoded)) { + throw invalid("Original post-authorization tuple must use canonical base64"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw invalid("Original post-authorization tuple must use canonical base64", malformed); + } + } + + private static void requireStartSessionGameSessionTarget( + StartSessionPostAuthorizationExecutionTuple tuple) { + var original = tuple.preAuthorizationTuple(); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(original.actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals(original.targetOwner())) { + throw invalid("World terminal requires the original Game Session StartSession tuple"); + } + } + + private static String requireNamespace(String value) { + Objects.requireNonNull(value, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(value)) { + throw invalid("targetNamespace must be one canonical DNS label"); + } + return value; + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw invalid(field + " must not be nil"); + } + return value; + } + + private static long requirePositive(long value, String field) { + if (value <= 0L) { + throw invalid(field + " must be a positive signed 64-bit integer"); + } + return value; + } + + private static String requireDigest(String value) { + Objects.requireNonNull(value, "preparationInputDigest"); + if (!SHA256.matcher(value).matches()) { + throw invalid("preparationInputDigest must be sha256: followed by lowercase hexadecimal"); + } + return value; + } + + private static String requirePreparationInput(String value) { + Objects.requireNonNull(value, "preparationInputJson"); + if (value.isBlank()) { + throw invalid("preparationInputJson must retain a nonblank exact input"); + } + if (value.length() > MAX_CANONICAL_BYTES) { + throw invalid("preparationInputJson exceeds the terminal byte limit"); + } + return value; + } + + private static String strictUtf8(byte[] value) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } catch (java.nio.charset.CharacterCodingException malformed) { + throw invalid("Canonical World StartSession terminal is not strict UTF-8", malformed); + } + } + + private static void requireExactFields(JsonNode root) { + if (root == null || !root.isObject()) { + throw invalid("Canonical World StartSession terminal must be a JSON object"); + } + Set actual = new HashSet<>(); + root.propertyNames().forEach(actual::add); + if (!FIELDS.equals(actual)) { + throw invalid("Canonical World StartSession terminal has missing or unsupported fields"); + } + } + + private static String text(JsonNode root, String field) { + JsonNode value = root == null ? null : root.get(field); + if (value == null || !value.isTextual()) { + throw invalid(field + " must be a string"); + } + return value.textValue(); + } + + private static UUID canonicalUuid(JsonNode root, String field) { + String value = text(root, field); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(NIL_UUID)) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static long positiveLong(JsonNode root, String field) { + String value = text(root, field); + if (!CANONICAL_POSITIVE_DECIMAL.matcher(value).matches()) { + throw invalid(field + " must be a canonical positive ASCII decimal string"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException overflow) { + throw invalid(field + " exceeds the positive signed 64-bit range", overflow); + } + } + + private static Outcome parseOutcome(String value) { + try { + return Outcome.valueOf(value); + } catch (IllegalArgumentException unsupported) { + throw invalid( + "World StartSession terminal outcome must be COMMITTED or ABORTED", unsupported); + } + } + + private static String sha256Prefixed(byte[] bytes) { + return "sha256:" + sha256(bytes); + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } + + public enum Outcome { + COMMITTED, + ABORTED + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java new file mode 100644 index 0000000000..efcb1e2b67 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java @@ -0,0 +1,309 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import org.junit.jupiter.api.Test; + +class WorldCanonicalInitialAdmissionHoldStateTest { + private static final UUID REALM = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID HOLD_FENCE = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + + @Test + void completePendingActiveStateRoundTripsExactNestedOwnerBytes() throws Exception { + WorldCanonicalInstanceLifecycleEvidence lifecycle = lifecycle("ACTIVE", 3L); + Request request = holdRequest(lifecycle); + var identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + var state = + new WorldCanonicalInitialAdmissionHoldState( + identity, WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, lifecycle); + + byte[] encoded = state.canonicalBytes(); + var decoded = WorldCanonicalInitialAdmissionHoldState.fromStored(encoded); + + assertThat(decoded).isEqualTo(state); + assertThat(decoded.isPendingAtExpectedActiveEpoch()).isTrue(); + String encodedText = new String(encoded, StandardCharsets.UTF_8); + assertThat(encodedText) + .contains(java.util.Base64.getEncoder().encodeToString(identity.canonicalBytes())); + assertThat(encodedText) + .contains(java.util.Base64.getEncoder().encodeToString(lifecycle.canonicalBytes())); + } + + @Test + void nonterminalAndAdvancedLifecycleSamplesRemainHonestButDoNotQualify() throws Exception { + WorldCanonicalInstanceLifecycleEvidence active = lifecycle("ACTIVE", 3L); + Request request = holdRequest(active); + HoldIdentity identity = new HoldIdentity(request, HOLD_ID, HOLD_FENCE); + + for (var status : + List.of( + WorldCanonicalInitialAdmissionHoldState.HoldStatus.RECONCILIATION_REQUIRED, + WorldCanonicalInitialAdmissionHoldState.HoldStatus.COMMITTED, + WorldCanonicalInitialAdmissionHoldState.HoldStatus.ABORTED)) { + var state = new WorldCanonicalInitialAdmissionHoldState(identity, status, active); + assertThat(state.isPendingAtExpectedActiveEpoch()).isFalse(); + assertThat(WorldCanonicalInitialAdmissionHoldState.fromStored(state.canonicalBytes())) + .isEqualTo(state); + } + + var advanced = lifecycle("TERMINATING", 4L); + var observed = + new WorldCanonicalInitialAdmissionHoldState( + identity, WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, advanced); + assertThat(observed.lifecycleEvidence().lifecycleStatus()).isEqualTo("TERMINATING"); + assertThat(observed.lifecycleEvidence().lifecycleEpoch()).isEqualTo(4L); + assertThat(observed.isPendingAtExpectedActiveEpoch()).isFalse(); + assertThat(WorldCanonicalInitialAdmissionHoldState.fromStored(observed.canonicalBytes())) + .isEqualTo(observed); + } + + @Test + void rejectsChangedTargetScopeWithoutEquatingIndependentRequestIds() throws Exception { + WorldCanonicalInstanceLifecycleEvidence lifecycle = lifecycle("ACTIVE", 3L); + Request original = holdRequest(lifecycle); + Request mismatched = + new Request( + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + REALM, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + original.playableStateScope(), + original.canonicalGameInstanceId(), + original.canonicalVersionId(), + original.activeLifecycleEpoch(), + original.initialAdmissionRequestId(), + original.initialAdmissionRequestDigest(), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + + assertThatThrownBy( + () -> + new WorldCanonicalInitialAdmissionHoldState( + new HoldIdentity(mismatched, HOLD_ID, HOLD_FENCE), + WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, + lifecycle)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("target scope"); + + Request independentRequestId = + new Request( + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + original.realmId(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.canonicalGameInstanceId(), + original.canonicalVersionId(), + original.activeLifecycleEpoch(), + "a-distinct-initial-admission-request-id", + original.initialAdmissionRequestDigest(), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + assertThat( + new WorldCanonicalInitialAdmissionHoldState( + new HoldIdentity(independentRequestId, HOLD_ID, HOLD_FENCE), + WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, + lifecycle) + .lifecycleEvidence() + .request() + .controlPlaneRequestId()) + .isEqualTo(lifecycle.request().controlPlaneRequestId()); + assertThat(independentRequestId.initialAdmissionRequestId()) + .isNotEqualTo(lifecycle.request().controlPlaneRequestId()); + } + + @Test + void rejectsUnknownDuplicateNoncanonicalMalformedAndOversizedState() throws Exception { + var state = + new WorldCanonicalInitialAdmissionHoldState( + new HoldIdentity(holdRequest(lifecycle("ACTIVE", 3L)), HOLD_ID, HOLD_FENCE), + WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, + lifecycle("ACTIVE", 3L)); + String canonical = new String(state.canonicalBytes(), StandardCharsets.UTF_8); + + assertInvalid(canonical.replace("\"schema\":", "\"extra\":true,\"schema\":")); + String duplicateSchema = + "\"schema\":\"" + + WorldCanonicalInitialAdmissionHoldState.SCHEMA + + "\",\"schema\":\"" + + WorldCanonicalInitialAdmissionHoldState.SCHEMA + + "\""; + assertInvalid( + canonical.replace( + "\"schema\":\"" + WorldCanonicalInitialAdmissionHoldState.SCHEMA + "\"", + duplicateSchema)); + assertInvalid(canonical.replace("PENDING", "UNKNOWN")); + assertInvalid(canonical.replace(",\"holdStatus\":\"PENDING\"", "")); + assertInvalid( + canonical.replace( + java.util.Base64.getEncoder().encodeToString(state.holdIdentity().canonicalBytes()), + "!")); + assertInvalid(canonical + " "); + assertThatThrownBy( + () -> + WorldCanonicalInitialAdmissionHoldState.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strict UTF-8"); + assertThatThrownBy( + () -> + WorldCanonicalInitialAdmissionHoldState.fromStored( + new byte[WorldCanonicalInitialAdmissionHoldState.MAX_CANONICAL_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("limit"); + } + + private static void assertInvalid(String value) { + assertThatThrownBy( + () -> + WorldCanonicalInitialAdmissionHoldState.fromStored( + value.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Request holdRequest(WorldCanonicalInstanceLifecycleEvidence lifecycle) { + var request = lifecycle.request(); + return new Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + REALM, + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + 3L, + "initial-admission-independent-from-preparation-request", + "a".repeat(64), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + } + + private static WorldCanonicalInstanceLifecycleEvidence lifecycle(String status, long epoch) + throws Exception { + WorldPublishedStartLocationEvidence selector = + WorldPublishedStartLocationGrpcCodecTest.evidence(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.request().targetNamespace(), + "world-lifecycle-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "canonical-instance-launch-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); + var request = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + request, + binding, + selectorReceipt.startLocation(), + 1042L, + status, + epoch, + 0L, + uuid("33333333-3333-4333-8333-333333333333"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "e".repeat(64), + Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.java new file mode 100644 index 0000000000..cbca5ca010 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.java @@ -0,0 +1,667 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal.Outcome; +import org.junit.jupiter.api.Test; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +class WorldStartSessionExecutionTerminalTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final UUID PARTICIPATION_ID = + UUID.fromString("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_ATTEMPT_ID = + UUID.fromString("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final String REQUEST_ID = "start-world-terminal-vector"; + private static final String NAMESPACE = "world-runtime"; + private static final String PREPARATION_INPUT = + "{ \"selected\" : \"immutable source\", \"revision\": 3 }\n"; + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private static final String EXPECTED_PREPARATION_INPUT_DIGEST = + "sha256:0b98b4ce717296fdaaeece6709c7c7d7b1b4c149ed1dc5b0c1afc43c91fe2bb1"; + private static final String EXPECTED_ORIGINAL_TUPLE_BASE64 = + String.join( + "", + "eyJhY3Rpb25GYW1pbHkiOiJTdGFydFNlc3Npb24iLCJhY3Rpb25GYW1pbHlSZXF1ZXN0SWRlbnRpdHkiOnsicmVxdWVzdElkIjoi", + "c3RhcnQtd29ybGQtdGVybWluYWwtdmVjdG9yIiwicmVxdWVzdElkZW50aXR5S2luZCI6ImNvbnRyb2xQbGFuZVJlcXVlc3RJZCJ9", + "LCJhY3Rpb25GYW1pbHlTY2hlbWFJZCI6ImZpcmVtdWQuZ2FtZS1zZXNzaW9uLnN0YXJ0LXNlc3Npb24iLCJhY3Rpb25GYW1pbHlT", + "Y2hlbWFWZXJzaW9uIjoiMSIsImFjdG9yIjp7ImFjY291bnRJZCI6ImE0ZjVmNGViLTgyNDMtNGQ0Mi05MDNhLTMzNDk1NDU2YTYy", + "MiIsImtpbmQiOiJIVU1BTiJ9LCJhdWRpdFJlYXNvbiI6ImNhbm9uaWNhbCBTdGFydFNlc3Npb24gb3duZXIgYXR0ZW1wdCIsImF1", + "dGhlbnRpY2F0ZWRXb3JrbG9hZElkZW50aXR5Ijp7ImlkZW50aXR5S2luZCI6Ik1VVFVBTF9UTFNfU1BJRkZFIiwidXJpIjoic3Bp", + "ZmZlOi8vZmlyZW11ZC9ucy93b3JsZC1ydW50aW1lL3NhL2xvZ2dpbmctYWRtaW4tc2VydmljZSJ9LCJhdXRob3JpdHlFdmlkZW5j", + "ZUJ1bmRsZSI6eyJhY2NvdW50UHJvamVjdGlvbkV2aWRlbmNlIjp7ImV2YWx1YXRlZEF0IjoiMjAyNi0xMC0wOVQwMDowMDowMFoi", + "LCJleHBpcmVzQXQiOiIyMDI2LTEwLTA5VDAwOjA1OjAwWiIsInByb2plY3Rpb25TdGF0dXMiOiJDVVJSRU5UIiwic291cmNlRXZp", + "ZGVuY2VJZCI6InNoYTI1NjphYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh", + "YWFhYWFhIiwic291cmNlRXZpZGVuY2VWZXJzaW9uIjoiMTciLCJzb3VyY2VUeXBlIjoiQUNDT1VOVCJ9LCJhdXRob3JpdHlTY29w", + "ZSI6eyJhY3Rpb25GYW1pbHkiOiJTdGFydFNlc3Npb24iLCJhcHBsaWNhYmxlQWNjb3VudElkIjoiYTRmNWY0ZWItODI0My00ZDQy", + "LTkwM2EtMzM0OTU0NTZhNjIyIiwiYXBwbGljYWJsZVRlbmFudElkIjoiOWY4ZjA2YjQtMzZlNS00ZDExLTljMmEtNWFkZmQ3ZjQx", + "NTMxIiwic2NvcGUiOnsidGFyZ2V0TmFtZXNwYWNlIjoid29ybGQtcnVudGltZSIsInRlbmFudElkIjoiOWY4ZjA2YjQtMzZlNS00", + "ZDExLTljMmEtNWFkZmQ3ZjQxNTMxIn19LCJhdXRob3JpdHlUdXBsZSI6eyJhY2NvdW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6Miwi", + "aXNzdWVyQXV0aEdlbmVyYXRpb24iOjEsIm1lbWJlcnNoaXBBdXRob3JpdHlHZW5lcmF0aW9uIjp7IjlmOGYwNmI0LTM2ZTUtNGQx", + "MS05YzJhLTVhZGZkN2Y0MTUzMSI6NH0sInByaXZhdGVSZWFsbUdyYW50VmVyc2lvbnMiOltdLCJ0ZW5hbnRBdXRob3JpdHlHZW5l", + "cmF0aW9uIjp7IjlmOGYwNmI0LTM2ZTUtNGQxMS05YzJhLTVhZGZkN2Y0MTUzMSI6M319LCJidW5kbGVWZXJzaW9uIjoiYXV0aG9y", + "aXR5RXZpZGVuY2VCdW5kbGUvdjEiLCJpc3N1YW5jZUV2aWRlbmNlIjp7ImFjY291bnRHZW5lcmF0aW9uIjoiMiIsImFjdG9yQWNj", + "b3VudElkIjoiYTRmNWY0ZWItODI0My00ZDQyLTkwM2EtMzM0OTU0NTZhNjIyIiwiY29udHJvbFVpVG9rZW5KdGkiOiJhNjgxYmJh", + "Ny1jMjE1LTRjZjEtYTM1Yi0xNDM0ODkxMmNiZGMiLCJldmlkZW5jZVR5cGUiOiJIdW1hbkF1dGhvcml0eUV2aWRlbmNlL3YxIiwi", + "cm9sZSI6InRlbmFudEFkbWluIiwidGVuYW50R2VuZXJhdGlvbiI6IjMifSwiaXNzdWFuY2VGZW5jZSI6IjIzIiwiaXNzdWFuY2VL", + "aW5kIjoiaHVtYW5fb3BlcmF0b3IiLCJpc3N1YW5jZU9wZXJhdGlvbklkZW50aXR5Ijp7ImFjdGlvbkZhbWlseVJlcXVlc3RJZGVu", + "dGl0eSI6eyJyZXF1ZXN0SWQiOiJzdGFydC13b3JsZC10ZXJtaW5hbC12ZWN0b3IiLCJyZXF1ZXN0SWRlbnRpdHlLaW5kIjoiY29u", + "dHJvbFBsYW5lUmVxdWVzdElkIn0sImNvbnRyb2xQbGFuZVJlcXVlc3RJZCI6InN0YXJ0LXdvcmxkLXRlcm1pbmFsLXZlY3RvciIs", + "Imlzc3VhbmNlT3BlcmF0aW9uSWQiOiJmNWQwNDRiZC03ZTVmLTRlMmQtOTg1OS05MDI1Y2JkY2M2MGYiLCJtdXRhdGlvbkRpZ2Vz", + "dCI6ImQyMGY5MDVkYjdiNmUzOTVjODAwOGY2ZjZlNDk4NjY0MWM1NTk1ZTEzNWRjZDkwN2E0YzQ2NGZmNjQyMDEwZTAifSwibWVt", + "YmVyc2hpcFZlcnNpb24iOnsiOWY4ZjA2YjQtMzZlNS00ZDExLTljMmEtNWFkZmQ3ZjQxNTMxIjo1fX0sImF1dGhvcml0eUV2aWRl", + "bmNlQnVuZGxlUmVmZXJlbmNlIjp7ImJ1bmRsZVZlcnNpb24iOiJhdXRob3JpdHlFdmlkZW5jZUJ1bmRsZS92MSIsImxpbmVhcml6", + "YXRpb24iOiIxODQ0Njc0NDA3MzcwOTU1MTYxNSIsInNvdXJjZUZlbmNlIjoiMjMiLCJzb3VyY2VWZXJzaW9uIjoiMTcifSwiYXV0", + "aG9yaXR5VHVwbGUiOnsiYWNjb3VudEF1dGhvcml0eUdlbmVyYXRpb24iOjIsImlzc3VlckF1dGhHZW5lcmF0aW9uIjoxLCJtZW1i", + "ZXJzaGlwQXV0aG9yaXR5R2VuZXJhdGlvbiI6eyI5ZjhmMDZiNC0zNmU1LTRkMTEtOWMyYS01YWRmZDdmNDE1MzEiOjR9LCJwcml2", + "YXRlUmVhbG1HcmFudFZlcnNpb25zIjpbXSwidGVuYW50QXV0aG9yaXR5R2VuZXJhdGlvbiI6eyI5ZjhmMDZiNC0zNmU1LTRkMTEt", + "OWMyYS01YWRmZDdmNDE1MzEiOjN9fSwiYXV0aG9yaXphdGlvblJlZmVyZW5jZUZpbmdlcnByaW50IjoiYXJmcC92MS90ZXN0LWtl", + "eS9iYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiIiwiYXV0b21h", + "dGlvblBvbGljeSI6eyJwcmVzZW5jZSI6IkFCU0VOVCJ9LCJjb250cm9sUGxhbmVSZXF1ZXN0SWQiOiJzdGFydC13b3JsZC10ZXJt", + "aW5hbC12ZWN0b3IiLCJleHBlY3RlZFZlcnNpb24iOnsicHJlc2VuY2UiOiJBQlNFTlQifSwiaXNzdWFuY2VGZW5jZSI6IjIzIiwi", + "aXNzdWFuY2VLaW5kIjoiaHVtYW5fb3BlcmF0b3IiLCJtZW1iZXJzaGlwVmVyc2lvbiI6eyI5ZjhmMDZiNC0zNmU1LTRkMTEtOWMy", + "YS01YWRmZDdmNDE1MzEiOjV9LCJtdXRhdGlvbiI6eyJjbGllbnRJcCI6eyJwcmVzZW5jZSI6IkFCU0VOVCJ9fSwibXV0YXRpb25E", + "aWdlc3QiOiJkMjBmOTA1ZGI3YjZlMzk1YzgwMDhmNmY2ZTQ5ODY2NDFjNTU5NWUxMzVkY2Q5MDdhNGM0NjRmZjY0MjAxMGUwIiwi", + "cHJlQXV0aG9yaXphdGlvblJlc2VydmF0aW9uVHVwbGUiOnsiYWN0aW9uRmFtaWx5IjoiU3RhcnRTZXNzaW9uIiwiYWN0aW9uRmFt", + "aWx5UmVxdWVzdElkZW50aXR5Ijp7InJlcXVlc3RJZCI6InN0YXJ0LXdvcmxkLXRlcm1pbmFsLXZlY3RvciIsInJlcXVlc3RJZGVu", + "dGl0eUtpbmQiOiJjb250cm9sUGxhbmVSZXF1ZXN0SWQifSwiYWN0aW9uRmFtaWx5U2NoZW1hSWQiOiJmaXJlbXVkLmdhbWUtc2Vz", + "c2lvbi5zdGFydC1zZXNzaW9uIiwiYWN0aW9uRmFtaWx5U2NoZW1hVmVyc2lvbiI6IjEiLCJhY3RvciI6eyJhY2NvdW50SWQiOiJh", + "NGY1ZjRlYi04MjQzLTRkNDItOTAzYS0zMzQ5NTQ1NmE2MjIiLCJraW5kIjoiSFVNQU4ifSwiYXVkaXRSZWFzb24iOiJjYW5vbmlj", + "YWwgU3RhcnRTZXNzaW9uIG93bmVyIGF0dGVtcHQiLCJhdXRvbWF0aW9uUG9saWN5Ijp7InByZXNlbmNlIjoiQUJTRU5UIn0sImV4", + "cGVjdGVkVmVyc2lvbiI6eyJwcmVzZW5jZSI6IkFCU0VOVCJ9LCJtdXRhdGlvbiI6eyJjbGllbnRJcCI6eyJwcmVzZW5jZSI6IkFC", + "U0VOVCJ9fSwic2NvcGUiOnsidGFyZ2V0TmFtZXNwYWNlIjoid29ybGQtcnVudGltZSIsInRlbmFudElkIjoiOWY4ZjA2YjQtMzZl", + "NS00ZDExLTljMmEtNWFkZmQ3ZjQxNTMxIn0sInRhcmdldCI6eyJnYW1lVGVtcGxhdGVJZCI6IjkxIiwib3duZXJBY2NvdW50SWQi", + "OiIzNmFhOWNlNS0wZWJjLTRjMTQtOWY2Yi1kMTYwZWRjNjA1OWEifSwidGFyZ2V0T3duZXIiOnsib3duZXJTZXJ2aWNlIjoiZ2Ft", + "ZS1zZXNzaW9uLXNlcnZpY2UifSwidHVwbGVTY2hlbWFJZCI6InByZUF1dGhvcml6YXRpb25SZXNlcnZhdGlvblR1cGxlIiwidHVw", + "bGVTY2hlbWFWZXJzaW9uIjoiMSJ9LCJyZXNlcnZhdGlvbkNsYWltRmVuY2UiOjE5LCJyZXNlcnZhdGlvbk93bmVySWQiOiI3YzAw", + "NWI2NS1mY2IxLTRhYzktYTcxNC1mM2QwZjQ0OWVkY2YiLCJzY29wZSI6eyJ0YXJnZXROYW1lc3BhY2UiOiJ3b3JsZC1ydW50aW1l", + "IiwidGVuYW50SWQiOiI5ZjhmMDZiNC0zNmU1LTRkMTEtOWMyYS01YWRmZDdmNDE1MzEifSwidGFyZ2V0Ijp7ImdhbWVUZW1wbGF0", + "ZUlkIjoiOTEiLCJvd25lckFjY291bnRJZCI6IjM2YWE5Y2U1LTBlYmMtNGMxNC05ZjZiLWQxNjBlZGM2MDU5YSJ9LCJ0YXJnZXRP", + "d25lciI6eyJvd25lclNlcnZpY2UiOiJnYW1lLXNlc3Npb24tc2VydmljZSJ9LCJ0dXBsZVNjaGVtYUlkIjoicG9zdEF1dGhvcml6", + "YXRpb25FeGVjdXRpb25UdXBsZSIsInR1cGxlU2NoZW1hVmVyc2lvbiI6IjEifQ=="); + private static final String EXPECTED_DIGEST = + "sha256:a3304a2e145bd7eec557cd87d233e9dd399d5c3a5c658438f2039eb7e0898eb1"; + private static final String EXPECTED_CANONICAL_PREIMAGE = + "{\"accountWorldParticipationFence\":\"31\"," + + "\"accountWorldParticipationId\":\"a8c1e8c8-f237-41b7-918d-ec2281bcac10\"," + + "\"canonicalGameInstanceId\":\"c0e30aea-1549-43d9-93af-0e44a3deae32\"," + + "\"canonicalTenantId\":\"9f8f06b4-36e5-4d11-9c2a-5adfd7f41531\"," + + "\"controlPlaneRequestId\":\"start-world-terminal-vector\"," + + "\"gameSessionOwnerAttemptId\":\"b9d2f9d9-0438-42c8-829e-fd3392cd9d21\"," + + "\"gameSessionOwnerFence\":\"37\"," + + "\"originalPostAuthorizationTupleBase64\":\"" + + EXPECTED_ORIGINAL_TUPLE_BASE64 + + "\",\"outcome\":\"COMMITTED\"," + + "\"preparationInputDigest\":\"" + + EXPECTED_PREPARATION_INPUT_DIGEST + + "\",\"preparationInputJson\":\"{ \\\"selected\\\" : \\\"immutable source\\\", \\\"revision\\\": 3 }\\n\"," + + "\"schema\":\"world-start-session-execution-terminal/v1\"," + + "\"targetNamespace\":\"world-runtime\",\"worldExecutionFence\":\"41\"}"; + + @Test + void committedTerminalMatchesFrozenCanonicalVectorAndPreservesExactTupleAndInput() + throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + byte[] originalTupleBytes = tuple.canonicalBytes(); + WorldStartSessionExecutionTerminal terminal = terminal(tuple, Outcome.COMMITTED); + + assertThat(new String(terminal.canonicalBytes(), StandardCharsets.UTF_8)) + .isEqualTo(EXPECTED_CANONICAL_PREIMAGE); + assertThat(terminal.digest()).isEqualTo(EXPECTED_DIGEST); + assertThat(terminal.originalPostAuthorizationTupleBase64()) + .isEqualTo(EXPECTED_ORIGINAL_TUPLE_BASE64); + assertThat(terminal.originalPostAuthorizationTuple()).containsExactly(originalTupleBytes); + assertThat(terminal.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + + WorldStartSessionExecutionTerminal decoded = + WorldStartSessionExecutionTerminal.fromStored(terminal.canonicalBytes()); + assertThat(decoded.canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(decoded.digest()).isEqualTo(terminal.digest()); + assertThat(decoded.originalPostAuthorizationTuple()).containsExactly(originalTupleBytes); + assertThat(decoded.originalPostAuthorizationTupleBase64()) + .isEqualTo(Base64.getEncoder().encodeToString(originalTupleBytes)); + assertThat(decoded.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + assertThat(decoded.accountWorldParticipationFence()).isEqualTo(31L); + assertThat(decoded.gameSessionOwnerFence()).isEqualTo(37L); + assertThat(decoded.worldExecutionFence()).isEqualTo(41L); + } + + @Test + void abortedAndCommittedOutcomesAreStableExactReadbacksWithoutObservationFields() + throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + WorldStartSessionExecutionTerminal committed = terminal(tuple, Outcome.COMMITTED); + WorldStartSessionExecutionTerminal aborted = terminal(tuple, Outcome.ABORTED); + + assertThat(committed.canonicalBytes()).isNotEqualTo(aborted.canonicalBytes()); + assertThat(committed.digest()).isNotEqualTo(aborted.digest()); + for (WorldStartSessionExecutionTerminal expected : List.of(committed, aborted)) { + byte[] firstRead = expected.canonicalBytes(); + WorldStartSessionExecutionTerminal firstDecoded = + WorldStartSessionExecutionTerminal.fromStored(firstRead); + WorldStartSessionExecutionTerminal secondDecoded = + WorldStartSessionExecutionTerminal.fromStored(firstDecoded.canonicalBytes()); + assertThat(secondDecoded.canonicalBytes()).containsExactly(firstRead); + assertThat(secondDecoded.digest()).isEqualTo(expected.digest()); + } + + assertInvalid( + withField(committed.canonicalBytes(), "currentReadCorrelationId", "later-read-id")); + assertInvalid( + withField(committed.canonicalBytes(), "authorizationExpiry", "2099-01-01T00:00:00Z")); + assertInvalid(withField(committed.canonicalBytes(), "outcome", "PENDING")); + assertInvalid(withField(committed.canonicalBytes(), "outcome", "TIMEOUT")); + } + + @Test + void retainsEveryBindingAndFenceAndRejectsScopeSubstitution() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + WorldStartSessionExecutionTerminal baseline = terminal(tuple, Outcome.COMMITTED); + byte[] original = baseline.canonicalBytes(); + + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + uuid("d1e40bfb-265a-44ea-84b0-1f55b4efbf43"), + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED), + original); + assertChanged(terminal(originalTuple(92L), Outcome.COMMITTED), original); + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 43L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED), + original); + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + uuid("e2f51c0c-376b-45fb-95b1-2066c5f0c054"), + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED), + original); + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 47L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED), + original); + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + uuid("f3042d1d-487c-46ac-a6c2-3177d6f1d165"), + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED), + original); + assertChanged( + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 43L, + Outcome.COMMITTED), + original); + + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + "another-runtime", + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("scope"); + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + uuid("d4053e2e-598d-47bd-b7d3-4288e702e276"), + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("scope"); + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + "substituted-request-id", + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("scope"); + + WorldStartSessionExecutionTerminal equalFenceValues = + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 31L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 31L, + Outcome.COMMITTED); + WorldStartSessionExecutionTerminal equalFenceReadback = + WorldStartSessionExecutionTerminal.fromStored(equalFenceValues.canonicalBytes()); + assertThat(equalFenceReadback.accountWorldParticipationFence()).isEqualTo(31L); + assertThat(equalFenceReadback.gameSessionOwnerFence()).isEqualTo(31L); + assertThat(equalFenceReadback.worldExecutionFence()).isEqualTo(31L); + assertThat(new String(equalFenceReadback.canonicalBytes(), StandardCharsets.UTF_8)) + .contains( + "\"accountWorldParticipationFence\":\"31\"", + "\"gameSessionOwnerFence\":\"31\"", + "\"worldExecutionFence\":\"31\""); + } + + @Test + void rejectsMalformedDuplicateUnknownTrailingAndNoncanonicalStoredValues() throws Exception { + WorldStartSessionExecutionTerminal terminal = terminal(originalTuple(), Outcome.COMMITTED); + String canonical = new String(terminal.canonicalBytes(), StandardCharsets.UTF_8); + + assertInvalid(canonical + " "); + assertInvalid(canonical + "{}"); + assertInvalid(canonical.replace("\"schema\":", "\"extra\":true,\"schema\":")); + assertInvalid( + canonical.replace( + "\"schema\":\"" + WorldStartSessionExecutionTerminal.SCHEMA + "\"", + "\"schema\":\"" + + WorldStartSessionExecutionTerminal.SCHEMA + + "\",\"schema\":\"" + + WorldStartSessionExecutionTerminal.SCHEMA + + "\"")); + assertInvalid( + canonical.replace( + "\"schema\":\"world-start-session-execution-terminal/v1\"", "\"schema\":\"v2\"")); + assertInvalid( + new StringBuilder(canonical).insert(canonical.indexOf("\"schema\""), " ").toString()); + assertThatThrownBy( + () -> WorldStartSessionExecutionTerminal.fromStored(new byte[] {(byte) 0xc3, 0x28})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("strict UTF-8"); + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminal.fromStored( + new byte[WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("byte limit"); + + byte[] tupleReencodedWithoutPadding = + withField( + terminal.canonicalBytes(), + "originalPostAuthorizationTupleBase64", + terminal.originalPostAuthorizationTupleBase64().replaceAll("=+$", "")); + if (!terminal.originalPostAuthorizationTupleBase64().endsWith("=")) { + String padded = terminal.originalPostAuthorizationTupleBase64() + "="; + tupleReencodedWithoutPadding = + withField(terminal.canonicalBytes(), "originalPostAuthorizationTupleBase64", padded); + } + assertInvalid(tupleReencodedWithoutPadding); + } + + @Test + void requiresCanonicalPositiveBigintStringsNonNilUuidsAndExactInputDigest() throws Exception { + WorldStartSessionExecutionTerminal terminal = terminal(originalTuple(), Outcome.COMMITTED); + for (String field : + List.of("accountWorldParticipationFence", "gameSessionOwnerFence", "worldExecutionFence")) { + for (String invalidCounter : List.of("0", "01", "-1", "9223372036854775808", "٣")) { + assertInvalid(withField(terminal.canonicalBytes(), field, invalidCounter)); + } + } + assertInvalid(withField(terminal.canonicalBytes(), "worldExecutionFence", 41)); + assertInvalid( + withField( + terminal.canonicalBytes(), + "accountWorldParticipationId", + "00000000-0000-0000-0000-000000000000")); + + assertThat( + new WorldStartSessionExecutionTerminal( + originalTuple().canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + Long.MAX_VALUE, + Outcome.ABORTED) + .worldExecutionFence()) + .isEqualTo(Long.MAX_VALUE); + + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminal( + originalTuple().canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest("changed input"), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("preparationInputDigest"); + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminal( + originalTuple().canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + "{ \"selected\" : \"different exact bytes\" }", + 41L, + Outcome.COMMITTED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("preparationInputDigest"); + } + + @Test + void defensivelyCopiesTupleAndCanonicalBytesAndKeepsPreparationStringUnchanged() { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + byte[] suppliedTuple = tuple.canonicalBytes(); + WorldStartSessionExecutionTerminal terminal = terminal(tuple, Outcome.COMMITTED); + byte[] stored = terminal.canonicalBytes(); + byte[] exposedTuple = terminal.originalPostAuthorizationTuple(); + suppliedTuple[0] = (byte) '!'; + stored[0] = (byte) '!'; + exposedTuple[0] = (byte) '!'; + + assertThat(terminal.canonicalBytes()[0]).isNotEqualTo((byte) '!'); + assertThat(terminal.originalPostAuthorizationTuple()[0]).isNotEqualTo((byte) '!'); + assertThat(terminal.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + } + + private static WorldStartSessionExecutionTerminal terminal( + StartSessionPostAuthorizationExecutionTuple tuple, Outcome outcome) { + return new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + outcome); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + return originalTuple(91L); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(long gameTemplateId) { + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + REQUEST_ID, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(gameTemplateId, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, WORKLOAD, FINGERPRINT, RESERVATION_OWNER, 19L, bundle(preTuple), reference()); + } + + private static byte[] bundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = TENANT.toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map identity = + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static StartSessionAuthorityEvidenceBundle.BundleReference reference() { + return new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + } + + private static byte[] withField(byte[] source, String field, Object replacement) + throws IOException { + Map value = + JSON.readValue(source, new TypeReference>() {}); + value.put(field, replacement); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static void assertInvalid(String value) { + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminal.fromStored( + value.getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertInvalid(byte[] value) { + assertThatThrownBy(() -> WorldStartSessionExecutionTerminal.fromStored(value)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertChanged( + WorldStartSessionExecutionTerminal changed, byte[] baselineCanonical) { + assertThat(changed.canonicalBytes()).isNotEqualTo(baselineCanonical); + assertThat(changed.digest()).isNotEqualTo("sha256:" + digestBytes(baselineCanonical)); + assertThat( + WorldStartSessionExecutionTerminal.fromStored(changed.canonicalBytes()) + .canonicalBytes()) + .containsExactly(changed.canonicalBytes()); + } + + private static String digest(String value) { + return "sha256:" + digestBytes(value.getBytes(StandardCharsets.UTF_8)); + } + + private static String digestBytes(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcService.java index 3fa0ad6b6c..932633a798 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcService.java @@ -12,11 +12,14 @@ import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldRequest; import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldResponse; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityRequest; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldStateRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldStateResponse; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldServiceGrpc; import org.jooq.exception.DataAccessException; import org.springframework.beans.factory.annotation.Value; @@ -216,6 +219,108 @@ public void readCanonicalInitialAdmissionHoldIdentity( responseObserver.onCompleted(); } + @Override + public void readCanonicalInitialAdmissionHoldState( + ReadCanonicalInitialAdmissionHoldStateRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedGameSessionPeer(responseObserver)) return; + if (!requireIndependentOwnerOperation(responseObserver)) return; + + ParsedStateRead parsed; + try { + parsed = parseStateReadRequest(request); + } catch (IllegalArgumentException invalid) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A canonical read UUID, complete hold identity, and lifecycle request are required"); + return; + } + if (!trustedNamespace.equals(parsed.holdIdentity().request().targetNamespace()) + || !trustedNamespace.equals(parsed.lifecycleRequest().targetNamespace())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Canonical World hold and lifecycle namespaces must match the authenticated peer"); + return; + } + if (!sameStateTarget(parsed.holdIdentity().request(), parsed.lifecycleRequest())) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World lifecycle evidence does not match the complete hold target"); + return; + } + + Optional maybeState; + try { + maybeState = repository.readState(parsed.holdIdentity(), parsed.lifecycleRequest()); + } catch (WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException conflict) { + fail( + responseObserver, + Status.ALREADY_EXISTS, + "Canonical World initial-admission hold state conflicts with owner state"); + return; + } catch ( + WorldCanonicalInitialAdmissionHoldRepository.InvalidHoldIdentityException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World initial-admission hold state is incomplete or inconsistent"); + return; + } catch (TransientDataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "Canonical World initial-admission hold state storage is temporarily unavailable"); + return; + } catch (DataAccessException storageFailure) { + fail( + responseObserver, + Status.INTERNAL, + "Canonical World initial-admission hold state storage failed"); + return; + } catch (RuntimeException failure) { + fail( + responseObserver, + Status.INTERNAL, + "Canonical World initial-admission hold state read failed"); + return; + } + if (maybeState == null) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World hold owner returned no state lookup result"); + return; + } + if (maybeState.isEmpty()) { + fail( + responseObserver, + Status.NOT_FOUND, + "No exact canonical World initial-admission hold state was found"); + return; + } + + byte[] stateBytes; + try { + stateBytes = requireExactState(parsed, maybeState.orElseThrow()); + } catch (RuntimeException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Canonical World hold owner returned substituted or incomplete state evidence"); + return; + } + + responseObserver.onNext( + ReadCanonicalInitialAdmissionHoldStateResponse.newBuilder() + .setReadRequestId(parsed.readRequestId()) + .setHoldStateBytes(ByteString.copyFrom(stateBytes)) + .build()); + responseObserver.onCompleted(); + } + private static ParsedAcquire parseAcquireRequest( AcquireCanonicalInitialAdmissionHoldRequest request) { if (request == null || !request.getUnknownFields().asMap().isEmpty()) { @@ -235,7 +340,31 @@ private static ParsedRead parseReadRequest( if (request == null || !request.getUnknownFields().asMap().isEmpty()) { throw new IllegalArgumentException("Closed canonical read request is required"); } - String readId = request.getReadRequestId(); + String readId = canonicalReadId(request.getReadRequestId()); + Request holdRequest = + WorldCanonicalInitialAdmissionHold.Request.fromStored( + request.getCanonicalHoldRequestBytes().toByteArray()); + return new ParsedRead(readId, holdRequest); + } + + private static ParsedStateRead parseStateReadRequest( + ReadCanonicalInitialAdmissionHoldStateRequest request) { + if (request == null || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed canonical hold-state read request is required"); + } + String readId = canonicalReadId(request.getReadRequestId()); + HoldIdentity identity = HoldIdentity.fromStored(request.getHoldIdentityBytes().toByteArray()); + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest = + WorldCanonicalInstanceLifecycleEvidence.Request.fromStored( + request.getCanonicalLifecycleReadRequestBytes().toByteArray()); + if (!readId.equals(lifecycleRequest.readRequestId().toString())) { + throw new IllegalArgumentException( + "Lifecycle read request correlation differs from the hold-state read UUID"); + } + return new ParsedStateRead(readId, identity, lifecycleRequest); + } + + private static String canonicalReadId(String readId) { UUID parsedReadId; try { parsedReadId = UUID.fromString(readId); @@ -245,10 +374,7 @@ private static ParsedRead parseReadRequest( if (new UUID(0L, 0L).equals(parsedReadId) || !parsedReadId.toString().equals(readId)) { throw new IllegalArgumentException("Read request ID must be a canonical non-nil UUID"); } - Request holdRequest = - WorldCanonicalInitialAdmissionHold.Request.fromStored( - request.getCanonicalHoldRequestBytes().toByteArray()); - return new ParsedRead(readId, holdRequest); + return readId; } private static boolean sameTarget( @@ -264,6 +390,12 @@ private static boolean sameTarget( && lifecycleRequest.publicProduction(); } + private static boolean sameStateTarget( + Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + return holdRequest.targetNamespace().equals(lifecycleRequest.targetNamespace()) + && sameTarget(holdRequest, lifecycleRequest); + } + private static byte[] requireExactIdentity(Request expected, HoldIdentity actual) { if (actual == null || actual.request() == null @@ -284,6 +416,25 @@ private static byte[] requireExactIdentity(Request expected, HoldIdentity actual return bytes; } + private static byte[] requireExactState( + ParsedStateRead expected, WorldCanonicalInitialAdmissionHoldState actual) { + if (actual == null + || actual.holdIdentity() == null + || !Arrays.equals( + expected.holdIdentity().canonicalBytes(), actual.holdIdentity().canonicalBytes()) + || actual.lifecycleEvidence() == null + || !expected.lifecycleRequest().equals(actual.lifecycleEvidence().request()) + || actual.holdStatus() == null) { + throw new IllegalStateException("Canonical World hold state differs from the exact request"); + } + byte[] bytes = actual.canonicalBytes(); + if (bytes.length == 0 + || bytes.length > WorldCanonicalInitialAdmissionHoldState.MAX_CANONICAL_BYTES) { + throw new IllegalStateException("Canonical World hold state response exceeds its limit"); + } + return bytes; + } + private boolean requireAuthenticatedGameSessionPeer(StreamObserver responseObserver) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer != null @@ -319,4 +470,9 @@ private record ParsedAcquire( Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) {} private record ParsedRead(String readRequestId, Request holdRequest) {} + + private record ParsedStateRead( + String readRequestId, + HoldIdentity holdIdentity, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) {} } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java index c9e49ec29e..0dc777282a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import org.jooq.DSLContext; import org.jooq.Record; @@ -31,6 +32,8 @@ public final class WorldCanonicalInitialAdmissionHoldRepository { + "canonical_world_slug, canonical_game_instance_id, canonical_version_id, " + "initial_admission_origin, expected_prior_pointer_version, canonical_request_bytes, " + "hold_binding_digest FROM initial_admission_bind_hold "; + private static final String HOLD_STATE_SELECT = + HOLD_SELECT.replace("SELECT hold_id,", "SELECT status, hold_id,"); private static final String TRANSACTION_STATE_SQL = "SELECT current_setting('transaction_isolation') AS isolation, " + "current_setting('transaction_read_only') AS read_only"; @@ -149,6 +152,107 @@ public Optional readIdentity(Request request) { })); } + /** + * Reads the exact immutable hold, its actual status, and current lifecycle in one read-only owner + * snapshot. This is a sampled observation only; it cannot acquire or settle the hold. + */ + public Optional readState( + HoldIdentity expectedIdentity, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleSelector) { + Objects.requireNonNull(expectedIdentity, "expectedIdentity"); + Objects.requireNonNull(lifecycleSelector, "lifecycleSelector"); + requireNoAmbientTransaction("World canonical initial-admission hold state read"); + Request expectedRequest = expectedIdentity.request(); + requireSelectorMatchesRequest(expectedRequest, lifecycleSelector); + + return Optional.ofNullable( + readTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + Optional maybeAssociation; + try { + maybeAssociation = + associationRepository.readOwnerAssociationInOwnerTransaction( + expectedRequest.canonicalGameInstanceId()); + } catch ( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException + inconsistent) { + throw new InvalidHoldIdentityException( + "Canonical World hold association is incomplete or inconsistent", inconsistent); + } + if (maybeAssociation.isEmpty()) { + Record detachedTypedHold = + dsl.fetchOne( + "SELECT hold_id FROM initial_admission_bind_hold " + + "WHERE canonical_game_instance_id = ?", + expectedRequest.canonicalGameInstanceId()); + if (detachedTypedHold != null) { + throw new InvalidHoldIdentityException( + "Canonical World hold exists without its required persisted association"); + } + return null; + } + WorldCanonicalInstanceAssociation association = maybeAssociation.orElseThrow(); + requireAssociationMatchesRequest(expectedRequest, association); + requireSelectorMatchesAssociation(lifecycleSelector, association); + + Record row = + dsl.fetchOne( + HOLD_STATE_SELECT + + "WHERE tenant_id = ? AND initial_admission_request_id = ?", + association.worldPrepareFields().privateTenantKey(), + expectedRequest.initialAdmissionRequestId()); + if (row == null) return null; + + HoldIdentity storedIdentity = verifyStoredIdentity(row, expectedRequest, association); + if (!Arrays.equals( + expectedIdentity.canonicalBytes(), storedIdentity.canonicalBytes())) { + throw new HoldConflictException( + "Canonical World initial-admission hold ID or fence differs from the exact " + + "expected identity"); + } + WorldCanonicalInitialAdmissionHoldState.HoldStatus holdStatus; + try { + holdStatus = + WorldCanonicalInitialAdmissionHoldState.HoldStatus.valueOf( + required(row, "status", String.class)); + } catch (RuntimeException invalid) { + throw new InvalidHoldIdentityException( + "Persisted canonical World initial-admission hold status is missing or invalid", + invalid); + } + + WorldCanonicalInstanceLifecycleEvidence lifecycle; + try { + lifecycle = + lifecycleReadRepository + .readForCurrentLocationInOwnerTransaction(lifecycleSelector) + .orElseThrow( + () -> + new InvalidHoldIdentityException( + "Canonical World lifecycle evidence is missing for an existing " + + "hold")); + } catch ( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException + inconsistent) { + throw new InvalidHoldIdentityException( + "Current canonical World lifecycle evidence is inconsistent", inconsistent); + } + if (!lifecycleSelector.equals(lifecycle.request())) { + throw new InvalidHoldIdentityException( + "Current canonical World lifecycle evidence substituted its exact read request"); + } + try { + return new WorldCanonicalInitialAdmissionHoldState( + storedIdentity, holdStatus, lifecycle); + } catch (IllegalArgumentException invalid) { + throw new InvalidHoldIdentityException( + "Canonical World hold state is inconsistent with current lifecycle evidence", + invalid); + } + })); + } + private int insert( Request request, WorldCanonicalInstanceAssociation.WorldPrepareFields privateKeys, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldMigrationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldMigrationPostgresIntegrationTest.java index a671234a01..7d1694ef0e 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldMigrationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldMigrationPostgresIntegrationTest.java @@ -251,6 +251,82 @@ void legacyReconciliationAndTerminalProofRemainAvailableAndNonterminalRowsBlockR } } + @Test + void migrationBackedReadOnlySnapshotObservesStoredStatusWithoutChangingSyntheticRows() + throws Exception { + // These are migration-fixture rows only: they do not supply canonical hold identity, + // authenticated Game Session authority, or lifecycle-owner evidence for the new RPC. + String schema = newSchema("initial_hold_state_snapshot_"); + try { + migrate(schema, "47"); + WorldFixture world = worldFixture(); + Map rows = new java.util.LinkedHashMap<>(); + try (Connection connection = connection()) { + DSLContext dsl = schemaContext(connection, schema); + insertLegacyWorld(dsl, world); + for (String status : List.of("PENDING", "COMMITTED", "ABORTED")) { + rows.put(status, insertLegacyHold(dsl, world, status)); + } + InitialAdmissionBindHoldRepository repository = new InitialAdmissionBindHoldRepository(dsl); + var pending = + repository + .findByTenantIdAndRequestId(world.tenantId(), rows.get("PENDING").requestId()) + .orElseThrow(); + var reconciling = + repository + .markReconciliationRequired( + pending, "SYNTHETIC_READBACK_FIXTURE", Instant.parse("2026-01-01T00:00:00Z")) + .orElseThrow(); + assertThat(reconciling.status()).isEqualTo("RECONCILIATION_REQUIRED"); + LegacySnapshot pendingSnapshot = rows.remove("PENDING"); + rows.put("RECONCILIATION_REQUIRED", pendingSnapshot); + } + + Map observedVersions = new java.util.LinkedHashMap<>(); + try (Connection connection = connection()) { + DSLContext dsl = schemaContext(connection, schema); + connection.setAutoCommit(false); + connection.setReadOnly(true); + connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + for (Map.Entry entry : rows.entrySet()) { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT status, row_version FROM initial_admission_bind_hold " + + "WHERE initial_admission_request_id = ?", + entry.getValue().requestId())); + assertThat(row.get("status", String.class)).isEqualTo(entry.getKey()); + observedVersions.put(entry.getKey(), row.get("row_version", Long.class)); + } + var transaction = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only")); + assertThat(transaction.get("isolation", String.class)).isEqualTo("repeatable read"); + assertThat(transaction.get("read_only", String.class)).isEqualTo("on"); + connection.rollback(); + } + + try (Connection connection = connection()) { + DSLContext dsl = schemaContext(connection, schema); + for (Map.Entry entry : rows.entrySet()) { + var row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT status, row_version FROM initial_admission_bind_hold " + + "WHERE initial_admission_request_id = ?", + entry.getValue().requestId())); + assertThat(row.get("status", String.class)).isEqualTo(entry.getKey()); + assertThat(row.get("row_version", Long.class)) + .isEqualTo(observedVersions.get(entry.getKey())); + } + } + } finally { + dropSchema(schema); + } + } + private LegacySnapshot insertLegacyHold(DSLContext dsl, WorldFixture world, String status) { String requestId = "legacy-" + status.toLowerCase() + "-" + UUID.randomUUID(); UUID holdId = UUID.randomUUID(); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcServiceTest.java index 7115b3248a..41c3bd17cb 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldGrpcServiceTest.java @@ -23,6 +23,7 @@ import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldRepository; @@ -30,6 +31,8 @@ import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldResponse; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityRequest; import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldIdentityResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldStateRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadCanonicalInitialAdmissionHoldStateResponse; import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.Test; import org.springframework.dao.TransientDataAccessException; @@ -245,6 +248,164 @@ void emptyHistoricalReadReturnsNotFoundWithoutAnIdentityPayload() { verify(repository).readIdentity(fixture.holdRequest); } + @Test + void stateReadRequiresLifecycleCorrelationAndCompleteTargetBeforeOwnerRead() { + Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var grpc = service(repository); + var wrongCorrelation = stateRead(HOLD_READ_ID.toString(), fixture); + + assertThat(callStateRead(grpc, wrongCorrelation, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + Fixture wrongNamespace = fixture("test", "other", PLAYABLE_NAMESPACE); + assertThat( + callStateRead( + grpc, + stateRead( + wrongNamespace.lifecycleRequest.readRequestId().toString(), wrongNamespace), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.PERMISSION_DENIED); + Fixture mismatchedScope = fixture("test", "test", OTHER_PLAYABLE_NAMESPACE); + assertThat( + callStateRead( + grpc, + stateRead( + mismatchedScope.lifecycleRequest.readRequestId().toString(), + mismatchedScope), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(repository); + } + + @Test + void stateReadEchoesExactMockedOwnerStateAndRequestCorrelation() { + Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence = + mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(lifecycleEvidence.request()).thenReturn(fixture.lifecycleRequest); + when(lifecycleEvidence.lifecycleStatus()).thenReturn("ACTIVE"); + when(lifecycleEvidence.lifecycleEpoch()).thenReturn(7L); + // The repository is mocked here; this sentinel only exercises response routing, not the + // validity or provenance of upstream lifecycle bytes. + when(lifecycleEvidence.canonicalBytes()).thenReturn(new byte[] {1}); + var expectedState = + new WorldCanonicalInitialAdmissionHoldState( + fixture.identity, + WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, + lifecycleEvidence); + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(repository.readState( + any(HoldIdentity.class), any(WorldCanonicalInstanceLifecycleEvidence.Request.class))) + .thenReturn(Optional.of(expectedState)); + var grpc = service(repository); + + Collector result = + callStateRead( + grpc, + stateRead(fixture.lifecycleRequest.readRequestId().toString(), fixture), + peer("game-session-service", "test")); + + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.value.getReadRequestId()) + .isEqualTo(fixture.lifecycleRequest.readRequestId().toString()); + assertThat(result.value.getHoldStateBytes().toByteArray()) + .containsExactly(expectedState.canonicalBytes()); + verify(repository).readState(fixture.identity, fixture.lifecycleRequest); + } + + @Test + void stateReadPeerAndAmbientTransactionGatesRunBeforeParsingOrRepositoryAccess() { + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var grpc = service(repository); + var malformed = + ReadCanonicalInitialAdmissionHoldStateRequest.newBuilder() + .setReadRequestId("not-a-uuid") + .build(); + + assertThat(callStateRead(grpc, malformed, null).error).isEqualTo(Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); + Collector endUser; + try { + endUser = callStateRead(grpc, malformed, peer("game-session-service", "test")); + } finally { + SessionContext.clear(); + } + assertThat(endUser.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + TransactionSynchronizationManager.setActualTransactionActive(true); + Collector ambient; + try { + ambient = callStateRead(grpc, malformed, peer("game-session-service", "test")); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + assertThat(ambient.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(repository); + } + + @Test + void stateReadRejectsUnknownWireFieldsAndReturnsNotFoundForAbsentOwnerState() { + Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); + var repository = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var grpc = service(repository); + var unknown = + stateRead(fixture.lifecycleRequest.readRequestId().toString(), fixture).toBuilder() + .setUnknownFields(unknownFields()) + .build(); + assertThat(callStateRead(grpc, unknown, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + var malformedIdentity = + stateRead(fixture.lifecycleRequest.readRequestId().toString(), fixture).toBuilder() + .setHoldIdentityBytes(ByteString.copyFrom(new byte[] {1})) + .build(); + assertThat(callStateRead(grpc, malformedIdentity, peer("game-session-service", "test")).error) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + when(repository.readState( + any(HoldIdentity.class), any(WorldCanonicalInstanceLifecycleEvidence.Request.class))) + .thenReturn(Optional.empty()); + assertThat( + callStateRead( + grpc, + stateRead(fixture.lifecycleRequest.readRequestId().toString(), fixture), + peer("game-session-service", "test")) + .error) + .isEqualTo(Status.Code.NOT_FOUND); + verify(repository).readState(fixture.identity, fixture.lifecycleRequest); + } + + @Test + void stateReadMapsIncompleteOwnerEvidenceAndUnavailableStorageWithoutStatePayload() { + Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); + var request = stateRead(fixture.lifecycleRequest.readRequestId().toString(), fixture); + + var incomplete = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(incomplete.readState( + any(HoldIdentity.class), any(WorldCanonicalInstanceLifecycleEvidence.Request.class))) + .thenThrow( + new WorldCanonicalInitialAdmissionHoldRepository.InvalidHoldIdentityException( + "incomplete state")); + Collector invalid = + callStateRead(service(incomplete), request, peer("game-session-service", "test")); + assertThat(invalid.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(invalid.value).isNull(); + + var unavailable = mock(WorldCanonicalInitialAdmissionHoldRepository.class); + when(unavailable.readState( + any(HoldIdentity.class), any(WorldCanonicalInstanceLifecycleEvidence.Request.class))) + .thenThrow(new TransientDataAccessException("temporary hold-state storage failure") {}); + Collector transientFailure = + callStateRead(service(unavailable), request, peer("game-session-service", "test")); + assertThat(transientFailure.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(transientFailure.value).isNull(); + } + @Test void mapsOwnerConflictsAndInconsistentIdentitiesToTheirExactStatuses() { Fixture fixture = fixture("test", "test", PLAYABLE_NAMESPACE); @@ -422,6 +583,15 @@ private static ReadCanonicalInitialAdmissionHoldIdentityRequest read( .build(); } + private static ReadCanonicalInitialAdmissionHoldStateRequest stateRead( + String readId, Fixture fixture) { + return ReadCanonicalInitialAdmissionHoldStateRequest.newBuilder() + .setReadRequestId(readId) + .setHoldIdentityBytes(ByteString.copyFrom(fixture.identity.canonicalBytes())) + .setCanonicalLifecycleReadRequestBytes(ByteString.copyFrom(fixture.lifecycleBytes)) + .build(); + } + private static UnknownFieldSet unknownFields() { return UnknownFieldSet.newBuilder() .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) @@ -464,6 +634,24 @@ private static Collector call return response; } + private static Collector callStateRead( + WorldCanonicalInitialAdmissionHoldGrpcService service, + ReadCanonicalInitialAdmissionHoldStateRequest request, + GrpcPeerIdentity peer) { + Collector response = new Collector<>(); + Context context = + peer == null + ? Context.current() + : Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readCanonicalInitialAdmissionHoldState(request, response); + } finally { + context.detach(previous); + } + return response; + } + private static GrpcPeerIdentity peer(String service, String namespace) { return new GrpcPeerIdentity( "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java index 70b808fd51..4590d763c9 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java @@ -7,11 +7,13 @@ import static org.mockito.ArgumentMatchers.contains; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -19,6 +21,7 @@ import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation.CanonicalIdentity; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation.WorldPrepareFields; @@ -232,6 +235,150 @@ void identityReadReturnsHistoricalAcquisitionWithoutUsingCurrentLifecycleRead() verify(fixture.associations).readOwnerAssociationInOwnerTransaction(CANONICAL_INSTANCE); } + @Test + void stateReadUsesOneReadOnlyRepeatableReadSnapshotAndReturnsExactIdentityStatusAndLifecycle() { + Request request = noPriorRequest(); + Fixture fixture = + fixture( + request, + activeLifecycle("ACTIVE", request.activeLifecycleEpoch()), + storedRow(request, HOLD_ID, HOLD_FENCE, "PENDING")); + + Optional result = + fixture.repository.readState( + new HoldIdentity(request, HOLD_ID, HOLD_FENCE), selector(request)); + + assertThat(result).isPresent(); + WorldCanonicalInitialAdmissionHoldState state = result.orElseThrow(); + assertThat(state.holdIdentity()).isEqualTo(new HoldIdentity(request, HOLD_ID, HOLD_FENCE)); + assertThat(state.holdStatus()) + .isEqualTo(WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING); + assertThat(state.lifecycleEvidence().request()).isEqualTo(selector(request)); + assertThat(state.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(state.isPendingAtExpectedActiveEpoch()).isTrue(); + assertThat(fixture.manager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(fixture.manager.startedWith.isReadOnly()).isTrue(); + assertThat(fixture.manager.startedCount).isEqualTo(1); + verify(fixture.lifecycle).readForCurrentLocationInOwnerTransaction(selector(request)); + verify(fixture.associations).readOwnerAssociationInOwnerTransaction(CANONICAL_INSTANCE); + verify(fixture.dsl, never()).execute(anyString(), any(Object[].class)); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(fixture.dsl, times(1)).fetchOne(sql.capture(), any(Object[].class)); + assertThat(sql.getAllValues()) + .anySatisfy( + statement -> + assertThat(statement) + .contains("SELECT status, hold_id") + .contains("initial_admission_request_id")); + } + + @Test + void stateReadReportsTerminalReconciliationAndAdvancedLifecycleWithoutQualifyingThem() { + Request request = noPriorRequest(); + for (String status : List.of("COMMITTED", "ABORTED", "RECONCILIATION_REQUIRED")) { + Fixture fixture = + fixture( + request, + activeLifecycle("ACTIVE", request.activeLifecycleEpoch()), + storedRow(request, HOLD_ID, HOLD_FENCE, status)); + var state = + fixture + .repository + .readState(new HoldIdentity(request, HOLD_ID, HOLD_FENCE), selector(request)) + .orElseThrow(); + assertThat(state.holdStatus().name()).isEqualTo(status); + assertThat(state.isPendingAtExpectedActiveEpoch()).isFalse(); + } + + Fixture advanced = + fixture( + request, + activeLifecycle("TERMINATING", request.activeLifecycleEpoch() + 1), + storedRow(request, HOLD_ID, HOLD_FENCE, "PENDING")); + var advancedState = + advanced + .repository + .readState(new HoldIdentity(request, HOLD_ID, HOLD_FENCE), selector(request)) + .orElseThrow(); + assertThat(advancedState.lifecycleEvidence().lifecycleStatus()).isEqualTo("TERMINATING"); + assertThat(advancedState.lifecycleEvidence().lifecycleEpoch()) + .isEqualTo(request.activeLifecycleEpoch() + 1); + assertThat(advancedState.isPendingAtExpectedActiveEpoch()).isFalse(); + } + + @Test + void missingLookupReturnsEmptyButIncompleteCurrentEvidenceAndSubstitutedFenceDeny() { + Request request = noPriorRequest(); + Fixture missing = fixture(request, activeLifecycle("ACTIVE", 7L), null); + assertThat( + missing.repository.readState( + new HoldIdentity(request, HOLD_ID, HOLD_FENCE), selector(request))) + .isEmpty(); + verify(missing.lifecycle, never()) + .readForCurrentLocationInOwnerTransaction( + any(WorldCanonicalInstanceLifecycleEvidence.Request.class)); + + Fixture incomplete = + fixture( + request, + activeLifecycle("ACTIVE", 7L), + storedRow(request, HOLD_ID, HOLD_FENCE, "PENDING")); + when(incomplete.lifecycle.readForCurrentLocationInOwnerTransaction(selector(request))) + .thenReturn(Optional.empty()); + assertThatThrownBy( + () -> + incomplete.repository.readState( + new HoldIdentity(request, HOLD_ID, HOLD_FENCE), selector(request))) + .isInstanceOf( + WorldCanonicalInitialAdmissionHoldRepository.InvalidHoldIdentityException.class); + + Fixture substituted = + fixture( + request, + activeLifecycle("ACTIVE", 7L), + storedRow(request, HOLD_ID, HOLD_FENCE, "PENDING")); + assertThatThrownBy( + () -> + substituted.repository.readState( + new HoldIdentity( + request, HOLD_ID, uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc")), + selector(request))) + .isInstanceOf(WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException.class) + .hasMessageContaining("ID or fence"); + + Map incompleteStatus = storedValues(request, HOLD_ID, HOLD_FENCE); + incompleteStatus.remove("status"); + Fixture badStatus = fixture(request, activeLifecycle("ACTIVE", 7L), row(incompleteStatus)); + assertThatThrownBy( + () -> + badStatus.repository.readState( + new HoldIdentity(request, HOLD_ID, HOLD_FENCE), selector(request))) + .isInstanceOf( + WorldCanonicalInitialAdmissionHoldRepository.InvalidHoldIdentityException.class); + verify(badStatus.lifecycle, never()) + .readForCurrentLocationInOwnerTransaction( + any(WorldCanonicalInstanceLifecycleEvidence.Request.class)); + } + + @Test + void stateReadRejectsAmbientTransactionBeforeAnyOwnerLookup() { + Request request = noPriorRequest(); + Fixture fixture = fixture(request, activeLifecycle("ACTIVE", 7L), null); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + fixture.repository.readState( + new HoldIdentity(request, HOLD_ID, HOLD_FENCE), selector(request))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not join an ambient transaction"); + + TransactionSynchronizationManager.setActualTransactionActive(false); + verifyNoInteractions(fixture.dsl, fixture.associations, fixture.lifecycle); + assertThat(fixture.manager.startedWith).isNull(); + } + private static void assertStoredRowDenied(Request request, Record storedRow) { Fixture fixture = fixture(request, activeLifecycle("ACTIVE", 7L), storedRow); assertThatThrownBy(() -> fixture.repository.acquire(request, selector(request))) @@ -254,6 +401,8 @@ private static Fixture fixture( when(lifecycle.readForActivationInOwnerTransaction(selector(request))) .thenReturn(Optional.of(lifecycleEvidence)); + when(lifecycle.readForCurrentLocationInOwnerTransaction(selector(request))) + .thenReturn(Optional.of(lifecycleEvidence)); when(associations.readOwnerAssociationInActivationTransaction(CANONICAL_INSTANCE)) .thenReturn(Optional.of(association)); when(associations.readOwnerAssociationInOwnerTransaction(CANONICAL_INSTANCE)) @@ -321,6 +470,7 @@ private static WorldCanonicalInstanceLifecycleEvidence activeLifecycle( when(evidence.request()).thenReturn(selector(request)); when(evidence.lifecycleStatus()).thenReturn(status); when(evidence.lifecycleEpoch()).thenReturn(epoch); + when(evidence.canonicalBytes()).thenReturn(new byte[] {1}); return evidence; } @@ -373,10 +523,17 @@ private static Record storedRow(Request request, UUID holdId, UUID holdFence) { return row(storedValues(request, holdId, holdFence)); } + private static Record storedRow(Request request, UUID holdId, UUID holdFence, String status) { + Map values = storedValues(request, holdId, holdFence); + values.put("status", status); + return row(values); + } + private static Map storedValues(Request request, UUID holdId, UUID holdFence) { Map values = new HashMap<>(); values.put("hold_id", holdId); values.put("hold_fence", holdFence); + values.put("status", "PENDING"); values.put("tenant_id", 41L); values.put("realm_uuid", request.realmId()); values.put("playable_state_namespace_uuid", request.playableStateNamespaceId()); @@ -455,12 +612,14 @@ private record Fixture( private static final class RecordingTransactionManager implements org.springframework.transaction.PlatformTransactionManager { private TransactionDefinition startedWith; + private int startedCount; @Override public TransactionStatus getTransaction(TransactionDefinition definition) { TransactionDefinition effectiveDefinition = definition == null ? TransactionDefinition.withDefaults() : definition; startedWith = effectiveDefinition; + startedCount++; TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly( effectiveDefinition.isReadOnly()); From a6c0c20d80c8a373a8af513e01d28b6956cadbb2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:04:17 +1300 Subject: [PATCH 067/129] Retain distinct World participation and correct composed owner proof --- ...ame-authoring-publishing-and-activation.md | 8 + .../DraftAuthorizationFenceRepository.java | 44 +- ...ostedTermsDisclosureHandoffRepository.java | 2 +- ...tartSessionAuthorityCaptureRepository.java | 16 +- ...129__start_session_world_participation.sql | 692 ++++++++++++++++++ ...V94__selected_publication_inventory_v2.sql | 4 +- ...e_logic_intake_source_read_reservation.sql | 4 +- .../AccountApplicationIntegrationTest.java | 2 + ...issionLeasePersistenceIntegrationTest.java | 3 +- ...uthorizationRepositoryIntegrationTest.java | 5 +- ...dParticipationPostgresIntegrationTest.java | 175 +++++ ...horizationFenceWorldParticipationTest.java | 287 ++++++++ ...sclosureHandoffWorldParticipationTest.java | 245 +++++++ ...SessionAuthorityCaptureRepositoryTest.java | 196 +++++ .../common/security/AuthTokenInterceptor.java | 53 +- .../CommonSecurityAutoConfigurationTest.java | 6 +- .../security/AuthTokenInterceptorTest.java | 215 ++++++ ...ldCanonicalInstancePreparationService.java | 37 + ...nceAssociationPostgresIntegrationTest.java | 207 +++--- ...CanonicalStartSessionTerminalReadTest.java | 357 +++++++++ 20 files changed, 2429 insertions(+), 129 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V129__start_session_world_participation.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffWorldParticipationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalStartSessionTerminalReadTest.java 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 5def168536..2f96baae1a 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 @@ -6,6 +6,14 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Account V129 prepares distinct World StartSession participation storage with an independent participation fence, the unchanged complete original post-authorization tuple, exact redeemed Game Session attempt/fence, canonical World target and byte-exact preparation input. Its immutable source children must equal the retained V128 capture; pending participation excludes source mutation and hosted-terms dispatch until an exact immutable World `COMMITTED` or fenced `ABORTED` receipt settles it. Acquisition checks exact captured hosted-terms evidence, not merely a historical disclosure sharing a source key. These SQL integrity and exclusion guards are not a genuine authenticated acquisition or settlement producer. The PostgreSQL definition currently covers migration installation, assembled guard preservation and append-only rejection, not positive authenticated participation or physical concurrency. World adds a read-only terminal projection behind its original-operation recovery verifier; missing or pending operations remain unresolved. The default verifier still denies and no new receiver is registered. Producer, transport, currentness, settlement, physical PostgreSQL and activation proof remain open. + +The originating [47078 validation run](https://github.com/benhook1013/FireMUD/actions/runs/38001925284) exposes real Account capture readback and shared authentication-context defects, alongside stale proof fixtures. The prepared correction compares canonical snapshot UUID strings with typed PostgreSQL UUID values and clears stale thread-local caller state on JWT-exempt calls without removing authenticated gRPC context or verified peer identity. Account fixtures now preserve historical pre-V81 creation order, bounded schema names and mocked outbound clients for unrelated HTTP proof; Gameplay's final V94/V97 guards are retained. World proof keeps canonical release profiles, translated SQL failures and distinct original operation identities; a racing exact duplicate must remain denied while the original is `PENDING`, not automatically restart. Corrected physical execution remains required. + +Four Account receipt-confirmation cases remain a separate durability-proof gap. Three fail at V120's conservative global-WAL coverage guard with the observed flush frontier 64 bytes behind the insert frontier; they do not reach the claimed receipt commit, duplicate or serializable-retry postcondition. The lost-acknowledgement case records no expected physical receipt commit, but its saved exception does not establish that same root cause. Unrelated marker writes, longer credential lifetime and a weakened durability guard are not accepted substitutes. This is not evidence that the active StartSession path must commit before its ingress credential expires, nor permission to enable an unproved admission path. + +The corrected V129/source-writer, terminal projection and CI-repair batch passes the composed affected local gate: 489 Common Platform, 141 Common Security, 1,188 Account, 224 Logging and 614 World unit cases (2,656 total), with zero failures, errors or skips. Nine non-container integration cases execute; 491 integration definitions skip without Docker (249 Account, 23 Logging, 219 World, including Redis definitions). Successful unchanged tasks reuse their results. Schema generation, formatting, Checkstyle, SpotBugs, coverage, affected boot JARs, links and Markdown pass; Flyway sanity checks 12 sets and 286 versioned files. New source-exclusion, typed UUID and terminal tests prove mocked owner ordering and integrity, not authenticated positive acquisition, physical PostgreSQL concurrency, socket currentness or end-to-end launch. The four durability cases and corrected physical execution remain open. + The disabled-by-default sole Account StartSession issuer now composes the original committed ControlUI owner with V128 full source capture. It commits capture before private reference generation, fingerprinting or response encryption, captures trusted environment evidence again outside SQL after private crypto, then rechecks the original actor/JTI, complete current source and exact capture under the final owner transaction before retaining issuance. Capture version/fence and the actual issuance fence remain independent; the one original capture reference is retained unchanged. Exact issue retry, recovery and concurrent-winner recovery use lookup-only capture readback and post-decryption currentness checks before returning the original encrypted result, without allocation, reminting or expiry extension. Original Logging claim expiry is checked before capture, before private crypto and through the final issuance callback; these samples do not establish external environment continuity or commit-spanning foreign claim protection. The passive Logging evidence dependency comes from merged #3132: exact same-namespace Account identity and actual approved certificate leaf, no authenticated end-user context, complete original claim readback, and production reservation mutation still denied. The original configured Game Session redeemer is allowed only the restricted credential-free current projection read; consumer claim/pin proof remains separately owned. Physical PostgreSQL, genuine live reservation authority, custody and activation remain open. The corrected sole-issuer/Logging/World recovery composition passes the full affected local checks: 479 Common, 1,178 Account, 224 Logging and 600 World unit cases (2,481 total), without failures, errors or skips. Nine non-container integration cases execute; 489 integration definitions skip without Docker (248 Account, 23 Logging, 218 World, including Redis definitions). Unchanged successful tasks reuse their local results; this is composed working-tree proof, not a fresh physical end-to-end run. Schema generation, affected boot JARs, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass. Flyway sanity passes 12 sets and 285 versioned files. Fourteen issuer-service cases cover mocked owner ordering, exact retry/recovery, changed-source denial and concurrent winner recovery; six World service cases cover explicitly synthetic recovery verification and read-only behavior. The genuine original-operation verifier, expired-operation Game Session producer, World terminal transport and continuously protected Account participation remain missing, not proved by these tests. Parent review also corrected the historical V75 upgrade fixture to use its actual database UUID-provenance insertion path rather than a later V81-dependent repository initializer; physical execution remains required. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 66099c9f28..846c1dc4b6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -252,6 +252,7 @@ public void requireDisclosurePreparation(List exactSources) { } requireNoPendingPublication(sources); requireNoPendingGameLogicIntake(sources); + requireNoPendingWorldParticipation(sources); for (UUID operationId : affectedOperations(sources)) { Record row = readOperation(operationId); if (row == null) { @@ -278,14 +279,27 @@ public void lockDisclosureSources(List exactSources) { throw new IllegalArgumentException("Distinct exact disclosure source evidence required"); } for (SourceEvidence source : sources) { - if (source.key().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 512) { + if (source.key().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 2048) { throw new IllegalArgumentException( - "Disclosure source key exceeds the existing Account source-lock bound"); + "Disclosure source key exceeds the Account source-lock bound"); } } lockSources(sources); } + /** + * Narrow World-participation exclusion for disclosure dispatch, including ambiguity recovery. + * This deliberately does not re-run the broader PREPARED-only admission checks. + */ + public void requireWorldParticipationDisclosureAdmission(List exactSources) { + List sources = + List.copyOf(Objects.requireNonNull(exactSources, "exact disclosure sources")).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + lockDisclosureSources(sources); + requireNoPendingWorldParticipation(sources); + } + private void requireNoAuthorizedDisclosure(List sources) { for (SourceEvidence source : sources) { if (source.kind() == SourceKind.HOSTED_TERMS @@ -354,6 +368,28 @@ private void requireNoPendingGameLogicIntake(List sources) { } } + private boolean hasPendingWorldParticipation(List sources) { + for (SourceEvidence source : sources) { + if (!dsl.fetch( + "SELECT 1 FROM account_start_session_world_participation_sources s " + + "JOIN account_start_session_world_participations p " + + "ON p.participation_id = s.participation_id " + + "WHERE s.source_key = ? " + + "AND NOT account_start_session_world_participation_is_settled(p.participation_id)", + source.key()) + .isEmpty()) { + return true; + } + } + return false; + } + + private void requireNoPendingWorldParticipation(List sources) { + if (hasPendingWorldParticipation(sources)) { + throw new IllegalStateException("Original StartSession World participation remains pending"); + } + } + private boolean hasPendingPublication(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( @@ -803,7 +839,9 @@ private List affectedOperations(List sources) { * evidence always remains pending. */ private boolean allAffectedSettled(List sources) { - if (hasPendingPublication(sources) || hasPendingGameLogicIntake(sources)) { + if (hasPendingPublication(sources) + || hasPendingGameLogicIntake(sources) + || hasPendingWorldParticipation(sources)) { return false; } for (UUID operation : affectedOperations(sources)) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java index fbff4669c8..acf2f8f849 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java @@ -149,7 +149,7 @@ public Snapshot prepare(HostedTermsDisclosureHandoff handoff) { public DispatchPermit authorizeDispatch(HostedTermsDisclosureHandoff handoff) { requireWriteTransaction(); Objects.requireNonNull(handoff); - fenceRepository.lockDisclosureSources(handoff.sources()); + fenceRepository.requireWorldParticipationDisclosureAdmission(handoff.sources()); Record row = requireExactRow(handoff); Status status = Status.valueOf(row.get("status", String.class)); boolean newlyAuthorized = false; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java index 57d0ded2f8..37022fd39c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java @@ -267,19 +267,21 @@ private static void requireStoredColumnsMatchPayload( || !capture.capturedAt().equals(reference.get("capturedAt")) || !capture.capturedAt().equals(row.get("captured_at", String.class)) || !capture.snapshotSha256().equals(row.get("snapshot_sha256", String.class)) - || !Objects.equals(snapshot.get("accountId"), uuid(row, "account_uuid")) - || !Objects.equals(snapshot.get("tenantId"), uuid(row, "tenant_uuid")) + || !Objects.equals(snapshot.get("accountId"), canonicalUuid(row, "account_uuid")) + || !Objects.equals(snapshot.get("tenantId"), canonicalUuid(row, "tenant_uuid")) || !Objects.equals(snapshot.get("targetOwner"), row.get("target_owner", String.class)) || !Objects.equals( snapshot.get("loggingWorkloadUri"), row.get("logging_workload_uri", String.class)) - || !Objects.equals(snapshot.get("reservationOwnerId"), uuid(row, "reservation_owner_id")) + || !Objects.equals( + snapshot.get("reservationOwnerId"), canonicalUuid(row, "reservation_owner_id")) || !Objects.equals( snapshot.get("reservationClaimFence"), Long.toString(number(row, "reservation_claim_fence"))) || !Objects.equals(snapshot.get("mutationDigest"), row.get("mutation_digest", String.class)) || !Objects.equals( - snapshot.get("controlUiOperationId"), uuid(row, "control_ui_operation_id")) - || !Objects.equals(snapshot.get("controlUiTokenJti"), uuid(row, "control_ui_token_jti")) + snapshot.get("controlUiOperationId"), canonicalUuid(row, "control_ui_operation_id")) + || !Objects.equals( + snapshot.get("controlUiTokenJti"), canonicalUuid(row, "control_ui_token_jti")) || !Objects.equals( snapshot.get("controlUiTokenHash"), row.get("control_ui_token_hash", String.class)) || !Objects.equals( @@ -450,9 +452,9 @@ private static boolean canonicalLoggingWorkload(String uri, String targetNamespa } } - private static UUID uuid(Record row, String field) { + private static String canonicalUuid(Record row, String field) { UUID value = row.get(field, UUID.class); - return value == null ? null : value; + return value == null ? null : value.toString(); } private static long number(Record row, String field) { diff --git a/services/account-service/src/main/resources/db/migration/V129__start_session_world_participation.sql b/services/account-service/src/main/resources/db/migration/V129__start_session_world_participation.sql new file mode 100644 index 0000000000..e553c2faba --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V129__start_session_world_participation.sql @@ -0,0 +1,692 @@ +-- Account-owned participation in the distinct World StartSession execution. This is an +-- integrity fence only: it does not authenticate the World transport or enable execution. +CREATE TABLE account_start_session_world_participations ( + participation_id UUID PRIMARY KEY + CHECK (participation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + participation_fence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE + CHECK (participation_fence > 0), + control_plane_request_id VARCHAR(128) NOT NULL UNIQUE + CHECK (octet_length(control_plane_request_id) BETWEEN 1 AND 128), + original_post_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + target_namespace VARCHAR(63) NOT NULL + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + canonical_tenant_id UUID NOT NULL + REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id) ON DELETE RESTRICT + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + canonical_game_instance_id UUID NOT NULL + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_attempt_id UUID NOT NULL + CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + preparation_input_json TEXT NOT NULL CHECK (length(preparation_input_json) > 0), + preparation_input_digest VARCHAR(71) NOT NULL + CHECK (preparation_input_digest ~ '^sha256:[0-9a-f]{64}$'), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_start_session_world_participation_authorization_fk + FOREIGN KEY (control_plane_request_id) + REFERENCES account_start_session_operator_authorizations(control_plane_request_id) + ON DELETE RESTRICT, + CONSTRAINT account_start_session_world_participation_capture_fk + FOREIGN KEY (control_plane_request_id) + REFERENCES account_start_session_authority_captures(control_plane_request_id) + ON DELETE RESTRICT +); + +CREATE TABLE account_start_session_world_participation_sources ( + participation_id UUID NOT NULL + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + source_key VARCHAR(2048) NOT NULL + CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048) + REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (participation_id, source_key) +); +CREATE INDEX account_start_session_world_participation_sources_by_key + ON account_start_session_world_participation_sources(source_key, participation_id); + +CREATE TABLE account_start_session_world_participation_settlements ( + participation_id UUID PRIMARY KEY + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + world_execution_fence BIGINT NOT NULL CHECK (world_execution_fence > 0), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 25165824), + terminal_digest VARCHAR(71) NOT NULL CHECK (terminal_digest ~ '^sha256:[0-9a-f]{64}$'), + settled_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK (terminal_digest = 'sha256:' || encode(sha256(terminal_bytes), 'hex')) +); + +-- [jooq ignore start] +CREATE FUNCTION account_start_session_world_participation_source_key(evidence BYTEA) +RETURNS TEXT LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + position_value INTEGER := 1; + parsed BYTEA; + kind_value TEXT; + scope_value TEXT; + source_key_value TEXT; +BEGIN + SELECT frame_value, next_position INTO parsed, position_value + FROM account_publication_authorization_read_frame(evidence, position_value); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Invalid StartSession participation source schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, position_value + FROM account_publication_authorization_read_frame(evidence, position_value); + kind_value := convert_from(parsed, 'UTF8'); + SELECT frame_value, next_position INTO parsed, position_value + FROM account_publication_authorization_read_frame(evidence, position_value); + scope_value := convert_from(parsed, 'UTF8'); + source_key_value := kind_value || ':' || scope_value; + IF length(kind_value) = 0 OR length(scope_value) = 0 + OR length(source_key_value) = 0 OR octet_length(source_key_value) > 2048 THEN + RAISE EXCEPTION 'Invalid StartSession participation source key' USING ERRCODE = '23514'; + END IF; + RETURN source_key_value; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_validate_input( + input_json TEXT, + input_digest TEXT, + original_tuple BYTEA, + namespace_value TEXT, + tenant_value UUID, + request_value TEXT, + instance_value UUID +) RETURNS VOID LANGUAGE plpgsql IMMUTABLE STRICT AS $$ +DECLARE + input_value JSONB; + tuple_value JSONB; + original_value JSONB; + descriptor_value JSONB; +BEGIN + IF length(input_json) = 0 + OR input_digest !~ '^sha256:[0-9a-f]{64}$' + OR input_digest IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(input_json, 'UTF8')), 'hex') + OR octet_length(original_tuple) NOT BETWEEN 1 AND 262144 + OR namespace_value !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR tenant_value = '00000000-0000-0000-0000-000000000000'::UUID + OR instance_value = '00000000-0000-0000-0000-000000000000'::UUID + OR length(request_value) = 0 THEN + RAISE EXCEPTION 'Malformed StartSession World participation identity or preparation input' + USING ERRCODE = '23514'; + END IF; + + input_value := input_json::JSONB; + tuple_value := convert_from(original_tuple, 'UTF8')::JSONB; + original_value := tuple_value->'preAuthorizationReservationTuple'; + IF jsonb_typeof(input_value) IS DISTINCT FROM 'object' + OR jsonb_typeof(input_value->'identity') IS DISTINCT FROM 'object' + OR jsonb_typeof(input_value->'gameSessionReadRequest') IS DISTINCT FROM 'object' + OR jsonb_typeof(input_value->'gameSessionReadEvidence') IS DISTINCT FROM 'object' + OR jsonb_typeof(tuple_value) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'StartSession World preparation input or tuple is not an object' + USING ERRCODE = '23514'; + END IF; + descriptor_value := (input_value->'gameSessionReadEvidence'->>'descriptorJson')::JSONB; + IF tuple_value->>'tupleSchemaId' IS DISTINCT FROM 'postAuthorizationExecutionTuple' + OR tuple_value->>'tupleSchemaVersion' IS DISTINCT FROM '1' + OR tuple_value->>'issuanceKind' IS DISTINCT FROM 'human_operator' + OR tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM + original_value->'actionFamilyRequestIdentity'->>'requestId' + OR tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM request_value + OR tuple_value->'scope'->>'targetNamespace' IS DISTINCT FROM namespace_value + OR tuple_value->'scope'->>'tenantId' IS DISTINCT FROM tenant_value::TEXT + OR tuple_value->'targetOwner'->>'ownerService' IS DISTINCT FROM 'game-session-service' + OR original_value->>'actionFamily' IS DISTINCT FROM 'StartSession' + OR (tuple_value->'target'->>'gameTemplateId')::BIGINT IS DISTINCT FROM + (descriptor_value->>'gameTemplateId')::BIGINT + OR input_value->'identity'->>'canonicalGameInstanceId' IS DISTINCT FROM instance_value::TEXT + OR input_value->'gameSessionReadEvidence'->>'canonicalGameInstanceId' IS DISTINCT FROM instance_value::TEXT + OR input_value->'gameSessionReadRequest'->>'canonicalGameInstanceId' IS DISTINCT FROM instance_value::TEXT + OR input_value->'identity'->>'targetNamespace' IS DISTINCT FROM namespace_value + OR input_value->'identity'->>'canonicalTenantId' IS DISTINCT FROM tenant_value::TEXT + OR input_value->'identity'->>'controlPlaneRequestId' IS DISTINCT FROM request_value + OR input_value->'gameSessionReadRequest'->>'targetNamespace' IS DISTINCT FROM namespace_value + OR input_value->'gameSessionReadRequest'->>'canonicalTenantId' IS DISTINCT FROM tenant_value::TEXT + OR input_value->'gameSessionReadRequest'->>'worldSlug' IS DISTINCT FROM + input_value->'identity'->>'worldSlug' + OR input_value->'gameSessionReadRequest'->>'controlPlaneRequestId' IS DISTINCT FROM request_value + OR input_value->'identity'->>'targetNamespace' IS DISTINCT FROM + input_value->'gameSessionReadEvidence'->>'targetNamespace' + OR input_value->'identity'->>'canonicalTenantId' IS DISTINCT FROM + input_value->'gameSessionReadEvidence'->>'canonicalTenantId' + OR input_value->'identity'->>'worldSlug' IS DISTINCT FROM + input_value->'gameSessionReadEvidence'->>'worldSlug' + OR input_value->'identity'->>'controlPlaneRequestId' IS DISTINCT FROM + input_value->'gameSessionReadEvidence'->>'controlPlaneRequestId' + OR input_value->'launchBinding'->>'targetNamespace' IS DISTINCT FROM namespace_value + OR input_value->'launchBinding'->>'canonicalTenantId' IS DISTINCT FROM tenant_value::TEXT + OR input_value->'launchBinding'->>'worldSlug' IS DISTINCT FROM + input_value->'identity'->>'worldSlug' + OR input_value->'launchBinding'->>'controlPlaneRequestId' IS DISTINCT FROM request_value + OR tuple_value->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt' IS NULL THEN + RAISE EXCEPTION 'World preparation identity or descriptor differs from the retained StartSession tuple' + USING ERRCODE = '23514'; + END IF; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_lock_sources(snapshot_value JSONB) +RETURNS TEXT[] LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + source_value JSONB; + evidence_value BYTEA; + source_key_value TEXT; + key_values TEXT[] := ARRAY[]::TEXT[]; + ordered_values TEXT[]; +BEGIN + IF jsonb_typeof(snapshot_value->'sourceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_value->'sourceVector') < 1 THEN + RAISE EXCEPTION 'StartSession participation requires a complete retained source vector' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + IF jsonb_typeof(source_value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'StartSession source vector entries must be Base64 strings' USING ERRCODE = '23514'; + END IF; + evidence_value := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(evidence_value); + IF source_key_value = ANY(key_values) THEN + RAISE EXCEPTION 'Duplicate StartSession participation source key' USING ERRCODE = '23514'; + END IF; + key_values := array_append(key_values, source_key_value); + END LOOP; + SELECT array_agg(value ORDER BY account_publication_authorization_source_sort_key(value)) + INTO ordered_values FROM unnest(key_values) AS keys(value); + IF key_values IS DISTINCT FROM ordered_values THEN + RAISE EXCEPTION 'StartSession retained source vector is not in canonical source-key order' + USING ERRCODE = '23514'; + END IF; + + FOR source_key_value IN + SELECT value FROM unnest(key_values) AS keys(value) + ORDER BY account_publication_authorization_source_sort_key(value) + LOOP + PERFORM source_key FROM account_draft_authorization_source_locks + WHERE source_key = source_key_value FOR UPDATE NOWAIT; + IF NOT FOUND THEN + RAISE EXCEPTION 'StartSession participation source lock is not provisioned' + USING ERRCODE = '23514'; + END IF; + END LOOP; + RETURN key_values; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_assert_exclusive( + source_keys TEXT[], snapshot_value JSONB +) +RETURNS VOID LANGUAGE plpgsql STABLE STRICT AS $$ +DECLARE + source_value JSONB; + evidence_value BYTEA; + source_key_value TEXT; +BEGIN + IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_draft_authorization_source_changes change USING (change_id) + WHERE changed.source_key = ANY(source_keys) AND change.status = 'WAITING' + ) THEN + RAISE EXCEPTION 'StartSession participation cannot acquire a source with a waiting source change' + USING ERRCODE = '55P03'; + END IF; + -- Match the exact captured hosted-terms evidence, as the existing Draft/publication + -- admission boundary does. An older DISCLOSED record or a shared role/source key + -- does not establish disclosure of this captured hosted-terms source version. + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + evidence_value := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(evidence_value); + IF source_key_value LIKE 'HOSTED_TERMS:%' AND EXISTS ( + SELECT 1 FROM account_hosted_terms_disclosure_handoffs handoff + JOIN account_hosted_terms_disclosure_sources handoff_source + ON handoff_source.handoff_id = handoff.handoff_id + WHERE handoff.source_key = source_key_value + AND handoff_source.source_key = handoff.source_key + AND handoff_source.source_evidence = evidence_value + AND handoff.status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS', 'DISCLOSED') + ) THEN + RAISE EXCEPTION 'StartSession participation cannot acquire an exactly disclosed hosted-terms source' + USING ERRCODE = '55P03'; + END IF; + END LOOP; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_assert_sources( + participation_value UUID, + snapshot_value JSONB +) RETURNS VOID LANGUAGE plpgsql STABLE STRICT AS $$ +DECLARE + source_value JSONB; + evidence_value BYTEA; + source_key_value TEXT; + key_values TEXT[] := ARRAY[]::TEXT[]; + ordered_values TEXT[]; + source_count INTEGER; +BEGIN + IF jsonb_typeof(snapshot_value->'sourceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_value->'sourceVector') < 1 THEN + RAISE EXCEPTION 'StartSession participation source vector is absent' USING ERRCODE = '23514'; + END IF; + source_count := jsonb_array_length(snapshot_value->'sourceVector'); + IF source_count IS DISTINCT FROM ( + SELECT count(*)::INTEGER FROM account_start_session_world_participation_sources + WHERE participation_id = participation_value) THEN + RAISE EXCEPTION 'StartSession participation has incomplete or extra source children' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + IF jsonb_typeof(source_value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'StartSession source vector entries must be Base64 strings' USING ERRCODE = '23514'; + END IF; + evidence_value := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(evidence_value); + IF source_key_value = ANY(key_values) + OR NOT EXISTS ( + SELECT 1 FROM account_start_session_world_participation_sources source + WHERE source.participation_id = participation_value + AND source.source_key = source_key_value + AND source.source_evidence = evidence_value) THEN + RAISE EXCEPTION 'StartSession source child differs from the exact captured source vector' + USING ERRCODE = '23514'; + END IF; + key_values := array_append(key_values, source_key_value); + END LOOP; + SELECT array_agg(value ORDER BY account_publication_authorization_source_sort_key(value)) + INTO ordered_values FROM unnest(key_values) AS keys(value); + IF key_values IS DISTINCT FROM ordered_values THEN + RAISE EXCEPTION 'StartSession captured source vector is not in canonical source-key order' + USING ERRCODE = '23514'; + END IF; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_is_settled(participation_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT EXISTS ( + SELECT 1 FROM account_start_session_world_participation_settlements settlement + WHERE settlement.participation_id = participation_value) +$$; + +CREATE FUNCTION account_start_session_world_participation_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + authorization account_start_session_operator_authorizations%ROWTYPE; + capture account_start_session_authority_captures%ROWTYPE; + tuple_value JSONB; + reservation_value JSONB; + bundle_reference JSONB; + snapshot_value JSONB; + source_keys TEXT[]; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'StartSession World participation is append-only' USING ERRCODE = '23514'; + END IF; + IF NEW.producer_xid IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'StartSession World participation must be created by its producer transaction' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = NEW.control_plane_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_value->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id THEN + RAISE EXCEPTION 'StartSession World participation must retain the exact Account capture' + USING ERRCODE = '23514'; + END IF; + source_keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(source_keys, snapshot_value); + + SELECT * INTO STRICT authorization FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = NEW.control_plane_request_id; + tuple_value := convert_from(NEW.original_post_authorization_tuple, 'UTF8')::JSONB; + IF authorization.status IS DISTINCT FROM 'REDEEMED' + OR authorization.reference_expires_at <= clock_timestamp() + OR tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM + convert_from(authorization.pre_authorization_tuple, 'UTF8')::JSONB + OR authorization.redemption_owner_attempt_id IS DISTINCT FROM NEW.game_session_owner_attempt_id + OR authorization.redemption_owner_fence IS DISTINCT FROM NEW.game_session_owner_fence THEN + RAISE EXCEPTION 'StartSession World participation requires the exact unexpired redeemed original authorization' + USING ERRCODE = '23514'; + END IF; + reservation_value := tuple_value->'preAuthorizationReservationTuple'; + bundle_reference := tuple_value->'authorityEvidenceBundleReference'; + IF tuple_value->>'tupleSchemaId' IS DISTINCT FROM 'postAuthorizationExecutionTuple' + OR tuple_value->>'tupleSchemaVersion' IS DISTINCT FROM '1' + OR tuple_value->>'issuanceKind' IS DISTINCT FROM 'human_operator' + OR tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR tuple_value->>'mutationDigest' IS DISTINCT FROM authorization.mutation_digest + OR tuple_value->>'authorizationReferenceFingerprint' IS DISTINCT FROM + authorization.authorization_reference_fingerprint + OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization.issuance_fence::TEXT + OR tuple_value->>'reservationOwnerId' IS DISTINCT FROM authorization.reservation_owner_id::TEXT + OR tuple_value->>'reservationClaimFence' IS DISTINCT FROM authorization.reservation_claim_fence::TEXT + OR tuple_value->>'authorityEvidenceBundleReference' IS NULL + OR bundle_reference->>'bundleVersion' IS DISTINCT FROM authorization.bundle_version + OR bundle_reference->>'sourceVersion' IS DISTINCT FROM authorization.bundle_source_version + OR bundle_reference->>'sourceFence' IS DISTINCT FROM authorization.bundle_source_fence + OR bundle_reference->>'linearization' IS DISTINCT FROM authorization.bundle_linearization + OR tuple_value->'authorityEvidenceBundle' IS DISTINCT FROM + convert_from(authorization.authority_evidence_bundle, 'UTF8')::JSONB + OR authorization.redemption_reference_fingerprint IS DISTINCT FROM + authorization.authorization_reference_fingerprint + OR authorization.redemption_authority_evidence_bundle IS DISTINCT FROM + authorization.authority_evidence_bundle + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization.pre_authorization_tuple + OR capture.account_uuid IS DISTINCT FROM (tuple_value->'actor'->>'accountId')::UUID + OR capture.tenant_uuid IS DISTINCT FROM NEW.canonical_tenant_id + OR capture.target_owner IS DISTINCT FROM tuple_value->'targetOwner'->>'ownerService' + OR capture.mutation_digest IS DISTINCT FROM authorization.mutation_digest + OR capture.reservation_owner_id IS DISTINCT FROM authorization.reservation_owner_id + OR capture.reservation_claim_fence IS DISTINCT FROM authorization.reservation_claim_fence + OR capture.issuance_fence IS DISTINCT FROM authorization.issuance_fence + OR capture.source_version::TEXT IS DISTINCT FROM bundle_reference->>'sourceVersion' + OR capture.source_fence::TEXT IS DISTINCT FROM bundle_reference->>'sourceFence' + OR capture.linearization IS DISTINCT FROM bundle_reference->>'linearization' + OR tuple_value->'scope'->>'targetNamespace' IS DISTINCT FROM NEW.target_namespace + OR tuple_value->'scope'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR reservation_value->>'actionFamily' IS DISTINCT FROM 'StartSession' + OR reservation_value->'actionFamilyRequestIdentity'->>'requestId' IS DISTINCT FROM + NEW.control_plane_request_id + OR tuple_value->'targetOwner'->>'ownerService' IS DISTINCT FROM 'game-session-service' THEN + RAISE EXCEPTION 'StartSession World participation differs from its original Account authorization or capture' + USING ERRCODE = '23514'; + END IF; + PERFORM account_start_session_world_participation_validate_input( + NEW.preparation_input_json, NEW.preparation_input_digest, + NEW.original_post_authorization_tuple, NEW.target_namespace, + NEW.canonical_tenant_id, NEW.control_plane_request_id, + NEW.canonical_game_instance_id); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + parent_xid BIGINT; +BEGIN + SELECT producer_xid INTO parent_xid FROM account_start_session_world_participations + WHERE participation_id = NEW.participation_id; + IF parent_xid IS DISTINCT FROM txid_current() + OR account_start_session_world_participation_source_key(NEW.source_evidence) IS DISTINCT FROM NEW.source_key THEN + RAISE EXCEPTION 'StartSession sources must accompany the exact original participation transaction' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_world_participations%ROWTYPE; + capture account_start_session_authority_captures%ROWTYPE; + snapshot_value JSONB; + source_keys TEXT[]; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_world_participations + WHERE participation_id = NEW.participation_id; + IF original.producer_xid IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'StartSession participation completion must run in its original transaction' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + source_keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(source_keys, snapshot_value); + PERFORM account_start_session_world_participation_assert_sources(original.participation_id, snapshot_value); + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_terminal_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_world_participations%ROWTYPE; + terminal_value JSONB; + terminal_field_count INTEGER; + source_key_value TEXT; + encoded_tuple TEXT; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'StartSession World participation settlement is append-only' USING ERRCODE = '23514'; + END IF; + SELECT * INTO STRICT original FROM account_start_session_world_participations + WHERE participation_id = NEW.participation_id; + FOR source_key_value IN SELECT source_key + FROM account_start_session_world_participation_sources + WHERE participation_id = NEW.participation_id + ORDER BY account_publication_authorization_source_sort_key(source_key) + LOOP + PERFORM source_key FROM account_draft_authorization_source_locks + WHERE source_key = source_key_value FOR UPDATE NOWAIT; + END LOOP; + PERFORM participation_id FROM account_start_session_world_participations + WHERE participation_id = NEW.participation_id FOR UPDATE NOWAIT; + + IF NEW.terminal_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') THEN + RAISE EXCEPTION 'World terminal digest does not bind the exact receipt bytes' USING ERRCODE = '23514'; + END IF; + terminal_value := convert_from(NEW.terminal_bytes, 'UTF8')::JSONB; + encoded_tuple := regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g'); + IF jsonb_typeof(terminal_value) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'World terminal must be a closed JSON object' USING ERRCODE = '23514'; + END IF; + SELECT count(*)::INTEGER INTO terminal_field_count FROM jsonb_object_keys(terminal_value); + IF terminal_field_count IS DISTINCT FROM 14 THEN + RAISE EXCEPTION 'World terminal must contain exactly fourteen fields' USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(terminal_value->'schema') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'originalPostAuthorizationTupleBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'accountWorldParticipationId') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'accountWorldParticipationFence') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'gameSessionOwnerAttemptId') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'gameSessionOwnerFence') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'targetNamespace') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'canonicalTenantId') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'controlPlaneRequestId') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'canonicalGameInstanceId') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'preparationInputDigest') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'preparationInputJson') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'worldExecutionFence') IS DISTINCT FROM 'string' + OR jsonb_typeof(terminal_value->'outcome') IS DISTINCT FROM 'string' + OR terminal_value->>'schema' IS DISTINCT FROM 'world-start-session-execution-terminal/v1' + OR terminal_value->>'originalPostAuthorizationTupleBase64' IS DISTINCT FROM encoded_tuple + OR terminal_value->>'accountWorldParticipationId' IS DISTINCT FROM original.participation_id::TEXT + OR terminal_value->>'accountWorldParticipationFence' IS DISTINCT FROM original.participation_fence::TEXT + OR terminal_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM original.game_session_owner_attempt_id::TEXT + OR terminal_value->>'gameSessionOwnerFence' IS DISTINCT FROM original.game_session_owner_fence::TEXT + OR terminal_value->>'targetNamespace' IS DISTINCT FROM original.target_namespace + OR terminal_value->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT + OR terminal_value->>'controlPlaneRequestId' IS DISTINCT FROM original.control_plane_request_id + OR terminal_value->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT + OR terminal_value->>'preparationInputDigest' IS DISTINCT FROM original.preparation_input_digest + OR terminal_value->>'preparationInputJson' IS DISTINCT FROM original.preparation_input_json + OR terminal_value->>'worldExecutionFence' !~ '^[1-9][0-9]{0,18}$' + OR (terminal_value->>'worldExecutionFence')::NUMERIC > 9223372036854775807 + OR (terminal_value->>'worldExecutionFence')::BIGINT IS DISTINCT FROM NEW.world_execution_fence + OR terminal_value->>'outcome' IS DISTINCT FROM NEW.outcome THEN + RAISE EXCEPTION 'World terminal is not the exact closed StartSession participation receipt' + USING ERRCODE = '23514'; + END IF; + PERFORM account_start_session_world_participation_validate_input( + original.preparation_input_json, original.preparation_input_digest, + original.original_post_authorization_tuple, original.target_namespace, + original.canonical_tenant_id, original.control_plane_request_id, + original.canonical_game_instance_id); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_world_participation_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'StartSession World participation evidence is append-only' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_start_session_world_participation_validate + BEFORE INSERT ON account_start_session_world_participations + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_insert_guard(); +CREATE TRIGGER account_start_session_world_participation_immutable + BEFORE UPDATE OR DELETE ON account_start_session_world_participations + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +CREATE TRIGGER account_start_session_world_participation_no_truncate + BEFORE TRUNCATE ON account_start_session_world_participations + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +CREATE TRIGGER account_start_session_world_participation_sources_insert + BEFORE INSERT ON account_start_session_world_participation_sources + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_source_insert_guard(); +CREATE TRIGGER account_start_session_world_participation_sources_immutable + BEFORE UPDATE OR DELETE ON account_start_session_world_participation_sources + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +CREATE TRIGGER account_start_session_world_participation_sources_no_truncate + BEFORE TRUNCATE ON account_start_session_world_participation_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +CREATE CONSTRAINT TRIGGER account_start_session_world_participation_complete + AFTER INSERT ON account_start_session_world_participations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_complete_guard(); +CREATE TRIGGER account_start_session_world_participation_settlement_validate + BEFORE INSERT ON account_start_session_world_participation_settlements + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_terminal_guard(); +CREATE TRIGGER account_start_session_world_participation_settlements_immutable + BEFORE UPDATE OR DELETE ON account_start_session_world_participation_settlements + FOR EACH ROW EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +CREATE TRIGGER account_start_session_world_settlement_no_truncate + BEFORE TRUNCATE ON account_start_session_world_participation_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_world_participation_no_mutation(); +-- [jooq ignore stop] + +-- Extend, rather than replace with an older migration body, the current V91/V93/V95/V96/V97 +-- assembled source-writer decision point. The source-key lock order already matches all owners. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_draft_authorization_sources s$anchor$; + participation_guard TEXT := $guard$ PERFORM participation.participation_id + FROM account_start_session_world_participations participation + JOIN account_start_session_world_participation_sources source + ON source.participation_id = participation.participation_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_start_session_world_participation_is_settled(participation.participation_id) + ORDER BY participation.participation_id FOR UPDATE OF participation NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'StartSession World participation remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled Account Draft source-writer anchor'; + END IF; + EXECUTE replace(original, anchor, participation_guard || anchor); +END; +$migration$; + +-- Pending World participation also excludes the existing source-change terminal writer. Keep +-- its current V91+ body and insert the check only after that body has locked its sorted sources. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation IN SELECT DISTINCT source.operation_id + FROM account_draft_authorization_changed_scopes changed$anchor$; + participation_guard TEXT := $guard$ IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_start_session_world_participation_sources source + ON source.source_key = changed.source_key + JOIN account_start_session_world_participations participation + ON participation.participation_id = source.participation_id + WHERE changed.change_id = OLD.change_id + AND NOT account_start_session_world_participation_is_settled(participation.participation_id) + ) THEN + PERFORM participation.participation_id + FROM account_draft_authorization_changed_scopes changed + JOIN account_start_session_world_participation_sources source + ON source.source_key = changed.source_key + JOIN account_start_session_world_participations participation + ON participation.participation_id = source.participation_id + WHERE changed.change_id = OLD.change_id + AND NOT account_start_session_world_participation_is_settled(participation.participation_id) + ORDER BY participation.participation_id FOR UPDATE OF participation NOWAIT; + RAISE EXCEPTION 'Pending StartSession World participation excludes source-change completion' + USING ERRCODE = '55P03'; + END IF; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_draft_authorization_source_change_guard()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one current Account source-change terminal anchor'; + END IF; + EXECUTE replace(original, anchor, participation_guard || anchor); +END; +$migration$; + +-- A disclosure dispatch or retry is excluded by every overlapping pending World participation. +-- The repository already takes these source locks before updating the handoff row; NOWAIT keeps +-- raw or incorrectly ordered paths from waiting in an inverse lock order. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED'$anchor$; + participation_guard TEXT := $guard$ IF OLD.status IN ('PREPARED', 'AMBIGUOUS') + AND NEW.status = 'DISPATCH_AUTHORIZED' THEN + PERFORM source_lock.source_key + FROM account_draft_authorization_source_locks source_lock + JOIN ( + SELECT OLD.source_key AS source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id + ) exact_source USING (source_key) + ORDER BY account_publication_authorization_source_sort_key(source_lock.source_key) + FOR UPDATE OF source_lock NOWAIT; + IF EXISTS ( + SELECT 1 FROM account_start_session_world_participations participation + JOIN account_start_session_world_participation_sources source + ON source.participation_id = participation.participation_id + WHERE source.source_key IN ( + SELECT OLD.source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id) + AND NOT account_start_session_world_participation_is_settled(participation.participation_id) + ) THEN + PERFORM participation.participation_id + FROM account_start_session_world_participations participation + JOIN account_start_session_world_participation_sources source + ON source.participation_id = participation.participation_id + WHERE source.source_key IN ( + SELECT OLD.source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id) + AND NOT account_start_session_world_participation_is_settled(participation.participation_id) + ORDER BY participation.participation_id FOR UPDATE OF participation NOWAIT; + RAISE EXCEPTION 'Pending StartSession World participation excludes hosted-terms dispatch' + USING ERRCODE = '55P03'; + END IF; + END IF; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_hosted_terms_disclosure_handoff_guard()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one current hosted-terms dispatch transition anchor'; + END IF; + EXECUTE replace(original, anchor, participation_guard || anchor); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql b/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql index 3a61bd3ef4..2def145a6a 100644 --- a/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql +++ b/services/account-service/src/main/resources/db/migration/V94__selected_publication_inventory_v2.sql @@ -275,7 +275,7 @@ BEGIN OR NOT (entry ?& ARRAY['family', 'rowCount']) OR jsonb_typeof(entry->'rowCount') IS DISTINCT FROM 'number' OR (entry->>'rowCount')::NUMERIC < 0) - OR (SELECT jsonb_agg(entry ORDER BY entry->>'regionTemplateId') FROM + OR (SELECT coalesce(jsonb_agg(entry ORDER BY entry->>'regionTemplateId'), '[]'::JSONB) FROM jsonb_array_elements(model->'regionGeneratorInputs') entry) IS DISTINCT FROM model->'regionGeneratorInputs' OR EXISTS (SELECT 1 FROM jsonb_array_elements(model->'regionGeneratorInputs') entry @@ -284,7 +284,7 @@ BEGIN OR NOT (entry ?& ARRAY['regionTemplateId', 'generatorType', 'generatorParams']) OR entry->>'generatorType' IS DISTINCT FROM '' OR entry->>'generatorParams' IS DISTINCT FROM '') - OR (SELECT jsonb_agg(entry ORDER BY entry->>'bindingTemplateId') FROM + OR (SELECT coalesce(jsonb_agg(entry ORDER BY entry->>'bindingTemplateId'), '[]'::JSONB) FROM jsonb_array_elements(model->'spawnBindingInputs') entry) IS DISTINCT FROM model->'spawnBindingInputs' OR EXISTS (SELECT 1 FROM jsonb_array_elements(model->'spawnBindingInputs') entry diff --git a/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql b/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql index 3564861a6d..b5eb4a4175 100644 --- a/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql +++ b/services/account-service/src/main/resources/db/migration/V97__game_logic_intake_source_read_reservation.sql @@ -115,7 +115,9 @@ BEGIN RAISE EXCEPTION 'Exact original author must have committed settlement before source scope' USING ERRCODE = '23514'; END IF; vector := convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'; - IF jsonb_array_length(vector) < 1 OR jsonb_array_length(vector) <> + IF jsonb_typeof(vector) IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'Incomplete preliminary source participation' USING ERRCODE = '23514'; END IF; + IF jsonb_array_length(vector) < 1 OR jsonb_array_length(vector) IS DISTINCT FROM (SELECT count(*) FROM account_game_logic_intake_source_read_sources WHERE operation_id = NEW.operation_id) THEN RAISE EXCEPTION 'Incomplete preliminary source participation' USING ERRCODE = '23514'; END IF; FOR source_bytes IN SELECT decode(value, 'base64') FROM jsonb_array_elements_text(vector) LOOP diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index a3a6d0602a..1554702736 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; import net.firedevops.firemud.accountservice.service.AccountService; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.test.GatewayTestProperties; @@ -70,6 +71,7 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private LoggingAdminClient loggingAdminClient; + @MockitoBean private StartSessionReservationEvidenceClient startSessionReservationEvidenceClient; @MockitoBean private JavaMailSender mailSender; @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index 418e25ebd4..96787ce4a3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -791,7 +791,7 @@ void freshMigrationStoresExactReplayAndRejectsChangedBaselineDigestOrAllocation( @Test void retainedAccountMigrationPreservesAccountAndAddsIndependentFenceDomain() { - var context = context("116"); + var context = context("80"); UUID account = tx( context, @@ -803,6 +803,7 @@ void retainedAccountMigrationPreservesAccountAndAddsIndependentFenceDomain() { "storage-fixture-only", "PASSWORD") .getAccountUuid()); + migrate(context, "116"); migrate(context, null); var first = pending(context, account); var second = pending(context, account); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java index 6781d57aec..82c3948816 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java @@ -62,7 +62,7 @@ static void stopPostgres() { void dropTestOwnedSchemas() { JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); for (String schema : schemas) { - if (!schema.matches("account_start_session_authorization_[a-f0-9]{32}")) { + if (!schema.matches("account_start_session_[a-f0-9]{32}")) { throw new IllegalStateException("Refusing to dispose an unowned PostgreSQL schema"); } jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); @@ -479,8 +479,7 @@ void expiredReferenceCannotBeConsumedAndSqlGuardsRetainEvidence() { } private Context context() { - String schema = - "account_start_session_authorization_" + UUID.randomUUID().toString().replace("-", ""); + String schema = "account_start_session_" + UUID.randomUUID().toString().replace("-", ""); schemas.add(schema); DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); Flyway.configure() diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java new file mode 100644 index 0000000000..68bc2ae7b5 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java @@ -0,0 +1,175 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL contract proof for the additive Account-owned World participation migration. */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionWorldParticipationPostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void latestMigrationsInstallParticipationGuardsAndPreserveAssembledSourceExclusions() { + String schema = "ss_world_part_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(source, SQLDialect.POSTGRES); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM unnest(ARRAY[" + + "'account_start_session_world_participations', " + + "'account_start_session_world_participation_sources', " + + "'account_start_session_world_participation_settlements']::TEXT[]) " + + "AS names(name) WHERE to_regclass(name) IS NOT NULL"), + "participation table inventory query must return a row") + .get(0, Long.class)) + .isEqualTo(3L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT attidentity FROM pg_attribute " + + "WHERE attrelid = 'account_start_session_world_participations'::regclass " + + "AND attname = 'participation_fence' AND NOT attisdropped"), + "participation fence column must exist") + .get(0, String.class)) + .isEqualTo("a"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM pg_constraint WHERE contype = 'f' AND conrelid IN (" + + "'account_start_session_world_participations'::regclass, " + + "'account_start_session_world_participation_sources'::regclass, " + + "'account_start_session_world_participation_settlements'::regclass)"), + "participation foreign-key query must return a row") + .get(0, Long.class)) + .isEqualTo(6L); + + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal " + + "AND tgname = 'account_start_session_world_participation_complete' " + + "AND tgconstraint <> 0 AND tgdeferrable AND tginitdeferred"), + "deferred participation completion trigger query must return a row") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM pg_trigger WHERE NOT tgisinternal AND tgname IN (" + + "'account_start_session_world_participation_validate', " + + "'account_start_session_world_participation_immutable', " + + "'account_start_session_world_participation_no_truncate', " + + "'account_start_session_world_participation_sources_insert', " + + "'account_start_session_world_participation_sources_immutable', " + + "'account_start_session_world_participation_sources_no_truncate', " + + "'account_start_session_world_participation_complete', " + + "'account_start_session_world_participation_settlement_validate', " + + "'account_start_session_world_participation_settlements_immutable', " + + "'account_start_session_world_settlement_no_truncate')"), + "participation protection trigger query must return a row") + .get(0, Long.class)) + .isEqualTo(10L); + + String holdGuard = functionDefinition(dsl, "account_control_ui_hold_required_sources(text[])"); + assertThat(holdGuard) + .contains( + "account_draft_authorization_sources", + "account_draft_authorization_is_settled(operation_value)", + "account_selected_publication_sources", + "account_selected_publication_authorizations", + "account_game_logic_intake_sources", + "account_game_logic_intake_authorizations", + "account_game_logic_intake_source_read_sources", + "account_game_logic_intake_source_read_is_pending(s.operation_id)", + "account_start_session_world_participations participation", + "account_start_session_world_participation_is_settled(participation.participation_id)", + "FOR UPDATE OF participation NOWAIT"); + assertThat(holdGuard.indexOf("FOR UPDATE NOWAIT")) + .isLessThan(holdGuard.indexOf("FROM account_start_session_world_participations")); + + String sourceChangeGuard = + functionDefinition(dsl, "account_draft_authorization_source_change_guard()"); + assertThat(sourceChangeGuard) + .contains( + "account_draft_authorization_changed_scopes", + "account_draft_authorization_is_settled(operation)", + "account_start_session_world_participation_is_settled(participation.participation_id)", + "Pending StartSession World participation excludes source-change completion"); + + String disclosureGuard = + functionDefinition(dsl, "account_hosted_terms_disclosure_handoff_guard()"); + assertThat(disclosureGuard) + .contains( + "OLD.status IN ('PREPARED', 'AMBIGUOUS')", + "NEW.status = 'DISPATCH_AUTHORIZED'", + "OLD.status = 'DISPATCH_AUTHORIZED' AND NEW.status = 'AMBIGUOUS'", + "account_hosted_terms_disclosure_sources", + "account_start_session_world_participation_is_settled(participation.participation_id)", + "Pending StartSession World participation excludes hosted-terms dispatch"); + + String acquisitionExclusion = + functionDefinition( + dsl, "account_start_session_world_participation_assert_exclusive(text[],jsonb)"); + assertThat(acquisitionExclusion) + .contains( + "change.status = 'WAITING'", + "source_key_value LIKE 'HOSTED_TERMS:%'", + "handoff.source_key = source_key_value", + "handoff_source.source_key = handoff.source_key", + "handoff_source.source_evidence = evidence_value", + "handoff.status IN ('DISPATCH_AUTHORIZED', 'AMBIGUOUS', 'DISCLOSED')"); + assertThat(acquisitionExclusion).doesNotContain("handoff.source_key = ANY(source_keys)"); + + for (String table : + new String[] { + "account_start_session_world_participations", + "account_start_session_world_participation_sources", + "account_start_session_world_participation_settlements" + }) { + assertThatThrownBy(() -> dsl.execute("TRUNCATE " + table)) + .as("TRUNCATE must be rejected for empty append-only table %s", table) + .isInstanceOf(RuntimeException.class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM " + table), + "post-TRUNCATE table state query must return a row") + .get(0, Long.class)) + .as("rejected TRUNCATE must leave the empty table unchanged") + .isZero(); + } + } + + private static String functionDefinition(DSLContext dsl, String signature) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT pg_get_functiondef(?::regprocedure)", signature), + "function definition query must return a row") + .get(0, String.class); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java new file mode 100644 index 0000000000..c70f9c2bf8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java @@ -0,0 +1,287 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic unit proof for Account's World-participation exclusion seam. */ +class DraftAuthorizationFenceWorldParticipationTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void worldParticipationAdmissionRequiresWritableReadCommittedOwnerTransaction() throws Exception { + Fixture fixture = new Fixture(false); + + assertThatThrownBy( + () -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) + .isInstanceOf(IllegalStateException.class); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy( + () -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) + .isInstanceOf(IllegalStateException.class); + + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + fixture.begin(); + fixture.autoCommit = true; + assertThatThrownBy( + () -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) + .isInstanceOf(IllegalStateException.class); + + fixture.autoCommit = false; + fixture.isolation = Connection.TRANSACTION_REPEATABLE_READ; + assertThatThrownBy( + () -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) + .isInstanceOf(IllegalStateException.class); + + assertThat(fixture.lockedKeys).isEmpty(); + } + + @Test + void pendingWorldParticipationBlocksDisclosureAdmissionAndChecksSortedExactKeys() + throws Exception { + Fixture fixture = new Fixture(true); + fixture.begin(); + SourceEvidence first = source("a-first"); + SourceEvidence second = source("z-second"); + fixture.pendingWorldKey = second.key(); + + assertThatThrownBy( + () -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(second, first))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("World participation remains pending"); + + assertThat(fixture.lockedKeys).containsExactly(first.key(), second.key()); + assertThat(fixture.worldKeys).containsExactly(first.key(), second.key()); + assertThat(fixture.eventOrder) + .containsExactly( + "lock:" + first.key(), + "lock-row:" + first.key(), + "lock:" + second.key(), + "lock-row:" + second.key(), + "world:" + first.key(), + "world:" + second.key()); + assertThat(fixture.worldSql.getFirst()) + .contains("JOIN account_start_session_world_participations") + .contains("NOT account_start_session_world_participation_is_settled"); + } + + @Test + void disclosurePreparationRejectsPendingWorldParticipationWithoutOwnerOperationReads() + throws Exception { + Fixture fixture = new Fixture(true); + fixture.begin(); + + assertThatThrownBy( + () -> fixture.repository.requireDisclosurePreparation(List.of(fixture.source))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("World participation remains pending"); + + assertThat(fixture.worldKeys).containsExactly(fixture.source.key()); + assertThat(fixture.fetchedSql) + .anyMatch(statement -> statement.contains("account_draft_authorization_source_changes")) + .anyMatch(statement -> statement.contains("account_selected_publication_sources")) + .anyMatch(statement -> statement.contains("account_game_logic_intake_sources")); + assertThat(fixture.fetchedSql) + .noneMatch( + statement -> + statement.contains("account_draft_authorization_fences") + || statement.contains( + "SELECT operation_id FROM account_draft_authorization_sources")); + assertThat(fixture.sql).noneMatch(statement -> statement.contains("UPDATE ")); + } + + @Test + void pendingWorldParticipationBlocksSourceMutationAndAbortWhileSettledKeepsPriorAdmission() + throws Exception { + Fixture pending = new Fixture(true); + pending.begin(); + SourceChange pendingChange = sourceChange(pending.source); + pending.installWaitingChange(pendingChange); + + assertThat(pending.repository.sourceMutationPermitted(pendingChange)).isFalse(); + assertThat(pending.repository.sourceAbortPermitted(pendingChange)).isFalse(); + assertThat(pending.sql).noneMatch(statement -> statement.contains("UPDATE ")); + + Fixture settled = new Fixture(false); + settled.begin(); + SourceChange settledChange = sourceChange(settled.source); + settled.installWaitingChange(settledChange); + + assertThat(settled.repository.sourceMutationPermitted(settledChange)).isTrue(); + assertThat(settled.repository.sourceAbortPermitted(settledChange)).isTrue(); + assertThat(settled.worldKeys).containsExactly(settled.source.key(), settled.source.key()); + } + + @Test + void disclosureSourceLockAcceptsCanonicalKeysThrough2048BytesWithoutAliasing() throws Exception { + Fixture fixture = new Fixture(false); + fixture.begin(); + SourceEvidence boundary = source("x".repeat(2035)); + assertThat(boundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(2048); + + fixture.repository.lockDisclosureSources(List.of(boundary)); + + assertThat(fixture.lockedKeys).containsExactly(boundary.key()); + assertThatThrownBy(() -> source("x".repeat(2036))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("2048 UTF-8 bytes"); + } + + private static SourceChange sourceChange(SourceEvidence source) { + return new SourceChange(UUID.randomUUID(), List.of(source), new byte[] {1, 2, 3}); + } + + private static SourceEvidence source(String scope) { + return new SourceEvidence( + SourceKind.HOSTED_TERMS, scope, null, "1", null, null, new byte[] {4, 5, 6}); + } + + private static final class Fixture { + private final DSLContext dsl = mock(DSLContext.class); + private final Connection connection = mock(Connection.class); + private final SourceEvidence source = source("world-participation-test"); + private final DraftAuthorizationFenceRepository repository = + new DraftAuthorizationFenceRepository(dsl); + private final List lockedKeys = new ArrayList<>(); + private final List worldKeys = new ArrayList<>(); + private final List worldSql = new ArrayList<>(); + private final List eventOrder = new ArrayList<>(); + private final List sql = new ArrayList<>(); + private final List fetchedSql = new ArrayList<>(); + private final Result emptyRows = rows(true); + private final Result matchingRows = rows(false); + private final Record lockRow = mock(Record.class); + private final Record changeRow = mock(Record.class); + private final boolean worldPending; + private boolean autoCommit; + private String pendingWorldKey; + private int isolation = Connection.TRANSACTION_READ_COMMITTED; + private Result changedRows = emptyRows; + + private Fixture(boolean worldPending) throws Exception { + this.worldPending = worldPending; + doAnswer(invocation -> autoCommit).when(connection).getAutoCommit(); + doAnswer(invocation -> false).when(connection).isReadOnly(); + doAnswer(invocation -> isolation).when(connection).getTransactionIsolation(); + doAnswer( + invocation -> { + invocation.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + doAnswer( + invocation -> { + String statement = invocation.getArgument(0); + sql.add(statement); + if (statement.startsWith("INSERT INTO account_draft_authorization_source_locks")) { + String sourceKey = invocation.getArgument(1, String.class); + lockedKeys.add(sourceKey); + eventOrder.add("lock:" + sourceKey); + } + return 1; + }) + .when(dsl) + .execute(anyString(), any(Object[].class)); + doAnswer( + invocation -> { + String statement = invocation.getArgument(0); + fetchedSql.add(statement); + if (statement.contains("account_start_session_world_participation_sources")) { + String sourceKey = invocation.getArgument(1, String.class); + worldKeys.add(sourceKey); + worldSql.add(statement); + eventOrder.add("world:" + sourceKey); + return worldPending + && (pendingWorldKey == null || pendingWorldKey.equals(sourceKey)) + ? matchingRows + : emptyRows; + } + if (statement.contains("account_draft_authorization_changed_scopes")) { + return changedRows; + } + return emptyRows; + }) + .when(dsl) + .fetch(anyString(), any(Object[].class)); + doAnswer( + invocation -> { + String statement = invocation.getArgument(0); + fetchedSql.add(statement); + if (statement.contains("account_draft_authorization_source_changes")) { + return changeRow; + } + if (statement.contains("account_draft_authorization_source_locks")) { + String sourceKey = invocation.getArgument(1, String.class); + eventOrder.add("lock-row:" + sourceKey); + } + return lockRow; + }) + .when(dsl) + .fetchOne(anyString(), any(Object[].class)); + } + + private void begin() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + private void installWaitingChange(SourceChange change) { + doReturn(change.canonicalBytes()).when(changeRow).get("binding", byte[].class); + doReturn("WAITING").when(changeRow).get("status", String.class); + changedRows = rowsWithSource(change.sources().getFirst().key()); + } + } + + @SuppressWarnings("unchecked") + private static Result rows(boolean empty) { + Result result = mock(Result.class); + doReturn(empty).when(result).isEmpty(); + doReturn(List.of()).when(result).getValues("operation_id", UUID.class); + doReturn(List.of()).when(result).getValues("source_key", String.class); + return result; + } + + @SuppressWarnings("unchecked") + private static Result rowsWithSource(String sourceKey) { + Result result = mock(Result.class); + doReturn(List.of(sourceKey)).when(result).getValues("source_key", String.class); + doReturn(false).when(result).isEmpty(); + return result; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffWorldParticipationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffWorldParticipationTest.java new file mode 100644 index 0000000000..c8dbfb5953 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffWorldParticipationTest.java @@ -0,0 +1,245 @@ +package net.firedevops.firemud.accountservice.hostedterms; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoff.Kind; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsDisclosureHandoffRepository.Status; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic repository-unit proof for the disclosure/World-participation seam. */ +class HostedTermsDisclosureHandoffWorldParticipationTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void preparationDeniesPendingWorldParticipationBeforeWritingDisclosureJournal() throws Exception { + Fixture fixture = new Fixture(Status.PREPARED, false); + fixture.begin(); + doAnswer( + invocation -> { + throw new IllegalStateException( + "Original StartSession World participation remains pending"); + }) + .when(fixture.fenceRepository) + .requireDisclosurePreparation(fixture.handoff.sources()); + + assertThatThrownBy(() -> fixture.repository.prepare(fixture.handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("World participation remains pending"); + + verify(fixture.fenceRepository).lockDisclosureSources(fixture.handoff.sources()); + verify(fixture.fenceRepository).requireDisclosurePreparation(fixture.handoff.sources()); + assertThat(fixture.executedSql).isEmpty(); + } + + @Test + void dispatchDenialChecksWorldBeforeJournalReadAndDoesNotAdvanceAmbiguousRetry() + throws Exception { + Fixture fixture = new Fixture(Status.AMBIGUOUS, true); + fixture.begin(); + doAnswer( + invocation -> { + throw new IllegalStateException( + "Original StartSession World participation remains pending"); + }) + .when(fixture.fenceRepository) + .requireWorldParticipationDisclosureAdmission(fixture.handoff.sources()); + + assertThatThrownBy(() -> fixture.repository.authorizeDispatch(fixture.handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("World participation remains pending"); + + verify(fixture.fenceRepository) + .requireWorldParticipationDisclosureAdmission(fixture.handoff.sources()); + verify(fixture.fenceRepository, never()) + .requireDisclosurePreparation(fixture.handoff.sources()); + assertThat(fixture.journalReads).isZero(); + assertThat(fixture.executedSql).isEmpty(); + } + + @Test + void settledWorldParticipationKeepsAmbiguousRetryAndSourceLockOrdering() throws Exception { + Fixture fixture = new Fixture(Status.AMBIGUOUS, true); + fixture.begin(); + + var permit = fixture.repository.authorizeDispatch(fixture.handoff); + + assertThat(permit.newlyAuthorized()).isTrue(); + assertThat(permit.snapshot().status()).isEqualTo(Status.DISPATCH_AUTHORIZED); + assertThat(permit.snapshot().dispatchAttempts()).isEqualTo(3); + var order = inOrder(fixture.fenceRepository, fixture.dsl); + order + .verify(fixture.fenceRepository) + .requireWorldParticipationDisclosureAdmission(fixture.handoff.sources()); + order.verify(fixture.dsl, times(4)).fetch(anyString(), any(Object[].class)); + verify(fixture.fenceRepository, never()) + .requireDisclosurePreparation(fixture.handoff.sources()); + assertThat(fixture.executedSql) + .containsExactly( + "UPDATE account_hosted_terms_disclosure_handoffs" + + " SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = dispatch_attempts + 1 " + + "WHERE handoff_id = ? AND status = ?"); + } + + private static final class Fixture { + private final DSLContext dsl = mock(DSLContext.class); + private final Connection connection = mock(Connection.class); + private final DraftAuthorizationFenceRepository fenceRepository = + mock(DraftAuthorizationFenceRepository.class); + private final HostedTermsDisclosureHandoff handoff = handoff(); + private final HostedTermsDisclosureHandoffRepository repository = + new HostedTermsDisclosureHandoffRepository(dsl, fenceRepository); + private final List executedSql = new ArrayList<>(); + private final Record handoffRow; + private final Record sourceRow; + private final Result handoffRows; + private final Result sourceRows; + private final Result noRows = result(List.of()); + private int journalReads; + + private Fixture(Status initialStatus, boolean includeHandoff) throws Exception { + Map handoffFields = new HashMap<>(); + handoffFields.put("handoff_id", handoff.handoffId()); + handoffFields.put("request_id", handoff.requestId()); + handoffFields.put("kind", handoff.kind().name()); + handoffFields.put("source_key", handoff.sourceKey()); + handoffFields.put("predecessor_digest", handoff.predecessorDigest()); + handoffFields.put("candidate_digest", handoff.candidateDigest()); + handoffFields.put( + "effective_at", OffsetDateTime.ofInstant(handoff.effectiveAt(), ZoneOffset.UTC)); + handoffFields.put("binding", handoff.canonicalBytes()); + handoffFields.put("binding_digest", HostedTermsEncoding.digest(handoff.canonicalBytes())); + handoffFields.put("status", initialStatus.name()); + handoffFields.put("dispatch_attempts", 2); + handoffFields.put("result_outcome", null); + handoffFields.put("result_payload", null); + handoffFields.put("result_digest", null); + handoffFields.put("result_recorded_at", null); + handoffFields.put("created_at", OffsetDateTime.parse("2026-10-08T00:00:00Z")); + handoffRow = record(handoffFields); + + SourceEvidence source = handoff.sources().getFirst(); + Map sourceFields = new HashMap<>(); + sourceFields.put("source_key", source.key()); + sourceFields.put("source_evidence", source.canonicalBytes()); + sourceFields.put( + "source_evidence_digest", HostedTermsEncoding.digest(source.canonicalBytes())); + sourceRow = record(sourceFields); + handoffRows = result(includeHandoff ? List.of(handoffRow) : List.of()); + sourceRows = result(List.of(sourceRow)); + + doReturn(false).when(connection).getAutoCommit(); + doReturn(false).when(connection).isReadOnly(); + doReturn(Connection.TRANSACTION_READ_COMMITTED).when(connection).getTransactionIsolation(); + doAnswer( + invocation -> { + invocation.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + doAnswer( + invocation -> { + String statement = invocation.getArgument(0); + executedSql.add(statement); + if (statement.contains("dispatch_attempts = dispatch_attempts + 1")) { + handoffFields.put("status", Status.DISPATCH_AUTHORIZED.name()); + handoffFields.put("dispatch_attempts", 3); + } + return 1; + }) + .when(dsl) + .execute(anyString(), any(Object[].class)); + doAnswer( + invocation -> { + String statement = invocation.getArgument(0); + if (statement.contains("account_hosted_terms_disclosure_handoffs")) { + journalReads++; + return handoffRows; + } + if (statement.contains("account_hosted_terms_disclosure_sources")) { + return sourceRows; + } + return noRows; + }) + .when(dsl) + .fetch(anyString(), any(Object[].class)); + } + + private void begin() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + } + + private static HostedTermsDisclosureHandoff handoff() { + SourceEvidence source = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + UUID.randomUUID().toString(), + null, + "7", + null, + null, + new byte[] {1, 2, 3}); + return new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + source.key(), + HostedTermsEncoding.digest(new byte[] {4}), + HostedTermsEncoding.digest(new byte[] {5}), + Instant.parse("2026-10-08T00:00:00.123456Z"), + List.of(source), + "test-only-authority-evidence".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + @SuppressWarnings("unchecked") + private static Record record(Map fields) { + Record record = mock(Record.class); + doAnswer(invocation -> fields.get(invocation.getArgument(0))) + .when(record) + .get(anyString(), any(Class.class)); + return record; + } + + @SuppressWarnings("unchecked") + private static Result result(List records) { + Result result = mock(Result.class); + doReturn(records.size()).when(result).size(); + doReturn(records.isEmpty()).when(result).isEmpty(); + doReturn(records.isEmpty() ? null : records.getFirst()).when(result).getFirst(); + doAnswer(invocation -> records.stream()).when(result).stream(); + return result; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java new file mode 100644 index 0000000000..b0df423cd8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java @@ -0,0 +1,196 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.jooq.impl.DSL.field; +import static org.jooq.impl.DSL.name; + +import java.lang.reflect.InvocationTargetException; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.SQLDataType; +import org.junit.jupiter.api.Test; + +class AccountStartSessionAuthorityCaptureRepositoryTest { + private static final String REQUEST_ID = "capture-repository-unit"; + private static final String CAPTURED_AT = "2026-10-10T12:34:56.789Z"; + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID CONTROL_UI_OPERATION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID CONTROL_UI_TOKEN_JTI = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + + private static final Field CONTROL_PLANE_REQUEST_ID = + field(name("control_plane_request_id"), SQLDataType.VARCHAR); + private static final Field ACCOUNT_UUID = field(name("account_uuid"), SQLDataType.UUID); + private static final Field TENANT_UUID = field(name("tenant_uuid"), SQLDataType.UUID); + private static final Field TARGET_OWNER = + field(name("target_owner"), SQLDataType.VARCHAR); + private static final Field LOGGING_WORKLOAD_URI = + field(name("logging_workload_uri"), SQLDataType.VARCHAR); + private static final Field RESERVATION_OWNER_UUID = + field(name("reservation_owner_id"), SQLDataType.UUID); + private static final Field RESERVATION_CLAIM_FENCE = + field(name("reservation_claim_fence"), SQLDataType.BIGINT); + private static final Field MUTATION_DIGEST = + field(name("mutation_digest"), SQLDataType.VARCHAR); + private static final Field CONTROL_UI_OPERATION_UUID = + field(name("control_ui_operation_id"), SQLDataType.UUID); + private static final Field CONTROL_UI_TOKEN_UUID = + field(name("control_ui_token_jti"), SQLDataType.UUID); + private static final Field CONTROL_UI_TOKEN_HASH = + field(name("control_ui_token_hash"), SQLDataType.VARCHAR); + private static final Field SIGNER_RECEIPT_SHA256 = + field(name("control_ui_signer_receipt_sha256"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_FENCE = + field(name("issuance_fence"), SQLDataType.BIGINT); + private static final Field ISSUANCE_FENCE_SOURCE_VERSION = + field(name("issuance_fence_source_version"), SQLDataType.BIGINT); + private static final Field CAPTURED_AT_FIELD = + field(name("captured_at"), SQLDataType.VARCHAR); + private static final Field SNAPSHOT_SHA256 = + field(name("snapshot_sha256"), SQLDataType.VARCHAR); + private static final Field SNAPSHOT_BYTES = + field(name("canonical_snapshot_bytes"), SQLDataType.VARBINARY); + private static final Field SOURCE_VERSION = + field(name("source_version"), SQLDataType.BIGINT); + private static final Field SOURCE_FENCE = field(name("source_fence"), SQLDataType.BIGINT); + private static final Field LINEARIZATION = + field(name("linearization"), SQLDataType.VARCHAR); + private static final Field CANONICAL_SHA256 = + field(name("canonical_sha256"), SQLDataType.VARCHAR); + private static final Field CANONICAL_BYTES = + field(name("canonical_capture_bytes"), SQLDataType.VARBINARY); + + @Test + void decodesCanonicalSnapshotUuidsFromTypedJooqUuidColumns() { + CaptureFixture fixture = fixture(ACCOUNT_ID.toString()); + + assertThat(fixture.row().get(ACCOUNT_UUID, UUID.class)).isEqualTo(ACCOUNT_ID); + assertThat(fixture.row().get(TENANT_UUID, UUID.class)).isEqualTo(TENANT_ID); + assertThat(decode(fixture.row()).sameStoredValue(fixture.capture())).isTrue(); + } + + @Test + void rejectsWrongMissingAndMalformedSnapshotUuidEvidence() { + assertUnavailable(fixture("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa").row()); + assertUnavailable(fixture("not-a-uuid").row()); + assertUnavailable(fixture(null).row()); + + CaptureFixture missingStoredUuid = fixture(ACCOUNT_ID.toString()); + missingStoredUuid.row().setValue(ACCOUNT_UUID, (UUID) null); + assertUnavailable(missingStoredUuid.row()); + } + + private static CaptureFixture fixture(String snapshotAccountId) { + Map snapshot = new LinkedHashMap<>(); + snapshot.put("schema", "account-start-session-authority-snapshot/v1"); + snapshot.put( + "preAuthorizationTuple", + java.util.Base64.getEncoder() + .encodeToString("canonical tuple".getBytes(StandardCharsets.UTF_8))); + snapshot.put("mutationDigest", "a".repeat(64)); + if (snapshotAccountId != null) snapshot.put("accountId", snapshotAccountId); + snapshot.put("tenantId", TENANT_ID.toString()); + snapshot.put("targetOwner", "game-session-service"); + snapshot.put("loggingWorkloadUri", "spiffe://firemud/ns/gameplay/sa/logging-admin-service"); + snapshot.put("reservationOwnerId", RESERVATION_OWNER_ID.toString()); + snapshot.put("reservationClaimFence", "7"); + snapshot.put("controlUiOperationId", CONTROL_UI_OPERATION_ID.toString()); + snapshot.put("controlUiTokenJti", CONTROL_UI_TOKEN_JTI.toString()); + snapshot.put("controlUiTokenHash", "b".repeat(64)); + snapshot.put("controlUiSignerReceiptSha256", "c".repeat(64)); + snapshot.put("issuanceFence", "9"); + snapshot.put("issuanceFenceSourceVersion", "10"); + + byte[] snapshotBytes = AccountControlUiAuthority.canonical(snapshot); + AccountStartSessionAuthorityCapture capture = + AccountStartSessionAuthorityCapture.create( + REQUEST_ID, 11L, 13L, "17", CAPTURED_AT, snapshotBytes); + + Record row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + CONTROL_PLANE_REQUEST_ID, + ACCOUNT_UUID, + TENANT_UUID, + TARGET_OWNER, + LOGGING_WORKLOAD_URI, + RESERVATION_OWNER_UUID, + RESERVATION_CLAIM_FENCE, + MUTATION_DIGEST, + CONTROL_UI_OPERATION_UUID, + CONTROL_UI_TOKEN_UUID, + CONTROL_UI_TOKEN_HASH, + SIGNER_RECEIPT_SHA256, + ISSUANCE_FENCE, + ISSUANCE_FENCE_SOURCE_VERSION, + CAPTURED_AT_FIELD, + SNAPSHOT_SHA256, + SNAPSHOT_BYTES, + SOURCE_VERSION, + SOURCE_FENCE, + LINEARIZATION, + CANONICAL_SHA256, + CANONICAL_BYTES); + row.setValue(CONTROL_PLANE_REQUEST_ID, REQUEST_ID); + row.setValue(ACCOUNT_UUID, ACCOUNT_ID); + row.setValue(TENANT_UUID, TENANT_ID); + row.setValue(TARGET_OWNER, "game-session-service"); + row.setValue(LOGGING_WORKLOAD_URI, "spiffe://firemud/ns/gameplay/sa/logging-admin-service"); + row.setValue(RESERVATION_OWNER_UUID, RESERVATION_OWNER_ID); + row.setValue(RESERVATION_CLAIM_FENCE, 7L); + row.setValue(MUTATION_DIGEST, "a".repeat(64)); + row.setValue(CONTROL_UI_OPERATION_UUID, CONTROL_UI_OPERATION_ID); + row.setValue(CONTROL_UI_TOKEN_UUID, CONTROL_UI_TOKEN_JTI); + row.setValue(CONTROL_UI_TOKEN_HASH, "b".repeat(64)); + row.setValue(SIGNER_RECEIPT_SHA256, "c".repeat(64)); + row.setValue(ISSUANCE_FENCE, 9L); + row.setValue(ISSUANCE_FENCE_SOURCE_VERSION, 10L); + row.setValue(CAPTURED_AT_FIELD, CAPTURED_AT); + row.setValue(SNAPSHOT_SHA256, capture.snapshotSha256()); + row.setValue(SNAPSHOT_BYTES, capture.snapshotBytes()); + row.setValue(SOURCE_VERSION, 11L); + row.setValue(SOURCE_FENCE, 13L); + row.setValue(LINEARIZATION, "17"); + row.setValue(CANONICAL_SHA256, capture.canonicalSha256()); + row.setValue(CANONICAL_BYTES, capture.canonicalBytes()); + return new CaptureFixture(row, capture); + } + + private static AccountStartSessionAuthorityCapture decode(Record row) { + try { + var method = + AccountStartSessionAuthorityCaptureRepository.class.getDeclaredMethod( + "decode", Record.class); + method.setAccessible(true); + return (AccountStartSessionAuthorityCapture) + method.invoke( + new AccountStartSessionAuthorityCaptureRepository(DSL.using(SQLDialect.POSTGRES)), + row); + } catch (InvocationTargetException failure) { + if (failure.getCause() instanceof RuntimeException runtime) throw runtime; + throw new AssertionError("Unexpected capture decode failure", failure.getCause()); + } catch (ReflectiveOperationException failure) { + throw new AssertionError("Could not invoke capture decoder", failure); + } + } + + private static void assertUnavailable(Record row) { + assertThatThrownBy(() -> decode(row)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account StartSession source capture is unavailable"); + } + + private record CaptureFixture(Record row, AccountStartSessionAuthorityCapture capture) {} +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java index 4edf985984..7b060396cb 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AuthTokenInterceptor.java @@ -33,7 +33,19 @@ public AuthTokenInterceptor(JwtUtil jwtUtil, Set unauthenticatedMethods) public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { if (unauthenticatedMethods.contains(call.getMethodDescriptor().getFullMethodName())) { - return next.startCall(call, headers); + ServerCall clearingCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void close(Status status, Metadata trailers) { + runWithClearedSessionContext(() -> super.close(status, trailers)); + } + }; + SessionContext.clear(); + try { + return withClearedSessionContextCallbacks(next.startCall(clearingCall, headers)); + } finally { + SessionContext.clear(); + } } String authHeader = headers.get(AUTH_HEADER); if (authHeader == null || !authHeader.startsWith("Bearer ")) { @@ -82,4 +94,43 @@ public void onCancel() { return new ServerCall.Listener<>() {}; } } + + private static ServerCall.Listener withClearedSessionContextCallbacks( + ServerCall.Listener listener) { + return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>(listener) { + @Override + public void onMessage(ReqT message) { + runWithClearedSessionContext(() -> super.onMessage(message)); + } + + @Override + public void onHalfClose() { + runWithClearedSessionContext(super::onHalfClose); + } + + @Override + public void onCancel() { + runWithClearedSessionContext(super::onCancel); + } + + @Override + public void onComplete() { + runWithClearedSessionContext(super::onComplete); + } + + @Override + public void onReady() { + runWithClearedSessionContext(super::onReady); + } + }; + } + + private static void runWithClearedSessionContext(Runnable callback) { + SessionContext.clear(); + try { + callback.run(); + } finally { + SessionContext.clear(); + } + } } diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java index dca3029a7b..be5286ebf7 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java @@ -125,12 +125,14 @@ void configuredPublicMethodsBypassBearerRequirement() { ServerCallHandler next = Mockito.mock(ServerCallHandler.class); MethodDescriptor methodDescriptor = unaryMethod("demo.Service/Ping"); Mockito.when(call.getMethodDescriptor()).thenReturn(methodDescriptor); - Mockito.when(next.startCall(Mockito.eq(call), Mockito.any(Metadata.class))) + Mockito.when( + next.startCall(Mockito.any(ServerCall.class), Mockito.any(Metadata.class))) .thenReturn(new ServerCall.Listener<>() {}); interceptor.interceptCall(call, new Metadata(), next); - Mockito.verify(next).startCall(Mockito.eq(call), Mockito.any(Metadata.class)); + Mockito.verify(next) + .startCall(Mockito.any(ServerCall.class), Mockito.any(Metadata.class)); }); } diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java index 7c41c48784..d21d5f456d 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java @@ -1,15 +1,21 @@ package unit.net.firedevops.firemud.common.security; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.Empty; +import io.grpc.Context; +import io.grpc.Contexts; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.ServerCall; import io.grpc.ServerCall.Listener; import io.grpc.ServerCallHandler; import io.grpc.Status; +import java.util.ArrayList; +import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.security.AuthTokenInterceptor; @@ -67,6 +73,205 @@ void rejectsMalformedJwtClaims() { assertThat(SessionContext.getScopedRolesMap()).isEmpty(); } + @Test + void clearsStaleThreadLocalBeforeExemptDispatchAndEveryListenerCallback() { + AuthTokenInterceptor interceptor = + new AuthTokenInterceptor(jwtUtil, Set.of(METHOD.getFullMethodName())); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + List callerContextObserved = new ArrayList<>(); + ServerCallHandler next = + new ServerCallHandler<>() { + @Override + public Listener startCall(ServerCall serverCall, Metadata headers) { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + return new Listener<>() { + @Override + public void onMessage(Empty message) { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + } + + @Override + public void onHalfClose() { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + } + + @Override + public void onReady() { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + } + + @Override + public void onComplete() { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + } + + @Override + public void onCancel() { + callerContextObserved.add( + AuthTokenInterceptorTest.this.recordCallerContextAndSeedThreadLocal()); + } + }; + } + }; + + Mockito.when(call.getMethodDescriptor()).thenReturn(METHOD); + seedStaleCallerContext(); + + Listener listener = interceptor.interceptCall(call, new Metadata(), next); + + assertThat(callerContextObserved).containsExactly(false); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + listener.onMessage(Empty.getDefaultInstance()); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + listener.onHalfClose(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + listener.onReady(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + listener.onComplete(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + Listener cancelListener = interceptor.interceptCall(call, new Metadata(), next); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + cancelListener.onCancel(); + + assertThat(callerContextObserved) + .containsExactly(false, false, false, false, false, false, false); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + assertThat(SessionContext.getAccountId()).isNull(); + } + + @Test + void preservesAuthenticatedGrpcCallerAndPeerContextForExemptReceiverGuard() { + AuthTokenInterceptor jwtInterceptor = new AuthTokenInterceptor(jwtUtil); + AuthTokenInterceptor exemptInterceptor = + new AuthTokenInterceptor(jwtUtil, Set.of(METHOD.getFullMethodName())); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + // A context sentinel verifies ThreadLocal cleanup does not replace the enclosing gRPC context. + Context.Key peerContextKey = Context.key("test-peer-context"); + String peerContextValue = "account-peer-context-preserved"; + AtomicReference accountObservedAtStart = new AtomicReference<>(); + AtomicReference peerObservedAtStart = new AtomicReference<>(); + AtomicBoolean callerContextObservedAtStart = new AtomicBoolean(false); + AtomicReference accountObservedInCallback = new AtomicReference<>(); + AtomicReference peerObservedInCallback = new AtomicReference<>(); + AtomicBoolean callerContextObservedInCallback = new AtomicBoolean(false); + ServerCallHandler receiver = + new ServerCallHandler<>() { + @Override + public Listener startCall(ServerCall serverCall, Metadata headers) { + accountObservedAtStart.set(SessionContext.getAccountId()); + peerObservedAtStart.set(peerContextKey.get()); + callerContextObservedAtStart.set(SessionContext.hasAuthenticatedCallerContext()); + return new Listener<>() { + @Override + public void onHalfClose() { + accountObservedInCallback.set(SessionContext.getAccountId()); + peerObservedInCallback.set(peerContextKey.get()); + callerContextObservedInCallback.set(SessionContext.hasAuthenticatedCallerContext()); + } + }; + } + }; + Mockito.when(call.getMethodDescriptor()).thenReturn(METHOD); + + Metadata headers = new Metadata(); + String token = + jwtUtil.generateToken( + "trusted-account", + Map.of( + "accountId", "42", + "globalRoles", List.of(), + "scopedRoles", Map.of())); + headers.put(AUTH_HEADER, "Bearer " + token); + seedStaleCallerContext(); + Context peerContext = Context.current().withValue(peerContextKey, peerContextValue); + Listener listener = + Contexts.interceptCall( + peerContext, + call, + headers, + (peerCall, peerHeaders) -> + jwtInterceptor.interceptCall( + peerCall, + peerHeaders, + (authenticatedCall, authenticatedHeaders) -> + exemptInterceptor.interceptCall( + authenticatedCall, authenticatedHeaders, receiver))); + + assertThat(accountObservedAtStart).hasValue("42"); + assertThat(callerContextObservedAtStart).isTrue(); + assertThat(peerObservedAtStart).hasValue(peerContextValue); + listener.onHalfClose(); + + // This is the same caller-context predicate used by passive receivers, so the legitimate JWT + // principal remains visible and would still be denied there despite the method exemption. + assertThat(accountObservedInCallback).hasValue("42"); + assertThat(callerContextObservedInCallback).isTrue(); + assertThat(peerObservedInCallback).hasValue(peerContextValue); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + } + + @Test + void clearsSessionContextWhenExemptCallClosesOrStartCallFails() { + AuthTokenInterceptor interceptor = + new AuthTokenInterceptor(jwtUtil, Set.of(METHOD.getFullMethodName())); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + AtomicReference> forwardedCall = new AtomicReference<>(); + AtomicBoolean callerContextObservedDuringClose = new AtomicBoolean(true); + ServerCallHandler next = + new ServerCallHandler<>() { + @Override + public Listener startCall(ServerCall serverCall, Metadata headers) { + forwardedCall.set(serverCall); + return new Listener<>() {}; + } + }; + Mockito.when(call.getMethodDescriptor()).thenReturn(METHOD); + Mockito.doAnswer( + invocation -> { + callerContextObservedDuringClose.set(SessionContext.hasAuthenticatedCallerContext()); + seedStaleCallerContext(); + return null; + }) + .when(call) + .close(Mockito.any(Status.class), Mockito.any(Metadata.class)); + + interceptor.interceptCall(call, new Metadata(), next); + seedStaleCallerContext(); + forwardedCall.get().close(Status.OK, new Metadata()); + + assertThat(callerContextObservedDuringClose).isFalse(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + + seedStaleCallerContext(); + assertThatThrownBy( + () -> + interceptor.interceptCall( + call, + new Metadata(), + (serverCall, headers) -> { + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + throw new IllegalStateException("failed startCall"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("failed startCall"); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + } + @Test void appliesSessionContextDuringCallbacksAndClearsAfterCompletion() { AuthTokenInterceptor interceptor = new AuthTokenInterceptor(jwtUtil); @@ -201,6 +406,16 @@ private void seedThreadLocalInternalServiceState() { "", java.util.List.of(), Map.of(), true, "seeded-service", "seeded-instance"); } + private void seedStaleCallerContext() { + SessionContext.setContext("stale-account", List.of("platformAdmin"), Map.of()); + } + + private boolean recordCallerContextAndSeedThreadLocal() { + boolean callerContextPresent = SessionContext.hasAuthenticatedCallerContext(); + seedStaleCallerContext(); + return callerContextPresent; + } + private Metadata internalServiceHeaders() { Metadata headers = new Metadata(); String token = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java index 536fb0bd68..cd816044a3 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.worldmanagement.tenant; import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Result; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -89,6 +91,41 @@ public WorldCanonicalInstancePreparationRepository.ExecutionLookup recoverExact( return repository.readExactExecution(originalIdentity); } + /** + * Reads the exact durable COMMITTED or ABORTED World terminal through authenticated recovery. + * Missing and PENDING operations remain unresolved and therefore have no terminal receipt. + */ + public Optional recoverExactTerminal( + WorldCanonicalInstanceExecutionIdentity originalIdentity) { + return recoverExact(originalIdentity) + .operation() + .filter( + operation -> + operation.state() + == WorldCanonicalInstancePreparationRepository.ExecutionState.COMMITTED + || operation.state() + == WorldCanonicalInstancePreparationRepository.ExecutionState.ABORTED) + .map( + operation -> + new WorldStartSessionExecutionTerminal( + originalIdentity.originalPostAuthorizationTuple(), + originalIdentity.accountWorldParticipationId(), + originalIdentity.accountWorldParticipationFence(), + originalIdentity.gameSessionOwnerAttemptId(), + originalIdentity.gameSessionOwnerFence(), + originalIdentity.targetNamespace(), + originalIdentity.canonicalTenantId(), + originalIdentity.controlPlaneRequestId(), + originalIdentity.canonicalGameInstanceId(), + originalIdentity.preparationInputDigest(), + originalIdentity.preparationInputJson(), + operation.worldExecutionFence(), + operation.state() + == WorldCanonicalInstancePreparationRepository.ExecutionState.COMMITTED + ? WorldStartSessionExecutionTerminal.Outcome.COMMITTED + : WorldStartSessionExecutionTerminal.Outcome.ABORTED)); + } + private static HeldCommitAuthority denyByDefault(Input input) { throw new PreparationDeniedException( "Canonical World preparation has no authenticated source/release terminal verifier"); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index 021c67ea44..018b66f50a 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -2,8 +2,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.util.JsonFormat; @@ -84,6 +82,7 @@ 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; @@ -172,19 +171,22 @@ void createRepositories() { } @Test - void changedReleaseCommitFailsJavaAndDatabaseBeforeAllocation() { + void changedReleaseCommitFailsCodecBeforeAllocation() { assertReleaseCheckpointSubstitutionDenied(true); } @Test - void changedWorldContentDigestFailsJavaAndDatabaseBeforeAllocation() { + void changedWorldContentDigestFailsCodecBeforeAllocation() { assertReleaseCheckpointSubstitutionDenied(false); } private void assertReleaseCheckpointSubstitutionDenied(boolean changeCommit) { Fixture original = fixture(); - var topology = frozenPlan(original); - var checkpoint = topology.sourceBinding().freeze(); + var checkpoint = frozenPlan(original).sourceBinding().freeze(); + var selector = + Objects.requireNonNull( + original.binding().evidence().releaseAttestation().worldStartLocationEvidence(), + "retained World selector is required for the original release profile"); var changedCheckpoint = new CaptureRequest( checkpoint.targetNamespace(), @@ -203,59 +205,29 @@ private void assertReleaseCheckpointSubstitutionDenied(boolean changeCommit) { + checkpoint.contentDigest().substring(1), checkpoint.digestSchemaVersion(), checkpoint.suppliedOwnedAffectedTuples()); + String candidateControlRequest = controlRequest(); var descriptorEvidence = completeEvidence( original.source().source(), - controlRequest(), + candidateControlRequest, original.versionIdentity().gameDesignVersionId(), original.versionIdentity().canonicalVersionId(), VERSION_EPOCH, "changed-checkpoint-descriptor", - changedCheckpoint.appliedCommitId()); - var evidence = - new CompleteLaunchBindingEvidence( - descriptorEvidence.descriptor(), - releaseWithWorldCheckpoint(descriptorEvidence.releaseAttestation(), changedCheckpoint)); - // This is a complete, digest-valid five-owner pair for the same Version. Pair retention alone - // must not make its different commit or World content eligible for local materialization. - var changedBinding = - Objects.requireNonNull( - ownerTransaction() - .execute( - status -> - launchBindingRepository.acceptFresh( - NAMESPACE, original.source().receipt(), evidence))); - UUID instance = UUID.randomUUID(); - UUID playableNamespace = UUID.randomUUID(); - var request = requestFor(evidence, instance, UUID.randomUUID()); - var response = - responseFor( - evidence, instance, playableNamespace, request.readRequestId(), "GS_FIXTURE", 1L); + selector.request().appliedCommitId(), + selector); + // Keep the actual retained selector/profile intact. A substituted participant commit or + // World digest cannot be made eligible by constructing a second, mismatched release graph. + // This proves immutable codec rejection only; independent SQL substitution coverage remains + // an open proof obligation because these cases intentionally stop before SQL. assertThatThrownBy( () -> - new WorldCanonicalInstancePreparation.Input( - request, response, changedBinding, original.versionIdentity(), topology)) - .isInstanceOf(IllegalArgumentException.class); + releaseWithWorldCheckpoint( + descriptorEvidence.releaseAttestation(), changedCheckpoint)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("World selector differs from the exact attested release checkpoint"); - // Deliberately bypass the Java constructor to exercise the database owner's independent gate. - var rawInput = mock(WorldCanonicalInstancePreparation.Input.class); - when(rawInput.gameSessionReadRequest()).thenReturn(request); - when(rawInput.gameSessionReadEvidence()).thenReturn(response); - when(rawInput.completeLaunchBinding()).thenReturn(changedBinding); - when(rawInput.versionIdentity()).thenReturn(original.versionIdentity()); - when(rawInput.topologyPlan()).thenReturn(topology); - String inputJson = WorldCanonicalInstancePreparationRepository.inputJson(rawInput); - assertThatThrownBy( - () -> - ownerTransaction() - .execute( - status -> - dsl.fetch( - "SELECT * FROM world_prepare_canonical_instance(?, 'sha256:' || encode(sha256(convert_to(?, 'UTF8')), 'hex'))", - inputJson, - inputJson))) - .rootCause() - .hasMessageContaining("release differs from the exact selected frozen World graph"); + UUID instance = UUID.randomUUID(); assertThat(preparationCount(instance)).isZero(); assertThat(associationCount(instance)).isZero(); assertThat( @@ -263,19 +235,18 @@ private void assertReleaseCheckpointSubstitutionDenied(boolean changeCommit) { "SELECT id FROM world_instance WHERE canonical_game_instance_id = ?", instance)) .isNull(); assertThat( - dsl.fetchOne( - "SELECT id FROM world_instance WHERE canonical_launch_binding_operation_id = ?", - changedBinding.operationId())) - .isNull(); + launchBindingRepository.read( + NAMESPACE, original.source().source().canonicalTenantId(), candidateControlRequest)) + .isEmpty(); assertThat( launchBindingRepository .read( NAMESPACE, - changedBinding.canonicalTenantId(), - changedBinding.controlPlaneRequestId()) + original.binding().canonicalTenantId(), + original.binding().controlPlaneRequestId()) .orElseThrow() .evidence()) - .isEqualTo(evidence); + .isEqualTo(original.binding().evidence()); } @Test @@ -839,6 +810,9 @@ void rejectsDifferentBindingTenantVersionAndPrivateWorldRowWithoutMutation() { "synthetic-second-binding"); Fixture changedBindingFixture = new Fixture(original.source(), secondBinding.binding(), secondBinding.versionIdentity()); + // The historical row now hits V62's target-wide missing-execution-identity gate first, so + // this call does not prove the Java changed-binding comparison. The owner-side claim check + // below remains a separate association-evidence rejection proof. assertThatThrownBy( () -> prepareCanonicalWorldRow( @@ -847,8 +821,9 @@ void rejectsDifferentBindingTenantVersionAndPrivateWorldRowWithoutMutation() { playableStateNamespaceId, "GS_FIXTURE", 1L)) - .isInstanceOf( - WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class); + .isInstanceOf(DataIntegrityViolationException.class) + .rootCause() + .hasMessageContaining("Historical World materialization has no exact execution identity"); WorldCanonicalInstanceAssociation.Claim changedBindingClaim = claim( secondBinding, @@ -1169,10 +1144,18 @@ void exactIdentitySubstitutionIsRejectedBeforeAnyNewSourceOrWriterWork() { @Test void worldExecutionFenceIsMonotonicAndDistinctFromSyntheticSourceFences() { Fixture fixture = fixture(); + SeededPair secondPair = + seedPair( + fixture.source(), + fixture.versionIdentity(), + controlRequest(), + "synthetic-second-execution-fence"); + Fixture secondFixture = + new Fixture(fixture.source(), secondPair.binding(), secondPair.versionIdentity()); WorldCanonicalInstancePreparation.Input firstInput = preparationInput(fixture, UUID.randomUUID(), UUID.randomUUID(), "GS_FENCE_ONE", 1L); WorldCanonicalInstancePreparation.Input secondInput = - preparationInput(fixture, UUID.randomUUID(), UUID.randomUUID(), "GS_FENCE_TWO", 1L); + preparationInput(secondFixture, UUID.randomUUID(), UUID.randomUUID(), "GS_FENCE_TWO", 1L); WorldCanonicalInstanceExecutionIdentity firstIdentity = withLargeSyntheticSourceFences( WorldCanonicalInstanceExecutionTestFixtures.identity(firstInput)); @@ -1231,12 +1214,12 @@ void durableAbortBlocksFreshServiceV35AndV34Writers() { () -> dsl.fetchOne( "SELECT * FROM world_prepare_canonical_instance(?, ?)", inputJson, inputDigest)) - .isInstanceOf(DataAccessException.class) + .isInstanceOf(DataIntegrityViolationException.class) .rootCause() .hasMessageContaining("exact current World execution identity and fence"); assertThatThrownBy( () -> dsl.execute("INSERT INTO world_canonical_instance_association DEFAULT VALUES")) - .isInstanceOf(DataAccessException.class) + .isInstanceOf(DataIntegrityViolationException.class) .rootCause() .hasMessageContaining("exact active World execution identity and fence"); assertThat(preparationCount(canonicalGameInstanceId)).isZero(); @@ -1266,7 +1249,7 @@ void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { () -> dsl.fetchOne( "SELECT * FROM world_prepare_canonical_instance(?, ?)", inputJson, inputDigest)) - .isInstanceOf(DataAccessException.class) + .isInstanceOf(DataIntegrityViolationException.class) .rootCause() .hasMessageContaining("exact current World execution identity and fence"); @@ -1324,7 +1307,7 @@ void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { inputJson, inputDigest); })) - .isInstanceOf(DataAccessException.class) + .isInstanceOf(DataIntegrityViolationException.class) .rootCause() .hasMessageContaining("exact current World execution identity and fence"); assertThat(preparationCount(identity.canonicalGameInstanceId())).isZero(); @@ -1462,7 +1445,7 @@ void expiryIsRecheckedByDatabaseClockAfterWaitingOnV35PublicationOwnerLock() thr fixture.source().receipt().localTenantKey(), fixture.versionIdentity().localVersionKey()); ownerRowLocked.countDown(); - await(releaseOwnerRow); + await(releaseOwnerRow, 30, TimeUnit.SECONDS); return null; })); assertThat(ownerRowLocked.await(10, TimeUnit.SECONDS)).isTrue(); @@ -1611,8 +1594,7 @@ void concurrentExecutionAndDurableAbortSerializeToCommittedResult() throws Excep } @Test - void concurrentExactPreparationsForTheSameCanonicalGameInstanceRetainOneOwnerResult() - throws Exception { + void concurrentExactPreparationDeniesPendingDuplicateAndRetainsOneOwnerResult() throws Exception { Fixture fixture = fixture(); UUID canonicalGameInstanceId = UUID.randomUUID(); UUID playableStateNamespaceId = UUID.randomUUID(); @@ -1621,35 +1603,59 @@ void concurrentExactPreparationsForTheSameCanonicalGameInstanceRetainOneOwnerRes fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); WorldCanonicalInstanceExecutionIdentity exactIdentity = WorldCanonicalInstanceExecutionTestFixtures.identity(exactInput); + AtomicInteger heldChecks = new AtomicInteger(); + CountDownLatch associationRetained = new CountDownLatch(1); + CountDownLatch releaseOriginalExecution = new CountDownLatch(1); WorldCanonicalInstancePreparationService firstService = - preparationService(() -> {}, ignored -> exactIdentity); + preparationService( + () -> { + if (heldChecks.incrementAndGet() == 8) { + associationRetained.countDown(); + await(releaseOriginalExecution); + } + }, + ignored -> exactIdentity); WorldCanonicalInstancePreparationService secondService = preparationService(() -> {}, ignored -> exactIdentity); - CountDownLatch ready = new CountDownLatch(2); - CountDownLatch start = new CountDownLatch(1); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future first = - executor.submit( - () -> { - ready.countDown(); - await(start); - return firstService.prepare(exactInput); - }); - Future second = - executor.submit( - () -> { - ready.countDown(); - await(start); - return secondService.prepare(exactInput); + executor.submit(() -> firstService.prepare(exactInput)); + try { + assertThat(associationRetained.await(10, TimeUnit.SECONDS)).isTrue(); + Future duplicate = + executor.submit(() -> secondService.prepare(exactInput)); + assertThatThrownBy(() -> duplicate.get(10, TimeUnit.SECONDS)) + .isInstanceOfSatisfying( + java.util.concurrent.ExecutionException.class, + failure -> + assertThat(failure.getCause()) + .isInstanceOfSatisfying( + WorldCanonicalInstancePreparationRepository + .ConflictingPreparationException.class, + pending -> + assertThat(pending) + .hasMessage( + "Exact original World execution has a retained PENDING intent; " + + "only serialized ABORTED recovery may resolve it"))); + } finally { + releaseOriginalExecution.countDown(); + } + + WorldCanonicalInstancePreparation.Result originalResult = first.get(25, TimeUnit.SECONDS); + assertThat(originalResult.association().identity().canonicalGameInstanceId()) + .isEqualTo(canonicalGameInstanceId); + assertThat( + preparationRepository().readExactExecution(exactIdentity).operation().orElseThrow()) + .satisfies( + operation -> { + assertThat(operation.state()) + .isEqualTo( + WorldCanonicalInstancePreparationRepository.ExecutionState.COMMITTED); + assertThat(operation.worldInstanceId()) + .isEqualTo(originalResult.association().worldInstanceId()); }); - assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); - start.countDown(); - WorldCanonicalInstancePreparation.Result firstResult = first.get(25, TimeUnit.SECONDS); - WorldCanonicalInstancePreparation.Result secondResult = second.get(25, TimeUnit.SECONDS); - assertThat(firstResult.association().worldInstanceId()) - .isEqualTo(secondResult.association().worldInstanceId()); - assertThat(firstResult.inputDigest()).isEqualTo(secondResult.inputDigest()); + assertThat(preparationRepository().readOwnerPreparation(exactInput)).contains(originalResult); } assertThat(associationCount(canonicalGameInstanceId)).isEqualTo(1L); @@ -2880,25 +2886,6 @@ private TransactionTemplate ownerTransaction() { return transaction; } - private static CompleteLaunchBindingEvidence completeEvidence( - AuthoredWorldSourceEvidence source, - String controlPlaneRequestId, - long gameDesignVersionId, - UUID canonicalVersionId, - long epoch, - String launchDescriptorId, - String attestationCommit) { - return completeEvidence( - source, - controlPlaneRequestId, - gameDesignVersionId, - canonicalVersionId, - epoch, - launchDescriptorId, - attestationCommit, - null); - } - private static CompleteLaunchBindingEvidence completeEvidence( AuthoredWorldSourceEvidence source, String controlPlaneRequestId, @@ -3231,8 +3218,12 @@ private static long positiveLong() { } private static void await(CountDownLatch latch) { + await(latch, 10, TimeUnit.SECONDS); + } + + private static void await(CountDownLatch latch, long timeout, TimeUnit unit) { try { - if (!latch.await(10, TimeUnit.SECONDS)) { + if (!latch.await(timeout, unit)) { throw new IllegalStateException("Concurrent canonical association barrier timed out"); } } catch (InterruptedException exception) { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalStartSessionTerminalReadTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalStartSessionTerminalReadTest.java new file mode 100644 index 0000000000..43481856ab --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalStartSessionTerminalReadTest.java @@ -0,0 +1,357 @@ +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.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +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 java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionLookup; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionOperation; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionState; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService.PreparationDeniedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class WorldCanonicalStartSessionTerminalReadTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID INSTANCE_ID = UUID.fromString("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final String NAMESPACE = "world-runtime"; + private static final String REQUEST_ID = "world-terminal-read-test"; + private static final String WORKLOAD_IDENTITY = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String AUTHORIZATION_REFERENCE_FINGERPRINT = + "arfp/v1/test-key/" + "b".repeat(64); + private static final String PREPARATION_INPUT_JSON = + "{ \"selected\" : \"immutable source\", \"revision\": 3 }\n"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearAmbientTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void committedAndAbortedReadsProjectExactIdentityAndWorldFenceWithoutMutation() { + for (ExecutionState state : List.of(ExecutionState.COMMITTED, ExecutionState.ABORTED)) { + WorldCanonicalInstanceExecutionIdentity identity = + identity(Instant.now().plusSeconds(300L), false); + long worldFence = 83L; + long privateWorldRowKey = 991L; + ExecutionOperation operation = + new ExecutionOperation( + state, worldFence, state == ExecutionState.COMMITTED ? privateWorldRowKey : null); + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var recoveryVerifier = mock(OriginalOperationRecoveryVerifier.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + when(repository.readExactExecution(identity)) + .thenReturn(new ExecutionLookup(Optional.of(operation), true)); + var service = + new WorldCanonicalInstancePreparationService( + repository, commitVerifier, recoveryVerifier); + + WorldStartSessionExecutionTerminal terminal = + service.recoverExactTerminal(identity).orElseThrow(); + WorldStartSessionExecutionTerminal decoded = + WorldStartSessionExecutionTerminal.fromStored(terminal.canonicalBytes()); + + assertThat(decoded.canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(decoded.originalPostAuthorizationTuple()) + .containsExactly(identity.originalPostAuthorizationTuple()); + assertThat(decoded.accountWorldParticipationId()) + .isEqualTo(identity.accountWorldParticipationId()); + assertThat(decoded.accountWorldParticipationFence()) + .isEqualTo(identity.accountWorldParticipationFence()); + assertThat(decoded.gameSessionOwnerAttemptId()) + .isEqualTo(identity.gameSessionOwnerAttemptId()); + assertThat(decoded.gameSessionOwnerFence()).isEqualTo(identity.gameSessionOwnerFence()); + assertThat(decoded.targetNamespace()).isEqualTo(identity.targetNamespace()); + assertThat(decoded.canonicalTenantId()).isEqualTo(identity.canonicalTenantId()); + assertThat(decoded.controlPlaneRequestId()).isEqualTo(identity.controlPlaneRequestId()); + assertThat(decoded.canonicalGameInstanceId()).isEqualTo(identity.canonicalGameInstanceId()); + assertThat(decoded.preparationInputDigest()).isEqualTo(identity.preparationInputDigest()); + assertThat(decoded.preparationInputJson()).isEqualTo(identity.preparationInputJson()); + assertThat(decoded.worldExecutionFence()).isEqualTo(worldFence); + assertThat(decoded.outcome()) + .isEqualTo( + state == ExecutionState.COMMITTED + ? WorldStartSessionExecutionTerminal.Outcome.COMMITTED + : WorldStartSessionExecutionTerminal.Outcome.ABORTED); + String canonical = new String(decoded.canonicalBytes(), StandardCharsets.UTF_8); + assertThat(canonical).doesNotContain("worldInstanceId"); + + var order = inOrder(recoveryVerifier, repository); + order.verify(recoveryVerifier).verifyOriginalOperation(identity); + order.verify(repository).readExactExecution(identity); + verifyNoMoreInteractions(recoveryVerifier, repository); + verifyNoInteractions(commitVerifier); + } + } + + @Test + void absentAndPendingOperationsRemainUnresolved() { + WorldCanonicalInstanceExecutionIdentity identity = + identity(Instant.now().plusSeconds(300L), false); + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var recoveryVerifier = mock(OriginalOperationRecoveryVerifier.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + when(repository.readExactExecution(identity)) + .thenReturn( + new ExecutionLookup(Optional.empty(), true), + new ExecutionLookup( + Optional.of(new ExecutionOperation(ExecutionState.PENDING, 83L, null)), true)); + var service = + new WorldCanonicalInstancePreparationService(repository, commitVerifier, recoveryVerifier); + + assertThat(service.recoverExactTerminal(identity)).isEmpty(); + assertThat(service.recoverExactTerminal(identity)).isEmpty(); + + verify(recoveryVerifier, org.mockito.Mockito.times(2)).verifyOriginalOperation(identity); + verify(repository, org.mockito.Mockito.times(2)).readExactExecution(identity); + verifyNoMoreInteractions(recoveryVerifier, repository); + verifyNoInteractions(commitVerifier); + } + + @Test + void expiredOriginalAuthorizationCanOnlyProduceStableExactReadbackWithExplicitVerifier() { + WorldCanonicalInstanceExecutionIdentity identity = + identity(Instant.now().minusSeconds(5L), false); + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var recoveryVerifier = mock(OriginalOperationRecoveryVerifier.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + var operation = new ExecutionOperation(ExecutionState.ABORTED, 83L, null); + when(repository.readExactExecution(identity)) + .thenReturn( + new ExecutionLookup(Optional.of(operation), false), + new ExecutionLookup(Optional.of(operation), false)); + var service = + new WorldCanonicalInstancePreparationService(repository, commitVerifier, recoveryVerifier); + + byte[] first = service.recoverExactTerminal(identity).orElseThrow().canonicalBytes(); + byte[] second = service.recoverExactTerminal(identity).orElseThrow().canonicalBytes(); + + assertThat(second).containsExactly(first); + verify(recoveryVerifier, org.mockito.Mockito.times(2)).verifyOriginalOperation(identity); + verify(repository, org.mockito.Mockito.times(2)).readExactExecution(identity); + verifyNoMoreInteractions(recoveryVerifier, repository); + verifyNoInteractions(commitVerifier); + } + + @Test + void preservesEqualIndependentlyOwnedFenceValuesInTerminal() { + WorldCanonicalInstanceExecutionIdentity identity = + identity(Instant.now().plusSeconds(300L), true); + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var recoveryVerifier = mock(OriginalOperationRecoveryVerifier.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + when(repository.readExactExecution(identity)) + .thenReturn( + new ExecutionLookup( + Optional.of(new ExecutionOperation(ExecutionState.COMMITTED, 31L, 991L)), false)); + var service = + new WorldCanonicalInstancePreparationService(repository, commitVerifier, recoveryVerifier); + + WorldStartSessionExecutionTerminal terminal = + service.recoverExactTerminal(identity).orElseThrow(); + + assertThat(terminal.accountWorldParticipationFence()).isEqualTo(31L); + assertThat(terminal.gameSessionOwnerFence()).isEqualTo(31L); + assertThat(terminal.worldExecutionFence()).isEqualTo(31L); + } + + @Test + void defaultDenialVerifierDenialAndAmbientTransactionPrecedeStorage() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + WorldCanonicalInstanceExecutionIdentity identity = + mock(WorldCanonicalInstanceExecutionIdentity.class); + + assertThatThrownBy( + () -> + new WorldCanonicalInstancePreparationService(repository) + .recoverExactTerminal(identity)) + .isInstanceOf(PreparationDeniedException.class) + .hasMessageContaining("no authenticated original-operation verifier"); + verifyNoInteractions(repository); + + var recoveryVerifier = mock(OriginalOperationRecoveryVerifier.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + doThrow(new PreparationDeniedException("denied")) + .when(recoveryVerifier) + .verifyOriginalOperation(identity); + var service = + new WorldCanonicalInstancePreparationService(repository, commitVerifier, recoveryVerifier); + assertThatThrownBy(() -> service.recoverExactTerminal(identity)) + .isInstanceOf(PreparationDeniedException.class) + .hasMessage("denied"); + verifyNoInteractions(repository, commitVerifier); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> service.recoverExactTerminal(identity)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an ambient transaction"); + verifyNoInteractions(repository); + } + + private static WorldCanonicalInstanceExecutionIdentity identity( + Instant originalExpiry, boolean equalFences) { + UUID actorAccountId = UUID.randomUUID(); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(91L, actorAccountId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "synthetic World terminal-read fixture"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + REQUEST_ID, actorAccountId, action); + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + StartSessionPostAuthorizationExecutionTuple postTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + WORKLOAD_IDENTITY, + AUTHORIZATION_REFERENCE_FINGERPRINT, + UUID.randomUUID(), + 19L, + authorityEvidenceBundle(preTuple, actorAccountId, originalExpiry), + bundleReference); + long accountParticipationFence = 31L; + long gameSessionOwnerFence = equalFences ? accountParticipationFence : 37L; + return new WorldCanonicalInstanceExecutionIdentity( + postTuple.canonicalBytes(), + UUID.randomUUID(), + accountParticipationFence, + UUID.randomUUID(), + gameSessionOwnerFence, + INSTANCE_ID, + PREPARATION_INPUT_JSON); + } + + /** Canonical integrity fixture only; these synthetic bytes do not authenticate Account. */ + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple tuple, UUID actorAccountId, Instant expiresAt) { + String tenantId = tuple.action().scope().tenantId().toString(); + Instant now = Instant.now(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + canonicalTimestamp(now.minusSeconds(30L)), + "expiresAt", + canonicalTimestamp(expiresAt)); + Map operationIdentity = + Map.of( + "issuanceOperationId", + UUID.randomUUID().toString(), + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", + tuple.mutationDigest()); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 2L, + "tenantAuthorityGeneration", + Map.of(tenantId, 3L), + "membershipAuthorityGeneration", + Map.of(tenantId, 4L), + "privateRealmGrantVersions", + List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actorAccountId.toString(), + "controlUiTokenJti", + UUID.randomUUID().toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorAccountId.toString(), + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operationIdentity, + "issuanceKind", + "human_operator", + "authorityTuple", + authorityTuple, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + } catch (IOException exception) { + throw new IllegalStateException( + "Could not encode synthetic StartSession evidence", exception); + } + } + + private static String canonicalTimestamp(Instant instant) { + return Instant.ofEpochMilli(instant.toEpochMilli()).toString(); + } +} From b6456cc7fc8a7aba1b8a952b315f005fca7a21f6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 13:46:58 +1300 Subject: [PATCH 068/129] Construct exact World participation settlement and repair inventory migration overlap --- .../account-service/api-contracts.md | 2 +- .../world-management-service/api-contracts.md | 2 + .../runtime-and-data.md | 2 +- ...ame-authoring-publishing-and-activation.md | 10 +- .../world-runtime-and-movement.md | 2 +- .../v1/world_management_service.proto | 27 + ...rtSessionWorldParticipationRepository.java | 1057 +++++++++++++++++ ...rtSessionOperatorAuthorizationService.java | 134 +++ ...onWorldParticipationSettlementService.java | 198 +++ .../V127__selected_inventory_empty_arrays.sql | 30 +- ...rraysMigrationPostgresIntegrationTest.java | 259 ++++ ...ssionWorldParticipationRepositoryTest.java | 894 ++++++++++++++ ...ssionOperatorAuthorizationServiceTest.java | 391 +++++- ...rldParticipationSettlementServiceTest.java | 566 +++++++++ ...artSessionExecutionTerminalReadClient.java | 162 +++ ...SessionExecutionTerminalReadGrpcCodec.java | 127 ++ ...rtSessionExecutionTerminalReadRequest.java | 195 +++ ...essionExecutionTerminalReadClientTest.java | 75 ++ ...ionExecutionTerminalReadGrpcCodecTest.java | 283 +++++ ...ssionExecutionTerminalReadGrpcService.java | 156 +++ ...nExecutionTerminalReadGrpcServiceTest.java | 452 +++++++ 21 files changed, 5006 insertions(+), 18 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSelectedInventoryEmptyArraysMigrationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadRequest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcService.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcServiceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index b1e7508623..54644c5d70 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -187,7 +187,7 @@ Error precedence is canonical: (1) Account authenticates the exact immediate mTL These RPCs and schemas are accepted target state but are not present in the current Account proto or implementation. Logging & Admin remains the external operator ingress and durable intent/audit coordinator, Account remains the authorization authority and owner of original-reference retention, and the domain service remains the mutation owner. -For StartSession, Account's existing human authorization-reference issuer remains the sole issuer and the original reference retains `targetOwner=game-session-service`. The distinct Account-owned same-namespace World receiving-participation and source-protection lifecycle is defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation); this API contract adds no replacement issuer, reference-renewal, or re-redemption path. The Game Design projection read and publication hold/settlement producers remain separate and grant no StartSession World permission. StartSession participation acquisition, World admission, terminal settlement, and their proof remain unimplemented. +For StartSession, Account's existing human authorization-reference issuer remains the sole issuer and the original reference retains `targetOwner=game-session-service`. The distinct Account-owned same-namespace World receiving-participation and source-protection lifecycle is defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation); this API contract adds no replacement issuer, reference-renewal, or re-redemption path. The Game Design projection read and publication hold/settlement producers remain separate and grant no StartSession World permission. Unregistered repository, currentness and exact-terminal settlement components do not establish a complete genuine participation producer or World admission; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records their remaining producer, consumer and physical proof gates. The credential-free `ReadRedeemedOperationProjection` receiver accepts the exact configured same-namespace Game Design peer and the exact original Game Session redeemer under [ADR 0047's restricted original-operation read](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). Before returning the retained projection, Account compares the original request/reservation and redeemed workload/attempt/fence, then revalidates the original actor/JTI, current source and reference expiry. The response contains no credential or renewed permission. Game Session must separately prove its original claim and immutable pin under the owner-local checks required by that contract; this Account read is not World participation or admission. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 6fd6ee61fd..ef0f6fdd51 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -13,6 +13,7 @@ This API contract is target-state canonical; implementation coverage is partial - The standalone canonical initial-placement adapter now defines an Entity Management-only historical terminal-result read. Its proto and handler remain unregistered; the read supplies settlement evidence for the exact immutable placement operation, without admitting gameplay or directly mutating any hold. - The authored-world intake construction reads its complete immutable Game Design source through the exact authenticated owner-read contract in [Game Design API Contracts](../game-design-service/api-contracts.md#authored-world-source-readback). The intake transport remains unregistered and does not authorize source mutation, instance preparation, publication, or runtime admission. - The separate canonical StartSession preparation construction must use the distinct Account World receiving participation and World-local terminal serialization described in [World runtime/data](runtime-and-data.md#original-startsession-execution-storage). Its typed execution identity is binding data, not authenticated authorization. No runtime RPC or positive producer is registered by these storage seams; the ordinary lifecycle handler's Game Session peer guard does not complete this canonical path. +- A standalone `ReadWorldStartSessionExecutionTerminal` adapter and file-backed mTLS client are constructed but unregistered. The adapter requires the exact same-namespace Account workload without end-user context before parsing, then delegates to the separately verified original-operation recovery read. Its focused unit definitions stipulate that verifier; they do not establish genuine authenticated recovery or settlement. - The unregistered canonical initial-admission hold adapter includes a separate exact hold-state/lifecycle read. The repository reads actual status and current lifecycle in one read-only snapshot; historical identity readback remains unchanged. Focused mock/unit definitions and a synthetic legacy-row PostgreSQL definition are not genuine database-to-RPC or continuous-protection proof. - 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. @@ -31,6 +32,7 @@ This API contract is target-state canonical; implementation coverage is partial - `ActivatePreparedWorldInstance` – performs the fenced `PREPARING -> ACTIVE` lifecycle transition after Game Session has finished local start-up work for the same `gameInstanceId`. - `FailPreparedWorldInstance` – performs the fenced `PREPARING -> FAILED_PRE_ACTIVATION` transition when Game Session or another pre-admission consumer must roll back a prepared instance before admission opens. - `GetWorldInstanceLifecycle` – returns the current fenced lifecycle snapshot for an existing `(tenantId, gameInstanceId)` so stop/cutover consumers can retry against fresh lifecycle truth instead of cached guesses. +- `ReadWorldStartSessionExecutionTerminal` – reads the [exact original StartSession terminal](./runtime-and-data.md#original-startsession-execution-storage) for Account settlement, with fresh read correlation and the complete unchanged execution identity. The independent owner read returns only the echoed read UUID and canonical terminal bytes. Missing or `PENDING` state remains unresolved with no terminal response; it is never abort proof or fresh execution permission. - `ReadCanonicalInitialAdmissionHoldState` – the unregistered canonical hold adapter accepts a fresh canonical non-nil `readRequestId`, complete immutable hold identity bytes and a complete canonical lifecycle read request with that same read UUID. Only verified same-namespace Game Session without end-user caller context may read; authentication and ambient-transaction denial precede parsing or owner queries. The response echoes the exact read UUID and returns the [closed same-snapshot state carrier](./runtime-and-data.md#canonical-initial-admission-hold-state-snapshot). Unknown protobuf fields, mixed scope or correlation, substituted identity/fence and incomplete owner evidence deny. This is distinct from historical `ReadCanonicalInitialAdmissionHoldIdentity` and StartSession execution-terminal recovery; it neither acquires nor resolves a hold. - `TerminateWorldInstance` – requests or resumes fenced termination from `PREPARING`, `FAILED_PRE_ACTIVATION`, or `ACTIVE`; it reports `TERMINATED` only after every owner in the frozen required cleanup-owner snapshot captured for `terminationRequestId`, together with its ownership-registry revision, acknowledges cleanup and the final lifecycle CAS commits against that same snapshot. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index ab3530959e..b2b23c8e65 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -33,7 +33,7 @@ World Management instances are intended to be replaceable workers over authorita Execution admission, materialization, canonical association and `COMMITTED` publication share one uninterrupted local SQL transaction. The operation/request and canonical-target serialization precede the existing publication and topology locks; the database checks actual current time after lock waits before admitting execution. Network calls occur before SQL, never under these locks. Operational transaction timeouts and cancellation bound resource use, not the physical instant of commit. An execution admitted while the original authorization and owner claim are valid may finish after ingress expiry; expiry never permits another execution transaction, renewed participation or a replacement attempt. -Exact recovery compares the retained full identity and immutable terminal preparation result. Its service read path authenticates the original operation outside SQL, separately from fresh-admission verification, and reads only that stored operation; ingress expiry cannot turn it into renewed execution. Existing constructors deny recovery unless an explicit original-operation verifier is supplied. A separate `ABORTED` transaction takes the same operation and target serialization, excludes a live execution and permanently fences later materialization and canonical association. Missing rows, timeouts and rolled-back intermediate states are not abort proof. An unknown outcome remains unresolved until exact `COMMITTED` readback or serialized `ABORTED` proof; Account retains its source protection until authenticated terminal settlement. These storage rules do not supply the missing genuine Account participation producer or authenticated terminal transport. The canonical preparation service remains unavailable for runtime use until that producer, consumer and physical concurrency/recovery proof are complete. +Exact recovery compares the retained full identity and immutable terminal preparation result. Its service read path authenticates the original operation outside SQL, separately from fresh-admission verification, and reads only that stored operation; ingress expiry cannot turn it into renewed execution. Existing constructors deny recovery unless an explicit original-operation verifier is supplied. The unregistered terminal-read adapter accepts only exact same-namespace Account, denies ambient transactions or synchronization, and compares fresh read correlation and every immutable identity field through the closed Common codec. Its file-backed mTLS client checks the exact World peer and applies a bounded call deadline. These transport components do not supply the missing genuine original-operation verifier. A separate `ABORTED` transaction takes the same operation and target serialization, excludes a live execution and permanently fences later materialization and canonical association. Missing rows, timeouts and rolled-back intermediate states are not abort proof. An unknown outcome remains unresolved until exact `COMMITTED` readback or serialized `ABORTED` proof; Account retains its source protection until authenticated terminal settlement. These storage and transport components do not supply the missing genuine Account participation producer or complete authenticated terminal settlement. The canonical preparation service remains unavailable for runtime use until that producer, consumer and physical concurrency/recovery proof are complete. The immutable integrity carrier is `world-start-session-execution-terminal/v1`. Its closed RFC 8785 UTF-8 object contains exactly `schema`, `originalPostAuthorizationTupleBase64`, `accountWorldParticipationId`, `accountWorldParticipationFence`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `targetNamespace`, `canonicalTenantId`, `controlPlaneRequestId`, `canonicalGameInstanceId`, `preparationInputDigest`, `preparationInputJson`, `worldExecutionFence`, and `outcome`. The original post-authorization tuple remains byte-exact with `targetOwner=game-session-service`; the duplicated namespace, tenant and request must match it. UUIDs are canonical and non-nil. Each fence is an independently owned positive BIGINT represented as a canonical decimal string; equal numeric values across owners are permitted, not evidence of an alias. Outcomes are only `COMMITTED` or `ABORTED`. 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 2f96baae1a..7b28133f57 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 @@ -6,7 +6,15 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Account V129 prepares distinct World StartSession participation storage with an independent participation fence, the unchanged complete original post-authorization tuple, exact redeemed Game Session attempt/fence, canonical World target and byte-exact preparation input. Its immutable source children must equal the retained V128 capture; pending participation excludes source mutation and hosted-terms dispatch until an exact immutable World `COMMITTED` or fenced `ABORTED` receipt settles it. Acquisition checks exact captured hosted-terms evidence, not merely a historical disclosure sharing a source key. These SQL integrity and exclusion guards are not a genuine authenticated acquisition or settlement producer. The PostgreSQL definition currently covers migration installation, assembled guard preservation and append-only rejection, not positive authenticated participation or physical concurrency. World adds a read-only terminal projection behind its original-operation recovery verifier; missing or pending operations remain unresolved. The default verifier still denies and no new receiver is registered. Producer, transport, currentness, settlement, physical PostgreSQL and activation proof remain open. +Account V129 prepares distinct World StartSession participation storage with an independent participation fence, the unchanged complete original post-authorization tuple, exact redeemed Game Session attempt/fence, canonical World target and byte-exact preparation input. Its immutable source children must equal the retained V128 capture; pending participation excludes source mutation and hosted-terms dispatch until an exact immutable World `COMMITTED` or fenced `ABORTED` receipt settles it. Acquisition checks exact captured hosted-terms evidence, not merely a historical disclosure sharing a source key. The Account repository constructs typed exact insert/readback and lookup-only historical settlement recovery; the sole issuer supplies a World-only currentness callback without widening the original Game Design/Game Session projection allowlist. Neither supplies genuine Game Session original-operation evidence or a complete authenticated acquisition producer. The PostgreSQL definition currently covers migration installation, assembled guard preservation and append-only rejection, not positive authenticated participation or physical concurrency. + +The separate unregistered World terminal-read contract and strict file-backed mTLS client return only the existing closed terminal bytes for the complete immutable original operation. World authenticates the same-namespace Account receiver before decoding and invokes its original-operation recovery verifier outside SQL; missing or pending operations remain unresolved. The unregistered Account settlement composition derives the read from retained participation, calls World outside SQL, appends the exact terminal in one independent transaction and performs a separate lookup-only post-commit readback. Historical expiry neither renews authority nor authorizes admission. These components remain unregistered; World's default recovery verifier denies. Genuine live/historical Game Session tuple proof, the World verifier, authenticated acquisition/settlement and socket/physical PostgreSQL proof remain required before activation. Mocked transaction ordering and stipulated terminal evidence are not that proof. + +Exact-source [Validation run 38007433576](https://github.com/benhook1013/FireMUD/actions/runs/38007433576) completed red on source `a6c0c20d80c8a373a8af513e01d28b6956cadbb2`. Account executed 255 integration cases with 228 failures; World executed 220 with two failures; Game Design executed 151 with 15 failures; Game Logic executed nine with one failure. These suites report zero skips. The cross-owner failures stop during Account Flyway V127 setup at its selected-inventory ordering-anchor preflight, before their claimed postconditions; V129's installation case and the four receipt-confirmation cases do not establish their intended proof. World's 21 canonical-instance-association cases executed successfully, including the previous fixture corrections. Logging's check and test tasks completed successfully, but no originating class-level artifact establishes the exact mTLS socket case. Corrected physical execution remains open. This run predates the new local repository, terminal transport and settlement composition, and grants them no execution credit. + +The V127 root is a duplicated migration transformation: frozen Gameplay V94 already contains the canonical empty-array ordering expressions. The corrected V127 preserves V94 byte-for-byte, accepts exactly one original or canonical expression per array, rejects missing or ambiguous guards and verifies the final canonical shape. Four PostgreSQL definitions exercise both known V126-to-V127 inputs and missing/duplicate rollback; they still require physical execution. This content-only convergence allocates no version and relaxes no inventory, ordering or source-protection requirement. + +The corrected repository/currentness/terminal-transport/settlement and V127 batch passes the composed local full checks in 3m58s: Common Platform 493, Account 1,213 and World 621 unit cases (2,327 total), with zero failures, errors or skips. Eight non-container integration cases execute; 472 definitions skip without Docker (253 Account, 219 World, including Redis and the four new migration cases). Successful unchanged tasks reuse their results. Schema generation, affected boot JARs, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass; Flyway sanity checks 12 sets and 286 versions. The eleven repository and eight settlement cases establish mocked storage/transaction composition, not physical PostgreSQL or genuine owner authorization. The separately recorded earlier Logging and Common Security results are not new executions in this batch. Corrected-head physical migration, positive authenticated producer/consumer and runtime proof remain open. The originating [47078 validation run](https://github.com/benhook1013/FireMUD/actions/runs/38001925284) exposes real Account capture readback and shared authentication-context defects, alongside stale proof fixtures. The prepared correction compares canonical snapshot UUID strings with typed PostgreSQL UUID values and clears stale thread-local caller state on JWT-exempt calls without removing authenticated gRPC context or verified peer identity. Account fixtures now preserve historical pre-V81 creation order, bounded schema names and mocked outbound clients for unrelated HTTP proof; Gameplay's final V94/V97 guards are retained. World proof keeps canonical release profiles, translated SQL failures and distinct original operation identities; a racing exact duplicate must remain denied while the original is `PENDING`, not automatically restart. Corrected physical execution remains required. 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 7510d6e4e9..571221e5ad 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -14,7 +14,7 @@ The unregistered [canonical initial-placement terminal read](../../architecture/ The unregistered [canonical initial-admission hold-state snapshot](../../architecture/microservices/world-management-service/runtime-and-data.md#canonical-initial-admission-hold-state-snapshot) now has a closed Common carrier, method-specific Game Session peer guard and one read-only `REPEATABLE_READ` repository read of exact immutable identity, actual hold status and current lifecycle. Existing hold identity and acquisition bytes are unchanged. Executed Common and mock-owner unit cases cover peer-first/no-query denial, independent request IDs, exact target/fence, all hold statuses, lifecycle advancement and no mutation. The corrected composed Common/World full checks pass with 489 Common and 609 World unit cases, zero failures/errors/skips; unchanged successful World tasks reuse their local results. Of 220 World integration definitions, one non-container case executes and 219 skip without Docker. The new PostgreSQL definition reads synthetic legacy migration rows only; it does not exercise the canonical repository or genuine lifecycle evidence through the RPC and has not executed locally. Physical producer/consumer proof remains required; no runtime registration or continuous-protection credit follows from the sampled read. -The [original StartSession terminal integrity carrier](../../architecture/microservices/world-management-service/runtime-and-data.md#original-startsession-execution-storage) preserves the complete original tuple, independent Account/Game Session/World identities and fences, exact preparation bytes and terminal outcome. Its six executed codec cases, including the corrected frozen canonical vector, do not authenticate a producer or settle Account source protection. Genuine Account World participation, authenticated original-operation terminal transport and physical expiry/abort/crash/recovery proof remain open. +The [original StartSession terminal integrity carrier](../../architecture/microservices/world-management-service/runtime-and-data.md#original-startsession-execution-storage) preserves the complete original tuple, independent Account/Game Session/World identities and fences, exact preparation bytes and terminal outcome. Its six executed codec cases, including the corrected frozen canonical vector, do not authenticate a producer or settle Account source protection. An unregistered Account-only terminal receiver and file-backed mTLS client now retain exact correlation and full terminal identity; their new definitions stipulate the original-operation verifier and remain separate from genuine authenticated recovery proof. Genuine Account World participation, original-operation verification, terminal settlement and physical expiry/abort/crash/recovery proof remain open. ## Packet 4 Status and Proof Gaps diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index 4ca2622d1a..7a36702ef9 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -52,6 +52,33 @@ service WorldCanonicalInstancePreparationService { returns (PrepareCanonicalWorldInstanceResponse); } +// Explicitly unwired Account-authenticated read of one original StartSession World terminal. +service WorldStartSessionExecutionTerminalReadService { + rpc ReadWorldStartSessionExecutionTerminal( + ReadWorldStartSessionExecutionTerminalRequest) + returns (ReadWorldStartSessionExecutionTerminalResponse); +} + +message ReadWorldStartSessionExecutionTerminalRequest { + // Fresh correlation identity for this read, distinct from all retained operation identities. + string read_request_id = 1; + string target_namespace = 2; + bytes original_post_authorization_tuple = 3; + string account_world_participation_id = 4; + int64 account_world_participation_fence = 5; + string game_session_owner_attempt_id = 6; + int64 game_session_owner_fence = 7; + string canonical_game_instance_id = 8; + // Exact original preparation input. World never reparses or normalizes it during recovery. + string preparation_input_json = 9; +} + +message ReadWorldStartSessionExecutionTerminalResponse { + string read_request_id = 1; + // The only result is the existing closed WorldStartSessionExecutionTerminal carrier. + bytes canonical_terminal_bytes = 2; +} + // The exact ten-field committed Game Session launch-association selector. message PrepareCanonicalWorldInstanceRequest { string read_request_id = 1; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java new file mode 100644 index 0000000000..dac5fdccca --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java @@ -0,0 +1,1057 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCapture; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable Account storage for the distinct World StartSession receiving participation. + * + *

This repository is not a transport authenticator, authority issuer, currentness proof, or + * execution-admission decision. Acquisition callers must authenticate the same-namespace World peer + * before parsing, and must establish the original actor/JTI, live Account source, original redeemed + * Game Session attempt/fence, and exact retained capture inside the existing {@code + * withCurrentCommitted} source-protection callback before calling this repository. Remote + * environment observations belong outside SQL. Terminal callers must separately authenticate the + * original World operation before passing its typed terminal here. + * + *

All operations require the caller's writable READ COMMITTED Account transaction. In + * particular, an exact create retry is not admitted by the database's insert-only expiry trigger: + * the caller must re-establish currentness before retrying. Historical reads and terminal + * settlement intentionally do not renew or recheck reference expiry. + */ +@Repository +public class AccountStartSessionWorldParticipationRepository { + private static final String PARTICIPATIONS = "account_start_session_world_participations"; + private static final String SOURCES = "account_start_session_world_participation_sources"; + private static final String SETTLEMENTS = "account_start_session_world_participation_settlements"; + private static final String CAPTURES = "account_start_session_authority_captures"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern PREPARATION_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern CAPTURED_AT = + Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + private static final Set PARTICIPATION_COLUMNS = + Set.of( + "participation_id", + "participation_fence", + "control_plane_request_id", + "original_post_authorization_tuple", + "target_namespace", + "canonical_tenant_id", + "canonical_game_instance_id", + "game_session_owner_attempt_id", + "game_session_owner_fence", + "preparation_input_json", + "preparation_input_digest", + "producer_xid", + "created_at"); + private static final Set SOURCE_COLUMNS = + Set.of("participation_id", "source_key", "source_evidence"); + private static final Set SETTLEMENT_COLUMNS = + Set.of( + "participation_id", + "outcome", + "world_execution_fence", + "terminal_bytes", + "terminal_digest", + "settled_at"); + private static final Set CAPTURE_COLUMNS = + Set.of( + "control_plane_request_id", + "account_uuid", + "tenant_uuid", + "target_owner", + "logging_workload_uri", + "reservation_owner_id", + "reservation_claim_fence", + "pre_authorization_tuple", + "mutation_digest", + "control_ui_operation_id", + "control_ui_token_jti", + "control_ui_token_hash", + "control_ui_signer_receipt_sha256", + "issuance_fence", + "issuance_fence_source_version", + "captured_at", + "snapshot_sha256", + "canonical_snapshot_bytes", + "source_version", + "source_fence", + "linearization", + "canonical_sha256", + "canonical_capture_bytes", + "created_at"); + private static final Set CAPTURE_SNAPSHOT_FIELDS = + Set.of( + "schema", + "controlPlaneRequestId", + "preAuthorizationTuple", + "mutationDigest", + "accountId", + "tenantId", + "targetOwner", + "loggingWorkloadUri", + "reservationOwnerId", + "reservationClaimFence", + "controlUiOperationId", + "controlUiTokenJti", + "controlUiTokenHash", + "controlUiSignerReceipt", + "controlUiSignerReceiptSha256", + "sourceVectorEvidence", + "sourceVector", + "outboxCheckpoints", + "authorityTuple", + "membershipVersion", + "accountIdentitySource", + "issuanceFence", + "issuanceFenceSourceVersion"); + private static final Set CAPTURE_REFERENCE_FIELDS = + Set.of("schema", "controlPlaneRequestId", "capturedAt", "bundleReference", "snapshotSha256"); + private static final Set BUNDLE_REFERENCE_FIELDS = + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization"); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve the injected DSLContext precondition; this transactional Spring repository must remain proxyable, owns no resources, and declares no finalizer.") + public AccountStartSessionWorldParticipationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Inserts the exact participation and every child from the already retained source capture, or + * returns the immutable winner for an exact request retry. + * + *

Call only after the service has revalidated currentness, original redemption, and the exact + * capture inside {@code withCurrentCommitted}. The reference expiry check in V129 runs on an + * attempted insert; it cannot establish admission for a duplicate lookup. + */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredParticipation createOrReadExact(Candidate candidate) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(candidate, "exact participation candidate is required"); + List expectedSources = + sourceVector(candidate.capture().snapshotBytes(), candidate.controlPlaneRequestId()); + requireCaptureMatches( + candidate.capture(), + candidate.originalTuple(), + selectCapture(candidate.controlPlaneRequestId(), true)); + + UUID proposedId = UUID.randomUUID(); + int inserted = + dsl.execute( + "INSERT INTO " + + PARTICIPATIONS + + " (participation_id, control_plane_request_id, original_post_authorization_tuple, " + + "target_namespace, canonical_tenant_id, canonical_game_instance_id, " + + "game_session_owner_attempt_id, game_session_owner_fence, preparation_input_json, " + + "preparation_input_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (control_plane_request_id) DO NOTHING", + proposedId, + candidate.controlPlaneRequestId(), + candidate.originalPostAuthorizationTuple(), + candidate.targetNamespace(), + candidate.canonicalTenantId(), + candidate.canonicalGameInstanceId(), + candidate.gameSessionOwnerAttemptId(), + candidate.gameSessionOwnerFence(), + candidate.preparationInputJson(), + candidate.preparationInputDigest()); + + if (inserted == 1) { + for (SourceEvidence source : expectedSources) { + dsl.execute( + "INSERT INTO " + + SOURCES + + " (participation_id, source_key, source_evidence) VALUES (?, ?, ?)", + proposedId, + source.key(), + source.canonicalBytes()); + } + } + + Record row = selectByRequestId(candidate.controlPlaneRequestId(), true); + if (row == null) throw unavailable(); + StoredParticipation stored = decodeParticipation(row, readSources(candidateId(row))); + requireSameCandidate(candidate, stored); + requireExactSources(expectedSources, stored.sources()); + if (inserted == 1 && !proposedId.equals(stored.participationId())) throw unavailable(); + if (readSettlement(stored.participationId()) != null) throw unavailable(); + return stored; + } + + /** + * Lookup-only read used after the caller independently establishes current Account authority. + * + *

This method never creates a capture or participation, never authenticates the peer, and + * refuses a settled participation. The currentness proof and capture lock belong to the + * surrounding service callback. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional findCurrentExact(Candidate expected) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(expected, "exact current participation binding is required"); + List expectedSources = + sourceVector(expected.capture().snapshotBytes(), expected.controlPlaneRequestId()); + requireCaptureMatches( + expected.capture(), + expected.originalTuple(), + selectCapture(expected.controlPlaneRequestId(), false)); + Record row = selectByRequestId(expected.controlPlaneRequestId(), false); + if (row == null) return java.util.Optional.empty(); + StoredParticipation stored = decodeParticipation(row, readSources(candidateId(row))); + requireSameCandidate(expected, stored); + requireExactSources(expectedSources, stored.sources()); + if (readSettlement(stored.participationId()) != null) throw unavailable(); + return java.util.Optional.of(stored); + } + + /** + * Exact historical lookup for recovery only; it proves no fresh admission or expiry extension. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional findHistoricalExact( + UUID participationId, long participationFence) { + requireWritableReadCommittedTransaction(); + requireNonnil(participationId, "participationId"); + requirePositive(participationFence, "participationFence"); + Record row = selectById(participationId, false); + if (row == null) return java.util.Optional.empty(); + StoredParticipation parent = decodeParticipation(row, List.of()); + if (parent.participationFence() != participationFence) throw unavailable(); + Record capture = selectCapture(parent.controlPlaneRequestId(), false); + List capturedSources = decodeHistoricalCapture(capture, parent); + List children = readSources(participationId); + requireExactSources(capturedSources, children); + return java.util.Optional.of(withSources(parent, children)); + } + + /** + * Lookup-only post-commit readback of an immutable terminal receipt for exact historical + * participation identity. + * + *

A missing participation or receipt returns empty. This does not admit a new operation, renew + * reference expiry, or require a current actor; it validates the retained historical parent, + * capture, complete source vector, and terminal binding only. It never inserts. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional findSettlementExact( + UUID participationId, long participationFence) { + requireWritableReadCommittedTransaction(); + java.util.Optional participation = + findHistoricalExact(participationId, participationFence); + if (participation.isEmpty()) return java.util.Optional.empty(); + Record row = readSettlement(participationId); + if (row == null) return java.util.Optional.empty(); + return java.util.Optional.of(decodeSettlement(row, participation.orElseThrow())); + } + + /** + * Appends or reads back the exact typed terminal for an existing participation. + * + *

The caller authenticates the original World operation before invoking this method. This + * storage boundary accepts no raw outcome or fence and does not require a current actor or an + * unexpired reference; it only binds immutable historical identity and terminal bytes. + */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSettlement settleExact(WorldStartSessionExecutionTerminal terminal) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(terminal, "authenticated typed World terminal is required"); + StoredParticipation participation = + findHistoricalExact( + terminal.accountWorldParticipationId(), terminal.accountWorldParticipationFence()) + .orElseThrow(AccountStartSessionWorldParticipationRepository::unavailable); + requireTerminalMatches(participation, terminal); + + byte[] terminalBytes = terminal.canonicalBytes(); + dsl.execute( + "INSERT INTO " + + SETTLEMENTS + + " (participation_id, outcome, world_execution_fence, terminal_bytes, terminal_digest) " + + "VALUES (?, ?, ?, ?, ?) ON CONFLICT (participation_id) DO NOTHING", + participation.participationId(), + terminal.outcome().name(), + terminal.worldExecutionFence(), + terminalBytes, + terminal.digest()); + + Record row = readSettlement(participation.participationId()); + if (row == null) throw unavailable(); + StoredSettlement stored = decodeSettlement(row, participation); + requireSameTerminal(stored, terminal); + return stored; + } + + private Record selectByRequestId(String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + PARTICIPATIONS + + " WHERE control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + requestId); + } + + private Record selectById(UUID id, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + PARTICIPATIONS + + " WHERE participation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + id); + } + + private Record selectCapture(String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + CAPTURES + + " WHERE control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + requestId); + } + + private List readSources(UUID participationId) { + var rows = + dsl.fetch("SELECT * FROM " + SOURCES + " WHERE participation_id = ?", participationId); + List sources = new ArrayList<>(rows.size()); + for (Record row : rows) { + requireColumns(row, SOURCE_COLUMNS, "participation source"); + UUID storedId = typedUuid(row, "participation_id"); + String key = requiredString(row, "source_key"); + byte[] bytes = requiredBytes(row, "source_evidence"); + if (!participationId.equals(storedId)) throw unavailable(); + SourceEvidence source = decodeSource(key, bytes); + sources.add(source); + } + sources.sort(Comparator.comparing(SourceEvidence::key)); + if (sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw unavailable(); + } + return List.copyOf(sources); + } + + static StoredParticipation decodeParticipation(Record row, List sources) { + try { + requireColumns(row, PARTICIPATION_COLUMNS, "participation"); + UUID id = typedUuid(row, "participation_id"); + long fence = positive(number(row, "participation_fence"), "participation_fence"); + String requestId = requiredString(row, "control_plane_request_id"); + byte[] tupleBytes = requiredBytes(row, "original_post_authorization_tuple"); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + String namespace = requiredString(row, "target_namespace"); + UUID tenant = typedUuid(row, "canonical_tenant_id"); + UUID instance = typedUuid(row, "canonical_game_instance_id"); + UUID ownerAttempt = typedUuid(row, "game_session_owner_attempt_id"); + long ownerFence = + positive(number(row, "game_session_owner_fence"), "game_session_owner_fence"); + String preparationJson = requiredString(row, "preparation_input_json"); + String preparationDigest = requiredString(row, "preparation_input_digest"); + long producerXid = positive(number(row, "producer_xid"), "producer_xid"); + OffsetDateTime createdAt = + Objects.requireNonNull(row.get("created_at", OffsetDateTime.class)); + if (id.equals(NIL_UUID) + || !requestId.equals(tuple.controlPlaneRequestId()) + || !namespace.equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !tenant.equals(tuple.preAuthorizationTuple().action().scope().tenantId()) + || !"game-session-service".equals(tuple.preAuthorizationTuple().targetOwner()) + || !PREPARATION_DIGEST.matcher(preparationDigest).matches() + || !preparationDigest.equals( + digestPrefixed(preparationJson.getBytes(StandardCharsets.UTF_8)))) { + throw unavailable(); + } + return new StoredParticipation( + id, + fence, + requestId, + tupleBytes, + namespace, + tenant, + instance, + ownerAttempt, + ownerFence, + preparationJson, + preparationDigest, + producerXid, + createdAt, + sources); + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && "Exact StartSession World participation evidence unavailable" + .equals(state.getMessage())) { + throw state; + } + throw unavailable(); + } + } + + private static StoredParticipation withSources( + StoredParticipation parent, List sources) { + return new StoredParticipation( + parent.participationId(), + parent.participationFence(), + parent.controlPlaneRequestId(), + parent.originalPostAuthorizationTuple(), + parent.targetNamespace(), + parent.canonicalTenantId(), + parent.canonicalGameInstanceId(), + parent.gameSessionOwnerAttemptId(), + parent.gameSessionOwnerFence(), + parent.preparationInputJson(), + parent.preparationInputDigest(), + parent.producerXid(), + parent.createdAt(), + sources); + } + + private static List sourceVector(byte[] snapshotBytes, String requestId) { + Map snapshot = parseCanonicalObject(snapshotBytes, "Account capture snapshot"); + if (!CAPTURE_SNAPSHOT_FIELDS.equals(snapshot.keySet()) + || !"account-start-session-authority-snapshot/v1".equals(snapshot.get("schema")) + || !requestId.equals(snapshot.get("controlPlaneRequestId"))) { + throw unavailable(); + } + Object value = snapshot.get("sourceVector"); + if (!(value instanceof List encoded) || encoded.isEmpty()) throw unavailable(); + List sources = new ArrayList<>(encoded.size()); + Set keys = new HashSet<>(); + String previousKey = null; + for (Object element : encoded) { + if (!(element instanceof String base64)) throw unavailable(); + byte[] bytes = strictBase64(base64); + SourceEvidence source = SourceEvidence.fromStored(bytes); + if (bytes.length == 0 + || bytes.length > 131_072 + || !keys.add(source.key()) + || (previousKey != null && previousKey.compareTo(source.key()) >= 0)) { + throw unavailable(); + } + previousKey = source.key(); + sources.add(source); + } + return List.copyOf(sources); + } + + private static SourceEvidence decodeSource(String key, byte[] bytes) { + try { + SourceEvidence source = SourceEvidence.fromStored(bytes); + if (!key.equals(source.key()) || bytes.length > 131_072) throw unavailable(); + return source; + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static void requireCaptureMatches( + AccountStartSessionAuthorityCapture capture, + StartSessionPostAuthorizationExecutionTuple tuple, + Record retainedRow) { + Objects.requireNonNull(capture, "exact retained Account capture is required"); + Objects.requireNonNull(tuple, "exact original StartSession tuple is required"); + if (!capture.controlPlaneRequestId().equals(tuple.controlPlaneRequestId())) throw conflict(); + if (retainedRow == null) throw unavailable(); + Map snapshot = + parseCanonicalObject(capture.snapshotBytes(), "Account capture snapshot"); + if (!CAPTURE_SNAPSHOT_FIELDS.equals(snapshot.keySet()) + || !"account-start-session-authority-snapshot/v1".equals(snapshot.get("schema")) + || !tuple.controlPlaneRequestId().equals(snapshot.get("controlPlaneRequestId")) + || !Base64.getEncoder() + .encodeToString( + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8)) + .equals(snapshot.get("preAuthorizationTuple")) + || !tuple.mutationDigest().equals(snapshot.get("mutationDigest")) + || !tuple + .preAuthorizationTuple() + .actor() + .accountId() + .toString() + .equals(snapshot.get("accountId")) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .toString() + .equals(snapshot.get("tenantId")) + || !"game-session-service".equals(snapshot.get("targetOwner")) + || !tuple.authenticatedWorkloadIdentity().equals(snapshot.get("loggingWorkloadUri")) + || !tuple.reservationOwnerId().toString().equals(snapshot.get("reservationOwnerId")) + || !Long.toString(tuple.reservationClaimFence()) + .equals(snapshot.get("reservationClaimFence")) + || !tuple.issuanceFence().equals(snapshot.get("issuanceFence")) + || !capture.bundleReference().equals(tuple.bundleReference())) { + throw conflict(); + } + sourceVector(capture.snapshotBytes(), tuple.controlPlaneRequestId()); + requireCaptureRow(retainedRow, capture, tuple, snapshot); + } + + private static void requireCaptureRow( + Record row, + AccountStartSessionAuthorityCapture capture, + StartSessionPostAuthorizationExecutionTuple tuple, + Map snapshot) { + requireColumns(row, CAPTURE_COLUMNS, "Account capture"); + requireCaptureColumnsMatchSnapshot(row, snapshot); + OffsetDateTime capturedAt = requiredTimestamp(row, "captured_at"); + if (!tuple.controlPlaneRequestId().equals(requiredString(row, "control_plane_request_id")) + || !Instant.parse(capture.capturedAt()).equals(capturedAt.toInstant()) + || !capture.controlPlaneRequestId().equals(requiredString(row, "control_plane_request_id")) + || capture.sourceVersion() != number(row, "source_version") + || capture.sourceFence() != number(row, "source_fence") + || !capture.linearization().equals(requiredString(row, "linearization")) + || !capture.snapshotSha256().equals(requiredString(row, "snapshot_sha256")) + || !Arrays.equals(capture.snapshotBytes(), requiredBytes(row, "canonical_snapshot_bytes")) + || !capture.canonicalSha256().equals(requiredString(row, "canonical_sha256")) + || !Arrays.equals( + capture.canonicalBytes(), requiredBytes(row, "canonical_capture_bytes"))) { + throw unavailable(); + } + } + + private static void requireCaptureColumnsMatchSnapshot(Record row, Map snapshot) { + if (!Objects.equals(requiredUuidString(row, "account_uuid"), snapshot.get("accountId")) + || !Objects.equals(requiredUuidString(row, "tenant_uuid"), snapshot.get("tenantId")) + || !Objects.equals(requiredString(row, "target_owner"), snapshot.get("targetOwner")) + || !Objects.equals( + requiredString(row, "logging_workload_uri"), snapshot.get("loggingWorkloadUri")) + || !Objects.equals( + requiredUuidString(row, "reservation_owner_id"), snapshot.get("reservationOwnerId")) + || !Objects.equals( + Long.toString(number(row, "reservation_claim_fence")), + snapshot.get("reservationClaimFence")) + || !Arrays.equals( + requiredBytes(row, "pre_authorization_tuple"), + strictBase64(string(snapshot.get("preAuthorizationTuple")))) + || !Objects.equals(requiredString(row, "mutation_digest"), snapshot.get("mutationDigest")) + || !Objects.equals( + requiredUuidString(row, "control_ui_operation_id"), + snapshot.get("controlUiOperationId")) + || !Objects.equals( + requiredUuidString(row, "control_ui_token_jti"), snapshot.get("controlUiTokenJti")) + || !Objects.equals( + requiredString(row, "control_ui_token_hash"), snapshot.get("controlUiTokenHash")) + || !Objects.equals( + requiredString(row, "control_ui_signer_receipt_sha256"), + snapshot.get("controlUiSignerReceiptSha256")) + || !Objects.equals( + Long.toString(number(row, "issuance_fence")), snapshot.get("issuanceFence")) + || !Objects.equals( + Long.toString(number(row, "issuance_fence_source_version")), + snapshot.get("issuanceFenceSourceVersion"))) { + throw unavailable(); + } + byte[] receipt = strictBase64(string(snapshot.get("controlUiSignerReceipt"))); + if (!digestHex(receipt).equals(snapshot.get("controlUiSignerReceiptSha256"))) + throw unavailable(); + } + + private static List decodeHistoricalCapture( + Record row, StoredParticipation parent) { + requireColumns(row, CAPTURE_COLUMNS, "Account capture"); + byte[] snapshotBytes = requiredBytes(row, "canonical_snapshot_bytes"); + byte[] canonicalCaptureBytes = requiredBytes(row, "canonical_capture_bytes"); + if (!digestHex(snapshotBytes).equals(requiredString(row, "snapshot_sha256")) + || !digestHex(canonicalCaptureBytes).equals(requiredString(row, "canonical_sha256"))) { + throw unavailable(); + } + Map snapshot = parseCanonicalObject(snapshotBytes, "Account capture snapshot"); + Map reference = + parseCanonicalObject(canonicalCaptureBytes, "Account capture reference"); + if (!CAPTURE_SNAPSHOT_FIELDS.equals(snapshot.keySet()) + || !CAPTURE_REFERENCE_FIELDS.equals(reference.keySet()) + || !"account-start-session-authority-snapshot/v1".equals(snapshot.get("schema")) + || !"account-start-session-authority-capture/v1".equals(reference.get("schema")) + || !parent.controlPlaneRequestId().equals(requiredString(row, "control_plane_request_id")) + || !parent.controlPlaneRequestId().equals(snapshot.get("controlPlaneRequestId")) + || !parent.controlPlaneRequestId().equals(reference.get("controlPlaneRequestId")) + || !requiredString(row, "snapshot_sha256").equals(reference.get("snapshotSha256")) + || !CAPTURED_AT.matcher(string(reference.get("capturedAt"))).matches() + || !Instant.parse(string(reference.get("capturedAt"))) + .equals(requiredTimestamp(row, "captured_at").toInstant()) + || !referenceMatchesCaptureRow(reference, row)) { + throw unavailable(); + } + requireCaptureColumnsMatchSnapshot(row, snapshot); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(parent.originalPostAuthorizationTuple()); + if (!Base64.getEncoder() + .encodeToString( + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8)) + .equals(snapshot.get("preAuthorizationTuple")) + || !tuple.mutationDigest().equals(snapshot.get("mutationDigest")) + || !tuple + .preAuthorizationTuple() + .actor() + .accountId() + .toString() + .equals(snapshot.get("accountId")) + || !parent.canonicalTenantId().toString().equals(snapshot.get("tenantId")) + || !tuple.authenticatedWorkloadIdentity().equals(snapshot.get("loggingWorkloadUri")) + || !tuple.reservationOwnerId().toString().equals(snapshot.get("reservationOwnerId")) + || !Long.toString(tuple.reservationClaimFence()) + .equals(snapshot.get("reservationClaimFence")) + || !tuple.issuanceFence().equals(snapshot.get("issuanceFence")) + || !tuple.preAuthorizationTuple().targetOwner().equals(snapshot.get("targetOwner")) + || !referenceMatchesTuple(reference, tuple) + || !parent + .targetNamespace() + .equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !parent + .canonicalTenantId() + .equals(tuple.preAuthorizationTuple().action().scope().tenantId())) { + throw unavailable(); + } + return sourceVector(snapshotBytes, parent.controlPlaneRequestId()); + } + + private static boolean referenceMatchesCaptureRow(Map reference, Record row) { + Object bundleValue = reference.get("bundleReference"); + if (!(bundleValue instanceof Map bundle) + || !BUNDLE_REFERENCE_FIELDS.equals(bundle.keySet())) return false; + return StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION.equals(bundle.get("bundleVersion")) + && Long.toString(number(row, "source_version")).equals(bundle.get("sourceVersion")) + && Long.toString(number(row, "source_fence")).equals(bundle.get("sourceFence")) + && requiredString(row, "linearization").equals(bundle.get("linearization")); + } + + private static boolean referenceMatchesTuple( + Map reference, StartSessionPostAuthorizationExecutionTuple tuple) { + Object bundleValue = reference.get("bundleReference"); + if (!(bundleValue instanceof Map bundle)) return false; + var expected = tuple.bundleReference(); + return expected.bundleVersion().equals(bundle.get("bundleVersion")) + && expected.sourceVersion().equals(bundle.get("sourceVersion")) + && expected.sourceFence().equals(bundle.get("sourceFence")) + && expected.linearization().equals(bundle.get("linearization")); + } + + static void requireSameCandidate(Candidate candidate, StoredParticipation stored) { + if (!candidate.controlPlaneRequestId().equals(stored.controlPlaneRequestId()) + || !Arrays.equals( + candidate.originalPostAuthorizationTuple(), stored.originalPostAuthorizationTuple()) + || !candidate.targetNamespace().equals(stored.targetNamespace()) + || !candidate.canonicalTenantId().equals(stored.canonicalTenantId()) + || !candidate.canonicalGameInstanceId().equals(stored.canonicalGameInstanceId()) + || !candidate.gameSessionOwnerAttemptId().equals(stored.gameSessionOwnerAttemptId()) + || candidate.gameSessionOwnerFence() != stored.gameSessionOwnerFence() + || !candidate.preparationInputJson().equals(stored.preparationInputJson()) + || !candidate.preparationInputDigest().equals(stored.preparationInputDigest())) { + throw conflict(); + } + } + + static void requireExactSources(List expected, List actual) { + if (expected == null + || actual == null + || expected.isEmpty() + || expected.size() != actual.size()) { + throw unavailable(); + } + List expectedSorted = + expected.stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + List actualSorted = + actual.stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + Set expectedKeys = new HashSet<>(); + for (int index = 0; index < expectedSorted.size(); index++) { + SourceEvidence left = expectedSorted.get(index); + SourceEvidence right = actualSorted.get(index); + if (!expectedKeys.add(left.key()) + || !left.key().equals(right.key()) + || !Arrays.equals(left.canonicalBytes(), right.canonicalBytes())) { + throw unavailable(); + } + } + } + + static void requireTerminalMatches( + StoredParticipation participation, WorldStartSessionExecutionTerminal terminal) { + if (!participation.participationId().equals(terminal.accountWorldParticipationId()) + || participation.participationFence() != terminal.accountWorldParticipationFence() + || !Arrays.equals( + participation.originalPostAuthorizationTuple(), + terminal.originalPostAuthorizationTuple()) + || !participation.gameSessionOwnerAttemptId().equals(terminal.gameSessionOwnerAttemptId()) + || participation.gameSessionOwnerFence() != terminal.gameSessionOwnerFence() + || !participation.targetNamespace().equals(terminal.targetNamespace()) + || !participation.canonicalTenantId().equals(terminal.canonicalTenantId()) + || !participation.controlPlaneRequestId().equals(terminal.controlPlaneRequestId()) + || !participation.canonicalGameInstanceId().equals(terminal.canonicalGameInstanceId()) + || !participation.preparationInputDigest().equals(terminal.preparationInputDigest()) + || !participation.preparationInputJson().equals(terminal.preparationInputJson())) { + throw conflict(); + } + } + + private Record readSettlement(UUID participationId) { + return dsl.fetchOne( + "SELECT * FROM " + SETTLEMENTS + " WHERE participation_id = ?", participationId); + } + + private static StoredSettlement decodeSettlement(Record row, StoredParticipation participation) { + try { + requireColumns(row, SETTLEMENT_COLUMNS, "participation settlement"); + UUID id = typedUuid(row, "participation_id"); + String outcomeValue = requiredString(row, "outcome"); + WorldStartSessionExecutionTerminal.Outcome outcome = + WorldStartSessionExecutionTerminal.Outcome.valueOf(outcomeValue); + long worldFence = positive(number(row, "world_execution_fence"), "world_execution_fence"); + byte[] terminalBytes = requiredBytes(row, "terminal_bytes"); + String terminalDigest = requiredString(row, "terminal_digest"); + OffsetDateTime settledAt = requiredTimestamp(row, "settled_at"); + if (!id.equals(participation.participationId()) + || !PREPARATION_DIGEST.matcher(terminalDigest).matches() + || !terminalDigest.equals(digestPrefixed(terminalBytes))) { + throw unavailable(); + } + WorldStartSessionExecutionTerminal terminal = + WorldStartSessionExecutionTerminal.fromStored(terminalBytes); + requireTerminalMatches(participation, terminal); + if (terminal.outcome() != outcome || terminal.worldExecutionFence() != worldFence) { + throw unavailable(); + } + return new StoredSettlement( + id, outcome, worldFence, terminalBytes, terminalDigest, settledAt); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static void requireSameTerminal( + StoredSettlement stored, WorldStartSessionExecutionTerminal terminal) { + if (stored.outcome() != terminal.outcome() + || stored.worldExecutionFence() != terminal.worldExecutionFence() + || !stored.terminalDigest().equals(terminal.digest()) + || !Arrays.equals(stored.terminalBytes(), terminal.canonicalBytes())) { + throw conflict(); + } + } + + private static Map parseCanonicalObject(byte[] bytes, String field) { + try { + String json = strictUtf8(bytes); + if (!Arrays.equals(Rfc8785CanonicalJson.canonicalizeUtf8(json), bytes)) throw unavailable(); + Object decoded = JSON.readValue(json, Object.class); + if (!(decoded instanceof Map raw)) throw unavailable(); + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : raw.entrySet()) { + if (!(entry.getKey() instanceof String key)) throw unavailable(); + result.put(key, entry.getValue()); + } + return Map.copyOf(result); + } catch (RuntimeException | java.io.IOException malformed) { + throw unavailable(); + } + } + + private static byte[] strictBase64(String value) { + try { + byte[] decoded = Base64.getDecoder().decode(value); + if (!Base64.getEncoder().encodeToString(decoded).equals(value)) throw unavailable(); + return decoded; + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw unavailable(); + } + } + + private static void requireColumns(Record row, Set expected, String kind) { + if (row == null) throw unavailable(); + Set actual = new HashSet<>(); + Arrays.stream(row.fields()).forEach(field -> actual.add(field.getName())); + if (!actual.equals(expected)) throw unavailable(); + } + + private static UUID candidateId(Record row) { + return typedUuid(row, "participation_id"); + } + + private static UUID typedUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || value.equals(NIL_UUID)) throw unavailable(); + return value; + } + + private static String requiredUuidString(Record row, String field) { + return typedUuid(row, field).toString(); + } + + private static String requiredString(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw unavailable(); + return value; + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) throw unavailable(); + return value.clone(); + } + + private static OffsetDateTime requiredTimestamp(Record row, String field) { + OffsetDateTime value = row.get(field, OffsetDateTime.class); + if (value == null) throw unavailable(); + return value; + } + + private static long number(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) throw unavailable(); + return value; + } + + private static long positive(long value, String field) { + if (value <= 0L) throw unavailable(); + return value; + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) throw new IllegalArgumentException(field + " must be positive"); + } + + private static void requireNonnil(UUID value, String field) { + if (value == null || value.equals(NIL_UUID)) + throw new IllegalArgumentException(field + " must be nonnil"); + } + + private static String string(Object value) { + if (!(value instanceof String text)) throw unavailable(); + return text; + } + + private static String digestPrefixed(byte[] bytes) { + return "sha256:" + digestHex(bytes); + } + + private static String digestHex(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + }); + } + + private static IllegalStateException conflict() { + return new IllegalStateException( + "StartSession World participation conflicts with its immutable binding"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Exact StartSession World participation evidence unavailable"); + } + + public record Candidate( + StartSessionPostAuthorizationExecutionTuple originalTuple, + AccountStartSessionAuthorityCapture capture, + UUID canonicalGameInstanceId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + String preparationInputJson, + String preparationInputDigest) { + public Candidate { + Objects.requireNonNull(originalTuple, "typed original StartSession tuple is required"); + Objects.requireNonNull(capture, "exact retained Account capture is required"); + requireNonnil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonnil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + Objects.requireNonNull(preparationInputJson, "exact preparation input JSON is required"); + Objects.requireNonNull(preparationInputDigest, "preparation input digest is required"); + if (!"StartSession".equals(originalTuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(originalTuple.preAuthorizationTuple().targetOwner()) + || !capture.controlPlaneRequestId().equals(originalTuple.controlPlaneRequestId()) + || preparationInputJson.isBlank() + || !StandardCharsets.UTF_8.newEncoder().canEncode(preparationInputJson) + || preparationInputJson.getBytes(StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + || !PREPARATION_DIGEST.matcher(preparationInputDigest).matches() + || !digestPrefixed(preparationInputJson.getBytes(StandardCharsets.UTF_8)) + .equals(preparationInputDigest)) { + throw new IllegalArgumentException( + "StartSession World participation candidate is malformed"); + } + sourceVector(capture.snapshotBytes(), originalTuple.controlPlaneRequestId()); + } + + public byte[] originalPostAuthorizationTuple() { + return originalTuple.canonicalBytes(); + } + + public String controlPlaneRequestId() { + return originalTuple.controlPlaneRequestId(); + } + + public String targetNamespace() { + return originalTuple.preAuthorizationTuple().action().scope().targetNamespace(); + } + + public UUID canonicalTenantId() { + return originalTuple.preAuthorizationTuple().action().scope().tenantId(); + } + + @Override + public String toString() { + return "Candidate[requestId=" + controlPlaneRequestId() + ", preparationInput=]"; + } + } + + public record StoredParticipation( + UUID participationId, + long participationFence, + String controlPlaneRequestId, + byte[] originalPostAuthorizationTuple, + String targetNamespace, + UUID canonicalTenantId, + UUID canonicalGameInstanceId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + String preparationInputJson, + String preparationInputDigest, + long producerXid, + OffsetDateTime createdAt, + List sources) { + public StoredParticipation { + requireNonnil(participationId, "participationId"); + requirePositive(participationFence, "participationFence"); + Objects.requireNonNull(controlPlaneRequestId); + originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + requireNonnil(canonicalTenantId, "canonicalTenantId"); + requireNonnil(canonicalGameInstanceId, "canonicalGameInstanceId"); + requireNonnil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + requirePositive(producerXid, "producerXid"); + Objects.requireNonNull(preparationInputJson); + Objects.requireNonNull(preparationInputDigest); + Objects.requireNonNull(createdAt); + sources = List.copyOf(sources); + } + + @Override + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + @Override + public String toString() { + return "StoredParticipation[id=" + + participationId + + ", fence=" + + participationFence + + ", requestId=" + + controlPlaneRequestId + + ", sources=" + + sources.size() + + "]"; + } + + public List sourceVector() { + return sources; + } + } + + public record StoredSettlement( + UUID participationId, + WorldStartSessionExecutionTerminal.Outcome outcome, + long worldExecutionFence, + byte[] terminalBytes, + String terminalDigest, + OffsetDateTime settledAt) { + public StoredSettlement { + requireNonnil(participationId, "participationId"); + Objects.requireNonNull(outcome); + requirePositive(worldExecutionFence, "worldExecutionFence"); + terminalBytes = terminalBytes.clone(); + Objects.requireNonNull(terminalDigest); + Objects.requireNonNull(settledAt); + } + + @Override + public byte[] terminalBytes() { + return terminalBytes.clone(); + } + + @Override + public String toString() { + return "StoredSettlement[id=" + + participationId + + ", outcome=" + + outcome + + ", fence=" + + worldExecutionFence + + "]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java index 80a00a7a86..0f1e39490e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java @@ -14,6 +14,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.function.Function; import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; @@ -31,10 +32,12 @@ import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import tools.jackson.core.StreamReadFeature; import tools.jackson.core.type.TypeReference; @@ -78,6 +81,7 @@ public final class AccountStartSessionOperatorAuthorizationService { private final String loggingPeerUri; private final String gameSessionPeerUri; private final String gameDesignPeerUri; + private final String worldManagementPeerUri; private final long referenceLifetimeMillis; private final long responseRecoveryWindowMillis; @@ -123,6 +127,7 @@ public AccountStartSessionOperatorAuthorizationService( loggingPeerUri = exactPeer(exactLoggingPeerUri, "logging-admin-service"); gameSessionPeerUri = exactPeer(exactGameSessionPeerUri, "game-session-service"); gameDesignPeerUri = sameNamespacePeer(gameSessionPeerUri, "game-design-service"); + worldManagementPeerUri = sameNamespacePeer(gameSessionPeerUri, "world-management-service"); referenceLifetimeMillis = policyMillis(referenceLifetime, "reference lifetime", 5 * 60_000L); responseRecoveryWindowMillis = policyMillis(responseRecoveryWindow, "response recovery window", 60_000L); @@ -650,6 +655,135 @@ public RedeemedOperationProjection readRedeemedOperationProjection( }); } + /** + * Revalidates the original human StartSession authority for a package-local World participation + * mutation and invokes the supplied Account-local mutation callback after locking its exact + * durable source capture in the same Account transaction. This is only a currentness building + * block: it does not authenticate caller-provided Game Session evidence or constitute a complete + * World participation service. A future caller must obtain genuine Game Session proof before + * invoking it. No end-user credential is accepted on this World-only path. + * + *

The canonical tuple is decoded only after authenticating the exact derived same-namespace + * World peer. All input bytes and the actual redeemed Game Session attempt/fence are compared to + * Account's original issuance and redemption; this path never issues, redeems, allocates, or + * renews authority. + */ + T withCurrentWorldReceivingParticipationCurrentness( + byte[] exactCanonicalPostAuthorizationTuple, + UUID actualGameSessionOwnerAttemptId, + long actualGameSessionOwnerFence, + Function accountMutation) { + requirePeer(worldManagementPeerUri); + requireNoAmbientTransactionOrSynchronization(); + + byte[] exactPostTupleBytes = copy(exactCanonicalPostAuthorizationTuple); + StartSessionPostAuthorizationExecutionTuple postTuple = + StartSessionPostAuthorizationExecutionTuple.decode(exactPostTupleBytes); + Objects.requireNonNull(accountMutation, "Account-local participation mutation is required"); + StartSessionPreAuthorizationReservationTuple tuple = postTuple.preAuthorizationTuple(); + if (!"game-session-service".equals(tuple.targetOwner())) { + throw denied("Original StartSession target owner must remain Game Session"); + } + GrpcPeerIdentity worldPeer = GrpcPeerIdentity.current(); + if (worldPeer == null + || !tuple.action().scope().targetNamespace().equals(worldPeer.namespace())) { + throw denied("StartSession target namespace does not match the authenticated World peer"); + } + if (!loggingPeerUri.equals(postTuple.authenticatedWorkloadIdentity())) { + throw denied("Original StartSession Logging workload identity changed"); + } + requireNonNilUuid(actualGameSessionOwnerAttemptId, "actual Game Session owner attempt ID"); + requirePositiveFence(actualGameSessionOwnerFence, "actual Game Session owner fence"); + + byte[] exactPreTupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + IssuanceRecord observed = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireOriginalBinding( + observed, + tuple, + exactPreTupleBytes, + postTuple.reservationOwnerId(), + postTuple.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle observedBundle = + AccountStartSessionOperatorAuthorityBundle.decode(observed.authorityEvidenceBundle()); + observedBundle.requireTupleBinding(tuple); + requireWorldReceivingPostTupleBinding(postTuple, observed, tuple); + ReadRedeemedOperationProjectionRequest redemptionRequest = + new ReadRedeemedOperationProjectionRequest( + exactPreTupleBytes, + postTuple.authorizationReferenceFingerprint(), + postTuple.reservationOwnerId(), + postTuple.reservationClaimFence(), + actualGameSessionOwnerAttemptId, + actualGameSessionOwnerFence); + requireRedeemedProjectionBinding( + observed, tuple, redemptionRequest, observedBundle, clock.instant()); + + var environment = hostedTerms.captureCurrentEnvironmentBoundary(); + return actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + observedBundle.controlUiTokenJti(), + environment, + current -> { + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredRedemption(observed, exact); + requireOriginalBinding( + exact, + tuple, + exactPreTupleBytes, + postTuple.reservationOwnerId(), + postTuple.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()); + exactBundle.requireTupleBinding(tuple); + requireWorldReceivingPostTupleBinding(postTuple, exact, tuple); + requireRedeemedProjectionBinding( + exact, tuple, redemptionRequest, exactBundle, clock.instant()); + + AccountStartSessionAuthorityCapture lockedCapture = + captureRepository.lockReadExactCurrent( + current, + tuple, + loggingPeerUri, + postTuple.reservationOwnerId(), + postTuple.reservationClaimFence()); + var originalReference = + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()); + exactBundle.requireCaptureBinding(lockedCapture, tuple, originalReference); + exactBundle.requireCurrent( + current.source(), current.stored(), tuple, originalReference, clock.instant()); + return accountMutation.apply(lockedCapture); + }); + } + + private void requireWorldReceivingPostTupleBinding( + StartSessionPostAuthorizationExecutionTuple supplied, + IssuanceRecord original, + StartSessionPreAuthorizationReservationTuple tuple) { + StartSessionPostAuthorizationExecutionTuple expected = + StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + original.issuanceWorkloadUri(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.authorityEvidenceBundle(), + original.bundleReference()); + if (!MessageDigest.isEqual(expected.canonicalBytes(), supplied.canonicalBytes())) { + throw denied("World participation tuple differs from the original Account issuance"); + } + } + + private static void requireNoAmbientTransactionOrSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw denied("World currentness must begin without an ambient Account transaction"); + } + } + private PreparedIssuance prepareIssuance( Stored controlUiIssuance, AccountStartSessionAuthorityCapture capture, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java new file mode 100644 index 0000000000..5b3e786ca4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java @@ -0,0 +1,198 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredSettlement; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadClient; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadGrpcCodec; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadRequest; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Account composition that settles only authenticated exact World StartSession + * terminal readback. Historical settlement is not fresh authorization, admission, or renewal. + * + *

The World owner recovery verifier and Game Session original-claim producer remain separate + * prerequisites; this composition alone is not end-to-end execution proof. + */ +public final class AccountStartSessionWorldParticipationSettlementService { + private final AccountStartSessionWorldParticipationRepository repository; + private final WorldStartSessionExecutionTerminalReadClient worldClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public AccountStartSessionWorldParticipationSettlementService( + AccountStartSessionWorldParticipationRepository repository, + WorldStartSessionExecutionTerminalReadClient worldClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "participation repository is required"); + this.worldClient = Objects.requireNonNull(worldClient, "World terminal client is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Settles or recovers one exact participation using World-owned historical terminal evidence. The + * request supplies only the immutable participation lookup identity; all terminal-read fields are + * derived from Account's retained participation. + */ + public StoredSettlement settle(UUID participationId, long participationFence) { + requireWorldPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(participationId, "participationId is required"); + if (participationId.equals(new UUID(0L, 0L)) || participationFence <= 0L) { + throw new IllegalArgumentException("Non-nil participation ID and positive fence required"); + } + + Lookup lookup = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> { + StoredParticipation participation = + repository + .findHistoricalExact(participationId, participationFence) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Exact historical World participation is unavailable") + .asRuntimeException()); + if (!workloadNamespace.equals(participation.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription( + "World participation target namespace differs from authenticated peer") + .asRuntimeException(); + } + Optional settled = + repository.findSettlementExact(participationId, participationFence); + return new Lookup(participation, settled.orElse(null)); + }), + "Account participation lookup transaction returned no result"); + if (lookup.settlement() != null) return lookup.settlement(); + + WorldStartSessionExecutionTerminalReadRequest request = requestFor(lookup.participation()); + requireNoAmbientTransaction(); + WorldStartSessionExecutionTerminal terminal = worldClient.read(request); + if (terminal == null) { + throw Status.FAILED_PRECONDITION + .withDescription( + "World StartSession execution remains unresolved without exact terminal proof") + .asRuntimeException(); + } + // Reuse the closed Common codec's complete identity check. The client already performs this + // decode for a real response; this round trip keeps the service boundary explicit and testable. + var response = WorldStartSessionExecutionTerminalReadGrpcCodec.toResponse(request, terminal); + WorldStartSessionExecutionTerminal exactTerminal = + WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse(request, response); + + requireNoAmbientTransaction(); + StoredSettlement committed = + Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.settleExact(exactTerminal)), + "Account terminal settlement transaction returned no receipt"); + + // This lookup-only transaction establishes durable post-commit readback. It must not call + // settleExact again, since doing so could hide an uncertain first commit as an exact replay. + requireNoAmbientTransaction(); + StoredSettlement readback = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository + .findSettlementExact(participationId, participationFence) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Committed World terminal settlement is not readable") + .asRuntimeException())), + "Account terminal settlement readback transaction returned no receipt"); + if (!sameSettlement(committed, readback)) { + throw Status.FAILED_PRECONDITION + .withDescription("Committed World terminal settlement readback differs") + .asRuntimeException(); + } + return readback; + } + + private WorldStartSessionExecutionTerminalReadRequest requestFor( + StoredParticipation participation) { + return new WorldStartSessionExecutionTerminalReadRequest( + freshReadId(participation), + participation.targetNamespace(), + participation.originalPostAuthorizationTuple(), + participation.participationId(), + participation.participationFence(), + participation.gameSessionOwnerAttemptId(), + participation.gameSessionOwnerFence(), + participation.canonicalGameInstanceId(), + participation.preparationInputJson()); + } + + private static UUID freshReadId(StoredParticipation participation) { + UUID readId; + do { + readId = UUID.randomUUID(); + } while (readId.equals(participation.participationId()) + || readId.equals(participation.gameSessionOwnerAttemptId()) + || readId.equals(participation.canonicalGameInstanceId()) + || readId.equals( + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple + .decode(participation.originalPostAuthorizationTuple()) + .reservationOwnerId())); + return readId; + } + + private void requireWorldPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified World workload identity required") + .asRuntimeException(); + } + if (SessionContext.hasAuthenticatedCallerContext() + || !workloadNamespace.equals(peer.namespace()) + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service")) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("World terminal settlement requires independent Account transactions") + .asRuntimeException(); + } + } + + private static boolean sameSettlement(StoredSettlement left, StoredSettlement right) { + return left.participationId().equals(right.participationId()) + && left.outcome() == right.outcome() + && left.worldExecutionFence() == right.worldExecutionFence() + && left.terminalDigest().equals(right.terminalDigest()) + && java.util.Arrays.equals(left.terminalBytes(), right.terminalBytes()); + } + + private record Lookup(StoredParticipation participation, StoredSettlement settlement) {} +} diff --git a/services/account-service/src/main/resources/db/migration/V127__selected_inventory_empty_arrays.sql b/services/account-service/src/main/resources/db/migration/V127__selected_inventory_empty_arrays.sql index b307544bcc..cc6fdb9955 100644 --- a/services/account-service/src/main/resources/db/migration/V127__selected_inventory_empty_arrays.sql +++ b/services/account-service/src/main/resources/db/migration/V127__selected_inventory_empty_arrays.sql @@ -7,6 +7,10 @@ ALTER TABLE account_selected_publication_sources DO $migration$ DECLARE original TEXT; + region_anchor_count INTEGER; + region_replacement_count INTEGER; + spawn_anchor_count INTEGER; + spawn_replacement_count INTEGER; region_anchor TEXT := $anchor$ OR (SELECT jsonb_agg(entry ORDER BY entry->>'regionTemplateId') FROM jsonb_array_elements(model->'regionGeneratorInputs') entry) IS DISTINCT FROM model->'regionGeneratorInputs'$anchor$; @@ -22,12 +26,30 @@ DECLARE BEGIN SELECT pg_get_functiondef('require_selected_inventory_operation_v2(BYTEA)'::REGPROCEDURE) INTO STRICT original; - IF (length(original) - length(replace(original, region_anchor, ''))) / length(region_anchor) <> 1 - OR (length(original) - length(replace(original, spawn_anchor, ''))) / length(spawn_anchor) <> 1 THEN + region_anchor_count := + (length(original) - length(replace(original, region_anchor, ''))) / length(region_anchor); + region_replacement_count := + (length(original) - length(replace(original, region_replacement, ''))) / length(region_replacement); + spawn_anchor_count := + (length(original) - length(replace(original, spawn_anchor, ''))) / length(spawn_anchor); + spawn_replacement_count := + (length(original) - length(replace(original, spawn_replacement, ''))) / length(spawn_replacement); + IF region_anchor_count + region_replacement_count <> 1 + OR spawn_anchor_count + spawn_replacement_count <> 1 THEN RAISE EXCEPTION 'Expected exactly one V108 ordering guard for each selected inventory input array'; END IF; - original := replace(original, region_anchor, region_replacement); - original := replace(original, spawn_anchor, spawn_replacement); + IF region_anchor_count = 1 THEN + original := replace(original, region_anchor, region_replacement); + END IF; + IF spawn_anchor_count = 1 THEN + original := replace(original, spawn_anchor, spawn_replacement); + END IF; + IF (length(original) - length(replace(original, region_replacement, ''))) / length(region_replacement) <> 1 + OR (length(original) - length(replace(original, region_anchor, ''))) / length(region_anchor) <> 0 + OR (length(original) - length(replace(original, spawn_replacement, ''))) / length(spawn_replacement) <> 1 + OR (length(original) - length(replace(original, spawn_anchor, ''))) / length(spawn_anchor) <> 0 THEN + RAISE EXCEPTION 'Expected exactly one canonical ordering guard for each selected inventory input array'; + END IF; EXECUTE original; END; $migration$; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSelectedInventoryEmptyArraysMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSelectedInventoryEmptyArraysMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..eb39b3b184 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSelectedInventoryEmptyArraysMigrationPostgresIntegrationTest.java @@ -0,0 +1,259 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Consumer; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Physical V127 installation proof for both known V126 inventory guard shapes. */ +@Testcontainers(disabledWithoutDocker = true) +class AccountSelectedInventoryEmptyArraysMigrationPostgresIntegrationTest { + private static final String HISTORY_TABLE = ".flyway_schema_history"; + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void acceptsTheCurrentCoalescedV126DefinitionAndRetainsBothOrderingGuards() { + withVersion126( + context -> { + assertCanonicalOrderingGuards(functionDefinition(context)); + + migrateTo127(context); + + assertVersionApplied(context, "127"); + assertCanonicalOrderingGuards(functionDefinition(context)); + assertThat(sourceKeyLength(context)).isEqualTo(2048); + }); + } + + @Test + void upgradesTheOriginalV126OrderingAnchorsToCanonicalEmptyArrayGuards() { + withVersion126( + context -> { + String current = functionDefinition(context); + String originalAnchors = + replaceExactlyOnce( + replaceExactlyOnce(current, regionReplacement(), regionAnchor()), + spawnReplacement(), + spawnAnchor()); + executeFunctionDefinition(context, originalAnchors); + assertOriginalOrderingGuards(functionDefinition(context)); + + migrateTo127(context); + + assertVersionApplied(context, "127"); + assertCanonicalOrderingGuards(functionDefinition(context)); + assertThat(sourceKeyLength(context)).isEqualTo(2048); + }); + } + + @Test + void rejectsAMissingOrderingGuardAndRollsBackV127() { + withVersion126( + context -> { + String before = functionDefinition(context); + String missingRegion = replaceExactlyOnce(before, regionReplacement(), ""); + executeFunctionDefinition(context, missingRegion); + String preflightDefinition = functionDefinition(context); + Integer preflightSourceKeyLength = sourceKeyLength(context); + + assertV127RejectedWithoutChangingV126(context); + + assertThat(functionDefinition(context)).isEqualTo(preflightDefinition); + assertThat(sourceKeyLength(context)).isEqualTo(preflightSourceKeyLength); + }); + } + + @Test + void rejectsADuplicatedOrderingGuardAndRollsBackV127() { + withVersion126( + context -> { + String before = functionDefinition(context); + String duplicatedSpawn = + replaceExactlyOnce( + before, spawnReplacement(), spawnReplacement() + "\n" + spawnReplacement()); + executeFunctionDefinition(context, duplicatedSpawn); + String preflightDefinition = functionDefinition(context); + Integer preflightSourceKeyLength = sourceKeyLength(context); + + assertV127RejectedWithoutChangingV126(context); + + assertThat(functionDefinition(context)).isEqualTo(preflightDefinition); + assertThat(sourceKeyLength(context)).isEqualTo(preflightSourceKeyLength); + }); + } + + private static void withVersion126(Consumer proof) { + String schema = "selected_inventory_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + try { + migration(dataSource, schema, "126").migrate(); + TestContext context = new TestContext(schema, jdbc, dataSource); + assertVersionApplied(context, "126"); + assertVersionNotApplied(context, "127"); + proof.accept(context); + } finally { + jdbc.execute("DROP SCHEMA IF EXISTS " + quotedSchema(schema) + " CASCADE"); + } + } + + private static Flyway migration( + DriverManagerDataSource dataSource, String schema, String targetVersion) { + return Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion(targetVersion)) + .load(); + } + + private static void migrateTo127(TestContext context) { + migration(context.dataSource(), context.schema(), "127").migrate(); + } + + private static void assertV127RejectedWithoutChangingV126(TestContext context) { + assertThatThrownBy(() -> migrateTo127(context)) + .hasStackTraceContaining( + "Expected exactly one V108 ordering guard for each selected inventory input array"); + assertVersionApplied(context, "126"); + assertVersionNotApplied(context, "127"); + } + + private static String functionDefinition(TestContext context) { + String signature = + quotedSchema(context.schema()) + ".require_selected_inventory_operation_v2(bytea)"; + return Objects.requireNonNull( + context + .jdbc() + .queryForObject("SELECT pg_get_functiondef(?::regprocedure)", String.class, signature)); + } + + private static void executeFunctionDefinition(TestContext context, String definition) { + context.jdbc().execute(definition); + } + + private static void assertOriginalOrderingGuards(String definition) { + assertThat(countOccurrences(definition, regionAnchor())).isEqualTo(1); + assertThat(countOccurrences(definition, spawnAnchor())).isEqualTo(1); + assertThat(countOccurrences(definition, regionReplacement())).isZero(); + assertThat(countOccurrences(definition, spawnReplacement())).isZero(); + assertOrderingLoopsRemain(definition); + } + + private static void assertCanonicalOrderingGuards(String definition) { + assertThat(countOccurrences(definition, regionAnchor())).isZero(); + assertThat(countOccurrences(definition, spawnAnchor())).isZero(); + assertThat(countOccurrences(definition, regionReplacement())).isEqualTo(1); + assertThat(countOccurrences(definition, spawnReplacement())).isEqualTo(1); + assertOrderingLoopsRemain(definition); + } + + private static void assertOrderingLoopsRemain(String definition) { + assertThat(countOccurrences(definition, "previous_key COLLATE \"C\" >=")).isEqualTo(2); + } + + private static int sourceKeyLength(TestContext context) { + return Objects.requireNonNull( + context + .jdbc() + .queryForObject( + "SELECT character_maximum_length FROM information_schema.columns " + + "WHERE table_schema = ? AND table_name = 'account_selected_publication_sources' " + + "AND column_name = 'source_key'", + Integer.class, + context.schema())); + } + + private static void assertVersionApplied(TestContext context, String version) { + assertThat(historyCount(context, version)).isEqualTo(1); + } + + private static void assertVersionNotApplied(TestContext context, String version) { + assertThat(historyCount(context, version)).isZero(); + } + + private static int historyCount(TestContext context, String version) { + return Objects.requireNonNull( + context + .jdbc() + .queryForObject( + "SELECT count(*) FROM " + + quotedSchema(context.schema()) + + HISTORY_TABLE + + " WHERE version = ? AND success", + Integer.class, + version)); + } + + private static String regionAnchor() { + return orderingGuard("regionGeneratorInputs", "regionTemplateId", false); + } + + private static String regionReplacement() { + return orderingGuard("regionGeneratorInputs", "regionTemplateId", true); + } + + private static String spawnAnchor() { + return orderingGuard("spawnBindingInputs", "bindingTemplateId", false); + } + + private static String spawnReplacement() { + return orderingGuard("spawnBindingInputs", "bindingTemplateId", true); + } + + private static String orderingGuard(String inputArray, String orderKey, boolean coalesceEmpty) { + String aggregate = "jsonb_agg(entry ORDER BY entry->>'" + orderKey + "')"; + if (coalesceEmpty) aggregate = "coalesce(" + aggregate + ", '[]'::JSONB)"; + return " OR (SELECT " + + aggregate + + " FROM\n" + + " jsonb_array_elements(model->'" + + inputArray + + "') entry)\n" + + " IS DISTINCT FROM model->'" + + inputArray + + "'"; + } + + private static String replaceExactlyOnce(String source, String expected, String replacement) { + int first = source.indexOf(expected); + if (first < 0 || source.indexOf(expected, first + expected.length()) >= 0) { + throw new AssertionError("Expected exactly one fixture guard occurrence"); + } + return source.substring(0, first) + replacement + source.substring(first + expected.length()); + } + + private static int countOccurrences(String source, String value) { + int count = 0; + int offset = 0; + while ((offset = source.indexOf(value, offset)) >= 0) { + count++; + offset += value.length(); + } + return count; + } + + private static String quotedSchema(String schema) { + return "\"" + schema + "\""; + } + + private record TestContext( + String schema, JdbcTemplate jdbc, DriverManagerDataSource dataSource) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java new file mode 100644 index 0000000000..a7335e05db --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java @@ -0,0 +1,894 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.jooq.impl.DSL.field; +import static org.jooq.impl.DSL.name; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.Candidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCapture; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.SQLDataType; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Mocked jOOQ rows prove storage composition only, not PostgreSQL guards or authenticated proof. + */ +class AccountStartSessionWorldParticipationRepositoryTest { + private static final String REQUEST_ID = + "start-session/operator/2355f292-ab9c-458c-8d52-aef18b9254e8"; + private static final UUID ACTOR_ID = UUID.fromString("d888ddc4-4a62-4b25-9bab-c4f94860c2ca"); + private static final UUID TENANT_ID = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("ca1b63bf-f09f-4a55-96bf-a1fd2e22349e"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("51c67424-324e-486d-b3ad-45b6e85c1a0d"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"); + private static final UUID PARTICIPATION_ID = + UUID.fromString("fa3555ac-e039-4827-9e04-eb0fa8cd37d4"); + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final String LOGGING_URI = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final BundleReference BUNDLE_REFERENCE = + new BundleReference("authorityEvidenceBundle/v1", "11", "13", "17"); + private static final Field PARTICIPATION_ID_FIELD = + field(name("participation_id"), SQLDataType.UUID); + private static final Field PARTICIPATION_FENCE_FIELD = + field(name("participation_fence"), SQLDataType.BIGINT); + private static final Field REQUEST_ID_FIELD = + field(name("control_plane_request_id"), SQLDataType.VARCHAR); + private static final Field ORIGINAL_TUPLE_FIELD = + field(name("original_post_authorization_tuple"), SQLDataType.VARBINARY); + private static final Field NAMESPACE_FIELD = + field(name("target_namespace"), SQLDataType.VARCHAR); + private static final Field TENANT_FIELD = + field(name("canonical_tenant_id"), SQLDataType.UUID); + private static final Field GAME_INSTANCE_FIELD = + field(name("canonical_game_instance_id"), SQLDataType.UUID); + private static final Field OWNER_ATTEMPT_FIELD = + field(name("game_session_owner_attempt_id"), SQLDataType.UUID); + private static final Field OWNER_FENCE_FIELD = + field(name("game_session_owner_fence"), SQLDataType.BIGINT); + private static final Field PREPARATION_JSON_FIELD = + field(name("preparation_input_json"), SQLDataType.VARCHAR); + private static final Field PREPARATION_DIGEST_FIELD = + field(name("preparation_input_digest"), SQLDataType.VARCHAR); + private static final Field PRODUCER_XID_FIELD = + field(name("producer_xid"), SQLDataType.BIGINT); + private static final Field CREATED_AT_FIELD = + field(name("created_at"), SQLDataType.OFFSETDATETIME); + private static final Field UNKNOWN_FIELD = + field(name("future_unreviewed_column"), SQLDataType.VARCHAR); + private static final Field CAPTURE_REQUEST_ID_FIELD = + field(name("control_plane_request_id"), SQLDataType.VARCHAR); + private static final Field CAPTURE_ACCOUNT_FIELD = + field(name("account_uuid"), SQLDataType.UUID); + private static final Field CAPTURE_TENANT_FIELD = + field(name("tenant_uuid"), SQLDataType.UUID); + private static final Field CAPTURE_TARGET_OWNER_FIELD = + field(name("target_owner"), SQLDataType.VARCHAR); + private static final Field CAPTURE_LOGGING_URI_FIELD = + field(name("logging_workload_uri"), SQLDataType.VARCHAR); + private static final Field CAPTURE_RESERVATION_OWNER_FIELD = + field(name("reservation_owner_id"), SQLDataType.UUID); + private static final Field CAPTURE_RESERVATION_FENCE_FIELD = + field(name("reservation_claim_fence"), SQLDataType.BIGINT); + private static final Field CAPTURE_PRE_TUPLE_FIELD = + field(name("pre_authorization_tuple"), SQLDataType.VARBINARY); + private static final Field CAPTURE_MUTATION_DIGEST_FIELD = + field(name("mutation_digest"), SQLDataType.VARCHAR); + private static final Field CAPTURE_OPERATION_ID_FIELD = + field(name("control_ui_operation_id"), SQLDataType.UUID); + private static final Field CAPTURE_TOKEN_JTI_FIELD = + field(name("control_ui_token_jti"), SQLDataType.UUID); + private static final Field CAPTURE_TOKEN_HASH_FIELD = + field(name("control_ui_token_hash"), SQLDataType.VARCHAR); + private static final Field CAPTURE_RECEIPT_DIGEST_FIELD = + field(name("control_ui_signer_receipt_sha256"), SQLDataType.VARCHAR); + private static final Field CAPTURE_ISSUANCE_FENCE_FIELD = + field(name("issuance_fence"), SQLDataType.BIGINT); + private static final Field CAPTURE_ISSUANCE_SOURCE_VERSION_FIELD = + field(name("issuance_fence_source_version"), SQLDataType.BIGINT); + private static final Field CAPTURED_AT_FIELD = + field(name("captured_at"), SQLDataType.OFFSETDATETIME); + private static final Field CAPTURE_SNAPSHOT_DIGEST_FIELD = + field(name("snapshot_sha256"), SQLDataType.VARCHAR); + private static final Field CAPTURE_SNAPSHOT_BYTES_FIELD = + field(name("canonical_snapshot_bytes"), SQLDataType.VARBINARY); + private static final Field CAPTURE_SOURCE_VERSION_FIELD = + field(name("source_version"), SQLDataType.BIGINT); + private static final Field CAPTURE_SOURCE_FENCE_FIELD = + field(name("source_fence"), SQLDataType.BIGINT); + private static final Field CAPTURE_LINEARIZATION_FIELD = + field(name("linearization"), SQLDataType.VARCHAR); + private static final Field CAPTURE_CANONICAL_DIGEST_FIELD = + field(name("canonical_sha256"), SQLDataType.VARCHAR); + private static final Field CAPTURE_CANONICAL_BYTES_FIELD = + field(name("canonical_capture_bytes"), SQLDataType.VARBINARY); + private static final Field CAPTURE_CREATED_AT_FIELD = + field(name("created_at"), SQLDataType.OFFSETDATETIME); + private static final Field SOURCE_PARTICIPATION_ID_FIELD = + field(name("participation_id"), SQLDataType.UUID); + private static final Field SOURCE_KEY_FIELD = + field(name("source_key"), SQLDataType.VARCHAR); + private static final Field SOURCE_EVIDENCE_FIELD = + field(name("source_evidence"), SQLDataType.VARBINARY); + private static final Field SETTLEMENT_PARTICIPATION_ID_FIELD = + field(name("participation_id"), SQLDataType.UUID); + private static final Field SETTLEMENT_OUTCOME_FIELD = + field(name("outcome"), SQLDataType.VARCHAR); + private static final Field SETTLEMENT_WORLD_FENCE_FIELD = + field(name("world_execution_fence"), SQLDataType.BIGINT); + private static final Field SETTLEMENT_TERMINAL_BYTES_FIELD = + field(name("terminal_bytes"), SQLDataType.VARBINARY); + private static final Field SETTLEMENT_TERMINAL_DIGEST_FIELD = + field(name("terminal_digest"), SQLDataType.VARCHAR); + private static final Field SETTLEMENT_SETTLED_AT_FIELD = + field(name("settled_at"), SQLDataType.OFFSETDATETIME); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void typedReadbackRetainsTheExactCandidateAndRejectsChangedImmutableFields() { + Fixture fixture = fixture(); + StoredParticipation stored = + AccountStartSessionWorldParticipationRepository.decodeParticipation( + participationRow(fixture.candidate()), List.of(fixture.source())); + + AccountStartSessionWorldParticipationRepository.requireSameCandidate( + fixture.candidate(), stored); + assertThat(stored.participationId()).isEqualTo(PARTICIPATION_ID); + assertThat(stored.participationFence()).isEqualTo(41L); + assertThat(stored.producerXid()).isEqualTo(2_147_483_651L); + assertThat(stored.originalPostAuthorizationTuple()) + .containsExactly(fixture.candidate().originalPostAuthorizationTuple()); + + Candidate changedPreparation = + new Candidate( + fixture.candidate().originalTuple(), + fixture.candidate().capture(), + fixture.candidate().canonicalGameInstanceId(), + fixture.candidate().gameSessionOwnerAttemptId(), + fixture.candidate().gameSessionOwnerFence(), + "{\"changed\":true}", + digest("{\"changed\":true}")); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationRepository.requireSameCandidate( + changedPreparation, stored)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + + @Test + void participationReadbackRejectsUnknownDatabaseColumns() { + Fixture fixture = fixture(); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationRepository.decodeParticipation( + participationRow(fixture.candidate(), true), List.of(fixture.source()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + } + + @Test + void sourceReadbackRejectsMissingAndSubstitutedChildren() { + Fixture fixture = fixture(); + SourceEvidence substituted = + new SourceEvidence( + SourceKind.ACCOUNT, + ACTOR_ID.toString(), + "1", + "2", + "account/test", + "1", + bytes("substituted evidence")); + + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationRepository.requireExactSources( + List.of(fixture.source()), List.of())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationRepository.requireExactSources( + List.of(fixture.source()), List.of(substituted))) + .isInstanceOf(IllegalStateException.class); + AccountStartSessionWorldParticipationRepository.requireExactSources( + List.of(fixture.source()), List.of(fixture.source())); + } + + @Test + void terminalMustRepeatEveryStoredIdentityAndPreparationField() { + Fixture fixture = fixture(); + Candidate candidate = fixture.candidate(); + StoredParticipation stored = + AccountStartSessionWorldParticipationRepository.decodeParticipation( + participationRow(candidate), List.of(fixture.source())); + WorldStartSessionExecutionTerminal exact = terminal(candidate, 41L, OWNER_ATTEMPT_ID, 8L); + + AccountStartSessionWorldParticipationRepository.requireTerminalMatches(stored, exact); + + WorldStartSessionExecutionTerminal changedAttempt = + terminal(candidate, 41L, UUID.fromString("274c7a54-2f2a-409f-9eac-7b8a7733e590"), 8L); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationRepository.requireTerminalMatches( + stored, changedAttempt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + + @Test + void persistenceDeniesAbsentReadOnlyAndWrongIsolationTransactionsBeforeSql() { + AtomicInteger databaseCalls = new AtomicInteger(); + MockDataProvider provider = + context -> { + databaseCalls.incrementAndGet(); + return new MockResult[0]; + }; + var repository = + new AccountStartSessionWorldParticipationRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + Candidate candidate = fixture().candidate(); + + assertThatThrownBy(() -> repository.createOrReadExact(candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.createOrReadExact(candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + TransactionSynchronizationManager.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + Connection.TRANSACTION_SERIALIZABLE); + assertThatThrownBy(() -> repository.createOrReadExact(candidate)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + assertThat(databaseCalls.get()).isZero(); + } + + @Test + void findCurrentExactReadsRetainedCaptureParentAndEveryChildWithoutWriting() throws Exception { + Fixture fixture = fixture(); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, null); + beginWritableTransaction(); + + var found = repository.findCurrentExact(fixture.candidate()); + + assertThat(found).isPresent(); + assertThat(found.orElseThrow().participationId()).isEqualTo(PARTICIPATION_ID); + assertThat(found.orElseThrow().sources()).hasSize(1); + assertThat(found.orElseThrow().sources().get(0).canonicalBytes()) + .containsExactly(fixture.source().canonicalBytes()); + assertThat(reads) + .anyMatch(sql -> sql.contains("account_start_session_authority_captures")) + .anyMatch(sql -> sql.contains("account_start_session_world_participations")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_sources")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_settlements")); + assertThat(reads) + .allMatch(sql -> !sql.toLowerCase(java.util.Locale.ROOT).contains("for update")); + assertThat(writes.get()).isNull(); + } + + @Test + void settleExactInsertsAndReadsBackTheSameTypedTerminalAfterHistoricalIdentityCheck() + throws Exception { + Fixture fixture = fixture(); + WorldStartSessionExecutionTerminal terminal = + terminal(fixture.candidate(), 41L, OWNER_ATTEMPT_ID, 8L); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, terminal); + beginWritableTransaction(); + + var stored = repository.settleExact(terminal); + + assertThat(stored.participationId()).isEqualTo(PARTICIPATION_ID); + assertThat(stored.outcome()).isEqualTo(terminal.outcome()); + assertThat(stored.worldExecutionFence()).isEqualTo(terminal.worldExecutionFence()); + assertThat(stored.terminalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(stored.terminalDigest()).isEqualTo(terminal.digest()); + assertThat(reads) + .anyMatch(sql -> sql.contains("account_start_session_authority_captures")) + .anyMatch(sql -> sql.contains("account_start_session_world_participations")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_sources")) + .anyMatch( + sql -> + sql.startsWith("INSERT INTO account_start_session_world_participation_settlements")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_settlements")); + assertThat(writes.get()).isNotNull().hasSize(5); + assertThat(writes.get()[0]).isEqualTo(PARTICIPATION_ID); + assertThat(writes.get()[1]).isEqualTo(terminal.outcome().name()); + assertThat(writes.get()[2]).isEqualTo(terminal.worldExecutionFence()); + assertThat((byte[]) writes.get()[3]).containsExactly(terminal.canonicalBytes()); + assertThat(writes.get()[4]).isEqualTo(terminal.digest()); + } + + @Test + void settleExactRejectsSubstitutedOriginalAttemptBeforeSettlementInsert() throws Exception { + Fixture fixture = fixture(); + WorldStartSessionExecutionTerminal changedAttempt = + terminal( + fixture.candidate(), 41L, UUID.fromString("274c7a54-2f2a-409f-9eac-7b8a7733e590"), 8L); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, null); + beginWritableTransaction(); + + assertThatThrownBy(() -> repository.settleExact(changedAttempt)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + assertThat(writes.get()).isNull(); + } + + @Test + void findSettlementExactReadsBackOnlyTheExactHistoricalReceiptWithoutWriting() throws Exception { + Fixture fixture = fixture(); + WorldStartSessionExecutionTerminal terminal = + terminal(fixture.candidate(), 41L, OWNER_ATTEMPT_ID, 8L); + List sqlCalls = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, sqlCalls, writes, terminal); + beginWritableTransaction(); + + var found = repository.findSettlementExact(PARTICIPATION_ID, 41L); + + assertThat(found).isPresent(); + assertThat(found.orElseThrow().terminalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(found.orElseThrow().terminalDigest()).isEqualTo(terminal.digest()); + assertThat(sqlCalls) + .anyMatch(sql -> sql.contains("account_start_session_authority_captures")) + .anyMatch(sql -> sql.contains("account_start_session_world_participations")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_sources")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_settlements")); + assertThat(sqlCalls) + .allMatch(sql -> !sql.toLowerCase(java.util.Locale.ROOT).contains("for update")); + assertThat(writes.get()).isNull(); + } + + @Test + void findSettlementExactReturnsEmptyForMissingReceiptOrParticipationWithoutWriting() + throws Exception { + Fixture fixture = fixture(); + List missingReceiptCalls = new java.util.ArrayList<>(); + AtomicReference missingReceiptWrites = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository missingReceiptRepository = + mockedRepository(fixture, missingReceiptCalls, missingReceiptWrites, null); + beginWritableTransaction(); + + assertThat(missingReceiptRepository.findSettlementExact(PARTICIPATION_ID, 41L)).isEmpty(); + assertThat(missingReceiptWrites.get()).isNull(); + + TransactionSynchronizationManager.clear(); + List missingParentCalls = new java.util.ArrayList<>(); + AtomicReference missingParentWrites = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository missingParentRepository = + mockedRepository(fixture, missingParentCalls, missingParentWrites, null, true); + beginWritableTransaction(); + + assertThat(missingParentRepository.findSettlementExact(PARTICIPATION_ID, 41L)).isEmpty(); + assertThat(missingParentWrites.get()).isNull(); + assertThat(missingParentCalls) + .noneMatch(sql -> sql.contains("account_start_session_world_participation_settlements")); + } + + @Test + void findSettlementExactRejectsReceiptWithSubstitutedOriginalAttemptWithoutWriting() + throws Exception { + Fixture fixture = fixture(); + WorldStartSessionExecutionTerminal changedAttempt = + terminal( + fixture.candidate(), 41L, UUID.fromString("274c7a54-2f2a-409f-9eac-7b8a7733e590"), 8L); + List sqlCalls = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, sqlCalls, writes, changedAttempt); + beginWritableTransaction(); + + assertThatThrownBy(() -> repository.findSettlementExact(PARTICIPATION_ID, 41L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + assertThat(writes.get()).isNull(); + } + + private static AccountStartSessionWorldParticipationRepository mockedRepository( + Fixture fixture, + List sqlCalls, + AtomicReference writes, + WorldStartSessionExecutionTerminal settlement) + throws Exception { + return mockedRepository(fixture, sqlCalls, writes, settlement, false); + } + + private static AccountStartSessionWorldParticipationRepository mockedRepository( + Fixture fixture, + List sqlCalls, + AtomicReference writes, + WorldStartSessionExecutionTerminal settlement, + boolean missingParticipation) + throws Exception { + DSLContext dsl = mock(DSLContext.class); + Connection connection = mock(Connection.class); + when(connection.getAutoCommit()).thenReturn(false); + when(connection.isReadOnly()).thenReturn(false); + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_READ_COMMITTED); + doAnswer( + invocation -> { + invocation.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + sqlCalls.add(sql); + if (sql.contains("account_start_session_authority_captures")) { + return captureRow(fixture.candidate()); + } + if (sql.contains("account_start_session_world_participations")) { + return missingParticipation ? null : participationRow(fixture.candidate()); + } + if (sql.contains("account_start_session_world_participation_settlements")) { + return settlement == null ? null : settlementRow(settlement); + } + throw new AssertionError("Unexpected participation repository query: " + sql); + }); + when(dsl.fetch(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + sqlCalls.add(sql); + if (!sql.contains("account_start_session_world_participation_sources")) { + throw new AssertionError( + "Unexpected participation repository result query: " + sql); + } + return sourceRows(PARTICIPATION_ID, fixture.source()); + }); + when(dsl.execute(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + sqlCalls.add(sql); + writes.set((Object[]) invocation.getRawArguments()[1]); + return 1; + }); + return new AccountStartSessionWorldParticipationRepository(dsl); + } + + private static void beginWritableTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static Record participationRow(Candidate candidate) { + return participationRow(candidate, false); + } + + private static Record participationRow(Candidate candidate, boolean withUnknownColumn) { + Record row; + if (withUnknownColumn) { + row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + PARTICIPATION_ID_FIELD, + PARTICIPATION_FENCE_FIELD, + REQUEST_ID_FIELD, + ORIGINAL_TUPLE_FIELD, + NAMESPACE_FIELD, + TENANT_FIELD, + GAME_INSTANCE_FIELD, + OWNER_ATTEMPT_FIELD, + OWNER_FENCE_FIELD, + PREPARATION_JSON_FIELD, + PREPARATION_DIGEST_FIELD, + PRODUCER_XID_FIELD, + CREATED_AT_FIELD, + UNKNOWN_FIELD); + row.setValue(UNKNOWN_FIELD, "unreviewed"); + } else { + row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + PARTICIPATION_ID_FIELD, + PARTICIPATION_FENCE_FIELD, + REQUEST_ID_FIELD, + ORIGINAL_TUPLE_FIELD, + NAMESPACE_FIELD, + TENANT_FIELD, + GAME_INSTANCE_FIELD, + OWNER_ATTEMPT_FIELD, + OWNER_FENCE_FIELD, + PREPARATION_JSON_FIELD, + PREPARATION_DIGEST_FIELD, + PRODUCER_XID_FIELD, + CREATED_AT_FIELD); + } + row.setValue(PARTICIPATION_ID_FIELD, PARTICIPATION_ID); + row.setValue(PARTICIPATION_FENCE_FIELD, 41L); + row.setValue(REQUEST_ID_FIELD, candidate.controlPlaneRequestId()); + row.setValue(ORIGINAL_TUPLE_FIELD, candidate.originalPostAuthorizationTuple()); + row.setValue(NAMESPACE_FIELD, candidate.targetNamespace()); + row.setValue(TENANT_FIELD, candidate.canonicalTenantId()); + row.setValue(GAME_INSTANCE_FIELD, candidate.canonicalGameInstanceId()); + row.setValue(OWNER_ATTEMPT_FIELD, candidate.gameSessionOwnerAttemptId()); + row.setValue(OWNER_FENCE_FIELD, candidate.gameSessionOwnerFence()); + row.setValue(PREPARATION_JSON_FIELD, candidate.preparationInputJson()); + row.setValue(PREPARATION_DIGEST_FIELD, candidate.preparationInputDigest()); + row.setValue(PRODUCER_XID_FIELD, 2_147_483_651L); + row.setValue(CREATED_AT_FIELD, OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC)); + return row; + } + + private static Record captureRow(Candidate candidate) { + var tuple = candidate.originalTuple(); + var capture = candidate.capture(); + Record row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + CAPTURE_REQUEST_ID_FIELD, + CAPTURE_ACCOUNT_FIELD, + CAPTURE_TENANT_FIELD, + CAPTURE_TARGET_OWNER_FIELD, + CAPTURE_LOGGING_URI_FIELD, + CAPTURE_RESERVATION_OWNER_FIELD, + CAPTURE_RESERVATION_FENCE_FIELD, + CAPTURE_PRE_TUPLE_FIELD, + CAPTURE_MUTATION_DIGEST_FIELD, + CAPTURE_OPERATION_ID_FIELD, + CAPTURE_TOKEN_JTI_FIELD, + CAPTURE_TOKEN_HASH_FIELD, + CAPTURE_RECEIPT_DIGEST_FIELD, + CAPTURE_ISSUANCE_FENCE_FIELD, + CAPTURE_ISSUANCE_SOURCE_VERSION_FIELD, + CAPTURED_AT_FIELD, + CAPTURE_SNAPSHOT_DIGEST_FIELD, + CAPTURE_SNAPSHOT_BYTES_FIELD, + CAPTURE_SOURCE_VERSION_FIELD, + CAPTURE_SOURCE_FENCE_FIELD, + CAPTURE_LINEARIZATION_FIELD, + CAPTURE_CANONICAL_DIGEST_FIELD, + CAPTURE_CANONICAL_BYTES_FIELD, + CAPTURE_CREATED_AT_FIELD); + row.setValue(CAPTURE_REQUEST_ID_FIELD, candidate.controlPlaneRequestId()); + row.setValue(CAPTURE_ACCOUNT_FIELD, tuple.preAuthorizationTuple().actor().accountId()); + row.setValue(CAPTURE_TENANT_FIELD, candidate.canonicalTenantId()); + row.setValue(CAPTURE_TARGET_OWNER_FIELD, "game-session-service"); + row.setValue(CAPTURE_LOGGING_URI_FIELD, tuple.authenticatedWorkloadIdentity()); + row.setValue(CAPTURE_RESERVATION_OWNER_FIELD, tuple.reservationOwnerId()); + row.setValue(CAPTURE_RESERVATION_FENCE_FIELD, tuple.reservationClaimFence()); + row.setValue( + CAPTURE_PRE_TUPLE_FIELD, + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8)); + row.setValue(CAPTURE_MUTATION_DIGEST_FIELD, tuple.mutationDigest()); + row.setValue( + CAPTURE_OPERATION_ID_FIELD, UUID.fromString("44444444-4444-4444-8444-444444444444")); + row.setValue(CAPTURE_TOKEN_JTI_FIELD, UUID.fromString("55555555-5555-4555-8555-555555555555")); + row.setValue(CAPTURE_TOKEN_HASH_FIELD, "b".repeat(64)); + row.setValue(CAPTURE_RECEIPT_DIGEST_FIELD, sha256Hex(bytes("receipt"))); + row.setValue(CAPTURE_ISSUANCE_FENCE_FIELD, 9L); + row.setValue(CAPTURE_ISSUANCE_SOURCE_VERSION_FIELD, 10L); + OffsetDateTime capturedAt = OffsetDateTime.parse(capture.capturedAt().replace("Z", "+00:00")); + row.setValue(CAPTURED_AT_FIELD, capturedAt); + row.setValue(CAPTURE_SNAPSHOT_DIGEST_FIELD, capture.snapshotSha256()); + row.setValue(CAPTURE_SNAPSHOT_BYTES_FIELD, capture.snapshotBytes()); + row.setValue(CAPTURE_SOURCE_VERSION_FIELD, capture.sourceVersion()); + row.setValue(CAPTURE_SOURCE_FENCE_FIELD, capture.sourceFence()); + row.setValue(CAPTURE_LINEARIZATION_FIELD, capture.linearization()); + row.setValue(CAPTURE_CANONICAL_DIGEST_FIELD, capture.canonicalSha256()); + row.setValue(CAPTURE_CANONICAL_BYTES_FIELD, capture.canonicalBytes()); + row.setValue(CAPTURE_CREATED_AT_FIELD, capturedAt); + return row; + } + + private static org.jooq.Result> sourceRows( + UUID participationId, SourceEvidence source) { + var context = DSL.using(SQLDialect.POSTGRES); + var result = + context.newResult(SOURCE_PARTICIPATION_ID_FIELD, SOURCE_KEY_FIELD, SOURCE_EVIDENCE_FIELD); + var row = + context.newRecord(SOURCE_PARTICIPATION_ID_FIELD, SOURCE_KEY_FIELD, SOURCE_EVIDENCE_FIELD); + row.setValue(SOURCE_PARTICIPATION_ID_FIELD, participationId); + row.setValue(SOURCE_KEY_FIELD, source.key()); + row.setValue(SOURCE_EVIDENCE_FIELD, source.canonicalBytes()); + result.add(row); + return result; + } + + private static Record settlementRow(WorldStartSessionExecutionTerminal terminal) { + Record row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + SETTLEMENT_PARTICIPATION_ID_FIELD, + SETTLEMENT_OUTCOME_FIELD, + SETTLEMENT_WORLD_FENCE_FIELD, + SETTLEMENT_TERMINAL_BYTES_FIELD, + SETTLEMENT_TERMINAL_DIGEST_FIELD, + SETTLEMENT_SETTLED_AT_FIELD); + row.setValue(SETTLEMENT_PARTICIPATION_ID_FIELD, terminal.accountWorldParticipationId()); + row.setValue(SETTLEMENT_OUTCOME_FIELD, terminal.outcome().name()); + row.setValue(SETTLEMENT_WORLD_FENCE_FIELD, terminal.worldExecutionFence()); + row.setValue(SETTLEMENT_TERMINAL_BYTES_FIELD, terminal.canonicalBytes()); + row.setValue(SETTLEMENT_TERMINAL_DIGEST_FIELD, terminal.digest()); + row.setValue(SETTLEMENT_SETTLED_AT_FIELD, OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC)); + return row; + } + + private static WorldStartSessionExecutionTerminal terminal( + Candidate candidate, long participationFence, UUID attemptId, long ownerFence) { + return new WorldStartSessionExecutionTerminal( + candidate.originalPostAuthorizationTuple(), + PARTICIPATION_ID, + participationFence, + attemptId, + ownerFence, + candidate.targetNamespace(), + candidate.canonicalTenantId(), + candidate.controlPlaneRequestId(), + candidate.canonicalGameInstanceId(), + candidate.preparationInputDigest(), + candidate.preparationInputJson(), + 19L, + WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + } + + private static Fixture fixture() { + SourceEvidence source = + new SourceEvidence( + SourceKind.ACCOUNT, + ACTOR_ID.toString(), + "1", + "1", + "account/test", + "1", + bytes("retained source evidence")); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + REQUEST_ID, + ACTOR_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "World participation repository proof")); + byte[] bundle = authorityBundle(preTuple); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + LOGGING_URI, + "arfp/v1/key-1/" + "a".repeat(64), + RESERVATION_OWNER_ID, + 7L, + bundle, + BUNDLE_REFERENCE); + byte[] snapshot = + AccountControlUiAuthority.canonical( + Map.ofEntries( + Map.entry("schema", "account-start-session-authority-snapshot/v1"), + Map.entry("controlPlaneRequestId", REQUEST_ID), + Map.entry( + "preAuthorizationTuple", + Base64.getEncoder() + .encodeToString(preTuple.canonicalJson().getBytes(StandardCharsets.UTF_8))), + Map.entry("mutationDigest", preTuple.mutationDigest()), + Map.entry("accountId", ACTOR_ID.toString()), + Map.entry("tenantId", TENANT_ID.toString()), + Map.entry("targetOwner", "game-session-service"), + Map.entry("loggingWorkloadUri", LOGGING_URI), + Map.entry("reservationOwnerId", RESERVATION_OWNER_ID.toString()), + Map.entry("reservationClaimFence", "7"), + Map.entry("controlUiOperationId", "44444444-4444-4444-8444-444444444444"), + Map.entry("controlUiTokenJti", "55555555-5555-4555-8555-555555555555"), + Map.entry("controlUiTokenHash", "b".repeat(64)), + Map.entry( + "controlUiSignerReceipt", Base64.getEncoder().encodeToString(bytes("receipt"))), + Map.entry("controlUiSignerReceiptSha256", sha256Hex(bytes("receipt"))), + Map.entry( + "sourceVectorEvidence", + Base64.getEncoder().encodeToString(source.canonicalBytes())), + Map.entry( + "sourceVector", + List.of(Base64.getEncoder().encodeToString(source.canonicalBytes()))), + Map.entry("outboxCheckpoints", List.of()), + Map.entry( + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 1L, + "tenantAuthorityGeneration", Map.of(TENANT_ID.toString(), 1L), + "membershipAuthorityGeneration", Map.of(TENANT_ID.toString(), 1L), + "privateRealmGrantVersions", List.of())), + Map.entry("membershipVersion", Map.of(TENANT_ID.toString(), 2L)), + Map.entry("accountIdentitySource", Map.of("source", "fixture")), + Map.entry("issuanceFence", "9"), + Map.entry("issuanceFenceSourceVersion", "10"))); + var capture = capture(REQUEST_ID, 11L, 13L, "17", "2026-10-09T00:00:00.000Z", snapshot); + String preparationJson = "{\"identity\":{\"worldSlug\":\"arena\"}}"; + Candidate candidate = + new Candidate( + tuple, + capture, + GAME_INSTANCE_ID, + OWNER_ATTEMPT_ID, + 8L, + preparationJson, + digest(preparationJson)); + return new Fixture(candidate, source); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = tuple.action().scope().tenantId().toString(); + String actor = tuple.actor().accountId().toString(); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 1L, + "tenantAuthorityGeneration", Map.of(tenant, 1L), + "membershipAuthorityGeneration", Map.of(tenant, 1L), + "privateRealmGrantVersions", List.of()); + return AccountControlUiAuthority.canonical( + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenant, "targetNamespace", "world-runtime"), + "actionFamily", + "StartSession", + "applicableAccountId", + actor, + "applicableTenantId", + tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "c".repeat(64), + "sourceEvidenceVersion", + BUNDLE_REFERENCE.sourceVersion(), + "projectionStatus", + "CURRENT", + "evaluatedAt", + NOW.toString(), + "expiresAt", + NOW.plusSeconds(180).toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + "44444444-4444-4444-8444-444444444444", + "controlPlaneRequestId", + REQUEST_ID, + "actionFamilyRequestIdentity", + Map.of("requestIdentityKind", "controlPlaneRequestId", "requestId", REQUEST_ID), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", authorityTuple, + "membershipVersion", Map.of(tenant, 2L), + "issuanceFence", "9", + "issuanceEvidence", + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", actor, + "controlUiTokenJti", "55555555-5555-4555-8555-555555555555", + "role", "tenantAdmin", + "accountGeneration", "1", + "tenantGeneration", "1"))); + } + + private static AccountStartSessionAuthorityCapture capture( + String requestId, + long sourceVersion, + long sourceFence, + String linearization, + String capturedAt, + byte[] snapshot) { + try { + Method factory = + net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCapture + .class + .getDeclaredMethod( + "create", + String.class, + long.class, + long.class, + String.class, + String.class, + byte[].class); + factory.setAccessible(true); + return (net.firedevops.firemud.accountservice.service.session + .AccountStartSessionAuthorityCapture) + factory.invoke( + null, requestId, sourceVersion, sourceFence, linearization, capturedAt, snapshot); + } catch (InvocationTargetException failure) { + if (failure.getCause() instanceof RuntimeException runtime) throw runtime; + throw new AssertionError("Unexpected capture fixture failure", failure.getCause()); + } catch (ReflectiveOperationException failure) { + throw new AssertionError("Could not create exact capture fixture", failure); + } + } + + private static String digest(String value) { + return "sha256:" + sha256Hex(value.getBytes(StandardCharsets.UTF_8)); + } + + private static String sha256Hex(byte[] bytes) { + try { + byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(bytes); + return java.util.HexFormat.of().formatHex(digest); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private record Fixture(Candidate candidate, SourceEvidence source) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java index 787941a593..a21bfe77d5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java @@ -45,6 +45,7 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; @@ -65,6 +66,8 @@ class AccountStartSessionOperatorAuthorizationServiceTest { private static final String GAME_SESSION_PEER = "spiffe://firemud/ns/test/sa/game-session-service"; private static final String GAME_DESIGN_PEER = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String WORLD_MANAGEMENT_PEER = + "spiffe://firemud/ns/test/sa/world-management-service"; @AfterEach void clearTransactionState() { @@ -658,7 +661,8 @@ void projectionRequiresExactSameNamespaceGameDesignOrOriginalGameSessionPeerBefo "spiffe://firemud/ns/other/sa/game-design-service", "spiffe://firemud/ns/other/sa/game-session-service", "spiffe://firemud/ns/test/sa/account-service", - LOGGING_PEER)) { + LOGGING_PEER, + WORLD_MANAGEMENT_PEER)) { Context.current() .withValue( GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(wrongPeerUri).orElseThrow()) @@ -873,6 +877,303 @@ void projectionRejectsRevokedOrChangedCurrentAccountSource() { harness.captureRepository()); } + @Test + void worldCurrentnessAuthenticatesExactPeerBeforeParsingAndDoesNotWidenProjectionRead() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + byte[] malformed = "not a canonical tuple".getBytes(StandardCharsets.UTF_8); + + for (String wrongPeerUri : + List.of( + "spiffe://firemud/ns/other/sa/world-management-service", + GAME_DESIGN_PEER, + GAME_SESSION_PEER, + LOGGING_PEER, + "spiffe://firemud/ns/test/sa/account-service")) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(wrongPeerUri).orElseThrow()) + .run( + () -> + assertThatThrownBy( + () -> + harness + .service() + .withCurrentWorldReceivingParticipationCurrentness( + malformed, + harness.request().ownerAttemptId(), + harness.request().ownerFence(), + ignored -> "unexpected")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact authenticated internal workload identity")); + } + Context.ROOT.run( + () -> + assertThatThrownBy( + () -> + harness + .service() + .withCurrentWorldReceivingParticipationCurrentness( + malformed, + harness.request().ownerAttemptId(), + harness.request().ownerFence(), + ignored -> "unexpected")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact authenticated internal workload identity")); + + worldManagementContext() + .run( + () -> + assertThatThrownBy( + () -> + harness + .service() + .withCurrentWorldReceivingParticipationCurrentness( + malformed, + harness.request().ownerAttemptId(), + harness.request().ownerFence(), + ignored -> "unexpected")) + .isInstanceOf(IllegalArgumentException.class)); + + verify(harness.repository(), never()).findByControlPlaneRequestId(anyString()); + verify(harness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); + verify(harness.hostedTerms(), never()).captureCurrentEnvironmentBoundary(); + verifyNoInteractions(harness.captureRepository()); + } + + @Test + void worldCurrentnessRejectsTupleNamespaceDifferentFromAuthenticatedPeerBeforeLookup() { + String loggingPeer = "spiffe://firemud/ns/logging-ns/sa/logging-admin-service"; + String gameSessionPeer = "spiffe://firemud/ns/world-ns/sa/game-session-service"; + ReadHarness harness = readHarness(NOW.plusSeconds(30), loggingPeer, gameSessionPeer); + StartSessionPostAuthorizationExecutionTuple canonicalPostTuple = postTuple(harness); + + assertThat(canonicalPostTuple.preAuthorizationTuple().action().scope().targetNamespace()) + .isEqualTo("logging-ns"); + worldManagementContext("spiffe://firemud/ns/world-ns/sa/world-management-service") + .run( + () -> + assertThatThrownBy( + () -> + harness + .service() + .withCurrentWorldReceivingParticipationCurrentness( + canonicalPostTuple.canonicalBytes(), + harness.request().ownerAttemptId(), + harness.request().ownerFence(), + ignored -> "unexpected")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "StartSession target namespace does not match the authenticated World peer")); + + verify(harness.repository(), never()).findByControlPlaneRequestId(anyString()); + verify(harness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); + verify(harness.hostedTerms(), never()).captureCurrentEnvironmentBoundary(); + verifyNoInteractions(harness.captureRepository()); + } + + @Test + void worldCurrentnessRejectsAmbientTransactionOrSynchronizationBeforeCurrentness() { + ReadHarness transactionHarness = readHarness(NOW.plusSeconds(30)); + byte[] postTuple = postTuple(transactionHarness).canonicalBytes(); + TransactionSynchronizationManager.setActualTransactionActive(true); + worldManagementContext() + .run( + () -> + assertThatThrownBy( + () -> + transactionHarness + .service() + .withCurrentWorldReceivingParticipationCurrentness( + postTuple, + transactionHarness.request().ownerAttemptId(), + transactionHarness.request().ownerFence(), + ignored -> "unexpected")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient Account transaction")); + TransactionSynchronizationManager.clear(); + + ReadHarness synchronizationHarness = readHarness(NOW.plusSeconds(30)); + byte[] synchronizedPostTuple = postTuple(synchronizationHarness).canonicalBytes(); + TransactionSynchronizationManager.initSynchronization(); + worldManagementContext() + .run( + () -> + assertThatThrownBy( + () -> + synchronizationHarness + .service() + .withCurrentWorldReceivingParticipationCurrentness( + synchronizedPostTuple, + synchronizationHarness.request().ownerAttemptId(), + synchronizationHarness.request().ownerFence(), + ignored -> "unexpected")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("without an ambient Account transaction")); + + verify(transactionHarness.repository(), never()).findByControlPlaneRequestId(anyString()); + verify(synchronizationHarness.repository(), never()).findByControlPlaneRequestId(anyString()); + verify(transactionHarness.hostedTerms(), never()).captureCurrentEnvironmentBoundary(); + verify(synchronizationHarness.hostedTerms(), never()).captureCurrentEnvironmentBoundary(); + verify(transactionHarness.actors(), never()) + .withCurrentCommitted(any(), any(), any(), any(), any()); + verify(synchronizationHarness.actors(), never()) + .withCurrentCommitted(any(), any(), any(), any(), any()); + } + + @Test + void worldCurrentnessLocksExactCaptureAndRunsOnlyAccountCallbackInSameTransaction() + throws Exception { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + allowCurrent(harness, harness.source()); + AtomicReference callbackCapture = new AtomicReference<>(); + + AccountStartSessionAuthorityCapture result = + worldManagementContext() + .call( + () -> + harness + .service() + .withCurrentWorldReceivingParticipationCurrentness( + postTuple(harness).canonicalBytes(), + harness.request().ownerAttemptId(), + harness.request().ownerFence(), + lockedCapture -> { + assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(lockedCapture).isEqualTo(harness.capture()); + callbackCapture.set(lockedCapture); + return lockedCapture; + })); + + assertThat(result).isEqualTo(harness.capture()); + assertThat(callbackCapture.get()).isEqualTo(harness.capture()); + verify(harness.captureRepository()) + .lockReadExactCurrent( + any(), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.record().reservationOwnerId()), + eq(harness.record().reservationClaimFence())); + verify(harness.captureRepository(), never()) + .prepareOrReadExact(any(), any(), anyString(), any(), anyLong()); + verify(harness.captureRepository(), never()) + .lockExactCurrent(any(), any(), any(), anyString(), any(), anyLong()); + verify(harness.repository(), never()).createOrReadExact(any()); + verify(harness.repository(), never()).redeemExact(any()); + verifyNoInteractions(harness.claims(), harness.fingerprintKeys(), harness.responseCrypto()); + } + + @Test + void worldCurrentnessRejectsExpiredReferenceAndChangedCurrentSourceBeforeCallback() { + ReadHarness expired = readHarness(NOW.minusSeconds(10)); + AtomicReference expiredCallback = new AtomicReference<>(false); + worldManagementContext() + .run( + () -> + assertThatThrownBy( + () -> + expired + .service() + .withCurrentWorldReceivingParticipationCurrentness( + postTuple(expired).canonicalBytes(), + expired.request().ownerAttemptId(), + expired.request().ownerFence(), + ignored -> { + expiredCallback.set(true); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); + assertThat(expiredCallback).hasValue(false); + verify(expired.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); + verify(expired.captureRepository(), never()) + .lockReadExactCurrent(any(), any(), anyString(), any(), anyLong()); + + ReadHarness changed = readHarness(NOW.plusSeconds(30)); + AccountControlUiAuthority.Snapshot changedSource = + source(changed.actorId(), changed.tenantId(), 8L, new byte[] {2}); + allowCurrent(changed, changedSource); + AtomicReference changedCallback = new AtomicReference<>(false); + worldManagementContext() + .run( + () -> + assertThatThrownBy( + () -> + changed + .service() + .withCurrentWorldReceivingParticipationCurrentness( + postTuple(changed).canonicalBytes(), + changed.request().ownerAttemptId(), + changed.request().ownerFence(), + ignored -> { + changedCallback.set(true); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Current Account source")); + assertThat(changedCallback).hasValue(false); + verify(changed.captureRepository()) + .lockReadExactCurrent(any(), eq(changed.tuple()), eq(LOGGING_PEER), any(), anyLong()); + } + + @Test + void worldCurrentnessRejectsPostTupleFingerprintAndOwnerAttemptSubstitution() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + StartSessionPostAuthorizationExecutionTuple original = postTuple(harness); + StartSessionPostAuthorizationExecutionTuple substitutedFingerprint = + StartSessionPostAuthorizationExecutionTuple.createHuman( + harness.tuple(), + LOGGING_PEER, + "arfp/v1/test-key/" + "b".repeat(64), + harness.record().reservationOwnerId(), + harness.record().reservationClaimFence(), + harness.record().authorityEvidenceBundle(), + harness.record().bundleReference()); + AtomicReference callback = new AtomicReference<>(false); + + worldManagementContext() + .run( + () -> + assertThatThrownBy( + () -> + harness + .service() + .withCurrentWorldReceivingParticipationCurrentness( + substitutedFingerprint.canonicalBytes(), + harness.request().ownerAttemptId(), + harness.request().ownerFence(), + ignored -> { + callback.set(true); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("tuple differs from the original Account issuance")); + + worldManagementContext() + .run( + () -> + assertThatThrownBy( + () -> + harness + .service() + .withCurrentWorldReceivingParticipationCurrentness( + original.canonicalBytes(), + UUID.randomUUID(), + harness.request().ownerFence(), + ignored -> { + callback.set(true); + return null; + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); + + assertThat(callback).hasValue(false); + verify(harness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); + verify(harness.captureRepository(), never()) + .lockReadExactCurrent(any(), any(), anyString(), any(), anyLong()); + } + @Test void expiredOrFutureOriginalClaimEvidenceStopsBeforeCaptureAndPrivateCrypto() { MutableClock expiredClock = new MutableClock(NOW); @@ -1449,20 +1750,35 @@ private static byte[] fill(int length, byte value) { } private static ReadHarness readHarness(Instant referenceExpiresAt) { + return readHarness(referenceExpiresAt, LOGGING_PEER, GAME_SESSION_PEER); + } + + private static ReadHarness readHarness( + Instant referenceExpiresAt, String exactLoggingPeerUri, String exactGameSessionPeerUri) { UUID actorId = UUID.randomUUID(); UUID tenantId = UUID.randomUUID(); UUID reservationOwnerId = UUID.randomUUID(); UUID ownerAttemptId = UUID.randomUUID(); UUID issuanceOperationId = UUID.randomUUID(); UUID tokenJti = UUID.randomUUID(); - StartSessionPreAuthorizationReservationTuple tuple = tuple(actorId, tenantId); + String targetNamespace = + GrpcPeerIdentity.parseUri(exactLoggingPeerUri).orElseThrow().namespace(); + StartSessionPreAuthorizationReservationTuple tuple = tuple(actorId, tenantId, targetNamespace); AccountControlUiAuthority.Snapshot source = source(actorId, tenantId, 7L, new byte[] {1}); AccountControlUiIssuanceRepository.Stored stored = stored(actorId, tenantId, tokenJti, issuanceOperationId, source); Instant issuedAt = referenceExpiresAt.minusSeconds(50); Instant redeemedAt = referenceExpiresAt.isAfter(NOW) ? NOW.minusSeconds(1) : referenceExpiresAt.minusSeconds(1); - var capture = capture(tuple, source, stored, reservationOwnerId, 10L, issuedAt.minusSeconds(1)); + var capture = + capture( + tuple, + source, + stored, + reservationOwnerId, + 10L, + issuedAt.minusSeconds(1), + exactLoggingPeerUri); assertThat(Instant.parse(capture.capturedAt())).isBefore(issuedAt).isBefore(referenceExpiresAt); var bundle = AccountStartSessionOperatorAuthorityBundle.create( @@ -1474,7 +1790,7 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { tuple.controlPlaneRequestId(), tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), tuple.mutationDigest(), - LOGGING_PEER, + exactLoggingPeerUri, reservationOwnerId, 10L, issuanceOperationId, @@ -1487,7 +1803,7 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { referenceExpiresAt, referenceExpiresAt.plusSeconds(20), Status.REDEEMED, - GAME_SESSION_PEER, + exactGameSessionPeerUri, ownerAttemptId, 18L, redeemedAt, @@ -1510,9 +1826,24 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { org.mockito.Mockito.mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); when(transactions.getTransaction(any(TransactionDefinition.class))) .thenAnswer(ignored -> new SimpleTransactionStatus()); - when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); + when(hostedTerms.captureCurrentEnvironmentBoundary()) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return environment; + }); when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) .thenReturn(Optional.of(record)); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(invocation.getArgument(0).stored()).isSameAs(stored); + return capture; + }) + .when(captureRepository) + .lockReadExactCurrent( + any(), eq(tuple), eq(exactLoggingPeerUri), eq(reservationOwnerId), eq(10L)); var service = new AccountStartSessionOperatorAuthorizationService( actors, @@ -1526,8 +1857,8 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { transactions, Clock.fixed(NOW, ZoneOffset.UTC), new java.security.SecureRandom(), - LOGGING_PEER, - GAME_SESSION_PEER, + exactLoggingPeerUri, + exactGameSessionPeerUri, java.time.Duration.ofSeconds(60), java.time.Duration.ofSeconds(20)); ReadRedeemedOperationProjectionRequest request = @@ -1550,6 +1881,7 @@ private static ReadHarness readHarness(Instant referenceExpiresAt) { environment, tuple, source, + capture, stored, record, request, @@ -1647,6 +1979,16 @@ private static Context gameSessionContext() { GrpcPeerIdentity.parseUri(GAME_SESSION_PEER).orElseThrow()); } + private static Context worldManagementContext() { + return worldManagementContext(WORLD_MANAGEMENT_PEER); + } + + private static Context worldManagementContext(String worldPeerUri) { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(worldPeerUri).orElseThrow()); + } + private record ReadHarness( AccountStartSessionOperatorAuthorizationService service, AccountControlUiActorService actors, @@ -1659,6 +2001,7 @@ private record ReadHarness( AccountHostedTermsService.CapturedEnvironmentBoundary environment, StartSessionPreAuthorizationReservationTuple tuple, AccountControlUiAuthority.Snapshot source, + AccountStartSessionAuthorityCapture capture, AccountControlUiIssuanceRepository.Stored stored, IssuanceRecord record, ReadRedeemedOperationProjectionRequest request, @@ -1666,12 +2009,28 @@ private record ReadHarness( UUID tenantId, UUID tokenJti) {} + private static StartSessionPostAuthorizationExecutionTuple postTuple(ReadHarness harness) { + return StartSessionPostAuthorizationExecutionTuple.createHuman( + harness.tuple(), + harness.record().issuanceWorkloadUri(), + harness.request().authorizationReferenceFingerprint(), + harness.request().reservationOwnerId(), + harness.request().reservationClaimFence(), + harness.record().authorityEvidenceBundle(), + harness.record().bundleReference()); + } + private static StartSessionPreAuthorizationReservationTuple tuple(UUID actorId, UUID tenantId) { + return tuple(actorId, tenantId, "test"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + UUID actorId, UUID tenantId, String targetNamespace) { var action = new StartSessionOperatorAction( StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(tenantId, "test"), + new StartSessionOperatorAction.Scope(tenantId, targetNamespace), new StartSessionOperatorAction.Target(1L, actorId), StartSessionOperatorAction.ExpectedVersion.ABSENT, new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), @@ -1696,6 +2055,18 @@ private static AccountStartSessionAuthorityCapture capture( UUID reservationOwnerId, long reservationClaimFence, Instant capturedAt) { + return capture( + tuple, source, stored, reservationOwnerId, reservationClaimFence, capturedAt, LOGGING_PEER); + } + + private static AccountStartSessionAuthorityCapture capture( + StartSessionPreAuthorizationReservationTuple tuple, + AccountControlUiAuthority.Snapshot source, + AccountControlUiIssuanceRepository.Stored stored, + UUID reservationOwnerId, + long reservationClaimFence, + Instant capturedAt, + String loggingWorkloadUri) { byte[] signerReceipt = stored.signerReceipt.clone(); Map snapshot = Map.ofEntries( @@ -1709,7 +2080,7 @@ private static AccountStartSessionAuthorityCapture capture( Map.entry("accountId", tuple.actor().accountId().toString()), Map.entry("tenantId", tuple.action().scope().tenantId().toString()), Map.entry("targetOwner", tuple.targetOwner()), - Map.entry("loggingWorkloadUri", LOGGING_PEER), + Map.entry("loggingWorkloadUri", loggingWorkloadUri), Map.entry("reservationOwnerId", reservationOwnerId.toString()), Map.entry("reservationClaimFence", Long.toString(reservationClaimFence)), Map.entry("controlUiOperationId", stored.operationId.toString()), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java new file mode 100644 index 0000000000..61c19fdbfd --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java @@ -0,0 +1,566 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredSettlement; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadClient; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadRequest; +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.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Composition seams only: authenticated peer and exact owner terminal are stipulated here. */ +class AccountStartSessionWorldParticipationSettlementServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final long PARTICIPATION_FENCE = 31L; + private static final long GAME_SESSION_FENCE = 37L; + private static final String PREPARATION_INPUT = + "{ \"selected\" : \"immutable source\", \"revision\": 3 }\n"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final AccountStartSessionWorldParticipationRepository repository = + mock(AccountStartSessionWorldParticipationRepository.class); + private final WorldStartSessionExecutionTerminalReadClient world = + mock(WorldStartSessionExecutionTerminalReadClient.class); + private final OwnerTransactions transactions = new OwnerTransactions(); + private final AccountStartSessionWorldParticipationSettlementService service = + new AccountStartSessionWorldParticipationSettlementService( + repository, world, transactions, NAMESPACE); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactWorldPeerWithoutEndUserBeforeLookupIdentityOrOwnerAccess() { + assertCode(Status.Code.UNAUTHENTICATED, () -> service.settle(null, 0)); + for (String workload : List.of("account-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer(NAMESPACE, workload, () -> service.settle(null, 0))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("other", "world-management-service", () -> service.settle(null, 0))); + SessionContext.setContext("123", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer(NAMESPACE, "world-management-service", () -> service.settle(null, 0))); + verifyNoInteractions(repository, world); + assertThat(transactions.begins).isZero(); + } + + @Test + void deniesAmbientSqlOrSynchronizationBeforeIdentityValidation() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null, 0))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null, 0))); + verifyNoInteractions(repository, world); + assertThat(transactions.begins).isZero(); + } + + @Test + void derivesExactReadFromRetainedParticipationAndCommitsThenReadsBackBothOutcomes() { + for (WorldStartSessionExecutionTerminal.Outcome outcome : + WorldStartSessionExecutionTerminal.Outcome.values()) { + reset(repository, world); + Fixture fixture = fixture(); + WorldStartSessionExecutionTerminal terminal = fixture.terminal(outcome); + StoredSettlement expected = fixture.settlement(terminal); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty(), Optional.of(expected)); + when(world.read(any())) + .thenAnswer( + call -> { + assertNoSql(); + WorldStartSessionExecutionTerminalReadRequest request = call.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.originalPostAuthorizationTuple()) + .containsExactly(fixture.participation.originalPostAuthorizationTuple()); + assertThat(request.accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(request.accountWorldParticipationFence()).isEqualTo(PARTICIPATION_FENCE); + assertThat(request.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); + assertThat(request.gameSessionOwnerFence()).isEqualTo(GAME_SESSION_FENCE); + assertThat(request.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(request.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + assertThat(request.preparationInputDigest()) + .isEqualTo(fixture.participation.preparationInputDigest()); + return terminal; + }); + when(repository.settleExact(any())) + .thenAnswer( + call -> { + assertWritableTransaction(); + assertThat(call.getArgument(0, WorldStartSessionExecutionTerminal.class).outcome()) + .isEqualTo(outcome); + return expected; + }); + + int priorCommits = transactions.commits; + StoredSettlement actual = + authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE)); + assertThat(actual.terminalBytes()).containsExactly(expected.terminalBytes()); + assertThat(actual.outcome()).isEqualTo(outcome); + assertThat(actual.worldExecutionFence()).isEqualTo(terminal.worldExecutionFence()); + assertThat(transactions.commits - priorCommits).isEqualTo(3); + assertThat(authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))) + .isSameAs(expected); + assertThat(transactions.commits - priorCommits).isEqualTo(4); + ArgumentCaptor terminalCaptor = + ArgumentCaptor.forClass(WorldStartSessionExecutionTerminal.class); + verify(repository).settleExact(terminalCaptor.capture()); + assertThat(terminalCaptor.getValue().canonicalBytes()) + .containsExactly(terminal.canonicalBytes()); + verify(world).read(any()); + assertNoSql(); + } + } + + @Test + void alreadySettledHistoricalReceiptRecoversWithoutWorldOrCurrentActorChecks() { + Fixture fixture = fixture(); + var terminal = fixture.terminal(WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + StoredSettlement receipt = fixture.settlement(terminal); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(receipt)); + + assertThat(authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))) + .isSameAs(receipt); + verifyNoInteractions(world); + assertThat(transactions.begins).isEqualTo(1); + assertThat(transactions.commits).isEqualTo(1); + } + + @Test + void absentOrUnavailableWorldTerminalNeverSettlesParticipation() { + Fixture fixture = fixture(); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty()); + when(world.read(any())).thenReturn(null); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))); + verify(repository, org.mockito.Mockito.never()).settleExact(any()); + assertThat(transactions.commits).isEqualTo(1); + + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(world).read(any()); + assertCode( + Status.Code.UNAVAILABLE, + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))); + verify(repository, org.mockito.Mockito.never()).settleExact(any()); + assertThat(transactions.commits).isEqualTo(2); + } + + @Test + void exactCodecRejectsSubstitutedWorldTerminalAndNoSqlOccursAcrossNetwork() { + Fixture fixture = fixture(); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty()); + var substituted = + new WorldStartSessionExecutionTerminal( + fixture.participation.originalPostAuthorizationTuple(), + PARTICIPATION_ID, + PARTICIPATION_FENCE, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + NAMESPACE, + fixture.participation.canonicalTenantId(), + fixture.participation.controlPlaneRequestId(), + GAME_INSTANCE_ID, + digest("substituted preparation"), + "substituted preparation", + 41L, + WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + when(world.read(any())) + .thenAnswer( + call -> { + assertNoSql(); + return substituted; + }); + assertThatThrownBy( + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete original StartSession identity"); + verify(repository, org.mockito.Mockito.never()).settleExact(any()); + assertThat(transactions.commits).isEqualTo(1); + } + + @Test + void targetNamespaceMismatchFailsBeforeWorldCallAndExpiredOriginalEvidenceDoesNotGateHistory() { + Fixture fixture = fixture(); + StoredParticipation otherNamespace = + new StoredParticipation( + fixture.participation.participationId(), + fixture.participation.participationFence(), + fixture.participation.controlPlaneRequestId(), + fixture.participation.originalPostAuthorizationTuple(), + "other-runtime", + fixture.participation.canonicalTenantId(), + fixture.participation.canonicalGameInstanceId(), + fixture.participation.gameSessionOwnerAttemptId(), + fixture.participation.gameSessionOwnerFence(), + fixture.participation.preparationInputJson(), + fixture.participation.preparationInputDigest(), + fixture.participation.producerXid(), + fixture.participation.createdAt(), + fixture.participation.sources()); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(otherNamespace)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))); + verifyNoInteractions(world); + assertThat(transactions.commits).isEqualTo(0); + + // The persisted tuple's bundle is intentionally expired. Historical exact settlement + // depends on immutable owner readback and must not invoke current actor/JTI or expiry checks. + Fixture expired = fixture(true); + var terminal = expired.terminal(WorldStartSessionExecutionTerminal.Outcome.ABORTED); + StoredSettlement receipt = expired.settlement(terminal); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(expired.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty(), Optional.of(receipt)); + when(world.read(any())).thenReturn(terminal); + when(repository.settleExact(any())).thenReturn(receipt); + assertThat(authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))) + .isSameAs(receipt); + } + + @Test + void readbackMismatchAndSettlementCommitFailureDoNotReturnSuccess() { + Fixture fixture = fixture(); + var terminal = fixture.terminal(WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + StoredSettlement first = fixture.settlement(terminal); + StoredSettlement changed = + new StoredSettlement( + first.participationId(), + first.outcome(), + first.worldExecutionFence() + 1, + first.terminalBytes(), + first.terminalDigest(), + first.settledAt()); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty(), Optional.of(changed)); + when(world.read(any())).thenReturn(terminal); + when(repository.settleExact(any())).thenReturn(first); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))); + assertThat(transactions.commits).isEqualTo(3); + + reset(repository, world); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.of(fixture.participation)); + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty()); + when(world.read(any())).thenReturn(terminal); + when(repository.settleExact(any())).thenReturn(first); + transactions.failCommitAt = transactions.commits + 2; + assertThatThrownBy( + () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synthetic commit failure"); + assertThat(transactions.begins).isEqualTo(5); + } + + private static void assertWritableTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_READ_COMMITTED); + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static T authorized(Supplier action) { + return peer(NAMESPACE, "world-management-service", action); + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static String digest(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static Fixture fixture() { + return fixture(false); + } + + private static Fixture fixture(boolean expiredBundle) { + UUID tenantId = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + UUID actorId = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + UUID targetOwner = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwner = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + String requestId = "world-participation-settlement-original-request"; + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + actorId, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, NAMESPACE), + new StartSessionOperatorAction.Target(91L, targetOwner), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "StartSession terminal settlement test")); + var reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + StartSessionPostAuthorizationExecutionTuple original = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + reservationOwner, + 19L, + authorityBundle(preTuple, expiredBundle), + reference); + byte[] tupleBytes = original.canonicalBytes(); + StoredParticipation participation = + new StoredParticipation( + PARTICIPATION_ID, + PARTICIPATION_FENCE, + requestId, + tupleBytes, + NAMESPACE, + tenantId, + GAME_INSTANCE_ID, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + PREPARATION_INPUT, + digest(PREPARATION_INPUT), + 987L, + OffsetDateTime.parse("2026-10-09T00:00:00Z"), + List.of()); + return new Fixture(participation); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, boolean expired) { + String tenantId = tuple.action().scope().tenantId().toString(); + String actorId = tuple.actor().accountId().toString(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + expired ? "2020-01-01T00:00:00Z" : "2026-10-09T00:00:00Z", + "expiresAt", + expired ? "2020-01-02T00:00:00Z" : "2026-10-10T00:00:00Z"); + Map identity = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", actorId, + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record Fixture(StoredParticipation participation) { + WorldStartSessionExecutionTerminal terminal( + WorldStartSessionExecutionTerminal.Outcome outcome) { + return new WorldStartSessionExecutionTerminal( + participation.originalPostAuthorizationTuple(), + PARTICIPATION_ID, + PARTICIPATION_FENCE, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + NAMESPACE, + participation.canonicalTenantId(), + participation.controlPlaneRequestId(), + GAME_INSTANCE_ID, + participation.preparationInputDigest(), + PREPARATION_INPUT, + 41L, + outcome); + } + + StoredSettlement settlement(WorldStartSessionExecutionTerminal terminal) { + return new StoredSettlement( + PARTICIPATION_ID, + terminal.outcome(), + terminal.worldExecutionFence(), + terminal.canonicalBytes(), + terminal.digest(), + OffsetDateTime.parse("2026-10-09T00:01:00Z")); + } + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + int failCommitAt = -1; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + if (commits == failCommitAt) throw new IllegalStateException("synthetic commit failure"); + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java new file mode 100644 index 0000000000..69b859d18e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java @@ -0,0 +1,162 @@ +package net.firedevops.firemud.common.world; + +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.WorldStartSessionExecutionTerminalReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for the unregistered Account-authenticated World read. */ +public final class WorldStartSessionExecutionTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + WorldStartSessionExecutionTerminalReadServiceGrpc + .WorldStartSessionExecutionTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldStartSessionExecutionTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldStartSessionExecutionTerminalReadClient.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 StartSession terminal read client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World StartSession terminal read client has no gRPC stub"); + } + initialized = true; + } + + /** Reads one exact historical terminal without renewing or settling its source participation. */ + public WorldStartSessionExecutionTerminal read( + WorldStartSessionExecutionTerminalReadRequest request) { + Objects.requireNonNull(request, "World StartSession terminal read request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World StartSession terminal request must use the configured workload namespace"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World StartSession terminal read must start outside an ambient transaction"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readWorldStartSessionExecutionTerminal( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request)); + try { + return WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid original StartSession terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldStartSessionExecutionTerminalReadServiceGrpc + .WorldStartSessionExecutionTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldStartSessionExecutionTerminalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldStartSessionExecutionTerminalReadServiceGrpc + .WorldStartSessionExecutionTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World StartSession terminal read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World StartSession terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World StartSession terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World StartSession terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World StartSession terminal read " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World StartSession terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..19d7dcdecc --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java @@ -0,0 +1,127 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldStartSessionExecutionTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldStartSessionExecutionTerminalResponse; + +/** Closed protobuf adapter for exact historical StartSession terminal readback. */ +public final class WorldStartSessionExecutionTerminalReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private WorldStartSessionExecutionTerminalReadGrpcCodec() {} + + public static WorldStartSessionExecutionTerminalReadRequest fromRequest( + ReadWorldStartSessionExecutionTerminalRequest request) { + Objects.requireNonNull(request, "World StartSession terminal read request"); + requireNoUnknownFields(request, "request"); + return new WorldStartSessionExecutionTerminalReadRequest( + canonicalUuid(request.getReadRequestId(), "readRequestId"), + request.getTargetNamespace(), + request.getOriginalPostAuthorizationTuple().toByteArray(), + canonicalUuid(request.getAccountWorldParticipationId(), "accountWorldParticipationId"), + request.getAccountWorldParticipationFence(), + canonicalUuid(request.getGameSessionOwnerAttemptId(), "gameSessionOwnerAttemptId"), + request.getGameSessionOwnerFence(), + canonicalUuid(request.getCanonicalGameInstanceId(), "canonicalGameInstanceId"), + request.getPreparationInputJson()); + } + + public static ReadWorldStartSessionExecutionTerminalRequest toRequest( + WorldStartSessionExecutionTerminalReadRequest request) { + Objects.requireNonNull(request, "World StartSession terminal read request"); + return ReadWorldStartSessionExecutionTerminalRequest.newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setOriginalPostAuthorizationTuple( + ByteString.copyFrom(request.originalPostAuthorizationTuple())) + .setAccountWorldParticipationId(request.accountWorldParticipationId().toString()) + .setAccountWorldParticipationFence(request.accountWorldParticipationFence()) + .setGameSessionOwnerAttemptId(request.gameSessionOwnerAttemptId().toString()) + .setGameSessionOwnerFence(request.gameSessionOwnerFence()) + .setCanonicalGameInstanceId(request.canonicalGameInstanceId().toString()) + .setPreparationInputJson(request.preparationInputJson()) + .build(); + } + + public static ReadWorldStartSessionExecutionTerminalResponse toResponse( + WorldStartSessionExecutionTerminalReadRequest request, + WorldStartSessionExecutionTerminal terminal) { + requireSameIdentity(request, terminal); + return ReadWorldStartSessionExecutionTerminalResponse.newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setCanonicalTerminalBytes(ByteString.copyFrom(terminal.canonicalBytes())) + .build(); + } + + public static WorldStartSessionExecutionTerminal fromResponse( + WorldStartSessionExecutionTerminalReadRequest request, + ReadWorldStartSessionExecutionTerminalResponse response) { + Objects.requireNonNull(request, "World StartSession terminal read request"); + Objects.requireNonNull(response, "World StartSession terminal response"); + requireNoUnknownFields(response, "response"); + UUID readRequestId = canonicalUuid(response.getReadRequestId(), "readRequestId"); + if (!request.readRequestId().equals(readRequestId)) { + throw invalid("World changed the exact StartSession terminal read correlation"); + } + byte[] bytes = response.getCanonicalTerminalBytes().toByteArray(); + if (bytes.length == 0 + || bytes.length > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { + throw invalid("World StartSession terminal bytes are missing or exceed their limit"); + } + WorldStartSessionExecutionTerminal terminal = + WorldStartSessionExecutionTerminal.fromStored(bytes); + requireSameIdentity(request, terminal); + return terminal; + } + + private static void requireSameIdentity( + WorldStartSessionExecutionTerminalReadRequest request, + WorldStartSessionExecutionTerminal terminal) { + Objects.requireNonNull(request, "World StartSession terminal read request"); + Objects.requireNonNull(terminal, "World StartSession terminal"); + if (!Arrays.equals( + request.originalPostAuthorizationTuple(), terminal.originalPostAuthorizationTuple()) + || !request.accountWorldParticipationId().equals(terminal.accountWorldParticipationId()) + || request.accountWorldParticipationFence() != terminal.accountWorldParticipationFence() + || !request.gameSessionOwnerAttemptId().equals(terminal.gameSessionOwnerAttemptId()) + || request.gameSessionOwnerFence() != terminal.gameSessionOwnerFence() + || !request.targetNamespace().equals(terminal.targetNamespace()) + || !request.canonicalTenantId().equals(terminal.canonicalTenantId()) + || !request.controlPlaneRequestId().equals(terminal.controlPlaneRequestId()) + || !request.canonicalGameInstanceId().equals(terminal.canonicalGameInstanceId()) + || !request.preparationInputDigest().equals(terminal.preparationInputDigest()) + || !request.preparationInputJson().equals(terminal.preparationInputJson())) { + throw invalid("World terminal differs from the complete original StartSession identity"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid("World StartSession terminal " + label + " contains unsupported fields"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadRequest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadRequest.java new file mode 100644 index 0000000000..0ce227095a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadRequest.java @@ -0,0 +1,195 @@ +package net.firedevops.firemud.common.world; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; + +/** Exact immutable identity and fresh correlation for one historical World terminal read. */ +public final class WorldStartSessionExecutionTerminalReadRequest { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final UUID readRequestId; + private final String targetNamespace; + private final byte[] originalPostAuthorizationTuple; + private final StartSessionPostAuthorizationExecutionTuple decodedOriginalTuple; + private final UUID accountWorldParticipationId; + private final long accountWorldParticipationFence; + private final UUID gameSessionOwnerAttemptId; + private final long gameSessionOwnerFence; + private final UUID canonicalGameInstanceId; + private final String preparationInputJson; + private final String preparationInputDigest; + + public WorldStartSessionExecutionTerminalReadRequest( + UUID readRequestId, + String targetNamespace, + byte[] originalPostAuthorizationTuple, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + UUID canonicalGameInstanceId, + String preparationInputJson) { + this.readRequestId = requireNonNil(readRequestId, "readRequestId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw invalid("targetNamespace must be one canonical DNS label"); + } + this.targetNamespace = targetNamespace; + if (originalPostAuthorizationTuple == null + || originalPostAuthorizationTuple.length == 0 + || originalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw invalid("Exact original StartSession post-authorization tuple is required"); + } + this.originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + this.decodedOriginalTuple = + StartSessionPostAuthorizationExecutionTuple.decode(this.originalPostAuthorizationTuple); + var original = decodedOriginalTuple.preAuthorizationTuple(); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(original.actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals(original.targetOwner())) { + throw invalid("Original tuple must identify the Game Session StartSession operation"); + } + if (!targetNamespace.equals(original.action().scope().targetNamespace())) { + throw invalid("targetNamespace differs from the exact original StartSession tuple"); + } + + this.accountWorldParticipationId = + requireNonNil(accountWorldParticipationId, "accountWorldParticipationId"); + this.accountWorldParticipationFence = + requirePositive(accountWorldParticipationFence, "accountWorldParticipationFence"); + this.gameSessionOwnerAttemptId = + requireNonNil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + this.gameSessionOwnerFence = requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + this.canonicalGameInstanceId = + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + if (this.readRequestId.equals(this.accountWorldParticipationId) + || this.readRequestId.equals(this.gameSessionOwnerAttemptId) + || this.readRequestId.equals(this.canonicalGameInstanceId) + || this.readRequestId.equals(decodedOriginalTuple.reservationOwnerId())) { + throw invalid("readRequestId must be fresh and distinct from retained operation identities"); + } + this.preparationInputJson = requirePreparationInput(preparationInputJson); + this.preparationInputDigest = digest(strictUtf8(this.preparationInputJson)); + } + + public UUID readRequestId() { + return readRequestId; + } + + public String targetNamespace() { + return targetNamespace; + } + + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + public StartSessionPostAuthorizationExecutionTuple decodedOriginalTuple() { + return decodedOriginalTuple; + } + + public UUID accountWorldParticipationId() { + return accountWorldParticipationId; + } + + public long accountWorldParticipationFence() { + return accountWorldParticipationFence; + } + + public UUID gameSessionOwnerAttemptId() { + return gameSessionOwnerAttemptId; + } + + public long gameSessionOwnerFence() { + return gameSessionOwnerFence; + } + + public UUID canonicalGameInstanceId() { + return canonicalGameInstanceId; + } + + public UUID canonicalTenantId() { + return decodedOriginalTuple.preAuthorizationTuple().action().scope().tenantId(); + } + + public String controlPlaneRequestId() { + return decodedOriginalTuple.controlPlaneRequestId(); + } + + public String preparationInputJson() { + return preparationInputJson; + } + + /** Derived from the exact input string; it is never a separate request authority field. */ + public String preparationInputDigest() { + return preparationInputDigest; + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return value; + } + + private static long requirePositive(long value, String field) { + if (value <= 0L) { + throw invalid(field + " must be a positive signed 64-bit integer"); + } + return value; + } + + private static String requirePreparationInput(String value) { + Objects.requireNonNull(value, "preparationInputJson"); + if (value.isBlank()) { + throw invalid("preparationInputJson must retain the exact original input"); + } + if (strictUtf8(value).length > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { + throw invalid("preparationInputJson exceeds the terminal byte limit"); + } + return value; + } + + private static byte[] strictUtf8(String value) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] result = new byte[encoded.remaining()]; + encoded.get(result); + return result; + } catch (CharacterCodingException malformed) { + throw invalid("preparationInputJson must be valid Unicode", malformed); + } + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java new file mode 100644 index 0000000000..f2ce5b08aa --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java @@ -0,0 +1,75 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +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 org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldStartSessionExecutionTerminalReadClientTest { + @Test + void requiresFileBackedMtlsInitializationAndAnIndependentCallerTransaction( + @TempDir Path directory) throws Exception { + var plaintext = fileBacked(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminalReadClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var classpath = fileBacked(directory); + classpath.setCaCert("classpath:ca.crt"); + assertThatThrownBy( + () -> + new WorldStartSessionExecutionTerminalReadClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + var client = + new WorldStartSessionExecutionTerminalReadClient( + new ServiceEndpointsProperties(), + fileBacked(directory), + new GrpcChannelFactory(), + "world-runtime"); + try { + assertThatThrownBy(() -> client.read(null)).isInstanceOf(NullPointerException.class); + var request = WorldStartSessionExecutionTerminalReadGrpcCodecTest.request(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + } finally { + TransactionSynchronizationManager.clear(); + client.close(); + } + } + + private static CommonGrpcClientProperties fileBacked(Path directory) throws Exception { + var properties = new CommonGrpcClientProperties(); + properties.setCertChain( + Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + properties.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "private key").toString()); + properties.setCaCert( + Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return properties; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..c82598b08c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java @@ -0,0 +1,283 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal.Outcome; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldStartSessionExecutionTerminalResponse; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class WorldStartSessionExecutionTerminalReadGrpcCodecTest { + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final UUID READ_ID = uuid("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"); + private static final String CONTROL_PLANE_REQUEST_ID = "terminal-read-original-request"; + private static final String NAMESPACE = "world-runtime"; + private static final String PREPARATION_INPUT = + "{ \"selected\" : \"immutable source\", \"revision\": 3 }\n"; + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void roundTripsFreshReadAndOnlyCanonicalTerminalResult() { + var request = request(); + var wireRequest = WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request); + var decoded = WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest(wireRequest); + assertThat(decoded.readRequestId()).isEqualTo(READ_ID); + assertThat(decoded.originalPostAuthorizationTuple()) + .containsExactly(request.originalPostAuthorizationTuple()); + assertThat(decoded.accountWorldParticipationFence()).isEqualTo(31L); + assertThat(decoded.gameSessionOwnerFence()).isEqualTo(37L); + assertThat(decoded.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + + var terminal = terminal(request, PARTICIPATION_ID, 31L, GAME_SESSION_ATTEMPT_ID, 37L); + var response = WorldStartSessionExecutionTerminalReadGrpcCodec.toResponse(request, terminal); + assertThat(response.getAllFields()).hasSize(2); + var recovered = WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse(request, response); + assertThat(recovered.canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(recovered.outcome()).isEqualTo(Outcome.COMMITTED); + } + + @Test + void rejectsUnknownFieldsMalformedIdentityAndMixedNamespaceBeforeUse() { + var request = request(); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setUnknownFields(unknown) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setReadRequestId("d1f41bfb-265a-4f3b-8b2a-124cba20ce43 ") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil UUID"); + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setAccountWorldParticipationFence(0L) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive"); + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setTargetNamespace("other-runtime") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from the exact original"); + } + + @Test + void rejectsSubstitutedTerminalIdentityOrReadCorrelation() { + var request = request(); + var substituted = + terminal( + request, + uuid("e2a52c0c-c71f-4900-b1f2-c78f8b512a63"), + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L); + var response = + ReadWorldStartSessionExecutionTerminalResponse.newBuilder() + .setReadRequestId(READ_ID.toString()) + .setCanonicalTerminalBytes( + com.google.protobuf.ByteString.copyFrom(substituted.canonicalBytes())) + .build(); + assertThatThrownBy( + () -> WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete original StartSession identity"); + + var valid = terminal(request, PARTICIPATION_ID, 31L, GAME_SESSION_ATTEMPT_ID, 37L); + var changedCorrelation = + ReadWorldStartSessionExecutionTerminalResponse.newBuilder() + .setReadRequestId("e2a52c0c-c71f-4900-b1f2-c78f8b512a63") + .setCanonicalTerminalBytes( + com.google.protobuf.ByteString.copyFrom(valid.canonicalBytes())) + .build(); + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse( + request, changedCorrelation)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact"); + + assertThatThrownBy( + () -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse( + request, changedCorrelation.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + static WorldStartSessionExecutionTerminalReadRequest request() { + return new WorldStartSessionExecutionTerminalReadRequest( + READ_ID, + NAMESPACE, + originalTuple().canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + PREPARATION_INPUT); + } + + private static WorldStartSessionExecutionTerminal terminal( + WorldStartSessionExecutionTerminalReadRequest request, + UUID participationId, + long participationFence, + UUID attemptId, + long attemptFence) { + return new WorldStartSessionExecutionTerminal( + request.originalPostAuthorizationTuple(), + participationId, + participationFence, + attemptId, + attemptFence, + request.targetNamespace(), + request.canonicalTenantId(), + request.controlPlaneRequestId(), + request.canonicalGameInstanceId(), + request.preparationInputDigest(), + request.preparationInputJson(), + 41L, + Outcome.COMMITTED); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + CONTROL_PLANE_REQUEST_ID, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + WORKLOAD, + FINGERPRINT, + RESERVATION_OWNER, + 19L, + bundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] bundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = TENANT.toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map identity = + Map.of( + "issuanceOperationId", uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f").toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", ACTOR.toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcService.java new file mode 100644 index 0000000000..bfbb9ea9f1 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcService.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadGrpcCodec; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldStartSessionExecutionTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldStartSessionExecutionTerminalResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldStartSessionExecutionTerminalReadServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone Account-authenticated World terminal read; deliberately not registered at runtime. */ +public final class WorldStartSessionExecutionTerminalReadGrpcService + extends WorldStartSessionExecutionTerminalReadServiceGrpc + .WorldStartSessionExecutionTerminalReadServiceImplBase { + private final WorldCanonicalInstancePreparationService preparationService; + private final String trustedNamespace; + + public WorldStartSessionExecutionTerminalReadGrpcService( + WorldCanonicalInstancePreparationService preparationService, String trustedNamespace) { + this.preparationService = Objects.requireNonNull(preparationService, "preparationService"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readWorldStartSessionExecutionTerminal( + ReadWorldStartSessionExecutionTerminalRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedAccountPeer(responseObserver)) return; + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "World StartSession terminal recovery requires an independent owner operation"); + return; + } + + final WorldStartSessionExecutionTerminalReadRequest decoded; + try { + decoded = WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A complete canonical original StartSession identity and fresh read UUID are required"); + return; + } + if (!trustedNamespace.equals(decoded.targetNamespace())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "World StartSession terminal namespace must match the authenticated Account workload"); + return; + } + + final WorldCanonicalInstanceExecutionIdentity identity; + try { + identity = + new WorldCanonicalInstanceExecutionIdentity( + decoded.originalPostAuthorizationTuple(), + decoded.accountWorldParticipationId(), + decoded.accountWorldParticipationFence(), + decoded.gameSessionOwnerAttemptId(), + decoded.gameSessionOwnerFence(), + decoded.canonicalGameInstanceId(), + decoded.preparationInputJson()); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "World StartSession terminal identity does not match its original tuple"); + return; + } + + final WorldStartSessionExecutionTerminal terminal; + try { + terminal = preparationService.recoverExactTerminal(identity).orElse(null); + } catch (WorldCanonicalInstancePreparationService.PreparationDeniedException denied) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "The exact original World StartSession operation is not authenticated for recovery"); + return; + } catch (DataAccessException | org.springframework.dao.DataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "World StartSession terminal storage is temporarily unavailable"); + return; + } catch (IllegalArgumentException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Exact World StartSession terminal owner evidence is inconsistent"); + return; + } catch (RuntimeException failure) { + fail(responseObserver, Status.INTERNAL, "World StartSession terminal recovery failed"); + return; + } + if (terminal == null) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "World StartSession execution remains unresolved: missing or PENDING is not terminal proof"); + return; + } + + final ReadWorldStartSessionExecutionTerminalResponse response; + try { + response = WorldStartSessionExecutionTerminalReadGrpcCodec.toResponse(decoded, terminal); + } catch (IllegalArgumentException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Recovered World terminal differs from the complete original StartSession identity"); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean requireAuthenticatedAccountPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + fail( + responseObserver, + Status.UNAUTHENTICATED, + "Verified same-namespace Account workload identity is required"); + return false; + } + if (!peer.isService("account-service") + || !peer.isInNamespace(trustedNamespace) + || !peer.uri().equals("spiffe://firemud/ns/" + trustedNamespace + "/sa/account-service") + || SessionContext.hasAuthenticatedCallerContext()) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Only the exact same-namespace Account workload without end-user context is allowed"); + return false; + } + return true; + } + + private static void fail(StreamObserver responseObserver, Status status, String description) { + responseObserver.onError(status.withDescription(description).asRuntimeException()); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcServiceTest.java new file mode 100644 index 0000000000..22ef496328 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcServiceTest.java @@ -0,0 +1,452 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import 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.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadGrpcCodec; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadRequest; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceExecutionIdentity; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionLookup; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionOperation; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionState; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldStartSessionExecutionTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldStartSessionExecutionTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadWorldStartSessionExecutionTerminalResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldStartSessionExecutionTerminalReadServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class WorldStartSessionExecutionTerminalReadGrpcServiceTest { + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d42-903a-33495456a622"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID OWNER_ATTEMPT_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final UUID READ_ID = uuid("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"); + private static final String CONTROL_PLANE_REQUEST_ID = "terminal-read-original-request"; + private static final String NAMESPACE = "world-runtime"; + private static final String PREPARATION_INPUT = + "{ \"selected\" : \"immutable source\", \"revision\": 3 }\n"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearAmbientContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactAccountWorkloadIsAuthenticatedBeforeParsingOrOwnerAccess() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var service = service(repository, ignored -> {}); + var grpc = new WorldStartSessionExecutionTerminalReadGrpcService(service, NAMESPACE); + var malformed = + ReadWorldStartSessionExecutionTerminalRequest.newBuilder().setReadRequestId("bad").build(); + + Collector noPeer = new Collector(); + grpc.readWorldStartSessionExecutionTerminal(malformed, noPeer); + assertCode(noPeer, Status.Code.UNAUTHENTICATED); + + Collector wrongWorkload = new Collector(); + callAs(grpc, peer("game-session-service", NAMESPACE), malformed, wrongWorkload); + assertCode(wrongWorkload, Status.Code.PERMISSION_DENIED); + + Collector wrongNamespace = new Collector(); + callAs(grpc, peer("account-service", "other-runtime"), malformed, wrongNamespace); + assertCode(wrongNamespace, Status.Code.PERMISSION_DENIED); + + Collector endUser = new Collector(); + SessionContext.setContext("42", List.of(), Map.of()); + callAs(grpc, peer("account-service", NAMESPACE), malformed, endUser); + assertCode(endUser, Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void actualTransactionAndSynchronizationAreRejectedBeforeDecode() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var grpc = + new WorldStartSessionExecutionTerminalReadGrpcService( + service(repository, ignored -> {}), NAMESPACE); + var malformed = + ReadWorldStartSessionExecutionTerminalRequest.newBuilder().setReadRequestId("bad").build(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + Collector actualTransaction = new Collector(); + callAs(grpc, peer("account-service", NAMESPACE), malformed, actualTransaction); + assertCode(actualTransaction, Status.Code.FAILED_PRECONDITION); + + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.initSynchronization(); + Collector synchronization = new Collector(); + callAs(grpc, peer("account-service", NAMESPACE), malformed, synchronization); + assertCode(synchronization, Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(repository); + } + + @Test + void authenticatedMalformedOrUnknownFieldsFailBeforeRecovery() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var grpc = + new WorldStartSessionExecutionTerminalReadGrpcService( + service(repository, ignored -> {}), NAMESPACE); + + Collector malformed = new Collector(); + callAs( + grpc, + peer("account-service", NAMESPACE), + ReadWorldStartSessionExecutionTerminalRequest.newBuilder().setReadRequestId("bad").build(), + malformed); + assertCode(malformed, Status.Code.INVALID_ARGUMENT); + + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + Collector unknownField = new Collector(); + callAs( + grpc, + peer("account-service", NAMESPACE), + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request()).toBuilder() + .setUnknownFields(unknown) + .build(), + unknownField); + assertCode(unknownField, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void requestNamespaceMustMatchOwnerNamespaceBeforeTheRecoveryVerifier() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var verificationCalls = new AtomicInteger(); + var grpc = + new WorldStartSessionExecutionTerminalReadGrpcService( + service(repository, ignored -> verificationCalls.incrementAndGet()), NAMESPACE); + var foreignRequest = + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request("other-runtime")); + Collector collector = new Collector(); + callAs(grpc, peer("account-service", NAMESPACE), foreignRequest, collector); + + assertCode(collector, Status.Code.PERMISSION_DENIED); + assertThat(verificationCalls).hasValue(0); + verifyNoInteractions(repository); + } + + @Test + void missingAndPendingWorldRowsRemainUnresolvedAndNeverReturnTerminalBytes() { + for (ExecutionLookup lookup : + List.of( + new ExecutionLookup(Optional.empty(), false), + new ExecutionLookup( + Optional.of(new ExecutionOperation(ExecutionState.PENDING, 73L, null)), false))) { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + when(repository.readExactExecution(any(WorldCanonicalInstanceExecutionIdentity.class))) + .thenReturn(lookup); + var verificationCalls = new AtomicInteger(); + var grpc = + new WorldStartSessionExecutionTerminalReadGrpcService( + service(repository, ignored -> verificationCalls.incrementAndGet()), NAMESPACE); + Collector collector = new Collector(); + callAs( + grpc, + peer("account-service", NAMESPACE), + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request()), + collector); + + assertCode(collector, Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(collector.error).getDescription()) + .contains("remains unresolved") + .contains("not terminal proof"); + assertThat(collector.value).isNull(); + assertThat(verificationCalls).hasValue(1); + } + } + + @Test + void returnsOnlyExactCommittedOrAbortedTerminalAfterSyntheticOriginalVerification() { + for (ExecutionState state : List.of(ExecutionState.COMMITTED, ExecutionState.ABORTED)) { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var order = new ArrayList(); + Long instanceId = state == ExecutionState.COMMITTED ? 991L : null; + var lookup = + new ExecutionLookup(Optional.of(new ExecutionOperation(state, 73L, instanceId)), false); + when(repository.readExactExecution(any(WorldCanonicalInstanceExecutionIdentity.class))) + .thenAnswer( + invocation -> { + order.add("owner-read"); + return lookup; + }); + // This explicitly synthetic verifier accepts the expired historical tuple so the test + // proves recovery reads history without applying fresh-admission expiry. + var grpc = + new WorldStartSessionExecutionTerminalReadGrpcService( + service( + repository, + identity -> { + order.add("synthetic-original-verifier"); + assertThat(identity.originalAuthorizationExpiry()).isBefore(Instant.now()); + }), + NAMESPACE); + Collector collector = new Collector(); + callAs( + grpc, + peer("account-service", NAMESPACE), + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request()), + collector); + + assertThat(collector.error).isNull(); + assertThat(collector.completed).isTrue(); + assertThat(order).containsExactly("synthetic-original-verifier", "owner-read"); + assertThat(collector.value.getAllFields()).hasSize(2); + var terminal = + WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse(request(), collector.value); + assertThat(terminal.outcome()) + .isEqualTo( + state == ExecutionState.COMMITTED + ? WorldStartSessionExecutionTerminal.Outcome.COMMITTED + : WorldStartSessionExecutionTerminal.Outcome.ABORTED); + assertThat(terminal.worldExecutionFence()).isEqualTo(73L); + assertThat(terminal.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(terminal.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + } + } + + @Test + void defaultRecoveryVerifierDeniesWithoutInventingPositiveEvidence() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var grpc = + new WorldStartSessionExecutionTerminalReadGrpcService( + new WorldCanonicalInstancePreparationService(repository), NAMESPACE); + Collector collector = new Collector(); + callAs( + grpc, + peer("account-service", NAMESPACE), + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request()), + collector); + + assertCode(collector, Status.Code.FAILED_PRECONDITION); + assertThat(collector.value).isNull(); + verifyNoInteractions(repository); + } + + private static WorldCanonicalInstancePreparationService service( + WorldCanonicalInstancePreparationRepository repository, + WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier verifier) { + return new WorldCanonicalInstancePreparationService( + repository, + input -> { + throw new AssertionError("Historical terminal read must not start fresh execution"); + }, + verifier); + } + + private static WorldStartSessionExecutionTerminalReadRequest request() { + return request(NAMESPACE); + } + + private static WorldStartSessionExecutionTerminalReadRequest request(String namespace) { + var tuple = originalTuple(namespace); + return new WorldStartSessionExecutionTerminalReadRequest( + READ_ID, + namespace, + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + OWNER_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + PREPARATION_INPUT); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(String namespace) { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + CONTROL_PLANE_REQUEST_ID, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + bundle(preTuple, namespace), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] bundle( + StartSessionPreAuthorizationReservationTuple tuple, String namespace) { + String tenantId = TENANT.toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2020-01-01T00:00:00Z", + "expiresAt", "2020-01-01T00:05:00Z"); + Map identity = + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", namespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static void callAs( + WorldStartSessionExecutionTerminalReadServiceGrpc + .WorldStartSessionExecutionTerminalReadServiceImplBase + service, + GrpcPeerIdentity peer, + ReadWorldStartSessionExecutionTerminalRequest request, + Collector collector) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readWorldStartSessionExecutionTerminal(request, collector); + } finally { + context.detach(previous); + } + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static void assertCode(Collector collector, Status.Code code) { + assertThat(collector.error).isNotNull(); + assertThat(Status.fromThrowable(collector.error).getCode()).isEqualTo(code); + assertThat(collector.value).isNull(); + assertThat(collector.completed).isFalse(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Collector + implements StreamObserver { + private ReadWorldStartSessionExecutionTerminalResponse value; + private Throwable error; + private boolean completed; + + @Override + public void onNext(ReadWorldStartSessionExecutionTerminalResponse response) { + value = response; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The test collector retains the response throwable for assertions.") + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} From 17d3872f84358e0bae753620da578c818c503a46 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 14:56:21 +1300 Subject: [PATCH 069/129] Add historical Account participation reads and distinct selected-owner reservations --- .../account-service/api-contracts.md | 4 +- ...ame-authoring-publishing-and-activation.md | 14 +- ...art_session_world_participation_read.proto | 32 + .../DraftAuthorizationFenceRepository.java | 45 ++ ...tSelectedOwnerIntakeSourceReadService.java | 99 +++ ...wnerIntakeSourceReservationRepository.java | 432 +++++++++++ ...edOwnerIntakeSourceReservationService.java | 199 +++++ ...articipationHistoricalReadGrpcService.java | 81 ++ ...rldParticipationHistoricalReadService.java | 124 +++ ...129__start_session_world_participation.sql | 52 +- ...ected_owner_intake_source_reservations.sql | 428 +++++++++++ ...rceReservationPostgresIntegrationTest.java | 209 +++++ ...dParticipationPostgresIntegrationTest.java | 716 ++++++++++++++++++ ...orizationFenceSelectedOwnerIntakeTest.java | 262 +++++++ ...ectedOwnerIntakeSourceReadServiceTest.java | 199 +++++ ...IntakeSourceReservationRepositoryTest.java | 39 + ...nerIntakeSourceReservationServiceTest.java | 403 ++++++++++ ...cipationHistoricalReadGrpcServiceTest.java | 165 ++++ ...articipationHistoricalReadServiceTest.java | 402 ++++++++++ .../AccountControlUiOriginalOrderFixture.java | 69 ++ ...orldParticipationHistoricalReadClient.java | 168 ++++ ...ldParticipationHistoricalReadEvidence.java | 111 +++ ...dParticipationHistoricalReadGrpcCodec.java | 142 ++++ ...rldParticipationHistoricalReadRequest.java | 44 ++ ...artSessionExecutionTerminalReadClient.java | 2 + ...SessionExecutionTerminalReadGrpcCodec.java | 7 + ...ParticipationHistoricalReadClientTest.java | 116 +++ ...ticipationHistoricalReadGrpcCodecTest.java | 328 ++++++++ ...essionExecutionTerminalReadClientTest.java | 23 + ...ionExecutionTerminalReadGrpcCodecTest.java | 15 + ...licationExportPostgresIntegrationTest.java | 134 +++- ...ldCanonicalInstancePreparationService.java | 6 +- ...nonicalInstancePreparationServiceTest.java | 41 + 33 files changed, 5077 insertions(+), 34 deletions(-) create mode 100644 protos/account/v1/start_session_world_participation_read.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java create mode 100644 services/account-service/src/main/resources/db/migration/V130__selected_owner_intake_source_reservations.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadRequest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 54644c5d70..f46f403eb7 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -108,7 +108,7 @@ The standalone [`SettleGameLogicIntake`](../../../../protos/account/v1/game_logi Entity and Automation's selected-source intake use the same two-phase ownership boundary, with distinct Account operations and proof domains, not Game Logic grants. The preliminary scope schema is `account-entity-intake-source-read/v1` with purpose `ENTITY_INTAKE_SOURCE`, or `account-automation-intake-source-read/v1` with purpose `AUTOMATION_INTAKE_SOURCE`. Its canonical preimage uses the existing byte-length framing in this fixed order: schema, closed owner (`ENTITY_MANAGEMENT` or `AUTOMATION_SCRIPTING`), namespace, original Account operation UUID, original fence UUID, stable intake request UUID, acting account UUID, complete canonical selected Draft binding bytes, that binding's digest, derived same-namespace Account workload reader, and the corresponding purpose. UUIDs are canonical and nonzero; unknown owners, substituted domains/readers, malformed or noncanonical frames, trailing bytes and scopes over 4 MiB deny. The SHA-256 digest covers the complete preimage. The reader and purpose derive from the owner and namespace, never caller-selected aliases. -That scope is preliminary integrity input, not authenticated authorization, finalized owner retention permission or evidence that any source family is empty. Account must authenticate and retain the distinct reservation before Game Design returns source content; it must then obtain the complete immutable selected inputs and finalize the owner-specific authorization with revalidated held sources. Original revision provenance is retained separately from the selected capture and must not be rewritten to manufacture a World association. Entity's [complete authored inventory](../entity-management-service/runtime-and-data.md) and Automation's [source inventory and inbound closure](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) remain owner-validated obligations. Both owners retain their original terminal under continuously protected Account authority; only authenticated exact terminal settlement can release participation. A decoded scope or sampled `HELD` response proves none of those obligations. The reservation, held-retention producers and executed proof remain open in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); these domains do not register or enable a runtime path. +That scope is preliminary integrity input, not authenticated authorization, finalized owner retention permission or evidence that any source family is empty. Account must authenticate and retain the distinct reservation before Game Design returns source content; it must then obtain the complete immutable selected inputs and finalize the owner-specific authorization with revalidated held sources. The original Draft's required-owner vector identifies its mutation participants, not the consumers of this later distinct intake. Original revision provenance is retained separately from the selected capture and must not be rewritten to manufacture a World association. Entity's [complete authored inventory](../entity-management-service/runtime-and-data.md) and Automation's [source inventory and inbound closure](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) remain owner-validated obligations. Both owners retain their original terminal under continuously protected Account authority; only authenticated exact terminal settlement can release participation. A decoded scope or sampled `HELD` response proves none of those obligations. Complete authenticated reservation/finalization, held-retention producers and executed proof remain open in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); these domains do not register or enable a runtime path. `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. @@ -187,7 +187,7 @@ Error precedence is canonical: (1) Account authenticates the exact immediate mTL These RPCs and schemas are accepted target state but are not present in the current Account proto or implementation. Logging & Admin remains the external operator ingress and durable intent/audit coordinator, Account remains the authorization authority and owner of original-reference retention, and the domain service remains the mutation owner. -For StartSession, Account's existing human authorization-reference issuer remains the sole issuer and the original reference retains `targetOwner=game-session-service`. The distinct Account-owned same-namespace World receiving-participation and source-protection lifecycle is defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation); this API contract adds no replacement issuer, reference-renewal, or re-redemption path. The Game Design projection read and publication hold/settlement producers remain separate and grant no StartSession World permission. Unregistered repository, currentness and exact-terminal settlement components do not establish a complete genuine participation producer or World admission; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records their remaining producer, consumer and physical proof gates. +For StartSession, Account's existing human authorization-reference issuer remains the sole issuer and the original reference retains `targetOwner=game-session-service`. The distinct Account-owned same-namespace World receiving-participation and source-protection lifecycle is defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation); this API contract adds no replacement issuer, reference-renewal, or re-redemption path. The Game Design projection read and publication hold/settlement producers remain separate and grant no StartSession World permission. The standalone, unregistered [historical participation read](../../../../protos/account/v1/start_session_world_participation_read.proto) authenticates the exact configured same-namespace World workload and returns only the retained original identity from an independent Account transaction. Its fresh read correlation and original participation ID/fence are lookup selectors, not fresh authority; expiry or settlement cannot renew the reference, restart execution or manufacture an abort. Unregistered repository, currentness, historical-read and exact-terminal settlement components do not establish a complete genuine participation producer or World admission; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records their remaining producer, consumer and physical proof gates. The credential-free `ReadRedeemedOperationProjection` receiver accepts the exact configured same-namespace Game Design peer and the exact original Game Session redeemer under [ADR 0047's restricted original-operation read](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). Before returning the retained projection, Account compares the original request/reservation and redeemed workload/attempt/fence, then revalidates the original actor/JTI, current source and reference expiry. The response contains no credential or renewed permission. Game Session must separately prove its original claim and immutable pin under the owner-local checks required by that contract; this Account read is not World participation or admission. 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 7b28133f57..177787bd1a 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 @@ -6,7 +6,19 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Account V129 prepares distinct World StartSession participation storage with an independent participation fence, the unchanged complete original post-authorization tuple, exact redeemed Game Session attempt/fence, canonical World target and byte-exact preparation input. Its immutable source children must equal the retained V128 capture; pending participation excludes source mutation and hosted-terms dispatch until an exact immutable World `COMMITTED` or fenced `ABORTED` receipt settles it. Acquisition checks exact captured hosted-terms evidence, not merely a historical disclosure sharing a source key. The Account repository constructs typed exact insert/readback and lookup-only historical settlement recovery; the sole issuer supplies a World-only currentness callback without widening the original Game Design/Game Session projection allowlist. Neither supplies genuine Game Session original-operation evidence or a complete authenticated acquisition producer. The PostgreSQL definition currently covers migration installation, assembled guard preservation and append-only rejection, not positive authenticated participation or physical concurrency. +The historical participation, preliminary selected-owner reservation and V129 parse-correction batch passes the final affected Account/World/Game Design gate in 1m19s, including integration compilation, static checks, formatting, schema generation and boot JARs. Account's 1,230, World's 623 and Game Design's 539 unit results are green; the separate unchanged Common Platform gate passes with 501 units in 2m46s. Successful unchanged tasks reuse their results. Eight non-container integration cases execute; 622 integration definitions skip without Docker (255 Account, 219 World, 148 Game Design). These include the new participation, migration and originating Game Design reservation definitions; no physical database, socket, fresh-image boot or complete producer/consumer credit follows. Flyway sanity checks 12 sets and 287 versions; links and Markdown pass. The earlier compile/static failures were repaired rather than counted as proof. All four complete Gameplay handoffs remain open. + +Source `b6456cc7fc8a7aba1b8a952b315f005fca7a21f6` [Validation run 38010530067](https://github.com/benhook1013/FireMUD/actions/runs/38010530067) completed red on synthetic merge `c62aba65d5343a98b84b6d3a71cf9bc052fdd33b` (tree `e0feba547ca21848510e2b4637d12fdbd13e0096`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source). Game Design executed 151 integration cases with 15 failures, World 220 with two failures and Game Logic nine with one failure, all without skips. These failures stop at PostgreSQL SQLSTATE `42601` in Account V129's participation insertion function; they do not prove the blocked authorization or settlement assertions. World's 21 canonical association cases passed. Account's job was canceled without originating results, so neither its test counts nor V127's four physical migration cases receive execution credit. Logging's successful tasks lack exact class-level socket evidence. The duplicate validation run skipped substantive jobs. The separate four V120 durability gaps remain open; this run supplies no new causal evidence for them. Corrected migration installation and genuine composed producer proof remain required. + +The V129 parse repair renames the PL/pgSQL record variable `authorization` to `authorization_row`; PostgreSQL interpreted its qualified field access as a reserved keyword. No tuple, expiry, original owner-attempt/fence, immutable receipt or source-protection condition changes. Its existing installation case must execute again before this correction receives physical proof. + +The distinct unregistered Account historical participation receiver and file-backed mTLS client supply lookup-only original identity for World reconciliation, separately from fresh acquisition and terminal settlement. Account authenticates the exact configured same-namespace World workload before decoding or storage, binds the complete fresh read echo and original participation ID/fence, and returns only its retained full original tuple, Game Session attempt/fence, canonical target and byte-exact preparation input. Missing or substituted evidence denies; historical reads do not invoke currentness, allocate participation, renew expiry, mutate state or infer abort. Mocked receiver/codec tests are not genuine socket or original Game Session producer proof. The World terminal client now explicitly admits its complete 24 MiB canonical result plus bounded wire framing rather than retaining gRPC's smaller default; focused stub configuration is not authenticated transport proof. Registration, genuine recovery composition and physical execution remain required. + +The distinct Entity/Automation preliminary reservation construction adds Account V130, current-creator admission against the exact settled original Draft, immutable owner-specific source scopes and sorted Account source participation. It is not a Game Logic grant and does not change the original Draft's participant vector or require its later intake consumer to have authored that Draft. Exact recovery preserves the original request, credential hash and scope; explicit abort releases only that reservation. The unregistered live read confirms the original issuer and full source/checkpoint evidence in independent Account transactions around the external active-registry read, then checks database-clock expiry after final source and operation lock waits. The originating Game Design PostgreSQL fixture now defines positive Account reservation, exact retry/recovery and isolated abort against its actual authenticated Game Design/World original settlement; its direct Game Design peer context and repository export remain stipulated transport, not authenticated source-read or downstream owner receipt proof. The separate Account migration definition checks V129-to-V130 installation and assembled guard preservation. Both require physical execution. Finalized held-retention authorization, authenticated selected-source transport, Entity/Automation census and original receipts, through-commit authority and exact terminal settlement remain open. Schema generation alone does not prove V130 installation or PostgreSQL behavior. + +The new Account-backed World participation PostgreSQL definition uses actual Account creator issuance, source capture, signing, original StartSession issuance and redemption before exact participation insert/readback and typed settlement. Logging claim evidence, Game Session attempt/fence, preparation input and World terminal are stipulated collaborators; this is not genuine end-to-end owner producer proof. Exact retry and historical readback compare full canonical source bytes rather than Java array identity. The definition remains unexecuted locally without Docker. World preparation and historical recovery also reject ambient transaction synchronization before external verification or storage; eight focused service unit cases execute successfully, but do not prove the missing authenticated verifier. + +Account V129 prepares distinct World StartSession participation storage with an independent participation fence, the unchanged complete original post-authorization tuple, exact redeemed Game Session attempt/fence, canonical World target and byte-exact preparation input. Its immutable source children must equal the retained V128 capture; pending participation excludes source mutation and hosted-terms dispatch until an exact immutable World `COMMITTED` or fenced `ABORTED` receipt settles it. Acquisition checks exact captured hosted-terms evidence, not merely a historical disclosure sharing a source key. The Account repository constructs typed exact insert/readback and lookup-only historical settlement recovery; the sole issuer supplies a World-only currentness callback without widening the original Game Design/Game Session projection allowlist. Neither supplies genuine Game Session original-operation evidence or a complete authenticated acquisition producer. The earlier repository-only PostgreSQL definition covers migration installation, assembled guard preservation and append-only rejection; the separate Account-backed definition above does not replace missing positive authenticated participation or physical concurrency proof. The separate unregistered World terminal-read contract and strict file-backed mTLS client return only the existing closed terminal bytes for the complete immutable original operation. World authenticates the same-namespace Account receiver before decoding and invokes its original-operation recovery verifier outside SQL; missing or pending operations remain unresolved. The unregistered Account settlement composition derives the read from retained participation, calls World outside SQL, appends the exact terminal in one independent transaction and performs a separate lookup-only post-commit readback. Historical expiry neither renews authority nor authorizes admission. These components remain unregistered; World's default recovery verifier denies. Genuine live/historical Game Session tuple proof, the World verifier, authenticated acquisition/settlement and socket/physical PostgreSQL proof remain required before activation. Mocked transaction ordering and stipulated terminal evidence are not that proof. diff --git a/protos/account/v1/start_session_world_participation_read.proto b/protos/account/v1/start_session_world_participation_read.proto new file mode 100644 index 0000000000..0260e1508c --- /dev/null +++ b/protos/account/v1/start_session_world_participation_read.proto @@ -0,0 +1,32 @@ +syntax = "proto3"; + +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. This exact historical read neither admits execution nor renews +// Account authority; World must separately authenticate its original Game Session operation. +service AccountStartSessionWorldParticipationHistoricalReadService { + rpc ReadHistoricalStartSessionWorldParticipation( + ReadHistoricalStartSessionWorldParticipationRequest) + returns (ReadHistoricalStartSessionWorldParticipationResponse); +} + +message ReadHistoricalStartSessionWorldParticipationRequest { + int32 schema_version = 1; + string read_request_id = 2; + string target_namespace = 3; + string account_world_participation_id = 4; + int64 account_world_participation_fence = 5; +} + +message ReadHistoricalStartSessionWorldParticipationResponse { + ReadHistoricalStartSessionWorldParticipationRequest request = 1; + bytes original_post_authorization_tuple = 2; + string game_session_owner_attempt_id = 3; + int64 game_session_owner_fence = 4; + string canonical_game_instance_id = 5; + // Byte-for-byte retained World preparation JSON, not fresh admission or currentness evidence. + string preparation_input_json = 6; + string preparation_input_digest = 7; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 846c1dc4b6..8d04f0bdad 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -252,6 +252,7 @@ public void requireDisclosurePreparation(List exactSources) { } requireNoPendingPublication(sources); requireNoPendingGameLogicIntake(sources); + requireNoPendingSelectedOwnerIntakeSourceRead(sources); requireNoPendingWorldParticipation(sources); for (UUID operationId : affectedOperations(sources)) { Record row = readOperation(operationId); @@ -348,6 +349,31 @@ public void requireGameLogicIntakeAdmission( } } + /** + * Admission for either Entity or Automation preliminary source reads. The selected Game Design + * operation is exact; this establishes no owner retention authority. + */ + public void requireSelectedOwnerIntakeAdmission( + List sources, DraftCommitBinding selected) { + requirePublicationAdmission(sources); + Objects.requireNonNull(selected, "selected Draft binding is required"); + Record originalRow = + dsl.fetchOne( + "SELECT * FROM " + FENCES + " WHERE request_id = ? AND commit_id = ? FOR UPDATE", + selected.requestId(), + selected.commitId()); + if (originalRow == null) { + throw new IllegalStateException("Selected author operation is unavailable"); + } + DraftAuthorizationFenceBinding original = originalBinding(originalRow); + if (!Arrays.equals(original.gameDesignBinding(), selected.canonicalBytes()) + || !Ordering.COMMIT_ORDER.name().equals(originalRow.get("ordering", String.class)) + || settlement(original, Ordering.COMMIT_ORDER) != Settlement.COMMITTED) { + throw new IllegalStateException( + "Exact selected original author operation must be committed and settled"); + } + } + private boolean hasPendingGameLogicIntake(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( @@ -368,6 +394,24 @@ private void requireNoPendingGameLogicIntake(List sources) { } } + private boolean hasPendingSelectedOwnerIntakeSourceRead(List sources) { + for (SourceEvidence source : sources) { + if (!dsl.fetch( + "SELECT source.operation_id FROM account_selected_owner_intake_source_read_sources source " + + "WHERE source.source_key = ? " + + "AND account_selected_owner_intake_source_read_is_pending(source.operation_id)", + source.key()) + .isEmpty()) return true; + } + return false; + } + + private void requireNoPendingSelectedOwnerIntakeSourceRead(List sources) { + if (hasPendingSelectedOwnerIntakeSourceRead(sources)) { + throw new IllegalStateException("Selected owner intake source read remains pending"); + } + } + private boolean hasPendingWorldParticipation(List sources) { for (SourceEvidence source : sources) { if (!dsl.fetch( @@ -841,6 +885,7 @@ private List affectedOperations(List sources) { private boolean allAffectedSettled(List sources) { if (hasPendingPublication(sources) || hasPendingGameLogicIntake(sources) + || hasPendingSelectedOwnerIntakeSourceRead(sources) || hasPendingWorldParticipation(sources)) { return false; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java new file mode 100644 index 0000000000..da3fc6945c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered exact pending Entity/Automation source readback; never finalizes owner retention. + */ +public final class AccountSelectedOwnerIntakeSourceReadService { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final AccountControlUiCoordination registry; + private final TransactionTemplate transaction; + private final String namespace; + + public AccountSelectedOwnerIntakeSourceReadService( + AccountSelectedOwnerIntakeSourceReservationRepository repository, + AccountControlUiCoordination registry, + PlatformTransactionManager transactions, + String namespace) { + this.repository = Objects.requireNonNull(repository); + this.registry = Objects.requireNonNull(registry); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + /** + * Confirms one exact, still-live preliminary source reservation. The registry read is outside + * both independent READ_COMMITTED SQL transactions; this result grants no retention authority. + */ + public SelectedOwnerIntakeSourceReadScope readSourceScope( + SelectedOwnerIntakeSourceReadScope scope, String intendedReader, String purpose) { + requireGameDesignPeer(); + Objects.requireNonNull(scope, "source-read scope is required"); + if (!namespace.equals(scope.targetNamespace()) + || !intendedReader(scope.owner()).equals(intendedReader) + || !scope.intendedReader().equals(intendedReader) + || !scope.purpose().equals(purpose)) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + requireOutsideSql(); + var current = + Objects.requireNonNull( + transaction.execute(ignored -> repository.sourceReadCurrentness(scope))); + var active = registry.readActive(current.tokenHash()); + if (!current.registryDigest().equals(DraftAuthorizationFenceBinding.digest(active))) { + throw Status.FAILED_PRECONDITION + .withDescription("Original creator registry evidence is no longer exact") + .asRuntimeException(); + } + return Objects.requireNonNull( + transaction.execute( + ignored -> { + repository.readSourceScope(scope, current); + return scope; + })); + } + + private String intendedReader(Owner owner) { + if (owner != Owner.ENTITY_MANAGEMENT && owner != Owner.AUTOMATION_SCRIPTING) + throw Status.PERMISSION_DENIED.asRuntimeException(); + return "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Game Design workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireOutsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected-owner source read requires independent Account transactions") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java new file mode 100644 index 0000000000..4fcbd71e63 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java @@ -0,0 +1,432 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Immutable preliminary Entity/Automation source-read reservations and their own abort marker. */ +public final class AccountSelectedOwnerIntakeSourceReservationRepository { + private static final String RESERVATIONS = + "account_selected_owner_intake_source_read_reservations"; + private static final String SOURCES = "account_selected_owner_intake_source_read_sources"; + private static final String ABORTS = "account_selected_owner_intake_source_read_aborts"; + + private final DSLContext dsl; + + public AccountSelectedOwnerIntakeSourceReservationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + public enum State { + RESERVED, + ABORTED + } + + /** Historical evidence only. RESERVED does not imply a live source-read permission. */ + public record Recovery(SelectedOwnerIntakeSourceReadScope scope, State state) { + public Recovery { + Objects.requireNonNull(scope, "scope"); + Objects.requireNonNull(state, "state"); + } + } + + /** Exact database evidence sampled before the independent active-registry read. */ + record SourceReadCurrentness( + String tokenHash, + String registryDigest, + long expiresAtEpochSecond, + String issuerEvidenceDigest, + String sourceVectorDigest) { + SourceReadCurrentness { + Objects.requireNonNull(tokenHash); + Objects.requireNonNull(registryDigest); + Objects.requireNonNull(issuerEvidenceDigest); + Objects.requireNonNull(sourceVectorDigest); + } + } + + SelectedOwnerIntakeSourceReadScope reserveSourceRead( + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected, + AccountControlUiActorService.Current current, + String namespace, + Runnable admission) { + requireTransaction(); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(selected, "selected"); + requireOwner(owner); + Objects.requireNonNull(current, "current"); + Objects.requireNonNull(admission, "admission"); + + UUID tenantId = selected.target().canonicalTenantId(); + Record existing = + dsl.fetchOne( + "SELECT * FROM " + + RESERVATIONS + + " WHERE tenant_uuid = ? AND intake_request_id = ? FOR UPDATE", + tenantId, + intakeRequestId); + if (existing != null) { + SelectedOwnerIntakeSourceReadScope original = + SelectedOwnerIntakeSourceReadScope.fromStored(existing.get("scope_bytes", byte[].class)); + requireReservation(existing, original); + requireSameScope(original, namespace, owner, selected, current.stored().accountId); + requireCurrentReservation(existing, current); + if (aborted(original)) throw new IllegalStateException("Original source-read scope aborted"); + return original; + } + + admission.run(); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + namespace, + UUID.randomUUID(), + UUID.randomUUID(), + intakeRequestId, + current.stored().accountId, + selected); + dsl.execute( + "INSERT INTO " + + RESERVATIONS + + " (operation_id, fence_id, intake_request_id, owner, actor_account_uuid, tenant_uuid, " + + "version_uuid, scope_bytes, scope_digest, issuance_operation_id, issuance_fence, " + + "source_payload, issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + scope.operationId(), + scope.fenceId(), + intakeRequestId, + owner.name(), + scope.actorAccountId(), + tenantId, + selected.target().canonicalVersionId(), + scope.canonicalBytes(), + scope.digest(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + AccountControlUiAuthority.canonical(current.source().outboxCheckpoints())); + for (var source : current.source().sources()) { + dsl.execute( + "INSERT INTO " + + SOURCES + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + scope.operationId(), + source.key(), + source.canonicalBytes()); + } + requireReservation(reservation(scope), scope); + return scope; + } + + Optional findSourceReadScope( + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected, + String namespace, + String originalTokenHash) { + requireTransaction(); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(selected, "selected"); + requireOwner(owner); + Objects.requireNonNull(namespace, "namespace"); + Objects.requireNonNull(originalTokenHash, "originalTokenHash"); + var row = + dsl.fetchOne( + "SELECT * FROM " + RESERVATIONS + " WHERE tenant_uuid = ? AND intake_request_id = ?", + selected.target().canonicalTenantId(), + intakeRequestId); + if (row == null) return Optional.empty(); + var scope = SelectedOwnerIntakeSourceReadScope.fromStored(row.get("scope_bytes", byte[].class)); + requireReservation(row, scope); + requireSameScope(scope, namespace, owner, selected, scope.actorAccountId()); + var issuer = issuer(row.get("issuance_operation_id", UUID.class)); + if (!originalTokenHash.equals(issuer.tokenHash)) { + throw new IllegalArgumentException("Original creator credential differs from reservation"); + } + return Optional.of(scope); + } + + Recovery recoverSourceRead(SelectedOwnerIntakeSourceReadScope scope) { + requireTransaction(); + lockReservedSources(scope); + Record row = reservation(scope); + requireReservation(row, scope); + return new Recovery(scope, aborted(scope) ? State.ABORTED : State.RESERVED); + } + + Recovery abortSourceRead(SelectedOwnerIntakeSourceReadScope scope) { + requireTransaction(); + lockReservedSources(scope); + Record row = reservation(scope); + requireReservation(row, scope); + if (!aborted(scope)) { + dsl.execute("INSERT INTO " + ABORTS + " (operation_id) VALUES (?)", scope.operationId()); + } + return new Recovery(scope, State.ABORTED); + } + + SourceReadCurrentness sourceReadCurrentness(SelectedOwnerIntakeSourceReadScope scope) { + requireTransaction(); + Record row = reservation(scope); + requireReservation(row, scope); + if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + var original = issuer(row.get("issuance_operation_id", UUID.class)); + if (!"COMMITTED".equals(original.status)) + throw new IllegalStateException("Original creator issuance is no longer committed"); + return currentness(row, original); + } + + void readSourceScope(SelectedOwnerIntakeSourceReadScope scope, SourceReadCurrentness expected) { + requireTransaction(); + lockReservedSources(scope); + Record row = reservation(scope); + requireReservation(row, scope); + if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + var original = issuer(row.get("issuance_operation_id", UUID.class)); + if (!"COMMITTED".equals(original.status) || !currentness(row, original).equals(expected)) { + throw new IllegalStateException("Exact current pending source-read scope required"); + } + // Use the Account database clock only after the final sorted source and operation locks. + // A caller clock sampled before lock acquisition is not a live-read expiry proof. + if (dsl.fetchOne( + "SELECT operation_id FROM account_control_ui_issuance_operations" + + " WHERE operation_id = ? AND status = 'COMMITTED'" + + " AND extract(epoch FROM clock_timestamp()) < expires_at_epoch_second", + original.operationId) + == null) { + throw new IllegalStateException("Original creator issuance expired before final readback"); + } + } + + private SourceReadCurrentness currentness( + Record row, AccountControlUiIssuanceRepository.Stored original) { + return new SourceReadCurrentness( + original.tokenHash, + DraftAuthorizationFenceBinding.digest(original.activeRegistry), + original.expiresAt.getEpochSecond(), + issuerEvidenceDigest(row, original), + sourceVectorDigest(row.get("operation_id", UUID.class))); + } + + private String issuerEvidenceDigest( + Record reservation, AccountControlUiIssuanceRepository.Stored original) { + Map evidence = new LinkedHashMap<>(); + evidence.put("operationId", original.operationId.toString()); + evidence.put("requestId", original.requestId.toString()); + evidence.put("jti", original.jti.toString()); + evidence.put("accountId", original.accountId.toString()); + evidence.put("tenantId", original.tenantId.toString()); + evidence.put("caller", original.caller); + evidence.put("callerContextId", original.callerContextId.toString()); + evidence.put("requestMacKeyId", original.requestMacKeyId); + evidence.put("requestDigest", original.requestDigest); + evidence.put("status", original.status); + evidence.put("tokenHash", original.tokenHash); + evidence.put("claims", Base64.getEncoder().encodeToString(original.claims)); + evidence.put("sources", Base64.getEncoder().encodeToString(original.sources)); + evidence.put("bundle", Base64.getEncoder().encodeToString(original.bundle)); + evidence.put("signerReceipt", Base64.getEncoder().encodeToString(original.signerReceipt)); + evidence.put("pendingRegistry", Base64.getEncoder().encodeToString(original.pendingRegistry)); + evidence.put("activeRegistry", Base64.getEncoder().encodeToString(original.activeRegistry)); + evidence.put("issuedAt", original.issuedAt.toString()); + evidence.put("expiresAt", original.expiresAt.toString()); + evidence.put("recoveryExpiresAt", original.recoveryExpiry.toString()); + evidence.put( + "issuanceOperationId", reservation.get("issuance_operation_id", UUID.class).toString()); + evidence.put("issuanceFence", reservation.get("issuance_fence", Long.class).toString()); + evidence.put( + "outboxCheckpoints", + Base64.getEncoder().encodeToString(reservation.get("outbox_checkpoints", byte[].class))); + return DraftAuthorizationFenceBinding.digest(AccountControlUiAuthority.canonical(evidence)); + } + + private String sourceVectorDigest(UUID operationId) { + List> vector = new ArrayList<>(); + for (Record row : + dsl.fetch( + "SELECT source_key, source_evidence FROM " + + SOURCES + + " WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + operationId)) { + vector.add( + Map.of( + "sourceKey", row.get("source_key", String.class), + "sourceEvidence", + Base64.getEncoder().encodeToString(row.get("source_evidence", byte[].class)))); + } + return DraftAuthorizationFenceBinding.digest( + AccountControlUiAuthority.canonical(Map.of("sources", vector))); + } + + private Record reservation(SelectedOwnerIntakeSourceReadScope scope) { + return dsl.fetchOne( + "SELECT * FROM " + RESERVATIONS + " WHERE operation_id = ? FOR UPDATE", + scope.operationId()); + } + + private boolean aborted(SelectedOwnerIntakeSourceReadScope scope) { + return dsl.fetchOne( + "SELECT operation_id FROM " + ABORTS + " WHERE operation_id = ?", scope.operationId()) + != null; + } + + private void lockReservedSources(SelectedOwnerIntakeSourceReadScope scope) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + RESERVATIONS + " WHERE operation_id = ?", scope.operationId()); + requireReservation(row, scope); + for (Record source : + dsl.fetch( + "SELECT source_key FROM " + + SOURCES + + " WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + scope.operationId())) { + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE", + source.get("source_key", String.class)) + == null) { + throw new IllegalStateException("Original preliminary source lock is unavailable"); + } + } + } + + private void requireReservation(Record row, SelectedOwnerIntakeSourceReadScope scope) { + if (row == null + || !Arrays.equals(scope.canonicalBytes(), row.get("scope_bytes", byte[].class)) + || !scope.digest().equals(row.get("scope_digest", String.class)) + || !scope.operationId().equals(row.get("operation_id", UUID.class)) + || !scope.fenceId().equals(row.get("fence_id", UUID.class)) + || !scope.intakeRequestId().equals(row.get("intake_request_id", UUID.class)) + || !scope.owner().name().equals(row.get("owner", String.class)) + || !scope.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !scope.selected().target().canonicalTenantId().equals(row.get("tenant_uuid", UUID.class)) + || !scope + .selected() + .target() + .canonicalVersionId() + .equals(row.get("version_uuid", UUID.class))) { + throw new IllegalArgumentException("Original preliminary source scope is absent or changed"); + } + var original = issuer(row.get("issuance_operation_id", UUID.class)); + if (!scope.actorAccountId().equals(original.accountId) + || !scope.selected().target().canonicalTenantId().equals(original.tenantId) + || !Arrays.equals(original.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(original.bundle, row.get("issuance_bundle", byte[].class))) { + throw new IllegalArgumentException("Original preliminary creator evidence changed"); + } + var bundle = AccountControlUiIssuanceRepository.object(original.bundle); + Object fence = bundle.get("issuanceFence"); + if (!Long.toString(row.get("issuance_fence", Long.class)).equals(String.valueOf(fence))) { + throw new IllegalArgumentException("Original creator issuance fence changed"); + } + var checkpoints = bundle.get("outboxCheckpoints"); + if (!Arrays.equals( + AccountControlUiAuthority.canonical(checkpoints), + row.get("outbox_checkpoints", byte[].class))) { + throw new IllegalArgumentException("Original creator checkpoints changed"); + } + + Object storedSources = + AccountControlUiIssuanceRepository.object(original.sources).get("sources"); + List held = + dsl.fetch( + "SELECT source_key, source_evidence FROM " + + SOURCES + + " WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + scope.operationId()); + if (!(storedSources instanceof List values) + || values.isEmpty() + || held.size() != values.size()) { + throw new IllegalArgumentException("Incomplete original creator source participation"); + } + for (int index = 0; index < values.size(); index++) { + if (!(values.get(index) instanceof String encoded)) { + throw new IllegalArgumentException("Malformed original creator source vector"); + } + byte[] exact = Base64.getDecoder().decode(encoded); + var source = DraftAuthorizationFenceBinding.SourceEvidence.fromStored(exact); + if (!source.key().equals(held.get(index).get("source_key", String.class)) + || !Arrays.equals(exact, held.get(index).get("source_evidence", byte[].class))) { + throw new IllegalArgumentException("Changed original complete source participation"); + } + } + } + + private AccountControlUiIssuanceRepository.Stored issuer(UUID operationId) { + Record issuer = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE operation_id = ?", + operationId); + if (issuer == null) throw new IllegalStateException("Original creator issuance is unavailable"); + return new AccountControlUiIssuanceRepository.Stored(issuer); + } + + private static void requireSameScope( + SelectedOwnerIntakeSourceReadScope scope, + String namespace, + Owner owner, + DraftCommitBinding selected, + UUID actorAccountId) { + if (!namespace.equals(scope.targetNamespace()) + || owner != scope.owner() + || !selected.equals(scope.selected()) + || !actorAccountId.equals(scope.actorAccountId())) { + throw new IllegalArgumentException("Intake request conflicts with its original source scope"); + } + } + + private static void requireOwner(Owner owner) { + if (owner != Owner.ENTITY_MANAGEMENT && owner != Owner.AUTOMATION_SCRIPTING) { + throw new IllegalArgumentException("Entity or Automation selected-source owner required"); + } + } + + private void requireCurrentReservation(Record row, AccountControlUiActorService.Current current) { + var original = issuer(row.get("issuance_operation_id", UUID.class)); + if (!"COMMITTED".equals(original.status) + || !original.operationId.equals(current.stored().operationId) + || !Arrays.equals(current.stored().sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(current.stored().bundle, row.get("issuance_bundle", byte[].class)) + || !Arrays.equals( + AccountControlUiAuthority.canonical(current.source().outboxCheckpoints()), + row.get("outbox_checkpoints", byte[].class))) { + throw new IllegalArgumentException("Changed original intake creator authority"); + } + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account owner transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Writable READ_COMMITTED Account owner transaction required"); + } + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java new file mode 100644 index 0000000000..571ae7e553 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java @@ -0,0 +1,199 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered preliminary source-read producer; it grants no owner retention authority. */ +public final class AccountSelectedOwnerIntakeSourceReservationService { + private final AccountControlUiActorService actors; + private final DraftAuthorizationFenceRepository fences; + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final String namespace; + private final TransactionTemplate ownerTransaction; + + public AccountSelectedOwnerIntakeSourceReservationService( + AccountControlUiActorService actors, + DraftAuthorizationFenceRepository fences, + AccountSelectedOwnerIntakeSourceReservationRepository repository, + PlatformTransactionManager transactions, + String namespace) { + this.actors = Objects.requireNonNull(actors, "actors"); + this.fences = Objects.requireNonNull(fences, "fences"); + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Reserves one fresh source-read scope under the current creator, or recovers the exact existing + * request by its original credential hash. An expired credential cannot create a reservation. + */ + public SelectedOwnerIntakeSourceReadScope reserveSourceRead( + String compactJwt, + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected, + CapturedEnvironmentBoundary environment) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + requireOwner(owner); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + Objects.requireNonNull(selected, "selected"); + Objects.requireNonNull(environment, "current Account environment is required"); + + Optional retained = + findScope(compactJwt, intakeRequestId, owner, selected); + if (retained.isPresent()) { + var recovery = recover(retained.orElseThrow()); + if (recovery.state() == AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED) + throw Status.FAILED_PRECONDITION + .withDescription("Original source-read reservation was aborted") + .asRuntimeException(); + return recovery.scope(); + } + + return actors.withCurrent( + compactJwt, + selected.target().canonicalTenantId(), + environment, + current -> { + fences.requireSelectedOwnerIntakeAdmission(current.source().sources(), selected); + return repository.reserveSourceRead( + intakeRequestId, owner, selected, current, namespace, () -> {}); + }); + } + + /** Historical exact recovery; it never renews authority or reopens an aborted reservation. */ + public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery recover( + SelectedOwnerIntakeSourceReadScope scope) { + requireGameDesignPeer(); + requireScope(scope); + requireNoAmbientTransaction(); + return Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.recoverSourceRead(scope))); + } + + /** Finds a lost first response from the original stable identity and exact credential hash. */ + public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery recover( + String originalCompactJwt, UUID intakeRequestId, Owner owner, DraftCommitBinding selected) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + requireOwner(owner); + Objects.requireNonNull(selected, "selected"); + var scope = + findScope(originalCompactJwt, intakeRequestId, owner, selected) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Original source-read reservation is unavailable") + .asRuntimeException()); + return recover(scope); + } + + /** A definitive abort locks only this reservation's sorted source participation. */ + public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery abortSourceRead( + SelectedOwnerIntakeSourceReadScope scope) { + requireGameDesignPeer(); + requireScope(scope); + requireNoAmbientTransaction(); + return Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.abortSourceRead(scope))); + } + + /** Aborts the exact original operation even after credential expiry; it does not renew it. */ + public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery abortSourceRead( + String originalCompactJwt, UUID intakeRequestId, Owner owner, DraftCommitBinding selected) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + requireOwner(owner); + Objects.requireNonNull(selected, "selected"); + var scope = + findScope(originalCompactJwt, intakeRequestId, owner, selected) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Original source-read reservation is unavailable") + .asRuntimeException()); + return abortSourceRead(scope); + } + + private Optional findScope( + String originalCompactJwt, UUID intakeRequestId, Owner owner, DraftCommitBinding selected) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + requireOwner(owner); + Objects.requireNonNull(selected, "selected"); + if (originalCompactJwt == null + || originalCompactJwt.isEmpty() + || originalCompactJwt.length() > 16384 + || !StandardCharsets.US_ASCII.newEncoder().canEncode(originalCompactJwt)) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + String tokenHash = + AccountControlUiIssuanceRepository.hash( + originalCompactJwt.getBytes(StandardCharsets.US_ASCII)); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository.findSourceReadScope( + intakeRequestId, owner, selected, namespace, tokenHash))); + } + + private void requireScope(SelectedOwnerIntakeSourceReadScope scope) { + if (scope == null + || !namespace.equals(scope.targetNamespace()) + || (scope.owner() != Owner.ENTITY_MANAGEMENT + && scope.owner() != Owner.AUTOMATION_SCRIPTING)) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private static void requireOwner(Owner owner) { + if (owner != Owner.ENTITY_MANAGEMENT && owner != Owner.AUTOMATION_SCRIPTING) + throw Status.INVALID_ARGUMENT + .withDescription("Entity or Automation selected-source owner required") + .asRuntimeException(); + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Game Design workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected-owner Account reservation requires an independent transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcService.java new file mode 100644 index 0000000000..1586df3f5b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcService.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationHistoricalReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Standalone unregistered same-namespace Account historical participation receiver. */ +public final class AccountStartSessionWorldParticipationHistoricalReadGrpcService + extends AccountStartSessionWorldParticipationHistoricalReadServiceGrpc + .AccountStartSessionWorldParticipationHistoricalReadServiceImplBase { + private final AccountStartSessionWorldParticipationHistoricalReadService owner; + private final String workloadNamespace; + + public AccountStartSessionWorldParticipationHistoricalReadGrpcService( + AccountStartSessionWorldParticipationHistoricalReadService owner, String workloadNamespace) { + this.owner = Objects.requireNonNull(owner, "historical participation owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readHistoricalStartSessionWorldParticipation( + ReadHistoricalStartSessionWorldParticipationRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (SessionContext.hasAuthenticatedCallerContext() + || !workloadNamespace.equals(peer.namespace()) + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service")) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (request == null) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + // Bind the raw selector before decoding any other caller-controlled request fields. + if (!workloadNamespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + final net.firedevops.firemud.common.account.startsession + .AccountStartSessionWorldParticipationHistoricalReadRequest + decoded; + try { + decoded = AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var evidence = owner.read(decoded); + observer.onNext( + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse( + decoded, evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + } catch (IllegalArgumentException | IllegalStateException mismatch) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java new file mode 100644 index 0000000000..330757f791 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadRequest; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered lookup-only Account read for exact historical World StartSession reconciliation. + * + *

It returns retained identity only. It does not establish fresh currentness, admit or restart + * World execution, renew an authorization reference, or prove the original Game Session operation. + */ +public final class AccountStartSessionWorldParticipationHistoricalReadService { + private final AccountStartSessionWorldParticipationRepository repository; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public AccountStartSessionWorldParticipationHistoricalReadService( + AccountStartSessionWorldParticipationRepository repository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "participation repository is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Reads the exact retained row by its independent participation ID and fence, including after + * original ingress expiry or prior immutable terminal settlement. + */ + public AccountStartSessionWorldParticipationHistoricalReadEvidence read( + AccountStartSessionWorldParticipationHistoricalReadRequest request) { + requireWorldPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(request, "historical participation request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Historical participation namespace differs from the configured World peer") + .asRuntimeException(); + } + + StoredParticipation participation = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository + .findHistoricalExact( + request.accountWorldParticipationId(), + request.accountWorldParticipationFence()) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Exact historical World participation is unavailable") + .asRuntimeException())), + "Account historical participation transaction returned no result"); + + if (!participation.participationId().equals(request.accountWorldParticipationId()) + || participation.participationFence() != request.accountWorldParticipationFence() + || !workloadNamespace.equals(participation.targetNamespace())) { + throw Status.FAILED_PRECONDITION + .withDescription("Stored World participation differs from the exact historical lookup") + .asRuntimeException(); + } + try { + return new AccountStartSessionWorldParticipationHistoricalReadEvidence( + request, + participation.originalPostAuthorizationTuple(), + participation.gameSessionOwnerAttemptId(), + participation.gameSessionOwnerFence(), + participation.canonicalGameInstanceId(), + participation.preparationInputJson(), + participation.preparationInputDigest()); + } catch (IllegalArgumentException malformedStorage) { + throw Status.FAILED_PRECONDITION + .withDescription("Stored World participation identity is not exact") + .withCause(malformedStorage) + .asRuntimeException(); + } + } + + private void requireWorldPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified World workload identity required") + .asRuntimeException(); + } + if (SessionContext.hasAuthenticatedCallerContext() + || !workloadNamespace.equals(peer.namespace()) + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service")) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Historical World participation read requires an independent Account transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V129__start_session_world_participation.sql b/services/account-service/src/main/resources/db/migration/V129__start_session_world_participation.sql index e553c2faba..16fbdad0f0 100644 --- a/services/account-service/src/main/resources/db/migration/V129__start_session_world_participation.sql +++ b/services/account-service/src/main/resources/db/migration/V129__start_session_world_participation.sql @@ -314,7 +314,7 @@ $$; CREATE FUNCTION account_start_session_world_participation_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ DECLARE - authorization account_start_session_operator_authorizations%ROWTYPE; + authorization_row account_start_session_operator_authorizations%ROWTYPE; capture account_start_session_authority_captures%ROWTYPE; tuple_value JSONB; reservation_value JSONB; @@ -340,15 +340,15 @@ BEGIN source_keys := account_start_session_world_participation_lock_sources(snapshot_value); PERFORM account_start_session_world_participation_assert_exclusive(source_keys, snapshot_value); - SELECT * INTO STRICT authorization FROM account_start_session_operator_authorizations + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations WHERE control_plane_request_id = NEW.control_plane_request_id; tuple_value := convert_from(NEW.original_post_authorization_tuple, 'UTF8')::JSONB; - IF authorization.status IS DISTINCT FROM 'REDEEMED' - OR authorization.reference_expires_at <= clock_timestamp() + IF authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.reference_expires_at <= clock_timestamp() OR tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM - convert_from(authorization.pre_authorization_tuple, 'UTF8')::JSONB - OR authorization.redemption_owner_attempt_id IS DISTINCT FROM NEW.game_session_owner_attempt_id - OR authorization.redemption_owner_fence IS DISTINCT FROM NEW.game_session_owner_fence THEN + convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM NEW.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM NEW.game_session_owner_fence THEN RAISE EXCEPTION 'StartSession World participation requires the exact unexpired redeemed original authorization' USING ERRCODE = '23514'; END IF; @@ -358,31 +358,31 @@ BEGIN OR tuple_value->>'tupleSchemaVersion' IS DISTINCT FROM '1' OR tuple_value->>'issuanceKind' IS DISTINCT FROM 'human_operator' OR tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id - OR tuple_value->>'mutationDigest' IS DISTINCT FROM authorization.mutation_digest + OR tuple_value->>'mutationDigest' IS DISTINCT FROM authorization_row.mutation_digest OR tuple_value->>'authorizationReferenceFingerprint' IS DISTINCT FROM - authorization.authorization_reference_fingerprint - OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization.issuance_fence::TEXT - OR tuple_value->>'reservationOwnerId' IS DISTINCT FROM authorization.reservation_owner_id::TEXT - OR tuple_value->>'reservationClaimFence' IS DISTINCT FROM authorization.reservation_claim_fence::TEXT + authorization_row.authorization_reference_fingerprint + OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization_row.issuance_fence::TEXT + OR tuple_value->>'reservationOwnerId' IS DISTINCT FROM authorization_row.reservation_owner_id::TEXT + OR tuple_value->>'reservationClaimFence' IS DISTINCT FROM authorization_row.reservation_claim_fence::TEXT OR tuple_value->>'authorityEvidenceBundleReference' IS NULL - OR bundle_reference->>'bundleVersion' IS DISTINCT FROM authorization.bundle_version - OR bundle_reference->>'sourceVersion' IS DISTINCT FROM authorization.bundle_source_version - OR bundle_reference->>'sourceFence' IS DISTINCT FROM authorization.bundle_source_fence - OR bundle_reference->>'linearization' IS DISTINCT FROM authorization.bundle_linearization + OR bundle_reference->>'bundleVersion' IS DISTINCT FROM authorization_row.bundle_version + OR bundle_reference->>'sourceVersion' IS DISTINCT FROM authorization_row.bundle_source_version + OR bundle_reference->>'sourceFence' IS DISTINCT FROM authorization_row.bundle_source_fence + OR bundle_reference->>'linearization' IS DISTINCT FROM authorization_row.bundle_linearization OR tuple_value->'authorityEvidenceBundle' IS DISTINCT FROM - convert_from(authorization.authority_evidence_bundle, 'UTF8')::JSONB - OR authorization.redemption_reference_fingerprint IS DISTINCT FROM - authorization.authorization_reference_fingerprint - OR authorization.redemption_authority_evidence_bundle IS DISTINCT FROM - authorization.authority_evidence_bundle - OR capture.pre_authorization_tuple IS DISTINCT FROM authorization.pre_authorization_tuple + convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB + OR authorization_row.redemption_reference_fingerprint IS DISTINCT FROM + authorization_row.authorization_reference_fingerprint + OR authorization_row.redemption_authority_evidence_bundle IS DISTINCT FROM + authorization_row.authority_evidence_bundle + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization_row.pre_authorization_tuple OR capture.account_uuid IS DISTINCT FROM (tuple_value->'actor'->>'accountId')::UUID OR capture.tenant_uuid IS DISTINCT FROM NEW.canonical_tenant_id OR capture.target_owner IS DISTINCT FROM tuple_value->'targetOwner'->>'ownerService' - OR capture.mutation_digest IS DISTINCT FROM authorization.mutation_digest - OR capture.reservation_owner_id IS DISTINCT FROM authorization.reservation_owner_id - OR capture.reservation_claim_fence IS DISTINCT FROM authorization.reservation_claim_fence - OR capture.issuance_fence IS DISTINCT FROM authorization.issuance_fence + OR capture.mutation_digest IS DISTINCT FROM authorization_row.mutation_digest + OR capture.reservation_owner_id IS DISTINCT FROM authorization_row.reservation_owner_id + OR capture.reservation_claim_fence IS DISTINCT FROM authorization_row.reservation_claim_fence + OR capture.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence OR capture.source_version::TEXT IS DISTINCT FROM bundle_reference->>'sourceVersion' OR capture.source_fence::TEXT IS DISTINCT FROM bundle_reference->>'sourceFence' OR capture.linearization IS DISTINCT FROM bundle_reference->>'linearization' diff --git a/services/account-service/src/main/resources/db/migration/V130__selected_owner_intake_source_reservations.sql b/services/account-service/src/main/resources/db/migration/V130__selected_owner_intake_source_reservations.sql new file mode 100644 index 0000000000..54f460da6b --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V130__selected_owner_intake_source_reservations.sql @@ -0,0 +1,428 @@ +-- Preliminary Entity/Automation source participation only; no finalized owner authorization. +CREATE TABLE account_selected_owner_intake_source_read_reservations ( + operation_id UUID PRIMARY KEY, + fence_id UUID NOT NULL UNIQUE, + intake_request_id UUID NOT NULL, + owner VARCHAR(32) NOT NULL CHECK (owner IN ('ENTITY_MANAGEMENT', 'AUTOMATION_SCRIPTING')), + actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + version_uuid UUID NOT NULL, + scope_bytes BYTEA NOT NULL CHECK (octet_length(scope_bytes) BETWEEN 1 AND 4194304), + scope_digest VARCHAR(71) NOT NULL CHECK (scope_digest ~ '^sha256:[0-9a-f]{64}$'), + issuance_operation_id UUID NOT NULL REFERENCES account_control_ui_issuance_operations(operation_id), + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + issuance_bundle BYTEA NOT NULL CHECK (octet_length(issuance_bundle) BETWEEN 1 AND 131072), + outbox_checkpoints BYTEA NOT NULL CHECK (octet_length(outbox_checkpoints) BETWEEN 1 AND 131072), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + reserved_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (fence_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (intake_request_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (actor_account_uuid <> '00000000-0000-0000-0000-000000000000'), + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'), + CHECK (version_uuid <> '00000000-0000-0000-0000-000000000000'), + UNIQUE (tenant_uuid, intake_request_id) +); +CREATE TABLE account_selected_owner_intake_source_read_sources ( + operation_id UUID NOT NULL REFERENCES account_selected_owner_intake_source_read_reservations(operation_id), + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_selected_owner_intake_source_read_lookup + ON account_selected_owner_intake_source_read_sources(source_key, operation_id); +CREATE TABLE account_selected_owner_intake_source_read_aborts ( + operation_id UUID PRIMARY KEY REFERENCES account_selected_owner_intake_source_read_reservations(operation_id), + aborted_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- [jooq ignore start] +CREATE FUNCTION account_selected_owner_intake_source_read_is_pending(operation_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_reservations reservation + WHERE reservation.operation_id = operation_value + AND NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_aborts aborted + WHERE aborted.operation_id = reservation.operation_id)); +$$; + +CREATE FUNCTION account_selected_owner_intake_source_read_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + p INTEGER := 1; + q INTEGER := 1; + parsed BYTEA; + selected_bytes BYTEA; + selected JSONB; + namespace_value TEXT; + owner_value TEXT; + purpose_value TEXT; + reader_value TEXT; + source_bytes BYTEA; + source_kind TEXT; + source_scope TEXT; + source_key_value TEXT; + marker TEXT; + ignored_frame BYTEA; + source_position INTEGER; + source_count INTEGER := 0; + seen TEXT[] := ARRAY[]::TEXT[]; + issuer account_control_ui_issuance_operations%ROWTYPE; + original account_draft_authorization_fences%ROWTYPE; + vector JSONB; +BEGIN + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations + WHERE operation_id = NEW.issuance_operation_id; + IF NEW.producer_xid <> txid_current() + OR issuer.status IS DISTINCT FROM 'COMMITTED' + OR extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second + OR issuer.account_uuid IS DISTINCT FROM NEW.actor_account_uuid + OR issuer.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR issuer.source_payload IS DISTINCT FROM NEW.source_payload + OR issuer.bundle_payload IS DISTINCT FROM NEW.issuance_bundle + OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT IS DISTINCT FROM NEW.issuance_fence + OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' + IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB + OR NEW.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.scope_bytes), 'hex') THEN + RAISE EXCEPTION 'Preliminary owner scope requires exact current committed creator evidence' + USING ERRCODE = '23514'; + END IF; + + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') NOT IN ( + 'account-entity-intake-source-read/v1', 'account-automation-intake-source-read/v1') THEN + RAISE EXCEPTION 'Invalid preliminary owner scope schema' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO owner_value, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF owner_value IS DISTINCT FROM NEW.owner + OR (NEW.owner = 'ENTITY_MANAGEMENT' + AND convert_from(parsed, 'UTF8') <> 'account-entity-intake-source-read/v1') + OR (NEW.owner = 'AUTOMATION_SCRIPTING' + AND convert_from(parsed, 'UTF8') <> 'account-automation-intake-source-read/v1') THEN + RAISE EXCEPTION 'Preliminary owner schema and owner differ' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF namespace_value !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' THEN + RAISE EXCEPTION 'Invalid preliminary owner namespace' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.operation_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary owner operation' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.fence_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary owner fence' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.intake_request_id::TEXT THEN + RAISE EXCEPTION 'Changed preliminary owner request' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Changed preliminary owner actor' USING ERRCODE = '23514'; END IF; + SELECT frame_value, next_position INTO selected_bytes, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + selected := convert_from(selected_bytes, 'UTF8')::JSONB; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'sha256:' || encode(sha256(selected_bytes), 'hex') + OR selected->>'requestId' IS NULL OR selected->>'commitId' IS NULL + OR jsonb_typeof(selected->'requiredOwners') IS DISTINCT FROM 'array' + OR selected->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR selected->>'canonicalVersionId' IS DISTINCT FROM NEW.version_uuid::TEXT THEN + RAISE EXCEPTION 'Changed preliminary owner complete selection' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO reader_value, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF reader_value IS DISTINCT FROM 'spiffe://firemud/ns/' || namespace_value || '/sa/account-service' THEN + RAISE EXCEPTION 'Invalid preliminary owner intended reader' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO purpose_value, p + FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); + IF purpose_value IS DISTINCT FROM CASE NEW.owner + WHEN 'ENTITY_MANAGEMENT' THEN 'ENTITY_INTAKE_SOURCE' + WHEN 'AUTOMATION_SCRIPTING' THEN 'AUTOMATION_INTAKE_SOURCE' + ELSE NULL END + OR p <> octet_length(NEW.scope_bytes) + 1 THEN + RAISE EXCEPTION 'Invalid preliminary owner purpose or trailing scope bytes' USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT original FROM account_draft_authorization_fences + WHERE request_id = (selected->>'requestId')::UUID + AND commit_id = (selected->>'commitId')::UUID; + PERFORM account_draft_authorization_required_owners(original.binding); + FOR i IN 1..11 LOOP + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(original.binding, q); + END LOOP; + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(original.binding, q); + IF parsed IS DISTINCT FROM selected_bytes + OR original.ordering IS DISTINCT FROM 'COMMIT_ORDER' + OR NOT account_draft_authorization_is_settled(original.operation_id) + OR EXISTS (SELECT 1 FROM account_draft_authorization_owner_readbacks + WHERE operation_id = original.operation_id AND outcome IS DISTINCT FROM 'COMMITTED') + OR (SELECT count(*) FROM account_draft_authorization_owner_readbacks + WHERE operation_id = original.operation_id) + IS DISTINCT FROM cardinality(account_draft_authorization_required_owners(original.binding)) THEN + RAISE EXCEPTION 'Exact original creator Draft must be committed and settled before source read' + USING ERRCODE = '23514'; + END IF; + + vector := convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'; + IF jsonb_typeof(vector) IS DISTINCT FROM 'array' + OR jsonb_array_length(vector) < 1 + OR jsonb_array_length(vector) IS DISTINCT FROM + (SELECT count(*) FROM account_selected_owner_intake_source_read_sources + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Incomplete preliminary complete Account source participation' + USING ERRCODE = '23514'; + END IF; + FOR source_bytes IN SELECT decode(value, 'base64') FROM jsonb_array_elements_text(vector) LOOP + source_count := source_count + 1; + source_position := 1; + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF convert_from(parsed, 'UTF8') <> 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Invalid preliminary Account source schema' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_kind, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF source_kind NOT IN ('ISSUER', 'ACCOUNT', 'TENANT', 'MEMBERSHIP', 'GLOBAL_ROLES', 'CREATOR_PARTY', 'HOSTED_TERMS') THEN + RAISE EXCEPTION 'Invalid preliminary Account source kind' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_scope, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF marker = 'PRESENT' THEN + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF marker !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid preliminary source generation' USING ERRCODE = '23514'; END IF; + ELSIF marker <> 'ABSENT' THEN + RAISE EXCEPTION 'Invalid preliminary source generation marker' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF marker !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid preliminary source version' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF marker = 'PRESENT' THEN + SELECT frame_value, next_position INTO ignored_frame, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF octet_length(ignored_frame) = 0 THEN + RAISE EXCEPTION 'Invalid preliminary source checkpoint stream' USING ERRCODE = '23514'; END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF marker !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid preliminary source checkpoint sequence' USING ERRCODE = '23514'; END IF; + ELSIF marker <> 'ABSENT' THEN + RAISE EXCEPTION 'Invalid preliminary source checkpoint marker' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO ignored_frame, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := source_kind || ':' || source_scope; + IF octet_length(source_bytes) > 131072 OR source_scope = '' + OR source_position <> octet_length(source_bytes) + 1 + OR octet_length(ignored_frame) = 0 + OR source_key_value = ANY(seen) + OR NOT EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_sources + WHERE operation_id = NEW.operation_id AND source_key = source_key_value + AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Changed or noncanonical preliminary complete Account source vector' + USING ERRCODE = '23514'; + END IF; + seen := array_append(seen, source_key_value); + END LOOP; + IF source_count <> jsonb_array_length(vector) THEN + RAISE EXCEPTION 'Incomplete preliminary Account source vector' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER account_selected_owner_intake_source_read_complete + AFTER INSERT ON account_selected_owner_intake_source_read_reservations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_selected_owner_intake_source_read_complete_guard(); + +CREATE FUNCTION account_selected_owner_intake_source_read_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id AND producer_xid = txid_current()) THEN + RAISE EXCEPTION 'Preliminary owner sources must accompany original reservation transaction' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_selected_owner_intake_source_read_source_validate + BEFORE INSERT ON account_selected_owner_intake_source_read_sources FOR EACH ROW + EXECUTE FUNCTION account_selected_owner_intake_source_read_source_insert_guard(); + +CREATE FUNCTION account_selected_owner_intake_source_read_abort_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + PERFORM lock_row.source_key FROM account_draft_authorization_source_locks lock_row + JOIN account_selected_owner_intake_source_read_sources source + ON source.source_key = lock_row.source_key + WHERE source.operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(lock_row.source_key) + FOR UPDATE OF lock_row; + PERFORM operation_id FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF NOT FOUND OR EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_aborts + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Only the exact active preliminary owner reservation can be aborted' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_selected_owner_intake_source_read_abort_validate + BEFORE INSERT ON account_selected_owner_intake_source_read_aborts FOR EACH ROW + EXECUTE FUNCTION account_selected_owner_intake_source_read_abort_guard(); + +CREATE TRIGGER account_selected_owner_intake_source_read_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_source_read_reservations + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_source_read_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_source_read_reservations + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_source_read_sources_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_source_read_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_source_read_sources_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_source_read_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_source_read_aborts_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_source_read_aborts + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_source_read_aborts_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_source_read_aborts + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +-- Keep the current V129 assembled source-writer hook and add this independent owner participation. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_draft_authorization_sources s$anchor$; + owner_guard TEXT := $guard$ FOR operation_value IN SELECT DISTINCT source.operation_id + FROM account_selected_owner_intake_source_read_sources source + WHERE source.source_key = ANY(source_keys) + AND account_selected_owner_intake_source_read_is_pending(source.operation_id) + ORDER BY source.operation_id LOOP + PERFORM operation_id FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = operation_value FOR UPDATE NOWAIT; + RAISE EXCEPTION 'Selected owner intake source read remains pending for a required source' + USING ERRCODE = '55P03'; + END LOOP; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one current Account source-writer anchor'; + END IF; + EXECUTE replace(original, anchor, owner_guard || anchor); +END; +$migration$; + +-- Pending reservations exclude terminal source changes after the current V129 sorted source locks. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ FOR operation IN SELECT DISTINCT source.operation_id + FROM account_draft_authorization_changed_scopes changed$anchor$; + owner_guard TEXT := $guard$ IF EXISTS ( + SELECT 1 FROM account_draft_authorization_changed_scopes changed + JOIN account_selected_owner_intake_source_read_sources source + ON source.source_key = changed.source_key + WHERE changed.change_id = OLD.change_id + AND account_selected_owner_intake_source_read_is_pending(source.operation_id) + ) THEN + PERFORM reservation.operation_id + FROM account_draft_authorization_changed_scopes changed + JOIN account_selected_owner_intake_source_read_sources source + ON source.source_key = changed.source_key + JOIN account_selected_owner_intake_source_read_reservations reservation + ON reservation.operation_id = source.operation_id + WHERE changed.change_id = OLD.change_id + AND account_selected_owner_intake_source_read_is_pending(source.operation_id) + ORDER BY reservation.operation_id FOR UPDATE OF reservation NOWAIT; + RAISE EXCEPTION 'Pending selected owner intake source read excludes source-change completion' + USING ERRCODE = '55P03'; + END IF; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_draft_authorization_source_change_guard()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one current V129 source-change anchor'; + END IF; + EXECUTE replace(original, anchor, owner_guard || anchor); +END; +$migration$; + +-- A hosted-terms dispatch/retry cannot disclose a source vector still reserved for an owner read. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED'$anchor$; + owner_guard TEXT := $guard$ IF OLD.status IN ('PREPARED', 'AMBIGUOUS') + AND NEW.status = 'DISPATCH_AUTHORIZED' THEN + PERFORM source_lock.source_key + FROM account_draft_authorization_source_locks source_lock + JOIN ( + SELECT OLD.source_key AS source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id + ) exact_source USING (source_key) + ORDER BY account_publication_authorization_source_sort_key(source_lock.source_key) + FOR UPDATE OF source_lock NOWAIT; + IF EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_sources source + WHERE source.source_key IN ( + SELECT OLD.source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id) + AND account_selected_owner_intake_source_read_is_pending(source.operation_id) + ) THEN + PERFORM reservation.operation_id + FROM account_selected_owner_intake_source_read_sources source + JOIN account_selected_owner_intake_source_read_reservations reservation + ON reservation.operation_id = source.operation_id + WHERE source.source_key IN ( + SELECT OLD.source_key + UNION + SELECT handoff_source.source_key + FROM account_hosted_terms_disclosure_sources handoff_source + WHERE handoff_source.handoff_id = OLD.handoff_id) + AND account_selected_owner_intake_source_read_is_pending(source.operation_id) + ORDER BY reservation.operation_id FOR UPDATE OF reservation NOWAIT; + RAISE EXCEPTION 'Pending selected owner intake source read excludes hosted-terms dispatch' + USING ERRCODE = '55P03'; + END IF; + END IF; +$guard$; +BEGIN + SELECT pg_get_functiondef('account_hosted_terms_disclosure_handoff_guard()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one current V129 hosted-terms dispatch anchor'; + END IF; + EXECUTE replace(original, anchor, owner_guard || anchor); +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java new file mode 100644 index 0000000000..80a6316cc1 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java @@ -0,0 +1,209 @@ +package integration.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; + +/** PostgreSQL installation proof for V130's additive selected-owner source reservations. */ +class AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest { + @Test + void installsV130OverV129WorldGuardsAndRejectsMalformedReservationWithoutSourceRows() { + var fixture = new AccountPostgresIntegrationFixture(); + try { + fixture.start(); + String schema = "selected_owner_source_" + UUID.randomUUID().toString().replace("-", ""); + JdbcTemplate admin = new JdbcTemplate(fixture.dataSource()); + try { + admin.execute("CREATE SCHEMA " + quotedSchema(schema)); + DriverManagerDataSource source = fixture.dataSource(schema); + JdbcTemplate jdbc = new JdbcTemplate(source); + + migration(source, schema, "129").migrate(); + assertVersionApplied(jdbc, schema, "129"); + assertVersionNotApplied(jdbc, schema, "130"); + assertWorldSourceExclusionGuards( + functionDefinition(jdbc, "account_control_ui_hold_required_sources(text[])"), + functionDefinition(jdbc, "account_draft_authorization_source_change_guard()"), + functionDefinition(jdbc, "account_hosted_terms_disclosure_handoff_guard()")); + + migration(source, schema, "130").migrate(); + assertVersionApplied(jdbc, schema, "129"); + assertVersionApplied(jdbc, schema, "130"); + assertInstalledOwnerReservationSchema(jdbc, schema); + + String holdGuard = + functionDefinition(jdbc, "account_control_ui_hold_required_sources(text[])"); + String sourceChangeGuard = + functionDefinition(jdbc, "account_draft_authorization_source_change_guard()"); + String disclosureGuard = + functionDefinition(jdbc, "account_hosted_terms_disclosure_handoff_guard()"); + assertWorldSourceExclusionGuards(holdGuard, sourceChangeGuard, disclosureGuard); + assertThat(holdGuard) + .contains( + "account_selected_owner_intake_source_read_sources source", + "account_selected_owner_intake_source_read_is_pending(source.operation_id)", + "Selected owner intake source read remains pending for a required source"); + assertThat(sourceChangeGuard) + .contains( + "account_selected_owner_intake_source_read_sources source", + "Pending selected owner intake source read excludes source-change completion"); + assertThat(disclosureGuard) + .contains( + "account_selected_owner_intake_source_read_sources source", + "Pending selected owner intake source read excludes hosted-terms dispatch"); + + assertMalformedReservationCreatesNoSourceRows(jdbc); + } finally { + admin.execute("DROP SCHEMA IF EXISTS " + quotedSchema(schema) + " CASCADE"); + } + } finally { + fixture.stop(); + } + } + + private static Flyway migration( + DriverManagerDataSource source, String schema, String targetVersion) { + return Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion(targetVersion)) + .load(); + } + + private static void assertInstalledOwnerReservationSchema(JdbcTemplate jdbc, String schema) { + assertThat( + Objects.requireNonNull( + jdbc.queryForObject( + "SELECT count(*) FROM unnest(ARRAY[" + + "'account_selected_owner_intake_source_read_reservations', " + + "'account_selected_owner_intake_source_read_sources', " + + "'account_selected_owner_intake_source_read_aborts']::TEXT[]) " + + "AS names(name) WHERE to_regclass(name) IS NOT NULL", + Long.class))) + .isEqualTo(3L); + + assertThat( + Objects.requireNonNull( + jdbc.queryForObject( + "SELECT count(*) FROM pg_trigger trigger_row " + + "JOIN pg_class relation ON relation.oid = trigger_row.tgrelid " + + "JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace " + + "WHERE namespace.nspname = ? AND NOT trigger_row.tgisinternal " + + "AND trigger_row.tgname IN (" + + "'account_selected_owner_intake_source_read_complete', " + + "'account_selected_owner_intake_source_read_source_validate', " + + "'account_selected_owner_intake_source_read_abort_validate', " + + "'account_selected_owner_intake_source_read_immutable', " + + "'account_selected_owner_intake_source_read_no_truncate', " + + "'account_selected_owner_intake_source_read_sources_immutable', " + + "'account_selected_owner_intake_source_read_sources_no_truncate', " + + "'account_selected_owner_intake_source_read_aborts_immutable', " + + "'account_selected_owner_intake_source_read_aborts_no_truncate')", + Long.class, + schema))) + .isEqualTo(9L); + + assertThat( + Objects.requireNonNull( + jdbc.queryForObject( + "SELECT count(*) FROM pg_proc p " + + "JOIN pg_namespace n ON n.oid = p.pronamespace " + + "WHERE n.nspname = ? AND p.proname IN (" + + "'account_selected_owner_intake_source_read_is_pending', " + + "'account_selected_owner_intake_source_read_complete_guard', " + + "'account_selected_owner_intake_source_read_source_insert_guard', " + + "'account_selected_owner_intake_source_read_abort_guard')", + Long.class, + schema))) + .isEqualTo(4L); + } + + private static void assertMalformedReservationCreatesNoSourceRows(JdbcTemplate jdbc) { + UUID operationId = UUID.randomUUID(); + assertThatThrownBy( + () -> + jdbc.update( + "INSERT INTO account_selected_owner_intake_source_read_reservations (" + + "operation_id, fence_id, intake_request_id, owner, actor_account_uuid, " + + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, " + + "outbox_checkpoints) VALUES (?, ?, ?, 'UNDECLARED_OWNER', ?, ?, ?, " + + "decode('00', 'hex'), 'sha256:' || repeat('0', 64), ?, 1, " + + "decode('7b7d', 'hex'), decode('7b7d', 'hex'), decode('7b7d', 'hex'))", + operationId, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID())) + .isInstanceOf(RuntimeException.class); + + assertThat(count(jdbc, "account_selected_owner_intake_source_read_reservations")).isZero(); + assertThat(count(jdbc, "account_selected_owner_intake_source_read_sources")).isZero(); + assertThat(count(jdbc, "account_selected_owner_intake_source_read_aborts")).isZero(); + } + + private static void assertWorldSourceExclusionGuards( + String holdGuard, String sourceChangeGuard, String disclosureGuard) { + assertThat(holdGuard) + .contains( + "account_start_session_world_participations participation", + "account_start_session_world_participation_is_settled(participation.participation_id)", + "FOR UPDATE OF participation NOWAIT"); + assertThat(sourceChangeGuard) + .contains( + "account_start_session_world_participation_is_settled(participation.participation_id)", + "Pending StartSession World participation excludes source-change completion"); + assertThat(disclosureGuard) + .contains( + "OLD.status IN ('PREPARED', 'AMBIGUOUS')", + "account_start_session_world_participation_is_settled(participation.participation_id)", + "Pending StartSession World participation excludes hosted-terms dispatch"); + } + + private static String functionDefinition(JdbcTemplate jdbc, String signature) { + return Objects.requireNonNull( + jdbc.queryForObject("SELECT pg_get_functiondef(?::regprocedure)", String.class, signature)); + } + + private static int count(JdbcTemplate jdbc, String table) { + return Objects.requireNonNull( + jdbc.queryForObject("SELECT count(*) FROM " + table, Integer.class)); + } + + private static void assertVersionApplied(JdbcTemplate jdbc, String schema, String version) { + assertThat(historyCount(jdbc, schema, version)).isEqualTo(1); + } + + private static void assertVersionNotApplied(JdbcTemplate jdbc, String schema, String version) { + assertThat(historyCount(jdbc, schema, version)).isZero(); + } + + private static int historyCount(JdbcTemplate jdbc, String schema, String version) { + return Objects.requireNonNull( + jdbc.queryForObject( + "SELECT count(*) FROM " + + quotedSchema(schema) + + ".flyway_schema_history " + + "WHERE version = ? AND success", + Integer.class, + version)); + } + + private static String quotedSchema(String schema) { + return "\"" + schema + "\""; + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java new file mode 100644 index 0000000000..409efce42e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java @@ -0,0 +1,716 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Function; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.Candidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredSettlement; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.Snapshot; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +/** + * PostgreSQL proof of Account's immutable World participation storage behind its actual signer, + * current-actor, V128 capture, and original operator issuance/redemption owners. + * + *

The test stipulates Logging's claim response, the Game Session attempt/fence supplied to its + * real Account redemption, and the World terminal producer value. Its in-process peer contexts do + * not prove mTLS transport, authenticated Game Session production, a genuine World producer, or + * runtime activation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountStartSessionWorldParticipationPostgresIntegrationTest { + private static final String NAMESPACE = "control-ui-owner-proof"; + private static final long ORIGINAL_GAME_TEMPLATE_ID = 42L; + private static final String LOGGING_PEER_URI = + "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; + private static final String GAME_SESSION_PEER_URI = + "spiffe://firemud/ns/control-ui-owner-proof/sa/game-session-service"; + private static final String WORLD_PEER_URI = + "spiffe://firemud/ns/control-ui-owner-proof/sa/world-management-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(DockerImageName.parse("postgres:16-alpine")); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("world-participation-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "world-participation-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() throws Exception { + try (var controlUi = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var creator = controlUi.issueCreator(); + var account = creator.sources(); + var actorService = creator.actors(); + String requestId = "world-participation-" + UUID.randomUUID(); + UUID reservationOwnerId = UUID.randomUUID(); + long reservationClaimFence = 31L; + UUID gameSessionAttemptId = UUID.randomUUID(); + long gameSessionOwnerFence = 47L; + UUID gameInstanceId = UUID.randomUUID(); + String preparationInputJson = + preparationInput( + NAMESPACE, + account.tenant, + requestId, + gameInstanceId, + "owner-proof-world", + ORIGINAL_GAME_TEMPLATE_ID); + String preparationInputDigest = digest(preparationInputJson); + + var preAuthorizationTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + account.account.getAccountUuid(), + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(account.tenant, NAMESPACE), + new StartSessionOperatorAction.Target( + ORIGINAL_GAME_TEMPLATE_ID, account.account.getAccountUuid()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "test-only StartSession World participation storage proof")); + + // This client response is explicitly stipulated Logging claim evidence. Account still runs + // its real typed-claim checks, source capture, signing, currentness, issuance, and + // redemption. + var claimClient = mock(StartSessionReservationEvidenceClient.class); + var claim = + stipulatedLoggingClaim( + preAuthorizationTuple, reservationOwnerId, reservationClaimFence, Instant.now()); + when(claimClient.readCurrentClaimEvidence( + preAuthorizationTuple, + reservationOwnerId, + reservationClaimFence, + reservationOwnerId, + reservationClaimFence, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .thenReturn(claim); + + var operatorRepository = new AccountStartSessionOperatorAuthorizationRepository(account.dsl); + var captureRepository = new AccountStartSessionAuthorityCaptureRepository(account.dsl); + var fingerprintKeys = fingerprintKeys(); + var operatorResponseCryptography = responseCryptography(temporary); + var operatorAuthorization = + new AccountStartSessionOperatorAuthorizationService( + actorService, + new AccountControlUiIssuanceRepository(account.dsl), + captureRepository, + claimClient, + operatorRepository, + fingerprintKeys, + operatorResponseCryptography, + account.terms, + account.manager, + Clock.systemUTC(), + new SecureRandom(), + LOGGING_PEER_URI, + GAME_SESSION_PEER_URI, + Duration.ofMinutes(2), + Duration.ofSeconds(30)); + + var authorization = + withPeer( + LOGGING_PEER_URI, + () -> + operatorAuthorization.issue( + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + creator.compact(), + preAuthorizationTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + reservationOwnerId, + reservationClaimFence, + reservationOwnerId, + reservationClaimFence))); + + // The exact Account issuance result becomes the original post-authorization tuple. The + // target owner is still Game Session; World is only the same-namespace receiver. + var originalTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preAuthorizationTuple, + LOGGING_PEER_URI, + authorization.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + authorization.authorityEvidenceBundle(), + new BundleReference( + authorization.bundleReference().bundleVersion(), + authorization.bundleReference().sourceVersion(), + authorization.bundleReference().sourceFence(), + authorization.bundleReference().linearization())); + assertThat(originalTuple.preAuthorizationTuple().targetOwner()) + .isEqualTo("game-session-service"); + + // Account performs its real one-time redemption. The Game Session peer and attempt/fence + // are stipulated test inputs, not evidence from an authenticated Game Session producer. + withPeer( + GAME_SESSION_PEER_URI, + () -> + operatorAuthorization.redeem( + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + preAuthorizationTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + authorization.operatorAuthorizationReference(), + authorization.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + gameSessionAttemptId, + gameSessionOwnerFence))); + + var redeemed = + account.tx(() -> operatorRepository.findByControlPlaneRequestId(requestId).orElseThrow()); + assertThat(redeemed.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + assertThat(redeemed.redemptionOwnerAttemptId()).isEqualTo(gameSessionAttemptId); + assertThat(redeemed.redemptionOwnerFence()).isEqualTo(gameSessionOwnerFence); + assertThat(redeemed.issuanceFence()).isPositive(); + + var repository = new AccountStartSessionWorldParticipationRepository(account.dsl); + var initialCapture = + new java.util.concurrent.atomic.AtomicReference(); + var initialCandidate = new java.util.concurrent.atomic.AtomicReference(); + StoredParticipation first = + withWorldCurrentness( + operatorAuthorization, + originalTuple, + gameSessionAttemptId, + gameSessionOwnerFence, + capture -> { + assertActiveReadCommittedTransaction(); + initialCapture.set(capture); + var candidate = + candidate( + originalTuple, + capture, + gameInstanceId, + gameSessionAttemptId, + gameSessionOwnerFence, + preparationInputJson, + preparationInputDigest); + initialCandidate.set(candidate); + return repository.createOrReadExact(candidate); + }); + + var capture = initialCapture.get(); + assertThat(capture).isNotNull(); + assertThat(capture.controlPlaneRequestId()).isEqualTo(requestId); + assertThat(capture.sourceVersion()).isPositive(); + assertThat(capture.sourceFence()).isPositive(); + assertThat(account.dsl.fetchCount(DSL.table("account_start_session_authority_captures"))) + .isEqualTo(1); + var captureRow = + account.dsl.fetchOne( + "SELECT source_version, source_fence, issuance_fence, " + + "issuance_fence_source_version, canonical_snapshot_bytes " + + "FROM account_start_session_authority_captures " + + "WHERE control_plane_request_id = ?", + requestId); + assertThat(captureRow).isNotNull(); + assertThat(captureRow.get("source_version", Long.class)).isEqualTo(capture.sourceVersion()); + assertThat(captureRow.get("source_fence", Long.class)).isEqualTo(capture.sourceFence()); + assertThat(captureRow.get("issuance_fence", Long.class)).isEqualTo(redeemed.issuanceFence()); + assertThat(captureRow.get("canonical_snapshot_bytes", byte[].class)) + .containsExactly(capture.snapshotBytes()); + Map captureSnapshot = captureSnapshot(capture); + assertThat(captureSnapshot.get("issuanceFence")) + .isEqualTo(Long.toString(redeemed.issuanceFence())); + assertThat(captureSnapshot.get("issuanceFenceSourceVersion")) + .isEqualTo(Long.toString(captureRow.get("issuance_fence_source_version", Long.class))); + assertThat(captureSnapshot.get("controlUiSignerReceiptSha256").toString()) + .matches("[0-9a-f]{64}"); + + assertThat(first.participationId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(first.participationFence()).isPositive(); + assertThat(first.producerXid()).isPositive(); + assertThat(first.originalPostAuthorizationTuple()) + .containsExactly(originalTuple.canonicalBytes()); + assertThat(first.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(first.canonicalTenantId()).isEqualTo(account.tenant); + assertThat(first.canonicalGameInstanceId()).isEqualTo(gameInstanceId); + assertThat(first.gameSessionOwnerAttemptId()).isEqualTo(gameSessionAttemptId); + assertThat(first.gameSessionOwnerFence()).isEqualTo(gameSessionOwnerFence); + assertThat(first.preparationInputJson()).isEqualTo(preparationInputJson); + assertThat(first.preparationInputDigest()).isEqualTo(preparationInputDigest); + assertThat(capturedSourceVector(capture)) + .containsExactlyElementsOf( + first.sources().stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()); + + StoredParticipation exactRetry = + withWorldCurrentness( + operatorAuthorization, + originalTuple, + gameSessionAttemptId, + gameSessionOwnerFence, + currentCapture -> { + assertThat(currentCapture.canonicalBytes()) + .containsExactly(capture.canonicalBytes()); + return repository.createOrReadExact(initialCandidate.get()); + }); + assertThat(exactRetry.participationId()).isEqualTo(first.participationId()); + assertThat(exactRetry.participationFence()).isEqualTo(first.participationFence()); + assertThat(exactRetry.originalPostAuthorizationTuple()) + .containsExactly(first.originalPostAuthorizationTuple()); + assertThat( + exactRetry.sources().stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()) + .isEqualTo( + first.sources().stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()); + + var changedPreparation = + preparationInput( + NAMESPACE, + account.tenant, + requestId, + gameInstanceId, + "changed-owner-proof-world", + ORIGINAL_GAME_TEMPLATE_ID); + var changedCandidate = + candidate( + originalTuple, + capture, + gameInstanceId, + gameSessionAttemptId, + gameSessionOwnerFence, + changedPreparation, + digest(changedPreparation)); + assertThatThrownBy( + () -> + withWorldCurrentness( + operatorAuthorization, + originalTuple, + gameSessionAttemptId, + gameSessionOwnerFence, + ignored -> repository.createOrReadExact(changedCandidate))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("StartSession World participation conflicts with its immutable binding"); + assertThatThrownBy( + () -> + withWorldCurrentness( + operatorAuthorization, + originalTuple, + UUID.randomUUID(), + gameSessionOwnerFence, + ignored -> repository.createOrReadExact(initialCandidate.get()))) + .isInstanceOf(IllegalStateException.class); + + assertThatThrownBy(() -> repository.createOrReadExact(initialCandidate.get())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Writable Account READ_COMMITTED transaction required"); + + long fenceSequenceBeforeHistoricalRead = participationFenceSequence(account.dsl); + StoredParticipation historical = + account.tx( + () -> + repository + .findHistoricalExact(first.participationId(), first.participationFence()) + .orElseThrow()); + long fenceSequenceAfterHistoricalRead = participationFenceSequence(account.dsl); + assertThat(historical.participationId()).isEqualTo(first.participationId()); + assertThat(historical.participationFence()).isEqualTo(first.participationFence()); + assertThat(historical.originalPostAuthorizationTuple()) + .containsExactly(first.originalPostAuthorizationTuple()); + assertThat( + historical.sources().stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()) + .isEqualTo( + first.sources().stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()); + assertThat(fenceSequenceAfterHistoricalRead).isEqualTo(fenceSequenceBeforeHistoricalRead); + var issuanceAfterHistoricalRead = + account.tx(() -> operatorRepository.findByControlPlaneRequestId(requestId).orElseThrow()); + assertThat(issuanceAfterHistoricalRead.referenceExpiresAt()) + .isEqualTo(redeemed.referenceExpiresAt()); + assertThat(issuanceAfterHistoricalRead.responseEnvelopeExpiresAt()) + .isEqualTo(redeemed.responseEnvelopeExpiresAt()); + assertThat(account.tx(() -> repository.findHistoricalExact(UUID.randomUUID(), 1L))).isEmpty(); + + var committedTerminal = + terminal(first, WorldStartSessionExecutionTerminal.Outcome.COMMITTED, 73L); + StoredSettlement committed = account.tx(() -> repository.settleExact(committedTerminal)); + StoredSettlement exactSettlementRetry = + account.tx(() -> repository.settleExact(committedTerminal)); + assertThat(committed.participationId()).isEqualTo(first.participationId()); + assertThat(committed.outcome()) + .isEqualTo(WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + assertThat(committed.worldExecutionFence()).isEqualTo(73L); + assertThat(exactSettlementRetry.terminalBytes()).containsExactly(committed.terminalBytes()); + assertThat(exactSettlementRetry.terminalDigest()).isEqualTo(committed.terminalDigest()); + assertThat( + account + .tx( + () -> + repository + .findSettlementExact( + first.participationId(), first.participationFence()) + .orElseThrow()) + .terminalBytes()) + .containsExactly(committed.terminalBytes()); + + var conflictingTerminal = + terminal(first, WorldStartSessionExecutionTerminal.Outcome.ABORTED, 74L); + assertThatThrownBy(() -> account.tx(() -> repository.settleExact(conflictingTerminal))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("StartSession World participation conflicts with its immutable binding"); + assertThatThrownBy( + () -> + account.dsl.execute( + "UPDATE account_start_session_world_participation_settlements " + + "SET outcome = 'ABORTED' WHERE participation_id = ?", + first.participationId())) + .isInstanceOf(RuntimeException.class); + assertThat( + account.tx( + () -> + repository + .findSettlementExact(first.participationId(), first.participationFence()) + .orElseThrow() + .terminalBytes())) + .containsExactly(committed.terminalBytes()); + + var absentParentTerminal = + new WorldStartSessionExecutionTerminal( + first.originalPostAuthorizationTuple(), + UUID.randomUUID(), + first.participationFence() + 1L, + first.gameSessionOwnerAttemptId(), + first.gameSessionOwnerFence(), + first.targetNamespace(), + first.canonicalTenantId(), + first.controlPlaneRequestId(), + first.canonicalGameInstanceId(), + first.preparationInputDigest(), + first.preparationInputJson(), + 75L, + WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + assertThatThrownBy(() -> account.tx(() -> repository.settleExact(absentParentTerminal))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact StartSession World participation evidence unavailable"); + assertThat( + account.tx( + () -> + repository.findSettlementExact( + absentParentTerminal.accountWorldParticipationId(), + absentParentTerminal.accountWorldParticipationFence()))) + .isEmpty(); + + // The terminal is a typed test collaborator. Its validity proves Account storage binding, + // not a World producer, Game Session owner, transport peer, or execution result. + assertThat(account.dsl.fetchCount(DSL.table("account_start_session_world_participations"))) + .isEqualTo(1); + assertThat( + account.dsl.fetchCount( + DSL.table("account_start_session_world_participation_sources"))) + .isEqualTo(first.sources().size()); + assertThat( + account.dsl.fetchCount( + DSL.table("account_start_session_world_participation_settlements"))) + .isEqualTo(1); + } + } + + private static Candidate candidate( + StartSessionPostAuthorizationExecutionTuple originalTuple, + AccountStartSessionAuthorityCapture capture, + UUID gameInstanceId, + UUID gameSessionAttemptId, + long gameSessionOwnerFence, + String preparationInputJson, + String preparationInputDigest) { + return new Candidate( + originalTuple, + capture, + gameInstanceId, + gameSessionAttemptId, + gameSessionOwnerFence, + preparationInputJson, + preparationInputDigest); + } + + /** + * Stipulated structurally complete identity/descriptor envelope for Account storage validation. + * The echoed World and Game Session fields are test input, not authenticated producer evidence. + */ + private static String preparationInput( + String namespace, + UUID tenantId, + String requestId, + UUID gameInstanceId, + String worldSlug, + long gameTemplateId) + throws Exception { + String descriptorJson = JSON.writeValueAsString(Map.of("gameTemplateId", gameTemplateId)); + return JSON.writeValueAsString( + Map.of( + "schemaVersion", + 1, + "identity", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug), + "gameSessionReadRequest", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug), + "gameSessionReadEvidence", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug, + "descriptorJson", + descriptorJson), + "launchBinding", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "worldSlug", + worldSlug))); + } + + private static WorldStartSessionExecutionTerminal terminal( + StoredParticipation participation, + WorldStartSessionExecutionTerminal.Outcome outcome, + long worldExecutionFence) { + return new WorldStartSessionExecutionTerminal( + participation.originalPostAuthorizationTuple(), + participation.participationId(), + participation.participationFence(), + participation.gameSessionOwnerAttemptId(), + participation.gameSessionOwnerFence(), + participation.targetNamespace(), + participation.canonicalTenantId(), + participation.controlPlaneRequestId(), + participation.canonicalGameInstanceId(), + participation.preparationInputDigest(), + participation.preparationInputJson(), + worldExecutionFence, + outcome); + } + + private static T withWorldCurrentness( + AccountStartSessionOperatorAuthorizationService operatorAuthorization, + StartSessionPostAuthorizationExecutionTuple originalTuple, + UUID gameSessionAttemptId, + long gameSessionOwnerFence, + Function callback) { + try (var ignored = AccountControlUiOwnerSourcesFixture.withPeer(WORLD_PEER_URI)) { + return operatorAuthorization.withCurrentWorldReceivingParticipationCurrentness( + originalTuple.canonicalBytes(), gameSessionAttemptId, gameSessionOwnerFence, callback); + } + } + + private static T withPeer(String peerUri, java.util.concurrent.Callable action) { + try (var ignored = AccountControlUiOwnerSourcesFixture.withPeer(peerUri)) { + return action.call(); + } catch (RuntimeException failure) { + throw failure; + } catch (Exception failure) { + throw new IllegalStateException("Test peer-scoped Account owner action failed", failure); + } + } + + private static ReadCurrentClaimEvidenceResponse stipulatedLoggingClaim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + Instant now) { + return ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + com.google.protobuf.ByteString.copyFrom(tuple.canonicalJson(), StandardCharsets.UTF_8)) + .setMutationDigest(tuple.mutationDigest()) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setClaimOwnerId(reservationOwnerId.toString()) + .setClaimFence(reservationClaimFence) + .setObservedAtEpochMillis(now.minusSeconds(1).toEpochMilli()) + .setClaimExpiresAtEpochMillis(now.plus(Duration.ofMinutes(5)).toEpochMilli()) + .setPurpose( + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) + .build(); + } + + private static AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys() { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) 0x51); + return new AccountOperatorAuthorizationFingerprintKeyring( + () -> + new Snapshot( + new KeyMaterial("test-active", new SecretKeySpec(key, "HmacSHA256")), List.of()), + Clock.systemUTC(), + Duration.ofMinutes(2)); + } + + private static AccountResponseEnvelopeCryptography responseCryptography(Path temporary) + throws Exception { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) 0x26); + Path root = Files.createDirectories(temporary.resolve("operator-response-envelope")); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive test-response " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n"); + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(root.toString()), Clock.systemUTC(), new SecureRandom()); + } + + private static Map captureSnapshot(AccountStartSessionAuthorityCapture capture) + throws Exception { + return JSON.readValue(capture.snapshotBytes(), new TypeReference<>() {}); + } + + @SuppressWarnings("unchecked") + private static List capturedSourceVector(AccountStartSessionAuthorityCapture capture) + throws Exception { + return (List) captureSnapshot(capture).get("sourceVector"); + } + + private static long participationFenceSequence(DSLContext dsl) { + String sequence = + java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT pg_get_serial_sequence(" + + "'account_start_session_world_participations', 'participation_fence')")) + .get(0, String.class)); + return java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull(dsl.fetchOne("SELECT last_value FROM " + sequence)) + .get(0, Long.class)); + } + + private static String digest(String value) throws Exception { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } + + private static void assertActiveReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java new file mode 100644 index 0000000000..38d6aacf84 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java @@ -0,0 +1,262 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +import java.sql.Connection; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic Account owner tests; PostgreSQL trigger installation is not proven here. */ +class DraftAuthorizationFenceSelectedOwnerIntakeTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void pendingSelectedOwnerReservationBlocksDisclosurePreparation() throws Exception { + Fixture fixture = new Fixture(true); + fixture.begin(); + + assertThatThrownBy( + () -> fixture.repository.requireDisclosurePreparation(List.of(fixture.currentSource))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Selected owner intake source read remains pending"); + + assertThat(fixture.fetchedSql) + .anyMatch(sql -> sql.contains("account_selected_owner_intake_source_read_sources")) + .noneMatch(sql -> sql.contains("SELECT * FROM account_draft_authorization_fences")); + assertThat(fixture.executedSql) + .noneMatch(sql -> sql.contains("UPDATE account_draft_authorization_fences")); + } + + @Test + void currentCreatorMaySelectAnotherActorsExactSettledOriginalDraft() throws Exception { + Fixture fixture = new Fixture(false); + fixture.begin(); + UUID originalAuthor = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID currentCreator = UUID.fromString("22222222-2222-4222-8222-222222222222"); + assertThat(fixture.originalBinding.actorAccountId()).isEqualTo(originalAuthor); + assertThat(fixture.currentSource.scopeId()).isEqualTo(currentCreator.toString()); + + fixture.repository.requireSelectedOwnerIntakeAdmission( + List.of(fixture.currentSource), fixture.selected); + + assertThat(fixture.fetchedSql) + .anyMatch(sql -> sql.contains("WHERE request_id = ? AND commit_id = ? FOR UPDATE")) + .anyMatch(sql -> sql.contains("account_draft_authorization_owner_readbacks")); + } + + @Test + void substitutedSelectedBindingCannotUseAnOriginalSettlement() throws Exception { + Fixture fixture = new Fixture(false); + fixture.begin(); + DraftCommitBinding changed = + selected(fixture.selected.requestId(), fixture.selected.commitId(), "changed"); + + assertThatThrownBy( + () -> + fixture.repository.requireSelectedOwnerIntakeAdmission( + List.of(fixture.currentSource), changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed and settled"); + } + + private static final class Fixture { + private final DSLContext dsl = mock(DSLContext.class); + private final Connection connection = mock(Connection.class); + private final Record lockRow = mock(Record.class); + private final DraftCommitBinding selected = + selected( + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "selected"); + private final UUID originalAuthor = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private final SourceEvidence originalSource = source(originalAuthor); + private final UUID currentCreator = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private final SourceEvidence currentSource = source(currentCreator); + private final DraftAuthorizationFenceBinding originalBinding = originalBinding(); + private final Record originalRow = recordForBinding(originalBinding); + private final Result originalSources = result(List.of(sourceRow(originalSource))); + private final Result committedReadbacks = result(List.of(readbackRow(originalBinding))); + private final Result emptyRows = result(List.of()); + private final Result pendingRows = result(List.of(mock(Record.class))); + private final boolean pending; + private final List fetchedSql = new java.util.ArrayList<>(); + private final List executedSql = new java.util.ArrayList<>(); + private final DraftAuthorizationFenceRepository repository = + new DraftAuthorizationFenceRepository(dsl); + + private Fixture(boolean pending) throws Exception { + this.pending = pending; + doAnswer(invocation -> false).when(connection).getAutoCommit(); + doAnswer(invocation -> false).when(connection).isReadOnly(); + doAnswer(invocation -> Connection.TRANSACTION_READ_COMMITTED) + .when(connection) + .getTransactionIsolation(); + doAnswer( + invocation -> { + invocation.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + doAnswer( + invocation -> { + String sql = invocation.getArgument(0); + executedSql.add(sql); + return 1; + }) + .when(dsl) + .execute(anyString(), any(Object[].class)); + doAnswer( + invocation -> { + String sql = invocation.getArgument(0); + fetchedSql.add(sql); + if (sql.contains("account_selected_owner_intake_source_read_sources")) { + return pending ? pendingRows : emptyRows; + } + if (sql.contains("account_draft_authorization_owner_readbacks")) { + return committedReadbacks; + } + if (sql.contains("account_draft_authorization_sources WHERE operation_id")) { + return originalSources; + } + return emptyRows; + }) + .when(dsl) + .fetch(anyString(), any(Object[].class)); + doAnswer( + invocation -> { + String sql = invocation.getArgument(0); + fetchedSql.add(sql); + if (sql.contains("WHERE request_id = ? AND commit_id = ?")) return originalRow; + if (sql.contains("account_draft_authorization_source_locks")) return lockRow; + return null; + }) + .when(dsl) + .fetchOne(anyString(), any(Object[].class)); + } + + private void begin() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + private DraftAuthorizationFenceBinding originalBinding() { + var original = + new DraftAuthorizationFenceBinding( + UUID.fromString("55555555-5555-4555-8555-555555555555"), + selected.requestId(), + selected.commitId(), + UUID.fromString("66666666-6666-4666-8666-666666666666"), + originalAuthor, + selected.target().canonicalTenantId(), + selected.target().canonicalVersionId(), + selected.baseCommitId(), + "0", + selected.canonicalBytes(), + selected.canonicalBytes(), + selected.digest(), + List.of(originalSource)); + return original.withRequiredOwners(); + } + } + + private static DraftCommitBinding selected(UUID request, UUID commit, String payload) { + UUID tenant = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID version = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 9L, "tenant-key", 10L, "tenant-key", "NEW_GAME_ROW"), + request, + commit, + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULES", + "rules", + "TENANT", + tenant.toString(), + "0"))); + } + + private static SourceEvidence source(UUID actor) { + return new SourceEvidence( + SourceKind.ACCOUNT, actor.toString(), "1", "1", null, null, new byte[] {1, 2, 3}); + } + + private static Record recordForBinding(DraftAuthorizationFenceBinding binding) { + Record record = mock(Record.class); + doReturn(binding.operationId()).when(record).get("operation_id", UUID.class); + doReturn(binding.requestId()).when(record).get("request_id", UUID.class); + doReturn(binding.commitId()).when(record).get("commit_id", UUID.class); + doReturn(binding.fenceId()).when(record).get("fence_id", UUID.class); + doReturn(binding.canonicalBytes()).when(record).get("binding", byte[].class); + doReturn("COMMIT_ORDER").when(record).get("ordering", String.class); + return record; + } + + private static Record sourceRow(SourceEvidence source) { + Record row = mock(Record.class); + doReturn(source.key()).when(row).get("source_key", String.class); + doReturn(source.canonicalBytes()).when(row).get("source_evidence", byte[].class); + return row; + } + + private static Record readbackRow(DraftAuthorizationFenceBinding binding) { + OwnerReadback readback = + new OwnerReadback( + Owner.GAME_DESIGN, + Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {9}); + Record row = mock(Record.class); + doReturn(Owner.GAME_DESIGN.name()).when(row).get("owner", String.class); + doReturn(Outcome.COMMITTED.name()).when(row).get("outcome", String.class); + doReturn(readback.canonicalBytes()).when(row).get("readback", byte[].class); + return row; + } + + @SuppressWarnings("unchecked") + private static Result result(List rows) { + Result result = mock(Result.class); + doReturn(rows.size()).when(result).size(); + doReturn(rows.isEmpty()).when(result).isEmpty(); + doAnswer(invocation -> rows.iterator()).when(result).iterator(); + doAnswer(invocation -> rows.stream()).when(result).stream(); + return result; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java new file mode 100644 index 0000000000..1bbcf2842f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java @@ -0,0 +1,199 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic owner-context tests; these do not establish TLS or PostgreSQL runtime proof. */ +class AccountSelectedOwnerIntakeSourceReadServiceTest { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository = + mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + private final AccountControlUiCoordination registry = mock(AccountControlUiCoordination.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final AccountSelectedOwnerIntakeSourceReadService service = + new AccountSelectedOwnerIntakeSourceReadService(repository, registry, transactions, "test"); + + @AfterEach + void clearContextAndTransaction() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactCreatorRegistryReadOccursBetweenIndependentSqlReadbacks() { + var scope = scope("test"); + assertThat(scope.selected().requiredOwners()) + .doesNotContain(DraftCommitBinding.Owner.ENTITY_MANAGEMENT) + .doesNotContain(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + byte[] active = "exact-active-registry".getBytes(java.nio.charset.StandardCharsets.UTF_8); + var current = + new AccountSelectedOwnerIntakeSourceReservationRepository.SourceReadCurrentness( + "token-hash", + DraftAuthorizationFenceBinding.digest(active), + 1_900_000_000L, + "issuer-evidence", + "complete-source-vector"); + TransactionStatus status = new SimpleTransactionStatus(); + when(transactions.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + when(repository.sourceReadCurrentness(scope)).thenReturn(current); + when(registry.readActive("token-hash")).thenReturn(active); + asPeer( + "test", + "game-design-service", + () -> service.readSourceScope(scope, scope.intendedReader(), scope.purpose())); + + InOrder order = inOrder(repository, registry); + order.verify(repository).sourceReadCurrentness(scope); + order.verify(registry).readActive("token-hash"); + order.verify(repository).readSourceScope(scope, current); + verify(transactions, times(2)).commit(status); + + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions, times(2)).getTransaction(definition.capture()); + assertThat(definition.getAllValues()) + .allSatisfy( + value -> { + assertThat(value.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(value.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(value.isReadOnly()).isFalse(); + }); + } + + @Test + void changedActiveRegistryDeniesBeforeFinalDatabaseConfirmation() { + var scope = scope("test"); + byte[] originalActive = "original-active".getBytes(java.nio.charset.StandardCharsets.UTF_8); + TransactionStatus status = new SimpleTransactionStatus(); + when(transactions.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + when(repository.sourceReadCurrentness(scope)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository.SourceReadCurrentness( + "token-hash", + DraftAuthorizationFenceBinding.digest(originalActive), + 1_900_000_000L, + "issuer-evidence", + "complete-source-vector")); + when(registry.readActive("token-hash")).thenReturn("replaced-active".getBytes()); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + asPeer( + "test", + "game-design-service", + () -> service.readSourceScope(scope, scope.intendedReader(), scope.purpose()))); + + verify(repository, never()).readSourceScope(any(), any()); + verify(transactions).commit(status); + } + + @Test + void authenticatesExactPeerAndRejectsEndUserContextBeforeScopeOrStorageAccess() { + assertCode(Status.Code.UNAUTHENTICATED, () -> service.readSourceScope(null, null, null)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "other", "game-design-service", () -> service.readSourceScope(null, null, null))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", "account-service", () -> service.readSourceScope(null, null, null))); + + SessionContext.setContext("44", List.of(), Map.of()); + try { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "test", "game-design-service", () -> service.readSourceScope(null, null, null))); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(repository, registry, transactions); + } + + private static SelectedOwnerIntakeSourceReadScope scope(String namespace) { + UUID tenant = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID version = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + var selected = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 1L, "tenant-key", 2L, "tenant-key", "NEW_GAME_ROW"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + tenant.toString(), + "0"))); + return new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + namespace, + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.requestId(), + UUID.fromString("12121212-1212-4212-8212-121212121212"), + selected); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = peer.attach(); + try { + action.run(); + } finally { + peer.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java new file mode 100644 index 0000000000..5f321fb4fc --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java @@ -0,0 +1,39 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +/** Synthetic transaction-bound repository boundary tests; no PostgreSQL proof is claimed. */ +class AccountSelectedOwnerIntakeSourceReservationRepositoryTest { + @Test + void everyReservationRecoveryAbortAndCurrentnessReadRequiresAnOwnerTransaction() { + var dsl = mock(DSLContext.class); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(dsl); + + assertThatThrownBy(() -> repository.reserveSourceRead(null, null, null, null, null, () -> {})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.findSourceReadScope(null, null, null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + + assertThatThrownBy(() -> repository.recoverSourceRead(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.abortSourceRead(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.sourceReadCurrentness(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.readSourceScope(null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + + verifyNoInteractions(dsl); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java new file mode 100644 index 0000000000..105b642c97 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java @@ -0,0 +1,403 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic owner producer tests; these do not establish TLS or PostgreSQL runtime proof. */ +class AccountSelectedOwnerIntakeSourceReservationServiceTest { + private static final String TOKEN = "header.payload.signature"; + private final AccountControlUiActorService actors = mock(AccountControlUiActorService.class); + private final DraftAuthorizationFenceRepository fences = + mock(DraftAuthorizationFenceRepository.class); + private final AccountSelectedOwnerIntakeSourceReservationRepository repository = + mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final AccountSelectedOwnerIntakeSourceReservationService service = + new AccountSelectedOwnerIntakeSourceReservationService( + actors, fences, repository, transactions, "test"); + + @AfterEach + void clearContextAndTransaction() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void freshProducerRunsCurrentActorThenSelectedAdmissionBeforePersisting() { + var selected = selected(); + assertThat(selected.requiredOwners()) + .doesNotContain(DraftCommitBinding.Owner.ENTITY_MANAGEMENT) + .doesNotContain(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + UUID actorId = UUID.fromString("44444444-4444-4444-8444-444444444444"); + var currentSource = source(actorId); + var actorCurrent = + new AccountControlUiActorService.Current( + stored(actorId, selected.target().canonicalTenantId()), + snapshot(List.of(currentSource))); + var environment = mock(CapturedEnvironmentBoundary.class); + var scope = + new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + "test", + UUID.fromString("55555555-5555-4555-8555-555555555555"), + UUID.fromString("66666666-6666-4666-8666-666666666666"), + selected.requestId(), + actorId, + selected); + var status = new SimpleTransactionStatus(); + when(transactions.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + when(repository.findSourceReadScope( + selected.requestId(), + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + selected, + "test", + tokenHash(TOKEN))) + .thenReturn(Optional.empty()); + when(repository.reserveSourceRead( + eq(selected.requestId()), + eq(DraftCommitBinding.Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(actorCurrent), + eq("test"), + any(Runnable.class))) + .thenReturn(scope); + doAnswer( + invocation -> { + Function action = + invocation.getArgument(3); + return action.apply(actorCurrent); + }) + .when(actors) + .withCurrent(eq(TOKEN), eq(selected.target().canonicalTenantId()), eq(environment), any()); + + var result = + asPeerResult( + "test", + "game-design-service", + () -> + service.reserveSourceRead( + TOKEN, + selected.requestId(), + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + selected, + environment)); + + assertThat(result).isEqualTo(scope); + InOrder order = inOrder(repository, actors, fences); + order + .verify(repository) + .findSourceReadScope( + selected.requestId(), + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + selected, + "test", + tokenHash(TOKEN)); + order + .verify(actors) + .withCurrent(eq(TOKEN), eq(selected.target().canonicalTenantId()), eq(environment), any()); + order.verify(fences).requireSelectedOwnerIntakeAdmission(List.of(currentSource), selected); + order + .verify(repository) + .reserveSourceRead( + eq(selected.requestId()), + eq(DraftCommitBinding.Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(actorCurrent), + eq("test"), + any(Runnable.class)); + } + + @Test + void historicalRecoveryAndAbortUseTheExactOriginalCredentialAndDoNotRenewIt() { + var selected = selected(); + var scope = + new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + "test", + UUID.fromString("77777777-7777-4777-8777-777777777777"), + UUID.fromString("88888888-8888-4888-8888-888888888888"), + selected.requestId(), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected); + var status = new SimpleTransactionStatus(); + when(transactions.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + when(repository.findSourceReadScope( + selected.requestId(), + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + selected, + "test", + tokenHash(TOKEN))) + .thenReturn(Optional.of(scope)); + when(repository.recoverSourceRead(scope)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository.Recovery( + scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED)); + when(repository.abortSourceRead(scope)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository.Recovery( + scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED)); + + var recovered = + asPeerResult( + "test", + "game-design-service", + () -> + service.recover( + TOKEN, + selected.requestId(), + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + selected)); + var aborted = + asPeerResult( + "test", + "game-design-service", + () -> + service.abortSourceRead( + TOKEN, + selected.requestId(), + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + selected)); + + assertThat(recovered.state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED); + assertThat(aborted.state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED); + InOrder order = inOrder(repository); + order + .verify(repository) + .findSourceReadScope( + selected.requestId(), + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + selected, + "test", + tokenHash(TOKEN)); + order.verify(repository).recoverSourceRead(scope); + order + .verify(repository) + .findSourceReadScope( + selected.requestId(), + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, + selected, + "test", + tokenHash(TOKEN)); + order.verify(repository).abortSourceRead(scope); + } + + @Test + void exactSameNamespaceGameDesignPeerIsRequiredBeforeInputsOrStorage() { + assertCode( + Status.Code.UNAUTHENTICATED, () -> service.reserveSourceRead(null, null, null, null, null)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "other", + "game-design-service", + () -> service.reserveSourceRead(null, null, null, null, null))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "test", + "account-service", + () -> service.reserveSourceRead(null, null, null, null, null))); + + SessionContext.setContext("44", List.of(), Map.of()); + try { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "test", + "game-design-service", + () -> service.reserveSourceRead(null, null, null, null, null))); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(actors, fences, repository, transactions); + } + + @Test + void originalCreatorRecoveryUsesAnIndependentReadCommittedTransaction() { + var selected = selected(); + var scope = + new SelectedOwnerIntakeSourceReadScope( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + "test", + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + selected.requestId(), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + selected); + var status = new SimpleTransactionStatus(); + when(transactions.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + when(repository.recoverSourceRead(scope)) + .thenReturn( + new AccountSelectedOwnerIntakeSourceReservationRepository.Recovery( + scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED)); + + asPeer("test", "game-design-service", () -> service.recover(scope)); + + var definition = org.mockito.ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(repository).recoverSourceRead(scope); + } + + private static AccountControlUiAuthority.Snapshot snapshot( + List sources) { + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + when(snapshot.sources()).thenReturn(sources); + when(snapshot.issuanceFence()).thenReturn(17L); + when(snapshot.outboxCheckpoints()) + .thenReturn(List.of(Map.of("stream", "account", "sequence", 7))); + return snapshot; + } + + private static AccountControlUiIssuanceRepository.Stored stored(UUID actorId, UUID tenantId) { + Record row = mock(Record.class); + var operation = UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + var sourcePayload = AccountControlUiAuthority.canonical(Map.of("sources", List.of("AQID"))); + var bundle = + AccountControlUiAuthority.canonical( + Map.of("issuanceFence", 17, "outboxCheckpoints", List.of())); + when(row.get("request_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("operation_id", UUID.class)).thenReturn(operation); + when(row.get("token_jti", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("account_uuid", UUID.class)).thenReturn(actorId); + when(row.get("tenant_uuid", UUID.class)).thenReturn(tenantId); + when(row.get("caller_context_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("caller_workload", String.class)).thenReturn("game-design-service"); + when(row.get("request_mac_key_id", String.class)).thenReturn("key"); + when(row.get("request_digest", String.class)).thenReturn("digest"); + when(row.get("status", String.class)).thenReturn("COMMITTED"); + when(row.get("token_hash", String.class)).thenReturn(tokenHash(TOKEN)); + when(row.get("claims_payload", byte[].class)).thenReturn(new byte[] {1}); + when(row.get("source_payload", byte[].class)).thenReturn(sourcePayload); + when(row.get("bundle_payload", byte[].class)).thenReturn(bundle); + when(row.get("signer_receipt", byte[].class)).thenReturn(new byte[] {2}); + when(row.get("pending_registry", byte[].class)).thenReturn(new byte[] {3}); + when(row.get("active_registry", byte[].class)).thenReturn(new byte[] {4}); + when(row.get("issued_at_epoch_second", Long.class)).thenReturn(1_800_000_000L); + when(row.get("expires_at_epoch_second", Long.class)).thenReturn(1_800_000_300L); + when(row.get("recovery_expires_at", OffsetDateTime.class)) + .thenReturn(OffsetDateTime.parse("2027-01-01T00:01:00Z")); + return new AccountControlUiIssuanceRepository.Stored(row); + } + + private static DraftAuthorizationFenceBinding.SourceEvidence source(UUID actorId) { + return new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actorId.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}); + } + + private static DraftCommitBinding selected() { + UUID tenant = UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + UUID version = UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 1L, "tenant-key", 2L, "tenant-key", "NEW_GAME_ROW"), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + tenant.toString(), + "0"))); + } + + private static String tokenHash(String value) { + return AccountControlUiIssuanceRepository.hash(value.getBytes(StandardCharsets.US_ASCII)); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = peer.attach(); + try { + action.run(); + } finally { + peer.detach(previous); + } + } + + private static T asPeerResult(String namespace, String workload, Supplier action) { + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = peer.attach(); + try { + return action.get(); + } finally { + peer.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest.java new file mode 100644 index 0000000000..338f6d5365 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.function.Consumer; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** Verifies authentication-before-codec ordering; this is not mTLS or producer proof. */ +class AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + + private final AccountStartSessionWorldParticipationHistoricalReadService owner = + mock(AccountStartSessionWorldParticipationHistoricalReadService.class); + private final AccountStartSessionWorldParticipationHistoricalReadGrpcService receiver = + new AccountStartSessionWorldParticipationHistoricalReadGrpcService(owner, NAMESPACE); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + } + + @Test + void authenticatesExactWorldAndAbsentEndUserBeforeRequestDecodeOrOwnerAccess() { + var malformed = ReadHistoricalStartSessionWorldParticipationRequest.newBuilder().build(); + assertRpcStatus(Status.Code.UNAUTHENTICATED, observer -> invoke(malformed, observer)); + assertRpcStatus( + Status.Code.PERMISSION_DENIED, + observer -> + peer( + NAMESPACE, + "game-session-service", + () -> { + invoke(malformed, observer); + return null; + })); + assertRpcStatus( + Status.Code.PERMISSION_DENIED, + observer -> + peer( + "other-runtime", + "world-management-service", + () -> { + invoke(malformed, observer); + return null; + })); + SessionContext.setContext("123", java.util.List.of(), java.util.Map.of()); + assertRpcStatus( + Status.Code.PERMISSION_DENIED, + observer -> + peer( + NAMESPACE, + "world-management-service", + () -> { + invoke(malformed, observer); + return null; + })); + verifyNoInteractions(owner); + } + + @Test + void bindsConfiguredNamespaceBeforeClosedRequestCodecAndRejectsUnknownOrWrongVersion() { + var foreignNamespace = + ReadHistoricalStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId("d1f41bfb-265a-4f3b-8b2a-124cba20ce43") + .setTargetNamespace("other-runtime") + .setAccountWorldParticipationId("a8c1e8c8-f237-41b7-918d-ec2281bcac10") + .setAccountWorldParticipationFence(31L) + .build(); + var wrongVersion = validWire().toBuilder().setSchemaVersion(2).build(); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + var unknownField = validWire().toBuilder().setUnknownFields(unknown).build(); + + assertRpcStatus( + Status.Code.PERMISSION_DENIED, + observer -> + peer( + NAMESPACE, + "world-management-service", + () -> { + invoke(foreignNamespace, observer); + return null; + })); + assertRpcStatus( + Status.Code.INVALID_ARGUMENT, + observer -> + peer( + NAMESPACE, + "world-management-service", + () -> { + invoke(wrongVersion, observer); + return null; + })); + assertRpcStatus( + Status.Code.INVALID_ARGUMENT, + observer -> + peer( + NAMESPACE, + "world-management-service", + () -> { + invoke(unknownField, observer); + return null; + })); + verifyNoInteractions(owner); + } + + private static ReadHistoricalStartSessionWorldParticipationRequest validWire() { + return ReadHistoricalStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId("d1f41bfb-265a-4f3b-8b2a-124cba20ce43") + .setTargetNamespace(NAMESPACE) + .setAccountWorldParticipationId("a8c1e8c8-f237-41b7-918d-ec2281bcac10") + .setAccountWorldParticipationFence(31L) + .build(); + } + + private void invoke( + ReadHistoricalStartSessionWorldParticipationRequest request, + StreamObserver observer) { + receiver.readHistoricalStartSessionWorldParticipation(request, observer); + } + + private static void assertRpcStatus( + Status.Code expected, + Consumer> action) { + @SuppressWarnings("unchecked") + var observer = + (StreamObserver) + mock(StreamObserver.class); + action.accept(observer); + var error = org.mockito.ArgumentCaptor.forClass(Throwable.class); + org.mockito.Mockito.verify(observer).onError(error.capture()); + assertThat(Status.fromThrowable(error.getValue()).getCode()).isEqualTo(expected); + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java new file mode 100644 index 0000000000..5650893e1b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java @@ -0,0 +1,402 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +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 io.grpc.Context; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadRequest; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Mocked owner-storage boundary only; no PostgreSQL or authenticated Game Session proof. */ +class AccountStartSessionWorldParticipationHistoricalReadServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID READ_ID = uuid("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final long PARTICIPATION_FENCE = 31L; + private static final long GAME_SESSION_FENCE = 37L; + private static final String PREPARATION_INPUT = + "{ \"historical\" : \"retained exactly\", \"revision\": 1 }\n"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final AccountStartSessionWorldParticipationRepository repository = + mock(AccountStartSessionWorldParticipationRepository.class); + private final OwnerTransactions transactions = new OwnerTransactions(); + private final AccountStartSessionWorldParticipationHistoricalReadService service = + new AccountStartSessionWorldParticipationHistoricalReadService( + repository, transactions, NAMESPACE); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactWorldWorkloadAndNoEndUserBeforeRequestOrStorageAccess() { + assertCode(Status.Code.UNAUTHENTICATED, () -> service.read(null)); + for (String workload : List.of("account-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, () -> peer(NAMESPACE, workload, () -> service.read(null))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("other-runtime", "world-management-service", () -> service.read(null))); + SessionContext.setContext("123", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer(NAMESPACE, "world-management-service", () -> service.read(null))); + verifyNoInteractions(repository); + assertThat(transactions.begins).isZero(); + } + + @Test + void deniesAmbientSqlOrSynchronizationBeforeValidatingRequestOrStartingOwnerTransaction() { + var request = request(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read(request))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read(request))); + verifyNoInteractions(repository); + assertThat(transactions.begins).isZero(); + } + + @Test + void readsExactHistoryAfterIngressExpiryAndPriorSettlementWithoutCurrentnessOrMutation() + throws Exception { + StoredParticipation expired = participation(true); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenAnswer( + call -> { + assertWritableReadCommittedTransaction(); + return Optional.of(expired); + }); + // A prior terminal receipt is deliberately present; historical participation reads do not + // require it, rewrite it, or treat its outcome as fresh execution permission. + when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn( + Optional.of( + mock(AccountStartSessionWorldParticipationRepository.StoredSettlement.class))); + + var evidence = authorized(() -> service.read(request())); + + assertThat(evidence.request()).isEqualTo(request()); + assertThat(evidence.originalPostAuthorizationTuple()) + .containsExactly(expired.originalPostAuthorizationTuple()); + assertThat(evidence.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); + assertThat(evidence.gameSessionOwnerFence()).isEqualTo(GAME_SESSION_FENCE); + assertThat(evidence.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(evidence.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + assertThat(evidence.preparationInputDigest()).isEqualTo(digest(PREPARATION_INPUT)); + assertThat(transactions.begins).isEqualTo(1); + assertThat(transactions.commits).isEqualTo(1); + assertNoSql(); + verify(repository).findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE); + verifyNoMoreInteractions(repository); + } + + @Test + void absentMismatchedNamespaceAndMismatchedRetainedIdentityFailClosed() { + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn(Optional.empty()); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read(request()))); + assertThat(transactions.commits).isZero(); + assertThat(transactions.rollbacks).isEqualTo(1); + + TransactionSynchronizationManager.clear(); + transactions.resetCounts(); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn( + Optional.of( + participation(false, "other-runtime", PARTICIPATION_ID, PARTICIPATION_FENCE))); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read(request()))); + assertThat(transactions.commits).isEqualTo(1); + + TransactionSynchronizationManager.clear(); + transactions.resetCounts(); + when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenReturn( + Optional.of( + participation(false, NAMESPACE, PARTICIPATION_ID, PARTICIPATION_FENCE + 1L))); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read(request()))); + assertThat(transactions.commits).isEqualTo(1); + + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + authorized( + () -> + service.read( + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, "other-runtime", PARTICIPATION_ID, PARTICIPATION_FENCE)))); + verify(repository, org.mockito.Mockito.times(3)) + .findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE); + } + + private AccountStartSessionWorldParticipationHistoricalReadRequest request() { + return new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, NAMESPACE, PARTICIPATION_ID, PARTICIPATION_FENCE); + } + + private static StoredParticipation participation(boolean expired) { + return participation(expired, NAMESPACE, PARTICIPATION_ID, PARTICIPATION_FENCE); + } + + private static StoredParticipation participation( + boolean expired, String namespace, UUID participationId, long participationFence) { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(namespace, expired); + return new StoredParticipation( + participationId, + participationFence, + tuple.controlPlaneRequestId(), + tuple.canonicalBytes(), + namespace, + TENANT, + GAME_INSTANCE_ID, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + PREPARATION_INPUT, + digest(PREPARATION_INPUT), + 987L, + OffsetDateTime.parse("2026-10-09T00:00:00Z"), + List.of()); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple( + String namespace, boolean expired) { + UUID actor = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + UUID targetOwner = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwner = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + String requestId = "historical-participation-original-request"; + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + actor, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, targetOwner), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "mocked historical Account read boundary")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + reservationOwner, + 19L, + authorityBundle(preTuple, expired), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, boolean expired) { + String actorId = tuple.actor().accountId().toString(); + String tenantId = tuple.action().scope().tenantId().toString(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + expired ? "2020-01-01T00:00:00Z" : "2026-10-09T00:00:00Z", + "expiresAt", + expired ? "2020-01-02T00:00:00Z" : "2026-10-10T00:00:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map human = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", actorId, + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + human); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static T authorized(Supplier action) { + return peer(NAMESPACE, "world-management-service", action); + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertWritableReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static String digest(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private int begins; + private int commits; + private int rollbacks; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + rollbacks++; + } + + void resetCounts() { + begins = 0; + commits = 0; + rollbacks = 0; + } + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index e6af17e723..e808ce56c1 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.grpc.Context; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; @@ -16,8 +17,11 @@ import java.util.List; import java.util.UUID; import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedOwnerIntakeSourceReservationRepository.Recovery; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; @@ -220,6 +224,71 @@ AccountControlUiCoordination coordination() { return coordination; } + /** + * Invokes the real preliminary reservation owner with the existing creator and current Account + * environment. The Game Design peer context is stipulated by this direct fixture call; this does + * not prove authenticated transport. + */ + public SelectedOwnerIntakeSourceReadScope reserveSelectedOwnerSourceRead( + UUID intakeRequestId, Owner owner, DraftCommitBinding selected, String namespace) { + requireOriginalCreator(); + var service = selectedOwnerSourceReservationService(namespace); + return asStipulatedGameDesignPeer( + namespace, + () -> + service.reserveSourceRead( + originalCreator.compact(), + intakeRequestId, + owner, + selected, + originalCreator.environment())); + } + + /** Exact historical recovery of one preliminary source reservation. */ + public Recovery recoverSelectedOwnerSourceRead( + SelectedOwnerIntakeSourceReadScope scope, String namespace) { + var service = selectedOwnerSourceReservationService(namespace); + return asStipulatedGameDesignPeer(namespace, () -> service.recover(scope)); + } + + /** Definitively aborts only the supplied preliminary source reservation. */ + public Recovery abortSelectedOwnerSourceRead( + SelectedOwnerIntakeSourceReadScope scope, String namespace) { + var service = selectedOwnerSourceReservationService(namespace); + return asStipulatedGameDesignPeer(namespace, () -> service.abortSourceRead(scope)); + } + + private AccountSelectedOwnerIntakeSourceReservationService selectedOwnerSourceReservationService( + String namespace) { + return new AccountSelectedOwnerIntakeSourceReservationService( + actors, + f.fences, + new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl), + f.manager, + namespace); + } + + private void requireOriginalCreator() { + if (originalCreator == null) { + throw new IllegalStateException( + "Prepare the original Draft order before reserving selected-owner source reads"); + } + } + + private static T asStipulatedGameDesignPeer( + String namespace, java.util.function.Supplier action) { + var identity = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/game-design-service") + .orElseThrow(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, identity); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + /** Real unregistered Account producer, with Account-internal environment capture. */ public io.grpc.BindableService originalDraftOrderProducer(String namespace) { return new AccountOriginalDraftOrderGrpcService( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java new file mode 100644 index 0000000000..74ce234a98 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.common.account.startsession; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationHistoricalReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicit file-backed mTLS client for Account's unregistered historical World participation read. + */ +public final class AccountStartSessionWorldParticipationHistoricalReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountStartSessionWorldParticipationHistoricalReadServiceGrpc + .AccountStartSessionWorldParticipationHistoricalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountStartSessionWorldParticipationHistoricalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountStartSessionWorldParticipationHistoricalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning World component explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account historical participation client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account historical participation client has no gRPC stub"); + } + initialized = true; + } + + /** Reads only the exact retained Account row; it does not admit or renew World execution. */ + public AccountStartSessionWorldParticipationHistoricalReadEvidence read( + AccountStartSessionWorldParticipationHistoricalReadRequest request) { + Objects.requireNonNull(request, "historical participation request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account historical participation request must use the configured workload namespace"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account historical participation read must start outside an ambient transaction"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .withMaxInboundMessageSize( + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec + .MAX_RESPONSE_WIRE_BYTES) + .readHistoricalStartSessionWorldParticipation( + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toRequest(request)); + try { + return AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid historical World participation evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountStartSessionWorldParticipationHistoricalReadServiceGrpc + .AccountStartSessionWorldParticipationHistoricalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountStartSessionWorldParticipationHistoricalReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withMaxInboundMessageSize( + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountStartSessionWorldParticipationHistoricalReadServiceGrpc + .AccountStartSessionWorldParticipationHistoricalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account historical participation client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account historical participation read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account historical participation read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account historical participation read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account historical participation read " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account historical participation read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadEvidence.java new file mode 100644 index 0000000000..f263bc9aad --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadEvidence.java @@ -0,0 +1,111 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadRequest; + +/** + * Account-derived immutable historical participation fields for exact World reconciliation. + * + *

This carrier is not currentness, admission, producer authentication, or renewed permission. + */ +public final class AccountStartSessionWorldParticipationHistoricalReadEvidence { + private final AccountStartSessionWorldParticipationHistoricalReadRequest request; + private final byte[] originalPostAuthorizationTuple; + private final UUID gameSessionOwnerAttemptId; + private final long gameSessionOwnerFence; + private final UUID canonicalGameInstanceId; + private final String preparationInputJson; + private final String preparationInputDigest; + + public AccountStartSessionWorldParticipationHistoricalReadEvidence( + AccountStartSessionWorldParticipationHistoricalReadRequest request, + byte[] originalPostAuthorizationTuple, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + UUID canonicalGameInstanceId, + String preparationInputJson, + String preparationInputDigest) { + this.request = Objects.requireNonNull(request, "historical participation request is required"); + Objects.requireNonNull(originalPostAuthorizationTuple, "original tuple is required"); + if (originalPostAuthorizationTuple.length == 0 + || originalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException("Original StartSession tuple is missing or oversized"); + } + this.originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + this.gameSessionOwnerAttemptId = + Objects.requireNonNull(gameSessionOwnerAttemptId, "Game Session attempt is required"); + if (gameSessionOwnerFence <= 0L) { + throw new IllegalArgumentException("Game Session owner fence must be positive"); + } + this.gameSessionOwnerFence = gameSessionOwnerFence; + this.canonicalGameInstanceId = + Objects.requireNonNull(canonicalGameInstanceId, "canonical Game Instance ID is required"); + this.preparationInputJson = + Objects.requireNonNull(preparationInputJson, "exact preparation input is required"); + this.preparationInputDigest = + Objects.requireNonNull(preparationInputDigest, "preparation input digest is required"); + + // Reuse the existing closed World identity validator without aliasing its terminal-read wire + // type or claiming that this historical evidence admits a World execution. + WorldStartSessionExecutionTerminalReadRequest exactIdentity = + new WorldStartSessionExecutionTerminalReadRequest( + request.readRequestId(), + request.targetNamespace(), + this.originalPostAuthorizationTuple, + request.accountWorldParticipationId(), + request.accountWorldParticipationFence(), + this.gameSessionOwnerAttemptId, + this.gameSessionOwnerFence, + this.canonicalGameInstanceId, + this.preparationInputJson); + if (!exactIdentity.preparationInputDigest().equals(this.preparationInputDigest)) { + throw new IllegalArgumentException( + "preparationInputDigest differs from the exact retained preparation input"); + } + if (this.preparationInputJson.getBytes(java.nio.charset.StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException( + "Historical World preparation input exceeds its byte limit"); + } + } + + public AccountStartSessionWorldParticipationHistoricalReadRequest request() { + return request; + } + + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + public UUID gameSessionOwnerAttemptId() { + return gameSessionOwnerAttemptId; + } + + public long gameSessionOwnerFence() { + return gameSessionOwnerFence; + } + + public UUID canonicalGameInstanceId() { + return canonicalGameInstanceId; + } + + /** Returns the retained input byte-for-byte as text; it is never rewritten during recovery. */ + public String preparationInputJson() { + return preparationInputJson; + } + + public String preparationInputDigest() { + return preparationInputDigest; + } + + @Override + public String toString() { + return "AccountStartSessionWorldParticipationHistoricalReadEvidence[request=" + + request + + ", preparationInput=]"; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.java new file mode 100644 index 0000000000..dee08b1460 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.common.account.startsession; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; + +/** Closed protobuf adapter for Account's historical World participation read. */ +public final class AccountStartSessionWorldParticipationHistoricalReadGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = + WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + + 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountStartSessionWorldParticipationHistoricalReadGrpcCodec() {} + + public static ReadHistoricalStartSessionWorldParticipationRequest toRequest( + AccountStartSessionWorldParticipationHistoricalReadRequest request) { + Objects.requireNonNull(request, "historical participation request is required"); + var result = + ReadHistoricalStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion( + AccountStartSessionWorldParticipationHistoricalReadRequest.SCHEMA_VERSION) + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setAccountWorldParticipationId(request.accountWorldParticipationId().toString()) + .setAccountWorldParticipationFence(request.accountWorldParticipationFence()) + .build(); + if (result.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) { + throw new IllegalArgumentException("Historical participation request exceeds its wire limit"); + } + return result; + } + + public static AccountStartSessionWorldParticipationHistoricalReadRequest fromRequest( + ReadHistoricalStartSessionWorldParticipationRequest request) { + Objects.requireNonNull(request, "historical participation request is required"); + requireClosedMessage(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_WIRE_BYTES + || request.getSchemaVersion() + != AccountStartSessionWorldParticipationHistoricalReadRequest.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Unsupported or oversized historical participation request"); + } + return new AccountStartSessionWorldParticipationHistoricalReadRequest( + canonicalUuid(request.getReadRequestId(), "readRequestId"), + request.getTargetNamespace(), + canonicalUuid(request.getAccountWorldParticipationId(), "accountWorldParticipationId"), + request.getAccountWorldParticipationFence()); + } + + public static ReadHistoricalStartSessionWorldParticipationResponse toResponse( + AccountStartSessionWorldParticipationHistoricalReadRequest request, + AccountStartSessionWorldParticipationHistoricalReadEvidence evidence) { + Objects.requireNonNull(evidence, "historical participation evidence is required"); + requireSameRequest(request, evidence.request()); + var response = + ReadHistoricalStartSessionWorldParticipationResponse.newBuilder() + .setRequest(toRequest(request)) + .setOriginalPostAuthorizationTuple( + ByteString.copyFrom(evidence.originalPostAuthorizationTuple())) + .setGameSessionOwnerAttemptId(evidence.gameSessionOwnerAttemptId().toString()) + .setGameSessionOwnerFence(evidence.gameSessionOwnerFence()) + .setCanonicalGameInstanceId(evidence.canonicalGameInstanceId().toString()) + .setPreparationInputJson(evidence.preparationInputJson()) + .setPreparationInputDigest(evidence.preparationInputDigest()) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) { + throw new IllegalArgumentException( + "Historical participation response exceeds its wire limit"); + } + return response; + } + + public static AccountStartSessionWorldParticipationHistoricalReadEvidence fromResponse( + AccountStartSessionWorldParticipationHistoricalReadRequest request, + ReadHistoricalStartSessionWorldParticipationResponse response) { + Objects.requireNonNull(request, "historical participation request is required"); + Objects.requireNonNull(response, "historical participation response is required"); + requireClosedMessage(response, "response"); + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES || !response.hasRequest()) { + throw new IllegalArgumentException("Missing or oversized historical participation response"); + } + AccountStartSessionWorldParticipationHistoricalReadRequest echoedRequest = + fromRequest(response.getRequest()); + requireSameRequest(request, echoedRequest); + byte[] originalTuple = response.getOriginalPostAuthorizationTuple().toByteArray(); + if (originalTuple.length == 0 + || originalTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException("Original StartSession tuple is missing or oversized"); + } + if (response.getPreparationInputJson().getBytes(java.nio.charset.StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException("Historical preparation input exceeds its byte limit"); + } + return new AccountStartSessionWorldParticipationHistoricalReadEvidence( + echoedRequest, + originalTuple, + canonicalUuid(response.getGameSessionOwnerAttemptId(), "gameSessionOwnerAttemptId"), + response.getGameSessionOwnerFence(), + canonicalUuid(response.getCanonicalGameInstanceId(), "canonicalGameInstanceId"), + response.getPreparationInputJson(), + response.getPreparationInputDigest()); + } + + private static void requireSameRequest( + AccountStartSessionWorldParticipationHistoricalReadRequest expected, + AccountStartSessionWorldParticipationHistoricalReadRequest actual) { + Objects.requireNonNull(expected, "historical participation request is required"); + if (!expected.equals(actual)) { + throw new IllegalArgumentException( + "Account changed the exact historical participation request"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static void requireClosedMessage(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Account historical participation " + label + " contains unsupported fields"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadRequest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadRequest.java new file mode 100644 index 0000000000..a9e1359062 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadRequest.java @@ -0,0 +1,44 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact lookup identity for one historical Account World StartSession participation. */ +public record AccountStartSessionWorldParticipationHistoricalReadRequest( + UUID readRequestId, + String targetNamespace, + UUID accountWorldParticipationId, + long accountWorldParticipationFence) { + public static final int SCHEMA_VERSION = 1; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public AccountStartSessionWorldParticipationHistoricalReadRequest { + requireNonNil(readRequestId, "readRequestId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + Objects.requireNonNull(accountWorldParticipationId, "accountWorldParticipationId"); + if (NIL_UUID.equals(accountWorldParticipationId)) { + throw new IllegalArgumentException( + "accountWorldParticipationId must be a canonical non-nil UUID"); + } + if (readRequestId.equals(accountWorldParticipationId)) { + throw new IllegalArgumentException( + "readRequestId must be fresh and distinct from the participation ID"); + } + if (accountWorldParticipationFence <= 0L) { + throw new IllegalArgumentException( + "accountWorldParticipationFence must be a positive signed 64-bit integer"); + } + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return value; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java index 69b859d18e..8023bac9c4 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClient.java @@ -102,6 +102,8 @@ protected String defaultTarget() { String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; return WorldStartSessionExecutionTerminalReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + WorldStartSessionExecutionTerminalReadGrpcCodec.MAX_RESPONSE_BYTES) .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java index 19d7dcdecc..d4f36ac9ff 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodec.java @@ -10,6 +10,10 @@ /** Closed protobuf adapter for exact historical StartSession terminal readback. */ public final class WorldStartSessionExecutionTerminalReadGrpcCodec { + /** Canonical terminal plus bounded protobuf framing and the fresh read UUID. */ + public static final int MAX_RESPONSE_BYTES = + WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + 1_024; + private static final UUID NIL_UUID = new UUID(0L, 0L); private WorldStartSessionExecutionTerminalReadGrpcCodec() {} @@ -62,6 +66,9 @@ public static WorldStartSessionExecutionTerminal fromResponse( ReadWorldStartSessionExecutionTerminalResponse response) { Objects.requireNonNull(request, "World StartSession terminal read request"); Objects.requireNonNull(response, "World StartSession terminal response"); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw invalid("World StartSession terminal response exceeds its wire limit"); + } requireNoUnknownFields(response, "response"); UUID readRequestId = canonicalUuid(response.getReadRequestId(), "readRequestId"); if (!request.readRequestId().equals(readRequestId)) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java new file mode 100644 index 0000000000..b5795f3343 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +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; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Configuration and call-boundary proof only; this is not socket or peer-authentication proof. */ +class AccountStartSessionWorldParticipationHistoricalReadClientTest { + @Test + void requiresFileBackedMtlsAndConfiguredNamespace(@TempDir Path directory) throws Exception { + var plaintext = fileBacked(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var classpath = fileBacked(directory); + classpath.setPrivateKey("classpath:private.key"); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + var client = + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + fileBacked(directory), + new GrpcChannelFactory(), + "world-runtime"); + try { + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + fileBacked(directory), + new GrpcChannelFactory(), + "not a namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + assertThatThrownBy(() -> client.read(request("other-runtime"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + } finally { + client.close(); + } + } + + @Test + void requiresInitializedClientAndNoAmbientSqlOrSynchronization(@TempDir Path directory) + throws Exception { + var client = + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + fileBacked(directory), + new GrpcChannelFactory(), + "world-runtime"); + try { + assertThatThrownBy(() -> client.read(request("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(request("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + } finally { + TransactionSynchronizationManager.clear(); + client.close(); + } + } + + private static AccountStartSessionWorldParticipationHistoricalReadRequest request( + String namespace) { + return new AccountStartSessionWorldParticipationHistoricalReadRequest( + UUID.fromString("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"), + namespace, + UUID.fromString("a8c1e8c8-f237-41b7-918d-ec2281bcac10"), + 31L); + } + + private static CommonGrpcClientProperties fileBacked(Path directory) throws Exception { + var properties = new CommonGrpcClientProperties(); + properties.setCertChain( + Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + properties.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "private key").toString()); + properties.setCaCert( + Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return properties; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java new file mode 100644 index 0000000000..553dde81d2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java @@ -0,0 +1,328 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final UUID READ_ID = uuid("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"); + private static final String PREPARATION_INPUT = + "{ \"identity\" : \"retained original input\", \"revision\": 3 }\n"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void roundTripsOnlyTheExactHistoricalRequestAndAccountRetainedFields() { + var request = request(); + var evidence = evidence(request); + + var wireRequest = + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toRequest(request); + var decodedRequest = + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest(wireRequest); + assertThat(decodedRequest).isEqualTo(request); + + var response = + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse(request, evidence); + assertThat(response.getAllFields()).hasSize(7); + var decoded = + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, response); + assertThat(decoded.request()).isEqualTo(request); + assertThat(decoded.originalPostAuthorizationTuple()) + .containsExactly(evidence.originalPostAuthorizationTuple()); + assertThat(decoded.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); + assertThat(decoded.gameSessionOwnerFence()).isEqualTo(37L); + assertThat(decoded.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(decoded.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + assertThat(decoded.preparationInputDigest()).isEqualTo(digest(PREPARATION_INPUT)); + } + + @Test + void rejectsUnknownFieldsUnsupportedVersionMalformedIdsAndNonpositiveFences() { + var request = request(); + UnknownFieldSet unknown = unknown(); + var wire = AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toRequest(request); + + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder().setSchemaVersion(2).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder().setReadRequestId(READ_ID + " ").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil UUID"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder().setAccountWorldParticipationFence(0L).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive"); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, NAMESPACE, READ_ID, 31L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("distinct"); + } + + @Test + void rejectsChangedRequestEchoUnknownResponseAndInconsistentRetainedIdentity() { + var request = request(); + var response = + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse( + request, evidence(request)); + + var changedEcho = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder().setTargetNamespace("other-runtime").build()) + .build(); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, changedEcho)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setPreparationInputDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from the exact retained"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse( + request, + new AccountStartSessionWorldParticipationHistoricalReadEvidence( + request, + originalTuple("other-runtime").canonicalBytes(), + GAME_SESSION_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + PREPARATION_INPUT, + digest(PREPARATION_INPUT)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from the exact original"); + } + + @Test + void rejectsOversizedPreparationInputAndTupleAtClosedCarrierBoundary() { + var request = request(); + String oversized = "x".repeat(WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + 1); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadEvidence( + request, + originalTuple(NAMESPACE).canonicalBytes(), + GAME_SESSION_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + oversized, + digest(oversized))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("byte limit"); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadEvidence( + request, + new byte + [net.firedevops.firemud.common.operator + .StartSessionPostAuthorizationExecutionTuple + .MAX_CANONICAL_TUPLE_BYTES + + 1], + GAME_SESSION_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + PREPARATION_INPUT, + digest(PREPARATION_INPUT))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("oversized"); + } + + private static AccountStartSessionWorldParticipationHistoricalReadRequest request() { + return new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, NAMESPACE, PARTICIPATION_ID, 31L); + } + + private static AccountStartSessionWorldParticipationHistoricalReadEvidence evidence( + AccountStartSessionWorldParticipationHistoricalReadRequest request) { + return new AccountStartSessionWorldParticipationHistoricalReadEvidence( + request, + originalTuple(NAMESPACE).canonicalBytes(), + GAME_SESSION_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + PREPARATION_INPUT, + digest(PREPARATION_INPUT)); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(String namespace) { + UUID actor = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + UUID targetOwner = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwner = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + String requestId = "historical-participation-original-request"; + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + actor, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, targetOwner), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic historical Account evidence carrier test")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + reservationOwner, + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String actorId = tuple.actor().accountId().toString(); + String tenantId = tuple.action().scope().tenantId().toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2020-01-01T00:00:00Z", + "expiresAt", "2020-01-02T00:00:00Z"); + Map issuanceIdentity = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map humanEvidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", actorId, + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + issuanceIdentity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + humanEvidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static String digest(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java index f2ce5b08aa..d7b806d289 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java @@ -1,7 +1,9 @@ package net.firedevops.firemud.common.world; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.grpc.ManagedChannelBuilder; import java.nio.file.Files; import java.nio.file.Path; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -12,6 +14,27 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; class WorldStartSessionExecutionTerminalReadClientTest { + @Test + void clientReceiveLimitIncludesTheCompleteCanonicalTerminalEnvelope(@TempDir Path directory) + throws Exception { + var client = + new WorldStartSessionExecutionTerminalReadClient( + new ServiceEndpointsProperties(), + fileBacked(directory), + new GrpcChannelFactory(), + "world-runtime"); + // No connection is made: this verifies stub configuration, not authenticated socket proof. + var channel = ManagedChannelBuilder.forTarget("localhost:1").usePlaintext().build(); + try { + assertThat(client.buildStub(channel).getCallOptions().getMaxInboundMessageSize()) + .isEqualTo(WorldStartSessionExecutionTerminalReadGrpcCodec.MAX_RESPONSE_BYTES) + .isGreaterThan(WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES); + } finally { + channel.shutdownNow(); + client.close(); + } + } + @Test void requiresFileBackedMtlsInitializationAndAnIndependentCallerTransaction( @TempDir Path directory) throws Exception { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java index c82598b08c..567f98dab2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java @@ -36,6 +36,21 @@ class WorldStartSessionExecutionTerminalReadGrpcCodecTest { private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); private static final JsonMapper JSON = JsonMapper.builder().build(); + @Test + void rejectsAnOverboundWireEnvelopeBeforeDecodingItsTerminal() { + var response = + ReadWorldStartSessionExecutionTerminalResponse.newBuilder() + .setReadRequestId(READ_ID.toString()) + .setCanonicalTerminalBytes( + com.google.protobuf.ByteString.copyFrom( + new byte[WorldStartSessionExecutionTerminalReadGrpcCodec.MAX_RESPONSE_BYTES])) + .build(); + assertThatThrownBy( + () -> WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse(request(), response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire limit"); + } + @Test void roundTripsFreshReadAndOnlyCanonicalTerminalResult() { var request = request(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 7af93d68db..cb588dd7fe 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -745,6 +745,87 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex .sources() .tx(() -> accountAccess.sources().fences.readSettlement(original))) .isEqualTo(DraftAuthorizationFenceRepository.Settlement.COMMITTED); + + // Entity and Automation are later source readers, not members required by the original + // Draft's mutation participant vector. These are distinct Account reservations under the + // same current creator and exact already-settled selected Draft. + UUID entityIntakeRequest = UUID.randomUUID(); + var entitySourceReservation = + account.reserveSelectedOwnerSourceRead( + entityIntakeRequest, Owner.ENTITY_MANAGEMENT, selectedCommit, NAMESPACE); + var entitySourceReservationRetry = + account.reserveSelectedOwnerSourceRead( + entityIntakeRequest, Owner.ENTITY_MANAGEMENT, selectedCommit, NAMESPACE); + assertThat(entitySourceReservation.owner()).isEqualTo(Owner.ENTITY_MANAGEMENT); + assertThat(entitySourceReservation.intakeRequestId()).isEqualTo(entityIntakeRequest); + assertThat(entitySourceReservation.selected().canonicalBytes()) + .containsExactly(selectedCommit.canonicalBytes()); + assertThat(entitySourceReservation.actorAccountId()).isEqualTo(original.actorAccountId()); + assertThat(entitySourceReservation.operationId()).isNotEqualTo(original.operationId()); + assertThat(entitySourceReservation.fenceId()).isNotEqualTo(original.fenceId()); + assertThat(entitySourceReservationRetry.canonicalBytes()) + .containsExactly(entitySourceReservation.canonicalBytes()); + assertThat( + account.recoverSelectedOwnerSourceRead(entitySourceReservation, NAMESPACE).state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED); + + UUID automationIntakeRequest = UUID.randomUUID(); + var automationSourceReservation = + account.reserveSelectedOwnerSourceRead( + automationIntakeRequest, Owner.AUTOMATION_SCRIPTING, selectedCommit, NAMESPACE); + var automationSourceReservationRetry = + account.reserveSelectedOwnerSourceRead( + automationIntakeRequest, Owner.AUTOMATION_SCRIPTING, selectedCommit, NAMESPACE); + assertThat(automationSourceReservation.owner()).isEqualTo(Owner.AUTOMATION_SCRIPTING); + assertThat(automationSourceReservation.intakeRequestId()) + .isEqualTo(automationIntakeRequest); + assertThat(automationSourceReservation.intakeRequestId()) + .isNotEqualTo(entitySourceReservation.intakeRequestId()); + assertThat(automationSourceReservation.selected().canonicalBytes()) + .containsExactly(selectedCommit.canonicalBytes()); + assertThat(automationSourceReservation.actorAccountId()) + .isEqualTo(original.actorAccountId()); + assertThat(automationSourceReservation.operationId()) + .isNotEqualTo(original.operationId()) + .isNotEqualTo(entitySourceReservation.operationId()); + assertThat(automationSourceReservation.fenceId()) + .isNotEqualTo(original.fenceId()) + .isNotEqualTo(entitySourceReservation.fenceId()); + assertThat(automationSourceReservationRetry.canonicalBytes()) + .containsExactly(automationSourceReservation.canonicalBytes()); + assertThat( + account + .recoverSelectedOwnerSourceRead(automationSourceReservation, NAMESPACE) + .state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED); + + var expectedAccountSourceEvidence = + original.sources().stream() + .map( + source -> + source.key() + ":" + HexFormat.of().formatHex(source.canonicalBytes())) + .sorted() + .toList(); + var accountSourceDsl = accountAccess.sources().dsl; + var entityReservationSourcesBeforeAbort = + selectedOwnerReservationSourceRows( + accountSourceDsl, entitySourceReservation.operationId()); + var automationReservationSourcesBeforeAbort = + selectedOwnerReservationSourceRows( + accountSourceDsl, automationSourceReservation.operationId()); + assertThat(entityReservationSourcesBeforeAbort) + .containsExactlyElementsOf(expectedAccountSourceEvidence); + assertThat(automationReservationSourcesBeforeAbort) + .containsExactlyElementsOf(expectedAccountSourceEvidence); + var accountReservationSourcesBeforeExport = + Map.of( + Owner.ENTITY_MANAGEMENT, + selectedOwnerReservationSourceRows( + accountSourceDsl, entitySourceReservation.operationId()), + Owner.AUTOMATION_SCRIPTING, + selectedOwnerReservationSourceRows( + accountSourceDsl, automationSourceReservation.operationId())); + var appliedWorld = worldApplications.readCommitted(NAMESPACE, original.canonicalBytes()).orElseThrow(); assertThat(appliedWorld.status()).isEqualTo("APPLIED"); @@ -767,14 +848,20 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var ownerIntakeSourceRepository = new GameDesignSourceRepository(gd.dsl()); var sourceRowsBeforeExport = selectedOwnerSourceRowCounts(gd.dsl()); for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { - // This scope is only the export's integrity input. No Account authorization or owner - // retention receipt exists for these domains in this composed fixture. - var scope = selectedOwnerSourceScope(owner, selectedCommit); + // Account's real preliminary scope authorizes source-read participation only. The direct + // Game Design repository export below checks selected-source integrity, not authenticated + // transport, owner retention, settlement, or activation. + var scope = + owner == Owner.ENTITY_MANAGEMENT + ? entitySourceReservation + : automationSourceReservation; SelectedOwnerIntakeSourceExport exportedSource = ownerIntakeSourceRepository.requireSelectedOwnerIntakeSource(scope); SelectedOwnerIntakeSourceExport exactRetry = ownerIntakeSourceRepository.requireSelectedOwnerIntakeSource(scope); + assertThat(exportedSource.scope().canonicalBytes()) + .containsExactly(scope.canonicalBytes()); assertThat(exportedSource.scope().selected().canonicalBytes()) .containsExactly(selectedCommit.canonicalBytes()); assertThat(exportedSource.sources().command().binding()).isEqualTo(selectedCommit); @@ -788,6 +875,34 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(exactRetry.canonicalBytes()).containsExactly(exportedSource.canonicalBytes()); assertThat(exactRetry.digest()).isEqualTo(exportedSource.digest()); } + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, entitySourceReservation.operationId())) + .containsExactlyElementsOf( + accountReservationSourcesBeforeExport.get(Owner.ENTITY_MANAGEMENT)); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, automationSourceReservation.operationId())) + .containsExactlyElementsOf( + accountReservationSourcesBeforeExport.get(Owner.AUTOMATION_SCRIPTING)); + assertThat(account.abortSelectedOwnerSourceRead(entitySourceReservation, NAMESPACE).state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED); + assertThat( + account.recoverSelectedOwnerSourceRead(entitySourceReservation, NAMESPACE).state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED); + assertThat( + account + .recoverSelectedOwnerSourceRead(automationSourceReservation, NAMESPACE) + .state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, entitySourceReservation.operationId())) + .containsExactlyElementsOf(entityReservationSourcesBeforeAbort); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, automationSourceReservation.operationId())) + .containsExactlyElementsOf(automationReservationSourcesBeforeAbort); var wrongTarget = new TargetProof( gd.target().canonicalTenantId(), @@ -2141,6 +2256,19 @@ private static Map selectedOwnerSourceRowCounts(DSLContext dsl) dsl.fetchCount(DSL.table("game_design_template_config_source_snapshot"))); } + private static List selectedOwnerReservationSourceRows(DSLContext dsl, UUID operationId) { + return dsl.fetch( + "SELECT source_key, source_evidence " + + "FROM account_selected_owner_intake_source_read_sources " + + "WHERE operation_id = ? ORDER BY source_key", + operationId) + .map( + row -> + row.get("source_key", String.class) + + ":" + + HexFormat.of().formatHex(row.get("source_evidence", byte[].class))); + } + private static Store serviceStore(PostgreSQLContainer postgres, String service) { var schema = service.replace('-', '_') + "_" + UUID.randomUUID().toString().replace("-", ""); var data = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java index cd816044a3..4347853fe3 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java @@ -56,7 +56,8 @@ public WorldCanonicalInstancePreparationService( */ public Result prepare(Input input) { Objects.requireNonNull(input, "input"); - if (TransactionSynchronizationManager.isActualTransactionActive()) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { throw new IllegalStateException( "Canonical World preparation must verify outside an ambient transaction"); } @@ -82,7 +83,8 @@ public Result prepare(Input input) { public WorldCanonicalInstancePreparationRepository.ExecutionLookup recoverExact( WorldCanonicalInstanceExecutionIdentity originalIdentity) { Objects.requireNonNull(originalIdentity, "original World execution identity is required"); - if (TransactionSynchronizationManager.isActualTransactionActive()) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { throw new IllegalStateException( "Exact World execution recovery must authenticate outside an ambient transaction"); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java index 50815f5f2b..7b3472dd9e 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java @@ -90,6 +90,47 @@ void ambientTransactionIsDeniedBeforeRecoveryAuthenticationOrStorage() { verifyNoInteractions(repository, recoveryVerifier); } + @Test + void ambientSynchronizationIsDeniedBeforeRecoveryAuthenticationOrStorage() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var recoveryVerifier = + mock(WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier.class); + var identity = mock(WorldCanonicalInstanceExecutionIdentity.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + var service = + new WorldCanonicalInstancePreparationService(repository, commitVerifier, recoveryVerifier); + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy(() -> service.recoverExact(identity)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must authenticate outside an ambient transaction"); + + verifyNoInteractions(repository, recoveryVerifier, commitVerifier); + } + + @Test + void ambientSynchronizationIsDeniedBeforeFreshPreparationVerificationOrStorage() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + var recoveryVerifier = + mock(WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier.class); + var input = + mock( + net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input + .class); + var service = + new WorldCanonicalInstancePreparationService(repository, commitVerifier, recoveryVerifier); + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy(() -> service.prepare(input)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must verify outside an ambient transaction"); + + verifyNoInteractions(repository, recoveryVerifier, commitVerifier, input); + } + @Test void exactRecoveryAuthenticatesThenReturnsTheUnchangedReadOnlyLookup() { var repository = mock(WorldCanonicalInstancePreparationRepository.class); From b2a64a4f40526167395ed1df00812bd80be5d9a6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 15:46:09 +1300 Subject: [PATCH 070/129] Compose exact historical World recovery and canonical hold reconciliation --- .../world-management-service/api-contracts.md | 1 + .../runtime-and-data.md | 4 +- ...ame-authoring-publishing-and-activation.md | 4 + .../world-runtime-and-movement.md | 4 +- ...riginal_start_session_owner_evidence.proto | 60 ++ ...ected_owner_intake_source_reservations.sql | 4 +- ...uthoredWorldLaunchDescriptorGrpcCodec.java | 22 + ...icalOriginalStartSessionOwnerEvidence.java | 374 +++++++ ...nalStartSessionOwnerEvidenceGrpcCodec.java | 278 +++++ ...alStartSessionOwnerEvidenceReadClient.java | 166 +++ ...tartSessionOwnerEvidenceGrpcCodecTest.java | 148 +++ ...artSessionOwnerEvidenceReadClientTest.java | 122 +++ .../InitialAdmissionBindHoldRepository.java | 3 +- ...nonicalInitialAdmissionHoldReconciler.java | 139 +++ ...nCanonicalInitialAdmissionOwnerClient.java | 20 +- ...nonicalInitialAdmissionOwnerGrpcCodec.java | 36 +- ...itialAdmissionHoldFinalizationService.java | 42 + ...nonicalInitialAdmissionHoldRepository.java | 158 +++ ...anceOriginalOperationRecoveryVerifier.java | 973 ++++++++++++++++++ ...ldCanonicalInstancePreparationService.java | 14 +- ...aphApplicationPostgresIntegrationTest.java | 142 +++ ...nitialAdmissionBindHoldRepositoryTest.java | 19 + ...calInitialAdmissionHoldReconcilerTest.java | 244 +++++ ...alInitialAdmissionOwnerClientMtlsTest.java | 38 +- ...onicalInitialAdmissionOwnerClientTest.java | 4 + ...calInitialAdmissionOwnerGrpcCodecTest.java | 55 + ...lAdmissionHoldFinalizationServiceTest.java | 127 +++ ...calInitialAdmissionHoldRepositoryTest.java | 64 ++ ...OriginalOperationRecoveryVerifierTest.java | 869 ++++++++++++++++ ...anonicalPlayerLocationGrpcServiceTest.java | 3 +- 30 files changed, 4110 insertions(+), 27 deletions(-) create mode 100644 protos/game-session/v1/historical_original_start_session_owner_evidence.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldCanonicalInitialAdmissionHoldReconciler.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldCanonicalInitialAdmissionHoldReconcilerTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index ef0f6fdd51..6a0e372112 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -15,6 +15,7 @@ This API contract is target-state canonical; implementation coverage is partial - The separate canonical StartSession preparation construction must use the distinct Account World receiving participation and World-local terminal serialization described in [World runtime/data](runtime-and-data.md#original-startsession-execution-storage). Its typed execution identity is binding data, not authenticated authorization. No runtime RPC or positive producer is registered by these storage seams; the ordinary lifecycle handler's Game Session peer guard does not complete this canonical path. - A standalone `ReadWorldStartSessionExecutionTerminal` adapter and file-backed mTLS client are constructed but unregistered. The adapter requires the exact same-namespace Account workload without end-user context before parsing, then delegates to the separately verified original-operation recovery read. Its focused unit definitions stipulate that verifier; they do not establish genuine authenticated recovery or settlement. - The unregistered canonical initial-admission hold adapter includes a separate exact hold-state/lifecycle read. The repository reads actual status and current lifecycle in one read-only snapshot; historical identity readback remains unchanged. Focused mock/unit definitions and a synthetic legacy-row PostgreSQL definition are not genuine database-to-RPC or continuous-protection proof. +- An unregistered original-operation recovery verifier composes the distinct Account historical participation read with Game Session's historical original tuple, owner attempt, first-selection pin and immutable launch evidence. It compares the exact retained World preparation input without renewing execution authority; mocked composition tests do not prove genuine authenticated producer composition. The unregistered canonical hold reconciler similarly requires exact Game Session terminal evidence and never infers abort from expiry or absence. Detailed proof limits remain in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md). - 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. ## gRPC APIs diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index b2b23c8e65..8e25f8aa30 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -33,7 +33,7 @@ World Management instances are intended to be replaceable workers over authorita Execution admission, materialization, canonical association and `COMMITTED` publication share one uninterrupted local SQL transaction. The operation/request and canonical-target serialization precede the existing publication and topology locks; the database checks actual current time after lock waits before admitting execution. Network calls occur before SQL, never under these locks. Operational transaction timeouts and cancellation bound resource use, not the physical instant of commit. An execution admitted while the original authorization and owner claim are valid may finish after ingress expiry; expiry never permits another execution transaction, renewed participation or a replacement attempt. -Exact recovery compares the retained full identity and immutable terminal preparation result. Its service read path authenticates the original operation outside SQL, separately from fresh-admission verification, and reads only that stored operation; ingress expiry cannot turn it into renewed execution. Existing constructors deny recovery unless an explicit original-operation verifier is supplied. The unregistered terminal-read adapter accepts only exact same-namespace Account, denies ambient transactions or synchronization, and compares fresh read correlation and every immutable identity field through the closed Common codec. Its file-backed mTLS client checks the exact World peer and applies a bounded call deadline. These transport components do not supply the missing genuine original-operation verifier. A separate `ABORTED` transaction takes the same operation and target serialization, excludes a live execution and permanently fences later materialization and canonical association. Missing rows, timeouts and rolled-back intermediate states are not abort proof. An unknown outcome remains unresolved until exact `COMMITTED` readback or serialized `ABORTED` proof; Account retains its source protection until authenticated terminal settlement. These storage and transport components do not supply the missing genuine Account participation producer or complete authenticated terminal settlement. The canonical preparation service remains unavailable for runtime use until that producer, consumer and physical concurrency/recovery proof are complete. +Exact recovery compares the retained full identity and immutable terminal preparation result. Its service read path authenticates the original operation outside SQL, separately from fresh-admission verification, and reads only that stored operation; ingress expiry cannot turn it into renewed execution. Existing constructors deny recovery unless an explicit original-operation verifier is supplied. The unregistered terminal-read adapter accepts only exact same-namespace Account, denies ambient transactions or synchronization, and compares fresh read correlation and every immutable identity field through the closed Common codec. Its file-backed mTLS client checks the exact World peer and applies a bounded call deadline. A separate unregistered verifier composes Account's historical participation read and Game Session's historical original tuple, owner attempt, first-selection pin and immutable launch evidence against the exact retained preparation bytes. It grants no fresh execution authority; genuine producer composition remains unproved. A separate `ABORTED` transaction takes the same operation and target serialization, excludes a live execution and permanently fences later materialization and canonical association. Missing rows, timeouts and rolled-back intermediate states are not abort proof. An unknown outcome remains unresolved until exact `COMMITTED` readback or serialized `ABORTED` proof; Account retains its source protection until authenticated terminal settlement. These storage and transport components do not supply the missing genuine Account participation acquisition or complete authenticated terminal settlement. The canonical preparation service remains unavailable for runtime use until producer, consumer and physical concurrency/recovery proof are complete. The immutable integrity carrier is `world-start-session-execution-terminal/v1`. Its closed RFC 8785 UTF-8 object contains exactly `schema`, `originalPostAuthorizationTupleBase64`, `accountWorldParticipationId`, `accountWorldParticipationFence`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `targetNamespace`, `canonicalTenantId`, `controlPlaneRequestId`, `canonicalGameInstanceId`, `preparationInputDigest`, `preparationInputJson`, `worldExecutionFence`, and `outcome`. The original post-authorization tuple remains byte-exact with `targetOwner=game-session-service`; the duplicated namespace, tenant and request must match it. UUIDs are canonical and non-nil. Each fence is an independently owned positive BIGINT represented as a canonical decimal string; equal numeric values across owners are permitted, not evidence of an alias. Outcomes are only `COMMITTED` or `ABORTED`. @@ -138,7 +138,7 @@ The initial realm bind uses a separate World-owned hold because it has no source The World termination compare-and-set checks that neither an initial-bind nor replacement hold is nonterminal under the same lifecycle-row serialization. A held instance cannot enter `TERMINATING` or advance its lifecycle epoch. Resolving the hold does not weaken ordinary termination: the stable cleanup request, frozen owner/registry snapshot, owner acknowledgements, and final `TERMINATED` compare-and-set remain in force. Game Session must atomically commit the first pointer, matching append-only audit, and terminal attempt outcome in its own database; World then uses authenticated exact owner readback to finalize or to accept only a durable `ABORTED` outcome bound to the same hold/tuple that prevents a later commit for that attempt. Missing, pending, unavailable, mismatched, or contradictory evidence leaves the hold nonterminal. Durable records and the automatic reconciliation path recover the exact identity/fence after response loss or restart; timeout or expiry only triggers repair and never auto-releases the hold. The full normative contract is in [Initial Admission Bind Hold Contract](./api-contracts.md#initial-admission-bind-hold-contract). -World now persists the initial-bind hold separately and includes it in the lifecycle-row termination check. Its scheduled reconciler uses the method-specific authenticated Game Session owner-proof reader; unavailable, ambiguous, or mismatched evidence keeps the hold nonterminal and termination-blocking. PostgreSQL-backed race/restart and live Compose proof remain unclaimed. See the [World API contract](./api-contracts.md#initial-admission-bind-hold-contract) and [World Runtime and Movement tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md) for the canonical contract and current proof status. +World now persists the initial-bind hold separately and includes it in the lifecycle-row termination check. The legacy numeric scheduled reconciler excludes canonical typed rows. A separate unregistered canonical reconciler scans bounded namespace-qualified keyset pages, independently rereads each exact association, and uses the method-specific authenticated Game Session owner reader outside SQL before serialized terminal finalization. Pending or uncertain evidence leaves the hold nonterminal; reconciliation-required rows are reported without reset. This construction is not automatic runtime wiring or PostgreSQL-backed cross-owner restart proof. See the [World API contract](./api-contracts.md#initial-admission-bind-hold-contract) and [World Runtime and Movement tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md) for the canonical contract and current proof status. ### Runtime configuration and events 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 177787bd1a..d2f451d5fb 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The corrected World historical-recovery and canonical-hold reconciliation batch passes the affected Common/World full checks, Account schema generation and integration compilation, World boot JAR, formatting, static checks, coverage, links and Markdown in 2m23s. World executes 644 unit cases; Common retains 507 passing results. Account's unchanged integration results retain seven non-container passes and 255 skips; World executes one non-container case and skips 220 definitions without Docker. The new recovery positives use mocked owner clients and synthetic constructor-validated source evidence; the canonical-hold database definition stipulates lifecycle and Game Session terminal proof. Neither proves genuine cross-owner recovery or runtime scheduling. All receivers remain unregistered and all four complete Gameplay handoffs remain open. + +Source `17d3872f84358e0bae753620da578c818c503a46` [Validation run 38015116807](https://github.com/benhook1013/FireMUD/actions/runs/38015116807) completed red on synthetic merge `2af891e2352655ca2d33e191e461a1aa1ac79638`, tree `faafb0d3394a5f441e85ca3b54cd2761ca063359`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source; this is not the recorded integration parent. Account executes 261 integration cases with 230 failures, Game Design 151 with 15, World 220 with two and Game Logic nine with one, with zero skips. Account's V129-to-V130 installation and genuine composed fixtures stop at V130's PL/pgSQL inline `CASE` parse error before the intended assertions. The correction parenthesizes that expression without changing owner/purpose mapping, trailing-byte rejection or source protection; schema generation does not prove the ignored procedural block. Corrected physical execution remains required. World's 13 authored-source intake and five mTLS intake cases pass, and Common Data Runtime's check succeeds; the previous dependency-resolution failure does not recur. Game Logic counts originate in its HTML report because its XML capture skipped. The metadata-only duplicate run supplies no substantive proof, and the separate four V120 durability gaps remain open. + The historical participation, preliminary selected-owner reservation and V129 parse-correction batch passes the final affected Account/World/Game Design gate in 1m19s, including integration compilation, static checks, formatting, schema generation and boot JARs. Account's 1,230, World's 623 and Game Design's 539 unit results are green; the separate unchanged Common Platform gate passes with 501 units in 2m46s. Successful unchanged tasks reuse their results. Eight non-container integration cases execute; 622 integration definitions skip without Docker (255 Account, 219 World, 148 Game Design). These include the new participation, migration and originating Game Design reservation definitions; no physical database, socket, fresh-image boot or complete producer/consumer credit follows. Flyway sanity checks 12 sets and 287 versions; links and Markdown pass. The earlier compile/static failures were repaired rather than counted as proof. All four complete Gameplay handoffs remain open. Source `b6456cc7fc8a7aba1b8a952b315f005fca7a21f6` [Validation run 38010530067](https://github.com/benhook1013/FireMUD/actions/runs/38010530067) completed red on synthetic merge `c62aba65d5343a98b84b6d3a71cf9bc052fdd33b` (tree `e0feba547ca21848510e2b4637d12fdbd13e0096`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source). Game Design executed 151 integration cases with 15 failures, World 220 with two failures and Game Logic nine with one failure, all without skips. These failures stop at PostgreSQL SQLSTATE `42601` in Account V129's participation insertion function; they do not prove the blocked authorization or settlement assertions. World's 21 canonical association cases passed. Account's job was canceled without originating results, so neither its test counts nor V127's four physical migration cases receive execution credit. Logging's successful tasks lack exact class-level socket evidence. The duplicate validation run skipped substantive jobs. The separate four V120 durability gaps remain open; this run supplies no new causal evidence for them. Corrected migration installation and genuine composed producer proof remain required. 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 571221e5ad..07e683ed06 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -14,7 +14,9 @@ The unregistered [canonical initial-placement terminal read](../../architecture/ The unregistered [canonical initial-admission hold-state snapshot](../../architecture/microservices/world-management-service/runtime-and-data.md#canonical-initial-admission-hold-state-snapshot) now has a closed Common carrier, method-specific Game Session peer guard and one read-only `REPEATABLE_READ` repository read of exact immutable identity, actual hold status and current lifecycle. Existing hold identity and acquisition bytes are unchanged. Executed Common and mock-owner unit cases cover peer-first/no-query denial, independent request IDs, exact target/fence, all hold statuses, lifecycle advancement and no mutation. The corrected composed Common/World full checks pass with 489 Common and 609 World unit cases, zero failures/errors/skips; unchanged successful World tasks reuse their local results. Of 220 World integration definitions, one non-container case executes and 219 skip without Docker. The new PostgreSQL definition reads synthetic legacy migration rows only; it does not exercise the canonical repository or genuine lifecycle evidence through the RPC and has not executed locally. Physical producer/consumer proof remains required; no runtime registration or continuous-protection credit follows from the sampled read. -The [original StartSession terminal integrity carrier](../../architecture/microservices/world-management-service/runtime-and-data.md#original-startsession-execution-storage) preserves the complete original tuple, independent Account/Game Session/World identities and fences, exact preparation bytes and terminal outcome. Its six executed codec cases, including the corrected frozen canonical vector, do not authenticate a producer or settle Account source protection. An unregistered Account-only terminal receiver and file-backed mTLS client now retain exact correlation and full terminal identity; their new definitions stipulate the original-operation verifier and remain separate from genuine authenticated recovery proof. Genuine Account World participation, original-operation verification, terminal settlement and physical expiry/abort/crash/recovery proof remain open. +The [original StartSession terminal integrity carrier](../../architecture/microservices/world-management-service/runtime-and-data.md#original-startsession-execution-storage) preserves the complete original tuple, independent Account/Game Session/World identities and fences, exact preparation bytes and terminal outcome. Its six executed codec cases, including the corrected frozen canonical vector, do not authenticate a producer or settle Account source protection. An unregistered Account-only terminal receiver and file-backed mTLS client retain exact correlation and full terminal identity. The new [original-operation recovery verifier](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java) composes published historical Game Session and Account owner clients; its [unit definitions](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java) use mocked clients and synthetic, constructor-validated upstream evidence. They are not genuine authenticated recovery proof. Genuine Account World participation acquisition, cross-owner original-operation verification, terminal settlement and physical expiry/abort/crash/recovery proof remain open. + +The separate [canonical hold reconciler](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldCanonicalInitialAdmissionHoldReconciler.java) is unregistered and processes bounded typed namespace-qualified keyset pages without expiry filtering. It rereads each exact association, preserves pending/uncertain holds, and finalizes only complete authenticated Game Session terminal evidence. The legacy scheduled numeric finder excludes canonical rows. [Focused unit definitions](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldCanonicalInitialAdmissionHoldReconcilerTest.java) cover page progress, unavailable evidence, unsigned UUID ordering and ambient-transaction denial. The additional [PostgreSQL definition](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java) uses actual canonical hold persistence with stipulated lifecycle and Game Session terminal proof; it is not genuine owner-to-owner restart or runtime scheduling proof. The corrected combined check passes in 2m23s with 644 World unit cases and retained 507 Common results, zero failures, errors or unit skips. One World non-container integration case executes; 220 definitions skip without Docker. The eight mocked-client recovery cases pass, but genuine producer, database-to-transport, restart and scheduling proof remain open. ## Packet 4 Status and Proof Gaps diff --git a/protos/game-session/v1/historical_original_start_session_owner_evidence.proto b/protos/game-session/v1/historical_original_start_session_owner_evidence.proto new file mode 100644 index 0000000000..1fdd11b1bf --- /dev/null +++ b/protos/game-session/v1/historical_original_start_session_owner_evidence.proto @@ -0,0 +1,60 @@ +syntax = "proto3"; + +package game_session.v1; + +import "game-design/v1/game_design_service.proto"; +import "game-design/v1/start_session_template_association_service.proto"; + +option java_package = "net.firedevops.firemud.gamesession.v1"; +option java_multiple_files = true; + +// Unregistered, read-only historical evidence. This endpoint never grants StartSession +// continuation, mutation, current lease, or admission authority. +service HistoricalOriginalStartSessionOwnerEvidenceReadService { + rpc ReadHistoricalOriginalStartSessionOwnerEvidence( + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest) + returns (ReadHistoricalOriginalStartSessionOwnerEvidenceResponse); +} + +message ReadHistoricalOriginalStartSessionOwnerEvidenceRequest { + int32 schema_version = 1; + string read_request_id = 2; + string target_namespace = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string game_instance_uuid = 6; + string control_plane_request_id = 7; + string launch_descriptor_id = 8; + string expected_descriptor_request_digest = 9; + string expected_descriptor_result_digest = 10; + string expected_release_attestation_evidence_digest = 11; + string expected_owner_attempt_id = 12; + int64 expected_owner_fence = 13; +} + +message ReadHistoricalOriginalStartSessionOwnerEvidenceResponse { + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest request = 1; + bytes canonical_post_authorization_tuple = 2; + string owner_attempt_id = 3; + int64 owner_fence = 4; + bytes account_redemption_projection = 5; + game_design.v1.ReadStartSessionTemplateAssociationRequest template_association_request = 6; + game_design.v1.ReadStartSessionTemplateAssociationResponse template_association_response = 7; + string template_association_request_digest = 8; + string template_association_response_digest = 9; + game_design.v1.ResolveStartSessionLaunchDescriptorResponse descriptor_pin_response = 10; + string descriptor_pin_request_digest = 11; + string descriptor_pin_response_digest = 12; + string playable_state_namespace_id = 13; + string playable_state_scope = 14; + bool public_production = 15; + int64 captured_starting_row_version = 16; + gamedesign.v1.LaunchDescriptor launch_descriptor = 17; + gamedesign.v1.AuthoredWorldReleaseAttestationEvidence release_attestation = 18; + string association_target_namespace = 19; + string association_canonical_tenant_id = 20; + string association_world_slug = 21; + string association_game_instance_uuid = 22; + string association_control_plane_request_id = 23; + string association_launch_descriptor_id = 24; +} diff --git a/services/account-service/src/main/resources/db/migration/V130__selected_owner_intake_source_reservations.sql b/services/account-service/src/main/resources/db/migration/V130__selected_owner_intake_source_reservations.sql index 54f460da6b..7e5139be0f 100644 --- a/services/account-service/src/main/resources/db/migration/V130__selected_owner_intake_source_reservations.sql +++ b/services/account-service/src/main/resources/db/migration/V130__selected_owner_intake_source_reservations.sql @@ -145,10 +145,10 @@ BEGIN END IF; SELECT convert_from(frame_value, 'UTF8'), next_position INTO purpose_value, p FROM account_publication_authorization_read_frame(NEW.scope_bytes, p); - IF purpose_value IS DISTINCT FROM CASE NEW.owner + IF purpose_value IS DISTINCT FROM (CASE NEW.owner WHEN 'ENTITY_MANAGEMENT' THEN 'ENTITY_INTAKE_SOURCE' WHEN 'AUTOMATION_SCRIPTING' THEN 'AUTOMATION_INTAKE_SOURCE' - ELSE NULL END + ELSE NULL END) OR p <> octet_length(NEW.scope_bytes) + 1 THEN RAISE EXCEPTION 'Invalid preliminary owner purpose or trailing scope bytes' USING ERRCODE = '23514'; END IF; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java index ac1740309d..8db53d7fda 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java @@ -179,6 +179,28 @@ public static CompleteLaunchBindingEvidence fromCompleteResponse( } } + /** + * Decodes an already correlated immutable descriptor/attestation pair from another owner read. + */ + public static CompleteLaunchBindingEvidence fromCompleteEvidenceMessages( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, + LaunchDescriptor descriptor, + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence + releaseAttestation) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(releaseAttestation, "releaseAttestation"); + AuthoredWorldLaunchDescriptorEvidence decodedDescriptor = + decodeDescriptor(expectedRequest, descriptor); + AuthoredWorldReleaseAttestationEvidence decodedRelease = + decodeReleaseAttestation(releaseAttestation); + try { + return new CompleteLaunchBindingEvidence(decodedDescriptor, decodedRelease); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Complete launch binding evidence is invalid", invalid); + } + } + /** Encodes and revalidates the exact immutable descriptor and release-attestation pair. */ public static GetCompleteLaunchBindingResponse toCompleteResponse( GetLaunchDescriptorRequest request, CompleteLaunchBindingEvidence evidence) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java new file mode 100644 index 0000000000..0e7e1e3aed --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java @@ -0,0 +1,374 @@ +package net.firedevops.firemud.common.gamesession; + +import java.io.IOException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import tools.jackson.databind.json.JsonMapper; + +/** + * Read-only historical evidence for one exact original StartSession attempt. + * + *

This carrier proves only the retained original tuple, attached Account projection, first + * association selection, and descriptor/release binding. It does not represent a current owner + * claim, authorization, lease, terminal outcome, hold, or admission decision. + */ +public final class HistoricalOriginalStartSessionOwnerEvidence { + public static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private HistoricalOriginalStartSessionOwnerEvidence() {} + + /** Exact retained launch selector plus the actual original owner attempt and fence. */ + public record Request( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request associationSelector, + UUID expectedOwnerAttemptId, + long expectedOwnerFence) { + public Request { + Objects.requireNonNull(associationSelector, "associationSelector"); + requireNonNil(expectedOwnerAttemptId, "expectedOwnerAttemptId"); + if (expectedOwnerFence <= 0L) { + throw new IllegalArgumentException("expectedOwnerFence must be positive"); + } + } + } + + /** Immutable association row projection. Mutable Game Instance state is intentionally absent. */ + public record LaunchAssociation( + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID gameInstanceUuid, + String controlPlaneRequestId, + String launchDescriptorId, + UUID playableStateNamespaceId, + RealmEntryPolicy.StateScope playableStateScope, + boolean publicProduction, + long capturedStartingRowVersion, + CompleteLaunchBindingEvidence launchBindingEvidence) { + public LaunchAssociation { + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(gameInstanceUuid, "gameInstanceUuid"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + Objects.requireNonNull(launchBindingEvidence, "launchBindingEvidence"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireText(launchDescriptorId, "launchDescriptorId", 128); + if (playableStateScope != RealmEntryPolicy.StateScope.SHARED || !publicProduction) { + throw new IllegalArgumentException( + "Historical StartSession association must retain public SHARED state"); + } + if (capturedStartingRowVersion < 0L) { + throw new IllegalArgumentException("capturedStartingRowVersion must not be negative"); + } + AuthoredWorldLaunchDescriptorEvidence descriptor = launchBindingEvidence.descriptor(); + descriptor.requireValid(); + launchBindingEvidence.releaseAttestation().requireValid(descriptor); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId())) { + throw new IllegalArgumentException( + "Historical launch association differs from its complete descriptor binding"); + } + } + } + + /** + * Complete immutable readback. The projection bytes are the exact retained Account projection; + * accessors return copies to keep the carrier immutable. + */ + public static final class Result { + private final Request request; + private final StartSessionPostAuthorizationExecutionTuple originalTuple; + private final UUID ownerAttemptId; + private final long ownerFence; + private final byte[] accountRedemptionProjection; + private final StartSessionTemplateAssociationReadEvidence.Result firstSelection; + private final StartSessionLaunchDescriptorGrpcCodec.Resolved descriptorPin; + private final LaunchAssociation launchAssociation; + private final String templateAssociationRequestDigest; + private final String templateAssociationResponseDigest; + private final String descriptorPinRequestDigest; + private final String descriptorPinResponseDigest; + + public Result( + Request request, + StartSessionPostAuthorizationExecutionTuple originalTuple, + UUID ownerAttemptId, + long ownerFence, + byte[] accountRedemptionProjection, + StartSessionTemplateAssociationReadEvidence.Result firstSelection, + StartSessionLaunchDescriptorGrpcCodec.Resolved descriptorPin, + LaunchAssociation launchAssociation, + String templateAssociationRequestDigest, + String templateAssociationResponseDigest, + String descriptorPinRequestDigest, + String descriptorPinResponseDigest) { + this.request = Objects.requireNonNull(request, "request"); + this.originalTuple = Objects.requireNonNull(originalTuple, "originalTuple"); + this.ownerAttemptId = requireNonNil(ownerAttemptId, "ownerAttemptId"); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + this.ownerFence = ownerFence; + this.accountRedemptionProjection = + Objects.requireNonNull(accountRedemptionProjection, "accountRedemptionProjection") + .clone(); + this.firstSelection = Objects.requireNonNull(firstSelection, "firstSelection"); + this.descriptorPin = Objects.requireNonNull(descriptorPin, "descriptorPin"); + this.launchAssociation = Objects.requireNonNull(launchAssociation, "launchAssociation"); + this.templateAssociationRequestDigest = + requireDigest(templateAssociationRequestDigest, "templateAssociationRequestDigest"); + this.templateAssociationResponseDigest = + requireDigest(templateAssociationResponseDigest, "templateAssociationResponseDigest"); + this.descriptorPinRequestDigest = + requireDigest(descriptorPinRequestDigest, "descriptorPinRequestDigest"); + this.descriptorPinResponseDigest = + requireDigest(descriptorPinResponseDigest, "descriptorPinResponseDigest"); + requireCoherentEvidence(); + requirePinDigests(); + } + + public Request request() { + return request; + } + + public StartSessionPostAuthorizationExecutionTuple originalTuple() { + return originalTuple; + } + + public UUID ownerAttemptId() { + return ownerAttemptId; + } + + public long ownerFence() { + return ownerFence; + } + + public byte[] accountRedemptionProjection() { + return accountRedemptionProjection.clone(); + } + + public StartSessionTemplateAssociationReadEvidence.Result firstSelection() { + return firstSelection; + } + + public StartSessionLaunchDescriptorGrpcCodec.Resolved descriptorPin() { + return descriptorPin; + } + + public LaunchAssociation launchAssociation() { + return launchAssociation; + } + + public String templateAssociationRequestDigest() { + return templateAssociationRequestDigest; + } + + public String templateAssociationResponseDigest() { + return templateAssociationResponseDigest; + } + + public String descriptorPinRequestDigest() { + return descriptorPinRequestDigest; + } + + public String descriptorPinResponseDigest() { + return descriptorPinResponseDigest; + } + + private void requireCoherentEvidence() { + var selector = request.associationSelector(); + var action = originalTuple.preAuthorizationTuple().action(); + byte[] tupleBytes = originalTuple.canonicalBytes(); + if (!Arrays.equals( + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes).canonicalBytes(), + tupleBytes) + || !selector.targetNamespace().equals(action.scope().targetNamespace()) + || !selector.canonicalTenantId().equals(action.scope().tenantId()) + || !selector.controlPlaneRequestId().equals(originalTuple.controlPlaneRequestId()) + || !selector.gameInstanceUuid().equals(launchAssociation.gameInstanceUuid()) + || !selector.targetNamespace().equals(launchAssociation.targetNamespace()) + || !selector.canonicalTenantId().equals(launchAssociation.canonicalTenantId()) + || !selector.worldSlug().equals(launchAssociation.worldSlug()) + || !selector.controlPlaneRequestId().equals(launchAssociation.controlPlaneRequestId()) + || !selector.launchDescriptorId().equals(launchAssociation.launchDescriptorId()) + || !request.expectedOwnerAttemptId().equals(ownerAttemptId) + || request.expectedOwnerFence() != ownerFence + || !expectedAccountProjection(originalTuple).equalsBytes(accountRedemptionProjection)) { + throw new IllegalArgumentException( + "Historical StartSession tuple, projection, attempt, or association selector differs"); + } + + var selectionRequest = firstSelection.request(); + if (selectionRequest.schemaVersion() + != StartSessionTemplateAssociationReadEvidence.SCHEMA_VERSION + || !selector.targetNamespace().equals(selectionRequest.targetNamespace()) + || !Arrays.equals(selectionRequest.canonicalPostAuthorizationTuple(), tupleBytes) + || !ownerAttemptId.equals(selectionRequest.ownerAttemptId()) + || ownerFence != selectionRequest.ownerFence() + || !(selectionRequest.selection() + instanceof StartSessionTemplateAssociationReadEvidence.InitialConfigured) + || !selector.canonicalTenantId().equals(firstSelection.association().canonicalTenantId()) + || action.target().gameTemplateId() != firstSelection.association().templateId() + || !selector.worldSlug().equals(firstSelection.association().worldSlug())) { + throw new IllegalArgumentException( + "Historical first selection differs from the complete original StartSession tuple"); + } + + var descriptorRequest = descriptorPin.associationRead().request(); + var firstAssociation = firstSelection.association(); + boolean exactReplay = + descriptorRequest.selection() + instanceof StartSessionTemplateAssociationReadEvidence.ExactReplay replay + && replay.canonicalVersionId().equals(firstAssociation.canonicalVersionId()) + && replay.selectedCommitId().equals(firstAssociation.selectedCommitId()) + && replay.publishWorkflowId().equals(firstAssociation.publishWorkflowId()) + && replay.associationDigest().equals(firstAssociation.associationDigest()); + if (!exactReplay + || !selector.targetNamespace().equals(descriptorRequest.targetNamespace()) + || !Arrays.equals(descriptorRequest.canonicalPostAuthorizationTuple(), tupleBytes) + || !ownerAttemptId.equals(descriptorRequest.ownerAttemptId()) + || ownerFence != descriptorRequest.ownerFence() + || !(descriptorPin.outcome() + instanceof StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome outcome) + || !outcome.descriptor().equals(launchAssociation.launchBindingEvidence().descriptor())) { + throw new IllegalArgumentException( + "Historical descriptor pin differs from the immutable first selection or launch binding"); + } + + AuthoredWorldLaunchDescriptorEvidence descriptor = + launchAssociation.launchBindingEvidence().descriptor(); + var releaseAttestation = launchAssociation.launchBindingEvidence().releaseAttestation(); + if (!selector.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !selector.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !selector + .expectedReleaseAttestationEvidenceDigest() + .equals(releaseAttestation.evidenceDigest())) { + throw new IllegalArgumentException( + "Historical descriptor or release attestation differs from its exact selector"); + } + } + + private void requirePinDigests() { + var associationRequest = firstSelection.request(); + var associationRequestWire = + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .toRequest(associationRequest) + .toByteArray(); + var associationResponseWire = + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .toResponse(firstSelection) + .toByteArray(); + var descriptorRequest = descriptorPin.associationRead().request(); + var descriptorRequestWire = + StartSessionLaunchDescriptorGrpcCodec.toRequest(descriptorRequest).toByteArray(); + var descriptorResponseWire = + StartSessionLaunchDescriptorGrpcCodec.toResponse( + descriptorRequest, descriptorPin.associationRead(), descriptorPin.outcome()) + .toByteArray(); + if (!templateAssociationRequestDigest.equals(sha256(associationRequestWire)) + || !templateAssociationResponseDigest.equals(sha256(associationResponseWire)) + || !descriptorPinRequestDigest.equals(sha256(descriptorRequestWire)) + || !descriptorPinResponseDigest.equals(sha256(descriptorResponseWire))) { + throw new IllegalArgumentException( + "Historical StartSession pin digests differ from their canonical retained evidence"); + } + } + } + + private record ExpectedProjection(byte[] bytes) { + private boolean equalsBytes(byte[] candidate) { + return Arrays.equals(bytes, candidate); + } + } + + private static ExpectedProjection expectedAccountProjection( + StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + long issuanceFence; + try { + issuanceFence = Long.parseLong(tuple.issuanceFence()); + } catch (NumberFormatException malformed) { + throw new IllegalArgumentException( + "Historical Account issuance fence is malformed", malformed); + } + if (issuanceFence <= 0L) { + throw new IllegalArgumentException("Historical Account projection identity is malformed"); + } + Map projection = + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + issuanceFence); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + return new ExpectedProjection(bytes); + } catch (IOException malformed) { + throw new IllegalStateException( + "Could not encode the retained Account projection", malformed); + } + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + return value; + } + + private static void requireText(String value, String name, int maxLength) { + Objects.requireNonNull(value, name); + if (value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(name + " must be non-blank and bounded"); + } + } + + private static String requireDigest(String value, String name) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + return value; + } + + public static String sha256(byte[] value) { + Objects.requireNonNull(value, "value"); + try { + return "sha256:" + + HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.java new file mode 100644 index 0000000000..3a24731d41 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.java @@ -0,0 +1,278 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Request; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Result; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceRequest; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceResponse; + +/** Closed request and response mapping for historical original StartSession evidence. */ +public final class HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec() {} + + public static ReadHistoricalOriginalStartSessionOwnerEvidenceRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var selector = request.associationSelector(); + return ReadHistoricalOriginalStartSessionOwnerEvidenceRequest.newBuilder() + .setSchemaVersion(HistoricalOriginalStartSessionOwnerEvidence.SCHEMA_VERSION) + .setReadRequestId(selector.readRequestId().toString()) + .setTargetNamespace(selector.targetNamespace()) + .setCanonicalTenantId(selector.canonicalTenantId().toString()) + .setWorldSlug(selector.worldSlug()) + .setGameInstanceUuid(selector.gameInstanceUuid().toString()) + .setControlPlaneRequestId(selector.controlPlaneRequestId()) + .setLaunchDescriptorId(selector.launchDescriptorId()) + .setExpectedDescriptorRequestDigest(selector.expectedDescriptorRequestDigest()) + .setExpectedDescriptorResultDigest(selector.expectedDescriptorResultDigest()) + .setExpectedReleaseAttestationEvidenceDigest( + selector.expectedReleaseAttestationEvidenceDigest()) + .setExpectedOwnerAttemptId(request.expectedOwnerAttemptId().toString()) + .setExpectedOwnerFence(request.expectedOwnerFence()) + .build(); + } + + /** Decodes only the closed exact-selector request; decoding does not authenticate its caller. */ + public static Request fromRequest( + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadHistoricalOriginalStartSessionOwnerEvidenceRequest"); + if (request.getSchemaVersion() != HistoricalOriginalStartSessionOwnerEvidence.SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported historical StartSession read schema"); + } + try { + var selector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + parseUuid(request.getReadRequestId(), "readRequestId"), + request.getTargetNamespace(), + parseUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseUuid(request.getGameInstanceUuid(), "gameInstanceUuid"), + request.getControlPlaneRequestId(), + request.getLaunchDescriptorId(), + request.getExpectedDescriptorRequestDigest(), + request.getExpectedDescriptorResultDigest(), + request.getExpectedReleaseAttestationEvidenceDigest()); + Request decoded = + new Request( + selector, + parseUuid(request.getExpectedOwnerAttemptId(), "expectedOwnerAttemptId"), + request.getExpectedOwnerFence()); + if (!toRequest(decoded).equals(request)) { + throw new IllegalArgumentException("Historical StartSession request is not canonical"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Canonical historical original StartSession evidence request required", malformed); + } + } + + public static ReadHistoricalOriginalStartSessionOwnerEvidenceResponse toResponse(Result result) { + Objects.requireNonNull(result, "result"); + var association = result.launchAssociation(); + CompleteLaunchBindingEvidence binding = association.launchBindingEvidence(); + var descriptor = binding.descriptor(); + var attestation = binding.releaseAttestation(); + var associationRead = result.firstSelection(); + var descriptorPin = result.descriptorPin(); + var descriptorRequest = descriptorPin.associationRead().request(); + return ReadHistoricalOriginalStartSessionOwnerEvidenceResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setCanonicalPostAuthorizationTuple( + com.google.protobuf.ByteString.copyFrom(result.originalTuple().canonicalBytes())) + .setOwnerAttemptId(result.ownerAttemptId().toString()) + .setOwnerFence(result.ownerFence()) + .setAccountRedemptionProjection( + com.google.protobuf.ByteString.copyFrom(result.accountRedemptionProjection())) + .setTemplateAssociationRequest( + StartSessionTemplateAssociationReadGrpcCodec.toRequest(associationRead.request())) + .setTemplateAssociationResponse( + StartSessionTemplateAssociationReadGrpcCodec.toResponse(associationRead)) + .setTemplateAssociationRequestDigest(result.templateAssociationRequestDigest()) + .setTemplateAssociationResponseDigest(result.templateAssociationResponseDigest()) + .setDescriptorPinResponse( + StartSessionLaunchDescriptorGrpcCodec.toResponse( + descriptorRequest, descriptorPin.associationRead(), descriptorPin.outcome())) + .setDescriptorPinRequestDigest(result.descriptorPinRequestDigest()) + .setDescriptorPinResponseDigest(result.descriptorPinResponseDigest()) + .setPlayableStateNamespaceId(association.playableStateNamespaceId().toString()) + .setPlayableStateScope(association.playableStateScope().name()) + .setPublicProduction(association.publicProduction()) + .setCapturedStartingRowVersion(association.capturedStartingRowVersion()) + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptor)) + .setReleaseAttestation( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(attestation)) + .setAssociationTargetNamespace(association.targetNamespace()) + .setAssociationCanonicalTenantId(association.canonicalTenantId().toString()) + .setAssociationWorldSlug(association.worldSlug()) + .setAssociationGameInstanceUuid(association.gameInstanceUuid().toString()) + .setAssociationControlPlaneRequestId(association.controlPlaneRequestId()) + .setAssociationLaunchDescriptorId(association.launchDescriptorId()) + .build(); + } + + /** Validates the exact request echo, original pins, projection, and immutable launch binding. */ + public static Result fromResponse( + Request expectedRequest, ReadHistoricalOriginalStartSessionOwnerEvidenceResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadHistoricalOriginalStartSessionOwnerEvidenceResponse"); + if (!response.hasRequest() + || !response.hasTemplateAssociationRequest() + || !response.hasTemplateAssociationResponse() + || !response.hasDescriptorPinResponse() + || !response.hasLaunchDescriptor() + || !response.hasReleaseAttestation()) { + throw new IllegalArgumentException( + "Complete historical original StartSession evidence required"); + } + + Request echoed = fromRequest(response.getRequest()); + if (!expectedRequest.equals(echoed)) { + throw new IllegalArgumentException( + "Game Session changed the exact historical read request echo"); + } + + byte[] tupleBytes = response.getCanonicalPostAuthorizationTuple().toByteArray(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (!java.util.Arrays.equals(tuple.canonicalBytes(), tupleBytes)) { + throw new IllegalArgumentException("Historical original StartSession tuple is not canonical"); + } + + var firstRequest = + StartSessionTemplateAssociationReadGrpcCodec.fromRequest( + response.getTemplateAssociationRequest()); + var firstSelection = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + firstRequest, response.getTemplateAssociationResponse()); + var selector = expectedRequest.associationSelector(); + if (!(firstRequest.selection() + instanceof StartSessionTemplateAssociationReadEvidence.InitialConfigured) + || !selector.targetNamespace().equals(firstRequest.targetNamespace()) + || !java.util.Arrays.equals(firstRequest.canonicalPostAuthorizationTuple(), tupleBytes) + || !expectedRequest.expectedOwnerAttemptId().equals(firstRequest.ownerAttemptId()) + || expectedRequest.expectedOwnerFence() != firstRequest.ownerFence()) { + throw new IllegalArgumentException( + "Historical first selection differs from its exact original attempt and tuple"); + } + + var pinnedAssociation = firstSelection.association(); + var originalSelectionRequest = firstSelection.request(); + var exactReplayRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + originalSelectionRequest.schemaVersion(), + originalSelectionRequest.targetNamespace(), + originalSelectionRequest.readRequestId(), + originalSelectionRequest.canonicalPostAuthorizationTuple(), + originalSelectionRequest.ownerAttemptId(), + originalSelectionRequest.ownerFence(), + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + pinnedAssociation.canonicalVersionId(), + pinnedAssociation.selectedCommitId(), + pinnedAssociation.publishWorkflowId(), + pinnedAssociation.associationDigest())); + var descriptorPin = + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + exactReplayRequest, response.getDescriptorPinResponse()); + + if (!(descriptorPin.outcome() + instanceof StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome descriptorOutcome)) { + throw new IllegalArgumentException( + "Historical StartSession descriptor pin has no descriptor"); + } + AuthoredWorldLaunchDescriptorEvidence.Request expectedDescriptorRequest = + descriptorOutcome.descriptor().request(); + CompleteLaunchBindingEvidence launchBinding = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteEvidenceMessages( + expectedDescriptorRequest, + response.getLaunchDescriptor(), + response.getReleaseAttestation()); + + RealmEntryPolicy.StateScope stateScope; + try { + stateScope = RealmEntryPolicy.StateScope.valueOf(response.getPlayableStateScope()); + } catch (RuntimeException invalidScope) { + throw new IllegalArgumentException( + "Historical playable-state scope is malformed", invalidScope); + } + LaunchAssociation launchAssociation = + new LaunchAssociation( + response.getAssociationTargetNamespace(), + parseUuid(response.getAssociationCanonicalTenantId(), "associationCanonicalTenantId"), + response.getAssociationWorldSlug(), + parseUuid(response.getAssociationGameInstanceUuid(), "associationGameInstanceUuid"), + response.getAssociationControlPlaneRequestId(), + response.getAssociationLaunchDescriptorId(), + parseUuid(response.getPlayableStateNamespaceId(), "playableStateNamespaceId"), + stateScope, + response.getPublicProduction(), + response.getCapturedStartingRowVersion(), + launchBinding); + + Result result = + new Result( + expectedRequest, + tuple, + parseUuid(response.getOwnerAttemptId(), "ownerAttemptId"), + response.getOwnerFence(), + response.getAccountRedemptionProjection().toByteArray(), + firstSelection, + descriptorPin, + launchAssociation, + response.getTemplateAssociationRequestDigest(), + response.getTemplateAssociationResponseDigest(), + response.getDescriptorPinRequestDigest(), + response.getDescriptorPinResponseDigest()); + if (!toResponse(result).equals(response)) { + throw new IllegalArgumentException( + "Historical original StartSession response is not canonical"); + } + return result; + } + + private static UUID parseUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, field)); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) continue; + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java new file mode 100644 index 0000000000..b4603bd61e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClient.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.common.gamesession; + +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.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Request; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Result; +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.gamesession.v1.HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for the unregistered historical Game Session evidence read. */ +public final class HistoricalOriginalStartSessionOwnerEvidenceReadClient + extends AbstractReloadingBlockingGrpcClient< + HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc + .HistoricalOriginalStartSessionOwnerEvidenceReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final int MAX_INBOUND_MESSAGE_BYTES = 16 * 1024 * 1024; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public HistoricalOriginalStartSessionOwnerEvidenceReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when a consuming owner explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Historical StartSession evidence client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Historical StartSession evidence client has no gRPC stub"); + } + initialized = true; + } + + /** + * Reads immutable evidence outside any owner transaction; the result is not execution authority. + */ + public Result read(Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Historical StartSession evidence read requires no ambient owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.associationSelector().targetNamespace())) { + throw new IllegalArgumentException( + "Historical StartSession request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readHistoricalOriginalStartSessionOwnerEvidence( + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request)); + try { + return HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Session returned invalid historical original StartSession evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc + .HistoricalOriginalStartSessionOwnerEvidenceReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + return HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(MAX_INBOUND_MESSAGE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc + .HistoricalOriginalStartSessionOwnerEvidenceReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Historical StartSession evidence client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Historical StartSession evidence reads require 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( + "Historical StartSession evidence reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Historical StartSession evidence reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Historical StartSession " + label + " must be a readable file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Historical StartSession " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java new file mode 100644 index 0000000000..4054a7c985 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java @@ -0,0 +1,148 @@ +package net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Request; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceResponse; +import org.junit.jupiter.api.Test; + +class HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest { + private static final String NAMESPACE = "gameplay"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID GAME_INSTANCE = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID READ_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID ATTEMPT_ID = uuid("44444444-4444-4444-8444-444444444444"); + + @Test + void requestRoundTripsExactAssociationSelectorAndOriginalAttemptFence() { + Request request = request(); + var wire = HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request); + + assertThat(HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(wire)) + .isEqualTo(request); + } + + @Test + void requestRejectsUnknownFieldsUnsupportedSchemaAndNonPositiveFence() { + var wire = HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request()); + var unknown = + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var unsupported = wire.toBuilder().setSchemaVersion(2).build(); + var noFence = wire.toBuilder().setExpectedOwnerFence(0L).build(); + + assertThatThrownBy( + () -> HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "ReadHistoricalOriginalStartSessionOwnerEvidenceRequest contains unsupported fields"); + assertThatThrownBy( + () -> HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(unsupported)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("schema"); + assertThatThrownBy( + () -> HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(noFence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "Canonical historical original StartSession evidence request required") + .hasRootCauseMessage("expectedOwnerFence must be positive"); + } + + @Test + void responseRequiresTheExactRequestEchoBeforeDecodingEvidence() { + Request request = request(); + var changedEcho = + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request).toBuilder() + .setExpectedOwnerFence(request.expectedOwnerFence() + 1L) + .build(); + var response = + ReadHistoricalOriginalStartSessionOwnerEvidenceResponse.newBuilder() + .setRequest(changedEcho) + .setTemplateAssociationRequest( + net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest + .getDefaultInstance()) + .setTemplateAssociationResponse( + net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse + .getDefaultInstance()) + .setDescriptorPinResponse( + net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse + .getDefaultInstance()) + .setLaunchDescriptor( + net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.getDefaultInstance()) + .setReleaseAttestation( + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence + .getDefaultInstance()) + .build(); + + assertThatThrownBy( + () -> + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse( + request, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("request echo"); + } + + @Test + void responseRejectsUnknownNestedPinFields() { + var request = HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(request()); + var response = + ReadHistoricalOriginalStartSessionOwnerEvidenceResponse.newBuilder() + .setRequest(request) + .setTemplateAssociationRequest( + net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest + .newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .setTemplateAssociationResponse( + net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse + .getDefaultInstance()) + .setDescriptorPinResponse( + net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse + .getDefaultInstance()) + .setLaunchDescriptor( + net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.getDefaultInstance()) + .setReleaseAttestation( + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence + .getDefaultInstance()) + .build(); + + assertThatThrownBy( + () -> + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse( + request(), response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining( + "ReadHistoricalOriginalStartSessionOwnerEvidenceResponse.template_association_request contains unsupported fields"); + } + + private static Request request() { + return new Request( + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + READ_ID, + NAMESPACE, + TENANT, + "world", + GAME_INSTANCE, + "start-request-1", + "launch-descriptor-1", + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)), + ATTEMPT_ID, + 17L); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java new file mode 100644 index 0000000000..59ecb44f01 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceReadClientTest.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.common.gamesession; + +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.io.IOException; +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.gamesession.HistoricalOriginalStartSessionOwnerEvidence.Request; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class HistoricalOriginalStartSessionOwnerEvidenceReadClientTest { + private static final String NAMESPACE = "gameplay"; + + private HistoricalOriginalStartSessionOwnerEvidenceReadClient client; + + @AfterEach + void closeClientAndClearTransactionContext() throws Exception { + if (client != null) { + client.close(); + client = null; + } + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresFileBackedMtlsAndDoesNotInitializeOrReadWithoutExplicitInit(@TempDir Path dir) + throws Exception { + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = fileBackedMtls(dir); + plaintext.setPlaintext(true); + org.assertj.core.api.Assertions.assertThatThrownBy(() -> newClient(plaintext, factory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + client = newClient(fileBackedMtls(dir), factory); + assertThatThrownBy(() -> client.read(request(NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.read(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request(NAMESPACE))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + verifyNoInteractions(factory); + } + + @Test + void initializesOnlyTheConfiguredGameSessionTargetWithFileBackedMtls(@TempDir Path dir) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("game-session.internal:6565"); + CommonGrpcClientProperties tls = fileBackedMtls(dir); + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(factory.buildChannel( + eq("game-session.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + client = + new HistoricalOriginalStartSessionOwnerEvidenceReadClient( + endpoints, tls, factory, NAMESPACE); + + client.init(); + + verify(factory) + .buildChannel( + eq("game-session.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } + + private HistoricalOriginalStartSessionOwnerEvidenceReadClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory factory) { + return new HistoricalOriginalStartSessionOwnerEvidenceReadClient( + new ServiceEndpointsProperties(), tls, factory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws IOException { + 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; + } + + private static Request request(String namespace) { + return new Request( + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + namespace, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "start-session-request", + "launch-descriptor", + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + 9L); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java index 7011b84675..22c263e434 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java @@ -64,7 +64,8 @@ public List findNonterminal(int limit) { "SELECT " + SELECT_COLUMNS + " FROM initial_admission_bind_hold WHERE status IN " - + "('PENDING', 'RECONCILIATION_REQUIRED') ORDER BY updated_at, hold_id LIMIT ?", + + "('PENDING', 'RECONCILIATION_REQUIRED') " + + "AND canonical_request_bytes IS NULL ORDER BY updated_at, hold_id LIMIT ?", Math.max(1, Math.min(limit, 256))); return rows.map(this::toEntity); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldCanonicalInitialAdmissionHoldReconciler.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldCanonicalInitialAdmissionHoldReconciler.java new file mode 100644 index 0000000000..8410377a34 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldCanonicalInitialAdmissionHoldReconciler.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldFinalizationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldRepository; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicit, unregistered bounded restart reconciliation for canonical World admission holds. + * + *

This class has no Spring component or scheduling annotation. Its caller chooses when to invoke + * the next page; each page advances its in-memory keyset cursor before processing rows so one + * unavailable or malformed owner proof cannot starve later candidates. + */ +public final class WorldCanonicalInitialAdmissionHoldReconciler { + public static final int DEFAULT_PAGE_SIZE = 64; + + private final WorldCanonicalInitialAdmissionHoldRepository holdRepository; + private final WorldCanonicalInitialAdmissionHoldFinalizationService finalizationService; + private final String targetNamespace; + private final AtomicReference + cursor = new AtomicReference<>(); + + public WorldCanonicalInitialAdmissionHoldReconciler( + WorldCanonicalInitialAdmissionHoldRepository holdRepository, + WorldCanonicalInitialAdmissionHoldFinalizationService finalizationService, + String targetNamespace) { + this.holdRepository = Objects.requireNonNull(holdRepository, "holdRepository"); + this.finalizationService = Objects.requireNonNull(finalizationService, "finalizationService"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + this.targetNamespace = targetNamespace; + } + + /** + * Processes at most one bounded page. Invoke again while {@code endOfPass} is false; an empty + * page resets the keyset so later invocations begin a new fair pass. + */ + public PageResult reconcileNextPage() { + return reconcileNextPage(DEFAULT_PAGE_SIZE); + } + + /** Same as {@link #reconcileNextPage()}, with a caller-selected but capped page size. */ + public PageResult reconcileNextPage(int requestedPageSize) { + requireNoAmbientTransaction(); + int pageSize = Math.max(1, Math.min(requestedPageSize, 256)); + WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCursor after = cursor.get(); + List page = + holdRepository.findReconciliationCandidates(targetNamespace, after, pageSize); + if (page.isEmpty()) { + cursor.compareAndSet(after, null); + return new PageResult(0, 0, 0, List.of(), List.of(), true); + } + + advanceCursor(page.getLast().cursor()); + int terminalized = 0; + int pending = 0; + List unresolved = new ArrayList<>(); + List reconciliationRequired = new ArrayList<>(); + for (WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCandidateReference ref : page) { + try { + Optional candidate = + holdRepository.readReconciliationCandidate(targetNamespace, ref.holdId()); + if (candidate.isEmpty()) continue; + + WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCandidate exact = + candidate.orElseThrow(); + if (exact.status() + == WorldCanonicalInitialAdmissionHoldState.HoldStatus.RECONCILIATION_REQUIRED) { + reconciliationRequired.add(ref.holdId()); + continue; + } + if (exact.status() != WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING) { + unresolved.add(ref.holdId()); + continue; + } + + Optional result = + finalizationService.observeAndFinalizeHold(exact.identity()); + if (result.isPresent()) terminalized++; + else pending++; + } catch (RuntimeException unavailableOrInconsistent) { + unresolved.add(ref.holdId()); + } + } + return new PageResult( + page.size(), terminalized, pending, unresolved, reconciliationRequired, false); + } + + private void advanceCursor( + WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCursor next) { + cursor.updateAndGet(current -> current == null || compare(next, current) > 0 ? next : current); + } + + private static int compare( + WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCursor left, + WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCursor right) { + int updated = left.updatedAt().compareTo(right.updatedAt()); + if (updated != 0) return updated; + int mostSignificant = + Long.compareUnsigned( + left.holdId().getMostSignificantBits(), right.holdId().getMostSignificantBits()); + return mostSignificant != 0 + ? mostSignificant + : Long.compareUnsigned( + left.holdId().getLeastSignificantBits(), right.holdId().getLeastSignificantBits()); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World canonical initial-admission reconciliation must start outside an ambient transaction"); + } + } + + /** Counts and row keys only; uncertainty is reported without fabricating a hold transition. */ + public record PageResult( + int scanned, + int terminalized, + int stillPending, + List unresolvedHoldIds, + List reconciliationRequiredHoldIds, + boolean endOfPass) { + public PageResult { + unresolvedHoldIds = List.copyOf(unresolvedHoldIds); + reconciliationRequiredHoldIds = List.copyOf(reconciliationRequiredHoldIds); + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClient.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClient.java index 51ce1523b5..530f86f225 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClient.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClient.java @@ -83,6 +83,24 @@ public HeldOwnerProof verifyAndHold( if (expectedOutcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { throw denied("PENDING is not a terminal owner-proof selection"); } + HeldOwnerProof held = verifyAndHoldObserved(expectedIdentity); + try { + if (held.proof().outcome() != expectedOutcome) { + throw denied("Game Session returned no proof for the exact requested terminal outcome"); + } + held.requireHeld(); + return held; + } catch (RuntimeException mismatch) { + held.close(); + throw mismatch; + } + } + + /** Reads the actual persisted state for the explicit bounded World restart reconciler. */ + @Override + public HeldOwnerProof verifyAndHoldObserved(HoldIdentity expectedIdentity) { + Objects.requireNonNull(expectedIdentity, "expectedIdentity"); + requireNoAmbientTransaction(); if (!workloadNamespace.equals(expectedIdentity.request().targetNamespace())) { throw denied("Canonical Game Session owner read must use the configured workload namespace"); } @@ -100,7 +118,7 @@ public HeldOwnerProof verifyAndHold( try { proof = GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.fromResponse( - expectedIdentity, expectedOutcome, response); + expectedIdentity, response); } catch (IllegalArgumentException invalid) { throw denied("Game Session returned invalid canonical initial-admission owner proof"); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.java index 3e023275c8..215bf99142 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.java @@ -54,10 +54,21 @@ public static GameSessionCanonicalInitialAdmissionOwnerProof fromResponse( GetCanonicalInitialAdmissionOwnerProofResponse response) { Objects.requireNonNull(expectedIdentity, "expectedIdentity"); Objects.requireNonNull(expectedOutcome, "expectedOutcome"); - Objects.requireNonNull(response, "response"); if (expectedOutcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { throw invalid("PENDING is not a terminal owner-proof selection"); } + GameSessionCanonicalInitialAdmissionOwnerProof proof = fromResponse(expectedIdentity, response); + if (proof.outcome() != expectedOutcome) { + throw invalid("Game Session returned no proof for the exact requested terminal outcome"); + } + return proof; + } + + /** Decodes the actual producer outcome, including an exact nonterminal PENDING observation. */ + public static GameSessionCanonicalInitialAdmissionOwnerProof fromResponse( + HoldIdentity expectedIdentity, GetCanonicalInitialAdmissionOwnerProofResponse response) { + Objects.requireNonNull(expectedIdentity, "expectedIdentity"); + Objects.requireNonNull(response, "response"); if (!response.getUnknownFields().asMap().isEmpty()) { throw invalid("Game Session owner proof response contains unknown fields"); } @@ -65,15 +76,22 @@ public static GameSessionCanonicalInitialAdmissionOwnerProof fromResponse( requireExactIdentityEcho(expectedIdentity, response); GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome = fromWireOutcome(response.getOutcome()); - if (outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING - || outcome != expectedOutcome) { - throw invalid("Game Session returned no proof for the exact requested terminal outcome"); - } Long committedPointerVersion = response.hasCommittedPointerVersion() ? response.getCommittedPointerVersion() : null; Long auditEventId = response.hasAuditEventId() ? response.getAuditEventId() : null; - if (outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + Instant terminalAt = null; + String proofDigest = response.getProofDigest().isEmpty() ? null : response.getProofDigest(); + if (outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + if (committedPointerVersion != null + || auditEventId != null + || proofDigest != null + || response.getPositiveDurableAbort() + || response.hasTerminalAt()) { + throw invalid("PENDING owner observation cannot carry terminal proof fields"); + } + terminalAt = null; + } else if (outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { if (committedPointerVersion == null || auditEventId == null) { throw invalid("COMMITTED owner proof requires pointer and audit fields"); } @@ -87,7 +105,9 @@ public static GameSessionCanonicalInitialAdmissionOwnerProof fromResponse( throw invalid("ABORTED owner proof requires positive fencing without commit fields"); } - Instant terminalAt = toInstant(response); + if (outcome != GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + terminalAt = toInstant(response); + } try { GameSessionCanonicalInitialAdmissionOwnerProof proof = new GameSessionCanonicalInitialAdmissionOwnerProof( @@ -95,7 +115,7 @@ public static GameSessionCanonicalInitialAdmissionOwnerProof fromResponse( outcome, committedPointerVersion, auditEventId, - response.getProofDigest(), + proofDigest, response.getPositiveDurableAbort(), terminalAt); return GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationService.java index 88e861e0b5..b51f21744a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationService.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.worldmanagement.tenant; import java.util.Objects; +import java.util.Optional; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -55,6 +56,41 @@ public GameSessionCanonicalInitialAdmissionOwnerProof finalizeHold( } } + /** + * Reads the actual exact Game Session outcome for restart reconciliation. PENDING is a successful + * read but leaves World unchanged; only authenticated terminal proof reaches the existing + * serialized finalizer. + */ + public Optional observeAndFinalizeHold( + HoldIdentity expectedIdentity) { + Objects.requireNonNull(expectedIdentity, "expectedIdentity"); + requireNoAmbientTransaction(); + + HeldOwnerProof held = + Objects.requireNonNull( + verifier.verifyAndHoldObserved(expectedIdentity), + "Game Session owner proof verifier returned no held proof"); + try { + GameSessionCanonicalInitialAdmissionOwnerProof proof = + Objects.requireNonNull(held.proof(), "held owner proof"); + held.requireHeld(); + if (!expectedIdentity.equals(proof.holdIdentity())) { + throw denied("Game Session owner proof differs from the exact requested hold"); + } + if (proof.outcome() == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + return Optional.empty(); + } + + requireExactProof(expectedIdentity, proof.outcome(), proof); + GameSessionCanonicalInitialAdmissionOwnerProof stored = + repository.finalizeTerminal(expectedIdentity, proof, held); + held.requireHeld(); + return Optional.of(stored); + } finally { + held.close(); + } + } + /** Explicit fail-closed verifier for configurations that have no authenticated GS adapter. */ public static OwnerProofVerifier denyAllVerifier() { return (identity, outcome) -> { @@ -114,6 +150,12 @@ public interface OwnerProofVerifier { HeldOwnerProof verifyAndHold( HoldIdentity expectedIdentity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome expectedOutcome); + + /** Actual-outcome lookup used only by the explicit World restart reconciler. */ + default HeldOwnerProof verifyAndHoldObserved(HoldIdentity expectedIdentity) { + throw denied( + "Authenticated Game Session canonical initial-admission outcome read is unavailable"); + } } /** A verified exact owner outcome held valid until the enclosing World commit returns. */ diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java index 0dc777282a..4653f3b887 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java @@ -1,10 +1,16 @@ package net.firedevops.firemud.worldmanagement.tenant; import java.sql.Connection; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.Arrays; +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.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; @@ -12,6 +18,7 @@ import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.Result; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -253,6 +260,118 @@ public Optional readState( })); } + /** + * Finds a bounded keyset page of typed nonterminal holds for one namespace. This is only a + * candidate scan: callers must independently re-read each candidate before contacting its Game + * Session owner. Diagnostic expiry is deliberately not part of the predicate. + */ + public List findReconciliationCandidates( + String targetNamespace, ReconciliationCursor after, int limit) { + requireNamespace(targetNamespace); + requireNoAmbientTransaction("World canonical initial-admission reconciliation scan"); + int boundedLimit = Math.max(1, Math.min(limit, 256)); + return readTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + String query = + "SELECT hold_id, updated_at FROM initial_admission_bind_hold " + + "WHERE canonical_request_bytes IS NOT NULL " + + "AND canonical_target_namespace = ? " + + "AND status IN ('PENDING', 'RECONCILIATION_REQUIRED') "; + Result rows; + if (after == null) { + rows = + dsl.fetch( + query + "ORDER BY updated_at, hold_id LIMIT ?", targetNamespace, boundedLimit); + } else { + rows = + dsl.fetch( + query + + "AND (updated_at, hold_id) > (?::timestamp, ?::uuid) " + + "ORDER BY updated_at, hold_id LIMIT ?", + targetNamespace, + LocalDateTime.ofInstant(after.updatedAt(), ZoneOffset.UTC), + after.holdId(), + boundedLimit); + } + List candidates = new ArrayList<>(rows.size()); + for (Record row : rows) { + UUID holdId = required(row, "hold_id", UUID.class); + LocalDateTime updatedAt = required(row, "updated_at", LocalDateTime.class); + candidates.add( + new ReconciliationCandidateReference( + holdId, new ReconciliationCursor(updatedAt.toInstant(ZoneOffset.UTC), holdId))); + } + return List.copyOf(candidates); + }); + } + + /** + * Re-reads one scanned hold and verifies its complete immutable typed identity against the + * persisted owner association in a separate read-only snapshot. A concurrent terminalization + * makes the candidate empty; malformed or detached typed evidence fails closed for that row. + */ + public Optional readReconciliationCandidate( + String targetNamespace, UUID holdId) { + requireNamespace(targetNamespace); + Objects.requireNonNull(holdId, "holdId"); + requireNoAmbientTransaction("World canonical initial-admission reconciliation candidate read"); + return Optional.ofNullable( + readTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + Record row = + dsl.fetchOne( + HOLD_STATE_SELECT + + "WHERE hold_id = ?::uuid AND canonical_target_namespace = ? " + + "AND canonical_request_bytes IS NOT NULL " + + "AND status IN ('PENDING', 'RECONCILIATION_REQUIRED')", + holdId, + targetNamespace); + if (row == null) return null; + + Request request = readRequest(row); + if (!targetNamespace.equals(request.targetNamespace())) { + throw new InvalidHoldIdentityException( + "Canonical World hold candidate differs from the scanned namespace"); + } + WorldCanonicalInstanceAssociation association; + try { + association = + associationRepository + .readOwnerAssociationInOwnerTransaction(request.canonicalGameInstanceId()) + .orElseThrow( + () -> + new InvalidHoldIdentityException( + "Canonical World hold exists without its required persisted association")); + requireAssociationMatchesRequest(request, association); + } catch ( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException + inconsistent) { + throw new InvalidHoldIdentityException( + "Canonical World hold association is incomplete or inconsistent", inconsistent); + } + HoldIdentity identity = verifyStoredIdentity(row, request, association); + WorldCanonicalInitialAdmissionHoldState.HoldStatus holdStatus; + try { + holdStatus = + WorldCanonicalInitialAdmissionHoldState.HoldStatus.valueOf( + required(row, "status", String.class)); + } catch (RuntimeException invalid) { + throw new InvalidHoldIdentityException( + "Persisted canonical World initial-admission hold status is missing or invalid", + invalid); + } + return new ReconciliationCandidate(identity, holdStatus); + })); + } + + private static void requireNamespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); + } + } + private int insert( Request request, WorldCanonicalInstanceAssociation.WorldPrepareFields privateKeys, @@ -301,6 +420,15 @@ private int insert( return inserted; } + private static Request readRequest(Record row) { + try { + return Request.fromStored(required(row, "canonical_request_bytes", byte[].class)); + } catch (RuntimeException invalid) { + throw new InvalidHoldIdentityException( + "Persisted canonical World initial-admission request is incomplete or invalid", invalid); + } + } + private Record readByOwnerRequest(long privateTenantKey, Request request) { return dsl.fetchOne( HOLD_SELECT + "WHERE tenant_id = ? AND initial_admission_request_id = ?", @@ -483,6 +611,36 @@ private static T required(Record row, String column, Class type) { return Objects.requireNonNull(row.get(column, type), "Persisted " + column + " is null"); } + /** Keyset cursor ordered by the persisted reconciliation index. */ + public record ReconciliationCursor(Instant updatedAt, UUID holdId) { + public ReconciliationCursor { + Objects.requireNonNull(updatedAt, "updatedAt"); + Objects.requireNonNull(holdId, "holdId"); + } + } + + /** + * Candidate scan result; it carries no authority beyond the immutable row key and sort cursor. + */ + public record ReconciliationCandidateReference(UUID holdId, ReconciliationCursor cursor) { + public ReconciliationCandidateReference { + Objects.requireNonNull(holdId, "holdId"); + Objects.requireNonNull(cursor, "cursor"); + if (!holdId.equals(cursor.holdId())) { + throw new IllegalArgumentException("Candidate key differs from its reconciliation cursor"); + } + } + } + + /** Exact immutable candidate re-read, including its current stored status. */ + public record ReconciliationCandidate( + HoldIdentity identity, WorldCanonicalInitialAdmissionHoldState.HoldStatus status) { + public ReconciliationCandidate { + Objects.requireNonNull(identity, "identity"); + Objects.requireNonNull(status, "status"); + } + } + public static final class HoldConflictException extends IllegalStateException { public HoldConflictException(String message) { super(message); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java new file mode 100644 index 0000000000..bd3bebf787 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java @@ -0,0 +1,973 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadClient; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidenceReadClient; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService.PreparationDeniedException; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Authenticates exact historical Account and Game Session evidence for read-only World recovery. + * + *

This unregistered verifier performs only owner reads. It does not refresh original authority, + * reacquire participation, authorize a new preparation, or infer a World terminal outcome. + */ +public final class WorldCanonicalInstanceOriginalOperationRecoveryVerifier + implements OriginalOperationRecoveryVerifier { + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private final AccountStartSessionWorldParticipationHistoricalReadClient accountClient; + private final HistoricalOriginalStartSessionOwnerEvidenceReadClient gameSessionClient; + + public WorldCanonicalInstanceOriginalOperationRecoveryVerifier( + AccountStartSessionWorldParticipationHistoricalReadClient accountClient, + HistoricalOriginalStartSessionOwnerEvidenceReadClient gameSessionClient) { + this.accountClient = Objects.requireNonNull(accountClient, "accountClient"); + this.gameSessionClient = Objects.requireNonNull(gameSessionClient, "gameSessionClient"); + } + + @Override + public void verifyOriginalOperation(WorldCanonicalInstanceExecutionIdentity identity) { + Objects.requireNonNull(identity, "original World execution identity is required"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Historical StartSession recovery must authenticate outside an ambient transaction"); + } + + final RetainedPreparation retained; + try { + retained = RetainedPreparation.parse(identity.preparationInputJson()); + requireIdentityMatches(identity, retained); + } catch (PreparationDeniedException denied) { + throw denied; + } catch (IllegalArgumentException | ArithmeticException malformed) { + throw denied("Retained World StartSession identity is malformed", malformed); + } + + UUID accountReadId = + freshReadId( + identity.accountWorldParticipationId(), + identity.gameSessionOwnerAttemptId(), + identity.canonicalGameInstanceId()); + AccountStartSessionWorldParticipationHistoricalReadRequest accountRequest = + new AccountStartSessionWorldParticipationHistoricalReadRequest( + accountReadId, + identity.targetNamespace(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence()); + AccountStartSessionWorldParticipationHistoricalReadEvidence accountEvidence = + accountClient.read(accountRequest); + if (accountEvidence == null) { + throw denied("Account returned no historical participation evidence"); + } + requireAccountEvidence(identity, accountRequest, accountEvidence); + + HistoricalOriginalStartSessionOwnerEvidence.Request gameSessionRequest = + retained.gameSessionRequest(identity); + HistoricalOriginalStartSessionOwnerEvidence.Result gameSessionEvidence = + gameSessionClient.read(gameSessionRequest); + if (gameSessionEvidence == null) { + throw denied("Game Session returned no historical original-operation evidence"); + } + requireGameSessionEvidence(identity, retained, gameSessionRequest, gameSessionEvidence); + } + + private static void requireIdentityMatches( + WorldCanonicalInstanceExecutionIdentity identity, RetainedPreparation retained) { + JsonNode savedIdentity = retained.identity(); + if (!identity.canonicalGameInstanceId().equals(uuid(savedIdentity, "canonicalGameInstanceId")) + || !identity.targetNamespace().equals(text(savedIdentity, "targetNamespace")) + || !identity.canonicalTenantId().equals(uuid(savedIdentity, "canonicalTenantId")) + || !identity.controlPlaneRequestId().equals(text(savedIdentity, "controlPlaneRequestId"))) { + throw denied("Retained World preparation identity differs from its exact execution identity"); + } + String input = identity.preparationInputJson(); + if (!identity.preparationInputDigest().equals(digest(input.getBytes(StandardCharsets.UTF_8)))) { + throw denied("World preparation input digest differs from its exact retained bytes"); + } + retained.requireCrossOwnerReadSelectors(); + } + + private static void requireAccountEvidence( + WorldCanonicalInstanceExecutionIdentity identity, + AccountStartSessionWorldParticipationHistoricalReadRequest expectedRequest, + AccountStartSessionWorldParticipationHistoricalReadEvidence actual) { + if (!expectedRequest.equals(actual.request()) + || !Arrays.equals( + identity.originalPostAuthorizationTuple(), actual.originalPostAuthorizationTuple()) + || !identity.gameSessionOwnerAttemptId().equals(actual.gameSessionOwnerAttemptId()) + || identity.gameSessionOwnerFence() != actual.gameSessionOwnerFence() + || !identity.canonicalGameInstanceId().equals(actual.canonicalGameInstanceId()) + || !identity.preparationInputJson().equals(actual.preparationInputJson()) + || !identity.preparationInputDigest().equals(actual.preparationInputDigest())) { + throw denied( + "Account historical participation differs from the complete original World execution tuple"); + } + } + + private static void requireGameSessionEvidence( + WorldCanonicalInstanceExecutionIdentity identity, + RetainedPreparation retained, + HistoricalOriginalStartSessionOwnerEvidence.Request expectedRequest, + HistoricalOriginalStartSessionOwnerEvidence.Result actual) { + if (!expectedRequest.equals(actual.request()) + || !Arrays.equals( + identity.originalPostAuthorizationTuple(), actual.originalTuple().canonicalBytes()) + || !identity.gameSessionOwnerAttemptId().equals(actual.ownerAttemptId()) + || identity.gameSessionOwnerFence() != actual.ownerFence()) { + throw denied( + "Game Session historical evidence differs from the exact original tuple or owner attempt"); + } + + HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation association = + actual.launchAssociation(); + JsonNode savedIdentity = retained.identity(); + if (!identity.targetNamespace().equals(association.targetNamespace()) + || !identity.canonicalTenantId().equals(association.canonicalTenantId()) + || !text(savedIdentity, "worldSlug").equals(association.worldSlug()) + || !identity.canonicalGameInstanceId().equals(association.gameInstanceUuid()) + || !identity.controlPlaneRequestId().equals(association.controlPlaneRequestId()) + || !text(retained.gameSessionReadEvidence(), "launchDescriptorId") + .equals(association.launchDescriptorId()) + || descriptorTemplateId(association) != identity.gameTemplateId() + || actual.firstSelection().association().templateId() != identity.gameTemplateId() + || !uuid(savedIdentity, "playableStateNamespaceId") + .equals(association.playableStateNamespaceId()) + || !RealmEntryPolicy.StateScope.SHARED.equals(association.playableStateScope()) + || !bool(savedIdentity, "publicProduction") + || !association.publicProduction()) { + throw denied("Game Session launch association differs from the retained World identity"); + } + + CompleteLaunchBindingEvidence launchBinding = association.launchBindingEvidence(); + AuthoredWorldLaunchDescriptorEvidence descriptor = launchBinding.descriptor(); + var release = launchBinding.releaseAttestation(); + requireFirstSelectionMatches(identity, retained, actual, release); + if (!retained.sameJsonValue( + retained.gameSessionReadEvidence().get("descriptorJson"), descriptor) + || !retained.sameJsonValue( + retained.gameSessionReadEvidence().get("releaseAttestationJson"), release)) { + throw denied( + "Game Session descriptor or release attestation differs from the exact retained preparation input"); + } + retained.requireLaunchBindingAndSource(descriptor, release); + } + + private static void requireFirstSelectionMatches( + WorldCanonicalInstanceExecutionIdentity identity, + RetainedPreparation retained, + HistoricalOriginalStartSessionOwnerEvidence.Result actual, + net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence release) { + var firstSelection = actual.firstSelection().association(); + if (!identity.targetNamespace().equals(firstSelection.targetNamespace()) + || !identity.canonicalTenantId().equals(firstSelection.canonicalTenantId()) + || identity.gameTemplateId() != firstSelection.templateId() + || !text(retained.identity(), "worldSlug").equals(firstSelection.worldSlug()) + || !uuid(retained.launchBinding, "canonicalVersionId") + .equals(firstSelection.canonicalVersionId()) + || !release.commitId().equals(firstSelection.selectedCommitId().toString()) + || !release.publishWorkflowId().equals(firstSelection.publishWorkflowId()) + || !uuid(retained.sourceIntake, "sourceOperationId") + .equals(firstSelection.sourceOperationId()) + || !text(retained.sourceIntake, "sourceEvidenceDigest") + .equals(firstSelection.sourceEvidenceDigest())) { + throw denied( + "Game Session first-selection pin differs from the exact retained World release and source"); + } + } + + private static long descriptorTemplateId( + HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation association) { + return association.launchBindingEvidence().descriptor().gameTemplateId(); + } + + private static UUID freshReadId(UUID... excluded) { + while (true) { + UUID candidate = UUID.randomUUID(); + if (NIL_UUID.equals(candidate)) continue; + boolean matches = false; + for (UUID value : excluded) matches |= candidate.equals(value); + if (!matches) return candidate; + } + } + + private static String text(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isTextual() || value.asText().isBlank()) { + throw denied("Historical World preparation field is missing or malformed: " + field); + } + return value.asText(); + } + + private static UUID uuid(JsonNode object, String field) { + String value = text(object, field); + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("UUID is not canonical and non-nil"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw denied("Historical World preparation UUID is malformed: " + field, malformed); + } + } + + private static boolean bool(JsonNode object, String field) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isBoolean()) { + throw denied("Historical World preparation field is missing or malformed: " + field); + } + return value.booleanValue(); + } + + private static long number(JsonNode object, String field, boolean positive) { + JsonNode value = object == null ? null : object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw denied("Historical World preparation field is missing or malformed: " + field); + } + long parsed = value.longValue(); + if (positive ? parsed <= 0L : parsed < 0L) { + throw denied("Historical World preparation number is outside its allowed range: " + field); + } + return parsed; + } + + private static void fields(JsonNode object, String label, String... names) { + if (object == null || !object.isObject() || object.size() != names.length) { + throw denied("Historical World preparation object is incomplete or open: " + label); + } + for (String name : names) { + if (!object.has(name)) { + throw denied("Historical World preparation object is missing " + label + "." + name); + } + } + } + + private static void digestText(JsonNode object, String field) { + if (!SHA256.matcher(text(object, field)).matches()) { + throw denied("Historical World preparation digest is malformed: " + field); + } + } + + private static void rawDigestText(JsonNode object, String field) { + if (!text(object, field).matches("[0-9a-f]{64}")) { + throw denied("Historical World preparation digest is malformed: " + field); + } + } + + private static PreparationDeniedException denied(String message) { + return new PreparationDeniedException(message); + } + + private static PreparationDeniedException denied(String message, Throwable cause) { + PreparationDeniedException denied = new PreparationDeniedException(message); + denied.initCause(cause); + return denied; + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private record RetainedPreparation( + int schemaVersion, + JsonNode identity, + JsonNode gameSessionReadRequest, + JsonNode gameSessionReadEvidence, + JsonNode launchBinding, + JsonNode versionIdentity, + JsonNode sourceIntake, + JsonNode topology, + String worldStartLocationEvidenceBase64) { + static RetainedPreparation parse(String preparationInputJson) { + if (preparationInputJson == null + || preparationInputJson.isBlank() + || preparationInputJson.getBytes(StandardCharsets.UTF_8).length + > net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal + .MAX_CANONICAL_BYTES) { + throw denied("Exact retained World preparation input is missing or oversized"); + } + final JsonNode root; + try { + root = JSON.readTree(preparationInputJson); + } catch (JacksonException malformed) { + throw denied("Exact retained World preparation input is not strict JSON", malformed); + } + if (root == null || !root.isObject()) { + throw denied("Exact retained World preparation input must be an object"); + } + int schemaVersion = Math.toIntExact(number(root, "schemaVersion", true)); + if (schemaVersion != 1 && schemaVersion != 2) { + throw denied("Unsupported retained World preparation input schema"); + } + if (schemaVersion == 1) { + fields( + root, + "root", + "schemaVersion", + "identity", + "gameSessionReadRequest", + "gameSessionReadEvidence", + "launchBinding", + "versionIdentity", + "sourceIntake", + "topology"); + } else { + fields( + root, + "root", + "schemaVersion", + "identity", + "gameSessionReadRequest", + "gameSessionReadEvidence", + "launchBinding", + "versionIdentity", + "sourceIntake", + "topology", + "worldStartLocationEvidenceBase64"); + } + String selector = null; + if (schemaVersion == 2) { + if (root.size() != 9 || !root.has("worldStartLocationEvidenceBase64")) { + throw denied("Schema-2 World preparation input requires its start-location evidence"); + } + selector = text(root, "worldStartLocationEvidenceBase64"); + try { + byte[] decoded = Base64.getDecoder().decode(selector); + if (decoded.length == 0 + || !Base64.getEncoder().encodeToString(decoded).equals(selector)) { + throw new IllegalArgumentException("selector base64 is not canonical"); + } + } catch (IllegalArgumentException malformed) { + throw denied("Retained World start-location evidence is malformed", malformed); + } + } else if (root.size() != 8) { + throw denied("Schema-1 World preparation input has an unsupported root shape"); + } + + JsonNode identity = root.get("identity"); + fields( + identity, + "identity", + "canonicalGameInstanceId", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "playableStateNamespaceId", + "playableStateScope", + "publicProduction", + "controlPlaneRequestId"); + uuid(identity, "canonicalGameInstanceId"); + uuid(identity, "canonicalTenantId"); + uuid(identity, "playableStateNamespaceId"); + text(identity, "targetNamespace"); + text(identity, "worldSlug"); + text(identity, "playableStateScope"); + text(identity, "controlPlaneRequestId"); + bool(identity, "publicProduction"); + + JsonNode request = root.get("gameSessionReadRequest"); + fields( + request, + "gameSessionReadRequest", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "canonicalGameInstanceId", + "controlPlaneRequestId", + "launchDescriptorId", + "expectedDescriptorRequestDigest", + "expectedDescriptorResultDigest", + "expectedReleaseAttestationEvidenceDigest"); + JsonNode evidence = root.get("gameSessionReadEvidence"); + fields( + evidence, + "gameSessionReadEvidence", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "canonicalGameInstanceId", + "controlPlaneRequestId", + "launchDescriptorId", + "descriptorRequestDigest", + "descriptorResultDigest", + "releaseAttestationEvidenceDigest", + "playableStateNamespaceId", + "playableStateScope", + "publicProduction", + "descriptorJson", + "releaseAttestationJson"); + for (String field : new String[] {"canonicalTenantId", "canonicalGameInstanceId"}) { + uuid(request, field); + uuid(evidence, field); + } + uuid(evidence, "playableStateNamespaceId"); + for (String field : + new String[] { + "targetNamespace", + "worldSlug", + "controlPlaneRequestId", + "launchDescriptorId", + "expectedDescriptorRequestDigest", + "expectedDescriptorResultDigest", + "expectedReleaseAttestationEvidenceDigest" + }) { + text(request, field); + } + for (String field : + new String[] { + "targetNamespace", + "worldSlug", + "controlPlaneRequestId", + "launchDescriptorId", + "playableStateScope" + }) { + text(evidence, field); + } + for (String field : + new String[] { + "expectedDescriptorRequestDigest", + "expectedDescriptorResultDigest", + "expectedReleaseAttestationEvidenceDigest" + }) { + digestText(request, field); + } + for (String field : + new String[] { + "descriptorRequestDigest", "descriptorResultDigest", "releaseAttestationEvidenceDigest" + }) { + digestText(evidence, field); + } + bool(evidence, "publicProduction"); + parseEvidenceJson(text(evidence, "descriptorJson"), "descriptorJson"); + parseEvidenceJson(text(evidence, "releaseAttestationJson"), "releaseAttestationJson"); + + JsonNode launch = root.get("launchBinding"); + fields( + launch, + "launchBinding", + "schemaVersion", + "operationId", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "controlPlaneRequestId", + "descriptorRequestDigest", + "descriptorResultDigest", + "releaseAttestationDigest", + "canonicalVersionId", + "localTenantKey", + "intakeOperationId", + "intakeRequestId", + "sourceOperationId", + "sourceEvidenceDigest", + "intakeRequestDigest", + "intakeReceiptDigest"); + number(launch, "schemaVersion", true); + for (String field : + new String[] { + "operationId", + "canonicalTenantId", + "canonicalVersionId", + "intakeOperationId", + "intakeRequestId", + "sourceOperationId" + }) { + uuid(launch, field); + } + for (String field : new String[] {"targetNamespace", "worldSlug", "controlPlaneRequestId"}) { + text(launch, field); + } + number(launch, "localTenantKey", true); + for (String field : + new String[] { + "descriptorRequestDigest", "descriptorResultDigest", "releaseAttestationDigest", + "sourceEvidenceDigest", "intakeRequestDigest", "intakeReceiptDigest" + }) { + digestText(launch, field); + } + + JsonNode version = root.get("versionIdentity"); + fields( + version, + "versionIdentity", + "schemaVersion", + "operationId", + "canonicalVersionId", + "localVersionKey", + "gameDesignVersionId", + "versionState", + "versionStateEpoch", + "evidenceDigest"); + number(version, "schemaVersion", true); + uuid(version, "operationId"); + uuid(version, "canonicalVersionId"); + number(version, "localVersionKey", true); + number(version, "gameDesignVersionId", true); + number(version, "versionStateEpoch", true); + if (!Set.of( + "VERSION_LIFECYCLE_STATE_DRAFT", + "VERSION_LIFECYCLE_STATE_PUBLISHED", + "VERSION_LIFECYCLE_STATE_ACTIVE") + .contains(text(version, "versionState"))) { + throw denied("Retained World version state is not supported"); + } + digestText(version, "evidenceDigest"); + + JsonNode source = root.get("sourceIntake"); + fields( + source, + "sourceIntake", + "schemaVersion", + "targetNamespace", + "intakeRequestId", + "operationId", + "canonicalTenantId", + "worldSlug", + "sourceOperationId", + "sourceEvidenceDigest", + "requestDigest", + "receiptDigest", + "localTenantKey", + "sourceEvidence"); + number(source, "schemaVersion", true); + for (String field : + new String[] { + "intakeRequestId", "operationId", "canonicalTenantId", "sourceOperationId" + }) { + uuid(source, field); + } + text(source, "targetNamespace"); + text(source, "worldSlug"); + number(source, "localTenantKey", true); + for (String field : new String[] {"sourceEvidenceDigest", "requestDigest", "receiptDigest"}) { + digestText(source, field); + } + JsonNode sourceEvidence = source.get("sourceEvidence"); + fields( + sourceEvidence, + "sourceIntake.sourceEvidence", + "schemaVersion", + "registrationRequestId", + "sourceOperationId", + "requestDigest", + "canonicalTenantId", + "tenantSlug", + "worldSlug", + "worldDisplayName", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + number(sourceEvidence, "schemaVersion", true); + for (String field : + new String[] {"registrationRequestId", "sourceOperationId", "canonicalTenantId"}) { + uuid(sourceEvidence, field); + } + for (String field : + new String[] { + "requestDigest", + "tenantSlug", + "worldSlug", + "worldDisplayName", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest" + }) { + text(sourceEvidence, field); + } + number(sourceEvidence, "sourceGameRowId", true); + + JsonNode topology = root.get("topology"); + fields( + topology, + "topology", + "captureId", + "targetNamespace", + "canonicalTenantId", + "canonicalVersionId", + "versionIdentityOperationId", + "requestId", + "commitId", + "freezeRequestId", + "publicationFence", + "publicationRequestDigest", + "appliedCommitId", + "planDigest", + "regionCount", + "zoneCount", + "roomCount", + "exitCount", + "generationRuleCount", + "spawnBindingCount"); + for (String field : + new String[] { + "captureId", + "canonicalTenantId", + "canonicalVersionId", + "versionIdentityOperationId", + "requestId", + "commitId" + }) { + uuid(topology, field); + } + for (String field : new String[] {"targetNamespace", "freezeRequestId", "appliedCommitId"}) { + text(topology, field); + } + uuid(topology, "publicationFence"); + rawDigestText(topology, "publicationRequestDigest"); + digestText(topology, "planDigest"); + number(topology, "regionCount", true); + for (String field : + new String[] { + "zoneCount", "roomCount", "exitCount", "generationRuleCount", "spawnBindingCount" + }) { + number(topology, field, false); + } + if (number(topology, "generationRuleCount", false) != 0L + || number(topology, "spawnBindingCount", false) != 0L) { + throw denied("Retained World preparation input contains unsupported generation intent"); + } + + return new RetainedPreparation( + schemaVersion, identity, request, evidence, launch, version, source, topology, selector); + } + + HistoricalOriginalStartSessionOwnerEvidence.Request gameSessionRequest( + WorldCanonicalInstanceExecutionIdentity identity) { + String namespace = text(gameSessionReadEvidence, "targetNamespace"); + UUID tenant = uuid(gameSessionReadEvidence, "canonicalTenantId"); + UUID gameInstance = uuid(gameSessionReadEvidence, "canonicalGameInstanceId"); + UUID readId = + freshReadId( + identity.accountWorldParticipationId(), + identity.gameSessionOwnerAttemptId(), + gameInstance); + var selector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + readId, + namespace, + tenant, + text(gameSessionReadEvidence, "worldSlug"), + gameInstance, + text(gameSessionReadEvidence, "controlPlaneRequestId"), + text(gameSessionReadEvidence, "launchDescriptorId"), + text(gameSessionReadEvidence, "descriptorRequestDigest"), + text(gameSessionReadEvidence, "descriptorResultDigest"), + text(gameSessionReadEvidence, "releaseAttestationEvidenceDigest")); + return new HistoricalOriginalStartSessionOwnerEvidence.Request( + selector, identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence()); + } + + void requireCrossOwnerReadSelectors() { + for (String field : + new String[] { + "targetNamespace", "worldSlug", "controlPlaneRequestId", "launchDescriptorId" + }) { + if (!text(gameSessionReadRequest, field).equals(text(gameSessionReadEvidence, field))) { + throw denied("Retained Game Session request and evidence differ at " + field); + } + } + if (!uuid(gameSessionReadRequest, "canonicalTenantId") + .equals(uuid(gameSessionReadEvidence, "canonicalTenantId")) + || !uuid(gameSessionReadRequest, "canonicalGameInstanceId") + .equals(uuid(gameSessionReadEvidence, "canonicalGameInstanceId")) + || !text(gameSessionReadRequest, "expectedDescriptorRequestDigest") + .equals(text(gameSessionReadEvidence, "descriptorRequestDigest")) + || !text(gameSessionReadRequest, "expectedDescriptorResultDigest") + .equals(text(gameSessionReadEvidence, "descriptorResultDigest")) + || !text(gameSessionReadRequest, "expectedReleaseAttestationEvidenceDigest") + .equals(text(gameSessionReadEvidence, "releaseAttestationEvidenceDigest"))) { + throw denied("Retained Game Session selector differs from its exact response projection"); + } + for (String field : + new String[] { + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "canonicalGameInstanceId", + "controlPlaneRequestId" + }) { + String identityValue = + field.startsWith("canonical") + ? uuid(this.identity, field).toString() + : text(this.identity, field); + String requestValue = + field.startsWith("canonical") + ? uuid(gameSessionReadRequest, field).toString() + : text(gameSessionReadRequest, field); + if (!identityValue.equals(requestValue)) { + throw denied("Retained World identity differs from Game Session selector at " + field); + } + } + if (!uuid(this.identity, "playableStateNamespaceId") + .equals(uuid(gameSessionReadEvidence, "playableStateNamespaceId")) + || !text(this.identity, "playableStateScope") + .equals(text(gameSessionReadEvidence, "playableStateScope")) + || bool(this.identity, "publicProduction") + != bool(gameSessionReadEvidence, "publicProduction")) { + throw denied("Retained World state namespace differs from Game Session evidence"); + } + + if (number(launchBinding, "schemaVersion", true) != 1L + || number(versionIdentity, "schemaVersion", true) != 1L + || number(sourceIntake, "schemaVersion", true) != 1L) { + throw denied("Unsupported World preparation subdocument schema"); + } + JsonNode sourceEvidence = requiredSourceEvidence(); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + Math.toIntExact(number(sourceEvidence, "schemaVersion", true)), + text(sourceIntake, "targetNamespace"), + uuid(sourceEvidence, "registrationRequestId"), + uuid(sourceEvidence, "sourceOperationId"), + text(sourceEvidence, "requestDigest"), + uuid(sourceEvidence, "canonicalTenantId"), + text(sourceEvidence, "tenantSlug"), + text(sourceEvidence, "worldSlug"), + text(sourceEvidence, "worldDisplayName"), + number(sourceEvidence, "sourceGameRowId", true), + text(sourceEvidence, "sourceGameTenantKey"), + text(sourceEvidence, "provenanceKind"), + text(sourceEvidence, "evidenceDigest")); + WorldAuthoredSourceIntakeReceipt receipt = + new WorldAuthoredSourceIntakeReceipt( + Math.toIntExact(number(sourceIntake, "schemaVersion", true)), + text(sourceIntake, "targetNamespace"), + uuid(sourceIntake, "intakeRequestId"), + uuid(sourceIntake, "operationId"), + uuid(sourceIntake, "canonicalTenantId"), + text(sourceIntake, "worldSlug"), + uuid(sourceIntake, "sourceOperationId"), + text(sourceIntake, "sourceEvidenceDigest"), + text(sourceIntake, "requestDigest"), + text(sourceIntake, "receiptDigest"), + number(sourceIntake, "localTenantKey", true), + source); + + UUID versionId = uuid(versionIdentity, "canonicalVersionId"); + if (!versionId.equals(uuid(launchBinding, "canonicalVersionId")) + || !versionId.equals(uuid(topology, "canonicalVersionId")) + || !uuid(versionIdentity, "operationId") + .equals(uuid(topology, "versionIdentityOperationId"))) { + throw denied("Retained World version identity differs from its frozen topology"); + } + if (!uuid(versionIdentity, "operationId").equals(uuid(topology, "versionIdentityOperationId")) + || !text(this.identity, "targetNamespace").equals(text(topology, "targetNamespace")) + || !uuid(this.identity, "canonicalTenantId").equals(uuid(topology, "canonicalTenantId")) + || !text(identity, "canonicalGameInstanceId") + .equals(text(gameSessionReadRequest, "canonicalGameInstanceId"))) { + throw denied("Retained World topology identity is inconsistent"); + } + if (!uuid(sourceIntake, "canonicalTenantId").equals(uuid(this.identity, "canonicalTenantId")) + || !text(sourceIntake, "targetNamespace").equals(text(this.identity, "targetNamespace")) + || !text(sourceIntake, "worldSlug").equals(text(identity, "worldSlug"))) { + throw denied("Retained authored-source intake differs from the World target"); + } + if (!uuid(launchBinding, "intakeOperationId").equals(receipt.operationId()) + || !uuid(launchBinding, "intakeRequestId").equals(receipt.intakeRequestId()) + || !uuid(launchBinding, "sourceOperationId").equals(receipt.sourceOperationId()) + || !text(launchBinding, "sourceEvidenceDigest").equals(receipt.sourceEvidenceDigest()) + || !text(launchBinding, "intakeRequestDigest").equals(receipt.requestDigest()) + || !text(launchBinding, "intakeReceiptDigest").equals(receipt.receiptDigest()) + || number(launchBinding, "localTenantKey", true) != receipt.localTenantKey()) { + throw denied("Retained launch binding differs from its exact World source-intake receipt"); + } + if (!uuid(sourceEvidence, "sourceOperationId").equals(receipt.sourceOperationId()) + || !text(sourceEvidence, "evidenceDigest").equals(receipt.sourceEvidenceDigest()) + || !uuid(sourceEvidence, "canonicalTenantId").equals(receipt.canonicalTenantId()) + || !text(sourceEvidence, "worldSlug").equals(receipt.worldSlug())) { + throw denied("Retained authored source evidence differs from its intake receipt"); + } + } + + void requireLaunchBindingAndSource( + AuthoredWorldLaunchDescriptorEvidence descriptor, + net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence release) { + try { + WorldAuthoredSourceIntakeReceipt receipt = sourceReceipt(); + CompleteLaunchBindingEvidence evidence = + new CompleteLaunchBindingEvidence(descriptor, release); + WorldCompleteLaunchBindingReceipt binding = + new WorldCompleteLaunchBindingReceipt( + Math.toIntExact(number(launchBinding, "schemaVersion", true)), + uuid(launchBinding, "operationId"), + text(launchBinding, "targetNamespace"), + uuid(launchBinding, "canonicalTenantId"), + text(launchBinding, "worldSlug"), + text(launchBinding, "controlPlaneRequestId"), + receipt, + evidence); + if (!descriptor.requestDigest().equals(text(launchBinding, "descriptorRequestDigest")) + || !descriptor.resultDigest().equals(text(launchBinding, "descriptorResultDigest")) + || !release.evidenceDigest().equals(text(launchBinding, "releaseAttestationDigest")) + || !release.canonicalVersionId().equals(uuid(launchBinding, "canonicalVersionId")) + || !release.canonicalVersionId().equals(uuid(versionIdentity, "canonicalVersionId")) + || !release.canonicalVersionId().equals(uuid(topology, "canonicalVersionId")) + || !release.commitId().equals(text(topology, "commitId")) + || !release.commitId().equals(text(topology, "appliedCommitId")) + || !binding.descriptor().equals(descriptor) + || !identityValuesMatch(descriptor, release)) { + throw denied("Retained complete launch binding differs from historical owner evidence"); + } + var worldParticipants = + release.participantDigests().stream() + .filter(participant -> "WORLD_MANAGEMENT".equals(participant.participantKey())) + .toList(); + if (worldParticipants.size() != 1 + || !worldParticipants + .getFirst() + .scopeValue() + .equals(Long.toString(number(versionIdentity, "gameDesignVersionId", true)))) { + throw denied("Historical release does not bind the retained World Version scope"); + } + var worldSelector = release.worldStartLocationEvidence(); + if (schemaVersion == 2) { + if (worldSelector == null + || !Base64.getEncoder() + .encodeToString(worldSelector.canonicalBytes()) + .equals(worldStartLocationEvidenceBase64)) { + throw denied("Historical release selector differs from the retained World input"); + } + } else if (worldSelector != null) { + throw denied("Schema-1 retained World input cannot match a selected release selector"); + } + } catch (PreparationDeniedException denied) { + throw denied; + } catch (IllegalArgumentException malformed) { + throw denied( + "Retained World launch, source, or version identity is inconsistent", malformed); + } + } + + private boolean identityValuesMatch( + AuthoredWorldLaunchDescriptorEvidence descriptor, + net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence release) { + return text(launchBinding, "targetNamespace").equals(descriptor.targetNamespace()) + && uuid(launchBinding, "canonicalTenantId").equals(descriptor.canonicalTenantId()) + && text(launchBinding, "worldSlug").equals(descriptor.worldSlug()) + && text(launchBinding, "controlPlaneRequestId").equals(descriptor.controlPlaneRequestId()) + && descriptor + .authoredWorldSourceOperationId() + .equals(uuid(sourceIntake, "sourceOperationId")) + && descriptor + .authoredWorldSourceEvidenceDigest() + .equals(text(sourceIntake, "sourceEvidenceDigest")) + && release + .authoredWorldSourceOperationId() + .equals(uuid(sourceIntake, "sourceOperationId")) + && release + .authoredWorldSourceEvidenceDigest() + .equals(text(sourceIntake, "sourceEvidenceDigest")) + && descriptor.canonicalTenantId().equals(uuid(identity, "canonicalTenantId")) + && descriptor.targetNamespace().equals(text(identity, "targetNamespace")) + && descriptor.worldSlug().equals(text(identity, "worldSlug")); + } + + private WorldAuthoredSourceIntakeReceipt sourceReceipt() { + JsonNode sourceEvidence = requiredSourceEvidence(); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + Math.toIntExact(number(sourceEvidence, "schemaVersion", true)), + text(sourceIntake, "targetNamespace"), + uuid(sourceEvidence, "registrationRequestId"), + uuid(sourceEvidence, "sourceOperationId"), + text(sourceEvidence, "requestDigest"), + uuid(sourceEvidence, "canonicalTenantId"), + text(sourceEvidence, "tenantSlug"), + text(sourceEvidence, "worldSlug"), + text(sourceEvidence, "worldDisplayName"), + number(sourceEvidence, "sourceGameRowId", true), + text(sourceEvidence, "sourceGameTenantKey"), + text(sourceEvidence, "provenanceKind"), + text(sourceEvidence, "evidenceDigest")); + return new WorldAuthoredSourceIntakeReceipt( + Math.toIntExact(number(sourceIntake, "schemaVersion", true)), + text(sourceIntake, "targetNamespace"), + uuid(sourceIntake, "intakeRequestId"), + uuid(sourceIntake, "operationId"), + uuid(sourceIntake, "canonicalTenantId"), + text(sourceIntake, "worldSlug"), + uuid(sourceIntake, "sourceOperationId"), + text(sourceIntake, "sourceEvidenceDigest"), + text(sourceIntake, "requestDigest"), + text(sourceIntake, "receiptDigest"), + number(sourceIntake, "localTenantKey", true), + source); + } + + private JsonNode requiredSourceEvidence() { + if (sourceIntake == null || !sourceIntake.isObject()) { + throw denied("Retained authored-source intake is missing"); + } + JsonNode sourceEvidence = sourceIntake.get("sourceEvidence"); + if (sourceEvidence == null || !sourceEvidence.isObject()) { + throw denied("Retained authored source evidence is missing"); + } + return sourceEvidence; + } + + boolean sameJsonValue(JsonNode expected, Object actual) { + if (expected == null || !expected.isTextual()) { + throw denied("Retained World evidence JSON must be stored as an exact JSON string"); + } + try { + JsonNode retained = parseEvidenceJson(expected.textValue(), "retained evidence"); + JsonNode observed = JSON.readTree(JSON.writeValueAsString(actual)); + return retained.equals(observed); + } catch (JacksonException malformed) { + throw denied( + "Historical Game Session evidence could not be encoded for exact comparison", + malformed); + } + } + + private static JsonNode parseEvidenceJson(String value, String label) { + try { + JsonNode node = JSON.readTree(value); + if (node == null || !node.isObject()) { + throw denied("Retained World " + label + " must be a JSON object"); + } + return node; + } catch (JacksonException malformed) { + throw denied("Retained World " + label + " is not strict JSON", malformed); + } + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java index 4347853fe3..f38a901ed3 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java @@ -10,12 +10,14 @@ /** * Unregistered, default-denied owner operation for a canonical generation-free world instance. * - *

No production verifier is supplied in this slice. A future authenticated integration must - * verify the same-namespace Game Session producer and exact current Game Design release/terminal - * source before the World transaction begins. The original Account-authorized APPLIED result is - * immutable input evidence; preparation must not reauthorize the creator or reuse Draft/publication + *

No fresh-execution verifier is wired in this slice. An authenticated integration must verify + * the same-namespace Game Session producer and exact current Game Design release/terminal source + * before the World transaction begins. The original Account-authorized APPLIED result is immutable + * input evidence; preparation must not reauthorize the creator or reuse Draft/publication * permission. Its held producer evidence must remain valid through commit. This class is - * deliberately not a Spring component and adds no RPC or public activation path. + * deliberately not a Spring component and adds no RPC or public activation path. The separate + * explicitly supplied historical recovery verifier reads retained Account and Game Session + * evidence; it supplies no held authority for another execution. */ public final class WorldCanonicalInstancePreparationService { private final WorldCanonicalInstancePreparationRepository repository; @@ -39,7 +41,7 @@ public WorldCanonicalInstancePreparationService( /** * Constructor for explicit fresh-execution and original-operation recovery verifiers. No - * production verifier is supplied in this slice. + * constructor registers or enables a runtime path. */ public WorldCanonicalInstancePreparationService( WorldCanonicalInstancePreparationRepository repository, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 6269704b30..2249dc9a9d 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -85,6 +85,7 @@ import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState; import net.firedevops.firemud.common.world.WorldCanonicalInitialPlayerLocation; import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; @@ -2338,6 +2339,147 @@ void canonicalInitialAdmissionHoldAcquiresFromRealActiveLifecycleAndRetainsPendi assertOrigin(); } + @Test + void canonicalHoldReconciliationUsesTypedBoundedPagesAndLegacyFinderExcludesTypedRows() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + // World lifecycle/association and hold storage are real; activation authority is stipulated. + var activation = + canonicalActivationService(fixture, ignored -> stipulatedActivationAuthority()) + .activate( + new WorldCanonicalInstanceActivation.Request( + UUID.randomUUID(), fixture.preparing())); + assertThat(activation.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + var active = + fixture + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(activation.lifecycleEvidence().request())) + .orElseThrow(); + + Request firstRequest = + canonicalReconciliationHoldRequest( + active, "canonical-reconcile-first-" + UUID.randomUUID(), "c".repeat(64)); + Request secondRequest = + canonicalReconciliationHoldRequest( + active, "canonical-reconcile-second-" + UUID.randomUUID(), "d".repeat(64)); + var repository = + new WorldCanonicalInitialAdmissionHoldRepository( + dsl, manager, associationRepository(), fixture.lifecycleRepository()); + HoldIdentity first = repository.acquire(firstRequest, active.request()); + HoldIdentity second = repository.acquire(secondRequest, active.request()); + + // A different valid namespace sees no rows from this real canonical namespace. + assertThat(repository.findReconciliationCandidates("otherworld", null, 8)).isEmpty(); + + var legacyRows = new InitialAdmissionBindHoldRepository(dsl).findNonterminal(256); + assertThat(legacyRows).hasSizeLessThan(256); + assertThat(legacyRows.stream().map(row -> row.holdId()).toList()) + .doesNotContain(first.holdId().toString(), second.holdId().toString()); + + List foundTypedHolds = new ArrayList<>(); + WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCursor after = null; + for (int pageNumber = 0; pageNumber < 256 && foundTypedHolds.size() < 2; pageNumber++) { + var page = + repository.findReconciliationCandidates(active.request().targetNamespace(), after, 1); + assertThat(page).hasSizeLessThanOrEqualTo(1); + if (page.isEmpty()) break; + + var reference = page.getFirst(); + after = reference.cursor(); + if (!reference.holdId().equals(first.holdId()) + && !reference.holdId().equals(second.holdId())) { + continue; + } + var exact = + repository + .readReconciliationCandidate(active.request().targetNamespace(), reference.holdId()) + .orElseThrow(); + assertThat(exact.status()) + .isIn( + WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, + WorldCanonicalInitialAdmissionHoldState.HoldStatus.RECONCILIATION_REQUIRED); + if (reference.holdId().equals(first.holdId())) { + assertThat(exact.identity().canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(exact.status()) + .isEqualTo(WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING); + foundTypedHolds.add(reference.holdId()); + } else if (reference.holdId().equals(second.holdId())) { + assertThat(exact.identity().canonicalBytes()).containsExactly(second.canonicalBytes()); + assertThat(exact.status()) + .isEqualTo(WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING); + foundTypedHolds.add(reference.holdId()); + } + } + assertThat(foundTypedHolds).contains(first.holdId(), second.holdId()); + + // This uses the existing serialized terminal path with a stipulated GS proof, not live GS auth. + var stipulatedCommittedProof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + first, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 1L, + 41L, + "sha256:" + "e".repeat(64), + false, + Instant.parse("2026-10-07T01:02:03.123456Z")); + var finalizer = + new WorldCanonicalInitialAdmissionHoldFinalizationService( + new WorldCanonicalInitialAdmissionHoldFinalizationRepository( + dsl, manager, associationRepository(), fixture.lifecycleRepository()), + stipulatedCanonicalGameSessionOwnerProofVerifier(stipulatedCommittedProof)); + assertThat( + finalizer.finalizeHold( + first, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .isEqualTo(stipulatedCommittedProof); + assertThat( + repository.readReconciliationCandidate( + active.request().targetNamespace(), first.holdId())) + .isEmpty(); + + List remainingTypedHolds = new ArrayList<>(); + after = null; + for (int pageNumber = 0; pageNumber < 256; pageNumber++) { + var page = + repository.findReconciliationCandidates(active.request().targetNamespace(), after, 1); + assertThat(page).hasSizeLessThanOrEqualTo(1); + if (page.isEmpty()) break; + var reference = page.getFirst(); + after = reference.cursor(); + if (reference.holdId().equals(first.holdId())) { + remainingTypedHolds.add(reference.holdId()); + } else if (reference.holdId().equals(second.holdId())) { + var exact = + repository + .readReconciliationCandidate(active.request().targetNamespace(), reference.holdId()) + .orElseThrow(); + assertThat(exact.identity().canonicalBytes()).containsExactly(second.canonicalBytes()); + assertThat(exact.status()) + .isEqualTo(WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING); + remainingTypedHolds.add(reference.holdId()); + } + } + assertThat(remainingTypedHolds).contains(second.holdId()).doesNotContain(first.holdId()); + assertOrigin(); + } + + private static Request canonicalReconciliationHoldRequest( + WorldCanonicalInstanceLifecycleEvidence active, String requestId, String requestDigest) { + return new Request( + active.request().targetNamespace(), + active.request().canonicalTenantId(), + active.request().worldSlug(), + UUID.randomUUID(), + active.request().playableStateNamespaceId(), + active.request().playableStateScope(), + active.request().canonicalGameInstanceId(), + active.request().canonicalVersionId(), + active.lifecycleEpoch(), + requestId, + requestDigest, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + } + @Test void canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas() throws Exception { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java index 11f2a47a53..50fe809f8f 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.Result; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; @@ -94,6 +95,24 @@ void realmHoldPredicateFailsClearlyWhenTheQueryReturnsNoRow() { assertTrue(exception.getMessage().startsWith("INITIAL_ADMISSION_BIND_HOLD_LOOKUP_FAILED:")); } + @Test + void legacyNonterminalFinderExcludesTypedCanonicalHoldsAndCapsItsPage() { + DSLContext dsl = Mockito.mock(DSLContext.class); + Result rows = Mockito.mock(Result.class); + when(dsl.fetch(anyString(), any(Object[].class))).thenReturn(rows); + when(rows.isEmpty()).thenReturn(true); + InitialAdmissionBindHoldRepository repository = new InitialAdmissionBindHoldRepository(dsl); + + assertTrue(repository.findNonterminal(900).isEmpty()); + + ArgumentCaptor query = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bindings = ArgumentCaptor.forClass(Object[].class); + verify(dsl).fetch(query.capture(), bindings.capture()); + assertTrue(query.getValue().contains("canonical_request_bytes IS NULL")); + assertTrue(query.getValue().contains("ORDER BY updated_at, hold_id LIMIT ?")); + assertEquals(256, bindings.getValue()[0]); + } + private InitialAdmissionBindHold hold() { Instant now = Instant.parse("2026-10-02T00:00:00Z"); return new InitialAdmissionBindHold( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldCanonicalInitialAdmissionHoldReconcilerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldCanonicalInitialAdmissionHoldReconcilerTest.java new file mode 100644 index 0000000000..355e2e482e --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldCanonicalInitialAdmissionHoldReconcilerTest.java @@ -0,0 +1,244 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldFinalizationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class WorldCanonicalInitialAdmissionHoldReconcilerTest { + private static final String NAMESPACE = "prod"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void advancesBoundedKeysetAcrossRowFailuresAndReportsReconciliationRequired() { + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var finalizer = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + var first = ref(1, 1); + var second = ref(2, 2); + var third = ref(3, 3); + var fourth = ref(4, 4); + var firstIdentity = identity(first.holdId()); + var terminalIdentity = identity(fourth.holdId()); + when(repository.findReconciliationCandidates(NAMESPACE, null, 2)) + .thenReturn(List.of(first, second)); + when(repository.readReconciliationCandidate(NAMESPACE, first.holdId())) + .thenThrow( + new WorldCanonicalInitialAdmissionHoldRepository.InvalidHoldIdentityException( + "malformed first row")); + when(repository.readReconciliationCandidate(NAMESPACE, second.holdId())) + .thenReturn( + Optional.of( + candidate( + identity(second.holdId()), + WorldCanonicalInitialAdmissionHoldState.HoldStatus.RECONCILIATION_REQUIRED))); + + when(repository.findReconciliationCandidates(NAMESPACE, second.cursor(), 2)) + .thenReturn(List.of(third, fourth)); + when(repository.readReconciliationCandidate(NAMESPACE, third.holdId())) + .thenReturn(Optional.empty()); + when(repository.readReconciliationCandidate(NAMESPACE, fourth.holdId())) + .thenReturn( + Optional.of( + candidate( + terminalIdentity, WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING))); + var committed = committed(terminalIdentity); + when(finalizer.observeAndFinalizeHold(terminalIdentity)).thenReturn(Optional.of(committed)); + when(repository.findReconciliationCandidates(NAMESPACE, fourth.cursor(), 2)) + .thenReturn(List.of()); + + var reconciler = + new WorldCanonicalInitialAdmissionHoldReconciler(repository, finalizer, NAMESPACE); + + var firstPage = reconciler.reconcileNextPage(2); + assertThat(firstPage.scanned()).isEqualTo(2); + assertThat(firstPage.unresolvedHoldIds()).containsExactly(first.holdId()); + assertThat(firstPage.reconciliationRequiredHoldIds()).containsExactly(second.holdId()); + assertThat(firstPage.stillPending()).isZero(); + assertThat(firstPage.endOfPass()).isFalse(); + verify(finalizer, never()).observeAndFinalizeHold(firstIdentity); + + var secondPage = reconciler.reconcileNextPage(2); + assertThat(secondPage.scanned()).isEqualTo(2); + assertThat(secondPage.terminalized()).isEqualTo(1); + assertThat(secondPage.unresolvedHoldIds()).isEmpty(); + assertThat(secondPage.endOfPass()).isFalse(); + verify(finalizer).observeAndFinalizeHold(terminalIdentity); + + var end = reconciler.reconcileNextPage(2); + assertThat(end.scanned()).isZero(); + assertThat(end.endOfPass()).isTrue(); + + verify(repository).findReconciliationCandidates(NAMESPACE, null, 2); + verify(repository).findReconciliationCandidates(NAMESPACE, second.cursor(), 2); + verify(repository).findReconciliationCandidates(NAMESPACE, fourth.cursor(), 2); + } + + @Test + void pendingOwnerOutcomeIsNoOpAndUnavailableTerminalReadLeavesTheRowUnresolved() { + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var finalizer = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + var pendingRef = ref(5, 5); + var unavailableRef = ref(6, 6); + HoldIdentity pending = identity(pendingRef.holdId()); + HoldIdentity unavailable = identity(unavailableRef.holdId()); + when(repository.findReconciliationCandidates(NAMESPACE, null, 8)) + .thenReturn(List.of(pendingRef, unavailableRef)); + when(repository.readReconciliationCandidate(NAMESPACE, pendingRef.holdId())) + .thenReturn( + Optional.of( + candidate(pending, WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING))); + when(repository.readReconciliationCandidate(NAMESPACE, unavailableRef.holdId())) + .thenReturn( + Optional.of( + candidate( + unavailable, WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING))); + when(finalizer.observeAndFinalizeHold(pending)).thenReturn(Optional.empty()); + doThrow(new IllegalStateException("owner read unavailable")) + .when(finalizer) + .observeAndFinalizeHold(unavailable); + + var reconciler = + new WorldCanonicalInitialAdmissionHoldReconciler(repository, finalizer, NAMESPACE); + var page = reconciler.reconcileNextPage(8); + + assertThat(page.stillPending()).isEqualTo(1); + assertThat(page.unresolvedHoldIds()).containsExactly(unavailableRef.holdId()); + verify(finalizer).observeAndFinalizeHold(pending); + verify(finalizer).observeAndFinalizeHold(unavailable); + } + + @Test + void equalTimestampCursorProgressUsesDatabaseUnsignedUuidOrderingAcrossHighBitBoundary() { + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var finalizer = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + Instant updatedAt = Instant.parse("2026-10-08T12:00:00Z"); + var lower = ref("7fffffff-ffff-4fff-8fff-000000000001", updatedAt); + var lowerLast = ref("7fffffff-ffff-4fff-8fff-000000000002", updatedAt); + var upper = ref("80000000-0000-4000-8000-000000000001", updatedAt); + var upperLast = ref("80000000-0000-4000-8000-000000000002", updatedAt); + when(repository.findReconciliationCandidates(NAMESPACE, null, 2)) + .thenReturn(List.of(lower, lowerLast)); + when(repository.findReconciliationCandidates(NAMESPACE, lowerLast.cursor(), 2)) + .thenReturn(List.of(upper, upperLast)); + when(repository.findReconciliationCandidates(NAMESPACE, upperLast.cursor(), 2)) + .thenReturn(List.of()); + for (var ref : List.of(lower, lowerLast, upper, upperLast)) { + when(repository.readReconciliationCandidate(NAMESPACE, ref.holdId())) + .thenReturn(Optional.empty()); + } + var reconciler = + new WorldCanonicalInitialAdmissionHoldReconciler(repository, finalizer, NAMESPACE); + + assertThat(reconciler.reconcileNextPage(2).scanned()).isEqualTo(2); + assertThat(reconciler.reconcileNextPage(2).scanned()).isEqualTo(2); + assertThat(reconciler.reconcileNextPage(2).endOfPass()).isTrue(); + + verify(repository).findReconciliationCandidates(NAMESPACE, null, 2); + verify(repository).findReconciliationCandidates(NAMESPACE, lowerLast.cursor(), 2); + verify(repository).findReconciliationCandidates(NAMESPACE, upperLast.cursor(), 2); + } + + @Test + void refusesAmbientTransactionAndSynchronizationBeforeTheCandidateScan() { + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldRepository.class); + var finalizer = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationService.class); + var reconciler = + new WorldCanonicalInitialAdmissionHoldReconciler(repository, finalizer, NAMESPACE); + + TransactionSynchronizationManager.setActualTransactionActive(true); + org.assertj.core.api.Assertions.assertThatThrownBy(reconciler::reconcileNextPage) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an ambient transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + org.assertj.core.api.Assertions.assertThatThrownBy(reconciler::reconcileNextPage) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an ambient transaction"); + verifyNoInteractions(repository, finalizer); + } + + private static WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCandidate candidate( + HoldIdentity identity, WorldCanonicalInitialAdmissionHoldState.HoldStatus status) { + return new WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCandidate( + identity, status); + } + + private static WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCandidateReference ref( + long suffix, long second) { + return ref( + String.format("00000000-0000-4000-8000-%012d", suffix), + Instant.parse("2026-10-08T12:00:00Z").plusSeconds(second)); + } + + private static WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCandidateReference ref( + String holdIdText, Instant updatedAt) { + UUID holdId = uuid(holdIdText); + var cursor = + new WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCursor(updatedAt, holdId); + return new WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCandidateReference( + holdId, cursor); + } + + private static HoldIdentity identity(UUID holdId) { + Request request = + new Request( + NAMESPACE, + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 7L, + "gs-initial-admission-" + holdId.toString().substring(24), + "a".repeat(64), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null); + return new HoldIdentity(request, holdId, uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof committed(HoldIdentity identity) { + return new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 1L, + 27L, + "sha256:" + "c".repeat(64), + false, + Instant.parse("2026-10-08T12:10:00Z")); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java index 36d5eaaa13..29d218a09b 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java @@ -186,6 +186,29 @@ void positiveDurableAbortIsReturnedAsTerminalOwnerEvidence() throws Exception { assertThat(bodyCalls).hasValue(1); } + @Test + void observedReadAcceptsExactPendingWithoutTerminalFieldsFromTheAuthenticatedPeer() + throws Exception { + startServer(pki.gameSessionServer(), ResponseMode.PENDING); + client = newClient(server); + client.init(); + HoldIdentity identity = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER); + + var held = client.verifyAndHoldObserved(identity); + try { + held.requireHeld(); + assertThat(held.proof().holdIdentity()).isEqualTo(identity); + assertThat(held.proof().outcome()) + .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + assertThat(held.proof().terminalAt()).isNull(); + assertThat(held.proof().proofDigest()).isNull(); + } finally { + held.close(); + } + assertThat(metadataCalls).hasValue(1); + assertThat(bodyCalls).hasValue(1); + } + @Test void changedResponseIdentityAndChangedOutcomeAreRejected() throws Exception { startServer(pki.gameSessionServer(), ResponseMode.SUBSTITUTED_REALM); @@ -261,6 +284,7 @@ void closedClientHandleCannotVerifyAnotherProof() throws Exception { } private enum ResponseMode { + PENDING, COMMITTED, ABORTED, SUBSTITUTED_REALM @@ -340,23 +364,29 @@ private static GetCanonicalInitialAdmissionOwnerProofResponse responseFor( .setOrigin(request.getOrigin()) .setHoldId(request.getHoldId()) .setHoldFence(request.getHoldFence()) - .setHoldBindingDigest(request.getHoldBindingDigest()) - .setProofDigest("sha256:" + "b".repeat(64)) - .setTerminalAt(Timestamp.newBuilder().setSeconds(1_791_331_200L)); + .setHoldBindingDigest(request.getHoldBindingDigest()); if (request.hasExpectedPriorPointerVersion()) { builder.setExpectedPriorPointerVersion(request.getExpectedPriorPointerVersion()); } - if (mode == ResponseMode.ABORTED) { + if (mode == ResponseMode.PENDING) { + builder.setOutcome( + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING); + } else if (mode == ResponseMode.ABORTED) { builder .setOutcome( CanonicalInitialAdmissionOwnerProofOutcome .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED) + .setProofDigest("sha256:" + "b".repeat(64)) + .setTerminalAt(Timestamp.newBuilder().setSeconds(1_791_331_200L)) .setPositiveDurableAbort(true); } else { builder .setOutcome( CanonicalInitialAdmissionOwnerProofOutcome .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED) + .setProofDigest("sha256:" + "b".repeat(64)) + .setTerminalAt(Timestamp.newBuilder().setSeconds(1_791_331_200L)) .setCommittedPointerVersion( request.getOrigin() == CanonicalInitialAdmissionOrigin diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientTest.java index 96a464b1d2..6059813f15 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerClientTest.java @@ -71,6 +71,8 @@ void rejectsBothFormsOfAmbientTransactionBeforeAnyOwnerRead(@TempDir Path direct () -> client.verifyAndHold( identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + assertThrows( + FinalizationDeniedException.class, () -> client.verifyAndHoldObserved(identity)); } finally { TransactionSynchronizationManager.setActualTransactionActive(false); } @@ -82,6 +84,8 @@ void rejectsBothFormsOfAmbientTransactionBeforeAnyOwnerRead(@TempDir Path direct () -> client.verifyAndHold( identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + assertThrows( + FinalizationDeniedException.class, () -> client.verifyAndHoldObserved(identity)); } finally { TransactionSynchronizationManager.clearSynchronization(); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodecTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodecTest.java index 1b489ed05b..277957f1d8 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodecTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/GameSessionCanonicalInitialAdmissionOwnerGrpcCodecTest.java @@ -116,6 +116,61 @@ void decodesPositiveDurableAbortWithoutPointerOrAuditEvidence() { assertTrue(proof.positiveDurableAbort()); } + @Test + void decodesExactPendingObservationWithoutTerminalFields() { + HoldIdentity identity = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + var response = + terminalResponse( + identity, + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING) + .clearTerminalAt() + .build(); + + var proof = GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.fromResponse(identity, response); + + assertEquals(identity, proof.holdIdentity()); + assertEquals(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING, proof.outcome()); + assertNull(proof.committedPointerVersion()); + assertNull(proof.auditEventId()); + assertNull(proof.proofDigest()); + assertNull(proof.terminalAt()); + assertFalse(proof.positiveDurableAbort()); + assertThrows( + IllegalArgumentException.class, + () -> + GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.fromResponse( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + response)); + } + + @Test + void rejectsTerminalFieldsOnPendingObservation() { + HoldIdentity identity = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + var pending = + terminalResponse( + identity, + CanonicalInitialAdmissionOwnerProofOutcome + .CANONICAL_INITIAL_ADMISSION_OWNER_PROOF_OUTCOME_PENDING); + + assertThrows( + IllegalArgumentException.class, + () -> + GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.fromResponse( + identity, pending.build())); + assertThrows( + IllegalArgumentException.class, + () -> + GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.fromResponse( + identity, pending.clearTerminalAt().setProofDigest(PROOF_DIGEST).build())); + assertThrows( + IllegalArgumentException.class, + () -> + GameSessionCanonicalInitialAdmissionOwnerGrpcCodec.fromResponse( + identity, pending.clearTerminalAt().setAuditEventId(31L).build())); + } + @Test void rejectsChangedOrMissingIdentityEchoAndWrongOptionalPresence() { HoldIdentity identity = identity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationServiceTest.java index 6873fe1285..87c08f0886 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationServiceTest.java @@ -155,6 +155,101 @@ void ambientTransactionsAreRejectedBeforeRemoteOwnerProofVerification() { verifyNoInteractions(repository); } + @Test + void observedPendingDoesNotReachTheWorldFinalizerAndClosesItsHeldObservation() { + HoldIdentity identity = identity(request(InitialAdmissionOrigin.NO_PRIOR_POINTER, null)); + var pending = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING, + null, + null, + null, + false, + null); + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationRepository.class); + AtomicBoolean closed = new AtomicBoolean(); + var service = + new WorldCanonicalInitialAdmissionHoldFinalizationService( + repository, observedVerifier(pending, closed)); + + assertThat(service.observeAndFinalizeHold(identity)).isEmpty(); + assertThat(closed).isTrue(); + verifyNoInteractions(repository); + } + + @Test + void observedTerminalOutcomesUseTheExistingFinalizerAndRejectSubstitutedIdentity() { + HoldIdentity identity = identity(request(InitialAdmissionOrigin.NO_PRIOR_POINTER, null)); + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationRepository.class); + var committed = committed(identity, 1L); + when(repository.finalizeTerminal(Mockito.eq(identity), Mockito.eq(committed), Mockito.any())) + .thenReturn(committed); + AtomicBoolean closed = new AtomicBoolean(); + var service = + new WorldCanonicalInitialAdmissionHoldFinalizationService( + repository, observedVerifier(committed, closed)); + + assertThat(service.observeAndFinalizeHold(identity)).contains(committed); + assertThat(closed).isTrue(); + verify(repository).finalizeTerminal(Mockito.eq(identity), Mockito.eq(committed), Mockito.any()); + + HoldIdentity substituted = + new HoldIdentity( + identity.request(), uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), identity.holdFence()); + var mismatchService = + new WorldCanonicalInitialAdmissionHoldFinalizationService( + repository, observedVerifier(committed(substituted, 1L), new AtomicBoolean())); + assertThatThrownBy(() -> mismatchService.observeAndFinalizeHold(identity)) + .isInstanceOf( + WorldCanonicalInitialAdmissionHoldFinalizationService.FinalizationDeniedException.class) + .hasMessageContaining("exact requested hold"); + verify(repository, Mockito.times(1)) + .finalizeTerminal(Mockito.eq(identity), Mockito.eq(committed), Mockito.any()); + + var aborted = + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + null, + null, + "sha256:" + "d".repeat(64), + true, + Instant.parse("2026-10-08T01:02:03.123456Z")); + when(repository.finalizeTerminal(Mockito.eq(identity), Mockito.eq(aborted), Mockito.any())) + .thenReturn(aborted); + var abortService = + new WorldCanonicalInitialAdmissionHoldFinalizationService( + repository, observedVerifier(aborted, new AtomicBoolean())); + assertThat(abortService.observeAndFinalizeHold(identity)).contains(aborted); + verify(repository).finalizeTerminal(Mockito.eq(identity), Mockito.eq(aborted), Mockito.any()); + } + + @Test + void observedOwnerReadRejectsAmbientTransactionAndSynchronizationBeforeVerification() { + HoldIdentity identity = identity(request(InitialAdmissionOrigin.NO_PRIOR_POINTER, null)); + var repository = Mockito.mock(WorldCanonicalInitialAdmissionHoldFinalizationRepository.class); + var verifier = + Mockito.mock( + WorldCanonicalInitialAdmissionHoldFinalizationService.OwnerProofVerifier.class); + var service = new WorldCanonicalInitialAdmissionHoldFinalizationService(repository, verifier); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> service.observeAndFinalizeHold(identity)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an ambient transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> service.observeAndFinalizeHold(identity)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an ambient transaction"); + TransactionSynchronizationManager.clearSynchronization(); + + verify(verifier, never()).verifyAndHoldObserved(Mockito.any()); + verifyNoInteractions(repository); + } + private static WorldCanonicalInitialAdmissionHoldFinalizationService.OwnerProofVerifier verifier( GameSessionCanonicalInitialAdmissionOwnerProof proof, AtomicBoolean closed) { return (identity, outcome) -> @@ -176,6 +271,38 @@ public void close() { }; } + private static WorldCanonicalInitialAdmissionHoldFinalizationService.OwnerProofVerifier + observedVerifier(GameSessionCanonicalInitialAdmissionOwnerProof proof, AtomicBoolean closed) { + return new WorldCanonicalInitialAdmissionHoldFinalizationService.OwnerProofVerifier() { + @Override + public WorldCanonicalInitialAdmissionHoldFinalizationService.HeldOwnerProof verifyAndHold( + HoldIdentity identity, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome) { + throw new AssertionError("Observed verification must not select an expected outcome"); + } + + @Override + public WorldCanonicalInitialAdmissionHoldFinalizationService.HeldOwnerProof + verifyAndHoldObserved(HoldIdentity identity) { + return new WorldCanonicalInitialAdmissionHoldFinalizationService.HeldOwnerProof() { + @Override + public GameSessionCanonicalInitialAdmissionOwnerProof proof() { + return proof; + } + + @Override + public void requireHeld() { + if (closed.get()) throw new IllegalStateException("held proof already closed"); + } + + @Override + public void close() { + closed.set(true); + } + }; + } + }; + } + private static GameSessionCanonicalInitialAdmissionOwnerProof committed( HoldIdentity identity, long pointerVersion) { return new GameSessionCanonicalInitialAdmissionOwnerProof( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java index 4590d763c9..bcc89028d3 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java @@ -12,6 +12,9 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -27,6 +30,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation.WorldPrepareFields; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.Result; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -379,6 +383,66 @@ void stateReadRejectsAmbientTransactionBeforeAnyOwnerLookup() { assertThat(fixture.manager.startedWith).isNull(); } + @Test + void reconciliationScanUsesNamespaceTypedKeysetAndBoundedLimitWithoutExpiry() { + Request request = noPriorRequest(); + Fixture fixture = fixture(request, activeLifecycle("ACTIVE", 7L), null); + Result rows = Mockito.mock(Result.class); + LocalDateTime updatedAt = LocalDateTime.parse("2026-10-08T12:13:14.123456"); + Record candidate = row(Map.of("hold_id", HOLD_ID, "updated_at", updatedAt)); + when(fixture.dsl.fetch(anyString(), any(Object[].class))).thenReturn(rows); + when(rows.size()).thenReturn(1); + when(rows.iterator()).thenReturn(List.of(candidate).iterator()); + var after = + new WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCursor( + Instant.parse("2026-10-08T12:00:00Z"), READ_ID); + + var found = fixture.repository.findReconciliationCandidates("prod", after, 900); + + assertThat(found) + .containsExactly( + new WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCandidateReference( + HOLD_ID, + new WorldCanonicalInitialAdmissionHoldRepository.ReconciliationCursor( + updatedAt.toInstant(ZoneOffset.UTC), HOLD_ID))); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bindings = ArgumentCaptor.forClass(Object[].class); + verify(fixture.dsl).fetch(sql.capture(), bindings.capture()); + assertThat(sql.getValue()) + .contains("canonical_request_bytes IS NOT NULL") + .contains("canonical_target_namespace = ?") + .contains("status IN ('PENDING', 'RECONCILIATION_REQUIRED')") + .contains("(updated_at, hold_id) > (?::timestamp, ?::uuid)") + .contains("ORDER BY updated_at, hold_id LIMIT ?") + .doesNotContain("diagnostic_expires_at"); + assertThat(bindings.getValue()) + .containsExactly( + "prod", LocalDateTime.ofInstant(after.updatedAt(), ZoneOffset.UTC), READ_ID, 256); + assertThat(fixture.manager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(fixture.manager.startedWith.isReadOnly()).isTrue(); + } + + @Test + void reconciliationCandidateRereadVerifiesTypedIdentityAndOwnerAssociation() { + Request request = noPriorRequest(); + Fixture fixture = + fixture(request, activeLifecycle("ACTIVE", 7L), storedRow(request, HOLD_ID, HOLD_FENCE)); + + var candidate = fixture.repository.readReconciliationCandidate("prod", HOLD_ID).orElseThrow(); + + assertThat(candidate.identity()).isEqualTo(new HoldIdentity(request, HOLD_ID, HOLD_FENCE)); + assertThat(candidate.status()) + .isEqualTo(WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING); + verify(fixture.associations).readOwnerAssociationInOwnerTransaction(CANONICAL_INSTANCE); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(fixture.dsl).fetchOne(sql.capture(), any(Object[].class)); + assertThat(sql.getValue()) + .contains("canonical_target_namespace = ?") + .contains("canonical_request_bytes IS NOT NULL") + .contains("status IN ('PENDING', 'RECONCILIATION_REQUIRED')"); + } + private static void assertStoredRowDenied(Request request, Record storedRow) { Fixture fixture = fixture(request, activeLifecycle("ACTIVE", 7L), storedRow); assertThatThrownBy(() -> fixture.repository.acquire(request, selector(request))) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java new file mode 100644 index 0000000000..cae1775dac --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java @@ -0,0 +1,869 @@ +package unit.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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadClient; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadRequest; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidenceReadClient; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeDigest; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceExecutionIdentity; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceOriginalOperationRecoveryVerifier; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService.PreparationDeniedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.json.JsonMapper; + +/** Mocked owner-client evidence exercises composition only; it is not genuine cross-owner proof. */ +class WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String NAMESPACE = "gameplay"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID GAME_INSTANCE = uuid("23232323-2323-4323-8323-232323232323"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID PARTICIPATION_ID = uuid("13131313-1313-4313-8313-131313131313"); + private static final UUID ATTEMPT_ID = uuid("12121212-1212-4121-8121-121212121212"); + private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID VERSION_OPERATION_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final long ACCOUNT_FENCE = 31L; + private static final long GAME_SESSION_FENCE = 37L; + private static final long GAME_TEMPLATE_ID = 91L; + private static final byte[] ORIGINAL_TUPLE = + "synthetic-original-start-session-tuple".getBytes(StandardCharsets.UTF_8); + + @AfterEach + void clearAmbientTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void acceptsExactHistoricalOwnerEvidenceAndUsesFreshReadCorrelations() { + acceptsExactHistoricalOwnerEvidenceAndUsesFreshReadCorrelations(fixture(false)); + } + + @Test + void acceptsSerializerShapedSchemaTwoHistoricalEvidence() { + acceptsExactHistoricalOwnerEvidenceAndUsesFreshReadCorrelations(fixture(false, true)); + } + + private void acceptsExactHistoricalOwnerEvidenceAndUsesFreshReadCorrelations(Fixture fixture) { + var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); + var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) + .thenAnswer( + invocation -> + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.preparationInputJson())); + when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) + .thenAnswer( + invocation -> + gameSessionEvidence( + invocation.getArgument(0), + fixture, + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.launchAssociation())); + + verifier(account, gameSession).verifyOriginalOperation(fixture.identity()); + + var accountRequest = + org.mockito.ArgumentCaptor.forClass( + AccountStartSessionWorldParticipationHistoricalReadRequest.class); + verify(account).read(accountRequest.capture()); + assertThat(accountRequest.getValue().targetNamespace()).isEqualTo(NAMESPACE); + assertThat(accountRequest.getValue().accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(accountRequest.getValue().accountWorldParticipationFence()).isEqualTo(ACCOUNT_FENCE); + assertThat(accountRequest.getValue().readRequestId()) + .isNotEqualTo(PARTICIPATION_ID) + .isNotEqualTo(ATTEMPT_ID) + .isNotEqualTo(GAME_INSTANCE); + + var gameSessionRequest = + org.mockito.ArgumentCaptor.forClass( + HistoricalOriginalStartSessionOwnerEvidence.Request.class); + verify(gameSession).read(gameSessionRequest.capture()); + assertThat(gameSessionRequest.getValue().associationSelector().readRequestId()) + .isNotEqualTo(GAME_INSTANCE) + .isNotEqualTo(PARTICIPATION_ID) + .isNotEqualTo(ATTEMPT_ID); + assertThat(gameSessionRequest.getValue().expectedOwnerAttemptId()).isEqualTo(ATTEMPT_ID); + assertThat(gameSessionRequest.getValue().expectedOwnerFence()).isEqualTo(GAME_SESSION_FENCE); + assertThat(fixture.launchAssociation().capturedStartingRowVersion()).isEqualTo(9_999L); + } + + @Test + void rejectsAccountTupleAttemptOrFenceSubstitutionBeforeGameSessionRead() { + for (int substitution = 0; substitution < 3; substitution++) { + Fixture fixture = fixture(false); + var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); + var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + byte[] tuple = + substitution == 0 ? "changed tuple".getBytes(StandardCharsets.UTF_8) : ORIGINAL_TUPLE; + UUID attempt = substitution == 1 ? uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa") : ATTEMPT_ID; + long fence = substitution == 2 ? GAME_SESSION_FENCE + 1L : GAME_SESSION_FENCE; + when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) + .thenAnswer( + invocation -> + accountEvidence( + invocation.getArgument(0), + tuple, + attempt, + fence, + fixture.preparationInputJson())); + + assertDenied(verifier(account, gameSession), fixture.identity()); + verifyNoInteractions(gameSession); + } + } + + @Test + void rejectsGameSessionTupleAttemptOrFenceSubstitution() { + for (int substitution = 0; substitution < 3; substitution++) { + Fixture fixture = fixture(false); + var account = exactAccountClient(fixture); + var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + byte[] tuple = + substitution == 0 ? "changed tuple".getBytes(StandardCharsets.UTF_8) : ORIGINAL_TUPLE; + UUID attempt = substitution == 1 ? uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa") : ATTEMPT_ID; + long fence = substitution == 2 ? GAME_SESSION_FENCE + 1L : GAME_SESSION_FENCE; + when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) + .thenAnswer( + invocation -> + gameSessionEvidence( + invocation.getArgument(0), + fixture, + tuple, + attempt, + fence, + fixture.launchAssociation())); + + assertDenied(verifier(account, gameSession), fixture.identity()); + } + } + + @Test + void rejectsDescriptorOrSourceAssociationSubstitution() { + Fixture exact = fixture(false); + var account = exactAccountClient(exact); + var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + LaunchAssociation substitutedDescriptor = fixture(true).launchAssociation(); + when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) + .thenAnswer( + invocation -> + gameSessionEvidence( + invocation.getArgument(0), + exact, + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + substitutedDescriptor)); + assertDenied(verifier(account, gameSession), exact.identity()); + + Fixture substitutedSource = fixtureWithSubstitutedSource(); + var sourceAccount = exactAccountClient(substitutedSource); + var sourceGameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + when(sourceGameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) + .thenAnswer( + invocation -> + gameSessionEvidence( + invocation.getArgument(0), + substitutedSource, + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + exact.launchAssociation())); + assertDenied(verifier(sourceAccount, sourceGameSession), substitutedSource.identity()); + } + + @Test + void rejectsPreparationInputSubstitutionAndMissingOwnerEvidence() { + Fixture fixture = fixture(false); + var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); + var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) + .thenAnswer( + invocation -> + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.preparationInputJson() + " ")); + assertDenied(verifier(account, gameSession), fixture.identity()); + verifyNoInteractions(gameSession); + + var missingAccount = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); + var missingGameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + when(missingAccount.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) + .thenReturn(null); + assertDenied(verifier(missingAccount, missingGameSession), fixture.identity()); + verifyNoInteractions(missingGameSession); + + var exactAccount = exactAccountClient(fixture); + var missingGameSessionResult = + mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + when(missingGameSessionResult.read( + any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) + .thenReturn(null); + assertDenied(verifier(exactAccount, missingGameSessionResult), fixture.identity()); + } + + @Test + void rejectsSchemaTwoSelectorSubstitutionAgainstTheRetainedRelease() { + Fixture fixture = fixture(false, true); + String selectedEvidence = + java.util.Base64.getEncoder() + .encodeToString( + fixture + .launchAssociation() + .launchBindingEvidence() + .releaseAttestation() + .worldStartLocationEvidence() + .canonicalBytes()); + String substitutedInput = fixture.preparationInputJson().replace(selectedEvidence, "e30="); + assertThat(substitutedInput) + .isNotEqualTo(fixture.preparationInputJson()) + .contains("\"schemaVersion\":2", "\"worldStartLocationEvidenceBase64\":\"e30=\""); + when(fixture.identity().preparationInputJson()).thenReturn(substitutedInput); + when(fixture.identity().preparationInputDigest()) + .thenReturn(sha256(substitutedInput.getBytes(StandardCharsets.UTF_8))); + + var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); + when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) + .thenAnswer( + invocation -> + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + substitutedInput)); + var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) + .thenAnswer( + invocation -> + gameSessionEvidence( + invocation.getArgument(0), + fixture, + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.launchAssociation())); + + assertDenied(verifier(account, gameSession), fixture.identity()); + } + + @Test + void ambientSqlAndSynchronizationAreRejectedBeforeOwnerReads() { + Fixture fixture = fixture(false); + var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); + var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + var verifier = verifier(account, gameSession); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> verifier.verifyOriginalOperation(fixture.identity())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an ambient transaction"); + TransactionSynchronizationManager.clear(); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> verifier.verifyOriginalOperation(fixture.identity())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an ambient transaction"); + verifyNoInteractions(account, gameSession); + } + + private static Fixture fixture(boolean alternateDescriptor) { + return fixture(alternateDescriptor, false); + } + + private static Fixture fixture(boolean alternateDescriptor, boolean selectedSchema) { + WorldPublishedStartLocationEvidence selector = selectedSchema ? retainedWorldSelector() : null; + WorldAuthoredSourceIntakeReceipt source = + sourceReceipt(false, selector == null ? null : selector.request().intakeRequestId()); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(source, alternateDescriptor); + AuthoredWorldReleaseAttestationEvidence release = release(descriptor, selector); + return fixture(source, descriptor, release, selector); + } + + private static WorldPublishedStartLocationEvidence retainedWorldSelector() { + try { + return WorldCanonicalPlayerLocationGrpcServiceTest.publishedSelector(NAMESPACE); + } catch (Exception malformedFixture) { + throw new AssertionError( + "Constructor-validated World selector fixture is invalid", malformedFixture); + } + } + + private static Fixture fixtureWithSubstitutedSource() { + WorldAuthoredSourceIntakeReceipt originalSource = sourceReceipt(false); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(originalSource, false); + AuthoredWorldReleaseAttestationEvidence release = release(descriptor); + WorldAuthoredSourceIntakeReceipt substitutedSource = sourceReceipt(true); + return fixture(substitutedSource, descriptor, release); + } + + private static Fixture fixture( + WorldAuthoredSourceIntakeReceipt retainedSource, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence release) { + return fixture(retainedSource, descriptor, release, null); + } + + private static Fixture fixture( + WorldAuthoredSourceIntakeReceipt retainedSource, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence release, + WorldPublishedStartLocationEvidence selector) { + String input = preparationInput(descriptor, release, retainedSource, selector); + WorldCanonicalInstanceExecutionIdentity identity = + mock(WorldCanonicalInstanceExecutionIdentity.class); + when(identity.originalPostAuthorizationTuple()).thenReturn(ORIGINAL_TUPLE.clone()); + when(identity.accountWorldParticipationId()).thenReturn(PARTICIPATION_ID); + when(identity.accountWorldParticipationFence()).thenReturn(ACCOUNT_FENCE); + when(identity.gameSessionOwnerAttemptId()).thenReturn(ATTEMPT_ID); + when(identity.gameSessionOwnerFence()).thenReturn(GAME_SESSION_FENCE); + when(identity.canonicalGameInstanceId()).thenReturn(GAME_INSTANCE); + when(identity.targetNamespace()).thenReturn(NAMESPACE); + when(identity.canonicalTenantId()).thenReturn(TENANT); + when(identity.controlPlaneRequestId()).thenReturn("start-session-control-request"); + when(identity.gameTemplateId()).thenReturn(GAME_TEMPLATE_ID); + when(identity.preparationInputJson()).thenReturn(input); + when(identity.preparationInputDigest()) + .thenReturn(sha256(input.getBytes(StandardCharsets.UTF_8))); + return new Fixture( + identity, + input, + retainedSource, + launchAssociation(new CompleteLaunchBindingEvidence(descriptor, release))); + } + + private static WorldAuthoredSourceIntakeReceipt sourceReceipt(boolean alternate) { + return sourceReceipt(alternate, null); + } + + private static WorldAuthoredSourceIntakeReceipt sourceReceipt( + boolean alternate, UUID intakeRequestId) { + UUID registration = + uuid( + alternate + ? "99999999-9999-4999-8999-999999999999" + : "a1111111-1111-4111-8111-111111111111"); + UUID operation = + uuid( + alternate + ? "a2222222-2222-4222-8222-222222222222" + : "a3333333-3333-4333-8333-333333333333"); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registration, TENANT, "tenant", "world", "A World"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + operation, + requestDigest, + TENANT, + "tenant", + "world", + "A World", + 17L, + "tenant-key", + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + operation, + requestDigest, + TENANT, + "tenant", + "world", + "A World", + 17L, + "tenant-key", + "NEW_GAME_ROW", + evidenceDigest); + UUID intakeRequest = + intakeRequestId == null ? uuid("a4444444-4444-4444-8444-444444444444") : intakeRequestId; + UUID intakeOperation = uuid("a5555555-5555-4555-8555-555555555555"); + long localTenantKey = 51L; + String intakeRequestDigest = + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, intakeRequest, source); + String receiptDigest = + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, intakeOperation, intakeRequestDigest, source, localTenantKey); + return new WorldAuthoredSourceIntakeReceipt( + 1, + NAMESPACE, + intakeRequest, + intakeOperation, + TENANT, + "world", + operation, + evidenceDigest, + intakeRequestDigest, + receiptDigest, + localTenantKey, + source); + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptor( + WorldAuthoredSourceIntakeReceipt source, boolean alternate) { + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "start-session-control-request", + TENANT, + "world", + source.sourceOperationId(), + source.sourceEvidenceDigest(), + alternate ? GAME_TEMPLATE_ID + 1L : GAME_TEMPLATE_ID, + false, + null, + false, + null, + false, + null, + false, + null); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + alternate ? "launch-descriptor-substitute" : "launch-descriptor-original", + 42L, + false, + null, + "{}", + "generation-config-1", + 7L, + 51L, + "release-bundle-51", + false, + null); + } + + private static AuthoredWorldReleaseAttestationEvidence release( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return release(descriptor, null); + } + + private static AuthoredWorldReleaseAttestationEvidence release( + AuthoredWorldLaunchDescriptorEvidence descriptor, + WorldPublishedStartLocationEvidence selector) { + List participants = new ArrayList<>(); + for (String participant : AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()) { + boolean hasAbilityDigest = "GAME_LOGIC".equals(participant); + String contentDigest = + selector != null && "WORLD_MANAGEMENT".equals(participant) + ? selector.request().contentDigest() + : "a".repeat(64); + participants.add( + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant, + "42", + false, + null, + COMMIT_ID.toString(), + contentDigest, + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant, + selector == null + ? AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION + : AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + hasAbilityDigest, + hasAbilityDigest ? sha256("ability-schema".getBytes(StandardCharsets.UTF_8)) : null)); + } + if (selector == null) { + return AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT, + VERSION_ID, + "world", + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish-workflow-original", + COMMIT_ID.toString(), + participants, + sha256("manifest".getBytes(StandardCharsets.UTF_8)), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + } + return AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT, + VERSION_ID, + "world", + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + sha256("manifest".getBytes(StandardCharsets.UTF_8)), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selector); + } + + private static String preparationInput( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence release, + WorldAuthoredSourceIntakeReceipt source, + WorldPublishedStartLocationEvidence selector) { + Map identity = + map( + "canonicalGameInstanceId", + GAME_INSTANCE.toString(), + "targetNamespace", + NAMESPACE, + "canonicalTenantId", + TENANT.toString(), + "worldSlug", + "world", + "playableStateNamespaceId", + PLAYABLE_NAMESPACE.toString(), + "playableStateScope", + "SHARED", + "publicProduction", + true, + "controlPlaneRequestId", + "start-session-control-request"); + Map readRequest = + map( + "targetNamespace", NAMESPACE, + "canonicalTenantId", TENANT.toString(), + "worldSlug", "world", + "canonicalGameInstanceId", GAME_INSTANCE.toString(), + "controlPlaneRequestId", "start-session-control-request", + "launchDescriptorId", descriptor.launchDescriptorId(), + "expectedDescriptorRequestDigest", descriptor.requestDigest(), + "expectedDescriptorResultDigest", descriptor.resultDigest(), + "expectedReleaseAttestationEvidenceDigest", release.evidenceDigest()); + Map readEvidence = + map( + "targetNamespace", NAMESPACE, + "canonicalTenantId", TENANT.toString(), + "worldSlug", "world", + "canonicalGameInstanceId", GAME_INSTANCE.toString(), + "controlPlaneRequestId", "start-session-control-request", + "launchDescriptorId", descriptor.launchDescriptorId(), + "descriptorRequestDigest", descriptor.requestDigest(), + "descriptorResultDigest", descriptor.resultDigest(), + "releaseAttestationEvidenceDigest", release.evidenceDigest(), + "playableStateNamespaceId", PLAYABLE_NAMESPACE.toString(), + "playableStateScope", "SHARED", + "publicProduction", true, + "descriptorJson", json(descriptor), + "releaseAttestationJson", json(release)); + Map launch = + map( + "schemaVersion", 1, + "operationId", "a6666666-6666-4666-8666-666666666666", + "targetNamespace", NAMESPACE, + "canonicalTenantId", TENANT.toString(), + "worldSlug", "world", + "controlPlaneRequestId", "start-session-control-request", + "descriptorRequestDigest", descriptor.requestDigest(), + "descriptorResultDigest", descriptor.resultDigest(), + "releaseAttestationDigest", release.evidenceDigest(), + "canonicalVersionId", VERSION_ID.toString(), + "localTenantKey", source.localTenantKey(), + "intakeOperationId", source.operationId().toString(), + "intakeRequestId", source.intakeRequestId().toString(), + "sourceOperationId", source.sourceOperationId().toString(), + "sourceEvidenceDigest", source.sourceEvidenceDigest(), + "intakeRequestDigest", source.requestDigest(), + "intakeReceiptDigest", source.receiptDigest()); + var evidence = source.source(); + Map sourceEvidence = + map( + "schemaVersion", evidence.schemaVersion(), + "registrationRequestId", evidence.registrationRequestId().toString(), + "sourceOperationId", evidence.operationId().toString(), + "requestDigest", evidence.requestDigest(), + "canonicalTenantId", evidence.canonicalTenantId().toString(), + "tenantSlug", evidence.tenantSlug(), + "worldSlug", evidence.worldSlug(), + "worldDisplayName", evidence.worldDisplayName(), + "sourceGameRowId", evidence.sourceGameRowId(), + "sourceGameTenantKey", evidence.sourceGameTenantKey(), + "provenanceKind", evidence.provenanceKind(), + "evidenceDigest", evidence.evidenceDigest()); + Map sourceIntake = + map( + "schemaVersion", source.schemaVersion(), + "targetNamespace", source.targetNamespace(), + "intakeRequestId", source.intakeRequestId().toString(), + "operationId", source.operationId().toString(), + "canonicalTenantId", source.canonicalTenantId().toString(), + "worldSlug", source.worldSlug(), + "sourceOperationId", source.sourceOperationId().toString(), + "sourceEvidenceDigest", source.sourceEvidenceDigest(), + "requestDigest", source.requestDigest(), + "receiptDigest", source.receiptDigest(), + "localTenantKey", source.localTenantKey(), + "sourceEvidence", sourceEvidence); + Map versionIdentity = + map( + "schemaVersion", + 1, + "operationId", + VERSION_OPERATION_ID.toString(), + "canonicalVersionId", + VERSION_ID.toString(), + "localVersionKey", + 61L, + "gameDesignVersionId", + 42L, + "versionState", + "VERSION_LIFECYCLE_STATE_PUBLISHED", + "versionStateEpoch", + 5L, + "evidenceDigest", + sha256("version-state".getBytes(StandardCharsets.UTF_8))); + Map topology = + map( + "captureId", + "a7777777-7777-4777-8777-777777777777", + "targetNamespace", + NAMESPACE, + "canonicalTenantId", + TENANT.toString(), + "canonicalVersionId", + VERSION_ID.toString(), + "versionIdentityOperationId", + VERSION_OPERATION_ID.toString(), + "requestId", + selector == null + ? "a8888888-8888-4888-8888-888888888889" + : DraftAuthorizationFenceBinding.fromStored(selector.originalAccountBindingBytes()) + .requestId() + .toString(), + "commitId", + COMMIT_ID.toString(), + "freezeRequestId", + selector == null ? "publication-request-1" : selector.request().publicationRequestId(), + "publicationFence", + selector == null + ? "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb" + : selector.request().publicationFence().toString(), + "publicationRequestDigest", + selector == null + ? sha256("publication".getBytes(StandardCharsets.UTF_8)) + .substring("sha256:".length()) + : selector.request().requestDigest(), + "appliedCommitId", + selector == null ? COMMIT_ID.toString() : selector.request().appliedCommitId(), + "planDigest", + sha256("topology-plan".getBytes(StandardCharsets.UTF_8)), + "regionCount", + 1, + "zoneCount", + selector == null ? 0 : 1, + "roomCount", + selector == null ? 0 : 1, + "exitCount", + 0, + "generationRuleCount", + 0, + "spawnBindingCount", + 0); + Map root = + map( + "schemaVersion", selector == null ? 1 : 2, + "identity", identity, + "gameSessionReadRequest", readRequest, + "gameSessionReadEvidence", readEvidence, + "launchBinding", launch, + "versionIdentity", versionIdentity, + "sourceIntake", sourceIntake, + "topology", topology); + if (selector != null) { + root.put( + "worldStartLocationEvidenceBase64", + java.util.Base64.getEncoder().encodeToString(selector.canonicalBytes())); + } + return json(root); + } + + private static AccountStartSessionWorldParticipationHistoricalReadClient exactAccountClient( + Fixture fixture) { + var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); + when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) + .thenAnswer( + invocation -> + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.preparationInputJson())); + return account; + } + + private static AccountStartSessionWorldParticipationHistoricalReadEvidence accountEvidence( + AccountStartSessionWorldParticipationHistoricalReadRequest request, + byte[] tuple, + UUID attempt, + long fence, + String preparationInput) { + var evidence = mock(AccountStartSessionWorldParticipationHistoricalReadEvidence.class); + when(evidence.request()).thenReturn(request); + when(evidence.originalPostAuthorizationTuple()).thenReturn(tuple.clone()); + when(evidence.gameSessionOwnerAttemptId()).thenReturn(attempt); + when(evidence.gameSessionOwnerFence()).thenReturn(fence); + when(evidence.canonicalGameInstanceId()).thenReturn(GAME_INSTANCE); + when(evidence.preparationInputJson()).thenReturn(preparationInput); + when(evidence.preparationInputDigest()) + .thenReturn(sha256(preparationInput.getBytes(StandardCharsets.UTF_8))); + return evidence; + } + + private static HistoricalOriginalStartSessionOwnerEvidence.Result gameSessionEvidence( + HistoricalOriginalStartSessionOwnerEvidence.Request request, + Fixture fixture, + byte[] tupleBytes, + UUID attempt, + long fence, + LaunchAssociation launchAssociation) { + var result = mock(HistoricalOriginalStartSessionOwnerEvidence.Result.class); + var tuple = mock(StartSessionPostAuthorizationExecutionTuple.class); + when(tuple.canonicalBytes()).thenReturn(tupleBytes.clone()); + var selection = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + var selectionAssociation = mock(StartSessionTemplateAssociationReadEvidence.Association.class); + var retainedRelease = fixture.launchAssociation().launchBindingEvidence().releaseAttestation(); + when(selectionAssociation.targetNamespace()).thenReturn(NAMESPACE); + when(selectionAssociation.canonicalTenantId()).thenReturn(TENANT); + when(selectionAssociation.templateId()).thenReturn(GAME_TEMPLATE_ID); + when(selectionAssociation.worldSlug()).thenReturn("world"); + when(selectionAssociation.canonicalVersionId()) + .thenReturn(retainedRelease.canonicalVersionId()); + when(selectionAssociation.selectedCommitId()) + .thenReturn(UUID.fromString(retainedRelease.commitId())); + when(selectionAssociation.publishWorkflowId()).thenReturn(retainedRelease.publishWorkflowId()); + when(selectionAssociation.sourceOperationId()) + .thenReturn(fixture.retainedSource().sourceOperationId()); + when(selectionAssociation.sourceEvidenceDigest()) + .thenReturn(fixture.retainedSource().sourceEvidenceDigest()); + when(selection.association()).thenReturn(selectionAssociation); + when(result.request()).thenReturn(request); + when(result.originalTuple()).thenReturn(tuple); + when(result.ownerAttemptId()).thenReturn(attempt); + when(result.ownerFence()).thenReturn(fence); + when(result.firstSelection()).thenReturn(selection); + when(result.launchAssociation()).thenReturn(launchAssociation); + return result; + } + + private static LaunchAssociation launchAssociation(CompleteLaunchBindingEvidence binding) { + var descriptor = binding.descriptor(); + return new LaunchAssociation( + NAMESPACE, + TENANT, + "world", + GAME_INSTANCE, + "start-session-control-request", + descriptor.launchDescriptorId(), + PLAYABLE_NAMESPACE, + RealmEntryPolicy.StateScope.SHARED, + true, + 9_999L, + binding); + } + + private static WorldCanonicalInstanceOriginalOperationRecoveryVerifier verifier( + AccountStartSessionWorldParticipationHistoricalReadClient account, + HistoricalOriginalStartSessionOwnerEvidenceReadClient gameSession) { + return new WorldCanonicalInstanceOriginalOperationRecoveryVerifier(account, gameSession); + } + + private static void assertDenied( + WorldCanonicalInstanceOriginalOperationRecoveryVerifier verifier, + WorldCanonicalInstanceExecutionIdentity identity) { + assertThatThrownBy(() -> verifier.verifyOriginalOperation(identity)) + .isInstanceOf(PreparationDeniedException.class); + } + + private static Map map(Object... values) { + Map result = new LinkedHashMap<>(); + for (int index = 0; index < values.length; index += 2) { + result.put((String) values[index], values[index + 1]); + } + return result; + } + + private static String json(Object value) { + try { + return JSON.writeValueAsString(value); + } catch (JacksonException failure) { + throw new IllegalStateException("Synthetic recovery input could not be serialized", failure); + } + } + + private static String sha256(byte[] value) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + WorldCanonicalInstanceExecutionIdentity identity, + String preparationInputJson, + WorldAuthoredSourceIntakeReceipt retainedSource, + LaunchAssociation launchAssociation) {} +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java index e0b2b73e35..17f8902fce 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationGrpcServiceTest.java @@ -1161,8 +1161,7 @@ private static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence( uuid("22222222-2222-4222-8222-222222222222"))); } - private static WorldPublishedStartLocationEvidence publishedSelector(String namespace) - throws Exception { + static WorldPublishedStartLocationEvidence publishedSelector(String namespace) throws Exception { DraftCommitBinding draft = freshGraphBinding(); byte[] accountBytes = accountBinding(draft); var terminalRequest = From d52b123ffaab637cac974012a708de508cc0468b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:09:52 +1300 Subject: [PATCH 071/129] Add authenticated preliminary selected-owner source permission --- .../account-service/api-contracts.md | 2 + .../game-design-service/api-contracts.md | 2 + ...ame-authoring-publishing-and-activation.md | 4 +- ...ted_owner_intake_source_read_service.proto | 27 + ...ectedOwnerIntakeSourceReadGrpcService.java | 93 +++ ...dOwnerIntakeSourceReadGrpcServiceTest.java | 296 ++++++++++ ...pcSelectedOwnerIntakeSourceReadClient.java | 147 +++++ .../SelectedOwnerIntakeSourceReadClient.java | 6 + ...SelectedOwnerIntakeSourceReadEvidence.java | 73 +++ ...lectedOwnerIntakeSourceReadProtoCodec.java | 91 +++ ...edOwnerIntakeSourceReadClientMtlsTest.java | 529 ++++++++++++++++++ ...edOwnerIntakeSourceReadProtoCodecTest.java | 224 ++++++++ ...nSelectedOwnerIntakeSourceReadService.java | 92 +++ ...ectedOwnerIntakeSourceReadServiceTest.java | 288 ++++++++++ 14 files changed, 1873 insertions(+), 1 deletion(-) create mode 100644 protos/account/v1/selected_owner_intake_source_read_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index f46f403eb7..a4aa80a77a 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -110,6 +110,8 @@ Entity and Automation's selected-source intake use the same two-phase ownership That scope is preliminary integrity input, not authenticated authorization, finalized owner retention permission or evidence that any source family is empty. Account must authenticate and retain the distinct reservation before Game Design returns source content; it must then obtain the complete immutable selected inputs and finalize the owner-specific authorization with revalidated held sources. The original Draft's required-owner vector identifies its mutation participants, not the consumers of this later distinct intake. Original revision provenance is retained separately from the selected capture and must not be rewritten to manufacture a World association. Entity's [complete authored inventory](../entity-management-service/runtime-and-data.md) and Automation's [source inventory and inbound closure](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) remain owner-validated obligations. Both owners retain their original terminal under continuously protected Account authority; only authenticated exact terminal settlement can release participation. A decoded scope or sampled `HELD` response proves none of those obligations. Complete authenticated reservation/finalization, held-retention producers and executed proof remain open in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); these domains do not register or enable a runtime path. +The distinct [`AccountSelectedOwnerIntakeSourceReadService.ReadSourceScope`](../../../../protos/account/v1/selected_owner_intake_source_read_service.proto) confirms only the retained preliminary Entity or Automation reservation. Account authenticates the exact configured same-namespace Game Design workload and rejects authenticated end-user context before decoding or storage. The closed schema-version-1 request binds namespace, independent nonzero transport correlation, derived Account reader and closed purpose, and the original scope bytes and digest. Account revalidates its own original creator and source participation in independent transactions around the external registry read; neither a client digest nor peer identity creates a reservation. A successful response echoes the complete request unchanged and confirms only that preliminary scope. Missing, expired, changed, malformed or unavailable evidence denies. The canonical scope remains bounded to 4 MiB; the separately enforced request and response wire budget is 8 MiB, including echo and framing. The file-backed mTLS client pins the Account server, applies a five-second deadline and rejects ambient SQL or synchronization. This standalone method has no finalized-retention branch, supplies no census or owner receipt, and does not register or activate a runtime path. Game Design must finish this authenticated Account confirmation outside SQL before reading or returning any selected source content. + `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `account_service.proto`. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 1e62b93540..4f129acfbf 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -75,6 +75,8 @@ After that confirmation, Game Design reads only the complete immutable source fo For distinct Entity and Automation intake, the complete Game Design selected-source content binds the owner-specific preliminary scope unchanged and includes all six synchronized families: command, realm policy, asset, gameplay rule, branding and template configuration. Each family retains its original canonical snapshot bytes and provenance for the exact same selected Draft binding; unavailable branding or template history is unknown, not empty. The bounded owner-local construction uses `game-design-selected-owner-intake-source/v1` byte-length framing: domain, complete scope bytes and digest, then `COMMAND`, `REALM_POLICY`, `ASSET`, `GAMEPLAY_RULE`, `BRANDING` and `TEMPLATE_CONFIG` in that fixed order, each followed by its exact snapshot bytes and digest. The complete framed content is limited to 8 MiB. This source value is not authenticated disclosure, an Account reservation or finalization, an Entity/Automation completeness judgment, or an owner receipt. The distinct authenticated permission, source-read transport and held owner retention remain required before any content can be disclosed or accepted through those boundaries; the owner-local constructor does not add a registered RPC or expand the Gameplay Rule method's allowlist. +The separate preliminary owner-read composition accepts only the exact same-namespace Account workload without end-user context. It obtains the [Account-owned preliminary permission confirmation](../account-service/api-contracts.md#grpc-apis) outside SQL, compares the complete original request and independent correlation, then opens its own source transaction and reads all six families for the unchanged selected binding. Failed, absent or substituted confirmation returns no content and performs no source query. The resulting export must retain the exact original scope. This unregistered composition does not expand `ReadSelectedGameplayRuleSource`, supply a finalized owner grant or register the still-required selected-content transport; its proof and remaining producer/consumer gaps belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + ## Exact Publication Terminal Read `GameDesignPublicationTerminalReadService.ReadPublicationTerminal` reads the original immutable terminal result, not current permission or a new publication attempt. Its closed version-1 request binds the canonical workload namespace, a non-nil canonical read-request UUID and the complete original `game-design-publication-operation/v1` bytes. The receiver authenticates the exact same-namespace Account or World Management workload before decoding input or accessing storage. 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 d2f451d5fb..d02f1711e3 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The preliminary Entity/Automation source-permission transport and Game Design permission-before-query composition pass the affected Common/Account/Game Design full-check gate in 2m30s, including affected boot JARs, formatting, static checks, coverage, links and Markdown. The exact same-namespace Game Design caller is authenticated before Account decoding or storage; the file-backed client authenticates Account, compares the full unchanged echo and performs no network call under SQL or transaction synchronization. Game Design obtains that confirmation outside SQL before opening its independent six-family source transaction. Common retains 516 passing unit results and Game Design 544; Account executes 1,236 unit cases, all without failures, errors or unit skips. The nine new Common codec/mTLS cases and five Game Design ordering cases passed in the first run and remain unchanged; the corrected six Account receiver cases pass in this gate. Account retains seven non-container integration passes and skips 255 definitions; Game Design skips all 148 definitions without Docker. Loopback mTLS uses a synthetic Account handler, while receiver and transaction-order tests use mocked owners: none establishes genuine Account-to-Game Design source disclosure, finalized owner retention, Entity/Automation census or terminal receipts. The selected-content transport and complete finalization/settlement remain open; all new components remain unregistered. + The corrected World historical-recovery and canonical-hold reconciliation batch passes the affected Common/World full checks, Account schema generation and integration compilation, World boot JAR, formatting, static checks, coverage, links and Markdown in 2m23s. World executes 644 unit cases; Common retains 507 passing results. Account's unchanged integration results retain seven non-container passes and 255 skips; World executes one non-container case and skips 220 definitions without Docker. The new recovery positives use mocked owner clients and synthetic constructor-validated source evidence; the canonical-hold database definition stipulates lifecycle and Game Session terminal proof. Neither proves genuine cross-owner recovery or runtime scheduling. All receivers remain unregistered and all four complete Gameplay handoffs remain open. Source `17d3872f84358e0bae753620da578c818c503a46` [Validation run 38015116807](https://github.com/benhook1013/FireMUD/actions/runs/38015116807) completed red on synthetic merge `2af891e2352655ca2d33e191e461a1aa1ac79638`, tree `faafb0d3394a5f441e85ca3b54cd2761ca063359`, parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source; this is not the recorded integration parent. Account executes 261 integration cases with 230 failures, Game Design 151 with 15, World 220 with two and Game Logic nine with one, with zero skips. Account's V129-to-V130 installation and genuine composed fixtures stop at V130's PL/pgSQL inline `CASE` parse error before the intended assertions. The correction parenthesizes that expression without changing owner/purpose mapping, trailing-byte rejection or source protection; schema generation does not prove the ignored procedural block. Corrected physical execution remains required. World's 13 authored-source intake and five mTLS intake cases pass, and Common Data Runtime's check succeeds; the previous dependency-resolution failure does not recur. Game Logic counts originate in its HTML report because its XML capture skipped. The metadata-only duplicate run supplies no substantive proof, and the separate four V120 durability gaps remain open. @@ -48,7 +50,7 @@ Exact-source [Validation run 37992891243](https://github.com/benhook1013/FireMUD The previous capture/profile-only composed local gate passed Common, Account, Game Design and World checks, formatting, Checkstyle, SpotBugs, coverage, schema generation, links and Markdown: Common 479, Account 1,125, Game Design 539 and World 594 unit cases (2,737 total), with zero failures/errors/skips. Eight non-container integration cases executed; 606 integration cases skipped without Docker (240 Account, 148 Game Design, 218 World, including Redis definitions). These results do not replace the later sole-issuer composition or corrected-head physical PostgreSQL execution. Flyway sanity then passed 12 sets and 282 versioned files. Independent body-level preservation verified all 43 protected baseline and 25 frozen Gameplay migrations; the creator-party preservation test now isolates the actual V83-to-V84 upgrade. Parent review removed a nonexistent tuple-digest extraction that would have denied every genuine capture, retaining the separately derived snapshot/row digest binding. World paired graph/2 and graph/3 readback, phase-driven late-fence proof and Game Design safe commit diagnostics are included; the finalization root cause still needs executed physical diagnostics. -The distinct Entity/Automation preliminary source-read value binds closed owner-specific schema and purpose, exact Account operation/fence/request/actor, unchanged complete selected Draft evidence and the derived same-namespace Account reader. The six-family selected-source export constructor and exact repository accessor retain the original snapshot bytes, reject missing branding/template history and enforce the complete-content bound. Their focused structural proof does not authenticate disclosure, prove owner census/retention or create an owner receipt. A genuine selected-source repository test expansion is prepared; its PostgreSQL execution remains required. The authenticated selected-input transport, distinct Account reservation/finalization and source-writer/disclosure exclusion, actual owner census/retention and exact terminal settlement remain open. +The distinct Entity/Automation preliminary source-read value binds closed owner-specific schema and purpose, exact Account operation/fence/request/actor, unchanged complete selected Draft evidence and the derived same-namespace Account reader. The six-family selected-source export constructor and exact repository accessor retain the original snapshot bytes, reject missing branding/template history and enforce the complete-content bound. Preliminary permission has a separate unregistered Account receiver and authenticated mTLS client; Game Design confirms that permission before its source query. This bounded transport does not finalize owner retention or authenticate the six-family content return. A genuine selected-source repository test expansion is prepared; its PostgreSQL execution remains required. Complete authenticated selected-input transport, distinct Account finalization, through-commit source-writer/disclosure exclusion, actual owner census/retention and exact terminal settlement remain open. The local Account migration assembly preserves all 43 protected baseline files and the exact frozen V74–V98 source from Gameplay `1f074314528fef08bc552cab973ccfd1989c7051`, including both V98 disclosure TRUNCATE guards. Its former V98–V122 stages shift byte-exactly to V99–V123; the duplicate later disclosure creation is removed and V124–V127 remain preserved. The resulting 97 versions are unique, but fresh/upgrade physical execution of this composed ordering remains required. The current-committed-JTI actor prerequisite has ten executed local unit cases; Account's 1,122 unit cases and Common's 479 unit cases passed during a broader run that stopped on a duplicate fixture variable in Game Design, subsequently corrected. The integrity decoder and dormant StartSession storage no longer equate the capture source fence with the independent issuance fence; the consumer still exact-compares the complete reference. Full durable capture-before-private-crypto and genuine issuer/participation wiring remain open. World service-level authenticated recovery after ingress expiry remains open: authenticated original Account participation and Game Session attempt/fence evidence remain prerequisites, not optional verifier checks. diff --git a/protos/account/v1/selected_owner_intake_source_read_service.proto b/protos/account/v1/selected_owner_intake_source_read_service.proto new file mode 100644 index 0000000000..92661916d5 --- /dev/null +++ b/protos/account/v1/selected_owner_intake_source_read_service.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered preliminary Entity/Automation source-scope confirmation. +// This proof is not finalized retention authority or evidence of a complete source census. +service AccountSelectedOwnerIntakeSourceReadService { + rpc ReadSourceScope(SelectedOwnerIntakeSourcePermissionRequest) + returns (SelectedOwnerIntakeSourcePermissionResponse); +} + +message SelectedOwnerIntakeSourcePermissionRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intended_reader = 4; + string purpose = 5; + bytes preliminary_source_scope = 6; + string preliminary_scope_digest = 7; +} + +message SelectedOwnerIntakeSourcePermissionResponse { + SelectedOwnerIntakeSourcePermissionRequest request = 1; + bool permitted = 2; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcService.java new file mode 100644 index 0000000000..29c3b6a369 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcService.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadProtoCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Standalone preliminary Entity/Automation source permission receiver; never registered. */ +public final class AccountSelectedOwnerIntakeSourceReadGrpcService + extends AccountSelectedOwnerIntakeSourceReadServiceGrpc + .AccountSelectedOwnerIntakeSourceReadServiceImplBase { + private final AccountSelectedOwnerIntakeSourceReadService owner; + private final String namespace; + + public AccountSelectedOwnerIntakeSourceReadGrpcService( + AccountSelectedOwnerIntakeSourceReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-owner source reader is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readSourceScope( + SelectedOwnerIntakeSourcePermissionRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() > SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + final net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence + .Request + decoded; + try { + decoded = SelectedOwnerIntakeSourceReadProtoCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(decoded.targetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + try { + var confirmed = + owner.readSourceScope(decoded.scope(), decoded.intendedReader(), decoded.purpose()); + if (confirmed == null + || !java.util.Arrays.equals(decoded.scope().canonicalBytes(), confirmed.canonicalBytes()) + || !decoded.scope().digest().equals(confirmed.digest())) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + observer.onNext(SelectedOwnerIntakeSourceReadProtoCodec.toResponse(decoded)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + var code = Status.fromThrowable(failure).getCode(); + if (code == Status.Code.PERMISSION_DENIED || code == Status.Code.FAILED_PRECONDITION) { + observer.onError(Status.fromCode(code).asRuntimeException()); + } else { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } catch (IllegalArgumentException | IllegalStateException staleOrChanged) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java new file mode 100644 index 0000000000..7b9350cff7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java @@ -0,0 +1,296 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +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.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadProtoCodec; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** Synthetic transport tests; these do not establish mutual TLS or PostgreSQL runtime proof. */ +class AccountSelectedOwnerIntakeSourceReadGrpcServiceTest { + private static final int MAX_WIRE_BYTES = 8 * 1024 * 1024; + private static final int MAX_SCOPE_BYTES = 4 * 1024 * 1024; + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void authenticatesExactGameDesignPeerAndRejectsEndUserBeforeDecodingOrOwnerAccess() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + var malformed = + SelectedOwnerIntakeSourcePermissionRequest.newBuilder().setTargetNamespace("test").build(); + + var missing = new Collector(); + service.readSourceScope(malformed, missing); + assertThat(missing.error).isEqualTo(Status.Code.UNAUTHENTICATED); + + for (String caller : + List.of("account-service", "game-logic-service", "world-management-service")) { + var result = new Collector(); + peer("test", caller).run(() -> service.readSourceScope(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + var otherNamespace = new Collector(); + peer("other", "game-design-service") + .run(() -> service.readSourceScope(malformed, otherNamespace)); + assertThat(otherNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("44", List.of(), java.util.Map.of()); + try { + var endUser = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(malformed, endUser)); + assertThat(endUser.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + + var validPeerMalformed = new Collector(); + peer("test", "game-design-service") + .run(() -> service.readSourceScope(malformed, validPeerMalformed)); + assertThat(validPeerMalformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void confirmsEntityAndAutomationScopesAndEchoesTheExactRequest() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + when(owner.readSourceScope(any(), any(), any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + + for (var scope : + List.of( + scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT), + scope(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING))) { + var request = request(scope); + var result = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, result)); + + assertThat(result.error).isNull(); + assertThat(result.response).isNotNull(); + assertThat(result.response.getPermitted()).isTrue(); + assertThat(result.response.getRequest()).isEqualTo(request); + verify(owner).readSourceScope(scope, scope.intendedReader(), scope.purpose()); + } + } + + @Test + void rejectsWrongNamespaceBeforeOwnerAndRejectsWrongReaderPurposeOrDomain() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + var original = request(scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT)); + + var wrongNamespace = new Collector(); + peer("test", "game-design-service") + .run( + () -> + service.readSourceScope( + original.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + var wrongReader = + request(scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT)).toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") + .build(); + var readerResult = new Collector(); + peer("test", "game-design-service") + .run(() -> service.readSourceScope(wrongReader, readerResult)); + assertDeniedOrMalformed(readerResult); + + var wrongPurpose = + request(scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT)).toBuilder() + .setPurpose("AUTOMATION_INTAKE_SOURCE") + .build(); + var purposeResult = new Collector(); + peer("test", "game-design-service") + .run(() -> service.readSourceScope(wrongPurpose, purposeResult)); + assertDeniedOrMalformed(purposeResult); + + var wrongDomain = + request(scope(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING)).toBuilder() + .setPurpose("ENTITY_INTAKE_SOURCE") + .build(); + var domainResult = new Collector(); + peer("test", "game-design-service") + .run(() -> service.readSourceScope(wrongDomain, domainResult)); + assertDeniedOrMalformed(domainResult); + verifyNoInteractions(owner); + } + + @Test + void rejectsUnknownMalformedTamperedDigestAndOversizedWireRequests() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + var valid = request(scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT)); + var unknown = + valid.toBuilder() + .setPreliminarySourceScope(ByteString.copyFrom(new byte[] {0, 1, 2})) + .build(); + var badDigest = valid.toBuilder().setPreliminaryScopeDigest("0".repeat(64)).build(); + var oversizedScope = + valid.toBuilder() + .setPreliminarySourceScope(ByteString.copyFrom(new byte[MAX_SCOPE_BYTES + 1])) + .build(); + var oversized = + valid.toBuilder() + .setPreliminarySourceScope(ByteString.copyFrom(new byte[MAX_WIRE_BYTES + 1])) + .build(); + + for (var request : List.of(unknown, badDigest, oversizedScope, oversized)) { + var result = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, result)); + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(result.response).isNull(); + } + verifyNoInteractions(owner); + } + + @Test + void changedOwnerResponseAndStaleOrMissingEvidenceFailClosedWithSanitizedErrors() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + var original = scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT); + var request = request(original); + var changed = + new SelectedOwnerIntakeSourceReadScope( + original.owner(), + original.targetNamespace(), + UUID.randomUUID(), + original.fenceId(), + original.intakeRequestId(), + original.actorAccountId(), + original.selected()); + when(owner.readSourceScope(any(), any(), any())).thenReturn(changed); + var changedResult = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, changedResult)); + assertThat(changedResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + + doReturn(null).when(owner).readSourceScope(any(), any(), any()); + var missingResult = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, missingResult)); + assertThat(missingResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + + for (var failure : + List.of( + Status.FAILED_PRECONDITION.withDescription("credential-secret").asRuntimeException(), + new IllegalStateException("credential-secret"))) { + doThrow(failure).when(owner).readSourceScope(any(), any(), any()); + var result = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, result)); + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(result.errorDescription).isNull(); + } + } + + @Test + void returnsPermissionDenialWithoutLeakingOwnerExceptionDetails() { + var owner = mock(AccountSelectedOwnerIntakeSourceReadService.class); + var service = new AccountSelectedOwnerIntakeSourceReadGrpcService(owner, "test"); + var request = request(scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT)); + when(owner.readSourceScope(any(), any(), any())) + .thenThrow( + Status.PERMISSION_DENIED.withDescription("credential-secret").asRuntimeException()); + + var result = new Collector(); + peer("test", "game-design-service").run(() -> service.readSourceScope(request, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(result.errorDescription).isNull(); + } + + private static void assertDeniedOrMalformed(Collector result) { + assertThat(result.error).isIn(Status.Code.PERMISSION_DENIED, Status.Code.INVALID_ARGUMENT); + assertThat(result.response).isNull(); + } + + private static SelectedOwnerIntakeSourcePermissionRequest request( + SelectedOwnerIntakeSourceReadScope scope) { + return SelectedOwnerIntakeSourceReadProtoCodec.toRequest( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence + .Request.create(scope.targetNamespace(), scope)); + } + + private static SelectedOwnerIntakeSourceReadScope scope(DraftCommitBinding.Owner owner) { + UUID tenant = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID version = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + var selected = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 1, "tenant-key", 2, "tenant-key", "NEW_GAME_ROW"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + tenant.toString(), + "0"))); + return new SelectedOwnerIntakeSourceReadScope( + owner, + "test", + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.requestId(), + UUID.fromString("12121212-1212-4212-8212-121212121212"), + selected); + } + + private static Context peer(String namespace, String workload) { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + } + + private static final class Collector + implements StreamObserver { + Status.Code error; + String errorDescription; + SelectedOwnerIntakeSourcePermissionResponse response; + + @Override + public void onNext(SelectedOwnerIntakeSourcePermissionResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + errorDescription = Status.fromThrowable(failure).getDescription(); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java new file mode 100644 index 0000000000..b4e1179457 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/GrpcSelectedOwnerIntakeSourceReadClient.java @@ -0,0 +1,147 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for preliminary selected-owner source-scope confirmation. */ +public final class GrpcSelectedOwnerIntakeSourceReadClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedOwnerIntakeSourceReadServiceGrpc + .AccountSelectedOwnerIntakeSourceReadServiceBlockingStub> + implements SelectedOwnerIntakeSourceReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcSelectedOwnerIntakeSourceReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcSelectedOwnerIntakeSourceReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account selected-owner read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account selected-owner read stub unavailable"); + initialized = true; + } + + /** Returns Account's exact preliminary confirmation after authenticating its server identity. */ + @Override + public SelectedOwnerIntakeSourceReadEvidence read( + SelectedOwnerIntakeSourceReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Account selected-owner read must run outside SQL"); + Objects.requireNonNull(request, "source-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) + throw new IllegalArgumentException( + "Account selected-owner read must use the configured workload namespace"); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSourceScope(SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request)); + try { + return SelectedOwnerIntakeSourceReadProtoCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid preliminary selected-owner source-read evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedOwnerIntakeSourceReadServiceGrpc + .AccountSelectedOwnerIntakeSourceReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountSelectedOwnerIntakeSourceReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountSelectedOwnerIntakeSourceReadServiceGrpc + .AccountSelectedOwnerIntakeSourceReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) + throw new IllegalStateException( + "Account selected-owner read client is not initialized and available"); + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) + throw new IllegalArgumentException("Account selected-owner read requires workload mTLS"); + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) + throw new IllegalArgumentException( + "Account selected-owner read requires file-backed certificate, key, and CA material"); + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) + throw new IllegalArgumentException( + "Account selected-owner read requires file-backed certificate, key, and CA material"); + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account selected-owner read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) + throw new IllegalArgumentException( + "Account selected-owner read " + label + " must be an existing readable file"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClient.java new file mode 100644 index 0000000000..00fa374152 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClient.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.common.account.sourceintake; + +/** Dedicated Account confirmation of a preliminary selected-owner source-read scope. */ +public interface SelectedOwnerIntakeSourceReadClient { + SelectedOwnerIntakeSourceReadEvidence read(SelectedOwnerIntakeSourceReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadEvidence.java new file mode 100644 index 0000000000..1d8b44177f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadEvidence.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Preliminary Account confirmation of the exact Entity/Automation source-read scope. */ +public record SelectedOwnerIntakeSourceReadEvidence(Request request) { + public static final int SCHEMA_VERSION = 1; + + public SelectedOwnerIntakeSourceReadEvidence { + Objects.requireNonNull(request, "source-read request is required"); + } + + /** + * This request transports integrity input only; it does not assert finalized retention rights. + */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + String intendedReader, + String purpose, + SelectedOwnerIntakeSourceReadScope scope) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || scope == null) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + if ((scope.owner() != Owner.ENTITY_MANAGEMENT && scope.owner() != Owner.AUTOMATION_SCRIPTING) + || !targetNamespace.equals(scope.targetNamespace()) + || !scope.intendedReader().equals(intendedReader) + || !scope.purpose().equals(purpose)) { + throw invalid(); + } + if (readRequestId.equals(scope.operationId()) + || readRequestId.equals(scope.fenceId()) + || readRequestId.equals(scope.intakeRequestId()) + || readRequestId.equals(scope.actorAccountId()) + || readRequestId.equals(scope.selected().requestId()) + || readRequestId.equals(scope.selected().commitId())) { + throw invalid(); + } + } + + public static Request create(String namespace, SelectedOwnerIntakeSourceReadScope scope) { + Objects.requireNonNull(scope, "source-read scope is required"); + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (sameIdentity(readRequestId, scope)); + return new Request( + SCHEMA_VERSION, namespace, readRequestId, scope.intendedReader(), scope.purpose(), scope); + } + + private static boolean sameIdentity(UUID candidate, SelectedOwnerIntakeSourceReadScope scope) { + return candidate.equals(scope.operationId()) + || candidate.equals(scope.fenceId()) + || candidate.equals(scope.intakeRequestId()) + || candidate.equals(scope.actorAccountId()) + || candidate.equals(scope.selected().requestId()) + || candidate.equals(scope.selected().commitId()); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid preliminary selected-owner source-read evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodec.java new file mode 100644 index 0000000000..f57d97132f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodec.java @@ -0,0 +1,91 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed preliminary source-scope wire mapping and exact Account echo validation. */ +public final class SelectedOwnerIntakeSourceReadProtoCodec { + public static final int MAX_WIRE_BYTES = 8 * 1024 * 1024; + + private SelectedOwnerIntakeSourceReadProtoCodec() {} + + public static SelectedOwnerIntakeSourcePermissionRequest toRequest( + SelectedOwnerIntakeSourceReadEvidence.Request request) { + Objects.requireNonNull(request, "source-read request is required"); + var wire = + SelectedOwnerIntakeSourcePermissionRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setPurpose(request.purpose()) + .setPreliminarySourceScope(ByteString.copyFrom(request.scope().canonicalBytes())) + .setPreliminaryScopeDigest(request.scope().digest()) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static SelectedOwnerIntakeSourceReadEvidence.Request fromRequest( + SelectedOwnerIntakeSourcePermissionRequest request) { + requireKnownAndWithinBudget(request); + DraftAuthorizationFenceBinding.canonicalUuid(request.getReadRequestId()); + var scope = + SelectedOwnerIntakeSourceReadScope.fromStored( + request.getPreliminarySourceScope().toByteArray()); + if (!scope.digest().equals(request.getPreliminaryScopeDigest())) + throw invalid("Changed preliminary source-scope digest"); + return new SelectedOwnerIntakeSourceReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getReadRequestId()), + request.getIntendedReader(), + request.getPurpose(), + scope); + } + + public static SelectedOwnerIntakeSourcePermissionResponse toResponse( + SelectedOwnerIntakeSourceReadEvidence.Request request) { + var wire = + SelectedOwnerIntakeSourcePermissionResponse.newBuilder() + .setRequest(toRequest(request)) + .setPermitted(true) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static SelectedOwnerIntakeSourceReadEvidence fromResponse( + SelectedOwnerIntakeSourceReadEvidence.Request request, + SelectedOwnerIntakeSourcePermissionResponse response) { + Objects.requireNonNull(request, "source-read request is required"); + requireKnownAndWithinBudget(response); + if (!response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || !response.getPermitted()) { + throw invalid("Exact permitted Account source-scope confirmation required"); + } + return new SelectedOwnerIntakeSourceReadEvidence(request); + } + + private static void requireKnownAndWithinBudget(Message wire) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) + throw invalid("Missing or oversized selected-owner source-read message"); + if (!wire.getUnknownFields().asMap().isEmpty()) + throw invalid("Unknown selected-owner source-read fields"); + } + + private static void requireWithinBudget(int size) { + if (size > MAX_WIRE_BYTES) + throw invalid("Selected-owner source-read message exceeds the 8 MiB wire budget"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java new file mode 100644 index 0000000000..3ce2d53d90 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java @@ -0,0 +1,529 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeSourceReadServiceGrpc; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSourcePermissionResponse; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic scopes exercise client mTLS and correlation, not Account database/source proof. */ +class SelectedOwnerIntakeSourceReadClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_SERVER_URI = "spiffe://firemud/ns/test/sa/game-logic-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private final AtomicInteger calls = new AtomicInteger(); + private Server server; + private boolean stall; + private boolean substitute; + + @BeforeAll + static void certificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void closeServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + TransactionSynchronizationManager.clear(); + } + + @Test + void pinsAccountServerAndRoundTripsBothPreliminaryOwnerScopes() throws Exception { + start(pki.accountServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + for (var owner : + List.of( + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + DraftCommitBinding.Owner.AUTOMATION_SCRIPTING)) { + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(owner, NAMESPACE)); + assertThat(client.read(request).request()).isEqualTo(request); + } + assertThat(calls).hasValue(2); + } + + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + start(pki.wrongServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT, NAMESPACE)); + assertThatThrownBy(() -> client.read(request)).isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(2); + } + } + + @Test + void transportsNearFourMiBCanonicalScopeAndEchoWithinEightMiBWireBudget() throws Exception { + var scope = scopeAtCanonicalLimit(); + assertThat(scope.canonicalBytes().length) + .isGreaterThan(SelectedOwnerIntakeSourceReadScope.MAX_BYTES - 16) + .isLessThanOrEqualTo(SelectedOwnerIntakeSourceReadScope.MAX_BYTES); + var request = SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope); + assertThat(SelectedOwnerIntakeSourceReadProtoCodec.toResponse(request).getSerializedSize()) + .isGreaterThan(4 * 1024 * 1024) + .isLessThanOrEqualTo(SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES); + + start(pki.accountServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + assertThat(client.read(request).request()).isEqualTo(request); + } + } + + @Test + void rejectsOtherNamespaceAmbientSqlAndSubstitutedResponse() throws Exception { + start(pki.accountServer()); + substitute = true; + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + var otherNamespace = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + "other", scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT, "other")); + assertThatThrownBy(() -> client.read(otherNamespace)) + .isInstanceOf(IllegalArgumentException.class); + + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT, NAMESPACE)); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + assertThat(calls).hasValue(1); + } + } + + @Test + void boundsUnavailableAccountReadByFiveSecondDeadline() throws Exception { + stall = true; + start(pki.accountServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, NAMESPACE)); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + } + + @Test + void requiresTlsAndReadableFileBackedCredentials() { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSourceReadClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSourceReadClient( + endpoints, + new CommonGrpcClientProperties(), + new GrpcChannelFactory(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + private void start(TestIdentity identity) throws Exception { + var service = + new AccountSelectedOwnerIntakeSourceReadServiceGrpc + .AccountSelectedOwnerIntakeSourceReadServiceImplBase() { + @Override + public void readSourceScope( + SelectedOwnerIntakeSourcePermissionRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + if (!GAME_DESIGN_URI.equals(GrpcPeerIdentity.current().uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (stall) return; + var request = SelectedOwnerIntakeSourceReadProtoCodec.fromRequest(wire); + var response = SelectedOwnerIntakeSourceReadProtoCodec.toResponse(request); + if (substitute) { + response = + response.toBuilder() + .setRequest( + wire.toBuilder().setReadRequestId(UUID.randomUUID().toString()).build()) + .build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcSelectedOwnerIntakeSourceReadClient newClient(TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new GrpcSelectedOwnerIntakeSourceReadClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + DraftCommitBinding.Owner owner, String namespace) { + return scope(owner, namespace, "{}"); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + DraftCommitBinding.Owner owner, String namespace, String revisionPayload) { + UUID tenant = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + var selected = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + 1L, + "tenant-key", + 2L, + "tenant-key", + "NEW_GAME_ROW"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + revisionPayload)), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + tenant.toString(), + "0"))); + return new SelectedOwnerIntakeSourceReadScope( + owner, + namespace, + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.requestId(), + UUID.fromString("12121212-1212-4212-8212-121212121212"), + selected); + } + + private static SelectedOwnerIntakeSourceReadScope scopeAtCanonicalLimit() { + int lower = 0; + int upper = SelectedOwnerIntakeSourceReadScope.MAX_BYTES; + while (lower < upper) { + int candidate = lower + (upper - lower + 1) / 2; + try { + scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT, NAMESPACE, "x".repeat(candidate)); + lower = candidate; + } catch (IllegalArgumentException tooLarge) { + upper = candidate - 1; + } + } + return scope(DraftCommitBinding.Owner.ENTITY_MANAGEMENT, NAMESPACE, "x".repeat(lower)); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity accountServer, + TestIdentity wrongServer, + TestIdentity gameDesignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("selected-owner-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD selected-owner test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("selected-owner-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-server", WRONG_SERVER_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("selected-owner-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java new file mode 100644 index 0000000000..0366f41ff1 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java @@ -0,0 +1,224 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Synthetic canonical scopes exercise the wire boundary, not Account or owner-source proof. */ +class SelectedOwnerIntakeSourceReadProtoCodecTest { + private static final String NAMESPACE = "test"; + + @Test + void roundTripsEntityAndAutomationScopesWithIndependentCorrelationsAndExactEchoes() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var request = SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope(owner)); + var wire = SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request); + + assertThat(SelectedOwnerIntakeSourceReadProtoCodec.fromRequest(wire)).isEqualTo(request); + assertThat(wire.getPreliminaryScopeDigest()).isEqualTo(request.scope().digest()); + assertThat(request.readRequestId()) + .isNotIn( + request.scope().operationId(), + request.scope().fenceId(), + request.scope().intakeRequestId(), + request.scope().actorAccountId(), + request.scope().selected().requestId(), + request.scope().selected().commitId()); + var response = SelectedOwnerIntakeSourceReadProtoCodec.toResponse(request); + assertThat(SelectedOwnerIntakeSourceReadProtoCodec.fromResponse(request, response).request()) + .isEqualTo(request); + } + } + + @Test + void rejectsUnsupportedSchemaWrongDomainNamespaceReaderPurposeAndCorrelation() { + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(Owner.ENTITY_MANAGEMENT)); + var wire = SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setSchemaVersion(2).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setTargetNamespace("other").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setPurpose("AUTOMATION_INTAKE_SOURCE").build())) + .isInstanceOf(IllegalArgumentException.class); + for (UUID reusedIdentity : + List.of( + request.scope().operationId(), + request.scope().fenceId(), + request.scope().intakeRequestId(), + request.scope().actorAccountId(), + request.scope().selected().requestId(), + request.scope().selected().commitId())) { + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setReadRequestId(reusedIdentity.toString()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setReadRequestId("00000000-0000-0000-0000-000000000000") + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMissingUnknownOversizedAndDigestSubstitutedRequests() { + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(Owner.AUTOMATION_SCRIPTING)); + var wire = SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().clearPreliminarySourceScope().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setPreliminaryScopeDigest("sha256:" + "0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setPreliminarySourceScope(ByteString.copyFrom(new byte[] {1})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknownField()).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setPurpose( + "x".repeat(SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresACompletePermittedAndUnmodifiedResponseEcho() { + var request = + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, scope(Owner.ENTITY_MANAGEMENT)); + var wire = SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request); + var response = SelectedOwnerIntakeSourceReadProtoCodec.toResponse(request); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, + response.toBuilder() + .setRequest(wire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().setPermitted(false).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().clearRequest().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknownField()).build())) + .isInstanceOf(IllegalArgumentException.class); + var oversizedResponseUnknownFields = + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES])) + .build()) + .build(); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, + response.toBuilder().setUnknownFields(oversizedResponseUnknownFields).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SelectedOwnerIntakeSourceReadScope scope(Owner owner) { + UUID tenant = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + var selected = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + 1L, + "tenant-key", + 2L, + "tenant-key", + "NEW_GAME_ROW"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + tenant.toString(), + "0"))); + return new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + UUID.fromString("99999999-9999-4999-8999-999999999999"), + selected.requestId(), + UUID.fromString("12121212-1212-4212-8212-121212121212"), + selected); + } + + private static UnknownFieldSet unknownField() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java new file mode 100644 index 0000000000..4624f10a27 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered selected-owner source read that obtains exact Account permission before opening the + * independent Game Design source transaction. + */ +public final class GameDesignSelectedOwnerIntakeSourceReadService { + private final GameDesignSourceRepository repository; + private final SelectedOwnerIntakeSourceReadClient permissions; + private final String namespace; + private final TransactionTemplate transaction; + + public GameDesignSelectedOwnerIntakeSourceReadService( + GameDesignSourceRepository repository, + PlatformTransactionManager transactions, + SelectedOwnerIntakeSourceReadClient permissions, + String namespace) { + this.repository = Objects.requireNonNull(repository, "source repository is required"); + this.permissions = Objects.requireNonNull(permissions, "Account permission client is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.namespace = namespace; + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + } + + public SelectedOwnerIntakeSourceExport readSource(SelectedOwnerIntakeSourceReadScope scope) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + if (scope == null || !namespace.equals(scope.targetNamespace())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + if (!scope.intendedReader().equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent Game Design owner read required") + .asRuntimeException(); + } + + var permissionRequest = SelectedOwnerIntakeSourceReadEvidence.Request.create(namespace, scope); + var permission = permissions.read(permissionRequest); + if (permission == null || !permissionRequest.equals(permission.request())) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact Account source permission required") + .asRuntimeException(); + } + + return transaction.execute( + ignored -> { + var exported = repository.requireSelectedOwnerIntakeSource(scope); + if (exported == null + || !Arrays.equals(scope.canonicalBytes(), exported.scope().canonicalBytes()) + || !scope.digest().equals(exported.scope().digest())) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected owner source scope differs") + .asRuntimeException(); + } + byte[] canonicalBytes = exported.canonicalBytes(); + if (!DraftAuthorizationFenceBinding.digest(canonicalBytes).equals(exported.digest())) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected owner source export digest differs") + .asRuntimeException(); + } + return exported; + }); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java new file mode 100644 index 0000000000..6d079a3010 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadServiceTest.java @@ -0,0 +1,288 @@ +package net.firedevops.firemud.gamedesign.publication; + +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.when; + +import io.grpc.Context; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameDesignSelectedOwnerIntakeSourceReadServiceTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_PEER = "spiffe://firemud/ns/test/sa/account-service"; + private static final UUID GENESIS = UUID.randomUUID(); + + @AfterEach + void clearCallerAndTransactionContext() { + SessionContext.clear(); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void readsCompleteSelectedSourceForEntityAndAutomationOnlyAfterExactPermission() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var repository = mock(GameDesignSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + when(transactions.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); + var permissions = + mock( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + .class); + org.mockito.Mockito.doAnswer( + invocation -> new SelectedOwnerIntakeSourceReadEvidence(invocation.getArgument(0))) + .when(permissions) + .read(any()); + + var binding = binding(); + var scope = scope(owner, binding); + var export = SelectedOwnerIntakeSourceExport.create(scope, sources(binding)); + when(repository.requireSelectedOwnerIntakeSource(scope)).thenReturn(export); + var service = service(repository, transactions, permissions); + + var result = + new java.util.concurrent.atomic.AtomicReference(); + asAccount(() -> result.set(service.readSource(scope))); + + assertThat(result.get()).isSameAs(export); + assertThat(result.get().scope().canonicalBytes()).isEqualTo(scope.canonicalBytes()); + assertThat(result.get().scope().digest()).isEqualTo(scope.digest()); + assertThat(result.get().canonicalBytes()).isNotEmpty(); + assertThat(result.get().digest()).isNotBlank(); + var ordered = org.mockito.Mockito.inOrder(permissions, transactions, repository); + ordered.verify(permissions).read(any()); + ordered.verify(transactions).getTransaction(any()); + ordered.verify(repository).requireSelectedOwnerIntakeSource(scope); + } + } + + @Test + void rejectsMissingOrSubstitutedPermissionBeforeOpeningTheSourceTransaction() { + var binding = binding(); + var scope = scope(Owner.ENTITY_MANAGEMENT, binding); + + assertPermissionDeniedBeforeQuery(scope, null); + assertPermissionDeniedBeforeQuery( + scope, + request -> + new SelectedOwnerIntakeSourceReadEvidence( + new SelectedOwnerIntakeSourceReadEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + UUID.randomUUID(), + request.intendedReader(), + request.purpose(), + request.scope()))); + assertPermissionDeniedBeforeQuery( + scope, + request -> + new SelectedOwnerIntakeSourceReadEvidence( + SelectedOwnerIntakeSourceReadEvidence.Request.create( + request.targetNamespace(), + scope(Owner.AUTOMATION_SCRIPTING, request.scope().selected())))); + } + + @Test + void authenticatesAccountPeerAndRejectsEndUserContextBeforePermissionOrStorage() { + var scope = scope(Owner.ENTITY_MANAGEMENT, binding()); + var repository = mock(GameDesignSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var permissions = + mock( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + .class); + var service = service(repository, transactions, permissions); + + assertThatThrownBy(() -> service.readSource(scope)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + asPeer("spiffe://firemud/ns/test/sa/game-design-service", () -> denied(service, scope)); + asPeer("spiffe://firemud/ns/other/sa/account-service", () -> denied(service, scope)); + SessionContext.setContext("123", List.of(), java.util.Map.of()); + asAccount(() -> denied(service, scope)); + assertNoPermissionOrQuery(permissions, transactions, repository); + } + + @Test + void rejectsNamespaceMismatchAndAmbientTransactionOrSynchronizationBeforePermission() { + var repository = mock(GameDesignSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var permissions = + mock( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + .class); + var service = service(repository, transactions, permissions); + var scope = scope(Owner.ENTITY_MANAGEMENT, binding()); + var wrongNamespace = + new SelectedOwnerIntakeSourceReadScope( + Owner.ENTITY_MANAGEMENT, + "other", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + scope.selected()); + + asAccount(() -> denied(service, wrongNamespace)); + TransactionSynchronizationManager.setActualTransactionActive(true); + asAccount(() -> denied(service, scope)); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + asAccount(() -> denied(service, scope)); + assertNoPermissionOrQuery(permissions, transactions, repository); + } + + @Test + void rejectsRepositoryExportForAnotherExactScope() { + var repository = mock(GameDesignSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + when(transactions.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); + var permissions = + mock( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + .class); + org.mockito.Mockito.doAnswer( + invocation -> new SelectedOwnerIntakeSourceReadEvidence(invocation.getArgument(0))) + .when(permissions) + .read(any()); + var binding = binding(); + var scope = scope(Owner.ENTITY_MANAGEMENT, binding); + var substitutedScope = + new SelectedOwnerIntakeSourceReadScope( + Owner.ENTITY_MANAGEMENT, + NAMESPACE, + UUID.randomUUID(), + scope.fenceId(), + scope.intakeRequestId(), + scope.actorAccountId(), + binding); + when(repository.requireSelectedOwnerIntakeSource(scope)) + .thenReturn(SelectedOwnerIntakeSourceExport.create(substitutedScope, sources(binding))); + var service = service(repository, transactions, permissions); + + assertThatThrownBy(() -> asAccount(() -> service.readSource(scope))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verify(permissions).read(any()); + org.mockito.Mockito.verify(transactions).getTransaction(any()); + org.mockito.Mockito.verify(repository).requireSelectedOwnerIntakeSource(scope); + } + + private static void assertPermissionDeniedBeforeQuery( + SelectedOwnerIntakeSourceReadScope scope, + java.util.function.Function< + SelectedOwnerIntakeSourceReadEvidence.Request, SelectedOwnerIntakeSourceReadEvidence> + response) { + var repository = mock(GameDesignSourceRepository.class); + var transactions = mock(PlatformTransactionManager.class); + var permissions = + mock( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + .class); + if (response == null) { + org.mockito.Mockito.doReturn(null).when(permissions).read(any()); + } else { + org.mockito.Mockito.doAnswer(invocation -> response.apply(invocation.getArgument(0))) + .when(permissions) + .read(any()); + } + var service = service(repository, transactions, permissions); + + assertThatThrownBy(() -> asAccount(() -> service.readSource(scope))) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + org.mockito.Mockito.verify(permissions).read(any()); + org.mockito.Mockito.verifyNoInteractions(transactions, repository); + } + + private static void assertNoPermissionOrQuery( + Object permissions, Object transactions, Object repository) { + org.mockito.Mockito.verifyNoInteractions(permissions, transactions, repository); + } + + private static void denied( + GameDesignSelectedOwnerIntakeSourceReadService service, + SelectedOwnerIntakeSourceReadScope scope) { + assertThatThrownBy(() -> service.readSource(scope)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + } + + private static GameDesignSelectedOwnerIntakeSourceReadService service( + GameDesignSourceRepository repository, + PlatformTransactionManager transactions, + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadClient + permissions) { + return new GameDesignSelectedOwnerIntakeSourceReadService( + repository, transactions, permissions, NAMESPACE); + } + + private static GameDesignSourceRepository.SynchronizedSources sources( + DraftCommitBinding binding) { + var command = new CommandSnapshot(binding, "0", null, "sha256:" + "a".repeat(64), List.of()); + var policy = new RealmPolicySnapshot(binding, "0", List.of()); + var asset = new AssetSnapshot(binding, "0", null, GENESIS, List.of()); + var gameplay = new GameplayRuleSnapshot(binding, "0", null, GENESIS, List.of()); + var branding = new BrandingSourceSnapshot(binding, "0", null, GENESIS, List.of()); + var template = new TemplateConfigSourceSnapshot(binding, "0", null, GENESIS, List.of()); + return new GameDesignSourceRepository.SynchronizedSources( + command, policy, asset, gameplay, Optional.of(branding), Optional.of(template)); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + Owner owner, DraftCommitBinding selected) { + return new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + selected); + } + + private static DraftCommitBinding binding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + target.canonicalVersionId().toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static void asAccount(Runnable action) { + asPeer(ACCOUNT_PEER, action); + } + + private static void asPeer(String uri, Runnable action) { + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()) + .run(action); + } +} From b44b04c9673e32d54ac2576988285617c9500ea4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:34:03 +1300 Subject: [PATCH 072/129] Carry complete authenticated selected-owner source content --- .../game-design-service/api-contracts.md | 4 + ...ame-authoring-publishing-and-activation.md | 4 + ...selected_owner_intake_source_service.proto | 27 + .../GrpcSelectedOwnerIntakeSourceClient.java | 149 ++++ .../SelectedOwnerIntakeSourceClient.java | 8 + .../SelectedOwnerIntakeSourceContent.java | 186 +++++ .../SelectedOwnerIntakeSourceProtoCodec.java | 120 ++++ ...lectedOwnerIntakeSourceClientMtlsTest.java | 657 ++++++++++++++++++ .../SelectedOwnerIntakeSourceContentTest.java | 360 ++++++++++ ...lectedOwnerIntakeSourceProtoCodecTest.java | 306 ++++++++ ...nSelectedOwnerIntakeSourceGrpcService.java | 89 +++ ...ectedOwnerIntakeSourceGrpcServiceTest.java | 233 +++++++ .../SelectedOwnerIntakeSourceExportTest.java | 38 +- 13 files changed, 2177 insertions(+), 4 deletions(-) create mode 100644 protos/game-design/v1/selected_owner_intake_source_service.proto create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcService.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 4f129acfbf..03df62f6de 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -77,6 +77,10 @@ For distinct Entity and Automation intake, the complete Game Design selected-sou The separate preliminary owner-read composition accepts only the exact same-namespace Account workload without end-user context. It obtains the [Account-owned preliminary permission confirmation](../account-service/api-contracts.md#grpc-apis) outside SQL, compares the complete original request and independent correlation, then opens its own source transaction and reads all six families for the unchanged selected binding. Failed, absent or substituted confirmation returns no content and performs no source query. The resulting export must retain the exact original scope. This unregistered composition does not expand `ReadSelectedGameplayRuleSource`, supply a finalized owner grant or register the still-required selected-content transport; its proof and remaining producer/consumer gaps belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The distinct [`GameDesignSelectedOwnerIntakeSourceService.ReadSelectedSource`](../../../../protos/game-design/v1/selected_owner_intake_source_service.proto) carries that complete selected content without expanding the Gameplay Rule method's caller policy. Its closed schema-version-1 request binds the namespace, independent nonzero read correlation, derived same-namespace Account reader, owner-specific purpose and complete preliminary scope bytes/digest. The configured Account workload must be authenticated, without end-user context, before parsing or any source query. Game Design obtains its own exact Account preliminary confirmation before disclosure, then returns the unchanged complete request and the original six-family bytes and digest. The canonical content limit remains 8 MiB; the separate request/response wire limit is 16 MiB to carry content, the bounded 4 MiB scope echo and framing, without changing global gRPC limits. The file-backed client authenticates the exact same-namespace Game Design server, applies a five-second deadline, and rejects ambient SQL and transaction synchronization. + +The shared content decoder rejects changed scope, family order, family bytes/digests, selected binding, framing, canonical JSON or trailing bytes. All six snapshots must retain their exact selected Draft binding. Game Design remains the semantic owner for command, realm-policy, asset and branding snapshots; their consumer representation preserves original bytes rather than copying their grammars into another authority. Existing shared Gameplay Rule and Template Configuration parsers retain their applicable complete typed checks. Valid stored template v1/v2 content is not proof of a complete fresh Entity/Automation inventory. This transport and decoder neither finalize Account retention permission nor prove owner census, emptiness, receipt or settlement; production registration and acceptance remain denied until those producer/consumer boundaries and their focused proof are complete. + ## Exact Publication Terminal Read `GameDesignPublicationTerminalReadService.ReadPublicationTerminal` reads the original immutable terminal result, not current permission or a new publication attempt. Its closed version-1 request binds the canonical workload namespace, a non-nil canonical read-request UUID and the complete original `game-design-publication-operation/v1` bytes. The receiver authenticates the exact same-namespace Account or World Management workload before decoding input or accessing storage. 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 d02f1711e3..f72c1b3806 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The complete selected-owner content value, closed Game Design RPC, exact request echo and file-backed mTLS client pass the affected Common/Game Design full checks, Game Design boot JAR, links and Markdown in 2m33s. Common has 535 passing unit cases and Game Design 549, with zero failures, errors or unit skips; successful unchanged tasks reuse their results. All 148 Game Design integration definitions skip without Docker. Nineteen new Common cases cover content integrity, closed wire mapping and synthetic mTLS; five new Game Design cases cover the guarded receiver and actual six-family export constructors for both owners. These establish bounded transport/integrity and constructor compatibility, not genuine Account permission followed by authenticated database-backed disclosure, complete owner inventory or final retention receipts. All components remain unregistered; Account finalization, Entity/Automation census and terminal settlement remain open. + +The earlier source `b2a` [Validation run 38018179856](https://github.com/benhook1013/FireMUD/actions/runs/38018179856) was cancelled and its required gate failed. Originating World XML nevertheless records 221 integration executions with zero failures, errors or skips; 173 cases are in explicitly PostgreSQL-named suites, and their logs establish the assembled Account migrations through V130. This does not establish genuine cross-owner admission. The cancelled Account job logged 13 failures without uploading complete XML: eight original operator-issuance fixture failures and five confirmation cases, including a changed-binding case that fails before its intended assertion. Game Design logged one genuine selected-export publication failure before cancellation. Their deeper causes and complete execution totals are not established by those logs; these remain open, rather than being credited as completed physical proof or all attributed to the four older V120 durability gaps. Actual merge `f0fa86a46cdc5494e651f0cc0654a2dfbdb97111`, tree `6ba462f99cd7dd4cf5fa9ff49bfba7b606807f9b`, uses parent `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source, not the recorded integration parent. + The preliminary Entity/Automation source-permission transport and Game Design permission-before-query composition pass the affected Common/Account/Game Design full-check gate in 2m30s, including affected boot JARs, formatting, static checks, coverage, links and Markdown. The exact same-namespace Game Design caller is authenticated before Account decoding or storage; the file-backed client authenticates Account, compares the full unchanged echo and performs no network call under SQL or transaction synchronization. Game Design obtains that confirmation outside SQL before opening its independent six-family source transaction. Common retains 516 passing unit results and Game Design 544; Account executes 1,236 unit cases, all without failures, errors or unit skips. The nine new Common codec/mTLS cases and five Game Design ordering cases passed in the first run and remain unchanged; the corrected six Account receiver cases pass in this gate. Account retains seven non-container integration passes and skips 255 definitions; Game Design skips all 148 definitions without Docker. Loopback mTLS uses a synthetic Account handler, while receiver and transaction-order tests use mocked owners: none establishes genuine Account-to-Game Design source disclosure, finalized owner retention, Entity/Automation census or terminal receipts. The selected-content transport and complete finalization/settlement remain open; all new components remain unregistered. The corrected World historical-recovery and canonical-hold reconciliation batch passes the affected Common/World full checks, Account schema generation and integration compilation, World boot JAR, formatting, static checks, coverage, links and Markdown in 2m23s. World executes 644 unit cases; Common retains 507 passing results. Account's unchanged integration results retain seven non-container passes and 255 skips; World executes one non-container case and skips 220 definitions without Docker. The new recovery positives use mocked owner clients and synthetic constructor-validated source evidence; the canonical-hold database definition stipulates lifecycle and Game Session terminal proof. Neither proves genuine cross-owner recovery or runtime scheduling. All receivers remain unregistered and all four complete Gameplay handoffs remain open. diff --git a/protos/game-design/v1/selected_owner_intake_source_service.proto b/protos/game-design/v1/selected_owner_intake_source_service.proto new file mode 100644 index 0000000000..c3947bcae8 --- /dev/null +++ b/protos/game-design/v1/selected_owner_intake_source_service.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package game_design.v1; +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Standalone, unregistered transport for complete selected-owner source content. +service GameDesignSelectedOwnerIntakeSourceService { + rpc ReadSelectedSource(SelectedOwnerIntakeSourceRequest) + returns (SelectedOwnerIntakeSourceResponse); +} + +message SelectedOwnerIntakeSourceRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intended_reader = 4; + string purpose = 5; + bytes preliminary_source_scope = 6; + string preliminary_scope_digest = 7; +} + +message SelectedOwnerIntakeSourceResponse { + SelectedOwnerIntakeSourceRequest request = 1; + bytes selected_source_content = 2; + string selected_source_digest = 3; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java new file mode 100644 index 0000000000..7cb2563ed6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcSelectedOwnerIntakeSourceClient.java @@ -0,0 +1,149 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +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.GameDesignSelectedOwnerIntakeSourceServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for complete selected-owner source content. */ +public final class GrpcSelectedOwnerIntakeSourceClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignSelectedOwnerIntakeSourceServiceGrpc + .GameDesignSelectedOwnerIntakeSourceServiceBlockingStub> + implements SelectedOwnerIntakeSourceClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcSelectedOwnerIntakeSourceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcSelectedOwnerIntakeSourceClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Game Design source client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) throw new IllegalStateException("Game Design source stub unavailable"); + initialized = true; + } + + /** Reads exact selected source content after authenticating the configured Game Design peer. */ + @Override + public SelectedOwnerIntakeSourceContent read( + SelectedOwnerIntakeSourceReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException( + "Game Design selected-owner source read must run outside SQL"); + Objects.requireNonNull(request, "selected-owner source-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) + throw new IllegalArgumentException( + "Game Design selected-owner source read must use the configured workload namespace"); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedSource(SelectedOwnerIntakeSourceProtoCodec.toRequest(request)); + try { + return SelectedOwnerIntakeSourceProtoCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid selected-owner source content", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignSelectedOwnerIntakeSourceServiceGrpc + .GameDesignSelectedOwnerIntakeSourceServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignSelectedOwnerIntakeSourceServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignSelectedOwnerIntakeSourceServiceGrpc + .GameDesignSelectedOwnerIntakeSourceServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) + throw new IllegalStateException( + "Game Design selected-owner source client is not initialized and available"); + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) + throw new IllegalArgumentException( + "Game Design selected-owner source requires workload mTLS"); + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) + throw new IllegalArgumentException( + "Game Design selected-owner source requires file-backed certificate, key, and CA material"); + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) + throw new IllegalArgumentException( + "Game Design selected-owner source requires file-backed certificate, key, and CA material"); + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Design selected-owner source " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) + throw new IllegalArgumentException( + "Game Design selected-owner source " + label + " must be an existing readable file"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClient.java new file mode 100644 index 0000000000..29dfd28e51 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClient.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.common.gamedesign; + +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; + +/** Reads complete immutable selected-owner source content from Game Design. */ +public interface SelectedOwnerIntakeSourceClient { + SelectedOwnerIntakeSourceContent read(SelectedOwnerIntakeSourceReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java new file mode 100644 index 0000000000..2c19fb4789 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java @@ -0,0 +1,186 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** + * Exact six-family Game Design source content bound to one selected-owner preliminary scope. + * + *

Decoding checks framing, hashes, canonical JSON bindings and the existing typed gameplay-rule + * and template-config sources. It does not authenticate disclosure, grant finalization or retention + * authority, prove an owner inventory complete or empty, or create an owner receipt. Template + * snapshot v1/v2 parsing retains the stored grammar but does not prove a fresh authored inventory. + * Four source families remain opaque beyond their canonical JSON binding to the selected Draft. + */ +public final class SelectedOwnerIntakeSourceContent { + public static final String DOMAIN = "game-design-selected-owner-intake-source/v1"; + public static final int MAX_BYTES = 8 * 1024 * 1024; + + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final List FAMILIES = + List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG"); + + private final SelectedOwnerIntakeSourceReadScope scope; + private final byte[] canonicalBytes; + private final String digest; + private final Map snapshots; + private final GameplayRuleSelectedSource gameplaySource; + private final TemplateConfigSourceSnapshot templateConfigSource; + + private SelectedOwnerIntakeSourceContent( + SelectedOwnerIntakeSourceReadScope scope, + byte[] canonicalBytes, + String digest, + Map snapshots, + GameplayRuleSelectedSource gameplaySource, + TemplateConfigSourceSnapshot templateConfigSource) { + this.scope = scope; + this.canonicalBytes = canonicalBytes.clone(); + this.digest = digest; + var copiedSnapshots = new LinkedHashMap(); + for (String family : FAMILIES) copiedSnapshots.put(family, snapshots.get(family).clone()); + this.snapshots = Map.copyOf(copiedSnapshots); + this.gameplaySource = gameplaySource; + this.templateConfigSource = templateConfigSource; + } + + /** + * Decodes exact persisted content against the independently expected preliminary scope and + * content digest. This value is integrity evidence only; it is not an authority grant. + */ + public static SelectedOwnerIntakeSourceContent fromStored( + byte[] bytes, SelectedOwnerIntakeSourceReadScope expectedScope, String expectedDigest) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) + throw new IllegalArgumentException("Selected owner source content size is invalid"); + Objects.requireNonNull(expectedScope, "expectedScope"); + if (expectedDigest == null || !SHA256.matcher(expectedDigest).matches()) + throw new IllegalArgumentException("Expected selected owner source digest is invalid"); + + // Enforce the envelope budget before copying, hashing or parsing any caller-controlled bytes. + byte[] stored = bytes.clone(); + String actualDigest = DraftAuthorizationFenceBinding.digest(stored); + if (!actualDigest.equals(expectedDigest)) + throw new IllegalArgumentException("Selected owner source content digest differs"); + + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(DOMAIN); + byte[] scopeBytes = reader.bytes(); + String scopeDigest = reader.text(); + if (!DraftAuthorizationFenceBinding.digest(scopeBytes).equals(scopeDigest)) + throw new IllegalArgumentException("Selected owner source scope digest differs"); + SelectedOwnerIntakeSourceReadScope decodedScope = + SelectedOwnerIntakeSourceReadScope.fromStored(scopeBytes); + if (!Arrays.equals(scopeBytes, decodedScope.canonicalBytes()) + || !decodedScope.equals(expectedScope) + || decodedScope.owner() != expectedScope.owner() + || !decodedScope.selected().equals(expectedScope.selected()) + || !decodedScope.digest().equals(scopeDigest)) + throw new IllegalArgumentException("Selected owner source scope differs from expectation"); + + var snapshots = new LinkedHashMap(); + for (String family : FAMILIES) { + reader.expect(family); + byte[] snapshot = reader.bytes(); + if (snapshot.length == 0) + throw new IllegalArgumentException("Selected " + family + " snapshot size is invalid"); + String familyDigest = reader.text(); + if (!DraftAuthorizationFenceBinding.digest(snapshot).equals(familyDigest)) + throw new IllegalArgumentException("Selected " + family + " snapshot digest differs"); + requireSelectedBinding(family, snapshot, decodedScope.selected()); + snapshots.put(family, snapshot); + } + reader.requireEnd(); + + GameplayRuleSelectedSource gameplaySource = + new GameplayRuleSelectedSource(utf8(snapshots.get("GAMEPLAY_RULE"), "GAMEPLAY_RULE")); + if (!decodedScope.selected().equals(gameplaySource.binding())) + throw new IllegalArgumentException("Selected gameplay rule binding differs"); + + TemplateConfigSourceSnapshot templateConfigSource = + TemplateConfigSourceSnapshot.fromStored( + utf8(snapshots.get("TEMPLATE_CONFIG"), "TEMPLATE_CONFIG")); + if (!decodedScope.selected().equals(templateConfigSource.binding())) + throw new IllegalArgumentException("Selected template config binding differs"); + + return new SelectedOwnerIntakeSourceContent( + decodedScope, stored, actualDigest, snapshots, gameplaySource, templateConfigSource); + } + + public SelectedOwnerIntakeSourceReadScope scope() { + return scope; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + /** Returns the original canonical snapshot bytes for one of the six closed family names. */ + public byte[] snapshotBytes(String closedFamily) { + if (closedFamily == null) + throw new IllegalArgumentException("Unsupported selected owner source family"); + byte[] snapshot = snapshots.get(closedFamily); + if (snapshot == null) + throw new IllegalArgumentException("Unsupported selected owner source family"); + return snapshot.clone(); + } + + public GameplayRuleSelectedSource gameplaySource() { + return gameplaySource; + } + + public TemplateConfigSourceSnapshot templateConfigSource() { + return templateConfigSource; + } + + private static void requireSelectedBinding( + String family, byte[] snapshot, DraftCommitBinding selected) { + String json = utf8(snapshot, family); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!Arrays.equals(snapshot, canonical)) + throw new IllegalArgumentException( + "Selected " + family + " snapshot is not canonical JSON"); + var root = GameplayRuleManifest.tree(json); + if (!root.isObject()) + throw new IllegalArgumentException( + "Selected " + family + " snapshot root must be an object"); + var bindingJson = root.get("bindingJson"); + var bindingDigest = root.get("bindingDigest"); + if (bindingJson == null + || !bindingJson.isTextual() + || bindingDigest == null + || !bindingDigest.isTextual()) + throw new IllegalArgumentException("Selected " + family + " binding fields must be text"); + DraftCommitBinding decoded = + DraftCommitBinding.fromStored(bindingJson.textValue(), bindingDigest.textValue()); + if (!selected.equals(decoded)) + throw new IllegalArgumentException("Selected " + family + " binding differs"); + } catch (IOException failure) { + throw new IllegalArgumentException( + "Selected " + family + " snapshot JSON is invalid", failure); + } + } + + private static String utf8(byte[] bytes, String family) { + String value = new String(bytes, StandardCharsets.UTF_8); + if (!Arrays.equals(bytes, value.getBytes(StandardCharsets.UTF_8))) + throw new IllegalArgumentException("Selected " + family + " snapshot is not exact UTF-8"); + return value; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodec.java new file mode 100644 index 0000000000..c0f213858a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodec.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceRequest; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceResponse; + +/** Closed wire mapping for selected-owner source content and exact request-echo validation. */ +public final class SelectedOwnerIntakeSourceProtoCodec { + public static final int MAX_WIRE_BYTES = 16 * 1024 * 1024; + + private SelectedOwnerIntakeSourceProtoCodec() {} + + public static SelectedOwnerIntakeSourceRequest toRequest( + SelectedOwnerIntakeSourceReadEvidence.Request request) { + Objects.requireNonNull(request, "selected-owner source-read request is required"); + var wire = + SelectedOwnerIntakeSourceRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setPurpose(request.purpose()) + .setPreliminarySourceScope(ByteString.copyFrom(request.scope().canonicalBytes())) + .setPreliminaryScopeDigest(request.scope().digest()) + .build(); + requireWithinBudget(wire); + return wire; + } + + /** Decodes integrity metadata only; this does not authenticate or authorize source disclosure. */ + public static SelectedOwnerIntakeSourceReadEvidence.Request fromRequest( + SelectedOwnerIntakeSourceRequest request) { + requireKnownAndWithinBudget(request, "selected-owner source-read request"); + try { + DraftAuthorizationFenceBinding.canonicalUuid(request.getReadRequestId()); + var scope = + SelectedOwnerIntakeSourceReadScope.fromStored( + request.getPreliminarySourceScope().toByteArray()); + if (!scope.digest().equals(request.getPreliminaryScopeDigest())) + throw invalid("Changed preliminary source-scope digest"); + return new SelectedOwnerIntakeSourceReadEvidence.Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + UUID.fromString(request.getReadRequestId()), + request.getIntendedReader(), + request.getPurpose(), + scope); + } catch (IllegalArgumentException exception) { + throw invalid("Invalid selected-owner source-read request", exception); + } + } + + public static SelectedOwnerIntakeSourceResponse toResponse( + SelectedOwnerIntakeSourceReadEvidence.Request request, + SelectedOwnerIntakeSourceContent content) { + Objects.requireNonNull(request, "selected-owner source-read request is required"); + Objects.requireNonNull(content, "selected-owner source content is required"); + if (!request.scope().equals(content.scope())) + throw invalid("Selected source content is bound to a different preliminary scope"); + var checkedContent = + SelectedOwnerIntakeSourceContent.fromStored( + content.canonicalBytes(), request.scope(), content.digest()); + var wire = + SelectedOwnerIntakeSourceResponse.newBuilder() + .setRequest(toRequest(request)) + .setSelectedSourceContent(ByteString.copyFrom(checkedContent.canonicalBytes())) + .setSelectedSourceDigest(checkedContent.digest()) + .build(); + requireWithinBudget(wire); + return wire; + } + + /** Validates the complete unchanged echo before accepting bound source content. */ + public static SelectedOwnerIntakeSourceContent fromResponse( + SelectedOwnerIntakeSourceReadEvidence.Request request, + SelectedOwnerIntakeSourceResponse response) { + Objects.requireNonNull(request, "selected-owner source-read request is required"); + requireKnownAndWithinBudget(response, "selected-owner source-read response"); + if (!response.hasRequest()) throw invalid("Selected-owner response has no request echo"); + var echoedRequest = response.getRequest(); + requireKnownAndWithinBudget(echoedRequest, "selected-owner response request echo"); + if (!toRequest(request).equals(echoedRequest)) + throw invalid("Selected-owner response does not echo the complete request unchanged"); + + var contentBytes = response.getSelectedSourceContent(); + if (contentBytes.isEmpty() || contentBytes.size() > SelectedOwnerIntakeSourceContent.MAX_BYTES) + throw invalid("Missing or oversized selected-owner source content"); + try { + return SelectedOwnerIntakeSourceContent.fromStored( + contentBytes.toByteArray(), request.scope(), response.getSelectedSourceDigest()); + } catch (IllegalArgumentException exception) { + throw invalid("Game Design returned invalid selected-owner source content", exception); + } + } + + private static void requireKnownAndWithinBudget(Message wire, String label) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) + throw invalid("Missing or oversized " + label); + if (!wire.getUnknownFields().asMap().isEmpty()) throw invalid("Unknown fields in " + label); + } + + private static void requireWithinBudget(Message wire) { + if (wire.getSerializedSize() > MAX_WIRE_BYTES) + throw invalid("Selected-owner source message exceeds the 16 MiB wire budget"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java new file mode 100644 index 0000000000..04e5653691 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java @@ -0,0 +1,657 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedOwnerIntakeSourceServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceRequest; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic loopback transport proof; it does not establish genuine Game Design source reads. */ +class SelectedOwnerIntakeSourceClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String OTHER_CLIENT_URI = + "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST_ID = id("33333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = id("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID OPERATION = id("66666666-6666-4666-8666-666666666666"); + private static final UUID FENCE = id("77777777-7777-4777-8777-777777777777"); + private static final UUID INTAKE = id("88888888-8888-4888-8888-888888888888"); + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final UUID GENESIS = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final List FAMILIES = + List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG"); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private final AtomicInteger calls = new AtomicInteger(); + private final AtomicInteger responseBytes = new AtomicInteger(); + private Server server; + private boolean stall; + private boolean substituteEcho; + private boolean largeResponse; + + @BeforeAll + static void certificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void closeServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + TransactionSynchronizationManager.clear(); + } + + @Test + void pinsGameDesignServerAndRoundTripsBothOwnerScopesOverLoopbackMtls() throws Exception { + start(pki.gameDesignServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var request = request(owner, "{}"); + assertThat(client.read(request).scope()).isEqualTo(request.scope()); + } + assertThat(calls).hasValue(2); + } + + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + start(pki.wrongServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + assertThatThrownBy(() -> client.read(request(Owner.ENTITY_MANAGEMENT, "{}"))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(2); + } + } + + @Test + void transportsLargeCompleteContentWithinExplicitWireBudget() throws Exception { + largeResponse = true; + start(pki.gameDesignServer()); + var request = request(Owner.AUTOMATION_SCRIPTING, "{}"); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + var content = client.read(request); + assertThat(content.scope()).isEqualTo(request.scope()); + assertThat(content.snapshotBytes("COMMAND").length).isGreaterThan(6_000_000); + assertThat(responseBytes.get()) + .isGreaterThan(4 * 1024 * 1024) + .isLessThanOrEqualTo(SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES); + assertThat(calls).hasValue(1); + } + } + + @Test + void requiresExactClientCertificateAndRejectsExpiredServerOrClientCertificates() + throws Exception { + start(pki.gameDesignServer()); + try (var client = newClient(pki.wrongClient())) { + client.init(); + assertThatThrownBy(() -> client.read(request(Owner.ENTITY_MANAGEMENT, "{}"))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(calls).hasValue(1); + } + + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + start(pki.expiredGameDesignServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + assertThatThrownBy(() -> client.read(request(Owner.ENTITY_MANAGEMENT, "{}"))) + .isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(1); + } + + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + start(pki.gameDesignServer()); + try (var client = newClient(pki.expiredGameDesignClient())) { + client.init(); + assertThatThrownBy(() -> client.read(request(Owner.ENTITY_MANAGEMENT, "{}"))) + .isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(1); + } + } + + @Test + void rejectsOtherNamespaceAmbientSqlSynchronizationAndSubstitutedEcho() throws Exception { + start(pki.gameDesignServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + var otherNamespace = request(Owner.ENTITY_MANAGEMENT, "{}", "other"); + assertThatThrownBy(() -> client.read(otherNamespace)) + .isInstanceOf(IllegalArgumentException.class); + + var request = request(Owner.ENTITY_MANAGEMENT, "{}"); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(calls).hasValue(0); + + substituteEcho = true; + assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); + assertThat(calls).hasValue(1); + } + } + + @Test + void boundsUnavailableReadByFiveSecondDeadline() throws Exception { + stall = true; + start(pki.gameDesignServer()); + try (var client = newClient(pki.gameDesignClient())) { + client.init(); + assertThatThrownBy(() -> client.read(request(Owner.AUTOMATION_SCRIPTING, "{}"))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + } + + @Test + void requiresTlsAndReadableFileBackedCredentials() { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSourceClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + + var classpath = new CommonGrpcClientProperties(); + classpath.setCertChain("classpath:client.crt"); + classpath.setPrivateKey("/tmp/client.key"); + classpath.setCaCert("/tmp/ca.crt"); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSourceClient( + endpoints, classpath, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + private void start(TestIdentity identity) throws Exception { + var service = + new GameDesignSelectedOwnerIntakeSourceServiceGrpc + .GameDesignSelectedOwnerIntakeSourceServiceImplBase() { + @Override + public void readSelectedSource( + SelectedOwnerIntakeSourceRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + var peer = GrpcPeerIdentity.current(); + if (peer == null || !GAME_DESIGN_URI.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (stall) return; + var request = SelectedOwnerIntakeSourceProtoCodec.fromRequest(wire); + var content = content(request.scope(), largeResponse ? 6_500_000 : 0); + var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, content); + responseBytes.set(response.getSerializedSize()); + if (substituteEcho) { + response = + response.toBuilder() + .setRequest( + wire.toBuilder().setReadRequestId(UUID.randomUUID().toString()).build()) + .build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcSelectedOwnerIntakeSourceClient newClient(TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + return new GrpcSelectedOwnerIntakeSourceClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static SelectedOwnerIntakeSourceReadEvidence.Request request( + Owner owner, String payload) { + return request(owner, payload, NAMESPACE); + } + + private static SelectedOwnerIntakeSourceReadEvidence.Request request( + Owner owner, String payload, String namespace) { + return SelectedOwnerIntakeSourceReadEvidence.Request.create( + namespace, scope(owner, payload, namespace)); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + Owner owner, String payload, String namespace) { + DraftCommitBinding selected = binding(COMMIT, payload); + return new SelectedOwnerIntakeSourceReadScope( + owner, namespace, OPERATION, FENCE, INTAKE, ACTOR, selected); + } + + private static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope, int largeCommandMarkerSize) { + var selected = scope.selected(); + var gameplay = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "sourceEpoch", "0", + "inheritedCommitId", "", + "genesisReceiptId", GENESIS.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var template = new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()); + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : FAMILIES) { + byte[] snapshot = + switch (family) { + case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); + case "TEMPLATE_CONFIG" -> template.canonicalBytes(); + default -> + opaqueSnapshot( + family, + selected, + family.equals("COMMAND") + ? "x".repeat(largeCommandMarkerSize) + : "synthetic-" + family); + }; + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] encoded = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + encoded, scope, DraftAuthorizationFenceBinding.digest(encoded)); + } + + private static byte[] opaqueSnapshot(String family, DraftCommitBinding selected, String marker) { + return GameplayRuleManifest.canonical( + Map.of( + "schema", + "synthetic-test-only/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "family", + family, + "marker", + marker)) + .getBytes(StandardCharsets.UTF_8); + } + + private static DraftCommitBinding binding(UUID commitId, String payload) { + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + REQUEST_ID, + commitId, + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameDesignServer, + TestIdentity wrongServer, + TestIdentity expiredGameDesignServer, + TestIdentity gameDesignClient, + TestIdentity wrongClient, + TestIdentity expiredGameDesignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("selected-content-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD selected-content test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("selected-content-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity( + directory, caStore, caFile, "game-design-server", GAME_DESIGN_URI, true, false), + issueIdentity(directory, caStore, caFile, "wrong-server", ACCOUNT_URI, true, false), + issueIdentity(directory, caStore, caFile, "expired-server", GAME_DESIGN_URI, true, true), + issueIdentity( + directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false, false), + issueIdentity(directory, caStore, caFile, "wrong-client", OTHER_CLIENT_URI, false, false), + issueIdentity( + directory, caStore, caFile, "expired-client", GAME_DESIGN_URI, false, true)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("selected-content-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("selected-content-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("selected-content-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, + Path caStore, + Path caFile, + String alias, + String workloadUri, + boolean server, + boolean expired) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + var startDate = expired ? List.of("-startdate", "2000/01/01 00:00:00") : List.of(); + var validity = expired ? "1" : "30"; + var generate = + new ArrayList( + List.of( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + validity, + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD)); + runKeytool(generate.toArray(String[]::new)); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + var sign = + new ArrayList( + List.of( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + validity, + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san)); + sign.addAll(startDate); + runKeytool(sign.toArray(String[]::new)); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java new file mode 100644 index 0000000000..59b9163053 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java @@ -0,0 +1,360 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import org.junit.jupiter.api.Test; + +/** + * Synthetic integrity fixtures only; these do not prove genuine owner rows, census, or authority. + */ +class SelectedOwnerIntakeSourceContentTest { + private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST = id("33333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = id("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID OPERATION = id("66666666-6666-4666-8666-666666666666"); + private static final UUID FENCE = id("77777777-7777-4777-8777-777777777777"); + private static final UUID INTAKE = id("88888888-8888-4888-8888-888888888888"); + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final UUID GENESIS = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final List FAMILIES = + List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG"); + + @Test + void roundTripsBothOwnerDomainsAndPreservesDefensiveExactFamilyBytes() { + DraftCommitBinding selected = binding(COMMIT); + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var scope = scope(owner, selected, INTAKE); + List snapshots = snapshots(selected); + byte[] encoded = encode(scope, snapshots); + var content = SelectedOwnerIntakeSourceContent.fromStored(encoded, scope, digest(encoded)); + byte[] expected = snapshots.getFirst().bytes().clone(); + byte[] expectedContent = encoded.clone(); + byte[] exposedContent = content.canonicalBytes(); + byte[] exposedSnapshot = content.snapshotBytes("COMMAND"); + exposedContent[0] ^= 0x7f; + exposedSnapshot[0] ^= 0x7f; + encoded[0] ^= 0x7f; + + assertThat(content.scope()).isEqualTo(scope); + assertThat(content.canonicalBytes()).isEqualTo(expectedContent); + assertThat(content.canonicalBytes()).isNotEqualTo(exposedContent); + assertThat(content.digest()).isEqualTo(digest(encode(scope, snapshots))); + assertThat(content.snapshotBytes("COMMAND")).isEqualTo(expected); + assertThat(content.gameplaySource().binding()).isEqualTo(selected); + assertThat(content.templateConfigSource().binding()).isEqualTo(selected); + assertThatThrownBy(() -> content.snapshotBytes("UNKNOWN")) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void requiresExpectedScopeDigestAndEveryScopeFieldToMatch() { + DraftCommitBinding selected = binding(COMMIT); + var expectedScope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + byte[] original = encode(expectedScope, snapshots(selected)); + byte[] changedActor = + encode( + scope(Owner.ENTITY_MANAGEMENT, selected, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab")), + snapshots(selected)); + byte[] changedOwner = + encode(scope(Owner.AUTOMATION_SCRIPTING, selected, INTAKE), snapshots(selected)); + byte[] changedSelection = + encode( + scope( + Owner.ENTITY_MANAGEMENT, + binding(id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")), + INTAKE), + snapshots(selected)); + + assertInvalid(original, expectedScope, "sha256:" + "0".repeat(64)); + assertInvalid(changedActor, expectedScope, digest(changedActor)); + assertInvalid(changedOwner, expectedScope, digest(changedOwner)); + assertInvalid(changedSelection, expectedScope, digest(changedSelection)); + assertInvalid( + encode(expectedScope, snapshots(selected), "sha256:" + "0".repeat(64), Map.of(), null), + expectedScope, + null); + assertThatThrownBy( + () -> SelectedOwnerIntakeSourceContent.fromStored(original, expectedScope, null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedSelectedBindingEvenWhenInnerAndOuterHashesAreRecomputed() { + DraftCommitBinding selected = binding(COMMIT); + DraftCommitBinding substituted = binding(id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + var scope = scope(Owner.AUTOMATION_SCRIPTING, selected, INTAKE); + List altered = snapshots(selected); + altered.set( + 0, new FamilySnapshot("COMMAND", opaqueSnapshot("COMMAND", substituted, "changed"))); + byte[] forged = encode(scope, altered); + + assertInvalid(forged, scope, digest(forged)); + } + + @Test + void rejectsFamilyChangesAgainstThePreviouslyExpectedOuterDigest() { + DraftCommitBinding selected = binding(COMMIT); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + byte[] original = encode(scope, snapshots(selected)); + List altered = snapshots(selected); + altered.set(0, new FamilySnapshot("COMMAND", opaqueSnapshot("COMMAND", selected, "changed"))); + byte[] changed = encode(scope, altered); + + assertInvalid(changed, scope, digest(original)); + } + + @Test + void rejectsWrongFamilyDigestAndNoncanonicalOrInvalidJsonContent() { + DraftCommitBinding selected = binding(COMMIT); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + List valid = snapshots(selected); + + assertInvalid( + encode(scope, valid, null, Map.of("COMMAND", "sha256:" + "0".repeat(64)), null), + scope, + null); + + List noncanonical = new ArrayList<>(valid); + noncanonical.set( + 0, + new FamilySnapshot( + "COMMAND", + (" " + new String(valid.getFirst().bytes(), StandardCharsets.UTF_8)) + .getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, noncanonical), scope, null); + + List duplicate = new ArrayList<>(valid); + String bindingJson = selected.canonicalJson(); + String duplicateJson = + "{\"bindingJson\":" + + quote(bindingJson) + + ",\"bindingJson\":" + + quote(bindingJson) + + ",\"bindingDigest\":" + + quote(selected.digest()) + + "}"; + duplicate.set(0, new FamilySnapshot("COMMAND", duplicateJson.getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, duplicate), scope, null); + + List emptyFamily = new ArrayList<>(valid); + emptyFamily.set(0, new FamilySnapshot("COMMAND", new byte[0])); + assertInvalid(encode(scope, emptyFamily), scope, null); + + List invalidUtf8 = new ArrayList<>(valid); + invalidUtf8.set(0, new FamilySnapshot("COMMAND", new byte[] {(byte) 0xc3, 0x28})); + assertInvalid(encode(scope, invalidUtf8), scope, null); + } + + @Test + void requiresTextualBindingFieldsAndTypedGameplayAndTemplateSnapshots() { + DraftCommitBinding selected = binding(COMMIT); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + List invalidBinding = new ArrayList<>(snapshots(selected)); + invalidBinding.set( + 0, + new FamilySnapshot( + "COMMAND", + GameplayRuleManifest.canonical( + Map.of("bindingJson", 1, "bindingDigest", selected.digest())) + .getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, invalidBinding), scope, null); + + List missingBinding = new ArrayList<>(snapshots(selected)); + missingBinding.set( + 0, + new FamilySnapshot( + "COMMAND", + GameplayRuleManifest.canonical(Map.of("bindingJson", selected.canonicalJson())) + .getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, missingBinding), scope, null); + + List invalidGameplay = new ArrayList<>(snapshots(selected)); + invalidGameplay.set( + 3, + new FamilySnapshot( + "GAMEPLAY_RULE", opaqueSnapshot("GAMEPLAY_RULE", selected, "typed-invalid"))); + assertInvalid(encode(scope, invalidGameplay), scope, null); + + List invalidTemplate = new ArrayList<>(snapshots(selected)); + invalidTemplate.set( + 5, + new FamilySnapshot( + "TEMPLATE_CONFIG", opaqueSnapshot("TEMPLATE_CONFIG", selected, "typed-invalid"))); + assertInvalid(encode(scope, invalidTemplate), scope, null); + } + + @Test + void rejectsUnknownOrderDuplicateMissingTruncatedTrailingAndOversizedFrames() { + DraftCommitBinding selected = binding(COMMIT); + var scope = scope(Owner.AUTOMATION_SCRIPTING, selected, INTAKE); + List valid = snapshots(selected); + + List swapped = new ArrayList<>(valid); + swapped.set(0, new FamilySnapshot("REALM_POLICY", valid.get(0).bytes())); + swapped.set(1, new FamilySnapshot("COMMAND", valid.get(1).bytes())); + assertInvalid(encode(scope, swapped), scope, null); + + List duplicate = new ArrayList<>(valid); + duplicate.set(1, new FamilySnapshot("COMMAND", valid.get(1).bytes())); + assertInvalid(encode(scope, duplicate), scope, null); + assertInvalid(encode(scope, valid.subList(0, 5)), scope, null); + + byte[] encoded = encode(scope, valid); + assertInvalid(encode(scope, valid, null, Map.of(), new byte[] {1}), scope, null); + assertInvalid(Arrays.copyOf(encoded, encoded.length - 1), scope, null); + + byte[] oversizedFrame = encoded.clone(); + ByteBuffer.wrap(oversizedFrame).putInt(0, Integer.MAX_VALUE); + assertInvalid(oversizedFrame, scope, null); + + byte[] oversizedEnvelope = new byte[SelectedOwnerIntakeSourceContent.MAX_BYTES + 1]; + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceContent.fromStored( + oversizedEnvelope, scope, "sha256:" + "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static List snapshots(DraftCommitBinding selected) { + var gameplay = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "sourceEpoch", "0", + "inheritedCommitId", "", + "genesisReceiptId", GENESIS.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var template = new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()); + var result = new ArrayList(); + for (String family : FAMILIES) { + byte[] bytes = + switch (family) { + case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); + case "TEMPLATE_CONFIG" -> template.canonicalBytes(); + default -> opaqueSnapshot(family, selected, "synthetic-" + family); + }; + result.add(new FamilySnapshot(family, bytes)); + } + return result; + } + + private static byte[] opaqueSnapshot(String family, DraftCommitBinding selected, String marker) { + return GameplayRuleManifest.canonical( + Map.of( + "schema", + "synthetic-test-only/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "family", + family, + "marker", + marker)) + .getBytes(StandardCharsets.UTF_8); + } + + private static byte[] encode( + SelectedOwnerIntakeSourceReadScope scope, List snapshots) { + return encode(scope, snapshots, null, Map.of(), null); + } + + private static byte[] encode( + SelectedOwnerIntakeSourceReadScope scope, + List snapshots, + String scopeDigest, + Map familyDigests, + byte[] trailing) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scopeDigest == null ? scope.digest() : scopeDigest); + for (FamilySnapshot snapshot : snapshots) { + frame(out, snapshot.family()); + frame(out, snapshot.bytes()); + frame(out, familyDigests.getOrDefault(snapshot.family(), digest(snapshot.bytes()))); + } + if (trailing != null) out.writeBytes(trailing); + return out.toByteArray(); + } + + private static void assertInvalid( + byte[] bytes, SelectedOwnerIntakeSourceReadScope expectedScope, String expectedDigest) { + String digest = expectedDigest == null ? digest(bytes) : expectedDigest; + assertThatThrownBy( + () -> SelectedOwnerIntakeSourceContent.fromStored(bytes, expectedScope, digest)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + Owner owner, DraftCommitBinding selected, UUID intakeRequestId) { + return new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, intakeRequestId, ACTOR, selected); + } + + private static DraftCommitBinding binding(UUID commitId) { + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + REQUEST, + commitId, + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static String digest(byte[] value) { + return DraftAuthorizationFenceBinding.digest(value); + } + + private static String quote(String value) { + return GameplayRuleManifest.tree(GameplayRuleManifest.canonical(Map.of("value", value))) + .get("value") + .toString(); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private record FamilySnapshot(String family, byte[] bytes) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java new file mode 100644 index 0000000000..5dde9740a8 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java @@ -0,0 +1,306 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.UnaryOperator; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceRequest; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceResponse; +import org.junit.jupiter.api.Test; + +/** Synthetic codec fixtures cover integrity mapping only, not genuine source-owner proof. */ +class SelectedOwnerIntakeSourceProtoCodecTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST_ID = id("33333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = id("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID OPERATION = id("66666666-6666-4666-8666-666666666666"); + private static final UUID FENCE = id("77777777-7777-4777-8777-777777777777"); + private static final UUID INTAKE = id("88888888-8888-4888-8888-888888888888"); + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final UUID GENESIS = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final List FAMILIES = + List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG"); + + @Test + void roundTripsBothOwnerRequestsAndCompleteSourceContent() { + DraftCommitBinding selected = binding(COMMIT, "{}"); + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var request = request(owner, selected); + var wireRequest = SelectedOwnerIntakeSourceProtoCodec.toRequest(request); + assertThat(SelectedOwnerIntakeSourceProtoCodec.fromRequest(wireRequest)).isEqualTo(request); + + var content = content(request.scope(), 0); + var wireResponse = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, content); + assertThat(wireResponse.getRequest()).isEqualTo(wireRequest); + var decoded = SelectedOwnerIntakeSourceProtoCodec.fromResponse(request, wireResponse); + assertThat(decoded.scope()).isEqualTo(request.scope()); + assertThat(decoded.digest()).isEqualTo(content.digest()); + assertThat(decoded.canonicalBytes()).isEqualTo(content.canonicalBytes()); + assertThat(decoded.snapshotBytes("COMMAND")).isEqualTo(content.snapshotBytes("COMMAND")); + } + } + + @Test + void rejectsChangedSchemaNamespaceCorrelationReaderPurposeScopeAndDigest() { + var request = request(Owner.ENTITY_MANAGEMENT, binding(COMMIT, "{}")); + var wire = SelectedOwnerIntakeSourceProtoCodec.toRequest(request); + + assertInvalidRequest(wire.toBuilder().setSchemaVersion(2).build()); + assertInvalidRequest(wire.toBuilder().setTargetNamespace("other").build()); + assertInvalidRequest(wire.toBuilder().setReadRequestId("not-a-uuid").build()); + assertInvalidRequest(wire.toBuilder().setIntendedReader("spiffe://wrong").build()); + assertInvalidRequest(wire.toBuilder().setPurpose("PUBLICATION").build()); + assertInvalidRequest(wire.toBuilder().clearPreliminarySourceScope().build()); + assertInvalidRequest( + wire.toBuilder().setPreliminaryScopeDigest("sha256:" + "0".repeat(64)).build()); + } + + @Test + void requiresTheFullUnchangedRequestEchoBeforeInspectingContent() { + var request = request(Owner.AUTOMATION_SCRIPTING, binding(COMMIT, "{}")); + var content = content(request.scope(), 0); + var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, content); + List> substitutions = + List.of( + builder -> builder.setSchemaVersion(2), + builder -> builder.setTargetNamespace("other"), + builder -> builder.setReadRequestId(UUID.randomUUID().toString()), + builder -> builder.setIntendedReader("spiffe://wrong"), + builder -> builder.setPurpose("PUBLICATION"), + builder -> builder.setPreliminarySourceScope(ByteString.copyFromUtf8("substituted")), + builder -> builder.setPreliminaryScopeDigest("sha256:" + "0".repeat(64))); + + for (var substitution : substitutions) { + var changedEcho = substitution.apply(response.getRequest().toBuilder()).build(); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().setRequest(changedEcho).build())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().clearRequest().build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsUnknownOuterAndNestedFields() { + var request = request(Owner.ENTITY_MANAGEMENT, binding(COMMIT, "{}")); + var wireRequest = SelectedOwnerIntakeSourceProtoCodec.toRequest(request); + var response = + SelectedOwnerIntakeSourceProtoCodec.toResponse(request, content(request.scope(), 0)); + var unknown = unknownFields(); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromRequest( + wireRequest.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsContentDigestAndScopeSubstitution() { + var request = request(Owner.ENTITY_MANAGEMENT, binding(COMMIT, "{}")); + var original = content(request.scope(), 0); + var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, original); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, + response.toBuilder() + .setSelectedSourceDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, + response.toBuilder() + .setSelectedSourceContent(ByteString.copyFromUtf8("changed")) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().clearSelectedSourceContent().build())) + .isInstanceOf(IllegalArgumentException.class); + + var substitutedScope = scope(Owner.AUTOMATION_SCRIPTING, request.scope().selected()); + var substitutedContent = content(substitutedScope, 0); + var scopeSubstitution = + response.toBuilder() + .setSelectedSourceContent(ByteString.copyFrom(substitutedContent.canonicalBytes())) + .setSelectedSourceDigest(substitutedContent.digest()) + .build(); + assertThatThrownBy( + () -> SelectedOwnerIntakeSourceProtoCodec.fromResponse(request, scopeSubstitution)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void admitsContentAboveDefaultGrpcMessageSizeAndRejectsOversizedWireEnvelopes() { + var request = request(Owner.AUTOMATION_SCRIPTING, binding(COMMIT, "{}")); + var largeContent = content(request.scope(), 6_500_000); + var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, largeContent); + assertThat(response.getSerializedSize()).isGreaterThan(4 * 1024 * 1024); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES); + assertThat(SelectedOwnerIntakeSourceProtoCodec.fromResponse(request, response).digest()) + .isEqualTo(largeContent.digest()); + + var oversized = + SelectedOwnerIntakeSourceResponse.newBuilder() + .setRequest(SelectedOwnerIntakeSourceProtoCodec.toRequest(request)) + .setSelectedSourceContent( + ByteString.copyFrom(new byte[SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES])) + .setSelectedSourceDigest("sha256:" + "0".repeat(64)) + .build(); + assertThatThrownBy(() -> SelectedOwnerIntakeSourceProtoCodec.fromResponse(request, oversized)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertInvalidRequest(SelectedOwnerIntakeSourceRequest wire) { + assertThatThrownBy(() -> SelectedOwnerIntakeSourceProtoCodec.fromRequest(wire)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SelectedOwnerIntakeSourceReadEvidence.Request request( + Owner owner, DraftCommitBinding selected) { + return SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope(owner, selected)); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + Owner owner, DraftCommitBinding selected) { + return new SelectedOwnerIntakeSourceReadScope( + owner, NAMESPACE, OPERATION, FENCE, INTAKE, ACTOR, selected); + } + + private static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope, int largeCommandMarkerSize) { + var selected = scope.selected(); + var gameplay = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "sourceEpoch", "0", + "inheritedCommitId", "", + "genesisReceiptId", GENESIS.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var template = new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()); + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : FAMILIES) { + byte[] snapshot = + switch (family) { + case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); + case "TEMPLATE_CONFIG" -> template.canonicalBytes(); + default -> + opaqueSnapshot( + family, + selected, + family.equals("COMMAND") + ? "x".repeat(largeCommandMarkerSize) + : "synthetic-" + family); + }; + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] encoded = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + encoded, scope, DraftAuthorizationFenceBinding.digest(encoded)); + } + + private static byte[] opaqueSnapshot(String family, DraftCommitBinding selected, String marker) { + return GameplayRuleManifest.canonical( + Map.of( + "schema", + "synthetic-test-only/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "family", + family, + "marker", + marker)) + .getBytes(StandardCharsets.UTF_8); + } + + private static DraftCommitBinding binding(UUID commitId, String payload) { + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + REQUEST_ID, + commitId, + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcService.java new file mode 100644 index 0000000000..7e91d460ab --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcService.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceProtoCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.GameDesignSelectedOwnerIntakeSourceServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceRequest; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceResponse; + +/** Unregistered complete selected-content endpoint; never supplies an owner retention grant. */ +public final class GameDesignSelectedOwnerIntakeSourceGrpcService + extends GameDesignSelectedOwnerIntakeSourceServiceGrpc + .GameDesignSelectedOwnerIntakeSourceServiceImplBase { + private final GameDesignSelectedOwnerIntakeSourceReadService owner; + private final String namespace; + + public GameDesignSelectedOwnerIntakeSourceGrpcService( + GameDesignSelectedOwnerIntakeSourceReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-source owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void readSelectedSource( + SelectedOwnerIntakeSourceRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() > SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + final net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence + .Request + decoded; + try { + decoded = SelectedOwnerIntakeSourceProtoCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + var export = owner.readSource(decoded.scope()); + if (export == null) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + var content = + SelectedOwnerIntakeSourceContent.fromStored( + export.canonicalBytes(), decoded.scope(), export.digest()); + observer.onNext(SelectedOwnerIntakeSourceProtoCodec.toResponse(decoded, content)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + var code = Status.fromThrowable(failure).getCode(); + if (code == Status.Code.PERMISSION_DENIED || code == Status.Code.FAILED_PRECONDITION) { + observer.onError(Status.fromCode(code).asRuntimeException()); + } else { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } catch (IllegalArgumentException | IllegalStateException unavailable) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java new file mode 100644 index 0000000000..d936aa3241 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java @@ -0,0 +1,233 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceProtoCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceRequest; +import net.firedevops.firemud.gamedesign.v1.SelectedOwnerIntakeSourceResponse; +import org.junit.jupiter.api.Test; + +class GameDesignSelectedOwnerIntakeSourceGrpcServiceTest { + private static final String NAMESPACE = "test"; + + @Test + void authenticatesAccountPeerAndRejectsMalformedOrMismatchedInputBeforeOwnerRead() { + var owner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + var service = new GameDesignSelectedOwnerIntakeSourceGrpcService(owner, NAMESPACE); + var valid = request(Owner.ENTITY_MANAGEMENT); + var malformed = valid.toBuilder().setSchemaVersion(0).build(); + + var absentPeer = new Collector(); + service.readSelectedSource(malformed, absentPeer); + assertThat(absentPeer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + + String[][] identities = { + {"test", "game-design-service"}, + {"other", "account-service"}, + {"test", "world-management-service"} + }; + for (String[] identity : identities) { + var denied = new Collector(); + peer(identity[0], identity[1]).run(() -> service.readSelectedSource(valid, denied)); + assertThat(denied.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + + var malformedResult = new Collector(); + peer(NAMESPACE, "account-service") + .run(() -> service.readSelectedSource(malformed, malformedResult)); + assertThat(malformedResult.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + + var wrongNamespace = new Collector(); + peer(NAMESPACE, "account-service") + .run( + () -> + service.readSelectedSource( + valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("123", List.of(), java.util.Map.of()); + try { + var endUser = new Collector(); + peer(NAMESPACE, "account-service").run(() -> service.readSelectedSource(valid, endUser)); + assertThat(endUser.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + + verifyNoInteractions(owner); + } + + @Test + void rejectsChangedRequestFieldsUnknownFieldsAndOversizedWireBeforeOwnerRead() { + var owner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + var service = new GameDesignSelectedOwnerIntakeSourceGrpcService(owner, NAMESPACE); + var valid = request(Owner.AUTOMATION_SCRIPTING); + var changedReader = valid.toBuilder().setIntendedReader("spiffe://wrong").build(); + var changedPurpose = valid.toBuilder().setPurpose("OTHER_PURPOSE").build(); + var unknown = + valid.toBuilder() + .mergeUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + var oversized = + valid.toBuilder() + .setPreliminarySourceScope( + ByteString.copyFrom(new byte[SelectedOwnerIntakeSourceProtoCodec.MAX_WIRE_BYTES])) + .build(); + + for (var invalid : List.of(changedReader, changedPurpose, unknown, oversized)) { + var result = new Collector(); + peer(NAMESPACE, "account-service").run(() -> service.readSelectedSource(invalid, result)); + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(result.response).isNull(); + } + + verifyNoInteractions(owner); + } + + @Test + void returnsExactEchoAndActualCompleteExportForBothOwnerScopes() { + var selected = + SelectedOwnerIntakeSourceExportTest.binding( + java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), "{}"); + for (Owner ownerType : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var scope = SelectedOwnerIntakeSourceExportTest.scope(ownerType, selected); + var export = + SelectedOwnerIntakeSourceExport.create( + scope, SelectedOwnerIntakeSourceExportTest.sources(selected, "0")); + var owner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + when(owner.readSource(any())).thenReturn(export); + var service = new GameDesignSelectedOwnerIntakeSourceGrpcService(owner, NAMESPACE); + var request = request(scope); + var result = new Collector(); + + peer(NAMESPACE, "account-service").run(() -> service.readSelectedSource(request, result)); + + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.response).isNotNull(); + assertThat(result.response.getRequest()).isEqualTo(request); + var decodedRequest = SelectedOwnerIntakeSourceProtoCodec.fromRequest(request); + var content = + SelectedOwnerIntakeSourceProtoCodec.fromResponse(decodedRequest, result.response); + assertThat(content.canonicalBytes()).isEqualTo(export.canonicalBytes()); + assertThat(content.digest()).isEqualTo(export.digest()); + verify(owner).readSource(scope); + } + } + + @Test + void deniesAbsentOrMismatchedExportAndSanitizesOwnerFailures() { + var scope = + SelectedOwnerIntakeSourceExportTest.scope( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceExportTest.binding( + java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), "{}")); + var request = request(scope); + + var missingOwner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + when(missingOwner.readSource(scope)).thenReturn(null); + assertFailure(missingOwner, request, Status.Code.FAILED_PRECONDITION); + + var differentScope = + SelectedOwnerIntakeSourceExportTest.scope( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceExportTest.binding( + java.util.UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), "{}")); + var differentExport = + SelectedOwnerIntakeSourceExport.create( + differentScope, + SelectedOwnerIntakeSourceExportTest.sources(differentScope.selected(), "0")); + var mismatchedOwner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + when(mismatchedOwner.readSource(scope)).thenReturn(differentExport); + assertFailure(mismatchedOwner, request, Status.Code.FAILED_PRECONDITION); + + var failingOwner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); + when(failingOwner.readSource(scope)) + .thenThrow(Status.UNAVAILABLE.withDescription("private owner detail").asRuntimeException()); + var failure = invoke(failingOwner, request); + assertThat(failure.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(failure.errorDescription).isNull(); + assertThat(failure.response).isNull(); + } + + private static void assertFailure( + GameDesignSelectedOwnerIntakeSourceReadService owner, + SelectedOwnerIntakeSourceRequest request, + Status.Code code) { + var result = invoke(owner, request); + assertThat(result.error).isEqualTo(code); + assertThat(result.response).isNull(); + } + + private static Collector invoke( + GameDesignSelectedOwnerIntakeSourceReadService owner, + SelectedOwnerIntakeSourceRequest request) { + var service = new GameDesignSelectedOwnerIntakeSourceGrpcService(owner, NAMESPACE); + var result = new Collector(); + peer(NAMESPACE, "account-service").run(() -> service.readSelectedSource(request, result)); + return result; + } + + private static SelectedOwnerIntakeSourceRequest request(Owner owner) { + var selected = + SelectedOwnerIntakeSourceExportTest.binding( + java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), "{}"); + return request(SelectedOwnerIntakeSourceExportTest.scope(owner, selected)); + } + + private static SelectedOwnerIntakeSourceRequest request( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope) { + return SelectedOwnerIntakeSourceProtoCodec.toRequest( + SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope)); + } + + private static Context peer(String namespace, String service) { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow()); + } + + private static final class Collector + implements StreamObserver { + Status.Code error; + String errorDescription; + SelectedOwnerIntakeSourceResponse response; + boolean completed; + + @Override + public void onNext(SelectedOwnerIntakeSourceResponse value) { + response = value; + } + + @Override + public void onError(Throwable value) { + error = Status.fromThrowable(value).getCode(); + errorDescription = Status.fromThrowable(value).getDescription(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java index 4113f9a3ab..15fd9a874c 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java @@ -13,6 +13,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import org.junit.jupiter.api.Test; class SelectedOwnerIntakeSourceExportTest { @@ -53,6 +54,36 @@ void framesTheScopeAndAllSixFamiliesInFixedOrder() { assertThat(export.scope()).isEqualTo(scope); } + @Test + void sharedConsumerDecodesExactCompleteExportsForBothOwners() { + var selected = binding(COMMIT, "{}"); + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var scope = scope(owner, selected); + var sources = sources(selected, "0"); + var exported = SelectedOwnerIntakeSourceExport.create(scope, sources); + + var content = + SelectedOwnerIntakeSourceContent.fromStored( + exported.canonicalBytes(), scope, exported.digest()); + + assertThat(content.scope()).isEqualTo(scope); + assertThat(content.canonicalBytes()).isEqualTo(exported.canonicalBytes()); + assertThat(content.digest()).isEqualTo(exported.digest()); + assertThat(content.snapshotBytes("COMMAND")).isEqualTo(sources.command().canonicalBytes()); + assertThat(content.snapshotBytes("REALM_POLICY")) + .isEqualTo(sources.policy().canonicalBytes()); + assertThat(content.snapshotBytes("ASSET")).isEqualTo(sources.asset().canonicalBytes()); + assertThat(content.snapshotBytes("GAMEPLAY_RULE")) + .isEqualTo(sources.gameplay().canonicalBytes()); + assertThat(content.snapshotBytes("BRANDING")) + .isEqualTo(sources.branding().orElseThrow().canonicalBytes()); + assertThat(content.snapshotBytes("TEMPLATE_CONFIG")) + .isEqualTo(sources.templateConfig().orElseThrow().canonicalBytes()); + assertThat(content.gameplaySource().binding()).isEqualTo(selected); + assertThat(content.templateConfigSource().binding()).isEqualTo(selected); + } + } + @Test void contentIsDeterministicAndCanonicalBytesAreDefensivelyExposed() { var selected = binding(COMMIT, "{}"); @@ -139,7 +170,7 @@ void rejectsExportLargerThanEightMib() { .hasMessageContaining("8 MiB"); } - private static GameDesignSourceRepository.SynchronizedSources sources( + static GameDesignSourceRepository.SynchronizedSources sources( DraftCommitBinding binding, String commandEpoch) { var command = new CommandSnapshot(binding, commandEpoch, null, "sha256:" + "a".repeat(64), List.of()); @@ -152,13 +183,12 @@ private static GameDesignSourceRepository.SynchronizedSources sources( command, policy, asset, gameplay, Optional.of(branding), Optional.of(template)); } - private static SelectedOwnerIntakeSourceReadScope scope( - Owner owner, DraftCommitBinding selected) { + static SelectedOwnerIntakeSourceReadScope scope(Owner owner, DraftCommitBinding selected) { return new SelectedOwnerIntakeSourceReadScope( owner, "test", OPERATION, FENCE, INTAKE, ACTOR, selected); } - private static DraftCommitBinding binding(UUID commitId, String payload) { + static DraftCommitBinding binding(UUID commitId, String payload) { return DraftCommitBinding.create( new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), REQUEST, From 695dc8ee2daaba5180d0975f07d25adf04e9b7b6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 17:08:12 +1300 Subject: [PATCH 073/129] Bind original Game Session attempt to Account World acquisition --- .../account-service/api-contracts.md | 2 + design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 8 + ...l_start_session_current_attempt_read.proto | 36 + ...essionOperatorAuthorizationRepository.java | 9 +- ...orldOriginalAttemptEvidenceRepository.java | 577 +++++++++++++ ...nWorldParticipationAcquisitionService.java | 505 ++++++++++++ ...ession_world_original_attempt_evidence.sql | 73 ++ ...ttemptEvidencePostgresIntegrationTest.java | 613 ++++++++++++++ ...onOperatorAuthorizationRepositoryTest.java | 29 + ...OriginalAttemptEvidenceRepositoryTest.java | 388 +++++++++ ...ldParticipationAcquisitionServiceTest.java | 769 ++++++++++++++++++ ...ginalStartSessionCurrentAttemptClient.java | 171 ++++ ...ginalStartSessionCurrentAttemptClient.java | 13 + ...nalStartSessionCurrentAttemptEvidence.java | 190 +++++ ...essionCurrentAttemptEvidenceGrpcCodec.java | 159 ++++ ...rtSessionCurrentAttemptClientMtlsTest.java | 535 ++++++++++++ ...onCurrentAttemptEvidenceGrpcCodecTest.java | 294 +++++++ .../VersionPublishCommandServiceImpl.java | 45 +- .../VersionPublishCommandServiceImplTest.java | 73 ++ ...nEvidenceGrpcMutualTlsIntegrationTest.java | 211 ++++- 21 files changed, 4686 insertions(+), 20 deletions(-) create mode 100644 protos/game-session/v1/original_start_session_current_attempt_read.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java create mode 100644 services/account-service/src/main/resources/db/migration/V131__start_session_world_original_attempt_evidence.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionCurrentAttemptClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index a4aa80a77a..d87bc18346 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -191,6 +191,8 @@ These RPCs and schemas are accepted target state but are not present in the curr For StartSession, Account's existing human authorization-reference issuer remains the sole issuer and the original reference retains `targetOwner=game-session-service`. The distinct Account-owned same-namespace World receiving-participation and source-protection lifecycle is defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation); this API contract adds no replacement issuer, reference-renewal, or re-redemption path. The Game Design projection read and publication hold/settlement producers remain separate and grant no StartSession World permission. The standalone, unregistered [historical participation read](../../../../protos/account/v1/start_session_world_participation_read.proto) authenticates the exact configured same-namespace World workload and returns only the retained original identity from an independent Account transaction. Its fresh read correlation and original participation ID/fence are lookup selectors, not fresh authority; expiry or settlement cannot renew the reference, restart execution or manufacture an abort. Unregistered repository, currentness, historical-read and exact-terminal settlement components do not establish a complete genuine participation producer or World admission; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records their remaining producer, consumer and physical proof gates. +Fresh World participation acquisition first obtains the [Game Session current-original-attempt observation](../../../../protos/game-session/v1/original_start_session_current_attempt_read.proto) outside Account SQL. Account compares its complete original tuple, actual owner mutation and attempt identities, fence, pending phase, unchanged finite lease expiry and exact Account-issued redemption projection; a projection hash alone is insufficient. Only then may its existing current-actor/source callback retain the participation, complete source vector and immutable original-attempt evidence in one Account transaction. Both new acquisition and exact acquisition retry recheck the original lease against the Account database clock after lock waits. A fresh read correlation is not a new durable operation, and independent lookup-only readback must preserve the first observation and exact participation. Historical expiry permits readback only, not new acquisition, renewal or restarted execution. This point-in-time observation is not continuous Game Session claim protection or World admission authority; the through-admission and owner execution proof required by ADR 0047 remains distinct. + The credential-free `ReadRedeemedOperationProjection` receiver accepts the exact configured same-namespace Game Design peer and the exact original Game Session redeemer under [ADR 0047's restricted original-operation read](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). Before returning the retained projection, Account compares the original request/reservation and redeemed workload/attempt/fence, then revalidates the original actor/JTI, current source and reference expiry. The response contains no credential or renewed permission. Game Session must separately prove its original claim and immutable pin under the owner-local checks required by that contract; this Account read is not World participation or admission. ## REST APIs diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 53ea233465..38357597ce 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -174,3 +174,9 @@ Entry format: - Observation: Cancellation text did not establish concurrency cancellation; configured job limits caused termination. Missing reports prevent complete executed/failed/skipped counts and positive corrected-head proof even when individual failure names appear in logs. - Expected pattern: Distinguish job timeout, container initialization and assertion failures; retain exact checkout provenance and never turn absent artifacts into passing or skipped totals. Diagnose reproducible fixture causes independently without weakening production guards or inferring provisioning authority. - Current status: The source and synthetic merge are recorded in the owning tracker/controller. The historical V75 fixture incorrectly called the current initializer requiring V81 tables; its test-only seed is corrected, with physical execution still required. No workflow timeout or infrastructure change was made. + +- `2026-10-10`: Redacted publication failures still need safe database guard identity + - Context: PR #3105's genuine selected-export PostgreSQL fixture repeatedly returned `Cannot commit transaction`; saved diagnostics established SQLSTATE `23514` at release finalization but did not identify the failed guard. + - Observation: Exception types and SQLSTATE alone could not distinguish several integrity checks. Guessing a cause would risk changing a valid guard, while logging full SQL exception text could disclose row or authorization data. + - Expected pattern: Preserve bounded, allowlisted constraint identifiers and PL/pgSQL routine/line metadata alongside existing status, never raw messages, SQL, row values or full server context. Keep unknown root causes explicit until attributable evidence exists. + - Current status: The existing publication diagnostic and focused secret-exclusion tests pass the affected full checks. Corrected PostgreSQL execution remains pending, and no publication integrity guard is changed. 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 f72c1b3806..e166af3014 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 @@ -6,6 +6,14 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The original Game Session current-attempt client, immutable Account V131 observation retention and sole-issuer World acquisition composition pass the affected Common/Account/Game Design full checks, schema generation, boot JARs, formatting, static checks, coverage, links and Markdown in 47 seconds. Originating local XML records 544 Common, 1,248 Account and 551 Game Design unit cases with zero failures, errors or skips; successful unchanged tasks retain results. Account executes seven non-container integration cases and skips 258 definitions; Game Design skips 148 without Docker. The twelve new Account unit cases cover timestamp casts, complete observation binding and mocked acquisition/readback ordering. The three new PostgreSQL definitions compile but do not execute; their synthetic parent and stipulated Game Session observation do not establish genuine Account/Game Session producer composition. The client uses synthetic loopback mTLS. Acquisition and retries preserve the actual mutation/attempt/fence, unchanged finite lease and first complete response bytes, rechecking the database clock after Account lock waits. This observation remains distinct from continuous Game Session claim protection and World execution/admission authority. All new paths remain unregistered. + +The concrete original-issuance timestamp repair adds explicit PostgreSQL casts without changing timestamps or guards. Game Design's existing redacted diagnostic now preserves only allowlisted constraint and routine/line identifiers, with two secret-exclusion cases; the release-finalization check's behavioral cause remains unresolved until corrected physical execution. Logging's affected full check passes in 49 seconds with 224 unit cases and one executed non-persistence TLS integration case; 23 container-dependent definitions skip. The untrusted-chain probe now requires the server's original CA trust manager to reject the exact presented certificate, rather than treating a broken pipe alone as rejection. Flyway sanity passes 12 sets and 288 versions. These checks do not establish fresh-image boot, corrected PostgreSQL execution or any complete Gameplay handoff. + +Saved confirmation traces attribute the five Account admission denials below to a WAL upper bound beyond the independently observed flush position, including catalog heap-pruning WAL before the row-trigger capture; the original expiry remains valid. No confirmation receipt was retained. The existing SQL has no private pre-INSERT capture handoff or separate sole-writer privilege boundary, so relocating the trigger alone is not a proved repair. A bounded protected-entry feasibility proposal is with Overseer under the existing durable-COMMIT confirmation decision. Denial and the unchanged deadline remain intact; these cases hold Account CI and admission completion, not independent source/receipt or release work. + +Exact source `d52b123ffaab637cac974012a708de508cc0468b` [Validation run 38019593927](https://github.com/benhook1013/FireMUD/actions/runs/38019593927) completed with a failed required Validation Gate. Originating XML records Account 270 integration executions with fourteen failures, Game Design 151 with one, and World 221 with none; all have zero skips. Nine Account failures share the concrete original-issuance `issued_at` timestamptz-versus-varchar binding error; five confirmation cases deny unavailable WAL coverage. Game Design's genuine selected-export failure is a PostgreSQL `23514` check violation at release finalization, without a retained constraint identifier. Logging's non-persistence TLS test expected a certificate-handshake exception but observed a broken pipe; that network symptom alone does not prove CA rejection. License, Security and CodeQL passed. Account's selected-owner reservation case and three publication-authority mTLS/PostgreSQL cases passed, as did three Game Design genuine source/settlement cases and five World authored-source mTLS cases; these are bounded owner proofs, not a complete release or admission. Actual merge `83f6acb3cd710ee63a50516470fcdc464beda890`, tree `3c043ab69bc675abbe50dc078362138e6771f6a3`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, not the recorded integration parent. Corrected source execution, genuine selected-content transport, finalized receipts and activation remain open. + The complete selected-owner content value, closed Game Design RPC, exact request echo and file-backed mTLS client pass the affected Common/Game Design full checks, Game Design boot JAR, links and Markdown in 2m33s. Common has 535 passing unit cases and Game Design 549, with zero failures, errors or unit skips; successful unchanged tasks reuse their results. All 148 Game Design integration definitions skip without Docker. Nineteen new Common cases cover content integrity, closed wire mapping and synthetic mTLS; five new Game Design cases cover the guarded receiver and actual six-family export constructors for both owners. These establish bounded transport/integrity and constructor compatibility, not genuine Account permission followed by authenticated database-backed disclosure, complete owner inventory or final retention receipts. All components remain unregistered; Account finalization, Entity/Automation census and terminal settlement remain open. The earlier source `b2a` [Validation run 38018179856](https://github.com/benhook1013/FireMUD/actions/runs/38018179856) was cancelled and its required gate failed. Originating World XML nevertheless records 221 integration executions with zero failures, errors or skips; 173 cases are in explicitly PostgreSQL-named suites, and their logs establish the assembled Account migrations through V130. This does not establish genuine cross-owner admission. The cancelled Account job logged 13 failures without uploading complete XML: eight original operator-issuance fixture failures and five confirmation cases, including a changed-binding case that fails before its intended assertion. Game Design logged one genuine selected-export publication failure before cancellation. Their deeper causes and complete execution totals are not established by those logs; these remain open, rather than being credited as completed physical proof or all attributed to the four older V120 durability gaps. Actual merge `f0fa86a46cdc5494e651f0cc0654a2dfbdb97111`, tree `6ba462f99cd7dd4cf5fa9ff49bfba7b606807f9b`, uses parent `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source, not the recorded integration parent. diff --git a/protos/game-session/v1/original_start_session_current_attempt_read.proto b/protos/game-session/v1/original_start_session_current_attempt_read.proto new file mode 100644 index 0000000000..bfb4f8893d --- /dev/null +++ b/protos/game-session/v1/original_start_session_current_attempt_read.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; + +package game_session.v1; + +import "google/protobuf/timestamp.proto"; + +option java_package = "net.firedevops.firemud.gamesession.v1"; +option java_multiple_files = true; + +// Unregistered, observation-only read of one exact live original StartSession owner attempt. +// It exposes no claimant credential and grants no mutation, renewal, redemption, or admission authority. +service OriginalStartSessionCurrentAttemptReadService { + rpc ReadOriginalStartSessionCurrentAttempt( + ReadOriginalStartSessionCurrentAttemptRequest) + returns (ReadOriginalStartSessionCurrentAttemptResponse); +} + +message ReadOriginalStartSessionCurrentAttemptRequest { + int32 schema_version = 1; + // Fresh correlation UUID for this observation; it is not a durable mutation identity. + string read_request_id = 2; + string target_namespace = 3; + bytes canonical_post_authorization_tuple = 4; + string expected_owner_attempt_id = 5; + string expected_owner_mutation_id = 6; + int64 expected_owner_fence = 7; +} + +message ReadOriginalStartSessionCurrentAttemptResponse { + ReadOriginalStartSessionCurrentAttemptRequest request = 1; + string phase_state = 2; + google.protobuf.Timestamp original_lease_expires_at = 3; + bytes account_redemption_projection = 4; + // Raw lowercase SHA-256 of account_redemption_projection. + string account_redemption_projection_digest = 5; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java index aa34607a0a..1eee39913a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java @@ -91,7 +91,9 @@ public CreateOrReadResult createOrReadExact(IssuanceCandidate candidate) { + "bundle_source_fence, bundle_linearization, authority_evidence_bundle, " + "authorization_reference_fingerprint, encrypted_response_envelope, issued_at, " + "reference_expires_at, response_envelope_expires_at, status) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ISSUED') " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ), " + + "CAST(? AS TIMESTAMPTZ), 'ISSUED') " + "ON CONFLICT (control_plane_request_id) DO NOTHING", candidate.controlPlaneRequestId(), candidate.preAuthorizationTuple(), @@ -166,11 +168,12 @@ public RedemptionResult redeemExact(RedemptionRequest request) { "UPDATE " + TABLE + " SET status = 'REDEEMED', redemption_redeemer_workload_uri = ?, " - + "redemption_owner_attempt_id = ?, redemption_owner_fence = ?, redeemed_at = ?, " + + "redemption_owner_attempt_id = ?, redemption_owner_fence = ?, " + + "redeemed_at = CAST(? AS TIMESTAMPTZ), " + "redemption_reference_fingerprint = ?, " + "redemption_authority_evidence_bundle = ? " + "WHERE control_plane_request_id = ? AND status = 'ISSUED' " - + "AND reference_expires_at > ?", + + "AND reference_expires_at > CAST(? AS TIMESTAMPTZ)", request.redeemerWorkloadUri(), request.ownerAttemptId(), request.ownerFence(), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java new file mode 100644 index 0000000000..66cdfcceec --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java @@ -0,0 +1,577 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable storage for the exact observation of the original live Game Session StartSession + * attempt that is attached to an existing Account World participation. + * + *

This repository does not authenticate Game Session, continuously establish owner authority, + * issue or renew an Account reference, or authorize World admission. The attached response is a + * point-in-time observation. Callers must obtain it from the exact same-namespace Game Session read + * and independently perform the current Account authority checks required by the owning service + * path. + * + *

All operations require the caller's writable READ COMMITTED Account transaction. Current + * retention and lookup lock the exact immutable participation before checking settlement and the + * original lease against the Account database clock. Historical readback is lookup-only and may + * return expired evidence; it cannot be used as current admission evidence. + */ +@Repository +public class AccountStartSessionWorldOriginalAttemptEvidenceRepository { + private static final String EVIDENCE = "account_start_session_world_original_attempt_evidence"; + private static final String PARTICIPATIONS = "account_start_session_world_participations"; + private static final String SOURCES = "account_start_session_world_participation_sources"; + private static final String SETTLEMENTS = "account_start_session_world_participation_settlements"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Set EVIDENCE_COLUMNS = + Set.of( + "participation_id", + "target_namespace", + "game_session_owner_attempt_id", + "game_session_owner_mutation_id", + "game_session_owner_fence", + "original_lease_expires_at", + "original_response_bytes", + "original_response_digest"); + private static final Set SOURCE_COLUMNS = + Set.of("participation_id", "source_key", "source_evidence"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve the injected DSLContext precondition; this transactional Spring repository must remain proxyable, owns no resources, and declares no finalizer.") + public AccountStartSessionWorldOriginalAttemptEvidenceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Appends the first complete observation for an existing unsettled participation, or reads back + * its immutable winner for an exact semantic retry. + * + *

A new transport correlation UUID is allowed on retry. The original tuple, target namespace, + * owner attempt, owner mutation UUID, owner fence, original expiry, and exact Account projection + * must remain unchanged. The first encoded complete response and its digest are retained. + */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredEvidence retainCurrentExact(StoredParticipation participation, Result observation) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(participation, "exact Account World participation is required"); + Objects.requireNonNull(observation, "exact current Game Session observation is required"); + + byte[] responseBytes = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observation).toByteArray(); + Result decoded = decodeResponse(observation.request(), responseBytes, participation); + + StoredParticipation locked = lockExactParent(participation); + requirePending(locked.participationId()); + requireLeaseCurrent(decoded.originalLeaseExpiresAt()); + + dsl.execute( + "INSERT INTO " + + EVIDENCE + + " (participation_id, target_namespace, game_session_owner_attempt_id, " + + "game_session_owner_mutation_id, game_session_owner_fence, original_lease_expires_at, " + + "original_response_bytes, original_response_digest) " + + "VALUES (?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?) " + + "ON CONFLICT (participation_id) DO NOTHING", + locked.participationId(), + decoded.request().targetNamespace(), + decoded.request().expectedOwnerAttemptId(), + decoded.request().expectedOwnerMutationId(), + decoded.request().expectedOwnerFence(), + OffsetDateTime.ofInstant(decoded.originalLeaseExpiresAt(), java.time.ZoneOffset.UTC), + responseBytes, + digestPrefixed(responseBytes)); + + Record row = selectEvidence(locked.participationId(), false); + if (row == null) throw unavailable(); + StoredEvidence stored = decodeStoredEvidence(row, locked); + requireSameSemanticObservation(decoded, stored.result()); + // Recheck after row-lock waits and readback work. The migration's INSERT guard independently + // checks the database clock after its parent lock as well. + requireLeaseCurrent(stored.originalLeaseExpiresAt()); + return stored; + } + + /** + * Lookup-only current read. It locks the exact pending Account participation and rechecks the + * retained original lease against the database clock after the lock wait. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCurrentExact( + StoredParticipation participation, Request expectedRequest) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(participation, "exact Account World participation is required"); + Objects.requireNonNull(expectedRequest, "exact current-attempt request is required"); + StoredParticipation locked = lockExactParent(participation); + requirePending(locked.participationId()); + Record row = selectEvidence(locked.participationId(), false); + if (row == null) return Optional.empty(); + StoredEvidence stored = decodeStoredEvidence(row, locked); + requireSameSemanticRequest(expectedRequest, stored.result().request()); + requireLeaseCurrent(stored.originalLeaseExpiresAt()); + return Optional.of(stored); + } + + /** + * Exact historical readback for recovery. It neither locks for admission nor checks current + * expiry or settlement; the returned observation remains historical evidence only. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findHistoricalExact( + StoredParticipation participation, Request expectedRequest) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(participation, "exact Account World participation is required"); + Objects.requireNonNull(expectedRequest, "exact historical current-attempt request is required"); + StoredParticipation historical = readExactParent(participation, false); + if (historical == null) return Optional.empty(); + Record row = selectEvidence(historical.participationId(), false); + if (row == null) return Optional.empty(); + StoredEvidence stored = decodeStoredEvidence(row, historical); + requireSameSemanticRequest(expectedRequest, stored.result().request()); + return Optional.of(stored); + } + + private StoredParticipation lockExactParent(StoredParticipation expected) { + StoredParticipation stored = readExactParent(expected, true); + if (stored == null) throw unavailable(); + return stored; + } + + private StoredParticipation readExactParent(StoredParticipation expected, boolean forUpdate) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + PARTICIPATIONS + + " WHERE participation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + expected.participationId()); + if (row == null) return null; + StoredParticipation actual = + AccountStartSessionWorldParticipationRepository.decodeParticipation(row, List.of()); + requireSameParent(expected, actual); + requireSameParentSources(expected); + return actual; + } + + private void requireSameParentSources(StoredParticipation expected) { + var rows = + dsl.fetch( + "SELECT * FROM " + SOURCES + " WHERE participation_id = ? ORDER BY source_key", + expected.participationId()); + List actual = new ArrayList<>(rows.size()); + for (Record row : rows) { + requireColumns(row, SOURCE_COLUMNS, "participation source"); + if (!expected.participationId().equals(requiredUuid(row, "participation_id"))) { + throw unavailable(); + } + actual.add( + new SourceRow(requiredString(row, "source_key"), requiredBytes(row, "source_evidence"))); + } + actual.sort(Comparator.comparing(SourceRow::key)); + List expectedSources = + expected.sources().stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); + if (actual.size() != expectedSources.size()) throw conflict(); + for (int index = 0; index < actual.size(); index++) { + SourceRow left = actual.get(index); + SourceEvidence right = expectedSources.get(index); + if (!left.key().equals(right.key()) + || !Arrays.equals(left.canonicalBytes(), right.canonicalBytes())) { + throw conflict(); + } + } + } + + private static void requireSameParent(StoredParticipation expected, StoredParticipation actual) { + if (!expected.participationId().equals(actual.participationId()) + || expected.participationFence() != actual.participationFence() + || !expected.controlPlaneRequestId().equals(actual.controlPlaneRequestId()) + || !Arrays.equals( + expected.originalPostAuthorizationTuple(), actual.originalPostAuthorizationTuple()) + || !expected.targetNamespace().equals(actual.targetNamespace()) + || !expected.canonicalTenantId().equals(actual.canonicalTenantId()) + || !expected.canonicalGameInstanceId().equals(actual.canonicalGameInstanceId()) + || !expected.gameSessionOwnerAttemptId().equals(actual.gameSessionOwnerAttemptId()) + || expected.gameSessionOwnerFence() != actual.gameSessionOwnerFence() + || !expected.preparationInputJson().equals(actual.preparationInputJson()) + || !expected.preparationInputDigest().equals(actual.preparationInputDigest()) + || expected.producerXid() != actual.producerXid() + || !expected.createdAt().equals(actual.createdAt())) { + throw conflict(); + } + } + + private void requirePending(UUID participationId) { + if (dsl.fetchOne( + "SELECT participation_id FROM " + SETTLEMENTS + " WHERE participation_id = ?", + participationId) + != null) { + throw unavailable(); + } + } + + private Record selectEvidence(UUID participationId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + EVIDENCE + + " WHERE participation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + participationId); + } + + private StoredEvidence decodeStoredEvidence(Record row, StoredParticipation parent) { + try { + requireColumns(row, EVIDENCE_COLUMNS, "original attempt evidence"); + UUID participationId = requiredUuid(row, "participation_id"); + String namespace = requiredString(row, "target_namespace"); + UUID ownerAttempt = requiredUuid(row, "game_session_owner_attempt_id"); + UUID ownerMutation = requiredUuid(row, "game_session_owner_mutation_id"); + long ownerFence = positive(requiredLong(row, "game_session_owner_fence")); + OffsetDateTime expiry = requiredTimestamp(row, "original_lease_expires_at"); + byte[] responseBytes = requiredBytes(row, "original_response_bytes"); + String responseDigest = requiredString(row, "original_response_digest"); + if (!parent.participationId().equals(participationId) + || !parent.targetNamespace().equals(namespace) + || !parent.gameSessionOwnerAttemptId().equals(ownerAttempt) + || parent.gameSessionOwnerFence() != ownerFence + || !SHA256.matcher(responseDigest).matches() + || !responseDigest.equals(digestPrefixed(responseBytes))) { + throw unavailable(); + } + + Result result = decodeResponseFromStoredBytes(responseBytes, parent); + if (!ownerMutation.equals(result.request().expectedOwnerMutationId()) + || !ownerAttempt.equals(result.request().expectedOwnerAttemptId()) + || ownerFence != result.request().expectedOwnerFence() + || !namespace.equals(result.request().targetNamespace()) + || !expiry.toInstant().equals(result.originalLeaseExpiresAt())) { + throw unavailable(); + } + return new StoredEvidence( + participationId, + ownerMutation, + expiry.toInstant(), + responseBytes, + responseDigest, + result); + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && ("Exact original StartSession attempt evidence unavailable".equals(state.getMessage()) + || "Original StartSession attempt evidence conflicts with its immutable binding" + .equals(state.getMessage()))) { + throw state; + } + throw unavailable(); + } + } + + private static Result decodeResponse( + Request expectedRequest, byte[] responseBytes, StoredParticipation parent) { + return validateResponse(expectedRequest, responseBytes, parent); + } + + static Result validateResponse( + Request expectedRequest, byte[] responseBytes, StoredParticipation parent) { + Objects.requireNonNull(expectedRequest, "exact current-attempt request is required"); + Objects.requireNonNull(responseBytes, "complete current-attempt response bytes are required"); + if (responseBytes.length == 0 + || responseBytes.length + > OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES) { + throw conflict(); + } + try { + ReadOriginalStartSessionCurrentAttemptResponse response = + ReadOriginalStartSessionCurrentAttemptResponse.parseFrom(responseBytes); + Result result = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + expectedRequest, response); + if (!Arrays.equals( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result).toByteArray(), + responseBytes)) { + throw conflict(); + } + requireObservationBinding(parent, result); + return result; + } catch (IOException | RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && "Original StartSession attempt evidence conflicts with its immutable binding" + .equals(state.getMessage())) { + throw state; + } + throw conflict(); + } + } + + private static Result decodeResponseFromStoredBytes( + byte[] responseBytes, StoredParticipation parent) { + if (responseBytes.length == 0 + || responseBytes.length + > OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES) { + throw unavailable(); + } + try { + ReadOriginalStartSessionCurrentAttemptResponse response = + ReadOriginalStartSessionCurrentAttemptResponse.parseFrom(responseBytes); + if (!response.hasRequest()) throw unavailable(); + Request echoedRequest = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(response.getRequest()); + Result result = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse(echoedRequest, response); + if (!Arrays.equals( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result).toByteArray(), + responseBytes)) { + throw unavailable(); + } + requireObservationBinding(parent, result); + return result; + } catch (IOException | RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && "Exact original StartSession attempt evidence unavailable" + .equals(state.getMessage())) { + throw state; + } + throw unavailable(); + } + } + + private static void requireObservationBinding(StoredParticipation parent, Result result) { + Request request = result.request(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(parent.originalPostAuthorizationTuple()); + if (!"StartSession".equals(tuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(tuple.preAuthorizationTuple().targetOwner()) + || !parent.controlPlaneRequestId().equals(tuple.controlPlaneRequestId()) + || !parent.targetNamespace().equals(request.targetNamespace()) + || !parent + .targetNamespace() + .equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !Arrays.equals( + parent.originalPostAuthorizationTuple(), request.canonicalPostAuthorizationTuple()) + || !parent.gameSessionOwnerAttemptId().equals(request.expectedOwnerAttemptId()) + || parent.gameSessionOwnerFence() != request.expectedOwnerFence() + || !accountProjectionMatches(tuple, result.accountRedemptionProjection()) + || result.originalLeaseExpiresAt().getNano() % 1_000 != 0) { + throw conflict(); + } + } + + static void requireSameSemanticObservation(Result expected, Result actual) { + requireSameSemanticRequest(expected.request(), actual.request()); + if (!expected.phaseState().equals(actual.phaseState()) + || !expected.originalLeaseExpiresAt().equals(actual.originalLeaseExpiresAt()) + || !Arrays.equals( + expected.accountRedemptionProjection(), actual.accountRedemptionProjection())) { + throw conflict(); + } + } + + static void requireSameSemanticRequest(Request expected, Request actual) { + if (!expected.targetNamespace().equals(actual.targetNamespace()) + || !Arrays.equals( + expected.canonicalPostAuthorizationTuple(), actual.canonicalPostAuthorizationTuple()) + || !expected.expectedOwnerAttemptId().equals(actual.expectedOwnerAttemptId()) + || !expected.expectedOwnerMutationId().equals(actual.expectedOwnerMutationId()) + || expected.expectedOwnerFence() != actual.expectedOwnerFence()) { + throw conflict(); + } + } + + private static boolean accountProjectionMatches( + StartSessionPostAuthorizationExecutionTuple tuple, byte[] projectionBytes) { + try { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + long issuanceFence = Long.parseLong(tuple.issuanceFence()); + if (issuanceFence <= 0L) return false; + byte[] expected = + Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + issuanceFence))); + return Arrays.equals(expected, projectionBytes); + } catch (IOException | RuntimeException malformed) { + return false; + } + } + + private void requireLeaseCurrent(Instant expiry) { + Record row = dsl.fetchOne("SELECT clock_timestamp()"); + if (row == null) throw unavailable(); + OffsetDateTime now = Objects.requireNonNull(row.get(0, OffsetDateTime.class)); + if (!expiry.isAfter(now.toInstant())) throw unavailable(); + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + }); + } + + private static void requireColumns(Record row, Set expected, String label) { + Set actual = + Arrays.stream(row.fields()) + .map(field -> field.getName()) + .collect(java.util.stream.Collectors.toSet()); + if (!actual.equals(expected)) throw unavailable(); + } + + private static UUID requiredUuid(Record row, String column) { + UUID value = Objects.requireNonNull(row.get(column, UUID.class), column + " is required"); + if (NIL_UUID.equals(value)) throw unavailable(); + return value; + } + + private static String requiredString(Record row, String column) { + String value = Objects.requireNonNull(row.get(column, String.class), column + " is required"); + if (value.isBlank()) throw unavailable(); + return value; + } + + private static byte[] requiredBytes(Record row, String column) { + byte[] value = Objects.requireNonNull(row.get(column, byte[].class), column + " is required"); + return value.clone(); + } + + private static long requiredLong(Record row, String column) { + return Objects.requireNonNull(row.get(column, Long.class), column + " is required"); + } + + private static OffsetDateTime requiredTimestamp(Record row, String column) { + return Objects.requireNonNull(row.get(column, OffsetDateTime.class), column + " is required"); + } + + private static long positive(long value) { + if (value <= 0L) throw unavailable(); + return value; + } + + private static String digestPrefixed(byte[] bytes) { + return "sha256:" + digestHex(bytes); + } + + private static String digestHex(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalStateException conflict() { + return new IllegalStateException( + "Original StartSession attempt evidence conflicts with its immutable binding"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Exact original StartSession attempt evidence unavailable"); + } + + private record SourceRow(String key, byte[] canonicalBytes) { + private SourceRow { + canonicalBytes = canonicalBytes.clone(); + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + } + + public record StoredEvidence( + UUID participationId, + UUID gameSessionOwnerMutationId, + Instant originalLeaseExpiresAt, + byte[] originalResponseBytes, + String originalResponseDigest, + Result result) { + public StoredEvidence { + Objects.requireNonNull(participationId); + Objects.requireNonNull(gameSessionOwnerMutationId); + Objects.requireNonNull(originalLeaseExpiresAt); + originalResponseBytes = Objects.requireNonNull(originalResponseBytes).clone(); + Objects.requireNonNull(originalResponseDigest); + Objects.requireNonNull(result); + if (!SHA256.matcher(originalResponseDigest).matches() + || !originalResponseDigest.equals(digestPrefixed(originalResponseBytes))) { + throw new IllegalArgumentException( + "Stored original response digest differs from its bytes"); + } + } + + @Override + public byte[] originalResponseBytes() { + return originalResponseBytes.clone(); + } + + @Override + public String toString() { + return "StoredEvidence[participationId=" + + participationId + + ", ownerMutationId=" + + gameSessionOwnerMutationId + + ", responseBytes=, projection=]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java new file mode 100644 index 0000000000..d97a5d5f18 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java @@ -0,0 +1,505 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.Candidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unregistered Account composition that acquires one exact World receiving participation from the + * original Game Session owner attempt and retains its current-attempt observation atomically with + * the participation. + * + *

The Game Session response is a point-in-time observation only. Account revalidates the + * original issuer, redemption, authority and locked source capture around the local write; this + * component does not renew authorization or establish World execution admission. No external + * service or runtime transport is registered here. + */ +public final class AccountStartSessionWorldParticipationAcquisitionService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final AccountStartSessionOperatorAuthorizationService issuer; + private final AccountStartSessionWorldParticipationRepository participationRepository; + private final AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptEvidenceRepository; + private final OriginalStartSessionCurrentAttemptClient gameSessionClient; + private final TransactionTemplate readbackTransaction; + private final String workloadNamespace; + + public AccountStartSessionWorldParticipationAcquisitionService( + AccountStartSessionOperatorAuthorizationService issuer, + AccountStartSessionWorldParticipationRepository participationRepository, + AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptEvidenceRepository, + OriginalStartSessionCurrentAttemptClient gameSessionClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.issuer = + Objects.requireNonNull(issuer, "original Account StartSession issuer is required"); + this.participationRepository = + Objects.requireNonNull( + participationRepository, "World participation repository is required"); + this.attemptEvidenceRepository = + Objects.requireNonNull( + attemptEvidenceRepository, "original-attempt evidence repository is required"); + this.gameSessionClient = + Objects.requireNonNull( + gameSessionClient, "Game Session current-attempt client is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + readbackTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + readbackTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readbackTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readbackTransaction.setReadOnly(false); + } + + /** + * Acquires and reads back the exact immutable Account participation and retained observation. An + * unknown commit is propagated for a later retry with this same original request; no reference is + * renewed and no retry write is attempted during readback. + */ + public AcquiredParticipation acquire(AcquisitionRequest request) { + requireWorldPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(request, "World participation acquisition request is required"); + + byte[] originalTupleBytes = request.originalPostAuthorizationTuple(); + StartSessionPostAuthorizationExecutionTuple originalTuple = + decodeOriginalTuple(originalTupleBytes); + if (!"StartSession".equals(originalTuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(originalTuple.preAuthorizationTuple().targetOwner()) + || !workloadNamespace.equals( + originalTuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw denied("Exact original human StartSession tuple for this World namespace required"); + } + requireNonnil(request.gameSessionOwnerMutationId(), "Game Session owner mutation ID"); + requireNonnil(request.gameSessionOwnerAttemptId(), "Game Session owner attempt ID"); + requirePositive(request.gameSessionOwnerFence(), "Game Session owner fence"); + requireNonnil(request.canonicalGameInstanceId(), "canonical Game Instance ID"); + requirePreparationInput(request.preparationInputJson(), request.preparationInputDigest()); + + Request currentAttemptRequest = + new Request( + freshReadId(originalTuple, request), + workloadNamespace, + originalTupleBytes, + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerFence()); + + // Game Session is always read before opening Account SQL. A fresh point-in-time read is + // required for every original-request retry; the Account callback below remains the authority. + requireNoAmbientTransaction(); + Result observed = gameSessionClient.read(currentAttemptRequest); + requireNoAmbientTransaction(); + Result exactObservation = exactObservation(currentAttemptRequest, observed, originalTuple); + + Commit commit = + issuer.withCurrentWorldReceivingParticipationCurrentness( + originalTupleBytes, + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + capture -> { + Candidate candidate = + new Candidate( + originalTuple, + capture, + request.canonicalGameInstanceId(), + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + request.preparationInputJson(), + request.preparationInputDigest()); + StoredParticipation participation = + participationRepository.createOrReadExact(candidate); + StoredEvidence evidence = + attemptEvidenceRepository.retainCurrentExact(participation, exactObservation); + requireStoredEvidenceBinding( + participation, currentAttemptRequest, originalTuple, evidence); + return new Commit(candidate, participation, evidence, currentAttemptRequest); + }); + + requireNoAmbientTransaction(); + Readback readback = + Objects.requireNonNull( + readbackTransaction.execute( + ignored -> { + Optional participation = + Objects.requireNonNull( + participationRepository.findCurrentExact(commit.candidate()), + "Current participation lookup returned no optional"); + if (participation.isEmpty()) { + throw denied("Committed exact World participation is not readable as current"); + } + StoredParticipation actualParticipation = participation.orElseThrow(); + StoredEvidence actualEvidence = + attemptEvidenceRepository + .findCurrentExact(actualParticipation, commit.request()) + .orElseThrow( + () -> + denied( + "Committed original Game Session attempt evidence is not readable")); + return new Readback(actualParticipation, actualEvidence); + }), + "Account World participation readback transaction returned no result"); + + if (!sameParticipation(commit.participation(), readback.participation()) + || !sameStoredEvidence(commit.evidence(), readback.evidence())) { + throw denied("Committed World participation or original-attempt proof readback differs"); + } + requireStoredEvidenceBinding( + readback.participation(), commit.request(), originalTuple, readback.evidence()); + return new AcquiredParticipation(readback.participation(), readback.evidence()); + } + + private Result exactObservation( + Request expected, + Result observed, + StartSessionPostAuthorizationExecutionTuple originalTuple) { + if (observed == null) { + throw denied("Exact current original Game Session attempt evidence is unavailable"); + } + try { + var canonicalResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observed); + Result exact = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + expected, canonicalResponse); + if (!OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals(exact.phaseState()) + || !sameRequest(expected, exact.request(), false) + || !MessageDigest.isEqual( + expectedAccountRedemptionProjection(originalTuple), + exact.accountRedemptionProjection())) { + throw denied( + "Current Game Session attempt or full Account redemption projection differs from the original issuer"); + } + return exact; + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact current original Game Session attempt evidence is malformed") + .withCause(malformed) + .asRuntimeException(); + } + } + + private void requireStoredEvidenceBinding( + StoredParticipation participation, + Request expectedRequest, + StartSessionPostAuthorizationExecutionTuple originalTuple, + StoredEvidence evidence) { + if (evidence == null + || !participation.participationId().equals(evidence.participationId()) + || !expectedRequest.expectedOwnerMutationId().equals(evidence.gameSessionOwnerMutationId()) + || !sameRequest(expectedRequest, evidence.result().request(), false) + || !OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( + evidence.result().phaseState()) + || !MessageDigest.isEqual( + expectedAccountRedemptionProjection(originalTuple), + evidence.result().accountRedemptionProjection()) + || !evidence.originalLeaseExpiresAt().equals(evidence.result().originalLeaseExpiresAt())) { + throw denied("Retained original Game Session attempt proof differs from the exact request"); + } + try { + var response = + net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse + .parseFrom(evidence.originalResponseBytes()); + Result decoded = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + evidence.result().request(), response); + if (!sameResult(evidence.result(), decoded) + || !Arrays.equals( + evidence.originalResponseBytes(), + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(decoded) + .toByteArray())) { + throw denied("Retained original Game Session response bytes are not canonical readback"); + } + } catch (com.google.protobuf.InvalidProtocolBufferException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Retained original Game Session response is not a complete wire value") + .withCause(malformed) + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Retained original Game Session response is malformed") + .withCause(malformed) + .asRuntimeException(); + } + } + + private static byte[] expectedAccountRedemptionProjection( + StartSessionPostAuthorizationExecutionTuple originalTuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(originalTuple.authorityEvidenceBundleBytes()); + long issuanceFence; + try { + issuanceFence = Long.parseLong(originalTuple.issuanceFence()); + } catch (NumberFormatException malformed) { + throw denied("Original Account issuance fence is malformed"); + } + if (issuanceFence <= 0L) throw denied("Original Account issuance fence is not positive"); + Map projection = + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + originalTuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + issuanceFence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + } catch (IOException malformed) { + throw new IllegalStateException( + "Could not encode the original Account redemption projection", malformed); + } + } + + private static boolean sameParticipation( + StoredParticipation expected, StoredParticipation actual) { + if (!expected.participationId().equals(actual.participationId()) + || expected.participationFence() != actual.participationFence() + || !expected.controlPlaneRequestId().equals(actual.controlPlaneRequestId()) + || !Arrays.equals( + expected.originalPostAuthorizationTuple(), actual.originalPostAuthorizationTuple()) + || !expected.targetNamespace().equals(actual.targetNamespace()) + || !expected.canonicalTenantId().equals(actual.canonicalTenantId()) + || !expected.canonicalGameInstanceId().equals(actual.canonicalGameInstanceId()) + || !expected.gameSessionOwnerAttemptId().equals(actual.gameSessionOwnerAttemptId()) + || expected.gameSessionOwnerFence() != actual.gameSessionOwnerFence() + || !expected.preparationInputJson().equals(actual.preparationInputJson()) + || !expected.preparationInputDigest().equals(actual.preparationInputDigest()) + || expected.producerXid() != actual.producerXid() + || !expected.createdAt().equals(actual.createdAt())) { + return false; + } + List expectedSources = + expected.sources().stream() + .sorted(java.util.Comparator.comparing(SourceEvidence::key)) + .toList(); + List actualSources = + actual.sources().stream() + .sorted(java.util.Comparator.comparing(SourceEvidence::key)) + .toList(); + if (expectedSources.size() != actualSources.size()) return false; + for (int index = 0; index < expectedSources.size(); index++) { + var left = expectedSources.get(index); + var right = actualSources.get(index); + if (!left.key().equals(right.key()) + || !Arrays.equals(left.canonicalBytes(), right.canonicalBytes())) return false; + } + return true; + } + + private static boolean sameStoredEvidence(StoredEvidence expected, StoredEvidence actual) { + return expected.participationId().equals(actual.participationId()) + && expected.gameSessionOwnerMutationId().equals(actual.gameSessionOwnerMutationId()) + && expected.originalLeaseExpiresAt().equals(actual.originalLeaseExpiresAt()) + && Arrays.equals(expected.originalResponseBytes(), actual.originalResponseBytes()) + && expected.originalResponseDigest().equals(actual.originalResponseDigest()) + && sameResult(expected.result(), actual.result()); + } + + private static boolean sameResult(Result expected, Result actual) { + return expected.originalLeaseExpiresAt().equals(actual.originalLeaseExpiresAt()) + && sameRequest(expected.request(), actual.request(), true) + && Arrays.equals( + expected.accountRedemptionProjection(), actual.accountRedemptionProjection()); + } + + private static boolean sameRequest(Request expected, Request actual, boolean compareReadId) { + return (!compareReadId || expected.readRequestId().equals(actual.readRequestId())) + && expected.targetNamespace().equals(actual.targetNamespace()) + && Arrays.equals( + expected.canonicalPostAuthorizationTuple(), actual.canonicalPostAuthorizationTuple()) + && expected.expectedOwnerAttemptId().equals(actual.expectedOwnerAttemptId()) + && expected.expectedOwnerMutationId().equals(actual.expectedOwnerMutationId()) + && expected.expectedOwnerFence() == actual.expectedOwnerFence(); + } + + private static StartSessionPostAuthorizationExecutionTuple decodeOriginalTuple( + byte[] tupleBytes) { + if (tupleBytes == null) throw denied("Complete original StartSession tuple is required"); + try { + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (!Arrays.equals(tupleBytes, tuple.canonicalBytes())) { + throw denied("Original StartSession tuple is not exact canonical bytes"); + } + return tuple; + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Complete canonical original StartSession tuple required") + .withCause(malformed) + .asRuntimeException(); + } + } + + private static UUID freshReadId( + StartSessionPostAuthorizationExecutionTuple tuple, AcquisitionRequest request) { + Set occupied = new HashSet<>(); + occupied.addAll( + List.of( + tuple.reservationOwnerId(), + tuple.preAuthorizationTuple().actor().accountId(), + tuple.preAuthorizationTuple().action().scope().tenantId(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerAttemptId(), + request.canonicalGameInstanceId(), + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .issuanceOperationId())); + UUID result; + do { + result = UUID.randomUUID(); + } while (occupied.contains(result)); + return result; + } + + private static void requirePreparationInput(String json, String digest) { + Objects.requireNonNull(json, "exact preparation input JSON is required"); + Objects.requireNonNull(digest, "preparation input digest is required"); + if (json.isBlank() + || !StandardCharsets.UTF_8.newEncoder().canEncode(json) + || json.getBytes(StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + || !SHA256.matcher(digest).matches() + || !digest.equals(digestPrefixed(json.getBytes(StandardCharsets.UTF_8)))) { + throw denied("Exact bounded World preparation input and digest required"); + } + } + + private void requireWorldPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified World workload identity required") + .asRuntimeException(); + } + String expectedUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !workloadNamespace.equals(peer.namespace()) + || !expectedUri.equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription( + "World participation acquisition requires remote currentness outside Account SQL") + .asRuntimeException(); + } + } + + private static void requireNonnil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw Status.FAILED_PRECONDITION + .withDescription(name + " must be a canonical non-nil UUID") + .asRuntimeException(); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) { + throw Status.FAILED_PRECONDITION + .withDescription(name + " must be positive") + .asRuntimeException(); + } + } + + private static String digestPrefixed(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static StatusRuntimeException denied(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } + + /** Raw bounded DTO; validation and canonical decoding occur only after exact peer auth. */ + public record AcquisitionRequest( + byte[] originalPostAuthorizationTuple, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + UUID canonicalGameInstanceId, + String preparationInputJson, + String preparationInputDigest) { + public AcquisitionRequest { + originalPostAuthorizationTuple = + originalPostAuthorizationTuple == null ? null : originalPostAuthorizationTuple.clone(); + } + + @Override + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple == null ? null : originalPostAuthorizationTuple.clone(); + } + } + + /** Exact participation plus retained observation; neither value is World admission authority. */ + public record AcquiredParticipation( + StoredParticipation participation, StoredEvidence originalAttemptEvidence) { + public AcquiredParticipation { + Objects.requireNonNull(participation); + Objects.requireNonNull(originalAttemptEvidence); + } + } + + private record Commit( + Candidate candidate, + StoredParticipation participation, + StoredEvidence evidence, + Request request) {} + + private record Readback(StoredParticipation participation, StoredEvidence evidence) {} +} diff --git a/services/account-service/src/main/resources/db/migration/V131__start_session_world_original_attempt_evidence.sql b/services/account-service/src/main/resources/db/migration/V131__start_session_world_original_attempt_evidence.sql new file mode 100644 index 0000000000..8ab48f8541 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V131__start_session_world_original_attempt_evidence.sql @@ -0,0 +1,73 @@ +-- Retain an observation of the exact live original Game Session attempt beside the +-- distinct Account-owned World participation. This is not producer authentication, +-- continuous owner authority, or admission permission. +CREATE TABLE account_start_session_world_original_attempt_evidence ( + participation_id UUID PRIMARY KEY + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + target_namespace VARCHAR(63) NOT NULL + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + game_session_owner_attempt_id UUID NOT NULL + CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_mutation_id UUID NOT NULL UNIQUE + CHECK (game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + original_lease_expires_at TIMESTAMPTZ NOT NULL + CHECK (isfinite(original_lease_expires_at)), + original_response_bytes BYTEA NOT NULL + CHECK (octet_length(original_response_bytes) BETWEEN 1 AND 525824), + original_response_digest VARCHAR(71) NOT NULL + CHECK (original_response_digest ~ '^sha256:[0-9a-f]{64}$') + CHECK (original_response_digest = 'sha256:' || encode(sha256(original_response_bytes), 'hex')) +); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_world_attempt_evidence_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + parent account_start_session_world_participations%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Original StartSession attempt observation is append-only' + USING ERRCODE = '23514'; + END IF; + -- Lock first so a concurrent terminal settlement cannot pass the pending-parent check. + SELECT * INTO STRICT parent FROM account_start_session_world_participations + WHERE participation_id = NEW.participation_id FOR UPDATE; + IF parent.target_namespace IS DISTINCT FROM NEW.target_namespace + OR parent.game_session_owner_attempt_id IS DISTINCT FROM NEW.game_session_owner_attempt_id + OR parent.game_session_owner_fence IS DISTINCT FROM NEW.game_session_owner_fence THEN + RAISE EXCEPTION 'Original StartSession attempt observation differs from its participation' + USING ERRCODE = '23514'; + END IF; + IF account_start_session_world_participation_is_settled(NEW.participation_id) THEN + RAISE EXCEPTION 'Original StartSession attempt observation requires pending participation' + USING ERRCODE = '23514'; + END IF; + -- This is a database-clock freshness guard after any parent lock wait. It does not + -- authenticate Game Session or assert that this point-in-time observation stays current. + IF NEW.original_lease_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession attempt observation lease is expired' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_world_attempt_evidence_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession attempt observation is append-only' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_world_attempt_evidence_validate + BEFORE INSERT ON account_start_session_world_original_attempt_evidence + FOR EACH ROW EXECUTE FUNCTION account_ss_world_attempt_evidence_insert_guard(); +CREATE TRIGGER account_ss_world_attempt_evidence_immutable + BEFORE UPDATE OR DELETE ON account_start_session_world_original_attempt_evidence + FOR EACH ROW EXECUTE FUNCTION account_ss_world_attempt_evidence_no_mutation(); +CREATE TRIGGER account_ss_world_attempt_evidence_no_truncate + BEFORE TRUNCATE ON account_start_session_world_original_attempt_evidence + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_world_attempt_evidence_no_mutation(); +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java new file mode 100644 index 0000000000..c5f2906af8 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java @@ -0,0 +1,613 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof for exact retry, lock-wait expiry, pending-parent, and immutable-row behavior. + * + *

The fixture deliberately inserts a synthetic Account participation with triggers disabled and + * supplies a synthetic Game Session observation. It proves database/repository binding only; it + * does not claim authenticated cross-owner source evidence or a genuine Game Session producer. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest { + private static final UUID OWNER_MUTATION_ID = + UUID.fromString("f7811486-2bd4-41a0-9bf7-a351ce3a0c8f"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"); + private static final long OWNER_FENCE = 47L; + private static final String NAMESPACE = "world-runtime"; + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void exactRetryPreservesFirstBytesAndExpiryAfterLockWaitCannotCreateOrRefreshEvidence() + throws Exception { + String schema = "ss_world_attempt_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + AccountStartSessionWorldOriginalAttemptEvidenceRepository repository = + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(dsl); + Fixture fixture = fixture(); + StoredParticipation parent = + transaction.execute( + status -> insertSyntheticParent(dsl, fixture, UUID.randomUUID(), false)); + assertThat(parent).isNotNull(); + + Instant retryExpiry = databaseNow(dsl).plusMillis(6_000L); + Result firstObservation = observation(fixture, UUID.randomUUID(), retryExpiry); + StoredEvidence first = + transaction.execute(status -> repository.retainCurrentExact(parent, firstObservation)); + assertThat(first).isNotNull(); + assertThat(first.gameSessionOwnerMutationId()).isEqualTo(OWNER_MUTATION_ID); + + Request freshCorrelation = request(fixture, UUID.randomUUID()); + Result exactRetryObservation = + new Result(freshCorrelation, first.originalLeaseExpiresAt(), fixture.accountProjection()); + StoredEvidence exactRetry = + transaction.execute(status -> repository.retainCurrentExact(parent, exactRetryObservation)); + assertThat(exactRetry.originalResponseBytes()).containsExactly(first.originalResponseBytes()); + assertThat(exactRetry.originalResponseDigest()).isEqualTo(first.originalResponseDigest()); + assertThat(exactRetry.result().request().readRequestId()) + .isEqualTo(first.result().request().readRequestId()); + StoredEvidence current = + transaction.execute( + status -> + repository + .findCurrentExact(parent, request(fixture, UUID.randomUUID())) + .orElseThrow()); + assertThat(current.originalResponseBytes()).containsExactly(first.originalResponseBytes()); + assertThat(current.originalResponseDigest()).isEqualTo(first.originalResponseDigest()); + + Result changedMutation = + new Result( + new Request( + UUID.randomUUID(), + NAMESPACE, + fixture.tuple().canonicalBytes(), + OWNER_ATTEMPT_ID, + UUID.fromString("1f2d6f4e-1202-4bdb-bcd4-f3c14e4cc764"), + OWNER_FENCE), + retryExpiry, + fixture.accountProjection()); + assertThatThrownBy( + () -> + transaction.execute( + status -> repository.retainCurrentExact(parent, changedMutation))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + + assertAppendOnly(dsl, parent.participationId()); + assertLeaseExpiresWhileParentLocked( + dsl, transaction, repository, parent, fixture, exactRetryObservation); + + assertThatThrownBy( + () -> + transaction.execute( + status -> repository.findCurrentExact(parent, freshCorrelation).orElseThrow())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + StoredEvidence historical = + transaction.execute( + status -> + repository + .findHistoricalExact(parent, request(fixture, UUID.randomUUID())) + .orElseThrow()); + assertThat(historical.originalLeaseExpiresAt()).isEqualTo(retryExpiry); + assertThat(historical.originalResponseBytes()).containsExactly(first.originalResponseBytes()); + } + + @Test + void freshInsertLeaseIsRecheckedAfterWaitingForTheExactParentLock() throws Exception { + String schema = "ss_world_attempt_wait_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + AccountStartSessionWorldOriginalAttemptEvidenceRepository repository = + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(dsl); + Fixture fixture = fixture(); + StoredParticipation parent = + transaction.execute( + status -> insertSyntheticParent(dsl, fixture, UUID.randomUUID(), false)); + assertThat(parent).isNotNull(); + + Instant expiry = databaseNow(dsl).plusMillis(3_000L); + Result observation = observation(fixture, UUID.randomUUID(), expiry); + assertLeaseExpiresWhileParentLocked(dsl, transaction, repository, parent, fixture, observation); + Record evidenceCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM account_start_session_world_original_attempt_evidence " + + "WHERE participation_id = ?", + parent.participationId()), + "evidence count query returned no row"); + assertThat(evidenceCount.get(0, Long.class)).isZero(); + + Instant expiredAt = databaseNow(dsl).minusSeconds(1L); + Result expiredObservation = observation(fixture, UUID.randomUUID(), expiredAt); + byte[] expiredResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(expiredObservation) + .toByteArray(); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO account_start_session_world_original_attempt_evidence " + + "(participation_id, target_namespace, game_session_owner_attempt_id, " + + "game_session_owner_mutation_id, game_session_owner_fence, " + + "original_lease_expires_at, original_response_bytes, original_response_digest) " + + "VALUES (?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", + parent.participationId(), + NAMESPACE, + fixture.ownerAttemptId(), + OWNER_MUTATION_ID, + OWNER_FENCE, + OffsetDateTime.ofInstant(expiredAt, ZoneOffset.UTC), + expiredResponse, + "sha256:" + sha256Hex(expiredResponse))) + .isInstanceOf(RuntimeException.class); + Record expiredEvidenceCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM account_start_session_world_original_attempt_evidence " + + "WHERE participation_id = ?", + parent.participationId()), + "evidence count query returned no row"); + assertThat(expiredEvidenceCount.get(0, Long.class)).isZero(); + } + + @Test + void settledParticipationCannotReceiveNewObservation() { + String schema = "ss_world_attempt_settled_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + AccountStartSessionWorldOriginalAttemptEvidenceRepository repository = + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(dsl); + Fixture fixture = fixture(); + UUID participationId = UUID.randomUUID(); + StoredParticipation parent = + transaction.execute( + status -> { + StoredParticipation inserted = + insertSyntheticParent(dsl, fixture, participationId, true); + return inserted; + }); + + assertThatThrownBy( + () -> + transaction.execute( + status -> + repository.retainCurrentExact( + parent, + observation( + fixture, UUID.randomUUID(), databaseNow(dsl).plusSeconds(30))))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + } + + private static void assertAppendOnly(DSLContext dsl, UUID participationId) { + String table = "account_start_session_world_original_attempt_evidence"; + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + + table + + " SET original_response_digest = original_response_digest " + + "WHERE participation_id = ?", + participationId)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM " + table + " WHERE participation_id = ?", participationId)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE " + table)).isInstanceOf(RuntimeException.class); + Record evidenceCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM " + table + " WHERE participation_id = ?", participationId), + "append-only evidence count query returned no row"); + assertThat(evidenceCount.get(0, Long.class)).isEqualTo(1L); + } + + private static void assertLeaseExpiresWhileParentLocked( + DSLContext dsl, + TransactionTemplate transaction, + AccountStartSessionWorldOriginalAttemptEvidenceRepository repository, + StoredParticipation parent, + Fixture fixture, + Result observation) + throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(2); + CountDownLatch parentLocked = new CountDownLatch(1); + CountDownLatch releaseParent = new CountDownLatch(1); + try { + Future holder = + executor.submit( + () -> + transaction.execute( + status -> { + dsl.fetchOne( + "SELECT participation_id FROM account_start_session_world_participations " + + "WHERE participation_id = ? FOR UPDATE", + parent.participationId()); + parentLocked.countDown(); + await(releaseParent); + return null; + })); + assertTrue(parentLocked.await(5, TimeUnit.SECONDS), "parent lock holder did not start"); + CountDownLatch writerStarted = new CountDownLatch(1); + Future writer = + executor.submit( + () -> { + writerStarted.countDown(); + return transaction.execute( + status -> repository.retainCurrentExact(parent, observation)); + }); + assertTrue(writerStarted.await(5, TimeUnit.SECONDS), "evidence writer did not start"); + awaitBlockedOnParentLock(dsl); + while (observation.originalLeaseExpiresAt().isAfter(databaseNow(dsl))) { + Thread.sleep(25L); + } + releaseParent.countDown(); + holder.get(5, TimeUnit.SECONDS); + assertThatThrownBy(() -> writer.get(5, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class) + .hasRootCauseMessage("Exact original StartSession attempt evidence unavailable"); + } finally { + releaseParent.countDown(); + executor.shutdownNow(); + } + } + + private static void awaitBlockedOnParentLock(DSLContext dsl) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + Record row = + dsl.fetchOne( + "SELECT count(*) FROM pg_stat_activity " + + "WHERE cardinality(pg_blocking_pids(pid)) > 0 " + + "AND query ILIKE '%account_start_session_world_participations%' "); + if (row != null && row.get(0, Long.class) > 0L) return; + Thread.sleep(20L); + } + throw new AssertionError("evidence writer did not block behind the Account participation lock"); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("test lock release was not signaled"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("test lock holder was interrupted", interrupted); + } + } + + private static StoredParticipation insertSyntheticParent( + DSLContext dsl, Fixture fixture, UUID participationId, boolean settled) { + dsl.execute("SET LOCAL session_replication_role = replica"); + dsl.execute( + "INSERT INTO account_start_session_world_participations " + + "(participation_id, participation_fence, control_plane_request_id, " + + "original_post_authorization_tuple, target_namespace, canonical_tenant_id, " + + "canonical_game_instance_id, game_session_owner_attempt_id, game_session_owner_fence, " + + "preparation_input_json, preparation_input_digest, created_at) " + + "OVERRIDING SYSTEM VALUE VALUES (?, 41, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ)) ", + participationId, + fixture.tuple().controlPlaneRequestId(), + fixture.tuple().canonicalBytes(), + NAMESPACE, + fixture.tenantId(), + fixture.gameInstanceId(), + OWNER_ATTEMPT_ID, + OWNER_FENCE, + fixture.preparationJson(), + fixture.preparationDigest(), + OffsetDateTime.ofInstant(Instant.parse("2026-10-09T00:00:00Z"), ZoneOffset.UTC)); + if (settled) { + byte[] terminal = "synthetic settled parent".getBytes(StandardCharsets.UTF_8); + dsl.execute( + "INSERT INTO account_start_session_world_participation_settlements " + + "(participation_id, outcome, world_execution_fence, terminal_bytes, terminal_digest) " + + "VALUES (?, 'ABORTED', 1, ?, ?)", + participationId, + terminal, + "sha256:" + sha256Hex(terminal)); + } + dsl.execute("SET LOCAL session_replication_role = origin"); + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM account_start_session_world_participations WHERE participation_id = ?", + participationId), + "synthetic Account participation insert produced no row"); + return new StoredParticipation( + UUID.fromString(row.get("participation_id", UUID.class).toString()), + row.get("participation_fence", Long.class), + row.get("control_plane_request_id", String.class), + row.get("original_post_authorization_tuple", byte[].class), + row.get("target_namespace", String.class), + row.get("canonical_tenant_id", UUID.class), + row.get("canonical_game_instance_id", UUID.class), + row.get("game_session_owner_attempt_id", UUID.class), + row.get("game_session_owner_fence", Long.class), + row.get("preparation_input_json", String.class), + row.get("preparation_input_digest", String.class), + row.get("producer_xid", Long.class), + row.get("created_at", OffsetDateTime.class), + List.of()); + } + + private static Fixture fixture() { + UUID actorId = UUID.fromString("d888ddc4-4a62-4b25-9bab-c4f94860c2ca"); + UUID tenantId = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); + UUID targetAccountId = UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); + UUID reservationOwnerId = UUID.fromString("ca1b63bf-f09f-4a55-96bf-a1fd2e22349e"); + String requestId = "start-session/original-attempt/" + UUID.randomUUID(); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + actorId, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, NAMESPACE), + new StartSessionOperatorAction.Target(17L, targetAccountId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "Synthetic Account participation integration proof")); + byte[] bundle = authorityBundle(preTuple, actorId, tenantId, requestId); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + "arfp/v1/key-1/" + "a".repeat(64), + reservationOwnerId, + 7L, + bundle, + new BundleReference("authorityEvidenceBundle/v1", "11", "13", "17")); + String preparationJson = "{\"identity\":{\"worldSlug\":\"synthetic-arena\"}}"; + return new Fixture( + tuple, + tenantId, + UUID.fromString("51c67424-324e-486d-b3ad-45b6e85c1a0d"), + OWNER_ATTEMPT_ID, + preparationJson, + "sha256:" + sha256Hex(preparationJson.getBytes(StandardCharsets.UTF_8)), + accountProjection(tuple)); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, + UUID actorId, + UUID tenantId, + String requestId) { + String tenant = tenantId.toString(); + String actor = actorId.toString(); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 1L, + "tenantAuthorityGeneration", Map.of(tenant, 1L), + "membershipAuthorityGeneration", Map.of(tenant, 1L), + "privateRealmGrantVersions", List.of()); + return AccountControlUiAuthority.canonical( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenant, "targetNamespace", NAMESPACE), + "actionFamily", + "StartSession", + "applicableAccountId", + actor, + "applicableTenantId", + tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "c".repeat(64), + "sourceEvidenceVersion", + "11", + "projectionStatus", + "CURRENT", + "evaluatedAt", + "2026-10-09T00:00:00Z", + "expiresAt", + "2026-10-09T00:03:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + "44444444-4444-4444-8444-444444444444", + "controlPlaneRequestId", + requestId, + "actionFamilyRequestIdentity", + Map.of("requestIdentityKind", "controlPlaneRequestId", "requestId", requestId), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + authorityTuple, + "membershipVersion", + Map.of(tenant, 2L), + "issuanceFence", + "9", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actor, + "controlUiTokenJti", + "55555555-5555-4555-8555-555555555555", + "role", + "tenantAdmin", + "accountGeneration", + "1", + "tenantGeneration", + "1"))); + } + + private static Result observation(Fixture fixture, UUID readId, Instant expiry) { + return new Result(request(fixture, readId), expiry, fixture.accountProjection()); + } + + private static Request request(Fixture fixture, UUID readId) { + return new Request( + readId, + NAMESPACE, + fixture.tuple().canonicalBytes(), + fixture.ownerAttemptId(), + OWNER_MUTATION_ID, + OWNER_FENCE); + } + + private static byte[] accountProjection(StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return AccountControlUiAuthority.canonical( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + 9L)); + } + + private static Instant databaseNow(DSLContext dsl) { + Record row = + Objects.requireNonNull( + dsl.fetchOne("SELECT clock_timestamp()"), "database clock query returned no row"); + return row.get(0, OffsetDateTime.class).toInstant(); + } + + private static String sha256Hex(byte[] bytes) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + + private record Fixture( + StartSessionPostAuthorizationExecutionTuple tuple, + UUID tenantId, + UUID gameInstanceId, + UUID ownerAttemptId, + String preparationJson, + String preparationDigest, + byte[] accountProjection) { + private Fixture { + accountProjection = accountProjection.clone(); + } + + @Override + public byte[] accountProjection() { + return accountProjection.clone(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java index 48a2958fa8..a2359e2659 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java @@ -53,6 +53,33 @@ void clearTransactionState() { TransactionSynchronizationManager.clear(); } + @Test + void timestampWritesAndExpiryPredicateUseExplicitPostgresTypes() { + MockStore store = new MockStore(); + var repository = repository(store); + var candidate = candidate(tuple()); + var created = inTransaction(() -> repository.createOrReadExact(candidate)); + var redeemed = + inTransaction( + () -> repository.redeemExact(redemption(candidate, OWNER_ATTEMPT_ID, 8L, OWNER_URI))); + + assertThat(created.issuance().issuedAt()).isEqualTo(candidate.issuedAt()); + assertThat(redeemed).isNotNull(); + assertThat(store.queries) + .anySatisfy( + sql -> + assertThat(sql) + .contains( + "cast(? as timestamptz), cast(? as timestamptz), " + + "cast(? as timestamptz), 'issued'")) + .anySatisfy( + sql -> + assertThat(sql) + .contains( + "redeemed_at = cast(? as timestamptz)", + "reference_expires_at > cast(? as timestamptz)")); + } + @Test void exactDuplicateReturnsOriginalOutputAndNeverReplacesIt() { MockStore store = new MockStore(); @@ -684,6 +711,7 @@ private static final class MockStore implements MockDataProvider { private final AtomicInteger databaseCallCount = new AtomicInteger(); private final AtomicInteger insertCount = new AtomicInteger(); private final AtomicInteger redemptionUpdateCount = new AtomicInteger(); + private final List queries = new java.util.ArrayList<>(); private String lastLockSql = ""; private StoredRow row; @@ -691,6 +719,7 @@ private static final class MockStore implements MockDataProvider { public MockResult[] execute(MockExecuteContext context) throws SQLException { databaseCallCount.incrementAndGet(); String sql = context.sql().stripLeading().toLowerCase(java.util.Locale.ROOT); + queries.add(sql); Object[] bind = context.bindings(); if (sql.startsWith("insert into account_start_session_operator_authorizations")) { if (row == null) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java new file mode 100644 index 0000000000..147fa56e34 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java @@ -0,0 +1,388 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.junit.jupiter.api.Test; + +/** Unit proof of exact closed-codec observation binding; no Game Session producer is exercised. */ +class AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest { + private static final String REQUEST_ID = + "start-session/original-attempt/2355f292-ab9c-458c-8d52-aef18b9254e8"; + private static final UUID PARTICIPATION_ID = + UUID.fromString("fa3555ac-e039-4827-9e04-eb0fa8cd37d4"); + private static final UUID ACTOR_ID = UUID.fromString("d888ddc4-4a62-4b25-9bab-c4f94860c2ca"); + private static final UUID TENANT_ID = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("ca1b63bf-f09f-4a55-96bf-a1fd2e22349e"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("51c67424-324e-486d-b3ad-45b6e85c1a0d"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"); + private static final UUID OWNER_MUTATION_ID = + UUID.fromString("f7811486-2bd4-41a0-9bf7-a351ce3a0c8f"); + private static final long OWNER_FENCE = 47L; + private static final String NAMESPACE = "world-runtime"; + private static final String LOGGING_URI = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final BundleReference BUNDLE_REFERENCE = + new BundleReference("authorityEvidenceBundle/v1", "11", "13", "17"); + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + + @Test + void closedCodecReadbackBindsCompleteTupleProjectionAndRejectsSubmicrosecondExpiry() { + Fixture fixture = fixture(); + Request expected = request(fixture, UUID.fromString("6a3922eb-96f5-4cc5-8e43-85c1bb3f49c0")); + Result exact = + new Result( + expected, Instant.parse("2026-10-09T00:02:00.123456Z"), fixture.accountProjection()); + byte[] completeResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(exact).toByteArray(); + + Result decoded = + AccountStartSessionWorldOriginalAttemptEvidenceRepository.validateResponse( + expected, completeResponse, fixture.parent()); + + assertThat(decoded.originalLeaseExpiresAt()).isEqualTo(exact.originalLeaseExpiresAt()); + assertThat(decoded.accountRedemptionProjection()).containsExactly(fixture.accountProjection()); + assertThat(decoded.request().expectedOwnerMutationId()).isEqualTo(OWNER_MUTATION_ID); + assertThat(decoded.phaseState()) + .isEqualTo(OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE); + + Result subMicrosecond = + new Result( + expected, Instant.parse("2026-10-09T00:02:00.123456789Z"), fixture.accountProjection()); + byte[] roundedTimestampCandidate = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(subMicrosecond) + .toByteArray(); + assertThatThrownBy( + () -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository.validateResponse( + expected, roundedTimestampCandidate, fixture.parent())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + + byte[] changedProjection = "not the exact Account projection".getBytes(StandardCharsets.UTF_8); + Result wrongProjection = + new Result(expected, exact.originalLeaseExpiresAt(), changedProjection); + assertThatThrownBy( + () -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository.validateResponse( + expected, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(wrongProjection) + .toByteArray(), + fixture.parent())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + + @Test + void freshReadCorrelationIsNotDurableIdentityButEveryOwnerBindingFieldIs() { + Fixture fixture = fixture(); + Request first = request(fixture, UUID.fromString("6a3922eb-96f5-4cc5-8e43-85c1bb3f49c0")); + Request retry = request(fixture, UUID.fromString("21fa4d95-98f0-4c19-a5b6-864bd0467f94")); + + assertThatCode( + () -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository + .requireSameSemanticRequest(first, retry)) + .doesNotThrowAnyException(); + + assertMismatch( + first, + fixture.namespace(), + fixture.parent().originalPostAuthorizationTuple(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + OWNER_FENCE + 1L); + assertMismatch( + first, + fixture.namespace(), + fixture.parent().originalPostAuthorizationTuple(), + UUID.fromString("274c7a54-2f2a-409f-9eac-7b8a7733e590"), + OWNER_MUTATION_ID, + OWNER_FENCE); + assertMismatch( + first, + fixture.namespace(), + fixture.parent().originalPostAuthorizationTuple(), + OWNER_ATTEMPT_ID, + UUID.fromString("1f2d6f4e-1202-4bdb-bcd4-f3c14e4cc764"), + OWNER_FENCE); + assertThatThrownBy( + () -> + new Request( + UUID.randomUUID(), + "other-runtime", + fixture.parent().originalPostAuthorizationTuple(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + OWNER_FENCE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("target the exact requested namespace"); + + Request changedTuple = + new Request( + UUID.fromString("578bc4d6-6a96-4bb9-a6f9-2d4d54f0c547"), + fixture.namespace(), + tupleFor("Changed exact tuple").canonicalBytes(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + OWNER_FENCE); + assertThatThrownBy( + () -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository + .requireSameSemanticRequest(first, changedTuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + + @Test + void storedResponseIsDefensiveAndItsDigestCoversTheCompleteResponseBytes() { + Fixture fixture = fixture(); + Request request = request(fixture, UUID.fromString("6a3922eb-96f5-4cc5-8e43-85c1bb3f49c0")); + Result result = new Result(request, NOW.plusSeconds(120), fixture.accountProjection()); + byte[] bytes = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result).toByteArray(); + String digest = "sha256:" + sha256Hex(bytes); + StoredEvidence stored = + new StoredEvidence( + PARTICIPATION_ID, + OWNER_MUTATION_ID, + result.originalLeaseExpiresAt(), + bytes, + digest, + result); + bytes[0] ^= 0x01; + + assertThat(stored.originalResponseBytes()) + .containsExactly( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result).toByteArray()); + assertThat(stored.originalResponseDigest()).isEqualTo(digest); + assertThat(stored.toString()) + .contains("projection=") + .contains("responseBytes="); + assertThatThrownBy( + () -> + new StoredEvidence( + PARTICIPATION_ID, + OWNER_MUTATION_ID, + result.originalLeaseExpiresAt(), + new byte[] {1}, + digest, + result)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest differs"); + } + + private static void assertMismatch( + Request expected, String namespace, byte[] tuple, UUID attempt, UUID mutation, long fence) { + Request changed = new Request(UUID.randomUUID(), namespace, tuple, attempt, mutation, fence); + assertThatThrownBy( + () -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository + .requireSameSemanticRequest(expected, changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + + private static Request request(Fixture fixture, UUID readId) { + return new Request( + readId, + fixture.namespace(), + fixture.parent().originalPostAuthorizationTuple(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + OWNER_FENCE); + } + + private static Fixture fixture() { + StartSessionPostAuthorizationExecutionTuple tuple = + tupleFor("Original attempt evidence repository proof"); + String preparationJson = "{\"identity\":{\"worldSlug\":\"arena\"}}"; + StoredParticipation parent = + new StoredParticipation( + PARTICIPATION_ID, + 41L, + REQUEST_ID, + tuple.canonicalBytes(), + NAMESPACE, + TENANT_ID, + GAME_INSTANCE_ID, + OWNER_ATTEMPT_ID, + OWNER_FENCE, + preparationJson, + "sha256:" + sha256Hex(preparationJson.getBytes(StandardCharsets.UTF_8)), + 2_147_483_651L, + OffsetDateTime.ofInstant(NOW, ZoneOffset.UTC), + List.of()); + return new Fixture(parent, tuple, accountProjection(tuple)); + } + + private static StartSessionPostAuthorizationExecutionTuple tupleFor(String auditReason) { + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + REQUEST_ID, + ACTOR_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + auditReason)); + byte[] bundle = authorityBundle(preTuple); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + LOGGING_URI, + "arfp/v1/key-1/" + "a".repeat(64), + RESERVATION_OWNER_ID, + 7L, + bundle, + BUNDLE_REFERENCE); + return tuple; + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = tuple.action().scope().tenantId().toString(); + String actor = tuple.actor().accountId().toString(); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 1L, + "tenantAuthorityGeneration", Map.of(tenant, 1L), + "membershipAuthorityGeneration", Map.of(tenant, 1L), + "privateRealmGrantVersions", List.of()); + return AccountControlUiAuthority.canonical( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenant, "targetNamespace", NAMESPACE), + "actionFamily", + "StartSession", + "applicableAccountId", + actor, + "applicableTenantId", + tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "c".repeat(64), + "sourceEvidenceVersion", + BUNDLE_REFERENCE.sourceVersion(), + "projectionStatus", + "CURRENT", + "evaluatedAt", + NOW.toString(), + "expiresAt", + NOW.plusSeconds(180).toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + "44444444-4444-4444-8444-444444444444", + "controlPlaneRequestId", + REQUEST_ID, + "actionFamilyRequestIdentity", + Map.of("requestIdentityKind", "controlPlaneRequestId", "requestId", REQUEST_ID), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + authorityTuple, + "membershipVersion", + Map.of(tenant, 2L), + "issuanceFence", + "9", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actor, + "controlUiTokenJti", + "55555555-5555-4555-8555-555555555555", + "role", + "tenantAdmin", + "accountGeneration", + "1", + "tenantGeneration", + "1"))); + } + + private static byte[] accountProjection(StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return AccountControlUiAuthority.canonical( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + 9L)); + } + + private static String sha256Hex(byte[] bytes) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + + private record Fixture( + StoredParticipation parent, + StartSessionPostAuthorizationExecutionTuple tuple, + byte[] accountProjection) { + private Fixture { + accountProjection = accountProjection.clone(); + } + + private String namespace() { + return NAMESPACE; + } + + @Override + public byte[] accountProjection() { + return accountProjection.clone(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java new file mode 100644 index 0000000000..c0ed07f307 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java @@ -0,0 +1,769 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.Candidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquiredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquisitionRequest; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +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.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Synthetic composition proof only; current Game Session and Account storage are mocked. */ +class AccountStartSessionWorldParticipationAcquisitionServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID ACCOUNT_ID = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TENANT_ID = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_MUTATION_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("4a3fc69f-a18a-4b94-b1d1-2e8b4c3f0e4b"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final long PARTICIPATION_FENCE = 31L; + private static final long GAME_SESSION_FENCE = 37L; + private static final String PREPARATION_INPUT = + "{ \"selected\" : \"immutable source\", \"revision\": 3 }\n"; + private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-12T00:00:00Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactWorldPeerWithoutEndUserBeforeDecodingOrCallingDependencies() { + Harness harness = new Harness(); + + assertCode(Status.Code.UNAUTHENTICATED, () -> harness.service.acquire(null)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + peer( + NAMESPACE, + "game-session-service", + () -> harness.service.acquire(request(new byte[0])))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + peer( + "other-runtime", + "world-management-service", + () -> harness.service.acquire(request(new byte[0])))); + SessionContext.setContext("123", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> authorized(() -> harness.service.acquire(request(new byte[0])))); + + verifyNoInteractions(harness.issuer); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptEvidenceRepository); + verifyNoInteractions(harness.gameSessionClient); + assertThat(harness.readbackTransactions.begins).isZero(); + } + + @Test + void rejectsAmbientSqlOrSynchronizationBeforeDecodingOrRemoteRead() { + Harness harness = new Harness(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(new byte[0])))); + TransactionSynchronizationManager.clear(); + TransactionSynchronizationManager.initSynchronization(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(new byte[0])))); + + verifyNoInteractions(harness.issuer); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptEvidenceRepository); + verifyNoInteractions(harness.gameSessionClient); + assertThat(harness.readbackTransactions.begins).isZero(); + } + + @Test + void rejectsUnavailableOrSubstitutedGameSessionRequestEchoBeforeIssuerCallbackOrWrites() { + List> substitutedEchoes = + List.of( + ignored -> null, + read -> + new Request( + read.readRequestId(), + read.targetNamespace(), + read.canonicalPostAuthorizationTuple(), + uuid("11111111-1111-4111-8111-111111111111"), + read.expectedOwnerMutationId(), + read.expectedOwnerFence()), + read -> + new Request( + read.readRequestId(), + read.targetNamespace(), + read.canonicalPostAuthorizationTuple(), + read.expectedOwnerAttemptId(), + uuid("22222222-2222-4222-8222-222222222222"), + read.expectedOwnerFence()), + read -> + new Request( + read.readRequestId(), + read.targetNamespace(), + read.canonicalPostAuthorizationTuple(), + read.expectedOwnerAttemptId(), + read.expectedOwnerMutationId(), + read.expectedOwnerFence() + 1)); + + for (Function substituteEcho : substitutedEchoes) { + Harness harness = new Harness(); + when(harness.gameSessionClient.read(any(Request.class))) + .thenAnswer( + invocation -> { + assertNoSql(); + harness.steps.add("remote-read"); + Request expected = invocation.getArgument(0); + Request echoed = substituteEcho.apply(expected); + return echoed == null + ? null + : new Result( + echoed, ORIGINAL_LEASE_EXPIRY, projection(harness.tuple, Map.of())); + }); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(null)))); + + assertThat(harness.steps).containsExactly("remote-read"); + verify(harness.gameSessionClient).read(any(Request.class)); + verify(harness.issuer, times(0)) + .withCurrentWorldReceivingParticipationCurrentness( + any(byte[].class), eq(GAME_SESSION_ATTEMPT_ID), eq(GAME_SESSION_FENCE), any()); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptEvidenceRepository); + assertThat(harness.readbackTransactions.begins).isZero(); + } + } + + @Test + void readsGameSessionOutsideSqlThenWritesAtomicallyAndPerformsIndependentLookupOnlyReadback() { + Harness harness = new Harness(); + harness.configureSuccess(); + + AcquiredParticipation acquired = authorized(() -> harness.service.acquire(request(null))); + + assertThat(acquired.participation().participationId()).isEqualTo(PARTICIPATION_ID); + assertThat(acquired.participation().participationFence()).isEqualTo(PARTICIPATION_FENCE); + assertThat(acquired.participation().originalPostAuthorizationTuple()) + .containsExactly(harness.tuple.canonicalBytes()); + assertThat(acquired.participation().sources()).hasSize(1); + assertThat(acquired.originalAttemptEvidence().gameSessionOwnerMutationId()) + .isEqualTo(GAME_SESSION_MUTATION_ID); + assertThat(acquired.originalAttemptEvidence().originalResponseBytes()).isNotEmpty(); + assertThat(harness.steps) + .containsExactly( + "remote-read", + "issuer-currentness", + "participation-write", + "proof-write", + "participation-readback", + "proof-readback"); + assertThat(harness.readbackTransactions.begins).isEqualTo(1); + assertThat(harness.readbackTransactions.commits).isEqualTo(1); + verify(harness.gameSessionClient).read(any(Request.class)); + verify(harness.issuer) + .withCurrentWorldReceivingParticipationCurrentness( + eq(harness.tuple.canonicalBytes()), + eq(GAME_SESSION_ATTEMPT_ID), + eq(GAME_SESSION_FENCE), + any()); + verify(harness.participationRepository).createOrReadExact(any(Candidate.class)); + verify(harness.attemptEvidenceRepository) + .retainCurrentExact(any(StoredParticipation.class), any(Result.class)); + verify(harness.participationRepository).findCurrentExact(any(Candidate.class)); + verify(harness.attemptEvidenceRepository) + .findCurrentExact(any(StoredParticipation.class), any(Request.class)); + } + + @Test + void retriesTheSameOriginalTupleWithFreshGameSessionReadsAndCurrentAccountChecks() { + Harness harness = new Harness(); + harness.configureSuccess(); + var originalRequest = request(null); + + AcquiredParticipation first = authorized(() -> harness.service.acquire(originalRequest)); + AcquiredParticipation second = authorized(() -> harness.service.acquire(originalRequest)); + + ArgumentCaptor requests = ArgumentCaptor.forClass(Request.class); + verify(harness.gameSessionClient, times(2)).read(requests.capture()); + assertThat(requests.getAllValues()).hasSize(2); + assertThat(requests.getAllValues().get(0).readRequestId()) + .isNotEqualTo(requests.getAllValues().get(1).readRequestId()); + for (Request read : requests.getAllValues()) { + assertThat(read.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(read.canonicalPostAuthorizationTuple()) + .containsExactly(harness.tuple.canonicalBytes()); + assertThat(read.expectedOwnerMutationId()).isEqualTo(GAME_SESSION_MUTATION_ID); + assertThat(read.expectedOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); + assertThat(read.expectedOwnerFence()).isEqualTo(GAME_SESSION_FENCE); + } + assertThat(first.participation().participationId()) + .isEqualTo(second.participation().participationId()); + assertThat(first.originalAttemptEvidence().originalResponseBytes()) + .containsExactly(second.originalAttemptEvidence().originalResponseBytes()); + assertThat(harness.readbackTransactions.begins).isEqualTo(2); + assertThat(harness.readbackTransactions.commits).isEqualTo(2); + assertThat(harness.steps) + .containsExactly( + "remote-read", + "issuer-currentness", + "participation-write", + "proof-write", + "participation-readback", + "proof-readback", + "remote-read", + "issuer-currentness", + "participation-write", + "proof-write", + "participation-readback", + "proof-readback"); + } + + @Test + void rejectsChangedAccountRedemptionProjectionBeforeCurrentnessOrWrites() { + Harness harness = new Harness(); + harness.configureClientResult(projection(harness.tuple, Map.of("unbound", "changed"))); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(null)))); + + assertThat(harness.steps).containsExactly("remote-read"); + verify(harness.issuer, times(0)) + .withCurrentWorldReceivingParticipationCurrentness( + any(byte[].class), eq(GAME_SESSION_ATTEMPT_ID), eq(GAME_SESSION_FENCE), any()); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptEvidenceRepository); + assertThat(harness.readbackTransactions.begins).isZero(); + } + + @Test + void rejectsChangedCommittedSourceVectorDuringIndependentReadbackWithoutRetryWrite() { + Harness harness = new Harness(); + harness.configureSuccess(); + harness.participationReadback.set( + participation(harness.tuple, List.of(sourceEvidence("different source")))); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(null)))); + + assertThat(harness.readbackTransactions.begins).isEqualTo(1); + // The lookup-only transaction completes before the exact source-vector comparison denies. + assertThat(harness.readbackTransactions.commits).isEqualTo(1); + verify(harness.participationRepository, times(1)).createOrReadExact(any(Candidate.class)); + verify(harness.participationRepository, times(1)).findCurrentExact(any(Candidate.class)); + } + + @Test + void missingPostCommitReadbackDeniesAndDoesNotRepeatTheParticipationWrite() { + Harness harness = new Harness(); + harness.configureSuccess(); + harness.participationMissingOnReadback = true; + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(null)))); + + assertThat(harness.readbackTransactions.begins).isEqualTo(1); + assertThat(harness.readbackTransactions.rollbacks).isEqualTo(1); + verify(harness.participationRepository, times(1)).createOrReadExact(any(Candidate.class)); + verify(harness.participationRepository, times(1)).findCurrentExact(any(Candidate.class)); + verify(harness.attemptEvidenceRepository, times(1)) + .retainCurrentExact(any(StoredParticipation.class), any(Result.class)); + verify(harness.attemptEvidenceRepository, times(0)) + .findCurrentExact(any(StoredParticipation.class), any(Request.class)); + } + + private static AcquisitionRequest request(byte[] tupleBytes) { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + return new AcquisitionRequest( + tupleBytes == null ? tuple.canonicalBytes() : tupleBytes, + GAME_SESSION_MUTATION_ID, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + GAME_INSTANCE_ID, + PREPARATION_INPUT, + digest(PREPARATION_INPUT)); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + UUID targetOwnerId = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwnerId = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + String requestId = "world-participation-original-request"; + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + ACCOUNT_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(91L, targetOwnerId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic World participation composition proof")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + reservationOwnerId, + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String actorId = tuple.actor().accountId().toString(); + String tenantId = tuple.action().scope().tenantId().toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-10T00:00:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map human = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", actorId, + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + human); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static byte[] projection( + StartSessionPostAuthorizationExecutionTuple tuple, Map additionalFields) { + var bundle = StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + Map projection = + Map.of( + "projectionSchemaId", "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", "1", + "authorizationReferenceFingerprint", tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", bundle.jsonValue(), + "issuanceOperationId", bundle.issuanceOperationId().toString(), + "issuanceFence", Long.parseLong(tuple.issuanceFence())); + if (additionalFields.isEmpty()) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + var changed = new java.util.LinkedHashMap<>(projection); + changed.putAll(additionalFields); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(changed)); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static AccountStartSessionAuthorityCapture capture( + StartSessionPostAuthorizationExecutionTuple tuple) { + SourceEvidence source = sourceEvidence("current source"); + var bundle = StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + byte[] signerReceipt = "synthetic-signer-receipt".getBytes(StandardCharsets.UTF_8); + Map snapshot = + Map.ofEntries( + Map.entry("schema", "account-start-session-authority-snapshot/v1"), + Map.entry("controlPlaneRequestId", tuple.controlPlaneRequestId()), + Map.entry( + "preAuthorizationTuple", + Base64.getEncoder() + .encodeToString( + tuple + .preAuthorizationTuple() + .canonicalJson() + .getBytes(StandardCharsets.UTF_8))), + Map.entry("mutationDigest", tuple.mutationDigest()), + Map.entry("accountId", tuple.preAuthorizationTuple().actor().accountId().toString()), + Map.entry( + "tenantId", tuple.preAuthorizationTuple().action().scope().tenantId().toString()), + Map.entry("targetOwner", tuple.preAuthorizationTuple().targetOwner()), + Map.entry("loggingWorkloadUri", tuple.authenticatedWorkloadIdentity()), + Map.entry("reservationOwnerId", tuple.reservationOwnerId().toString()), + Map.entry("reservationClaimFence", Long.toString(tuple.reservationClaimFence())), + Map.entry("controlUiOperationId", bundle.issuanceOperationId().toString()), + Map.entry("controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc"), + Map.entry("controlUiTokenHash", "sha256:" + "d".repeat(64)), + Map.entry("controlUiSignerReceipt", Base64.getEncoder().encodeToString(signerReceipt)), + Map.entry("controlUiSignerReceiptSha256", sha256(signerReceipt)), + Map.entry( + "sourceVectorEvidence", + Base64.getEncoder().encodeToString(source.canonicalBytes())), + Map.entry( + "sourceVector", + List.of(Base64.getEncoder().encodeToString(source.canonicalBytes()))), + Map.entry("outboxCheckpoints", Map.of()), + Map.entry("authorityTuple", bundle.authorityTuple()), + Map.entry("membershipVersion", bundle.membershipVersion()), + Map.entry("accountIdentitySource", "ACCOUNT_UUID"), + Map.entry("issuanceFence", tuple.issuanceFence()), + Map.entry("issuanceFenceSourceVersion", "17")); + try { + return AccountStartSessionAuthorityCapture.create( + tuple.controlPlaneRequestId(), + 17L, + 31L, + "123456", + "2026-10-09T00:00:00.000Z", + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot))); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static SourceEvidence sourceEvidence(String detail) { + return new SourceEvidence( + SourceKind.ACCOUNT, + ACCOUNT_ID.toString(), + "2", + "17", + null, + null, + detail.getBytes(StandardCharsets.UTF_8)); + } + + private static StoredParticipation participation( + StartSessionPostAuthorizationExecutionTuple tuple, List sources) { + return new StoredParticipation( + PARTICIPATION_ID, + PARTICIPATION_FENCE, + tuple.controlPlaneRequestId(), + tuple.canonicalBytes(), + NAMESPACE, + TENANT_ID, + GAME_INSTANCE_ID, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + PREPARATION_INPUT, + digest(PREPARATION_INPUT), + 987L, + OffsetDateTime.parse("2026-10-09T00:00:00Z"), + sources); + } + + private static SourceEvidence participationSource(SourceEvidence source) { + return SourceEvidence.fromStored(source.canonicalBytes()); + } + + private static String digest(String value) { + return "sha256:" + + HexFormat.of().formatHex(sha256Bytes(value.getBytes(StandardCharsets.UTF_8))); + } + + private static byte[] sha256Bytes(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String sha256(byte[] value) { + return HexFormat.of().formatHex(sha256Bytes(value)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static T authorized(java.util.function.Supplier action) { + return peer(NAMESPACE, "world-management-service", action); + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static void assertWritableReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static final class Harness { + final AccountStartSessionOperatorAuthorizationService issuer = + mock(AccountStartSessionOperatorAuthorizationService.class); + final AccountStartSessionWorldParticipationRepository participationRepository = + mock(AccountStartSessionWorldParticipationRepository.class); + final AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptEvidenceRepository = + mock(AccountStartSessionWorldOriginalAttemptEvidenceRepository.class); + final OriginalStartSessionCurrentAttemptClient gameSessionClient = + mock(OriginalStartSessionCurrentAttemptClient.class); + final OwnerTransactions readbackTransactions = new OwnerTransactions(); + final StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + final StoredParticipation committedParticipation = + participation(tuple, List.of(participationSource(sourceEvidence("current source")))); + final AtomicReference participationReadback = + new AtomicReference<>(committedParticipation); + final AtomicReference retainedProof = new AtomicReference<>(); + final List steps = new ArrayList<>(); + final AccountStartSessionWorldParticipationAcquisitionService service = + new AccountStartSessionWorldParticipationAcquisitionService( + issuer, + participationRepository, + attemptEvidenceRepository, + gameSessionClient, + readbackTransactions, + NAMESPACE); + boolean participationMissingOnReadback; + + void configureSuccess() { + configureClientResult(projection(tuple, Map.of())); + doAnswer( + invocation -> { + assertNoSql(); + steps.add("issuer-currentness"); + @SuppressWarnings("unchecked") + Function callback = + invocation.getArgument(3); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.initSynchronization(); + try { + return callback.apply(capture(tuple)); + } finally { + TransactionSynchronizationManager.clear(); + } + }) + .when(issuer) + .withCurrentWorldReceivingParticipationCurrentness( + any(byte[].class), eq(GAME_SESSION_ATTEMPT_ID), eq(GAME_SESSION_FENCE), any()); + when(participationRepository.createOrReadExact(any(Candidate.class))) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("participation-write"); + return committedParticipation; + }); + when(attemptEvidenceRepository.retainCurrentExact( + any(StoredParticipation.class), any(Result.class))) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("proof-write"); + StoredParticipation exactParticipation = invocation.getArgument(0); + Result observation = invocation.getArgument(1); + StoredEvidence existing = retainedProof.get(); + if (existing != null) return existing; + StoredEvidence created = storedEvidence(exactParticipation, observation); + retainedProof.set(created); + return created; + }); + when(participationRepository.findCurrentExact(any(Candidate.class))) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("participation-readback"); + return participationMissingOnReadback + ? Optional.empty() + : Optional.of(participationReadback.get()); + }); + when(attemptEvidenceRepository.findCurrentExact( + any(StoredParticipation.class), any(Request.class))) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("proof-readback"); + return Optional.ofNullable(retainedProof.get()); + }); + } + + void configureClientResult(byte[] projectionBytes) { + when(gameSessionClient.read(any(Request.class))) + .thenAnswer( + invocation -> { + assertNoSql(); + steps.add("remote-read"); + Request read = invocation.getArgument(0); + return new Result(read, ORIGINAL_LEASE_EXPIRY, projectionBytes); + }); + } + } + + private static StoredEvidence storedEvidence( + StoredParticipation participation, Result observation) { + byte[] responseBytes = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observation).toByteArray(); + return new StoredEvidence( + participation.participationId(), + GAME_SESSION_MUTATION_ID, + observation.originalLeaseExpiresAt(), + responseBytes, + "sha256:" + sha256(responseBytes), + observation); + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + int rollbacks; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertNoSql(); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + rollbacks++; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionCurrentAttemptClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionCurrentAttemptClient.java new file mode 100644 index 0000000000..df09b2de3e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionCurrentAttemptClient.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.common.gamesession; + +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.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +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.gamesession.v1.OriginalStartSessionCurrentAttemptReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicit file-backed mTLS client for the unregistered Account-authenticated Game Session read. + */ +public final class GrpcOriginalStartSessionCurrentAttemptClient + extends AbstractReloadingBlockingGrpcClient< + OriginalStartSessionCurrentAttemptReadServiceGrpc + .OriginalStartSessionCurrentAttemptReadServiceBlockingStub> + implements OriginalStartSessionCurrentAttemptClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcOriginalStartSessionCurrentAttemptClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcOriginalStartSessionCurrentAttemptClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning caller explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Current original StartSession attempt client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Current original StartSession attempt client has no gRPC stub"); + } + initialized = true; + } + + /** Reads one bounded live-attempt observation outside all ambient SQL transaction state. */ + @Override + public Result read(Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Current original StartSession attempt read requires no ambient transaction or synchronization"); + } + Objects.requireNonNull(request, "current original StartSession attempt request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Current original StartSession attempt must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readOriginalStartSessionCurrentAttempt( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request)); + try { + return OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Session returned invalid current original StartSession attempt evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected OriginalStartSessionCurrentAttemptReadServiceGrpc + .OriginalStartSessionCurrentAttemptReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + return OriginalStartSessionCurrentAttemptReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private OriginalStartSessionCurrentAttemptReadServiceGrpc + .OriginalStartSessionCurrentAttemptReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Current original StartSession attempt client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Current original StartSession attempt 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( + "Current original StartSession attempt reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Current original StartSession attempt reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Current original StartSession attempt " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Current original StartSession attempt " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClient.java new file mode 100644 index 0000000000..7b3714deda --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClient.java @@ -0,0 +1,13 @@ +package net.firedevops.firemud.common.gamesession; + +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; + +/** Reads one exact current original Game Session attempt as a point-in-time observation. */ +public interface OriginalStartSessionCurrentAttemptClient { + /** + * Returns an observation only. The result is not a transferable claim, lease renewal, or + * continuous authorization to redeem, execute, or admit. + */ + Result read(Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidence.java new file mode 100644 index 0000000000..47662174f7 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidence.java @@ -0,0 +1,190 @@ +package net.firedevops.firemud.common.gamesession; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; + +/** Observation-only evidence for one exact, currently leased original StartSession attempt. */ +public final class OriginalStartSessionCurrentAttemptEvidence { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_REQUEST_BYTES = + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + 512; + public static final int MAX_PROJECTION_BYTES = + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES; + public static final String PENDING_PHASE = "OWNER_EXECUTION_PENDING"; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + private OriginalStartSessionCurrentAttemptEvidence() {} + + public static String projectionDigest(byte[] projection) { + Objects.requireNonNull(projection, "Account redemption projection is required"); + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(projection)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + /** Exact request selector; all byte arrays are defensively copied. */ + public static final class Request { + private final UUID readRequestId; + private final String targetNamespace; + private final StartSessionPostAuthorizationExecutionTuple originalTuple; + private final byte[] originalTupleBytes; + private final UUID expectedOwnerAttemptId; + private final UUID expectedOwnerMutationId; + private final long expectedOwnerFence; + + public Request( + UUID readRequestId, + String targetNamespace, + byte[] canonicalPostAuthorizationTuple, + UUID expectedOwnerAttemptId, + UUID expectedOwnerMutationId, + long expectedOwnerFence) { + this.readRequestId = requireUuid(readRequestId, "readRequestId"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be a valid workload namespace"); + } + this.targetNamespace = targetNamespace; + Objects.requireNonNull( + canonicalPostAuthorizationTuple, "complete original tuple is required"); + if (canonicalPostAuthorizationTuple.length == 0 + || canonicalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException("Complete original tuple is empty or exceeds its bound"); + } + this.originalTupleBytes = canonicalPostAuthorizationTuple.clone(); + this.originalTuple = + StartSessionPostAuthorizationExecutionTuple.decode(this.originalTupleBytes); + if (!Arrays.equals(this.originalTuple.canonicalBytes(), this.originalTupleBytes) + || !targetNamespace.equals( + this.originalTuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw new IllegalArgumentException( + "Original tuple must be canonical and target the exact requested namespace"); + } + this.expectedOwnerAttemptId = requireUuid(expectedOwnerAttemptId, "ownerAttemptId"); + this.expectedOwnerMutationId = requireUuid(expectedOwnerMutationId, "ownerMutationId"); + if (expectedOwnerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + this.expectedOwnerFence = expectedOwnerFence; + } + + public UUID readRequestId() { + return readRequestId; + } + + public String targetNamespace() { + return targetNamespace; + } + + public StartSessionPostAuthorizationExecutionTuple originalTuple() { + return originalTuple; + } + + public byte[] canonicalPostAuthorizationTuple() { + return originalTupleBytes.clone(); + } + + public UUID expectedOwnerAttemptId() { + return expectedOwnerAttemptId; + } + + public UUID expectedOwnerMutationId() { + return expectedOwnerMutationId; + } + + public long expectedOwnerFence() { + return expectedOwnerFence; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof Request that)) { + return false; + } + return expectedOwnerFence == that.expectedOwnerFence + && readRequestId.equals(that.readRequestId) + && targetNamespace.equals(that.targetNamespace) + && Arrays.equals(originalTupleBytes, that.originalTupleBytes) + && expectedOwnerAttemptId.equals(that.expectedOwnerAttemptId) + && expectedOwnerMutationId.equals(that.expectedOwnerMutationId); + } + + @Override + public int hashCode() { + int result = + Objects.hash( + readRequestId, + targetNamespace, + expectedOwnerAttemptId, + expectedOwnerMutationId, + expectedOwnerFence); + return 31 * result + Arrays.hashCode(originalTupleBytes); + } + } + + /** Exact successful point-in-time response, including the original unchanged lease expiry. */ + public static final class Result { + private final Request request; + private final Instant originalLeaseExpiresAt; + private final byte[] accountRedemptionProjection; + + public Result(Request request, Instant originalLeaseExpiresAt, byte[] projection) { + this.request = Objects.requireNonNull(request, "request is required"); + this.originalLeaseExpiresAt = + Objects.requireNonNull(originalLeaseExpiresAt, "original lease expiry is required"); + Objects.requireNonNull(projection, "attached Account projection is required"); + if (projection.length == 0 || projection.length > MAX_PROJECTION_BYTES) { + throw new IllegalArgumentException( + "Attached Account projection is empty or exceeds its bound"); + } + this.accountRedemptionProjection = projection.clone(); + } + + public Request request() { + return request; + } + + public String phaseState() { + return PENDING_PHASE; + } + + public Instant originalLeaseExpiresAt() { + return originalLeaseExpiresAt; + } + + public byte[] accountRedemptionProjection() { + return accountRedemptionProjection.clone(); + } + + public String accountRedemptionProjectionDigest() { + return projectionDigest(accountRedemptionProjection); + } + } + + private static UUID requireUuid(UUID value, String name) { + Objects.requireNonNull(value, name + " is required"); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a canonical non-nil UUID"); + } + return value; + } + + static boolean isCanonicalDigest(String value) { + return value != null && SHA256.matcher(value).matches(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.java new file mode 100644 index 0000000000..8dca147f44 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; + +/** Closed schema-1 wire mapping for an observation-only live original-attempt read. */ +public final class OriginalStartSessionCurrentAttemptEvidenceGrpcCodec { + private static final long MIN_TIMESTAMP_SECONDS = -62_135_596_800L; + private static final long MAX_TIMESTAMP_SECONDS = 253_402_300_799L; + private static final int MAX_TIMESTAMP_NANOS = 999_999_999; + + public static final int MAX_RESPONSE_BYTES = + OriginalStartSessionCurrentAttemptEvidence.MAX_REQUEST_BYTES + + OriginalStartSessionCurrentAttemptEvidence.MAX_PROJECTION_BYTES + + 1024; + + private OriginalStartSessionCurrentAttemptEvidenceGrpcCodec() {} + + public static ReadOriginalStartSessionCurrentAttemptRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var wire = + ReadOriginalStartSessionCurrentAttemptRequest.newBuilder() + .setSchemaVersion(OriginalStartSessionCurrentAttemptEvidence.SCHEMA_VERSION) + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalPostAuthorizationTuple( + ByteString.copyFrom(request.canonicalPostAuthorizationTuple())) + .setExpectedOwnerAttemptId(request.expectedOwnerAttemptId().toString()) + .setExpectedOwnerMutationId(request.expectedOwnerMutationId().toString()) + .setExpectedOwnerFence(request.expectedOwnerFence()) + .build(); + if (wire.getSerializedSize() > OriginalStartSessionCurrentAttemptEvidence.MAX_REQUEST_BYTES) { + throw new IllegalArgumentException("Current-attempt request exceeds its byte bound"); + } + return wire; + } + + /** Decodes only a closed exact selector; it does not authenticate the caller. */ + public static Request fromRequest(ReadOriginalStartSessionCurrentAttemptRequest request) { + Objects.requireNonNull(request, "request"); + if (request.getSerializedSize() > OriginalStartSessionCurrentAttemptEvidence.MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() + != OriginalStartSessionCurrentAttemptEvidence.SCHEMA_VERSION) { + throw new IllegalArgumentException( + "Closed bounded schema-1 current-attempt request required"); + } + try { + Request decoded = + new Request( + canonicalUuid(request.getReadRequestId(), "read_request_id"), + request.getTargetNamespace(), + request.getCanonicalPostAuthorizationTuple().toByteArray(), + canonicalUuid(request.getExpectedOwnerAttemptId(), "expected_owner_attempt_id"), + canonicalUuid(request.getExpectedOwnerMutationId(), "expected_owner_mutation_id"), + request.getExpectedOwnerFence()); + if (!toRequest(decoded).equals(request)) { + throw new IllegalArgumentException("Current-attempt request is not canonical"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Exact canonical current-attempt request required", malformed); + } + } + + public static ReadOriginalStartSessionCurrentAttemptResponse toResponse(Result result) { + Objects.requireNonNull(result, "result"); + var response = + ReadOriginalStartSessionCurrentAttemptResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setPhaseState(result.phaseState()) + .setOriginalLeaseExpiresAt(toTimestamp(result.originalLeaseExpiresAt())) + .setAccountRedemptionProjection( + ByteString.copyFrom(result.accountRedemptionProjection())) + .setAccountRedemptionProjectionDigest(result.accountRedemptionProjectionDigest()) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Current-attempt response exceeds its byte bound"); + } + return response; + } + + public static Result fromResponse( + Request expectedRequest, ReadOriginalStartSessionCurrentAttemptResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || !response.hasOriginalLeaseExpiresAt() + || !response.getOriginalLeaseExpiresAt().getUnknownFields().asMap().isEmpty() + || !OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( + response.getPhaseState()) + || response.getAccountRedemptionProjection().isEmpty()) { + throw new IllegalArgumentException( + "Closed complete pending current-attempt response required"); + } + Request echoed = fromRequest(response.getRequest()); + if (!expectedRequest.equals(echoed)) { + throw new IllegalArgumentException("Current-attempt response changed the exact read request"); + } + byte[] projection = response.getAccountRedemptionProjection().toByteArray(); + Result result = + new Result(echoed, fromTimestamp(response.getOriginalLeaseExpiresAt()), projection); + if (!OriginalStartSessionCurrentAttemptEvidence.isCanonicalDigest( + response.getAccountRedemptionProjectionDigest()) + || !result + .accountRedemptionProjectionDigest() + .equals(response.getAccountRedemptionProjectionDigest())) { + throw new IllegalArgumentException("Account projection digest differs from its exact bytes"); + } + return result; + } + + private static Timestamp toTimestamp(Instant instant) { + long seconds = instant.getEpochSecond(); + int nanos = instant.getNano(); + requireTimestampRange(seconds, nanos); + return Timestamp.newBuilder().setSeconds(seconds).setNanos(nanos).build(); + } + + private static Instant fromTimestamp(Timestamp timestamp) { + requireTimestampRange(timestamp.getSeconds(), timestamp.getNanos()); + try { + return Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException("Original lease timestamp is invalid", malformed); + } + } + + private static void requireTimestampRange(long seconds, int nanos) { + if (seconds < MIN_TIMESTAMP_SECONDS + || seconds > MAX_TIMESTAMP_SECONDS + || nanos < 0 + || nanos > MAX_TIMESTAMP_NANOS) { + throw new IllegalArgumentException("Original lease timestamp is outside the protobuf range"); + } + } + + private static UUID canonicalUuid(String value, String name) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, name)); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException(name + " must be canonical and non-nil"); + } + return parsed; + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(name + " must be canonical and non-nil", invalid); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java new file mode 100644 index 0000000000..f069bcd89e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java @@ -0,0 +1,535 @@ +package net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.gamesession.v1.OriginalStartSessionCurrentAttemptReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic loopback mTLS proof; it does not read a real Game Session database. */ +class OriginalStartSessionCurrentAttemptClientMtlsTest { + private static final String NAMESPACE = "world-runtime"; + private static final String GAME_SESSION_URI = + "spiffe://firemud/ns/world-runtime/sa/game-session-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/world-runtime/sa/account-service"; + private static final String OTHER_CLIENT_URI = + "spiffe://firemud/ns/world-runtime/sa/entity-management-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final byte[] PROJECTION = + "synthetic-attached-account-projection".getBytes(StandardCharsets.UTF_8); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private final AtomicInteger calls = new AtomicInteger(); + private final AtomicReference lastPeerUri = new AtomicReference<>(); + private Server server; + private boolean substituteEcho; + private boolean malformedExpiry; + private boolean stall; + + @BeforeAll + static void certificates() throws Exception { + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void closeServerAndClearTransactionContext() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + TransactionSynchronizationManager.clear(); + } + + @Test + void readsExactPendingObservationOverMutualTlsWithAccountWorkloadPeer() throws Exception { + start(pki.gameSessionServer()); + try (var client = newClient(pki.accountClient())) { + client.init(); + + Result result = + client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request()); + + assertThat(result.phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(result.request()) + .isEqualTo(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request()); + assertThat(result.accountRedemptionProjection()).containsExactly(PROJECTION); + assertThat(result.accountRedemptionProjectionDigest()) + .isEqualTo(OriginalStartSessionCurrentAttemptEvidence.projectionDigest(PROJECTION)); + assertThat(lastPeerUri).hasValue(ACCOUNT_URI); + assertThat(calls).hasValue(1); + } + } + + @Test + void rejectsWrongClientPeerAndChangedGameSessionServerPeer() throws Exception { + start(pki.gameSessionServer()); + try (var client = newClient(pki.otherClient())) { + client.init(); + assertThatThrownBy( + () -> client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(lastPeerUri).hasValue(OTHER_CLIENT_URI); + assertThat(calls).hasValue(1); + } + + stopServer(); + start(pki.wrongGameSessionServer()); + int callsBeforeWrongServer = calls.get(); + try (var client = newClient(pki.accountClient())) { + client.init(); + assertThatThrownBy( + () -> client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(callsBeforeWrongServer); + } + } + + @Test + void rejectsWrongNamespaceAmbientTransactionAndSynchronizationBeforeCallingPeer() + throws Exception { + start(pki.gameSessionServer()); + try (var client = newClient(pki.accountClient())) { + client.init(); + var valid = OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request(); + try (var wrongNamespaceClient = newClient(pki.accountClient(), "another-runtime")) { + wrongNamespaceClient.init(); + assertThatThrownBy(() -> wrongNamespaceClient.read(valid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + } + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(valid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction or synchronization"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(valid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction or synchronization"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(calls).hasValue(0); + } + } + + @Test + void rejectsSubstitutedRequestEchoAndMalformedLeaseExpiry() throws Exception { + start(pki.gameSessionServer()); + try (var client = newClient(pki.accountClient())) { + client.init(); + var request = OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request(); + + substituteEcho = true; + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid current original StartSession attempt evidence"); + substituteEcho = false; + malformedExpiry = true; + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid current original StartSession attempt evidence"); + assertThat(calls).hasValue(2); + } + } + + @Test + void boundsUnavailableReadWithFiveSecondRpcDeadline() throws Exception { + stall = true; + start(pki.gameSessionServer()); + try (var client = newClient(pki.accountClient())) { + client.init(); + assertThatThrownBy( + () -> client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + } + } + + @Test + void requiresMutualTlsFileBackedCredentialsAndExplicitInitialization() throws Exception { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = pki.clientProperties(tempDirectory, pki.accountClient()); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcOriginalStartSessionCurrentAttemptClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var client = + new GrpcOriginalStartSessionCurrentAttemptClient( + endpoints, + pki.clientProperties(tempDirectory, pki.accountClient()), + new GrpcChannelFactory(), + NAMESPACE); + try { + assertThatThrownBy( + () -> client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + } finally { + client.close(); + } + } + + private void start(TestIdentity serverIdentity) throws Exception { + var service = + new OriginalStartSessionCurrentAttemptReadServiceGrpc + .OriginalStartSessionCurrentAttemptReadServiceImplBase() { + @Override + public void readOriginalStartSessionCurrentAttempt( + ReadOriginalStartSessionCurrentAttemptRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + var peer = GrpcPeerIdentity.current(); + lastPeerUri.set(peer == null ? null : peer.uri()); + if (peer == null || !ACCOUNT_URI.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (stall) { + return; + } + var request = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(wire); + var result = + new Result(request, java.time.Instant.parse("2035-01-01T00:00:00Z"), PROJECTION); + var response = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result); + if (substituteEcho) { + response = + response.toBuilder() + .setRequest( + wire.toBuilder() + .setReadRequestId("04444444-4444-4444-8444-444444444444") + .build()) + .build(); + } + if (malformedExpiry) { + response = + response.toBuilder() + .setOriginalLeaseExpiresAt( + response.getOriginalLeaseExpiresAt().toBuilder() + .setNanos(1_000_000_000) + .build()) + .build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private void stopServer() throws Exception { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + + private GrpcOriginalStartSessionCurrentAttemptClient newClient(TestIdentity identity) + throws Exception { + return newClient(identity, NAMESPACE); + } + + private GrpcOriginalStartSessionCurrentAttemptClient newClient( + TestIdentity identity, String workloadNamespace) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("localhost:" + server.getPort()); + return new GrpcOriginalStartSessionCurrentAttemptClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + workloadNamespace); + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameSessionServer, + TestIdentity wrongGameSessionServer, + TestIdentity accountClient, + TestIdentity otherClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("current-attempt-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD current-attempt test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("current-attempt-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + return new TestPki( + readCertificate(caFile), + issueIdentity(directory, caStore, caFile, "game-session-server", GAME_SESSION_URI, true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-game-session-server", + "spiffe://firemud/ns/world-runtime/sa/world-management-service", + true), + issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false), + issueIdentity(directory, caStore, caFile, "other-client", OTHER_CLIENT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve(identity.alias() + ".client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve(identity.alias() + ".client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("current-attempt-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] encoded) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + return path; + } + + private static void runKeytool(String... arguments) throws Exception { + List command = new ArrayList<>(); + command.add(Path.of(System.getProperty("java.home"), "bin", "keytool").toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + process.getInputStream().transferTo(output); + int exitCode = process.waitFor(); + assertThat(exitCode) + .withFailMessage("keytool failed: %s", output.toString(StandardCharsets.UTF_8)) + .isZero(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java new file mode 100644 index 0000000000..2b68de8450 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java @@ -0,0 +1,294 @@ +package net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.Timestamp; +import com.google.protobuf.UnknownFieldSet; +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest { + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID MUTATION = uuid("03333333-3333-4333-8333-333333333333"); + + @Test + void roundTripsExactRequestPendingPhaseProjectionAndOriginalExpiry() { + Request request = request(); + byte[] projection = + "attached-account-projection".getBytes(java.nio.charset.StandardCharsets.UTF_8); + Result result = + new Result(request, Instant.parse("2030-01-01T00:00:00.123456789Z"), projection); + var wireRequest = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request); + var wireResponse = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result); + + assertThat(OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(request); + var decoded = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse(request, wireResponse); + assertThat(decoded.request()).isEqualTo(request); + assertThat(decoded.phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(decoded.originalLeaseExpiresAt()).isEqualTo(result.originalLeaseExpiresAt()); + assertThat(decoded.accountRedemptionProjection()).containsExactly(projection); + assertThat(wireResponse.getAccountRedemptionProjectionDigest()) + .isEqualTo(result.accountRedemptionProjectionDigest()); + } + + @Test + void rejectsUnknownFieldsUnsupportedSchemaInvalidFenceAndChangedEcho() { + Request request = request(); + var wire = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request); + var unknownRequest = + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy( + () -> OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(unknownRequest)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest( + wire.toBuilder().setSchemaVersion(2).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest( + wire.toBuilder().setExpectedOwnerFence(0L).build())) + .isInstanceOf(IllegalArgumentException.class); + + var response = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, Instant.parse("2030-01-01T00:00:00Z"), new byte[] {1, 2, 3})); + var changedEcho = + response.toBuilder() + .setRequest( + wire.toBuilder() + .setReadRequestId(uuid("04444444-4444-4444-8444-444444444444").toString())) + .build(); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, changedEcho)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact read request"); + } + + @Test + void rejectsWrongPhaseDigestResponseAndTimestampShapes() { + Request request = request(); + var valid = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, Instant.parse("2030-01-01T00:00:00Z"), new byte[] {1, 2, 3})); + var unknownResponse = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, unknownResponse)) + .isInstanceOf(IllegalArgumentException.class); + var unknownTimestamp = + valid.toBuilder() + .setOriginalLeaseExpiresAt( + valid.getOriginalLeaseExpiresAt().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, unknownTimestamp)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, valid.toBuilder().setPhaseState("OWNER_EXECUTION_COMMITTED").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, + valid.toBuilder().setAccountRedemptionProjectionDigest("0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, + valid.toBuilder() + .setOriginalLeaseExpiresAt( + Timestamp.newBuilder().setSeconds(253_402_300_800L).setNanos(0).build()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("timestamp"); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, + valid.toBuilder() + .setOriginalLeaseExpiresAt( + Timestamp.newBuilder() + .setSeconds(Instant.parse("2030-01-01T00:00:00Z").getEpochSecond()) + .setNanos(1_000_000_000) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, valid.toBuilder().clearOriginalLeaseExpiresAt().build())) + .isInstanceOf(IllegalArgumentException.class); + } + + static Request request() { + return new Request( + READ_ID, + "world-runtime", + CurrentAttemptTestData.tuple().canonicalBytes(), + ATTEMPT, + MUTATION, + 8L); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} + +/** Minimal synthetic StartSession tuple fixture shared by the two focused transport tests. */ +final class CurrentAttemptTestData { + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private CurrentAttemptTestData() {} + + static StartSessionPostAuthorizationExecutionTuple tuple() { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "current-attempt-test", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index 57ff2dcce2..dc2ef52611 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -6,6 +6,8 @@ import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; @@ -33,6 +35,8 @@ import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.RecordedParticipantDigestService; import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; +import org.postgresql.util.PSQLException; +import org.postgresql.util.ServerErrorMessage; import org.slf4j.Logger; import org.springframework.stereotype.Service; @@ -43,6 +47,12 @@ public class VersionPublishCommandServiceImpl { private static final java.util.regex.Pattern SELECTION_DIGEST = java.util.regex.Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern POSTGRES_IDENTIFIER = Pattern.compile("[A-Za-z_][A-Za-z0-9_]{0,62}"); + private static final Pattern PLPGSQL_ROUTINE_LINE = + Pattern.compile( + "(?:^|\\n)PL/pgSQL function (?:[A-Za-z_][A-Za-z0-9_]{0,62}\\.)?" + + "([A-Za-z_][A-Za-z0-9_]{0,62})\\(\\) line ([1-9][0-9]{0,5})" + + " at [A-Za-z_ ]+(?:\\r?\\n|$)"); private static final Logger logger = LoggingUtil.getLogger(VersionPublishCommandServiceImpl.class); @@ -1060,8 +1070,11 @@ static String safeFailureDiagnostic(String stage, Throwable failure) { .append("[sqlState=") .append(emptyIfNullStatic(sqlException.getSQLState())) .append(",vendorCode=") - .append(sqlException.getErrorCode()) - .append(']'); + .append(sqlException.getErrorCode()); + if (sqlException instanceof PSQLException postgresException) { + appendPostgresFailureIdentity(diagnostic, postgresException.getServerErrorMessage()); + } + diagnostic.append(']'); } current = current.getCause(); depth++; @@ -1072,6 +1085,34 @@ static String safeFailureDiagnostic(String stage, Throwable failure) { return diagnostic.toString(); } + private static void appendPostgresFailureIdentity( + StringBuilder diagnostic, ServerErrorMessage serverError) { + if (serverError == null) { + return; + } + String constraint = serverError.getConstraint(); + if (isSafePostgresIdentifier(constraint)) { + diagnostic.append(",constraint=").append(constraint); + } + + Matcher contextMatcher = + PLPGSQL_ROUTINE_LINE.matcher(emptyIfNullStatic(serverError.getWhere())); + if (contextMatcher.find()) { + String routine = contextMatcher.group(1); + if (isSafePostgresIdentifier(routine)) { + diagnostic + .append(",routine=") + .append(routine) + .append(",line=") + .append(contextMatcher.group(2)); + } + } + } + + private static boolean isSafePostgresIdentifier(String value) { + return value != null && POSTGRES_IDENTIFIER.matcher(value).matches(); + } + private static String emptyIfNullStatic(String value) { return value == null ? "" : value; } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 8551e98c43..0b4026afed 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -62,6 +62,8 @@ import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.postgresql.util.PSQLException; +import org.postgresql.util.ServerErrorMessage; class VersionPublishCommandServiceImplTest { @Mock private VersionRepository versionRepository; @@ -96,6 +98,77 @@ void failureDiagnosticsNameStageAndJdbcStateWithoutExceptionMessages() { assertTrue(!diagnostic.contains("credential payload")); } + @Test + void failureDiagnosticsExposeOnlyAllowlistedPostgresConstraintAndRoutineLine() { + ServerErrorMessage serverError = org.mockito.Mockito.mock(ServerErrorMessage.class); + when(serverError.getConstraint()).thenReturn("publication_commit_guard"); + when(serverError.getWhere()) + .thenReturn( + "PL/pgSQL function verify_publication_operation_commit() line 126 at RAISE\n" + + "SQL statement: secret-row-and-credential-context"); + PSQLException sqlFailure = org.mockito.Mockito.mock(PSQLException.class); + when(sqlFailure.getSQLState()).thenReturn("23514"); + when(sqlFailure.getErrorCode()).thenReturn(0); + when(sqlFailure.getServerErrorMessage()).thenReturn(serverError); + IllegalStateException failure = new IllegalStateException("secret payload", sqlFailure); + + String diagnostic = + VersionPublishCommandServiceImpl.safeFailureDiagnostic("RELEASE_FINALIZATION", failure); + + assertEquals( + "stage=RELEASE_FINALIZATION causeTypes=java.lang.IllegalStateException" + + " <- org.postgresql.util.PSQLException[sqlState=23514,vendorCode=0" + + ",constraint=publication_commit_guard" + + ",routine=verify_publication_operation_commit,line=126]", + diagnostic); + assertTrue(!diagnostic.contains("secret")); + assertTrue(!diagnostic.contains("SQL statement")); + } + + @Test + void failureDiagnosticsRejectUnsafePostgresIdentifiersAndDeepCauses() { + ServerErrorMessage unsafeServerError = org.mockito.Mockito.mock(ServerErrorMessage.class); + when(unsafeServerError.getConstraint()).thenReturn("guard,secret=credential"); + when(unsafeServerError.getWhere()) + .thenReturn("PL/pgSQL function unsafe-routine() line 7 at RAISE secret-context"); + PSQLException unsafeSqlFailure = org.mockito.Mockito.mock(PSQLException.class); + when(unsafeSqlFailure.getSQLState()).thenReturn("23514"); + when(unsafeSqlFailure.getErrorCode()).thenReturn(0); + when(unsafeSqlFailure.getServerErrorMessage()).thenReturn(unsafeServerError); + + String unsafeDiagnostic = + VersionPublishCommandServiceImpl.safeFailureDiagnostic( + "RELEASE_FINALIZATION", unsafeSqlFailure); + + assertEquals( + "stage=RELEASE_FINALIZATION causeTypes=org.postgresql.util.PSQLException" + + "[sqlState=23514,vendorCode=0]", + unsafeDiagnostic); + assertTrue(!unsafeDiagnostic.contains("credential")); + assertTrue(!unsafeDiagnostic.contains("secret")); + + ServerErrorMessage deepServerError = org.mockito.Mockito.mock(ServerErrorMessage.class); + when(deepServerError.getConstraint()).thenReturn("hidden_deep_constraint"); + when(deepServerError.getWhere()) + .thenReturn("PL/pgSQL function hidden_deep_routine() line 8 at RAISE"); + PSQLException deepSqlFailure = org.mockito.Mockito.mock(PSQLException.class); + when(deepSqlFailure.getSQLState()).thenReturn("23514"); + when(deepSqlFailure.getErrorCode()).thenReturn(0); + when(deepSqlFailure.getServerErrorMessage()).thenReturn(deepServerError); + Throwable deepFailure = deepSqlFailure; + for (int index = 0; index < 5; index++) { + deepFailure = new IllegalStateException("secret-depth-message", deepFailure); + } + + String deepDiagnostic = + VersionPublishCommandServiceImpl.safeFailureDiagnostic("RELEASE_FINALIZATION", deepFailure); + + assertTrue(deepDiagnostic.endsWith(" <- ...")); + assertTrue(!deepDiagnostic.contains("hidden_deep_constraint")); + assertTrue(!deepDiagnostic.contains("hidden_deep_routine")); + assertTrue(!deepDiagnostic.contains("secret-depth-message")); + } + @BeforeEach void setup() { MockitoAnnotations.openMocks(this); diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java index 030398a20e..971ee7472b 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java @@ -21,6 +21,8 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.SslProvider; import java.io.IOException; import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -30,6 +32,7 @@ import java.security.Principal; import java.security.PrivateKey; import java.security.cert.Certificate; +import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.PKCS8EncodedKeySpec; @@ -43,6 +46,7 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; @@ -50,8 +54,11 @@ import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509ExtendedKeyManager; +import javax.net.ssl.X509ExtendedTrustManager; +import javax.net.ssl.X509TrustManager; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; @@ -98,14 +105,16 @@ void socketMtlsCertificateChecksDoNotRequirePersistence(@TempDir Path temporaryD .extracting(GrpcPeerIdentity::uri) .isEqualTo("spiffe://firemud/ns/test/sa/logging-admin-service"); - Server server = - startTransport(pki, Mockito.mock(StartSessionPreAuthorizationReservationService.class)); + StartSessionPreAuthorizationReservationService reservationService = + Mockito.mock(StartSessionPreAuthorizationReservationService.class); + Server server = startTransport(pki, reservationService); try { assertTlsHandshakeAccepted(server, pki, pki.accountClient()); assertHandshakeRejected( server, pki, pki.clientWithoutCertificate(), "missing client certificate"); assertHandshakeRejected( - server, pki, pki.untrustedAccountClient(), "untrusted client certificate chain"); + server, pki, pki.untrustedAccountClient(), "untrusted client certificate chain", true); + Mockito.verifyNoInteractions(reservationService); } finally { server.shutdownNow(); } @@ -189,7 +198,7 @@ void socketMtlsUsesTheVerifiedAccountPeerAndExactJwtExemption(@TempDir Path temp assertHandshakeRejected( server, pki, pki.clientWithoutCertificate(), "missing client certificate"); assertHandshakeRejected( - server, pki, pki.untrustedAccountClient(), "untrusted client certificate chain"); + server, pki, pki.untrustedAccountClient(), "untrusted client certificate chain", true); assertThat(readStatus(server, pki, pki.wrongServiceClient(), request)) .isEqualTo(Status.Code.PERMISSION_DENIED); assertThat(readStatus(server, pki, pki.wrongNamespaceClient(), request)) @@ -254,7 +263,7 @@ private static Server startTransport( SslContextBuilder.forServer( pki.serverCertificate().toFile(), pki.serverPrivateKey().toFile()), SslProvider.JDK) - .trustManager(pki.trustedCaCertificate().toFile()) + .trustManager((TrustManager) pki.serverTrustManager()) .clientAuth(ClientAuth.REQUIRE) .protocols("TLSv1.3") .build(); @@ -327,6 +336,17 @@ private static void assertHandshakeRejected( TestWorkloadPki.ClientIdentity clientIdentity, String description) throws Exception { + assertHandshakeRejected(server, pki, clientIdentity, description, false); + } + + private static void assertHandshakeRejected( + Server server, + TestWorkloadPki pki, + TestWorkloadPki.ClientIdentity clientIdentity, + String description, + boolean requireServerTrustRejection) + throws Exception { + pki.serverTrustManager().clearRejection(); RawClientTls clientTls = rawClientTls(pki, clientIdentity); Throwable failure = catchThrowable( @@ -337,14 +357,43 @@ private static void assertHandshakeRejected( } }); assertThat(failure).as(description).isNotNull(); - assertThat(failure) - .as("%s must surface a TLS handshake exception", description) - .isInstanceOf(SSLHandshakeException.class); - assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) - .as( - "%s must fail during the TLS certificate handshake; failure chain: %s", - description, throwableChain(failure)) - .isTrue(); + if (requireServerTrustRejection) { + TrustRejection rejection = pki.serverTrustManager().rejection(); + assertThat(rejection) + .as("%s must reach and fail the server's original CA trust validation", description) + .isNotNull(); + assertThat(rejection.presentedChain()) + .as( + "%s server trust validation must inspect the exact presented certificate chain", + description) + .containsExactly(readCertificate(clientIdentity.certificate())); + assertThat(rejection.failure()) + .as("%s rejection must be the original trust manager's certificate failure", description) + .isInstanceOf(CertificateException.class); + + if (failure instanceof SSLHandshakeException) { + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "%s must fail during the TLS certificate handshake; failure chain: %s", + description, throwableChain(failure)) + .isTrue(); + } else { + assertThat(hasCause(failure, SocketException.class)) + .as( + "%s may surface a socket reset only after attributable server CA rejection; failure chain: %s", + description, throwableChain(failure)) + .isTrue(); + } + } else { + assertThat(failure) + .as("%s must surface a TLS handshake exception", description) + .isInstanceOf(SSLHandshakeException.class); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "%s must fail during the TLS certificate handshake; failure chain: %s", + description, throwableChain(failure)) + .isTrue(); + } if (clientIdentity.certificate() != null) { clientTls.assertIdentitySelected(clientIdentity, ACCOUNT_URI); assertThat(clientTls.keyManager().requestedIssuers()) @@ -362,6 +411,15 @@ private static String throwableChain(Throwable failure) { return String.join(" -> ", causes); } + private static boolean hasCause(Throwable failure, Class type) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (type.isInstance(cause)) { + return true; + } + } + return false; + } + private static void assertTlsHandshakeAccepted( Server server, TestWorkloadPki pki, TestWorkloadPki.ClientIdentity clientIdentity) throws Exception { @@ -438,6 +496,121 @@ void assertIdentitySelected(TestWorkloadPki.ClientIdentity clientIdentity, Strin } } + /** Records only failures from the delegated server-side client-certificate CA check. */ + private static final class RecordingClientCertificateTrustManager + extends X509ExtendedTrustManager { + private final X509TrustManager delegate; + private final AtomicReference rejection = new AtomicReference<>(); + + private RecordingClientCertificateTrustManager(X509TrustManager delegate) { + this.delegate = Objects.requireNonNull(delegate); + } + + void clearRejection() { + rejection.set(null); + } + + TrustRejection rejection() { + return rejection.get(); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + checkClientTrusted(chain, authType, (Socket) null); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) + throws CertificateException { + try { + if (delegate instanceof X509ExtendedTrustManager extended) { + extended.checkClientTrusted(chain, authType, socket); + } else { + delegate.checkClientTrusted(chain, authType); + } + } catch (CertificateException failure) { + rejection.set(new TrustRejection(chain, failure)); + throw failure; + } + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) + throws CertificateException { + try { + if (delegate instanceof X509ExtendedTrustManager extended) { + extended.checkClientTrusted(chain, authType, engine); + } else { + delegate.checkClientTrusted(chain, authType); + } + } catch (CertificateException failure) { + rejection.set(new TrustRejection(chain, failure)); + throw failure; + } + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + delegate.checkServerTrusted(chain, authType); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) + throws CertificateException { + if (delegate instanceof X509ExtendedTrustManager extended) { + extended.checkServerTrusted(chain, authType, socket); + } else { + delegate.checkServerTrusted(chain, authType); + } + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) + throws CertificateException { + if (delegate instanceof X509ExtendedTrustManager extended) { + extended.checkServerTrusted(chain, authType, engine); + } else { + delegate.checkServerTrusted(chain, authType); + } + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + X509Certificate[] issuers = delegate.getAcceptedIssuers(); + return issuers == null ? new X509Certificate[0] : issuers.clone(); + } + } + + private record TrustRejection(X509Certificate[] presentedChain, CertificateException failure) { + private TrustRejection { + presentedChain = presentedChain == null ? new X509Certificate[0] : presentedChain.clone(); + Objects.requireNonNull(failure); + } + + @Override + public X509Certificate[] presentedChain() { + return presentedChain.clone(); + } + } + + private static RecordingClientCertificateTrustManager recordingTrustManager(Path caCertificate) + throws Exception { + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + trustStore.setCertificateEntry("logging-admin-test-ca", readCertificate(caCertificate)); + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + for (TrustManager trustManager : trustManagers.getTrustManagers()) { + if (trustManager instanceof X509TrustManager x509TrustManager) { + return new RecordingClientCertificateTrustManager(x509TrustManager); + } + } + throw new IllegalStateException("The test CA did not produce an X.509 trust manager"); + } + /** * Test-only key manager that selects its one explicit identity even when the server's issuer hint * excludes that identity's issuer; this makes the untrusted-chain probe exercise rejection of the @@ -629,6 +802,7 @@ private static final class TestWorkloadPki { private final ClientIdentity wrongServiceClient; private final ClientIdentity wrongNamespaceClient; private final ClientIdentity untrustedAccountClient; + private final RecordingClientCertificateTrustManager serverTrustManager; private TestWorkloadPki( Path trustedCaCertificate, @@ -638,7 +812,8 @@ private TestWorkloadPki( ClientIdentity replacementAccountClient, ClientIdentity wrongServiceClient, ClientIdentity wrongNamespaceClient, - ClientIdentity untrustedAccountClient) { + ClientIdentity untrustedAccountClient, + RecordingClientCertificateTrustManager serverTrustManager) { this.trustedCaCertificate = trustedCaCertificate; this.serverCertificate = serverCertificate; this.serverPrivateKey = serverPrivateKey; @@ -647,6 +822,7 @@ private TestWorkloadPki( this.wrongServiceClient = wrongServiceClient; this.wrongNamespaceClient = wrongNamespaceClient; this.untrustedAccountClient = untrustedAccountClient; + this.serverTrustManager = serverTrustManager; } static TestWorkloadPki create(Path directory) throws Exception { @@ -716,7 +892,8 @@ static TestWorkloadPki create(Path directory) throws Exception { replacementAccount, wrongService, wrongNamespace, - untrustedAccount); + untrustedAccount, + recordingTrustManager(trustedCaCertificate)); } Path trustedCaCertificate() { @@ -751,6 +928,10 @@ ClientIdentity untrustedAccountClient() { return untrustedAccountClient; } + RecordingClientCertificateTrustManager serverTrustManager() { + return serverTrustManager; + } + ClientIdentity clientWithoutCertificate() { return new ClientIdentity(null, null); } From d63a9f0fad74dea824ecb811e26137b246734360 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 17:49:24 +1300 Subject: [PATCH 074/129] Finalize distinct selected-owner source retention authorizations --- .../account-service/api-contracts.md | 2 + ...ame-authoring-publishing-and-activation.md | 4 + ...lectedOwnerIntakeAuthorizationService.java | 296 ++++++++ ...wnerIntakeSourceReservationRepository.java | 223 +++++- ...cted_owner_intake_final_authorizations.sql | 457 ++++++++++++ ...eAuthorizationPostgresIntegrationTest.java | 613 ++++++++++++++++ ...wnerIntakeAuthorizationRepositoryTest.java | 29 + ...edOwnerIntakeAuthorizationServiceTest.java | 691 ++++++++++++++++++ ...lectedOwnerIntakeAuthorizationBinding.java | 257 +++++++ ...edOwnerIntakeAuthorizationBindingTest.java | 460 ++++++++++++ 10 files changed, 3030 insertions(+), 2 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java create mode 100644 services/account-service/src/main/resources/db/migration/V132__selected_owner_intake_final_authorizations.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d87bc18346..c9a29b4a97 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -110,6 +110,8 @@ Entity and Automation's selected-source intake use the same two-phase ownership That scope is preliminary integrity input, not authenticated authorization, finalized owner retention permission or evidence that any source family is empty. Account must authenticate and retain the distinct reservation before Game Design returns source content; it must then obtain the complete immutable selected inputs and finalize the owner-specific authorization with revalidated held sources. The original Draft's required-owner vector identifies its mutation participants, not the consumers of this later distinct intake. Original revision provenance is retained separately from the selected capture and must not be rewritten to manufacture a World association. Entity's [complete authored inventory](../entity-management-service/runtime-and-data.md) and Automation's [source inventory and inbound closure](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) remain owner-validated obligations. Both owners retain their original terminal under continuously protected Account authority; only authenticated exact terminal settlement can release participation. A decoded scope or sampled `HELD` response proves none of those obligations. Complete authenticated reservation/finalization, held-retention producers and executed proof remain open in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); these domains do not register or enable a runtime path. +The distinct finalized integrity envelope uses `account-entity-intake-authorization/v1` with purpose `ENTITY_INTAKE_RETENTION` and the exact same-namespace Entity workload recipient, or `account-automation-intake-authorization/v1` with purpose `AUTOMATION_INTAKE_RETENTION` and the corresponding Automation recipient. Its canonical byte-length-framed preimage is, in order: that closed schema, the complete six-family selected-content bytes, their SHA-256 digest, the derived recipient SPIFFE URI, the closed retention purpose, a canonical decimal source count, and each complete Account source-evidence frame in sorted distinct source-key order. The content embeds the unchanged preliminary scope, so operation, fence, request, actor, namespace and selected Draft identity are reused rather than reallocated. The complete envelope is bounded to 16 MiB without changing the content's 8 MiB or preliminary scope's 4 MiB bounds. Unknown or substituted owner, reader or purpose, changed content or source scope, duplicate or noncanonical source order, malformed counts and trailing bytes deny. This value's decoder establishes integrity only; genuine Account finalization/readback and continuously held source participation, followed by the owner's own census, retention and exact terminal, establish the separate authorization and outcome. Preliminary abort cannot release a finalized operation; expiry, absence or a digest alone never settles it. + The distinct [`AccountSelectedOwnerIntakeSourceReadService.ReadSourceScope`](../../../../protos/account/v1/selected_owner_intake_source_read_service.proto) confirms only the retained preliminary Entity or Automation reservation. Account authenticates the exact configured same-namespace Game Design workload and rejects authenticated end-user context before decoding or storage. The closed schema-version-1 request binds namespace, independent nonzero transport correlation, derived Account reader and closed purpose, and the original scope bytes and digest. Account revalidates its own original creator and source participation in independent transactions around the external registry read; neither a client digest nor peer identity creates a reservation. A successful response echoes the complete request unchanged and confirms only that preliminary scope. Missing, expired, changed, malformed or unavailable evidence denies. The canonical scope remains bounded to 4 MiB; the separately enforced request and response wire budget is 8 MiB, including echo and framing. The file-backed mTLS client pins the Account server, applies a five-second deadline and rejects ambient SQL or synchronization. This standalone method has no finalized-retention branch, supplies no census or owner receipt, and does not register or activate a runtime path. Game Design must finish this authenticated Account confirmation outside SQL before reading or returning any selected source content. `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. 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 e166af3014..fe00b74643 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Distinct Account selected-owner finalization now retains the complete six-family content, original reservation tuple, creator evidence and full held source vector in V132's append-only authorization and child rows. The unregistered producer performs the authenticated source read outside SQL, revalidates current creator/source evidence before finalization, and independently reads back the exact original result; lost acknowledgements recover the same binding without another reservation. Finalization excludes preliminary abort and source mutation, and has no expiry-based or locally invented settlement. The affected Common check passes with 551 unit cases; Account's full check and boot JAR pass with 1,256 unit cases and seven non-container integration executions, all without failures or errors. Account skips 260 container-dependent definitions, including the two new finalization PostgreSQL methods; schema generation does not prove their procedural guards. Seven new Common integrity cases and eight Account producer/repository cases pass. Content and issuer fixtures are stipulated, not genuine owner census or authenticated Entity/Automation receipts. Their HELD transport, complete owner inventories, continuously protected retention and exact authenticated terminal settlement remain open. All components remain unregistered and runtime activation remains denied. + +Exact source `695dc8ee2daaba5180d0975f07d25adf04e9b7b6` [Validation run 38023005491](https://github.com/benhook1013/FireMUD/actions/runs/38023005491) fails the required Validation Gate. Originating XML establishes 273 Account integration executions with nine failures: six admission-confirmation failures, two exception-type assertions where PostgreSQL correctly denies immutable-evidence updates, and one original source-capture/currentness denial. The three V131 original-attempt observation cases pass, including unchanged first-response retention and database-clock expiry after lock waits; these use stipulated Game Session evidence, not continuous cross-owner claim protection. Separate Account draft-fence PostgreSQL proof passes 31 cases. Game Design executes 151 integration cases with one release-finalization denial (`23514`, `verify_publication_operation_commit`, line 19); no constraint identifier is reported. World executes 221 with none, all without skips. Logging's job passes, but its XML capture skips, so this run does not establish the specific CA-rejection case's execution. The tested merge is `6253d6a060e75dcfa3190a925cdc743afefc29a7`, tree `ff827c27b11f6a9bb6d5ca277b894c96eaf1eacb`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source. License, Security and CodeQL pass. The later metadata-only run supplies no source proof; the older fourteen-failure report below is historical, not the current result. + The original Game Session current-attempt client, immutable Account V131 observation retention and sole-issuer World acquisition composition pass the affected Common/Account/Game Design full checks, schema generation, boot JARs, formatting, static checks, coverage, links and Markdown in 47 seconds. Originating local XML records 544 Common, 1,248 Account and 551 Game Design unit cases with zero failures, errors or skips; successful unchanged tasks retain results. Account executes seven non-container integration cases and skips 258 definitions; Game Design skips 148 without Docker. The twelve new Account unit cases cover timestamp casts, complete observation binding and mocked acquisition/readback ordering. The three new PostgreSQL definitions compile but do not execute; their synthetic parent and stipulated Game Session observation do not establish genuine Account/Game Session producer composition. The client uses synthetic loopback mTLS. Acquisition and retries preserve the actual mutation/attempt/fence, unchanged finite lease and first complete response bytes, rechecking the database clock after Account lock waits. This observation remains distinct from continuous Game Session claim protection and World execution/admission authority. All new paths remain unregistered. The concrete original-issuance timestamp repair adds explicit PostgreSQL casts without changing timestamps or guards. Game Design's existing redacted diagnostic now preserves only allowlisted constraint and routine/line identifiers, with two secret-exclusion cases; the release-finalization check's behavioral cause remains unresolved until corrected physical execution. Logging's affected full check passes in 49 seconds with 224 unit cases and one executed non-persistence TLS integration case; 23 container-dependent definitions skip. The untrusted-chain probe now requires the server's original CA trust manager to reject the exact presented certificate, rather than treating a broken pipe alone as rejection. Flyway sanity passes 12 sets and 288 versions. These checks do not establish fresh-image boot, corrected PostgreSQL execution or any complete Gameplay handoff. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java new file mode 100644 index 0000000000..463201b390 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java @@ -0,0 +1,296 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceClient; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered distinct Account producer for selected Entity and Automation intake authority. */ +public final class AccountSelectedOwnerIntakeAuthorizationService { + private static final int MAX_CREATOR_CREDENTIAL_LENGTH = 16384; + + private final AccountControlUiActorService actors; + private final DraftAuthorizationFenceRepository fences; + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final SelectedOwnerIntakeSourceClient sources; + private final String namespace; + private final TransactionTemplate ownerTransaction; + + public AccountSelectedOwnerIntakeAuthorizationService( + AccountControlUiActorService actors, + DraftAuthorizationFenceRepository fences, + AccountSelectedOwnerIntakeSourceReservationRepository repository, + SelectedOwnerIntakeSourceClient sources, + PlatformTransactionManager transactions, + String namespace) { + this.actors = Objects.requireNonNull(actors, "actors"); + this.fences = Objects.requireNonNull(fences, "fences"); + this.repository = Objects.requireNonNull(repository, "repository"); + this.sources = Objects.requireNonNull(sources, "sources"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Reserves one distinct source-read operation, obtains exact selected content outside SQL, and + * finalizes that same operation under a freshly captured current creator and held-source vector. + * Exact final recovery happens before the mutable environment supplier is invoked. + */ + public SelectedOwnerIntakeAuthorizationBinding authorizeWithEnvironmentCapture( + String originalCreatorCredential, + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected, + Supplier environmentCapture) { + requireGameDesignPeer(); + outsideSql(); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + requireOwner(owner); + Objects.requireNonNull(selected, "selected Draft binding is required"); + Objects.requireNonNull(environmentCapture, "current Account environment capture is required"); + + Optional retained = + findScope(originalCreatorCredential, intakeRequestId, owner, selected); + SelectedOwnerIntakeSourceReadScope scope = null; + if (retained.isPresent()) { + scope = retained.orElseThrow(); + var recovery = recover(scope); + if (recovery.state() == AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED) + throw denied("Original selected-owner intake reservation was aborted"); + if (recovery.state() + == AccountSelectedOwnerIntakeSourceReservationRepository.State.FINALIZED) { + var original = + findFinalAuthorization(scope) + .orElseThrow( + () -> denied("Finalized selected-owner intake authorization is unavailable")); + return readFinalAuthorization(original); + } + } else { + var initialEnvironment = requireEnvironment(environmentCapture.get()); + scope = + reserveSourceRead( + originalCreatorCredential, intakeRequestId, owner, selected, initialEnvironment); + var recovery = recover(scope); + if (recovery.state() == AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED) + throw denied("Original selected-owner intake reservation was aborted"); + if (recovery.state() + == AccountSelectedOwnerIntakeSourceReservationRepository.State.FINALIZED) { + var original = + findFinalAuthorization(scope) + .orElseThrow( + () -> denied("Finalized selected-owner intake authorization is unavailable")); + return readFinalAuthorization(original); + } + } + + var request = SelectedOwnerIntakeSourceReadEvidence.Request.create(namespace, scope); + SelectedOwnerIntakeSourceReadScope reservationScope = scope; + outsideSql(); + // The authenticated Game Design client enforces exact request echo, wire closure, six-family + // content integrity and the absence of SQL or transaction synchronization during this call. + var received = sources.read(request); + var content = requireExactContent(request, received); + + var finalizationEnvironment = requireEnvironment(environmentCapture.get()); + SelectedOwnerIntakeAuthorizationBinding finalized; + try { + finalized = + actors.withCurrent( + originalCreatorCredential, + selected.target().canonicalTenantId(), + finalizationEnvironment, + current -> + repository.finalizeSourceRead( + reservationScope, + content, + current, + () -> + fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected))); + } catch (RuntimeException finalizationFailure) { + // A commit acknowledgement can be lost after the immutable authorization commits. Recover + // only the exact same content and operation; never allocate a replacement scope or fence. + Optional committed; + try { + committed = findFinalAuthorization(reservationScope); + } catch (RuntimeException readFailure) { + if (readFailure != finalizationFailure) finalizationFailure.addSuppressed(readFailure); + throw finalizationFailure; + } + if (committed.isEmpty() + || !java.util.Arrays.equals( + committed.orElseThrow().content().canonicalBytes(), content.canonicalBytes())) { + throw finalizationFailure; + } + finalized = committed.orElseThrow(); + } + return readFinalAuthorization(finalized); + } + + private SelectedOwnerIntakeSourceReadScope reserveSourceRead( + String originalCreatorCredential, + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected, + CapturedEnvironmentBoundary environment) { + return actors.withCurrent( + originalCreatorCredential, + selected.target().canonicalTenantId(), + environment, + current -> + repository.reserveSourceRead( + intakeRequestId, + owner, + selected, + current, + namespace, + () -> + fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected))); + } + + private Optional findScope( + String originalCreatorCredential, + UUID intakeRequestId, + Owner owner, + DraftCommitBinding selected) { + requireGameDesignPeer(); + outsideSql(); + if (originalCreatorCredential == null + || originalCreatorCredential.isEmpty() + || originalCreatorCredential.length() > MAX_CREATOR_CREDENTIAL_LENGTH + || !StandardCharsets.US_ASCII.newEncoder().canEncode(originalCreatorCredential)) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + String tokenHash = + AccountControlUiIssuanceRepository.hash( + originalCreatorCredential.getBytes(StandardCharsets.US_ASCII)); + return Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository.findSourceReadScope( + intakeRequestId, owner, selected, namespace, tokenHash))); + } + + private AccountSelectedOwnerIntakeSourceReservationRepository.Recovery recover( + SelectedOwnerIntakeSourceReadScope scope) { + requireScope(scope); + outsideSql(); + return Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.recoverSourceRead(scope))); + } + + private Optional findFinalAuthorization( + SelectedOwnerIntakeSourceReadScope scope) { + requireScope(scope); + outsideSql(); + return Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.findFinalAuthorization(scope))); + } + + private SelectedOwnerIntakeAuthorizationBinding readFinalAuthorization( + SelectedOwnerIntakeAuthorizationBinding requested) { + Objects.requireNonNull(requested, "finalized selected-owner authorization is required"); + requireScope(requested.content().scope()); + outsideSql(); + ownerTransaction.execute( + ignored -> { + repository.readFinalAuthorization(requested); + return null; + }); + return requested; + } + + private SelectedOwnerIntakeSourceContent requireExactContent( + SelectedOwnerIntakeSourceReadEvidence.Request request, + SelectedOwnerIntakeSourceContent received) { + if (received == null || !request.scope().equals(received.scope())) + throw denied("Game Design returned substituted selected-owner source content"); + try { + var checked = + SelectedOwnerIntakeSourceContent.fromStored( + received.canonicalBytes(), request.scope(), received.digest()); + for (String family : + java.util.List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + if (checked.snapshotBytes(family).length == 0) + throw new IllegalArgumentException("Selected-owner source family is empty"); + } + return checked; + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact complete selected-owner source content is required") + .withCause(invalid) + .asRuntimeException(); + } + } + + private void requireScope(SelectedOwnerIntakeSourceReadScope scope) { + if (scope == null + || !namespace.equals(scope.targetNamespace()) + || (scope.owner() != Owner.ENTITY_MANAGEMENT + && scope.owner() != Owner.AUTOMATION_SCRIPTING)) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Game Design workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireOwner(Owner owner) { + if (owner != Owner.ENTITY_MANAGEMENT && owner != Owner.AUTOMATION_SCRIPTING) + throw Status.INVALID_ARGUMENT + .withDescription("Entity or Automation selected-source owner required") + .asRuntimeException(); + } + + private static CapturedEnvironmentBoundary requireEnvironment( + CapturedEnvironmentBoundary environment) { + return Objects.requireNonNull(environment, "current Account environment is required"); + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected-owner Account phases require independent transactions") + .asRuntimeException(); + } + } + + private static RuntimeException denied(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java index 4fcbd71e63..9b68e40337 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java @@ -11,20 +11,29 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Immutable preliminary Entity/Automation source-read reservations and their own abort marker. */ +/** + * Immutable Entity/Automation preliminary reservations and distinct finalized source retention. + * Finalization excludes preliminary abort; authenticated owner-terminal settlement is not yet + * implemented, so finalized participation remains held. + */ public final class AccountSelectedOwnerIntakeSourceReservationRepository { private static final String RESERVATIONS = "account_selected_owner_intake_source_read_reservations"; private static final String SOURCES = "account_selected_owner_intake_source_read_sources"; private static final String ABORTS = "account_selected_owner_intake_source_read_aborts"; + private static final String AUTHORIZATIONS = "account_selected_owner_intake_authorizations"; + private static final String AUTHORIZATION_SOURCES = "account_selected_owner_intake_sources"; private final DSLContext dsl; @@ -34,6 +43,7 @@ public AccountSelectedOwnerIntakeSourceReservationRepository(DSLContext dsl) { public enum State { RESERVED, + FINALIZED, ABORTED } @@ -171,7 +181,14 @@ Recovery recoverSourceRead(SelectedOwnerIntakeSourceReadScope scope) { lockReservedSources(scope); Record row = reservation(scope); requireReservation(row, scope); - return new Recovery(scope, aborted(scope) ? State.ABORTED : State.RESERVED); + if (aborted(scope)) return new Recovery(scope, State.ABORTED); + var authorization = authorization(scope.operationId()); + if (authorization == null) return new Recovery(scope, State.RESERVED); + var binding = + SelectedOwnerIntakeAuthorizationBinding.fromStored( + authorization.get("binding_bytes", byte[].class)); + requireAuthorization(authorization, binding); + return new Recovery(scope, State.FINALIZED); } Recovery abortSourceRead(SelectedOwnerIntakeSourceReadScope scope) { @@ -179,17 +196,198 @@ Recovery abortSourceRead(SelectedOwnerIntakeSourceReadScope scope) { lockReservedSources(scope); Record row = reservation(scope); requireReservation(row, scope); + if (authorization(scope.operationId()) != null) { + throw new IllegalStateException("Finalized owner intake cannot be preliminarily aborted"); + } if (!aborted(scope)) { dsl.execute("INSERT INTO " + ABORTS + " (operation_id) VALUES (?)", scope.operationId()); } return new Recovery(scope, State.ABORTED); } + SelectedOwnerIntakeAuthorizationBinding finalizeSourceRead( + SelectedOwnerIntakeSourceReadScope scope, + SelectedOwnerIntakeSourceContent content, + AccountControlUiActorService.Current current, + Runnable admission) { + requireTransaction(); + Objects.requireNonNull(content, "content"); + Objects.requireNonNull(current, "current"); + Objects.requireNonNull(admission, "admission"); + lockReservedSources(scope); + Record reserved = reservation(scope); + requireReservation(reserved, scope); + requireCurrentReservation(reserved, current); + if (!scope.equals(content.scope())) + throw new IllegalArgumentException("Selected content differs from original source scope"); + if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + + Record row = authorization(scope.operationId()); + if (row != null) { + var original = + SelectedOwnerIntakeAuthorizationBinding.fromStored( + row.get("binding_bytes", byte[].class)); + if (!Arrays.equals(original.content().canonicalBytes(), content.canonicalBytes())) + throw new IllegalArgumentException( + "Intake request identity conflicts with original selected content"); + requireAuthorization(row, original); + return original; + } + + List sourceVector = current.source().sources(); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, sourceVector); + admission.run(); + dsl.execute( + "INSERT INTO " + + AUTHORIZATIONS + + " (operation_id, fence_id, intake_request_id, owner, target_namespace, actor_account_uuid, " + + "tenant_uuid, version_uuid, content_bytes, content_digest, binding_bytes, binding_digest, " + + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.owner().name(), + binding.targetNamespace(), + binding.actorAccountId(), + binding.tenantId(), + binding.versionId(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.canonicalBytes(), + binding.digest(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + AccountControlUiAuthority.canonical(current.source().outboxCheckpoints())); + for (SourceEvidence source : binding.sources()) { + dsl.execute( + "INSERT INTO " + + AUTHORIZATION_SOURCES + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + source.key(), + source.canonicalBytes()); + } + requireAuthorization( + dsl.fetchOne( + "SELECT * FROM " + AUTHORIZATIONS + " WHERE operation_id = ? FOR UPDATE", + binding.operationId()), + binding); + return binding; + } + + Optional findFinalAuthorization( + SelectedOwnerIntakeSourceReadScope scope) { + requireTransaction(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + Record row = authorization(scope.operationId()); + if (row == null) return Optional.empty(); + var binding = + SelectedOwnerIntakeAuthorizationBinding.fromStored(row.get("binding_bytes", byte[].class)); + requireAuthorization(row, binding); + if (!scope.equals(binding.content().scope())) + throw new IllegalArgumentException("Finalized authorization differs from original scope"); + return Optional.of(binding); + } + + void readFinalAuthorization(SelectedOwnerIntakeAuthorizationBinding requested) { + requireTransaction(); + Objects.requireNonNull(requested, "requested"); + Record lookup = authorizationLookup(requested.operationId()); + if (lookup == null + || !Arrays.equals(requested.canonicalBytes(), lookup.get("binding_bytes", byte[].class))) + throw new IllegalArgumentException( + "Original finalized owner authorization absent or changed"); + var original = + SelectedOwnerIntakeAuthorizationBinding.fromStored( + lookup.get("binding_bytes", byte[].class)); + SelectedOwnerIntakeSourceReadScope scope = original.content().scope(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + Record row = authorization(original.operationId()); + requireAuthorization(row, original); + if (aborted(original.content().scope())) + throw new IllegalArgumentException("Finalized owner authorization cannot be aborted"); + } + + private Record authorization(UUID operationId) { + return dsl.fetchOne( + "SELECT * FROM " + AUTHORIZATIONS + " WHERE operation_id = ? FOR UPDATE", operationId); + } + + private Record authorizationLookup(UUID operationId) { + return dsl.fetchOne("SELECT * FROM " + AUTHORIZATIONS + " WHERE operation_id = ?", operationId); + } + + private void requireAuthorization(Record row, SelectedOwnerIntakeAuthorizationBinding binding) { + if (row == null + || !Arrays.equals(binding.canonicalBytes(), row.get("binding_bytes", byte[].class)) + || !binding.digest().equals(row.get("binding_digest", String.class)) + || !Arrays.equals( + binding.content().canonicalBytes(), row.get("content_bytes", byte[].class)) + || !binding.content().digest().equals(row.get("content_digest", String.class)) + || !binding.operationId().equals(row.get("operation_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class)) + || !binding.intakeRequestId().equals(row.get("intake_request_id", UUID.class)) + || !binding.owner().name().equals(row.get("owner", String.class)) + || !binding.targetNamespace().equals(row.get("target_namespace", String.class)) + || !binding.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !binding.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !binding.versionId().equals(row.get("version_uuid", UUID.class))) { + throw new IllegalArgumentException( + "Original finalized owner authorization absent or changed"); + } + Record reserved = reservation(binding.content().scope()); + requireReservation(reserved, binding.content().scope()); + if (!binding.operationId().equals(reserved.get("operation_id", UUID.class)) + || !binding.fenceId().equals(reserved.get("fence_id", UUID.class)) + || !binding.intakeRequestId().equals(reserved.get("intake_request_id", UUID.class)) + || !binding.owner().name().equals(reserved.get("owner", String.class)) + || !binding.actorAccountId().equals(reserved.get("actor_account_uuid", UUID.class)) + || !binding.tenantId().equals(reserved.get("tenant_uuid", UUID.class)) + || !binding.versionId().equals(reserved.get("version_uuid", UUID.class))) { + throw new IllegalArgumentException( + "Finalized authorization differs from original reservation"); + } + var issuer = issuer(reserved.get("issuance_operation_id", UUID.class)); + if (!issuer.operationId.equals(row.get("issuance_operation_id", UUID.class)) + || !Objects.equals( + reserved.get("issuance_fence", Long.class), row.get("issuance_fence", Long.class)) + || !Arrays.equals(issuer.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(issuer.bundle, row.get("issuance_bundle", byte[].class)) + || !Arrays.equals( + reserved.get("outbox_checkpoints", byte[].class), + row.get("outbox_checkpoints", byte[].class))) { + throw new IllegalArgumentException("Changed finalized creator evidence"); + } + List sources = + dsl.fetch( + "SELECT source_key, source_evidence FROM " + + AUTHORIZATION_SOURCES + + " WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + binding.operationId()); + if (sources.size() != binding.sources().size()) + throw new IllegalArgumentException("Incomplete finalized source participation"); + for (int index = 0; index < sources.size(); index++) { + SourceEvidence source = binding.sources().get(index); + if (!source.key().equals(sources.get(index).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), sources.get(index).get("source_evidence", byte[].class))) { + throw new IllegalArgumentException("Changed finalized source participation"); + } + } + } + SourceReadCurrentness sourceReadCurrentness(SelectedOwnerIntakeSourceReadScope scope) { requireTransaction(); Record row = reservation(scope); requireReservation(row, scope); if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + if (authorization(scope.operationId()) != null) + throw new IllegalStateException("Finalized owner intake is not a preliminary source read"); var original = issuer(row.get("issuance_operation_id", UUID.class)); if (!"COMMITTED".equals(original.status)) throw new IllegalStateException("Original creator issuance is no longer committed"); @@ -202,6 +400,8 @@ void readSourceScope(SelectedOwnerIntakeSourceReadScope scope, SourceReadCurrent Record row = reservation(scope); requireReservation(row, scope); if (aborted(scope)) throw new IllegalStateException("Original source-read scope aborted"); + if (authorization(scope.operationId()) != null) + throw new IllegalStateException("Finalized owner intake is not a preliminary source read"); var original = issuer(row.get("issuance_operation_id", UUID.class)); if (!"COMMITTED".equals(original.status) || !currentness(row, original).equals(expected)) { throw new IllegalStateException("Exact current pending source-read scope required"); @@ -405,6 +605,9 @@ private void requireCurrentReservation(Record row, AccountControlUiActorService. var original = issuer(row.get("issuance_operation_id", UUID.class)); if (!"COMMITTED".equals(original.status) || !original.operationId.equals(current.stored().operationId) + || !original.accountId.equals(current.stored().accountId) + || !original.tenantId.equals(current.stored().tenantId) + || !original.tokenHash.equals(current.stored().tokenHash) || !Arrays.equals(current.stored().sources, row.get("source_payload", byte[].class)) || !Arrays.equals(current.stored().bundle, row.get("issuance_bundle", byte[].class)) || !Arrays.equals( @@ -412,6 +615,22 @@ private void requireCurrentReservation(Record row, AccountControlUiActorService. row.get("outbox_checkpoints", byte[].class))) { throw new IllegalArgumentException("Changed original intake creator authority"); } + List currentSources = current.source().sources(); + List heldSources = + dsl.fetch( + "SELECT source_key, source_evidence FROM " + + SOURCES + + " WHERE operation_id = ? ORDER BY account_publication_authorization_source_sort_key(source_key)", + row.get("operation_id", UUID.class)); + if (currentSources.size() != heldSources.size()) + throw new IllegalArgumentException("Changed original intake source vector"); + for (int index = 0; index < currentSources.size(); index++) { + SourceEvidence source = currentSources.get(index); + Record held = heldSources.get(index); + if (!source.key().equals(held.get("source_key", String.class)) + || !Arrays.equals(source.canonicalBytes(), held.get("source_evidence", byte[].class))) + throw new IllegalArgumentException("Changed original intake source vector"); + } } private void requireTransaction() { diff --git a/services/account-service/src/main/resources/db/migration/V132__selected_owner_intake_final_authorizations.sql b/services/account-service/src/main/resources/db/migration/V132__selected_owner_intake_final_authorizations.sql new file mode 100644 index 0000000000..d727c03aca --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V132__selected_owner_intake_final_authorizations.sql @@ -0,0 +1,457 @@ +-- Final Entity/Automation retention authorization. Without an authenticated owner terminal, +-- this order remains held indefinitely; there is deliberately no timeout or local settlement. +CREATE TABLE account_selected_owner_intake_authorizations ( + operation_id UUID PRIMARY KEY + REFERENCES account_selected_owner_intake_source_read_reservations(operation_id), + fence_id UUID NOT NULL UNIQUE, + intake_request_id UUID NOT NULL, + owner VARCHAR(32) NOT NULL CHECK (owner IN ('ENTITY_MANAGEMENT', 'AUTOMATION_SCRIPTING')), + target_namespace VARCHAR(63) NOT NULL, + actor_account_uuid UUID NOT NULL REFERENCES accounts(account_uuid), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + version_uuid UUID NOT NULL, + content_bytes BYTEA NOT NULL CHECK (octet_length(content_bytes) BETWEEN 1 AND 8388608), + content_digest VARCHAR(71) NOT NULL CHECK (content_digest ~ '^sha256:[0-9a-f]{64}$'), + binding_bytes BYTEA NOT NULL CHECK (octet_length(binding_bytes) BETWEEN 1 AND 16777216), + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + issuance_operation_id UUID NOT NULL REFERENCES account_control_ui_issuance_operations(operation_id), + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + source_payload BYTEA NOT NULL CHECK (octet_length(source_payload) BETWEEN 1 AND 131072), + issuance_bundle BYTEA NOT NULL CHECK (octet_length(issuance_bundle) BETWEEN 1 AND 131072), + outbox_checkpoints BYTEA NOT NULL CHECK (octet_length(outbox_checkpoints) BETWEEN 1 AND 131072), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + finalized_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (fence_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (intake_request_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (actor_account_uuid <> '00000000-0000-0000-0000-000000000000'), + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'), + CHECK (version_uuid <> '00000000-0000-0000-0000-000000000000'), + UNIQUE (tenant_uuid, intake_request_id) +); + +CREATE TABLE account_selected_owner_intake_sources ( + operation_id UUID NOT NULL REFERENCES account_selected_owner_intake_authorizations(operation_id), + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (operation_id, source_key) +); +CREATE INDEX account_selected_owner_intake_source_lookup + ON account_selected_owner_intake_sources(source_key, operation_id); + +-- [jooq ignore start] +-- Serialize finalization and preliminary abort with the same sorted source-lock then reservation +-- order used by the existing V130 abort path. +CREATE OR REPLACE FUNCTION account_selected_owner_intake_source_read_abort_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + PERFORM lock_row.source_key FROM account_draft_authorization_source_locks lock_row + JOIN account_selected_owner_intake_source_read_sources source + ON source.source_key = lock_row.source_key + WHERE source.operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(lock_row.source_key) + FOR UPDATE OF lock_row; + PERFORM operation_id FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF NOT FOUND + OR EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_aborts + WHERE operation_id = NEW.operation_id) + OR EXISTS (SELECT 1 FROM account_selected_owner_intake_authorizations + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Only an unfinalized active preliminary owner reservation can be aborted' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_selected_owner_intake_authorization_serialize() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_selected_owner_intake_source_read_reservations%ROWTYPE; +BEGIN + PERFORM lock_row.source_key FROM account_draft_authorization_source_locks lock_row + JOIN account_selected_owner_intake_source_read_sources source + ON source.source_key = lock_row.source_key + WHERE source.operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(lock_row.source_key) + FOR UPDATE OF lock_row; + SELECT * INTO STRICT original FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_aborts + WHERE operation_id = NEW.operation_id) + OR EXISTS (SELECT 1 FROM account_selected_owner_intake_authorizations + WHERE operation_id = NEW.operation_id) + OR NEW.producer_xid <> txid_current() + OR NEW.operation_id IS DISTINCT FROM original.operation_id + OR NEW.fence_id IS DISTINCT FROM original.fence_id + OR NEW.intake_request_id IS DISTINCT FROM original.intake_request_id + OR NEW.owner IS DISTINCT FROM original.owner + OR NEW.actor_account_uuid IS DISTINCT FROM original.actor_account_uuid + OR NEW.tenant_uuid IS DISTINCT FROM original.tenant_uuid + OR NEW.version_uuid IS DISTINCT FROM original.version_uuid + OR NEW.issuance_operation_id IS DISTINCT FROM original.issuance_operation_id + OR NEW.issuance_fence IS DISTINCT FROM original.issuance_fence + OR NEW.source_payload IS DISTINCT FROM original.source_payload + OR NEW.issuance_bundle IS DISTINCT FROM original.issuance_bundle + OR NEW.outbox_checkpoints IS DISTINCT FROM original.outbox_checkpoints THEN + RAISE EXCEPTION 'Finalization must bind the exact active preliminary owner reservation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_selected_owner_intake_authorization_serialize + BEFORE INSERT ON account_selected_owner_intake_authorizations + FOR EACH ROW EXECUTE FUNCTION account_selected_owner_intake_authorization_serialize(); + +CREATE FUNCTION account_selected_owner_intake_authorization_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + p INTEGER := 1; + q INTEGER := 1; + scope_position INTEGER := 1; + source_position INTEGER := 1; + parsed BYTEA; + scope_bytes BYTEA; + content_bytes BYTEA; + selected_bytes BYTEA; + source_bytes BYTEA; + snapshot_bytes BYTEA; + source_schema TEXT; + text_value TEXT; + scope_schema TEXT; + scope_owner TEXT; + namespace_value TEXT; + operation_value TEXT; + fence_value TEXT; + request_value TEXT; + actor_value TEXT; + selected_digest TEXT; + scope_digest TEXT; + content_digest TEXT; + binding_schema TEXT; + expected_binding_schema TEXT; + recipient_value TEXT; + purpose_value TEXT; + count_text TEXT; + source_count INTEGER; + max_source_count INTEGER; + source_index INTEGER := 0; + family_value TEXT; + family_digest TEXT; + family_schema TEXT; + expected_family_schema TEXT; + snapshot JSONB; + source_kind TEXT; + source_scope TEXT; + source_key_value TEXT; + generation_marker TEXT; + vector JSONB; + seen TEXT[] := ARRAY[]::TEXT[]; + previous_key TEXT; + original account_selected_owner_intake_source_read_reservations%ROWTYPE; + issuer account_control_ui_issuance_operations%ROWTYPE; + expected_schema TEXT; + expected_purpose TEXT; + expected_reader TEXT; + families TEXT[] := ARRAY['COMMAND', 'REALM_POLICY', 'ASSET', 'GAMEPLAY_RULE', 'BRANDING', 'TEMPLATE_CONFIG']; +BEGIN + SELECT * INTO STRICT original FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id; + SELECT * INTO STRICT issuer FROM account_control_ui_issuance_operations + WHERE operation_id = NEW.issuance_operation_id; + IF NEW.producer_xid <> txid_current() + OR issuer.status IS DISTINCT FROM 'COMMITTED' + OR extract(epoch FROM clock_timestamp()) >= issuer.expires_at_epoch_second + OR issuer.account_uuid IS DISTINCT FROM NEW.actor_account_uuid + OR issuer.tenant_uuid IS DISTINCT FROM NEW.tenant_uuid + OR issuer.source_payload IS DISTINCT FROM NEW.source_payload + OR issuer.bundle_payload IS DISTINCT FROM NEW.issuance_bundle + OR NEW.binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.binding_bytes), 'hex') + OR NEW.content_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.content_bytes), 'hex') + OR (convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->>'issuanceFence')::BIGINT + IS DISTINCT FROM NEW.issuance_fence + OR convert_from(NEW.issuance_bundle, 'UTF8')::JSONB->'outboxCheckpoints' + IS DISTINCT FROM convert_from(NEW.outbox_checkpoints, 'UTF8')::JSONB + OR original.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(original.scope_bytes), 'hex') + OR EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_aborts + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Finalized authorization requires exact current committed creator evidence' + USING ERRCODE = '23514'; + END IF; + + -- The complete selected-owner authorization frame is closed and content-bound. + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + binding_schema := convert_from(parsed, 'UTF8'); + SELECT frame_value, next_position INTO content_bytes, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO content_digest, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + IF content_bytes IS DISTINCT FROM NEW.content_bytes + OR content_digest IS DISTINCT FROM NEW.content_digest THEN + RAISE EXCEPTION 'Finalized authorization differs from exact selected content' + USING ERRCODE = '23514'; + END IF; + + -- Decode preliminary scope from the content and require the exact retained owner tuple. + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF convert_from(parsed, 'UTF8') <> 'game-design-selected-owner-intake-source/v1' THEN + RAISE EXCEPTION 'Unknown selected owner content schema' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO scope_bytes, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO scope_digest, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF scope_bytes IS DISTINCT FROM original.scope_bytes + OR scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(scope_bytes), 'hex') THEN + RAISE EXCEPTION 'Selected content scope differs from original reservation' + USING ERRCODE = '23514'; + END IF; + + SELECT frame_value, next_position INTO parsed, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + scope_schema := convert_from(parsed, 'UTF8'); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO scope_owner, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO operation_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO fence_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO request_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO actor_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT frame_value, next_position INTO selected_bytes, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO selected_digest, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + IF scope_owner = 'ENTITY_MANAGEMENT' THEN + expected_schema := 'account-entity-intake-source-read/v1'; + expected_purpose := 'ENTITY_INTAKE_SOURCE'; + expected_reader := 'spiffe://firemud/ns/' || namespace_value || '/sa/account-service'; + expected_binding_schema := 'account-entity-intake-authorization/v1'; + ELSIF scope_owner = 'AUTOMATION_SCRIPTING' THEN + expected_schema := 'account-automation-intake-source-read/v1'; + expected_purpose := 'AUTOMATION_INTAKE_SOURCE'; + expected_reader := 'spiffe://firemud/ns/' || namespace_value || '/sa/account-service'; + expected_binding_schema := 'account-automation-intake-authorization/v1'; + ELSE + RAISE EXCEPTION 'Unknown selected owner domain' USING ERRCODE = '23514'; + END IF; + IF scope_schema IS DISTINCT FROM expected_schema + OR namespace_value !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR operation_value IS DISTINCT FROM NEW.operation_id::TEXT + OR fence_value IS DISTINCT FROM NEW.fence_id::TEXT + OR request_value IS DISTINCT FROM NEW.intake_request_id::TEXT + OR actor_value IS DISTINCT FROM NEW.actor_account_uuid::TEXT + OR selected_digest IS DISTINCT FROM 'sha256:' || encode(sha256(selected_bytes), 'hex') + OR NEW.owner IS DISTINCT FROM scope_owner + OR NEW.target_namespace IS DISTINCT FROM namespace_value + OR NEW.actor_account_uuid::TEXT IS DISTINCT FROM actor_value + OR NEW.tenant_uuid::TEXT IS DISTINCT FROM convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalTenantId' + OR NEW.version_uuid::TEXT IS DISTINCT FROM convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalVersionId' + THEN + RAISE EXCEPTION 'Selected owner scope fields differ from finalized authorization' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + IF text_value IS DISTINCT FROM expected_reader THEN + RAISE EXCEPTION 'Selected owner Account reader differs from closed scope' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, scope_position + FROM account_publication_authorization_read_frame(scope_bytes, scope_position); + IF text_value IS DISTINCT FROM expected_purpose + OR scope_position <> octet_length(scope_bytes) + 1 THEN + RAISE EXCEPTION 'Selected owner scope has an unknown purpose or trailing bytes' + USING ERRCODE = '23514'; + END IF; + + -- Exactly six named canonical snapshots, each tied to this exact selected Draft binding. + FOR family_value IN SELECT unnest(families) LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT frame_value, next_position INTO snapshot_bytes, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO family_digest, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF text_value IS DISTINCT FROM family_value + OR octet_length(snapshot_bytes) = 0 + OR family_digest IS DISTINCT FROM 'sha256:' || encode(sha256(snapshot_bytes), 'hex') THEN + RAISE EXCEPTION 'Selected owner content family is missing, unknown, or changed' + USING ERRCODE = '23514'; + END IF; + snapshot := convert_from(snapshot_bytes, 'UTF8')::JSONB; + family_schema := snapshot->>'schema'; + expected_family_schema := CASE family_value + WHEN 'COMMAND' THEN 'game-design-command-source-snapshot/v1' + WHEN 'REALM_POLICY' THEN 'game-design-realm-policy-snapshot/v1' + WHEN 'ASSET' THEN 'game-design-ordinary-asset-source-snapshot/v1' + WHEN 'GAMEPLAY_RULE' THEN 'game-design-gameplay-rule-source-snapshot/v1' + WHEN 'BRANDING' THEN 'game-design-branding-asset-source-snapshot/v1' + ELSE NULL END; + IF jsonb_typeof(snapshot) IS DISTINCT FROM 'object' + OR snapshot->>'bindingJson' IS DISTINCT FROM convert_from(selected_bytes, 'UTF8') + OR snapshot->>'bindingDigest' IS DISTINCT FROM selected_digest + OR (family_value = 'TEMPLATE_CONFIG' + AND (family_schema IS NULL OR family_schema NOT IN ( + 'game-design-template-config-source-snapshot/v1', + 'game-design-template-config-source-snapshot/v2'))) + OR (family_value <> 'TEMPLATE_CONFIG' + AND family_schema IS DISTINCT FROM expected_family_schema) THEN + RAISE EXCEPTION 'Selected owner family differs from exact selected Draft binding' + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF q <> octet_length(content_bytes) + 1 THEN + RAISE EXCEPTION 'Selected owner content has trailing or extra family bytes' + USING ERRCODE = '23514'; + END IF; + + -- Final authorization reader/purpose and all source evidence frames are closed. + SELECT convert_from(frame_value, 'UTF8'), next_position INTO recipient_value, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO purpose_value, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO count_text, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + IF binding_schema IS DISTINCT FROM expected_binding_schema + OR recipient_value IS DISTINCT FROM + CASE scope_owner WHEN 'ENTITY_MANAGEMENT' + THEN 'spiffe://firemud/ns/' || namespace_value || '/sa/entity-management-service' + ELSE 'spiffe://firemud/ns/' || namespace_value || '/sa/automation-scripting-service' END + OR purpose_value IS DISTINCT FROM + CASE scope_owner WHEN 'ENTITY_MANAGEMENT' THEN 'ENTITY_INTAKE_RETENTION' + ELSE 'AUTOMATION_INTAKE_RETENTION' END + OR count_text !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Finalized authorization schema, reader, purpose, or source count is invalid' + USING ERRCODE = '23514'; + END IF; + max_source_count := (octet_length(NEW.binding_bytes) - p) / 4; + IF length(count_text) > length(max_source_count::TEXT) THEN + RAISE EXCEPTION 'Finalized source count exceeds remaining canonical frame capacity' + USING ERRCODE = '23514'; + END IF; + source_count := count_text::INTEGER; + vector := convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'; + IF source_count < 1 OR source_count > max_source_count + OR jsonb_typeof(vector) IS DISTINCT FROM 'array' + OR jsonb_array_length(vector) IS DISTINCT FROM source_count + OR (SELECT count(*) FROM account_selected_owner_intake_sources + WHERE operation_id = NEW.operation_id) IS DISTINCT FROM source_count THEN + RAISE EXCEPTION 'Finalized authorization requires the complete current source vector' + USING ERRCODE = '23514'; + END IF; + FOR source_index IN 1..source_count LOOP + SELECT frame_value, next_position INTO source_bytes, p + FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); + IF source_bytes IS DISTINCT FROM decode(vector->>(source_index - 1), 'base64') + OR octet_length(source_bytes) > 131072 THEN + RAISE EXCEPTION 'Finalized source differs from current issuer source vector' + USING ERRCODE = '23514'; + END IF; + source_position := 1; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_schema, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_kind, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_scope, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO generation_marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF generation_marker = 'PRESENT' THEN + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF text_value !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid finalized source generation' USING ERRCODE = '23514'; + END IF; + ELSIF generation_marker <> 'ABSENT' THEN + RAISE EXCEPTION 'Invalid finalized source generation marker' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF text_value !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid finalized source version' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO generation_marker, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF generation_marker = 'PRESENT' THEN + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF octet_length(parsed) = 0 THEN + RAISE EXCEPTION 'Invalid finalized source checkpoint stream' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO text_value, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF text_value !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Invalid finalized source checkpoint sequence' USING ERRCODE = '23514'; + END IF; + ELSIF generation_marker <> 'ABSENT' THEN + RAISE EXCEPTION 'Invalid finalized source checkpoint marker' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := source_kind || ':' || source_scope; + IF source_schema <> 'account-draft-source-evidence/v1' + OR source_kind NOT IN ('ISSUER', 'ACCOUNT', 'TENANT', 'MEMBERSHIP', 'GLOBAL_ROLES', 'CREATOR_PARTY', 'HOSTED_TERMS') + OR source_scope = '' OR source_position <> octet_length(source_bytes) + 1 + OR octet_length(parsed) = 0 OR source_key_value = ANY(seen) + OR (previous_key IS NOT NULL AND + account_publication_authorization_source_sort_key(previous_key) >= + account_publication_authorization_source_sort_key(source_key_value)) + OR (source_kind IN ('ACCOUNT', 'GLOBAL_ROLES') AND source_scope IS DISTINCT FROM actor_value) + OR (source_kind = 'TENANT' AND source_scope IS DISTINCT FROM NEW.tenant_uuid::TEXT) + OR (source_kind = 'MEMBERSHIP' AND source_scope IS DISTINCT FROM actor_value || '/' || NEW.tenant_uuid::TEXT) + OR NOT EXISTS (SELECT 1 FROM account_selected_owner_intake_sources held + WHERE held.operation_id = NEW.operation_id AND held.source_key = source_key_value + AND held.source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Malformed, changed, or incomplete finalized source evidence' + USING ERRCODE = '23514'; + END IF; + seen := array_append(seen, source_key_value); + previous_key := source_key_value; + END LOOP; + IF p <> octet_length(NEW.binding_bytes) + 1 THEN + RAISE EXCEPTION 'Finalized authorization has trailing bytes' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER account_selected_owner_intake_authorization_complete + AFTER INSERT ON account_selected_owner_intake_authorizations + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_selected_owner_intake_authorization_complete_guard(); + +CREATE FUNCTION account_selected_owner_intake_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM account_selected_owner_intake_authorizations + WHERE operation_id = NEW.operation_id AND producer_xid = txid_current()) THEN + RAISE EXCEPTION 'Finalized sources must accompany the original Account transaction' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_selected_owner_intake_source_validate + BEFORE INSERT ON account_selected_owner_intake_sources FOR EACH ROW + EXECUTE FUNCTION account_selected_owner_intake_source_insert_guard(); + +CREATE TRIGGER account_selected_owner_intake_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_authorizations + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_authorizations + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_sources_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_sources + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_sources_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java new file mode 100644 index 0000000000..690bd67e6f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -0,0 +1,613 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedOwnerIntakeSourceReservationRepository.State; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Account creator/currentness, PostgreSQL finalization, immutable source participation and + * pending source guards. Six-family content and the Game Design caller are stipulated test inputs; + * this is not producer transport, authenticated Entity/Automation retention, terminal settlement, + * activation, or runtime proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest { + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("intake-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "intake-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void finalizesBothOwnersExactlyAndKeepsTheirFullSourceVectorsPending() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + settleOriginal(issued, selected); + var expectedSources = + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment()).sources()); + + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservationService = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var finalized = new ArrayList(); + var scopes = new ArrayList(); + + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + UUID requestId = UUID.randomUUID(); + var scope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), requestId, owner, selected, issued.environment())); + var content = content(scope, "stipulated-original"); + var authorization = + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); + + assertThat(authorization.owner()).isEqualTo(owner); + assertThat(authorization.content().canonicalBytes()).isEqualTo(content.canonicalBytes()); + assertThat(authorization.sources()).hasSize(expectedSources.size()); + for (int index = 0; index < expectedSources.size(); index++) { + assertThat(authorization.sources().get(index).key()) + .isEqualTo(expectedSources.get(index).key()); + assertThat(authorization.sources().get(index).canonicalBytes()) + .isEqualTo(expectedSources.get(index).canonicalBytes()); + } + assertThat(f.tx(() -> repository.recoverSourceRead(scope)).state()) + .isEqualTo(State.FINALIZED); + var readback = f.tx(() -> repository.findFinalAuthorization(scope)).orElseThrow(); + assertThat(readback.canonicalBytes()).isEqualTo(authorization.canonicalBytes()); + assertThat(readback.digest()).isEqualTo(authorization.digest()); + var exactRetry = + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> { + throw new AssertionError( + "Exact finalization retry must not re-admit"); + }))); + assertThat(exactRetry.canonicalBytes()).isEqualTo(authorization.canonicalBytes()); + f.tx( + () -> { + repository.readFinalAuthorization(authorization); + return null; + }); + assertThatThrownBy(() -> f.tx(() -> repository.sourceReadCurrentness(scope))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("preliminary source read"); + assertThatThrownBy(() -> f.tx(() -> repository.abortSourceRead(scope))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot be preliminarily aborted"); + + var changedContent = content(scope, "stipulated-changed"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, changedContent, current, () -> {})))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("conflicts with original selected content"); + + scopes.add(scope); + finalized.add(authorization); + } + + UUID abortedRequest = UUID.randomUUID(); + var abortedScope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + abortedRequest, + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); + assertThat(f.tx(() -> repository.abortSourceRead(abortedScope).state())) + .isEqualTo(State.ABORTED); + var abortedContent = content(abortedScope, "stipulated-aborted"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + abortedScope, abortedContent, current, () -> {})))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("scope aborted"); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_selected_owner_intake_authorizations WHERE operation_id = ?", + abortedScope.operationId())) + .isNull(); + + var sourceChange = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), finalized.getFirst().sources(), new byte[] {2}); + assertThat(f.tx(() -> f.fences.requestSourceChange(sourceChange))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(sourceChange))).isFalse(); + assertThat(scopes).hasSize(2); + } + } + + @Test + void postgresRejectsChangedNamespaceUnknownFamilyAndSelectedScopeEvidence() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selected(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservationService = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var scopes = new ArrayList(); + for (int index = 0; index < 3; index++) { + scopes.add( + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment()))); + } + + var original = scopes.get(0); + var changedNamespace = + new SelectedOwnerIntakeSourceReadScope( + original.owner(), + "different-namespace", + original.operationId(), + original.fenceId(), + original.intakeRequestId(), + original.actorAccountId(), + original.selected()); + var namespaceContent = content(changedNamespace, "stipulated-namespace-mismatch"); + var namespaceBinding = + new SelectedOwnerIntakeAuthorizationBinding( + namespaceContent, + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment()).sources())); + assertRejectedByPostgres( + issued, + original, + namespaceContent.canonicalBytes(), + namespaceBinding.canonicalBytes(), + "Selected content scope differs from original reservation"); + + var familyScope = scopes.get(1); + var familyContent = content(familyScope, "stipulated-family-mismatch"); + byte[] unknownFamilyContent = replaceFirstFamily(familyContent.canonicalBytes(), "UNKNOWN"); + var familySources = + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment()).sources()); + assertRejectedByPostgres( + issued, + familyScope, + unknownFamilyContent, + authorizationBytes(familyScope, unknownFamilyContent, familySources), + "Selected owner content family is missing, unknown, or changed"); + + var selectedScope = scopes.get(2); + var changedSelectedScope = + new SelectedOwnerIntakeSourceReadScope( + selectedScope.owner(), + selectedScope.targetNamespace(), + selectedScope.operationId(), + selectedScope.fenceId(), + selectedScope.intakeRequestId(), + selectedScope.actorAccountId(), + selected(f.tenant)); + var changedSelectedContent = content(changedSelectedScope, "stipulated-scope-mismatch"); + var changedSelectedBinding = + new SelectedOwnerIntakeAuthorizationBinding( + changedSelectedContent, + f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment()).sources())); + assertRejectedByPostgres( + issued, + selectedScope, + changedSelectedContent.canonicalBytes(), + changedSelectedBinding.canonicalBytes(), + "Selected content scope differs from original reservation"); + } + } + + private static void assertRejectedByPostgres( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + SelectedOwnerIntakeSourceReadScope reservationScope, + byte[] contentBytes, + byte[] bindingBytes, + String expectedDiagnostic) { + var f = issued.sources(); + assertThatThrownBy( + () -> + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + insertRawAuthorization( + f.dsl, reservationScope, contentBytes, bindingBytes, current); + return null; + }))) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(root) + .isInstanceOfSatisfying( + java.sql.SQLException.class, + sql -> { + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains(expectedDiagnostic); + }); + }); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_selected_owner_intake_authorizations " + + "WHERE operation_id = ?", + reservationScope.operationId())) + .isNull(); + } + + private static void insertRawAuthorization( + org.jooq.DSLContext dsl, + SelectedOwnerIntakeSourceReadScope reservationScope, + byte[] contentBytes, + byte[] bindingBytes, + AccountControlUiActorService.Current current) { + dsl.execute( + "INSERT INTO account_selected_owner_intake_authorizations " + + "(operation_id, fence_id, intake_request_id, owner, target_namespace, " + + "actor_account_uuid, tenant_uuid, version_uuid, content_bytes, content_digest, " + + "binding_bytes, binding_digest, issuance_operation_id, issuance_fence, source_payload, " + + "issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + reservationScope.operationId(), + reservationScope.fenceId(), + reservationScope.intakeRequestId(), + reservationScope.owner().name(), + reservationScope.targetNamespace(), + reservationScope.actorAccountId(), + reservationScope.selected().target().canonicalTenantId(), + reservationScope.selected().target().canonicalVersionId(), + contentBytes, + DraftAuthorizationFenceBinding.digest(contentBytes), + bindingBytes, + DraftAuthorizationFenceBinding.digest(bindingBytes), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + AccountControlUiAuthority.canonical(current.source().outboxCheckpoints())); + var sources = + current.source().sources().stream() + .sorted(Comparator.comparing(DraftAuthorizationFenceBinding.SourceEvidence::key)) + .toList(); + for (var source : sources) { + dsl.execute( + "INSERT INTO account_selected_owner_intake_sources " + + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + reservationScope.operationId(), + source.key(), + source.canonicalBytes()); + } + } + + private static byte[] authorizationBytes( + SelectedOwnerIntakeSourceReadScope scope, + byte[] contentBytes, + List sources) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, authorizationSchema(scope.owner())); + DraftAuthorizationFenceBinding.frame(out, contentBytes); + DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(contentBytes)); + DraftAuthorizationFenceBinding.frame( + out, + scope.owner() == Owner.ENTITY_MANAGEMENT + ? "spiffe://firemud/ns/" + scope.targetNamespace() + "/sa/entity-management-service" + : "spiffe://firemud/ns/" + + scope.targetNamespace() + + "/sa/automation-scripting-service"); + DraftAuthorizationFenceBinding.frame( + out, + scope.owner() == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_RETENTION" + : "AUTOMATION_INTAKE_RETENTION"); + var sorted = + sources.stream() + .sorted(Comparator.comparing(DraftAuthorizationFenceBinding.SourceEvidence::key)) + .toList(); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(sorted.size())); + for (var source : sorted) DraftAuthorizationFenceBinding.frame(out, source.canonicalBytes()); + return out.toByteArray(); + } + + private static String authorizationSchema(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT + ? "account-entity-intake-authorization/v1" + : "account-automation-intake-authorization/v1"; + } + + private static byte[] replaceFirstFamily(byte[] contentBytes, String replacement) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(contentBytes); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, reader.text()); + DraftAuthorizationFenceBinding.frame(out, reader.bytes()); + DraftAuthorizationFenceBinding.frame(out, reader.text()); + for (int index = 0; index < 6; index++) { + String family = reader.text(); + DraftAuthorizationFenceBinding.frame(out, index == 0 ? replacement : family); + DraftAuthorizationFenceBinding.frame(out, reader.bytes()); + DraftAuthorizationFenceBinding.frame(out, reader.text()); + } + reader.requireEnd(); + return out.toByteArray(); + } + + private static void settleOriginal( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, DraftCommitBinding selected) { + var f = issued.sources(); + var captured = f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + selected.requestId(), + selected.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + selected.target().canonicalVersionId(), + selected.baseCommitId(), + "0", + selected.canonicalBytes(), + selected.canonicalBytes(), + selected.digest(), + captured.sources()) + .withRequiredOwners(); + issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); + f.tx( + () -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); + } + + private static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope, String marker) { + var selected = scope.selected(); + UUID genesis = UUID.randomUUID(); + var gameplay = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "sourceEpoch", "0", + "inheritedCommitId", "", + "genesisReceiptId", genesis.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var template = new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()); + var snapshots = + Map.of( + "COMMAND", + opaqueSnapshot("game-design-command-source-snapshot/v1", "COMMAND", selected, marker), + "REALM_POLICY", + opaqueSnapshot( + "game-design-realm-policy-snapshot/v1", "REALM_POLICY", selected, marker), + "ASSET", + opaqueSnapshot( + "game-design-ordinary-asset-source-snapshot/v1", "ASSET", selected, marker), + "BRANDING", + opaqueSnapshot( + "game-design-branding-asset-source-snapshot/v1", "BRANDING", selected, marker)); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + switch (family) { + case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); + case "TEMPLATE_CONFIG" -> template.canonicalBytes(); + default -> snapshots.get(family); + }; + DraftAuthorizationFenceBinding.frame(out, family); + DraftAuthorizationFenceBinding.frame(out, snapshot); + DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] opaqueSnapshot( + String schema, String family, DraftCommitBinding selected, String marker) { + return GameplayRuleManifest.canonical( + Map.of( + "schema", schema, + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "family", family, + "marker", marker)) + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + + private static DraftCommitBinding selected(UUID tenant) { + var target = + new DraftCommitBinding.TargetProof( + tenant, UUID.randomUUID(), 17, "private", 11, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleManifest.canonical(Map.of("schema", "test/v1")))), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + target.canonicalVersionId().toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } + + private static T asGameDesign(java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationRepositoryTest.java new file mode 100644 index 0000000000..8db02479e7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationRepositoryTest.java @@ -0,0 +1,29 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +/** Synthetic repository boundary proof; PostgreSQL finalization is covered separately. */ +class AccountSelectedOwnerIntakeAuthorizationRepositoryTest { + @Test + void finalizationAndExactReadsRequireWritableOwnerTransactions() { + var dsl = mock(DSLContext.class); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(dsl); + + assertThatThrownBy(() -> repository.finalizeSourceRead(null, null, null, () -> {})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.findFinalAuthorization(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.readFinalAuthorization(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + + verifyNoInteractions(dsl); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java new file mode 100644 index 0000000000..8a4e17c840 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java @@ -0,0 +1,691 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceClient; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic Account composition tests; they do not establish physical or cross-owner proof. */ +class AccountSelectedOwnerIntakeAuthorizationServiceTest { + private static final String TOKEN = "header.payload.signature"; + private static final UUID ACTOR = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID TENANT = UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID VERSION = UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"); + private static final UUID OPERATION = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID GENESIS = UUID.fromString("33333333-3333-4333-8333-333333333333"); + + private final AccountControlUiActorService actors = mock(AccountControlUiActorService.class); + private final DraftAuthorizationFenceRepository fences = + mock(DraftAuthorizationFenceRepository.class); + private final AccountSelectedOwnerIntakeSourceReservationRepository repository = + mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + private final SelectedOwnerIntakeSourceClient sources = + mock(SelectedOwnerIntakeSourceClient.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final AccountSelectedOwnerIntakeAuthorizationService service = + new AccountSelectedOwnerIntakeAuthorizationService( + actors, fences, repository, sources, transactions, "test"); + + @AfterEach + void clearContextAndTransaction() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void freshAuthorizationReadsOutsideSqlThenRevalidatesAndReadsBackExactOriginalIdentity() { + var selected = selected(); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, OPERATION, FENCE); + var content = content(scope, "original"); + var current = current(ACTOR, TENANT); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, current.source().sources()); + var firstEnvironment = mock(CapturedEnvironmentBoundary.class); + var finalEnvironment = mock(CapturedEnvironmentBoundary.class); + var captures = new AtomicInteger(); + var request = + org.mockito.ArgumentCaptor.forClass(SelectedOwnerIntakeSourceReadEvidence.Request.class); + stubTransactions(); + when(repository.findSourceReadScope( + selected.requestId(), Owner.ENTITY_MANAGEMENT, selected, "test", tokenHash(TOKEN))) + .thenReturn(Optional.empty()); + when(repository.reserveSourceRead( + eq(selected.requestId()), + eq(Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(current), + eq("test"), + any(Runnable.class))) + .thenAnswer( + invocation -> { + invocation.getArgument(5).run(); + return scope; + }); + when(repository.recoverSourceRead(scope)) + .thenReturn( + recovery(scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED)); + when(repository.finalizeSourceRead( + eq(scope), + argThat(candidate -> sameContent(candidate, content)), + eq(current), + any(Runnable.class))) + .thenAnswer( + invocation -> { + invocation.getArgument(3).run(); + return binding; + }); + doAnswer( + invocation -> { + Function action = invocation.getArgument(3); + return action.apply(current); + }) + .when(actors) + .withCurrent( + eq(TOKEN), eq(TENANT), any(CapturedEnvironmentBoundary.class), any(Function.class)); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return content; + }) + .when(sources) + .read(request.capture()); + + var result = + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> captures.incrementAndGet() == 1 ? firstEnvironment : finalEnvironment)); + + assertThat(result.canonicalBytes()).isEqualTo(binding.canonicalBytes()); + assertThat(captures.get()).isEqualTo(2); + assertThat(request.getValue().scope()).isEqualTo(scope); + assertThat(result.operationId()).isEqualTo(scope.operationId()); + assertThat(result.fenceId()).isEqualTo(scope.fenceId()); + assertThat(result.intakeRequestId()).isEqualTo(selected.requestId()); + verify(repository).readFinalAuthorization(binding); + verify(fences, org.mockito.Mockito.times(2)) + .requireSelectedOwnerIntakeAdmission(current.source().sources(), selected); + InOrder order = inOrder(actors, repository, sources); + order + .verify(repository) + .findSourceReadScope( + selected.requestId(), Owner.ENTITY_MANAGEMENT, selected, "test", tokenHash(TOKEN)); + order.verify(actors).withCurrent(eq(TOKEN), eq(TENANT), eq(firstEnvironment), any()); + order + .verify(repository) + .reserveSourceRead( + eq(selected.requestId()), + eq(Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(current), + eq("test"), + any(Runnable.class)); + order.verify(repository).recoverSourceRead(scope); + order.verify(sources).read(request.getValue()); + order.verify(actors).withCurrent(eq(TOKEN), eq(TENANT), eq(finalEnvironment), any()); + order + .verify(repository) + .finalizeSourceRead( + eq(scope), + argThat(candidate -> sameContent(candidate, content)), + eq(current), + any(Runnable.class)); + order.verify(repository).readFinalAuthorization(binding); + } + + @Test + void exactFinalRetryUsesOriginalBindingBeforeEnvironmentOrRemoteSourceRead() { + var selected = selected(); + var scope = scope(Owner.AUTOMATION_SCRIPTING, selected, OPERATION, FENCE); + var content = content(scope, "retained"); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, sources(ACTOR)); + stubTransactions(); + when(repository.findSourceReadScope( + selected.requestId(), Owner.AUTOMATION_SCRIPTING, selected, "test", tokenHash(TOKEN))) + .thenReturn(Optional.of(scope)); + when(repository.recoverSourceRead(scope)) + .thenReturn( + recovery(scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.FINALIZED)); + when(repository.findFinalAuthorization(scope)).thenReturn(Optional.of(binding)); + AtomicInteger environmentReads = new AtomicInteger(); + + var result = + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.AUTOMATION_SCRIPTING, + selected, + () -> { + environmentReads.incrementAndGet(); + throw new AssertionError( + "exact finalized retry must not capture environment"); + })); + + assertThat(result.canonicalBytes()).isEqualTo(binding.canonicalBytes()); + assertThat(result.operationId()).isEqualTo(OPERATION); + assertThat(result.fenceId()).isEqualTo(FENCE); + assertThat(result.intakeRequestId()).isEqualTo(selected.requestId()); + assertThat(environmentReads.get()).isZero(); + verify(repository).readFinalAuthorization(binding); + verifyNoInteractions(actors, fences, sources); + } + + @Test + void substitutedSelectedContentDeniesWithoutReleasingThePreliminaryReservation() { + var selected = selected(); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, OPERATION, FENCE); + var substitutedScope = + scope( + Owner.ENTITY_MANAGEMENT, + selected, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + FENCE); + var current = current(ACTOR, TENANT); + var captures = new AtomicInteger(); + var environment = mock(CapturedEnvironmentBoundary.class); + stubFreshReservation(selected, scope, current); + when(sources.read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class))) + .thenReturn(content(substitutedScope, "substituted")); + + assertThatThrownBy( + () -> + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> { + captures.incrementAndGet(); + return environment; + }))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + + assertThat(captures.get()).isEqualTo(1); + verify(repository) + .reserveSourceRead( + eq(selected.requestId()), + eq(Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(current), + eq("test"), + any(Runnable.class)); + verify(repository, never()).finalizeSourceRead(any(), any(), any(), any()); + verify(repository, never()).abortSourceRead(any()); + } + + @Test + void changedCurrentCreatorDuringPostReadCaptureCannotFinalize() { + var selected = selected(); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, OPERATION, FENCE); + var content = content(scope, "source"); + var current = current(ACTOR, TENANT); + var environment = mock(CapturedEnvironmentBoundary.class); + var actorCalls = new AtomicInteger(); + stubFreshReservation(selected, scope, current); + when(sources.read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class))) + .thenReturn(content); + doAnswer( + invocation -> { + if (actorCalls.incrementAndGet() == 1) { + Function action = + invocation.getArgument(3); + return action.apply(current); + } + throw Status.PERMISSION_DENIED + .withDescription("creator source changed after remote read") + .asRuntimeException(); + }) + .when(actors) + .withCurrent( + eq(TOKEN), eq(TENANT), any(CapturedEnvironmentBoundary.class), any(Function.class)); + + assertThatThrownBy( + () -> + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> environment))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(actorCalls.get()).isEqualTo(2); + verify(sources).read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class)); + verify(repository, never()).finalizeSourceRead(any(), any(), any(), any()); + verify(repository, never()).abortSourceRead(any()); + } + + @Test + void lostFinalizationAcknowledgementRecoversOnlyTheCommittedSameBinding() { + var selected = selected(); + var scope = scope(Owner.AUTOMATION_SCRIPTING, selected, OPERATION, FENCE); + var content = content(scope, "exact source"); + var current = current(ACTOR, TENANT); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, current.source().sources()); + var environment = mock(CapturedEnvironmentBoundary.class); + stubFreshReservation(selected, scope, current); + when(sources.read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class))) + .thenReturn(content); + when(repository.finalizeSourceRead( + eq(scope), + argThat(candidate -> sameContent(candidate, content)), + eq(current), + any(Runnable.class))) + .thenAnswer( + invocation -> { + invocation.getArgument(3).run(); + throw new IllegalStateException("final commit acknowledgement lost"); + }); + when(repository.findFinalAuthorization(scope)).thenReturn(Optional.of(binding)); + + var result = + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.AUTOMATION_SCRIPTING, + selected, + () -> environment)); + + assertThat(result.canonicalBytes()).isEqualTo(binding.canonicalBytes()); + verify(repository).findFinalAuthorization(scope); + verify(repository).readFinalAuthorization(binding); + // The fresh attempt reserves once before finalization; lost-ACK recovery must not reserve + // again. + verify(repository) + .reserveSourceRead(eq(selected.requestId()), any(), any(), any(), any(), any()); + InOrder order = inOrder(repository); + order + .verify(repository) + .finalizeSourceRead( + eq(scope), argThat(candidate -> sameContent(candidate, content)), eq(current), any()); + order.verify(repository).findFinalAuthorization(scope); + order.verify(repository).readFinalAuthorization(binding); + } + + @Test + void unavailableRemoteResponseLeavesTheOriginalPreliminaryReservationHeld() { + var selected = selected(); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, OPERATION, FENCE); + var current = current(ACTOR, TENANT); + var environment = mock(CapturedEnvironmentBoundary.class); + stubFreshReservation(selected, scope, current); + when(sources.read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class))) + .thenThrow( + Status.UNAVAILABLE.withDescription("source read outcome unknown").asRuntimeException()); + + assertThatThrownBy( + () -> + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> environment))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + + verify(repository) + .reserveSourceRead( + eq(selected.requestId()), + eq(Owner.ENTITY_MANAGEMENT), + eq(selected), + eq(current), + eq("test"), + any(Runnable.class)); + verify(repository, never()).finalizeSourceRead(any(), any(), any(), any()); + verify(repository, never()).abortSourceRead(any()); + } + + @Test + void exactGameDesignPeerAndNoEndUserContextAreCheckedBeforeInputOrStorage() { + assertCode( + Status.Code.UNAUTHENTICATED, + () -> service.authorizeWithEnvironmentCapture(null, null, null, null, null)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "other", + "game-design-service", + () -> service.authorizeWithEnvironmentCapture(null, null, null, null, null))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "test", + "account-service", + () -> service.authorizeWithEnvironmentCapture(null, null, null, null, null))); + + SessionContext.setContext("44", List.of(), Map.of()); + try { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + asPeer( + "test", + "game-design-service", + () -> service.authorizeWithEnvironmentCapture(null, null, null, null, null))); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(actors, fences, repository, sources, transactions); + } + + private void stubFreshReservation( + DraftCommitBinding selected, + SelectedOwnerIntakeSourceReadScope scope, + AccountControlUiActorService.Current current) { + stubTransactions(); + when(repository.findSourceReadScope( + selected.requestId(), scope.owner(), selected, "test", tokenHash(TOKEN))) + .thenReturn(Optional.empty()); + when(repository.reserveSourceRead( + eq(selected.requestId()), + eq(scope.owner()), + eq(selected), + eq(current), + eq("test"), + any(Runnable.class))) + .thenAnswer( + invocation -> { + invocation.getArgument(5).run(); + return scope; + }); + when(repository.recoverSourceRead(scope)) + .thenReturn( + recovery(scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED)); + doAnswer( + invocation -> { + Function action = invocation.getArgument(3); + return action.apply(current); + }) + .when(actors) + .withCurrent( + eq(TOKEN), + eq(selected.target().canonicalTenantId()), + any(CapturedEnvironmentBoundary.class), + any(Function.class)); + } + + private void stubTransactions() { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + } + + private static AccountSelectedOwnerIntakeSourceReservationRepository.Recovery recovery( + SelectedOwnerIntakeSourceReadScope scope, + AccountSelectedOwnerIntakeSourceReservationRepository.State state) { + return new AccountSelectedOwnerIntakeSourceReservationRepository.Recovery(scope, state); + } + + private static AccountControlUiActorService.Current current(UUID actorId, UUID tenantId) { + Record row = mock(Record.class); + byte[] sourcePayload = AccountControlUiAuthority.canonical(Map.of("sources", List.of("AQID"))); + byte[] bundle = AccountControlUiAuthority.canonical(Map.of("issuanceFence", 17)); + when(row.get("request_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("operation_id", UUID.class)) + .thenReturn(UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd")); + when(row.get("token_jti", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("account_uuid", UUID.class)).thenReturn(actorId); + when(row.get("tenant_uuid", UUID.class)).thenReturn(tenantId); + when(row.get("caller_context_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(row.get("caller_workload", String.class)).thenReturn("game-design-service"); + when(row.get("request_mac_key_id", String.class)).thenReturn("key"); + when(row.get("request_digest", String.class)).thenReturn("digest"); + when(row.get("status", String.class)).thenReturn("COMMITTED"); + when(row.get("token_hash", String.class)).thenReturn(tokenHash(TOKEN)); + when(row.get("claims_payload", byte[].class)).thenReturn(new byte[] {1}); + when(row.get("source_payload", byte[].class)).thenReturn(sourcePayload); + when(row.get("bundle_payload", byte[].class)).thenReturn(bundle); + when(row.get("signer_receipt", byte[].class)).thenReturn(new byte[] {2}); + when(row.get("pending_registry", byte[].class)).thenReturn(new byte[] {3}); + when(row.get("active_registry", byte[].class)).thenReturn(new byte[] {4}); + when(row.get("issued_at_epoch_second", Long.class)).thenReturn(1_800_000_000L); + when(row.get("expires_at_epoch_second", Long.class)).thenReturn(1_800_000_300L); + when(row.get("recovery_expires_at", OffsetDateTime.class)) + .thenReturn(OffsetDateTime.parse("2027-01-01T00:01:00Z")); + var stored = new AccountControlUiIssuanceRepository.Stored(row); + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + when(snapshot.sources()).thenReturn(sources(actorId)); + when(snapshot.issuanceFence()).thenReturn(17L); + when(snapshot.outboxCheckpoints()) + .thenReturn(List.of(Map.of("stream", "account", "sequence", 7))); + return new AccountControlUiActorService.Current(stored, snapshot); + } + + private static List sources(UUID actorId) { + return List.of( + evidence(SourceKind.ACCOUNT, actorId.toString(), "account"), + evidence(SourceKind.TENANT, TENANT.toString(), "tenant"), + evidence(SourceKind.MEMBERSHIP, actorId + "/" + TENANT, "membership")); + } + + private static SourceEvidence evidence(SourceKind kind, String scope, String payload) { + return new SourceEvidence( + kind, scope, null, "1", null, null, payload.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected() { + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 1L, "tenant-key", 2L, "tenant-key", "NEW_GAME_ROW"), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + "templates", + "TENANT", + TENANT.toString(), + "0"))); + } + + private static SelectedOwnerIntakeSourceReadScope scope( + Owner owner, DraftCommitBinding selected, UUID operation, UUID fence) { + return new SelectedOwnerIntakeSourceReadScope( + owner, "test", operation, fence, selected.requestId(), ACTOR, selected); + } + + private static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope, String marker) { + var selected = scope.selected(); + var gameplay = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "sourceEpoch", "0", + "inheritedCommitId", "", + "genesisReceiptId", GENESIS.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var template = new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()); + Map opaque = + Map.of( + "COMMAND", opaqueSnapshot("COMMAND", selected, marker), + "REALM_POLICY", opaqueSnapshot("REALM_POLICY", selected, marker), + "ASSET", opaqueSnapshot("ASSET", selected, marker), + "BRANDING", opaqueSnapshot("BRANDING", selected, marker)); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + switch (family) { + case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); + case "TEMPLATE_CONFIG" -> template.canonicalBytes(); + default -> opaque.get(family); + }; + DraftAuthorizationFenceBinding.frame(out, family); + DraftAuthorizationFenceBinding.frame(out, snapshot); + DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] opaqueSnapshot(String family, DraftCommitBinding selected, String marker) { + return GameplayRuleManifest.canonical( + Map.of( + "schema", + "synthetic-test-only/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "family", + family, + "marker", + marker)) + .getBytes(StandardCharsets.UTF_8); + } + + private static String tokenHash(String value) { + return AccountControlUiIssuanceRepository.hash(value.getBytes(StandardCharsets.US_ASCII)); + } + + private static boolean sameContent( + SelectedOwnerIntakeSourceContent candidate, SelectedOwnerIntakeSourceContent expected) { + return candidate != null + && expected != null + && candidate.scope().equals(expected.scope()) + && candidate.digest().equals(expected.digest()) + && java.util.Arrays.equals(candidate.canonicalBytes(), expected.canonicalBytes()); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = peer.attach(); + try { + action.run(); + } finally { + peer.detach(previous); + } + } + + private static T asPeerResult(String namespace, String workload, Supplier action) { + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = peer.attach(); + try { + return action.get(); + } finally { + peer.detach(previous); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java new file mode 100644 index 0000000000..a70bc98e1c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBinding.java @@ -0,0 +1,257 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; + +/** + * Integrity input for Account's distinct selected-owner source-retention authorization. Decoding + * proves only the canonical relationship among the supplied content and source evidence; it does + * not authenticate Account, establish HELD/current authority, prove a complete source census, or + * create an owner receipt. + */ +public record SelectedOwnerIntakeAuthorizationBinding( + SelectedOwnerIntakeSourceContent content, List sources) { + public static final int MAX_BYTES = 16 * 1024 * 1024; + + public SelectedOwnerIntakeAuthorizationBinding { + Objects.requireNonNull(content, "content"); + SelectedOwnerIntakeSourceReadScope scope = content.scope(); + schemaFor(scope.owner()); + sources = + List.copyOf(Objects.requireNonNull(sources, "sources")).stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.isEmpty() + || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw new IllegalArgumentException("Complete distinct Account sources required"); + } + for (SourceEvidence source : sources) requireActorTenantScope(source, scope); + canonicalBytes( + content, + sources, + intendedReader(scope.owner(), scope.targetNamespace()), + purposeFor(scope.owner())); + } + + @Override + public List sources() { + return List.copyOf(sources); + } + + public Owner owner() { + return content.scope().owner(); + } + + public String targetNamespace() { + return content.scope().targetNamespace(); + } + + public UUID operationId() { + return content.scope().operationId(); + } + + public UUID fenceId() { + return content.scope().fenceId(); + } + + public UUID intakeRequestId() { + return content.scope().intakeRequestId(); + } + + public UUID actorAccountId() { + return content.scope().actorAccountId(); + } + + public DraftCommitBinding selected() { + return content.scope().selected(); + } + + public UUID tenantId() { + return selected().target().canonicalTenantId(); + } + + public UUID versionId() { + return selected().target().canonicalVersionId(); + } + + public String schema() { + return schemaFor(owner()); + } + + public String purpose() { + return purposeFor(owner()); + } + + public String intendedReader() { + return intendedReader(owner(), targetNamespace()); + } + + public byte[] canonicalBytes() { + return canonicalBytes(content, sources, intendedReader(), purpose()); + } + + public String digest() { + return DraftAuthorizationFenceBinding.digest(canonicalBytes()); + } + + /** + * Decodes a self-contained integrity envelope by revalidating its embedded exact source scope, + * complete six-family content and all Account source-evidence frames. + */ + public static SelectedOwnerIntakeAuthorizationBinding fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Selected owner intake authorization size is invalid"); + } + byte[] stored = bytes.clone(); + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + String schema = reader.text(); + Owner owner = ownerForSchema(schema); + byte[] contentBytes = reader.bytes(); + String contentDigest = reader.text(); + if (!DraftAuthorizationFenceBinding.digest(contentBytes).equals(contentDigest)) { + throw new IllegalArgumentException("Selected owner intake content digest differs"); + } + + SelectedOwnerIntakeSourceReadScope embeddedScope = embeddedScope(contentBytes); + if (embeddedScope.owner() != owner) { + throw new IllegalArgumentException("Selected owner intake schema differs from content owner"); + } + SelectedOwnerIntakeSourceContent content = + SelectedOwnerIntakeSourceContent.fromStored(contentBytes, embeddedScope, contentDigest); + String recipientReader = reader.text(); + String purpose = reader.text(); + String expectedReader = intendedReader(owner, embeddedScope.targetNamespace()); + String expectedPurpose = purposeFor(owner); + if (!expectedReader.equals(recipientReader) || !expectedPurpose.equals(purpose)) { + throw new IllegalArgumentException("Selected owner intake recipient or purpose differs"); + } + + String countText = reader.text(); + DraftAuthorizationFenceBinding.decimal(countText, false); + int count = Integer.parseInt(countText); + if (count > reader.remaining() / Integer.BYTES) { + throw new IllegalArgumentException("Incomplete selected owner intake source vector"); + } + var sources = new java.util.ArrayList(); + for (int i = 0; i < count; i++) { + sources.add(SourceEvidence.fromStored(reader.bytes())); + } + reader.requireEnd(); + + var result = new SelectedOwnerIntakeAuthorizationBinding(content, sources); + if (!schema.equals(result.schema()) + || !recipientReader.equals(result.intendedReader()) + || !purpose.equals(result.purpose()) + || !Arrays.equals(stored, result.canonicalBytes())) { + throw new IllegalArgumentException("Noncanonical selected owner intake authorization"); + } + return result; + } + + private static SelectedOwnerIntakeSourceReadScope embeddedScope(byte[] contentBytes) { + if (contentBytes == null + || contentBytes.length == 0 + || contentBytes.length > SelectedOwnerIntakeSourceContent.MAX_BYTES) { + throw new IllegalArgumentException("Selected owner intake content size is invalid"); + } + var contentReader = new DraftAuthorizationFenceBinding.FrameReader(contentBytes); + contentReader.expect(SelectedOwnerIntakeSourceContent.DOMAIN); + byte[] scopeBytes = contentReader.bytes(); + String scopeDigest = contentReader.text(); + if (!DraftAuthorizationFenceBinding.digest(scopeBytes).equals(scopeDigest)) { + throw new IllegalArgumentException("Selected owner intake scope digest differs"); + } + return SelectedOwnerIntakeSourceReadScope.fromStored(scopeBytes); + } + + private static byte[] canonicalBytes( + SelectedOwnerIntakeSourceContent content, + List sources, + String intendedReader, + String purpose) { + var out = new ByteArrayOutputStream(); + frameBounded(out, schemaFor(content.scope().owner())); + byte[] contentBytes = content.canonicalBytes(); + frameBounded(out, contentBytes); + frameBounded(out, content.digest()); + frameBounded(out, intendedReader); + frameBounded(out, purpose); + frameBounded(out, Integer.toString(sources.size())); + for (SourceEvidence source : sources) { + frameBounded(out, source.canonicalBytes()); + } + return out.toByteArray(); + } + + private static void frameBounded(ByteArrayOutputStream out, String value) { + byte[] utf8 = value.getBytes(StandardCharsets.UTF_8); + requireFrameCapacity(out, utf8.length); + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frameBounded(ByteArrayOutputStream out, byte[] value) { + requireFrameCapacity(out, value.length); + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void requireFrameCapacity(ByteArrayOutputStream out, int frameBytes) { + if ((long) out.size() + Integer.BYTES + frameBytes > MAX_BYTES) { + throw new IllegalArgumentException("Selected owner intake authorization exceeds 16 MiB"); + } + } + + private static void requireActorTenantScope( + SourceEvidence source, SelectedOwnerIntakeSourceReadScope scope) { + String expected = + switch (source.kind()) { + case ACCOUNT, GLOBAL_ROLES -> scope.actorAccountId().toString(); + case TENANT -> scope.selected().target().canonicalTenantId().toString(); + case MEMBERSHIP -> + scope.actorAccountId() + "/" + scope.selected().target().canonicalTenantId(); + default -> null; + }; + if (expected != null && !expected.equals(source.scopeId())) { + throw new IllegalArgumentException("Intake source differs from actor/tenant"); + } + } + + private static String schemaFor(Owner owner) { + if (owner == Owner.ENTITY_MANAGEMENT) return "account-entity-intake-authorization/v1"; + if (owner == Owner.AUTOMATION_SCRIPTING) return "account-automation-intake-authorization/v1"; + throw new IllegalArgumentException("Unsupported selected source intake owner"); + } + + private static Owner ownerForSchema(String schema) { + if ("account-entity-intake-authorization/v1".equals(schema)) return Owner.ENTITY_MANAGEMENT; + if ("account-automation-intake-authorization/v1".equals(schema)) + return Owner.AUTOMATION_SCRIPTING; + throw new IllegalArgumentException("Unsupported selected owner intake authorization schema"); + } + + private static String purposeFor(Owner owner) { + schemaFor(owner); + return owner == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_RETENTION" + : "AUTOMATION_INTAKE_RETENTION"; + } + + private static String intendedReader(Owner owner, String namespace) { + String workload = + switch (owner) { + case ENTITY_MANAGEMENT -> "entity-management-service"; + case AUTOMATION_SCRIPTING -> "automation-scripting-service"; + default -> throw new IllegalArgumentException("Unsupported selected source intake owner"); + }; + return "spiffe://firemud/ns/" + namespace + "/sa/" + workload; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java new file mode 100644 index 0000000000..25bdbe30fd --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java @@ -0,0 +1,460 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import org.junit.jupiter.api.Test; + +/** Synthetic integrity fixtures do not establish Account authority, source census, or receipts. */ +class SelectedOwnerIntakeAuthorizationBindingTest { + private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST = id("33333333-3333-4333-8333-333333333333"); + private static final UUID COMMIT = id("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID OPERATION = id("66666666-6666-4666-8666-666666666666"); + private static final UUID FENCE = id("77777777-7777-4777-8777-777777777777"); + private static final UUID INTAKE = id("88888888-8888-4888-8888-888888888888"); + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final UUID GENESIS = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final List FAMILIES = + List.of("COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG"); + + @Test + void roundTripsBothClosedOwnerDomainsWithExactCanonicalFrameAndCompleteContent() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var content = content(owner, ACTOR); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, unsortedSources(ACTOR)); + byte[] expected = encode(binding, binding.sources()); + byte[] observed = binding.canonicalBytes(); + + assertThat(observed).isEqualTo(expected); + assertThat(binding.schema()).isEqualTo(schema(owner)); + assertThat(binding.purpose()).isEqualTo(purpose(owner)); + assertThat(binding.intendedReader()).isEqualTo(reader(owner, "test")); + assertThat(binding.digest()).isEqualTo(digest(expected)); + assertThat(binding.sources().stream().map(SourceEvidence::key)) + .containsExactly( + "ACCOUNT:" + ACTOR, "MEMBERSHIP:" + ACTOR + "/" + TENANT, "TENANT:" + TENANT); + + var restored = SelectedOwnerIntakeAuthorizationBinding.fromStored(expected); + assertThat(restored.canonicalBytes()).isEqualTo(expected); + assertThat(restored.digest()).isEqualTo(binding.digest()); + assertThat(restored.content().canonicalBytes()).isEqualTo(content.canonicalBytes()); + assertThat(restored.content().digest()).isEqualTo(content.digest()); + assertThat(restored.content().scope()).isEqualTo(content.scope()); + assertThat(restored.owner()).isEqualTo(owner); + assertThat(restored.targetNamespace()).isEqualTo("test"); + assertThat(restored.operationId()).isEqualTo(OPERATION); + assertThat(restored.fenceId()).isEqualTo(FENCE); + assertThat(restored.intakeRequestId()).isEqualTo(INTAKE); + assertThat(restored.actorAccountId()).isEqualTo(ACTOR); + assertThat(restored.selected()).isEqualTo(content.scope().selected()); + assertThat(restored.tenantId()).isEqualTo(TENANT); + assertThat(restored.versionId()).isEqualTo(VERSION); + for (String family : FAMILIES) { + assertThat(restored.content().snapshotBytes(family)) + .isEqualTo(content.snapshotBytes(family)); + } + } + } + + @Test + void preservesDefensiveCopiesOfSourceListAndCanonicalContent() { + var content = content(Owner.ENTITY_MANAGEMENT, ACTOR); + var input = new ArrayList<>(unsortedSources(ACTOR)); + var binding = new SelectedOwnerIntakeAuthorizationBinding(content, input); + byte[] expected = binding.canonicalBytes(); + byte[] exposed = binding.canonicalBytes(); + exposed[0] ^= 0x7f; + input.clear(); + byte[] exposedEvidence = binding.sources().getFirst().evidence(); + exposedEvidence[0] ^= 0x7f; + byte[] exposedContent = binding.content().canonicalBytes(); + exposedContent[0] ^= 0x7f; + + assertThat(binding.canonicalBytes()).isEqualTo(expected); + assertThat(binding.content().canonicalBytes()).isNotEqualTo(exposedContent); + assertThat(binding.sources()).hasSize(3); + assertThat(binding.sources().getFirst().evidence()).isNotEqualTo(exposedEvidence); + assertThatThrownBy(() -> binding.sources().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void rejectsChangedPurposeReaderAndContentDigests() { + var binding = + new SelectedOwnerIntakeAuthorizationBinding( + content(Owner.AUTOMATION_SCRIPTING, ACTOR), unsortedSources(ACTOR)); + byte[] encoded = binding.canonicalBytes(); + + assertInvalid( + encode( + binding, + binding.sources(), + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + "ENTITY_INTAKE_RETENTION", + "3", + null)); + assertInvalid( + encode( + binding, + binding.sources(), + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + reader(Owner.ENTITY_MANAGEMENT, "test"), + binding.purpose(), + "3", + null)); + assertInvalid( + encode( + binding, + binding.sources(), + binding.schema(), + binding.content().canonicalBytes(), + "sha256:" + "0".repeat(64), + binding.intendedReader(), + binding.purpose(), + "3", + null)); + + byte[] invalidFrame = encoded.clone(); + ByteBuffer.wrap(invalidFrame).putInt(0, Integer.MAX_VALUE); + assertInvalid(invalidFrame); + byte[] invalidUtf8 = encoded.clone(); + invalidUtf8[4] = (byte) 0xc3; + invalidUtf8[5] = 0x28; + assertInvalid(invalidUtf8); + } + + @Test + void rejectsActorMismatchAndSourceEvidenceForAnotherActorOrTenant() { + var original = + new SelectedOwnerIntakeAuthorizationBinding( + content(Owner.ENTITY_MANAGEMENT, ACTOR), unsortedSources(ACTOR)); + UUID otherActor = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"); + UUID otherTenant = id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + assertThatThrownBy( + () -> + new SelectedOwnerIntakeAuthorizationBinding( + content(Owner.ENTITY_MANAGEMENT, otherActor), unsortedSources(ACTOR))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new SelectedOwnerIntakeAuthorizationBinding( + original.content(), + List.of( + evidence(SourceKind.ACCOUNT, ACTOR.toString(), "changed"), + evidence(SourceKind.TENANT, otherTenant.toString(), "tenant")))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new SelectedOwnerIntakeAuthorizationBinding( + original.content(), + List.of( + evidence(SourceKind.ACCOUNT, otherActor.toString(), "actor"), + evidence(SourceKind.TENANT, TENANT.toString(), "tenant")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresNonemptyDistinctSourceEvidence() { + var content = content(Owner.ENTITY_MANAGEMENT, ACTOR); + SourceEvidence account = evidence(SourceKind.ACCOUNT, ACTOR.toString(), "account"); + + assertThatThrownBy(() -> new SelectedOwnerIntakeAuthorizationBinding(content, List.of())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new SelectedOwnerIntakeAuthorizationBinding(content, List.of(account, account))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsCountOrderTrailingAndUnknownSchemaChanges() { + var binding = + new SelectedOwnerIntakeAuthorizationBinding( + content(Owner.ENTITY_MANAGEMENT, ACTOR), unsortedSources(ACTOR)); + List sorted = binding.sources(); + byte[] canonical = binding.canonicalBytes(); + byte[] reversed = + encode( + binding, + reversed(sorted), + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + binding.purpose(), + "3", + null); + + assertInvalid( + encode( + binding, + sorted, + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + binding.purpose(), + "2", + null)); + assertInvalid( + encode( + binding, + sorted, + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + binding.purpose(), + "03", + null)); + assertInvalid(reversed); + assertInvalid(append(canonical, new byte[] {1})); + assertInvalid( + encode( + binding, + sorted, + "account-entity-intake-authorization/v2", + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + binding.purpose(), + "3", + null)); + assertThatThrownBy(() -> SelectedOwnerIntakeAuthorizationBinding.fromStored(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationBinding.fromStored( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void changedValidSourceEvidenceChangesDigestAndReadsBackExactly() { + var content = content(Owner.AUTOMATION_SCRIPTING, ACTOR); + var original = new SelectedOwnerIntakeAuthorizationBinding(content, unsortedSources(ACTOR)); + var changedSources = new ArrayList<>(unsortedSources(ACTOR)); + changedSources.set(0, evidence(SourceKind.TENANT, TENANT.toString(), "changed tenant source")); + var changed = new SelectedOwnerIntakeAuthorizationBinding(content, changedSources); + + assertThat(changed.digest()).isNotEqualTo(original.digest()); + assertThat( + SelectedOwnerIntakeAuthorizationBinding.fromStored(changed.canonicalBytes()) + .canonicalBytes()) + .isEqualTo(changed.canonicalBytes()); + } + + private static SelectedOwnerIntakeSourceContent content(Owner owner, UUID actor) { + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, INTAKE, actor, selected()); + byte[] bytes = encodeContent(scope, snapshots(scope.selected())); + return SelectedOwnerIntakeSourceContent.fromStored(bytes, scope, digest(bytes)); + } + + private static List unsortedSources(UUID actor) { + return List.of( + evidence(SourceKind.TENANT, TENANT.toString(), "tenant"), + evidence(SourceKind.ACCOUNT, actor.toString(), "account"), + evidence(SourceKind.MEMBERSHIP, actor + "/" + TENANT, "membership")); + } + + private static List reversed(List values) { + var reversed = new ArrayList<>(values); + java.util.Collections.reverse(reversed); + return reversed; + } + + private static SourceEvidence evidence(SourceKind kind, String scope, String value) { + return new SourceEvidence( + kind, scope, null, "1", null, null, value.getBytes(StandardCharsets.UTF_8)); + } + + private static List snapshots(DraftCommitBinding selected) { + var gameplay = + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "sourceEpoch", "0", + "inheritedCommitId", "", + "genesisReceiptId", GENESIS.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + var template = new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()); + var result = new ArrayList(); + for (String family : FAMILIES) { + byte[] bytes = + switch (family) { + case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); + case "TEMPLATE_CONFIG" -> template.canonicalBytes(); + default -> opaqueSnapshot(family, selected, "synthetic-" + family); + }; + result.add(new FamilySnapshot(family, bytes)); + } + return result; + } + + private static byte[] opaqueSnapshot(String family, DraftCommitBinding selected, String marker) { + return GameplayRuleManifest.canonical( + Map.of( + "schema", + "synthetic-test-only/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "family", + family, + "marker", + marker)) + .getBytes(StandardCharsets.UTF_8); + } + + private static byte[] encodeContent( + SelectedOwnerIntakeSourceReadScope scope, List snapshots) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (FamilySnapshot snapshot : snapshots) { + frame(out, snapshot.family()); + frame(out, snapshot.bytes()); + frame(out, digest(snapshot.bytes())); + } + return out.toByteArray(); + } + + private static byte[] encode( + SelectedOwnerIntakeAuthorizationBinding binding, List sources) { + return encode( + binding, + sources, + binding.schema(), + binding.content().canonicalBytes(), + binding.content().digest(), + binding.intendedReader(), + binding.purpose(), + Integer.toString(sources.size()), + null); + } + + private static byte[] encode( + SelectedOwnerIntakeAuthorizationBinding binding, + List sources, + String schema, + byte[] content, + String contentDigest, + String reader, + String purpose, + String count, + byte[] trailing) { + var out = new ByteArrayOutputStream(); + frame(out, schema); + frame(out, content); + frame(out, contentDigest); + frame(out, reader); + frame(out, purpose); + frame(out, count); + for (SourceEvidence source : sources) frame(out, source.canonicalBytes()); + if (trailing != null) out.writeBytes(trailing); + return out.toByteArray(); + } + + private static void assertInvalid(byte[] bytes) { + assertThatThrownBy(() -> SelectedOwnerIntakeAuthorizationBinding.fromStored(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DraftCommitBinding selected() { + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + REQUEST, + COMMIT, + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + VERSION.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static String schema(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT + ? "account-entity-intake-authorization/v1" + : "account-automation-intake-authorization/v1"; + } + + private static String purpose(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_RETENTION" + : "AUTOMATION_INTAKE_RETENTION"; + } + + private static String reader(Owner owner, String namespace) { + return "spiffe://firemud/ns/" + + namespace + + "/sa/" + + (owner == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static String digest(byte[] bytes) { + return DraftAuthorizationFenceBinding.digest(bytes); + } + + private static byte[] append(byte[] value, byte[] suffix) { + byte[] joined = Arrays.copyOf(value, value.length + suffix.length); + System.arraycopy(suffix, 0, joined, value.length, suffix.length); + return joined; + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private record FamilySnapshot(String family, byte[] bytes) {} +} From c16370dc158100da94b19619c23f7b1f05a11959 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 18:19:44 +1300 Subject: [PATCH 075/129] Fix source authorization proof and add bounded owner retention reads --- .../account-service/api-contracts.md | 4 + design/project-management/ai-observations.md | 12 + ...ame-authoring-publishing-and-activation.md | 6 +- ...cted_owner_intake_authorization_read.proto | 34 + ...nerIntakeAuthorizationReadGrpcService.java | 88 +++ ...edOwnerIntakeAuthorizationReadService.java | 75 ++ ...tartSessionAuthorityCaptureRepository.java | 79 +- ...rtSessionOperatorAuthorizationService.java | 5 +- ...cted_owner_intake_final_authorizations.sql | 8 +- ...rotectedEntryPrototypeIntegrationTest.java | 690 ++++++++++++++++++ ...uthorizationRepositoryIntegrationTest.java | 101 ++- ...ntakeAuthorizationReadGrpcServiceTest.java | 232 ++++++ ...nerIntakeAuthorizationReadServiceTest.java | 290 ++++++++ ...SessionAuthorityCaptureRepositoryTest.java | 473 ++++++++++++ ...ssionOperatorAuthorizationServiceTest.java | 39 +- ...nt-admission-protected-entry-prototype.sql | 186 +++++ ...tedOwnerIntakeAuthorizationGrpcClient.java | 155 ++++ ...tedOwnerIntakeAuthorizationReadClient.java | 7 + ...dOwnerIntakeAuthorizationReadEvidence.java | 69 ++ ...OwnerIntakeAuthorizationReadGrpcCodec.java | 104 +++ ...wnerIntakeAuthorizationGrpcClientTest.java | 87 +++ ...erIntakeAuthorizationReadEvidenceTest.java | 186 +++++ ...rIntakeAuthorizationReadGrpcCodecTest.java | 174 +++++ ...licationExportPostgresIntegrationTest.java | 14 +- 24 files changed, 3059 insertions(+), 59 deletions(-) create mode 100644 protos/account/v1/selected_owner_intake_authorization_read.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java create mode 100644 services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index c9a29b4a97..226f6cb39e 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -112,6 +112,8 @@ That scope is preliminary integrity input, not authenticated authorization, fina The distinct finalized integrity envelope uses `account-entity-intake-authorization/v1` with purpose `ENTITY_INTAKE_RETENTION` and the exact same-namespace Entity workload recipient, or `account-automation-intake-authorization/v1` with purpose `AUTOMATION_INTAKE_RETENTION` and the corresponding Automation recipient. Its canonical byte-length-framed preimage is, in order: that closed schema, the complete six-family selected-content bytes, their SHA-256 digest, the derived recipient SPIFFE URI, the closed retention purpose, a canonical decimal source count, and each complete Account source-evidence frame in sorted distinct source-key order. The content embeds the unchanged preliminary scope, so operation, fence, request, actor, namespace and selected Draft identity are reused rather than reallocated. The complete envelope is bounded to 16 MiB without changing the content's 8 MiB or preliminary scope's 4 MiB bounds. Unknown or substituted owner, reader or purpose, changed content or source scope, duplicate or noncanonical source order, malformed counts and trailing bytes deny. This value's decoder establishes integrity only; genuine Account finalization/readback and continuously held source participation, followed by the owner's own census, retention and exact terminal, establish the separate authorization and outcome. Preliminary abort cannot release a finalized operation; expiry, absence or a digest alone never settles it. +The standalone [`AccountSelectedOwnerIntakeAuthorizationReadService.ReadHeldSelectedOwnerIntakeAuthorization`](../../../../protos/account/v1/selected_owner_intake_authorization_read.proto) reads that original finalized order, not its preliminary reservation. Its closed schema-version-1 request binds namespace, an independent nonzero read correlation distinct from the retained operation/fence/intake request, the exact derived owner reader and retention purpose, and the full original binding bytes/digest. Account authenticates same-namespace Entity or Automation and rejects end-user context before decoding; after decoding, the actual peer must be that binding's exact recipient. An independent writable `READ COMMITTED` transaction locks and compares the original authorization, reservation, creator evidence and complete source participation. Success echoes the entire request unchanged with `held=true`; missing, changed, aborted, malformed, mismatched or unavailable evidence denies. The file-backed mTLS client pins Account, uses a five-second deadline, rejects ambient SQL/synchronization and enforces a separate 24 MiB wire budget without expanding the 16 MiB binding limit. This sampled HELD read cannot create/finalize/settle an order, allocate a replacement identity, renew authority or prove continuous protection through the owner's commit, complete census or a terminal receipt. The unregistered components and their proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + The distinct [`AccountSelectedOwnerIntakeSourceReadService.ReadSourceScope`](../../../../protos/account/v1/selected_owner_intake_source_read_service.proto) confirms only the retained preliminary Entity or Automation reservation. Account authenticates the exact configured same-namespace Game Design workload and rejects authenticated end-user context before decoding or storage. The closed schema-version-1 request binds namespace, independent nonzero transport correlation, derived Account reader and closed purpose, and the original scope bytes and digest. Account revalidates its own original creator and source participation in independent transactions around the external registry read; neither a client digest nor peer identity creates a reservation. A successful response echoes the complete request unchanged and confirms only that preliminary scope. Missing, expired, changed, malformed or unavailable evidence denies. The canonical scope remains bounded to 4 MiB; the separately enforced request and response wire budget is 8 MiB, including echo and framing. The file-backed mTLS client pins the Account server, applies a five-second deadline and rejects ambient SQL or synchronization. This standalone method has no finalized-retention branch, supplies no census or owner receipt, and does not register or activate a runtime path. Game Design must finish this authenticated Account confirmation outside SQL before reading or returning any selected source content. `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. @@ -193,6 +195,8 @@ These RPCs and schemas are accepted target state but are not present in the curr For StartSession, Account's existing human authorization-reference issuer remains the sole issuer and the original reference retains `targetOwner=game-session-service`. The distinct Account-owned same-namespace World receiving-participation and source-protection lifecycle is defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation); this API contract adds no replacement issuer, reference-renewal, or re-redemption path. The Game Design projection read and publication hold/settlement producers remain separate and grant no StartSession World permission. The standalone, unregistered [historical participation read](../../../../protos/account/v1/start_session_world_participation_read.proto) authenticates the exact configured same-namespace World workload and returns only the retained original identity from an independent Account transaction. Its fresh read correlation and original participation ID/fence are lookup selectors, not fresh authority; expiry or settlement cannot renew the reference, restart execution or manufacture an abort. Unregistered repository, currentness, historical-read and exact-terminal settlement components do not establish a complete genuine participation producer or World admission; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records their remaining producer, consumer and physical proof gates. +The original source capture continues to bind the exact Logging issuer identity. Account's authenticated World receiving lookup compares that retained identity and the complete original tuple/current-source capture without treating Logging as the current caller: the receiving method authenticates the exact configured same-namespace World workload and rejects end-user context. This distinct lookup cannot allocate or replace a capture, issue or redeem a reference, or skip the source, bundle, original-attempt, lease and commit-bound participation checks. Issuance and Logging-owned recovery retain their original Logging caller requirement. + Fresh World participation acquisition first obtains the [Game Session current-original-attempt observation](../../../../protos/game-session/v1/original_start_session_current_attempt_read.proto) outside Account SQL. Account compares its complete original tuple, actual owner mutation and attempt identities, fence, pending phase, unchanged finite lease expiry and exact Account-issued redemption projection; a projection hash alone is insufficient. Only then may its existing current-actor/source callback retain the participation, complete source vector and immutable original-attempt evidence in one Account transaction. Both new acquisition and exact acquisition retry recheck the original lease against the Account database clock after lock waits. A fresh read correlation is not a new durable operation, and independent lookup-only readback must preserve the first observation and exact participation. Historical expiry permits readback only, not new acquisition, renewal or restarted execution. This point-in-time observation is not continuous Game Session claim protection or World admission authority; the through-admission and owner execution proof required by ADR 0047 remains distinct. The credential-free `ReadRedeemedOperationProjection` receiver accepts the exact configured same-namespace Game Design peer and the exact original Game Session redeemer under [ADR 0047's restricted original-operation read](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). Before returning the retained projection, Account compares the original request/reservation and redeemed workload/attempt/fence, then revalidates the original actor/JTI, current source and reference expiry. The response contains no credential or renewed permission. Game Session must separately prove its original claim and immutable pin under the owner-local checks required by that contract; this Account read is not World participation or admission. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 38357597ce..6ae13e0634 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -180,3 +180,15 @@ Entry format: - Observation: Exception types and SQLSTATE alone could not distinguish several integrity checks. Guessing a cause would risk changing a valid guard, while logging full SQL exception text could disclose row or authorization data. - Expected pattern: Preserve bounded, allowlisted constraint identifiers and PL/pgSQL routine/line metadata alongside existing status, never raw messages, SQL, row values or full server context. Keep unknown root causes explicit until attributable evidence exists. - Current status: The existing publication diagnostic and focused secret-exclusion tests pass the affected full checks. Corrected PostgreSQL execution remains pending, and no publication integrity guard is changed. + +- `2026-10-10`: Cross-owner PostgreSQL fixtures must preserve the application's transaction provider + - Context: PR #3105's genuine selected-export fixture reached the real release repository but failed the deferred common-commit guard while its publication operation was still pending. + - Observation: Its jOOQ context used Spring's transaction-aware data source without Spring's transaction provider. A nested jOOQ transaction could therefore commit the bound connection after inserting the release, before the outer finalizer retained its terminal outcome. Production's auto-configuration and the existing canonical release fixture supply both components. + - Expected pattern: Construct cross-owner fixtures with the same connection and transaction providers as the owning service. Do not weaken deferred atomicity guards or mistake an unintended fixture commit for missing authorization evidence. + - Current status: The single fixture's provider wiring is corrected; physical PostgreSQL re-execution remains required. No production transaction boundary, migration or integrity guard changes. + +- `2026-10-10`: Schema generation does not establish PostgreSQL procedural parsing + - Context: PR #3105's V132 generated jOOQ metadata locally, but exact-head PostgreSQL CI rejected its complete-authorization trigger with SQLSTATE `42601` before owner assertions could run. + - Observation: Bare `CASE` expressions inside a PL/pgSQL `IF` boolean chain repeat the earlier source-guard parse hazard. A successful simulator run cannot prove that PostgreSQL accepts the procedural function or executes its constraints. + - Expected pattern: Parenthesize `CASE` expression operands in procedural conditions and retain physical Flyway startup plus positive and negative owner cases as a separate proof gate. Report startup cascades separately from actual owner assertion failures. + - Current status: The two expression operands are parenthesized without changing their mappings or rejection guards; physical PostgreSQL re-execution remains required. 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 fe00b74643..376599e0bf 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 @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Distinct Account selected-owner finalization now retains the complete six-family content, original reservation tuple, creator evidence and full held source vector in V132's append-only authorization and child rows. The unregistered producer performs the authenticated source read outside SQL, revalidates current creator/source evidence before finalization, and independently reads back the exact original result; lost acknowledgements recover the same binding without another reservation. Finalization excludes preliminary abort and source mutation, and has no expiry-based or locally invented settlement. The affected Common check passes with 551 unit cases; Account's full check and boot JAR pass with 1,256 unit cases and seven non-container integration executions, all without failures or errors. Account skips 260 container-dependent definitions, including the two new finalization PostgreSQL methods; schema generation does not prove their procedural guards. Seven new Common integrity cases and eight Account producer/repository cases pass. Content and issuer fixtures are stipulated, not genuine owner census or authenticated Entity/Automation receipts. Their HELD transport, complete owner inventories, continuously protected retention and exact authenticated terminal settlement remain open. All components remain unregistered and runtime activation remains denied. +Distinct Account selected-owner finalization retains the complete six-family content, original reservation tuple, creator evidence and full held source vector in V132's append-only authorization and child rows. The unregistered producer reads authenticated source outside SQL, revalidates creator/source evidence before finalization, and reads back the exact original result; lost acknowledgements recover the same binding without another reservation. Finalization excludes preliminary abort and source mutation, with no expiry-based settlement. The separate unregistered HELD transport authenticates the exact same-namespace Entity or Automation recipient before decoding, validates the complete unchanged binding/echo, and reads it in an independent writable read-committed Account transaction. Its sample is not continuous protection: the durable source-participation writer exclusion remains pending until a future exact owner-terminal settlement, which is not implemented. Complete owner inventories and authenticated Entity/Automation receipts remain open; stipulated content and issuer fixtures do not prove them. + +The source-repair and transport batch passes the affected Common/Account/Game Design full checks, Account schema generation, affected boot JARs, formatting, static checks, links and Markdown in 2m57s. XML records 560 Common, 1,270 Account and 551 Game Design unit cases, all without failures, errors or skips; successful unchanged tasks retain results. Account executes seven non-container integration cases and skips 270; Game Design skips all 148 without Docker. All ten isolated protected-entry PostgreSQL prototype cases compile and skip: this is test-only durability feasibility, not a production writer grant, original-COMMIT proof or adoption. Quiet cold/warm success, privilege/forgery denial, snapshot ordering, concurrent original/receipt visibility, lock-wait expiry and exact lost-response recovery require physical execution. Guaranteed catalog-PRUNE provenance and visible-but-unflushed asynchronous original COMMIT are not established by these definitions. The bounded World capture lookup distinguishes the authenticated World reader from its retained original Logging issuer without relaxing Logging issuance/recovery guards. Game Design's genuine release fixture now uses Spring's transaction provider so nested repository work does not prematurely commit its outer publication. PostgreSQL re-execution of both corrections remains required. All new components remain unregistered and activation remains denied. + +Exact source `d63a9f0fad74dea824ecb811e26137b246734360` [Validation run 38025424129](https://github.com/benhook1013/FireMUD/actions/runs/38025424129) fails the required gate. Originating Account XML reports 266 cases, 228 failures, zero errors and zero skips; both V132 finalization cases and all three V131 observation cases fail before owner assertions because PostgreSQL rejects V132's complete-authorization function with SQLSTATE `42601` at its definition on line 108. The separate Draft-fence verifier reports 31/31 failures from the same startup problem. Game Design's job log reports 151 cases with 15 failures; its originating XML was not retained locally. Game Session's job passes. The bounded repair parenthesizes the reader/purpose `CASE` operands without changing guard mappings; simulator success is not physical parsing proof. The tested merge is `642b461e25bf60c4f342f9c18fa419eaddb6285c`, tree `bb8954e8ac5cfed4857c176f2f11a37b8e9afc2a`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source; that base is not the recorded integration parent. The later duplicate run is not additional proof. The earlier executed failures below remain historical evidence, not corrected-head proof. Exact source `695dc8ee2daaba5180d0975f07d25adf04e9b7b6` [Validation run 38023005491](https://github.com/benhook1013/FireMUD/actions/runs/38023005491) fails the required Validation Gate. Originating XML establishes 273 Account integration executions with nine failures: six admission-confirmation failures, two exception-type assertions where PostgreSQL correctly denies immutable-evidence updates, and one original source-capture/currentness denial. The three V131 original-attempt observation cases pass, including unchanged first-response retention and database-clock expiry after lock waits; these use stipulated Game Session evidence, not continuous cross-owner claim protection. Separate Account draft-fence PostgreSQL proof passes 31 cases. Game Design executes 151 integration cases with one release-finalization denial (`23514`, `verify_publication_operation_commit`, line 19); no constraint identifier is reported. World executes 221 with none, all without skips. Logging's job passes, but its XML capture skips, so this run does not establish the specific CA-rejection case's execution. The tested merge is `6253d6a060e75dcfa3190a925cdc743afefc29a7`, tree `ff827c27b11f6a9bb6d5ca277b894c96eaf1eacb`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source. License, Security and CodeQL pass. The later metadata-only run supplies no source proof; the older fourteen-failure report below is historical, not the current result. diff --git a/protos/account/v1/selected_owner_intake_authorization_read.proto b/protos/account/v1/selected_owner_intake_authorization_read.proto new file mode 100644 index 0000000000..5a9da9e5fc --- /dev/null +++ b/protos/account/v1/selected_owner_intake_authorization_read.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone read of a distinct finalized Entity or Automation intake authorization. This method +// samples that the exact Account authorization and source participation remain held at read time; +// it does not prove continuous commit protection, owner inventory, or terminal settlement. +service AccountSelectedOwnerIntakeAuthorizationReadService { + rpc ReadHeldSelectedOwnerIntakeAuthorization( + ReadHeldSelectedOwnerIntakeAuthorizationRequest) + returns (ReadHeldSelectedOwnerIntakeAuthorizationResponse); +} + +message ReadHeldSelectedOwnerIntakeAuthorizationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Derived from the closed Entity or Automation owner in the complete original binding. + string intended_reader = 4; + // ENTITY_INTAKE_RETENTION or AUTOMATION_INTAKE_RETENTION, derived from that same owner. + string retention_purpose = 5; + // Complete canonical SelectedOwnerIntakeAuthorizationBinding bytes and their SHA-256 digest. + bytes original_intake_authorization_binding = 6; + string intake_authorization_digest = 7; +} + +message ReadHeldSelectedOwnerIntakeAuthorizationResponse { + // Echo the complete request tuple unchanged. Only held=true is a successful result. + ReadHeldSelectedOwnerIntakeAuthorizationRequest request = 1; + bool held = 2; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcService.java new file mode 100644 index 0000000000..e6c722e107 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcService.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Standalone receiver: authenticate the exact owner workload before parsing or looking up data. */ +public final class AccountSelectedOwnerIntakeAuthorizationReadGrpcService + extends AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationReadServiceImplBase { + private final AccountSelectedOwnerIntakeAuthorizationReadService owner; + private final String namespace; + + public AccountSelectedOwnerIntakeAuthorizationReadGrpcService( + AccountSelectedOwnerIntakeAuthorizationReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-owner authorization reader is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readHeldSelectedOwnerIntakeAuthorization( + ReadHeldSelectedOwnerIntakeAuthorizationRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + String peerUri = peer.uri(); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !(peerUri.equals("spiffe://firemud/ns/" + namespace + "/sa/entity-management-service") + || peerUri.equals( + "spiffe://firemud/ns/" + namespace + "/sa/automation-scripting-service"))) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() + > SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + final SelectedOwnerIntakeAuthorizationReadEvidence.Request decoded; + try { + decoded = SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(decoded.targetNamespace()) || !peerUri.equals(decoded.intendedReader())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + try { + owner.requireHeld(decoded); + observer.onNext(SelectedOwnerIntakeAuthorizationReadGrpcCodec.toHeldResponse(decoded)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + observer.onError(Status.fromCode(code).asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java new file mode 100644 index 0000000000..50bb396a07 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java @@ -0,0 +1,75 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered exact held-retention read; it neither creates authority nor settles participation. + */ +public final class AccountSelectedOwnerIntakeAuthorizationReadService { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final TransactionTemplate ownerTransaction; + private final String namespace; + + public AccountSelectedOwnerIntakeAuthorizationReadService( + AccountSelectedOwnerIntakeSourceReservationRepository repository, + PlatformTransactionManager transactions, + String namespace) { + this.repository = + Objects.requireNonNull(repository, "source reservation repository is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** Confirms the exact finalized authorization and source locks in an independent transaction. */ + public void requireHeld(SelectedOwnerIntakeAuthorizationReadEvidence.Request request) { + Objects.requireNonNull(request, "authorization-read request is required"); + requirePeer(namespace, request.intendedReader()); + if (!namespace.equals(request.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + try { + ownerTransaction.execute( + ignored -> { + repository.readFinalAuthorization(request.binding()); + return null; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (IllegalArgumentException changedOrAbsent) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } + } + + static void requirePeer(String namespace, String expectedReader) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !peer.uri().equals(expectedReader) + || !(expectedReader.equals( + "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service") + || expectedReader.equals( + "spiffe://firemud/ns/" + namespace + "/sa/automation-scripting-service"))) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java index 37022fd39c..e20c425eb4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -95,11 +96,50 @@ public AccountStartSessionAuthorityCapture lockReadExactCurrent( String loggingWorkloadUri, UUID reservationOwnerId, long reservationClaimFence) { + return lockReadExactCurrent( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence, true); + } + + /** + * Locks and reads the original capture for the authenticated same-namespace World receiver. The + * original Logging identity is checked as retained issuance evidence; it is not the current + * caller on this receiver path. + */ + public AccountStartSessionAuthorityCapture lockReadExactCurrentFromWorldReceiving( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + String worldManagementWorkloadUri) { + requireOwnerTransaction(); + Objects.requireNonNull(current, "current committed ControlUI actor is required"); + Objects.requireNonNull(tuple, "exact typed StartSession tuple is required"); + if (!canonicalWorldWorkload( + worldManagementWorkloadUri, tuple.action().scope().targetNamespace())) { + throw unavailable(); + } + return lockReadExactCurrent( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence, false); + } + + private AccountStartSessionAuthorityCapture lockReadExactCurrent( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + boolean requireLoggingPeer) { requireOwnerTransaction(); Objects.requireNonNull(current, "current committed ControlUI actor is required"); RequestSnapshot observed = requestSnapshot( - current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence); + current, + tuple, + loggingWorkloadUri, + reservationOwnerId, + reservationClaimFence, + requireLoggingPeer); Record row = lockByRequestId(observed.requestId()); if (row == null) throw unavailable(); AccountStartSessionAuthorityCapture stored = decode(row); @@ -302,6 +342,17 @@ private static RequestSnapshot requestSnapshot( String loggingWorkloadUri, UUID reservationOwnerId, long reservationClaimFence) { + return requestSnapshot( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence, true); + } + + private static RequestSnapshot requestSnapshot( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + boolean requireLoggingPeer) { Objects.requireNonNull(tuple, "exact typed StartSession tuple is required"); Objects.requireNonNull(current.stored(), "original committed ControlUI issuance is required"); Snapshot source = @@ -315,7 +366,10 @@ private static RequestSnapshot requestSnapshot( || !"game-session-service".equals(tuple.targetOwner()) || !"COMMITTED".equals(stored.status) || !canonicalTuple(tupleBytes, tuple) - || !canonicalLoggingWorkload(loggingWorkloadUri, tuple.action().scope().targetNamespace()) + || !(requireLoggingPeer + ? canonicalLoggingWorkload(loggingWorkloadUri, tuple.action().scope().targetNamespace()) + : canonicalLoggingWorkloadUri( + loggingWorkloadUri, tuple.action().scope().targetNamespace())) || reservationOwnerId == null || reservationOwnerId.equals(new UUID(0L, 0L)) || reservationClaimFence <= 0L @@ -427,9 +481,7 @@ private static boolean canonicalTuple( } private static boolean canonicalLoggingWorkload(String uri, String targetNamespace) { - if (uri == null) return false; - var match = LOGGING_WORKLOAD.matcher(uri); - if (!match.matches() || !match.group(1).equals(targetNamespace)) return false; + if (!canonicalLoggingWorkloadUri(uri, targetNamespace)) return false; GrpcPeerIdentity peer = GrpcPeerIdentity.current(); return peer != null && uri.equals(peer.uri()) @@ -437,6 +489,23 @@ private static boolean canonicalLoggingWorkload(String uri, String targetNamespa && targetNamespace.equals(peer.namespace()); } + private static boolean canonicalLoggingWorkloadUri(String uri, String targetNamespace) { + if (uri == null) return false; + var match = LOGGING_WORKLOAD.matcher(uri); + return match.matches() && match.group(1).equals(targetNamespace); + } + + private static boolean canonicalWorldWorkload(String uri, String targetNamespace) { + String expectedUri = "spiffe://firemud/ns/" + targetNamespace + "/sa/world-management-service"; + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return !SessionContext.hasAuthenticatedCallerContext() + && expectedUri.equals(uri) + && peer != null + && uri.equals(peer.uri()) + && "world-management-service".equals(peer.service()) + && targetNamespace.equals(peer.namespace()); + } + private static Map parseObject(byte[] bytes) { try { Object value = diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java index 0f1e39490e..4e7f96d4af 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java @@ -743,12 +743,13 @@ T withCurrentWorldReceivingParticipationCurrentness( exact, tuple, redemptionRequest, exactBundle, clock.instant()); AccountStartSessionAuthorityCapture lockedCapture = - captureRepository.lockReadExactCurrent( + captureRepository.lockReadExactCurrentFromWorldReceiving( current, tuple, loggingPeerUri, postTuple.reservationOwnerId(), - postTuple.reservationClaimFence()); + postTuple.reservationClaimFence(), + worldManagementPeerUri); var originalReference = AccountStartSessionOperatorAuthorityBundle.fromSharedReference( exact.bundleReference()); diff --git a/services/account-service/src/main/resources/db/migration/V132__selected_owner_intake_final_authorizations.sql b/services/account-service/src/main/resources/db/migration/V132__selected_owner_intake_final_authorizations.sql index d727c03aca..ea9db5125a 100644 --- a/services/account-service/src/main/resources/db/migration/V132__selected_owner_intake_final_authorizations.sql +++ b/services/account-service/src/main/resources/db/migration/V132__selected_owner_intake_final_authorizations.sql @@ -322,12 +322,12 @@ BEGIN FROM account_publication_authorization_read_frame(NEW.binding_bytes, p); IF binding_schema IS DISTINCT FROM expected_binding_schema OR recipient_value IS DISTINCT FROM - CASE scope_owner WHEN 'ENTITY_MANAGEMENT' + (CASE scope_owner WHEN 'ENTITY_MANAGEMENT' THEN 'spiffe://firemud/ns/' || namespace_value || '/sa/entity-management-service' - ELSE 'spiffe://firemud/ns/' || namespace_value || '/sa/automation-scripting-service' END + ELSE 'spiffe://firemud/ns/' || namespace_value || '/sa/automation-scripting-service' END) OR purpose_value IS DISTINCT FROM - CASE scope_owner WHEN 'ENTITY_MANAGEMENT' THEN 'ENTITY_INTAKE_RETENTION' - ELSE 'AUTOMATION_INTAKE_RETENTION' END + (CASE scope_owner WHEN 'ENTITY_MANAGEMENT' THEN 'ENTITY_INTAKE_RETENTION' + ELSE 'AUTOMATION_INTAKE_RETENTION' END) OR count_text !~ '^[1-9][0-9]*$' THEN RAISE EXCEPTION 'Finalized authorization schema, reader, purpose, or source count is invalid' USING ERRCODE = '23514'; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java new file mode 100644 index 0000000000..568638759f --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -0,0 +1,690 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.JSONB; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Test-only protected-entry feasibility, never production privilege adoption or admission proof. + * + *

The original operation is finalized in unchanged Flyway storage. Upstream carrier fields are + * shape fixtures only. Quiet cold/warm successes are requirements, not assumptions: catalog WAL + * preventing coverage fails visibly without a marker, forced flush, retry warming or deadline + * extension. Async-original unflushed-COMMIT and guaranteed catalog-PRUNE provenance are not + * claimed by this fixture; establishing those exact conditions needs separate physical evidence. + */ +@Testcontainers(disabledWithoutDocker = true) +@Execution(ExecutionMode.SAME_THREAD) +class AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest { + // Never consumes the shared fixture's external database override. + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>("postgres:16-alpine") + .withCommand("postgres", "-c", "fsync=on", "-c", "synchronous_commit=on"); + + private static final String TENANT = "22222222-2222-4222-8222-222222222222"; + private static final String OTHER = "33333333-3333-4333-8333-333333333333"; + + @Test + void coldQuietEntryProvesExactOriginalThenIndependentReceiptWithoutAuxiliaryWrites() + throws Exception { + var context = context(); + var original = finalized(context, 15000); + JSONB created = call(context, original, "confirm"); + assertProof(context, original, created); + assertThat(call(context, original, "read_receipt")).isEqualTo(created); + assertProductionReceiptTablesEmpty(context); + } + + @Test + void warmedEntryStillRequiresQuietCoverageAndLostResponseRecoveryPreservesExpiry() + throws Exception { + var context = context(); + // Warm entry/catalog resolution on the SAME backend before original finalization. The + // missing-operation branch does not claim to warm every lazily planned PL/pgSQL statement. + try (var warm = context.caller().getConnection()) { + warm.setAutoCommit(false); + warm.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + assertThatThrownBy( + () -> + invoke( + warm, + context, + "confirm", + UUID.randomUUID(), + "a".repeat(64), + UUID.randomUUID())) + .hasMessageContaining("prototype exact original required"); + warm.rollback(); + var original = finalized(context, 1500); + JSONB discardedResponse = + invoke( + warm, + context, + "confirm", + request(original), + original.evidence().sha256(), + original.decision()); + warm.commit(); + waitPastExpiry(context, original); + assertThat(call(context, original, "read_receipt")).isEqualTo(discardedResponse); + assertThat(call(context, original, "confirm")).isEqualTo(discardedResponse); + assertProof(context, original, discardedResponse); + } + } + + @Test + void callerCannotForgeCaptureWriteTablesInvokePrivateWriterOrEscalate() throws Exception { + var context = context(); + var original = finalized(context, 15000); + List denied = + List.of( + "INSERT INTO " + + context.proofSchema() + + ".receipts(request_id) VALUES ('" + + request(original) + + "')", + "UPDATE " + context.proofSchema() + ".receipts SET committed_before_ms = 1", + "DELETE FROM " + context.proofSchema() + ".receipts", + "TRUNCATE " + context.proofSchema() + ".receipts", + "SELECT " + + context.proofSchema() + + ".write_receipt(NULL::" + + context.proofSchema() + + ".receipts)", + "SELECT " + context.proofSchema() + ".immutable()", + "SET ROLE " + context.proofSchema() + "_owner", + "ALTER FUNCTION " + context.proofSchema() + ".confirm(uuid,text,uuid) RESET ALL", + "ALTER TABLE " + context.proofSchema() + ".receipts DISABLE TRIGGER ALL", + "CREATE TABLE " + context.proofSchema() + ".shadow(id integer)", + "SET session_replication_role = replica", + "SELECT " + + context.proofSchema() + + ".confirm('" + + request(original) + + "'::uuid, '" + + original.evidence().sha256() + + "', '" + + original.decision() + + "'::uuid, '0/1'::pg_lsn)"); + for (String sql : denied) { + assertThatThrownBy( + () -> + callerTransaction( + context, + connection -> { + try (var statement = connection.createStatement()) { + return statement.execute(sql); + } + })) + .as(sql) + .isInstanceOf(SQLException.class) + .satisfies( + failure -> + assertThat(sqlState(failure)) + .isEqualTo(sql.endsWith("'0/1'::pg_lsn)") ? "42883" : "42501")); + } + // A hostile session search path cannot replace fully qualified owner objects. + JSONB created = + callerTransaction( + context, + connection -> { + DSL.using(connection).execute("SET LOCAL search_path = pg_temp, public"); + return invoke( + connection, + context, + "confirm", + request(original), + original.evidence().sha256(), + original.decision()); + }); + assertProof(context, original, created); + assertThat(call(context, original, "read_receipt")).isEqualTo(created); + } + + @Test + void ownFinalizationAndReleasedSubtransactionCannotSupplyIndependentOriginal() { + for (boolean subtransaction : List.of(false, true)) { + var context = context(); + var evidence = pending(context, 15000); + UUID decision = UUID.randomUUID(); + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> { + if (subtransaction) + context.dsl().execute("SAVEPOINT original_finalization"); + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordCommitted(evidence, decision); + if (subtransaction) + context.dsl().execute("RELEASE SAVEPOINT original_finalization"); + context + .dsl() + .fetchSingle( + "SELECT " + context.proofSchema() + ".confirm(?, ?, ?)", + request(evidence), + evidence.sha256(), + decision); + })) + .hasMessageContaining("prototype independent original required"); + assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isZero(); + } + } + + @Test + void receiptCreatedInCurrentTransactionIsNotIndependentRecovery() throws Exception { + var context = context(); + var original = finalized(context, 15000); + assertThatThrownBy( + () -> + callerTransaction( + context, + connection -> { + invoke( + connection, + context, + "confirm", + request(original), + original.evidence().sha256(), + original.decision()); + return invoke( + connection, + context, + "read_receipt", + request(original), + original.evidence().sha256(), + original.decision()); + })) + .hasMessageContaining("prototype independent receipt required"); + assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isZero(); + } + + @Test + void lateAndChangedOriginalDenyWithoutReceiptOrDeadlineMutation() throws Exception { + var context = context(); + var original = finalized(context, 1200); + assertThatThrownBy( + () -> + callerTransaction( + context, + connection -> + invoke( + connection, + context, + "confirm", + request(original), + "b".repeat(64), + original.decision()))) + .hasMessageContaining("prototype exact original required"); + assertThatThrownBy( + () -> + callerTransaction( + context, + connection -> + invoke( + connection, + context, + "confirm", + request(original), + original.evidence().sha256(), + UUID.randomUUID()))) + .hasMessageContaining("prototype exact original required"); + waitPastExpiry(context, original); + assertThatThrownBy(() -> call(context, original, "confirm")) + .hasMessageContaining("prototype unchanged deadline expired"); + assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isZero(); + assertThat( + context + .dsl() + .fetchSingle( + "SELECT expires_at_ms FROM account_gameplay_admission_lease_operations WHERE request_id = ?", + request(original)) + .get(0, Long.class)) + .isEqualTo(expiry(original)); + } + + @Test + void staleSerializableCreatorMustRetryAndRecoverOneExactWinner() throws Exception { + var context = context(); + var original = finalized(context, 15000); + try (var stale = context.caller().getConnection()) { + stale.setAutoCommit(false); + stale.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + DSL.using(stale).fetchSingle("SELECT pg_current_snapshot()"); + JSONB winner = call(context, original, "confirm"); + assertThatThrownBy( + () -> + invoke( + stale, + context, + "confirm", + request(original), + original.evidence().sha256(), + original.decision())) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("40001")); + stale.rollback(); + assertThat(call(context, original, "read_receipt")).isEqualTo(winner); + assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isOne(); + } + } + + @Test + void snapshotBeforeIndependentFinalizationCannotSeeItsLaterCommit() throws Exception { + var context = context(); + var evidence = pending(context, 15000); + UUID decision = UUID.randomUUID(); + try (var stale = context.caller().getConnection()) { + stale.setAutoCommit(false); + stale.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + DSL.using(stale).fetchSingle("SELECT pg_current_snapshot()"); + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(evidence, decision); + assertThatThrownBy( + () -> + invoke(stale, context, "confirm", request(evidence), evidence.sha256(), decision)) + .hasMessageContaining("prototype exact original required"); + stale.rollback(); + } + assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isZero(); + } + + @Test + void lockWaitPastOriginalExpiryDeniesWithoutReceipt() throws Exception { + var context = context(); + var original = finalized(context, 1800); + try (var lock = context.admin().getConnection(); + var executor = Executors.newSingleThreadExecutor()) { + lock.setAutoCommit(false); + UUID account = + DSL.using(lock) + .fetchSingle( + "SELECT account_uuid FROM account_gameplay_admission_lease_operations WHERE request_id = ?", + request(original)) + .get(0, UUID.class); + DSL.using(lock) + .fetchSingle( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", account); + var entered = new CountDownLatch(1); + var pid = new AtomicInteger(); + var attempt = + executor.submit( + () -> + callerTransaction( + context, + connection -> { + pid.set( + DSL.using(connection) + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class)); + entered.countDown(); + return invoke( + connection, + context, + "confirm", + request(original), + original.evidence().sha256(), + original.decision()); + })); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + // Establish actual lock waiting, rather than assuming a thread-start latch proves it. + boolean waiting = false; + long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!waiting && System.nanoTime() < until) { + waiting = + Boolean.TRUE.equals( + context + .dsl() + .fetchSingle( + "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE pid = ? AND wait_event_type = 'Lock')", + pid.get()) + .get(0, Boolean.class)); + if (!waiting) Thread.sleep(10); + } + assertThat(waiting).isTrue(); + waitPastExpiry(context, original); + lock.rollback(); + assertThatThrownBy(() -> attempt.get(5, TimeUnit.SECONDS)) + .satisfies( + failure -> { + assertThat(sqlState(failure)).isEqualTo("23514"); + assertThat(failure.getCause()) + .hasMessageContaining("prototype unchanged deadline expired"); + }); + } + assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isZero(); + } + + @Test + void catalogChurnBeforeFinalizationDoesNotPermitWarmingAwayColdCoverageFailure() + throws Exception { + var context = context(); + // Real catalog churn creates dead catalog tuples. It does not prove PostgreSQL will prune a + // specific pg_class/pg_attribute page at function entry; exact PRUNE coverage remains unproved. + for (int index = 0; index < 30; index++) { + context + .dsl() + .execute("CREATE TABLE prototype_catalog_" + index + "(id integer, payload text)"); + context.dsl().execute("DROP TABLE prototype_catalog_" + index); + } + var original = finalized(context, 15000); + JSONB created = call(context, original, "confirm"); + assertProof(context, original, created); + assertThat(call(context, original, "read_receipt")).isEqualTo(created); + } + + private static Context context() { + String schema = "protected_" + UUID.randomUUID().toString().replace("-", ""); + String proof = schema + "_proof"; + var admin = source(schema, POSTGRES.getUsername(), POSTGRES.getPassword()); + Flyway.configure() + .dataSource(admin) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(admin)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(admin), SQLDialect.POSTGRES); + try (var resource = + Objects.requireNonNull( + AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.class + .getResourceAsStream("/account-admission-protected-entry-prototype.sql"))) { + dsl.execute( + new String(resource.readAllBytes(), StandardCharsets.UTF_8) + .replace("__S__", schema) + .replace("__P__", proof)); + } catch (IOException failure) { + throw new IllegalStateException("Test-only protected entry fixture unavailable", failure); + } + assertThat( + dsl.fetchSingle("SELECT current_setting('server_version_num')::integer") + .get(0, Integer.class)) + .isBetween(160000, 169999); + return new Context( + proof, admin, source(null, proof + "_caller", "isolated-prototype-only"), dsl, transaction); + } + + private static DriverManagerDataSource source(String schema, String username, String password) { + var source = new DriverManagerDataSource(); + source.setUrl( + POSTGRES.getJdbcUrl() + + (schema == null + ? "" + : (POSTGRES.getJdbcUrl().contains("?") ? "&" : "?") + "currentSchema=" + schema)); + source.setUsername(username); + source.setPassword(password); + return source; + } + + private static Original finalized(Context context, long lifetime) { + var evidence = pending(context, lifetime); + UUID decision = UUID.randomUUID(); + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()).execute(evidence, decision); + return new Original(evidence, decision); + } + + private static AccountGameplayAdmissionLeaseEvidence pending(Context context, long lifetime) { + return context + .transaction() + .execute( + status -> { + var authorities = new AccountAuthorityGenerationRepository(context.dsl()); + var sources = + new AccountAuthoritySourceEvidenceRepository( + context.dsl(), + authorities, + new AccountAuthorityOutboxRepository(context.dsl())); + sources.initializeIssuerIfAbsent("firemud-account-service"); + var account = new Account(); + account.setUsername("protected-" + UUID.randomUUID()); + account.setEmail(UUID.randomUUID() + "@example.test"); + account.setPasswordHash("shape-fixture-only"); + account.setLoginAuthModes("PASSWORD"); + UUID accountId = + new AccountRepository(context.dsl(), sources).save(account).getAccountUuid(); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var allocation = repository.allocate(accountId, UUID.randomUUID(), UUID.randomUUID()); + var evidence = evidence(allocation, lifetime); + repository.beginPending(evidence); + return evidence; + }); + } + + private static AccountGameplayAdmissionLeaseEvidence evidence( + AccountGameplayAdmissionLeaseRepository.Allocation allocation, long lifetime) { + long now = Instant.now().toEpochMilli(); + String account = allocation.accountId().toString(); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", "test"); + carrier.put("callerWorkload", "spiffe://firemud/ns/test/sa/game-session-service"); + carrier.put("requestId", allocation.requestId().toString()); + carrier.put("leaseId", allocation.leaseId().toString()); + carrier.put("leaseFence", Long.toString(allocation.leaseFence())); + carrier.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + for (String key : + List.of( + "realmId", + "playableStateNamespaceId", + "gameInstanceId", + "characterId", + "sessionId", + "regionId")) scope.put(key, OTHER); + scope.put("accountId", account); + scope.put("tenantId", TENANT); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateScope", "SHARED"); + for (String key : + List.of("bindingGeneration", "catalogRevision", "pointerVersion", "regionEpoch")) + scope.put(key, "1"); + carrier.put("bindingScope", scope); + carrier.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + Map.of(TENANT, "1"), + "privateRealmGrantVersions", + List.of())); + carrier.put("issuanceFence", "7"); + carrier.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(TENANT, "1"), + "membershipAuthorityGeneration", + "1")); + carrier.put( + "outboxCheckpoints", + List.of( + "account/" + account, + "issuer/firemud-account-service", + "membership/" + account + "/" + TENANT, + "tenant/" + TENANT) + .stream() + .map( + suffix -> + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + "1")) + .toList()); + Map token = new LinkedHashMap<>(); + token.put("accountId", account); + for (String key : List.of("operationId", "issuanceRequestId", "tokenJti")) + token.put(key, OTHER); + token.put("tokenSHA256", "a".repeat(64)); + token.put("tokenProfile", "game-session-account-delegation"); + token.put("tokenGeneration", "1"); + token.put("issuanceFence", "7"); + token.put("tokenIdentityFence", "9"); + token.put("issuedAt", Long.toString(now / 1000 - 1)); + token.put("notBefore", Long.toString(now / 1000 - 1)); + token.put("expiresAt", Long.toString(now / 1000 + 300)); + carrier.put("tokenIdentityEvidence", token); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put("expiresAt", Long.toString(now + lifetime)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private static JSONB call(Context context, Original original, String entry) throws SQLException { + return callerTransaction( + context, + connection -> + invoke( + connection, + context, + entry, + request(original), + original.evidence().sha256(), + original.decision())); + } + + private static JSONB invoke( + Connection connection, Context context, String entry, UUID request, String sha, UUID decision) + throws SQLException { + try (var statement = + connection.prepareStatement( + "SELECT " + context.proofSchema() + "." + entry + "(?, ?, ?)")) { + statement.setObject(1, request); + statement.setString(2, sha); + statement.setObject(3, decision); + try (var result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + JSONB receipt = JSONB.valueOf(result.getString(1)); + assertThat(result.next()).isFalse(); + return receipt; + } + } + } + + private static T callerTransaction(Context context, SqlAction action) throws SQLException { + try (var connection = context.caller().getConnection()) { + connection.setAutoCommit(false); + connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + try { + T result = action.execute(connection); + connection.commit(); + return result; + } catch (Exception failure) { + connection.rollback(); + if (failure instanceof SQLException sql) throw sql; + if (failure instanceof RuntimeException runtime) throw runtime; + throw new IllegalStateException(failure); + } + } + } + + private static void assertProof(Context context, Original original, JSONB receipt) { + assertThat( + context + .dsl() + .fetchSingle( + "SELECT (r.original_operation = to_jsonb(o)) AND r.finalization_xid = o.finalization_xid AND r.confirmation_xid <> o.finalization_xid AND pg_visible_in_snapshot(o.finalization_xid::xid8, r.snapshot::pg_snapshot) AND r.flush_lsn >= r.insert_lsn AND r.committed_before_ms < o.expires_at_ms AND r.expires_at_ms = o.expires_at_ms AND to_jsonb(r) = ?::jsonb FROM " + + context.proofSchema() + + ".receipts r JOIN account_gameplay_admission_lease_operations o USING(request_id) WHERE r.request_id = ?", + receipt.data(), + request(original)) + .get(0, Boolean.class)) + .isTrue(); + } + + private static void assertProductionReceiptTablesEmpty(Context context) { + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); + assertThat( + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) + .isZero(); + } + + private static void waitPastExpiry(Context context, Original original) { + context + .dsl() + .fetchSingle( + "SELECT pg_sleep(GREATEST(0, (? - ceil(extract(epoch FROM clock_timestamp()) * 1000) + 50) / 1000.0))", + expiry(original)); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) + if (cause instanceof SQLException sql) return sql.getSQLState(); + return null; + } + + private static UUID request(Original original) { + return request(original.evidence()); + } + + private static UUID request(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString((String) evidence.carrier().get("requestId")); + } + + private static long expiry(Original original) { + return Long.parseLong((String) original.evidence().carrier().get("expiresAt")); + } + + @FunctionalInterface + private interface SqlAction { + T execute(Connection connection) throws SQLException; + } + + private record Original(AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) {} + + private record Context( + String proofSchema, + DriverManagerDataSource admin, + DriverManagerDataSource caller, + DSLContext dsl, + TransactionTemplate transaction) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java index 82c3948816..7a6e366392 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; +import java.sql.SQLException; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -27,15 +28,16 @@ import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; +import org.jooq.exception.IntegrityConstraintViolationException; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -107,16 +109,16 @@ void realPostgresCreateRetryAndRedemptionRetainTheOriginalAuthorityRecord() { () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); assertThat(retainedAfterRedemption.bundleReference()).isEqualTo(candidate.bundleReference()); assertThat(retainedAfterRedemption.bundleReference().linearization()).isEqualTo("123456789"); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "UPDATE account_start_session_operator_authorizations " - + "SET bundle_linearization = ? WHERE control_plane_request_id = ?", - "123456788", - REQUEST_ID))) - .isInstanceOf(DataAccessException.class); + assertImmutableGuardRejected( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET bundle_linearization = ? WHERE control_plane_request_id = ?", + "123456788", + REQUEST_ID)), + "StartSession authorization evidence is immutable except one exact redemption"); assertThat( context.inTransaction( () -> @@ -442,32 +444,32 @@ void expiredReferenceCannotBeConsumedAndSqlGuardsRetainEvidence() { .isInstanceOf( AccountStartSessionOperatorAuthorizationRepository.ReferenceExpiredException.class); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "UPDATE account_start_session_operator_authorizations " - + "SET authority_evidence_bundle = ? WHERE control_plane_request_id = ?", - bytes("rewritten"), - REQUEST_ID))) - .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "DELETE FROM account_start_session_operator_authorizations " - + "WHERE control_plane_request_id = ?", - REQUEST_ID))) - .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "TRUNCATE account_start_session_operator_authorizations"))) - .isInstanceOf(DataAccessException.class); + assertImmutableGuardRejected( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET authority_evidence_bundle = ? WHERE control_plane_request_id = ?", + bytes("rewritten"), + REQUEST_ID)), + "StartSession authorization evidence is immutable except one exact redemption"); + assertImmutableGuardRejected( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "DELETE FROM account_start_session_operator_authorizations " + + "WHERE control_plane_request_id = ?", + REQUEST_ID)), + "StartSession operator authorization evidence cannot be deleted"); + assertImmutableGuardRejected( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "TRUNCATE account_start_session_operator_authorizations")), + "StartSession operator authorization evidence cannot be truncated"); var retained = context.inTransaction( @@ -767,6 +769,31 @@ private static byte[] authorityBundle( return AccountControlUiAuthority.canonical(bundle); } + private static void assertImmutableGuardRejected( + ThrowingCallable action, String expectedDiagnostic) { + assertThatThrownBy(action) + .isInstanceOf(IntegrityConstraintViolationException.class) + .satisfies( + failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Immutable guard rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); + } + + private static SQLException findSqlException(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlFailure) return sqlFailure; + } + throw new AssertionError("Immutable guard rejection did not retain its SQLException", failure); + } + private static final UUID TENANT_ID = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); private static final UUID TARGET_ACCOUNT_ID = UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java new file mode 100644 index 0000000000..9603c2eaf1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java @@ -0,0 +1,232 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** Synthetic handler tests only; they do not establish mTLS or PostgreSQL owner proof. */ +class AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest { + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void authenticatesOwnerAndRejectsEndUserBeforeParsingOrOwnerAccess() { + var owner = mock(AccountSelectedOwnerIntakeAuthorizationReadService.class); + var service = new AccountSelectedOwnerIntakeAuthorizationReadGrpcService(owner, "test"); + var malformed = + ReadHeldSelectedOwnerIntakeAuthorizationRequest.newBuilder() + .setTargetNamespace("test") + .setSchemaVersion(-1) + .build(); + + var noPeer = new Collector(); + service.readHeldSelectedOwnerIntakeAuthorization(malformed, noPeer); + assertThat(noPeer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + + for (String workload : + List.of( + "account-service", + "game-design-service", + "game-logic-service", + "world-management-service")) { + var denied = new Collector(); + peer("test", workload) + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(malformed, denied)); + assertThat(denied.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + var otherNamespace = new Collector(); + peer("other", "entity-management-service") + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(malformed, otherNamespace)); + assertThat(otherNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("44", List.of(), java.util.Map.of()); + try { + var endUser = new Collector(); + peer("test", "entity-management-service") + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(malformed, endUser)); + assertThat(endUser.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + + var allowedPeerMalformed = new Collector(); + peer("test", "entity-management-service") + .run( + () -> + service.readHeldSelectedOwnerIntakeAuthorization(malformed, allowedPeerMalformed)); + assertThat(allowedPeerMalformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void returnsExactEchoOnlyForMatchingEntityAndAutomationReader() { + var owner = mock(AccountSelectedOwnerIntakeAuthorizationReadService.class); + var service = new AccountSelectedOwnerIntakeAuthorizationReadGrpcService(owner, "test"); + + for (Owner domain : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(domain); + var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding); + var wire = SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest(request); + var result = new Collector(); + peerFromUri(binding.intendedReader()) + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(wire, result)); + + assertThat(result.error).isNull(); + assertThat(result.response).isNotNull(); + assertThat(result.response.getRequest()).isEqualTo(wire); + assertThat(result.response.getHeld()).isTrue(); + } + verify(owner, times(2)).requireHeld(any()); + } + + @Test + void entityCannotReadAutomationAndAutomationCannotReadEntity() { + var owner = mock(AccountSelectedOwnerIntakeAuthorizationReadService.class); + var service = new AccountSelectedOwnerIntakeAuthorizationReadGrpcService(owner, "test"); + + for (Owner bindingOwner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(bindingOwner); + var request = + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest( + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding)); + String wrongReader = + bindingOwner == Owner.ENTITY_MANAGEMENT + ? "automation-scripting-service" + : "entity-management-service"; + var result = new Collector(); + peer("test", wrongReader) + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(request, result)); + assertThat(result.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(result.response).isNull(); + } + verifyNoInteractions(owner); + } + + @Test + void rejectsWrongNamespaceClosedFieldsDigestUnknownFieldsAndMalformedSizes() { + var owner = mock(AccountSelectedOwnerIntakeAuthorizationReadService.class); + var service = new AccountSelectedOwnerIntakeAuthorizationReadGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + var valid = + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest( + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding)); + + var wrongNamespace = new Collector(); + peer("test", "entity-management-service") + .run( + () -> + service.readHeldSelectedOwnerIntakeAuthorization( + valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + var changedReader = + valid.toBuilder().setIntendedReader("spiffe://firemud/ns/test/sa/account-service").build(); + var changedPurpose = valid.toBuilder().setRetentionPurpose("ENTITY_INTAKE_SOURCE").build(); + var changedDigest = + valid.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build(); + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var malformedBinding = + valid.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + var oversizedBinding = + valid.toBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .build(); + for (var malformed : + List.of( + changedReader, + changedPurpose, + changedDigest, + unknown, + malformedBinding, + oversizedBinding)) { + var result = new Collector(); + peerFromUri(binding.intendedReader()) + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(result.response).isNull(); + } + verifyNoInteractions(owner); + } + + @Test + void mapsOwnerReadFailureToNoHeldResponse() { + var owner = mock(AccountSelectedOwnerIntakeAuthorizationReadService.class); + org.mockito.Mockito.doThrow(Status.FAILED_PRECONDITION.asRuntimeException()) + .when(owner) + .requireHeld(any()); + var service = new AccountSelectedOwnerIntakeAuthorizationReadGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + var wire = + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest( + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding)); + var result = new Collector(); + + peerFromUri(binding.intendedReader()) + .run(() -> service.readHeldSelectedOwnerIntakeAuthorization(wire, result)); + + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(result.response).isNull(); + } + + private static Context peer(String namespace, String workload) { + return peerFromUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload); + } + + private static Context peerFromUri(String uri) { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + } + + private static final class Collector + implements StreamObserver { + private ReadHeldSelectedOwnerIntakeAuthorizationResponse response; + private Status.Code error; + + @Override + public void onNext(ReadHeldSelectedOwnerIntakeAuthorizationResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java new file mode 100644 index 0000000000..dc8548f39b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java @@ -0,0 +1,290 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.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 io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic Account read tests; they do not establish PostgreSQL or owner-terminal proof. */ +class AccountSelectedOwnerIntakeAuthorizationReadServiceTest { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository = + mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + + @AfterEach + void clearCallerAndTransactionContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void readsExactEntityAndAutomationBindingsInIndependentReadCommittedTransactions() { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + var service = newService(); + + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = binding(owner); + var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding); + asReader(binding, () -> service.requireHeld(request)); + verify(repository).readFinalAuthorization(binding); + } + + var definitions = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions, times(2)).getTransaction(definitions.capture()); + assertThat(definitions.getAllValues()) + .allSatisfy( + definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); + } + + @Test + void rejectsMissingWrongOwnerAndEndUserContextsBeforeRepositoryAccess() { + var service = newService(); + var entity = binding(Owner.ENTITY_MANAGEMENT); + var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", entity); + + assertCode(Status.Code.UNAUTHENTICATED, () -> service.requireHeld(request)); + asPeer( + "test", + "automation-scripting-service", + () -> assertCode(Status.Code.PERMISSION_DENIED, () -> service.requireHeld(request))); + + SessionContext.setContext("44", List.of(), Map.of()); + try { + asReader( + entity, + () -> assertCode(Status.Code.PERMISSION_DENIED, () -> service.requireHeld(request))); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(repository, transactions); + } + + @Test + void rejectsAmbientSqlBeforeStartingOwnerRead() { + var service = newService(); + var binding = binding(Owner.ENTITY_MANAGEMENT); + var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + asReader( + binding, + () -> assertCode(Status.Code.FAILED_PRECONDITION, () -> service.requireHeld(request))); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(repository, transactions); + } + + @Test + void distinguishesAbsentOrChangedAuthorizationFromUnavailableStorage() { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + var service = newService(); + var binding = binding(Owner.AUTOMATION_SCRIPTING); + var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding); + + org.mockito.Mockito.doThrow(new IllegalArgumentException("not available")) + .when(repository) + .readFinalAuthorization(binding); + asReader( + binding, + () -> assertCode(Status.Code.FAILED_PRECONDITION, () -> service.requireHeld(request))); + + org.mockito.Mockito.doThrow(new IllegalStateException("storage unavailable")) + .when(repository) + .readFinalAuthorization(binding); + asReader( + binding, () -> assertCode(Status.Code.UNAVAILABLE, () -> service.requireHeld(request))); + } + + private AccountSelectedOwnerIntakeAuthorizationReadService newService() { + return new AccountSelectedOwnerIntakeAuthorizationReadService(repository, transactions, "test"); + } + + static SelectedOwnerIntakeAuthorizationBinding binding(Owner owner) { + UUID tenant = id("11111111-1111-4111-8111-111111111111"); + UUID actor = id("99999999-9999-4999-8999-999999999999"); + UUID operation = id("55555555-5555-4555-8555-555555555555"); + UUID fence = id("66666666-6666-4666-8666-666666666666"); + UUID intake = id("77777777-7777-4777-8777-777777777777"); + var selected = selected(tenant); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, "test", operation, fence, intake, actor, selected); + return new SelectedOwnerIntakeAuthorizationBinding(content(scope), sources(actor, tenant)); + } + + private static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = snapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] snapshot(String family, DraftCommitBinding selected) { + if ("GAMEPLAY_RULE".equals(family)) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + } + if ("TEMPLATE_CONFIG".equals(family)) + return new TemplateConfigSourceSnapshot( + selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) + .canonicalBytes(); + return GameplayRuleManifest.canonical( + Map.of( + "schema", + "synthetic-test-only/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "family", + family)) + .getBytes(StandardCharsets.UTF_8); + } + + private static List sources(UUID actor, UUID tenant) { + return List.of( + evidence(SourceKind.TENANT, tenant.toString(), "tenant"), + evidence(SourceKind.ACCOUNT, actor.toString(), "account"), + evidence(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership")); + } + + private static SourceEvidence evidence(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected(UUID tenant) { + UUID version = id("22222222-2222-4222-8222-222222222222"); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), + Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + version.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private static void asReader(SelectedOwnerIntakeAuthorizationBinding binding, Runnable action) { + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri(binding.intendedReader()).orElseThrow()); + peer.run(action); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + var peer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + peer.run(action); + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(error -> assertThat(Status.fromThrowable(error).getCode()).isEqualTo(expected)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java index b0df423cd8..9dfbf55165 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java @@ -4,19 +4,45 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.jooq.impl.DSL.field; import static org.jooq.impl.DSL.name; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.startsWith; +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 io.grpc.Context; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.OffsetDateTime; +import java.util.Base64; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.Snapshot; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.jooq.impl.SQLDataType; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountStartSessionAuthorityCaptureRepositoryTest { private static final String REQUEST_ID = "capture-repository-unit"; @@ -71,6 +97,54 @@ class AccountStartSessionAuthorityCaptureRepositoryTest { field(name("canonical_sha256"), SQLDataType.VARCHAR); private static final Field CANONICAL_BYTES = field(name("canonical_capture_bytes"), SQLDataType.VARBINARY); + private static final Field PRE_AUTHORIZATION_TUPLE = + field(name("pre_authorization_tuple"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_REQUEST_ID = + field(name("request_id"), SQLDataType.UUID); + private static final Field ISSUANCE_OPERATION_ID = + field(name("operation_id"), SQLDataType.UUID); + private static final Field ISSUANCE_TOKEN_JTI = field(name("token_jti"), SQLDataType.UUID); + private static final Field ISSUANCE_CALLER_CONTEXT_ID = + field(name("caller_context_id"), SQLDataType.UUID); + private static final Field ISSUANCE_CALLER_WORKLOAD = + field(name("caller_workload"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_REQUEST_MAC_KEY_ID = + field(name("request_mac_key_id"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_REQUEST_DIGEST = + field(name("request_digest"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_STATUS = field(name("status"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_TOKEN_HASH = + field(name("token_hash"), SQLDataType.VARCHAR); + private static final Field ISSUANCE_CLAIMS = + field(name("claims_payload"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_SOURCES = + field(name("source_payload"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_BUNDLE = + field(name("bundle_payload"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_SIGNER_RECEIPT = + field(name("signer_receipt"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_PENDING_REGISTRY = + field(name("pending_registry"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_ACTIVE_REGISTRY = + field(name("active_registry"), SQLDataType.VARBINARY); + private static final Field ISSUANCE_CREATED_AT = + field(name("issued_at_epoch_second"), SQLDataType.BIGINT); + private static final Field ISSUANCE_EXPIRES_AT = + field(name("expires_at_epoch_second"), SQLDataType.BIGINT); + private static final Field ISSUANCE_RECOVERY_EXPIRES_AT = + field(name("recovery_expires_at"), SQLDataType.OFFSETDATETIME); + + private static final String NAMESPACE = "gameplay"; + private static final String LOGGING_PEER_URI = + "spiffe://firemud/ns/gameplay/sa/logging-admin-service"; + private static final String WORLD_PEER_URI = + "spiffe://firemud/ns/gameplay/sa/world-management-service"; + + @AfterEach + void clearContext() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } @Test void decodesCanonicalSnapshotUuidsFromTypedJooqUuidColumns() { @@ -92,6 +166,154 @@ void rejectsWrongMissingAndMalformedSnapshotUuidEvidence() { assertUnavailable(missingStoredUuid.row()); } + @Test + void worldReceivingLookupAcceptsWorldPeerAndRetainedLoggingIssuer() { + WorldLookupFixture fixture = worldLookupFixture(true); + beginOwnerTransaction(); + + AccountStartSessionAuthorityCapture observed = + withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI)); + + assertThat(observed.sameStoredValue(fixture.capture())).isTrue(); + verify(fixture.dsl(), times(1)) + .fetchOne(startsWith("SELECT control_plane_request_id"), any(Object[].class)); + verifyNoMoreInteractions(fixture.dsl()); + } + + @Test + void worldReceivingLookupRejectsWrongPeerAndNamespaceBeforeStorage() { + WorldLookupFixture fixture = worldLookupFixture(true); + beginOwnerTransaction(); + + assertUnavailable( + () -> + withPeer(LOGGING_PEER_URI, NAMESPACE, "logging-admin-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); + assertUnavailable( + () -> + withPeer( + "spiffe://firemud/ns/other/sa/world-management-service", + "other", + "world-management-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); + + verifyNoInteractions(fixture.dsl()); + } + + @Test + void worldReceivingLookupRejectsAmbientEndUserContextBeforeStorage() { + WorldLookupFixture fixture = worldLookupFixture(true); + beginOwnerTransaction(); + SessionContext.setContext("account-user", List.of("tenantAdmin"), Map.of()); + + assertUnavailable( + () -> + withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); + + verifyNoInteractions(fixture.dsl()); + } + + @Test + void worldReceivingLookupDoesNotCreateMissingOriginalCapture() { + WorldLookupFixture fixture = worldLookupFixture(false); + beginOwnerTransaction(); + + assertUnavailable( + () -> + withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); + + verify(fixture.dsl(), times(1)) + .fetchOne(startsWith("SELECT control_plane_request_id"), any(Object[].class)); + verifyNoMoreInteractions(fixture.dsl()); + } + + @Test + void existingExactCurrentReadStillRequiresLoggingPeer() { + WorldLookupFixture fixture = worldLookupFixture(true); + beginOwnerTransaction(); + + assertUnavailable( + () -> + withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrent( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L))); + assertThat( + withPeer(LOGGING_PEER_URI, NAMESPACE, "logging-admin-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrent( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L)) + .sameStoredValue(fixture.capture())) + .isTrue(); + } + private static CaptureFixture fixture(String snapshotAccountId) { Map snapshot = new LinkedHashMap<>(); snapshot.put("schema", "account-start-session-authority-snapshot/v1"); @@ -192,5 +414,256 @@ private static void assertUnavailable(Record row) { .hasMessage("Account StartSession source capture is unavailable"); } + private static void assertUnavailable(ThrowingCallable action) { + assertThatThrownBy(action) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account StartSession source capture is unavailable"); + } + + private static WorldLookupFixture worldLookupFixture(boolean capturePresent) { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + Snapshot source = sourceSnapshot(); + var stored = issuance(tuple); + CaptureFixture capture = worldCapture(tuple, source, stored); + DSLContext dsl = mock(DSLContext.class); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenReturn(capturePresent ? capture.row() : null); + return new WorldLookupFixture( + dsl, + new AccountStartSessionAuthorityCaptureRepository(dsl), + new AccountControlUiActorService.Current(stored, source), + tuple, + capture.capture()); + } + + private static StartSessionPreAuthorizationReservationTuple tuple() { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(71L, ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "capture lookup test"); + return StartSessionPreAuthorizationReservationTuple.createHuman(REQUEST_ID, ACCOUNT_ID, action); + } + + private static Snapshot sourceSnapshot() { + SourceEvidence sourceEvidence = + new SourceEvidence( + SourceKind.TENANT, + TENANT_ID.toString(), + "3", + "4", + null, + null, + "exact tenant source".getBytes(StandardCharsets.UTF_8)); + try { + var constructor = + Snapshot.class.getDeclaredConstructor( + UUID.class, + UUID.class, + Map.class, + Map.class, + long.class, + long.class, + List.class, + byte[].class, + List.class, + Map.class); + constructor.setAccessible(true); + return constructor.newInstance( + ACCOUNT_ID, + TENANT_ID, + Map.of("issuerAuthGeneration", 1L), + Map.of(TENANT_ID.toString(), 2L), + 9L, + 10L, + List.of(sourceEvidence), + "exact source vector".getBytes(StandardCharsets.UTF_8), + List.of(), + Map.of("sourceRowId", 17L, "provenance", "canonical", "sourceNumericId", 17L)); + } catch (ReflectiveOperationException failure) { + throw new AssertionError("Could not construct the captured Account source fixture", failure); + } + } + + private static AccountControlUiIssuanceRepository.Stored issuance( + StartSessionPreAuthorizationReservationTuple tuple) { + Record row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + ISSUANCE_REQUEST_ID, + ISSUANCE_OPERATION_ID, + ISSUANCE_TOKEN_JTI, + ACCOUNT_UUID, + TENANT_UUID, + ISSUANCE_CALLER_CONTEXT_ID, + ISSUANCE_CALLER_WORKLOAD, + ISSUANCE_REQUEST_MAC_KEY_ID, + ISSUANCE_REQUEST_DIGEST, + ISSUANCE_STATUS, + ISSUANCE_TOKEN_HASH, + ISSUANCE_CLAIMS, + ISSUANCE_SOURCES, + ISSUANCE_BUNDLE, + ISSUANCE_SIGNER_RECEIPT, + ISSUANCE_PENDING_REGISTRY, + ISSUANCE_ACTIVE_REGISTRY, + ISSUANCE_CREATED_AT, + ISSUANCE_EXPIRES_AT, + ISSUANCE_RECOVERY_EXPIRES_AT); + row.setValue(ISSUANCE_REQUEST_ID, CONTROL_UI_OPERATION_ID); + row.setValue(ISSUANCE_OPERATION_ID, CONTROL_UI_OPERATION_ID); + row.setValue(ISSUANCE_TOKEN_JTI, CONTROL_UI_TOKEN_JTI); + row.setValue(ACCOUNT_UUID, tuple.actor().accountId()); + row.setValue(TENANT_UUID, tuple.action().scope().tenantId()); + row.setValue( + ISSUANCE_CALLER_CONTEXT_ID, UUID.fromString("66666666-6666-4666-8666-666666666666")); + row.setValue(ISSUANCE_CALLER_WORKLOAD, LOGGING_PEER_URI); + row.setValue(ISSUANCE_REQUEST_MAC_KEY_ID, "capture-test-key"); + row.setValue(ISSUANCE_REQUEST_DIGEST, "request-digest"); + row.setValue(ISSUANCE_STATUS, "COMMITTED"); + row.setValue(ISSUANCE_TOKEN_HASH, "b".repeat(64)); + row.setValue(ISSUANCE_CLAIMS, "claims".getBytes(StandardCharsets.UTF_8)); + row.setValue(ISSUANCE_SOURCES, "sources".getBytes(StandardCharsets.UTF_8)); + row.setValue(ISSUANCE_BUNDLE, "bundle".getBytes(StandardCharsets.UTF_8)); + row.setValue( + ISSUANCE_SIGNER_RECEIPT, "original signer receipt".getBytes(StandardCharsets.UTF_8)); + row.setValue(ISSUANCE_PENDING_REGISTRY, "pending".getBytes(StandardCharsets.UTF_8)); + row.setValue(ISSUANCE_ACTIVE_REGISTRY, "active".getBytes(StandardCharsets.UTF_8)); + row.setValue(ISSUANCE_CREATED_AT, 1_800_000_000L); + row.setValue(ISSUANCE_EXPIRES_AT, 1_900_000_000L); + row.setValue(ISSUANCE_RECOVERY_EXPIRES_AT, OffsetDateTime.parse("2040-01-01T00:00:00Z")); + return new AccountControlUiIssuanceRepository.Stored(row); + } + + private static CaptureFixture worldCapture( + StartSessionPreAuthorizationReservationTuple tuple, + Snapshot source, + AccountControlUiIssuanceRepository.Stored stored) { + byte[] tupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + Map snapshot = new LinkedHashMap<>(); + snapshot.put("schema", "account-start-session-authority-snapshot/v1"); + snapshot.put("controlPlaneRequestId", tuple.controlPlaneRequestId()); + snapshot.put("preAuthorizationTuple", Base64.getEncoder().encodeToString(tupleBytes)); + snapshot.put("mutationDigest", tuple.mutationDigest()); + snapshot.put("accountId", stored.accountId.toString()); + snapshot.put("tenantId", stored.tenantId.toString()); + snapshot.put("targetOwner", tuple.targetOwner()); + snapshot.put("loggingWorkloadUri", LOGGING_PEER_URI); + snapshot.put("reservationOwnerId", RESERVATION_OWNER_ID.toString()); + snapshot.put("reservationClaimFence", "7"); + snapshot.put("controlUiOperationId", stored.operationId.toString()); + snapshot.put("controlUiTokenJti", stored.jti.toString()); + snapshot.put("controlUiTokenHash", stored.tokenHash); + snapshot.put( + "controlUiSignerReceipt", Base64.getEncoder().encodeToString(stored.signerReceipt)); + snapshot.put("controlUiSignerReceiptSha256", sha256(stored.signerReceipt)); + snapshot.put("sourceVectorEvidence", Base64.getEncoder().encodeToString(source.evidence())); + snapshot.put( + "sourceVector", + source.sources().stream() + .map(value -> Base64.getEncoder().encodeToString(value.canonicalBytes())) + .toList()); + snapshot.put("outboxCheckpoints", source.outboxCheckpoints()); + snapshot.put("authorityTuple", source.authorityTuple()); + snapshot.put("membershipVersion", source.membershipVersion()); + snapshot.put("accountIdentitySource", source.accountIdentitySource()); + snapshot.put("issuanceFence", Long.toString(source.issuanceFence())); + snapshot.put("issuanceFenceSourceVersion", Long.toString(source.issuanceFenceSourceVersion())); + byte[] snapshotBytes = AccountControlUiAuthority.canonical(Map.copyOf(snapshot)); + AccountStartSessionAuthorityCapture capture = + AccountStartSessionAuthorityCapture.create( + tuple.controlPlaneRequestId(), 11L, 13L, "17", CAPTURED_AT, snapshotBytes); + Record row = + DSL.using(SQLDialect.POSTGRES) + .newRecord( + CONTROL_PLANE_REQUEST_ID, + ACCOUNT_UUID, + TENANT_UUID, + TARGET_OWNER, + LOGGING_WORKLOAD_URI, + RESERVATION_OWNER_UUID, + RESERVATION_CLAIM_FENCE, + PRE_AUTHORIZATION_TUPLE, + MUTATION_DIGEST, + CONTROL_UI_OPERATION_UUID, + CONTROL_UI_TOKEN_UUID, + CONTROL_UI_TOKEN_HASH, + SIGNER_RECEIPT_SHA256, + ISSUANCE_FENCE, + ISSUANCE_FENCE_SOURCE_VERSION, + CAPTURED_AT_FIELD, + SNAPSHOT_SHA256, + SNAPSHOT_BYTES, + SOURCE_VERSION, + SOURCE_FENCE, + LINEARIZATION, + CANONICAL_SHA256, + CANONICAL_BYTES); + row.setValue(CONTROL_PLANE_REQUEST_ID, tuple.controlPlaneRequestId()); + row.setValue(ACCOUNT_UUID, tuple.actor().accountId()); + row.setValue(TENANT_UUID, tuple.action().scope().tenantId()); + row.setValue(TARGET_OWNER, tuple.targetOwner()); + row.setValue(LOGGING_WORKLOAD_URI, LOGGING_PEER_URI); + row.setValue(RESERVATION_OWNER_UUID, RESERVATION_OWNER_ID); + row.setValue(RESERVATION_CLAIM_FENCE, 7L); + row.setValue(PRE_AUTHORIZATION_TUPLE, tupleBytes); + row.setValue(MUTATION_DIGEST, tuple.mutationDigest()); + row.setValue(CONTROL_UI_OPERATION_UUID, stored.operationId); + row.setValue(CONTROL_UI_TOKEN_UUID, stored.jti); + row.setValue(CONTROL_UI_TOKEN_HASH, stored.tokenHash); + row.setValue(SIGNER_RECEIPT_SHA256, sha256(stored.signerReceipt)); + row.setValue(ISSUANCE_FENCE, source.issuanceFence()); + row.setValue(ISSUANCE_FENCE_SOURCE_VERSION, source.issuanceFenceSourceVersion()); + row.setValue(CAPTURED_AT_FIELD, CAPTURED_AT); + row.setValue(SNAPSHOT_SHA256, capture.snapshotSha256()); + row.setValue(SNAPSHOT_BYTES, capture.snapshotBytes()); + row.setValue(SOURCE_VERSION, capture.sourceVersion()); + row.setValue(SOURCE_FENCE, capture.sourceFence()); + row.setValue(LINEARIZATION, capture.linearization()); + row.setValue(CANONICAL_SHA256, capture.canonicalSha256()); + row.setValue(CANONICAL_BYTES, capture.canonicalBytes()); + return new CaptureFixture(row, capture); + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new AssertionError("SHA-256 is required", impossible); + } + } + + private static void beginOwnerTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + } + + private static PeerContext withPeer(String uri, String namespace, String service) { + return new PeerContext(new GrpcPeerIdentity(uri, namespace, service)); + } + private record CaptureFixture(Record row, AccountStartSessionAuthorityCapture capture) {} + + private record WorldLookupFixture( + DSLContext dsl, + AccountStartSessionAuthorityCaptureRepository repository, + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + AccountStartSessionAuthorityCapture capture) {} + + private record PeerContext(GrpcPeerIdentity peer) { + T call(Supplier action) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java index a21bfe77d5..d0fdb75bc7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java @@ -1049,12 +1049,13 @@ void worldCurrentnessLocksExactCaptureAndRunsOnlyAccountCallbackInSameTransactio assertThat(result).isEqualTo(harness.capture()); assertThat(callbackCapture.get()).isEqualTo(harness.capture()); verify(harness.captureRepository()) - .lockReadExactCurrent( + .lockReadExactCurrentFromWorldReceiving( any(), eq(harness.tuple()), eq(LOGGING_PEER), eq(harness.record().reservationOwnerId()), - eq(harness.record().reservationClaimFence())); + eq(harness.record().reservationClaimFence()), + eq(WORLD_MANAGEMENT_PEER)); verify(harness.captureRepository(), never()) .prepareOrReadExact(any(), any(), anyString(), any(), anyLong()); verify(harness.captureRepository(), never()) @@ -1088,7 +1089,8 @@ void worldCurrentnessRejectsExpiredReferenceAndChangedCurrentSourceBeforeCallbac assertThat(expiredCallback).hasValue(false); verify(expired.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); verify(expired.captureRepository(), never()) - .lockReadExactCurrent(any(), any(), anyString(), any(), anyLong()); + .lockReadExactCurrentFromWorldReceiving( + any(), any(), anyString(), any(), anyLong(), anyString()); ReadHarness changed = readHarness(NOW.plusSeconds(30)); AccountControlUiAuthority.Snapshot changedSource = @@ -1114,7 +1116,13 @@ void worldCurrentnessRejectsExpiredReferenceAndChangedCurrentSourceBeforeCallbac .hasMessageContaining("Current Account source")); assertThat(changedCallback).hasValue(false); verify(changed.captureRepository()) - .lockReadExactCurrent(any(), eq(changed.tuple()), eq(LOGGING_PEER), any(), anyLong()); + .lockReadExactCurrentFromWorldReceiving( + any(), + eq(changed.tuple()), + eq(LOGGING_PEER), + any(), + anyLong(), + eq(WORLD_MANAGEMENT_PEER)); } @Test @@ -1171,7 +1179,8 @@ void worldCurrentnessRejectsPostTupleFingerprintAndOwnerAttemptSubstitution() { assertThat(callback).hasValue(false); verify(harness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); verify(harness.captureRepository(), never()) - .lockReadExactCurrent(any(), any(), anyString(), any(), anyLong()); + .lockReadExactCurrentFromWorldReceiving( + any(), any(), anyString(), any(), anyLong(), anyString()); } @Test @@ -1835,6 +1844,10 @@ private static ReadHarness readHarness( }); when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) .thenReturn(Optional.of(record)); + String exactWorldManagementPeerUri = + "spiffe://firemud/ns/" + + GrpcPeerIdentity.parseUri(exactGameSessionPeerUri).orElseThrow().namespace() + + "/sa/world-management-service"; doAnswer( invocation -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); @@ -1844,6 +1857,22 @@ private static ReadHarness readHarness( .when(captureRepository) .lockReadExactCurrent( any(), eq(tuple), eq(exactLoggingPeerUri), eq(reservationOwnerId), eq(10L)); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(invocation.getArgument(0).stored()).isSameAs(stored); + assertThat(invocation.getArgument(2)).isEqualTo(exactLoggingPeerUri); + assertThat(invocation.getArgument(5)).isEqualTo(exactWorldManagementPeerUri); + return capture; + }) + .when(captureRepository) + .lockReadExactCurrentFromWorldReceiving( + any(), + eq(tuple), + eq(exactLoggingPeerUri), + eq(reservationOwnerId), + eq(10L), + eq(exactWorldManagementPeerUri)); var service = new AccountStartSessionOperatorAuthorizationService( actors, diff --git a/services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql b/services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql new file mode 100644 index 0000000000..96049bd8d7 --- /dev/null +++ b/services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql @@ -0,0 +1,186 @@ +-- Isolated feasibility fixture only. No production migration or privilege adoption. +-- __S__ is the actual Flyway schema; __P__ is a separate test receipt schema. +CREATE ROLE __P___owner NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT; +CREATE ROLE __P___caller LOGIN PASSWORD 'isolated-prototype-only' NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT; +CREATE SCHEMA __P__ AUTHORIZATION __P___owner; +REVOKE ALL ON SCHEMA __P__ FROM PUBLIC; +GRANT USAGE ON SCHEMA __P__ TO __P___caller; +GRANT USAGE ON SCHEMA __S__ TO __P___owner; +GRANT SELECT ON __S__.accounts, __S__.account_gameplay_admission_lease_operations TO __P___owner; +-- PostgreSQL row locking requires UPDATE privilege; no caller receives it. +GRANT UPDATE(account_uuid) ON __S__.accounts TO __P___owner; +GRANT UPDATE(request_id) ON __S__.account_gameplay_admission_lease_operations TO __P___owner; + +CREATE TABLE __P__.receipts ( + request_id UUID PRIMARY KEY REFERENCES __S__.account_gameplay_admission_lease_operations(request_id), + original_operation JSONB NOT NULL, + finalization_xid TEXT NOT NULL, + confirmation_xid TEXT NOT NULL, + snapshot TEXT NOT NULL, + insert_lsn PG_LSN NOT NULL CHECK (insert_lsn > '0/0'), + flush_lsn PG_LSN NOT NULL CHECK (flush_lsn >= insert_lsn), + committed_before_ms BIGINT NOT NULL CHECK (committed_before_ms > 0), + expires_at_ms BIGINT NOT NULL CHECK (expires_at_ms > committed_before_ms), + CHECK (finalization_xid <> confirmation_xid) +); +ALTER TABLE __P__.receipts OWNER TO __P___owner; +REVOKE ALL ON __P__.receipts FROM PUBLIC, __P___caller; + +CREATE FUNCTION __P__.immutable() RETURNS TRIGGER LANGUAGE plpgsql SET search_path = pg_catalog AS $$ +BEGIN + RAISE EXCEPTION 'prototype receipt immutable' USING ERRCODE = '23514'; +END; +$$; +ALTER FUNCTION __P__.immutable() OWNER TO __P___owner; +REVOKE ALL ON FUNCTION __P__.immutable() FROM PUBLIC, __P___caller; +CREATE TRIGGER immutable BEFORE UPDATE OR DELETE ON __P__.receipts + FOR EACH ROW EXECUTE FUNCTION __P__.immutable(); +CREATE TRIGGER immutable_truncate BEFORE TRUNCATE ON __P__.receipts + FOR EACH STATEMENT EXECUTE FUNCTION __P__.immutable(); + +-- Private writer is never executable by the caller. Capture is not an external API. +CREATE FUNCTION __P__.write_receipt(p_receipt __P__.receipts) RETURNS JSONB +LANGUAGE plpgsql SET search_path = pg_catalog AS $$ +DECLARE retained __P__.receipts%ROWTYPE; +BEGIN + INSERT INTO __P__.receipts SELECT (p_receipt).* WHERE TRUE ON CONFLICT (request_id) DO NOTHING + RETURNING * INTO retained; + IF NOT FOUND THEN + RAISE EXCEPTION 'prototype stale receipt snapshot' USING ERRCODE = '40001'; + END IF; + RETURN to_jsonb(retained); +END; +$$; +ALTER FUNCTION __P__.write_receipt(__P__.receipts) OWNER TO __P___owner; +REVOKE ALL ON FUNCTION __P__.write_receipt(__P__.receipts) FROM PUBLIC, __P___caller; + +CREATE FUNCTION __P__.confirm(p_request UUID, p_sha TEXT, p_decision UUID) RETURNS JSONB +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$ +DECLARE + op __S__.account_gameplay_admission_lease_operations%ROWTYPE; + locked_op __S__.account_gameplay_admission_lease_operations%ROWTYPE; + retained __P__.receipts%ROWTYPE; + candidate __P__.receipts%ROWTYPE; + fixed_snapshot pg_snapshot; + own_xid TEXT; + upper_lsn pg_lsn; + flush_lsn pg_lsn; + observed_ms BIGINT; + observation INTEGER; +BEGIN + IF current_setting('transaction_isolation') <> 'serializable' + OR current_setting('transaction_read_only') <> 'off' + OR pg_is_in_recovery() OR current_setting('fsync') <> 'on' THEN + RAISE EXCEPTION 'prototype durable primary SERIALIZABLE required' USING ERRCODE = '23514'; + END IF; + -- Function entry itself can already require catalog/planning reads. Cold tests must expose + -- resulting unflushed WAL rather than claiming these statements precede all backend reads. + fixed_snapshot := pg_current_snapshot(); + own_xid := pg_current_xact_id_if_assigned()::text; + upper_lsn := pg_current_wal_insert_lsn(); + SELECT * INTO op FROM __S__.account_gameplay_admission_lease_operations WHERE request_id = p_request; + IF NOT FOUND OR op.status <> 'COMMITTED' OR op.finalization_xid IS NULL + OR op.evidence_sha256 IS DISTINCT FROM p_sha OR op.binding_decision_id IS DISTINCT FROM p_decision THEN + RAISE EXCEPTION 'prototype exact original required' USING ERRCODE = '23514'; + END IF; + IF op.finalization_xid = own_xid + OR NOT pg_visible_in_snapshot(op.finalization_xid::xid8, fixed_snapshot) THEN + RAISE EXCEPTION 'prototype independent original required' USING ERRCODE = '23514'; + END IF; + PERFORM 1 FROM __S__.accounts WHERE account_uuid = op.account_uuid FOR UPDATE; + SELECT * INTO locked_op FROM __S__.account_gameplay_admission_lease_operations + WHERE request_id = p_request FOR UPDATE; + IF NOT FOUND OR locked_op IS DISTINCT FROM op THEN + RAISE EXCEPTION 'prototype original changed' USING ERRCODE = '23514'; + END IF; + SELECT * INTO retained FROM __P__.receipts WHERE request_id = p_request FOR UPDATE; + IF FOUND THEN + IF retained.original_operation IS DISTINCT FROM to_jsonb(op) THEN + RAISE EXCEPTION 'prototype retained binding conflict' USING ERRCODE = '23514'; + END IF; + RETURN to_jsonb(retained); + END IF; + IF pg_xact_status(op.finalization_xid::xid8) IS DISTINCT FROM 'committed' THEN + RAISE EXCEPTION 'prototype independent original required' USING ERRCODE = '23514'; + END IF; + -- Same-snapshot independent visibility places original COMMIT before snapshot acquisition; + -- this later insertion upper bound covers that COMMIT, not merely its earlier row WAL. + FOR observation IN 1..50 LOOP + flush_lsn := pg_current_wal_flush_lsn(); + observed_ms := ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint; + IF observed_ms <= 0 OR observed_ms >= op.expires_at_ms THEN + RAISE EXCEPTION 'prototype unchanged deadline expired' USING ERRCODE = '23514'; + END IF; + EXIT WHEN upper_lsn > '0/0' AND flush_lsn >= upper_lsn; + IF observation = 50 THEN + RAISE EXCEPTION 'prototype WAL coverage unavailable' USING ERRCODE = '23514', + DETAIL = format('snapshot=%s own_xid=%s original_xid=%s upper_lsn=%s flush_lsn=%s observed_ms=%s expiry=%s', + fixed_snapshot, own_xid, op.finalization_xid, upper_lsn, flush_lsn, observed_ms, op.expires_at_ms); + END IF; + PERFORM pg_sleep(0.01); + END LOOP; + candidate.request_id := p_request; + candidate.original_operation := to_jsonb(op); + candidate.finalization_xid := op.finalization_xid; + candidate.confirmation_xid := pg_current_xact_id()::text; + candidate.snapshot := fixed_snapshot::text; + candidate.insert_lsn := upper_lsn; + candidate.flush_lsn := flush_lsn; + candidate.committed_before_ms := observed_ms; + candidate.expires_at_ms := op.expires_at_ms; + RETURN __P__.write_receipt(candidate); +END; +$$; +ALTER FUNCTION __P__.confirm(UUID, TEXT, UUID) OWNER TO __P___owner; +REVOKE ALL ON FUNCTION __P__.confirm(UUID, TEXT, UUID) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION __P__.confirm(UUID, TEXT, UUID) TO __P___caller; + +CREATE FUNCTION __P__.read_receipt(p_request UUID, p_sha TEXT, p_decision UUID) RETURNS JSONB +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$ +DECLARE + op __S__.account_gameplay_admission_lease_operations%ROWTYPE; + retained __P__.receipts%ROWTYPE; + fixed_snapshot pg_snapshot; + own_xid TEXT; + upper_lsn pg_lsn; + flush_lsn pg_lsn; + observation INTEGER; +BEGIN + IF current_setting('transaction_isolation') <> 'serializable' + OR current_setting('transaction_read_only') <> 'off' + OR pg_is_in_recovery() OR current_setting('fsync') <> 'on' THEN + RAISE EXCEPTION 'prototype durable primary SERIALIZABLE required' USING ERRCODE = '23514'; + END IF; + fixed_snapshot := pg_current_snapshot(); + own_xid := pg_current_xact_id_if_assigned()::text; + upper_lsn := pg_current_wal_insert_lsn(); + SELECT * INTO op FROM __S__.account_gameplay_admission_lease_operations WHERE request_id = p_request; + IF NOT FOUND OR op.status <> 'COMMITTED' OR op.evidence_sha256 IS DISTINCT FROM p_sha + OR op.binding_decision_id IS DISTINCT FROM p_decision THEN + RAISE EXCEPTION 'prototype exact original required' USING ERRCODE = '23514'; + END IF; + SELECT * INTO retained FROM __P__.receipts WHERE request_id = p_request; + IF NOT FOUND OR retained.original_operation IS DISTINCT FROM to_jsonb(op) THEN + RAISE EXCEPTION 'prototype exact receipt required' USING ERRCODE = '23514'; + END IF; + IF retained.confirmation_xid = own_xid + OR NOT pg_visible_in_snapshot(retained.confirmation_xid::xid8, fixed_snapshot) THEN + RAISE EXCEPTION 'prototype independent receipt required' USING ERRCODE = '23514'; + END IF; + FOR observation IN 1..50 LOOP + flush_lsn := pg_current_wal_flush_lsn(); + EXIT WHEN upper_lsn > '0/0' AND flush_lsn >= upper_lsn; + IF observation = 50 THEN + RAISE EXCEPTION 'prototype receipt WAL coverage unavailable' USING ERRCODE = '23514', + DETAIL = format('snapshot=%s receipt_xid=%s upper_lsn=%s flush_lsn=%s', + fixed_snapshot, retained.confirmation_xid, upper_lsn, flush_lsn); + END IF; + PERFORM pg_sleep(0.01); + END LOOP; + -- Historical recovery preserves the original deadline-qualified evidence after expiry. + RETURN to_jsonb(retained); +END; +$$; +ALTER FUNCTION __P__.read_receipt(UUID, TEXT, UUID) OWNER TO __P___owner; +REVOKE ALL ON FUNCTION __P__.read_receipt(UUID, TEXT, UUID) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION __P__.read_receipt(UUID, TEXT, UUID) TO __P___caller; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java new file mode 100644 index 0000000000..a067af1d91 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClient.java @@ -0,0 +1,155 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for Account's distinct selected-owner HELD read. */ +public final class AccountSelectedOwnerIntakeAuthorizationGrpcClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationReadServiceBlockingStub> + implements SelectedOwnerIntakeAuthorizationReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountSelectedOwnerIntakeAuthorizationGrpcClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountSelectedOwnerIntakeAuthorizationGrpcClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) + throw new IllegalStateException("Account selected-owner authorization client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account selected-owner authorization stub unavailable"); + initialized = true; + } + + /** Returns only Account's exact echoed HELD result, outside ambient SQL and synchronization. */ + @Override + public SelectedOwnerIntakeAuthorizationReadEvidence read( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account selected-owner authorization read must run outside SQL"); + } + Objects.requireNonNull(request, "authorization-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) + throw new IllegalArgumentException( + "Account selected-owner authorization read must use the configured namespace"); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readHeldSelectedOwnerIntakeAuthorization( + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest(request)); + try { + return SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid selected-owner HELD authorization evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountSelectedOwnerIntakeAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) + throw new IllegalStateException( + "Account selected-owner authorization client is not initialized and available"); + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) + throw new IllegalArgumentException( + "Account selected-owner authorization read requires workload mTLS"); + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) + throw new IllegalArgumentException( + "Account selected-owner authorization read requires file-backed certificate, key, and CA material"); + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) + throw new IllegalArgumentException( + "Account selected-owner authorization read requires file-backed certificate, key, and CA material"); + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account selected-owner authorization read " + label + " must be a file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) + throw new IllegalArgumentException( + "Account selected-owner authorization read " + + label + + " must be an existing readable file"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadClient.java new file mode 100644 index 0000000000..54ddf57b05 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadClient.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.common.account.sourceintake; + +/** Account's authenticated held-retention read, separate from original Draft authorization. */ +public interface SelectedOwnerIntakeAuthorizationReadClient { + SelectedOwnerIntakeAuthorizationReadEvidence read( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidence.java new file mode 100644 index 0000000000..9c8f75066e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidence.java @@ -0,0 +1,69 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact lookup identity for reading a finalized selected-owner Account authorization. */ +public record SelectedOwnerIntakeAuthorizationReadEvidence(Request request) { + public static final int SCHEMA_VERSION = 1; + + public SelectedOwnerIntakeAuthorizationReadEvidence { + Objects.requireNonNull(request, "authorization-read request is required"); + } + + /** The binding is lookup evidence only; Account authentication establishes the HELD result. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + SelectedOwnerIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || binding == null + || !targetNamespace.equals(binding.targetNamespace())) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.fenceId()) + || readRequestId.equals(binding.intakeRequestId())) { + throw invalid(); + } + // These accessors reject any owner outside the closed Entity and Automation domains. + Objects.requireNonNull(binding.intendedReader()); + Objects.requireNonNull(binding.purpose()); + } + + public static Request create( + String namespace, SelectedOwnerIntakeAuthorizationBinding binding) { + Objects.requireNonNull(binding, "finalized selected-owner authorization is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (sameIdentity(correlation, binding)); + return new Request(SCHEMA_VERSION, namespace, correlation, binding); + } + + public String intendedReader() { + return binding.intendedReader(); + } + + public String retentionPurpose() { + return binding.purpose(); + } + + private static boolean sameIdentity( + UUID candidate, SelectedOwnerIntakeAuthorizationBinding binding) { + return candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-owner authorization-read evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodec.java new file mode 100644 index 0000000000..efe3a4bc91 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodec.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed HELD-read wire mapping with full request-echo validation. */ +public final class SelectedOwnerIntakeAuthorizationReadGrpcCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + private SelectedOwnerIntakeAuthorizationReadGrpcCodec() {} + + public static ReadHeldSelectedOwnerIntakeAuthorizationRequest toRequest( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request) { + Objects.requireNonNull(request, "authorization-read request is required"); + byte[] bindingBytes = request.binding().canonicalBytes(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Selected-owner authorization exceeds its 16 MiB limit"); + } + var wire = + ReadHeldSelectedOwnerIntakeAuthorizationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setRetentionPurpose(request.retentionPurpose()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(bindingBytes)) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static SelectedOwnerIntakeAuthorizationReadEvidence.Request fromRequest( + ReadHeldSelectedOwnerIntakeAuthorizationRequest wire) { + requireKnownAndWithinBudget(wire); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getReadRequestId()); + byte[] bindingBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Selected-owner authorization size is invalid"); + } + var binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + if (!binding.digest().equals(wire.getIntakeAuthorizationDigest())) + throw invalid("Selected-owner authorization digest differs"); + var request = + new SelectedOwnerIntakeAuthorizationReadEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getReadRequestId()), + binding); + if (!request.intendedReader().equals(wire.getIntendedReader()) + || !request.retentionPurpose().equals(wire.getRetentionPurpose()) + || !toRequest(request).equals(wire)) { + throw invalid("Selected-owner authorization reader, purpose, or request differs"); + } + return request; + } + + public static ReadHeldSelectedOwnerIntakeAuthorizationResponse toHeldResponse( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request) { + var response = + ReadHeldSelectedOwnerIntakeAuthorizationResponse.newBuilder() + .setRequest(toRequest(request)) + .setHeld(true) + .build(); + requireWithinBudget(response.getSerializedSize()); + return response; + } + + public static SelectedOwnerIntakeAuthorizationReadEvidence fromResponse( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request, + ReadHeldSelectedOwnerIntakeAuthorizationResponse response) { + Objects.requireNonNull(request, "authorization-read request is required"); + requireKnownAndWithinBudget(response); + if (!response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || !response.getHeld()) { + throw invalid("Exact held selected-owner authorization response required"); + } + return new SelectedOwnerIntakeAuthorizationReadEvidence(request); + } + + private static void requireKnownAndWithinBudget(Message wire) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) + throw invalid("Missing or oversized selected-owner authorization-read message"); + if (!wire.getUnknownFields().asMap().isEmpty()) + throw invalid("Unknown selected-owner authorization-read fields"); + } + + private static void requireWithinBudget(int size) { + if (size > MAX_WIRE_BYTES) + throw invalid("Selected-owner authorization-read message exceeds 24 MiB"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java new file mode 100644 index 0000000000..d263141833 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +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 org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountSelectedOwnerIntakeAuthorizationGrpcClientTest { + @TempDir Path temporaryDirectory; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresFileBackedWorkloadMtlsAndCanonicalNamespace() { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, plaintext, new GrpcChannelFactory(), "test")) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), "test")) + .isInstanceOf(IllegalArgumentException.class); + + var properties = tlsFiles(); + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, properties, new GrpcChannelFactory(), "not/a/namespace")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsRemoteReadWithAmbientSqlOrSynchronizationBeforeChannelUse() throws IOException { + var client = + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + new ServiceEndpointsProperties(), tlsFiles(), new GrpcChannelFactory(), "test"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(null)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(null)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + client.close(); + } + + private CommonGrpcClientProperties tlsFiles() { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(file("client.crt").toString()); + properties.setPrivateKey(file("client.key").toString()); + properties.setCaCert(file("ca.crt").toString()); + return properties; + } + + private Path file(String name) { + Path path = temporaryDirectory.resolve(name); + try { + return Files.createFile(path); + } catch (IOException failure) { + throw new IllegalStateException(failure); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java new file mode 100644 index 0000000000..02114c823d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java @@ -0,0 +1,186 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import org.junit.jupiter.api.Test; + +/** Synthetic lookup evidence only; Account authentication establishes the HELD result. */ +class SelectedOwnerIntakeAuthorizationReadEvidenceTest { + private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666"); + private static final UUID INTAKE = id("77777777-7777-4777-8777-777777777777"); + private static final UUID READ = id("88888888-8888-4888-8888-888888888888"); + + @Test + void requestDerivesOwnerReaderAndRetentionPurposeForBothClosedOwners() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = binding(owner); + var request = Request.create("test", binding); + + assertThat(request.schemaVersion()).isEqualTo(1); + assertThat(request.targetNamespace()).isEqualTo("test"); + assertThat(request.readRequestId()) + .isNotIn(binding.operationId(), binding.fenceId(), binding.intakeRequestId()); + assertThat(request.intendedReader()).isEqualTo(binding.intendedReader()); + assertThat(request.retentionPurpose()).isEqualTo(binding.purpose()); + assertThat(request.binding()).isSameAs(binding); + } + } + + @Test + void rejectsInvalidNamespaceCorrelationVersionAndBindingNamespace() { + var binding = binding(Owner.ENTITY_MANAGEMENT); + assertThatThrownBy(() -> new Request(1, "not/a/namespace", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(2, "test", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "other", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", OPERATION, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", FENCE, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", INTAKE, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", new UUID(0, 0), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", READ, null)) + .isInstanceOf(IllegalArgumentException.class); + } + + static SelectedOwnerIntakeAuthorizationBinding binding(Owner owner) { + UUID tenant = id("11111111-1111-4111-8111-111111111111"); + UUID actor = id("99999999-9999-4999-8999-999999999999"); + var selected = selected(tenant); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, INTAKE, actor, selected); + var content = content(scope); + return new SelectedOwnerIntakeAuthorizationBinding(content, sources(actor, tenant)); + } + + private static SelectedOwnerIntakeSourceContent content( + SelectedOwnerIntakeSourceReadScope scope) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = snapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] snapshot(String family, DraftCommitBinding selected) { + if ("GAMEPLAY_RULE".equals(family)) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + } + if ("TEMPLATE_CONFIG".equals(family)) + return new TemplateConfigSourceSnapshot( + selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) + .canonicalBytes(); + return GameplayRuleManifest.canonical( + Map.of( + "schema", + "synthetic-test-only/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "family", + family)) + .getBytes(StandardCharsets.UTF_8); + } + + private static List sources(UUID actor, UUID tenant) { + var values = new ArrayList(); + values.add(evidence(SourceKind.TENANT, tenant.toString(), "tenant")); + values.add(evidence(SourceKind.ACCOUNT, actor.toString(), "account")); + values.add(evidence(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership")); + return values; + } + + private static SourceEvidence evidence(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected(UUID tenant) { + UUID version = id("22222222-2222-4222-8222-222222222222"); + return DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), + Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + version.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java new file mode 100644 index 0000000000..c2c0d07d48 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java @@ -0,0 +1,174 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerIntakeAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Synthetic protobuf integrity cases only; HELD comes from Account's authenticated read. */ +class SelectedOwnerIntakeAuthorizationReadGrpcCodecTest { + @Test + void roundTripsClosedEntityAndAutomationRequestsAndExactHeldEchoes() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(owner); + var request = Request.create("test", binding); + var wire = SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest(request); + + assertThat(wire.getSchemaVersion()).isEqualTo(1); + assertThat(wire.getTargetNamespace()).isEqualTo("test"); + assertThat(wire.getReadRequestId()).isEqualTo(request.readRequestId().toString()); + assertThat(wire.getIntendedReader()).isEqualTo(binding.intendedReader()); + assertThat(wire.getRetentionPurpose()).isEqualTo(binding.purpose()); + assertThat(wire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .isEqualTo(binding.canonicalBytes()); + assertThat(wire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + var decoded = SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromRequest(wire); + assertThat(decoded.schemaVersion()).isEqualTo(request.schemaVersion()); + assertThat(decoded.targetNamespace()).isEqualTo(request.targetNamespace()); + assertThat(decoded.readRequestId()).isEqualTo(request.readRequestId()); + assertThat(decoded.binding().canonicalBytes()).isEqualTo(binding.canonicalBytes()); + + var response = SelectedOwnerIntakeAuthorizationReadGrpcCodec.toHeldResponse(request); + assertThat(response.getRequest()).isEqualTo(wire); + assertThat(response.getHeld()).isTrue(); + assertThat(SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse(request, response)) + .isEqualTo(new SelectedOwnerIntakeAuthorizationReadEvidence(request)); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + } + } + + @Test + void rejectsChangedClosedPurposeReaderNamespaceVersionDigestAndUuid() { + var request = + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT))); + for (var changed : + List.of( + request.toBuilder().setSchemaVersion(2).build(), + request.toBuilder().setTargetNamespace("other").build(), + request.toBuilder().setReadRequestId("not-a-uuid").build(), + request.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/account-service") + .build(), + request.toBuilder().setRetentionPurpose("ENTITY_INTAKE_SOURCE").build(), + request.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build())) { + assertThatThrownBy(() -> SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsUnknownFieldsAndMalformedOrOversizedBindings() { + var request = + SelectedOwnerIntakeAuthorizationReadGrpcCodec.toRequest( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( + Owner.AUTOMATION_SCRIPTING))); + var unknown = + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var malformed = + request.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + var oversizedBinding = + request.toBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .build(); + + for (var changed : List.of(unknown, malformed, oversizedBinding)) { + assertThatThrownBy(() -> SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsNonHeldSubstitutedAndUnknownResponses() { + var request = + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT)); + var exact = SelectedOwnerIntakeAuthorizationReadGrpcCodec.toHeldResponse(request); + var notHeld = exact.toBuilder().setHeld(false).build(); + var substituted = + exact.toBuilder() + .setRequest( + exact.getRequest().toBuilder() + .setReadRequestId("12121212-1212-4212-8212-121212121212")) + .build(); + var unknown = + exact.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var nestedUnknown = + exact.toBuilder() + .setRequest( + exact.getRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build())) + .build(); + for (var changed : List.of(notHeld, substituted, unknown, nestedUnknown)) { + assertThatThrownBy( + () -> SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse( + request, ReadHeldSelectedOwnerIntakeAuthorizationResponse.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsWireMessagesBeyondTheTwentyFourMibBudget() { + byte[] oversizedBytes = + new byte[SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES + 1]; + var oversized = + ReadHeldSelectedOwnerIntakeAuthorizationRequest.newBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(oversizedBytes)) + .build(); + assertThat(oversized.getSerializedSize()) + .isGreaterThan(SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + assertThatThrownBy(() -> SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromRequest(oversized)) + .isInstanceOf(IllegalArgumentException.class); + + var oversizedResponse = + ReadHeldSelectedOwnerIntakeAuthorizationResponse.newBuilder() + .setRequest(oversized) + .setHeld(true) + .build(); + assertThat(oversizedResponse.getSerializedSize()) + .isGreaterThan(SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( + Owner.ENTITY_MANAGEMENT)), + oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index cb588dd7fe..ee33a2aebb 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -231,9 +231,12 @@ import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.jooq.impl.DataSourceConnectionProvider; +import org.jooq.impl.DefaultConfiguration; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mapstruct.factory.Mappers; +import org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -2284,11 +2287,12 @@ private static Store serviceStore(PostgreSQLContainer postgres, String servic .locations(migrationLocation(service)) .load() .migrate(); - return new Store( - DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES), - new DataSourceTransactionManager(data), - null, - null); + var transactions = new DataSourceTransactionManager(data); + var configuration = new DefaultConfiguration(); + configuration.set(SQLDialect.POSTGRES); + configuration.set(new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(data))); + configuration.set(new SpringTransactionProvider(transactions)); + return new Store(DSL.using(configuration), transactions, null, null); } private static String migrationLocation(String service) { From 51dc2ef1cc2eeb3117e825447add4766ef599f0a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 19:09:57 +1300 Subject: [PATCH 076/129] Bind selected-owner World closure reads to exact Account authorization --- .../account-service/api-contracts.md | 2 + .../world-management-service/api-contracts.md | 4 + .../runtime-and-data.md | 2 +- ...ame-authoring-publishing-and-activation.md | 4 + ...ake_world_closure_authorization_read.proto | 35 ++ .../selected_owner_world_inventory_read.proto | 38 ++ ...ldClosureAuthorizationReadGrpcService.java | 88 ++++ ...eWorldClosureAuthorizationReadService.java | 72 +++ ...osureAuthorizationReadGrpcServiceTest.java | 222 ++++++++ ...ldClosureAuthorizationReadServiceTest.java | 159 ++++++ ...keWorldClosureAuthorizationGrpcClient.java | 158 ++++++ ...keWorldClosureAuthorizationReadClient.java | 7 + ...WorldClosureAuthorizationReadEvidence.java | 72 +++ ...orldClosureAuthorizationReadGrpcCodec.java | 104 ++++ ...SelectedOwnerWorldInventoryReadClient.java | 7 + ...lectedOwnerWorldInventoryReadEvidence.java | 125 +++++ ...ectedOwnerWorldInventoryReadGrpcCodec.java | 180 +++++++ ...electedDraftPublicationFreezeEvidence.java | 12 + ...WorldSelectedOwnerInventoryGrpcClient.java | 148 ++++++ ...rldClosureAuthorizationGrpcClientTest.java | 100 ++++ ...dClosureAuthorizationReadEvidenceTest.java | 57 ++ ...ClosureAuthorizationReadGrpcCodecTest.java | 184 +++++++ ...wnerWorldInventoryRecipientFieldsTest.java | 495 +++++++++++++++++ ...dOwnerWorldInventoryReadGrpcCodecTest.java | 40 ++ ...SelectedOwnerInventoryReadGrpcService.java | 142 +++++ ...orldSelectedOwnerInventoryReadService.java | 90 ++++ ...blicationArtifactInventoryReadService.java | 6 + ...SelectedOwnerInventoryReadServiceTest.java | 496 ++++++++++++++++++ 28 files changed, 3048 insertions(+), 1 deletion(-) create mode 100644 protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto create mode 100644 protos/world-management/v1/selected_owner_world_inventory_read.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodecTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 226f6cb39e..93cfade658 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -114,6 +114,8 @@ The distinct finalized integrity envelope uses `account-entity-intake-authorizat The standalone [`AccountSelectedOwnerIntakeAuthorizationReadService.ReadHeldSelectedOwnerIntakeAuthorization`](../../../../protos/account/v1/selected_owner_intake_authorization_read.proto) reads that original finalized order, not its preliminary reservation. Its closed schema-version-1 request binds namespace, an independent nonzero read correlation distinct from the retained operation/fence/intake request, the exact derived owner reader and retention purpose, and the full original binding bytes/digest. Account authenticates same-namespace Entity or Automation and rejects end-user context before decoding; after decoding, the actual peer must be that binding's exact recipient. An independent writable `READ COMMITTED` transaction locks and compares the original authorization, reservation, creator evidence and complete source participation. Success echoes the entire request unchanged with `held=true`; missing, changed, aborted, malformed, mismatched or unavailable evidence denies. The file-backed mTLS client pins Account, uses a five-second deadline, rejects ambient SQL/synchronization and enforces a separate 24 MiB wire budget without expanding the 16 MiB binding limit. This sampled HELD read cannot create/finalize/settle an order, allocate a replacement identity, renew authority or prove continuous protection through the owner's commit, complete census or a terminal receipt. The unregistered components and their proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The separate [`AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.ReadHeldSelectedOwnerWorldClosureAuthorization`](../../../../protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto) permits World to independently verify that exact finalized Entity or Automation order before returning the selected World closure. Its outer recipient is the exact same-namespace World workload, and its closed purpose is respectively `ENTITY_INTAKE_WORLD_CLOSURE_READ` or `AUTOMATION_INTAKE_WORLD_CLOSURE_READ`. The inner original authorization retains its Entity or Automation recipient, retention purpose, operation, fence, intake request, complete content and source evidence unchanged. The request binds schema version 1, namespace, an independent nonzero read correlation, and the full original bytes and digest; success echoes it unchanged with `held=true`. Account authenticates World and rejects end-user context before decoding, then locks and verifies the exact original finalized order and source participation in an independent writable `READ COMMITTED` transaction. The existing Entity/Automation recipient read is not widened. World must obtain and validate this confirmation directly over authenticated Account mTLS outside SQL; caller-forwarded bytes or a digest do not establish Account authorization. The five-second deadline, 24 MiB wire budget and unchanged 16 MiB binding bound apply. This is permission for an exact retained closure read, not an owner census, source-mutation grant, receipt, settlement or continuous-through-commit proof; an unavailable or mismatched confirmation denies the read. + The distinct [`AccountSelectedOwnerIntakeSourceReadService.ReadSourceScope`](../../../../protos/account/v1/selected_owner_intake_source_read_service.proto) confirms only the retained preliminary Entity or Automation reservation. Account authenticates the exact configured same-namespace Game Design workload and rejects authenticated end-user context before decoding or storage. The closed schema-version-1 request binds namespace, independent nonzero transport correlation, derived Account reader and closed purpose, and the original scope bytes and digest. Account revalidates its own original creator and source participation in independent transactions around the external registry read; neither a client digest nor peer identity creates a reservation. A successful response echoes the complete request unchanged and confirms only that preliminary scope. Missing, expired, changed, malformed or unavailable evidence denies. The canonical scope remains bounded to 4 MiB; the separately enforced request and response wire budget is 8 MiB, including echo and framing. The file-backed mTLS client pins the Account server, applies a five-second deadline and rejects ambient SQL or synchronization. This standalone method has no finalized-retention branch, supplies no census or owner receipt, and does not register or activate a runtime path. Game Design must finish this authenticated Account confirmation outside SQL before reading or returning any selected source content. `IssueConnectToken` is not a gRPC method. It is the local Account application operation behind the REST `POST /auth/connect-token` route documented below; no `IssueConnectToken` RPC or protobuf transport is implied. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 6a0e372112..cd7289147e 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -130,6 +130,10 @@ For the selected-Draft producer, World also returns the immutable `worldIntakeRe The selected-release artifact inventory/read must authenticate Game Design before content access and return the exact immutable inventory retained with the qualified selected graph and freeze. Its closed-model completeness, source bindings and artifact requiredness are owned by [World runtime and data](runtime-and-data.md#complete-selected-release-artifact-inventory). Missing or mismatched inventory evidence cannot be represented as an empty artifact list, and this owner read confers neither Account settlement nor release/admission authority. +The separate [`WorldSelectedOwnerInventoryReadService.ReadSelectedOwnerWorldInventory`](../../../../protos/world-management/v1/selected_owner_world_inventory_read.proto) serves the exact same-namespace Entity or Automation recipient of a finalized selected-owner intake order, without widening the Game Design-only publication method. It authenticates that concrete recipient and rejects end-user context before decoding. Its closed schema-version-1 request binds namespace, independent nonzero read correlation, derived owner-specific closure-read purpose and recipient, the complete original Account intake authorization bytes/digest, and the exact original World freeze request and committed acknowledgement. World compares the full selected `DraftCommitBinding` in the intake order with the publication order's selected commit, including target provenance, operation and revision identities; tenant/version equality alone is insufficient. Historical template declarations retain their creating revision/application evidence rather than being rewritten to this selected commit. + +Before content access, World obtains its own exact Account-authenticated confirmation through the [Account closure-read contract](../account-service/api-contracts.md), outside ambient SQL or synchronization. It then verifies the retained World attempt, original Account publication order and immutable inventory using the same complete original freeze/acknowledgement checks as the Game Design read; it does not recapture mutable source or allocate another freeze. Success echoes the full request unchanged and returns the canonical typed public inventory and digest. The file-backed mTLS client pins World and applies a five-second deadline. This separate transport admits at most 32 MiB per wire message and 8 MiB of canonical inventory, preserving the original 16 MiB intake-binding and 1 MiB publication-binding bounds; oversize denies the complete read, never truncates the inventory or claims unsupported content is empty. Missing or conflicting Account confirmation, source correlation, retained rows, inventory or echo denies. This read alone neither proves the receiving owner's census/retention nor releases Account participation, emits an owner receipt, publishes a release or admits gameplay. Runtime registration and physical proof remain separately tracked. + Every Draft `ApplyWorldDesignMutation` must first lock and check the same owner-freeze row for its `(tenantId, versionId)` target, including an ordinary or otherwise unbound mutation that does not carry a publication request identity. An ordinary mutation may proceed only while the owner row is in its writable `OPEN` state with no active publication freeze. A publication-bound mutation must additionally carry `publicationRequestId`, the exact `requestDigest`, the exact observed Game Design `versionStateEpoch`, and the exact WMS `publicationFence` from that acknowledgement, so it cannot be admitted before the fence exists. It may execute in `FROZEN` only when it is one of the explicitly pre-authorized final publication mutations covered by that request digest; `FROZEN` is not reopened for arbitrary Draft writes, and an unbound or mismatched mutation remains rejected. The final publication digest checkpoint includes the result of any such authorized mutation, and the owner must not accept another mutation after that bounded publication step. Both forms reject or drain stale or mismatched evidence, `PUBLISHED`, `RECONCILIATION_REQUIRED`, and any unauthorized `FROZEN` phase; an `ABORTED` attempt remains closed to ordinary writes until its failed or ambiguous outcome is reconciled and the owner row is reopened without accepting the old fence. A pre-freeze writer that already holds the row lock may finish before the acknowledgement; no writer reaching the lock afterward may commit unless it is the exact pre-authorized publication-bound mutation. The owner mutation result and updated digest checkpoint remain bound to the applicable request, digest, and fence. Game Design completes the handoff through one outcome-typed terminal operation, `CompleteVersionPublication`, carrying exactly `tenantId`, `versionId`, `publicationRequestId`, `publishWorkflowId`, `requestDigest`, `publicationFence`, `outcome`, and the final owner evidence. The cross-service field bindings are canonical: Game Design `publishRequestId` is WMS `publicationRequestId`; Game Design `publishWorkflowId` is the durable publication-workflow identity for the attempt and is required as explicit input and evidence; Game Design `publishedReleaseBundleRef` is WMS `publishedReleaseBundleId`; and each Game Design participant `commitId` is WMS `appliedCommitId`. `outcome=PUBLISHED` requires the immutable release evidence `{publishedReleaseBundleId, publishedReleaseBundleDigest, publishWorkflowId, versionStateEpoch}` plus the final WMS digest checkpoint `{appliedCommitId, contentDigest, digestSchemaVersion}`. Every participant digest and artifact evidence item is bound under that same outer `publishWorkflowId`, and WMS exact-compares the workflow identity across the request, release bundle, participant attestations, and stored publication attempt; any mismatch, omission, or incomplete binding fails closed as an idempotency or reconciliation conflict. WMS records that evidence and atomically advances the row to `PUBLISHED`, after which all later Draft mutations with that fence are rejected. `outcome=ABORTED` requires the same request/fence/workflow identity and reconciled no-publication evidence, records the terminal abort, and permits Draft writes only after the failed/ambiguous Game Design attempt has been reconciled and the old fence is no longer accepted. The operation authenticates the Game Design caller and never treats a Temporal completion as owner proof. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 8e25f8aa30..fc704d598d 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -215,7 +215,7 @@ In the initial slice, exported world artifacts such as navmesh/path-graph bundle World owns a typed, authenticated, immutable `COMPLETE` inventory for the exact selected, retained `APPLIED` graph. It binds the canonical tenant/version/commit, original source and application identities, complete affected scopes and applied epochs, exact Account publication-order identity and fence, topology result and graph digest, and the publication freeze/checkpoint. World captures and durably reads back that inventory under the same owner lock as its qualified first freeze; a caller-supplied inventory or later current-state sample cannot replace the selected graph. Exact retries preserve the original inventory rather than reclassifying mutable source state. -The authenticated owner read takes the exact original freeze request and committed acknowledgement as lookup identity, verifies them against the retained attempt and original Account order, and returns only the closed canonical public inventory and its public-view digest. Its same-namespace Game Design workload check precedes parsing and storage access; end-user context and ambient owner transactions are rejected. Private numeric owner/source keys and raw Account binding bytes remain outside the public inventory. Public region-generator and spawn-binding inputs use unique canonical UUID-string order, independently of the retained private envelope's source order. This projection never rewrites private history. Byte/digest validation alone does not authenticate the producer; the client must verify the concrete World workload identity over mTLS. +The authenticated publication-owner read takes the exact original freeze request and committed acknowledgement as lookup identity, verifies them against the retained attempt and original Account order, and returns only the closed canonical public inventory and its public-view digest. Its same-namespace Game Design workload check precedes parsing and storage access; end-user context and ambient owner transactions are rejected. The distinct Entity/Automation selected-owner read defined in [World API contracts](api-contracts.md#publication-freeze-and-terminal-handoff-target-state) uses this same immutable storage readback only after its own recipient authentication, independent Account confirmation and full selected-commit correlation; it does not widen the publication-owner method. Private numeric owner/source keys and raw Account binding bytes remain outside the public inventory. Public region-generator and spawn-binding inputs use unique canonical UUID-string order, independently of the retained private envelope's source order. This projection never rewrites private history. Byte/digest validation alone does not authenticate the producer; the client must verify the concrete World workload identity over mTLS. The inventory identifies a versioned, closed source model and enumerates all six current topology families from the digest manifest, including explicit zero counts. Its requiredness evaluation covers the complete typed topology, region generator type/parameters, generation-rule name/scope/value, and typed spawn bindings. The public inventory schema v2 also carries the exact original graph's version-1 selected-inbound declaration for loot-reference roots and attachments, behavior selections and bindings, and Automation hooks, script references, and target bindings. Its checkpoint must be World digest schema `4`; legacy inventory/v1 remains paired with World/3 and is read only from its exact retained history. Only the complete fixed-order all-zero inbound vector is supported; nonempty or opaque values are rejected because no member grammar or producer/readback contract is established. A missing declaration in older graph/inventory bytes remains unavailable evidence and is never normalized to empty. New graph/3 and inventory/v2 bytes retain the source-authored declaration; exact retries preserve the original bytes and do not recapture mutable source state. Unknown schemas, fields, families, omitted requiredness inputs, or unrepresentable generation semantics deny `COMPLETE`; missing producer rows or runtime consumers never establish that an artifact is unnecessary. The direct-authored room/exit model uses its persisted directed edges and does not require a separate generated navigation bundle; typed room-bound spawn references alone do not change that rule. Opaque generation inputs cannot inherit this classification without a defined, proved requiredness interpretation. 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 376599e0bf..0958d4d533 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Exact source `c16370dc158100da94b19619c23f7b1f05a11959` [Validation run 38027144761](https://github.com/benhook1013/FireMUD/actions/runs/38027144761) ended cancelled with a failed required gate. Originating Account XML records 285 executions, six failures and no skips: five production admission-confirmation WAL-coverage denials and one isolated prototype denial. Both V132 finalization cases and all three V131 observation cases pass. All ten prototype definitions execute: nine pass, including quiet cold/warm entry, while the privilege case completes its twelve denial assertions but fails the subsequent valid hostile-search-path confirmation with the flush frontier 128 bytes behind its entry upper bound despite about fourteen seconds of remaining original validity. The WAL's origin is not established. These positives are feasibility evidence, not production adoption; no warming, forced flush, marker write or deadline extension is applied to conceal the failed entry. World executes all 221 integration cases without failures or skips; Game Design is cancelled without originating XML, so no new Game Design proof is claimed. CI identifies merge `1e493b96dfc334590d96f0c3f04a77917f12891a` and the merge message's base `fe15a31f274b1c9850dd388e83faf540916ee8a3`; the tree and ordered parent objects are not independently verified. This is not recorded-parent alignment, full original-COMMIT durability proof or runtime activation. + +The distinct, unregistered selected-owner World closure read now authenticates the exact Entity or Automation recipient, preserves its original finalized Account binding and original World freeze, obtains separate authenticated Account confirmation outside SQL, and returns only the unchanged retained typed inventory. The Game Design publication read remains Game Design-only. The affected Common/Account/World full checks and boot JARs pass in 2m58s: 573, 1,278 and 648 unit cases respectively, without failures, errors or unit skips. Account executes seven non-container integration cases and skips 270; World executes one and skips 220 without Docker. A complete request/response roundtrip exposed object-identity comparison of an otherwise identical freeze; the correction compares the full request and acknowledgement and preserves changed-acknowledgement rejection. The final Common full check, formatting, static checks, links and Markdown pass in 3m40s with 576 unit cases and no failures, errors or skips, including four complete recipient/echo/inventory cases. These are bounded codec, synthetic mTLS and mocked ordering tests, not database-backed closure disclosure, complete owner census or terminal receipt proof. Continuous participation follows the existing pending source-writer exclusion, not this sampled confirmation; exact Entity/Automation terminal settlement remains open. Separately approved Account protection through the original Game Session admission commit is under construction, distinct from V129 World settlement and V131 finite observation; no runtime registration or activation follows. + Distinct Account selected-owner finalization retains the complete six-family content, original reservation tuple, creator evidence and full held source vector in V132's append-only authorization and child rows. The unregistered producer reads authenticated source outside SQL, revalidates creator/source evidence before finalization, and reads back the exact original result; lost acknowledgements recover the same binding without another reservation. Finalization excludes preliminary abort and source mutation, with no expiry-based settlement. The separate unregistered HELD transport authenticates the exact same-namespace Entity or Automation recipient before decoding, validates the complete unchanged binding/echo, and reads it in an independent writable read-committed Account transaction. Its sample is not continuous protection: the durable source-participation writer exclusion remains pending until a future exact owner-terminal settlement, which is not implemented. Complete owner inventories and authenticated Entity/Automation receipts remain open; stipulated content and issuer fixtures do not prove them. The source-repair and transport batch passes the affected Common/Account/Game Design full checks, Account schema generation, affected boot JARs, formatting, static checks, links and Markdown in 2m57s. XML records 560 Common, 1,270 Account and 551 Game Design unit cases, all without failures, errors or skips; successful unchanged tasks retain results. Account executes seven non-container integration cases and skips 270; Game Design skips all 148 without Docker. All ten isolated protected-entry PostgreSQL prototype cases compile and skip: this is test-only durability feasibility, not a production writer grant, original-COMMIT proof or adoption. Quiet cold/warm success, privilege/forgery denial, snapshot ordering, concurrent original/receipt visibility, lock-wait expiry and exact lost-response recovery require physical execution. Guaranteed catalog-PRUNE provenance and visible-but-unflushed asynchronous original COMMIT are not established by these definitions. The bounded World capture lookup distinguishes the authenticated World reader from its retained original Logging issuer without relaxing Logging issuance/recovery guards. Game Design's genuine release fixture now uses Spring's transaction provider so nested repository work does not prematurely commit its outer publication. PostgreSQL re-execution of both corrections remains required. All new components remain unregistered and activation remains denied. diff --git a/protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto b/protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto new file mode 100644 index 0000000000..fc32c17503 --- /dev/null +++ b/protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone World read of a finalized Entity or Automation intake authorization. This samples +// the original Account authorization and source participation at read time; it does not prove +// continuous commit protection, complete World inventory, or terminal settlement. +service AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService { + rpc ReadHeldSelectedOwnerWorldClosureAuthorization( + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest) + returns (ReadHeldSelectedOwnerWorldClosureAuthorizationResponse); +} + +message ReadHeldSelectedOwnerWorldClosureAuthorizationRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Always the exact same-namespace World Management workload. + string intended_reader = 4; + // ENTITY_INTAKE_WORLD_CLOSURE_READ or AUTOMATION_INTAKE_WORLD_CLOSURE_READ, derived from the + // original binding's owner. + string closure_read_purpose = 5; + // Complete canonical original SelectedOwnerIntakeAuthorizationBinding bytes and SHA-256 digest. + bytes original_intake_authorization_binding = 6; + string intake_authorization_digest = 7; +} + +message ReadHeldSelectedOwnerWorldClosureAuthorizationResponse { + // Echo the complete request unchanged. Only held=true is a successful result. + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest request = 1; + bool held = 2; +} diff --git a/protos/world-management/v1/selected_owner_world_inventory_read.proto b/protos/world-management/v1/selected_owner_world_inventory_read.proto new file mode 100644 index 0000000000..f6f57d9111 --- /dev/null +++ b/protos/world-management/v1/selected_owner_world_inventory_read.proto @@ -0,0 +1,38 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +import "world-management/v1/world_selected_draft_publication_freeze_service.proto"; + +// Standalone recipient-specific read of the retained World inventory for selected Entity or +// Automation source intake. This is read-only and does not alter the Game Design publication read. +service WorldSelectedOwnerInventoryReadService { + rpc ReadSelectedOwnerWorldInventory(ReadSelectedOwnerWorldInventoryRequest) + returns (ReadSelectedOwnerWorldInventoryResponse); +} + +message ReadSelectedOwnerWorldInventoryRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete canonical Account owner-intake authorization binding and its digest. + bytes original_intake_authorization_binding = 4; + string intake_authorization_digest = 5; + // Exact original selected-publication freeze request and committed acknowledgement. + BeginVersionPublicationFreezeRequest freeze_request = 6; + BeginVersionPublicationFreezeResponse freeze_acknowledgement = 7; + // Original Entity/Automation recipient and the distinct recipient-specific closure purpose. + string intended_reader = 8; + string closure_read_purpose = 9; +} + +message ReadSelectedOwnerWorldInventoryResponse { + int32 schema_version = 1; + // Complete request echo; only the public World inventory projection follows. + ReadSelectedOwnerWorldInventoryRequest request = 2; + bytes canonical_public_inventory = 3; + string public_inventory_digest = 4; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService.java new file mode 100644 index 0000000000..7e70c238c2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Standalone receiver: authenticate exact World before parsing a caller-carried binding. */ +public final class AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService + extends AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceImplBase { + private final AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService owner; + private final String namespace; + + public AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService( + AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "World closure authorization reader is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + } + + @Override + public void readHeldSelectedOwnerWorldClosureAuthorization( + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + String peerUri = peer.uri(); + String expectedReader = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !expectedReader.equals(peerUri)) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() + > SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + final SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request decoded; + try { + decoded = SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(decoded.targetNamespace()) || !peerUri.equals(decoded.intendedReader())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + try { + owner.requireHeld(decoded); + observer.onNext( + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toHeldResponse(decoded)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + observer.onError(Status.fromCode(code).asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java new file mode 100644 index 0000000000..c5ecec0bd3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered World HELD read; it neither creates authority nor settles participation. */ +public final class AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final TransactionTemplate ownerTransaction; + private final String namespace; + + public AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService( + AccountSelectedOwnerIntakeSourceReservationRepository repository, + PlatformTransactionManager transactions, + String namespace) { + this.repository = + Objects.requireNonNull(repository, "source reservation repository is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account workload namespace required"); + this.namespace = namespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** Confirms the exact finalized authorization and source locks in an independent transaction. */ + public void requireHeld( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request) { + Objects.requireNonNull(request, "World closure authorization-read request is required"); + requirePeer(namespace, request.intendedReader()); + if (!namespace.equals(request.targetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + try { + ownerTransaction.execute( + ignored -> { + repository.readFinalAuthorization(request.binding()); + return null; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (IllegalArgumentException changedOrAbsent) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE.asRuntimeException(); + } + } + + static void requirePeer(String namespace, String expectedReader) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) throw Status.UNAUTHENTICATED.asRuntimeException(); + String worldReader = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !worldReader.equals(peer.uri()) + || !worldReader.equals(expectedReader)) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java new file mode 100644 index 0000000000..7f031371b8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java @@ -0,0 +1,222 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** Synthetic handler tests only; they do not establish mTLS or PostgreSQL owner proof. */ +class AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest { + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void authenticatesWorldAndRejectsEndUserBeforeParsingOrOwnerAccess() { + var owner = mock(AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.class); + var service = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService(owner, "test"); + var malformed = + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest.newBuilder() + .setTargetNamespace("test") + .setSchemaVersion(-1) + .build(); + + var noPeer = new Collector(); + service.readHeldSelectedOwnerWorldClosureAuthorization(malformed, noPeer); + assertThat(noPeer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + + for (String workload : + List.of( + "account-service", + "game-design-service", + "game-logic-service", + "entity-management-service", + "automation-scripting-service")) { + var denied = new Collector(); + peer("test", workload) + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(malformed, denied)); + assertThat(denied.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } + var otherNamespace = new Collector(); + peer("other", "world-management-service") + .run( + () -> + service.readHeldSelectedOwnerWorldClosureAuthorization(malformed, otherNamespace)); + assertThat(otherNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("44", List.of(), java.util.Map.of()); + try { + var endUser = new Collector(); + peer("test", "world-management-service") + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(malformed, endUser)); + assertThat(endUser.error).isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + + var allowedPeerMalformed = new Collector(); + peer("test", "world-management-service") + .run( + () -> + service.readHeldSelectedOwnerWorldClosureAuthorization( + malformed, allowedPeerMalformed)); + assertThat(allowedPeerMalformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void returnsExactEchoForEntityAndAutomationButRejectsSubstitutedPurposeOrReader() { + var owner = mock(AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.class); + var service = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService(owner, "test"); + + for (Owner domain : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(domain); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + var wire = SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest(request); + var result = new Collector(); + peer("test", "world-management-service") + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(wire, result)); + + assertThat(result.error).isNull(); + assertThat(result.response).isNotNull(); + assertThat(result.response.getRequest()).isEqualTo(wire); + assertThat(result.response.getHeld()).isTrue(); + + for (var changed : + List.of( + wire.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") + .build(), + wire.toBuilder().setClosureReadPurpose("ENTITY_INTAKE_RETENTION").build())) { + var denied = new Collector(); + peer("test", "world-management-service") + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(changed, denied)); + assertThat(denied.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(denied.response).isNull(); + } + } + verify(owner, times(2)).requireHeld(any()); + } + + @Test + void rejectsWrongNamespaceClosedFieldsDigestUnknownFieldsAndMalformedSizes() { + var owner = mock(AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.class); + var service = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + var valid = + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + "test", binding)); + + var wrongNamespace = new Collector(); + peer("test", "world-management-service") + .run( + () -> + service.readHeldSelectedOwnerWorldClosureAuthorization( + valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); + + var changedDigest = + valid.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build(); + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var malformedBinding = + valid.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + var oversizedBinding = + valid.toBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .build(); + for (var malformed : List.of(changedDigest, unknown, malformedBinding, oversizedBinding)) { + var result = new Collector(); + peer("test", "world-management-service") + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(malformed, result)); + assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(result.response).isNull(); + } + verifyNoInteractions(owner); + } + + @Test + void mapsOwnerReadFailureToNoHeldResponse() { + var owner = mock(AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.class); + org.mockito.Mockito.doThrow(Status.FAILED_PRECONDITION.asRuntimeException()) + .when(owner) + .requireHeld(any()); + var service = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + var wire = + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + "test", binding)); + var result = new Collector(); + + peer("test", "world-management-service") + .run(() -> service.readHeldSelectedOwnerWorldClosureAuthorization(wire, result)); + + assertThat(result.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(result.response).isNull(); + } + + private static Context peer(String namespace, String workload) { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + } + + private static final class Collector + implements StreamObserver { + private ReadHeldSelectedOwnerWorldClosureAuthorizationResponse response; + private Status.Code error; + + @Override + public void onNext(ReadHeldSelectedOwnerWorldClosureAuthorizationResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java new file mode 100644 index 0000000000..44b3f51cca --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.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 io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic Account read tests; they do not establish PostgreSQL or owner-terminal proof. */ +class AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest { + private final AccountSelectedOwnerIntakeSourceReservationRepository repository = + mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + + @AfterEach + void clearCallerAndTransactionContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void readsExactEntityAndAutomationBindingsInIndependentReadCommittedTransactions() { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + var service = newService(); + + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(owner); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + asWorldReader(() -> service.requireHeld(request)); + verify(repository).readFinalAuthorization(binding); + } + + var definitions = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions, times(2)).getTransaction(definitions.capture()); + assertThat(definitions.getAllValues()) + .allSatisfy( + definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); + } + + @Test + void independentlyRejectsWrongWorkloadNamespaceAndEndUserBeforeRepositoryAccess() { + var service = newService(); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + + assertCode(Status.Code.UNAUTHENTICATED, () -> service.requireHeld(request)); + asPeer( + "test", + "entity-management-service", + () -> assertCode(Status.Code.PERMISSION_DENIED, () -> service.requireHeld(request))); + asPeer( + "other", + "world-management-service", + () -> assertCode(Status.Code.PERMISSION_DENIED, () -> service.requireHeld(request))); + + SessionContext.setContext("44", List.of(), Map.of()); + try { + asWorldReader( + () -> assertCode(Status.Code.PERMISSION_DENIED, () -> service.requireHeld(request))); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(repository, transactions); + } + + @Test + void rejectsAmbientSqlBeforeStartingOwnerRead() { + var service = newService(); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + asWorldReader( + () -> assertCode(Status.Code.FAILED_PRECONDITION, () -> service.requireHeld(request))); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(repository, transactions); + } + + @Test + void distinguishesAbsentOrChangedAuthorizationFromUnavailableStorage() { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + var service = newService(); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + + org.mockito.Mockito.doThrow(new IllegalArgumentException("not available")) + .when(repository) + .readFinalAuthorization(binding); + asWorldReader( + () -> assertCode(Status.Code.FAILED_PRECONDITION, () -> service.requireHeld(request))); + + org.mockito.Mockito.doThrow(new IllegalStateException("storage unavailable")) + .when(repository) + .readFinalAuthorization(binding); + asWorldReader(() -> assertCode(Status.Code.UNAVAILABLE, () -> service.requireHeld(request))); + } + + private AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService newService() { + return new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService( + repository, transactions, "test"); + } + + private static void asWorldReader(Runnable action) { + asPeer("test", "world-management-service", action); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()) + .run(action); + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(error -> assertThat(Status.fromThrowable(error).getCode()).isEqualTo(expected)); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java new file mode 100644 index 0000000000..1941d4d1ea --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for Account's distinct World closure HELD read. */ +public final class AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceBlockingStub> + implements SelectedOwnerIntakeWorldClosureAuthorizationReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) + throw new IllegalStateException("Account World closure authorization client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("Account World closure authorization stub unavailable"); + initialized = true; + } + + /** Returns only Account's exact echoed HELD result, outside ambient SQL and synchronization. */ + @Override + public SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence readHeld( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account World closure authorization read must run outside SQL"); + } + Objects.requireNonNull(request, "World closure authorization-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) + throw new IllegalArgumentException( + "Account World closure authorization read must use the configured namespace"); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readHeldSelectedOwnerWorldClosureAuthorization( + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest(request)); + try { + return SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid selected-owner World closure HELD evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc.newBlockingStub( + channel) + .withMaxInboundMessageSize( + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceGrpc + .AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) + throw new IllegalStateException( + "Account World closure authorization client is not initialized and available"); + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) + throw new IllegalArgumentException( + "Account World closure authorization read requires workload mTLS"); + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) + throw new IllegalArgumentException( + "Account World closure authorization read requires file-backed certificate, key, and CA material"); + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) + throw new IllegalArgumentException( + "Account World closure authorization read requires file-backed certificate, key, and CA material"); + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account World closure authorization read " + label + " must be a file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) + throw new IllegalArgumentException( + "Account World closure authorization read " + + label + + " must be an existing readable file"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadClient.java new file mode 100644 index 0000000000..01d96dce15 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadClient.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.common.account.sourceintake; + +/** Account client for the distinct selected-owner World closure HELD read. */ +public interface SelectedOwnerIntakeWorldClosureAuthorizationReadClient { + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence readHeld( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.java new file mode 100644 index 0000000000..ba6702a1db --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact lookup identity for World to read a finalized selected-owner Account authorization. */ +public record SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(Request request) { + public static final int SCHEMA_VERSION = 1; + + public SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence { + Objects.requireNonNull(request, "World closure authorization-read request is required"); + } + + /** The original binding is lookup evidence only; Account authentication establishes HELD. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + SelectedOwnerIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || binding == null + || !targetNamespace.equals(binding.targetNamespace())) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + if (readRequestId.equals(binding.operationId()) + || readRequestId.equals(binding.fenceId()) + || readRequestId.equals(binding.intakeRequestId())) { + throw invalid(); + } + Objects.requireNonNull(binding.owner(), "closed Entity or Automation owner is required"); + } + + public static Request create( + String namespace, SelectedOwnerIntakeAuthorizationBinding binding) { + Objects.requireNonNull(binding, "finalized selected-owner authorization is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (sameIdentity(correlation, binding)); + return new Request(SCHEMA_VERSION, namespace, correlation, binding); + } + + public String intendedReader() { + return "spiffe://firemud/ns/" + targetNamespace + "/sa/world-management-service"; + } + + public String closureReadPurpose() { + return switch (binding.owner()) { + case ENTITY_MANAGEMENT -> "ENTITY_INTAKE_WORLD_CLOSURE_READ"; + case AUTOMATION_SCRIPTING -> "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"; + default -> throw invalid(); + }; + } + + private static boolean sameIdentity( + UUID candidate, SelectedOwnerIntakeAuthorizationBinding binding) { + return candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Invalid selected-owner World closure authorization-read evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.java new file mode 100644 index 0000000000..0f8f39131d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed protobuf encoding for Account's distinct World closure HELD read. */ +public final class SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + + private SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec() {} + + public static ReadHeldSelectedOwnerWorldClosureAuthorizationRequest toRequest( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request) { + Objects.requireNonNull(request, "World closure authorization-read request is required"); + byte[] bindingBytes = request.binding().canonicalBytes(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Selected-owner authorization exceeds its 16 MiB limit"); + } + var wire = + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setClosureReadPurpose(request.closureReadPurpose()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(bindingBytes)) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request fromRequest( + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest wire) { + requireKnownAndWithinBudget(wire); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getReadRequestId()); + byte[] bindingBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Selected-owner authorization size is invalid"); + } + var binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + if (!binding.digest().equals(wire.getIntakeAuthorizationDigest())) + throw invalid("Selected-owner authorization digest differs"); + var request = + new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getReadRequestId()), + binding); + if (!request.intendedReader().equals(wire.getIntendedReader()) + || !request.closureReadPurpose().equals(wire.getClosureReadPurpose()) + || !toRequest(request).equals(wire)) { + throw invalid("Selected-owner World reader, purpose, or request differs"); + } + return request; + } + + public static ReadHeldSelectedOwnerWorldClosureAuthorizationResponse toHeldResponse( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request) { + var response = + ReadHeldSelectedOwnerWorldClosureAuthorizationResponse.newBuilder() + .setRequest(toRequest(request)) + .setHeld(true) + .build(); + requireWithinBudget(response.getSerializedSize()); + return response; + } + + public static SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence fromResponse( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request request, + ReadHeldSelectedOwnerWorldClosureAuthorizationResponse response) { + Objects.requireNonNull(request, "World closure authorization-read request is required"); + requireKnownAndWithinBudget(response); + if (!response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || !response.getHeld()) { + throw invalid("Exact held selected-owner World closure authorization response required"); + } + return new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(request); + } + + private static void requireKnownAndWithinBudget(Message wire) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) + throw invalid("Missing or oversized selected-owner World closure read message"); + if (!wire.getUnknownFields().asMap().isEmpty()) + throw invalid("Unknown selected-owner World closure read fields"); + } + + private static void requireWithinBudget(int size) { + if (size > MAX_WIRE_BYTES) + throw invalid("Selected-owner World closure read message exceeds 24 MiB"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadClient.java new file mode 100644 index 0000000000..f164ab8e1f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadClient.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.common.publication; + +/** Authenticated read of the exact retained World inventory for selected owner intake. */ +public interface SelectedOwnerWorldInventoryReadClient { + SelectedOwnerWorldInventoryReadEvidence read( + SelectedOwnerWorldInventoryReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadEvidence.java new file mode 100644 index 0000000000..15a38719d8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadEvidence.java @@ -0,0 +1,125 @@ +package net.firedevops.firemud.common.publication; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact read correlation and public inventory for an Entity or Automation intake. */ +public record SelectedOwnerWorldInventoryReadEvidence( + Request request, WorldSelectedPublicationArtifactInventoryEvidence inventory) { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_INTAKE_AUTHORIZATION_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES; + public static final int MAX_PUBLIC_INVENTORY_BYTES = 8 * 1024 * 1024; + + /** Includes the 16 MiB owner binding, duplicated bounded freeze order, inventory, and framing. */ + public static final int MAX_WIRE_BYTES = 32 * 1024 * 1024; + + public SelectedOwnerWorldInventoryReadEvidence { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(inventory, "inventory"); + if (!request.freezeEvidence().equals(inventory.freezeEvidence()) + || inventory.canonicalBytes().length == 0 + || inventory.canonicalBytes().length > MAX_PUBLIC_INVENTORY_BYTES) { + throw new IllegalArgumentException( + "World owner inventory differs from exact bounded request"); + } + } + + /** A new read UUID is independent from both Account intake and World intake correlations. */ + public static Request create( + String namespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (Request.collides(readRequestId, binding, freezeEvidence)); + return new Request(SCHEMA_VERSION, namespace, readRequestId, binding, freezeEvidence); + } + + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + SelectedOwnerIntakeAuthorizationBinding authorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || readRequestId == null + || new UUID(0L, 0L).equals(readRequestId)) { + throw new IllegalArgumentException("Canonical selected-owner World read identity required"); + } + Objects.requireNonNull(authorizationBinding, "authorizationBinding"); + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + var scope = authorizationBinding.content().scope(); + var freeze = freezeEvidence.request(); + var selected = freeze.accountBinding().input().selection().selectedCommit(); + var publicationBinding = freeze.accountBinding(); + if (!targetNamespace.equals(scope.targetNamespace()) + || !targetNamespace.equals(freeze.targetNamespace()) + || !scope.selected().target().canonicalTenantId().equals(freeze.canonicalTenantId()) + || !scope.selected().target().canonicalVersionId().equals(freeze.canonicalVersionId()) + || !java.util.Arrays.equals(scope.selected().canonicalBytes(), selected.canonicalBytes()) + || collides(readRequestId, authorizationBinding, freezeEvidence) + || readRequestId.equals(publicationBinding.operationId()) + || readRequestId.equals(publicationBinding.fenceId())) { + throw new IllegalArgumentException( + "Selected-owner source binding differs from exact World freeze selection"); + } + String expectedPurpose = + authorizationBinding.owner() == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_RETENTION" + : "AUTOMATION_INTAKE_RETENTION"; + if (!authorizationBinding.purpose().equals(expectedPurpose) + || !authorizationBinding + .intendedReader() + .equals(ownerIntendedReader(authorizationBinding.owner(), targetNamespace))) { + throw new IllegalArgumentException( + "Original selected-owner recipient or retention purpose differs"); + } + if (authorizationBinding.canonicalBytes().length > MAX_INTAKE_AUTHORIZATION_BYTES) { + throw new IllegalArgumentException("Selected-owner authorization binding exceeds limit"); + } + } + + public static Request create( + String namespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + return SelectedOwnerWorldInventoryReadEvidence.create(namespace, binding, freezeEvidence); + } + + public String closureReadPurpose() { + return authorizationBinding.owner() == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" + : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"; + } + + private static String ownerIntendedReader(Owner owner, String namespace) { + String workload = + owner == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"; + return "spiffe://firemud/ns/" + namespace + "/sa/" + workload; + } + + private static boolean collides( + UUID candidate, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var account = freezeEvidence.request().accountBinding(); + var acknowledgement = freezeEvidence.acknowledgement(); + return candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()) + || candidate.equals(account.operationId()) + || candidate.equals(account.fenceId()) + || candidate.equals(acknowledgement.intakeRequestId()) + || candidate.equals(acknowledgement.publicationFence()); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java new file mode 100644 index 0000000000..44b36cf560 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodec.java @@ -0,0 +1,180 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence.Request; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryResponse; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedPublicationArtifactInventoryResponse; + +/** Closed wire mapping for the bounded recipient-specific World inventory read. */ +public final class SelectedOwnerWorldInventoryReadGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private SelectedOwnerWorldInventoryReadGrpcCodec() {} + + public static ReadSelectedOwnerWorldInventoryRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var freeze = request.freezeEvidence(); + var result = + ReadSelectedOwnerWorldInventoryRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom(request.authorizationBinding().canonicalBytes())) + .setIntakeAuthorizationDigest(request.authorizationBinding().digest()) + .setFreezeRequest( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())) + .setFreezeAcknowledgement( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())) + .setIntendedReader(request.authorizationBinding().intendedReader()) + .setClosureReadPurpose(request.closureReadPurpose()) + .build(); + requireWireSize(result.getSerializedSize()); + return result; + } + + /** Decode only after the receiver has authenticated an allowed owner peer. */ + public static Request fromRequest(ReadSelectedOwnerWorldInventoryRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize(request.getSerializedSize()); + requireNoUnknownFields(request, "ReadSelectedOwnerWorldInventoryRequest"); + if (request.getSchemaVersion() != SelectedOwnerWorldInventoryReadEvidence.SCHEMA_VERSION + || request.getTargetNamespace().isEmpty()) { + throw invalid("Canonical selected-owner World inventory read identity is required"); + } + UUID readRequestId = canonicalUuid(request.getReadRequestId(), "readRequestId"); + byte[] bindingBytes = request.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 + || bindingBytes.length + > SelectedOwnerWorldInventoryReadEvidence.MAX_INTAKE_AUTHORIZATION_BYTES) { + throw invalid("Selected-owner authorization binding is absent or oversized"); + } + SelectedOwnerIntakeAuthorizationBinding binding; + try { + binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + } catch (RuntimeException invalidBinding) { + throw invalid("Selected-owner authorization binding is invalid", invalidBinding); + } + if (!binding.digest().equals(request.getIntakeAuthorizationDigest())) { + throw invalid("Selected-owner authorization binding digest differs"); + } + if (!binding.intendedReader().equals(request.getIntendedReader())) { + throw invalid("Original selected-owner recipient differs"); + } + String expectedPurpose = + binding.owner() == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" + : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"; + if (!expectedPurpose.equals(request.getClosureReadPurpose())) { + throw invalid("Selected-owner World closure read purpose differs"); + } + if (!request.hasFreezeRequest() || !request.hasFreezeAcknowledgement()) { + throw invalid("Complete selected-owner World inventory freeze evidence is required"); + } + var freezeRequest = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(request.getFreezeRequest()); + var freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, request.getFreezeAcknowledgement()); + return new Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + readRequestId, + binding, + freezeEvidence); + } + + public static ReadSelectedOwnerWorldInventoryResponse toResponse( + Request request, WorldSelectedPublicationArtifactInventoryEvidence inventory) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(inventory, "inventory"); + if (!request.freezeEvidence().equals(inventory.freezeEvidence())) { + throw invalid("World inventory is not bound to the exact selected-owner freeze"); + } + byte[] inventoryBytes = inventory.canonicalBytes(); + if (inventoryBytes.length == 0 + || inventoryBytes.length + > SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES) { + throw invalid("World public inventory is absent or exceeds the recipient-read limit"); + } + var response = + ReadSelectedOwnerWorldInventoryResponse.newBuilder() + .setSchemaVersion(SelectedOwnerWorldInventoryReadEvidence.SCHEMA_VERSION) + .setRequest(toRequest(request)) + .setCanonicalPublicInventory(ByteString.copyFrom(inventoryBytes)) + .setPublicInventoryDigest(inventory.digest()) + .build(); + requireWireSize(response.getSerializedSize()); + return response; + } + + /** Requires the exact echoed request, then validates the existing typed inventory codec. */ + public static SelectedOwnerWorldInventoryReadEvidence fromResponse( + Request expected, ReadSelectedOwnerWorldInventoryResponse response) { + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(response, "response"); + requireWireSize(response.getSerializedSize()); + requireNoUnknownFields(response, "ReadSelectedOwnerWorldInventoryResponse"); + if (response.getSchemaVersion() != SelectedOwnerWorldInventoryReadEvidence.SCHEMA_VERSION + || !response.hasRequest() + || !response.getRequest().equals(toRequest(expected))) { + throw invalid("World changed the exact selected-owner inventory read request"); + } + requireNoUnknownFields(response.getRequest(), "echoed ReadSelectedOwnerWorldInventoryRequest"); + byte[] inventoryBytes = response.getCanonicalPublicInventory().toByteArray(); + if (inventoryBytes.length == 0 + || inventoryBytes.length + > SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES + || response.getPublicInventoryDigest().isEmpty()) { + throw invalid("World response lacks a complete bounded public inventory"); + } + var inventoryResponse = + ReadSelectedPublicationArtifactInventoryResponse.newBuilder() + .setSchemaVersion(1) + .setCanonicalPublicInventory(ByteString.copyFrom(inventoryBytes)) + .setPublicInventoryDigest(response.getPublicInventoryDigest()) + .build(); + var inventory = + WorldSelectedPublicationArtifactInventoryGrpcCodec.fromResponse( + expected.freezeEvidence(), inventoryResponse); + return new SelectedOwnerWorldInventoryReadEvidence(expected, inventory); + } + + private static UUID canonicalUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw invalid(label + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(label + " must be a canonical non-nil UUID", malformed); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid(label + " contains unsupported fields"); + } + } + + private static void requireWireSize(int size) { + if (size > SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES) { + throw invalid("Selected-owner World inventory message exceeds its wire limit"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java index e4a2dce3ac..5435410efa 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeEvidence.java @@ -27,6 +27,18 @@ public Acknowledgement acknowledgement() { return acknowledgement; } + @Override + public boolean equals(Object other) { + return other instanceof WorldSelectedDraftPublicationFreezeEvidence that + && request.equals(that.request) + && acknowledgement.equals(that.acknowledgement); + } + + @Override + public int hashCode() { + return Objects.hash(request, acknowledgement); + } + /** Complete exact request from Game Design; its Account bytes are correlation, not authority. */ public record Request( int schemaVersion, diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java new file mode 100644 index 0000000000..a9d352baac --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedOwnerInventoryGrpcClient.java @@ -0,0 +1,148 @@ +package net.firedevops.firemud.common.publication; + +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.WorldSelectedOwnerInventoryReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for the recipient-specific retained World inventory read. */ +public final class WorldSelectedOwnerInventoryGrpcClient + extends AbstractReloadingBlockingGrpcClient< + WorldSelectedOwnerInventoryReadServiceGrpc + .WorldSelectedOwnerInventoryReadServiceBlockingStub> + implements SelectedOwnerWorldInventoryReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldSelectedOwnerInventoryGrpcClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldSelectedOwnerInventoryGrpcClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("World owner inventory client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World owner inventory stub unavailable"); + } + initialized = true; + } + + @Override + public SelectedOwnerWorldInventoryReadEvidence read( + SelectedOwnerWorldInventoryReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("World owner inventory read requires no ambient SQL"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException("World owner inventory namespace differs from client"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedOwnerWorldInventory( + SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(request)); + try { + return SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("World returned invalid owner inventory evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldSelectedOwnerInventoryReadServiceGrpc + .WorldSelectedOwnerInventoryReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldSelectedOwnerInventoryReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldSelectedOwnerInventoryReadServiceGrpc + .WorldSelectedOwnerInventoryReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException("World owner inventory client is not initialized"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World owner inventory read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World owner inventory read requires file-backed TLS files"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World owner inventory read requires file-backed TLS files"); + } + Path path = Path.of(pathText); + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World owner inventory read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java new file mode 100644 index 0000000000..3217cdea5a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java @@ -0,0 +1,100 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +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.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest { + @TempDir Path temporaryDirectory; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresFileBackedWorkloadMtlsAndCanonicalNamespace() { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + endpoints, plaintext, new GrpcChannelFactory(), "test")) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), "test")) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + endpoints, tlsFiles(), new GrpcChannelFactory(), "not/a/namespace")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsRemoteReadWithAmbientSqlOrSynchronizationBeforeChannelUse() throws IOException { + var client = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + new ServiceEndpointsProperties(), tlsFiles(), new GrpcChannelFactory(), "test"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.readHeld(null)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.readHeld(null)).isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + client.close(); + } + + @Test + void rejectsRequestOutsideConfiguredNamespaceBeforeChannelUse() throws IOException { + var client = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + new ServiceEndpointsProperties(), tlsFiles(), new GrpcChannelFactory(), "other"); + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); + + assertThatThrownBy(() -> client.readHeld(request)).isInstanceOf(IllegalArgumentException.class); + client.close(); + } + + private CommonGrpcClientProperties tlsFiles() { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(file("client.crt").toString()); + properties.setPrivateKey(file("client.key").toString()); + properties.setCaCert(file("ca.crt").toString()); + return properties; + } + + private Path file(String name) { + Path path = temporaryDirectory.resolve(name); + try { + return Files.createFile(path); + } catch (IOException failure) { + throw new IllegalStateException(failure); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidenceTest.java new file mode 100644 index 0000000000..2a08a82d03 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadEvidenceTest.java @@ -0,0 +1,57 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Synthetic lookup evidence only; Account authentication establishes the HELD result. */ +class SelectedOwnerIntakeWorldClosureAuthorizationReadEvidenceTest { + private static final UUID READ = UUID.fromString("88888888-8888-4888-8888-888888888888"); + + @Test + void derivesWorldReaderAndClosedPurposeFromBothOriginalOwnerBindings() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(owner); + var request = Request.create("test", binding); + + assertThat(request.schemaVersion()).isEqualTo(1); + assertThat(request.targetNamespace()).isEqualTo("test"); + assertThat(request.readRequestId()) + .isNotIn(binding.operationId(), binding.fenceId(), binding.intakeRequestId()); + assertThat(request.intendedReader()) + .isEqualTo("spiffe://firemud/ns/test/sa/world-management-service"); + assertThat(request.closureReadPurpose()) + .isEqualTo( + owner == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" + : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"); + assertThat(request.binding()).isSameAs(binding); + } + } + + @Test + void rejectsInvalidNamespaceCorrelationVersionAndBindingNamespace() { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + assertThatThrownBy(() -> new Request(1, "not/a/namespace", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(2, "test", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "other", READ, binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", binding.operationId(), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", binding.fenceId(), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", binding.intakeRequestId(), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", new UUID(0, 0), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(1, "test", READ, null)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java new file mode 100644 index 0000000000..e75fee51c6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java @@ -0,0 +1,184 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldSelectedOwnerWorldClosureAuthorizationResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Synthetic protobuf integrity cases only; HELD comes from Account's authenticated read. */ +class SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest { + @Test + void roundTripsClosedOwnerRequestsAndExactHeldEchoes() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(owner); + var request = Request.create("test", binding); + var wire = SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest(request); + + assertThat(wire.getSchemaVersion()).isEqualTo(1); + assertThat(wire.getTargetNamespace()).isEqualTo("test"); + assertThat(wire.getReadRequestId()).isEqualTo(request.readRequestId().toString()); + assertThat(wire.getIntendedReader()).isEqualTo(request.intendedReader()); + assertThat(wire.getClosureReadPurpose()).isEqualTo(request.closureReadPurpose()); + assertThat(wire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .isEqualTo(binding.canonicalBytes()); + assertThat(wire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + var decoded = SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromRequest(wire); + assertThat(decoded.schemaVersion()).isEqualTo(request.schemaVersion()); + assertThat(decoded.targetNamespace()).isEqualTo(request.targetNamespace()); + assertThat(decoded.readRequestId()).isEqualTo(request.readRequestId()); + assertThat(decoded.binding().canonicalBytes()).isEqualTo(binding.canonicalBytes()); + + var response = + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toHeldResponse(request); + assertThat(response.getRequest()).isEqualTo(wire); + assertThat(response.getHeld()).isTrue(); + assertThat( + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + request, response)) + .isEqualTo(new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(request)); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo( + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + } + } + + @Test + void rejectsChangedClosedPurposeReaderNamespaceVersionDigestAndUuid() { + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT))); + for (var changed : + List.of( + request.toBuilder().setSchemaVersion(2).build(), + request.toBuilder().setTargetNamespace("other").build(), + request.toBuilder().setReadRequestId("not-a-uuid").build(), + request.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/account-service") + .build(), + request.toBuilder().setClosureReadPurpose("ENTITY_INTAKE_SOURCE").build(), + request.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build())) { + assertThatThrownBy( + () -> SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsUnknownFieldsAndMalformedOrOversizedBindings() { + var request = + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toRequest( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( + Owner.AUTOMATION_SCRIPTING))); + var unknown = + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var malformed = + request.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + var oversizedBinding = + request.toBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .build(); + + for (var changed : List.of(unknown, malformed, oversizedBinding)) { + assertThatThrownBy( + () -> SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsNonHeldSubstitutedAndUnknownResponses() { + var request = + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT)); + var exact = SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.toHeldResponse(request); + var notHeld = exact.toBuilder().setHeld(false).build(); + var substituted = + exact.toBuilder() + .setRequest( + exact.getRequest().toBuilder() + .setReadRequestId("12121212-1212-4212-8212-121212121212")) + .build(); + var unknown = + exact.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var nestedUnknown = + exact.toBuilder() + .setRequest( + exact.getRequest().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build())) + .build(); + for (var changed : List.of(notHeld, substituted, unknown, nestedUnknown)) { + assertThatThrownBy( + () -> + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + request, + ReadHeldSelectedOwnerWorldClosureAuthorizationResponse.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMessagesBeyondTheTwentyFourMibBudget() { + byte[] oversizedBytes = + new byte[SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES + 1]; + var oversized = + ReadHeldSelectedOwnerWorldClosureAuthorizationRequest.newBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(oversizedBytes)) + .build(); + assertThat(oversized.getSerializedSize()) + .isGreaterThan(SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + assertThatThrownBy( + () -> SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromRequest(oversized)) + .isInstanceOf(IllegalArgumentException.class); + + var oversizedResponse = + ReadHeldSelectedOwnerWorldClosureAuthorizationResponse.newBuilder() + .setRequest(oversized) + .setHeld(true) + .build(); + assertThat(oversizedResponse.getSerializedSize()) + .isGreaterThan(SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); + assertThatThrownBy( + () -> + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( + Owner.ENTITY_MANAGEMENT)), + oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java new file mode 100644 index 0000000000..49be8a3aea --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java @@ -0,0 +1,495 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import org.junit.jupiter.api.Test; + +class SelectedOwnerWorldInventoryRecipientFieldsTest { + @Test + void rejectsChangedOriginalRecipientAndDerivedClosurePurposeForBothOwners() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(owner); + String purpose = + owner == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" + : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"; + var base = + ReadSelectedOwnerWorldInventoryRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(binding.targetNamespace()) + .setReadRequestId("12121212-1212-4212-8212-121212121212") + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(binding.canonicalBytes())) + .setIntakeAuthorizationDigest(binding.digest()) + .setIntendedReader(binding.intendedReader()) + .setClosureReadPurpose(purpose) + .build(); + + assertThatThrownBy(() -> SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(base)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("freeze evidence"); + assertThatThrownBy( + () -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest( + base.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/world-management-service") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("recipient differs"); + assertThatThrownBy( + () -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest( + base.toBuilder().setClosureReadPurpose("ENTITY_INTAKE_RETENTION").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("closure read purpose differs"); + } + } + + @Test + void roundTripsCompleteOwnerRequestAndTypedPublicInventoryForBothOwners() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var fixture = fixture(owner); + var requestWire = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); + var decodedRequest = SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(requestWire); + + assertThat(requestWire.getSerializedSize()) + .isLessThanOrEqualTo(SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES); + assertThat(requestWire.getIntendedReader()).isEqualTo(fixture.binding().intendedReader()); + assertThat(requestWire.getClosureReadPurpose()) + .isEqualTo(fixture.request().closureReadPurpose()); + assertThat(decodedRequest.authorizationBinding().canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(decodedRequest.freezeEvidence().request()) + .isEqualTo(fixture.freezeEvidence().request()); + assertThat(decodedRequest.freezeEvidence().acknowledgement()) + .isEqualTo(fixture.freezeEvidence().acknowledgement()); + assertThat(decodedRequest.freezeEvidence()) + .isEqualTo(fixture.freezeEvidence()) + .hasSameHashCodeAs(fixture.freezeEvidence()); + + var responseWire = + SelectedOwnerWorldInventoryReadGrpcCodec.toResponse(decodedRequest, fixture.inventory()); + var decodedEvidence = + SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse(decodedRequest, responseWire); + + assertThat(fixture.inventory().canonicalBytes().length) + .isLessThanOrEqualTo(SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES); + assertThat(responseWire.getSerializedSize()) + .isLessThanOrEqualTo(SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES); + assertThat(responseWire.getRequest()).isEqualTo(requestWire); + assertThat(decodedEvidence.request().authorizationBinding().canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(decodedEvidence.request().freezeEvidence().request()) + .isEqualTo(fixture.freezeEvidence().request()); + assertThat(decodedEvidence.inventory().canonicalBytes()) + .containsExactly(fixture.inventory().canonicalBytes()); + assertThat(decodedEvidence.inventory().digest()).isEqualTo(fixture.inventory().digest()); + assertThat(decodedEvidence.inventory().publicEvidence()) + .isEqualTo(fixture.inventory().publicEvidence()); + } + } + + @Test + void rejectsChangedCompleteRequestEchoAndInventoryDigest() { + var fixture = fixture(Owner.ENTITY_MANAGEMENT); + var requestWire = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); + var response = + SelectedOwnerWorldInventoryReadGrpcCodec.toResponse(fixture.request(), fixture.inventory()); + var changedEcho = + response.toBuilder() + .setRequest( + requestWire.toBuilder().setReadRequestId("abababab-abab-4bab-8bab-abababababab")) + .build(); + String zeroDigest = "sha256:" + "0".repeat(64); + var changedDigest = + response.toBuilder() + .setPublicInventoryDigest( + fixture.inventory().digest().equals(zeroDigest) + ? "sha256:" + "1".repeat(64) + : zeroDigest) + .build(); + + assertThatThrownBy( + () -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse( + fixture.request(), changedEcho)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected-owner inventory read request"); + assertThatThrownBy( + () -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse( + fixture.request(), changedDigest)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsInventoryBoundToDifferentFreezeAcknowledgement() { + var fixture = fixture(Owner.ENTITY_MANAGEMENT); + var requestWire = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(fixture.request()); + var changedAcknowledgement = + requestWire.getFreezeAcknowledgement().toBuilder().setContentDigest("b".repeat(64)).build(); + var changedRequestWire = + requestWire.toBuilder().setFreezeAcknowledgement(changedAcknowledgement).build(); + var changedRequest = SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(changedRequestWire); + + assertThat(changedRequest.freezeEvidence()).isNotEqualTo(fixture.freezeEvidence()); + assertThatThrownBy( + () -> + SelectedOwnerWorldInventoryReadGrpcCodec.toResponse( + changedRequest, fixture.inventory())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected-owner freeze"); + } + + private static Fixture fixture(Owner owner) { + String namespace = "test"; + UUID tenant = id("11111111-1111-4111-8111-111111111111"); + UUID version = id("22222222-2222-4222-8222-222222222222"); + UUID actor = id("99999999-9999-4999-8999-999999999999"); + var target = new TargetProof(tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + var selected = + DraftCommitBinding.create( + target, + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + var sourceScope = + new SelectedOwnerIntakeSourceReadScope( + owner, + namespace, + id("55555555-5555-4555-8555-555555555555"), + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + actor, + selected); + var authorization = + new SelectedOwnerIntakeAuthorizationBinding( + sourceContent(sourceScope), + List.of( + source(SourceKind.TENANT, tenant.toString(), "tenant"), + source(SourceKind.ACCOUNT, actor.toString(), "account"), + source(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "9", + "selected-owner codec fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + target, + selected, + new VisibilityFence( + target, + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, actor.toString(), "1", "1", null, null, new byte[] {1}))); + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + namespace, + tenant, + version, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + freezeRequest, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + var freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + var request = + SelectedOwnerWorldInventoryReadEvidence.create(namespace, authorization, freezeEvidence); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freezeEvidence, publicInventory(freezeEvidence, selected, account)); + return new Fixture(authorization, freezeEvidence, request, inventory); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + SelectedOwnerIntakeSourceReadScope scope) { + var out = new java.io.ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + if ("GAMEPLAY_RULE".equals(family)) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + } + if ("TEMPLATE_CONFIG".equals(family)) { + return new TemplateConfigSourceSnapshot( + selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) + .canonicalBytes(); + } + return GameplayRuleManifest.canonical( + Map.of( + "schema", + "synthetic-test-only/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "family", + family)) + .getBytes(StandardCharsets.UTF_8); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freeze, + DraftCommitBinding selected, + AccountPublicationAuthorizationBinding account) { + var request = freeze.request(); + var acknowledgement = freeze.acknowledgement(); + var inboundClosure = + new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 0), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + inboundClosure); + var selection = account.input().selection(); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + new PublicOwnerScope( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + id("12121212-1212-4212-8212-121212121212"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("14141414-1414-4414-8414-141414141414"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)), + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint( + acknowledgement.appliedCommitId(), + acknowledgement.contentDigest(), + acknowledgement.digestSchemaVersion()), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static void frame(java.io.ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(java.io.ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private record Fixture( + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence.Request request, + WorldSelectedPublicationArtifactInventoryEvidence inventory) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodecTest.java new file mode 100644 index 0000000000..f8f12666cb --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedOwnerWorldInventoryReadGrpcCodecTest.java @@ -0,0 +1,40 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import org.junit.jupiter.api.Test; + +class SelectedOwnerWorldInventoryReadGrpcCodecTest { + @Test + void rejectsIncompleteOrUnknownRequestsBeforeOwnerStorageCanBeReached() { + var missing = ReadSelectedOwnerWorldInventoryRequest.getDefaultInstance(); + var unknown = + missing.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + + assertThatThrownBy(() -> SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(missing)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(unknown)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsWireMessagesAboveTheFiniteRecipientReadBudget() { + var oversized = + ReadSelectedOwnerWorldInventoryRequest.newBuilder() + .setOriginalIntakeAuthorizationBinding( + com.google.protobuf.ByteString.copyFrom( + new byte[SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES + 1])) + .build(); + + assertThatThrownBy(() -> SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(oversized)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire limit"); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java new file mode 100644 index 0000000000..27402243de --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcService.java @@ -0,0 +1,142 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldSelectedOwnerInventoryReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered recipient-specific gRPC boundary; authenticates before parsing the request. */ +public final class WorldSelectedOwnerInventoryReadGrpcService + extends WorldSelectedOwnerInventoryReadServiceGrpc + .WorldSelectedOwnerInventoryReadServiceImplBase { + private final String trustedNamespace; + private final WorldSelectedOwnerInventoryReadService readService; + + public WorldSelectedOwnerInventoryReadGrpcService( + String trustedNamespace, WorldSelectedOwnerInventoryReadService readService) { + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + this.readService = Objects.requireNonNull(readService, "readService"); + } + + @Override + public void readSelectedOwnerWorldInventory( + ReadSelectedOwnerWorldInventoryRequest request, + StreamObserver responseObserver) { + if (!requireAuthenticatedOwnerPeer(responseObserver)) return; + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "World owner inventory read requires an independent owner operation"); + return; + } + + final SelectedOwnerWorldInventoryReadEvidence.Request decoded; + try { + decoded = SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException invalid) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "A complete bounded selected-owner World inventory request is required"); + return; + } + if (!trustedNamespace.equals(decoded.targetNamespace()) + || !peerMatchesOwner(decoded.authorizationBinding().owner())) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "World inventory namespace and owner must match the authenticated recipient"); + return; + } + + final ReadSelectedOwnerWorldInventoryResponse response; + try { + var evidence = readService.read(decoded); + response = SelectedOwnerWorldInventoryReadGrpcCodec.toResponse(decoded, evidence.inventory()); + } catch (StatusRuntimeException failure) { + responseObserver.onError(failure); + return; + } catch (SecurityException denied) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Account did not confirm the exact selected-owner World closure read"); + return; + } catch (WorldDesignPublicationFenceRepository.ConflictException + | IllegalArgumentException inconsistent) { + fail( + responseObserver, + Status.FAILED_PRECONDITION, + "Exact retained World artifact inventory is unavailable"); + return; + } catch (org.springframework.dao.DataAccessException + | org.jooq.exception.DataAccessException unavailable) { + fail( + responseObserver, + Status.UNAVAILABLE, + "World selected inventory owner storage is unavailable"); + return; + } catch (RuntimeException failure) { + fail( + responseObserver, + Status.UNAVAILABLE, + "World selected-owner authorization or inventory read failed"); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + private boolean requireAuthenticatedOwnerPeer(StreamObserver responseObserver) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + fail( + responseObserver, + Status.UNAUTHENTICATED, + "Verified Entity or Automation workload required"); + return false; + } + boolean entity = isExpectedPeer(peer, "entity-management-service"); + boolean automation = isExpectedPeer(peer, "automation-scripting-service"); + if ((entity || automation) && !SessionContext.hasAuthenticatedCallerContext()) return true; + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Only a same-namespace Entity or Automation workload without end-user context is allowed"); + return false; + } + + private boolean isExpectedPeer(GrpcPeerIdentity peer, String service) { + String expected = "spiffe://firemud/ns/" + trustedNamespace + "/sa/" + service; + return expected.equals(peer.uri()) + && peer.isService(service) + && peer.isInNamespace(trustedNamespace); + } + + private boolean peerMatchesOwner(Owner owner) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expectedService = + owner == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"; + return peer != null && isExpectedPeer(peer, expectedService); + } + + private static void fail(StreamObserver observer, Status status, String description) { + observer.onError(status.withDescription(description).asRuntimeException()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java new file mode 100644 index 0000000000..e3c170b6fa --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadService.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account-confirmed composition for the exact recipient-specific retained World inventory. */ +final class WorldSelectedOwnerInventoryReadService { + private final String trustedNamespace; + private final WorldSelectedPublicationArtifactInventoryReadService inventoryReadService; + private final SelectedOwnerIntakeWorldClosureAuthorizationReadClient accountReadClient; + + WorldSelectedOwnerInventoryReadService( + String trustedNamespace, + WorldSelectedPublicationArtifactInventoryReadService inventoryReadService, + SelectedOwnerIntakeWorldClosureAuthorizationReadClient accountReadClient) { + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = Objects.requireNonNull(trustedNamespace, "trustedNamespace"); + this.inventoryReadService = + Objects.requireNonNull(inventoryReadService, "inventoryReadService"); + this.accountReadClient = Objects.requireNonNull(accountReadClient, "accountReadClient"); + } + + SelectedOwnerWorldInventoryReadEvidence read( + SelectedOwnerWorldInventoryReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("World owner inventory read requires no ambient SQL"); + } + if (!trustedNamespace.equals(request.targetNamespace())) { + throw new SecurityException("World owner inventory namespace differs from this workload"); + } + requireAuthenticatedRecipient(request); + var accountRequest = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + trustedNamespace, request.authorizationBinding()); + while (accountRequest.readRequestId().equals(request.readRequestId())) { + accountRequest = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + trustedNamespace, request.authorizationBinding()); + } + var accountEvidence = accountReadClient.readHeld(accountRequest); + if (accountEvidence == null || !sameAccountRequest(accountRequest, accountEvidence.request())) { + throw new SecurityException("Account changed the exact World closure authorization read"); + } + + var inventory = inventoryReadService.readRetained(request.freezeEvidence()); + return new SelectedOwnerWorldInventoryReadEvidence(request, inventory); + } + + private void requireAuthenticatedRecipient( + SelectedOwnerWorldInventoryReadEvidence.Request request) { + var binding = request.authorizationBinding(); + String service = + binding.owner() == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"; + String expected = "spiffe://firemud/ns/" + trustedNamespace + "/sa/" + service; + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!expected.equals(binding.intendedReader()) + || peer == null + || !expected.equals(peer.uri()) + || !peer.isService(service) + || !peer.isInNamespace(trustedNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException("Exact same-namespace selected-owner workload is required"); + } + } + + private static boolean sameAccountRequest( + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request expected, + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request actual) { + return actual != null + && expected.schemaVersion() == actual.schemaVersion() + && expected.targetNamespace().equals(actual.targetNamespace()) + && expected.readRequestId().equals(actual.readRequestId()) + && expected.intendedReader().equals(actual.intendedReader()) + && expected.closureReadPurpose().equals(actual.closureReadPurpose()) + && Arrays.equals(expected.binding().canonicalBytes(), actual.binding().canonicalBytes()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryReadService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryReadService.java index cc5545c8ac..ee1011f1ef 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryReadService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryReadService.java @@ -38,6 +38,12 @@ final class WorldSelectedPublicationArtifactInventoryReadService { WorldSelectedPublicationArtifactInventoryEvidence read( WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { requireAuthenticatedGameDesignCaller(); + return readRetained(freezeEvidence); + } + + /** Storage-only retained read for a separately authenticated recipient-specific boundary. */ + WorldSelectedPublicationArtifactInventoryEvidence readRetained( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { requireNoAmbientTransaction(); Objects.requireNonNull(freezeEvidence, "freezeEvidence"); diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java new file mode 100644 index 0000000000..a3612ff0d0 --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java @@ -0,0 +1,496 @@ +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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic exact source/freeze fixtures; Account and retained storage are explicit boundaries. */ +class WorldSelectedOwnerInventoryReadServiceTest { + private static final String NAMESPACE = "firemud"; + + @AfterEach + void clearRequestContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesOwnerWorkloadBeforeParsingAndRequiresIndependentRead() { + var inventory = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + var orchestrator = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventory, account); + var receiver = new WorldSelectedOwnerInventoryReadGrpcService(NAMESPACE, orchestrator); + var malformed = ReadSelectedOwnerWorldInventoryRequest.getDefaultInstance(); + + var anonymous = new RecordingObserver(); + withoutPeer(() -> receiver.readSelectedOwnerWorldInventory(malformed, anonymous)); + assertDenied(anonymous, Status.Code.UNAUTHENTICATED); + + var wrongWorkload = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> receiver.readSelectedOwnerWorldInventory(malformed, wrongWorkload)); + assertDenied(wrongWorkload, Status.Code.PERMISSION_DENIED); + + var wrongNamespace = new RecordingObserver(); + withPeer( + peer("other", "entity-management-service"), + () -> receiver.readSelectedOwnerWorldInventory(malformed, wrongNamespace)); + assertDenied(wrongNamespace, Status.Code.PERMISSION_DENIED); + + SessionContext.setContext( + "11111111-1111-4111-8111-111111111111", java.util.List.of(), java.util.Map.of()); + var endUser = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "automation-scripting-service"), + () -> receiver.readSelectedOwnerWorldInventory(malformed, endUser)); + assertDenied(endUser, Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + var ambient = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "entity-management-service"), + () -> receiver.readSelectedOwnerWorldInventory(malformed, ambient)); + assertDenied(ambient, Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + var authenticatedMalformed = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "entity-management-service"), + () -> receiver.readSelectedOwnerWorldInventory(malformed, authenticatedMalformed)); + assertDenied(authenticatedMalformed, Status.Code.INVALID_ARGUMENT); + + var authenticatedAutomationMalformed = new RecordingObserver(); + withPeer( + peer(NAMESPACE, "automation-scripting-service"), + () -> + receiver.readSelectedOwnerWorldInventory(malformed, authenticatedAutomationMalformed)); + assertDenied(authenticatedAutomationMalformed, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(inventory, account); + } + + @Test + void accountConfirmationPrecedesTheExactRetainedReadForBothOwners() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var fixture = fixture(owner); + var inventoryRead = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + var retainedInventory = mock(WorldSelectedPublicationArtifactInventoryEvidence.class); + when(retainedInventory.freezeEvidence()).thenReturn(fixture.freezeEvidence()); + when(retainedInventory.canonicalBytes()).thenReturn(new byte[] {1, 2, 3}); + when(retainedInventory.digest()).thenReturn("sha256:" + "a".repeat(64)); + + var callOrder = new ArrayList(); + when(account.readHeld(any())) + .thenAnswer( + invocation -> { + var request = + (SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request) + invocation.getArgument(0); + callOrder.add("account"); + assertThat(request.binding().canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(request.intendedReader()) + .isEqualTo("spiffe://firemud/ns/firemud/sa/world-management-service"); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.readRequestId()).isNotEqualTo(fixture.request().readRequestId()); + assertThat(request.closureReadPurpose()) + .isEqualTo( + owner == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" + : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"); + return new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(request); + }); + when(inventoryRead.readRetained(fixture.freezeEvidence())) + .thenAnswer( + invocation -> { + callOrder.add("retained-world"); + return retainedInventory; + }); + + var service = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventoryRead, account); + var result = + withPeer(peer(NAMESPACE, serviceName(owner)), () -> service.read(fixture.request())); + + assertThat(callOrder).containsExactly("account", "retained-world"); + assertThat(result.request()).isEqualTo(fixture.request()); + assertThat(result.request().authorizationBinding().canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(result.inventory()).isSameAs(retainedInventory); + verify(account).readHeld(any()); + verify(inventoryRead).readRetained(fixture.freezeEvidence()); + } + } + + @Test + void absentOrChangedAccountEchoNeverReadsWorldStorage() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var fixture = fixture(owner); + for (boolean absent : List.of(true, false)) { + var inventoryRead = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + when(account.readHeld(any())) + .thenAnswer( + invocation -> { + var expected = + (SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request) + invocation.getArgument(0); + if (absent) return null; + var changed = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + NAMESPACE, fixture.binding()); + while (changed.readRequestId().equals(expected.readRequestId())) { + changed = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + NAMESPACE, fixture.binding()); + } + return new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(changed); + }); + var service = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventoryRead, account); + + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, serviceName(owner)), () -> service.read(fixture.request()))) + .isInstanceOf(SecurityException.class); + verify(inventoryRead, never()).readRetained(any()); + } + } + } + + @Test + void domainServiceRejectsWrongRecipientEndUserAndAmbientSqlBeforeAccountCall() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var fixture = fixture(owner); + var inventoryRead = mock(WorldSelectedPublicationArtifactInventoryReadService.class); + var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); + var service = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventoryRead, account); + String caller = serviceName(owner); + String wrongCaller = + serviceName( + owner == Owner.ENTITY_MANAGEMENT + ? Owner.AUTOMATION_SCRIPTING + : Owner.ENTITY_MANAGEMENT); + + assertThatThrownBy( + () -> withPeer(peer(NAMESPACE, wrongCaller), () -> service.read(fixture.request()))) + .isInstanceOf(SecurityException.class); + + SessionContext.setContext("abababab-abab-4bab-8bab-abababababab", List.of(), Map.of()); + try { + assertThatThrownBy( + () -> withPeer(peer(NAMESPACE, caller), () -> service.read(fixture.request()))) + .isInstanceOf(SecurityException.class); + } finally { + SessionContext.clear(); + } + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> withPeer(peer(NAMESPACE, caller), () -> service.read(fixture.request()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(account, inventoryRead); + } + } + + private static Fixture fixture(Owner owner) { + UUID tenant = id("11111111-1111-4111-8111-111111111111"); + UUID version = id("22222222-2222-4222-8222-222222222222"); + UUID actor = id("99999999-9999-4999-8999-999999999999"); + var selected = + DraftCommitBinding.create( + new TargetProof(tenant, version, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), + Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "TEMPLATE_CONFIG", + version.toString(), + "TEMPLATE_CONFIG", + "ALL", + "0"))); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + id("55555555-5555-4555-8555-555555555555"), + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + actor, + selected); + var content = sourceContent(scope); + var binding = + new SelectedOwnerIntakeAuthorizationBinding( + content, + List.of( + source(SourceKind.TENANT, tenant.toString(), "tenant"), + source(SourceKind.ACCOUNT, actor.toString(), "account"), + source(SourceKind.MEMBERSHIP, actor + "/" + tenant, "membership"))); + + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "9", + "source-intake test", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var publicationBinding = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, actor.toString(), "1", "1", null, null, new byte[] {1}))); + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + tenant, + version, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + publicationBinding); + var acknowledgement = + new Acknowledgement( + freezeRequest, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 3); + var freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + return new Fixture( + binding, + freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, binding, freezeEvidence)); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + SelectedOwnerIntakeSourceReadScope scope) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = sourceSnapshot(family, scope.selected()); + DraftAuthorizationFenceBinding.frame(out, family); + DraftAuthorizationFenceBinding.frame(out, snapshot); + DraftAuthorizationFenceBinding.frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + if ("GAMEPLAY_RULE".equals(family)) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + } + if ("TEMPLATE_CONFIG".equals(family)) { + return new TemplateConfigSourceSnapshot( + selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) + .canonicalBytes(); + } + return GameplayRuleManifest.canonical( + Map.of( + "schema", + "synthetic-test-only/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "family", + family)) + .getBytes(StandardCharsets.UTF_8); + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static String serviceName(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT + ? "entity-management-service" + : "automation-scripting-service"; + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private record Fixture( + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence.Request request) {} + + private static void assertDenied(RecordingObserver observer, Status.Code code) { + assertThat(Status.fromThrowable(observer.error).getCode()).isEqualTo(code); + assertThat(observer.response).isNull(); + assertThat(observer.completed).isFalse(); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static T withPeer(GrpcPeerIdentity peer, java.util.function.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 void withPeer(GrpcPeerIdentity peer, Runnable action) { + withPeer( + peer, + () -> { + action.run(); + return null; + }); + } + + private static void withoutPeer(Runnable action) { + Context previous = Context.ROOT.attach(); + try { + action.run(); + } finally { + Context.ROOT.detach(previous); + } + } + + private static final class RecordingObserver + implements StreamObserver { + ReadSelectedOwnerWorldInventoryResponse response; + Throwable error; + boolean completed; + + @Override + public void onNext(ReadSelectedOwnerWorldInventoryResponse value) { + response = value; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Test observer intentionally retains the reported failure.") + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} From 0a99100a98ee19197bf162a4c1c202acec8e9055 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 19:52:52 +1300 Subject: [PATCH 077/129] Retain distinct Account protection through original StartSession admission --- ...dmin-as-external-operator-write-ingress.md | 10 + .../account-service/api-contracts.md | 4 + ...ame-authoring-publishing-and-activation.md | 2 + ...tSessionAdmissionProtectionRepository.java | 690 +++++++++++++++ ...AdmissionProtectionAcquisitionService.java | 419 +++++++++ ...tartSessionAuthorityCaptureRepository.java | 32 +- ...rtSessionOperatorAuthorizationService.java | 78 +- ...nWorldParticipationAcquisitionService.java | 41 +- ...33__start_session_admission_protection.sql | 365 ++++++++ ...rotectedEntryPrototypeIntegrationTest.java | 112 ++- ...sionProtectionPostgresIntegrationTest.java | 823 ++++++++++++++++++ ...sionAdmissionProtectionRepositoryTest.java | 83 ++ ...ssionProtectionAcquisitionServiceTest.java | 789 +++++++++++++++++ ...SessionAuthorityCaptureRepositoryTest.java | 91 ++ ...ssionOperatorAuthorizationServiceTest.java | 196 +++++ ...nt-admission-protected-entry-prototype.sql | 14 +- ...artSessionAdmissionProtectionEvidence.java | 446 ++++++++++ ...tartSessionAdmissionProtectionRequest.java | 448 ++++++++++ ...artSessionAccountRedemptionProjection.java | 59 ++ ...icalOriginalStartSessionOwnerEvidence.java | 54 +- ...essionAdmissionProtectionEvidenceTest.java | 481 ++++++++++ 21 files changed, 5118 insertions(+), 119 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java create mode 100644 services/account-service/src/main/resources/db/migration/V133__start_session_admission_protection.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionRequest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 3af5a58919..12755d712f 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -111,6 +111,16 @@ World owns a durable operation row and a separate monotonic execution fence that Expiry forbids dispatch of a new owner attempt, opening or restarting the World SQL transaction, reacquiring or renewing participation, renewing or reissuing the reference, or re-redeeming it. After a crash or unknown outcome following expiry, World may perform only an exact read-only lookup of the original durable operation: return `COMMITTED` only for the exact stored tuple, or record/return `ABORTED` only through the serialized fence after proving no in-flight or later commit; otherwise remain unresolved, retain source protection, and deny mutation retry. The original operation cannot be retried as a new mutation after expiry or uncertainty. The [implementation tracker](../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) distinguishes World-local execution storage from the still-missing genuine Account participation and authenticated recovery producer. This target contract grants no positive StartSession admission or runtime-activation approval; execution must remain unavailable until those boundaries and proofs exist. +#### Original StartSession Admission Source Protection + +Account owns a distinct source-protection lifecycle through the original Game Session admission commit. World receiving participation ends only at its own authenticated World terminal outcome; its settlement does not settle this admission protection. A retained finite Game Session attempt observation is not continuous source protection or current claim authority. Account retains the complete unchanged original post-authorization tuple and Account redemption projection, actual Game Session mutation/attempt/fence and original finite lease expiry, original World participation ID/fence, complete canonical World initial-admission hold identity, and exact original Account capture reference and source vector under a separate immutable protection ID and positive fence. The World initial-admission request identity and original control-plane request identity remain distinct and are both bound rather than aliased. + +Before acquiring or exactly recovering this protection, Account authenticates the exact configured same-namespace Game Session workload without end-user context and obtains authenticated evidence of the same current original attempt outside Account SQL. Its existing Account currentness boundary must then revalidate the original actor, `control-ui` token `jti`, issuance/reference, authority and complete unchanged source capture. Acquisition either overlaps World source protection or, after any World-settled gap, freshly proves the unchanged original authority and sources under the existing Account source locks; historical World bindings alone do not establish that proof. It never reissues or re-redeems a reference, renews a lease, changes an attempt/fence, borrows JOIN authority, or substitutes a new source capture. Original reference and Game Session lease expiry are checked against Account database time after lock waits. Pending admission protection excludes the existing applicable Account source writers and disclosure dispatch until exact terminal settlement; expiry or a failed lookup alone never releases it. + +Creation retains the protection and complete source children atomically. Independent lookup-only readback must return the exact first identity/fence, request, source capture and vector; lost acknowledgements cannot allocate an alternate operation or extend expiry. Game Session binds this complete Account protection into its actual original admission owner transaction and returns authenticated, durable terminal evidence for that same operation: exact `COMMITTED` pointer/audit/outcome, or definitive fenced `ABORTED` proof excluding an in-flight or later commit. Account releases only after exact terminal verification and immutable settlement. Missing, pending, conflicting or ambiguous evidence preserves source protection and reconciliation requirements. This lifecycle supplies neither gameplay admission by itself nor runtime activation; the [Account API](../microservices/account-service/api-contracts.md#operator-authorization-references) owns its closed carrier and producer/readback boundary, and the [authoring tracker](../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) owns implementation and proof status. + +#### Shared Forwarded Mutation Evidence And Digest + `authorityTuple` is copied without scalarization or field renaming from the complete canonical shape in the [JWT and token contracts](../system-architecture-jwt-and-token-contracts.md#canonical-authority-tuple). `membershipVersion` is the independently applicable Account membership-version map, including `{}` when no membership applies. `HumanAuthorityEvidence/v1` carries the Account-derived actor account, `control-ui` token `jti`, role, assurance, account generation, and applicable tenant or target-tenant generation. `AutomationAuthorityEvidence/v1` carries the exact authenticated workload, automation-policy identity/version, and applicable tenant generation. The tagged `issuanceEvidence` arm must agree with Account-derived `issuanceKind`; the inapplicable arm and inapplicable authority-scope identifiers are omitted rather than serialized as `null`, empty objects, or sentinels. `sourceEvidenceId` identifies the one Account authority snapshot and its linearization evidence, while `sourceEvidenceVersion` is the corresponding Account-issued source version; together they are the canonical source fence for the bundle and are carried unchanged with the existing `{bundleVersion, sourceVersion, sourceFence, linearization}` reference. Account derives every authority, generation, membership, freshness, and branch-decision member from that one atomic snapshot and stores the source pair with the issuance record. During redemption, Account exact-compares `sourceEvidenceId`, `sourceEvidenceVersion`, the bundle reference, and every snapshot-bound field against the stored issuance record and the current applicable authority evidence; a missing, changed, or mixed-version value rejects redemption. Consumers reject missing, extra, contradictory, separately sourced, stale, expired, wrongly tagged, or non-canonical bundle fields and must redeem the original reference with Account; a copied bundle never becomes a second authority. For every forwarded owner-mutation family, ADR 0048's canonical complete `postAuthorizationExecutionTuple` is the required post-authorization identity. It explicitly contains ADR 0048's stable `controlPlaneRequestId` for orchestration, reservation, lookup, and correlation across forwarding, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor/policy binding, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` defined above (whose issuance identity carries the tagged `actionFamilyRequestIdentity` for domain action/idempotency), and every schema-bound typed presence/absence value. `targetOwner` is distinct from `target`, immutable after reservation, and is never inferred from current routing or owner state. Reservation and pre-authorization Account issuance/recovery compare `preAuthorizationReservationTuple`; post-authorization tuple completion, owner idempotency, terminal/no-commit proof, result lookup, conflict handling, and any later fresh owner attempt carries and compares its own exact tuple; no participant may omit a required identity because it is unavailable locally. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 93cfade658..0da482e703 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -203,6 +203,10 @@ Fresh World participation acquisition first obtains the [Game Session current-or The credential-free `ReadRedeemedOperationProjection` receiver accepts the exact configured same-namespace Game Design peer and the exact original Game Session redeemer under [ADR 0047's restricted original-operation read](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). Before returning the retained projection, Account compares the original request/reservation and redeemed workload/attempt/fence, then revalidates the original actor/JTI, current source and reference expiry. The response contains no credential or renewed permission. Game Session must separately prove its original claim and immutable pin under the owner-local checks required by that contract; this Account read is not World participation or admission. +The distinct original-admission producer and independent readback implement [ADR 0047's admission source protection](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection), not the World receiving lifecycle above. Its closed RFC 8785 `account-start-session-admission-protection-request/v1` object has exactly `schema`, `originalPostAuthorizationTupleBytesBase64`, `accountRedemptionProjectionBytesBase64`, `gameSessionOwnerMutationId`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `originalLeaseExpiresAt`, `accountWorldParticipationId`, `accountWorldParticipationFence`, and `worldAdmissionHoldIdentityBytesBase64`. UUIDs are canonical non-nil strings; positive fences are canonical decimal strings bounded by the owner counter type; expiry is unchanged UTC with exactly three fractional digits. Base64 members carry exact canonical complete original values, not hashes or caller-selected projections. The complete World hold binds its separate admission request/digest, precondition and canonical target. Unknown, duplicate, trailing, noncanonical, substituted or oversized data is rejected. + +The closed `account-start-session-admission-protection-evidence/v1` object carries exactly `schema`, `requestBytesBase64`, `accountProtectionId`, `accountProtectionFence`, `originalSourceCaptureReferenceBytesBase64`, `originalSourceCaptureReferenceSha256`, and `sourceEvidenceVector`. The capture reference retains the original Account version/fence/linearization and exact SHA-256; the vector contains each exact canonical source frame in canonical source-key order, without omissions, extras or duplicate keys. Carrier validation establishes integrity only, not authentication, currentness, continuity or admission. The exact same-namespace Game Session caller is checked before input handling; its fresh current-attempt read runs outside SQL, the original Account currentness callback creates or recovers immutable evidence in writable read-committed SQL, and a separate lookup-only transaction exact-compares post-commit readback. Runtime registration and authenticated terminal composition remain gated in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + ## REST APIs | Method | Path | Description | 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 0958d4d533..f887655c9c 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Distinct original-StartSession Account admission protection is prepared under [ADR 0047's canonical lifecycle](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection). It authenticates the original Game Session receiving workload, obtains the exact current original-attempt observation outside SQL, then revalidates the original actor/JTI/reference and unchanged complete capture through the existing Account currentness callback. V133 retains the complete request, actual mutation/attempt/fence and unchanged finite expiry, original World participation, full World hold, immutable capture and exact source children; additive writer/disclosure hooks preserve the existing assembled owner checks. A settled World row can supply historical binding but cannot supply current authority: the producer must freshly prove unchanged original sources after a gap. Independent lookup-only readback returns the first protection unchanged. V129 World settlement and V131 observation are unchanged. Authenticated Game Session terminal composition is not yet complete, so every V133 settlement insertion remains denied; missing or ambiguous proof cannot release protection. This producer remains unregistered and does not enable admission. The final affected Common/Account full-check, formatting, static-analysis, schema-generation, boot-JAR, links and Markdown gate passes in 1m12s. XML retains 581 Common and 1,296 Account unit cases with zero failures, errors or skips; unchanged successful tasks reuse their results. Account executes seven non-container integration cases and skips 277, including all seven new upstream-stipulated V133 PostgreSQL integrity definitions, without Docker. These synthetic units and compiled definitions do not establish genuine authenticated owner composition, live claim continuity, restart settlement or executed PostgreSQL proof. The approved isolated durability diagnostic adds administrator phase observations, entry observations and a failure-only WAL dump bounded to two segments/128 records/16,384 characters; none supplies authority, and no caller preflight SQL, forced flushing or expiry change is added. Its physical execution, possible timing perturbation and record provenance remain unproved; the earlier valid fresh-backend failure does not authorize production adoption. + Exact source `c16370dc158100da94b19619c23f7b1f05a11959` [Validation run 38027144761](https://github.com/benhook1013/FireMUD/actions/runs/38027144761) ended cancelled with a failed required gate. Originating Account XML records 285 executions, six failures and no skips: five production admission-confirmation WAL-coverage denials and one isolated prototype denial. Both V132 finalization cases and all three V131 observation cases pass. All ten prototype definitions execute: nine pass, including quiet cold/warm entry, while the privilege case completes its twelve denial assertions but fails the subsequent valid hostile-search-path confirmation with the flush frontier 128 bytes behind its entry upper bound despite about fourteen seconds of remaining original validity. The WAL's origin is not established. These positives are feasibility evidence, not production adoption; no warming, forced flush, marker write or deadline extension is applied to conceal the failed entry. World executes all 221 integration cases without failures or skips; Game Design is cancelled without originating XML, so no new Game Design proof is claimed. CI identifies merge `1e493b96dfc334590d96f0c3f04a77917f12891a` and the merge message's base `fe15a31f274b1c9850dd388e83faf540916ee8a3`; the tree and ordered parent objects are not independently verified. This is not recorded-parent alignment, full original-COMMIT durability proof or runtime activation. The distinct, unregistered selected-owner World closure read now authenticates the exact Entity or Automation recipient, preserves its original finalized Account binding and original World freeze, obtains separate authenticated Account confirmation outside SQL, and returns only the unchanged retained typed inventory. The Game Design publication read remains Game Design-only. The affected Common/Account/World full checks and boot JARs pass in 2m58s: 573, 1,278 and 648 unit cases respectively, without failures, errors or unit skips. Account executes seven non-container integration cases and skips 270; World executes one and skips 220 without Docker. A complete request/response roundtrip exposed object-identity comparison of an otherwise identical freeze; the correction compares the full request and acknowledgement and preserves changed-acknowledgement rejection. The final Common full check, formatting, static checks, links and Markdown pass in 3m40s with 576 unit cases and no failures, errors or skips, including four complete recipient/echo/inventory cases. These are bounded codec, synthetic mTLS and mocked ordering tests, not database-backed closure disclosure, complete owner census or terminal receipt proof. Continuous participation follows the existing pending source-writer exclusion, not this sampled confirmation; exact Entity/Automation terminal settlement remains open. Separately approved Account protection through the original Game Session admission commit is under construction, distinct from V129 World settlement and V131 finite observation; no runtime registration or activation follows. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java new file mode 100644 index 0000000000..46c6d5f59a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java @@ -0,0 +1,690 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCapture; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable Account storage for the original StartSession admission source protection. + * + *

Every operation requires the producer's writable READ COMMITTED Account transaction. The + * producer authenticates Game Session and establishes original actor/JTI/reference currentness + * before using this repository. SQL revalidates the full retained source, World participation, + * owner observation, lease and request bindings; this repository is not an authenticator or a + * terminal settlement path. + */ +@Repository +public class AccountStartSessionAdmissionProtectionRepository { + private static final String PROTECTIONS = "account_start_session_admission_protections"; + private static final String SOURCES = "account_start_session_admission_protection_sources"; + private static final String CAPTURES = "account_start_session_authority_captures"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Set PROTECTION_COLUMNS = + Set.of( + "protection_id", + "protection_fence", + "control_plane_request_id", + "original_post_authorization_tuple", + "account_redemption_projection", + "game_session_owner_mutation_id", + "game_session_owner_attempt_id", + "game_session_owner_fence", + "original_lease_expires_at", + "account_world_participation_id", + "account_world_participation_fence", + "target_namespace", + "canonical_tenant_id", + "canonical_game_instance_id", + "capture_source_version", + "capture_source_fence", + "capture_sha256", + "world_admission_hold_identity_bytes", + "request_binding_bytes", + "request_binding_digest", + "producer_xid", + "created_at"); + private static final Set SOURCE_COLUMNS = + Set.of("protection_id", "source_key", "source_evidence"); + private static final Set CAPTURE_COLUMNS = + Set.of( + "control_plane_request_id", + "source_version", + "source_fence", + "snapshot_sha256", + "canonical_sha256", + "canonical_capture_bytes", + "canonical_snapshot_bytes"); + private static final Set CAPTURE_SNAPSHOT_FIELDS = + Set.of( + "schema", + "controlPlaneRequestId", + "preAuthorizationTuple", + "mutationDigest", + "accountId", + "tenantId", + "targetOwner", + "loggingWorkloadUri", + "reservationOwnerId", + "reservationClaimFence", + "controlUiOperationId", + "controlUiTokenJti", + "controlUiTokenHash", + "controlUiSignerReceipt", + "controlUiSignerReceiptSha256", + "sourceVectorEvidence", + "sourceVector", + "outboxCheckpoints", + "authorityTuple", + "membershipVersion", + "accountIdentitySource", + "issuanceFence", + "issuanceFenceSourceVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve the injected DSLContext precondition; this transactional Spring repository must remain proxyable, owns no resources, and declares no finalizer.") + public AccountStartSessionAdmissionProtectionRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Inserts the exact original protection and complete captured source vector, or returns its + * immutable winner on an exact request retry. + * + *

The caller invokes this inside the Account currentness callback, after the independent Game + * Session observation and the original World participation/attempt comparison. A duplicate never + * replaces the retained identity; its complete row and source children are checked only after + * database locks have revalidated currentness and the finite original expiry. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountStartSessionAdmissionProtectionEvidence createOrReadExact( + AccountStartSessionAdmissionProtectionRequest request, + AccountStartSessionAuthorityCapture capture) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(request, "exact admission protection request is required"); + Objects.requireNonNull(capture, "exact current Account capture is required"); + CaptureValue expectedCapture = CaptureValue.from(capture); + List expectedSources = + sourceVector(expectedCapture.snapshotBytes(), request.originalTuple()); + requireCaptureMatches(capture, request.originalTuple(), selectCapture(capture, false)); + + Record existing = selectByRequestId(request.originalTuple().controlPlaneRequestId(), false); + if (existing != null) { + UUID existingId = requiredUuid(existing, "protection_id"); + long existingFence = positive(requiredLong(existing, "protection_fence")); + assertCurrent(existingId, existingFence, request.canonicalBytes()); + Record locked = selectById(existingId, true); + if (locked == null) throw unavailable(); + return decodeAndRequireExact(locked, request, expectedCapture, expectedSources); + } + + UUID proposedId = UUID.randomUUID(); + int inserted = insert(request, capture, expectedSources, proposedId); + if (inserted == 1) insertSources(proposedId, expectedSources); + + Record winner = selectByRequestId(request.originalTuple().controlPlaneRequestId(), false); + if (winner == null) throw unavailable(); + UUID protectionId = requiredUuid(winner, "protection_id"); + long protectionFence = positive(requiredLong(winner, "protection_fence")); + assertCurrent(protectionId, protectionFence, request.canonicalBytes()); + Record locked = selectById(protectionId, true); + if (locked == null) throw unavailable(); + AccountStartSessionAdmissionProtectionEvidence evidence = + decodeAndRequireExact(locked, request, expectedCapture, expectedSources); + if (inserted == 1 && !proposedId.equals(evidence.accountProtectionId())) throw unavailable(); + return evidence; + } + + /** + * Lookup-only current read for independent post-commit readback. It never inserts or renews a + * lease, and locks the source/capture/World/owner/protection chain before exact comparison. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findCurrentExact( + AccountStartSessionAdmissionProtectionRequest request) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(request, "exact admission protection request is required"); + Record observed = selectByRequestId(request.originalTuple().controlPlaneRequestId(), false); + if (observed == null) return Optional.empty(); + UUID protectionId = requiredUuid(observed, "protection_id"); + long protectionFence = positive(requiredLong(observed, "protection_fence")); + assertCurrent(protectionId, protectionFence, request.canonicalBytes()); + + Record captureRow = selectCaptureForOriginalTuple(request.originalTuple(), false); + if (captureRow == null) throw unavailable(); + CaptureValue capture = captureFromRow(captureRow); + List expectedSources = + sourceVector(capture.snapshotBytes(), request.originalTuple()); + Record locked = selectById(protectionId, true); + if (locked == null) throw unavailable(); + return Optional.of(decodeAndRequireExact(locked, request, capture, expectedSources)); + } + + private int insert( + AccountStartSessionAdmissionProtectionRequest request, + AccountStartSessionAuthorityCapture capture, + List sources, + UUID protectionId) { + var tuple = request.originalTuple(); + var hold = request.worldAdmissionHoldIdentity(); + return dsl.execute( + "INSERT INTO " + + PROTECTIONS + + " (protection_id, control_plane_request_id, original_post_authorization_tuple, " + + "account_redemption_projection, game_session_owner_mutation_id, " + + "game_session_owner_attempt_id, game_session_owner_fence, original_lease_expires_at, " + + "account_world_participation_id, account_world_participation_fence, target_namespace, " + + "canonical_tenant_id, canonical_game_instance_id, capture_source_version, " + + "capture_source_fence, capture_sha256, world_admission_hold_identity_bytes, " + + "request_binding_bytes, request_binding_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (control_plane_request_id) DO NOTHING", + protectionId, + tuple.controlPlaneRequestId(), + request.originalPostAuthorizationTupleBytes(), + request.accountRedemptionProjectionBytes(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + OffsetDateTime.ofInstant(request.originalLeaseExpiresAt(), ZoneOffset.UTC), + request.accountWorldParticipationId(), + request.accountWorldParticipationFence(), + tuple.preAuthorizationTuple().action().scope().targetNamespace(), + tuple.preAuthorizationTuple().action().scope().tenantId(), + hold.request().canonicalGameInstanceId(), + capture.sourceVersion(), + capture.sourceFence(), + capture.canonicalSha256(), + request.worldAdmissionHoldIdentityBytes(), + request.canonicalBytes(), + digestPrefixed(request.canonicalBytes())); + } + + private void insertSources(UUID protectionId, List sources) { + for (SourceEvidence source : sources) { + byte[] bytes = source.canonicalBytes(); + dsl.execute( + "INSERT INTO " + + SOURCES + + " (protection_id, source_key, source_evidence) VALUES (?, ?, ?)", + protectionId, + source.key(), + bytes); + } + } + + private AccountStartSessionAdmissionProtectionEvidence decodeAndRequireExact( + Record row, + AccountStartSessionAdmissionProtectionRequest expectedRequest, + CaptureValue expectedCapture, + List expectedSources) { + try { + requireColumns(row, PROTECTION_COLUMNS, "admission protection"); + UUID protectionId = requiredUuid(row, "protection_id"); + long protectionFence = positive(requiredLong(row, "protection_fence")); + String requestId = requiredString(row, "control_plane_request_id"); + byte[] tupleBytes = requiredBytes(row, "original_post_authorization_tuple"); + byte[] projectionBytes = requiredBytes(row, "account_redemption_projection"); + UUID ownerMutation = requiredUuid(row, "game_session_owner_mutation_id"); + UUID ownerAttempt = requiredUuid(row, "game_session_owner_attempt_id"); + long ownerFence = positive(requiredLong(row, "game_session_owner_fence")); + Instant originalExpiry = requiredTimestamp(row, "original_lease_expires_at").toInstant(); + UUID participationId = requiredUuid(row, "account_world_participation_id"); + long participationFence = positive(requiredLong(row, "account_world_participation_fence")); + String namespace = requiredString(row, "target_namespace"); + UUID tenant = requiredUuid(row, "canonical_tenant_id"); + UUID gameInstance = requiredUuid(row, "canonical_game_instance_id"); + long captureVersion = positive(requiredLong(row, "capture_source_version")); + long captureFence = positive(requiredLong(row, "capture_source_fence")); + String captureDigest = requiredString(row, "capture_sha256"); + byte[] holdBytes = requiredBytes(row, "world_admission_hold_identity_bytes"); + byte[] requestBytes = requiredBytes(row, "request_binding_bytes"); + String requestDigest = requiredString(row, "request_binding_digest"); + positive(requiredLong(row, "producer_xid")); + requiredTimestamp(row, "created_at"); + + var tuple = expectedRequest.originalTuple(); + var hold = expectedRequest.worldAdmissionHoldIdentity(); + if (!tuple.controlPlaneRequestId().equals(requestId) + || !Arrays.equals(tupleBytes, expectedRequest.originalPostAuthorizationTupleBytes()) + || !Arrays.equals(projectionBytes, expectedRequest.accountRedemptionProjectionBytes()) + || !ownerMutation.equals(expectedRequest.gameSessionOwnerMutationId()) + || !ownerAttempt.equals(expectedRequest.gameSessionOwnerAttemptId()) + || ownerFence != expectedRequest.gameSessionOwnerFence() + || !originalExpiry.equals(expectedRequest.originalLeaseExpiresAt()) + || !participationId.equals(expectedRequest.accountWorldParticipationId()) + || participationFence != expectedRequest.accountWorldParticipationFence() + || !namespace.equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !tenant.equals(tuple.preAuthorizationTuple().action().scope().tenantId()) + || !gameInstance.equals(hold.request().canonicalGameInstanceId()) + || captureVersion != expectedCapture.sourceVersion() + || captureFence != expectedCapture.sourceFence() + || !captureDigest.equals(expectedCapture.canonicalSha256()) + || !Arrays.equals(holdBytes, expectedRequest.worldAdmissionHoldIdentityBytes()) + || !MessageDigest.isEqual(requestBytes, expectedRequest.canonicalBytes()) + || !requestDigest.equals(digestPrefixed(requestBytes))) { + throw conflict(); + } + + List storedSources = readSources(protectionId); + requireExactSources(expectedSources, storedSources); + AccountStartSessionAdmissionProtectionEvidence evidence = + AccountStartSessionAdmissionProtectionEvidence.create( + expectedRequest, + protectionId, + protectionFence, + expectedCapture.canonicalBytes(), + expectedCapture.canonicalSha256(), + storedSources); + return evidence; + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && ("StartSession admission protection is unavailable".equals(state.getMessage()) + || "StartSession admission protection conflicts with its immutable binding" + .equals(state.getMessage()))) { + throw state; + } + throw unavailable(); + } + } + + private List readSources(UUID protectionId) { + var rows = + dsl.fetch( + "SELECT * FROM " + SOURCES + " WHERE protection_id = ? ORDER BY source_key", + protectionId); + List result = new ArrayList<>(rows.size()); + for (Record row : rows) { + requireColumns(row, SOURCE_COLUMNS, "admission protection source"); + if (!protectionId.equals(requiredUuid(row, "protection_id"))) throw unavailable(); + String key = requiredString(row, "source_key"); + byte[] bytes = requiredBytes(row, "source_evidence"); + SourceEvidence source; + try { + source = SourceEvidence.fromStored(bytes); + } catch (RuntimeException malformed) { + throw unavailable(); + } + if (!key.equals(source.key()) || bytes.length == 0 || bytes.length > 131_072) { + throw unavailable(); + } + result.add(source); + } + result.sort(Comparator.comparing(SourceEvidence::key)); + if (result.stream().map(SourceEvidence::key).distinct().count() != result.size()) { + throw unavailable(); + } + return List.copyOf(result); + } + + private Record selectByRequestId(String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + PROTECTIONS + + " WHERE control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + requestId); + } + + private Record selectById(UUID protectionId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + PROTECTIONS + + " WHERE protection_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + protectionId); + } + + void assertCurrent(UUID protectionId, long protectionFence, byte[] exactRequestBytes) { + if (exactRequestBytes == null || exactRequestBytes.length == 0) throw unavailable(); + Record checked = + dsl.fetchOne( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + protectionId, + protectionFence, + exactRequestBytes); + if (checked == null) throw unavailable(); + } + + private Record selectCaptureForOriginalTuple( + StartSessionPostAuthorizationExecutionTuple tuple, boolean forUpdate) { + return dsl.fetchOne( + "SELECT control_plane_request_id, source_version, source_fence, snapshot_sha256, canonical_sha256, " + + "canonical_capture_bytes, canonical_snapshot_bytes FROM " + + CAPTURES + + " WHERE control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + tuple.controlPlaneRequestId()); + } + + private Record selectCapture(AccountStartSessionAuthorityCapture capture, boolean forUpdate) { + return dsl.fetchOne( + "SELECT control_plane_request_id, source_version, source_fence, snapshot_sha256, canonical_sha256, " + + "canonical_capture_bytes, canonical_snapshot_bytes FROM " + + CAPTURES + + " WHERE control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + capture.controlPlaneRequestId()); + } + + private CaptureValue captureFromRow(Record row) { + requireColumns(row, CAPTURE_COLUMNS, "Account source capture"); + try { + String requestId = requiredString(row, "control_plane_request_id"); + long sourceVersion = positive(requiredLong(row, "source_version")); + long sourceFence = positive(requiredLong(row, "source_fence")); + String snapshotDigest = requiredString(row, "snapshot_sha256"); + String digest = requiredString(row, "canonical_sha256"); + byte[] reference = requiredBytes(row, "canonical_capture_bytes"); + byte[] snapshot = requiredBytes(row, "canonical_snapshot_bytes"); + return new CaptureValue( + requestId, sourceVersion, sourceFence, snapshot, snapshotDigest, reference, digest); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private void requireCaptureMatches( + AccountStartSessionAuthorityCapture capture, + StartSessionPostAuthorizationExecutionTuple tuple, + Record row) { + if (row == null) throw unavailable(); + requireColumns(row, CAPTURE_COLUMNS, "Account source capture"); + if (!tuple.controlPlaneRequestId().equals(capture.controlPlaneRequestId()) + || !tuple.controlPlaneRequestId().equals(requiredString(row, "control_plane_request_id")) + || capture.sourceVersion() != positive(requiredLong(row, "source_version")) + || capture.sourceFence() != positive(requiredLong(row, "source_fence")) + || !capture.snapshotSha256().equals(requiredString(row, "snapshot_sha256")) + || !capture.canonicalSha256().equals(requiredString(row, "canonical_sha256")) + || !Arrays.equals(capture.canonicalBytes(), requiredBytes(row, "canonical_capture_bytes")) + || !Arrays.equals( + capture.snapshotBytes(), requiredBytes(row, "canonical_snapshot_bytes"))) { + throw conflict(); + } + } + + private static List sourceVector( + byte[] snapshotBytes, StartSessionPostAuthorizationExecutionTuple tuple) { + Map snapshot = parseCanonicalObject(snapshotBytes, "Account source snapshot"); + if (!CAPTURE_SNAPSHOT_FIELDS.equals(snapshot.keySet()) + || !"account-start-session-authority-snapshot/v1".equals(snapshot.get("schema")) + || !tuple.controlPlaneRequestId().equals(snapshot.get("controlPlaneRequestId"))) { + throw unavailable(); + } + Object value = snapshot.get("sourceVector"); + if (!(value instanceof List encoded) || encoded.isEmpty()) throw unavailable(); + List sources = new ArrayList<>(encoded.size()); + Set keys = new HashSet<>(); + String previousKey = null; + for (Object element : encoded) { + if (!(element instanceof String base64)) throw unavailable(); + byte[] bytes = strictBase64(base64); + SourceEvidence source; + try { + source = SourceEvidence.fromStored(bytes); + } catch (RuntimeException malformed) { + throw unavailable(); + } + if (bytes.length == 0 + || bytes.length > 131_072 + || !keys.add(source.key()) + || (previousKey != null && previousKey.compareTo(source.key()) >= 0)) { + throw unavailable(); + } + previousKey = source.key(); + sources.add(source); + } + return List.copyOf(sources); + } + + static void requireExactSources(List expected, List actual) { + if (actual.size() != expected.size()) throw conflict(); + for (int index = 0; index < expected.size(); index++) { + SourceEvidence left = expected.get(index); + SourceEvidence right = actual.get(index); + if (!left.key().equals(right.key()) + || !Arrays.equals(left.canonicalBytes(), right.canonicalBytes())) { + throw conflict(); + } + } + } + + private static Map parseCanonicalObject(byte[] bytes, String label) { + try { + String text = strictUtf8(bytes); + if (!Arrays.equals( + bytes, net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8(text))) { + throw unavailable(); + } + Object value = JSON.readValue(text, Object.class); + if (!(value instanceof Map object)) throw unavailable(); + return object; + } catch (IOException | RuntimeException malformed) { + if (malformed instanceof IllegalStateException expected) throw expected; + throw new IllegalStateException(label + " is unavailable", malformed); + } + } + + private static byte[] strictBase64(String value) { + try { + byte[] decoded = Base64.getDecoder().decode(value); + if (!Base64.getEncoder().encodeToString(decoded).equals(value)) throw unavailable(); + return decoded; + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + } catch (java.nio.charset.CharacterCodingException malformed) { + throw unavailable(); + } + } + + private record CaptureValue( + String controlPlaneRequestId, + long sourceVersion, + long sourceFence, + byte[] snapshotBytes, + String snapshotSha256, + byte[] canonicalBytes, + String canonicalSha256) { + private CaptureValue { + if (controlPlaneRequestId == null + || sourceVersion <= 0L + || sourceFence <= 0L + || snapshotBytes == null + || snapshotBytes.length == 0 + || snapshotBytes.length > AccountStartSessionAuthorityCapture.MAX_SNAPSHOT_BYTES + || snapshotSha256 == null + || canonicalBytes == null + || canonicalBytes.length == 0 + || canonicalBytes.length > AccountStartSessionAuthorityCapture.MAX_CAPTURE_BYTES + || canonicalSha256 == null) { + throw unavailable(); + } + snapshotBytes = snapshotBytes.clone(); + canonicalBytes = canonicalBytes.clone(); + if (!snapshotSha256.equals(digestHex(snapshotBytes)) + || !canonicalSha256.equals(digestHex(canonicalBytes))) { + throw unavailable(); + } + Map reference = parseCanonicalObject(canonicalBytes, "Account capture reference"); + if (!reference + .keySet() + .equals( + Set.of( + "schema", + "controlPlaneRequestId", + "capturedAt", + "bundleReference", + "snapshotSha256")) + || !AccountStartSessionAuthorityCapture.SCHEMA.equals(reference.get("schema")) + || !controlPlaneRequestId.equals(reference.get("controlPlaneRequestId")) + || !snapshotSha256.equals(reference.get("snapshotSha256")) + || !(reference.get("bundleReference") instanceof Map bundle) + || !bundle + .keySet() + .equals(Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization")) + || !StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION.equals(bundle.get("bundleVersion")) + || !Long.toString(sourceVersion).equals(bundle.get("sourceVersion")) + || !Long.toString(sourceFence).equals(bundle.get("sourceFence"))) { + throw unavailable(); + } + } + + private static CaptureValue from(AccountStartSessionAuthorityCapture capture) { + return new CaptureValue( + capture.controlPlaneRequestId(), + capture.sourceVersion(), + capture.sourceFence(), + capture.snapshotBytes(), + capture.snapshotSha256(), + capture.canonicalBytes(), + capture.canonicalSha256()); + } + + @Override + public byte[] snapshotBytes() { + return snapshotBytes.clone(); + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + }); + } + + private static void requireColumns(Record row, Set expected, String label) { + Set actual = new HashSet<>(); + Arrays.stream(row.fields()).forEach(field -> actual.add(field.getName())); + if (!actual.equals(expected)) { + throw new IllegalStateException(label + " has an unknown or missing database column"); + } + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) throw unavailable(); + return value; + } + + private static String requiredString(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw unavailable(); + return value; + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) throw unavailable(); + return value; + } + + private static Long requiredLong(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) throw unavailable(); + return value; + } + + private static OffsetDateTime requiredTimestamp(Record row, String field) { + OffsetDateTime value = row.get(field, OffsetDateTime.class); + if (value == null) throw unavailable(); + return value; + } + + private static long positive(long value) { + if (value <= 0L) throw unavailable(); + return value; + } + + private static String digestPrefixed(byte[] bytes) { + return "sha256:" + digestHex(bytes); + } + + private static String digestHex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalStateException conflict() { + return new IllegalStateException( + "StartSession admission protection conflicts with its immutable binding"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("StartSession admission protection is unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java new file mode 100644 index 0000000000..592046525c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java @@ -0,0 +1,419 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Account composition that retains exact original StartSession protection through the + * original Game Session admission boundary. + * + *

Game Session is read outside Account SQL on every attempt. Account then rechecks the live + * original actor, JTI, reference, current authority and captured sources in its existing + * currentness callback before it creates or reads the immutable protection. This component does not + * issue or renew authorization, settle/release protection, or perform a remote call under SQL. + */ +public final class AccountStartSessionAdmissionProtectionAcquisitionService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final AccountStartSessionOperatorAuthorizationService issuer; + private final AccountStartSessionWorldParticipationRepository participationRepository; + private final AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptEvidenceRepository; + private final AccountStartSessionAdmissionProtectionRepository protectionRepository; + private final OriginalStartSessionCurrentAttemptClient gameSessionClient; + private final TransactionTemplate readbackTransaction; + private final String workloadNamespace; + + public AccountStartSessionAdmissionProtectionAcquisitionService( + AccountStartSessionOperatorAuthorizationService issuer, + AccountStartSessionWorldParticipationRepository participationRepository, + AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptEvidenceRepository, + AccountStartSessionAdmissionProtectionRepository protectionRepository, + OriginalStartSessionCurrentAttemptClient gameSessionClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.issuer = + Objects.requireNonNull(issuer, "original Account StartSession issuer is required"); + this.participationRepository = + Objects.requireNonNull( + participationRepository, "World participation repository is required"); + this.attemptEvidenceRepository = + Objects.requireNonNull( + attemptEvidenceRepository, "original-attempt evidence repository is required"); + this.protectionRepository = + Objects.requireNonNull(protectionRepository, "admission protection repository is required"); + this.gameSessionClient = + Objects.requireNonNull( + gameSessionClient, "Game Session current-attempt client is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + readbackTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + readbackTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readbackTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readbackTransaction.setReadOnly(false); + } + + /** + * Acquires and reads back the exact immutable protection. An unknown commit is propagated for a + * later retry with this same original tuple; each retry first obtains fresh Game Session and + * Account currentness evidence and can only read the existing protection identity. + */ + public AccountStartSessionAdmissionProtectionEvidence acquire(AcquisitionRequest request) { + requireGameSessionPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(request, "admission protection acquisition request is required"); + Objects.requireNonNull(request.worldHoldIdentity(), "original World hold identity is required"); + + byte[] tupleBytes = request.originalPostAuthorizationTuple(); + StartSessionPostAuthorizationExecutionTuple tuple = decodeOriginalTuple(tupleBytes); + requireOriginalBinding(tuple, request); + Request currentAttemptRequest = + new Request( + freshReadId(tuple, request), + workloadNamespace, + tupleBytes, + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerFence()); + + // Every acquisition and exact retry observes the original owner before opening Account SQL. + requireNoAmbientTransaction(); + Result observed = gameSessionClient.read(currentAttemptRequest); + requireNoAmbientTransaction(); + Result exactObservation = exactObservation(currentAttemptRequest, observed, tuple); + + AccountStartSessionAdmissionProtectionEvidence committed = + issuer.withCurrentGameSessionAdmissionProtectionCurrentness( + tupleBytes, + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + capture -> { + StoredParticipation historicalParticipation = + participationRepository + .findHistoricalExact( + request.accountWorldParticipationId(), + request.accountWorldParticipationFence()) + .orElseThrow( + () -> denied("Exact original World participation is unavailable")); + requireParticipationBinding(request, tuple, historicalParticipation); + + StoredEvidence priorObservation = + attemptEvidenceRepository + .findHistoricalExact(historicalParticipation, currentAttemptRequest) + .orElseThrow( + () -> denied("Exact original Game Session observation is unavailable")); + requireUnchangedObservation( + currentAttemptRequest, + exactObservation, + historicalParticipation, + priorObservation); + + AccountStartSessionAdmissionProtectionRequest exactRequest = + AccountStartSessionAdmissionProtectionRequest.create( + tupleBytes, + exactObservation.accountRedemptionProjection(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + exactObservation.originalLeaseExpiresAt(), + historicalParticipation.participationId(), + historicalParticipation.participationFence(), + request.worldHoldIdentity()); + return protectionRepository.createOrReadExact(exactRequest, capture); + }); + + requireNoAmbientTransaction(); + AccountStartSessionAdmissionProtectionEvidence readback = + Objects.requireNonNull( + readbackTransaction.execute( + ignored -> + protectionRepository + .findCurrentExact(committed.request()) + .orElseThrow( + () -> + denied( + "Committed exact Account admission protection is not readable"))), + "Account admission protection readback transaction returned no result"); + + if (!MessageDigest.isEqual(committed.canonicalBytes(), readback.canonicalBytes())) { + throw denied("Committed Account admission protection readback differs"); + } + return readback; + } + + private Result exactObservation( + Request expected, Result observed, StartSessionPostAuthorizationExecutionTuple tuple) { + if (observed == null) { + throw denied("Exact current original Game Session attempt evidence is unavailable"); + } + try { + var canonicalResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observed); + Result exact = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + expected, canonicalResponse); + if (!OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals(exact.phaseState()) + || !sameRequest(expected, exact.request()) + || !MessageDigest.isEqual( + expectedAccountRedemptionProjection(tuple), exact.accountRedemptionProjection())) { + throw denied( + "Current Game Session attempt or full Account redemption projection differs from the original issuer"); + } + return exact; + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact current original Game Session attempt evidence is malformed") + .withCause(malformed) + .asRuntimeException(); + } + } + + private static void requireUnchangedObservation( + Request expectedRequest, + Result observed, + StoredParticipation participation, + StoredEvidence retained) { + if (retained == null + || !participation.participationId().equals(retained.participationId()) + || !expectedRequest.expectedOwnerMutationId().equals(retained.gameSessionOwnerMutationId()) + || !sameRequest(expectedRequest, retained.result().request()) + || !sameResult(observed, retained.result()) + || !OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( + retained.result().phaseState()) + || !retained.originalLeaseExpiresAt().equals(observed.originalLeaseExpiresAt())) { + throw denied("Current original Game Session attempt differs from retained World evidence"); + } + try { + var response = + net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse + .parseFrom(retained.originalResponseBytes()); + Result decoded = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + retained.result().request(), response); + if (!sameResult(retained.result(), decoded) + || !Arrays.equals( + retained.originalResponseBytes(), + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(decoded) + .toByteArray())) { + throw denied("Retained original Game Session response bytes are not canonical"); + } + } catch (com.google.protobuf.InvalidProtocolBufferException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Retained original Game Session response is malformed") + .withCause(malformed) + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Retained original Game Session response is malformed") + .withCause(malformed) + .asRuntimeException(); + } + } + + private static void requireParticipationBinding( + AcquisitionRequest request, + StartSessionPostAuthorizationExecutionTuple tuple, + StoredParticipation participation) { + if (!request.accountWorldParticipationId().equals(participation.participationId()) + || request.accountWorldParticipationFence() != participation.participationFence() + || !tuple.controlPlaneRequestId().equals(participation.controlPlaneRequestId()) + || !MessageDigest.isEqual( + tuple.canonicalBytes(), participation.originalPostAuthorizationTuple()) + || !request + .worldHoldIdentity() + .request() + .targetNamespace() + .equals(participation.targetNamespace()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .equals(participation.canonicalTenantId()) + || !request + .worldHoldIdentity() + .request() + .canonicalGameInstanceId() + .equals(participation.canonicalGameInstanceId()) + || !request.gameSessionOwnerAttemptId().equals(participation.gameSessionOwnerAttemptId()) + || request.gameSessionOwnerFence() != participation.gameSessionOwnerFence()) { + throw denied("Original Account World participation binding differs"); + } + } + + private void requireOriginalBinding( + StartSessionPostAuthorizationExecutionTuple tuple, AcquisitionRequest request) { + if (!"StartSession".equals(tuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(tuple.preAuthorizationTuple().targetOwner()) + || !workloadNamespace.equals( + tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !workloadNamespace.equals(request.worldHoldIdentity().request().targetNamespace()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .equals(request.worldHoldIdentity().request().canonicalTenantId())) { + throw denied("Exact original human StartSession tuple and World hold are required"); + } + requireNonnil(request.gameSessionOwnerMutationId(), "Game Session owner mutation ID"); + requireNonnil(request.gameSessionOwnerAttemptId(), "Game Session owner attempt ID"); + requirePositive(request.gameSessionOwnerFence(), "Game Session owner fence"); + requireNonnil(request.accountWorldParticipationId(), "Account World participation ID"); + requirePositive(request.accountWorldParticipationFence(), "Account World participation fence"); + } + + private static StartSessionPostAuthorizationExecutionTuple decodeOriginalTuple( + byte[] tupleBytes) { + if (tupleBytes == null) throw denied("Complete original StartSession tuple is required"); + try { + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (!Arrays.equals(tupleBytes, tuple.canonicalBytes())) { + throw denied("Original StartSession tuple is not exact canonical bytes"); + } + return tuple; + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Complete canonical original StartSession tuple required") + .withCause(malformed) + .asRuntimeException(); + } + } + + private static byte[] expectedAccountRedemptionProjection( + StartSessionPostAuthorizationExecutionTuple tuple) { + return StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple); + } + + private static boolean sameResult(Result expected, Result actual) { + return expected.originalLeaseExpiresAt().equals(actual.originalLeaseExpiresAt()) + && expected.phaseState().equals(actual.phaseState()) + && sameRequest(expected.request(), actual.request()) + && Arrays.equals( + expected.accountRedemptionProjection(), actual.accountRedemptionProjection()); + } + + private static boolean sameRequest(Request expected, Request actual) { + return expected.targetNamespace().equals(actual.targetNamespace()) + && Arrays.equals( + expected.canonicalPostAuthorizationTuple(), actual.canonicalPostAuthorizationTuple()) + && expected.expectedOwnerAttemptId().equals(actual.expectedOwnerAttemptId()) + && expected.expectedOwnerMutationId().equals(actual.expectedOwnerMutationId()) + && expected.expectedOwnerFence() == actual.expectedOwnerFence(); + } + + private static UUID freshReadId( + StartSessionPostAuthorizationExecutionTuple tuple, AcquisitionRequest request) { + Set occupied = new HashSet<>(); + occupied.addAll( + List.of( + tuple.reservationOwnerId(), + tuple.preAuthorizationTuple().actor().accountId(), + tuple.preAuthorizationTuple().action().scope().tenantId(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerAttemptId(), + request.accountWorldParticipationId(), + request.worldHoldIdentity().holdId(), + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .issuanceOperationId())); + UUID result; + do { + result = UUID.randomUUID(); + } while (occupied.contains(result)); + return result; + } + + private void requireGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + String expectedUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !workloadNamespace.equals(peer.namespace()) + || !expectedUri.equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Game Session workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Admission protection acquisition requires owner currentness outside Account SQL") + .asRuntimeException(); + } + } + + private static void requireNonnil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw denied(name + " must be a canonical non-nil UUID"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) throw denied(name + " must be positive"); + } + + private static StatusRuntimeException denied(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } + + /** Raw bounded DTO; peer and transaction checks precede decoding or dependency calls. */ + public record AcquisitionRequest( + byte[] originalPostAuthorizationTuple, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + WorldCanonicalInitialAdmissionHold.HoldIdentity worldHoldIdentity) { + public AcquisitionRequest { + originalPostAuthorizationTuple = + originalPostAuthorizationTuple == null ? null : originalPostAuthorizationTuple.clone(); + } + + @Override + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple == null ? null : originalPostAuthorizationTuple.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java index e20c425eb4..334e8cd361 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java @@ -123,6 +123,29 @@ public AccountStartSessionAuthorityCapture lockReadExactCurrentFromWorldReceivin current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence, false); } + /** + * Lookup-only original capture read for the distinct authenticated Game Session admission + * currentness callback. The original Logging issuer remains retained evidence, not the caller. + * This does not allocate a capture or provide continuous owner claim protection. + */ + public AccountStartSessionAuthorityCapture lockReadExactCurrentFromGameSessionAdmission( + AccountControlUiActorService.Current current, + StartSessionPreAuthorizationReservationTuple tuple, + String loggingWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + String gameSessionWorkloadUri) { + requireOwnerTransaction(); + Objects.requireNonNull(current, "current committed ControlUI actor is required"); + Objects.requireNonNull(tuple, "exact typed StartSession tuple is required"); + if (!canonicalReceivingWorkload( + gameSessionWorkloadUri, tuple.action().scope().targetNamespace(), "game-session-service")) { + throw unavailable(); + } + return lockReadExactCurrent( + current, tuple, loggingWorkloadUri, reservationOwnerId, reservationClaimFence, false); + } + private AccountStartSessionAuthorityCapture lockReadExactCurrent( AccountControlUiActorService.Current current, StartSessionPreAuthorizationReservationTuple tuple, @@ -496,13 +519,18 @@ private static boolean canonicalLoggingWorkloadUri(String uri, String targetName } private static boolean canonicalWorldWorkload(String uri, String targetNamespace) { - String expectedUri = "spiffe://firemud/ns/" + targetNamespace + "/sa/world-management-service"; + return canonicalReceivingWorkload(uri, targetNamespace, "world-management-service"); + } + + private static boolean canonicalReceivingWorkload( + String uri, String targetNamespace, String service) { + String expectedUri = "spiffe://firemud/ns/" + targetNamespace + "/sa/" + service; GrpcPeerIdentity peer = GrpcPeerIdentity.current(); return !SessionContext.hasAuthenticatedCallerContext() && expectedUri.equals(uri) && peer != null && uri.equals(peer.uri()) - && "world-management-service".equals(peer.service()) + && service.equals(peer.service()) && targetNamespace.equals(peer.namespace()); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java index 4e7f96d4af..f651d5b0ad 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java @@ -34,6 +34,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -675,6 +676,44 @@ T withCurrentWorldReceivingParticipationCurrentness( Function accountMutation) { requirePeer(worldManagementPeerUri); requireNoAmbientTransactionOrSynchronization(); + return withCurrentReceivingParticipationCurrentness( + exactCanonicalPostAuthorizationTuple, + actualGameSessionOwnerAttemptId, + actualGameSessionOwnerFence, + accountMutation, + false); + } + + /** + * Revalidates original authority for a distinct Account-local Game Session admission protection + * callback. This lookup-only currentness building block neither acquires admission participation + * by itself nor establishes continuous Game Session claim protection. The exact configured Game + * Session peer, without end-user context or ambient SQL, is required before tuple decoding. + */ + T withCurrentGameSessionAdmissionProtectionCurrentness( + byte[] exactCanonicalPostAuthorizationTuple, + UUID actualGameSessionOwnerAttemptId, + long actualGameSessionOwnerFence, + Function accountMutation) { + requirePeer(gameSessionPeerUri); + if (SessionContext.hasAuthenticatedCallerContext()) { + throw denied("Game Session admission currentness requires no authenticated end-user context"); + } + requireNoAmbientTransactionOrSynchronization(); + return withCurrentReceivingParticipationCurrentness( + exactCanonicalPostAuthorizationTuple, + actualGameSessionOwnerAttemptId, + actualGameSessionOwnerFence, + accountMutation, + true); + } + + private T withCurrentReceivingParticipationCurrentness( + byte[] exactCanonicalPostAuthorizationTuple, + UUID actualGameSessionOwnerAttemptId, + long actualGameSessionOwnerFence, + Function accountMutation, + boolean gameSessionAdmission) { byte[] exactPostTupleBytes = copy(exactCanonicalPostAuthorizationTuple); StartSessionPostAuthorizationExecutionTuple postTuple = @@ -684,10 +723,13 @@ T withCurrentWorldReceivingParticipationCurrentness( if (!"game-session-service".equals(tuple.targetOwner())) { throw denied("Original StartSession target owner must remain Game Session"); } - GrpcPeerIdentity worldPeer = GrpcPeerIdentity.current(); - if (worldPeer == null - || !tuple.action().scope().targetNamespace().equals(worldPeer.namespace())) { - throw denied("StartSession target namespace does not match the authenticated World peer"); + GrpcPeerIdentity receivingPeer = GrpcPeerIdentity.current(); + if (receivingPeer == null + || !tuple.action().scope().targetNamespace().equals(receivingPeer.namespace())) { + throw denied( + gameSessionAdmission + ? "StartSession target namespace does not match the authenticated Game Session peer" + : "StartSession target namespace does not match the authenticated World peer"); } if (!loggingPeerUri.equals(postTuple.authenticatedWorkloadIdentity())) { throw denied("Original StartSession Logging workload identity changed"); @@ -707,7 +749,7 @@ T withCurrentWorldReceivingParticipationCurrentness( AccountStartSessionOperatorAuthorityBundle observedBundle = AccountStartSessionOperatorAuthorityBundle.decode(observed.authorityEvidenceBundle()); observedBundle.requireTupleBinding(tuple); - requireWorldReceivingPostTupleBinding(postTuple, observed, tuple); + requireReceivingPostTupleBinding(postTuple, observed, tuple); ReadRedeemedOperationProjectionRequest redemptionRequest = new ReadRedeemedOperationProjectionRequest( exactPreTupleBytes, @@ -738,18 +780,26 @@ T withCurrentWorldReceivingParticipationCurrentness( AccountStartSessionOperatorAuthorityBundle exactBundle = AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()); exactBundle.requireTupleBinding(tuple); - requireWorldReceivingPostTupleBinding(postTuple, exact, tuple); + requireReceivingPostTupleBinding(postTuple, exact, tuple); requireRedeemedProjectionBinding( exact, tuple, redemptionRequest, exactBundle, clock.instant()); AccountStartSessionAuthorityCapture lockedCapture = - captureRepository.lockReadExactCurrentFromWorldReceiving( - current, - tuple, - loggingPeerUri, - postTuple.reservationOwnerId(), - postTuple.reservationClaimFence(), - worldManagementPeerUri); + gameSessionAdmission + ? captureRepository.lockReadExactCurrentFromGameSessionAdmission( + current, + tuple, + loggingPeerUri, + postTuple.reservationOwnerId(), + postTuple.reservationClaimFence(), + gameSessionPeerUri) + : captureRepository.lockReadExactCurrentFromWorldReceiving( + current, + tuple, + loggingPeerUri, + postTuple.reservationOwnerId(), + postTuple.reservationClaimFence(), + worldManagementPeerUri); var originalReference = AccountStartSessionOperatorAuthorityBundle.fromSharedReference( exact.bundleReference()); @@ -760,7 +810,7 @@ T withCurrentWorldReceivingParticipationCurrentness( }); } - private void requireWorldReceivingPostTupleBinding( + private void requireReceivingPostTupleBinding( StartSessionPostAuthorizationExecutionTuple supplied, IssuanceRecord original, StartSessionPreAuthorizationReservationTuple tuple) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java index d97a5d5f18..3b6ae7a0ff 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java @@ -2,7 +2,6 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; -import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -10,7 +9,6 @@ import java.util.HashSet; import java.util.HexFormat; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -21,6 +19,7 @@ import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.Candidate; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; @@ -28,7 +27,6 @@ import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.security.SessionContext; @@ -205,7 +203,7 @@ private Result exactObservation( if (!OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals(exact.phaseState()) || !sameRequest(expected, exact.request(), false) || !MessageDigest.isEqual( - expectedAccountRedemptionProjection(originalTuple), + StartSessionAccountRedemptionProjection.fromOriginalTuple(originalTuple), exact.accountRedemptionProjection())) { throw denied( "Current Game Session attempt or full Account redemption projection differs from the original issuer"); @@ -231,7 +229,7 @@ private void requireStoredEvidenceBinding( || !OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( evidence.result().phaseState()) || !MessageDigest.isEqual( - expectedAccountRedemptionProjection(originalTuple), + StartSessionAccountRedemptionProjection.fromOriginalTuple(originalTuple), evidence.result().accountRedemptionProjection()) || !evidence.originalLeaseExpiresAt().equals(evidence.result().originalLeaseExpiresAt())) { throw denied("Retained original Game Session attempt proof differs from the exact request"); @@ -263,39 +261,6 @@ private void requireStoredEvidenceBinding( } } - private static byte[] expectedAccountRedemptionProjection( - StartSessionPostAuthorizationExecutionTuple originalTuple) { - StartSessionAuthorityEvidenceBundle bundle = - StartSessionAuthorityEvidenceBundle.decode(originalTuple.authorityEvidenceBundleBytes()); - long issuanceFence; - try { - issuanceFence = Long.parseLong(originalTuple.issuanceFence()); - } catch (NumberFormatException malformed) { - throw denied("Original Account issuance fence is malformed"); - } - if (issuanceFence <= 0L) throw denied("Original Account issuance fence is not positive"); - Map projection = - Map.of( - "projectionSchemaId", - "accountStartSessionRedemptionProjection", - "projectionSchemaVersion", - "1", - "authorizationReferenceFingerprint", - originalTuple.authorizationReferenceFingerprint(), - "authorityEvidenceBundle", - bundle.jsonValue(), - "issuanceOperationId", - bundle.issuanceOperationId().toString(), - "issuanceFence", - issuanceFence); - try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); - } catch (IOException malformed) { - throw new IllegalStateException( - "Could not encode the original Account redemption projection", malformed); - } - } - private static boolean sameParticipation( StoredParticipation expected, StoredParticipation actual) { if (!expected.participationId().equals(actual.participationId()) diff --git a/services/account-service/src/main/resources/db/migration/V133__start_session_admission_protection.sql b/services/account-service/src/main/resources/db/migration/V133__start_session_admission_protection.sql new file mode 100644 index 0000000000..625bb03898 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V133__start_session_admission_protection.sql @@ -0,0 +1,365 @@ +-- Distinct Account source protection through original Game Session admission. World +-- settlement and original-attempt observation expiry never settle this participation. +-- These integrity guards do not authenticate a producer or Game Session terminal RPC. +CREATE TABLE account_start_session_admission_protections ( + protection_id UUID PRIMARY KEY CHECK (protection_id <> '00000000-0000-0000-0000-000000000000'::UUID), + protection_fence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE CHECK (protection_fence > 0), + control_plane_request_id VARCHAR(128) NOT NULL UNIQUE + REFERENCES account_start_session_authority_captures(control_plane_request_id) ON DELETE RESTRICT, + original_post_authorization_tuple BYTEA NOT NULL CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + account_redemption_projection BYTEA NOT NULL CHECK (octet_length(account_redemption_projection) BETWEEN 1 AND 262144), + game_session_owner_mutation_id UUID NOT NULL UNIQUE CHECK (game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_attempt_id UUID NOT NULL CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + original_lease_expires_at TIMESTAMPTZ NOT NULL CHECK (isfinite(original_lease_expires_at)), + account_world_participation_id UUID NOT NULL UNIQUE + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + target_namespace VARCHAR(63) NOT NULL CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + canonical_tenant_id UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id) ON DELETE RESTRICT, + canonical_game_instance_id UUID NOT NULL CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + capture_source_version BIGINT NOT NULL CHECK (capture_source_version > 0), + capture_source_fence BIGINT NOT NULL CHECK (capture_source_fence > 0), + capture_sha256 VARCHAR(64) NOT NULL CHECK (capture_sha256 ~ '^[0-9a-f]{64}$'), + world_admission_hold_identity_bytes BYTEA NOT NULL CHECK (octet_length(world_admission_hold_identity_bytes) BETWEEN 1 AND 262144), + request_binding_bytes BYTEA NOT NULL CHECK (octet_length(request_binding_bytes) BETWEEN 1 AND 1048576), + request_binding_digest VARCHAR(71) NOT NULL + CHECK (request_binding_digest = 'sha256:' || encode(sha256(request_binding_bytes), 'hex')), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE account_start_session_admission_protection_sources ( + protection_id UUID NOT NULL REFERENCES account_start_session_admission_protections(protection_id) ON DELETE RESTRICT, + source_key VARCHAR(2048) NOT NULL REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (protection_id, source_key) +); +CREATE INDEX account_ss_admission_sources_by_key + ON account_start_session_admission_protection_sources(source_key, protection_id); + +CREATE TABLE account_start_session_admission_protection_settlements ( + protection_id UUID PRIMARY KEY REFERENCES account_start_session_admission_protections(protection_id) ON DELETE RESTRICT, + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + terminal_bytes BYTEA NOT NULL CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 25165824), + terminal_digest VARCHAR(71) NOT NULL CHECK (terminal_digest = 'sha256:' || encode(sha256(terminal_bytes), 'hex')), + settled_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +-- [jooq ignore start] +-- PostgreSQL enforces exact retained millisecond precision; jOOQ's DDL simulator +-- does not evaluate this date_trunc part. Keep the column and table visible. +ALTER TABLE account_start_session_admission_protections + ADD CONSTRAINT account_ss_admission_original_lease_millis + CHECK (original_lease_expires_at = date_trunc('milliseconds', original_lease_expires_at)); + +CREATE FUNCTION account_ss_admission_is_settled(protection_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT EXISTS (SELECT 1 FROM account_start_session_admission_protection_settlements + WHERE protection_id = protection_value) +$$; + +-- Called only after the owning writer has locked its canonical source-key set. This +-- shared addition preserves the independently assembled World and other owner guards. +CREATE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; + +-- Account currentness must independently reconstruct the exact live original actor, +-- registry, signer and source capture before invoking this integrity boundary. SQL +-- validates retained bindings; neither a capture nor a historical observation grants +-- admission, and a gap requires the producer's fresh unchanged-source validation. +CREATE FUNCTION account_ss_admission_assert_current( + original account_start_session_admission_protections, + require_complete BOOLEAN +) RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + capture account_start_session_authority_captures%ROWTYPE; + world_parent account_start_session_world_participations%ROWTYPE; + observation account_start_session_world_original_attempt_evidence%ROWTYPE; + authorization_row account_start_session_operator_authorizations%ROWTYPE; + snapshot_value JSONB; + tuple_value JSONB; + request_value JSONB; + hold_value JSONB; + hold_request JSONB; + projection_value JSONB; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + keys TEXT[]; +BEGIN + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_value->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM original.control_plane_request_id THEN + RAISE EXCEPTION 'Admission protection requires the exact original source snapshot' USING ERRCODE = '23514'; + END IF; + keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(keys, snapshot_value); + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT world_parent FROM account_start_session_world_participations + WHERE participation_id = original.account_world_participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT observation FROM account_start_session_world_original_attempt_evidence + WHERE participation_id = original.account_world_participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = original.control_plane_request_id FOR UPDATE NOWAIT; + PERFORM protection_id FROM account_start_session_admission_protections + WHERE protection_id = original.protection_id FOR UPDATE NOWAIT; + -- Always check actual database time after every lock, including exact recovery. + IF original.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() + OR account_ss_admission_is_settled(original.protection_id) THEN + RAISE EXCEPTION 'Original StartSession admission protection is not current' + USING ERRCODE = '23514'; + END IF; + IF capture.source_version IS DISTINCT FROM original.capture_source_version + OR capture.source_fence IS DISTINCT FROM original.capture_source_fence + OR capture.canonical_sha256 IS DISTINCT FROM original.capture_sha256 + OR world_parent.participation_fence IS DISTINCT FROM original.account_world_participation_fence + OR world_parent.control_plane_request_id IS DISTINCT FROM original.control_plane_request_id + OR world_parent.original_post_authorization_tuple IS DISTINCT FROM original.original_post_authorization_tuple + OR world_parent.game_session_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR world_parent.game_session_owner_fence IS DISTINCT FROM original.game_session_owner_fence + OR world_parent.target_namespace IS DISTINCT FROM original.target_namespace + OR world_parent.canonical_tenant_id IS DISTINCT FROM original.canonical_tenant_id + OR world_parent.canonical_game_instance_id IS DISTINCT FROM original.canonical_game_instance_id + OR observation.target_namespace IS DISTINCT FROM original.target_namespace + OR observation.game_session_owner_mutation_id IS DISTINCT FROM original.game_session_owner_mutation_id + OR observation.game_session_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR observation.game_session_owner_fence IS DISTINCT FROM original.game_session_owner_fence + OR observation.original_lease_expires_at IS DISTINCT FROM original.original_lease_expires_at + OR authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM original.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM original.game_session_owner_fence + OR authorization_row.redemption_reference_fingerprint IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR authorization_row.redemption_authority_evidence_bundle IS DISTINCT FROM authorization_row.authority_evidence_bundle + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization_row.pre_authorization_tuple + OR capture.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence THEN + RAISE EXCEPTION 'Original StartSession admission protection differs from its retained owner bindings' + USING ERRCODE = '23514'; + END IF; + tuple_value := convert_from(original.original_post_authorization_tuple, 'UTF8')::JSONB; + IF tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + OR tuple_value->>'authorizationReferenceFingerprint' IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization_row.issuance_fence::TEXT + OR tuple_value->'authorityEvidenceBundle' IS DISTINCT FROM convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB THEN + RAISE EXCEPTION 'Admission tuple differs from original Account issuance' USING ERRCODE = '23514'; + END IF; + projection_value := convert_from(original.account_redemption_projection, 'UTF8')::JSONB; + IF projection_value IS DISTINCT FROM jsonb_build_object( + 'projectionSchemaId', 'accountStartSessionRedemptionProjection', + 'projectionSchemaVersion', '1', + 'authorizationReferenceFingerprint', authorization_row.authorization_reference_fingerprint, + 'authorityEvidenceBundle', convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB, + 'issuanceOperationId', authorization_row.issuance_operation_id::TEXT, + 'issuanceFence', authorization_row.issuance_fence) THEN + RAISE EXCEPTION 'Admission projection differs from complete original Account redemption' USING ERRCODE = '23514'; + END IF; + request_value := convert_from(original.request_binding_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request_value) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Admission request binding is not an object' USING ERRCODE = '23514'; + END IF; + IF (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 10 + OR EXISTS (SELECT 1 FROM jsonb_each(request_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR request_value->>'schema' IS DISTINCT FROM 'account-start-session-admission-protection-request/v1' + OR request_value->>'originalPostAuthorizationTupleBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g') + OR request_value->>'accountRedemptionProjectionBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.account_redemption_projection, 'base64'), E'[\n\r]', '', 'g') + OR request_value->>'gameSessionOwnerMutationId' IS DISTINCT FROM original.game_session_owner_mutation_id::TEXT + OR request_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM original.game_session_owner_attempt_id::TEXT + OR request_value->>'gameSessionOwnerFence' IS DISTINCT FROM original.game_session_owner_fence::TEXT + OR request_value->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') + OR request_value->>'accountWorldParticipationId' IS DISTINCT FROM original.account_world_participation_id::TEXT + OR request_value->>'accountWorldParticipationFence' IS DISTINCT FROM original.account_world_participation_fence::TEXT + OR request_value->>'worldAdmissionHoldIdentityBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') THEN + RAISE EXCEPTION 'Admission request binding differs from exact immutable selectors' USING ERRCODE = '23514'; + END IF; + hold_value := convert_from(original.world_admission_hold_identity_bytes, 'UTF8')::JSONB; + hold_request := convert_from(decode(hold_value->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + IF hold_value->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' + OR (SELECT count(*) FROM jsonb_object_keys(hold_value)) <> 5 + OR NOT (hold_value ?& ARRAY['schema', 'holdId', 'holdFence', 'holdBindingDigest', 'requestBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(hold_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR (hold_value->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR (hold_value->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR hold_value->>'holdBindingDigest' IS DISTINCT FROM encode(sha256(decode(hold_value->>'requestBytesBase64', 'base64')), 'hex') + OR hold_request->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR hold_request->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace + OR hold_request->'request'->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT + OR hold_request->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'Admission hold identity differs from original instance and request' USING ERRCODE = '23514'; + END IF; + -- Original World source children remain immutable even when World has settled. + PERFORM account_start_session_world_participation_assert_sources(world_parent.participation_id, snapshot_value); + IF require_complete THEN + IF (SELECT count(*) FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id) <> jsonb_array_length(snapshot_value->'sourceVector') THEN + RAISE EXCEPTION 'Admission protection has incomplete or extra source children' USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + source_bytes := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(source_bytes); + IF NOT EXISTS (SELECT 1 FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id AND source_key = source_key_value + AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Admission source child differs from complete original capture' USING ERRCODE = '23514'; + END IF; + END LOOP; + END IF; + IF original.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession admission expiry elapsed during integrity validation' USING ERRCODE = '23514'; + END IF; +END; +$$; + +CREATE FUNCTION account_ss_admission_read_current_exact(protection_value UUID, fence_value BIGINT, request_value BYTEA) +RETURNS SETOF account_start_session_admission_protections LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE original account_start_session_admission_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_admission_protections + WHERE protection_id = protection_value AND protection_fence = fence_value; + IF original.request_binding_bytes IS DISTINCT FROM request_value THEN + RAISE EXCEPTION 'Original admission recovery binding differs' USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_admission_assert_current(original, TRUE); + RETURN NEXT original; +END; +$$; + +CREATE FUNCTION account_ss_admission_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() THEN + RAISE EXCEPTION 'Admission protection must be created by its producer transaction' USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_admission_assert_current(NEW::account_start_session_admission_protections, FALSE); + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_admission_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE producer BIGINT; +BEGIN + SELECT producer_xid INTO STRICT producer FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + IF producer IS DISTINCT FROM txid_current() + OR account_start_session_world_participation_source_key(NEW.source_evidence) IS DISTINCT FROM NEW.source_key THEN + RAISE EXCEPTION 'Admission sources must be exact same-producer children' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_admission_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE original account_start_session_admission_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + PERFORM account_ss_admission_assert_current(original, TRUE); + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_ss_admission_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession admission evidence is append-only' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_admission_validate BEFORE INSERT ON account_start_session_admission_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_insert_guard(); +CREATE TRIGGER account_ss_admission_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protections + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_sources_validate BEFORE INSERT ON account_start_session_admission_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_source_insert_guard(); +CREATE TRIGGER account_ss_admission_sources_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_sources_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protection_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE CONSTRAINT TRIGGER account_ss_admission_complete AFTER INSERT ON account_start_session_admission_protections + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_ss_admission_complete_guard(); +CREATE TRIGGER account_ss_admission_settlements_immutable BEFORE UPDATE OR DELETE ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +-- The authenticated exact Game Session terminal API is not yet composed. Reject every +-- settlement insertion until its sealed complete terminal binding guard replaces this +-- unpublished gate. An outcome assertion alone can never release source protection. +CREATE TRIGGER account_ss_admission_settlements_disabled BEFORE INSERT ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_no_mutation(); +CREATE TRIGGER account_ss_admission_settlements_no_truncate BEFORE TRUNCATE ON account_start_session_admission_protection_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_admission_no_mutation(); + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ FOR operation_value IN SELECT DISTINCT s.operation_id + FROM account_draft_authorization_sources s$anchor$; +BEGIN + SELECT pg_get_functiondef('account_control_ui_hold_required_sources(TEXT[])'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled admission source-writer anchor'; + END IF; + EXECUTE replace(original, anchor, + E' PERFORM account_ss_admission_assert_no_pending(source_keys);\n' || anchor); +END; +$migration$; + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ FOR operation IN SELECT DISTINCT source.operation_id + FROM account_draft_authorization_changed_scopes changed$anchor$; +BEGIN + SELECT pg_get_functiondef('account_draft_authorization_source_change_guard()'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled admission source-change anchor'; + END IF; + EXECUTE replace(original, anchor, $guard$ PERFORM account_ss_admission_assert_no_pending( + ARRAY(SELECT source_key FROM account_draft_authorization_changed_scopes + WHERE change_id = OLD.change_id)); +$guard$ || anchor); +END; +$migration$; + +DO $migration$ +DECLARE original TEXT; + anchor TEXT := $anchor$ IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED'$anchor$; +BEGIN + SELECT pg_get_functiondef('account_hosted_terms_disclosure_handoff_guard()'::REGPROCEDURE) INTO STRICT original; + IF (length(original) - length(replace(original, anchor, ''))) / length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one assembled admission disclosure anchor'; + END IF; + EXECUTE replace(original, anchor, $guard$ IF OLD.status IN ('PREPARED', 'AMBIGUOUS') AND NEW.status = 'DISPATCH_AUTHORIZED' THEN + PERFORM source_lock.source_key FROM account_draft_authorization_source_locks source_lock + JOIN (SELECT OLD.source_key AS source_key UNION + SELECT source_key FROM account_hosted_terms_disclosure_sources + WHERE handoff_id = OLD.handoff_id) exact_source USING (source_key) + ORDER BY account_publication_authorization_source_sort_key(source_lock.source_key) + FOR UPDATE OF source_lock NOWAIT; + PERFORM account_ss_admission_assert_no_pending(ARRAY( + SELECT OLD.source_key UNION SELECT source_key FROM account_hosted_terms_disclosure_sources + WHERE handoff_id = OLD.handoff_id)); + END IF; +$guard$ || anchor); +END; +$migration$; +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java index 568638759f..342194bfbc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -17,6 +17,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import org.flywaydb.core.Flyway; @@ -27,6 +28,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -109,6 +111,7 @@ void warmedEntryStillRequiresQuietCoverageAndLostResponseRecoveryPreservesExpiry void callerCannotForgeCaptureWriteTablesInvokePrivateWriterOrEscalate() throws Exception { var context = context(); var original = finalized(context, 15000); + String diagnosticStart = observeWal(context, "after-original-finalization"); List denied = List.of( "INSERT INTO " @@ -156,24 +159,107 @@ void callerCannotForgeCaptureWriteTablesInvokePrivateWriterOrEscalate() throws E assertThat(sqlState(failure)) .isEqualTo(sql.endsWith("'0/1'::pg_lsn)") ? "42883" : "42501")); } + observeWal(context, "after-denial-loop"); // A hostile session search path cannot replace fully qualified owner objects. - JSONB created = - callerTransaction( - context, - connection -> { - DSL.using(connection).execute("SET LOCAL search_path = pg_temp, public"); - return invoke( - connection, - context, - "confirm", - request(original), - original.evidence().sha256(), - original.decision()); - }); + JSONB created; + try { + created = + callerTransaction( + context, + connection -> { + DSL.using(connection).execute("SET LOCAL search_path = pg_temp, public"); + // Observe from the administrator only; do not warm this new caller with SQL. + observeWal(context, "before-fresh-caller-confirm"); + return invoke( + connection, + context, + "confirm", + request(original), + original.evidence().sha256(), + original.decision()); + }); + } catch (SQLException failure) { + retainFailureWal(context, diagnosticStart, failure); + throw failure; + } assertProof(context, original, created); assertThat(call(context, original, "read_receipt")).isEqualTo(created); } + private static String observeWal(Context context, String phase) { + var observation = + context + .dsl() + .fetchSingle( + "SELECT pg_current_wal_insert_lsn()::text AS insert_lsn, pg_current_wal_flush_lsn()::text AS flush_lsn, ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint AS observed_ms"); + System.out.println( + "Protected-entry administrator WAL observation " + phase + " " + observation); + return observation.get("flush_lsn", String.class); + } + + private static void retainFailureWal(Context context, String start, SQLException failure) { + // Failure diagnostics must never replace the original failure or force WAL durability. + try { + if (!(failure instanceof PSQLException postgres)) { + System.out.println("Protected-entry WAL diagnostic unavailable: no PostgreSQL detail"); + return; + } + var serverError = postgres.getServerErrorMessage(); + String detail = serverError == null ? null : serverError.getDetail(); + if (detail == null) { + System.out.println("Protected-entry WAL diagnostic unavailable: no PostgreSQL detail"); + return; + } + var upper = Pattern.compile("(?:^| )upper_lsn=([0-9A-F]+/[0-9A-F]+)(?: |$)").matcher(detail); + if (!upper.find()) { + System.out.println("Protected-entry WAL diagnostic unavailable: no captured upper LSN"); + return; + } + String end = upper.group(1); + var bounds = + context + .dsl() + .fetchSingle( + "SELECT pg_wal_lsn_diff(?::pg_lsn, ?::pg_lsn)::bigint AS bytes, (pg_walfile_name_offset(?::pg_lsn)).file_offset AS start_offset, pg_size_bytes(current_setting('wal_segment_size')) AS segment_bytes", + end, + start, + start); + long bytes = bounds.get("bytes", Long.class); + long offset = bounds.get("start_offset", Long.class); + long segmentBytes = bounds.get("segment_bytes", Long.class); + if (bytes <= 0 || bytes > 2 * segmentBytes - offset) { + System.out.println( + "Protected-entry WAL diagnostic unavailable: empty range or more than two segments " + + start + + ".." + + end); + return; + } + // This container belongs only to this test class. Retain decoded output, never an archive. + var dump = + POSTGRES.execInContainer( + "pg_waldump", + "--path=/var/lib/postgresql/data/pg_wal", + "--start=" + start, + "--end=" + end, + "--limit=128"); + String output = dump.getStdout() + dump.getStderr(); + System.out.println( + "Protected-entry WAL diagnostic " + + start + + ".." + + end + + " exit=" + + dump.getExitCode() + + " (maximum two segments, 128 records, 16384 characters):\n" + + output.substring(0, Math.min(output.length(), 16384))); + System.out.println( + "Protected-entry WAL diagnostic may be partial or unreadable before ordinary flushing; no flush, checkpoint, segment switch or retry was requested. Record/character limits may truncate provenance, and WAL records alone do not identify their backend."); + } catch (Exception diagnosticFailure) { + System.out.println("Protected-entry WAL diagnostic unavailable: " + diagnosticFailure); + } + } + @Test void ownFinalizationAndReleasedSubtransactionCannotSupplyIndependentOriginal() { for (boolean subtransaction : List.of(false, true)) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java new file mode 100644 index 0000000000..d194bcd05e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -0,0 +1,823 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.Connection; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * SQL integrity and source-writer definitions. Upstream Account capture, redeemed authorization, + * World settlement and Game Session observation are explicitly stipulated with upstream triggers + * disabled. New V133 guards remain enabled for acquisition and all assertions. These fixtures are + * not genuine authenticated Account/World/Game Session producer or consumer proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionAdmissionProtectionPostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void installsAdditiveHooksWithoutRemovingExistingOwnerChecks() { + Fixture fixture = fixture(); + for (String function : + List.of( + "account_control_ui_hold_required_sources(text[])", + "account_draft_authorization_source_change_guard()", + "account_hosted_terms_disclosure_handoff_guard()")) { + String definition = + fixture + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", function) + .get(0, String.class); + assertThat(definition) + .contains( + "account_ss_admission_assert_no_pending", + "account_start_session_world_participations", + "account_selected_owner_intake_source_read"); + } + String hold = + fixture + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef('account_control_ui_hold_required_sources(text[])'::regprocedure)") + .get(0, String.class); + assertThat(hold) + .contains( + "account_draft_authorization_sources", + "account_selected_publication_sources", + "account_game_logic_intake_sources", + "account_game_logic_intake_source_read_sources"); + } + + @Test + void exactCurrentReadPreservesIdentityWithoutAllocatingAndWorldCommitCannotReleaseIt() { + Fixture fixture = fixture(); + acquire(fixture); + Long sequence = sequenceValue(fixture); + for (int retry = 0; retry < 2; retry++) { + var current = + fixture + .transaction() + .execute( + status -> + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request())); + assertThat(current.get("protection_id", UUID.class)).isEqualTo(fixture.protectionId()); + assertThat(current.get("request_binding_bytes", byte[].class)) + .containsExactly(fixture.request()); + } + assertThat(sequenceValue(fixture)).isEqualTo(sequence); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT account_start_session_world_participation_is_settled(?)", + fixture.worldId()) + .get(0, Boolean.class)) + .isTrue(); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + fixture.source().key()))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + } + + @Test + void pendingAdmissionExcludesRealSourceChangeCompletionAndDisclosureDispatch() { + Fixture fixture = fixture(); + acquire(fixture); + UUID changeId = UUID.randomUUID(); + fixture + .transaction() + .executeWithoutResult( + status -> { + insert( + fixture.dsl(), + "account_draft_authorization_source_changes", + "change_id", + changeId, + "binding", + bytes("change"), + "status", + "WAITING"); + insert( + fixture.dsl(), + "account_draft_authorization_changed_scopes", + "change_id", + changeId, + "source_key", + fixture.source().key()); + }); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes SET status = 'SOURCE_COMMITTED', committed_at = clock_timestamp() WHERE change_id = ?", + changeId))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + UUID handoffId = UUID.randomUUID(); + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_hosted_terms_disclosure_handoffs", + "handoff_id", + handoffId, + "request_id", + UUID.randomUUID(), + "kind", + "CATALOG", + "source_key", + fixture.source().key(), + "predecessor_digest", + "sha256:" + "a".repeat(64), + "candidate_digest", + "sha256:" + "b".repeat(64), + "effective_at", + OffsetDateTime.now().plusDays(1), + "binding", + bytes("disclosure"), + "binding_digest", + "sha256:" + hash(bytes("disclosure")), + "status", + "PREPARED")); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 WHERE handoff_id = ?", + handoffId))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + } + + @Test + void rawChangedCaptureAndIncompleteChildrenCannotBecomeProtection() { + Fixture changed = fixture(); + assertThatThrownBy( + () -> + changed + .transaction() + .executeWithoutResult(status -> insertProtection(changed, 99L))) + .hasMessageContaining("retained owner bindings"); + Fixture incomplete = fixture(); + assertThatThrownBy( + () -> + incomplete + .transaction() + .executeWithoutResult(status -> insertProtection(incomplete, 11L))) + .hasMessageContaining("incomplete or extra source children"); + } + + @Test + void immutableRowsAndUnprovedTerminalCannotReleaseProtection() { + Fixture fixture = fixture(); + acquire(fixture); + for (String table : + List.of( + "account_start_session_admission_protections", + "account_start_session_admission_protection_sources")) { + assertThatThrownBy(() -> fixture.dsl().execute("DELETE FROM " + table)) + .hasMessageContaining("append-only"); + assertThatThrownBy(() -> fixture.dsl().execute("TRUNCATE " + table + " CASCADE")) + .hasMessageContaining("append-only"); + } + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_admission_protection_sources SET source_evidence = ?", + bytes("changed"))) + .hasMessageContaining("append-only"); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO account_start_session_admission_protection_settlements (protection_id, outcome, terminal_bytes, terminal_digest) VALUES (?, 'ABORTED', ?, ?)", + fixture.protectionId(), + bytes("unproved"), + "sha256:" + hash(bytes("unproved")))) + .hasMessageContaining("append-only"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void expiredOriginalCannotRecoverEvenWhenRetainedIdentityAndSourcesRemain() { + Fixture fixture = fixture(); + acquire(fixture); + // Stipulate passage of the immutable original expiry without changing protection: + // rewriting the fixture row requires disabling the immutable upstream/new triggers. + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_admission_protections SET original_lease_expires_at = date_trunc('milliseconds', clock_timestamp() - INTERVAL '1 second') WHERE protection_id = ?", + fixture.protectionId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request()))) + .hasMessageContaining("not current"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void currentRecoveryRechecksDatabaseExpiryAfterTheCallerWaitsForOriginalCaptureLock() + throws Exception { + Fixture fixture = fixture(3_000L); + acquire(fixture); + var executor = Executors.newSingleThreadExecutor(); + CountDownLatch entered = new CountDownLatch(1); + try (Connection lock = fixture.dataSource().getConnection()) { + lock.setAutoCommit(false); + DSL.using(lock, SQLDialect.POSTGRES) + .fetch( + "SELECT control_plane_request_id FROM account_start_session_authority_captures WHERE control_plane_request_id = ? FOR UPDATE", + fixture.requestId()); + var waiting = + executor.submit( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> { + entered.countDown(); + // The currentness producer's original-capture lock can wait before the + // V133 + // boundary. V133 itself uses NOWAIT to avoid reversing source lock + // order. + fixture + .dsl() + .fetch( + "SELECT control_plane_request_id FROM account_start_session_authority_captures WHERE control_plane_request_id = ? FOR UPDATE", + fixture.requestId()); + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request()); + })); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + long expiryDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (fixture + .dsl() + .fetchSingle("SELECT clock_timestamp() >= ?::timestamptz", fixture.expiry()) + .get(0, Boolean.class) + .equals(false) + && System.nanoTime() < expiryDeadline) { + Thread.sleep(20L); + } + assertThat( + fixture + .dsl() + .fetchSingle("SELECT clock_timestamp() >= ?::timestamptz", fixture.expiry()) + .get(0, Boolean.class)) + .isTrue(); + assertThat(waiting.isDone()).isFalse(); + lock.commit(); + assertThatThrownBy(() -> waiting.get(5, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasStackTraceContaining("not current"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + private static void acquire(Fixture fixture) { + fixture + .transaction() + .executeWithoutResult( + status -> { + insertProtection(fixture, 11L); + insert( + fixture.dsl(), + "account_start_session_admission_protection_sources", + "protection_id", + fixture.protectionId(), + "source_key", + fixture.source().key(), + "source_evidence", + fixture.source().canonicalBytes()); + }); + } + + private static void insertProtection(Fixture fixture, long version) { + insert( + fixture.dsl(), + "account_start_session_admission_protections", + "protection_id", + fixture.protectionId(), + "control_plane_request_id", + fixture.requestId(), + "original_post_authorization_tuple", + fixture.tuple(), + "account_redemption_projection", + fixture.projection(), + "game_session_owner_mutation_id", + fixture.mutationId(), + "game_session_owner_attempt_id", + fixture.attemptId(), + "game_session_owner_fence", + 47L, + "original_lease_expires_at", + fixture.expiry(), + "account_world_participation_id", + fixture.worldId(), + "account_world_participation_fence", + 1L, + "target_namespace", + "test", + "canonical_tenant_id", + fixture.tenantId(), + "canonical_game_instance_id", + fixture.instanceId(), + "capture_source_version", + version, + "capture_source_fence", + 13L, + "capture_sha256", + hash(bytes("{}")), + "world_admission_hold_identity_bytes", + fixture.hold(), + "request_binding_bytes", + fixture.request(), + "request_binding_digest", + "sha256:" + hash(fixture.request())); + } + + private static Fixture fixture() { + return fixture(60_000L); + } + + private static Fixture fixture(long leaseMillis) { + String schema = "ss_admission_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + OffsetDateTime now = + dsl.fetchSingle("SELECT clock_timestamp()") + .get(0, OffsetDateTime.class) + .truncatedTo(ChronoUnit.MILLIS); + UUID tenant = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + UUID actor = UUID.randomUUID(); + UUID mutation = UUID.randomUUID(); + UUID attempt = UUID.randomUUID(); + UUID world = UUID.randomUUID(); + UUID issuance = UUID.randomUUID(); + String requestId = "original/" + UUID.randomUUID(); + SourceEvidence evidence = + new SourceEvidence( + SourceKind.HOSTED_TERMS, "test-terms", "1", "1", null, null, bytes("terms")); + byte[] tuple = + json( + Map.of( + "preAuthorizationReservationTuple", + Map.of(), + "authorizationReferenceFingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "issuanceFence", + "9", + "authorityEvidenceBundle", + Map.of())); + byte[] projection = + json( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "authorityEvidenceBundle", + Map.of(), + "issuanceOperationId", + issuance.toString(), + "issuanceFence", + 9L)); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + "test", + tenant, + "test-world", + UUID.randomUUID(), + UUID.randomUUID(), + "SHARED", + instance, + UUID.randomUUID(), + 1L, + "separate-initial-admission-identity", + "b".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + byte[] hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, UUID.randomUUID(), UUID.randomUUID()) + .canonicalBytes(); + OffsetDateTime expiry = now.plusNanos(leaseMillis * 1_000_000L); + byte[] request = + json( + Map.of( + "schema", + "account-start-session-admission-protection-request/v1", + "originalPostAuthorizationTupleBytesBase64", + base64(tuple), + "accountRedemptionProjectionBytesBase64", + base64(projection), + "gameSessionOwnerMutationId", + mutation.toString(), + "gameSessionOwnerAttemptId", + attempt.toString(), + "gameSessionOwnerFence", + "47", + "originalLeaseExpiresAt", + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'") + .withZone(ZoneOffset.UTC) + .format(expiry.toInstant()), + "accountWorldParticipationId", + world.toString(), + "accountWorldParticipationFence", + "1", + "worldAdmissionHoldIdentityBytesBase64", + base64(hold))); + Fixture fixture = + new Fixture( + dsl, + transaction, + source, + UUID.randomUUID(), + requestId, + tenant, + instance, + mutation, + attempt, + world, + expiry, + evidence, + tuple, + projection, + hold, + request); + byte[] snapshot = + json( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + requestId, + "sourceVector", + List.of(base64(evidence.canonicalBytes())))); + transaction.executeWithoutResult( + status -> { + dsl.execute("SET LOCAL session_replication_role = replica"); + insert( + dsl, + "account_canonical_tenant_identity_claims", + "canonical_tenant_id", + tenant, + "identity_kind", + "APPROVED_RETAINED", + "source_operation_id", + UUID.randomUUID(), + "source_account_legacy_tenant_id", + 1L, + "source_target_namespace", + "test", + "source_game_row_id", + 1L, + "source_game_tenant_key", + tenant.toString()); + insert(dsl, "account_draft_authorization_source_locks", "source_key", evidence.key()); + insert( + dsl, + "account_start_session_authority_captures", + "control_plane_request_id", + requestId, + "account_uuid", + actor, + "tenant_uuid", + tenant, + "target_owner", + "game-session-service", + "logging_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "pre_authorization_tuple", + bytes("{}"), + "mutation_digest", + "c".repeat(64), + "control_ui_operation_id", + UUID.randomUUID(), + "control_ui_token_jti", + UUID.randomUUID(), + "control_ui_token_hash", + "d".repeat(64), + "control_ui_signer_receipt_sha256", + "e".repeat(64), + "issuance_fence", + 9L, + "issuance_fence_source_version", + 1L, + "captured_at", + now, + "snapshot_sha256", + hash(snapshot), + "canonical_snapshot_bytes", + snapshot, + "source_version", + 11L, + "source_fence", + 13L, + "linearization", + "17", + "canonical_sha256", + hash(bytes("{}")), + "canonical_capture_bytes", + bytes("{}")); + insert( + dsl, + "account_start_session_operator_authorizations", + "control_plane_request_id", + requestId, + "pre_authorization_tuple", + bytes("{}"), + "mutation_digest", + "c".repeat(64), + "issuance_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "issuance_operation_id", + issuance, + "issuance_fence", + 9L, + "bundle_version", + "authorityEvidenceBundle/v1", + "bundle_source_version", + "11", + "bundle_source_fence", + "13", + "bundle_linearization", + "17", + "authority_evidence_bundle", + bytes("{}"), + "authorization_reference_fingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "encrypted_response_envelope", + bytes("synthetic"), + "issued_at", + now.minusSeconds(10), + "reference_expires_at", + now.plusSeconds(90), + "response_envelope_expires_at", + now.plusSeconds(120), + "status", + "REDEEMED", + "redemption_redeemer_workload_uri", + "spiffe://firemud/ns/test/sa/game-session-service", + "redemption_owner_attempt_id", + attempt, + "redemption_owner_fence", + 47L, + "redeemed_at", + now.minusSeconds(5), + "redemption_reference_fingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "redemption_authority_evidence_bundle", + bytes("{}")); + insert( + dsl, + "account_start_session_world_participations", + "participation_id", + world, + "control_plane_request_id", + requestId, + "original_post_authorization_tuple", + tuple, + "target_namespace", + "test", + "canonical_tenant_id", + tenant, + "canonical_game_instance_id", + instance, + "game_session_owner_attempt_id", + attempt, + "game_session_owner_fence", + 47L, + "preparation_input_json", + "{}", + "preparation_input_digest", + "sha256:" + hash(bytes("{}"))); + insert( + dsl, + "account_start_session_world_participation_sources", + "participation_id", + world, + "source_key", + evidence.key(), + "source_evidence", + evidence.canonicalBytes()); + insert( + dsl, + "account_start_session_world_original_attempt_evidence", + "participation_id", + world, + "target_namespace", + "test", + "game_session_owner_mutation_id", + mutation, + "game_session_owner_attempt_id", + attempt, + "game_session_owner_fence", + 47L, + "original_lease_expires_at", + expiry, + "original_response_bytes", + bytes("synthetic-observation"), + "original_response_digest", + "sha256:" + hash(bytes("synthetic-observation"))); + insert( + dsl, + "account_start_session_world_participation_settlements", + "participation_id", + world, + "outcome", + "COMMITTED", + "world_execution_fence", + 1L, + "terminal_bytes", + bytes("synthetic-terminal"), + "terminal_digest", + "sha256:" + hash(bytes("synthetic-terminal"))); + dsl.execute("SET LOCAL session_replication_role = origin"); + }); + return fixture; + } + + private static void insert(DSLContext dsl, String table, Object... fields) { + Map, Object> values = new LinkedHashMap<>(); + for (int index = 0; index < fields.length; index += 2) + values.put(DSL.field(DSL.name((String) fields[index])), fields[index + 1]); + dsl.insertInto(DSL.table(DSL.name(table))).set(values).execute(); + } + + private static Long sequenceValue(Fixture fixture) { + return fixture + .dsl() + .fetchSingle( + "SELECT last_value FROM account_start_session_admission_protections_protection_fence_seq") + .get(0, Long.class); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static byte[] json(Map value) { + return AccountControlUiAuthority.canonical(value); + } + + private static String base64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static String hash(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transaction, + DriverManagerDataSource dataSource, + UUID protectionId, + String requestId, + UUID tenantId, + UUID instanceId, + UUID mutationId, + UUID attemptId, + UUID worldId, + OffsetDateTime expiry, + SourceEvidence source, + byte[] tuple, + byte[] projection, + byte[] hold, + byte[] request) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java new file mode 100644 index 0000000000..1065482932 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +/** Mocked database interactions verify comparison and guard ordering, not PostgreSQL execution. */ +class AccountStartSessionAdmissionProtectionRepositoryTest { + private static final UUID PROTECTION_ID = UUID.fromString("f0467d79-a879-4f4f-99f0-b2369d49bd9b"); + private static final long PROTECTION_FENCE = 71L; + private static final byte[] REQUEST_BYTES = new byte[] {1, 2, 3}; + private static final UUID ACCOUNT_ID = UUID.fromString("8d5cb900-7900-4200-88ae-113ca0f7028f"); + + @Test + void sourceChildrenMustMatchTheFullCanonicalEvidenceBytes() { + SourceEvidence expected = source("2", "17", "current source bytes"); + SourceEvidence changedMetadata = source("3", "17", "current source bytes"); + SourceEvidence changedBytes = source("2", "17", "substituted source bytes"); + + AccountStartSessionAdmissionProtectionRepository.requireExactSources( + List.of(expected), List.of(expected)); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionRepository.requireExactSources( + List.of(expected), List.of(changedMetadata))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionRepository.requireExactSources( + List.of(expected), List.of(changedBytes))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + + @Test + void databaseCurrentnessExpiryAfterLockWaitAbortsBeforeSourceReadback() { + DSLContext dsl = mock(DSLContext.class); + when(dsl.fetchOne(contains("account_ss_admission_read_current_exact"), any(Object[].class))) + .thenThrow(new DataAccessException("original lease elapsed after row-lock wait") {}); + + AccountStartSessionAdmissionProtectionRepository repository = + new AccountStartSessionAdmissionProtectionRepository(dsl); + + assertThatThrownBy( + () -> repository.assertCurrent(PROTECTION_ID, PROTECTION_FENCE, REQUEST_BYTES)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("elapsed after row-lock wait"); + + ArgumentCaptor arguments = ArgumentCaptor.forClass(Object[].class); + verify(dsl, times(1)) + .fetchOne(contains("account_ss_admission_read_current_exact"), arguments.capture()); + assertThat(arguments.getValue()) + .containsExactly(PROTECTION_ID, PROTECTION_FENCE, REQUEST_BYTES); + assertThat(arguments.getValue()[2]).isSameAs(REQUEST_BYTES); + } + + private static SourceEvidence source(String generation, String sourceVersion, String bytes) { + return new SourceEvidence( + SourceKind.ACCOUNT, + ACCOUNT_ID.toString(), + generation, + sourceVersion, + "account/admission-protection", + "17", + bytes.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionServiceTest.java new file mode 100644 index 0000000000..b1a47e58fb --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionServiceTest.java @@ -0,0 +1,789 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +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.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Synthetic composition proof; Game Session and Account storage remain explicit mocks. */ +class AccountStartSessionAdmissionProtectionAcquisitionServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID ACCOUNT_ID = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TENANT_ID = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_MUTATION_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("4a3fc69f-a18a-4b94-b1d1-2e8b4c3f0e4b"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final UUID PROTECTION_ID = uuid("9e180ae4-ea1b-42cf-8e61-a49a112a95d5"); + private static final UUID DIFFERENT_PROTECTION_ID = uuid("b833e0a3-e6e9-43ed-846a-a0a2c39052a3"); + private static final long PARTICIPATION_FENCE = 31L; + private static final long GAME_SESSION_FENCE = 37L; + private static final long PROTECTION_FENCE = 43L; + private static final String PREPARATION_INPUT = "{\"selected\":\"immutable source\"}"; + private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-12T00:00:00Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactGameSessionPeerAndRejectsEndUserOrAmbientSqlBeforeInputProcessing() { + Harness harness = new Harness(); + + assertCode(Status.Code.UNAUTHENTICATED, () -> harness.service.acquire(null)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer(NAMESPACE, "world-management-service", () -> harness.service.acquire(null))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("other-runtime", "game-session-service", () -> harness.service.acquire(null))); + SessionContext.setContext("123", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer(NAMESPACE, "game-session-service", () -> harness.service.acquire(null))); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> peer(NAMESPACE, "game-session-service", () -> harness.service.acquire(null))); + + verifyNoInteractions(harness.issuer); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptEvidenceRepository); + verifyNoInteractions(harness.protectionRepository); + verifyNoInteractions(harness.gameSessionClient); + assertThat(harness.readbackTransactions.begins).isZero(); + } + + @Test + void changedCompleteAccountProjectionDeniesBeforeCurrentnessOrProtectionWrite() { + Harness harness = new Harness(); + harness.configureClientResult("substituted projection".getBytes(StandardCharsets.UTF_8)); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(harness.request))); + + assertThat(harness.steps).containsExactly("remote-read"); + verifyNoInteractions(harness.issuer); + verifyNoInteractions(harness.protectionRepository); + assertThat(harness.readbackTransactions.begins).isZero(); + } + + @Test + void comparesFreshObservationWithHistoricalWorldEvidenceInsideCurrentnessCallback() { + Harness harness = new Harness(); + harness.configureSuccess(); + AccountStartSessionAdmissionProtectionEvidence acquired = + authorized(() -> harness.service.acquire(harness.request)); + + assertThat(acquired.accountProtectionId()).isEqualTo(PROTECTION_ID); + assertThat(acquired.accountProtectionFence()).isEqualTo(PROTECTION_FENCE); + assertThat(acquired.request().accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(acquired.request().gameSessionOwnerMutationId()).isEqualTo(GAME_SESSION_MUTATION_ID); + assertThat(harness.steps) + .containsExactly( + "remote-read", + "issuer-currentness", + "world-history", + "attempt-history", + "protection-write-or-exact-read", + "protection-readback"); + assertThat(harness.readbackTransactions.begins).isEqualTo(1); + assertThat(harness.readbackTransactions.commits).isEqualTo(1); + verify(harness.issuer) + .withCurrentGameSessionAdmissionProtectionCurrentness( + eq(harness.tuple.canonicalBytes()), + eq(GAME_SESSION_ATTEMPT_ID), + eq(GAME_SESSION_FENCE), + any()); + verify(harness.participationRepository) + .findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE); + verify(harness.attemptEvidenceRepository) + .findHistoricalExact(any(StoredParticipation.class), any(Request.class)); + verify(harness.participationRepository, times(0)).findCurrentExact(any()); + } + + @Test + void changedOriginalLeaseExpiryDeniesBeforeCreatingProtection() { + Harness harness = new Harness(); + harness.configureSuccess(); + harness.configureClientResult(projection(harness.tuple), ORIGINAL_LEASE_EXPIRY.plusMillis(1)); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(harness.request))); + + assertThat(harness.steps) + .containsExactly("remote-read", "issuer-currentness", "world-history", "attempt-history"); + verifyNoInteractions(harness.protectionRepository); + assertThat(harness.readbackTransactions.begins).isZero(); + } + + @Test + void missingIndependentReadbackDeniesWithoutRetryingTheCreatePath() { + Harness harness = new Harness(); + harness.configureSuccess(); + harness.protectionMissingOnReadback = true; + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(harness.request))); + + assertThat(harness.steps) + .containsExactly( + "remote-read", + "issuer-currentness", + "world-history", + "attempt-history", + "protection-write-or-exact-read", + "protection-readback"); + verify(harness.protectionRepository, times(1)).createOrReadExact(any(), any()); + verify(harness.protectionRepository, times(1)).findCurrentExact(any()); + assertThat(harness.readbackTransactions.begins).isEqualTo(1); + } + + @Test + void lostReadbackAckRetryRechecksCurrentnessAndReturnsTheOriginalIdentityAndExpiry() { + Harness harness = new Harness(); + harness.configureSuccess(); + harness.missingReadbacksRemaining = 1; + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(harness.request))); + AccountStartSessionAdmissionProtectionEvidence committedButUnacknowledged = + harness.retainedProtection.get(); + assertThat(committedButUnacknowledged).isNotNull(); + assertThat(harness.readbackTransactions.begins).isEqualTo(1); + assertThat(harness.readbackTransactions.commits).isZero(); + assertThat(harness.readbackTransactions.rollbacks).isEqualTo(1); + + AccountStartSessionAdmissionProtectionEvidence retry = + authorized(() -> harness.service.acquire(harness.request)); + + assertThat(retry.canonicalBytes()).containsExactly(committedButUnacknowledged.canonicalBytes()); + assertThat(retry.accountProtectionId()).isEqualTo(PROTECTION_ID); + assertThat(retry.request().originalLeaseExpiresAt()).isEqualTo(ORIGINAL_LEASE_EXPIRY); + ArgumentCaptor currentReads = ArgumentCaptor.forClass(Request.class); + verify(harness.gameSessionClient, times(2)).read(currentReads.capture()); + assertThat(currentReads.getAllValues().get(0).readRequestId()) + .isNotEqualTo(currentReads.getAllValues().get(1).readRequestId()); + ArgumentCaptor protectionRequests = + ArgumentCaptor.forClass(AccountStartSessionAdmissionProtectionRequest.class); + verify(harness.protectionRepository, times(2)) + .createOrReadExact( + protectionRequests.capture(), any(AccountStartSessionAuthorityCapture.class)); + assertThat(protectionRequests.getAllValues().get(0).canonicalBytes()) + .containsExactly(protectionRequests.getAllValues().get(1).canonicalBytes()); + assertThat(protectionRequests.getAllValues()) + .allSatisfy( + value -> assertThat(value.originalLeaseExpiresAt()).isEqualTo(ORIGINAL_LEASE_EXPIRY)); + assertThat(harness.steps) + .containsExactly( + "remote-read", + "issuer-currentness", + "world-history", + "attempt-history", + "protection-write-or-exact-read", + "protection-readback", + "remote-read", + "issuer-currentness", + "world-history", + "attempt-history", + "protection-write-or-exact-read", + "protection-readback"); + assertThat(harness.readbackTransactions.begins).isEqualTo(2); + assertThat(harness.readbackTransactions.commits).isEqualTo(1); + assertThat(harness.readbackTransactions.rollbacks).isEqualTo(1); + } + + @Test + void changedCompleteReadbackIsRejectedWithoutRepeatingTheCreatePath() { + Harness harness = new Harness(); + harness.configureSuccess(); + harness.changedReadbackIdentity = true; + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(harness.request))); + + assertThat(harness.steps) + .containsExactly( + "remote-read", + "issuer-currentness", + "world-history", + "attempt-history", + "protection-write-or-exact-read", + "protection-readback"); + verify(harness.protectionRepository, times(1)).createOrReadExact(any(), any()); + verify(harness.protectionRepository, times(1)).findCurrentExact(any()); + assertThat(harness.readbackTransactions.begins).isEqualTo(1); + assertThat(harness.readbackTransactions.commits).isEqualTo(1); + assertThat(harness.readbackTransactions.rollbacks).isZero(); + } + + @Test + void exactRetryGetsFreshCurrentnessBeforeLookupAndKeepsTheOriginalProtectionIdentity() { + Harness harness = new Harness(); + harness.configureSuccess(); + + AccountStartSessionAdmissionProtectionEvidence first = + authorized(() -> harness.service.acquire(harness.request)); + AccountStartSessionAdmissionProtectionEvidence retry = + authorized(() -> harness.service.acquire(harness.request)); + + ArgumentCaptor reads = ArgumentCaptor.forClass(Request.class); + verify(harness.gameSessionClient, times(2)).read(reads.capture()); + assertThat(reads.getAllValues()).hasSize(2); + assertThat(reads.getAllValues().get(0).readRequestId()) + .isNotEqualTo(reads.getAllValues().get(1).readRequestId()); + assertThat(first.accountProtectionId()).isEqualTo(retry.accountProtectionId()); + assertThat(first.accountProtectionFence()).isEqualTo(retry.accountProtectionFence()); + assertThat(first.canonicalBytes()).containsExactly(retry.canonicalBytes()); + assertThat(harness.steps) + .containsExactly( + "remote-read", + "issuer-currentness", + "world-history", + "attempt-history", + "protection-write-or-exact-read", + "protection-readback", + "remote-read", + "issuer-currentness", + "world-history", + "attempt-history", + "protection-write-or-exact-read", + "protection-readback"); + verify(harness.protectionRepository, times(2)).createOrReadExact(any(), any()); + verify(harness.protectionRepository, times(2)).findCurrentExact(any()); + assertThat(harness.readbackTransactions.begins).isEqualTo(2); + assertThat(harness.readbackTransactions.commits).isEqualTo(2); + } + + private static byte[] projection(StartSessionPostAuthorizationExecutionTuple tuple) { + return net.firedevops.firemud.common.account.startsession + .StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + UUID targetOwnerId = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwnerId = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + String requestId = "admission-protection-original-request"; + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + ACCOUNT_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(91L, targetOwnerId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic Account admission-protection proof")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + reservationOwnerId, + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String actorId = tuple.actor().accountId().toString(); + String tenantId = tuple.action().scope().tenantId().toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-10T00:00:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map human = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", actorId, + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + human); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity() { + WorldCanonicalInitialAdmissionHold.Request request = + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT_ID, + "admission-world", + uuid("5d9e714d-f9be-4e7c-8e32-2f740e4caf95"), + uuid("64366775-dfea-4710-a168-1fd618bb0be8"), + "SHARED", + GAME_INSTANCE_ID, + uuid("ea2bb613-dbc7-4a7f-9e27-202b4189a104"), + 1L, + "distinct-world-admission-request-id", + "b".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + return new WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, + uuid("6af87b1d-d2c4-4a8e-ae39-bf815d4e257a"), + uuid("72d2d148-0831-4ca3-85b0-6db4ed8a5673")); + } + + private static AccountStartSessionAuthorityCapture capture( + StartSessionPostAuthorizationExecutionTuple tuple) { + SourceEvidence source = sourceEvidence("current source"); + var bundle = StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + byte[] signerReceipt = "synthetic-signer-receipt".getBytes(StandardCharsets.UTF_8); + Map snapshot = + Map.ofEntries( + Map.entry("schema", "account-start-session-authority-snapshot/v1"), + Map.entry("controlPlaneRequestId", tuple.controlPlaneRequestId()), + Map.entry( + "preAuthorizationTuple", + Base64.getEncoder() + .encodeToString( + tuple + .preAuthorizationTuple() + .canonicalJson() + .getBytes(StandardCharsets.UTF_8))), + Map.entry("mutationDigest", tuple.mutationDigest()), + Map.entry("accountId", tuple.preAuthorizationTuple().actor().accountId().toString()), + Map.entry( + "tenantId", tuple.preAuthorizationTuple().action().scope().tenantId().toString()), + Map.entry("targetOwner", tuple.preAuthorizationTuple().targetOwner()), + Map.entry("loggingWorkloadUri", tuple.authenticatedWorkloadIdentity()), + Map.entry("reservationOwnerId", tuple.reservationOwnerId().toString()), + Map.entry("reservationClaimFence", Long.toString(tuple.reservationClaimFence())), + Map.entry("controlUiOperationId", bundle.issuanceOperationId().toString()), + Map.entry("controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc"), + Map.entry("controlUiTokenHash", "sha256:" + "d".repeat(64)), + Map.entry("controlUiSignerReceipt", Base64.getEncoder().encodeToString(signerReceipt)), + Map.entry("controlUiSignerReceiptSha256", sha256(signerReceipt)), + Map.entry( + "sourceVectorEvidence", + Base64.getEncoder().encodeToString(source.canonicalBytes())), + Map.entry( + "sourceVector", + List.of(Base64.getEncoder().encodeToString(source.canonicalBytes()))), + Map.entry("outboxCheckpoints", Map.of()), + Map.entry("authorityTuple", bundle.authorityTuple()), + Map.entry("membershipVersion", bundle.membershipVersion()), + Map.entry("accountIdentitySource", "ACCOUNT_UUID"), + Map.entry("issuanceFence", tuple.issuanceFence()), + Map.entry("issuanceFenceSourceVersion", "17")); + try { + return AccountStartSessionAuthorityCapture.create( + tuple.controlPlaneRequestId(), + Long.parseLong(tuple.bundleReference().sourceVersion()), + Long.parseLong(tuple.bundleReference().sourceFence()), + tuple.bundleReference().linearization(), + "2026-10-09T00:00:00.000Z", + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot))); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static SourceEvidence sourceEvidence(String detail) { + return new SourceEvidence( + SourceKind.ACCOUNT, + ACCOUNT_ID.toString(), + "2", + "17", + null, + null, + detail.getBytes(StandardCharsets.UTF_8)); + } + + private static StoredParticipation participation( + StartSessionPostAuthorizationExecutionTuple tuple) { + return new StoredParticipation( + PARTICIPATION_ID, + PARTICIPATION_FENCE, + tuple.controlPlaneRequestId(), + tuple.canonicalBytes(), + NAMESPACE, + TENANT_ID, + GAME_INSTANCE_ID, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + PREPARATION_INPUT, + digest(PREPARATION_INPUT), + 987L, + OffsetDateTime.parse("2026-10-09T00:00:00Z"), + List.of(sourceEvidence("current source"))); + } + + private static StoredEvidence previousObservation( + StoredParticipation participation, + StartSessionPostAuthorizationExecutionTuple tuple, + Instant expiry) { + Request originalRead = + new Request( + uuid("dfdaaf5d-4af0-4a25-9015-b55a328e4d70"), + NAMESPACE, + tuple.canonicalBytes(), + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_MUTATION_ID, + GAME_SESSION_FENCE); + Result result = new Result(originalRead, expiry, projection(tuple)); + byte[] response = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result).toByteArray(); + return new StoredEvidence( + participation.participationId(), + GAME_SESSION_MUTATION_ID, + expiry, + response, + "sha256:" + sha256(response), + result); + } + + private static String digest(String value) { + return "sha256:" + sha256(value.getBytes(StandardCharsets.UTF_8)); + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static T authorized(java.util.function.Supplier action) { + return peer(NAMESPACE, "game-session-service", action); + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static void assertWritableReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static final class Harness { + final AccountStartSessionOperatorAuthorizationService issuer = + mock(AccountStartSessionOperatorAuthorizationService.class); + final AccountStartSessionWorldParticipationRepository participationRepository = + mock(AccountStartSessionWorldParticipationRepository.class); + final AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptEvidenceRepository = + mock(AccountStartSessionWorldOriginalAttemptEvidenceRepository.class); + final AccountStartSessionAdmissionProtectionRepository protectionRepository = + mock(AccountStartSessionAdmissionProtectionRepository.class); + final OriginalStartSessionCurrentAttemptClient gameSessionClient = + mock(OriginalStartSessionCurrentAttemptClient.class); + final OwnerTransactions readbackTransactions = new OwnerTransactions(); + final StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(); + final WorldCanonicalInitialAdmissionHold.HoldIdentity hold = holdIdentity(); + final StoredParticipation worldParticipation = participation(tuple); + final StoredEvidence previousEvidence = + previousObservation(worldParticipation, tuple, ORIGINAL_LEASE_EXPIRY); + final AtomicReference retainedProtection = + new AtomicReference<>(); + final List steps = new ArrayList<>(); + final AccountStartSessionAdmissionProtectionAcquisitionService.AcquisitionRequest request = + new AccountStartSessionAdmissionProtectionAcquisitionService.AcquisitionRequest( + tuple.canonicalBytes(), + GAME_SESSION_MUTATION_ID, + GAME_SESSION_ATTEMPT_ID, + GAME_SESSION_FENCE, + PARTICIPATION_ID, + PARTICIPATION_FENCE, + hold); + final AccountStartSessionAdmissionProtectionAcquisitionService service = + new AccountStartSessionAdmissionProtectionAcquisitionService( + issuer, + participationRepository, + attemptEvidenceRepository, + protectionRepository, + gameSessionClient, + readbackTransactions, + NAMESPACE); + boolean protectionMissingOnReadback; + int missingReadbacksRemaining; + boolean changedReadbackIdentity; + + void configureSuccess() { + configureClientResult(projection(tuple), ORIGINAL_LEASE_EXPIRY); + doAnswer( + invocation -> { + assertNoSql(); + steps.add("issuer-currentness"); + @SuppressWarnings("unchecked") + Function callback = + invocation.getArgument(3); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.initSynchronization(); + try { + return callback.apply(capture(tuple)); + } finally { + TransactionSynchronizationManager.clear(); + } + }) + .when(issuer) + .withCurrentGameSessionAdmissionProtectionCurrentness( + any(byte[].class), eq(GAME_SESSION_ATTEMPT_ID), eq(GAME_SESSION_FENCE), any()); + when(participationRepository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenAnswer( + ignored -> { + assertWritableReadCommittedTransaction(); + steps.add("world-history"); + return Optional.of(worldParticipation); + }); + when(attemptEvidenceRepository.findHistoricalExact( + any(StoredParticipation.class), any(Request.class))) + .thenAnswer( + ignored -> { + assertWritableReadCommittedTransaction(); + steps.add("attempt-history"); + return Optional.of(previousEvidence); + }); + when(protectionRepository.createOrReadExact(any(), any())) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("protection-write-or-exact-read"); + if (retainedProtection.get() == null) { + var exactRequest = + invocation + . + getArgument(0); + AccountStartSessionAuthorityCapture exactCapture = invocation.getArgument(1); + retainedProtection.set( + AccountStartSessionAdmissionProtectionEvidence.create( + exactRequest, + PROTECTION_ID, + PROTECTION_FENCE, + exactCapture.canonicalBytes(), + exactCapture.canonicalSha256(), + List.of(sourceEvidence("current source")))); + } + return retainedProtection.get(); + }); + when(protectionRepository.findCurrentExact(any())) + .thenAnswer( + ignored -> { + assertWritableReadCommittedTransaction(); + steps.add("protection-readback"); + if (protectionMissingOnReadback || missingReadbacksRemaining > 0) { + if (missingReadbacksRemaining > 0) missingReadbacksRemaining--; + return Optional.empty(); + } + AccountStartSessionAdmissionProtectionEvidence stored = retainedProtection.get(); + if (stored == null) return Optional.empty(); + return Optional.of( + changedReadbackIdentity + ? AccountStartSessionAdmissionProtectionEvidence.create( + stored.request(), + DIFFERENT_PROTECTION_ID, + PROTECTION_FENCE + 1, + stored.originalSourceCaptureReferenceBytes(), + stored.originalSourceCaptureReferenceSha256(), + stored.sourceEvidenceVector()) + : stored); + }); + } + + void configureClientResult(byte[] projectionBytes) { + configureClientResult(projectionBytes, ORIGINAL_LEASE_EXPIRY); + } + + void configureClientResult(byte[] projectionBytes, Instant expiry) { + when(gameSessionClient.read(any(Request.class))) + .thenAnswer( + invocation -> { + assertNoSql(); + steps.add("remote-read"); + Request read = invocation.getArgument(0); + return new Result(read, expiry, projectionBytes); + }); + } + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + int rollbacks; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertNoSql(); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + rollbacks++; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java index 9dfbf55165..7e25966596 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java @@ -139,6 +139,8 @@ class AccountStartSessionAuthorityCaptureRepositoryTest { "spiffe://firemud/ns/gameplay/sa/logging-admin-service"; private static final String WORLD_PEER_URI = "spiffe://firemud/ns/gameplay/sa/world-management-service"; + private static final String GAME_SESSION_PEER_URI = + "spiffe://firemud/ns/gameplay/sa/game-session-service"; @AfterEach void clearContext() { @@ -166,6 +168,95 @@ void rejectsWrongMissingAndMalformedSnapshotUuidEvidence() { assertUnavailable(missingStoredUuid.row()); } + @Test + void gameSessionAdmissionLookupReadsOriginalCaptureWithoutAllocation() { + WorldLookupFixture fixture = worldLookupFixture(true); + beginOwnerTransaction(); + var observed = + withPeer(GAME_SESSION_PEER_URI, NAMESPACE, "game-session-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromGameSessionAdmission( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + GAME_SESSION_PEER_URI)); + assertThat(observed.sameStoredValue(fixture.capture())).isTrue(); + verify(fixture.dsl(), times(1)) + .fetchOne(startsWith("SELECT control_plane_request_id"), any(Object[].class)); + verifyNoMoreInteractions(fixture.dsl()); + } + + @Test + void gameSessionAdmissionLookupRejectsWrongPeerNamespaceAndEndUserBeforeStorage() { + WorldLookupFixture fixture = worldLookupFixture(true); + beginOwnerTransaction(); + for (String peer : + List.of( + WORLD_PEER_URI, + LOGGING_PEER_URI, + "spiffe://firemud/ns/other/sa/game-session-service")) { + var identity = GrpcPeerIdentity.parseUri(peer).orElseThrow(); + assertUnavailable( + () -> + withPeer(peer, identity.namespace(), identity.service()) + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromGameSessionAdmission( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + GAME_SESSION_PEER_URI))); + } + SessionContext.setContext("account-user", List.of("tenantAdmin"), Map.of()); + assertUnavailable( + () -> + withPeer(GAME_SESSION_PEER_URI, NAMESPACE, "game-session-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromGameSessionAdmission( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + GAME_SESSION_PEER_URI))); + verifyNoInteractions(fixture.dsl()); + } + + @Test + void gameSessionAdmissionLookupDoesNotAllocateMissingCapture() { + WorldLookupFixture fixture = worldLookupFixture(false); + beginOwnerTransaction(); + assertUnavailable( + () -> + withPeer(GAME_SESSION_PEER_URI, NAMESPACE, "game-session-service") + .call( + () -> + fixture + .repository() + .lockReadExactCurrentFromGameSessionAdmission( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + GAME_SESSION_PEER_URI))); + verify(fixture.dsl(), times(1)) + .fetchOne(startsWith("SELECT control_plane_request_id"), any(Object[].class)); + verifyNoMoreInteractions(fixture.dsl()); + } + @Test void worldReceivingLookupAcceptsWorldPeerAndRetainedLoggingIssuer() { WorldLookupFixture fixture = worldLookupFixture(true); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java index d0fdb75bc7..5930ef7e95 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java @@ -47,6 +47,7 @@ import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; import org.jooq.Record; @@ -71,6 +72,7 @@ class AccountStartSessionOperatorAuthorizationServiceTest { @AfterEach void clearTransactionState() { + SessionContext.clear(); TransactionSynchronizationManager.clear(); } @@ -877,6 +879,200 @@ void projectionRejectsRevokedOrChangedCurrentAccountSource() { harness.captureRepository()); } + @Test + void gameSessionAdmissionCurrentnessAuthenticatesBeforeDecodingOrOwnerAccess() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + byte[] malformed = "malformed".getBytes(StandardCharsets.UTF_8); + for (String peer : + List.of( + WORLD_MANAGEMENT_PEER, + LOGGING_PEER, + "spiffe://firemud/ns/other/sa/game-session-service")) { + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(peer).orElseThrow()) + .run( + () -> + assertThatThrownBy( + () -> + harness + .service() + .withCurrentGameSessionAdmissionProtectionCurrentness( + malformed, + harness.request().ownerAttemptId(), + harness.request().ownerFence(), + ignored -> "unexpected")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact authenticated internal workload identity")); + } + SessionContext.setContext("account-user", List.of("tenantAdmin"), Map.of()); + gameSessionContext() + .run( + () -> + assertThatThrownBy( + () -> + harness + .service() + .withCurrentGameSessionAdmissionProtectionCurrentness( + malformed, + harness.request().ownerAttemptId(), + harness.request().ownerFence(), + ignored -> "unexpected")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("end-user")); + verifyNoInteractions( + harness.repository(), harness.actors(), harness.hostedTerms(), harness.captureRepository()); + } + + @Test + void gameSessionAdmissionCurrentnessRejectsAmbientSqlBeforeDecoding() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + for (boolean transaction : List.of(true, false)) { + if (transaction) TransactionSynchronizationManager.setActualTransactionActive(true); + else TransactionSynchronizationManager.initSynchronization(); + try { + gameSessionContext() + .run( + () -> + assertThatThrownBy( + () -> + harness + .service() + .withCurrentGameSessionAdmissionProtectionCurrentness( + new byte[] {1}, + harness.request().ownerAttemptId(), + harness.request().ownerFence(), + ignored -> "unexpected")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient Account transaction")); + } finally { + TransactionSynchronizationManager.clear(); + } + } + verifyNoInteractions( + harness.repository(), harness.actors(), harness.hostedTerms(), harness.captureRepository()); + } + + @Test + void gameSessionAdmissionCurrentnessRejectsTupleNamespaceBeforeLookup() { + ReadHarness harness = + readHarness( + NOW.plusSeconds(30), LOGGING_PEER, "spiffe://firemud/ns/other/sa/game-session-service"); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/other/sa/game-session-service") + .orElseThrow()) + .run( + () -> + assertThatThrownBy( + () -> + harness + .service() + .withCurrentGameSessionAdmissionProtectionCurrentness( + postTuple(harness).canonicalBytes(), + harness.request().ownerAttemptId(), + harness.request().ownerFence(), + ignored -> "unexpected")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("target namespace")); + verifyNoInteractions( + harness.repository(), harness.actors(), harness.hostedTerms(), harness.captureRepository()); + } + + @Test + void gameSessionAdmissionCurrentnessLocksOriginalCaptureWithoutIssuanceOrWorldGuard() + throws Exception { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + allowCurrent(harness, harness.source()); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return harness.capture(); + }) + .when(harness.captureRepository()) + .lockReadExactCurrentFromGameSessionAdmission( + any(), + eq(harness.tuple()), + eq(LOGGING_PEER), + eq(harness.record().reservationOwnerId()), + eq(harness.record().reservationClaimFence()), + eq(GAME_SESSION_PEER)); + var result = + gameSessionContext() + .call( + () -> + harness + .service() + .withCurrentGameSessionAdmissionProtectionCurrentness( + postTuple(harness).canonicalBytes(), + harness.request().ownerAttemptId(), + harness.request().ownerFence(), + capture -> { + assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + return capture; + })); + assertThat(result).isEqualTo(harness.capture()); + verify(harness.captureRepository(), never()) + .lockReadExactCurrentFromWorldReceiving( + any(), any(), anyString(), any(), anyLong(), anyString()); + verify(harness.captureRepository(), never()) + .prepareOrReadExact(any(), any(), anyString(), any(), anyLong()); + verify(harness.repository(), never()).createOrReadExact(any()); + verify(harness.repository(), never()).redeemExact(any()); + verifyNoInteractions(harness.claims(), harness.fingerprintKeys(), harness.responseCrypto()); + } + + @Test + void gameSessionAdmissionCurrentnessRejectsExpiredReferenceAndChangedCurrentSource() { + ReadHarness expired = readHarness(NOW.minusSeconds(10)); + gameSessionContext() + .run( + () -> + assertThatThrownBy( + () -> + expired + .service() + .withCurrentGameSessionAdmissionProtectionCurrentness( + postTuple(expired).canonicalBytes(), + expired.request().ownerAttemptId(), + expired.request().ownerFence(), + ignored -> { + throw new AssertionError("callback ran"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); + verifyNoInteractions(expired.actors(), expired.captureRepository()); + + ReadHarness changed = readHarness(NOW.plusSeconds(30)); + allowCurrent(changed, source(changed.actorId(), changed.tenantId(), 8L, new byte[] {2})); + when(changed + .captureRepository() + .lockReadExactCurrentFromGameSessionAdmission( + any(), any(), anyString(), any(), anyLong(), anyString())) + .thenReturn(changed.capture()); + gameSessionContext() + .run( + () -> + assertThatThrownBy( + () -> + changed + .service() + .withCurrentGameSessionAdmissionProtectionCurrentness( + postTuple(changed).canonicalBytes(), + changed.request().ownerAttemptId(), + changed.request().ownerFence(), + ignored -> { + throw new AssertionError("callback ran"); + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Current Account source")); + verify(changed.captureRepository()) + .lockReadExactCurrentFromGameSessionAdmission( + any(), eq(changed.tuple()), eq(LOGGING_PEER), any(), anyLong(), eq(GAME_SESSION_PEER)); + } + @Test void worldCurrentnessAuthenticatesExactPeerBeforeParsingAndDoesNotWidenProjectionRead() { ReadHarness harness = readHarness(NOW.plusSeconds(30)); diff --git a/services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql b/services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql index 96049bd8d7..ae05c263aa 100644 --- a/services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql +++ b/services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql @@ -67,7 +67,15 @@ DECLARE flush_lsn pg_lsn; observed_ms BIGINT; observation INTEGER; + diagnostic_entry_insert pg_lsn; + diagnostic_entry_flush pg_lsn; + diagnostic_capture_flush pg_lsn; + diagnostic_pid INTEGER; BEGIN + -- Observations only: even this first statement follows function resolution/planning. + diagnostic_entry_insert := pg_current_wal_insert_lsn(); + diagnostic_entry_flush := pg_current_wal_flush_lsn(); + diagnostic_pid := pg_backend_pid(); IF current_setting('transaction_isolation') <> 'serializable' OR current_setting('transaction_read_only') <> 'off' OR pg_is_in_recovery() OR current_setting('fsync') <> 'on' THEN @@ -78,6 +86,7 @@ BEGIN fixed_snapshot := pg_current_snapshot(); own_xid := pg_current_xact_id_if_assigned()::text; upper_lsn := pg_current_wal_insert_lsn(); + diagnostic_capture_flush := pg_current_wal_flush_lsn(); SELECT * INTO op FROM __S__.account_gameplay_admission_lease_operations WHERE request_id = p_request; IF NOT FOUND OR op.status <> 'COMMITTED' OR op.finalization_xid IS NULL OR op.evidence_sha256 IS DISTINCT FROM p_sha OR op.binding_decision_id IS DISTINCT FROM p_decision THEN @@ -114,8 +123,9 @@ BEGIN EXIT WHEN upper_lsn > '0/0' AND flush_lsn >= upper_lsn; IF observation = 50 THEN RAISE EXCEPTION 'prototype WAL coverage unavailable' USING ERRCODE = '23514', - DETAIL = format('snapshot=%s own_xid=%s original_xid=%s upper_lsn=%s flush_lsn=%s observed_ms=%s expiry=%s', - fixed_snapshot, own_xid, op.finalization_xid, upper_lsn, flush_lsn, observed_ms, op.expires_at_ms); + DETAIL = format('snapshot=%s own_xid=%s original_xid=%s upper_lsn=%s flush_lsn=%s observed_ms=%s expiry=%s diagnostic_pid=%s diagnostic_entry_insert=%s diagnostic_entry_flush=%s diagnostic_capture_flush=%s', + fixed_snapshot, own_xid, op.finalization_xid, upper_lsn, flush_lsn, observed_ms, op.expires_at_ms, + diagnostic_pid, diagnostic_entry_insert, diagnostic_entry_flush, diagnostic_capture_flush); END IF; PERFORM pg_sleep(0.01); END LOOP; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java new file mode 100644 index 0000000000..ac669858e2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java @@ -0,0 +1,446 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Canonical integrity evidence for one Account StartSession admission-protection value. + * + *

This carrier retains the exact request, Account protection identity, capture reference, and + * complete ordered Account source-evidence children. It proves supplied-byte integrity and + * structural binding only; it does not authenticate the Account issuer, establish source + * currentness, prove a live Game Session claim, or itself exclude source writers. + */ +public final class AccountStartSessionAdmissionProtectionEvidence { + public static final String SCHEMA = "account-start-session-admission-protection-evidence/v1"; + public static final String SOURCE_CAPTURE_REFERENCE_SCHEMA = + "account-start-session-authority-capture/v1"; + public static final int MAX_CANONICAL_BYTES = 8 * 1024 * 1024; + public static final int MAX_CAPTURE_REFERENCE_BYTES = 256 * 1024; + public static final int MAX_SOURCE_EVIDENCE_COUNT = 256; + public static final int MAX_SOURCE_EVIDENCE_VECTOR_BYTES = 4 * 1024 * 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POSITIVE_LONG = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern MILLIS_UTC = + Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z"); + private static final DateTimeFormatter MILLIS_FORMAT = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "requestBytesBase64", + "accountProtectionId", + "accountProtectionFence", + "originalSourceCaptureReferenceBytesBase64", + "originalSourceCaptureReferenceSha256", + "sourceEvidenceVector"); + private static final Set CAPTURE_REFERENCE_FIELDS = + Set.of("schema", "controlPlaneRequestId", "capturedAt", "bundleReference", "snapshotSha256"); + private static final Set BUNDLE_REFERENCE_FIELDS = + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountStartSessionAdmissionProtectionRequest request; + private final UUID accountProtectionId; + private final long accountProtectionFence; + private final byte[] originalSourceCaptureReferenceBytes; + private final String originalSourceCaptureReferenceSha256; + private final List sourceEvidenceVector; + private final byte[] canonicalBytes; + + private AccountStartSessionAdmissionProtectionEvidence( + AccountStartSessionAdmissionProtectionRequest request, + UUID accountProtectionId, + long accountProtectionFence, + byte[] originalSourceCaptureReferenceBytes, + String originalSourceCaptureReferenceSha256, + List sourceEvidenceVector, + byte[] canonicalBytes) { + this.request = request; + this.accountProtectionId = accountProtectionId; + this.accountProtectionFence = accountProtectionFence; + this.originalSourceCaptureReferenceBytes = originalSourceCaptureReferenceBytes.clone(); + this.originalSourceCaptureReferenceSha256 = originalSourceCaptureReferenceSha256; + this.sourceEvidenceVector = List.copyOf(sourceEvidenceVector); + this.canonicalBytes = canonicalBytes.clone(); + } + + /** Creates one canonical Account evidence value from exact capture and source bytes. */ + public static AccountStartSessionAdmissionProtectionEvidence create( + AccountStartSessionAdmissionProtectionRequest request, + UUID accountProtectionId, + long accountProtectionFence, + byte[] exactOriginalSourceCaptureReferenceBytes, + String originalSourceCaptureReferenceSha256, + List sourceEvidenceVector) { + Objects.requireNonNull(request, "request is required"); + requireNonNil(accountProtectionId, "accountProtectionId"); + requirePositive(accountProtectionFence, "accountProtectionFence"); + + byte[] captureReferenceBytes = + bounded( + exactOriginalSourceCaptureReferenceBytes, + MAX_CAPTURE_REFERENCE_BYTES, + "original Account source capture reference"); + String captureReferenceDigest = requireDigest(originalSourceCaptureReferenceSha256); + if (!captureReferenceDigest.equals(sha256(captureReferenceBytes))) { + throw invalid("Original Account source capture reference digest differs from its bytes"); + } + requireCaptureReferenceBinding(captureReferenceBytes, request.originalTuple()); + + List sources = canonicalSourceVector(sourceEvidenceVector); + byte[] canonical = + encode( + request.canonicalBytes(), + accountProtectionId, + accountProtectionFence, + captureReferenceBytes, + captureReferenceDigest, + sources); + return new AccountStartSessionAdmissionProtectionEvidence( + request, + accountProtectionId, + accountProtectionFence, + captureReferenceBytes, + captureReferenceDigest, + sources, + canonical); + } + + /** Strictly decodes one whole canonical evidence value; decoding grants no issuer authority. */ + public static AccountStartSessionAdmissionProtectionEvidence decode(byte[] exactCanonicalBytes) { + byte[] stored = + bounded(exactCanonicalBytes, MAX_CANONICAL_BYTES, "admission protection evidence"); + try { + String json = strictUtf8(stored); + requireCanonicalJson(stored, json, "admission protection evidence"); + Map root = JSON.readValue(json, new TypeReference<>() {}); + requireExactFields(root, ROOT_FIELDS, "admission protection evidence"); + if (!SCHEMA.equals(string(root.get("schema"), "schema"))) { + throw invalid("Unsupported Account admission protection evidence schema"); + } + Object rawSources = root.get("sourceEvidenceVector"); + if (!(rawSources instanceof List encodedSources)) { + throw invalid("sourceEvidenceVector must be an array"); + } + if (encodedSources.isEmpty() || encodedSources.size() > MAX_SOURCE_EVIDENCE_COUNT) { + throw invalid("sourceEvidenceVector is empty or exceeds its item limit"); + } + List sources = new ArrayList<>(encodedSources.size()); + for (int index = 0; index < encodedSources.size(); index++) { + String field = "sourceEvidenceVector[" + index + "]"; + byte[] sourceBytes = decodeBase64(encodedSources.get(index), field); + sources.add(SourceEvidence.fromStored(sourceBytes)); + } + AccountStartSessionAdmissionProtectionEvidence result = + create( + AccountStartSessionAdmissionProtectionRequest.decode( + decodeBase64(root.get("requestBytesBase64"), "requestBytesBase64")), + canonicalUuid(root.get("accountProtectionId"), "accountProtectionId"), + positiveLong(root.get("accountProtectionFence"), "accountProtectionFence"), + decodeBase64( + root.get("originalSourceCaptureReferenceBytesBase64"), + "originalSourceCaptureReferenceBytesBase64"), + string( + root.get("originalSourceCaptureReferenceSha256"), + "originalSourceCaptureReferenceSha256"), + sources); + if (!MessageDigest.isEqual(stored, result.canonicalBytes)) { + throw invalid("Account admission protection evidence members are inconsistent"); + } + return result; + } catch (IllegalArgumentException expected) { + throw expected; + } catch (IOException | RuntimeException malformed) { + throw invalid("Account admission protection evidence is malformed"); + } + } + + public AccountStartSessionAdmissionProtectionRequest request() { + return request; + } + + public UUID accountProtectionId() { + return accountProtectionId; + } + + public long accountProtectionFence() { + return accountProtectionFence; + } + + public byte[] originalSourceCaptureReferenceBytes() { + return originalSourceCaptureReferenceBytes.clone(); + } + + public String originalSourceCaptureReferenceSha256() { + return originalSourceCaptureReferenceSha256; + } + + public List sourceEvidenceVector() { + return List.copyOf(sourceEvidenceVector); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + private static byte[] encode( + byte[] requestBytes, + UUID protectionId, + long protectionFence, + byte[] captureReferenceBytes, + String captureReferenceDigest, + List sources) { + Map root = new LinkedHashMap<>(); + root.put("schema", SCHEMA); + root.put("requestBytesBase64", Base64.getEncoder().encodeToString(requestBytes)); + root.put("accountProtectionId", protectionId.toString()); + root.put("accountProtectionFence", Long.toString(protectionFence)); + root.put( + "originalSourceCaptureReferenceBytesBase64", + Base64.getEncoder().encodeToString(captureReferenceBytes)); + root.put("originalSourceCaptureReferenceSha256", captureReferenceDigest); + root.put( + "sourceEvidenceVector", + sources.stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (canonical.length > MAX_CANONICAL_BYTES) { + throw invalid("Account admission protection evidence exceeds its byte limit"); + } + return canonical; + } catch (IOException impossible) { + throw new IllegalStateException( + "Account admission protection evidence cannot be encoded", impossible); + } + } + + private static List canonicalSourceVector( + List sourceEvidenceVector) { + Objects.requireNonNull(sourceEvidenceVector, "sourceEvidenceVector is required"); + if (sourceEvidenceVector.isEmpty() || sourceEvidenceVector.size() > MAX_SOURCE_EVIDENCE_COUNT) { + throw invalid("sourceEvidenceVector is empty or exceeds its item limit"); + } + List sources = + sourceEvidenceVector.stream() + .map( + source -> { + Objects.requireNonNull(source, "sourceEvidenceVector child is required"); + byte[] exactBytes = source.canonicalBytes(); + return SourceEvidence.fromStored(exactBytes); + }) + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + if (sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw invalid("sourceEvidenceVector contains duplicate source keys"); + } + long totalBytes = 0L; + for (SourceEvidence source : sources) { + totalBytes += source.canonicalBytes().length; + if (totalBytes > MAX_SOURCE_EVIDENCE_VECTOR_BYTES) { + throw invalid("sourceEvidenceVector exceeds its byte limit"); + } + } + return List.copyOf(sources); + } + + private static void requireCaptureReferenceBinding( + byte[] exactReferenceBytes, StartSessionPostAuthorizationExecutionTuple tuple) { + try { + String json = strictUtf8(exactReferenceBytes); + requireCanonicalJson(exactReferenceBytes, json, "original Account source capture reference"); + Map root = JSON.readValue(json, new TypeReference<>() {}); + requireExactFields(root, CAPTURE_REFERENCE_FIELDS, "Account source capture reference"); + if (!SOURCE_CAPTURE_REFERENCE_SCHEMA.equals(string(root.get("schema"), "schema"))) { + throw invalid("Unsupported Account source capture reference schema"); + } + if (!tuple + .controlPlaneRequestId() + .equals(string(root.get("controlPlaneRequestId"), "controlPlaneRequestId"))) { + throw invalid("Account source capture reference belongs to another original request"); + } + String capturedAt = string(root.get("capturedAt"), "capturedAt"); + if (!MILLIS_UTC.matcher(capturedAt).matches()) { + throw invalid("Account source capture timestamp must use canonical UTC milliseconds"); + } + Instant parsed = Instant.parse(capturedAt); + if (!MILLIS_FORMAT.format(parsed).equals(capturedAt)) { + throw invalid("Account source capture timestamp must use canonical UTC milliseconds"); + } + if (!SHA256.matcher(string(root.get("snapshotSha256"), "snapshotSha256")).matches()) { + throw invalid("Account source capture snapshot digest is malformed"); + } + Map reference = object(root.get("bundleReference"), "bundleReference"); + requireExactFields(reference, BUNDLE_REFERENCE_FIELDS, "Account bundle reference"); + StartSessionAuthorityEvidenceBundle.BundleReference decodedReference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + string(reference.get("bundleVersion"), "bundleVersion"), + string(reference.get("sourceVersion"), "sourceVersion"), + string(reference.get("sourceFence"), "sourceFence"), + string(reference.get("linearization"), "linearization")); + if (!tuple.bundleReference().equals(decodedReference)) { + throw invalid("Account source capture reference differs from the original tuple bundle"); + } + } catch (IllegalArgumentException expected) { + throw expected; + } catch (IOException | RuntimeException malformed) { + throw invalid("Original Account source capture reference is malformed"); + } + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map raw)) throw invalid(field + " must be an object"); + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : raw.entrySet()) { + if (!(entry.getKey() instanceof String key)) throw invalid(field + " has a non-string key"); + result.put(key, entry.getValue()); + } + return result; + } + + private static byte[] decodeBase64(Object value, String field) { + String text = string(value, field); + try { + byte[] decoded = Base64.getDecoder().decode(text); + if (!Base64.getEncoder().encodeToString(decoded).equals(text)) { + throw invalid(field + " must use canonical Base64"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is malformed Base64"); + } + } + + private static byte[] bounded(byte[] value, int maximum, String name) { + if (value == null || value.length == 0 || value.length > maximum) { + throw invalid(name + " is absent or exceeds its byte limit"); + } + return value.clone(); + } + + private static String requireDigest(String value) { + if (value == null || !SHA256.matcher(value).matches()) { + throw invalid("originalSourceCaptureReferenceSha256 must be lowercase SHA-256 hex"); + } + return value; + } + + private static long positiveLong(Object value, String field) { + String text = string(value, field); + if (!POSITIVE_LONG.matcher(text).matches()) { + throw invalid(field + " must be a positive canonical signed 64-bit decimal string"); + } + try { + long parsed = Long.parseLong(text); + if (parsed <= 0L || !Long.toString(parsed).equals(text)) { + throw invalid(field + " must be a positive canonical signed 64-bit decimal string"); + } + return parsed; + } catch (NumberFormatException malformed) { + throw invalid(field + " is outside the supported signed 64-bit range"); + } + } + + private static UUID canonicalUuid(Object value, String field) { + String text = string(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || NIL_UUID.equals(parsed)) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (NIL_UUID.equals(value)) throw invalid(field + " must be a non-nil UUID"); + return value; + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) throw invalid(field + " must be positive"); + } + + private static String string(Object value, String field) { + if (!(value instanceof String text)) throw invalid(field + " must be a string"); + return text; + } + + private static void requireExactFields( + Map root, Set expected, String label) { + if (root == null || !root.keySet().equals(expected)) { + throw invalid(label + " has missing or unsupported fields"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw invalid("Account admission protection evidence is not valid UTF-8"); + } + } + + private static void requireCanonicalJson(byte[] originalBytes, String json, String label) + throws IOException { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!MessageDigest.isEqual(canonical, originalBytes)) { + throw invalid(label + " is not canonical RFC 8785 JSON"); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionRequest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionRequest.java new file mode 100644 index 0000000000..bad2c5ff27 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionRequest.java @@ -0,0 +1,448 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact integrity-only inputs for Account source protection through original StartSession + * admission. + * + *

This carrier does not authenticate an issuer, establish current source state, prove an active + * claim, or itself protect Account writes. It retains the complete original tuple, redemption + * projection, finite owner lease, Account World participation identity, and World hold identity. + */ +public final class AccountStartSessionAdmissionProtectionRequest { + public static final String SCHEMA = "account-start-session-admission-protection-request/v1"; + public static final int MAX_CANONICAL_BYTES = 768 * 1024; + public static final int MAX_PROJECTION_BYTES = 132 * 1024; + public static final int MAX_HOLD_IDENTITY_BYTES = 64 * 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POSITIVE_LONG = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern MILLIS_UTC = + Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z"); + private static final DateTimeFormatter MILLIS_FORMAT = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "originalPostAuthorizationTupleBytesBase64", + "accountRedemptionProjectionBytesBase64", + "gameSessionOwnerMutationId", + "gameSessionOwnerAttemptId", + "gameSessionOwnerFence", + "originalLeaseExpiresAt", + "accountWorldParticipationId", + "accountWorldParticipationFence", + "worldAdmissionHoldIdentityBytesBase64"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final byte[] originalPostAuthorizationTupleBytes; + private final byte[] accountRedemptionProjectionBytes; + private final UUID gameSessionOwnerMutationId; + private final UUID gameSessionOwnerAttemptId; + private final long gameSessionOwnerFence; + private final Instant originalLeaseExpiresAt; + private final UUID accountWorldParticipationId; + private final long accountWorldParticipationFence; + private final byte[] worldAdmissionHoldIdentityBytes; + private final StartSessionPostAuthorizationExecutionTuple originalTuple; + private final WorldCanonicalInitialAdmissionHold.HoldIdentity worldAdmissionHoldIdentity; + private final byte[] canonicalBytes; + + private AccountStartSessionAdmissionProtectionRequest( + byte[] originalPostAuthorizationTupleBytes, + byte[] accountRedemptionProjectionBytes, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + Instant originalLeaseExpiresAt, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + byte[] worldAdmissionHoldIdentityBytes, + StartSessionPostAuthorizationExecutionTuple originalTuple, + WorldCanonicalInitialAdmissionHold.HoldIdentity worldAdmissionHoldIdentity, + byte[] canonicalBytes) { + this.originalPostAuthorizationTupleBytes = originalPostAuthorizationTupleBytes.clone(); + this.accountRedemptionProjectionBytes = accountRedemptionProjectionBytes.clone(); + this.gameSessionOwnerMutationId = gameSessionOwnerMutationId; + this.gameSessionOwnerAttemptId = gameSessionOwnerAttemptId; + this.gameSessionOwnerFence = gameSessionOwnerFence; + this.originalLeaseExpiresAt = originalLeaseExpiresAt; + this.accountWorldParticipationId = accountWorldParticipationId; + this.accountWorldParticipationFence = accountWorldParticipationFence; + this.worldAdmissionHoldIdentityBytes = worldAdmissionHoldIdentityBytes.clone(); + this.originalTuple = originalTuple; + this.worldAdmissionHoldIdentity = worldAdmissionHoldIdentity; + this.canonicalBytes = canonicalBytes.clone(); + } + + /** Creates one canonical request and validates every complete-byte binding. */ + public static AccountStartSessionAdmissionProtectionRequest create( + byte[] exactCanonicalOriginalPostAuthorizationTupleBytes, + byte[] exactCanonicalAccountRedemptionProjectionBytes, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + Instant originalLeaseExpiresAt, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + WorldCanonicalInitialAdmissionHold.HoldIdentity worldAdmissionHoldIdentity) { + byte[] tupleBytes = + bounded( + exactCanonicalOriginalPostAuthorizationTupleBytes, + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES, + "original post-authorization tuple"); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (!Arrays.equals(tupleBytes, tuple.canonicalBytes())) { + throw invalid("Original post-authorization tuple bytes are not exact canonical bytes"); + } + + byte[] projectionBytes = + bounded( + exactCanonicalAccountRedemptionProjectionBytes, + MAX_PROJECTION_BYTES, + "Account redemption projection"); + byte[] expectedProjection = StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple); + if (!MessageDigest.isEqual(expectedProjection, projectionBytes)) { + throw invalid("Complete Account redemption projection differs from the original tuple"); + } + + requireNonNil(gameSessionOwnerMutationId, "gameSessionOwnerMutationId"); + requireNonNil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + Objects.requireNonNull(originalLeaseExpiresAt, "originalLeaseExpiresAt is required"); + String expiryText = canonicalExpiry(originalLeaseExpiresAt); + requireNonNil(accountWorldParticipationId, "accountWorldParticipationId"); + requirePositive(accountWorldParticipationFence, "accountWorldParticipationFence"); + Objects.requireNonNull(worldAdmissionHoldIdentity, "worldAdmissionHoldIdentity is required"); + byte[] holdBytes = + bounded( + worldAdmissionHoldIdentity.canonicalBytes(), + MAX_HOLD_IDENTITY_BYTES, + "World admission hold identity"); + WorldCanonicalInitialAdmissionHold.HoldIdentity decodedHold = + WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(holdBytes); + requireTupleAndHoldBinding(tuple, decodedHold); + + byte[] canonical = + encode( + tupleBytes, + projectionBytes, + gameSessionOwnerMutationId, + gameSessionOwnerAttemptId, + gameSessionOwnerFence, + expiryText, + accountWorldParticipationId, + accountWorldParticipationFence, + holdBytes); + return new AccountStartSessionAdmissionProtectionRequest( + tupleBytes, + projectionBytes, + gameSessionOwnerMutationId, + gameSessionOwnerAttemptId, + gameSessionOwnerFence, + originalLeaseExpiresAt, + accountWorldParticipationId, + accountWorldParticipationFence, + holdBytes, + tuple, + decodedHold, + canonical); + } + + /** Strictly decodes one complete, canonical, bounded request; decoding grants no authority. */ + public static AccountStartSessionAdmissionProtectionRequest decode(byte[] exactCanonicalBytes) { + byte[] stored = + bounded(exactCanonicalBytes, MAX_CANONICAL_BYTES, "admission protection request"); + try { + String json = strictUtf8(stored); + requireCanonicalJson(stored, json, "admission protection request"); + Map root = JSON.readValue(json, new TypeReference<>() {}); + requireExactFields(root, ROOT_FIELDS, "admission protection request"); + if (!SCHEMA.equals(string(root.get("schema"), "schema"))) { + throw invalid("Unsupported Account admission protection request schema"); + } + AccountStartSessionAdmissionProtectionRequest result = + create( + decodeBase64( + root.get("originalPostAuthorizationTupleBytesBase64"), + "originalPostAuthorizationTupleBytesBase64"), + decodeBase64( + root.get("accountRedemptionProjectionBytesBase64"), + "accountRedemptionProjectionBytesBase64"), + canonicalUuid(root.get("gameSessionOwnerMutationId"), "gameSessionOwnerMutationId"), + canonicalUuid(root.get("gameSessionOwnerAttemptId"), "gameSessionOwnerAttemptId"), + positiveLong(root.get("gameSessionOwnerFence"), "gameSessionOwnerFence"), + parseExpiry(string(root.get("originalLeaseExpiresAt"), "originalLeaseExpiresAt")), + canonicalUuid(root.get("accountWorldParticipationId"), "accountWorldParticipationId"), + positiveLong( + root.get("accountWorldParticipationFence"), "accountWorldParticipationFence"), + WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored( + decodeBase64( + root.get("worldAdmissionHoldIdentityBytesBase64"), + "worldAdmissionHoldIdentityBytesBase64"))); + if (!MessageDigest.isEqual(stored, result.canonicalBytes)) { + throw invalid("Account admission protection request members are inconsistent"); + } + return result; + } catch (IllegalArgumentException expected) { + throw expected; + } catch (IOException | RuntimeException malformed) { + throw invalid("Account admission protection request is malformed"); + } + } + + public byte[] originalPostAuthorizationTupleBytes() { + return originalPostAuthorizationTupleBytes.clone(); + } + + public byte[] accountRedemptionProjectionBytes() { + return accountRedemptionProjectionBytes.clone(); + } + + public UUID gameSessionOwnerMutationId() { + return gameSessionOwnerMutationId; + } + + public UUID gameSessionOwnerAttemptId() { + return gameSessionOwnerAttemptId; + } + + public long gameSessionOwnerFence() { + return gameSessionOwnerFence; + } + + public Instant originalLeaseExpiresAt() { + return originalLeaseExpiresAt; + } + + public UUID accountWorldParticipationId() { + return accountWorldParticipationId; + } + + public long accountWorldParticipationFence() { + return accountWorldParticipationFence; + } + + public byte[] worldAdmissionHoldIdentityBytes() { + return worldAdmissionHoldIdentityBytes.clone(); + } + + public StartSessionPostAuthorizationExecutionTuple originalTuple() { + return originalTuple; + } + + public WorldCanonicalInitialAdmissionHold.HoldIdentity worldAdmissionHoldIdentity() { + return worldAdmissionHoldIdentity; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + private static byte[] encode( + byte[] tupleBytes, + byte[] projectionBytes, + UUID ownerMutationId, + UUID ownerAttemptId, + long ownerFence, + String leaseExpiry, + UUID participationId, + long participationFence, + byte[] holdBytes) { + Map root = new LinkedHashMap<>(); + root.put("schema", SCHEMA); + root.put( + "originalPostAuthorizationTupleBytesBase64", + Base64.getEncoder().encodeToString(tupleBytes)); + root.put( + "accountRedemptionProjectionBytesBase64", + Base64.getEncoder().encodeToString(projectionBytes)); + root.put("gameSessionOwnerMutationId", ownerMutationId.toString()); + root.put("gameSessionOwnerAttemptId", ownerAttemptId.toString()); + root.put("gameSessionOwnerFence", Long.toString(ownerFence)); + root.put("originalLeaseExpiresAt", leaseExpiry); + root.put("accountWorldParticipationId", participationId.toString()); + root.put("accountWorldParticipationFence", Long.toString(participationFence)); + root.put( + "worldAdmissionHoldIdentityBytesBase64", Base64.getEncoder().encodeToString(holdBytes)); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (canonical.length > MAX_CANONICAL_BYTES) { + throw invalid("Account admission protection request exceeds its byte limit"); + } + return canonical; + } catch (IOException impossible) { + throw new IllegalStateException( + "Account admission protection request cannot be encoded", impossible); + } + } + + private static void requireTupleAndHoldBinding( + StartSessionPostAuthorizationExecutionTuple tuple, + WorldCanonicalInitialAdmissionHold.HoldIdentity hold) { + var preTuple = tuple.preAuthorizationTuple(); + var action = preTuple.action(); + var request = hold.request(); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(preTuple.actionFamily()) + || !"game-session-service".equals(preTuple.targetOwner()) + || !action.scope().tenantId().equals(request.canonicalTenantId()) + || !action.scope().targetNamespace().equals(request.targetNamespace()) + || !GrpcPeerIdentity.isValidNamespace(action.scope().targetNamespace())) { + throw invalid("Original StartSession tuple differs from the complete World hold scope"); + } + } + + private static byte[] decodeBase64(Object value, String field) { + String text = string(value, field); + try { + byte[] decoded = Base64.getDecoder().decode(text); + if (!Base64.getEncoder().encodeToString(decoded).equals(text)) { + throw invalid(field + " must use canonical Base64"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is malformed Base64"); + } + } + + private static byte[] bounded(byte[] value, int maximum, String name) { + if (value == null || value.length == 0 || value.length > maximum) { + throw invalid(name + " is absent or exceeds its byte limit"); + } + return value.clone(); + } + + private static String canonicalExpiry(Instant value) { + if (value.getNano() % 1_000_000 != 0) { + throw invalid("originalLeaseExpiresAt must use exact millisecond precision"); + } + String text = MILLIS_FORMAT.format(value); + if (!MILLIS_UTC.matcher(text).matches()) { + throw invalid("originalLeaseExpiresAt must use canonical UTC millisecond text"); + } + return text; + } + + private static Instant parseExpiry(String value) { + if (!MILLIS_UTC.matcher(value).matches()) { + throw invalid("originalLeaseExpiresAt must use canonical UTC millisecond text"); + } + try { + Instant parsed = Instant.parse(value); + if (!MILLIS_FORMAT.format(parsed).equals(value)) { + throw invalid("originalLeaseExpiresAt must use canonical UTC millisecond text"); + } + return parsed; + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException expected) throw expected; + throw invalid("originalLeaseExpiresAt is malformed"); + } + } + + private static long positiveLong(Object value, String field) { + String text = string(value, field); + if (!POSITIVE_LONG.matcher(text).matches()) { + throw invalid(field + " must be a positive canonical signed 64-bit decimal string"); + } + try { + long parsed = Long.parseLong(text); + if (parsed <= 0L || !Long.toString(parsed).equals(text)) { + throw invalid(field + " must be a positive canonical signed 64-bit decimal string"); + } + return parsed; + } catch (NumberFormatException malformed) { + throw invalid(field + " is outside the supported signed 64-bit range"); + } + } + + private static UUID canonicalUuid(Object value, String field) { + String text = string(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || NIL_UUID.equals(parsed)) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (NIL_UUID.equals(value)) throw invalid(field + " must be a non-nil UUID"); + return value; + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) throw invalid(field + " must be positive"); + } + + private static String string(Object value, String field) { + if (!(value instanceof String text)) throw invalid(field + " must be a string"); + return text; + } + + private static void requireExactFields( + Map root, Set expected, String label) { + if (root == null || !root.keySet().equals(expected)) { + throw invalid(label + " has missing or unsupported fields"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw invalid("Account admission protection request is not valid UTF-8"); + } + } + + private static void requireCanonicalJson(byte[] originalBytes, String json, String label) + throws IOException { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!MessageDigest.isEqual(canonical, originalBytes)) { + throw invalid(label + " is not canonical RFC 8785 JSON"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.java new file mode 100644 index 0000000000..5c6f4335f1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.java @@ -0,0 +1,59 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.io.IOException; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import tools.jackson.databind.json.JsonMapper; + +/** Canonical full Account projection used by original StartSession redemption. */ +public final class StartSessionAccountRedemptionProjection { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private StartSessionAccountRedemptionProjection() {} + + /** + * Derives the complete canonical Account redemption projection from the original tuple. + * + *

The issuance fence remains a JSON number, matching the original projection bytes. This value + * proves integrity and tuple binding only; it does not establish Account authentication, + * currentness, or a live reservation claim. + */ + public static byte[] fromOriginalTuple( + StartSessionPostAuthorizationExecutionTuple originalTuple) { + Objects.requireNonNull(originalTuple, "originalTuple is required"); + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(originalTuple.authorityEvidenceBundleBytes()); + long issuanceFence; + try { + issuanceFence = Long.parseLong(originalTuple.issuanceFence()); + } catch (NumberFormatException malformed) { + throw new IllegalArgumentException("Original Account issuance fence is malformed", malformed); + } + if (issuanceFence <= 0L) { + throw new IllegalArgumentException("Original Account issuance fence is not positive"); + } + Map projection = + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + originalTuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + issuanceFence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + } catch (IOException malformed) { + throw new IllegalStateException( + "Could not encode the original Account redemption projection", malformed); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java index 0e7e1e3aed..90713a3df8 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java @@ -1,22 +1,18 @@ package net.firedevops.firemud.common.gamesession; -import java.io.IOException; import java.util.Arrays; import java.util.HexFormat; -import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; -import tools.jackson.databind.json.JsonMapper; /** * Read-only historical evidence for one exact original StartSession attempt. @@ -29,7 +25,6 @@ public final class HistoricalOriginalStartSessionOwnerEvidence { public static final int SCHEMA_VERSION = 1; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); - private static final JsonMapper JSON = JsonMapper.builder().build(); private HistoricalOriginalStartSessionOwnerEvidence() {} @@ -214,7 +209,9 @@ private void requireCoherentEvidence() { || !selector.launchDescriptorId().equals(launchAssociation.launchDescriptorId()) || !request.expectedOwnerAttemptId().equals(ownerAttemptId) || request.expectedOwnerFence() != ownerFence - || !expectedAccountProjection(originalTuple).equalsBytes(accountRedemptionProjection)) { + || !Arrays.equals( + StartSessionAccountRedemptionProjection.fromOriginalTuple(originalTuple), + accountRedemptionProjection)) { throw new IllegalArgumentException( "Historical StartSession tuple, projection, attempt, or association selector differs"); } @@ -296,49 +293,6 @@ private void requirePinDigests() { } } - private record ExpectedProjection(byte[] bytes) { - private boolean equalsBytes(byte[] candidate) { - return Arrays.equals(bytes, candidate); - } - } - - private static ExpectedProjection expectedAccountProjection( - StartSessionPostAuthorizationExecutionTuple tuple) { - StartSessionAuthorityEvidenceBundle bundle = - StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); - long issuanceFence; - try { - issuanceFence = Long.parseLong(tuple.issuanceFence()); - } catch (NumberFormatException malformed) { - throw new IllegalArgumentException( - "Historical Account issuance fence is malformed", malformed); - } - if (issuanceFence <= 0L) { - throw new IllegalArgumentException("Historical Account projection identity is malformed"); - } - Map projection = - Map.of( - "projectionSchemaId", - "accountStartSessionRedemptionProjection", - "projectionSchemaVersion", - "1", - "authorizationReferenceFingerprint", - tuple.authorizationReferenceFingerprint(), - "authorityEvidenceBundle", - bundle.jsonValue(), - "issuanceOperationId", - bundle.issuanceOperationId().toString(), - "issuanceFence", - issuanceFence); - try { - byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); - return new ExpectedProjection(bytes); - } catch (IOException malformed) { - throw new IllegalStateException( - "Could not encode the retained Account projection", malformed); - } - } - private static UUID requireNonNil(UUID value, String name) { Objects.requireNonNull(value, name); if (NIL_UUID.equals(value)) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java new file mode 100644 index 0000000000..a4174e34ce --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java @@ -0,0 +1,481 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import org.junit.jupiter.api.Test; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +class AccountStartSessionAdmissionProtectionEvidenceTest { + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID GAME_SESSION_MUTATION = uuid("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"); + private static final UUID GAME_SESSION_ATTEMPT = uuid("ec13cc04-ec15-4eb8-a018-c2c5e8da65f8"); + private static final UUID ACCOUNT_PARTICIPATION = uuid("47b3be7f-a32f-4e19-8916-8c3b8da07a82"); + private static final UUID WORLD_HOLD = uuid("0db7344a-1e67-4b95-905a-83dc9c472f0c"); + private static final UUID WORLD_HOLD_FENCE = uuid("52a14272-f9e4-4f67-97c9-62247b5fbcc1"); + private static final UUID ACCOUNT_PROTECTION = uuid("6b763f1d-c5bc-4080-b499-d29debc0a7b8"); + private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-09T10:20:30.456Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void redemptionProjectionRetainsTheOriginalNumericIssuanceFenceRepresentation() + throws IOException { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple("admission-projection"); + + byte[] projection = StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple); + Map projectionValue = readObject(projection); + + Object issuanceFence = projectionValue.get("issuanceFence"); + assertThat(issuanceFence).isInstanceOf(Number.class); + assertThat(((Number) issuanceFence).toString()).isEqualTo("23"); + assertThat(((Map) projectionValue.get("authorityEvidenceBundle")).get("issuanceFence")) + .isEqualTo("23"); + } + + @Test + void requestAndEvidenceRoundTripCompleteOriginalIdentityAndSourceChildren() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple("admission-roundtrip"); + AccountStartSessionAdmissionProtectionRequest request = request(tuple); + SourceEvidence issuerSource = + new SourceEvidence( + SourceKind.ISSUER, + "https://issuer.example", + null, + "9", + null, + null, + new byte[] {0, 1, 2, (byte) 0xff}); + SourceEvidence accountSource = source("account-source-before"); + byte[] captureReference = captureReference(tuple, "17", "23", "18446744073709551615"); + AccountStartSessionAdmissionProtectionEvidence evidence = + AccountStartSessionAdmissionProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + Long.MAX_VALUE, + captureReference, + sha256(captureReference), + List.of(issuerSource, accountSource)); + + AccountStartSessionAdmissionProtectionRequest decodedRequest = + AccountStartSessionAdmissionProtectionRequest.decode(request.canonicalBytes()); + AccountStartSessionAdmissionProtectionEvidence decodedEvidence = + AccountStartSessionAdmissionProtectionEvidence.decode(evidence.canonicalBytes()); + + assertThat(decodedRequest.canonicalBytes()).containsExactly(request.canonicalBytes()); + assertThat(decodedRequest.originalPostAuthorizationTupleBytes()) + .containsExactly(tuple.canonicalBytes()); + assertThat(decodedRequest.accountRedemptionProjectionBytes()) + .containsExactly(StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); + assertThat(decodedRequest.gameSessionOwnerMutationId()).isEqualTo(GAME_SESSION_MUTATION); + assertThat(decodedRequest.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT); + assertThat(decodedRequest.gameSessionOwnerFence()).isEqualTo(Long.MAX_VALUE); + assertThat(decodedRequest.originalLeaseExpiresAt()).isEqualTo(ORIGINAL_LEASE_EXPIRY); + assertThat(decodedRequest.accountWorldParticipationId()).isEqualTo(ACCOUNT_PARTICIPATION); + assertThat(decodedRequest.accountWorldParticipationFence()).isEqualTo(Long.MAX_VALUE); + assertThat(decodedRequest.worldAdmissionHoldIdentityBytes()) + .containsExactly(request.worldAdmissionHoldIdentity().canonicalBytes()); + assertThat(decodedEvidence.canonicalBytes()).containsExactly(evidence.canonicalBytes()); + assertThat(decodedEvidence.request().canonicalBytes()) + .containsExactly(request.canonicalBytes()); + assertThat(decodedEvidence.accountProtectionId()).isEqualTo(ACCOUNT_PROTECTION); + assertThat(decodedEvidence.accountProtectionFence()).isEqualTo(Long.MAX_VALUE); + assertThat(decodedEvidence.originalSourceCaptureReferenceBytes()) + .containsExactly(evidence.originalSourceCaptureReferenceBytes()); + assertThat(decodedEvidence.originalSourceCaptureReferenceSha256()) + .isEqualTo(sha256(evidence.originalSourceCaptureReferenceBytes())); + assertThat(decodedEvidence.sourceEvidenceVector()) + .extracting(SourceEvidence::key) + .containsExactly("ACCOUNT:" + TENANT, "ISSUER:https://issuer.example"); + assertThat(decodedEvidence.sourceEvidenceVector().get(0).canonicalBytes()) + .containsExactly(accountSource.canonicalBytes()); + assertThat(decodedEvidence.sourceEvidenceVector().get(1).canonicalBytes()) + .containsExactly(issuerSource.canonicalBytes()); + } + + @Test + void rejectsRequestProjectionHoldScopeExpiryAndCounterSubstitutions() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple("admission-binding"); + byte[] expectedProjection = StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple); + byte[] substitutedProjection = expectedProjection.clone(); + substitutedProjection[substitutedProjection.length - 2] ^= 1; + + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionRequest.create( + tuple.canonicalBytes(), + substitutedProjection, + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + 1L, + ORIGINAL_LEASE_EXPIRY, + ACCOUNT_PARTICIPATION, + 2L, + hold(tuple))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionRequest.create( + tuple.canonicalBytes(), + expectedProjection, + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + 1L, + ORIGINAL_LEASE_EXPIRY.plusNanos(1), + ACCOUNT_PARTICIPATION, + 2L, + hold(tuple))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("millisecond"); + + WorldCanonicalInitialAdmissionHold.HoldIdentity wrongNamespace = + hold(tuple, TENANT, "another-world-runtime"); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionRequest.create( + tuple.canonicalBytes(), + expectedProjection, + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + 1L, + ORIGINAL_LEASE_EXPIRY, + ACCOUNT_PARTICIPATION, + 2L, + wrongNamespace)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("World hold scope"); + + Map overflow = readObject(request(tuple).canonicalBytes()); + overflow.put("gameSessionOwnerFence", "9223372036854775808"); + assertThatThrownBy( + () -> AccountStartSessionAdmissionProtectionRequest.decode(canonical(overflow))) + .isInstanceOf(IllegalArgumentException.class); + Map missing = readObject(request(tuple).canonicalBytes()); + missing.remove("originalLeaseExpiresAt"); + assertThatThrownBy( + () -> AccountStartSessionAdmissionProtectionRequest.decode(canonical(missing))) + .isInstanceOf(IllegalArgumentException.class); + Map extra = readObject(request(tuple).canonicalBytes()); + extra.put("opaqueAuthorizationReference", "must-not-be-retained"); + assertThatThrownBy(() -> AccountStartSessionAdmissionProtectionRequest.decode(canonical(extra))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionRequest.decode( + withDuplicateSchema(request(tuple).canonicalBytes()))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void bindsCaptureReferenceToTupleAndRetainsCompleteChangedSourceEvidence() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple("admission-evidence"); + AccountStartSessionAdmissionProtectionRequest request = request(tuple); + byte[] captureBytes = captureReference(tuple, "17", "23", "18446744073709551615"); + String digest = sha256(captureBytes); + SourceEvidence originalSource = source("complete-account-source-before"); + AccountStartSessionAdmissionProtectionEvidence original = + AccountStartSessionAdmissionProtectionEvidence.create( + request, ACCOUNT_PROTECTION, 4L, captureBytes, digest, List.of(originalSource)); + SourceEvidence changedSource = source("complete-account-source-after"); + AccountStartSessionAdmissionProtectionEvidence changed = + AccountStartSessionAdmissionProtectionEvidence.create( + request, ACCOUNT_PROTECTION, 4L, captureBytes, digest, List.of(changedSource)); + + assertThat(changed.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat( + AccountStartSessionAdmissionProtectionEvidence.decode(changed.canonicalBytes()) + .sourceEvidenceVector() + .get(0) + .canonicalBytes()) + .containsExactly(changedSource.canonicalBytes()); + + byte[] wrongReference = captureReference(tuple, "18", "23", "18446744073709551615"); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + 4L, + wrongReference, + sha256(wrongReference), + List.of(originalSource))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("original tuple bundle"); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + 4L, + captureBytes, + "0".repeat(64), + List.of(originalSource))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest differs"); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + 4L, + captureBytes, + digest, + List.of(originalSource, originalSource))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate source keys"); + } + + @Test + void rejectsEvidenceShapeDuplicatesTrailingBytesAndOverflowingCounters() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple("admission-shape"); + byte[] captureReference = captureReference(tuple, "17", "23", "18446744073709551615"); + AccountStartSessionAdmissionProtectionEvidence evidence = + AccountStartSessionAdmissionProtectionEvidence.create( + request(tuple), + ACCOUNT_PROTECTION, + 4L, + captureReference, + sha256(captureReference), + List.of(source("shape-source"))); + + Map overflow = readObject(evidence.canonicalBytes()); + overflow.put("accountProtectionFence", "9223372036854775808"); + assertThatThrownBy( + () -> AccountStartSessionAdmissionProtectionEvidence.decode(canonical(overflow))) + .isInstanceOf(IllegalArgumentException.class); + Map missing = readObject(evidence.canonicalBytes()); + missing.remove("accountProtectionId"); + assertThatThrownBy( + () -> AccountStartSessionAdmissionProtectionEvidence.decode(canonical(missing))) + .isInstanceOf(IllegalArgumentException.class); + Map extra = readObject(evidence.canonicalBytes()); + extra.put("accountCredential", "not-carried"); + assertThatThrownBy( + () -> AccountStartSessionAdmissionProtectionEvidence.decode(canonical(extra))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionEvidence.decode( + withDuplicateSchema(evidence.canonicalBytes()))) + .isInstanceOf(IllegalArgumentException.class); + byte[] trailing = + Arrays.copyOf(evidence.canonicalBytes(), evidence.canonicalBytes().length + 1); + trailing[trailing.length - 1] = (byte) ' '; + assertThatThrownBy(() -> AccountStartSessionAdmissionProtectionEvidence.decode(trailing)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AccountStartSessionAdmissionProtectionRequest request( + StartSessionPostAuthorizationExecutionTuple tuple) { + return AccountStartSessionAdmissionProtectionRequest.create( + tuple.canonicalBytes(), + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + Long.MAX_VALUE, + ORIGINAL_LEASE_EXPIRY, + ACCOUNT_PARTICIPATION, + Long.MAX_VALUE, + hold(tuple)); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(String requestId) { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical original StartSession admission attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = TENANT.toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", ACTOR.toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence); + return canonical(bundle); + } + + private static WorldCanonicalInitialAdmissionHold.HoldIdentity hold( + StartSessionPostAuthorizationExecutionTuple tuple) { + return hold(tuple, TENANT, "world-runtime"); + } + + private static WorldCanonicalInitialAdmissionHold.HoldIdentity hold( + StartSessionPostAuthorizationExecutionTuple tuple, UUID tenant, String namespace) { + return new WorldCanonicalInitialAdmissionHold.HoldIdentity( + new WorldCanonicalInitialAdmissionHold.Request( + namespace, + tenant, + "earth", + uuid("3916f423-2870-426a-a8aa-5e3f97412613"), + uuid("54e6094e-11bb-4f4c-93ee-a52f715b530b"), + "SHARED", + uuid("a55b2e10-9a24-4adb-adb8-6fc66fe3b8e9"), + uuid("d7280ec0-5979-4b62-8418-e9f139415184"), + 3L, + tuple.controlPlaneRequestId(), + "c".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null), + WORLD_HOLD, + WORLD_HOLD_FENCE); + } + + private static byte[] captureReference( + StartSessionPostAuthorizationExecutionTuple tuple, + String sourceVersion, + String sourceFence, + String linearization) { + return canonical( + Map.of( + "schema", + AccountStartSessionAdmissionProtectionEvidence.SOURCE_CAPTURE_REFERENCE_SCHEMA, + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "capturedAt", "2026-10-09T10:11:12.123Z", + "bundleReference", + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "sourceVersion", sourceVersion, + "sourceFence", sourceFence, + "linearization", linearization), + "snapshotSha256", "d".repeat(64))); + } + + private static SourceEvidence source(String exactEvidence) { + return new SourceEvidence( + SourceKind.ACCOUNT, + TENANT.toString(), + "2", + "17", + null, + null, + exactEvidence.getBytes(StandardCharsets.UTF_8)); + } + + private static Map readObject(byte[] bytes) throws IOException { + return JSON.readValue(bytes, new TypeReference<>() {}); + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static byte[] withDuplicateSchema(byte[] original) { + String json = new String(original, StandardCharsets.UTF_8); + String duplicated = + json.replaceFirst( + "\\{", "{\"schema\":\"account-start-session-admission-protection-request/v1\","); + return duplicated.getBytes(StandardCharsets.UTF_8); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} From 1f9f673095e4ac8f5bb6b9c0a969469854de4d86 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 20:50:05 +1300 Subject: [PATCH 078/129] Preserve exact original admission lease and acquire Account protection over mTLS --- .github/workflows/ci.yml | 9 + .../account-service/api-contracts.md | 4 +- .../architecture/system-architecture-cicd.md | 1 + ...ame-authoring-publishing-and-activation.md | 8 +- .../tests/ci-lightweight-scope-contract.sh | 40 + ...ion_admission_protection_acquisition.proto | 32 + ...ssionProtectionAcquisitionGrpcService.java | 103 ++ ...33__start_session_admission_protection.sql | 10 +- ...sionProtectionPostgresIntegrationTest.java | 108 +- ...ionAcquisitionPostgresIntegrationTest.java | 1023 +++++++++++++++++ ...sionProtectionAcquisitionGrpcMtlsTest.java | 734 ++++++++++++ ...nProtectionAcquisitionGrpcServiceTest.java | 435 +++++++ ...nAdmissionProtectionAcquisitionClient.java | 12 + ...missionProtectionAcquisitionGrpcCodec.java | 183 +++ ...onAdmissionProtectionAcquisitionInput.java | 103 ++ ...tartSessionAdmissionProtectionRequest.java | 26 +- ...ionProtectionAcquisitionGrpcCodecTest.java | 335 ++++++ ...essionAdmissionProtectionEvidenceTest.java | 21 +- services/common-security/build.gradle.kts | 1 + ...issionProtectionAcquisitionGrpcClient.java | 177 +++ ...onProtectionAcquisitionGrpcClientTest.java | 305 +++++ 21 files changed, 3637 insertions(+), 33 deletions(-) create mode 100644 protos/account/v1/start_session_admission_protection_acquisition.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcService.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionInput.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClient.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClientTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8d78dc28e3..69d2c930e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1113,6 +1113,15 @@ jobs: name: test-logs-${{ matrix.module }}-${{ github.sha }} path: ${{ matrix.module == 'load-testing' && 'dev-tools/load-testing/build/reports/tests/' || format('services/{0}/build/reports/tests/', matrix.module) }} + - name: 📤 Upload JUnit Test Results + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: junit-${{ matrix.module }}-results-${{ github.sha }}-attempt-${{ github.run_attempt }} + path: ${{ matrix.module == 'load-testing' && 'dev-tools/load-testing/build/test-results/**/*.xml' || format('services/{0}/build/test-results/**/*.xml', matrix.module) }} + if-no-files-found: warn + retention-days: 14 + # Final gating and PR reporting validation-summary: name: ${{ github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Summary)' || 'Validation Summary' }} diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 0da482e703..2bccfcb156 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -203,10 +203,12 @@ Fresh World participation acquisition first obtains the [Game Session current-or The credential-free `ReadRedeemedOperationProjection` receiver accepts the exact configured same-namespace Game Design peer and the exact original Game Session redeemer under [ADR 0047's restricted original-operation read](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). Before returning the retained projection, Account compares the original request/reservation and redeemed workload/attempt/fence, then revalidates the original actor/JTI, current source and reference expiry. The response contains no credential or renewed permission. Game Session must separately prove its original claim and immutable pin under the owner-local checks required by that contract; this Account read is not World participation or admission. -The distinct original-admission producer and independent readback implement [ADR 0047's admission source protection](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection), not the World receiving lifecycle above. Its closed RFC 8785 `account-start-session-admission-protection-request/v1` object has exactly `schema`, `originalPostAuthorizationTupleBytesBase64`, `accountRedemptionProjectionBytesBase64`, `gameSessionOwnerMutationId`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `originalLeaseExpiresAt`, `accountWorldParticipationId`, `accountWorldParticipationFence`, and `worldAdmissionHoldIdentityBytesBase64`. UUIDs are canonical non-nil strings; positive fences are canonical decimal strings bounded by the owner counter type; expiry is unchanged UTC with exactly three fractional digits. Base64 members carry exact canonical complete original values, not hashes or caller-selected projections. The complete World hold binds its separate admission request/digest, precondition and canonical target. Unknown, duplicate, trailing, noncanonical, substituted or oversized data is rejected. +The distinct original-admission producer and independent readback implement [ADR 0047's admission source protection](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection), not the World receiving lifecycle above. Its closed RFC 8785 `account-start-session-admission-protection-request/v1` object has exactly `schema`, `originalPostAuthorizationTupleBytesBase64`, `accountRedemptionProjectionBytesBase64`, `gameSessionOwnerMutationId`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `originalLeaseExpiresAt`, `accountWorldParticipationId`, `accountWorldParticipationFence`, and `worldAdmissionHoldIdentityBytesBase64`. UUIDs are canonical non-nil strings; positive fences are canonical decimal strings bounded by the owner counter type; expiry is the unchanged UTC lease with exactly six fractional digits, retaining PostgreSQL microsecond precision. Base64 members carry exact canonical complete original values, not hashes or caller-selected projections. The complete World hold binds its separate admission request/digest, precondition and canonical target. Unknown, duplicate, trailing, noncanonical, substituted or oversized data is rejected. The closed `account-start-session-admission-protection-evidence/v1` object carries exactly `schema`, `requestBytesBase64`, `accountProtectionId`, `accountProtectionFence`, `originalSourceCaptureReferenceBytesBase64`, `originalSourceCaptureReferenceSha256`, and `sourceEvidenceVector`. The capture reference retains the original Account version/fence/linearization and exact SHA-256; the vector contains each exact canonical source frame in canonical source-key order, without omissions, extras or duplicate keys. Carrier validation establishes integrity only, not authentication, currentness, continuity or admission. The exact same-namespace Game Session caller is checked before input handling; its fresh current-attempt read runs outside SQL, the original Account currentness callback creates or recovers immutable evidence in writable read-committed SQL, and a separate lookup-only transaction exact-compares post-commit readback. Runtime registration and authenticated terminal composition remain gated in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The distinct internal `AcquireOriginalStartSessionAdmissionProtection` RPC carries a closed schema-version-1 request and exact target namespace, complete original post-authorization tuple, actual Game Session mutation/attempt/fence, original World participation ID/fence, and complete canonical World hold identity. The caller does not supply a redemption projection or lease expiry: Account obtains those unchanged values from the authenticated current original Game Session attempt. The exact same-namespace Game Session workload is authenticated before parsing; end-user context and ambient transactions are rejected. Request data is bounded to 768 KiB, canonical evidence to 8 MiB, and wire framing to 9 MiB. A successful response carries the complete canonical protection evidence, and the client exact-compares every caller-carried binding. This comparison does not prove Game Session's current claim or unchanged lease; its receiving owner must independently enforce those retained values at its admission boundary. The receiver and clients remain unregistered until their producer, consumer, terminal and activation gates are proved. + ## REST APIs | Method | Path | Description | diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 1ccff9f360..083c6e5cdc 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -88,6 +88,7 @@ The main [`ci.yml`](../../.github/workflows/ci.yml) workflow: - Runs formatting and lint steps (Spotless, markdownlint, link checks). - On the complete CI path, executes a matrix of Gradle `check` tasks (one per microservice) with SpotBugs, Checkstyle, and tests enabled; lightweight documentation-only PR validation does not run these service checks. - On the complete CI path, generates one per-service JaCoCo report from unit and every available categorized integration/cross-service test execution, uploads that combined XML to Codecov using GitHub OIDC, and runs the Trivy scans. Modules without categorized tests retain their unit-only report; production classes remain in the report rather than being excluded to improve percentages. Lightweight documentation-only PR validation does not run these Trivy jobs. +- Retains the Gradle JUnit XML results from each affected-module `check` run, including unit and integration outcomes, in an artifact named with the module, workflow SHA, and run attempt for 14 days. Including the attempt keeps partial workflow reruns from colliding with earlier artifacts. The load-testing matrix entry uses its `dev-tools/load-testing` output; missing XML is reported as a warning so artifact retention does not change the test gate. - Uses Node 24 to lint OpenAPI specs, run React linters, and execute an accessibility audit using headless Chrome. - Validates tracked Bash scripts across the repository with ShellCheck and validates every tracked Python script with `py_compile` plus repository-wide Ruff linting. - Invokes a dedicated `generate-erd` job that runs [`dev-tools/docs/generate-erd.sh`](../../dev-tools/docs/generate-erd.sh) to build ERD diagrams from service migrations and upload them as artifacts. 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 f887655c9c..a274fac695 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 @@ -6,7 +6,13 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Distinct original-StartSession Account admission protection is prepared under [ADR 0047's canonical lifecycle](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection). It authenticates the original Game Session receiving workload, obtains the exact current original-attempt observation outside SQL, then revalidates the original actor/JTI/reference and unchanged complete capture through the existing Account currentness callback. V133 retains the complete request, actual mutation/attempt/fence and unchanged finite expiry, original World participation, full World hold, immutable capture and exact source children; additive writer/disclosure hooks preserve the existing assembled owner checks. A settled World row can supply historical binding but cannot supply current authority: the producer must freshly prove unchanged original sources after a gap. Independent lookup-only readback returns the first protection unchanged. V129 World settlement and V131 observation are unchanged. Authenticated Game Session terminal composition is not yet complete, so every V133 settlement insertion remains denied; missing or ambiguous proof cannot release protection. This producer remains unregistered and does not enable admission. The final affected Common/Account full-check, formatting, static-analysis, schema-generation, boot-JAR, links and Markdown gate passes in 1m12s. XML retains 581 Common and 1,296 Account unit cases with zero failures, errors or skips; unchanged successful tasks reuse their results. Account executes seven non-container integration cases and skips 277, including all seven new upstream-stipulated V133 PostgreSQL integrity definitions, without Docker. These synthetic units and compiled definitions do not establish genuine authenticated owner composition, live claim continuity, restart settlement or executed PostgreSQL proof. The approved isolated durability diagnostic adds administrator phase observations, entry observations and a failure-only WAL dump bounded to two segments/128 records/16,384 characters; none supplies authority, and no caller preflight SQL, forced flushing or expiry change is added. Its physical execution, possible timing perturbation and record provenance remain unproved; the earlier valid fresh-backend failure does not authorize production adoption. +Distinct original-StartSession Account admission protection is prepared under [ADR 0047's canonical lifecycle](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection). It authenticates the original Game Session receiving workload, obtains the exact current original-attempt observation outside SQL, then revalidates the original actor/JTI/reference and unchanged complete capture through the existing Account currentness callback. V133 retains the complete request, actual mutation/attempt/fence and unchanged finite expiry, original World participation, full World hold, immutable capture and exact source children; additive writer/disclosure hooks preserve the existing assembled owner checks. A settled World row supplies historical binding, not current authority: acquisition must freshly prove unchanged original sources after a gap. Independent lookup-only readback returns the first protection unchanged. V129 World settlement and V131 observation are unchanged. Every V133 settlement insertion remains denied pending genuine authenticated Game Session terminal composition; expiry, missing or ambiguous proof cannot release protection. The producer remains unregistered and does not enable admission. + +The prepared acquisition transport exposes the [closed Account RPC](../../../protos/account/v1/start_session_admission_protection_acquisition.proto), with the mTLS client in Common Security so it can reject authenticated end-user context before transport. It authenticates the exact Game Session workload before parsing and returns complete canonical evidence rather than selected hashes. The exact original PostgreSQL lease is retained at microsecond precision, with six canonical fractional digits and no rounding or renewal. V133 now compares the full World hold's canonical `sha256:`-prefixed digest. Nine repository integrity definitions cover exact retained sub-millisecond expiry, changed caller expiry without modifying the stored row, and forged digest rejection; the five new real-Account producer definitions cover exact acquisition/retry/readback, lost acknowledgement, changed Account sources after World settlement, protection beyond World settlement and lease expiry, and expiry while waiting for the original issuance lock. Logging, Game Session and World collaborators in those producer definitions are explicitly stipulated; they do not establish genuine cross-owner execution. The corrected composed Common Platform, Common Security and Account full checks, formatting, Checkstyle, SpotBugs, coverage, Account schema generation and boot JAR, links and Markdown pass in 2m1s. XML retains 584, 143 and 1,304 unit cases respectively, with zero failures, errors or skips; unchanged successful tasks reuse results. Four new native loopback mTLS cases execute and pass with the real Common client but a mocked Account owner. Account executes seven non-container integration cases and skips 284 of 291 definitions without Docker, including all nine V133 and five new producer cases. Their compilation and discovery are not PostgreSQL execution proof. Flyway sanity passes 12 sets and 290 versioned files; the inherited CI scope contract passes 24 tests and its structural assertions, with ShellCheck and diff hygiene clean. + +Historical source `0a99100a98ee19197bf162a4c1c202acec8e9055` [Validation run 38032471916](https://github.com/benhook1013/FireMUD/actions/runs/38032471916) ended cancelled with a failed required gate. Originating Account XML records 292 integration executions, 12 failures and no skips: six of seven V133 cases failed at the now-corrected hold-digest comparison; four of 40 admission-lease cases and two of ten isolated prototype cases failed WAL coverage. World executed 221 cases without failures or skips. Game Design XML records 146 successful executions before its later checks were cancelled, not a completed passing job. The actual tested merge `21819de08ba16420f1749a5de4e37ada1b842b2c` has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source; it is not proof against the separately recorded integration parent. Corrected V133 physical execution remains required. + +The approved test-only durability diagnostic retains administrator and entry observations plus failure-only WAL inspection bounded to two segments, 128 records and 16,384 characters. None supplies authority or changes the original commit, fixed snapshot, upper bound, independent covering flush or expiry sequence. The saved production failure range contains a transaction-zero `Heap2 PRUNE` record and the original transaction's commit, but does not prove backend provenance or coverage. The two prototype upper/flush gaps are 72 and 64 bytes; their bounded dump cannot find a valid record after the flush frontier, so origin and timing perturbation remain unestablished. No production adoption, forced flush, checkpoint, marker, warm-up or expiry change is authorized. The inherited CI JUnit upload repair preserves originating service XML for 14 days under merge-SHA/attempt-specific names; attribution infrastructure is not admission proof. Exact source `c16370dc158100da94b19619c23f7b1f05a11959` [Validation run 38027144761](https://github.com/benhook1013/FireMUD/actions/runs/38027144761) ended cancelled with a failed required gate. Originating Account XML records 285 executions, six failures and no skips: five production admission-confirmation WAL-coverage denials and one isolated prototype denial. Both V132 finalization cases and all three V131 observation cases pass. All ten prototype definitions execute: nine pass, including quiet cold/warm entry, while the privilege case completes its twelve denial assertions but fails the subsequent valid hostile-search-path confirmation with the flush frontier 128 bytes behind its entry upper bound despite about fourteen seconds of remaining original validity. The WAL's origin is not established. These positives are feasibility evidence, not production adoption; no warming, forced flush, marker write or deadline extension is applied to conceal the failed entry. World executes all 221 integration cases without failures or skips; Game Design is cancelled without originating XML, so no new Game Design proof is claimed. CI identifies merge `1e493b96dfc334590d96f0c3f04a77917f12891a` and the merge message's base `fe15a31f274b1c9850dd388e83faf540916ee8a3`; the tree and ordered parent objects are not independently verified. This is not recorded-parent alignment, full original-COMMIT durability proof or runtime activation. diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index 6144e19a55..d0f0fa617b 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -608,6 +608,46 @@ require_contains( "ci workflow", ) +junit_results_step = find_step( + ci, "build-and-test", "Upload JUnit Test Results", "ci workflow" +) +require_equal( + junit_results_step, + ("if",), + "always()", + "ci workflow", +) +require_equal( + junit_results_step, + ("uses",), + "actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9", + "ci workflow", +) +require_equal( + junit_results_step, + ("with", "name"), + "junit-${{ matrix.module }}-results-${{ github.sha }}-attempt-${{ github.run_attempt }}", + "ci workflow", +) +require_equal( + junit_results_step, + ("with", "path"), + "${{ matrix.module == 'load-testing' && 'dev-tools/load-testing/build/test-results/**/*.xml' || format('services/{0}/build/test-results/**/*.xml', matrix.module) }}", + "ci workflow", +) +require_equal( + junit_results_step, + ("with", "if-no-files-found"), + "warn", + "ci workflow", +) +require_equal( + junit_results_step, + ("with", "retention-days"), + "14", + "ci workflow", +) + require_equal( security, ("jobs", "changes", "permissions", "pull-requests"), diff --git a/protos/account/v1/start_session_admission_protection_acquisition.proto b/protos/account/v1/start_session_admission_protection_acquisition.proto new file mode 100644 index 0000000000..121dcbf4d6 --- /dev/null +++ b/protos/account/v1/start_session_admission_protection_acquisition.proto @@ -0,0 +1,32 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered source-protection acquisition for the original StartSession. +// It does not admit gameplay or settle/release the retained protection. +service AccountStartSessionAdmissionProtectionAcquisitionService { + rpc AcquireOriginalStartSessionAdmissionProtection( + AcquireOriginalStartSessionAdmissionProtectionRequest) + returns (AcquireOriginalStartSessionAdmissionProtectionResponse); +} + +message AcquireOriginalStartSessionAdmissionProtectionRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Exact fields of AccountStartSessionAdmissionProtectionAcquisitionService.AcquisitionRequest. + bytes original_post_authorization_tuple = 3; + string game_session_owner_mutation_id = 4; + string game_session_owner_attempt_id = 5; + int64 game_session_owner_fence = 6; + string account_world_participation_id = 7; + int64 account_world_participation_fence = 8; + bytes world_hold_identity = 9; +} + +message AcquireOriginalStartSessionAdmissionProtectionResponse { + // Complete canonical AccountStartSessionAdmissionProtectionEvidence bytes. + bytes evidence_canonical_bytes = 1; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcService.java new file mode 100644 index 0000000000..d0a71236bc --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcService.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountStartSessionAdmissionProtectionAcquisitionServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionAdmissionProtectionResponse; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionAcquisitionInput; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone unregistered receiver: authenticate exact Game Session before request decoding. */ +public final class AccountStartSessionAdmissionProtectionAcquisitionGrpcService + extends AccountStartSessionAdmissionProtectionAcquisitionServiceGrpc + .AccountStartSessionAdmissionProtectionAcquisitionServiceImplBase { + private final AccountStartSessionAdmissionProtectionAcquisitionService owner; + private final String namespace; + + public AccountStartSessionAdmissionProtectionAcquisitionGrpcService( + AccountStartSessionAdmissionProtectionAcquisitionService owner, String namespace) { + this.owner = + Objects.requireNonNull(owner, "admission protection acquisition owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void acquireOriginalStartSessionAdmissionProtection( + AcquireOriginalStartSessionAdmissionProtectionRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !expectedPeer.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() + > AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.MAX_REQUEST_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + final AccountStartSessionAdmissionProtectionAcquisitionInput input; + try { + input = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( + request, namespace); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var evidence = + owner.acquire( + new AccountStartSessionAdmissionProtectionAcquisitionService.AcquisitionRequest( + input.originalPostAuthorizationTuple(), + input.gameSessionOwnerMutationId(), + input.gameSessionOwnerAttemptId(), + input.gameSessionOwnerFence(), + input.accountWorldParticipationId(), + input.accountWorldParticipationFence(), + input.worldHoldIdentity())); + var response = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toResponse( + input, namespace, evidence); + observer.onNext(response); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.INVALID_ARGUMENT + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + observer.onError(Status.fromCode(code).asRuntimeException()); + } catch (IllegalArgumentException invalidEvidence) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/resources/db/migration/V133__start_session_admission_protection.sql b/services/account-service/src/main/resources/db/migration/V133__start_session_admission_protection.sql index 625bb03898..4cd2240051 100644 --- a/services/account-service/src/main/resources/db/migration/V133__start_session_admission_protection.sql +++ b/services/account-service/src/main/resources/db/migration/V133__start_session_admission_protection.sql @@ -47,12 +47,6 @@ CREATE TABLE account_start_session_admission_protection_settlements ( ); -- [jooq ignore start] --- PostgreSQL enforces exact retained millisecond precision; jOOQ's DDL simulator --- does not evaluate this date_trunc part. Keep the column and table visible. -ALTER TABLE account_start_session_admission_protections - ADD CONSTRAINT account_ss_admission_original_lease_millis - CHECK (original_lease_expires_at = date_trunc('milliseconds', original_lease_expires_at)); - CREATE FUNCTION account_ss_admission_is_settled(protection_value UUID) RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ SELECT EXISTS (SELECT 1 FROM account_start_session_admission_protection_settlements @@ -184,7 +178,7 @@ BEGIN OR request_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM original.game_session_owner_attempt_id::TEXT OR request_value->>'gameSessionOwnerFence' IS DISTINCT FROM original.game_session_owner_fence::TEXT OR request_value->>'originalLeaseExpiresAt' IS DISTINCT FROM - to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') + to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') OR request_value->>'accountWorldParticipationId' IS DISTINCT FROM original.account_world_participation_id::TEXT OR request_value->>'accountWorldParticipationFence' IS DISTINCT FROM original.account_world_participation_fence::TEXT OR request_value->>'worldAdmissionHoldIdentityBytesBase64' IS DISTINCT FROM regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') THEN @@ -198,7 +192,7 @@ BEGIN OR EXISTS (SELECT 1 FROM jsonb_each(hold_value) field WHERE jsonb_typeof(field.value) <> 'string') OR (hold_value->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID OR (hold_value->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID - OR hold_value->>'holdBindingDigest' IS DISTINCT FROM encode(sha256(decode(hold_value->>'requestBytesBase64', 'base64')), 'hex') + OR hold_value->>'holdBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(hold_value->>'requestBytesBase64', 'base64')), 'hex') OR hold_request->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' OR hold_request->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace OR hold_request->'request'->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index d194bcd05e..3ca848953b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -9,7 +9,6 @@ import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; -import java.time.temporal.ChronoUnit; import java.util.Base64; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -88,6 +87,7 @@ void installsAdditiveHooksWithoutRemovingExistingOwnerChecks() { @Test void exactCurrentReadPreservesIdentityWithoutAllocatingAndWorldCommitCannotReleaseIt() { Fixture fixture = fixture(); + assertThat(fixture.expiry().getNano() % 1_000_000).isNotZero(); acquire(fixture); Long sequence = sequenceValue(fixture); for (int retry = 0; retry < 2; retry++) { @@ -106,6 +106,10 @@ void exactCurrentReadPreservesIdentityWithoutAllocatingAndWorldCommitCannotRelea assertThat(current.get("protection_id", UUID.class)).isEqualTo(fixture.protectionId()); assertThat(current.get("request_binding_bytes", byte[].class)) .containsExactly(fixture.request()); + OffsetDateTime retainedExpiry = + current.get("original_lease_expires_at", OffsetDateTime.class); + assertThat(retainedExpiry).isNotNull(); + assertThat(retainedExpiry.toInstant()).isEqualTo(fixture.expiry().toInstant()); } assertThat(sequenceValue(fixture)).isEqualTo(sequence); assertThat( @@ -130,6 +134,89 @@ void exactCurrentReadPreservesIdentityWithoutAllocatingAndWorldCommitCannotRelea .hasMessageContaining("Original StartSession admission protection remains pending"); } + @Test + void changedSubmillisecondOriginalExpiryCannotRecoverRetainedProtection() { + Fixture fixture = fixture(); + acquire(fixture); + var storedRowBefore = + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_start_session_admission_protections WHERE protection_id = ?", + fixture.protectionId()); + DateTimeFormatter expiryFormat = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC); + String originalExpiryText = expiryFormat.format(fixture.expiry().toInstant()); + String changedExpiryText = expiryFormat.format(fixture.expiry().plusNanos(1_000).toInstant()); + byte[] changedRequest = + new String(fixture.request(), StandardCharsets.UTF_8) + .replace(originalExpiryText, changedExpiryText) + .getBytes(StandardCharsets.UTF_8); + assertThat(changedRequest).isNotEqualTo(fixture.request()); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + changedRequest))) + .hasMessageContaining("Original admission recovery binding differs"); + var storedRowAfter = + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_start_session_admission_protections WHERE protection_id = ?", + fixture.protectionId()); + assertThat(storedRowAfter).isEqualTo(storedRowBefore); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT account_ss_admission_is_settled(?)", fixture.protectionId()) + .get(0, Boolean.class)) + .isFalse(); + } + + @Test + void forgedWorldHoldDigestWithoutCanonicalPrefixCannotBecomeProtection() { + Fixture fixture = fixture(); + String holdText = new String(fixture.hold(), StandardCharsets.UTF_8); + String digestMarker = "\"holdBindingDigest\":\""; + int digestStart = holdText.indexOf(digestMarker) + digestMarker.length(); + int digestEnd = holdText.indexOf('"', digestStart); + String validDigest = holdText.substring(digestStart, digestEnd); + assertThat(validDigest).startsWith("sha256:"); + String forgedHoldText = + holdText.substring(0, digestStart) + + validDigest.substring("sha256:".length()) + + holdText.substring(digestEnd); + byte[] forgedHold = forgedHoldText.getBytes(StandardCharsets.UTF_8); + byte[] forgedRequest = + new String(fixture.request(), StandardCharsets.UTF_8) + .replace(base64(fixture.hold()), base64(forgedHold)) + .getBytes(StandardCharsets.UTF_8); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> insertProtection(fixture, 11L, forgedHold, forgedRequest))) + .hasMessageContaining("Admission hold identity differs from original instance and request"); + assertThat( + fixture + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); + } + @Test void pendingAdmissionExcludesRealSourceChangeCompletionAndDisclosureDispatch() { Fixture fixture = fixture(); @@ -397,6 +484,11 @@ private static void acquire(Fixture fixture) { } private static void insertProtection(Fixture fixture, long version) { + insertProtection(fixture, version, fixture.hold(), fixture.request()); + } + + private static void insertProtection( + Fixture fixture, long version, byte[] holdIdentity, byte[] request) { insert( fixture.dsl(), "account_start_session_admission_protections", @@ -433,11 +525,11 @@ private static void insertProtection(Fixture fixture, long version) { "capture_sha256", hash(bytes("{}")), "world_admission_hold_identity_bytes", - fixture.hold(), + holdIdentity, "request_binding_bytes", - fixture.request(), + request, "request_binding_digest", - "sha256:" + hash(fixture.request())); + "sha256:" + hash(request)); } private static Fixture fixture() { @@ -463,9 +555,9 @@ private static Fixture fixture(long leaseMillis) { new TransactionTemplate(new DataSourceTransactionManager(source)); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); OffsetDateTime now = - dsl.fetchSingle("SELECT clock_timestamp()") - .get(0, OffsetDateTime.class) - .truncatedTo(ChronoUnit.MILLIS); + dsl.fetchSingle( + "SELECT date_trunc('milliseconds', clock_timestamp()) + INTERVAL '123 microseconds'") + .get(0, OffsetDateTime.class); UUID tenant = UUID.randomUUID(); UUID instance = UUID.randomUUID(); UUID actor = UUID.randomUUID(); @@ -540,7 +632,7 @@ private static Fixture fixture(long leaseMillis) { "gameSessionOwnerFence", "47", "originalLeaseExpiresAt", - DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'") + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") .withZone(ZoneOffset.UTC) .format(expiry.toInstant()), "accountWorldParticipationId", diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java new file mode 100644 index 0000000000..d62b3be263 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java @@ -0,0 +1,1023 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.Candidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiOriginalOrderFixture.IssuedCreator; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.Snapshot; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionException; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; +import tools.jackson.databind.json.JsonMapper; + +/** + * PostgreSQL proof that the real Account issuer, signed actor, original capture, redemption, + * currentness callback, World participation and V133 producer compose into admission protection. + * Logging claim evidence, the Game Session current-attempt client, and World hold/terminal values + * are stipulated test collaborators. This proves no genuine upstream producer, authenticated + * cross-service transport, Game Session terminal settlement, runtime registration, or activation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest { + private static final String NAMESPACE = "control-ui-owner-proof"; + private static final String LOGGING_PEER_URI = + "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; + private static final String GAME_SESSION_PEER_URI = + "spiffe://firemud/ns/control-ui-owner-proof/sa/game-session-service"; + private static final String WORLD_PEER_URI = + "spiffe://firemud/ns/control-ui-owner-proof/sa/world-management-service"; + private static final long ORIGINAL_GAME_TEMPLATE_ID = 42L; + private static final long GAME_SESSION_OWNER_FENCE = 47L; + private static final long WORLD_EXECUTION_FENCE = 73L; + private static final String WORLD_SLUG = "owner-proof-world"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(DockerImageName.parse("postgres:16-alpine")); + + @Container + static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("admission-protection-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer REDIS_REPLICA = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(REDIS) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "admission-protection-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void realAccountAcquisitionAndExactRetryPreserveProtectionCaptureAndFiniteLease() + throws Exception { + try (Prepared prepared = prepare(Duration.ofSeconds(90))) { + var service = prepared.acquisitionService(prepared.account.manager); + + AccountStartSessionAdmissionProtectionEvidence first = prepared.acquire(service); + assertProtectionRow(prepared, first); + assertThat(first.accountProtectionId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(first.accountProtectionFence()).isPositive(); + assertThat(first.request().originalLeaseExpiresAt()) + .isEqualTo(prepared.originalObservation.originalLeaseExpiresAt()); + assertThat(first.originalSourceCaptureReferenceBytes()) + .containsExactly(prepared.capture.canonicalBytes()); + assertThat(first.originalSourceCaptureReferenceSha256()) + .isEqualTo(prepared.capture.canonicalSha256()); + assertThat(encoded(first.sourceEvidenceVector())) + .containsExactlyElementsOf(encoded(prepared.participation.sources())); + + AccountStartSessionAdmissionProtectionEvidence exactRetry = prepared.acquire(service); + assertThat(exactRetry.accountProtectionId()).isEqualTo(first.accountProtectionId()); + assertThat(exactRetry.accountProtectionFence()).isEqualTo(first.accountProtectionFence()); + assertThat(exactRetry.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(exactRetry.request().originalLeaseExpiresAt()) + .isEqualTo(first.request().originalLeaseExpiresAt()); + assertThat(encoded(exactRetry.sourceEvidenceVector())) + .containsExactlyElementsOf(encoded(first.sourceEvidenceVector())); + assertThat(rowCount(prepared.account.dsl, "account_start_session_admission_protections")) + .isEqualTo(1L); + assertThat(prepared.reads).hasSize(2); + assertThat(prepared.reads.get(0).readRequestId()) + .isNotEqualTo(prepared.reads.get(1).readRequestId()); + } + } + + @Test + void lostIndependentReadbackAcknowledgementRetriesTheCommittedProtectionExactly() + throws Exception { + try (Prepared prepared = prepare(Duration.ofSeconds(90))) { + var readbackManager = new CommitThenLoseOneAcknowledgement(prepared.account.manager); + var service = prepared.acquisitionService(readbackManager); + + assertThatThrownBy(() -> prepared.acquire(service)) + .isInstanceOf(LostReadbackAcknowledgement.class); + Record committed = protectionRow(prepared); + byte[] committedRequest = committed.get("request_binding_bytes", byte[].class); + UUID committedId = committed.get("protection_id", UUID.class); + Long committedFence = committed.get("protection_fence", Long.class); + OffsetDateTime committedExpiry = + committed.get("original_lease_expires_at", OffsetDateTime.class); + assertThat(committedId).isNotNull(); + assertThat(committedFence).isNotNull().isPositive(); + assertThat(committedExpiry).isNotNull(); + assertThat(readbackManager.didLoseAcknowledgement()).isTrue(); + assertThat(rowCount(prepared.account.dsl, "account_start_session_admission_protections")) + .isEqualTo(1L); + + AccountStartSessionAdmissionProtectionEvidence committedReadback = + readCurrentProtection(prepared); + assertProtectionRow(prepared, committedReadback); + + AccountStartSessionAdmissionProtectionEvidence retry = prepared.acquire(service); + assertThat(retry.accountProtectionId()).isEqualTo(committedId); + assertThat(retry.accountProtectionFence()).isEqualTo(committedFence); + assertThat(retry.canonicalBytes()).containsExactly(committedReadback.canonicalBytes()); + assertThat(retry.request().canonicalBytes()).containsExactly(committedRequest); + assertThat(retry.request().originalLeaseExpiresAt()).isEqualTo(committedExpiry.toInstant()); + assertThat(encoded(retry.sourceEvidenceVector())) + .containsExactlyElementsOf(encoded(prepared.participation.sources())); + assertProtectionRow(prepared, retry); + assertThat(rowCount(prepared.account.dsl, "account_start_session_admission_protections")) + .isEqualTo(1L); + assertThat(prepared.reads).hasSize(2); + assertThat(prepared.reads.get(0).readRequestId()) + .isNotEqualTo(prepared.reads.get(1).readRequestId()); + } + } + + @Test + void changedRealAccountSourceAfterSettledWorldGapDeniesWithoutAdmissionInsert() throws Exception { + try (Prepared prepared = prepare(Duration.ofSeconds(90))) { + prepared.settleWorldWithStipulatedTerminal(); + Account changed = prepared.account.tx(prepared.account::changeRoleToAdmin); + assertThat(changed.getRole()).isEqualTo("admin"); + + assertThatThrownBy( + () -> prepared.acquire(prepared.acquisitionService(prepared.account.manager))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact current authenticated initial creator required"); + + assertThat(rowCount(prepared.account.dsl, "account_start_session_admission_protections")) + .isZero(); + assertThat( + rowCount(prepared.account.dsl, "account_start_session_admission_protection_sources")) + .isZero(); + verify(prepared.gameSessionClient, times(1)).read(any(Request.class)); + } + } + + @Test + void settledWorldAndExpiredOriginalLeaseDoNotReleasePendingAccountSourceProtection() + throws Exception { + try (Prepared prepared = prepare(Duration.ofSeconds(10))) { + AccountStartSessionAdmissionProtectionEvidence protection = + prepared.acquire(prepared.acquisitionService(prepared.account.manager)); + assertProtectionRow(prepared, protection); + + WorldStartSessionExecutionTerminal stipulatedTerminal = terminal(prepared.participation); + prepared.settleWorldWithStipulatedTerminal(); + var worldSettlement = + prepared.account.tx( + () -> + prepared + .participationRepository + .findSettlementExact( + prepared.participation.participationId(), + prepared.participation.participationFence()) + .orElseThrow()); + assertThat(worldSettlement.outcome()) + .isEqualTo(WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + assertThat(worldSettlement.terminalBytes()) + .containsExactly(stipulatedTerminal.canonicalBytes()); + assertThat(worldSettlement.terminalDigest()).isEqualTo(stipulatedTerminal.digest()); + + Instant originalLeaseExpiry = protection.request().originalLeaseExpiresAt(); + awaitDatabaseTime( + prepared.account.dsl, originalLeaseExpiry.plusMillis(100), Duration.ofSeconds(15)); + assertThat(databaseNow(prepared.account.dsl)).isAfter(originalLeaseExpiry); + + String roleBefore = + prepared + .account + .accounts + .findById(prepared.account.account.getId()) + .orElseThrow() + .getRole(); + List authorityGenerationsBefore = authorityGenerationSnapshot(prepared.account.dsl); + assertThatThrownBy(() -> prepared.account.tx(prepared.account::changeRoleToAdmin)) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) rootCause = rootCause.getCause(); + assertThat(rootCause) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + postgresFailure -> { + assertThat(postgresFailure.getSQLState()).isEqualTo("55P03"); + var serverError = postgresFailure.getServerErrorMessage(); + if (serverError == null) { + throw new AssertionError( + "Pending-source denial lacks PostgreSQL server evidence"); + } + assertThat(serverError.getMessage()) + .isEqualTo( + "Original StartSession admission protection remains pending " + + "for a required source"); + }); + }); + + assertThat( + prepared + .account + .accounts + .findById(prepared.account.account.getId()) + .orElseThrow() + .getRole()) + .isEqualTo(roleBefore); + assertThat(authorityGenerationSnapshot(prepared.account.dsl)) + .containsExactlyElementsOf(authorityGenerationsBefore); + assertProtectionRow(prepared, protection); + assertThat( + rowCount( + prepared.account.dsl, "account_start_session_admission_protection_settlements")) + .isZero(); + } + } + + @Test + void leaseExpiryDuringRealOriginalActorIssuanceLockWaitDeniesDespiteTimelyRemoteRead() + throws Exception { + try (Prepared prepared = prepare(Duration.ofSeconds(10))) { + Instant leaseExpiry = prepared.originalObservation.originalLeaseExpiresAt(); + UUID controlUiOperationId = + prepared + .account + .dsl + .fetchSingle( + "SELECT control_ui_operation_id FROM account_start_session_authority_captures " + + "WHERE control_plane_request_id = ?", + prepared.originalTuple.controlPlaneRequestId()) + .get("control_ui_operation_id", UUID.class); + assertThat(controlUiOperationId).isNotNull(); + + CountDownLatch issuanceRowLocked = new CountDownLatch(1); + CountDownLatch releaseIssuanceRow = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var lockHolder = + executor.submit( + () -> + prepared.account.tx( + () -> { + prepared.account.dsl.fetchSingle( + "SELECT operation_id FROM account_control_ui_issuance_operations " + + "WHERE operation_id = ? FOR UPDATE", + controlUiOperationId); + issuanceRowLocked.countDown(); + awaitLatch(releaseIssuanceRow); + return null; + })); + assertThat(issuanceRowLocked.await(10, TimeUnit.SECONDS)).isTrue(); + + var service = prepared.acquisitionService(prepared.account.manager); + var acquisition = executor.submit(() -> prepared.acquire(service)); + assertThat(prepared.remoteRead.await(10, TimeUnit.SECONDS)).isTrue(); + Instant remoteReadAt = prepared.remoteReadAt.get(); + assertThat(remoteReadAt).isNotNull().isBefore(leaseExpiry); + + awaitDatabaseTime( + prepared.account.dsl, leaseExpiry.plusMillis(100), Duration.ofSeconds(15)); + Instant afterLeaseExpiry = databaseNow(prepared.account.dsl); + Record originalAuthorization = + prepared.account.dsl.fetchSingle( + "SELECT reference_expires_at FROM account_start_session_operator_authorizations " + + "WHERE control_plane_request_id = ?", + prepared.originalTuple.controlPlaneRequestId()); + OffsetDateTime referenceExpiry = + originalAuthorization.get("reference_expires_at", OffsetDateTime.class); + assertThat(afterLeaseExpiry).isAfterOrEqualTo(leaseExpiry); + assertThat(referenceExpiry) + .isNotNull() + .satisfies(value -> assertThat(value.toInstant()).isAfter(afterLeaseExpiry)); + + releaseIssuanceRow.countDown(); + ExecutionException acquisitionFailure; + try { + acquisition.get(20, TimeUnit.SECONDS); + throw new AssertionError( + "Expired original admission lease unexpectedly acquired protection"); + } catch (ExecutionException failure) { + acquisitionFailure = failure; + } + Throwable rootCause = acquisitionFailure; + while (rootCause.getCause() != null) rootCause = rootCause.getCause(); + assertThat(rootCause) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + postgresFailure -> { + assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); + var serverError = postgresFailure.getServerErrorMessage(); + if (serverError == null) { + throw new AssertionError("Expiry denial lacks PostgreSQL server evidence"); + } + assertThat(serverError.getMessage()) + .isEqualTo("Original StartSession admission protection is not current"); + }); + lockHolder.get(10, TimeUnit.SECONDS); + } finally { + releaseIssuanceRow.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + + assertThat(rowCount(prepared.account.dsl, "account_start_session_admission_protections")) + .isZero(); + assertThat( + rowCount(prepared.account.dsl, "account_start_session_admission_protection_sources")) + .isZero(); + assertThat(prepared.reads).hasSize(1); + } + } + + private Prepared prepare(Duration observationLease) throws Exception { + var controlUi = + new AccountControlUiOriginalOrderFixture( + POSTGRES.getJdbcUrl(), + POSTGRES.getUsername(), + POSTGRES.getPassword(), + REDIS.getHost(), + REDIS.getMappedPort(6379), + temporary); + try { + IssuedCreator creator = controlUi.issueCreator(); + var account = creator.sources(); + var tupleId = "admission-protection-" + UUID.randomUUID(); + UUID reservationOwnerId = UUID.randomUUID(); + long reservationClaimFence = 31L; + UUID gameSessionAttemptId = UUID.randomUUID(); + UUID gameSessionMutationId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + String preparationJson = + preparationInput(NAMESPACE, account.tenant, tupleId, gameInstanceId, WORLD_SLUG); + String preparationDigest = digest(preparationJson); + + var preAuthorizationTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + tupleId, + account.account.getAccountUuid(), + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(account.tenant, NAMESPACE), + new StartSessionOperatorAction.Target( + ORIGINAL_GAME_TEMPLATE_ID, account.account.getAccountUuid()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "test-only Account admission protection producer proof")); + + var claimClient = mock(StartSessionReservationEvidenceClient.class); + Instant claimNow = Instant.now(); + var claim = + ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(preAuthorizationTuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + com.google.protobuf.ByteString.copyFrom( + preAuthorizationTuple.canonicalJson(), StandardCharsets.UTF_8)) + .setMutationDigest(preAuthorizationTuple.mutationDigest()) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setClaimOwnerId(reservationOwnerId.toString()) + .setClaimFence(reservationClaimFence) + .setObservedAtEpochMillis(claimNow.minusSeconds(1).toEpochMilli()) + .setClaimExpiresAtEpochMillis(claimNow.plus(Duration.ofMinutes(5)).toEpochMilli()) + .setPurpose( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) + .build(); + when(claimClient.readCurrentClaimEvidence( + preAuthorizationTuple, + reservationOwnerId, + reservationClaimFence, + reservationOwnerId, + reservationClaimFence, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .thenReturn(claim); + + var operatorRepository = new AccountStartSessionOperatorAuthorizationRepository(account.dsl); + var captureRepository = new AccountStartSessionAuthorityCaptureRepository(account.dsl); + var operatorAuthorization = + new AccountStartSessionOperatorAuthorizationService( + creator.actors(), + new AccountControlUiIssuanceRepository(account.dsl), + captureRepository, + claimClient, + operatorRepository, + fingerprintKeys(), + responseCryptography(temporary), + account.terms, + account.manager, + Clock.systemUTC(), + new SecureRandom(), + LOGGING_PEER_URI, + GAME_SESSION_PEER_URI, + Duration.ofMinutes(2), + Duration.ofSeconds(30)); + + var authorization = + withPeer( + LOGGING_PEER_URI, + () -> + operatorAuthorization.issue( + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + creator.compact(), + preAuthorizationTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + reservationOwnerId, + reservationClaimFence, + reservationOwnerId, + reservationClaimFence))); + var originalTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preAuthorizationTuple, + LOGGING_PEER_URI, + authorization.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + authorization.authorityEvidenceBundle(), + new BundleReference( + authorization.bundleReference().bundleVersion(), + authorization.bundleReference().sourceVersion(), + authorization.bundleReference().sourceFence(), + authorization.bundleReference().linearization())); + + withPeer( + GAME_SESSION_PEER_URI, + () -> + operatorAuthorization.redeem( + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + preAuthorizationTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + authorization.operatorAuthorizationReference(), + authorization.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + gameSessionAttemptId, + GAME_SESSION_OWNER_FENCE))); + + Instant unadjustedLeaseExpiry = + databaseNow(account.dsl).truncatedTo(ChronoUnit.MICROS).plus(observationLease); + long nanosWithinMillisecond = unadjustedLeaseExpiry.getNano() % 1_000_000L; + final Instant leaseExpiry = + unadjustedLeaseExpiry.plusNanos(456_000L - nanosWithinMillisecond); + byte[] projection = StartSessionAccountRedemptionProjection.fromOriginalTuple(originalTuple); + var originalObservationRequest = + new Request( + UUID.randomUUID(), + NAMESPACE, + originalTuple.canonicalBytes(), + gameSessionAttemptId, + gameSessionMutationId, + GAME_SESSION_OWNER_FENCE); + var originalObservation = new Result(originalObservationRequest, leaseExpiry, projection); + + var participationRepository = + new AccountStartSessionWorldParticipationRepository(account.dsl); + var attemptEvidenceRepository = + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(account.dsl); + var capture = new AtomicReference(); + var participation = + withWorldCurrentness( + operatorAuthorization, + originalTuple, + gameSessionAttemptId, + GAME_SESSION_OWNER_FENCE, + currentCapture -> { + capture.set(currentCapture); + var candidate = + new Candidate( + originalTuple, + currentCapture, + gameInstanceId, + gameSessionAttemptId, + GAME_SESSION_OWNER_FENCE, + preparationJson, + preparationDigest); + StoredParticipation stored = participationRepository.createOrReadExact(candidate); + attemptEvidenceRepository.retainCurrentExact(stored, originalObservation); + return stored; + }); + + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + account.tenant, + WORLD_SLUG, + UUID.randomUUID(), + UUID.randomUUID(), + "SHARED", + gameInstanceId, + UUID.randomUUID(), + 1L, + "initial-admission-" + UUID.randomUUID(), + sha256Hex("stipulated-world-admission-request".getBytes(StandardCharsets.UTF_8)), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + var holdIdentity = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, UUID.randomUUID(), UUID.randomUUID()); + var acquisitionRequest = + new AccountStartSessionAdmissionProtectionAcquisitionService.AcquisitionRequest( + originalTuple.canonicalBytes(), + gameSessionMutationId, + gameSessionAttemptId, + GAME_SESSION_OWNER_FENCE, + participation.participationId(), + participation.participationFence(), + holdIdentity); + + var gameSessionClient = mock(OriginalStartSessionCurrentAttemptClient.class); + var reads = new java.util.concurrent.CopyOnWriteArrayList(); + var remoteRead = new CountDownLatch(1); + var remoteReadAt = new AtomicReference(); + when(gameSessionClient.read(any(Request.class))) + .thenAnswer( + invocation -> { + Request request = invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + reads.add(request); + remoteReadAt.set(databaseNow(account.dsl)); + remoteRead.countDown(); + return new Result(request, leaseExpiry, projection); + }); + + return new Prepared( + controlUi, + creator, + account, + operatorAuthorization, + originalTuple, + capture.get(), + participationRepository, + attemptEvidenceRepository, + participation, + gameSessionMutationId, + gameSessionAttemptId, + originalObservation, + acquisitionRequest, + gameSessionClient, + reads, + remoteRead, + remoteReadAt); + } catch (Exception | Error failure) { + controlUi.close(); + throw failure; + } + } + + private static void assertProtectionRow( + Prepared prepared, AccountStartSessionAdmissionProtectionEvidence evidence) { + Record row = protectionRow(prepared); + assertThat(row.get("protection_id", UUID.class)).isEqualTo(evidence.accountProtectionId()); + assertThat(row.get("protection_fence", Long.class)) + .isEqualTo(evidence.accountProtectionFence()); + assertThat(row.get("original_post_authorization_tuple", byte[].class)) + .containsExactly(prepared.originalTuple.canonicalBytes()); + assertThat(row.get("account_redemption_projection", byte[].class)) + .containsExactly( + StartSessionAccountRedemptionProjection.fromOriginalTuple(prepared.originalTuple)); + OffsetDateTime storedLeaseExpiry = row.get("original_lease_expires_at", OffsetDateTime.class); + Instant originalLeaseExpiry = prepared.originalObservation.originalLeaseExpiresAt(); + assertThat(evidence.request().originalLeaseExpiresAt()).isEqualTo(originalLeaseExpiry); + assertThat(storedLeaseExpiry.toInstant()).isEqualTo(originalLeaseExpiry); + assertThat(storedLeaseExpiry.getNano() % 1_000).isZero(); + assertThat(storedLeaseExpiry.getNano() % 1_000_000).isEqualTo(456_000); + Record retainedObservation = + prepared.account.dsl.fetchSingle( + "SELECT original_lease_expires_at " + + "FROM account_start_session_world_original_attempt_evidence " + + "WHERE participation_id = ?", + prepared.participation.participationId()); + assertThat( + retainedObservation.get("original_lease_expires_at", OffsetDateTime.class).toInstant()) + .isEqualTo(originalLeaseExpiry); + assertThat(row.get("account_world_participation_id", UUID.class)) + .isEqualTo(prepared.participation.participationId()); + assertThat(row.get("account_world_participation_fence", Long.class)) + .isEqualTo(prepared.participation.participationFence()); + assertThat(row.get("request_binding_bytes", byte[].class)) + .containsExactly(evidence.request().canonicalBytes()); + assertThat(row.get("producer_xid", Long.class)).isNotNull().isPositive(); + + List sourceRows = + prepared.account.dsl.fetch( + "SELECT source_key, source_evidence FROM " + + "account_start_session_admission_protection_sources " + + "WHERE protection_id = ? ORDER BY source_key", + evidence.accountProtectionId()); + assertThat(sourceRows).hasSize(prepared.captureSources().size()); + assertThat( + sourceRows.stream() + .map( + rowValue -> + Base64.getEncoder() + .encodeToString(rowValue.get("source_evidence", byte[].class)))) + .containsExactlyElementsOf( + prepared.captureSources().stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()); + assertThat(encoded(evidence.sourceEvidenceVector())) + .containsExactlyElementsOf(encoded(prepared.captureSources())); + } + + private static Record protectionRow(Prepared prepared) { + return prepared.account.dsl.fetchSingle( + "SELECT * FROM account_start_session_admission_protections " + + "WHERE control_plane_request_id = ?", + prepared.originalTuple.controlPlaneRequestId()); + } + + private static AccountStartSessionAdmissionProtectionEvidence readCurrentProtection( + Prepared prepared) { + var request = + AccountStartSessionAdmissionProtectionRequest.create( + prepared.originalTuple.canonicalBytes(), + prepared.originalObservation.accountRedemptionProjection(), + prepared.gameSessionMutationId, + prepared.gameSessionAttemptId, + GAME_SESSION_OWNER_FENCE, + prepared.originalObservation.originalLeaseExpiresAt(), + prepared.participation.participationId(), + prepared.participation.participationFence(), + prepared.acquisitionRequest.worldHoldIdentity()); + var repository = new AccountStartSessionAdmissionProtectionRepository(prepared.account.dsl); + return prepared.account.tx( + () -> + repository + .findCurrentExact(request) + .orElseThrow( + () -> new IllegalStateException("Committed protection readback missing"))); + } + + private static long rowCount(DSLContext dsl, String table) { + return dsl.fetchSingle("SELECT count(*)::bigint AS row_count FROM " + table) + .get("row_count", Long.class); + } + + private static List authorityGenerationSnapshot(DSLContext dsl) { + return dsl + .fetch( + "SELECT scope_kind || '|' || COALESCE(issuer_id, '') || '|' " + + "|| COALESCE(account_uuid::TEXT, '') || '|' " + + "|| COALESCE(tenant_uuid::TEXT, '') || '|' " + + "|| generation::TEXT || '|' || source_version::TEXT AS generation_state " + + "FROM account_authority_generations " + + "ORDER BY scope_kind, issuer_id NULLS FIRST, account_uuid NULLS FIRST, " + + "tenant_uuid NULLS FIRST") + .stream() + .map(row -> row.get("generation_state", String.class)) + .toList(); + } + + private static List encoded(List sources) { + return sources.stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList(); + } + + private static T withWorldCurrentness( + AccountStartSessionOperatorAuthorizationService issuer, + StartSessionPostAuthorizationExecutionTuple originalTuple, + UUID gameSessionAttemptId, + long gameSessionOwnerFence, + Function callback) { + try (var ignored = AccountControlUiOwnerSourcesFixture.withPeer(WORLD_PEER_URI)) { + return issuer.withCurrentWorldReceivingParticipationCurrentness( + originalTuple.canonicalBytes(), gameSessionAttemptId, gameSessionOwnerFence, callback); + } + } + + private static T withPeer(String peerUri, java.util.concurrent.Callable action) { + try (var ignored = AccountControlUiOwnerSourcesFixture.withPeer(peerUri)) { + return action.call(); + } catch (RuntimeException failure) { + throw failure; + } catch (Exception failure) { + throw new IllegalStateException("Test peer-scoped Account action failed", failure); + } + } + + private static AccountStartSessionAdmissionProtectionEvidence acquire( + Prepared prepared, AccountStartSessionAdmissionProtectionAcquisitionService service) { + return withPeer(GAME_SESSION_PEER_URI, () -> service.acquire(prepared.acquisitionRequest)); + } + + private static void awaitDatabaseTime(DSLContext dsl, Instant deadline, Duration timeout) + throws InterruptedException { + long stopAt = System.nanoTime() + timeout.toNanos(); + while (databaseNow(dsl).isBefore(deadline)) { + if (System.nanoTime() >= stopAt) { + throw new IllegalStateException("Database clock did not reach the original lease expiry"); + } + TimeUnit.MILLISECONDS.sleep(20); + } + } + + private static Instant databaseNow(DSLContext dsl) { + Record row = dsl.fetchSingle("SELECT clock_timestamp() AS database_now"); + OffsetDateTime value = row.get("database_now", OffsetDateTime.class); + return value.toInstant(); + } + + private static void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to release the Account issuance row"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while holding the Account issuance row", interrupted); + } + } + + private static String preparationInput( + String namespace, UUID tenantId, String requestId, UUID gameInstanceId, String worldSlug) + throws Exception { + String descriptorJson = + JSON.writeValueAsString(Map.of("gameTemplateId", ORIGINAL_GAME_TEMPLATE_ID)); + return JSON.writeValueAsString( + Map.of( + "schemaVersion", + 1, + "identity", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug), + "gameSessionReadRequest", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug), + "gameSessionReadEvidence", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + worldSlug, + "descriptorJson", + descriptorJson), + "launchBinding", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "worldSlug", + worldSlug))); + } + + private static String digest(String value) { + return "sha256:" + sha256Hex(value.getBytes(StandardCharsets.UTF_8)); + } + + private static String sha256Hex(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + + private static AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys() { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) 0x51); + return new AccountOperatorAuthorizationFingerprintKeyring( + () -> + new Snapshot( + new KeyMaterial("test-active", new SecretKeySpec(key, "HmacSHA256")), List.of()), + Clock.systemUTC(), + Duration.ofMinutes(2)); + } + + private static AccountResponseEnvelopeCryptography responseCryptography(Path temporary) + throws Exception { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) 0x26); + Path root = Files.createDirectories(temporary.resolve("operator-response-envelope")); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive test-response " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n"); + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(root.toString()), Clock.systemUTC(), new SecureRandom()); + } + + private static WorldStartSessionExecutionTerminal terminal(StoredParticipation participation) { + return new WorldStartSessionExecutionTerminal( + participation.originalPostAuthorizationTuple(), + participation.participationId(), + participation.participationFence(), + participation.gameSessionOwnerAttemptId(), + participation.gameSessionOwnerFence(), + participation.targetNamespace(), + participation.canonicalTenantId(), + participation.controlPlaneRequestId(), + participation.canonicalGameInstanceId(), + participation.preparationInputDigest(), + participation.preparationInputJson(), + WORLD_EXECUTION_FENCE, + WorldStartSessionExecutionTerminal.Outcome.COMMITTED); + } + + private record Prepared( + AccountControlUiOriginalOrderFixture controlUi, + IssuedCreator creator, + AccountControlUiOwnerSourcesFixture account, + AccountStartSessionOperatorAuthorizationService operatorAuthorization, + StartSessionPostAuthorizationExecutionTuple originalTuple, + AccountStartSessionAuthorityCapture capture, + AccountStartSessionWorldParticipationRepository participationRepository, + AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptEvidenceRepository, + StoredParticipation participation, + UUID gameSessionMutationId, + UUID gameSessionAttemptId, + Result originalObservation, + AccountStartSessionAdmissionProtectionAcquisitionService.AcquisitionRequest + acquisitionRequest, + OriginalStartSessionCurrentAttemptClient gameSessionClient, + List reads, + CountDownLatch remoteRead, + AtomicReference remoteReadAt) + implements AutoCloseable { + AccountStartSessionAdmissionProtectionAcquisitionService acquisitionService( + PlatformTransactionManager readbackManager) { + return new AccountStartSessionAdmissionProtectionAcquisitionService( + operatorAuthorization, + participationRepository, + attemptEvidenceRepository, + new AccountStartSessionAdmissionProtectionRepository(account.dsl), + gameSessionClient, + readbackManager, + NAMESPACE); + } + + AccountStartSessionAdmissionProtectionEvidence acquire( + AccountStartSessionAdmissionProtectionAcquisitionService service) { + return AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.acquire( + this, service); + } + + List captureSources() { + return participation.sources(); + } + + void settleWorldWithStipulatedTerminal() { + account.tx(() -> participationRepository.settleExact(terminal(participation))); + } + + @Override + public void close() { + controlUi.close(); + } + } + + private static final class CommitThenLoseOneAcknowledgement + implements PlatformTransactionManager { + private final PlatformTransactionManager delegate; + private final AtomicBoolean loseNextCommit = new AtomicBoolean(true); + private final AtomicBoolean lostAcknowledgement = new AtomicBoolean(); + + private CommitThenLoseOneAcknowledgement(PlatformTransactionManager delegate) { + this.delegate = delegate; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) + throws TransactionException { + return delegate.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) throws TransactionException { + delegate.commit(status); + if (loseNextCommit.compareAndSet(true, false)) { + lostAcknowledgement.set(true); + throw new LostReadbackAcknowledgement(); + } + } + + @Override + public void rollback(TransactionStatus status) throws TransactionException { + delegate.rollback(status); + } + + boolean didLoseAcknowledgement() { + return lostAcknowledgement.get(); + } + } + + private static final class LostReadbackAcknowledgement extends RuntimeException { + private static final long serialVersionUID = 1L; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java new file mode 100644 index 0000000000..ca6715cc29 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java @@ -0,0 +1,734 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +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.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountStartSessionAdmissionProtectionAcquisitionServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionAdmissionProtectionResponse; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAdmissionProtectionAcquisitionGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAdmissionProtectionAcquisitionService; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionAcquisitionGrpcClient; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionAcquisitionInput; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +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.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.test.TlsTestSupport; +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.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Physical loopback mTLS proof for the unregistered Account admission-protection receiver. */ +class AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest { + private static final String NAMESPACE = "world-runtime"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/world-runtime/sa/account-service"; + private static final String GAME_SESSION_URI = + "spiffe://firemud/ns/world-runtime/sa/game-session-service"; + private static final String WRONG_SERVICE_URI = + "spiffe://firemud/ns/world-runtime/sa/world-management-service"; + private static final String OTHER_NAMESPACE_URI = + "spiffe://firemud/ns/other-runtime/sa/game-session-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID MUTATION = uuid("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"); + private static final UUID ATTEMPT = uuid("ec13cc04-ec15-4eb8-a018-c2c5e8da65f8"); + private static final UUID PARTICIPATION = uuid("47b3be7f-a32f-4e19-8916-8c3b8da07a82"); + private static final UUID HOLD_ID = uuid("0db7344a-1e67-4b95-905a-83dc9c472f0c"); + private static final UUID HOLD_FENCE = uuid("52a14272-f9e4-4f67-97c9-62247b5fbcc1"); + private static final UUID PROTECTION_ID = uuid("6b763f1d-c5bc-4080-b499-d29debc0a7b8"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir static Path temporaryDirectory; + + private static TestPki pki; + + @BeforeAll + static void generateTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactSameNamespaceGameSessionPeerAcquiresCompleteEvidenceWithTheCommonClient() + throws Exception { + var input = input(); + var expectedEvidence = evidence(input); + var owner = mock(AccountStartSessionAdmissionProtectionAcquisitionService.class); + when(owner.acquire(any())).thenReturn(expectedEvidence); + try (TransportServer server = startServer(owner, false); + var client = newClient(server.port(), pki.gameSessionClient())) { + client.init(); + + var actualEvidence = client.acquire(input); + + assertThat(actualEvidence.canonicalBytes()) + .containsExactly(expectedEvidence.canonicalBytes()); + assertThat(server.handlerCalls()).hasValue(1); + ArgumentCaptor + captured = + ArgumentCaptor.forClass( + AccountStartSessionAdmissionProtectionAcquisitionService.AcquisitionRequest + .class); + verify(owner).acquire(captured.capture()); + assertThat(captured.getValue().originalPostAuthorizationTuple()) + .containsExactly(input.originalPostAuthorizationTuple()); + assertThat(captured.getValue().gameSessionOwnerMutationId()) + .isEqualTo(input.gameSessionOwnerMutationId()); + assertThat(captured.getValue().gameSessionOwnerAttemptId()) + .isEqualTo(input.gameSessionOwnerAttemptId()); + assertThat(captured.getValue().gameSessionOwnerFence()) + .isEqualTo(input.gameSessionOwnerFence()); + assertThat(captured.getValue().accountWorldParticipationId()) + .isEqualTo(input.accountWorldParticipationId()); + assertThat(captured.getValue().accountWorldParticipationFence()) + .isEqualTo(input.accountWorldParticipationFence()); + assertThat(captured.getValue().worldHoldIdentity().canonicalBytes()) + .containsExactly(input.worldHoldIdentity().canonicalBytes()); + } + } + + @Test + void trustedWrongServiceAndNamespacePeersAreDeniedBeforeOwnerInteraction() throws Exception { + var input = input(); + for (TestIdentity identity : List.of(pki.wrongServiceClient(), pki.otherNamespaceClient())) { + var owner = mock(AccountStartSessionAdmissionProtectionAcquisitionService.class); + try (TransportServer server = startServer(owner, false); + var client = newClient(server.port(), identity)) { + client.init(); + + assertThatThrownBy(() -> client.acquire(input)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(1); + verifyNoInteractions(owner); + } + } + } + + @Test + void missingClientCertificateIsRejectedByTlsBeforeHandlerOrOwner() throws Exception { + var owner = mock(AccountStartSessionAdmissionProtectionAcquisitionService.class); + try (TransportServer server = startServer(owner, false); + ClientTransport client = newClientWithoutIdentity(server.port())) { + assertThatThrownBy( + () -> + client.acquire( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest( + input(), NAMESPACE))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + + assertThat(server.handlerCalls()).hasValue(0); + verifyNoInteractions(owner); + } + } + + @Test + void authenticatedEndUserContextIsDeniedAtHandlerBeforeOwnerInteraction() throws Exception { + var owner = mock(AccountStartSessionAdmissionProtectionAcquisitionService.class); + try (TransportServer server = startServer(owner, true); + var client = newClient(server.port(), pki.gameSessionClient())) { + client.init(); + + assertThatThrownBy(() -> client.acquire(input())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).hasValue(1); + verifyNoInteractions(owner); + } + } + + private static TransportServer startServer( + AccountStartSessionAdmissionProtectionAcquisitionService owner, boolean injectEndUserContext) + throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + var service = + new AccountStartSessionAdmissionProtectionAcquisitionGrpcService(owner, NAMESPACE); + ServerInterceptor countHandlerCalls = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + handlerCalls.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + ServerInterceptor endUserContext = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + var delegate = next.startCall(call, metadata); + if (!injectEndUserContext) return delegate; + return new io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener<>( + delegate) { + @Override + public void onHalfClose() { + SessionContext.setContext("123", List.of(), Map.of()); + try { + super.onHalfClose(); + } finally { + SessionContext.clear(); + } + } + }; + } + }; + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.accountServer().privateKey(), pki.accountServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHandlerCalls, new GrpcPeerIdentityInterceptor(), endUserContext)) + .build() + .start(); + return new TransportServer(server, handlerCalls); + } + + private static AccountStartSessionAdmissionProtectionAcquisitionGrpcClient newClient( + int port, TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + return new AccountStartSessionAdmissionProtectionAcquisitionGrpcClient( + endpoints, + pki.clientProperties(temporaryDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ClientTransport newClientWithoutIdentity(int port) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCaCert(pki.caCertificatePem().toString()); + ManagedChannel channel = + new GrpcChannelFactory().buildChannel("localhost:" + port, 6565, tls, false); + return new ClientTransport(channel); + } + + private static AccountStartSessionAdmissionProtectionAcquisitionInput input() { + var tuple = originalTuple(); + return new AccountStartSessionAdmissionProtectionAcquisitionInput( + tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, PARTICIPATION, 22L, hold(tuple)); + } + + private static AccountStartSessionAdmissionProtectionEvidence evidence( + AccountStartSessionAdmissionProtectionAcquisitionInput input) { + var tuple = + StartSessionPostAuthorizationExecutionTuple.decode(input.originalPostAuthorizationTuple()); + var ownerRequest = + AccountStartSessionAdmissionProtectionRequest.create( + input.originalPostAuthorizationTuple(), + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + input.gameSessionOwnerMutationId(), + input.gameSessionOwnerAttemptId(), + input.gameSessionOwnerFence(), + java.time.Instant.parse("2026-10-09T10:20:30.456Z"), + input.accountWorldParticipationId(), + input.accountWorldParticipationFence(), + input.worldHoldIdentity()); + byte[] capture = + canonical( + Map.of( + "schema", + AccountStartSessionAdmissionProtectionEvidence.SOURCE_CAPTURE_REFERENCE_SCHEMA, + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "capturedAt", + "2026-10-09T10:11:12.123Z", + "bundleReference", + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "sourceVersion", + "17", + "sourceFence", + "23", + "linearization", + "18446744073709551615"), + "snapshotSha256", + "d".repeat(64))); + return AccountStartSessionAdmissionProtectionEvidence.create( + ownerRequest, + PROTECTION_ID, + 23L, + capture, + sha256(capture), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + TENANT.toString(), + "2", + "17", + null, + null, + "exact Account source".getBytes(StandardCharsets.UTF_8)))); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "transport-test", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical original StartSession admission attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(TENANT.toString(), 3L), + "membershipAuthorityGeneration", Map.of(TENANT.toString(), 4L), + "privateRealmGrantVersions", List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", ACTOR.toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + return canonical( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", TENANT.toString(), "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", TENANT.toString()), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(TENANT.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence)); + } + + private static WorldCanonicalInitialAdmissionHold.HoldIdentity hold( + StartSessionPostAuthorizationExecutionTuple tuple) { + return new WorldCanonicalInitialAdmissionHold.HoldIdentity( + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "earth", + uuid("3916f423-2870-426a-a8aa-5e3f97412613"), + uuid("54e6094e-11bb-4f4c-93ee-a52f715b530b"), + "SHARED", + uuid("a55b2e10-9a24-4adb-adb8-6fc66fe3b8e9"), + uuid("d7280ec0-5979-4b62-8418-e9f139415184"), + 3L, + tuple.controlPlaneRequestId(), + "c".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null), + HOLD_ID, + HOLD_FENCE); + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record TransportServer(Server server, AtomicInteger handlerCalls) + implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private AcquireOriginalStartSessionAdmissionProtectionResponse acquire( + AcquireOriginalStartSessionAdmissionProtectionRequest request) { + return AccountStartSessionAdmissionProtectionAcquisitionServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .acquireOriginalStartSessionAdmissionProtection(request); + } + + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC client did not terminate"); + } + } + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + Path caCertificatePem, + TestIdentity accountServer, + TestIdentity gameSessionClient, + TestIdentity wrongServiceClient, + TestIdentity otherNamespaceClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("admission-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD Account admission test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("admission-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + caFile, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "game-session-client", GAME_SESSION_URI, false), + issueIdentity( + directory, caStore, caFile, "wrong-service-client", WRONG_SERVICE_URI, false), + issueIdentity( + directory, caStore, caFile, "other-namespace-client", OTHER_NAMESPACE_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve(identity.alias() + ".crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve(identity.alias() + ".key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(caCertificatePem.toString()); + tls.setPlaintext(false); + return tls; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String extendedKeyUsage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + ArrayList command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcServiceTest.java new file mode 100644 index 0000000000..cdad949a86 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcServiceTest.java @@ -0,0 +1,435 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionAdmissionProtectionResponse; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionAcquisitionInput; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Synthetic receiver proof; the owner and TLS peer are supplied by test doubles/context. */ +class AccountStartSessionAdmissionProtectionAcquisitionGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final String GAME_SESSION_URI = + "spiffe://firemud/ns/world-runtime/sa/game-session-service"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID MUTATION = uuid("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"); + private static final UUID ATTEMPT = uuid("ec13cc04-ec15-4eb8-a018-c2c5e8da65f8"); + private static final UUID PARTICIPATION = uuid("47b3be7f-a32f-4e19-8916-8c3b8da07a82"); + private static final UUID HOLD_ID = uuid("0db7344a-1e67-4b95-905a-83dc9c472f0c"); + private static final UUID HOLD_FENCE = uuid("52a14272-f9e4-4f67-97c9-62247b5fbcc1"); + private static final UUID PROTECTION_ID = uuid("6b763f1d-c5bc-4080-b499-d29debc0a7b8"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesPeerAndRejectsEndUserBeforeInspectingRequest() { + var owner = mock(AccountStartSessionAdmissionProtectionAcquisitionService.class); + var service = + new AccountStartSessionAdmissionProtectionAcquisitionGrpcService(owner, NAMESPACE); + var malformed = AcquireOriginalStartSessionAdmissionProtectionRequest.newBuilder().build(); + + var missingPeer = invoke(service, null, malformed); + assertCode(Status.Code.UNAUTHENTICATED, missingPeer.error); + var wrongService = + invoke( + service, + identity("spiffe://firemud/ns/world-runtime/sa/world-management-service"), + malformed); + assertCode(Status.Code.PERMISSION_DENIED, wrongService.error); + var wrongNamespace = + invoke( + service, + identity("spiffe://firemud/ns/other-runtime/sa/game-session-service"), + malformed); + assertCode(Status.Code.PERMISSION_DENIED, wrongNamespace.error); + + SessionContext.setContext("123", List.of(), Map.of()); + var userContext = invoke(service, identity(GAME_SESSION_URI), malformed); + assertCode(Status.Code.PERMISSION_DENIED, userContext.error); + verifyNoInteractions(owner); + } + + @Test + void rejectsAmbientSqlBeforeParsingAndMalformedMessagesBeforeOwnerCall() { + var owner = mock(AccountStartSessionAdmissionProtectionAcquisitionService.class); + var service = + new AccountStartSessionAdmissionProtectionAcquisitionGrpcService(owner, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + var ambient = invoke(service, identity(GAME_SESSION_URI), null); + assertCode(Status.Code.FAILED_PRECONDITION, ambient.error); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + var synchronizedCall = invoke(service, identity(GAME_SESSION_URI), null); + assertCode(Status.Code.FAILED_PRECONDITION, synchronizedCall.error); + TransactionSynchronizationManager.clearSynchronization(); + + var missing = invoke(service, identity(GAME_SESSION_URI), null); + assertCode(Status.Code.INVALID_ARGUMENT, missing.error); + var malformed = + AcquireOriginalStartSessionAdmissionProtectionRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setGameSessionOwnerMutationId("not-a-uuid") + .build(); + var invalid = invoke(service, identity(GAME_SESSION_URI), malformed); + assertCode(Status.Code.INVALID_ARGUMENT, invalid.error); + verifyNoInteractions(owner); + } + + @Test + void delegatesExactInputAndReturnsTheCompleteCanonicalEvidence() { + var owner = mock(AccountStartSessionAdmissionProtectionAcquisitionService.class); + var service = + new AccountStartSessionAdmissionProtectionAcquisitionGrpcService(owner, NAMESPACE); + var input = input(); + var evidence = evidence(input); + when(owner.acquire(any())).thenReturn(evidence); + var request = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(input, NAMESPACE); + + var result = invoke(service, identity(GAME_SESSION_URI), request); + + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.response) + .isEqualTo( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toResponse( + input, NAMESPACE, evidence)); + assertThat(result.response.getEvidenceCanonicalBytes().toByteArray()) + .containsExactly(evidence.canonicalBytes()); + ArgumentCaptor + captured = + ArgumentCaptor.forClass( + AccountStartSessionAdmissionProtectionAcquisitionService.AcquisitionRequest.class); + verify(owner).acquire(captured.capture()); + var actual = captured.getValue(); + assertThat(actual.originalPostAuthorizationTuple()) + .containsExactly(input.originalPostAuthorizationTuple()); + assertThat(actual.gameSessionOwnerMutationId()).isEqualTo(MUTATION); + assertThat(actual.gameSessionOwnerAttemptId()).isEqualTo(ATTEMPT); + assertThat(actual.gameSessionOwnerFence()).isEqualTo(21L); + assertThat(actual.accountWorldParticipationId()).isEqualTo(PARTICIPATION); + assertThat(actual.accountWorldParticipationFence()).isEqualTo(22L); + assertThat(actual.worldHoldIdentity().canonicalBytes()) + .containsExactly(input.worldHoldIdentity().canonicalBytes()); + } + + @Test + void rejectsOwnerEvidenceWithSubstitutedBindingAndRedactsOwnerFailure() { + var owner = mock(AccountStartSessionAdmissionProtectionAcquisitionService.class); + var service = + new AccountStartSessionAdmissionProtectionAcquisitionGrpcService(owner, NAMESPACE); + var input = input(); + var changedInput = + new AccountStartSessionAdmissionProtectionAcquisitionInput( + input.originalPostAuthorizationTuple(), + MUTATION, + uuid("5bc4c35d-eac4-4f9e-a8fc-7ac79aebee23"), + 21L, + PARTICIPATION, + 22L, + input.worldHoldIdentity()); + when(owner.acquire(any())).thenReturn(evidence(changedInput)); + var substituted = + invoke( + service, + identity(GAME_SESSION_URI), + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(input, NAMESPACE)); + assertCode(Status.Code.FAILED_PRECONDITION, substituted.error); + assertThat(Status.fromThrowable(substituted.error).getDescription()).isNull(); + + when(owner.acquire(any())) + .thenThrow( + Status.UNAVAILABLE.withDescription("sensitive owner detail").asRuntimeException()); + var unavailable = + invoke( + service, + identity(GAME_SESSION_URI), + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(input, NAMESPACE)); + assertCode(Status.Code.UNAVAILABLE, unavailable.error); + assertThat(Status.fromThrowable(unavailable.error).getDescription()).isNull(); + } + + private static Invocation invoke( + AccountStartSessionAdmissionProtectionAcquisitionGrpcService service, + GrpcPeerIdentity peer, + AcquireOriginalStartSessionAdmissionProtectionRequest request) { + var result = new Invocation(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.acquireOriginalStartSessionAdmissionProtection(request, result); + } finally { + context.detach(previous); + } + return result; + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, Throwable failure) { + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected); + } + + private static AccountStartSessionAdmissionProtectionAcquisitionInput input() { + var tuple = originalTuple(); + return new AccountStartSessionAdmissionProtectionAcquisitionInput( + tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, PARTICIPATION, 22L, hold(tuple)); + } + + private static AccountStartSessionAdmissionProtectionEvidence evidence( + AccountStartSessionAdmissionProtectionAcquisitionInput input) { + var tuple = + StartSessionPostAuthorizationExecutionTuple.decode(input.originalPostAuthorizationTuple()); + var ownerRequest = + AccountStartSessionAdmissionProtectionRequest.create( + input.originalPostAuthorizationTuple(), + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + input.gameSessionOwnerMutationId(), + input.gameSessionOwnerAttemptId(), + input.gameSessionOwnerFence(), + Instant.parse("2026-10-09T10:20:30.456Z"), + input.accountWorldParticipationId(), + input.accountWorldParticipationFence(), + input.worldHoldIdentity()); + byte[] capture = + canonical( + Map.of( + "schema", + AccountStartSessionAdmissionProtectionEvidence.SOURCE_CAPTURE_REFERENCE_SCHEMA, + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "capturedAt", + "2026-10-09T10:11:12.123Z", + "bundleReference", + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "sourceVersion", + "17", + "sourceFence", + "23", + "linearization", + "18446744073709551615"), + "snapshotSha256", + "d".repeat(64))); + return AccountStartSessionAdmissionProtectionEvidence.create( + ownerRequest, + PROTECTION_ID, + 23L, + capture, + sha256(capture), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + TENANT.toString(), + "2", + "17", + null, + null, + "exact account source".getBytes(StandardCharsets.UTF_8)))); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "receiver-test", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical original StartSession admission attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(TENANT.toString(), 3L), + "membershipAuthorityGeneration", Map.of(TENANT.toString(), 4L), + "privateRealmGrantVersions", List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", ACTOR.toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + return canonical( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", TENANT.toString(), "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", TENANT.toString()), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(TENANT.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence)); + } + + private static WorldCanonicalInitialAdmissionHold.HoldIdentity hold( + StartSessionPostAuthorizationExecutionTuple tuple) { + return new WorldCanonicalInitialAdmissionHold.HoldIdentity( + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "earth", + uuid("3916f423-2870-426a-a8aa-5e3f97412613"), + uuid("54e6094e-11bb-4f4c-93ee-a52f715b530b"), + "SHARED", + uuid("a55b2e10-9a24-4adb-adb8-6fc66fe3b8e9"), + uuid("d7280ec0-5979-4b62-8418-e9f139415184"), + 3L, + tuple.controlPlaneRequestId(), + "c".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null), + HOLD_ID, + HOLD_FENCE); + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Invocation + implements StreamObserver { + private AcquireOriginalStartSessionAdmissionProtectionResponse response; + private Throwable error; + private boolean completed; + + @Override + public void onNext(AcquireOriginalStartSessionAdmissionProtectionResponse value) { + response = value; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The test observer retains the transport failure for status and redaction assertions") + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionClient.java new file mode 100644 index 0000000000..e48347e200 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionClient.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.common.account.startsession; + +/** + * Explicit caller-side seam for Account's original StartSession protection acquisition. + * + *

Returned Account evidence does not prove the caller's current Game Session claim or expiry; + * the consumer must independently compare both against its own retained owner state. + */ +public interface AccountStartSessionAdmissionProtectionAcquisitionClient { + AccountStartSessionAdmissionProtectionEvidence acquire( + AccountStartSessionAdmissionProtectionAcquisitionInput input); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.java new file mode 100644 index 0000000000..c0b8407b11 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.java @@ -0,0 +1,183 @@ +package net.firedevops.firemud.common.account.startsession; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionAdmissionProtectionResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; + +/** Closed bounded protobuf encoding for Account's original StartSession protection producer. */ +public final class AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec { + public static final int MAX_WIRE_BYTES = 9 * 1024 * 1024; + public static final int MAX_REQUEST_BYTES = 768 * 1024; + + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec() {} + + public static AcquireOriginalStartSessionAdmissionProtectionRequest toRequest( + AccountStartSessionAdmissionProtectionAcquisitionInput input, String targetNamespace) { + Objects.requireNonNull(input, "admission protection acquisition input is required"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw invalid("Target namespace must be one canonical DNS label"); + } + input.requireTargetNamespace(targetNamespace); + var result = + AcquireOriginalStartSessionAdmissionProtectionRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setTargetNamespace(targetNamespace) + .setOriginalPostAuthorizationTuple( + ByteString.copyFrom(input.originalPostAuthorizationTuple())) + .setGameSessionOwnerMutationId(input.gameSessionOwnerMutationId().toString()) + .setGameSessionOwnerAttemptId(input.gameSessionOwnerAttemptId().toString()) + .setGameSessionOwnerFence(input.gameSessionOwnerFence()) + .setAccountWorldParticipationId(input.accountWorldParticipationId().toString()) + .setAccountWorldParticipationFence(input.accountWorldParticipationFence()) + .setWorldHoldIdentity(ByteString.copyFrom(input.worldHoldIdentity().canonicalBytes())) + .build(); + requireRequestBudget(result); + return result; + } + + /** Parses only after the receiver authenticates its exact same-namespace Game Session peer. */ + public static AccountStartSessionAdmissionProtectionAcquisitionInput fromRequest( + AcquireOriginalStartSessionAdmissionProtectionRequest request, String expectedNamespace) { + Objects.requireNonNull(request, "admission protection acquisition request is required"); + requireClosed(request, "request"); + requireRequestBudget(request); + if (request.getSchemaVersion() != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(expectedNamespace) + || !expectedNamespace.equals(request.getTargetNamespace())) { + throw invalid("Unsupported schema or target namespace"); + } + byte[] tupleBytes = request.getOriginalPostAuthorizationTuple().toByteArray(); + byte[] holdBytes = request.getWorldHoldIdentity().toByteArray(); + if (tupleBytes.length == 0 + || tupleBytes.length + > net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple + .MAX_CANONICAL_TUPLE_BYTES + || holdBytes.length == 0 + || holdBytes.length > 64 * 1024) { + throw invalid("Original tuple or complete World hold identity is missing or oversized"); + } + AccountStartSessionAdmissionProtectionAcquisitionInput input = + new AccountStartSessionAdmissionProtectionAcquisitionInput( + tupleBytes, + canonicalUuid(request.getGameSessionOwnerMutationId(), "gameSessionOwnerMutationId"), + canonicalUuid(request.getGameSessionOwnerAttemptId(), "gameSessionOwnerAttemptId"), + request.getGameSessionOwnerFence(), + canonicalUuid(request.getAccountWorldParticipationId(), "accountWorldParticipationId"), + request.getAccountWorldParticipationFence(), + WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(holdBytes)); + input.requireTargetNamespace(expectedNamespace); + if (!toRequest(input, expectedNamespace).equals(request)) { + throw invalid("Admission protection request is not the exact canonical tuple"); + } + return input; + } + + public static AcquireOriginalStartSessionAdmissionProtectionResponse toResponse( + AccountStartSessionAdmissionProtectionAcquisitionInput input, + String targetNamespace, + AccountStartSessionAdmissionProtectionEvidence evidence) { + requireEvidenceMatchesInput(input, targetNamespace, evidence); + var response = + AcquireOriginalStartSessionAdmissionProtectionResponse.newBuilder() + .setEvidenceCanonicalBytes(ByteString.copyFrom(evidence.canonicalBytes())) + .build(); + requireResponseBudget(response); + return response; + } + + public static AccountStartSessionAdmissionProtectionEvidence fromResponse( + AccountStartSessionAdmissionProtectionAcquisitionInput input, + String targetNamespace, + AcquireOriginalStartSessionAdmissionProtectionResponse response) { + Objects.requireNonNull(input, "admission protection acquisition input is required"); + Objects.requireNonNull(response, "admission protection acquisition response is required"); + requireClosed(response, "response"); + requireResponseBudget(response); + byte[] canonicalEvidence = response.getEvidenceCanonicalBytes().toByteArray(); + AccountStartSessionAdmissionProtectionEvidence evidence = + AccountStartSessionAdmissionProtectionEvidence.decode(canonicalEvidence); + requireEvidenceMatchesInput(input, targetNamespace, evidence); + return evidence; + } + + private static void requireEvidenceMatchesInput( + AccountStartSessionAdmissionProtectionAcquisitionInput input, + String targetNamespace, + AccountStartSessionAdmissionProtectionEvidence evidence) { + Objects.requireNonNull(input, "admission protection acquisition input is required"); + Objects.requireNonNull(evidence, "admission protection evidence is required"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw invalid("Target namespace must be one canonical DNS label"); + } + input.requireTargetNamespace(targetNamespace); + var retained = evidence.request(); + if (!Arrays.equals( + input.originalPostAuthorizationTuple(), retained.originalPostAuthorizationTupleBytes()) + || !input.gameSessionOwnerMutationId().equals(retained.gameSessionOwnerMutationId()) + || !input.gameSessionOwnerAttemptId().equals(retained.gameSessionOwnerAttemptId()) + || input.gameSessionOwnerFence() != retained.gameSessionOwnerFence() + || !input.accountWorldParticipationId().equals(retained.accountWorldParticipationId()) + || input.accountWorldParticipationFence() != retained.accountWorldParticipationFence() + || !MessageDigest.isEqual( + input.worldHoldIdentity().canonicalBytes(), retained.worldAdmissionHoldIdentityBytes()) + || !retained + .originalTuple() + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(targetNamespace)) { + throw invalid("Account evidence changed the exact original acquisition binding"); + } + } + + private static void requireRequestBudget( + AcquireOriginalStartSessionAdmissionProtectionRequest request) { + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || request.getSerializedSize() > MAX_WIRE_BYTES) { + throw invalid("Admission protection request exceeds its wire budget"); + } + } + + private static void requireResponseBudget( + AcquireOriginalStartSessionAdmissionProtectionResponse response) { + if (response.getSerializedSize() > MAX_WIRE_BYTES + || response.getEvidenceCanonicalBytes().isEmpty() + || response.getEvidenceCanonicalBytes().size() + > AccountStartSessionAdmissionProtectionEvidence.MAX_CANONICAL_BYTES) { + throw invalid("Admission protection evidence is missing or exceeds its wire budget"); + } + } + + private static void requireClosed(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid("Admission protection " + label + " contains unsupported fields"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionInput.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionInput.java new file mode 100644 index 0000000000..723b8b0672 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionInput.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; + +/** Immutable caller-carried fields for original StartSession admission-protection acquisition. */ +public record AccountStartSessionAdmissionProtectionAcquisitionInput( + byte[] originalPostAuthorizationTuple, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + WorldCanonicalInitialAdmissionHold.HoldIdentity worldHoldIdentity) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public AccountStartSessionAdmissionProtectionAcquisitionInput { + Objects.requireNonNull( + originalPostAuthorizationTuple, "original StartSession tuple is required"); + if (originalPostAuthorizationTuple.length == 0 + || originalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException("Original StartSession tuple is missing or oversized"); + } + originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + var tuple = StartSessionPostAuthorizationExecutionTuple.decode(originalPostAuthorizationTuple); + if (!Arrays.equals(originalPostAuthorizationTuple, tuple.canonicalBytes())) { + throw new IllegalArgumentException("Original StartSession tuple must be canonical"); + } + if (!"StartSession".equals(tuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(tuple.preAuthorizationTuple().targetOwner())) { + throw new IllegalArgumentException("Original human StartSession tuple is required"); + } + gameSessionOwnerMutationId = + requireNonNil(gameSessionOwnerMutationId, "Game Session mutation ID"); + gameSessionOwnerAttemptId = requireNonNil(gameSessionOwnerAttemptId, "Game Session attempt ID"); + if (gameSessionOwnerFence <= 0L) { + throw new IllegalArgumentException("Game Session owner fence must be positive"); + } + accountWorldParticipationId = + requireNonNil(accountWorldParticipationId, "Account World participation ID"); + if (accountWorldParticipationFence <= 0L) { + throw new IllegalArgumentException("Account World participation fence must be positive"); + } + Objects.requireNonNull(worldHoldIdentity, "complete World hold identity is required"); + byte[] holdBytes = worldHoldIdentity.canonicalBytes(); + if (holdBytes.length == 0 || holdBytes.length > 64 * 1024) { + throw new IllegalArgumentException("Complete World hold identity is missing or oversized"); + } + if (!Arrays.equals( + holdBytes, + WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(holdBytes).canonicalBytes())) { + throw new IllegalArgumentException("World hold identity must be canonical"); + } + if (!tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .equals(worldHoldIdentity.request().canonicalTenantId()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(worldHoldIdentity.request().targetNamespace())) { + throw new IllegalArgumentException("Original tuple and complete World hold scope differ"); + } + } + + @Override + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + /** Requires the configured target namespace to match both complete original values. */ + public void requireTargetNamespace(String targetNamespace) { + if (!tupleTargetNamespace().equals(targetNamespace) + || !worldHoldIdentity.request().targetNamespace().equals(targetNamespace)) { + throw new IllegalArgumentException( + "Target namespace differs from the original tuple or hold"); + } + } + + private String tupleTargetNamespace() { + return StartSessionPostAuthorizationExecutionTuple.decode(originalPostAuthorizationTuple) + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace(); + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a non-nil UUID"); + } + return value; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionRequest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionRequest.java index bad2c5ff27..ac20a27d50 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionRequest.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionRequest.java @@ -43,10 +43,10 @@ public final class AccountStartSessionAdmissionProtectionRequest { private static final UUID NIL_UUID = new UUID(0L, 0L); private static final Pattern POSITIVE_LONG = Pattern.compile("[1-9][0-9]{0,18}"); - private static final Pattern MILLIS_UTC = - Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z"); - private static final DateTimeFormatter MILLIS_FORMAT = - DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); + private static final Pattern MICROS_UTC = + Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{6}Z"); + private static final DateTimeFormatter MICROS_FORMAT = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC); private static final Set ROOT_FIELDS = Set.of( "schema", @@ -344,24 +344,24 @@ private static byte[] bounded(byte[] value, int maximum, String name) { } private static String canonicalExpiry(Instant value) { - if (value.getNano() % 1_000_000 != 0) { - throw invalid("originalLeaseExpiresAt must use exact millisecond precision"); + if (value.getNano() % 1_000 != 0) { + throw invalid("originalLeaseExpiresAt must use exact microsecond precision"); } - String text = MILLIS_FORMAT.format(value); - if (!MILLIS_UTC.matcher(text).matches()) { - throw invalid("originalLeaseExpiresAt must use canonical UTC millisecond text"); + String text = MICROS_FORMAT.format(value); + if (!MICROS_UTC.matcher(text).matches()) { + throw invalid("originalLeaseExpiresAt must use canonical UTC microsecond text"); } return text; } private static Instant parseExpiry(String value) { - if (!MILLIS_UTC.matcher(value).matches()) { - throw invalid("originalLeaseExpiresAt must use canonical UTC millisecond text"); + if (!MICROS_UTC.matcher(value).matches()) { + throw invalid("originalLeaseExpiresAt must use canonical UTC microsecond text"); } try { Instant parsed = Instant.parse(value); - if (!MILLIS_FORMAT.format(parsed).equals(value)) { - throw invalid("originalLeaseExpiresAt must use canonical UTC millisecond text"); + if (!MICROS_FORMAT.format(parsed).equals(value)) { + throw invalid("originalLeaseExpiresAt must use canonical UTC microsecond text"); } return parsed; } catch (RuntimeException malformed) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java new file mode 100644 index 0000000000..c091fb730c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java @@ -0,0 +1,335 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionAdmissionProtectionResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID MUTATION = uuid("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"); + private static final UUID ATTEMPT = uuid("ec13cc04-ec15-4eb8-a018-c2c5e8da65f8"); + private static final UUID PARTICIPATION = uuid("47b3be7f-a32f-4e19-8916-8c3b8da07a82"); + private static final UUID HOLD_ID = uuid("0db7344a-1e67-4b95-905a-83dc9c472f0c"); + private static final UUID HOLD_FENCE = uuid("52a14272-f9e4-4f67-97c9-62247b5fbcc1"); + private static final UUID PROTECTION_ID = uuid("6b763f1d-c5bc-4080-b499-d29debc0a7b8"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void roundTripsExactSevenFieldRequestAndCanonicalEvidence() { + var input = input(); + var evidence = evidence(input); + var wireRequest = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(input, NAMESPACE); + + var decodedInput = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( + wireRequest, NAMESPACE); + assertThat(decodedInput.originalPostAuthorizationTuple()) + .containsExactly(input.originalPostAuthorizationTuple()); + assertThat(decodedInput.gameSessionOwnerMutationId()).isEqualTo(MUTATION); + assertThat(decodedInput.gameSessionOwnerAttemptId()).isEqualTo(ATTEMPT); + assertThat(decodedInput.accountWorldParticipationId()).isEqualTo(PARTICIPATION); + assertThat(decodedInput.worldHoldIdentity().canonicalBytes()) + .containsExactly(input.worldHoldIdentity().canonicalBytes()); + + var wireResponse = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toResponse( + input, NAMESPACE, evidence); + var decodedEvidence = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( + input, NAMESPACE, wireResponse); + assertThat(decodedEvidence.canonicalBytes()).containsExactly(evidence.canonicalBytes()); + } + + @Test + void rejectsUnknownFieldsAndSubstitutedRequestOrResponseBindings() { + var input = input(); + var evidence = evidence(input); + var wireRequest = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(input, NAMESPACE); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( + wireRequest.toBuilder().setUnknownFields(unknown()).build(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( + wireRequest.toBuilder().setTargetNamespace("other-runtime").build(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( + wireRequest.toBuilder().setGameSessionOwnerFence(0L).build(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive"); + + var response = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toResponse( + input, NAMESPACE, evidence); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( + input, NAMESPACE, response.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( + copyInput(uuid("5bc4c35d-eac4-4f9e-a8fc-7ac79aebee23")), NAMESPACE, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact original acquisition binding"); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( + input, + NAMESPACE, + AcquireOriginalStartSessionAdmissionProtectionResponse.newBuilder().build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void inputOwnsItsTupleBytesAndRejectsNamespaceOrTenantSubstitution() { + var tuple = originalTuple(); + byte[] supplied = tuple.canonicalBytes(); + var input = + new AccountStartSessionAdmissionProtectionAcquisitionInput( + supplied, MUTATION, ATTEMPT, 21L, PARTICIPATION, 22L, hold(tuple)); + supplied[0] ^= 1; + assertThat(input.originalPostAuthorizationTuple()).containsExactly(tuple.canonicalBytes()); + byte[] returned = input.originalPostAuthorizationTuple(); + returned[0] ^= 1; + assertThat(input.originalPostAuthorizationTuple()).containsExactly(tuple.canonicalBytes()); + assertThatThrownBy(() -> input.requireTargetNamespace("other-runtime")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest( + input, "other-runtime")) + .isInstanceOf(IllegalArgumentException.class); + } + + static AccountStartSessionAdmissionProtectionAcquisitionInput input() { + var tuple = originalTuple(); + return new AccountStartSessionAdmissionProtectionAcquisitionInput( + tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, PARTICIPATION, 22L, hold(tuple)); + } + + private static AccountStartSessionAdmissionProtectionAcquisitionInput copyInput(UUID attempt) { + var tuple = originalTuple(); + return new AccountStartSessionAdmissionProtectionAcquisitionInput( + tuple.canonicalBytes(), MUTATION, attempt, 21L, PARTICIPATION, 22L, hold(tuple)); + } + + private static AccountStartSessionAdmissionProtectionEvidence evidence( + AccountStartSessionAdmissionProtectionAcquisitionInput input) { + var tuple = + StartSessionPostAuthorizationExecutionTuple.decode(input.originalPostAuthorizationTuple()); + var request = + AccountStartSessionAdmissionProtectionRequest.create( + input.originalPostAuthorizationTuple(), + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + input.gameSessionOwnerMutationId(), + input.gameSessionOwnerAttemptId(), + input.gameSessionOwnerFence(), + Instant.parse("2026-10-09T10:20:30.456Z"), + input.accountWorldParticipationId(), + input.accountWorldParticipationFence(), + input.worldHoldIdentity()); + byte[] capture = + canonical( + Map.of( + "schema", + AccountStartSessionAdmissionProtectionEvidence.SOURCE_CAPTURE_REFERENCE_SCHEMA, + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "capturedAt", + "2026-10-09T10:11:12.123Z", + "bundleReference", + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "sourceVersion", + "17", + "sourceFence", + "23", + "linearization", + "18446744073709551615"), + "snapshotSha256", + "d".repeat(64))); + return AccountStartSessionAdmissionProtectionEvidence.create( + request, + PROTECTION_ID, + 23L, + capture, + sha256(capture), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + TENANT.toString(), + "2", + "17", + null, + null, + "exact account source".getBytes(StandardCharsets.UTF_8)))); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "acquisition-test", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical original StartSession admission attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(TENANT.toString(), 3L), + "membershipAuthorityGeneration", Map.of(TENANT.toString(), 4L), + "privateRealmGrantVersions", List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", ACTOR.toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + return canonical( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", TENANT.toString(), "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", TENANT.toString()), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(TENANT.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence)); + } + + private static WorldCanonicalInitialAdmissionHold.HoldIdentity hold( + StartSessionPostAuthorizationExecutionTuple tuple) { + return new WorldCanonicalInitialAdmissionHold.HoldIdentity( + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "earth", + uuid("3916f423-2870-426a-a8aa-5e3f97412613"), + uuid("54e6094e-11bb-4f4c-93ee-a52f715b530b"), + "SHARED", + uuid("a55b2e10-9a24-4adb-adb8-6fc66fe3b8e9"), + uuid("d7280ec0-5979-4b62-8418-e9f139415184"), + 3L, + tuple.controlPlaneRequestId(), + "c".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null), + HOLD_ID, + HOLD_FENCE); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java index a4174e34ce..70e9d99eda 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java @@ -34,7 +34,7 @@ class AccountStartSessionAdmissionProtectionEvidenceTest { private static final UUID WORLD_HOLD = uuid("0db7344a-1e67-4b95-905a-83dc9c472f0c"); private static final UUID WORLD_HOLD_FENCE = uuid("52a14272-f9e4-4f67-97c9-62247b5fbcc1"); private static final UUID ACCOUNT_PROTECTION = uuid("6b763f1d-c5bc-4080-b499-d29debc0a7b8"); - private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-09T10:20:30.456Z"); + private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-09T10:20:30.456789Z"); private static final JsonMapper JSON = JsonMapper.builder().build(); @Test @@ -145,7 +145,24 @@ void rejectsRequestProjectionHoldScopeExpiryAndCounterSubstitutions() throws Exc 2L, hold(tuple))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("millisecond"); + .hasMessageContaining("microsecond"); + + Map finerPrecision = readObject(request(tuple).canonicalBytes()); + finerPrecision.put("originalLeaseExpiresAt", "2026-10-09T10:20:30.456789001Z"); + assertThatThrownBy( + () -> AccountStartSessionAdmissionProtectionRequest.decode(canonical(finerPrecision))) + .isInstanceOf(IllegalArgumentException.class); + Map alternateFraction = readObject(request(tuple).canonicalBytes()); + alternateFraction.put("originalLeaseExpiresAt", "2026-10-09T10:20:30.45678Z"); + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionRequest.decode(canonical(alternateFraction))) + .isInstanceOf(IllegalArgumentException.class); + Map alternateOffset = readObject(request(tuple).canonicalBytes()); + alternateOffset.put("originalLeaseExpiresAt", "2026-10-09T10:20:30.456789+00:00"); + assertThatThrownBy( + () -> AccountStartSessionAdmissionProtectionRequest.decode(canonical(alternateOffset))) + .isInstanceOf(IllegalArgumentException.class); WorldCanonicalInitialAdmissionHold.HoldIdentity wrongNamespace = hold(tuple, TENANT, "another-world-runtime"); diff --git a/services/common-security/build.gradle.kts b/services/common-security/build.gradle.kts index 4109423d1f..41173f7b58 100644 --- a/services/common-security/build.gradle.kts +++ b/services/common-security/build.gradle.kts @@ -9,6 +9,7 @@ dependencies { implementation(libs.jjwt.api) implementation(libs.spring.aop) implementation(libs.spring.boot.starter) + implementation("org.springframework:spring-tx") compileOnly(libs.spring.boot.starter.web) implementation(libs.aspectjweaver) compileOnly(libs.grpc.spring.boot.starter) diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClient.java new file mode 100644 index 0000000000..2eefd8f3cf --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClient.java @@ -0,0 +1,177 @@ +package net.firedevops.firemud.common.account.startsession; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountStartSessionAdmissionProtectionAcquisitionServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for Account's unregistered original StartSession protection producer. */ +public final class AccountStartSessionAdmissionProtectionAcquisitionGrpcClient + extends AbstractReloadingBlockingGrpcClient< + AccountStartSessionAdmissionProtectionAcquisitionServiceGrpc + .AccountStartSessionAdmissionProtectionAcquisitionServiceBlockingStub> + implements AccountStartSessionAdmissionProtectionAcquisitionClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountStartSessionAdmissionProtectionAcquisitionGrpcClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMutualTls(tlsProperties), + channelFactory, + AccountStartSessionAdmissionProtectionAcquisitionGrpcClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning Game Session component explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account admission-protection client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account admission-protection stub is unavailable"); + } + initialized = true; + } + + /** Acquires exact Account evidence over mTLS, outside ambient SQL and synchronization. */ + @Override + public AccountStartSessionAdmissionProtectionEvidence acquire( + AccountStartSessionAdmissionProtectionAcquisitionInput input) { + Objects.requireNonNull(input, "admission protection acquisition input is required"); + if (net.firedevops.firemud.common.security.SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException( + "Account admission-protection acquisition requires a workload-only caller context"); + } + if (!workloadNamespace.equals( + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple.decode( + input.originalPostAuthorizationTuple()) + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace())) { + throw new IllegalArgumentException( + "Admission protection acquisition must use the configured workload namespace"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account admission-protection acquisition must run outside ambient SQL"); + } + var request = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest( + input, workloadNamespace); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .acquireOriginalStartSessionAdmissionProtection(request); + try { + return AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( + input, workloadNamespace, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid original StartSession admission-protection evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountStartSessionAdmissionProtectionAcquisitionServiceGrpc + .AccountStartSessionAdmissionProtectionAcquisitionServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountStartSessionAdmissionProtectionAcquisitionServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountStartSessionAdmissionProtectionAcquisitionServiceGrpc + .AccountStartSessionAdmissionProtectionAcquisitionServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account admission-protection client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMutualTls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Account admission-protection acquisition requires mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account admission-protection acquisition requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account admission-protection acquisition requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account admission-protection acquisition " + label + " must be file-backed", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account admission-protection acquisition " + + label + + " must be an existing readable file"); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClientTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClientTest.java new file mode 100644 index 0000000000..3d83274962 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClientTest.java @@ -0,0 +1,305 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +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 java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountStartSessionAdmissionProtectionAcquisitionServiceGrpc; +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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Client configuration proof; mocked channels do not establish a physical mTLS handshake. */ +class AccountStartSessionAdmissionProtectionAcquisitionGrpcClientTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID MUTATION = uuid("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"); + private static final UUID ATTEMPT = uuid("ec13cc04-ec15-4eb8-a018-c2c5e8da65f8"); + private static final UUID PARTICIPATION = uuid("47b3be7f-a32f-4e19-8916-8c3b8da07a82"); + private static final UUID HOLD_ID = uuid("0db7344a-1e67-4b95-905a-83dc9c472f0c"); + private static final UUID HOLD_FENCE = uuid("52a14272-f9e4-4f67-97c9-62247b5fbcc1"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void requiresReadableFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) + throws Exception { + var channelFactory = mock(GrpcChannelFactory.class); + var tls = tls(directory); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountStartSessionAdmissionProtectionAcquisitionGrpcClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + tls.setPlaintext(false); + String[] invalidPaths = { + null, + "", + "classpath:material.pem", + directory.toString(), + directory.resolve("missing.pem").toString() + }; + String[] expectedMessages = { + "file-backed", + "file-backed", + "file-backed", + "existing readable file", + "existing readable file" + }; + for (int index = 0; index < invalidPaths.length; index++) { + String path = invalidPaths[index]; + tls.setCertChain(path); + assertThatThrownBy( + () -> + new AccountStartSessionAdmissionProtectionAcquisitionGrpcClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(expectedMessages[index]); + } + + assertThatThrownBy( + () -> + new AccountStartSessionAdmissionProtectionAcquisitionGrpcClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "Test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + verifyNoInteractions(channelFactory); + } + + @Test + void pinsAccountPeerAndRejectsAmbientTransactionOrEndUserBeforeTransport(@TempDir Path directory) + throws Exception { + var channelFactory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + when(channelFactory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new AccountStartSessionAdmissionProtectionAcquisitionGrpcClient( + endpoints, tls(directory), channelFactory, NAMESPACE); + try { + client.init(); + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + var initialized = (io.grpc.stub.AbstractStub) field.get(client); + assertThat(initialized.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + var peerField = + GrpcServerPeerIdentityCallCredentials.class.getDeclaredField("expectedPeerUri"); + peerField.setAccessible(true); + assertThat(peerField.get(initialized.getCallOptions().getCredentials())) + .isEqualTo("spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service"); + + var stub = + mock( + AccountStartSessionAdmissionProtectionAcquisitionServiceGrpc + .AccountStartSessionAdmissionProtectionAcquisitionServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withMaxInboundMessageSize( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.MAX_WIRE_BYTES)) + .thenReturn(stub); + when(stub.withCallCredentials(any())).thenReturn(stub); + when(stub.withInterceptors(any())).thenReturn(stub); + when(stub.withCompression("gzip")).thenReturn(stub); + field.set(client, stub); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.acquire(input())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.acquire(input())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + + SessionContext.setContext("101", List.of(), Map.of()); + assertThatThrownBy(() -> client.acquire(input())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only caller context"); + verifyNoInteractions(stub); + verify(channelFactory) + .buildChannel( + eq("account.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + private static CommonGrpcClientProperties tls(Path directory) throws IOException { + Path cert = Files.writeString(directory.resolve("client.crt"), "synthetic certificate"); + Path key = Files.writeString(directory.resolve("client.key"), "synthetic private key"); + Path ca = Files.writeString(directory.resolve("ca.crt"), "synthetic CA"); + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(cert.toString()); + tls.setPrivateKey(key.toString()); + tls.setCaCert(ca.toString()); + return tls; + } + + private static AccountStartSessionAdmissionProtectionAcquisitionInput input() { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "client-guard-test", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical original StartSession admission attempt")); + var tuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "earth", + uuid("3916f423-2870-426a-a8aa-5e3f97412613"), + uuid("54e6094e-11bb-4f4c-93ee-a52f715b530b"), + "SHARED", + uuid("a55b2e10-9a24-4adb-adb8-6fc66fe3b8e9"), + uuid("d7280ec0-5979-4b62-8418-e9f139415184"), + 3L, + tuple.controlPlaneRequestId(), + "c".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null), + HOLD_ID, + HOLD_FENCE); + return new AccountStartSessionAdmissionProtectionAcquisitionInput( + tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, PARTICIPATION, 22L, hold); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(TENANT.toString(), 3L), + "membershipAuthorityGeneration", Map.of(TENANT.toString(), 4L), + "privateRealmGrantVersions", List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", ACTOR.toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + return canonical( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", TENANT.toString(), "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", TENANT.toString()), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(TENANT.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence)); + } + + private static byte[] canonical(Object value) { + try { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} From e6b0d6d2b901e785c955bbf5f8c606578adfdc15 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:29:33 +1300 Subject: [PATCH 079/129] fix: resolve original admission participation at Account owner --- .../account-service/api-contracts.md | 6 +- ...ame-authoring-publishing-and-activation.md | 6 +- ...ion_admission_protection_acquisition.proto | 7 +- ...l_start_session_current_attempt_read.proto | 26 +++ ...tSessionAdmissionProtectionRepository.java | 55 ++++- ...rtSessionWorldParticipationRepository.java | 44 ++++ ...ssionProtectionAcquisitionGrpcService.java | 2 - ...AdmissionProtectionAcquisitionService.java | 13 +- ...rotectedEntryPrototypeIntegrationTest.java | 7 +- .../AccountPostgresIntegrationFixture.java | 183 ++++++++++++++- ...ionAcquisitionPostgresIntegrationTest.java | 26 ++- ...sionAdmissionProtectionRepositoryTest.java | 112 +++++++++ ...ssionWorldParticipationRepositoryTest.java | 81 +++++++ ...sionProtectionAcquisitionGrpcMtlsTest.java | 15 +- ...nProtectionAcquisitionGrpcServiceTest.java | 10 +- ...ssionProtectionAcquisitionServiceTest.java | 32 ++- ...missionProtectionAcquisitionGrpcCodec.java | 6 - ...onAdmissionProtectionAcquisitionInput.java | 7 - ...tartSessionAdmissionTerminalGrpcCodec.java | 97 ++++++++ ...artSessionAdmissionTerminalReadClient.java | 8 + ...lStartSessionAdmissionTerminalRequest.java | 64 +++++ ...alStartSessionAdmissionTerminalResult.java | 81 +++++++ ...ionProtectionAcquisitionGrpcCodecTest.java | 18 +- ...SessionAdmissionTerminalGrpcCodecTest.java | 194 +++++++++++++++ ...artSessionAdmissionTerminalReadClient.java | 172 ++++++++++++++ ...onProtectionAcquisitionGrpcClientTest.java | 3 +- ...essionAdmissionTerminalReadClientTest.java | 220 ++++++++++++++++++ 27 files changed, 1420 insertions(+), 75 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalRequest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalResult.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/OriginalStartSessionAdmissionTerminalGrpcCodecTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionAdmissionTerminalReadClient.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcOriginalStartSessionAdmissionTerminalReadClientTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 2bccfcb156..d8b66c790b 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -203,11 +203,13 @@ Fresh World participation acquisition first obtains the [Game Session current-or The credential-free `ReadRedeemedOperationProjection` receiver accepts the exact configured same-namespace Game Design peer and the exact original Game Session redeemer under [ADR 0047's restricted original-operation read](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). Before returning the retained projection, Account compares the original request/reservation and redeemed workload/attempt/fence, then revalidates the original actor/JTI, current source and reference expiry. The response contains no credential or renewed permission. Game Session must separately prove its original claim and immutable pin under the owner-local checks required by that contract; this Account read is not World participation or admission. -The distinct original-admission producer and independent readback implement [ADR 0047's admission source protection](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection), not the World receiving lifecycle above. Its closed RFC 8785 `account-start-session-admission-protection-request/v1` object has exactly `schema`, `originalPostAuthorizationTupleBytesBase64`, `accountRedemptionProjectionBytesBase64`, `gameSessionOwnerMutationId`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `originalLeaseExpiresAt`, `accountWorldParticipationId`, `accountWorldParticipationFence`, and `worldAdmissionHoldIdentityBytesBase64`. UUIDs are canonical non-nil strings; positive fences are canonical decimal strings bounded by the owner counter type; expiry is the unchanged UTC lease with exactly six fractional digits, retaining PostgreSQL microsecond precision. Base64 members carry exact canonical complete original values, not hashes or caller-selected projections. The complete World hold binds its separate admission request/digest, precondition and canonical target. Unknown, duplicate, trailing, noncanonical, substituted or oversized data is rejected. +The distinct original-admission producer and independent readback implement [ADR 0047's admission source protection](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection), not the World receiving lifecycle above. The standalone acquisition RPC carries only the complete canonical original post-authorization tuple, the Game Session mutation/attempt/fence, and the complete canonical World hold identity, in addition to its schema version and target namespace; it never accepts a projection, lease expiry, or Account participation coordinates from Game Session. Account resolves the real retained participation ID/fence from its existing historical row within the fresh currentness callback. The retained closed RFC 8785 `account-start-session-admission-protection-request/v1` object continues to have exactly `schema`, `originalPostAuthorizationTupleBytesBase64`, `accountRedemptionProjectionBytesBase64`, `gameSessionOwnerMutationId`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `originalLeaseExpiresAt`, `accountWorldParticipationId`, `accountWorldParticipationFence`, and `worldAdmissionHoldIdentityBytesBase64`. UUIDs are canonical non-nil strings; positive fences are canonical decimal strings bounded by the owner counter type; expiry is the unchanged UTC lease with exactly six fractional digits, retaining PostgreSQL microsecond precision. Base64 members carry exact canonical complete original values, not hashes or caller-selected projections. The complete World hold binds its separate admission request/digest, precondition and canonical target. Unknown, duplicate, trailing, noncanonical, substituted or oversized data is rejected. The closed `account-start-session-admission-protection-evidence/v1` object carries exactly `schema`, `requestBytesBase64`, `accountProtectionId`, `accountProtectionFence`, `originalSourceCaptureReferenceBytesBase64`, `originalSourceCaptureReferenceSha256`, and `sourceEvidenceVector`. The capture reference retains the original Account version/fence/linearization and exact SHA-256; the vector contains each exact canonical source frame in canonical source-key order, without omissions, extras or duplicate keys. Carrier validation establishes integrity only, not authentication, currentness, continuity or admission. The exact same-namespace Game Session caller is checked before input handling; its fresh current-attempt read runs outside SQL, the original Account currentness callback creates or recovers immutable evidence in writable read-committed SQL, and a separate lookup-only transaction exact-compares post-commit readback. Runtime registration and authenticated terminal composition remain gated in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). -The distinct internal `AcquireOriginalStartSessionAdmissionProtection` RPC carries a closed schema-version-1 request and exact target namespace, complete original post-authorization tuple, actual Game Session mutation/attempt/fence, original World participation ID/fence, and complete canonical World hold identity. The caller does not supply a redemption projection or lease expiry: Account obtains those unchanged values from the authenticated current original Game Session attempt. The exact same-namespace Game Session workload is authenticated before parsing; end-user context and ambient transactions are rejected. Request data is bounded to 768 KiB, canonical evidence to 8 MiB, and wire framing to 9 MiB. A successful response carries the complete canonical protection evidence, and the client exact-compares every caller-carried binding. This comparison does not prove Game Session's current claim or unchanged lease; its receiving owner must independently enforce those retained values at its admission boundary. The receiver and clients remain unregistered until their producer, consumer, terminal and activation gates are proved. +The distinct internal `AcquireOriginalStartSessionAdmissionProtection` RPC transports the five-field caller binding above in a closed schema-version-1 request with the exact target namespace. The caller does not supply a redemption projection or lease expiry: Account obtains those unchanged values from the authenticated current original Game Session attempt. The exact same-namespace Game Session workload is authenticated before parsing; end-user context and ambient transactions are rejected. Request data is bounded to 768 KiB, canonical evidence to 8 MiB, and wire framing to 9 MiB. A successful response carries the complete canonical protection evidence, and the client exact-compares every caller-carried binding. This comparison does not prove Game Session's current claim or unchanged lease; its receiving owner must independently enforce those retained values at its admission boundary. The receiver and clients remain unregistered until their producer, consumer, terminal and activation gates are proved. + +Terminal recovery uses a separate lookup-only Account historical read of the exact protection ID/fence, complete canonical request, original capture and source children. This read does not consult live expiry or establish fresh authority; a lost response or expired original lease cannot release protection. Account's distinct Game Session terminal client runs outside SQL and authenticates the exact configured receiving workload before accepting the complete protection echo and canonical owner proof. Only the exact durable `COMMITTED` or positively fenced `ABORTED` evidence defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection) can support later immutable settlement; pending, missing, substituted or ambiguous evidence preserves protection. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records the still-gated settlement composition and execution proof. ## REST APIs 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 a274fac695..1b9b4ea141 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 @@ -8,7 +8,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a Distinct original-StartSession Account admission protection is prepared under [ADR 0047's canonical lifecycle](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection). It authenticates the original Game Session receiving workload, obtains the exact current original-attempt observation outside SQL, then revalidates the original actor/JTI/reference and unchanged complete capture through the existing Account currentness callback. V133 retains the complete request, actual mutation/attempt/fence and unchanged finite expiry, original World participation, full World hold, immutable capture and exact source children; additive writer/disclosure hooks preserve the existing assembled owner checks. A settled World row supplies historical binding, not current authority: acquisition must freshly prove unchanged original sources after a gap. Independent lookup-only readback returns the first protection unchanged. V129 World settlement and V131 observation are unchanged. Every V133 settlement insertion remains denied pending genuine authenticated Game Session terminal composition; expiry, missing or ambiguous proof cannot release protection. The producer remains unregistered and does not enable admission. -The prepared acquisition transport exposes the [closed Account RPC](../../../protos/account/v1/start_session_admission_protection_acquisition.proto), with the mTLS client in Common Security so it can reject authenticated end-user context before transport. It authenticates the exact Game Session workload before parsing and returns complete canonical evidence rather than selected hashes. The exact original PostgreSQL lease is retained at microsecond precision, with six canonical fractional digits and no rounding or renewal. V133 now compares the full World hold's canonical `sha256:`-prefixed digest. Nine repository integrity definitions cover exact retained sub-millisecond expiry, changed caller expiry without modifying the stored row, and forged digest rejection; the five new real-Account producer definitions cover exact acquisition/retry/readback, lost acknowledgement, changed Account sources after World settlement, protection beyond World settlement and lease expiry, and expiry while waiting for the original issuance lock. Logging, Game Session and World collaborators in those producer definitions are explicitly stipulated; they do not establish genuine cross-owner execution. The corrected composed Common Platform, Common Security and Account full checks, formatting, Checkstyle, SpotBugs, coverage, Account schema generation and boot JAR, links and Markdown pass in 2m1s. XML retains 584, 143 and 1,304 unit cases respectively, with zero failures, errors or skips; unchanged successful tasks reuse results. Four new native loopback mTLS cases execute and pass with the real Common client but a mocked Account owner. Account executes seven non-container integration cases and skips 284 of 291 definitions without Docker, including all nine V133 and five new producer cases. Their compilation and discovery are not PostgreSQL execution proof. Flyway sanity passes 12 sets and 290 versioned files; the inherited CI scope contract passes 24 tests and its structural assertions, with ShellCheck and diff hygiene clean. +The prepared acquisition transport exposes the [closed Account RPC](../../../protos/account/v1/start_session_admission_protection_acquisition.proto), with the mTLS client in Common Security so it can reject authenticated end-user context before transport. Its caller supplies the complete original tuple, actual Game Session mutation/attempt/fence and full World hold, not private Account participation coordinates; Account resolves the unchanged retained participation within its fresh currentness callback. It authenticates the exact Game Session workload before parsing and returns complete canonical evidence rather than selected hashes. The exact original PostgreSQL lease is retained at microsecond precision, with six canonical fractional digits and no rounding or renewal. V133 compares the full World hold's canonical `sha256:`-prefixed digest. Nine repository integrity definitions cover exact retained sub-millisecond expiry, changed caller expiry without modifying the stored row, and forged digest rejection; five real-Account producer definitions cover acquisition/retry/readback, lost acknowledgement, changed sources after World settlement, protection beyond World settlement and expiry, and expiry while waiting for the original issuance lock. The expired-protection case also verifies full historical lookup-only readback without renewal or settlement. Logging, Game Session and World collaborators are stipulated; these definitions do not establish genuine cross-owner execution. + +The distinct terminal-read carrier and Common Security client bind the complete Account protection echo to the existing canonical Game Session owner proof, accept only exact `COMMITTED` or positively fenced `ABORTED`, and reject pending or substituted evidence. Historical Account lookup validates the immutable parent, original capture and complete source children without consulting live expiry or releasing protection. Terminal storage and automatic reconciliation remain unimplemented; every V133 settlement insertion is still denied. The corrected composed Common Platform, Common Security and Account full checks, formatting, Checkstyle, SpotBugs, coverage, integration compilation and Account boot JAR pass in 2m40s. XML retains 587, 146 and 1,312 unit cases respectively, with zero failures, errors or skips; unchanged successful tasks reuse results. All four native loopback acquisition mTLS cases execute and pass with the real Common client but a mocked Account owner. Terminal codec and client tests use synthetic or stubbed evidence, not a genuine Game Session transaction or terminal socket. Account executes seven non-container integration cases and skips 284 of 291 definitions without Docker, including all nine V133 and five producer cases. Compilation and discovery are not PostgreSQL execution proof. Earlier schema generation and Flyway sanity pass 12 sets and 290 versioned files; no migration changes accompany this correction. + +Exact source `1f9f673095e4ac8f5bb6b9c0a969469854de4d86` [Validation run 38035808533](https://github.com/benhook1013/FireMUD/actions/runs/38035808533) failed the required gate: Account executed 1,304 unit cases with one missing-client-certificate matcher assertion failure. Retained XML and logs omit the transport exception/cause, so its cause and subsequent no-handler assertions are unproved for that run. The local corrected batch preserves the strict TLS matcher and required client certificate, adds failure diagnostics, and executes all four native cases successfully without weakening denial. Account's integration task never ran in that CI run; no PostgreSQL durability or acquisition proof follows. The tested merge `2be00c0c20e4feb76097547b9e9992c53e3ae6e3` has tree `96a7913e52c5ce281c81093e1b225fb3e9344ee2` and ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, not the separately recorded integration parent. The approved failure-only diagnostic now maps bounded captured WAL relation locators through the same run-owned database's current catalog after failure; missing, reused, changed or cross-database locators remain inconclusive. It has no executed PostgreSQL result and establishes neither historical relation identity, backend origin nor timing causation. Historical source `0a99100a98ee19197bf162a4c1c202acec8e9055` [Validation run 38032471916](https://github.com/benhook1013/FireMUD/actions/runs/38032471916) ended cancelled with a failed required gate. Originating Account XML records 292 integration executions, 12 failures and no skips: six of seven V133 cases failed at the now-corrected hold-digest comparison; four of 40 admission-lease cases and two of ten isolated prototype cases failed WAL coverage. World executed 221 cases without failures or skips. Game Design XML records 146 successful executions before its later checks were cancelled, not a completed passing job. The actual tested merge `21819de08ba16420f1749a5de4e37ada1b842b2c` has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source; it is not proof against the separately recorded integration parent. Corrected V133 physical execution remains required. diff --git a/protos/account/v1/start_session_admission_protection_acquisition.proto b/protos/account/v1/start_session_admission_protection_acquisition.proto index 121dcbf4d6..890c70fe64 100644 --- a/protos/account/v1/start_session_admission_protection_acquisition.proto +++ b/protos/account/v1/start_session_admission_protection_acquisition.proto @@ -16,14 +16,13 @@ service AccountStartSessionAdmissionProtectionAcquisitionService { message AcquireOriginalStartSessionAdmissionProtectionRequest { int32 schema_version = 1; string target_namespace = 2; - // Exact fields of AccountStartSessionAdmissionProtectionAcquisitionService.AcquisitionRequest. + // The five caller-supplied fields of the owner AcquisitionRequest; Account resolves retained + // participation coordinates and sources the original lease/projection from fresh currentness. bytes original_post_authorization_tuple = 3; string game_session_owner_mutation_id = 4; string game_session_owner_attempt_id = 5; int64 game_session_owner_fence = 6; - string account_world_participation_id = 7; - int64 account_world_participation_fence = 8; - bytes world_hold_identity = 9; + bytes world_hold_identity = 7; } message AcquireOriginalStartSessionAdmissionProtectionResponse { diff --git a/protos/game-session/v1/original_start_session_current_attempt_read.proto b/protos/game-session/v1/original_start_session_current_attempt_read.proto index bfb4f8893d..241aab0714 100644 --- a/protos/game-session/v1/original_start_session_current_attempt_read.proto +++ b/protos/game-session/v1/original_start_session_current_attempt_read.proto @@ -15,6 +15,16 @@ service OriginalStartSessionCurrentAttemptReadService { returns (ReadOriginalStartSessionCurrentAttemptResponse); } +// Unregistered Account-facing read of the durable terminal result for original-admission +// protection. This method is distinct from both the observation-only current-attempt read and the +// World-facing initial-admission proof service. +service OriginalStartSessionAdmissionTerminalReadService { + // Read the exact terminal result for Account's distinct original-admission protection. + rpc ReadOriginalStartSessionAdmissionTerminal( + ReadOriginalStartSessionAdmissionTerminalRequest) + returns (ReadOriginalStartSessionAdmissionTerminalResponse); +} + message ReadOriginalStartSessionCurrentAttemptRequest { int32 schema_version = 1; // Fresh correlation UUID for this observation; it is not a durable mutation identity. @@ -34,3 +44,19 @@ message ReadOriginalStartSessionCurrentAttemptResponse { // Raw lowercase SHA-256 of account_redemption_projection. string account_redemption_projection_digest = 5; } + +// Account supplies its complete canonical protection evidence, including the exact original +// request, protection identity/fence, source-capture reference, and source-evidence vector. +// Decoding this read selector grants no authority and does not release Account protection. +message ReadOriginalStartSessionAdmissionTerminalRequest { + int32 schema_version = 1; + bytes canonical_account_protection_evidence = 2; +} + +// The unchanged complete Account protection request is echoed. The owner proof bytes use the +// existing GameSessionCanonicalInitialAdmissionOwnerProof canonical representation; only exact +// COMMITTED or definitive durable ABORTED results are returned as a successful domain result. +message ReadOriginalStartSessionAdmissionTerminalResponse { + ReadOriginalStartSessionAdmissionTerminalRequest request = 1; + bytes canonical_game_session_owner_proof = 2; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java index 46c6d5f59a..093cff5f7d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java @@ -40,11 +40,11 @@ /** * Immutable Account storage for the original StartSession admission source protection. * - *

Every operation requires the producer's writable READ COMMITTED Account transaction. The - * producer authenticates Game Session and establishes original actor/JTI/reference currentness - * before using this repository. SQL revalidates the full retained source, World participation, - * owner observation, lease and request bindings; this repository is not an authenticator or a - * terminal settlement path. + *

Every operation requires a writable READ COMMITTED Account transaction. The producer + * authenticates Game Session and establishes original actor/JTI/reference currentness before + * acquisition; SQL revalidates the full retained source, World participation, owner observation, + * lease and request bindings. Historical lookup is integrity-only and does not authenticate a + * caller, establish currentness, release protection, or settle a terminal outcome. */ @Repository public class AccountStartSessionAdmissionProtectionRepository { @@ -202,6 +202,51 @@ public Optional findCurrentExact return Optional.of(decodeAndRequireExact(locked, request, capture, expectedSources)); } + /** + * Lookup-only read of one immutable protection for later independently authenticated terminal + * verification. + * + *

This method validates the retained identity, canonical request, capture and complete source + * vector, but performs no authentication or currentness check. It does not consult lease expiry, + * lock or renew the protection, insert a settlement, or release source protection. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findHistoricalExact( + UUID protectionId, long protectionFence) { + requireWritableReadCommittedTransaction(); + if (protectionId == null || NIL_UUID.equals(protectionId) || protectionFence <= 0L) { + throw unavailable(); + } + + Record row = selectById(protectionId, false); + if (row == null) return Optional.empty(); + + UUID retainedId = requiredUuid(row, "protection_id"); + long retainedFence = positive(requiredLong(row, "protection_fence")); + if (!protectionId.equals(retainedId) || protectionFence != retainedFence) { + throw unavailable(); + } + + AccountStartSessionAdmissionProtectionRequest request; + try { + request = + AccountStartSessionAdmissionProtectionRequest.decode( + requiredBytes(row, "request_binding_bytes")); + } catch (RuntimeException malformed) { + throw unavailable(); + } + + Record captureRow = selectCaptureForOriginalTuple(request.originalTuple(), false); + if (captureRow == null) throw unavailable(); + CaptureValue capture = captureFromRow(captureRow); + if (!request.originalTuple().controlPlaneRequestId().equals(capture.controlPlaneRequestId())) { + throw unavailable(); + } + List expectedSources = + sourceVector(capture.snapshotBytes(), request.originalTuple()); + return Optional.of(decodeAndRequireExact(row, request, capture, expectedSources)); + } + private int insert( AccountStartSessionAdmissionProtectionRequest request, AccountStartSessionAuthorityCapture capture, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java index dac5fdccca..925ae6a8d7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java @@ -269,6 +269,50 @@ public java.util.Optional findHistoricalExact( return java.util.Optional.of(withSources(parent, children)); } + /** + * Resolves the retained World participation for the exact original StartSession tuple. + * + *

The canonical tuple's stable request identity is only a unique historical lookup key. The + * complete tuple is compared with the retained parent, and the historical Account capture and + * every source child are verified before its participation identity and fence are returned. This + * supplies coordinates only; callers must independently establish fresh Account currentness + * before using the result. + */ + @Transactional(propagation = Propagation.MANDATORY) + public java.util.Optional findHistoricalForOriginalTuple( + byte[] originalPostAuthorizationTuple) { + requireWritableReadCommittedTransaction(); + if (originalPostAuthorizationTuple == null || originalPostAuthorizationTuple.length == 0) { + throw unavailable(); + } + + StartSessionPostAuthorizationExecutionTuple expectedTuple; + try { + expectedTuple = + StartSessionPostAuthorizationExecutionTuple.decode(originalPostAuthorizationTuple); + } catch (RuntimeException malformed) { + throw unavailable(); + } + if (!Arrays.equals(originalPostAuthorizationTuple, expectedTuple.canonicalBytes())) { + throw unavailable(); + } + + String requestId = expectedTuple.controlPlaneRequestId(); + Record row = selectByRequestId(requestId, false); + if (row == null) return java.util.Optional.empty(); + + StoredParticipation parent = decodeParticipation(row, List.of()); + if (!MessageDigest.isEqual( + originalPostAuthorizationTuple, parent.originalPostAuthorizationTuple())) { + throw unavailable(); + } + List capturedSources = + decodeHistoricalCapture(selectCapture(requestId, false), parent); + List children = readSources(parent.participationId()); + requireExactSources(capturedSources, children); + return java.util.Optional.of(withSources(parent, children)); + } + /** * Lookup-only post-commit readback of an immutable terminal receipt for exact historical * participation identity. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcService.java index d0a71236bc..009d858a78 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcService.java @@ -77,8 +77,6 @@ public void acquireOriginalStartSessionAdmissionProtection( input.gameSessionOwnerMutationId(), input.gameSessionOwnerAttemptId(), input.gameSessionOwnerFence(), - input.accountWorldParticipationId(), - input.accountWorldParticipationFence(), input.worldHoldIdentity())); var response = AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toResponse( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java index 592046525c..a5df7212e3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java @@ -121,9 +121,7 @@ public AccountStartSessionAdmissionProtectionEvidence acquire(AcquisitionRequest capture -> { StoredParticipation historicalParticipation = participationRepository - .findHistoricalExact( - request.accountWorldParticipationId(), - request.accountWorldParticipationFence()) + .findHistoricalForOriginalTuple(tupleBytes) .orElseThrow( () -> denied("Exact original World participation is unavailable")); requireParticipationBinding(request, tuple, historicalParticipation); @@ -245,9 +243,7 @@ private static void requireParticipationBinding( AcquisitionRequest request, StartSessionPostAuthorizationExecutionTuple tuple, StoredParticipation participation) { - if (!request.accountWorldParticipationId().equals(participation.participationId()) - || request.accountWorldParticipationFence() != participation.participationFence() - || !tuple.controlPlaneRequestId().equals(participation.controlPlaneRequestId()) + if (!tuple.controlPlaneRequestId().equals(participation.controlPlaneRequestId()) || !MessageDigest.isEqual( tuple.canonicalBytes(), participation.originalPostAuthorizationTuple()) || !request @@ -290,8 +286,6 @@ private void requireOriginalBinding( requireNonnil(request.gameSessionOwnerMutationId(), "Game Session owner mutation ID"); requireNonnil(request.gameSessionOwnerAttemptId(), "Game Session owner attempt ID"); requirePositive(request.gameSessionOwnerFence(), "Game Session owner fence"); - requireNonnil(request.accountWorldParticipationId(), "Account World participation ID"); - requirePositive(request.accountWorldParticipationFence(), "Account World participation fence"); } private static StartSessionPostAuthorizationExecutionTuple decodeOriginalTuple( @@ -344,7 +338,6 @@ private static UUID freshReadId( tuple.preAuthorizationTuple().action().scope().tenantId(), request.gameSessionOwnerMutationId(), request.gameSessionOwnerAttemptId(), - request.accountWorldParticipationId(), request.worldHoldIdentity().holdId(), StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) .issuanceOperationId())); @@ -403,8 +396,6 @@ public record AcquisitionRequest( UUID gameSessionOwnerMutationId, UUID gameSessionOwnerAttemptId, long gameSessionOwnerFence, - UUID accountWorldParticipationId, - long accountWorldParticipationFence, WorldCanonicalInitialAdmissionHold.HoldIdentity worldHoldIdentity) { public AcquisitionRequest { originalPostAuthorizationTuple = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java index 342194bfbc..3bacc02e05 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.sql.Connection; @@ -244,6 +245,7 @@ private static void retainFailureWal(Context context, String start, SQLException "--end=" + end, "--limit=128"); String output = dump.getStdout() + dump.getStderr(); + String retainedOutput = output.substring(0, Math.min(output.length(), 16384)); System.out.println( "Protected-entry WAL diagnostic " + start @@ -252,7 +254,10 @@ private static void retainFailureWal(Context context, String start, SQLException + " exit=" + dump.getExitCode() + " (maximum two segments, 128 records, 16384 characters):\n" - + output.substring(0, Math.min(output.length(), 16384))); + + retainedOutput); + System.out.println( + AccountPostgresIntegrationFixture.mapWalRelationLocatorsAfterFailure( + retainedOutput, context.admin())); System.out.println( "Protected-entry WAL diagnostic may be partial or unreadable before ordinary flushing; no flush, checkpoint, segment switch or retry was requested. Record/character limits may truncate provenance, and WAL records alone do not identify their backend."); } catch (Exception diagnosticFailure) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java index 17f1efcc84..017e512d0b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixture.java @@ -4,8 +4,15 @@ import java.math.BigInteger; import java.net.URI; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.Properties; +import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.DockerClientFactory; @@ -22,6 +29,14 @@ public final class AccountPostgresIntegrationFixture { private static final BigInteger MAX_UINT64 = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); + private static final BigInteger MAX_UINT32 = + BigInteger.ONE.shiftLeft(32).subtract(BigInteger.ONE); + private static final int MAX_RELATION_LOCATOR_OCCURRENCES = 256; + private static final int MAX_DISTINCT_RELATION_LOCATORS = 32; + private static final int MAX_WAL_DUMP_OUTPUT_CHARS = 16_384; + private static final int MAX_COMBINED_WAL_DUMP_OUTPUT_CHARS = MAX_WAL_DUMP_OUTPUT_CHARS * 3 + 256; + private static final Pattern WAL_RELATION_LOCATOR = + Pattern.compile("\\bblkref #\\d+: rel ([0-9]{1,10})/([0-9]{1,10})/([0-9]{1,10})\\b"); private static final Pattern WAL_FAILURE_DETAIL = Pattern.compile( "(?:phase=(?:create|receipt-read) )?snapshot=[0-9:,]+ own_xid_if_assigned=([0-9]*)" @@ -32,7 +47,9 @@ public final class AccountPostgresIntegrationFixture { + "(?: observed_db_ms=([1-9][0-9]{0,18}))?" + " unchanged_expiry_ms=([1-9][0-9]{0,18})"); - /** Failure-only observation; never opens a database connection or changes database settings. */ + /** + * Failure-only observation; WAL capture and locator lookup use the run-owned fixture database. + */ public String describeWalCoverageFailure(String detail) throws Exception { if (detail == null || detail.length() > 1024) { return "WAL diagnostic unavailable: missing or oversized server DETAIL"; @@ -85,8 +102,9 @@ public String describeWalCoverageFailure(String detail) throws Exception { String start = formatLsn(finalFlush.subtract(BigInteger.valueOf(1_048_576)).max(BigInteger.ZERO)); StringBuilder result = new StringBuilder("WAL failure DETAIL: ").append(detail); + StringBuilder walOutput = new StringBuilder(); result.append("\nUnflushed interval (up to 256 records):\n"); - result.append(dumpWal(fields.group(6), fields.group(4), null)); + appendWalDump(result, walOutput, dumpWal(fields.group(6), fields.group(4), null)); for (int group : new int[] {2, 3}) { String xid = fields.group(group); if (xid.isEmpty()) continue; @@ -103,8 +121,11 @@ public String describeWalCoverageFailure(String detail) throws Exception { .append("..") .append(fields.group(4)) .append(":\n"); - result.append(dumpWal(start, fields.group(4), walXid)); + appendWalDump(result, walOutput, dumpWal(start, fields.group(4), walXid)); } + result + .append('\n') + .append(mapWalRelationLocatorsAfterFailure(walOutput.toString(), dataSource())); return result .append( "\nLimits: each dump <=6s, <=16KiB, <=256 matching records; output may be truncated. " @@ -114,6 +135,162 @@ public String describeWalCoverageFailure(String detail) throws Exception { .toString(); } + private static void appendWalDump(StringBuilder result, StringBuilder walOutput, String dump) { + result.append(dump); + walOutput.append(dump).append('\n'); + } + + /** + * Maps bounded WAL relation locators against the current catalog after failure-only WAL capture. + * Results are current observations only; they do not establish historical identity, backend, or + * causation for a record. + */ + public static String mapWalRelationLocatorsAfterFailure( + String walOutput, DataSource sameDatabase) { + if (walOutput == null || walOutput.length() > MAX_COMBINED_WAL_DUMP_OUTPUT_CHARS) { + return "WAL relation mapping unavailable: missing or oversized bounded dump output"; + } + + Map locators = new LinkedHashMap<>(); + Matcher matcher = WAL_RELATION_LOCATOR.matcher(walOutput); + int occurrences = 0; + int invalidLocators = 0; + boolean occurrenceLimitReached = false; + boolean distinctLimitReached = false; + while (matcher.find()) { + if (++occurrences > MAX_RELATION_LOCATOR_OCCURRENCES) { + occurrenceLimitReached = true; + break; + } + String tablespace = matcher.group(1); + String database = matcher.group(2); + String relfilenode = matcher.group(3); + if (!validOid(tablespace) || !validOid(database) || !validOid(relfilenode)) { + invalidLocators++; + continue; + } + String key = tablespace + "/" + database + "/" + relfilenode; + if (!locators.containsKey(key)) { + if (locators.size() == MAX_DISTINCT_RELATION_LOCATORS) { + distinctLimitReached = true; + continue; + } + locators.put(key, new RelationLocator(tablespace, database, relfilenode)); + } + } + if (locators.isEmpty()) { + return "WAL relation mapping inconclusive: no valid relation locators in captured records" + + locatorLimitNote(occurrenceLimitReached, distinctLimitReached, invalidLocators); + } + + StringBuilder mapping = + new StringBuilder("WAL relation mappings (post-failure current catalog only):"); + try (Connection connection = sameDatabase.getConnection()) { + String currentDatabase = null; + String currentDatabaseOid = null; + StringBuilder values = new StringBuilder(); + for (int index = 0; index < locators.size(); index++) { + if (index > 0) values.append(','); + values.append("(?::oid, ?::oid, ?::oid)"); + } + String sql = + "WITH locator_input(tablespace_oid, database_oid, relfilenode) AS (VALUES " + + values + + "), current_database_row AS (" + + "SELECT oid FROM pg_database WHERE datname = current_database()" + + "), resolved AS (" + + "SELECT l.*, d.oid AS current_database_oid, " + + "CASE WHEN l.database_oid = d.oid " + + "THEN pg_filenode_relation(l.tablespace_oid, l.relfilenode) END AS relation_oid " + + "FROM locator_input l CROSS JOIN current_database_row d) " + + "SELECT current_database(), r.current_database_oid::text, " + + "r.tablespace_oid::text, r.database_oid::text, r.relfilenode::text, " + + "r.relation_oid::oid::text, n.nspname, c.relname, c.relkind::text, " + + "c.reltablespace::text, pg_relation_filenode(c.oid)::text " + + "FROM resolved r LEFT JOIN pg_class c ON c.oid = r.relation_oid " + + "LEFT JOIN pg_namespace n ON n.oid = c.relnamespace " + + "ORDER BY r.tablespace_oid, r.database_oid, r.relfilenode"; + try (PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setQueryTimeout(5); + int parameter = 1; + for (RelationLocator locator : locators.values()) { + statement.setString(parameter++, locator.tablespaceOid()); + statement.setString(parameter++, locator.databaseOid()); + statement.setString(parameter++, locator.relfilenode()); + } + try (ResultSet rows = statement.executeQuery()) { + while (rows.next()) { + currentDatabase = rows.getString(1); + currentDatabaseOid = rows.getString(2); + String locator = rows.getString(3) + "/" + rows.getString(4) + "/" + rows.getString(5); + String relationOid = rows.getString(6); + String schema = rows.getString(7); + String relation = rows.getString(8); + String relationKind = rows.getString(9); + String relationTablespace = rows.getString(10); + String currentRelfilenode = rows.getString(11); + mapping.append("\n ").append(locator).append(" -> "); + if (!rows.getString(4).equals(currentDatabaseOid)) { + mapping.append("different database; not looked up (inconclusive)"); + } else if (relationOid == null || schema == null || relation == null) { + mapping.append("no current mapping (missing/reused locator; inconclusive)"); + } else if (!rows.getString(5).equals(currentRelfilenode)) { + mapping + .append("catalog mapping changed during lookup to ") + .append(schema) + .append('.') + .append(relation) + .append("; locator identity inconclusive"); + } else { + mapping + .append(schema) + .append('.') + .append(relation) + .append(" relation_oid=") + .append(relationOid) + .append(" relkind=") + .append(relationKind) + .append(" reltablespace=") + .append(relationTablespace) + .append(" (current mapping only; reuse and causation not excluded)"); + } + } + } + } + if (currentDatabase == null || currentDatabaseOid == null) { + return "WAL relation mapping inconclusive: current database catalog identity unavailable"; + } + mapping + .append("\n current database: ") + .append(currentDatabase) + .append(" oid=") + .append(currentDatabaseOid); + } catch (Exception lookupFailure) { + return "WAL relation mapping unavailable: " + lookupFailure.getClass().getSimpleName(); + } + return mapping + .append(locatorLimitNote(occurrenceLimitReached, distinctLimitReached, invalidLocators)) + .toString(); + } + + private static String locatorLimitNote( + boolean occurrenceLimitReached, boolean distinctLimitReached, int invalidLocators) { + if (!occurrenceLimitReached && !distinctLimitReached && invalidLocators == 0) return ""; + return "\n mapping coverage is incomplete:" + + (occurrenceLimitReached ? " occurrence limit reached;" : "") + + (distinctLimitReached ? " distinct-locator limit reached;" : "") + + (invalidLocators == 0 ? "" : " invalid locator count=" + invalidLocators + ";") + + " omitted or invalid locators are inconclusive"; + } + + private static boolean validOid(String oid) { + if (!oid.matches("[0-9]{1,10}")) return false; + BigInteger value = new BigInteger(oid); + return value.compareTo(MAX_UINT32) <= 0; + } + + private record RelationLocator(String tablespaceOid, String databaseOid, String relfilenode) {} + private String dumpWal(String start, String end, String xid) throws Exception { // The shell program is constant; validated values travel only as positional arguments. var arguments = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java index d62b3be263..62f43a34a2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java @@ -155,6 +155,10 @@ void realAccountAcquisitionAndExactRetryPreserveProtectionCaptureAndFiniteLease( assertThat(first.accountProtectionFence()).isPositive(); assertThat(first.request().originalLeaseExpiresAt()) .isEqualTo(prepared.originalObservation.originalLeaseExpiresAt()); + assertThat(first.request().accountWorldParticipationId()) + .isEqualTo(prepared.participation.participationId()); + assertThat(first.request().accountWorldParticipationFence()) + .isEqualTo(prepared.participation.participationFence()); assertThat(first.originalSourceCaptureReferenceBytes()) .containsExactly(prepared.capture.canonicalBytes()); assertThat(first.originalSourceCaptureReferenceSha256()) @@ -272,6 +276,26 @@ void settledWorldAndExpiredOriginalLeaseDoNotReleasePendingAccountSourceProtecti prepared.account.dsl, originalLeaseExpiry.plusMillis(100), Duration.ofSeconds(15)); assertThat(databaseNow(prepared.account.dsl)).isAfter(originalLeaseExpiry); + var historicalProtectionRepository = + new AccountStartSessionAdmissionProtectionRepository(prepared.account.dsl); + AccountStartSessionAdmissionProtectionEvidence historical = + prepared.account.tx( + () -> + historicalProtectionRepository + .findHistoricalExact( + protection.accountProtectionId(), protection.accountProtectionFence()) + .orElseThrow()); + assertThat(historical.canonicalBytes()).containsExactly(protection.canonicalBytes()); + assertThat(historical.accountProtectionId()).isEqualTo(protection.accountProtectionId()); + assertThat(historical.accountProtectionFence()) + .isEqualTo(protection.accountProtectionFence()); + assertThat(historical.request().canonicalBytes()) + .containsExactly(protection.request().canonicalBytes()); + assertThat(historical.originalSourceCaptureReferenceBytes()) + .containsExactly(protection.originalSourceCaptureReferenceBytes()); + assertThat(encoded(historical.sourceEvidenceVector())) + .containsExactlyElementsOf(encoded(protection.sourceEvidenceVector())); + String roleBefore = prepared .account @@ -608,8 +632,6 @@ private Prepared prepare(Duration observationLease) throws Exception { gameSessionMutationId, gameSessionAttemptId, GAME_SESSION_OWNER_FENCE, - participation.participationId(), - participation.participationFence(), holdIdentity); var gameSessionClient = mock(OriginalStartSessionCurrentAttemptClient.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java index 1065482932..887053b035 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java @@ -3,21 +3,31 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.SQLException; import java.util.List; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.jooq.ConnectionRunnable; import org.jooq.DSLContext; +import org.jooq.Record; import org.jooq.exception.DataAccessException; +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.support.TransactionSynchronizationManager; /** Mocked database interactions verify comparison and guard ordering, not PostgreSQL execution. */ class AccountStartSessionAdmissionProtectionRepositoryTest { @@ -26,6 +36,11 @@ class AccountStartSessionAdmissionProtectionRepositoryTest { private static final byte[] REQUEST_BYTES = new byte[] {1, 2, 3}; private static final UUID ACCOUNT_ID = UUID.fromString("8d5cb900-7900-4200-88ae-113ca0f7028f"); + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + @Test void sourceChildrenMustMatchTheFullCanonicalEvidenceBytes() { SourceEvidence expected = source("2", "17", "current source bytes"); @@ -70,6 +85,80 @@ void databaseCurrentnessExpiryAfterLockWaitAbortsBeforeSourceReadback() { assertThat(arguments.getValue()[2]).isSameAs(REQUEST_BYTES); } + @Test + void historicalLookupRequiresWritableReadCommittedTransactionBeforeDatabaseAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountStartSessionAdmissionProtectionRepository repository = + new AccountStartSessionAdmissionProtectionRepository(dsl); + + assertThatThrownBy(() -> repository.findHistoricalExact(PROTECTION_ID, PROTECTION_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + + verifyNoInteractions(dsl); + } + + @Test + void historicalLookupRejectsAMismatchedRetainedFenceBeforeCaptureOrSourceRead() + throws SQLException { + DSLContext dsl = writableDsl(); + Record row = mock(Record.class); + when(row.get("protection_id", UUID.class)).thenReturn(PROTECTION_ID); + when(row.get("protection_fence", Long.class)).thenReturn(PROTECTION_FENCE + 1L); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(row); + AccountStartSessionAdmissionProtectionRepository repository = + new AccountStartSessionAdmissionProtectionRepository(dsl); + beginWritableReadCommittedTransaction(); + + assertThatThrownBy(() -> repository.findHistoricalExact(PROTECTION_ID, PROTECTION_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + + ArgumentCaptor arguments = ArgumentCaptor.forClass(Object[].class); + verify(dsl, times(1)).fetchOne(contains("WHERE protection_id = ?"), arguments.capture()); + assertThat(arguments.getValue()).containsExactly(PROTECTION_ID); + verify(dsl, times(0)).fetch(anyString(), any(Object[].class)); + } + + @Test + void historicalLookupReturnsEmptyWhenProtectionIdIsNotRetained() throws SQLException { + DSLContext dsl = writableDsl(); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(null); + AccountStartSessionAdmissionProtectionRepository repository = + new AccountStartSessionAdmissionProtectionRepository(dsl); + beginWritableReadCommittedTransaction(); + + assertThat(repository.findHistoricalExact(PROTECTION_ID, PROTECTION_FENCE)).isEmpty(); + + ArgumentCaptor arguments = ArgumentCaptor.forClass(Object[].class); + verify(dsl, times(1)).fetchOne(contains("WHERE protection_id = ?"), arguments.capture()); + assertThat(arguments.getValue()).containsExactly(PROTECTION_ID); + verify(dsl, times(0)).fetch(anyString(), any(Object[].class)); + } + + @Test + void historicalLookupRejectsMalformedRetainedRequestBeforeCaptureOrSourceRead() + throws SQLException { + DSLContext dsl = writableDsl(); + Record row = mock(Record.class); + when(row.get("protection_id", UUID.class)).thenReturn(PROTECTION_ID); + when(row.get("protection_fence", Long.class)).thenReturn(PROTECTION_FENCE); + when(row.get("request_binding_bytes", byte[].class)).thenReturn(new byte[] {1, 2, 3}); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(row); + AccountStartSessionAdmissionProtectionRepository repository = + new AccountStartSessionAdmissionProtectionRepository(dsl); + beginWritableReadCommittedTransaction(); + + assertThatThrownBy(() -> repository.findHistoricalExact(PROTECTION_ID, PROTECTION_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + + ArgumentCaptor arguments = ArgumentCaptor.forClass(Object[].class); + verify(dsl, times(1)).fetchOne(contains("WHERE protection_id = ?"), arguments.capture()); + assertThat(arguments.getValue()).containsExactly(PROTECTION_ID); + verify(dsl, times(0)).fetch(anyString(), any(Object[].class)); + } + private static SourceEvidence source(String generation, String sourceVersion, String bytes) { return new SourceEvidence( SourceKind.ACCOUNT, @@ -80,4 +169,27 @@ private static SourceEvidence source(String generation, String sourceVersion, St "17", bytes.getBytes(StandardCharsets.UTF_8)); } + + private static DSLContext writableDsl() throws SQLException { + DSLContext dsl = mock(DSLContext.class); + Connection connection = mock(Connection.class); + when(connection.getAutoCommit()).thenReturn(false); + when(connection.isReadOnly()).thenReturn(false); + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_READ_COMMITTED); + doAnswer( + invocation -> { + invocation.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + return dsl; + } + + private static void beginWritableReadCommittedTransaction() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + TransactionDefinition.ISOLATION_READ_COMMITTED); + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java index a7335e05db..b0e63eddeb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java @@ -324,6 +324,87 @@ void findCurrentExactReadsRetainedCaptureParentAndEveryChildWithoutWriting() thr assertThat(writes.get()).isNull(); } + @Test + void findHistoricalForOriginalTupleResolvesTheRetainedIdentityAndVerifiesItsSources() + throws Exception { + Fixture fixture = fixture(); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, null); + beginWritableTransaction(); + + var found = + repository.findHistoricalForOriginalTuple( + fixture.candidate().originalPostAuthorizationTuple()); + + assertThat(found).isPresent(); + assertThat(found.orElseThrow().participationId()).isEqualTo(PARTICIPATION_ID); + assertThat(found.orElseThrow().participationFence()).isEqualTo(41L); + assertThat(found.orElseThrow().originalPostAuthorizationTuple()) + .containsExactly(fixture.candidate().originalPostAuthorizationTuple()); + assertThat(found.orElseThrow().sources()).hasSize(1); + assertThat(found.orElseThrow().sources().get(0).canonicalBytes()) + .containsExactly(fixture.source().canonicalBytes()); + assertThat(reads) + .anyMatch(sql -> sql.contains("WHERE control_plane_request_id = ?")) + .anyMatch(sql -> sql.contains("account_start_session_authority_captures")) + .anyMatch(sql -> sql.contains("account_start_session_world_participation_sources")); + assertThat(reads) + .allMatch(sql -> !sql.toLowerCase(java.util.Locale.ROOT).contains("for update")); + assertThat(writes.get()).isNull(); + } + + @Test + void findHistoricalForOriginalTupleRejectsSameRequestIdWithChangedCompleteTuple() + throws Exception { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple retained = fixture.candidate().originalTuple(); + byte[] changedTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + retained.preAuthorizationTuple(), + retained.authenticatedWorkloadIdentity(), + retained.authorizationReferenceFingerprint(), + retained.reservationOwnerId(), + retained.reservationClaimFence() + 1L, + retained.authorityEvidenceBundleBytes(), + retained.bundleReference()) + .canonicalBytes(); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, null); + beginWritableTransaction(); + + assertThatThrownBy(() -> repository.findHistoricalForOriginalTuple(changedTuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + + assertThat(reads).hasSize(1); + assertThat(reads.get(0)).contains("WHERE control_plane_request_id = ?"); + assertThat(writes.get()).isNull(); + } + + @Test + void findHistoricalForOriginalTupleReturnsEmptyWhenRequestIdentityHasNoRetainedRow() + throws Exception { + Fixture fixture = fixture(); + List reads = new java.util.ArrayList<>(); + AtomicReference writes = new AtomicReference<>(); + AccountStartSessionWorldParticipationRepository repository = + mockedRepository(fixture, reads, writes, null, true); + beginWritableTransaction(); + + var found = + repository.findHistoricalForOriginalTuple( + fixture.candidate().originalPostAuthorizationTuple()); + + assertThat(found).isEmpty(); + assertThat(reads).hasSize(1); + assertThat(reads.get(0)).contains("WHERE control_plane_request_id = ?"); + assertThat(writes.get()).isNull(); + } + @Test void settleExactInsertsAndReadsBackTheSameTypedTerminalAfterHistoricalIdentityCheck() throws Exception { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java index ca6715cc29..ab021057dd 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java @@ -138,10 +138,6 @@ void exactSameNamespaceGameSessionPeerAcquiresCompleteEvidenceWithTheCommonClien .isEqualTo(input.gameSessionOwnerAttemptId()); assertThat(captured.getValue().gameSessionOwnerFence()) .isEqualTo(input.gameSessionOwnerFence()); - assertThat(captured.getValue().accountWorldParticipationId()) - .isEqualTo(input.accountWorldParticipationId()); - assertThat(captured.getValue().accountWorldParticipationFence()) - .isEqualTo(input.accountWorldParticipationFence()); assertThat(captured.getValue().worldHoldIdentity().canonicalBytes()) .containsExactly(input.worldHoldIdentity().canonicalBytes()); } @@ -181,7 +177,10 @@ void missingClientCertificateIsRejectedByTlsBeforeHandlerOrOwner() throws Except input(), NAMESPACE))) .isInstanceOf(StatusRuntimeException.class) .satisfies( - failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as("TLS rejection: %s; immediate cause: %s", failure, failure.getCause()) + .isTrue()); assertThat(server.handlerCalls()).hasValue(0); verifyNoInteractions(owner); @@ -287,7 +286,7 @@ private static ClientTransport newClientWithoutIdentity(int port) throws Excepti private static AccountStartSessionAdmissionProtectionAcquisitionInput input() { var tuple = originalTuple(); return new AccountStartSessionAdmissionProtectionAcquisitionInput( - tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, PARTICIPATION, 22L, hold(tuple)); + tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, hold(tuple)); } private static AccountStartSessionAdmissionProtectionEvidence evidence( @@ -302,8 +301,8 @@ private static AccountStartSessionAdmissionProtectionEvidence evidence( input.gameSessionOwnerAttemptId(), input.gameSessionOwnerFence(), java.time.Instant.parse("2026-10-09T10:20:30.456Z"), - input.accountWorldParticipationId(), - input.accountWorldParticipationFence(), + PARTICIPATION, + 22L, input.worldHoldIdentity()); byte[] capture = canonical( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcServiceTest.java index cdad949a86..ac1e62c89a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcServiceTest.java @@ -150,8 +150,6 @@ void delegatesExactInputAndReturnsTheCompleteCanonicalEvidence() { assertThat(actual.gameSessionOwnerMutationId()).isEqualTo(MUTATION); assertThat(actual.gameSessionOwnerAttemptId()).isEqualTo(ATTEMPT); assertThat(actual.gameSessionOwnerFence()).isEqualTo(21L); - assertThat(actual.accountWorldParticipationId()).isEqualTo(PARTICIPATION); - assertThat(actual.accountWorldParticipationFence()).isEqualTo(22L); assertThat(actual.worldHoldIdentity().canonicalBytes()) .containsExactly(input.worldHoldIdentity().canonicalBytes()); } @@ -168,8 +166,6 @@ void rejectsOwnerEvidenceWithSubstitutedBindingAndRedactsOwnerFailure() { MUTATION, uuid("5bc4c35d-eac4-4f9e-a8fc-7ac79aebee23"), 21L, - PARTICIPATION, - 22L, input.worldHoldIdentity()); when(owner.acquire(any())).thenReturn(evidence(changedInput)); var substituted = @@ -220,7 +216,7 @@ private static void assertCode(Status.Code expected, Throwable failure) { private static AccountStartSessionAdmissionProtectionAcquisitionInput input() { var tuple = originalTuple(); return new AccountStartSessionAdmissionProtectionAcquisitionInput( - tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, PARTICIPATION, 22L, hold(tuple)); + tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, hold(tuple)); } private static AccountStartSessionAdmissionProtectionEvidence evidence( @@ -235,8 +231,8 @@ private static AccountStartSessionAdmissionProtectionEvidence evidence( input.gameSessionOwnerAttemptId(), input.gameSessionOwnerFence(), Instant.parse("2026-10-09T10:20:30.456Z"), - input.accountWorldParticipationId(), - input.accountWorldParticipationFence(), + PARTICIPATION, + 22L, input.worldHoldIdentity()); byte[] capture = canonical( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionServiceTest.java index b1a47e58fb..4f66065150 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionServiceTest.java @@ -135,6 +135,7 @@ void comparesFreshObservationWithHistoricalWorldEvidenceInsideCurrentnessCallbac assertThat(acquired.accountProtectionId()).isEqualTo(PROTECTION_ID); assertThat(acquired.accountProtectionFence()).isEqualTo(PROTECTION_FENCE); assertThat(acquired.request().accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(acquired.request().accountWorldParticipationFence()).isEqualTo(PARTICIPATION_FENCE); assertThat(acquired.request().gameSessionOwnerMutationId()).isEqualTo(GAME_SESSION_MUTATION_ID); assertThat(harness.steps) .containsExactly( @@ -152,13 +153,31 @@ void comparesFreshObservationWithHistoricalWorldEvidenceInsideCurrentnessCallbac eq(GAME_SESSION_ATTEMPT_ID), eq(GAME_SESSION_FENCE), any()); - verify(harness.participationRepository) - .findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE); + ArgumentCaptor tupleBytes = ArgumentCaptor.forClass(byte[].class); + verify(harness.participationRepository).findHistoricalForOriginalTuple(tupleBytes.capture()); + assertThat(tupleBytes.getValue()).containsExactly(harness.tuple.canonicalBytes()); verify(harness.attemptEvidenceRepository) .findHistoricalExact(any(StoredParticipation.class), any(Request.class)); verify(harness.participationRepository, times(0)).findCurrentExact(any()); } + @Test + void missingTupleResolvedWorldParticipationDeniesBeforeHistoricalObservationOrProtection() { + Harness harness = new Harness(); + harness.configureSuccess(); + harness.worldParticipationMissing = true; + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(harness.request))); + + assertThat(harness.steps).containsExactly("remote-read", "issuer-currentness", "world-history"); + verify(harness.attemptEvidenceRepository, times(0)) + .findHistoricalExact(any(StoredParticipation.class), any(Request.class)); + verifyNoInteractions(harness.protectionRepository); + assertThat(harness.readbackTransactions.begins).isZero(); + } + @Test void changedOriginalLeaseExpiryDeniesBeforeCreatingProtection() { Harness harness = new Harness(); @@ -637,8 +656,6 @@ private static final class Harness { GAME_SESSION_MUTATION_ID, GAME_SESSION_ATTEMPT_ID, GAME_SESSION_FENCE, - PARTICIPATION_ID, - PARTICIPATION_FENCE, hold); final AccountStartSessionAdmissionProtectionAcquisitionService service = new AccountStartSessionAdmissionProtectionAcquisitionService( @@ -652,6 +669,7 @@ private static final class Harness { boolean protectionMissingOnReadback; int missingReadbacksRemaining; boolean changedReadbackIdentity; + boolean worldParticipationMissing; void configureSuccess() { configureClientResult(projection(tuple), ORIGINAL_LEASE_EXPIRY); @@ -676,12 +694,14 @@ void configureSuccess() { .when(issuer) .withCurrentGameSessionAdmissionProtectionCurrentness( any(byte[].class), eq(GAME_SESSION_ATTEMPT_ID), eq(GAME_SESSION_FENCE), any()); - when(participationRepository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + when(participationRepository.findHistoricalForOriginalTuple(any(byte[].class))) .thenAnswer( ignored -> { assertWritableReadCommittedTransaction(); steps.add("world-history"); - return Optional.of(worldParticipation); + return worldParticipationMissing + ? Optional.empty() + : Optional.of(worldParticipation); }); when(attemptEvidenceRepository.findHistoricalExact( any(StoredParticipation.class), any(Request.class))) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.java index c0b8407b11..92dcff7d9b 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.java @@ -37,8 +37,6 @@ public static AcquireOriginalStartSessionAdmissionProtectionRequest toRequest( .setGameSessionOwnerMutationId(input.gameSessionOwnerMutationId().toString()) .setGameSessionOwnerAttemptId(input.gameSessionOwnerAttemptId().toString()) .setGameSessionOwnerFence(input.gameSessionOwnerFence()) - .setAccountWorldParticipationId(input.accountWorldParticipationId().toString()) - .setAccountWorldParticipationFence(input.accountWorldParticipationFence()) .setWorldHoldIdentity(ByteString.copyFrom(input.worldHoldIdentity().canonicalBytes())) .build(); requireRequestBudget(result); @@ -72,8 +70,6 @@ public static AccountStartSessionAdmissionProtectionAcquisitionInput fromRequest canonicalUuid(request.getGameSessionOwnerMutationId(), "gameSessionOwnerMutationId"), canonicalUuid(request.getGameSessionOwnerAttemptId(), "gameSessionOwnerAttemptId"), request.getGameSessionOwnerFence(), - canonicalUuid(request.getAccountWorldParticipationId(), "accountWorldParticipationId"), - request.getAccountWorldParticipationFence(), WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(holdBytes)); input.requireTargetNamespace(expectedNamespace); if (!toRequest(input, expectedNamespace).equals(request)) { @@ -126,8 +122,6 @@ private static void requireEvidenceMatchesInput( || !input.gameSessionOwnerMutationId().equals(retained.gameSessionOwnerMutationId()) || !input.gameSessionOwnerAttemptId().equals(retained.gameSessionOwnerAttemptId()) || input.gameSessionOwnerFence() != retained.gameSessionOwnerFence() - || !input.accountWorldParticipationId().equals(retained.accountWorldParticipationId()) - || input.accountWorldParticipationFence() != retained.accountWorldParticipationFence() || !MessageDigest.isEqual( input.worldHoldIdentity().canonicalBytes(), retained.worldAdmissionHoldIdentityBytes()) || !retained diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionInput.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionInput.java index 723b8b0672..ed94e19a15 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionInput.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionInput.java @@ -12,8 +12,6 @@ public record AccountStartSessionAdmissionProtectionAcquisitionInput( UUID gameSessionOwnerMutationId, UUID gameSessionOwnerAttemptId, long gameSessionOwnerFence, - UUID accountWorldParticipationId, - long accountWorldParticipationFence, WorldCanonicalInitialAdmissionHold.HoldIdentity worldHoldIdentity) { private static final UUID NIL_UUID = new UUID(0L, 0L); @@ -40,11 +38,6 @@ public record AccountStartSessionAdmissionProtectionAcquisitionInput( if (gameSessionOwnerFence <= 0L) { throw new IllegalArgumentException("Game Session owner fence must be positive"); } - accountWorldParticipationId = - requireNonNil(accountWorldParticipationId, "Account World participation ID"); - if (accountWorldParticipationFence <= 0L) { - throw new IllegalArgumentException("Account World participation fence must be positive"); - } Objects.requireNonNull(worldHoldIdentity, "complete World hold identity is required"); byte[] holdBytes = worldHoldIdentity.canonicalBytes(); if (holdBytes.length == 0 || holdBytes.length > 64 * 1024) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalGrpcCodec.java new file mode 100644 index 0000000000..63c2bf9371 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalGrpcCodec.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionAdmissionTerminalResponse; + +/** Closed wire mapping for the distinct Account-facing original-admission terminal read. */ +public final class OriginalStartSessionAdmissionTerminalGrpcCodec { + public static final int MAX_REQUEST_BYTES = + OriginalStartSessionAdmissionTerminalRequest.MAX_CANONICAL_BYTES + 16; + public static final int MAX_OWNER_PROOF_BYTES = + OriginalStartSessionAdmissionTerminalResult.MAX_CANONICAL_BYTES; + public static final int MAX_RESPONSE_BYTES = MAX_REQUEST_BYTES + MAX_OWNER_PROOF_BYTES + 16; + + private OriginalStartSessionAdmissionTerminalGrpcCodec() {} + + public static ReadOriginalStartSessionAdmissionTerminalRequest toRequest( + OriginalStartSessionAdmissionTerminalRequest request) { + Objects.requireNonNull(request, "request is required"); + var wire = + ReadOriginalStartSessionAdmissionTerminalRequest.newBuilder() + .setSchemaVersion(OriginalStartSessionAdmissionTerminalRequest.SCHEMA_VERSION) + .setCanonicalAccountProtectionEvidence(ByteString.copyFrom(request.canonicalBytes())) + .build(); + requirePositiveBound(wire.getSerializedSize(), MAX_REQUEST_BYTES, "terminal-read request"); + return wire; + } + + /** Decodes only a closed, bounded selector; caller authentication is a separate GS boundary. */ + public static OriginalStartSessionAdmissionTerminalRequest fromRequest( + ReadOriginalStartSessionAdmissionTerminalRequest request) { + Objects.requireNonNull(request, "request is required"); + requirePositiveBound(request.getSerializedSize(), MAX_REQUEST_BYTES, "terminal-read request"); + if (!request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != OriginalStartSessionAdmissionTerminalRequest.SCHEMA_VERSION + || request.getCanonicalAccountProtectionEvidence().isEmpty()) { + throw new IllegalArgumentException("Closed complete schema-1 terminal-read request required"); + } + OriginalStartSessionAdmissionTerminalRequest decoded = + new OriginalStartSessionAdmissionTerminalRequest( + request.getCanonicalAccountProtectionEvidence().toByteArray()); + if (!toRequest(decoded).equals(request)) { + throw new IllegalArgumentException("Terminal-read request is not canonical"); + } + return decoded; + } + + public static ReadOriginalStartSessionAdmissionTerminalResponse toResponse( + OriginalStartSessionAdmissionTerminalResult result) { + Objects.requireNonNull(result, "result is required"); + var response = + ReadOriginalStartSessionAdmissionTerminalResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setCanonicalGameSessionOwnerProof(ByteString.copyFrom(result.canonicalBytes())) + .build(); + requirePositiveBound( + response.getSerializedSize(), MAX_RESPONSE_BYTES, "terminal-read response"); + return response; + } + + public static OriginalStartSessionAdmissionTerminalResult fromResponse( + OriginalStartSessionAdmissionTerminalRequest expectedRequest, + ReadOriginalStartSessionAdmissionTerminalResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest is required"); + Objects.requireNonNull(response, "response is required"); + requirePositiveBound( + response.getSerializedSize(), MAX_RESPONSE_BYTES, "terminal-read response"); + if (!response.getUnknownFields().asMap().isEmpty() + || !response.hasRequest() + || response.getCanonicalGameSessionOwnerProof().isEmpty() + || response.getCanonicalGameSessionOwnerProof().size() > MAX_OWNER_PROOF_BYTES) { + throw new IllegalArgumentException("Closed complete terminal-read response required"); + } + OriginalStartSessionAdmissionTerminalRequest echoed = fromRequest(response.getRequest()); + if (!expectedRequest.equals(echoed)) { + throw new IllegalArgumentException( + "Terminal-read response changed the complete Account protection evidence"); + } + byte[] proofBytes = response.getCanonicalGameSessionOwnerProof().toByteArray(); + var ownerProof = GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored(proofBytes); + OriginalStartSessionAdmissionTerminalResult result = + new OriginalStartSessionAdmissionTerminalResult(echoed, ownerProof); + if (!Arrays.equals(proofBytes, result.canonicalBytes())) { + throw new IllegalArgumentException("Owner proof bytes are not canonical"); + } + return result; + } + + private static void requirePositiveBound(int size, int maximum, String field) { + if (size <= 0 || size > maximum) { + throw new IllegalArgumentException(field + " is empty or exceeds its byte bound"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalReadClient.java new file mode 100644 index 0000000000..29935f6122 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalReadClient.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.common.gamesession; + +/** Reads one exact durable terminal result for Account's original StartSession protection. */ +public interface OriginalStartSessionAdmissionTerminalReadClient { + /** Returns only a complete COMMITTED or positively fenced ABORTED owner result. */ + OriginalStartSessionAdmissionTerminalResult read( + OriginalStartSessionAdmissionTerminalRequest request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalRequest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalRequest.java new file mode 100644 index 0000000000..dbf17fb56e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalRequest.java @@ -0,0 +1,64 @@ +package net.firedevops.firemud.common.gamesession; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; + +/** Exact complete Account protection evidence selecting one original-admission terminal read. */ +public final class OriginalStartSessionAdmissionTerminalRequest { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_CANONICAL_BYTES = + AccountStartSessionAdmissionProtectionEvidence.MAX_CANONICAL_BYTES; + + private final AccountStartSessionAdmissionProtectionEvidence protectionEvidence; + private final byte[] canonicalBytes; + + /** Decodes one bounded, exact canonical Account evidence value. */ + public OriginalStartSessionAdmissionTerminalRequest(byte[] canonicalProtectionEvidenceBytes) { + Objects.requireNonNull( + canonicalProtectionEvidenceBytes, "canonicalProtectionEvidenceBytes is required"); + if (canonicalProtectionEvidenceBytes.length == 0 + || canonicalProtectionEvidenceBytes.length > MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException( + "Canonical Account protection evidence is empty or exceeds its byte bound"); + } + this.protectionEvidence = + AccountStartSessionAdmissionProtectionEvidence.decode(canonicalProtectionEvidenceBytes); + this.canonicalBytes = protectionEvidence.canonicalBytes(); + if (!Arrays.equals(canonicalProtectionEvidenceBytes, canonicalBytes)) { + throw new IllegalArgumentException( + "Account protection evidence bytes are not the exact canonical value"); + } + } + + public AccountStartSessionAdmissionProtectionEvidence protectionEvidence() { + return protectionEvidence; + } + + public String targetNamespace() { + return protectionEvidence + .request() + .originalTuple() + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace(); + } + + /** Returns the exact complete Account evidence bytes, including all retained source children. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof OriginalStartSessionAdmissionTerminalRequest that + && Arrays.equals(canonicalBytes, that.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalResult.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalResult.java new file mode 100644 index 0000000000..14bbb9f4e0 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionAdmissionTerminalResult.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.common.gamesession; + +import java.util.Objects; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; + +/** Exact terminal owner result bound to the complete Account protection read request. */ +public final class OriginalStartSessionAdmissionTerminalResult { + public static final int MAX_CANONICAL_BYTES = + AccountStartSessionAdmissionProtectionRequest.MAX_HOLD_IDENTITY_BYTES + 512; + + private final OriginalStartSessionAdmissionTerminalRequest request; + private final GameSessionCanonicalInitialAdmissionOwnerProof ownerProof; + private final byte[] canonicalBytes; + + public OriginalStartSessionAdmissionTerminalResult( + OriginalStartSessionAdmissionTerminalRequest request, + GameSessionCanonicalInitialAdmissionOwnerProof ownerProof) { + this.request = Objects.requireNonNull(request, "request is required"); + this.ownerProof = Objects.requireNonNull(ownerProof, "ownerProof is required"); + requireExactTerminalProof(request, ownerProof); + this.canonicalBytes = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(ownerProof); + if (canonicalBytes.length == 0 || canonicalBytes.length > MAX_CANONICAL_BYTES) { + throw new IllegalArgumentException( + "Canonical Game Session owner proof exceeds its byte bound"); + } + } + + public OriginalStartSessionAdmissionTerminalRequest request() { + return request; + } + + public GameSessionCanonicalInitialAdmissionOwnerProof ownerProof() { + return ownerProof; + } + + /** Returns the existing canonical owner-proof representation without introducing a new schema. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + static void requireExactTerminalProof( + OriginalStartSessionAdmissionTerminalRequest request, + GameSessionCanonicalInitialAdmissionOwnerProof proof) { + var expectedHold = request.protectionEvidence().request().worldAdmissionHoldIdentity(); + if (!expectedHold.equals(proof.holdIdentity())) { + throw new IllegalArgumentException( + "Game Session owner proof differs from the exact Account World hold identity"); + } + switch (proof.outcome()) { + case PENDING -> + throw new IllegalArgumentException("Pending owner proof is not terminal evidence"); + case COMMITTED -> { + var holdRequest = expectedHold.request(); + long expectedVersion; + try { + expectedVersion = + switch (holdRequest.initialAdmissionOrigin()) { + case NO_PRIOR_POINTER -> 1L; + case EXPECT_CLOSED -> Math.addExact(holdRequest.expectedPriorPointerVersion(), 1L); + }; + } catch (ArithmeticException overflow) { + throw new IllegalArgumentException( + "Expected pointer version cannot advance without overflow", overflow); + } + if (!Long.valueOf(expectedVersion).equals(proof.committedPointerVersion())) { + throw new IllegalArgumentException( + "Committed owner proof does not name the exact next pointer version"); + } + } + case ABORTED -> { + if (!proof.positiveDurableAbort()) { + throw new IllegalArgumentException( + "Aborted owner proof must exclude future or in-flight commits"); + } + } + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java index c091fb730c..b6852e3fc0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java @@ -36,7 +36,7 @@ class AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest { private static final JsonMapper JSON = JsonMapper.builder().build(); @Test - void roundTripsExactSevenFieldRequestAndCanonicalEvidence() { + void roundTripsExactFiveFieldRequestAndCanonicalEvidence() { var input = input(); var evidence = evidence(input); var wireRequest = @@ -49,7 +49,7 @@ void roundTripsExactSevenFieldRequestAndCanonicalEvidence() { .containsExactly(input.originalPostAuthorizationTuple()); assertThat(decodedInput.gameSessionOwnerMutationId()).isEqualTo(MUTATION); assertThat(decodedInput.gameSessionOwnerAttemptId()).isEqualTo(ATTEMPT); - assertThat(decodedInput.accountWorldParticipationId()).isEqualTo(PARTICIPATION); + assertThat(decodedInput.gameSessionOwnerFence()).isEqualTo(21L); assertThat(decodedInput.worldHoldIdentity().canonicalBytes()) .containsExactly(input.worldHoldIdentity().canonicalBytes()); @@ -60,6 +60,8 @@ void roundTripsExactSevenFieldRequestAndCanonicalEvidence() { AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( input, NAMESPACE, wireResponse); assertThat(decodedEvidence.canonicalBytes()).containsExactly(evidence.canonicalBytes()); + assertThat(decodedEvidence.request().accountWorldParticipationId()).isEqualTo(PARTICIPATION); + assertThat(decodedEvidence.request().accountWorldParticipationFence()).isEqualTo(22L); } @Test @@ -116,7 +118,7 @@ void inputOwnsItsTupleBytesAndRejectsNamespaceOrTenantSubstitution() { byte[] supplied = tuple.canonicalBytes(); var input = new AccountStartSessionAdmissionProtectionAcquisitionInput( - supplied, MUTATION, ATTEMPT, 21L, PARTICIPATION, 22L, hold(tuple)); + supplied, MUTATION, ATTEMPT, 21L, hold(tuple)); supplied[0] ^= 1; assertThat(input.originalPostAuthorizationTuple()).containsExactly(tuple.canonicalBytes()); byte[] returned = input.originalPostAuthorizationTuple(); @@ -134,16 +136,16 @@ void inputOwnsItsTupleBytesAndRejectsNamespaceOrTenantSubstitution() { static AccountStartSessionAdmissionProtectionAcquisitionInput input() { var tuple = originalTuple(); return new AccountStartSessionAdmissionProtectionAcquisitionInput( - tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, PARTICIPATION, 22L, hold(tuple)); + tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, hold(tuple)); } private static AccountStartSessionAdmissionProtectionAcquisitionInput copyInput(UUID attempt) { var tuple = originalTuple(); return new AccountStartSessionAdmissionProtectionAcquisitionInput( - tuple.canonicalBytes(), MUTATION, attempt, 21L, PARTICIPATION, 22L, hold(tuple)); + tuple.canonicalBytes(), MUTATION, attempt, 21L, hold(tuple)); } - private static AccountStartSessionAdmissionProtectionEvidence evidence( + static AccountStartSessionAdmissionProtectionEvidence evidence( AccountStartSessionAdmissionProtectionAcquisitionInput input) { var tuple = StartSessionPostAuthorizationExecutionTuple.decode(input.originalPostAuthorizationTuple()); @@ -155,8 +157,8 @@ private static AccountStartSessionAdmissionProtectionEvidence evidence( input.gameSessionOwnerAttemptId(), input.gameSessionOwnerFence(), Instant.parse("2026-10-09T10:20:30.456Z"), - input.accountWorldParticipationId(), - input.accountWorldParticipationFence(), + PARTICIPATION, + 22L, input.worldHoldIdentity()); byte[] capture = canonical( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/OriginalStartSessionAdmissionTerminalGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/OriginalStartSessionAdmissionTerminalGrpcCodecTest.java new file mode 100644 index 0000000000..3062739e0b --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/OriginalStartSessionAdmissionTerminalGrpcCodecTest.java @@ -0,0 +1,194 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalGrpcCodec; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalResult; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import org.junit.jupiter.api.Test; + +/** Synthetic carrier tests; the fixture does not represent a genuine Game Session terminal. */ +class OriginalStartSessionAdmissionTerminalGrpcCodecTest { + private static final UUID OTHER_HOLD_FENCE = + UUID.fromString("c3527a86-eae1-4a1e-b8a6-13c831f7a665"); + private static final String PROOF_DIGEST = "sha256:" + "d".repeat(64); + + @Test + void roundTripsCompleteAccountProtectionAndBothTerminalOutcomes() { + var request = request(); + var wireRequest = OriginalStartSessionAdmissionTerminalGrpcCodec.toRequest(request); + assertThat(OriginalStartSessionAdmissionTerminalGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(request); + + var committed = + result(request, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + var committedResponse = OriginalStartSessionAdmissionTerminalGrpcCodec.toResponse(committed); + assertThat(committedResponse.getRequest()) + .isEqualTo(OriginalStartSessionAdmissionTerminalGrpcCodec.toRequest(request)); + var recoveredCommitted = + OriginalStartSessionAdmissionTerminalGrpcCodec.fromResponse(request, committedResponse); + assertThat(recoveredCommitted.request().canonicalBytes()) + .containsExactly(request.canonicalBytes()); + assertThat(recoveredCommitted.canonicalBytes()).containsExactly(committed.canonicalBytes()); + assertThat(recoveredCommitted.ownerProof().outcome()) + .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + + var aborted = result(request, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + var recoveredAborted = + OriginalStartSessionAdmissionTerminalGrpcCodec.fromResponse( + request, OriginalStartSessionAdmissionTerminalGrpcCodec.toResponse(aborted)); + assertThat(recoveredAborted.canonicalBytes()).containsExactly(aborted.canonicalBytes()); + assertThat(recoveredAborted.ownerProof().positiveDurableAbort()).isTrue(); + } + + @Test + void rejectsUnknownMalformedPendingAndChangedFullProtectionEchoes() { + var request = request(); + assertThatThrownBy(() -> new OriginalStartSessionAdmissionTerminalRequest(new byte[] {1, 2, 3})) + .isInstanceOf(IllegalArgumentException.class); + var wireRequest = OriginalStartSessionAdmissionTerminalGrpcCodec.toRequest(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + assertThatThrownBy( + () -> + OriginalStartSessionAdmissionTerminalGrpcCodec.fromRequest( + wireRequest.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Closed complete"); + + var committed = + result(request, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + var validResponse = OriginalStartSessionAdmissionTerminalGrpcCodec.toResponse(committed); + assertThatThrownBy( + () -> + OriginalStartSessionAdmissionTerminalGrpcCodec.fromResponse( + request, validResponse.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Closed complete"); + assertThatThrownBy( + () -> + OriginalStartSessionAdmissionTerminalGrpcCodec.fromResponse( + request, + validResponse.toBuilder() + .setCanonicalGameSessionOwnerProof( + ByteString.copyFrom(new byte[] {1, 2, 3})) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + var changedInput = + new AccountStartSessionAdmissionProtectionAcquisitionInput( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.input() + .originalPostAuthorizationTuple(), + UUID.fromString("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"), + UUID.fromString("5bc4c35d-eac4-4f9e-a8fc-7ac79aebee23"), + 21L, + request.protectionEvidence().request().worldAdmissionHoldIdentity()); + var changedEvidence = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.evidence(changedInput); + var changedRequest = + new OriginalStartSessionAdmissionTerminalRequest(changedEvidence.canonicalBytes()); + assertThatThrownBy( + () -> + OriginalStartSessionAdmissionTerminalGrpcCodec.fromResponse( + request, + validResponse.toBuilder() + .setRequest( + OriginalStartSessionAdmissionTerminalGrpcCodec.toRequest( + changedRequest)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete Account protection evidence"); + + var pending = + new GameSessionCanonicalInitialAdmissionOwnerProof( + request.protectionEvidence().request().worldAdmissionHoldIdentity(), + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING, + null, + null, + null, + false, + null); + assertThatThrownBy(() -> new OriginalStartSessionAdmissionTerminalResult(request, pending)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Pending"); + } + + @Test + void rejectsWrongPointerVersionAndAnySubstitutedFullWorldHold() { + var request = request(); + var hold = request.protectionEvidence().request().worldAdmissionHoldIdentity(); + var wrongPointer = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 2L, + 23L, + PROOF_DIGEST, + false, + Instant.parse("2026-10-09T10:20:30Z")); + assertThatThrownBy(() -> new OriginalStartSessionAdmissionTerminalResult(request, wrongPointer)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact next pointer version"); + + var changedHold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + hold.request(), hold.holdId(), OTHER_HOLD_FENCE); + var substitutedHold = + new GameSessionCanonicalInitialAdmissionOwnerProof( + changedHold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + null, + null, + PROOF_DIGEST, + true, + Instant.parse("2026-10-09T10:20:30Z")); + assertThatThrownBy( + () -> new OriginalStartSessionAdmissionTerminalResult(request, substitutedHold)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact Account World hold identity"); + } + + private static OriginalStartSessionAdmissionTerminalRequest request() { + var evidence = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.evidence( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.input()); + return new OriginalStartSessionAdmissionTerminalRequest(evidence.canonicalBytes()); + } + + private static OriginalStartSessionAdmissionTerminalResult result( + OriginalStartSessionAdmissionTerminalRequest request, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome) { + var proof = + switch (outcome) { + case COMMITTED -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + request.protectionEvidence().request().worldAdmissionHoldIdentity(), + outcome, + 1L, + 23L, + PROOF_DIGEST, + false, + Instant.parse("2026-10-09T10:20:30Z")); + case ABORTED -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + request.protectionEvidence().request().worldAdmissionHoldIdentity(), + outcome, + null, + null, + PROOF_DIGEST, + true, + Instant.parse("2026-10-09T10:20:30Z")); + case PENDING -> throw new IllegalArgumentException("Pending is not terminal"); + }; + return new OriginalStartSessionAdmissionTerminalResult(request, proof); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionAdmissionTerminalReadClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionAdmissionTerminalReadClient.java new file mode 100644 index 0000000000..7239f4f1b9 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionAdmissionTerminalReadClient.java @@ -0,0 +1,172 @@ +package net.firedevops.firemud.common.gamesession; + +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.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.OriginalStartSessionAdmissionTerminalReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicit file-backed mTLS client for the unregistered Account-facing Game Session terminal read. + */ +public final class GrpcOriginalStartSessionAdmissionTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + OriginalStartSessionAdmissionTerminalReadServiceGrpc + .OriginalStartSessionAdmissionTerminalReadServiceBlockingStub> + implements OriginalStartSessionAdmissionTerminalReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcOriginalStartSessionAdmissionTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcOriginalStartSessionAdmissionTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when a consuming service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Original StartSession terminal-read client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Original StartSession terminal-read stub is unavailable"); + } + initialized = true; + } + + /** Reads exact terminal evidence without treating it as current claim or admission authority. */ + @Override + public OriginalStartSessionAdmissionTerminalResult read( + OriginalStartSessionAdmissionTerminalRequest request) { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException( + "Original StartSession terminal read requires a workload-only caller context"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Original StartSession terminal read must run outside ambient SQL"); + } + Objects.requireNonNull(request, "original StartSession terminal-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Original StartSession terminal-read request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readOriginalStartSessionAdmissionTerminal( + OriginalStartSessionAdmissionTerminalGrpcCodec.toRequest(request)); + try { + return OriginalStartSessionAdmissionTerminalGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Session returned invalid original StartSession terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected OriginalStartSessionAdmissionTerminalReadServiceGrpc + .OriginalStartSessionAdmissionTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + return OriginalStartSessionAdmissionTerminalReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + OriginalStartSessionAdmissionTerminalGrpcCodec.MAX_RESPONSE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private OriginalStartSessionAdmissionTerminalReadServiceGrpc + .OriginalStartSessionAdmissionTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Original StartSession terminal-read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Original StartSession terminal reads require 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( + "Original StartSession terminal reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Original StartSession terminal reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Original StartSession terminal-read " + label + " must be file-backed", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Original StartSession terminal-read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClientTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClientTest.java index 3d83274962..27b4764752 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClientTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcClientTest.java @@ -43,7 +43,6 @@ class AccountStartSessionAdmissionProtectionAcquisitionGrpcClientTest { private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); private static final UUID MUTATION = uuid("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"); private static final UUID ATTEMPT = uuid("ec13cc04-ec15-4eb8-a018-c2c5e8da65f8"); - private static final UUID PARTICIPATION = uuid("47b3be7f-a32f-4e19-8916-8c3b8da07a82"); private static final UUID HOLD_ID = uuid("0db7344a-1e67-4b95-905a-83dc9c472f0c"); private static final UUID HOLD_FENCE = uuid("52a14272-f9e4-4f67-97c9-62247b5fbcc1"); private static final JsonMapper JSON = JsonMapper.builder().build(); @@ -226,7 +225,7 @@ private static AccountStartSessionAdmissionProtectionAcquisitionInput input() { HOLD_ID, HOLD_FENCE); return new AccountStartSessionAdmissionProtectionAcquisitionInput( - tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, PARTICIPATION, 22L, hold); + tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, hold); } private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcOriginalStartSessionAdmissionTerminalReadClientTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcOriginalStartSessionAdmissionTerminalReadClientTest.java new file mode 100644 index 0000000000..be9814ef70 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcOriginalStartSessionAdmissionTerminalReadClientTest.java @@ -0,0 +1,220 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +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 java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.GrpcOriginalStartSessionAdmissionTerminalReadClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalGrpcCodec; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalRequest; +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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.OriginalStartSessionAdmissionTerminalReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionAdmissionTerminalResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic mTLS client setup tests; no Game Session producer or database is exercised. */ +class GrpcOriginalStartSessionAdmissionTerminalReadClientTest { + private static final String NAMESPACE = "world-runtime"; + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) throws Exception { + var channelFactory = mock(GrpcChannelFactory.class); + var tls = tls(directory); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcOriginalStartSessionAdmissionTerminalReadClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + tls.setPlaintext(false); + String[] invalidPaths = { + null, + "", + "classpath:material.pem", + directory.toString(), + directory.resolve("missing.pem").toString() + }; + String[] expectedMessages = { + "file-backed", + "file-backed", + "file-backed", + "existing readable file", + "existing readable file" + }; + for (int index = 0; index < invalidPaths.length; index++) { + tls.setCertChain(invalidPaths[index]); + assertThatThrownBy( + () -> + new GrpcOriginalStartSessionAdmissionTerminalReadClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining(expectedMessages[index]); + } + assertThatThrownBy( + () -> + new GrpcOriginalStartSessionAdmissionTerminalReadClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "Test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + verifyNoInteractions(channelFactory); + } + + @Test + void explicitlyInitializesPinsPeerAndCallsBoundedTerminalRead(@TempDir Path directory) + throws Exception { + var channelFactory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("game-session.internal:6565"); + when(channelFactory.buildChannel( + eq("game-session.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + var client = + new GrpcOriginalStartSessionAdmissionTerminalReadClient( + endpoints, tls(directory), channelFactory, NAMESPACE); + var request = mock(OriginalStartSessionAdmissionTerminalRequest.class); + when(request.targetNamespace()).thenReturn(NAMESPACE); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + + try { + client.init(); + var stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + var initialized = (io.grpc.stub.AbstractStub) stubField.get(client); + assertThat(initialized.getCallOptions().getMaxInboundMessageSize()) + .isEqualTo(OriginalStartSessionAdmissionTerminalGrpcCodec.MAX_RESPONSE_BYTES); + assertThat(initialized.getCallOptions().getCompressor()).isEqualTo("gzip"); + assertThat(initialized.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + var credentials = initialized.getCallOptions().getCredentials(); + var expectedPeerField = + GrpcServerPeerIdentityCallCredentials.class.getDeclaredField("expectedPeerUri"); + expectedPeerField.setAccessible(true); + assertThat(expectedPeerField.get(credentials)) + .isEqualTo("spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"); + + var stub = + mock( + OriginalStartSessionAdmissionTerminalReadServiceGrpc + .OriginalStartSessionAdmissionTerminalReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(request.canonicalBytes()).thenReturn(new byte[] {1}); + when(stub.readOriginalStartSessionAdmissionTerminal( + any(ReadOriginalStartSessionAdmissionTerminalRequest.class))) + .thenReturn(ReadOriginalStartSessionAdmissionTerminalResponse.newBuilder().build()); + stubField.set(client, stub); + + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid original StartSession terminal evidence"); + verify(stub).withDeadlineAfter(5, TimeUnit.SECONDS); + verify(stub) + .readOriginalStartSessionAdmissionTerminal( + OriginalStartSessionAdmissionTerminalGrpcCodec.toRequest(request)); + verify(channelFactory) + .buildChannel( + eq("game-session.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + client.close(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + } finally { + client.close(); + } + } + + @Test + void rejectsEndUserAndAmbientSqlBeforeCallingTheStub(@TempDir Path directory) throws Exception { + var channelFactory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("game-session.internal:6565"); + when(channelFactory.buildChannel( + eq("game-session.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + var client = + new GrpcOriginalStartSessionAdmissionTerminalReadClient( + endpoints, tls(directory), channelFactory, NAMESPACE); + try { + client.init(); + var stub = + mock( + OriginalStartSessionAdmissionTerminalReadServiceGrpc + .OriginalStartSessionAdmissionTerminalReadServiceBlockingStub.class); + var stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + + SessionContext.setContext("101", List.of(), Map.of()); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only"); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + verifyNoInteractions(stub); + } finally { + client.close(); + } + } + + private static CommonGrpcClientProperties tls(Path directory) throws IOException { + Path cert = Files.writeString(directory.resolve("client.crt"), "synthetic certificate"); + Path key = Files.writeString(directory.resolve("client.key"), "synthetic private key"); + Path ca = Files.writeString(directory.resolve("ca.crt"), "synthetic CA"); + var tls = new CommonGrpcClientProperties(); + tls.setCertChain(cert.toString()); + tls.setPrivateKey(key.toString()); + tls.setCaCert(ca.toString()); + return tls; + } +} From 46a306f65b410fc9dde7b64be204a9f4e364e8a2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:27:47 +1300 Subject: [PATCH 080/129] Implement exact original admission protection settlement --- .../account-service/api-contracts.md | 4 + design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 10 +- ...tSessionAdmissionProtectionRepository.java | 190 ++++++ ...nAdmissionProtectionSettlementService.java | 239 +++++++ ...ession_admission_protection_settlement.sql | 470 +++++++++++++ ...AccountPostgresIntegrationFixtureTest.java | 190 ++++++ ...sionProtectionPostgresIntegrationTest.java | 13 +- ...ionAcquisitionPostgresIntegrationTest.java | 362 +++++++++- ...sionAdmissionProtectionRepositoryTest.java | 55 ++ ...sionProtectionAcquisitionGrpcMtlsTest.java | 48 +- ...issionProtectionSettlementServiceTest.java | 621 ++++++++++++++++++ ...tSessionAdmissionProtectionSettlement.java | 268 ++++++++ ...sionAdmissionProtectionSettlementTest.java | 271 ++++++++ 14 files changed, 2730 insertions(+), 17 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java create mode 100644 services/account-service/src/main/resources/db/migration/V134__start_session_admission_protection_settlement.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlement.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d8b66c790b..3c2a773cd6 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -211,6 +211,10 @@ The distinct internal `AcquireOriginalStartSessionAdmissionProtection` RPC trans Terminal recovery uses a separate lookup-only Account historical read of the exact protection ID/fence, complete canonical request, original capture and source children. This read does not consult live expiry or establish fresh authority; a lost response or expired original lease cannot release protection. Account's distinct Game Session terminal client runs outside SQL and authenticates the exact configured receiving workload before accepting the complete protection echo and canonical owner proof. Only the exact durable `COMMITTED` or positively fenced `ABORTED` evidence defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection) can support later immutable settlement; pending, missing, substituted or ambiguous evidence preserves protection. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records the still-gated settlement composition and execution proof. +Account's immutable admission-settlement value is the closed RFC 8785 object `account-start-session-admission-protection-settlement/v1`, with exactly `schema`, `canonicalAccountProtectionEvidenceBytesBase64`, and `canonicalGameSessionOwnerProofBytesBase64`. Each base64 field retains the complete original canonical bytes, not a digest-only substitute; the first includes the immutable request, protection ID/fence, capture reference and complete source vector, and the second uses the existing Game Session canonical initial-admission owner-proof representation. The stored digest is `sha256:` plus lowercase SHA-256 of the entire canonical object. The complete object is bounded to 24 MiB. Unknown, duplicate, trailing, noncanonical or oversized values, changed protection/capture/source/hold binding, pending outcomes and terminal conflicts are denied. `COMMITTED` must name the exact next pointer and positive audit identity; `ABORTED` requires positive durable exclusion of in-flight and later commit, never expiry or absence alone. Decoding establishes integrity, not authenticated producer provenance. + +The internal Account settlement composition obtains exact historical protection and any already-retained terminal receipt in an independent writable read-committed transaction. It calls the authenticated Game Session terminal reader outside SQL, persists only the exact fully bound terminal value in a separate Account transaction, and verifies it through an independent lookup-only post-commit readback. An uncertain commit or absent readback remains unresolved; retry recovers the same immutable result without renewing authority or replaying the admission mutation. Settlement follows the existing source-lock-before-protection ordering and preserves source exclusion until its commit. This internal recovery does not create an external settlement permission or runtime registration; its unexecuted producer, consumer and physical proof gates remain in the linked tracker. + ## REST APIs | Method | Path | Description | diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 6ae13e0634..a00ea99f97 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -192,3 +192,9 @@ Entry format: - Observation: Bare `CASE` expressions inside a PL/pgSQL `IF` boolean chain repeat the earlier source-guard parse hazard. A successful simulator run cannot prove that PostgreSQL accepts the procedural function or executes its constraints. - Expected pattern: Parenthesize `CASE` expression operands in procedural conditions and retain physical Flyway startup plus positive and negative owner cases as a separate proof gate. Report startup cascades separately from actual owner assertion failures. - Current status: The two expression operands are parenthesized without changing their mappings or rejection guards; physical PostgreSQL re-execution remains required. + +- `2026-10-10`: Native TLS-denial probes must target the bound loopback address + - Context: PR #3105's missing-client-certificate test passed locally but failed twice in GitHub CI before the Account PostgreSQL stage. + - Observation: Originating XML finally showed an IPv6 `localhost` connection refusal while the test server listened only on IPv4. A failed connection and zero handler calls do not establish TLS rejection, and reporting only a boolean matcher initially concealed the transport cause. + - Expected pattern: Match the client endpoint to the server's explicit loopback bind and certificate SAN, retain bounded cause-chain diagnostics, and check certificate rejection separately from absence of application calls. Never broaden a TLS matcher to accept generic connection failure. + - Current status: Both test clients use the existing `127.0.0.1` bind/SAN, the strict matcher and required client certificate are unchanged, and grouped assertions retain all denial evidence. All four native acquisition mTLS cases pass locally; corrected CI execution remains required. 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 1b9b4ea141..6a27bafc4b 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 @@ -6,11 +6,17 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Distinct original-StartSession Account admission protection is prepared under [ADR 0047's canonical lifecycle](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection). It authenticates the original Game Session receiving workload, obtains the exact current original-attempt observation outside SQL, then revalidates the original actor/JTI/reference and unchanged complete capture through the existing Account currentness callback. V133 retains the complete request, actual mutation/attempt/fence and unchanged finite expiry, original World participation, full World hold, immutable capture and exact source children; additive writer/disclosure hooks preserve the existing assembled owner checks. A settled World row supplies historical binding, not current authority: acquisition must freshly prove unchanged original sources after a gap. Independent lookup-only readback returns the first protection unchanged. V129 World settlement and V131 observation are unchanged. Every V133 settlement insertion remains denied pending genuine authenticated Game Session terminal composition; expiry, missing or ambiguous proof cannot release protection. The producer remains unregistered and does not enable admission. +Distinct original-StartSession Account admission protection is prepared under [ADR 0047's canonical lifecycle](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection). It authenticates the original Game Session receiving workload, obtains the exact current original-attempt observation outside SQL, then revalidates the original actor/JTI/reference and unchanged complete capture through the existing Account currentness callback. V133 retains the complete request, actual mutation/attempt/fence and unchanged finite expiry, original World participation, full World hold, immutable capture and exact source children; additive writer/disclosure hooks preserve the existing assembled owner checks. A settled World row supplies historical binding, not current authority: acquisition must freshly prove unchanged original sources after a gap. Independent lookup-only readback returns the first protection unchanged. V129 World settlement and V131 observation are unchanged. Forward V134 prepares closed terminal-settlement integrity checks and preserves the existing immutable receipt and source-writer guards; expiry, missing or ambiguous proof cannot release protection. The producer and settlement composition remain unregistered and do not enable admission. The prepared acquisition transport exposes the [closed Account RPC](../../../protos/account/v1/start_session_admission_protection_acquisition.proto), with the mTLS client in Common Security so it can reject authenticated end-user context before transport. Its caller supplies the complete original tuple, actual Game Session mutation/attempt/fence and full World hold, not private Account participation coordinates; Account resolves the unchanged retained participation within its fresh currentness callback. It authenticates the exact Game Session workload before parsing and returns complete canonical evidence rather than selected hashes. The exact original PostgreSQL lease is retained at microsecond precision, with six canonical fractional digits and no rounding or renewal. V133 compares the full World hold's canonical `sha256:`-prefixed digest. Nine repository integrity definitions cover exact retained sub-millisecond expiry, changed caller expiry without modifying the stored row, and forged digest rejection; five real-Account producer definitions cover acquisition/retry/readback, lost acknowledgement, changed sources after World settlement, protection beyond World settlement and expiry, and expiry while waiting for the original issuance lock. The expired-protection case also verifies full historical lookup-only readback without renewal or settlement. Logging, Game Session and World collaborators are stipulated; these definitions do not establish genuine cross-owner execution. -The distinct terminal-read carrier and Common Security client bind the complete Account protection echo to the existing canonical Game Session owner proof, accept only exact `COMMITTED` or positively fenced `ABORTED`, and reject pending or substituted evidence. Historical Account lookup validates the immutable parent, original capture and complete source children without consulting live expiry or releasing protection. Terminal storage and automatic reconciliation remain unimplemented; every V133 settlement insertion is still denied. The corrected composed Common Platform, Common Security and Account full checks, formatting, Checkstyle, SpotBugs, coverage, integration compilation and Account boot JAR pass in 2m40s. XML retains 587, 146 and 1,312 unit cases respectively, with zero failures, errors or skips; unchanged successful tasks reuse results. All four native loopback acquisition mTLS cases execute and pass with the real Common client but a mocked Account owner. Terminal codec and client tests use synthetic or stubbed evidence, not a genuine Game Session transaction or terminal socket. Account executes seven non-container integration cases and skips 284 of 291 definitions without Docker, including all nine V133 and five producer cases. Compilation and discovery are not PostgreSQL execution proof. Earlier schema generation and Flyway sanity pass 12 sets and 290 versioned files; no migration changes accompany this correction. +The distinct terminal-read carrier and Common Security client bind the complete Account protection echo to the existing canonical Game Session owner proof, accept only exact `COMMITTED` or positively fenced `ABORTED`, and reject pending or substituted evidence. Historical Account lookup validates the immutable parent, original capture and complete source children without consulting live expiry or releasing protection. The internal settlement composition now prepares historical receipt lookup, authenticated remote read outside SQL, an immutable full-evidence settlement transaction, and independent post-commit lookup-only readback. The repository locks the original source rows before the protection, exact-compares the retained winner, and does not use expiry as a release condition. V134 validates the complete canonical Account envelope and existing framed Game Session proof, including the exact next pointer, positive audit identity or durable abort, original hold, source vector and digest; these SQL integrity checks do not authenticate the producer. Automatic scanning/reconciliation, genuine authenticated Game Session terminal composition and corrected physical PostgreSQL execution remain open. The previous published acquisition batch's Common Platform, Common Security and Account full checks pass in 2m40s with 587, 146 and 1,312 unit cases respectively, zero failures, errors or skips. That batch executes seven non-container Account integration cases and skips 284 of 291 definitions without Docker; those results are not proof of the new V134 batch. + +The corrected Common Platform/Account full gate passes in 49s, including formatting, Checkstyle, SpotBugs, coverage, Account schema generation, integration compilation and boot JAR. Successful unchanged tasks reuse their originating results: Common Platform has 591 unit cases and Account has 1,322, with zero failures, errors or skips. These include seven mocked settlement-ordering cases and four native acquisition mTLS cases with a mocked Account owner. Account integration has 299 definitions: twelve non-container cases execute and 287 skip without Docker. Three added PostgreSQL definitions reuse the genuine Account issuer/acquisition fixture for historical terminal release, exact abort/retry and raw malformed/conflicting settlement denial; all three skip locally, and their Game Session and World terminal values remain stipulated. They do not establish authenticated upstream transactions or end-to-end admission. The recovered gate's Mockito-only JDBC resource warnings are corrected with narrow test-local annotations and explicit connection, statement and result-set closure assertions; no production guard is suppressed. The native missing-client-certificate matcher remains strict, while bounded cause-chain reporting and grouped assertions retain the no-handler/no-owner evidence even when its matcher assertion fails. No runtime registration, source grant or production durability adoption follows. + +Exact source `e6b0d6d2b901e785c955bbf5f8c606578adfdc15` [Validation run 38038069636](https://github.com/benhook1013/FireMUD/actions/runs/38038069636) failed its required gate. Account's 1,312 unit cases have one failure: the missing-client-certificate probe resolved `localhost` to IPv6 while its server bound IPv4, and the originating cause is connection refusal before TLS. That run supplies no certificate-policy proof and never executes Account integration tests. Both local test clients now target the existing `127.0.0.1` server binding and certificate SAN without changing required-client-certificate or matcher policy; corrected native cases pass locally, while corrected CI remains required. Game Design's 151 integration cases and World's 221 execute with no failures, errors or skips, including the five genuine Game Design source/export cases and eighteen World authored-source/mTLS intake cases. The selected-export fixture still stipulates Entity/Automation participant digests, in-memory S3 and the StartSession Account projection: this is bounded physical source/release proof, not complete four-owner publication or gameplay admission. Tested merge `6dfe4e4a298685446cdceeb9073d7029c090361a`, tree `4c585a242d909c0648c76e003c19fb60928d276c`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, rather than the recorded integration parent. + +Fresh Entity/Automation empty-source receipts remain concrete producer obligations. Entity currently has partial numeric-tenant storage for items, NPCs, recipes/ingredients, equipment slots and body layouts, but no typed provider for fourteen of the required 23 inventory families. Automation has script definitions, event bindings and patch/base identity, with retained unbound rows still denied. Neither owner has a complete canonical-UUID census, shared writer exclusion and immutable selected-source receipt/readback. Missing tables, a declared empty array, a synthetic version marker or an unqualified zero query cannot prove owner absence; existing numeric content cannot be assigned by borrowing Game Design's private key. The next cut must establish the actual fresh owner scope and full census before replacing stipulated publication participants. Exact source `1f9f673095e4ac8f5bb6b9c0a969469854de4d86` [Validation run 38035808533](https://github.com/benhook1013/FireMUD/actions/runs/38035808533) failed the required gate: Account executed 1,304 unit cases with one missing-client-certificate matcher assertion failure. Retained XML and logs omit the transport exception/cause, so its cause and subsequent no-handler assertions are unproved for that run. The local corrected batch preserves the strict TLS matcher and required client certificate, adds failure diagnostics, and executes all four native cases successfully without weakening denial. Account's integration task never ran in that CI run; no PostgreSQL durability or acquisition proof follows. The tested merge `2be00c0c20e4feb76097547b9e9992c53e3ae6e3` has tree `96a7913e52c5ce281c81093e1b225fb3e9344ee2` and ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, not the separately recorded integration parent. The approved failure-only diagnostic now maps bounded captured WAL relation locators through the same run-owned database's current catalog after failure; missing, reused, changed or cross-database locators remain inconclusive. It has no executed PostgreSQL result and establishes neither historical relation identity, backend origin nor timing causation. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java index 093cff5f7d..7e2c05b794 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java @@ -24,9 +24,11 @@ import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCapture; import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionSettlement; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; @@ -50,6 +52,8 @@ public class AccountStartSessionAdmissionProtectionRepository { private static final String PROTECTIONS = "account_start_session_admission_protections"; private static final String SOURCES = "account_start_session_admission_protection_sources"; + private static final String SETTLEMENTS = + "account_start_session_admission_protection_settlements"; private static final String CAPTURES = "account_start_session_authority_captures"; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final Set PROTECTION_COLUMNS = @@ -87,6 +91,8 @@ public class AccountStartSessionAdmissionProtectionRepository { "canonical_sha256", "canonical_capture_bytes", "canonical_snapshot_bytes"); + private static final Set SETTLEMENT_COLUMNS = + Set.of("protection_id", "outcome", "terminal_bytes", "terminal_digest", "settled_at"); private static final Set CAPTURE_SNAPSHOT_FIELDS = Set.of( "schema", @@ -247,6 +253,190 @@ public Optional findHistoricalEx return Optional.of(decodeAndRequireExact(row, request, capture, expectedSources)); } + /** + * Inserts an exact terminal settlement or returns the immutable winner on an exact retry. + * + *

This runs only after the authenticated owner terminal read has completed outside SQL. It + * locks the original canonical source-lock rows before the immutable protection row, compares the + * complete historical Account evidence without consulting live expiry, and writes the outcome + * derived from the typed owner proof. The database trigger repeats the closed structural binding + * checks; neither layer authenticates the remote producer. + */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSettlement settleExact(AccountStartSessionAdmissionProtectionSettlement settlement) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(settlement, "exact admission protection settlement is required"); + AccountStartSessionAdmissionProtectionEvidence expectedEvidence = + settlement.protectionEvidence(); + UUID protectionId = expectedEvidence.accountProtectionId(); + long protectionFence = expectedEvidence.accountProtectionFence(); + + lockOriginalSourceRows(expectedEvidence); + Record locked = selectById(protectionId, true); + if (locked == null + || !protectionId.equals(requiredUuid(locked, "protection_id")) + || protectionFence != positive(requiredLong(locked, "protection_fence"))) { + throw unavailable(); + } + AccountStartSessionAdmissionProtectionEvidence retainedEvidence = + findHistoricalExact(protectionId, protectionFence) + .orElseThrow(AccountStartSessionAdmissionProtectionRepository::unavailable); + requireSameEvidence(expectedEvidence, retainedEvidence); + + byte[] terminalBytes = settlement.canonicalBytes(); + dsl.execute( + "INSERT INTO " + + SETTLEMENTS + + " (protection_id, outcome, terminal_bytes, terminal_digest) VALUES (?, ?, ?, ?) " + + "ON CONFLICT (protection_id) DO NOTHING", + protectionId, + settlement.outcome().name(), + terminalBytes, + settlement.digest()); + StoredSettlement stored = + readSettlementExact(protectionId, protectionFence, retainedEvidence) + .orElseThrow(AccountStartSessionAdmissionProtectionRepository::unavailable); + AccountStartSessionAdmissionProtectionSettlement storedSettlement = stored.settlement(); + if (!Arrays.equals(terminalBytes, storedSettlement.canonicalBytes()) + || !settlement.digest().equals(storedSettlement.digest()) + || settlement.outcome() != stored.outcome()) { + throw conflict(); + } + return stored; + } + + /** + * Lookup-only historical settlement read. It validates the full retained protection and + * settlement binding but never checks current authority or either original expiry. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findSettlementExact(UUID protectionId, long protectionFence) { + requireWritableReadCommittedTransaction(); + if (protectionId == null || NIL_UUID.equals(protectionId) || protectionFence <= 0L) { + throw unavailable(); + } + Optional evidence = + findHistoricalExact(protectionId, protectionFence); + if (evidence.isEmpty()) return Optional.empty(); + return readSettlementExact(protectionId, protectionFence, evidence.get()); + } + + private void lockOriginalSourceRows( + AccountStartSessionAdmissionProtectionEvidence expectedEvidence) { + UUID protectionId = expectedEvidence.accountProtectionId(); + long protectionFence = expectedEvidence.accountProtectionFence(); + Record observed = selectById(protectionId, false); + if (observed == null + || !protectionId.equals(requiredUuid(observed, "protection_id")) + || protectionFence != positive(requiredLong(observed, "protection_fence"))) { + throw unavailable(); + } + + AccountStartSessionAdmissionProtectionRequest retainedRequest; + try { + retainedRequest = + AccountStartSessionAdmissionProtectionRequest.decode( + requiredBytes(observed, "request_binding_bytes")); + } catch (RuntimeException malformed) { + throw unavailable(); + } + if (!MessageDigest.isEqual( + retainedRequest.canonicalBytes(), expectedEvidence.request().canonicalBytes())) { + throw conflict(); + } + Record captureRow = selectCaptureForOriginalTuple(retainedRequest.originalTuple(), false); + if (captureRow == null) throw unavailable(); + CaptureValue capture = captureFromRow(captureRow); + List expectedSources = + sourceVector(capture.snapshotBytes(), retainedRequest.originalTuple()); + requireExactSources(expectedSources, expectedEvidence.sourceEvidenceVector()); + + // The captured vector is already in canonical Java string order. Lock one existing source + // lock row at a time in that order, matching the V129 owner-before-protection lock discipline. + for (SourceEvidence source : expectedSources) { + Record sourceLock = + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks " + + "WHERE source_key = ? FOR UPDATE NOWAIT", + source.key()); + if (sourceLock == null || !source.key().equals(requiredString(sourceLock, "source_key"))) { + throw unavailable(); + } + } + } + + private Optional readSettlementExact( + UUID protectionId, + long protectionFence, + AccountStartSessionAdmissionProtectionEvidence expectedEvidence) { + Record row = + dsl.fetchOne("SELECT * FROM " + SETTLEMENTS + " WHERE protection_id = ?", protectionId); + if (row == null) return Optional.empty(); + try { + requireColumns(row, SETTLEMENT_COLUMNS, "admission protection settlement"); + if (!protectionId.equals(requiredUuid(row, "protection_id"))) throw unavailable(); + String outcome = requiredString(row, "outcome"); + byte[] terminalBytes = requiredBytes(row, "terminal_bytes"); + String terminalDigest = requiredString(row, "terminal_digest"); + Instant settledAt = requiredTimestamp(row, "settled_at").toInstant(); + if (!terminalDigest.equals(digestPrefixed(terminalBytes))) throw unavailable(); + + AccountStartSessionAdmissionProtectionSettlement settlement; + try { + settlement = AccountStartSessionAdmissionProtectionSettlement.decode(terminalBytes); + } catch (RuntimeException malformed) { + throw unavailable(); + } + AccountStartSessionAdmissionProtectionEvidence retainedEvidence = + settlement.protectionEvidence(); + if (!Arrays.equals(terminalBytes, settlement.canonicalBytes()) + || !terminalDigest.equals(settlement.digest()) + || !outcome.equals(settlement.outcome().name()) + || !protectionId.equals(retainedEvidence.accountProtectionId()) + || protectionFence != retainedEvidence.accountProtectionFence()) { + throw conflict(); + } + requireSameEvidence(expectedEvidence, retainedEvidence); + return Optional.of(new StoredSettlement(settlement, settledAt)); + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && ("StartSession admission protection is unavailable".equals(state.getMessage()) + || "StartSession admission protection conflicts with its immutable binding" + .equals(state.getMessage()))) { + throw state; + } + throw unavailable(); + } + } + + private static void requireSameEvidence( + AccountStartSessionAdmissionProtectionEvidence expected, + AccountStartSessionAdmissionProtectionEvidence actual) { + if (!MessageDigest.isEqual(expected.canonicalBytes(), actual.canonicalBytes())) + throw conflict(); + } + + /** Immutable database receipt for one exact original Game Session terminal value. */ + public record StoredSettlement( + AccountStartSessionAdmissionProtectionSettlement settlement, Instant settledAt) { + public StoredSettlement { + Objects.requireNonNull(settlement, "settlement is required"); + Objects.requireNonNull(settledAt, "settledAt is required"); + } + + public UUID protectionId() { + return settlement.protectionEvidence().accountProtectionId(); + } + + public long protectionFence() { + return settlement.protectionEvidence().accountProtectionFence(); + } + + public GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome() { + return settlement.outcome(); + } + } + private int insert( AccountStartSessionAdmissionProtectionRequest request, AccountStartSessionAuthorityCapture capture, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java new file mode 100644 index 0000000000..eb05274f2b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java @@ -0,0 +1,239 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository.StoredSettlement; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionSettlement; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalReadClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalResult; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered internal Account recovery composition for exact original StartSession admission + * protection settlement. + * + *

This is not an external settlement permission or runtime registration. Historical terminal + * recovery neither checks live expiry/currentness nor creates a new admission grant. The repository + * owns source-lock-before-protection ordering and immutable retained-row comparison. + */ +public final class AccountStartSessionAdmissionProtectionSettlementService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AccountStartSessionAdmissionProtectionRepository repository; + private final OriginalStartSessionAdmissionTerminalReadClient gameSessionClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public AccountStartSessionAdmissionProtectionSettlementService( + AccountStartSessionAdmissionProtectionRepository repository, + OriginalStartSessionAdmissionTerminalReadClient gameSessionClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = + Objects.requireNonNull(repository, "admission protection repository required"); + this.gameSessionClient = + Objects.requireNonNull(gameSessionClient, "Game Session terminal client required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager required")); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Settles or recovers one exact historical protection. The ID/fence are lookup selectors only; + * all terminal-read identity is derived from retained Account evidence. + */ + public StoredSettlement settle(UUID protectionId, long protectionFence) { + requireNoAuthenticatedEndUser(); + requireNoAmbientTransaction(); + if (protectionId == null || NIL_UUID.equals(protectionId) || protectionFence <= 0L) { + throw new IllegalArgumentException( + "Non-nil Account protection ID and positive fence required"); + } + + Lookup lookup = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> { + AccountStartSessionAdmissionProtectionEvidence evidence = + repository + .findHistoricalExact(protectionId, protectionFence) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Exact historical Account admission protection is unavailable") + .asRuntimeException()); + requireExactProtection(evidence, protectionId, protectionFence); + String retainedNamespace = + evidence + .request() + .originalTuple() + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace(); + if (!workloadNamespace.equals(retainedNamespace)) { + throw Status.PERMISSION_DENIED + .withDescription( + "Account admission protection target namespace differs from configuration") + .asRuntimeException(); + } + Optional receipt = + repository.findSettlementExact(protectionId, protectionFence); + return new Lookup(evidence, receipt.orElse(null)); + }), + "Account historical protection transaction returned no result"); + if (lookup.receipt() != null) { + return requireReceipt(lookup.receipt(), lookup.evidence(), protectionId, protectionFence); + } + + OriginalStartSessionAdmissionTerminalRequest request = + new OriginalStartSessionAdmissionTerminalRequest(lookup.evidence().canonicalBytes()); + requireNoAmbientTransaction(); + OriginalStartSessionAdmissionTerminalResult remoteResult = gameSessionClient.read(request); + requireNoAmbientTransaction(); + if (remoteResult == null) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Original Game Session admission outcome remains unresolved without terminal evidence") + .asRuntimeException(); + } + if (!request.equals(remoteResult.request()) + || !Arrays.equals(request.canonicalBytes(), remoteResult.request().canonicalBytes())) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Game Session terminal result did not echo the complete Account protection evidence") + .asRuntimeException(); + } + OriginalStartSessionAdmissionTerminalResult exactResult = + new OriginalStartSessionAdmissionTerminalResult(request, remoteResult.ownerProof()); + if (!Arrays.equals(remoteResult.canonicalBytes(), exactResult.canonicalBytes())) { + throw Status.FAILED_PRECONDITION + .withDescription("Game Session terminal result is not its exact typed owner proof") + .asRuntimeException(); + } + AccountStartSessionAdmissionProtectionSettlement settlement = + AccountStartSessionAdmissionProtectionSettlement.create(exactResult); + + requireNoAmbientTransaction(); + StoredSettlement committed = + Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.settleExact(settlement)), + "Account terminal settlement transaction returned no receipt"); + requireReceipt(committed, lookup.evidence(), protectionId, protectionFence); + if (!settlement.digest().equals(committed.settlement().digest()) + || settlement.outcome() != committed.outcome() + || !Arrays.equals(settlement.canonicalBytes(), committed.settlement().canonicalBytes())) { + throw Status.FAILED_PRECONDITION + .withDescription("Account settlement repository returned a different terminal value") + .asRuntimeException(); + } + + // This separate lookup is intentionally read-only at the repository API level. In particular, + // never call settleExact here: doing so could conceal an unknown first commit as an exact + // retry. + requireNoAmbientTransaction(); + StoredSettlement readback = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository + .findSettlementExact(protectionId, protectionFence) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Committed Account admission settlement is not readable") + .asRuntimeException())), + "Account terminal settlement readback transaction returned no receipt"); + requireReceipt(readback, lookup.evidence(), protectionId, protectionFence); + if (!sameSettlement(committed, readback)) { + throw Status.FAILED_PRECONDITION + .withDescription("Committed Account admission settlement readback differs") + .asRuntimeException(); + } + return readback; + } + + private static void requireNoAuthenticatedEndUser() { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription("Internal Account terminal recovery rejects end-user context") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Account terminal settlement requires independent transactions") + .asRuntimeException(); + } + } + + private static void requireExactProtection( + AccountStartSessionAdmissionProtectionEvidence evidence, + UUID protectionId, + long protectionFence) { + if (!protectionId.equals(evidence.accountProtectionId()) + || protectionFence != evidence.accountProtectionFence()) { + throw Status.FAILED_PRECONDITION + .withDescription("Historical Account protection differs from its exact lookup identity") + .asRuntimeException(); + } + } + + private static StoredSettlement requireReceipt( + StoredSettlement receipt, + AccountStartSessionAdmissionProtectionEvidence evidence, + UUID protectionId, + long protectionFence) { + Objects.requireNonNull(receipt, "stored Account settlement receipt is required"); + Objects.requireNonNull(receipt.settledAt(), "stored Account settlement timestamp is required"); + AccountStartSessionAdmissionProtectionSettlement settlement = + Objects.requireNonNull(receipt.settlement(), "stored Account settlement value is required"); + if (!protectionId.equals(receipt.protectionId()) + || protectionFence != receipt.protectionFence() + || !protectionId.equals(settlement.protectionEvidence().accountProtectionId()) + || protectionFence != settlement.protectionEvidence().accountProtectionFence() + || receipt.outcome() != settlement.outcome() + || !Arrays.equals( + evidence.canonicalBytes(), settlement.protectionEvidence().canonicalBytes())) { + throw Status.FAILED_PRECONDITION + .withDescription("Stored Account settlement differs from exact historical protection") + .asRuntimeException(); + } + return receipt; + } + + private static boolean sameSettlement(StoredSettlement left, StoredSettlement right) { + return left.protectionId().equals(right.protectionId()) + && left.protectionFence() == right.protectionFence() + && left.outcome() == right.outcome() + && left.settledAt().equals(right.settledAt()) + && left.settlement().digest().equals(right.settlement().digest()) + && Arrays.equals(left.settlement().canonicalBytes(), right.settlement().canonicalBytes()); + } + + private record Lookup( + AccountStartSessionAdmissionProtectionEvidence evidence, StoredSettlement receipt) {} +} diff --git a/services/account-service/src/main/resources/db/migration/V134__start_session_admission_protection_settlement.sql b/services/account-service/src/main/resources/db/migration/V134__start_session_admission_protection_settlement.sql new file mode 100644 index 0000000000..d4742176be --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V134__start_session_admission_protection_settlement.sql @@ -0,0 +1,470 @@ +-- Immutable Account settlement for the exact original Game Session admission proof. +-- This guard validates retained structure and integrity only. It does not authenticate +-- the remote producer; the internal Game Session client owns that provenance boundary. +-- [jooq ignore start] +CREATE FUNCTION account_ss_admission_settlement_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_admission_protections%ROWTYPE; + capture account_start_session_authority_captures%ROWTYPE; + existing account_start_session_admission_protection_settlements%ROWTYPE; + terminal_json JSONB; + evidence_json JSONB; + hold_json JSONB; + hold_request_json JSONB; + snapshot_json JSONB; + evidence_bytes BYTEA; + owner_proof_bytes BYTEA; + canonical_outer TEXT; + canonical_evidence TEXT; + canonical_request TEXT; + canonical_hold TEXT; + canonical_hold_request TEXT; + source_vector TEXT; + source_count BIGINT; + source_bytes_total BIGINT; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + previous_sort_key INTEGER[]; + current_sort_key INTEGER[]; + position_value INTEGER := 1; + frame_next_position INTEGER; + parsed BYTEA; + marker TEXT; + proof_schema TEXT; + proof_hold_bytes BYTEA; + proof_outcome TEXT; + pointer_marker TEXT; + pointer_text TEXT; + audit_marker TEXT; + audit_text TEXT; + digest_marker TEXT; + proof_digest TEXT; + abort_value TEXT; + terminal_marker TEXT; + terminal_at_text TEXT; + terminal_stem TEXT; + expected_pointer NUMERIC; + prior_pointer NUMERIC; + original_request JSONB; +BEGIN + SELECT * INTO STRICT original + FROM account_start_session_admission_protections + WHERE protection_id = NEW.protection_id; + + IF NEW.outcome NOT IN ('COMMITTED', 'ABORTED') + OR NEW.terminal_bytes IS NULL + OR octet_length(NEW.terminal_bytes) NOT BETWEEN 1 AND 25165824 + OR NEW.terminal_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') THEN + RAISE EXCEPTION 'Malformed original StartSession admission settlement' + USING ERRCODE = '23514'; + END IF; + + -- Reconstructing the complete outer object makes duplicate keys, alternate escaping, + -- trailing input, and non-RFC8785 ordering fail byte-for-byte. + terminal_json := convert_from(NEW.terminal_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(terminal_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(terminal_json)) <> 3 + OR NOT (terminal_json ?& ARRAY[ + 'schema', 'canonicalAccountProtectionEvidenceBytesBase64', + 'canonicalGameSessionOwnerProofBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(terminal_json) field + WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR terminal_json->>'schema' IS DISTINCT FROM + 'account-start-session-admission-protection-settlement/v1' THEN + RAISE EXCEPTION 'Original StartSession admission settlement is not the closed envelope' + USING ERRCODE = '23514'; + END IF; + evidence_bytes := decode(terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64', 'base64'); + owner_proof_bytes := decode(terminal_json->>'canonicalGameSessionOwnerProofBytesBase64', 'base64'); + IF octet_length(evidence_bytes) NOT BETWEEN 1 AND 8388608 + OR octet_length(owner_proof_bytes) NOT BETWEEN 1 AND 66048 + OR regexp_replace(encode(evidence_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64' + OR regexp_replace(encode(owner_proof_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM terminal_json->>'canonicalGameSessionOwnerProofBytesBase64' THEN + RAISE EXCEPTION 'Original StartSession admission settlement has invalid canonical Base64' + USING ERRCODE = '23514'; + END IF; + canonical_outer := '{"canonicalAccountProtectionEvidenceBytesBase64":"' + || (terminal_json->>'canonicalAccountProtectionEvidenceBytesBase64') + || '","canonicalGameSessionOwnerProofBytesBase64":"' + || (terminal_json->>'canonicalGameSessionOwnerProofBytesBase64') + || '","schema":"account-start-session-admission-protection-settlement/v1"}'; + IF convert_to(canonical_outer, 'UTF8') IS DISTINCT FROM NEW.terminal_bytes THEN + RAISE EXCEPTION 'Original StartSession admission settlement is not canonical JSON' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO STRICT capture + FROM account_start_session_authority_captures + WHERE control_plane_request_id = original.control_plane_request_id; + IF capture.source_version IS DISTINCT FROM original.capture_source_version + OR capture.source_fence IS DISTINCT FROM original.capture_source_fence + OR capture.canonical_sha256 IS DISTINCT FROM original.capture_sha256 + OR octet_length(capture.canonical_capture_bytes) NOT BETWEEN 1 AND 262144 + OR octet_length(capture.canonical_snapshot_bytes) NOT BETWEEN 1 AND 245760 + OR capture.canonical_sha256 IS DISTINCT FROM + encode(sha256(capture.canonical_capture_bytes), 'hex') + OR capture.snapshot_sha256 IS DISTINCT FROM + encode(sha256(capture.canonical_snapshot_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession admission capture differs from retained protection' + USING ERRCODE = '23514'; + END IF; + + -- The immutable Account request is a closed ten-string object. Rebuild its canonical + -- representation from the retained parent so the settlement cannot bind a projection. + canonical_request := '{"accountRedemptionProjectionBytesBase64":"' + || regexp_replace(encode(original.account_redemption_projection, 'base64'), E'[\n\r]', '', 'g') + || '","accountWorldParticipationFence":"' + || original.account_world_participation_fence::TEXT + || '","accountWorldParticipationId":"' + || original.account_world_participation_id::TEXT + || '","gameSessionOwnerAttemptId":"' + || original.game_session_owner_attempt_id::TEXT + || '","gameSessionOwnerFence":"' + || original.game_session_owner_fence::TEXT + || '","gameSessionOwnerMutationId":"' + || original.game_session_owner_mutation_id::TEXT + || '","originalLeaseExpiresAt":"' + || to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + || '","originalPostAuthorizationTupleBytesBase64":"' + || regexp_replace(encode(original.original_post_authorization_tuple, 'base64'), E'[\n\r]', '', 'g') + || '","schema":"account-start-session-admission-protection-request/v1"' + || ',"worldAdmissionHoldIdentityBytesBase64":"' + || regexp_replace(encode(original.world_admission_hold_identity_bytes, 'base64'), E'[\n\r]', '', 'g') + || '"}'; + IF octet_length(original.request_binding_bytes) NOT BETWEEN 1 AND 786432 + OR octet_length(original.world_admission_hold_identity_bytes) NOT BETWEEN 1 AND 65536 + OR convert_to(canonical_request, 'UTF8') IS DISTINCT FROM original.request_binding_bytes + OR original.request_binding_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(original.request_binding_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession admission request is not its exact canonical binding' + USING ERRCODE = '23514'; + END IF; + + snapshot_json := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_json->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_json->>'controlPlaneRequestId' IS DISTINCT FROM original.control_plane_request_id + OR jsonb_typeof(snapshot_json->'sourceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_json->'sourceVector') NOT BETWEEN 1 AND 256 THEN + RAISE EXCEPTION 'Original StartSession admission source capture is incomplete' + USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO source_count + FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id; + SELECT COALESCE(sum(octet_length(source_evidence)), 0) INTO source_bytes_total + FROM account_start_session_admission_protection_sources + WHERE protection_id = original.protection_id; + IF source_count IS DISTINCT FROM jsonb_array_length(snapshot_json->'sourceVector')::BIGINT + OR source_bytes_total > 4194304 THEN + RAISE EXCEPTION 'Original StartSession admission source children are incomplete' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_json->'sourceVector') LOOP + IF jsonb_typeof(source_value) IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'Original StartSession source vector has a non-string member' + USING ERRCODE = '23514'; + END IF; + source_bytes := decode(source_value #>> '{}', 'base64'); + IF octet_length(source_bytes) NOT BETWEEN 1 AND 131072 + OR regexp_replace(encode(source_bytes, 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM source_value #>> '{}' THEN + RAISE EXCEPTION 'Original StartSession source vector has noncanonical bytes' + USING ERRCODE = '23514'; + END IF; + source_key_value := account_start_session_world_participation_source_key(source_bytes); + current_sort_key := account_publication_authorization_source_sort_key(source_key_value); + IF previous_sort_key IS NOT NULL AND current_sort_key <= previous_sort_key THEN + RAISE EXCEPTION 'Original StartSession source vector is duplicated or out of order' + USING ERRCODE = '23514'; + END IF; + previous_sort_key := current_sort_key; + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_admission_protection_sources source + WHERE source.protection_id = original.protection_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Original StartSession source child differs from its immutable capture' + USING ERRCODE = '23514'; + END IF; + END LOOP; + + SELECT string_agg( + '"' || regexp_replace(encode(source.source_evidence, 'base64'), E'[\n\r]', '', 'g') || '"', + ',' ORDER BY account_publication_authorization_source_sort_key(source.source_key)) + INTO source_vector + FROM account_start_session_admission_protection_sources source + WHERE source.protection_id = original.protection_id; + canonical_evidence := '{"accountProtectionFence":"' || original.protection_fence::TEXT + || '","accountProtectionId":"' || original.protection_id::TEXT + || '","originalSourceCaptureReferenceBytesBase64":"' + || regexp_replace(encode(capture.canonical_capture_bytes, 'base64'), E'[\n\r]', '', 'g') + || '","originalSourceCaptureReferenceSha256":"' || capture.canonical_sha256 + || '","requestBytesBase64":"' + || regexp_replace(encode(original.request_binding_bytes, 'base64'), E'[\n\r]', '', 'g') + || '","schema":"account-start-session-admission-protection-evidence/v1"' + || ',"sourceEvidenceVector":[' || source_vector || ']}'; + IF convert_to(canonical_evidence, 'UTF8') IS DISTINCT FROM evidence_bytes THEN + RAISE EXCEPTION 'Original StartSession admission evidence differs from its full retained binding' + USING ERRCODE = '23514'; + END IF; + + -- Validate the exact retained World hold identity and request, including the original + -- target and the pointer precondition used to derive a committed next pointer. + hold_json := convert_from(original.world_admission_hold_identity_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(hold_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_json)) <> 5 + OR NOT (hold_json ?& ARRAY['schema', 'holdId', 'holdFence', 'holdBindingDigest', 'requestBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(hold_json) field + WHERE jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR hold_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is malformed' + USING ERRCODE = '23514'; + END IF; + IF (hold_json->>'holdId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR (hold_json->>'holdFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR hold_json->>'holdId' IS DISTINCT FROM (hold_json->>'holdId')::UUID::TEXT + OR hold_json->>'holdFence' IS DISTINCT FROM (hold_json->>'holdFence')::UUID::TEXT THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is nil' + USING ERRCODE = '23514'; + END IF; + hold_request_json := convert_from(decode(hold_json->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + IF regexp_replace(encode(decode(hold_json->>'requestBytesBase64', 'base64'), 'base64'), E'[\n\r]', '', 'g') + IS DISTINCT FROM hold_json->>'requestBytesBase64' + OR hold_json->>'holdBindingDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(decode(hold_json->>'requestBytesBase64', 'base64')), 'hex') + OR jsonb_typeof(hold_request_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json)) <> 2 + OR NOT (hold_request_json ?& ARRAY['schema', 'request']) + OR hold_request_json->>'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR jsonb_typeof(hold_request_json->'request') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(hold_request_json->'request')) <> 14 + OR NOT (hold_request_json->'request' ?& ARRAY[ + 'activeLifecycleEpoch', 'canonicalGameInstanceId', 'canonicalTenantId', + 'canonicalVersionId', 'expectedCatalogRevision', 'expectedPriorPointerVersion', + 'initialAdmissionOrigin', 'initialAdmissionRequestDigest', + 'initialAdmissionRequestId', 'playableStateNamespaceId', 'playableStateScope', + 'realmId', 'targetNamespace', 'worldSlug']) + OR hold_request_json->'request'->>'targetNamespace' IS DISTINCT FROM original.target_namespace + OR hold_request_json->'request'->>'canonicalTenantId' IS DISTINCT FROM original.canonical_tenant_id::TEXT + OR hold_request_json->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM original.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'Original StartSession admission hold request differs from retained protection' + USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT 1 FROM jsonb_each(hold_request_json->'request') field + WHERE field.key <> 'expectedPriorPointerVersion' + AND jsonb_typeof(field.value) IS DISTINCT FROM 'string') + OR jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') NOT IN ('string', 'null') THEN + RAISE EXCEPTION 'Original StartSession hold request fields have invalid JSON types' + USING ERRCODE = '23514'; + END IF; + canonical_hold_request := '{"request":{"activeLifecycleEpoch":' + || to_json(hold_request_json->'request'->>'activeLifecycleEpoch')::TEXT + || ',"canonicalGameInstanceId":' + || to_json(hold_request_json->'request'->>'canonicalGameInstanceId')::TEXT + || ',"canonicalTenantId":' + || to_json(hold_request_json->'request'->>'canonicalTenantId')::TEXT + || ',"canonicalVersionId":' + || to_json(hold_request_json->'request'->>'canonicalVersionId')::TEXT + || ',"expectedCatalogRevision":' + || to_json(hold_request_json->'request'->>'expectedCatalogRevision')::TEXT + || ',"expectedPriorPointerVersion":' + || CASE + WHEN jsonb_typeof(hold_request_json->'request'->'expectedPriorPointerVersion') = 'null' + THEN 'null' + ELSE to_json(hold_request_json->'request'->>'expectedPriorPointerVersion')::TEXT + END + || ',"initialAdmissionOrigin":' + || to_json(hold_request_json->'request'->>'initialAdmissionOrigin')::TEXT + || ',"initialAdmissionRequestDigest":' + || to_json(hold_request_json->'request'->>'initialAdmissionRequestDigest')::TEXT + || ',"initialAdmissionRequestId":' + || to_json(hold_request_json->'request'->>'initialAdmissionRequestId')::TEXT + || ',"playableStateNamespaceId":' + || to_json(hold_request_json->'request'->>'playableStateNamespaceId')::TEXT + || ',"playableStateScope":' + || to_json(hold_request_json->'request'->>'playableStateScope')::TEXT + || ',"realmId":' + || to_json(hold_request_json->'request'->>'realmId')::TEXT + || ',"targetNamespace":' + || to_json(hold_request_json->'request'->>'targetNamespace')::TEXT + || ',"worldSlug":' + || to_json(hold_request_json->'request'->>'worldSlug')::TEXT + || '},"schema":"world-canonical-initial-admission-hold-request/v1"}'; + IF convert_to(canonical_hold_request, 'UTF8') IS DISTINCT FROM + decode(hold_json->>'requestBytesBase64', 'base64') THEN + RAISE EXCEPTION 'Original StartSession hold request is not canonical JSON' + USING ERRCODE = '23514'; + END IF; + canonical_hold := '{"holdBindingDigest":"' || (hold_json->>'holdBindingDigest') + || '","holdFence":"' || (hold_json->>'holdFence') + || '","holdId":"' || (hold_json->>'holdId') + || '","requestBytesBase64":"' || (hold_json->>'requestBytesBase64') + || '","schema":"world-canonical-initial-admission-hold-identity/v1"}'; + IF convert_to(canonical_hold, 'UTF8') IS DISTINCT FROM original.world_admission_hold_identity_bytes THEN + RAISE EXCEPTION 'Original StartSession admission hold identity is not canonical' + USING ERRCODE = '23514'; + END IF; + + -- The actual Game Session codec frames the hold and seven terminal fields. Do not treat + -- its opaque terminal proof digest as permission; only the exact COMMITTED/ABORTED shape + -- below may settle this immutable Account binding. + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + proof_schema := convert_from(parsed, 'UTF8'); + position_value := frame_next_position; + SELECT frame.frame_value, frame.next_position INTO proof_hold_bytes, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + proof_outcome := convert_from(parsed, 'UTF8'); + + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + pointer_marker := convert_from(parsed, 'UTF8'); + IF pointer_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + pointer_text := convert_from(parsed, 'UTF8'); + ELSIF pointer_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal pointer frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + audit_marker := convert_from(parsed, 'UTF8'); + IF audit_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + audit_text := convert_from(parsed, 'UTF8'); + ELSIF audit_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal audit frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + digest_marker := convert_from(parsed, 'UTF8'); + IF digest_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + proof_digest := convert_from(parsed, 'UTF8'); + ELSIF digest_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal digest frame is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + abort_value := convert_from(parsed, 'UTF8'); + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + terminal_marker := convert_from(parsed, 'UTF8'); + IF terminal_marker = 'PRESENT' THEN + SELECT frame.frame_value, frame.next_position INTO parsed, frame_next_position + FROM account_publication_authorization_read_frame(owner_proof_bytes, position_value) AS frame; + position_value := frame_next_position; + terminal_at_text := convert_from(parsed, 'UTF8'); + ELSIF terminal_marker IS DISTINCT FROM 'ABSENT' THEN + RAISE EXCEPTION 'Original StartSession terminal timestamp frame is malformed' USING ERRCODE = '23514'; + END IF; + IF position_value <> octet_length(owner_proof_bytes) + 1 + OR proof_schema IS DISTINCT FROM 'game-session-canonical-initial-admission-owner-proof/v1' + OR proof_hold_bytes IS DISTINCT FROM original.world_admission_hold_identity_bytes + OR proof_digest IS NULL OR proof_digest !~ '^sha256:[0-9a-f]{64}$' + OR terminal_at_text IS NULL + OR terminal_at_text !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{3}|\.[0-9]{6}|\.[0-9]{9})?Z$' + OR terminal_at_text ~ '\.000Z$' + OR terminal_at_text ~ '\.[0-9]{3}000Z$' + OR terminal_at_text ~ '\.[0-9]{6}000Z$' + OR abort_value NOT IN ('true', 'false') THEN + RAISE EXCEPTION 'Original StartSession owner proof is malformed or differs from its hold' + USING ERRCODE = '23514'; + END IF; + -- Validate the calendar/time stem separately. Casting the complete fraction to + -- TIMESTAMPTZ would round nanoseconds to PostgreSQL microseconds and could silently + -- accept noncanonical Java Instant text; the exact frame bytes remain authoritative. + terminal_stem := to_char( + substring(terminal_at_text FROM 1 FOR 19)::TIMESTAMP WITHOUT TIME ZONE, + 'YYYY-MM-DD"T"HH24:MI:SS'); + IF terminal_stem IS DISTINCT FROM substring(terminal_at_text FROM 1 FOR 19) THEN + RAISE EXCEPTION 'Original StartSession owner proof timestamp stem is not normalized' + USING ERRCODE = '23514'; + END IF; + original_request := hold_request_json->'request'; + IF proof_outcome = 'COMMITTED' THEN + IF pointer_marker IS DISTINCT FROM 'PRESENT' + OR pointer_text IS NULL OR pointer_text !~ '^[1-9][0-9]{0,18}$' + OR audit_marker IS DISTINCT FROM 'PRESENT' + OR audit_text IS NULL OR audit_text !~ '^[1-9][0-9]{0,18}$' + OR abort_value IS DISTINCT FROM 'false' THEN + RAISE EXCEPTION 'Committed Game Session terminal proof has invalid outcome fields' + USING ERRCODE = '23514'; + END IF; + IF original_request->>'initialAdmissionOrigin' = 'NO_PRIOR_POINTER' + AND original_request->'expectedPriorPointerVersion' = 'null'::JSONB THEN + expected_pointer := 1; + ELSIF original_request->>'initialAdmissionOrigin' = 'EXPECT_CLOSED' + AND jsonb_typeof(original_request->'expectedPriorPointerVersion') = 'string' + AND original_request->>'expectedPriorPointerVersion' ~ '^[1-9][0-9]{0,18}$' THEN + prior_pointer := (original_request->>'expectedPriorPointerVersion')::NUMERIC; + IF prior_pointer >= 9223372036854775807 THEN + RAISE EXCEPTION 'Original StartSession pointer version cannot advance without overflow' + USING ERRCODE = '23514'; + END IF; + expected_pointer := prior_pointer + 1; + ELSE + RAISE EXCEPTION 'Original StartSession hold has an invalid pointer precondition' + USING ERRCODE = '23514'; + END IF; + IF pointer_text::NUMERIC IS DISTINCT FROM expected_pointer THEN + RAISE EXCEPTION 'Committed Game Session terminal proof does not name the exact next pointer' + USING ERRCODE = '23514'; + END IF; + PERFORM audit_text::BIGINT; + IF NEW.outcome IS DISTINCT FROM 'COMMITTED' THEN + RAISE EXCEPTION 'Account settlement outcome differs from Game Session owner proof' + USING ERRCODE = '23514'; + END IF; + ELSIF proof_outcome = 'ABORTED' THEN + IF pointer_marker IS DISTINCT FROM 'ABSENT' + OR audit_marker IS DISTINCT FROM 'ABSENT' + OR abort_value IS DISTINCT FROM 'true' + OR NEW.outcome IS DISTINCT FROM 'ABORTED' THEN + RAISE EXCEPTION 'Aborted Game Session terminal proof lacks positive durable exclusion' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'Pending or unsupported Game Session owner proof cannot settle protection' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO existing + FROM account_start_session_admission_protection_settlements + WHERE protection_id = NEW.protection_id; + IF FOUND AND (existing.outcome IS DISTINCT FROM NEW.outcome + OR existing.terminal_bytes IS DISTINCT FROM NEW.terminal_bytes + OR existing.terminal_digest IS DISTINCT FROM NEW.terminal_digest) THEN + RAISE EXCEPTION 'Original StartSession admission terminal settlement conflicts with its first receipt' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +DROP TRIGGER account_ss_admission_settlements_disabled + ON account_start_session_admission_protection_settlements; +CREATE TRIGGER account_ss_admission_settlements_validate + BEFORE INSERT ON account_start_session_admission_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_admission_settlement_insert_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java index 196561b722..1499798a4c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java @@ -2,9 +2,20 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.List; +import javax.sql.DataSource; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; class AccountPostgresIntegrationFixtureTest { private static final String V90_DETAIL = @@ -115,4 +126,183 @@ void rejectsRemoteCredentialBearingAndOptionBearingUrls() { .hasMessageContaining(AccountPostgresIntegrationFixture.JDBC_URL_ENV); } } + + @Test + void invalidMissingOversizedAndLocatorFreeDumpsDoNotAccessDatabase() { + DataSource dataSource = mock(DataSource.class); + for (String dump : + List.of( + "no relation locator", + "blkref #0: rel 4294967296/42/99", + "blkref #0: rel 42/4294967296/99", + "blkref #0: rel 42/99/4294967296")) { + assertThat( + AccountPostgresIntegrationFixture.mapWalRelationLocatorsAfterFailure( + dump, dataSource)) + .contains("inconclusive"); + } + assertThat( + AccountPostgresIntegrationFixture.mapWalRelationLocatorsAfterFailure(null, dataSource)) + .contains("unavailable"); + assertThat( + AccountPostgresIntegrationFixture.mapWalRelationLocatorsAfterFailure( + "x".repeat(49_409), dataSource)) + .contains("unavailable"); + verifyNoInteractions(dataSource); + } + + @Test + @SuppressFBWarnings( + value = {"ODR_OPEN_DATABASE_RESOURCE", "OBL_UNSATISFIED_OBLIGATION"}, + justification = + "The JDBC values in this test are Mockito mocks; the mapper under test owns and closes its connection, statement, and result set with try-with-resources.") + void validLocatorUsesOneBoundedPreparedCurrentCatalogQuery() throws Exception { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + PreparedStatement statement = mock(PreparedStatement.class); + ResultSet rows = mock(ResultSet.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.prepareStatement(org.mockito.ArgumentMatchers.anyString())) + .thenReturn(statement); + when(statement.executeQuery()).thenReturn(rows); + when(rows.next()).thenReturn(true, false); + stubCatalogRow( + rows, "firemud", "16384", "1663", "16384", "24600", "24610", "public", "account", "r", "0", + "24600"); + + String mapping = + AccountPostgresIntegrationFixture.mapWalRelationLocatorsAfterFailure( + "blkref #0: rel 1663/16384/24600", dataSource); + + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(connection).prepareStatement(sql.capture()); + assertThat(sql.getValue()) + .contains("pg_filenode_relation") + .contains("pg_relation_filenode(c.oid)") + .contains("pg_database") + .contains("current_database()"); + verify(statement).setQueryTimeout(5); + ArgumentCaptor indexes = ArgumentCaptor.forClass(Integer.class); + ArgumentCaptor values = ArgumentCaptor.forClass(String.class); + verify(statement, org.mockito.Mockito.times(3)).setString(indexes.capture(), values.capture()); + assertThat(indexes.getAllValues()).containsExactly(1, 2, 3); + assertThat(values.getAllValues()).containsExactly("1663", "16384", "24600"); + verify(dataSource).getConnection(); + verify(rows).close(); + verify(statement).close(); + verify(connection).close(); + assertThat(mapping) + .contains("public.account") + .contains("relation_oid=24610") + .contains("current mapping only") + .contains("reuse and causation not excluded") + .contains("current database: firemud oid=16384"); + } + + @Test + void crossDatabaseMissingAndChangedCatalogMappingsStayInconclusive() throws Exception { + for (String[] row : + List.of( + new String[] { + "firemud", "16384", "1663", "16385", "24576", null, null, null, null, null, null + }, + new String[] { + "firemud", "16384", "1663", "16384", "24576", null, null, null, null, null, null + }, + new String[] { + "firemud", "16384", "1663", "16384", "24576", "24600", "public", "account", "r", "0", + "24601" + })) { + DataSource dataSource = catalogDataSource(row); + String mapping = + AccountPostgresIntegrationFixture.mapWalRelationLocatorsAfterFailure( + "blkref #0: rel 1663/16384/24576", dataSource); + assertThat(mapping).contains("inconclusive"); + assertThat(mapping) + .containsAnyOf("different database", "no current mapping", "identity inconclusive"); + } + } + + @Test + void databaseLookupFailureReturnsBoundedUnavailableDiagnostic() throws Exception { + DataSource dataSource = mock(DataSource.class); + when(dataSource.getConnection()).thenThrow(new SQLException("sensitive connection detail")); + + String diagnostic = + AccountPostgresIntegrationFixture.mapWalRelationLocatorsAfterFailure( + "blkref #0: rel 1663/16384/24576", dataSource); + + assertThat(diagnostic).isEqualTo("WAL relation mapping unavailable: SQLException"); + assertThat(diagnostic).doesNotContain("sensitive connection detail"); + } + + @Test + void occurrenceAndDistinctLimitsKeepCoverageExplicitlyIncomplete() throws Exception { + String repeated = "blkref #0: rel 1663/16384/24576\n".repeat(257); + assertThat(mapWithRows(repeated, 1)) + .contains("occurrence limit reached") + .contains("mapping coverage is incomplete") + .contains("omitted or invalid locators are inconclusive"); + + StringBuilder manyDistinct = new StringBuilder(); + for (int index = 1; index <= 33; index++) { + manyDistinct.append("blkref #0: rel 1663/16384/").append(24_000 + index).append('\n'); + } + assertThat(mapWithRows(manyDistinct.toString(), 32)) + .contains("distinct-locator limit reached") + .contains("mapping coverage is incomplete") + .contains("omitted or invalid locators are inconclusive"); + } + + @SuppressFBWarnings( + value = "OBL_UNSATISFIED_OBLIGATION", + justification = + "These JDBC values are Mockito mocks; the mapper under test owns and closes its connection, statement, and result set with try-with-resources.") + private static String mapWithRows(String dump, int rowCount) throws Exception { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + PreparedStatement statement = mock(PreparedStatement.class); + ResultSet rows = mock(ResultSet.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.prepareStatement(org.mockito.ArgumentMatchers.anyString())) + .thenReturn(statement); + when(statement.executeQuery()).thenReturn(rows); + when(rows.next()).thenReturn(true, false); + String node = rowCount == 1 ? "24576" : "24001"; + stubCatalogRow( + rows, "firemud", "16384", "1663", "16384", node, "24610", "public", "account", "r", "0", + node); + String diagnostic = + AccountPostgresIntegrationFixture.mapWalRelationLocatorsAfterFailure(dump, dataSource); + verify(statement, org.mockito.Mockito.times(rowCount * 3)) + .setString(org.mockito.ArgumentMatchers.anyInt(), org.mockito.ArgumentMatchers.anyString()); + verify(rows).close(); + verify(statement).close(); + verify(connection).close(); + return diagnostic; + } + + @SuppressFBWarnings( + value = "OBL_UNSATISFIED_OBLIGATION", + justification = + "These JDBC values are Mockito mocks returned through a fake DataSource; the mapper under test owns and closes its connection, statement, and result set with try-with-resources.") + private static DataSource catalogDataSource(String[] values) throws Exception { + DataSource dataSource = mock(DataSource.class); + Connection connection = mock(Connection.class); + PreparedStatement statement = mock(PreparedStatement.class); + ResultSet rows = mock(ResultSet.class); + when(dataSource.getConnection()).thenReturn(connection); + when(connection.prepareStatement(org.mockito.ArgumentMatchers.anyString())) + .thenReturn(statement); + when(statement.executeQuery()).thenReturn(rows); + when(rows.next()).thenReturn(true, false); + stubCatalogRow(rows, values); + return dataSource; + } + + private static void stubCatalogRow(ResultSet rows, String... values) throws Exception { + for (int index = 0; index < values.length; index++) { + when(rows.getString(index + 1)).thenReturn(values[index]); + } + } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index 3ca848953b..7cdea75093 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -343,9 +343,9 @@ void immutableRowsAndUnprovedTerminalCannotReleaseProtection() { .execute( "INSERT INTO account_start_session_admission_protection_settlements (protection_id, outcome, terminal_bytes, terminal_digest) VALUES (?, 'ABORTED', ?, ?)", fixture.protectionId(), - bytes("unproved"), - "sha256:" + hash(bytes("unproved")))) - .hasMessageContaining("append-only"); + malformedSettlementBytes(), + "sha256:" + hash(malformedSettlementBytes()))) + .hasMessageContaining("not the closed envelope"); assertThat( fixture .dsl() @@ -879,6 +879,13 @@ private static byte[] bytes(String value) { return value.getBytes(StandardCharsets.UTF_8); } + private static byte[] malformedSettlementBytes() { + return bytes( + "{\"canonicalAccountProtectionEvidenceBytesBase64\":\"\"," + + "\"canonicalGameSessionOwnerProofBytesBase64\":\"\"," + + "\"schema\":\"account-start-session-admission-protection-settlement/v2\"}"); + } + private static byte[] json(Map value) { return AccountControlUiAuthority.canonical(value); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java index 62f43a34a2..09a5eca363 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java @@ -8,6 +8,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -46,15 +47,21 @@ import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.Snapshot; import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionSettlement; import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalResult; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; @@ -79,10 +86,11 @@ /** * PostgreSQL proof that the real Account issuer, signed actor, original capture, redemption, - * currentness callback, World participation and V133 producer compose into admission protection. - * Logging claim evidence, the Game Session current-attempt client, and World hold/terminal values - * are stipulated test collaborators. This proves no genuine upstream producer, authenticated - * cross-service transport, Game Session terminal settlement, runtime registration, or activation. + * currentness callback, World participation and V134 storage compose into admission protection and + * exact terminal settlement. Logging claim evidence, the Game Session current-attempt client, and + * World/Game Session hold/terminal values are stipulated test collaborators. This proves no genuine + * upstream producer, authenticated cross-service transport, Game Session terminal owner + * transaction, runtime registration, or activation. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -345,6 +353,236 @@ void settledWorldAndExpiredOriginalLeaseDoNotReleasePendingAccountSourceProtecti } } + @Test + void exactHistoricalSettlementAfterExpiryReleasesSourcesOnlyAfterCommit() throws Exception { + try (Prepared prepared = prepare(Duration.ofSeconds(10))) { + AccountStartSessionAdmissionProtectionEvidence protection = + prepared.acquire(prepared.acquisitionService(prepared.account.manager)); + prepared.settleWorldWithStipulatedTerminal(); + Instant expiry = protection.request().originalLeaseExpiresAt(); + awaitDatabaseTime(prepared.account.dsl, expiry.plusMillis(100), Duration.ofSeconds(15)); + + var repository = new AccountStartSessionAdmissionProtectionRepository(prepared.account.dsl); + var settlement = + terminalSettlement( + protection, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + Instant.parse("2026-10-10T04:05:06.123456789Z")); + CountDownLatch receiptInserted = new CountDownLatch(1); + CountDownLatch allowCommit = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var settling = + executor.submit( + () -> + prepared.account.transactions.execute( + ignored -> { + repository.settleExact(settlement); + receiptInserted.countDown(); + awaitLatch(allowCommit); + return null; + })); + assertThat(receiptInserted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat( + rowCount( + prepared.account.dsl, "account_start_session_admission_protection_settlements")) + .isZero(); + + var blockedWriter = + executor.submit( + () -> { + try { + return prepared.account.tx(prepared.account::changeRoleToAdmin); + } catch (RuntimeException failure) { + return failure; + } + }); + Object beforeCommitResult = blockedWriter.get(20, TimeUnit.SECONDS); + assertThat(beforeCommitResult).isInstanceOf(RuntimeException.class); + assertPostgresSqlState((RuntimeException) beforeCommitResult, "55P03"); + assertThat( + prepared + .account + .accounts + .findById(prepared.account.account.getId()) + .orElseThrow() + .getRole()) + .isEqualTo(prepared.account.account.getRole()); + + allowCommit.countDown(); + settling.get(20, TimeUnit.SECONDS); + } finally { + allowCommit.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + + var stored = + prepared.account.tx( + () -> + repository + .findSettlementExact( + protection.accountProtectionId(), protection.accountProtectionFence()) + .orElseThrow()); + assertThat(stored.settlement().canonicalBytes()).containsExactly(settlement.canonicalBytes()); + assertThat(stored.settlement().protectionEvidence().canonicalBytes()) + .containsExactly(protection.canonicalBytes()); + assertThat(stored.outcome()) + .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(stored.settledAt()).isNotNull(); + + Account changed = prepared.account.tx(prepared.account::changeRoleToAdmin); + assertThat(changed.getRole()).isEqualTo("admin"); + assertThat( + rowCount( + prepared.account.dsl, "account_start_session_admission_protection_settlements")) + .isEqualTo(1L); + } + } + + @Test + void settlementInsertGuardRejectsMalformedBindingDigestPendingAndNoncanonicalInstant() + throws Exception { + try (Prepared prepared = prepare(Duration.ofSeconds(90))) { + AccountStartSessionAdmissionProtectionEvidence protection = + prepared.acquire(prepared.acquisitionService(prepared.account.manager)); + var committed = + terminalSettlement( + protection, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + Instant.parse("2026-10-10T04:05:06.123456789Z")); + byte[] exactProofBytes = committed.result().canonicalBytes(); + + assertRawSettlementRejected( + prepared, + "COMMITTED", + settlementEnvelope( + protection.canonicalBytes(), + exactProofBytes, + "account-start-session-admission-protection-settlement/v2"), + settlementDigest( + settlementEnvelope( + protection.canonicalBytes(), + exactProofBytes, + "account-start-session-admission-protection-settlement/v2"))); + + byte[] changedEvidence = protection.canonicalBytes(); + String changedEvidenceJson = + new String(changedEvidence, StandardCharsets.UTF_8) + .replace( + "\"accountProtectionFence\":\"" + protection.accountProtectionFence() + "\"", + "\"accountProtectionFence\":\"" + + (protection.accountProtectionFence() + 1) + + "\""); + byte[] changedEvidenceBytes = Rfc8785CanonicalJson.canonicalizeUtf8(changedEvidenceJson); + assertThat(changedEvidenceBytes).isNotEqualTo(protection.canonicalBytes()); + byte[] changedBindingEnvelope = settlementEnvelope(changedEvidenceBytes, exactProofBytes); + assertRawSettlementRejected( + prepared, "COMMITTED", changedBindingEnvelope, settlementDigest(changedBindingEnvelope)); + + byte[] validEnvelope = committed.canonicalBytes(); + assertRawSettlementRejected(prepared, "COMMITTED", validEnvelope, "sha256:" + "0".repeat(64)); + + byte[] pendingProof = + ownerProofBytes( + protection, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING, + null, + null, + null, + false, + null); + byte[] pendingEnvelope = settlementEnvelope(protection.canonicalBytes(), pendingProof); + assertRawSettlementRejected( + prepared, "COMMITTED", pendingEnvelope, settlementDigest(pendingEnvelope)); + + byte[] noncanonicalTimestampProof = + ownerProofBytesWithTerminalText( + protection, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + "2026-10-10T04:05:06.123000Z"); + byte[] noncanonicalTimestampEnvelope = + settlementEnvelope(protection.canonicalBytes(), noncanonicalTimestampProof); + assertRawSettlementRejected( + prepared, + "COMMITTED", + noncanonicalTimestampEnvelope, + settlementDigest(noncanonicalTimestampEnvelope)); + + var stored = + prepared.account.tx( + () -> + new AccountStartSessionAdmissionProtectionRepository(prepared.account.dsl) + .settleExact(committed)); + assertThat(stored.settlement().canonicalBytes()).containsExactly(committed.canonicalBytes()); + + var aborted = + terminalSettlement( + protection, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + Instant.parse("2026-10-10T04:05:07.123456789Z")); + byte[] conflictingEnvelope = aborted.canonicalBytes(); + assertRawSettlementRejected( + prepared, "ABORTED", conflictingEnvelope, settlementDigest(conflictingEnvelope)); + var exactRetry = + prepared.account.tx( + () -> + new AccountStartSessionAdmissionProtectionRepository(prepared.account.dsl) + .findSettlementExact( + protection.accountProtectionId(), protection.accountProtectionFence()) + .orElseThrow()); + assertThat(exactRetry.settlement().canonicalBytes()) + .containsExactly(committed.canonicalBytes()); + assertThat( + rowCount( + prepared.account.dsl, "account_start_session_admission_protection_settlements")) + .isEqualTo(1L); + } + } + + @Test + void exactAbortedSettlementRetryAndReadbackPreserveTheFirstReceipt() throws Exception { + try (Prepared prepared = prepare(Duration.ofSeconds(90))) { + AccountStartSessionAdmissionProtectionEvidence protection = + prepared.acquire(prepared.acquisitionService(prepared.account.manager)); + var repository = new AccountStartSessionAdmissionProtectionRepository(prepared.account.dsl); + var settlement = + terminalSettlement( + protection, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + Instant.parse("2026-10-10T04:05:08.123456789Z")); + + var first = prepared.account.tx(() -> repository.settleExact(settlement)); + var exactRetry = prepared.account.tx(() -> repository.settleExact(settlement)); + var historicalReadback = + prepared.account.tx( + () -> + repository + .findSettlementExact( + protection.accountProtectionId(), protection.accountProtectionFence()) + .orElseThrow()); + + assertThat(first.settlement().canonicalBytes()).containsExactly(settlement.canonicalBytes()); + assertThat(exactRetry.settlement().canonicalBytes()) + .containsExactly(settlement.canonicalBytes()); + assertThat(historicalReadback.settlement().canonicalBytes()) + .containsExactly(settlement.canonicalBytes()); + assertThat(historicalReadback.settlement().digest()).isEqualTo(settlement.digest()); + assertThat(historicalReadback.protectionId()).isEqualTo(protection.accountProtectionId()); + assertThat(historicalReadback.protectionFence()) + .isEqualTo(protection.accountProtectionFence()); + assertThat(historicalReadback.outcome()) + .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + assertThat(historicalReadback.settlement().protectionEvidence().canonicalBytes()) + .containsExactly(protection.canonicalBytes()); + assertProtectionRow(prepared, protection); + assertThat( + rowCount( + prepared.account.dsl, "account_start_session_admission_protection_settlements")) + .isEqualTo(1L); + } + } + @Test void leaseExpiryDuringRealOriginalActorIssuanceLockWaitDeniesDespiteTimelyRemoteRead() throws Exception { @@ -757,6 +995,122 @@ private static AccountStartSessionAdmissionProtectionEvidence readCurrentProtect () -> new IllegalStateException("Committed protection readback missing"))); } + private static AccountStartSessionAdmissionProtectionSettlement terminalSettlement( + AccountStartSessionAdmissionProtectionEvidence protection, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome, + Instant terminalAt) { + var hold = protection.request().worldAdmissionHoldIdentity(); + var proof = + switch (outcome) { + case COMMITTED -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, outcome, 1L, 23L, "sha256:" + "d".repeat(64), false, terminalAt); + case ABORTED -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, outcome, null, null, "sha256:" + "d".repeat(64), true, terminalAt); + case PENDING -> throw new IllegalArgumentException("Pending is not terminal evidence"); + }; + var result = + new OriginalStartSessionAdmissionTerminalResult( + new OriginalStartSessionAdmissionTerminalRequest(protection.canonicalBytes()), proof); + return AccountStartSessionAdmissionProtectionSettlement.create(result); + } + + private static byte[] ownerProofBytes( + AccountStartSessionAdmissionProtectionEvidence protection, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome, + String pointerVersion, + String auditEventId, + String proofDigest, + boolean positiveDurableAbort, + String terminalAt) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + output, "game-session-canonical-initial-admission-owner-proof/v1"); + DraftAuthorizationFenceBinding.frame( + output, protection.request().worldAdmissionHoldIdentity().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(output, outcome.name()); + frameOptional(output, pointerVersion); + frameOptional(output, auditEventId); + frameOptional(output, proofDigest); + DraftAuthorizationFenceBinding.frame(output, positiveDurableAbort ? "true" : "false"); + frameOptional(output, terminalAt); + return output.toByteArray(); + } + + private static byte[] ownerProofBytesWithTerminalText( + AccountStartSessionAdmissionProtectionEvidence protection, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome, + String terminalAt) { + return ownerProofBytes( + protection, outcome, "1", "23", "sha256:" + "d".repeat(64), false, terminalAt); + } + + private static void frameOptional(ByteArrayOutputStream output, String value) { + if (value == null) { + DraftAuthorizationFenceBinding.frame(output, "ABSENT"); + } else { + DraftAuthorizationFenceBinding.frame(output, "PRESENT"); + DraftAuthorizationFenceBinding.frame(output, value); + } + } + + private static byte[] settlementEnvelope(byte[] evidence, byte[] ownerProof) { + return settlementEnvelope( + evidence, ownerProof, "account-start-session-admission-protection-settlement/v1"); + } + + private static byte[] settlementEnvelope(byte[] evidence, byte[] ownerProof, String schema) { + String canonical = + "{\"canonicalAccountProtectionEvidenceBytesBase64\":\"" + + Base64.getEncoder().encodeToString(evidence) + + "\",\"canonicalGameSessionOwnerProofBytesBase64\":\"" + + Base64.getEncoder().encodeToString(ownerProof) + + "\",\"schema\":\"" + + schema + + "\"}"; + return canonical.getBytes(StandardCharsets.UTF_8); + } + + private static String settlementDigest(byte[] bytes) { + return "sha256:" + sha256Hex(bytes); + } + + private static void assertRawSettlementRejected( + Prepared prepared, String outcome, byte[] bytes, String digest) { + long settlementCountBefore = + rowCount(prepared.account.dsl, "account_start_session_admission_protection_settlements"); + assertThatThrownBy( + () -> + prepared.account.tx( + () -> { + prepared.account.dsl.execute( + "INSERT INTO account_start_session_admission_protection_settlements " + + "(protection_id, outcome, terminal_bytes, terminal_digest) " + + "VALUES (?, ?, ?, ?)", + protectionRow(prepared).get("protection_id", UUID.class), + outcome, + bytes, + digest); + return null; + })) + .isInstanceOf(RuntimeException.class) + .satisfies(failure -> assertPostgresSqlState((RuntimeException) failure, "23514")); + assertThat( + rowCount( + prepared.account.dsl, "account_start_session_admission_protection_settlements")) + .isEqualTo(settlementCountBefore); + } + + private static void assertPostgresSqlState(RuntimeException failure, String expectedState) { + Throwable rootCause = failure; + while (rootCause.getCause() != null) rootCause = rootCause.getCause(); + assertThat(rootCause) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + postgresFailure -> assertThat(postgresFailure.getSQLState()).isEqualTo(expectedState)); + } + private static long rowCount(DSLContext dsl, String table) { return dsl.fetchSingle("SELECT count(*)::bigint AS row_count FROM " + table) .get("row_count", Long.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java index 887053b035..fb3d33df43 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java @@ -17,6 +17,7 @@ import java.sql.SQLException; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionSettlement; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import org.jooq.ConnectionRunnable; @@ -98,6 +99,60 @@ void historicalLookupRequiresWritableReadCommittedTransactionBeforeDatabaseAcces verifyNoInteractions(dsl); } + @Test + void settlementLookupRequiresWritableReadCommittedTransactionBeforeDatabaseAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountStartSessionAdmissionProtectionRepository repository = + new AccountStartSessionAdmissionProtectionRepository(dsl); + + assertThatThrownBy(() -> repository.findSettlementExact(PROTECTION_ID, PROTECTION_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + + verifyNoInteractions(dsl); + } + + @Test + void settlementWriteChecksTransactionBeforeInspectingTypedCarrier() { + DSLContext dsl = mock(DSLContext.class); + AccountStartSessionAdmissionProtectionRepository repository = + new AccountStartSessionAdmissionProtectionRepository(dsl); + AccountStartSessionAdmissionProtectionSettlement settlement = + mock(AccountStartSessionAdmissionProtectionSettlement.class); + + assertThatThrownBy(() -> repository.settleExact(settlement)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("READ_COMMITTED"); + + verifyNoInteractions(dsl, settlement); + } + + @Test + void settlementLookupRejectsMismatchedRetainedFenceBeforeCaptureOrReceiptRead() + throws SQLException { + DSLContext dsl = writableDsl(); + Record row = mock(Record.class); + when(row.get("protection_id", UUID.class)).thenReturn(PROTECTION_ID); + when(row.get("protection_fence", Long.class)).thenReturn(PROTECTION_FENCE + 1L); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(row); + AccountStartSessionAdmissionProtectionRepository repository = + new AccountStartSessionAdmissionProtectionRepository(dsl); + beginWritableReadCommittedTransaction(); + + assertThatThrownBy(() -> repository.findSettlementExact(PROTECTION_ID, PROTECTION_FENCE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unavailable"); + + ArgumentCaptor arguments = ArgumentCaptor.forClass(Object[].class); + verify(dsl, times(1)).fetchOne(contains("WHERE protection_id = ?"), arguments.capture()); + assertThat(arguments.getValue()).containsExactly(PROTECTION_ID); + verify(dsl, times(0)).fetch(anyString(), any(Object[].class)); + verify(dsl, times(0)) + .fetchOne( + contains("account_start_session_admission_protection_settlements"), + any(Object[].class)); + } + @Test void historicalLookupRejectsAMismatchedRetainedFenceBeforeCaptureOrSourceRead() throws SQLException { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java index ab021057dd..89d4b61a6c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionGrpcMtlsTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertAll; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -33,6 +34,7 @@ import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Base64; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -178,12 +180,14 @@ void missingClientCertificateIsRejectedByTlsBeforeHandlerOrOwner() throws Except .isInstanceOf(StatusRuntimeException.class) .satisfies( failure -> - assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) - .as("TLS rejection: %s; immediate cause: %s", failure, failure.getCause()) - .isTrue()); - - assertThat(server.handlerCalls()).hasValue(0); - verifyNoInteractions(owner); + assertAll( + "missing client certificate is rejected before application handling", + () -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as("TLS rejection cause chain: %s", describeCauseChain(failure)) + .isTrue(), + () -> assertThat(server.handlerCalls()).hasValue(0), + () -> verifyNoInteractions(owner))); } } @@ -266,7 +270,7 @@ service, countHandlerCalls, new GrpcPeerIdentityInterceptor(), endUserContext)) private static AccountStartSessionAdmissionProtectionAcquisitionGrpcClient newClient( int port, TestIdentity identity) throws Exception { var endpoints = new ServiceEndpointsProperties(); - endpoints.setAccountService("localhost:" + port); + endpoints.setAccountService("127.0.0.1:" + port); return new AccountStartSessionAdmissionProtectionAcquisitionGrpcClient( endpoints, pki.clientProperties(temporaryDirectory, identity), @@ -279,7 +283,7 @@ private static ClientTransport newClientWithoutIdentity(int port) throws Excepti tls.setPlaintext(false); tls.setCaCert(pki.caCertificatePem().toString()); ManagedChannel channel = - new GrpcChannelFactory().buildChannel("localhost:" + port, 6565, tls, false); + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false); return new ClientTransport(channel); } @@ -289,6 +293,34 @@ private static AccountStartSessionAdmissionProtectionAcquisitionInput input() { tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, hold(tuple)); } + private static String describeCauseChain(Throwable failure) { + final int maxCauses = 12; + final int maxMessageLength = 240; + var seen = new IdentityHashMap(); + var description = new StringBuilder(); + Throwable current = failure; + int causeCount = 0; + while (current != null && causeCount < maxCauses && seen.put(current, Boolean.TRUE) == null) { + if (causeCount > 0) description.append(" <- "); + description.append(current.getClass().getName()); + String message = current.getMessage(); + if (message != null && !message.isEmpty()) { + description.append(": "); + description.append( + message.length() <= maxMessageLength + ? message + : message.substring(0, maxMessageLength) + "…[truncated]"); + } + causeCount++; + current = current.getCause(); + } + if (current != null) { + description.append( + seen.containsKey(current) ? " <- [cause cycle]" : " <- [cause chain truncated]"); + } + return description.toString(); + } + private static AccountStartSessionAdmissionProtectionEvidence evidence( AccountStartSessionAdmissionProtectionAcquisitionInput input) { var tuple = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementServiceTest.java new file mode 100644 index 0000000000..4d08b71d4c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementServiceTest.java @@ -0,0 +1,621 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +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.Status; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.Connection; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository.StoredSettlement; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionSettlement; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalReadClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalResult; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Mocked producer/storage/transaction-control ordering only; not database or authenticated GS + * proof. + */ +class AccountStartSessionAdmissionProtectionSettlementServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID PROTECTION_ID = uuid("6b763f1d-c5bc-4080-b499-d29debc0a7b8"); + private static final UUID OTHER_PROTECTION_ID = uuid("af5f4dc2-5a8e-4c1a-9413-66ec60a35d80"); + private static final Instant EXPIRED_LEASE = Instant.parse("2020-01-02T03:04:05.123456Z"); + private static final Instant TERMINAL_AT = Instant.parse("2026-10-09T10:20:30Z"); + private static final Instant SETTLED_AT = Instant.parse("2026-10-09T10:21:30Z"); + private static final String PROOF_DIGEST = "sha256:" + "d".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void settlesCommittedAndAbortedWithExactTransactionAndNetworkOrderingEvenAfterExpiry() { + for (GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome : + List.of( + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)) { + Harness harness = new Harness(NAMESPACE); + Fixture fixture = fixture(NAMESPACE, PROTECTION_ID, 23L); + OriginalStartSessionAdmissionTerminalResult terminal = fixture.result(outcome); + AtomicReference stored = new AtomicReference<>(); + AtomicInteger receiptReads = new AtomicInteger(); + + when(harness.repository.findHistoricalExact(PROTECTION_ID, 23L)) + .thenAnswer( + ignored -> { + assertWritableReadCommittedTransaction(); + harness.steps.add("historical-protection"); + return Optional.of(fixture.evidence()); + }); + when(harness.repository.findSettlementExact(PROTECTION_ID, 23L)) + .thenAnswer( + ignored -> { + assertWritableReadCommittedTransaction(); + int read = receiptReads.incrementAndGet(); + harness.steps.add(read == 1 ? "prior-receipt" : "post-commit-readback"); + return read == 1 ? Optional.empty() : Optional.of(stored.get()); + }); + when(harness.client.read(any())) + .thenAnswer( + invocation -> { + assertNoSql(); + harness.steps.add("remote-game-session-read"); + OriginalStartSessionAdmissionTerminalRequest request = invocation.getArgument(0); + assertThat(request.canonicalBytes()) + .containsExactly(fixture.evidence().canonicalBytes()); + return terminal; + }); + when(harness.repository.settleExact(any())) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + harness.steps.add("persist-settlement"); + AccountStartSessionAdmissionProtectionSettlement settlement = + invocation.getArgument(0); + assertThat(settlement.protectionEvidence().canonicalBytes()) + .containsExactly(fixture.evidence().canonicalBytes()); + assertThat(settlement.ownerProof()).isEqualTo(terminal.ownerProof()); + StoredSettlement receipt = new StoredSettlement(settlement, SETTLED_AT); + stored.set(receipt); + return receipt; + }); + + StoredSettlement actual = harness.service.settle(PROTECTION_ID, 23L); + + assertThat(actual).isSameAs(stored.get()); + assertThat(actual.outcome()).isEqualTo(outcome); + if (outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + assertThat(actual.settlement().ownerProof().committedPointerVersion()).isEqualTo(1L); + assertThat(actual.settlement().ownerProof().auditEventId()).isPositive(); + assertThat(actual.settlement().ownerProof().positiveDurableAbort()).isFalse(); + } else { + assertThat(actual.settlement().ownerProof().committedPointerVersion()).isNull(); + assertThat(actual.settlement().ownerProof().auditEventId()).isNull(); + assertThat(actual.settlement().ownerProof().positiveDurableAbort()).isTrue(); + } + assertThat(actual.settlement().canonicalBytes()) + .containsExactly(stored.get().settlement().canonicalBytes()); + assertThat(harness.steps) + .containsExactly( + "historical-protection", + "prior-receipt", + "remote-game-session-read", + "persist-settlement", + "post-commit-readback"); + assertThat(harness.transactions.begins).isEqualTo(3); + assertThat(harness.transactions.commits).isEqualTo(3); + verify(harness.client).read(any()); + verify(harness.repository).settleExact(any()); + assertNoSql(); + } + } + + @Test + void alreadyRetainedReceiptMakesLostResponseRetryExactAndRemoteFree() { + Harness harness = new Harness(NAMESPACE); + Fixture fixture = fixture(NAMESPACE, PROTECTION_ID, 23L); + StoredSettlement receipt = + fixture.receipt(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, SETTLED_AT); + when(harness.repository.findHistoricalExact(PROTECTION_ID, 23L)) + .thenReturn(Optional.of(fixture.evidence())); + when(harness.repository.findSettlementExact(PROTECTION_ID, 23L)) + .thenReturn(Optional.of(receipt)); + + StoredSettlement recovered = harness.service.settle(PROTECTION_ID, 23L); + + assertThat(recovered).isSameAs(receipt); + assertThat(harness.transactions.begins).isEqualTo(1); + assertThat(harness.transactions.commits).isEqualTo(1); + verifyNoInteractions(harness.client); + verify(harness.repository, never()).settleExact(any()); + } + + @Test + void endUserAmbientTransactionsAndInvalidIdentityAreRejectedBeforeRepositoryAccess() { + Harness harness = new Harness(NAMESPACE); + SessionContext.setContext("123", List.of(), Map.of()); + assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(null, 0L)); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(null, 0L)); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(null, 0L)); + TransactionSynchronizationManager.clear(); + + assertThatThrownBy(() -> harness.service.settle(new UUID(0L, 0L), 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> harness.service.settle(PROTECTION_ID, 0L)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(harness.repository, harness.client); + assertThat(harness.transactions.begins).isZero(); + } + + @Test + void retainedNamespaceMustMatchConfiguredAccountWorkloadNamespace() { + Harness harness = new Harness(NAMESPACE); + Fixture fixture = fixture("other-runtime", PROTECTION_ID, 23L); + when(harness.repository.findHistoricalExact(PROTECTION_ID, 23L)) + .thenReturn(Optional.of(fixture.evidence())); + + assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(PROTECTION_ID, 23L)); + + verifyNoInteractions(harness.client); + verify(harness.repository, never()).findSettlementExact(any(), anyLong()); + assertThat(harness.transactions.commits).isZero(); + } + + @Test + void unavailableNullOrChangedFullRemoteEchoNeverReachesSettlementInsert() { + Fixture fixture = fixture(NAMESPACE, PROTECTION_ID, 23L); + + Harness unavailable = preparedHarness(fixture); + when(unavailable.client.read(any())).thenThrow(Status.UNAVAILABLE.asRuntimeException()); + assertStatus(Status.Code.UNAVAILABLE, () -> unavailable.service.settle(PROTECTION_ID, 23L)); + verify(unavailable.repository, never()).settleExact(any()); + + Harness missing = preparedHarness(fixture); + when(missing.client.read(any())).thenReturn(null); + assertStatus(Status.Code.FAILED_PRECONDITION, () -> missing.service.settle(PROTECTION_ID, 23L)); + verify(missing.repository, never()).settleExact(any()); + + Harness changedEcho = preparedHarness(fixture); + Fixture substituted = fixture(NAMESPACE, OTHER_PROTECTION_ID, 24L); + when(changedEcho.client.read(any())) + .thenReturn( + substituted.result(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> changedEcho.service.settle(PROTECTION_ID, 23L)); + verify(changedEcho.repository, never()).settleExact(any()); + assertThat(unavailable.transactions.commits).isEqualTo(1); + assertThat(missing.transactions.commits).isEqualTo(1); + assertThat(changedEcho.transactions.commits).isEqualTo(1); + } + + @Test + void unknownSettlementCommitPropagatesAndRetryRecoversReceiptWithoutRemoteReplay() { + Harness harness = new Harness(NAMESPACE); + Fixture fixture = fixture(NAMESPACE, PROTECTION_ID, 23L); + OriginalStartSessionAdmissionTerminalResult terminal = + fixture.result(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + AtomicReference receipt = new AtomicReference<>(); + AtomicInteger receiptReads = new AtomicInteger(); + when(harness.repository.findHistoricalExact(PROTECTION_ID, 23L)) + .thenReturn(Optional.of(fixture.evidence())); + when(harness.repository.findSettlementExact(PROTECTION_ID, 23L)) + .thenAnswer( + ignored -> + receiptReads.incrementAndGet() == 1 + ? Optional.empty() + : Optional.of(receipt.get())); + when(harness.client.read(any())).thenReturn(terminal); + when(harness.repository.settleExact(any())) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + receipt.set(new StoredSettlement(invocation.getArgument(0), SETTLED_AT)); + return receipt.get(); + }); + harness.transactions.failCommitAt = 2; + + assertThatThrownBy(() -> harness.service.settle(PROTECTION_ID, 23L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synthetic unknown commit"); + assertThat(receiptReads.get()).isEqualTo(1); + + assertThat(harness.service.settle(PROTECTION_ID, 23L)).isSameAs(receipt.get()); + + assertThat(receiptReads.get()).isEqualTo(2); + assertThat(harness.transactions.begins).isEqualTo(3); + verify(harness.client).read(any()); + verify(harness.repository).settleExact(any()); + } + + @Test + void missingOrMismatchedPostCommitReadbackRemainsUnresolved() { + Fixture fixture = fixture(NAMESPACE, PROTECTION_ID, 23L); + assertReadbackDoesNotSucceed(fixture, Optional.empty(), 2, 1); + StoredSettlement changedTime = + fixture.receipt( + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + SETTLED_AT.plusSeconds(1)); + assertReadbackDoesNotSucceed(fixture, Optional.of(changedTime), 3, 0); + } + + private static void assertReadbackDoesNotSucceed( + Fixture fixture, + Optional readback, + int expectedCommits, + int expectedRollbacks) { + Harness harness = new Harness(NAMESPACE); + OriginalStartSessionAdmissionTerminalResult terminal = + fixture.result(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + AtomicReference committed = new AtomicReference<>(); + AtomicInteger receiptReads = new AtomicInteger(); + when(harness.repository.findHistoricalExact(PROTECTION_ID, 23L)) + .thenReturn(Optional.of(fixture.evidence())); + when(harness.repository.findSettlementExact(PROTECTION_ID, 23L)) + .thenAnswer(ignored -> receiptReads.incrementAndGet() == 1 ? Optional.empty() : readback); + when(harness.client.read(any())).thenReturn(terminal); + when(harness.repository.settleExact(any())) + .thenAnswer( + invocation -> { + StoredSettlement result = new StoredSettlement(invocation.getArgument(0), SETTLED_AT); + committed.set(result); + return result; + }); + + assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(PROTECTION_ID, 23L)); + + assertThat(committed.get()).isNotNull(); + verify(harness.repository).settleExact(any()); + assertThat(harness.transactions.begins).isEqualTo(3); + assertThat(harness.transactions.commits).isEqualTo(expectedCommits); + assertThat(harness.transactions.rollbacks).isEqualTo(expectedRollbacks); + } + + private static Harness preparedHarness(Fixture fixture) { + Harness harness = new Harness(NAMESPACE); + when(harness.repository.findHistoricalExact(PROTECTION_ID, 23L)) + .thenReturn(Optional.of(fixture.evidence())); + when(harness.repository.findSettlementExact(PROTECTION_ID, 23L)).thenReturn(Optional.empty()); + return harness; + } + + private static void assertWritableReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(Connection.TRANSACTION_READ_COMMITTED); + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static void assertStatus(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static Fixture fixture(String namespace, UUID protectionId, long protectionFence) { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(namespace); + WorldCanonicalInitialAdmissionHold.HoldIdentity hold = hold(tuple, namespace); + AccountStartSessionAdmissionProtectionRequest request = + AccountStartSessionAdmissionProtectionRequest.create( + tuple.canonicalBytes(), + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + uuid("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"), + uuid("ec13cc04-ec15-4eb8-a018-c2c5e8da65f8"), + 21L, + EXPIRED_LEASE, + uuid("47b3be7f-a32f-4e19-8916-8c3b8da07a82"), + 22L, + hold); + byte[] captureReference = + canonical( + Map.of( + "schema", + AccountStartSessionAdmissionProtectionEvidence.SOURCE_CAPTURE_REFERENCE_SCHEMA, + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "capturedAt", + "2026-10-09T10:11:12.123Z", + "bundleReference", + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "sourceVersion", + "17", + "sourceFence", + "23", + "linearization", + "18446744073709551615"), + "snapshotSha256", + "a".repeat(64))); + AccountStartSessionAdmissionProtectionEvidence evidence = + AccountStartSessionAdmissionProtectionEvidence.create( + request, + protectionId, + protectionFence, + captureReference, + sha256(captureReference), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531").toString(), + "2", + "17", + null, + null, + "exact historical source evidence".getBytes(StandardCharsets.UTF_8)))); + return new Fixture(evidence); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(String namespace) { + UUID tenant = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + UUID actor = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "settlement-test", + actor, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenant, namespace), + new StartSessionOperatorAction.Target( + 91L, uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "original StartSession admission settlement fixture")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple, actor), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, UUID actor) { + UUID tenant = tuple.action().scope().tenantId(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant.toString(), 3L), + "membershipAuthorityGeneration", Map.of(tenant.toString(), 4L), + "privateRealmGrantVersions", List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", actor.toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + return canonical( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenant.toString(), + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actor.toString(), + "applicableTenantId", + tenant.toString()), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenant.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence)); + } + + private static WorldCanonicalInitialAdmissionHold.HoldIdentity hold( + StartSessionPostAuthorizationExecutionTuple tuple, String namespace) { + return new WorldCanonicalInitialAdmissionHold.HoldIdentity( + new WorldCanonicalInitialAdmissionHold.Request( + namespace, + tuple.preAuthorizationTuple().action().scope().tenantId(), + "earth", + uuid("3916f423-2870-426a-a8aa-5e3f97412613"), + uuid("54e6094e-11bb-4f4c-93ee-a52f715b530b"), + "SHARED", + uuid("a55b2e10-9a24-4adb-adb8-6fc66fe3b8e9"), + uuid("d7280ec0-5979-4b62-8418-e9f139415184"), + 3L, + tuple.controlPlaneRequestId(), + "c".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null), + uuid("0db7344a-1e67-4b95-905a-83dc9c472f0c"), + uuid("52a14272-f9e4-4f67-97c9-62247b5fbcc1")); + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture(AccountStartSessionAdmissionProtectionEvidence evidence) { + OriginalStartSessionAdmissionTerminalResult result( + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome) { + var hold = evidence.request().worldAdmissionHoldIdentity(); + var proof = + switch (outcome) { + case COMMITTED -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, outcome, 1L, 23L, PROOF_DIGEST, false, TERMINAL_AT); + case ABORTED -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, outcome, null, null, PROOF_DIGEST, true, TERMINAL_AT); + case PENDING -> throw new IllegalArgumentException("Pending is not terminal evidence"); + }; + return new OriginalStartSessionAdmissionTerminalResult( + new OriginalStartSessionAdmissionTerminalRequest(evidence.canonicalBytes()), proof); + } + + StoredSettlement receipt( + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome, Instant settledAt) { + return new StoredSettlement( + AccountStartSessionAdmissionProtectionSettlement.create(result(outcome)), settledAt); + } + } + + private static final class Harness { + final AccountStartSessionAdmissionProtectionRepository repository = + mock(AccountStartSessionAdmissionProtectionRepository.class); + final OriginalStartSessionAdmissionTerminalReadClient client = + mock(OriginalStartSessionAdmissionTerminalReadClient.class); + final OwnerTransactions transactions = new OwnerTransactions(); + final List steps = new ArrayList<>(); + final AccountStartSessionAdmissionProtectionSettlementService service; + + Harness(String namespace) { + service = + new AccountStartSessionAdmissionProtectionSettlementService( + repository, client, transactions, namespace); + } + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + int rollbacks; + int failCommitAt = -1; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertNoSql(); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + if (commits == failCommitAt) { + throw new IllegalStateException("synthetic unknown commit"); + } + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + rollbacks++; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlement.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlement.java new file mode 100644 index 0000000000..a25da991b3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlement.java @@ -0,0 +1,268 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalResult; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed canonical Account settlement value containing the full Account evidence and exact Game + * Session owner-proof bytes. + * + *

This carrier validates integrity and cross-binding only. It does not authenticate the producer + * or compare the Account evidence with retained database rows. + */ +public final class AccountStartSessionAdmissionProtectionSettlement { + public static final String SCHEMA = "account-start-session-admission-protection-settlement/v1"; + public static final int MAX_CANONICAL_BYTES = 24 * 1024 * 1024; + + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "canonicalAccountProtectionEvidenceBytesBase64", + "canonicalGameSessionOwnerProofBytesBase64"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final OriginalStartSessionAdmissionTerminalResult result; + private final AccountStartSessionAdmissionProtectionEvidence protectionEvidence; + private final GameSessionCanonicalInitialAdmissionOwnerProof ownerProof; + private final byte[] canonicalBytes; + private final String digest; + + private AccountStartSessionAdmissionProtectionSettlement( + OriginalStartSessionAdmissionTerminalResult result, + byte[] exactAccountEvidenceBytes, + byte[] exactOwnerProofBytes) { + this.result = Objects.requireNonNull(result, "terminal result is required"); + this.protectionEvidence = result.request().protectionEvidence(); + this.ownerProof = result.ownerProof(); + if (!Arrays.equals(exactAccountEvidenceBytes, protectionEvidence.canonicalBytes()) + || !Arrays.equals(exactOwnerProofBytes, result.canonicalBytes())) { + throw invalid("Settlement components differ from their exact canonical values"); + } + this.canonicalBytes = encode(exactAccountEvidenceBytes, exactOwnerProofBytes); + this.digest = digestPrefixed(canonicalBytes); + } + + /** Creates a complete immutable settlement from the validated terminal result. */ + public static AccountStartSessionAdmissionProtectionSettlement create( + OriginalStartSessionAdmissionTerminalResult result) { + Objects.requireNonNull(result, "terminal result is required"); + byte[] accountEvidenceBytes = result.request().protectionEvidence().canonicalBytes(); + byte[] ownerProofBytes = result.canonicalBytes(); + GameSessionCanonicalInitialAdmissionOwnerProof proof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored(ownerProofBytes); + OriginalStartSessionAdmissionTerminalResult exactResult = + new OriginalStartSessionAdmissionTerminalResult( + new OriginalStartSessionAdmissionTerminalRequest(accountEvidenceBytes), proof); + if (!Arrays.equals(ownerProofBytes, exactResult.canonicalBytes())) { + throw invalid("Game Session owner proof bytes are not exact canonical bytes"); + } + return new AccountStartSessionAdmissionProtectionSettlement( + exactResult, accountEvidenceBytes, ownerProofBytes); + } + + /** Strictly decodes one complete canonical settlement; decoding establishes no provenance. */ + public static AccountStartSessionAdmissionProtectionSettlement decode( + byte[] exactCanonicalBytes) { + byte[] stored = bounded(exactCanonicalBytes, MAX_CANONICAL_BYTES, "settlement"); + try { + String json = strictUtf8(stored); + requireCanonicalJson(stored, json); + Map root = JSON.readValue(json, new TypeReference<>() {}); + requireExactFields(root); + if (!SCHEMA.equals(string(root.get("schema"), "schema"))) { + throw invalid("Unsupported Account admission protection settlement schema"); + } + + byte[] accountEvidenceBytes = + decodeBase64( + root.get("canonicalAccountProtectionEvidenceBytesBase64"), + "canonicalAccountProtectionEvidenceBytesBase64", + AccountStartSessionAdmissionProtectionEvidence.MAX_CANONICAL_BYTES); + byte[] ownerProofBytes = + decodeBase64( + root.get("canonicalGameSessionOwnerProofBytesBase64"), + "canonicalGameSessionOwnerProofBytesBase64", + OriginalStartSessionAdmissionTerminalResult.MAX_CANONICAL_BYTES); + AccountStartSessionAdmissionProtectionEvidence evidence = + AccountStartSessionAdmissionProtectionEvidence.decode(accountEvidenceBytes); + GameSessionCanonicalInitialAdmissionOwnerProof proof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored(ownerProofBytes); + OriginalStartSessionAdmissionTerminalResult result = + new OriginalStartSessionAdmissionTerminalResult( + new OriginalStartSessionAdmissionTerminalRequest(evidence.canonicalBytes()), proof); + if (!Arrays.equals(ownerProofBytes, result.canonicalBytes())) { + throw invalid("Game Session owner proof bytes are not canonical"); + } + + AccountStartSessionAdmissionProtectionSettlement decoded = + new AccountStartSessionAdmissionProtectionSettlement( + result, accountEvidenceBytes, ownerProofBytes); + if (!MessageDigest.isEqual(stored, decoded.canonicalBytes)) { + throw invalid("Account admission protection settlement members are inconsistent"); + } + return decoded; + } catch (IllegalArgumentException expected) { + throw expected; + } catch (IOException | RuntimeException malformed) { + throw invalid("Account admission protection settlement is malformed"); + } + } + + public AccountStartSessionAdmissionProtectionEvidence protectionEvidence() { + return protectionEvidence; + } + + public GameSessionCanonicalInitialAdmissionOwnerProof ownerProof() { + return ownerProof; + } + + /** + * Returns the existing exact terminal result, whose canonical bytes contain only the GS proof. + */ + public OriginalStartSessionAdmissionTerminalResult result() { + return result; + } + + public GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome() { + return ownerProof.outcome(); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** Returns {@code sha256:} plus lowercase SHA-256 of the complete canonical settlement object. */ + public String digest() { + return digest; + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof AccountStartSessionAdmissionProtectionSettlement that + && Arrays.equals(canonicalBytes, that.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + private static byte[] encode(byte[] accountEvidenceBytes, byte[] ownerProofBytes) { + Map root = new LinkedHashMap<>(); + root.put("schema", SCHEMA); + root.put( + "canonicalAccountProtectionEvidenceBytesBase64", + Base64.getEncoder().encodeToString(accountEvidenceBytes)); + root.put( + "canonicalGameSessionOwnerProofBytesBase64", + Base64.getEncoder().encodeToString(ownerProofBytes)); + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (canonical.length == 0 || canonical.length > MAX_CANONICAL_BYTES) { + throw invalid("Account admission protection settlement exceeds its byte limit"); + } + return canonical; + } catch (IOException impossible) { + throw new IllegalStateException( + "Account admission protection settlement cannot be encoded", impossible); + } + } + + private static byte[] decodeBase64(Object value, String field, int maximumBytes) { + String encoded = string(value, field); + long maximumEncodedLength = 4L * ((maximumBytes + 2L) / 3L); + if (encoded.isEmpty() || encoded.length() > maximumEncodedLength) { + throw invalid(field + " is empty or exceeds its byte limit"); + } + try { + byte[] decoded = Base64.getDecoder().decode(encoded); + if (decoded.length == 0 + || decoded.length > maximumBytes + || !Base64.getEncoder().encodeToString(decoded).equals(encoded)) { + throw invalid(field + " is not bounded canonical Base64"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is malformed or noncanonical Base64"); + } + } + + private static void requireCanonicalJson(byte[] originalBytes, String json) throws IOException { + if (!MessageDigest.isEqual(Rfc8785CanonicalJson.canonicalizeUtf8(json), originalBytes)) { + throw invalid("Account admission protection settlement is not canonical RFC 8785 JSON"); + } + } + + private static void requireExactFields(Map root) { + if (root == null || !root.keySet().equals(ROOT_FIELDS)) { + throw invalid("Account admission protection settlement has missing or unsupported fields"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw invalid("Account admission protection settlement is not strict UTF-8"); + } + } + + private static byte[] bounded(byte[] value, int maximum, String field) { + if (value == null || value.length == 0 || value.length > maximum) { + throw invalid( + "Account admission protection " + field + " is empty or exceeds its byte limit"); + } + return value.clone(); + } + + private static String digestPrefixed(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static String string(Object value, String field) { + if (!(value instanceof String text)) { + throw invalid(field + " must be a string"); + } + return text; + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementTest.java new file mode 100644 index 0000000000..93492c8aef --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementTest.java @@ -0,0 +1,271 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalResult; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import org.junit.jupiter.api.Test; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +/** Synthetic integrity tests; these fixtures provide no peer, database, or genuine GS proof. */ +class AccountStartSessionAdmissionProtectionSettlementTest { + private static final String PROOF_DIGEST = "sha256:" + "d".repeat(64); + private static final UUID ALTERED_PROTECTION_ID = + UUID.fromString("621a42c0-49c9-4b08-8f1c-ae9db562dd23"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void roundTripsCompleteAccountEvidenceAndCommittedOrAbortedOwnerProof() throws Exception { + var committedResult = result(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + var committed = AccountStartSessionAdmissionProtectionSettlement.create(committedResult); + var decodedCommitted = + AccountStartSessionAdmissionProtectionSettlement.decode(committed.canonicalBytes()); + + assertThat(decodedCommitted.canonicalBytes()).containsExactly(committed.canonicalBytes()); + assertThat(decodedCommitted.protectionEvidence().canonicalBytes()) + .containsExactly(committedResult.request().protectionEvidence().canonicalBytes()); + assertThat(decodedCommitted.ownerProof()).isEqualTo(committedResult.ownerProof()); + assertThat(decodedCommitted.result().canonicalBytes()) + .containsExactly(committedResult.canonicalBytes()); + assertThat(decodedCommitted.outcome()) + .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(decodedCommitted.digest()).isEqualTo(digest(committed.canonicalBytes())); + assertThat(decodedCommitted.digest()).matches("^sha256:[0-9a-f]{64}$"); + assertThat(decodedCommitted).isEqualTo(committed); + assertThat(decodedCommitted.hashCode()).isEqualTo(committed.hashCode()); + byte[] escapedBytes = committed.canonicalBytes(); + escapedBytes[0] ^= 1; + assertThat(committed.canonicalBytes()).containsExactly(decodedCommitted.canonicalBytes()); + Map committedEnvelope = readObject(committed.canonicalBytes()); + assertThat(committedEnvelope.keySet()) + .containsExactlyInAnyOrder( + "schema", + "canonicalAccountProtectionEvidenceBytesBase64", + "canonicalGameSessionOwnerProofBytesBase64"); + assertThat( + Base64.getDecoder() + .decode( + (String) + committedEnvelope.get("canonicalAccountProtectionEvidenceBytesBase64"))) + .containsExactly(committedResult.request().protectionEvidence().canonicalBytes()); + assertThat( + Base64.getDecoder() + .decode( + (String) committedEnvelope.get("canonicalGameSessionOwnerProofBytesBase64"))) + .containsExactly(committedResult.canonicalBytes()); + + var abortedResult = result(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + var aborted = AccountStartSessionAdmissionProtectionSettlement.create(abortedResult); + var decodedAborted = + AccountStartSessionAdmissionProtectionSettlement.decode(aborted.canonicalBytes()); + + assertThat(decodedAborted.canonicalBytes()).containsExactly(aborted.canonicalBytes()); + assertThat(decodedAborted.ownerProof().positiveDurableAbort()).isTrue(); + assertThat(decodedAborted.outcome()) + .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + assertThat(aborted).isNotEqualTo(committed); + } + + @Test + void changedAccountProtectionBytesAreNotAnExactReplay() { + var originalResult = result(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + var original = AccountStartSessionAdmissionProtectionSettlement.create(originalResult); + var evidence = originalResult.request().protectionEvidence(); + var changedEvidence = + AccountStartSessionAdmissionProtectionEvidence.create( + evidence.request(), + ALTERED_PROTECTION_ID, + evidence.accountProtectionFence(), + evidence.originalSourceCaptureReferenceBytes(), + evidence.originalSourceCaptureReferenceSha256(), + evidence.sourceEvidenceVector()); + var changedResult = + new OriginalStartSessionAdmissionTerminalResult( + new OriginalStartSessionAdmissionTerminalRequest(changedEvidence.canonicalBytes()), + originalResult.ownerProof()); + var changed = AccountStartSessionAdmissionProtectionSettlement.create(changedResult); + + assertThat(changed.protectionEvidence().accountProtectionId()).isEqualTo(ALTERED_PROTECTION_ID); + assertThat(changed.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(AccountStartSessionAdmissionProtectionSettlement.decode(changed.canonicalBytes())) + .isNotEqualTo(original); + // This is only an exact-byte conflict signal. Comparing the ID with retained Account rows is + // the settlement repository's responsibility; decoding alone cannot authenticate provenance. + } + + @Test + void rejectsPendingSubstitutedHoldAndWrongNextPointerResults() { + var request = request(); + var hold = request.protectionEvidence().request().worldAdmissionHoldIdentity(); + var pending = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.PENDING, + null, + null, + null, + false, + null); + assertThatThrownBy(() -> new OriginalStartSessionAdmissionTerminalResult(request, pending)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Pending"); + + var wrongPointer = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 2L, + 23L, + PROOF_DIGEST, + false, + Instant.parse("2026-10-09T10:20:30Z")); + assertThatThrownBy(() -> new OriginalStartSessionAdmissionTerminalResult(request, wrongPointer)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact next pointer version"); + + var changedHold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + hold.request(), hold.holdId(), UUID.fromString("c3527a86-eae1-4a1e-b8a6-13c831f7a665")); + var substitutedHoldProof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + changedHold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + null, + null, + PROOF_DIGEST, + true, + Instant.parse("2026-10-09T10:20:30Z")); + assertThatThrownBy( + () -> new OriginalStartSessionAdmissionTerminalResult(request, substitutedHoldProof)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact Account World hold identity"); + + assertThatThrownBy( + () -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + null, + null, + PROOF_DIGEST, + false, + Instant.parse("2026-10-09T10:20:30Z"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive durable fencing"); + } + + @Test + void rejectsMissingExtraDuplicateNoncanonicalMalformedAndOversizedEnvelopes() throws Exception { + byte[] valid = + AccountStartSessionAdmissionProtectionSettlement.create( + result(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)) + .canonicalBytes(); + Map fields = readObject(valid); + + Map missing = new LinkedHashMap<>(fields); + missing.remove("canonicalAccountProtectionEvidenceBytesBase64"); + assertRejected(canonical(missing)); + + Map extra = new LinkedHashMap<>(fields); + extra.put("unexpected", "field"); + assertRejected(canonical(extra)); + + Map wrongSchema = new LinkedHashMap<>(fields); + wrongSchema.put("schema", "account-start-session-admission-protection-settlement/v2"); + assertRejected(canonical(wrongSchema)); + + String text = new String(valid, StandardCharsets.UTF_8); + String schema = + "\"schema\":\"" + AccountStartSessionAdmissionProtectionSettlement.SCHEMA + "\""; + String duplicate = text.replaceFirst(schema, schema + "," + schema); + assertThat(duplicate).isNotEqualTo(text); + assertRejected(duplicate.getBytes(StandardCharsets.UTF_8)); + + assertRejected(Arrays.copyOf(valid, valid.length + 1)); + assertRejected((text + "{}").getBytes(StandardCharsets.UTF_8)); + assertRejected((text + " ").getBytes(StandardCharsets.UTF_8)); + + Map badBase64 = new LinkedHashMap<>(fields); + badBase64.put("canonicalGameSessionOwnerProofBytesBase64", "%%%not-base64%%%"); + assertRejected(canonical(badBase64)); + + byte[] malformedUtf8 = valid.clone(); + malformedUtf8[0] = (byte) 0xff; + assertRejected(malformedUtf8); + + assertThatThrownBy( + () -> + AccountStartSessionAdmissionProtectionSettlement.decode( + new byte + [AccountStartSessionAdmissionProtectionSettlement.MAX_CANONICAL_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("byte limit"); + } + + private static OriginalStartSessionAdmissionTerminalRequest request() { + return new OriginalStartSessionAdmissionTerminalRequest( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.evidence( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.input()) + .canonicalBytes()); + } + + private static OriginalStartSessionAdmissionTerminalResult result( + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome) { + var request = request(); + var hold = request.protectionEvidence().request().worldAdmissionHoldIdentity(); + var proof = + switch (outcome) { + case COMMITTED -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + outcome, + 1L, + 23L, + PROOF_DIGEST, + false, + Instant.parse("2026-10-09T10:20:30Z")); + case ABORTED -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + outcome, + null, + null, + PROOF_DIGEST, + true, + Instant.parse("2026-10-09T10:20:30Z")); + case PENDING -> throw new IllegalArgumentException("Pending is not terminal"); + }; + return new OriginalStartSessionAdmissionTerminalResult(request, proof); + } + + private static void assertRejected(byte[] bytes) { + assertThatThrownBy(() -> AccountStartSessionAdmissionProtectionSettlement.decode(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static byte[] canonical(Map value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static Map readObject(byte[] bytes) throws Exception { + return JSON.readValue(new String(bytes, StandardCharsets.UTF_8), new TypeReference<>() {}); + } + + private static String digest(byte[] value) throws Exception { + return "sha256:" + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } +} From 9931cc5c1a89b074a5bb2cab2a96f26c5f6259ce Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:47:51 +1300 Subject: [PATCH 081/129] Add bounded historical admission protection reconciliation --- .../account-service/api-contracts.md | 4 + ...ame-authoring-publishing-and-activation.md | 4 +- ...tSessionAdmissionProtectionRepository.java | 65 +++ ...issionProtectionReconciliationService.java | 149 +++++++ ...ionAcquisitionPostgresIntegrationTest.java | 77 ++++ ...sionAdmissionProtectionRepositoryTest.java | 68 +++ ...onProtectionReconciliationServiceTest.java | 389 ++++++++++++++++++ 7 files changed, 754 insertions(+), 2 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionReconciliationService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionReconciliationServiceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3c2a773cd6..86017532e8 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -215,6 +215,10 @@ Account's immutable admission-settlement value is the closed RFC 8785 object `ac The internal Account settlement composition obtains exact historical protection and any already-retained terminal receipt in an independent writable read-committed transaction. It calls the authenticated Game Session terminal reader outside SQL, persists only the exact fully bound terminal value in a separate Account transaction, and verifies it through an independent lookup-only post-commit readback. An uncertain commit or absent readback remains unresolved; retry recovers the same immutable result without renewing authority or replaying the admission mutation. Settlement follows the existing source-lock-before-protection ordering and preserves source exclusion until its commit. This internal recovery does not create an external settlement permission or runtime registration; its unexecuted producer, consumer and physical proof gates remain in the linked tracker. +### Bounded Historical Recovery + +The prepared internal Account recovery batch selects at most 100 unsettled protection identities in one independent writable `READ COMMITTED` page transaction. The lookup uses an exclusive descending keyset over immutable positive protection fences, excludes identities with a retained settlement, and applies no original-expiry predicate; it does not lock or mutate protections or establish terminal authority. The page transaction commits before the batch attempts settlement for any selected identity, so authenticated Game Session terminal reads and exact immutable settlement/readback remain outside the page transaction. The in-memory cursor advances across the entire selected page, including unresolved items, and resets after a short or empty page so a later invocation wraps to the newest candidates. Only an exact protection-ID/fence receipt from the existing settlement and independent readback path counts as settled; exceptions, missing or mismatched receipts, and ambiguous terminal evidence remain unresolved and preserve protection. This composition is prepared but unregistered and unscheduled: it is not an automatic production reconciler and does not renew leases, grant admission, or activate runtime. + ## REST APIs | Method | Path | Description | 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 6a27bafc4b..7fa9291ae9 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 @@ -6,11 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Distinct original-StartSession Account admission protection is prepared under [ADR 0047's canonical lifecycle](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection). It authenticates the original Game Session receiving workload, obtains the exact current original-attempt observation outside SQL, then revalidates the original actor/JTI/reference and unchanged complete capture through the existing Account currentness callback. V133 retains the complete request, actual mutation/attempt/fence and unchanged finite expiry, original World participation, full World hold, immutable capture and exact source children; additive writer/disclosure hooks preserve the existing assembled owner checks. A settled World row supplies historical binding, not current authority: acquisition must freshly prove unchanged original sources after a gap. Independent lookup-only readback returns the first protection unchanged. V129 World settlement and V131 observation are unchanged. Forward V134 prepares closed terminal-settlement integrity checks and preserves the existing immutable receipt and source-writer guards; expiry, missing or ambiguous proof cannot release protection. The producer and settlement composition remain unregistered and do not enable admission. +Distinct original-StartSession Account admission protection is prepared under [ADR 0047's canonical lifecycle](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection). It authenticates the original Game Session receiving workload, obtains the exact current original-attempt observation outside SQL, then revalidates the original actor/JTI/reference and unchanged complete capture through the existing Account currentness callback. V133 retains the complete request, actual mutation/attempt/fence and unchanged finite expiry, original World participation, full World hold, immutable capture and exact source children; additive writer/disclosure hooks preserve the existing assembled owner checks. A settled World row supplies historical binding, not current authority: acquisition must freshly prove unchanged original sources after a gap. Independent lookup-only readback returns the first protection unchanged. V129 World settlement and V131 observation are unchanged. Forward V134 prepares closed terminal-settlement integrity checks and preserves the existing immutable receipt and source-writer guards; expiry, missing or ambiguous proof cannot release protection. The producer, settlement composition and bounded recovery batch remain unregistered and do not enable admission. The prepared acquisition transport exposes the [closed Account RPC](../../../protos/account/v1/start_session_admission_protection_acquisition.proto), with the mTLS client in Common Security so it can reject authenticated end-user context before transport. Its caller supplies the complete original tuple, actual Game Session mutation/attempt/fence and full World hold, not private Account participation coordinates; Account resolves the unchanged retained participation within its fresh currentness callback. It authenticates the exact Game Session workload before parsing and returns complete canonical evidence rather than selected hashes. The exact original PostgreSQL lease is retained at microsecond precision, with six canonical fractional digits and no rounding or renewal. V133 compares the full World hold's canonical `sha256:`-prefixed digest. Nine repository integrity definitions cover exact retained sub-millisecond expiry, changed caller expiry without modifying the stored row, and forged digest rejection; five real-Account producer definitions cover acquisition/retry/readback, lost acknowledgement, changed sources after World settlement, protection beyond World settlement and expiry, and expiry while waiting for the original issuance lock. The expired-protection case also verifies full historical lookup-only readback without renewal or settlement. Logging, Game Session and World collaborators are stipulated; these definitions do not establish genuine cross-owner execution. -The distinct terminal-read carrier and Common Security client bind the complete Account protection echo to the existing canonical Game Session owner proof, accept only exact `COMMITTED` or positively fenced `ABORTED`, and reject pending or substituted evidence. Historical Account lookup validates the immutable parent, original capture and complete source children without consulting live expiry or releasing protection. The internal settlement composition now prepares historical receipt lookup, authenticated remote read outside SQL, an immutable full-evidence settlement transaction, and independent post-commit lookup-only readback. The repository locks the original source rows before the protection, exact-compares the retained winner, and does not use expiry as a release condition. V134 validates the complete canonical Account envelope and existing framed Game Session proof, including the exact next pointer, positive audit identity or durable abort, original hold, source vector and digest; these SQL integrity checks do not authenticate the producer. Automatic scanning/reconciliation, genuine authenticated Game Session terminal composition and corrected physical PostgreSQL execution remain open. The previous published acquisition batch's Common Platform, Common Security and Account full checks pass in 2m40s with 587, 146 and 1,312 unit cases respectively, zero failures, errors or skips. That batch executes seven non-container Account integration cases and skips 284 of 291 definitions without Docker; those results are not proof of the new V134 batch. +The distinct terminal-read carrier and Common Security client bind the complete Account protection echo to the existing canonical Game Session owner proof, accept only exact `COMMITTED` or positively fenced `ABORTED`, and reject pending or substituted evidence. Historical Account lookup validates the immutable parent, original capture and complete source children without consulting live expiry or releasing protection. The internal settlement composition prepares historical receipt lookup, authenticated remote read outside SQL, an immutable full-evidence settlement transaction, and independent post-commit lookup-only readback. The repository locks the original source rows before the protection, exact-compares the retained winner, and does not use expiry as a release condition. The prepared [bounded Account recovery batch](../../architecture/microservices/account-service/api-contracts.md#bounded-historical-recovery) selects at most one bounded page per invocation and advances across unresolved candidates, but remains unregistered and has no scheduler; it is not automatic production reconciliation. Eight mocked unit cases pass for page transaction ordering, cursor progress/wrap, read and commit failure, per-instance concurrency and fail-closed receipts; two added repository cases verify SQL construction and bounded decoding, not real SQL execution. The corrected Account full check, static checks, formatting, integration compilation and boot JAR pass in 2m56s, with 1,332 unit cases and no failures, errors or skips. Account integration has 300 definitions: twelve non-container cases execute and 288 skip without Docker. The new one-candidate PostgreSQL definition for expiry-independent selection and settlement exclusion is among those skips and does not prove relative ordering across multiple candidates. Genuine authenticated Game Session terminal composition and corrected physical PostgreSQL execution remain open. The previous published acquisition batch's Common Platform, Common Security and Account full checks pass in 2m40s with 587, 146 and 1,312 unit cases respectively, zero failures, errors or skips. That batch executes seven non-container Account integration cases and skips 284 of 291 definitions without Docker; those results are not proof of the new V134 batch. The corrected Common Platform/Account full gate passes in 49s, including formatting, Checkstyle, SpotBugs, coverage, Account schema generation, integration compilation and boot JAR. Successful unchanged tasks reuse their originating results: Common Platform has 591 unit cases and Account has 1,322, with zero failures, errors or skips. These include seven mocked settlement-ordering cases and four native acquisition mTLS cases with a mocked Account owner. Account integration has 299 definitions: twelve non-container cases execute and 287 skip without Docker. Three added PostgreSQL definitions reuse the genuine Account issuer/acquisition fixture for historical terminal release, exact abort/retry and raw malformed/conflicting settlement denial; all three skip locally, and their Game Session and World terminal values remain stipulated. They do not establish authenticated upstream transactions or end-to-end admission. The recovered gate's Mockito-only JDBC resource warnings are corrected with narrow test-local annotations and explicit connection, statement and result-set closure assertions; no production guard is suppressed. The native missing-client-certificate matcher remains strict, while bounded cause-chain reporting and grouped assertions retain the no-handler/no-owner evidence even when its matcher assertion fails. No runtime registration, source grant or production durability adoption follows. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java index 7e2c05b794..5e284ca904 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java @@ -50,6 +50,8 @@ */ @Repository public class AccountStartSessionAdmissionProtectionRepository { + public static final int MAX_PENDING_SWEEP_SIZE = 100; + private static final String PROTECTIONS = "account_start_session_admission_protections"; private static final String SOURCES = "account_start_session_admission_protection_sources"; private static final String SETTLEMENTS = @@ -93,6 +95,8 @@ public class AccountStartSessionAdmissionProtectionRepository { "canonical_snapshot_bytes"); private static final Set SETTLEMENT_COLUMNS = Set.of("protection_id", "outcome", "terminal_bytes", "terminal_digest", "settled_at"); + private static final Set PENDING_PROTECTION_COLUMNS = + Set.of("protection_id", "protection_fence"); private static final Set CAPTURE_SNAPSHOT_FIELDS = Set.of( "schema", @@ -321,6 +325,58 @@ public Optional findSettlementExact(UUID protectionId, long pr return readSettlementExact(protectionId, protectionFence, evidence.get()); } + /** + * Selects one bounded descending keyset page of still-pending historical protections. + * + *

This query is lookup-only: it neither locks nor changes protection state, checks original + * expiry, or establishes terminal authority. The unique immutable positive fence is the page + * cursor; callers settle each returned identity through the separate authenticated composition. + * + * @param beforeProtectionFence exclusive descending cursor, or {@code null} for the first page + * @param limit maximum number of candidates to return + * @return candidates ordered by descending protection fence + */ + @Transactional(propagation = Propagation.MANDATORY) + public List findUnsettledPageDescending( + Long beforeProtectionFence, int limit) { + requireWritableReadCommittedTransaction(); + if ((beforeProtectionFence != null && beforeProtectionFence <= 0L) + || limit <= 0 + || limit > MAX_PENDING_SWEEP_SIZE) { + throw new IllegalArgumentException("Positive cursor and bounded page size required"); + } + + String query = + "SELECT protection.protection_id, protection.protection_fence FROM " + + PROTECTIONS + + " protection WHERE NOT EXISTS (SELECT 1 FROM " + + SETTLEMENTS + + " settlement WHERE settlement.protection_id = protection.protection_id)"; + Object[] parameters; + if (beforeProtectionFence == null) { + parameters = new Object[] {limit}; + } else { + query += " AND protection.protection_fence < ?"; + parameters = new Object[] {beforeProtectionFence, limit}; + } + query += " ORDER BY protection.protection_fence DESC LIMIT ?"; + + List candidates = new ArrayList<>(); + Long previousFence = beforeProtectionFence; + for (Record row : dsl.fetch(query, parameters)) { + requireColumns(row, PENDING_PROTECTION_COLUMNS, "pending admission protection candidate"); + UUID protectionId = requiredUuid(row, "protection_id"); + long protectionFence = positive(requiredLong(row, "protection_fence")); + if ((previousFence != null && protectionFence >= previousFence) + || candidates.size() >= limit) { + throw unavailable(); + } + candidates.add(new PendingProtection(protectionId, protectionFence)); + previousFence = protectionFence; + } + return List.copyOf(candidates); + } + private void lockOriginalSourceRows( AccountStartSessionAdmissionProtectionEvidence expectedEvidence) { UUID protectionId = expectedEvidence.accountProtectionId(); @@ -437,6 +493,15 @@ public GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome() { } } + /** Exact immutable protection identity selected for a later settlement attempt. */ + public record PendingProtection(UUID protectionId, long protectionFence) { + public PendingProtection { + if (protectionId == null || NIL_UUID.equals(protectionId) || protectionFence <= 0L) { + throw new IllegalArgumentException("Non-nil protection ID and positive fence required"); + } + } + } + private int insert( AccountStartSessionAdmissionProtectionRequest request, AccountStartSessionAuthorityCapture capture, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionReconciliationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionReconciliationService.java new file mode 100644 index 0000000000..47005dac13 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionReconciliationService.java @@ -0,0 +1,149 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository.PendingProtection; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered, bounded Account-local composition for retrying historical protection settlement. + * + *

Each invocation selects one short page in its own writable READ COMMITTED transaction, then + * closes that transaction before the existing settlement composition performs authenticated Game + * Session reads and immutable settlement/readback. The in-memory cursor advances across the entire + * selected page, including unresolved items; another invocation eventually wraps to the newest + * candidate. Separate service instances may select the same candidate, relying on exact immutable + * settlement idempotency. + */ +public final class AccountStartSessionAdmissionProtectionReconciliationService { + private final AccountStartSessionAdmissionProtectionRepository repository; + private final AccountStartSessionAdmissionProtectionSettlementService settlementService; + private final TransactionTemplate pageTransaction; + private final int pageSize; + private final AtomicBoolean invocationActive = new AtomicBoolean(); + + /** Null begins a sweep from the newest positive protection fence. */ + private Long beforeProtectionFence; + + public AccountStartSessionAdmissionProtectionReconciliationService( + AccountStartSessionAdmissionProtectionRepository repository, + AccountStartSessionAdmissionProtectionSettlementService settlementService, + PlatformTransactionManager transactionManager, + int pageSize) { + this.repository = + Objects.requireNonNull(repository, "admission protection repository required"); + this.settlementService = + Objects.requireNonNull( + settlementService, "admission protection settlement service required"); + if (pageSize <= 0 + || pageSize > AccountStartSessionAdmissionProtectionRepository.MAX_PENDING_SWEEP_SIZE) { + throw new IllegalArgumentException( + "Bounded positive admission protection page size required"); + } + this.pageSize = pageSize; + pageTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager required")); + pageTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + pageTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + pageTransaction.setReadOnly(false); + } + + /** + * Selects and attempts at most one bounded page. Per-item runtime failures remain unresolved and + * do not prevent later candidates in the page from being attempted. + * + *

A simultaneous invocation on this instance returns an empty skipped result. Page read or + * commit failures propagate before cursor movement or any settlement call. + */ + public BatchResult reconcilePendingBatch() { + if (!invocationActive.compareAndSet(false, true)) return BatchResult.skipped(); + try { + requireNoAuthenticatedEndUser(); + requireNoAmbientTransaction(); + + Long pageCursor = beforeProtectionFence; + List candidates = + Objects.requireNonNull( + pageTransaction.execute( + ignored -> repository.findUnsettledPageDescending(pageCursor, pageSize)), + "Account pending protection page returned no result"); + candidates = List.copyOf(candidates); + if (candidates.size() > pageSize) { + throw new IllegalStateException("Account pending protection page exceeded its bound"); + } + + advanceCursor(candidates); + int settledCount = 0; + int unresolvedCount = 0; + for (PendingProtection candidate : candidates) { + try { + var receipt = + settlementService.settle(candidate.protectionId(), candidate.protectionFence()); + if (receipt == null + || !candidate.protectionId().equals(receipt.protectionId()) + || candidate.protectionFence() != receipt.protectionFence()) { + unresolvedCount++; + continue; + } + settledCount++; + } catch (RuntimeException unresolved) { + unresolvedCount++; + } + } + return new BatchResult(candidates.size(), settledCount, unresolvedCount, false); + } finally { + invocationActive.set(false); + } + } + + private void advanceCursor(List candidates) { + if (candidates.isEmpty() || candidates.size() < pageSize) { + beforeProtectionFence = null; + return; + } + beforeProtectionFence = candidates.get(candidates.size() - 1).protectionFence(); + } + + private static void requireNoAuthenticatedEndUser() { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription("Internal Account historical recovery rejects end-user context") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Account historical recovery requires an independent page transaction") + .asRuntimeException(); + } + } + + /** Bounded outcome for one invocation; unresolved candidates remain protected and retryable. */ + public record BatchResult( + int selectedCount, int settledCount, int unresolvedCount, boolean skippedBecauseActive) { + public BatchResult { + if (selectedCount < 0 + || settledCount < 0 + || unresolvedCount < 0 + || settledCount + unresolvedCount != selectedCount + || (skippedBecauseActive && selectedCount != 0)) { + throw new IllegalArgumentException("Invalid Account recovery batch result"); + } + } + + private static BatchResult skipped() { + return new BatchResult(0, 0, 0, true); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java index 09a5eca363..069e3685ba 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java @@ -583,6 +583,70 @@ void exactAbortedSettlementRetryAndReadbackPreserveTheFirstReceipt() throws Exce } } + @Test + void unsettledPageIsBoundedExclusiveExpiryIndependentAndSettlementAware() throws Exception { + try (Prepared prepared = prepare(Duration.ofSeconds(5))) { + AccountStartSessionAdmissionProtectionEvidence protection = + prepared.acquire(prepared.acquisitionService(prepared.account.manager)); + var repository = new AccountStartSessionAdmissionProtectionRepository(prepared.account.dsl); + var expected = + new AccountStartSessionAdmissionProtectionRepository.PendingProtection( + protection.accountProtectionId(), protection.accountProtectionFence()); + Record protectionBefore = protectionRow(prepared); + long sourceCountBefore = + rowCount(prepared.account.dsl, "account_start_session_admission_protection_sources"); + + var initialPage = prepared.account.tx(() -> repository.findUnsettledPageDescending(null, 1)); + assertThat(initialPage).containsExactly(expected); + assertThat( + prepared.account.tx( + () -> + repository.findUnsettledPageDescending( + protection.accountProtectionFence(), 1))) + .isEmpty(); + assertProtectionRow(prepared, protection); + assertProtectionRowUnchanged(protectionBefore, protectionRow(prepared)); + assertThat( + rowCount( + prepared.account.dsl, "account_start_session_admission_protection_settlements")) + .isZero(); + assertThat( + rowCount(prepared.account.dsl, "account_start_session_admission_protection_sources")) + .isEqualTo(sourceCountBefore); + + awaitDatabaseTime( + prepared.account.dsl, + prepared.originalObservation.originalLeaseExpiresAt(), + Duration.ofSeconds(15)); + assertThat(prepared.account.tx(() -> repository.findUnsettledPageDescending(null, 1))) + .containsExactly(expected); + assertProtectionRow(prepared, protection); + assertProtectionRowUnchanged(protectionBefore, protectionRow(prepared)); + assertThat( + rowCount( + prepared.account.dsl, "account_start_session_admission_protection_settlements")) + .isZero(); + + var settlement = + terminalSettlement( + protection, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + Instant.parse("2026-10-10T04:05:06.123456789Z")); + prepared.account.tx(() -> repository.settleExact(settlement)); + assertThat(prepared.account.tx(() -> repository.findUnsettledPageDescending(null, 1))) + .isEmpty(); + assertProtectionRow(prepared, protection); + assertProtectionRowUnchanged(protectionBefore, protectionRow(prepared)); + assertThat( + rowCount( + prepared.account.dsl, "account_start_session_admission_protection_settlements")) + .isEqualTo(1L); + assertThat( + rowCount(prepared.account.dsl, "account_start_session_admission_protection_sources")) + .isEqualTo(sourceCountBefore); + } + } + @Test void leaseExpiryDuringRealOriginalActorIssuanceLockWaitDeniesDespiteTimelyRemoteRead() throws Exception { @@ -966,6 +1030,19 @@ private static void assertProtectionRow( .containsExactlyElementsOf(encoded(prepared.captureSources())); } + private static void assertProtectionRowUnchanged(Record before, Record after) { + Object[] beforeValues = before.intoArray(); + Object[] afterValues = after.intoArray(); + assertThat(afterValues).hasSameSizeAs(beforeValues); + for (int index = 0; index < beforeValues.length; index++) { + if (beforeValues[index] instanceof byte[] bytes) { + assertThat((byte[]) afterValues[index]).containsExactly(bytes); + } else { + assertThat(afterValues[index]).isEqualTo(beforeValues[index]); + } + } + } + private static Record protectionRow(Prepared prepared) { return prepared.account.dsl.fetchSingle( "SELECT * FROM account_start_session_admission_protections " diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java index fb3d33df43..063f40f09f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepositoryTest.java @@ -17,13 +17,19 @@ import java.sql.SQLException; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository.PendingProtection; import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionSettlement; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import org.jooq.ConnectionRunnable; import org.jooq.DSLContext; +import org.jooq.Field; import org.jooq.Record; +import org.jooq.Result; +import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.jooq.impl.SQLDataType; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -127,6 +133,51 @@ void settlementWriteChecksTransactionBeforeInspectingTypedCarrier() { verifyNoInteractions(dsl, settlement); } + @Test + void pendingPageUsesBoundedDescendingFenceKeysetAndDecodesExactIds() throws SQLException { + DSLContext dsl = writableDsl(); + UUID newestId = UUID.fromString("c5dc6d8d-13ee-42a8-83a5-a78ee044b55c"); + UUID olderId = UUID.fromString("db7c25cb-dcb1-4ec5-af07-8f48d1e0a62c"); + when(dsl.fetch(anyString(), any(Object[].class))) + .thenReturn(pendingRows(newestId, 90L, olderId, 73L)); + AccountStartSessionAdmissionProtectionRepository repository = + new AccountStartSessionAdmissionProtectionRepository(dsl); + beginWritableReadCommittedTransaction(); + + List candidates = repository.findUnsettledPageDescending(100L, 2); + + assertThat(candidates) + .containsExactly(new PendingProtection(newestId, 90L), new PendingProtection(olderId, 73L)); + ArgumentCaptor query = ArgumentCaptor.forClass(String.class); + ArgumentCaptor arguments = ArgumentCaptor.forClass(Object[].class); + verify(dsl).fetch(query.capture(), arguments.capture()); + assertThat(query.getValue()) + .contains("SELECT protection.protection_id, protection.protection_fence") + .contains("NOT EXISTS") + .contains("protection.protection_fence < ?") + .contains("ORDER BY protection.protection_fence DESC LIMIT ?") + .doesNotContain("FOR UPDATE", "expires_at", "UPDATE ", "DELETE "); + assertThat(arguments.getValue()).containsExactly(100L, 2); + } + + @Test + void pendingPageRejectsUnboundedLimitsBeforeSelect() throws SQLException { + DSLContext dsl = writableDsl(); + AccountStartSessionAdmissionProtectionRepository repository = + new AccountStartSessionAdmissionProtectionRepository(dsl); + beginWritableReadCommittedTransaction(); + + assertThatThrownBy( + () -> + repository.findUnsettledPageDescending( + null, + AccountStartSessionAdmissionProtectionRepository.MAX_PENDING_SWEEP_SIZE + 1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bounded page size"); + + verify(dsl, times(0)).fetch(anyString(), any(Object[].class)); + } + @Test void settlementLookupRejectsMismatchedRetainedFenceBeforeCaptureOrReceiptRead() throws SQLException { @@ -241,6 +292,23 @@ private static DSLContext writableDsl() throws SQLException { return dsl; } + private static Result pendingRows( + UUID firstId, long firstFence, UUID secondId, long secondFence) { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + Field idField = DSL.field("protection_id", SQLDataType.UUID); + Field fenceField = DSL.field("protection_fence", SQLDataType.BIGINT); + Result rows = resultDsl.newResult(new Field[] {idField, fenceField}); + Record first = resultDsl.newRecord(idField, fenceField); + first.setValue(idField, firstId); + first.setValue(fenceField, firstFence); + Record second = resultDsl.newRecord(idField, fenceField); + second.setValue(idField, secondId); + second.setValue(fenceField, secondFence); + rows.add(first); + rows.add(second); + return rows; + } + private static void beginWritableReadCommittedTransaction() { TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionReconciliationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionReconciliationServiceTest.java new file mode 100644 index 0000000000..67f78b27c4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionReconciliationServiceTest.java @@ -0,0 +1,389 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.inOrder; +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 io.grpc.Status; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository.PendingProtection; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository.StoredSettlement; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mocked paging and settlement composition verifies bounded ordering, not SQL or peer proof. */ +class AccountStartSessionAdmissionProtectionReconciliationServiceTest { + private static final UUID FIRST_ID = uuid("d14a9c31-46cc-49f7-9f82-78a945f9c58d"); + private static final UUID SECOND_ID = uuid("18d258b7-2bb9-4bdb-9f5c-dfc84ce9c1e4"); + private static final UUID THIRD_ID = uuid("933a5f0d-d4a7-4fe4-a897-b695a95351c1"); + private static final UUID FOURTH_ID = uuid("a18b1d53-2b8a-4d70-9cef-630170a4f4a2"); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void pageTransactionClosesBeforeSettlementAndOneFailureDoesNotStarveLaterItems() { + Harness harness = new Harness(2); + List attemptedFences = new ArrayList<>(); + Map receipts = + Map.of( + 90L, receipt(SECOND_ID, 90L), + 80L, receipt(THIRD_ID, 80L), + 70L, receipt(FOURTH_ID, 70L)); + when(harness.repository.findUnsettledPageDescending(null, 2)) + .thenAnswer( + ignored -> { + assertWritablePageTransaction(); + return List.of(candidate(FIRST_ID, 100L), candidate(SECOND_ID, 90L)); + }); + when(harness.repository.findUnsettledPageDescending(90L, 2)) + .thenAnswer( + ignored -> { + assertWritablePageTransaction(); + return List.of(candidate(THIRD_ID, 80L), candidate(FOURTH_ID, 70L)); + }); + when(harness.settlementService.settle(any(), anyLong())) + .thenAnswer( + invocation -> { + assertOutsideTransaction(); + long protectionFence = invocation.getArgument(1); + attemptedFences.add(protectionFence); + if (protectionFence == 100L) { + throw new IllegalStateException("terminal proof remains pending"); + } + return receipts.get(protectionFence); + }); + + var first = harness.service.reconcilePendingBatch(); + var second = harness.service.reconcilePendingBatch(); + + assertThat(first.selectedCount()).isEqualTo(2); + assertThat(first.settledCount()).isEqualTo(1); + assertThat(first.unresolvedCount()).isEqualTo(1); + assertThat(second.selectedCount()).isEqualTo(2); + assertThat(second.settledCount()).isEqualTo(2); + assertThat(attemptedFences).containsExactly(100L, 90L, 80L, 70L); + assertThat(harness.transactions.begins).isEqualTo(2); + assertThat(harness.transactions.commits).isEqualTo(2); + assertOutsideTransaction(); + } + + @Test + void emptyEndPageWrapsAndRevisitsAnUnresolvedCandidate() { + Harness harness = new Harness(2); + StoredSettlement secondReceipt = receipt(SECOND_ID, 80L); + when(harness.repository.findUnsettledPageDescending(null, 2)) + .thenReturn(List.of(candidate(FIRST_ID, 90L), candidate(SECOND_ID, 80L))) + .thenReturn(List.of(candidate(FIRST_ID, 90L))); + when(harness.repository.findUnsettledPageDescending(80L, 2)).thenReturn(List.of()); + when(harness.settlementService.settle(SECOND_ID, 80L)).thenReturn(secondReceipt); + when(harness.settlementService.settle(FIRST_ID, 90L)) + .thenThrow(new IllegalStateException("terminal proof remains pending")); + + var first = harness.service.reconcilePendingBatch(); + var endOfSweep = harness.service.reconcilePendingBatch(); + var wrapped = harness.service.reconcilePendingBatch(); + + assertThat(first.unresolvedCount()).isEqualTo(1); + assertThat(endOfSweep.selectedCount()).isZero(); + assertThat(wrapped.selectedCount()).isEqualTo(1); + assertThat(wrapped.unresolvedCount()).isEqualTo(1); + InOrder order = inOrder(harness.repository); + order.verify(harness.repository).findUnsettledPageDescending(null, 2); + order.verify(harness.repository).findUnsettledPageDescending(80L, 2); + order.verify(harness.repository).findUnsettledPageDescending(null, 2); + verify(harness.settlementService, times(2)).settle(FIRST_ID, 90L); + } + + @Test + void pageReadFailurePreservesCursorAndMakesNoSettlementCalls() { + Harness harness = new Harness(2); + Map receipts = + Map.of( + 90L, receipt(FIRST_ID, 90L), + 80L, receipt(SECOND_ID, 80L), + 70L, receipt(THIRD_ID, 70L), + 60L, receipt(FOURTH_ID, 60L)); + when(harness.repository.findUnsettledPageDescending(null, 2)) + .thenReturn(List.of(candidate(FIRST_ID, 90L), candidate(SECOND_ID, 80L))); + when(harness.repository.findUnsettledPageDescending(80L, 2)) + .thenThrow(new IllegalStateException("synthetic page read failure")) + .thenReturn(List.of(candidate(THIRD_ID, 70L), candidate(FOURTH_ID, 60L))); + when(harness.settlementService.settle(any(), anyLong())) + .thenAnswer(invocation -> receipts.get(invocation.getArgument(1))); + + harness.service.reconcilePendingBatch(); + assertThatThrownBy(harness.service::reconcilePendingBatch) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("page read failure"); + var afterFailure = harness.service.reconcilePendingBatch(); + + assertThat(afterFailure.selectedCount()).isEqualTo(2); + InOrder order = inOrder(harness.repository); + order.verify(harness.repository).findUnsettledPageDescending(null, 2); + order.verify(harness.repository, times(2)).findUnsettledPageDescending(80L, 2); + verify(harness.settlementService, times(4)).settle(any(), anyLong()); + } + + @Test + void nullOrMismatchedSettlementReceiptRemainsUnresolved() { + Harness missing = new Harness(1); + when(missing.repository.findUnsettledPageDescending(null, 1)) + .thenReturn(List.of(candidate(FIRST_ID, 90L))); + when(missing.settlementService.settle(FIRST_ID, 90L)).thenReturn(null); + + var missingResult = missing.service.reconcilePendingBatch(); + + assertThat(missingResult.settledCount()).isZero(); + assertThat(missingResult.unresolvedCount()).isEqualTo(1); + + Harness changedId = new Harness(1); + StoredSettlement wrongIdReceipt = receipt(SECOND_ID, 90L); + when(changedId.repository.findUnsettledPageDescending(null, 1)) + .thenReturn(List.of(candidate(FIRST_ID, 90L))); + when(changedId.settlementService.settle(FIRST_ID, 90L)).thenReturn(wrongIdReceipt); + + var changedIdResult = changedId.service.reconcilePendingBatch(); + + assertThat(changedIdResult.settledCount()).isZero(); + assertThat(changedIdResult.unresolvedCount()).isEqualTo(1); + + Harness changedFence = new Harness(1); + StoredSettlement wrongFenceReceipt = receipt(FIRST_ID, 91L); + when(changedFence.repository.findUnsettledPageDescending(null, 1)) + .thenReturn(List.of(candidate(FIRST_ID, 90L))); + when(changedFence.settlementService.settle(FIRST_ID, 90L)).thenReturn(wrongFenceReceipt); + + var changedFenceResult = changedFence.service.reconcilePendingBatch(); + + assertThat(changedFenceResult.settledCount()).isZero(); + assertThat(changedFenceResult.unresolvedCount()).isEqualTo(1); + } + + @Test + void pageCommitFailurePreservesCursorAndMakesNoSettlementCalls() { + Harness harness = new Harness(2); + harness.transactions.failCommitAt = 2; + Map receipts = + Map.of( + 90L, receipt(FIRST_ID, 90L), + 80L, receipt(SECOND_ID, 80L), + 70L, receipt(THIRD_ID, 70L), + 60L, receipt(FOURTH_ID, 60L)); + when(harness.repository.findUnsettledPageDescending(null, 2)) + .thenReturn(List.of(candidate(FIRST_ID, 90L), candidate(SECOND_ID, 80L))); + when(harness.repository.findUnsettledPageDescending(80L, 2)) + .thenReturn(List.of(candidate(THIRD_ID, 70L), candidate(FOURTH_ID, 60L))); + when(harness.settlementService.settle(any(), anyLong())) + .thenAnswer(invocation -> receipts.get(invocation.getArgument(1))); + + harness.service.reconcilePendingBatch(); + assertThatThrownBy(harness.service::reconcilePendingBatch) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synthetic page commit failure"); + verify(harness.settlementService, times(2)).settle(any(), anyLong()); + var afterFailure = harness.service.reconcilePendingBatch(); + + assertThat(afterFailure.selectedCount()).isEqualTo(2); + InOrder order = inOrder(harness.repository); + order.verify(harness.repository).findUnsettledPageDescending(null, 2); + order.verify(harness.repository, times(2)).findUnsettledPageDescending(80L, 2); + verify(harness.settlementService, times(4)).settle(any(), anyLong()); + } + + @Test + void sameInstanceConcurrentInvocationIsSkippedWhileOnePageIsBeingSettled() throws Exception { + Harness harness = new Harness(1); + CountDownLatch settlementEntered = new CountDownLatch(1); + CountDownLatch releaseSettlement = new CountDownLatch(1); + AtomicInteger activeSettlements = new AtomicInteger(); + AtomicInteger maximumActiveSettlements = new AtomicInteger(); + StoredSettlement receipt = receipt(FIRST_ID, 90L); + when(harness.repository.findUnsettledPageDescending(null, 1)) + .thenReturn(List.of(candidate(FIRST_ID, 90L))); + when(harness.settlementService.settle(FIRST_ID, 90L)) + .thenAnswer( + ignored -> { + assertOutsideTransaction(); + int active = activeSettlements.incrementAndGet(); + maximumActiveSettlements.accumulateAndGet(active, Math::max); + settlementEntered.countDown(); + try { + if (!releaseSettlement.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("test did not release settlement call"); + } + return receipt; + } finally { + activeSettlements.decrementAndGet(); + } + }); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future first = + executor.submit(harness.service::reconcilePendingBatch); + assertThat(settlementEntered.await(5, TimeUnit.SECONDS)).isTrue(); + + var overlapping = harness.service.reconcilePendingBatch(); + + assertThat(overlapping.skippedBecauseActive()).isTrue(); + releaseSettlement.countDown(); + assertThat(first.get(5, TimeUnit.SECONDS).settledCount()).isEqualTo(1); + assertThat(maximumActiveSettlements.get()).isEqualTo(1); + verify(harness.repository, times(1)).findUnsettledPageDescending(null, 1); + verify(harness.settlementService, times(1)).settle(FIRST_ID, 90L); + } finally { + releaseSettlement.countDown(); + executor.shutdownNow(); + } + } + + @Test + void endUserAndAmbientTransactionAreRejectedBeforePageSelection() { + Harness harness = new Harness(2); + SessionContext.setContext("123", List.of(), Map.of()); + + assertStatus(Status.Code.PERMISSION_DENIED, harness.service::reconcilePendingBatch); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus(Status.Code.FAILED_PRECONDITION, harness.service::reconcilePendingBatch); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertStatus(Status.Code.FAILED_PRECONDITION, harness.service::reconcilePendingBatch); + + verifyNoInteractions(harness.repository, harness.settlementService); + assertThat(harness.transactions.begins).isZero(); + } + + @Test + void constructorRequiresAServiceBoundedPageSize() { + assertThatThrownBy(() -> new Harness(0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Bounded positive"); + assertThatThrownBy( + () -> + new AccountStartSessionAdmissionProtectionReconciliationService( + mock(AccountStartSessionAdmissionProtectionRepository.class), + mock(AccountStartSessionAdmissionProtectionSettlementService.class), + new PageTransactions(), + AccountStartSessionAdmissionProtectionRepository.MAX_PENDING_SWEEP_SIZE + 1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Bounded positive"); + } + + private static void assertWritablePageTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(Connection.TRANSACTION_READ_COMMITTED); + } + + private static void assertOutsideTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static PendingProtection candidate(UUID id, long fence) { + return new PendingProtection(id, fence); + } + + private static StoredSettlement receipt(UUID id, long fence) { + StoredSettlement receipt = mock(StoredSettlement.class); + when(receipt.protectionId()).thenReturn(id); + when(receipt.protectionFence()).thenReturn(fence); + return receipt; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static void assertStatus(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable((Throwable) failure).getCode()).isEqualTo(code)); + } + + private static final class Harness { + final AccountStartSessionAdmissionProtectionRepository repository = + mock(AccountStartSessionAdmissionProtectionRepository.class); + final AccountStartSessionAdmissionProtectionSettlementService settlementService = + mock(AccountStartSessionAdmissionProtectionSettlementService.class); + final PageTransactions transactions = new PageTransactions(); + final AccountStartSessionAdmissionProtectionReconciliationService service; + + Harness(int pageSize) { + service = + new AccountStartSessionAdmissionProtectionReconciliationService( + repository, settlementService, transactions, pageSize); + } + } + + private static final class PageTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + int rollbacks; + int failCommitAt = -1; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + assertWritablePageTransaction(); + commits++; + if (commits == failCommitAt) { + throw new IllegalStateException("synthetic page commit failure"); + } + } + + @Override + protected void doRollback(DefaultTransactionStatus status) { + rollbacks++; + } + } +} From 0910fe485b54253b44b1652a1bec985b014ac7ef Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:40:42 +1300 Subject: [PATCH 082/129] Bind exact empty-owner inputs and repair Account proof fixtures --- ...ame-authoring-publishing-and-activation.md | 4 + ...issionLeasePersistenceIntegrationTest.java | 20 + ...sionProtectionPostgresIntegrationTest.java | 46 +- ...ionAcquisitionPostgresIntegrationTest.java | 9 +- .../SelectedOwnerEmptySourceInputs.java | 156 ++++ .../SelectedOwnerEmptySourceInputsTest.java | 787 ++++++++++++++++++ 6 files changed, 1017 insertions(+), 5 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java 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 7fa9291ae9..2d4b8e01b3 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Exact source `9931cc5c1a89b074a5bb2cab2a96f26c5f6259ce` [Validation run 38042678886](https://github.com/benhook1013/FireMUD/actions/runs/38042678886) ended cancelled overall, but its Account check completed with failure and uploaded originating XML: 1,332 unit cases pass; 308 integration cases execute with eighteen failures, no errors and no skips. Eight of the nine real Account acquisition/settlement/paging cases pass, including all three settlement cases and the single-candidate paging case; their Game Session and World evidence remains stipulated, so this is not genuine cross-owner admission. The ninth case reaches the deliberate generic-source-history denial rather than its stale expected creator-role message; existing closed-receipt currentness restrictions remain intact. All nine protection-integrity cases fail the shared fixture capture insert; the first exception identifies `account_start_session_capture_captured_at_millis` and a sub-millisecond `captured_at`. The correction truncates only that capture to milliseconds, preserving the deliberately microsecond-precision original expiry. Failure-only diagnostics preserve the original exception and disclose safe identifiers, not evidence or row values. Five legacy lease cases and two protected-entry prototype cases report WAL-coverage denials; the sixth lease case instead fails a lost-acknowledgement assertion and does not independently establish the same cause. Post-failure locator mappings identify current catalog relations only, not historical identity, backend attribution, causation or durable flush. Production WAL and source-currentness guards remain unchanged. Corrected fixture PostgreSQL execution and admission durability remain required. Tested merge `5bdca37edb0db7ab10c48f22cce00cc022c8fa7c`, tree `7ed297fd1cff734b593e4448c09930e9d9739efe`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and exact source `9931cc5c1a89b074a5bb2cab2a96f26c5f6259ce`, not the separately recorded integration parent. Cancelled overall status does not erase uploaded completed Account evidence; skipped duplicate jobs supply no proof. + Distinct original-StartSession Account admission protection is prepared under [ADR 0047's canonical lifecycle](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection). It authenticates the original Game Session receiving workload, obtains the exact current original-attempt observation outside SQL, then revalidates the original actor/JTI/reference and unchanged complete capture through the existing Account currentness callback. V133 retains the complete request, actual mutation/attempt/fence and unchanged finite expiry, original World participation, full World hold, immutable capture and exact source children; additive writer/disclosure hooks preserve the existing assembled owner checks. A settled World row supplies historical binding, not current authority: acquisition must freshly prove unchanged original sources after a gap. Independent lookup-only readback returns the first protection unchanged. V129 World settlement and V131 observation are unchanged. Forward V134 prepares closed terminal-settlement integrity checks and preserves the existing immutable receipt and source-writer guards; expiry, missing or ambiguous proof cannot release protection. The producer, settlement composition and bounded recovery batch remain unregistered and do not enable admission. The prepared acquisition transport exposes the [closed Account RPC](../../../protos/account/v1/start_session_admission_protection_acquisition.proto), with the mTLS client in Common Security so it can reject authenticated end-user context before transport. Its caller supplies the complete original tuple, actual Game Session mutation/attempt/fence and full World hold, not private Account participation coordinates; Account resolves the unchanged retained participation within its fresh currentness callback. It authenticates the exact Game Session workload before parsing and returns complete canonical evidence rather than selected hashes. The exact original PostgreSQL lease is retained at microsecond precision, with six canonical fractional digits and no rounding or renewal. V133 compares the full World hold's canonical `sha256:`-prefixed digest. Nine repository integrity definitions cover exact retained sub-millisecond expiry, changed caller expiry without modifying the stored row, and forged digest rejection; five real-Account producer definitions cover acquisition/retry/readback, lost acknowledgement, changed sources after World settlement, protection beyond World settlement and expiry, and expiry while waiting for the original issuance lock. The expired-protection case also verifies full historical lookup-only readback without renewal or settlement. Logging, Game Session and World collaborators are stipulated; these definitions do not establish genuine cross-owner execution. @@ -18,6 +20,8 @@ Exact source `e6b0d6d2b901e785c955bbf5f8c606578adfdc15` [Validation run 38038069 Fresh Entity/Automation empty-source receipts remain concrete producer obligations. Entity currently has partial numeric-tenant storage for items, NPCs, recipes/ingredients, equipment slots and body layouts, but no typed provider for fourteen of the required 23 inventory families. Automation has script definitions, event bindings and patch/base identity, with retained unbound rows still denied. Neither owner has a complete canonical-UUID census, shared writer exclusion and immutable selected-source receipt/readback. Missing tables, a declared empty array, a synthetic version marker or an unqualified zero query cannot prove owner absence; existing numeric content cannot be assigned by borrowing Game Design's private key. The next cut must establish the actual fresh owner scope and full census before replacing stipulated publication participants. +The prepared shared `SelectedOwnerEmptySourceInputs` value exact-compares the supplied finalized Account binding with the World response, selected commit and canonical tenant/version/namespace. It requires the supported complete World inbound closure and the recipient's typed TEMPLATE_CONFIG inventory declaration, preserves that declaration's original inherited revision provenance, and rejects recipient-owned template references and nonempty Entity spawn input. This is local input-integrity composition only, not authenticated producer evidence, complete database census, continuously held authority or an owner terminal receipt. Its proof remains bounded to synthetic immutable inputs and must not be used to replace the owner obligations above. + Exact source `1f9f673095e4ac8f5bb6b9c0a969469854de4d86` [Validation run 38035808533](https://github.com/benhook1013/FireMUD/actions/runs/38035808533) failed the required gate: Account executed 1,304 unit cases with one missing-client-certificate matcher assertion failure. Retained XML and logs omit the transport exception/cause, so its cause and subsequent no-handler assertions are unproved for that run. The local corrected batch preserves the strict TLS matcher and required client certificate, adds failure diagnostics, and executes all four native cases successfully without weakening denial. Account's integration task never ran in that CI run; no PostgreSQL durability or acquisition proof follows. The tested merge `2be00c0c20e4feb76097547b9e9992c53e3ae6e3` has tree `96a7913e52c5ce281c81093e1b225fb3e9344ee2` and ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, not the separately recorded integration parent. The approved failure-only diagnostic now maps bounded captured WAL relation locators through the same run-owned database's current catalog after failure; missing, reused, changed or cross-database locators remain inconclusive. It has no executed PostgreSQL result and establishes neither historical relation identity, backend origin nor timing causation. Historical source `0a99100a98ee19197bf162a4c1c202acec8e9055` [Validation run 38032471916](https://github.com/benhook1013/FireMUD/actions/runs/38032471916) ended cancelled with a failed required gate. Originating Account XML records 292 integration executions, 12 failures and no skips: six of seven V133 cases failed at the now-corrected hold-digest comparison; four of 40 admission-lease cases and two of ten isolated prototype cases failed WAL coverage. World executed 221 cases without failures or skips. Game Design XML records 146 successful executions before its later checks were cancelled, not a completed passing job. The actual tested merge `21819de08ba16420f1749a5de4e37ada1b842b2c` has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source; it is not proof against the separately recorded integration parent. Corrected V133 physical execution remains required. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index 96787ce4a3..e26894ef78 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -14,6 +14,7 @@ import java.sql.SQLException; import java.sql.Statement; import java.time.Instant; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -75,13 +76,32 @@ class AccountGameplayAdmissionLeasePersistenceIntegrationTest { (context, failure) -> { // Only unexpected test failures reach this hook; expected assertThrows cases do not. try { + String testName = context.getRequiredTestMethod().getName(); + boolean confirmationCase = + "staleSerializableConfirmationInsertRetriesInsteadOfLeakingUniqueViolation" + .equals(testName) + || "idlePrimaryConfirmationCapturesBeforeLocksAndIndependentlyReadsExactReceipt" + .equals(testName); Throwable cause = failure; + var causeTypes = new ArrayList(); var visited = java.util.Collections.newSetFromMap( new java.util.IdentityHashMap()); while (cause != null && visited.add(cause)) { + causeTypes.add(cause.getClass().getSimpleName()); if (cause instanceof PSQLException postgresFailure) { var error = postgresFailure.getServerErrorMessage(); + if (confirmationCase) { + System.err.printf( + "Account admission confirmation failure for %s: causeTypes=%s " + + "SQLSTATE=%s constraint=%s%n", + testName, + causeTypes, + postgresFailure.getSQLState(), + error == null + ? "" + : Objects.toString(error.getConstraint(), "")); + } if ("23514".equals(postgresFailure.getSQLState()) && error != null && ("account_admission_confirmation_wal_coverage".equals(error.getConstraint()) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index 7cdea75093..fd7395ee2d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -6,9 +6,11 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.sql.Connection; +import java.sql.SQLException; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; import java.util.Base64; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -30,6 +32,7 @@ import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -558,6 +561,7 @@ private static Fixture fixture(long leaseMillis) { dsl.fetchSingle( "SELECT date_trunc('milliseconds', clock_timestamp()) + INTERVAL '123 microseconds'") .get(0, OffsetDateTime.class); + OffsetDateTime capturedAt = now.truncatedTo(ChronoUnit.MILLIS); UUID tenant = UUID.randomUUID(); UUID instance = UUID.randomUUID(); UUID actor = UUID.randomUUID(); @@ -723,7 +727,7 @@ private static Fixture fixture(long leaseMillis) { "issuance_fence_source_version", 1L, "captured_at", - now, + capturedAt, "snapshot_sha256", hash(snapshot), "canonical_snapshot_bytes", @@ -864,7 +868,45 @@ private static void insert(DSLContext dsl, String table, Object... fields) { Map, Object> values = new LinkedHashMap<>(); for (int index = 0; index < fields.length; index += 2) values.put(DSL.field(DSL.name((String) fields[index])), fields[index + 1]); - dsl.insertInto(DSL.table(DSL.name(table))).set(values).execute(); + try { + dsl.insertInto(DSL.table(DSL.name(table))).set(values).execute(); + } catch (RuntimeException failure) { + String sqlState = "unavailable"; + String constraint = "unavailable"; + StringBuilder causeTypes = new StringBuilder(); + var visited = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + Throwable cause = failure; + int causeCount = 0; + while (cause != null && causeCount < 32 && visited.add(cause)) { + if (causeTypes.length() > 0) causeTypes.append("->"); + causeTypes.append(diagnosticIdentifier(cause.getClass().getSimpleName())); + causeCount++; + if (cause instanceof SQLException sqlFailure && sqlFailure.getSQLState() != null) { + sqlState = sqlFailure.getSQLState(); + } + if (cause instanceof PSQLException postgresFailure) { + var serverError = postgresFailure.getServerErrorMessage(); + if (serverError != null && serverError.getConstraint() != null) { + constraint = serverError.getConstraint(); + } + } + cause = cause.getCause(); + } + if (cause != null) causeTypes.append("->truncated"); + System.err.printf( + "StartSession admission fixture insert failed: " + + "table=%s SQLSTATE=%s constraint=%s causeTypes=%s%n", + diagnosticIdentifier(table), + diagnosticIdentifier(sqlState), + diagnosticIdentifier(constraint), + causeTypes); + throw failure; + } + } + + private static String diagnosticIdentifier(String value) { + return value != null && value.matches("[A-Za-z0-9_]+") ? value : "unavailable"; } private static Long sequenceValue(Fixture fixture) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java index 069e3685ba..2b6d552581 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java @@ -25,6 +25,7 @@ import java.util.HexFormat; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; @@ -240,10 +241,12 @@ void changedRealAccountSourceAfterSettledWorldGapDeniesWithoutAdmissionInsert() Account changed = prepared.account.tx(prepared.account::changeRoleToAdmin); assertThat(changed.getRole()).isEqualTo("admin"); + // Generic mutation history is retained, but does not prove a closed current-authority + // receipt. assertThatThrownBy( () -> prepared.acquire(prepared.acquisitionService(prepared.account.manager))) .isInstanceOf(IllegalStateException.class) - .hasMessage("Exact current authenticated initial creator required"); + .hasMessageContaining("Account source event schema is unsupported"); assertThat(rowCount(prepared.account.dsl, "account_start_session_admission_protections")) .isZero(); @@ -1031,8 +1034,8 @@ private static void assertProtectionRow( } private static void assertProtectionRowUnchanged(Record before, Record after) { - Object[] beforeValues = before.intoArray(); - Object[] afterValues = after.intoArray(); + Object[] beforeValues = Objects.requireNonNull(before.intoArray(), "before protection row"); + Object[] afterValues = Objects.requireNonNull(after.intoArray(), "after protection row"); assertThat(afterValues).hasSameSizeAs(beforeValues); for (int index = 0; index < beforeValues.length; index++) { if (beforeValues[index] instanceof byte[] bytes) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java new file mode 100644 index 0000000000..d90e70a218 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; + +/** + * Exact local inputs for composing an approved fresh empty Entity or Automation intake. + * + *

This value binds the supplied original Account owner authorization to the exact World + * inventory response and the matching typed authored declaration. It is integrity/input binding + * only: its inputs do not authenticate either producer, establish current or through-commit Account + * protection, census the complete owner database, or produce an owner receipt. + */ +public final class SelectedOwnerEmptySourceInputs { + private final SelectedOwnerIntakeAuthorizationBinding authorizationBinding; + private final SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence; + private final SelectedOwnerIntakeSourceContent sourceContent; + private final TemplateConfigOwnerSourceInventoryDeclaration ownerSourceInventoryDeclaration; + + public SelectedOwnerEmptySourceInputs( + SelectedOwnerIntakeAuthorizationBinding authorizationBinding, + SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence) { + this.authorizationBinding = + Objects.requireNonNull(authorizationBinding, "authorizationBinding"); + this.worldInventoryReadEvidence = + Objects.requireNonNull(worldInventoryReadEvidence, "worldInventoryReadEvidence"); + this.sourceContent = authorizationBinding.content(); + requireExactWorldBinding(authorizationBinding, worldInventoryReadEvidence); + requireSupportedWorldClosure(authorizationBinding.owner(), worldInventoryReadEvidence); + this.ownerSourceInventoryDeclaration = + requireOwnerDeclaration(authorizationBinding.owner(), sourceContent.templateConfigSource()); + requireNoOwnerTemplateReferences( + authorizationBinding.owner(), sourceContent.templateConfigSource()); + } + + /** Returns the exact supplied original Account owner authorization binding. */ + public SelectedOwnerIntakeAuthorizationBinding authorizationBinding() { + return authorizationBinding; + } + + /** Returns the exact supplied World response, including its original read request echo. */ + public SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence() { + return worldInventoryReadEvidence; + } + + /** Returns the immutable source content carried by the original authorization binding. */ + public SelectedOwnerIntakeSourceContent sourceContent() { + return sourceContent; + } + + /** Returns the original typed owner declaration and its unchanged source revision provenance. */ + public TemplateConfigOwnerSourceInventoryDeclaration ownerSourceInventoryDeclaration() { + return ownerSourceInventoryDeclaration; + } + + private static void requireExactWorldBinding( + SelectedOwnerIntakeAuthorizationBinding authorization, + SelectedOwnerWorldInventoryReadEvidence worldEvidence) { + var request = worldEvidence.request(); + var echoedAuthorization = request.authorizationBinding(); + if (!Arrays.equals(authorization.canonicalBytes(), echoedAuthorization.canonicalBytes()) + || !authorization.digest().equals(echoedAuthorization.digest())) { + throw new IllegalArgumentException( + "World inventory read does not echo the exact original owner authorization"); + } + + var scope = authorization.content().scope(); + var freeze = request.freezeEvidence().request(); + var selected = authorization.selected(); + var echoedSelected = freeze.accountBinding().input().selection().selectedCommit(); + var publicInventory = worldEvidence.inventory().publicEvidence(); + var publicOwner = publicInventory.ownerScope(); + if (!authorization.targetNamespace().equals(request.targetNamespace()) + || !scope.targetNamespace().equals(request.targetNamespace()) + || !request.targetNamespace().equals(freeze.targetNamespace()) + || !request.targetNamespace().equals(publicOwner.targetNamespace()) + || !selected.target().canonicalTenantId().equals(freeze.canonicalTenantId()) + || !selected.target().canonicalVersionId().equals(freeze.canonicalVersionId()) + || !selected.target().canonicalTenantId().equals(publicOwner.canonicalTenantId()) + || !selected.target().canonicalVersionId().equals(publicOwner.canonicalVersionId()) + || !Arrays.equals(selected.canonicalBytes(), echoedSelected.canonicalBytes()) + || !selected.digest().equals(echoedSelected.digest()) + || !Arrays.equals( + selected.canonicalBytes(), request.authorizationBinding().selected().canonicalBytes()) + || !selected.digest().equals(request.authorizationBinding().selected().digest()) + || !selected + .commitId() + .toString() + .equals(publicInventory.selectedApplication().appliedCommitId()) + || !selected.digest().equals(publicInventory.selectedApplication().bindingDigest())) { + throw new IllegalArgumentException( + "World inventory read differs from the exact selected owner scope or commit"); + } + } + + private static void requireSupportedWorldClosure( + Owner owner, SelectedOwnerWorldInventoryReadEvidence worldEvidence) { + WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence inventory = + worldEvidence.inventory().publicEvidence(); + var sourceModel = inventory.sourceModel(); + if (!WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA.equals( + inventory.schema()) + || inventory.schemaVersion() + != WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION + || !WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL.equals( + sourceModel.modelId()) + || sourceModel.graphSchemaVersion() + != WorldSelectedPublicationArtifactInventoryEvidence + .INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION + || sourceModel.inboundSourceClosure() == null) { + throw new IllegalArgumentException( + "Selected World inventory requires the supported complete v2 inbound closure"); + } + if (owner == Owner.ENTITY_MANAGEMENT && sourceModel.spawnBindingCount() != 0) { + throw new IllegalArgumentException( + "Entity empty-source intake cannot bind a nonempty World spawn inventory"); + } + } + + private static TemplateConfigOwnerSourceInventoryDeclaration requireOwnerDeclaration( + Owner owner, TemplateConfigSourceSnapshot snapshot) { + if (snapshot.ownerSourceInventoryDeclarations().isEmpty()) { + throw new IllegalArgumentException( + "Selected template config requires its original v2 owner inventory declaration"); + } + return snapshot.ownerSourceInventoryDeclarations().stream() + .filter(declaration -> declaration.owner() == owner) + .findFirst() + .orElseThrow( + () -> + new IllegalArgumentException( + "Selected template config has no declaration for the authorized owner")); + } + + private static void requireNoOwnerTemplateReferences( + Owner owner, TemplateConfigSourceSnapshot snapshot) { + for (var entry : snapshot.entries()) { + boolean conflict = + switch (owner) { + case ENTITY_MANAGEMENT -> entry.config().hasEntityReferences(); + case AUTOMATION_SCRIPTING -> entry.config().hasAutomationReferences(); + default -> throw new IllegalArgumentException("Unsupported selected source owner"); + }; + if (conflict) { + throw new IllegalArgumentException( + "Selected template config contains a reference owned by the intake recipient"); + } + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java new file mode 100644 index 0000000000..927d4242d6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java @@ -0,0 +1,787 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.Config; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.Entry; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues.OperationKind; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; +import org.junit.jupiter.api.Test; + +class SelectedOwnerEmptySourceInputsTest { + private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final String TEMPLATE_CONFIG = + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + VERSION + + "\",\"world\":{\"regions\":[],\"rooms\":[]}," + + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]}," + + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}}," + + "\"supportedSettings\":[]}"; + + @Test + void retainsTheExactEmptyInputsAndOriginalDeclarationForBothOwners() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + Fixture fixture = fixture(owner, Options.defaults()); + + var result = + new SelectedOwnerEmptySourceInputs( + fixture.authorization(), fixture.worldInventoryReadEvidence()); + + assertThat(result.authorizationBinding()).isSameAs(fixture.authorization()); + assertThat(result.worldInventoryReadEvidence()) + .isSameAs(fixture.worldInventoryReadEvidence()); + assertThat(result.sourceContent()).isSameAs(fixture.authorization().content()); + var actualDeclaration = result.ownerSourceInventoryDeclaration(); + var expectedDeclaration = fixture.expectedDeclaration(); + assertThat(actualDeclaration.object()).isEqualTo(expectedDeclaration.object()); + assertThat(actualDeclaration.owner()).isEqualTo(owner); + assertThat(actualDeclaration.inventoryJson()).isEqualTo(expectedDeclaration.inventoryJson()); + assertThat(actualDeclaration.sourceBinding().canonicalBytes()) + .containsExactly(expectedDeclaration.sourceBinding().canonicalBytes()); + assertThat(actualDeclaration.sourceBinding().digest()) + .isEqualTo(expectedDeclaration.sourceBinding().digest()); + assertThat(actualDeclaration.sourceBinding().commitId()) + .isNotEqualTo(fixture.authorization().selected().commitId()); + assertThat(actualDeclaration.revisionOrder()).isEqualTo(expectedDeclaration.revisionOrder()); + assertThat(actualDeclaration.revisionId()).isEqualTo(expectedDeclaration.revisionId()); + assertThat(actualDeclaration.revisionOrder()) + .isEqualTo(owner == Owner.ENTITY_MANAGEMENT ? "0" : "1"); + assertThat( + fixture + .worldInventoryReadEvidence() + .inventory() + .publicEvidence() + .sourceModel() + .familyCounts()) + .extracting(FamilyCount::family) + .contains("ROOM", "ROOM_EXIT"); + } + } + + @Test + void rejectsChangedOriginalBindingContentNamespaceAndSelectedCommit() { + Fixture original = fixture(Owner.ENTITY_MANAGEMENT, Options.defaults()); + + Fixture changedBinding = + fixture( + Owner.ENTITY_MANAGEMENT, + Options.defaults().withOperation(id("55555555-5555-4555-8555-555555555551"))); + assertRejected(original.authorization(), changedBinding.worldInventoryReadEvidence()); + + Fixture changedContent = + fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withSourceEpoch("2")); + assertRejected(original.authorization(), changedContent.worldInventoryReadEvidence()); + + Fixture changedReadNamespace = + fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withNamespace("other")); + assertRejected(original.authorization(), changedReadNamespace.worldInventoryReadEvidence()); + + Fixture changedCommit = + fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withSelectedVariant(1)); + assertRejected(original.authorization(), changedCommit.worldInventoryReadEvidence()); + } + + @Test + void rejectsMissingAndOtherOwnerOnlyDeclarationsFromTemplateConfigSnapshot() { + Fixture missing = + fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withDeclarationOwners(List.of())); + assertThat(missing.authorization().content().templateConfigSource().canonicalJson()) + .contains(TemplateConfigSourceSnapshot.SCHEMA); + assertRejected(missing.authorization(), missing.worldInventoryReadEvidence()); + + Fixture otherOwnerOnly = + fixture( + Owner.ENTITY_MANAGEMENT, + Options.defaults().withDeclarationOwners(List.of(Owner.AUTOMATION_SCRIPTING))); + assertThat(otherOwnerOnly.authorization().content().templateConfigSource().canonicalJson()) + .contains(TemplateConfigSourceSnapshot.SCHEMA_V2); + assertRejected(otherOwnerOnly.authorization(), otherOwnerOnly.worldInventoryReadEvidence()); + } + + @Test + void rejectsAllOwnerSpecificTemplateReferencesInEveryEntry() { + for (String collection : List.of("items", "npcs")) { + String key = "items".equals(collection) ? "items" : "npcs"; + Config config = + new Config( + TEMPLATE_CONFIG.replace( + "\"" + key + "\":[]", + "\"" + + key + + "\":[{\"entityTemplateId\":\"" + + "33333333-3333-4333-8333-333333333333" + + "\"}]")); + Fixture fixture = + fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withEntries(List.of(config))); + assertRejected(fixture.authorization(), fixture.worldInventoryReadEvidence()); + } + + Config scripts = + new Config( + TEMPLATE_CONFIG.replace( + "\"scripts\":[]", + "\"scripts\":[{\"scriptId\":\"authored-script\",\"eventBindings\":[]}]")); + Fixture scriptReference = + fixture(Owner.AUTOMATION_SCRIPTING, Options.defaults().withEntries(List.of(scripts))); + assertRejected(scriptReference.authorization(), scriptReference.worldInventoryReadEvidence()); + + Config patch = + new Config( + TEMPLATE_CONFIG.replace( + "\"presence\":\"ABSENT\"", + "\"presence\":\"PRESENT\",\"scriptPatchVersion\":\"patch-1\"")); + Fixture patchReference = + fixture(Owner.AUTOMATION_SCRIPTING, Options.defaults().withEntries(List.of(patch))); + assertRejected(patchReference.authorization(), patchReference.worldInventoryReadEvidence()); + } + + @Test + void rejectsLegacyOrMissingWorldClosureAndEntitySpawnBindings() { + Fixture legacyWorld = + fixture( + Owner.ENTITY_MANAGEMENT, Options.defaults().withWorldProfile(WorldProfile.LEGACY_V1)); + assertRejected(legacyWorld.authorization(), legacyWorld.worldInventoryReadEvidence()); + + assertThatThrownBy( + () -> + fixture( + Owner.ENTITY_MANAGEMENT, + Options.defaults().withWorldProfile(WorldProfile.MISSING_CLOSURE_V2))) + .isInstanceOf(IllegalArgumentException.class); + + Fixture entitySpawn = fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withSpawnBindings(1)); + assertRejected(entitySpawn.authorization(), entitySpawn.worldInventoryReadEvidence()); + } + + private static void assertRejected( + SelectedOwnerIntakeAuthorizationBinding authorization, + SelectedOwnerWorldInventoryReadEvidence worldEvidence) { + assertThatThrownBy(() -> new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Fixture fixture(Owner owner, Options options) { + DraftCommitBinding selected = selected(options.selectedVariant()); + SelectedOwnerIntakeSourceReadScope scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + options.namespace(), + options.operation(), + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + ACTOR, + selected); + var templateSnapshot = templateSnapshot(selected, options); + var sourceContent = sourceContent(scope, templateSnapshot); + var authorization = + new SelectedOwnerIntakeAuthorizationBinding(sourceContent, accountSources()); + var freezeEvidence = freezeEvidence(options.namespace(), selected, options.worldProfile()); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create( + options.namespace(), authorization, freezeEvidence); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freezeEvidence, + publicInventory(freezeEvidence, options.worldProfile(), options.spawnBindings())); + return new Fixture( + authorization, + new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory), + templateSnapshot.ownerSourceInventoryDeclarations().stream() + .filter(declaration -> declaration.owner() == owner) + .findFirst() + .orElse(null)); + } + + private static TemplateConfigSourceSnapshot templateSnapshot( + DraftCommitBinding selected, Options options) { + var declarationPayloads = new ArrayList(); + for (Owner owner : options.declarationOwners().stream().sorted().toList()) { + if (owner == Owner.AUTOMATION_SCRIPTING) { + var inventory = AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()); + declarationPayloads.add(TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory)); + } else if (owner == Owner.ENTITY_MANAGEMENT) { + var inventory = EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()); + declarationPayloads.add(TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory)); + } + } + var payloads = new ArrayList<>(declarationPayloads); + for (int index = 0; index < options.entries().size(); index++) { + payloads.add( + TemplateConfigSourceValues.createPayload("entry-" + index, options.entries().get(index))); + } + if (payloads.isEmpty()) payloads.add("{\"revisionKind\":\"COMMAND_DEFINITION\"}"); + + DraftCommitBinding authored = authoredBinding(payloads); + var mutations = TemplateConfigSourceValues.mutations(authored); + var declarations = + mutations.stream() + .filter( + mutation -> mutation.operation() == OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .sorted(java.util.Comparator.comparing(declaration -> declaration.owner().name())) + .toList(); + var entries = new ArrayList(); + for (int index = 0; index < options.entries().size(); index++) { + var revision = authored.revisions().get(declarationPayloads.size() + index); + entries.add( + new Entry( + Integer.toString(index + 1), + options.entries().get(index), + authored, + revision.revisionOrder(), + revision.revisionId(), + "entry-" + index)); + } + return new TemplateConfigSourceSnapshot( + selected, + options.sourceEpoch(), + declarations.isEmpty() ? null : authored.commitId(), + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + entries, + declarations); + } + + private static DraftCommitBinding authoredBinding(List payloads) { + List revisions = new ArrayList<>(); + for (int index = 0; index < payloads.size(); index++) { + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads.get(index))); + } + return DraftCommitBinding.create( + target(), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + VERSION.toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + SelectedOwnerIntakeSourceReadScope scope, TemplateConfigSourceSnapshot templateSnapshot) { + var out = new java.io.ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + "TEMPLATE_CONFIG".equals(family) + ? templateSnapshot.canonicalBytes() + : sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + if ("GAMEPLAY_RULE".equals(family)) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + } + return GameplayRuleManifest.canonical( + Map.of( + "schema", + "synthetic-test-only/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "family", + family)) + .getBytes(StandardCharsets.UTF_8); + } + + private static List accountSources() { + return List.of( + source(SourceKind.TENANT, TENANT.toString(), "tenant"), + source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership")); + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected(int variant) { + return DraftCommitBinding.create( + target(), + variant == 0 + ? id("33333333-3333-4333-8333-333333333333") + : id("35353535-3535-4535-8535-353535353535"), + variant == 0 + ? id("44444444-4444-4444-8444-444444444444") + : id("45454545-4545-4545-8454-454545454545"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + } + + private static TargetProof target() { + return new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + String namespace, DraftCommitBinding selected, WorldProfile profile) { + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + TENANT, + VERSION, + "publication-request", + "9", + "selected-owner intake fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), + List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication"))); + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + namespace, + TENANT, + VERSION, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + freezeRequest, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + profile == WorldProfile.LEGACY_V1 ? 3 : 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + WorldProfile profile, + int spawnBindings) { + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + boolean closureProfile = profile != WorldProfile.LEGACY_V1; + InboundSourceClosureDeclaration closure = + profile == WorldProfile.INBOUND_CLOSURE_V2 ? emptyInboundClosure() : null; + var spawnInputs = + spawnBindings == 0 + ? List.of() + : List.of( + new WorldSelectedPublicationArtifactInventoryEvidence.SpawnBindingInput( + id("18181818-1818-4818-8818-181818181818"), + id("19191919-1919-4919-8919-191919191919"), + "ITEM", + "ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID", + TENANT, + VERSION, + id("20202020-2020-4020-8020-202020202020"), + 1, + 0)); + var sourceModel = + new SourceModel( + closureProfile + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL + : WorldSelectedPublicationArtifactInventoryEvidence.SOURCE_MODEL, + closureProfile + ? WorldSelectedPublicationArtifactInventoryEvidence + .INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION + : 2, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 1), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", spawnBindings)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + spawnInputs, + 0, + spawnBindings, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + closure); + var ownerScope = + new PublicOwnerScope( + request.targetNamespace(), + TENANT, + VERSION, + id("14141414-1414-4414-8414-141414141414"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("17171717-1717-4717-8717-171717171717"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new PublicEvidence( + closureProfile + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA + : WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA, + closureProfile + ? WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION + : WorldSelectedPublicationArtifactInventoryEvidence.SCHEMA_VERSION, + "COMPLETE", + ownerScope, + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint( + acknowledgement.appliedCommitId(), + acknowledgement.contentDigest(), + closureProfile ? 4 : 3), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static InboundSourceClosureDeclaration emptyInboundClosure() { + return new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + } + + private static void frame(java.io.ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(java.io.ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static String automationInventory() { + return "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[],\"SCRIPT_PATCH_SOURCES\":[]}}"; + } + + private static String entityInventory() { + return "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"; + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + private enum WorldProfile { + INBOUND_CLOSURE_V2, + LEGACY_V1, + MISSING_CLOSURE_V2 + } + + private record Options( + String namespace, + int selectedVariant, + UUID operation, + String sourceEpoch, + List declarationOwners, + List entries, + WorldProfile worldProfile, + int spawnBindings) { + private static Options defaults() { + return new Options( + "test", + 0, + id("55555555-5555-4555-8555-555555555555"), + "1", + List.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT), + List.of(), + WorldProfile.INBOUND_CLOSURE_V2, + 0); + } + + private Options withNamespace(String value) { + return new Options( + value, + selectedVariant, + operation, + sourceEpoch, + declarationOwners, + entries, + worldProfile, + spawnBindings); + } + + private Options withSelectedVariant(int value) { + return new Options( + namespace, + value, + operation, + sourceEpoch, + declarationOwners, + entries, + worldProfile, + spawnBindings); + } + + private Options withOperation(UUID value) { + return new Options( + namespace, + selectedVariant, + value, + sourceEpoch, + declarationOwners, + entries, + worldProfile, + spawnBindings); + } + + private Options withSourceEpoch(String value) { + return new Options( + namespace, + selectedVariant, + operation, + value, + declarationOwners, + entries, + worldProfile, + spawnBindings); + } + + private Options withDeclarationOwners(List values) { + return new Options( + namespace, + selectedVariant, + operation, + sourceEpoch, + values, + entries, + worldProfile, + spawnBindings); + } + + private Options withEntries(List values) { + return new Options( + namespace, + selectedVariant, + operation, + sourceEpoch, + declarationOwners, + values, + worldProfile, + spawnBindings); + } + + private Options withWorldProfile(WorldProfile value) { + return new Options( + namespace, + selectedVariant, + operation, + sourceEpoch, + declarationOwners, + entries, + value, + spawnBindings); + } + + private Options withSpawnBindings(int value) { + return new Options( + namespace, + selectedVariant, + operation, + sourceEpoch, + declarationOwners, + entries, + worldProfile, + value); + } + } + + private record Fixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence, + TemplateConfigOwnerSourceInventoryDeclaration expectedDeclaration) {} +} From 05525f1d2682fcb0d98f67a7d87343adfc95b0a0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:00:08 +1300 Subject: [PATCH 083/129] Prepare guarded Automation empty-source storage and closed command inputs --- ...ame-authoring-publishing-and-activation.md | 2 + ...issionLeasePersistenceIntegrationTest.java | 39 +- ...ationEmptySelectedSourceIntakeReceipt.java | 711 ++++++++++++++++++ ...onEmptySelectedSourceIntakeRepository.java | 457 +++++++++++ ...ationEmptySelectedSourceIntakeService.java | 175 +++++ .../V5__selected_empty_source_intake.sql | 316 ++++++++ ...edSourceIntakePostgresIntegrationTest.java | 333 ++++++++ ...ionEmptySelectedSourceIntakeValueTest.java | 291 +++++++ .../gamedesign/publication/CommandSource.java | 45 +- .../publication/CommandSourceTest.java | 97 +++ 10 files changed, 2456 insertions(+), 10 deletions(-) create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java create mode 100644 services/automation-scripting-service/src/main/resources/db/migration/V5__selected_empty_source_intake.sql create mode 100644 services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java create mode 100644 services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java create mode 100644 services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java 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 2d4b8e01b3..8b78ce5c6e 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 @@ -22,6 +22,8 @@ Fresh Entity/Automation empty-source receipts remain concrete producer obligatio The prepared shared `SelectedOwnerEmptySourceInputs` value exact-compares the supplied finalized Account binding with the World response, selected commit and canonical tenant/version/namespace. It requires the supported complete World inbound closure and the recipient's typed TEMPLATE_CONFIG inventory declaration, preserves that declaration's original inherited revision provenance, and rejects recipient-owned template references and nonempty Entity spawn input. This is local input-integrity composition only, not authenticated producer evidence, complete database census, continuously held authority or an owner terminal receipt. Its proof remains bounded to synthetic immutable inputs and must not be used to replace the owner obligations above. +Automation's prepared V5 storage cut covers its three actual authored-source families: script definitions, event bindings and script-patch base bindings; derived schedules are not a fourth authored family. It retains immutable canonical tenant/version associations, locally allocated private numeric keys and exact selected-source receipt bytes. The repository serializes allocation before source census and rejects unqualified legacy rows rather than treating absent mappings as empty. Source row and truncate guards reject writes against reserved empty scopes and require READ COMMITTED so a stale transaction snapshot cannot bypass a committed reservation. The standalone service remains unregistered and denies every new positive intake while COMMAND, REALM_POLICY, ASSET and BRANDING lack shared typed reference validation; two HELD observations do not prove continuous Account protection through commit or terminal settlement. PostgreSQL migration and writer-race definitions are not authenticated positive producer proof, and physical execution remains required. Game Design's existing command grammar now rejects unknown fields at each supported definition/effect/payload/modifier level while preserving its defined optional modifier fields; this does not add a new effect grammar or independently prove the other selected-source families closed. + Exact source `1f9f673095e4ac8f5bb6b9c0a969469854de4d86` [Validation run 38035808533](https://github.com/benhook1013/FireMUD/actions/runs/38035808533) failed the required gate: Account executed 1,304 unit cases with one missing-client-certificate matcher assertion failure. Retained XML and logs omit the transport exception/cause, so its cause and subsequent no-handler assertions are unproved for that run. The local corrected batch preserves the strict TLS matcher and required client certificate, adds failure diagnostics, and executes all four native cases successfully without weakening denial. Account's integration task never ran in that CI run; no PostgreSQL durability or acquisition proof follows. The tested merge `2be00c0c20e4feb76097547b9e9992c53e3ae6e3` has tree `96a7913e52c5ce281c81093e1b225fb3e9344ee2` and ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, not the separately recorded integration parent. The approved failure-only diagnostic now maps bounded captured WAL relation locators through the same run-owned database's current catalog after failure; missing, reused, changed or cross-database locators remain inconclusive. It has no executed PostgreSQL result and establishes neither historical relation identity, backend origin nor timing causation. Historical source `0a99100a98ee19197bf162a4c1c202acec8e9055` [Validation run 38032471916](https://github.com/benhook1013/FireMUD/actions/runs/38032471916) ended cancelled with a failed required gate. Originating Account XML records 292 integration executions, 12 failures and no skips: six of seven V133 cases failed at the now-corrected hold-digest comparison; four of 40 admission-lease cases and two of ten isolated prototype cases failed WAL coverage. World executed 221 cases without failures or skips. Game Design XML records 146 successful executions before its later checks were cancelled, not a completed passing job. The actual tested merge `21819de08ba16420f1749a5de4e37ada1b842b2c` has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source; it is not proof against the separately recorded integration parent. Corrected V133 physical execution remains required. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index e26894ef78..83f363396a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -1222,9 +1222,11 @@ void lostReceiptCommitAcknowledgementDeniesThenRecoversOnlyThroughIndependentV12 assertThatThrownBy(() -> syntheticReadPeer().call(() -> owner.confirm(request))) .isInstanceOf(StatusRuntimeException.class) .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + failure -> { + if (trace.count("physical-commit") != 1) describeLostReceiptCommitFailure(failure); + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + }); assertThat(trace.count("physical-commit")).isEqualTo(1); assertThat(trace.count("v120-read")).isZero(); @@ -3021,6 +3023,37 @@ private static ReceiptCommitEvent firstEvent(ReceiptCommitTrace trace, String ki .orElseThrow(() -> new AssertionError("Missing receipt JDBC event: " + kind)); } + private static void describeLostReceiptCommitFailure(Throwable failure) { + try { + var causeTypes = new ArrayList(); + var postgresDetails = new ArrayList(); + var visited = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + Throwable cause = failure; + while (cause != null && visited.add(cause) && causeTypes.size() < 12) { + causeTypes.add(cause.getClass().getSimpleName()); + if (cause instanceof PSQLException postgresFailure) { + var error = postgresFailure.getServerErrorMessage(); + postgresDetails.add( + "SQLSTATE=" + + postgresFailure.getSQLState() + + " constraint=" + + (error == null + ? "" + : Objects.toString(error.getConstraint(), ""))); + } + cause = cause.getCause(); + } + System.err.printf( + "Lost receipt COMMIT diagnostic: causeTypes=%s postgres=%s%n", + causeTypes, postgresDetails); + } catch (Throwable diagnosticFailure) { + System.err.println( + "Lost receipt COMMIT diagnostic unavailable: " + + diagnosticFailure.getClass().getSimpleName()); + } + } + private static void assertGlobalWalCoverageFailure(Throwable failure) { Throwable cause = failure; while (cause != null) { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java new file mode 100644 index 0000000000..acb6ff1c12 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java @@ -0,0 +1,711 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.io.ByteArrayOutputStream; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; + +/** Immutable retained outcome for one freshly founded empty Automation source scope. */ +public final class AutomationEmptySelectedSourceIntakeReceipt { + public static final String DOMAIN = "automation-empty-selected-source-intake-receipt/v1"; + public static final int MAX_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES + + SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES + + 16 * 1024; + + private final String targetNamespace; + private final UUID operationId; + private final UUID fenceId; + private final UUID intakeRequestId; + private final UUID canonicalTenantId; + private final UUID canonicalVersionId; + private final UUID selectedCommitId; + private final UUID sourceRevisionId; + private final String sourceRevisionOrder; + private final long localTenantKey; + private final long localVersionKey; + private final String requestDigest; + private final String authorizationBindingDigest; + private final byte[] authorizationBindingBytes; + private final UUID worldReadRequestId; + private final String worldReadRequestDigest; + private final byte[] worldReadRequestBytes; + private final String worldInventoryDigest; + private final byte[] worldInventoryBytes; + private final long scriptsRowCount; + private final long eventBindingsRowCount; + private final long patchBaseBindingsRowCount; + private final long unqualifiedScriptsRowCount; + private final long unqualifiedEventBindingsRowCount; + private final long unqualifiedPatchBaseBindingsRowCount; + private final long emptyAssociatedScriptsRowCount; + private final long emptyAssociatedEventBindingsRowCount; + private final long emptyAssociatedPatchBaseBindingsRowCount; + private final long selectedScopeScriptsRowCount; + private final long selectedScopeEventBindingsRowCount; + private final long selectedScopePatchBaseBindingsRowCount; + private final OffsetDateTime retainedAt; + private final byte[] canonicalBytes; + private final String receiptDigest; + private final SelectedOwnerIntakeAuthorizationBinding authorizationBinding; + private final SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence; + + private AutomationEmptySelectedSourceIntakeReceipt( + String targetNamespace, + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID selectedCommitId, + UUID sourceRevisionId, + String sourceRevisionOrder, + long localTenantKey, + long localVersionKey, + String requestDigest, + String authorizationBindingDigest, + byte[] authorizationBindingBytes, + UUID worldReadRequestId, + String worldReadRequestDigest, + byte[] worldReadRequestBytes, + String worldInventoryDigest, + byte[] worldInventoryBytes, + long scriptsRowCount, + long eventBindingsRowCount, + long patchBaseBindingsRowCount, + long unqualifiedScriptsRowCount, + long unqualifiedEventBindingsRowCount, + long unqualifiedPatchBaseBindingsRowCount, + long emptyAssociatedScriptsRowCount, + long emptyAssociatedEventBindingsRowCount, + long emptyAssociatedPatchBaseBindingsRowCount, + long selectedScopeScriptsRowCount, + long selectedScopeEventBindingsRowCount, + long selectedScopePatchBaseBindingsRowCount, + OffsetDateTime retainedAt) { + this.targetNamespace = requireText(targetNamespace, "targetNamespace"); + this.operationId = requireUuid(operationId, "operationId"); + this.fenceId = requireUuid(fenceId, "fenceId"); + this.intakeRequestId = requireUuid(intakeRequestId, "intakeRequestId"); + this.canonicalTenantId = requireUuid(canonicalTenantId, "canonicalTenantId"); + this.canonicalVersionId = requireUuid(canonicalVersionId, "canonicalVersionId"); + this.selectedCommitId = requireUuid(selectedCommitId, "selectedCommitId"); + this.sourceRevisionId = requireUuid(sourceRevisionId, "sourceRevisionId"); + this.sourceRevisionOrder = requireDecimal(sourceRevisionOrder, "sourceRevisionOrder"); + if (localTenantKey <= 0L || localVersionKey <= 0L || localTenantKey == localVersionKey) { + throw new IllegalArgumentException("Distinct positive Automation local keys are required"); + } + this.localTenantKey = localTenantKey; + this.localVersionKey = localVersionKey; + this.requestDigest = requireDigest(requestDigest, "requestDigest"); + this.authorizationBindingDigest = + requireDigest(authorizationBindingDigest, "authorizationBindingDigest"); + this.authorizationBindingBytes = + boundedBytes( + authorizationBindingBytes, + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES, + "authorizationBindingBytes"); + this.worldReadRequestId = requireUuid(worldReadRequestId, "worldReadRequestId"); + this.worldReadRequestDigest = requireDigest(worldReadRequestDigest, "worldReadRequestDigest"); + this.worldReadRequestBytes = + boundedBytes( + worldReadRequestBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES, + "worldReadRequestBytes"); + this.worldInventoryDigest = requireDigest(worldInventoryDigest, "worldInventoryDigest"); + this.worldInventoryBytes = + boundedBytes( + worldInventoryBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES, + "worldInventoryBytes"); + this.scriptsRowCount = nonnegative(scriptsRowCount, "scriptsRowCount"); + this.eventBindingsRowCount = nonnegative(eventBindingsRowCount, "eventBindingsRowCount"); + this.patchBaseBindingsRowCount = + nonnegative(patchBaseBindingsRowCount, "patchBaseBindingsRowCount"); + this.unqualifiedScriptsRowCount = + nonnegative(unqualifiedScriptsRowCount, "unqualifiedScriptsRowCount"); + this.unqualifiedEventBindingsRowCount = + nonnegative(unqualifiedEventBindingsRowCount, "unqualifiedEventBindingsRowCount"); + this.unqualifiedPatchBaseBindingsRowCount = + nonnegative(unqualifiedPatchBaseBindingsRowCount, "unqualifiedPatchBaseBindingsRowCount"); + this.emptyAssociatedScriptsRowCount = + nonnegative(emptyAssociatedScriptsRowCount, "emptyAssociatedScriptsRowCount"); + this.emptyAssociatedEventBindingsRowCount = + nonnegative(emptyAssociatedEventBindingsRowCount, "emptyAssociatedEventBindingsRowCount"); + this.emptyAssociatedPatchBaseBindingsRowCount = + nonnegative( + emptyAssociatedPatchBaseBindingsRowCount, "emptyAssociatedPatchBaseBindingsRowCount"); + this.selectedScopeScriptsRowCount = + nonnegative(selectedScopeScriptsRowCount, "selectedScopeScriptsRowCount"); + this.selectedScopeEventBindingsRowCount = + nonnegative(selectedScopeEventBindingsRowCount, "selectedScopeEventBindingsRowCount"); + this.selectedScopePatchBaseBindingsRowCount = + nonnegative( + selectedScopePatchBaseBindingsRowCount, "selectedScopePatchBaseBindingsRowCount"); + if (Math.addExact(unqualifiedScriptsRowCount, emptyAssociatedScriptsRowCount) != scriptsRowCount + || Math.addExact(unqualifiedEventBindingsRowCount, emptyAssociatedEventBindingsRowCount) + != eventBindingsRowCount + || Math.addExact( + unqualifiedPatchBaseBindingsRowCount, emptyAssociatedPatchBaseBindingsRowCount) + != patchBaseBindingsRowCount) { + throw new IllegalArgumentException("Automation source census partitions do not add up"); + } + if (unqualifiedScriptsRowCount != 0L + || unqualifiedEventBindingsRowCount != 0L + || unqualifiedPatchBaseBindingsRowCount != 0L + || emptyAssociatedScriptsRowCount != 0L + || emptyAssociatedEventBindingsRowCount != 0L + || emptyAssociatedPatchBaseBindingsRowCount != 0L + || selectedScopeScriptsRowCount != 0L + || selectedScopeEventBindingsRowCount != 0L + || selectedScopePatchBaseBindingsRowCount != 0L) { + throw new IllegalArgumentException( + "Fresh empty Automation intake requires a zero unqualified and selected-scope census"); + } + this.retainedAt = Objects.requireNonNull(retainedAt, "retainedAt"); + if (retainedAt.getOffset().getTotalSeconds() != 0) { + throw new IllegalArgumentException("Receipt timestamp must use UTC"); + } + + this.authorizationBinding = + SelectedOwnerIntakeAuthorizationBinding.fromStored(this.authorizationBindingBytes); + if (!this.authorizationBinding.digest().equals(this.authorizationBindingDigest)) { + throw new IllegalArgumentException("Retained Account authorization digest differs"); + } + requireAuthorizationIdentity(); + this.worldInventoryReadEvidence = decodeWorldEvidence(); + this.canonicalBytes = encode(); + if (canonicalBytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Automation source receipt exceeds its size limit"); + } + this.receiptDigest = DraftAuthorizationFenceBinding.digest(canonicalBytes); + } + + static AutomationEmptySelectedSourceIntakeReceipt create( + SelectedOwnerEmptySourceInputs inputs, + long localTenantKey, + long localVersionKey, + String requestDigest, + long scriptsRowCount, + long eventBindingsRowCount, + long patchBaseBindingsRowCount, + long unqualifiedScriptsRowCount, + long unqualifiedEventBindingsRowCount, + long unqualifiedPatchBaseBindingsRowCount, + long emptyAssociatedScriptsRowCount, + long emptyAssociatedEventBindingsRowCount, + long emptyAssociatedPatchBaseBindingsRowCount, + long selectedScopeScriptsRowCount, + long selectedScopeEventBindingsRowCount, + long selectedScopePatchBaseBindingsRowCount, + OffsetDateTime retainedAt) { + Objects.requireNonNull(inputs, "validated empty-source inputs are required"); + var binding = inputs.authorizationBinding(); + var declaration = inputs.ownerSourceInventoryDeclaration(); + var worldEvidence = inputs.worldInventoryReadEvidence(); + var worldRequest = SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(worldEvidence.request()); + byte[] accountBytes = binding.canonicalBytes(); + byte[] worldRequestBytes = worldRequest.toByteArray(); + byte[] worldInventoryBytes = worldEvidence.inventory().canonicalBytes(); + return new AutomationEmptySelectedSourceIntakeReceipt( + binding.targetNamespace(), + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.tenantId(), + binding.versionId(), + binding.selected().commitId(), + declaration.revisionId(), + declaration.revisionOrder(), + localTenantKey, + localVersionKey, + requestDigest, + binding.digest(), + accountBytes, + worldEvidence.request().readRequestId(), + DraftAuthorizationFenceBinding.digest(worldRequestBytes), + worldRequestBytes, + worldEvidence.inventory().digest(), + worldInventoryBytes, + scriptsRowCount, + eventBindingsRowCount, + patchBaseBindingsRowCount, + unqualifiedScriptsRowCount, + unqualifiedEventBindingsRowCount, + unqualifiedPatchBaseBindingsRowCount, + emptyAssociatedScriptsRowCount, + emptyAssociatedEventBindingsRowCount, + emptyAssociatedPatchBaseBindingsRowCount, + selectedScopeScriptsRowCount, + selectedScopeEventBindingsRowCount, + selectedScopePatchBaseBindingsRowCount, + retainedAt); + } + + /** Strictly decodes the complete immutable owner receipt retained by Automation. */ + public static AutomationEmptySelectedSourceIntakeReceipt fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Stored Automation source receipt size is invalid"); + } + byte[] stored = bytes.clone(); + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(DOMAIN); + if (!"1".equals(reader.text())) { + throw new IllegalArgumentException("Unsupported Automation source receipt schema"); + } + var result = + new AutomationEmptySelectedSourceIntakeReceipt( + reader.text(), + parseUuid(reader.text(), "operationId"), + parseUuid(reader.text(), "fenceId"), + parseUuid(reader.text(), "intakeRequestId"), + parseUuid(reader.text(), "canonicalTenantId"), + parseUuid(reader.text(), "canonicalVersionId"), + parseUuid(reader.text(), "selectedCommitId"), + parseUuid(reader.text(), "sourceRevisionId"), + reader.text(), + parsePositiveLong(reader.text(), "localTenantKey"), + parsePositiveLong(reader.text(), "localVersionKey"), + reader.text(), + reader.text(), + reader.bytes(), + parseUuid(reader.text(), "worldReadRequestId"), + reader.text(), + reader.bytes(), + reader.text(), + reader.bytes(), + parseLong(reader.text(), "scriptsRowCount"), + parseLong(reader.text(), "eventBindingsRowCount"), + parseLong(reader.text(), "patchBaseBindingsRowCount"), + parseLong(reader.text(), "unqualifiedScriptsRowCount"), + parseLong(reader.text(), "unqualifiedEventBindingsRowCount"), + parseLong(reader.text(), "unqualifiedPatchBaseBindingsRowCount"), + parseLong(reader.text(), "emptyAssociatedScriptsRowCount"), + parseLong(reader.text(), "emptyAssociatedEventBindingsRowCount"), + parseLong(reader.text(), "emptyAssociatedPatchBaseBindingsRowCount"), + parseLong(reader.text(), "selectedScopeScriptsRowCount"), + parseLong(reader.text(), "selectedScopeEventBindingsRowCount"), + parseLong(reader.text(), "selectedScopePatchBaseBindingsRowCount"), + parseTimestamp(reader.text())); + reader.requireEnd(); + if (!Arrays.equals(stored, result.canonicalBytes)) { + throw new IllegalArgumentException("Noncanonical stored Automation source receipt"); + } + return result; + } + + public String targetNamespace() { + return targetNamespace; + } + + public UUID operationId() { + return operationId; + } + + public UUID fenceId() { + return fenceId; + } + + public UUID intakeRequestId() { + return intakeRequestId; + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public UUID canonicalVersionId() { + return canonicalVersionId; + } + + public UUID selectedCommitId() { + return selectedCommitId; + } + + public UUID sourceRevisionId() { + return sourceRevisionId; + } + + public String sourceRevisionOrder() { + return sourceRevisionOrder; + } + + public long localTenantKey() { + return localTenantKey; + } + + public long localVersionKey() { + return localVersionKey; + } + + public String requestDigest() { + return requestDigest; + } + + public String authorizationBindingDigest() { + return authorizationBindingDigest; + } + + public byte[] authorizationBindingBytes() { + return authorizationBindingBytes.clone(); + } + + public UUID worldReadRequestId() { + return worldReadRequestId; + } + + public String worldReadRequestDigest() { + return worldReadRequestDigest; + } + + public byte[] worldReadRequestBytes() { + return worldReadRequestBytes.clone(); + } + + public String worldInventoryDigest() { + return worldInventoryDigest; + } + + public byte[] worldInventoryBytes() { + return worldInventoryBytes.clone(); + } + + public long scriptsRowCount() { + return scriptsRowCount; + } + + public long eventBindingsRowCount() { + return eventBindingsRowCount; + } + + public long patchBaseBindingsRowCount() { + return patchBaseBindingsRowCount; + } + + public long unqualifiedScriptsRowCount() { + return unqualifiedScriptsRowCount; + } + + public long unqualifiedEventBindingsRowCount() { + return unqualifiedEventBindingsRowCount; + } + + public long unqualifiedPatchBaseBindingsRowCount() { + return unqualifiedPatchBaseBindingsRowCount; + } + + public long emptyAssociatedScriptsRowCount() { + return emptyAssociatedScriptsRowCount; + } + + public long emptyAssociatedEventBindingsRowCount() { + return emptyAssociatedEventBindingsRowCount; + } + + public long emptyAssociatedPatchBaseBindingsRowCount() { + return emptyAssociatedPatchBaseBindingsRowCount; + } + + public long selectedScopeScriptsRowCount() { + return selectedScopeScriptsRowCount; + } + + public long selectedScopeEventBindingsRowCount() { + return selectedScopeEventBindingsRowCount; + } + + public long selectedScopePatchBaseBindingsRowCount() { + return selectedScopePatchBaseBindingsRowCount; + } + + public OffsetDateTime retainedAt() { + return retainedAt; + } + + public String receiptDigest() { + return receiptDigest; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String outcome() { + return "COMMITTED_EMPTY"; + } + + /** This bounded slice never settles or releases Account's original source participation. */ + public String sourceParticipationDisposition() { + return "PENDING_OWNER_TERMINAL_SETTLEMENT"; + } + + SelectedOwnerIntakeAuthorizationBinding authorizationBinding() { + return authorizationBinding; + } + + SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence() { + return worldInventoryReadEvidence; + } + + /** Checks a caller retry against the original Account binding and exact selected World freeze. */ + public void requireSameRequest( + String namespace, + SelectedOwnerIntakeAuthorizationBinding candidateBinding, + WorldSelectedDraftPublicationFreezeEvidence candidateFreeze) { + Objects.requireNonNull(candidateBinding, "candidate Account binding is required"); + Objects.requireNonNull(candidateFreeze, "candidate World freeze is required"); + String candidateDigest = requestDigest(namespace, candidateBinding, candidateFreeze); + if (!targetNamespace.equals(namespace) + || !requestDigest.equals(candidateDigest) + || !Arrays.equals(authorizationBindingBytes, candidateBinding.canonicalBytes()) + || !worldInventoryReadEvidence.request().freezeEvidence().equals(candidateFreeze)) { + throw new IllegalStateException( + "Automation source intake request identity already records different selected evidence"); + } + } + + /** Also binds a concurrent first-write race to the exact newly read World inventory content. */ + void requireSameInputs(SelectedOwnerEmptySourceInputs candidateInputs) { + Objects.requireNonNull(candidateInputs, "validated empty-source inputs are required"); + var candidateBinding = candidateInputs.authorizationBinding(); + var candidateWorld = candidateInputs.worldInventoryReadEvidence(); + requireSameRequest( + candidateBinding.targetNamespace(), + candidateBinding, + candidateWorld.request().freezeEvidence()); + if (!Arrays.equals(worldInventoryBytes, candidateWorld.inventory().canonicalBytes()) + || !worldInventoryDigest.equals(candidateWorld.inventory().digest())) { + throw new IllegalStateException( + "Automation source intake request identity already records different World evidence"); + } + } + + /** Digest for the caller-stable request, excluding the fresh World read correlation. */ + public static String requestDigest( + String namespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + requireText(namespace, "targetNamespace"); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "automation-empty-selected-source-intake-request/v1"); + DraftAuthorizationFenceBinding.frame(out, namespace); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame( + out, + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freezeEvidence.request()) + .toByteArray()); + DraftAuthorizationFenceBinding.frame( + out, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freezeEvidence.acknowledgement()) + .toByteArray()); + return DraftAuthorizationFenceBinding.digest(out.toByteArray()); + } + + private void requireAuthorizationIdentity() { + if (authorizationBinding.owner() != Owner.AUTOMATION_SCRIPTING + || !authorizationBinding.schema().equals("account-automation-intake-authorization/v1") + || !authorizationBinding.purpose().equals("AUTOMATION_INTAKE_RETENTION") + || !authorizationBinding.targetNamespace().equals(targetNamespace) + || !authorizationBinding.operationId().equals(operationId) + || !authorizationBinding.fenceId().equals(fenceId) + || !authorizationBinding.intakeRequestId().equals(intakeRequestId) + || !authorizationBinding.tenantId().equals(canonicalTenantId) + || !authorizationBinding.versionId().equals(canonicalVersionId) + || !authorizationBinding.selected().commitId().equals(selectedCommitId)) { + throw new IllegalArgumentException( + "Automation receipt differs from its original Account binding"); + } + var declaration = + new SelectedOwnerEmptySourceInputs(authorizationBinding, decodeWorldEvidence()) + .ownerSourceInventoryDeclaration(); + if (declaration.owner() != Owner.AUTOMATION_SCRIPTING + || !declaration.revisionId().equals(sourceRevisionId) + || !declaration.revisionOrder().equals(sourceRevisionOrder)) { + throw new IllegalArgumentException( + "Automation receipt differs from its original source revision"); + } + if (!requestDigest.equals( + requestDigest( + targetNamespace, + authorizationBinding, + worldInventoryReadEvidence.request().freezeEvidence()))) { + throw new IllegalArgumentException("Automation receipt request digest differs"); + } + } + + private SelectedOwnerWorldInventoryReadEvidence decodeWorldEvidence() { + if (!DraftAuthorizationFenceBinding.digest(worldReadRequestBytes) + .equals(worldReadRequestDigest)) { + throw new IllegalArgumentException("Retained World read request digest differs"); + } + final ReadSelectedOwnerWorldInventoryRequest requestMessage; + try { + requestMessage = ReadSelectedOwnerWorldInventoryRequest.parseFrom(worldReadRequestBytes); + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalArgumentException("Retained World read request is malformed", invalid); + } + if (!Arrays.equals(worldReadRequestBytes, requestMessage.toByteArray())) { + throw new IllegalArgumentException("Retained World read request is not canonical"); + } + var request = SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(requestMessage); + if (!request.readRequestId().equals(worldReadRequestId) + || !request.targetNamespace().equals(targetNamespace) + || !Arrays.equals( + authorizationBindingBytes, request.authorizationBinding().canonicalBytes())) { + throw new IllegalArgumentException( + "Retained World request differs from the original binding"); + } + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromCanonicalBytes( + request.freezeEvidence(), worldInventoryBytes, worldInventoryDigest); + return new SelectedOwnerWorldInventoryReadEvidence(request, inventory); + } + + private byte[] encode() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + frame(out, DOMAIN); + frame(out, "1"); + frame(out, targetNamespace); + frame(out, operationId.toString()); + frame(out, fenceId.toString()); + frame(out, intakeRequestId.toString()); + frame(out, canonicalTenantId.toString()); + frame(out, canonicalVersionId.toString()); + frame(out, selectedCommitId.toString()); + frame(out, sourceRevisionId.toString()); + frame(out, sourceRevisionOrder); + frame(out, Long.toString(localTenantKey)); + frame(out, Long.toString(localVersionKey)); + frame(out, requestDigest); + frame(out, authorizationBindingDigest); + frame(out, authorizationBindingBytes); + frame(out, worldReadRequestId.toString()); + frame(out, worldReadRequestDigest); + frame(out, worldReadRequestBytes); + frame(out, worldInventoryDigest); + frame(out, worldInventoryBytes); + frame(out, Long.toString(scriptsRowCount)); + frame(out, Long.toString(eventBindingsRowCount)); + frame(out, Long.toString(patchBaseBindingsRowCount)); + frame(out, Long.toString(unqualifiedScriptsRowCount)); + frame(out, Long.toString(unqualifiedEventBindingsRowCount)); + frame(out, Long.toString(unqualifiedPatchBaseBindingsRowCount)); + frame(out, Long.toString(emptyAssociatedScriptsRowCount)); + frame(out, Long.toString(emptyAssociatedEventBindingsRowCount)); + frame(out, Long.toString(emptyAssociatedPatchBaseBindingsRowCount)); + frame(out, Long.toString(selectedScopeScriptsRowCount)); + frame(out, Long.toString(selectedScopeEventBindingsRowCount)); + frame(out, Long.toString(selectedScopePatchBaseBindingsRowCount)); + frame(out, retainedAt.toString()); + return out.toByteArray(); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static byte[] boundedBytes(byte[] value, int max, String label) { + if (value == null || value.length == 0 || value.length > max) { + throw new IllegalArgumentException(label + " is absent or exceeds its limit"); + } + return value.clone(); + } + + private static String requireText(String value, String label) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) { + throw new IllegalArgumentException(label + " is required"); + } + for (int i = 0; i < value.length(); i++) { + char character = value.charAt(i); + if (Character.isHighSurrogate(character)) { + if (++i >= value.length() || !Character.isLowSurrogate(value.charAt(i))) { + throw new IllegalArgumentException(label + " contains an unpaired surrogate"); + } + } else if (Character.isLowSurrogate(character)) { + throw new IllegalArgumentException(label + " contains an unpaired surrogate"); + } + } + return value; + } + + private static String requireDigest(String value, String label) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be a canonical SHA-256 digest"); + } + return value; + } + + private static String requireDecimal(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, true); + return value; + } + + private static long nonnegative(long value, String label) { + if (value < 0L) { + throw new IllegalArgumentException(label + " cannot be negative"); + } + return value; + } + + private static UUID requireUuid(UUID value, String label) { + try { + DraftAuthorizationFenceBinding.requireUuid(value); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + return value; + } + + private static UUID parseUuid(String value, String label) { + try { + UUID id = UUID.fromString(value); + if (!id.toString().equals(value)) { + throw new IllegalArgumentException("Noncanonical UUID"); + } + return requireUuid(id, label); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(label + " must be a canonical non-nil UUID", invalid); + } + } + + private static long parsePositiveLong(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, false); + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal"); + } + return parsed; + } + + private static long parseLong(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, true); + return Long.parseLong(value); + } + + private static OffsetDateTime parseTimestamp(String value) { + OffsetDateTime parsed = OffsetDateTime.parse(value); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException("Receipt timestamp is not canonical"); + } + return parsed; + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java new file mode 100644 index 0000000000..5595bc341f --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java @@ -0,0 +1,457 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered persistence boundary for immutable, freshly founded empty Automation receipts. + * + *

The source-family census is deliberately direct: absent associations never prove empty + * storage. This bounded schema only creates empty-source associations, so any row matching one of + * them is also a contradiction; rows without such a positive association are unqualified and deny a + * new founding. + */ +public final class AutomationEmptySelectedSourceIntakeRepository { + private static final String ASSOCIATION = "automation_empty_selected_source_association"; + private static final String RECEIPT = "automation_empty_selected_source_receipt"; + private static final String RESERVATION = "automation_empty_source_numeric_key_reservation"; + + private static final String READ_RECEIPT = + "SELECT a.target_namespace, a.operation_id, a.fence_id, a.intake_request_id, " + + "a.canonical_tenant_id, a.canonical_version_id, a.selected_commit_id, " + + "a.source_revision_id, a.source_revision_order, a.local_tenant_key, " + + "a.local_version_key, a.request_digest, a.authorization_binding_digest, " + + "a.receipt_digest, a.associated_at, r.request_digest, r.receipt_digest, " + + "r.receipt_bytes, r.retained_at FROM " + + ASSOCIATION + + " a LEFT JOIN " + + RECEIPT + + " r ON r.target_namespace = a.target_namespace " + + "AND r.intake_request_id = a.intake_request_id " + + "WHERE a.target_namespace = ? AND a.intake_request_id = ?"; + + private final DSLContext dsl; + + public AutomationEmptySelectedSourceIntakeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** Reads only a committed receipt; absence is not interpreted as abort or terminal settlement. */ + public Optional read( + String targetNamespace, UUID intakeRequestId) { + requireNoAmbientOwnerSql("Automation source receipt read"); + requireReadKey(targetNamespace, intakeRequestId); + return readValidated(dsl, targetNamespace, intakeRequestId); + } + + /** + * Persists one fresh empty-source receipt in an independent local transaction, then reads it back + * after commit using a separate non-transactional owner read. + */ + public AutomationEmptySelectedSourceIntakeReceipt retainFresh( + SelectedOwnerEmptySourceInputs inputs, String requestDigest) { + Objects.requireNonNull(inputs, "validated selected empty-source inputs are required"); + SelectedOwnerIntakeAuthorizationBinding binding = inputs.authorizationBinding(); + String expectedDigest = + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + binding.targetNamespace(), + binding, + inputs.worldInventoryReadEvidence().request().freezeEvidence()); + if (!expectedDigest.equals(requestDigest)) { + throw new IllegalArgumentException("Automation source intake request digest differs"); + } + if (binding.owner() != Owner.AUTOMATION_SCRIPTING) { + throw new IllegalArgumentException("Automation owner evidence is required"); + } + requireNoAmbientOwnerSql("Automation source intake transaction"); + + AutomationEmptySelectedSourceIntakeReceipt committed = + dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + lockAllocatorAndAssociations(tx); + lockSourceFamilies(tx); + + // This is the exact request/operation/scope phase of the lock order. A competing + // local founder has already completed its source census before these rows are read. + var previous = + readValidated(tx, binding.targetNamespace(), binding.intakeRequestId()); + if (previous.isPresent()) { + AutomationEmptySelectedSourceIntakeReceipt receipt = previous.orElseThrow(); + receipt.requireSameInputs(inputs); + return receipt; + } + requireNoPriorScopeOrOperation(tx, binding); + + Census census = censusAllSourceFamilies(tx); + census.requireFreshFoundingAllowed(); + + long maximumOccupiedKey = maximumOccupiedNumericKey(tx); + long localTenantKey = Math.addExact(maximumOccupiedKey, 1L); + long localVersionKey = Math.addExact(maximumOccupiedKey, 2L); + Census selectedScope = + censusSelectedNumericScope(tx, localTenantKey, localVersionKey); + selectedScope.requireSelectedScopeEmpty(); + + reserveCanonicalKey(tx, "TENANT", localTenantKey); + reserveCanonicalKey(tx, "VERSION", localVersionKey); + OffsetDateTime retainedAt = + requiredScalar(tx, "SELECT CURRENT_TIMESTAMP", OffsetDateTime.class) + .withOffsetSameInstant(ZoneOffset.UTC); + AutomationEmptySelectedSourceIntakeReceipt receipt = + AutomationEmptySelectedSourceIntakeReceipt.create( + inputs, + localTenantKey, + localVersionKey, + requestDigest, + census.scriptsRows(), + census.eventBindingRows(), + census.patchBaseBindingRows(), + census.unqualifiedScriptsRows(), + census.unqualifiedEventBindingRows(), + census.unqualifiedPatchBaseBindingRows(), + census.emptyAssociatedScriptsRows(), + census.emptyAssociatedEventBindingRows(), + census.emptyAssociatedPatchBaseBindingRows(), + selectedScope.scriptsRows(), + selectedScope.eventBindingRows(), + selectedScope.patchBaseBindingRows(), + retainedAt); + + insertAssociation(tx, receipt, retainedAt); + insertReceipt(tx, receipt, retainedAt); + return receipt; + }); + + AutomationEmptySelectedSourceIntakeReceipt readBack = + read(committed.targetNamespace(), committed.intakeRequestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Committed Automation source receipt is unavailable")); + if (!Arrays.equals(committed.canonicalBytes(), readBack.canonicalBytes()) + || !committed.receiptDigest().equals(readBack.receiptDigest()) + || !committed.requestDigest().equals(readBack.requestDigest())) { + throw new IllegalStateException("Committed Automation source receipt readback differs"); + } + return readBack; + } + + private static void lockAllocatorAndAssociations(DSLContext tx) { + tx.execute( + "LOCK TABLE " + + RESERVATION + + ", " + + ASSOCIATION + + ", " + + RECEIPT + + " IN SHARE ROW EXCLUSIVE MODE"); + } + + private static void lockSourceFamilies(DSLContext tx) { + // Fixed order shared with the source-owner allocation protocol. + tx.execute( + "LOCK TABLE script_event_bindings, script_patch_base_bindings, scripts IN SHARE MODE"); + } + + private static void requireNoPriorScopeOrOperation( + DSLContext tx, SelectedOwnerIntakeAuthorizationBinding binding) { + Record prior = + tx.fetchOne( + "SELECT intake_request_id FROM " + + ASSOCIATION + + " WHERE target_namespace = ? AND (canonical_tenant_id = ? " + + "OR canonical_version_id = ? OR operation_id = ?)", + binding.targetNamespace(), + binding.tenantId(), + binding.versionId(), + binding.operationId()); + if (prior != null) { + throw new IntakeConflictException( + "Automation canonical scope or owner operation is already associated"); + } + } + + private static Census censusAllSourceFamilies(DSLContext tx) { + long scripts = count(tx, "SELECT COUNT(*) FROM scripts"); + long eventBindings = count(tx, "SELECT COUNT(*) FROM script_event_bindings"); + long patchBaseBindings = count(tx, "SELECT COUNT(*) FROM script_patch_base_bindings"); + + long unqualifiedScripts = + count( + tx, + "SELECT COUNT(*) FROM scripts s WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = s.tenant_id " + + "AND a.local_version_key = s.base_version_id)"); + long unqualifiedEventBindings = + count( + tx, + "SELECT COUNT(*) FROM script_event_bindings b WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = b.tenant_id " + + "AND a.local_version_key = b.base_version_id)"); + long unqualifiedPatchBaseBindings = + count( + tx, + "SELECT COUNT(*) FROM script_patch_base_bindings b WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = " + + "automation_source_positive_numeric_key(b.tenant_id) " + + "AND a.local_version_key = b.base_version_id)"); + + return new Census( + scripts, + eventBindings, + patchBaseBindings, + unqualifiedScripts, + unqualifiedEventBindings, + unqualifiedPatchBaseBindings, + scripts - unqualifiedScripts, + eventBindings - unqualifiedEventBindings, + patchBaseBindings - unqualifiedPatchBaseBindings); + } + + private static Census censusSelectedNumericScope(DSLContext tx, long tenantKey, long versionKey) { + long scripts = + count( + tx, + "SELECT COUNT(*) FROM scripts WHERE tenant_id = ? OR base_version_id = ?", + tenantKey, + versionKey); + long eventBindings = + count( + tx, + "SELECT COUNT(*) FROM script_event_bindings WHERE tenant_id = ? " + + "OR base_version_id = ?", + tenantKey, + versionKey); + long patchBaseBindings = + count( + tx, + "SELECT COUNT(*) FROM script_patch_base_bindings WHERE " + + "automation_source_positive_numeric_key(tenant_id) = ? " + + "OR base_version_id = ?", + tenantKey, + versionKey); + return new Census(scripts, eventBindings, patchBaseBindings, 0L, 0L, 0L, 0L, 0L, 0L); + } + + private static long maximumOccupiedNumericKey(DSLContext tx) { + return requiredScalar( + tx, + "SELECT COALESCE(MAX(occupied_key), 0) FROM (" + + "SELECT numeric_key AS occupied_key FROM " + + RESERVATION + + " UNION ALL SELECT tenant_id FROM scripts" + + " UNION ALL SELECT base_version_id FROM scripts WHERE base_version_id IS NOT NULL" + + " UNION ALL SELECT tenant_id FROM script_event_bindings" + + " UNION ALL SELECT base_version_id FROM script_event_bindings " + + "WHERE base_version_id IS NOT NULL" + + " UNION ALL SELECT automation_source_positive_numeric_key(tenant_id) " + + "FROM script_patch_base_bindings" + + " UNION ALL SELECT base_version_id FROM script_patch_base_bindings" + + ") AS occupied", + Long.class); + } + + private static void reserveCanonicalKey(DSLContext tx, String kind, long key) { + int inserted = + tx.execute( + "INSERT INTO " + + RESERVATION + + " (key_kind, numeric_key, claim_kind) VALUES (?, ?, 'CANONICAL_EMPTY_SOURCE')", + kind, + key); + if (inserted != 1) { + throw new IntakeConflictException("Automation source numeric key was not reserved"); + } + } + + private static void insertAssociation( + DSLContext tx, + AutomationEmptySelectedSourceIntakeReceipt receipt, + OffsetDateTime retainedAt) { + int inserted = + tx.execute( + "INSERT INTO " + + ASSOCIATION + + " (target_namespace, operation_id, fence_id, intake_request_id, " + + "canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "source_revision_id, source_revision_order, local_tenant_key, " + + "local_version_key, request_digest, authorization_binding_digest, " + + "receipt_digest, associated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.targetNamespace(), + receipt.operationId(), + receipt.fenceId(), + receipt.intakeRequestId(), + receipt.canonicalTenantId(), + receipt.canonicalVersionId(), + receipt.selectedCommitId(), + receipt.sourceRevisionId(), + receipt.sourceRevisionOrder(), + receipt.localTenantKey(), + receipt.localVersionKey(), + receipt.requestDigest(), + receipt.authorizationBindingDigest(), + receipt.receiptDigest(), + retainedAt); + if (inserted != 1) { + throw new IntakeConflictException("Automation source scope association was not inserted"); + } + } + + private static void insertReceipt( + DSLContext tx, + AutomationEmptySelectedSourceIntakeReceipt receipt, + OffsetDateTime retainedAt) { + int inserted = + tx.execute( + "INSERT INTO " + + RECEIPT + + " (target_namespace, intake_request_id, request_digest, receipt_digest, " + + "receipt_bytes, retained_at) VALUES (?, ?, ?, ?, ?, ?)", + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.requestDigest(), + receipt.receiptDigest(), + receipt.canonicalBytes(), + retainedAt); + if (inserted != 1) { + throw new IntakeConflictException("Automation source receipt was not inserted"); + } + } + + private static Optional readValidated( + DSLContext context, String namespace, UUID requestId) { + Record record = context.fetchOne(READ_RECEIPT, namespace, requestId); + if (record == null) { + return Optional.empty(); + } + byte[] receiptBytes = record.get(17, byte[].class); + if (receiptBytes == null) { + throw new IllegalStateException("Automation source association has no retained receipt"); + } + AutomationEmptySelectedSourceIntakeReceipt receipt = + AutomationEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes); + if (!Objects.equals(record.get(0, String.class), receipt.targetNamespace()) + || !Objects.equals(record.get(1, UUID.class), receipt.operationId()) + || !Objects.equals(record.get(2, UUID.class), receipt.fenceId()) + || !Objects.equals(record.get(3, UUID.class), receipt.intakeRequestId()) + || !Objects.equals(record.get(4, UUID.class), receipt.canonicalTenantId()) + || !Objects.equals(record.get(5, UUID.class), receipt.canonicalVersionId()) + || !Objects.equals(record.get(6, UUID.class), receipt.selectedCommitId()) + || !Objects.equals(record.get(7, UUID.class), receipt.sourceRevisionId()) + || !Objects.equals(record.get(8, String.class), receipt.sourceRevisionOrder()) + || !Objects.equals(record.get(9, Long.class), receipt.localTenantKey()) + || !Objects.equals(record.get(10, Long.class), receipt.localVersionKey()) + || !Objects.equals(record.get(11, String.class), receipt.requestDigest()) + || !Objects.equals(record.get(12, String.class), receipt.authorizationBindingDigest()) + || !Objects.equals(record.get(13, String.class), receipt.receiptDigest()) + || !Objects.equals(record.get(15, String.class), receipt.requestDigest()) + || !Objects.equals(record.get(16, String.class), receipt.receiptDigest()) + || !Objects.equals( + record.get(18, OffsetDateTime.class).toInstant(), receipt.retainedAt().toInstant()) + || !Objects.equals( + record.get(14, OffsetDateTime.class).toInstant(), receipt.retainedAt().toInstant()) + || !Arrays.equals(receipt.canonicalBytes(), receiptBytes)) { + throw new IllegalStateException( + "Automation source receipt differs from its owner association"); + } + return Optional.of(receipt); + } + + private static long count(DSLContext context, String sql, Object... parameters) { + long value = requiredScalar(context, sql, Long.class, parameters); + if (value < 0L) { + throw new IllegalStateException("Automation source census returned an invalid count"); + } + return value; + } + + private static T requiredScalar( + DSLContext context, String sql, Class valueType, Object... parameters) { + Record record = context.fetchOne(sql, parameters); + if (record == null) { + throw new IllegalStateException("Automation owner query returned no row"); + } + T value = record.get(0, valueType); + if (value == null) { + throw new IllegalStateException("Automation owner query returned a null value"); + } + return value; + } + + private static void requireReadKey(String namespace, UUID requestId) { + if (!GrpcPeerIdentity.isValidNamespace(namespace) || requestId == null) { + throw new IllegalArgumentException("Automation source receipt lookup identity is required"); + } + DraftAuthorizationFenceBinding.requireUuid(requestId); + } + + private static void requireNoAmbientOwnerSql(String action) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException(action + " requires no ambient owner SQL"); + } + } + + private record Census( + long scriptsRows, + long eventBindingRows, + long patchBaseBindingRows, + long unqualifiedScriptsRows, + long unqualifiedEventBindingRows, + long unqualifiedPatchBaseBindingRows, + long emptyAssociatedScriptsRows, + long emptyAssociatedEventBindingRows, + long emptyAssociatedPatchBaseBindingRows) { + private void requireFreshFoundingAllowed() { + if (unqualifiedScriptsRows != 0L + || unqualifiedEventBindingRows != 0L + || unqualifiedPatchBaseBindingRows != 0L) { + throw new UnqualifiedSourceRowsException( + "Fresh Automation founding requires a positively owned empty source inventory"); + } + if (emptyAssociatedScriptsRows != 0L + || emptyAssociatedEventBindingRows != 0L + || emptyAssociatedPatchBaseBindingRows != 0L) { + throw new IntakeConflictException( + "An existing empty Automation association contains authored source rows"); + } + } + + private void requireSelectedScopeEmpty() { + if (scriptsRows != 0L || eventBindingRows != 0L || patchBaseBindingRows != 0L) { + throw new IntakeConflictException( + "Allocated Automation source scope is not empty across all source families"); + } + } + } + + public static class IntakeConflictException extends IllegalStateException { + public IntakeConflictException(String message) { + super(message); + } + } + + public static final class UnqualifiedSourceRowsException extends IntakeConflictException { + public UnqualifiedSourceRowsException(String message) { + super(message); + } + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java new file mode 100644 index 0000000000..c1314c5ed4 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java @@ -0,0 +1,175 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered preparation service for authenticated, freshly founded empty Automation scopes. + * + *

Account's HELD reads are point-in-time samples. They do not extend through Automation's local + * commit and do not settle the original Account source participation. + * + *

The current shared six-family selected-source envelope leaves COMMAND, REALM_POLICY, ASSET, + * and BRANDING opaque to Automation. This service therefore fails closed before local retention; + * typed validation of those family references is still required for a successful fresh receipt. + */ +public final class AutomationEmptySelectedSourceIntakeService { + private final AutomationEmptySelectedSourceIntakeRepository repository; + private final SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient; + private final SelectedOwnerWorldInventoryReadClient worldInventoryReadClient; + + public AutomationEmptySelectedSourceIntakeService( + AutomationEmptySelectedSourceIntakeRepository repository, + SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient, + SelectedOwnerWorldInventoryReadClient worldInventoryReadClient) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.authorizationReadClient = + Objects.requireNonNull(authorizationReadClient, "authorizationReadClient"); + this.worldInventoryReadClient = + Objects.requireNonNull(worldInventoryReadClient, "worldInventoryReadClient"); + } + + /** + * Returns an exact prior receipt for a lost-response retry, or prepares a fresh retention + * attempt. Fresh acceptance currently fails closed because four selected source families remain + * opaque to Automation. This operation does not create scripts, bindings, runtime markers, or + * activation state. + */ + public AutomationEmptySelectedSourceIntakeReceipt retain( + String targetNamespace, + SelectedOwnerIntakeAuthorizationBinding originalBinding, + WorldSelectedDraftPublicationFreezeEvidence exactFreeze) { + requireAuthenticatedGameDesignCaller(targetNamespace); + requireNoAmbientOwnerSql(); + requireRequest(targetNamespace, originalBinding, exactFreeze); + String requestDigest = + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + targetNamespace, originalBinding, exactFreeze); + + // A committed receipt is authoritative for exact lost-response retries, even after Account's + // temporary HELD state has subsequently settled. It never implies that an unrecorded request + // was aborted. + var retained = repository.read(targetNamespace, originalBinding.intakeRequestId()); + if (retained.isPresent()) { + AutomationEmptySelectedSourceIntakeReceipt receipt = retained.orElseThrow(); + receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze); + return receipt; + } + + SelectedOwnerIntakeAuthorizationReadEvidence.Request authorizationReadRequest = + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( + targetNamespace, originalBinding); + var authorizationEvidence = authorizationReadClient.read(authorizationReadRequest); + if (authorizationEvidence == null + || !authorizationReadRequest.equals(authorizationEvidence.request())) { + throw new IllegalStateException("Account did not echo the exact selected-owner read request"); + } + + SelectedOwnerWorldInventoryReadEvidence.Request worldReadRequest = + SelectedOwnerWorldInventoryReadEvidence.Request.create( + targetNamespace, originalBinding, exactFreeze); + var worldEvidence = worldInventoryReadClient.read(worldReadRequest); + if (worldEvidence == null || !worldReadRequest.equals(worldEvidence.request())) { + throw new IllegalStateException("World did not echo the exact selected-owner read request"); + } + + // This shared value validates only exact evidence integrity, complete supported inbound World + // closure, and the typed empty Automation declaration. The authenticated clients above—not + // the value itself—supply producer identity and HELD authorization. + SelectedOwnerEmptySourceInputs inputs = + new SelectedOwnerEmptySourceInputs(originalBinding, worldEvidence); + requireSupportedSelectedSourceClosure(inputs); + + // Re-sample HELD after the remote World read to reduce the gap before local commit. This is + // still not continuous protection; Account's source participation remains pending for a + // future exact terminal settlement protocol. + SelectedOwnerIntakeAuthorizationReadEvidence.Request finalAuthorizationReadRequest = + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( + targetNamespace, originalBinding); + var finalAuthorizationEvidence = authorizationReadClient.read(finalAuthorizationReadRequest); + if (finalAuthorizationEvidence == null + || !finalAuthorizationReadRequest.equals(finalAuthorizationEvidence.request())) { + throw new IllegalStateException("Account did not echo the exact final HELD read request"); + } + + AutomationEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(inputs, requestDigest); + receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze); + return receipt; + } + + private static void requireSupportedSelectedSourceClosure(SelectedOwnerEmptySourceInputs inputs) { + List opaqueFamilies = List.of("COMMAND", "REALM_POLICY", "ASSET", "BRANDING"); + for (String family : opaqueFamilies) { + // The current integrity envelope retains these exact bytes but does not expose a typed + // reference validator. Nonempty bytes or a declaration saying [] cannot prove that an + // opaque selected source contains no inbound script or hook references. + if (inputs.sourceContent().snapshotBytes(family).length > 0) { + throw new IllegalArgumentException( + "Automation selected-source closure is unsupported for opaque " + family + " content"); + } + } + } + + private static void requireAuthenticatedGameDesignCaller(String targetNamespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw new SecurityException("Authenticated same-namespace Game Design peer is required"); + } + if (AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get() != null + || SessionContext.hasAuthenticatedCallerContext() + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !targetNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + targetNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw new SecurityException( + "Selected Automation intake requires the exact same-namespace Game Design peer"); + } + } + + private static void requireRequest( + String targetNamespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + Objects.requireNonNull(binding, "original Account authorization binding is required"); + Objects.requireNonNull(freezeEvidence, "exact World freeze is required"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !targetNamespace.equals(binding.targetNamespace()) + || binding.owner() != Owner.AUTOMATION_SCRIPTING + || !binding.schema().equals("account-automation-intake-authorization/v1") + || !binding.purpose().equals("AUTOMATION_INTAKE_RETENTION")) { + throw new IllegalArgumentException( + "Fresh Automation intake requires its exact finalized Account owner binding"); + } + var freeze = freezeEvidence.request(); + if (!targetNamespace.equals(freeze.targetNamespace()) + || !binding.tenantId().equals(freeze.canonicalTenantId()) + || !binding.versionId().equals(freeze.canonicalVersionId()) + || !binding + .selected() + .equals(freeze.accountBinding().input().selection().selectedCommit())) { + throw new IllegalArgumentException( + "Automation owner binding differs from the exact selected World freeze"); + } + } + + private static void requireNoAmbientOwnerSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account and World evidence reads must run outside Automation owner SQL"); + } + } +} diff --git a/services/automation-scripting-service/src/main/resources/db/migration/V5__selected_empty_source_intake.sql b/services/automation-scripting-service/src/main/resources/db/migration/V5__selected_empty_source_intake.sql new file mode 100644 index 0000000000..bb20d86f27 --- /dev/null +++ b/services/automation-scripting-service/src/main/resources/db/migration/V5__selected_empty_source_intake.sql @@ -0,0 +1,316 @@ +-- This migration installs only the storage and writer guards for a fresh, explicitly empty +-- Automation source scope. Existing rows remain legacy/unqualified; no numeric ID is adopted. +CREATE TABLE automation_empty_source_numeric_key_reservation ( + key_kind VARCHAR(16) NOT NULL, + numeric_key BIGINT NOT NULL, + claim_kind VARCHAR(32) NOT NULL, + CONSTRAINT pk_automation_empty_source_numeric_key_reservation + PRIMARY KEY (key_kind, numeric_key), + CONSTRAINT uq_automation_empty_source_numeric_key_kind_value + UNIQUE (numeric_key, key_kind), + CONSTRAINT uq_automation_empty_source_numeric_key_claim + UNIQUE (numeric_key, key_kind, claim_kind), + CONSTRAINT ck_automation_empty_source_numeric_key_kind + CHECK (key_kind IN ('TENANT', 'VERSION')), + CONSTRAINT ck_automation_empty_source_numeric_key_positive + CHECK (numeric_key > 0), + CONSTRAINT ck_automation_empty_source_numeric_key_claim + CHECK (claim_kind IN ('LEGACY_NUMERIC', 'CANONICAL_EMPTY_SOURCE')) +); + +CREATE TABLE automation_empty_selected_source_association ( + target_namespace VARCHAR(63) NOT NULL, + operation_id UUID NOT NULL, + fence_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + source_revision_id UUID NOT NULL, + source_revision_order VARCHAR(32) NOT NULL, + local_tenant_key BIGINT NOT NULL, + local_tenant_key_kind VARCHAR(16) NOT NULL DEFAULT 'TENANT', + local_tenant_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE', + local_version_key BIGINT NOT NULL, + local_version_key_kind VARCHAR(16) NOT NULL DEFAULT 'VERSION', + local_version_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE', + request_digest VARCHAR(71) NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + associated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_automation_empty_selected_source_association + PRIMARY KEY (target_namespace, canonical_tenant_id, canonical_version_id), + CONSTRAINT uq_automation_empty_selected_source_request + UNIQUE (target_namespace, intake_request_id), + CONSTRAINT uq_automation_empty_selected_source_operation + UNIQUE (target_namespace, operation_id), + CONSTRAINT uq_automation_empty_selected_source_local_tenant + UNIQUE (local_tenant_key), + CONSTRAINT uq_automation_empty_selected_source_local_version + UNIQUE (local_version_key), + CONSTRAINT ck_automation_empty_selected_source_namespace + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT ck_automation_empty_selected_source_ids_nonzero + CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_revision_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_automation_empty_selected_source_local_keys + CHECK ( + local_tenant_key > 0 + AND local_version_key > 0 + AND local_tenant_key <> local_version_key + AND local_tenant_key_kind = 'TENANT' + AND local_tenant_key_claim_kind = 'CANONICAL_EMPTY_SOURCE' + AND local_version_key_kind = 'VERSION' + AND local_version_key_claim_kind = 'CANONICAL_EMPTY_SOURCE' + ), + CONSTRAINT ck_automation_empty_selected_source_revision_order + CHECK (source_revision_order ~ '^(0|[1-9][0-9]*)$'), + CONSTRAINT ck_automation_empty_selected_source_digests + CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT fk_automation_empty_selected_source_tenant_key + FOREIGN KEY (local_tenant_key, local_tenant_key_kind, local_tenant_key_claim_kind) + REFERENCES automation_empty_source_numeric_key_reservation + (numeric_key, key_kind, claim_kind), + CONSTRAINT fk_automation_empty_selected_source_version_key + FOREIGN KEY (local_version_key, local_version_key_kind, local_version_key_claim_kind) + REFERENCES automation_empty_source_numeric_key_reservation + (numeric_key, key_kind, claim_kind) +); + +CREATE TABLE automation_empty_selected_source_receipt ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + receipt_bytes BYTEA NOT NULL, + retained_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_automation_empty_selected_source_receipt + PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_automation_empty_selected_source_receipt_association + FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES automation_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_automation_empty_selected_source_receipt_digests + CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(receipt_bytes) BETWEEN 1 AND 58736640 + ) +); + +CREATE INDEX idx_automation_empty_source_key_claim_kind + ON automation_empty_source_numeric_key_reservation (claim_kind, key_kind, numeric_key); + +/* [jooq ignore start] */ +CREATE FUNCTION automation_source_positive_numeric_key(value_text TEXT) +RETURNS BIGINT +LANGUAGE plpgsql +IMMUTABLE +STRICT +SET search_path = pg_catalog +AS $$ +DECLARE + parsed_value NUMERIC; +BEGIN + IF value_text !~ '^[0-9]+$' THEN + RETURN NULL; + END IF; + parsed_value := value_text::NUMERIC; + IF parsed_value <= 0 OR parsed_value > 9223372036854775807 THEN + RETURN NULL; + END IF; + RETURN parsed_value::BIGINT; +END; +$$; +/* [jooq ignore stop] */ + +-- Lock allocator/association rows before source families, matching the owner allocation order. +-- Old writers can finish before the family locks and are included in this seed; later writes see +-- the reservation triggers installed below. +/* [jooq ignore start] */ +LOCK TABLE automation_empty_source_numeric_key_reservation, + automation_empty_selected_source_association, + automation_empty_selected_source_receipt IN SHARE ROW EXCLUSIVE MODE; +LOCK TABLE script_event_bindings, script_patch_base_bindings, scripts IN SHARE MODE; +/* [jooq ignore stop] */ + +-- Data-only PostgreSQL seeding uses the procedural parser above and ON CONFLICT; the jOOQ H2 +-- simulator cannot execute that seed. All table definitions remain in generation scope. +/* [jooq ignore start] */ +INSERT INTO automation_empty_source_numeric_key_reservation (key_kind, numeric_key, claim_kind) +SELECT DISTINCT key_kind, numeric_key, 'LEGACY_NUMERIC' +FROM ( + SELECT 'TENANT'::VARCHAR(16) AS key_kind, tenant_id AS numeric_key + FROM scripts WHERE tenant_id > 0 + UNION ALL + SELECT 'TENANT', tenant_id + FROM script_event_bindings WHERE tenant_id > 0 + UNION ALL + SELECT 'TENANT', automation_source_positive_numeric_key(tenant_id) + FROM script_patch_base_bindings + WHERE automation_source_positive_numeric_key(tenant_id) IS NOT NULL + UNION ALL + SELECT 'VERSION', base_version_id + FROM scripts WHERE base_version_id > 0 + UNION ALL + SELECT 'VERSION', base_version_id + FROM script_event_bindings WHERE base_version_id > 0 + UNION ALL + SELECT 'VERSION', base_version_id + FROM script_patch_base_bindings WHERE base_version_id > 0 +) AS existing_source_keys +ON CONFLICT (key_kind, numeric_key) DO NOTHING; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +CREATE FUNCTION automation_require_source_numeric_key_unreserved( + requested_kind TEXT, requested_key BIGINT +) RETURNS VOID +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + retained_claim TEXT; +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Automation authored-source row writes require READ COMMITTED isolation'; + END IF; + IF requested_key IS NULL OR requested_key <= 0 THEN + RETURN; + END IF; + SELECT claim_kind INTO retained_claim + FROM "${serviceSchema}".automation_empty_source_numeric_key_reservation + WHERE key_kind = requested_kind AND numeric_key = requested_key; + IF retained_claim = 'CANONICAL_EMPTY_SOURCE' THEN + RAISE EXCEPTION 'Automation numeric source key is reserved by an immutable empty-source receipt'; + END IF; +END; +$$; + +CREATE FUNCTION automation_guard_authored_source_row() +RETURNS TRIGGER +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + old_value JSONB; + new_value JSONB; + old_tenant_key BIGINT; + new_tenant_key BIGINT; + old_version_key BIGINT; + new_version_key BIGINT; +BEGIN + IF TG_OP IN ('UPDATE', 'DELETE') THEN + old_value := to_jsonb(OLD); + old_tenant_key := automation_source_positive_numeric_key(old_value->>'tenant_id'); + old_version_key := automation_source_positive_numeric_key(old_value->>'base_version_id'); + PERFORM automation_require_source_numeric_key_unreserved('TENANT', old_tenant_key); + PERFORM automation_require_source_numeric_key_unreserved('VERSION', old_version_key); + END IF; + IF TG_OP IN ('INSERT', 'UPDATE') THEN + new_value := to_jsonb(NEW); + new_tenant_key := automation_source_positive_numeric_key(new_value->>'tenant_id'); + new_version_key := automation_source_positive_numeric_key(new_value->>'base_version_id'); + -- Do not mutate the allocator table from a source-row trigger. PostgreSQL has already + -- acquired the source table's ROW EXCLUSIVE lock before firing this trigger, while the + -- founding path intentionally locks allocator tables first. A read-only reservation + -- check keeps that global lock order acyclic; new allocations also census every source + -- family while holding the source locks, so unreserved legacy keys cannot be missed. + PERFORM automation_require_source_numeric_key_unreserved('TENANT', new_tenant_key); + PERFORM automation_require_source_numeric_key_unreserved('VERSION', new_version_key); + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION automation_reject_authored_source_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Automation authored-source TRUNCATE requires READ COMMITTED isolation'; + END IF; + IF EXISTS ( + SELECT 1 FROM "${serviceSchema}".automation_empty_source_numeric_key_reservation + WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE' + ) THEN + RAISE EXCEPTION 'Automation authored source TRUNCATE is forbidden after canonical intake'; + END IF; + RETURN NULL; +END; +$$; + +CREATE FUNCTION automation_reject_empty_source_intake_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'Automation empty-source intake records are immutable'; +END; +$$; + +REVOKE ALL ON FUNCTION automation_require_source_numeric_key_unreserved(TEXT, BIGINT) FROM PUBLIC; +REVOKE ALL ON FUNCTION automation_guard_authored_source_row() FROM PUBLIC; +REVOKE ALL ON FUNCTION automation_reject_authored_source_truncate() FROM PUBLIC; +REVOKE ALL ON FUNCTION automation_reject_empty_source_intake_mutation() FROM PUBLIC; + +CREATE TRIGGER trg_automation_scripts_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON scripts + FOR EACH ROW EXECUTE FUNCTION automation_guard_authored_source_row(); +CREATE TRIGGER trg_automation_event_bindings_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON script_event_bindings + FOR EACH ROW EXECUTE FUNCTION automation_guard_authored_source_row(); +CREATE TRIGGER trg_automation_patch_base_bindings_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON script_patch_base_bindings + FOR EACH ROW EXECUTE FUNCTION automation_guard_authored_source_row(); + +CREATE TRIGGER trg_automation_scripts_source_no_truncate + BEFORE TRUNCATE ON scripts + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_authored_source_truncate(); +CREATE TRIGGER trg_automation_event_bindings_source_no_truncate + BEFORE TRUNCATE ON script_event_bindings + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_authored_source_truncate(); +CREATE TRIGGER trg_automation_patch_base_bindings_source_no_truncate + BEFORE TRUNCATE ON script_patch_base_bindings + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_authored_source_truncate(); + +CREATE TRIGGER trg_automation_empty_source_key_reservation_immutable + BEFORE UPDATE OR DELETE ON automation_empty_source_numeric_key_reservation + FOR EACH ROW EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +CREATE TRIGGER trg_automation_empty_source_key_reservation_no_truncate + BEFORE TRUNCATE ON automation_empty_source_numeric_key_reservation + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +CREATE TRIGGER trg_automation_empty_source_association_immutable + BEFORE UPDATE OR DELETE ON automation_empty_selected_source_association + FOR EACH ROW EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +CREATE TRIGGER trg_automation_empty_source_association_no_truncate + BEFORE TRUNCATE ON automation_empty_selected_source_association + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +CREATE TRIGGER trg_automation_empty_source_receipt_immutable + BEFORE UPDATE OR DELETE ON automation_empty_selected_source_receipt + FOR EACH ROW EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +CREATE TRIGGER trg_automation_empty_source_receipt_no_truncate + BEFORE TRUNCATE ON automation_empty_selected_source_receipt + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +/* [jooq ignore stop] */ diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java new file mode 100644 index 0000000000..fc29b14fdd --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java @@ -0,0 +1,333 @@ +package net.firedevops.firemud.automationscripting.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class AutomationEmptySelectedSourceIntakePostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DSLContext dsl; + + @BeforeAll + void migrateWithRetainedLegacyAuthoredRows() { + schema = "automation_empty_source_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target("3.2") + .load() + .migrate(); + + DSLContext upgradeDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + upgradeDsl.execute( + "INSERT INTO scripts (tenant_id, name, version, definition, base_version_id) " + + "VALUES (101, 'retained-script', 'legacy-patch', '{}', 201)"); + upgradeDsl.execute( + "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, " + + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) " + + "VALUES (102, 'legacy-patch', 'legacy-event', 'v1', 'retained-script', " + + "'TENANT', 'legacy', 202)"); + upgradeDsl.execute( + "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) " + + "VALUES ('103', 'legacy-patch', 203)"); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + } + + @AfterAll + void dropIsolatedSchema() { + if (schema != null) { + String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE"); + schema = null; + } + } + + @Test + void migrationSeedsLegacyKeysAndGuardsAllThreeAuthoredSourceFamilies() { + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation " + + "WHERE claim_kind = 'LEGACY_NUMERIC'", + Long.class)) + .isEqualTo(6L); + assertThat( + dsl.fetchValue( + "SELECT claim_kind FROM automation_empty_source_numeric_key_reservation " + + "WHERE key_kind = 'TENANT' AND numeric_key = 101", + String.class)) + .isEqualTo("LEGACY_NUMERIC"); + + reserveCanonicalScope(9001L, 9002L); + + // NEW-side guards deny writes that target either locally reserved numeric dimension. + assertRejected( + "INSERT INTO scripts (tenant_id, name, version, definition) " + + "VALUES (9001, 'blocked-script', 'v1', '{}')"); + assertRejected( + "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, " + + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) " + + "VALUES (400, 'blocked-patch', 'blocked-event', 'v1', 'blocked-script', " + + "'TENANT', 'one', 9002)"); + assertRejected( + "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) " + + "VALUES ('9001', 'blocked-patch', 400)"); + + // UPDATE checks both sides: legacy rows cannot be moved into a canonical scope. + upgradeLegacyRowsForUpdate(); + assertRejected("UPDATE scripts SET tenant_id = 9001 WHERE name = 'update-script'"); + assertRejected( + "UPDATE script_event_bindings SET base_version_id = 9002 " + + "WHERE script_patch_version = 'update-patch'"); + assertRejected( + "UPDATE script_patch_base_bindings SET tenant_id = '9001' " + + "WHERE script_patch_version = 'update-patch'"); + + // Fixture-only trigger bypass seeds rows already inside the protected scope so OLD-side + // UPDATE/DELETE rejection is exercised independently of the NEW-side checks above. + seedCanonicalRowsForOldSideChecks(); + assertRejected("DELETE FROM scripts WHERE name = 'old-side-script'"); + assertRejected("UPDATE scripts SET tenant_id = 9101 WHERE name = 'old-side-script'"); + assertRejected( + "DELETE FROM script_event_bindings WHERE script_patch_version = 'old-side-patch'"); + assertRejected( + "UPDATE script_event_bindings SET base_version_id = 9102 " + + "WHERE script_patch_version = 'old-side-patch'"); + assertRejected( + "DELETE FROM script_patch_base_bindings WHERE script_patch_version = 'old-side-patch'"); + assertRejected( + "UPDATE script_patch_base_bindings SET tenant_id = '9103' " + + "WHERE script_patch_version = 'old-side-patch'"); + + assertRejected("TRUNCATE TABLE scripts"); + assertRejected("TRUNCATE TABLE script_event_bindings"); + assertRejected("TRUNCATE TABLE script_patch_base_bindings"); + } + + @Test + void staleRepeatableReadWritersCannotMissACommittedCanonicalReservation() throws SQLException { + try (Connection staleRowWriter = repeatableReadSnapshot()) { + commitCanonicalEmptySourceFixture(9301L, 9302L); + try { + assertThatThrownBy( + () -> + execute( + staleRowWriter, + "INSERT INTO scripts (tenant_id, name, version, definition) " + + "VALUES (9301, 'stale-snapshot-script', 'v1', '{}')")) + .isInstanceOf(SQLException.class); + } finally { + staleRowWriter.rollback(); + } + } + + try (Connection staleTruncator = repeatableReadSnapshot()) { + commitCanonicalEmptySourceFixture(9401L, 9402L); + try { + assertThatThrownBy(() -> execute(staleTruncator, "TRUNCATE TABLE scripts")) + .isInstanceOf(SQLException.class); + } finally { + staleTruncator.rollback(); + } + } + } + + private void reserveCanonicalScope(long tenantKey, long versionKey) { + dsl.execute( + "INSERT INTO automation_empty_source_numeric_key_reservation " + + "(key_kind, numeric_key, claim_kind) VALUES " + + "('TENANT', ?, 'CANONICAL_EMPTY_SOURCE'), " + + "('VERSION', ?, 'CANONICAL_EMPTY_SOURCE')", + tenantKey, + versionKey); + } + + private void upgradeLegacyRowsForUpdate() { + dsl.execute( + "INSERT INTO scripts (tenant_id, name, version, definition) " + + "VALUES (410, 'update-script', 'v1', '{}')"); + dsl.execute( + "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, " + + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) " + + "VALUES (411, 'update-patch', 'update-event', 'v1', 'update-script', " + + "'TENANT', 'one', 412)"); + dsl.execute( + "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) " + + "VALUES ('413', 'update-patch', 414)"); + } + + private void seedCanonicalRowsForOldSideChecks() { + dsl.execute("ALTER TABLE scripts DISABLE TRIGGER trg_automation_scripts_source_reservation"); + dsl.execute( + "INSERT INTO scripts (tenant_id, name, version, definition) " + + "VALUES (9001, 'old-side-script', 'v1', '{}')"); + dsl.execute("ALTER TABLE scripts ENABLE TRIGGER trg_automation_scripts_source_reservation"); + + dsl.execute( + "ALTER TABLE script_event_bindings " + + "DISABLE TRIGGER trg_automation_event_bindings_source_reservation"); + dsl.execute( + "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, " + + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) " + + "VALUES (420, 'old-side-patch', 'old-side-event', 'v1', 'old-side-script', " + + "'TENANT', 'one', 9002)"); + dsl.execute( + "ALTER TABLE script_event_bindings " + + "ENABLE TRIGGER trg_automation_event_bindings_source_reservation"); + + dsl.execute( + "ALTER TABLE script_patch_base_bindings " + + "DISABLE TRIGGER trg_automation_patch_base_bindings_source_reservation"); + dsl.execute( + "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) " + + "VALUES ('9001', 'old-side-patch', 420)"); + dsl.execute( + "ALTER TABLE script_patch_base_bindings " + + "ENABLE TRIGGER trg_automation_patch_base_bindings_source_reservation"); + } + + private void assertRejected(String sql) { + assertThatThrownBy(() -> dsl.execute(sql)).isInstanceOf(DataAccessException.class); + } + + private Connection repeatableReadSnapshot() throws SQLException { + Connection connection = dataSource(schema).getConnection(); + connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + connection.setAutoCommit(false); + try (Statement statement = connection.createStatement()) { + statement + .executeQuery("SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation") + .close(); + } + return connection; + } + + private void commitCanonicalEmptySourceFixture(long tenantKey, long versionKey) + throws SQLException { + // Synthetic SQL-only rows exercise the database fence; they do not authenticate Account or + // World producers and are not proof of the physical owner path. + try (Connection founder = dataSource(schema).getConnection()) { + founder.setAutoCommit(false); + try (PreparedStatement reservation = + founder.prepareStatement( + "INSERT INTO automation_empty_source_numeric_key_reservation " + + "(key_kind, numeric_key, claim_kind) VALUES " + + "('TENANT', ?, 'CANONICAL_EMPTY_SOURCE'), " + + "('VERSION', ?, 'CANONICAL_EMPTY_SOURCE')")) { + reservation.setLong(1, tenantKey); + reservation.setLong(2, versionKey); + reservation.executeUpdate(); + } + + UUID operationId = UUID.randomUUID(); + UUID fenceId = UUID.randomUUID(); + UUID intakeRequestId = UUID.randomUUID(); + UUID canonicalTenantId = UUID.randomUUID(); + UUID canonicalVersionId = UUID.randomUUID(); + UUID selectedCommitId = UUID.randomUUID(); + UUID sourceRevisionId = UUID.randomUUID(); + String digest = "sha256:" + "c".repeat(64); + try (var association = + founder.prepareStatement( + "INSERT INTO automation_empty_selected_source_association " + + "(target_namespace, operation_id, fence_id, intake_request_id, " + + "canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "source_revision_id, source_revision_order, local_tenant_key, " + + "local_tenant_key_kind, local_tenant_key_claim_kind, local_version_key, " + + "local_version_key_kind, local_version_key_claim_kind, request_digest, " + + "authorization_binding_digest, receipt_digest, associated_at) " + + "VALUES ('example', ?, ?, ?, ?, ?, ?, ?, '1', ?, 'TENANT', " + + "'CANONICAL_EMPTY_SOURCE', ?, 'VERSION', 'CANONICAL_EMPTY_SOURCE', " + + "?, ?, ?, CURRENT_TIMESTAMP)")) { + association.setObject(1, operationId); + association.setObject(2, fenceId); + association.setObject(3, intakeRequestId); + association.setObject(4, canonicalTenantId); + association.setObject(5, canonicalVersionId); + association.setObject(6, selectedCommitId); + association.setObject(7, sourceRevisionId); + association.setLong(8, tenantKey); + association.setLong(9, versionKey); + association.setString(10, digest); + association.setString(11, digest); + association.setString(12, digest); + association.executeUpdate(); + } + try (var receipt = + founder.prepareStatement( + "INSERT INTO automation_empty_selected_source_receipt " + + "(target_namespace, intake_request_id, request_digest, receipt_digest, " + + "receipt_bytes, retained_at) VALUES ('example', ?, ?, ?, decode('01', 'hex'), " + + "CURRENT_TIMESTAMP)")) { + receipt.setObject(1, intakeRequestId); + receipt.setString(2, digest); + receipt.setString(3, digest); + receipt.executeUpdate(); + } + founder.commit(); + } + } + + private static void execute(Connection connection, String sql) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + String baseUrl = postgres.getJdbcUrl(); + dataSource.setUrl( + schemaName == null + ? baseUrl + : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } +} diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java new file mode 100644 index 0000000000..5de777a0ab --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java @@ -0,0 +1,291 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.time.OffsetDateTime; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Repository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AutomationEmptySelectedSourceIntakeValueTest { + @BeforeEach + void clearCallerContext() { + SessionContext.clear(); + } + + @AfterEach + void clearCallerAndTransactionContext() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void storedReceiptDecoderRejectsMalformedValues() { + assertThatThrownBy(() -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(new byte[] {1, 2, 3})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void intakePreparationTypesAreNotLiveSpringComponents() { + assertThat( + AutomationEmptySelectedSourceIntakeRepository.class.isAnnotationPresent( + Component.class)) + .isFalse(); + assertThat( + AutomationEmptySelectedSourceIntakeRepository.class.isAnnotationPresent( + Repository.class)) + .isFalse(); + assertThat( + AutomationEmptySelectedSourceIntakeService.class.isAnnotationPresent(Component.class)) + .isFalse(); + assertThat(AutomationEmptySelectedSourceIntakeService.class.isAnnotationPresent(Service.class)) + .isFalse(); + } + + @Test + void retainRejectsMissingAndWrongSameNamespaceWorkloadPeersBeforeInputOrOwnerRead() { + AutomationEmptySelectedSourceIntakeRepository repository = + mock(AutomationEmptySelectedSourceIntakeRepository.class); + SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient = + mock(SelectedOwnerIntakeAuthorizationReadClient.class); + SelectedOwnerWorldInventoryReadClient worldInventoryReadClient = + mock(SelectedOwnerWorldInventoryReadClient.class); + AutomationEmptySelectedSourceIntakeService service = + new AutomationEmptySelectedSourceIntakeService( + repository, authorizationReadClient, worldInventoryReadClient); + + assertThatThrownBy(() -> service.retain("example", null, null)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("Game Design peer"); + + GrpcPeerIdentity wrongPeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/account-service", "example", "account-service"); + Context wrongPeerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer); + Context previous = wrongPeerContext.attach(); + try { + assertThatThrownBy(() -> service.retain("example", null, null)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("same-namespace Game Design peer"); + } finally { + wrongPeerContext.detach(previous); + } + GrpcPeerIdentity correctPeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/game-design-service", "example", "game-design-service"); + Context correctPeerContext = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, correctPeer); + previous = correctPeerContext.attach(); + try { + SessionContext.setContext("1001", java.util.List.of(), java.util.Map.of()); + assertThatThrownBy(() -> service.retain("example", null, null)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("same-namespace Game Design peer"); + } finally { + SessionContext.clear(); + correctPeerContext.detach(previous); + } + verifyNoInteractions(repository, authorizationReadClient, worldInventoryReadClient); + } + + @Test + void retainRejectsAmbientOwnerSqlBeforeReadingAnyOwnerEvidence() { + AutomationEmptySelectedSourceIntakeRepository repository = + mock(AutomationEmptySelectedSourceIntakeRepository.class); + SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient = + mock(SelectedOwnerIntakeAuthorizationReadClient.class); + SelectedOwnerWorldInventoryReadClient worldInventoryReadClient = + mock(SelectedOwnerWorldInventoryReadClient.class); + AutomationEmptySelectedSourceIntakeService service = + new AutomationEmptySelectedSourceIntakeService( + repository, authorizationReadClient, worldInventoryReadClient); + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/game-design-service", "example", "game-design-service"); + Context peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = peerContext.attach(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> service.retain("example", null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside Automation owner SQL"); + } finally { + peerContext.detach(previous); + } + verifyNoInteractions(repository, authorizationReadClient, worldInventoryReadClient); + } + + @Test + void exactCommittedRequestRetryReturnsReceiptBeforeConsultingSettledAuthority() { + String namespace = "example"; + UUID requestId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + String requestDigest = "sha256:" + "b".repeat(64); + SelectedOwnerIntakeAuthorizationBinding binding = + mock(SelectedOwnerIntakeAuthorizationBinding.class); + DraftCommitBinding selectedCommit = mock(DraftCommitBinding.class); + when(binding.targetNamespace()).thenReturn(namespace); + when(binding.owner()).thenReturn(Owner.AUTOMATION_SCRIPTING); + when(binding.schema()).thenReturn("account-automation-intake-authorization/v1"); + when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION"); + when(binding.intakeRequestId()).thenReturn(requestId); + when(binding.tenantId()).thenReturn(tenantId); + when(binding.versionId()).thenReturn(versionId); + when(binding.selected()).thenReturn(selectedCommit); + + WorldSelectedDraftPublicationFreezeEvidence freeze = + mock(WorldSelectedDraftPublicationFreezeEvidence.class); + WorldSelectedDraftPublicationFreezeEvidence.Request freezeRequest = + mock(WorldSelectedDraftPublicationFreezeEvidence.Request.class); + AccountPublicationAuthorizationBinding publicationBinding = + mock(AccountPublicationAuthorizationBinding.class); + AccountPublicationAuthorizationBinding.PreallocationInput publicationInput = + mock(AccountPublicationAuthorizationBinding.PreallocationInput.class); + AuthoredDraftPublishSelectionBinding selection = + mock(AuthoredDraftPublishSelectionBinding.class); + when(freeze.request()).thenReturn(freezeRequest); + when(freezeRequest.targetNamespace()).thenReturn(namespace); + when(freezeRequest.canonicalTenantId()).thenReturn(tenantId); + when(freezeRequest.canonicalVersionId()).thenReturn(versionId); + when(freezeRequest.accountBinding()).thenReturn(publicationBinding); + when(publicationBinding.input()).thenReturn(publicationInput); + when(publicationInput.selection()).thenReturn(selection); + when(selection.selectedCommit()).thenReturn(selectedCommit); + + AutomationEmptySelectedSourceIntakeRepository repository = + mock(AutomationEmptySelectedSourceIntakeRepository.class); + SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient = + mock(SelectedOwnerIntakeAuthorizationReadClient.class); + SelectedOwnerWorldInventoryReadClient worldInventoryReadClient = + mock(SelectedOwnerWorldInventoryReadClient.class); + AutomationEmptySelectedSourceIntakeReceipt receipt = + mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(repository.read(namespace, requestId)).thenReturn(java.util.Optional.of(receipt)); + AutomationEmptySelectedSourceIntakeService service = + new AutomationEmptySelectedSourceIntakeService( + repository, authorizationReadClient, worldInventoryReadClient); + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/game-design-service", "example", "game-design-service"); + Context peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = peerContext.attach(); + try (MockedStatic receiptStatic = + mockStatic(AutomationEmptySelectedSourceIntakeReceipt.class)) { + receiptStatic + .when( + () -> + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + namespace, binding, freeze)) + .thenReturn(requestDigest); + assertThat(service.retain(namespace, binding, freeze)).isSameAs(receipt); + } finally { + peerContext.detach(previous); + } + verify(repository).read(namespace, requestId); + verify(receipt).requireSameRequest(namespace, binding, freeze); + verifyNoInteractions(authorizationReadClient, worldInventoryReadClient); + } + + @Test + void committedReceiptLookupReturnsTheExactStoredReceiptBytes() { + DSLContext dsl = mock(DSLContext.class); + Record record = mock(Record.class); + String namespace = "example"; + UUID operationId = UUID.randomUUID(); + UUID fenceId = UUID.randomUUID(); + UUID intakeRequestId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID selectedCommitId = UUID.randomUUID(); + UUID sourceRevisionId = UUID.randomUUID(); + String digest = "sha256:" + "a".repeat(64); + OffsetDateTime retainedAt = OffsetDateTime.parse("2026-10-10T00:00:00Z"); + byte[] canonicalBytes = new byte[] {1, 2, 3}; + AutomationEmptySelectedSourceIntakeReceipt receipt = + mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(receipt.targetNamespace()).thenReturn(namespace); + when(receipt.operationId()).thenReturn(operationId); + when(receipt.fenceId()).thenReturn(fenceId); + when(receipt.intakeRequestId()).thenReturn(intakeRequestId); + when(receipt.canonicalTenantId()).thenReturn(tenantId); + when(receipt.canonicalVersionId()).thenReturn(versionId); + when(receipt.selectedCommitId()).thenReturn(selectedCommitId); + when(receipt.sourceRevisionId()).thenReturn(sourceRevisionId); + when(receipt.sourceRevisionOrder()).thenReturn("7"); + when(receipt.localTenantKey()).thenReturn(9001L); + when(receipt.localVersionKey()).thenReturn(9002L); + when(receipt.requestDigest()).thenReturn(digest); + when(receipt.authorizationBindingDigest()).thenReturn(digest); + when(receipt.receiptDigest()).thenReturn(digest); + when(receipt.retainedAt()).thenReturn(retainedAt); + when(receipt.canonicalBytes()).thenReturn(canonicalBytes); + + when(record.get(0, String.class)).thenReturn(namespace); + when(record.get(1, UUID.class)).thenReturn(operationId); + when(record.get(2, UUID.class)).thenReturn(fenceId); + when(record.get(3, UUID.class)).thenReturn(intakeRequestId); + when(record.get(4, UUID.class)).thenReturn(tenantId); + when(record.get(5, UUID.class)).thenReturn(versionId); + when(record.get(6, UUID.class)).thenReturn(selectedCommitId); + when(record.get(7, UUID.class)).thenReturn(sourceRevisionId); + when(record.get(8, String.class)).thenReturn("7"); + when(record.get(9, Long.class)).thenReturn(9001L); + when(record.get(10, Long.class)).thenReturn(9002L); + when(record.get(11, String.class)).thenReturn(digest); + when(record.get(12, String.class)).thenReturn(digest); + when(record.get(13, String.class)).thenReturn(digest); + when(record.get(14, OffsetDateTime.class)).thenReturn(retainedAt); + when(record.get(15, String.class)).thenReturn(digest); + when(record.get(16, String.class)).thenReturn(digest); + when(record.get(17, byte[].class)).thenReturn(canonicalBytes); + when(record.get(18, OffsetDateTime.class)).thenReturn(retainedAt); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(record); + + try (MockedStatic decoder = + mockStatic(AutomationEmptySelectedSourceIntakeReceipt.class)) { + decoder + .when(() -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(canonicalBytes)) + .thenReturn(receipt); + var result = + new AutomationEmptySelectedSourceIntakeRepository(dsl).read(namespace, intakeRequestId); + assertThat(result).isPresent(); + assertThat(result.orElseThrow()).isSameAs(receipt); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java index 2e7aeec475..9cf5ec7746 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java @@ -493,6 +493,19 @@ private static void validateCommandDefinition(String json) { if (!definition.isObject() || definition.path("schemaVersion").asInt() != SCHEMA_VERSION) { throw new IllegalArgumentException("Unsupported command definition schema"); } + fields( + definition, + "schemaVersion", + "commandId", + "semanticOwner", + "executionDiscipline", + "stageRequirement", + "promptPolicy", + "actionCategory", + "historyRecordable", + "aliases", + "actionTags", + "effects"); requiredText(definition, "commandId"); requiredText(definition, "semanticOwner"); requireEnum(definition, "executionDiscipline", "DURABLE_GAMEPLAY"); @@ -524,6 +537,7 @@ private static void validateCommandDefinition(String json) { } private static void validateEffect(JsonNode effect) { + fields(effect, "effectKind", "schemaVersion", "targeting", "replayPolicy", "payload"); if (!effect.isObject() || !"APPLY_ACTION_STATE".equals(requiredText(effect, "effectKind")) || !effect.path("schemaVersion").isInt() @@ -533,8 +547,7 @@ private static void validateEffect(JsonNode effect) { throw new IllegalArgumentException("Unsupported command effect declaration"); } JsonNode payload = effect.get("payload"); - if (payload == null || !payload.isObject()) - throw new IllegalArgumentException("Effect payload must be an object"); + fields(payload, "conditionKey", "durationSeconds", "effectPayload"); requireIdentifier(payload, "conditionKey"); JsonNode duration = payload.get("durationSeconds"); if (duration == null @@ -544,13 +557,15 @@ private static void validateEffect(JsonNode effect) { } JsonNode effectPayload = payload.get("effectPayload"); JsonNode modifiers = effectPayload == null ? null : effectPayload.get("modifiers"); - if (effectPayload == null - || !effectPayload.isObject() - || modifiers == null - || !modifiers.isArray()) { + fields(effectPayload, "modifiers"); + if (modifiers == null || !modifiers.isArray()) { throw new IllegalArgumentException("Command effect modifiers must be an array"); } for (JsonNode modifier : modifiers) { + fields( + modifier, + List.of("operation", "target_key", "value"), + List.of("scope_kind", "scope_key", "priority")); if (!modifier.isObject()) throw new IllegalArgumentException("Command effect modifier must be an object"); String operation = requiredText(modifier, "operation"); @@ -625,7 +640,7 @@ private static String normalizeToken(String token) { } private static void fields(JsonNode node, String... names) { - if (!node.isObject() || node.size() != names.length) { + if (node == null || !node.isObject() || node.size() != names.length) { throw new IllegalArgumentException("Closed command source operation fields are required"); } for (String name : names) { @@ -634,6 +649,22 @@ private static void fields(JsonNode node, String... names) { } } + private static void fields(JsonNode node, List required, List optional) { + if (node == null || !node.isObject()) { + throw new IllegalArgumentException("Closed command source object fields are required"); + } + List supported = new ArrayList<>(required); + supported.addAll(optional); + if (node.properties().stream().anyMatch(property -> !supported.contains(property.getKey()))) { + throw new IllegalArgumentException("Unsupported command source field"); + } + for (String name : required) { + if (node.get(name) == null) { + throw new IllegalArgumentException("Missing command source field " + name); + } + } + } + private static void requireCounter(String value, String name) { if (value == null || !value.matches("0|[1-9][0-9]*")) { throw new IllegalArgumentException(name + " must be a canonical nonnegative decimal"); diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java new file mode 100644 index 0000000000..a0b68100de --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +class CommandSourceTest { + private static final String VALID_DEFINITION = + """ + { + "schemaVersion": 1, + "commandId": "salute", + "semanticOwner": "GAME_LOGIC", + "executionDiscipline": "DURABLE_GAMEPLAY", + "stageRequirement": "GAMEPLAY", + "promptPolicy": "WHEN_GAMEPLAY", + "actionCategory": "SOCIAL", + "historyRecordable": true, + "aliases": ["salute"], + "actionTags": ["COMMUNICATION"], + "effects": [ + { + "effectKind": "APPLY_ACTION_STATE", + "schemaVersion": 1, + "targeting": "SELF", + "replayPolicy": "EFFECT_IDEMPOTENT", + "payload": { + "conditionKey": "SALUTING", + "durationSeconds": 30, + "effectPayload": { + "modifiers": [ + { + "operation": "ADD", + "target_key": "salute_count", + "value": 1, + "scope_kind": "ACTION_FAMILY", + "scope_key": "social", + "priority": 2 + } + ] + } + } + } + ] + } + """; + + @Test + void acceptsCanonicalDefinitionAndDefinedOptionalModifierFields() { + assertThat(CommandSource.upsertPayload(VALID_DEFINITION)).isNotBlank(); + } + + @Test + void acceptsCanonicalDefinitionWhenAllOptionalModifierFieldsAreAbsent() { + String definitionWithoutOptionalModifierFields = + VALID_DEFINITION.replace( + ",\n \"scope_kind\": \"ACTION_FAMILY\",\n \"scope_key\": \"social\",\n \"priority\": 2", + ""); + + assertThat(definitionWithoutOptionalModifierFields) + .doesNotContain("scope_kind", "scope_key", "priority"); + assertThat(CommandSource.upsertPayload(definitionWithoutOptionalModifierFields)).isNotBlank(); + } + + @Test + void rejectsUnknownDefinitionFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"commandId\": \"salute\",", "\"targetSelectionPolicyKey\": \"self\","); + } + + @Test + void rejectsUnknownEffectFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"effectKind\": \"APPLY_ACTION_STATE\",", "\"targetSetKey\": \"SOURCE\","); + } + + @Test + void rejectsUnknownPayloadFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"conditionKey\": \"SALUTING\",", "\"sourceRuleId\": \"rule-1\","); + } + + @Test + void rejectsUnknownEffectPayloadFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"effectPayload\": {", "\"targetRefs\": [],"); + } + + @Test + void rejectsUnknownModifierFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"operation\": \"ADD\",", "\"targetTemplateId\": \"item-1\","); + } + + private static void assertRejected(String marker, String insertion) { + String unsupported = VALID_DEFINITION.replace(marker, marker + insertion); + assertThat(unsupported).isNotEqualTo(VALID_DEFINITION); + assertThatThrownBy(() -> CommandSource.upsertPayload(unsupported)) + .isInstanceOf(IllegalArgumentException.class); + } +} From 5570cd97cd2b71998a77d64f0b52536a37732f54 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:31:44 +1300 Subject: [PATCH 084/129] Share canonical selected source grammars and prove Automation intake storage --- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 2 +- ...eAuthorizationPostgresIntegrationTest.java | 40 +- ...nerIntakeAuthorizationReadServiceTest.java | 85 ++-- ...edOwnerIntakeAuthorizationServiceTest.java | 53 +- ...ationEmptySelectedSourceIntakeService.java | 32 +- ...tySelectedSourceIntakePostgresFixture.java | 463 ++++++++++++++++++ ...takeRepositoryPostgresIntegrationTest.java | 318 ++++++++++++ ...tedSourceIntakeServiceIntegrationTest.java | 323 ++++++++++++ .../common/gamedesign/AssetSnapshot.java | 166 +++++++ .../common/gamedesign}/AssetSource.java | 8 +- .../common/gamedesign}/BrandingSource.java | 8 +- .../gamedesign/BrandingSourceSnapshot.java | 179 +++++++ .../common/gamedesign/CommandSnapshot.java | 107 ++++ .../common/gamedesign}/CommandSource.java | 25 +- .../gamedesign}/GameplayRuleSource.java | 12 +- .../gamedesign/RealmPolicySnapshot.java | 64 +++ .../common/gamedesign}/RealmPolicySource.java | 11 +- .../SelectedOwnerIntakeSourceContent.java | 74 ++- .../SelectedOwnerEmptySourceInputsTest.java | 16 +- ...edOwnerIntakeAuthorizationBindingTest.java | 24 +- ...erIntakeAuthorizationReadEvidenceTest.java | 15 +- ...wnerWorldInventoryRecipientFieldsTest.java | 13 +- ...lectedOwnerIntakeSourceClientMtlsTest.java | 78 +-- .../SelectedOwnerIntakeSourceContentTest.java | 85 +++- ...lectedOwnerIntakeSourceProtoCodecTest.java | 53 +- ...SelectedOwnerIntakeSourceTestFixtures.java | 84 ++++ .../publication/AssetApplication.java | 1 + .../gamedesign/publication/AssetSnapshot.java | 163 ++---- .../publication/AssetSourceRepository.java | 19 +- .../BrandingSourceApplication.java | 1 + .../publication/BrandingSourceRepository.java | 20 +- .../publication/BrandingSourceSnapshot.java | 181 ++----- .../publication/CommandApplication.java | 1 + .../publication/CommandSnapshot.java | 97 +--- .../publication/CommandSourceRepository.java | 5 + .../GameDesignSourceRepository.java | 5 + .../publication/GameplayRuleSnapshot.java | 1 + .../GameplayRuleSourceRepository.java | 2 + .../publication/RealmPolicyApplication.java | 1 + .../publication/RealmPolicyGenesis.java | 1 + .../RealmPolicyPublicationRepository.java | 1 + .../RealmPolicyPublishedEvidence.java | 1 + .../publication/RealmPolicySnapshot.java | 54 +- .../RealmPolicySourceRepository.java | 1 + .../SelectedDraftAssetInventory.java | 3 + ...electedDraftAssetInventoryReadService.java | 10 +- ...edDraftTemplateWorldSourceAssociation.java | 1 + .../TemplateConfigSourceRepository.java | 1 + .../TemplateConfigSourceSnapshot.java | 1 + .../TemplateReferenceRepository.java | 1 + .../PublishedReleaseBundleRepository.java | 2 +- .../draft/IsolatedPublicationOwnerSetup.java | 2 +- ...ldSourceCommitPostgresIntegrationTest.java | 2 +- ...BrandingSourcePostgresIntegrationTest.java | 10 +- ...gnSourceCommitPostgresIntegrationTest.java | 4 +- ...teConfigSourcePostgresIntegrationTest.java | 4 +- ...ameLogicIntakePostgresIntegrationTest.java | 2 +- ...licationExportPostgresIntegrationTest.java | 6 +- ...setPublicationPostgresIntegrationTest.java | 8 +- ...xportCandidatePostgresIntegrationTest.java | 2 +- .../publication/AssetSnapshotTest.java | 18 +- .../publication/AssetSourceTest.java | 1 + .../publication/BrandingSourceTest.java | 8 +- .../publication/CommandSourceTest.java | 1 + .../RealmPolicyApplicationTest.java | 2 + .../publication/TemplateConfigSourceTest.java | 4 + ...signGameplayRuleSourceReadServiceTest.java | 1 + ...ectedOwnerIntakeSourceGrpcServiceTest.java | 13 +- .../publication/GameplayRuleSourceTest.java | 1 + ...tedDraftAssetInventoryReadServiceTest.java | 8 +- .../SelectedDraftControlPlaneDigestTest.java | 1 + ...DraftPublicationDigestReadServiceTest.java | 1 + .../SelectedOwnerIntakeSourceExportTest.java | 15 +- ...SelectedOwnerInventoryReadServiceTest.java | 86 ++-- 75 files changed, 2372 insertions(+), 746 deletions(-) create mode 100644 services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java create mode 100644 services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java create mode 100644 services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSnapshot.java rename services/{game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication => common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign}/AssetSource.java (98%) rename services/{game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication => common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign}/BrandingSource.java (98%) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSourceSnapshot.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSnapshot.java rename services/{game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication => common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign}/CommandSource.java (97%) rename services/{game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication => common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign}/GameplayRuleSource.java (96%) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySnapshot.java rename services/{game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication => common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign}/RealmPolicySource.java (95%) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a00ea99f97..1f24c7dc32 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -198,3 +198,9 @@ Entry format: - Observation: Originating XML finally showed an IPv6 `localhost` connection refusal while the test server listened only on IPv4. A failed connection and zero handler calls do not establish TLS rejection, and reporting only a boolean matcher initially concealed the transport cause. - Expected pattern: Match the client endpoint to the server's explicit loopback bind and certificate SAN, retain bounded cause-chain diagnostics, and check certificate rejection separately from absence of application calls. Never broaden a TLS matcher to accept generic connection failure. - Current status: Both test clients use the existing `127.0.0.1` bind/SAN, the strict matcher and required client certificate are unchanged, and grouped assertions retain all denial evidence. All four native acquisition mTLS cases pass locally; corrected CI execution remains required. + +- `2026-10-11`: Publication can interrupt the physical proof it was meant to obtain + - Context: PR #3105's Account database job repeatedly stopped before PostgreSQL assertion evidence was available. + - Observation: The next source publication started a same-PR Validation run fourteen seconds before the preceding Account checks were canceled. The workflow's per-PR concurrency group uses `cancel-in-progress: true`; local green checks and canceled remote unit artifacts did not establish database proof. + - Expected pattern: Batch a corrected proof checkpoint, then hold further branch publications until its required database job completes while continuing implementation locally. Attribute artifacts to their originating checkout and distinguish interruption from a database assertion failure. + - Current status: The cancellation cause is strongly supported by workflow configuration and run timing. The next corrected source checkpoint will have an uninterrupted Account proof window; physical proof remains open until the resulting artifacts establish execution. 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 8b78ce5c6e..ec202b7e28 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 @@ -22,7 +22,7 @@ Fresh Entity/Automation empty-source receipts remain concrete producer obligatio The prepared shared `SelectedOwnerEmptySourceInputs` value exact-compares the supplied finalized Account binding with the World response, selected commit and canonical tenant/version/namespace. It requires the supported complete World inbound closure and the recipient's typed TEMPLATE_CONFIG inventory declaration, preserves that declaration's original inherited revision provenance, and rejects recipient-owned template references and nonempty Entity spawn input. This is local input-integrity composition only, not authenticated producer evidence, complete database census, continuously held authority or an owner terminal receipt. Its proof remains bounded to synthetic immutable inputs and must not be used to replace the owner obligations above. -Automation's prepared V5 storage cut covers its three actual authored-source families: script definitions, event bindings and script-patch base bindings; derived schedules are not a fourth authored family. It retains immutable canonical tenant/version associations, locally allocated private numeric keys and exact selected-source receipt bytes. The repository serializes allocation before source census and rejects unqualified legacy rows rather than treating absent mappings as empty. Source row and truncate guards reject writes against reserved empty scopes and require READ COMMITTED so a stale transaction snapshot cannot bypass a committed reservation. The standalone service remains unregistered and denies every new positive intake while COMMAND, REALM_POLICY, ASSET and BRANDING lack shared typed reference validation; two HELD observations do not prove continuous Account protection through commit or terminal settlement. PostgreSQL migration and writer-race definitions are not authenticated positive producer proof, and physical execution remains required. Game Design's existing command grammar now rejects unknown fields at each supported definition/effect/payload/modifier level while preserving its defined optional modifier fields; this does not add a new effect grammar or independently prove the other selected-source families closed. +Automation's prepared V5 storage cut covers its three actual authored-source families: script definitions, event bindings and script-patch base bindings; derived schedules are not a fourth authored family. It retains immutable canonical tenant/version associations, locally allocated private numeric keys and exact selected-source receipt bytes. The repository serializes allocation before source census and rejects unqualified legacy rows rather than treating absent mappings as empty. Source row and truncate guards reject writes against reserved empty scopes and require READ COMMITTED so a stale transaction snapshot cannot bypass a committed reservation. The existing Game Design source grammars and four additional typed snapshot values now live in Common, and the selected-source recipient validates all six families and raw selected Game Design revisions without a parallel schema. The standalone Automation service can compose typed empty inputs after authenticated Account/World reads but remains unregistered; two HELD observations are not continuous protection proof, and the finalized Account source reservation must remain pending under its existing writer guards until exact owner terminal settlement is proved. Actual repository persistence/readback and service ordering have focused test definitions with explicitly synthetic upstream inputs; they do not establish authenticated positive producer or physical PostgreSQL proof. Game Design's command grammar rejects unknown fields at each supported definition/effect/payload/modifier level while preserving its defined optional modifier fields; extraction does not add an effect grammar, prove foreign-owner census or authorize runtime activation. Exact source `1f9f673095e4ac8f5bb6b9c0a969469854de4d86` [Validation run 38035808533](https://github.com/benhook1013/FireMUD/actions/runs/38035808533) failed the required gate: Account executed 1,304 unit cases with one missing-client-certificate matcher assertion failure. Retained XML and logs omit the transport exception/cause, so its cause and subsequent no-handler assertions are unproved for that run. The local corrected batch preserves the strict TLS matcher and required client certificate, adds failure diagnostics, and executes all four native cases successfully without weakening denial. Account's integration task never ran in that CI run; no PostgreSQL durability or acquisition proof follows. The tested merge `2be00c0c20e4feb76097547b9e9992c53e3ae6e3` has tree `96a7913e52c5ce281c81093e1b225fb3e9344ee2` and ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, not the separately recorded integration parent. The approved failure-only diagnostic now maps bounded captured WAL relation locators through the same run-owned database's current catalog after failure; missing, reused, changed or cross-database locators remain inconclusive. It has no executed PostgreSQL result and establishes neither historical relation identity, backend origin nor timing causation. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java index 690bd67e6f..b32c7fdc52 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -18,6 +18,11 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; @@ -510,7 +515,8 @@ private static void settleOriginal( private static SelectedOwnerIntakeSourceContent content( SelectedOwnerIntakeSourceReadScope scope, String marker) { var selected = scope.selected(); - UUID genesis = UUID.randomUUID(); + UUID genesis = UUID.nameUUIDFromBytes(marker.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + String markerEpoch = Integer.toUnsignedString(marker.hashCode()); var gameplay = new GameplayRuleSelectedSource( GameplayRuleManifest.canonical( @@ -527,16 +533,20 @@ private static SelectedOwnerIntakeSourceContent content( var snapshots = Map.of( "COMMAND", - opaqueSnapshot("game-design-command-source-snapshot/v1", "COMMAND", selected, marker), + new CommandSnapshot( + selected, + "0", + null, + DraftAuthorizationFenceBinding.digest( + marker.getBytes(java.nio.charset.StandardCharsets.UTF_8)), + List.of()) + .canonicalBytes(), "REALM_POLICY", - opaqueSnapshot( - "game-design-realm-policy-snapshot/v1", "REALM_POLICY", selected, marker), + new RealmPolicySnapshot(selected, markerEpoch, List.of()).canonicalBytes(), "ASSET", - opaqueSnapshot( - "game-design-ordinary-asset-source-snapshot/v1", "ASSET", selected, marker), + new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(), "BRANDING", - opaqueSnapshot( - "game-design-branding-asset-source-snapshot/v1", "BRANDING", selected, marker)); + new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes()); var out = new ByteArrayOutputStream(); DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); @@ -559,18 +569,6 @@ private static SelectedOwnerIntakeSourceContent content( bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); } - private static byte[] opaqueSnapshot( - String schema, String family, DraftCommitBinding selected, String marker) { - return GameplayRuleManifest.canonical( - Map.of( - "schema", schema, - "bindingJson", selected.canonicalJson(), - "bindingDigest", selected.digest(), - "family", family, - "marker", marker)) - .getBytes(java.nio.charset.StandardCharsets.UTF_8); - } - private static DraftCommitBinding selected(UUID tenant) { var target = new DraftCommitBinding.TargetProof( @@ -585,7 +583,7 @@ private static DraftCommitBinding selected(UUID tenant) { "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, - GameplayRuleManifest.canonical(Map.of("schema", "test/v1")))), + CommandSource.deletePayload("synthetic-fixture-command"))), List.of( new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java index dc8548f39b..893d4da95b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java @@ -25,6 +25,11 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; @@ -176,43 +181,47 @@ private static SelectedOwnerIntakeSourceContent content( } private static byte[] snapshot(String family, DraftCommitBinding selected) { - if ("GAMEPLAY_RULE".equals(family)) { - return new GameplayRuleSelectedSource( - GameplayRuleManifest.canonical( - Map.of( - "schema", - "game-design-gameplay-rule-source-snapshot/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "sourceEpoch", - "0", - "inheritedCommitId", - "", - "genesisReceiptId", - "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", - "manifestJson", - GameplayRuleManifest.explicitEmpty().canonicalJson(), - "entries", - List.of()))) - .canonicalBytes(); - } - if ("TEMPLATE_CONFIG".equals(family)) - return new TemplateConfigSourceSnapshot( - selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) - .canonicalBytes(); - return GameplayRuleManifest.canonical( - Map.of( - "schema", - "synthetic-test-only/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "family", - family)) - .getBytes(StandardCharsets.UTF_8); + UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + return switch (family) { + case "COMMAND" -> + new CommandSnapshot( + selected, + "0", + null, + DraftAuthorizationFenceBinding.digest( + "synthetic-read-fixture".getBytes(StandardCharsets.UTF_8)), + List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + genesis.toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "TEMPLATE_CONFIG" -> + new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); + }; } private static List sources(UUID actor, UUID tenant) { @@ -240,7 +249,7 @@ private static DraftCommitBinding selected(UUID tenant) { "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.GAME_DESIGN_CONTROL_PLANE, - "{}")), + CommandSource.deletePayload("synthetic-fixture-command"))), List.of( new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java index 8a4e17c840..b1f8d51584 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java @@ -37,6 +37,11 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceClient; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; @@ -61,7 +66,6 @@ class AccountSelectedOwnerIntakeAuthorizationServiceTest { private static final UUID VERSION = UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"); private static final UUID OPERATION = UUID.fromString("55555555-5555-4555-8555-555555555555"); private static final UUID FENCE = UUID.fromString("66666666-6666-4666-8666-666666666666"); - private static final UUID GENESIS = UUID.fromString("33333333-3333-4333-8333-333333333333"); private final AccountControlUiActorService actors = mock(AccountControlUiActorService.class); private final DraftAuthorizationFenceRepository fences = @@ -563,7 +567,7 @@ private static DraftCommitBinding selected() { "0", UUID.fromString("33333333-3333-4333-8333-333333333333"), Owner.GAME_DESIGN_CONTROL_PLANE, - "{}")), + CommandSource.deletePayload("synthetic-fixture-command"))), List.of( new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, @@ -583,6 +587,8 @@ private static SelectedOwnerIntakeSourceReadScope scope( private static SelectedOwnerIntakeSourceContent content( SelectedOwnerIntakeSourceReadScope scope, String marker) { var selected = scope.selected(); + UUID markerGenesis = UUID.nameUUIDFromBytes(marker.getBytes(StandardCharsets.UTF_8)); + String markerEpoch = Integer.toUnsignedString(marker.hashCode()); var gameplay = new GameplayRuleSelectedSource( GameplayRuleManifest.canonical( @@ -592,16 +598,27 @@ private static SelectedOwnerIntakeSourceContent content( "bindingDigest", selected.digest(), "sourceEpoch", "0", "inheritedCommitId", "", - "genesisReceiptId", GENESIS.toString(), + "genesisReceiptId", markerGenesis.toString(), "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), "entries", List.of()))); - var template = new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()); - Map opaque = + var template = new TemplateConfigSourceSnapshot(selected, "0", null, markerGenesis, List.of()); + Map snapshots = Map.of( - "COMMAND", opaqueSnapshot("COMMAND", selected, marker), - "REALM_POLICY", opaqueSnapshot("REALM_POLICY", selected, marker), - "ASSET", opaqueSnapshot("ASSET", selected, marker), - "BRANDING", opaqueSnapshot("BRANDING", selected, marker)); + "COMMAND", + new CommandSnapshot( + selected, + "0", + null, + DraftAuthorizationFenceBinding.digest(marker.getBytes(StandardCharsets.UTF_8)), + List.of()) + .canonicalBytes(), + "REALM_POLICY", + new RealmPolicySnapshot(selected, markerEpoch, List.of()).canonicalBytes(), + "ASSET", + new AssetSnapshot(selected, "0", null, markerGenesis, List.of()).canonicalBytes(), + "BRANDING", + new BrandingSourceSnapshot(selected, "0", null, markerGenesis, List.of()) + .canonicalBytes()); var out = new ByteArrayOutputStream(); DraftAuthorizationFenceBinding.frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); DraftAuthorizationFenceBinding.frame(out, scope.canonicalBytes()); @@ -613,7 +630,7 @@ private static SelectedOwnerIntakeSourceContent content( switch (family) { case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); case "TEMPLATE_CONFIG" -> template.canonicalBytes(); - default -> opaque.get(family); + default -> snapshots.get(family); }; DraftAuthorizationFenceBinding.frame(out, family); DraftAuthorizationFenceBinding.frame(out, snapshot); @@ -624,22 +641,6 @@ private static SelectedOwnerIntakeSourceContent content( bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); } - private static byte[] opaqueSnapshot(String family, DraftCommitBinding selected, String marker) { - return GameplayRuleManifest.canonical( - Map.of( - "schema", - "synthetic-test-only/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "family", - family, - "marker", - marker)) - .getBytes(StandardCharsets.UTF_8); - } - private static String tokenHash(String value) { return AccountControlUiIssuanceRepository.hash(value.getBytes(StandardCharsets.US_ASCII)); } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java index c1314c5ed4..d6ec281e80 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.automationscripting.sourceintake; -import java.util.List; import java.util.Objects; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; @@ -21,9 +20,10 @@ *

Account's HELD reads are point-in-time samples. They do not extend through Automation's local * commit and do not settle the original Account source participation. * - *

The current shared six-family selected-source envelope leaves COMMAND, REALM_POLICY, ASSET, - * and BRANDING opaque to Automation. This service therefore fails closed before local retention; - * typed validation of those family references is still required for a successful fresh receipt. + *

The shared selected-source value checks exact canonical bytes and typed snapshots for all six + * existing Game Design source families. Authenticated Account and World clients establish the + * remote read identities and HELD/inventory results; typed integrity alone does not authenticate + * either producer or establish continuous source-writer protection. */ public final class AutomationEmptySelectedSourceIntakeService { private final AutomationEmptySelectedSourceIntakeRepository repository; @@ -43,9 +43,8 @@ public AutomationEmptySelectedSourceIntakeService( /** * Returns an exact prior receipt for a lost-response retry, or prepares a fresh retention - * attempt. Fresh acceptance currently fails closed because four selected source families remain - * opaque to Automation. This operation does not create scripts, bindings, runtime markers, or - * activation state. + * attempt. This operation does not create scripts, bindings, runtime markers, or activation + * state. */ public AutomationEmptySelectedSourceIntakeReceipt retain( String targetNamespace, @@ -90,11 +89,11 @@ public AutomationEmptySelectedSourceIntakeReceipt retain( // the value itself—supply producer identity and HELD authorization. SelectedOwnerEmptySourceInputs inputs = new SelectedOwnerEmptySourceInputs(originalBinding, worldEvidence); - requireSupportedSelectedSourceClosure(inputs); // Re-sample HELD after the remote World read to reduce the gap before local commit. This is - // still not continuous protection; Account's source participation remains pending for a - // future exact terminal settlement protocol. + // only a point-in-time observation: finalized pending Account source participation remains + // under its source-writer exclusion guards. This preparation neither extends nor settles or + // releases them; exact Automation terminal settlement is not implemented. SelectedOwnerIntakeAuthorizationReadEvidence.Request finalAuthorizationReadRequest = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( targetNamespace, originalBinding); @@ -110,19 +109,6 @@ public AutomationEmptySelectedSourceIntakeReceipt retain( return receipt; } - private static void requireSupportedSelectedSourceClosure(SelectedOwnerEmptySourceInputs inputs) { - List opaqueFamilies = List.of("COMMAND", "REALM_POLICY", "ASSET", "BRANDING"); - for (String family : opaqueFamilies) { - // The current integrity envelope retains these exact bytes but does not expose a typed - // reference validator. Nonempty bytes or a declaration saying [] cannot prove that an - // opaque selected source contains no inbound script or hook references. - if (inputs.sourceContent().snapshotBytes(family).length > 0) { - throw new IllegalArgumentException( - "Automation selected-source closure is unsupported for opaque " + family + " content"); - } - } - } - private static void requireAuthenticatedGameDesignCaller(String targetNamespace) { var peer = GrpcPeerIdentity.current(); if (peer == null) { diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java new file mode 100644 index 0000000000..e193216ed5 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java @@ -0,0 +1,463 @@ +package net.firedevops.firemud.automationscripting.repository; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; + +/** + * Test-only synthetic inputs built through the same typed Common decoders as the shared fixture. + * They are not authenticated Account or World producer evidence or physical owner proof. + */ +final class AutomationEmptySelectedSourceIntakePostgresFixture { + static final String NAMESPACE = "test"; + static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + + private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666"); + private static final UUID INTAKE_REQUEST = id("77777777-7777-4777-8777-777777777777"); + private static final UUID GENESIS_RECEIPT = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + private static final String TEMPLATE_CONFIG = + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + VERSION + + "\",\"world\":{\"regions\":[],\"rooms\":[]}," + + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]}," + + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}}," + + "\"supportedSettings\":[]}"; + + private AutomationEmptySelectedSourceIntakePostgresFixture() {} + + static Fixture create(String sourceEpoch) { + DraftCommitBinding selected = selected(); + var scope = + new net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope( + Owner.AUTOMATION_SCRIPTING, + NAMESPACE, + OPERATION, + FENCE, + INTAKE_REQUEST, + ACTOR, + selected); + TemplateConfigSourceSnapshot templateSnapshot = templateSnapshot(selected, sourceEpoch); + SelectedOwnerIntakeAuthorizationBinding authorization = + new SelectedOwnerIntakeAuthorizationBinding( + sourceContent(scope, templateSnapshot), accountSources()); + WorldSelectedDraftPublicationFreezeEvidence freeze = freezeEvidence(selected); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freeze, publicInventory(freeze)); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, authorization, freeze); + var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory); + return new Fixture( + authorization, + freeze, + worldEvidence, + new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)); + } + + static Fixture withFreshWorldReadCorrelation(Fixture original) { + var request = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, original.authorization(), original.freezeEvidence()); + var evidence = + new SelectedOwnerWorldInventoryReadEvidence(request, original.worldEvidence().inventory()); + return new Fixture( + original.authorization(), + original.freezeEvidence(), + evidence, + new SelectedOwnerEmptySourceInputs(original.authorization(), evidence)); + } + + private static TemplateConfigSourceSnapshot templateSnapshot( + DraftCommitBinding selected, String sourceEpoch) { + var declaration = + AutomationAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"); + String declarationPayload = + TemplateConfigSourceValues.ownerInventoryPayload(Owner.AUTOMATION_SCRIPTING, declaration); + DraftCommitBinding authored = authoredBinding(declarationPayload); + TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration = + TemplateConfigSourceValues.mutations(authored).stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .findFirst() + .orElseThrow(); + return new TemplateConfigSourceSnapshot( + selected, + sourceEpoch, + authored.commitId(), + GENESIS_RECEIPT, + List.of(), + List.of(ownerDeclaration)); + } + + private static DraftCommitBinding authoredBinding(String payload) { + return DraftCommitBinding.create( + target(), + id("51515151-5151-4151-8151-515151515151"), + id("52525252-5252-4252-8252-525252525252"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", + id("53535353-5353-4353-8353-535353535353"), + Owner.GAME_DESIGN_CONTROL_PLANE, + payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + VERSION.toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope, + TemplateConfigSourceSnapshot templateSnapshot) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + "TEMPLATE_CONFIG".equals(family) + ? templateSnapshot.canonicalBytes() + : sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + // These values exercise exact stored-byte decoding only; they are synthetic, not owner proof. + return switch (family) { + case "COMMAND" -> + new CommandSnapshot(selected, "0", null, "sha256:" + "0".repeat(64), List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> + new AssetSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + GENESIS_RECEIPT.toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported source family fixture: " + family); + }; + } + + private static List accountSources() { + return List.of( + source(SourceKind.TENANT, TENANT.toString(), "tenant"), + source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership")); + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected() { + return DraftCommitBinding.create( + target(), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + } + + private static TargetProof target() { + return new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + DraftCommitBinding selected) { + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + TENANT, + VERSION, + "publication-request", + "9", + "synthetic selected-owner intake fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), + List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication"))); + var request = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + TENANT, + VERSION, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + request, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 1), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + emptyInboundClosure()); + var ownerScope = + new PublicOwnerScope( + request.targetNamespace(), + TENANT, + VERSION, + id("14141414-1414-4414-8414-141414141414"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("17171717-1717-4717-8717-171717171717"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + ownerScope, + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static InboundSourceClosureDeclaration emptyInboundClosure() { + return new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + record Fixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence worldEvidence, + SelectedOwnerEmptySourceInputs inputs) {} +} diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..3a565487bf --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java @@ -0,0 +1,318 @@ +package net.firedevops.firemud.automationscripting.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Real PostgreSQL proof of Automation's bounded local repository persistence and census path. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DSLContext dsl; + private AutomationEmptySelectedSourceIntakeRepository repository; + + @BeforeEach + void migrateFreshIsolatedSchema() { + schema = "automation_empty_source_repo_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target("3.2") + .load() + .migrate(); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + repository = new AutomationEmptySelectedSourceIntakeRepository(dsl); + } + + @AfterEach + void dropIsolatedSchema() { + if (schema != null) { + String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE"); + schema = null; + } + } + + @Test + void retainsCanonicalEmptyCensusAndExactReadbackAcrossCorrelationIndependentRetry() { + AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture = + AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + var inputs = fixture.inputs(); + String requestDigest = requestDigest(fixture); + + // This validates typed synthetic Common inputs; it does not authenticate either producer. + assertThat(inputs.authorizationBinding().targetNamespace()) + .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE); + assertThat(inputs.authorizationBinding().tenantId()) + .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.TENANT); + assertThat(inputs.authorizationBinding().versionId()) + .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.VERSION); + assertThat(inputs.ownerSourceInventoryDeclaration().owner()) + .isEqualTo( + net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + assertThat( + inputs + .worldInventoryReadEvidence() + .inventory() + .publicEvidence() + .sourceModel() + .inboundSourceClosure() + .familyCounts()) + .allSatisfy(count -> assertThat(count.count()).isZero()); + + AutomationEmptySelectedSourceIntakeReceipt first = + repository.retainFresh(inputs, requestDigest); + + assertThat(first.targetNamespace()).isEqualTo(inputs.authorizationBinding().targetNamespace()); + assertThat(first.canonicalTenantId()).isEqualTo(inputs.authorizationBinding().tenantId()); + assertThat(first.canonicalVersionId()).isEqualTo(inputs.authorizationBinding().versionId()); + assertThat(first.selectedCommitId()) + .isEqualTo(inputs.authorizationBinding().selected().commitId()); + assertThat(first.sourceRevisionId()) + .isEqualTo(inputs.ownerSourceInventoryDeclaration().revisionId()); + assertThat(first.sourceRevisionOrder()) + .isEqualTo(inputs.ownerSourceInventoryDeclaration().revisionOrder()); + assertThat(first.localTenantKey()).isPositive(); + assertThat(first.localVersionKey()).isPositive().isNotEqualTo(first.localTenantKey()); + assertThat(first.outcome()).isEqualTo("COMMITTED_EMPTY"); + assertThat(first.scriptsRowCount()).isZero(); + assertThat(first.eventBindingsRowCount()).isZero(); + assertThat(first.patchBaseBindingsRowCount()).isZero(); + assertThat(first.unqualifiedScriptsRowCount()).isZero(); + assertThat(first.unqualifiedEventBindingsRowCount()).isZero(); + assertThat(first.unqualifiedPatchBaseBindingsRowCount()).isZero(); + assertThat(first.emptyAssociatedScriptsRowCount()).isZero(); + assertThat(first.emptyAssociatedEventBindingsRowCount()).isZero(); + assertThat(first.emptyAssociatedPatchBaseBindingsRowCount()).isZero(); + assertThat(first.selectedScopeScriptsRowCount()).isZero(); + assertThat(first.selectedScopeEventBindingsRowCount()).isZero(); + assertThat(first.selectedScopePatchBaseBindingsRowCount()).isZero(); + assertThat(first.authorizationBindingBytes()) + .containsExactly(inputs.authorizationBinding().canonicalBytes()); + assertThat(first.worldInventoryBytes()) + .containsExactly(inputs.worldInventoryReadEvidence().inventory().canonicalBytes()); + assertThat(first.worldReadRequestId()) + .isEqualTo(inputs.worldInventoryReadEvidence().request().readRequestId()); + + assertThat(rowCount("SELECT COUNT(*) FROM scripts")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM script_event_bindings")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM script_patch_base_bindings")).isZero(); + assertThat( + rowCount( + "SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation " + + "WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE'")) + .isEqualTo(2L); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association")) + .isEqualTo(1L); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")) + .isEqualTo(1L); + + Record storedReceipt = + dsl.fetchOne( + "SELECT receipt_bytes, receipt_digest, request_digest FROM " + + "automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + first.targetNamespace(), + first.intakeRequestId()); + assertThat(storedReceipt).isNotNull(); + assertThat(storedReceipt.get(0, byte[].class)).containsExactly(first.canonicalBytes()); + assertThat(storedReceipt.get(1, String.class)).isEqualTo(first.receiptDigest()); + assertThat(storedReceipt.get(2, String.class)).isEqualTo(first.requestDigest()); + + Record storedAssociation = + dsl.fetchOne( + "SELECT canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "source_revision_id, source_revision_order, local_tenant_key, local_version_key, " + + "request_digest, authorization_binding_digest, receipt_digest " + + "FROM automation_empty_selected_source_association " + + "WHERE target_namespace = ? AND intake_request_id = ?", + first.targetNamespace(), + first.intakeRequestId()); + assertThat(storedAssociation).isNotNull(); + assertThat(storedAssociation.get(0, UUID.class)).isEqualTo(first.canonicalTenantId()); + assertThat(storedAssociation.get(1, UUID.class)).isEqualTo(first.canonicalVersionId()); + assertThat(storedAssociation.get(2, UUID.class)).isEqualTo(first.selectedCommitId()); + assertThat(storedAssociation.get(3, UUID.class)).isEqualTo(first.sourceRevisionId()); + assertThat(storedAssociation.get(4, String.class)).isEqualTo(first.sourceRevisionOrder()); + assertThat(storedAssociation.get(5, Long.class)).isEqualTo(first.localTenantKey()); + assertThat(storedAssociation.get(6, Long.class)).isEqualTo(first.localVersionKey()); + assertThat(storedAssociation.get(7, String.class)).isEqualTo(first.requestDigest()); + assertThat(storedAssociation.get(8, String.class)) + .isEqualTo(first.authorizationBindingDigest()); + assertThat(storedAssociation.get(9, String.class)).isEqualTo(first.receiptDigest()); + + var readBack = repository.read(first.targetNamespace(), first.intakeRequestId()).orElseThrow(); + assertThat(readBack.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(readBack.receiptDigest()).isEqualTo(first.receiptDigest()); + + var retry = + AutomationEmptySelectedSourceIntakePostgresFixture.withFreshWorldReadCorrelation(fixture); + assertThat(retry.worldEvidence().request().readRequestId()) + .isNotEqualTo(fixture.worldEvidence().request().readRequestId()); + String retryDigest = requestDigest(retry); + assertThat(retryDigest).isEqualTo(requestDigest); + var retryReceipt = repository.retainFresh(retry.inputs(), retryDigest); + assertThat(retryReceipt.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(retryReceipt.worldReadRequestId()).isEqualTo(first.worldReadRequestId()); + + var altered = AutomationEmptySelectedSourceIntakePostgresFixture.create("2"); + assertThat(altered.authorization().intakeRequestId()) + .isEqualTo(fixture.authorization().intakeRequestId()); + assertThat(altered.authorization().canonicalBytes()) + .isNotEqualTo(fixture.authorization().canonicalBytes()); + String alteredDigest = requestDigest(altered); + assertThat(alteredDigest).isNotEqualTo(requestDigest); + assertThatThrownBy(() -> repository.retainFresh(altered.inputs(), alteredDigest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("already records different selected evidence"); + + assertThat( + rowCount( + "SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation " + + "WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE'")) + .isEqualTo(2L); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association")) + .isEqualTo(1L); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")) + .isEqualTo(1L); + Record unchangedReceipt = + dsl.fetchOne( + "SELECT receipt_bytes FROM automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + first.targetNamespace(), + first.intakeRequestId()); + assertThat(unchangedReceipt).isNotNull(); + assertThat(unchangedReceipt.get(0, byte[].class)).containsExactly(first.canonicalBytes()); + } + + @Test + void deniesUnqualifiedRowsInEachAuthoredFamilyWithoutCreatingOwnerRecords() { + var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + String requestDigest = requestDigest(fixture); + + dsl.execute( + "INSERT INTO scripts (tenant_id, name, version, definition) VALUES (?, ?, ?, ?)", + 501L, + "unqualified-script", + "legacy-patch", + "{}"); + assertUnqualifiedDenial(fixture, requestDigest); + dsl.execute("DELETE FROM scripts WHERE name = ?", "unqualified-script"); + + dsl.execute( + "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, " + + "event_schema_version, script_id, target_scope_type, target_scope_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + 502L, + "unqualified-event-patch", + "unqualified-event", + "v1", + "unqualified-script", + "TENANT", + "test"); + assertUnqualifiedDenial(fixture, requestDigest); + dsl.execute( + "DELETE FROM script_event_bindings WHERE script_patch_version = ?", + "unqualified-event-patch"); + + dsl.execute( + "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) " + + "VALUES (?, ?, ?)", + "unqualified-tenant-key", + "unqualified-patch", + 503L); + assertUnqualifiedDenial(fixture, requestDigest); + dsl.execute( + "DELETE FROM script_patch_base_bindings WHERE script_patch_version = ?", + "unqualified-patch"); + + assertThat(rowCount("SELECT COUNT(*) FROM scripts")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM script_event_bindings")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM script_patch_base_bindings")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation")) + .isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association")) + .isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")).isZero(); + } + + private void assertUnqualifiedDenial( + AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture, String requestDigest) { + assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest)) + .isInstanceOf( + AutomationEmptySelectedSourceIntakeRepository.UnqualifiedSourceRowsException.class); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation")) + .isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association")) + .isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")).isZero(); + } + + private static String requestDigest( + AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture) { + return AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + fixture.authorization(), + fixture.freezeEvidence()); + } + + private long rowCount(String sql, Object... parameters) { + Record record = dsl.fetchOne(sql, parameters); + assertThat(record).isNotNull(); + Long value = record.get(0, Long.class); + assertThat(value).isNotNull(); + return value; + } + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + String baseUrl = postgres.getJdbcUrl(); + dataSource.setUrl( + schemaName == null + ? baseUrl + : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } +} diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java new file mode 100644 index 0000000000..c2b340aa3a --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java @@ -0,0 +1,323 @@ +package net.firedevops.firemud.automationscripting.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +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.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Mocked service ordering proof using exact typed, synthetic Common owner-input fixtures. + * Collaborator echoes here are not authenticated producer or physical owner proof. + */ +class AutomationEmptySelectedSourceIntakeServiceIntegrationTest { + private static final String NAMESPACE = + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE; + + @BeforeEach + void clearPriorContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @AfterEach + void clearContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void freshTypedInputsReachRepositoryOnlyAfterTwoAccountEchoesAndWorldEcho() { + var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + var inputs = fixture.inputs(); + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var accountClient = mock(SelectedOwnerIntakeAuthorizationReadClient.class); + var worldClient = mock(SelectedOwnerWorldInventoryReadClient.class); + var receipt = mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(repository.read(NAMESPACE, inputs.authorizationBinding().intakeRequestId())) + .thenReturn(Optional.empty()); + when(repository.retainFresh(any(SelectedOwnerEmptySourceInputs.class), anyString())) + .thenReturn(receipt); + when(accountClient.read(any())) + .thenAnswer( + invocation -> + new SelectedOwnerIntakeAuthorizationReadEvidence(invocation.getArgument(0))); + when(worldClient.read(any())) + .thenAnswer( + invocation -> + new SelectedOwnerWorldInventoryReadEvidence( + invocation.getArgument(0), fixture.worldEvidence().inventory())); + + var service = + new AutomationEmptySelectedSourceIntakeService(repository, accountClient, worldClient); + String requestDigest = + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, fixture.authorization(), fixture.freezeEvidence()); + + AutomationEmptySelectedSourceIntakeReceipt returned = + withGameDesignPeer( + () -> service.retain(NAMESPACE, fixture.authorization(), fixture.freezeEvidence())); + + assertThat(returned).isSameAs(receipt); + ArgumentCaptor accountRequests = + ArgumentCaptor.forClass(SelectedOwnerIntakeAuthorizationReadEvidence.Request.class); + ArgumentCaptor worldRequests = + ArgumentCaptor.forClass(SelectedOwnerWorldInventoryReadEvidence.Request.class); + ArgumentCaptor retainedInputs = + ArgumentCaptor.forClass(SelectedOwnerEmptySourceInputs.class); + InOrder order = inOrder(repository, accountClient, worldClient, receipt); + order.verify(repository).read(NAMESPACE, inputs.authorizationBinding().intakeRequestId()); + order.verify(accountClient).read(accountRequests.capture()); + order.verify(worldClient).read(worldRequests.capture()); + order.verify(accountClient).read(accountRequests.capture()); + order.verify(repository).retainFresh(retainedInputs.capture(), eq(requestDigest)); + order + .verify(receipt) + .requireSameRequest(NAMESPACE, fixture.authorization(), fixture.freezeEvidence()); + + assertThat(accountRequests.getAllValues()).hasSize(2); + assertThat(accountRequests.getAllValues().get(0).binding()).isEqualTo(fixture.authorization()); + assertThat(accountRequests.getAllValues().get(1).binding()).isEqualTo(fixture.authorization()); + assertThat(accountRequests.getAllValues().get(0).readRequestId()) + .isNotEqualTo(accountRequests.getAllValues().get(1).readRequestId()); + assertThat(worldRequests.getValue().authorizationBinding()).isEqualTo(fixture.authorization()); + assertThat(worldRequests.getValue().freezeEvidence()).isEqualTo(fixture.freezeEvidence()); + + SelectedOwnerEmptySourceInputs actualInputs = retainedInputs.getValue(); + assertThat(actualInputs.authorizationBinding().canonicalBytes()) + .containsExactly(fixture.authorization().canonicalBytes()); + assertThat(actualInputs.authorizationBinding().digest()) + .isEqualTo(fixture.authorization().digest()); + assertThat(actualInputs.sourceContent().canonicalBytes()) + .containsExactly(fixture.authorization().content().canonicalBytes()); + assertThat(actualInputs.sourceContent().digest()) + .isEqualTo(fixture.authorization().content().digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + assertThat(actualInputs.sourceContent().snapshotBytes(family)) + .containsExactly(fixture.authorization().content().snapshotBytes(family)); + } + var actualDeclaration = actualInputs.ownerSourceInventoryDeclaration(); + var expectedDeclaration = inputs.ownerSourceInventoryDeclaration(); + assertThat(actualDeclaration.owner()).isEqualTo(expectedDeclaration.owner()); + assertThat(actualDeclaration.inventory().canonicalJson()) + .isEqualTo(expectedDeclaration.inventory().canonicalJson()); + assertThat(actualDeclaration.sourceBinding().canonicalBytes()) + .containsExactly(expectedDeclaration.sourceBinding().canonicalBytes()); + assertThat(actualDeclaration.revisionOrder()).isEqualTo(expectedDeclaration.revisionOrder()); + assertThat(actualDeclaration.revisionId()).isEqualTo(expectedDeclaration.revisionId()); + assertThat(actualInputs.worldInventoryReadEvidence().request()) + .isEqualTo(worldRequests.getValue()); + assertThat(actualInputs.worldInventoryReadEvidence().inventory().canonicalBytes()) + .containsExactly(fixture.worldEvidence().inventory().canonicalBytes()); + assertThat(actualInputs.worldInventoryReadEvidence().inventory().digest()) + .isEqualTo(fixture.worldEvidence().inventory().digest()); + } + + @Test + void unavailableOrMismatchedAccountAndWorldEchoesNeverReachFreshRetention() { + var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + for (ReadFailure failure : ReadFailure.values()) { + var inputs = fixture.inputs(); + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var accountClient = mock(SelectedOwnerIntakeAuthorizationReadClient.class); + var worldClient = mock(SelectedOwnerWorldInventoryReadClient.class); + when(repository.read(NAMESPACE, inputs.authorizationBinding().intakeRequestId())) + .thenReturn(Optional.empty()); + + AtomicInteger accountReads = new AtomicInteger(); + when(accountClient.read(any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, SelectedOwnerIntakeAuthorizationReadEvidence.Request.class); + int call = accountReads.incrementAndGet(); + if (failure == ReadFailure.FIRST_ACCOUNT_UNAVAILABLE && call == 1 + || failure == ReadFailure.FINAL_ACCOUNT_UNAVAILABLE && call == 2) { + return null; + } + if (failure == ReadFailure.FIRST_ACCOUNT_MISMATCH && call == 1 + || failure == ReadFailure.FINAL_ACCOUNT_MISMATCH && call == 2) { + request = mismatched(request); + } + return new SelectedOwnerIntakeAuthorizationReadEvidence(request); + }); + + AtomicInteger worldReads = new AtomicInteger(); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, SelectedOwnerWorldInventoryReadEvidence.Request.class); + worldReads.incrementAndGet(); + if (failure == ReadFailure.WORLD_UNAVAILABLE) return null; + if (failure == ReadFailure.WORLD_MISMATCH) request = mismatched(request); + return new SelectedOwnerWorldInventoryReadEvidence( + request, fixture.worldEvidence().inventory()); + }); + + var service = + new AutomationEmptySelectedSourceIntakeService(repository, accountClient, worldClient); + assertThatThrownBy( + () -> + withGameDesignPeer( + () -> + service.retain( + NAMESPACE, fixture.authorization(), fixture.freezeEvidence()))) + .as(failure.name()) + .isInstanceOf(IllegalStateException.class); + + verify(repository).read(NAMESPACE, inputs.authorizationBinding().intakeRequestId()); + verify(repository, never()) + .retainFresh(any(SelectedOwnerEmptySourceInputs.class), anyString()); + int expectedAccountReads = + failure == ReadFailure.FINAL_ACCOUNT_UNAVAILABLE + || failure == ReadFailure.FINAL_ACCOUNT_MISMATCH + ? 2 + : 1; + int expectedWorldReads = + failure == ReadFailure.FIRST_ACCOUNT_UNAVAILABLE + || failure == ReadFailure.FIRST_ACCOUNT_MISMATCH + ? 0 + : 1; + assertThat(accountReads.get()).isEqualTo(expectedAccountReads); + assertThat(worldReads.get()).isEqualTo(expectedWorldReads); + } + } + + @Test + void exactStoredRetryReturnsBeforeRemoteOwnerReads() { + var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var accountClient = mock(SelectedOwnerIntakeAuthorizationReadClient.class); + var worldClient = mock(SelectedOwnerWorldInventoryReadClient.class); + var retained = mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(repository.read(NAMESPACE, fixture.authorization().intakeRequestId())) + .thenReturn(Optional.of(retained)); + var service = + new AutomationEmptySelectedSourceIntakeService(repository, accountClient, worldClient); + + var returned = + withGameDesignPeer( + () -> service.retain(NAMESPACE, fixture.authorization(), fixture.freezeEvidence())); + + assertThat(returned).isSameAs(retained); + verify(repository).read(NAMESPACE, fixture.authorization().intakeRequestId()); + verify(retained) + .requireSameRequest(NAMESPACE, fixture.authorization(), fixture.freezeEvidence()); + verify(repository, never()).retainFresh(any(SelectedOwnerEmptySourceInputs.class), anyString()); + verifyNoInteractions(accountClient, worldClient); + } + + private static SelectedOwnerIntakeAuthorizationReadEvidence.Request mismatched( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request) { + UUID differentId = + differentReadId( + request.readRequestId(), + request.binding().operationId(), + request.binding().fenceId(), + request.binding().intakeRequestId()); + return new SelectedOwnerIntakeAuthorizationReadEvidence.Request( + request.schemaVersion(), request.targetNamespace(), differentId, request.binding()); + } + + private static SelectedOwnerWorldInventoryReadEvidence.Request mismatched( + SelectedOwnerWorldInventoryReadEvidence.Request request) { + var binding = request.authorizationBinding(); + var accountBinding = request.freezeEvidence().request().accountBinding(); + var acknowledgement = request.freezeEvidence().acknowledgement(); + UUID differentId = + differentReadId( + request.readRequestId(), + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + accountBinding.operationId(), + accountBinding.fenceId(), + acknowledgement.intakeRequestId(), + acknowledgement.publicationFence()); + return new SelectedOwnerWorldInventoryReadEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + differentId, + binding, + request.freezeEvidence()); + } + + private static UUID differentReadId(UUID original, UUID... reserved) { + UUID candidate; + do { + candidate = UUID.randomUUID(); + } while (candidate.equals(original) || contains(reserved, candidate)); + return candidate; + } + + private static boolean contains(UUID[] values, UUID candidate) { + for (UUID value : values) { + if (candidate.equals(value)) return true; + } + return false; + } + + private static T withGameDesignPeer(Supplier action) { + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service", + NAMESPACE, + "game-design-service"); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private enum ReadFailure { + FIRST_ACCOUNT_UNAVAILABLE, + FIRST_ACCOUNT_MISMATCH, + WORLD_UNAVAILABLE, + WORLD_MISMATCH, + FINAL_ACCOUNT_UNAVAILABLE, + FINAL_ACCOUNT_MISMATCH + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSnapshot.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSnapshot.java new file mode 100644 index 0000000000..65e60aaf3d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSnapshot.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Ordinary selected source only; no total inventory or template/branding completeness claim. */ +public record AssetSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List items) { + public AssetSnapshot { + Objects.requireNonNull(binding); + Objects.requireNonNull(genesisReceiptId); + if (!sourceEpoch.matches("0|[1-9][0-9]*") || new UUID(0, 0).equals(genesisReceiptId)) + throw new IllegalArgumentException("Exact ordinary asset source epoch and genesis required"); + items = List.copyOf(items); + new AssetSource.Snapshot(binding, items.stream().map(Item::reference).toList()); + var ordered = + items.stream() + .sorted( + java.util.Comparator.comparing( + item -> item.reference().usageKey(), + (String left, String right) -> + java.util.Arrays.compareUnsigned( + left.getBytes(StandardCharsets.UTF_8), + right.getBytes(StandardCharsets.UTF_8)))) + .toList(); + if (!items.equals(ordered)) + throw new IllegalArgumentException("Ordinary asset items must be in canonical key order"); + } + + public record Item( + AssetSource.Reference reference, String contentType, String contentDigest, long byteSize) { + public Item { + Objects.requireNonNull(reference); + if (contentType == null + || contentType.isBlank() + || contentType.codePointCount(0, contentType.length()) > 100 + || contentDigest == null + || !contentDigest.matches("sha256:[0-9a-f]{64}") + || byteSize < 0) + throw new IllegalArgumentException("Exact ordinary asset byte metadata required"); + } + + Map object() { + var r = reference; + return Map.ofEntries( + Map.entry("family", r.family()), + Map.entry("role", r.role()), + Map.entry("usageKey", r.usageKey()), + Map.entry("assetRowId", r.assetRowId()), + Map.entry("requiredness", r.requiredness().name()), + Map.entry("sourceBindingJson", r.sourceBinding().canonicalJson()), + Map.entry("sourceBindingDigest", r.sourceBinding().digest()), + Map.entry("revisionOrder", r.revisionOrder()), + Map.entry("revisionId", r.revisionId().toString()), + Map.entry("contentType", contentType), + Map.entry("contentDigest", contentDigest), + Map.entry("byteSize", Long.toString(byteSize))); + } + } + + public String canonicalJson() { + return CommandSource.canonical( + Map.of( + "schema", + "game-design-ordinary-asset-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptId", + genesisReceiptId.toString(), + "items", + items.stream().map(Item::object).toList())); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static AssetSnapshot fromStored(String json) { + var root = CommandSource.tree(json); + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "items"); + if (!"game-design-ordinary-asset-source-snapshot/v1" + .equals(CommandSource.requiredStoredText(root, "schema")) + || !root.path("items").isArray()) + throw new IllegalArgumentException("Unsupported ordinary asset snapshot"); + var binding = + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(root, "bindingJson"), + CommandSource.requiredStoredText(root, "bindingDigest")); + var items = new java.util.ArrayList(); + for (var node : root.path("items")) { + CommandSource.requireStoredFields( + node, + "family", + "role", + "usageKey", + "assetRowId", + "requiredness", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId", + "contentType", + "contentDigest", + "byteSize"); + if (!AssetSource.FAMILY.equals(CommandSource.requiredStoredText(node, "family")) + || !AssetSource.ROLE.equals(CommandSource.requiredStoredText(node, "role"))) + throw new IllegalArgumentException("Unsupported ordinary source family or role"); + var reference = + new AssetSource.Reference( + CommandSource.requiredStoredText(node, "usageKey"), + CommandSource.requiredStoredText(node, "assetRowId"), + AssetSource.Requiredness.valueOf( + CommandSource.requiredStoredText(node, "requiredness")), + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(node, "sourceBindingJson"), + CommandSource.requiredStoredText(node, "sourceBindingDigest")), + CommandSource.requiredStoredText(node, "revisionOrder"), + UUID.fromString(CommandSource.requiredStoredText(node, "revisionId"))); + items.add( + new Item( + reference, + CommandSource.requiredStoredText(node, "contentType"), + CommandSource.requiredStoredText(node, "contentDigest"), + Long.parseLong(CommandSource.requiredStoredText(node, "byteSize")))); + } + if (!root.path("inheritedCommitId").isTextual()) + throw new IllegalArgumentException("Stored inherited commit must be text"); + String inherited = root.path("inheritedCommitId").textValue(); + var result = + new AssetSnapshot( + binding, + CommandSource.requiredStoredText(root, "sourceEpoch"), + inherited.isEmpty() ? null : UUID.fromString(inherited), + UUID.fromString(CommandSource.requiredStoredText(root, "genesisReceiptId")), + items); + if (!result.canonicalJson().equals(json)) + throw new IllegalArgumentException("Noncanonical ordinary asset snapshot"); + return result; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSource.java similarity index 98% rename from services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java rename to services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSource.java index 1257d52680..4f3da0cb00 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSource.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AssetSource.java @@ -1,4 +1,4 @@ -package net.firedevops.firemud.gamedesign.publication; +package net.firedevops.firemud.common.gamedesign; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -152,9 +152,9 @@ public static List mutations(DraftCommitBinding binding) { if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; JsonNode payload = tree(revision.payload()); String kind = text(payload, "revisionKind"); - if ("COMMAND_DEFINITION".equals(kind) - || "REALM_ENTRY_POLICY".equals(kind) - || TemplateConfigSource.REVISION_KIND.equals(kind) + if (CommandSource.REVISION_KIND.equals(kind) + || RealmPolicySource.REVISION_KIND.equals(kind) + || TemplateConfigSourceValues.REVISION_KIND.equals(kind) || GameplayRuleSource.REVISION_KIND.equals(kind) || BrandingSource.REVISION_KIND.equals(kind)) continue; if (!REVISION_KIND.equals(kind)) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSource.java similarity index 98% rename from services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSource.java rename to services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSource.java index 93d948c425..14872582a0 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSource.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSource.java @@ -1,4 +1,4 @@ -package net.firedevops.firemud.gamedesign.publication; +package net.firedevops.firemud.common.gamedesign; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -162,9 +162,9 @@ public static List mutations(DraftCommitBinding binding) { if (revision.owner() != Owner.GAME_DESIGN_CONTROL_PLANE) continue; JsonNode payload = tree(revision.payload()); String kind = text(payload, "revisionKind"); - if ("COMMAND_DEFINITION".equals(kind) - || "REALM_ENTRY_POLICY".equals(kind) - || TemplateConfigSource.REVISION_KIND.equals(kind) + if (CommandSource.REVISION_KIND.equals(kind) + || RealmPolicySource.REVISION_KIND.equals(kind) + || TemplateConfigSourceValues.REVISION_KIND.equals(kind) || GameplayRuleSource.REVISION_KIND.equals(kind) || AssetSource.REVISION_KIND.equals(kind)) continue; if (!REVISION_KIND.equals(kind)) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSourceSnapshot.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSourceSnapshot.java new file mode 100644 index 0000000000..0804dcec58 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/BrandingSourceSnapshot.java @@ -0,0 +1,179 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Branding selected source only; no total inventory or template completeness claim. */ +public record BrandingSourceSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + UUID genesisReceiptId, + List items) { + public BrandingSourceSnapshot { + Objects.requireNonNull(binding); + Objects.requireNonNull(genesisReceiptId); + if (!sourceEpoch.matches("0|[1-9][0-9]*") || new UUID(0, 0).equals(genesisReceiptId)) + throw new IllegalArgumentException("Exact branding asset source epoch and genesis required"); + items = List.copyOf(items); + new BrandingSource.Snapshot(binding, items.stream().map(Item::reference).toList()); + var ordered = + items.stream() + .sorted( + java.util.Comparator.comparing( + item -> item.reference().usageKey(), + (String left, String right) -> + java.util.Arrays.compareUnsigned( + left.getBytes(StandardCharsets.UTF_8), + right.getBytes(StandardCharsets.UTF_8)))) + .toList(); + if (!items.equals(ordered)) + throw new IllegalArgumentException("Branding asset items must be in canonical key order"); + } + + public record Item( + BrandingSource.Reference reference, String contentType, String contentDigest, long byteSize) { + public Item { + Objects.requireNonNull(reference); + if (contentType == null + || contentType.isBlank() + || contentType.codePointCount(0, contentType.length()) > 100 + || contentDigest == null + || !contentDigest.matches("sha256:[0-9a-f]{64}") + || byteSize < 0) + throw new IllegalArgumentException("Exact branding asset byte metadata required"); + } + + Map object() { + var r = reference; + return Map.ofEntries( + Map.entry("family", r.family()), + Map.entry("role", r.role().name()), + Map.entry("usageKey", r.usageKey()), + Map.entry("assetRowId", r.assetRowId()), + Map.entry("requiredness", r.requiredness().name()), + Map.entry("sourceBindingJson", r.sourceBinding().canonicalJson()), + Map.entry("sourceBindingDigest", r.sourceBinding().digest()), + Map.entry("revisionOrder", r.revisionOrder()), + Map.entry("revisionId", r.revisionId().toString()), + Map.entry("contentType", contentType), + Map.entry("contentDigest", contentDigest), + Map.entry("byteSize", Long.toString(byteSize))); + } + } + + public String canonicalJson() { + return CommandSource.canonical( + Map.of( + "schema", + "game-design-branding-asset-source-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptId", + genesisReceiptId.toString(), + "roles", + roleDeclarations(), + "items", + items.stream().map(Item::object).toList())); + } + + /** Every role is explicitly declared against actual genesis and selected writer history. */ + public Map roleDeclarations() { + var result = new java.util.TreeMap(); + for (var role : BrandingSource.Role.values()) + result.put( + role.name(), + items.stream().anyMatch(item -> item.reference().role() == role) ? "PRESENT" : "EMPTY"); + return Map.copyOf(result); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static BrandingSourceSnapshot fromStored(String json) { + var root = CommandSource.tree(json); + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptId", + "roles", + "items"); + if (!"game-design-branding-asset-source-snapshot/v1" + .equals(CommandSource.requiredStoredText(root, "schema")) + || !root.path("items").isArray()) + throw new IllegalArgumentException("Unsupported branding asset snapshot"); + var binding = + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(root, "bindingJson"), + CommandSource.requiredStoredText(root, "bindingDigest")); + var items = new java.util.ArrayList(); + for (var node : root.path("items")) { + CommandSource.requireStoredFields( + node, + "family", + "role", + "usageKey", + "assetRowId", + "requiredness", + "sourceBindingJson", + "sourceBindingDigest", + "revisionOrder", + "revisionId", + "contentType", + "contentDigest", + "byteSize"); + if (!BrandingSource.FAMILY.equals(CommandSource.requiredStoredText(node, "family"))) + throw new IllegalArgumentException("Unsupported branding source family or role"); + var reference = + new BrandingSource.Reference( + CommandSource.requiredStoredText(node, "usageKey"), + CommandSource.requiredStoredText(node, "assetRowId"), + BrandingSource.Role.valueOf(CommandSource.requiredStoredText(node, "role")), + BrandingSource.Requiredness.valueOf( + CommandSource.requiredStoredText(node, "requiredness")), + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(node, "sourceBindingJson"), + CommandSource.requiredStoredText(node, "sourceBindingDigest")), + CommandSource.requiredStoredText(node, "revisionOrder"), + UUID.fromString(CommandSource.requiredStoredText(node, "revisionId"))); + items.add( + new Item( + reference, + CommandSource.requiredStoredText(node, "contentType"), + CommandSource.requiredStoredText(node, "contentDigest"), + Long.parseLong(CommandSource.requiredStoredText(node, "byteSize")))); + } + if (!root.path("inheritedCommitId").isTextual()) + throw new IllegalArgumentException("Stored inherited commit must be text"); + String inherited = root.path("inheritedCommitId").textValue(); + var result = + new BrandingSourceSnapshot( + binding, + CommandSource.requiredStoredText(root, "sourceEpoch"), + inherited.isEmpty() ? null : UUID.fromString(inherited), + UUID.fromString(CommandSource.requiredStoredText(root, "genesisReceiptId")), + items); + if (!result.canonicalJson().equals(json)) + throw new IllegalArgumentException("Noncanonical branding asset snapshot"); + return result; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSnapshot.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSnapshot.java new file mode 100644 index 0000000000..c83cce9605 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSnapshot.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Complete effective command set captured at one actual synchronized Draft commit. */ +public record CommandSnapshot( + DraftCommitBinding binding, + String sourceEpoch, + UUID inheritedCommitId, + String genesisReceiptDigest, + List definitions) { + public CommandSnapshot { + Objects.requireNonNull(binding, "binding"); + requireCounter(sourceEpoch, "sourceEpoch"); + if (inheritedCommitId != null && new UUID(0, 0).equals(inheritedCommitId)) { + throw new IllegalArgumentException("inheritedCommitId must be non-nil when present"); + } + if (genesisReceiptDigest == null || !genesisReceiptDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Exact command source genesis receipt digest required"); + } + definitions = List.copyOf(Objects.requireNonNull(definitions, "definitions")); + CommandSource.requireCanonicalDefinitions(definitions); + } + + @Override + public List definitions() { + return List.copyOf(definitions); + } + + public String canonicalJson() { + return CommandSource.canonical( + Map.of( + "schema", + CommandSource.SNAPSHOT_SCHEMA, + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "inheritedCommitId", + inheritedCommitId == null ? "" : inheritedCommitId.toString(), + "genesisReceiptDigest", + genesisReceiptDigest, + "definitions", + CommandSource.tree(CommandSource.definitionsJson(definitions)))); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static CommandSnapshot fromStored(String json) { + var root = CommandSource.tree(json); + CommandSource.requireStoredFields( + root, + "schema", + "bindingJson", + "bindingDigest", + "sourceEpoch", + "inheritedCommitId", + "genesisReceiptDigest", + "definitions"); + if (!CommandSource.SNAPSHOT_SCHEMA.equals(CommandSource.requiredStoredText(root, "schema"))) { + throw new IllegalArgumentException("Unsupported command source snapshot schema"); + } + var inheritedNode = root.get("inheritedCommitId"); + if (inheritedNode == null || !inheritedNode.isTextual()) { + throw new IllegalArgumentException("Stored command source inheritedCommitId must be text"); + } + String inherited = inheritedNode.textValue(); + UUID inheritedCommitId = inherited.isEmpty() ? null : UUID.fromString(inherited); + if (inheritedCommitId != null && !inheritedCommitId.toString().equals(inherited)) { + throw new IllegalArgumentException( + "Stored command source inheritedCommitId must be a canonical UUID"); + } + var result = + new CommandSnapshot( + DraftCommitBinding.fromStored( + CommandSource.requiredStoredText(root, "bindingJson"), + CommandSource.requiredStoredText(root, "bindingDigest")), + CommandSource.requiredStoredText(root, "sourceEpoch"), + inheritedCommitId, + CommandSource.requiredStoredText(root, "genesisReceiptDigest"), + CommandSource.definitionsFromStored(root.get("definitions").toString())); + if (!result.canonicalJson().equals(json)) { + throw new IllegalArgumentException( + "Stored command source snapshot is not exact canonical JSON"); + } + return result; + } + + private static void requireCounter(String value, String name) { + if (value == null || !value.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException(name + " must be a canonical nonnegative decimal"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java similarity index 97% rename from services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java rename to services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java index 9cf5ec7746..9c90c4ecea 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSource.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/CommandSource.java @@ -1,4 +1,4 @@ -package net.firedevops.firemud.gamedesign.publication; +package net.firedevops.firemud.common.gamedesign; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -26,9 +26,8 @@ public final class CommandSource { public static final String SCOPE_ID = "effective"; public static final String SNAPSHOT_SCHEMA = "game-design-command-source-snapshot/v1"; public static final String APPLICATION_SCHEMA = "game-design-command-source-application/v1"; - public static final String REALM_POLICY_REVISION_KIND = "REALM_ENTRY_POLICY"; - private static final String REVISION_KIND = "COMMAND_DEFINITION"; + public static final String REVISION_KIND = "COMMAND_DEFINITION"; private static final int SCHEMA_VERSION = 1; private static final UUID NIL_UUID = new UUID(0, 0); private static final ObjectMapper JSON = new ObjectMapper(); @@ -155,11 +154,11 @@ public static List mutations(DraftCommitBinding binding) { throw new IllegalArgumentException("Closed Game Design owner revision kind is required"); } String revisionKind = payload.path("revisionKind").asText(); - if (REALM_POLICY_REVISION_KIND.equals(revisionKind) + if (RealmPolicySource.REVISION_KIND.equals(revisionKind) || AssetSource.REVISION_KIND.equals(revisionKind) || GameplayRuleSource.REVISION_KIND.equals(revisionKind) || BrandingSource.REVISION_KIND.equals(revisionKind) - || TemplateConfigSource.REVISION_KIND.equals(revisionKind)) continue; + || TemplateConfigSourceValues.REVISION_KIND.equals(revisionKind)) continue; if (!REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } @@ -206,13 +205,13 @@ public static boolean hasRealmPolicyRevision(DraftCommitBinding binding) { throw new IllegalArgumentException("Closed Game Design owner revision kind is required"); } String revisionKind = payload.path("revisionKind").asText(); - if (REALM_POLICY_REVISION_KIND.equals(revisionKind)) { + if (RealmPolicySource.REVISION_KIND.equals(revisionKind)) { found = true; } else if (!REVISION_KIND.equals(revisionKind) && !AssetSource.REVISION_KIND.equals(revisionKind) && !GameplayRuleSource.REVISION_KIND.equals(revisionKind) && !BrandingSource.REVISION_KIND.equals(revisionKind) - && !TemplateConfigSource.REVISION_KIND.equals(revisionKind)) { + && !TemplateConfigSourceValues.REVISION_KIND.equals(revisionKind)) { throw new IllegalArgumentException("Unsupported Game Design command source revision kind"); } } @@ -323,11 +322,11 @@ static List definitionsFromStored(String json) { return List.copyOf(result); } - static String mutationsJson(List mutations) { + public static String mutationsJson(List mutations) { return canonical(mutations.stream().map(Mutation::canonicalObject).toList()); } - static List mutationsFromStored(String json) { + public static List mutationsFromStored(String json) { JsonNode root = tree(json); if (!root.isArray()) throw new IllegalArgumentException("Complete command operation list is required"); @@ -405,7 +404,7 @@ static String requiredStoredText(JsonNode node, String field) { return requiredText(node, field); } - static String canonical(Object value) { + public static String canonical(Object value) { try { return new String( Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), @@ -415,7 +414,7 @@ static String canonical(Object value) { } } - static JsonNode tree(String json) { + public static JsonNode tree(String json) { try { return JSON.readTree(Rfc8785CanonicalJson.canonicalizeUtf8(json)); } catch (IOException | RuntimeException failure) { @@ -427,7 +426,7 @@ static byte[] canonicalBytes(String json) { return json.getBytes(StandardCharsets.UTF_8); } - static String sha256(byte[] bytes) { + public static String sha256(byte[] bytes) { try { return "sha256:" + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); @@ -436,7 +435,7 @@ static String sha256(byte[] bytes) { } } - static Map targetObject(DraftCommitBinding.TargetProof target) { + public static Map targetObject(DraftCommitBinding.TargetProof target) { Map result = new LinkedHashMap<>(); result.put("canonicalTenantId", target.canonicalTenantId().toString()); result.put("canonicalVersionId", target.canonicalVersionId().toString()); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java similarity index 96% rename from services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSource.java rename to services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java index 36e760c912..da9bb63451 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSource.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java @@ -1,4 +1,4 @@ -package net.firedevops.firemud.gamedesign.publication; +package net.firedevops.firemud.common.gamedesign; import java.util.ArrayList; import java.util.EnumMap; @@ -111,11 +111,11 @@ public static List mutations(DraftCommitBinding binding) { var node = GameplayRuleManifest.tree(revision.payload()); String kind = text(node, "revisionKind"); if (Set.of( - "COMMAND_DEFINITION", - "REALM_ENTRY_POLICY", - "ASSET_REFERENCE", + CommandSource.REVISION_KIND, + RealmPolicySource.REVISION_KIND, + AssetSource.REVISION_KIND, BrandingSource.REVISION_KIND, - TemplateConfigSource.REVISION_KIND) + TemplateConfigSourceValues.REVISION_KIND) .contains(kind)) continue; if (!REVISION_KIND.equals(kind)) throw new IllegalArgumentException("Unknown Game Design revision kind"); @@ -209,7 +209,7 @@ public static boolean isScope(DraftCommitBinding.AffectedUnit unit) { && SCOPE_ID.equals(unit.scopeId()); } - static String text(tools.jackson.databind.JsonNode node, String key) { + public static String text(tools.jackson.databind.JsonNode node, String key) { if (!node.path(key).isTextual() || node.path(key).textValue().isBlank()) throw new IllegalArgumentException("Required rule-source field missing: " + key); return node.path(key).textValue(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySnapshot.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySnapshot.java new file mode 100644 index 0000000000..f46d3a7754 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySnapshot.java @@ -0,0 +1,64 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; + +/** Complete effective source at one synchronized fence, including original revision provenance. */ +public record RealmPolicySnapshot( + DraftCommitBinding binding, String sourceEpoch, List policies) { + public RealmPolicySnapshot { + if (binding == null || sourceEpoch == null || !sourceEpoch.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("Exact source binding and canonical epoch required"); + } + policies = RealmPolicySource.draftOrdered(policies); + } + + @Override + public List policies() { + return List.copyOf(policies); + } + + public String canonicalJson() { + return RealmPolicySource.canonical( + Map.of( + "schema", + "game-design-realm-policy-snapshot/v1", + "bindingJson", + binding.canonicalJson(), + "bindingDigest", + binding.digest(), + "sourceEpoch", + sourceEpoch, + "policies", + RealmPolicySource.tree(RealmPolicySource.policiesJson(policies)))); + } + + public byte[] canonicalBytes() { + return canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return CommandSource.sha256(canonicalBytes()); + } + + public static RealmPolicySnapshot fromStored(String json) { + var node = RealmPolicySource.tree(json); + RealmPolicySource.fields( + node, "schema", "bindingJson", "bindingDigest", "sourceEpoch", "policies"); + if (!"game-design-realm-policy-snapshot/v1".equals(RealmPolicySource.text(node, "schema"))) { + throw new IllegalArgumentException("Unsupported policy snapshot schema"); + } + var result = + new RealmPolicySnapshot( + DraftCommitBinding.fromStored( + RealmPolicySource.text(node, "bindingJson"), + RealmPolicySource.text(node, "bindingDigest")), + RealmPolicySource.text(node, "sourceEpoch"), + RealmPolicySource.policiesFromStored(node.get("policies").toString())); + if (!result.canonicalJson().equals(json)) + throw new IllegalArgumentException("Policy snapshot bytes changed"); + return result; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java similarity index 95% rename from services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java rename to services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java index c22014d880..8531045118 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java @@ -1,4 +1,4 @@ -package net.firedevops.firemud.gamedesign.publication; +package net.firedevops.firemud.common.gamedesign; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -19,6 +19,7 @@ public final class RealmPolicySource { private static final ObjectMapper JSON = new ObjectMapper(); public static final String SCOPE = "REALM_ENTRY_POLICY_SET"; + public static final String REVISION_KIND = RealmEntryPolicy.REVISION_KIND; public static final int MAX_POLICIES = 128; private RealmPolicySource() {} @@ -43,11 +44,11 @@ public record Policy( public static boolean isPolicyRevision(DraftCommitBinding.RevisionPayload input) { var kind = text(tree(input.payload()), "revisionKind"); if (RealmEntryPolicy.REVISION_KIND.equals(kind)) return true; - if ("COMMAND_DEFINITION".equals(kind) + if (CommandSource.REVISION_KIND.equals(kind) || AssetSource.REVISION_KIND.equals(kind) || GameplayRuleSource.REVISION_KIND.equals(kind) || BrandingSource.REVISION_KIND.equals(kind) - || TemplateConfigSource.REVISION_KIND.equals(kind)) return false; + || TemplateConfigSourceValues.REVISION_KIND.equals(kind)) return false; throw new IllegalArgumentException("Unsupported Game Design owner revision kind"); } @@ -153,7 +154,7 @@ static List policiesFromStored(String bytes) { return result; } - static String canonical(Object value) { + public static String canonical(Object value) { try { return new String( Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), @@ -163,7 +164,7 @@ static String canonical(Object value) { } } - static JsonNode tree(String value) { + public static JsonNode tree(String value) { try { return JSON.readTree(Rfc8785CanonicalJson.canonicalizeUtf8(value)); } catch (IOException | RuntimeException failure) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java index 2c19fb4789..b6c06f57e4 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContent.java @@ -18,11 +18,11 @@ /** * Exact six-family Game Design source content bound to one selected-owner preliminary scope. * - *

Decoding checks framing, hashes, canonical JSON bindings and the existing typed gameplay-rule - * and template-config sources. It does not authenticate disclosure, grant finalization or retention - * authority, prove an owner inventory complete or empty, or create an owner receipt. Template - * snapshot v1/v2 parsing retains the stored grammar but does not prove a fresh authored inventory. - * Four source families remain opaque beyond their canonical JSON binding to the selected Draft. + *

Decoding checks framing, hashes, canonical JSON bindings and each existing typed source + * snapshot. It does not authenticate disclosure, grant finalization or retention authority, prove + * an owner inventory complete or empty, or create an owner receipt. Template snapshot v1/v2 parsing + * retains the stored grammar but does not prove a fresh authored inventory. Typed snapshot + * integrity is not independent proof that all owner references are resolved. */ public final class SelectedOwnerIntakeSourceContent { public static final String DOMAIN = "game-design-selected-owner-intake-source/v1"; @@ -36,6 +36,10 @@ public final class SelectedOwnerIntakeSourceContent { private final byte[] canonicalBytes; private final String digest; private final Map snapshots; + private final CommandSnapshot commandSource; + private final RealmPolicySnapshot realmPolicySource; + private final AssetSnapshot assetSource; + private final BrandingSourceSnapshot brandingSource; private final GameplayRuleSelectedSource gameplaySource; private final TemplateConfigSourceSnapshot templateConfigSource; @@ -44,6 +48,10 @@ private SelectedOwnerIntakeSourceContent( byte[] canonicalBytes, String digest, Map snapshots, + CommandSnapshot commandSource, + RealmPolicySnapshot realmPolicySource, + AssetSnapshot assetSource, + BrandingSourceSnapshot brandingSource, GameplayRuleSelectedSource gameplaySource, TemplateConfigSourceSnapshot templateConfigSource) { this.scope = scope; @@ -52,6 +60,10 @@ private SelectedOwnerIntakeSourceContent( var copiedSnapshots = new LinkedHashMap(); for (String family : FAMILIES) copiedSnapshots.put(family, snapshots.get(family).clone()); this.snapshots = Map.copyOf(copiedSnapshots); + this.commandSource = commandSource; + this.realmPolicySource = realmPolicySource; + this.assetSource = assetSource; + this.brandingSource = brandingSource; this.gameplaySource = gameplaySource; this.templateConfigSource = templateConfigSource; } @@ -103,6 +115,15 @@ public static SelectedOwnerIntakeSourceContent fromStored( } reader.requireEnd(); + CommandSnapshot commandSource = + CommandSnapshot.fromStored(utf8(snapshots.get("COMMAND"), "COMMAND")); + RealmPolicySnapshot realmPolicySource = + RealmPolicySnapshot.fromStored(utf8(snapshots.get("REALM_POLICY"), "REALM_POLICY")); + AssetSnapshot assetSource = AssetSnapshot.fromStored(utf8(snapshots.get("ASSET"), "ASSET")); + BrandingSourceSnapshot brandingSource = + BrandingSourceSnapshot.fromStored(utf8(snapshots.get("BRANDING"), "BRANDING")); + requireClosedGameDesignRevisions(decodedScope.selected()); + GameplayRuleSelectedSource gameplaySource = new GameplayRuleSelectedSource(utf8(snapshots.get("GAMEPLAY_RULE"), "GAMEPLAY_RULE")); if (!decodedScope.selected().equals(gameplaySource.binding())) @@ -115,7 +136,16 @@ public static SelectedOwnerIntakeSourceContent fromStored( throw new IllegalArgumentException("Selected template config binding differs"); return new SelectedOwnerIntakeSourceContent( - decodedScope, stored, actualDigest, snapshots, gameplaySource, templateConfigSource); + decodedScope, + stored, + actualDigest, + snapshots, + commandSource, + realmPolicySource, + assetSource, + brandingSource, + gameplaySource, + templateConfigSource); } public SelectedOwnerIntakeSourceReadScope scope() { @@ -144,10 +174,42 @@ public GameplayRuleSelectedSource gameplaySource() { return gameplaySource; } + public CommandSnapshot commandSource() { + return commandSource; + } + + public RealmPolicySnapshot realmPolicySource() { + return realmPolicySource; + } + + public AssetSnapshot assetSource() { + return assetSource; + } + + public BrandingSourceSnapshot brandingSource() { + return brandingSource; + } + public TemplateConfigSourceSnapshot templateConfigSource() { return templateConfigSource; } + private static void requireClosedGameDesignRevisions(DraftCommitBinding binding) { + // Each actual owner grammar validates its family and rejects unrecognized Game Design kinds. + // Other owners' payloads are not interpreted as Game Design sources or silently reconstructed. + CommandSource.mutations(binding); + AssetSource.mutations(binding); + BrandingSource.mutations(binding); + GameplayRuleSource.mutations(binding); + TemplateConfigSourceValues.mutations(binding); + for (var revision : binding.revisions()) { + if (revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE + && RealmPolicySource.isPolicyRevision(revision)) { + RealmPolicySource.revision(binding, revision); + } + } + } + private static void requireSelectedBinding( String family, byte[] snapshot, DraftCommitBinding selected) { String json = utf8(snapshot, family); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java index 927d4242d6..8464d9316d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java @@ -21,6 +21,7 @@ import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; @@ -257,7 +258,8 @@ private static TemplateConfigSourceSnapshot templateSnapshot( payloads.add( TemplateConfigSourceValues.createPayload("entry-" + index, options.entries().get(index))); } - if (payloads.isEmpty()) payloads.add("{\"revisionKind\":\"COMMAND_DEFINITION\"}"); + if (payloads.isEmpty()) + payloads.add(SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); DraftCommitBinding authored = authoredBinding(payloads); var mutations = TemplateConfigSourceValues.mutations(authored); @@ -360,17 +362,7 @@ private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) List.of()))) .canonicalBytes(); } - return GameplayRuleManifest.canonical( - Map.of( - "schema", - "synthetic-test-only/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "family", - family)) - .getBytes(StandardCharsets.UTF_8); + return SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); } private static List accountSources() { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java index 25bdbe30fd..ae65cb4f3b 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java @@ -17,6 +17,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; @@ -315,29 +316,13 @@ private static List snapshots(DraftCommitBinding selected) { switch (family) { case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); case "TEMPLATE_CONFIG" -> template.canonicalBytes(); - default -> opaqueSnapshot(family, selected, "synthetic-" + family); + default -> SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); }; result.add(new FamilySnapshot(family, bytes)); } return result; } - private static byte[] opaqueSnapshot(String family, DraftCommitBinding selected, String marker) { - return GameplayRuleManifest.canonical( - Map.of( - "schema", - "synthetic-test-only/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "family", - family, - "marker", - marker)) - .getBytes(StandardCharsets.UTF_8); - } - private static byte[] encodeContent( SelectedOwnerIntakeSourceReadScope scope, List snapshots) { var out = new ByteArrayOutputStream(); @@ -402,7 +387,10 @@ private static DraftCommitBinding selected() { "base-commit-0", List.of( new DraftCommitBinding.RevisionPayload( - "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + "0", + REVISION, + Owner.GAME_DESIGN_CONTROL_PLANE, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())), List.of( new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java index 02114c823d..17196be056 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadEvidenceTest.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; @@ -122,17 +123,7 @@ private static byte[] snapshot(String family, DraftCommitBinding selected) { return new TemplateConfigSourceSnapshot( selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) .canonicalBytes(); - return GameplayRuleManifest.canonical( - Map.of( - "schema", - "synthetic-test-only/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "family", - family)) - .getBytes(StandardCharsets.UTF_8); + return SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); } private static List sources(UUID actor, UUID tenant) { @@ -161,7 +152,7 @@ private static DraftCommitBinding selected(UUID tenant) { "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.GAME_DESIGN_CONTROL_PLANE, - "{}")), + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())), List.of( new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java index 49be8a3aea..3fe96e7796 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; @@ -325,17 +326,7 @@ private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) .canonicalBytes(); } - return GameplayRuleManifest.canonical( - Map.of( - "schema", - "synthetic-test-only/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "family", - family)) - .getBytes(StandardCharsets.UTF_8); + return SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); } private static PublicEvidence publicInventory( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java index 04e5653691..a525c43a3f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java @@ -102,7 +102,8 @@ void pinsGameDesignServerAndRoundTripsBothOwnerScopesOverLoopbackMtls() throws E try (var client = newClient(pki.gameDesignClient())) { client.init(); for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { - var request = request(owner, "{}"); + var request = + request(owner, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); assertThat(client.read(request).scope()).isEqualTo(request.scope()); } assertThat(calls).hasValue(2); @@ -114,7 +115,12 @@ void pinsGameDesignServerAndRoundTripsBothOwnerScopesOverLoopbackMtls() throws E start(pki.wrongServer()); try (var client = newClient(pki.gameDesignClient())) { client.init(); - assertThatThrownBy(() -> client.read(request(Owner.ENTITY_MANAGEMENT, "{}"))) + assertThatThrownBy( + () -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) .isInstanceOf(StatusRuntimeException.class) .satisfies( error -> @@ -128,7 +134,10 @@ void pinsGameDesignServerAndRoundTripsBothOwnerScopesOverLoopbackMtls() throws E void transportsLargeCompleteContentWithinExplicitWireBudget() throws Exception { largeResponse = true; start(pki.gameDesignServer()); - var request = request(Owner.AUTOMATION_SCRIPTING, "{}"); + var request = + request( + Owner.AUTOMATION_SCRIPTING, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); try (var client = newClient(pki.gameDesignClient())) { client.init(); var content = client.read(request); @@ -147,7 +156,12 @@ void requiresExactClientCertificateAndRejectsExpiredServerOrClientCertificates() start(pki.gameDesignServer()); try (var client = newClient(pki.wrongClient())) { client.init(); - assertThatThrownBy(() -> client.read(request(Owner.ENTITY_MANAGEMENT, "{}"))) + assertThatThrownBy( + () -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) .isInstanceOf(StatusRuntimeException.class) .satisfies( error -> @@ -162,7 +176,12 @@ void requiresExactClientCertificateAndRejectsExpiredServerOrClientCertificates() start(pki.expiredGameDesignServer()); try (var client = newClient(pki.gameDesignClient())) { client.init(); - assertThatThrownBy(() -> client.read(request(Owner.ENTITY_MANAGEMENT, "{}"))) + assertThatThrownBy( + () -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) .isInstanceOf(StatusRuntimeException.class); assertThat(calls).hasValue(1); } @@ -173,7 +192,12 @@ void requiresExactClientCertificateAndRejectsExpiredServerOrClientCertificates() start(pki.gameDesignServer()); try (var client = newClient(pki.expiredGameDesignClient())) { client.init(); - assertThatThrownBy(() -> client.read(request(Owner.ENTITY_MANAGEMENT, "{}"))) + assertThatThrownBy( + () -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) .isInstanceOf(StatusRuntimeException.class); assertThat(calls).hasValue(1); } @@ -184,11 +208,18 @@ void rejectsOtherNamespaceAmbientSqlSynchronizationAndSubstitutedEcho() throws E start(pki.gameDesignServer()); try (var client = newClient(pki.gameDesignClient())) { client.init(); - var otherNamespace = request(Owner.ENTITY_MANAGEMENT, "{}", "other"); + var otherNamespace = + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload(), + "other"); assertThatThrownBy(() -> client.read(otherNamespace)) .isInstanceOf(IllegalArgumentException.class); - var request = request(Owner.ENTITY_MANAGEMENT, "{}"); + var request = + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); TransactionSynchronizationManager.setActualTransactionActive(true); try { assertThatThrownBy(() -> client.read(request)).isInstanceOf(IllegalStateException.class); @@ -215,7 +246,12 @@ void boundsUnavailableReadByFiveSecondDeadline() throws Exception { start(pki.gameDesignServer()); try (var client = newClient(pki.gameDesignClient())) { client.init(); - assertThatThrownBy(() -> client.read(request(Owner.AUTOMATION_SCRIPTING, "{}"))) + assertThatThrownBy( + () -> + client.read( + request( + Owner.AUTOMATION_SCRIPTING, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) .isInstanceOf(StatusRuntimeException.class) .satisfies( error -> @@ -344,12 +380,8 @@ private static SelectedOwnerIntakeSourceContent content( case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); case "TEMPLATE_CONFIG" -> template.canonicalBytes(); default -> - opaqueSnapshot( - family, - selected, - family.equals("COMMAND") - ? "x".repeat(largeCommandMarkerSize) - : "synthetic-" + family); + SelectedOwnerIntakeSourceTestFixtures.snapshot( + family, selected, family.equals("COMMAND") ? largeCommandMarkerSize : 0); }; frame(out, family); frame(out, snapshot); @@ -360,22 +392,6 @@ private static SelectedOwnerIntakeSourceContent content( encoded, scope, DraftAuthorizationFenceBinding.digest(encoded)); } - private static byte[] opaqueSnapshot(String family, DraftCommitBinding selected, String marker) { - return GameplayRuleManifest.canonical( - Map.of( - "schema", - "synthetic-test-only/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "family", - family, - "marker", - marker)) - .getBytes(StandardCharsets.UTF_8); - } - private static DraftCommitBinding binding(UUID commitId, String payload) { return DraftCommitBinding.create( new DraftCommitBinding.TargetProof( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java index 59b9163053..b43910ce8f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java @@ -57,6 +57,26 @@ void roundTripsBothOwnerDomainsAndPreservesDefensiveExactFamilyBytes() { assertThat(content.canonicalBytes()).isNotEqualTo(exposedContent); assertThat(content.digest()).isEqualTo(digest(encode(scope, snapshots))); assertThat(content.snapshotBytes("COMMAND")).isEqualTo(expected); + assertThat(content.commandSource().binding()).isEqualTo(selected); + assertThat(content.commandSource().definitions()).isEmpty(); + assertThat(content.commandSource().canonicalBytes()) + .containsExactly(content.snapshotBytes("COMMAND")); + assertThat(content.realmPolicySource().binding()).isEqualTo(selected); + assertThat(content.realmPolicySource().policies()).isEmpty(); + assertThat(content.realmPolicySource().canonicalBytes()) + .containsExactly(content.snapshotBytes("REALM_POLICY")); + assertThat(content.assetSource().binding()).isEqualTo(selected); + assertThat(content.assetSource().inheritedCommitId()).isNull(); + assertThat(content.assetSource().genesisReceiptId()).isEqualTo(GENESIS); + assertThat(content.assetSource().items()).isEmpty(); + assertThat(content.assetSource().canonicalBytes()) + .containsExactly(content.snapshotBytes("ASSET")); + assertThat(content.brandingSource().binding()).isEqualTo(selected); + assertThat(content.brandingSource().inheritedCommitId()).isNull(); + assertThat(content.brandingSource().genesisReceiptId()).isEqualTo(GENESIS); + assertThat(content.brandingSource().items()).isEmpty(); + assertThat(content.brandingSource().canonicalBytes()) + .containsExactly(content.snapshotBytes("BRANDING")); assertThat(content.gameplaySource().binding()).isEqualTo(selected); assertThat(content.templateConfigSource().binding()).isEqualTo(selected); assertThatThrownBy(() -> content.snapshotBytes("UNKNOWN")) @@ -103,7 +123,9 @@ void rejectsChangedSelectedBindingEvenWhenInnerAndOuterHashesAreRecomputed() { var scope = scope(Owner.AUTOMATION_SCRIPTING, selected, INTAKE); List altered = snapshots(selected); altered.set( - 0, new FamilySnapshot("COMMAND", opaqueSnapshot("COMMAND", substituted, "changed"))); + 0, + new FamilySnapshot( + "COMMAND", SelectedOwnerIntakeSourceTestFixtures.snapshot("COMMAND", substituted))); byte[] forged = encode(scope, altered); assertInvalid(forged, scope, digest(forged)); @@ -115,7 +137,10 @@ void rejectsFamilyChangesAgainstThePreviouslyExpectedOuterDigest() { var scope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); byte[] original = encode(scope, snapshots(selected)); List altered = snapshots(selected); - altered.set(0, new FamilySnapshot("COMMAND", opaqueSnapshot("COMMAND", selected, "changed"))); + altered.set( + 0, + new FamilySnapshot( + "COMMAND", SelectedOwnerIntakeSourceTestFixtures.snapshot("COMMAND", selected, 1))); byte[] changed = encode(scope, altered); assertInvalid(changed, scope, digest(original)); @@ -201,6 +226,50 @@ void requiresTextualBindingFieldsAndTypedGameplayAndTemplateSnapshots() { assertInvalid(encode(scope, invalidTemplate), scope, null); } + @Test + void rejectsMalformedTypedCommandPolicyAssetAndBrandingSnapshots() { + DraftCommitBinding selected = binding(COMMIT); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + for (int index : List.of(0, 1, 2, 4)) { + List invalid = new ArrayList<>(snapshots(selected)); + FamilySnapshot original = invalid.get(index); + String field = index == 0 ? "definitions" : index == 1 ? "policies" : "items"; + String malformed = + new String(original.bytes(), StandardCharsets.UTF_8) + .replaceFirst("\"" + field + "\":\\[\\]", "\"" + field + "\":{}"); + invalid.set( + index, new FamilySnapshot(original.family(), malformed.getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, invalid), scope, null); + } + } + + @Test + void rejectsChangedTypedSourceBindingWhenEnvelopeDigestsAreRecomputed() { + DraftCommitBinding selected = binding(COMMIT); + DraftCommitBinding substituted = binding(id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + var scope = scope(Owner.AUTOMATION_SCRIPTING, selected, INTAKE); + for (int index : List.of(0, 1, 2, 4)) { + List altered = new ArrayList<>(snapshots(selected)); + FamilySnapshot original = altered.get(index); + String changed = + new String(original.bytes(), StandardCharsets.UTF_8) + .replace(escaped(selected.canonicalJson()), escaped(substituted.canonicalJson())) + .replace(selected.digest(), substituted.digest()); + altered.set( + index, new FamilySnapshot(original.family(), changed.getBytes(StandardCharsets.UTF_8))); + assertInvalid(encode(scope, altered), scope, null); + } + } + + @Test + void rejectsOpaqueSelectedGameDesignRevisionWithOtherwiseTypedSnapshotEnvelope() { + DraftCommitBinding selected = binding(COMMIT, "{\"source\":1}"); + var scope = scope(Owner.ENTITY_MANAGEMENT, selected, INTAKE); + List typedSnapshots = snapshots(selected); + + assertInvalid(encode(scope, typedSnapshots), scope, null); + } + @Test void rejectsUnknownOrderDuplicateMissingTruncatedTrailingAndOversizedFrames() { DraftCommitBinding selected = binding(COMMIT); @@ -253,7 +322,7 @@ private static List snapshots(DraftCommitBinding selected) { switch (family) { case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); case "TEMPLATE_CONFIG" -> template.canonicalBytes(); - default -> opaqueSnapshot(family, selected, "synthetic-" + family); + default -> SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); }; result.add(new FamilySnapshot(family, bytes)); } @@ -276,6 +345,10 @@ private static byte[] opaqueSnapshot(String family, DraftCommitBinding selected, .getBytes(StandardCharsets.UTF_8); } + private static String escaped(String value) { + return value.replace("\\", "\\\\").replace("\"", "\\\""); + } + private static byte[] encode( SelectedOwnerIntakeSourceReadScope scope, List snapshots) { return encode(scope, snapshots, null, Map.of(), null); @@ -315,6 +388,10 @@ private static SelectedOwnerIntakeSourceReadScope scope( } private static DraftCommitBinding binding(UUID commitId) { + return binding(commitId, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); + } + + private static DraftCommitBinding binding(UUID commitId, String revisionPayload) { return DraftCommitBinding.create( new DraftCommitBinding.TargetProof( TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"), @@ -323,7 +400,7 @@ private static DraftCommitBinding binding(UUID commitId) { "base-commit-0", List.of( new DraftCommitBinding.RevisionPayload( - "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + "0", REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, revisionPayload)), List.of( new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java index 5dde9740a8..1adbf6647b 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java @@ -6,7 +6,6 @@ import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; import java.io.ByteArrayOutputStream; -import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.UUID; @@ -40,7 +39,8 @@ class SelectedOwnerIntakeSourceProtoCodecTest { @Test void roundTripsBothOwnerRequestsAndCompleteSourceContent() { - DraftCommitBinding selected = binding(COMMIT, "{}"); + DraftCommitBinding selected = + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()); for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { var request = request(owner, selected); var wireRequest = SelectedOwnerIntakeSourceProtoCodec.toRequest(request); @@ -59,7 +59,10 @@ void roundTripsBothOwnerRequestsAndCompleteSourceContent() { @Test void rejectsChangedSchemaNamespaceCorrelationReaderPurposeScopeAndDigest() { - var request = request(Owner.ENTITY_MANAGEMENT, binding(COMMIT, "{}")); + var request = + request( + Owner.ENTITY_MANAGEMENT, + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())); var wire = SelectedOwnerIntakeSourceProtoCodec.toRequest(request); assertInvalidRequest(wire.toBuilder().setSchemaVersion(2).build()); @@ -74,7 +77,10 @@ void rejectsChangedSchemaNamespaceCorrelationReaderPurposeScopeAndDigest() { @Test void requiresTheFullUnchangedRequestEchoBeforeInspectingContent() { - var request = request(Owner.AUTOMATION_SCRIPTING, binding(COMMIT, "{}")); + var request = + request( + Owner.AUTOMATION_SCRIPTING, + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())); var content = content(request.scope(), 0); var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, content); List> substitutions = @@ -104,7 +110,10 @@ void requiresTheFullUnchangedRequestEchoBeforeInspectingContent() { @Test void rejectsUnknownOuterAndNestedFields() { - var request = request(Owner.ENTITY_MANAGEMENT, binding(COMMIT, "{}")); + var request = + request( + Owner.ENTITY_MANAGEMENT, + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())); var wireRequest = SelectedOwnerIntakeSourceProtoCodec.toRequest(request); var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, content(request.scope(), 0)); @@ -132,7 +141,10 @@ void rejectsUnknownOuterAndNestedFields() { @Test void rejectsContentDigestAndScopeSubstitution() { - var request = request(Owner.ENTITY_MANAGEMENT, binding(COMMIT, "{}")); + var request = + request( + Owner.ENTITY_MANAGEMENT, + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())); var original = content(request.scope(), 0); var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, original); @@ -172,7 +184,10 @@ void rejectsContentDigestAndScopeSubstitution() { @Test void admitsContentAboveDefaultGrpcMessageSizeAndRejectsOversizedWireEnvelopes() { - var request = request(Owner.AUTOMATION_SCRIPTING, binding(COMMIT, "{}")); + var request = + request( + Owner.AUTOMATION_SCRIPTING, + binding(COMMIT, SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload())); var largeContent = content(request.scope(), 6_500_000); var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, largeContent); assertThat(response.getSerializedSize()).isGreaterThan(4 * 1024 * 1024); @@ -234,12 +249,8 @@ private static SelectedOwnerIntakeSourceContent content( case "GAMEPLAY_RULE" -> gameplay.canonicalBytes(); case "TEMPLATE_CONFIG" -> template.canonicalBytes(); default -> - opaqueSnapshot( - family, - selected, - family.equals("COMMAND") - ? "x".repeat(largeCommandMarkerSize) - : "synthetic-" + family); + SelectedOwnerIntakeSourceTestFixtures.snapshot( + family, selected, family.equals("COMMAND") ? largeCommandMarkerSize : 0); }; frame(out, family); frame(out, snapshot); @@ -250,22 +261,6 @@ private static SelectedOwnerIntakeSourceContent content( encoded, scope, DraftAuthorizationFenceBinding.digest(encoded)); } - private static byte[] opaqueSnapshot(String family, DraftCommitBinding selected, String marker) { - return GameplayRuleManifest.canonical( - Map.of( - "schema", - "synthetic-test-only/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "family", - family, - "marker", - marker)) - .getBytes(StandardCharsets.UTF_8); - } - private static DraftCommitBinding binding(UUID commitId, String payload) { return DraftCommitBinding.create( new DraftCommitBinding.TargetProof( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java new file mode 100644 index 0000000000..63f6e6ff59 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceTestFixtures.java @@ -0,0 +1,84 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; + +/** Synthetic canonical typed source snapshots for selected-owner Common tests. */ +public final class SelectedOwnerIntakeSourceTestFixtures { + private static final UUID GENESIS = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final String GENESIS_DIGEST = "sha256:" + "a".repeat(64); + + private SelectedOwnerIntakeSourceTestFixtures() {} + + public static byte[] snapshot(String family, DraftCommitBinding selected) { + return snapshot(family, selected, 0); + } + + /** Canonical delete of a synthetic command for otherwise inert selected-source bindings. */ + public static String selectedRevisionPayload() { + return CommandSource.deletePayload("synthetic-fixture-command"); + } + + /** Uses a valid, oversized command field when the transport test needs a large response body. */ + public static byte[] snapshot( + String family, DraftCommitBinding selected, int largeCommandFieldSize) { + return switch (family) { + case "COMMAND" -> command(selected, largeCommandFieldSize).canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> new AssetSnapshot(selected, "0", null, GENESIS, List.of()).canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, GENESIS, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> gameplay(selected).canonicalBytes(); + case "TEMPLATE_CONFIG" -> + new TemplateConfigSourceSnapshot(selected, "0", null, GENESIS, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); + }; + } + + private static CommandSnapshot command(DraftCommitBinding selected, int largeCommandFieldSize) { + if (largeCommandFieldSize < 0) + throw new IllegalArgumentException("Command field size must be nonnegative"); + List definitions = + largeCommandFieldSize == 0 + ? List.of() + : List.of( + new CommandSource.Definition( + "synthetic-large-command", + CommandSource.canonical( + Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry("commandId", "synthetic-large-command"), + Map.entry("semanticOwner", "x".repeat(largeCommandFieldSize)), + Map.entry("executionDiscipline", "DURABLE_GAMEPLAY"), + Map.entry("stageRequirement", "NONE"), + Map.entry("promptPolicy", "NEVER"), + Map.entry("actionCategory", "META"), + Map.entry("historyRecordable", false), + Map.entry("aliases", List.of()), + Map.entry("actionTags", List.of()), + Map.entry("effects", List.of()))), + selected.commitId(), + selected.revisions().getFirst().revisionId(), + selected.revisions().getFirst().revisionOrder())); + return new CommandSnapshot(selected, "0", null, GENESIS_DIGEST, definitions); + } + + private static GameplayRuleSelectedSource gameplay(DraftCommitBinding selected) { + return new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", selected.canonicalJson(), + "bindingDigest", selected.digest(), + "sourceEpoch", "0", + "inheritedCommitId", "", + "genesisReceiptId", GENESIS.toString(), + "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", List.of()))); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java index f4158090b4..aca551643e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetApplication.java @@ -4,6 +4,7 @@ import java.util.Objects; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; /** Exact ordinary-source application evidence, composed into one control-plane owner result. */ diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java index e6fc02b7e2..0c174c79b3 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshot.java @@ -1,12 +1,12 @@ package net.firedevops.firemud.gamedesign.publication; -import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item; +import net.firedevops.firemud.common.gamedesign.CommandSource; /** Ordinary selected source only; no total inventory or template/branding completeness claim. */ public record AssetSnapshot( @@ -16,153 +16,46 @@ public record AssetSnapshot( UUID genesisReceiptId, List items) { public AssetSnapshot { - Objects.requireNonNull(binding); - Objects.requireNonNull(genesisReceiptId); - if (!sourceEpoch.matches("0|[1-9][0-9]*") || new UUID(0, 0).equals(genesisReceiptId)) - throw new IllegalArgumentException("Exact ordinary asset source epoch and genesis required"); - items = List.copyOf(items); - new AssetSource.Snapshot(binding, items.stream().map(Item::reference).toList()); - var ordered = - items.stream() - .sorted( - java.util.Comparator.comparing( - item -> item.reference().usageKey(), - (String left, String right) -> - java.util.Arrays.compareUnsigned( - left.getBytes(StandardCharsets.UTF_8), - right.getBytes(StandardCharsets.UTF_8)))) - .toList(); - if (!items.equals(ordered)) - throw new IllegalArgumentException("Ordinary asset items must be in canonical key order"); + var value = + new net.firedevops.firemud.common.gamedesign.AssetSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptId, items); + items = value.items(); } - public record Item( - AssetSource.Reference reference, String contentType, String contentDigest, long byteSize) { - public Item { - Objects.requireNonNull(reference); - if (contentType == null - || contentType.isBlank() - || contentType.codePointCount(0, contentType.length()) > 100 - || contentDigest == null - || !contentDigest.matches("sha256:[0-9a-f]{64}") - || byteSize < 0) - throw new IllegalArgumentException("Exact ordinary asset byte metadata required"); - } - - Map object() { - var r = reference; - return Map.ofEntries( - Map.entry("family", r.family()), - Map.entry("role", r.role()), - Map.entry("usageKey", r.usageKey()), - Map.entry("assetRowId", r.assetRowId()), - Map.entry("requiredness", r.requiredness().name()), - Map.entry("sourceBindingJson", r.sourceBinding().canonicalJson()), - Map.entry("sourceBindingDigest", r.sourceBinding().digest()), - Map.entry("revisionOrder", r.revisionOrder()), - Map.entry("revisionId", r.revisionId().toString()), - Map.entry("contentType", contentType), - Map.entry("contentDigest", contentDigest), - Map.entry("byteSize", Long.toString(byteSize))); - } + @Override + public List items() { + return List.copyOf(items); } public String canonicalJson() { - return CommandSource.canonical( - Map.of( - "schema", - "game-design-ordinary-asset-source-snapshot/v1", - "bindingJson", - binding.canonicalJson(), - "bindingDigest", - binding.digest(), - "sourceEpoch", - sourceEpoch, - "inheritedCommitId", - inheritedCommitId == null ? "" : inheritedCommitId.toString(), - "genesisReceiptId", - genesisReceiptId.toString(), - "items", - items.stream().map(Item::object).toList())); + return shared().canonicalJson(); } public byte[] canonicalBytes() { - return canonicalJson().getBytes(StandardCharsets.UTF_8); + return shared().canonicalBytes(); } public String digest() { - return CommandSource.sha256(canonicalBytes()); + return shared().digest(); } public static AssetSnapshot fromStored(String json) { - var root = CommandSource.tree(json); - CommandSource.requireStoredFields( - root, - "schema", - "bindingJson", - "bindingDigest", - "sourceEpoch", - "inheritedCommitId", - "genesisReceiptId", - "items"); - if (!"game-design-ordinary-asset-source-snapshot/v1" - .equals(CommandSource.requiredStoredText(root, "schema")) - || !root.path("items").isArray()) - throw new IllegalArgumentException("Unsupported ordinary asset snapshot"); - var binding = - DraftCommitBinding.fromStored( - CommandSource.requiredStoredText(root, "bindingJson"), - CommandSource.requiredStoredText(root, "bindingDigest")); - var items = new java.util.ArrayList(); - for (var node : root.path("items")) { - CommandSource.requireStoredFields( - node, - "family", - "role", - "usageKey", - "assetRowId", - "requiredness", - "sourceBindingJson", - "sourceBindingDigest", - "revisionOrder", - "revisionId", - "contentType", - "contentDigest", - "byteSize"); - if (!AssetSource.FAMILY.equals(CommandSource.requiredStoredText(node, "family")) - || !AssetSource.ROLE.equals(CommandSource.requiredStoredText(node, "role"))) - throw new IllegalArgumentException("Unsupported ordinary source family or role"); - var reference = - new AssetSource.Reference( - CommandSource.requiredStoredText(node, "usageKey"), - CommandSource.requiredStoredText(node, "assetRowId"), - AssetSource.Requiredness.valueOf( - CommandSource.requiredStoredText(node, "requiredness")), - DraftCommitBinding.fromStored( - CommandSource.requiredStoredText(node, "sourceBindingJson"), - CommandSource.requiredStoredText(node, "sourceBindingDigest")), - CommandSource.requiredStoredText(node, "revisionOrder"), - UUID.fromString(CommandSource.requiredStoredText(node, "revisionId"))); - items.add( - new Item( - reference, - CommandSource.requiredStoredText(node, "contentType"), - CommandSource.requiredStoredText(node, "contentDigest"), - Long.parseLong(CommandSource.requiredStoredText(node, "byteSize")))); - } - if (!root.path("inheritedCommitId").isTextual()) - throw new IllegalArgumentException("Stored inherited commit must be text"); - String inherited = root.path("inheritedCommitId").textValue(); - var result = - new AssetSnapshot( - binding, - CommandSource.requiredStoredText(root, "sourceEpoch"), - inherited.isEmpty() ? null : UUID.fromString(inherited), - UUID.fromString(CommandSource.requiredStoredText(root, "genesisReceiptId")), - items); - if (!result.canonicalJson().equals(json)) - throw new IllegalArgumentException("Noncanonical ordinary asset snapshot"); - return result; + return fromShared(net.firedevops.firemud.common.gamedesign.AssetSnapshot.fromStored(json)); + } + + public net.firedevops.firemud.common.gamedesign.AssetSnapshot shared() { + return new net.firedevops.firemud.common.gamedesign.AssetSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptId, items); + } + + public static AssetSnapshot fromShared( + net.firedevops.firemud.common.gamedesign.AssetSnapshot value) { + return new AssetSnapshot( + value.binding(), + value.sourceEpoch(), + value.inheritedCommitId(), + value.genesisReceiptId(), + value.items()); } public record Genesis(TargetProof target, UUID receiptId, String creationTransactionId) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java index f734179ca8..74a9f5bcbc 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java @@ -10,6 +10,8 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import org.jooq.DSLContext; import org.jooq.Record; @@ -116,7 +118,7 @@ public Optional apply(DraftCommitBinding binding) { throw new IllegalStateException("ASSET_SOURCE_EPOCH_CONFLICT"); UUID inherited = head.get("visible_commit_id", UUID.class); requirePreviousFence(binding.target(), inherited); - List previous = + List previous = inherited == null ? List.of() : readSnapshot(binding.target(), inherited).orElseThrow().items(); @@ -137,7 +139,7 @@ public Optional apply(DraftCommitBinding binding) { == null) throw new IllegalStateException("ASSET_SOURCE_ROW_UNAVAILABLE"); }); for (var mutation : mutations) { - AssetSnapshot.Item item = + net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item item = mutation.operation() == AssetSource.OperationKind.UPSERT ? qualify( new AssetSource.Reference( @@ -168,7 +170,11 @@ public Optional apply(DraftCommitBinding binding) { item == null ? null : item.byteSize()); } var references = - AssetSource.replay(previous.stream().map(AssetSnapshot.Item::reference).toList(), binding) + AssetSource.replay( + previous.stream() + .map(net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item::reference) + .toList(), + binding) .references(); var snapshot = new AssetSnapshot( @@ -227,7 +233,7 @@ public AssetSnapshot captureSynchronized(DraftCommitBinding binding) { } else { var items = inherited == null - ? List.of() + ? List.of() : readSnapshot(binding.target(), inherited).orElseThrow().items(); snapshot = new AssetSnapshot( @@ -428,7 +434,8 @@ private Optional application(DraftCommitBinding binding) { return Optional.of(result); } - private AssetSnapshot.Item qualify(AssetSource.Reference reference, boolean lock) { + private net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item qualify( + AssetSource.Reference reference, boolean lock) { var target = reference.sourceBinding().target(); var row = dsl.fetchOne( @@ -441,7 +448,7 @@ private AssetSnapshot.Item qualify(AssetSource.Reference reference, boolean lock || row.get("data", byte[].class) == null) throw new IllegalStateException("ASSET_SOURCE_EXACT_BYTES_UNAVAILABLE"); byte[] bytes = row.get("data", byte[].class); - return new AssetSnapshot.Item( + return new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( reference, row.get("content_type", String.class), CommandSource.sha256(bytes), diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java index d6244ccae3..958612cfc6 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceApplication.java @@ -4,6 +4,7 @@ import java.util.Objects; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.BrandingSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; /** Exact branding-source application evidence, composed into one control-plane owner result. */ diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java index c1914c7cb3..8c2e3db97f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java @@ -10,6 +10,8 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import org.jooq.DSLContext; import org.jooq.Record; @@ -120,7 +122,7 @@ public Optional apply(DraftCommitBinding binding) { throw new IllegalStateException("BRANDING_SOURCE_EPOCH_CONFLICT"); UUID inherited = head.get("visible_commit_id", UUID.class); requirePreviousFence(binding.target(), inherited); - List previous = + List previous = inherited == null ? List.of() : readSnapshot(binding.target(), inherited).orElseThrow().items(); @@ -141,7 +143,7 @@ public Optional apply(DraftCommitBinding binding) { == null) throw new IllegalStateException("BRANDING_SOURCE_ROW_UNAVAILABLE"); }); for (var mutation : mutations) { - BrandingSourceSnapshot.Item item = + net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item item = mutation.operation() == BrandingSource.OperationKind.UPSERT ? qualify( new BrandingSource.Reference( @@ -175,7 +177,12 @@ public Optional apply(DraftCommitBinding binding) { } var references = BrandingSource.replay( - previous.stream().map(BrandingSourceSnapshot.Item::reference).toList(), binding) + previous.stream() + .map( + net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item + ::reference) + .toList(), + binding) .references(); var snapshot = new BrandingSourceSnapshot( @@ -234,7 +241,7 @@ public BrandingSourceSnapshot captureSynchronized(DraftCommitBinding binding) { } else { var items = inherited == null - ? List.of() + ? List.of() : readSnapshot(binding.target(), inherited).orElseThrow().items(); snapshot = new BrandingSourceSnapshot( @@ -372,7 +379,8 @@ private Optional application(DraftCommitBinding bindi return Optional.of(result); } - private BrandingSourceSnapshot.Item qualify(BrandingSource.Reference reference, boolean lock) { + private net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item qualify( + BrandingSource.Reference reference, boolean lock) { var target = reference.sourceBinding().target(); var row = dsl.fetchOne( @@ -385,7 +393,7 @@ private BrandingSourceSnapshot.Item qualify(BrandingSource.Reference reference, || row.get("data", byte[].class) == null) throw new IllegalStateException("BRANDING_SOURCE_EXACT_BYTES_UNAVAILABLE"); byte[] bytes = row.get("data", byte[].class); - return new BrandingSourceSnapshot.Item( + return new net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item( reference, row.get("content_type", String.class), CommandSource.sha256(bytes), diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java index a683ec1cd6..3d830052d3 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceSnapshot.java @@ -1,12 +1,14 @@ package net.firedevops.firemud.gamedesign.publication; -import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item; +import net.firedevops.firemud.common.gamedesign.CommandSource; /** Branding selected source only; no total inventory or template completeness claim. */ public record BrandingSourceSnapshot( @@ -16,166 +18,51 @@ public record BrandingSourceSnapshot( UUID genesisReceiptId, List items) { public BrandingSourceSnapshot { - Objects.requireNonNull(binding); - Objects.requireNonNull(genesisReceiptId); - if (!sourceEpoch.matches("0|[1-9][0-9]*") || new UUID(0, 0).equals(genesisReceiptId)) - throw new IllegalArgumentException("Exact branding asset source epoch and genesis required"); - items = List.copyOf(items); - new BrandingSource.Snapshot(binding, items.stream().map(Item::reference).toList()); - var ordered = - items.stream() - .sorted( - java.util.Comparator.comparing( - item -> item.reference().usageKey(), - (String left, String right) -> - java.util.Arrays.compareUnsigned( - left.getBytes(StandardCharsets.UTF_8), - right.getBytes(StandardCharsets.UTF_8)))) - .toList(); - if (!items.equals(ordered)) - throw new IllegalArgumentException("Branding asset items must be in canonical key order"); + var value = + new net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptId, items); + items = value.items(); } - public record Item( - BrandingSource.Reference reference, String contentType, String contentDigest, long byteSize) { - public Item { - Objects.requireNonNull(reference); - if (contentType == null - || contentType.isBlank() - || contentType.codePointCount(0, contentType.length()) > 100 - || contentDigest == null - || !contentDigest.matches("sha256:[0-9a-f]{64}") - || byteSize < 0) - throw new IllegalArgumentException("Exact branding asset byte metadata required"); - } - - Map object() { - var r = reference; - return Map.ofEntries( - Map.entry("family", r.family()), - Map.entry("role", r.role().name()), - Map.entry("usageKey", r.usageKey()), - Map.entry("assetRowId", r.assetRowId()), - Map.entry("requiredness", r.requiredness().name()), - Map.entry("sourceBindingJson", r.sourceBinding().canonicalJson()), - Map.entry("sourceBindingDigest", r.sourceBinding().digest()), - Map.entry("revisionOrder", r.revisionOrder()), - Map.entry("revisionId", r.revisionId().toString()), - Map.entry("contentType", contentType), - Map.entry("contentDigest", contentDigest), - Map.entry("byteSize", Long.toString(byteSize))); - } + @Override + public List items() { + return List.copyOf(items); } public String canonicalJson() { - return CommandSource.canonical( - Map.of( - "schema", - "game-design-branding-asset-source-snapshot/v1", - "bindingJson", - binding.canonicalJson(), - "bindingDigest", - binding.digest(), - "sourceEpoch", - sourceEpoch, - "inheritedCommitId", - inheritedCommitId == null ? "" : inheritedCommitId.toString(), - "genesisReceiptId", - genesisReceiptId.toString(), - "roles", - roleDeclarations(), - "items", - items.stream().map(Item::object).toList())); - } - - /** Every role is explicitly declared against actual genesis and selected writer history. */ - public Map roleDeclarations() { - var result = new java.util.TreeMap(); - for (var role : BrandingSource.Role.values()) - result.put( - role.name(), - items.stream().anyMatch(item -> item.reference().role() == role) ? "PRESENT" : "EMPTY"); - return Map.copyOf(result); + return shared().canonicalJson(); } public byte[] canonicalBytes() { - return canonicalJson().getBytes(StandardCharsets.UTF_8); + return shared().canonicalBytes(); } public String digest() { - return CommandSource.sha256(canonicalBytes()); + return shared().digest(); + } + + public Map roleDeclarations() { + return shared().roleDeclarations(); } public static BrandingSourceSnapshot fromStored(String json) { - var root = CommandSource.tree(json); - CommandSource.requireStoredFields( - root, - "schema", - "bindingJson", - "bindingDigest", - "sourceEpoch", - "inheritedCommitId", - "genesisReceiptId", - "roles", - "items"); - if (!"game-design-branding-asset-source-snapshot/v1" - .equals(CommandSource.requiredStoredText(root, "schema")) - || !root.path("items").isArray()) - throw new IllegalArgumentException("Unsupported branding asset snapshot"); - var binding = - DraftCommitBinding.fromStored( - CommandSource.requiredStoredText(root, "bindingJson"), - CommandSource.requiredStoredText(root, "bindingDigest")); - var items = new java.util.ArrayList(); - for (var node : root.path("items")) { - CommandSource.requireStoredFields( - node, - "family", - "role", - "usageKey", - "assetRowId", - "requiredness", - "sourceBindingJson", - "sourceBindingDigest", - "revisionOrder", - "revisionId", - "contentType", - "contentDigest", - "byteSize"); - if (!BrandingSource.FAMILY.equals(CommandSource.requiredStoredText(node, "family"))) - throw new IllegalArgumentException("Unsupported branding source family or role"); - var reference = - new BrandingSource.Reference( - CommandSource.requiredStoredText(node, "usageKey"), - CommandSource.requiredStoredText(node, "assetRowId"), - BrandingSource.Role.valueOf(CommandSource.requiredStoredText(node, "role")), - BrandingSource.Requiredness.valueOf( - CommandSource.requiredStoredText(node, "requiredness")), - DraftCommitBinding.fromStored( - CommandSource.requiredStoredText(node, "sourceBindingJson"), - CommandSource.requiredStoredText(node, "sourceBindingDigest")), - CommandSource.requiredStoredText(node, "revisionOrder"), - UUID.fromString(CommandSource.requiredStoredText(node, "revisionId"))); - items.add( - new Item( - reference, - CommandSource.requiredStoredText(node, "contentType"), - CommandSource.requiredStoredText(node, "contentDigest"), - Long.parseLong(CommandSource.requiredStoredText(node, "byteSize")))); - } - if (!root.path("inheritedCommitId").isTextual()) - throw new IllegalArgumentException("Stored inherited commit must be text"); - String inherited = root.path("inheritedCommitId").textValue(); - var result = - new BrandingSourceSnapshot( - binding, - CommandSource.requiredStoredText(root, "sourceEpoch"), - inherited.isEmpty() ? null : UUID.fromString(inherited), - UUID.fromString(CommandSource.requiredStoredText(root, "genesisReceiptId")), - items); - if (!result.canonicalJson().equals(json)) - throw new IllegalArgumentException("Noncanonical branding asset snapshot"); - return result; + return fromShared( + net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.fromStored(json)); + } + + public net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot shared() { + return new net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptId, items); + } + + public static BrandingSourceSnapshot fromShared( + net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot value) { + return new BrandingSourceSnapshot( + value.binding(), + value.sourceEpoch(), + value.inheritedCommitId(), + value.genesisReceiptId(), + value.items()); } public record Genesis(TargetProof target, UUID receiptId, String creationTransactionId) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java index 65f7993ee8..4bf9e8c8f8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandApplication.java @@ -8,6 +8,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; /** Exact staged command-source application evidence, separate from the combined owner outcome. */ diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java index a4085e12d4..8c014f6c5c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSnapshot.java @@ -1,11 +1,10 @@ package net.firedevops.firemud.gamedesign.publication; -import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.CommandSource; /** Complete effective command set captured at one actual synchronized Draft commit. */ public record CommandSnapshot( @@ -15,16 +14,10 @@ public record CommandSnapshot( String genesisReceiptDigest, List definitions) { public CommandSnapshot { - Objects.requireNonNull(binding, "binding"); - requireCounter(sourceEpoch, "sourceEpoch"); - if (inheritedCommitId != null && new UUID(0, 0).equals(inheritedCommitId)) { - throw new IllegalArgumentException("inheritedCommitId must be non-nil when present"); - } - if (genesisReceiptDigest == null || !genesisReceiptDigest.matches("sha256:[0-9a-f]{64}")) { - throw new IllegalArgumentException("Exact command source genesis receipt digest required"); - } - definitions = List.copyOf(Objects.requireNonNull(definitions, "definitions")); - CommandSource.requireCanonicalDefinitions(definitions); + var value = + new net.firedevops.firemud.common.gamedesign.CommandSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptDigest, definitions); + definitions = value.definitions(); } @Override @@ -33,70 +26,34 @@ public List definitions() { } public String canonicalJson() { - return CommandSource.canonical( - Map.of( - "schema", - CommandSource.SNAPSHOT_SCHEMA, - "bindingJson", - binding.canonicalJson(), - "bindingDigest", - binding.digest(), - "sourceEpoch", - sourceEpoch, - "inheritedCommitId", - inheritedCommitId == null ? "" : inheritedCommitId.toString(), - "genesisReceiptDigest", - genesisReceiptDigest, - "definitions", - CommandSource.tree(CommandSource.definitionsJson(definitions)))); + return shared().canonicalJson(); } public byte[] canonicalBytes() { - return canonicalJson().getBytes(StandardCharsets.UTF_8); + return shared().canonicalBytes(); } public String digest() { - return CommandSource.sha256(canonicalBytes()); + return shared().digest(); } public static CommandSnapshot fromStored(String json) { - var root = CommandSource.tree(json); - CommandSource.requireStoredFields( - root, - "schema", - "bindingJson", - "bindingDigest", - "sourceEpoch", - "inheritedCommitId", - "genesisReceiptDigest", - "definitions"); - if (!CommandSource.SNAPSHOT_SCHEMA.equals(CommandSource.requiredStoredText(root, "schema"))) { - throw new IllegalArgumentException("Unsupported command source snapshot schema"); - } - var inheritedNode = root.get("inheritedCommitId"); - if (inheritedNode == null || !inheritedNode.isTextual()) { - throw new IllegalArgumentException("Stored command source inheritedCommitId must be text"); - } - String inherited = inheritedNode.textValue(); - UUID inheritedCommitId = inherited.isEmpty() ? null : UUID.fromString(inherited); - if (inheritedCommitId != null && !inheritedCommitId.toString().equals(inherited)) { - throw new IllegalArgumentException( - "Stored command source inheritedCommitId must be a canonical UUID"); - } - var result = - new CommandSnapshot( - DraftCommitBinding.fromStored( - CommandSource.requiredStoredText(root, "bindingJson"), - CommandSource.requiredStoredText(root, "bindingDigest")), - CommandSource.requiredStoredText(root, "sourceEpoch"), - inheritedCommitId, - CommandSource.requiredStoredText(root, "genesisReceiptDigest"), - CommandSource.definitionsFromStored(root.get("definitions").toString())); - if (!result.canonicalJson().equals(json)) { - throw new IllegalArgumentException( - "Stored command source snapshot is not exact canonical JSON"); - } - return result; + return fromShared(net.firedevops.firemud.common.gamedesign.CommandSnapshot.fromStored(json)); + } + + public net.firedevops.firemud.common.gamedesign.CommandSnapshot shared() { + return new net.firedevops.firemud.common.gamedesign.CommandSnapshot( + binding, sourceEpoch, inheritedCommitId, genesisReceiptDigest, definitions); + } + + public static CommandSnapshot fromShared( + net.firedevops.firemud.common.gamedesign.CommandSnapshot value) { + return new CommandSnapshot( + value.binding(), + value.sourceEpoch(), + value.inheritedCommitId(), + value.genesisReceiptDigest(), + value.definitions()); } /** Frozen source paired with the actual operation bytes and selected synchronized snapshot. */ @@ -125,10 +82,4 @@ public String digest() { return CommandSource.sha256(canonicalBytes()); } } - - private static void requireCounter(String value, String name) { - if (value == null || !value.matches("0|[1-9][0-9]*")) { - throw new IllegalArgumentException(name + " must be a canonical nonnegative decimal"); - } - } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java index c4678d333b..340659f6c9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java @@ -9,6 +9,11 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; import org.jooq.DSLContext; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java index 0185fdcf60..5b62dc2296 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java @@ -12,6 +12,11 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSnapshot.java index 68b5b4bbfb..09ddfa9b45 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSnapshot.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSnapshot.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java index e4d77b7158..c0c5b3bd9d 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java @@ -10,6 +10,8 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import org.jooq.DSLContext; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java index cb62ef5bbc..9502c171c9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplication.java @@ -7,6 +7,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerOutcome; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.OwnerStatus; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java index af88d5d246..73bf068090 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyGenesis.java @@ -4,6 +4,7 @@ import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; /** Empty new-Draft baseline receipt, distinct from every actual authored commit. */ public record RealmPolicyGenesis(TargetProof target, UUID receiptId, String creationTransactionId) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java index 6dd212cb71..580030fbc9 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import org.jooq.DSLContext; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java index 496d2113a7..fc3732a1c4 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java @@ -11,6 +11,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; /** Immutable internal evidence associating a frozen source set with its actual sealed release. */ public final class RealmPolicyPublishedEvidence { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java index a024a75b5a..b2a643681a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySnapshot.java @@ -1,20 +1,19 @@ package net.firedevops.firemud.gamedesign.publication; import java.io.ByteArrayOutputStream; -import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.Map; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; /** Complete effective source at one synchronized fence, including original revision provenance. */ public record RealmPolicySnapshot( DraftCommitBinding binding, String sourceEpoch, List policies) { public RealmPolicySnapshot { - if (binding == null || sourceEpoch == null || !sourceEpoch.matches("0|[1-9][0-9]*")) { - throw new IllegalArgumentException("Exact source binding and canonical epoch required"); - } - policies = RealmPolicySource.draftOrdered(policies); + var value = + new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( + binding, sourceEpoch, policies); + policies = value.policies(); } @Override @@ -23,41 +22,26 @@ public List policies() { } public String canonicalJson() { - return RealmPolicySource.canonical( - Map.of( - "schema", - "game-design-realm-policy-snapshot/v1", - "bindingJson", - binding.canonicalJson(), - "bindingDigest", - binding.digest(), - "sourceEpoch", - sourceEpoch, - "policies", - RealmPolicySource.tree(RealmPolicySource.policiesJson(policies)))); + return shared().canonicalJson(); } public byte[] canonicalBytes() { - return canonicalJson().getBytes(StandardCharsets.UTF_8); + return shared().canonicalBytes(); } public static RealmPolicySnapshot fromStored(String json) { - var node = RealmPolicySource.tree(json); - RealmPolicySource.fields( - node, "schema", "bindingJson", "bindingDigest", "sourceEpoch", "policies"); - if (!"game-design-realm-policy-snapshot/v1".equals(RealmPolicySource.text(node, "schema"))) { - throw new IllegalArgumentException("Unsupported policy snapshot schema"); - } - var result = - new RealmPolicySnapshot( - DraftCommitBinding.fromStored( - RealmPolicySource.text(node, "bindingJson"), - RealmPolicySource.text(node, "bindingDigest")), - RealmPolicySource.text(node, "sourceEpoch"), - RealmPolicySource.policiesFromStored(node.get("policies").toString())); - if (!result.canonicalJson().equals(json)) - throw new IllegalArgumentException("Policy snapshot bytes changed"); - return result; + return fromShared( + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot.fromStored(json)); + } + + public net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot shared() { + return new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( + binding, sourceEpoch, policies); + } + + public static RealmPolicySnapshot fromShared( + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot value) { + return new RealmPolicySnapshot(value.binding(), value.sourceEpoch(), value.policies()); } /** Frozen source only. No terminal association or PUBLISHED claim is represented here. */ diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java index a68f69c8e1..1c4186d440 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import org.jooq.DSLContext; import org.jooq.Record; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventory.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventory.java index 66b7acc2b1..caf248b132 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventory.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventory.java @@ -11,6 +11,9 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; /** Closed exact Game Design source inventory; it does not export or attest release objects. */ diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadService.java index e917cbfed0..76ea66ce70 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadService.java @@ -12,6 +12,10 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import org.jooq.DSLContext; import org.jooq.Record; @@ -204,7 +208,8 @@ private static List pendingAssets( TargetProof selectedTarget, GameDesignSourceRepository.SynchronizedSources sources) { var pending = new ArrayList(); var usageKeys = new HashSet(); - for (AssetSnapshot.Item item : sources.asset().items()) { + for (net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item item : + sources.asset().items()) { var reference = item.reference(); requireAssetReference(selectedTarget, reference.sourceBinding(), reference.usageKey()); if (reference.requiredness() != AssetSource.Requiredness.REQUIRED @@ -226,7 +231,8 @@ private static List pendingAssets( item.byteSize())); } BrandingSourceSnapshot branding = sources.branding().orElseThrow(); - for (BrandingSourceSnapshot.Item item : branding.items()) { + for (net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item item : + branding.items()) { var reference = item.reference(); requireAssetReference(selectedTarget, reference.sourceBinding(), reference.usageKey()); if (reference.requiredness() != BrandingSource.Requiredness.REQUIRED diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociation.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociation.java index 4ec94a53b1..39eecd5852 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociation.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociation.java @@ -6,6 +6,7 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java index 52dac9b2eb..7ce96b1035 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; import org.jooq.DSLContext; import org.jooq.Record; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java index d5768c2a94..eef2edd437 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceSnapshot.java @@ -7,6 +7,7 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository.AppliedEpoch; /** Actual template wiring history only; no Game Logic receipt or total-release completeness. */ diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java index 105ccf2720..b30d4e7a62 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java @@ -13,6 +13,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import org.jooq.DSLContext; import org.jooq.Record; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index 925e7f2314..f77d30f8ea 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java @@ -9,9 +9,9 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; -import net.firedevops.firemud.gamedesign.publication.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index bf26a6fce1..4d4c1ae7ce 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -6,6 +6,7 @@ import java.util.UUID; import java.util.function.Supplier; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; @@ -19,7 +20,6 @@ import net.firedevops.firemud.gamedesign.model.PublishType; import net.firedevops.firemud.gamedesign.model.VersionAssetArtifactState; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.publication.AssetSource; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java index bd9a662702..01ca5c9f71 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java @@ -42,6 +42,7 @@ import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyGrpcCodec; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; @@ -58,7 +59,6 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; -import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository; diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java index eae553564d..1f3d784a53 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -10,17 +10,17 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.publication.AssetSource; -import net.firedevops.firemud.gamedesign.publication.BrandingSource; import net.firedevops.firemud.gamedesign.publication.BrandingSourceRepository; -import net.firedevops.firemud.gamedesign.publication.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; -import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; @@ -326,7 +326,7 @@ private DraftCommitBinding binding( if (payloads[i].contains("\"revisionKind\":\"COMMAND_DEFINITION\"")) scopes.add(CommandSource.SCOPE); if (payloads[i].contains("\"revisionKind\":\"REALM_ENTRY_POLICY\"")) - scopes.add(net.firedevops.firemud.gamedesign.publication.RealmPolicySource.SCOPE); + scopes.add(net.firedevops.firemud.common.gamedesign.RealmPolicySource.SCOPE); } var units = scopes.stream() diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java index 2bdf532768..5ae35df158 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourceCommitPostgresIntegrationTest.java @@ -30,6 +30,7 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -38,7 +39,6 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; -import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.test.TestContainerImages; @@ -1163,7 +1163,7 @@ private Local local(String maximumMigration) { .recordFreshGenesis(historicalTarget); new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(dsl) .enrollNewDraftGenesis( - new net.firedevops.firemud.gamedesign.publication.CommandSource + new net.firedevops.firemud.common.gamedesign.CommandSource .NewDraftGenesisReceipt( historicalTarget, policy.receiptId(), diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java index 5575c90193..b06a05fdea 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -14,16 +14,16 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.publication.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; -import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation; diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java index c7e35cf132..0b1142f1ee 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java @@ -34,6 +34,7 @@ import net.firedevops.firemud.common.authoring.GameDesignDraftTerminalReadClient; import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationClient; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; @@ -60,7 +61,6 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadGrpcService; import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; -import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; import net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicIntakeCommandService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index ee33a2aebb..42af404011 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -67,9 +67,12 @@ import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.AssetSource; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; @@ -124,12 +127,9 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.mapper.VersionMapper; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.publication.AssetSource; import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadGrpcService; import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; -import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; -import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventoryReadService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftControlPlaneDigest; diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java index fc86741d1d..22b73ae1a8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java @@ -14,6 +14,10 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; @@ -24,14 +28,10 @@ import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.publication.AssetSource; import net.firedevops.firemud.gamedesign.publication.AssetSourceRepository; -import net.firedevops.firemud.gamedesign.publication.CommandSource; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; -import net.firedevops.firemud.gamedesign.publication.GameplayRuleSource; import net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; -import net.firedevops.firemud.gamedesign.publication.RealmPolicySource; import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java index 78b6c806ce..5bcc27f8dd 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/impl/SelectedAssetExportCandidatePostgresIntegrationTest.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSource; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; @@ -33,7 +34,6 @@ import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.publication.AssetSource; import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; import net.firedevops.firemud.gamedesign.repository.GameRepository; diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java index 9cfcf1c28b..4f54642590 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java @@ -7,6 +7,8 @@ import java.util.List; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; import org.junit.jupiter.api.Test; class AssetSnapshotTest { @@ -15,7 +17,8 @@ void exactTypedSnapshotRoundTripsAndOwnsItsImmutableCollection() { var binding = binding(); var reference = AssetSource.replay(List.of(), binding).references().getFirst(); var item = - new AssetSnapshot.Item(reference, "image/png", CommandSource.sha256(new byte[] {1, 2}), 2); + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[] {1, 2}), 2); var mutable = new ArrayList<>(List.of(item)); var snapshot = new AssetSnapshot(binding, "1", null, UUID.randomUUID(), mutable); mutable.clear(); @@ -42,7 +45,7 @@ void storedSnapshotCannotChangeBoundRequirednessIdentityOrCanonicalRepresentatio null, UUID.randomUUID(), List.of( - new AssetSnapshot.Item( + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( reference, "image/png", CommandSource.sha256(new byte[0]), 0))); String json = snapshot.canonicalJson(); for (String invalid : @@ -55,13 +58,18 @@ void storedSnapshotCannotChangeBoundRequirednessIdentityOrCanonicalRepresentatio .isInstanceOf(IllegalArgumentException.class); } assertThatThrownBy( - () -> new AssetSnapshot.Item(reference, "", CommandSource.sha256(new byte[0]), 0)) + () -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "", CommandSource.sha256(new byte[0]), 0)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> new AssetSnapshot.Item(reference, "image/png", "sha256:00", 0)) + assertThatThrownBy( + () -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", "sha256:00", 0)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> - new AssetSnapshot.Item( + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( reference, "image/png", CommandSource.sha256(new byte[0]), -1)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSourceTest.java index 9b33fff94e..80614e9a3e 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSourceTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSourceTest.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSource; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java index f94af447dc..ef7ac23699 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java @@ -8,6 +8,10 @@ import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import org.junit.jupiter.api.Test; class BrandingSourceTest { @@ -49,7 +53,9 @@ void replayPreservesUntouchedOriginalRevisionAndExplicitRoleDeclarations() { var items = replay.references().stream() .map( - r -> new BrandingSourceSnapshot.Item(r, "image/png", "sha256:" + "a".repeat(64), 1)) + r -> + new net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item( + r, "image/png", "sha256:" + "a".repeat(64), 1)) .toList(); var snapshot = new BrandingSourceSnapshot(changed, "2", original.commitId(), UUID.randomUUID(), items); diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java index a0b68100de..a61b7dfdb5 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import net.firedevops.firemud.common.gamedesign.CommandSource; import org.junit.jupiter.api.Test; class CommandSourceTest { diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java index df3726cff3..e1c9fc20da 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java @@ -14,6 +14,8 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import org.junit.jupiter.api.Test; class RealmPolicyApplicationTest { diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java index a462cd4ee9..2c2acb9d03 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java @@ -10,6 +10,10 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import org.junit.jupiter.api.Test; class TemplateConfigSourceTest { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java index fa9cec4748..5ec5b3b4e6 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java @@ -12,6 +12,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSourceReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java index d936aa3241..233a1123c8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java @@ -15,6 +15,7 @@ import java.util.List; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceProtoCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; @@ -106,7 +107,8 @@ void rejectsChangedRequestFieldsUnknownFieldsAndOversizedWireBeforeOwnerRead() { void returnsExactEchoAndActualCompleteExportForBothOwnerScopes() { var selected = SelectedOwnerIntakeSourceExportTest.binding( - java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), "{}"); + java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), + CommandSource.deletePayload("absent-command")); for (Owner ownerType : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { var scope = SelectedOwnerIntakeSourceExportTest.scope(ownerType, selected); var export = @@ -139,7 +141,8 @@ void deniesAbsentOrMismatchedExportAndSanitizesOwnerFailures() { SelectedOwnerIntakeSourceExportTest.scope( Owner.ENTITY_MANAGEMENT, SelectedOwnerIntakeSourceExportTest.binding( - java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), "{}")); + java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), + CommandSource.deletePayload("absent-command"))); var request = request(scope); var missingOwner = mock(GameDesignSelectedOwnerIntakeSourceReadService.class); @@ -150,7 +153,8 @@ void deniesAbsentOrMismatchedExportAndSanitizesOwnerFailures() { SelectedOwnerIntakeSourceExportTest.scope( Owner.ENTITY_MANAGEMENT, SelectedOwnerIntakeSourceExportTest.binding( - java.util.UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), "{}")); + java.util.UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + CommandSource.deletePayload("absent-command"))); var differentExport = SelectedOwnerIntakeSourceExport.create( differentScope, @@ -189,7 +193,8 @@ private static Collector invoke( private static SelectedOwnerIntakeSourceRequest request(Owner owner) { var selected = SelectedOwnerIntakeSourceExportTest.binding( - java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), "{}"); + java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), + CommandSource.deletePayload("absent-command")); return request(SelectedOwnerIntakeSourceExportTest.scope(owner, selected)); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java index 7ae8cbb3e0..6edb3510ed 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Ability; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Action; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadServiceTest.java index 09ed793be6..56ccdfb035 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftAssetInventoryReadServiceTest.java @@ -20,6 +20,10 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeSettlementEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeOperation; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; @@ -469,7 +473,7 @@ private Fixture withAssets( "0", ordinarySource.revisions().getFirst().revisionId()); var ordinaryItem = - new AssetSnapshot.Item( + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( ordinaryReference, "application/octet-stream", CommandSource.sha256(ordinaryBytes), @@ -494,7 +498,7 @@ private Fixture withAssets( "0", brandingSource.revisions().getFirst().revisionId()); var brandingItem = - new BrandingSourceSnapshot.Item( + new net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item( brandingReference, "image/png", CommandSource.sha256(brandingBytes), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java index 78d5aa8633..7481d9a05f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigestTest.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import org.junit.jupiter.api.Test; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java index dbc1aa9c40..fc3d6a7ab8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java @@ -17,6 +17,7 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java index 15fd9a874c..4fe0d656c0 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java @@ -13,6 +13,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import org.junit.jupiter.api.Test; @@ -30,7 +31,7 @@ class SelectedOwnerIntakeSourceExportTest { @Test void framesTheScopeAndAllSixFamiliesInFixedOrder() { - var selected = binding(COMMIT, "{}"); + var selected = binding(COMMIT, CommandSource.deletePayload("absent-command")); var scope = scope(Owner.ENTITY_MANAGEMENT, selected); var sources = sources(selected, "0"); var export = SelectedOwnerIntakeSourceExport.create(scope, sources); @@ -56,7 +57,7 @@ void framesTheScopeAndAllSixFamiliesInFixedOrder() { @Test void sharedConsumerDecodesExactCompleteExportsForBothOwners() { - var selected = binding(COMMIT, "{}"); + var selected = binding(COMMIT, CommandSource.deletePayload("absent-command")); for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { var scope = scope(owner, selected); var sources = sources(selected, "0"); @@ -86,7 +87,7 @@ void sharedConsumerDecodesExactCompleteExportsForBothOwners() { @Test void contentIsDeterministicAndCanonicalBytesAreDefensivelyExposed() { - var selected = binding(COMMIT, "{}"); + var selected = binding(COMMIT, CommandSource.deletePayload("absent-command")); var first = SelectedOwnerIntakeSourceExport.create( scope(Owner.AUTOMATION_SCRIPTING, selected), sources(selected, "0")); @@ -102,14 +103,16 @@ void contentIsDeterministicAndCanonicalBytesAreDefensivelyExposed() { @Test void rejectsDifferentSelectedBindingAndChangedFamilyContent() { - var selected = binding(COMMIT, "{}"); + var selected = binding(COMMIT, CommandSource.deletePayload("absent-command")); var sources = sources(selected, "0"); assertThatThrownBy( () -> SelectedOwnerIntakeSourceExport.create( scope( Owner.ENTITY_MANAGEMENT, - binding(id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), "{}")), + binding( + id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + CommandSource.deletePayload("absent-command"))), sources)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("COMMAND"); @@ -125,7 +128,7 @@ void rejectsDifferentSelectedBindingAndChangedFamilyContent() { @Test void missingBrandingOrTemplateSourceIsNotAnEmptyFamily() { - var selected = binding(COMMIT, "{}"); + var selected = binding(COMMIT, CommandSource.deletePayload("absent-command")); var complete = sources(selected, "0"); var missingBranding = new GameDesignSourceRepository.SynchronizedSources( diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java index a3612ff0d0..5fbdea3f93 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java @@ -31,6 +31,11 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; @@ -266,7 +271,7 @@ private static Fixture fixture(Owner owner) { "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.GAME_DESIGN_CONTROL_PLANE, - "{}")), + CommandSource.deletePayload("synthetic-fixture-command"))), List.of( new DraftCommitBinding.AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, @@ -370,44 +375,47 @@ private static SelectedOwnerIntakeSourceContent sourceContent( } private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { - if ("GAMEPLAY_RULE".equals(family)) { - return new GameplayRuleSelectedSource( - GameplayRuleManifest.canonical( - Map.of( - "schema", - "game-design-gameplay-rule-source-snapshot/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "sourceEpoch", - "0", - "inheritedCommitId", - "", - "genesisReceiptId", - "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", - "manifestJson", - GameplayRuleManifest.explicitEmpty().canonicalJson(), - "entries", - List.of()))) - .canonicalBytes(); - } - if ("TEMPLATE_CONFIG".equals(family)) { - return new TemplateConfigSourceSnapshot( - selected, "0", null, id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), List.of()) - .canonicalBytes(); - } - return GameplayRuleManifest.canonical( - Map.of( - "schema", - "synthetic-test-only/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "family", - family)) - .getBytes(StandardCharsets.UTF_8); + UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + return switch (family) { + case "COMMAND" -> + new CommandSnapshot( + selected, + "0", + null, + DraftAuthorizationFenceBinding.digest( + "synthetic-world-fixture".getBytes(StandardCharsets.UTF_8)), + List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + genesis.toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "TEMPLATE_CONFIG" -> + new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported selected source fixture family"); + }; } private static SourceEvidence source(SourceKind kind, String scope, String marker) { From 16682dd44e2141a4060ab7cefdea55ea775f1018 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:39:00 +1300 Subject: [PATCH 085/129] Bind Automation source guards to install schema and repair Account proof fixtures --- ...sionProtectionPostgresIntegrationTest.java | 55 ++++- .../V5__selected_empty_source_intake.sql | 194 ++++++++++-------- ...edSourceIntakePostgresIntegrationTest.java | 23 ++- 3 files changed, 177 insertions(+), 95 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index fd7395ee2d..80211c817c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -315,7 +315,18 @@ void rawChangedCaptureAndIncompleteChildrenCannotBecomeProtection() { incomplete .transaction() .executeWithoutResult(status -> insertProtection(incomplete, 11L))) - .hasMessageContaining("incomplete or extra source children"); + .satisfies( + failure -> + assertDatabaseGuardFailure( + failure, + "Admission protection has incomplete or extra source children", + "23514")); + assertThat( + incomplete + .dsl() + .fetchSingle("SELECT count(*) FROM account_start_session_admission_protections") + .get(0, Long.class)) + .isZero(); } @Test @@ -910,11 +921,47 @@ private static String diagnosticIdentifier(String value) { } private static Long sequenceValue(Fixture fixture) { + var sequence = + fixture + .dsl() + .fetchSingle( + "SELECT namespace.nspname AS schema_name, relation.relname AS sequence_name " + + "FROM pg_class relation " + + "JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace " + + "WHERE relation.oid = pg_get_serial_sequence(" + + "format('%I.%I', current_schema(), ?), ?)::regclass", + "account_start_session_admission_protections", + "protection_fence"); return fixture .dsl() - .fetchSingle( - "SELECT last_value FROM account_start_session_admission_protections_protection_fence_seq") - .get(0, Long.class); + .select(DSL.field(DSL.name("last_value"), Long.class)) + .from( + DSL.table( + DSL.name( + sequence.get("schema_name", String.class), + sequence.get("sequence_name", String.class)))) + .fetchSingle(0, Long.class); + } + + private static void assertDatabaseGuardFailure( + Throwable failure, String expectedMessage, String expectedSqlState) { + var visited = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + Throwable cause = failure; + PSQLException databaseFailure = null; + while (cause != null && visited.add(cause)) { + if (cause instanceof PSQLException postgresFailure) { + databaseFailure = postgresFailure; + break; + } + cause = cause.getCause(); + } + assertThat(databaseFailure) + .as("the rejected fixture write must fail at PostgreSQL's database guard") + .isNotNull(); + assertThat(databaseFailure.getSQLState()).isEqualTo(expectedSqlState); + assertThat(databaseFailure.getServerErrorMessage()).isNotNull(); + assertThat(databaseFailure.getServerErrorMessage().getMessage()).contains(expectedMessage); } private static byte[] bytes(String value) { diff --git a/services/automation-scripting-service/src/main/resources/db/migration/V5__selected_empty_source_intake.sql b/services/automation-scripting-service/src/main/resources/db/migration/V5__selected_empty_source_intake.sql index bb20d86f27..e43eb6aa7a 100644 --- a/services/automation-scripting-service/src/main/resources/db/migration/V5__selected_empty_source_intake.sql +++ b/services/automation-scripting-service/src/main/resources/db/migration/V5__selected_empty_source_intake.sql @@ -174,101 +174,119 @@ ON CONFLICT (key_kind, numeric_key) DO NOTHING; /* [jooq ignore stop] */ /* [jooq ignore start] */ -CREATE FUNCTION automation_require_source_numeric_key_unreserved( - requested_kind TEXT, requested_key BIGINT -) RETURNS VOID -LANGUAGE plpgsql -SECURITY DEFINER -SET search_path = pg_catalog, "${serviceSchema}" -AS $$ +DO $automation_empty_source_functions$ DECLARE - retained_claim TEXT; + owner_schema TEXT := current_schema(); BEGIN - IF current_setting('transaction_isolation') <> 'read committed' THEN - RAISE EXCEPTION 'Automation authored-source row writes require READ COMMITTED isolation'; - END IF; - IF requested_key IS NULL OR requested_key <= 0 THEN - RETURN; - END IF; - SELECT claim_kind INTO retained_claim - FROM "${serviceSchema}".automation_empty_source_numeric_key_reservation - WHERE key_kind = requested_kind AND numeric_key = requested_key; - IF retained_claim = 'CANONICAL_EMPTY_SOURCE' THEN - RAISE EXCEPTION 'Automation numeric source key is reserved by an immutable empty-source receipt'; + IF owner_schema IS NULL THEN + RAISE EXCEPTION 'Automation empty-source functions require an explicit installation schema'; END IF; -END; -$$; -CREATE FUNCTION automation_guard_authored_source_row() -RETURNS TRIGGER -LANGUAGE plpgsql -SECURITY DEFINER -SET search_path = pg_catalog, "${serviceSchema}" -AS $$ -DECLARE - old_value JSONB; - new_value JSONB; - old_tenant_key BIGINT; - new_tenant_key BIGINT; - old_version_key BIGINT; - new_version_key BIGINT; -BEGIN - IF TG_OP IN ('UPDATE', 'DELETE') THEN - old_value := to_jsonb(OLD); - old_tenant_key := automation_source_positive_numeric_key(old_value->>'tenant_id'); - old_version_key := automation_source_positive_numeric_key(old_value->>'base_version_id'); - PERFORM automation_require_source_numeric_key_unreserved('TENANT', old_tenant_key); - PERFORM automation_require_source_numeric_key_unreserved('VERSION', old_version_key); - END IF; - IF TG_OP IN ('INSERT', 'UPDATE') THEN - new_value := to_jsonb(NEW); - new_tenant_key := automation_source_positive_numeric_key(new_value->>'tenant_id'); - new_version_key := automation_source_positive_numeric_key(new_value->>'base_version_id'); - -- Do not mutate the allocator table from a source-row trigger. PostgreSQL has already - -- acquired the source table's ROW EXCLUSIVE lock before firing this trigger, while the - -- founding path intentionally locks allocator tables first. A read-only reservation - -- check keeps that global lock order acyclic; new allocations also census every source - -- family while holding the source locks, so unreserved legacy keys cannot be missed. - PERFORM automation_require_source_numeric_key_unreserved('TENANT', new_tenant_key); - PERFORM automation_require_source_numeric_key_unreserved('VERSION', new_version_key); - END IF; - IF TG_OP = 'DELETE' THEN - RETURN OLD; - END IF; - RETURN NEW; -END; -$$; + EXECUTE format($function$ + CREATE FUNCTION %I.automation_require_source_numeric_key_unreserved( + requested_kind TEXT, requested_key BIGINT + ) RETURNS VOID + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + retained_claim TEXT; + BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Automation authored-source row writes require READ COMMITTED isolation'; + END IF; + IF requested_key IS NULL OR requested_key <= 0 THEN + RETURN; + END IF; + SELECT claim_kind INTO retained_claim + FROM %I.automation_empty_source_numeric_key_reservation + WHERE key_kind = requested_kind AND numeric_key = requested_key; + IF retained_claim = 'CANONICAL_EMPTY_SOURCE' THEN + RAISE EXCEPTION 'Automation numeric source key is reserved by an immutable empty-source receipt'; + END IF; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema); -CREATE FUNCTION automation_reject_authored_source_truncate() -RETURNS TRIGGER -LANGUAGE plpgsql -SECURITY DEFINER -SET search_path = pg_catalog, "${serviceSchema}" -AS $$ -BEGIN - IF current_setting('transaction_isolation') <> 'read committed' THEN - RAISE EXCEPTION 'Automation authored-source TRUNCATE requires READ COMMITTED isolation'; - END IF; - IF EXISTS ( - SELECT 1 FROM "${serviceSchema}".automation_empty_source_numeric_key_reservation - WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE' - ) THEN - RAISE EXCEPTION 'Automation authored source TRUNCATE is forbidden after canonical intake'; - END IF; - RETURN NULL; -END; -$$; + EXECUTE format($function$ + CREATE FUNCTION %I.automation_guard_authored_source_row() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + old_value JSONB; + new_value JSONB; + old_tenant_key BIGINT; + new_tenant_key BIGINT; + old_version_key BIGINT; + new_version_key BIGINT; + BEGIN + IF TG_OP IN ('UPDATE', 'DELETE') THEN + old_value := to_jsonb(OLD); + old_tenant_key := automation_source_positive_numeric_key(old_value->>'tenant_id'); + old_version_key := automation_source_positive_numeric_key(old_value->>'base_version_id'); + PERFORM automation_require_source_numeric_key_unreserved('TENANT', old_tenant_key); + PERFORM automation_require_source_numeric_key_unreserved('VERSION', old_version_key); + END IF; + IF TG_OP IN ('INSERT', 'UPDATE') THEN + new_value := to_jsonb(NEW); + new_tenant_key := automation_source_positive_numeric_key(new_value->>'tenant_id'); + new_version_key := automation_source_positive_numeric_key(new_value->>'base_version_id'); + -- Do not mutate the allocator table from a source-row trigger. PostgreSQL has already + -- acquired the source table's ROW EXCLUSIVE lock before firing this trigger, while the + -- founding path intentionally locks allocator tables first. A read-only reservation + -- check keeps that global lock order acyclic; new allocations also census every source + -- family while holding the source locks, so unreserved legacy keys cannot be missed. + PERFORM automation_require_source_numeric_key_unreserved('TENANT', new_tenant_key); + PERFORM automation_require_source_numeric_key_unreserved('VERSION', new_version_key); + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END; + $body$ + $function$, owner_schema, owner_schema); -CREATE FUNCTION automation_reject_empty_source_intake_mutation() -RETURNS TRIGGER -LANGUAGE plpgsql -SECURITY DEFINER -SET search_path = pg_catalog, "${serviceSchema}" -AS $$ -BEGIN - RAISE EXCEPTION 'Automation empty-source intake records are immutable'; + EXECUTE format($function$ + CREATE FUNCTION %I.automation_reject_authored_source_truncate() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Automation authored-source TRUNCATE requires READ COMMITTED isolation'; + END IF; + IF EXISTS ( + SELECT 1 FROM %I.automation_empty_source_numeric_key_reservation + WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE' + ) THEN + RAISE EXCEPTION 'Automation authored source TRUNCATE is forbidden after canonical intake'; + END IF; + RETURN NULL; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.automation_reject_empty_source_intake_mutation() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + BEGIN + RAISE EXCEPTION 'Automation empty-source intake records are immutable'; + END; + $body$ + $function$, owner_schema, owner_schema); END; -$$; +$automation_empty_source_functions$; REVOKE ALL ON FUNCTION automation_require_source_numeric_key_unreserved(TEXT, BIGINT) FROM PUBLIC; REVOKE ALL ON FUNCTION automation_guard_authored_source_row() FROM PUBLIC; diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java index fc29b14fdd..e413ae057f 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java @@ -8,7 +8,6 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; -import java.util.Map; import java.util.UUID; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -48,7 +47,6 @@ void migrateWithRetainedLegacyAuthoredRows() { .locations(MIGRATION_LOCATION) .schemas(schema) .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) .target("3.2") .load() .migrate(); @@ -71,7 +69,6 @@ void migrateWithRetainedLegacyAuthoredRows() { .locations(MIGRATION_LOCATION) .schemas(schema) .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) .load() .migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); @@ -148,6 +145,26 @@ void migrationSeedsLegacyKeysAndGuardsAllThreeAuthoredSourceFamilies() { assertRejected("TRUNCATE TABLE script_patch_base_bindings"); } + @Test + void securityDefinerFunctionsUseTheExactInstalledSchemaInTheirFixedSearchPath() { + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM pg_proc AS p " + + "JOIN pg_namespace AS n ON n.oid = p.pronamespace " + + "WHERE n.nspname = ? " + + "AND p.proname IN (" + + "'automation_require_source_numeric_key_unreserved', " + + "'automation_guard_authored_source_row', " + + "'automation_reject_authored_source_truncate', " + + "'automation_reject_empty_source_intake_mutation') " + + "AND p.prosecdef " + + "AND p.proconfig @> ARRAY[format('search_path=pg_catalog, %I', ?)]", + Integer.class, + schema, + schema)) + .isEqualTo(4); + } + @Test void staleRepeatableReadWritersCannotMissACommittedCanonicalReservation() throws SQLException { try (Connection staleRowWriter = repeatableReadSnapshot()) { From 464dedc52895cb1cc3c4255cc650c7a4cc226457 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:46:58 +1300 Subject: [PATCH 086/129] Disambiguate PostgreSQL guard assertion as throwable --- ...tStartSessionAdmissionProtectionPostgresIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index 80211c817c..3fa4db2fe1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -956,7 +956,7 @@ private static void assertDatabaseGuardFailure( } cause = cause.getCause(); } - assertThat(databaseFailure) + assertThat((Throwable) databaseFailure) .as("the rejected fixture write must fail at PostgreSQL's database guard") .isNotNull(); assertThat(databaseFailure.getSQLState()).isEqualTo(expectedSqlState); From 32cdc878d444f5aee77fec7c82eeed2baaa513c9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 00:48:42 +1300 Subject: [PATCH 087/129] Apply canonical formatting to source guard proof fixtures --- ...tartSessionAdmissionProtectionPostgresIntegrationTest.java | 3 +-- ...ationEmptySelectedSourceIntakePostgresIntegrationTest.java | 4 +--- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index 3fa4db2fe1..86c4bec005 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -930,8 +930,7 @@ private static Long sequenceValue(Fixture fixture) { + "JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace " + "WHERE relation.oid = pg_get_serial_sequence(" + "format('%I.%I', current_schema(), ?), ?)::regclass", - "account_start_session_admission_protections", - "protection_fence"); + "account_start_session_admission_protections", "protection_fence"); return fixture .dsl() .select(DSL.field(DSL.name("last_value"), Long.class)) diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java index e413ae057f..28adae0e52 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java @@ -159,9 +159,7 @@ void securityDefinerFunctionsUseTheExactInstalledSchemaInTheirFixedSearchPath() + "'automation_reject_empty_source_intake_mutation') " + "AND p.prosecdef " + "AND p.proconfig @> ARRAY[format('search_path=pg_catalog, %I', ?)]", - Integer.class, - schema, - schema)) + Integer.class, schema, schema)) .isEqualTo(4); } From fce7b38e8431dd7020cb2b11d98753a0f4f41e4b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 01:47:29 +1300 Subject: [PATCH 088/129] Bind Automation terminal readback to immutable Account source settlement --- .../account-service/api-contracts.md | 4 + .../runtime-and-data.md | 8 +- ...ame-authoring-publishing-and-activation.md | 6 +- ...selected_source_intake_terminal_read.proto | 34 + ...edOwnerIntakeAuthorizationReadService.java | 2 +- ...tSelectedOwnerIntakeSettlementService.java | 303 ++++++++ ...tSelectedOwnerIntakeSourceReadService.java | 5 + ...wnerIntakeSourceReservationRepository.java | 136 +++- ...eWorldClosureAuthorizationReadService.java | 2 +- ...ected_owner_intake_terminal_settlement.sql | 495 +++++++++++++ ...eAuthorizationPostgresIntegrationTest.java | 650 +++++++++++++++++- ...nerIntakeAuthorizationReadServiceTest.java | 6 +- ...ectedOwnerIntakeSettlementServiceTest.java | 506 ++++++++++++++ ...IntakeSourceReservationRepositoryTest.java | 12 + ...ldClosureAuthorizationReadServiceTest.java | 6 +- ...onEmptySelectedSourceIntakeRepository.java | 26 + ...ationEmptySelectedSourceIntakeService.java | 1 + ...lectedSourceIntakeTerminalReadService.java | 80 +++ ...edSourceIntakeTerminalReadGrpcService.java | 53 ++ ...edSourceIntakePostgresIntegrationTest.java | 25 +- ...takeRepositoryPostgresIntegrationTest.java | 43 +- ...tedSourceIntakeServiceIntegrationTest.java | 2 +- ...ionEmptySelectedSourceIntakeValueTest.java | 1 + ...edSourceIntakeTerminalReadServiceTest.java | 253 +++++++ ...tSelectedOwnerIntakeSettlementReceipt.java | 210 ++++++ ...ationEmptySelectedSourceIntakeReceipt.java | 20 +- ...electedSourceIntakeTerminalReadClient.java | 158 +++++ ...ectedSourceIntakeTerminalReadEvidence.java | 95 +++ ...ctedSourceIntakeTerminalReadGrpcCodec.java | 138 ++++ ...ectedOwnerIntakeSettlementReceiptTest.java | 98 +++ .../SelectedOwnerEmptySourceInputsTest.java | 116 ++++ ...ourceIntakeTerminalReadClientMtlsTest.java | 168 +++++ 32 files changed, 3612 insertions(+), 50 deletions(-) create mode 100644 protos/automation-scripting/v1/automation_selected_source_intake_terminal_read.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java create mode 100644 services/account-service/src/main/resources/db/migration/V135__selected_owner_intake_terminal_settlement.sql create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcService.java create mode 100644 services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java rename services/{automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting => common-platform-core/src/main/java/net/firedevops/firemud/common/automation}/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java (97%) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 86017532e8..f2095ecca1 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -114,6 +114,10 @@ The distinct finalized integrity envelope uses `account-entity-intake-authorizat The standalone [`AccountSelectedOwnerIntakeAuthorizationReadService.ReadHeldSelectedOwnerIntakeAuthorization`](../../../../protos/account/v1/selected_owner_intake_authorization_read.proto) reads that original finalized order, not its preliminary reservation. Its closed schema-version-1 request binds namespace, an independent nonzero read correlation distinct from the retained operation/fence/intake request, the exact derived owner reader and retention purpose, and the full original binding bytes/digest. Account authenticates same-namespace Entity or Automation and rejects end-user context before decoding; after decoding, the actual peer must be that binding's exact recipient. An independent writable `READ COMMITTED` transaction locks and compares the original authorization, reservation, creator evidence and complete source participation. Success echoes the entire request unchanged with `held=true`; missing, changed, aborted, malformed, mismatched or unavailable evidence denies. The file-backed mTLS client pins Account, uses a five-second deadline, rejects ambient SQL/synchronization and enforces a separate 24 MiB wire budget without expanding the 16 MiB binding limit. This sampled HELD read cannot create/finalize/settle an order, allocate a replacement identity, renew authority or prove continuous protection through the owner's commit, complete census or a terminal receipt. The unregistered components and their proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +For Automation, Account may settle finalized source participation only after an authenticated exact same-namespace read of the Automation-owned `COMMITTED_EMPTY` terminal for the complete original authorization; the [Automation contract](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) owns its closed request, receipt and retry rules. Account first reads any exact committed settlement independently, then obtains missing terminal evidence outside SQL, commits one immutable settlement under its existing source locks, and performs a separate lookup-only committed readback. Only that exact committed settlement releases this operation's participation, after which both external `HELD` readers deny; historical authorization and terminal recovery remain available without creating fresh authority. Source locks in canonical order precede the reservation, finalized authorization and settlement locks, so a source writer cannot bypass pending participation. Missing, pending, changed, corrupt or ambiguous owner evidence preserves participation; absence or expiry is not an abort. Unregistered construction components do not establish a complete authenticated producer or executed physical proof; see the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + +The immutable Account settlement uses `account-selected-owner-intake-settlement/v1` and the existing byte-length framing and SHA-256 representation. Its fixed frame order is domain, version `1`, complete original authorization bytes and digest, terminal request schema version, namespace, read request UUID, exact Account reader, terminal-read purpose, complete echoed authorization bytes and digest, and complete Automation receipt bytes and digest. Every embedded value must decode canonically and match the same original operation. The complete settlement is bounded to 92,356,608 bytes: two original authorization bounds, one Automation receipt bound, and 64 KiB of framing allowance; it does not widen those embedded bounds. The first terminal-read correlation is retained with the result but is not a new settlement identity: a retry with another valid correlation and identical original binding and owner receipt returns the first settlement byte-for-byte. Changed original binding or owner receipt conflicts without overwriting it. The settlement neither releases another pending operation nor permits preliminary abort of a finalized order; uncertainty remains reconciliation-only. + The separate [`AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.ReadHeldSelectedOwnerWorldClosureAuthorization`](../../../../protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto) permits World to independently verify that exact finalized Entity or Automation order before returning the selected World closure. Its outer recipient is the exact same-namespace World workload, and its closed purpose is respectively `ENTITY_INTAKE_WORLD_CLOSURE_READ` or `AUTOMATION_INTAKE_WORLD_CLOSURE_READ`. The inner original authorization retains its Entity or Automation recipient, retention purpose, operation, fence, intake request, complete content and source evidence unchanged. The request binds schema version 1, namespace, an independent nonzero read correlation, and the full original bytes and digest; success echoes it unchanged with `held=true`. Account authenticates World and rejects end-user context before decoding, then locks and verifies the exact original finalized order and source participation in an independent writable `READ COMMITTED` transaction. The existing Entity/Automation recipient read is not widened. World must obtain and validate this confirmation directly over authenticated Account mTLS outside SQL; caller-forwarded bytes or a digest do not establish Account authorization. The five-second deadline, 24 MiB wire budget and unchanged 16 MiB binding bound apply. This is permission for an exact retained closure read, not an owner census, source-mutation grant, receipt, settlement or continuous-through-commit proof; an unavailable or mismatched confirmation denies the read. The distinct [`AccountSelectedOwnerIntakeSourceReadService.ReadSourceScope`](../../../../protos/account/v1/selected_owner_intake_source_read_service.proto) confirms only the retained preliminary Entity or Automation reservation. Account authenticates the exact configured same-namespace Game Design workload and rejects authenticated end-user context before decoding or storage. The closed schema-version-1 request binds namespace, independent nonzero transport correlation, derived Account reader and closed purpose, and the original scope bytes and digest. Account revalidates its own original creator and source participation in independent transactions around the external registry read; neither a client digest nor peer identity creates a reservation. A successful response echoes the complete request unchanged and confirms only that preliminary scope. Missing, expired, changed, malformed or unavailable evidence denies. The canonical scope remains bounded to 4 MiB; the separately enforced request and response wire budget is 8 MiB, including echo and framing. The file-backed mTLS client pins the Account server, applies a five-second deadline and rejects ambient SQL or synchronization. This standalone method has no finalized-retention branch, supplies no census or owner receipt, and does not register or activate a runtime path. Game Design must finish this authenticated Account confirmation outside SQL before reading or returning any selected source content. diff --git a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md index 12a6292a05..cebe658244 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -39,6 +39,8 @@ The current dry-run and readiness capacity reservations also are not idempotent The current queue consumer has an additional bounded-drain limitation that must remain explicit: `drainWorkItems` and `drainIndexedWorkItemPointers` consume pointers with atomic Redis `LPOP`, so a producer's concurrent `RPUSH` is not discarded by a range/read followed by deletion. The indexed path still uses database-wide `KEYS("automation:queue:*")`, and the current lists have no pointer TTL or maximum-length bound, so the path is not a cluster-safe discovery or retention proof. Durable claim fallback can process pending PostgreSQL rows independently, but it does not establish a reset/rebuild recovery gate. Target enqueue/rebuild must atomically apply `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`, preserve or durably account for unreturned tails and concurrent appends, use an owner-maintained/cursor-based cluster-safe queue index rather than database-wide `KEYS`, and trigger bounded durable re-drive with exact identity/readback before reset-gate release. The two settings remain environment/service configuration (currently `TBD`); no target support claim is valid until each environment supplies validated positive bounds and focused concurrent-drain, truncation/expiry, cluster, and re-drive proof. +The selected-source terminal reader and Account settlement composition are standalone and unregistered construction components; they do not establish complete authenticated owner intake or physical proof. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) owns their code and validation status. Without the exact committed Account settlement, finalized source participation remains pending. + ## Authored Template Source Inventory Automation owns the source inventory declaration schema carried as authored content by a new versioned Game Design `TEMPLATE_CONFIG` source ([closed schema and reference rules](../game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state)). The Automation value schema is `automation-authored-source-inventory/v1` with exactly three required family arrays: `SCRIPT_DEFINITIONS`, `EVENT_BINDINGS`, and `SCRIPT_PATCH_SOURCES`. The current shared value accepts only explicitly authored empty arrays; omitted, null, unknown, malformed, duplicate, trailing, oversized, or nonempty input is rejected. Its canonical RFC 8785 bytes preserve the authored declaration deterministically. This declaration is content only: it is not an owner receipt, source readback, authorization, provenance, or proof of owner completeness, and cannot qualify a publication on its own. Existing `TEMPLATE_CONFIG` schema-version content is not reinterpreted as this declaration. @@ -56,11 +58,13 @@ The authored shape is: } ``` -Script schedule definitions remain derived from script source and are not another authored family. The optional template `automation.scriptPatch` is a separate default selection of one exact patch for the same base version; its absence means no template default and does not establish an empty patch-source inventory. The declaration producer, Automation owner intake/readback, and physical proof remain incomplete; publication must continue to deny where that evidence is unavailable. +Script schedule definitions remain derived from script source and are not another authored family. The optional template `automation.scriptPatch` is a separate default selection of one exact patch for the same base version; its absence means no template default and does not establish an empty patch-source inventory. The declaration producer, full owner census/retention and Account terminal-settlement composition remain incomplete; the standalone terminal reader does not register or enable intake. Publication must continue to deny where complete authenticated owner evidence or physical proof is unavailable. An Automation selected-source intake is a distinct Account-authorized operation, not participation inferred from a Game Design-only commit. Account must first authorize the exact immutable source read; after the read, Automation must retain the original content and outcome while holding revalidated current Account authority through its local commit. The declaration must originate in a genuine authored revision of the exact selected Game Design commit. Its inventory covers script roots, every event binding and patch source, and all dependent or inbound behavior/hook references from the complete selected World and other authored inputs. An explicit empty declaration is supported only when authenticated owner evidence closes that whole selected input set and rejects conflicting or unqualified existing content. Missing producers, omitted families, unavailable rows and a tenant-wide script query are not absence proof; an unsupported nonempty input denies instead of being discarded. -The immutable intake result retains the canonical tenant/version and selected commit, original source revision and operation, complete inventory bytes, exact Account authorization binding, original owner terminal and their digests. The result and authenticated readback are derived after the authored source commit, outside its preimage. An identical retry reads the original result; changed scope, selection, content or authorization binding conflicts rather than manufacturing a new receipt. A workload identity, creator declaration or matching digest alone is insufficient. Until the required selected-input producers and held-authority proof exist, the owner receipt remains unavailable and publication must not substitute an empty or synthetic version marker. +The immutable intake result retains the canonical tenant/version and selected commit, original source revision and operation, complete inventory bytes, exact Account authorization binding, original owner terminal and their digests. The result and authenticated readback are derived after the authored source commit, outside its preimage. An identical retry reads the original result; changed scope, selection, content or authorization binding conflicts rather than manufacturing a new receipt. A workload identity, creator declaration or matching digest alone is insufficient. Until the required selected-input producers and continuously held-authority proof exist, the Automation receipt cannot qualify publication, which must not substitute an empty or synthetic version marker. + +Automation's terminal read is a separate schema-version-1 `AUTOMATION_INTAKE_TERMINAL_READ` request, authenticated only for the exact same-namespace Account mTLS peer. It carries a fresh read correlation distinct from the original operation, fence and intake request, plus the complete original authorization binding bytes and digest. The only positive terminal is the typed `COMMITTED_EMPTY` outcome, with the complete canonical immutable Automation receipt bytes and recomputed digest; an exact retry returns that same receipt even when the read correlation changes. Missing, pending, changed, corrupt or ambiguous evidence denies and is never interpreted as absence, abort or release authority. Account's settlement consequence is defined by its [selected-owner intake contract](../account-service/api-contracts.md#grpc-apis) and must preserve the same original operation under its existing source locks. ## Architecture and Design Notes diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index ec202b7e28..351c8d9fc0 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 @@ -18,11 +18,13 @@ The corrected Common Platform/Account full gate passes in 49s, including formatt Exact source `e6b0d6d2b901e785c955bbf5f8c606578adfdc15` [Validation run 38038069636](https://github.com/benhook1013/FireMUD/actions/runs/38038069636) failed its required gate. Account's 1,312 unit cases have one failure: the missing-client-certificate probe resolved `localhost` to IPv6 while its server bound IPv4, and the originating cause is connection refusal before TLS. That run supplies no certificate-policy proof and never executes Account integration tests. Both local test clients now target the existing `127.0.0.1` server binding and certificate SAN without changing required-client-certificate or matcher policy; corrected native cases pass locally, while corrected CI remains required. Game Design's 151 integration cases and World's 221 execute with no failures, errors or skips, including the five genuine Game Design source/export cases and eighteen World authored-source/mTLS intake cases. The selected-export fixture still stipulates Entity/Automation participant digests, in-memory S3 and the StartSession Account projection: this is bounded physical source/release proof, not complete four-owner publication or gameplay admission. Tested merge `6dfe4e4a298685446cdceeb9073d7029c090361a`, tree `4c585a242d909c0648c76e003c19fb60928d276c`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, rather than the recorded integration parent. -Fresh Entity/Automation empty-source receipts remain concrete producer obligations. Entity currently has partial numeric-tenant storage for items, NPCs, recipes/ingredients, equipment slots and body layouts, but no typed provider for fourteen of the required 23 inventory families. Automation has script definitions, event bindings and patch/base identity, with retained unbound rows still denied. Neither owner has a complete canonical-UUID census, shared writer exclusion and immutable selected-source receipt/readback. Missing tables, a declared empty array, a synthetic version marker or an unqualified zero query cannot prove owner absence; existing numeric content cannot be assigned by borrowing Game Design's private key. The next cut must establish the actual fresh owner scope and full census before replacing stipulated publication participants. +Fresh Entity/Automation empty-source receipts remain concrete producer obligations. Entity currently has partial numeric-tenant storage for items, NPCs, recipes/ingredients, equipment slots and body layouts, but no typed provider for fourteen of the required 23 inventory families. Automation has script definitions, event bindings and patch/base identity, with retained unbound rows still denied. Neither owner has a complete authenticated and physically proved selected-source producer-to-terminal boundary. Missing tables, a declared empty array, a synthetic version marker or an unqualified zero query cannot prove owner absence; existing numeric content cannot be assigned by borrowing Game Design's private key. The next cut must establish the actual fresh owner scope and full census before replacing stipulated publication participants. The prepared shared `SelectedOwnerEmptySourceInputs` value exact-compares the supplied finalized Account binding with the World response, selected commit and canonical tenant/version/namespace. It requires the supported complete World inbound closure and the recipient's typed TEMPLATE_CONFIG inventory declaration, preserves that declaration's original inherited revision provenance, and rejects recipient-owned template references and nonempty Entity spawn input. This is local input-integrity composition only, not authenticated producer evidence, complete database census, continuously held authority or an owner terminal receipt. Its proof remains bounded to synthetic immutable inputs and must not be used to replace the owner obligations above. -Automation's prepared V5 storage cut covers its three actual authored-source families: script definitions, event bindings and script-patch base bindings; derived schedules are not a fourth authored family. It retains immutable canonical tenant/version associations, locally allocated private numeric keys and exact selected-source receipt bytes. The repository serializes allocation before source census and rejects unqualified legacy rows rather than treating absent mappings as empty. Source row and truncate guards reject writes against reserved empty scopes and require READ COMMITTED so a stale transaction snapshot cannot bypass a committed reservation. The existing Game Design source grammars and four additional typed snapshot values now live in Common, and the selected-source recipient validates all six families and raw selected Game Design revisions without a parallel schema. The standalone Automation service can compose typed empty inputs after authenticated Account/World reads but remains unregistered; two HELD observations are not continuous protection proof, and the finalized Account source reservation must remain pending under its existing writer guards until exact owner terminal settlement is proved. Actual repository persistence/readback and service ordering have focused test definitions with explicitly synthetic upstream inputs; they do not establish authenticated positive producer or physical PostgreSQL proof. Game Design's command grammar rejects unknown fields at each supported definition/effect/payload/modifier level while preserving its defined optional modifier fields; extraction does not add an effect grammar, prove foreign-owner census or authorize runtime activation. +Automation's prepared V5 storage cut covers its three actual authored-source families: script definitions, event bindings and script-patch base bindings; derived schedules are not a fourth authored family. It retains immutable canonical tenant/version associations, locally allocated private numeric keys and exact selected-source receipt bytes. The repository serializes allocation before source census and rejects unqualified legacy rows rather than treating absent mappings as empty. Source row and truncate guards reject writes against reserved empty scopes and require READ COMMITTED so a stale transaction snapshot cannot bypass a committed reservation. The existing Game Design source grammars and four additional typed snapshot values now live in Common, and the selected-source recipient validates all six families and raw selected Game Design revisions without a parallel schema. The standalone Automation service can compose typed empty inputs after authenticated Account/World reads but remains unregistered; two HELD observations are not continuous protection proof. The schema-version-1 Automation `COMMITTED_EMPTY` terminal codec/client and exact-binding receiver/repository read are prepared alongside Account's V135 immutable settlement/storage and independent lookup/read/commit/readback composition; all remain unregistered. The finalized Account source reservation stays pending under its existing writer guards until Account commits the exact same-operation settlement under those locks; only that receipt releases its participation, after which both external `HELD` readers deny while historical exact recovery remains available. Other pending operations remain protected. Missing or ambiguous owner evidence is not absence or abort. Focused receipt, repository, codec, receiver, synthetic mTLS and PostgreSQL test definitions cover bounded behavior; the corrected consolidated local terminal gate passed compilation, formatting, static analysis, checks, schema generation, boot packaging and documentation validation. Available unit reports show 602 Common, 1,339 Account and 1,200 Automation cases passing; those tasks were up-to-date in the final gate. Fresh local integration reports show Account 301 discovered, 12 executed and 289 skipped, and Automation 96 discovered, three executed and 93 skipped; the changed PostgreSQL suites skipped without Docker. Receipt recovery, wrong-purpose/echo denial and the synthetic missing-receipt native mTLS case have local proof, not an authenticated positive owner/database handoff. Synthetic evidence and test definitions do not establish authenticated positive producer or physical PostgreSQL proof. Game Design's command grammar rejects unknown fields at each supported definition/effect/payload/modifier level while preserving its defined optional modifier fields; extraction does not add an effect grammar, prove foreign-owner census or authorize runtime activation. + +Exact source `32cdc878d444f5aee77fec7c82eeed2baaa513c9` [Validation run 38050056519](https://github.com/benhook1013/FireMUD/actions/runs/38050056519) failed. Automation executed 1,195 unit and 96 integration tests, with two integration failures: receipt World-evidence initialization order and a test incorrectly passing a Java result class as a SQL bind. Both are corrected in the following local terminal batch without weakening assertions. The V5 installation/census guard migration case executed and passed. Account executed 1,332 passing units, then its database job exceeded the annotated 30-minute limit; logs contain seven PostgreSQL exceptions and two assertion failures, but no completed integration XML or total executed/failed/skipped counts. Missing reports do not establish SQLSTATE, constraint, original-COMMIT durability, V133 proof or a green database result. The tested checkout was merge `be5d9c85b2a7becf04baa64f113e98fbef9a7521`, tree `007478f73e7d71b339b34621cc471db6a75ec3ff`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and that source, not the separately recorded parent `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`. The existing [service-timeout observation](../ai-observations.md) records this evidence limitation; no workflow budget, deployment or runtime activation changed. Exact source `1f9f673095e4ac8f5bb6b9c0a969469854de4d86` [Validation run 38035808533](https://github.com/benhook1013/FireMUD/actions/runs/38035808533) failed the required gate: Account executed 1,304 unit cases with one missing-client-certificate matcher assertion failure. Retained XML and logs omit the transport exception/cause, so its cause and subsequent no-handler assertions are unproved for that run. The local corrected batch preserves the strict TLS matcher and required client certificate, adds failure diagnostics, and executes all four native cases successfully without weakening denial. Account's integration task never ran in that CI run; no PostgreSQL durability or acquisition proof follows. The tested merge `2be00c0c20e4feb76097547b9e9992c53e3ae6e3` has tree `96a7913e52c5ce281c81093e1b225fb3e9344ee2` and ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, not the separately recorded integration parent. The approved failure-only diagnostic now maps bounded captured WAL relation locators through the same run-owned database's current catalog after failure; missing, reused, changed or cross-database locators remain inconclusive. It has no executed PostgreSQL result and establishes neither historical relation identity, backend origin nor timing causation. diff --git a/protos/automation-scripting/v1/automation_selected_source_intake_terminal_read.proto b/protos/automation-scripting/v1/automation_selected_source_intake_terminal_read.proto new file mode 100644 index 0000000000..095934762f --- /dev/null +++ b/protos/automation-scripting/v1/automation_selected_source_intake_terminal_read.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +package automation_scripting.v1; +option java_package = "net.firedevops.firemud.automationscripting.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. Only the same-namespace Account workload may read. +service AutomationSelectedSourceIntakeTerminalReadService { + rpc ReadSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest) + returns (ReadSelectedSourceIntakeTerminalResponse); +} + +message ReadSelectedSourceIntakeTerminalRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intended_reader = 4; + string terminal_read_purpose = 5; + bytes original_intake_authorization_binding = 6; + string intake_authorization_digest = 7; +} + +enum AutomationSelectedSourceIntakeTerminalResult { + AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED = 0; + AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY = 1; +} + +message ReadSelectedSourceIntakeTerminalResponse { + ReadSelectedSourceIntakeTerminalRequest request = 1; + AutomationSelectedSourceIntakeTerminalResult result = 2; + bytes committed_empty_receipt = 3; + string receipt_digest = 4; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java index 50bb396a07..1895937609 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java @@ -47,7 +47,7 @@ public void requireHeld(SelectedOwnerIntakeAuthorizationReadEvidence.Request req try { ownerTransaction.execute( ignored -> { - repository.readFinalAuthorization(request.binding()); + repository.readHeldFinalAuthorization(request.binding()); return null; }); } catch (StatusRuntimeException failure) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java new file mode 100644 index 0000000000..1d3205c67e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java @@ -0,0 +1,303 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered composition for settling one exact finalized Automation intake operation. + * + *

The Account source reservation repository owns source-lock ordering and immutable settlement + * persistence. This service only permits its pending participation to advance after an exact + * authenticated Automation COMMITTED_EMPTY receipt has been read outside SQL. + */ +public final class AccountSelectedOwnerIntakeSettlementService { + private static final String AUTOMATION_READER = "automation-scripting-service"; + private static final String GAME_DESIGN_CALLER = "game-design-service"; + private static final String ACCOUNT_READER = "account-service"; + + private final AccountSelectedOwnerIntakeSourceReservationRepository repository; + private final AutomationSelectedSourceIntakeTerminalReadClient automationClient; + private final TransactionTemplate ownerTransaction; + private final String namespace; + + public AccountSelectedOwnerIntakeSettlementService( + AccountSelectedOwnerIntakeSourceReservationRepository repository, + AutomationSelectedSourceIntakeTerminalReadClient automationClient, + PlatformTransactionManager transactionManager, + String namespace) { + this.repository = Objects.requireNonNull(repository, "source reservation repository required"); + this.automationClient = Objects.requireNonNull(automationClient, "Automation client required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + ownerTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager required")); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Settles or recovers the exact finalized Automation authorization selected by Game Design. + * + *

The authorization is a lookup key, not caller authority. Account revalidates its complete + * retained value before checking for an immutable prior settlement or contacting Automation. + */ + public AccountSelectedOwnerIntakeSettlementReceipt settle( + SelectedOwnerIntakeAuthorizationBinding original) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + requireOriginalBinding(original); + + Lookup lookup = + ownerTransaction.execute( + ignored -> { + try { + repository.readFinalAuthorization(original); + Optional prior = + Objects.requireNonNull( + repository.findSettlement(original), + "Account settlement lookup returned no result"); + return new Lookup(prior.orElse(null)); + } catch (IllegalArgumentException absentOrChanged) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact finalized Automation authorization is unavailable") + .withCause(absentOrChanged) + .asRuntimeException(); + } + }); + if (lookup == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Account authorization transaction returned no result") + .asRuntimeException(); + } + if (lookup.prior() != null) { + return requireSettlement(lookup.prior(), original, null); + } + + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(namespace, original); + requireNoAmbientTransaction(); + AutomationSelectedSourceIntakeTerminalReadEvidence remote; + try { + remote = automationClient.read(request); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Automation terminal evidence is unavailable") + .withCause(unavailable) + .asRuntimeException(); + } + AutomationSelectedSourceIntakeTerminalReadEvidence exactEvidence = + requireExactTerminal(request, original, remote); + + requireNoAmbientTransaction(); + AccountSelectedOwnerIntakeSettlementReceipt committed = + ownerTransaction.execute(ignored -> repository.settleCommittedEmpty(exactEvidence)); + requireSettlement(committed, original, exactEvidence); + + // This independent lookup is deliberately lookup-only. An unknown first commit remains + // unresolved; replaying settleCommittedEmpty here could conceal its outcome. + requireNoAmbientTransaction(); + AccountSelectedOwnerIntakeSettlementReceipt readback = + ownerTransaction.execute( + ignored -> + Objects.requireNonNull( + repository.findSettlement(original), + "Account settlement readback returned no result") + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription("Committed Account settlement is not readable") + .asRuntimeException())); + requireSettlement(readback, original, exactEvidence); + if (!sameSettlement(committed, readback)) { + throw Status.FAILED_PRECONDITION + .withDescription("Committed Account settlement readback differs") + .asRuntimeException(); + } + return readback; + } + + private void requireGameDesignPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Authenticated Game Design workload is required") + .asRuntimeException(); + } + String expectedUri = workloadUri(namespace, GAME_DESIGN_CALLER); + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !expectedUri.equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Game Design workload without end-user context required") + .asRuntimeException(); + } + } + + private void requireOriginalBinding(SelectedOwnerIntakeAuthorizationBinding original) { + if (original == null + || original.owner() != Owner.AUTOMATION_SCRIPTING + || !namespace.equals(original.targetNamespace()) + || !"account-automation-intake-authorization/v1".equals(original.schema()) + || !"AUTOMATION_INTAKE_RETENTION".equals(original.purpose()) + || !workloadUri(namespace, AUTOMATION_READER).equals(original.intendedReader())) { + throw Status.FAILED_PRECONDITION + .withDescription("Canonical same-namespace Automation authorization is required") + .asRuntimeException(); + } + try { + byte[] bytes = original.canonicalBytes(); + SelectedOwnerIntakeAuthorizationBinding canonical = + SelectedOwnerIntakeAuthorizationBinding.fromStored(bytes); + if (bytes.length == 0 + || bytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + || !Arrays.equals(bytes, canonical.canonicalBytes()) + || !original.digest().equals(canonical.digest())) { + throw new IllegalArgumentException("Noncanonical selected-owner authorization"); + } + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Canonical same-namespace Automation authorization is required") + .withCause(invalid) + .asRuntimeException(); + } + } + + private AutomationSelectedSourceIntakeTerminalReadEvidence requireExactTerminal( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request, + SelectedOwnerIntakeAuthorizationBinding original, + AutomationSelectedSourceIntakeTerminalReadEvidence remote) { + if (remote == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Automation returned no terminal evidence") + .asRuntimeException(); + } + try { + var echoed = remote.request(); + if (!request.equals(echoed) + || echoed.schemaVersion() + != AutomationSelectedSourceIntakeTerminalReadEvidence.SCHEMA_VERSION + || !namespace.equals(echoed.targetNamespace()) + || !request.readRequestId().equals(echoed.readRequestId()) + || !Arrays.equals(original.canonicalBytes(), echoed.binding().canonicalBytes()) + || !workloadUri(namespace, ACCOUNT_READER).equals(echoed.intendedReader()) + || !AutomationSelectedSourceIntakeTerminalReadEvidence.TERMINAL_READ_PURPOSE.equals( + echoed.terminalReadPurpose())) { + throw new IllegalArgumentException("Automation changed the complete terminal-read request"); + } + + AutomationEmptySelectedSourceIntakeReceipt receipt = remote.receipt(); + byte[] receiptBytes = receipt.canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES + || !DraftAuthorizationFenceBinding.digest(receiptBytes).equals(receipt.receiptDigest()) + || !"COMMITTED_EMPTY".equals(receipt.outcome()) + || !namespace.equals(receipt.targetNamespace()) + || !original.operationId().equals(receipt.operationId()) + || !original.fenceId().equals(receipt.fenceId()) + || !original.intakeRequestId().equals(receipt.intakeRequestId()) + || !original.tenantId().equals(receipt.canonicalTenantId()) + || !original.versionId().equals(receipt.canonicalVersionId()) + || !original.selected().commitId().equals(receipt.selectedCommitId()) + || !Arrays.equals(original.canonicalBytes(), receipt.authorizationBindingBytes()) + || !original.digest().equals(receipt.authorizationBindingDigest())) { + throw new IllegalArgumentException( + "Automation receipt is not the canonical original terminal"); + } + AutomationSelectedSourceIntakeTerminalReadEvidence exact = + new AutomationSelectedSourceIntakeTerminalReadEvidence(request, receipt); + if (!Arrays.equals(receiptBytes, exact.receipt().canonicalBytes()) + || !receipt.receiptDigest().equals(exact.receipt().receiptDigest())) { + throw new IllegalArgumentException("Automation terminal receipt changed during validation"); + } + return exact; + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Automation terminal differs from the exact original authorization") + .withCause(invalid) + .asRuntimeException(); + } + } + + private AccountSelectedOwnerIntakeSettlementReceipt requireSettlement( + AccountSelectedOwnerIntakeSettlementReceipt receipt, + SelectedOwnerIntakeAuthorizationBinding original, + AutomationSelectedSourceIntakeTerminalReadEvidence expectedOwnerTerminal) { + if (receipt == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Account terminal settlement receipt is unavailable") + .asRuntimeException(); + } + try { + if (!Arrays.equals(original.canonicalBytes(), receipt.authorizationBinding().canonicalBytes()) + || !original.digest().equals(receipt.authorizationBinding().digest()) + || !original.operationId().equals(receipt.operationId()) + || !namespace.equals(receipt.targetNamespace()) + || !Arrays.equals( + original.canonicalBytes(), + receipt.terminalEvidence().request().binding().canonicalBytes())) { + throw new IllegalArgumentException("Account settlement changed the original binding"); + } + AccountSelectedOwnerIntakeSettlementReceipt canonical = + AccountSelectedOwnerIntakeSettlementReceipt.create(receipt.terminalEvidence()); + if (!Arrays.equals(canonical.canonicalBytes(), receipt.canonicalBytes()) + || !canonical.digest().equals(receipt.digest()) + || (expectedOwnerTerminal != null + && !receipt.sameImmutableOwnerReceipt(expectedOwnerTerminal))) { + throw new IllegalArgumentException( + "Account settlement receipt changed its canonical owner value"); + } + return receipt; + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Account settlement receipt differs from the original Automation terminal") + .withCause(invalid) + .asRuntimeException(); + } + } + + private static boolean sameSettlement( + AccountSelectedOwnerIntakeSettlementReceipt left, + AccountSelectedOwnerIntakeSettlementReceipt right) { + return left.digest().equals(right.digest()) + && Arrays.equals(left.canonicalBytes(), right.canonicalBytes()); + } + + private static String workloadUri(String namespace, String service) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Account terminal settlement requires independent transactions") + .asRuntimeException(); + } + } + + private record Lookup(AccountSelectedOwnerIntakeSettlementReceipt prior) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java index da3fc6945c..87f49ba243 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.accountservice.service.session; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; import java.util.Objects; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; @@ -21,6 +22,10 @@ public final class AccountSelectedOwnerIntakeSourceReadService { private final TransactionTemplate transaction; private final String namespace; + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected owner repository is intentionally shared and never exposed to callers") public AccountSelectedOwnerIntakeSourceReadService( AccountSelectedOwnerIntakeSourceReservationRepository repository, AccountControlUiCoordination registry, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java index 9b68e40337..f4800b8fbf 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java @@ -11,21 +11,22 @@ import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * Immutable Entity/Automation preliminary reservations and distinct finalized source retention. - * Finalization excludes preliminary abort; authenticated owner-terminal settlement is not yet - * implemented, so finalized participation remains held. + * Immutable Entity/Automation preliminary reservations, finalized source retention, and exact + * Automation {@code COMMITTED_EMPTY} terminal settlement. */ public final class AccountSelectedOwnerIntakeSourceReservationRepository { private static final String RESERVATIONS = @@ -34,6 +35,7 @@ public final class AccountSelectedOwnerIntakeSourceReservationRepository { private static final String ABORTS = "account_selected_owner_intake_source_read_aborts"; private static final String AUTHORIZATIONS = "account_selected_owner_intake_authorizations"; private static final String AUTHORIZATION_SOURCES = "account_selected_owner_intake_sources"; + private static final String SETTLEMENTS = "account_selected_owner_intake_settlements"; private final DSLContext dsl; @@ -293,7 +295,20 @@ Optional findFinalAuthorization( return Optional.of(binding); } + /** Historical exact authorization read; settled orders remain recoverable through this path. */ void readFinalAuthorization(SelectedOwnerIntakeAuthorizationBinding requested) { + readFinalAuthorization(requested, false); + } + + /** + * External HELD reads deny after exact terminal settlement; historical reads remain available. + */ + void readHeldFinalAuthorization(SelectedOwnerIntakeAuthorizationBinding requested) { + readFinalAuthorization(requested, true); + } + + private void readFinalAuthorization( + SelectedOwnerIntakeAuthorizationBinding requested, boolean requireHeld) { requireTransaction(); Objects.requireNonNull(requested, "requested"); Record lookup = authorizationLookup(requested.operationId()); @@ -311,6 +326,121 @@ void readFinalAuthorization(SelectedOwnerIntakeAuthorizationBinding requested) { requireAuthorization(row, original); if (aborted(original.content().scope())) throw new IllegalArgumentException("Finalized owner authorization cannot be aborted"); + if (requireHeld && settlement(original.operationId()) != null) { + throw new IllegalArgumentException("Settled owner authorization is no longer held"); + } + } + + /** + * Exact committed settlement recovery; callers perform this before any external terminal read. + */ + Optional findSettlement( + SelectedOwnerIntakeAuthorizationBinding requested) { + requireTransaction(); + Objects.requireNonNull(requested, "original selected-owner authorization is required"); + if (requested.owner() != Owner.AUTOMATION_SCRIPTING) { + throw new IllegalArgumentException("Automation terminal settlement required"); + } + SelectedOwnerIntakeSourceReadScope scope = requested.content().scope(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + Record order = authorization(requested.operationId()); + requireAuthorization(order, requested); + if (aborted(scope)) + throw new IllegalArgumentException("Finalized owner authorization was aborted"); + Record row = settlement(requested.operationId()); + if (row == null) return Optional.empty(); + return Optional.of(exactSettlement(row, requested, null)); + } + + /** + * Commits one immutable COMMITTED_EMPTY owner receipt after the authenticated owner read has + * completed outside SQL. The read correlation is retained on first write but is not settlement + * identity; a fresh correlation with identical owner receipt bytes recovers the first receipt. + */ + AccountSelectedOwnerIntakeSettlementReceipt settleCommittedEmpty( + AutomationSelectedSourceIntakeTerminalReadEvidence evidence) { + requireTransaction(); + Objects.requireNonNull(evidence, "Automation terminal evidence is required"); + var requested = evidence.request().binding(); + if (requested.owner() != Owner.AUTOMATION_SCRIPTING + || !"COMMITTED_EMPTY".equals(evidence.receipt().outcome())) { + throw new IllegalArgumentException("Exact Automation COMMITTED_EMPTY evidence required"); + } + SelectedOwnerIntakeSourceReadScope scope = requested.content().scope(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + Record order = authorization(requested.operationId()); + requireAuthorization(order, requested); + if (aborted(scope)) + throw new IllegalArgumentException("Finalized owner authorization was aborted"); + + Record prior = settlement(requested.operationId()); + if (prior != null) return exactSettlement(prior, requested, evidence); + + AccountSelectedOwnerIntakeSettlementReceipt receipt = + AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + dsl.execute( + "INSERT INTO " + + SETTLEMENTS + + " (operation_id, fence_id, intake_request_id, owner, target_namespace, tenant_uuid, " + + "version_uuid, binding_bytes, binding_digest, terminal_read_request_id, " + + "terminal_receipt_bytes, terminal_receipt_digest, receipt_bytes, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.operationId(), + requested.fenceId(), + requested.intakeRequestId(), + requested.owner().name(), + requested.targetNamespace(), + requested.tenantId(), + requested.versionId(), + requested.canonicalBytes(), + requested.digest(), + evidence.request().readRequestId(), + receipt.ownerReceiptBytes(), + receipt.ownerReceiptDigest(), + receipt.canonicalBytes(), + receipt.digest()); + return exactSettlement(settlement(requested.operationId()), requested, evidence); + } + + private AccountSelectedOwnerIntakeSettlementReceipt exactSettlement( + Record row, + SelectedOwnerIntakeAuthorizationBinding requested, + AutomationSelectedSourceIntakeTerminalReadEvidence retryEvidence) { + if (row == null) throw new IllegalStateException("Account settlement commit readback absent"); + byte[] storedBytes = row.get("receipt_bytes", byte[].class); + var receipt = AccountSelectedOwnerIntakeSettlementReceipt.fromStored(storedBytes); + var original = receipt.authorizationBinding(); + var request = receipt.terminalEvidence().request(); + var ownerReceipt = receipt.terminalEvidence().receipt(); + if (!Arrays.equals(original.canonicalBytes(), requested.canonicalBytes()) + || !Arrays.equals(storedBytes, receipt.canonicalBytes()) + || !receipt.digest().equals(row.get("receipt_digest", String.class)) + || !Arrays.equals( + ownerReceipt.canonicalBytes(), row.get("terminal_receipt_bytes", byte[].class)) + || !ownerReceipt.receiptDigest().equals(row.get("terminal_receipt_digest", String.class)) + || !request.readRequestId().equals(row.get("terminal_read_request_id", UUID.class)) + || !original.operationId().equals(row.get("operation_id", UUID.class)) + || !original.fenceId().equals(row.get("fence_id", UUID.class)) + || !original.intakeRequestId().equals(row.get("intake_request_id", UUID.class)) + || !original.owner().name().equals(row.get("owner", String.class)) + || !original.targetNamespace().equals(row.get("target_namespace", String.class)) + || !original.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !original.versionId().equals(row.get("version_uuid", UUID.class)) + || !Arrays.equals(original.canonicalBytes(), row.get("binding_bytes", byte[].class)) + || !original.digest().equals(row.get("binding_digest", String.class))) { + throw new IllegalArgumentException("Changed exact selected-owner terminal settlement"); + } + if (retryEvidence != null && !receipt.sameImmutableOwnerReceipt(retryEvidence)) { + throw new IllegalArgumentException("Changed Automation owner terminal receipt"); + } + return receipt; + } + + private Record settlement(UUID operationId) { + return dsl.fetchOne( + "SELECT * FROM " + SETTLEMENTS + " WHERE operation_id = ? FOR UPDATE", operationId); } private Record authorization(UUID operationId) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java index c5ecec0bd3..190a47e7b6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java @@ -46,7 +46,7 @@ public void requireHeld( try { ownerTransaction.execute( ignored -> { - repository.readFinalAuthorization(request.binding()); + repository.readHeldFinalAuthorization(request.binding()); return null; }); } catch (StatusRuntimeException failure) { diff --git a/services/account-service/src/main/resources/db/migration/V135__selected_owner_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V135__selected_owner_intake_terminal_settlement.sql new file mode 100644 index 0000000000..057e8a0c7e --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V135__selected_owner_intake_terminal_settlement.sql @@ -0,0 +1,495 @@ +-- Exact Automation COMMITTED_EMPTY terminal settlement. Entity participation and every +-- unresolved/ambiguous owner outcome remain pending indefinitely. +CREATE TABLE account_selected_owner_intake_settlements ( + operation_id UUID PRIMARY KEY + REFERENCES account_selected_owner_intake_authorizations(operation_id), + fence_id UUID NOT NULL UNIQUE, + intake_request_id UUID NOT NULL, + owner VARCHAR(32) NOT NULL CHECK (owner = 'AUTOMATION_SCRIPTING'), + target_namespace VARCHAR(63) NOT NULL + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + tenant_uuid UUID NOT NULL REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + version_uuid UUID NOT NULL, + binding_bytes BYTEA NOT NULL CHECK (octet_length(binding_bytes) BETWEEN 1 AND 16777216), + binding_digest VARCHAR(71) NOT NULL CHECK (binding_digest ~ '^sha256:[0-9a-f]{64}$'), + terminal_read_request_id UUID NOT NULL, + terminal_receipt_bytes BYTEA NOT NULL CHECK (octet_length(terminal_receipt_bytes) BETWEEN 1 AND 58736640), + terminal_receipt_digest VARCHAR(71) NOT NULL CHECK (terminal_receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + receipt_bytes BYTEA NOT NULL CHECK (octet_length(receipt_bytes) BETWEEN 1 AND 92356608), + receipt_digest VARCHAR(71) NOT NULL CHECK (receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + settled_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (fence_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (intake_request_id <> '00000000-0000-0000-0000-000000000000'), + CHECK (terminal_read_request_id <> '00000000-0000-0000-0000-000000000000') +); + +-- [jooq ignore start] +CREATE FUNCTION account_selected_owner_intake_settlement_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_selected_owner_intake_authorizations%ROWTYPE; + reservation account_selected_owner_intake_source_read_reservations%ROWTYPE; + p INTEGER := 1; + q INTEGER := 1; + source_position INTEGER := 1; + receipt_position INTEGER := 1; + parsed BYTEA; + binding_scope BYTEA; + content_bytes BYTEA; + selected_bytes BYTEA; + terminal_binding BYTEA; + owner_receipt BYTEA; + world_request_bytes BYTEA; + world_inventory_bytes BYTEA; + source_bytes BYTEA; + source_kind TEXT; + source_scope TEXT; + source_key_value TEXT; + previous_sort_key INTEGER[]; + current_sort_key INTEGER[]; + namespace_value TEXT; + request_id_value UUID; + owner_world_request_id UUID; + count_text TEXT; + count_value INTEGER; + index_value INTEGER; + local_key_value BIGINT; + local_key_text TEXT; + first_local_key_text TEXT; + request_digest_text TEXT; + ignored_text TEXT; + marker TEXT; + retained_timestamp TIMESTAMPTZ; +BEGIN + -- Source writers and settlement serialize on Account's retained source rows in canonical + -- sort order, followed by reservation, final authorization, then this settlement identity. + PERFORM lock_row.source_key + FROM account_draft_authorization_source_locks lock_row + JOIN account_selected_owner_intake_source_read_sources source + ON source.source_key = lock_row.source_key + WHERE source.operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(lock_row.source_key) + FOR UPDATE OF lock_row; + SELECT * INTO STRICT reservation + FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id FOR UPDATE; + SELECT * INTO STRICT original + FROM account_selected_owner_intake_authorizations + WHERE operation_id = NEW.operation_id FOR UPDATE; + PERFORM operation_id FROM account_selected_owner_intake_settlements + WHERE operation_id = NEW.operation_id FOR UPDATE; + + IF FOUND + OR EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_aborts + WHERE operation_id = NEW.operation_id) + OR NEW.operation_id IS DISTINCT FROM original.operation_id + OR NEW.fence_id IS DISTINCT FROM original.fence_id + OR NEW.intake_request_id IS DISTINCT FROM original.intake_request_id + OR NEW.owner IS DISTINCT FROM original.owner + OR NEW.target_namespace IS DISTINCT FROM original.target_namespace + OR NEW.tenant_uuid IS DISTINCT FROM original.tenant_uuid + OR NEW.version_uuid IS DISTINCT FROM original.version_uuid + OR original.owner IS DISTINCT FROM 'AUTOMATION_SCRIPTING' + OR reservation.owner IS DISTINCT FROM original.owner + OR reservation.operation_id IS DISTINCT FROM original.operation_id + OR reservation.fence_id IS DISTINCT FROM original.fence_id + OR reservation.intake_request_id IS DISTINCT FROM original.intake_request_id + OR reservation.actor_account_uuid IS DISTINCT FROM original.actor_account_uuid + OR reservation.tenant_uuid IS DISTINCT FROM original.tenant_uuid + OR reservation.version_uuid IS DISTINCT FROM original.version_uuid + OR NEW.binding_bytes IS DISTINCT FROM original.binding_bytes + OR NEW.binding_digest IS DISTINCT FROM original.binding_digest + OR original.binding_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(original.binding_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement must bind one exact active Automation authorization' + USING ERRCODE = '23514'; + END IF; + + -- Recheck every finalized source child against both the complete immutable binding and the + -- retained preliminary child vector. A digest or parent-row match alone is insufficient. + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-automation-intake-authorization/v1' THEN + RAISE EXCEPTION 'Settlement original binding is not Automation authorization' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO content_bytes, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM 'sha256:' || encode(sha256(content_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement original content digest differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM 'spiffe://firemud/ns/' || original.target_namespace || '/sa/automation-scripting-service' THEN + RAISE EXCEPTION 'Settlement original retention reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM 'AUTOMATION_INTAKE_RETENTION' THEN + RAISE EXCEPTION 'Settlement original retention purpose differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO count_text, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF count_text !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Settlement original source count is malformed' USING ERRCODE = '23514'; + END IF; + count_value := count_text::INTEGER; + IF count_value > 256 THEN + RAISE EXCEPTION 'Settlement original source vector exceeds its bound' + USING ERRCODE = '23514'; + END IF; + + q := 1; + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'game-design-selected-owner-intake-source/v1' THEN + RAISE EXCEPTION 'Settlement original selected content schema differs' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO binding_scope, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF marker IS DISTINCT FROM 'sha256:' || encode(sha256(binding_scope), 'hex') + OR binding_scope IS DISTINCT FROM reservation.scope_bytes + OR reservation.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(binding_scope), 'hex') + OR original.content_bytes IS DISTINCT FROM content_bytes + OR original.content_digest IS DISTINCT FROM 'sha256:' || encode(sha256(content_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement original selected scope or content differs' + USING ERRCODE = '23514'; + END IF; + -- The finalized binding contains six exact selected family frames after its scope header. + FOREACH ignored_text IN ARRAY ARRAY['COMMAND', 'REALM_POLICY', 'ASSET', 'GAMEPLAY_RULE', 'BRANDING', 'TEMPLATE_CONFIG'] LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF marker IS DISTINCT FROM ignored_text + OR namespace_value IS DISTINCT FROM 'sha256:' || encode(sha256(parsed), 'hex') THEN + RAISE EXCEPTION 'Settlement selected family snapshot differs' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF q <> octet_length(content_bytes) + 1 THEN + RAISE EXCEPTION 'Settlement selected content has trailing bytes' USING ERRCODE = '23514'; + END IF; + + -- Bind the full preliminary scope tuple and selected-target JSON to all retained columns. + source_position := 1; + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-automation-intake-source-read/v1' THEN + RAISE EXCEPTION 'Settlement original preliminary scope schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM 'AUTOMATION_SCRIPTING' THEN + RAISE EXCEPTION 'Settlement original scope owner differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + FOR index_value IN 1..4 LOOP + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF index_value = 1 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.operation_id::TEXT + OR index_value = 2 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.fence_id::TEXT + OR index_value = 3 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.intake_request_id::TEXT + OR index_value = 4 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM original.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Settlement operation scope tuple differs' USING ERRCODE = '23514'; + END IF; + END LOOP; + SELECT frame_value, next_position INTO selected_bytes, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF namespace_value IS DISTINCT FROM NEW.target_namespace + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(selected_bytes), 'hex') + OR convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalVersionId' IS DISTINCT FROM NEW.version_uuid::TEXT THEN + RAISE EXCEPTION 'Settlement original selected scope differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM 'spiffe://firemud/ns/' || NEW.target_namespace || '/sa/account-service' THEN + RAISE EXCEPTION 'Settlement source scope reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM 'AUTOMATION_INTAKE_SOURCE' + OR source_position <> octet_length(binding_scope) + 1 THEN + RAISE EXCEPTION 'Settlement source scope purpose or trailing bytes differ' + USING ERRCODE = '23514'; + END IF; + + FOR index_value IN 1..count_value LOOP + SELECT frame_value, next_position INTO source_bytes, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + source_position := 1; + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Settlement source evidence schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_kind, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_scope, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := source_kind || ':' || source_scope; + current_sort_key := account_publication_authorization_source_sort_key(source_key_value); + IF previous_sort_key IS NOT NULL AND current_sort_key <= previous_sort_key THEN + RAISE EXCEPTION 'Settlement source vector is duplicated or unordered' + USING ERRCODE = '23514'; + END IF; + previous_sort_key := current_sort_key; + IF NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_sources source + WHERE source.operation_id = NEW.operation_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) + OR NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_sources source + WHERE source.operation_id = NEW.operation_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Settlement source child differs from complete original vector' + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF p <> octet_length(original.binding_bytes) + 1 + OR count_value IS DISTINCT FROM (SELECT count(*) FROM account_selected_owner_intake_sources + WHERE operation_id = NEW.operation_id) + OR count_value IS DISTINCT FROM (SELECT count(*) FROM account_selected_owner_intake_source_read_sources + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Settlement source child vector is incomplete' USING ERRCODE = '23514'; + END IF; + + IF NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') + OR NEW.terminal_receipt_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_receipt_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement or Automation receipt digest differs' USING ERRCODE = '23514'; + END IF; + p := 1; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-selected-owner-intake-settlement/v1' THEN + RAISE EXCEPTION 'Settlement receipt schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Settlement receipt version differs' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF parsed IS DISTINCT FROM NEW.binding_bytes THEN + RAISE EXCEPTION 'Settlement receipt changed original binding bytes' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM NEW.binding_digest THEN + RAISE EXCEPTION 'Settlement receipt changed original binding digest' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Settlement terminal request schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + BEGIN request_id_value := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Settlement terminal read correlation is malformed' USING ERRCODE = '23514'; END; + IF request_id_value = '00000000-0000-0000-0000-000000000000'::UUID + OR request_id_value::TEXT IS DISTINCT FROM ignored_text + OR request_id_value = NEW.operation_id OR request_id_value = NEW.fence_id + OR request_id_value = NEW.intake_request_id + OR request_id_value IS DISTINCT FROM NEW.terminal_read_request_id THEN + RAISE EXCEPTION 'Settlement terminal read correlation differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF namespace_value IS DISTINCT FROM NEW.target_namespace + OR marker IS DISTINCT FROM 'spiffe://firemud/ns/' || NEW.target_namespace || '/sa/account-service' THEN + RAISE EXCEPTION 'Settlement terminal reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM 'AUTOMATION_INTAKE_TERMINAL_READ' THEN + RAISE EXCEPTION 'Settlement terminal read purpose differs' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO terminal_binding, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF terminal_binding IS DISTINCT FROM NEW.binding_bytes OR marker IS DISTINCT FROM NEW.binding_digest THEN + RAISE EXCEPTION 'Settlement terminal request changed original Account binding' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO owner_receipt, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF owner_receipt IS DISTINCT FROM NEW.terminal_receipt_bytes + OR marker IS DISTINCT FROM NEW.terminal_receipt_digest + OR p <> octet_length(NEW.receipt_bytes) + 1 THEN + RAISE EXCEPTION 'Settlement receipt differs from exact Automation terminal bytes' + USING ERRCODE = '23514'; + END IF; + + -- The owner receipt has a closed canonical frame and embeds the complete same binding. + p := 1; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM 'automation-empty-selected-source-intake-receipt/v1' THEN + RAISE EXCEPTION 'Automation terminal receipt schema is not COMMITTED_EMPTY' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Automation terminal receipt version differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + FOR index_value IN 1..8 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF index_value = 1 AND marker IS DISTINCT FROM NEW.operation_id::TEXT + OR index_value = 2 AND marker IS DISTINCT FROM NEW.fence_id::TEXT + OR index_value = 3 AND marker IS DISTINCT FROM NEW.intake_request_id::TEXT + OR index_value = 4 AND marker IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR index_value = 5 AND marker IS DISTINCT FROM NEW.version_uuid::TEXT + OR index_value = 6 AND marker IS DISTINCT FROM convert_from(selected_bytes, 'UTF8')::JSONB->>'commitId' THEN + RAISE EXCEPTION 'Automation terminal identity differs from original order' + USING ERRCODE = '23514'; + END IF; + IF index_value = 7 THEN + BEGIN PERFORM marker::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation source revision identity is malformed' + USING ERRCODE = '23514'; END; + IF marker::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR marker::UUID::TEXT IS DISTINCT FROM marker THEN + RAISE EXCEPTION 'Automation source revision identity is noncanonical' + USING ERRCODE = '23514'; + END IF; + ELSIF index_value = 8 AND marker !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Automation source revision order is noncanonical' + USING ERRCODE = '23514'; + END IF; + END LOOP; + -- Skip source declaration and local key/request metadata, then verify the full bound receipt + -- digest and authorization bytes before consuming the independent World evidence frames. + FOR index_value IN 1..3 LOOP + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF index_value < 3 THEN + local_key_text := convert_from(parsed, 'UTF8'); + BEGIN local_key_value := local_key_text::BIGINT; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation local key is malformed' USING ERRCODE = '23514'; END; + IF local_key_value <= 0 OR local_key_value::TEXT IS DISTINCT FROM local_key_text + OR (index_value = 2 AND local_key_text IS NOT DISTINCT FROM first_local_key_text) THEN + RAISE EXCEPTION 'Automation local key is noncanonical or repeated' + USING ERRCODE = '23514'; + END IF; + IF index_value = 1 THEN first_local_key_text := local_key_text; END IF; + ELSE + request_digest_text := convert_from(parsed, 'UTF8'); + IF request_digest_text !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation caller request digest is malformed' + USING ERRCODE = '23514'; + END IF; + END IF; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM NEW.binding_digest OR parsed IS DISTINCT FROM NEW.binding_bytes THEN + RAISE EXCEPTION 'Automation terminal receipt changed full original binding' + USING ERRCODE = '23514'; + END IF; + IF namespace_value IS DISTINCT FROM NEW.target_namespace THEN + RAISE EXCEPTION 'Automation terminal namespace differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + BEGIN owner_world_request_id := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation World read correlation is malformed' USING ERRCODE = '23514'; END; + IF owner_world_request_id = '00000000-0000-0000-0000-000000000000'::UUID + OR owner_world_request_id::TEXT IS DISTINCT FROM ignored_text THEN + RAISE EXCEPTION 'Automation World read correlation is noncanonical' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation World request digest is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_request_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_request_bytes) NOT BETWEEN 1 AND 33554432 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_request_bytes), 'hex') THEN + RAISE EXCEPTION 'Automation World request bytes or digest differ' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation World inventory digest is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_inventory_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_inventory_bytes) NOT BETWEEN 1 AND 8388608 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_inventory_bytes), 'hex') THEN + RAISE EXCEPTION 'Automation World inventory bytes or digest differ' USING ERRCODE = '23514'; + END IF; + -- COMMITTED_EMPTY is represented only by a complete all-zero three-family census. + FOR index_value IN 1..12 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO count_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF count_text !~ '^(0|[1-9][0-9]*)$' OR count_text::BIGINT <> 0 THEN + RAISE EXCEPTION 'Automation COMMITTED_EMPTY receipt contains a nonempty census' + USING ERRCODE = '23514'; + END IF; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF ignored_text !~ '^[+-]?[0-9]{4,}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(:[0-9]{2}([.][0-9]{0,8}[1-9])?)?Z$' + OR p <> octet_length(owner_receipt) + 1 THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp or trailing bytes are invalid' + USING ERRCODE = '23514'; + END IF; + BEGIN retained_timestamp := ignored_text::TIMESTAMPTZ; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp is malformed' + USING ERRCODE = '23514'; END; + IF retained_timestamp IS NULL THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp is absent' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_selected_owner_intake_settlement_validate + BEFORE INSERT ON account_selected_owner_intake_settlements + FOR EACH ROW EXECUTE FUNCTION account_selected_owner_intake_settlement_guard(); +CREATE TRIGGER account_selected_owner_intake_settlement_immutable + BEFORE UPDATE OR DELETE ON account_selected_owner_intake_settlements + FOR EACH ROW EXECUTE FUNCTION account_draft_authorization_immutable_guard(); +CREATE TRIGGER account_selected_owner_intake_settlement_no_truncate + BEFORE TRUNCATE ON account_selected_owner_intake_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_draft_authorization_immutable_guard(); + +CREATE OR REPLACE FUNCTION account_selected_owner_intake_source_read_is_pending(operation_value UUID) +RETURNS BOOLEAN LANGUAGE SQL STABLE STRICT AS $$ + SELECT NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_aborts aborted + WHERE aborted.operation_id = operation_value) + AND NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_settlements settled + WHERE settled.operation_id = operation_value); +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java index b32c7fdc52..1142b3ffe7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -4,31 +4,72 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.service.session.AccountSelectedOwnerIntakeSourceReservationRepository.State; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.gamedesign.AssetSnapshot; import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; import net.firedevops.firemud.common.gamedesign.CommandSnapshot; import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.testcontainers.containers.GenericContainer; @@ -40,8 +81,9 @@ /** * Real Account creator/currentness, PostgreSQL finalization, immutable source participation and * pending source guards. Six-family content and the Game Design caller are stipulated test inputs; - * this is not producer transport, authenticated Entity/Automation retention, terminal settlement, - * activation, or runtime proof. + * the settlement case supplies explicitly synthetic upstream Automation terminal evidence (with no + * authentication proof) and proves real Account storage only, not producer transport or peer + * authentication, activation, or runtime behavior. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -217,6 +259,13 @@ void finalizesBothOwnersExactlyAndKeepsTheirFullSourceVectorsPending() throws Ex issued.environment())); assertThat(f.tx(() -> repository.abortSourceRead(abortedScope).state())) .isEqualTo(State.ABORTED); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + abortedScope.operationId()) + .get(0, Boolean.class)) + .isFalse(); var abortedContent = content(abortedScope, "stipulated-aborted"); assertThatThrownBy( () -> @@ -248,6 +297,258 @@ void finalizesBothOwnersExactlyAndKeepsTheirFullSourceVectorsPending() throws Ex } } + @Test + void commitsExactAutomationEmptySettlementAndReleasesOnlyThatOperation() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservationService = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var bindings = new ArrayList(); + var terminals = new ArrayList(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + UUID.randomUUID()) + .get(0, Boolean.class)) + .isTrue(); + + for (int index = 0; index < 2; index++) { + UUID requestId = UUID.randomUUID(); + var scope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + requestId, + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); + var content = content(scope, "automation-settlement-" + index); + var binding = + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); + bindings.add(binding); + terminals.add(terminalEvidence(binding, 9001L + index, 9002L + index)); + } + + var firstBinding = bindings.getFirst(); + var secondBinding = bindings.getLast(); + var firstTerminal = terminals.getFirst(); + assertThat(f.tx(() -> repository.findSettlement(firstBinding).isEmpty())).isTrue(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + firstBinding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + + var writerBeforeSettlement = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), firstBinding.sources(), new byte[] {3}); + assertThat(f.tx(() -> f.fences.requestSourceChange(writerBeforeSettlement))) + .isFalse(); + + var committed = f.tx(() -> repository.settleCommittedEmpty(firstTerminal)); + assertThat(committed.authorizationBinding().canonicalBytes()) + .isEqualTo(firstBinding.canonicalBytes()); + assertThat(committed.terminalEvidence().receipt().canonicalBytes()) + .isEqualTo(firstTerminal.receipt().canonicalBytes()); + var stored = + f.dsl.fetchOne( + "SELECT * FROM account_selected_owner_intake_settlements WHERE operation_id = ?", + firstBinding.operationId()); + assertThat(stored.get("receipt_bytes", byte[].class)).isEqualTo(committed.canonicalBytes()); + assertThat(stored.get("receipt_digest", String.class)).isEqualTo(committed.digest()); + assertThat(stored.get("terminal_receipt_bytes", byte[].class)) + .isEqualTo(firstTerminal.receipt().canonicalBytes()); + assertThat(stored.get("terminal_read_request_id", UUID.class)) + .isEqualTo(firstTerminal.request().readRequestId()); + + var exactReadback = f.tx(() -> repository.findSettlement(firstBinding).orElseThrow()); + assertThat(exactReadback.canonicalBytes()).isEqualTo(committed.canonicalBytes()); + f.tx( + () -> { + repository.readFinalAuthorization(firstBinding); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.readHeldFinalAuthorization(firstBinding); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no longer held"); + + var freshRead = + new AutomationSelectedSourceIntakeTerminalReadEvidence( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create( + "test", firstBinding), + firstTerminal.receipt()); + assertThat(freshRead.request().readRequestId()) + .isNotEqualTo(firstTerminal.request().readRequestId()); + var retry = f.tx(() -> repository.settleCommittedEmpty(freshRead)); + assertThat(retry.canonicalBytes()).isEqualTo(committed.canonicalBytes()); + assertThat( + f.dsl + .fetchSingle( + "SELECT terminal_read_request_id FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + firstBinding.operationId()) + .get(0, UUID.class)) + .isEqualTo(firstTerminal.request().readRequestId()); + var changedReceipt = terminalEvidence(firstBinding, 9101L, 9102L); + assertThatThrownBy(() -> f.tx(() -> repository.settleCommittedEmpty(changedReceipt))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed Automation owner terminal receipt"); + + var changedSources = new ArrayList<>(firstBinding.sources()); + var originalSource = changedSources.getFirst(); + changedSources.set( + 0, + new DraftAuthorizationFenceBinding.SourceEvidence( + originalSource.kind(), + originalSource.scopeId(), + originalSource.generation(), + originalSource.sourceVersion(), + originalSource.checkpointStream(), + originalSource.checkpointSequence(), + new byte[] {99})); + var changedBinding = + new SelectedOwnerIntakeAuthorizationBinding(firstBinding.content(), changedSources); + var changedBindingEvidence = terminalEvidence(changedBinding, 9201L, 9202L); + assertThatThrownBy(() -> f.tx(() -> repository.settleCommittedEmpty(changedBindingEvidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Original finalized owner authorization absent or changed"); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE account_selected_owner_intake_settlements " + + "SET receipt_digest = ? WHERE operation_id = ?", + DraftAuthorizationFenceBinding.digest(new byte[] {1}), + firstBinding.operationId())) + .isInstanceOf(RuntimeException.class); + assertThat( + f.dsl + .fetchSingle( + "SELECT receipt_bytes FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + firstBinding.operationId()) + .get(0, byte[].class)) + .isEqualTo(committed.canonicalBytes()); + + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + firstBinding.operationId()) + .get(0, Boolean.class)) + .isFalse(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + secondBinding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + var writerWhileOtherOperationHeld = writerBeforeSettlement; + assertThat(f.tx(() -> f.fences.requestSourceChange(writerWhileOtherOperationHeld))) + .isFalse(); + + var settlementInserted = new CountDownLatch(1); + var allowSettlementCommit = new CountDownLatch(1); + var writerStarted = new CountDownLatch(1); + var writerBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var settling = + executor.submit( + () -> + f.transactions.execute( + ignored -> { + var result = repository.settleCommittedEmpty(terminals.getLast()); + settlementInserted.countDown(); + awaitLatch(allowSettlementCommit); + return result; + })); + assertThat(settlementInserted.await(10, TimeUnit.SECONDS)).isTrue(); + + var waitingWriter = + executor.submit( + () -> + f.transactions.execute( + ignored -> { + writerBackendPid.set( + f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + writerStarted.countDown(); + return f.fences.requestSourceChange(writerWhileOtherOperationHeld); + })); + assertThat(writerStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(writerBackendPid.get()).isPositive(); + awaitSourceLockWait(f.dsl, writerBackendPid.get()); + assertThat(waitingWriter.isDone()).isFalse(); + + allowSettlementCommit.countDown(); + assertThat(settling.get(10, TimeUnit.SECONDS).authorizationBinding().canonicalBytes()) + .isEqualTo(secondBinding.canonicalBytes()); + assertThat(waitingWriter.get(10, TimeUnit.SECONDS)).isTrue(); + } finally { + allowSettlementCommit.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + secondBinding.operationId()) + .get(0, Boolean.class)) + .isFalse(); + assertThat( + f.tx(() -> f.fences.sourceMutationPermitted(writerWhileOtherOperationHeld))) + .isTrue(); + + String settlementGuard = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('account_selected_owner_intake_settlement_guard()'::regprocedure)") + .get(0, String.class); + assertThat(settlementGuard) + .contains( + "ORDER BY account_publication_authorization_source_sort_key(lock_row.source_key)", + "FOR UPDATE OF lock_row"); + } + } + @Test void postgresRejectsChangedNamespaceUnknownFamilyAndSelectedScopeEvidence() throws Exception { try (var fixture = @@ -497,17 +798,19 @@ private static void settleOriginal( issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); f.tx( () -> { - f.fences.recordOwnerReadback( - original, - new DraftAuthorizationFenceBinding.OwnerReadback( - DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, - DraftAuthorizationFenceBinding.Outcome.COMMITTED, - original.operationId(), - original.commitId(), - original.fenceId(), - original.inputDigest(), - original.canonicalBytes(), - new byte[] {1})); + for (var owner : original.requiredOwners()) { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + } return null; }); } @@ -529,7 +832,7 @@ private static SelectedOwnerIntakeSourceContent content( "genesisReceiptId", genesis.toString(), "manifestJson", GameplayRuleManifest.explicitEmpty().canonicalJson(), "entries", List.of()))); - var template = new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()); + var template = templateSnapshot(scope.owner(), selected, genesis); var snapshots = Map.of( "COMMAND", @@ -569,6 +872,278 @@ private static SelectedOwnerIntakeSourceContent content( bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); } + private static TemplateConfigSourceSnapshot templateSnapshot( + Owner owner, DraftCommitBinding selected, UUID genesis) { + if (owner != Owner.AUTOMATION_SCRIPTING) { + return new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()); + } + var inventory = + AutomationAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"); + String payload = TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory); + DraftCommitBinding authored = + DraftCommitBinding.create( + selected.target(), + UUID.randomUUID(), + UUID.randomUUID(), + "synthetic-template-config-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + selected.target().canonicalVersionId().toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + TemplateConfigOwnerSourceInventoryDeclaration declaration = + TemplateConfigSourceValues.mutations(authored).stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .findFirst() + .orElseThrow(); + return new TemplateConfigSourceSnapshot( + selected, "0", null, genesis, List.of(), List.of(declaration)); + } + + private static AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence( + SelectedOwnerIntakeAuthorizationBinding binding, long localTenantKey, long localVersionKey) { + var freeze = freezeEvidence(binding); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create(binding.targetNamespace(), binding, freeze); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freeze, publicInventory(freeze)); + var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory); + var inputs = new SelectedOwnerEmptySourceInputs(binding, worldEvidence); + var receipt = + AutomationEmptySelectedSourceIntakeReceipt.create( + inputs, + localTenantKey, + localVersionKey, + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + binding.targetNamespace(), binding, freeze), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + OffsetDateTime.parse("2026-10-10T00:00:00Z")); + return new AutomationSelectedSourceIntakeTerminalReadEvidence( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create( + binding.targetNamespace(), binding), + receipt); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + SelectedOwnerIntakeAuthorizationBinding binding) { + var selected = binding.selected(); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + binding.tenantId(), + binding.versionId(), + "settlement-publication-request", + "9", + "synthetic selected-owner settlement fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + binding.actorAccountId(), selection), + List.of(accountSource(binding.actorAccountId()))); + var request = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + binding.targetNamespace(), + binding.tenantId(), + binding.versionId(), + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + request, + UUID.randomUUID(), + 9, + UUID.randomUUID(), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + var closure = + new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 1), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(UUID.randomUUID(), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + closure); + var ownerScope = + new PublicOwnerScope( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + UUID.randomUUID(), + acknowledgement.intakeRequestId(), + UUID.randomUUID(), + "sha256:" + "1".repeat(64), + UUID.randomUUID(), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + ownerScope, + new SelectedApplication( + UUID.randomUUID(), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static SourceEvidence accountSource(UUID accountId) { + return new SourceEvidence( + SourceKind.ACCOUNT, + accountId.toString(), + null, + "1", + null, + null, + "synthetic-account-publication".getBytes(StandardCharsets.UTF_8)); + } + private static DraftCommitBinding selected(UUID tenant) { var target = new DraftCommitBinding.TargetProof( @@ -594,6 +1169,53 @@ private static DraftCommitBinding selected(UUID tenant) { "0"))); } + private static DraftCommitBinding selectedForSettlement(UUID tenant) { + var target = + new DraftCommitBinding.TargetProof( + tenant, UUID.randomUUID(), 17, "private", 11, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "genesis", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + } + + private static void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Expected concurrent settlement boundary"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted concurrent settlement boundary", interrupted); + } + } + + private static void awaitSourceLockWait(DSLContext dsl, int writerBackendPid) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + do { + if (Boolean.TRUE.equals( + dsl.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity" + + " WHERE pid = ? AND datname = current_database()" + + " AND wait_event_type = 'Lock'" + + " AND query LIKE '%account_draft_authorization_source_locks%')", + writerBackendPid) + .get(0, Boolean.class))) { + return; + } + Thread.sleep(10); + } while (System.nanoTime() < deadline); + throw new AssertionError("Source writer did not block on settlement-held source locks"); + } + private static T asGameDesign(java.util.function.Supplier action) { var context = io.grpc.Context.current() diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java index 893d4da95b..bd9dbc2025 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java @@ -66,7 +66,7 @@ void readsExactEntityAndAutomationBindingsInIndependentReadCommittedTransactions var binding = binding(owner); var request = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create("test", binding); asReader(binding, () -> service.requireHeld(request)); - verify(repository).readFinalAuthorization(binding); + verify(repository).readHeldFinalAuthorization(binding); } var definitions = ArgumentCaptor.forClass(TransactionDefinition.class); @@ -132,14 +132,14 @@ void distinguishesAbsentOrChangedAuthorizationFromUnavailableStorage() { org.mockito.Mockito.doThrow(new IllegalArgumentException("not available")) .when(repository) - .readFinalAuthorization(binding); + .readHeldFinalAuthorization(binding); asReader( binding, () -> assertCode(Status.Code.FAILED_PRECONDITION, () -> service.requireHeld(request))); org.mockito.Mockito.doThrow(new IllegalStateException("storage unavailable")) .when(repository) - .readFinalAuthorization(binding); + .readHeldFinalAuthorization(binding); asReader( binding, () -> assertCode(Status.Code.UNAVAILABLE, () -> service.requireHeld(request))); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java new file mode 100644 index 0000000000..8540514ed2 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java @@ -0,0 +1,506 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mocked Account transaction and owner-read ordering only; not genuine producer or SQL proof. */ +class AccountSelectedOwnerIntakeSettlementServiceTest { + private static final String NAMESPACE = "test"; + private static final SelectedOwnerIntakeAuthorizationBinding ORIGINAL = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void readsAutomationOutsideSqlThenCommitsAndReadsBackInIndependentTransactions() { + Harness harness = new Harness(NAMESPACE); + AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = ownerReceipt(ORIGINAL, "winner"); + AtomicReference stored = new AtomicReference<>(); + AtomicInteger settlementReads = new AtomicInteger(); + + doAnswer( + ignored -> { + assertWritableReadCommittedTransaction(); + harness.steps.add("validate-original-authorization"); + return null; + }) + .when(harness.repository) + .readFinalAuthorization(ORIGINAL); + when(harness.repository.findSettlement(ORIGINAL)) + .thenAnswer( + ignored -> { + assertWritableReadCommittedTransaction(); + int read = settlementReads.incrementAndGet(); + harness.steps.add(read == 1 ? "prior-settlement-lookup" : "post-commit-readback"); + return read == 1 ? Optional.empty() : Optional.of(stored.get()); + }); + when(harness.automationClient.read(any())) + .thenAnswer( + invocation -> { + assertNoSql(); + harness.steps.add("remote-automation-terminal-read"); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = + invocation.getArgument(0); + assertThat(request.binding().canonicalBytes()) + .containsExactly(ORIGINAL.canonicalBytes()); + assertThat(request.readRequestId()) + .isNotIn(ORIGINAL.operationId(), ORIGINAL.fenceId(), ORIGINAL.intakeRequestId()); + return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, ownerReceipt); + }); + when(harness.repository.settleCommittedEmpty(any())) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + harness.steps.add("commit-exact-terminal-settlement"); + AutomationSelectedSourceIntakeTerminalReadEvidence evidence = + invocation.getArgument(0); + assertThat(evidence.request().binding().canonicalBytes()) + .containsExactly(ORIGINAL.canonicalBytes()); + AccountSelectedOwnerIntakeSettlementReceipt receipt = + AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + stored.set(receipt); + return receipt; + }); + + AccountSelectedOwnerIntakeSettlementReceipt actual = + asGameDesign(() -> harness.service.settle(ORIGINAL)); + + assertThat(actual).isSameAs(stored.get()); + assertThat(actual.authorizationBinding().canonicalBytes()) + .containsExactly(ORIGINAL.canonicalBytes()); + assertThat(actual.terminalEvidence().receipt().canonicalBytes()) + .containsExactly(ownerReceipt.canonicalBytes()); + assertThat(harness.steps) + .containsExactly( + "validate-original-authorization", + "prior-settlement-lookup", + "remote-automation-terminal-read", + "commit-exact-terminal-settlement", + "post-commit-readback"); + assertThat(harness.transactions.begins).isEqualTo(3); + assertThat(harness.transactions.commits).isEqualTo(3); + verify(harness.automationClient).read(any()); + verify(harness.repository).settleCommittedEmpty(any()); + assertNoSql(); + } + + @Test + void priorExactSettlementIsReturnedWithoutAutomationContactOrSecondCommit() { + Harness harness = new Harness(NAMESPACE); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, ORIGINAL); + AccountSelectedOwnerIntakeSettlementReceipt prior = + AccountSelectedOwnerIntakeSettlementReceipt.create( + new AutomationSelectedSourceIntakeTerminalReadEvidence( + request, ownerReceipt(ORIGINAL, "retained"))); + when(harness.repository.findSettlement(ORIGINAL)).thenReturn(Optional.of(prior)); + + AccountSelectedOwnerIntakeSettlementReceipt recovered = + asGameDesign(() -> harness.service.settle(ORIGINAL)); + + assertThat(recovered).isSameAs(prior); + assertThat(harness.transactions.begins).isEqualTo(1); + assertThat(harness.transactions.commits).isEqualTo(1); + verify(harness.repository).readFinalAuthorization(ORIGINAL); + verify(harness.repository).findSettlement(ORIGINAL); + verifyNoInteractions(harness.automationClient); + verify(harness.repository, never()).settleCommittedEmpty(any()); + } + + @Test + void freshReadCorrelationKeepsAnAlreadyCommittedImmutableOwnerReceiptWinner() { + Harness harness = new Harness(NAMESPACE); + AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = ownerReceipt(ORIGINAL, "same-owner"); + AtomicInteger settlementReads = new AtomicInteger(); + AtomicReference remoteRequest = + new AtomicReference<>(); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request winnerRequest = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, ORIGINAL); + AccountSelectedOwnerIntakeSettlementReceipt winner = + AccountSelectedOwnerIntakeSettlementReceipt.create( + new AutomationSelectedSourceIntakeTerminalReadEvidence(winnerRequest, ownerReceipt)); + when(harness.repository.findSettlement(ORIGINAL)) + .thenAnswer( + ignored -> + settlementReads.incrementAndGet() == 1 ? Optional.empty() : Optional.of(winner)); + when(harness.automationClient.read(any())) + .thenAnswer( + invocation -> { + assertNoSql(); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = + invocation.getArgument(0); + remoteRequest.set(request); + return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, ownerReceipt); + }); + when(harness.repository.settleCommittedEmpty(any())) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + AutomationSelectedSourceIntakeTerminalReadEvidence evidence = + invocation.getArgument(0); + assertThat(evidence.request().readRequestId()) + .isEqualTo(remoteRequest.get().readRequestId()); + return winner; + }); + + AccountSelectedOwnerIntakeSettlementReceipt recovered = + asGameDesign(() -> harness.service.settle(ORIGINAL)); + + assertThat(remoteRequest.get().readRequestId()).isNotEqualTo(winnerRequest.readRequestId()); + assertThat(recovered).isSameAs(winner); + assertThat(recovered.terminalEvidence().request().readRequestId()) + .isEqualTo(winnerRequest.readRequestId()); + assertThat(recovered.terminalEvidence().receipt().canonicalBytes()) + .containsExactly(ownerReceipt.canonicalBytes()); + assertThat(harness.transactions.begins).isEqualTo(3); + } + + @Test + void unavailableNullAndChangedOwnerTerminalEvidenceNeverReachesAccountSettlement() { + Harness unavailable = preparedHarness(); + when(unavailable.automationClient.read(any())) + .thenThrow(Status.UNAVAILABLE.withDescription("offline").asRuntimeException()); + assertStatus( + Status.Code.UNAVAILABLE, () -> asGameDesign(() -> unavailable.service.settle(ORIGINAL))); + verify(unavailable.repository, never()).settleCommittedEmpty(any()); + + Harness missing = preparedHarness(); + when(missing.automationClient.read(any())).thenReturn(null); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> missing.service.settle(ORIGINAL))); + verify(missing.repository, never()).settleCommittedEmpty(any()); + + Harness changedEcho = preparedHarness(); + AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = + ownerReceipt(ORIGINAL, "changed-echo"); + when(changedEcho.automationClient.read(any())) + .thenAnswer( + invocation -> { + var request = + (AutomationSelectedSourceIntakeTerminalReadEvidence.Request) + invocation.getArgument(0); + var changed = + new AutomationSelectedSourceIntakeTerminalReadEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + UUID.randomUUID(), + request.binding()); + return new AutomationSelectedSourceIntakeTerminalReadEvidence(changed, ownerReceipt); + }); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> changedEcho.service.settle(ORIGINAL))); + verify(changedEcho.repository, never()).settleCommittedEmpty(any()); + + Harness corruptReceipt = preparedHarness(); + AutomationEmptySelectedSourceIntakeReceipt badReceipt = + ownerReceipt(ORIGINAL, "corrupt-digest"); + when(badReceipt.receiptDigest()).thenReturn("sha256:" + "f".repeat(64)); + when(corruptReceipt.automationClient.read(any())) + .thenAnswer( + invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), badReceipt)); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> corruptReceipt.service.settle(ORIGINAL))); + verify(corruptReceipt.repository, never()).settleCommittedEmpty(any()); + + assertThat(unavailable.transactions.begins).isEqualTo(1); + assertThat(missing.transactions.begins).isEqualTo(1); + assertThat(changedEcho.transactions.begins).isEqualTo(1); + assertThat(corruptReceipt.transactions.begins).isEqualTo(1); + } + + @Test + void failedSettlementCommitDoesNotPretendToHaveReadBackTheUnknownOutcome() { + Harness harness = preparedHarness(); + AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = + ownerReceipt(ORIGINAL, "commit-failure"); + when(harness.automationClient.read(any())) + .thenAnswer( + invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), ownerReceipt)); + when(harness.repository.settleCommittedEmpty(any())) + .thenAnswer( + invocation -> + AccountSelectedOwnerIntakeSettlementReceipt.create(invocation.getArgument(0))); + harness.transactions.failCommitAt = 2; + + assertThatThrownBy(() -> asGameDesign(() -> harness.service.settle(ORIGINAL))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("synthetic unknown commit"); + + verify(harness.repository).findSettlement(ORIGINAL); + verify(harness.repository, times(1)).findSettlement(ORIGINAL); + verify(harness.repository).settleCommittedEmpty(any()); + assertThat(harness.transactions.begins).isEqualTo(2); + assertThat(harness.transactions.commits).isEqualTo(2); + } + + @Test + void missingOrDifferentLookupOnlyReadbackRemainsUnresolved() { + Harness missing = preparedHarness(); + AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = ownerReceipt(ORIGINAL, "readback"); + AccountSelectedOwnerIntakeSettlementReceipt committed = + AccountSelectedOwnerIntakeSettlementReceipt.create( + new AutomationSelectedSourceIntakeTerminalReadEvidence( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create( + NAMESPACE, ORIGINAL), + ownerReceipt)); + when(missing.automationClient.read(any())) + .thenAnswer( + invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), ownerReceipt)); + when(missing.repository.settleCommittedEmpty(any())).thenReturn(committed); + when(missing.repository.findSettlement(ORIGINAL)) + .thenReturn(Optional.empty(), Optional.empty()); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> missing.service.settle(ORIGINAL))); + assertThat(missing.transactions.begins).isEqualTo(3); + + Harness changed = preparedHarness(); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request remoteRequest = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, ORIGINAL); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request otherRequest = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, ORIGINAL); + AccountSelectedOwnerIntakeSettlementReceipt exactCommit = + AccountSelectedOwnerIntakeSettlementReceipt.create( + new AutomationSelectedSourceIntakeTerminalReadEvidence(remoteRequest, ownerReceipt)); + AccountSelectedOwnerIntakeSettlementReceipt substitutedReadback = + AccountSelectedOwnerIntakeSettlementReceipt.create( + new AutomationSelectedSourceIntakeTerminalReadEvidence(otherRequest, ownerReceipt)); + when(changed.automationClient.read(any())) + .thenAnswer( + invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), ownerReceipt)); + when(changed.repository.settleCommittedEmpty(any())).thenReturn(exactCommit); + when(changed.repository.findSettlement(ORIGINAL)) + .thenReturn(Optional.empty(), Optional.of(substitutedReadback)); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> changed.service.settle(ORIGINAL))); + assertThat(changed.transactions.begins).isEqualTo(3); + } + + @Test + void wrongPeerEndUserAmbientSqlAndNonAutomationScopeAreRejectedBeforeRepositoryAccess() { + Harness harness = new Harness(NAMESPACE); + assertStatus(Status.Code.UNAUTHENTICATED, () -> harness.service.settle(ORIGINAL)); + + asPeer( + peer("test", "entity-management-service"), + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(ORIGINAL))); + asPeer( + peer("other", "game-design-service"), + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(ORIGINAL))); + + SessionContext.setContext("123", List.of(), Map.of()); + asGameDesign( + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(ORIGINAL))); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + asGameDesign( + () -> + assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(ORIGINAL))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + asGameDesign( + () -> + assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(ORIGINAL))); + TransactionSynchronizationManager.clear(); + + SelectedOwnerIntakeAuthorizationBinding entityBinding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + asGameDesign( + () -> + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(entityBinding))); + + Harness wrongBindingNamespace = new Harness("other-runtime"); + asPeer( + peer("other-runtime", "game-design-service"), + () -> + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> wrongBindingNamespace.service.settle(ORIGINAL))); + + verifyNoInteractions(harness.repository, harness.automationClient); + verifyNoInteractions(wrongBindingNamespace.repository, wrongBindingNamespace.automationClient); + assertThat(harness.transactions.begins).isZero(); + assertThat(wrongBindingNamespace.transactions.begins).isZero(); + } + + private static Harness preparedHarness() { + Harness harness = new Harness(NAMESPACE); + when(harness.repository.findSettlement(ORIGINAL)).thenReturn(Optional.empty()); + return harness; + } + + private static AutomationEmptySelectedSourceIntakeReceipt ownerReceipt( + SelectedOwnerIntakeAuthorizationBinding binding, String marker) { + AutomationEmptySelectedSourceIntakeReceipt receipt = + Mockito.mock(AutomationEmptySelectedSourceIntakeReceipt.class); + byte[] bytes = + ("synthetic canonical COMMITTED_EMPTY receipt " + marker).getBytes(StandardCharsets.UTF_8); + when(receipt.targetNamespace()).thenReturn(binding.targetNamespace()); + when(receipt.operationId()).thenReturn(binding.operationId()); + when(receipt.fenceId()).thenReturn(binding.fenceId()); + when(receipt.intakeRequestId()).thenReturn(binding.intakeRequestId()); + when(receipt.canonicalTenantId()).thenReturn(binding.tenantId()); + when(receipt.canonicalVersionId()).thenReturn(binding.versionId()); + when(receipt.selectedCommitId()).thenReturn(binding.selected().commitId()); + when(receipt.authorizationBindingBytes()).thenReturn(binding.canonicalBytes()); + when(receipt.authorizationBindingDigest()).thenReturn(binding.digest()); + when(receipt.canonicalBytes()).thenReturn(bytes); + when(receipt.receiptDigest()).thenReturn(DraftAuthorizationFenceBinding.digest(bytes)); + when(receipt.outcome()).thenReturn("COMMITTED_EMPTY"); + return receipt; + } + + private static void assertWritableReadCommittedTransaction() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(Connection.TRANSACTION_READ_COMMITTED); + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static void assertStatus(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void asGameDesign(Runnable action) { + asPeer(peer(NAMESPACE, "game-design-service"), action); + } + + private static T asGameDesign(java.util.function.Supplier action) { + return asPeer(peer(NAMESPACE, "game-design-service"), action); + } + + private static void asPeer(GrpcPeerIdentity peer, Runnable action) { + asPeer( + peer, + () -> { + action.run(); + return null; + }); + } + + private static T asPeer(GrpcPeerIdentity peer, java.util.function.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 GrpcPeerIdentity peer(String namespace, String service) { + String uri = "spiffe://firemud/ns/" + namespace + "/sa/" + service; + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static final class Harness { + final AccountSelectedOwnerIntakeSourceReservationRepository repository = + Mockito.mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); + final AutomationSelectedSourceIntakeTerminalReadClient automationClient = + Mockito.mock(AutomationSelectedSourceIntakeTerminalReadClient.class); + final OwnerTransactions transactions = new OwnerTransactions(); + final List steps = new ArrayList<>(); + final AccountSelectedOwnerIntakeSettlementService service; + + Harness(String namespace) { + service = + new AccountSelectedOwnerIntakeSettlementService( + repository, automationClient, transactions, namespace); + } + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + int failCommitAt = -1; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertNoSql(); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + if (commits == failCommitAt) { + throw new IllegalStateException("synthetic unknown commit"); + } + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java index 5f321fb4fc..194de5fc55 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepositoryTest.java @@ -33,6 +33,18 @@ void everyReservationRecoveryAbortAndCurrentnessReadRequiresAnOwnerTransaction() assertThatThrownBy(() -> repository.readSourceScope(null, null)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.readFinalAuthorization(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.readHeldFinalAuthorization(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.findSettlement(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); + assertThatThrownBy(() -> repository.settleCommittedEmpty(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account owner transaction"); verifyNoInteractions(dsl); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java index 44b3f51cca..ee268a7717 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java @@ -49,7 +49,7 @@ void readsExactEntityAndAutomationBindingsInIndependentReadCommittedTransactions var request = SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create("test", binding); asWorldReader(() -> service.requireHeld(request)); - verify(repository).readFinalAuthorization(binding); + verify(repository).readHeldFinalAuthorization(binding); } var definitions = ArgumentCaptor.forClass(TransactionDefinition.class); @@ -123,13 +123,13 @@ void distinguishesAbsentOrChangedAuthorizationFromUnavailableStorage() { org.mockito.Mockito.doThrow(new IllegalArgumentException("not available")) .when(repository) - .readFinalAuthorization(binding); + .readHeldFinalAuthorization(binding); asWorldReader( () -> assertCode(Status.Code.FAILED_PRECONDITION, () -> service.requireHeld(request))); org.mockito.Mockito.doThrow(new IllegalStateException("storage unavailable")) .when(repository) - .readFinalAuthorization(binding); + .readHeldFinalAuthorization(binding); asWorldReader(() -> assertCode(Status.Code.UNAVAILABLE, () -> service.requireHeld(request))); } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java index 5595bc341f..a43c790c43 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import org.jooq.DSLContext; import org.jooq.Record; @@ -57,6 +58,31 @@ public Optional read( return readValidated(dsl, targetNamespace, intakeRequestId); } + /** + * Reads the original committed receipt for an exact finalized Account authorization. A missing + * result remains absence; it is never converted into an abort or another terminal value. + */ + public Optional readCommittedTerminal( + SelectedOwnerIntakeAuthorizationBinding originalBinding) { + Objects.requireNonNull(originalBinding, "original Account authorization binding is required"); + if (originalBinding.owner() != Owner.AUTOMATION_SCRIPTING + || !"account-automation-intake-authorization/v1".equals(originalBinding.schema()) + || !"AUTOMATION_INTAKE_RETENTION".equals(originalBinding.purpose())) { + throw new IllegalArgumentException("Exact original Automation authorization is required"); + } + requireNoAmbientOwnerSql("Automation source terminal read"); + requireReadKey(originalBinding.targetNamespace(), originalBinding.intakeRequestId()); + var receipt = + readValidated(dsl, originalBinding.targetNamespace(), originalBinding.intakeRequestId()); + if (receipt.isPresent() + && !Arrays.equals( + originalBinding.canonicalBytes(), receipt.orElseThrow().authorizationBindingBytes())) { + throw new IntakeConflictException( + "Automation committed receipt differs from the complete original authorization"); + } + return receipt; + } + /** * Persists one fresh empty-source receipt in an independent local transaction, then reads it back * after commit using a separate non-transactional owner read. diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java index d6ec281e80..17d7c30114 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java @@ -6,6 +6,7 @@ import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient; diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java new file mode 100644 index 0000000000..8c4b867d75 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java @@ -0,0 +1,80 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone Account-only lookup over Automation's immutable selected-source receipt. */ +public final class AutomationEmptySelectedSourceIntakeTerminalReadService { + private final AutomationEmptySelectedSourceIntakeRepository repository; + private final String namespace; + + public AutomationEmptySelectedSourceIntakeTerminalReadService( + AutomationEmptySelectedSourceIntakeRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical namespace required"); + } + this.namespace = namespace; + } + + /** Called by the transport before request decoding so unauthorized peers never reach a lookup. */ + void requireAuthenticatedAccountCaller() { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + if (!namespace.equals(peer.namespace()) + || !"account-service".equals(peer.service()) + || !("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } + + public AutomationSelectedSourceIntakeTerminalReadEvidence read( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request) { + requireAuthenticatedAccountCaller(); + Objects.requireNonNull(request, "terminal-read request is required"); + if (!namespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + + final AutomationEmptySelectedSourceIntakeReceipt receipt; + try { + receipt = + repository + .readCommittedTerminal(request.binding()) + .orElseThrow(() -> Status.NOT_FOUND.asRuntimeException()); + } catch (StatusRuntimeException denied) { + throw denied; + } catch (AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException changed) { + throw Status.ALREADY_EXISTS + .withDescription("Automation receipt differs from the complete original authorization") + .asRuntimeException(); + } catch (RuntimeException corrupt) { + throw Status.DATA_LOSS + .withDescription("Automation committed receipt is invalid") + .asRuntimeException(); + } + + try { + return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, receipt); + } catch (IllegalArgumentException invalid) { + throw Status.DATA_LOSS + .withDescription("Automation receipt differs from its original order") + .asRuntimeException(); + } + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcService.java new file mode 100644 index 0000000000..a723e72dc9 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcService.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadGrpcCodec; + +/** No automatic registration; authenticate Account before parsing caller-carried evidence. */ +public final class AutomationSelectedSourceIntakeTerminalReadGrpcService + extends AutomationSelectedSourceIntakeTerminalReadServiceGrpc + .AutomationSelectedSourceIntakeTerminalReadServiceImplBase { + private final AutomationEmptySelectedSourceIntakeTerminalReadService owner; + + public AutomationSelectedSourceIntakeTerminalReadGrpcService( + AutomationEmptySelectedSourceIntakeTerminalReadService owner) { + this.owner = Objects.requireNonNull(owner, "terminal-read owner is required"); + } + + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest request, + StreamObserver observer) { + try { + owner.requireAuthenticatedAccountCaller(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final net.firedevops.firemud.common.automation.sourceintake + .AutomationSelectedSourceIntakeTerminalReadEvidence.Request + decoded; + try { + decoded = AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + var evidence = owner.read(decoded); + observer.onNext(AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toResponse(evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + } catch (RuntimeException invalid) { + observer.onError(Status.DATA_LOSS.asRuntimeException()); + } + } +} diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java index 28adae0e52..ecbd829169 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java @@ -148,18 +148,19 @@ void migrationSeedsLegacyKeysAndGuardsAllThreeAuthoredSourceFamilies() { @Test void securityDefinerFunctionsUseTheExactInstalledSchemaInTheirFixedSearchPath() { assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM pg_proc AS p " - + "JOIN pg_namespace AS n ON n.oid = p.pronamespace " - + "WHERE n.nspname = ? " - + "AND p.proname IN (" - + "'automation_require_source_numeric_key_unreserved', " - + "'automation_guard_authored_source_row', " - + "'automation_reject_authored_source_truncate', " - + "'automation_reject_empty_source_intake_mutation') " - + "AND p.prosecdef " - + "AND p.proconfig @> ARRAY[format('search_path=pg_catalog, %I', ?)]", - Integer.class, schema, schema)) + dsl.fetchSingle( + "SELECT COUNT(*) FROM pg_proc AS p " + + "JOIN pg_namespace AS n ON n.oid = p.pronamespace " + + "WHERE n.nspname = ? " + + "AND p.proname IN (" + + "'automation_require_source_numeric_key_unreserved', " + + "'automation_guard_authored_source_row', " + + "'automation_reject_authored_source_truncate', " + + "'automation_reject_empty_source_intake_mutation') " + + "AND p.prosecdef " + + "AND p.proconfig @> ARRAY[format('search_path=pg_catalog, %I', ?)]", + schema, schema) + .get(0, Integer.class)) .isEqualTo(4); } diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java index 3a565487bf..3cb23e8d72 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java @@ -6,8 +6,8 @@ import java.nio.file.Path; import java.util.Map; import java.util.UUID; -import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -183,6 +183,10 @@ void retainsCanonicalEmptyCensusAndExactReadbackAcrossCorrelationIndependentRetr var readBack = repository.read(first.targetNamespace(), first.intakeRequestId()).orElseThrow(); assertThat(readBack.canonicalBytes()).containsExactly(first.canonicalBytes()); assertThat(readBack.receiptDigest()).isEqualTo(first.receiptDigest()); + var terminalRead = repository.readCommittedTerminal(fixture.authorization()).orElseThrow(); + assertThat(terminalRead.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(terminalRead.authorizationBindingBytes()) + .containsExactly(fixture.authorization().canonicalBytes()); var retry = AutomationEmptySelectedSourceIntakePostgresFixture.withFreshWorldReadCorrelation(fixture); @@ -199,6 +203,9 @@ void retainsCanonicalEmptyCensusAndExactReadbackAcrossCorrelationIndependentRetr .isEqualTo(fixture.authorization().intakeRequestId()); assertThat(altered.authorization().canonicalBytes()) .isNotEqualTo(fixture.authorization().canonicalBytes()); + assertThatThrownBy(() -> repository.readCommittedTerminal(altered.authorization())) + .isInstanceOf(AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException.class) + .hasMessageContaining("complete original authorization"); String alteredDigest = requestDigest(altered); assertThat(alteredDigest).isNotEqualTo(requestDigest); assertThatThrownBy(() -> repository.retainFresh(altered.inputs(), alteredDigest)) @@ -222,6 +229,40 @@ void retainsCanonicalEmptyCensusAndExactReadbackAcrossCorrelationIndependentRetr first.intakeRequestId()); assertThat(unchangedReceipt).isNotNull(); assertThat(unchangedReceipt.get(0, byte[].class)).containsExactly(first.canonicalBytes()); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE automation_empty_selected_source_receipt SET receipt_bytes = ? " + + "WHERE target_namespace = ? AND intake_request_id = ?", + first.canonicalBytes(), + first.targetNamespace(), + first.intakeRequestId())) + .rootCause() + .hasMessageContaining("Automation empty-source intake records are immutable"); + + byte[] corruptBytes = first.canonicalBytes(); + corruptBytes[0] ^= 1; + // The isolated test owner bypasses only V5's immutable receipt-row trigger to model corruption. + dsl.execute( + "ALTER TABLE automation_empty_selected_source_receipt " + + "DISABLE TRIGGER trg_automation_empty_source_receipt_immutable"); + try { + assertThat( + dsl.execute( + "UPDATE automation_empty_selected_source_receipt SET receipt_bytes = ? " + + "WHERE target_namespace = ? AND intake_request_id = ?", + corruptBytes, + first.targetNamespace(), + first.intakeRequestId())) + .isEqualTo(1); + } finally { + dsl.execute( + "ALTER TABLE automation_empty_selected_source_receipt " + + "ENABLE TRIGGER trg_automation_empty_source_receipt_immutable"); + } + assertThatThrownBy(() -> repository.readCommittedTerminal(fixture.authorization())) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java index c2b340aa3a..1ffe6fb46a 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java @@ -18,12 +18,12 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; -import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient; import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java index 5de777a0ab..25dc6fd16e 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java @@ -17,6 +17,7 @@ import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java new file mode 100644 index 0000000000..c6291ba1b3 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java @@ -0,0 +1,253 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mocked owner-storage and peer tests do not establish physical Automation owner proof. */ +class AutomationSelectedSourceIntakeTerminalReadServiceTest { + private static final String NAMESPACE = "example"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/example/sa/account-service"; + private static final byte[] BINDING_BYTES = {1, 2, 3, 4}; + + @AfterEach + void clearContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void exactRetriesReturnOnlyTheOriginalCommittedEmptyReceipt() { + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var binding = binding(); + var receipt = receipt(BINDING_BYTES); + when(repository.readCommittedTerminal(binding)).thenReturn(Optional.of(receipt)); + var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(); + var previous = accountContext.attach(); + try { + var first = service.read(request(binding)); + var retry = service.read(request(binding)); + + assertThat(first.receipt()).isSameAs(receipt); + assertThat(retry.receipt()).isSameAs(receipt); + assertThat(first.request().readRequestId()).isNotEqualTo(retry.request().readRequestId()); + verify(repository, org.mockito.Mockito.times(2)).readCommittedTerminal(binding); + } finally { + accountContext.detach(previous); + } + } + + @Test + void missingReceiptIsNotConvertedToTerminalEvidence() { + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var binding = binding(); + when(repository.readCommittedTerminal(binding)).thenReturn(Optional.empty()); + var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(); + var previous = accountContext.attach(); + try { + assertThatThrownBy(() -> service.read(request(binding))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); + } finally { + accountContext.detach(previous); + } + } + + @Test + void rejectsChangedTupleAndCorruptStoredReceipt() { + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var binding = binding(); + when(repository.readCommittedTerminal(binding)) + .thenThrow( + new AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException( + "changed exact authorization")); + var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(); + var previous = accountContext.attach(); + try { + assertThatThrownBy(() -> service.read(request(binding))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); + + doThrow(new IllegalArgumentException("corrupt canonical receipt")) + .when(repository) + .readCommittedTerminal(binding); + assertThatThrownBy(() -> service.read(request(binding))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DATA_LOSS)); + } finally { + accountContext.detach(previous); + } + } + + @Test + void rejectsWrongPeerEndUserAndAmbientSqlBeforeRepositoryLookup() { + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var binding = binding(); + var request = request(binding); + var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + var wrongPeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/game-design-service", NAMESPACE, "game-design-service"); + var wrongContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer); + var previous = wrongContext.attach(); + try { + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } finally { + wrongContext.detach(previous); + } + + var accountContext = accountPeer(); + previous = accountContext.attach(); + try { + SessionContext.setContext("1001", List.of(), Map.of()); + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + TransactionSynchronizationManager.clearSynchronization(); + } finally { + accountContext.detach(previous); + } + verifyNoInteractions(repository); + } + + @Test + void transportAuthenticatesBeforeDecodingOrLookup() { + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var grpc = new AutomationSelectedSourceIntakeTerminalReadGrpcService(service); + var observedError = new AtomicReference(); + StreamObserver observer = + new StreamObserver<>() { + @Override + public void onNext(ReadSelectedSourceIntakeTerminalResponse value) { + throw new AssertionError("Unauthenticated caller received a response"); + } + + @Override + public void onError(Throwable error) { + observedError.set(error); + } + + @Override + public void onCompleted() { + throw new AssertionError("Unauthenticated caller completed a response"); + } + }; + + grpc.readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest.getDefaultInstance(), observer); + + assertThat(observedError.get()).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(observedError.get()).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(repository); + } + + private static SelectedOwnerIntakeAuthorizationBinding binding() { + var binding = mock(SelectedOwnerIntakeAuthorizationBinding.class); + when(binding.owner()) + .thenReturn( + net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + when(binding.targetNamespace()).thenReturn(NAMESPACE); + when(binding.schema()).thenReturn("account-automation-intake-authorization/v1"); + when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION"); + when(binding.canonicalBytes()).thenReturn(BINDING_BYTES.clone()); + when(binding.operationId()).thenReturn(UUID.randomUUID()); + when(binding.fenceId()).thenReturn(UUID.randomUUID()); + when(binding.intakeRequestId()).thenReturn(UUID.randomUUID()); + return binding; + } + + private static AutomationSelectedSourceIntakeTerminalReadEvidence.Request request( + SelectedOwnerIntakeAuthorizationBinding binding) { + return AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, binding); + } + + private static AutomationEmptySelectedSourceIntakeReceipt receipt(byte[] bindingBytes) { + var receipt = mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(receipt.targetNamespace()).thenReturn(NAMESPACE); + when(receipt.authorizationBindingBytes()).thenReturn(bindingBytes.clone()); + when(receipt.outcome()).thenReturn("COMMITTED_EMPTY"); + return receipt; + } + + private static Context accountPeer() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity(ACCOUNT_URI, NAMESPACE, "account-service")); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java new file mode 100644 index 0000000000..7b3c87d1f2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java @@ -0,0 +1,210 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; + +/** Immutable Account record of one exact Automation {@code COMMITTED_EMPTY} terminal read. */ +public final class AccountSelectedOwnerIntakeSettlementReceipt { + public static final String DOMAIN = "account-selected-owner-intake-settlement/v1"; + public static final int MAX_BYTES = + 2 * SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES + + 64 * 1024; + + private final SelectedOwnerIntakeAuthorizationBinding authorizationBinding; + private final AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence; + private final byte[] canonicalBytes; + private final String digest; + + private AccountSelectedOwnerIntakeSettlementReceipt( + SelectedOwnerIntakeAuthorizationBinding authorizationBinding, + AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence) { + this.authorizationBinding = Objects.requireNonNull(authorizationBinding); + this.terminalEvidence = Objects.requireNonNull(terminalEvidence); + if (!Arrays.equals( + authorizationBinding.canonicalBytes(), + terminalEvidence.request().binding().canonicalBytes()) + || !Arrays.equals( + authorizationBinding.canonicalBytes(), + terminalEvidence.receipt().authorizationBindingBytes()) + || !authorizationBinding + .digest() + .equals(terminalEvidence.receipt().authorizationBindingDigest()) + || !"COMMITTED_EMPTY".equals(terminalEvidence.receipt().outcome())) { + throw new IllegalArgumentException( + "Automation terminal differs from the complete original Account authorization"); + } + this.canonicalBytes = encode(); + if (canonicalBytes.length > MAX_BYTES) { + throw new IllegalArgumentException( + "Account selected-owner settlement exceeds its size limit"); + } + this.digest = DraftAuthorizationFenceBinding.digest(canonicalBytes); + } + + public static AccountSelectedOwnerIntakeSettlementReceipt create( + AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence) { + Objects.requireNonNull(terminalEvidence, "Automation terminal evidence is required"); + return new AccountSelectedOwnerIntakeSettlementReceipt( + terminalEvidence.request().binding(), terminalEvidence); + } + + /** Strictly decodes the complete immutable Account binding and Automation terminal evidence. */ + public static AccountSelectedOwnerIntakeSettlementReceipt fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) { + throw new IllegalArgumentException( + "Stored Account selected-owner settlement size is invalid"); + } + byte[] stored = bytes.clone(); + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(DOMAIN); + if (!"1".equals(reader.text())) { + throw new IllegalArgumentException("Unsupported Account selected-owner settlement schema"); + } + byte[] bindingBytes = + bounded(reader.bytes(), SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES); + String bindingDigest = reader.text(); + var binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + if (!binding.digest().equals(bindingDigest)) { + throw new IllegalArgumentException("Retained Account authorization digest differs"); + } + + int terminalSchemaVersion = parseSchemaVersion(reader.text()); + String namespace = reader.text(); + String readRequestIdText = reader.text(); + DraftAuthorizationFenceBinding.canonicalUuid(readRequestIdText); + UUID readRequestId = UUID.fromString(readRequestIdText); + String intendedReader = reader.text(); + String purpose = reader.text(); + byte[] terminalBindingBytes = + bounded(reader.bytes(), SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES); + String terminalBindingDigest = reader.text(); + var terminalBinding = SelectedOwnerIntakeAuthorizationBinding.fromStored(terminalBindingBytes); + if (!binding.digest().equals(terminalBindingDigest) + || !Arrays.equals(bindingBytes, terminalBindingBytes)) { + throw new IllegalArgumentException("Automation terminal request changed the Account binding"); + } + var request = + new AutomationSelectedSourceIntakeTerminalReadEvidence.Request( + terminalSchemaVersion, namespace, readRequestId, terminalBinding); + if (!intendedReader.equals(request.intendedReader()) + || !purpose.equals(request.terminalReadPurpose())) { + throw new IllegalArgumentException("Automation terminal reader or purpose differs"); + } + + byte[] ownerReceiptBytes = + bounded(reader.bytes(), AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES); + String ownerReceiptDigest = reader.text(); + reader.requireEnd(); + var ownerReceipt = AutomationEmptySelectedSourceIntakeReceipt.fromStored(ownerReceiptBytes); + if (!ownerReceipt.receiptDigest().equals(ownerReceiptDigest)) { + throw new IllegalArgumentException("Automation terminal receipt digest differs"); + } + var evidence = new AutomationSelectedSourceIntakeTerminalReadEvidence(request, ownerReceipt); + var result = new AccountSelectedOwnerIntakeSettlementReceipt(binding, evidence); + if (!Arrays.equals(stored, result.canonicalBytes)) { + throw new IllegalArgumentException("Noncanonical Account selected-owner settlement"); + } + return result; + } + + public SelectedOwnerIntakeAuthorizationBinding authorizationBinding() { + return authorizationBinding; + } + + public AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence() { + return terminalEvidence; + } + + public UUID operationId() { + return authorizationBinding.operationId(); + } + + public String targetNamespace() { + return authorizationBinding.targetNamespace(); + } + + public byte[] ownerReceiptBytes() { + return terminalEvidence.receipt().canonicalBytes(); + } + + public String ownerReceiptDigest() { + return terminalEvidence.receipt().receiptDigest(); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + /** Correlation is retained on first settlement, but is not part of owner receipt identity. */ + public boolean sameImmutableOwnerReceipt( + AutomationSelectedSourceIntakeTerminalReadEvidence requested) { + return requested != null + && Arrays.equals( + authorizationBinding.canonicalBytes(), requested.request().binding().canonicalBytes()) + && Arrays.equals( + terminalEvidence.receipt().canonicalBytes(), requested.receipt().canonicalBytes()) + && terminalEvidence.receipt().receiptDigest().equals(requested.receipt().receiptDigest()); + } + + @Override + public boolean equals(Object value) { + return value instanceof AccountSelectedOwnerIntakeSettlementReceipt other + && Arrays.equals(canonicalBytes, other.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + private byte[] encode() { + var out = new ByteArrayOutputStream(); + frame(out, DOMAIN); + frame(out, "1"); + frame(out, authorizationBinding.canonicalBytes()); + frame(out, authorizationBinding.digest()); + var request = terminalEvidence.request(); + frame(out, Integer.toString(request.schemaVersion())); + frame(out, request.targetNamespace()); + frame(out, request.readRequestId().toString()); + frame(out, request.intendedReader()); + frame(out, request.terminalReadPurpose()); + frame(out, request.binding().canonicalBytes()); + frame(out, request.binding().digest()); + frame(out, terminalEvidence.receipt().canonicalBytes()); + frame(out, terminalEvidence.receipt().receiptDigest()); + return out.toByteArray(); + } + + private static int parseSchemaVersion(String value) { + if (!"1".equals(value)) { + throw new IllegalArgumentException("Unsupported Automation terminal-read schema"); + } + return 1; + } + + private static byte[] bounded(byte[] value, int max) { + if (value == null || value.length == 0 || value.length > max) { + throw new IllegalArgumentException("Selected-owner settlement evidence size is invalid"); + } + return value; + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java similarity index 97% rename from services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java rename to services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java index acb6ff1c12..e36fac3be8 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationEmptySelectedSourceIntakeReceipt.java @@ -1,8 +1,9 @@ -package net.firedevops.firemud.automationscripting.sourceintake; +package net.firedevops.firemud.common.automation.sourceintake; import com.google.protobuf.InvalidProtocolBufferException; import java.io.ByteArrayOutputStream; import java.time.OffsetDateTime; +import java.time.format.DateTimeParseException; import java.util.Arrays; import java.util.Objects; import java.util.UUID; @@ -185,8 +186,8 @@ private AutomationEmptySelectedSourceIntakeReceipt( if (!this.authorizationBinding.digest().equals(this.authorizationBindingDigest)) { throw new IllegalArgumentException("Retained Account authorization digest differs"); } - requireAuthorizationIdentity(); this.worldInventoryReadEvidence = decodeWorldEvidence(); + requireAuthorizationIdentity(); this.canonicalBytes = encode(); if (canonicalBytes.length > MAX_BYTES) { throw new IllegalArgumentException("Automation source receipt exceeds its size limit"); @@ -194,7 +195,7 @@ private AutomationEmptySelectedSourceIntakeReceipt( this.receiptDigest = DraftAuthorizationFenceBinding.digest(canonicalBytes); } - static AutomationEmptySelectedSourceIntakeReceipt create( + public static AutomationEmptySelectedSourceIntakeReceipt create( SelectedOwnerEmptySourceInputs inputs, long localTenantKey, long localVersionKey, @@ -452,11 +453,11 @@ public String sourceParticipationDisposition() { return "PENDING_OWNER_TERMINAL_SETTLEMENT"; } - SelectedOwnerIntakeAuthorizationBinding authorizationBinding() { + public SelectedOwnerIntakeAuthorizationBinding authorizationBinding() { return authorizationBinding; } - SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence() { + public SelectedOwnerWorldInventoryReadEvidence worldInventoryReadEvidence() { return worldInventoryReadEvidence; } @@ -478,7 +479,7 @@ public void requireSameRequest( } /** Also binds a concurrent first-write race to the exact newly read World inventory content. */ - void requireSameInputs(SelectedOwnerEmptySourceInputs candidateInputs) { + public void requireSameInputs(SelectedOwnerEmptySourceInputs candidateInputs) { Objects.requireNonNull(candidateInputs, "validated empty-source inputs are required"); var candidateBinding = candidateInputs.authorizationBinding(); var candidateWorld = candidateInputs.worldInventoryReadEvidence(); @@ -702,7 +703,12 @@ private static long parseLong(String value, String label) { } private static OffsetDateTime parseTimestamp(String value) { - OffsetDateTime parsed = OffsetDateTime.parse(value); + final OffsetDateTime parsed; + try { + parsed = OffsetDateTime.parse(value); + } catch (DateTimeParseException malformed) { + throw new IllegalArgumentException("Receipt timestamp is malformed", malformed); + } if (!parsed.toString().equals(value)) { throw new IllegalArgumentException("Receipt timestamp is not canonical"); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java new file mode 100644 index 0000000000..63cc1cb3f3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadClient.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.common.automation.sourceintake; + +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.automationscripting.v1.AutomationSelectedSourceIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for Automation's exact original selected-source terminal read. */ +public final class AutomationSelectedSourceIntakeTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + AutomationSelectedSourceIntakeTerminalReadServiceGrpc + .AutomationSelectedSourceIntakeTerminalReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AutomationSelectedSourceIntakeTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AutomationSelectedSourceIntakeTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Automation terminal-read client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Automation terminal-read stub unavailable"); + } + initialized = true; + } + + /** Returns only an exact original COMMITTED_EMPTY receipt, outside owner SQL. */ + public AutomationSelectedSourceIntakeTerminalReadEvidence read( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Automation terminal read must run outside owner SQL"); + } + Objects.requireNonNull(request, "terminal-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Automation terminal read must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedSourceIntakeTerminal( + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request)); + try { + return AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("Automation returned invalid terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAutomationScriptingService(); + } + + @Override + protected String defaultTarget() { + return "automation-scripting-service:6565"; + } + + @Override + protected AutomationSelectedSourceIntakeTerminalReadServiceGrpc + .AutomationSelectedSourceIntakeTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/automation-scripting-service"; + return AutomationSelectedSourceIntakeTerminalReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AutomationSelectedSourceIntakeTerminalReadServiceGrpc + .AutomationSelectedSourceIntakeTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Automation terminal-read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Automation terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Automation terminal read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Automation terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Automation terminal read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Automation terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java new file mode 100644 index 0000000000..65c66ca538 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadEvidence.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.common.automation.sourceintake; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact lookup correlation and the original committed Automation receipt. */ +public record AutomationSelectedSourceIntakeTerminalReadEvidence( + Request request, AutomationEmptySelectedSourceIntakeReceipt receipt) { + public static final int SCHEMA_VERSION = 1; + public static final String TERMINAL_READ_PURPOSE = "AUTOMATION_INTAKE_TERMINAL_READ"; + + public AutomationSelectedSourceIntakeTerminalReadEvidence { + Objects.requireNonNull(request, "terminal-read request is required"); + Objects.requireNonNull(receipt, "committed Automation receipt is required"); + if (!request.targetNamespace().equals(receipt.targetNamespace()) + || !Arrays.equals(request.binding().canonicalBytes(), receipt.authorizationBindingBytes()) + || !"COMMITTED_EMPTY".equals(receipt.outcome())) { + throw new IllegalArgumentException( + "Automation receipt differs from the complete original terminal-read binding"); + } + } + + /** The correlation changes per transport read and never changes the retained operation. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + SelectedOwnerIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || binding == null + || !targetNamespace.equals(binding.targetNamespace()) + || binding.owner() != Owner.AUTOMATION_SCRIPTING + || !"account-automation-intake-authorization/v1".equals(binding.schema()) + || !"AUTOMATION_INTAKE_RETENTION".equals(binding.purpose()) + || binding.canonicalBytes().length == 0 + || binding.canonicalBytes().length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + if (collides(readRequestId, binding)) throw invalid(); + } + + public static Request create( + String namespace, SelectedOwnerIntakeAuthorizationBinding binding) { + Objects.requireNonNull(binding, "original finalized Account binding is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (collides(correlation, binding)); + return new Request(SCHEMA_VERSION, namespace, correlation, binding); + } + + /** Account is the only intended reader of this Automation-owned terminal. */ + public String intendedReader() { + return "spiffe://firemud/ns/" + targetNamespace + "/sa/account-service"; + } + + public String terminalReadPurpose() { + return TERMINAL_READ_PURPOSE; + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && readRequestId.equals(other.readRequestId) + && Arrays.equals(binding.canonicalBytes(), other.binding.canonicalBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, targetNamespace, readRequestId, Arrays.hashCode(binding.canonicalBytes())); + } + + private static boolean collides( + UUID candidate, SelectedOwnerIntakeAuthorizationBinding binding) { + return candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Automation selected-source terminal request"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..fb636d537c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcCodec.java @@ -0,0 +1,138 @@ +package net.firedevops.firemud.common.automation.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeTerminalResult; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Closed terminal mapping with an unchanged request echo and canonical receipt validation. */ +public final class AutomationSelectedSourceIntakeTerminalReadGrpcCodec { + private static final int MAX_REQUEST_FRAMING_BYTES = 64 * 1024; + + /** Full receipt plus a complete echoed 16 MiB Account binding and bounded protobuf framing. */ + public static final int MAX_WIRE_BYTES = + AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES + + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + MAX_REQUEST_FRAMING_BYTES; + + private AutomationSelectedSourceIntakeTerminalReadGrpcCodec() {} + + public static ReadSelectedSourceIntakeTerminalRequest toRequest( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "terminal-read request is required"); + byte[] bindingBytes = request.binding().canonicalBytes(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Automation authorization exceeds its 16 MiB limit"); + } + var wire = + ReadSelectedSourceIntakeTerminalRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setTerminalReadPurpose(request.terminalReadPurpose()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(bindingBytes)) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static AutomationSelectedSourceIntakeTerminalReadEvidence.Request fromRequest( + ReadSelectedSourceIntakeTerminalRequest wire) { + requireKnownAndWithinBudget(wire, "terminal-read request"); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getReadRequestId()); + byte[] bindingBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Automation authorization size is invalid"); + } + var binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + if (!binding.digest().equals(wire.getIntakeAuthorizationDigest())) { + throw invalid("Original Automation authorization digest differs"); + } + var request = + new AutomationSelectedSourceIntakeTerminalReadEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getReadRequestId()), + binding); + if (!request.intendedReader().equals(wire.getIntendedReader()) + || !request.terminalReadPurpose().equals(wire.getTerminalReadPurpose()) + || !toRequest(request).equals(wire)) { + throw invalid("Terminal reader, purpose, or request differs"); + } + return request; + } + + public static ReadSelectedSourceIntakeTerminalResponse toResponse( + AutomationSelectedSourceIntakeTerminalReadEvidence evidence) { + Objects.requireNonNull(evidence, "committed Automation terminal evidence is required"); + byte[] receiptBytes = evidence.receipt().canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Committed Automation receipt size is invalid"); + } + var response = + ReadSelectedSourceIntakeTerminalResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setResult( + AutomationSelectedSourceIntakeTerminalResult + .AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY) + .setCommittedEmptyReceipt(ByteString.copyFrom(receiptBytes)) + .setReceiptDigest(evidence.receipt().receiptDigest()) + .build(); + requireWithinBudget(response.getSerializedSize()); + return response; + } + + public static AutomationSelectedSourceIntakeTerminalReadEvidence fromResponse( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request, + ReadSelectedSourceIntakeTerminalResponse response) { + Objects.requireNonNull(request, "terminal-read request is required"); + requireKnownAndWithinBudget(response, "terminal-read response"); + if (!response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || response.getResult() + != AutomationSelectedSourceIntakeTerminalResult + .AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY) { + throw invalid("Exact COMMITTED_EMPTY response and full request echo required"); + } + byte[] receiptBytes = response.getCommittedEmptyReceipt().toByteArray(); + if (receiptBytes.length == 0 + || receiptBytes.length > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Missing or oversized committed Automation receipt"); + } + AutomationEmptySelectedSourceIntakeReceipt receipt = + AutomationEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes); + if (!receipt.receiptDigest().equals(response.getReceiptDigest())) { + throw invalid("Automation receipt digest differs"); + } + return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, receipt); + } + + private static void requireKnownAndWithinBudget(Message wire, String label) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) { + throw invalid("Missing or oversized Automation " + label); + } + if (!wire.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown Automation " + label + " fields"); + } + } + + private static void requireWithinBudget(int size) { + if (size > MAX_WIRE_BYTES) { + throw invalid("Automation terminal-read message exceeds its derived wire budget"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java new file mode 100644 index 0000000000..6c73b641b7 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import org.junit.jupiter.api.Test; + +/** Synthetic upstream value tests; mocks make no Account or Automation authentication claim. */ +class AccountSelectedOwnerIntakeSettlementReceiptTest { + private static final byte[] BINDING_BYTES = {1, 2, 3, 4}; + private static final String BINDING_DIGEST = DraftAuthorizationFenceBinding.digest(BINDING_BYTES); + private static final byte[] OWNER_RECEIPT_BYTES = {5, 6, 7}; + private static final String OWNER_RECEIPT_DIGEST = + DraftAuthorizationFenceBinding.digest(OWNER_RECEIPT_BYTES); + + @Test + void embedsCompleteImmutableEvidenceAndIgnoresOnlyFreshReadCorrelation() { + var binding = binding(); + var ownerReceipt = ownerReceipt(OWNER_RECEIPT_BYTES, OWNER_RECEIPT_DIGEST); + var firstEvidence = evidence(binding, ownerReceipt); + var first = AccountSelectedOwnerIntakeSettlementReceipt.create(firstEvidence); + + var reader = new DraftAuthorizationFenceBinding.FrameReader(first.canonicalBytes()); + reader.expect(AccountSelectedOwnerIntakeSettlementReceipt.DOMAIN); + reader.expect("1"); + assertThat(reader.bytes()).containsExactly(BINDING_BYTES); + reader.expect(BINDING_DIGEST); + reader.expect("1"); + reader.expect("test"); + String firstReadRequestId = reader.text(); + reader.expect("spiffe://firemud/ns/test/sa/account-service"); + reader.expect("AUTOMATION_INTAKE_TERMINAL_READ"); + assertThat(reader.bytes()).containsExactly(BINDING_BYTES); + reader.expect(BINDING_DIGEST); + assertThat(reader.bytes()).containsExactly(OWNER_RECEIPT_BYTES); + reader.expect(OWNER_RECEIPT_DIGEST); + reader.requireEnd(); + + var retryEvidence = evidence(binding, ownerReceipt); + var retried = AccountSelectedOwnerIntakeSettlementReceipt.create(retryEvidence); + assertThat(retryEvidence.request().readRequestId().toString()).isNotEqualTo(firstReadRequestId); + assertThat(first.sameImmutableOwnerReceipt(retryEvidence)).isTrue(); + assertThat(retried.canonicalBytes()).isNotEqualTo(first.canonicalBytes()); + + var changedOwnerReceipt = + ownerReceipt( + new byte[] {8, 9, 10}, DraftAuthorizationFenceBinding.digest(new byte[] {8, 9, 10})); + assertThat(first.sameImmutableOwnerReceipt(evidence(binding, changedOwnerReceipt))).isFalse(); + + byte[] exposed = first.canonicalBytes(); + exposed[0] ^= 0x7f; + assertThat(first.canonicalBytes()).isNotEqualTo(exposed); + assertThatThrownBy(() -> AccountSelectedOwnerIntakeSettlementReceipt.fromStored(exposed)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static SelectedOwnerIntakeAuthorizationBinding binding() { + var binding = mock(SelectedOwnerIntakeAuthorizationBinding.class); + when(binding.canonicalBytes()).thenReturn(BINDING_BYTES.clone()); + when(binding.digest()).thenReturn(BINDING_DIGEST); + when(binding.owner()).thenReturn(Owner.AUTOMATION_SCRIPTING); + when(binding.schema()).thenReturn("account-automation-intake-authorization/v1"); + when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION"); + when(binding.targetNamespace()).thenReturn("test"); + when(binding.operationId()).thenReturn(UUID.fromString("11111111-1111-4111-8111-111111111111")); + when(binding.fenceId()).thenReturn(UUID.fromString("22222222-2222-4222-8222-222222222222")); + when(binding.intakeRequestId()) + .thenReturn(UUID.fromString("33333333-3333-4333-8333-333333333333")); + return binding; + } + + private static AutomationEmptySelectedSourceIntakeReceipt ownerReceipt( + byte[] bytes, String digest) { + var receipt = mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(receipt.targetNamespace()).thenReturn("test"); + when(receipt.authorizationBindingBytes()).thenReturn(BINDING_BYTES.clone()); + when(receipt.authorizationBindingDigest()).thenReturn(BINDING_DIGEST); + when(receipt.outcome()).thenReturn("COMMITTED_EMPTY"); + when(receipt.canonicalBytes()).thenReturn(bytes.clone()); + when(receipt.receiptDigest()).thenReturn(digest); + return receipt; + } + + private static AutomationSelectedSourceIntakeTerminalReadEvidence evidence( + SelectedOwnerIntakeAuthorizationBinding binding, + AutomationEmptySelectedSourceIntakeReceipt receipt) { + return new AutomationSelectedSourceIntakeTerminalReadEvidence( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create("test", binding), + receipt); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java index 8464d9316d..bb486bd891 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.google.protobuf.ByteString; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; @@ -10,6 +11,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeTerminalResult; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; @@ -18,6 +20,9 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadGrpcCodec; import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; @@ -67,6 +72,117 @@ class SelectedOwnerEmptySourceInputsTest { + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}}," + "\"supportedSettings\":[]}"; + @Test + void automationTerminalReadEchoesExactBindingAndRequiresCommittedEmptyReceipt() { + Fixture fixture = fixture(Owner.AUTOMATION_SCRIPTING, Options.defaults()); + var inputs = + new SelectedOwnerEmptySourceInputs( + fixture.authorization(), fixture.worldInventoryReadEvidence()); + var binding = fixture.authorization(); + var receipt = + AutomationEmptySelectedSourceIntakeReceipt.create( + inputs, + 9001L, + 9002L, + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + "test", binding, fixture.worldInventoryReadEvidence().request().freezeEvidence()), + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + 0L, + OffsetDateTime.parse("2026-10-10T00:00:00Z")); + var request = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create("test", binding); + var evidence = new AutomationSelectedSourceIntakeTerminalReadEvidence(request, receipt); + var settlement = AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + assertThat( + AccountSelectedOwnerIntakeSettlementReceipt.fromStored(settlement.canonicalBytes()) + .canonicalBytes()) + .containsExactly(settlement.canonicalBytes()); + var requestWire = AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request); + var response = AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toResponse(evidence); + + assertThat(requestWire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .containsExactly(binding.canonicalBytes()); + assertThat(requestWire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + assertThat(request.readRequestId()) + .isNotIn(binding.operationId(), binding.fenceId(), binding.intakeRequestId()); + assertThat(request.intendedReader()).isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + assertThat(request.terminalReadPurpose()).isEqualTo("AUTOMATION_INTAKE_TERMINAL_READ"); + assertThat(response.getResult()) + .isEqualTo( + AutomationSelectedSourceIntakeTerminalResult + .AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY); + assertThat(response.getCommittedEmptyReceipt().toByteArray()) + .containsExactly(receipt.canonicalBytes()); + assertThat(AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(requestWire)) + .isEqualTo(request); + assertThat( + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response) + .receipt() + .canonicalBytes()) + .containsExactly(receipt.canonicalBytes()); + + var retry = AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create("test", binding); + assertThat(retry.readRequestId()).isNotEqualTo(request.readRequestId()); + var retryEvidence = new AutomationSelectedSourceIntakeTerminalReadEvidence(retry, receipt); + assertThat(settlement.sameImmutableOwnerReceipt(retryEvidence)).isTrue(); + assertThat( + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toResponse(retryEvidence) + .getCommittedEmptyReceipt()) + .isEqualTo(response.getCommittedEmptyReceipt()); + + var changedEcho = + response.toBuilder() + .setRequest(requestWire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, changedEcho)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setResult( + AutomationSelectedSourceIntakeTerminalResult + .AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, response.toBuilder().clearCommittedEmptyReceipt().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder().setReceiptDigest("sha256:" + "0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class); + + byte[] changedReceipt = response.getCommittedEmptyReceipt().toByteArray(); + changedReceipt[changedReceipt.length - 1] ^= 1; + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCommittedEmptyReceipt(ByteString.copyFrom(changedReceipt)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void retainsTheExactEmptyInputsAndOriginalDeclarationForBothOwners() { for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java new file mode 100644 index 0000000000..d20a72cca2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -0,0 +1,168 @@ +package net.firedevops.firemud.common.gamelogic; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Synthetic missing-receipt transport proof for client mTLS and server workload pinning only. */ +class AutomationSelectedSourceIntakeTerminalReadClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String AUTOMATION_URI = + "spiffe://firemud/ns/test/sa/automation-scripting-service"; + + @TempDir static Path tempDirectory; + + private static GameLogicIntakeSourceReadTransportTest.TestPki pki; + private static GameLogicIntakeSourceReadTransportTest.TestIdentity automationServer; + private static GameLogicIntakeSourceReadTransportTest.TestIdentity accountClient; + + private Server server; + private AutomationSelectedSourceIntakeTerminalReadClient client; + private final AtomicInteger calls = new AtomicInteger(); + + @BeforeAll + static void certificates() throws Exception { + pki = GameLogicIntakeSourceReadTransportTest.TestPki.create(tempDirectory); + Path caStore = tempDirectory.resolve("terminal-test-ca.p12"); + Path caFile = tempDirectory.resolve("terminal-test-ca.crt"); + automationServer = + GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + tempDirectory, caStore, caFile, "automation-terminal-server", AUTOMATION_URI, true); + accountClient = + GameLogicIntakeSourceReadTransportTest.TestPki.issueIdentity( + tempDirectory, caStore, caFile, "account-terminal-client", ACCOUNT_URI, false); + } + + @AfterEach + void closeTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void authenticatesAccountClientAndPinsSameNamespaceAutomationServer() throws Exception { + startServer(automationServer); + final int serverPort = server.getPort(); + client = newClient(accountClient); + client.init(); + + assertThatThrownBy(() -> client.read(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(Status.Code.NOT_FOUND)); + assertThat(calls).hasValue(1); + + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + startServer(pki.wrongServer(), serverPort); + assertThatThrownBy(() -> client.read(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(calls).hasValue(1); + } + + private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity) + throws Exception { + startServer(identity, 0); + } + + private void startServer(GameLogicIntakeSourceReadTransportTest.TestIdentity identity, int port) + throws Exception { + var service = + new AutomationSelectedSourceIntakeTerminalReadServiceGrpc + .AutomationSelectedSourceIntakeTerminalReadServiceImplBase() { + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + observer.onError(Status.NOT_FOUND.asRuntimeException()); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", port)) + .maxInboundMessageSize( + net.firedevops.firemud.common.automation.sourceintake + .AutomationSelectedSourceIntakeTerminalReadGrpcCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private AutomationSelectedSourceIntakeTerminalReadClient newClient( + GameLogicIntakeSourceReadTransportTest.TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAutomationScriptingService("localhost:" + server.getPort()); + return new AutomationSelectedSourceIntakeTerminalReadClient( + endpoints, + pki.clientProperties(tempDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static AutomationSelectedSourceIntakeTerminalReadEvidence.Request request() { + var binding = mock(SelectedOwnerIntakeAuthorizationBinding.class); + when(binding.owner()) + .thenReturn( + net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + when(binding.targetNamespace()).thenReturn(NAMESPACE); + when(binding.schema()).thenReturn("account-automation-intake-authorization/v1"); + when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION"); + when(binding.canonicalBytes()).thenReturn(new byte[] {1, 2, 3}); + when(binding.digest()).thenReturn("sha256:" + "a".repeat(64)); + when(binding.operationId()).thenReturn(UUID.randomUUID()); + when(binding.fenceId()).thenReturn(UUID.randomUUID()); + when(binding.intakeRequestId()).thenReturn(UUID.randomUUID()); + return AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, binding); + } +} From 5851bcd025d6e2c1220546a1ab913d174e9e55fe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:33:43 +1300 Subject: [PATCH 089/129] Prepare bounded player-created descriptors and correct Automation receipt proof --- .github/workflows/ci.yml | 2 +- build.gradle.kts | 10 + .../runtime-and-data.md | 8 + .../game-design-service/api-contracts.md | 2 + design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 6 + .../tests/ci-lightweight-scope-contract.sh | 45 +- ...onEmptySelectedSourceIntakeRepository.java | 5 +- ...ationEmptySelectedSourceIntakeService.java | 3 +- ...rminalReadMtlsPostgresIntegrationTest.java | 455 ++++++++++++++++++ .../publication/PlayerCreationDescriptor.java | 204 ++++++++ .../common/publication/RealmEntryPolicy.java | 81 +++- .../publication/RealmEntryPolicyTest.java | 249 ++++++++++ ...setPublicationPostgresIntegrationTest.java | 118 +++++ 14 files changed, 1173 insertions(+), 21 deletions(-) create mode 100644 services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PlayerCreationDescriptor.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69d2c930e3..173b0395ee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1107,7 +1107,7 @@ jobs: verbose: true - name: 📤 Upload Test Logs if Failed - if: failure() + if: ${{ failure() || cancelled() }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: test-logs-${{ matrix.module }}-${{ github.sha }} diff --git a/build.gradle.kts b/build.gradle.kts index d6084fdac7..d1d8d11363 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,6 +4,7 @@ import org.gradle.api.tasks.SourceSetContainer import org.gradle.api.plugins.quality.Checkstyle import org.gradle.api.plugins.jvm.JvmTestSuite import org.gradle.api.tasks.compile.JavaCompile +import org.gradle.api.tasks.testing.logging.TestExceptionFormat import java.io.File import org.flywaydb.gradle.FlywayExtension import org.springframework.boot.gradle.tasks.run.BootRun @@ -304,6 +305,15 @@ subprojects { tasks.matching { it.name.startsWith("spotless") && it.name.endsWith("Check") } .configureEach { enabled = fullCheck } + tasks.withType().configureEach { + testLogging { + exceptionFormat = TestExceptionFormat.FULL + showExceptions = true + showCauses = true + showStackTraces = true + } + } + tasks.test { useJUnitPlatform() } diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 6ac3196dc7..2237e22479 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -325,6 +325,14 @@ The published realm catalog supplies exactly one `PLAYER_CREATED`, `PRESEEDED_ON Copies into an isolated playtest namespace allocate a new fork-local `characterId`. When retained, `sourceCharacterId` must be accompanied by the immutable `{sourceTenantId, sourcePlayableStateNamespaceId}` binding and remains provenance only: that source tuple is never a live reference or authority for ownership, mutation, controller uniqueness, reconnect, cross-namespace reads, or merge-back. Game-specific RPG or non-RPG state is authored component data tied to the published descriptor/template and is not mandatory platform schema. +#### Bounded player-created input descriptor + +The closed descriptor for the bounded `PLAYER_CREATED` input shape contains exactly `schemaVersion: 1`, a canonical nonzero UUID `descriptorId`, a separately persisted authored nonzero UUID `descriptorRevisionId`, `inputKind: "EMPTY_OBJECT"`, and an explicit empty `dependencies` array. Its canonical representation is RFC 8785 JSON; its content digest is SHA-256 over those complete canonical UTF-8 bytes. Both identities are authored provenance, never aliases of an Account identity, private numeric key, published Version or inherited policy revision. This descriptor validates only an explicitly present canonical `{}` creation input. Missing, absent, `null`, nonempty or non-object input and unknown descriptor fields, kinds, versions or dependencies deny; there is no fixed RPG-field fallback. A future nonempty input or dependency family requires its own typed owner contract and inventory proof before acceptance. + +Game Design carries the complete descriptor as `creationDescriptor` inside a distinct closed realm-entry policy `schemaVersion: 2` with `entryPolicy: "PLAYER_CREATED"`. All existing selector/display/visibility/scope fields remain required; the entire policy retains its 4,096-byte UTF-8 limit. The retained schema-1 `PRESEEDED_ONLY` representation remains byte-exact and carries no descriptor. Schema 1 cannot be reinterpreted as player-created evidence, and this bounded schema 2 does not supply an auto-provision template. The authenticated selected-source scope binds the canonical tenant and Version; policy selectors bind the exact world and realm. Game Design retains the original policy commit and authored policy revision independently of the descriptor revision through its source snapshot, application, inheritance and exact readback. Changed identities or descriptor bytes are changed evidence, not an equivalent retry. + +The descriptor is not a pre-authored actor template or an `OTHER_ACTOR_TEMPLATE_ROOTS` inventory witness. An empty dependency array does not prove an empty Entity family: every one of the 23 Entity source-census obligations and the complete selected World/inbound closure remains required. Selected-source retention and its original owner receipt must bind the complete six-family Game Design content, including this exact policy and descriptor, to the unchanged finalized Account authorization and World evidence. Parsing or retaining the descriptor alone grants no creation, allocation, publication, placement, admission or activation authority; those producer/consumer and commit proofs remain separate obligations in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + ### Runtime Actor Identity Entity Management owns one persisted runtime actor for every active gameplay being. `actorId` is an opaque canonical gameplay-facing identity; services must not substitute composite reference strings such as `PLAYER:` or re-derive different player/NPC identity forms at each boundary. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 03df62f6de..c6e35b3e7b 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -81,6 +81,8 @@ The distinct [`GameDesignSelectedOwnerIntakeSourceService.ReadSelectedSource`](. The shared content decoder rejects changed scope, family order, family bytes/digests, selected binding, framing, canonical JSON or trailing bytes. All six snapshots must retain their exact selected Draft binding. Game Design remains the semantic owner for command, realm-policy, asset and branding snapshots; their consumer representation preserves original bytes rather than copying their grammars into another authority. Existing shared Gameplay Rule and Template Configuration parsers retain their applicable complete typed checks. Valid stored template v1/v2 content is not proof of a complete fresh Entity/Automation inventory. This transport and decoder neither finalize Account retention permission nor prove owner census, emptiness, receipt or settlement; production registration and acceptance remain denied until those producer/consumer boundaries and their focused proof are complete. +The realm-policy source carries the [Entity-owned bounded player-created input descriptor](../entity-management-service/runtime-and-data.md#bounded-player-created-input-descriptor) in the distinct policy schema 2 without reinterpreting retained schema-1 bytes. Game Design persists its authored descriptor identity/revision with the exact policy bytes and preserves the independent original policy commit and revision in its existing `REALM_POLICY` snapshot and application. Exact replay/readback must return those stored identities and bytes; a substituted descriptor, revision, selector or selected scope is not equivalent evidence. Neither an empty descriptor dependency list nor this source handoff discharges Entity census, World closure or actor-allocation proof. + ## Exact Publication Terminal Read `GameDesignPublicationTerminalReadService.ReadPublicationTerminal` reads the original immutable terminal result, not current permission or a new publication attempt. Its closed version-1 request binds the canonical workload namespace, a non-nil canonical read-request UUID and the complete original `game-design-publication-operation/v1` bytes. The receiver authenticates the exact same-namespace Account or World Management workload before decoding input or accessing storage. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 1f24c7dc32..39bbc7961b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -204,3 +204,9 @@ Entry format: - Observation: The next source publication started a same-PR Validation run fourteen seconds before the preceding Account checks were canceled. The workflow's per-PR concurrency group uses `cancel-in-progress: true`; local green checks and canceled remote unit artifacts did not establish database proof. - Expected pattern: Batch a corrected proof checkpoint, then hold further branch publications until its required database job completes while continuing implementation locally. Attribute artifacts to their originating checkout and distinguish interruption from a database assertion failure. - Current status: The cancellation cause is strongly supported by workflow configuration and run timing. The next corrected source checkpoint will have an uninterrupted Account proof window; physical proof remains open until the resulting artifacts establish execution. + +- `2026-10-11`: A patch-artifact task can accidentally mutate the shared checkout + - Context: A bounded Common codec helper was assigned temporary patch preparation while another owner gate used shared generated dependencies. It passed the intended implementation directly to `apply_patch`, modifying the checkout instead of creating the artifact; its reversal briefly removed the assigned tracked parser. + - Observation: An absolute repository path inside an executable patch is a live mutation target, not artifact content. Attempting to reverse the mistake introduced a second unsafe intermediate state. No concurrent build consumed the changed or missing parser, and the original tracked file was restored; unrelated edits were preserved. + - Expected pattern: Use the temporary artifact path as the only outer patch target, with implementation patch text as its contents. Report mistaken mutation immediately and let the parent choose recovery after checking running validation and concurrent ownership; do not start an independent reversal sequence. + - Current status: The parent stopped reversal, verified restoration and then explicitly authorized completion in the assigned Common files after the serialized owner gate finished. Integration inspection and consolidated proof remain required before publication. 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 351c8d9fc0..b03b219c56 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 @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The source checkpoint `fce7b38e8431dd7020cb2b11d98753a0f4f41e4b` [Validation run 38053396268](https://github.com/benhook1013/FireMUD/actions/runs/38053396268) ended with a failed required gate. Completed Automation artifacts show 1,200 unit cases pass and all 96 integration cases execute without skips, with one failure. All three `AutomationEmptySelectedSourceIntakePostgresIntegrationTest` cases pass. The repository readback case fails because PostgreSQL rejects a text-bound `associated_at` as a timestamp; the correction explicitly casts that association timestamp and the analogous retained-receipt timestamp without changing schema or source guards. The new native Account-to-Automation mTLS/PostgreSQL definition composes the real receiver and retained receipt repository, exact retry with a new transport correlation, and wrong-namespace denial with unchanged rows. Its Account/Game Design/World inputs are synthetic, so it is owner-edge proof only, not genuine upstream authorization or a complete handoff. Corrected local Automation checks pass: unit results are reused, three non-container integrations execute and 94 definitions skip without Docker, including the new native case. Physical execution of the corrected timestamp binding and native case remains required. Account's job was cancelled at its 30-minute limit, with 1,339 passing unit cases but no integration XML, including no originating selected-owner authorization report. Complete integration counts and V135 migration/settlement/concurrency outcomes are unknown, not passed or skipped; previous-head assertion and SQL failures do not supply this run's diagnosis. The tested merge `937fb427f9aab02030f28c990dac9cd83aaa0564`, tree `82066893d50c33d348931af2edba47ae07ac0bcb`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source; it does not prove alignment with the separately recorded integration parent. + +The [bounded player-created descriptor](../../architecture/microservices/entity-management-service/runtime-and-data.md#bounded-player-created-input-descriptor) is an approved input contract, not accepted actor-allocation or completeness proof. Its prepared distinct realm-policy schema preserves retained v1 bytes and independent authored policy/descriptor provenance. All nine new codec cases execute and pass. The Game Design owner-storage definition covers exact readback, unchanged original provenance through later inheritance, changed descriptor revisions and conflicting same-operation evidence; it compiles but skips without Docker. The composed Common Platform, Account, Automation and Game Design local checks execute 611, 1,339, 1,200 and 558 unit cases respectively, with no failures, errors or skips. Fifteen non-container integration cases execute; 532 definitions skip (Account 289, Automation 94, Game Design 149), including the new native mTLS case and all 21 Game Design version-asset publication cases. Affected boot JARs, static checks, formatting and documentation checks pass. All 23 Entity census obligations, complete World closure, genuine original receipts and runtime activation gates remain open. Gameplay confirmed the Common descriptor/source paths are disjoint from its current receiving work; its consumer adaptation requires the exact published source handoff rather than an inferred activation. + +The completed Account job log identifies nine failed integration cases before a later stall: eight SQL-related exceptions and one lost-acknowledgement assertion. Its incomplete log contains no SQLSTATE, constraint or assertion-value evidence, and the missing originating integration XML prevents reliable totals or V135 credit. The reviewed three-file diagnostic correction from commit `c85965a188ea44f16c8126ba1b38fcfed2f0befb` enables full test failure causes and retains available reports on cancellation without raising the 30-minute limit, exposing standard streams, weakening guards or rerunning an unchanged source. + Exact source `9931cc5c1a89b074a5bb2cab2a96f26c5f6259ce` [Validation run 38042678886](https://github.com/benhook1013/FireMUD/actions/runs/38042678886) ended cancelled overall, but its Account check completed with failure and uploaded originating XML: 1,332 unit cases pass; 308 integration cases execute with eighteen failures, no errors and no skips. Eight of the nine real Account acquisition/settlement/paging cases pass, including all three settlement cases and the single-candidate paging case; their Game Session and World evidence remains stipulated, so this is not genuine cross-owner admission. The ninth case reaches the deliberate generic-source-history denial rather than its stale expected creator-role message; existing closed-receipt currentness restrictions remain intact. All nine protection-integrity cases fail the shared fixture capture insert; the first exception identifies `account_start_session_capture_captured_at_millis` and a sub-millisecond `captured_at`. The correction truncates only that capture to milliseconds, preserving the deliberately microsecond-precision original expiry. Failure-only diagnostics preserve the original exception and disclose safe identifiers, not evidence or row values. Five legacy lease cases and two protected-entry prototype cases report WAL-coverage denials; the sixth lease case instead fails a lost-acknowledgement assertion and does not independently establish the same cause. Post-failure locator mappings identify current catalog relations only, not historical identity, backend attribution, causation or durable flush. Production WAL and source-currentness guards remain unchanged. Corrected fixture PostgreSQL execution and admission durability remain required. Tested merge `5bdca37edb0db7ab10c48f22cce00cc022c8fa7c`, tree `7ed297fd1cff734b593e4448c09930e9d9739efe`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and exact source `9931cc5c1a89b074a5bb2cab2a96f26c5f6259ce`, not the separately recorded integration parent. Cancelled overall status does not erase uploaded completed Account evidence; skipped duplicate jobs supply no proof. Distinct original-StartSession Account admission protection is prepared under [ADR 0047's canonical lifecycle](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection). It authenticates the original Game Session receiving workload, obtains the exact current original-attempt observation outside SQL, then revalidates the original actor/JTI/reference and unchanged complete capture through the existing Account currentness callback. V133 retains the complete request, actual mutation/attempt/fence and unchanged finite expiry, original World participation, full World hold, immutable capture and exact source children; additive writer/disclosure hooks preserve the existing assembled owner checks. A settled World row supplies historical binding, not current authority: acquisition must freshly prove unchanged original sources after a gap. Independent lookup-only readback returns the first protection unchanged. V129 World settlement and V131 observation are unchanged. Forward V134 prepares closed terminal-settlement integrity checks and preserves the existing immutable receipt and source-writer guards; expiry, missing or ambiguous proof cannot release protection. The producer, settlement composition and bounded recovery batch remain unregistered and do not enable admission. diff --git a/dev-tools/tests/ci-lightweight-scope-contract.sh b/dev-tools/tests/ci-lightweight-scope-contract.sh index d0f0fa617b..5e4caa7974 100644 --- a/dev-tools/tests/ci-lightweight-scope-contract.sh +++ b/dev-tools/tests/ci-lightweight-scope-contract.sh @@ -29,7 +29,7 @@ for expected in \ require_contains "$CLASSIFIER" "$expected" done -python3 - "$CI_WORKFLOW" "$SECURITY_WORKFLOW" "$PREVIEW_WORKFLOW" "$ZAP_WORKFLOW" "$CLASSIFIER" <<'PY' +python3 - "$CI_WORKFLOW" "$SECURITY_WORKFLOW" "$PREVIEW_WORKFLOW" "$ZAP_WORKFLOW" "$CLASSIFIER" "$ROOT_DIR/build.gradle.kts" <<'PY' import copy import json from pathlib import Path @@ -608,6 +608,16 @@ require_contains( "ci workflow", ) +test_logs_step = find_step( + ci, "build-and-test", "Upload Test Logs if Failed", "ci workflow" +) +require_equal( + test_logs_step, + ("if",), + "${{ failure() || cancelled() }}", + "ci workflow", +) + junit_results_step = find_step( ci, "build-and-test", "Upload JUnit Test Results", "ci workflow" ) @@ -648,6 +658,39 @@ require_equal( "ci workflow", ) +gradle_build = Path(sys.argv[6]).read_text(encoding="utf-8") +test_logging_match = re.search( + ( + r"tasks\.withType\(\)\.configureEach\s*\{\s*" + r"testLogging\s*\{(?P.*?)\n\s*\}\s*\}" + ), + gradle_build, + re.DOTALL, +) +if test_logging_match is None: + raise SystemExit( + "build.gradle.kts: missing canonical Test task logging configuration" + ) +test_logging_settings = test_logging_match.group("settings") +for expected in ( + "exceptionFormat = TestExceptionFormat.FULL", + "showExceptions = true", + "showCauses = true", + "showStackTraces = true", +): + if expected not in test_logging_settings: + raise SystemExit( + f"build.gradle.kts: Test task failure logging must include {expected!r}" + ) +if re.search(r"\bevents\s*(?:=|\()", test_logging_settings): + raise SystemExit( + "build.gradle.kts: Test task failure logging must preserve inherited events" + ) +if "showStandardStreams = true" in test_logging_settings: + raise SystemExit( + "build.gradle.kts: Test task failure logging must not expose standard streams" + ) + require_equal( security, ("jobs", "changes", "permissions", "pull-requests"), diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java index a43c790c43..3c0311c415 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java @@ -320,7 +320,8 @@ private static void insertAssociation( + "canonical_tenant_id, canonical_version_id, selected_commit_id, " + "source_revision_id, source_revision_order, local_tenant_key, " + "local_version_key, request_digest, authorization_binding_digest, " - + "receipt_digest, associated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + "receipt_digest, associated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ))", receipt.targetNamespace(), receipt.operationId(), receipt.fenceId(), @@ -350,7 +351,7 @@ private static void insertReceipt( "INSERT INTO " + RECEIPT + " (target_namespace, intake_request_id, request_digest, receipt_digest, " - + "receipt_bytes, retained_at) VALUES (?, ?, ?, ?, ?, ?)", + + "receipt_bytes, retained_at) VALUES (?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ))", receipt.targetNamespace(), receipt.intakeRequestId(), receipt.requestDigest(), diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java index 17d7c30114..84dc5e0b68 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java @@ -94,7 +94,8 @@ public AutomationEmptySelectedSourceIntakeReceipt retain( // Re-sample HELD after the remote World read to reduce the gap before local commit. This is // only a point-in-time observation: finalized pending Account source participation remains // under its source-writer exclusion guards. This preparation neither extends nor settles or - // releases them; exact Automation terminal settlement is not implemented. + // releases them. Account's separate exact Automation terminal settlement owns that release; + // this intake method does not invoke it, and unregistered construction is not activation proof. SelectedOwnerIntakeAuthorizationReadEvidence.Request finalAuthorizationReadRequest = SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( targetNamespace, originalBinding); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java new file mode 100644 index 0000000000..d91d2a77a0 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java @@ -0,0 +1,455 @@ +package net.firedevops.firemud.automationscripting.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeTerminalReadService; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedSourceIntakeTerminalReadGrpcService; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +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.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Native Account mTLS proof for Automation's owner edge; upstream fixture evidence stays synthetic. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest { + private static final String NS = "test"; + private static final String ACCOUNT = "spiffe://firemud/ns/test/sa/account-service"; + private static final String AUTOMATION = + "spiffe://firemud/ns/test/sa/automation-scripting-service"; + private static final String WRONG_ACCOUNT = "spiffe://firemud/ns/other/sa/account-service"; + private static final String PASSWORD = "test-only-store-password"; + private static final String MIGRATIONS = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @TempDir static Path temp; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static Pki pki; + private static Identity serverIdentity; + private static Identity accountIdentity; + private static Identity wrongIdentity; + + private String schema; + private DSLContext dsl; + private AutomationEmptySelectedSourceIntakeRepository repository; + private Server server; + private AutomationSelectedSourceIntakeTerminalReadClient client; + + @BeforeAll + static void issueCertificates() throws Exception { + pki = Pki.create(temp); + serverIdentity = Pki.issue(temp, pki.store(), pki.caFile(), "automation", AUTOMATION, true); + accountIdentity = Pki.issue(temp, pki.store(), pki.caFile(), "account", ACCOUNT, false); + wrongIdentity = + Pki.issue(temp, pki.store(), pki.caFile(), "wrong-account", WRONG_ACCOUNT, false); + } + + @BeforeEach + void migrateIsolatedSchema() { + schema = "automation_terminal_read_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource ds = dataSource(schema); + Flyway.configure() + .dataSource(ds) + .locations(MIGRATIONS) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target("3.2") + .load() + .migrate(); + Flyway.configure() + .dataSource(ds) + .locations(MIGRATIONS) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + dsl = DSL.using(ds, SQLDialect.POSTGRES); + repository = new AutomationEmptySelectedSourceIntakeRepository(dsl); + } + + @AfterEach + void cleanup() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + if (schema != null) { + String safeSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + safeSchema + "\" CASCADE"); + schema = null; + } + } + + @Test + void readsStoredCommittedEmptyReceiptOverAccountMtlsAndRejectsWrongNamespace() throws Exception { + var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + String digest = + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NS, fixture.authorization(), fixture.freezeEvidence()); + + // These typed Common inputs are synthetic; proof covers only Automation's owner edge. + var committed = repository.retainFresh(fixture.inputs(), digest); + assertThat(committed.outcome()).isEqualTo("COMMITTED_EMPTY"); + Record stored = + dsl.fetchSingle( + "SELECT receipt_bytes, receipt_digest FROM automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + committed.targetNamespace(), + committed.intakeRequestId()); + assertThat(stored).isNotNull(); + assertThat(stored.get(0, byte[].class)).containsExactly(committed.canonicalBytes()); + assertThat(stored.get(1, String.class)).isEqualTo(committed.receiptDigest()); + + startReceiver(); + client = newClient(accountIdentity); + client.init(); + var request = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create( + NS, fixture.authorization()); + var first = client.read(request); + assertThat(first.receipt().canonicalBytes()).containsExactly(stored.get(0, byte[].class)); + assertThat(first.receipt().receiptDigest()).isEqualTo(stored.get(1, String.class)); + assertThat(first.receipt().outcome()).isEqualTo("COMMITTED_EMPTY"); + + var replayRequest = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create( + NS, fixture.authorization()); + assertThat(replayRequest.readRequestId()).isNotEqualTo(request.readRequestId()); + var replay = client.read(replayRequest); + assertThat(replay.request()).isEqualTo(replayRequest); + assertThat(replay.receipt().canonicalBytes()).containsExactly(first.receipt().canonicalBytes()); + assertThat(replay.receipt().receiptDigest()).isEqualTo(first.receipt().receiptDigest()); + + var wrongClient = newClient(wrongIdentity); + try { + wrongClient.init(); + assertThatThrownBy(() -> wrongClient.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } finally { + wrongClient.close(); + } + assertThat(count("SELECT COUNT(*) FROM automation_empty_selected_source_association")) + .isEqualTo(1); + assertThat(count("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")).isEqualTo(1); + Record unchanged = + dsl.fetchSingle( + "SELECT receipt_bytes, receipt_digest FROM automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + committed.targetNamespace(), + committed.intakeRequestId()); + assertThat(unchanged).isNotNull(); + assertThat(unchanged.get(0, byte[].class)).containsExactly(first.receipt().canonicalBytes()); + assertThat(unchanged.get(1, String.class)).isEqualTo(first.receipt().receiptDigest()); + } + + private void startReceiver() throws Exception { + var owner = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NS); + var service = new AutomationSelectedSourceIntakeTerminalReadGrpcService(owner); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + net.firedevops.firemud.common.automation.sourceintake + .AutomationSelectedSourceIntakeTerminalReadGrpcCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(serverIdentity.key(), serverIdentity.cert())) + .trustManager(pki.caCert()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private AutomationSelectedSourceIntakeTerminalReadClient newClient(Identity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAutomationScriptingService("127.0.0.1:" + server.getPort()); + return new AutomationSelectedSourceIntakeTerminalReadClient( + endpoints, pki.clientProperties(temp, identity), new GrpcChannelFactory(), NS); + } + + private DriverManagerDataSource dataSource(String schemaName) { + var ds = new DriverManagerDataSource(); + ds.setDriverClassName(postgres.getDriverClassName()); + String base = postgres.getJdbcUrl(); + ds.setUrl( + schemaName == null + ? base + : base + (base.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + ds.setUsername(postgres.getUsername()); + ds.setPassword(postgres.getPassword()); + return ds; + } + + private long count(String sql) { + return dsl.fetchSingle(sql).get(0, Long.class); + } + + private record Identity(PrivateKey key, X509Certificate cert) {} + + private record Pki(X509Certificate caCert, Path store, Path caFile) { + static Pki create(Path dir) throws Exception { + Path store = dir.resolve("native-test-ca.p12"); + Path ca = dir.resolve("native-test-ca.crt"); + keytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + keytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + ca.toString(), + "-rfc"); + try (var in = Files.newInputStream(ca)) { + return new Pki( + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(in), + store, + ca); + } + } + + static Identity issue( + Path dir, Path caStore, Path caFile, String alias, String uri, boolean server) + throws Exception { + Path store = dir.resolve(alias + ".p12"); + Path csr = dir.resolve(alias + ".csr"); + Path cert = dir.resolve(alias + ".crt"); + String san = "URI:" + uri + ",DNS:localhost,IP:127.0.0.1"; + keytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + keytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + csr.toString(), + "-ext", + "SAN=" + san); + keytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-infile", + csr.toString(), + "-outfile", + cert.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + keytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + keytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + cert.toString(), + "-noprompt"); + KeyStore keys = KeyStore.getInstance("PKCS12"); + try (var in = Files.newInputStream(store)) { + keys.load(in, PASSWORD.toCharArray()); + } + return new Identity( + (PrivateKey) keys.getKey(alias, PASSWORD.toCharArray()), + (X509Certificate) keys.getCertificate(alias)); + } + + CommonGrpcClientProperties clientProperties(Path dir, Identity identity) throws Exception { + Path clientDir = Files.createTempDirectory(dir, "terminal-client-"); + Path chain = + pem(clientDir.resolve("client.crt"), "CERTIFICATE", identity.cert().getEncoded()); + Path key = pem(clientDir.resolve("client.key"), "PRIVATE KEY", identity.key().getEncoded()); + Path ca = pem(clientDir.resolve("client-ca.crt"), "CERTIFICATE", caCert.getEncoded()); + var props = new CommonGrpcClientProperties(); + props.setCertChain(chain.toString()); + props.setPrivateKey(key.toString()); + props.setCaCert(ca.toString()); + return props; + } + + private static void keytool(String... args) throws Exception { + Path bin = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(bin.toString()); + command.addAll(List.of(args)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(5, TimeUnit.SECONDS); + throw new IllegalStateException("keytool timed out"); + } + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static Path pem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PlayerCreationDescriptor.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PlayerCreationDescriptor.java new file mode 100644 index 0000000000..a0b1fb1bea --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PlayerCreationDescriptor.java @@ -0,0 +1,204 @@ +package net.firedevops.firemud.common.publication; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Closed schema-1 descriptor for a player-created actor with explicitly empty input. */ +public final class PlayerCreationDescriptor { + public static final int SCHEMA_VERSION = 1; + public static final String INPUT_KIND = "EMPTY_OBJECT"; + public static final int MAX_JSON_BYTES = 4096; + + private static final Set FIELDS = + Set.of("schemaVersion", "descriptorId", "descriptorRevisionId", "inputKind", "dependencies"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final String descriptorId; + private final String descriptorRevisionId; + private final byte[] canonicalBytes; + private final String canonicalJson; + private final String digest; + + private PlayerCreationDescriptor( + String descriptorId, String descriptorRevisionId, byte[] canonicalBytes) { + this.descriptorId = descriptorId; + this.descriptorRevisionId = descriptorRevisionId; + this.canonicalBytes = canonicalBytes.clone(); + this.canonicalJson = new String(this.canonicalBytes, StandardCharsets.UTF_8); + this.digest = sha256(this.canonicalBytes); + } + + /** Parses the exact closed descriptor grammar and retains its canonical bytes and digest. */ + public static PlayerCreationDescriptor parse(String json) { + byte[] inputBytes = boundedUtf8(json); + final byte[] canonicalBytes; + final JsonNode root; + try { + canonicalBytes = Rfc8785CanonicalJson.canonicalizeUtf8(json); + root = JSON.readTree(new String(canonicalBytes, StandardCharsets.UTF_8)); + } catch (IOException | RuntimeException invalidJson) { + throw invalid("must be valid unambiguous JSON", invalidJson); + } + if (inputBytes.length > MAX_JSON_BYTES || root == null || !root.isObject()) { + throw invalid("must be a bounded JSON object"); + } + requireObjectFields(root); + + JsonNode schemaVersion = root.get("schemaVersion"); + if (schemaVersion == null + || !schemaVersion.isIntegralNumber() + || !schemaVersion.canConvertToInt() + || schemaVersion.intValue() != SCHEMA_VERSION) { + throw invalid("schemaVersion must be the integer 1"); + } + String descriptorId = requireCanonicalNonNilUuid(root, "descriptorId"); + String descriptorRevisionId = requireCanonicalNonNilUuid(root, "descriptorRevisionId"); + JsonNode inputKind = root.get("inputKind"); + if (inputKind == null || !inputKind.isTextual() || !INPUT_KIND.equals(inputKind.asText())) { + throw invalid("inputKind must be EMPTY_OBJECT"); + } + JsonNode dependencies = root.get("dependencies"); + if (dependencies == null || !dependencies.isArray() || dependencies.size() != 0) { + throw invalid("dependencies must be an explicit empty array"); + } + return new PlayerCreationDescriptor(descriptorId, descriptorRevisionId, canonicalBytes); + } + + public int schemaVersion() { + return SCHEMA_VERSION; + } + + public String descriptorId() { + return descriptorId; + } + + public String descriptorRevisionId() { + return descriptorRevisionId; + } + + public String inputKind() { + return INPUT_KIND; + } + + public List dependencies() { + return List.of(); + } + + public String canonicalJson() { + return canonicalJson; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** SHA-256 of the complete canonical descriptor UTF-8 bytes, without an authority frame. */ + public String digest() { + return digest; + } + + /** Accepts only the explicitly present canonical empty-object creation input. */ + public void validateCreationInput(String inputJson) { + if (!"{}".equals(inputJson)) { + throw invalid("creation input must be the canonical empty object"); + } + } + + @Override + public boolean equals(Object other) { + return other instanceof PlayerCreationDescriptor descriptor + && Arrays.equals(canonicalBytes, descriptor.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + private static byte[] boundedUtf8(String json) { + if (json == null) { + throw invalid("data is required"); + } + try { + ByteBuffer inputBytes = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(json)); + if (inputBytes.remaining() > MAX_JSON_BYTES) { + throw invalid("data exceeds the byte limit"); + } + byte[] bytes = new byte[inputBytes.remaining()]; + inputBytes.get(bytes); + return bytes; + } catch (CharacterCodingException malformedUnicode) { + throw invalid("data must be valid UTF-8", malformedUnicode); + } + } + + private static void requireObjectFields(JsonNode root) { + Set actual = new HashSet<>(); + root.properties().forEach(property -> actual.add(property.getKey())); + if (!actual.equals(FIELDS)) { + throw invalid("must contain exactly the descriptor fields"); + } + } + + private static String requireCanonicalNonNilUuid(JsonNode root, String field) { + JsonNode node = root.get(field); + if (node == null || !node.isTextual()) { + throw invalid(field + " must be a canonical nonzero UUID"); + } + String value = node.asText(); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) + || (parsed.getMostSignificantBits() == 0 && parsed.getLeastSignificantBits() == 0)) { + throw invalid(field + " must be a canonical nonzero UUID"); + } + } catch (IllegalArgumentException invalidUuid) { + throw invalid(field + " must be a canonical nonzero UUID", invalidUuid); + } + return value; + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException("INVALID_ARGUMENT: playerCreationDescriptor " + message); + } + + private static IllegalArgumentException invalid(String message, Exception cause) { + return new IllegalArgumentException( + "INVALID_ARGUMENT: playerCreationDescriptor " + message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java index 75ccc90dc2..c5bc8e38fa 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java @@ -3,13 +3,14 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.util.Objects; import java.util.Set; import java.util.regex.Pattern; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; -/** Closed v1 authored realm-entry policy shared by the publication owner and runtime receivers. */ +/** Closed authored realm-entry policy shared by the publication owner and runtime receivers. */ public record RealmEntryPolicy( int schemaVersion, String worldSlug, @@ -20,14 +21,16 @@ public record RealmEntryPolicy( boolean publicProduction, StateScope stateScope, EntryPolicy entryPolicy, + PlayerCreationDescriptor creationDescriptor, String canonicalJson) { public static final String REVISION_KIND = "REALM_ENTRY_POLICY"; public static final int SCHEMA_VERSION = 1; + public static final int PLAYER_CREATED_SCHEMA_VERSION = 2; public static final int MAX_JSON_BYTES = 4096; public static final int MAX_SLUG_LENGTH = 64; public static final int MAX_DISPLAY_NAME_CODE_POINTS = 128; - private static final Set FIELDS = + private static final Set V1_FIELDS = Set.of( "schemaVersion", "worldSlug", @@ -38,18 +41,48 @@ public record RealmEntryPolicy( "publicProduction", "stateScope", "entryPolicy"); + private static final Set V2_FIELDS = + Set.of( + "schemaVersion", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "visible", + "publicProduction", + "stateScope", + "entryPolicy", + "creationDescriptor"); private static final Pattern SLUG_PATTERN = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + public RealmEntryPolicy { + Objects.requireNonNull(stateScope, "stateScope"); + Objects.requireNonNull(entryPolicy, "entryPolicy"); + Objects.requireNonNull(canonicalJson, "canonicalJson"); + if (schemaVersion == SCHEMA_VERSION) { + if (entryPolicy != EntryPolicy.PRESEEDED_ONLY || creationDescriptor != null) { + throw invalid("schemaVersion 1 requires PRESEEDED_ONLY without a descriptor"); + } + } else if (schemaVersion == PLAYER_CREATED_SCHEMA_VERSION) { + if (entryPolicy != EntryPolicy.PLAYER_CREATED || creationDescriptor == null) { + throw invalid("schemaVersion 2 requires PLAYER_CREATED with a descriptor"); + } + } else { + throw invalid("schemaVersion is unsupported"); + } + } + public enum StateScope { SHARED, ISOLATED } public enum EntryPolicy { - PRESEEDED_ONLY + PRESEEDED_ONLY, + PLAYER_CREATED } - /** Parses valid v1 JSON and returns the RFC 8785 canonical policy representation. */ + /** Parses supported policy JSON and returns its RFC 8785 canonical representation. */ public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { if (json == null || json.isBlank()) { throw invalid("data is required"); @@ -74,21 +107,26 @@ public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { if (root == null || !root.isObject()) { throw invalid("must be a JSON object"); } - for (String field : FIELDS) { + JsonNode schemaVersion = root.get("schemaVersion"); + if (schemaVersion == null + || !schemaVersion.isIntegralNumber() + || !schemaVersion.canConvertToInt()) { + throw invalid("schemaVersion must be a supported integer"); + } + int version = schemaVersion.intValue(); + Set fields = + switch (version) { + case SCHEMA_VERSION -> V1_FIELDS; + case PLAYER_CREATED_SCHEMA_VERSION -> V2_FIELDS; + default -> throw invalid("schemaVersion is unsupported"); + }; + for (String field : fields) { if (!root.has(field)) { throw invalid(field + " is required"); } } - if (root.size() != FIELDS.size()) { - throw invalid("must contain exactly the v1 fields"); - } - - JsonNode schemaVersion = root.get("schemaVersion"); - if (schemaVersion == null - || !schemaVersion.isIntegralNumber() - || !schemaVersion.canConvertToInt() - || schemaVersion.intValue() != SCHEMA_VERSION) { - throw invalid("schemaVersion must be the integer 1"); + if (root.size() != fields.size()) { + throw invalid("must contain exactly the schema fields"); } String worldSlug = requireSlug(root, "worldSlug"); String worldDisplayName = requireDisplayName(root, "worldDisplayName"); @@ -98,9 +136,19 @@ public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { boolean publicProduction = requireBoolean(root, "publicProduction"); StateScope stateScope = requireEnum(root, "stateScope", StateScope.class); EntryPolicy entryPolicy = requireEnum(root, "entryPolicy", EntryPolicy.class); + if (version == SCHEMA_VERSION && entryPolicy != EntryPolicy.PRESEEDED_ONLY) { + throw invalid("schemaVersion 1 supports only PRESEEDED_ONLY"); + } + if (version == PLAYER_CREATED_SCHEMA_VERSION && entryPolicy != EntryPolicy.PLAYER_CREATED) { + throw invalid("schemaVersion 2 supports only PLAYER_CREATED"); + } + PlayerCreationDescriptor creationDescriptor = + version == PLAYER_CREATED_SCHEMA_VERSION + ? PlayerCreationDescriptor.parse(root.get("creationDescriptor").toString()) + : null; return new RealmEntryPolicy( - SCHEMA_VERSION, + version, worldSlug, worldDisplayName, realmSlug, @@ -109,6 +157,7 @@ public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { publicProduction, stateScope, entryPolicy, + creationDescriptor, canonicalJson); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java new file mode 100644 index 0000000000..0381260b77 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java @@ -0,0 +1,249 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import net.firedevops.firemud.common.publication.RealmEntryPolicy.EntryPolicy; +import net.firedevops.firemud.common.publication.RealmEntryPolicy.StateScope; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class RealmEntryPolicyTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String DESCRIPTOR_ID = "11111111-1111-4111-8111-111111111111"; + private static final String REVISION_ID = "22222222-2222-4222-8222-222222222222"; + + @Test + void preservesV1CanonicalBytesAndPreseededPolicyResult() { + String input = policy(1, "PRESEEDED_ONLY", null); + var parsed = RealmEntryPolicy.parse(input, JSON); + String expected = + "{\"entryPolicy\":\"PRESEEDED_ONLY\",\"publicProduction\":true," + + "\"realmDisplayName\":\"Realm\",\"realmSlug\":\"realm\"," + + "\"schemaVersion\":1,\"stateScope\":\"SHARED\",\"visible\":true," + + "\"worldDisplayName\":\"World\",\"worldSlug\":\"world\"}"; + + assertThat(parsed.schemaVersion()).isEqualTo(RealmEntryPolicy.SCHEMA_VERSION); + assertThat(parsed.entryPolicy()).isEqualTo(EntryPolicy.PRESEEDED_ONLY); + assertThat(parsed.creationDescriptor()).isNull(); + assertThat(parsed.canonicalJson()).isEqualTo(expected); + assertThat(parsed.canonicalJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(expected.getBytes(StandardCharsets.UTF_8)); + assertThat(RealmEntryPolicy.parseCanonical(expected, JSON)).isEqualTo(parsed); + } + + @Test + void parsesV2PlayerCreatedPolicyAndDescriptorRoundTrip() { + var parsed = RealmEntryPolicy.parse(policy(2, "PLAYER_CREATED", descriptor()), JSON); + var descriptor = parsed.creationDescriptor(); + + assertThat(parsed.schemaVersion()).isEqualTo(RealmEntryPolicy.PLAYER_CREATED_SCHEMA_VERSION); + assertThat(parsed.entryPolicy()).isEqualTo(EntryPolicy.PLAYER_CREATED); + assertThat(descriptor).isNotNull(); + assertThat(descriptor.schemaVersion()).isEqualTo(PlayerCreationDescriptor.SCHEMA_VERSION); + assertThat(descriptor.descriptorId()).isEqualTo(DESCRIPTOR_ID); + assertThat(descriptor.descriptorRevisionId()).isEqualTo(REVISION_ID); + assertThat(descriptor.inputKind()).isEqualTo(PlayerCreationDescriptor.INPUT_KIND); + assertThat(descriptor.dependencies()).isEmpty(); + assertThat(RealmEntryPolicy.parseCanonical(parsed.canonicalJson(), JSON)).isEqualTo(parsed); + } + + @Test + void descriptorSubstitutionChangesPolicyBytesAndDescriptorDigest() { + var original = RealmEntryPolicy.parse(policy(2, "PLAYER_CREATED", descriptor()), JSON); + String substitutedDescriptor = + descriptor().replace(REVISION_ID, "33333333-3333-4333-8333-333333333333"); + var substituted = + RealmEntryPolicy.parse(policy(2, "PLAYER_CREATED", substitutedDescriptor), JSON); + + assertThat(substituted.canonicalJson()).isNotEqualTo(original.canonicalJson()); + assertThat(substituted.creationDescriptor().canonicalBytes()) + .isNotEqualTo(original.creationDescriptor().canonicalBytes()); + assertThat(substituted.creationDescriptor().digest()) + .isNotEqualTo(original.creationDescriptor().digest()); + } + + @Test + void rejectsPolicyVersionAndEntryPolicyMismatches() { + for (String entryPolicy : List.of("PLAYER_CREATED", "AUTO_PROVISIONED", "UNKNOWN")) { + assertInvalid(policy(1, entryPolicy, null)); + } + for (String entryPolicy : List.of("PRESEEDED_ONLY", "AUTO_PROVISIONED", "UNKNOWN")) { + assertInvalid(policy(2, entryPolicy, descriptor())); + } + assertInvalid(policy(3, "PLAYER_CREATED", descriptor())); + assertInvalid(policy(2, "PLAYER_CREATED", null)); + assertInvalid(policyWithExtraField(2, "PLAYER_CREATED", descriptor())); + } + + @Test + void rejectsMalformedOrUnsupportedDescriptorShapes() { + for (String invalidDescriptor : + List.of( + descriptor().replace("\"schemaVersion\":1", "\"schemaVersion\":2"), + descriptor().replace("\"inputKind\":\"EMPTY_OBJECT\"", "\"inputKind\":\"OBJECT\""), + descriptor().replace("\"dependencies\":[]", "\"dependencies\":[\"other\"]"), + descriptor().replace("\"dependencies\":[]", "\"dependencies\":null"), + descriptor().replace("\"dependencies\":[]", "\"dependencies\":[],\"unknown\":true"), + descriptor().replace("\"descriptorRevisionId\":\"" + REVISION_ID + "\",", ""))) { + assertInvalid(policy(2, "PLAYER_CREATED", invalidDescriptor)); + } + } + + @Test + void rejectsNilNoncanonicalAndMalformedDescriptorUuids() { + for (String invalidId : + List.of( + "00000000-0000-0000-0000-000000000000", + "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", + "1-1-1-1-1")) { + assertInvalid(policy(2, "PLAYER_CREATED", descriptor().replace(DESCRIPTOR_ID, invalidId))); + assertInvalid(policy(2, "PLAYER_CREATED", descriptor().replace(REVISION_ID, invalidId))); + } + } + + @Test + void validatesOnlyExplicitCanonicalEmptyObjectCreationInput() { + var descriptor = PlayerCreationDescriptor.parse(descriptor()); + descriptor.validateCreationInput("{}"); + + assertThatThrownBy(() -> descriptor.validateCreationInput(null)) + .isInstanceOf(IllegalArgumentException.class); + for (String invalidInput : List.of("{ }", "[]", "{\"value\":1}", "{\"unknown\":true}")) { + assertThatThrownBy(() -> descriptor.validateCreationInput(invalidInput)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { + assertThatThrownBy( + () -> + new RealmEntryPolicy( + 1, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PLAYER_CREATED, + null, + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new RealmEntryPolicy( + 1, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PRESEEDED_ONLY, + PlayerCreationDescriptor.parse(descriptor()), + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new RealmEntryPolicy( + 2, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PRESEEDED_ONLY, + null, + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new RealmEntryPolicy( + 2, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PLAYER_CREATED, + null, + "{}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new RealmEntryPolicy( + 3, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PRESEEDED_ONLY, + null, + "{}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void preservesThe4096BytePolicyInputLimitForBothSchemas() { + for (String input : + List.of(policy(1, "PRESEEDED_ONLY", null), policy(2, "PLAYER_CREATED", descriptor()))) { + String atLimit = padToLimit(input, RealmEntryPolicy.MAX_JSON_BYTES); + assertThat(atLimit.getBytes(StandardCharsets.UTF_8)).hasSize(RealmEntryPolicy.MAX_JSON_BYTES); + assertThat(RealmEntryPolicy.parse(atLimit, JSON).canonicalJson()).isNotEmpty(); + + String aboveLimit = padToLimit(input, RealmEntryPolicy.MAX_JSON_BYTES + 1); + assertThat(aboveLimit.getBytes(StandardCharsets.UTF_8)) + .hasSize(RealmEntryPolicy.MAX_JSON_BYTES + 1); + assertThatThrownBy(() -> RealmEntryPolicy.parse(aboveLimit, JSON)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static void assertInvalid(String input) { + assertThatThrownBy(() -> RealmEntryPolicy.parse(input, JSON)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static String policy(int version, String entryPolicy, String descriptor) { + return "{\"schemaVersion\":" + + version + + ",\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\"," + + "\"visible\":true,\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"" + + entryPolicy + + "\"" + + (descriptor == null ? "" : ",\"creationDescriptor\":" + descriptor) + + "}"; + } + + private static String policyWithExtraField(int version, String entryPolicy, String descriptor) { + String input = policy(version, entryPolicy, descriptor); + return input.substring(0, input.length() - 1) + ",\"unknown\":true}"; + } + + private static String descriptor() { + return "{\"schemaVersion\":1,\"descriptorId\":\"" + + DESCRIPTOR_ID + + "\",\"descriptorRevisionId\":\"" + + REVISION_ID + + "\",\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}"; + } + + private static String padToLimit(String input, int bytes) { + return " ".repeat(bytes - input.getBytes(StandardCharsets.UTF_8).length) + input; + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java index 22b73ae1a8..c7bf60b78e 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationPostgresIntegrationTest.java @@ -32,6 +32,7 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository; import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository; import net.firedevops.firemud.gamedesign.repository.GameAssetRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; @@ -348,6 +349,123 @@ void policyCommandAndAssetShareOneExactOwnerOutcomeAndSynchronizedSnapshot() thr assertThat(readback.policy()).isEqualTo(result.policy().orElseThrow().snapshot()); } + @Test + void playerCreatedPolicyDescriptorPersistsAndReplaysWithIndependentAuthoredProvenance() { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "player-created-policy"); + Version version = saveDraftVersion(fixture, owner, 1); + String descriptorRevisionId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + String policyBytes = playerCreatedPolicy(descriptorRevisionId); + String authoredPayload = policyRevision(policyBytes); + var binding = sourceBinding(fixture, version, authoredPayload); + UUID authoredRevisionId = binding.revisions().getFirst().revisionId(); + + var applied = inTransaction(fixture, () -> applySources(fixture, binding)); + var original = applied.policy().orElseThrow().snapshot(); + assertThat(original.policies()).hasSize(1); + var authored = original.policies().getFirst(); + assertThat(authored.commitId()).isEqualTo(binding.commitId()); + assertThat(authored.revisionId()).isEqualTo(authoredRevisionId); + assertThat(authoredRevisionId.toString()).isNotEqualTo(descriptorRevisionId); + assertThat(authored.policy().canonicalJson()).isEqualTo(policyBytes); + + String applicationJson = + fixture + .dsl() + .fetchSingle( + "SELECT snapshot_json FROM game_design_realm_policy_application WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND commit_id = ?", + binding.target().canonicalTenantId(), + binding.target().canonicalVersionId(), + binding.commitId()) + .get(0, String.class); + assertThat(applicationJson).isEqualTo(original.canonicalJson()); + var stored = + new RealmPolicySourceRepository(fixture.dsl()) + .readSnapshot(binding.target(), binding.commitId()) + .orElseThrow(); + assertThat(stored.canonicalBytes()).containsExactly(original.canonicalBytes()); + assertThat(stored.policies().getFirst().policy().canonicalJson()).isEqualTo(policyBytes); + + var retry = + inTransaction(fixture, () -> new GameDesignSourceRepository(fixture.dsl()).apply(binding)); + assertThat(retry.ownerOutcome()).isEqualTo(applied.ownerOutcome()); + assertThat(retry.policy().orElseThrow().canonicalBytes()) + .containsExactly(applied.policy().orElseThrow().canonicalBytes()); + + var originalRevision = binding.revisions().getFirst(); + var changedSameIdentity = + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + List.of( + new DraftCommitBinding.RevisionPayload( + originalRevision.revisionOrder(), + originalRevision.revisionId(), + originalRevision.owner(), + policyRevision(playerCreatedPolicy("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")))), + binding.affectedUnits()); + assertThat(changedSameIdentity.digest()).isNotEqualTo(binding.digest()); + assertThatThrownBy( + () -> + inTransaction( + fixture, + () -> + new RealmPolicySourceRepository(fixture.dsl()).apply(changedSameIdentity))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("POLICY_COMMIT_BINDING_CONFLICT"); + assertThat( + new RealmPolicySourceRepository(fixture.dsl()) + .readSnapshot(binding.target(), binding.commitId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(original.canonicalBytes()); + + var inheritedBinding = + sourceBinding(fixture, version, CommandSource.deletePayload("no-such-command")); + inTransaction(fixture, () -> applySources(fixture, inheritedBinding)); + var inherited = + new RealmPolicySourceRepository(fixture.dsl()) + .readSnapshot(inheritedBinding.target(), inheritedBinding.commitId()) + .orElseThrow(); + assertThat(inherited.policies()).hasSize(1); + assertThat(inherited.policies().getFirst().commitId()).isEqualTo(binding.commitId()); + assertThat(inherited.policies().getFirst().revisionId()).isEqualTo(authoredRevisionId); + assertThat(inherited.policies().getFirst().policy().canonicalJson()).isEqualTo(policyBytes); + + String changedPolicyBytes = playerCreatedPolicy("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + var changedBinding = sourceBinding(fixture, version, policyRevision(changedPolicyBytes)); + var changed = inTransaction(fixture, () -> applySources(fixture, changedBinding)); + var changedPolicy = changed.policy().orElseThrow().snapshot().policies().getFirst(); + assertThat(changedPolicy.commitId()).isEqualTo(changedBinding.commitId()); + assertThat(changedPolicy.revisionId()) + .isEqualTo(changedBinding.revisions().getFirst().revisionId()); + assertThat(changedPolicy.policy().canonicalJson()).isEqualTo(changedPolicyBytes); + assertThat(changedPolicy.policy().canonicalJson()).isNotEqualTo(policyBytes); + assertThat( + new RealmPolicySourceRepository(fixture.dsl()) + .readSnapshot(binding.target(), binding.commitId()) + .orElseThrow() + .policies() + .getFirst() + .policy() + .canonicalJson()) + .isEqualTo(policyBytes); + } + + private String playerCreatedPolicy(String descriptorRevisionId) { + return "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"99999999-9999-4999-8999-999999999999\",\"descriptorRevisionId\":\"" + + descriptorRevisionId + + "\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\",\"publicProduction\":false,\"realmDisplayName\":\"Player Realm\",\"realmSlug\":\"player-realm\",\"schemaVersion\":2,\"stateScope\":\"ISOLATED\",\"visible\":true,\"worldDisplayName\":\"Player World\",\"worldSlug\":\"player-world\"}"; + } + + private String policyRevision(String policyBytes) { + return "{\"logicalRevisionId\":\"player-created-realm-policy\",\"policy\":" + + policyBytes + + ",\"revisionKind\":\"REALM_ENTRY_POLICY\"}"; + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void stagedOrdinaryApplicationCannotCommitWithoutItsCompleteAppliedOwnerOutcome(boolean unknown) { From 74294ebbf2976cc5334416b32762774d2c22ef23 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 02:36:32 +1300 Subject: [PATCH 090/129] Record originating Account and Game Design CI proof limits --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 b03b219c56..c15a7732e4 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 @@ -10,7 +10,7 @@ The source checkpoint `fce7b38e8431dd7020cb2b11d98753a0f4f41e4b` [Validation run The [bounded player-created descriptor](../../architecture/microservices/entity-management-service/runtime-and-data.md#bounded-player-created-input-descriptor) is an approved input contract, not accepted actor-allocation or completeness proof. Its prepared distinct realm-policy schema preserves retained v1 bytes and independent authored policy/descriptor provenance. All nine new codec cases execute and pass. The Game Design owner-storage definition covers exact readback, unchanged original provenance through later inheritance, changed descriptor revisions and conflicting same-operation evidence; it compiles but skips without Docker. The composed Common Platform, Account, Automation and Game Design local checks execute 611, 1,339, 1,200 and 558 unit cases respectively, with no failures, errors or skips. Fifteen non-container integration cases execute; 532 definitions skip (Account 289, Automation 94, Game Design 149), including the new native mTLS case and all 21 Game Design version-asset publication cases. Affected boot JARs, static checks, formatting and documentation checks pass. All 23 Entity census obligations, complete World closure, genuine original receipts and runtime activation gates remain open. Gameplay confirmed the Common descriptor/source paths are disjoint from its current receiving work; its consumer adaptation requires the exact published source handoff rather than an inferred activation. -The completed Account job log identifies nine failed integration cases before a later stall: eight SQL-related exceptions and one lost-acknowledgement assertion. Its incomplete log contains no SQLSTATE, constraint or assertion-value evidence, and the missing originating integration XML prevents reliable totals or V135 credit. The reviewed three-file diagnostic correction from commit `c85965a188ea44f16c8126ba1b38fcfed2f0befb` enables full test failure causes and retains available reports on cancellation without raising the 30-minute limit, exposing standard streams, weakening guards or rerunning an unchanged source. +The completed Account job log identifies nine failed integration cases before a later stall: eight SQL-related exceptions and one lost-acknowledgement assertion. Its incomplete log contains no SQLSTATE, constraint or assertion-value evidence, and the missing originating integration XML prevents reliable totals or V135 credit. Eight names recur in preceding evidence; the catalog-churn prototype case is newly failing, but older causes cannot be assigned to this run. The reviewed three-file diagnostic correction from commit `c85965a188ea44f16c8126ba1b38fcfed2f0befb` enables full test failure causes and retains available reports on cancellation without raising the 30-minute limit, exposing standard streams, weakening guards or rerunning an unchanged source. Game Design's originating artifacts from the same run show 558 passing unit and 151 physically executed integration cases without skips, failures or errors; its job was nevertheless cancelled at the separate 20-minute limit before Gradle completed. Those originating test results are valid evidence, not a completed full-module gate or proof of the later descriptor definitions, and identify no Game Design source defect. Exact source `9931cc5c1a89b074a5bb2cab2a96f26c5f6259ce` [Validation run 38042678886](https://github.com/benhook1013/FireMUD/actions/runs/38042678886) ended cancelled overall, but its Account check completed with failure and uploaded originating XML: 1,332 unit cases pass; 308 integration cases execute with eighteen failures, no errors and no skips. Eight of the nine real Account acquisition/settlement/paging cases pass, including all three settlement cases and the single-candidate paging case; their Game Session and World evidence remains stipulated, so this is not genuine cross-owner admission. The ninth case reaches the deliberate generic-source-history denial rather than its stale expected creator-role message; existing closed-receipt currentness restrictions remain intact. All nine protection-integrity cases fail the shared fixture capture insert; the first exception identifies `account_start_session_capture_captured_at_millis` and a sub-millisecond `captured_at`. The correction truncates only that capture to milliseconds, preserving the deliberately microsecond-precision original expiry. Failure-only diagnostics preserve the original exception and disclose safe identifiers, not evidence or row values. Five legacy lease cases and two protected-entry prototype cases report WAL-coverage denials; the sixth lease case instead fails a lost-acknowledgement assertion and does not independently establish the same cause. Post-failure locator mappings identify current catalog relations only, not historical identity, backend attribution, causation or durable flush. Production WAL and source-currentness guards remain unchanged. Corrected fixture PostgreSQL execution and admission durability remain required. Tested merge `5bdca37edb0db7ab10c48f22cce00cc022c8fa7c`, tree `7ed297fd1cff734b593e4448c09930e9d9739efe`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and exact source `9931cc5c1a89b074a5bb2cab2a96f26c5f6259ce`, not the separately recorded integration parent. Cancelled overall status does not erase uploaded completed Account evidence; skipped duplicate jobs supply no proof. From 8911d8537d54163388e50ca2c50c01918cb5d1f3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 03:19:57 +1300 Subject: [PATCH 091/129] Prove native selected-owner authorization and receipt composition --- .../account-service/api-contracts.md | 2 + .../game-design-service/api-contracts.md | 2 + ...ame-authoring-publishing-and-activation.md | 8 + ..._owner_intake_authorization_producer.proto | 37 ++ ...ntakeAuthorizationProducerGrpcService.java | 196 ++++++++ ...eAuthorizationProducerGrpcServiceTest.java | 312 ++++++++++++ .../AccountControlUiOriginalOrderFixture.java | 16 + .../build.gradle.kts | 15 + ...ntakeAuthorizationProducerCredentials.java | 120 +++++ ...erIntakeAuthorizationProducerEvidence.java | 220 ++++++++ ...IntakeAuthorizationProducerProtoCodec.java | 152 ++++++ ...eAuthorizationProducerCredentialsTest.java | 103 ++++ ...keAuthorizationProducerProtoCodecTest.java | 256 ++++++++++ ...wnerIntakeAuthorizationProducerClient.java | 185 +++++++ ...IntakeAuthorizationProducerClientTest.java | 165 ++++++ services/game-design-service/build.gradle.kts | 17 +- ...licationExportPostgresIntegrationTest.java | 475 ++++++++++++++++-- .../world-management-service/build.gradle.kts | 22 + ...electedOwnerInventoryReadProofFixture.java | 32 ++ 19 files changed, 2305 insertions(+), 30 deletions(-) create mode 100644 protos/account/v1/selected_owner_intake_authorization_producer.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentials.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeAuthorizationProducerClient.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeAuthorizationProducerClientTest.java create mode 100644 services/world-management-service/src/testFixtures/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadProofFixture.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index f2095ecca1..aaf0d5ef6c 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -112,6 +112,8 @@ That scope is preliminary integrity input, not authenticated authorization, fina The distinct finalized integrity envelope uses `account-entity-intake-authorization/v1` with purpose `ENTITY_INTAKE_RETENTION` and the exact same-namespace Entity workload recipient, or `account-automation-intake-authorization/v1` with purpose `AUTOMATION_INTAKE_RETENTION` and the corresponding Automation recipient. Its canonical byte-length-framed preimage is, in order: that closed schema, the complete six-family selected-content bytes, their SHA-256 digest, the derived recipient SPIFFE URI, the closed retention purpose, a canonical decimal source count, and each complete Account source-evidence frame in sorted distinct source-key order. The content embeds the unchanged preliminary scope, so operation, fence, request, actor, namespace and selected Draft identity are reused rather than reallocated. The complete envelope is bounded to 16 MiB without changing the content's 8 MiB or preliminary scope's 4 MiB bounds. Unknown or substituted owner, reader or purpose, changed content or source scope, duplicate or noncanonical source order, malformed counts and trailing bytes deny. This value's decoder establishes integrity only; genuine Account finalization/readback and continuously held source participation, followed by the owner's own census, retention and exact terminal, establish the separate authorization and outcome. Preliminary abort cannot release a finalized operation; expiry, absence or a digest alone never settles it. +The separate [`AccountSelectedOwnerIntakeAuthorizationProducerService.AuthorizeSelectedOwnerIntake`](../../../../protos/account/v1/selected_owner_intake_authorization_producer.proto) supplies the authenticated command boundary for that two-phase producer. Account authenticates the exact same-namespace Game Design workload and rejects end-user context before protected metadata or request decoding. The original creator credential is carried only in the method-specific `x-firemud-selected-owner-intake-creator` metadata: exactly one nonblank ASCII value of at most 16,384 characters. It is not a response field, request preimage, stored transport value or log value. The closed version-1 request binds namespace, an independent nonzero transport correlation, stable intake request, closed Entity or Automation owner and complete canonical selected Draft bytes. The correlation is distinct from the intake request and selected Draft request/commit identities; it does not replace the durable intake identity. Account captures its own current environment boundary around the external authenticated selected-source read and revalidates the original creator, exact selection and held sources before finalization. A finalized exact retry returns the stored binding without creating a replacement reservation or recapturing source content. Unavailable or unresolved evidence denies without inventing an abort or terminal outcome. Success echoes every request field and selected byte unchanged and returns the complete original finalized authorization bytes and digest. The request selection is bounded to 4 MiB; the existing 4 MiB preliminary scope, 8 MiB content and 16 MiB authorization limits remain independent, with a separate 24 MiB wire budget. The client pins Account over file-backed mTLS, applies a five-second deadline, and rejects ambient SQL/synchronization and authenticated end-user context. This standalone transport does not register a runtime path or prove owner retention, census, settlement or admission; executed proof and remaining registration limits belong in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + The standalone [`AccountSelectedOwnerIntakeAuthorizationReadService.ReadHeldSelectedOwnerIntakeAuthorization`](../../../../protos/account/v1/selected_owner_intake_authorization_read.proto) reads that original finalized order, not its preliminary reservation. Its closed schema-version-1 request binds namespace, an independent nonzero read correlation distinct from the retained operation/fence/intake request, the exact derived owner reader and retention purpose, and the full original binding bytes/digest. Account authenticates same-namespace Entity or Automation and rejects end-user context before decoding; after decoding, the actual peer must be that binding's exact recipient. An independent writable `READ COMMITTED` transaction locks and compares the original authorization, reservation, creator evidence and complete source participation. Success echoes the entire request unchanged with `held=true`; missing, changed, aborted, malformed, mismatched or unavailable evidence denies. The file-backed mTLS client pins Account, uses a five-second deadline, rejects ambient SQL/synchronization and enforces a separate 24 MiB wire budget without expanding the 16 MiB binding limit. This sampled HELD read cannot create/finalize/settle an order, allocate a replacement identity, renew authority or prove continuous protection through the owner's commit, complete census or a terminal receipt. The unregistered components and their proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). For Automation, Account may settle finalized source participation only after an authenticated exact same-namespace read of the Automation-owned `COMMITTED_EMPTY` terminal for the complete original authorization; the [Automation contract](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) owns its closed request, receipt and retry rules. Account first reads any exact committed settlement independently, then obtains missing terminal evidence outside SQL, commits one immutable settlement under its existing source locks, and performs a separate lookup-only committed readback. Only that exact committed settlement releases this operation's participation, after which both external `HELD` readers deny; historical authorization and terminal recovery remain available without creating fresh authority. Source locks in canonical order precede the reservation, finalized authorization and settlement locks, so a source writer cannot bypass pending participation. Missing, pending, changed, corrupt or ambiguous owner evidence preserves participation; absence or expiry is not an abort. Unregistered construction components do not establish a complete authenticated producer or executed physical proof; see the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index c6e35b3e7b..ae3c8313d7 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -79,6 +79,8 @@ The separate preliminary owner-read composition accepts only the exact same-name The distinct [`GameDesignSelectedOwnerIntakeSourceService.ReadSelectedSource`](../../../../protos/game-design/v1/selected_owner_intake_source_service.proto) carries that complete selected content without expanding the Gameplay Rule method's caller policy. Its closed schema-version-1 request binds the namespace, independent nonzero read correlation, derived same-namespace Account reader, owner-specific purpose and complete preliminary scope bytes/digest. The configured Account workload must be authenticated, without end-user context, before parsing or any source query. Game Design obtains its own exact Account preliminary confirmation before disclosure, then returns the unchanged complete request and the original six-family bytes and digest. The canonical content limit remains 8 MiB; the separate request/response wire limit is 16 MiB to carry content, the bounded 4 MiB scope echo and framing, without changing global gRPC limits. The file-backed client authenticates the exact same-namespace Game Design server, applies a five-second deadline, and rejects ambient SQL and transaction synchronization. +Game Design requests distinct intake finalization through the [Account-owned selected-owner authorization producer](../account-service/api-contracts.md#grpc-apis), retaining the stable intake request and exact selected Draft binding. It forwards the original creator credential only through that method's protected per-call metadata, not selected source content or a publication digest. Account remains the sole finalization and currentness owner; neither Game Design's workload identity nor its local source export creates retention authority. The returned full binding must remain unchanged through the subsequent owner intake and terminal readback; this consumer consequence does not register or enable the transport. + The shared content decoder rejects changed scope, family order, family bytes/digests, selected binding, framing, canonical JSON or trailing bytes. All six snapshots must retain their exact selected Draft binding. Game Design remains the semantic owner for command, realm-policy, asset and branding snapshots; their consumer representation preserves original bytes rather than copying their grammars into another authority. Existing shared Gameplay Rule and Template Configuration parsers retain their applicable complete typed checks. Valid stored template v1/v2 content is not proof of a complete fresh Entity/Automation inventory. This transport and decoder neither finalize Account retention permission nor prove owner census, emptiness, receipt or settlement; production registration and acceptance remain denied until those producer/consumer boundaries and their focused proof are complete. The realm-policy source carries the [Entity-owned bounded player-created input descriptor](../entity-management-service/runtime-and-data.md#bounded-player-created-input-descriptor) in the distinct policy schema 2 without reinterpreting retained schema-1 bytes. Game Design persists its authored descriptor identity/revision with the exact policy bytes and preserves the independent original policy commit and revision in its existing `REALM_POLICY` snapshot and application. Exact replay/readback must return those stored identities and bytes; a substituted descriptor, revision, selector or selected scope is not equivalent evidence. Neither an empty descriptor dependency list nor this source handoff discharges Entity census, World closure or actor-allocation proof. 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 c15a7732e4..bb2da55c60 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 @@ -6,6 +6,14 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Exact source `74294ebbf2976cc5334416b32762774d2c22ef23` [Validation run 38056381237](https://github.com/benhook1013/FireMUD/actions/runs/38056381237) completed with a failed required gate. Originating Account results show 1,339 passing unit cases and 309 physically executed integration cases, with eight failures and no skips. Four lease-persistence cases and four protected-entry prototype cases fail the conservative WAL-coverage boundary; observed insert or upper bounds are 64 bytes ahead of the flush frontier. The saved failure evidence supplies no SQLSTATE or constraint identity and does not establish the WAL record's cause. No marker, forced flush, longer expiry, warm-up or weakened guard is accepted as a correction. Automation's 1,200 unit and 97 integration cases and Game Design's 558 unit and 152 integration cases all pass without skips. The tested merge `e949a1cb38aa4f769dd2a58dfc21409384cfeb90`, tree `61fa6de5bc0fafb0ac2df747ce3b6795c8b8ab12`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, not the separately recorded integration parent. + +That run provides specific corrected proof rather than aggregate completion: Account's three selected-owner authorization integration cases pass, including exact Automation empty settlement and release of only that operation; its preliminary reservation migration case also passes. Automation's native Account-mTLS terminal-read case executes against a real retained `COMMITTED_EMPTY` receipt and denies the wrong namespace without row changes, while its upstream Account/Game Design/World inputs remain synthetic. Game Design's descriptor persistence, retry and independent authored-provenance case passes in its 24-case version-asset publication suite. The separate genuine Game Logic intake/settlement definition passes with migrations through V135; it does not substitute for the distinct Entity/Automation composition. Complete original handoffs, Entity's 23-family census, authenticated command composition, Account admission durability and runtime activation remain open. + +The next prepared composition adds the standalone [Account selected-owner authorization producer](../../architecture/microservices/account-service/api-contracts.md#grpc-apis), native Game Design-to-Account command and Account-to-Game Design source disclosure, actual recipient-qualified World inventory, Automation empty-source retention and Account settlement. These changes are not part of the source tested above. The new client resides in Common Security for direct end-user-context rejection, while its closed evidence, codec and method-bound creator credentials reside in Common Platform. The composed PostgreSQL definition retains explicit limitations: preliminary reservation context, local Automation retention and local Account settlement command contexts remain stipulated; Entity retention, publication participant digests, S3 and StartSession projection are not complete owner proof. All components remain unregistered. + +The corrected six-module local gate passes in 2m44s after repairing a duplicate fixture-local variable, without changing owner behavior. Common Platform, Common Security, Account, Automation, Game Design and World unit results contain 620, 148, 1,345, 1,200, 558 and 648 cases respectively, all with zero failures, errors or skips. Their unit tasks execute across the first and corrected gates; the corrected gate reuses unchanged Common Platform, Common Security, Account and Automation results rather than rerunning them. Sixteen non-container integration cases execute; 752 definitions skip without Docker (Account 289, Automation 94, Game Design 149, World 220), including the expanded genuine composition. All four integration sources compile, affected boot JARs and classes-only World/Automation proof artifacts build, and formatting, static checks, coverage, links, Markdown and Flyway sanity pass. The two opt-in proof artifacts contain no application or migration resources. Nine new codec/credential, two pre-transport client and six mocked receiver cases strengthen the bounded command contract but do not prove its physical PostgreSQL/mTLS composition, production registration or activation. Corrected originating CI remains required for that new batch. + The source checkpoint `fce7b38e8431dd7020cb2b11d98753a0f4f41e4b` [Validation run 38053396268](https://github.com/benhook1013/FireMUD/actions/runs/38053396268) ended with a failed required gate. Completed Automation artifacts show 1,200 unit cases pass and all 96 integration cases execute without skips, with one failure. All three `AutomationEmptySelectedSourceIntakePostgresIntegrationTest` cases pass. The repository readback case fails because PostgreSQL rejects a text-bound `associated_at` as a timestamp; the correction explicitly casts that association timestamp and the analogous retained-receipt timestamp without changing schema or source guards. The new native Account-to-Automation mTLS/PostgreSQL definition composes the real receiver and retained receipt repository, exact retry with a new transport correlation, and wrong-namespace denial with unchanged rows. Its Account/Game Design/World inputs are synthetic, so it is owner-edge proof only, not genuine upstream authorization or a complete handoff. Corrected local Automation checks pass: unit results are reused, three non-container integrations execute and 94 definitions skip without Docker, including the new native case. Physical execution of the corrected timestamp binding and native case remains required. Account's job was cancelled at its 30-minute limit, with 1,339 passing unit cases but no integration XML, including no originating selected-owner authorization report. Complete integration counts and V135 migration/settlement/concurrency outcomes are unknown, not passed or skipped; previous-head assertion and SQL failures do not supply this run's diagnosis. The tested merge `937fb427f9aab02030f28c990dac9cd83aaa0564`, tree `82066893d50c33d348931af2edba47ae07ac0bcb`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source; it does not prove alignment with the separately recorded integration parent. The [bounded player-created descriptor](../../architecture/microservices/entity-management-service/runtime-and-data.md#bounded-player-created-input-descriptor) is an approved input contract, not accepted actor-allocation or completeness proof. Its prepared distinct realm-policy schema preserves retained v1 bytes and independent authored policy/descriptor provenance. All nine new codec cases execute and pass. The Game Design owner-storage definition covers exact readback, unchanged original provenance through later inheritance, changed descriptor revisions and conflicting same-operation evidence; it compiles but skips without Docker. The composed Common Platform, Account, Automation and Game Design local checks execute 611, 1,339, 1,200 and 558 unit cases respectively, with no failures, errors or skips. Fifteen non-container integration cases execute; 532 definitions skip (Account 289, Automation 94, Game Design 149), including the new native mTLS case and all 21 Game Design version-asset publication cases. Affected boot JARs, static checks, formatting and documentation checks pass. All 23 Entity census obligations, complete World closure, genuine original receipts and runtime activation gates remain open. Gameplay confirmed the Common descriptor/source paths are disjoint from its current receiving work; its consumer adaptation requires the exact published source handoff rather than an inferred activation. diff --git a/protos/account/v1/selected_owner_intake_authorization_producer.proto b/protos/account/v1/selected_owner_intake_authorization_producer.proto new file mode 100644 index 0000000000..3e7d745341 --- /dev/null +++ b/protos/account/v1/selected_owner_intake_authorization_producer.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered producer for the distinct Entity and Automation intake authorization. +service AccountSelectedOwnerIntakeAuthorizationProducerService { + rpc AuthorizeSelectedOwnerIntake(SelectedOwnerIntakeAuthorizationProducerRequest) + returns (SelectedOwnerIntakeAuthorizationProducerResponse); +} + +enum SelectedOwnerIntakeAuthorizationProducerOwner { + SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_UNSPECIFIED = 0; + SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_ENTITY_MANAGEMENT = 1; + SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_AUTOMATION_SCRIPTING = 2; +} + +message SelectedOwnerIntakeAuthorizationProducerRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Independent per-transport correlation; not the stable intake or selected Draft identity. + string transport_request_id = 3; + string intake_request_id = 4; + SelectedOwnerIntakeAuthorizationProducerOwner owner = 5; + // Complete canonical DraftCommitBinding JSON bytes. + bytes selected_draft_binding = 6; +} + +message SelectedOwnerIntakeAuthorizationProducerResponse { + // Exact unchanged request echo. + SelectedOwnerIntakeAuthorizationProducerRequest request = 1; + // Complete canonical SelectedOwnerIntakeAuthorizationBinding bytes and its SHA-256 digest. + bytes intake_authorization_binding = 2; + string intake_authorization_digest = 3; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcService.java new file mode 100644 index 0000000000..ec0e14b1a0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcService.java @@ -0,0 +1,196 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.BindableService; +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerProtoCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone, unregistered same-namespace Game Design selected-owner intake producer. */ +public final class AccountSelectedOwnerIntakeAuthorizationProducerGrpcService + implements BindableService { + private final AccountSelectedOwnerIntakeAuthorizationService owner; + private final AccountHostedTermsService terms; + private final String namespace; + + public AccountSelectedOwnerIntakeAuthorizationProducerGrpcService( + AccountSelectedOwnerIntakeAuthorizationService owner, + AccountHostedTermsService terms, + String namespace) { + this.owner = Objects.requireNonNull(owner); + this.terms = Objects.requireNonNull(terms); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + /** Peer authentication precedes protected metadata parsing and all evidence decoding. */ + @Override + public ServerServiceDefinition bindService() { + var handler = + new AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationProducerServiceImplBase() { + @Override + public void authorizeSelectedOwnerIntake( + SelectedOwnerIntakeAuthorizationProducerRequest request, + StreamObserver observer) { + AccountSelectedOwnerIntakeAuthorizationProducerGrpcService.this + .authorizeSelectedOwnerIntake(request, observer); + } + }; + return ServerInterceptors.intercept( + handler, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Status denied = peerDenial(); + if (denied != null) { + call.close(sanitized(denied), new Metadata()); + return new ServerCall.Listener<>() {}; + } + String method = call.getMethodDescriptor().getFullMethodName(); + if (!SelectedOwnerIntakeAuthorizationProducerCredentials.allowedMethod(method)) { + call.close(sanitized(Status.UNIMPLEMENTED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + if (hasAmbientSql()) { + call.close(sanitized(Status.FAILED_PRECONDITION), new Metadata()); + return new ServerCall.Listener<>() {}; + } + final SelectedOwnerIntakeAuthorizationProducerCredentials.Credential credential; + try { + credential = + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + headers, method); + } catch (IllegalArgumentException malformed) { + call.close(sanitized(Status.UNAUTHENTICATED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + Context context = + Context.current() + .withValue( + SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY, + credential); + return Contexts.interceptCall(context, call, headers, next); + } + }); + } + + public void authorizeSelectedOwnerIntake( + SelectedOwnerIntakeAuthorizationProducerRequest wire, + StreamObserver observer) { + final AuthenticatedRequest authenticated; + try { + authenticated = request(wire); + } catch (StatusRuntimeException denied) { + deny(observer, Status.fromCode(denied.getStatus().getCode())); + return; + } + var request = authenticated.request(); + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + + final SelectedOwnerIntakeAuthorizationProducerResponse response; + try { + var binding = + owner.authorizeWithEnvironmentCapture( + authenticated.originalCreatorCredential(), + request.intakeRequestId(), + request.owner(), + request.selected(), + terms::captureCurrentEnvironmentBoundary); + var result = + new SelectedOwnerIntakeAuthorizationProducerEvidence.Result( + request, binding, binding.digest()); + response = SelectedOwnerIntakeAuthorizationProducerProtoCodec.toResponse(result); + } catch (RuntimeException unavailable) { + deny(observer, statusOf(unavailable)); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private AuthenticatedRequest request(SelectedOwnerIntakeAuthorizationProducerRequest wire) { + Status denied = peerDenial(); + if (denied != null) throw sanitized(denied).asRuntimeException(); + if (hasAmbientSql()) throw sanitized(Status.FAILED_PRECONDITION).asRuntimeException(); + + var protectedCredential = SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get(); + if (protectedCredential == null) throw sanitized(Status.UNAUTHENTICATED).asRuntimeException(); + final String credential; + try { + credential = protectedCredential.value(); + } catch (IllegalArgumentException malformed) { + throw sanitized(Status.UNAUTHENTICATED).asRuntimeException(); + } + try { + return new AuthenticatedRequest( + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromRequest(wire), credential); + } catch (IllegalArgumentException malformed) { + throw sanitized(Status.INVALID_ARGUMENT).asRuntimeException(); + } + } + + private Status peerDenial() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) return Status.UNAUTHENTICATED; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + return Status.PERMISSION_DENIED; + } + return null; + } + + private static boolean hasAmbientSql() { + return TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive(); + } + + private static Status statusOf(RuntimeException error) { + if (error instanceof StatusRuntimeException status) + return Status.fromCode(status.getStatus().getCode()); + if (error instanceof IllegalArgumentException) return Status.FAILED_PRECONDITION; + return Status.UNAVAILABLE; + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError(sanitized(status).asRuntimeException()); + } + + private static Status sanitized(Status status) { + return status.withDescription( + "Account selected-owner intake authorization denied or unavailable"); + } + + private record AuthenticatedRequest( + SelectedOwnerIntakeAuthorizationProducerEvidence.Request request, + String originalCreatorCredential) { + @Override + public String toString() { + return "AuthenticatedSelectedOwnerIntakeAuthorizationRequest[redacted]"; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java new file mode 100644 index 0000000000..4666b4da76 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java @@ -0,0 +1,312 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerProtoCodec; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Receiver boundary tests; the mocked owner does not establish durable retry or retention proof. + */ +class AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String CREDENTIAL = "original.creator.credential"; + + private final AccountSelectedOwnerIntakeAuthorizationService owner = + mock(AccountSelectedOwnerIntakeAuthorizationService.class); + private final AccountHostedTermsService terms = mock(AccountHostedTermsService.class); + private final AccountSelectedOwnerIntakeAuthorizationProducerGrpcService receiver = + new AccountSelectedOwnerIntakeAuthorizationProducerGrpcService(owner, terms, NAMESPACE); + + @AfterEach + void clearContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsWrongPeerNamespaceAndEndUserBeforeCredentialOrRequestDecoding() { + assertThat(invokeAuthorize(null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer(NAMESPACE, "world-management-service", () -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("42", List.of(), java.util.Map.of()); + assertThat(peer(NAMESPACE, "game-design-service", () -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner, terms); + } + + @Test + void boundInterceptorChecksPeerAndMethodBeforeProtectedMetadata() { + var headers = mock(io.grpc.Metadata.class); + assertThat(boundCode(headers, null)).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer(NAMESPACE, "world-management-service", () -> boundCode(headers, null))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> boundCode(headers, null))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("42", List.of(), java.util.Map.of()); + assertThat(peer(NAMESPACE, "game-design-service", () -> boundCode(headers, null))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(headers, owner, terms); + SessionContext.clear(); + + var empty = new io.grpc.Metadata(); + assertThat(peer(NAMESPACE, "game-design-service", () -> boundCode(empty, null))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + var duplicate = new io.grpc.Metadata(); + duplicate.put( + SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(CREDENTIAL)); + duplicate.put( + SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(CREDENTIAL)); + assertThat(peer(NAMESPACE, "game-design-service", () -> boundCode(duplicate, null))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer(NAMESPACE, "game-design-service", () -> boundCode(empty, "OtherMethod"))) + .isEqualTo(Status.Code.UNIMPLEMENTED); + verifyNoInteractions(owner, terms); + } + + @Test + void rejectsMalformedRequestAndRequestNamespaceBeforeOwnerAccess() { + assertThat(authorized(() -> invokeAuthorize(null)).code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + var valid = request(Owner.ENTITY_MANAGEMENT); + assertThat( + authorized(() -> invokeAuthorize(valid.toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner, terms); + } + + @Test + void delegatesExactRequestAndEnvironmentCaptureAndPassesThroughOwnerBindingOnRetry() { + var wire = request(Owner.AUTOMATION_SCRIPTING); + var decoded = SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromRequest(wire); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + byte[] authorizationBytes = {1, 2, 3, 4}; + String digest = "a".repeat(64); + var binding = mock(SelectedOwnerIntakeAuthorizationBinding.class); + when(binding.owner()).thenReturn(decoded.owner()); + when(binding.targetNamespace()).thenReturn(NAMESPACE); + when(binding.intakeRequestId()).thenReturn(decoded.intakeRequestId()); + when(binding.selected()).thenReturn(decoded.selected()); + when(binding.intendedReader()) + .thenReturn("spiffe://firemud/ns/" + NAMESPACE + "/sa/automation-scripting-service"); + when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION"); + when(binding.digest()).thenReturn(digest); + when(binding.canonicalBytes()).thenReturn(authorizationBytes); + when(owner.authorizeWithEnvironmentCapture( + eq(CREDENTIAL), + eq(decoded.intakeRequestId()), + eq(decoded.owner()), + eq(decoded.selected()), + any())) + .thenAnswer( + call -> { + Supplier capture = call.getArgument(4); + assertThat(capture.get()).isSameAs(captured); + return binding; + }); + + var first = authorized(() -> invokeAuthorize(wire)); + var retry = authorized(() -> invokeAuthorize(wire)); + assertThat(first.error()).isNull(); + assertThat(retry.error()).isNull(); + for (var result : List.of(first, retry)) { + assertThat(result.response().getRequest()).isEqualTo(wire); + assertThat(result.response().getIntakeAuthorizationBinding().toByteArray()) + .containsExactly(authorizationBytes); + assertThat(result.response().getIntakeAuthorizationDigest()).isEqualTo(digest); + assertThat(result.response().toString()).doesNotContain(CREDENTIAL); + } + verify(owner, times(2)) + .authorizeWithEnvironmentCapture( + eq(CREDENTIAL), + eq(decoded.intakeRequestId()), + eq(decoded.owner()), + eq(decoded.selected()), + any()); + assertThat(wire.toString()).doesNotContain(CREDENTIAL); + } + + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeCallingOwner() { + var wire = request(Owner.ENTITY_MANAGEMENT); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThat(authorized(() -> invokeAuthorize(wire)).code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThat(authorized(() -> invokeAuthorize(wire)).code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(owner, terms); + } + + @Test + void sanitizesOwnerFailures() { + when(owner.authorizeWithEnvironmentCapture(any(), any(), any(), any(), any())) + .thenThrow(Status.PERMISSION_DENIED.withDescription(CREDENTIAL).asRuntimeException()); + var denied = authorized(() -> invokeAuthorize(request(Owner.ENTITY_MANAGEMENT))); + assertThat(denied.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + assertThat(denied.error().getCause()).isNull(); + } + + private record Result( + SelectedOwnerIntakeAuthorizationProducerResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private Result invokeAuthorize(SelectedOwnerIntakeAuthorizationProducerRequest request) { + var response = new AtomicReference(); + var error = new AtomicReference(); + var observer = + new io.grpc.stub.StreamObserver() { + @Override + public void onNext(SelectedOwnerIntakeAuthorizationProducerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() {} + }; + receiver.authorizeSelectedOwnerIntake(request, observer); + return new Result(response.get(), error.get()); + } + + @SuppressWarnings("unchecked") + private Status.Code boundCode(io.grpc.Metadata headers, String replacementMethodName) { + var method = + (io.grpc.ServerMethodDefinition< + SelectedOwnerIntakeAuthorizationProducerRequest, + SelectedOwnerIntakeAuthorizationProducerResponse>) + receiver.bindService().getMethods().stream().findFirst().orElseThrow(); + io.grpc.ServerCall< + SelectedOwnerIntakeAuthorizationProducerRequest, + SelectedOwnerIntakeAuthorizationProducerResponse> + call = mock(io.grpc.ServerCall.class); + var descriptor = method.getMethodDescriptor(); + if (replacementMethodName != null) { + descriptor = + MethodDescriptor + . + newBuilder() + .setType(descriptor.getType()) + .setFullMethodName( + AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc.SERVICE_NAME + + "/" + + replacementMethodName) + .setRequestMarshaller(descriptor.getRequestMarshaller()) + .setResponseMarshaller(descriptor.getResponseMarshaller()) + .build(); + } + when(call.getMethodDescriptor()).thenReturn(descriptor); + method.getServerCallHandler().startCall(call, headers); + var status = org.mockito.ArgumentCaptor.forClass(Status.class); + org.mockito.Mockito.verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any()); + return status.getValue().getCode(); + } + + private static T authorized(Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(CREDENTIAL)); + var previous = context.attach(); + try { + return peer(NAMESPACE, "game-design-service", action); + } finally { + context.detach(previous); + } + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static SelectedOwnerIntakeAuthorizationProducerRequest request(Owner owner) { + var safe = + SelectedOwnerIntakeAuthorizationProducerEvidence.Request.create( + NAMESPACE, UUID.randomUUID(), owner, selected()); + return SelectedOwnerIntakeAuthorizationProducerProtoCodec.toRequest(safe); + } + + private static DraftCommitBinding selected() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 1, "private", 2, "private", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULE_SET", + version.toString(), + "GAMEPLAY_RULE_SET", + "effective", + "0"))); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index e808ce56c1..67fa43743a 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceClient; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; @@ -258,6 +259,21 @@ public Recovery abortSelectedOwnerSourceRead( return asStipulatedGameDesignPeer(namespace, () -> service.abortSourceRead(scope)); } + /** Real unregistered producer; callers must authenticate the Game Design peer over transport. */ + public io.grpc.BindableService selectedOwnerIntakeAuthorizationProducerReceiver( + SelectedOwnerIntakeSourceClient sources, String namespace) { + var owner = + new AccountSelectedOwnerIntakeAuthorizationService( + actors, + f.fences, + new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl), + sources, + f.manager, + namespace); + return new AccountSelectedOwnerIntakeAuthorizationProducerGrpcService( + owner, f.terms, namespace); + } + private AccountSelectedOwnerIntakeSourceReservationService selectedOwnerSourceReservationService( String namespace) { return new AccountSelectedOwnerIntakeSourceReservationService( diff --git a/services/automation-scripting-service/build.gradle.kts b/services/automation-scripting-service/build.gradle.kts index 50a061526d..473608e839 100644 --- a/services/automation-scripting-service/build.gradle.kts +++ b/services/automation-scripting-service/build.gradle.kts @@ -10,3 +10,18 @@ plugins { dependencies { compileOnly(libs.spotbugs.annotations) } + +// Opt-in proof artifact: expose Automation classes to owner integration tests without its +// application or migration resources. +val automationClassesProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("classes-proof") + dependsOn(tasks.named("classes")) + from(sourceSets.main.get().output.classesDirs) +} + +val automationClassesProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(automationClassesProofJar) +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentials.java new file mode 100644 index 0000000000..119ec8f098 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentials.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import io.grpc.CallCredentials; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import io.grpc.Status; +import java.util.Iterator; +import java.util.concurrent.Executor; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc; + +/** Method-scoped protected metadata for the unchanged selected-owner creator credential. */ +public final class SelectedOwnerIntakeAuthorizationProducerCredentials { + public static final int MAX_CREDENTIAL_CHARS = 16384; + public static final Context.Key CONTEXT_KEY = + Context.key("selected-owner-intake-authorization-original-creator"); + public static final Metadata.Key HEADER = + Metadata.Key.of( + "x-firemud-selected-owner-intake-creator", + new Metadata.AsciiMarshaller<>() { + @Override + public String toAsciiString(Credential value) { + return value.value(); + } + + // Credential validation is deferred until after the receiving peer is authenticated. + @Override + public Credential parseAsciiString(String serialized) { + return new Credential(serialized); + } + }); + + private SelectedOwnerIntakeAuthorizationProducerCredentials() {} + + public static final class Credential { + private final String credential; + + private Credential(String credential) { + this.credential = credential; + } + + public static Credential of(String value) { + if (!validCredential(value)) throw invalid(); + return new Credential(value); + } + + public String value() { + if (!validCredential(credential)) throw invalid(); + return credential; + } + + @Override + public String toString() { + return "SelectedOwnerIntakeAuthorizationCredential[redacted]"; + } + } + + /** Call only after authenticating the exact same-namespace Game Design workload. */ + public static Credential readAuthenticated(Metadata headers, String methodName) { + if (!allowedMethod(methodName) || headers == null) throw invalid(); + Iterable values = headers.getAll(HEADER); + if (values == null) throw invalid(); + Iterator iterator = values.iterator(); + if (!iterator.hasNext()) throw invalid(); + Credential credential = iterator.next(); + if (iterator.hasNext()) throw invalid(); + credential.value(); + return credential; + } + + public static CallCredentials forAuthorize(String value) { + Credential credential = Credential.of(value); + return new CallCredentials() { + @Override + public void applyRequestMetadata( + RequestInfo info, Executor executor, MetadataApplier applier) { + if (info.getSecurityLevel() != SecurityLevel.PRIVACY_AND_INTEGRITY + || info.getMethodDescriptor() == null + || !AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .getAuthorizeSelectedOwnerIntakeMethod() + .getFullMethodName() + .equals(info.getMethodDescriptor().getFullMethodName())) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Protected selected-owner intake producer transport required")); + return; + } + var headers = new Metadata(); + headers.put(HEADER, credential); + applier.apply(headers); + } + + @Override + public void thisUsesUnstableApi() {} + + @Override + public String toString() { + return "SelectedOwnerIntakeAuthorizationCallCredentials[redacted]"; + } + }; + } + + public static boolean allowedMethod(String methodName) { + return AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .getAuthorizeSelectedOwnerIntakeMethod() + .getFullMethodName() + .equals(methodName); + } + + private static boolean validCredential(String credential) { + return credential != null + && !credential.isEmpty() + && credential.length() <= MAX_CREDENTIAL_CHARS + && credential.chars().allMatch(value -> value > 32 && value < 127); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-owner intake creator metadata"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerEvidence.java new file mode 100644 index 0000000000..6e15f0de5f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerEvidence.java @@ -0,0 +1,220 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Immutable evidence for the distinct selected-owner Account authorization producer transport. */ +public final class SelectedOwnerIntakeAuthorizationProducerEvidence { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_SELECTION_BYTES = SelectedOwnerIntakeSourceReadScope.MAX_BYTES; + + private SelectedOwnerIntakeAuthorizationProducerEvidence() {} + + /** Closed producer request. The selected Draft bytes are retained and returned exactly. */ + public static final class Request { + private final int schemaVersion; + private final String targetNamespace; + private final UUID transportRequestId; + private final UUID intakeRequestId; + private final Owner owner; + private final byte[] selectedDraftBinding; + + public Request( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + UUID intakeRequestId, + Owner owner, + byte[] selectedDraftBinding) { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !isSupportedOwner(owner)) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(transportRequestId); + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + if (transportRequestId.equals(intakeRequestId)) throw invalid(); + if (selectedDraftBinding == null + || selectedDraftBinding.length == 0 + || selectedDraftBinding.length > MAX_SELECTION_BYTES) { + throw invalid(); + } + this.schemaVersion = schemaVersion; + this.targetNamespace = targetNamespace; + this.transportRequestId = transportRequestId; + this.intakeRequestId = intakeRequestId; + this.owner = owner; + this.selectedDraftBinding = selectedDraftBinding.clone(); + DraftCommitBinding selected = decodeSelection(this.selectedDraftBinding); + if (transportRequestId.equals(selected.requestId()) + || transportRequestId.equals(selected.commitId())) { + throw invalid(); + } + } + + public static Request create( + String namespace, UUID intakeRequestId, Owner owner, DraftCommitBinding selected) { + Objects.requireNonNull(selected, "selected Draft binding is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (correlation.equals(intakeRequestId) + || correlation.equals(selected.requestId()) + || correlation.equals(selected.commitId())); + return new Request( + SCHEMA_VERSION, + namespace, + correlation, + intakeRequestId, + owner, + selected.canonicalBytes()); + } + + public int schemaVersion() { + return schemaVersion; + } + + public String targetNamespace() { + return targetNamespace; + } + + public UUID transportRequestId() { + return transportRequestId; + } + + public UUID intakeRequestId() { + return intakeRequestId; + } + + public Owner owner() { + return owner; + } + + public byte[] selectedDraftBinding() { + return selectedDraftBinding.clone(); + } + + public DraftCommitBinding selected() { + return decodeSelection(selectedDraftBinding); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof Request request)) return false; + return schemaVersion == request.schemaVersion + && targetNamespace.equals(request.targetNamespace) + && transportRequestId.equals(request.transportRequestId) + && intakeRequestId.equals(request.intakeRequestId) + && owner == request.owner + && Arrays.equals(selectedDraftBinding, request.selectedDraftBinding); + } + + @Override + public int hashCode() { + int result = + Objects.hash(schemaVersion, targetNamespace, transportRequestId, intakeRequestId, owner); + return 31 * result + Arrays.hashCode(selectedDraftBinding); + } + + @Override + public String toString() { + return "SelectedOwnerIntakeAuthorizationProducer.Request[redacted]"; + } + } + + /** Exact immutable authorization returned by Account, including its canonical digest. */ + public static final class Result { + private final Request request; + private final SelectedOwnerIntakeAuthorizationBinding binding; + private final String digest; + + public Result(Request request, SelectedOwnerIntakeAuthorizationBinding binding, String digest) { + this.request = Objects.requireNonNull(request, "producer request is required"); + this.binding = Objects.requireNonNull(binding, "finalized authorization binding is required"); + this.digest = Objects.requireNonNull(digest, "authorization digest is required"); + requireBindingMatches(request, binding); + if (!binding.digest().equals(digest)) throw invalid(); + } + + public Request request() { + return request; + } + + public SelectedOwnerIntakeAuthorizationBinding binding() { + return binding; + } + + public String digest() { + return digest; + } + + public byte[] canonicalBindingBytes() { + return binding.canonicalBytes(); + } + + @Override + public String toString() { + return "SelectedOwnerIntakeAuthorizationProducer.Result[redacted]"; + } + } + + static void requireBindingMatches( + Request request, SelectedOwnerIntakeAuthorizationBinding binding) { + if (binding.owner() != request.owner() + || !binding.targetNamespace().equals(request.targetNamespace()) + || !binding.intakeRequestId().equals(request.intakeRequestId()) + || !Arrays.equals(binding.selected().canonicalBytes(), request.selectedDraftBinding()) + || !binding + .intendedReader() + .equals(intendedReader(request.owner(), request.targetNamespace())) + || !binding.purpose().equals(purpose(request.owner()))) { + throw invalid(); + } + } + + static boolean isSupportedOwner(Owner owner) { + return owner == Owner.ENTITY_MANAGEMENT || owner == Owner.AUTOMATION_SCRIPTING; + } + + static String intendedReader(Owner owner, String namespace) { + String workload = + switch (owner) { + case ENTITY_MANAGEMENT -> "entity-management-service"; + case AUTOMATION_SCRIPTING -> "automation-scripting-service"; + default -> throw invalid(); + }; + return "spiffe://firemud/ns/" + namespace + "/sa/" + workload; + } + + static String purpose(Owner owner) { + return switch (owner) { + case ENTITY_MANAGEMENT -> "ENTITY_INTAKE_RETENTION"; + case AUTOMATION_SCRIPTING -> "AUTOMATION_INTAKE_RETENTION"; + default -> throw invalid(); + }; + } + + private static DraftCommitBinding decodeSelection(byte[] bytes) { + try { + String json = new String(bytes, StandardCharsets.UTF_8); + DraftCommitBinding selected = + DraftCommitBinding.fromStored(json, DraftAuthorizationFenceBinding.digest(bytes)); + if (!Arrays.equals(bytes, selected.canonicalBytes())) throw invalid(); + return selected; + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException( + "Invalid selected-owner intake authorization producer evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodec.java new file mode 100644 index 0000000000..bc562791ed --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodec.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerOwner; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence.Request; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence.Result; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; + +/** Closed request and exact authorization response mapping for the selected-owner producer. */ +public final class SelectedOwnerIntakeAuthorizationProducerProtoCodec { + public static final int MAX_WIRE_BYTES = 24 * 1024 * 1024; + public static final int MAX_AUTHORIZATION_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES; + + private SelectedOwnerIntakeAuthorizationProducerProtoCodec() {} + + public static SelectedOwnerIntakeAuthorizationProducerRequest toRequest(Request request) { + Objects.requireNonNull(request, "producer request is required"); + byte[] selection = request.selectedDraftBinding(); + if (selection.length == 0 + || selection.length + > SelectedOwnerIntakeAuthorizationProducerEvidence.MAX_SELECTION_BYTES) { + throw invalid("Selected Draft binding exceeds the 4 MiB scope limit"); + } + var wire = + SelectedOwnerIntakeAuthorizationProducerRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setTransportRequestId(request.transportRequestId().toString()) + .setIntakeRequestId(request.intakeRequestId().toString()) + .setOwner(toWire(request.owner())) + .setSelectedDraftBinding(ByteString.copyFrom(selection)) + .build(); + requireWithinBudget(wire.getSerializedSize()); + return wire; + } + + public static Request fromRequest(SelectedOwnerIntakeAuthorizationProducerRequest wire) { + requireKnownAndWithinBudget(wire, "request"); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getTransportRequestId()); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getIntakeRequestId()); + byte[] selection = wire.getSelectedDraftBinding().toByteArray(); + if (selection.length == 0 + || selection.length + > SelectedOwnerIntakeAuthorizationProducerEvidence.MAX_SELECTION_BYTES) { + throw invalid("Selected Draft binding size is invalid"); + } + Request request = + new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getTransportRequestId()), + UUID.fromString(wire.getIntakeRequestId()), + fromWire(wire.getOwner()), + selection); + if (!Arrays.equals(selection, request.selectedDraftBinding()) + || !toRequest(request).equals(wire)) { + throw invalid("Selected Draft binding or request is noncanonical"); + } + return request; + } + + public static SelectedOwnerIntakeAuthorizationProducerResponse toResponse(Result result) { + Objects.requireNonNull(result, "Account authorization result is required"); + byte[] binding = result.canonicalBindingBytes(); + if (binding.length == 0 || binding.length > MAX_AUTHORIZATION_BYTES) { + throw invalid("Complete authorization binding exceeds its 16 MiB limit"); + } + var response = + SelectedOwnerIntakeAuthorizationProducerResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setIntakeAuthorizationBinding(ByteString.copyFrom(binding)) + .setIntakeAuthorizationDigest(result.digest()) + .build(); + requireWithinBudget(response.getSerializedSize()); + return response; + } + + public static Result fromResponse( + Request request, SelectedOwnerIntakeAuthorizationProducerResponse response) { + Objects.requireNonNull(request, "producer request is required"); + requireKnownAndWithinBudget(response, "response"); + if (!response.hasRequest()) throw invalid("Complete request echo is required"); + requireKnownAndWithinBudget(response.getRequest(), "echoed request"); + if (!toRequest(request).equals(response.getRequest())) { + throw invalid("Account changed the selected-owner producer request"); + } + byte[] bindingBytes = response.getIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 || bindingBytes.length > MAX_AUTHORIZATION_BYTES) { + throw invalid("Complete authorization binding size is invalid"); + } + SelectedOwnerIntakeAuthorizationBinding binding; + try { + binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + } catch (RuntimeException malformed) { + throw invalid("Complete authorization binding is malformed or noncanonical"); + } + if (!Arrays.equals(bindingBytes, binding.canonicalBytes()) + || !binding.digest().equals(response.getIntakeAuthorizationDigest())) { + throw invalid("Complete authorization binding or SHA-256 digest differs"); + } + return new Result(request, binding, response.getIntakeAuthorizationDigest()); + } + + private static SelectedOwnerIntakeAuthorizationProducerOwner toWire(Owner owner) { + return switch (owner) { + case ENTITY_MANAGEMENT -> + SelectedOwnerIntakeAuthorizationProducerOwner + .SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_ENTITY_MANAGEMENT; + case AUTOMATION_SCRIPTING -> + SelectedOwnerIntakeAuthorizationProducerOwner + .SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_AUTOMATION_SCRIPTING; + default -> throw invalid("Unsupported selected-owner intake authorization owner"); + }; + } + + private static Owner fromWire(SelectedOwnerIntakeAuthorizationProducerOwner owner) { + return switch (owner) { + case SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_ENTITY_MANAGEMENT -> + Owner.ENTITY_MANAGEMENT; + case SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_AUTOMATION_SCRIPTING -> + Owner.AUTOMATION_SCRIPTING; + default -> throw invalid("Unsupported or unspecified selected-owner intake owner"); + }; + } + + private static void requireKnownAndWithinBudget(Message wire, String label) { + if (wire == null || wire.getSerializedSize() > MAX_WIRE_BYTES) { + throw invalid("Missing or oversized selected-owner producer " + label); + } + if (!wire.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown selected-owner producer " + label + " fields"); + } + } + + private static void requireWithinBudget(int size) { + if (size > MAX_WIRE_BYTES) { + throw invalid("Selected-owner producer message exceeds its 24 MiB wire budget"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java new file mode 100644 index 0000000000..991d91f0ad --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Metadata; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc; +import org.junit.jupiter.api.Test; + +class SelectedOwnerIntakeAuthorizationProducerCredentialsTest { + private static final String SECRET = "original.creator.credential"; + + @Test + void acceptsOnlyTheAuthorizeSelectedOwnerIntakeMethod() { + String allowedMethod = + AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .getAuthorizeSelectedOwnerIntakeMethod() + .getFullMethodName(); + + assertThat(SelectedOwnerIntakeAuthorizationProducerCredentials.allowedMethod(allowedMethod)) + .isTrue(); + assertThat(SelectedOwnerIntakeAuthorizationProducerCredentials.allowedMethod("other/Method")) + .isFalse(); + assertThat( + SelectedOwnerIntakeAuthorizationProducerCredentials.allowedMethod( + "account.v1.OtherService/AuthorizeSelectedOwnerIntake")) + .isFalse(); + + var headers = new Metadata(); + headers.put( + SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(SECRET)); + assertThat( + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + headers, allowedMethod) + .value()) + .isEqualTo(SECRET); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + headers, "other/Method")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void requiresExactlyOneCredentialAndRedactsItsTextRepresentation() { + var missing = new Metadata(); + var one = new Metadata(); + var credential = SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(SECRET); + one.put(SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, credential); + var duplicate = new Metadata(); + duplicate.put( + SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(SECRET)); + duplicate.put( + SelectedOwnerIntakeAuthorizationProducerCredentials.HEADER, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of("second.credential")); + String method = + AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .getAuthorizeSelectedOwnerIntakeMethod() + .getFullMethodName(); + + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + missing, method)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + duplicate, method)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(credential.toString()).doesNotContain(SECRET); + assertThat(SelectedOwnerIntakeAuthorizationProducerCredentials.forAuthorize(SECRET).toString()) + .doesNotContain(SECRET); + } + + @Test + void rejectsBlankWhitespaceNonAsciiAndOversizedCredentialsWithoutTrimming() { + for (String invalid : + new String[] { + null, + "", + " ", + "has whitespace", + "\ttab", + "non-ascii-\u00e9", + "x".repeat(SelectedOwnerIntakeAuthorizationProducerCredentials.MAX_CREDENTIAL_CHARS + 1) + }) { + assertThatThrownBy( + () -> SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat( + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of( + "x" + .repeat( + SelectedOwnerIntakeAuthorizationProducerCredentials + .MAX_CREDENTIAL_CHARS)) + .value()) + .hasSize(SelectedOwnerIntakeAuthorizationProducerCredentials.MAX_CREDENTIAL_CHARS); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java new file mode 100644 index 0000000000..e0dca16491 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java @@ -0,0 +1,256 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +class SelectedOwnerIntakeAuthorizationProducerProtoCodecTest { + @Test + void roundTripsExactCanonicalSelectionAndCompleteOwnerAuthorization() { + for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(owner); + var request = + new Request( + 1, + "test", + UUID.randomUUID(), + binding.intakeRequestId(), + owner, + binding.selected().canonicalBytes()); + var wireRequest = SelectedOwnerIntakeAuthorizationProducerProtoCodec.toRequest(request); + + assertThat(SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromRequest(wireRequest)) + .isEqualTo(request); + assertThat(wireRequest.getSelectedDraftBinding().toByteArray()) + .containsExactly(binding.selected().canonicalBytes()); + var result = + new SelectedOwnerIntakeAuthorizationProducerEvidence.Result( + request, binding, binding.digest()); + var response = SelectedOwnerIntakeAuthorizationProducerProtoCodec.toResponse(result); + assertThat(response.getRequest()).isEqualTo(wireRequest); + assertThat(response.getIntakeAuthorizationBinding().toByteArray()) + .containsExactly(binding.canonicalBytes()); + assertThat(response.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + + var decoded = + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, response); + assertThat(decoded.request()).isEqualTo(request); + assertThat(decoded.binding().canonicalBytes()).containsExactly(binding.canonicalBytes()); + assertThat(decoded.digest()).isEqualTo(binding.digest()); + } + } + + @Test + void rejectsChangedTransportNamespaceIntakeOwnerAndSelectedDraftEchoes() { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var request = request(Owner.ENTITY_MANAGEMENT, binding); + var response = response(request, binding); + var exactEcho = response.getRequest(); + var changed = + List.of( + exactEcho.toBuilder().setTransportRequestId(UUID.randomUUID().toString()).build(), + exactEcho.toBuilder().setTargetNamespace("other").build(), + exactEcho.toBuilder().setIntakeRequestId(UUID.randomUUID().toString()).build(), + exactEcho.toBuilder() + .setOwner( + net.firedevops.firemud.account.v1.SelectedOwnerIntakeAuthorizationProducerOwner + .SELECTED_OWNER_INTAKE_AUTHORIZATION_PRODUCER_OWNER_AUTOMATION_SCRIPTING) + .build(), + exactEcho.toBuilder().setSelectedDraftBinding(ByteString.copyFromUtf8("{}")).build()); + + for (var echo : changed) { + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( + request, response.toBuilder().setRequest(echo).build())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void acceptsDifferentAccountSourceCaptureButRejectsMismatchedOwnerAndDigest() { + var entity = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var automation = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = request(Owner.ENTITY_MANAGEMENT, entity); + var response = response(request, entity); + + var changedSources = new java.util.ArrayList<>(entity.sources()); + var source = changedSources.get(0); + changedSources.set( + 0, + new SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + new byte[] {9, 8, 7})); + var changedCompleteBinding = + new SelectedOwnerIntakeAuthorizationBinding(entity.content(), changedSources); + var changedAccountSourceResponse = + response.toBuilder() + .setIntakeAuthorizationBinding( + ByteString.copyFrom(changedCompleteBinding.canonicalBytes())) + .setIntakeAuthorizationDigest(changedCompleteBinding.digest()) + .build(); + var accepted = + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( + request, changedAccountSourceResponse); + assertThat(accepted.binding().canonicalBytes()) + .containsExactly(changedCompleteBinding.canonicalBytes()); + + var mismatchedOwnerBinding = + response.toBuilder() + .setIntakeAuthorizationBinding(ByteString.copyFrom(automation.canonicalBytes())) + .setIntakeAuthorizationDigest(automation.digest()) + .build(); + var wrongDigest = + response.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build(); + + for (var changed : List.of(mismatchedOwnerBinding, wrongDigest)) { + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsUnknownDefaultMalformedAndOversizedRequestValues() { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var request = request(Owner.ENTITY_MANAGEMENT, binding); + var wire = SelectedOwnerIntakeAuthorizationProducerProtoCodec.toRequest(request); + var unknown = + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + var nestedUnknown = + SelectedOwnerIntakeAuthorizationProducerProtoCodec.toResponse( + new SelectedOwnerIntakeAuthorizationProducerEvidence.Result( + request, binding, binding.digest())) + .toBuilder() + .setRequest( + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()) + .build(); + var malformed = + wire.toBuilder().setSelectedDraftBinding(ByteString.copyFrom(new byte[] {1, 2, 3})).build(); + var unspecifiedOwner = wire.toBuilder().clearOwner().build(); + var unknownOwner = wire.toBuilder().setOwnerValue(99).build(); + var oversizedSelection = + wire.toBuilder() + .setSelectedDraftBinding( + ByteString.copyFrom( + new byte + [SelectedOwnerIntakeAuthorizationProducerEvidence.MAX_SELECTION_BYTES + 1])) + .build(); + + for (var changed : + List.of(unknown, malformed, unspecifiedOwner, unknownOwner, oversizedSelection)) { + assertThatThrownBy( + () -> SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + var unknownResponse = + SelectedOwnerIntakeAuthorizationProducerProtoCodec.toResponse( + new SelectedOwnerIntakeAuthorizationProducerEvidence.Result( + request, binding, binding.digest())) + .toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( + request, nestedUnknown)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( + request, unknownResponse)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMalformedNoncanonicalOrOversizedAuthorizationBinding() { + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = request(Owner.AUTOMATION_SCRIPTING, binding); + var exact = response(request, binding); + var malformed = + exact.toBuilder() + .setIntakeAuthorizationBinding(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + var oversized = + exact.toBuilder() + .setIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .build(); + var missing = SelectedOwnerIntakeAuthorizationProducerResponse.getDefaultInstance(); + + for (var changed : List.of(malformed, oversized, missing)) { + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsResponsesBeyondTheTwentyFourMibWireBudget() { + var binding = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var request = request(Owner.ENTITY_MANAGEMENT, binding); + var oversizedEcho = + SelectedOwnerIntakeAuthorizationProducerProtoCodec.toRequest(request).toBuilder() + .setSelectedDraftBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationProducerProtoCodec.MAX_WIRE_BYTES])) + .build(); + var oversized = response(request, binding).toBuilder().setRequest(oversizedEcho).build(); + + assertThat(oversized.getSerializedSize()) + .isGreaterThan(SelectedOwnerIntakeAuthorizationProducerProtoCodec.MAX_WIRE_BYTES); + assertThatThrownBy( + () -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, oversized)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Request request(Owner owner, SelectedOwnerIntakeAuthorizationBinding binding) { + return new Request( + 1, + "test", + UUID.randomUUID(), + binding.intakeRequestId(), + owner, + binding.selected().canonicalBytes()); + } + + private static SelectedOwnerIntakeAuthorizationProducerResponse response( + Request request, SelectedOwnerIntakeAuthorizationBinding binding) { + return SelectedOwnerIntakeAuthorizationProducerProtoCodec.toResponse( + new SelectedOwnerIntakeAuthorizationProducerEvidence.Result( + request, binding, binding.digest())); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeAuthorizationProducerClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeAuthorizationProducerClient.java new file mode 100644 index 0000000000..fc1b0743d3 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeAuthorizationProducerClient.java @@ -0,0 +1,185 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import io.grpc.CompositeCallCredentials; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence.Request; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence.Result; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerProtoCodec; +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.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for the standalone, unregistered Account selected-owner producer. */ +public final class GrpcSelectedOwnerIntakeAuthorizationProducerClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationProducerServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcSelectedOwnerIntakeAuthorizationProducerClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcSelectedOwnerIntakeAuthorizationProducerClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account selected-owner producer client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account selected-owner producer stub unavailable"); + } + initialized = true; + } + + /** + * Calls the original Account owner with the same stable request identity on every exact retry. + */ + public Result authorize(Request request, String originalCreatorCredential) { + requireNoAmbientContext(); + Objects.requireNonNull(request, "selected-owner producer request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException("Account selected-owner producer namespace mismatch"); + } + var wireRequest = SelectedOwnerIntakeAuthorizationProducerProtoCodec.toRequest(request); + var current = stub(); + if (closed || !initialized || current == null) { + throw new IllegalStateException("Account selected-owner producer client unavailable"); + } + var credentials = + SelectedOwnerIntakeAuthorizationProducerCredentials.forAuthorize(originalCreatorCredential); + try { + var secured = + current + .withCallCredentials( + new CompositeCallCredentials( + new GrpcServerPeerIdentityCallCredentials( + accountServerPeerUri(workloadNamespace)), + credentials)) + .withMaxOutboundMessageSize( + SelectedOwnerIntakeAuthorizationProducerProtoCodec.MAX_WIRE_BYTES) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + var response = secured.authorizeSelectedOwnerIntake(wireRequest); + return SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, response); + } catch (StatusRuntimeException unavailable) { + throw Status.fromCode(unavailable.getStatus().getCode()) + .withDescription("Account selected-owner intake authorization denied or unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Account returned invalid selected-owner intake authorization evidence"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc + .AccountSelectedOwnerIntakeAuthorizationProducerServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = accountServerPeerUri(workloadNamespace); + return AccountSelectedOwnerIntakeAuthorizationProducerServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + SelectedOwnerIntakeAuthorizationProducerProtoCodec.MAX_WIRE_BYTES) + .withMaxOutboundMessageSize( + SelectedOwnerIntakeAuthorizationProducerProtoCodec.MAX_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private static void requireNoAmbientContext() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account selected-owner authorization requires no ambient SQL or synchronization"); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException( + "Account selected-owner authorization requires workload-only context"); + } + } + + private static String accountServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account selected-owner authorization requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account selected-owner authorization requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Invalid Account selected-owner authorization " + label + " path"); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account selected-owner authorization " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeAuthorizationProducerClientTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeAuthorizationProducerClientTest.java new file mode 100644 index 0000000000..0567ffe94c --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeAuthorizationProducerClientTest.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Constructor and pre-transport gates only; placeholder files do not prove an mTLS handshake. */ +class GrpcSelectedOwnerIntakeAuthorizationProducerClientTest { + @AfterEach + void clearAmbientContext() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void requiresReadableFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) + throws IOException { + var channelFactory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeAuthorizationProducerClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + for (String invalidPath : + new String[] { + null, + "", + "classpath:credential.pem", + directory.toString(), + directory.resolve("missing.pem").toString() + }) { + var invalidCertificate = tls(directory); + invalidCertificate.setCertChain(invalidPath); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeAuthorizationProducerClient( + new ServiceEndpointsProperties(), invalidCertificate, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var invalidKey = tls(directory); + invalidKey.setPrivateKey(directory.resolve("missing-key.pem").toString()); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeAuthorizationProducerClient( + new ServiceEndpointsProperties(), invalidKey, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + var invalidCa = tls(directory); + invalidCa.setCaCert(directory.resolve("missing-ca.pem").toString()); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeAuthorizationProducerClient( + new ServiceEndpointsProperties(), invalidCa, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeAuthorizationProducerClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "Test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsAmbientSqlSynchronizationAndEndUserContextBeforeInitOrTransport( + @TempDir Path directory) throws IOException { + var channelFactory = mock(GrpcChannelFactory.class); + var client = + new GrpcSelectedOwnerIntakeAuthorizationProducerClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "test"); + var request = request("test"); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.authorize(request, "creator.credential")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.authorize(request, "creator.credential")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + + SessionContext.setContext("101", List.of(), Map.of()); + assertThatThrownBy(() -> client.authorize(request, "creator.credential")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + SessionContext.clear(); + + assertThatThrownBy(() -> client.authorize(request("other"), "creator.credential")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace mismatch"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + } + + private static CommonGrpcClientProperties tls(Path directory) throws IOException { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain( + Files.writeString(directory.resolve("client.crt"), "placeholder cert").toString()); + tls.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "placeholder key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "placeholder CA").toString()); + return tls; + } + + private static SelectedOwnerIntakeAuthorizationProducerEvidence.Request request( + String namespace) { + UUID tenant = UUID.fromString("11111111-1111-4111-8111-111111111111"); + UUID version = UUID.fromString("22222222-2222-4222-8222-222222222222"); + var selected = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + tenant, version, 1L, "tenant", 2L, "tenant", "NEW_GAME_ROW"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "DESIGN", + version.toString(), + "DESIGN", + "effective", + "0"))); + return SelectedOwnerIntakeAuthorizationProducerEvidence.Request.create( + namespace, + UUID.fromString("55555555-5555-4555-8555-555555555555"), + DraftCommitBinding.Owner.ENTITY_MANAGEMENT, + selected); + } +} diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index fb84c97252..d6d1812b60 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -26,7 +26,22 @@ testing { dependencies { integrationTestImplementation(project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof"))) integrationTestImplementation(project(mapOf("path" to ":game-logic-service", "configuration" to "gameLogicClassesProof"))) - integrationTestImplementation(project(mapOf("path" to ":world-management-service", "configuration" to "worldClassesProof"))) + integrationTestImplementation( + project( + mapOf( + "path" to ":world-management-service", + "configuration" to "worldSelectedOwnerInventoryProof" + ) + ) + ) + integrationTestImplementation( + project( + mapOf( + "path" to ":automation-scripting-service", + "configuration" to "automationClassesProof" + ) + ) + ) integrationTestImplementation("io.grpc:grpc-util:${libs.versions.grpc.get()}") compileOnly(libs.spotbugs.annotations) testCompileOnly(libs.spotbugs.annotations) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 42af404011..9aad9a3501 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -48,7 +48,17 @@ import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeTerminalReadService; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedSourceIntakeTerminalReadGrpcService; import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeAuthorizationGrpcClient; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient; +import net.firedevops.firemud.common.account.sourceintake.GrpcSelectedOwnerIntakeSourceReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; @@ -65,6 +75,8 @@ import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadClient; import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyClient; import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.gamedesign.AssetSource; @@ -72,7 +84,9 @@ import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; @@ -105,8 +119,10 @@ import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedOwnerInventoryGrpcClient; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; import net.firedevops.firemud.common.security.PublicationReadGuard; +import net.firedevops.firemud.common.security.sourceintake.GrpcSelectedOwnerIntakeAuthorizationProducerClient; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; @@ -129,6 +145,8 @@ import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadGrpcService; import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadService; +import net.firedevops.firemud.gamedesign.publication.GameDesignSelectedOwnerIntakeSourceGrpcService; +import net.firedevops.firemud.gamedesign.publication.GameDesignSelectedOwnerIntakeSourceReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventoryReadService; @@ -139,7 +157,6 @@ import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationAdmissionService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociationRepository; -import net.firedevops.firemud.gamedesign.publication.SelectedOwnerIntakeSourceExport; import net.firedevops.firemud.gamedesign.publication.StartSessionLaunchDescriptorProducer; import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; @@ -216,6 +233,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalReadGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplicationService; import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplyGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldSelectedOwnerInventoryReadProofFixture; import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; @@ -266,12 +284,20 @@ * evidence are supplied by test context. The immutable selection read and held-order reads use * loopback mTLS. World freeze, immutable inventory and published selector use their actual owner * services over loopback mTLS, with the canonical frozen selector captured owner-locally from the - * committed freeze and retained APPLIED graph. Entity/Automation participant digests, in-memory S3 - * and the StartSession Account projection remain test doubles. The complete launch-binding case - * wires the actual Game Design handler and World Management mTLS client on this fixture's loopback - * server to the actual owner implementation in an explicitly established read-only repeatable-read - * snapshot; unrelated handler dependencies are isolated. This fixture does not provide - * production-mounted certificates or full application server wiring, Account-projection-backed + * committed freeze and retained APPLIED graph. Entity/Automation source disclosure uses the genuine + * Account issuer and retained preliminary reservations (the reservation helper's incoming Game + * Design peer is stipulated), then loopback mTLS for both the Account permission hop and the Game + * Design source hop. Automation additionally composes real Account finalization, the actual + * recipient-specific World closure/inventory reader, the Automation empty-source receipt owner, and + * Account terminal settlement. Its Account authorization command traverses the native producer over + * loopback mTLS; preliminary reservation and local Automation-retain/Account-settlement calls still + * use stipulated Game Design peer contexts. Entity retention and Entity/Automation publication + * participant digests, in-memory S3 and the StartSession Account projection remain test doubles. + * The complete launch-binding case wires the actual Game Design handler and World Management mTLS + * client on this fixture's loopback server to the actual owner implementation in an explicitly + * established read-only repeatable-read snapshot; unrelated handler dependencies are isolated. This + * fixture does not provide production-mounted certificates or full application server wiring, + * authenticated Automation retention/settlement command ingress, Account-projection-backed * StartSession admission, a complete four-owner authenticated release, runtime launch, activation * or registration. */ @@ -340,17 +366,20 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var gd = gameDesignStore(); var world = serviceStore(WORLD_POSTGRES, "world-management"); var gameLogic = serviceStore(GAME_LOGIC_POSTGRES, "game-logic"); + var automation = serviceStore(GAME_LOGIC_POSTGRES, "automation-scripting"); var pki = new TestPki(temporary.resolve("pki")); var gdHandlers = new MutableHandlerRegistry(); var worldHandlers = new MutableHandlerRegistry(); var accountHandlers = new MutableHandlerRegistry(); var gameLogicHandlers = new MutableHandlerRegistry(); + var automationHandlers = new MutableHandlerRegistry(); Map startSessionProjections = new ConcurrentHashMap<>(); Server gdServer = startServer(pki, "game-design-service", gdHandlers); Server worldServer = startServer(pki, "world-management-service", worldHandlers); Server accountServer = startServer(pki, "account-service", accountHandlers); Server gameLogicServer = startServer(pki, "game-logic-service", gameLogicHandlers); + Server automationServer = startServer(pki, "automation-scripting-service", automationHandlers); try (var account = new AccountControlUiOriginalOrderFixture( ACCOUNT_POSTGRES.getJdbcUrl(), @@ -365,7 +394,15 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex endpoints.setGameDesignService(loopback(gdServer)); endpoints.setWorldManagementService(loopback(worldServer)); endpoints.setGameLogicService(loopback(gameLogicServer)); + endpoints.setAutomationScriptingService(loopback(automationServer)); var channels = new GrpcChannelFactory(); + var automationIntakeRepository = + new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); + register( + automationHandlers, + new AutomationSelectedSourceIntakeTerminalReadGrpcService( + new AutomationEmptySelectedSourceIntakeTerminalReadService( + automationIntakeRepository, NAMESPACE))); var sourceRepository = new GameAuthoredWorldSourceRepository(gd.dsl()); register( @@ -414,6 +451,30 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var gdToAccountPermission = new GrpcGameLogicIntakeSourceReadClient( endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var gdToAccountSelectedOwnerPermission = + new GrpcSelectedOwnerIntakeSourceReadClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var accountToGdSelectedOwnerSource = + new GrpcSelectedOwnerIntakeSourceClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var gdToAccountSelectedOwnerAuthorizationProducer = + new GrpcSelectedOwnerIntakeAuthorizationProducerClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var wrongWorkloadSelectedOwnerAuthorizationProducer = + new GrpcSelectedOwnerIntakeAuthorizationProducerClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var automationToAccountHeld = + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, pki.client("automation-scripting-service"), channels, NAMESPACE); + var automationToWorldInventory = + new WorldSelectedOwnerInventoryGrpcClient( + endpoints, pki.client("automation-scripting-service"), channels, NAMESPACE); + var worldToAccountClosure = + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var accountToAutomationTerminal = + new AutomationSelectedSourceIntakeTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); var glToAccountHeld = new GameLogicIntakeAuthorizationReadClient( endpoints, pki.client("game-logic-service"), channels, NAMESPACE); @@ -572,6 +633,21 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var accountAccess = account.preparedOriginalCreator(); var accountRepository = new AccountGameLogicIntakeAuthorizationRepository(accountAccess.sources().dsl); + var accountSelectedOwnerSourceRepository = + new AccountSelectedOwnerIntakeSourceReservationRepository(accountAccess.sources().dsl); + var accountSelectedOwnerSourceReadOwner = + new AccountSelectedOwnerIntakeSourceReadService( + accountSelectedOwnerSourceRepository, + account.coordination(), + accountAccess.sources().manager, + NAMESPACE); + var accountSelectedSourceReads = new AtomicInteger(); + var observedAccountToGdSource = + (net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceClient) + request -> { + accountSelectedSourceReads.incrementAndGet(); + return accountToGdSelectedOwnerSource.read(request); + }; register( accountHandlers, @@ -579,7 +655,23 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new AccountDraftCommitOrderReadGrpcService( account.heldOrderOwner(NAMESPACE), NAMESPACE), new AccountPublicationAuthorizationReadGrpcService( - account.heldPublicationOwner(NAMESPACE), NAMESPACE)); + account.heldPublicationOwner(NAMESPACE), NAMESPACE), + new AccountSelectedOwnerIntakeSourceReadGrpcService( + accountSelectedOwnerSourceReadOwner, NAMESPACE), + new AccountSelectedOwnerIntakeAuthorizationReadGrpcService( + new AccountSelectedOwnerIntakeAuthorizationReadService( + accountSelectedOwnerSourceRepository, + accountAccess.sources().manager, + NAMESPACE), + NAMESPACE), + new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcService( + new AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService( + accountSelectedOwnerSourceRepository, + accountAccess.sources().manager, + NAMESPACE), + NAMESPACE), + account.selectedOwnerIntakeAuthorizationProducerReceiver( + observedAccountToGdSource, NAMESPACE)); var coordinator = new DraftCommitCoordinatorRepository(gd.dsl()); var gdTerminals = new GameDesignDraftTerminalOutcomeRepository(gd.dsl()); @@ -590,6 +682,10 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex gdHandlers, new GameDesignSelectedDraftPublicationReadGrpcService(selectionRepository, NAMESPACE)); var worldFence = new WorldDesignPublicationFenceRepository(world.dsl(), worldIntakes); + register( + worldHandlers, + WorldSelectedOwnerInventoryReadProofFixture.receiver( + NAMESPACE, world.dsl(), worldFence, worldToAccountClosure)); var worldApplications = new WorldDraftGraphApplicationRepository(world.dsl(), worldFence, new ObjectMapper()); var worldPublicationProof = @@ -628,6 +724,10 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex register( gdHandlers, new GameDesignDraftTerminalReadGrpcService(gdTerminals, NAMESPACE), + new GameDesignSelectedOwnerIntakeSourceGrpcService( + new GameDesignSelectedOwnerIntakeSourceReadService( + gdSources, gd.transactions(), gdToAccountSelectedOwnerPermission, NAMESPACE), + NAMESPACE), new GameDesignGameplayRuleSourceReadGrpcService( new GameDesignGameplayRuleSourceReadService( new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository( @@ -711,6 +811,14 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex worldTerminalClient.init(); accountToGdSource.init(); gdToAccountPermission.init(); + gdToAccountSelectedOwnerPermission.init(); + accountToGdSelectedOwnerSource.init(); + gdToAccountSelectedOwnerAuthorizationProducer.init(); + wrongWorkloadSelectedOwnerAuthorizationProducer.init(); + automationToAccountHeld.init(); + automationToWorldInventory.init(); + worldToAccountClosure.init(); + accountToAutomationTerminal.init(); glToAccountHeld.init(); glToGdSource.init(); accountToGlTerminal.init(); @@ -724,6 +832,9 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex selectedPublicationFreezeClient.init(); selectedPublicationInventoryClient.init(); publishedStartLocationClient.init(); + var automationIntakeOwner = + new AutomationEmptySelectedSourceIntakeService( + automationIntakeRepository, automationToAccountHeld, automationToWorldInventory); var sourceCommit = new GameDesignWorldSourceCommitService( @@ -851,32 +962,41 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var ownerIntakeSourceRepository = new GameDesignSourceRepository(gd.dsl()); var sourceRowsBeforeExport = selectedOwnerSourceRowCounts(gd.dsl()); for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { - // Account's real preliminary scope authorizes source-read participation only. The direct - // Game Design repository export below checks selected-source integrity, not authenticated - // transport, owner retention, settlement, or activation. + // Account's retained preliminary scope authorizes disclosure only through the two + // authenticated owner transports; this does not establish owner retention or settlement. var scope = owner == Owner.ENTITY_MANAGEMENT ? entitySourceReservation : automationSourceReservation; - SelectedOwnerIntakeSourceExport exportedSource = - ownerIntakeSourceRepository.requireSelectedOwnerIntakeSource(scope); - SelectedOwnerIntakeSourceExport exactRetry = - ownerIntakeSourceRepository.requireSelectedOwnerIntakeSource(scope); + var readRequest = SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope); + SelectedOwnerIntakeSourceContent exportedSource = + accountToGdSelectedOwnerSource.read(readRequest); + SelectedOwnerIntakeSourceContent exactRetry = + accountToGdSelectedOwnerSource.read(readRequest); + assertThat(exportedSource.scope().owner()).isEqualTo(owner); assertThat(exportedSource.scope().canonicalBytes()) .containsExactly(scope.canonicalBytes()); assertThat(exportedSource.scope().selected().canonicalBytes()) .containsExactly(selectedCommit.canonicalBytes()); - assertThat(exportedSource.sources().command().binding()).isEqualTo(selectedCommit); - assertThat(exportedSource.sources().policy().binding()).isEqualTo(selectedCommit); - assertThat(exportedSource.sources().asset().binding()).isEqualTo(selectedCommit); - assertThat(exportedSource.sources().gameplay().binding()).isEqualTo(selectedCommit); - assertThat(exportedSource.sources().branding().orElseThrow().binding()) - .isEqualTo(selectedCommit); - assertThat(exportedSource.sources().templateConfig().orElseThrow().binding()) - .isEqualTo(selectedCommit); + assertThat(exportedSource.snapshotBytes("COMMAND")) + .containsExactly(selectedSources.command().canonicalBytes()); + assertThat(exportedSource.snapshotBytes("REALM_POLICY")) + .containsExactly(selectedSources.policy().canonicalBytes()); + assertThat(exportedSource.snapshotBytes("ASSET")) + .containsExactly(selectedSources.asset().canonicalBytes()); + assertThat(exportedSource.snapshotBytes("GAMEPLAY_RULE")) + .containsExactly(selectedSources.gameplay().canonicalBytes()); + assertThat(exportedSource.snapshotBytes("BRANDING")) + .containsExactly(selectedSources.branding().orElseThrow().canonicalBytes()); + assertThat(exportedSource.snapshotBytes("TEMPLATE_CONFIG")) + .containsExactly(selectedSources.templateConfig().orElseThrow().canonicalBytes()); + assertThat(exportedSource.digest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(exportedSource.canonicalBytes())); assertThat(exactRetry.canonicalBytes()).containsExactly(exportedSource.canonicalBytes()); assertThat(exactRetry.digest()).isEqualTo(exportedSource.digest()); + assertThat(exactRetry.digest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(exactRetry.canonicalBytes())); } assertThat( selectedOwnerReservationSourceRows( @@ -898,6 +1018,25 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex .recoverSelectedOwnerSourceRead(automationSourceReservation, NAMESPACE) .state()) .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, entitySourceReservation.operationId())) + .containsExactlyElementsOf(entityReservationSourcesBeforeAbort); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, automationSourceReservation.operationId())) + .containsExactlyElementsOf(automationReservationSourcesBeforeAbort); + assertThatThrownBy( + () -> + accountToGdSelectedOwnerSource.read( + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, entitySourceReservation))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + assertThat(selectedOwnerSourceRowCounts(gd.dsl())).isEqualTo(sourceRowsBeforeExport); assertThat( selectedOwnerReservationSourceRows( accountSourceDsl, entitySourceReservation.operationId())) @@ -1141,6 +1280,254 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(retainedTemplateAssociations).hasSize(1); assertThat(retainedTemplateAssociations.getFirst().templateId()).isEqualTo(templateId); + var automationAuthorizationRequest = + SelectedOwnerIntakeAuthorizationProducerEvidence.Request.create( + NAMESPACE, automationIntakeRequest, Owner.AUTOMATION_SCRIPTING, selectedCommit); + var automationAuthorizationResult = + gdToAccountSelectedOwnerAuthorizationProducer.authorize( + automationAuthorizationRequest, accountAccess.compact()); + var automationAuthorization = automationAuthorizationResult.binding(); + assertThat(automationAuthorizationResult.request()) + .isEqualTo(automationAuthorizationRequest); + assertThat(automationAuthorizationResult.canonicalBindingBytes()) + .containsExactly(automationAuthorization.canonicalBytes()); + assertThat(automationAuthorizationResult.digest()) + .isEqualTo(automationAuthorization.digest()); + assertThat(automationAuthorization.owner()).isEqualTo(Owner.AUTOMATION_SCRIPTING); + assertThat(automationAuthorization.intakeRequestId()) + .isEqualTo(automationSourceReservation.intakeRequestId()); + assertThat(automationAuthorization.operationId()) + .isEqualTo(automationSourceReservation.operationId()); + assertThat(automationAuthorization.fenceId()) + .isEqualTo(automationSourceReservation.fenceId()); + assertThat(automationAuthorization.content().scope().canonicalBytes()) + .containsExactly(automationSourceReservation.canonicalBytes()); + assertThat(automationAuthorization.content().snapshotBytes("COMMAND")) + .containsExactly(selectedSources.command().canonicalBytes()); + assertThat(automationAuthorization.content().snapshotBytes("REALM_POLICY")) + .containsExactly(selectedSources.policy().canonicalBytes()); + assertThat(automationAuthorization.content().snapshotBytes("ASSET")) + .containsExactly(selectedSources.asset().canonicalBytes()); + assertThat(automationAuthorization.content().snapshotBytes("GAMEPLAY_RULE")) + .containsExactly(selectedSources.gameplay().canonicalBytes()); + assertThat(automationAuthorization.content().snapshotBytes("BRANDING")) + .containsExactly(selectedSources.branding().orElseThrow().canonicalBytes()); + assertThat(automationAuthorization.content().snapshotBytes("TEMPLATE_CONFIG")) + .containsExactly(selectedSources.templateConfig().orElseThrow().canonicalBytes()); + assertThat(automationAuthorization.content().digest()) + .isEqualTo( + DraftAuthorizationFenceBinding.digest( + automationAuthorization.content().canonicalBytes())); + assertThat(automationAuthorization.selected().canonicalBytes()) + .containsExactly(selectedCommit.canonicalBytes()); + assertThat(accountSelectedSourceReads).hasValue(1); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, automationSourceReservation.operationId())) + .containsExactlyElementsOf(automationReservationSourcesBeforeAbort); + assertThatThrownBy( + () -> + wrongWorkloadSelectedOwnerAuthorizationProducer.authorize( + automationAuthorizationRequest, accountAccess.compact())) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + assertThat(accountSelectedSourceReads).hasValue(1); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, automationSourceReservation.operationId())) + .containsExactlyElementsOf(automationReservationSourcesBeforeAbort); + + var exactAutomationAuthorizationRetry = + gdToAccountSelectedOwnerAuthorizationProducer.authorize( + automationAuthorizationRequest, accountAccess.compact()); + assertThat(exactAutomationAuthorizationRetry.request()) + .isEqualTo(automationAuthorizationRequest); + assertThat(exactAutomationAuthorizationRetry.canonicalBindingBytes()) + .containsExactly(automationAuthorization.canonicalBytes()); + assertThat(exactAutomationAuthorizationRetry.digest()) + .isEqualTo(automationAuthorization.digest()); + assertThat(accountSelectedSourceReads).hasValue(1); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, automationSourceReservation.operationId())) + .containsExactlyElementsOf(automationReservationSourcesBeforeAbort); + + var automationRowsBeforeRetention = automationSourceRowCounts(automation.dsl()); + var automationReceipt = + withGameDesignPeer( + () -> + automationIntakeOwner.retain(NAMESPACE, automationAuthorization, actualFreeze)); + assertThat(automationReceipt.outcome()).isEqualTo("COMMITTED_EMPTY"); + assertThat(automationReceipt.intakeRequestId()).isEqualTo(automationIntakeRequest); + assertThat(automationReceipt.authorizationBindingBytes()) + .containsExactly(automationAuthorization.canonicalBytes()); + assertThat(automationReceipt.authorizationBindingDigest()) + .isEqualTo(automationAuthorization.digest()); + assertThat(automationReceipt.requestDigest()) + .isEqualTo( + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, automationAuthorization, actualFreeze)); + var retainedAutomationFreeze = + automationReceipt.worldInventoryReadEvidence().request().freezeEvidence(); + assertThat( + automationReceipt + .worldInventoryReadEvidence() + .request() + .authorizationBinding() + .canonicalBytes()) + .containsExactly(automationAuthorization.canonicalBytes()); + assertThat(automationReceipt.worldInventoryReadEvidence().request().closureReadPurpose()) + .isEqualTo("AUTOMATION_INTAKE_WORLD_CLOSURE_READ"); + assertThat( + automationReceipt + .worldInventoryReadEvidence() + .request() + .authorizationBinding() + .intendedReader()) + .isEqualTo("spiffe://firemud/ns/" + NAMESPACE + "/sa/automation-scripting-service"); + assertThat(retainedAutomationFreeze).isEqualTo(actualFreeze); + assertThat( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest( + retainedAutomationFreeze.request()) + .toByteArray()) + .containsExactly( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(actualFreeze.request()) + .toByteArray()); + assertThat( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse( + retainedAutomationFreeze.acknowledgement()) + .toByteArray()) + .containsExactly( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse( + actualFreeze.acknowledgement()) + .toByteArray()); + assertThat(automationReceipt.worldInventoryBytes()) + .containsExactly( + automationReceipt.worldInventoryReadEvidence().inventory().canonicalBytes()); + assertThat(automationReceipt.worldInventoryDigest()) + .isEqualTo(automationReceipt.worldInventoryReadEvidence().inventory().digest()); + assertThat(automationReceipt.scriptsRowCount()).isZero(); + assertThat(automationReceipt.eventBindingsRowCount()).isZero(); + assertThat(automationReceipt.patchBaseBindingsRowCount()).isZero(); + assertThat(automationReceipt.unqualifiedScriptsRowCount()).isZero(); + assertThat(automationReceipt.unqualifiedEventBindingsRowCount()).isZero(); + assertThat(automationReceipt.unqualifiedPatchBaseBindingsRowCount()).isZero(); + assertThat(automationReceipt.selectedScopeScriptsRowCount()).isZero(); + assertThat(automationReceipt.selectedScopeEventBindingsRowCount()).isZero(); + assertThat(automationReceipt.selectedScopePatchBaseBindingsRowCount()).isZero(); + assertThat(automationReceipt.receiptDigest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(automationReceipt.canonicalBytes())); + var persistedAutomationReceipt = + automationIntakeRepository.read(NAMESPACE, automationIntakeRequest).orElseThrow(); + assertThat(persistedAutomationReceipt.canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + assertThat(persistedAutomationReceipt.receiptDigest()) + .isEqualTo(automationReceipt.receiptDigest()); + var automationRowsAfterRetention = automationSourceRowCounts(automation.dsl()); + assertThat(automationRowsAfterRetention.get("scripts")) + .isEqualTo(automationRowsBeforeRetention.get("scripts")); + assertThat(automationRowsAfterRetention.get("script_event_bindings")) + .isEqualTo(automationRowsBeforeRetention.get("script_event_bindings")); + assertThat(automationRowsAfterRetention.get("script_patch_base_bindings")) + .isEqualTo(automationRowsBeforeRetention.get("script_patch_base_bindings")); + assertThat(automationRowsAfterRetention.get("automation_empty_selected_source_association")) + .isEqualTo( + automationRowsBeforeRetention.get("automation_empty_selected_source_association") + + 1); + assertThat(automationRowsAfterRetention.get("automation_empty_selected_source_receipt")) + .isEqualTo( + automationRowsBeforeRetention.get("automation_empty_selected_source_receipt") + 1); + assertThat( + automationRowsAfterRetention.get("automation_empty_source_numeric_key_reservation")) + .isEqualTo( + automationRowsBeforeRetention.get("automation_empty_source_numeric_key_reservation") + + 2); + + var automationReceiptRetry = + withGameDesignPeer( + () -> + automationIntakeOwner.retain(NAMESPACE, automationAuthorization, actualFreeze)); + assertThat(automationReceiptRetry.canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + assertThat(automationReceiptRetry.receiptDigest()) + .isEqualTo(automationReceipt.receiptDigest()); + assertThat(automationSourceRowCounts(automation.dsl())) + .isEqualTo(automationRowsAfterRetention); + + var selectedOwnerSettlementOwner = + new AccountSelectedOwnerIntakeSettlementService( + accountSelectedOwnerSourceRepository, + accountToAutomationTerminal, + accountAccess.sources().manager, + NAMESPACE); + assertThat( + accountSourceDsl.fetchCount(DSL.table("account_selected_owner_intake_settlements"))) + .isZero(); + var accountSettlement = + withGameDesignPeer(() -> selectedOwnerSettlementOwner.settle(automationAuthorization)); + assertThat(accountSettlement.authorizationBinding().canonicalBytes()) + .containsExactly(automationAuthorization.canonicalBytes()); + assertThat(accountSettlement.ownerReceiptBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + assertThat(accountSettlement.ownerReceiptDigest()) + .isEqualTo(automationReceipt.receiptDigest()); + assertThat(accountSettlement.digest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(accountSettlement.canonicalBytes())); + var settlementRows = + accountSourceDsl.fetch( + "SELECT binding_bytes, binding_digest, terminal_read_request_id, " + + "terminal_receipt_bytes, terminal_receipt_digest, receipt_bytes, " + + "receipt_digest FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + automationAuthorization.operationId()); + assertThat(settlementRows).hasSize(1); + var settlementRow = settlementRows.getFirst(); + assertThat(settlementRow.get("binding_bytes", byte[].class)) + .containsExactly(automationAuthorization.canonicalBytes()); + assertThat(settlementRow.get("binding_digest", String.class)) + .isEqualTo(automationAuthorization.digest()); + assertThat(settlementRow.get("terminal_receipt_bytes", byte[].class)) + .containsExactly(automationReceipt.canonicalBytes()); + assertThat(settlementRow.get("terminal_receipt_digest", String.class)) + .isEqualTo(automationReceipt.receiptDigest()); + assertThat(settlementRow.get("receipt_bytes", byte[].class)) + .containsExactly(accountSettlement.canonicalBytes()); + assertThat(settlementRow.get("receipt_digest", String.class)) + .isEqualTo(accountSettlement.digest()); + assertThat(settlementRow.get("terminal_read_request_id", UUID.class)) + .isEqualTo(accountSettlement.terminalEvidence().request().readRequestId()); + + var exactAccountSettlementRetry = + withGameDesignPeer(() -> selectedOwnerSettlementOwner.settle(automationAuthorization)); + assertThat(exactAccountSettlementRetry.canonicalBytes()) + .containsExactly(accountSettlement.canonicalBytes()); + assertThat( + accountSourceDsl.fetchCount(DSL.table("account_selected_owner_intake_settlements"))) + .isOne(); + assertFailedPrecondition( + () -> + automationToAccountHeld.read( + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( + NAMESPACE, automationAuthorization))); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, automationSourceReservation.operationId())) + .containsExactlyElementsOf(automationReservationSourcesBeforeAbort); + + var automationReceiptAfterSettlement = + withGameDesignPeer( + () -> + automationIntakeOwner.retain(NAMESPACE, automationAuthorization, actualFreeze)); + assertThat(automationReceiptAfterSettlement.canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + assertThat(automationReceiptAfterSettlement.receiptDigest()) + .isEqualTo(automationReceipt.receiptDigest()); + assertThat(automationSourceRowCounts(automation.dsl())) + .isEqualTo(automationRowsAfterRetention); + var publicationRequest = PublicationDigestRequestBinding.full( gd.target().canonicalTenantId().toString(), @@ -1837,14 +2224,15 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex .isEqualTo(first.candidateBinding()); } } finally { - stopAll(gameLogicServer, accountServer, worldServer, gdServer); + stopAll(automationServer, gameLogicServer, accountServer, worldServer, gdServer); } } /** - * Entity and Automation participant rows remain stipulated test inputs. World freeze, inventory, - * selector and Game Design and Game Logic source reads come from their actual owner compositions. - * This does not prove complete four-owner publication or activation. + * Entity and Automation participant digests remain stipulated test inputs. Automation's source + * receipt and Account settlement do not replace those publication participants. World freeze, + * inventory, selector and Game Design and Game Logic source reads come from their actual owner + * compositions. This does not prove complete four-owner publication or activation. */ private static List selectedSelectorParticipantDigests( DraftCommitBinding selectedCommit, @@ -2161,6 +2549,21 @@ private static T withGameSessionPeer(Supplier operation) { } } + private static T withGameDesignPeer(Supplier operation) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service", + NAMESPACE, + "game-design-service"); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return operation.get(); + } finally { + context.detach(previous); + } + } + private static void assertFailedPrecondition(Runnable operation) { assertThatThrownBy(operation::run) .isInstanceOf(io.grpc.StatusRuntimeException.class) @@ -2259,6 +2662,19 @@ private static Map selectedOwnerSourceRowCounts(DSLContext dsl) dsl.fetchCount(DSL.table("game_design_template_config_source_snapshot"))); } + private static Map automationSourceRowCounts(DSLContext dsl) { + return Map.of( + "scripts", dsl.fetchCount(DSL.table("scripts")), + "script_event_bindings", dsl.fetchCount(DSL.table("script_event_bindings")), + "script_patch_base_bindings", dsl.fetchCount(DSL.table("script_patch_base_bindings")), + "automation_empty_selected_source_association", + dsl.fetchCount(DSL.table("automation_empty_selected_source_association")), + "automation_empty_selected_source_receipt", + dsl.fetchCount(DSL.table("automation_empty_selected_source_receipt")), + "automation_empty_source_numeric_key_reservation", + dsl.fetchCount(DSL.table("automation_empty_source_numeric_key_reservation"))); + } + private static List selectedOwnerReservationSourceRows(DSLContext dsl, UUID operationId) { return dsl.fetch( "SELECT source_key, source_evidence " @@ -2806,7 +3222,7 @@ CommonGrpcClientProperties properties(Path ca) { private record StartSessionProjectionBinding( StartSessionPostAuthorizationExecutionTuple tuple, UUID ownerAttemptId, long ownerFence) {} - /** Ephemeral same-namespace mTLS identities for the four real owner boundaries. */ + /** Ephemeral same-namespace mTLS identities for the native owner-service proof fixture. */ private static final class TestPki { private final Path ca; private final Map servers = new ConcurrentHashMap<>(); @@ -2847,7 +3263,8 @@ private static final class TestPki { "account-service", "game-design-service", "world-management-service", - "game-logic-service")) { + "game-logic-service", + "automation-scripting-service")) { servers.put(service, issue(root, service, true, caKeys, caCertificate)); clients.put(service, issue(root, service, false, caKeys, caCertificate)); } diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index 47b07db156..40b725fd86 100644 --- a/services/world-management-service/build.gradle.kts +++ b/services/world-management-service/build.gradle.kts @@ -2,12 +2,18 @@ apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { + `java-test-fixtures` id("net.firedevops.firemud.secured-stateful-service-conventions") id("net.firedevops.firemud.openapi-conventions") id("net.firedevops.firemud.temporal-conventions") id("net.firedevops.firemud.jooq-conventions") } +// Test fixtures compose package-private World owners without widening production visibility. +configurations.named("testFixturesImplementation") { + extendsFrom(configurations.implementation.get()) +} + firemudJooq { packageName.set("net.firedevops.firemud.worldmanagement.jooq") } @@ -33,3 +39,19 @@ val worldClassesProof by configurations.creating { extendsFrom(configurations.implementation.get()) outgoing.artifact(worldClassesProofJar) } + +// Opt-in owner proof: expose World classes and the selected-owner fixture without application or +// migration resources. +val worldSelectedOwnerInventoryProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("owner-inventory-proof") + dependsOn(tasks.named("classes"), tasks.named("testFixturesClasses")) + from(sourceSets.main.get().output.classesDirs) + from(sourceSets["testFixtures"].output.classesDirs) +} + +val worldSelectedOwnerInventoryProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(worldSelectedOwnerInventoryProofJar) +} diff --git a/services/world-management-service/src/testFixtures/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadProofFixture.java b/services/world-management-service/src/testFixtures/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadProofFixture.java new file mode 100644 index 0000000000..45cf332204 --- /dev/null +++ b/services/world-management-service/src/testFixtures/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadProofFixture.java @@ -0,0 +1,32 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.BindableService; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeWorldClosureAuthorizationReadClient; +import org.jooq.DSLContext; + +/** Test-only composition of the actual recipient-specific World inventory reader and receiver. */ +public final class WorldSelectedOwnerInventoryReadProofFixture { + private WorldSelectedOwnerInventoryReadProofFixture() {} + + public static BindableService receiver( + String workloadNamespace, + DSLContext worldDsl, + WorldDesignPublicationFenceRepository worldFence, + SelectedOwnerIntakeWorldClosureAuthorizationReadClient accountReadClient) { + Objects.requireNonNull(worldDsl, "worldDsl"); + Objects.requireNonNull(worldFence, "worldFence"); + Objects.requireNonNull(accountReadClient, "accountReadClient"); + + var authorizationRepository = + new WorldSelectedDraftPublicationAuthorizationRepository(worldDsl); + var inventoryRepository = new WorldSelectedPublicationArtifactInventoryRepository(worldDsl); + var inventoryReadService = + new WorldSelectedPublicationArtifactInventoryReadService( + workloadNamespace, worldFence, authorizationRepository, inventoryRepository); + var readService = + new WorldSelectedOwnerInventoryReadService( + workloadNamespace, inventoryReadService, accountReadClient); + return new WorldSelectedOwnerInventoryReadGrpcService(workloadNamespace, readService); + } +} From 2f4d57c020d560bb8971606b16549456734a3448 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 04:32:58 +1300 Subject: [PATCH 092/129] Compose native selected-owner commands and preserve canonical receipt timestamps --- .../account-service/api-contracts.md | 2 + .../runtime-and-data.md | 2 + .../game-design-service/api-contracts.md | 2 + ...ame-authoring-publishing-and-activation.md | 8 +- ...cted_owner_intake_settlement_service.proto | 30 ++ ...ation_selected_source_intake_command.proto | 30 ++ ...ectedOwnerIntakeSettlementGrpcService.java | 90 ++++++ ...ected_owner_intake_terminal_settlement.sql | 7 +- ...eAuthorizationPostgresIntegrationTest.java | 268 ++++++++++++++++- ...dOwnerIntakeSettlementGrpcServiceTest.java | 235 +++++++++++++++ ...electedSourceIntakeCommandGrpcService.java | 97 ++++++ ...tedSourceIntakeCommandGrpcServiceTest.java | 146 +++++++++ ...SelectedOwnerIntakeSettlementEvidence.java | 117 ++++++++ ...electedOwnerIntakeSettlementGrpcCodec.java | 137 +++++++++ ...onSelectedSourceIntakeCommandEvidence.java | 171 +++++++++++ ...nSelectedSourceIntakeCommandGrpcCodec.java | 177 +++++++++++ ...tedOwnerIntakeSettlementGrpcCodecTest.java | 197 +++++++++++++ ...ectedSourceIntakeCommandGrpcCodecTest.java | 279 ++++++++++++++++++ ...tionSelectedSourceIntakeCommandClient.java | 181 ++++++++++++ ...pcSelectedOwnerIntakeSettlementClient.java | 171 +++++++++++ ...SelectedSourceIntakeCommandClientTest.java | 124 ++++++++ ...lectedOwnerIntakeSettlementClientTest.java | 123 ++++++++ ...licationExportPostgresIntegrationTest.java | 275 +++++++++++++---- 23 files changed, 2808 insertions(+), 61 deletions(-) create mode 100644 protos/account/v1/selected_owner_intake_settlement_service.proto create mode 100644 protos/automation-scripting/v1/automation_selected_source_intake_command.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java create mode 100644 services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeSettlementClient.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeSettlementClientTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index aaf0d5ef6c..a62053e76e 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -120,6 +120,8 @@ For Automation, Account may settle finalized source participation only after an The immutable Account settlement uses `account-selected-owner-intake-settlement/v1` and the existing byte-length framing and SHA-256 representation. Its fixed frame order is domain, version `1`, complete original authorization bytes and digest, terminal request schema version, namespace, read request UUID, exact Account reader, terminal-read purpose, complete echoed authorization bytes and digest, and complete Automation receipt bytes and digest. Every embedded value must decode canonically and match the same original operation. The complete settlement is bounded to 92,356,608 bytes: two original authorization bounds, one Automation receipt bound, and 64 KiB of framing allowance; it does not widen those embedded bounds. The first terminal-read correlation is retained with the result but is not a new settlement identity: a retry with another valid correlation and identical original binding and owner receipt returns the first settlement byte-for-byte. Changed original binding or owner receipt conflicts without overwriting it. The settlement neither releases another pending operation nor permits preliminary abort of a finalized order; uncertainty remains reconciliation-only. +The separate [`AccountSelectedOwnerIntakeSettlementService.SettleSelectedOwnerIntake`](../../../../protos/account/v1/selected_owner_intake_settlement_service.proto) is a closed schema-version-1 Game Design command for that same settlement. Account authenticates the exact Game Design peer against its configured namespace and rejects end-user or ambient SQL/synchronization context before decoding. The request binds that namespace, an independent nonzero transport correlation distinct from the original operation/fence/intake request, and the complete original Automation authorization bytes and digest. It carries no fresh creator credential or replacement source authority; Entity settlement is unsupported and denies. Success echoes the request unchanged and returns the entire original Account settlement bytes and digest. A new transport correlation does not allocate a second settlement or alter the first terminal-read correlation. The request wire bound is the unchanged 16 MiB authorization bound plus 64 KiB; the response bound is the unchanged 92,356,608-byte settlement bound plus the complete request bound and another 64 KiB. Embedded bounds, canonical parsing and unknown-field rejection remain independent. The file-backed mTLS client pins Account, uses a five-second deadline and rejects end-user and ambient SQL context before transport. This unregistered command does not bypass authenticated Automation terminal readback, source locks or committed postcondition checks, or authorize runtime activation. + The separate [`AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.ReadHeldSelectedOwnerWorldClosureAuthorization`](../../../../protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto) permits World to independently verify that exact finalized Entity or Automation order before returning the selected World closure. Its outer recipient is the exact same-namespace World workload, and its closed purpose is respectively `ENTITY_INTAKE_WORLD_CLOSURE_READ` or `AUTOMATION_INTAKE_WORLD_CLOSURE_READ`. The inner original authorization retains its Entity or Automation recipient, retention purpose, operation, fence, intake request, complete content and source evidence unchanged. The request binds schema version 1, namespace, an independent nonzero read correlation, and the full original bytes and digest; success echoes it unchanged with `held=true`. Account authenticates World and rejects end-user context before decoding, then locks and verifies the exact original finalized order and source participation in an independent writable `READ COMMITTED` transaction. The existing Entity/Automation recipient read is not widened. World must obtain and validate this confirmation directly over authenticated Account mTLS outside SQL; caller-forwarded bytes or a digest do not establish Account authorization. The five-second deadline, 24 MiB wire budget and unchanged 16 MiB binding bound apply. This is permission for an exact retained closure read, not an owner census, source-mutation grant, receipt, settlement or continuous-through-commit proof; an unavailable or mismatched confirmation denies the read. The distinct [`AccountSelectedOwnerIntakeSourceReadService.ReadSourceScope`](../../../../protos/account/v1/selected_owner_intake_source_read_service.proto) confirms only the retained preliminary Entity or Automation reservation. Account authenticates the exact configured same-namespace Game Design workload and rejects authenticated end-user context before decoding or storage. The closed schema-version-1 request binds namespace, independent nonzero transport correlation, derived Account reader and closed purpose, and the original scope bytes and digest. Account revalidates its own original creator and source participation in independent transactions around the external registry read; neither a client digest nor peer identity creates a reservation. A successful response echoes the complete request unchanged and confirms only that preliminary scope. Missing, expired, changed, malformed or unavailable evidence denies. The canonical scope remains bounded to 4 MiB; the separately enforced request and response wire budget is 8 MiB, including echo and framing. The file-backed mTLS client pins the Account server, applies a five-second deadline and rejects ambient SQL or synchronization. This standalone method has no finalized-retention branch, supplies no census or owner receipt, and does not register or activate a runtime path. Game Design must finish this authenticated Account confirmation outside SQL before reading or returning any selected source content. diff --git a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md index cebe658244..73ba3114d9 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -64,6 +64,8 @@ An Automation selected-source intake is a distinct Account-authorized operation, The immutable intake result retains the canonical tenant/version and selected commit, original source revision and operation, complete inventory bytes, exact Account authorization binding, original owner terminal and their digests. The result and authenticated readback are derived after the authored source commit, outside its preimage. An identical retry reads the original result; changed scope, selection, content or authorization binding conflicts rather than manufacturing a new receipt. A workload identity, creator declaration or matching digest alone is insufficient. Until the required selected-input producers and continuously held-authority proof exist, the Automation receipt cannot qualify publication, which must not substitute an empty or synthetic version marker. +The separate [`AutomationSelectedSourceIntakeCommandService.RetainSelectedSource`](../../../../protos/automation-scripting/v1/automation_selected_source_intake_command.proto) supplies a closed schema-version-1 retention command without changing those owner checks. The receiver authenticates the exact Game Design workload against its configured namespace before decoding, rejects end-user context, then separately denies a mismatched request namespace or ambient SQL/synchronization. Its request binds an independent nonzero transport correlation, complete original Account Automation-retention authorization bytes/digest, and the original World freeze request and acknowledgement through their existing codecs. The complete selected Draft, canonical tenant/version and namespace must agree across those bindings; original operation, fence, intake and applicable freeze identities cannot be reused as transport correlation. Success echoes the entire request and returns only the complete canonical `COMMITTED_EMPTY` receipt and digest. Changing only the transport correlation replays the same owner receipt, not another intake. The request wire bound is the 16 MiB authorization bound plus both existing 1 MiB World Account-binding bounds and 64 KiB; the response bound adds the unchanged Automation receipt bound and another 64 KiB. These wire budgets do not expand any embedded grammar or byte limit. The workload-only file-backed mTLS client pins Automation, applies a five-second deadline and rejects ambient SQL/synchronization before transport. This standalone command remains unregistered and grants no publication, source release, admission or runtime activation. + Automation's terminal read is a separate schema-version-1 `AUTOMATION_INTAKE_TERMINAL_READ` request, authenticated only for the exact same-namespace Account mTLS peer. It carries a fresh read correlation distinct from the original operation, fence and intake request, plus the complete original authorization binding bytes and digest. The only positive terminal is the typed `COMMITTED_EMPTY` outcome, with the complete canonical immutable Automation receipt bytes and recomputed digest; an exact retry returns that same receipt even when the read correlation changes. Missing, pending, changed, corrupt or ambiguous evidence denies and is never interpreted as absence, abort or release authority. Account's settlement consequence is defined by its [selected-owner intake contract](../account-service/api-contracts.md#grpc-apis) and must preserve the same original operation under its existing source locks. ## Architecture and Design Notes diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index ae3c8313d7..e861278930 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -81,6 +81,8 @@ The distinct [`GameDesignSelectedOwnerIntakeSourceService.ReadSelectedSource`](. Game Design requests distinct intake finalization through the [Account-owned selected-owner authorization producer](../account-service/api-contracts.md#grpc-apis), retaining the stable intake request and exact selected Draft binding. It forwards the original creator credential only through that method's protected per-call metadata, not selected source content or a publication digest. Account remains the sole finalization and currentness owner; neither Game Design's workload identity nor its local source export creates retention authority. The returned full binding must remain unchanged through the subsequent owner intake and terminal readback; this consumer consequence does not register or enable the transport. +After finalization, Game Design invokes the [Automation-owned retention command](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) with the unchanged full Account binding and original World freeze, then the [Account-owned exact settlement command](../account-service/api-contracts.md#grpc-apis) for that same authorization. It checks each complete request echo and canonical receipt rather than treating its own workload identity or a successful forwarding call as owner proof. These distinct commands do not register a public creator path or complete Entity intake, publication or runtime activation. + The shared content decoder rejects changed scope, family order, family bytes/digests, selected binding, framing, canonical JSON or trailing bytes. All six snapshots must retain their exact selected Draft binding. Game Design remains the semantic owner for command, realm-policy, asset and branding snapshots; their consumer representation preserves original bytes rather than copying their grammars into another authority. Existing shared Gameplay Rule and Template Configuration parsers retain their applicable complete typed checks. Valid stored template v1/v2 content is not proof of a complete fresh Entity/Automation inventory. This transport and decoder neither finalize Account retention permission nor prove owner census, emptiness, receipt or settlement; production registration and acceptance remain denied until those producer/consumer boundaries and their focused proof are complete. The realm-policy source carries the [Entity-owned bounded player-created input descriptor](../entity-management-service/runtime-and-data.md#bounded-player-created-input-descriptor) in the distinct policy schema 2 without reinterpreting retained schema-1 bytes. Game Design persists its authored descriptor identity/revision with the exact policy bytes and preserves the independent original policy commit and revision in its existing `REALM_POLICY` snapshot and application. Exact replay/readback must return those stored identities and bytes; a substituted descriptor, revision, selector or selected scope is not equivalent evidence. Neither an empty descriptor dependency list nor this source handoff discharges Entity census, World closure or actor-allocation proof. 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 bb2da55c60..a40c64e0c1 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 @@ -6,11 +6,17 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The current construction replaces the remaining in-process Automation-retention and Account-settlement commands with distinct, unregistered native mTLS transports. The owning [Automation command](../../architecture/microservices/automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) and [Account settlement command](../../architecture/microservices/account-service/api-contracts.md#grpc-apis) retain full original evidence, independent transport correlations, exact request echoes and immutable receipt readback. Receiver authentication derives from each server's configured namespace, not a namespace supplied by the caller. The genuine PostgreSQL fixture defines a fresh native Account reserve → authenticated source read → finalize → Automation retain → Account settle flow, plus wrong-workload no-mutation, exact retry, unchanged rows and post-settlement HELD denial. Its earlier, manually reserved Entity/Automation disclosure fixtures are explicitly aborted before the fresh positive operation; those setup contexts do not establish the positive producer boundary. Entity retention and publication participation, S3 and StartSession projection remain incomplete. + +Local validation of this native-command and timestamp-correction batch passes the five affected module checks, integration compilation, affected boot JARs, isolated proof JARs, static analysis, formatting, documentation and Flyway sanity (12 sets / 293 versioned files). The corrected final gate freshly executes 1,349 Account unit cases; unchanged tasks reuse the preceding passing 629 Common Platform, 152 Common Security, 1,202 Automation and 558 Game Design cases. Across those checks, 15 non-container integration cases pass and 533 cases skip (Account 290, Automation 94, Game Design 149). The four Account selected-owner PostgreSQL cases and expanded genuine Game Design composition compile but skip without Docker. These results are not physically executed current-composition PostgreSQL proof, production registration, or completion of any full Gameplay handoff. + +Exact source `8911d8537d54163388e50ca2c50c01918cb5d1f3` [Validation run 38059995674](https://github.com/benhook1013/FireMUD/actions/runs/38059995674) ended cancelled with a failed required gate. Account physically executed 309 integration cases with nine failures and no skips; Game Design executed 152 with one failure and no skips; World executed all 221 without failures or skips. Game Design's genuine composition reached V135 settlement and exposed a receipt timestamp parser defect: Java's canonical UTC timestamp may end a three-, six- or nine-digit fractional group in zero, while SQL wrongly required its last digit to be nonzero. This batch corrects that grammar without rewriting receipt bytes or identity and adds exact-byte preservation and malformed-frame rollback definitions; corrected physical execution remains required. Account's ninth case, `lostReceiptCommitAcknowledgementDeniesThenRecoversOnlyThroughIndependentV120Read`, records `23514` / `account_admission_confirmation_wal_coverage` and expected one physical receipt commit versus zero before the injected acknowledgement loss. It therefore does not reach receipt-acknowledgement recovery proof. The other eight admission/prototype failures remain included, unresolved CI obligations; distinguishing the fresh acknowledged-COMMIT path does not clear this gate. Automation's job passed but originating integration XML was unavailable, so no new count is attributed. The tested merge `3020322ef326b4e6aea81d87c104acf5cecfcce0`, tree `02090b8c787148af973c75986ca94ae6a9196d18`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, not the separately recorded integration parent. Game Design cancellation causation remains unestablished. + Exact source `74294ebbf2976cc5334416b32762774d2c22ef23` [Validation run 38056381237](https://github.com/benhook1013/FireMUD/actions/runs/38056381237) completed with a failed required gate. Originating Account results show 1,339 passing unit cases and 309 physically executed integration cases, with eight failures and no skips. Four lease-persistence cases and four protected-entry prototype cases fail the conservative WAL-coverage boundary; observed insert or upper bounds are 64 bytes ahead of the flush frontier. The saved failure evidence supplies no SQLSTATE or constraint identity and does not establish the WAL record's cause. No marker, forced flush, longer expiry, warm-up or weakened guard is accepted as a correction. Automation's 1,200 unit and 97 integration cases and Game Design's 558 unit and 152 integration cases all pass without skips. The tested merge `e949a1cb38aa4f769dd2a58dfc21409384cfeb90`, tree `61fa6de5bc0fafb0ac2df747ce3b6795c8b8ab12`, has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, not the separately recorded integration parent. That run provides specific corrected proof rather than aggregate completion: Account's three selected-owner authorization integration cases pass, including exact Automation empty settlement and release of only that operation; its preliminary reservation migration case also passes. Automation's native Account-mTLS terminal-read case executes against a real retained `COMMITTED_EMPTY` receipt and denies the wrong namespace without row changes, while its upstream Account/Game Design/World inputs remain synthetic. Game Design's descriptor persistence, retry and independent authored-provenance case passes in its 24-case version-asset publication suite. The separate genuine Game Logic intake/settlement definition passes with migrations through V135; it does not substitute for the distinct Entity/Automation composition. Complete original handoffs, Entity's 23-family census, authenticated command composition, Account admission durability and runtime activation remain open. -The next prepared composition adds the standalone [Account selected-owner authorization producer](../../architecture/microservices/account-service/api-contracts.md#grpc-apis), native Game Design-to-Account command and Account-to-Game Design source disclosure, actual recipient-qualified World inventory, Automation empty-source retention and Account settlement. These changes are not part of the source tested above. The new client resides in Common Security for direct end-user-context rejection, while its closed evidence, codec and method-bound creator credentials reside in Common Platform. The composed PostgreSQL definition retains explicit limitations: preliminary reservation context, local Automation retention and local Account settlement command contexts remain stipulated; Entity retention, publication participant digests, S3 and StartSession projection are not complete owner proof. All components remain unregistered. +The standalone [Account selected-owner authorization producer](../../architecture/microservices/account-service/api-contracts.md#grpc-apis), native Game Design-to-Account command and Account-to-Game Design source disclosure, actual recipient-qualified World inventory, Automation empty-source retention and Account settlement are now composed in the definition described above. The clients reside in Common Security for direct end-user-context rejection, while closed evidence, codecs and method-bound creator credentials reside in Common Platform. The fresh positive operation no longer substitutes manually seeded reservation contexts or local command calls for native producer/consumer composition. Entity retention, publication participant digests, S3 and StartSession projection remain incomplete owner proof. All components remain unregistered. The corrected six-module local gate passes in 2m44s after repairing a duplicate fixture-local variable, without changing owner behavior. Common Platform, Common Security, Account, Automation, Game Design and World unit results contain 620, 148, 1,345, 1,200, 558 and 648 cases respectively, all with zero failures, errors or skips. Their unit tasks execute across the first and corrected gates; the corrected gate reuses unchanged Common Platform, Common Security, Account and Automation results rather than rerunning them. Sixteen non-container integration cases execute; 752 definitions skip without Docker (Account 289, Automation 94, Game Design 149, World 220), including the expanded genuine composition. All four integration sources compile, affected boot JARs and classes-only World/Automation proof artifacts build, and formatting, static checks, coverage, links, Markdown and Flyway sanity pass. The two opt-in proof artifacts contain no application or migration resources. Nine new codec/credential, two pre-transport client and six mocked receiver cases strengthen the bounded command contract but do not prove its physical PostgreSQL/mTLS composition, production registration or activation. Corrected originating CI remains required for that new batch. diff --git a/protos/account/v1/selected_owner_intake_settlement_service.proto b/protos/account/v1/selected_owner_intake_settlement_service.proto new file mode 100644 index 0000000000..cbf6192f16 --- /dev/null +++ b/protos/account/v1/selected_owner_intake_settlement_service.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered command for settling one finalized Automation intake operation. +service AccountSelectedOwnerIntakeSettlementService { + rpc SettleSelectedOwnerIntake(SelectedOwnerIntakeSettlementRequest) + returns (SelectedOwnerIntakeSettlementResponse); +} + +message SelectedOwnerIntakeSettlementRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Independent transport correlation; the retained authorization remains the settlement key. + string transport_request_id = 3; + // Complete canonical Account authorization bytes and their SHA-256 digest. + bytes original_intake_authorization_binding = 4; + string intake_authorization_digest = 5; +} + +message SelectedOwnerIntakeSettlementResponse { + // Exact unchanged request echo. + SelectedOwnerIntakeSettlementRequest request = 1; + // Complete immutable Account settlement receipt bytes and their SHA-256 digest. + bytes settlement_receipt = 2; + string settlement_receipt_digest = 3; +} diff --git a/protos/automation-scripting/v1/automation_selected_source_intake_command.proto b/protos/automation-scripting/v1/automation_selected_source_intake_command.proto new file mode 100644 index 0000000000..2454b5a8b7 --- /dev/null +++ b/protos/automation-scripting/v1/automation_selected_source_intake_command.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package automation_scripting.v1; +option java_package = "net.firedevops.firemud.automationscripting.v1"; +option java_multiple_files = true; + +import "world-management/v1/world_selected_draft_publication_freeze_service.proto"; + +// Standalone and unregistered. Authenticated same-namespace Game Design may retain its exact +// Account-authorized selected-source intake after the exact World freeze has committed. +service AutomationSelectedSourceIntakeCommandService { + rpc RetainSelectedSource(RetainSelectedSourceRequest) + returns (RetainSelectedSourceResponse); +} + +message RetainSelectedSourceRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string transport_request_id = 3; + bytes original_intake_authorization_binding = 4; + string intake_authorization_digest = 5; + world_management.v1.BeginVersionPublicationFreezeRequest freeze_request = 6; + world_management.v1.BeginVersionPublicationFreezeResponse freeze_acknowledgement = 7; +} + +message RetainSelectedSourceResponse { + RetainSelectedSourceRequest request = 1; + bytes committed_empty_receipt = 2; + string receipt_digest = 3; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcService.java new file mode 100644 index 0000000000..0fedc11b04 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcService.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered Game Design-only transport; Account alone owns the durable settlement. */ +public final class AccountSelectedOwnerIntakeSettlementGrpcService + extends AccountSelectedOwnerIntakeSettlementServiceGrpc + .AccountSelectedOwnerIntakeSettlementServiceImplBase { + private final AccountSelectedOwnerIntakeSettlementService owner; + private final String namespace; + + public AccountSelectedOwnerIntakeSettlementGrpcService( + AccountSelectedOwnerIntakeSettlementService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "Account settlement owner service required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account namespace required"); + } + this.namespace = namespace; + } + + @Override + public void settleSelectedOwnerIntake( + SelectedOwnerIntakeSettlementRequest wire, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/game-design-service"; + if (SessionContext.hasAuthenticatedCallerContext() || !expectedPeer.equals(peer.uri())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + + final SelectedOwnerIntakeSettlementEvidence.Request request; + try { + request = SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + + final SelectedOwnerIntakeSettlementResponse response; + try { + var receipt = owner.settle(request.authorizationBinding()); + response = + SelectedOwnerIntakeSettlementGrpcCodec.toResponse( + new SelectedOwnerIntakeSettlementEvidence.Result(request, receipt)); + } catch (StatusRuntimeException failure) { + deny(observer, Status.fromCode(failure.getStatus().getCode())); + return; + } catch (IllegalArgumentException inconsistent) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError( + status + .withDescription("Account selected-owner settlement denied or unavailable") + .asRuntimeException()); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V135__selected_owner_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V135__selected_owner_intake_terminal_settlement.sql index 057e8a0c7e..b437b921b8 100644 --- a/services/account-service/src/main/resources/db/migration/V135__selected_owner_intake_terminal_settlement.sql +++ b/services/account-service/src/main/resources/db/migration/V135__selected_owner_intake_terminal_settlement.sql @@ -457,7 +457,12 @@ BEGIN END LOOP; SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p FROM account_publication_authorization_read_frame(owner_receipt, p); - IF ignored_text !~ '^[+-]?[0-9]{4,}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(:[0-9]{2}([.][0-9]{0,8}[1-9])?)?Z$' + IF ignored_text !~ '^(?:[0-9]{4}|-[0-9]{4}|-[1-9][0-9]{4,8}|[+][1-9][0-9]{4,8})-[0-9]{2}-[0-9]{2}T(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9](?:[.](?:[0-9]{3}|[0-9]{6}|[0-9]{9}))?)?Z$' + OR ignored_text ~ '^-0000-' + OR ignored_text ~ 'T(?:[01][0-9]|2[0-3]):[0-5][0-9]:00Z$' + OR ignored_text ~ '[.]000Z$' + OR ignored_text ~ '[.][0-9]{3}000Z$' + OR ignored_text ~ '[.][0-9]{6}000Z$' OR p <> octet_length(owner_receipt) + 1 THEN RAISE EXCEPTION 'Automation terminal receipt timestamp or trailing bytes are invalid' USING ERRCODE = '23514'; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java index 1142b3ffe7..8a918ce9bf 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -12,6 +12,7 @@ import java.util.Comparator; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -21,6 +22,7 @@ import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.service.session.AccountSelectedOwnerIntakeSourceReservationRepository.State; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; @@ -549,6 +551,106 @@ void commitsExactAutomationEmptySettlementAndReleasesOnlyThatOperation() throws } } + @Test + void postgresPreservesCanonicalAutomationTimestampBytesAndRejectsNoncanonicalFrames() + throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservationService = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + + var rejectedBinding = + finalizeAutomationBinding( + issued, reservationService, repository, selected, "timestamp-invalid"); + var validBase = + terminalEvidence( + rejectedBinding, 9301L, 9302L, OffsetDateTime.parse("2026-10-10T00:00Z")); + var validOwnerBytes = validBase.receipt().canonicalBytes(); + assertThat(lastFrame(validOwnerBytes)).isEqualTo("2026-10-10T00:00Z"); + + for (String noncanonicalTimestamp : + List.of( + "2026-10-10T24:00Z", + "2026-10-10T00:00:60Z", + "2026-10-10T00:00:00Z", + "2026-10-10T00:00:00.000Z", + "2026-10-10T00:00:00.123450000Z", + "2026-10-10T00:00:00.12Z", + "2026-10-10T00:00:00.120000Z", + "2026-10-10T00:00:00+01:00")) { + assertRejectedSettlementByPostgres( + issued, + rejectedBinding, + validBase, + replaceLastFrame(validOwnerBytes, noncanonicalTimestamp, false), + "Automation terminal receipt timestamp or trailing bytes are invalid"); + } + assertRejectedSettlementByPostgres( + issued, + rejectedBinding, + validBase, + replaceLastFrame(validOwnerBytes, null, true), + "Automation terminal receipt timestamp or trailing bytes are invalid"); + + var canonicalTimestamps = + List.of( + "2026-10-10T00:00Z", + "2026-10-10T00:00:01Z", + "2026-10-10T00:00:00.120Z", + "2026-10-10T00:00:00.123450Z", + "2026-10-10T00:00:00.123456780Z"); + for (int index = 0; index < canonicalTimestamps.size(); index++) { + String timestamp = canonicalTimestamps.get(index); + var binding = + index == 0 + ? rejectedBinding + : finalizeAutomationBinding( + issued, + reservationService, + repository, + selected, + "timestamp-canonical-" + index); + var terminal = + index == 0 + ? validBase + : terminalEvidence( + binding, 9401L + index, 9402L + index, OffsetDateTime.parse(timestamp)); + assertThat(lastFrame(terminal.receipt().canonicalBytes())).isEqualTo(timestamp); + + var committed = f.tx(() -> repository.settleCommittedEmpty(terminal)); + assertThat(committed.terminalEvidence().receipt().canonicalBytes()) + .isEqualTo(terminal.receipt().canonicalBytes()); + assertThat( + f.dsl + .fetchSingle( + "SELECT terminal_receipt_bytes FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + binding.operationId()) + .get(0, byte[].class)) + .isEqualTo(terminal.receipt().canonicalBytes()); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + binding.operationId()) + .get(0, Boolean.class)) + .isFalse(); + } + } + } + @Test void postgresRejectsChangedNamespaceUnknownFamilyAndSelectedScopeEvidence() throws Exception { try (var fixture = @@ -913,8 +1015,172 @@ private static TemplateConfigSourceSnapshot templateSnapshot( selected, "0", null, genesis, List.of(), List.of(declaration)); } + private static SelectedOwnerIntakeAuthorizationBinding finalizeAutomationBinding( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + AccountSelectedOwnerIntakeSourceReservationService reservationService, + AccountSelectedOwnerIntakeSourceReservationRepository repository, + DraftCommitBinding selected, + String marker) { + var f = issued.sources(); + var scope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); + var selectedContent = content(scope, marker); + return asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + selectedContent, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); + } + + private static void assertRejectedSettlementByPostgres( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + SelectedOwnerIntakeAuthorizationBinding binding, + AutomationSelectedSourceIntakeTerminalReadEvidence validEvidence, + byte[] changedOwnerReceiptBytes, + String expectedDiagnostic) { + var f = issued.sources(); + assertThatThrownBy( + () -> + f.tx( + () -> { + insertRawSettlement(f.dsl, binding, validEvidence, changedOwnerReceiptBytes); + return null; + })) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(root) + .isInstanceOfSatisfying( + java.sql.SQLException.class, + sql -> { + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains(expectedDiagnostic); + }); + }); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + binding.operationId())) + .isNull(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + binding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + } + + private static void insertRawSettlement( + org.jooq.DSLContext dsl, + SelectedOwnerIntakeAuthorizationBinding binding, + AutomationSelectedSourceIntakeTerminalReadEvidence evidence, + byte[] ownerReceiptBytes) { + String ownerReceiptDigest = DraftAuthorizationFenceBinding.digest(ownerReceiptBytes); + byte[] receiptBytes = + settlementReceiptBytes(binding, evidence, ownerReceiptBytes, ownerReceiptDigest); + dsl.execute( + "INSERT INTO account_selected_owner_intake_settlements " + + "(operation_id, fence_id, intake_request_id, owner, target_namespace, tenant_uuid, " + + "version_uuid, binding_bytes, binding_digest, terminal_read_request_id, " + + "terminal_receipt_bytes, terminal_receipt_digest, receipt_bytes, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.owner().name(), + binding.targetNamespace(), + binding.tenantId(), + binding.versionId(), + binding.canonicalBytes(), + binding.digest(), + evidence.request().readRequestId(), + ownerReceiptBytes, + ownerReceiptDigest, + receiptBytes, + DraftAuthorizationFenceBinding.digest(receiptBytes)); + } + + private static byte[] settlementReceiptBytes( + SelectedOwnerIntakeAuthorizationBinding binding, + AutomationSelectedSourceIntakeTerminalReadEvidence evidence, + byte[] ownerReceiptBytes, + String ownerReceiptDigest) { + var request = evidence.request(); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, AccountSelectedOwnerIntakeSettlementReceipt.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, "1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, binding.digest()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(request.schemaVersion())); + DraftAuthorizationFenceBinding.frame(out, request.targetNamespace()); + DraftAuthorizationFenceBinding.frame(out, request.readRequestId().toString()); + DraftAuthorizationFenceBinding.frame(out, request.intendedReader()); + DraftAuthorizationFenceBinding.frame(out, request.terminalReadPurpose()); + DraftAuthorizationFenceBinding.frame(out, request.binding().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, request.binding().digest()); + DraftAuthorizationFenceBinding.frame(out, ownerReceiptBytes); + DraftAuthorizationFenceBinding.frame(out, ownerReceiptDigest); + return out.toByteArray(); + } + + private static byte[] replaceLastFrame( + byte[] canonicalBytes, String replacement, boolean appendTrailingByte) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(canonicalBytes); + var frames = new ArrayList(); + while (reader.remaining() > 0) frames.add(reader.bytes()); + reader.requireEnd(); + if (replacement != null) { + frames.set(frames.size() - 1, replacement.getBytes(StandardCharsets.UTF_8)); + } + var out = new ByteArrayOutputStream(); + for (byte[] frame : frames) DraftAuthorizationFenceBinding.frame(out, frame); + if (appendTrailingByte) out.write(0x5a); + return out.toByteArray(); + } + + private static String lastFrame(byte[] canonicalBytes) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(canonicalBytes); + byte[] last = null; + while (reader.remaining() > 0) last = reader.bytes(); + reader.requireEnd(); + byte[] timestampFrame = + Objects.requireNonNull(last, "Complete Automation receipt must contain a timestamp frame"); + return new String(timestampFrame, StandardCharsets.UTF_8); + } + private static AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence( SelectedOwnerIntakeAuthorizationBinding binding, long localTenantKey, long localVersionKey) { + return terminalEvidence( + binding, localTenantKey, localVersionKey, OffsetDateTime.parse("2026-10-10T00:00:00Z")); + } + + private static AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence( + SelectedOwnerIntakeAuthorizationBinding binding, + long localTenantKey, + long localVersionKey, + OffsetDateTime retainedAt) { var freeze = freezeEvidence(binding); var worldRequest = SelectedOwnerWorldInventoryReadEvidence.create(binding.targetNamespace(), binding, freeze); @@ -942,7 +1208,7 @@ private static AutomationSelectedSourceIntakeTerminalReadEvidence terminalEviden 0, 0, 0, - OffsetDateTime.parse("2026-10-10T00:00:00Z")); + retainedAt); return new AutomationSelectedSourceIntakeTerminalReadEvidence( AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create( binding.targetNamespace(), binding), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java new file mode 100644 index 0000000000..8325c8a06d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java @@ -0,0 +1,235 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +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.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementResponse; +import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeSettlementReceipt; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementGrpcCodec; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Handler boundary tests only; mocks do not prove authenticated mTLS or physical settlement. */ +class AccountSelectedOwnerIntakeSettlementGrpcServiceTest { + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesSameNamespaceGameDesignAndRejectsEndUserBeforeDecode() { + var owner = mock(AccountSelectedOwnerIntakeSettlementService.class); + var service = new AccountSelectedOwnerIntakeSettlementGrpcService(owner, "test"); + var malformed = SelectedOwnerIntakeSettlementRequest.getDefaultInstance(); + + assertThat(invoke(service, malformed).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String workload : + List.of( + "account-service", + "automation-scripting-service", + "entity-management-service", + "game-logic-service", + "world-management-service")) { + assertThat(peer("test", workload, () -> invoke(service, malformed)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(peer("other", "game-design-service", () -> invoke(service, malformed)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("44", List.of(), java.util.Map.of()); + try { + assertThat(peer("test", "game-design-service", () -> invoke(service, malformed)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + assertThat(peer("test", "game-design-service", () -> invoke(service, malformed)).code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void rejectsAmbientSqlUnknownFieldsAndChangedNamespaceBeforeOwnerAccess() { + var owner = mock(AccountSelectedOwnerIntakeSettlementService.class); + var service = new AccountSelectedOwnerIntakeSettlementGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + var valid = + SelectedOwnerIntakeSettlementGrpcCodec.toRequest( + SelectedOwnerIntakeSettlementEvidence.Request.create("test", binding)); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(peer("test", "game-design-service", () -> invoke(service, valid)).code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThat(peer("test", "game-design-service", () -> invoke(service, valid)).code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clearSynchronization(); + + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThat(peer("test", "game-design-service", () -> invoke(service, unknown)).code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + peer( + "test", + "game-design-service", + () -> invoke(service, valid.toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner); + } + + @Test + void returnsFullStoredReceiptAndExactEchoForNewCorrelationRetry() { + var owner = mock(AccountSelectedOwnerIntakeSettlementService.class); + var service = new AccountSelectedOwnerIntakeSettlementGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + var firstRequest = SelectedOwnerIntakeSettlementEvidence.Request.create("test", binding); + var retryRequest = SelectedOwnerIntakeSettlementEvidence.Request.create("test", binding); + var receiptBytes = new byte[8192]; + for (int index = 0; index < receiptBytes.length; index++) { + receiptBytes[index] = (byte) (index * 17); + } + var receipt = receipt(binding, receiptBytes); + when(owner.settle(any())).thenReturn(receipt); + + var firstWire = SelectedOwnerIntakeSettlementGrpcCodec.toRequest(firstRequest); + var first = peer("test", "game-design-service", () -> invoke(service, firstWire)); + assertThat(first.error()).isNull(); + assertThat(first.response().getRequest()).isEqualTo(firstWire); + assertThat(first.response().getSettlementReceipt().toByteArray()).containsExactly(receiptBytes); + assertThat(first.response().getSettlementReceiptDigest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(receiptBytes)); + + var retryWire = SelectedOwnerIntakeSettlementGrpcCodec.toRequest(retryRequest); + var retry = peer("test", "game-design-service", () -> invoke(service, retryWire)); + assertThat(retry.error()).isNull(); + assertThat(retry.response().getRequest()).isEqualTo(retryWire); + assertThat(retry.response().getRequest()).isNotEqualTo(first.response().getRequest()); + assertThat(retry.response().getSettlementReceipt()) + .isEqualTo(first.response().getSettlementReceipt()); + var bindings = ArgumentCaptor.forClass(SelectedOwnerIntakeAuthorizationBinding.class); + verify(owner, times(2)).settle(bindings.capture()); + assertThat(bindings.getAllValues()) + .allSatisfy( + retained -> + assertThat(retained.canonicalBytes()).containsExactly(binding.canonicalBytes())); + } + + @Test + void sanitizesOwnerFailureAndRejectsReceiptSubstitution() { + var owner = mock(AccountSelectedOwnerIntakeSettlementService.class); + var service = new AccountSelectedOwnerIntakeSettlementGrpcService(owner, "test"); + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.AUTOMATION_SCRIPTING); + var wire = + SelectedOwnerIntakeSettlementGrpcCodec.toRequest( + SelectedOwnerIntakeSettlementEvidence.Request.create("test", binding)); + + doThrow( + Status.FAILED_PRECONDITION + .withDescription("private-owner-settlement-evidence") + .asRuntimeException()) + .when(owner) + .settle(any()); + var failure = peer("test", "game-design-service", () -> invoke(service, wire)); + assertThat(failure.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(failure.error().toString()).doesNotContain("private-owner-settlement-evidence"); + + var substituted = + receipt( + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT), + new byte[] {1, 2, 3}); + doReturn(substituted).when(owner).settle(any()); + var mismatch = peer("test", "game-design-service", () -> invoke(service, wire)); + assertThat(mismatch.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(mismatch.error().toString()).doesNotContain("authorization"); + } + + private static AccountSelectedOwnerIntakeSettlementReceipt receipt( + SelectedOwnerIntakeAuthorizationBinding binding, byte[] bytes) { + var receipt = mock(AccountSelectedOwnerIntakeSettlementReceipt.class); + when(receipt.authorizationBinding()).thenReturn(binding); + when(receipt.targetNamespace()).thenReturn(binding.targetNamespace()); + when(receipt.canonicalBytes()).thenReturn(bytes.clone()); + when(receipt.digest()).thenReturn(DraftAuthorizationFenceBinding.digest(bytes)); + return receipt; + } + + private record Result(SelectedOwnerIntakeSettlementResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private static Result invoke( + AccountSelectedOwnerIntakeSettlementGrpcService service, + SelectedOwnerIntakeSettlementRequest request) { + var response = new AtomicReference(); + var error = new AtomicReference(); + service.settleSelectedOwnerIntake( + request, + new StreamObserver<>() { + @Override + public void onNext(SelectedOwnerIntakeSettlementResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable value) { + error.set(value); + } + + @Override + public void onCompleted() {} + }); + return new Result(response.get(), error.get()); + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java new file mode 100644 index 0000000000..f9c96c8f79 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeCommandServiceGrpc; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceRequest; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceResponse; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered Game Design command boundary for retaining exact selected Automation inputs. */ +public final class AutomationSelectedSourceIntakeCommandGrpcService + extends AutomationSelectedSourceIntakeCommandServiceGrpc + .AutomationSelectedSourceIntakeCommandServiceImplBase { + private final AutomationEmptySelectedSourceIntakeService owner; + private final String namespace; + + public AutomationSelectedSourceIntakeCommandGrpcService( + AutomationEmptySelectedSourceIntakeService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-source intake owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("configured namespace is invalid"); + } + this.namespace = namespace; + } + + @Override + public void retainSelectedSource( + RetainSelectedSourceRequest request, StreamObserver observer) { + try { + requireAuthenticatedGameDesignCaller(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + + final AutomationSelectedSourceIntakeCommandEvidence.Request decoded; + try { + decoded = AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var receipt = + owner.retain( + decoded.targetNamespace(), + decoded.originalAuthorizationBinding(), + decoded.freezeEvidence()); + var evidence = new AutomationSelectedSourceIntakeCommandEvidence(decoded, receipt); + observer.onNext(AutomationSelectedSourceIntakeCommandGrpcCodec.toResponse(evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException denied) { + observer.onError(Status.fromCode(denied.getStatus().getCode()).asRuntimeException()); + } catch (SecurityException denied) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + } catch (AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException conflict) { + observer.onError(Status.ALREADY_EXISTS.asRuntimeException()); + } catch (IllegalArgumentException | IllegalStateException unavailable) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } + + /** Authenticate the exact same-namespace workload and reject user context before decoding. */ + private void requireAuthenticatedGameDesignCaller() { + if (SessionContext.hasAuthenticatedCallerContext() + || AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get() != null) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + if (!namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } +} diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcServiceTest.java new file mode 100644 index 0000000000..ca3c5a3be4 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcServiceTest.java @@ -0,0 +1,146 @@ +package unit.net.firedevops.firemud.automationscripting.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedSourceIntakeCommandGrpcService; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceRequest; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Receiver gate tests use mocked owner storage and do not claim physical mTLS or PostgreSQL proof. + */ +class AutomationSelectedSourceIntakeCommandGrpcServiceTest { + private static final String NAMESPACE = "example"; + private static final String GAME_DESIGN_URI = + "spiffe://firemud/ns/example/sa/game-design-service"; + + @AfterEach + void clearContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsMissingOrWrongPeerBeforeRequestDecodeOrOwnerInvocation() { + var owner = mock(AutomationEmptySelectedSourceIntakeService.class); + var service = new AutomationSelectedSourceIntakeCommandGrpcService(owner, NAMESPACE); + var response = new CapturingObserver(); + + service.retainSelectedSource(RetainSelectedSourceRequest.getDefaultInstance(), response); + + assertThat(Status.fromThrowable(response.failure()).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(owner); + + var wrongPeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/account-service", NAMESPACE, "account-service"); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer); + var previous = context.attach(); + try { + var denied = new CapturingObserver(); + service.retainSelectedSource(RetainSelectedSourceRequest.getDefaultInstance(), denied); + assertThat(Status.fromThrowable(denied.failure()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } finally { + context.detach(previous); + } + + var wrongNamespacePeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-design-service", "other", "game-design-service"); + var wrongNamespaceContext = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongNamespacePeer); + previous = wrongNamespaceContext.attach(); + try { + var denied = new CapturingObserver(); + service.retainSelectedSource( + RetainSelectedSourceRequest.newBuilder().setTargetNamespace(NAMESPACE).build(), denied); + assertThat(Status.fromThrowable(denied.failure()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } finally { + wrongNamespaceContext.detach(previous); + } + } + + @Test + void rejectsEndUserAndAmbientSqlBeforeMalformedEvidenceCanBeDecoded() { + var owner = mock(AutomationEmptySelectedSourceIntakeService.class); + var service = new AutomationSelectedSourceIntakeCommandGrpcService(owner, NAMESPACE); + var peer = new GrpcPeerIdentity(GAME_DESIGN_URI, NAMESPACE, "game-design-service"); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var malformedRequest = + RetainSelectedSourceRequest.newBuilder().setTargetNamespace(NAMESPACE).build(); + var previous = context.attach(); + try { + SessionContext.setContext("101", List.of(), Map.of()); + var userDenied = new CapturingObserver(); + service.retainSelectedSource(malformedRequest, userDenied); + assertThat(Status.fromThrowable(userDenied.failure()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + var sqlDenied = new CapturingObserver(); + service.retainSelectedSource(malformedRequest, sqlDenied); + assertThat(Status.fromThrowable(sqlDenied.failure()).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clear(); + + var malformed = new CapturingObserver(); + service.retainSelectedSource(malformedRequest, malformed); + assertThat(Status.fromThrowable(malformed.failure()).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + var mismatchedTarget = new CapturingObserver(); + service.retainSelectedSource( + RetainSelectedSourceRequest.newBuilder().setTargetNamespace("other").build(), + mismatchedTarget); + assertThat(Status.fromThrowable(mismatchedTarget.failure()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } finally { + context.detach(previous); + } + } + + private static final class CapturingObserver + implements StreamObserver { + private final AtomicReference failure = new AtomicReference<>(); + + @Override + public void onNext(RetainSelectedSourceResponse value) { + throw new AssertionError("Malformed or unauthorized request unexpectedly returned evidence"); + } + + @Override + public void onError(Throwable error) { + failure.set(error); + } + + @Override + public void onCompleted() { + throw new AssertionError("Malformed or unauthorized request unexpectedly completed"); + } + + Throwable failure() { + return failure.get(); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java new file mode 100644 index 0000000000..e82d5afbad --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed transport correlation and the complete immutable Account settlement response. */ +public final class SelectedOwnerIntakeSettlementEvidence { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_REQUEST_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 64 * 1024; + public static final int MAX_RESPONSE_BYTES = + AccountSelectedOwnerIntakeSettlementReceipt.MAX_BYTES + MAX_REQUEST_BYTES + 64 * 1024; + + private SelectedOwnerIntakeSettlementEvidence() {} + + /** The correlation is independent from the retained operation, fence and intake identities. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + SelectedOwnerIntakeAuthorizationBinding authorizationBinding) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || authorizationBinding == null + || authorizationBinding.owner() != Owner.AUTOMATION_SCRIPTING + || !targetNamespace.equals(authorizationBinding.targetNamespace()) + || !"account-automation-intake-authorization/v1".equals(authorizationBinding.schema()) + || !"AUTOMATION_INTAKE_RETENTION".equals(authorizationBinding.purpose())) { + throw invalid("Canonical same-namespace Automation authorization required"); + } + DraftAuthorizationFenceBinding.requireUuid(transportRequestId); + if (transportRequestId.equals(authorizationBinding.operationId()) + || transportRequestId.equals(authorizationBinding.fenceId()) + || transportRequestId.equals(authorizationBinding.intakeRequestId())) { + throw invalid("Independent settlement transport correlation required"); + } + byte[] bytes = authorizationBinding.canonicalBytes(); + if (bytes.length == 0 + || bytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + || !DraftAuthorizationFenceBinding.digest(bytes).equals(authorizationBinding.digest())) { + throw invalid("Canonical original authorization is required"); + } + var decoded = SelectedOwnerIntakeAuthorizationBinding.fromStored(bytes); + if (!Arrays.equals(bytes, decoded.canonicalBytes()) + || !authorizationBinding.digest().equals(decoded.digest())) { + throw invalid("Canonical original authorization is required"); + } + } + + public static Request create( + String namespace, SelectedOwnerIntakeAuthorizationBinding authorizationBinding) { + Objects.requireNonNull(authorizationBinding, "Original authorization is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (correlation.equals(authorizationBinding.operationId()) + || correlation.equals(authorizationBinding.fenceId()) + || correlation.equals(authorizationBinding.intakeRequestId())); + return new Request(SCHEMA_VERSION, namespace, correlation, authorizationBinding); + } + + public byte[] authorizationBindingBytes() { + return authorizationBinding.canonicalBytes(); + } + + public String authorizationBindingDigest() { + return authorizationBinding.digest(); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && transportRequestId.equals(other.transportRequestId) + && Arrays.equals(authorizationBindingBytes(), other.authorizationBindingBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, + targetNamespace, + transportRequestId, + Arrays.hashCode(authorizationBindingBytes())); + } + } + + /** Full settlement receipt paired with the exact request that Account echoed. */ + public record Result(Request request, AccountSelectedOwnerIntakeSettlementReceipt receipt) { + public Result { + Objects.requireNonNull(request, "Settlement request is required"); + Objects.requireNonNull(receipt, "Complete Account settlement receipt is required"); + byte[] receiptBytes = receipt.canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length > AccountSelectedOwnerIntakeSettlementReceipt.MAX_BYTES + || !DraftAuthorizationFenceBinding.digest(receiptBytes).equals(receipt.digest()) + || !request.targetNamespace().equals(receipt.targetNamespace()) + || !Arrays.equals( + request.authorizationBindingBytes(), receipt.authorizationBinding().canonicalBytes()) + || !request + .authorizationBindingDigest() + .equals(receipt.authorizationBinding().digest())) { + throw invalid("Settlement receipt differs from the exact original authorization"); + } + } + } + + private static IllegalArgumentException invalid(String description) { + return new IllegalArgumentException(description); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java new file mode 100644 index 0000000000..c6c9a6a60e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java @@ -0,0 +1,137 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementRequest; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence.Request; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence.Result; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; + +/** Strict closed-schema mapping for the standalone selected-owner settlement command. */ +public final class SelectedOwnerIntakeSettlementGrpcCodec { + public static final int MAX_REQUEST_BYTES = + SelectedOwnerIntakeSettlementEvidence.MAX_REQUEST_BYTES; + public static final int MAX_RESPONSE_BYTES = + SelectedOwnerIntakeSettlementEvidence.MAX_RESPONSE_BYTES; + + private SelectedOwnerIntakeSettlementGrpcCodec() {} + + public static SelectedOwnerIntakeSettlementRequest toRequest(Request request) { + if (request == null) throw invalid("Settlement request is required"); + byte[] authorization = request.authorizationBindingBytes(); + if (authorization.length == 0 + || authorization.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original authorization exceeds its 16 MiB bound"); + } + var wire = + SelectedOwnerIntakeSettlementRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setTransportRequestId(request.transportRequestId().toString()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(authorization)) + .setIntakeAuthorizationDigest(request.authorizationBindingDigest()) + .build(); + requireWithinBudget(wire.getSerializedSize(), MAX_REQUEST_BYTES, "request"); + return wire; + } + + public static Request fromRequest(SelectedOwnerIntakeSettlementRequest wire) { + requireKnownAndWithinBudget(wire, MAX_REQUEST_BYTES, "request"); + if (wire.getOriginalIntakeAuthorizationBinding().size() + > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original authorization exceeds its 16 MiB bound"); + } + DraftAuthorizationFenceBinding.canonicalUuid(wire.getTransportRequestId()); + byte[] authorizationBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (authorizationBytes.length == 0) throw invalid("Original authorization is required"); + SelectedOwnerIntakeAuthorizationBinding authorization; + try { + authorization = SelectedOwnerIntakeAuthorizationBinding.fromStored(authorizationBytes); + } catch (RuntimeException malformed) { + throw invalid("Original authorization is malformed or noncanonical"); + } + if (!authorization.digest().equals(wire.getIntakeAuthorizationDigest())) { + throw invalid("Original authorization digest differs"); + } + Request request = + new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getTransportRequestId()), + authorization); + if (!Arrays.equals(authorizationBytes, request.authorizationBindingBytes()) + || !toRequest(request).equals(wire)) { + throw invalid("Settlement request is noncanonical"); + } + return request; + } + + public static SelectedOwnerIntakeSettlementResponse toResponse(Result result) { + if (result == null) throw invalid("Complete settlement result is required"); + byte[] receipt = result.receipt().canonicalBytes(); + if (receipt.length == 0 + || receipt.length > AccountSelectedOwnerIntakeSettlementReceipt.MAX_BYTES) { + throw invalid("Complete settlement receipt exceeds its 92,356,608 byte bound"); + } + var response = + SelectedOwnerIntakeSettlementResponse.newBuilder() + .setRequest(toRequest(result.request())) + .setSettlementReceipt(ByteString.copyFrom(receipt)) + .setSettlementReceiptDigest(result.receipt().digest()) + .build(); + requireWithinBudget(response.getSerializedSize(), MAX_RESPONSE_BYTES, "response"); + return response; + } + + public static Result fromResponse( + Request request, SelectedOwnerIntakeSettlementResponse response) { + if (request == null) throw invalid("Original settlement request is required"); + requireKnownAndWithinBudget(response, MAX_RESPONSE_BYTES, "response"); + if (!response.hasRequest()) throw invalid("Exact settlement request echo is required"); + requireKnownAndWithinBudget(response.getRequest(), MAX_REQUEST_BYTES, "echoed request"); + if (!toRequest(request).equals(response.getRequest())) { + throw invalid("Account changed the complete settlement request"); + } + if (response.getSettlementReceipt().size() + > AccountSelectedOwnerIntakeSettlementReceipt.MAX_BYTES) { + throw invalid("Complete settlement receipt exceeds its 92,356,608 byte bound"); + } + byte[] receiptBytes = response.getSettlementReceipt().toByteArray(); + AccountSelectedOwnerIntakeSettlementReceipt receipt; + try { + receipt = AccountSelectedOwnerIntakeSettlementReceipt.fromStored(receiptBytes); + } catch (RuntimeException malformed) { + throw invalid("Complete settlement receipt is malformed or noncanonical"); + } + if (!Arrays.equals(receiptBytes, receipt.canonicalBytes()) + || !receipt.digest().equals(response.getSettlementReceiptDigest()) + || !Arrays.equals( + request.authorizationBindingBytes(), receipt.authorizationBinding().canonicalBytes()) + || !request.authorizationBindingDigest().equals(receipt.authorizationBinding().digest())) { + throw invalid("Settlement receipt digest or original authorization differs"); + } + return new Result(request, receipt); + } + + private static void requireKnownAndWithinBudget(Message wire, int maxBytes, String label) { + if (wire == null || wire.getSerializedSize() > maxBytes) { + throw invalid("Missing or oversized selected-owner settlement " + label); + } + if (!wire.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown selected-owner settlement " + label + " fields"); + } + } + + private static void requireWithinBudget(int size, int maxBytes, String label) { + if (size > maxBytes) { + throw invalid("Selected-owner settlement " + label + " exceeds its wire budget"); + } + } + + private static IllegalArgumentException invalid(String description) { + return new IllegalArgumentException(description); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandEvidence.java new file mode 100644 index 0000000000..9e36d9d88e --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandEvidence.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.common.automation.sourceintake; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; + +/** Exact Game Design command correlation and the immutable Automation receipt. */ +public record AutomationSelectedSourceIntakeCommandEvidence( + Request request, AutomationEmptySelectedSourceIntakeReceipt receipt) { + public AutomationSelectedSourceIntakeCommandEvidence { + Objects.requireNonNull(request, "selected-source command request is required"); + Objects.requireNonNull(receipt, "committed Automation receipt is required"); + try { + receipt.requireSameRequest( + request.targetNamespace(), + request.originalAuthorizationBinding(), + request.freezeEvidence()); + } catch (RuntimeException mismatch) { + throw new IllegalArgumentException( + "Automation receipt differs from the complete selected-source command", mismatch); + } + if (!Arrays.equals( + request.originalIntakeAuthorizationBinding(), receipt.authorizationBindingBytes()) + || !request.intakeAuthorizationDigest().equals(receipt.authorizationBindingDigest())) { + throw new IllegalArgumentException( + "Automation receipt differs from the original Account authorization bytes"); + } + } + + /** Caller-generated transport correlation; all retained inputs remain the original values. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + public static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public Request { + Objects.requireNonNull( + originalAuthorizationBinding, "original Account authorization is required"); + Objects.requireNonNull(freezeEvidence, "complete World freeze evidence is required"); + if (schemaVersion != SCHEMA_VERSION + || !net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !targetNamespace.equals(originalAuthorizationBinding.targetNamespace()) + || originalAuthorizationBinding.canonicalBytes().length == 0 + || originalAuthorizationBinding.canonicalBytes().length + > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + || originalAuthorizationBinding.owner() != Owner.AUTOMATION_SCRIPTING + || !"account-automation-intake-authorization/v1" + .equals(originalAuthorizationBinding.schema()) + || !"AUTOMATION_INTAKE_RETENTION".equals(originalAuthorizationBinding.purpose()) + || !targetNamespace.equals(freezeEvidence.request().targetNamespace()) + || !originalAuthorizationBinding + .tenantId() + .equals(freezeEvidence.request().canonicalTenantId()) + || !originalAuthorizationBinding + .versionId() + .equals(freezeEvidence.request().canonicalVersionId()) + || !originalAuthorizationBinding + .selected() + .equals( + freezeEvidence.request().accountBinding().input().selection().selectedCommit()) + || !originalAuthorizationBinding + .selected() + .commitId() + .toString() + .equals(freezeEvidence.acknowledgement().appliedCommitId())) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(transportRequestId); + if (NIL_UUID.equals(transportRequestId) + || collidesWithRetainedIdentity( + transportRequestId, originalAuthorizationBinding, freezeEvidence)) { + throw invalid(); + } + } + + public static Request create( + String namespace, + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + Objects.requireNonNull( + originalAuthorizationBinding, "original Account authorization is required"); + Objects.requireNonNull(freezeEvidence, "complete World freeze evidence is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (collidesWithRetainedIdentity( + correlation, originalAuthorizationBinding, freezeEvidence)); + return new Request( + SCHEMA_VERSION, namespace, correlation, originalAuthorizationBinding, freezeEvidence); + } + + public byte[] originalIntakeAuthorizationBinding() { + return originalAuthorizationBinding.canonicalBytes(); + } + + public String intakeAuthorizationDigest() { + return originalAuthorizationBinding.digest(); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && transportRequestId.equals(other.transportRequestId) + && Arrays.equals( + originalIntakeAuthorizationBinding(), other.originalIntakeAuthorizationBinding()) + && intakeAuthorizationDigest().equals(other.intakeAuthorizationDigest()) + && freezeEvidence.equals(other.freezeEvidence); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, + targetNamespace, + transportRequestId, + Arrays.hashCode(originalIntakeAuthorizationBinding()), + intakeAuthorizationDigest(), + freezeEvidence); + } + + private static boolean collidesWithRetainedIdentity( + UUID candidate, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freeze) { + if (candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()) + || candidate.equals(binding.selected().requestId()) + || candidate.equals(binding.selected().commitId())) { + return true; + } + var account = freeze.request().accountBinding(); + var selection = account.input().selection(); + List freezeIds = + new ArrayList<>( + List.of( + account.operationId(), + account.fenceId(), + selection.fenceRequestId(), + selection.fenceCommitId(), + selection.selectedCommit().requestId(), + selection.selectedCommit().commitId(), + freeze.acknowledgement().intakeRequestId(), + freeze.acknowledgement().publicationFence())); + if (freezeIds.contains(candidate)) return true; + try { + UUID publicationRequestId = UUID.fromString(freeze.request().publicationRequestId()); + return publicationRequestId.toString().equals(freeze.request().publicationRequestId()) + && publicationRequestId.equals(candidate); + } catch (IllegalArgumentException notUuid) { + return false; + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Automation selected-source command request"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandGrpcCodec.java new file mode 100644 index 0000000000..223ce89e55 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandGrpcCodec.java @@ -0,0 +1,177 @@ +package net.firedevops.firemud.common.automation.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceRequest; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence.Request; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; + +/** Closed mapping for selected-source retention with exact Account and World evidence echoes. */ +public final class AutomationSelectedSourceIntakeCommandGrpcCodec { + private static final int MAX_REQUEST_FRAMING_BYTES = 64 * 1024; + + /** Authorization plus complete freeze request and acknowledgement Account bindings. */ + public static final int MAX_REQUEST_WIRE_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + 2 * WorldSelectedDraftPublicationFreezeEvidence.Request.MAX_ACCOUNT_BINDING_BYTES + + MAX_REQUEST_FRAMING_BYTES; + + /** Complete receipt, complete echoed request, and bounded outer response framing. */ + public static final int MAX_RESPONSE_WIRE_BYTES = + AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES + + MAX_REQUEST_WIRE_BYTES + + MAX_REQUEST_FRAMING_BYTES; + + private AutomationSelectedSourceIntakeCommandGrpcCodec() {} + + public static RetainSelectedSourceRequest toRequest(Request request) { + Objects.requireNonNull(request, "selected-source command request is required"); + byte[] authorizationBytes = request.originalIntakeAuthorizationBinding(); + if (authorizationBytes.length == 0 + || authorizationBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Account authorization exceeds its 16 MiB limit"); + } + var freeze = request.freezeEvidence(); + var wire = + RetainSelectedSourceRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setTransportRequestId(request.transportRequestId().toString()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(authorizationBytes)) + .setIntakeAuthorizationDigest(request.intakeAuthorizationDigest()) + .setFreezeRequest( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())) + .setFreezeAcknowledgement( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())) + .build(); + requireWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request"); + return wire; + } + + /** Decode after the receiver authenticates the exact same-namespace Game Design peer. */ + public static Request fromRequest(RetainSelectedSourceRequest wire) { + requireKnownAndWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request"); + if (!wire.hasFreezeRequest() || !wire.hasFreezeAcknowledgement()) { + throw invalid("Complete original World freeze request and acknowledgement are required"); + } + UUID transportRequestId = canonicalUuid(wire.getTransportRequestId()); + int authorizationSize = wire.getOriginalIntakeAuthorizationBinding().size(); + if (authorizationSize == 0 + || authorizationSize > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Account authorization size is invalid"); + } + byte[] authorizationBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + SelectedOwnerIntakeAuthorizationBinding authorization; + try { + authorization = SelectedOwnerIntakeAuthorizationBinding.fromStored(authorizationBytes); + } catch (RuntimeException malformed) { + throw invalid("Original Account authorization is invalid", malformed); + } + if (!authorization.digest().equals(wire.getIntakeAuthorizationDigest())) { + throw invalid("Original Account authorization digest differs"); + } + var freezeRequest = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(wire.getFreezeRequest()); + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, wire.getFreezeAcknowledgement()); + Request request = + new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + transportRequestId, + authorization, + freezeEvidence); + if (!toRequest(request).equals(wire)) { + throw invalid("Selected-source command request is not an exact canonical echo"); + } + return request; + } + + public static RetainSelectedSourceResponse toResponse( + AutomationSelectedSourceIntakeCommandEvidence evidence) { + Objects.requireNonNull(evidence, "selected-source command evidence is required"); + byte[] receiptBytes = evidence.receipt().canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Committed Automation receipt size is invalid"); + } + var response = + RetainSelectedSourceResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setCommittedEmptyReceipt(ByteString.copyFrom(receiptBytes)) + .setReceiptDigest(evidence.receipt().receiptDigest()) + .build(); + requireWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response"); + return response; + } + + /** Requires the exact complete request echo and verifies the canonical retained receipt. */ + public static AutomationSelectedSourceIntakeCommandEvidence fromResponse( + Request expected, RetainSelectedSourceResponse response) { + Objects.requireNonNull(expected, "selected-source command request is required"); + requireKnownAndWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response"); + if (!response.hasRequest()) { + throw invalid("Exact selected-source command request echo is required"); + } + RetainSelectedSourceRequest expectedWire = toRequest(expected); + if (!response.getRequest().equals(expectedWire)) { + throw invalid("Automation changed the exact selected-source command request"); + } + int receiptSize = response.getCommittedEmptyReceipt().size(); + if (receiptSize == 0 || receiptSize > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Missing or oversized committed Automation receipt"); + } + byte[] receiptBytes = response.getCommittedEmptyReceipt().toByteArray(); + AutomationEmptySelectedSourceIntakeReceipt receipt; + try { + receipt = AutomationEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes); + } catch (RuntimeException malformed) { + throw invalid("Committed Automation receipt is invalid", malformed); + } + if (!receipt.receiptDigest().equals(response.getReceiptDigest())) { + throw invalid("Automation receipt digest differs"); + } + return new AutomationSelectedSourceIntakeCommandEvidence(expected, receipt); + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw invalid("Canonical nonzero transport request UUID required"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid("Canonical nonzero transport request UUID required", malformed); + } + } + + private static void requireKnownAndWithinBudget(Message message, int budget, String label) { + if (message == null || message.getSerializedSize() > budget) { + throw invalid("Automation selected-source command " + label + " exceeds its wire budget"); + } + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown Automation selected-source command " + label + " fields"); + } + } + + private static void requireWithinBudget(Message message, int budget, String label) { + if (message.getSerializedSize() > budget) { + throw invalid("Automation selected-source command " + label + " exceeds its wire budget"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java new file mode 100644 index 0000000000..4ba7df44df --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java @@ -0,0 +1,197 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementRequest; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence.Request; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import org.junit.jupiter.api.Test; + +/** Closed-schema codec tests; these values do not establish Account or Automation authority. */ +class SelectedOwnerIntakeSettlementGrpcCodecTest { + @Test + void roundTripsCanonicalRequestWithIndependentTransportCorrelation() { + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = Request.create("test", binding); + assertThat(SelectedOwnerIntakeSettlementEvidence.MAX_REQUEST_BYTES) + .isEqualTo(SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 64 * 1024); + assertThat(SelectedOwnerIntakeSettlementEvidence.MAX_RESPONSE_BYTES) + .isEqualTo( + AccountSelectedOwnerIntakeSettlementReceipt.MAX_BYTES + + SelectedOwnerIntakeSettlementEvidence.MAX_REQUEST_BYTES + + 64 * 1024); + var wire = SelectedOwnerIntakeSettlementGrpcCodec.toRequest(request); + + assertThat(wire.getSchemaVersion()).isEqualTo(1); + assertThat(wire.getTargetNamespace()).isEqualTo("test"); + assertThat(wire.getTransportRequestId()).isEqualTo(request.transportRequestId().toString()); + assertThat(wire.getTransportRequestId()) + .isNotIn( + binding.operationId().toString(), + binding.fenceId().toString(), + binding.intakeRequestId().toString()); + assertThat(wire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .containsExactly(binding.canonicalBytes()); + assertThat(wire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + assertThat(SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(wire)).isEqualTo(request); + } + + @Test + void rejectsDefaultUnknownWrongOwnerAndChangedDigestRequests() { + assertThatThrownBy( + () -> + SelectedOwnerIntakeSettlementGrpcCodec.fromRequest( + SelectedOwnerIntakeSettlementRequest.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var valid = SelectedOwnerIntakeSettlementGrpcCodec.toRequest(Request.create("test", binding)); + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + + var changedDigest = + valid.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build(); + assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(changedDigest)) + .isInstanceOf(IllegalArgumentException.class); + + var entity = SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var wrongOwner = + valid.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(entity.canonicalBytes())) + .setIntakeAuthorizationDigest(entity.digest()) + .build(); + assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(wrongOwner)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsOversizedAuthorizationBeforeCanonicalDecoding() { + var oversized = + SelectedOwnerIntakeSettlementRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace("test") + .setTransportRequestId(UUID.randomUUID().toString()) + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + .setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)) + .build(); + + assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(oversized)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("16 MiB"); + } + + @Test + void echoesRequestAndCarriesEverySettlementReceiptByteAndDigest() { + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = Request.create("test", binding); + byte[] completeReceipt = new byte[4096]; + for (int index = 0; index < completeReceipt.length; index++) { + completeReceipt[index] = (byte) (index * 31); + } + var receipt = mock(AccountSelectedOwnerIntakeSettlementReceipt.class); + when(receipt.authorizationBinding()).thenReturn(binding); + when(receipt.targetNamespace()).thenReturn("test"); + when(receipt.canonicalBytes()).thenReturn(completeReceipt.clone()); + when(receipt.digest()).thenReturn(DraftAuthorizationFenceBinding.digest(completeReceipt)); + + var response = + SelectedOwnerIntakeSettlementGrpcCodec.toResponse( + new SelectedOwnerIntakeSettlementEvidence.Result(request, receipt)); + + assertThat(response.getRequest()) + .isEqualTo(SelectedOwnerIntakeSettlementGrpcCodec.toRequest(request)); + assertThat(response.getSettlementReceipt().toByteArray()).containsExactly(completeReceipt); + assertThat(response.getSettlementReceiptDigest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(completeReceipt)); + } + + @Test + void rejectsChangedEchoUnknownResponseAndMalformedFullReceipt() { + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + var request = Request.create("test", binding); + var base = + net.firedevops.firemud.account.v1.SelectedOwnerIntakeSettlementResponse.newBuilder() + .setRequest(SelectedOwnerIntakeSettlementGrpcCodec.toRequest(request)) + .setSettlementReceipt(ByteString.copyFrom(new byte[] {1, 2, 3, 4})) + .setSettlementReceiptDigest("sha256:" + "0".repeat(64)) + .build(); + + var changedEcho = + base.toBuilder() + .setRequest( + base.getRequest().toBuilder().setTransportRequestId(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy( + () -> SelectedOwnerIntakeSettlementGrpcCodec.fromResponse(request, changedEcho)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed"); + + var unknown = + base.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromResponse(request, unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + + assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromResponse(request, base)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("malformed"); + } + + @Test + void rejectsCorrelationReuseAndReceiptDigestOrAuthorizationSubstitution() { + var binding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.AUTOMATION_SCRIPTING); + assertThatThrownBy(() -> new Request(1, "test", binding.operationId(), binding)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("correlation"); + + var request = Request.create("test", binding); + byte[] receiptBytes = {10, 20, 30, 40}; + var badDigest = mock(AccountSelectedOwnerIntakeSettlementReceipt.class); + when(badDigest.authorizationBinding()).thenReturn(binding); + when(badDigest.targetNamespace()).thenReturn("test"); + when(badDigest.canonicalBytes()).thenReturn(receiptBytes); + when(badDigest.digest()).thenReturn("sha256:" + "0".repeat(64)); + assertThatThrownBy(() -> new SelectedOwnerIntakeSettlementEvidence.Result(request, badDigest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("receipt"); + + var substitutedBinding = + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding(Owner.ENTITY_MANAGEMENT); + var substitution = mock(AccountSelectedOwnerIntakeSettlementReceipt.class); + when(substitution.authorizationBinding()).thenReturn(substitutedBinding); + when(substitution.targetNamespace()).thenReturn("test"); + when(substitution.canonicalBytes()).thenReturn(receiptBytes); + when(substitution.digest()).thenReturn(DraftAuthorizationFenceBinding.digest(receiptBytes)); + assertThatThrownBy( + () -> new SelectedOwnerIntakeSettlementEvidence.Result(request, substitution)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("original authorization"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java new file mode 100644 index 0000000000..8b3007c481 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java @@ -0,0 +1,279 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeResponse; +import org.junit.jupiter.api.Test; + +class AutomationSelectedSourceIntakeCommandGrpcCodecTest { + private static final UUID ACTOR = id("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + + @Test + void roundTripsOriginalAutomationAuthorizationAndCompleteWorldFreezeOnDistinctCorrelations() { + var freeze = freeze(); + var binding = + authorization(freeze.request().accountBinding().input().selection().selectedCommit()); + var first = + AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze); + var retry = + AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze); + + var firstWire = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(first); + var retryWire = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(retry); + + assertThat(first.transportRequestId()).isNotEqualTo(retry.transportRequestId()); + assertThat(first.transportRequestId()) + .isNotIn( + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.selected().requestId(), + binding.selected().commitId(), + freeze.acknowledgement().intakeRequestId(), + freeze.acknowledgement().publicationFence()); + assertThat(AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(firstWire)) + .isEqualTo(first); + assertThat(AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(retryWire)) + .isEqualTo(retry); + assertThat(firstWire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .isEqualTo(binding.canonicalBytes()); + assertThat(firstWire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + assertThat(firstWire.getFreezeRequest()) + .isEqualTo(WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())); + assertThat(firstWire.getFreezeAcknowledgement()) + .isEqualTo( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())); + assertThat(firstWire.getSerializedSize()) + .isLessThanOrEqualTo(AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES); + } + + @Test + void rejectsUnknownFieldsOversizedWireAndChangedFreezeOrAuthorizationScope() { + var freeze = freeze(); + var binding = + authorization(freeze.request().accountBinding().input().selection().selectedCommit()); + var request = + AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze); + var wire = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setIntakeAuthorizationDigest("0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder() + .setFreezeRequest( + wire.getFreezeRequest().toBuilder().setUnknownFields(unknown).build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte + [AutomationSelectedSourceIntakeCommandGrpcCodec + .MAX_REQUEST_WIRE_BYTES + + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire budget"); + + var otherNamespaceFreeze = freeze("other"); + assertThatThrownBy( + () -> + new AutomationSelectedSourceIntakeCommandEvidence.Request( + AutomationSelectedSourceIntakeCommandEvidence.Request.SCHEMA_VERSION, + "test", + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + binding, + otherNamespaceFreeze)) + .isInstanceOf(IllegalArgumentException.class); + var wrongOwner = + authorization( + freeze.request().accountBinding().input().selection().selectedCommit(), + Owner.ENTITY_MANAGEMENT); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandEvidence.Request.create( + "test", wrongOwner, freeze)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void responseRequiresExactFullRequestEchoAndEncodesReceiptBytesAndDigest() { + var freeze = freeze(); + var binding = + authorization(freeze.request().accountBinding().input().selection().selectedCommit()); + var request = + AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze); + var receipt = mock(AutomationEmptySelectedSourceIntakeReceipt.class); + byte[] storedReceipt = {1, 2, 3}; + when(receipt.canonicalBytes()).thenReturn(storedReceipt); + when(receipt.receiptDigest()).thenReturn("a".repeat(64)); + when(receipt.authorizationBindingBytes()).thenReturn(binding.canonicalBytes()); + when(receipt.authorizationBindingDigest()).thenReturn(binding.digest()); + var evidence = new AutomationSelectedSourceIntakeCommandEvidence(request, receipt); + var response = AutomationSelectedSourceIntakeCommandGrpcCodec.toResponse(evidence); + + assertThat(response.getRequest()) + .isEqualTo(AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(request)); + assertThat(response.getCommittedEmptyReceipt().toByteArray()).isEqualTo(storedReceipt); + assertThat(response.getReceiptDigest()).isEqualTo("a".repeat(64)); + + var changedFreeze = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setFreezeAcknowledgement( + response.getRequest().getFreezeAcknowledgement().toBuilder() + .setContentDigest("b".repeat(64))) + .build()) + .build(); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse(request, changedFreeze)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed"); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + } + + private static SelectedOwnerIntakeAuthorizationBinding authorization( + DraftCommitBinding selected) { + return authorization(selected, Owner.AUTOMATION_SCRIPTING); + } + + private static SelectedOwnerIntakeAuthorizationBinding authorization( + DraftCommitBinding selected, Owner owner) { + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + "test", + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + id("88888888-8888-4888-8888-888888888888"), + ACTOR, + selected); + var contentBytes = new ByteArrayOutputStream(); + frame(contentBytes, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(contentBytes, scope.canonicalBytes()); + frame(contentBytes, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); + frame(contentBytes, family); + frame(contentBytes, snapshot); + frame(contentBytes, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] canonicalContent = contentBytes.toByteArray(); + var content = + SelectedOwnerIntakeSourceContent.fromStored( + canonicalContent, scope, DraftAuthorizationFenceBinding.digest(canonicalContent)); + return new SelectedOwnerIntakeAuthorizationBinding( + content, + List.of( + source(SourceKind.ACCOUNT, ACTOR.toString()), + source(SourceKind.TENANT, selected.target().canonicalTenantId().toString()), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + selected.target().canonicalTenantId()))); + } + + private static SourceEvidence source(SourceKind kind, String scope) { + return new SourceEvidence(kind, scope, null, "1", null, null, new byte[] {1}); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freeze() { + return freeze("test"); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freeze(String namespace) { + var original = WorldSelectedDraftPublicationFreezeGrpcCodecTest.request(); + if (!namespace.equals(original.targetNamespace())) { + // The fixture's Account publication binding is namespace-independent; rebuild only its + // request tuple through the same constructor used by the production value. + original = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + namespace, + original.canonicalTenantId(), + original.canonicalVersionId(), + original.publicationRequestId(), + original.expectedVersionStateEpoch(), + original.requestDigest(), + original.accountBinding()); + } + var acknowledgement = + new Acknowledgement( + original, + id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + original.expectedVersionStateEpoch(), + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + OwnerFreezePhase.FROZEN, + original.accountBinding().input().selection().selectedCommit().commitId().toString(), + "a".repeat(64), + 3); + BeginVersionPublicationFreezeResponse response = + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(original, response); + } + + private static void frame(ByteArrayOutputStream output, String value) { + DraftAuthorizationFenceBinding.frame(output, value); + } + + private static void frame(ByteArrayOutputStream output, byte[] value) { + DraftAuthorizationFenceBinding.frame(output, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java new file mode 100644 index 0000000000..dd9c12869b --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java @@ -0,0 +1,181 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeCommandServiceGrpc; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence.Request; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec; +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.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for Automation's unregistered selected-source command. */ +public final class GrpcAutomationSelectedSourceIntakeCommandClient + extends AbstractReloadingBlockingGrpcClient< + AutomationSelectedSourceIntakeCommandServiceGrpc + .AutomationSelectedSourceIntakeCommandServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcAutomationSelectedSourceIntakeCommandClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcAutomationSelectedSourceIntakeCommandClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Automation selected-source command client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Automation selected-source command stub unavailable"); + } + initialized = true; + } + + /** Returns only the exact immutable receipt echoed for this complete original request. */ + public AutomationSelectedSourceIntakeCommandEvidence retain(Request request) { + requireWorkloadOnlyContext(); + Objects.requireNonNull(request, "selected-source command request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Automation selected-source command must use the configured workload namespace"); + } + var wireRequest = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(request); + var current = requireStub(); + try { + var response = + current + .withMaxOutboundMessageSize( + AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .retainSelectedSource(wireRequest); + return AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse(request, response); + } catch (StatusRuntimeException denied) { + throw Status.fromCode(denied.getStatus().getCode()).asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Automation returned invalid selected-source receipt evidence"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAutomationScriptingService(); + } + + @Override + protected String defaultTarget() { + return "automation-scripting-service:6565"; + } + + @Override + protected AutomationSelectedSourceIntakeCommandServiceGrpc + .AutomationSelectedSourceIntakeCommandServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = automationServerPeerUri(workloadNamespace); + return AutomationSelectedSourceIntakeCommandServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withMaxOutboundMessageSize( + AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AutomationSelectedSourceIntakeCommandServiceGrpc + .AutomationSelectedSourceIntakeCommandServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Automation selected-source command client is not initialized and available"); + } + return currentStub; + } + + private static void requireWorkloadOnlyContext() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Automation selected-source command requires no ambient SQL or synchronization"); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException( + "Automation selected-source command requires workload-only context"); + } + } + + private static String automationServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/automation-scripting-service"; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Automation selected-source command requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Automation selected-source command requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Invalid Automation selected-source command " + label + " path"); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Automation selected-source command " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeSettlementClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeSettlementClient.java new file mode 100644 index 0000000000..cffa6a3712 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeSettlementClient.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedOwnerIntakeSettlementServiceGrpc; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence.Request; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence.Result; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementGrpcCodec; +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.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for the standalone, unregistered Account settlement command. */ +public final class GrpcSelectedOwnerIntakeSettlementClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedOwnerIntakeSettlementServiceGrpc + .AccountSelectedOwnerIntakeSettlementServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcSelectedOwnerIntakeSettlementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcSelectedOwnerIntakeSettlementClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Account settlement client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) throw new IllegalStateException("Account settlement stub unavailable"); + initialized = true; + } + + /** Settles the complete existing authorization under its original durable identity. */ + public Result settle(Request request) { + requireNoAmbientContext(); + Objects.requireNonNull(request, "Selected-owner settlement request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException("Account selected-owner settlement namespace mismatch"); + } + var wireRequest = SelectedOwnerIntakeSettlementGrpcCodec.toRequest(request); + var current = stub(); + if (closed || !initialized || current == null) { + throw new IllegalStateException("Account selected-owner settlement client unavailable"); + } + try { + var secured = + current + .withCallCredentials( + new GrpcServerPeerIdentityCallCredentials( + accountServerPeerUri(workloadNamespace))) + .withMaxOutboundMessageSize(SelectedOwnerIntakeSettlementGrpcCodec.MAX_REQUEST_BYTES) + .withMaxInboundMessageSize(SelectedOwnerIntakeSettlementGrpcCodec.MAX_RESPONSE_BYTES) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS); + var response = secured.settleSelectedOwnerIntake(wireRequest); + return SelectedOwnerIntakeSettlementGrpcCodec.fromResponse(request, response); + } catch (StatusRuntimeException unavailable) { + throw Status.fromCode(unavailable.getStatus().getCode()) + .withDescription("Account selected-owner settlement denied or unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Account returned invalid selected-owner settlement evidence"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedOwnerIntakeSettlementServiceGrpc + .AccountSelectedOwnerIntakeSettlementServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = accountServerPeerUri(workloadNamespace); + return AccountSelectedOwnerIntakeSettlementServiceGrpc.newBlockingStub(channel) + .withMaxOutboundMessageSize(SelectedOwnerIntakeSettlementGrpcCodec.MAX_REQUEST_BYTES) + .withMaxInboundMessageSize(SelectedOwnerIntakeSettlementGrpcCodec.MAX_RESPONSE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private static void requireNoAmbientContext() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account selected-owner settlement requires no ambient SQL or synchronization"); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException( + "Account selected-owner settlement requires workload-only context"); + } + } + + private static String accountServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account selected-owner settlement requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account selected-owner settlement requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Invalid Account selected-owner settlement " + label + " path"); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account selected-owner settlement " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java new file mode 100644 index 0000000000..3c3a3ea7e2 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +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.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Constructor and pre-transport gates only; placeholder files do not prove an mTLS handshake. */ +class GrpcAutomationSelectedSourceIntakeCommandClientTest { + @AfterEach + void clearAmbientContext() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void requiresReadableFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) + throws IOException { + var channelFactory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + for (String invalidPath : + new String[] { + null, + "", + "classpath:credential.pem", + directory.toString(), + directory.resolve("missing.pem").toString() + }) { + var invalidCertificate = tls(directory); + invalidCertificate.setCertChain(invalidPath); + assertThatThrownBy( + () -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), invalidCertificate, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var invalidKey = tls(directory); + invalidKey.setPrivateKey(directory.resolve("missing-key.pem").toString()); + assertThatThrownBy( + () -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), invalidKey, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + var invalidCa = tls(directory); + invalidCa.setCaCert(directory.resolve("missing-ca.pem").toString()); + assertThatThrownBy( + () -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), invalidCa, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "Test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsAmbientSqlSynchronizationAndEndUserContextBeforeTransport(@TempDir Path directory) + throws IOException { + var channelFactory = mock(GrpcChannelFactory.class); + var client = + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "test"); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + + SessionContext.setContext("101", List.of(), Map.of()); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + } + + private static CommonGrpcClientProperties tls(Path directory) throws IOException { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain( + Files.writeString(directory.resolve("client.crt"), "placeholder cert").toString()); + tls.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "placeholder key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "placeholder CA").toString()); + return tls; + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeSettlementClientTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeSettlementClientTest.java new file mode 100644 index 0000000000..a54b8d8478 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcSelectedOwnerIntakeSettlementClientTest.java @@ -0,0 +1,123 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +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.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Constructor and pre-transport checks only; placeholder files do not prove an mTLS handshake. */ +class GrpcSelectedOwnerIntakeSettlementClientTest { + @AfterEach + void clearThreadContext() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void requiresFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) throws IOException { + var channelFactory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSettlementClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + for (String invalidPath : + new String[] { + null, + "", + "classpath:credential.pem", + directory.toString(), + directory.resolve("missing.pem").toString() + }) { + var invalidCertificate = tls(directory); + invalidCertificate.setCertChain(invalidPath); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSettlementClient( + new ServiceEndpointsProperties(), invalidCertificate, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var invalidKey = tls(directory); + invalidKey.setPrivateKey(directory.resolve("missing-key.pem").toString()); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSettlementClient( + new ServiceEndpointsProperties(), invalidKey, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + var invalidCa = tls(directory); + invalidCa.setCaCert(directory.resolve("missing-ca.pem").toString()); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSettlementClient( + new ServiceEndpointsProperties(), invalidCa, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcSelectedOwnerIntakeSettlementClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "Test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsAmbientSqlSynchronizationAndEndUserContextBeforeTransport(@TempDir Path directory) + throws IOException { + var channelFactory = mock(GrpcChannelFactory.class); + var client = + new GrpcSelectedOwnerIntakeSettlementClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "test"); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.settle(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.settle(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + + SessionContext.setContext("101", List.of(), Map.of()); + assertThatThrownBy(() -> client.settle(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + } + + private static CommonGrpcClientProperties tls(Path directory) throws IOException { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain( + Files.writeString(directory.resolve("client.crt"), "placeholder cert").toString()); + tls.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "placeholder key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "placeholder CA").toString()); + return tls; + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 9aad9a3501..6657131c44 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -51,6 +51,7 @@ import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeTerminalReadService; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedSourceIntakeCommandGrpcService; import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedSourceIntakeTerminalReadGrpcService; import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeAuthorizationGrpcClient; @@ -58,6 +59,7 @@ import net.firedevops.firemud.common.account.sourceintake.GrpcSelectedOwnerIntakeSourceReadClient; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; @@ -76,6 +78,7 @@ import net.firedevops.firemud.common.authoring.WorldOriginalDraftGraphApplyClient; import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; @@ -122,7 +125,9 @@ import net.firedevops.firemud.common.publication.WorldSelectedOwnerInventoryGrpcClient; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; import net.firedevops.firemud.common.security.PublicationReadGuard; +import net.firedevops.firemud.common.security.sourceintake.GrpcAutomationSelectedSourceIntakeCommandClient; import net.firedevops.firemud.common.security.sourceintake.GrpcSelectedOwnerIntakeAuthorizationProducerClient; +import net.firedevops.firemud.common.security.sourceintake.GrpcSelectedOwnerIntakeSettlementClient; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; @@ -285,21 +290,21 @@ * loopback mTLS. World freeze, immutable inventory and published selector use their actual owner * services over loopback mTLS, with the canonical frozen selector captured owner-locally from the * committed freeze and retained APPLIED graph. Entity/Automation source disclosure uses the genuine - * Account issuer and retained preliminary reservations (the reservation helper's incoming Game - * Design peer is stipulated), then loopback mTLS for both the Account permission hop and the Game - * Design source hop. Automation additionally composes real Account finalization, the actual - * recipient-specific World closure/inventory reader, the Automation empty-source receipt owner, and - * Account terminal settlement. Its Account authorization command traverses the native producer over - * loopback mTLS; preliminary reservation and local Automation-retain/Account-settlement calls still - * use stipulated Game Design peer contexts. Entity retention and Entity/Automation publication - * participant digests, in-memory S3 and the StartSession Account projection remain test doubles. - * The complete launch-binding case wires the actual Game Design handler and World Management mTLS - * client on this fixture's loopback server to the actual owner implementation in an explicitly - * established read-only repeatable-read snapshot; unrelated handler dependencies are isolated. This - * fixture does not provide production-mounted certificates or full application server wiring, - * authenticated Automation retention/settlement command ingress, Account-projection-backed - * StartSession admission, a complete four-owner authenticated release, runtime launch, activation - * or registration. + * Account issuer and retained preliminary reservations, then loopback mTLS for both the Account + * permission hop and the Game Design source hop. Automation additionally composes real Account + * finalization, the actual recipient-specific World closure/inventory reader, the Automation + * empty-source receipt owner, and Account terminal settlement. Its positive Account authorization + * command creates a fresh reservation through the native producer. Automation retention and Account + * settlement each traverse their native command receivers over loopback mTLS. The earlier + * disclosure/abort setup uses stipulated incoming Game Design peer contexts and is not the positive + * authorization operation. Entity retention and Entity/Automation publication participant digests, + * in-memory S3 and the StartSession Account projection remain test doubles. The complete + * launch-binding case wires the actual Game Design handler and World Management mTLS client on this + * fixture's loopback server to the actual owner implementation in an explicitly established + * read-only repeatable-read snapshot; unrelated handler dependencies are isolated. This fixture + * does not provide production-mounted certificates or full application server wiring, complete + * owner census or production ingress, Account-projection-backed StartSession admission, a complete + * four-owner authenticated release, runtime launch, activation or registration. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -475,6 +480,18 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var accountToAutomationTerminal = new AutomationSelectedSourceIntakeTerminalReadClient( endpoints, pki.client("account-service"), channels, NAMESPACE); + var automationSelectedSourceCommandClient = + new GrpcAutomationSelectedSourceIntakeCommandClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var wrongWorkloadAutomationSelectedSourceCommandClient = + new GrpcAutomationSelectedSourceIntakeCommandClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var selectedOwnerSettlementClient = + new GrpcSelectedOwnerIntakeSettlementClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var wrongWorkloadSelectedOwnerSettlementClient = + new GrpcSelectedOwnerIntakeSettlementClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); var glToAccountHeld = new GameLogicIntakeAuthorizationReadClient( endpoints, pki.client("game-logic-service"), channels, NAMESPACE); @@ -819,6 +836,10 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex automationToWorldInventory.init(); worldToAccountClosure.init(); accountToAutomationTerminal.init(); + automationSelectedSourceCommandClient.init(); + wrongWorkloadAutomationSelectedSourceCommandClient.init(); + selectedOwnerSettlementClient.init(); + wrongWorkloadSelectedOwnerSettlementClient.init(); glToAccountHeld.init(); glToGdSource.init(); accountToGlTerminal.init(); @@ -835,6 +856,19 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var automationIntakeOwner = new AutomationEmptySelectedSourceIntakeService( automationIntakeRepository, automationToAccountHeld, automationToWorldInventory); + register( + automationHandlers, + new AutomationSelectedSourceIntakeCommandGrpcService(automationIntakeOwner, NAMESPACE)); + var selectedOwnerSettlementOwner = + new AccountSelectedOwnerIntakeSettlementService( + accountSelectedOwnerSourceRepository, + accountToAutomationTerminal, + accountAccess.sources().manager, + NAMESPACE); + register( + accountHandlers, + new AccountSelectedOwnerIntakeSettlementGrpcService( + selectedOwnerSettlementOwner, NAMESPACE)); var sourceCommit = new GameDesignWorldSourceCommitService( @@ -1026,6 +1060,26 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex selectedOwnerReservationSourceRows( accountSourceDsl, automationSourceReservation.operationId())) .containsExactlyElementsOf(automationReservationSourcesBeforeAbort); + assertThat( + account + .abortSelectedOwnerSourceRead(automationSourceReservation, NAMESPACE) + .state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED); + assertThat( + account + .recoverSelectedOwnerSourceRead(automationSourceReservation, NAMESPACE) + .state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, automationSourceReservation.operationId())) + .containsExactlyElementsOf(automationReservationSourcesBeforeAbort); + assertThat( + accountSourceDsl.fetchOne( + "SELECT operation_id FROM account_selected_owner_intake_authorizations " + + "WHERE operation_id = ?", + automationSourceReservation.operationId())) + .isNull(); assertThatThrownBy( () -> accountToGdSelectedOwnerSource.read( @@ -1280,13 +1334,24 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(retainedTemplateAssociations).hasSize(1); assertThat(retainedTemplateAssociations.getFirst().templateId()).isEqualTo(templateId); + UUID freshAutomationIntakeRequest = UUID.randomUUID(); + assertThat(freshAutomationIntakeRequest) + .isNotEqualTo(automationSourceReservation.intakeRequestId()) + .isNotEqualTo(entitySourceReservation.intakeRequestId()); var automationAuthorizationRequest = SelectedOwnerIntakeAuthorizationProducerEvidence.Request.create( - NAMESPACE, automationIntakeRequest, Owner.AUTOMATION_SCRIPTING, selectedCommit); + NAMESPACE, + freshAutomationIntakeRequest, + Owner.AUTOMATION_SCRIPTING, + selectedCommit); var automationAuthorizationResult = gdToAccountSelectedOwnerAuthorizationProducer.authorize( automationAuthorizationRequest, accountAccess.compact()); var automationAuthorization = automationAuthorizationResult.binding(); + var freshAutomationScope = automationAuthorization.content().scope(); + var freshAutomationReservationSources = + selectedOwnerReservationSourceRows( + accountSourceDsl, freshAutomationScope.operationId()); assertThat(automationAuthorizationResult.request()) .isEqualTo(automationAuthorizationRequest); assertThat(automationAuthorizationResult.canonicalBindingBytes()) @@ -1295,13 +1360,20 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex .isEqualTo(automationAuthorization.digest()); assertThat(automationAuthorization.owner()).isEqualTo(Owner.AUTOMATION_SCRIPTING); assertThat(automationAuthorization.intakeRequestId()) - .isEqualTo(automationSourceReservation.intakeRequestId()); + .isEqualTo(freshAutomationIntakeRequest); assertThat(automationAuthorization.operationId()) - .isEqualTo(automationSourceReservation.operationId()); + .isEqualTo(freshAutomationScope.operationId()) + .isNotEqualTo(automationSourceReservation.operationId()); assertThat(automationAuthorization.fenceId()) - .isEqualTo(automationSourceReservation.fenceId()); + .isEqualTo(freshAutomationScope.fenceId()) + .isNotEqualTo(automationSourceReservation.fenceId()); + assertThat(freshAutomationScope.owner()).isEqualTo(Owner.AUTOMATION_SCRIPTING); + assertThat(freshAutomationScope.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(freshAutomationScope.intakeRequestId()).isEqualTo(freshAutomationIntakeRequest); + assertThat(freshAutomationScope.selected().canonicalBytes()) + .containsExactly(selectedCommit.canonicalBytes()); assertThat(automationAuthorization.content().scope().canonicalBytes()) - .containsExactly(automationSourceReservation.canonicalBytes()); + .containsExactly(freshAutomationScope.canonicalBytes()); assertThat(automationAuthorization.content().snapshotBytes("COMMAND")) .containsExactly(selectedSources.command().canonicalBytes()); assertThat(automationAuthorization.content().snapshotBytes("REALM_POLICY")) @@ -1321,6 +1393,24 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(automationAuthorization.selected().canonicalBytes()) .containsExactly(selectedCommit.canonicalBytes()); assertThat(accountSelectedSourceReads).hasValue(1); + assertThat(freshAutomationReservationSources) + .containsExactlyElementsOf(expectedAccountSourceEvidence); + assertThat( + accountSourceDsl.fetchOne( + "SELECT operation_id FROM account_selected_owner_intake_authorizations " + + "WHERE operation_id = ?", + freshAutomationScope.operationId())) + .isNotNull(); + assertThat(account.recoverSelectedOwnerSourceRead(freshAutomationScope, NAMESPACE).state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.FINALIZED); + assertThat( + account.recoverSelectedOwnerSourceRead(entitySourceReservation, NAMESPACE).state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED); + assertThat( + account + .recoverSelectedOwnerSourceRead(automationSourceReservation, NAMESPACE) + .state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED); assertThat( selectedOwnerReservationSourceRows( accountSourceDsl, automationSourceReservation.operationId())) @@ -1335,6 +1425,10 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(io.grpc.Status.fromThrowable(failure).getCode()) .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); assertThat(accountSelectedSourceReads).hasValue(1); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, freshAutomationScope.operationId())) + .containsExactlyElementsOf(freshAutomationReservationSources); assertThat( selectedOwnerReservationSourceRows( accountSourceDsl, automationSourceReservation.operationId())) @@ -1350,18 +1444,36 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(exactAutomationAuthorizationRetry.digest()) .isEqualTo(automationAuthorization.digest()); assertThat(accountSelectedSourceReads).hasValue(1); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, freshAutomationScope.operationId())) + .containsExactlyElementsOf(freshAutomationReservationSources); assertThat( selectedOwnerReservationSourceRows( accountSourceDsl, automationSourceReservation.operationId())) .containsExactlyElementsOf(automationReservationSourcesBeforeAbort); var automationRowsBeforeRetention = automationSourceRowCounts(automation.dsl()); - var automationReceipt = - withGameDesignPeer( + var automationRetainRequest = + AutomationSelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, automationAuthorization, actualFreeze); + assertThatThrownBy( () -> - automationIntakeOwner.retain(NAMESPACE, automationAuthorization, actualFreeze)); + wrongWorkloadAutomationSelectedSourceCommandClient.retain( + automationRetainRequest)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + assertThat(automationSourceRowCounts(automation.dsl())) + .isEqualTo(automationRowsBeforeRetention); + AutomationSelectedSourceIntakeCommandEvidence automationRetainEvidence = + automationSelectedSourceCommandClient.retain(automationRetainRequest); + assertThat(automationRetainEvidence.request()).isEqualTo(automationRetainRequest); + var automationReceipt = automationRetainEvidence.receipt(); assertThat(automationReceipt.outcome()).isEqualTo("COMMITTED_EMPTY"); - assertThat(automationReceipt.intakeRequestId()).isEqualTo(automationIntakeRequest); + assertThat(automationReceipt.intakeRequestId()).isEqualTo(freshAutomationIntakeRequest); assertThat(automationReceipt.authorizationBindingBytes()) .containsExactly(automationAuthorization.canonicalBytes()); assertThat(automationReceipt.authorizationBindingDigest()) @@ -1421,7 +1533,7 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(automationReceipt.receiptDigest()) .isEqualTo(DraftAuthorizationFenceBinding.digest(automationReceipt.canonicalBytes())); var persistedAutomationReceipt = - automationIntakeRepository.read(NAMESPACE, automationIntakeRequest).orElseThrow(); + automationIntakeRepository.read(NAMESPACE, freshAutomationIntakeRequest).orElseThrow(); assertThat(persistedAutomationReceipt.canonicalBytes()) .containsExactly(automationReceipt.canonicalBytes()); assertThat(persistedAutomationReceipt.receiptDigest()) @@ -1446,10 +1558,10 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex automationRowsBeforeRetention.get("automation_empty_source_numeric_key_reservation") + 2); - var automationReceiptRetry = - withGameDesignPeer( - () -> - automationIntakeOwner.retain(NAMESPACE, automationAuthorization, actualFreeze)); + var automationReceiptRetryEvidence = + automationSelectedSourceCommandClient.retain(automationRetainRequest); + assertThat(automationReceiptRetryEvidence.request()).isEqualTo(automationRetainRequest); + var automationReceiptRetry = automationReceiptRetryEvidence.receipt(); assertThat(automationReceiptRetry.canonicalBytes()) .containsExactly(automationReceipt.canonicalBytes()); assertThat(automationReceiptRetry.receiptDigest()) @@ -1457,17 +1569,48 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(automationSourceRowCounts(automation.dsl())) .isEqualTo(automationRowsAfterRetention); - var selectedOwnerSettlementOwner = - new AccountSelectedOwnerIntakeSettlementService( - accountSelectedOwnerSourceRepository, - accountToAutomationTerminal, - accountAccess.sources().manager, - NAMESPACE); + var automationRetainNewCorrelationRequest = + AutomationSelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, automationAuthorization, actualFreeze); + assertThat(automationRetainNewCorrelationRequest.transportRequestId()) + .isNotEqualTo(automationRetainRequest.transportRequestId()); + assertThat( + automationRetainNewCorrelationRequest + .originalAuthorizationBinding() + .canonicalBytes()) + .containsExactly(automationAuthorization.canonicalBytes()); + assertThat(automationRetainNewCorrelationRequest.freezeEvidence()).isEqualTo(actualFreeze); + var automationRetainNewCorrelationEvidence = + automationSelectedSourceCommandClient.retain(automationRetainNewCorrelationRequest); + assertThat(automationRetainNewCorrelationEvidence.request()) + .isEqualTo(automationRetainNewCorrelationRequest); + assertThat(automationRetainNewCorrelationEvidence.receipt().canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + assertThat(automationRetainNewCorrelationEvidence.receipt().receiptDigest()) + .isEqualTo(automationReceipt.receiptDigest()); + assertThat(automationSourceRowCounts(automation.dsl())) + .isEqualTo(automationRowsAfterRetention); + assertThat( accountSourceDsl.fetchCount(DSL.table("account_selected_owner_intake_settlements"))) .isZero(); - var accountSettlement = - withGameDesignPeer(() -> selectedOwnerSettlementOwner.settle(automationAuthorization)); + var accountSettlementRequest = + SelectedOwnerIntakeSettlementEvidence.Request.create( + NAMESPACE, automationAuthorization); + assertThatThrownBy( + () -> wrongWorkloadSelectedOwnerSettlementClient.settle(accountSettlementRequest)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + assertThat( + accountSourceDsl.fetchCount(DSL.table("account_selected_owner_intake_settlements"))) + .isZero(); + var accountSettlementEvidence = + selectedOwnerSettlementClient.settle(accountSettlementRequest); + assertThat(accountSettlementEvidence.request()).isEqualTo(accountSettlementRequest); + var accountSettlement = accountSettlementEvidence.receipt(); assertThat(accountSettlement.authorizationBinding().canonicalBytes()) .containsExactly(automationAuthorization.canonicalBytes()); assertThat(accountSettlement.ownerReceiptBytes()) @@ -1501,26 +1644,57 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex .isEqualTo(accountSettlement.terminalEvidence().request().readRequestId()); var exactAccountSettlementRetry = - withGameDesignPeer(() -> selectedOwnerSettlementOwner.settle(automationAuthorization)); - assertThat(exactAccountSettlementRetry.canonicalBytes()) + selectedOwnerSettlementClient.settle(accountSettlementRequest); + assertThat(exactAccountSettlementRetry.request()).isEqualTo(accountSettlementRequest); + assertThat(exactAccountSettlementRetry.receipt().canonicalBytes()) .containsExactly(accountSettlement.canonicalBytes()); assertThat( accountSourceDsl.fetchCount(DSL.table("account_selected_owner_intake_settlements"))) .isOne(); + var accountSettlementNewCorrelationRequest = + SelectedOwnerIntakeSettlementEvidence.Request.create( + NAMESPACE, automationAuthorization); + assertThat(accountSettlementNewCorrelationRequest.transportRequestId()) + .isNotEqualTo(accountSettlementRequest.transportRequestId()); + assertThat(accountSettlementNewCorrelationRequest.authorizationBindingBytes()) + .containsExactly(automationAuthorization.canonicalBytes()); + var accountSettlementNewCorrelationResult = + selectedOwnerSettlementClient.settle(accountSettlementNewCorrelationRequest); + assertThat(accountSettlementNewCorrelationResult.request()) + .isEqualTo(accountSettlementNewCorrelationRequest); + assertThat(accountSettlementNewCorrelationResult.receipt().canonicalBytes()) + .containsExactly(accountSettlement.canonicalBytes()); + assertThat(accountSettlementNewCorrelationResult.receipt().digest()) + .isEqualTo(accountSettlement.digest()); + assertThat( + accountSettlementNewCorrelationResult + .receipt() + .terminalEvidence() + .request() + .readRequestId()) + .isEqualTo(accountSettlement.terminalEvidence().request().readRequestId()); + assertThat( + accountSourceDsl.fetchCount(DSL.table("account_selected_owner_intake_settlements"))) + .isOne(); assertFailedPrecondition( () -> automationToAccountHeld.read( SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( NAMESPACE, automationAuthorization))); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, freshAutomationScope.operationId())) + .containsExactlyElementsOf(freshAutomationReservationSources); assertThat( selectedOwnerReservationSourceRows( accountSourceDsl, automationSourceReservation.operationId())) .containsExactlyElementsOf(automationReservationSourcesBeforeAbort); - var automationReceiptAfterSettlement = - withGameDesignPeer( - () -> - automationIntakeOwner.retain(NAMESPACE, automationAuthorization, actualFreeze)); + var automationReceiptAfterSettlementEvidence = + automationSelectedSourceCommandClient.retain(automationRetainRequest); + assertThat(automationReceiptAfterSettlementEvidence.request()) + .isEqualTo(automationRetainRequest); + var automationReceiptAfterSettlement = automationReceiptAfterSettlementEvidence.receipt(); assertThat(automationReceiptAfterSettlement.canonicalBytes()) .containsExactly(automationReceipt.canonicalBytes()); assertThat(automationReceiptAfterSettlement.receiptDigest()) @@ -2549,21 +2723,6 @@ private static T withGameSessionPeer(Supplier operation) { } } - private static T withGameDesignPeer(Supplier operation) { - var peer = - new GrpcPeerIdentity( - "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service", - NAMESPACE, - "game-design-service"); - Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); - Context previous = context.attach(); - try { - return operation.get(); - } finally { - context.detach(previous); - } - } - private static void assertFailedPrecondition(Runnable operation) { assertThatThrownBy(operation::run) .isInstanceOf(io.grpc.StatusRuntimeException.class) From d4ba9edbd418d882a09417cf87bc62ea53e79b9d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 05:26:11 +1300 Subject: [PATCH 093/129] Converge admission confirmation on genuine acknowledged V122 finalization --- .../account-service/runtime-and-data.md | 8 + ...ame-authoring-publishing-and-activation.md | 6 + ...eplayAdmissionCommitConfirmationOwner.java | 20 +- ...AdmissionCommitConfirmationRepository.java | 20 +- ...ameplayAdmissionReceiptCommitExecutor.java | 27 +- ...rimental_admission_confirmation_writes.sql | 26 + ...issionLeasePersistenceIntegrationTest.java | 1428 ++--------------- ...rotectedEntryPrototypeIntegrationTest.java | 951 +++++------ ...yAdmissionCommitConfirmationOwnerTest.java | 29 +- ...ssionCommitConfirmationRepositoryTest.java | 41 +- ...layAdmissionReceiptCommitExecutorTest.java | 188 +-- ...nt-admission-protected-entry-prototype.sql | 196 --- 12 files changed, 707 insertions(+), 2233 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V136__retire_experimental_admission_confirmation_writes.sql delete mode 100644 services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index a5d78feaf0..fb802423f9 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -160,6 +160,14 @@ Token refresh, replacement, generation, revocation, fencing, and logout are cano Game Session orchestrates binding-refresh installation and reconciliation through Account-owned operations; it never writes Account-owned registry or authority state. Current runtime still uses the legacy Account session keys rather than the target issued-token registry, so the target refresh, replacement, fencing, and logout proof remains unavailable. +### Original Gameplay Admission COMMIT Acknowledgement + +The original lease finalizer owns a fresh writable SERIALIZABLE PostgreSQL 16 transaction, its enlisted physical connection, synchronous COMMIT acknowledgement and subsequent database-clock upper bound strictly before the unchanged original expiry. Only that successful physical path constructs the immutable in-process acknowledgement; a retained `COMMITTED` row, caller clock or receipt lookup cannot reconstruct it. Missing original acknowledgement, an unavailable or late clock bound, unsupported durability settings and ambiguous COMMIT outcomes deny without reminting the original proof. + +V122 stores that exact trusted-JVM acknowledgement in an independent receipt transaction. SQL validates its complete original binding, independent finalization XID and shape; it does not authenticate the opaque JVM capability or derive its original clock bound. A fresh receipt insert returns only after the actual synchronous receipt COMMIT and an independent exact read. An existing receipt, including recovery after lost receipt acknowledgement or original expiry, additionally requires the unchanged historical independent durability reader. Missing or unverifiable historical coverage denies; quiet-primary success is not guaranteed. Neither receipt nor recovery renews expiry or supplies current source authority, gameplay admission or runtime activation. Detailed implementation and executed proof belong in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + +Retained experimental confirmation evidence and its historical independent reader remain immutable; new experimental confirmation writes are unavailable. Original-finalization XID/binding stamps and pending source fences remain part of the genuine acknowledgement boundary. This does not authorize gameplay admission or production privilege adoption; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records migration, fixture convergence and executed proof. + ## Membership and Entitlement Authority Billing-safe mutation authority contract: 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 a40c64e0c1..adac2325f4 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 @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The accepted admission boundary is [genuine original-COMMIT acknowledgement with conditional independent recovery](../../architecture/microservices/account-service/runtime-and-data.md#original-gameplay-admission-commit-acknowledgement). Guaranteed quiet-primary recovery was an experimental feasibility objective, not an accepted requirement. The local correction removes only the unwired V120 fresh-confirmation JVM calls and prototype writer fixture; additive V136 closes its SQL function and every new receipt INSERT while preserving retained rows, immutable guards, historical readers, V120 finalization stamps and V121 pending fences. The transferred V122 definitions retain concurrency/exact-winner, rollback, binding/forgery/privilege, transaction-independence, unchanged expiry and lost-receipt-acknowledgement obligations. Synthetic pre-V136 rows prove migration preservation only, never historical durability. The nine failures on the older composed candidate are not cleared by wording or unexecuted replacement definitions; corrected PostgreSQL execution and a commissioned independent correction review remain required. V122 storage/acknowledgement proof does not supply current platform restrictions, complete current Account authority or gameplay admission. + +The bounded Account correction passes `generateJooq`, the complete Account `check`, integration compilation, affected formatting/static analysis and `bootJar`. Its first gate freshly executes 1,343 unit tests and 12 non-container integration tests; all 283 PostgreSQL-dependent integration cases skip locally, including the transferred finalization, synthetic-history migration and new-write-denial definitions. The final corrected gate reuses those passing unit results and recompiles/rechecks the fixed connection-owning fixture. These are local compilation and safety-definition results, not executed V136 PostgreSQL proof or independent-review completion. + +The local release-proof definition replaces the genuine fixture's in-memory object store with real SDK conditional PUT and exact GET readback against the Compose-pinned ephemeral MinIO image. Its Game Design check and compilation pass, but the PostgreSQL/MinIO case skips locally; real object I/O has not yet executed on this corrected definition. Entity, publication-participant and StartSession substitutes remain, so this is not full release or activation proof. + The current construction replaces the remaining in-process Automation-retention and Account-settlement commands with distinct, unregistered native mTLS transports. The owning [Automation command](../../architecture/microservices/automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) and [Account settlement command](../../architecture/microservices/account-service/api-contracts.md#grpc-apis) retain full original evidence, independent transport correlations, exact request echoes and immutable receipt readback. Receiver authentication derives from each server's configured namespace, not a namespace supplied by the caller. The genuine PostgreSQL fixture defines a fresh native Account reserve → authenticated source read → finalize → Automation retain → Account settle flow, plus wrong-workload no-mutation, exact retry, unchanged rows and post-settlement HELD denial. Its earlier, manually reserved Entity/Automation disclosure fixtures are explicitly aborted before the fresh positive operation; those setup contexts do not establish the positive producer boundary. Entity retention and publication participation, S3 and StartSession projection remain incomplete. Local validation of this native-command and timestamp-correction batch passes the five affected module checks, integration compilation, affected boot JARs, isolated proof JARs, static analysis, formatting, documentation and Flyway sanity (12 sets / 293 versioned files). The corrected final gate freshly executes 1,349 Account unit cases; unchanged tasks reuse the preceding passing 629 Common Platform, 152 Common Security, 1,202 Automation and 558 Game Design cases. Across those checks, 15 non-container integration cases pass and 533 cases skip (Account 290, Automation 94, Game Design 149). The four Account selected-owner PostgreSQL cases and expanded genuine Game Design composition compile but skip without Docker. These results are not physically executed current-composition PostgreSQL proof, production registration, or completion of any full Gameplay handoff. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java index d7563191da..5cd55caadf 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwner.java @@ -11,8 +11,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * Unregistered, non-admitting owner for database proof that an original lease COMMIT preceded its - * unchanged expiry. It evaluates no current source authority and does not finalize or admit. + * Unregistered, non-admitting historical reader for database proof that an original lease COMMIT + * preceded its unchanged expiry. It evaluates no current source authority and does not finalize or + * admit. */ public final class AccountGameplayAdmissionCommitConfirmationOwner { private final DataSource dataSource; @@ -32,21 +33,6 @@ public AccountGameplayAdmissionCommitConfirmationOwner(DataSource dataSource, St this.namespace = namespace; } - /** - * Creates/replays the temporal receipt, waits for that transaction to commit, then independently - * reads the durable receipt in a fresh transaction before returning it. - */ - public AccountGameplayAdmissionCommitConfirmation confirm( - FinalizeGameplayAdmissionLeaseRequest request) { - RequestIdentity identity = authenticateAndParse(request); - rejectAmbientTransaction(); - try { - return Objects.requireNonNull(executor.confirm(identity.evidence(), identity.decisionId())); - } catch (RuntimeException failure) { - throw unavailable(failure); - } - } - /** Reads an existing proof only; it never creates or repairs a receipt. */ public AccountGameplayAdmissionCommitConfirmation read( FinalizeGameplayAdmissionLeaseRequest request) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java index 4887402f54..373ff936f0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepository.java @@ -15,8 +15,9 @@ /** * Unregistered, non-admitting storage confirmation for an already retained COMMITTED lease. * - *

The database functions alone create or independently read a durability receipt. A raw - * operation state, timestamp, visible receipt row, or returned Java clock value is insufficient. + *

The retained historical database function alone independently reads a durability receipt. A + * raw operation state, timestamp, visible receipt row, or returned Java clock value is + * insufficient. */ public final class AccountGameplayAdmissionCommitConfirmationRepository { private final DSLContext dsl; @@ -31,21 +32,6 @@ public AccountGameplayAdmissionCommitConfirmationRepository( this.leaseRepository = Objects.requireNonNull(leaseRepository); } - /** Creates or exactly replays a database-stamped receipt for the original proven COMMIT. */ - AccountGameplayAdmissionCommitConfirmation confirmCommitted( - AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { - UUID requestId = validateRequest(evidence, bindingDecisionId); - Record row = - dsl.fetchOne( - "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", - requestId, - evidence.sha256(), - bindingDecisionId); - if (row == null) throw unavailable(); - AccountGameplayAdmissionLeaseOperation operation = exactCommitted(evidence, bindingDecisionId); - return confirmation(row, operation); - } - /** Reads only a committed, independently durable receipt; this path never creates one. */ AccountGameplayAdmissionCommitConfirmation readCommitConfirmation( AccountGameplayAdmissionLeaseEvidence evidence, UUID bindingDecisionId) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutor.java index 75d05e4406..49cb92d4c6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutor.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutor.java @@ -19,7 +19,10 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; -/** Unregistered receipt persistence executor; supplies no admission or original clock authority. */ +/** + * Unregistered retained historical receipt read executor; supplies no admission or original clock + * authority. + */ final class AccountGameplayAdmissionReceiptCommitExecutor { private final DataSource dataSource; @@ -27,29 +30,16 @@ final class AccountGameplayAdmissionReceiptCommitExecutor { this.dataSource = Objects.requireNonNull(dataSource); } - AccountGameplayAdmissionCommitConfirmation confirm( - AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { - rejectAmbient(); - var creation = new ReceiptTransactionManager(dataSource); - var created = execute(creation, evidence, decisionId, true); - // execute returns only after this manager observed the concrete JDBC COMMIT successfully. - rejectAmbient(); - var read = execute(new ReceiptTransactionManager(dataSource), evidence, decisionId, false); - if (!created.equals(read)) throw denied(); - return read; - } - AccountGameplayAdmissionCommitConfirmation read( AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { rejectAmbient(); - return execute(new ReceiptTransactionManager(dataSource), evidence, decisionId, false); + return execute(new ReceiptTransactionManager(dataSource), evidence, decisionId); } private static AccountGameplayAdmissionCommitConfirmation execute( ReceiptTransactionManager manager, AccountGameplayAdmissionLeaseEvidence evidence, - UUID decisionId, - boolean create) { + UUID decisionId) { Objects.requireNonNull(evidence); Objects.requireNonNull(decisionId); var transaction = new TransactionTemplate(manager); @@ -66,10 +56,7 @@ private static AccountGameplayAdmissionCommitConfirmation execute( new AccountGameplayAdmissionCommitConfirmationRepository( dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); var receipt = - Objects.requireNonNull( - create - ? repository.confirmCommitted(evidence, decisionId) - : repository.readCommitConfirmation(evidence, decisionId)); + Objects.requireNonNull(repository.readCommitConfirmation(evidence, decisionId)); if (!receipt.operation().evidence().canonicalJson().equals(evidence.canonicalJson()) || !receipt.operation().evidence().sha256().equals(evidence.sha256()) || !receipt.bindingDecisionId().equals(decisionId)) throw denied(); diff --git a/services/account-service/src/main/resources/db/migration/V136__retire_experimental_admission_confirmation_writes.sql b/services/account-service/src/main/resources/db/migration/V136__retire_experimental_admission_confirmation_writes.sql new file mode 100644 index 0000000000..ae140c93e9 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V136__retire_experimental_admission_confirmation_writes.sql @@ -0,0 +1,26 @@ +-- Retire only the unwired V120 fresh temporal-confirmation writer. Retained rows, its historical +-- independent durability reader and immutable guards remain unchanged. V120 original-finalizer +-- XID/binding stamps and V121 pending fences are still required by genuine V122 ACK receipts. +-- [jooq ignore start] +CREATE FUNCTION account_gameplay_admission_confirmation_writes_retired() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Experimental Account admission confirmation writes are retired' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_writes_retired'; +END; +$$; + +-- PostgreSQL executes same-event triggers by name: deny before the old INSERT proof guard. +CREATE TRIGGER account_admission_confirmation_00_retired_insert + BEFORE INSERT ON account_gameplay_admission_commit_confirmations FOR EACH ROW + EXECUTE FUNCTION account_gameplay_admission_confirmation_writes_retired(); + +CREATE OR REPLACE FUNCTION account_gameplay_admission_confirm_committed( + requested_request_id UUID, expected_sha TEXT, expected_decision UUID) +RETURNS SETOF account_gameplay_admission_commit_confirmations LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Experimental Account admission confirmation writes are retired' + USING ERRCODE = '23514', CONSTRAINT = 'account_admission_confirmation_writes_retired'; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index 83f363396a..4bf6be092c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -14,7 +14,6 @@ import java.sql.SQLException; import java.sql.Statement; import java.time.Instant; -import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -22,22 +21,14 @@ import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Function; import java.util.function.Supplier; import javax.sql.DataSource; import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; -import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; -import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionCommitConfirmation; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; @@ -76,32 +67,13 @@ class AccountGameplayAdmissionLeasePersistenceIntegrationTest { (context, failure) -> { // Only unexpected test failures reach this hook; expected assertThrows cases do not. try { - String testName = context.getRequiredTestMethod().getName(); - boolean confirmationCase = - "staleSerializableConfirmationInsertRetriesInsteadOfLeakingUniqueViolation" - .equals(testName) - || "idlePrimaryConfirmationCapturesBeforeLocksAndIndependentlyReadsExactReceipt" - .equals(testName); Throwable cause = failure; - var causeTypes = new ArrayList(); var visited = java.util.Collections.newSetFromMap( new java.util.IdentityHashMap()); while (cause != null && visited.add(cause)) { - causeTypes.add(cause.getClass().getSimpleName()); if (cause instanceof PSQLException postgresFailure) { var error = postgresFailure.getServerErrorMessage(); - if (confirmationCase) { - System.err.printf( - "Account admission confirmation failure for %s: causeTypes=%s " - + "SQLSTATE=%s constraint=%s%n", - testName, - causeTypes, - postgresFailure.getSQLState(), - error == null - ? "" - : Objects.toString(error.getConstraint(), "")); - } if ("23514".equals(postgresFailure.getSQLState()) && error != null && ("account_admission_confirmation_wal_coverage".equals(error.getConstraint()) @@ -128,8 +100,6 @@ class AccountGameplayAdmissionLeasePersistenceIntegrationTest { private static final String TENANT = "22222222-2222-4222-8222-222222222222"; private static final String OTHER = "33333333-3333-4333-8333-333333333333"; - private static final long V120_WAL_COORDINATOR_TIMEOUT_SECONDS = 3; - private static final String V120_WAL_MARKER_TABLE = "account_v120_wal_coverage_markers"; @BeforeAll static void start() { @@ -1065,585 +1035,107 @@ void concurrentDuplicatesReplayOneAllocationAndDistinctRequestsAdvanceFence() th } @Test - void durableConfirmationStoresOriginalCommitProofAndRecoversLostResponseAfterExpiry() - throws Exception { - var context = context(null); - UUID account = account(context); - var original = pending(context, account); - var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); - UUID decision = UUID.randomUUID(); - tx(context, () -> repository.recordCommitted(original, decision)); - var unchanged = storageSnapshot(context); - var transactionManager = new DataSourceTransactionManager(context.dataSource()); - var confirmationOwner = - new AccountGameplayAdmissionCommitConfirmationOwner(context.dataSource(), "test"); - var request = - FinalizeGameplayAdmissionLeaseRequest.newBuilder() - .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(original)) - .setBindingDecisionId(decision.toString()) - .build(); - - // The loopback peer, carrier and decision are synthetic upstream fixtures. The real Java - // owner creates and independently reads Account SQL proof; this does not prove mTLS. - syntheticReadPeer().call(() -> confirmationOwner.confirm(request)); // Discard the response. - // Inspect stored fields separately; this visible row alone is not durable readback proof. - var receipt = - Objects.requireNonNull( - context - .dsl() - .fetchOne( - "SELECT * FROM account_gameplay_admission_commit_confirmations WHERE request_id = ?", - requestId(original))); - assertThat(receipt.get("confirmation_version", Short.class)).isEqualTo((short) 1); - assertThat(receipt.get("request_id", UUID.class)).isEqualTo(requestId(original)); - assertThat(receipt.get("account_uuid", UUID.class)).isEqualTo(account); - assertThat(receipt.get("lease_id", UUID.class)) - .isEqualTo(UUID.fromString((String) original.carrier().get("leaseId"))); - assertThat(receipt.get("lease_fence", Long.class)) - .isEqualTo(original.leaseFence().longValueExact()); - assertThat(receipt.get("evidence_sha256", String.class)).isEqualTo(original.sha256()); - assertThat(receipt.get("binding_decision_id", UUID.class)).isEqualTo(decision); - assertThat(receipt.get("expires_at_ms", Long.class)).isEqualTo(expiresAt(original)); - assertThat(receipt.get("committed_before_ms", Long.class)) - .isPositive() - .isLessThan(expiresAt(original)); - assertThat(receipt.get("finalization_xid", String.class)) - .isEqualTo(operation(context, original).get("finalization_xid", String.class)); - assertThat(receipt.get("confirmation_xid", String.class)) - .isNotEqualTo(receipt.get("finalization_xid", String.class)); - assertThat( - Objects.requireNonNull( - context - .dsl() - .fetchOne( - "SELECT ?::pg_lsn >= ?::pg_lsn AS covered", - receipt.get("wal_flush_lsn", String.class), - receipt.get("wal_insert_lsn", String.class))) - .get("covered", Boolean.class)) - .isTrue(); - // Recovery opens the real owner's fresh transaction and covers the independently committed - // receipt's WAL before returning the immutable DTO, without reconstructing any proof fields. - var recovered = syntheticReadPeer().call(() -> confirmationOwner.read(request)); - assertThat(recovered.operation().state()).isEqualTo(State.COMMITTED); - assertThat(recovered.operation().evidence().canonicalJson()) - .isEqualTo(original.canonicalJson()); - assertThat(recovered.operation().evidence().sha256()).isEqualTo(original.sha256()); - assertThat(recovered.operation().bindingDecisionId()).isEqualTo(decision); - assertThat(recovered.requestId()).isEqualTo(receipt.get("request_id", UUID.class)); - assertThat(recovered.accountId()).isEqualTo(receipt.get("account_uuid", UUID.class)); - assertThat(recovered.leaseId()).isEqualTo(receipt.get("lease_id", UUID.class)); - assertThat(recovered.leaseFence()).isEqualTo(receipt.get("lease_fence", Long.class)); - assertThat(recovered.confirmationVersion()) - .isEqualTo(receipt.get("confirmation_version", Short.class)); - assertThat(recovered.evidenceSha256()).isEqualTo(receipt.get("evidence_sha256", String.class)); - assertThat(recovered.bindingDecisionId()) - .isEqualTo(receipt.get("binding_decision_id", UUID.class)); - assertThat(recovered.expiresAtMs()).isEqualTo(receipt.get("expires_at_ms", Long.class)); - assertThat(recovered.committedBeforeMs()) - .isEqualTo(receipt.get("committed_before_ms", Long.class)); - assertThat(recovered.finalizationXid()) - .isEqualTo(receipt.get("finalization_xid", String.class)); - assertThat(recovered.confirmationXid()) - .isEqualTo(receipt.get("confirmation_xid", String.class)); - assertThat(recovered.walInsertLsn()).isEqualTo(receipt.get("wal_insert_lsn", String.class)); - assertThat(recovered.walFlushLsn()).isEqualTo(receipt.get("wal_flush_lsn", String.class)); - waitPastDeadline(context, original); - assertThat(tx(context, () -> confirm(context, original, decision))).isEqualTo(receipt); - assertThat(syntheticReadPeer().call(() -> confirmationOwner.read(request))) - .isEqualTo(recovered); - assertThat(storageSnapshot(context)).isEqualTo(unchanged); - var readOwner = new AccountGameplayAdmissionReadOwner(repository, transactionManager, "test"); - assertFailedExactRead(readOwner, original); - } - - @Test - void receiptPhysicalCommitPrecedesIndependentV120ReadOnAnotherConnection() throws Exception { - var context = context(null); + void retainedUnstampedPreV120CommitCannotInventGenuineOriginalAcknowledgement() { + var context = context("119"); var original = pending(context, account(context)); UUID decision = UUID.randomUUID(); - new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) - .execute(original, decision); - createV120WalCoverageMarkerTable(context); - String applicationName = v120ApplicationName(); - var trace = new ReceiptCommitTrace(); - var owner = - new AccountGameplayAdmissionCommitConfirmationOwner( - receiptCommitDataSource( - applicationNamedDataSource(context.dataSource(), applicationName), - ReceiptCommitFault.NONE, - trace), - "test"); - - var receipt = - withV120WalCoverageCoordinator( - context, - applicationName, + tx( + context, + () -> + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordCommitted(original, decision)); + var before = operation(context, original).intoMap(); + migrate(context, null); + var after = operation(context, original).intoMap(); + for (var entry : before.entrySet()) + assertThat(after).containsEntry(entry.getKey(), entry.getValue()); + assertThat(after.get("finalization_xid")).isNull(); + assertThatThrownBy( () -> - callWithSyntheticReadPeer( - () -> owner.confirm(confirmationRequest(original, decision))), - AccountGameplayAdmissionCommitConfirmation::walInsertLsn); - - assertThat(trace.count("physical-commit")).isEqualTo(2); - assertThat(trace.count("v120-read")).isEqualTo(1); - var receiptCommit = firstEvent(trace, "physical-commit"); - var independentRead = firstEvent(trace, "v120-read"); - assertThat(trace.events().indexOf(receiptCommit)) - .isLessThan(trace.events().indexOf(independentRead)); - assertThat(independentRead.connectionId()).isNotEqualTo(receiptCommit.connectionId()); - assertThat(receipt.operation().evidence().canonicalJson()).isEqualTo(original.canonicalJson()); - assertThat(receipt.operation().evidence().sha256()).isEqualTo(original.sha256()); - assertThat(receipt.bindingDecisionId()).isEqualTo(decision); - assertThat(receipt.expiresAtMs()).isEqualTo(expiresAt(original)); - assertThat(receipt.committedBeforeMs()).isPositive().isLessThan(expiresAt(original)); - assertThat(receipt.confirmationXid()).isNotEqualTo(receipt.finalizationXid()); - assertThat(operation(context, original).get("finalization_xid", String.class)) - .isEqualTo(receipt.finalizationXid()); - assertThat( - context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) - .isEqualTo(1); - } - - @Test - void lostReceiptCommitAcknowledgementDeniesThenRecoversOnlyThroughIndependentV120Read() - throws Exception { - var context = context(null); - var original = pending(context, account(context)); - UUID decision = UUID.randomUUID(); - new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) - .execute(original, decision); - var trace = new ReceiptCommitTrace(); - var owner = - new AccountGameplayAdmissionCommitConfirmationOwner( - receiptCommitDataSource( - context.dataSource(), ReceiptCommitFault.AFTER_FIRST_COMMIT, trace), - "test"); - var request = confirmationRequest(original, decision); - - assertThatThrownBy(() -> syntheticReadPeer().call(() -> owner.confirm(request))) - .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - if (trace.count("physical-commit") != 1) describeLostReceiptCommitFailure(failure); - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE); - }); - assertThat(trace.count("physical-commit")).isEqualTo(1); - assertThat(trace.count("v120-read")).isZero(); - - var retainedRow = confirmationRow(context, original); - assertThat(retainedRow.get("request_id", UUID.class)).isEqualTo(requestId(original)); - assertThat(retainedRow.get("evidence_sha256", String.class)).isEqualTo(original.sha256()); - assertThat(retainedRow.get("binding_decision_id", UUID.class)).isEqualTo(decision); - assertThat(retainedRow.get("expires_at_ms", Long.class)).isEqualTo(expiresAt(original)); - assertThat(retainedRow.get("committed_before_ms", Long.class)) - .isPositive() - .isLessThan(expiresAt(original)); - assertThat(retainedRow.get("finalization_xid", String.class)) - .isEqualTo(operation(context, original).get("finalization_xid", String.class)); - assertThat(retainedRow.get("confirmation_xid", String.class)) - .isNotEqualTo(retainedRow.get("finalization_xid", String.class)); - - // Recovery is an explicit fresh owner read, which invokes the existing V120 independent WAL - // coverage observer. No confirm retry can mint or acknowledge the lost receipt COMMIT. - var recovered = syntheticReadPeer().call(() -> owner.read(request)); - assertThat(trace.count("v120-read")).isEqualTo(1); - var lostAckCommit = firstEvent(trace, "physical-commit"); - var independentRead = firstEvent(trace, "v120-read"); - assertThat(trace.events().indexOf(lostAckCommit)) - .isLessThan(trace.events().indexOf(independentRead)); - assertThat(independentRead.connectionId()).isNotEqualTo(lostAckCommit.connectionId()); - assertThat(recovered.requestId()).isEqualTo(retainedRow.get("request_id", UUID.class)); - assertThat(recovered.evidenceSha256()) - .isEqualTo(retainedRow.get("evidence_sha256", String.class)); - assertThat(recovered.bindingDecisionId()) - .isEqualTo(retainedRow.get("binding_decision_id", UUID.class)); - assertThat(recovered.expiresAtMs()).isEqualTo(retainedRow.get("expires_at_ms", Long.class)); - assertThat(recovered.committedBeforeMs()) - .isEqualTo(retainedRow.get("committed_before_ms", Long.class)); - assertThat(recovered.finalizationXid()) - .isEqualTo(retainedRow.get("finalization_xid", String.class)); - assertThat(recovered.confirmationXid()) - .isEqualTo(retainedRow.get("confirmation_xid", String.class)); - assertThat(confirmationRow(context, original).intoMap()).isEqualTo(retainedRow.intoMap()); - } - - @Test - void receiptCommitFailureOrPriorWalDenialRollsBackWithoutReceiptOrIndependentRead() { - var context = context(null); - var original = pending(context, account(context)); - UUID decision = UUID.randomUUID(); - new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) - .execute(original, decision); - var committedOperation = operation(context, original).intoMap(); - var unchanged = storageSnapshot(context); - var trace = new ReceiptCommitTrace(); - var owner = - new AccountGameplayAdmissionCommitConfirmationOwner( - receiptCommitDataSource( - context.dataSource(), ReceiptCommitFault.BEFORE_FIRST_COMMIT, trace), - "test"); - + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision)) + .hasMessageContaining("Fresh owned Account original COMMIT required"); assertThatThrownBy( () -> - syntheticReadPeer() - .call(() -> owner.confirm(confirmationRequest(original, decision)))) - .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE); - int commitAttempts = trace.count("commit-attempt"); - assertThat(commitAttempts).isBetween(0, 1); - if (commitAttempts == 0) assertGlobalWalCoverageFailure(failure); - else - assertCauseChainContainsMessage( - failure, "Test failed before physical receipt COMMIT"); - }); - assertThat(trace.count("physical-commit")).isZero(); - assertThat(trace.count("v120-read")).isZero(); + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.dataSource()) + .read(original, decision)) + .hasMessageContaining("Exact durable original Account acknowledgement receipt required"); + assertThat(operation(context, original).intoMap()).isEqualTo(after); assertThat( - context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + context + .dsl() + .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) .isZero(); - assertThat(operation(context, original).intoMap()).isEqualTo(committedOperation); - assertThat(storageSnapshot(context)).isEqualTo(unchanged); } @Test - void idlePrimaryConfirmationCapturesBeforeLocksAndIndependentlyReadsExactReceipt() { - var context = context(null); + void syntheticHistoricalV120RowSurvivesRetirementWithoutClaimingDurability() { + var context = context("135"); var original = pending(context, account(context)); - var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); - UUID decision = UUID.randomUUID(); - tx(context, () -> repository.recordCommitted(original, decision)); - var unchanged = storageSnapshot(context); - - String finalizationXid = operation(context, original).get("finalization_xid", String.class); - // No marker, forced flush or unrelated writer is used to make proof succeed. Establish a - // fixed snapshot before the call and prove the original finalizer is independently visible. - // Background WAL may advance, so a pre-call global LSN need not equal the stored fence. - var receipt = - tx( - context, - () -> { - assertThat( - Objects.requireNonNull( - context - .dsl() - .fetchOne( - "SELECT pg_visible_in_snapshot(?::xid8, pg_current_snapshot()) " - + "AND pg_current_xact_id_if_assigned() IS NULL AS independent", - finalizationXid)) - .get("independent", Boolean.class)) - .isTrue(); - String beforeHeapReads = - Objects.requireNonNull( - context.dsl().fetchOne("SELECT pg_current_wal_insert_lsn()::text AS lsn")) - .get("lsn", String.class); - var created = confirm(context, original, decision); - assertThat( - Objects.requireNonNull( - context - .dsl() - .fetchOne( - "SELECT ?::pg_lsn >= ?::pg_lsn " - + "AND ?::pg_lsn >= ?::pg_lsn AS snapshot_fence_covered", - created.get("wal_insert_lsn", String.class), - beforeHeapReads, - created.get("wal_flush_lsn", String.class), - created.get("wal_insert_lsn", String.class))) - .get("snapshot_fence_covered", Boolean.class)) - .isTrue(); - return created; - }); - - tx( - context, - () -> { - assertThat( - Objects.requireNonNull( - context - .dsl() - .fetchOne( - "SELECT pg_visible_in_snapshot(?::xid8, pg_current_snapshot()) " - + "AND pg_current_xact_id_if_assigned() IS NULL AS independent", - receipt.get("confirmation_xid", String.class))) - .get("independent", Boolean.class)) - .isTrue(); - assertThat(readConfirmation(context, original, decision)).isEqualTo(receipt); - return null; - }); - assertThat(storageSnapshot(context)).isEqualTo(unchanged); - } - - @Test - void staleSerializableConfirmationInsertRetriesInsteadOfLeakingUniqueViolation() - throws Exception { - var context = context(null); - var original = pending(context, account(context)); - var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); - UUID decision = UUID.randomUUID(); - tx(context, () -> repository.recordCommitted(original, decision)); - var unchanged = storageSnapshot(context); - var snapshotReady = new CountDownLatch(1); - var winnerCommitted = new CountDownLatch(1); - try (var executor = Executors.newSingleThreadExecutor()) { - var stale = - executor.submit( - () -> - tx( - context, - () -> { - assertThat( - context - .dsl() - .fetchCount( - DSL.table( - "account_gameplay_admission_commit_confirmations"))) - .isZero(); - snapshotReady.countDown(); - try { - if (!winnerCommitted.await(10, TimeUnit.SECONDS)) - throw new IllegalStateException("winner commit timeout"); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - return confirm(context, original, decision); - })); - Record retained; - try { - assertThat(snapshotReady.await(10, TimeUnit.SECONDS)).isTrue(); - retained = tx(context, () -> confirm(context, original, decision)); - } finally { - winnerCommitted.countDown(); - } - assertThatThrownBy(() -> stale.get(30, TimeUnit.SECONDS)) - .satisfies( - failure -> { - Throwable cause = failure; - while (cause != null && !(cause instanceof java.sql.SQLException)) - cause = cause.getCause(); - assertThat(cause).isInstanceOf(java.sql.SQLException.class); - assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("40001"); - }); - assertThat(tx(context, () -> confirm(context, original, decision))).isEqualTo(retained); - // This case proves serialization and exact retained storage, not the distinct V120 WAL - // durability observation. Dedicated independent-read/receipt-COMMIT cases cover that gate; - // a global insert-frontier denial remains an open durability limitation, never a bypass. - assertThat(tx(context, () -> confirmationRow(context, original)).intoMap()) - .isEqualTo(retained.intoMap()); - } - assertThat( - context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) - .isEqualTo(1); - assertThat(storageSnapshot(context)).isEqualTo(unchanged); - } - - @Test - void updateBeforeExpiryButPhysicalCommitAfterExpiryCannotCreateConfirmation() { - var context = context(null); - var original = pending(context, account(context), 1000); - var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); UUID decision = UUID.randomUUID(); + var ack = + new AccountGameplayAdmissionOriginalCommitExecutor(context.dataSource()) + .execute(original, decision); + var beforeSources = storageSnapshot(context); + var beforeChecksums = flywayChecksums(context); + var beforeDefinitions = retainedAdmissionDefinitions(context); + // Explicit synthetic history fixture only: this bypass cannot prove temporal or WAL durability. + // Restore the existing guard in this same transaction before any upgrade or genuine proof. tx( context, () -> { - repository.recordCommitted(original, decision); - assertThat(databaseNow(context)).isLessThan(expiresAt(original)); - waitPastDeadline(context, original); + context + .dsl() + .execute( + "ALTER TABLE account_gameplay_admission_commit_confirmations DISABLE TRIGGER account_admission_confirmation_guard"); + context + .dsl() + .execute( + "INSERT INTO account_gameplay_admission_commit_confirmations(confirmation_version, request_id, account_uuid, lease_id, lease_fence, evidence_sha256, binding_decision_id, expires_at_ms, finalization_xid, wal_insert_lsn, wal_flush_lsn, committed_before_ms, confirmation_xid) SELECT 1, request_id, account_uuid, lease_id, lease_fence, evidence_sha256, binding_decision_id, expires_at_ms, finalization_xid, '0/1', '0/1', ?, pg_current_xact_id()::text FROM account_gameplay_admission_lease_operations WHERE request_id = ?", + ack.committedBeforeMs(), + requestId(original)); + context + .dsl() + .execute( + "ALTER TABLE account_gameplay_admission_commit_confirmations ENABLE TRIGGER account_admission_confirmation_guard"); + // A visible synthetic row in its own transaction remains unusable as independent proof. + context.dsl().execute("SAVEPOINT synthetic_history_read"); + assertThatThrownBy( + () -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_read_commit_confirmation(?, ?, ?)", + requestId(original), + original.sha256(), + decision)) + .hasMessageContaining("requires independent receipt commit"); + context.dsl().execute("ROLLBACK TO SAVEPOINT synthetic_history_read"); + context.dsl().execute("RELEASE SAVEPOINT synthetic_history_read"); return null; }); - assertThat(operation(context, original).get("status", String.class)).isEqualTo("COMMITTED"); - assertThat(operation(context, original).get("finalization_xid", String.class)).isNotNull(); - var unchanged = storageSnapshot(context); - assertThatThrownBy(() -> tx(context, () -> confirm(context, original, decision))) - .hasMessageContaining("original deadline expired"); - assertThatThrownBy(() -> tx(context, () -> readConfirmation(context, original, decision))) - .hasMessageContaining("exact durable receipt required"); - assertThat( - context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) - .isZero(); - assertThat(storageSnapshot(context)).isEqualTo(unchanged); - } - - @Test - void sameTransactionAndReleasedSubtransactionCannotConfirmOriginalFinalization() { - var context = context(null); - UUID account = account(context); - var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); - for (boolean subtransaction : List.of(false, true)) { - var original = pending(context, account); - UUID decision = UUID.randomUUID(); - tx( - context, - () -> { - if (subtransaction) context.dsl().execute("SAVEPOINT original_finalization"); - repository.recordCommitted(original, decision); - if (subtransaction) context.dsl().execute("RELEASE SAVEPOINT original_finalization"); - var stamp = operation(context, original).get("finalization_xid", String.class); - assertThat(stamp) - .isEqualTo( - Objects.requireNonNull( - context.dsl().fetchOne("SELECT pg_current_xact_id()::text AS xid")) - .get("xid", String.class)); - assertDeniedInSavepoint( - context, - () -> confirm(context, original, decision), - "requires independent finalization commit"); - assertDeniedInSavepoint( - context, - () -> - context - .dsl() - .execute( - "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) VALUES (?, ?, ?)", - requestId(original), - original.sha256(), - decision), - "requires independent finalization commit"); - return null; - }); - } - assertThat( - context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) - .isZero(); - } - - @Test - void missingPendingRolledBackAbortedAndRetainedUnstampedCommitsStayUnproved() { - var context = context("119"); - UUID account = account(context); - var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); - var retained = pending(context, account); - UUID decision = UUID.randomUUID(); - tx(context, () -> repository.recordCommitted(retained, decision)); - var retainedPending = pending(context, account); - var aborted = pending(context, account); - tx(context, () -> repository.recordAborted(aborted, null, UUID.randomUUID())); + var retained = + context + .dsl() + .fetchSingle("SELECT * FROM account_gameplay_admission_commit_confirmations") + .intoMap(); migrate(context, null); - assertThat(operation(context, retained).get("finalization_xid", String.class)).isNull(); - assertThat(operation(context, retainedPending).get("finalization_xid", String.class)).isNull(); - assertThat(operation(context, aborted).get("finalization_xid", String.class)).isNull(); - var rolledBack = pending(context, account); - assertThatThrownBy( - () -> - tx( - context, - () -> { - repository.recordCommitted(rolledBack, decision); - throw new IllegalStateException("roll back physical finalization"); - })) - .hasMessageContaining("roll back physical finalization"); - assertThat(operation(context, rolledBack).get("status", String.class)).isEqualTo("PENDING"); - assertThat(operation(context, rolledBack).get("finalization_xid", String.class)).isNull(); - var unchanged = storageSnapshot(context); - for (var unproved : List.of(retained, retainedPending, aborted, rolledBack)) { - assertThatThrownBy(() -> tx(context, () -> confirm(context, unproved, decision))) - .hasMessageContaining("exact committed binding required"); - assertThatThrownBy(() -> tx(context, () -> readConfirmation(context, unproved, decision))) - .hasMessageContaining("exact durable receipt required"); - } - assertThatThrownBy( - () -> - tx( - context, - () -> - context - .dsl() - .fetchOne( - "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", - UUID.randomUUID(), - retained.sha256(), - decision))) - .hasMessageContaining("operation missing"); assertThat( - context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) - .isZero(); - assertThat(storageSnapshot(context)).isEqualTo(unchanged); - } - - @Test - void confirmationRejectsChangedBindingsAndCallerProofAndRemainsImmutable() { - var context = context(null); - UUID account = account(context); - var original = pending(context, account); - var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); - UUID decision = UUID.randomUUID(); - UUID request = requestId(original); - assertThatThrownBy( - () -> - tx( - context, - () -> - context - .dsl() - .execute( - "UPDATE account_gameplay_admission_lease_operations SET status = 'COMMITTED', binding_decision_id = ?, finalization_xid = '1' WHERE request_id = ?", - decision, - request))) - .hasMessageContaining("finalization transaction is database stamped"); - tx(context, () -> repository.recordCommitted(original, decision)); - var unchanged = storageSnapshot(context); - // SQL owns the transaction prerequisite even for callers bypassing the Java owner. - for (int isolation : - List.of( - TransactionDefinition.ISOLATION_READ_COMMITTED, - TransactionDefinition.ISOLATION_REPEATABLE_READ)) { - var unsupported = - new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); - unsupported.setIsolationLevel(isolation); - for (Supplier action : - List.>of( - () -> confirm(context, original, decision), - () -> readConfirmation(context, original, decision), - () -> - context - .dsl() - .execute( - "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) VALUES (?, ?, ?)", - request, - original.sha256(), - decision))) { - assertThatThrownBy(() -> unsupported.execute(status -> action.get())) - .hasMessageContaining("writable SERIALIZABLE transaction required"); - } - } - var readOnly = new TransactionTemplate(new DataSourceTransactionManager(context.dataSource())); - readOnly.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - readOnly.setReadOnly(true); - assertThatThrownBy( - () -> readOnly.execute(status -> readConfirmation(context, original, decision))) - .hasMessageContaining("writable SERIALIZABLE transaction required"); - assertThatThrownBy(() -> readOnly.execute(status -> confirm(context, original, decision))) - .hasMessageContaining("read-only transaction"); - assertThatThrownBy( - () -> - tx( - context, - () -> - context - .dsl() - .fetchOne( - "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", - request, - "b".repeat(64), - decision))) - .hasMessageContaining("exact committed binding required"); - assertThatThrownBy(() -> tx(context, () -> confirm(context, original, UUID.randomUUID()))) - .hasMessageContaining("exact committed binding required"); - // Every proof/identity field is database-derived even if supplied values look plausible. - for (String assignment : + context + .dsl() + .fetchSingle("SELECT * FROM account_gameplay_admission_commit_confirmations") + .intoMap()) + .isEqualTo(retained); + assertThat(storageSnapshot(context)).isEqualTo(beforeSources); + assertThat(retainedAdmissionDefinitions(context)).isEqualTo(beforeDefinitions); + for (var entry : beforeChecksums.entrySet()) + assertThat(flywayChecksums(context)).containsEntry(entry.getKey(), entry.getValue()); + assertThat(flywayChecksums(context)).containsKey("136"); + for (String sql : List.of( - "account_uuid = '" + account + "'::uuid", - "lease_id = '" + original.carrier().get("leaseId") + "'::uuid", - "lease_fence = 1", - "expires_at_ms = " + expiresAt(original), - "finalization_xid = '1'", - "wal_insert_lsn = '0/1'", - "wal_flush_lsn = '0/1'", - "committed_before_ms = 1", - "confirmation_xid = '1'")) { - String[] fieldAndValue = assignment.split(" = ", 2); + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) VALUES (?, ?, ?)", + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) VALUES (?, ?, ?) ON CONFLICT (request_id) DO NOTHING")) { assertThatThrownBy( () -> tx( @@ -1651,33 +1143,18 @@ void confirmationRejectsChangedBindingsAndCallerProofAndRemainsImmutable() { () -> context .dsl() - .execute( - "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id, " - + fieldAndValue[0] - + ") VALUES (?, ?, ?, " - + fieldAndValue[1] - + ")", - request, - original.sha256(), - decision))) - .hasMessageContaining("proof is database derived"); + .execute(sql, requestId(original), original.sha256(), decision))) + .hasMessageContaining("confirmation writes are retired"); } - var receipt = tx(context, () -> confirm(context, original, decision)); for (String mutation : List.of( "UPDATE account_gameplay_admission_commit_confirmations SET committed_before_ms = 1", - "UPDATE account_gameplay_admission_commit_confirmations SET expires_at_ms = expires_at_ms + 1", - "UPDATE account_gameplay_admission_commit_confirmations SET evidence_sha256 = '" - + "b".repeat(64) - + "'", "DELETE FROM account_gameplay_admission_commit_confirmations", "TRUNCATE account_gameplay_admission_commit_confirmations")) { assertThatThrownBy(() -> tx(context, () -> context.dsl().execute(mutation))) .hasMessageContaining("confirmation is immutable"); } - assertThatThrownBy( - () -> tx(context, () -> readConfirmation(context, original, UUID.randomUUID()))) - .hasMessageContaining("exact durable receipt required"); + // Historical lookup remains present and still rejects an unverifiable exact binding. assertThatThrownBy( () -> tx( @@ -1685,124 +1162,51 @@ void confirmationRejectsChangedBindingsAndCallerProofAndRemainsImmutable() { () -> context .dsl() - .execute( - "UPDATE account_gameplay_admission_lease_operations SET finalization_xid = '1' WHERE request_id = ?", - request))) - .hasMessageContaining("finalization transaction is database stamped"); - assertThat(tx(context, () -> readConfirmation(context, original, decision))).isEqualTo(receipt); - assertThat(storageSnapshot(context)).isEqualTo(unchanged); - } - - @Test - void sameTransactionReceiptReadAndRolledBackConfirmationCannotProveDurability() { - var context = context(null); - var original = pending(context, account(context)); - var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); - UUID decision = UUID.randomUUID(); - tx(context, () -> repository.recordCommitted(original, decision)); - createV120WalCoverageMarkerTable(context); - for (boolean subtransaction : List.of(false, true)) { - assertThatThrownBy( - () -> - tx( - context, - () -> { - if (subtransaction) context.dsl().execute("SAVEPOINT receipt_creation"); - String applicationName = v120ApplicationName(); - var receipt = - withV120WalCoverageCoordinator( - context, - applicationName, - () -> { - setLocalApplicationName(context.dsl(), applicationName); - return confirm(context, original, decision); - }, - row -> row.get("wal_insert_lsn", String.class)); - assertThat(receipt.get("committed_before_ms", Long.class)) - .isPositive() - .isLessThan(expiresAt(original)); - assertThat(receipt.get("expires_at_ms", Long.class)) - .isEqualTo(expiresAt(original)); - if (subtransaction) - context.dsl().execute("RELEASE SAVEPOINT receipt_creation"); - assertDeniedInSavepoint( - context, - () -> readConfirmation(context, original, decision), - "requires independent receipt commit"); - throw new IllegalStateException("roll back confirmation commit"); - })) - .hasMessageContaining("roll back confirmation commit"); - } - assertThat( - context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) - .isZero(); - assertThatThrownBy(() -> tx(context, () -> readConfirmation(context, original, decision))) + .fetch( + "SELECT * FROM account_gameplay_admission_read_commit_confirmation(?, ?, ?)", + requestId(original), + "b".repeat(64), + decision))) .hasMessageContaining("exact durable receipt required"); - var receipt = - tx( - context, - () -> { - String applicationName = v120ApplicationName(); - return withV120WalCoverageCoordinator( - context, - applicationName, - () -> { - setLocalApplicationName(context.dsl(), applicationName); - return confirm(context, original, decision); - }, - row -> row.get("wal_insert_lsn", String.class)); - }); - assertThat(tx(context, () -> readConfirmation(context, original, decision))).isEqualTo(receipt); + assertThat( + context + .dsl() + .fetchSingle("SELECT * FROM account_gameplay_admission_commit_confirmations") + .intoMap()) + .isEqualTo(retained); } - @Test - void concurrentConfirmationsRetainOneOriginalReceiptWithoutAdvancingSources() throws Exception { - var context = context(null); - var original = pending(context, account(context)); - var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); - UUID decision = UUID.randomUUID(); - tx(context, () -> repository.recordCommitted(original, decision)); - var unchanged = storageSnapshot(context); - var start = new CountDownLatch(1); - Callable duplicate = - () -> { - if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); - return retrySerialization(() -> tx(context, () -> confirm(context, original, decision))); - }; - try (var executor = Executors.newFixedThreadPool(2)) { - var left = executor.submit(duplicate); - var right = executor.submit(duplicate); - start.countDown(); - assertThat(left.get(30, TimeUnit.SECONDS)).isEqualTo(right.get(30, TimeUnit.SECONDS)); - } - assertThat( - context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) - .isEqualTo(1); - var retained = tx(context, () -> confirm(context, original, decision)); - waitPastDeadline(context, original); - assertThat( - tx( - context, - () -> - context - .dsl() - .execute( - "INSERT INTO account_gameplay_admission_commit_confirmations(request_id, evidence_sha256, binding_decision_id) VALUES (?, ?, ?) ON CONFLICT (request_id) DO NOTHING", - requestId(original), - original.sha256(), - decision))) - .isZero(); - // Both duplicates enter the INSERT guard but replay the expired retained receipt without - // taking fresh temporal proof, restamping its bound or allocating replacement evidence. - try (var executor = Executors.newFixedThreadPool(2)) { - var left = executor.submit(duplicate); - var right = executor.submit(duplicate); - assertThat(left.get(30, TimeUnit.SECONDS)).isEqualTo(retained); - assertThat(right.get(30, TimeUnit.SECONDS)).isEqualTo(retained); + private static Map retainedAdmissionDefinitions(Context context) { + Map definitions = new LinkedHashMap<>(); + for (String signature : + List.of( + "account_gameplay_admission_storage_guard()", + "account_gameplay_admission_confirmation_guard()", + "account_gameplay_admission_read_commit_confirmation(uuid,text,uuid)", + "account_gameplay_admission_original_ack_receipt_guard()", + "account_gameplay_admission_read_original_ack_receipt_durably(uuid,text,uuid)")) { + definitions.put( + signature, + context + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef(?::regprocedure)", context.schema() + "." + signature) + .get(0, String.class)); } - assertThat(tx(context, () -> readConfirmation(context, original, decision))) - .isEqualTo(retained); - assertThat(storageSnapshot(context)).isEqualTo(unchanged); + definitions.put( + "triggers", + context + .dsl() + .fetch( + "SELECT tgname, tgenabled, pg_get_triggerdef(oid) FROM pg_trigger WHERE tgrelid IN ('" + + context.schema() + + ".account_gameplay_admission_commit_confirmations'::regclass, '" + + context.schema() + + ".account_gameplay_admission_lease_operations'::regclass, '" + + context.schema() + + ".account_gameplay_admission_original_commit_ack_receipts'::regclass) AND NOT tgisinternal AND tgname <> 'account_admission_confirmation_00_retired_insert' ORDER BY tgname") + .formatJSON()); + return definitions; } @Test @@ -2367,429 +1771,6 @@ void concurrentOriginalAckReceiptRecoveriesRetainExactProofBeforeAndAfterExpiry( assertThat(storageSnapshot(context)).isEqualTo(sourcesBeforeRecovery); } - private static Record confirm( - Context context, AccountGameplayAdmissionLeaseEvidence original, UUID decision) { - return Objects.requireNonNull( - context - .dsl() - .fetchOne( - "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", - requestId(original), - original.sha256(), - decision)); - } - - private static T withV120WalCoverageCoordinator( - Context context, - String applicationName, - Supplier confirmation, - Function insertFence) { - var actionFinished = new AtomicBoolean(); - var coordinatorLock = new Object(); - var monitorReady = new CountDownLatch(1); - var coordinatorConnection = new AtomicReference(); - ExecutorService executor = - Executors.newSingleThreadExecutor( - task -> { - Thread thread = new Thread(task, "account-v120-wal-coordinator-" + applicationName); - thread.setDaemon(true); - return thread; - }); - Future future = - executor.submit( - () -> - observeV120WalCoverage( - context, - applicationName, - actionFinished, - coordinatorLock, - monitorReady, - coordinatorConnection)); - - T result = null; - Throwable actionFailure = null; - try { - if (!monitorReady.await(2, TimeUnit.SECONDS)) { - actionFailure = - new IllegalStateException( - "Account V120 WAL coverage coordinator could not open its observation connection"); - } else { - result = confirmation.get(); - } - } catch (InterruptedException failure) { - Thread.currentThread().interrupt(); - actionFailure = new IllegalStateException("Interrupted before Account confirmation", failure); - } catch (RuntimeException | Error failure) { - actionFailure = failure; - } finally { - synchronized (coordinatorLock) { - actionFinished.set(true); - } - } - - executor.shutdown(); - V120WalCoverageObservation observation = null; - Throwable coordinatorFailure = null; - try { - observation = future.get(2, TimeUnit.SECONDS); - } catch (ExecutionException failure) { - coordinatorFailure = failure.getCause(); - } catch (TimeoutException failure) { - coordinatorFailure = failure; - future.cancel(true); - executor.shutdownNow(); - closeCoordinatorConnection(coordinatorConnection, coordinatorFailure); - } catch (InterruptedException failure) { - Thread.currentThread().interrupt(); - coordinatorFailure = failure; - future.cancel(true); - executor.shutdownNow(); - closeCoordinatorConnection(coordinatorConnection, coordinatorFailure); - } - - try { - if (!executor.awaitTermination(2, TimeUnit.SECONDS)) { - executor.shutdownNow(); - var cleanupFailure = - new IllegalStateException("Account V120 WAL coverage coordinator did not terminate"); - closeCoordinatorConnection(coordinatorConnection, cleanupFailure); - if (!executor.awaitTermination(2, TimeUnit.SECONDS)) { - if (coordinatorFailure == null) coordinatorFailure = cleanupFailure; - else coordinatorFailure.addSuppressed(cleanupFailure); - } - } - } catch (InterruptedException failure) { - Thread.currentThread().interrupt(); - executor.shutdownNow(); - if (coordinatorFailure == null) coordinatorFailure = failure; - else coordinatorFailure.addSuppressed(failure); - closeCoordinatorConnection(coordinatorConnection, coordinatorFailure); - } - - if (actionFailure != null) { - if (coordinatorFailure != null) actionFailure.addSuppressed(coordinatorFailure); - actionFailure.addSuppressed( - new IllegalStateException( - describeV120WalCoordinatorOutcome(applicationName, observation))); - if (actionFailure instanceof RuntimeException runtimeFailure) throw runtimeFailure; - throw (Error) actionFailure; - } - - if (coordinatorFailure != null) { - throw new IllegalStateException( - "Account V120 confirmation succeeded, but its bounded WAL coordinator failed", - coordinatorFailure); - } - if (observation != null && observation.marker() != null) { - String fence = Objects.requireNonNull(insertFence.apply(result)); - Boolean covered = - Objects.requireNonNull( - context - .dsl() - .fetchOne( - "SELECT ?::pg_lsn >= ?::pg_lsn AS covered", - observation.marker().flushLsn(), - fence)) - .get("covered", Boolean.class); - assertThat(covered) - .as( - "independent marker COMMIT flush covers V120 fence %s from backend %s", - fence, observation.backendPid()) - .isTrue(); - } - return result; - } - - private static V120WalCoverageObservation observeV120WalCoverage( - Context context, - String applicationName, - AtomicBoolean actionFinished, - Object coordinatorLock, - CountDownLatch monitorReady, - AtomicReference coordinatorConnection) - throws SQLException { - Integer backendPid = null; - String lastWaitEventType = null; - String lastWaitEvent = null; - long deadline = - System.nanoTime() + TimeUnit.SECONDS.toNanos(V120_WAL_COORDINATOR_TIMEOUT_SECONDS); - try (Connection connection = context.dataSource().getConnection(); - PreparedStatement activity = - connection.prepareStatement( - "SELECT pid, wait_event_type, wait_event FROM pg_stat_activity " - + "WHERE application_name = ? AND state = 'active' " - + "AND strpos(query, 'account_gameplay_admission_confirm_committed') > 0 " - + "AND (?::integer IS NULL OR pid = ?)")) { - coordinatorConnection.set(connection); - activity.setQueryTimeout(1); - monitorReady.countDown(); - while (System.nanoTime() < deadline) { - activity.setString(1, applicationName); - if (backendPid == null) { - activity.setNull(2, java.sql.Types.INTEGER); - activity.setNull(3, java.sql.Types.INTEGER); - } else { - activity.setInt(2, backendPid); - activity.setInt(3, backendPid); - } - try (ResultSet rows = activity.executeQuery()) { - if (rows.next()) { - int currentPid = rows.getInt("pid"); - if (backendPid != null && backendPid != currentPid) { - throw new SQLException( - "Account V120 confirmation backend changed during WAL coordination"); - } - backendPid = currentPid; - lastWaitEventType = rows.getString("wait_event_type"); - lastWaitEvent = rows.getString("wait_event"); - if (rows.next()) { - throw new SQLException( - "Multiple Account V120 confirmation backends matched unique application name"); - } - if ("Timeout".equals(lastWaitEventType) && "PgSleep".equals(lastWaitEvent)) { - synchronized (coordinatorLock) { - if (actionFinished.get()) { - return new V120WalCoverageObservation( - backendPid, lastWaitEventType, lastWaitEvent, null, false); - } - connection.close(); - coordinatorConnection.compareAndSet(connection, null); - V120WalCoverageMarker marker = - commitV120WalCoverageMarker(context, coordinatorConnection); - return new V120WalCoverageObservation( - backendPid, lastWaitEventType, lastWaitEvent, marker, false); - } - } - } - } - synchronized (coordinatorLock) { - if (actionFinished.get()) { - return new V120WalCoverageObservation( - backendPid, lastWaitEventType, lastWaitEvent, null, false); - } - } - Thread.yield(); - } - return new V120WalCoverageObservation( - backendPid, lastWaitEventType, lastWaitEvent, null, true); - } finally { - monitorReady.countDown(); - } - } - - private static V120WalCoverageMarker commitV120WalCoverageMarker( - Context context, AtomicReference coordinatorConnection) throws SQLException { - UUID markerId = UUID.randomUUID(); - String markerValue = UUID.randomUUID().toString(); - int writerBackendPid; - try (Connection writer = context.dataSource().getConnection()) { - coordinatorConnection.set(writer); - writer.setAutoCommit(false); - try { - try (Statement statement = writer.createStatement()) { - statement.setQueryTimeout(1); - statement.execute("SET LOCAL synchronous_commit = on"); - try (ResultSet settings = - statement.executeQuery( - "SELECT pg_backend_pid(), current_setting('synchronous_commit')")) { - if (!settings.next() || !"on".equals(settings.getString(2))) { - throw new SQLException( - "Account V120 marker writer did not retain synchronous COMMIT"); - } - writerBackendPid = settings.getInt(1); - if (settings.next()) { - throw new SQLException( - "Account V120 marker writer settings query returned multiple rows"); - } - } - } - try (PreparedStatement insert = - writer.prepareStatement( - "INSERT INTO " - + V120_WAL_MARKER_TABLE - + " (marker_id, marker_value) VALUES (?, ?)")) { - insert.setQueryTimeout(1); - insert.setObject(1, markerId); - insert.setString(2, markerValue); - if (insert.executeUpdate() != 1) { - throw new SQLException("Account V120 marker INSERT did not write exactly one row"); - } - } - writer.commit(); - } catch (SQLException | RuntimeException | Error failure) { - try { - writer.rollback(); - } catch (SQLException rollbackFailure) { - failure.addSuppressed(rollbackFailure); - } - throw failure; - } finally { - coordinatorConnection.compareAndSet(writer, null); - } - } - - int readerBackendPid; - try (Connection reader = context.dataSource().getConnection(); - PreparedStatement readback = - reader.prepareStatement( - "SELECT marker_value, pg_backend_pid() FROM " - + V120_WAL_MARKER_TABLE - + " WHERE marker_id = ?")) { - coordinatorConnection.set(reader); - readback.setQueryTimeout(1); - readback.setObject(1, markerId); - try (ResultSet row = readback.executeQuery()) { - if (!row.next() || !markerValue.equals(row.getString(1))) { - throw new SQLException( - "Committed Account V120 WAL marker was not independently readable"); - } - readerBackendPid = row.getInt(2); - if (readerBackendPid == writerBackendPid || row.next()) { - throw new SQLException("Account V120 WAL marker readback was not exact and independent"); - } - } - String flushLsn; - try (Statement statement = reader.createStatement()) { - statement.setQueryTimeout(1); - try (ResultSet result = statement.executeQuery("SELECT pg_current_wal_flush_lsn()::text")) { - if (!result.next()) - throw new SQLException("Account V120 marker flush location unavailable"); - flushLsn = result.getString(1); - } - } - return new V120WalCoverageMarker(flushLsn); - } finally { - coordinatorConnection.set(null); - } - } - - private static void createV120WalCoverageMarkerTable(Context context) { - context - .dsl() - .execute( - "CREATE TABLE " - + V120_WAL_MARKER_TABLE - + " (marker_id UUID PRIMARY KEY, marker_value TEXT NOT NULL)"); - } - - private static DataSource applicationNamedDataSource(DataSource source, String applicationName) { - return new DelegatingDataSource(source) { - @Override - public Connection getConnection() throws SQLException { - return setApplicationName(super.getConnection(), applicationName); - } - - @Override - public Connection getConnection(String username, String password) throws SQLException { - return setApplicationName(super.getConnection(username, password), applicationName); - } - }; - } - - private static Connection setApplicationName(Connection connection, String applicationName) - throws SQLException { - try (PreparedStatement statement = - connection.prepareStatement("SELECT set_config('application_name', ?, false)")) { - statement.setString(1, applicationName); - try (ResultSet result = statement.executeQuery()) { - if (!result.next() || !applicationName.equals(result.getString(1)) || result.next()) { - throw new SQLException("Account V120 application name could not be verified"); - } - return connection; - } - } catch (SQLException failure) { - try { - connection.close(); - } catch (SQLException closeFailure) { - failure.addSuppressed(closeFailure); - } - throw failure; - } - } - - private static void setLocalApplicationName(DSLContext dsl, String applicationName) { - String configured = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT set_config('application_name', ?, true) AS application_name", - applicationName)) - .get("application_name", String.class); - assertThat(configured).isEqualTo(applicationName); - } - - private static String v120ApplicationName() { - return "account-v120-" + UUID.randomUUID().toString().replace("-", ""); - } - - private static T callWithSyntheticReadPeer(Callable action) { - try { - return syntheticReadPeer().call(action); - } catch (RuntimeException | Error failure) { - throw failure; - } catch (Exception failure) { - throw new IllegalStateException("Synthetic Account confirmation call failed", failure); - } - } - - private static String describeV120WalCoordinatorOutcome( - String applicationName, V120WalCoverageObservation observation) { - if (observation == null) { - return "Account V120 coordinator produced no observation for application_name=" - + applicationName; - } - return "Account V120 coordinator outcome" - + ": application_name=" - + applicationName - + " backend_pid=" - + observation.backendPid() - + " last_wait_event_type=" - + observation.waitEventType() - + " last_wait_event=" - + observation.waitEvent() - + " timed_out=" - + observation.timedOut() - + " marker_independently_read=" - + (observation.marker() != null); - } - - private static void closeCoordinatorConnection( - AtomicReference connectionReference, Throwable failure) { - Connection connection = connectionReference.getAndSet(null); - if (connection == null) return; - try { - connection.close(); - } catch (SQLException closeFailure) { - failure.addSuppressed(closeFailure); - } - } - - private record V120WalCoverageMarker(String flushLsn) {} - - private record V120WalCoverageObservation( - Integer backendPid, - String waitEventType, - String waitEvent, - V120WalCoverageMarker marker, - boolean timedOut) {} - - private static FinalizeGameplayAdmissionLeaseRequest confirmationRequest( - AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) { - return FinalizeGameplayAdmissionLeaseRequest.newBuilder() - .setLease(AccountGameplayAdmissionLeaseWireCodec.encodeReference(evidence)) - .setBindingDecisionId(decision.toString()) - .build(); - } - - private static Record confirmationRow( - Context context, AccountGameplayAdmissionLeaseEvidence original) { - return Objects.requireNonNull( - context - .dsl() - .fetchOne( - "SELECT * FROM account_gameplay_admission_commit_confirmations WHERE request_id = ?", - requestId(original))); - } - private static Record originalAckReceiptRow( Context context, AccountGameplayAdmissionLeaseEvidence original) { return Objects.requireNonNull( @@ -2827,59 +1808,6 @@ private synchronized List events() { } } - /** Traces only JDBC work performed by the real receipt owner over the supplied PostgreSQL DS. */ - private static DataSource receiptCommitDataSource( - DataSource source, ReceiptCommitFault fault, ReceiptCommitTrace trace) { - return new DelegatingDataSource(source) { - @Override - public Connection getConnection() throws SQLException { - return tracedConnection(super.getConnection()); - } - - @Override - public Connection getConnection(String username, String password) throws SQLException { - return tracedConnection(super.getConnection(username, password)); - } - - private Connection tracedConnection(Connection physical) { - int connectionId = trace.connectionIds.incrementAndGet(); - return (Connection) - Proxy.newProxyInstance( - Connection.class.getClassLoader(), - new Class[] {Connection.class}, - (proxy, method, arguments) -> { - if (method.getName().equals("commit") && method.getParameterCount() == 0) { - int attempt = trace.commitAttempts.incrementAndGet(); - if (attempt == 1 && fault == ReceiptCommitFault.BEFORE_FIRST_COMMIT) { - trace.record("commit-attempt", connectionId); - throw new SQLException("Test failed before physical receipt COMMIT", "08006"); - } - physical.commit(); - trace.record("physical-commit", connectionId); - if (attempt == 1 && fault == ReceiptCommitFault.AFTER_FIRST_COMMIT) - throw new SQLException("Test lost physical receipt COMMIT response", "08006"); - return null; - } - try { - Object result = method.invoke(physical, arguments); - if (result instanceof PreparedStatement statement) { - String sql = ""; - if (arguments != null - && arguments.length > 0 - && arguments[0] instanceof String statementSql) { - sql = statementSql; - } - return tracedStatement(statement, sql, connectionId, trace); - } - return result; - } catch (InvocationTargetException failure) { - throw failure.getCause(); - } - }); - } - }; - } - /** * Traces real original/receipt JDBC commits and ensures the exact read follows receipt COMMIT. */ @@ -2994,28 +1922,6 @@ private static PreparedStatement originalAckReceiptStatement( }); } - private static PreparedStatement tracedStatement( - PreparedStatement physical, String sql, int connectionId, ReceiptCommitTrace trace) { - return (PreparedStatement) - Proxy.newProxyInstance( - PreparedStatement.class.getClassLoader(), - new Class[] {PreparedStatement.class}, - (proxy, method, arguments) -> { - if (method.getName().startsWith("execute") && isV120IndependentRead(sql)) - trace.record("v120-read", connectionId); - try { - return method.invoke(physical, arguments); - } catch (InvocationTargetException failure) { - throw failure.getCause(); - } - }); - } - - private static boolean isV120IndependentRead(String sql) { - return sql.toLowerCase(java.util.Locale.ROOT) - .contains("account_gameplay_admission_read_commit_confirmation"); - } - private static ReceiptCommitEvent firstEvent(ReceiptCommitTrace trace, String kind) { return trace.events().stream() .filter(event -> event.kind().equals(kind)) @@ -3023,58 +1929,6 @@ private static ReceiptCommitEvent firstEvent(ReceiptCommitTrace trace, String ki .orElseThrow(() -> new AssertionError("Missing receipt JDBC event: " + kind)); } - private static void describeLostReceiptCommitFailure(Throwable failure) { - try { - var causeTypes = new ArrayList(); - var postgresDetails = new ArrayList(); - var visited = - java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); - Throwable cause = failure; - while (cause != null && visited.add(cause) && causeTypes.size() < 12) { - causeTypes.add(cause.getClass().getSimpleName()); - if (cause instanceof PSQLException postgresFailure) { - var error = postgresFailure.getServerErrorMessage(); - postgresDetails.add( - "SQLSTATE=" - + postgresFailure.getSQLState() - + " constraint=" - + (error == null - ? "" - : Objects.toString(error.getConstraint(), ""))); - } - cause = cause.getCause(); - } - System.err.printf( - "Lost receipt COMMIT diagnostic: causeTypes=%s postgres=%s%n", - causeTypes, postgresDetails); - } catch (Throwable diagnosticFailure) { - System.err.println( - "Lost receipt COMMIT diagnostic unavailable: " - + diagnosticFailure.getClass().getSimpleName()); - } - } - - private static void assertGlobalWalCoverageFailure(Throwable failure) { - Throwable cause = failure; - while (cause != null) { - var serverError = - cause instanceof PSQLException postgresFailure - ? postgresFailure.getServerErrorMessage() - : null; - if (cause instanceof PSQLException postgresFailure - && serverError != null - && "account_admission_confirmation_wal_coverage".equals(serverError.getConstraint())) { - assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); - assertThat(postgresFailure.getMessage()) - .contains("Account admission confirmation WAL coverage unavailable"); - return; - } - cause = cause.getCause(); - } - throw new AssertionError( - "Expected the retained Account admission confirmation WAL coverage failure", failure); - } - private static void assertCauseChainContainsMessage(Throwable failure, String expectedMessage) { Throwable cause = failure; while (cause != null) { @@ -3084,38 +1938,6 @@ private static void assertCauseChainContainsMessage(Throwable failure, String ex throw new AssertionError("Expected cause chain to contain: " + expectedMessage, failure); } - private static Record readConfirmation( - Context context, AccountGameplayAdmissionLeaseEvidence original, UUID decision) { - return Objects.requireNonNull( - context - .dsl() - .fetchOne( - "SELECT * FROM account_gameplay_admission_read_commit_confirmation(?, ?, ?)", - requestId(original), - original.sha256(), - decision)); - } - - private static void assertDeniedInSavepoint( - Context context, Supplier action, String expectedMessage) { - context.dsl().execute("SAVEPOINT denied_confirmation"); - try { - assertThatThrownBy(action::get) - .hasMessageContaining(expectedMessage) - .satisfies( - failure -> { - Throwable cause = failure; - while (cause != null && !(cause instanceof java.sql.SQLException)) - cause = cause.getCause(); - assertThat(cause).isInstanceOf(java.sql.SQLException.class); - assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("23514"); - }); - } finally { - context.dsl().execute("ROLLBACK TO SAVEPOINT denied_confirmation"); - context.dsl().execute("RELEASE SAVEPOINT denied_confirmation"); - } - } - private static Record operation(Context context, AccountGameplayAdmissionLeaseEvidence original) { return Objects.requireNonNull( context diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java index 3bacc02e05..2e25d39e00 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -3,33 +3,26 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; -import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.SQLException; import java.time.Instant; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; -import org.jooq.JSONB; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; -import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -40,18 +33,19 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Test-only protected-entry feasibility, never production privilege adoption or admission proof. + * Genuine V122 proof transferred from the retired test-only protected-entry feasibility fixture. * - *

The original operation is finalized in unchanged Flyway storage. Upstream carrier fields are - * shape fixtures only. Quiet cold/warm successes are requirements, not assumptions: catalog WAL - * preventing coverage fails visibly without a marker, forced flush, retry warming or deadline - * extension. Async-original unflushed-COMMIT and guaranteed catalog-PRUNE provenance are not - * claimed by this fixture; establishing those exact conditions needs separate physical evidence. + *

Upstream carrier fields are shape fixtures only. Recovery requires exact independent + * durability evidence; a quiet primary does not guarantee that evidence, and unavailable coverage + * must deny without a marker, forced flush, retry warming or deadline extension. Async-original + * unflushed-COMMIT and guaranteed catalog-PRUNE provenance are not claimed by this fixture. SQL + * checks binding and shape; only the trusted JVM physical-COMMIT path supplies the opaque ACK. + * Neither this receipt nor the restricted test role establishes production privilege adoption or + * gameplay admission. */ @Testcontainers(disabledWithoutDocker = true) @Execution(ExecutionMode.SAME_THREAD) class AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest { - // Never consumes the shared fixture's external database override. @Container static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine") @@ -59,210 +53,135 @@ class AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest { private static final String TENANT = "22222222-2222-4222-8222-222222222222"; private static final String OTHER = "33333333-3333-4333-8333-333333333333"; + private static final String RECEIPTS = "account_gameplay_admission_original_commit_ack_receipts"; @Test - void coldQuietEntryProvesExactOriginalThenIndependentReceiptWithoutAuxiliaryWrites() - throws Exception { + void coldGenuineAcknowledgedFinalizationPersistsExactProofWithoutAuxiliaryWrites() { var context = context(); - var original = finalized(context, 15000); - JSONB created = call(context, original, "confirm"); - assertProof(context, original, created); - assertThat(call(context, original, "read_receipt")).isEqualTo(created); - assertProductionReceiptTablesEmpty(context); + var ack = finalized(context, 15000); + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); + assertThat(receipt.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + assertThat(receipt.expiresAtMs()).isEqualTo(expiry(ack)); + assertThat(receipt.receiptXid()).isNotEqualTo(ack.finalizationXid()); + assertThat(receipt.operation().evidence()).isEqualTo(ack.evidence()); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); + assertThat( + context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) + .isZero(); } @Test - void warmedEntryStillRequiresQuietCoverageAndLostResponseRecoveryPreservesExpiry() - throws Exception { + void catalogChurnBeforeOriginalCommitPreservesGenuineAcknowledgedFinalization() { var context = context(); - // Warm entry/catalog resolution on the SAME backend before original finalization. The - // missing-operation branch does not claim to warm every lazily planned PL/pgSQL statement. - try (var warm = context.caller().getConnection()) { - warm.setAutoCommit(false); - warm.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); - assertThatThrownBy( - () -> - invoke( - warm, - context, - "confirm", - UUID.randomUUID(), - "a".repeat(64), - UUID.randomUUID())) - .hasMessageContaining("prototype exact original required"); - warm.rollback(); - var original = finalized(context, 1500); - JSONB discardedResponse = - invoke( - warm, - context, - "confirm", - request(original), - original.evidence().sha256(), - original.decision()); - warm.commit(); - waitPastExpiry(context, original); - assertThat(call(context, original, "read_receipt")).isEqualTo(discardedResponse); - assertThat(call(context, original, "confirm")).isEqualTo(discardedResponse); - assertProof(context, original, discardedResponse); + for (int index = 0; index < 30; index++) { + context.dsl().execute("CREATE TABLE retired_entry_catalog_" + index + "(id integer)"); + context.dsl().execute("DROP TABLE retired_entry_catalog_" + index); } + var ack = finalized(context, 15000); + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); + assertThat(receipt.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + assertThat(receipt.expiresAtMs()).isEqualTo(expiry(ack)); } @Test - void callerCannotForgeCaptureWriteTablesInvokePrivateWriterOrEscalate() throws Exception { + void concurrentGenuineAckCreatorsRetainOneExactWinnerWithoutRestamping() throws Exception { var context = context(); - var original = finalized(context, 15000); - String diagnosticStart = observeWal(context, "after-original-finalization"); - List denied = - List.of( - "INSERT INTO " - + context.proofSchema() - + ".receipts(request_id) VALUES ('" - + request(original) - + "')", - "UPDATE " + context.proofSchema() + ".receipts SET committed_before_ms = 1", - "DELETE FROM " + context.proofSchema() + ".receipts", - "TRUNCATE " + context.proofSchema() + ".receipts", - "SELECT " - + context.proofSchema() - + ".write_receipt(NULL::" - + context.proofSchema() - + ".receipts)", - "SELECT " + context.proofSchema() + ".immutable()", - "SET ROLE " + context.proofSchema() + "_owner", - "ALTER FUNCTION " + context.proofSchema() + ".confirm(uuid,text,uuid) RESET ALL", - "ALTER TABLE " + context.proofSchema() + ".receipts DISABLE TRIGGER ALL", - "CREATE TABLE " + context.proofSchema() + ".shadow(id integer)", - "SET session_replication_role = replica", - "SELECT " - + context.proofSchema() - + ".confirm('" - + request(original) - + "'::uuid, '" - + original.evidence().sha256() - + "', '" - + original.decision() - + "'::uuid, '0/1'::pg_lsn)"); - for (String sql : denied) { - assertThatThrownBy( + var ack = finalized(context, 15000); + var original = operation(context, ack.evidence()); + var sources = sourceSnapshot(context); + var start = new CountDownLatch(1); + java.util.concurrent.Callable duplicate = + () -> { + if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); + return retrySerialization( () -> - callerTransaction( - context, - connection -> { - try (var statement = connection.createStatement()) { - return statement.execute(sql); - } - })) - .as(sql) - .isInstanceOf(SQLException.class) - .satisfies( - failure -> - assertThat(sqlState(failure)) - .isEqualTo(sql.endsWith("'0/1'::pg_lsn)") ? "42883" : "42501")); - } - observeWal(context, "after-denial-loop"); - // A hostile session search path cannot replace fully qualified owner objects. - JSONB created; - try { - created = - callerTransaction( - context, - connection -> { - DSL.using(connection).execute("SET LOCAL search_path = pg_temp, public"); - // Observe from the administrator only; do not warm this new caller with SQL. - observeWal(context, "before-fresh-caller-confirm"); - return invoke( - connection, - context, - "confirm", - request(original), - original.evidence().sha256(), - original.decision()); - }); - } catch (SQLException failure) { - retainFailureWal(context, diagnosticStart, failure); - throw failure; + context + .transaction() + .execute(status -> repository(context).create(ack).receipt())); + }; + try (var executor = Executors.newFixedThreadPool(2)) { + var left = executor.submit(duplicate); + var right = executor.submit(duplicate); + start.countDown(); + assertThat(left.get(30, TimeUnit.SECONDS)).isEqualTo(right.get(30, TimeUnit.SECONDS)); } - assertProof(context, original, created); - assertThat(call(context, original, "read_receipt")).isEqualTo(created); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); + assertThat(operation(context, ack.evidence())).isEqualTo(original); + assertThat(sourceSnapshot(context)).isEqualTo(sources); + var before = receipt(context); + waitPastExpiry(context, ack); + var replay = context.transaction().execute(status -> repository(context).create(ack)); + assertThat(replay.inserted()).isFalse(); + assertThat(replay.receipt().committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + assertThat(receipt(context)).isEqualTo(before); + // This asserts exact storage replay. A retry COMMIT is not historical durability proof. } - private static String observeWal(Context context, String phase) { - var observation = - context - .dsl() - .fetchSingle( - "SELECT pg_current_wal_insert_lsn()::text AS insert_lsn, pg_current_wal_flush_lsn()::text AS flush_lsn, ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint AS observed_ms"); - System.out.println( - "Protected-entry administrator WAL observation " + phase + " " + observation); - return observation.get("flush_lsn", String.class); + @Test + void staleSerializableGenuineAckCreatorRetriesAndRetainsOneExactWinner() throws Exception { + var context = context(); + var ack = finalized(context, 15000); + try (var stale = context.admin().getConnection()) { + stale.setAutoCommit(false); + stale.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + DSL.using(stale).fetchSingle("SELECT pg_current_snapshot()"); + var winner = + context.transaction().execute(status -> repository(context).create(ack).receipt()); + assertThatThrownBy(() -> insertAck(DSL.using(stale), ack)) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("40001")); + stale.rollback(); + var retry = context.transaction().execute(status -> repository(context).create(ack)); + assertThat(retry.inserted()).isFalse(); + assertThat(retry.receipt()).isEqualTo(winner); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); + } } - private static void retainFailureWal(Context context, String start, SQLException failure) { - // Failure diagnostics must never replace the original failure or force WAL durability. - try { - if (!(failure instanceof PSQLException postgres)) { - System.out.println("Protected-entry WAL diagnostic unavailable: no PostgreSQL detail"); - return; - } - var serverError = postgres.getServerErrorMessage(); - String detail = serverError == null ? null : serverError.getDetail(); - if (detail == null) { - System.out.println("Protected-entry WAL diagnostic unavailable: no PostgreSQL detail"); - return; - } - var upper = Pattern.compile("(?:^| )upper_lsn=([0-9A-F]+/[0-9A-F]+)(?: |$)").matcher(detail); - if (!upper.find()) { - System.out.println("Protected-entry WAL diagnostic unavailable: no captured upper LSN"); - return; - } - String end = upper.group(1); - var bounds = - context - .dsl() - .fetchSingle( - "SELECT pg_wal_lsn_diff(?::pg_lsn, ?::pg_lsn)::bigint AS bytes, (pg_walfile_name_offset(?::pg_lsn)).file_offset AS start_offset, pg_size_bytes(current_setting('wal_segment_size')) AS segment_bytes", - end, - start, - start); - long bytes = bounds.get("bytes", Long.class); - long offset = bounds.get("start_offset", Long.class); - long segmentBytes = bounds.get("segment_bytes", Long.class); - if (bytes <= 0 || bytes > 2 * segmentBytes - offset) { - System.out.println( - "Protected-entry WAL diagnostic unavailable: empty range or more than two segments " - + start - + ".." - + end); - return; + @Test + void restrictedCallerCannotForgeProofWriteTablesInvokeGuardOrEscalate() throws Exception { + var context = context(); + var ack = finalized(context, 15000); + String role = context.schema() + "_caller"; + context + .dsl() + .execute( + "CREATE ROLE " + + role + + " LOGIN PASSWORD 'isolated-retirement-only' NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION"); + context.dsl().execute("GRANT USAGE ON SCHEMA " + context.schema() + " TO " + role); + var caller = source(context.schema(), role, "isolated-retirement-only"); + var denied = + List.of( + "INSERT INTO " + RECEIPTS + "(request_id) VALUES ('" + request(ack.evidence()) + "')", + "UPDATE " + RECEIPTS + " SET committed_before_ms = 1", + "DELETE FROM " + RECEIPTS, + "TRUNCATE " + RECEIPTS, + "INSERT INTO account_gameplay_admission_commit_confirmations(request_id) VALUES ('" + + request(ack.evidence()) + + "')", + "SELECT account_gameplay_admission_original_ack_receipt_guard()", + "SELECT account_gameplay_admission_confirmation_guard()", + "SET ROLE " + POSTGRES.getUsername(), + "ALTER FUNCTION account_gameplay_admission_original_ack_receipt_guard() RESET ALL", + "ALTER TABLE " + RECEIPTS + " DISABLE TRIGGER ALL", + "CREATE TABLE " + context.schema() + ".shadow(id integer)", + "SET session_replication_role = replica"); + for (String sql : denied) { + try (var connection = caller.getConnection()) { + assertThatThrownBy(() -> DSL.using(connection).execute(sql)) + .isInstanceOf(RuntimeException.class); } - // This container belongs only to this test class. Retain decoded output, never an archive. - var dump = - POSTGRES.execInContainer( - "pg_waldump", - "--path=/var/lib/postgresql/data/pg_wal", - "--start=" + start, - "--end=" + end, - "--limit=128"); - String output = dump.getStdout() + dump.getStderr(); - String retainedOutput = output.substring(0, Math.min(output.length(), 16384)); - System.out.println( - "Protected-entry WAL diagnostic " - + start - + ".." - + end - + " exit=" - + dump.getExitCode() - + " (maximum two segments, 128 records, 16384 characters):\n" - + retainedOutput); - System.out.println( - AccountPostgresIntegrationFixture.mapWalRelationLocatorsAfterFailure( - retainedOutput, context.admin())); - System.out.println( - "Protected-entry WAL diagnostic may be partial or unreadable before ordinary flushing; no flush, checkpoint, segment switch or retry was requested. Record/character limits may truncate provenance, and WAL records alone do not identify their backend."); - } catch (Exception diagnosticFailure) { - System.out.println("Protected-entry WAL diagnostic unavailable: " + diagnosticFailure); } + // The genuine trusted owner remains usable after all denied caller attempts. + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); + assertThat(receipt.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); } @Test @@ -285,221 +204,367 @@ void ownFinalizationAndReleasedSubtransactionCannotSupplyIndependentOriginal() { context.dsl().execute("RELEASE SAVEPOINT original_finalization"); context .dsl() - .fetchSingle( - "SELECT " + context.proofSchema() + ".confirm(?, ?, ?)", + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, pg_current_xact_id()::text, ?)", request(evidence), evidence.sha256(), - decision); + decision, + Long.parseLong((String) evidence.carrier().get("evaluatedAt"))); })) - .hasMessageContaining("prototype independent original required"); - assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isZero(); + .hasMessageContaining("requires independent transaction"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } } @Test - void receiptCreatedInCurrentTransactionIsNotIndependentRecovery() throws Exception { - var context = context(); - var original = finalized(context, 15000); - assertThatThrownBy( - () -> - callerTransaction( - context, - connection -> { - invoke( - connection, - context, - "confirm", - request(original), - original.evidence().sha256(), - original.decision()); - return invoke( - connection, - context, - "read_receipt", - request(original), - original.evidence().sha256(), - original.decision()); - })) - .hasMessageContaining("prototype independent receipt required"); - assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isZero(); - } - - @Test - void lateAndChangedOriginalDenyWithoutReceiptOrDeadlineMutation() throws Exception { - var context = context(); - var original = finalized(context, 1200); - assertThatThrownBy( - () -> - callerTransaction( - context, - connection -> - invoke( - connection, - context, - "confirm", - request(original), - "b".repeat(64), - original.decision()))) - .hasMessageContaining("prototype exact original required"); - assertThatThrownBy( - () -> - callerTransaction( - context, - connection -> - invoke( - connection, - context, - "confirm", - request(original), - original.evidence().sha256(), - UUID.randomUUID()))) - .hasMessageContaining("prototype exact original required"); - waitPastExpiry(context, original); - assertThatThrownBy(() -> call(context, original, "confirm")) - .hasMessageContaining("prototype unchanged deadline expired"); - assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isZero(); - assertThat( - context - .dsl() - .fetchSingle( - "SELECT expires_at_ms FROM account_gameplay_admission_lease_operations WHERE request_id = ?", - request(original)) - .get(0, Long.class)) - .isEqualTo(expiry(original)); + void receiptInCurrentTransactionAndReleasedSubtransactionCannotProveDurability() { + for (boolean subtransaction : List.of(false, true)) { + var context = context(); + var ack = finalized(context, 15000); + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> { + if (subtransaction) context.dsl().execute("SAVEPOINT receipt_creation"); + repository(context).create(ack); + if (subtransaction) + context.dsl().execute("RELEASE SAVEPOINT receipt_creation"); + repository(context).readDurably(ack.evidence(), ack.decisionId()); + })) + .hasMessageContaining("requires independent commit"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } } @Test - void staleSerializableCreatorMustRetryAndRecoverOneExactWinner() throws Exception { + void staleSnapshotBeforeOriginalCommitCannotCreateAcknowledgementReceipt() throws Exception { var context = context(); - var original = finalized(context, 15000); - try (var stale = context.caller().getConnection()) { + var evidence = pending(context, 15000); + try (var stale = context.admin().getConnection()) { stale.setAutoCommit(false); stale.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); DSL.using(stale).fetchSingle("SELECT pg_current_snapshot()"); - JSONB winner = call(context, original, "confirm"); - assertThatThrownBy( - () -> - invoke( - stale, - context, - "confirm", - request(original), - original.evidence().sha256(), - original.decision())) - .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("40001")); + var ack = + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(evidence, UUID.randomUUID()); + assertThatThrownBy(() -> insertAck(DSL.using(stale), ack)) + .satisfies(failure -> assertThat(sqlState(failure)).isIn("23514", "40001")); stale.rollback(); - assertThat(call(context, original, "read_receipt")).isEqualTo(winner); - assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isOne(); } + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } @Test - void snapshotBeforeIndependentFinalizationCannotSeeItsLaterCommit() throws Exception { + void changedCallerProofAndBindingsDenyAndRetainedReceiptRemainsImmutable() { var context = context(); - var evidence = pending(context, 15000); - UUID decision = UUID.randomUUID(); - try (var stale = context.caller().getConnection()) { - stale.setAutoCommit(false); - stale.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); - DSL.using(stale).fetchSingle("SELECT pg_current_snapshot()"); - new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) - .execute(evidence, decision); + var ack = finalized(context, 15000); + for (String field : + List.of("account_uuid", "lease_id", "lease_fence", "expires_at_ms", "receipt_xid")) { + String value = + switch (field) { + case "account_uuid", "lease_id" -> "'" + UUID.randomUUID() + "'::uuid"; + case "receipt_xid" -> "'1'"; + default -> "1"; + }; assertThatThrownBy( () -> - invoke(stale, context, "confirm", request(evidence), evidence.sha256(), decision)) - .hasMessageContaining("prototype exact original required"); - stale.rollback(); + context + .transaction() + .executeWithoutResult( + status -> + context + .dsl() + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms, " + + field + + ") VALUES (?, ?, ?, ?, ?, " + + value + + ")", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId(), + ack.finalizationXid(), + ack.committedBeforeMs()))) + .hasMessageContaining("binding is database derived"); } - assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isZero(); + for (String changed : List.of("digest", "decision", "xid", "bound")) { + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> + context + .dsl() + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, ?, ?)", + request(ack.evidence()), + changed.equals("digest") + ? "b".repeat(64) + : ack.evidence().sha256(), + changed.equals("decision") + ? UUID.randomUUID() + : ack.decisionId(), + changed.equals("xid") ? "1" : ack.finalizationXid(), + changed.equals("bound") + ? expiry(ack) + : ack.committedBeforeMs()))) + .hasMessageContaining("Exact original Account COMMIT acknowledgement required"); + } + var receipt = + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); + var before = receipt(context); + for (String mutation : + List.of( + "UPDATE " + RECEIPTS + " SET committed_before_ms = committed_before_ms + 1", + "UPDATE " + RECEIPTS + " SET expires_at_ms = expires_at_ms + 1", + "UPDATE " + RECEIPTS + " SET evidence_sha256 = '" + "b".repeat(64) + "'", + "DELETE FROM " + RECEIPTS, + "TRUNCATE " + RECEIPTS)) { + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult(status -> context.dsl().execute(mutation))) + .hasMessageContaining("receipt is immutable"); + } + assertThat(receipt(context)).isEqualTo(before); + assertThat(receipt.committedBeforeMs()).isEqualTo(ack.committedBeforeMs()); } @Test - void lockWaitPastOriginalExpiryDeniesWithoutReceipt() throws Exception { + void originalLockWaitPastExpiryCannotMintAcknowledgementOrReceipt() throws Exception { var context = context(); - var original = finalized(context, 1800); + var evidence = pending(context, 1800); try (var lock = context.admin().getConnection(); var executor = Executors.newSingleThreadExecutor()) { lock.setAutoCommit(false); - UUID account = + var owner = DSL.using(lock) .fetchSingle( "SELECT account_uuid FROM account_gameplay_admission_lease_operations WHERE request_id = ?", - request(original)) + request(evidence)) .get(0, UUID.class); DSL.using(lock) .fetchSingle( - "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", account); - var entered = new CountDownLatch(1); - var pid = new AtomicInteger(); + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", owner); + var started = new CountDownLatch(1); + var backendPid = new java.util.concurrent.atomic.AtomicInteger(); + var waitingSource = + new org.springframework.jdbc.datasource.DelegatingDataSource(context.admin()) { + @Override + public Connection getConnection() throws SQLException { + Connection connection = super.getConnection(); + try { + backendPid.set( + DSL.using(connection) + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class)); + started.countDown(); + return connection; + } catch (RuntimeException | Error failure) { + try { + connection.close(); + } catch (SQLException closeFailure) { + failure.addSuppressed(closeFailure); + } + throw failure; + } + } + }; var attempt = executor.submit( () -> - callerTransaction( - context, - connection -> { - pid.set( - DSL.using(connection) - .fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class)); - entered.countDown(); - return invoke( - connection, - context, - "confirm", - request(original), - original.evidence().sha256(), - original.decision()); - })); - assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); - // Establish actual lock waiting, rather than assuming a thread-start latch proves it. + new AccountGameplayAdmissionOriginalCommitExecutor(waitingSource) + .execute(evidence, UUID.randomUUID())); + assertThat(started.await(5, TimeUnit.SECONDS)).isTrue(); + // Verify an actual independent lock wait before the original expiry is allowed to pass. boolean waiting = false; long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (!waiting && System.nanoTime() < until) { waiting = - Boolean.TRUE.equals( - context - .dsl() - .fetchSingle( - "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE pid = ? AND wait_event_type = 'Lock')", - pid.get()) - .get(0, Boolean.class)); + context + .dsl() + .fetchSingle( + "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE pid = ? AND wait_event_type = 'Lock')", + backendPid.get()) + .get(0, Boolean.class); if (!waiting) Thread.sleep(10); } assertThat(waiting).isTrue(); - waitPastExpiry(context, original); + context + .dsl() + .fetchSingle( + "SELECT pg_sleep(GREATEST(0, (? - ceil(extract(epoch FROM clock_timestamp()) * 1000) + 50) / 1000.0))", + Long.parseLong((String) evidence.carrier().get("expiresAt"))); lock.rollback(); assertThatThrownBy(() -> attempt.get(5, TimeUnit.SECONDS)) - .satisfies( - failure -> { - assertThat(sqlState(failure)).isEqualTo("23514"); - assertThat(failure.getCause()) - .hasMessageContaining("prototype unchanged deadline expired"); - }); + .isInstanceOf(java.util.concurrent.ExecutionException.class); } - assertThat(context.dsl().fetchCount(DSL.table(context.proofSchema() + ".receipts"))).isZero(); + assertThat(operation(context, evidence).get("status")).isEqualTo("PENDING"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } @Test - void catalogChurnBeforeFinalizationDoesNotPermitWarmingAwayColdCoverageFailure() - throws Exception { + void originalUpdateBeforeExpiryButPhysicalCommitAfterExpiryCannotMintReceipt() { var context = context(); - // Real catalog churn creates dead catalog tuples. It does not prove PostgreSQL will prune a - // specific pg_class/pg_attribute page at function entry; exact PRUNE coverage remains unproved. - for (int index = 0; index < 30; index++) { - context - .dsl() - .execute("CREATE TABLE prototype_catalog_" + index + "(id integer, payload text)"); - context.dsl().execute("DROP TABLE prototype_catalog_" + index); + var evidence = pending(context, 1000); + var physicalCommits = new java.util.concurrent.atomic.AtomicInteger(); + var delayed = + new org.springframework.jdbc.datasource.DelegatingDataSource(context.admin()) { + @Override + public Connection getConnection() throws SQLException { + return delayedCommitConnection(super.getConnection()); + } + + private Connection delayedCommitConnection(Connection physical) { + try { + return (Connection) + java.lang.reflect.Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("commit") && method.getParameterCount() == 0) { + DSL.using(physical) + .fetchSingle( + "SELECT pg_sleep(GREATEST(0, (? - ceil(extract(epoch FROM clock_timestamp()) * 1000) + 50) / 1000.0))", + Long.parseLong((String) evidence.carrier().get("expiresAt"))); + physical.commit(); + physicalCommits.incrementAndGet(); + return null; + } + try { + return method.invoke(physical, arguments); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } catch (RuntimeException | Error failure) { + try { + physical.close(); + } catch (SQLException closeFailure) { + failure.addSuppressed(closeFailure); + } + throw failure; + } + } + }; + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(delayed) + .execute(evidence, UUID.randomUUID())) + .hasMessageContaining("post-COMMIT clock bound unavailable"); + assertThat(physicalCommits.get()).isOne(); + assertThat(operation(context, evidence).get("status")).isEqualTo("COMMITTED"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + + @Test + void missingPendingRolledBackAndAbortedOriginalRemainUnproved() { + var context = context(); + var evidence = pending(context, 15000); + UUID decision = UUID.randomUUID(); + var original = operation(context, evidence); + var executor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()); + assertThatThrownBy(() -> executor.read(evidence, decision)) + .hasMessageContaining("Exact durable original Account acknowledgement receipt required"); + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> { + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordCommitted(evidence, decision); + throw new IllegalStateException("rollback original"); + })) + .hasMessageContaining("rollback original"); + assertThat(operation(context, evidence)).isEqualTo(original); + assertThatThrownBy(() -> executor.read(evidence, decision)) + .hasMessageContaining("Exact durable original Account acknowledgement receipt required"); + context + .transaction() + .executeWithoutResult( + status -> + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordAborted(evidence, null, UUID.randomUUID())); + assertThatThrownBy(() -> executor.read(evidence, decision)) + .hasMessageContaining("Exact durable original Account acknowledgement receipt required"); + var missing = new LinkedHashMap<>(evidence.carrier()); + missing.put("requestId", UUID.randomUUID().toString()); + assertThatThrownBy( + () -> + executor.read(AccountGameplayAdmissionLeaseEvidence.fromCarrier(missing), decision)) + .isInstanceOf(RuntimeException.class); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + + @Test + void genuineAckSqlEntryRequiresWritableSerializableTransactionAndKeepsFinalizerStamp() { + var context = context(); + var ack = finalized(context, 15000); + for (int isolation : + List.of( + TransactionDefinition.ISOLATION_READ_COMMITTED, + TransactionDefinition.ISOLATION_REPEATABLE_READ)) { + var unsupported = new TransactionTemplate(new DataSourceTransactionManager(context.admin())); + unsupported.setIsolationLevel(isolation); + assertThatThrownBy( + () -> unsupported.executeWithoutResult(status -> insertAck(context.dsl(), ack))) + .hasMessageContaining("Writable SERIALIZABLE"); + assertThatThrownBy( + () -> + unsupported.executeWithoutResult( + status -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId()))) + .hasMessageContaining("Writable SERIALIZABLE"); } - var original = finalized(context, 15000); - JSONB created = call(context, original, "confirm"); - assertProof(context, original, created); - assertThat(call(context, original, "read_receipt")).isEqualTo(created); + var readOnly = new TransactionTemplate(new DataSourceTransactionManager(context.admin())); + readOnly.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.executeWithoutResult( + status -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId()))) + .hasMessageContaining("Writable SERIALIZABLE"); + assertThatThrownBy( + () -> + context + .transaction() + .executeWithoutResult( + status -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET finalization_xid = '1' WHERE request_id = ?", + request(ack.evidence())))) + .hasMessageContaining("finalization transaction is database stamped"); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } private static Context context() { String schema = "protected_" + UUID.randomUUID().toString().replace("-", ""); - String proof = schema + "_proof"; var admin = source(schema, POSTGRES.getUsername(), POSTGRES.getPassword()); Flyway.configure() .dataSource(admin) @@ -511,43 +576,28 @@ private static Context context() { .migrate(); var transaction = new TransactionTemplate(new DataSourceTransactionManager(admin)); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - var dsl = DSL.using(new TransactionAwareDataSourceProxy(admin), SQLDialect.POSTGRES); - try (var resource = - Objects.requireNonNull( - AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.class - .getResourceAsStream("/account-admission-protected-entry-prototype.sql"))) { - dsl.execute( - new String(resource.readAllBytes(), StandardCharsets.UTF_8) - .replace("__S__", schema) - .replace("__P__", proof)); - } catch (IOException failure) { - throw new IllegalStateException("Test-only protected entry fixture unavailable", failure); - } - assertThat( - dsl.fetchSingle("SELECT current_setting('server_version_num')::integer") - .get(0, Integer.class)) - .isBetween(160000, 169999); return new Context( - proof, admin, source(null, proof + "_caller", "isolated-prototype-only"), dsl, transaction); + schema, + admin, + DSL.using(new TransactionAwareDataSourceProxy(admin), SQLDialect.POSTGRES), + transaction); } private static DriverManagerDataSource source(String schema, String username, String password) { var source = new DriverManagerDataSource(); source.setUrl( POSTGRES.getJdbcUrl() - + (schema == null - ? "" - : (POSTGRES.getJdbcUrl().contains("?") ? "&" : "?") + "currentSchema=" + schema)); + + (POSTGRES.getJdbcUrl().contains("?") ? "&" : "?") + + "currentSchema=" + + schema); source.setUsername(username); source.setPassword(password); return source; } - private static Original finalized(Context context, long lifetime) { - var evidence = pending(context, lifetime); - UUID decision = UUID.randomUUID(); - new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()).execute(evidence, decision); - return new Original(evidence, decision); + private static OriginalCommitAcknowledgement finalized(Context context, long lifetime) { + return new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(pending(context, lifetime), UUID.randomUUID()); } private static AccountGameplayAdmissionLeaseEvidence pending(Context context, long lifetime) { @@ -666,116 +716,89 @@ private static AccountGameplayAdmissionLeaseEvidence evidence( return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); } - private static JSONB call(Context context, Original original, String entry) throws SQLException { - return callerTransaction( - context, - connection -> - invoke( - connection, - context, - entry, - request(original), - original.evidence().sha256(), - original.decision())); + private static AccountGameplayAdmissionOriginalAckReceiptRepository repository(Context context) { + return new AccountGameplayAdmissionOriginalAckReceiptRepository( + context.dsl(), new AccountGameplayAdmissionLeaseRepository(context.dsl())); } - private static JSONB invoke( - Connection connection, Context context, String entry, UUID request, String sha, UUID decision) - throws SQLException { - try (var statement = - connection.prepareStatement( - "SELECT " + context.proofSchema() + "." + entry + "(?, ?, ?)")) { - statement.setObject(1, request); - statement.setString(2, sha); - statement.setObject(3, decision); - try (var result = statement.executeQuery()) { - assertThat(result.next()).isTrue(); - JSONB receipt = JSONB.valueOf(result.getString(1)); - assertThat(result.next()).isFalse(); - return receipt; - } - } + private static void insertAck(DSLContext dsl, OriginalCommitAcknowledgement ack) { + dsl.execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, ?, ?) ON CONFLICT (request_id) DO NOTHING", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId(), + ack.finalizationXid(), + ack.committedBeforeMs()); } - private static T callerTransaction(Context context, SqlAction action) throws SQLException { - try (var connection = context.caller().getConnection()) { - connection.setAutoCommit(false); - connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); - try { - T result = action.execute(connection); - connection.commit(); - return result; - } catch (Exception failure) { - connection.rollback(); - if (failure instanceof SQLException sql) throw sql; - if (failure instanceof RuntimeException runtime) throw runtime; - throw new IllegalStateException(failure); - } + private static Map operation( + Context context, AccountGameplayAdmissionLeaseEvidence evidence) { + return context + .dsl() + .fetchSingle( + "SELECT * FROM account_gameplay_admission_lease_operations WHERE request_id = ?", + request(evidence)) + .intoMap(); + } + + private static Map sourceSnapshot(Context context) { + Map snapshot = new LinkedHashMap<>(); + for (String table : + List.of( + "accounts", + "account_gameplay_admission_lease_fences", + "account_gameplay_admission_lease_allocations", + "account_authority_generations", + "account_authority_issuance_fences", + "account_authority_source_records", + "account_authority_outbox_streams", + "account_authority_outbox_events")) { + snapshot.put(table, context.dsl().fetch("SELECT * FROM " + table + " ORDER BY 1").intoMaps()); } + return snapshot; } - private static void assertProof(Context context, Original original, JSONB receipt) { - assertThat( - context - .dsl() - .fetchSingle( - "SELECT (r.original_operation = to_jsonb(o)) AND r.finalization_xid = o.finalization_xid AND r.confirmation_xid <> o.finalization_xid AND pg_visible_in_snapshot(o.finalization_xid::xid8, r.snapshot::pg_snapshot) AND r.flush_lsn >= r.insert_lsn AND r.committed_before_ms < o.expires_at_ms AND r.expires_at_ms = o.expires_at_ms AND to_jsonb(r) = ?::jsonb FROM " - + context.proofSchema() - + ".receipts r JOIN account_gameplay_admission_lease_operations o USING(request_id) WHERE r.request_id = ?", - receipt.data(), - request(original)) - .get(0, Boolean.class)) - .isTrue(); + private static Map receipt(Context context) { + return context.dsl().fetchSingle("SELECT * FROM " + RECEIPTS).intoMap(); } - private static void assertProductionReceiptTablesEmpty(Context context) { - assertThat( - context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) - .isZero(); - assertThat( - context - .dsl() - .fetchCount(DSL.table("account_gameplay_admission_original_commit_ack_receipts"))) - .isZero(); + private static T retrySerialization(java.util.function.Supplier action) { + for (int attempt = 0; ; attempt++) { + try { + return action.get(); + } catch (RuntimeException failure) { + if (!"40001".equals(sqlState(failure)) || attempt >= 4) throw failure; + } + } } - private static void waitPastExpiry(Context context, Original original) { + private static void waitPastExpiry(Context context, OriginalCommitAcknowledgement ack) { context .dsl() .fetchSingle( "SELECT pg_sleep(GREATEST(0, (? - ceil(extract(epoch FROM clock_timestamp()) * 1000) + 50) / 1000.0))", - expiry(original)); - } - - private static String sqlState(Throwable failure) { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) - if (cause instanceof SQLException sql) return sql.getSQLState(); - return null; + expiry(ack)); } - private static UUID request(Original original) { - return request(original.evidence()); + private static long expiry(OriginalCommitAcknowledgement ack) { + return Long.parseLong((String) ack.evidence().carrier().get("expiresAt")); } private static UUID request(AccountGameplayAdmissionLeaseEvidence evidence) { return UUID.fromString((String) evidence.carrier().get("requestId")); } - private static long expiry(Original original) { - return Long.parseLong((String) original.evidence().carrier().get("expiresAt")); - } - - @FunctionalInterface - private interface SqlAction { - T execute(Connection connection) throws SQLException; + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) + if (cause instanceof SQLException sql) return sql.getSQLState(); + return null; } - private record Original(AccountGameplayAdmissionLeaseEvidence evidence, UUID decision) {} - private record Context( - String proofSchema, + String schema, DriverManagerDataSource admin, - DriverManagerDataSource caller, DSLContext dsl, TransactionTemplate transaction) {} } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java index 97ed6c08ac..6e899a7f63 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationOwnerTest.java @@ -2,9 +2,7 @@ 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; @@ -47,17 +45,6 @@ void clearTransaction() { TransactionSynchronizationManager.clear(); } - @Test - void authenticatedConfirmationDelegatesOnlyToPhysicalReceiptExecutor() throws Exception { - var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); - UUID decision = UUID.randomUUID(); - var receipt = receipt(evidence, decision); - when(executor.confirm(evidence, decision)).thenReturn(receipt); - assertThat(peer().call(() -> owner.confirm(request(evidence, decision)))).isSameAs(receipt); - verify(executor).confirm(evidence, decision); - verify(executor, never()).read(any(), any()); - } - @Test void dependencyFailureRetainsLocalCauseWithBoundedOwnerStatusAndNoTrailers() { var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); @@ -70,13 +57,6 @@ void dependencyFailureRetainsLocalCauseWithBoundedOwnerStatusAndNoTrailers() { Status.UNAVAILABLE .withDescription("private dependency description") .asRuntimeException(trailers); - when(executor.confirm(evidence, decision)).thenThrow(dependencyFailure); - - assertUnavailableIsRedacted( - () -> peer().call(() -> owner.confirm(request(evidence, decision))), dependencyFailure); - - TransactionSynchronizationManager.clear(); - org.mockito.Mockito.reset(executor); when(executor.read(evidence, decision)).thenThrow(dependencyFailure); assertUnavailableIsRedacted( () -> peer().call(() -> owner.read(request(evidence, decision))), dependencyFailure); @@ -96,14 +76,13 @@ void readReturnsHistoricalTemporalProofWithoutCreatingOrReevaluatingItsDeadline( assertThat(returned.expiresAtMs()).isEqualTo(1_015_000L); assertThat(returned.committedBeforeMs()).isLessThan(returned.expiresAtMs()); verify(executor).read(evidence, decision); - verify(executor, never()).confirm(any(), any()); } @Test void rejectsMissingWrongPeerAndNamespaceBeforeRequestParsingOrTransaction() { var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); var malformed = FinalizeGameplayAdmissionLeaseRequest.getDefaultInstance(); - assertStatus(Status.Code.UNAUTHENTICATED, () -> owner.confirm(malformed)); + assertStatus(Status.Code.UNAUTHENTICATED, () -> owner.read(malformed)); for (String uri : List.of( "spiffe://firemud/ns/test/sa/account-service", @@ -142,7 +121,7 @@ void rejectsMalformedEnvelopeDecisionUnknownFieldsAndCallerBindingBeforeTransact request(evidence, decision).toBuilder() .setBindingDecisionId(decision.toString().toUpperCase()) .build())) { - assertStatus(Status.Code.INVALID_ARGUMENT, () -> peer().call(() -> owner.confirm(request))); + assertStatus(Status.Code.INVALID_ARGUMENT, () -> peer().call(() -> owner.read(request))); } var changedCarrier = new LinkedHashMap<>(evidence.carrier()); changedCarrier.put("targetNamespace", "other"); @@ -161,7 +140,7 @@ void rejectsAmbientTransactionAndSynchronizationBeforeOwnedTransaction() { TransactionSynchronizationManager.setActualTransactionActive(true); assertStatus( Status.Code.FAILED_PRECONDITION, - () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + () -> peer().call(() -> owner.read(request(evidence, decision)))); TransactionSynchronizationManager.clear(); TransactionSynchronizationManager.initSynchronization(); assertStatus( @@ -172,7 +151,7 @@ void rejectsAmbientTransactionAndSynchronizationBeforeOwnedTransaction() { source, new ConnectionHolder(mock(java.sql.Connection.class))); assertStatus( Status.Code.FAILED_PRECONDITION, - () -> peer().call(() -> owner.confirm(request(evidence, decision)))); + () -> peer().call(() -> owner.read(request(evidence, decision)))); verifyNoInteractions(executor, source); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java index 20b32aca03..514cdcf8f8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCommitConfirmationRepositoryTest.java @@ -40,14 +40,14 @@ void clearTransaction() { } @Test - void confirmAndReadCallOnlyTheirDatabaseFunctionWithOriginalRequestDigestAndDecision() { + void historicalReadCallsOnlyDatabaseReaderWithOriginalRequestDigestAndDecision() { var evidence = AccountGameplayAdmissionAbortOwnerTest.fixture(); UUID decision = UUID.randomUUID(); var operation = committed(evidence, decision); var confirmDsl = dsl(evidence, operation, proofRow(evidence, decision)); var confirmRepository = repository(confirmDsl); - var created = confirmRepository.confirmCommitted(evidence, decision); + var created = confirmRepository.readCommitConfirmation(evidence, decision); assertThat(created.operation()).isEqualTo(operation); assertThat(created.operation().evidence().canonicalJson()).isEqualTo(evidence.canonicalJson()); @@ -71,7 +71,7 @@ void confirmAndReadCallOnlyTheirDatabaseFunctionWithOriginalRequestDigestAndDeci assertThat(created.confirmationXid()).isEqualTo("123457"); verify(confirmDsl) .fetchOne( - CONFIRM_SQL, + READ_SQL, UUID.fromString((String) evidence.carrier().get("requestId")), evidence.sha256(), decision); @@ -79,7 +79,7 @@ void confirmAndReadCallOnlyTheirDatabaseFunctionWithOriginalRequestDigestAndDeci confirmOrder .verify(confirmDsl) .fetchOne( - CONFIRM_SQL, + READ_SQL, UUID.fromString((String) evidence.carrier().get("requestId")), evidence.sha256(), decision); @@ -89,29 +89,7 @@ void confirmAndReadCallOnlyTheirDatabaseFunctionWithOriginalRequestDigestAndDeci .fetchOne( OPERATION_SELECT_SQL, UUID.fromString((String) evidence.carrier().get("requestId"))); - var readDsl = dsl(evidence, operation, proofRow(evidence, decision)); - var readRepository = repository(readDsl); - assertThat(readRepository.readCommitConfirmation(evidence, decision)).isEqualTo(created); - verify(readDsl) - .fetchOne( - READ_SQL, - UUID.fromString((String) evidence.carrier().get("requestId")), - evidence.sha256(), - decision); - var readOrder = inOrder(readDsl); - readOrder - .verify(readDsl) - .fetchOne( - READ_SQL, - UUID.fromString((String) evidence.carrier().get("requestId")), - evidence.sha256(), - decision); - readOrder.verify(readDsl).fetchOne(ACCOUNT_LOCK_SQL, ACCOUNT_ID); - readOrder - .verify(readDsl) - .fetchOne( - OPERATION_SELECT_SQL, UUID.fromString((String) evidence.carrier().get("requestId"))); - verify(readDsl, never()).fetchOne(eq(CONFIRM_SQL), any(Object[].class)); + verify(confirmDsl, never()).fetchOne(eq(CONFIRM_SQL), any(Object[].class)); } @Test @@ -132,7 +110,7 @@ void requiresWritableSerializableAccountTransactionBeforeAnyStorageAccess() { TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( Connection.TRANSACTION_SERIALIZABLE); TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); - assertThatThrownBy(() -> repository.confirmCommitted(evidence, UUID.randomUUID())) + assertThatThrownBy(() -> repository.readCommitConfirmation(evidence, UUID.randomUUID())) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(dsl); } @@ -149,10 +127,10 @@ void pendingAbortedMissingAndDecisionMismatchFailClosedAfterProofLookup() { new AccountGameplayAdmissionLeaseOperation( evidence, State.COMMITTED, UUID.randomUUID(), null))) { DSLContext dsl = dsl(evidence, operation, proofRow(evidence, decision)); - assertThatThrownBy(() -> repository(dsl).confirmCommitted(evidence, decision)) + assertThatThrownBy(() -> repository(dsl).readCommitConfirmation(evidence, decision)) .isInstanceOf(IllegalStateException.class); - verify(dsl).fetchOne(eq(CONFIRM_SQL), any(Object[].class)); - verify(dsl, never()).fetchOne(eq(READ_SQL), any(Object[].class)); + verify(dsl).fetchOne(eq(READ_SQL), any(Object[].class)); + verify(dsl, never()).fetchOne(eq(CONFIRM_SQL), any(Object[].class)); } DSLContext missingDsl = dsl(evidence, null, proofRow(evidence, decision)); @@ -209,7 +187,6 @@ private static DSLContext dsl( DSLContext dsl = mock(DSLContext.class); Record account = mock(Record.class); Record operationRow = operation == null ? null : operationRow(evidence, operation); - when(dsl.fetchOne(eq(CONFIRM_SQL), any(Object[].class))).thenReturn(proof); when(dsl.fetchOne(eq(READ_SQL), any(Object[].class))).thenReturn(proof); when(dsl.fetchOne(eq(ACCOUNT_LOCK_SQL), any(Object[].class))).thenReturn(account); when(dsl.fetchOne(eq(OPERATION_SELECT_SQL), any(Object[].class))).thenReturn(operationRow); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutorTest.java index b80321d457..668d461442 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionReceiptCommitExecutorTest.java @@ -2,7 +2,6 @@ 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.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.doAnswer; @@ -10,7 +9,6 @@ import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockConstruction; -import static org.mockito.Mockito.mockingDetails; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -48,132 +46,49 @@ void clearTransaction() { } @Test - void physicalReceiptCommitPrecedesNewConnectionAndExactHistoricalRead() throws Exception { + void readOnlyValidatesExistingReceipt() throws Exception { var fixture = new Fixture(); try (var repositories = fixture.repositories()) { - assertThat(fixture.executor.confirm(fixture.evidence, fixture.decision)) + assertThat(fixture.executor.read(fixture.evidence, fixture.decision)) .isSameAs(fixture.receipt); - assertThat(repositories.constructed()).hasSize(2); - var order = - inOrder( - fixture.first.connection, - fixture.second.connection, - repositories.constructed().get(0), - repositories.constructed().get(1)); - order - .verify(repositories.constructed().get(0)) - .confirmCommitted(fixture.evidence, fixture.decision); - order.verify(fixture.first.connection).commit(); - order.verify(fixture.first.connection).close(); - order - .verify(repositories.constructed().get(1)) + verify(repositories.constructed().getFirst()) .readCommitConfirmation(fixture.evidence, fixture.decision); - order.verify(fixture.second.connection).commit(); - assertIndependentAcquisition(fixture, repositories.constructed().get(1)); - // This is a historical receipt: receipt persistence does not restamp original expiry. - assertThat(fixture.receipt.expiresAtMs()).isLessThan(System.currentTimeMillis()); - verify(fixture.first.statement).execute("SET LOCAL synchronous_commit = on"); - verify(fixture.second.statement).execute("SET LOCAL synchronous_commit = on"); - } - } - - @Test - void uncertainPhysicalReceiptCommitNeverStartsIndependentRead() throws Exception { - var fixture = new Fixture(); - doThrow(new SQLException("COMMIT acknowledgement lost", "08006")) - .when(fixture.first.connection) - .commit(); - try (var repositories = fixture.repositories()) { - assertThatThrownBy(() -> fixture.executor.confirm(fixture.evidence, fixture.decision)) - .hasMessageContaining("physical COMMIT unavailable"); - assertThat(repositories.constructed()).hasSize(1); - verify(fixture.first.connection).rollback(); + verify(fixture.first.connection).commit(); verifyNoInteractions(fixture.second.connection); } } @ParameterizedTest - @ValueSource(strings = {"failure", "null", "decision", "evidence"}) - void unavailableOrNonExactCreationNeverCommitsOrReads(String fault) throws Exception { + @ValueSource(strings = {"null", "failure", "decision", "evidence", "commit-failure"}) + void unavailableOrNonExactHistoricalReadNeverReturnsProof(String fault) throws Exception { var fixture = new Fixture(); + switch (fault) { + case "null" -> fixture.readReceipt = null; + case "failure" -> fixture.failRead = true; + case "decision" -> + fixture.readReceipt = + AccountGameplayAdmissionCommitConfirmationOwnerTest.receipt( + fixture.evidence, UUID.randomUUID()); + case "evidence" -> { + var carrier = new java.util.LinkedHashMap<>(fixture.evidence.carrier()); + carrier.put("requestId", UUID.randomUUID().toString()); + fixture.readReceipt = + AccountGameplayAdmissionCommitConfirmationOwnerTest.receipt( + AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier), fixture.decision); + } + case "commit-failure" -> + doThrow(new SQLException("historical read COMMIT unavailable")) + .when(fixture.first.connection) + .commit(); + default -> throw new IllegalArgumentException(fault); + } try (var repositories = fixture.repositories()) { - fixture.creationFault = fault; - assertThatThrownBy(() -> fixture.executor.confirm(fixture.evidence, fixture.decision)) + assertThatThrownBy(() -> fixture.executor.read(fixture.evidence, fixture.decision)) .isInstanceOf(RuntimeException.class); assertThat(repositories.constructed()).hasSize(1); - verify(fixture.first.connection, never()).commit(); verify(fixture.first.connection).rollback(); verifyNoInteractions(fixture.second.connection); - } - } - - @ParameterizedTest - @ValueSource(strings = {"different", "failure", "commit-failure"}) - void readMismatchOrFailureDoesNotExposeCreatedReceipt(String fault) throws Exception { - var fixture = new Fixture(); - if (fault.equals("different")) { - var r = fixture.receipt; - fixture.readReceipt = - new AccountGameplayAdmissionCommitConfirmation( - r.operation(), - r.confirmationVersion(), - r.requestId(), - r.accountId(), - r.leaseId(), - r.leaseFence(), - r.evidenceSha256(), - r.bindingDecisionId(), - r.expiresAtMs(), - r.finalizationXid(), - r.walInsertLsn(), - r.walFlushLsn(), - r.committedBeforeMs(), - "123458"); - } - fixture.failRead = fault.equals("failure"); - if (fault.equals("commit-failure")) { - doThrow(new SQLException("read commit lost")).when(fixture.second.connection).commit(); - } - try (var repositories = fixture.repositories()) { - assertThatThrownBy(() -> fixture.executor.confirm(fixture.evidence, fixture.decision)) - .isInstanceOf(RuntimeException.class); - verify(fixture.first.connection).commit(); - assertThat(repositories.constructed()).hasSize(2); - } - } - - @Test - void poolMayReuseConnectionAfterCompletedCommitAndCleanup() throws Exception { - var fixture = new Fixture(); - when(fixture.source.getConnection()).thenReturn(fixture.first.connection); - fixture.readConnection = fixture.first.connection; - try (var repositories = fixture.repositories()) { - assertThat(fixture.executor.confirm(fixture.evidence, fixture.decision)) - .isSameAs(fixture.receipt); - assertThat(repositories.constructed()).hasSize(2); - var order = inOrder(fixture.first.connection, repositories.constructed().get(1)); - order.verify(fixture.first.connection).commit(); - order.verify(fixture.first.connection).close(); - order - .verify(repositories.constructed().get(1)) - .readCommitConfirmation(fixture.evidence, fixture.decision); - order.verify(fixture.first.connection).commit(); - assertIndependentAcquisition(fixture, repositories.constructed().get(1)); - verify(fixture.first.connection, never()).rollback(); - } - } - - @Test - void readOnlyValidatesExistingReceipt() throws Exception { - var fixture = new Fixture(); - try (var repositories = fixture.repositories()) { - assertThat(fixture.executor.read(fixture.evidence, fixture.decision)) - .isSameAs(fixture.receipt); - verify(repositories.constructed().getFirst(), never()).confirmCommitted(any(), any()); - verify(repositories.constructed().getFirst()) - .readCommitConfirmation(fixture.evidence, fixture.decision); - verify(fixture.first.connection).commit(); - verifyNoInteractions(fixture.second.connection); + if (!fault.equals("commit-failure")) verify(fixture.first.connection, never()).commit(); } } @@ -189,8 +104,6 @@ void ambientContextDeniesBeforeConnectionAcquisition(String ambient) throws Exce fixture.source, new ConnectionHolder(fixture.first.connection)); default -> throw new IllegalArgumentException(ambient); } - assertThatThrownBy(() -> fixture.executor.confirm(fixture.evidence, fixture.decision)) - .hasMessageContaining("Fresh owned"); assertThatThrownBy(() -> fixture.executor.read(fixture.evidence, fixture.decision)) .hasMessageContaining("Fresh owned"); verifyNoInteractions(fixture.source, fixture.first.connection); @@ -232,7 +145,7 @@ void invalidDurabilityRollsBackBeforeAutoCommitCleanup(String fault) throws Exce default -> throw new IllegalArgumentException(fault); } try (var repositories = fixture.repositories()) { - assertThatThrownBy(() -> fixture.executor.confirm(fixture.evidence, fixture.decision)) + assertThatThrownBy(() -> fixture.executor.read(fixture.evidence, fixture.decision)) .isInstanceOf(RuntimeException.class); verify(jdbc.connection, never()).commit(); var order = inOrder(jdbc.connection); @@ -243,29 +156,6 @@ void invalidDurabilityRollsBackBeforeAutoCommitCleanup(String fault) throws Exce } } - private static void assertIndependentAcquisition( - Fixture fixture, AccountGameplayAdmissionCommitConfirmationRepository readRepository) { - int[] acquisitions = invocationSequences(fixture.source, "getConnection"); - int[] commits = invocationSequences(fixture.first.connection, "commit"); - int[] closes = invocationSequences(fixture.first.connection, "close"); - int[] reads = invocationSequences(readRepository, "readCommitConfirmation"); - assertThat(acquisitions).hasSize(2); - assertThat(reads).hasSize(1); - assertThat(commits).isNotEmpty(); - assertThat(closes).isNotEmpty(); - assertThat(acquisitions[0]).isLessThan(commits[0]); - assertThat(commits[0]).isLessThan(closes[0]); - assertThat(closes[0]).isLessThan(acquisitions[1]); - assertThat(acquisitions[1]).isLessThan(reads[0]); - } - - private static int[] invocationSequences(Object mock, String method) { - return mockingDetails(mock).getInvocations().stream() - .filter(invocation -> invocation.getMethod().getName().equals(method)) - .mapToInt(invocation -> invocation.getSequenceNumber()) - .toArray(); - } - private static final class Fixture { private final DataSource source = mock(DataSource.class); private final Jdbc first = new Jdbc(); @@ -278,7 +168,6 @@ private static final class Fixture { AccountGameplayAdmissionCommitConfirmationOwnerTest.receipt(evidence, decision); private AccountGameplayAdmissionCommitConfirmation readReceipt = receipt; private boolean failRead; - private String creationFault; private final AccountGameplayAdmissionReceiptCommitExecutor executor = new AccountGameplayAdmissionReceiptCommitExecutor(source); @@ -299,25 +188,6 @@ private Fixture() throws SQLException { assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); - when(repository.confirmCommitted(evidence, decision)) - .thenAnswer( - ignored -> { - if (creationFault == null) return receipt; - return switch (creationFault) { - case "failure" -> throw new IllegalStateException("creation unavailable"); - case "null" -> null; - case "decision" -> - AccountGameplayAdmissionCommitConfirmationOwnerTest.receipt( - evidence, UUID.randomUUID()); - case "evidence" -> { - var carrier = new java.util.LinkedHashMap<>(evidence.carrier()); - carrier.put("requestId", UUID.randomUUID().toString()); - yield AccountGameplayAdmissionCommitConfirmationOwnerTest.receipt( - AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier), decision); - } - default -> throw new IllegalArgumentException(creationFault); - }; - }); when(repository.readCommitConfirmation(evidence, decision)) .thenAnswer( ignored -> { diff --git a/services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql b/services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql deleted file mode 100644 index ae05c263aa..0000000000 --- a/services/account-service/src/test/resources/account-admission-protected-entry-prototype.sql +++ /dev/null @@ -1,196 +0,0 @@ --- Isolated feasibility fixture only. No production migration or privilege adoption. --- __S__ is the actual Flyway schema; __P__ is a separate test receipt schema. -CREATE ROLE __P___owner NOLOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT; -CREATE ROLE __P___caller LOGIN PASSWORD 'isolated-prototype-only' NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT; -CREATE SCHEMA __P__ AUTHORIZATION __P___owner; -REVOKE ALL ON SCHEMA __P__ FROM PUBLIC; -GRANT USAGE ON SCHEMA __P__ TO __P___caller; -GRANT USAGE ON SCHEMA __S__ TO __P___owner; -GRANT SELECT ON __S__.accounts, __S__.account_gameplay_admission_lease_operations TO __P___owner; --- PostgreSQL row locking requires UPDATE privilege; no caller receives it. -GRANT UPDATE(account_uuid) ON __S__.accounts TO __P___owner; -GRANT UPDATE(request_id) ON __S__.account_gameplay_admission_lease_operations TO __P___owner; - -CREATE TABLE __P__.receipts ( - request_id UUID PRIMARY KEY REFERENCES __S__.account_gameplay_admission_lease_operations(request_id), - original_operation JSONB NOT NULL, - finalization_xid TEXT NOT NULL, - confirmation_xid TEXT NOT NULL, - snapshot TEXT NOT NULL, - insert_lsn PG_LSN NOT NULL CHECK (insert_lsn > '0/0'), - flush_lsn PG_LSN NOT NULL CHECK (flush_lsn >= insert_lsn), - committed_before_ms BIGINT NOT NULL CHECK (committed_before_ms > 0), - expires_at_ms BIGINT NOT NULL CHECK (expires_at_ms > committed_before_ms), - CHECK (finalization_xid <> confirmation_xid) -); -ALTER TABLE __P__.receipts OWNER TO __P___owner; -REVOKE ALL ON __P__.receipts FROM PUBLIC, __P___caller; - -CREATE FUNCTION __P__.immutable() RETURNS TRIGGER LANGUAGE plpgsql SET search_path = pg_catalog AS $$ -BEGIN - RAISE EXCEPTION 'prototype receipt immutable' USING ERRCODE = '23514'; -END; -$$; -ALTER FUNCTION __P__.immutable() OWNER TO __P___owner; -REVOKE ALL ON FUNCTION __P__.immutable() FROM PUBLIC, __P___caller; -CREATE TRIGGER immutable BEFORE UPDATE OR DELETE ON __P__.receipts - FOR EACH ROW EXECUTE FUNCTION __P__.immutable(); -CREATE TRIGGER immutable_truncate BEFORE TRUNCATE ON __P__.receipts - FOR EACH STATEMENT EXECUTE FUNCTION __P__.immutable(); - --- Private writer is never executable by the caller. Capture is not an external API. -CREATE FUNCTION __P__.write_receipt(p_receipt __P__.receipts) RETURNS JSONB -LANGUAGE plpgsql SET search_path = pg_catalog AS $$ -DECLARE retained __P__.receipts%ROWTYPE; -BEGIN - INSERT INTO __P__.receipts SELECT (p_receipt).* WHERE TRUE ON CONFLICT (request_id) DO NOTHING - RETURNING * INTO retained; - IF NOT FOUND THEN - RAISE EXCEPTION 'prototype stale receipt snapshot' USING ERRCODE = '40001'; - END IF; - RETURN to_jsonb(retained); -END; -$$; -ALTER FUNCTION __P__.write_receipt(__P__.receipts) OWNER TO __P___owner; -REVOKE ALL ON FUNCTION __P__.write_receipt(__P__.receipts) FROM PUBLIC, __P___caller; - -CREATE FUNCTION __P__.confirm(p_request UUID, p_sha TEXT, p_decision UUID) RETURNS JSONB -LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$ -DECLARE - op __S__.account_gameplay_admission_lease_operations%ROWTYPE; - locked_op __S__.account_gameplay_admission_lease_operations%ROWTYPE; - retained __P__.receipts%ROWTYPE; - candidate __P__.receipts%ROWTYPE; - fixed_snapshot pg_snapshot; - own_xid TEXT; - upper_lsn pg_lsn; - flush_lsn pg_lsn; - observed_ms BIGINT; - observation INTEGER; - diagnostic_entry_insert pg_lsn; - diagnostic_entry_flush pg_lsn; - diagnostic_capture_flush pg_lsn; - diagnostic_pid INTEGER; -BEGIN - -- Observations only: even this first statement follows function resolution/planning. - diagnostic_entry_insert := pg_current_wal_insert_lsn(); - diagnostic_entry_flush := pg_current_wal_flush_lsn(); - diagnostic_pid := pg_backend_pid(); - IF current_setting('transaction_isolation') <> 'serializable' - OR current_setting('transaction_read_only') <> 'off' - OR pg_is_in_recovery() OR current_setting('fsync') <> 'on' THEN - RAISE EXCEPTION 'prototype durable primary SERIALIZABLE required' USING ERRCODE = '23514'; - END IF; - -- Function entry itself can already require catalog/planning reads. Cold tests must expose - -- resulting unflushed WAL rather than claiming these statements precede all backend reads. - fixed_snapshot := pg_current_snapshot(); - own_xid := pg_current_xact_id_if_assigned()::text; - upper_lsn := pg_current_wal_insert_lsn(); - diagnostic_capture_flush := pg_current_wal_flush_lsn(); - SELECT * INTO op FROM __S__.account_gameplay_admission_lease_operations WHERE request_id = p_request; - IF NOT FOUND OR op.status <> 'COMMITTED' OR op.finalization_xid IS NULL - OR op.evidence_sha256 IS DISTINCT FROM p_sha OR op.binding_decision_id IS DISTINCT FROM p_decision THEN - RAISE EXCEPTION 'prototype exact original required' USING ERRCODE = '23514'; - END IF; - IF op.finalization_xid = own_xid - OR NOT pg_visible_in_snapshot(op.finalization_xid::xid8, fixed_snapshot) THEN - RAISE EXCEPTION 'prototype independent original required' USING ERRCODE = '23514'; - END IF; - PERFORM 1 FROM __S__.accounts WHERE account_uuid = op.account_uuid FOR UPDATE; - SELECT * INTO locked_op FROM __S__.account_gameplay_admission_lease_operations - WHERE request_id = p_request FOR UPDATE; - IF NOT FOUND OR locked_op IS DISTINCT FROM op THEN - RAISE EXCEPTION 'prototype original changed' USING ERRCODE = '23514'; - END IF; - SELECT * INTO retained FROM __P__.receipts WHERE request_id = p_request FOR UPDATE; - IF FOUND THEN - IF retained.original_operation IS DISTINCT FROM to_jsonb(op) THEN - RAISE EXCEPTION 'prototype retained binding conflict' USING ERRCODE = '23514'; - END IF; - RETURN to_jsonb(retained); - END IF; - IF pg_xact_status(op.finalization_xid::xid8) IS DISTINCT FROM 'committed' THEN - RAISE EXCEPTION 'prototype independent original required' USING ERRCODE = '23514'; - END IF; - -- Same-snapshot independent visibility places original COMMIT before snapshot acquisition; - -- this later insertion upper bound covers that COMMIT, not merely its earlier row WAL. - FOR observation IN 1..50 LOOP - flush_lsn := pg_current_wal_flush_lsn(); - observed_ms := ceil(extract(epoch FROM clock_timestamp()) * 1000)::bigint; - IF observed_ms <= 0 OR observed_ms >= op.expires_at_ms THEN - RAISE EXCEPTION 'prototype unchanged deadline expired' USING ERRCODE = '23514'; - END IF; - EXIT WHEN upper_lsn > '0/0' AND flush_lsn >= upper_lsn; - IF observation = 50 THEN - RAISE EXCEPTION 'prototype WAL coverage unavailable' USING ERRCODE = '23514', - DETAIL = format('snapshot=%s own_xid=%s original_xid=%s upper_lsn=%s flush_lsn=%s observed_ms=%s expiry=%s diagnostic_pid=%s diagnostic_entry_insert=%s diagnostic_entry_flush=%s diagnostic_capture_flush=%s', - fixed_snapshot, own_xid, op.finalization_xid, upper_lsn, flush_lsn, observed_ms, op.expires_at_ms, - diagnostic_pid, diagnostic_entry_insert, diagnostic_entry_flush, diagnostic_capture_flush); - END IF; - PERFORM pg_sleep(0.01); - END LOOP; - candidate.request_id := p_request; - candidate.original_operation := to_jsonb(op); - candidate.finalization_xid := op.finalization_xid; - candidate.confirmation_xid := pg_current_xact_id()::text; - candidate.snapshot := fixed_snapshot::text; - candidate.insert_lsn := upper_lsn; - candidate.flush_lsn := flush_lsn; - candidate.committed_before_ms := observed_ms; - candidate.expires_at_ms := op.expires_at_ms; - RETURN __P__.write_receipt(candidate); -END; -$$; -ALTER FUNCTION __P__.confirm(UUID, TEXT, UUID) OWNER TO __P___owner; -REVOKE ALL ON FUNCTION __P__.confirm(UUID, TEXT, UUID) FROM PUBLIC; -GRANT EXECUTE ON FUNCTION __P__.confirm(UUID, TEXT, UUID) TO __P___caller; - -CREATE FUNCTION __P__.read_receipt(p_request UUID, p_sha TEXT, p_decision UUID) RETURNS JSONB -LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$ -DECLARE - op __S__.account_gameplay_admission_lease_operations%ROWTYPE; - retained __P__.receipts%ROWTYPE; - fixed_snapshot pg_snapshot; - own_xid TEXT; - upper_lsn pg_lsn; - flush_lsn pg_lsn; - observation INTEGER; -BEGIN - IF current_setting('transaction_isolation') <> 'serializable' - OR current_setting('transaction_read_only') <> 'off' - OR pg_is_in_recovery() OR current_setting('fsync') <> 'on' THEN - RAISE EXCEPTION 'prototype durable primary SERIALIZABLE required' USING ERRCODE = '23514'; - END IF; - fixed_snapshot := pg_current_snapshot(); - own_xid := pg_current_xact_id_if_assigned()::text; - upper_lsn := pg_current_wal_insert_lsn(); - SELECT * INTO op FROM __S__.account_gameplay_admission_lease_operations WHERE request_id = p_request; - IF NOT FOUND OR op.status <> 'COMMITTED' OR op.evidence_sha256 IS DISTINCT FROM p_sha - OR op.binding_decision_id IS DISTINCT FROM p_decision THEN - RAISE EXCEPTION 'prototype exact original required' USING ERRCODE = '23514'; - END IF; - SELECT * INTO retained FROM __P__.receipts WHERE request_id = p_request; - IF NOT FOUND OR retained.original_operation IS DISTINCT FROM to_jsonb(op) THEN - RAISE EXCEPTION 'prototype exact receipt required' USING ERRCODE = '23514'; - END IF; - IF retained.confirmation_xid = own_xid - OR NOT pg_visible_in_snapshot(retained.confirmation_xid::xid8, fixed_snapshot) THEN - RAISE EXCEPTION 'prototype independent receipt required' USING ERRCODE = '23514'; - END IF; - FOR observation IN 1..50 LOOP - flush_lsn := pg_current_wal_flush_lsn(); - EXIT WHEN upper_lsn > '0/0' AND flush_lsn >= upper_lsn; - IF observation = 50 THEN - RAISE EXCEPTION 'prototype receipt WAL coverage unavailable' USING ERRCODE = '23514', - DETAIL = format('snapshot=%s receipt_xid=%s upper_lsn=%s flush_lsn=%s', - fixed_snapshot, retained.confirmation_xid, upper_lsn, flush_lsn); - END IF; - PERFORM pg_sleep(0.01); - END LOOP; - -- Historical recovery preserves the original deadline-qualified evidence after expiry. - RETURN to_jsonb(retained); -END; -$$; -ALTER FUNCTION __P__.read_receipt(UUID, TEXT, UUID) OWNER TO __P___owner; -REVOKE ALL ON FUNCTION __P__.read_receipt(UUID, TEXT, UUID) FROM PUBLIC; -GRANT EXECUTE ON FUNCTION __P__.read_receipt(UUID, TEXT, UUID) TO __P___caller; From 2b763b040c9b4f63baa88bff0c911d3be177abd9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 06:36:51 +1300 Subject: [PATCH 094/129] Compose genuine Entity selected-source retention and Account settlement --- .../account-service/api-contracts.md | 6 +- .../runtime-and-data.md | 14 + design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 12 +- ...cted_owner_intake_settlement_service.proto | 2 +- ...ntity_selected_source_intake_command.proto | 30 + ...selected_source_intake_terminal_read.proto | 34 + ...tSelectedOwnerIntakeSettlementService.java | 144 ++- ...wnerIntakeSourceReservationRepository.java | 69 +- ...ected_owner_intake_terminal_settlement.sql | 708 +++++++++++ ...eAuthorizationPostgresIntegrationTest.java | 700 ++++++++++- ...ectedOwnerIntakeSettlementServiceTest.java | 148 ++- .../AccountControlUiOriginalOrderFixture.java | 25 +- .../AccountControlUiOwnerSourcesFixture.java | 28 +- ...tSelectedOwnerIntakeSettlementReceipt.java | 125 +- ...SelectedOwnerIntakeSettlementEvidence.java | 16 +- ...electedOwnerIntakeSettlementGrpcCodec.java | 11 +- ...ntityEmptySelectedSourceIntakeReceipt.java | 880 ++++++++++++++ ...tySelectedSourceIntakeCommandEvidence.java | 171 +++ ...ySelectedSourceIntakeCommandGrpcCodec.java | 193 +++ ...electedSourceIntakeTerminalReadClient.java | 7 + ...ectedSourceIntakeTerminalReadEvidence.java | 95 ++ ...ctedSourceIntakeTerminalReadGrpcCodec.java | 139 +++ ...ectedOwnerIntakeSettlementReceiptTest.java | 56 + ...tedOwnerIntakeSettlementGrpcCodecTest.java | 9 +- ...ectedSourceIntakeCommandGrpcCodecTest.java | 213 ++++ ...SourceIntakeTerminalReadGrpcCodecTest.java | 247 ++++ services/common-security/build.gradle.kts | 2 + ...titySelectedSourceIntakeCommandClient.java | 181 +++ ...electedSourceIntakeTerminalReadClient.java | 180 +++ ...ctedSourceIntakeCommandClientMtlsTest.java | 507 ++++++++ ...ourceIntakeTerminalReadClientMtlsTest.java | 481 ++++++++ ...ectedSourceIntakeTerminalReadFixtures.java | 562 +++++++++ .../build.gradle.kts | 14 + ...tyEmptySelectedSourceIntakeRepository.java | 843 +++++++++++++ ...ntityEmptySelectedSourceIntakeService.java | 201 +++ ...lectedSourceIntakeTerminalReadService.java | 83 ++ ...electedSourceIntakeCommandGrpcService.java | 97 ++ ...edSourceIntakeTerminalReadGrpcService.java | 53 + ..._fresh_selected_empty_source_catalogue.sql | 1074 +++++++++++++++++ ...ntakeMigrationPostgresIntegrationTest.java | 167 +++ ...tySelectedSourceIntakePostgresFixture.java | 468 +++++++ ...takeRepositoryPostgresIntegrationTest.java | 299 +++++ ...ptySelectedSourceIntakeRepositoryTest.java | 89 ++ ...yEmptySelectedSourceIntakeServiceTest.java | 47 + ...tedSourceIntakeCommandGrpcServiceTest.java | 228 ++++ ...edSourceIntakeTerminalReadServiceTest.java | 295 +++++ services/game-design-service/build.gradle.kts | 8 + ...licationExportPostgresIntegrationTest.java | 768 ++++++++++-- 49 files changed, 10563 insertions(+), 172 deletions(-) create mode 100644 protos/entity-management/v1/entity_selected_source_intake_command.proto create mode 100644 protos/entity-management/v1/entity_selected_source_intake_terminal_read.proto create mode 100644 services/account-service/src/main/resources/db/migration/V138__entity_selected_owner_intake_terminal_settlement.sql create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntityEmptySelectedSourceIntakeReceipt.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java create mode 100644 services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcService.java create mode 100644 services/entity-management-service/src/main/resources/db/migration/V2__fresh_selected_empty_source_catalogue.sql create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index a62053e76e..db008832f9 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -116,11 +116,11 @@ The separate [`AccountSelectedOwnerIntakeAuthorizationProducerService.AuthorizeS The standalone [`AccountSelectedOwnerIntakeAuthorizationReadService.ReadHeldSelectedOwnerIntakeAuthorization`](../../../../protos/account/v1/selected_owner_intake_authorization_read.proto) reads that original finalized order, not its preliminary reservation. Its closed schema-version-1 request binds namespace, an independent nonzero read correlation distinct from the retained operation/fence/intake request, the exact derived owner reader and retention purpose, and the full original binding bytes/digest. Account authenticates same-namespace Entity or Automation and rejects end-user context before decoding; after decoding, the actual peer must be that binding's exact recipient. An independent writable `READ COMMITTED` transaction locks and compares the original authorization, reservation, creator evidence and complete source participation. Success echoes the entire request unchanged with `held=true`; missing, changed, aborted, malformed, mismatched or unavailable evidence denies. The file-backed mTLS client pins Account, uses a five-second deadline, rejects ambient SQL/synchronization and enforces a separate 24 MiB wire budget without expanding the 16 MiB binding limit. This sampled HELD read cannot create/finalize/settle an order, allocate a replacement identity, renew authority or prove continuous protection through the owner's commit, complete census or a terminal receipt. The unregistered components and their proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). -For Automation, Account may settle finalized source participation only after an authenticated exact same-namespace read of the Automation-owned `COMMITTED_EMPTY` terminal for the complete original authorization; the [Automation contract](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) owns its closed request, receipt and retry rules. Account first reads any exact committed settlement independently, then obtains missing terminal evidence outside SQL, commits one immutable settlement under its existing source locks, and performs a separate lookup-only committed readback. Only that exact committed settlement releases this operation's participation, after which both external `HELD` readers deny; historical authorization and terminal recovery remain available without creating fresh authority. Source locks in canonical order precede the reservation, finalized authorization and settlement locks, so a source writer cannot bypass pending participation. Missing, pending, changed, corrupt or ambiguous owner evidence preserves participation; absence or expiry is not an abort. Unregistered construction components do not establish a complete authenticated producer or executed physical proof; see the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +For Entity or Automation, Account may settle finalized source participation only after an authenticated exact same-namespace read of that owner's closed `COMMITTED_EMPTY` terminal for the complete original authorization; the [Entity contract](../entity-management-service/runtime-and-data.md) and [Automation contract](../automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) own their distinct receipt and retry rules. Account first reads any exact committed settlement independently, then obtains missing terminal evidence outside SQL, commits one immutable settlement under its existing source locks, and performs a separate lookup-only committed readback. Only that exact committed settlement releases this operation's participation, after which both external `HELD` readers deny; historical authorization and terminal recovery remain available without creating fresh authority. Source locks in canonical order precede the reservation, finalized authorization and settlement locks, so a source writer cannot bypass pending participation. Missing, pending, changed, corrupt or ambiguous owner evidence preserves participation; absence or expiry is not an abort. Entity provider-row existence belongs to its authenticated committed owner readback, not Account inference from a family-state ledger. Unregistered construction components do not establish complete authenticated production or executed physical proof; see the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). -The immutable Account settlement uses `account-selected-owner-intake-settlement/v1` and the existing byte-length framing and SHA-256 representation. Its fixed frame order is domain, version `1`, complete original authorization bytes and digest, terminal request schema version, namespace, read request UUID, exact Account reader, terminal-read purpose, complete echoed authorization bytes and digest, and complete Automation receipt bytes and digest. Every embedded value must decode canonically and match the same original operation. The complete settlement is bounded to 92,356,608 bytes: two original authorization bounds, one Automation receipt bound, and 64 KiB of framing allowance; it does not widen those embedded bounds. The first terminal-read correlation is retained with the result but is not a new settlement identity: a retry with another valid correlation and identical original binding and owner receipt returns the first settlement byte-for-byte. Changed original binding or owner receipt conflicts without overwriting it. The settlement neither releases another pending operation nor permits preliminary abort of a finalized order; uncertainty remains reconciliation-only. +The immutable Account settlement uses `account-selected-owner-intake-settlement/v1` and the existing byte-length framing and SHA-256 representation. Its fixed frame order is domain, version `1`, complete original authorization bytes and digest, terminal request schema version, namespace, read request UUID, exact Account reader, terminal-read purpose, complete echoed authorization bytes and digest, and complete owner receipt bytes and digest. The retained original authorization owner selects exactly one closed branch: `AUTOMATION_SCRIPTING` uses `AUTOMATION_INTAKE_TERMINAL_READ` and the original Automation receipt; `ENTITY_MANAGEMENT` uses `ENTITY_INTAKE_TERMINAL_READ` and `entity-selected-empty-source-catalogue/v1`. Every embedded value must decode canonically and match the same original operation. Automation retains its exact v1 encoding, 58,736,640-byte receipt bound and 92,356,608-byte settlement bound. Entity has an 83,886,080-byte receipt bound and 117,506,048-byte settlement bound; both settlement bounds include two unchanged 16 MiB authorization bounds and 64 KiB of framing allowance. No embedded bound is widened across owners. The first terminal-read correlation is retained with the result but is not a new settlement identity: a retry with another valid correlation and identical original binding and owner receipt returns the first settlement byte-for-byte. Changed original binding or owner receipt conflicts without overwriting it. Forward-only migration preserves retained Automation authorization, terminal and settlement bytes and history. The settlement neither releases another pending operation nor permits preliminary abort of a finalized order; uncertainty remains reconciliation-only. -The separate [`AccountSelectedOwnerIntakeSettlementService.SettleSelectedOwnerIntake`](../../../../protos/account/v1/selected_owner_intake_settlement_service.proto) is a closed schema-version-1 Game Design command for that same settlement. Account authenticates the exact Game Design peer against its configured namespace and rejects end-user or ambient SQL/synchronization context before decoding. The request binds that namespace, an independent nonzero transport correlation distinct from the original operation/fence/intake request, and the complete original Automation authorization bytes and digest. It carries no fresh creator credential or replacement source authority; Entity settlement is unsupported and denies. Success echoes the request unchanged and returns the entire original Account settlement bytes and digest. A new transport correlation does not allocate a second settlement or alter the first terminal-read correlation. The request wire bound is the unchanged 16 MiB authorization bound plus 64 KiB; the response bound is the unchanged 92,356,608-byte settlement bound plus the complete request bound and another 64 KiB. Embedded bounds, canonical parsing and unknown-field rejection remain independent. The file-backed mTLS client pins Account, uses a five-second deadline and rejects end-user and ambient SQL context before transport. This unregistered command does not bypass authenticated Automation terminal readback, source locks or committed postcondition checks, or authorize runtime activation. +The separate [`AccountSelectedOwnerIntakeSettlementService.SettleSelectedOwnerIntake`](../../../../protos/account/v1/selected_owner_intake_settlement_service.proto) is a closed schema-version-1 Game Design command for that same settlement. Account authenticates the exact Game Design peer against its configured namespace and rejects end-user or ambient SQL/synchronization context before decoding. The request binds that namespace, an independent nonzero transport correlation distinct from the original operation/fence/intake request, and the complete original Entity or Automation authorization bytes and digest. It carries no fresh creator credential or replacement source authority. Success echoes the request unchanged and returns the entire original Account settlement bytes and digest. A new transport correlation does not allocate a second settlement or alter the first terminal-read correlation. The request wire bound is the unchanged 16 MiB authorization bound plus 64 KiB; the response bound is the selected owner's settlement bound plus the complete request bound and another 64 KiB. Embedded owner-specific bounds, canonical parsing and unknown-field rejection remain independent. The file-backed mTLS client pins Account, uses a five-second deadline and rejects end-user and ambient SQL context before transport. This unregistered command does not bypass authenticated owner terminal readback, source locks or committed postcondition checks, or authorize runtime activation. The separate [`AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.ReadHeldSelectedOwnerWorldClosureAuthorization`](../../../../protos/account/v1/selected_owner_intake_world_closure_authorization_read.proto) permits World to independently verify that exact finalized Entity or Automation order before returning the selected World closure. Its outer recipient is the exact same-namespace World workload, and its closed purpose is respectively `ENTITY_INTAKE_WORLD_CLOSURE_READ` or `AUTOMATION_INTAKE_WORLD_CLOSURE_READ`. The inner original authorization retains its Entity or Automation recipient, retention purpose, operation, fence, intake request, complete content and source evidence unchanged. The request binds schema version 1, namespace, an independent nonzero read correlation, and the full original bytes and digest; success echoes it unchanged with `held=true`. Account authenticates World and rejects end-user context before decoding, then locks and verifies the exact original finalized order and source participation in an independent writable `READ COMMITTED` transaction. The existing Entity/Automation recipient read is not widened. World must obtain and validate this confirmation directly over authenticated Account mTLS outside SQL; caller-forwarded bytes or a digest do not establish Account authorization. The five-second deadline, 24 MiB wire budget and unchanged 16 MiB binding bound apply. This is permission for an exact retained closure read, not an owner census, source-mutation grant, receipt, settlement or continuous-through-commit proof; an unavailable or mismatched confirmation denies the read. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 2237e22479..1da075427e 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -63,10 +63,24 @@ The versioned `TEMPLATE_CONFIG` source must carry an explicitly authored, empty- `EntityAuthoredSourceInventoryDeclaration` accepts the exact closed `entity-authored-source-inventory/v1` shape: `schema`, `equipmentApplicability: "NOT_APPLICABLE"`, and `families` containing every required family below as an explicit empty array. Unknown, missing, null, malformed, duplicate, conflicting, oversized, or nonempty input is rejected. Nonempty entity definitions remain unsupported by this declaration; an unsupported family is never treated as empty. Legacy `inventoryEnabled=false`, a `DEFAULT` body layout, an absent table, or an omitted config member cannot establish equipment non-applicability or source absence. +Implementation limitation: the fresh-empty catalogue remains an unregistered preparation/retention foundation. Native owner transport, authenticated Entity terminal settlement and positive through-commit Account protection are not complete; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) owns detailed implementation and executed proof. No publication, nonempty engine or runtime activation is enabled. + +Fresh-only preparation is bound to Entity's configured namespace and authenticates the exact same-namespace Game Design workload before receipt replay, remote reads or mutation. It requires the exact Account authorization, selected World read and freeze, and shared typed selected-source validation. Account and World reads run outside Entity SQL; owner-local retention uses an independent transaction, an immutable byte-framed receipt, all 23 persisted family states and independent post-commit readback. HELD responses are point-in-time samples, not proof of continuous Account protection through retention commit, settlement or renewed authority. + +The standalone [selected-source retention command](../../../../protos/entity-management/v1/entity_selected_source_intake_command.proto) carries those complete original Account and World inputs, not a replacement creator authorization. Its independent transport correlation must not collide with the retained operation, source-selection or freeze identities. Entity authenticates the exact configured same-namespace Game Design peer before decoding, then checks the complete original authorization and freeze against the retained receipt. An identical retry with a new transport correlation returns the unchanged original receipt; conflicting evidence cannot overwrite it or silently found another association. Success echoes the complete request, including the original freeze request and acknowledgement, and returns the full Entity receipt and digest. The native client pins Entity's workload identity, rejects caller credentials and ambient SQL/synchronization, and applies a five-second deadline with separately derived full-request/response budgets. These transport components remain unregistered; constructor or loopback tests do not establish the genuine upstream authorization, physical census or through-commit source protection. + +The separate terminal read authenticates the exact same-namespace Account workload against Entity's configured namespace before decoding or looking up retained evidence. Its closed version-1 request carries an independent read correlation, the complete original Entity intake authorization bytes and digest, the Account recipient, and `ENTITY_INTAKE_TERMINAL_READ` purpose. The response echoes that exact request and returns only the original `COMMITTED_EMPTY` receipt with its digest. Entity independently validates the retained association, all family/provider states and full original binding on lookup; missing or corrupt evidence denies rather than establishing abort or source absence. Historical readback does not invoke fresh currentness, renew authorization, create a receipt or grant publication/admission. End-user context, ambient owner SQL and transaction synchronization are rejected. The transport preserves the receipt's 80 MiB bound and separately budgets the echoed 16 MiB authorization plus bounded framing; it does not inherit the smaller gRPC default or reuse Automation's receipt schema. + The complete required family coverage is `ITEM_TEMPLATE_ROOTS`, `NPC_TEMPLATE_ROOTS`, `OTHER_ACTOR_TEMPLATE_ROOTS`, `CRAFTING_RECIPE_ROOTS`, `CRAFTING_RECIPE_RESULT_BINDINGS`, `CRAFTING_INGREDIENT_BINDINGS`, `EQUIPMENT_CAPABILITIES`, `EQUIPMENT_SLOT_ROOTS`, `EQUIPMENT_SLOT_GROUPS`, `EQUIPMENT_ATTACHMENT_RULES`, `EQUIPMENT_COMPATIBILITY_RULES`, `EQUIPMENT_OCCUPANCY_RULES`, `BODY_LAYOUT_ROOTS`, `BODY_LAYOUT_MEMBERSHIPS`, `ACTOR_BODY_LAYOUT_ASSIGNMENTS`, `LOOT_TABLE_ROOTS`, `LOOT_ITEM_MAPPINGS`, `INBOUND_LOOT_BINDINGS`, `BALANCE_CURVE_ROOTS`, `BALANCE_CURVE_ATTACHMENTS`, `ARCHETYPE_ROOTS`, `ARCHETYPE_CONSTRAINTS`, and `ARCHETYPE_ASSIGNMENTS`. These family names close the empty declaration only; they do not define nonempty identifiers or element grammars. In particular, there is no separate equipment-template identity: equipment remains item-owned, while equipment bindings are separate runtime state. This empty-only declaration is a valid authored claim only when it is present in a genuinely new versioned source and survives the authorized commit/application/snapshot path. It must be read back exactly from the selected source and revalidated while held through retention commit. Its presence alone does not prove that the selected Entity source, selected World graph, or their inbound references are empty or complete. Existing `TEMPLATE_CONFIG` v1 item/NPC references are not reinterpreted or backfilled as this declaration. See [ADR 0127](../../decisions/adr-0127-game-authored-equipment-layouts-with-fail-closed-publication.md) for equipment applicability and complete-schema requirements. +The Entity-local founding boundary is intentionally fresh-only and conservative. Nine families use a real global V1 source/reference census: `items`, `npcs`, `crafting_recipes` (recipe roots and result-item bindings), `crafting_ingredients`, `equipment_slot_definitions` (slot roots and distinct groups), and `body_layout_slot_definitions` (layout roots and memberships). Any existing source row, unqualified/default row, retained row, selected numeric-scope row, or applicable reference denies founding. The other fourteen families—`OTHER_ACTOR_TEMPLATE_ROOTS`, `EQUIPMENT_CAPABILITIES`, `EQUIPMENT_ATTACHMENT_RULES`, `EQUIPMENT_COMPATIBILITY_RULES`, `EQUIPMENT_OCCUPANCY_RULES`, `ACTOR_BODY_LAYOUT_ASSIGNMENTS`, `LOOT_TABLE_ROOTS`, `LOOT_ITEM_MAPPINGS`, `INBOUND_LOOT_BINDINGS`, `BALANCE_CURVE_ROOTS`, `BALANCE_CURVE_ATTACHMENTS`, `ARCHETYPE_ROOTS`, `ARCHETYPE_CONSTRAINTS`, and `ARCHETYPE_ASSIGNMENTS`—have separate Entity-owned, family-specific V2 provider tables that support only a typed `EMPTY` state, provider schema version 1, and zero row/reference counts. Each provider state is inserted for the exact new association, binds the authorization, selected source, source-revision binding, and World-closure digests, and is independently read back before a receipt is accepted. Required provider tables are transaction-locked; a missing or unreadable table, missing row, unsupported state/schema, nonzero count, or mismatched readback denies. This is an explicitly approved fresh-empty boundary, not a claim that the providers implement nonempty family semantics or enumerate content. The creator declaration, an absent table, or the receipt's family-state ledger alone never establishes provider emptiness. + +The concrete fresh-only census also locks and reads the V1 inbound/holder closure under the Entity transaction: item references in `inventory`, `crafting_recipes.result_item_id`, `crafting_ingredients`, `room_ground_inventory`, `character_equipment`, `container_instances`, `item_instances`, `item_stacks`, and retained audit references in `item_transfer_audits.item_id` and `.item_instance_id`; logical equipment-slot references in `items`, `character_equipment`, `item_instances`, `item_stacks`, and `container_instances`; equipment group references in `items`; body-layout assignments in `characters.body_layout_key`; and character/equipment membership paths. Any such existing reference denies this globally fresh-only boundary. The transaction-held `SHARE` locks cover those relations and all V1 tenant/version-key holders—`actor_active_conditions`, `actor_resource_states`, `body_layout_slot_definitions`, `character_equipment`, `character_friend`, `characters`, `container_instances`, `crafting_ingredients`, `crafting_recipes`, `entity_mutation_effects`, `equipment_slot_definitions`, `inventory`, `item_instances`, `item_stacks`, `item_transfer_audits`, `item_visible_ref_counters`, `items`, `npcs`, and `room_ground_inventory`—after locking the local allocator and receipt relations in the fixed owner-then-source order. Legacy occupied numeric keys are seeded from actual V1 tenant/version columns; the Entity allocator chooses distinct positive keys above the actual occupied and already-reserved values rather than copying Account or Game Design identifiers. Immutable reservation and association constraints plus database writer guards protect the retained keys without changing existing Java writer paths. Those guards match only exact newly reserved tenant/version keys; writes under unrelated unassociated legacy keys remain allowed. Runtime actor/playable rows are not authored-source families and are not interpreted as such by the census. Current limitation: writes to key-holder/reference tables using the exact reserved association keys, including new runtime rows, are rejected so they cannot invalidate the retained empty-source boundary. This is not an authored-runtime family declaration or a general runtime activation policy; no activation path is added. This does not adopt legacy content or claim that an absent V1 table proves an unsupported family empty. + +The receipt uses `entity-selected-empty-source-catalogue/v1`, schema version 1, ADR-0047 byte-length framing, and a schema digest over the closed ordered field/type definition and all 23 lexical family names, including each family's evidence kind (`V1_SOURCE_CENSUS` or `EMPTY_ONLY_OWNER_PROVIDER`). It retains the complete original Account authorization bytes/digest; canonical Game Design selected-source content and source-operation binding bytes/digests from `SelectedOwnerEmptySourceInputs`; the original recipient-qualified World read request and public closure bytes/digests; Entity-allocated local keys; genesis/readback identities; and all typed family-state counts. The fourteen EMPTY-only provider rows bind those source digests and identities through an additional provider-state digest and remain immutable through retention. World inventory must be the existing v2 graph-schema-3 profile with zero population bindings and the exact ordered seven-family v1 inbound closure: `WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT`, `WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT`, `WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION`, `WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING`, `WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK`, `WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE`, and `WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING`. Missing or unreadable remote evidence denies. This is an unregistered owner-local foundation only, not a completed publication/admission proof. + ### Target-State Replacement-Instance State Classification Entity Management must classify its runtime persistence surface for cutover and migration tooling: diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 39bbc7961b..77fe40bd77 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -210,3 +210,9 @@ Entry format: - Observation: An absolute repository path inside an executable patch is a live mutation target, not artifact content. Attempting to reverse the mistake introduced a second unsafe intermediate state. No concurrent build consumed the changed or missing parser, and the original tracked file was restored; unrelated edits were preserved. - Expected pattern: Use the temporary artifact path as the only outer patch target, with implementation patch text as its contents. Report mistaken mutation immediately and let the parent choose recovery after checking running validation and concurrent ownership; do not start an independent reversal sequence. - Current status: The parent stopped reversal, verified restoration and then explicitly authorized completion in the assigned Common files after the serialized owner gate finished. Integration inspection and consolidated proof remain required before publication. + +- `2026-10-11`: Replacement-string expansion can corrupt embedded SQL regexes + - Context: Parent inspection of an unpublished V138 extension found function terminator text inserted into Entity digest and timestamp regex literals. + - Observation: The helper identified JavaScript replacement-string dollar expansion while preparing the patch. The resulting SQL block is excluded from the schema simulator, so successful schema generation would not establish its correctness. + - Expected pattern: Preserve literal replacement content with a replacement callback, inspect the resulting complete procedural block, and require actual PostgreSQL migration and negative-case execution separately from generated metadata. + - Current status: The helper corrected the literals and new inline `CASE` operands before validation or publication. Physical PostgreSQL parsing and assertion proof remain pending. 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 adac2325f4..0cb5da8177 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 @@ -6,11 +6,17 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The accepted admission boundary is [genuine original-COMMIT acknowledgement with conditional independent recovery](../../architecture/microservices/account-service/runtime-and-data.md#original-gameplay-admission-commit-acknowledgement). Guaranteed quiet-primary recovery was an experimental feasibility objective, not an accepted requirement. The local correction removes only the unwired V120 fresh-confirmation JVM calls and prototype writer fixture; additive V136 closes its SQL function and every new receipt INSERT while preserving retained rows, immutable guards, historical readers, V120 finalization stamps and V121 pending fences. The transferred V122 definitions retain concurrency/exact-winner, rollback, binding/forgery/privilege, transaction-independence, unchanged expiry and lost-receipt-acknowledgement obligations. Synthetic pre-V136 rows prove migration preservation only, never historical durability. The nine failures on the older composed candidate are not cleared by wording or unexecuted replacement definitions; corrected PostgreSQL execution and a commissioned independent correction review remain required. V122 storage/acknowledgement proof does not supply current platform restrictions, complete current Account authority or gameplay admission. +The accepted admission boundary is [genuine original-COMMIT acknowledgement with conditional independent recovery](../../architecture/microservices/account-service/runtime-and-data.md#original-gameplay-admission-commit-acknowledgement). Guaranteed quiet-primary recovery was an experimental feasibility objective, not an accepted requirement. Published correction `d4ba9edbd418d882a09417cf87bc62ea53e79b9d` removes only the unwired V120 fresh-confirmation JVM calls and prototype writer fixture; additive V136 closes its SQL function and every new receipt INSERT while preserving retained rows, immutable guards, historical readers, V120 finalization stamps and V121 pending fences. The transferred V122 definitions retain concurrency/exact-winner, rollback, binding/forgery/privilege, transaction-independence, unchanged expiry and lost-receipt-acknowledgement obligations. Synthetic pre-V136 rows prove migration preservation only, never historical durability. The exact correction received a commissioned independent zero-finding review and Overseer publication approval; this is not provider-review credit or merge readiness. The failures on older composed candidates are not cleared by wording or unexecuted replacement definitions; corrected PostgreSQL execution remains required. V122 storage/acknowledgement proof does not supply current platform restrictions, complete current Account authority or gameplay admission. -The bounded Account correction passes `generateJooq`, the complete Account `check`, integration compilation, affected formatting/static analysis and `bootJar`. Its first gate freshly executes 1,343 unit tests and 12 non-container integration tests; all 283 PostgreSQL-dependent integration cases skip locally, including the transferred finalization, synthetic-history migration and new-write-denial definitions. The final corrected gate reuses those passing unit results and recompiles/rechecks the fixed connection-owning fixture. These are local compilation and safety-definition results, not executed V136 PostgreSQL proof or independent-review completion. +The bounded Account correction passes `generateJooq`, the complete Account `check`, integration compilation, affected formatting/static analysis and `bootJar`. Its local gate executes 1,343 unit tests and 12 non-container integration tests; all 283 PostgreSQL-dependent cases skip locally. The substantive originating [Validation run 38067710993](https://github.com/benhook1013/FireMUD/actions/runs/38067710993) now completes successfully, with all 40 jobs passing. Its Account owner artifacts prove 1,343 units and 303 integrations executed with zero skips, failures or errors, including all 13 protected-entry cases and the V136 retained-history/new-write-denial and original-acknowledgement recovery cases. The actual tested merge is `b9d91aa36b2ea9fe85acd98935330c8e8d0f18b8`, tree `498745b64e4cb27c65c68cd7bfe7891e7d0cd023`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact `d4ba9ed` source; the first parent differs from the run title's recorded base. Owner XML artifact `11676209923` reports actual PostgreSQL **16.15** for the 30 lease-persistence and 13 protected-entry cases, not PostgreSQL 18. This is accepted scoped retirement/storage proof, not canonical PG18 fresh-executor proof, production privilege adoption, guaranteed historical recovery or activation. Gameplay owns the separate approved PG18 fresh-original-acknowledgement and insertion-gate convergence, reserved at V139; historical `readDurably` on PG18 remains denied. The duplicate dependency-deferred run supplies no additional proof. -The local release-proof definition replaces the genuine fixture's in-memory object store with real SDK conditional PUT and exact GET readback against the Compose-pinned ephemeral MinIO image. Its Game Design check and compilation pass, but the PostgreSQL/MinIO case skips locally; real object I/O has not yet executed on this corrected definition. Entity, publication-participant and StartSession substitutes remain, so this is not full release or activation proof. +The [fresh-empty Entity catalogue](../../architecture/microservices/entity-management-service/runtime-and-data.md#selected-entity-authored-source-inventory-empty-only-v1) combines nine actual V1 source/reference censuses with fourteen separate immutable EMPTY-only provider tables, Entity-allocated private keys, complete 23-family receipt evidence and independent provider/receipt readback. Native unregistered command and terminal-read boundaries now bind the complete original Account authorization and World freeze evidence to the exact configured workload peer before decoding or storage. Account's additive V138 accepts the closed Entity terminal receipt in its existing immutable settlement family, preserves prior Automation bytes and limits, and retains canonical source-lock ordering and independent readback. The preparation service checks its configured namespace before replay or remote reads. The complete Entity unit suite passes all 204 cases; earlier V2 schema generation and integration compilation pass, but all 13 integration definitions skip locally, including three migration and six repository cases. Narrow schema-generator exclusions preserve real PostgreSQL locks and occupied-key seeding; generation does not prove those statements. Physical V2/V138 installation, writer exclusion and genuine composed producer execution remain unproved. Sampled HELD reads, creator declarations and missing storage do not discharge continuous through-commit protection; matching reserved-key runtime writes remain restricted and no runtime path is registered or activated. + +The genuine release-proof definition now composes native Account/Game Design/World/Entity mTLS boundaries, isolated Entity PostgreSQL storage, exact provider/receipt readback and retry, and Account Entity terminal settlement. It uses a classes-only Entity proof artifact, not Entity application or migration resources on the Game Design classpath. Real SDK conditional PUT and exact GET readback replace its in-memory object store against the Compose-pinned ephemeral MinIO image, with exact durable candidate readback before each PUT. These definitions compile but skip locally; current physical Entity/Account composition and real object I/O have not executed. Entity/Automation publication-participant digests and the StartSession Account projection remain explicit doubles, so this is not full release or activation proof. + +The composed five-module local gate passes in 57 seconds: full checks, owning Account/Entity schema generation, integration compilation, classes-only proof artifact and affected boot JARs complete. Results across the corrected and preceding unchanged tasks retain 638 Common Platform, 156 Common Security, 1,346 Account, 204 Entity and 558 Game Design unit passes, without failures, errors or skips; unchanged tasks reuse their results. Account executes 12 non-container integrations and skips 286 definitions; Entity skips all 13 and Game Design all 149, for 448 skipped cases. The new V138 upgrade, closed-frame rollback, source-writer serialization and genuine Entity/MinIO composition therefore have no physical execution credit. The complete Entity suite initially exposed an older test's leaked thread-local account; symmetric before/after cleanup in the new receiver tests fixes isolation without changing production denial guards or canonical-input assertions. Architecture contracts pass all 228 cases; Flyway sanity passes 12 sets and 296 versioned files. Current PostgreSQL CI, production privileges, continuous protection and all four complete Gameplay handoffs remain open. + +## Earlier Construction Checkpoints The current construction replaces the remaining in-process Automation-retention and Account-settlement commands with distinct, unregistered native mTLS transports. The owning [Automation command](../../architecture/microservices/automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) and [Account settlement command](../../architecture/microservices/account-service/api-contracts.md#grpc-apis) retain full original evidence, independent transport correlations, exact request echoes and immutable receipt readback. Receiver authentication derives from each server's configured namespace, not a namespace supplied by the caller. The genuine PostgreSQL fixture defines a fresh native Account reserve → authenticated source read → finalize → Automation retain → Account settle flow, plus wrong-workload no-mutation, exact retry, unchanged rows and post-settlement HELD denial. Its earlier, manually reserved Entity/Automation disclosure fixtures are explicitly aborted before the fresh positive operation; those setup contexts do not establish the positive producer boundary. Entity retention and publication participation, S3 and StartSession projection remain incomplete. diff --git a/protos/account/v1/selected_owner_intake_settlement_service.proto b/protos/account/v1/selected_owner_intake_settlement_service.proto index cbf6192f16..d6e7925ae5 100644 --- a/protos/account/v1/selected_owner_intake_settlement_service.proto +++ b/protos/account/v1/selected_owner_intake_settlement_service.proto @@ -5,7 +5,7 @@ package account.v1; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; -// Standalone, unregistered command for settling one finalized Automation intake operation. +// Standalone, unregistered command for settling one finalized Entity or Automation intake operation. service AccountSelectedOwnerIntakeSettlementService { rpc SettleSelectedOwnerIntake(SelectedOwnerIntakeSettlementRequest) returns (SelectedOwnerIntakeSettlementResponse); diff --git a/protos/entity-management/v1/entity_selected_source_intake_command.proto b/protos/entity-management/v1/entity_selected_source_intake_command.proto new file mode 100644 index 0000000000..a29f838b30 --- /dev/null +++ b/protos/entity-management/v1/entity_selected_source_intake_command.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package entity_management.v1; +option java_package = "net.firedevops.firemud.entitymanagement.v1"; +option java_multiple_files = true; + +import "world-management/v1/world_selected_draft_publication_freeze_service.proto"; + +// Standalone and unregistered. Authenticated same-namespace Game Design may retain its exact +// Account-authorized selected Entity inputs after the exact World freeze has committed. +service EntitySelectedSourceIntakeCommandService { + rpc RetainSelectedEntitySource(RetainSelectedEntitySourceRequest) + returns (RetainSelectedEntitySourceResponse); +} + +message RetainSelectedEntitySourceRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string transport_request_id = 3; + bytes original_intake_authorization_binding = 4; + string intake_authorization_digest = 5; + world_management.v1.BeginVersionPublicationFreezeRequest freeze_request = 6; + world_management.v1.BeginVersionPublicationFreezeResponse freeze_acknowledgement = 7; +} + +message RetainSelectedEntitySourceResponse { + RetainSelectedEntitySourceRequest request = 1; + bytes committed_empty_receipt = 2; + string receipt_digest = 3; +} diff --git a/protos/entity-management/v1/entity_selected_source_intake_terminal_read.proto b/protos/entity-management/v1/entity_selected_source_intake_terminal_read.proto new file mode 100644 index 0000000000..4c0905b3dd --- /dev/null +++ b/protos/entity-management/v1/entity_selected_source_intake_terminal_read.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +package entity_management.v1; +option java_package = "net.firedevops.firemud.entitymanagement.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. Only the same-namespace Account workload may read. +service EntitySelectedSourceIntakeTerminalReadService { + rpc ReadSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest) + returns (ReadSelectedSourceIntakeTerminalResponse); +} + +message ReadSelectedSourceIntakeTerminalRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + string intended_reader = 4; + string terminal_read_purpose = 5; + bytes original_intake_authorization_binding = 6; + string intake_authorization_digest = 7; +} + +enum EntitySelectedSourceIntakeTerminalResult { + ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED = 0; + ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY = 1; +} + +message ReadSelectedSourceIntakeTerminalResponse { + ReadSelectedSourceIntakeTerminalRequest request = 1; + EntitySelectedSourceIntakeTerminalResult result = 2; + bytes committed_empty_receipt = 3; + string receipt_digest = 4; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java index 1d3205c67e..deaabc463f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java @@ -12,6 +12,9 @@ import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import org.springframework.transaction.PlatformTransactionManager; @@ -20,19 +23,21 @@ import org.springframework.transaction.support.TransactionTemplate; /** - * Unregistered composition for settling one exact finalized Automation intake operation. + * Unregistered composition for settling one exact finalized selected-owner intake operation. * *

The Account source reservation repository owns source-lock ordering and immutable settlement * persistence. This service only permits its pending participation to advance after an exact - * authenticated Automation COMMITTED_EMPTY receipt has been read outside SQL. + * authenticated owner COMMITTED_EMPTY receipt has been read outside SQL. */ public final class AccountSelectedOwnerIntakeSettlementService { private static final String AUTOMATION_READER = "automation-scripting-service"; + private static final String ENTITY_READER = "entity-management-service"; private static final String GAME_DESIGN_CALLER = "game-design-service"; private static final String ACCOUNT_READER = "account-service"; private final AccountSelectedOwnerIntakeSourceReservationRepository repository; private final AutomationSelectedSourceIntakeTerminalReadClient automationClient; + private final EntitySelectedSourceIntakeTerminalReadClient entityClient; private final TransactionTemplate ownerTransaction; private final String namespace; @@ -41,6 +46,16 @@ public AccountSelectedOwnerIntakeSettlementService( AutomationSelectedSourceIntakeTerminalReadClient automationClient, PlatformTransactionManager transactionManager, String namespace) { + this(repository, automationClient, null, transactionManager, namespace); + } + + public AccountSelectedOwnerIntakeSettlementService( + AccountSelectedOwnerIntakeSourceReservationRepository repository, + AutomationSelectedSourceIntakeTerminalReadClient automationClient, + EntitySelectedSourceIntakeTerminalReadClient entityClient, + PlatformTransactionManager transactionManager, + String namespace) { + this.entityClient = entityClient; this.repository = Objects.requireNonNull(repository, "source reservation repository required"); this.automationClient = Objects.requireNonNull(automationClient, "Automation client required"); if (!GrpcPeerIdentity.isValidNamespace(namespace)) { @@ -56,7 +71,7 @@ public AccountSelectedOwnerIntakeSettlementService( } /** - * Settles or recovers the exact finalized Automation authorization selected by Game Design. + * Settles or recovers the exact finalized owner authorization selected by Game Design. * *

The authorization is a lookup key, not caller authority. Account revalidates its complete * retained value before checking for an immutable prior settlement or contacting Automation. @@ -79,7 +94,7 @@ public AccountSelectedOwnerIntakeSettlementReceipt settle( return new Lookup(prior.orElse(null)); } catch (IllegalArgumentException absentOrChanged) { throw Status.FAILED_PRECONDITION - .withDescription("Exact finalized Automation authorization is unavailable") + .withDescription("Exact finalized selected-owner authorization is unavailable") .withCause(absentOrChanged) .asRuntimeException(); } @@ -93,6 +108,10 @@ public AccountSelectedOwnerIntakeSettlementReceipt settle( return requireSettlement(lookup.prior(), original, null); } + if (original.owner() == Owner.ENTITY_MANAGEMENT) { + return settleEntity(original); + } + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(namespace, original); requireNoAmbientTransaction(); @@ -138,6 +157,84 @@ public AccountSelectedOwnerIntakeSettlementReceipt settle( return readback; } + private AccountSelectedOwnerIntakeSettlementReceipt settleEntity( + SelectedOwnerIntakeAuthorizationBinding original) { + var request = + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create(namespace, original); + requireNoAmbientTransaction(); + final EntitySelectedSourceIntakeTerminalReadEvidence remote; + try { + remote = entityClient.read(request); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Entity terminal evidence is unavailable") + .withCause(unavailable) + .asRuntimeException(); + } + final EntitySelectedSourceIntakeTerminalReadEvidence exact; + try { + if (remote == null + || !request.equals(remote.request()) + || !workloadUri(namespace, ACCOUNT_READER).equals(remote.request().intendedReader()) + || !EntitySelectedSourceIntakeTerminalReadEvidence.TERMINAL_READ_PURPOSE.equals( + remote.request().terminalReadPurpose())) { + throw new IllegalArgumentException("Entity changed the complete terminal-read request"); + } + var receipt = remote.receipt(); + byte[] bytes = receipt.canonicalBytes(); + var canonical = EntityEmptySelectedSourceIntakeReceipt.fromStored(bytes); + if (bytes.length == 0 + || bytes.length > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES + || !Arrays.equals(bytes, canonical.canonicalBytes()) + || !DraftAuthorizationFenceBinding.digest(bytes).equals(receipt.receiptDigest()) + || !canonical.receiptDigest().equals(receipt.receiptDigest()) + || !"COMMITTED_EMPTY".equals(receipt.outcome()) + || !namespace.equals(receipt.targetNamespace()) + || !original.operationId().equals(receipt.operationId()) + || !original.fenceId().equals(receipt.fenceId()) + || !original.intakeRequestId().equals(receipt.intakeRequestId()) + || !original.tenantId().equals(receipt.canonicalTenantId()) + || !original.versionId().equals(receipt.canonicalVersionId()) + || !original.selected().commitId().equals(receipt.selectedCommitId()) + || !Arrays.equals(original.canonicalBytes(), receipt.authorizationBindingBytes()) + || !original.digest().equals(receipt.authorizationBindingDigest())) { + throw new IllegalArgumentException( + "Entity terminal differs from the original authorization"); + } + exact = new EntitySelectedSourceIntakeTerminalReadEvidence(request, canonical); + } catch (IllegalArgumentException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact original Entity terminal is required") + .withCause(invalid) + .asRuntimeException(); + } + requireNoAmbientTransaction(); + var committed = + ownerTransaction.execute(ignored -> repository.settleEntityCommittedEmpty(exact)); + requireSettlement(committed, original, exact); + requireNoAmbientTransaction(); + var readback = + ownerTransaction.execute( + ignored -> + Objects.requireNonNull( + repository.findSettlement(original), "Account lookup returned no result") + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Committed Account Entity settlement is not readable") + .asRuntimeException())); + requireSettlement(readback, original, exact); + if (!sameSettlement(committed, readback)) { + throw Status.FAILED_PRECONDITION + .withDescription("Committed Account Entity readback differs") + .asRuntimeException(); + } + return readback; + } + private void requireGameDesignPeer() { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer == null) { @@ -158,13 +255,19 @@ private void requireGameDesignPeer() { private void requireOriginalBinding(SelectedOwnerIntakeAuthorizationBinding original) { if (original == null - || original.owner() != Owner.AUTOMATION_SCRIPTING + || (original.owner() != Owner.AUTOMATION_SCRIPTING + && original.owner() != Owner.ENTITY_MANAGEMENT) || !namespace.equals(original.targetNamespace()) - || !"account-automation-intake-authorization/v1".equals(original.schema()) - || !"AUTOMATION_INTAKE_RETENTION".equals(original.purpose()) - || !workloadUri(namespace, AUTOMATION_READER).equals(original.intendedReader())) { + || !(original.owner() == Owner.AUTOMATION_SCRIPTING + ? "account-automation-intake-authorization/v1".equals(original.schema()) + && "AUTOMATION_INTAKE_RETENTION".equals(original.purpose()) + && workloadUri(namespace, AUTOMATION_READER).equals(original.intendedReader()) + : entityClient != null + && "account-entity-intake-authorization/v1".equals(original.schema()) + && "ENTITY_INTAKE_RETENTION".equals(original.purpose()) + && workloadUri(namespace, ENTITY_READER).equals(original.intendedReader()))) { throw Status.FAILED_PRECONDITION - .withDescription("Canonical same-namespace Automation authorization is required") + .withDescription("Canonical same-namespace selected-owner authorization is required") .asRuntimeException(); } try { @@ -179,7 +282,7 @@ private void requireOriginalBinding(SelectedOwnerIntakeAuthorizationBinding orig } } catch (IllegalArgumentException invalid) { throw Status.FAILED_PRECONDITION - .withDescription("Canonical same-namespace Automation authorization is required") + .withDescription("Canonical same-namespace selected-owner authorization is required") .withCause(invalid) .asRuntimeException(); } @@ -244,7 +347,7 @@ private AutomationSelectedSourceIntakeTerminalReadEvidence requireExactTerminal( private AccountSelectedOwnerIntakeSettlementReceipt requireSettlement( AccountSelectedOwnerIntakeSettlementReceipt receipt, SelectedOwnerIntakeAuthorizationBinding original, - AutomationSelectedSourceIntakeTerminalReadEvidence expectedOwnerTerminal) { + Object expectedOwnerTerminal) { if (receipt == null) { throw Status.FAILED_PRECONDITION .withDescription("Account terminal settlement receipt is unavailable") @@ -257,23 +360,30 @@ private AccountSelectedOwnerIntakeSettlementReceipt requireSettlement( || !namespace.equals(receipt.targetNamespace()) || !Arrays.equals( original.canonicalBytes(), - receipt.terminalEvidence().request().binding().canonicalBytes())) { + (original.owner() == Owner.ENTITY_MANAGEMENT + ? receipt.entityTerminalEvidence().request().binding() + : receipt.terminalEvidence().request().binding()) + .canonicalBytes())) { throw new IllegalArgumentException("Account settlement changed the original binding"); } AccountSelectedOwnerIntakeSettlementReceipt canonical = - AccountSelectedOwnerIntakeSettlementReceipt.create(receipt.terminalEvidence()); + original.owner() == Owner.ENTITY_MANAGEMENT + ? AccountSelectedOwnerIntakeSettlementReceipt.create(receipt.entityTerminalEvidence()) + : AccountSelectedOwnerIntakeSettlementReceipt.create(receipt.terminalEvidence()); if (!Arrays.equals(canonical.canonicalBytes(), receipt.canonicalBytes()) || !canonical.digest().equals(receipt.digest()) - || (expectedOwnerTerminal != null - && !receipt.sameImmutableOwnerReceipt(expectedOwnerTerminal))) { + || (expectedOwnerTerminal + instanceof AutomationSelectedSourceIntakeTerminalReadEvidence automation + && !receipt.sameImmutableOwnerReceipt(automation)) + || (expectedOwnerTerminal instanceof EntitySelectedSourceIntakeTerminalReadEvidence entity + && !receipt.sameImmutableOwnerReceipt(entity))) { throw new IllegalArgumentException( "Account settlement receipt changed its canonical owner value"); } return receipt; } catch (IllegalArgumentException invalid) { throw Status.FAILED_PRECONDITION - .withDescription( - "Account settlement receipt differs from the original Automation terminal") + .withDescription("Account settlement receipt differs from the original owner terminal") .withCause(invalid) .asRuntimeException(); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java index f4800b8fbf..ec50e5e71b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; import org.jooq.DSLContext; import org.jooq.Record; @@ -338,7 +339,8 @@ Optional findSettlement( SelectedOwnerIntakeAuthorizationBinding requested) { requireTransaction(); Objects.requireNonNull(requested, "original selected-owner authorization is required"); - if (requested.owner() != Owner.AUTOMATION_SCRIPTING) { + if (requested.owner() != Owner.AUTOMATION_SCRIPTING + && requested.owner() != Owner.ENTITY_MANAGEMENT) { throw new IllegalArgumentException("Automation terminal settlement required"); } SelectedOwnerIntakeSourceReadScope scope = requested.content().scope(); @@ -404,23 +406,65 @@ AccountSelectedOwnerIntakeSettlementReceipt settleCommittedEmpty( return exactSettlement(settlement(requested.operationId()), requested, evidence); } + AccountSelectedOwnerIntakeSettlementReceipt settleEntityCommittedEmpty( + EntitySelectedSourceIntakeTerminalReadEvidence evidence) { + requireTransaction(); + Objects.requireNonNull(evidence, "Entity terminal evidence is required"); + var requested = evidence.request().binding(); + if (requested.owner() != Owner.ENTITY_MANAGEMENT + || !"COMMITTED_EMPTY".equals(evidence.receipt().outcome())) { + throw new IllegalArgumentException("Exact Entity COMMITTED_EMPTY evidence required"); + } + SelectedOwnerIntakeSourceReadScope scope = requested.content().scope(); + lockReservedSources(scope); + requireReservation(reservation(scope), scope); + Record order = authorization(requested.operationId()); + requireAuthorization(order, requested); + if (aborted(scope)) + throw new IllegalArgumentException("Finalized owner authorization was aborted"); + + Record prior = settlement(requested.operationId()); + if (prior != null) return exactSettlement(prior, requested, evidence); + + AccountSelectedOwnerIntakeSettlementReceipt receipt = + AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + dsl.execute( + "INSERT INTO " + + SETTLEMENTS + + " (operation_id, fence_id, intake_request_id, owner, target_namespace, tenant_uuid, " + + "version_uuid, binding_bytes, binding_digest, terminal_read_request_id, " + + "terminal_receipt_bytes, terminal_receipt_digest, receipt_bytes, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.operationId(), + requested.fenceId(), + requested.intakeRequestId(), + requested.owner().name(), + requested.targetNamespace(), + requested.tenantId(), + requested.versionId(), + requested.canonicalBytes(), + requested.digest(), + evidence.request().readRequestId(), + receipt.ownerReceiptBytes(), + receipt.ownerReceiptDigest(), + receipt.canonicalBytes(), + receipt.digest()); + return exactSettlement(settlement(requested.operationId()), requested, evidence); + } + private AccountSelectedOwnerIntakeSettlementReceipt exactSettlement( - Record row, - SelectedOwnerIntakeAuthorizationBinding requested, - AutomationSelectedSourceIntakeTerminalReadEvidence retryEvidence) { + Record row, SelectedOwnerIntakeAuthorizationBinding requested, Object retryEvidence) { if (row == null) throw new IllegalStateException("Account settlement commit readback absent"); byte[] storedBytes = row.get("receipt_bytes", byte[].class); var receipt = AccountSelectedOwnerIntakeSettlementReceipt.fromStored(storedBytes); var original = receipt.authorizationBinding(); - var request = receipt.terminalEvidence().request(); - var ownerReceipt = receipt.terminalEvidence().receipt(); if (!Arrays.equals(original.canonicalBytes(), requested.canonicalBytes()) || !Arrays.equals(storedBytes, receipt.canonicalBytes()) || !receipt.digest().equals(row.get("receipt_digest", String.class)) || !Arrays.equals( - ownerReceipt.canonicalBytes(), row.get("terminal_receipt_bytes", byte[].class)) - || !ownerReceipt.receiptDigest().equals(row.get("terminal_receipt_digest", String.class)) - || !request.readRequestId().equals(row.get("terminal_read_request_id", UUID.class)) + receipt.ownerReceiptBytes(), row.get("terminal_receipt_bytes", byte[].class)) + || !receipt.ownerReceiptDigest().equals(row.get("terminal_receipt_digest", String.class)) + || !receipt.terminalReadRequestId().equals(row.get("terminal_read_request_id", UUID.class)) || !original.operationId().equals(row.get("operation_id", UUID.class)) || !original.fenceId().equals(row.get("fence_id", UUID.class)) || !original.intakeRequestId().equals(row.get("intake_request_id", UUID.class)) @@ -432,9 +476,14 @@ private AccountSelectedOwnerIntakeSettlementReceipt exactSettlement( || !original.digest().equals(row.get("binding_digest", String.class))) { throw new IllegalArgumentException("Changed exact selected-owner terminal settlement"); } - if (retryEvidence != null && !receipt.sameImmutableOwnerReceipt(retryEvidence)) { + if (retryEvidence instanceof AutomationSelectedSourceIntakeTerminalReadEvidence automation + && !receipt.sameImmutableOwnerReceipt(automation)) { throw new IllegalArgumentException("Changed Automation owner terminal receipt"); } + if (retryEvidence instanceof EntitySelectedSourceIntakeTerminalReadEvidence entity + && !receipt.sameImmutableOwnerReceipt(entity)) { + throw new IllegalArgumentException("Changed Entity owner terminal receipt"); + } return receipt; } diff --git a/services/account-service/src/main/resources/db/migration/V138__entity_selected_owner_intake_terminal_settlement.sql b/services/account-service/src/main/resources/db/migration/V138__entity_selected_owner_intake_terminal_settlement.sql new file mode 100644 index 0000000000..1219ca264f --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V138__entity_selected_owner_intake_terminal_settlement.sql @@ -0,0 +1,708 @@ +-- Add Entity's authenticated closed COMMITTED_EMPTY receipt to the existing immutable family. +-- V135 Automation rows and receipt bytes are retained exactly; no pending predicate changes. +-- [jooq ignore start] +DO $migration$ +DECLARE + check_row RECORD; + expected_limit TEXT; + changed_count INTEGER := 0; +BEGIN + FOR check_row IN + SELECT constraint_row.conname, attribute_row.attname, + pg_get_constraintdef(constraint_row.oid) AS definition + FROM pg_constraint constraint_row + JOIN pg_attribute attribute_row + ON attribute_row.attrelid = constraint_row.conrelid + AND constraint_row.conkey = ARRAY[attribute_row.attnum]::SMALLINT[] + WHERE constraint_row.conrelid = 'account_selected_owner_intake_settlements'::REGCLASS + AND constraint_row.contype = 'c' + AND attribute_row.attname IN ('owner', 'terminal_receipt_bytes', 'receipt_bytes') + LOOP + expected_limit := CASE check_row.attname WHEN 'owner' THEN 'AUTOMATION_SCRIPTING' + WHEN 'terminal_receipt_bytes' THEN '58736640' ELSE '92356608' END; + IF position(expected_limit IN check_row.definition) = 0 THEN + RAISE EXCEPTION 'Unexpected retained V135 settlement constraint: %', check_row.conname; + END IF; + EXECUTE format('ALTER TABLE account_selected_owner_intake_settlements DROP CONSTRAINT %I', + check_row.conname); + changed_count := changed_count + 1; + END LOOP; + IF changed_count <> 3 THEN + RAISE EXCEPTION 'Expected all three retained V135 settlement constraints'; + END IF; +END; +$migration$; +-- [jooq ignore stop] +ALTER TABLE account_selected_owner_intake_settlements + ADD CONSTRAINT selected_owner_settlement_owner_check + CHECK (owner IN ('AUTOMATION_SCRIPTING', 'ENTITY_MANAGEMENT')), + ADD CONSTRAINT selected_owner_settlement_terminal_size_check + CHECK (octet_length(terminal_receipt_bytes) >= 1 AND + ((owner = 'AUTOMATION_SCRIPTING' AND octet_length(terminal_receipt_bytes) <= 58736640) + OR (owner = 'ENTITY_MANAGEMENT' AND octet_length(terminal_receipt_bytes) <= 83886080))), + ADD CONSTRAINT selected_owner_settlement_receipt_size_check + CHECK (octet_length(receipt_bytes) >= 1 AND + ((owner = 'AUTOMATION_SCRIPTING' AND octet_length(receipt_bytes) <= 92356608) + OR (owner = 'ENTITY_MANAGEMENT' AND octet_length(receipt_bytes) <= 117506048))); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_selected_owner_intake_settlement_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_selected_owner_intake_authorizations%ROWTYPE; + reservation account_selected_owner_intake_source_read_reservations%ROWTYPE; + p INTEGER := 1; + q INTEGER := 1; + source_position INTEGER := 1; + receipt_position INTEGER := 1; + parsed BYTEA; + binding_scope BYTEA; + content_bytes BYTEA; + selected_bytes BYTEA; + terminal_binding BYTEA; + owner_receipt BYTEA; + world_request_bytes BYTEA; + world_inventory_bytes BYTEA; + source_bytes BYTEA; + source_kind TEXT; + source_scope TEXT; + source_key_value TEXT; + previous_sort_key INTEGER[]; + current_sort_key INTEGER[]; + namespace_value TEXT; + request_id_value UUID; + owner_world_request_id UUID; + count_text TEXT; + count_value INTEGER; + index_value INTEGER; + local_key_value BIGINT; + local_key_text TEXT; + first_local_key_text TEXT; + request_digest_text TEXT; + ignored_text TEXT; + marker TEXT; + retained_timestamp TIMESTAMPTZ; + template_snapshot JSONB; + entity_declaration JSONB; + revision_bytes BYTEA; + schema_bytes BYTEA := ''::BYTEA; + schema_digest_text TEXT; + expected_family TEXT; + entity_families TEXT[] := ARRAY['ACTOR_BODY_LAYOUT_ASSIGNMENTS', 'ARCHETYPE_ASSIGNMENTS', 'ARCHETYPE_CONSTRAINTS', 'ARCHETYPE_ROOTS', 'BALANCE_CURVE_ATTACHMENTS', 'BALANCE_CURVE_ROOTS', 'BODY_LAYOUT_MEMBERSHIPS', 'BODY_LAYOUT_ROOTS', 'CRAFTING_INGREDIENT_BINDINGS', 'CRAFTING_RECIPE_RESULT_BINDINGS', 'CRAFTING_RECIPE_ROOTS', 'EQUIPMENT_ATTACHMENT_RULES', 'EQUIPMENT_CAPABILITIES', 'EQUIPMENT_COMPATIBILITY_RULES', 'EQUIPMENT_OCCUPANCY_RULES', 'EQUIPMENT_SLOT_GROUPS', 'EQUIPMENT_SLOT_ROOTS', 'INBOUND_LOOT_BINDINGS', 'ITEM_TEMPLATE_ROOTS', 'LOOT_ITEM_MAPPINGS', 'LOOT_TABLE_ROOTS', 'NPC_TEMPLATE_ROOTS', 'OTHER_ACTOR_TEMPLATE_ROOTS']; +BEGIN + -- Source writers and settlement serialize on Account's retained source rows in canonical + -- sort order, followed by reservation, final authorization, then this settlement identity. + PERFORM lock_row.source_key + FROM account_draft_authorization_source_locks lock_row + JOIN account_selected_owner_intake_source_read_sources source + ON source.source_key = lock_row.source_key + WHERE source.operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(lock_row.source_key) + FOR UPDATE OF lock_row; + SELECT * INTO STRICT reservation + FROM account_selected_owner_intake_source_read_reservations + WHERE operation_id = NEW.operation_id FOR UPDATE; + SELECT * INTO STRICT original + FROM account_selected_owner_intake_authorizations + WHERE operation_id = NEW.operation_id FOR UPDATE; + PERFORM operation_id FROM account_selected_owner_intake_settlements + WHERE operation_id = NEW.operation_id FOR UPDATE; + + IF FOUND + OR EXISTS (SELECT 1 FROM account_selected_owner_intake_source_read_aborts + WHERE operation_id = NEW.operation_id) + OR NEW.operation_id IS DISTINCT FROM original.operation_id + OR NEW.fence_id IS DISTINCT FROM original.fence_id + OR NEW.intake_request_id IS DISTINCT FROM original.intake_request_id + OR NEW.owner IS DISTINCT FROM original.owner + OR NEW.target_namespace IS DISTINCT FROM original.target_namespace + OR NEW.tenant_uuid IS DISTINCT FROM original.tenant_uuid + OR NEW.version_uuid IS DISTINCT FROM original.version_uuid + OR original.owner NOT IN ('AUTOMATION_SCRIPTING', 'ENTITY_MANAGEMENT') + OR reservation.owner IS DISTINCT FROM original.owner + OR reservation.operation_id IS DISTINCT FROM original.operation_id + OR reservation.fence_id IS DISTINCT FROM original.fence_id + OR reservation.intake_request_id IS DISTINCT FROM original.intake_request_id + OR reservation.actor_account_uuid IS DISTINCT FROM original.actor_account_uuid + OR reservation.tenant_uuid IS DISTINCT FROM original.tenant_uuid + OR reservation.version_uuid IS DISTINCT FROM original.version_uuid + OR NEW.binding_bytes IS DISTINCT FROM original.binding_bytes + OR NEW.binding_digest IS DISTINCT FROM original.binding_digest + OR original.binding_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(original.binding_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement must bind one exact active Automation authorization' + USING ERRCODE = '23514'; + END IF; + + -- Recheck every finalized source child against both the complete immutable binding and the + -- retained preliminary child vector. A digest or parent-row match alone is insufficient. + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN 'account-automation-intake-authorization/v1' ELSE 'account-entity-intake-authorization/v1' END) THEN + RAISE EXCEPTION 'Settlement original binding is not Automation authorization' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO content_bytes, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM 'sha256:' || encode(sha256(content_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement original content digest differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM 'spiffe://firemud/ns/' || original.target_namespace || (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN '/sa/automation-scripting-service' ELSE '/sa/entity-management-service' END) THEN + RAISE EXCEPTION 'Settlement original retention reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF marker IS DISTINCT FROM (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN 'AUTOMATION_INTAKE_RETENTION' ELSE 'ENTITY_INTAKE_RETENTION' END) THEN + RAISE EXCEPTION 'Settlement original retention purpose differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO count_text, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + IF count_text !~ '^[1-9][0-9]*$' THEN + RAISE EXCEPTION 'Settlement original source count is malformed' USING ERRCODE = '23514'; + END IF; + count_value := count_text::INTEGER; + IF count_value > 256 THEN + RAISE EXCEPTION 'Settlement original source vector exceeds its bound' + USING ERRCODE = '23514'; + END IF; + + q := 1; + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'game-design-selected-owner-intake-source/v1' THEN + RAISE EXCEPTION 'Settlement original selected content schema differs' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO binding_scope, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF marker IS DISTINCT FROM 'sha256:' || encode(sha256(binding_scope), 'hex') + OR binding_scope IS DISTINCT FROM reservation.scope_bytes + OR reservation.scope_digest IS DISTINCT FROM 'sha256:' || encode(sha256(binding_scope), 'hex') + OR original.content_bytes IS DISTINCT FROM content_bytes + OR original.content_digest IS DISTINCT FROM 'sha256:' || encode(sha256(content_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement original selected scope or content differs' + USING ERRCODE = '23514'; + END IF; + -- The finalized binding contains six exact selected family frames after its scope header. + FOREACH ignored_text IN ARRAY ARRAY['COMMAND', 'REALM_POLICY', 'ASSET', 'GAMEPLAY_RULE', 'BRANDING', 'TEMPLATE_CONFIG'] LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT frame_value, next_position INTO parsed, q + FROM account_publication_authorization_read_frame(content_bytes, q); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, q + FROM account_publication_authorization_read_frame(content_bytes, q); + IF ignored_text = 'TEMPLATE_CONFIG' AND original.owner = 'ENTITY_MANAGEMENT' THEN + template_snapshot := convert_from(parsed, 'UTF8')::JSONB; + END IF; + IF marker IS DISTINCT FROM ignored_text + OR namespace_value IS DISTINCT FROM 'sha256:' || encode(sha256(parsed), 'hex') THEN + RAISE EXCEPTION 'Settlement selected family snapshot differs' USING ERRCODE = '23514'; + END IF; + END LOOP; + IF q <> octet_length(content_bytes) + 1 THEN + RAISE EXCEPTION 'Settlement selected content has trailing bytes' USING ERRCODE = '23514'; + END IF; + + -- Bind the full preliminary scope tuple and selected-target JSON to all retained columns. + source_position := 1; + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN 'account-automation-intake-source-read/v1' ELSE 'account-entity-intake-source-read/v1' END) THEN + RAISE EXCEPTION 'Settlement original preliminary scope schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM original.owner THEN + RAISE EXCEPTION 'Settlement original scope owner differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + FOR index_value IN 1..4 LOOP + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF index_value = 1 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.operation_id::TEXT + OR index_value = 2 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.fence_id::TEXT + OR index_value = 3 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM NEW.intake_request_id::TEXT + OR index_value = 4 AND convert_from(parsed, 'UTF8') IS DISTINCT FROM original.actor_account_uuid::TEXT THEN + RAISE EXCEPTION 'Settlement operation scope tuple differs' USING ERRCODE = '23514'; + END IF; + END LOOP; + SELECT frame_value, next_position INTO selected_bytes, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF namespace_value IS DISTINCT FROM NEW.target_namespace + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(selected_bytes), 'hex') + OR convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR convert_from(selected_bytes, 'UTF8')::JSONB->>'canonicalVersionId' IS DISTINCT FROM NEW.version_uuid::TEXT THEN + RAISE EXCEPTION 'Settlement original selected scope differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM 'spiffe://firemud/ns/' || NEW.target_namespace || '/sa/account-service' THEN + RAISE EXCEPTION 'Settlement source scope reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, source_position + FROM account_publication_authorization_read_frame(binding_scope, source_position); + IF marker IS DISTINCT FROM (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN 'AUTOMATION_INTAKE_SOURCE' ELSE 'ENTITY_INTAKE_SOURCE' END) + OR source_position <> octet_length(binding_scope) + 1 THEN + RAISE EXCEPTION 'Settlement source scope purpose or trailing bytes differ' + USING ERRCODE = '23514'; + END IF; + + FOR index_value IN 1..count_value LOOP + SELECT frame_value, next_position INTO source_bytes, p + FROM account_publication_authorization_read_frame(original.binding_bytes, p); + source_position := 1; + SELECT frame_value, next_position INTO parsed, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-draft-source-evidence/v1' THEN + RAISE EXCEPTION 'Settlement source evidence schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_kind, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO source_scope, source_position + FROM account_publication_authorization_read_frame(source_bytes, source_position); + source_key_value := source_kind || ':' || source_scope; + current_sort_key := account_publication_authorization_source_sort_key(source_key_value); + IF previous_sort_key IS NOT NULL AND current_sort_key <= previous_sort_key THEN + RAISE EXCEPTION 'Settlement source vector is duplicated or unordered' + USING ERRCODE = '23514'; + END IF; + previous_sort_key := current_sort_key; + IF NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_sources source + WHERE source.operation_id = NEW.operation_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) + OR NOT EXISTS ( + SELECT 1 FROM account_selected_owner_intake_source_read_sources source + WHERE source.operation_id = NEW.operation_id + AND source.source_key = source_key_value + AND source.source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Settlement source child differs from complete original vector' + USING ERRCODE = '23514'; + END IF; + END LOOP; + IF p <> octet_length(original.binding_bytes) + 1 + OR count_value IS DISTINCT FROM (SELECT count(*) FROM account_selected_owner_intake_sources + WHERE operation_id = NEW.operation_id) + OR count_value IS DISTINCT FROM (SELECT count(*) FROM account_selected_owner_intake_source_read_sources + WHERE operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'Settlement source child vector is incomplete' USING ERRCODE = '23514'; + END IF; + + IF NEW.receipt_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.receipt_bytes), 'hex') + OR NEW.terminal_receipt_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_receipt_bytes), 'hex') THEN + RAISE EXCEPTION 'Settlement or Automation receipt digest differs' USING ERRCODE = '23514'; + END IF; + p := 1; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF convert_from(parsed, 'UTF8') IS DISTINCT FROM 'account-selected-owner-intake-settlement/v1' THEN + RAISE EXCEPTION 'Settlement receipt schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Settlement receipt version differs' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF parsed IS DISTINCT FROM NEW.binding_bytes THEN + RAISE EXCEPTION 'Settlement receipt changed original binding bytes' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM NEW.binding_digest THEN + RAISE EXCEPTION 'Settlement receipt changed original binding digest' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Settlement terminal request schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + BEGIN request_id_value := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Settlement terminal read correlation is malformed' USING ERRCODE = '23514'; END; + IF request_id_value = '00000000-0000-0000-0000-000000000000'::UUID + OR request_id_value::TEXT IS DISTINCT FROM ignored_text + OR request_id_value = NEW.operation_id OR request_id_value = NEW.fence_id + OR request_id_value = NEW.intake_request_id + OR request_id_value IS DISTINCT FROM NEW.terminal_read_request_id THEN + RAISE EXCEPTION 'Settlement terminal read correlation differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF namespace_value IS DISTINCT FROM NEW.target_namespace + OR marker IS DISTINCT FROM 'spiffe://firemud/ns/' || NEW.target_namespace || '/sa/account-service' THEN + RAISE EXCEPTION 'Settlement terminal reader differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF marker IS DISTINCT FROM (CASE original.owner WHEN 'AUTOMATION_SCRIPTING' THEN 'AUTOMATION_INTAKE_TERMINAL_READ' ELSE 'ENTITY_INTAKE_TERMINAL_READ' END) THEN + RAISE EXCEPTION 'Settlement terminal read purpose differs' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO terminal_binding, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF terminal_binding IS DISTINCT FROM NEW.binding_bytes OR marker IS DISTINCT FROM NEW.binding_digest THEN + RAISE EXCEPTION 'Settlement terminal request changed original Account binding' + USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO owner_receipt, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(NEW.receipt_bytes, p); + IF owner_receipt IS DISTINCT FROM NEW.terminal_receipt_bytes + OR marker IS DISTINCT FROM NEW.terminal_receipt_digest + OR p <> octet_length(NEW.receipt_bytes) + 1 THEN + RAISE EXCEPTION 'Settlement receipt differs from exact Automation terminal bytes' + USING ERRCODE = '23514'; + END IF; + + IF original.owner = 'AUTOMATION_SCRIPTING' THEN + -- The owner receipt has a closed canonical frame and embeds the complete same binding. + p := 1; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM 'automation-empty-selected-source-intake-receipt/v1' THEN + RAISE EXCEPTION 'Automation terminal receipt schema is not COMMITTED_EMPTY' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Automation terminal receipt version differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO namespace_value, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + FOR index_value IN 1..8 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF index_value = 1 AND marker IS DISTINCT FROM NEW.operation_id::TEXT + OR index_value = 2 AND marker IS DISTINCT FROM NEW.fence_id::TEXT + OR index_value = 3 AND marker IS DISTINCT FROM NEW.intake_request_id::TEXT + OR index_value = 4 AND marker IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR index_value = 5 AND marker IS DISTINCT FROM NEW.version_uuid::TEXT + OR index_value = 6 AND marker IS DISTINCT FROM convert_from(selected_bytes, 'UTF8')::JSONB->>'commitId' THEN + RAISE EXCEPTION 'Automation terminal identity differs from original order' + USING ERRCODE = '23514'; + END IF; + IF index_value = 7 THEN + BEGIN PERFORM marker::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation source revision identity is malformed' + USING ERRCODE = '23514'; END; + IF marker::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR marker::UUID::TEXT IS DISTINCT FROM marker THEN + RAISE EXCEPTION 'Automation source revision identity is noncanonical' + USING ERRCODE = '23514'; + END IF; + ELSIF index_value = 8 AND marker !~ '^(0|[1-9][0-9]*)$' THEN + RAISE EXCEPTION 'Automation source revision order is noncanonical' + USING ERRCODE = '23514'; + END IF; + END LOOP; + -- Skip source declaration and local key/request metadata, then verify the full bound receipt + -- digest and authorization bytes before consuming the independent World evidence frames. + FOR index_value IN 1..3 LOOP + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF index_value < 3 THEN + local_key_text := convert_from(parsed, 'UTF8'); + BEGIN local_key_value := local_key_text::BIGINT; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation local key is malformed' USING ERRCODE = '23514'; END; + IF local_key_value <= 0 OR local_key_value::TEXT IS DISTINCT FROM local_key_text + OR (index_value = 2 AND local_key_text IS NOT DISTINCT FROM first_local_key_text) THEN + RAISE EXCEPTION 'Automation local key is noncanonical or repeated' + USING ERRCODE = '23514'; + END IF; + IF index_value = 1 THEN first_local_key_text := local_key_text; END IF; + ELSE + request_digest_text := convert_from(parsed, 'UTF8'); + IF request_digest_text !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation caller request digest is malformed' + USING ERRCODE = '23514'; + END IF; + END IF; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM NEW.binding_digest OR parsed IS DISTINCT FROM NEW.binding_bytes THEN + RAISE EXCEPTION 'Automation terminal receipt changed full original binding' + USING ERRCODE = '23514'; + END IF; + IF namespace_value IS DISTINCT FROM NEW.target_namespace THEN + RAISE EXCEPTION 'Automation terminal namespace differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + BEGIN owner_world_request_id := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation World read correlation is malformed' USING ERRCODE = '23514'; END; + IF owner_world_request_id = '00000000-0000-0000-0000-000000000000'::UUID + OR owner_world_request_id::TEXT IS DISTINCT FROM ignored_text THEN + RAISE EXCEPTION 'Automation World read correlation is noncanonical' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation World request digest is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_request_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_request_bytes) NOT BETWEEN 1 AND 33554432 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_request_bytes), 'hex') THEN + RAISE EXCEPTION 'Automation World request bytes or digest differ' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Automation World inventory digest is malformed' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_inventory_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_inventory_bytes) NOT BETWEEN 1 AND 8388608 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_inventory_bytes), 'hex') THEN + RAISE EXCEPTION 'Automation World inventory bytes or digest differ' USING ERRCODE = '23514'; + END IF; + -- COMMITTED_EMPTY is represented only by a complete all-zero three-family census. + FOR index_value IN 1..12 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO count_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF count_text !~ '^(0|[1-9][0-9]*)$' OR count_text::BIGINT <> 0 THEN + RAISE EXCEPTION 'Automation COMMITTED_EMPTY receipt contains a nonempty census' + USING ERRCODE = '23514'; + END IF; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF ignored_text !~ '^(?:[0-9]{4}|-[0-9]{4}|-[1-9][0-9]{4,8}|[+][1-9][0-9]{4,8})-[0-9]{2}-[0-9]{2}T(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9](?:[.](?:[0-9]{3}|[0-9]{6}|[0-9]{9}))?)?Z$' + OR ignored_text ~ '^-0000-' + OR ignored_text ~ 'T(?:[01][0-9]|2[0-3]):[0-5][0-9]:00Z$' + OR ignored_text ~ '[.]000Z$' + OR ignored_text ~ '[.][0-9]{3}000Z$' + OR ignored_text ~ '[.][0-9]{6}000Z$' + OR p <> octet_length(owner_receipt) + 1 THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp or trailing bytes are invalid' + USING ERRCODE = '23514'; + END IF; + BEGIN retained_timestamp := ignored_text::TIMESTAMPTZ; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp is malformed' + USING ERRCODE = '23514'; END; + IF retained_timestamp IS NULL THEN + RAISE EXCEPTION 'Automation terminal receipt timestamp is absent' + USING ERRCODE = '23514'; + END IF; + + ELSE + -- Entity terminal bytes are a distinct closed owner receipt. Provider-row existence is + -- established by the authenticated Entity terminal reader, never inferred by Account. + p := 1; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM 'entity-selected-empty-source-catalogue/v1' THEN + RAISE EXCEPTION 'Entity terminal receipt schema differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM '1' THEN + RAISE EXCEPTION 'Entity terminal receipt version differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO schema_digest_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + FOREACH ignored_text IN ARRAY (ARRAY[ + 'entity-selected-empty-source-catalogue-schema/v1', + 'entity-selected-empty-source-catalogue/v1', + '1', + 'encoding=ADR-0047-byte-length-frames;strings=UTF-8;counts=canonical-decimal', + 'targetNamespace:utf8', + 'authorizationBindingBytes:canonical-original-account-binding', + 'authorizationBindingDigest:sha256', + 'selectedSourceBytes:canonical-game-design-source-content', + 'selectedSourceDigest:sha256', + 'selectedSourceRevisionBindingBytes:canonical-game-design-source-operation-binding', + 'selectedSourceRevisionBindingDigest:sha256', + 'worldReadRequestBytes:canonical-recipient-qualified-world-request', + 'worldReadRequestDigest:sha256', + 'worldClosureBytes:canonical-public-world-inventory', + 'worldClosureDigest:sha256', + 'localTenantKey:positive-canonical-decimal', + 'localVersionKey:positive-canonical-decimal', + 'familyStates:count-then-23-lexical-family-records-with-provider-kind', + 'genesisId:canonical-uuid', + 'requestDigest:sha256', + 'worldReadRequestId:canonical-uuid', + 'retainedAt:canonical-utc-offset-date-time', + 'familyRecordFields=count-then-family,state,evidenceKind,rowCount,unqualifiedRowCount,retainedRowCount,selectedScopeRowCount,referenceCount', + 'family:utf8', + 'state=EMPTY', + 'evidenceKind=V1_SOURCE_CENSUS|EMPTY_ONLY_OWNER_PROVIDER', + 'rowCount:canonical-nonnegative-decimal', + 'unqualifiedRowCount:canonical-nonnegative-decimal', + 'retainedRowCount:canonical-nonnegative-decimal', + 'selectedScopeRowCount:canonical-nonnegative-decimal', + 'referenceCount:canonical-nonnegative-decimal', + '23' + ] || entity_families) LOOP + parsed := convert_to(ignored_text, 'UTF8'); + schema_bytes := schema_bytes || int4send(octet_length(parsed)) || parsed; + END LOOP; + IF schema_digest_text IS DISTINCT FROM 'sha256:' || encode(sha256(schema_bytes), 'hex') THEN + RAISE EXCEPTION 'Entity terminal schema digest differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM NEW.target_namespace THEN + RAISE EXCEPTION 'Entity terminal namespace differs' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF parsed IS DISTINCT FROM NEW.binding_bytes OR marker IS DISTINCT FROM NEW.binding_digest THEN + RAISE EXCEPTION 'Entity terminal changed original authorization' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO parsed, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF parsed IS DISTINCT FROM content_bytes + OR marker IS DISTINCT FROM original.content_digest THEN + RAISE EXCEPTION 'Entity terminal changed original selected source' USING ERRCODE = '23514'; + END IF; + IF template_snapshot->>'schema' IS DISTINCT FROM 'game-design-template-config-source-snapshot/v2' + OR jsonb_typeof(template_snapshot->'ownerSourceInventoryDeclarations') IS DISTINCT FROM 'array' + OR (SELECT count(*) FROM jsonb_array_elements(template_snapshot->'ownerSourceInventoryDeclarations') declaration + WHERE declaration->>'owner' = 'ENTITY_MANAGEMENT') <> 1 THEN + RAISE EXCEPTION 'Entity original typed source declaration is unavailable' USING ERRCODE = '23514'; + END IF; + SELECT declaration INTO STRICT entity_declaration + FROM jsonb_array_elements(template_snapshot->'ownerSourceInventoryDeclarations') declaration + WHERE declaration->>'owner' = 'ENTITY_MANAGEMENT'; + SELECT frame_value, next_position INTO revision_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(revision_bytes) NOT BETWEEN 1 AND 4194304 + OR revision_bytes IS DISTINCT FROM convert_to(entity_declaration->>'sourceBindingJson', 'UTF8') + OR marker IS DISTINCT FROM entity_declaration->>'sourceBindingDigest' + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(revision_bytes), 'hex') THEN + RAISE EXCEPTION 'Entity terminal changed original source revision binding' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_request_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_request_bytes) NOT BETWEEN 1 AND 33554432 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_request_bytes), 'hex') THEN + RAISE EXCEPTION 'Entity World request bytes or digest differ' USING ERRCODE = '23514'; + END IF; + SELECT frame_value, next_position INTO world_inventory_bytes, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF octet_length(world_inventory_bytes) NOT BETWEEN 1 AND 8388608 + OR marker IS DISTINCT FROM 'sha256:' || encode(sha256(world_inventory_bytes), 'hex') THEN + RAISE EXCEPTION 'Entity World closure bytes or digest differ' USING ERRCODE = '23514'; + END IF; + FOR index_value IN 1..2 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO local_key_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + BEGIN local_key_value := local_key_text::BIGINT; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Entity local key is malformed' USING ERRCODE = '23514'; END; + IF local_key_value <= 0 OR local_key_value::TEXT IS DISTINCT FROM local_key_text + OR (index_value = 2 AND local_key_text IS NOT DISTINCT FROM first_local_key_text) THEN + RAISE EXCEPTION 'Entity local key is noncanonical or repeated' USING ERRCODE = '23514'; + END IF; + IF index_value = 1 THEN first_local_key_text := local_key_text; END IF; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM '23' THEN + RAISE EXCEPTION 'Entity terminal requires all 23 families' USING ERRCODE = '23514'; + END IF; + FOREACH expected_family IN ARRAY entity_families LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM expected_family THEN + RAISE EXCEPTION 'Entity terminal family order differs' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM 'EMPTY' THEN + RAISE EXCEPTION 'Entity terminal family is not EMPTY' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM (CASE WHEN expected_family IN ( + 'ITEM_TEMPLATE_ROOTS', 'NPC_TEMPLATE_ROOTS', 'CRAFTING_RECIPE_ROOTS', + 'CRAFTING_RECIPE_RESULT_BINDINGS', 'CRAFTING_INGREDIENT_BINDINGS', + 'EQUIPMENT_SLOT_ROOTS', 'EQUIPMENT_SLOT_GROUPS', 'BODY_LAYOUT_ROOTS', + 'BODY_LAYOUT_MEMBERSHIPS') THEN 'V1_SOURCE_CENSUS' ELSE 'EMPTY_ONLY_OWNER_PROVIDER' END) THEN + RAISE EXCEPTION 'Entity terminal family evidence kind differs' USING ERRCODE = '23514'; + END IF; + FOR index_value IN 1..5 LOOP + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker IS DISTINCT FROM '0' THEN + RAISE EXCEPTION 'Entity EMPTY family contains nonzero or noncanonical counts' + USING ERRCODE = '23514'; + END IF; + END LOOP; + END LOOP; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + BEGIN request_id_value := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Entity genesis identity is malformed' USING ERRCODE = '23514'; END; + IF request_id_value = '00000000-0000-0000-0000-000000000000'::UUID + OR request_id_value::TEXT IS DISTINCT FROM ignored_text THEN + RAISE EXCEPTION 'Entity genesis identity is noncanonical' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO marker, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF marker !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Entity original request digest is malformed' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + BEGIN request_id_value := ignored_text::UUID; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Entity World read identity is malformed' USING ERRCODE = '23514'; END; + IF request_id_value = '00000000-0000-0000-0000-000000000000'::UUID + OR request_id_value::TEXT IS DISTINCT FROM ignored_text THEN + RAISE EXCEPTION 'Entity World read identity is noncanonical' USING ERRCODE = '23514'; + END IF; + SELECT convert_from(frame_value, 'UTF8'), next_position INTO ignored_text, p + FROM account_publication_authorization_read_frame(owner_receipt, p); + IF ignored_text !~ '^(?:[0-9]{4}|-[0-9]{4}|-[1-9][0-9]{4,8}|[+][1-9][0-9]{4,8})-[0-9]{2}-[0-9]{2}T(?:[01][0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9](?:[.](?:[0-9]{3}|[0-9]{6}|[0-9]{9}))?)?Z$' + OR ignored_text ~ '^-0000-' + OR ignored_text ~ 'T(?:[01][0-9]|2[0-3]):[0-5][0-9]:00Z$' + OR ignored_text ~ '[.]000Z$' + OR ignored_text ~ '[.][0-9]{3}000Z$' + OR ignored_text ~ '[.][0-9]{6}000Z$' + OR p <> octet_length(owner_receipt) + 1 THEN + RAISE EXCEPTION 'Entity terminal timestamp or trailing bytes are invalid' USING ERRCODE = '23514'; + END IF; + BEGIN retained_timestamp := ignored_text::TIMESTAMPTZ; EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Entity terminal timestamp is malformed' USING ERRCODE = '23514'; END; + IF retained_timestamp IS NULL THEN + RAISE EXCEPTION 'Entity terminal timestamp is absent' USING ERRCODE = '23514'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java index 8a918ce9bf..6abe23de62 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -7,6 +7,7 @@ import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.time.Clock; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Comparator; @@ -34,6 +35,12 @@ import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt.FamilyCensus; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt.FamilyState; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.gamedesign.AssetSnapshot; import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; import net.firedevops.firemud.common.gamedesign.CommandSnapshot; @@ -71,6 +78,7 @@ import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -551,6 +559,458 @@ void commitsExactAutomationEmptySettlementAndReleasesOnlyThatOperation() throws } } + @Test + void commitsExactEntityEmptySettlementAndReleasesOnlyThatOperation() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservationService = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var bindings = new ArrayList(); + var terminals = new ArrayList(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + UUID.randomUUID()) + .get(0, Boolean.class)) + .isTrue(); + + for (int index = 0; index < 2; index++) { + UUID requestId = UUID.randomUUID(); + var scope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + requestId, + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); + var content = content(scope, "automation-settlement-" + index); + var binding = + asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); + bindings.add(binding); + terminals.add(entityTerminalEvidence(binding, 9001L + index, 9002L + index)); + } + + var firstBinding = bindings.getFirst(); + var secondBinding = bindings.getLast(); + var firstTerminal = terminals.getFirst(); + assertThat(f.tx(() -> repository.findSettlement(firstBinding).isEmpty())).isTrue(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + firstBinding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + + var writerBeforeSettlement = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), firstBinding.sources(), new byte[] {3}); + assertThat(f.tx(() -> f.fences.requestSourceChange(writerBeforeSettlement))) + .isFalse(); + + var committed = f.tx(() -> repository.settleEntityCommittedEmpty(firstTerminal)); + assertThat(committed.authorizationBinding().canonicalBytes()) + .isEqualTo(firstBinding.canonicalBytes()); + assertThat(committed.entityTerminalEvidence().receipt().canonicalBytes()) + .isEqualTo(firstTerminal.receipt().canonicalBytes()); + var stored = + f.dsl.fetchOne( + "SELECT * FROM account_selected_owner_intake_settlements WHERE operation_id = ?", + firstBinding.operationId()); + assertThat(stored.get("receipt_bytes", byte[].class)).isEqualTo(committed.canonicalBytes()); + assertThat(stored.get("receipt_digest", String.class)).isEqualTo(committed.digest()); + assertThat(stored.get("terminal_receipt_bytes", byte[].class)) + .isEqualTo(firstTerminal.receipt().canonicalBytes()); + assertThat(stored.get("terminal_read_request_id", UUID.class)) + .isEqualTo(firstTerminal.request().readRequestId()); + + var exactReadback = f.tx(() -> repository.findSettlement(firstBinding).orElseThrow()); + assertThat(exactReadback.canonicalBytes()).isEqualTo(committed.canonicalBytes()); + f.tx( + () -> { + repository.readFinalAuthorization(firstBinding); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.readHeldFinalAuthorization(firstBinding); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no longer held"); + + var freshRead = + new EntitySelectedSourceIntakeTerminalReadEvidence( + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create("test", firstBinding), + firstTerminal.receipt()); + assertThat(freshRead.request().readRequestId()) + .isNotEqualTo(firstTerminal.request().readRequestId()); + var retry = f.tx(() -> repository.settleEntityCommittedEmpty(freshRead)); + assertThat(retry.canonicalBytes()).isEqualTo(committed.canonicalBytes()); + assertThat( + f.dsl + .fetchSingle( + "SELECT terminal_read_request_id FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + firstBinding.operationId()) + .get(0, UUID.class)) + .isEqualTo(firstTerminal.request().readRequestId()); + var changedReceipt = entityTerminalEvidence(firstBinding, 9101L, 9102L); + assertThatThrownBy(() -> f.tx(() -> repository.settleEntityCommittedEmpty(changedReceipt))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed Entity owner terminal receipt"); + + var changedSources = new ArrayList<>(firstBinding.sources()); + var originalSource = changedSources.getFirst(); + changedSources.set( + 0, + new DraftAuthorizationFenceBinding.SourceEvidence( + originalSource.kind(), + originalSource.scopeId(), + originalSource.generation(), + originalSource.sourceVersion(), + originalSource.checkpointStream(), + originalSource.checkpointSequence(), + new byte[] {99})); + var changedBinding = + new SelectedOwnerIntakeAuthorizationBinding(firstBinding.content(), changedSources); + var changedBindingEvidence = entityTerminalEvidence(changedBinding, 9201L, 9202L); + assertThatThrownBy( + () -> f.tx(() -> repository.settleEntityCommittedEmpty(changedBindingEvidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Original finalized owner authorization absent or changed"); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE account_selected_owner_intake_settlements " + + "SET receipt_digest = ? WHERE operation_id = ?", + DraftAuthorizationFenceBinding.digest(new byte[] {1}), + firstBinding.operationId())) + .isInstanceOf(RuntimeException.class); + assertThat( + f.dsl + .fetchSingle( + "SELECT receipt_bytes FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + firstBinding.operationId()) + .get(0, byte[].class)) + .isEqualTo(committed.canonicalBytes()); + + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + firstBinding.operationId()) + .get(0, Boolean.class)) + .isFalse(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + secondBinding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + var writerWhileOtherOperationHeld = writerBeforeSettlement; + assertThat(f.tx(() -> f.fences.requestSourceChange(writerWhileOtherOperationHeld))) + .isFalse(); + + var settlementInserted = new CountDownLatch(1); + var allowSettlementCommit = new CountDownLatch(1); + var writerStarted = new CountDownLatch(1); + var writerBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var settling = + executor.submit( + () -> + f.transactions.execute( + ignored -> { + var result = repository.settleEntityCommittedEmpty(terminals.getLast()); + settlementInserted.countDown(); + awaitLatch(allowSettlementCommit); + return result; + })); + assertThat(settlementInserted.await(10, TimeUnit.SECONDS)).isTrue(); + + var waitingWriter = + executor.submit( + () -> + f.transactions.execute( + ignored -> { + writerBackendPid.set( + f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + writerStarted.countDown(); + return f.fences.requestSourceChange(writerWhileOtherOperationHeld); + })); + assertThat(writerStarted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(writerBackendPid.get()).isPositive(); + awaitSourceLockWait(f.dsl, writerBackendPid.get()); + assertThat(waitingWriter.isDone()).isFalse(); + + allowSettlementCommit.countDown(); + assertThat(settling.get(10, TimeUnit.SECONDS).authorizationBinding().canonicalBytes()) + .isEqualTo(secondBinding.canonicalBytes()); + assertThat(waitingWriter.get(10, TimeUnit.SECONDS)).isTrue(); + } finally { + allowSettlementCommit.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + secondBinding.operationId()) + .get(0, Boolean.class)) + .isFalse(); + assertThat( + f.tx(() -> f.fences.sourceMutationPermitted(writerWhileOtherOperationHeld))) + .isTrue(); + + String settlementGuard = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('account_selected_owner_intake_settlement_guard()'::regprocedure)") + .get(0, String.class); + assertThat(settlementGuard) + .contains( + "ORDER BY account_publication_authorization_source_sort_key(lock_row.source_key)", + "FOR UPDATE OF lock_row"); + } + } + + @Test + void migratesRetainedV135AutomationBytesWithoutReleasingPendingEntity() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + Clock.systemUTC(), + "135")) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservations = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var automation = + finalizeAutomationBinding(issued, reservations, repository, selected, "retained-v135"); + var original = + f.tx(() -> repository.settleCommittedEmpty(terminalEvidence(automation, 8801, 8802))); + var entity = + finalizeEntityBinding(issued, reservations, repository, selected, "pending-v135-entity"); + var terminal = entityTerminalEvidence(entity, 8901, 8902); + byte[] retainedAuthorization = + f.dsl + .fetchSingle( + "SELECT binding_bytes FROM account_selected_owner_intake_authorizations WHERE operation_id = ?", + automation.operationId()) + .get(0, byte[].class); + byte[] retainedTerminal = original.ownerReceiptBytes(); + String pendingDefinition = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('account_selected_owner_intake_source_read_is_pending(uuid)'::regprocedure)") + .get(0, String.class); + assertRejectedSettlementByPostgres( + issued, + entity, + terminal, + terminal.receipt().canonicalBytes(), + "active Automation authorization"); + + String schema = f.dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + Path current = Path.of("").toAbsolutePath(); + while (current != null + && !java.nio.file.Files.isDirectory( + current.resolve("services/account-service/src/main/resources/db/migration"))) { + current = current.getParent(); + } + Path migrations = + Objects.requireNonNull(current, "Account migrations must be available") + .resolve("services/account-service/src/main/resources/db/migration"); + Flyway.configure() + .dataSource(Objects.requireNonNull(f.manager.getDataSource())) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + migrations) + .target("138") + .load() + .migrate(); + + var recovered = f.tx(() -> repository.findSettlement(automation).orElseThrow()); + assertThat(recovered.canonicalBytes()).isEqualTo(original.canonicalBytes()); + assertThat(recovered.digest()).isEqualTo(original.digest()); + assertThat(recovered.ownerReceiptBytes()).isEqualTo(retainedTerminal); + assertThat(recovered.terminalReadRequestId()).isEqualTo(original.terminalReadRequestId()); + assertThat( + f.dsl + .fetchSingle( + "SELECT binding_bytes FROM account_selected_owner_intake_authorizations WHERE operation_id = ?", + automation.operationId()) + .get(0, byte[].class)) + .isEqualTo(retainedAuthorization); + assertThat( + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('account_selected_owner_intake_source_read_is_pending(uuid)'::regprocedure)") + .get(0, String.class)) + .isEqualTo(pendingDefinition); + assertThat(f.tx(() -> repository.findSettlement(entity))).isEmpty(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + entity.operationId()) + .get(0, Boolean.class)) + .isTrue(); + var writer = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), entity.sources(), new byte[] {7}); + assertThat(f.tx(() -> f.fences.requestSourceChange(writer))).isFalse(); + var settledEntity = f.tx(() -> repository.settleEntityCommittedEmpty(terminal)); + assertThat(settledEntity.ownerReceiptBytes()).isEqualTo(terminal.receipt().canonicalBytes()); + assertThatThrownBy(() -> f.tx(() -> repository.abortSourceRead(entity.content().scope()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot be preliminarily aborted"); + assertThatThrownBy( + () -> + f.dsl.execute( + "DELETE FROM account_selected_owner_intake_settlements WHERE operation_id = ?", + automation.operationId())) + .isInstanceOf(RuntimeException.class); + assertThat(f.tx(() -> repository.findSettlement(automation).orElseThrow()).canonicalBytes()) + .isEqualTo(original.canonicalBytes()); + } + } + + @Test + void postgresRejectsMalformedEntityFramesWithoutReleasingItsParticipation() throws Exception { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var selected = selectedForSettlement(f.tenant); + settleOriginal(issued, selected); + var repository = new AccountSelectedOwnerIntakeSourceReservationRepository(f.dsl); + var reservations = + new AccountSelectedOwnerIntakeSourceReservationService( + issued.actors(), f.fences, repository, f.manager, "test"); + var binding = + finalizeEntityBinding(issued, reservations, repository, selected, "entity-malformed"); + var terminal = entityTerminalEvidence(binding, 8701, 8702); + byte[] bytes = terminal.receipt().canonicalBytes(); + for (var invalid : + Map.of( + 2, "sha256:" + "0".repeat(64), + 7, "sha256:" + "0".repeat(64), + 16, "22", + 17, "UNKNOWN_ENTITY_FAMILY", + 18, "UNKNOWN", + 19, "V1_SOURCE_CENSUS", + 20, "1", + 201, "00000000-0000-0000-0000-000000000000", + 203, "not-a-uuid", + 204, "2026-10-10T00:00:00.000Z") + .entrySet()) { + assertRejectedSettlementByPostgres( + issued, + binding, + terminal, + replaceFrame( + bytes, invalid.getKey(), invalid.getValue().getBytes(StandardCharsets.UTF_8)), + "Entity"); + } + assertRejectedSettlementByPostgres( + issued, + binding, + terminal, + replaceFrame(bytes, 4, new byte[] {1}), + "Entity terminal changed original authorization"); + assertRejectedSettlementByPostgres( + issued, + binding, + terminal, + replaceFrame(bytes, 8, "{}".getBytes(StandardCharsets.UTF_8)), + "Entity terminal changed original source revision binding"); + assertRejectedSettlementByPostgres( + issued, + binding, + terminal, + replaceLastFrame(bytes, null, true), + "Entity terminal timestamp or trailing bytes are invalid"); + var writer = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), binding.sources(), new byte[] {8}); + assertThat(f.tx(() -> f.fences.requestSourceChange(writer))).isFalse(); + var settled = f.tx(() -> repository.settleEntityCommittedEmpty(terminal)); + assertThat( + AccountSelectedOwnerIntakeSettlementReceipt.fromStored(settled.canonicalBytes()) + .canonicalBytes()) + .isEqualTo(settled.canonicalBytes()); + assertThat(f.tx(() -> repository.findSettlement(binding).orElseThrow()).ownerReceiptBytes()) + .isEqualTo(bytes); + } + } + + private static byte[] replaceFrame(byte[] bytes, int selectedFrame, byte[] replacement) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(bytes); + var out = new ByteArrayOutputStream(); + int index = 0; + while (reader.remaining() > 0) { + byte[] original = reader.bytes(); + DraftAuthorizationFenceBinding.frame(out, index++ == selectedFrame ? replacement : original); + } + reader.requireEnd(); + return out.toByteArray(); + } + @Test void postgresPreservesCanonicalAutomationTimestampBytesAndRejectsNoncanonicalFrames() throws Exception { @@ -976,15 +1436,17 @@ private static SelectedOwnerIntakeSourceContent content( private static TemplateConfigSourceSnapshot templateSnapshot( Owner owner, DraftCommitBinding selected, UUID genesis) { - if (owner != Owner.AUTOMATION_SCRIPTING) { - return new TemplateConfigSourceSnapshot(selected, "0", null, genesis, List.of()); + String payload; + if (owner == Owner.ENTITY_MANAGEMENT) { + payload = TemplateConfigSourceValues.ownerInventoryPayload(owner, emptyEntityDeclaration()); + } else { + var inventory = + AutomationAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"); + payload = TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory); } - var inventory = - AutomationAuthoredSourceInventoryDeclaration.parse( - "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" - + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," - + "\"SCRIPT_PATCH_SOURCES\":[]}}"); - String payload = TemplateConfigSourceValues.ownerInventoryPayload(owner, inventory); DraftCommitBinding authored = DraftCommitBinding.create( selected.target(), @@ -1050,6 +1512,41 @@ private static SelectedOwnerIntakeAuthorizationBinding finalizeAutomationBinding current.source().sources(), selected)))); } + private static SelectedOwnerIntakeAuthorizationBinding finalizeEntityBinding( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + AccountSelectedOwnerIntakeSourceReservationService reservationService, + AccountSelectedOwnerIntakeSourceReservationRepository repository, + DraftCommitBinding selected, + String marker) { + var f = issued.sources(); + var scope = + asGameDesign( + () -> + reservationService.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); + var selectedContent = content(scope, marker); + return asGameDesign( + () -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + selectedContent, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); + } + private static void assertRejectedSettlementByPostgres( AccountControlUiOriginalOrderFixture.IssuedCreator issued, SelectedOwnerIntakeAuthorizationBinding binding, @@ -1145,6 +1642,101 @@ private static byte[] settlementReceiptBytes( return out.toByteArray(); } + private static void assertRejectedSettlementByPostgres( + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + SelectedOwnerIntakeAuthorizationBinding binding, + EntitySelectedSourceIntakeTerminalReadEvidence validEvidence, + byte[] changedOwnerReceiptBytes, + String expectedDiagnostic) { + var f = issued.sources(); + assertThatThrownBy( + () -> + f.tx( + () -> { + insertRawSettlement(f.dsl, binding, validEvidence, changedOwnerReceiptBytes); + return null; + })) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(root) + .isInstanceOfSatisfying( + java.sql.SQLException.class, + sql -> { + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains(expectedDiagnostic); + }); + }); + assertThat( + f.dsl.fetchOne( + "SELECT operation_id FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + binding.operationId())) + .isNull(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_selected_owner_intake_source_read_is_pending(?)", + binding.operationId()) + .get(0, Boolean.class)) + .isTrue(); + } + + private static void insertRawSettlement( + org.jooq.DSLContext dsl, + SelectedOwnerIntakeAuthorizationBinding binding, + EntitySelectedSourceIntakeTerminalReadEvidence evidence, + byte[] ownerReceiptBytes) { + String ownerReceiptDigest = DraftAuthorizationFenceBinding.digest(ownerReceiptBytes); + byte[] receiptBytes = + settlementReceiptBytes(binding, evidence, ownerReceiptBytes, ownerReceiptDigest); + dsl.execute( + "INSERT INTO account_selected_owner_intake_settlements " + + "(operation_id, fence_id, intake_request_id, owner, target_namespace, tenant_uuid, " + + "version_uuid, binding_bytes, binding_digest, terminal_read_request_id, " + + "terminal_receipt_bytes, terminal_receipt_digest, receipt_bytes, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.owner().name(), + binding.targetNamespace(), + binding.tenantId(), + binding.versionId(), + binding.canonicalBytes(), + binding.digest(), + evidence.request().readRequestId(), + ownerReceiptBytes, + ownerReceiptDigest, + receiptBytes, + DraftAuthorizationFenceBinding.digest(receiptBytes)); + } + + private static byte[] settlementReceiptBytes( + SelectedOwnerIntakeAuthorizationBinding binding, + EntitySelectedSourceIntakeTerminalReadEvidence evidence, + byte[] ownerReceiptBytes, + String ownerReceiptDigest) { + var request = evidence.request(); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, AccountSelectedOwnerIntakeSettlementReceipt.DOMAIN); + DraftAuthorizationFenceBinding.frame(out, "1"); + DraftAuthorizationFenceBinding.frame(out, binding.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, binding.digest()); + DraftAuthorizationFenceBinding.frame(out, Integer.toString(request.schemaVersion())); + DraftAuthorizationFenceBinding.frame(out, request.targetNamespace()); + DraftAuthorizationFenceBinding.frame(out, request.readRequestId().toString()); + DraftAuthorizationFenceBinding.frame(out, request.intendedReader()); + DraftAuthorizationFenceBinding.frame(out, request.terminalReadPurpose()); + DraftAuthorizationFenceBinding.frame(out, request.binding().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, request.binding().digest()); + DraftAuthorizationFenceBinding.frame(out, ownerReceiptBytes); + DraftAuthorizationFenceBinding.frame(out, ownerReceiptDigest); + return out.toByteArray(); + } + private static byte[] replaceLastFrame( byte[] canonicalBytes, String replacement, boolean appendTrailingByte) { var reader = new DraftAuthorizationFenceBinding.FrameReader(canonicalBytes); @@ -1170,6 +1762,98 @@ private static String lastFrame(byte[] canonicalBytes) { return new String(timestampFrame, StandardCharsets.UTF_8); } + private static final List ENTITY_FAMILIES = + List.of( + "ACTOR_BODY_LAYOUT_ASSIGNMENTS", + "ARCHETYPE_ASSIGNMENTS", + "ARCHETYPE_CONSTRAINTS", + "ARCHETYPE_ROOTS", + "BALANCE_CURVE_ATTACHMENTS", + "BALANCE_CURVE_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS", + "BODY_LAYOUT_ROOTS", + "CRAFTING_INGREDIENT_BINDINGS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_RECIPE_ROOTS", + "EQUIPMENT_ATTACHMENT_RULES", + "EQUIPMENT_CAPABILITIES", + "EQUIPMENT_COMPATIBILITY_RULES", + "EQUIPMENT_OCCUPANCY_RULES", + "EQUIPMENT_SLOT_GROUPS", + "EQUIPMENT_SLOT_ROOTS", + "INBOUND_LOOT_BINDINGS", + "ITEM_TEMPLATE_ROOTS", + "LOOT_ITEM_MAPPINGS", + "LOOT_TABLE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "OTHER_ACTOR_TEMPLATE_ROOTS"); + private static final java.util.Set ENTITY_V1_FAMILIES = + java.util.Set.of( + "ITEM_TEMPLATE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "CRAFTING_RECIPE_ROOTS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_INGREDIENT_BINDINGS", + "EQUIPMENT_SLOT_ROOTS", + "EQUIPMENT_SLOT_GROUPS", + "BODY_LAYOUT_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS"); + + private static EntityAuthoredSourceInventoryDeclaration emptyEntityDeclaration() { + String families = + ENTITY_FAMILIES.stream() + .map(name -> "\"" + name + "\":[]") + .collect(java.util.stream.Collectors.joining(",")); + return EntityAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + families + + "}}"); + } + + private static EntitySelectedSourceIntakeTerminalReadEvidence entityTerminalEvidence( + SelectedOwnerIntakeAuthorizationBinding binding, long localTenantKey, long localVersionKey) { + var freeze = freezeEvidence(binding); + var request = + SelectedOwnerWorldInventoryReadEvidence.create(binding.targetNamespace(), binding, freeze); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freeze, publicInventory(freeze)); + var inputs = + new SelectedOwnerEmptySourceInputs( + binding, new SelectedOwnerWorldInventoryReadEvidence(request, inventory)); + var states = + ENTITY_FAMILIES.stream() + .map( + family -> + new FamilyCensus( + family, + FamilyState.EMPTY, + ENTITY_V1_FAMILIES.contains(family) + ? FamilyEvidenceKind.V1_SOURCE_CENSUS + : FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER, + 0, + 0, + 0, + 0, + 0)) + .toList(); + var receipt = + EntityEmptySelectedSourceIntakeReceipt.create( + inputs, + UUID.randomUUID(), + localTenantKey, + localVersionKey, + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + binding.targetNamespace(), binding, freeze), + states, + OffsetDateTime.parse("2026-10-10T00:00:00.120Z")); + return new EntitySelectedSourceIntakeTerminalReadEvidence( + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + binding.targetNamespace(), binding), + receipt); + } + private static AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence( SelectedOwnerIntakeAuthorizationBinding binding, long localTenantKey, long localVersionKey) { return terminalEvidence( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java index 8540514ed2..43f0ea7d0d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java @@ -28,6 +28,9 @@ import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; @@ -265,7 +268,9 @@ void failedSettlementCommitDoesNotPretendToHaveReadBackTheUnknownOutcome() { when(harness.repository.settleCommittedEmpty(any())) .thenAnswer( invocation -> - AccountSelectedOwnerIntakeSettlementReceipt.create(invocation.getArgument(0))); + AccountSelectedOwnerIntakeSettlementReceipt.create( + (AutomationSelectedSourceIntakeTerminalReadEvidence) + invocation.getArgument(0))); harness.transactions.failCommitAt = 2; assertThatThrownBy(() -> asGameDesign(() -> harness.service.settle(ORIGINAL))) @@ -376,6 +381,135 @@ void wrongPeerEndUserAmbientSqlAndNonAutomationScopeAreRejectedBeforeRepositoryA assertThat(wrongBindingNamespace.transactions.begins).isZero(); } + @Test + void entityLostLookupOnlyReadbackRecoversExactPriorWithoutAnotherRemoteReadOrWrite() { + // Synthetic receipt decoder and repository stand-ins prove transaction/call ordering only. + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + Harness harness = new Harness(NAMESPACE, true); + var owner = entityReceipt(binding); + var stored = new AtomicReference(); + when(harness.repository.findSettlement(binding)) + .thenAnswer(ignored -> Optional.ofNullable(stored.get())); + when(harness.entityClient.read(any())) + .thenAnswer( + invocation -> { + assertNoSql(); + EntitySelectedSourceIntakeTerminalReadEvidence.Request request = + invocation.getArgument(0); + return new EntitySelectedSourceIntakeTerminalReadEvidence(request, owner); + }); + when(harness.repository.settleEntityCommittedEmpty(any())) + .thenAnswer( + invocation -> { + assertWritableReadCommittedTransaction(); + EntitySelectedSourceIntakeTerminalReadEvidence evidence = invocation.getArgument(0); + var receipt = AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + stored.set(receipt); + return receipt; + }); + // The first post-commit lookup is absent even though the immutable writer committed. + AtomicInteger reads = new AtomicInteger(); + when(harness.repository.findSettlement(binding)) + .thenAnswer( + ignored -> { + assertWritableReadCommittedTransaction(); + return reads.incrementAndGet() <= 2 ? Optional.empty() : Optional.of(stored.get()); + }); + try (var decoder = Mockito.mockStatic(EntityEmptySelectedSourceIntakeReceipt.class)) { + decoder + .when(() -> EntityEmptySelectedSourceIntakeReceipt.fromStored(owner.canonicalBytes())) + .thenReturn(owner); + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> asGameDesign(() -> harness.service.settle(binding))); + var recovered = asGameDesign(() -> harness.service.settle(binding)); + assertThat(recovered.canonicalBytes()).isEqualTo(stored.get().canonicalBytes()); + assertThat(recovered.entityTerminalEvidence().receipt()).isSameAs(owner); + assertThat(harness.transactions.begins).isEqualTo(4); + verify(harness.entityClient, times(1)).read(any()); + verify(harness.repository, times(1)).settleEntityCommittedEmpty(any()); + verifyNoInteractions(harness.automationClient); + } + } + + @Test + void entityCallerNamespaceEndUserAndAmbientSqlGatesPrecedeRepositoryAndRemoteAccess() { + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + Harness harness = new Harness(NAMESPACE, true); + assertStatus(Status.Code.UNAUTHENTICATED, () -> harness.service.settle(binding)); + asPeer( + peer("test", "automation-scripting-service"), + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(binding))); + asPeer( + peer("other", "game-design-service"), + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(binding))); + SessionContext.setContext("123", List.of(), Map.of()); + asGameDesign( + () -> assertStatus(Status.Code.PERMISSION_DENIED, () -> harness.service.settle(binding))); + SessionContext.clear(); + TransactionSynchronizationManager.initSynchronization(); + asGameDesign( + () -> assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(binding))); + TransactionSynchronizationManager.clear(); + var other = new Harness("other", true); + asPeer( + peer("other", "game-design-service"), + () -> assertStatus(Status.Code.FAILED_PRECONDITION, () -> other.service.settle(binding))); + verifyNoInteractions(harness.repository, harness.entityClient, harness.automationClient); + verifyNoInteractions(other.repository, other.entityClient, other.automationClient); + } + + @Test + void unavailableOrChangedEntityReadNeverCreatesAccountSettlement() { + var binding = + AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); + Harness missing = new Harness(NAMESPACE, true); + when(missing.repository.findSettlement(binding)).thenReturn(Optional.empty()); + when(missing.entityClient.read(any())).thenReturn(null); + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> missing.service.settle(binding))); + verify(missing.repository, never()).settleEntityCommittedEmpty(any()); + Harness changed = new Harness(NAMESPACE, true); + when(changed.repository.findSettlement(binding)).thenReturn(Optional.empty()); + when(changed.entityClient.read(any())) + .thenAnswer( + invocation -> + new EntitySelectedSourceIntakeTerminalReadEvidence( + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + NAMESPACE, binding), + entityReceipt(binding))); + assertStatus( + Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> changed.service.settle(binding))); + verify(changed.repository, never()).settleEntityCommittedEmpty(any()); + Harness unavailable = new Harness(NAMESPACE, true); + when(unavailable.repository.findSettlement(binding)).thenReturn(Optional.empty()); + when(unavailable.entityClient.read(any())).thenThrow(Status.UNAVAILABLE.asRuntimeException()); + assertStatus( + Status.Code.UNAVAILABLE, () -> asGameDesign(() -> unavailable.service.settle(binding))); + verify(unavailable.repository, never()).settleEntityCommittedEmpty(any()); + } + + private static EntityEmptySelectedSourceIntakeReceipt entityReceipt( + SelectedOwnerIntakeAuthorizationBinding binding) { + var receipt = Mockito.mock(EntityEmptySelectedSourceIntakeReceipt.class); + byte[] bytes = "synthetic Entity committed receipt".getBytes(StandardCharsets.UTF_8); + when(receipt.targetNamespace()).thenReturn(binding.targetNamespace()); + when(receipt.operationId()).thenReturn(binding.operationId()); + when(receipt.fenceId()).thenReturn(binding.fenceId()); + when(receipt.intakeRequestId()).thenReturn(binding.intakeRequestId()); + when(receipt.canonicalTenantId()).thenReturn(binding.tenantId()); + when(receipt.canonicalVersionId()).thenReturn(binding.versionId()); + when(receipt.selectedCommitId()).thenReturn(binding.selected().commitId()); + when(receipt.authorizationBindingBytes()).thenReturn(binding.canonicalBytes()); + when(receipt.authorizationBindingDigest()).thenReturn(binding.digest()); + when(receipt.canonicalBytes()).thenReturn(bytes); + when(receipt.receiptDigest()).thenReturn(DraftAuthorizationFenceBinding.digest(bytes)); + when(receipt.outcome()).thenReturn("COMMITTED_EMPTY"); + return receipt; + } + private static Harness preparedHarness() { Harness harness = new Harness(NAMESPACE); when(harness.repository.findSettlement(ORIGINAL)).thenReturn(Optional.empty()); @@ -459,14 +593,24 @@ private static final class Harness { Mockito.mock(AccountSelectedOwnerIntakeSourceReservationRepository.class); final AutomationSelectedSourceIntakeTerminalReadClient automationClient = Mockito.mock(AutomationSelectedSourceIntakeTerminalReadClient.class); + final EntitySelectedSourceIntakeTerminalReadClient entityClient = + Mockito.mock(EntitySelectedSourceIntakeTerminalReadClient.class); final OwnerTransactions transactions = new OwnerTransactions(); final List steps = new ArrayList<>(); final AccountSelectedOwnerIntakeSettlementService service; Harness(String namespace) { + this(namespace, false); + } + + Harness(String namespace, boolean entityEnabled) { service = new AccountSelectedOwnerIntakeSettlementService( - repository, automationClient, transactions, namespace); + repository, + automationClient, + entityEnabled ? entityClient : null, + transactions, + namespace); } } diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 67fa43743a..6776a5a194 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -86,10 +86,33 @@ public AccountControlUiOriginalOrderFixture( UUID gameDesignTenant, Clock actorClock) throws Exception { + this( + jdbcUrl, + username, + password, + redisHost, + redisPort, + temporary, + gameDesignTenant, + actorClock, + null); + } + + public AccountControlUiOriginalOrderFixture( + String jdbcUrl, + String username, + String password, + String redisHost, + int redisPort, + Path temporary, + UUID gameDesignTenant, + Clock actorClock, + String migrationTarget) + throws Exception { this.temporary = temporary; f = new AccountControlUiOwnerSourcesFixture( - jdbcUrl, username, password, temporary, false, gameDesignTenant); + jdbcUrl, username, password, temporary, false, gameDesignTenant, migrationTarget); var lifecycle = new AccountControlUiSignerFixture(f, temporary); lifecycle.commit(); var originalSigner = f.tx(lifecycle.signer::captureCurrent); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 6b012a954b..174514c513 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -117,18 +117,30 @@ final class AccountControlUiOwnerSourcesFixture { Path root, boolean installNegativeIssuer, UUID tenant) { + this(jdbcUrl, username, password, root, installNegativeIssuer, tenant, null); + } + + AccountControlUiOwnerSourcesFixture( + String jdbcUrl, + String username, + String password, + Path root, + boolean installNegativeIssuer, + UUID tenant, + String migrationTarget) { this.tenant = Objects.requireNonNull(tenant); String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); var dataSource = new DriverManagerDataSource(jdbcUrl, username, password); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("filesystem:" + accountMigrations()) - .load() - .migrate(); + var migrations = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + accountMigrations()); + if (migrationTarget != null) migrations.target(migrationTarget); + migrations.load().migrate(); manager = new DataSourceTransactionManager(dataSource); transactions = new TransactionTemplate(manager); transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java index 7b3c87d1f2..32343ed7a5 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java @@ -5,19 +5,28 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; -/** Immutable Account record of one exact Automation {@code COMMITTED_EMPTY} terminal read. */ +/** Immutable Account record of one exact closed owner {@code COMMITTED_EMPTY} terminal read. */ public final class AccountSelectedOwnerIntakeSettlementReceipt { public static final String DOMAIN = "account-selected-owner-intake-settlement/v1"; - public static final int MAX_BYTES = + public static final int AUTOMATION_MAX_BYTES = 2 * SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES + 64 * 1024; + public static final int ENTITY_MAX_BYTES = + 2 * SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES + + 64 * 1024; + public static final int MAX_BYTES = Math.max(AUTOMATION_MAX_BYTES, ENTITY_MAX_BYTES); private final SelectedOwnerIntakeAuthorizationBinding authorizationBinding; private final AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence; + private final EntitySelectedSourceIntakeTerminalReadEvidence entityTerminalEvidence; private final byte[] canonicalBytes; private final String digest; @@ -26,6 +35,7 @@ private AccountSelectedOwnerIntakeSettlementReceipt( AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence) { this.authorizationBinding = Objects.requireNonNull(authorizationBinding); this.terminalEvidence = Objects.requireNonNull(terminalEvidence); + this.entityTerminalEvidence = null; if (!Arrays.equals( authorizationBinding.canonicalBytes(), terminalEvidence.request().binding().canonicalBytes()) @@ -40,7 +50,7 @@ private AccountSelectedOwnerIntakeSettlementReceipt( "Automation terminal differs from the complete original Account authorization"); } this.canonicalBytes = encode(); - if (canonicalBytes.length > MAX_BYTES) { + if (canonicalBytes.length > AUTOMATION_MAX_BYTES) { throw new IllegalArgumentException( "Account selected-owner settlement exceeds its size limit"); } @@ -54,7 +64,39 @@ public static AccountSelectedOwnerIntakeSettlementReceipt create( terminalEvidence.request().binding(), terminalEvidence); } - /** Strictly decodes the complete immutable Account binding and Automation terminal evidence. */ + private AccountSelectedOwnerIntakeSettlementReceipt( + EntitySelectedSourceIntakeTerminalReadEvidence evidence) { + this.entityTerminalEvidence = Objects.requireNonNull(evidence); + this.terminalEvidence = null; + this.authorizationBinding = evidence.request().binding(); + if (!Arrays.equals( + authorizationBinding.canonicalBytes(), evidence.receipt().authorizationBindingBytes()) + || !authorizationBinding.digest().equals(evidence.receipt().authorizationBindingDigest()) + || !"COMMITTED_EMPTY".equals(evidence.receipt().outcome())) { + throw new IllegalArgumentException( + "Entity terminal differs from the complete original Account authorization"); + } + this.canonicalBytes = encode(); + if (canonicalBytes.length > ENTITY_MAX_BYTES) { + throw new IllegalArgumentException("Account Entity settlement exceeds its size limit"); + } + this.digest = DraftAuthorizationFenceBinding.digest(canonicalBytes); + } + + public static AccountSelectedOwnerIntakeSettlementReceipt create( + EntitySelectedSourceIntakeTerminalReadEvidence evidence) { + return new AccountSelectedOwnerIntakeSettlementReceipt(evidence); + } + + public static int maxBytes(Owner owner) { + return switch (owner) { + case AUTOMATION_SCRIPTING -> AUTOMATION_MAX_BYTES; + case ENTITY_MANAGEMENT -> ENTITY_MAX_BYTES; + default -> throw new IllegalArgumentException("Unsupported selected-owner settlement"); + }; + } + + /** Strictly decodes the complete immutable Account binding and its closed owner terminal. */ public static AccountSelectedOwnerIntakeSettlementReceipt fromStored(byte[] bytes) { if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) { throw new IllegalArgumentException( @@ -87,7 +129,34 @@ public static AccountSelectedOwnerIntakeSettlementReceipt fromStored(byte[] byte var terminalBinding = SelectedOwnerIntakeAuthorizationBinding.fromStored(terminalBindingBytes); if (!binding.digest().equals(terminalBindingDigest) || !Arrays.equals(bindingBytes, terminalBindingBytes)) { - throw new IllegalArgumentException("Automation terminal request changed the Account binding"); + throw new IllegalArgumentException("Owner terminal request changed the Account binding"); + } + if (binding.owner() == Owner.ENTITY_MANAGEMENT) { + if (stored.length > ENTITY_MAX_BYTES) { + throw new IllegalArgumentException("Stored Entity settlement exceeds its size limit"); + } + var entityRequest = + new EntitySelectedSourceIntakeTerminalReadEvidence.Request( + terminalSchemaVersion, namespace, readRequestId, terminalBinding); + if (!intendedReader.equals(entityRequest.intendedReader()) + || !purpose.equals(entityRequest.terminalReadPurpose())) { + throw new IllegalArgumentException("Entity terminal reader or purpose differs"); + } + byte[] ownerBytes = bounded(reader.bytes(), EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES); + String ownerDigest = reader.text(); + reader.requireEnd(); + var owner = EntityEmptySelectedSourceIntakeReceipt.fromStored(ownerBytes); + if (!owner.receiptDigest().equals(ownerDigest)) { + throw new IllegalArgumentException("Entity terminal receipt digest differs"); + } + var result = create(new EntitySelectedSourceIntakeTerminalReadEvidence(entityRequest, owner)); + if (!Arrays.equals(stored, result.canonicalBytes)) { + throw new IllegalArgumentException("Noncanonical Account Entity settlement"); + } + return result; + } + if (binding.owner() != Owner.AUTOMATION_SCRIPTING || stored.length > AUTOMATION_MAX_BYTES) { + throw new IllegalArgumentException("Stored Automation settlement size or owner differs"); } var request = new AutomationSelectedSourceIntakeTerminalReadEvidence.Request( @@ -118,9 +187,21 @@ public SelectedOwnerIntakeAuthorizationBinding authorizationBinding() { } public AutomationSelectedSourceIntakeTerminalReadEvidence terminalEvidence() { + if (terminalEvidence == null) throw new IllegalStateException("Settlement is not Automation"); return terminalEvidence; } + public EntitySelectedSourceIntakeTerminalReadEvidence entityTerminalEvidence() { + if (entityTerminalEvidence == null) throw new IllegalStateException("Settlement is not Entity"); + return entityTerminalEvidence; + } + + public UUID terminalReadRequestId() { + return entityTerminalEvidence == null + ? terminalEvidence.request().readRequestId() + : entityTerminalEvidence.request().readRequestId(); + } + public UUID operationId() { return authorizationBinding.operationId(); } @@ -130,11 +211,15 @@ public String targetNamespace() { } public byte[] ownerReceiptBytes() { - return terminalEvidence.receipt().canonicalBytes(); + return entityTerminalEvidence == null + ? terminalEvidence.receipt().canonicalBytes() + : entityTerminalEvidence.receipt().canonicalBytes(); } public String ownerReceiptDigest() { - return terminalEvidence.receipt().receiptDigest(); + return entityTerminalEvidence == null + ? terminalEvidence.receipt().receiptDigest() + : entityTerminalEvidence.receipt().receiptDigest(); } public byte[] canonicalBytes() { @@ -148,7 +233,8 @@ public String digest() { /** Correlation is retained on first settlement, but is not part of owner receipt identity. */ public boolean sameImmutableOwnerReceipt( AutomationSelectedSourceIntakeTerminalReadEvidence requested) { - return requested != null + return terminalEvidence != null + && requested != null && Arrays.equals( authorizationBinding.canonicalBytes(), requested.request().binding().canonicalBytes()) && Arrays.equals( @@ -156,6 +242,16 @@ public boolean sameImmutableOwnerReceipt( && terminalEvidence.receipt().receiptDigest().equals(requested.receipt().receiptDigest()); } + public boolean sameImmutableOwnerReceipt( + EntitySelectedSourceIntakeTerminalReadEvidence requested) { + return entityTerminalEvidence != null + && requested != null + && Arrays.equals( + authorizationBinding.canonicalBytes(), requested.request().binding().canonicalBytes()) + && Arrays.equals(ownerReceiptBytes(), requested.receipt().canonicalBytes()) + && ownerReceiptDigest().equals(requested.receipt().receiptDigest()); + } + @Override public boolean equals(Object value) { return value instanceof AccountSelectedOwnerIntakeSettlementReceipt other @@ -173,6 +269,19 @@ private byte[] encode() { frame(out, "1"); frame(out, authorizationBinding.canonicalBytes()); frame(out, authorizationBinding.digest()); + if (entityTerminalEvidence != null) { + var entityRequest = entityTerminalEvidence.request(); + frame(out, Integer.toString(entityRequest.schemaVersion())); + frame(out, entityRequest.targetNamespace()); + frame(out, entityRequest.readRequestId().toString()); + frame(out, entityRequest.intendedReader()); + frame(out, entityRequest.terminalReadPurpose()); + frame(out, entityRequest.binding().canonicalBytes()); + frame(out, entityRequest.binding().digest()); + frame(out, entityTerminalEvidence.receipt().canonicalBytes()); + frame(out, entityTerminalEvidence.receipt().receiptDigest()); + return out.toByteArray(); + } var request = terminalEvidence.request(); frame(out, Integer.toString(request.schemaVersion())); frame(out, request.targetNamespace()); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java index e82d5afbad..a7835eb75a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementEvidence.java @@ -27,11 +27,15 @@ public record Request( if (schemaVersion != SCHEMA_VERSION || !GrpcPeerIdentity.isValidNamespace(targetNamespace) || authorizationBinding == null - || authorizationBinding.owner() != Owner.AUTOMATION_SCRIPTING + || (authorizationBinding.owner() != Owner.AUTOMATION_SCRIPTING + && authorizationBinding.owner() != Owner.ENTITY_MANAGEMENT) || !targetNamespace.equals(authorizationBinding.targetNamespace()) - || !"account-automation-intake-authorization/v1".equals(authorizationBinding.schema()) - || !"AUTOMATION_INTAKE_RETENTION".equals(authorizationBinding.purpose())) { - throw invalid("Canonical same-namespace Automation authorization required"); + || !(authorizationBinding.owner() == Owner.AUTOMATION_SCRIPTING + ? "account-automation-intake-authorization/v1".equals(authorizationBinding.schema()) + && "AUTOMATION_INTAKE_RETENTION".equals(authorizationBinding.purpose()) + : "account-entity-intake-authorization/v1".equals(authorizationBinding.schema()) + && "ENTITY_INTAKE_RETENTION".equals(authorizationBinding.purpose()))) { + throw invalid("Canonical same-namespace selected-owner authorization required"); } DraftAuthorizationFenceBinding.requireUuid(transportRequestId); if (transportRequestId.equals(authorizationBinding.operationId()) @@ -98,7 +102,9 @@ public record Result(Request request, AccountSelectedOwnerIntakeSettlementReceip Objects.requireNonNull(receipt, "Complete Account settlement receipt is required"); byte[] receiptBytes = receipt.canonicalBytes(); if (receiptBytes.length == 0 - || receiptBytes.length > AccountSelectedOwnerIntakeSettlementReceipt.MAX_BYTES + || receiptBytes.length + > AccountSelectedOwnerIntakeSettlementReceipt.maxBytes( + request.authorizationBinding().owner()) || !DraftAuthorizationFenceBinding.digest(receiptBytes).equals(receipt.digest()) || !request.targetNamespace().equals(receipt.targetNamespace()) || !Arrays.equals( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java index c6c9a6a60e..5a276e3312 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodec.java @@ -73,8 +73,10 @@ public static SelectedOwnerIntakeSettlementResponse toResponse(Result result) { if (result == null) throw invalid("Complete settlement result is required"); byte[] receipt = result.receipt().canonicalBytes(); if (receipt.length == 0 - || receipt.length > AccountSelectedOwnerIntakeSettlementReceipt.MAX_BYTES) { - throw invalid("Complete settlement receipt exceeds its 92,356,608 byte bound"); + || receipt.length + > AccountSelectedOwnerIntakeSettlementReceipt.maxBytes( + result.request().authorizationBinding().owner())) { + throw invalid("Complete settlement receipt exceeds its owner bound"); } var response = SelectedOwnerIntakeSettlementResponse.newBuilder() @@ -96,8 +98,9 @@ public static Result fromResponse( throw invalid("Account changed the complete settlement request"); } if (response.getSettlementReceipt().size() - > AccountSelectedOwnerIntakeSettlementReceipt.MAX_BYTES) { - throw invalid("Complete settlement receipt exceeds its 92,356,608 byte bound"); + > AccountSelectedOwnerIntakeSettlementReceipt.maxBytes( + request.authorizationBinding().owner())) { + throw invalid("Complete settlement receipt exceeds its owner bound"); } byte[] receiptBytes = response.getSettlementReceipt().toByteArray(); AccountSelectedOwnerIntakeSettlementReceipt receipt; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntityEmptySelectedSourceIntakeReceipt.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntityEmptySelectedSourceIntakeReceipt.java new file mode 100644 index 0000000000..0b3e2559ae --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntityEmptySelectedSourceIntakeReceipt.java @@ -0,0 +1,880 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.io.ByteArrayOutputStream; +import java.time.OffsetDateTime; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.worldmanagement.v1.ReadSelectedOwnerWorldInventoryRequest; +import tools.jackson.databind.json.JsonMapper; + +/** Immutable local receipt for a freshly founded, explicitly empty Entity source catalogue. */ +public final class EntityEmptySelectedSourceIntakeReceipt { + public static final String DOMAIN = "entity-selected-empty-source-catalogue/v1"; + public static final int SCHEMA_VERSION = 1; + public static final int MAX_BYTES = 80 * 1024 * 1024; + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final String targetNamespace; + private final UUID genesisId; + private final UUID operationId; + private final UUID fenceId; + private final UUID intakeRequestId; + private final UUID canonicalTenantId; + private final UUID canonicalVersionId; + private final UUID selectedCommitId; + private final UUID sourceRevisionId; + private final String sourceRevisionOrder; + private final long localTenantKey; + private final long localVersionKey; + private final String requestDigest; + private final String schemaDigest; + private final String authorizationBindingDigest; + private final byte[] authorizationBindingBytes; + private final String selectedSourceDigest; + private final byte[] selectedSourceBytes; + private final String selectedSourceRevisionBindingDigest; + private final byte[] selectedSourceRevisionBindingBytes; + private final UUID worldReadRequestId; + private final String worldReadRequestDigest; + private final byte[] worldReadRequestBytes; + private final String worldClosureDigest; + private final byte[] worldClosureBytes; + private final List familyStates; + private final OffsetDateTime retainedAt; + private final byte[] canonicalBytes; + private final String receiptDigest; + private final SelectedOwnerIntakeAuthorizationBinding authorizationBinding; + private final SelectedOwnerEmptySourceInputs inputs; + + private EntityEmptySelectedSourceIntakeReceipt( + String targetNamespace, + UUID genesisId, + long localTenantKey, + long localVersionKey, + String requestDigest, + String schemaDigest, + byte[] authorizationBindingBytes, + String authorizationBindingDigest, + byte[] selectedSourceBytes, + String selectedSourceDigest, + byte[] selectedSourceRevisionBindingBytes, + String selectedSourceRevisionBindingDigest, + UUID worldReadRequestId, + byte[] worldReadRequestBytes, + String worldReadRequestDigest, + byte[] worldClosureBytes, + String worldClosureDigest, + List familyStates, + OffsetDateTime retainedAt) { + this.targetNamespace = requireText(targetNamespace, "targetNamespace"); + this.genesisId = requireUuid(genesisId, "genesisId"); + if (localTenantKey <= 0L || localVersionKey <= 0L || localTenantKey == localVersionKey) { + throw new IllegalArgumentException("Distinct positive Entity local keys are required"); + } + this.localTenantKey = localTenantKey; + this.localVersionKey = localVersionKey; + this.requestDigest = requireDigest(requestDigest, "requestDigest"); + this.authorizationBindingBytes = + boundedBytes( + authorizationBindingBytes, + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES, + "authorizationBindingBytes"); + this.authorizationBinding = + SelectedOwnerIntakeAuthorizationBinding.fromStored(this.authorizationBindingBytes); + this.authorizationBindingDigest = + requireDigest(authorizationBindingDigest, "authorizationBindingDigest"); + if (!this.authorizationBinding.digest().equals(this.authorizationBindingDigest)) { + throw new IllegalArgumentException("Retained Account authorization digest differs"); + } + this.selectedSourceBytes = + boundedBytes( + selectedSourceBytes, SelectedOwnerIntakeSourceContent.MAX_BYTES, "selectedSourceBytes"); + this.selectedSourceDigest = requireDigest(selectedSourceDigest, "selectedSourceDigest"); + if (!Arrays.equals( + this.selectedSourceBytes, this.authorizationBinding.content().canonicalBytes()) + || !this.selectedSourceDigest.equals(this.authorizationBinding.content().digest())) { + throw new IllegalArgumentException( + "Selected source differs from its original Account binding"); + } + this.inputs = + decodeInputs( + this.authorizationBinding, + worldReadRequestId, + worldReadRequestBytes, + worldReadRequestDigest, + worldClosureBytes, + worldClosureDigest); + this.selectedSourceRevisionBindingBytes = + boundedBytes( + selectedSourceRevisionBindingBytes, + 4 * 1024 * 1024, + "selectedSourceRevisionBindingBytes"); + this.selectedSourceRevisionBindingDigest = + requireDigest(selectedSourceRevisionBindingDigest, "selectedSourceRevisionBindingDigest"); + var sourceDeclaration = this.inputs.ownerSourceInventoryDeclaration(); + byte[] expectedRevisionBinding = sourceDeclaration.sourceBinding().canonicalBytes(); + if (!Arrays.equals(this.selectedSourceRevisionBindingBytes, expectedRevisionBinding) + || !this.selectedSourceRevisionBindingDigest.equals( + sourceDeclaration.sourceBinding().digest())) { + throw new IllegalArgumentException( + "Selected source revision binding differs from the original Game Design source"); + } + this.operationId = requireUuid(this.authorizationBinding.operationId(), "operationId"); + this.fenceId = requireUuid(this.authorizationBinding.fenceId(), "fenceId"); + this.intakeRequestId = + requireUuid(this.authorizationBinding.intakeRequestId(), "intakeRequestId"); + this.canonicalTenantId = requireUuid(this.authorizationBinding.tenantId(), "canonicalTenantId"); + this.canonicalVersionId = + requireUuid(this.authorizationBinding.versionId(), "canonicalVersionId"); + this.selectedCommitId = + requireUuid(this.authorizationBinding.selected().commitId(), "selectedCommitId"); + this.sourceRevisionId = requireUuid(sourceDeclaration.revisionId(), "sourceRevisionId"); + this.sourceRevisionOrder = + requireDecimal(sourceDeclaration.revisionOrder(), "sourceRevisionOrder"); + this.worldReadRequestId = requireUuid(worldReadRequestId, "worldReadRequestId"); + this.worldReadRequestBytes = + boundedBytes( + worldReadRequestBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES, + "worldReadRequestBytes"); + this.worldReadRequestDigest = requireDigest(worldReadRequestDigest, "worldReadRequestDigest"); + if (!DraftAuthorizationFenceBinding.digest(this.worldReadRequestBytes) + .equals(this.worldReadRequestDigest)) { + throw new IllegalArgumentException("Retained World read request digest differs"); + } + this.worldClosureBytes = + boundedBytes( + worldClosureBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES, + "worldClosureBytes"); + this.worldClosureDigest = requireDigest(worldClosureDigest, "worldClosureDigest"); + if (!this.inputs + .worldInventoryReadEvidence() + .inventory() + .digest() + .equals(this.worldClosureDigest)) { + throw new IllegalArgumentException("Retained World closure digest differs"); + } + if (!Arrays.equals( + this.inputs.worldInventoryReadEvidence().inventory().canonicalBytes(), + this.worldClosureBytes)) { + throw new IllegalArgumentException("Retained World closure bytes differ"); + } + this.familyStates = + requireAllEmptyStates( + familyStates, familyNames(sourceDeclaration.entityInventory().canonicalJson())); + this.schemaDigest = requireDigest(schemaDigest, "schemaDigest"); + if (!schemaDigest.equals( + schemaDigest(familyNames(sourceDeclaration.entityInventory().canonicalJson())))) { + throw new IllegalArgumentException("Entity source catalogue schema digest differs"); + } + requireSameNamespace(this.targetNamespace, this.authorizationBinding); + if (this.authorizationBinding.owner() != Owner.ENTITY_MANAGEMENT + || !this.authorizationBinding.schema().equals("account-entity-intake-authorization/v1") + || !this.authorizationBinding.purpose().equals("ENTITY_INTAKE_RETENTION")) { + throw new IllegalArgumentException("Exact original Entity Account authorization is required"); + } + this.retainedAt = Objects.requireNonNull(retainedAt, "retainedAt"); + if (retainedAt.getOffset().getTotalSeconds() != 0) { + throw new IllegalArgumentException("Receipt timestamp must use UTC"); + } + if (!this.requestDigest.equals( + requestDigest( + targetNamespace, + authorizationBinding, + this.inputs.worldInventoryReadEvidence().request().freezeEvidence()))) { + throw new IllegalArgumentException("Entity source intake request digest differs"); + } + this.canonicalBytes = encode(); + if (this.canonicalBytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Entity source catalogue receipt exceeds its size limit"); + } + this.receiptDigest = DraftAuthorizationFenceBinding.digest(this.canonicalBytes); + } + + public static EntityEmptySelectedSourceIntakeReceipt create( + SelectedOwnerEmptySourceInputs inputs, + UUID genesisId, + long localTenantKey, + long localVersionKey, + String requestDigest, + List familyStates, + OffsetDateTime retainedAt) { + Objects.requireNonNull(inputs, "validated selected empty-source inputs are required"); + var binding = inputs.authorizationBinding(); + var worldEvidence = inputs.worldInventoryReadEvidence(); + byte[] worldReadRequest = + SelectedOwnerWorldInventoryReadGrpcCodec.toRequest(worldEvidence.request()).toByteArray(); + byte[] sourceRevisionBinding = + inputs.ownerSourceInventoryDeclaration().sourceBinding().canonicalBytes(); + return new EntityEmptySelectedSourceIntakeReceipt( + binding.targetNamespace(), + genesisId, + localTenantKey, + localVersionKey, + requestDigest, + schemaDigest( + familyNames( + inputs.ownerSourceInventoryDeclaration().entityInventory().canonicalJson())), + binding.canonicalBytes(), + binding.digest(), + inputs.sourceContent().canonicalBytes(), + inputs.sourceContent().digest(), + sourceRevisionBinding, + inputs.ownerSourceInventoryDeclaration().sourceBinding().digest(), + worldEvidence.request().readRequestId(), + worldReadRequest, + DraftAuthorizationFenceBinding.digest(worldReadRequest), + worldEvidence.inventory().canonicalBytes(), + worldEvidence.inventory().digest(), + familyStates, + retainedAt); + } + + /** Decodes and fully revalidates the immutable canonical owner receipt. */ + public static EntityEmptySelectedSourceIntakeReceipt fromStored(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Stored Entity source catalogue receipt size is invalid"); + } + byte[] stored = bytes.clone(); + var reader = new DraftAuthorizationFenceBinding.FrameReader(stored); + reader.expect(DOMAIN); + if (!Integer.toString(SCHEMA_VERSION).equals(reader.text())) { + throw new IllegalArgumentException("Unsupported Entity source catalogue schema"); + } + String schemaDigest = reader.text(); + String namespace = reader.text(); + byte[] authorizationBindingBytes = reader.bytes(); + String authorizationBindingDigest = reader.text(); + byte[] selectedSourceBytes = reader.bytes(); + String selectedSourceDigest = reader.text(); + byte[] selectedSourceRevisionBindingBytes = reader.bytes(); + String selectedSourceRevisionBindingDigest = reader.text(); + byte[] worldReadRequestBytes = reader.bytes(); + String worldReadRequestDigest = reader.text(); + byte[] worldClosureBytes = reader.bytes(); + String worldClosureDigest = reader.text(); + long localTenantKey = parsePositiveLong(reader.text(), "localTenantKey"); + long localVersionKey = parsePositiveLong(reader.text(), "localVersionKey"); + int stateCount = parsePositiveInt(reader.text(), "familyStateCount"); + if (stateCount != 23) { + throw new IllegalArgumentException("Entity receipt must retain all 23 typed family states"); + } + var states = new ArrayList(stateCount); + for (int index = 0; index < stateCount; index++) { + states.add( + new FamilyCensus( + reader.text(), + FamilyState.valueOf(reader.text()), + FamilyEvidenceKind.valueOf(reader.text()), + parseNonnegativeLong(reader.text(), "rowCount"), + parseNonnegativeLong(reader.text(), "unqualifiedRowCount"), + parseNonnegativeLong(reader.text(), "retainedRowCount"), + parseNonnegativeLong(reader.text(), "selectedScopeRowCount"), + parseNonnegativeLong(reader.text(), "referenceCount"))); + } + UUID genesisId = parseUuid(reader.text(), "genesisId"); + String requestDigest = reader.text(); + UUID worldReadRequestId = parseUuid(reader.text(), "worldReadRequestId"); + OffsetDateTime retainedAt = parseTimestamp(reader.text()); + reader.requireEnd(); + var result = + new EntityEmptySelectedSourceIntakeReceipt( + namespace, + genesisId, + localTenantKey, + localVersionKey, + requestDigest, + schemaDigest, + authorizationBindingBytes, + authorizationBindingDigest, + selectedSourceBytes, + selectedSourceDigest, + selectedSourceRevisionBindingBytes, + selectedSourceRevisionBindingDigest, + worldReadRequestId, + worldReadRequestBytes, + worldReadRequestDigest, + worldClosureBytes, + worldClosureDigest, + states, + retainedAt); + if (!Arrays.equals(stored, result.canonicalBytes)) { + throw new IllegalArgumentException("Noncanonical stored Entity source catalogue receipt"); + } + return result; + } + + public String targetNamespace() { + return targetNamespace; + } + + public UUID genesisId() { + return genesisId; + } + + public UUID operationId() { + return operationId; + } + + public UUID fenceId() { + return fenceId; + } + + public UUID intakeRequestId() { + return intakeRequestId; + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public UUID canonicalVersionId() { + return canonicalVersionId; + } + + public UUID selectedCommitId() { + return selectedCommitId; + } + + public UUID sourceRevisionId() { + return sourceRevisionId; + } + + public String sourceRevisionOrder() { + return sourceRevisionOrder; + } + + public long localTenantKey() { + return localTenantKey; + } + + public long localVersionKey() { + return localVersionKey; + } + + public String requestDigest() { + return requestDigest; + } + + public String schemaDigest() { + return schemaDigest; + } + + public String authorizationBindingDigest() { + return authorizationBindingDigest; + } + + public byte[] authorizationBindingBytes() { + return authorizationBindingBytes.clone(); + } + + public String selectedSourceDigest() { + return selectedSourceDigest; + } + + public String selectedSourceRevisionBindingDigest() { + return selectedSourceRevisionBindingDigest; + } + + public byte[] selectedSourceBytes() { + return selectedSourceBytes.clone(); + } + + public UUID worldReadRequestId() { + return worldReadRequestId; + } + + public String worldReadRequestDigest() { + return worldReadRequestDigest; + } + + public byte[] worldReadRequestBytes() { + return worldReadRequestBytes.clone(); + } + + public String worldClosureDigest() { + return worldClosureDigest; + } + + public byte[] worldClosureBytes() { + return worldClosureBytes.clone(); + } + + /** Digest of one persisted EMPTY-only provider row, bound to this exact retained source. */ + public String providerStateDigest(String family) { + if (evidenceKindForFamily(family) != FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER) { + throw new IllegalArgumentException("Family is not backed by an EMPTY-only Entity provider"); + } + var out = new ByteArrayOutputStream(); + frame(out, "entity-empty-only-family-provider-state/v1"); + frame(out, Integer.toString(SCHEMA_VERSION)); + frame(out, targetNamespace); + frame(out, authorizationBindingBytes); + frame(out, authorizationBindingDigest); + frame(out, selectedSourceBytes); + frame(out, selectedSourceDigest); + frame(out, selectedSourceRevisionBindingBytes); + frame(out, selectedSourceRevisionBindingDigest); + frame(out, worldClosureBytes); + frame(out, worldClosureDigest); + frame(out, Long.toString(localTenantKey)); + frame(out, Long.toString(localVersionKey)); + frame(out, genesisId.toString()); + frame(out, family); + frame(out, "providerSchemaVersion=1"); + frame(out, FamilyState.EMPTY.name()); + frame(out, "rowCount=0"); + frame(out, "referenceCount=0"); + return DraftAuthorizationFenceBinding.digest(out.toByteArray()); + } + + public List familyStates() { + return List.copyOf(familyStates); + } + + public OffsetDateTime retainedAt() { + return retainedAt; + } + + public String receiptDigest() { + return receiptDigest; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String outcome() { + return "COMMITTED_EMPTY"; + } + + public String sourceParticipationDisposition() { + return "PENDING_OWNER_TERMINAL_SETTLEMENT"; + } + + public SelectedOwnerIntakeAuthorizationBinding authorizationBinding() { + return authorizationBinding; + } + + public SelectedOwnerEmptySourceInputs inputs() { + return inputs; + } + + public void requireSameRequest( + String namespace, + SelectedOwnerIntakeAuthorizationBinding candidateBinding, + WorldSelectedDraftPublicationFreezeEvidence candidateFreeze) { + Objects.requireNonNull(candidateBinding, "candidate Account binding is required"); + Objects.requireNonNull(candidateFreeze, "candidate World freeze is required"); + if (!targetNamespace.equals(namespace) + || !requestDigest.equals(requestDigest(namespace, candidateBinding, candidateFreeze)) + || !Arrays.equals(authorizationBindingBytes, candidateBinding.canonicalBytes()) + || !inputs + .worldInventoryReadEvidence() + .request() + .freezeEvidence() + .equals(candidateFreeze)) { + throw new IllegalStateException( + "Entity source request identity already records different selected evidence"); + } + } + + public void requireSameInputs(SelectedOwnerEmptySourceInputs candidate) { + Objects.requireNonNull(candidate, "validated selected empty-source inputs are required"); + requireSameRequest( + candidate.authorizationBinding().targetNamespace(), + candidate.authorizationBinding(), + candidate.worldInventoryReadEvidence().request().freezeEvidence()); + if (!Arrays.equals( + worldClosureBytes, candidate.worldInventoryReadEvidence().inventory().canonicalBytes()) + || !worldClosureDigest.equals(candidate.worldInventoryReadEvidence().inventory().digest()) + || !Arrays.equals(selectedSourceBytes, candidate.sourceContent().canonicalBytes()) + || !selectedSourceDigest.equals(candidate.sourceContent().digest())) { + throw new IllegalStateException( + "Entity exact retry changed selected source or World closure"); + } + } + + /** Stable request identity; the fresh World read correlation is intentionally excluded. */ + public static String requestDigest( + String namespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + requireText(namespace, "targetNamespace"); + Objects.requireNonNull(binding, "binding"); + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); + var out = new ByteArrayOutputStream(); + frame(out, "entity-selected-empty-source-catalogue-request/v1"); + frame(out, namespace); + frame(out, binding.canonicalBytes()); + frame( + out, + net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec + .toRequest(freezeEvidence.request()) + .toByteArray()); + frame( + out, + net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec + .toResponse(freezeEvidence.acknowledgement()) + .toByteArray()); + return DraftAuthorizationFenceBinding.digest(out.toByteArray()); + } + + public static String schemaDigest(String canonicalEntityDeclaration) { + return schemaDigest(familyNames(canonicalEntityDeclaration)); + } + + private byte[] encode() { + var out = new ByteArrayOutputStream(); + frame(out, DOMAIN); + frame(out, Integer.toString(SCHEMA_VERSION)); + frame(out, schemaDigest); + frame(out, targetNamespace); + frame(out, authorizationBindingBytes); + frame(out, authorizationBindingDigest); + frame(out, selectedSourceBytes); + frame(out, selectedSourceDigest); + frame(out, selectedSourceRevisionBindingBytes); + frame(out, selectedSourceRevisionBindingDigest); + frame(out, worldReadRequestBytes); + frame(out, worldReadRequestDigest); + frame(out, worldClosureBytes); + frame(out, worldClosureDigest); + frame(out, Long.toString(localTenantKey)); + frame(out, Long.toString(localVersionKey)); + frame(out, Integer.toString(familyStates.size())); + for (FamilyCensus state : familyStates) { + frame(out, state.family()); + frame(out, state.state().name()); + frame(out, state.evidenceKind().name()); + frame(out, Long.toString(state.rowCount())); + frame(out, Long.toString(state.unqualifiedRowCount())); + frame(out, Long.toString(state.retainedRowCount())); + frame(out, Long.toString(state.selectedScopeRowCount())); + frame(out, Long.toString(state.referenceCount())); + } + frame(out, genesisId.toString()); + frame(out, requestDigest); + frame(out, worldReadRequestId.toString()); + frame(out, retainedAt.toString()); + return out.toByteArray(); + } + + private static SelectedOwnerEmptySourceInputs decodeInputs( + SelectedOwnerIntakeAuthorizationBinding binding, + UUID readRequestId, + byte[] requestBytes, + String requestDigest, + byte[] closureBytes, + String closureDigest) { + UUID checkedRequestId = requireUuid(readRequestId, "worldReadRequestId"); + byte[] boundedRequest = + boundedBytes( + requestBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_WIRE_BYTES, + "worldReadRequestBytes"); + if (!DraftAuthorizationFenceBinding.digest(boundedRequest) + .equals(requireDigest(requestDigest, "worldReadRequestDigest"))) { + throw new IllegalArgumentException("Retained World read request digest differs"); + } + final ReadSelectedOwnerWorldInventoryRequest requestMessage; + try { + requestMessage = ReadSelectedOwnerWorldInventoryRequest.parseFrom(boundedRequest); + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalArgumentException("Retained World read request is malformed", invalid); + } + if (!Arrays.equals(boundedRequest, requestMessage.toByteArray())) { + throw new IllegalArgumentException("Retained World read request is not canonical"); + } + var request = SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(requestMessage); + if (!request.readRequestId().equals(checkedRequestId) + || !request.targetNamespace().equals(binding.targetNamespace()) + || !Arrays.equals( + binding.canonicalBytes(), request.authorizationBinding().canonicalBytes())) { + throw new IllegalArgumentException( + "Retained World request differs from original Entity binding"); + } + byte[] boundedClosure = + boundedBytes( + closureBytes, + SelectedOwnerWorldInventoryReadEvidence.MAX_PUBLIC_INVENTORY_BYTES, + "worldClosureBytes"); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromCanonicalBytes( + request.freezeEvidence(), + boundedClosure, + requireDigest(closureDigest, "worldClosureDigest")); + return new SelectedOwnerEmptySourceInputs( + binding, new SelectedOwnerWorldInventoryReadEvidence(request, inventory)); + } + + private static List requireAllEmptyStates( + List states, List expectedFamilies) { + List copy = List.copyOf(Objects.requireNonNull(states, "familyStates")); + if (expectedFamilies.size() != 23 || copy.size() != expectedFamilies.size()) { + throw new IllegalArgumentException("All 23 Entity owner family states are required"); + } + for (int index = 0; index < expectedFamilies.size(); index++) { + FamilyCensus state = copy.get(index); + if (!expectedFamilies.get(index).equals(state.family()) + || state.state() != FamilyState.EMPTY) { + throw new IllegalArgumentException( + "Entity family states must be complete, ordered, and explicitly EMPTY"); + } + } + return copy; + } + + public static List familyNames(String canonicalDeclaration) { + try { + var root = JSON.readTree(canonicalDeclaration); + var families = root.get("families"); + if (families == null || !families.isObject()) { + throw new IllegalArgumentException("Typed Entity family declaration is required"); + } + var names = new ArrayList(); + families.properties().forEach(property -> names.add(property.getKey())); + names.sort(String::compareTo); + if (names.size() != 23) { + throw new IllegalArgumentException("Typed Entity declaration must provide all 23 families"); + } + return List.copyOf(names); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Entity family order could not be derived from its typed declaration", malformed); + } + } + + private static String schemaDigest(List familyNames) { + var out = new ByteArrayOutputStream(); + frame(out, "entity-selected-empty-source-catalogue-schema/v1"); + frame(out, DOMAIN); + frame(out, Integer.toString(SCHEMA_VERSION)); + frame(out, "encoding=ADR-0047-byte-length-frames;strings=UTF-8;counts=canonical-decimal"); + for (String field : + List.of( + "targetNamespace:utf8", + "authorizationBindingBytes:canonical-original-account-binding", + "authorizationBindingDigest:sha256", + "selectedSourceBytes:canonical-game-design-source-content", + "selectedSourceDigest:sha256", + "selectedSourceRevisionBindingBytes:canonical-game-design-source-operation-binding", + "selectedSourceRevisionBindingDigest:sha256", + "worldReadRequestBytes:canonical-recipient-qualified-world-request", + "worldReadRequestDigest:sha256", + "worldClosureBytes:canonical-public-world-inventory", + "worldClosureDigest:sha256", + "localTenantKey:positive-canonical-decimal", + "localVersionKey:positive-canonical-decimal", + "familyStates:count-then-23-lexical-family-records-with-provider-kind", + "genesisId:canonical-uuid", + "requestDigest:sha256", + "worldReadRequestId:canonical-uuid", + "retainedAt:canonical-utc-offset-date-time")) { + frame(out, field); + } + frame( + out, + "familyRecordFields=count-then-family,state,evidenceKind,rowCount,unqualifiedRowCount,retainedRowCount,selectedScopeRowCount,referenceCount"); + frame(out, "family:utf8"); + frame(out, "state=EMPTY"); + frame(out, "evidenceKind=V1_SOURCE_CENSUS|EMPTY_ONLY_OWNER_PROVIDER"); + frame(out, "rowCount:canonical-nonnegative-decimal"); + frame(out, "unqualifiedRowCount:canonical-nonnegative-decimal"); + frame(out, "retainedRowCount:canonical-nonnegative-decimal"); + frame(out, "selectedScopeRowCount:canonical-nonnegative-decimal"); + frame(out, "referenceCount:canonical-nonnegative-decimal"); + frame(out, Integer.toString(familyNames.size())); + for (String family : familyNames) frame(out, family); + return DraftAuthorizationFenceBinding.digest(out.toByteArray()); + } + + private static String requireSameNamespace( + String namespace, SelectedOwnerIntakeAuthorizationBinding binding) { + if (!namespace.equals(binding.targetNamespace())) { + throw new IllegalArgumentException("Entity authorization namespace differs"); + } + return namespace; + } + + private static FamilyEvidenceKind evidenceKindForFamily(String family) { + return switch (family) { + case "ITEM_TEMPLATE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "CRAFTING_RECIPE_ROOTS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_INGREDIENT_BINDINGS", + "EQUIPMENT_SLOT_ROOTS", + "EQUIPMENT_SLOT_GROUPS", + "BODY_LAYOUT_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS" -> + FamilyEvidenceKind.V1_SOURCE_CENSUS; + case "ACTOR_BODY_LAYOUT_ASSIGNMENTS", + "ARCHETYPE_ASSIGNMENTS", + "ARCHETYPE_CONSTRAINTS", + "ARCHETYPE_ROOTS", + "BALANCE_CURVE_ATTACHMENTS", + "BALANCE_CURVE_ROOTS", + "EQUIPMENT_ATTACHMENT_RULES", + "EQUIPMENT_CAPABILITIES", + "EQUIPMENT_COMPATIBILITY_RULES", + "EQUIPMENT_OCCUPANCY_RULES", + "INBOUND_LOOT_BINDINGS", + "LOOT_ITEM_MAPPINGS", + "LOOT_TABLE_ROOTS", + "OTHER_ACTOR_TEMPLATE_ROOTS" -> + FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER; + default -> throw new IllegalArgumentException("Unsupported Entity family: " + family); + }; + } + + private static String requireText(String value, String label) { + if (value == null || value.isBlank() || value.indexOf('\0') >= 0) { + throw new IllegalArgumentException(label + " is required"); + } + return value; + } + + private static String requireDigest(String value, String label) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(label + " must be canonical SHA-256"); + } + return value; + } + + private static byte[] boundedBytes(byte[] value, int max, String label) { + if (value == null || value.length == 0 || value.length > max) { + throw new IllegalArgumentException(label + " is absent or exceeds its limit"); + } + return value.clone(); + } + + private static UUID requireUuid(UUID value, String label) { + DraftAuthorizationFenceBinding.requireUuid(value); + return value; + } + + private static UUID parseUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value)) throw new IllegalArgumentException("Noncanonical UUID"); + return requireUuid(parsed, label); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException(label + " must be a canonical nonzero UUID", invalid); + } + } + + private static String requireDecimal(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, true); + return value; + } + + private static long parsePositiveLong(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, false); + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal"); + } + return parsed; + } + + private static long parseNonnegativeLong(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, true); + long parsed = Long.parseLong(value); + if (parsed < 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be a canonical nonnegative decimal"); + } + return parsed; + } + + private static int parsePositiveInt(String value, String label) { + DraftAuthorizationFenceBinding.decimal(value, false); + int parsed = Integer.parseInt(value); + if (parsed <= 0 || !Integer.toString(parsed).equals(value)) { + throw new IllegalArgumentException(label + " must be a positive canonical decimal"); + } + return parsed; + } + + private static OffsetDateTime parseTimestamp(String value) { + final OffsetDateTime parsed; + try { + parsed = OffsetDateTime.parse(value); + } catch (DateTimeParseException malformed) { + throw new IllegalArgumentException("Receipt timestamp must be canonical UTC", malformed); + } + if (parsed.getOffset().getTotalSeconds() != 0 || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Receipt timestamp must be canonical UTC"); + } + return parsed; + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + public enum FamilyState { + EMPTY + } + + /** Distinguishes source census from a newly persisted fresh-only owner state. */ + public enum FamilyEvidenceKind { + V1_SOURCE_CENSUS, + EMPTY_ONLY_OWNER_PROVIDER + } + + /** Actual owner-local census and reference counts captured under the source-table guard. */ + public record FamilyCensus( + String family, + FamilyState state, + FamilyEvidenceKind evidenceKind, + long rowCount, + long unqualifiedRowCount, + long retainedRowCount, + long selectedScopeRowCount, + long referenceCount) { + public FamilyCensus { + requireText(family, "family"); + Objects.requireNonNull(state, "state"); + Objects.requireNonNull(evidenceKind, "evidenceKind"); + if (evidenceKindForFamily(family) != evidenceKind) { + throw new IllegalArgumentException("Entity family evidence kind differs from its provider"); + } + if (rowCount < 0L + || unqualifiedRowCount < 0L + || retainedRowCount < 0L + || selectedScopeRowCount < 0L + || referenceCount < 0L) { + throw new IllegalArgumentException("Entity family census counts must be nonnegative"); + } + if (state == FamilyState.EMPTY + && (rowCount != 0L + || unqualifiedRowCount != 0L + || retainedRowCount != 0L + || selectedScopeRowCount != 0L + || referenceCount != 0L)) { + throw new IllegalArgumentException("An EMPTY Entity family must have a zero owner census"); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandEvidence.java new file mode 100644 index 0000000000..fa7082e0ba --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandEvidence.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; + +/** Exact Game Design command correlation and the immutable Entity receipt. */ +public record EntitySelectedSourceIntakeCommandEvidence( + Request request, EntityEmptySelectedSourceIntakeReceipt receipt) { + public EntitySelectedSourceIntakeCommandEvidence { + Objects.requireNonNull(request, "selected-source command request is required"); + Objects.requireNonNull(receipt, "committed Entity receipt is required"); + try { + receipt.requireSameRequest( + request.targetNamespace(), + request.originalAuthorizationBinding(), + request.freezeEvidence()); + } catch (RuntimeException mismatch) { + throw new IllegalArgumentException( + "Entity receipt differs from the complete selected-source command", mismatch); + } + if (!Arrays.equals( + request.originalIntakeAuthorizationBinding(), receipt.authorizationBindingBytes()) + || !request.intakeAuthorizationDigest().equals(receipt.authorizationBindingDigest())) { + throw new IllegalArgumentException( + "Entity receipt differs from the original Account authorization bytes"); + } + } + + /** Caller-generated transport correlation; all retained inputs remain the original values. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + public static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public Request { + Objects.requireNonNull( + originalAuthorizationBinding, "original Account authorization is required"); + Objects.requireNonNull(freezeEvidence, "complete World freeze evidence is required"); + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !targetNamespace.equals(originalAuthorizationBinding.targetNamespace()) + || originalAuthorizationBinding.canonicalBytes().length == 0 + || originalAuthorizationBinding.canonicalBytes().length + > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + || originalAuthorizationBinding.owner() != Owner.ENTITY_MANAGEMENT + || !"account-entity-intake-authorization/v1".equals(originalAuthorizationBinding.schema()) + || !"ENTITY_INTAKE_RETENTION".equals(originalAuthorizationBinding.purpose()) + || !targetNamespace.equals(freezeEvidence.request().targetNamespace()) + || !originalAuthorizationBinding + .tenantId() + .equals(freezeEvidence.request().canonicalTenantId()) + || !originalAuthorizationBinding + .versionId() + .equals(freezeEvidence.request().canonicalVersionId()) + || !originalAuthorizationBinding + .selected() + .equals( + freezeEvidence.request().accountBinding().input().selection().selectedCommit()) + || !originalAuthorizationBinding + .selected() + .commitId() + .toString() + .equals(freezeEvidence.acknowledgement().appliedCommitId())) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(transportRequestId); + if (NIL_UUID.equals(transportRequestId) + || collidesWithRetainedIdentity( + transportRequestId, originalAuthorizationBinding, freezeEvidence)) { + throw invalid(); + } + } + + public static Request create( + String namespace, + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + Objects.requireNonNull( + originalAuthorizationBinding, "original Account authorization is required"); + Objects.requireNonNull(freezeEvidence, "complete World freeze evidence is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (collidesWithRetainedIdentity( + correlation, originalAuthorizationBinding, freezeEvidence)); + return new Request( + SCHEMA_VERSION, namespace, correlation, originalAuthorizationBinding, freezeEvidence); + } + + public byte[] originalIntakeAuthorizationBinding() { + return originalAuthorizationBinding.canonicalBytes(); + } + + public String intakeAuthorizationDigest() { + return originalAuthorizationBinding.digest(); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && transportRequestId.equals(other.transportRequestId) + && Arrays.equals( + originalIntakeAuthorizationBinding(), other.originalIntakeAuthorizationBinding()) + && intakeAuthorizationDigest().equals(other.intakeAuthorizationDigest()) + && freezeEvidence.equals(other.freezeEvidence); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, + targetNamespace, + transportRequestId, + Arrays.hashCode(originalIntakeAuthorizationBinding()), + intakeAuthorizationDigest(), + freezeEvidence); + } + + private static boolean collidesWithRetainedIdentity( + UUID candidate, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freeze) { + if (candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()) + || candidate.equals(binding.selected().requestId()) + || candidate.equals(binding.selected().commitId())) { + return true; + } + var account = freeze.request().accountBinding(); + var selection = account.input().selection(); + List freezeIds = + new ArrayList<>( + List.of( + account.operationId(), + account.fenceId(), + selection.fenceRequestId(), + selection.fenceCommitId(), + selection.selectedCommit().requestId(), + selection.selectedCommit().commitId(), + freeze.acknowledgement().intakeRequestId(), + freeze.acknowledgement().publicationFence())); + if (freezeIds.contains(candidate)) return true; + try { + UUID publicationRequestId = UUID.fromString(freeze.request().publicationRequestId()); + return publicationRequestId.toString().equals(freeze.request().publicationRequestId()) + && publicationRequestId.equals(candidate); + } catch (IllegalArgumentException notUuid) { + return false; + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Entity selected-source command request"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodec.java new file mode 100644 index 0000000000..47e71734fc --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodec.java @@ -0,0 +1,193 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence.Request; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse; + +/** Closed Entity mapping with complete original Account/World evidence and exact receipt echo. */ +public final class EntitySelectedSourceIntakeCommandGrpcCodec { + private static final int MAX_REQUEST_FRAMING_BYTES = 64 * 1024; + + /** Original authorization, complete freeze request and acknowledgement, and outer framing. */ + public static final int MAX_REQUEST_WIRE_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + 2 * WorldSelectedDraftPublicationFreezeEvidence.Request.MAX_ACCOUNT_BINDING_BYTES + + MAX_REQUEST_FRAMING_BYTES; + + /** Full Entity receipt, full echoed request and bounded response framing. */ + public static final int MAX_RESPONSE_WIRE_BYTES = + EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES + + MAX_REQUEST_WIRE_BYTES + + MAX_REQUEST_FRAMING_BYTES; + + private EntitySelectedSourceIntakeCommandGrpcCodec() {} + + public static RetainSelectedEntitySourceRequest toRequest(Request request) { + Objects.requireNonNull(request, "selected-source command request is required"); + byte[] authorizationBytes = request.originalIntakeAuthorizationBinding(); + if (authorizationBytes.length == 0 + || authorizationBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Account authorization exceeds its 16 MiB limit"); + } + var freeze = request.freezeEvidence(); + var wire = + RetainSelectedEntitySourceRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setTransportRequestId(request.transportRequestId().toString()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(authorizationBytes)) + .setIntakeAuthorizationDigest(request.intakeAuthorizationDigest()) + .setFreezeRequest( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())) + .setFreezeAcknowledgement( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())) + .build(); + requireWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request"); + return wire; + } + + /** Decode only after the receiver authenticates the exact same-namespace Game Design peer. */ + public static Request fromRequest(RetainSelectedEntitySourceRequest wire) { + requireKnownAndWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request"); + if (!wire.hasFreezeRequest() || !wire.hasFreezeAcknowledgement()) { + throw invalid("Complete original World freeze request and acknowledgement are required"); + } + UUID transportRequestId = canonicalUuid(wire.getTransportRequestId()); + int authorizationSize = wire.getOriginalIntakeAuthorizationBinding().size(); + if (authorizationSize == 0 + || authorizationSize > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Account authorization size is invalid"); + } + byte[] authorizationBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + final SelectedOwnerIntakeAuthorizationBinding authorization; + try { + authorization = SelectedOwnerIntakeAuthorizationBinding.fromStored(authorizationBytes); + } catch (RuntimeException malformed) { + throw invalid("Original Account authorization is invalid", malformed); + } + if (!authorization.digest().equals(wire.getIntakeAuthorizationDigest())) { + throw invalid("Original Account authorization digest differs"); + } + final WorldSelectedDraftPublicationFreezeEvidence freezeEvidence; + try { + var freezeRequest = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(wire.getFreezeRequest()); + freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, wire.getFreezeAcknowledgement()); + } catch (RuntimeException malformed) { + throw invalid("Complete original World freeze evidence is invalid", malformed); + } + final Request request; + try { + request = + new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + transportRequestId, + authorization, + freezeEvidence); + } catch (RuntimeException malformed) { + throw invalid("Entity selected-source command binding is invalid", malformed); + } + if (!toRequest(request).equals(wire)) { + throw invalid("Selected-source command request is not an exact canonical echo"); + } + return request; + } + + public static RetainSelectedEntitySourceResponse toResponse( + EntitySelectedSourceIntakeCommandEvidence evidence) { + Objects.requireNonNull(evidence, "selected-source command evidence is required"); + byte[] receiptBytes = evidence.receipt().canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Committed Entity receipt size is invalid"); + } + var response = + RetainSelectedEntitySourceResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setCommittedEmptyReceipt(ByteString.copyFrom(receiptBytes)) + .setReceiptDigest(evidence.receipt().receiptDigest()) + .build(); + requireWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response"); + return response; + } + + /** + * Requires the exact complete request echo and verifies the canonical retained Entity receipt. + */ + public static EntitySelectedSourceIntakeCommandEvidence fromResponse( + Request expected, RetainSelectedEntitySourceResponse response) { + Objects.requireNonNull(expected, "selected-source command request is required"); + requireKnownAndWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response"); + if (!response.hasRequest()) { + throw invalid("Exact selected-source command request echo is required"); + } + if (!response.getRequest().equals(toRequest(expected))) { + throw invalid("Entity changed the exact selected-source command request"); + } + int receiptSize = response.getCommittedEmptyReceipt().size(); + if (receiptSize == 0 || receiptSize > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Missing or oversized committed Entity receipt"); + } + final EntityEmptySelectedSourceIntakeReceipt receipt; + try { + receipt = + EntityEmptySelectedSourceIntakeReceipt.fromStored( + response.getCommittedEmptyReceipt().toByteArray()); + } catch (RuntimeException malformed) { + throw invalid("Committed Entity receipt is invalid", malformed); + } + if (!receipt.receiptDigest().equals(response.getReceiptDigest())) { + throw invalid("Entity receipt digest differs"); + } + try { + return new EntitySelectedSourceIntakeCommandEvidence(expected, receipt); + } catch (RuntimeException mismatch) { + throw invalid("Entity receipt differs from the complete original command", mismatch); + } + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw invalid("Canonical nonzero transport request UUID required"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid("Canonical nonzero transport request UUID required", malformed); + } + } + + private static void requireKnownAndWithinBudget(Message wire, int budget, String label) { + if (wire == null || wire.getSerializedSize() > budget) { + throw invalid("Entity selected-source command " + label + " exceeds its wire budget"); + } + if (!wire.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown Entity selected-source command " + label + " fields"); + } + } + + private static void requireWithinBudget(Message wire, int budget, String label) { + if (wire.getSerializedSize() > budget) { + throw invalid("Entity selected-source command " + label + " exceeds its wire budget"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadClient.java new file mode 100644 index 0000000000..c6969746a6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadClient.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +/** Transport boundary for reading Entity's exact original selected-source terminal. */ +public interface EntitySelectedSourceIntakeTerminalReadClient { + EntitySelectedSourceIntakeTerminalReadEvidence read( + EntitySelectedSourceIntakeTerminalReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java new file mode 100644 index 0000000000..826c228781 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadEvidence.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact lookup correlation and the original committed Entity receipt. */ +public record EntitySelectedSourceIntakeTerminalReadEvidence( + Request request, EntityEmptySelectedSourceIntakeReceipt receipt) { + public static final int SCHEMA_VERSION = 1; + public static final String TERMINAL_READ_PURPOSE = "ENTITY_INTAKE_TERMINAL_READ"; + + public EntitySelectedSourceIntakeTerminalReadEvidence { + Objects.requireNonNull(request, "terminal-read request is required"); + Objects.requireNonNull(receipt, "committed Entity receipt is required"); + if (!request.targetNamespace().equals(receipt.targetNamespace()) + || !Arrays.equals(request.binding().canonicalBytes(), receipt.authorizationBindingBytes()) + || !"COMMITTED_EMPTY".equals(receipt.outcome())) { + throw new IllegalArgumentException( + "Entity receipt differs from the complete original terminal-read binding"); + } + } + + /** The correlation changes per transport read and never changes the retained operation. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID readRequestId, + SelectedOwnerIntakeAuthorizationBinding binding) { + public Request { + if (schemaVersion != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || binding == null + || !targetNamespace.equals(binding.targetNamespace()) + || binding.owner() != Owner.ENTITY_MANAGEMENT + || !"account-entity-intake-authorization/v1".equals(binding.schema()) + || !"ENTITY_INTAKE_RETENTION".equals(binding.purpose()) + || binding.canonicalBytes().length == 0 + || binding.canonicalBytes().length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid(); + } + DraftAuthorizationFenceBinding.requireUuid(readRequestId); + if (collides(readRequestId, binding)) throw invalid(); + } + + public static Request create( + String namespace, SelectedOwnerIntakeAuthorizationBinding binding) { + Objects.requireNonNull(binding, "original finalized Account binding is required"); + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (collides(correlation, binding)); + return new Request(SCHEMA_VERSION, namespace, correlation, binding); + } + + /** Account is the only intended reader of this Entity-owned terminal. */ + public String intendedReader() { + return "spiffe://firemud/ns/" + targetNamespace + "/sa/account-service"; + } + + public String terminalReadPurpose() { + return TERMINAL_READ_PURPOSE; + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && schemaVersion == other.schemaVersion + && targetNamespace.equals(other.targetNamespace) + && readRequestId.equals(other.readRequestId) + && Arrays.equals(binding.canonicalBytes(), other.binding.canonicalBytes()); + } + + @Override + public int hashCode() { + return Objects.hash( + schemaVersion, targetNamespace, readRequestId, Arrays.hashCode(binding.canonicalBytes())); + } + + private static boolean collides( + UUID candidate, SelectedOwnerIntakeAuthorizationBinding binding) { + return candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid Entity selected-source terminal request"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..c205600c49 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodec.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalResult; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse; + +/** Closed terminal mapping with an unchanged request echo and canonical receipt validation. */ +public final class EntitySelectedSourceIntakeTerminalReadGrpcCodec { + private static final int MAX_REQUEST_FRAMING_BYTES = 64 * 1024; + + /** Full receipt plus the complete echoed 16 MiB Account binding and bounded protobuf framing. */ + public static final int MAX_REQUEST_WIRE_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + MAX_REQUEST_FRAMING_BYTES; + + public static final int MAX_WIRE_BYTES = + EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES + MAX_REQUEST_WIRE_BYTES; + + private EntitySelectedSourceIntakeTerminalReadGrpcCodec() {} + + public static ReadSelectedSourceIntakeTerminalRequest toRequest( + EntitySelectedSourceIntakeTerminalReadEvidence.Request request) { + Objects.requireNonNull(request, "terminal-read request is required"); + byte[] bindingBytes = request.binding().canonicalBytes(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Entity authorization exceeds its 16 MiB limit"); + } + var wire = + ReadSelectedSourceIntakeTerminalRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setIntendedReader(request.intendedReader()) + .setTerminalReadPurpose(request.terminalReadPurpose()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(bindingBytes)) + .setIntakeAuthorizationDigest(request.binding().digest()) + .build(); + requireWithinBudget(wire.getSerializedSize(), MAX_REQUEST_WIRE_BYTES, "request"); + return wire; + } + + public static EntitySelectedSourceIntakeTerminalReadEvidence.Request fromRequest( + ReadSelectedSourceIntakeTerminalRequest wire) { + requireKnownAndWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request"); + DraftAuthorizationFenceBinding.canonicalUuid(wire.getReadRequestId()); + byte[] bindingBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + if (bindingBytes.length == 0 + || bindingBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Entity authorization size is invalid"); + } + var binding = SelectedOwnerIntakeAuthorizationBinding.fromStored(bindingBytes); + if (!binding.digest().equals(wire.getIntakeAuthorizationDigest())) { + throw invalid("Original Entity authorization digest differs"); + } + var request = + new EntitySelectedSourceIntakeTerminalReadEvidence.Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + UUID.fromString(wire.getReadRequestId()), + binding); + if (!request.intendedReader().equals(wire.getIntendedReader()) + || !request.terminalReadPurpose().equals(wire.getTerminalReadPurpose()) + || !toRequest(request).equals(wire)) { + throw invalid("Terminal reader, purpose, or request differs"); + } + return request; + } + + public static ReadSelectedSourceIntakeTerminalResponse toResponse( + EntitySelectedSourceIntakeTerminalReadEvidence evidence) { + Objects.requireNonNull(evidence, "committed Entity terminal evidence is required"); + byte[] receiptBytes = evidence.receipt().canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Committed Entity receipt size is invalid"); + } + var response = + ReadSelectedSourceIntakeTerminalResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setResult( + EntitySelectedSourceIntakeTerminalResult + .ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY) + .setCommittedEmptyReceipt(ByteString.copyFrom(receiptBytes)) + .setReceiptDigest(evidence.receipt().receiptDigest()) + .build(); + requireWithinBudget(response.getSerializedSize(), MAX_WIRE_BYTES, "response"); + return response; + } + + public static EntitySelectedSourceIntakeTerminalReadEvidence fromResponse( + EntitySelectedSourceIntakeTerminalReadEvidence.Request request, + ReadSelectedSourceIntakeTerminalResponse response) { + Objects.requireNonNull(request, "terminal-read request is required"); + requireKnownAndWithinBudget(response, MAX_WIRE_BYTES, "response"); + if (!response.hasRequest() + || !toRequest(request).equals(response.getRequest()) + || response.getResult() + != EntitySelectedSourceIntakeTerminalResult + .ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY) { + throw invalid("Exact COMMITTED_EMPTY response and full request echo required"); + } + byte[] receiptBytes = response.getCommittedEmptyReceipt().toByteArray(); + if (receiptBytes.length == 0 + || receiptBytes.length > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Missing or oversized committed Entity receipt"); + } + EntityEmptySelectedSourceIntakeReceipt receipt = + EntityEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes); + if (!receipt.receiptDigest().equals(response.getReceiptDigest())) { + throw invalid("Entity receipt digest differs"); + } + return new EntitySelectedSourceIntakeTerminalReadEvidence(request, receipt); + } + + private static void requireKnownAndWithinBudget(Message wire, int maxBytes, String label) { + if (wire == null || wire.getSerializedSize() > maxBytes) { + throw invalid("Missing or oversized Entity terminal-read " + label); + } + if (!wire.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown Entity terminal-read " + label + " fields"); + } + } + + private static void requireWithinBudget(int size, int maxBytes, String label) { + if (size > maxBytes) { + throw invalid("Entity terminal-read " + label + " exceeds its derived wire budget"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java index 6c73b641b7..22735d97ef 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceiptTest.java @@ -10,6 +10,8 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; import org.junit.jupiter.api.Test; /** Synthetic upstream value tests; mocks make no Account or Automation authentication claim. */ @@ -61,6 +63,60 @@ void embedsCompleteImmutableEvidenceAndIgnoresOnlyFreshReadCorrelation() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void keepsAutomationBoundsAndFramesWhileEntityUsesItsOwnTypedTerminal() { + assertThat(AccountSelectedOwnerIntakeSettlementReceipt.AUTOMATION_MAX_BYTES) + .isEqualTo(92356608); + assertThat(AccountSelectedOwnerIntakeSettlementReceipt.ENTITY_MAX_BYTES).isEqualTo(117506048); + var binding = binding(); + when(binding.owner()).thenReturn(Owner.ENTITY_MANAGEMENT); + when(binding.schema()).thenReturn("account-entity-intake-authorization/v1"); + when(binding.purpose()).thenReturn("ENTITY_INTAKE_RETENTION"); + var owner = mock(EntityEmptySelectedSourceIntakeReceipt.class); + when(owner.targetNamespace()).thenReturn("test"); + when(owner.authorizationBindingBytes()).thenReturn(BINDING_BYTES.clone()); + when(owner.authorizationBindingDigest()).thenReturn(BINDING_DIGEST); + when(owner.outcome()).thenReturn("COMMITTED_EMPTY"); + when(owner.canonicalBytes()).thenReturn(OWNER_RECEIPT_BYTES.clone()); + when(owner.receiptDigest()).thenReturn(OWNER_RECEIPT_DIGEST); + var first = + new EntitySelectedSourceIntakeTerminalReadEvidence( + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create("test", binding), owner); + var receipt = AccountSelectedOwnerIntakeSettlementReceipt.create(first); + var reader = new DraftAuthorizationFenceBinding.FrameReader(receipt.canonicalBytes()); + reader.expect(AccountSelectedOwnerIntakeSettlementReceipt.DOMAIN); + reader.expect("1"); + assertThat(reader.bytes()).isEqualTo(BINDING_BYTES); + reader.expect(BINDING_DIGEST); + reader.expect("1"); + reader.expect("test"); + reader.expect(first.request().readRequestId().toString()); + reader.expect("spiffe://firemud/ns/test/sa/account-service"); + reader.expect("ENTITY_INTAKE_TERMINAL_READ"); + assertThat(reader.bytes()).isEqualTo(BINDING_BYTES); + reader.expect(BINDING_DIGEST); + assertThat(reader.bytes()).isEqualTo(OWNER_RECEIPT_BYTES); + reader.expect(OWNER_RECEIPT_DIGEST); + reader.requireEnd(); + var retry = + new EntitySelectedSourceIntakeTerminalReadEvidence( + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create("test", binding), owner); + assertThat(receipt.sameImmutableOwnerReceipt(retry)).isTrue(); + assertThat(receipt.entityTerminalEvidence()).isSameAs(first); + assertThatThrownBy(receipt::terminalEvidence).isInstanceOf(IllegalStateException.class); + var changedOwner = mock(EntityEmptySelectedSourceIntakeReceipt.class); + when(changedOwner.targetNamespace()).thenReturn("test"); + when(changedOwner.authorizationBindingBytes()).thenReturn(BINDING_BYTES.clone()); + when(changedOwner.outcome()).thenReturn("COMMITTED_EMPTY"); + when(changedOwner.canonicalBytes()).thenReturn(new byte[] {9}); + when(changedOwner.receiptDigest()) + .thenReturn(DraftAuthorizationFenceBinding.digest(new byte[] {9})); + assertThat( + receipt.sameImmutableOwnerReceipt( + new EntitySelectedSourceIntakeTerminalReadEvidence(retry.request(), changedOwner))) + .isFalse(); + } + private static SelectedOwnerIntakeAuthorizationBinding binding() { var binding = mock(SelectedOwnerIntakeAuthorizationBinding.class); when(binding.canonicalBytes()).thenReturn(BINDING_BYTES.clone()); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java index 4ba7df44df..35d7f4ecde 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java @@ -45,7 +45,7 @@ void roundTripsCanonicalRequestWithIndependentTransportCorrelation() { } @Test - void rejectsDefaultUnknownWrongOwnerAndChangedDigestRequests() { + void rejectsDefaultUnknownAndChangedDigestRequestsWhileAcceptingClosedEntityOwner() { assertThatThrownBy( () -> SelectedOwnerIntakeSettlementGrpcCodec.fromRequest( @@ -77,8 +77,11 @@ void rejectsDefaultUnknownWrongOwnerAndChangedDigestRequests() { .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(entity.canonicalBytes())) .setIntakeAuthorizationDigest(entity.digest()) .build(); - assertThatThrownBy(() -> SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(wrongOwner)) - .isInstanceOf(IllegalArgumentException.class); + assertThat( + SelectedOwnerIntakeSettlementGrpcCodec.fromRequest(wrongOwner) + .authorizationBinding() + .owner()) + .isEqualTo(Owner.ENTITY_MANAGEMENT); } @Test diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java new file mode 100644 index 0000000000..1061b90c2c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java @@ -0,0 +1,213 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence.Request; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** Synthetic fixture codec proof does not establish Entity producer or physical census proof. */ +class EntitySelectedSourceIntakeCommandGrpcCodecTest { + private static final String NAMESPACE = "test"; + private static Fixture fixture; + + @BeforeAll + static void createSyntheticEntityInputs() { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + } + + @Test + void roundTripsCompleteOriginalAuthorizationFreezeAndCanonicalReceiptOnDistinctCorrelations() { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var binding = fixture.authorization(); + var first = Request.create(NAMESPACE, binding, freeze); + var retry = Request.create(NAMESPACE, binding, freeze); + + var firstWire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(first); + var retryWire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(retry); + assertThat(first.transportRequestId()).isNotEqualTo(retry.transportRequestId()); + assertThat(first.transportRequestId()) + .isNotIn( + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.selected().requestId(), + binding.selected().commitId(), + freeze.acknowledgement().intakeRequestId(), + freeze.acknowledgement().publicationFence()); + assertThat(EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(firstWire)).isEqualTo(first); + assertThat(EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(retryWire)).isEqualTo(retry); + assertThat(firstWire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .isEqualTo(binding.canonicalBytes()); + assertThat(firstWire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + assertThat(firstWire.getFreezeRequest()) + .isEqualTo(WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())); + assertThat(firstWire.getFreezeAcknowledgement()) + .isEqualTo( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())); + assertThat(firstWire.getSerializedSize()) + .isLessThanOrEqualTo(EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES); + + var evidence = new EntitySelectedSourceIntakeCommandEvidence(first, fixture.receipt()); + RetainSelectedEntitySourceResponse response = + EntitySelectedSourceIntakeCommandGrpcCodec.toResponse(evidence); + assertThat(response.getRequest()).isEqualTo(firstWire); + assertThat(response.getCommittedEmptyReceipt().toByteArray()) + .isEqualTo(fixture.receipt().canonicalBytes()); + assertThat(response.getReceiptDigest()).isEqualTo(fixture.receipt().receiptDigest()); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(EntitySelectedSourceIntakeCommandGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + var decoded = EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(first, response); + assertThat(decoded.request()).isEqualTo(first); + assertThat(decoded.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes()); + assertThat(decoded.receipt().authorizationBindingBytes()).isEqualTo(binding.canonicalBytes()); + } + + @Test + void rejectsWrongOwnerNamespaceAndChangedOriginalBindingOrFreeze() { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + assertThatThrownBy(() -> Request.create(NAMESPACE, fixture.wrongOwnerAuthorization(), freeze)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> Request.create("other", fixture.authorization(), freeze)) + .isInstanceOf(IllegalArgumentException.class); + + var request = Request.create(NAMESPACE, fixture.authorization(), freeze); + var wire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setIntakeAuthorizationDigest("0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + + byte[] changedBinding = fixture.authorization().canonicalBytes(); + changedBinding[changedBinding.length - 1] ^= 1; + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(changedBinding)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + var changedFreezeRequest = + wire.getFreezeRequest().toBuilder().setRequestDigest("0".repeat(64)).build(); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setFreezeRequest(changedFreezeRequest).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("freeze"); + var changedFreezeAck = + wire.getFreezeAcknowledgement().toBuilder().setAppliedCommitId("0".repeat(36)).build(); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setFreezeAcknowledgement(changedFreezeAck).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("freeze"); + } + + @Test + void rejectsUnknownFieldsOversizedWireAndChangedFullResponseEchoOrDigest() { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var request = Request.create(NAMESPACE, fixture.authorization(), freeze); + var requestWire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + requestWire.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + requestWire.toBuilder() + .setFreezeAcknowledgement( + requestWire.getFreezeAcknowledgement().toBuilder() + .setUnknownFields(unknown) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + RetainSelectedEntitySourceRequest.newBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte + [EntitySelectedSourceIntakeCommandGrpcCodec + .MAX_REQUEST_WIRE_BYTES + + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire budget"); + + var response = + EntitySelectedSourceIntakeCommandGrpcCodec.toResponse( + new EntitySelectedSourceIntakeCommandEvidence(request, fixture.receipt())); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setTransportRequestId(UUID.randomUUID().toString()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed"); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, response.toBuilder().setReceiptDigest("0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + + var changedRequest = Request.create(NAMESPACE, fixture.authorization(), freeze); + assertThatThrownBy( + () -> EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(changedRequest, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed"); + } + + @Test + void transportCorrelationMustBeCanonicalNonzeroAndNotReuseRetainedIdentity() { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var binding = fixture.authorization(); + assertThatThrownBy( + () -> + new Request( + Request.SCHEMA_VERSION, NAMESPACE, binding.operationId(), binding, freeze)) + .isInstanceOf(IllegalArgumentException.class); + var valid = Request.create(NAMESPACE, binding, freeze); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(valid).toBuilder() + .setTransportRequestId("00000000-0000-0000-0000-000000000000") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("UUID"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..7a7e4cc987 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java @@ -0,0 +1,247 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalResult; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +class EntitySelectedSourceIntakeTerminalReadGrpcCodecTest { + private static Fixture fixture; + + @BeforeAll + static void createSyntheticFixture() { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + } + + @Test + void roundTripsCompleteCanonicalReceiptAndOriginalBindingBytes() { + byte[] bindingBytes = fixture.authorization().canonicalBytes(); + byte[] receiptBytes = fixture.receipt().canonicalBytes(); + var request = + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + "test", fixture.authorization()); + var requestWire = EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request); + var decodedRequest = EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(requestWire); + + assertThat(decodedRequest).isEqualTo(request); + assertThat(decodedRequest.readRequestId()) + .isNotIn( + fixture.authorization().operationId(), + fixture.authorization().fenceId(), + fixture.authorization().intakeRequestId()); + assertThat(decodedRequest.binding().canonicalBytes()).isEqualTo(bindingBytes); + assertThat(decodedRequest.binding().digest()).isEqualTo(fixture.authorization().digest()); + + var response = + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence(request, fixture.receipt())); + assertThat(response.getSerializedSize()).isGreaterThan(4 * 1024 * 1024); + assertThat(response.getResult()) + .isEqualTo( + EntitySelectedSourceIntakeTerminalResult + .ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_COMMITTED_EMPTY); + assertThat(response.getRequest()).isEqualTo(requestWire); + var decoded = EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); + assertThat(decoded.request()).isEqualTo(request); + assertThat(decoded.receipt().canonicalBytes()).isEqualTo(receiptBytes); + assertThat(decoded.receipt().authorizationBindingBytes()).isEqualTo(bindingBytes); + assertThat(decoded.receipt().authorizationBindingDigest()) + .isEqualTo(fixture.authorization().digest()); + assertThat(decoded.receipt().selectedSourceBytes()) + .isEqualTo(fixture.inputs().sourceContent().canonicalBytes()); + assertThat(decoded.receipt().selectedSourceDigest()) + .isEqualTo(fixture.inputs().sourceContent().digest()); + assertThat(decoded.receipt().selectedSourceRevisionBindingDigest()) + .isEqualTo(fixture.inputs().ownerSourceInventoryDeclaration().sourceBinding().digest()); + byte[] originalWorldRequest = + SelectedOwnerWorldInventoryReadGrpcCodec.toRequest( + fixture.inputs().worldInventoryReadEvidence().request()) + .toByteArray(); + assertThat(decoded.receipt().worldReadRequestBytes()).isEqualTo(originalWorldRequest); + assertThat(decoded.receipt().worldReadRequestDigest()) + .isEqualTo(DraftAuthorizationFenceBinding.digest(originalWorldRequest)); + assertThat(decoded.receipt().worldClosureBytes()) + .isEqualTo(fixture.inputs().worldInventoryReadEvidence().inventory().canonicalBytes()); + assertThat(decoded.receipt().worldClosureDigest()) + .isEqualTo(fixture.inputs().worldInventoryReadEvidence().inventory().digest()); + assertThat(decoded.receipt().familyStates()).hasSize(23); + assertThat(EntityEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes).canonicalBytes()) + .isEqualTo(receiptBytes); + } + + @Test + void rejectsNamespaceReaderPurposeOwnerAndAuthorizationDrift() { + var binding = fixture.authorization(); + assertThatThrownBy( + () -> + new EntitySelectedSourceIntakeTerminalReadEvidence.Request( + 1, "other", UUID.randomUUID(), binding)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new EntitySelectedSourceIntakeTerminalReadEvidence.Request( + 1, "test", UUID.randomUUID(), fixture.wrongOwnerAuthorization())) + .isInstanceOf(IllegalArgumentException.class); + + var request = EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request()); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder().setTerminalReadPurpose("ENTITY_INTAKE_RETENTION").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder() + .setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + byte[] changedBinding = request.getOriginalIntakeAuthorizationBinding().toByteArray(); + changedBinding[4] ^= 1; + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(changedBinding)) + .setIntakeAuthorizationDigest( + DraftAuthorizationFenceBinding.digest(changedBinding)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedReceiptDigestEchoUnknownFieldsAndTrailingBytes() { + var request = request(); + var response = + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence(request, fixture.receipt())); + + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setResult( + EntitySelectedSourceIntakeTerminalResult + .ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder().setReceiptDigest("sha256:" + "0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setReadRequestId("12121212-1212-4212-8212-121212121212")) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + var requestUnknown = + ReadSelectedSourceIntakeTerminalRequest.newBuilder() + .mergeFrom(EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request)) + .setUnknownFields(unknownFields()) + .build(); + assertThatThrownBy( + () -> EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(requestUnknown)) + .isInstanceOf(IllegalArgumentException.class); + var responseUnknown = response.toBuilder().setUnknownFields(unknownFields()).build(); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, responseUnknown)) + .isInstanceOf(IllegalArgumentException.class); + + byte[] trailing = + java.util.Arrays.copyOf( + response.getCommittedEmptyReceipt().toByteArray(), + response.getCommittedEmptyReceipt().size() + 1); + trailing[trailing.length - 1] = 0x55; + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCommittedEmptyReceipt(ByteString.copyFrom(trailing)) + .setReceiptDigest(DraftAuthorizationFenceBinding.digest(trailing)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + byte[] changedReceipt = response.getCommittedEmptyReceipt().toByteArray(); + changedReceipt[changedReceipt.length - 1] ^= 1; + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCommittedEmptyReceipt(ByteString.copyFrom(changedReceipt)) + .setReceiptDigest(DraftAuthorizationFenceBinding.digest(changedReceipt)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsOverBudgetRequestAndReceipt() { + var request = request(); + byte[] oversizedBinding = + new byte + [net.firedevops.firemud.common.account.sourceintake + .SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + 1]; + var oversizedRequest = + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(oversizedBinding)) + .build(); + assertThatThrownBy( + () -> EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(oversizedRequest)) + .isInstanceOf(IllegalArgumentException.class); + + byte[] oversizedReceipt = new byte[EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES + 1]; + var oversizedResponse = + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence(request, fixture.receipt())) + .toBuilder() + .setCommittedEmptyReceipt(ByteString.copyFrom(oversizedReceipt)) + .build(); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static EntitySelectedSourceIntakeTerminalReadEvidence.Request request() { + return EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + "test", fixture.authorization()); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/common-security/build.gradle.kts b/services/common-security/build.gradle.kts index 41173f7b58..7a2c2ad7c1 100644 --- a/services/common-security/build.gradle.kts +++ b/services/common-security/build.gradle.kts @@ -18,4 +18,6 @@ dependencies { runtimeOnly(libs.jjwt.jackson) testImplementation(libs.spring.boot.starter.test) + testImplementation(testFixtures(project(":common-test-support"))) + testImplementation("io.grpc:grpc-netty-shaded:${libs.versions.grpc.get()}") } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java new file mode 100644 index 0000000000..e28665fa8e --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java @@ -0,0 +1,181 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec; +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.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for Entity's unregistered selected-source command. */ +public final class GrpcEntitySelectedSourceIntakeCommandClient + extends AbstractReloadingBlockingGrpcClient< + EntitySelectedSourceIntakeCommandServiceGrpc + .EntitySelectedSourceIntakeCommandServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcEntitySelectedSourceIntakeCommandClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcEntitySelectedSourceIntakeCommandClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Entity selected-source command client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Entity selected-source command stub unavailable"); + } + initialized = true; + } + + /** Returns only the exact immutable Entity receipt echoed for this complete original request. */ + public EntitySelectedSourceIntakeCommandEvidence retain( + EntitySelectedSourceIntakeCommandEvidence.Request request) { + requireWorkloadOnlyContext(); + Objects.requireNonNull(request, "selected-source command request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Entity selected-source command must use the configured workload namespace"); + } + var wireRequest = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request); + var current = requireStub(); + try { + var response = + current + .withMaxOutboundMessageSize( + EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .retainSelectedEntitySource(wireRequest); + return EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(request, response); + } catch (StatusRuntimeException denied) { + throw Status.fromCode(denied.getStatus().getCode()).asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException("Entity returned invalid selected-source receipt evidence"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getEntityManagementService(); + } + + @Override + protected String defaultTarget() { + return "entity-management-service:6565"; + } + + @Override + protected EntitySelectedSourceIntakeCommandServiceGrpc + .EntitySelectedSourceIntakeCommandServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = entityServerPeerUri(workloadNamespace); + return EntitySelectedSourceIntakeCommandServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + EntitySelectedSourceIntakeCommandGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withMaxOutboundMessageSize( + EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private EntitySelectedSourceIntakeCommandServiceGrpc + .EntitySelectedSourceIntakeCommandServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Entity selected-source command client is not initialized and available"); + } + return currentStub; + } + + private static void requireWorkloadOnlyContext() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Entity selected-source command requires no ambient SQL or synchronization"); + } + if (SessionContext.hasAuthenticatedCallerContext() + || AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get() != null) { + throw new IllegalStateException( + "Entity selected-source command requires workload-only context"); + } + } + + private static String entityServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service"; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Entity selected-source command requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Entity selected-source command requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Invalid Entity selected-source command " + label + " path"); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Entity selected-source command " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java new file mode 100644 index 0000000000..f36049a23a --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClient.java @@ -0,0 +1,180 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadGrpcCodec; +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.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for Entity's exact original selected-source terminal read. */ +public final class GrpcEntitySelectedSourceIntakeTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceBlockingStub> + implements EntitySelectedSourceIntakeTerminalReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcEntitySelectedSourceIntakeTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcEntitySelectedSourceIntakeTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Entity terminal-read client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Entity terminal-read stub unavailable"); + } + initialized = true; + } + + /** Returns only an exact original COMMITTED_EMPTY receipt, outside owner SQL. */ + @Override + public EntitySelectedSourceIntakeTerminalReadEvidence read( + EntitySelectedSourceIntakeTerminalReadEvidence.Request request) { + requireWorkloadOnlyContext(); + Objects.requireNonNull(request, "terminal-read request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Entity terminal read must use the configured workload namespace"); + } + var wireRequest = EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request); + var current = requireStub(); + try { + var response = + current + .withMaxOutboundMessageSize( + EntitySelectedSourceIntakeTerminalReadGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedSourceIntakeTerminal(wireRequest); + return EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); + } catch (StatusRuntimeException denied) { + throw Status.fromCode(denied.getStatus().getCode()).asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException("Entity returned invalid terminal evidence", malformed); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getEntityManagementService(); + } + + @Override + protected String defaultTarget() { + return "entity-management-service:6565"; + } + + @Override + protected EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = entityServerPeerUri(workloadNamespace); + return EntitySelectedSourceIntakeTerminalReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(EntitySelectedSourceIntakeTerminalReadGrpcCodec.MAX_WIRE_BYTES) + .withMaxOutboundMessageSize( + EntitySelectedSourceIntakeTerminalReadGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Entity terminal-read client is not initialized and available"); + } + return currentStub; + } + + private static void requireWorkloadOnlyContext() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Entity terminal read requires no ambient SQL or synchronization"); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException("Entity terminal read requires workload-only context"); + } + } + + private static String entityServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service"; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Entity terminal read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Entity terminal read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Entity terminal read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Entity terminal read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java new file mode 100644 index 0000000000..ed1326ed2d --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java @@ -0,0 +1,507 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Deadline; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Positive command mTLS proof; synthetic fixture is not Entity producer or physical census proof. + */ +class GrpcEntitySelectedSourceIntakeCommandClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final String WRONG_ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-other"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "synthetic-test-store-password"; + + @TempDir static Path tempDirectory; + private static Fixture fixture; + private static TestPki pki; + private Server server; + private GrpcEntitySelectedSourceIntakeCommandClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + private AtomicReference deadline; + + @BeforeAll + static void createSyntheticInputsAndTrustedCertificates() throws Exception { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransportAndClearAmbientContext() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void loopbackMtlsReturnsExactReceiptAndPinsEntityServerWithBoundedDeadline() throws Exception { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var request = + EntitySelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, fixture.authorization(), freeze); + byte[] receiptBytes = fixture.receipt().canonicalBytes(); + + startServer(pki.entityServer()); + client = newClient(server, pki.gameDesignClient()); + client.init(); + var actual = client.retain(request); + assertThat(actual.request()).isEqualTo(request); + assertThat(actual.receipt().canonicalBytes()).isEqualTo(receiptBytes); + assertThat(actual.receipt().authorizationBindingBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + assertThat(deadline.get()).isNotNull(); + assertThat(deadline.get().timeRemaining(TimeUnit.SECONDS)).isBetween(1L, 5L); + + stopCurrentTransport(); + startServer(pki.wrongServer()); + client = newClient(server, pki.gameDesignClient()); + client.init(); + assertThatThrownBy(() -> client.retain(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + + @Test + void namespaceSqlSynchronizationEndUserAndSelectedOrderAreDeniedBeforeTransport(@TempDir Path dir) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var request = + EntitySelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, + fixture.authorization(), + fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence()); + var wrongNamespaceClient = + new GrpcEntitySelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), placeholderTls(dir), factory, "other"); + try { + assertThatThrownBy(() -> wrongNamespaceClient.retain(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(factory); + } finally { + wrongNamespaceClient.close(); + } + + var client = + new GrpcEntitySelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), placeholderTls(dir), factory, NAMESPACE); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + + SessionContext.setContext("101", List.of(), Map.of()); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + SessionContext.clear(); + + var selectedOrder = + Context.current() + .withValue( + AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, + AccountSelectedPublicationOrderCredentials.Credential.of( + "synthetic-selected-order-credential")); + var previous = selectedOrder.attach(); + try { + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + } finally { + selectedOrder.detach(previous); + } + verifyNoInteractions(factory); + } finally { + client.close(); + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + } + + private void startServer(TestIdentity identity) throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + deadline = new AtomicReference<>(); + var service = + new EntitySelectedSourceIntakeCommandServiceGrpc + .EntitySelectedSourceIntakeCommandServiceImplBase() { + @Override + public void retainSelectedEntitySource( + RetainSelectedEntitySourceRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(GAME_DESIGN_URI); + deadline.set(Context.current().getDeadline()); + var request = EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(wire); + assertThat(request.originalAuthorizationBinding().canonicalBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + assertThat(request.freezeEvidence()) + .isEqualTo( + fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence()); + observer.onNext( + EntitySelectedSourceIntakeCommandGrpcCodec.toResponse( + new EntitySelectedSourceIntakeCommandEvidence(request, fixture.receipt()))); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcEntitySelectedSourceIntakeCommandClient newClient(Server target, TestIdentity local) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService("localhost:" + target.getPort()); + return new GrpcEntitySelectedSourceIntakeCommandClient( + endpoints, pki.clientProperties(tempDirectory, local), new GrpcChannelFactory(), NAMESPACE); + } + + private void stopCurrentTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private static CommonGrpcClientProperties placeholderTls(Path directory) throws IOException { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain( + Files.writeString(directory.resolve("client.crt"), "synthetic cert").toString()); + tls.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "synthetic key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "synthetic CA").toString()); + return tls; + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity entityServer, + TestIdentity wrongServer, + TestIdentity gameDesignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("entity-command-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD Entity command test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("entity-command-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "entity-server", ENTITY_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-entity-server", WRONG_ENTITY_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("entity-command-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java new file mode 100644 index 0000000000..73121c1e5c --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -0,0 +1,481 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Positive large-response loopback mTLS proof and client pre-transport denial tests. */ +class GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final String WRONG_ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-other"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String STORE_PASSWORD = "synthetic-test-store-password"; + + @TempDir static Path tempDirectory; + private static Fixture fixture; + private static TestPki pki; + private Server server; + private GrpcEntitySelectedSourceIntakeTerminalReadClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + + @BeforeAll + static void createSyntheticInputsAndTrustedCertificates() throws Exception { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + pki = TestPki.create(tempDirectory); + } + + @AfterEach + void stopTransportAndClearAmbientContext() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void loopbackMtlsAcceptsCompleteLargeCanonicalReceiptAndPinsEntityPeer() throws Exception { + var request = + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + NAMESPACE, fixture.authorization()); + byte[] receiptBytes = fixture.receipt().canonicalBytes(); + var expectedResponse = + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence(request, fixture.receipt())); + assertThat(expectedResponse.getSerializedSize()).isGreaterThan(4 * 1024 * 1024); + assertThat(expectedResponse.getSerializedSize()) + .isLessThanOrEqualTo(EntitySelectedSourceIntakeTerminalReadGrpcCodec.MAX_WIRE_BYTES); + + startServer(pki.entityServer()); + client = newClient(server, pki.accountClient()); + client.init(); + var actual = client.read(request); + assertThat(actual.request()).isEqualTo(request); + assertThat(actual.receipt().canonicalBytes()).isEqualTo(receiptBytes); + assertThat(actual.receipt().authorizationBindingBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + + stopCurrentTransport(); + startServer(pki.wrongServer()); + client = newClient(server, pki.accountClient()); + client.init(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + + @Test + void namespaceSqlSynchronizationAndEndUserContextAreDeniedBeforeTransport(@TempDir Path dir) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var request = + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + NAMESPACE, fixture.authorization()); + var wrongNamespaceClient = + new GrpcEntitySelectedSourceIntakeTerminalReadClient( + new ServiceEndpointsProperties(), placeholderTls(dir), factory, "other"); + try { + assertThatThrownBy(() -> wrongNamespaceClient.read(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(factory); + } finally { + wrongNamespaceClient.close(); + } + + var client = + new GrpcEntitySelectedSourceIntakeTerminalReadClient( + new ServiceEndpointsProperties(), placeholderTls(dir), factory, NAMESPACE); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + + SessionContext.setContext("101", List.of(), Map.of()); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + verifyNoInteractions(factory); + } finally { + client.close(); + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + } + + private void startServer(TestIdentity identity) throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + var service = + new EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceImplBase() { + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(ACCOUNT_URI); + var request = EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(wire); + assertThat(request.binding().canonicalBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + observer.onNext( + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( + new EntitySelectedSourceIntakeTerminalReadEvidence( + request, fixture.receipt()))); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + EntitySelectedSourceIntakeTerminalReadGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcEntitySelectedSourceIntakeTerminalReadClient newClient( + Server target, TestIdentity local) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService("localhost:" + target.getPort()); + return new GrpcEntitySelectedSourceIntakeTerminalReadClient( + endpoints, pki.clientProperties(tempDirectory, local), new GrpcChannelFactory(), NAMESPACE); + } + + private void stopCurrentTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private static CommonGrpcClientProperties placeholderTls(Path directory) throws IOException { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain( + Files.writeString(directory.resolve("client.crt"), "synthetic cert").toString()); + tls.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "synthetic key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "synthetic CA").toString()); + return tls; + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity entityServer, + TestIdentity wrongServer, + TestIdentity accountClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("entity-terminal-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD Entity terminal-read test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("entity-terminal-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "entity-server", ENTITY_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-entity-server", WRONG_ENTITY_URI, true), + issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("entity-terminal-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java new file mode 100644 index 0000000000..c352de61a5 --- /dev/null +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java @@ -0,0 +1,562 @@ +package net.firedevops.firemud.testsupport.entity; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; + +/** + * Synthetic input values for canonical codec and loopback-mTLS tests only. + * + *

The all-zero Entity family rows are deliberately fabricated constructor inputs. They do not + * prove an Entity provider census, physical persistence, fresh-empty admission, or retained + * production receipt. + */ +public final class EntitySelectedSourceIntakeTerminalReadFixtures { + private static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + private static final String NAMESPACE = "test"; + + private EntitySelectedSourceIntakeTerminalReadFixtures() {} + + public static Fixture create() { + OwnerFixture entity = ownerFixture(Owner.ENTITY_MANAGEMENT); + OwnerFixture automation = ownerFixture(Owner.AUTOMATION_SCRIPTING); + var binding = entity.authorization(); + var inputs = entity.inputs(); + String requestDigest = + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, binding, inputs.worldInventoryReadEvidence().request().freezeEvidence()); + var receipt = + EntityEmptySelectedSourceIntakeReceipt.create( + inputs, + id("88888888-8888-4888-8888-888888888888"), + 9001L, + 9002L, + requestDigest, + syntheticZeroFamilyRows(), + OffsetDateTime.parse("2026-10-01T00:00:00Z")); + return new Fixture(binding, automation.authorization(), inputs, receipt); + } + + private static OwnerFixture ownerFixture(Owner owner) { + DraftCommitBinding selected = selected(); + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + NAMESPACE, + id("55555555-5555-4555-8555-555555555555"), + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + ACTOR, + selected); + var sourceContent = sourceContent(scope, templateSnapshot(selected)); + var authorization = + new SelectedOwnerIntakeAuthorizationBinding(sourceContent, accountSources()); + var freezeEvidence = freezeEvidence(selected); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, authorization, freezeEvidence); + var worldInventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freezeEvidence, publicInventory(freezeEvidence)); + var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, worldInventory); + return new OwnerFixture( + authorization, new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)); + } + + private static TemplateConfigSourceSnapshot templateSnapshot(DraftCommitBinding selected) { + var payloads = new ArrayList(); + for (Owner owner : + List.of(Owner.AUTOMATION_SCRIPTING, Owner.ENTITY_MANAGEMENT).stream().sorted().toList()) { + if (owner == Owner.AUTOMATION_SCRIPTING) { + payloads.add( + TemplateConfigSourceValues.ownerInventoryPayload( + owner, + net.firedevops.firemud.common.automation + .AutomationAuthoredSourceInventoryDeclaration.parse(automationInventory()))); + } else { + payloads.add( + TemplateConfigSourceValues.ownerInventoryPayload( + owner, EntityAuthoredSourceInventoryDeclaration.parse(entityInventory()))); + } + } + DraftCommitBinding authored = authoredBinding(payloads); + var mutations = TemplateConfigSourceValues.mutations(authored); + var declarations = + mutations.stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .sorted(java.util.Comparator.comparing(declaration -> declaration.owner().name())) + .toList(); + return new TemplateConfigSourceSnapshot( + selected, + "1", + authored.commitId(), + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + List.of(), + declarations); + } + + private static DraftCommitBinding authoredBinding(List payloads) { + List revisions = new ArrayList<>(); + for (int index = 0; index < payloads.size(); index++) { + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads.get(index))); + } + return DraftCommitBinding.create( + target(), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + VERSION.toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + SelectedOwnerIntakeSourceReadScope scope, TemplateConfigSourceSnapshot templateSnapshot) { + var out = new java.io.ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + "TEMPLATE_CONFIG".equals(family) + ? templateSnapshot.canonicalBytes() + : sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + if ("GAMEPLAY_RULE".equals(family)) { + return new net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource( + net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "manifestJson", + net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.explicitEmpty() + .canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + } + UUID genesis = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + return switch (family) { + case "COMMAND" -> + new CommandSnapshot(selected, "0", null, "sha256:" + "a".repeat(64), List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> new AssetSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, genesis, List.of()).canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported synthetic source family"); + }; + } + + private static List accountSources() { + return List.of( + new SourceEvidence( + SourceKind.TENANT, + TENANT.toString(), + null, + "1", + null, + null, + syntheticLargeSourceBytes()), + source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership")); + } + + private static byte[] syntheticLargeSourceBytes() { + byte[] bytes = new byte[4 * 1024 * 1024 + 1024]; + java.util.Arrays.fill(bytes, (byte) 'S'); + return bytes; + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected() { + return DraftCommitBinding.create( + target(), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + } + + private static DraftCommitBinding.TargetProof target() { + return new DraftCommitBinding.TargetProof( + TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + DraftCommitBinding selected) { + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + TENANT, + VERSION, + "publication-request", + "9", + "synthetic selected-owner intake fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), + List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "synthetic-publication"))); + var request = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + TENANT, + VERSION, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + request, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 0), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + emptyInboundClosure()); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + new PublicOwnerScope( + request.targetNamespace(), + TENANT, + VERSION, + id("14141414-1414-4414-8414-141414141414"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("17171717-1717-4717-8717-171717171717"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)), + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static InboundSourceClosureDeclaration emptyInboundClosure() { + return new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + } + + private static List + syntheticZeroFamilyRows() { + List families = + List.of( + "ACTOR_BODY_LAYOUT_ASSIGNMENTS", + "ARCHETYPE_ASSIGNMENTS", + "ARCHETYPE_CONSTRAINTS", + "ARCHETYPE_ROOTS", + "BALANCE_CURVE_ATTACHMENTS", + "BALANCE_CURVE_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS", + "BODY_LAYOUT_ROOTS", + "CRAFTING_INGREDIENT_BINDINGS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_RECIPE_ROOTS", + "EQUIPMENT_ATTACHMENT_RULES", + "EQUIPMENT_CAPABILITIES", + "EQUIPMENT_COMPATIBILITY_RULES", + "EQUIPMENT_OCCUPANCY_RULES", + "EQUIPMENT_SLOT_GROUPS", + "EQUIPMENT_SLOT_ROOTS", + "INBOUND_LOOT_BINDINGS", + "ITEM_TEMPLATE_ROOTS", + "LOOT_ITEM_MAPPINGS", + "LOOT_TABLE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "OTHER_ACTOR_TEMPLATE_ROOTS"); + return families.stream() + .map( + family -> + new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( + family, + EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, + v1CensusFamily(family) + ? EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS + : EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind + .EMPTY_ONLY_OWNER_PROVIDER, + 0, + 0, + 0, + 0, + 0)) + .toList(); + } + + private static boolean v1CensusFamily(String family) { + return List.of( + "ITEM_TEMPLATE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "CRAFTING_RECIPE_ROOTS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_INGREDIENT_BINDINGS", + "EQUIPMENT_SLOT_ROOTS", + "EQUIPMENT_SLOT_GROUPS", + "BODY_LAYOUT_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS") + .contains(family); + } + + private static String automationInventory() { + return "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[],\"SCRIPT_PATCH_SOURCES\":[]}}"; + } + + private static String entityInventory() { + return "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"; + } + + private static void frame(java.io.ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(java.io.ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + public record Fixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + SelectedOwnerIntakeAuthorizationBinding wrongOwnerAuthorization, + SelectedOwnerEmptySourceInputs inputs, + EntityEmptySelectedSourceIntakeReceipt receipt) {} + + private record OwnerFixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + SelectedOwnerEmptySourceInputs inputs) {} +} diff --git a/services/entity-management-service/build.gradle.kts b/services/entity-management-service/build.gradle.kts index f83aff8cf7..d0edb47045 100644 --- a/services/entity-management-service/build.gradle.kts +++ b/services/entity-management-service/build.gradle.kts @@ -15,3 +15,17 @@ dependencies { implementation(project(":common-security")) implementation(libs.spring.boot.starter.cache) } + +// Opt-in proof artifact: expose Entity classes without application or migration resources. +val entityClassesProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("classes-proof") + dependsOn(tasks.named("classes")) + from(sourceSets.main.get().output.classesDirs) +} + +val entityClassesProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(entityClassesProofJar) +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java new file mode 100644 index 0000000000..58b04324de --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java @@ -0,0 +1,843 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered Entity persistence boundary for immutable, freshly founded empty catalogues. */ +public final class EntityEmptySelectedSourceIntakeRepository { + private static final String KEY_RESERVATION = "entity_empty_source_numeric_key_reservation"; + private static final String ASSOCIATION = "entity_empty_selected_source_association"; + private static final String FAMILY_STATE = "entity_empty_selected_source_family_state"; + private static final String RECEIPT = "entity_empty_selected_source_receipt"; + private static final Map EMPTY_ONLY_PROVIDER_TABLES = + Map.ofEntries( + Map.entry( + "ACTOR_BODY_LAYOUT_ASSIGNMENTS", "entity_empty_source_actor_body_layout_assignments"), + Map.entry("ARCHETYPE_ASSIGNMENTS", "entity_empty_source_archetype_assignments"), + Map.entry("ARCHETYPE_CONSTRAINTS", "entity_empty_source_archetype_constraints"), + Map.entry("ARCHETYPE_ROOTS", "entity_empty_source_archetype_roots"), + Map.entry("BALANCE_CURVE_ATTACHMENTS", "entity_empty_source_balance_curve_attachments"), + Map.entry("BALANCE_CURVE_ROOTS", "entity_empty_source_balance_curve_roots"), + Map.entry("EQUIPMENT_ATTACHMENT_RULES", "entity_empty_source_equipment_attachment_rules"), + Map.entry("EQUIPMENT_CAPABILITIES", "entity_empty_source_equipment_capabilities"), + Map.entry( + "EQUIPMENT_COMPATIBILITY_RULES", "entity_empty_source_equipment_compatibility_rules"), + Map.entry("EQUIPMENT_OCCUPANCY_RULES", "entity_empty_source_equipment_occupancy_rules"), + Map.entry("INBOUND_LOOT_BINDINGS", "entity_empty_source_inbound_loot_bindings"), + Map.entry("LOOT_ITEM_MAPPINGS", "entity_empty_source_loot_item_mappings"), + Map.entry("LOOT_TABLE_ROOTS", "entity_empty_source_loot_table_roots"), + Map.entry( + "OTHER_ACTOR_TEMPLATE_ROOTS", "entity_empty_source_other_actor_template_roots")); + private static final List EMPTY_ONLY_PROVIDER_LOCKS = + List.of( + "entity_empty_source_other_actor_template_roots", + "entity_empty_source_equipment_capabilities", + "entity_empty_source_equipment_attachment_rules", + "entity_empty_source_equipment_compatibility_rules", + "entity_empty_source_equipment_occupancy_rules", + "entity_empty_source_actor_body_layout_assignments", + "entity_empty_source_loot_table_roots", + "entity_empty_source_loot_item_mappings", + "entity_empty_source_inbound_loot_bindings", + "entity_empty_source_balance_curve_roots", + "entity_empty_source_balance_curve_attachments", + "entity_empty_source_archetype_roots", + "entity_empty_source_archetype_constraints", + "entity_empty_source_archetype_assignments"); + + private static final String READ_RECEIPT = + "SELECT a.target_namespace, a.genesis_id, a.operation_id, a.fence_id, " + + "a.intake_request_id, a.canonical_tenant_id, a.canonical_version_id, " + + "a.local_tenant_key, a.local_version_key, a.request_digest, a.schema_digest, " + + "a.authorization_binding_digest, a.selected_source_digest, a.world_read_request_id, " + + "a.world_read_request_digest, a.world_closure_digest, a.receipt_digest, a.associated_at, " + + "r.request_digest, r.schema_digest, r.receipt_digest, r.receipt_bytes, r.retained_at " + + "FROM " + + ASSOCIATION + + " a LEFT JOIN " + + RECEIPT + + " r ON r.target_namespace = a.target_namespace " + + "AND r.intake_request_id = a.intake_request_id " + + "WHERE a.target_namespace = ? AND a.intake_request_id = ?"; + + private static final String SOURCE_TABLE_LOCKS = + "LOCK TABLE actor_active_conditions, actor_resource_states, body_layout_slot_definitions, " + + "character_equipment, character_friend, characters, container_instances, " + + "crafting_ingredients, crafting_recipes, entity_mutation_effects, " + + "equipment_slot_definitions, inventory, item_instances, item_stacks, " + + "item_transfer_audits, item_visible_ref_counters, items, npcs, room_ground_inventory IN SHARE MODE"; + + private final DSLContext dsl; + + public EntityEmptySelectedSourceIntakeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Reads only a committed exact receipt; absence is not interpreted as abort or source absence. + */ + public Optional read( + String targetNamespace, UUID intakeRequestId) { + requireNoAmbientOwnerSql("Entity source receipt read"); + requireReadKey(targetNamespace, intakeRequestId); + return readValidated(dsl, targetNamespace, intakeRequestId); + } + + /** + * Commits a fresh empty catalogue and reads it back independently. A provider missing from the + * current Entity schema blocks founding, even if its creator declaration says the family is + * empty. + */ + public EntityEmptySelectedSourceIntakeReceipt retainFresh( + SelectedOwnerEmptySourceInputs inputs, String requestDigest) { + Objects.requireNonNull(inputs, "validated selected empty-source inputs are required"); + SelectedOwnerIntakeAuthorizationBinding binding = inputs.authorizationBinding(); + String expectedDigest = + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + binding.targetNamespace(), + binding, + inputs.worldInventoryReadEvidence().request().freezeEvidence()); + if (!expectedDigest.equals(requestDigest)) { + throw new IllegalArgumentException("Entity source intake request digest differs"); + } + requireExactEntityBinding(binding); + requireNoAmbientOwnerSql("Entity source catalogue transaction"); + + UUID genesisId = UUID.randomUUID(); + EntityEmptySelectedSourceIntakeReceipt committed = + dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + lockOwnerRecords(tx); + lockSourceAndInboundTables(tx); + + Optional previous = + readValidated(tx, binding.targetNamespace(), binding.intakeRequestId()); + if (previous.isPresent()) { + EntityEmptySelectedSourceIntakeReceipt receipt = previous.orElseThrow(); + receipt.requireSameInputs(inputs); + return receipt; + } + requireNoPriorScopeOrOperation(tx, binding); + + long maximumOccupiedKey = maximumOccupiedSourceKey(tx); + long localTenantKey = Math.addExact(maximumOccupiedKey, 1L); + long localVersionKey = Math.addExact(maximumOccupiedKey, 2L); + List familyStates = + censusEveryDeclaredFamily(tx, inputs, localTenantKey, localVersionKey); + + reserveCanonicalKey(tx, "TENANT", localTenantKey); + reserveCanonicalKey(tx, "VERSION", localVersionKey); + OffsetDateTime retainedAt = + requiredScalar(tx, "SELECT CURRENT_TIMESTAMP", OffsetDateTime.class) + .withOffsetSameInstant(ZoneOffset.UTC); + EntityEmptySelectedSourceIntakeReceipt receipt = + EntityEmptySelectedSourceIntakeReceipt.create( + inputs, + genesisId, + localTenantKey, + localVersionKey, + requestDigest, + familyStates, + retainedAt); + insertAssociation(tx, receipt); + insertEmptyOnlyProviderStates(tx, receipt); + insertFamilyStates(tx, receipt); + insertReceipt(tx, receipt); + return receipt; + }); + + EntityEmptySelectedSourceIntakeReceipt readBack = + read(committed.targetNamespace(), committed.intakeRequestId()) + .orElseThrow( + () -> + new IllegalStateException( + "Committed Entity source catalogue receipt is unavailable")); + if (!Arrays.equals(committed.canonicalBytes(), readBack.canonicalBytes()) + || !committed.receiptDigest().equals(readBack.receiptDigest()) + || !committed.requestDigest().equals(readBack.requestDigest()) + || !committed.genesisId().equals(readBack.genesisId())) { + throw new IllegalStateException("Committed Entity source receipt readback differs"); + } + return readBack; + } + + private static void lockOwnerRecords(DSLContext tx) { + tx.execute( + "LOCK TABLE " + + KEY_RESERVATION + + ", " + + ASSOCIATION + + ", " + + FAMILY_STATE + + ", " + + RECEIPT + + ", " + + String.join(", ", EMPTY_ONLY_PROVIDER_LOCKS) + + " IN SHARE ROW EXCLUSIVE MODE"); + } + + private static void lockSourceAndInboundTables(DSLContext tx) { + // Locks cover every source row, Entity item FK, actor/holder path, and logical slot/layout + // reference read by the conservative census. SHARE is held until the catalogue commit. + tx.execute(SOURCE_TABLE_LOCKS); + } + + private static void requireNoPriorScopeOrOperation( + DSLContext tx, SelectedOwnerIntakeAuthorizationBinding binding) { + Record prior = + tx.fetchOne( + "SELECT intake_request_id FROM " + + ASSOCIATION + + " WHERE target_namespace = ? AND (" + + "(canonical_tenant_id = ? AND canonical_version_id = ?) OR operation_id = ?) ", + binding.targetNamespace(), + binding.tenantId(), + binding.versionId(), + binding.operationId()); + if (prior != null) { + throw new IntakeConflictException( + "Entity selected scope or owner operation is already associated"); + } + } + + private static List + censusEveryDeclaredFamily( + DSLContext tx, + SelectedOwnerEmptySourceInputs inputs, + long localTenantKey, + long localVersionKey) { + List declaredFamilies = + declaredFamilies( + inputs.ownerSourceInventoryDeclaration().entityInventory().canonicalJson()); + var result = new ArrayList(23); + for (String family : declaredFamilies) { + requireReadableProvider(family); + Census counts = + EMPTY_ONLY_PROVIDER_TABLES.containsKey(family) + ? Census.emptyOnlyProviderState() + : switch (family) { + case "ITEM_TEMPLATE_ROOTS" -> censusItems(tx, localTenantKey, localVersionKey); + case "NPC_TEMPLATE_ROOTS" -> censusNpcs(tx, localTenantKey, localVersionKey); + case "CRAFTING_RECIPE_ROOTS" -> + censusRecipes(tx, localTenantKey, localVersionKey, false); + case "CRAFTING_RECIPE_RESULT_BINDINGS" -> + censusRecipes(tx, localTenantKey, localVersionKey, true); + case "CRAFTING_INGREDIENT_BINDINGS" -> + censusIngredients(tx, localTenantKey, localVersionKey); + case "EQUIPMENT_SLOT_ROOTS" -> + censusEquipmentSlots(tx, localTenantKey, localVersionKey, false); + case "EQUIPMENT_SLOT_GROUPS" -> + censusEquipmentSlots(tx, localTenantKey, localVersionKey, true); + case "BODY_LAYOUT_ROOTS" -> + censusBodyLayouts(tx, localTenantKey, localVersionKey, true); + case "BODY_LAYOUT_MEMBERSHIPS" -> + censusBodyLayouts(tx, localTenantKey, localVersionKey, false); + default -> + throw new IllegalStateException( + "No readable persisted Entity source provider for family " + family); + }; + if (!counts.isZero()) { + throw new IntakeConflictException( + "Entity source family or inbound reference census is not freshly empty: " + family); + } + result.add( + new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( + family, + EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, + EMPTY_ONLY_PROVIDER_TABLES.containsKey(family) + ? EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind + .EMPTY_ONLY_OWNER_PROVIDER + : EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS, + counts.rows(), + counts.unqualifiedRows(), + counts.retainedRows(), + counts.selectedScopeRows(), + counts.references())); + } + if (result.size() != 23) { + throw new IllegalStateException("Entity source census did not read all 23 declared families"); + } + return List.copyOf(result); + } + + static void requireReadableProvider(String family) { + if (!EMPTY_ONLY_PROVIDER_TABLES.containsKey(family) + && !List.of( + "ITEM_TEMPLATE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "CRAFTING_RECIPE_ROOTS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_INGREDIENT_BINDINGS", + "EQUIPMENT_SLOT_ROOTS", + "EQUIPMENT_SLOT_GROUPS", + "BODY_LAYOUT_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS") + .contains(family)) { + throw new IllegalStateException( + "No readable persisted Entity source provider for family " + family); + } + } + + private static Census censusItems(DSLContext tx, long tenantKey, long versionKey) { + return new Census( + count(tx, "SELECT COUNT(*) FROM items"), + count( + tx, + "SELECT COUNT(*) FROM items i WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = i.tenant_id AND a.local_version_key = i.version_id)"), + count( + tx, + "SELECT COUNT(*) FROM items i WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = i.tenant_id AND a.local_version_key = i.version_id)"), + count( + tx, + "SELECT COUNT(*) FROM items WHERE tenant_id = ? OR version_id = ?", + tenantKey, + versionKey), + countItemReferenceEdges(tx)); + } + + private static Census censusNpcs(DSLContext tx, long tenantKey, long versionKey) { + return new Census( + count(tx, "SELECT COUNT(*) FROM npcs"), + count( + tx, + "SELECT COUNT(*) FROM npcs n WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = n.tenant_id AND a.local_version_key = n.version_id)"), + count( + tx, + "SELECT COUNT(*) FROM npcs n WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = n.tenant_id AND a.local_version_key = n.version_id)"), + count( + tx, + "SELECT COUNT(*) FROM npcs WHERE tenant_id = ? OR version_id = ?", + tenantKey, + versionKey), + 0L); + } + + private static Census censusRecipes( + DSLContext tx, long tenantKey, long versionKey, boolean resultBinding) { + String nonnullResult = resultBinding ? " WHERE result_item_id IS NOT NULL" : ""; + String aliasFilter = resultBinding ? " AND r.result_item_id IS NOT NULL" : ""; + return new Census( + count(tx, "SELECT COUNT(*) FROM crafting_recipes" + nonnullResult), + count( + tx, + "SELECT COUNT(*) FROM crafting_recipes r WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)" + + aliasFilter), + count( + tx, + "SELECT COUNT(*) FROM crafting_recipes r WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)" + + aliasFilter), + count( + tx, + "SELECT COUNT(*) FROM crafting_recipes r WHERE (r.tenant_id = ? OR r.version_id = ?)" + + aliasFilter, + tenantKey, + versionKey), + resultBinding + ? count(tx, "SELECT COUNT(*) FROM crafting_recipes WHERE result_item_id IS NOT NULL") + : count(tx, "SELECT COUNT(*) FROM crafting_ingredients")); + } + + private static Census censusIngredients(DSLContext tx, long tenantKey, long versionKey) { + String recipeAssociation = + "SELECT COUNT(*) FROM crafting_ingredients i JOIN crafting_recipes r ON r.id = i.recipe_id "; + return new Census( + count(tx, "SELECT COUNT(*) FROM crafting_ingredients"), + count( + tx, + recipeAssociation + + "WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)"), + count( + tx, + recipeAssociation + + "WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)"), + count( + tx, + recipeAssociation + "WHERE r.tenant_id = ? OR r.version_id = ?", + tenantKey, + versionKey), + count(tx, "SELECT COUNT(*) FROM crafting_ingredients")); + } + + private static Census censusEquipmentSlots( + DSLContext tx, long tenantKey, long versionKey, boolean groups) { + String identity = + groups + ? "SELECT DISTINCT tenant_id, version_id, slot_group_key AS source_key " + + "FROM equipment_slot_definitions WHERE slot_group_key IS NOT NULL" + : "SELECT tenant_id, version_id, slot_key AS source_key FROM equipment_slot_definitions"; + String itemReferences = + "SELECT COUNT(*) FROM (" + + "SELECT equipment_slot AS source_key FROM items WHERE equipment_slot IS NOT NULL " + + "UNION ALL SELECT slot FROM character_equipment WHERE slot IS NOT NULL " + + "UNION ALL SELECT equipment_slot FROM item_instances WHERE equipment_slot IS NOT NULL " + + "UNION ALL SELECT equipment_slot FROM item_stacks WHERE equipment_slot IS NOT NULL " + + "UNION ALL SELECT equipment_slot FROM container_instances WHERE equipment_slot IS NOT NULL" + + ") slot_refs"; + String groupReferences = + "SELECT COUNT(*) FROM items WHERE equipment_slot_group_key IS NOT NULL"; + String total = "SELECT COUNT(*) FROM (" + identity + ") entity_family"; + String unqualified = + "SELECT COUNT(*) FROM (SELECT f.* FROM (" + + identity + + ") f WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q"; + String retained = + "SELECT COUNT(*) FROM (SELECT f.* FROM (" + + identity + + ") f WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q"; + String selected = + "SELECT COUNT(*) FROM (" + identity + ") f WHERE f.tenant_id = ? OR f.version_id = ?"; + return new Census( + count(tx, total), + count(tx, unqualified), + count(tx, retained), + count(tx, selected, tenantKey, versionKey), + groups ? count(tx, groupReferences) : count(tx, itemReferences)); + } + + private static Census censusBodyLayouts( + DSLContext tx, long tenantKey, long versionKey, boolean roots) { + String identity = + roots + ? "SELECT DISTINCT tenant_id, version_id, body_layout_key AS source_key " + + "FROM body_layout_slot_definitions" + : "SELECT tenant_id, version_id, body_layout_key, slot_key " + + "FROM body_layout_slot_definitions"; + String total = "SELECT COUNT(*) FROM (" + identity + ") entity_family"; + String unqualified = + "SELECT COUNT(*) FROM (SELECT f.* FROM (" + + identity + + ") f WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q"; + String retained = + "SELECT COUNT(*) FROM (SELECT f.* FROM (" + + identity + + ") f WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q"; + String selected = + "SELECT COUNT(*) FROM (" + identity + ") f WHERE f.tenant_id = ? OR f.version_id = ?"; + return new Census( + count(tx, total), + count(tx, unqualified), + count(tx, retained), + count(tx, selected, tenantKey, versionKey), + roots + ? count(tx, "SELECT COUNT(*) FROM characters WHERE body_layout_key IS NOT NULL") + : count( + tx, + "SELECT COUNT(*) FROM characters c JOIN character_equipment e " + + "ON e.character_id = c.id WHERE c.body_layout_key IS NOT NULL")); + } + + private static long countItemReferenceEdges(DSLContext tx) { + return count( + tx, + "SELECT COUNT(*) FROM (" + + "SELECT item_id FROM inventory " + + "UNION ALL SELECT result_item_id FROM crafting_recipes " + + "UNION ALL SELECT item_id FROM crafting_ingredients " + + "UNION ALL SELECT item_id FROM room_ground_inventory " + + "UNION ALL SELECT item_id FROM character_equipment " + + "UNION ALL SELECT item_id FROM container_instances " + + "UNION ALL SELECT item_id FROM item_instances " + + "UNION ALL SELECT item_id FROM item_stacks " + + "UNION ALL SELECT item_id FROM item_transfer_audits " + + "UNION ALL SELECT item_instance_id FROM item_transfer_audits WHERE item_instance_id IS NOT NULL" + + ") item_refs"); + } + + private static long maximumOccupiedSourceKey(DSLContext tx) { + return requiredScalar( + tx, + "SELECT COALESCE(MAX(key_value), 0) FROM (" + + "SELECT numeric_key AS key_value FROM " + + KEY_RESERVATION + + " UNION ALL SELECT tenant_id FROM items WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM npcs WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM crafting_recipes WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM equipment_slot_definitions WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM body_layout_slot_definitions WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM room_ground_inventory WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM container_instances WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM item_instances WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM item_stacks WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM characters WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM character_friend WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM item_visible_ref_counters WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM entity_mutation_effects WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM item_transfer_audits WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM actor_resource_states WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM actor_active_conditions WHERE tenant_id > 0" + + " UNION ALL SELECT version_id FROM items WHERE version_id > 0" + + " UNION ALL SELECT version_id FROM npcs WHERE version_id > 0" + + " UNION ALL SELECT version_id FROM crafting_recipes WHERE version_id > 0" + + " UNION ALL SELECT version_id FROM equipment_slot_definitions WHERE version_id > 0" + + " UNION ALL SELECT version_id FROM body_layout_slot_definitions WHERE version_id > 0" + + ") occupied_entity_source_keys", + Long.class); + } + + private static void reserveCanonicalKey(DSLContext tx, String kind, long key) { + int inserted = + tx.execute( + "INSERT INTO " + + KEY_RESERVATION + + " (key_kind, numeric_key, claim_kind) VALUES (?, ?, 'CANONICAL_EMPTY_SOURCE')", + kind, + key); + if (inserted != 1) { + throw new IllegalStateException("Entity allocated numeric source key was not reserved"); + } + } + + private static void insertAssociation( + DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + int inserted = + tx.execute( + "INSERT INTO " + + ASSOCIATION + + " (target_namespace, genesis_id, operation_id, fence_id, intake_request_id, " + + "canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "source_revision_id, source_revision_order, local_tenant_key, local_version_key, " + + "request_digest, schema_digest, authorization_binding_digest, selected_source_digest, " + + "world_read_request_id, world_read_request_digest, world_closure_digest, receipt_digest, " + + "associated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ))", + receipt.targetNamespace(), + receipt.genesisId(), + receipt.operationId(), + receipt.fenceId(), + receipt.intakeRequestId(), + receipt.canonicalTenantId(), + receipt.canonicalVersionId(), + receipt.selectedCommitId(), + receipt.sourceRevisionId(), + receipt.sourceRevisionOrder(), + receipt.localTenantKey(), + receipt.localVersionKey(), + receipt.requestDigest(), + receipt.schemaDigest(), + receipt.authorizationBindingDigest(), + receipt.selectedSourceDigest(), + receipt.worldReadRequestId(), + receipt.worldReadRequestDigest(), + receipt.worldClosureDigest(), + receipt.receiptDigest(), + receipt.retainedAt()); + if (inserted != 1) + throw new IllegalStateException("Entity source association was not inserted"); + } + + private static void insertFamilyStates( + DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + for (var state : receipt.familyStates()) { + int inserted = + tx.execute( + "INSERT INTO " + + FAMILY_STATE + + " (target_namespace, intake_request_id, family_name, owner_state, evidence_kind, row_count, " + + "unqualified_row_count, retained_row_count, selected_scope_row_count, reference_count) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.targetNamespace(), + receipt.intakeRequestId(), + state.family(), + state.state().name(), + state.evidenceKind().name(), + state.rowCount(), + state.unqualifiedRowCount(), + state.retainedRowCount(), + state.selectedScopeRowCount(), + state.referenceCount()); + if (inserted != 1) { + throw new IllegalStateException("Entity source family state was not retained"); + } + } + } + + private static void insertEmptyOnlyProviderStates( + DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + for (var state : receipt.familyStates()) { + if (state.evidenceKind() + != EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER) { + continue; + } + String table = EMPTY_ONLY_PROVIDER_TABLES.get(state.family()); + if (table == null) { + throw new IllegalStateException("Entity EMPTY-only family has no owner table"); + } + int inserted = + tx.execute( + "INSERT INTO " + + table + + " (target_namespace, intake_request_id, provider_schema_version, owner_state, " + + "row_count, reference_count, authorization_binding_digest, selected_source_digest, " + + "source_revision_binding_digest, world_closure_digest, provider_state_digest, observed_at) " + + "VALUES (?, ?, 1, ?, 0, 0, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ))", + receipt.targetNamespace(), + receipt.intakeRequestId(), + state.state().name(), + receipt.authorizationBindingDigest(), + receipt.selectedSourceDigest(), + receipt.selectedSourceRevisionBindingDigest(), + receipt.worldClosureDigest(), + receipt.providerStateDigest(state.family()), + receipt.retainedAt()); + if (inserted != 1) { + throw new IllegalStateException("Entity EMPTY-only provider state was not retained"); + } + } + } + + private static void insertReceipt(DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + int inserted = + tx.execute( + "INSERT INTO " + + RECEIPT + + " (target_namespace, intake_request_id, request_digest, schema_digest, " + + "receipt_digest, receipt_bytes, retained_at) VALUES (?, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ))", + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.requestDigest(), + receipt.schemaDigest(), + receipt.receiptDigest(), + receipt.canonicalBytes(), + receipt.retainedAt()); + if (inserted != 1) throw new IllegalStateException("Entity source receipt was not inserted"); + } + + private static Optional readValidated( + DSLContext tx, String targetNamespace, UUID intakeRequestId) { + Record row = tx.fetchOne(READ_RECEIPT, targetNamespace, intakeRequestId); + if (row == null) return Optional.empty(); + byte[] receiptBytes = row.get(21, byte[].class); + if (receiptBytes == null || row.get(22, OffsetDateTime.class) == null) { + throw new IllegalStateException("Entity source association has no committed receipt"); + } + EntityEmptySelectedSourceIntakeReceipt receipt = + EntityEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes); + if (!Objects.equals(row.get(0, String.class), receipt.targetNamespace()) + || !Objects.equals(row.get(1, UUID.class), receipt.genesisId()) + || !Objects.equals(row.get(2, UUID.class), receipt.operationId()) + || !Objects.equals(row.get(3, UUID.class), receipt.fenceId()) + || !Objects.equals(row.get(4, UUID.class), receipt.intakeRequestId()) + || !Objects.equals(row.get(5, UUID.class), receipt.canonicalTenantId()) + || !Objects.equals(row.get(6, UUID.class), receipt.canonicalVersionId()) + || !Objects.equals(row.get(7, Long.class), receipt.localTenantKey()) + || !Objects.equals(row.get(8, Long.class), receipt.localVersionKey()) + || !Objects.equals(row.get(9, String.class), receipt.requestDigest()) + || !Objects.equals(row.get(10, String.class), receipt.schemaDigest()) + || !Objects.equals(row.get(11, String.class), receipt.authorizationBindingDigest()) + || !Objects.equals(row.get(12, String.class), receipt.selectedSourceDigest()) + || !Objects.equals(row.get(13, UUID.class), receipt.worldReadRequestId()) + || !Objects.equals(row.get(14, String.class), receipt.worldReadRequestDigest()) + || !Objects.equals(row.get(15, String.class), receipt.worldClosureDigest()) + || !Objects.equals(row.get(16, String.class), receipt.receiptDigest()) + || !Objects.equals(row.get(17, OffsetDateTime.class), receipt.retainedAt()) + || !Objects.equals(row.get(18, String.class), receipt.requestDigest()) + || !Objects.equals(row.get(19, String.class), receipt.schemaDigest()) + || !Objects.equals(row.get(20, String.class), receipt.receiptDigest()) + || !Objects.equals(row.get(22, OffsetDateTime.class), receipt.retainedAt())) { + throw new IllegalStateException("Entity association differs from its immutable receipt"); + } + requirePersistedEmptyOnlyProviderStates(tx, receipt); + requirePersistedFamilyStates(tx, receipt); + return Optional.of(receipt); + } + + private static void requirePersistedEmptyOnlyProviderStates( + DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + for (var state : receipt.familyStates()) { + if (state.evidenceKind() + != EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER) { + continue; + } + String table = EMPTY_ONLY_PROVIDER_TABLES.get(state.family()); + if (table == null) { + throw new IllegalStateException("Entity EMPTY-only family has no owner table"); + } + Record row = + tx.fetchOne( + "SELECT provider_schema_version, owner_state, row_count, reference_count, " + + "authorization_binding_digest, selected_source_digest, " + + "source_revision_binding_digest, world_closure_digest, provider_state_digest, observed_at " + + "FROM " + + table + + " WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()); + if (row == null + || !Objects.equals(row.get(0, Short.class), (short) 1) + || !Objects.equals(row.get(1, String.class), state.state().name()) + || !Objects.equals(row.get(2, Long.class), state.rowCount()) + || !Objects.equals(row.get(3, Long.class), state.referenceCount()) + || !Objects.equals(row.get(4, String.class), receipt.authorizationBindingDigest()) + || !Objects.equals(row.get(5, String.class), receipt.selectedSourceDigest()) + || !Objects.equals( + row.get(6, String.class), receipt.selectedSourceRevisionBindingDigest()) + || !Objects.equals(row.get(7, String.class), receipt.worldClosureDigest()) + || !Objects.equals(row.get(8, String.class), receipt.providerStateDigest(state.family())) + || !Objects.equals(row.get(9, OffsetDateTime.class), receipt.retainedAt())) { + throw new IllegalStateException( + "Entity EMPTY-only provider readback is missing or differs for " + state.family()); + } + } + } + + private static void requirePersistedFamilyStates( + DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + var rows = + tx.fetch( + "SELECT family_name, owner_state, evidence_kind, row_count, unqualified_row_count, retained_row_count, " + + "selected_scope_row_count, reference_count FROM " + + FAMILY_STATE + + " WHERE target_namespace = ? AND intake_request_id = ? ORDER BY family_name", + receipt.targetNamespace(), + receipt.intakeRequestId()); + if (rows.size() != receipt.familyStates().size()) { + throw new IllegalStateException("Entity retained family-state vector is incomplete"); + } + var expected = + receipt.familyStates().stream() + .sorted( + java.util.Comparator.comparing( + EntityEmptySelectedSourceIntakeReceipt.FamilyCensus::family)) + .toList(); + for (int index = 0; index < expected.size(); index++) { + Record row = rows.get(index); + var state = expected.get(index); + if (!Objects.equals(row.get(0, String.class), state.family()) + || !Objects.equals(row.get(1, String.class), state.state().name()) + || !Objects.equals(row.get(2, String.class), state.evidenceKind().name()) + || !Objects.equals(row.get(3, Long.class), state.rowCount()) + || !Objects.equals(row.get(4, Long.class), state.unqualifiedRowCount()) + || !Objects.equals(row.get(5, Long.class), state.retainedRowCount()) + || !Objects.equals(row.get(6, Long.class), state.selectedScopeRowCount()) + || !Objects.equals(row.get(7, Long.class), state.referenceCount())) { + throw new IllegalStateException("Entity retained family state differs from its receipt"); + } + } + } + + private static List declaredFamilies(String canonicalDeclaration) { + return EntityEmptySelectedSourceIntakeReceipt.familyNames(canonicalDeclaration); + } + + private static void requireExactEntityBinding(SelectedOwnerIntakeAuthorizationBinding binding) { + if (binding.owner() != Owner.ENTITY_MANAGEMENT + || !"account-entity-intake-authorization/v1".equals(binding.schema()) + || !"ENTITY_INTAKE_RETENTION".equals(binding.purpose()) + || !binding + .intendedReader() + .equals( + "spiffe://firemud/ns/" + + binding.targetNamespace() + + "/sa/entity-management-service")) { + throw new IllegalArgumentException("Exact original Entity Account authorization is required"); + } + } + + private static long count(DSLContext tx, String sql, Object... arguments) { + return requiredScalar(tx, sql, Long.class, arguments); + } + + private static T requiredScalar( + DSLContext tx, String sql, Class type, Object... arguments) { + Record result = tx.fetchOne(sql, arguments); + if (result == null || result.get(0, type) == null) { + throw new IllegalStateException("Entity source census query returned no scalar value"); + } + return result.get(0, type); + } + + private static void requireReadKey(String targetNamespace, UUID intakeRequestId) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) || intakeRequestId == null) { + throw new IllegalArgumentException( + "Canonical Entity source receipt read identity is required"); + } + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + } + + private static void requireNoAmbientOwnerSql(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + label + " requires an independent Entity transaction boundary"); + } + } + + private record Census( + long rows, long unqualifiedRows, long retainedRows, long selectedScopeRows, long references) { + private Census { + if (rows < 0L + || unqualifiedRows < 0L + || retainedRows < 0L + || selectedScopeRows < 0L + || references < 0L + || Math.addExact(unqualifiedRows, retainedRows) != rows) { + throw new IllegalStateException("Entity census partitions are invalid"); + } + } + + private static Census emptyOnlyProviderState() { + // This is not inferred from missing legacy storage: the caller persists a typed, immutable + // EMPTY provider record for this exact newly authorized source and independently reads it. + return new Census(0L, 0L, 0L, 0L, 0L); + } + + private boolean isZero() { + return rows == 0L + && unqualifiedRows == 0L + && retainedRows == 0L + && selectedScopeRows == 0L + && references == 0L; + } + } + + private static final class IntakeConflictException extends IllegalStateException { + private IntakeConflictException(String message) { + super(message); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java new file mode 100644 index 0000000000..834fc925b5 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java @@ -0,0 +1,201 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered preparation service for authenticated, freshly founded empty Entity scopes. */ +public final class EntityEmptySelectedSourceIntakeService { + private final String configuredNamespace; + private final EntityEmptySelectedSourceIntakeRepository repository; + private final SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient; + private final SelectedOwnerWorldInventoryReadClient worldInventoryReadClient; + + public EntityEmptySelectedSourceIntakeService( + String configuredNamespace, + EntityEmptySelectedSourceIntakeRepository repository, + SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient, + SelectedOwnerWorldInventoryReadClient worldInventoryReadClient) { + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("Configured Entity namespace is required"); + } + this.configuredNamespace = configuredNamespace; + this.repository = Objects.requireNonNull(repository, "repository"); + this.authorizationReadClient = + Objects.requireNonNull(authorizationReadClient, "authorizationReadClient"); + this.worldInventoryReadClient = + Objects.requireNonNull(worldInventoryReadClient, "worldInventoryReadClient"); + } + + /** + * Replays an exact retained receipt or prepares a fresh owner-local retention attempt. This + * method does not publish, activate, create nonempty templates, or settle Account participation. + */ + public EntityEmptySelectedSourceIntakeReceipt retain( + String targetNamespace, + SelectedOwnerIntakeAuthorizationBinding originalBinding, + WorldSelectedDraftPublicationFreezeEvidence exactFreeze) { + requireConfiguredNamespace(targetNamespace); + requireAuthenticatedGameDesignCaller(targetNamespace); + requireNoAmbientOwnerSql(); + requireRequest(targetNamespace, originalBinding, exactFreeze); + String requestDigest = + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + targetNamespace, originalBinding, exactFreeze); + + var retained = repository.read(targetNamespace, originalBinding.intakeRequestId()); + if (retained.isPresent()) { + EntityEmptySelectedSourceIntakeReceipt receipt = retained.orElseThrow(); + receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze); + return receipt; + } + + SelectedOwnerIntakeAuthorizationReadEvidence.Request authorizationRequest = + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( + targetNamespace, originalBinding); + var authorizationEvidence = authorizationReadClient.read(authorizationRequest); + if (authorizationEvidence == null + || !authorizationRequest.equals(authorizationEvidence.request())) { + throw new IllegalStateException("Account did not echo the exact selected-owner read request"); + } + + SelectedOwnerWorldInventoryReadEvidence.Request worldRequest = + SelectedOwnerWorldInventoryReadEvidence.Request.create( + targetNamespace, originalBinding, exactFreeze); + var worldEvidence = worldInventoryReadClient.read(worldRequest); + if (worldEvidence == null || !worldRequest.equals(worldEvidence.request())) { + throw new IllegalStateException("World did not echo the exact selected-owner read request"); + } + + // Typed inputs bind bytes only. The authenticated clients supply producer identity; Account's + // distinct source participation remains protected until an exact owner terminal is settled. + SelectedOwnerEmptySourceInputs inputs = + new SelectedOwnerEmptySourceInputs(originalBinding, worldEvidence); + requireEmptyWorldEntityClosure(worldEvidence.inventory().publicEvidence()); + + // A second HELD sample narrows the gap after the remote World read. It does not extend or prove + // continuous Account protection through Entity's local commit. + SelectedOwnerIntakeAuthorizationReadEvidence.Request finalAuthorizationRequest = + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( + targetNamespace, originalBinding); + var finalAuthorizationEvidence = authorizationReadClient.read(finalAuthorizationRequest); + if (finalAuthorizationEvidence == null + || !finalAuthorizationRequest.equals(finalAuthorizationEvidence.request())) { + throw new IllegalStateException("Account did not echo the final selected-owner read request"); + } + + EntityEmptySelectedSourceIntakeReceipt receipt = repository.retainFresh(inputs, requestDigest); + receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze); + return receipt; + } + + private void requireConfiguredNamespace(String targetNamespace) { + if (!configuredNamespace.equals(targetNamespace)) { + throw new SecurityException( + "Selected Entity intake namespace differs from the configured Entity owner namespace"); + } + } + + private static void requireAuthenticatedGameDesignCaller(String targetNamespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw new SecurityException("Authenticated same-namespace Game Design peer is required"); + } + if (AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get() != null + || SessionContext.hasAuthenticatedCallerContext() + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !targetNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + targetNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw new SecurityException( + "Selected Entity intake requires the exact same-namespace Game Design peer"); + } + } + + private static void requireRequest( + String targetNamespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + Objects.requireNonNull(binding, "original Account authorization binding is required"); + Objects.requireNonNull(freezeEvidence, "exact World freeze is required"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !targetNamespace.equals(binding.targetNamespace()) + || binding.owner() != Owner.ENTITY_MANAGEMENT + || !binding.schema().equals("account-entity-intake-authorization/v1") + || !binding.purpose().equals("ENTITY_INTAKE_RETENTION")) { + throw new IllegalArgumentException( + "Fresh Entity intake requires its exact finalized Account owner binding"); + } + var freeze = freezeEvidence.request(); + if (!targetNamespace.equals(freeze.targetNamespace()) + || !binding.tenantId().equals(freeze.canonicalTenantId()) + || !binding.versionId().equals(freeze.canonicalVersionId()) + || !binding + .selected() + .equals(freeze.accountBinding().input().selection().selectedCommit())) { + throw new IllegalArgumentException( + "Entity owner binding differs from the exact selected World freeze"); + } + } + + private static void requireEmptyWorldEntityClosure( + WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence inventory) { + if (!WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA.equals( + inventory.schema()) + || inventory.schemaVersion() + != WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION + || !WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL.equals( + inventory.sourceModel().modelId()) + || inventory.sourceModel().graphSchemaVersion() + != WorldSelectedPublicationArtifactInventoryEvidence + .INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION + || inventory.sourceModel().inboundSourceClosure() == null) { + throw new IllegalArgumentException( + "Entity empty-source intake requires the complete supported World closure"); + } + var sourceModel = inventory.sourceModel(); + int spawnCount = + sourceModel.familyCounts().stream() + .filter(family -> "WORLD_ENTITY_SPAWN_BINDING".equals(family.family())) + .mapToInt(WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount::rowCount) + .findFirst() + .orElseThrow( + () -> new IllegalArgumentException("World population family state is unavailable")); + if (spawnCount != 0 + || sourceModel.spawnBindingCount() != 0 + || !sourceModel.spawnBindingInputs().isEmpty()) { + throw new IllegalArgumentException( + "Entity empty-source intake cannot retain World population bindings"); + } + var closure = sourceModel.inboundSourceClosure(); + if (closure.schemaVersion() != 1 || closure.familyCounts().size() != 7) { + throw new IllegalArgumentException("World inbound closure family vector is incomplete"); + } + for (var family : closure.familyCounts()) { + if (family.count() != 0) { + throw new IllegalArgumentException( + "Entity empty-source intake cannot retain World item, loot, behavior, or hook references"); + } + } + } + + private static void requireNoAmbientOwnerSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account and World evidence reads must run outside Entity SQL"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java new file mode 100644 index 0000000000..163256d712 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account-only lookup over Entity's immutable selected-source terminal receipt. */ +public final class EntityEmptySelectedSourceIntakeTerminalReadService { + private final EntityEmptySelectedSourceIntakeRepository repository; + private final String namespace; + + public EntityEmptySelectedSourceIntakeTerminalReadService( + EntityEmptySelectedSourceIntakeRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical namespace required"); + } + this.namespace = namespace; + } + + /** Called by the transport before decoding caller-carried evidence or touching owner storage. */ + void requireAuthenticatedAccountCaller() { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + if (!namespace.equals(peer.namespace()) + || !"account-service".equals(peer.service()) + || !("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } + + /** Reads only the exact original COMMITTED_EMPTY receipt; absence is not terminal abort. */ + public EntitySelectedSourceIntakeTerminalReadEvidence read( + EntitySelectedSourceIntakeTerminalReadEvidence.Request request) { + requireAuthenticatedAccountCaller(); + Objects.requireNonNull(request, "terminal-read request is required"); + if (!namespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + + final net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt + receipt; + try { + receipt = + repository + .read(namespace, request.binding().intakeRequestId()) + .orElseThrow(() -> Status.NOT_FOUND.asRuntimeException()); + } catch (StatusRuntimeException denied) { + throw denied; + } catch (RuntimeException corrupt) { + throw Status.DATA_LOSS + .withDescription("Entity committed receipt is invalid") + .asRuntimeException(); + } + + if (!Arrays.equals(request.binding().canonicalBytes(), receipt.authorizationBindingBytes())) { + throw Status.ALREADY_EXISTS + .withDescription("Entity receipt differs from the complete original authorization") + .asRuntimeException(); + } + try { + return new EntitySelectedSourceIntakeTerminalReadEvidence(request, receipt); + } catch (RuntimeException corrupt) { + throw Status.DATA_LOSS + .withDescription("Entity receipt differs from its original order") + .asRuntimeException(); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java new file mode 100644 index 0000000000..190e145b93 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered Game Design command boundary for retaining exact selected Entity inputs. */ +public final class EntitySelectedSourceIntakeCommandGrpcService + extends EntitySelectedSourceIntakeCommandServiceGrpc + .EntitySelectedSourceIntakeCommandServiceImplBase { + private final EntityEmptySelectedSourceIntakeService owner; + private final String namespace; + + public EntitySelectedSourceIntakeCommandGrpcService( + EntityEmptySelectedSourceIntakeService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-source intake owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("configured namespace is invalid"); + } + this.namespace = namespace; + } + + @Override + public void retainSelectedEntitySource( + RetainSelectedEntitySourceRequest request, + StreamObserver observer) { + try { + requireAuthenticatedGameDesignCaller(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + + final EntitySelectedSourceIntakeCommandEvidence.Request decoded; + try { + decoded = EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var receipt = + owner.retain( + decoded.targetNamespace(), + decoded.originalAuthorizationBinding(), + decoded.freezeEvidence()); + var evidence = new EntitySelectedSourceIntakeCommandEvidence(decoded, receipt); + observer.onNext(EntitySelectedSourceIntakeCommandGrpcCodec.toResponse(evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException denied) { + observer.onError(Status.fromCode(denied.getStatus().getCode()).asRuntimeException()); + } catch (SecurityException denied) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + } catch (IllegalArgumentException | IllegalStateException unavailable) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } + + /** Authenticate the exact same-namespace workload and reject user context before decoding. */ + private void requireAuthenticatedGameDesignCaller() { + if (SessionContext.hasAuthenticatedCallerContext() + || AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get() != null) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + if (!namespace.equals(peer.namespace()) + || !"game-design-service".equals(peer.service()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcService.java new file mode 100644 index 0000000000..1b58c29642 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcService.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadGrpcCodec; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse; + +/** No automatic registration; authenticate Account before parsing its claimed original binding. */ +public final class EntitySelectedSourceIntakeTerminalReadGrpcService + extends EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceImplBase { + private final EntityEmptySelectedSourceIntakeTerminalReadService owner; + + public EntitySelectedSourceIntakeTerminalReadGrpcService( + EntityEmptySelectedSourceIntakeTerminalReadService owner) { + this.owner = Objects.requireNonNull(owner, "terminal-read owner is required"); + } + + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest request, + StreamObserver observer) { + try { + owner.requireAuthenticatedAccountCaller(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadEvidence.Request + decoded; + try { + decoded = EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + var evidence = owner.read(decoded); + observer.onNext(EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse(evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + } catch (RuntimeException corrupt) { + observer.onError(Status.DATA_LOSS.asRuntimeException()); + } + } +} diff --git a/services/entity-management-service/src/main/resources/db/migration/V2__fresh_selected_empty_source_catalogue.sql b/services/entity-management-service/src/main/resources/db/migration/V2__fresh_selected_empty_source_catalogue.sql new file mode 100644 index 0000000000..5d6a33692f --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V2__fresh_selected_empty_source_catalogue.sql @@ -0,0 +1,1074 @@ +-- Fresh-only selected-source retention. Existing Entity rows are never adopted as a selected +-- source; they are reserved as occupied numeric keys and deny a fresh empty-source census. +CREATE TABLE entity_empty_source_numeric_key_reservation ( + key_kind VARCHAR(16) NOT NULL, + numeric_key BIGINT NOT NULL, + claim_kind VARCHAR(32) NOT NULL, + CONSTRAINT pk_entity_empty_source_numeric_key_reservation + PRIMARY KEY (key_kind, numeric_key), + CONSTRAINT uq_entity_empty_source_numeric_key_claim + UNIQUE (numeric_key, key_kind, claim_kind), + CONSTRAINT ck_entity_empty_source_numeric_key_kind + CHECK (key_kind IN ('TENANT', 'VERSION')), + CONSTRAINT ck_entity_empty_source_numeric_key_positive + CHECK (numeric_key > 0), + CONSTRAINT ck_entity_empty_source_numeric_key_claim + CHECK (claim_kind IN ('LEGACY_NUMERIC', 'CANONICAL_EMPTY_SOURCE')) +); + +CREATE TABLE entity_empty_selected_source_association ( + target_namespace VARCHAR(63) NOT NULL, + genesis_id UUID NOT NULL, + operation_id UUID NOT NULL, + fence_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + source_revision_id UUID NOT NULL, + source_revision_order VARCHAR(32) NOT NULL, + local_tenant_key BIGINT NOT NULL, + local_tenant_key_kind VARCHAR(16) NOT NULL DEFAULT 'TENANT', + local_tenant_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE', + local_version_key BIGINT NOT NULL, + local_version_key_kind VARCHAR(16) NOT NULL DEFAULT 'VERSION', + local_version_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE', + request_digest VARCHAR(71) NOT NULL, + schema_digest VARCHAR(71) NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + world_read_request_id UUID NOT NULL, + world_read_request_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + associated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_selected_source_association + PRIMARY KEY (target_namespace, canonical_tenant_id, canonical_version_id), + CONSTRAINT uq_entity_empty_selected_source_request + UNIQUE (target_namespace, intake_request_id), + CONSTRAINT uq_entity_empty_selected_source_operation + UNIQUE (target_namespace, operation_id), + CONSTRAINT uq_entity_empty_selected_source_genesis + UNIQUE (genesis_id), + CONSTRAINT uq_entity_empty_selected_source_local_tenant + UNIQUE (local_tenant_key), + CONSTRAINT uq_entity_empty_selected_source_local_version + UNIQUE (local_version_key), + CONSTRAINT ck_entity_empty_selected_source_namespace + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT ck_entity_empty_selected_source_ids_nonzero + CHECK ( + genesis_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_revision_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_read_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_entity_empty_selected_source_local_keys + CHECK ( + local_tenant_key > 0 + AND local_version_key > 0 + AND local_tenant_key <> local_version_key + AND local_tenant_key_kind = 'TENANT' + AND local_tenant_key_claim_kind = 'CANONICAL_EMPTY_SOURCE' + AND local_version_key_kind = 'VERSION' + AND local_version_key_claim_kind = 'CANONICAL_EMPTY_SOURCE' + ), + CONSTRAINT ck_entity_empty_selected_source_revision_order + CHECK (source_revision_order ~ '^(0|[1-9][0-9]*)$'), + CONSTRAINT ck_entity_empty_selected_source_digests + CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND schema_digest ~ '^sha256:[0-9a-f]{64}$' + AND authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_read_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT fk_entity_empty_selected_source_tenant_key + FOREIGN KEY (local_tenant_key, local_tenant_key_kind, local_tenant_key_claim_kind) + REFERENCES entity_empty_source_numeric_key_reservation + (numeric_key, key_kind, claim_kind), + CONSTRAINT fk_entity_empty_selected_source_version_key + FOREIGN KEY (local_version_key, local_version_key_kind, local_version_key_claim_kind) + REFERENCES entity_empty_source_numeric_key_reservation + (numeric_key, key_kind, claim_kind) +); + +-- These fourteen owner-local providers deliberately support only an explicit EMPTY state. +-- Each has its own persisted typed table; the receipt family-state ledger is not a provider. +CREATE TABLE entity_empty_source_other_actor_template_roots ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_other_actor_template_roots PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_other_actor_template_roots_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_other_actor_template_roots_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_other_actor_template_roots_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_other_actor_template_roots_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_other_actor_template_roots_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_equipment_capabilities ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_equipment_capabilities PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_equipment_capabilities_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_equipment_capabilities_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_equipment_capabilities_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_equipment_capabilities_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_equipment_capabilities_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_equipment_attachment_rules ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_equipment_attachment_rules PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_equipment_attachment_rules_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_equipment_compatibility_rules ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_equipment_compatibility_rules PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_equipment_compatibility_rules_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_equipment_occupancy_rules ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_equipment_occupancy_rules PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_equipment_occupancy_rules_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_actor_body_layout_assignments ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_actor_body_layout_assignments PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_actor_body_layout_assignments_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_loot_table_roots ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_loot_table_roots PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_loot_table_roots_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_loot_table_roots_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_loot_table_roots_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_loot_table_roots_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_loot_table_roots_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_loot_item_mappings ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_loot_item_mappings PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_loot_item_mappings_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_loot_item_mappings_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_loot_item_mappings_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_loot_item_mappings_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_loot_item_mappings_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_inbound_loot_bindings ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_inbound_loot_bindings PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_inbound_loot_bindings_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_balance_curve_roots ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_balance_curve_roots PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_balance_curve_roots_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_balance_curve_roots_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_balance_curve_roots_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_balance_curve_roots_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_balance_curve_roots_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_balance_curve_attachments ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_balance_curve_attachments PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_balance_curve_attachments_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_balance_curve_attachments_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_balance_curve_attachments_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_balance_curve_attachments_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_balance_curve_attachments_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_archetype_roots ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_archetype_roots PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_archetype_roots_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_archetype_roots_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_archetype_roots_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_archetype_roots_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_archetype_roots_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_archetype_constraints ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_archetype_constraints PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_archetype_constraints_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_archetype_constraints_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_archetype_constraints_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_archetype_constraints_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_archetype_constraints_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_archetype_assignments ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_archetype_assignments PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_archetype_assignments_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_archetype_assignments_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_archetype_assignments_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_archetype_assignments_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_archetype_assignments_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); +CREATE TABLE entity_empty_selected_source_family_state ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + family_name VARCHAR(64) NOT NULL, + owner_state VARCHAR(16) NOT NULL, + evidence_kind VARCHAR(32) NOT NULL, + row_count BIGINT NOT NULL, + unqualified_row_count BIGINT NOT NULL, + retained_row_count BIGINT NOT NULL, + selected_scope_row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + CONSTRAINT pk_entity_empty_selected_source_family_state + PRIMARY KEY (target_namespace, intake_request_id, family_name), + CONSTRAINT fk_entity_empty_selected_source_family_association + FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_selected_source_family_name + CHECK (family_name IN ( + 'ACTOR_BODY_LAYOUT_ASSIGNMENTS', + 'ARCHETYPE_ASSIGNMENTS', + 'ARCHETYPE_CONSTRAINTS', + 'ARCHETYPE_ROOTS', + 'BALANCE_CURVE_ATTACHMENTS', + 'BALANCE_CURVE_ROOTS', + 'BODY_LAYOUT_MEMBERSHIPS', + 'BODY_LAYOUT_ROOTS', + 'CRAFTING_INGREDIENT_BINDINGS', + 'CRAFTING_RECIPE_RESULT_BINDINGS', + 'CRAFTING_RECIPE_ROOTS', + 'EQUIPMENT_ATTACHMENT_RULES', + 'EQUIPMENT_CAPABILITIES', + 'EQUIPMENT_COMPATIBILITY_RULES', + 'EQUIPMENT_OCCUPANCY_RULES', + 'EQUIPMENT_SLOT_GROUPS', + 'EQUIPMENT_SLOT_ROOTS', + 'INBOUND_LOOT_BINDINGS', + 'ITEM_TEMPLATE_ROOTS', + 'LOOT_ITEM_MAPPINGS', + 'LOOT_TABLE_ROOTS', + 'NPC_TEMPLATE_ROOTS', + 'OTHER_ACTOR_TEMPLATE_ROOTS' + )), + CONSTRAINT ck_entity_empty_selected_source_family_state + CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_selected_source_family_evidence_kind + CHECK ( + (family_name IN ( + 'ITEM_TEMPLATE_ROOTS', 'NPC_TEMPLATE_ROOTS', 'CRAFTING_RECIPE_ROOTS', + 'CRAFTING_RECIPE_RESULT_BINDINGS', 'CRAFTING_INGREDIENT_BINDINGS', + 'EQUIPMENT_SLOT_ROOTS', 'EQUIPMENT_SLOT_GROUPS', 'BODY_LAYOUT_ROOTS', + 'BODY_LAYOUT_MEMBERSHIPS' + ) AND evidence_kind = 'V1_SOURCE_CENSUS') + OR (family_name IN ( + 'ACTOR_BODY_LAYOUT_ASSIGNMENTS', 'ARCHETYPE_ASSIGNMENTS', + 'ARCHETYPE_CONSTRAINTS', 'ARCHETYPE_ROOTS', 'BALANCE_CURVE_ATTACHMENTS', + 'BALANCE_CURVE_ROOTS', 'EQUIPMENT_ATTACHMENT_RULES', + 'EQUIPMENT_CAPABILITIES', 'EQUIPMENT_COMPATIBILITY_RULES', + 'EQUIPMENT_OCCUPANCY_RULES', 'INBOUND_LOOT_BINDINGS', 'LOOT_ITEM_MAPPINGS', + 'LOOT_TABLE_ROOTS', 'OTHER_ACTOR_TEMPLATE_ROOTS' + ) AND evidence_kind = 'EMPTY_ONLY_OWNER_PROVIDER') + ), + CONSTRAINT ck_entity_empty_selected_source_family_counts + CHECK ( + row_count = 0 + AND unqualified_row_count = 0 + AND retained_row_count = 0 + AND selected_scope_row_count = 0 + AND reference_count = 0 + ) +); + +CREATE TABLE entity_empty_selected_source_receipt ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + schema_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + receipt_bytes BYTEA NOT NULL, + retained_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_selected_source_receipt + PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_selected_source_receipt_association + FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_selected_source_receipt_digests + CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND schema_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(receipt_bytes) BETWEEN 1 AND 83886080 + ) +); + +CREATE INDEX idx_entity_empty_source_key_claim_kind + ON entity_empty_source_numeric_key_reservation (claim_kind, key_kind, numeric_key); + +/* [jooq ignore start] */ +CREATE FUNCTION entity_source_positive_numeric_key(value_text TEXT) +RETURNS BIGINT +LANGUAGE plpgsql +IMMUTABLE +STRICT +SET search_path = pg_catalog +AS $$ +DECLARE + parsed_value NUMERIC; +BEGIN + IF value_text !~ '^[0-9]+$' THEN + RETURN NULL; + END IF; + parsed_value := value_text::NUMERIC; + IF parsed_value <= 0 OR parsed_value > 9223372036854775807 THEN + RETURN NULL; + END IF; + RETURN parsed_value::BIGINT; +END; +$$; +/* [jooq ignore stop] */ + +-- Lock the receipt/key tables first and then every V1 tenant/version holder and source/reference +-- relation. This both seeds real occupied keys and closes insert/update phantoms for the same +-- fixed order used by the owner-local founding transaction. +/* [jooq ignore start] */ +LOCK TABLE entity_empty_source_numeric_key_reservation, + entity_empty_selected_source_association, + entity_empty_selected_source_family_state, + entity_empty_selected_source_receipt, + entity_empty_source_other_actor_template_roots, + entity_empty_source_equipment_capabilities, + entity_empty_source_equipment_attachment_rules, + entity_empty_source_equipment_compatibility_rules, + entity_empty_source_equipment_occupancy_rules, + entity_empty_source_actor_body_layout_assignments, + entity_empty_source_loot_table_roots, + entity_empty_source_loot_item_mappings, + entity_empty_source_inbound_loot_bindings, + entity_empty_source_balance_curve_roots, + entity_empty_source_balance_curve_attachments, + entity_empty_source_archetype_roots, + entity_empty_source_archetype_constraints, + entity_empty_source_archetype_assignments + IN SHARE ROW EXCLUSIVE MODE; +/* [jooq ignore stop] */ +/* [jooq ignore start] */ +LOCK TABLE actor_active_conditions, actor_resource_states, body_layout_slot_definitions, + character_equipment, character_friend, characters, container_instances, + crafting_ingredients, crafting_recipes, entity_mutation_effects, + equipment_slot_definitions, inventory, item_instances, item_stacks, + item_transfer_audits, item_visible_ref_counters, items, npcs, room_ground_inventory + IN SHARE MODE; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +INSERT INTO entity_empty_source_numeric_key_reservation (key_kind, numeric_key, claim_kind) +SELECT DISTINCT key_kind, numeric_key, 'LEGACY_NUMERIC' +FROM ( + SELECT 'TENANT'::VARCHAR(16) AS key_kind, tenant_id AS numeric_key FROM characters + UNION ALL SELECT 'TENANT', tenant_id FROM npcs + UNION ALL SELECT 'TENANT', tenant_id FROM items + UNION ALL SELECT 'TENANT', tenant_id FROM crafting_recipes + UNION ALL SELECT 'TENANT', tenant_id FROM character_friend + UNION ALL SELECT 'TENANT', tenant_id FROM room_ground_inventory + UNION ALL SELECT 'TENANT', tenant_id FROM container_instances + UNION ALL SELECT 'TENANT', tenant_id FROM item_instances + UNION ALL SELECT 'TENANT', tenant_id FROM item_visible_ref_counters + UNION ALL SELECT 'TENANT', tenant_id FROM item_stacks + UNION ALL SELECT 'TENANT', tenant_id FROM entity_mutation_effects + UNION ALL SELECT 'TENANT', tenant_id FROM item_transfer_audits + UNION ALL SELECT 'TENANT', tenant_id FROM equipment_slot_definitions + UNION ALL SELECT 'TENANT', tenant_id FROM body_layout_slot_definitions + UNION ALL SELECT 'TENANT', tenant_id FROM actor_resource_states + UNION ALL SELECT 'TENANT', tenant_id FROM actor_active_conditions + UNION ALL SELECT 'VERSION', version_id FROM items + UNION ALL SELECT 'VERSION', version_id FROM npcs + UNION ALL SELECT 'VERSION', version_id FROM crafting_recipes + UNION ALL SELECT 'VERSION', version_id FROM equipment_slot_definitions + UNION ALL SELECT 'VERSION', version_id FROM body_layout_slot_definitions +) AS existing_entity_keys +WHERE numeric_key > 0 +ON CONFLICT (key_kind, numeric_key) DO NOTHING; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +DO $entity_empty_source_functions$ +DECLARE + owner_schema TEXT := current_schema(); +BEGIN + IF owner_schema IS NULL THEN + RAISE EXCEPTION 'Entity empty-source functions require an explicit installation schema'; + END IF; + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_require_source_numeric_key_unreserved( + requested_kind TEXT, requested_key BIGINT + ) RETURNS VOID + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + retained_claim TEXT; + BEGIN + IF requested_key IS NULL OR requested_key <= 0 THEN + RETURN; + END IF; + SELECT claim_kind INTO retained_claim + FROM %I.entity_empty_source_numeric_key_reservation + WHERE key_kind = requested_kind AND numeric_key = requested_key; + IF retained_claim = 'CANONICAL_EMPTY_SOURCE' THEN + RAISE EXCEPTION 'Entity numeric source key is reserved by an immutable empty-source receipt'; + END IF; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_guard_source_owner_row() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + old_value JSONB; + new_value JSONB; + old_tenant_key BIGINT; + new_tenant_key BIGINT; + old_version_key BIGINT; + new_version_key BIGINT; + BEGIN + IF TG_OP IN ('UPDATE', 'DELETE') THEN + old_value := to_jsonb(OLD); + old_tenant_key := %I.entity_source_positive_numeric_key(old_value->>'tenant_id'); + old_version_key := %I.entity_source_positive_numeric_key(old_value->>'version_id'); + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', old_tenant_key); + PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', old_version_key); + END IF; + IF TG_OP IN ('INSERT', 'UPDATE') THEN + new_value := to_jsonb(NEW); + new_tenant_key := %I.entity_source_positive_numeric_key(new_value->>'tenant_id'); + new_version_key := %I.entity_source_positive_numeric_key(new_value->>'version_id'); + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', new_tenant_key); + PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', new_version_key); + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema, owner_schema, + owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_guard_character_template_reference() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + old_character_id BIGINT; + new_character_id BIGINT; + referenced_tenant BIGINT; + BEGIN + IF TG_OP IN ('UPDATE', 'DELETE') THEN + old_character_id := (to_jsonb(OLD)->>'character_id')::BIGINT; + SELECT tenant_id INTO referenced_tenant FROM %I.characters WHERE id = old_character_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Entity character reference owner is unavailable'; + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + END IF; + IF TG_OP IN ('INSERT', 'UPDATE') THEN + new_character_id := (to_jsonb(NEW)->>'character_id')::BIGINT; + SELECT tenant_id INTO referenced_tenant FROM %I.characters WHERE id = new_character_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Entity character reference owner is unavailable'; + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_guard_recipe_ingredient_reference() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + old_recipe_id BIGINT; + new_recipe_id BIGINT; + referenced_tenant BIGINT; + referenced_version BIGINT; + BEGIN + IF TG_OP IN ('UPDATE', 'DELETE') THEN + old_recipe_id := (to_jsonb(OLD)->>'recipe_id')::BIGINT; + SELECT tenant_id, version_id INTO referenced_tenant, referenced_version + FROM %I.crafting_recipes WHERE id = old_recipe_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Entity crafting recipe reference owner is unavailable'; + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', referenced_version); + END IF; + IF TG_OP IN ('INSERT', 'UPDATE') THEN + new_recipe_id := (to_jsonb(NEW)->>'recipe_id')::BIGINT; + SELECT tenant_id, version_id INTO referenced_tenant, referenced_version + FROM %I.crafting_recipes WHERE id = new_recipe_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Entity crafting recipe reference owner is unavailable'; + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', referenced_version); + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, + owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_reject_source_truncate() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + BEGIN + IF EXISTS ( + SELECT 1 FROM %I.entity_empty_source_numeric_key_reservation + WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE' + ) THEN + RAISE EXCEPTION 'Entity authored-source TRUNCATE is forbidden after canonical intake'; + END IF; + RETURN NULL; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_reject_empty_source_record_mutation() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + BEGIN + RAISE EXCEPTION 'Entity empty-source intake records are immutable'; + END; + $body$ + $function$, owner_schema, owner_schema); +END; +$entity_empty_source_functions$; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +REVOKE ALL ON FUNCTION entity_source_positive_numeric_key(TEXT) FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_require_source_numeric_key_unreserved(TEXT, BIGINT) FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_guard_source_owner_row() FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_guard_character_template_reference() FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_guard_recipe_ingredient_reference() FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_reject_source_truncate() FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_reject_empty_source_record_mutation() FROM PUBLIC; + +CREATE TRIGGER trg_entity_items_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON items + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_npcs_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON npcs + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_recipes_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON crafting_recipes + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_equipment_slots_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON equipment_slot_definitions + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_body_layouts_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON body_layout_slot_definitions + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); + +CREATE TRIGGER trg_entity_character_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON characters + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_character_friend_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON character_friend + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_room_ground_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON room_ground_inventory + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_container_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON container_instances + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_item_instance_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON item_instances + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_item_stack_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON item_stacks + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_item_audit_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON item_transfer_audits + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_item_reference_counter_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON item_visible_ref_counters + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_mutation_effect_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON entity_mutation_effects + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_actor_resource_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON actor_resource_states + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_actor_condition_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON actor_active_conditions + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); + +CREATE TRIGGER trg_entity_inventory_character_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON inventory + FOR EACH ROW EXECUTE FUNCTION entity_guard_character_template_reference(); +CREATE TRIGGER trg_entity_character_equipment_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON character_equipment + FOR EACH ROW EXECUTE FUNCTION entity_guard_character_template_reference(); +CREATE TRIGGER trg_entity_crafting_ingredient_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON crafting_ingredients + FOR EACH ROW EXECUTE FUNCTION entity_guard_recipe_ingredient_reference(); + +CREATE TRIGGER trg_entity_items_source_no_truncate + BEFORE TRUNCATE ON items + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); +CREATE TRIGGER trg_entity_npcs_source_no_truncate + BEFORE TRUNCATE ON npcs + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); +CREATE TRIGGER trg_entity_recipes_source_no_truncate + BEFORE TRUNCATE ON crafting_recipes + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); +CREATE TRIGGER trg_entity_ingredients_source_no_truncate + BEFORE TRUNCATE ON crafting_ingredients + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); +CREATE TRIGGER trg_entity_equipment_slots_source_no_truncate + BEFORE TRUNCATE ON equipment_slot_definitions + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); +CREATE TRIGGER trg_entity_body_layouts_source_no_truncate + BEFORE TRUNCATE ON body_layout_slot_definitions + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); + +CREATE TRIGGER trg_entity_empty_source_key_reservation_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_numeric_key_reservation + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_key_reservation_no_truncate + BEFORE TRUNCATE ON entity_empty_source_numeric_key_reservation + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_association_immutable + BEFORE UPDATE OR DELETE ON entity_empty_selected_source_association + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_association_no_truncate + BEFORE TRUNCATE ON entity_empty_selected_source_association + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_family_state_immutable + BEFORE UPDATE OR DELETE ON entity_empty_selected_source_family_state + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_family_state_no_truncate + BEFORE TRUNCATE ON entity_empty_selected_source_family_state + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_receipt_immutable + BEFORE UPDATE OR DELETE ON entity_empty_selected_source_receipt + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_receipt_no_truncate + BEFORE TRUNCATE ON entity_empty_selected_source_receipt + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_other_actor_template_roots_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_other_actor_template_roots + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_other_actor_template_roots_no_truncate + BEFORE TRUNCATE ON entity_empty_source_other_actor_template_roots + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_capabilities_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_capabilities + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_capabilities_no_truncate + BEFORE TRUNCATE ON entity_empty_source_equipment_capabilities + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_attachment_rules_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_attachment_rules + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_attachment_rules_no_truncate + BEFORE TRUNCATE ON entity_empty_source_equipment_attachment_rules + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_compatibility_rules_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_compatibility_rules + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_compatibility_rules_no_truncate + BEFORE TRUNCATE ON entity_empty_source_equipment_compatibility_rules + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_occupancy_rules_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_occupancy_rules + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_occupancy_rules_no_truncate + BEFORE TRUNCATE ON entity_empty_source_equipment_occupancy_rules + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_actor_body_layout_assignments_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_actor_body_layout_assignments + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_actor_body_layout_assignments_no_truncate + BEFORE TRUNCATE ON entity_empty_source_actor_body_layout_assignments + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_loot_table_roots_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_loot_table_roots + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_loot_table_roots_no_truncate + BEFORE TRUNCATE ON entity_empty_source_loot_table_roots + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_loot_item_mappings_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_loot_item_mappings + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_loot_item_mappings_no_truncate + BEFORE TRUNCATE ON entity_empty_source_loot_item_mappings + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_inbound_loot_bindings_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_inbound_loot_bindings + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_inbound_loot_bindings_no_truncate + BEFORE TRUNCATE ON entity_empty_source_inbound_loot_bindings + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_balance_curve_roots_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_balance_curve_roots + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_balance_curve_roots_no_truncate + BEFORE TRUNCATE ON entity_empty_source_balance_curve_roots + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_balance_curve_attachments_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_balance_curve_attachments + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_balance_curve_attachments_no_truncate + BEFORE TRUNCATE ON entity_empty_source_balance_curve_attachments + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_roots_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_archetype_roots + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_roots_no_truncate + BEFORE TRUNCATE ON entity_empty_source_archetype_roots + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_constraints_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_archetype_constraints + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_constraints_no_truncate + BEFORE TRUNCATE ON entity_empty_source_archetype_constraints + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_assignments_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_archetype_assignments + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_assignments_no_truncate + BEFORE TRUNCATE ON entity_empty_source_archetype_assignments + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..41227af001 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for V2's real legacy-key seed and retained-key writer guards. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DSLContext dsl; + + @BeforeEach + void seedLegacyRowsBeforeV2() { + schema = "entity_empty_source_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .target("1") + .load() + .migrate(); + + DSLContext legacyDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + // Synthetic pre-V2 rows exercise migration occupancy only. They are not selected-source + // evidence and do not authenticate Account, Game Design, or World producers. + legacyDsl.execute( + "INSERT INTO characters (account_id, name, tenant_id) VALUES (1, 'legacy', 31001)"); + legacyDsl.execute( + "INSERT INTO items (name, tenant_id, version_id) VALUES ('legacy', 41001, 51001)"); + legacyDsl.execute( + "INSERT INTO item_transfer_audits (tenant_id, item_id, quantity, verb, correlation_key, " + + "source_holder_kind, destination_holder_kind) " + + "VALUES (61001, 99001, 1, 'MOVE', 'legacy-audit', 'UNKNOWN', 'UNKNOWN')"); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + } + + @AfterEach + void dropIsolatedSchema() { + if (schema != null) { + String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE"); + schema = null; + } + } + + @Test + void migrationSeedsActualLegacySourceAndAuditTenantVersionKeys() { + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM entity_empty_source_numeric_key_reservation " + + "WHERE claim_kind = 'LEGACY_NUMERIC'", + Long.class)) + .isEqualTo(5L); + assertLegacyKey("TENANT", 31001L); + assertLegacyKey("TENANT", 41001L); + assertLegacyKey("TENANT", 61001L); + assertLegacyKey("VERSION", 51001L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM entity_empty_source_numeric_key_reservation " + + "WHERE key_kind = 'VERSION' AND numeric_key = 51001 " + + "AND claim_kind = 'LEGACY_NUMERIC'", + Long.class)) + .isEqualTo(1L); + } + + @Test + void retainedNumericKeysRejectLaterSourceRuntimeAndAuditWriters() { + dsl.execute( + "INSERT INTO entity_empty_source_numeric_key_reservation " + + "(key_kind, numeric_key, claim_kind) VALUES " + + "('TENANT', 99001, 'CANONICAL_EMPTY_SOURCE'), " + + "('VERSION', 99002, 'CANONICAL_EMPTY_SOURCE')"); + + assertRejected( + "INSERT INTO items (name, tenant_id, version_id) VALUES ('blocked', 99001, 99002)"); + assertRejected("UPDATE items SET tenant_id = 99001 WHERE tenant_id = 41001"); + assertRejected( + "INSERT INTO characters (account_id, name, tenant_id) VALUES (2, 'blocked', 99001)"); + assertRejected("UPDATE characters SET tenant_id = 99001 WHERE tenant_id = 31001"); + assertRejected( + "INSERT INTO item_transfer_audits (tenant_id, item_id, quantity, verb, correlation_key, " + + "source_holder_kind, destination_holder_kind) " + + "VALUES (99001, 99003, 1, 'MOVE', 'blocked-audit', 'UNKNOWN', 'UNKNOWN')"); + } + + @Test + void unassociatedLegacyKeysRemainWritable() { + dsl.execute( + "INSERT INTO items (name, tenant_id, version_id) " + + "VALUES ('unassociated legacy item', 71001, 71002)"); + dsl.execute( + "INSERT INTO characters (account_id, name, tenant_id) " + + "VALUES (3, 'unassociated legacy character', 72001)"); + + assertThat(dsl.fetchValue("SELECT COUNT(*) FROM items WHERE tenant_id = 71001", Long.class)) + .isEqualTo(1L); + assertThat( + dsl.fetchValue("SELECT COUNT(*) FROM characters WHERE tenant_id = 72001", Long.class)) + .isEqualTo(1L); + } + + private void assertLegacyKey(String kind, long key) { + assertThat( + dsl.fetchValue( + "SELECT claim_kind FROM entity_empty_source_numeric_key_reservation " + + "WHERE key_kind = ? AND numeric_key = ?", + String.class, + kind, + key)) + .isEqualTo("LEGACY_NUMERIC"); + } + + private void assertRejected(String sql) { + assertThatThrownBy(() -> dsl.execute(sql)).isInstanceOf(DataAccessException.class); + } + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + String baseUrl = postgres.getJdbcUrl(); + dataSource.setUrl( + schemaName == null + ? baseUrl + : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } +} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java new file mode 100644 index 0000000000..13c9d1f222 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java @@ -0,0 +1,468 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; + +/** + * Test-only synthetic inputs built through the same typed Common decoders as the shared fixture. + * They are not authenticated Account or World producer evidence or physical owner proof. + */ +final class EntityEmptySelectedSourceIntakePostgresFixture { + static final String NAMESPACE = "test"; + static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + + private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666"); + private static final UUID INTAKE_REQUEST = id("77777777-7777-4777-8777-777777777777"); + private static final UUID GENESIS_RECEIPT = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + private static final String TEMPLATE_CONFIG = + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + VERSION + + "\",\"world\":{\"regions\":[],\"rooms\":[]}," + + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]}," + + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}}," + + "\"supportedSettings\":[]}"; + + private EntityEmptySelectedSourceIntakePostgresFixture() {} + + static Fixture create(String sourceEpoch) { + DraftCommitBinding selected = selected(); + var scope = + new net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope( + Owner.ENTITY_MANAGEMENT, NAMESPACE, OPERATION, FENCE, INTAKE_REQUEST, ACTOR, selected); + TemplateConfigSourceSnapshot templateSnapshot = templateSnapshot(selected, sourceEpoch); + SelectedOwnerIntakeAuthorizationBinding authorization = + new SelectedOwnerIntakeAuthorizationBinding( + sourceContent(scope, templateSnapshot), accountSources()); + WorldSelectedDraftPublicationFreezeEvidence freeze = freezeEvidence(selected); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freeze, publicInventory(freeze)); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, authorization, freeze); + var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory); + return new Fixture( + authorization, + freeze, + worldEvidence, + new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)); + } + + static Fixture withFreshWorldReadCorrelation(Fixture original) { + var request = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, original.authorization(), original.freezeEvidence()); + var evidence = + new SelectedOwnerWorldInventoryReadEvidence(request, original.worldEvidence().inventory()); + return new Fixture( + original.authorization(), + original.freezeEvidence(), + evidence, + new SelectedOwnerEmptySourceInputs(original.authorization(), evidence)); + } + + private static TemplateConfigSourceSnapshot templateSnapshot( + DraftCommitBinding selected, String sourceEpoch) { + var declaration = + EntityAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"); + String declarationPayload = + TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, declaration); + DraftCommitBinding authored = authoredBinding(declarationPayload); + TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration = + TemplateConfigSourceValues.mutations(authored).stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .findFirst() + .orElseThrow(); + return new TemplateConfigSourceSnapshot( + selected, + sourceEpoch, + authored.commitId(), + GENESIS_RECEIPT, + List.of(), + List.of(ownerDeclaration)); + } + + private static DraftCommitBinding authoredBinding(String payload) { + return DraftCommitBinding.create( + target(), + id("51515151-5151-4151-8151-515151515151"), + id("52525252-5252-4252-8252-525252525252"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", + id("53535353-5353-4353-8353-535353535353"), + Owner.GAME_DESIGN_CONTROL_PLANE, + payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + VERSION.toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope, + TemplateConfigSourceSnapshot templateSnapshot) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + "TEMPLATE_CONFIG".equals(family) + ? templateSnapshot.canonicalBytes() + : sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + // These values exercise exact stored-byte decoding only; they are synthetic, not owner proof. + return switch (family) { + case "COMMAND" -> + new CommandSnapshot(selected, "0", null, "sha256:" + "0".repeat(64), List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> + new AssetSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + GENESIS_RECEIPT.toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported source family fixture: " + family); + }; + } + + private static List accountSources() { + return List.of( + source(SourceKind.TENANT, TENANT.toString(), "tenant"), + source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership")); + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected() { + return DraftCommitBinding.create( + target(), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + } + + private static TargetProof target() { + return new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + DraftCommitBinding selected) { + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + TENANT, + VERSION, + "publication-request", + "9", + "synthetic selected-owner intake fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), + List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication"))); + var request = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + TENANT, + VERSION, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + request, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 1), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + emptyInboundClosure()); + var ownerScope = + new PublicOwnerScope( + request.targetNamespace(), + TENANT, + VERSION, + id("14141414-1414-4414-8414-141414141414"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("17171717-1717-4717-8717-171717171717"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + ownerScope, + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static InboundSourceClosureDeclaration emptyInboundClosure() { + return new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + record Fixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence worldEvidence, + SelectedOwnerEmptySourceInputs inputs) {} +} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..ccde5b99f8 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java @@ -0,0 +1,299 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Physical PostgreSQL proof for Entity's synthetic-input fresh EMPTY-only retention boundary. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final List EMPTY_ONLY_TABLES = + List.of( + "entity_empty_source_actor_body_layout_assignments", + "entity_empty_source_archetype_assignments", + "entity_empty_source_archetype_constraints", + "entity_empty_source_archetype_roots", + "entity_empty_source_balance_curve_attachments", + "entity_empty_source_balance_curve_roots", + "entity_empty_source_equipment_attachment_rules", + "entity_empty_source_equipment_capabilities", + "entity_empty_source_equipment_compatibility_rules", + "entity_empty_source_equipment_occupancy_rules", + "entity_empty_source_inbound_loot_bindings", + "entity_empty_source_loot_item_mappings", + "entity_empty_source_loot_table_roots", + "entity_empty_source_other_actor_template_roots"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DSLContext dsl; + private EntityEmptySelectedSourceIntakeRepository repository; + + @BeforeEach + void migrateFreshIsolatedSchema() { + schema = "entity_empty_source_repo_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + repository = new EntityEmptySelectedSourceIntakeRepository(dsl); + } + + @AfterEach + void dropIsolatedSchema() { + if (schema != null) { + String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE"); + schema = null; + } + } + + @Test + void persistsAllTwentyThreeExplicitEmptyStatesAndReplaysOriginalReceiptBytes() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + var inputs = fixture.inputs(); + assertThat(inputs.ownerSourceInventoryDeclaration().owner()).isEqualTo(Owner.ENTITY_MANAGEMENT); + assertThat( + inputs + .worldInventoryReadEvidence() + .inventory() + .publicEvidence() + .sourceModel() + .inboundSourceClosure() + .familyCounts()) + .allSatisfy(count -> assertThat(count.count()).isZero()); + String requestDigest = requestDigest(fixture); + + EntityEmptySelectedSourceIntakeReceipt first = repository.retainFresh(inputs, requestDigest); + assertThat(first.familyStates()) + .hasSize(23) + .allSatisfy( + state -> { + assertThat(state.state()) + .isEqualTo(EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY); + assertThat(state.rowCount()).isZero(); + assertThat(state.referenceCount()).isZero(); + }); + assertThat(first.familyStates()) + .filteredOn( + state -> + state.evidenceKind() + == EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind + .EMPTY_ONLY_OWNER_PROVIDER) + .hasSize(14); + assertThat(first.familyStates()) + .filteredOn( + state -> + state.evidenceKind() + == EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS) + .hasSize(9); + assertThat(first.localTenantKey()).isPositive(); + assertThat(first.localVersionKey()).isPositive().isNotEqualTo(first.localTenantKey()); + assertThat(first.authorizationBindingBytes()) + .containsExactly(inputs.authorizationBinding().canonicalBytes()); + assertThat(first.selectedSourceBytes()) + .containsExactly(inputs.sourceContent().canonicalBytes()); + assertThat(first.worldClosureBytes()) + .containsExactly(inputs.worldInventoryReadEvidence().inventory().canonicalBytes()); + + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_association")) + .isEqualTo(1L); + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_family_state")) + .isEqualTo(23L); + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_receipt")).isEqualTo(1L); + for (String table : EMPTY_ONLY_TABLES) { + assertThat(rowCount("SELECT COUNT(*) FROM " + table)).as(table).isEqualTo(1L); + } + assertThat( + repository + .read(first.targetNamespace(), first.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(first.canonicalBytes()); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO items (name, tenant_id, version_id) VALUES ('blocked', ?, ?)", + first.localTenantKey(), + first.localVersionKey())) + .isInstanceOf(DataAccessException.class); + dsl.execute( + "INSERT INTO items (name, tenant_id, version_id) VALUES ('unassociated', 81001, 81002)"); + assertThat(rowCount("SELECT COUNT(*) FROM items WHERE tenant_id = 81001")).isEqualTo(1L); + + var retry = + EntityEmptySelectedSourceIntakePostgresFixture.withFreshWorldReadCorrelation(fixture); + assertThat(retry.worldEvidence().request().readRequestId()) + .isNotEqualTo(fixture.worldEvidence().request().readRequestId()); + EntityEmptySelectedSourceIntakeReceipt replay = + repository.retainFresh(retry.inputs(), requestDigest(retry)); + assertThat(replay.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(replay.worldReadRequestId()).isEqualTo(first.worldReadRequestId()); + + var changed = EntityEmptySelectedSourceIntakePostgresFixture.create("2"); + assertThatThrownBy(() -> repository.retainFresh(changed.inputs(), requestDigest(changed))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("different selected evidence"); + assertThat( + repository + .read(first.targetNamespace(), first.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(first.canonicalBytes()); + } + + @Test + void existingGlobalEntityRowsAndReferencesDenyFreshGenesisAndRollBackOwnerRecords() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + dsl.execute("INSERT INTO items (name, tenant_id, version_id) VALUES ('legacy', 72001, 72002)"); + + assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not freshly empty"); + assertNoCanonicalOwnerRecords(); + } + + @Test + void retainedAuditReferenceWithoutAnItemDeniesFreshGenesis() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + dsl.execute( + "INSERT INTO item_transfer_audits (tenant_id, item_id, quantity, verb, correlation_key, " + + "source_holder_kind, destination_holder_kind) " + + "VALUES (73001, 999999, 1, 'MOVE', 'retained-audit', 'UNKNOWN', 'UNKNOWN')"); + + assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not freshly empty"); + assertNoCanonicalOwnerRecords(); + } + + @Test + void providerWriteFailureRollsBackAssociationKeysAndAllTypedStates() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + dsl.execute( + "ALTER TABLE entity_empty_source_archetype_roots " + + "ADD CONSTRAINT test_force_empty_provider_failure CHECK (FALSE)"); + + assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture))) + .isInstanceOf(DataAccessException.class); + assertNoCanonicalOwnerRecords(); + } + + @Test + void absentEmptyOnlyProviderFailsClosedBeforeAnyAssociationIsCommitted() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + dsl.execute("DROP TABLE entity_empty_source_archetype_roots"); + + assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture))) + .isInstanceOf(DataAccessException.class); + assertNoCanonicalOwnerRecords("entity_empty_source_archetype_roots"); + } + + @Test + void providerConstraintsAndImmutableReadbackRejectUnknownNonemptyOrChangedState() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + String table = "entity_empty_source_archetype_roots"; + + dsl.execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); + try { + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + table + " SET row_count = 1 WHERE target_namespace = ?", + receipt.targetNamespace())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + table + " SET owner_state = 'UNKNOWN' WHERE target_namespace = ?", + receipt.targetNamespace())) + .isInstanceOf(DataAccessException.class); + dsl.execute( + "DELETE FROM " + table + " WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()); + } finally { + dsl.execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); + } + assertThatThrownBy(() -> repository.read(receipt.targetNamespace(), receipt.intakeRequestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("provider readback is missing or differs"); + } + + private String requestDigest(EntityEmptySelectedSourceIntakePostgresFixture.Fixture fixture) { + return EntityEmptySelectedSourceIntakeReceipt.requestDigest( + fixture.authorization().targetNamespace(), + fixture.authorization(), + fixture.freezeEvidence()); + } + + private long rowCount(String sql) { + var row = Objects.requireNonNull(dsl.fetchOne(sql), "count query returned no row"); + return Objects.requireNonNull(row.get(0, Long.class), "count query returned no value"); + } + + private void assertNoCanonicalOwnerRecords(String... unavailableProviderTables) { + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_association")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_family_state")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_receipt")).isZero(); + assertThat( + rowCount( + "SELECT COUNT(*) FROM entity_empty_source_numeric_key_reservation " + + "WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE'")) + .isZero(); + for (String table : EMPTY_ONLY_TABLES) { + if (List.of(unavailableProviderTables).contains(table)) continue; + assertThat(rowCount("SELECT COUNT(*) FROM " + table)).as(table).isZero(); + } + } + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + String baseUrl = postgres.getJdbcUrl(); + dataSource.setUrl( + schemaName == null + ? baseUrl + : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java new file mode 100644 index 0000000000..725aced55d --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import org.junit.jupiter.api.Test; + +class EntityEmptySelectedSourceIntakeRepositoryTest { + @Test + void recognizesAllFourteenExplicitFreshEmptyOwnerProviders() { + for (String family : + java.util.List.of( + "ACTOR_BODY_LAYOUT_ASSIGNMENTS", + "ARCHETYPE_ASSIGNMENTS", + "ARCHETYPE_CONSTRAINTS", + "ARCHETYPE_ROOTS", + "BALANCE_CURVE_ATTACHMENTS", + "BALANCE_CURVE_ROOTS", + "EQUIPMENT_ATTACHMENT_RULES", + "EQUIPMENT_CAPABILITIES", + "EQUIPMENT_COMPATIBILITY_RULES", + "EQUIPMENT_OCCUPANCY_RULES", + "INBOUND_LOOT_BINDINGS", + "LOOT_ITEM_MAPPINGS", + "LOOT_TABLE_ROOTS", + "OTHER_ACTOR_TEMPLATE_ROOTS")) { + EntityEmptySelectedSourceIntakeRepository.requireReadableProvider(family); + } + } + + @Test + void recognizesAllNineExistingV1CensusFamilies() { + for (String family : + java.util.List.of( + "ITEM_TEMPLATE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "CRAFTING_RECIPE_ROOTS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_INGREDIENT_BINDINGS", + "EQUIPMENT_SLOT_ROOTS", + "EQUIPMENT_SLOT_GROUPS", + "BODY_LAYOUT_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS")) { + EntityEmptySelectedSourceIntakeRepository.requireReadableProvider(family); + } + } + + @Test + void rejectsFamiliesWithNoDeclaredOwnerProvider() { + assertThatThrownBy( + () -> EntityEmptySelectedSourceIntakeRepository.requireReadableProvider("UNKNOWN")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No readable persisted Entity source provider"); + } + + @Test + void anEmptyFamilyStateCannotCarryRowsOrReferences() { + assertThrows( + IllegalArgumentException.class, + () -> + new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( + "ITEM_TEMPLATE_ROOTS", + EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, + EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS, + 0L, + 0L, + 0L, + 0L, + 1L)); + } + + @Test + void rejectsEvidenceKindThatDoesNotMatchFamilyProvider() { + assertThatThrownBy( + () -> + new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( + "ARCHETYPE_ROOTS", + EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, + EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS, + 0L, + 0L, + 0L, + 0L, + 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("evidence kind differs"); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java new file mode 100644 index 0000000000..8e95b351e4 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class EntityEmptySelectedSourceIntakeServiceTest { + @Test + void rejectsCallerSelectedNamespaceBeforeReceiptReplayOrRemoteReads() { + DSLContext dsl = mock(DSLContext.class); + SelectedOwnerIntakeAuthorizationReadClient authorizationClient = + mock(SelectedOwnerIntakeAuthorizationReadClient.class); + SelectedOwnerWorldInventoryReadClient worldClient = + mock(SelectedOwnerWorldInventoryReadClient.class); + var service = + new EntityEmptySelectedSourceIntakeService( + "configured", + new EntityEmptySelectedSourceIntakeRepository(dsl), + authorizationClient, + worldClient); + + assertThatThrownBy(() -> service.retain("attacker-selected", null, null)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("configured Entity owner namespace"); + + verifyNoInteractions(dsl, authorizationClient, worldClient); + } + + @Test + void rejectsInvalidConfiguredNamespaceAtConstruction() { + DSLContext dsl = mock(DSLContext.class); + assertThatThrownBy( + () -> + new EntityEmptySelectedSourceIntakeService( + "Invalid_Namespace", + new EntityEmptySelectedSourceIntakeRepository(dsl), + mock(SelectedOwnerIntakeAuthorizationReadClient.class), + mock(SelectedOwnerWorldInventoryReadClient.class))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Configured Entity namespace"); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java new file mode 100644 index 0000000000..ee4ed499a6 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java @@ -0,0 +1,228 @@ +package unit.net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeService; +import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedSourceIntakeCommandGrpcService; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +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.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mocked owner tests verify gates and delegation, not native producer or physical census proof. */ +class EntitySelectedSourceIntakeCommandGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static Fixture fixture; + + @BeforeAll + static void createSyntheticEntityInputs() { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + } + + @BeforeEach + @AfterEach + void clearContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatedGameDesignGetsExactRetainedReceiptFromOwner() { + var owner = mock(EntityEmptySelectedSourceIntakeService.class); + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var request = + EntitySelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, fixture.authorization(), freeze); + when(owner.retain( + eq(NAMESPACE), + any(SelectedOwnerIntakeAuthorizationBinding.class), + any(WorldSelectedDraftPublicationFreezeEvidence.class))) + .thenReturn(fixture.receipt()); + var service = new EntitySelectedSourceIntakeCommandGrpcService(owner, NAMESPACE); + var observedResponse = new AtomicReference(); + var observer = new CapturingObserver(observedResponse); + var accountContext = gameDesignPeer(NAMESPACE); + var previous = accountContext.attach(); + try { + service.retainSelectedEntitySource( + EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request), observer); + } finally { + accountContext.detach(previous); + } + + assertThat(observer.failure()).isNull(); + assertThat(observedResponse.get()).isNotNull(); + assertThat(observedResponse.get().getRequest()) + .isEqualTo(EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request)); + var evidence = + EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(request, observedResponse.get()); + assertThat(evidence.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes()); + var authorizationArgument = + ArgumentCaptor.forClass(SelectedOwnerIntakeAuthorizationBinding.class); + var freezeArgument = ArgumentCaptor.forClass(WorldSelectedDraftPublicationFreezeEvidence.class); + verify(owner).retain(eq(NAMESPACE), authorizationArgument.capture(), freezeArgument.capture()); + assertThat(authorizationArgument.getValue().canonicalBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + assertThat( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest( + freezeArgument.getValue().request())) + .isEqualTo(WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())); + assertThat( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse( + freezeArgument.getValue().acknowledgement())) + .isEqualTo( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())); + } + + @Test + void rejectsMissingWrongPeerAndWrongNamespaceBeforeDecodeOrOwnerInvocation() { + var owner = mock(EntityEmptySelectedSourceIntakeService.class); + var service = new EntitySelectedSourceIntakeCommandGrpcService(owner, NAMESPACE); + + var missingPeer = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource( + RetainSelectedEntitySourceRequest.getDefaultInstance(), missingPeer); + assertCode(missingPeer.failure(), Status.Code.UNAUTHENTICATED); + + var wrongPeer = gameDesignPeer("other"); + var previous = wrongPeer.attach(); + try { + var denied = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource( + RetainSelectedEntitySourceRequest.getDefaultInstance(), denied); + assertCode(denied.failure(), Status.Code.PERMISSION_DENIED); + } finally { + wrongPeer.detach(previous); + } + + var goodPeer = gameDesignPeer(NAMESPACE); + previous = goodPeer.attach(); + try { + var mismatchedTarget = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource( + RetainSelectedEntitySourceRequest.newBuilder().setTargetNamespace("other").build(), + mismatchedTarget); + assertCode(mismatchedTarget.failure(), Status.Code.PERMISSION_DENIED); + } finally { + goodPeer.detach(previous); + } + verifyNoInteractions(owner); + } + + @Test + void rejectsEndUserSelectedOrderAndAmbientSqlBeforeMalformedEvidenceDecode() { + var owner = mock(EntityEmptySelectedSourceIntakeService.class); + var service = new EntitySelectedSourceIntakeCommandGrpcService(owner, NAMESPACE); + var peer = gameDesignPeer(NAMESPACE); + var malformed = RetainSelectedEntitySourceRequest.getDefaultInstance(); + var previous = peer.attach(); + try { + SessionContext.setContext("101", List.of(), Map.of()); + var endUser = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource(malformed, endUser); + assertCode(endUser.failure(), Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + var selectedOrder = + Context.current() + .withValue( + AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, + AccountSelectedPublicationOrderCredentials.Credential.of( + "synthetic-selected-order-credential")); + var selectedOrderPrevious = selectedOrder.attach(); + try { + var denied = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource(malformed, denied); + assertCode(denied.failure(), Status.Code.PERMISSION_DENIED); + } finally { + selectedOrder.detach(selectedOrderPrevious); + } + + var malformedEvidence = + RetainSelectedEntitySourceRequest.newBuilder().setTargetNamespace(NAMESPACE).build(); + TransactionSynchronizationManager.setActualTransactionActive(true); + var activeSql = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource(malformedEvidence, activeSql); + assertCode(activeSql.failure(), Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clear(); + + TransactionSynchronizationManager.initSynchronization(); + var synchronizedSql = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource(malformedEvidence, synchronizedSql); + assertCode(synchronizedSql.failure(), Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clear(); + + var invalidEvidence = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource(malformedEvidence, invalidEvidence); + assertCode(invalidEvidence.failure(), Status.Code.INVALID_ARGUMENT); + } finally { + peer.detach(previous); + } + verifyNoInteractions(owner); + } + + private static void assertCode(Throwable error, Status.Code expected) { + assertThat(error).isNotNull(); + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(expected); + } + + private static Context gameDesignPeer(String namespace) { + String uri = "spiffe://firemud/ns/" + namespace + "/sa/game-design-service"; + return Context.ROOT.withValue( + GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, "game-design-service")); + } + + private static final class CapturingObserver + implements StreamObserver { + private final AtomicReference response; + private final AtomicReference failure = new AtomicReference<>(); + + private CapturingObserver(AtomicReference response) { + this.response = response; + } + + @Override + public void onNext(RetainSelectedEntitySourceResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + failure.set(error); + } + + @Override + public void onCompleted() {} + + Throwable failure() { + return failure.get(); + } + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java new file mode 100644 index 0000000000..62602d2c15 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java @@ -0,0 +1,295 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +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.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic receipt/peer tests do not establish Entity producer or database proof. */ +class EntitySelectedSourceIntakeTerminalReadServiceTest { + private static final String NAMESPACE = "test"; + private static Fixture fixture; + + @BeforeAll + static void createSyntheticReceiptFixture() { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + } + + @BeforeEach + @AfterEach + void clearContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactRetriesReadOnlyTheCommittedReceiptAndUseDistinctReadCorrelations() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var binding = fixture.authorization(); + when(repository.read(NAMESPACE, binding.intakeRequestId())) + .thenReturn(Optional.of(fixture.receipt())); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(NAMESPACE); + var previous = accountContext.attach(); + try { + var first = service.read(request(binding)); + var retry = service.read(request(binding)); + + assertThat(first.receipt()).isSameAs(fixture.receipt()); + assertThat(retry.receipt()).isSameAs(fixture.receipt()); + assertThat(first.request().readRequestId()).isNotEqualTo(retry.request().readRequestId()); + assertThat(first.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes()); + verify(repository, times(2)).read(NAMESPACE, binding.intakeRequestId()); + } finally { + accountContext.detach(previous); + } + } + + @Test + void grpcReturnsTheExactFullReceiptWithoutRemintingIt() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var binding = fixture.authorization(); + when(repository.read(NAMESPACE, binding.intakeRequestId())) + .thenReturn(Optional.of(fixture.receipt())); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var grpc = new EntitySelectedSourceIntakeTerminalReadGrpcService(service); + var request = request(binding); + var observedResponse = new AtomicReference(); + var observedError = new AtomicReference(); + var observer = responseObserver(observedResponse, observedError); + var accountContext = accountPeer(NAMESPACE); + var previous = accountContext.attach(); + try { + grpc.readSelectedSourceIntakeTerminal( + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request), observer); + } finally { + accountContext.detach(previous); + } + + assertThat(observedError.get()).isNull(); + var response = observedResponse.get(); + assertThat(response).isNotNull(); + assertThat(response.getRequest()) + .isEqualTo(EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request)); + var decoded = EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); + assertThat(decoded.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes()); + assertThat(decoded.receipt().authorizationBindingBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + verify(repository).read(NAMESPACE, binding.intakeRequestId()); + } + + @Test + void absentReceiptIsNotConvertedToAnAbortOrAnyTerminalEvidence() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var binding = fixture.authorization(); + when(repository.read(NAMESPACE, binding.intakeRequestId())).thenReturn(Optional.empty()); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(NAMESPACE); + var previous = accountContext.attach(); + try { + assertStatus(() -> service.read(request(binding)), Status.Code.NOT_FOUND); + } finally { + accountContext.detach(previous); + } + verify(repository).read(NAMESPACE, binding.intakeRequestId()); + } + + @Test + void changedCompleteOriginalAuthorizationIsAlreadyExistsAndCorruptReadbackIsDataLoss() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var changedAuthorization = + EntitySelectedSourceIntakeTerminalReadFixtures.create().authorization(); + assertThat(changedAuthorization.intakeRequestId()) + .isEqualTo(fixture.authorization().intakeRequestId()); + assertThat(changedAuthorization.canonicalBytes()) + .isNotEqualTo(fixture.authorization().canonicalBytes()); + when(repository.read(NAMESPACE, fixture.authorization().intakeRequestId())) + .thenReturn(Optional.of(fixture.receipt())); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(NAMESPACE); + var previous = accountContext.attach(); + try { + assertStatus(() -> service.read(request(changedAuthorization)), Status.Code.ALREADY_EXISTS); + + when(repository.read(NAMESPACE, fixture.authorization().intakeRequestId())) + .thenThrow(new IllegalArgumentException("corrupt stored Entity receipt")); + assertStatus(() -> service.read(request(fixture.authorization())), Status.Code.DATA_LOSS); + } finally { + accountContext.detach(previous); + } + } + + @Test + void rejectsWrongPeerNamespaceOwnerEndUserAndAmbientSqlBeforeRepositoryRead() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var request = request(fixture.authorization()); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + + assertStatus(() -> service.read(request), Status.Code.UNAUTHENTICATED); + + var wrongPeer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", + NAMESPACE, + "game-design-service")); + var previous = wrongPeer.attach(); + try { + assertStatus(() -> service.read(request), Status.Code.PERMISSION_DENIED); + } finally { + wrongPeer.detach(previous); + } + + var otherNamespaceService = + new EntityEmptySelectedSourceIntakeTerminalReadService(repository, "other"); + var otherAccount = accountPeer("other"); + previous = otherAccount.attach(); + try { + assertStatus(() -> otherNamespaceService.read(request), Status.Code.PERMISSION_DENIED); + } finally { + otherAccount.detach(previous); + } + + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + NAMESPACE, fixture.wrongOwnerAuthorization())) + .isInstanceOf(IllegalArgumentException.class); + + var accountContext = accountPeer(NAMESPACE); + previous = accountContext.attach(); + try { + SessionContext.setContext("101", java.util.List.of(), java.util.Map.of()); + assertStatus(() -> service.read(request), Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus(() -> service.read(request), Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertStatus(() -> service.read(request), Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clearSynchronization(); + } finally { + accountContext.detach(previous); + } + verifyNoInteractions(repository); + } + + @Test + void grpcAuthenticatesBeforeMalformedRequestDecodeOrRepositoryLookup() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var grpc = new EntitySelectedSourceIntakeTerminalReadGrpcService(service); + + var unauthenticatedError = invokeMalformed(grpc, null); + assertThat(Status.fromThrowable(unauthenticatedError).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + + var wrongPeer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", + NAMESPACE, + "game-design-service")); + var previous = wrongPeer.attach(); + try { + assertThat(Status.fromThrowable(invokeMalformed(grpc, null)).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + wrongPeer.detach(previous); + } + + var accountContext = accountPeer(NAMESPACE); + previous = accountContext.attach(); + try { + assertThat( + Status.fromThrowable( + invokeMalformed( + grpc, ReadSelectedSourceIntakeTerminalRequest.getDefaultInstance())) + .getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } finally { + accountContext.detach(previous); + } + verifyNoInteractions(repository); + } + + private static EntitySelectedSourceIntakeTerminalReadEvidence.Request request( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding + binding) { + return EntitySelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, binding); + } + + private static void assertStatus(Runnable action, Status.Code expected) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static Context accountPeer(String namespace) { + String uri = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + return Context.ROOT.withValue( + GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, "account-service")); + } + + private static Throwable invokeMalformed( + EntitySelectedSourceIntakeTerminalReadGrpcService grpc, + ReadSelectedSourceIntakeTerminalRequest request) { + var observedResponse = new AtomicReference(); + var observedError = new AtomicReference(); + grpc.readSelectedSourceIntakeTerminal( + request == null ? ReadSelectedSourceIntakeTerminalRequest.getDefaultInstance() : request, + responseObserver(observedResponse, observedError)); + assertThat(observedResponse.get()).isNull(); + assertThat(observedError.get()).isNotNull(); + return observedError.get(); + } + + private static StreamObserver responseObserver( + AtomicReference response, + AtomicReference error) { + return new StreamObserver<>() { + @Override + public void onNext(ReadSelectedSourceIntakeTerminalResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() {} + }; + } +} diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index d6d1812b60..6ba6d1c5f4 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -42,6 +42,14 @@ dependencies { ) ) ) + integrationTestImplementation( + project( + mapOf( + "path" to ":entity-management-service", + "configuration" to "entityClassesProof" + ) + ) + ) integrationTestImplementation("io.grpc:grpc-util:${libs.versions.grpc.get()}") compileOnly(libs.spotbugs.annotations) testCompileOnly(libs.spotbugs.annotations) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 6657131c44..b766bcd698 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -3,7 +3,6 @@ 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.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -22,6 +21,7 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.io.IOException; import java.net.InetSocketAddress; +import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -36,6 +36,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; @@ -82,6 +83,9 @@ import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.gamedesign.AssetSource; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; @@ -126,11 +130,18 @@ import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; import net.firedevops.firemud.common.security.PublicationReadGuard; import net.firedevops.firemud.common.security.sourceintake.GrpcAutomationSelectedSourceIntakeCommandClient; +import net.firedevops.firemud.common.security.sourceintake.GrpcEntitySelectedSourceIntakeCommandClient; +import net.firedevops.firemud.common.security.sourceintake.GrpcEntitySelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.security.sourceintake.GrpcSelectedOwnerIntakeAuthorizationProducerClient; import net.firedevops.firemud.common.security.sourceintake.GrpcSelectedOwnerIntakeSettlementClient; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeService; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeTerminalReadService; +import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedSourceIntakeCommandGrpcService; +import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedSourceIntakeTerminalReadGrpcService; import net.firedevops.firemud.gamedesign.client.GameLogicClient; import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; @@ -256,6 +267,7 @@ import org.jooq.impl.DSL; import org.jooq.impl.DataSourceConnectionProvider; import org.jooq.impl.DefaultConfiguration; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mapstruct.factory.Mappers; @@ -269,16 +281,22 @@ import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import software.amazon.awssdk.core.ResponseBytes; -import software.amazon.awssdk.core.sync.RequestBody; +import org.testcontainers.utility.DockerImageName; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.interceptor.ExecutionAttributes; +import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; +import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.S3Configuration; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.GetObjectRequest; -import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.PutObjectRequest; -import software.amazon.awssdk.services.s3.model.PutObjectResponse; -import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.S3Object; import tools.jackson.databind.ObjectMapper; /** @@ -296,21 +314,58 @@ * empty-source receipt owner, and Account terminal settlement. Its positive Account authorization * command creates a fresh reservation through the native producer. Automation retention and Account * settlement each traverse their native command receivers over loopback mTLS. The earlier - * disclosure/abort setup uses stipulated incoming Game Design peer contexts and is not the positive - * authorization operation. Entity retention and Entity/Automation publication participant digests, - * in-memory S3 and the StartSession Account projection remain test doubles. The complete + * disclosure/abort setup uses stipulated incoming Game Design peer contexts and is not either + * positive authorization operation. Entity retention also traverses the native Account, Game + * Design, Entity, World and settlement boundaries over loopback mTLS, with an isolated Entity + * PostgreSQL schema and migration path. Entity/Automation publication participant digests and the + * StartSession Account projection remain test doubles. MinIO object-store I/O is real. The complete * launch-binding case wires the actual Game Design handler and World Management mTLS client on this * fixture's loopback server to the actual owner implementation in an explicitly established * read-only repeatable-read snapshot; unrelated handler dependencies are isolated. This fixture - * does not provide production-mounted certificates or full application server wiring, complete - * owner census or production ingress, Account-projection-backed StartSession admission, a complete - * four-owner authenticated release, runtime launch, activation or registration. + * does not provide production-mounted certificates or full application server wiring, production + * ingress, Account-projection-backed StartSession admission, a complete four-owner authenticated + * release, runtime launch, activation or registration. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class GenuineSelectedPublicationExportPostgresIntegrationTest { private static final String NAMESPACE = "firemud"; + private static final String MINIO_IMAGE = + "ghcr.io/benhook1013/minio-server@sha256:a091800eb1c700ea662634c9ad5d9e4cf6980a1f61027a9b80aef0163e66c22a"; + private static final String MINIO_ACCESS_KEY = "firemud-test"; + private static final String MINIO_SECRET_KEY = "firemud-test-secret"; + private static final String MINIO_BUCKET = "genuine-selected-export-test"; + private static final Region MINIO_REGION = Region.US_EAST_1; private static final Network NETWORK = Network.newNetwork(); + private static final Map ENTITY_EMPTY_ONLY_PROVIDER_TABLES = + Map.ofEntries( + Map.entry( + "ACTOR_BODY_LAYOUT_ASSIGNMENTS", "entity_empty_source_actor_body_layout_assignments"), + Map.entry("ARCHETYPE_ASSIGNMENTS", "entity_empty_source_archetype_assignments"), + Map.entry("ARCHETYPE_CONSTRAINTS", "entity_empty_source_archetype_constraints"), + Map.entry("ARCHETYPE_ROOTS", "entity_empty_source_archetype_roots"), + Map.entry("BALANCE_CURVE_ATTACHMENTS", "entity_empty_source_balance_curve_attachments"), + Map.entry("BALANCE_CURVE_ROOTS", "entity_empty_source_balance_curve_roots"), + Map.entry("EQUIPMENT_ATTACHMENT_RULES", "entity_empty_source_equipment_attachment_rules"), + Map.entry("EQUIPMENT_CAPABILITIES", "entity_empty_source_equipment_capabilities"), + Map.entry( + "EQUIPMENT_COMPATIBILITY_RULES", "entity_empty_source_equipment_compatibility_rules"), + Map.entry("EQUIPMENT_OCCUPANCY_RULES", "entity_empty_source_equipment_occupancy_rules"), + Map.entry("INBOUND_LOOT_BINDINGS", "entity_empty_source_inbound_loot_bindings"), + Map.entry("LOOT_ITEM_MAPPINGS", "entity_empty_source_loot_item_mappings"), + Map.entry("LOOT_TABLE_ROOTS", "entity_empty_source_loot_table_roots"), + Map.entry( + "OTHER_ACTOR_TEMPLATE_ROOTS", "entity_empty_source_other_actor_template_roots")); + + // Keep this digest aligned with the minio service in docker/docker-compose.yml. + @Container + private static final GenericContainer MINIO = + new GenericContainer<>(DockerImageName.parse(MINIO_IMAGE)) + .withEnv("MINIO_ROOT_USER", MINIO_ACCESS_KEY) + .withEnv("MINIO_ROOT_PASSWORD", MINIO_SECRET_KEY) + .withCommand("server", "/data") + .withExposedPorts(9000) + .waitingFor(Wait.forHttp("/minio/health/live").forPort(9000)); @Container private static final PostgreSQLContainer GAME_DESIGN_POSTGRES = @@ -328,6 +383,10 @@ class GenuineSelectedPublicationExportPostgresIntegrationTest { private static final PostgreSQLContainer GAME_LOGIC_POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container + private static final PostgreSQLContainer ENTITY_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container private static final GenericContainer REDIS = new GenericContainer<>(TestContainerImages.redis()) @@ -366,18 +425,30 @@ class GenuineSelectedPublicationExportPostgresIntegrationTest { @TempDir Path temporary; + private MinioConditionalObjectStore objectStore; + + @AfterEach + void closeMinioClient() { + if (objectStore != null) { + objectStore.close(); + objectStore = null; + } + } + @Test void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Exception { var gd = gameDesignStore(); var world = serviceStore(WORLD_POSTGRES, "world-management"); var gameLogic = serviceStore(GAME_LOGIC_POSTGRES, "game-logic"); var automation = serviceStore(GAME_LOGIC_POSTGRES, "automation-scripting"); + var entity = serviceStore(ENTITY_POSTGRES, "entity-management"); var pki = new TestPki(temporary.resolve("pki")); var gdHandlers = new MutableHandlerRegistry(); var worldHandlers = new MutableHandlerRegistry(); var accountHandlers = new MutableHandlerRegistry(); var gameLogicHandlers = new MutableHandlerRegistry(); var automationHandlers = new MutableHandlerRegistry(); + var entityHandlers = new MutableHandlerRegistry(); Map startSessionProjections = new ConcurrentHashMap<>(); Server gdServer = startServer(pki, "game-design-service", gdHandlers); @@ -385,6 +456,7 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex Server accountServer = startServer(pki, "account-service", accountHandlers); Server gameLogicServer = startServer(pki, "game-logic-service", gameLogicHandlers); Server automationServer = startServer(pki, "automation-scripting-service", automationHandlers); + Server entityServer = startServer(pki, "entity-management-service", entityHandlers); try (var account = new AccountControlUiOriginalOrderFixture( ACCOUNT_POSTGRES.getJdbcUrl(), @@ -400,14 +472,21 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex endpoints.setWorldManagementService(loopback(worldServer)); endpoints.setGameLogicService(loopback(gameLogicServer)); endpoints.setAutomationScriptingService(loopback(automationServer)); + endpoints.setEntityManagementService(loopback(entityServer)); var channels = new GrpcChannelFactory(); var automationIntakeRepository = new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); + var entityIntakeRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); register( automationHandlers, new AutomationSelectedSourceIntakeTerminalReadGrpcService( new AutomationEmptySelectedSourceIntakeTerminalReadService( automationIntakeRepository, NAMESPACE))); + register( + entityHandlers, + new EntitySelectedSourceIntakeTerminalReadGrpcService( + new EntityEmptySelectedSourceIntakeTerminalReadService( + entityIntakeRepository, NAMESPACE))); var sourceRepository = new GameAuthoredWorldSourceRepository(gd.dsl()); register( @@ -486,6 +565,21 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var wrongWorkloadAutomationSelectedSourceCommandClient = new GrpcAutomationSelectedSourceIntakeCommandClient( endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var entityToAccountHeld = + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, pki.client("entity-management-service"), channels, NAMESPACE); + var entityToWorldInventory = + new WorldSelectedOwnerInventoryGrpcClient( + endpoints, pki.client("entity-management-service"), channels, NAMESPACE); + var accountToEntityTerminal = + new GrpcEntitySelectedSourceIntakeTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var entitySelectedSourceCommandClient = + new GrpcEntitySelectedSourceIntakeCommandClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var wrongWorkloadEntitySelectedSourceCommandClient = + new GrpcEntitySelectedSourceIntakeCommandClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); var selectedOwnerSettlementClient = new GrpcSelectedOwnerIntakeSettlementClient( endpoints, pki.client("game-design-service"), channels, NAMESPACE); @@ -838,6 +932,11 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex accountToAutomationTerminal.init(); automationSelectedSourceCommandClient.init(); wrongWorkloadAutomationSelectedSourceCommandClient.init(); + entityToAccountHeld.init(); + entityToWorldInventory.init(); + accountToEntityTerminal.init(); + entitySelectedSourceCommandClient.init(); + wrongWorkloadEntitySelectedSourceCommandClient.init(); selectedOwnerSettlementClient.init(); wrongWorkloadSelectedOwnerSettlementClient.init(); glToAccountHeld.init(); @@ -859,10 +958,17 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex register( automationHandlers, new AutomationSelectedSourceIntakeCommandGrpcService(automationIntakeOwner, NAMESPACE)); + var entityIntakeOwner = + new EntityEmptySelectedSourceIntakeService( + NAMESPACE, entityIntakeRepository, entityToAccountHeld, entityToWorldInventory); + register( + entityHandlers, + new EntitySelectedSourceIntakeCommandGrpcService(entityIntakeOwner, NAMESPACE)); var selectedOwnerSettlementOwner = new AccountSelectedOwnerIntakeSettlementService( accountSelectedOwnerSourceRepository, accountToAutomationTerminal, + accountToEntityTerminal, accountAccess.sources().manager, NAMESPACE); register( @@ -1702,6 +1808,255 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(automationSourceRowCounts(automation.dsl())) .isEqualTo(automationRowsAfterRetention); + UUID freshEntityIntakeRequest = UUID.randomUUID(); + assertThat(freshEntityIntakeRequest) + .isNotEqualTo(entitySourceReservation.intakeRequestId()); + var entityAuthorizationRequest = + SelectedOwnerIntakeAuthorizationProducerEvidence.Request.create( + NAMESPACE, freshEntityIntakeRequest, Owner.ENTITY_MANAGEMENT, selectedCommit); + var entityAuthorizationResult = + gdToAccountSelectedOwnerAuthorizationProducer.authorize( + entityAuthorizationRequest, accountAccess.compact()); + var entityAuthorization = entityAuthorizationResult.binding(); + var freshEntityScope = entityAuthorization.content().scope(); + var freshEntityReservationSources = + selectedOwnerReservationSourceRows(accountSourceDsl, freshEntityScope.operationId()); + assertThat(entityAuthorizationResult.request()).isEqualTo(entityAuthorizationRequest); + assertThat(entityAuthorizationResult.canonicalBindingBytes()) + .containsExactly(entityAuthorization.canonicalBytes()); + assertThat(entityAuthorizationResult.digest()).isEqualTo(entityAuthorization.digest()); + assertThat(entityAuthorization.owner()).isEqualTo(Owner.ENTITY_MANAGEMENT); + assertThat(entityAuthorization.intakeRequestId()).isEqualTo(freshEntityIntakeRequest); + assertThat(entityAuthorization.operationId()) + .isEqualTo(freshEntityScope.operationId()) + .isNotEqualTo(entitySourceReservation.operationId()); + assertThat(entityAuthorization.fenceId()) + .isEqualTo(freshEntityScope.fenceId()) + .isNotEqualTo(entitySourceReservation.fenceId()); + assertThat(freshEntityScope.owner()).isEqualTo(Owner.ENTITY_MANAGEMENT); + assertThat(freshEntityScope.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(freshEntityScope.intakeRequestId()).isEqualTo(freshEntityIntakeRequest); + assertThat(freshEntityScope.selected().canonicalBytes()) + .containsExactly(selectedCommit.canonicalBytes()); + assertThat(entityAuthorization.content().snapshotBytes("COMMAND")) + .containsExactly(selectedSources.command().canonicalBytes()); + assertThat(entityAuthorization.content().snapshotBytes("REALM_POLICY")) + .containsExactly(selectedSources.policy().canonicalBytes()); + assertThat(entityAuthorization.content().snapshotBytes("ASSET")) + .containsExactly(selectedSources.asset().canonicalBytes()); + assertThat(entityAuthorization.content().snapshotBytes("GAMEPLAY_RULE")) + .containsExactly(selectedSources.gameplay().canonicalBytes()); + assertThat(entityAuthorization.content().snapshotBytes("BRANDING")) + .containsExactly(selectedSources.branding().orElseThrow().canonicalBytes()); + assertThat(entityAuthorization.content().snapshotBytes("TEMPLATE_CONFIG")) + .containsExactly(selectedSources.templateConfig().orElseThrow().canonicalBytes()); + assertThat(entityAuthorization.content().digest()) + .isEqualTo( + DraftAuthorizationFenceBinding.digest( + entityAuthorization.content().canonicalBytes())); + assertThat(entityAuthorization.selected().canonicalBytes()) + .containsExactly(selectedCommit.canonicalBytes()); + assertThat(accountSelectedSourceReads).hasValue(2); + assertThat(freshEntityReservationSources) + .containsExactlyElementsOf(expectedAccountSourceEvidence); + assertThat( + accountSourceDsl.fetchOne( + "SELECT operation_id FROM account_selected_owner_intake_authorizations " + + "WHERE operation_id = ?", + freshEntityScope.operationId())) + .isNotNull(); + assertThat(account.recoverSelectedOwnerSourceRead(freshEntityScope, NAMESPACE).state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.FINALIZED); + assertThat( + account.recoverSelectedOwnerSourceRead(entitySourceReservation, NAMESPACE).state()) + .isEqualTo(AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED); + assertThat( + selectedOwnerReservationSourceRows( + accountSourceDsl, entitySourceReservation.operationId())) + .containsExactlyElementsOf(entityReservationSourcesBeforeAbort); + + var entityRowsBeforeRetention = entitySourceRowCounts(entity.dsl()); + assertThat(entityRowsBeforeRetention) + .allSatisfy((table, count) -> assertThat(count).as(table).isZero()); + var entityRetainRequest = + EntitySelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, entityAuthorization, actualFreeze); + assertThatThrownBy( + () -> wrongWorkloadEntitySelectedSourceCommandClient.retain(entityRetainRequest)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + assertThat(entitySourceRowCounts(entity.dsl())).isEqualTo(entityRowsBeforeRetention); + + var entityRetainEvidence = entitySelectedSourceCommandClient.retain(entityRetainRequest); + assertThat(entityRetainEvidence.request()).isEqualTo(entityRetainRequest); + var entityReceipt = entityRetainEvidence.receipt(); + assertThat(entityReceipt.outcome()).isEqualTo("COMMITTED_EMPTY"); + assertThat(entityReceipt.intakeRequestId()).isEqualTo(freshEntityIntakeRequest); + assertThat(entityReceipt.authorizationBindingBytes()) + .containsExactly(entityAuthorization.canonicalBytes()); + assertThat(entityReceipt.authorizationBindingDigest()) + .isEqualTo(entityAuthorization.digest()); + assertThat(entityReceipt.requestDigest()) + .isEqualTo( + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, entityAuthorization, actualFreeze)); + assertThat(entityReceipt.selectedSourceBytes()) + .containsExactly(entityAuthorization.content().canonicalBytes()); + assertThat(entityReceipt.selectedSourceDigest()) + .isEqualTo(entityAuthorization.content().digest()); + var entitySourceRevision = entityReceipt.inputs().ownerSourceInventoryDeclaration(); + assertThat(entityReceipt.sourceRevisionId()).isEqualTo(entitySourceRevision.revisionId()); + assertThat(entityReceipt.sourceRevisionOrder()) + .isEqualTo(entitySourceRevision.revisionOrder()); + assertThat(entityReceipt.selectedSourceRevisionBindingDigest()) + .isEqualTo(entitySourceRevision.sourceBinding().digest()); + assertThat(entitySourceRevision.sourceBinding().canonicalBytes()) + .containsExactly(selectedCommit.canonicalBytes()); + var entityWorldRead = entityReceipt.inputs().worldInventoryReadEvidence(); + assertThat(entityWorldRead.request().authorizationBinding().canonicalBytes()) + .containsExactly(entityAuthorization.canonicalBytes()); + assertThat(entityWorldRead.request().freezeEvidence()).isEqualTo(actualFreeze); + assertThat(entityReceipt.worldReadRequestId()) + .isEqualTo(entityWorldRead.request().readRequestId()); + assertThat(entityReceipt.worldReadRequestBytes()) + .containsExactly( + net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadGrpcCodec + .toRequest(entityWorldRead.request()) + .toByteArray()); + assertThat(entityReceipt.worldReadRequestDigest()) + .isEqualTo( + DraftAuthorizationFenceBinding.digest(entityReceipt.worldReadRequestBytes())); + assertThat(entityReceipt.worldClosureBytes()) + .containsExactly(entityWorldRead.inventory().canonicalBytes()); + assertThat(entityReceipt.worldClosureDigest()) + .isEqualTo(entityWorldRead.inventory().digest()); + assertThat(entityReceipt.familyStates()).hasSize(23); + assertThat(entityReceipt.familyStates()) + .allSatisfy( + family -> { + assertThat(family.state()) + .isEqualTo(EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY); + assertThat(family.rowCount()).isZero(); + assertThat(family.unqualifiedRowCount()).isZero(); + assertThat(family.retainedRowCount()).isZero(); + assertThat(family.selectedScopeRowCount()).isZero(); + assertThat(family.referenceCount()).isZero(); + }); + var entityRowsAfterRetention = entitySourceRowCounts(entity.dsl()); + var persistedEntityReceipt = + entityIntakeRepository.read(NAMESPACE, freshEntityIntakeRequest).orElseThrow(); + assertThat(persistedEntityReceipt.canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + assertThat(persistedEntityReceipt.receiptDigest()).isEqualTo(entityReceipt.receiptDigest()); + assertPersistedEntityReceipt( + entity.dsl(), persistedEntityReceipt, entityAuthorization, actualFreeze); + + var entityReceiptRetryEvidence = + entitySelectedSourceCommandClient.retain(entityRetainRequest); + assertThat(entityReceiptRetryEvidence.request()).isEqualTo(entityRetainRequest); + assertThat(entityReceiptRetryEvidence.receipt().canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + assertThat(entityReceiptRetryEvidence.receipt().receiptDigest()) + .isEqualTo(entityReceipt.receiptDigest()); + var entityRetainNewCorrelationRequest = + EntitySelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, entityAuthorization, actualFreeze); + assertThat(entityRetainNewCorrelationRequest.transportRequestId()) + .isNotEqualTo(entityRetainRequest.transportRequestId()); + assertThat(entityRetainNewCorrelationRequest.originalIntakeAuthorizationBinding()) + .containsExactly(entityAuthorization.canonicalBytes()); + assertThat(entityRetainNewCorrelationRequest.freezeEvidence()).isEqualTo(actualFreeze); + var entityRetainNewCorrelationEvidence = + entitySelectedSourceCommandClient.retain(entityRetainNewCorrelationRequest); + assertThat(entityRetainNewCorrelationEvidence.request()) + .isEqualTo(entityRetainNewCorrelationRequest); + assertThat(entityRetainNewCorrelationEvidence.receipt().canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + assertThat(entityRetainNewCorrelationEvidence.receipt().receiptDigest()) + .isEqualTo(entityReceipt.receiptDigest()); + assertThat(entitySourceRowCounts(entity.dsl())).isEqualTo(entityRowsAfterRetention); + + var entitySettlementRequest = + SelectedOwnerIntakeSettlementEvidence.Request.create(NAMESPACE, entityAuthorization); + var entitySettlementEvidence = + selectedOwnerSettlementClient.settle(entitySettlementRequest); + assertThat(entitySettlementEvidence.request()).isEqualTo(entitySettlementRequest); + var entitySettlement = entitySettlementEvidence.receipt(); + assertThat(entitySettlement.authorizationBinding().canonicalBytes()) + .containsExactly(entityAuthorization.canonicalBytes()); + assertThat(entitySettlement.ownerReceiptBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + assertThat(entitySettlement.ownerReceiptDigest()).isEqualTo(entityReceipt.receiptDigest()); + assertThat(entitySettlement.entityTerminalEvidence().request().binding().canonicalBytes()) + .containsExactly(entityAuthorization.canonicalBytes()); + assertThat(entitySettlement.entityTerminalEvidence().request().terminalReadPurpose()) + .isEqualTo(EntitySelectedSourceIntakeTerminalReadEvidence.TERMINAL_READ_PURPOSE); + assertThat(entitySettlement.entityTerminalEvidence().receipt().canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + var entitySettlementRows = + accountSourceDsl.fetch( + "SELECT binding_bytes, binding_digest, terminal_read_request_id, " + + "terminal_receipt_bytes, terminal_receipt_digest, receipt_bytes, " + + "receipt_digest FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + entityAuthorization.operationId()); + assertThat(entitySettlementRows).hasSize(1); + var entitySettlementRow = entitySettlementRows.getFirst(); + assertThat(entitySettlementRow.get("binding_bytes", byte[].class)) + .containsExactly(entityAuthorization.canonicalBytes()); + assertThat(entitySettlementRow.get("binding_digest", String.class)) + .isEqualTo(entityAuthorization.digest()); + assertThat(entitySettlementRow.get("terminal_receipt_bytes", byte[].class)) + .containsExactly(entityReceipt.canonicalBytes()); + assertThat(entitySettlementRow.get("terminal_receipt_digest", String.class)) + .isEqualTo(entityReceipt.receiptDigest()); + assertThat(entitySettlementRow.get("receipt_bytes", byte[].class)) + .containsExactly(entitySettlement.canonicalBytes()); + assertThat(entitySettlementRow.get("receipt_digest", String.class)) + .isEqualTo(entitySettlement.digest()); + assertThat(entitySettlementRow.get("terminal_read_request_id", UUID.class)) + .isEqualTo(entitySettlement.entityTerminalEvidence().request().readRequestId()); + + var entitySettlementRetry = selectedOwnerSettlementClient.settle(entitySettlementRequest); + assertThat(entitySettlementRetry.receipt().canonicalBytes()) + .containsExactly(entitySettlement.canonicalBytes()); + var entitySettlementNewCorrelationRequest = + SelectedOwnerIntakeSettlementEvidence.Request.create(NAMESPACE, entityAuthorization); + assertThat(entitySettlementNewCorrelationRequest.transportRequestId()) + .isNotEqualTo(entitySettlementRequest.transportRequestId()); + var entitySettlementNewCorrelation = + selectedOwnerSettlementClient.settle(entitySettlementNewCorrelationRequest); + assertThat(entitySettlementNewCorrelation.request()) + .isEqualTo(entitySettlementNewCorrelationRequest); + assertThat(entitySettlementNewCorrelation.receipt().canonicalBytes()) + .containsExactly(entitySettlement.canonicalBytes()); + assertThat( + entitySettlementNewCorrelation + .receipt() + .entityTerminalEvidence() + .request() + .readRequestId()) + .isEqualTo(entitySettlement.entityTerminalEvidence().request().readRequestId()); + assertThat( + accountSourceDsl.fetch( + "SELECT operation_id FROM account_selected_owner_intake_settlements " + + "WHERE operation_id = ?", + entityAuthorization.operationId())) + .hasSize(1); + assertFailedPrecondition( + () -> + entityToAccountHeld.read( + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( + NAMESPACE, entityAuthorization))); + var entityReceiptAfterSettlement = + entitySelectedSourceCommandClient.retain(entityRetainNewCorrelationRequest).receipt(); + assertThat(entityReceiptAfterSettlement.canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + assertThat(entitySourceRowCounts(entity.dsl())).isEqualTo(entityRowsAfterRetention); + var publicationRequest = PublicationDigestRequestBinding.full( gd.target().canonicalTenantId().toString(), @@ -1819,11 +2174,16 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new VersionRepository(gd.dsl()), gd.transactions(), new ObjectMapper()); - var objectStore = new InMemoryConditionalObjectStore(candidateService, publicationRequest); + var objectStore = + this.objectStore = + new MinioConditionalObjectStore(candidateService, publicationRequest); objectStore.requireCandidateBeforeWrites(actualInventory); var properties = new AssetStoreProperties(); - properties.setEndpoint("https://objects.invalid"); - properties.setBucket("genuine-selected-export-test"); + properties.setEndpoint(objectStore.endpoint()); + properties.setBucket(objectStore.bucket()); + properties.setRegion(MINIO_REGION.id()); + properties.setAccessKey(MINIO_ACCESS_KEY); + properties.setSecretKey(MINIO_SECRET_KEY); var exporter = new AssetExportServiceImpl( new VersionAssetPublicationRepository(gd.dsl()), @@ -1846,14 +2206,6 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(first.manifest().artifactDigests().getFirst().contentDigest()) .isEqualTo("sha256:" + sha256(assetBytes)); assertThat(objectStore.objects()).hasSize(2); - assertThat(objectStore.bytesAt("artifacts/sha256/" + sha256(assetBytes))) - .containsExactly(assetBytes); - assertThat(objectStore.contentTypeAt("artifacts/sha256/" + sha256(assetBytes))) - .isEqualTo("text/plain"); - assertThat( - objectStore.bytesAt( - "manifests/sha256/" + first.manifest().manifestHash().substring(7))) - .containsExactly(first.candidateBinding().manifestBytes()); SelectedExportResult retry = exporter.exportSelectedAssets(publicationRequest); assertThat(retry).isEqualTo(first); @@ -1862,6 +2214,15 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(candidateService.readSelectedCandidate(publicationRequest)) .isEqualTo(first.candidateBinding()); assertThat(gd.dsl().fetchCount(DSL.table("version_asset_export_candidate"))).isOne(); + var exportedAsset = objectStore.objectAt("artifacts/sha256/" + sha256(assetBytes)); + assertThat(exportedAsset.bytes()).containsExactly(assetBytes); + assertThat(exportedAsset.contentType()).isEqualTo("text/plain"); + var exportedManifest = + objectStore.objectAt( + "manifests/sha256/" + first.manifest().manifestHash().substring(7)); + assertThat(exportedManifest.bytes()) + .containsExactly(first.candidateBinding().manifestBytes()); + assertThat(exportedManifest.contentType()).isEqualTo("application/json"); byte[] alteredManifestBytes = alteredManifest(first.candidateBinding().manifestBytes()); var alteredManifest = @@ -2398,15 +2759,16 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex .isEqualTo(first.candidateBinding()); } } finally { - stopAll(automationServer, gameLogicServer, accountServer, worldServer, gdServer); + stopAll( + automationServer, entityServer, gameLogicServer, accountServer, worldServer, gdServer); } } /** - * Entity and Automation participant digests remain stipulated test inputs. Automation's source - * receipt and Account settlement do not replace those publication participants. World freeze, - * inventory, selector and Game Design and Game Logic source reads come from their actual owner - * compositions. This does not prove complete four-owner publication or activation. + * Entity and Automation participant digests remain stipulated test inputs. Their source receipts + * and Account settlements do not replace those publication participants. World freeze, inventory, + * selector and Game Design and Game Logic source reads come from their actual owner compositions. + * This does not prove complete four-owner publication or activation. */ private static List selectedSelectorParticipantDigests( DraftCommitBinding selectedCommit, @@ -2834,6 +3196,192 @@ private static Map automationSourceRowCounts(DSLContext dsl) { dsl.fetchCount(DSL.table("automation_empty_source_numeric_key_reservation"))); } + private static Map entitySourceRowCounts(DSLContext dsl) { + var counts = new TreeMap(); + for (String table : + List.of( + "actor_active_conditions", + "actor_resource_states", + "body_layout_slot_definitions", + "character_equipment", + "character_friend", + "characters", + "container_instances", + "crafting_ingredients", + "crafting_recipes", + "entity_mutation_effects", + "equipment_slot_definitions", + "inventory", + "item_instances", + "item_stacks", + "item_transfer_audits", + "item_visible_ref_counters", + "items", + "npcs", + "room_ground_inventory", + "entity_empty_source_numeric_key_reservation", + "entity_empty_selected_source_association", + "entity_empty_selected_source_family_state", + "entity_empty_selected_source_receipt")) { + counts.put(table, dsl.fetchCount(DSL.table(table))); + } + for (String table : ENTITY_EMPTY_ONLY_PROVIDER_TABLES.values()) { + counts.put(table, dsl.fetchCount(DSL.table(table))); + } + return Map.copyOf(counts); + } + + private static void assertPersistedEntityReceipt( + DSLContext dsl, + EntityEmptySelectedSourceIntakeReceipt receipt, + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding + authorization, + WorldSelectedDraftPublicationFreezeEvidence freeze) { + assertThat(receipt.localTenantKey()).isPositive(); + assertThat(receipt.localVersionKey()).isPositive().isNotEqualTo(receipt.localTenantKey()); + + var association = + dsl.fetchOne( + "SELECT genesis_id, operation_id, fence_id, intake_request_id, canonical_tenant_id, " + + "canonical_version_id, selected_commit_id, source_revision_id, " + + "source_revision_order, local_tenant_key, local_version_key, request_digest, " + + "schema_digest, authorization_binding_digest, selected_source_digest, " + + "world_read_request_id, world_read_request_digest, world_closure_digest, " + + "receipt_digest FROM entity_empty_selected_source_association " + + "WHERE target_namespace = ? AND intake_request_id = ?", + authorization.targetNamespace(), + authorization.intakeRequestId()); + assertThat(association).isNotNull(); + assertThat(association.get("operation_id", UUID.class)).isEqualTo(authorization.operationId()); + assertThat(association.get("fence_id", UUID.class)).isEqualTo(authorization.fenceId()); + assertThat(association.get("canonical_tenant_id", UUID.class)) + .isEqualTo(authorization.tenantId()); + assertThat(association.get("canonical_version_id", UUID.class)) + .isEqualTo(authorization.versionId()); + assertThat(association.get("selected_commit_id", UUID.class)) + .isEqualTo(authorization.selected().commitId()); + assertThat(association.get("source_revision_id", UUID.class)) + .isEqualTo(receipt.sourceRevisionId()); + assertThat(association.get("source_revision_order", String.class)) + .isEqualTo(receipt.sourceRevisionOrder()); + assertThat(association.get("local_tenant_key", Long.class)).isEqualTo(receipt.localTenantKey()); + assertThat(association.get("local_version_key", Long.class)) + .isEqualTo(receipt.localVersionKey()); + assertThat(association.get("request_digest", String.class)).isEqualTo(receipt.requestDigest()); + assertThat(association.get("schema_digest", String.class)).isEqualTo(receipt.schemaDigest()); + assertThat(association.get("authorization_binding_digest", String.class)) + .isEqualTo(authorization.digest()); + assertThat(association.get("selected_source_digest", String.class)) + .isEqualTo(receipt.selectedSourceDigest()); + assertThat(association.get("world_read_request_id", UUID.class)) + .isEqualTo(receipt.worldReadRequestId()); + assertThat(association.get("world_read_request_digest", String.class)) + .isEqualTo(receipt.worldReadRequestDigest()); + assertThat(association.get("world_closure_digest", String.class)) + .isEqualTo(receipt.worldClosureDigest()); + assertThat(association.get("receipt_digest", String.class)).isEqualTo(receipt.receiptDigest()); + + var reservedKeys = + dsl.fetch( + "SELECT key_kind, numeric_key, claim_kind FROM entity_empty_source_numeric_key_reservation " + + "WHERE numeric_key IN (?, ?) ORDER BY key_kind", + receipt.localTenantKey(), + receipt.localVersionKey()); + assertThat(reservedKeys).hasSize(2); + assertThat(reservedKeys.get(0).get("key_kind", String.class)).isEqualTo("TENANT"); + assertThat(reservedKeys.get(0).get("numeric_key", Long.class)) + .isEqualTo(receipt.localTenantKey()); + assertThat(reservedKeys.get(0).get("claim_kind", String.class)) + .isEqualTo("CANONICAL_EMPTY_SOURCE"); + assertThat(reservedKeys.get(1).get("key_kind", String.class)).isEqualTo("VERSION"); + assertThat(reservedKeys.get(1).get("numeric_key", Long.class)) + .isEqualTo(receipt.localVersionKey()); + assertThat(reservedKeys.get(1).get("claim_kind", String.class)) + .isEqualTo("CANONICAL_EMPTY_SOURCE"); + + var persistedFamilyStates = + dsl.fetch( + "SELECT family_name, owner_state, evidence_kind, row_count, unqualified_row_count, " + + "retained_row_count, selected_scope_row_count, reference_count " + + "FROM entity_empty_selected_source_family_state " + + "WHERE target_namespace = ? AND intake_request_id = ? ORDER BY family_name", + authorization.targetNamespace(), + authorization.intakeRequestId()); + var expectedFamilyNames = + receipt.familyStates().stream() + .map(EntityEmptySelectedSourceIntakeReceipt.FamilyCensus::family) + .sorted() + .toList(); + assertThat(persistedFamilyStates).hasSize(23); + assertThat(persistedFamilyStates.map(row -> row.get("family_name", String.class))) + .containsExactlyElementsOf(expectedFamilyNames); + for (var persisted : persistedFamilyStates) { + var family = + receipt.familyStates().stream() + .filter( + candidate -> + candidate.family().equals(persisted.get("family_name", String.class))) + .findFirst() + .orElseThrow(); + assertThat(persisted.get("owner_state", String.class)).isEqualTo(family.state().name()); + assertThat(persisted.get("evidence_kind", String.class)) + .isEqualTo(family.evidenceKind().name()); + assertThat(persisted.get("row_count", Long.class)).isZero(); + assertThat(persisted.get("unqualified_row_count", Long.class)).isZero(); + assertThat(persisted.get("retained_row_count", Long.class)).isZero(); + assertThat(persisted.get("selected_scope_row_count", Long.class)).isZero(); + assertThat(persisted.get("reference_count", Long.class)).isZero(); + } + + for (var provider : ENTITY_EMPTY_ONLY_PROVIDER_TABLES.entrySet()) { + var providerRow = + dsl.fetchOne( + "SELECT provider_schema_version, owner_state, row_count, reference_count, " + + "authorization_binding_digest, selected_source_digest, " + + "source_revision_binding_digest, world_closure_digest, provider_state_digest " + + "FROM " + + provider.getValue() + + " WHERE target_namespace = ? AND intake_request_id = ?", + authorization.targetNamespace(), + authorization.intakeRequestId()); + assertThat(providerRow).as(provider.getKey()).isNotNull(); + assertThat(providerRow.get("provider_schema_version", Short.class)).isEqualTo((short) 1); + assertThat(providerRow.get("owner_state", String.class)).isEqualTo("EMPTY"); + assertThat(providerRow.get("row_count", Long.class)).isZero(); + assertThat(providerRow.get("reference_count", Long.class)).isZero(); + assertThat(providerRow.get("authorization_binding_digest", String.class)) + .isEqualTo(authorization.digest()); + assertThat(providerRow.get("selected_source_digest", String.class)) + .isEqualTo(receipt.selectedSourceDigest()); + assertThat(providerRow.get("source_revision_binding_digest", String.class)) + .isEqualTo(receipt.selectedSourceRevisionBindingDigest()); + assertThat(providerRow.get("world_closure_digest", String.class)) + .isEqualTo(receipt.worldClosureDigest()); + assertThat(providerRow.get("provider_state_digest", String.class)) + .isEqualTo(receipt.providerStateDigest(provider.getKey())); + } + + var persistedReceipt = + dsl.fetchOne( + "SELECT request_digest, schema_digest, receipt_digest, receipt_bytes " + + "FROM entity_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + authorization.targetNamespace(), + authorization.intakeRequestId()); + assertThat(persistedReceipt).isNotNull(); + assertThat(persistedReceipt.get("request_digest", String.class)) + .isEqualTo(receipt.requestDigest()); + assertThat(persistedReceipt.get("schema_digest", String.class)) + .isEqualTo(receipt.schemaDigest()); + assertThat(persistedReceipt.get("receipt_digest", String.class)) + .isEqualTo(receipt.receiptDigest()); + assertThat(persistedReceipt.get("receipt_bytes", byte[].class)) + .containsExactly(receipt.canonicalBytes()); + + assertThat(receipt.inputs().worldInventoryReadEvidence().request().freezeEvidence()) + .isEqualTo(freeze); + } + private static List selectedOwnerReservationSourceRows(DSLContext dsl, UUID operationId) { return dsl.fetch( "SELECT source_key, source_evidence " @@ -3423,7 +3971,8 @@ private static final class TestPki { "game-design-service", "world-management-service", "game-logic-service", - "automation-scripting-service")) { + "automation-scripting-service", + "entity-management-service")) { servers.put(service, issue(root, service, true, caKeys, caCertificate)); clients.put(service, issue(root, service, false, caKeys, caCertificate)); } @@ -3513,99 +4062,79 @@ private static Path pem(Path path, Object value) throws Exception { } /** - * Object IO only; every put still observes the committed candidate through the real GD reader. + * Real S3-compatible object I/O; each outbound conditional PUT re-reads the committed candidate + * through the real GD reader immediately before transmission. */ - private static final class InMemoryConditionalObjectStore { + private static final class MinioConditionalObjectStore implements AutoCloseable { private final VersionAssetExportCandidateService candidates; private final PublicationDigestRequestBinding request; - private final Map stored = new ConcurrentHashMap<>(); private final AtomicInteger puts = new AtomicInteger(); private final AtomicInteger gets = new AtomicInteger(); - private final S3Client client = mock(S3Client.class); + private final URI endpoint; + private final S3Client client; private byte[] inventoryBytes; + private String operationDigest; + private String selectedCommitDigest; + private String inventoryDigest; - InMemoryConditionalObjectStore( + MinioConditionalObjectStore( VersionAssetExportCandidateService candidates, PublicationDigestRequestBinding request) { this.candidates = candidates; this.request = request; - doAnswer( - invocation -> { - PutObjectRequest put = invocation.getArgument(0); - RequestBody body = invocation.getArgument(1); - puts.incrementAndGet(); - if (!"*".equals(put.ifNoneMatch())) { - throw new AssertionError("Selected object PUT was not conditional"); - } - var retained = candidates.readSelectedCandidate(request); - if (inventoryBytes == null - || !request.requestDigest().equals(retained.requestDigest()) - || !Arrays.equals(request.canonicalPreimage(), retained.requestPreimage()) - || !Arrays.equals(inventoryBytes, retained.inventoryBytes()) - || !("sha256:" + sha256(retained.inventoryBytes())) - .equals(retained.inventoryDigest()) - || !("sha256:" + sha256(retained.manifestBytes())) - .equals(retained.manifest().manifestHash())) { - throw new AssertionError( - "Exact durable candidate, inventory and manifest were not readable before object PUT"); - } - byte[] bytes; - try (var stream = body.contentStreamProvider().newStream()) { - bytes = stream.readAllBytes(); - } - String key = put.key(); - StoredObject prior = - stored.putIfAbsent(key, new StoredObject(bytes, put.contentType())); - if (prior != null) { - throw S3Exception.builder() - .statusCode(412) - .message("conditional collision") - .build(); - } - return PutObjectResponse.builder().build(); - }) - .when(client) - .putObject(any(PutObjectRequest.class), any(RequestBody.class)); - when(client.getObjectAsBytes(any(GetObjectRequest.class))) - .thenAnswer( - invocation -> { - gets.incrementAndGet(); - GetObjectRequest get = invocation.getArgument(0); - StoredObject object = stored.get(get.key()); - if (object == null) { - throw S3Exception.builder() - .statusCode(404) - .message("missing test object") - .build(); - } - return ResponseBytes.fromByteArray( - GetObjectResponse.builder() - .contentLength((long) object.bytes().length) - .contentType(object.contentType()) - .build(), - object.bytes()); - }); + endpoint = URI.create("http://" + MINIO.getHost() + ":" + MINIO.getMappedPort(9000)); + client = + S3Client.builder() + .endpointOverride(endpoint) + .credentialsProvider( + StaticCredentialsProvider.create( + AwsBasicCredentials.create(MINIO_ACCESS_KEY, MINIO_SECRET_KEY))) + .region(MINIO_REGION) + .serviceConfiguration(S3Configuration.builder().pathStyleAccessEnabled(true).build()) + .overrideConfiguration( + configuration -> + configuration.addExecutionInterceptor( + new CandidateReadbackExecutionInterceptor())) + .build(); + try { + client.createBucket(CreateBucketRequest.builder().bucket(MINIO_BUCKET).build()); + } catch (RuntimeException failure) { + client.close(); + throw failure; + } } void requireCandidateBeforeWrites(SelectedDraftAssetInventory inventory) { inventoryBytes = inventory.canonicalBytes(); - if (!stored.isEmpty()) + operationDigest = sha256(inventory.operation().canonicalBytes()); + selectedCommitDigest = inventory.selectedCommit().digest(); + inventoryDigest = inventory.digest(); + if (!objects().isEmpty()) { throw new IllegalStateException("Test object store is already populated"); + } } - S3Client client() { - return client; + String endpoint() { + return endpoint.toString(); } - Map objects() { - return Map.copyOf(stored); + String bucket() { + return MINIO_BUCKET; + } + + S3Client client() { + return client; } - byte[] bytesAt(String key) { - return Objects.requireNonNull(stored.get(key), "missing selected test object").bytes(); + List objects() { + return client + .listObjectsV2(ListObjectsV2Request.builder().bucket(MINIO_BUCKET).build()) + .contents(); } - String contentTypeAt(String key) { - return Objects.requireNonNull(stored.get(key), "missing selected test object").contentType(); + StoredObject objectAt(String key) { + var observed = + client.getObjectAsBytes(GetObjectRequest.builder().bucket(MINIO_BUCKET).key(key).build()); + return new StoredObject(observed.asByteArray(), observed.response().contentType()); } int putCalls() { @@ -3615,6 +4144,47 @@ int putCalls() { int getCalls() { return gets.get(); } + + @Override + public void close() { + client.close(); + } + + private void requireExactCandidateBeforePut() { + var retained = candidates.readSelectedCandidate(request); + if (inventoryBytes == null + || !request.requestDigest().equals(retained.requestDigest()) + || !Arrays.equals(request.canonicalPreimage(), retained.requestPreimage()) + || !operationDigest.equals(retained.operationDigest()) + || !selectedCommitDigest.equals(retained.selectedCommitDigest()) + || !SelectedDraftAssetInventory.SCHEMA.equals(retained.inventorySchema()) + || !inventoryDigest.equals(retained.inventoryDigest()) + || !Arrays.equals(inventoryBytes, retained.inventoryBytes()) + || !("sha256:" + sha256(retained.inventoryBytes())).equals(retained.inventoryDigest()) + || !("sha256:" + sha256(retained.manifestBytes())) + .equals(retained.manifest().manifestHash())) { + throw new AssertionError( + "Exact durable candidate, inventory and manifest were not readable before object PUT"); + } + } + + private final class CandidateReadbackExecutionInterceptor implements ExecutionInterceptor { + @Override + public void beforeTransmission( + software.amazon.awssdk.core.interceptor.Context.BeforeTransmission context, + ExecutionAttributes executionAttributes) { + if (context.request() instanceof PutObjectRequest put) { + if (!MINIO_BUCKET.equals(put.bucket()) || !"*".equals(put.ifNoneMatch())) { + throw new AssertionError("Selected object PUT was not conditional to the test bucket"); + } + puts.incrementAndGet(); + requireExactCandidateBeforePut(); + } else if (context.request() instanceof GetObjectRequest get + && MINIO_BUCKET.equals(get.bucket())) { + gets.incrementAndGet(); + } + } + } } private record StoredObject(byte[] bytes, String contentType) { From e0f048e4eb5810eb69581dcb2c74e612cb368a60 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 07:17:54 +1300 Subject: [PATCH 095/129] Compose genuine selected-owner publication and immutable v4 release --- .../api-contracts.md | 8 +- .../api-contracts.md | 8 +- .../game-design-service/version-control.md | 4 + ...ame-authoring-publishing-and-activation.md | 10 +- ...onEmptySelectedSourceIntakeRepository.java | 72 +++ ...tedEmptyPublicationDigestGrpcReceiver.java | 103 ++++ ...SelectedEmptyPublicationDigestService.java | 161 ++++++ ...takeRepositoryPostgresIntegrationTest.java | 174 +++++++ ...mptyPublicationDigestGrpcReceiverTest.java | 173 +++++++ ...thoredWorldReleaseAttestationEvidence.java | 72 ++- ...GameDesignPublicationTerminalEvidence.java | 6 +- ...edWorldReleaseAttestationSelectorTest.java | 181 +++++++ ...gnPublicationTerminalReadEvidenceTest.java | 199 ++++++++ ...tyEmptySelectedSourceIntakeRepository.java | 70 +++ ...tedEmptyPublicationDigestGrpcReceiver.java | 103 ++++ ...SelectedEmptyPublicationDigestService.java | 148 ++++++ ...ntakeMigrationPostgresIntegrationTest.java | 26 +- ...takeRepositoryPostgresIntegrationTest.java | 171 +++++++ ...mptyPublicationDigestGrpcReceiverTest.java | 145 ++++++ .../dto/PublishedReleaseBundleDto.java | 4 +- .../StartSessionLaunchDescriptorProducer.java | 3 +- ...SessionTemplateAssociationReadService.java | 3 +- .../PublishedReleaseBundleRepository.java | 5 +- .../CompleteLaunchBindingServiceImpl.java | 27 +- .../service/impl/PublishGateServiceImpl.java | 2 +- .../impl/PublishedReleaseBundleContract.java | 23 +- .../PublishedReleaseBundleServiceImpl.java | 2 +- ...lected_full_semantic_owner_attestation.sql | 273 ++++++++++ .../impl/PublishedWorldSelectorFixtures.java | 21 + ...licationExportPostgresIntegrationTest.java | 476 ++++++++++++++---- ...leaseCanonicalIdentityIntegrationTest.java | 148 ++++++ .../CompleteLaunchBindingServiceImplTest.java | 55 ++ .../impl/PublishGateServiceImplTest.java | 40 +- ...PublishedReleaseBundleServiceImplTest.java | 103 +++- ...onicalInstanceLifecycleReadRepository.java | 4 +- ...alInstanceLifecycleReadRepositoryTest.java | 290 +++++++++++ 36 files changed, 3161 insertions(+), 152 deletions(-) create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiver.java create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java create mode 100644 services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiver.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V72__selected_full_semantic_owner_attestation.sql diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 6839cc3dc8..65ecea4590 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -272,10 +272,14 @@ This service is a required digest participant for full publishes and script-patc Publish gating must fail closed when the service cannot attest a digest under its documented manifest for the reported `digestSchemaVersion`. +**Current selected-empty status:** An unregistered owner-local reader now provides a bounded selected-empty full-version primitive over Automation's immutable validated fresh-empty receipt. Its native receiver applies the existing exact `PublicationReadGuard` and validates the complete publication request binding before lookup. The existing registered full-version reader remains unchanged; this primitive does not make Automation publication readiness or runtime registration complete. It accepts only a receipt created by the fresh `retainFresh` path with all three declared script, event-binding, and patch-base-binding families explicitly empty. Nonempty or historical participant evidence outside this exact fresh-empty path is unsupported and denied; old participant evidence is not silently rewritten or reinterpreted. This selected-empty full-version semantic path uses `digestSchemaVersion=6`; the existing script-patch digest remains schema 5 with its existing behavior. + +The selected-empty reader resolves by configured namespace, canonical tenant UUID, and the numeric Game Design Version row in the incoming full-version request. It scans only that namespace/tenant association prefix, fully validates each receipt, and requires exactly one association whose retained original selected-target proof matches the tenant, canonical Version UUID, and numeric Game Design Version row. The retained proof supplies the canonical Version UUID; the caller does not invent or submit it, and no mapping migration is introduced. Missing, ambiguous, corrupt, or mismatched evidence fails closed. Private Automation numeric keys, receipt digests/bytes, request/operation/authorization provenance, World read evidence, and timestamps are not publication identity or digest input. Its SHA-256 content preimage uses ADR 0047 byte-length framing over these ordered segments: the owner-specific domain `automation-selected-empty-publication-digest/v1`, schema `6`, canonical tenant UUID, numeric Game Design Version row, canonical Version UUID retained in the selected-target proof, and the exact canonical Automation inventory declaration. `appliedCommitId` is the original selected commit UUID retained in the receipt. This subset is not a claim that nonempty full-version script graphs or bindings are covered, and schema-6 participant evidence is not created by rewriting old evidence. + ### Game Design owner-to-owner digest authorization For publication-gate calls, `GetDraftDesignDigest` is not an admin or user operation. The target receiver authorization is a method-level allowlist for the authenticated Game Design workload identity, under the shared [Security Architecture](../../system-architecture-security.md) and [Authentication & Authorization](../../system-architecture-authentication.md) owner rules. The call must carry and validate the exact `{tenantId, scope}` (`versionId` or `scriptPatchVersion`) together with the stable caller `publishRequestId`, derived workflow identity, and canonical `requestDigest`; omitted or changed binding fails closed. This context is authorization and replay evidence, not a digest input. Other internal workloads are denied, and no user/admin JWT is accepted as a substitute. Game Design's Temporal activities must never forward the initiating human operator JWT; operator authority terminates at workflow admission. -**Current status:** `GetDraftDesignDigest` now invokes `PublicationReadGuard` for the exact Automation publication-read method. The guard requires the authenticated Game Design workload peer in the trusted namespace and a role-free internal JWT; the JWT `serviceName` claim is not treated as workload identity, and user/admin JWT substitution or a different peer is denied. The request proto carries tenant, typed scope, the patch `baseVersionId` when applicable, stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; the handler validates that complete binding before reading content and exact-compares the returned tenant and scope. Focused unit proof covers the allowlisted peer, missing/wrong peer, JWT-only/user/admin substitution, and changed request digest. This closes the former empty-role/admin-guard authorization failure, but does not claim live mounted-certificate or real Temporal-activity proof. The schema-5 script-patch content digest includes the retained base version. Remaining content/proof gaps are explicit: the full-version digest input is still tenant-wide rather than version-mapped, and multi-version/cross-tenant owner proof is still required. See the [Game Design publication/Temporal contract](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) for the coordinator-side boundary. +**Current status:** `GetDraftDesignDigest` now invokes `PublicationReadGuard` for the exact Automation publication-read method. The guard requires the authenticated exact Game Design workload mTLS peer in the configured trusted namespace and denies account, global-role, or scoped-role context. It does not add an end-user JWT requirement; a role-free internal identity is neither workload authorization nor an independent denial condition when the exact peer is present. The request proto carries tenant, typed scope, the patch `baseVersionId` when applicable, stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; the handler validates that complete binding before reading content and exact-compares the returned tenant and scope. Focused unit proof covers the allowlisted peer without end-user context, missing/wrong peer, account/global/scoped-role context denial, and changed request digest. This does not claim live mounted-certificate or real Temporal-activity proof. The existing script-patch content digest remains schema 5 and includes the retained base version; the selected-empty schema-6 primitive is unregistered and does not replace the live full-version reader, whose input remains tenant-wide. Multi-version/cross-tenant owner proof is still required. See the [Game Design publication/Temporal contract](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) for the coordinator-side boundary. -The same owner-to-owner authorization now covers the WMS, Entity, Game Logic, and Automation participant reads: each handler applies the shared exact-method `PublicationReadGuard`, validates the complete typed request binding, and checks the returned tenant/scope before exposing its digest. The shared negative proof covers missing or wrong peer identity and JWT-only/user/admin substitution; live mounted-certificate, real Temporal-activity, and multi-version/cross-tenant proof remain separate gaps. Content manifests remain owner-local: Automation's patch digest now binds the retained base version, while its full-version mapping remains tenant-wide, so the authorization boundary must not be read as complete digest correctness. The shared target and proof requirements are maintained in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity), not redefined here. +The same owner-to-owner authorization now covers the WMS, Entity, Game Logic, and Automation participant reads: each handler applies the shared exact-method `PublicationReadGuard`, validates the complete typed request binding, and checks the returned tenant/scope before exposing its digest. The guard requires the exact authenticated Game Design workload mTLS peer and denies account or role-bearing context; role-free internal identity alone is not authorization or a substitute for that peer. Live mounted-certificate, real Temporal-activity, and multi-version/cross-tenant proof remain separate gaps. Content manifests remain owner-local: Automation's patch digest now binds the retained base version, while its existing live full-version mapping remains tenant-wide, so the authorization boundary must not be read as complete digest correctness. The shared target and proof requirements are maintained in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity), not redefined here. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 35a0a887fb..da5e28da77 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -71,12 +71,18 @@ Entity Management must also expose a read-only design-time synchronization surfa - `GetDraftDesignDigest(GetDraftDesignDigestRequest)` uses request shape `{tenantId, scope: oneof {versionId, scriptPatchVersion}}`. Entity Management supports `versionId` scope only and returns `UNSUPPORTED_SCOPE` otherwise. - Response returns `{tenantId, scope, appliedCommitId, contentDigest, digestSchemaVersion}` as described in [`world-editing-tools.md`](../game-design-service/world-editing-tools.md). -- Current boundary: `GetDraftDesignDigest` requires a configured trusted namespace and an authenticated same-namespace Game Design workload peer, and rejects forwarded end-user context. The handler validates the supplied publication request binding and returned tenant/scope. Its synthetic `appliedCommitId = "version:"` and current digest do not establish selected-commit evidence; the target binding and proof remain canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). +- Current boundary: `GetDraftDesignDigest` requires a configured trusted namespace and the authenticated exact Game Design workload mTLS peer, and denies forwarded account, global-role, or scoped-role context. This guard does not add an end-user JWT requirement; a role-free internal identity is not workload authorization and is not independently denied when the exact mTLS peer is present. The handler validates the supplied publication request binding and returned tenant/scope. Its synthetic `appliedCommitId = "version:"` and current digest do not establish selected-commit evidence; the target binding and proof remain canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). ## Digest Input Manifest Entity Management is a required publish-gate participant and must maintain a stable digest manifest for `GetDraftDesignDigest(versionId)`: +**Current selected-empty status:** An unregistered owner-local reader now provides a bounded selected-empty full-version primitive over Entity's immutable validated fresh-empty receipt. Its native receiver applies the existing exact `PublicationReadGuard` and validates the complete publication request binding before lookup. The existing registered digest reader remains unchanged; this primitive does not make Entity publication readiness or runtime registration complete. It accepts only a receipt created by the fresh `retainFresh` path with the complete 23-family census explicitly empty, including `equipmentApplicability=NOT_APPLICABLE` and every declared family empty. Nonempty or historical participant evidence outside this exact fresh-empty path is unsupported and denied; old participant evidence is not silently rewritten or reinterpreted. + +The selected-empty reader resolves by configured namespace, canonical tenant UUID, and the numeric Game Design Version row in the incoming full-version request. It scans only that namespace/tenant association prefix, fully validates each receipt, and requires exactly one association whose retained original selected-target proof matches the tenant, canonical Version UUID, and numeric Game Design Version row. The retained proof supplies the canonical Version UUID; the caller does not invent or submit it, and no mapping migration is introduced. Missing, ambiguous, corrupt, or mismatched evidence fails closed. Private Entity numeric keys, receipt digests/bytes, request/operation/authorization provenance, World read evidence, and timestamps are not publication identity or digest input. + +For this selected-empty subset, `digestSchemaVersion=3`; the SHA-256 content preimage uses ADR 0047 byte-length framing over these ordered segments: the owner-specific domain `entity-selected-empty-publication-digest/v1`, schema `3`, canonical tenant UUID, numeric Game Design Version row, canonical Version UUID retained in the selected-target proof, and the exact canonical Entity inventory declaration. `appliedCommitId` is the original selected commit UUID retained in the receipt. The new semantic preimage requires a new schema under the digest migration rule; retained schema-2 participant evidence keeps its original meaning and bytes. This is a separately versioned, bounded semantic digest, not a receipt digest and not a claim that all nonempty Entity template families are covered. Only the new selected full-release profile may accept schema 3 after its compatible recorded owner evidence and exact readback pass; existing participant evidence is not upgraded in place. + Implementation Notes: - The current implementation hashes the version-scoped entity-definition rows for the requested `(tenantId, versionId)` and returns synthetic `appliedCommitId = "version:"` until the later applied-revision ledger lands. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index b652a34be9..b7838a8341 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -174,6 +174,10 @@ In addition to domain-service digests, publish safety requires a Game Design con Digest comparison rules: +New closure-qualified selected full publications that consume Entity's selected-empty semantic digest and Automation's version-scoped semantic `FULL_VERSION` digest use release-bundle schema `v4` and authenticated release-attestation schema 4, with domain `game-design-authored-world-release-attestation/v4`. The required ordered participant matrix is World 4, Entity 3, Game Logic 1, Automation 6, and Game Design control plane 2. Schema 4 retains the complete unchanged selected World evidence and all other release fields and framing; its distinct domain and exact participant schemas prevent it from aliasing retained schema 3. Game Design selects this profile from the complete participant matrix, not World schema 4 alone. Entity and Automation resolve the canonical tenant UUID and actual Game Design Version row to exactly one validated retained owner association; their private numeric keys and source-receipt digests are not publication content evidence. Their owning digest manifests define semantic content, independently of the publication request and retained provenance. The changed Entity preimage increments its digest schema rather than reinterpreting retained schema 2. Current fresh-empty producers do not establish nonempty or retained-source support. + +Retained release/attestation schemas 1, 2 and 3 keep their original canonical bytes and participant semantics; schema 3 continues to bind Automation 5, and script patches keep their separate schema-5 digest. A retained release is never promoted or rewritten when a newer owner digest becomes available. Recovery reads the original release and exact stored evidence; a fresh finalization or retry presenting a different profile, selected commit, participant value or World evidence conflicts rather than silently choosing another profile or minting a replacement release. Missing or mixed schema-4 participant evidence fails closed. This contract does not register publication ingress or authorize runtime activation; implementation and executed proof remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + For a new immutable selected-Draft full publication, the Game Design control-plane participant uses `digestSchemaVersion=2`, not the legacy mutable normalized-row digest. Its SHA-256 preimage uses ADR 0047-style canonical decimal ASCII byte-length framing: first the domain `game-design-selected-draft-control-plane-digest/v2`, then the exact canonical selected Draft binding, followed by each family label and its exact canonical synchronized snapshot bytes in the fixed order `COMMAND`, `REALM_POLICY`, `ASSET`, `GAMEPLAY_SOURCE`, `BRANDING`, `TEMPLATE_CONFIG`. All six snapshots must bind that same original Draft operation and commit. Branding and template/config absence is unknown, never an empty-family attestation. The immutable publication operation's five captured source families must match their synchronized selected snapshots byte-for-byte in one owner snapshot; the gameplay source is independently read from the same synchronized commit. The publication request binding and its digest are echoed and checked separately, not included in this content preimage. Mutable tenant-wide rows, notes, another request's selection or a `version:` marker cannot substitute. Actual asset bytes remain separately export-attested under [Asset Storage](asset-storage.md#complete-selected-release-asset-inventory). Selected publication consumes the World participant directly from its exact retained authenticated freeze evidence, not a fresh mutable Draft lookup. This local read does not create missing owner evidence or reduce the required participant matrix; retained earlier attestations and the separately scoped script-patch digest retain their explicitly declared schema semantics. - The Game Design Service records the per-domain-service `{commitId, contentDigest, digestSchemaVersion}` it observed when a commit was last applied successfully. 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 0cb5da8177..241b209738 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 @@ -10,11 +10,15 @@ The accepted admission boundary is [genuine original-COMMIT acknowledgement with The bounded Account correction passes `generateJooq`, the complete Account `check`, integration compilation, affected formatting/static analysis and `bootJar`. Its local gate executes 1,343 unit tests and 12 non-container integration tests; all 283 PostgreSQL-dependent cases skip locally. The substantive originating [Validation run 38067710993](https://github.com/benhook1013/FireMUD/actions/runs/38067710993) now completes successfully, with all 40 jobs passing. Its Account owner artifacts prove 1,343 units and 303 integrations executed with zero skips, failures or errors, including all 13 protected-entry cases and the V136 retained-history/new-write-denial and original-acknowledgement recovery cases. The actual tested merge is `b9d91aa36b2ea9fe85acd98935330c8e8d0f18b8`, tree `498745b64e4cb27c65c68cd7bfe7891e7d0cd023`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact `d4ba9ed` source; the first parent differs from the run title's recorded base. Owner XML artifact `11676209923` reports actual PostgreSQL **16.15** for the 30 lease-persistence and 13 protected-entry cases, not PostgreSQL 18. This is accepted scoped retirement/storage proof, not canonical PG18 fresh-executor proof, production privilege adoption, guaranteed historical recovery or activation. Gameplay owns the separate approved PG18 fresh-original-acknowledgement and insertion-gate convergence, reserved at V139; historical `readDurably` on PG18 remains denied. The duplicate dependency-deferred run supplies no additional proof. -The [fresh-empty Entity catalogue](../../architecture/microservices/entity-management-service/runtime-and-data.md#selected-entity-authored-source-inventory-empty-only-v1) combines nine actual V1 source/reference censuses with fourteen separate immutable EMPTY-only provider tables, Entity-allocated private keys, complete 23-family receipt evidence and independent provider/receipt readback. Native unregistered command and terminal-read boundaries now bind the complete original Account authorization and World freeze evidence to the exact configured workload peer before decoding or storage. Account's additive V138 accepts the closed Entity terminal receipt in its existing immutable settlement family, preserves prior Automation bytes and limits, and retains canonical source-lock ordering and independent readback. The preparation service checks its configured namespace before replay or remote reads. The complete Entity unit suite passes all 204 cases; earlier V2 schema generation and integration compilation pass, but all 13 integration definitions skip locally, including three migration and six repository cases. Narrow schema-generator exclusions preserve real PostgreSQL locks and occupied-key seeding; generation does not prove those statements. Physical V2/V138 installation, writer exclusion and genuine composed producer execution remain unproved. Sampled HELD reads, creator declarations and missing storage do not discharge continuous through-commit protection; matching reserved-key runtime writes remain restricted and no runtime path is registered or activated. +The [fresh-empty Entity catalogue](../../architecture/microservices/entity-management-service/runtime-and-data.md#selected-entity-authored-source-inventory-empty-only-v1) combines nine actual V1 source/reference censuses with fourteen separate immutable EMPTY-only provider tables, Entity-allocated private keys, complete 23-family receipt evidence and independent provider/receipt readback. Native unregistered command and terminal-read boundaries bind the complete original Account authorization and World freeze evidence to the exact configured workload peer before decoding or storage. Account's additive V138 accepts the closed Entity terminal receipt in its existing immutable settlement family, preserves prior Automation bytes and limits, and retains canonical source-lock ordering and independent readback. Originating source `2b763b040c9b4f63baa88bff0c911d3be177abd9` [Validation run 38072471688](https://github.com/benhook1013/FireMUD/actions/runs/38072471688) executes 204 Entity units and 13 integrations on PostgreSQL 18.6, without skips; one integration fails because its seed fixture expects five reserved keys instead of the actual three tenant keys and one version key. All six new repository cases and two other migration cases pass. The corrected fixture now asserts that exact typed four-key set without changing V2, its occupied-key seed or writer guards; corrected physical execution remains required. Sampled HELD reads, creator declarations and missing storage do not discharge continuous through-commit protection; matching reserved-key runtime writes remain restricted and no runtime path is registered or activated. -The genuine release-proof definition now composes native Account/Game Design/World/Entity mTLS boundaries, isolated Entity PostgreSQL storage, exact provider/receipt readback and retry, and Account Entity terminal settlement. It uses a classes-only Entity proof artifact, not Entity application or migration resources on the Game Design classpath. Real SDK conditional PUT and exact GET readback replace its in-memory object store against the Compose-pinned ephemeral MinIO image, with exact durable candidate readback before each PUT. These definitions compile but skip locally; current physical Entity/Account composition and real object I/O have not executed. Entity/Automation publication-participant digests and the StartSession Account projection remain explicit doubles, so this is not full release or activation proof. +The unregistered Entity and Automation selected-empty publication readers now independently validate their retained owner association and complete receipt in one read-only repeatable-read snapshot. Their content-only digest preimages are independently versioned at Entity 3 and Automation 6; unchanged script patches retain Automation 5. Additive Game Design V72 supports only the new release/attestation v4 profile with ordered schemas World 4, Entity 3, Game Logic 1, Automation 6 and Game Design control plane 2. It does not rewrite retained release schemas 1–3, their participant meanings or canonical bytes. Focused definitions cover exact scope and content, request-independent digest values, snapshot consistency, mixed-profile denial, immutable retry, retained v3 upgrade/readback and downstream World graph-profile selection. The World unit fixture stipulates carrier schemas; it does not establish physical closure recomputation or lifecycle readiness. New readers and runtime ingress remain unregistered. -The composed five-module local gate passes in 57 seconds: full checks, owning Account/Entity schema generation, integration compilation, classes-only proof artifact and affected boot JARs complete. Results across the corrected and preceding unchanged tasks retain 638 Common Platform, 156 Common Security, 1,346 Account, 204 Entity and 558 Game Design unit passes, without failures, errors or skips; unchanged tasks reuse their results. Account executes 12 non-container integrations and skips 286 definitions; Entity skips all 13 and Game Design all 149, for 448 skipped cases. The new V138 upgrade, closed-frame rollback, source-writer serialization and genuine Entity/MinIO composition therefore have no physical execution credit. The complete Entity suite initially exposed an older test's leaked thread-local account; symmetric before/after cleanup in the new receiver tests fixes isolation without changing production denial guards or canonical-input assertions. Architecture contracts pass all 228 cases; Flyway sanity passes 12 sets and 296 versioned files. Current PostgreSQL CI, production privileges, continuous protection and all four complete Gameplay handoffs remain open. +The genuine release-proof definition composes native Account/Game Design/World/Entity/Automation mTLS boundaries, isolated owner PostgreSQL stores, full provider/receipt readback and retry, Account terminal settlement, and actual selected-owner publication clients and Game Design publish gating rather than fixed participant hashes or a mocked gate. It uses a classes-only Entity proof artifact, not Entity application or migration resources on the Game Design classpath. Source `2b763b040c9b4f63baa88bff0c911d3be177abd9` executes this test against PostgreSQL 18.6 and the Compose-pinned real MinIO image, but fails before object PUT: the test interceptor incorrectly compares raw operation-digest hex with the canonical stored `sha256:` value. The fixture correction preserves conditional `If-None-Match: *`, every exact durable candidate/request/inventory/manifest check and exact object GET, adding bounded field-named diagnostics. Corrected physical export and the new native publication composition remain unproved until they execute successfully. StartSession's Account projection remains an explicit double; neither these definitions nor local container skips close full release, continuous protection, lifecycle readiness or activation. + +The corrected seven-module local gate passes in 5 minutes 7 seconds: complete checks, Game Design V72 schema generation, affected integration compilation, Entity's classes-only proof artifact and affected boot JARs complete. Available results total 4,768 unit passes with zero failures, errors or skips: 641 Common Platform, 156 Common Security, 1,346 Account, 207 Entity, 1,206 Automation, 562 Game Design and 650 World; unchanged tasks reuse their results. Account executes 12 non-container integrations, Automation three and World one. Container-dependent definitions skip locally: Account 286, Entity 15, Automation 96, Game Design 151 and World 220, totaling 768 skips. These skips supply no physical V72 upgrade, V138 settlement, same-snapshot owner lookup, corrected seed census, genuine native publication or MinIO execution credit. Flyway sanity passes 12 sets and 297 versioned files. Documentation validation passes all 548 Markdown files and links. The earlier Entity suite's leaked thread-local account was repaired with symmetric test cleanup, without changing production denial guards or canonical-input assertions. + +Originating run `38072471688` is terminal failure; its Account integration task was cancelled before any integration XML was captured. Artifact `11677753612` proves only 1,346 Account unit passes; no Account database execution count or PostgreSQL version can be attributed to the cancelled cases. Game Design's owner artifact `11677876709` records 152 integrations, zero skips and one failure (the candidate-digest fixture defect above); Entity artifact `11677281831` records the 13 integrations and sole seed-expectation failure above. The actual tested merge is `3543c22c2b945d553f2f7f19defd5606f469650f`, tree `b046aaa9c0e346eb5faca0698cf968d95829faba`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact `2b763b040c9b4f63baa88bff0c911d3be177abd9` source; the first parent differs from the recorded run-title base. Duplicate dependency-deferred run `38072575546` skips all build/test jobs and supplies no substantive proof. Corrected PostgreSQL CI, production privileges, continuous protection and all four complete Gameplay handoffs remain open. ## Earlier Construction Checkpoints diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java index 3c0311c415..d8c33f3cc7 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java @@ -2,6 +2,7 @@ import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; import java.util.Optional; @@ -58,6 +59,67 @@ public Optional read( return readValidated(dsl, targetNamespace, intakeRequestId); } + /** + * Resolves the one immutable selected-empty receipt for a canonical tenant and Game Design + * Version row. Every association in the tenant prefix is fully read back before its retained + * original TargetProof is considered; owner-local numeric keys are not publication identity. + */ + public AutomationEmptySelectedSourceIntakeReceipt readPublicationScope( + String targetNamespace, UUID canonicalTenantId, long gameDesignVersionRowId) { + requireNoAmbientOwnerSql("Automation publication receipt read"); + requirePublicationScopeKey(targetNamespace, canonicalTenantId, gameDesignVersionRowId); + + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + var associations = + tx.fetch( + "SELECT canonical_version_id, intake_request_id FROM " + + ASSOCIATION + + " WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "ORDER BY canonical_version_id", + targetNamespace, + canonicalTenantId); + if (associations.isEmpty()) { + throw new IllegalStateException( + "Automation selected-empty publication receipt is unavailable"); + } + + var matches = new ArrayList(); + for (Record association : associations) { + UUID associatedCanonicalVersionId = association.get(0, UUID.class); + UUID intakeRequestId = association.get(1, UUID.class); + if (associatedCanonicalVersionId == null || intakeRequestId == null) { + throw new IllegalStateException( + "Automation publication association identity is corrupt"); + } + AutomationEmptySelectedSourceIntakeReceipt receipt = + readValidated(tx, targetNamespace, intakeRequestId) + .orElseThrow( + () -> + new IllegalStateException( + "Automation publication association has no committed receipt")); + var target = receipt.authorizationBinding().selected().target(); + if (!canonicalTenantId.equals(receipt.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(receipt.canonicalVersionId()) + || !canonicalTenantId.equals(target.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(target.canonicalVersionId())) { + throw new IllegalStateException( + "Automation publication association differs from the retained selected target"); + } + if (target.gameDesignVersionRowId() == gameDesignVersionRowId) { + matches.add(receipt); + } + } + if (matches.size() != 1) { + throw new IllegalStateException( + "Automation selected-empty publication scope is missing or ambiguous"); + } + return matches.get(0); + }); + } + /** * Reads the original committed receipt for an exact finalized Account authorization. A missing * result remains absence; it is never converted into an abort or another terminal value. @@ -430,6 +492,16 @@ private static void requireReadKey(String namespace, UUID requestId) { DraftAuthorizationFenceBinding.requireUuid(requestId); } + private static void requirePublicationScopeKey( + String namespace, UUID canonicalTenantId, long gameDesignVersionRowId) { + if (!GrpcPeerIdentity.isValidNamespace(namespace) + || canonicalTenantId == null + || new UUID(0L, 0L).equals(canonicalTenantId) + || gameDesignVersionRowId <= 0L) { + throw new IllegalArgumentException("Automation publication scope identity is required"); + } + } + private static void requireNoAmbientOwnerSql(String action) { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiver.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiver.java new file mode 100644 index 0000000000..ca2788778c --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiver.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.MeterRegistry; +import java.util.Objects; +import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService.ScriptDraftDesignDigest; +import net.firedevops.firemud.automationscripting.v1.AutomationScriptingServiceGrpc; +import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestResponse; +import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.PublicationReadGuard; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Unregistered native receiver for the selected-empty Automation publication digest path. */ +public final class AutomationSelectedEmptyPublicationDigestGrpcReceiver + extends AutomationScriptingServiceGrpc.AutomationScriptingServiceImplBase { + private static final Logger LOGGER = + LoggerFactory.getLogger(AutomationSelectedEmptyPublicationDigestGrpcReceiver.class); + + private final AutomationSelectedEmptyPublicationDigestService digestService; + private final PublicationReadGuard publicationReadGuard; + private final MeterRegistry meterRegistry; + + public AutomationSelectedEmptyPublicationDigestGrpcReceiver( + AutomationSelectedEmptyPublicationDigestService digestService, + String configuredNamespace, + MeterRegistry meterRegistry) { + this.digestService = Objects.requireNonNull(digestService, "digestService"); + this.publicationReadGuard = PublicationReadGuard.configured(configuredNamespace); + this.meterRegistry = Objects.requireNonNull(meterRegistry, "meterRegistry"); + } + + @Override + public void getDraftDesignDigest( + GetDraftDesignDigestRequest request, + StreamObserver responseObserver) { + try { + requirePublicationRead(); + if (request.getScopeCase() != GetDraftDesignDigestRequest.ScopeCase.VERSION_ID) { + responseObserver.onNext( + error( + "UNSUPPORTED_SCOPE", + "Automation selected-empty publication supports version_id scope only")); + responseObserver.onCompleted(); + return; + } + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.forScope( + PublicationDigestRequestBinding.ScopeKind.FULL_VERSION, + request.getTenantId(), + request.getVersionId(), + request.getBaseVersionId(), + request.getScriptPatchVersion(), + request.getPublishRequestId()); + binding.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest()); + + ScriptDraftDesignDigest digest = digestService.getDraftDesignDigest(binding); + binding.requireOwnerScope(digest.tenantId(), digest.scopeValue()); + responseObserver.onNext( + GetDraftDesignDigestResponse.newBuilder() + .setTenantId(binding.tenantId()) + .setVersionId(binding.versionId()) + .setAppliedCommitId(digest.appliedCommitId()) + .setContentDigest(digest.contentDigest()) + .setDigestSchemaVersion(digest.digestSchemaVersion()) + .build()); + responseObserver.onCompleted(); + } catch (AdminAuthorizationException denied) { + responseObserver.onNext(error("PERMISSION_DENIED", denied.getMessage())); + responseObserver.onCompleted(); + } catch (IllegalArgumentException invalid) { + responseObserver.onNext(error("INVALID_ARGUMENT", invalid.getMessage())); + responseObserver.onCompleted(); + } catch (IllegalStateException unavailable) { + responseObserver.onNext(error("FAILED_PRECONDITION", unavailable.getMessage())); + responseObserver.onCompleted(); + } catch (RuntimeException failure) { + responseObserver.onNext( + GetDraftDesignDigestResponse.newBuilder() + .setError( + GrpcAppErrors.internal(meterRegistry, LOGGER, "GetDraftDesignDigest", failure)) + .build()); + responseObserver.onCompleted(); + } + } + + private void requirePublicationRead() { + if (publicationReadGuard == null) { + throw new AdminAuthorizationException("Publication read authorization is not configured"); + } + publicationReadGuard.requirePublicationRead( + PublicationReadGuard.AUTOMATION_SCRIPTING_DIGEST_METHOD); + } + + private GetDraftDesignDigestResponse error(String code, String message) { + return GetDraftDesignDigestResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, LOGGER, "GetDraftDesignDigest", code, message)) + .build(); + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java new file mode 100644 index 0000000000..3aa3f2a5a2 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java @@ -0,0 +1,161 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import java.io.ByteArrayOutputStream; +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 net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService.ScriptDraftDesignDigest; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; + +/** + * Unregistered selected-empty full-version digest reader over Automation's retained owner receipt. + */ +public final class AutomationSelectedEmptyPublicationDigestService { + public static final int DIGEST_SCHEMA_VERSION = 6; + private static final String DIGEST_DOMAIN = "automation-selected-empty-publication-digest/v1"; + + private final String configuredNamespace; + private final AutomationEmptySelectedSourceIntakeRepository repository; + + public AutomationSelectedEmptyPublicationDigestService( + String configuredNamespace, AutomationEmptySelectedSourceIntakeRepository repository) { + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("Configured Automation namespace is required"); + } + this.configuredNamespace = configuredNamespace; + this.repository = Objects.requireNonNull(repository, "repository"); + } + + /** Returns a selected-empty digest only for one exact canonical tenant and GD Version row. */ + public ScriptDraftDesignDigest getDraftDesignDigest( + PublicationDigestRequestBinding publicationRequest) { + Objects.requireNonNull(publicationRequest, "publication request is required"); + if (publicationRequest.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw new IllegalArgumentException( + "Automation selected-empty publication supports full versions only"); + } + UUID canonicalTenantId = canonicalUuid(publicationRequest.tenantId(), "tenantId"); + long gameDesignVersionRowId = + canonicalPositiveLong(publicationRequest.versionId(), "versionId"); + + AutomationEmptySelectedSourceIntakeReceipt receipt = + repository.readPublicationScope( + configuredNamespace, canonicalTenantId, gameDesignVersionRowId); + var target = receipt.authorizationBinding().selected().target(); + if (!configuredNamespace.equals(receipt.targetNamespace()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !canonicalTenantId.equals(target.canonicalTenantId()) + || target.gameDesignVersionRowId() != gameDesignVersionRowId + || !receipt.canonicalVersionId().equals(target.canonicalVersionId())) { + throw new IllegalStateException( + "Automation selected-empty receipt differs from publication scope"); + } + if (receipt.authorizationBinding().owner() != Owner.AUTOMATION_SCRIPTING) { + throw new IllegalStateException("Automation receipt contains a different owner declaration"); + } + requireEmptyReceipt(receipt); + + SelectedOwnerEmptySourceInputs inputs = + new SelectedOwnerEmptySourceInputs( + receipt.authorizationBinding(), receipt.worldInventoryReadEvidence()); + if (inputs.ownerSourceInventoryDeclaration().owner() != Owner.AUTOMATION_SCRIPTING) { + throw new IllegalStateException( + "Automation receipt has no exact owner inventory declaration"); + } + String inventoryJson = inputs.ownerSourceInventoryDeclaration().inventory().canonicalJson(); + String contentDigest = + contentDigest( + canonicalTenantId, gameDesignVersionRowId, receipt.canonicalVersionId(), inventoryJson); + return new ScriptDraftDesignDigest( + publicationRequest.tenantId(), + publicationRequest.versionId(), + 0L, + receipt.selectedCommitId().toString(), + contentDigest, + DIGEST_SCHEMA_VERSION); + } + + static String contentDigest( + UUID canonicalTenantId, + long gameDesignVersionRowId, + UUID canonicalVersionId, + String canonicalInventoryJson) { + if (gameDesignVersionRowId <= 0L) { + throw new IllegalArgumentException("Game Design Version row must be positive"); + } + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + Objects.requireNonNull(canonicalInventoryJson, "canonicalInventoryJson"); + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + appendSegment(preimage, DIGEST_DOMAIN); + appendSegment(preimage, Integer.toString(DIGEST_SCHEMA_VERSION)); + appendSegment(preimage, canonicalTenantId.toString()); + appendSegment(preimage, Long.toString(gameDesignVersionRowId)); + appendSegment(preimage, canonicalVersionId.toString()); + appendSegment(preimage, canonicalInventoryJson); + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void requireEmptyReceipt(AutomationEmptySelectedSourceIntakeReceipt receipt) { + if (!"COMMITTED_EMPTY".equals(receipt.outcome()) + || receipt.scriptsRowCount() != 0L + || receipt.eventBindingsRowCount() != 0L + || receipt.patchBaseBindingsRowCount() != 0L + || receipt.unqualifiedScriptsRowCount() != 0L + || receipt.unqualifiedEventBindingsRowCount() != 0L + || receipt.unqualifiedPatchBaseBindingsRowCount() != 0L + || receipt.emptyAssociatedScriptsRowCount() != 0L + || receipt.emptyAssociatedEventBindingsRowCount() != 0L + || receipt.emptyAssociatedPatchBaseBindingsRowCount() != 0L + || receipt.selectedScopeScriptsRowCount() != 0L + || receipt.selectedScopeEventBindingsRowCount() != 0L + || receipt.selectedScopePatchBaseBindingsRowCount() != 0L) { + throw new IllegalStateException( + "Automation selected-empty receipt is incomplete or nonempty"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException(field + " must be a canonical nonzero UUID"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException(field + " must be a canonical nonzero UUID", malformed); + } + } + + private static long canonicalPositiveLong(String value, String field) { + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical positive decimal"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + field + " must be a canonical positive decimal", malformed); + } + } + + private static void appendSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } +} diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java index 3cb23e8d72..d79b05c4d9 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java @@ -3,17 +3,29 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Locale; import java.util.Map; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestService; import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; +import org.jooq.ExecuteContext; import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -263,6 +275,139 @@ void retainsCanonicalEmptyCensusAndExactReadbackAcrossCorrelationIndependentRetr } assertThatThrownBy(() -> repository.readCommittedTerminal(fixture.authorization())) .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + repository.readPublicationScope( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + fixture.authorization().selected().target().gameDesignVersionRowId())) + .isInstanceOf(RuntimeException.class); + } + + @Test + void selectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSixDigest() { + AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture = + AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + AutomationEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + long gameDesignVersionRowId = + fixture.authorization().selected().target().gameDesignVersionRowId(); + + assertThat( + repository + .readPublicationScope( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId) + .canonicalBytes()) + .containsExactly(receipt.canonicalBytes()); + assertThatThrownBy( + () -> + repository.readPublicationScope( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId + 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("missing or ambiguous"); + + var digest = + new AutomationSelectedEmptyPublicationDigestService( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) + .getDraftDesignDigest( + PublicationDigestRequestBinding.full( + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), + Long.toString(gameDesignVersionRowId), + "publish-request-1")); + assertThat(digest.tenantId()) + .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.TENANT.toString()); + assertThat(digest.scopeValue()).isEqualTo(Long.toString(gameDesignVersionRowId)); + assertThat(digest.baseVersionId()).isZero(); + assertThat(digest.appliedCommitId()).isEqualTo(receipt.selectedCommitId().toString()); + String canonicalInventoryJson = + fixture.inputs().ownerSourceInventoryDeclaration().inventory().canonicalJson(); + assertThat(digest.contentDigest()) + .isEqualTo( + expectedSelectedEmptyDigest( + "automation-selected-empty-publication-digest/v1", + "6", + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId, + receipt.canonicalVersionId(), + canonicalInventoryJson)); + assertThat(digest.digestSchemaVersion()) + .isEqualTo(AutomationSelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION); + + var differentPublicationRequest = + new AutomationSelectedEmptyPublicationDigestService( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) + .getDraftDesignDigest( + PublicationDigestRequestBinding.full( + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), + Long.toString(gameDesignVersionRowId), + "publish-request-2")); + assertThat(differentPublicationRequest.contentDigest()).isEqualTo(digest.contentDigest()); + } + + @Test + void publicationScopeScanAndReceiptReadbackUseOneRepeatableReadSnapshot() { + AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture = + AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + AutomationEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + byte[] concurrentlyCorruptedBytes = receipt.canonicalBytes(); + concurrentlyCorruptedBytes[0] ^= 1; + AtomicBoolean concurrentMutationApplied = new AtomicBoolean(); + dsl.configuration() + .set( + new DefaultExecuteListenerProvider( + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql == null + || !sql.toLowerCase(Locale.ROOT) + .contains("from automation_empty_selected_source_association") + || !concurrentMutationApplied.compareAndSet(false, true)) { + return; + } + DSLContext concurrentDsl = DSL.using(dataSource(schema), SQLDialect.POSTGRES); + concurrentDsl.execute( + "ALTER TABLE automation_empty_selected_source_receipt " + + "DISABLE TRIGGER trg_automation_empty_source_receipt_immutable"); + try { + assertThat( + concurrentDsl.execute( + "UPDATE automation_empty_selected_source_receipt " + + "SET receipt_bytes = ? WHERE target_namespace = ? " + + "AND intake_request_id = ?", + concurrentlyCorruptedBytes, + receipt.targetNamespace(), + receipt.intakeRequestId())) + .isEqualTo(1); + } finally { + concurrentDsl.execute( + "ALTER TABLE automation_empty_selected_source_receipt " + + "ENABLE TRIGGER trg_automation_empty_source_receipt_immutable"); + } + } + })); + + AutomationEmptySelectedSourceIntakeReceipt read = + repository.readPublicationScope( + receipt.targetNamespace(), + receipt.canonicalTenantId(), + fixture.authorization().selected().target().gameDesignVersionRowId()); + + assertThat(read.canonicalBytes()).containsExactly(receipt.canonicalBytes()); + assertThat(concurrentMutationApplied).isTrue(); + Record storedReceipt = + dsl.fetchOne( + "SELECT receipt_bytes FROM automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()); + assertThat(storedReceipt).isNotNull(); + assertThat(storedReceipt.get(0, byte[].class)).containsExactly(concurrentlyCorruptedBytes); } @Test @@ -336,6 +481,35 @@ private static String requestDigest( fixture.freezeEvidence()); } + private static String expectedSelectedEmptyDigest( + String domain, + String schemaVersion, + UUID canonicalTenantId, + long gameDesignVersionRowId, + UUID canonicalVersionId, + String canonicalInventoryJson) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + appendDigestSegment(preimage, domain); + appendDigestSegment(preimage, schemaVersion); + appendDigestSegment(preimage, canonicalTenantId.toString()); + appendDigestSegment(preimage, Long.toString(gameDesignVersionRowId)); + appendDigestSegment(preimage, canonicalVersionId.toString()); + appendDigestSegment(preimage, canonicalInventoryJson); + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + + private static void appendDigestSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + private long rowCount(String sql, Object... parameters) { Record record = dsl.fetchOne(sql, parameters); assertThat(record).isNotNull(); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java new file mode 100644 index 0000000000..bed367ea99 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService.ScriptDraftDesignDigest; +import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class AutomationSelectedEmptyPublicationDigestGrpcReceiverTest { + private static final String NAMESPACE = "test"; + private static final String TENANT = "11111111-1111-4111-8111-111111111111"; + private static final String VERSION_ROW = "23"; + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void exactGameDesignPeerWithoutSessionContextCanReadValidatedFullVersionBinding() { + SessionContext.clear(); + AutomationSelectedEmptyPublicationDigestService digestService = + Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7"); + Mockito.when(digestService.getDraftDesignDigest(any(PublicationDigestRequestBinding.class))) + .thenReturn( + new ScriptDraftDesignDigest( + TENANT, VERSION_ROW, 0L, "selected-commit", "b".repeat(64), 6)); + AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver = + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, request(binding)); + + assertEquals("", response.getError().getCode()); + assertEquals(TENANT, response.getTenantId()); + assertEquals(VERSION_ROW, response.getVersionId()); + assertEquals("", response.getBaseVersionId()); + assertEquals("selected-commit", response.getAppliedCommitId()); + assertEquals("b".repeat(64), response.getContentDigest()); + assertEquals(6, response.getDigestSchemaVersion()); + verify(digestService).getDraftDesignDigest(any(PublicationDigestRequestBinding.class)); + } + + @Test + void accountOrGlobalOrScopedRoleContextDeniesEvenTheExactGameDesignPeer() { + AutomationSelectedEmptyPublicationDigestService digestService = + Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class); + AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver = + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + List deniedContexts = + List.of( + () -> SessionContext.setContext("user-1", List.of("player"), Map.of()), + () -> SessionContext.setContext(null, List.of("platformAdmin"), Map.of()), + () -> + SessionContext.setContext( + null, List.of(), Map.of("tenant-1", List.of("designer")))); + for (Runnable setDeniedContext : deniedContexts) { + SessionContext.clear(); + setDeniedContext.run(); + GetDraftDesignDigestResponse response = + invokeAsGameDesign( + receiver, + request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7"))); + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + } + verifyNoInteractions(digestService); + } + + @Test + void changedCompleteRequestBindingIsRejectedBeforeReceiptLookup() { + SessionContext.clear(); + AutomationSelectedEmptyPublicationDigestService digestService = + Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class); + AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver = + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + GetDraftDesignDigestRequest changedRequest = + request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7")).toBuilder() + .setRequestDigest("0".repeat(64)) + .build(); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, changedRequest); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + verifyNoInteractions(digestService); + } + + @Test + void patchScopeIsUnsupportedAndDoesNotReadTheSelectedEmptyReceipt() { + SessionContext.clear(); + AutomationSelectedEmptyPublicationDigestService digestService = + Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class); + AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver = + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.patch(TENANT, VERSION_ROW, "patch-1", "request-7"); + GetDraftDesignDigestRequest request = + GetDraftDesignDigestRequest.newBuilder() + .setTenantId(binding.tenantId()) + .setBaseVersionId(binding.baseVersionId()) + .setScriptPatchVersion(binding.scriptPatchVersion()) + .setPublishRequestId(binding.publishRequestId()) + .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) + .setRequestDigest(binding.requestDigest()) + .build(); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, request); + + assertEquals("UNSUPPORTED_SCOPE", response.getError().getCode()); + verifyNoInteractions(digestService); + } + + private static GetDraftDesignDigestRequest request(PublicationDigestRequestBinding binding) { + return GetDraftDesignDigestRequest.newBuilder() + .setTenantId(binding.tenantId()) + .setVersionId(binding.versionId()) + .setPublishRequestId(binding.publishRequestId()) + .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) + .setRequestDigest(binding.requestDigest()) + .build(); + } + + private static GetDraftDesignDigestResponse invokeAsGameDesign( + AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver, + GetDraftDesignDigestRequest request) { + AtomicReference response = new AtomicReference<>(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", + NAMESPACE, + "game-design-service")) + .run( + () -> + receiver.getDraftDesignDigest( + request, + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + throw new AssertionError(error); + } + + @Override + public void onCompleted() {} + })); + return response.get(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java index 8533583c91..dedcdd68f2 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationEvidence.java @@ -50,11 +50,14 @@ public record AuthoredWorldReleaseAttestationEvidence( public static final int SCHEMA_VERSION = 1; public static final int SELECTOR_SCHEMA_VERSION = 2; public static final int CLOSURE_SELECTOR_SCHEMA_VERSION = 3; + public static final int SELECTED_FULL_SCHEMA_VERSION = 4; private static final String EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v1"; private static final String SELECTOR_EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v2"; private static final String CLOSURE_SELECTOR_EVIDENCE_DOMAIN = "game-design-authored-world-release-attestation/v3"; + private static final String SELECTED_FULL_EVIDENCE_DOMAIN = + "game-design-authored-world-release-attestation/v4"; private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); private static final Pattern PARTICIPANT_CONTENT_DIGEST = Pattern.compile("[0-9a-f]{64}"); private static final Pattern CANONICAL_POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); @@ -88,12 +91,13 @@ public static int supportedParticipantDigestSchema(String participantKey) { return supportedParticipantDigestSchema(participantKey, SCHEMA_VERSION); } - /** Selects owner schemas from the retained-v1, selected-v2, or closure-selected-v3 contract. */ + /** Selects owner schemas from the retained or selected full-Version contract. */ public static int supportedParticipantDigestSchema( String participantKey, int attestationSchemaVersion) { if (attestationSchemaVersion != SCHEMA_VERSION && attestationSchemaVersion != SELECTOR_SCHEMA_VERSION - && attestationSchemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION) { + && attestationSchemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION + && attestationSchemaVersion != SELECTED_FULL_SCHEMA_VERSION) { throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); } Objects.requireNonNull(participantKey, "participantKey"); @@ -101,10 +105,19 @@ public static int supportedParticipantDigestSchema( if (version == null) { throw new IllegalArgumentException("Unsupported full-Version participant owner"); } - if (attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION + if ((attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION + || attestationSchemaVersion == SELECTED_FULL_SCHEMA_VERSION) && "WORLD_MANAGEMENT".equals(participantKey)) { return 4; } + if (attestationSchemaVersion == SELECTED_FULL_SCHEMA_VERSION + && "ENTITY_MANAGEMENT".equals(participantKey)) { + return 3; + } + if (attestationSchemaVersion == SELECTED_FULL_SCHEMA_VERSION + && "AUTOMATION_SCRIPTING".equals(participantKey)) { + return 6; + } return isSelectedSchema(attestationSchemaVersion) && "GAME_DESIGN_CONTROL_PLANE".equals(participantKey) ? 2 @@ -117,7 +130,8 @@ public static boolean requiresWorldStartLocationEvidence(int attestationSchemaVe private static boolean isSelectedSchema(int attestationSchemaVersion) { return attestationSchemaVersion == SELECTOR_SCHEMA_VERSION - || attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION; + || attestationSchemaVersion == CLOSURE_SELECTOR_SCHEMA_VERSION + || attestationSchemaVersion == SELECTED_FULL_SCHEMA_VERSION; } /** One successful, immutable owner digest included in the release attestation. */ @@ -175,7 +189,8 @@ public record Artifact( public AuthoredWorldReleaseAttestationEvidence { if (schemaVersion != SCHEMA_VERSION && schemaVersion != SELECTOR_SCHEMA_VERSION - && schemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION) { + && schemaVersion != CLOSURE_SELECTOR_SCHEMA_VERSION + && schemaVersion != SELECTED_FULL_SCHEMA_VERSION) { throw new IllegalArgumentException("Unsupported authored-world release-attestation schema"); } Objects.requireNonNull(targetNamespace, "targetNamespace"); @@ -373,6 +388,52 @@ public static AuthoredWorldReleaseAttestationEvidence createClosureSelector( worldStartLocationEvidence); } + /** Creates v4 for the complete selected full-Version participant matrix. */ + public static AuthoredWorldReleaseAttestationEvidence createSelectedFull( + String targetNamespace, + String descriptorResultDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + String worldSlug, + UUID authoredWorldSourceOperationId, + String authoredWorldSourceEvidenceDigest, + String launchDescriptorId, + String publishedReleaseBundleRef, + long versionStateEpoch, + String publishWorkflowId, + String commitId, + List participantDigests, + String manifestHash, + int manifestSchemaVersion, + List requiredManifestAssetKeys, + List artifactDigests, + List commandDefinitions, + String generationConfigRevision, + WorldPublishedStartLocationEvidence worldStartLocationEvidence) { + return createSelected( + SELECTED_FULL_SCHEMA_VERSION, + targetNamespace, + descriptorResultDigest, + canonicalTenantId, + canonicalVersionId, + worldSlug, + authoredWorldSourceOperationId, + authoredWorldSourceEvidenceDigest, + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + publishWorkflowId, + commitId, + participantDigests, + manifestHash, + manifestSchemaVersion, + requiredManifestAssetKeys, + artifactDigests, + commandDefinitions, + generationConfigRevision, + worldStartLocationEvidence); + } + private static AuthoredWorldReleaseAttestationEvidence createSelected( int schemaVersion, String targetNamespace, @@ -650,6 +711,7 @@ public static byte[] evidencePreimage(AuthoredWorldReleaseAttestationEvidence ev case SCHEMA_VERSION -> EVIDENCE_DOMAIN; case SELECTOR_SCHEMA_VERSION -> SELECTOR_EVIDENCE_DOMAIN; case CLOSURE_SELECTOR_SCHEMA_VERSION -> CLOSURE_SELECTOR_EVIDENCE_DOMAIN; + case SELECTED_FULL_SCHEMA_VERSION -> SELECTED_FULL_EVIDENCE_DOMAIN; default -> throw new IllegalArgumentException("Unsupported release-attestation schema"); }; return preimage(domain, fields.toArray(Field[]::new)); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java index c538b6d30b..e1e140ec9a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalEvidence.java @@ -83,12 +83,14 @@ public record ReleaseContent( switch (attestationSchemaVersion) { case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; case "v3" -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + case "v4" -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; default -> throw new IllegalArgumentException( - "Complete full-Version bundle/v2 or bundle/v3 required"); + "Complete full-Version bundle/v2, bundle/v3, or bundle/v4 required"); }; if (versionNumber <= 0 || manifestSchemaVersion != 1) { - throw new IllegalArgumentException("Complete full-Version bundle/v2 or bundle/v3 required"); + throw new IllegalArgumentException( + "Complete full-Version bundle/v2, bundle/v3, or bundle/v4 required"); } digest(manifestHash); artifactDigests = List.copyOf(artifactDigests); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java index 6e81e870cf..bc3d2ffb21 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java @@ -109,6 +109,51 @@ void v3BindsClosureQualifiedWorldSchema4InItsOwnDomainAndSurvivesStoredReadback( .hasMessageContaining("Participant digest schema is unsupported"); } + @Test + void v4BindsTheCompleteSelectedFullMatrixInItsOwnDomainAndSurvivesStoredReadback() + throws Exception { + var selector = selectorEvidence(4); + var descriptor = descriptor(selector); + var release = release(descriptor, selector, 4); + var stored = JSON.writeValueAsString(release); + var readback = JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class); + + assertThat(release.schemaVersion()) + .isEqualTo(AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + assertThat(release.participantDigests()) + .extracting(AuthoredWorldReleaseAttestationEvidence.Participant::digestSchemaVersion) + .containsExactly(4, 3, 1, 6, 2); + assertThat(readback).isEqualTo(release); + readback.requireValid(descriptor); + assertThat(readback.worldStartLocationEvidence().canonicalBytes()) + .containsExactly(selector.canonicalBytes()); + assertThat( + new String( + AuthoredWorldReleaseAttestationEvidence.evidencePreimage(release), + StandardCharsets.UTF_8)) + .startsWith("49:game-design-authored-world-release-attestation/v4") + .contains("worldStartLocationEvidence.canonicalBytesBase64") + .endsWith(Base64.getEncoder().encodeToString(selector.canonicalBytes())); + + var retainedAutomationSchema = participantDigestsWithSchema(release, "AUTOMATION_SCRIPTING", 5); + assertThatThrownBy(() -> selectedFull(release, retainedAutomationSchema, selector)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + var retainedEntitySchema = participantDigestsWithSchema(release, "ENTITY_MANAGEMENT", 2); + assertThatThrownBy(() -> selectedFull(release, retainedEntitySchema, selector)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + var retainedWorldSchema = participantDigestsWithSchema(release, "WORLD_MANAGEMENT", 3); + assertThatThrownBy(() -> selectedFull(release, retainedWorldSchema, selector)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + var retainedControlPlaneSchema = + participantDigestsWithSchema(release, "GAME_DESIGN_CONTROL_PLANE", 1); + assertThatThrownBy(() -> selectedFull(release, retainedControlPlaneSchema, selector)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + } + @Test void v1BytesAndDigestRemainUnchangedAndCannotBePromotedBySupplyingASelector() throws Exception { var selector = selectorEvidence(); @@ -154,6 +199,19 @@ void v1BytesAndDigestRemainUnchangedAndCannotBePromotedBySupplyingASelector() th .isInstanceOf(IllegalArgumentException.class); } + @Test + void retainedV1CanonicalByteVectorKeepsItsOriginalDigest() { + var evidence = retainedV1EvidenceVector(); + + assertThat(evidence.evidenceDigest()) + .isEqualTo("sha256:54d38e2af416b25c0c3d05495853124eedd885ed725046052a71e3cc0a6d87e5"); + assertThat( + new String( + AuthoredWorldReleaseAttestationEvidence.evidencePreimage(evidence), + StandardCharsets.UTF_8)) + .startsWith("49:game-design-authored-world-release-attestation/v1"); + } + @Test void selectorSubstitutionAtAnOtherwiseValidCheckpointChangesTheDigest() throws Exception { var selector = selectorEvidence(); @@ -263,6 +321,105 @@ private static List retaine .toList(); } + private static AuthoredWorldReleaseAttestationEvidence retainedV1EvidenceVector() { + var participants = + List.of( + new AuthoredWorldReleaseAttestationEvidence.Participant( + "WORLD_MANAGEMENT", "7", false, null, "commit", "1".repeat(64), 3, false, null), + new AuthoredWorldReleaseAttestationEvidence.Participant( + "ENTITY_MANAGEMENT", "7", false, null, "commit", "2".repeat(64), 2, false, null), + new AuthoredWorldReleaseAttestationEvidence.Participant( + "GAME_LOGIC", + "7", + false, + null, + "commit", + "3".repeat(64), + 1, + true, + "sha256:" + "c".repeat(64)), + new AuthoredWorldReleaseAttestationEvidence.Participant( + "AUTOMATION_SCRIPTING", "7", false, null, "commit", "4".repeat(64), 5, false, null), + new AuthoredWorldReleaseAttestationEvidence.Participant( + "GAME_DESIGN_CONTROL_PLANE", + "7", + false, + null, + "commit", + "5".repeat(64), + 1, + false, + null)); + return AuthoredWorldReleaseAttestationEvidence.create( + "test", + "sha256:" + "a".repeat(64), + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "synthetic-world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "sha256:" + "b".repeat(64), + "descriptor", + "release", + 42L, + "workflow", + "commit", + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + "generation"); + } + + private static List + participantDigestsWithSchema( + AuthoredWorldReleaseAttestationEvidence release, String owner, int schemaVersion) { + return release.participantDigests().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + owner.equals(participant.participantKey()) + ? schemaVersion + : participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) + .toList(); + } + + private static AuthoredWorldReleaseAttestationEvidence selectedFull( + AuthoredWorldReleaseAttestationEvidence basis, + List participants, + WorldPublishedStartLocationEvidence selector) { + return AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + basis.targetNamespace(), + basis.descriptorResultDigest(), + basis.canonicalTenantId(), + basis.canonicalVersionId(), + basis.worldSlug(), + basis.authoredWorldSourceOperationId(), + basis.authoredWorldSourceEvidenceDigest(), + basis.launchDescriptorId(), + basis.publishedReleaseBundleRef(), + basis.versionStateEpoch(), + basis.publishWorkflowId(), + basis.commitId(), + participants, + basis.manifestHash(), + basis.manifestSchemaVersion(), + basis.requiredManifestAssetKeys(), + basis.artifactDigests(), + basis.commandDefinitions(), + basis.generationConfigRevision(), + selector); + } + static WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { return selectorEvidence(3); } @@ -398,6 +555,30 @@ private static AuthoredWorldReleaseAttestationEvidence release( descriptor.generationConfigRevision(), selector); } + if (attestationSchemaVersion + == AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION) { + return AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + selector); + } return AuthoredWorldReleaseAttestationEvidence.create( descriptor.targetNamespace(), descriptor.resultDigest(), diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidenceTest.java index 046da4db0d..978d29a818 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadEvidenceTest.java @@ -3,11 +3,26 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.List; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodecTest; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; class GameDesignPublicationTerminalReadEvidenceTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + @Test void requestAndTerminalRetainDefensiveExactOriginalBytes() throws Exception { var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); @@ -52,4 +67,188 @@ void requestRejectsUnsupportedVersionInvalidNamespaceNilIdentityAndAbsentOperati 1, "test", UUID.randomUUID(), null)) .isInstanceOf(IllegalArgumentException.class); } + + @Test + void selectedFullBundleV4RetainsItsExactWorldBindingAndClosedParticipantMatrix() + throws Exception { + var operation = operationWithWorldSchema4(); + var release = releaseContent(operation, 6, operation.world().request().contentDigest()); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + Outcome.PUBLISHED, + release, + operation.world().request().versionStateEpoch() + 1L); + var readback = GameDesignPublicationTerminalEvidence.fromStored(terminal.canonicalBytes()); + + assertThat(readback.releaseContent().attestationSchemaVersion()).isEqualTo("v4"); + assertThat(readback.releaseContent().participantDigests()) + .extracting(GameDesignPublicationTerminalEvidence.Participant::digestSchemaVersion) + .containsExactly(4, 3, 1, 6, 2); + assertThat(readback.releaseContent().worldStartLocationEvidence().canonicalBytes()) + .containsExactly(operation.world().canonicalBytes()); + assertThat(readback.canonicalBytes()).containsExactly(terminal.canonicalBytes()); + + assertThatThrownBy( + () -> releaseContent(operation, 5, operation.world().request().contentDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Incomplete or changed required participant proof"); + assertThatThrownBy(() -> releaseContent(operation, 6, "f".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("World participant differs from frozen checkpoint"); + } + + private static GameDesignPublicationOperationBinding operationWithWorldSchema4() + throws Exception { + var upstream = + WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); + var applied = + WorldDraftTerminalReadGrpcCodecTest.committedFreshGraphReadbackForStartLocationEvidenceTest( + upstream); + var original = upstream.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var target = draft.target(); + var intent = + new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publication-request", + "5", + "fixture", + draft.requestId(), + draft.commitId(), + draft.digest()); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + intent, + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + // Distinct publication-order source stipulation, not the upstream Draft COMMIT_ORDER vector. + // This structural fixture proves neither current actor authority nor an actual source hold. + var publicationSources = + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + "stipulated-publication-account-source".getBytes(StandardCharsets.UTF_8))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selection), + publicationSources); + var tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + String workflow = + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity(); + var result = JSON.readTree(applied.result()); + var appliedOperation = + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.FrameReader( + Base64.getDecoder().decode(result.get("operationBytesBase64").textValue())); + // Retain the actual intake identity at frame 13 of the existing APPLIED operation. + appliedOperation.expect("world-draft-terminal-operation/v1"); + for (int frame = 1; frame < 13; frame++) { + appliedOperation.bytes(); + } + UUID intakeRequestId = UUID.fromString(appliedOperation.text()); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + target.canonicalTenantId(), + target.canonicalVersionId(), + intakeRequestId, + UUID.randomUUID(), + intent.publishRequestId(), + selection.digest().substring(7), + 5L, + workflow, + draft.commitId().toString(), + "b".repeat(64), + 4, + tuples); + var world = + new WorldPublishedStartLocationEvidence( + request, + Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()), + applied.fullBinding(), + applied.result()); + return new GameDesignPublicationOperationBinding( + account, + world, + net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures.stipulated( + account, world)); + } + + private static GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent( + GameDesignPublicationOperationBinding operation, + int automationDigestSchemaVersion, + String worldContentDigest) { + var selection = operation.account().input().selection(); + var world = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(selection.target().gameDesignVersionRowId()), + null, + world.appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) ? worldContentDigest : "c".repeat(64), + "AUTOMATION_SCRIPTING".equals(owner) + ? automationDigestSchemaVersion + : AuthoredWorldReleaseAttestationEvidence + .supportedParticipantDigestSchema( + owner, + AuthoredWorldReleaseAttestationEvidence + .SELECTED_FULL_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, + null, + null)) + .toList(); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + selection.intent().canonicalTenantId(), + selection.intent().canonicalVersionId(), + "fixture-bundle", + 1, + "v4", + world.publishWorkflowId(), + "sha256:" + "a".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of(), + "generation-1", + operation.world()); + } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java index 58b04324de..229daf2da3 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java @@ -100,6 +100,66 @@ public Optional read( return readValidated(dsl, targetNamespace, intakeRequestId); } + /** + * Resolves the one immutable selected-empty receipt for a canonical tenant and Game Design + * Version row. Every association in the tenant prefix is fully read back before its retained + * original TargetProof is considered; owner-local numeric keys are not publication identity. + */ + public EntityEmptySelectedSourceIntakeReceipt readPublicationScope( + String targetNamespace, UUID canonicalTenantId, long gameDesignVersionRowId) { + requireNoAmbientOwnerSql("Entity publication receipt read"); + requirePublicationScopeKey(targetNamespace, canonicalTenantId, gameDesignVersionRowId); + + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + var associations = + tx.fetch( + "SELECT canonical_version_id, intake_request_id FROM " + + ASSOCIATION + + " WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "ORDER BY canonical_version_id", + targetNamespace, + canonicalTenantId); + if (associations.isEmpty()) { + throw new IllegalStateException( + "Entity selected-empty publication receipt is unavailable"); + } + + var matches = new ArrayList(); + for (Record association : associations) { + UUID associatedCanonicalVersionId = association.get(0, UUID.class); + UUID intakeRequestId = association.get(1, UUID.class); + if (associatedCanonicalVersionId == null || intakeRequestId == null) { + throw new IllegalStateException("Entity publication association identity is corrupt"); + } + EntityEmptySelectedSourceIntakeReceipt receipt = + readValidated(tx, targetNamespace, intakeRequestId) + .orElseThrow( + () -> + new IllegalStateException( + "Entity publication association has no committed receipt")); + var target = receipt.authorizationBinding().selected().target(); + if (!canonicalTenantId.equals(receipt.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(receipt.canonicalVersionId()) + || !canonicalTenantId.equals(target.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(target.canonicalVersionId())) { + throw new IllegalStateException( + "Entity publication association differs from the retained selected target"); + } + if (target.gameDesignVersionRowId() == gameDesignVersionRowId) { + matches.add(receipt); + } + } + if (matches.size() != 1) { + throw new IllegalStateException( + "Entity selected-empty publication scope is missing or ambiguous"); + } + return matches.get(0); + }); + } + /** * Commits a fresh empty catalogue and reads it back independently. A provider missing from the * current Entity schema blocks founding, even if its creator declaration says the family is @@ -799,6 +859,16 @@ private static void requireReadKey(String targetNamespace, UUID intakeRequestId) DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); } + private static void requirePublicationScopeKey( + String targetNamespace, UUID canonicalTenantId, long gameDesignVersionRowId) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || canonicalTenantId == null + || new UUID(0L, 0L).equals(canonicalTenantId) + || gameDesignVersionRowId <= 0L) { + throw new IllegalArgumentException("Entity publication scope identity is required"); + } + } + private static void requireNoAmbientOwnerSql(String label) { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) { diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiver.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiver.java new file mode 100644 index 0000000000..48545091c9 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiver.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.MeterRegistry; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.PublicationReadGuard; +import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.EntityDraftDesignDigest; +import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Unregistered native receiver for the selected-empty Entity publication digest path. */ +public final class EntitySelectedEmptyPublicationDigestGrpcReceiver + extends EntityManagementServiceGrpc.EntityManagementServiceImplBase { + private static final Logger LOGGER = + LoggerFactory.getLogger(EntitySelectedEmptyPublicationDigestGrpcReceiver.class); + + private final EntitySelectedEmptyPublicationDigestService digestService; + private final PublicationReadGuard publicationReadGuard; + private final MeterRegistry meterRegistry; + + public EntitySelectedEmptyPublicationDigestGrpcReceiver( + EntitySelectedEmptyPublicationDigestService digestService, + String configuredNamespace, + MeterRegistry meterRegistry) { + this.digestService = Objects.requireNonNull(digestService, "digestService"); + this.publicationReadGuard = PublicationReadGuard.configured(configuredNamespace); + this.meterRegistry = Objects.requireNonNull(meterRegistry, "meterRegistry"); + } + + @Override + public void getDraftDesignDigest( + GetDraftDesignDigestRequest request, + StreamObserver responseObserver) { + try { + requirePublicationRead(); + if (request.getScopeCase() != GetDraftDesignDigestRequest.ScopeCase.VERSION_ID) { + responseObserver.onNext( + error( + "UNSUPPORTED_SCOPE", + "Entity selected-empty publication supports version_id scope only")); + responseObserver.onCompleted(); + return; + } + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.forScope( + PublicationDigestRequestBinding.ScopeKind.FULL_VERSION, + request.getTenantId(), + request.getVersionId(), + request.getBaseVersionId(), + request.getScriptPatchVersion(), + request.getPublishRequestId()); + binding.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest()); + + EntityDraftDesignDigest digest = digestService.getDraftDesignDigest(binding); + binding.requireOwnerScope(digest.tenantId(), digest.scopeValue()); + responseObserver.onNext( + GetDraftDesignDigestResponse.newBuilder() + .setTenantId(binding.tenantId()) + .setVersionId(binding.versionId()) + .setAppliedCommitId(digest.appliedCommitId()) + .setContentDigest(digest.contentDigest()) + .setDigestSchemaVersion(digest.digestSchemaVersion()) + .build()); + responseObserver.onCompleted(); + } catch (AdminAuthorizationException denied) { + responseObserver.onNext(error("PERMISSION_DENIED", denied.getMessage())); + responseObserver.onCompleted(); + } catch (IllegalArgumentException invalid) { + responseObserver.onNext(error("INVALID_ARGUMENT", invalid.getMessage())); + responseObserver.onCompleted(); + } catch (IllegalStateException unavailable) { + responseObserver.onNext(error("FAILED_PRECONDITION", unavailable.getMessage())); + responseObserver.onCompleted(); + } catch (RuntimeException failure) { + responseObserver.onNext( + GetDraftDesignDigestResponse.newBuilder() + .setError( + GrpcAppErrors.internal(meterRegistry, LOGGER, "GetDraftDesignDigest", failure)) + .build()); + responseObserver.onCompleted(); + } + } + + private void requirePublicationRead() { + if (publicationReadGuard == null) { + throw new AdminAuthorizationException("Publication read authorization is not configured"); + } + publicationReadGuard.requirePublicationRead( + PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD); + } + + private GetDraftDesignDigestResponse error(String code, String message) { + return GetDraftDesignDigestResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, LOGGER, "GetDraftDesignDigest", code, message)) + .build(); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java new file mode 100644 index 0000000000..445b908ff0 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java @@ -0,0 +1,148 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import java.io.ByteArrayOutputStream; +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 net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.EntityDraftDesignDigest; + +/** Unregistered selected-empty full-version digest reader over Entity's retained owner receipt. */ +public final class EntitySelectedEmptyPublicationDigestService { + public static final int DIGEST_SCHEMA_VERSION = 3; + private static final String DIGEST_DOMAIN = "entity-selected-empty-publication-digest/v1"; + + private final String configuredNamespace; + private final EntityEmptySelectedSourceIntakeRepository repository; + + public EntitySelectedEmptyPublicationDigestService( + String configuredNamespace, EntityEmptySelectedSourceIntakeRepository repository) { + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("Configured Entity namespace is required"); + } + this.configuredNamespace = configuredNamespace; + this.repository = Objects.requireNonNull(repository, "repository"); + } + + /** Returns a selected-empty digest only for one exact canonical tenant and GD Version row. */ + public EntityDraftDesignDigest getDraftDesignDigest( + PublicationDigestRequestBinding publicationRequest) { + Objects.requireNonNull(publicationRequest, "publication request is required"); + if (publicationRequest.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw new IllegalArgumentException( + "Entity selected-empty publication supports full versions only"); + } + UUID canonicalTenantId = canonicalUuid(publicationRequest.tenantId(), "tenantId"); + long gameDesignVersionRowId = + canonicalPositiveLong(publicationRequest.versionId(), "versionId"); + + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.readPublicationScope( + configuredNamespace, canonicalTenantId, gameDesignVersionRowId); + var target = receipt.authorizationBinding().selected().target(); + if (!configuredNamespace.equals(receipt.targetNamespace()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !canonicalTenantId.equals(target.canonicalTenantId()) + || target.gameDesignVersionRowId() != gameDesignVersionRowId + || !receipt.canonicalVersionId().equals(target.canonicalVersionId())) { + throw new IllegalStateException( + "Entity selected-empty receipt differs from publication scope"); + } + + var inputs = receipt.inputs(); + if (inputs.authorizationBinding().owner() != Owner.ENTITY_MANAGEMENT) { + throw new IllegalStateException("Entity receipt contains a different owner declaration"); + } + requireEmptyReceipt(receipt); + String inventoryJson = + inputs.ownerSourceInventoryDeclaration().entityInventory().canonicalJson(); + String contentDigest = + contentDigest( + canonicalTenantId, gameDesignVersionRowId, receipt.canonicalVersionId(), inventoryJson); + return new EntityDraftDesignDigest( + publicationRequest.tenantId(), + publicationRequest.versionId(), + receipt.selectedCommitId().toString(), + contentDigest, + DIGEST_SCHEMA_VERSION); + } + + static String contentDigest( + UUID canonicalTenantId, + long gameDesignVersionRowId, + UUID canonicalVersionId, + String canonicalInventoryJson) { + if (gameDesignVersionRowId <= 0L) { + throw new IllegalArgumentException("Game Design Version row must be positive"); + } + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + Objects.requireNonNull(canonicalInventoryJson, "canonicalInventoryJson"); + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + appendSegment(preimage, DIGEST_DOMAIN); + appendSegment(preimage, Integer.toString(DIGEST_SCHEMA_VERSION)); + appendSegment(preimage, canonicalTenantId.toString()); + appendSegment(preimage, Long.toString(gameDesignVersionRowId)); + appendSegment(preimage, canonicalVersionId.toString()); + appendSegment(preimage, canonicalInventoryJson); + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void requireEmptyReceipt(EntityEmptySelectedSourceIntakeReceipt receipt) { + if (receipt.familyStates().size() != 23 + || receipt.familyStates().stream() + .anyMatch( + state -> + state.state() != EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY + || state.rowCount() != 0L + || state.unqualifiedRowCount() != 0L + || state.retainedRowCount() != 0L + || state.selectedScopeRowCount() != 0L + || state.referenceCount() != 0L)) { + throw new IllegalStateException("Entity selected-empty receipt is incomplete or nonempty"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException(field + " must be a canonical nonzero UUID"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException(field + " must be a canonical nonzero UUID", malformed); + } + } + + private static long canonicalPositiveLong(String value, String field) { + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical positive decimal"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + field + " must be a canonical positive decimal", malformed); + } + } + + private static void appendSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } +} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java index 41227af001..f0f474d148 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Path; +import java.util.List; import java.util.Map; import java.util.UUID; import net.firedevops.firemud.test.TestContainerImages; @@ -82,12 +83,23 @@ void dropIsolatedSchema() { @Test void migrationSeedsActualLegacySourceAndAuditTenantVersionKeys() { - assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM entity_empty_source_numeric_key_reservation " - + "WHERE claim_kind = 'LEGACY_NUMERIC'", - Long.class)) - .isEqualTo(5L); + List legacyKeys = + dsl.fetch( + "SELECT key_kind, numeric_key, claim_kind " + + "FROM entity_empty_source_numeric_key_reservation " + + "WHERE claim_kind = 'LEGACY_NUMERIC' ORDER BY key_kind, numeric_key") + .map( + row -> + new ReservedNumericKey( + row.get(0, String.class), + row.get(1, Long.class), + row.get(2, String.class))); + assertThat(legacyKeys) + .containsExactly( + new ReservedNumericKey("TENANT", 31001L, "LEGACY_NUMERIC"), + new ReservedNumericKey("TENANT", 41001L, "LEGACY_NUMERIC"), + new ReservedNumericKey("TENANT", 61001L, "LEGACY_NUMERIC"), + new ReservedNumericKey("VERSION", 51001L, "LEGACY_NUMERIC")); assertLegacyKey("TENANT", 31001L); assertLegacyKey("TENANT", 41001L); assertLegacyKey("TENANT", 61001L); @@ -152,6 +164,8 @@ private void assertRejected(String sql) { assertThatThrownBy(() -> dsl.execute(sql)).isInstanceOf(DataAccessException.class); } + private record ReservedNumericKey(String keyKind, Long numericKey, String claimKind) {} + private DriverManagerDataSource dataSource(String schemaName) { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(postgres.getDriverClassName()); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java index ccde5b99f8..783c5a6dbb 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java @@ -3,20 +3,32 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestService; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; +import org.jooq.ExecuteContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -188,6 +200,129 @@ void existingGlobalEntityRowsAndReferencesDenyFreshGenesisAndRollBackOwnerRecord assertNoCanonicalOwnerRecords(); } + @Test + void selectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGameDesignRow() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + long gameDesignVersionRowId = + fixture.authorization().selected().target().gameDesignVersionRowId(); + + assertThat( + repository + .readPublicationScope( + EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + EntityEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId) + .canonicalBytes()) + .containsExactly(receipt.canonicalBytes()); + assertThatThrownBy( + () -> + repository.readPublicationScope( + EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + EntityEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId + 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("missing or ambiguous"); + + var digest = + new EntitySelectedEmptyPublicationDigestService( + EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) + .getDraftDesignDigest( + PublicationDigestRequestBinding.full( + EntityEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), + Long.toString(gameDesignVersionRowId), + "publish-request-1")); + assertThat(digest.tenantId()) + .isEqualTo(EntityEmptySelectedSourceIntakePostgresFixture.TENANT.toString()); + assertThat(digest.scopeValue()).isEqualTo(Long.toString(gameDesignVersionRowId)); + assertThat(digest.appliedCommitId()).isEqualTo(receipt.selectedCommitId().toString()); + String canonicalInventoryJson = + fixture.inputs().ownerSourceInventoryDeclaration().entityInventory().canonicalJson(); + assertThat(digest.contentDigest()) + .isEqualTo( + expectedSelectedEmptyDigest( + "entity-selected-empty-publication-digest/v1", + "3", + EntityEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId, + receipt.canonicalVersionId(), + canonicalInventoryJson)); + assertThat(digest.digestSchemaVersion()) + .isEqualTo(EntitySelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION); + + var differentPublicationRequest = + new EntitySelectedEmptyPublicationDigestService( + EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) + .getDraftDesignDigest( + PublicationDigestRequestBinding.full( + EntityEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), + Long.toString(gameDesignVersionRowId), + "publish-request-2")); + assertThat(differentPublicationRequest.contentDigest()).isEqualTo(digest.contentDigest()); + } + + @Test + void publicationScopeScanAndReceiptReadbackUseOneRepeatableReadSnapshot() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + byte[] concurrentlyCorruptedBytes = receipt.canonicalBytes(); + concurrentlyCorruptedBytes[0] ^= 1; + AtomicBoolean concurrentMutationApplied = new AtomicBoolean(); + dsl.configuration() + .set( + new DefaultExecuteListenerProvider( + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql == null + || !sql.toLowerCase(Locale.ROOT) + .contains("from entity_empty_selected_source_association") + || !concurrentMutationApplied.compareAndSet(false, true)) { + return; + } + DSLContext concurrentDsl = DSL.using(dataSource(schema), SQLDialect.POSTGRES); + concurrentDsl.execute( + "ALTER TABLE entity_empty_selected_source_receipt " + + "DISABLE TRIGGER trg_entity_empty_source_receipt_immutable"); + try { + assertThat( + concurrentDsl.execute( + "UPDATE entity_empty_selected_source_receipt " + + "SET receipt_bytes = ? WHERE target_namespace = ? " + + "AND intake_request_id = ?", + concurrentlyCorruptedBytes, + receipt.targetNamespace(), + receipt.intakeRequestId())) + .isEqualTo(1); + } finally { + concurrentDsl.execute( + "ALTER TABLE entity_empty_selected_source_receipt " + + "ENABLE TRIGGER trg_entity_empty_source_receipt_immutable"); + } + } + })); + + EntityEmptySelectedSourceIntakeReceipt read = + repository.readPublicationScope( + receipt.targetNamespace(), + receipt.canonicalTenantId(), + fixture.authorization().selected().target().gameDesignVersionRowId()); + + assertThat(read.canonicalBytes()).containsExactly(receipt.canonicalBytes()); + assertThat(concurrentMutationApplied).isTrue(); + var storedReceipt = + dsl.fetchOne( + "SELECT receipt_bytes FROM entity_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()); + assertThat(storedReceipt).isNotNull(); + assertThat(storedReceipt.get(0, byte[].class)).containsExactly(concurrentlyCorruptedBytes); + } + @Test void retainedAuditReferenceWithoutAnItemDeniesFreshGenesis() { var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); @@ -255,6 +390,42 @@ void providerConstraintsAndImmutableReadbackRejectUnknownNonemptyOrChangedState( assertThatThrownBy(() -> repository.read(receipt.targetNamespace(), receipt.intakeRequestId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("provider readback is missing or differs"); + assertThatThrownBy( + () -> + repository.readPublicationScope( + receipt.targetNamespace(), + receipt.canonicalTenantId(), + fixture.authorization().selected().target().gameDesignVersionRowId())) + .isInstanceOf(IllegalStateException.class); + } + + private static String expectedSelectedEmptyDigest( + String domain, + String schemaVersion, + UUID canonicalTenantId, + long gameDesignVersionRowId, + UUID canonicalVersionId, + String canonicalInventoryJson) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + appendDigestSegment(preimage, domain); + appendDigestSegment(preimage, schemaVersion); + appendDigestSegment(preimage, canonicalTenantId.toString()); + appendDigestSegment(preimage, Long.toString(gameDesignVersionRowId)); + appendDigestSegment(preimage, canonicalVersionId.toString()); + appendDigestSegment(preimage, canonicalInventoryJson); + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + + private static void appendDigestSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); } private String requestDigest(EntityEmptySelectedSourceIntakePostgresFixture.Fixture fixture) { diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java new file mode 100644 index 0000000000..a13d9a401a --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java @@ -0,0 +1,145 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.EntityDraftDesignDigest; +import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class EntitySelectedEmptyPublicationDigestGrpcReceiverTest { + private static final String NAMESPACE = "test"; + private static final String TENANT = "11111111-1111-4111-8111-111111111111"; + private static final String VERSION_ROW = "23"; + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void exactGameDesignPeerWithoutSessionContextCanReadValidatedFullVersionBinding() { + SessionContext.clear(); + EntitySelectedEmptyPublicationDigestService digestService = + Mockito.mock(EntitySelectedEmptyPublicationDigestService.class); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7"); + Mockito.when(digestService.getDraftDesignDigest(any(PublicationDigestRequestBinding.class))) + .thenReturn( + new EntityDraftDesignDigest(TENANT, VERSION_ROW, "selected-commit", "a".repeat(64), 3)); + EntitySelectedEmptyPublicationDigestGrpcReceiver receiver = + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, request(binding)); + + assertEquals("", response.getError().getCode()); + assertEquals(TENANT, response.getTenantId()); + assertEquals(VERSION_ROW, response.getVersionId()); + assertEquals("selected-commit", response.getAppliedCommitId()); + assertEquals("a".repeat(64), response.getContentDigest()); + assertEquals(3, response.getDigestSchemaVersion()); + verify(digestService).getDraftDesignDigest(any(PublicationDigestRequestBinding.class)); + } + + @Test + void accountOrGlobalOrScopedRoleContextDeniesEvenTheExactGameDesignPeer() { + EntitySelectedEmptyPublicationDigestService digestService = + Mockito.mock(EntitySelectedEmptyPublicationDigestService.class); + EntitySelectedEmptyPublicationDigestGrpcReceiver receiver = + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + List deniedContexts = + List.of( + () -> SessionContext.setContext("user-1", List.of("player"), Map.of()), + () -> SessionContext.setContext(null, List.of("platformAdmin"), Map.of()), + () -> + SessionContext.setContext( + null, List.of(), Map.of("tenant-1", List.of("designer")))); + for (Runnable setDeniedContext : deniedContexts) { + SessionContext.clear(); + setDeniedContext.run(); + GetDraftDesignDigestResponse response = + invokeAsGameDesign( + receiver, + request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7"))); + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + } + verifyNoInteractions(digestService); + } + + @Test + void changedCompleteRequestBindingIsRejectedBeforeReceiptLookup() { + SessionContext.clear(); + EntitySelectedEmptyPublicationDigestService digestService = + Mockito.mock(EntitySelectedEmptyPublicationDigestService.class); + EntitySelectedEmptyPublicationDigestGrpcReceiver receiver = + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + GetDraftDesignDigestRequest changedRequest = + request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7")).toBuilder() + .setRequestDigest("0".repeat(64)) + .build(); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, changedRequest); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + verifyNoInteractions(digestService); + } + + private static GetDraftDesignDigestRequest request(PublicationDigestRequestBinding binding) { + return GetDraftDesignDigestRequest.newBuilder() + .setTenantId(binding.tenantId()) + .setVersionId(binding.versionId()) + .setPublishRequestId(binding.publishRequestId()) + .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) + .setRequestDigest(binding.requestDigest()) + .build(); + } + + private static GetDraftDesignDigestResponse invokeAsGameDesign( + EntitySelectedEmptyPublicationDigestGrpcReceiver receiver, + GetDraftDesignDigestRequest request) { + AtomicReference response = new AtomicReference<>(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", + NAMESPACE, + "game-design-service")) + .run( + () -> + receiver.getDraftDesignDigest( + request, + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + throw new AssertionError(error); + } + + @Override + public void onCompleted() {} + })); + return response.get(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java index c6fd97f517..11d3341a49 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/PublishedReleaseBundleDto.java @@ -38,7 +38,9 @@ public record PublishedReleaseBundleDto( } artifactDigests = artifactDigests == null ? null : List.copyOf(artifactDigests); boolean selectorSchema = - "v2".equals(attestationSchemaVersion) || "v3".equals(attestationSchemaVersion); + "v2".equals(attestationSchemaVersion) + || "v3".equals(attestationSchemaVersion) + || "v4".equals(attestationSchemaVersion); if (selectorSchema != (worldPublishedStartLocationEvidence != null)) { throw new IllegalArgumentException( "Selector evidence is mandatory for selected release schemas and forbidden historically"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java index 0bfaeda361..9a696bb553 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java @@ -467,7 +467,8 @@ private void requireReleaseMatches( || !Objects.equals(release.canonicalVersionId(), exact.association().canonicalVersionId()) || !Objects.equals(release.publishWorkflowId(), exact.association().publishWorkflowId()) || !("v2".equals(release.attestationSchemaVersion()) - || "v3".equals(release.attestationSchemaVersion())) + || "v3".equals(release.attestationSchemaVersion()) + || "v4".equals(release.attestationSchemaVersion())) || !Objects.equals( release.worldPublishedStartLocationEvidence(), exact.worldPublishedStartLocationEvidence()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java index da6136d1f8..634024b0b7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java @@ -232,7 +232,8 @@ private Result readSnapshot(Request request, StartSessionPostAuthorizationExecut if (!canonicalTenantId.equals(configuredRelease.canonicalTenantId()) || !canonicalVersionId.equals(configuredRelease.canonicalVersionId()) || !("v2".equals(configuredRelease.attestationSchemaVersion()) - || "v3".equals(configuredRelease.attestationSchemaVersion()))) { + || "v3".equals(configuredRelease.attestationSchemaVersion()) + || "v4".equals(configuredRelease.attestationSchemaVersion()))) { throw new IllegalStateException("START_SESSION_CONFIGURED_RELEASE_IDENTITY_CONFLICT"); } workflowId = configuredRelease.publishWorkflowId(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index f77d30f8ea..36d20e1d68 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java @@ -375,7 +375,8 @@ private static void verifySelectorSource(PublishedReleaseBundle bundle, Canonica || !request.canonicalVersionId().equals(source.canonicalVersionId()) || !request.publishWorkflowId().equals(bundle.getPublishWorkflowId()) || ("v2".equals(bundle.getAttestationSchemaVersion()) && request.digestSchemaVersion() != 3) - || ("v3".equals(bundle.getAttestationSchemaVersion()) + || (("v3".equals(bundle.getAttestationSchemaVersion()) + || "v4".equals(bundle.getAttestationSchemaVersion())) && request.digestSchemaVersion() != 4)) { throw new IllegalArgumentException( "World selector differs from exact Version source/workflow"); @@ -383,7 +384,7 @@ private static void verifySelectorSource(PublishedReleaseBundle bundle, Canonica } private static boolean isSelectorSchema(String schemaVersion) { - return "v2".equals(schemaVersion) || "v3".equals(schemaVersion); + return "v2".equals(schemaVersion) || "v3".equals(schemaVersion) || "v4".equals(schemaVersion); } private record CanonicalSource(UUID canonicalTenantId, UUID canonicalVersionId) {} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java index 92998f033a..1d4e12a856 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java @@ -136,7 +136,31 @@ public CompleteLaunchBindingDto getCompleteLaunchBinding( requireManifestAndArtifactEvidence(bundle); AuthoredWorldReleaseAttestationEvidence releaseAttestation; - if (PublishedReleaseBundleContract.CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( + if (PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals( + bundle.attestationSchemaVersion())) { + releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + descriptor.targetNamespace(), + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersion.getCanonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + bundle.publishWorkflowId(), + commitId, + participants, + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + artifacts, + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.worldPublishedStartLocationEvidence()); + } else if (PublishedReleaseBundleContract.CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION.equals( bundle.attestationSchemaVersion())) { releaseAttestation = AuthoredWorldReleaseAttestationEvidence.createClosureSelector( @@ -368,6 +392,7 @@ private List requirePartici case "v1" -> AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION; case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; case "v3" -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + case "v4" -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; case null, default -> throw deny( "PARTICIPANT_EVIDENCE_INVALID", diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java index 7a236e1c59..9741f63ff2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java @@ -267,7 +267,7 @@ public void assertSelectedGatePassed( int selectedAttestationSchema = switch (worldDigests.getFirst().digestSchemaVersion()) { case 3 -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; - case 4 -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + case 4 -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; default -> throw new PublishGateFailureException( PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java index 481be5f442..8008b6e275 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java @@ -15,6 +15,7 @@ final class PublishedReleaseBundleContract { static final String SUPPORTED_ATTESTATION_SCHEMA_VERSION = "v1"; static final String SELECTOR_ATTESTATION_SCHEMA_VERSION = "v2"; static final String CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION = "v3"; + static final String SELECTED_FULL_ATTESTATION_SCHEMA_VERSION = "v4"; static final String SCHEMA_VERSION_UNSUPPORTED = "SCHEMA_VERSION_UNSUPPORTED"; static final String REPAIR_ATTESTATION_MISMATCH = "REPAIR_ATTESTATION_MISMATCH"; static final String REPAIR_ATTESTED_ASSET_KEY_MISMATCH = "REPAIR_ATTESTED_ASSET_KEY_MISMATCH"; @@ -36,6 +37,8 @@ static void requireSelectorBinding(PublishedReleaseBundleDto bundle) { AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; case CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + case SELECTED_FULL_ATTESTATION_SCHEMA_VERSION -> + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; default -> throw new IllegalArgumentException( "World selector requires a selected publication release schema"); @@ -104,10 +107,25 @@ static void requireExactSelectorRetry( "IDEMPOTENCY_CONFLICT: historical release is selector-ineligible"); } requireSelectorBinding(stored); + var automation = + participants.stream() + .filter(participant -> "AUTOMATION_SCRIPTING".equals(participant.participantKey())) + .toList(); + if (automation.size() != 1 || automation.getFirst().digestSchemaVersion() == null) { + throw new IllegalStateException("IDEMPOTENCY_CONFLICT: exact Automation schema required"); + } + int automationSchema = automation.getFirst().digestSchemaVersion(); String requestedSchema = switch (evidence.request().digestSchemaVersion()) { case 3 -> SELECTOR_ATTESTATION_SCHEMA_VERSION; - case 4 -> CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION; + case 4 -> + switch (automationSchema) { + case 5 -> CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION; + case 6 -> SELECTED_FULL_ATTESTATION_SCHEMA_VERSION; + default -> + throw new IllegalStateException( + "IDEMPOTENCY_CONFLICT: unsupported selected Automation schema"); + }; default -> throw new IllegalStateException( "IDEMPOTENCY_CONFLICT: unsupported retained World selector schema"); @@ -196,6 +214,7 @@ static void requireExactRepairMatch( static boolean isSelectorSchema(String schemaVersion) { return SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(schemaVersion) - || CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(schemaVersion); + || CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION.equals(schemaVersion) + || SELECTED_FULL_ATTESTATION_SCHEMA_VERSION.equals(schemaVersion); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index 1453e04bc3..a2e3a3f45b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -152,7 +152,7 @@ private PublishedReleaseBundleDto createBundle( entity.setAttestationSchemaVersion( worldEvidence == null ? PublishedReleaseBundleContract.SUPPORTED_ATTESTATION_SCHEMA_VERSION - : PublishedReleaseBundleContract.CLOSURE_SELECTOR_ATTESTATION_SCHEMA_VERSION); + : PublishedReleaseBundleContract.SELECTED_FULL_ATTESTATION_SCHEMA_VERSION); entity.setWorldPublishedStartLocationEvidenceJson( worldEvidence == null ? null diff --git a/services/game-design-service/src/main/resources/db/migration/V72__selected_full_semantic_owner_attestation.sql b/services/game-design-service/src/main/resources/db/migration/V72__selected_full_semantic_owner_attestation.sql new file mode 100644 index 0000000000..8460300129 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V72__selected_full_semantic_owner_attestation.sql @@ -0,0 +1,273 @@ +-- Add the selected-full semantic owner profile without rewriting retained release evidence. +-- v4 binds World 4, Entity 3 and Automation 6; v1/v2/v3 retain their original bytes and owner schemas. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION enforce_published_world_start_location_evidence() RETURNS trigger AS $$ +DECLARE + evidence JSONB; + selection JSONB; + applied JSONB; + receipt JSONB; + participants JSONB; + item JSONB; + owner_key TEXT; + required_schema INTEGER; + required_world_schema INTEGER; + required_entity_schema INTEGER; + required_automation_schema INTEGER; + field_name TEXT; + account_bytes BYTEA; + operation_bytes BYTEA; + draft JSONB; + affected JSONB; +BEGIN + IF NEW.attestation_schema_version NOT IN ('v2', 'v3', 'v4') THEN + IF NEW.world_published_start_location_evidence_json IS NOT NULL THEN + RAISE EXCEPTION 'historical release schemas cannot carry a World selector' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + required_world_schema := CASE NEW.attestation_schema_version WHEN 'v2' THEN 3 ELSE 4 END; + required_entity_schema := CASE NEW.attestation_schema_version WHEN 'v4' THEN 3 ELSE 2 END; + required_automation_schema := CASE NEW.attestation_schema_version WHEN 'v4' THEN 6 ELSE 5 END; + + IF NEW.world_published_start_location_evidence_json IS NULL + OR NEW.script_only OR NEW.script_patch_version IS NOT NULL + OR NEW.canonical_tenant_id IS NULL OR NEW.canonical_version_id IS NULL + OR NEW.manifest_schema_version IS NULL OR NEW.artifact_digests_json IS NULL THEN + RAISE EXCEPTION 'selected release requires complete full-Version selector evidence' + USING ERRCODE = 'check_violation'; + END IF; + evidence := NEW.world_published_start_location_evidence_json::JSONB; + selection := evidence->'request'; + FOR field_name IN SELECT unnest(ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'publishWorkflowId','appliedCommitId','contentDigest']) + LOOP + IF jsonb_typeof(selection->field_name) IS DISTINCT FROM 'string' + OR coalesce(selection->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected release has missing selection text binding' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + IF jsonb_typeof(evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(evidence)) <> 5 + OR NOT evidence ?& ARRAY['schema','request','selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64'] + OR evidence->>'schema' IS DISTINCT FROM 'world-published-start-location-evidence/v1' + OR jsonb_typeof(selection) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(selection)) <> 13 + OR NOT selection ?& ARRAY['targetNamespace','canonicalTenantId','canonicalVersionId', + 'intakeRequestId','publicationFence','publicationRequestId','requestDigest', + 'versionStateEpoch','publishWorkflowId','appliedCommitId','contentDigest', + 'digestSchemaVersion','worldAffectedTuples'] + OR selection->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR selection->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR selection->>'publishWorkflowId' IS DISTINCT FROM NEW.publish_workflow_id + OR selection->>'targetNamespace' !~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + OR selection->>'intakeRequestId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'intakeRequestId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'publicationFence' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'publicationFence')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR selection->>'appliedCommitId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (selection->>'appliedCommitId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR coalesce(selection->>'publicationRequestId','') = '' + OR selection->>'requestDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'contentDigest' !~ '^[0-9a-f]{64}$' + OR selection->>'versionStateEpoch' !~ '^[1-9][0-9]*$' + OR jsonb_typeof(selection->'versionStateEpoch') IS DISTINCT FROM 'string' + OR length(selection->>'versionStateEpoch') > 19 + OR (length(selection->>'versionStateEpoch') = 19 + AND selection->>'versionStateEpoch' > '9223372036854775807') + OR jsonb_typeof(selection->'digestSchemaVersion') IS DISTINCT FROM 'number' + OR selection->>'digestSchemaVersion' IS DISTINCT FROM required_world_schema::TEXT + OR jsonb_typeof(selection->'worldAffectedTuples') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'selected World selection has missing, unsupported or mismatched bindings' + USING ERRCODE = 'check_violation'; + END IF; + IF jsonb_array_length(selection->'worldAffectedTuples') = 0 THEN + RAISE EXCEPTION 'selected release requires the complete World affected set' USING ERRCODE = 'check_violation'; + END IF; + -- Binary Account and APPLIED bytes remain intact; Java independently checks their full relation. + IF jsonb_typeof(evidence->'originalAccountBindingBytesBase64') IS DISTINCT FROM 'string' + OR octet_length(decode(evidence->>'originalAccountBindingBytesBase64','base64')) = 0 + OR jsonb_typeof(evidence->'appliedResultBytesBase64') IS DISTINCT FROM 'string' + OR jsonb_typeof(evidence->'selectorReceiptBytesBase64') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'selected release requires complete original owner bytes' + USING ERRCODE = 'check_violation'; + END IF; + applied := convert_from(decode(evidence->>'appliedResultBytesBase64','base64'),'UTF8')::JSONB; + receipt := convert_from(decode(evidence->>'selectorReceiptBytesBase64','base64'),'UTF8')::JSONB; + FOR field_name IN SELECT unnest(ARRAY['selectorReceiptBytesBase64', + 'originalAccountBindingBytesBase64','appliedResultBytesBase64']) + LOOP + IF replace(encode(decode(evidence->>field_name,'base64'),'base64'), E'\n','') + IS DISTINCT FROM evidence->>field_name THEN + RAISE EXCEPTION 'selected release owner bytes are not canonical base64' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest']) + LOOP + IF jsonb_typeof(applied->field_name) IS DISTINCT FROM 'string' + OR coalesce(applied->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected APPLIED result has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + FOR field_name IN SELECT unnest(ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','graphDigest','receiptDigest']) + LOOP + IF jsonb_typeof(receipt->field_name) IS DISTINCT FROM 'string' + OR coalesce(receipt->>field_name,'') = '' THEN + RAISE EXCEPTION 'selected selector receipt has missing bindings' USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + account_bytes := decode(evidence->>'originalAccountBindingBytesBase64','base64'); + operation_bytes := decode(applied->>'operationBytesBase64','base64'); + draft := convert_from(published_world_selector_frame(account_bytes, 11),'UTF8')::JSONB; + SELECT coalesce(jsonb_agg(unit ORDER BY unit->>'owner', unit->>'aggregateType', + unit->>'aggregateId', unit->>'scopeType', unit->>'scopeId', unit->>'expectedEpoch'),'[]'::JSONB) + INTO affected FROM jsonb_array_elements(draft->'affectedUnits') unit + WHERE unit->>'owner' = 'WORLD_MANAGEMENT'; + IF applied->>'schema' IS DISTINCT FROM 'world-draft-graph-applied/v2' + OR applied->>'status' IS DISTINCT FROM 'APPLIED' + OR applied->>'startLocationReceiptBase64' IS DISTINCT FROM evidence->>'selectorReceiptBytesBase64' + OR receipt->>'schema' IS DISTINCT FROM 'world-draft-start-location-receipt/v1' + OR receipt->>'targetNamespace' IS DISTINCT FROM selection->>'targetNamespace' + OR receipt->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR receipt->'startLocation'->>'tenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR receipt->'startLocation'->>'versionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->>'graphDigest' IS DISTINCT FROM applied->>'graphDigest' + OR receipt->>'receiptDigest' IS DISTINCT FROM applied->>'startLocationReceiptDigest' + OR jsonb_typeof(applied) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(applied)) <> 8 + OR NOT applied ?& ARRAY['schema','status','operationBytesBase64','graphBytesBase64', + 'graphDigest','startLocationReceiptBase64','startLocationReceiptDigest','appliedEpochs'] + OR jsonb_typeof(receipt) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt)) <> 11 + OR NOT receipt ?& ARRAY['schema','targetNamespace','operationId','requestId','commitId', + 'authorizationFenceId','accountBindingDigest','bindingDigest','startLocation','graphDigest','receiptDigest'] + OR jsonb_typeof(receipt->'startLocation') IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(receipt->'startLocation')) <> 3 + OR NOT (receipt->'startLocation') ?& ARRAY['tenantId','versionId','roomTemplateId'] + OR selection->'worldAffectedTuples' IS DISTINCT FROM affected + OR draft->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR draft->>'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR draft->>'commitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR draft->'target'->>'gameDesignVersionRowId' IS DISTINCT FROM NEW.version_id::TEXT + OR draft->'target'->>'gameDesignVersionTenantKey' IS DISTINCT FROM NEW.tenant_id + OR published_world_selector_frame(account_bytes, 11) IS DISTINCT FROM published_world_selector_frame(account_bytes, 12) + OR published_world_selector_frame(operation_bytes, 7) IS DISTINCT FROM published_world_selector_frame(account_bytes, 11) + OR convert_from(published_world_selector_frame(account_bytes, 13),'UTF8') IS DISTINCT FROM receipt->>'bindingDigest' + OR receipt->>'accountBindingDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(account_bytes),'hex') + OR applied->>'graphDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(decode(applied->>'graphBytesBase64','base64')),'hex') + OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1' + OR convert_from(published_world_selector_frame(account_bytes, 1),'UTF8') IS DISTINCT FROM receipt->>'operationId' + OR convert_from(published_world_selector_frame(account_bytes, 2),'UTF8') IS DISTINCT FROM receipt->>'requestId' + OR convert_from(published_world_selector_frame(account_bytes, 3),'UTF8') IS DISTINCT FROM selection->>'appliedCommitId' + OR convert_from(published_world_selector_frame(account_bytes, 4),'UTF8') IS DISTINCT FROM receipt->>'authorizationFenceId' + OR convert_from(published_world_selector_frame(account_bytes, 6),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(account_bytes, 7),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 0),'UTF8') IS DISTINCT FROM 'world-draft-terminal-operation/v1' + OR published_world_selector_frame(operation_bytes, 20) IS DISTINCT FROM account_bytes + OR convert_from(published_world_selector_frame(operation_bytes, 13),'UTF8') IS DISTINCT FROM selection->>'intakeRequestId' + OR convert_from(published_world_selector_frame(operation_bytes, 8),'UTF8') IS DISTINCT FROM selection->>'targetNamespace' + OR convert_from(published_world_selector_frame(operation_bytes, 9),'UTF8') IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(operation_bytes, 10),'UTF8') IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR receipt->'startLocation'->>'roomTemplateId' IS NULL THEN + RAISE EXCEPTION 'selected selector differs from original APPLIED receipt' + USING ERRCODE = 'check_violation'; + END IF; + participants := NEW.participant_digests_json::JSONB; + IF jsonb_typeof(participants) IS DISTINCT FROM 'array' OR jsonb_array_length(participants) <> 5 THEN + RAISE EXCEPTION 'selected release requires all five participant owners' USING ERRCODE = 'check_violation'; + END IF; + FOR owner_key, required_schema IN SELECT * FROM (VALUES + ('WORLD_MANAGEMENT',required_world_schema),('ENTITY_MANAGEMENT',required_entity_schema),('GAME_LOGIC',1), + ('AUTOMATION_SCRIPTING',required_automation_schema),('GAME_DESIGN_CONTROL_PLANE',2)) owners(owner_key, required_schema) + LOOP + IF (SELECT count(*) FROM jsonb_array_elements(participants) p + WHERE p->>'participantKey' = owner_key) <> 1 THEN + RAISE EXCEPTION 'selected release has missing or duplicate participant owner' USING ERRCODE = 'check_violation'; + END IF; + SELECT p INTO item FROM jsonb_array_elements(participants) p WHERE p->>'participantKey' = owner_key; + IF item->>'scopeValue' IS DISTINCT FROM NEW.version_id::TEXT + OR item->>'baseVersionId' IS NOT NULL + OR item->>'appliedCommitId' IS DISTINCT FROM selection->>'appliedCommitId' + OR item->>'digestSchemaVersion' IS DISTINCT FROM required_schema::TEXT + OR coalesce(item->>'contentDigest','') !~ '^[0-9a-f]{64}$' + OR coalesce(item->>'errorCode','') <> '' + OR (owner_key = 'WORLD_MANAGEMENT' AND item->>'contentDigest' IS DISTINCT FROM selection->>'contentDigest') + OR (owner_key = 'GAME_LOGIC' AND coalesce(item->>'abilitySchemaDigest','') !~ '^sha256:[0-9a-f]{64}$') THEN + RAISE EXCEPTION 'selected participant differs from commit/digest/schema' + USING ERRCODE = 'check_violation'; + END IF; + END LOOP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION guard_selected_publication_release() RETURNS trigger AS $$ +DECLARE attempt publish_attempt%ROWTYPE; operation game_design_publication_operation%ROWTYPE; +BEGIN + IF NEW.script_only THEN RETURN NEW; END IF; + -- Old unselected history keeps its original read semantics; no operation is backfilled. + IF NEW.attestation_schema_version NOT IN ('v2', 'v3', 'v4') AND NOT EXISTS (SELECT 1 FROM game_design_authored_draft_publish_selection + WHERE game_design_version_tenant_key = NEW.tenant_id AND game_design_version_row_id = NEW.version_id) THEN + RETURN NEW; + END IF; + PERFORM 1 FROM game WHERE tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT attempt FROM publish_attempt WHERE publish_workflow_id = NEW.publish_workflow_id FOR UPDATE; + PERFORM 1 FROM version WHERE id = NEW.version_id AND tenant_id = NEW.tenant_id FOR UPDATE; + SELECT * INTO STRICT operation FROM game_design_publication_operation WHERE publish_workflow_id = NEW.publish_workflow_id; + IF attempt.status <> 'PENDING' OR operation.outcome <> 'PENDING' + OR operation.tenant_id <> NEW.tenant_id OR operation.version_id <> NEW.version_id + OR attempt.request_digest IS DISTINCT FROM operation.selection_digest + OR NEW.attestation_schema_version NOT IN ('v2', 'v3', 'v4') + OR convert_to(NEW.world_published_start_location_evidence_json, 'UTF8') + IS DISTINCT FROM published_world_selector_frame(operation.request_bytes, 2) THEN + RAISE EXCEPTION 'selected publication is absent, sealed, or changed' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE OR REPLACE FUNCTION publication_release_content(release published_release_bundle) RETURNS BYTEA AS $$ +DECLARE result BYTEA; entry BYTEA; item JSONB; +BEGIN + IF release.script_only OR release.script_patch_version IS NOT NULL + OR release.attestation_schema_version NOT IN ('v2', 'v3', 'v4') THEN + RAISE EXCEPTION 'terminal publication requires complete full-version selected content' USING ERRCODE = 'check_violation'; + END IF; + result := publication_content_text('game-design-published-release-bundle/v1') + || publication_content_text(release.canonical_tenant_id::TEXT) + || publication_content_text(release.canonical_version_id::TEXT) + || publication_content_text(release.published_release_bundle_ref) + || publication_content_text(release.version_number::TEXT) + || publication_content_text(release.attestation_schema_version) + || publication_content_text(release.publish_workflow_id) + || publication_content_text(release.manifest_hash) + || publication_content_text(release.manifest_schema_version::TEXT) + || publication_content_text(jsonb_array_length(release.artifact_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.artifact_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'usageKey') || publication_content_text(item->>'artifactKind') + || publication_content_text(item->>'immutableObjectKey') || publication_content_text(item->>'contentDigest') + || publication_content_text(item->>'contentType') || publication_content_text(item->>'artifactSchemaVersion'); + result := result || publication_content_frame(entry); + END LOOP; + result := result || publication_content_strings(release.required_manifest_asset_keys_json::JSONB) + || publication_content_text(jsonb_array_length(release.participant_digests_json::JSONB)::TEXT); + FOR item IN SELECT * FROM jsonb_array_elements(release.participant_digests_json::JSONB) LOOP + entry := publication_content_text(item->>'participantKey') || publication_content_text(item->>'scopeValue') + || publication_content_optional(item->>'baseVersionId') || publication_content_text(item->>'appliedCommitId') + || publication_content_text(item->>'contentDigest') || publication_content_text(item->>'digestSchemaVersion') + || publication_content_optional(item->>'abilitySchemaDigest') || publication_content_optional(item->>'errorCode') + || publication_content_optional(item->>'errorMessage'); + result := result || publication_content_frame(entry); + END LOOP; + RETURN result || publication_content_strings(release.command_definitions_json::JSONB) + || publication_content_text(release.generation_config_revision) + || publication_content_text(release.world_published_start_location_evidence_json) + || publication_content_text('false') || publication_content_optional(NULL); +END; +$$ LANGUAGE plpgsql STABLE STRICT; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java index ea2710977f..808094c61d 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -40,6 +40,27 @@ public static WorldPublishedStartLocationEvidence closureEvidence(TargetProof ta return new PublishedWorldSelectorFixtures(target).build(4); } + public static List + selectedFullParticipants(long versionId, WorldPublishedStartLocationEvidence evidence) { + return participants(versionId, evidence).stream() + .map( + participant -> + ("AUTOMATION_SCRIPTING".equals(participant.participantKey()) + || "ENTITY_MANAGEMENT".equals(participant.participantKey())) + ? new net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + "ENTITY_MANAGEMENT".equals(participant.participantKey()) ? 3 : 6, + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) + .toList(); + } + public static List participants(long versionId, WorldPublishedStartLocationEvidence evidence) { return net diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index b766bcd698..b7a7b45c54 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -2,9 +2,7 @@ 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.when; import com.google.protobuf.ByteString; import com.google.protobuf.Timestamp; @@ -19,6 +17,7 @@ import io.grpc.stub.StreamObserver; import io.grpc.util.MutableHandlerRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; @@ -52,12 +51,15 @@ import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeTerminalReadService; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestGrpcReceiver; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestService; import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedSourceIntakeCommandGrpcService; import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedSourceIntakeTerminalReadGrpcService; import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeAuthorizationGrpcClient; import net.firedevops.firemud.common.account.sourceintake.AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient; import net.firedevops.firemud.common.account.sourceintake.GrpcSelectedOwnerIntakeSourceReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence; @@ -140,9 +142,14 @@ import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeService; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeTerminalReadService; +import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestGrpcReceiver; +import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestService; import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedSourceIntakeCommandGrpcService; import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedSourceIntakeTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.client.AutomationScriptingClient; +import net.firedevops.firemud.gamedesign.client.EntityManagementClient; import net.firedevops.firemud.gamedesign.client.GameLogicClient; +import net.firedevops.firemud.gamedesign.client.WorldManagementClient; import net.firedevops.firemud.gamedesign.client.WorldPublishedStartLocationClient; import net.firedevops.firemud.gamedesign.config.AssetStoreProperties; import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; @@ -188,6 +195,7 @@ import net.firedevops.firemud.gamedesign.repository.PublishAttemptParticipantDigestRepository; import net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; @@ -201,8 +209,6 @@ import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptService; -import net.firedevops.firemud.gamedesign.service.PublishGateService; -import net.firedevops.firemud.gamedesign.service.RecordedParticipantDigestService; import net.firedevops.firemud.gamedesign.service.RevisionService; import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; @@ -216,7 +222,9 @@ import net.firedevops.firemud.gamedesign.service.impl.GameDesignGrpcService; import net.firedevops.firemud.gamedesign.service.impl.LaunchDescriptorServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.PublishAttemptServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.PublishGateServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.PublishedReleaseBundleServiceImpl; +import net.firedevops.firemud.gamedesign.service.impl.RecordedParticipantDigestServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.TemplateRemapSetServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflowMetadataResolver; import net.firedevops.firemud.gamedesign.service.impl.TenantIdentityGrpcService; @@ -317,14 +325,15 @@ * disclosure/abort setup uses stipulated incoming Game Design peer contexts and is not either * positive authorization operation. Entity retention also traverses the native Account, Game * Design, Entity, World and settlement boundaries over loopback mTLS, with an isolated Entity - * PostgreSQL schema and migration path. Entity/Automation publication participant digests and the - * StartSession Account projection remain test doubles. MinIO object-store I/O is real. The complete - * launch-binding case wires the actual Game Design handler and World Management mTLS client on this - * fixture's loopback server to the actual owner implementation in an explicitly established - * read-only repeatable-read snapshot; unrelated handler dependencies are isolated. This fixture - * does not provide production-mounted certificates or full application server wiring, production - * ingress, Account-projection-backed StartSession admission, a complete four-owner authenticated - * release, runtime launch, activation or registration. + * PostgreSQL schema and migration path. Entity and Automation publication digests use their native + * mTLS selected-empty owner readers and exact retained receipts; nonempty owner publication remains + * outside this proof. The StartSession Account projection remains a test double. MinIO object-store + * I/O is real. The complete launch-binding case wires the actual Game Design handler and World + * Management mTLS client on this fixture's loopback server to the actual owner implementation in an + * explicitly established read-only repeatable-read snapshot; unrelated handler dependencies are + * isolated. This fixture does not provide production-mounted certificates or full application + * server wiring, production ingress, Account-projection-backed StartSession admission, runtime + * launch, activation or registration. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -964,6 +973,19 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex register( entityHandlers, new EntitySelectedSourceIntakeCommandGrpcService(entityIntakeOwner, NAMESPACE)); + register( + automationHandlers, + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + new AutomationSelectedEmptyPublicationDigestService( + NAMESPACE, automationIntakeRepository), + NAMESPACE, + new SimpleMeterRegistry())); + register( + entityHandlers, + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + new EntitySelectedEmptyPublicationDigestService(NAMESPACE, entityIntakeRepository), + NAMESPACE, + new SimpleMeterRegistry())); var selectedOwnerSettlementOwner = new AccountSelectedOwnerIntakeSettlementService( accountSelectedOwnerSourceRepository, @@ -2278,16 +2300,6 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex exporter, releaseService, new ObjectMapper()); - var participantDigests = - selectedSelectorParticipantDigests( - selectedCommit, - gd.target().gameDesignVersionRowId(), - retainedWorldDigest, - actualDesignDigest, - actualGameLogicDigest); - var gate = mock(PublishGateService.class); - when(gate.collectSelectedFullVersionParticipantDigests(any(), any(), any())) - .thenReturn(participantDigests); var controlPlaneDigests = new net.firedevops.firemud.gamedesign.service.impl.ControlPlaneDigestServiceImpl( new net.firedevops.firemud.gamedesign.repository.GameTemplateRepository(gd.dsl()), @@ -2310,42 +2322,286 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var realAttemptPersistence = new PublishAttemptServiceImpl( publishAttemptRepository, new PublishAttemptParticipantDigestRepository(gd.dsl())); - var publisher = - new VersionPublishCommandServiceImpl( - new VersionRepository(gd.dsl()), - new GameRepository(gd.dsl()), - publishAttemptRepository, - mapper, - exporter, - transactionBoundPublishAttempts(gd, realAttemptPersistence), - gate, - controlPlaneDigests, - artifactService, - releaseService, - mock(RecordedParticipantDigestService.class)); - var published = - publisher.publishSelectedDraftFullVersion( - gd.target().gameDesignVersionTenantKey(), + var recordedParticipantDigests = + new RecordedParticipantDigestServiceImpl( + new RecordedParticipantDigestRepository(gd.dsl())); + var publicationVersion = + gd.transaction( + () -> + mapper.toDto( + new VersionRepository(gd.dsl()) + .findByTenantIdAndId( + gd.target().gameDesignVersionTenantKey(), + gd.target().gameDesignVersionRowId()) + .orElseThrow())); + var entityInventoryJson = + persistedEntityReceipt + .inputs() + .ownerSourceInventoryDeclaration() + .entityInventory() + .canonicalJson(); + assertThat(entityInventoryJson).isEqualTo(authoredEntityInventory.canonicalJson()); + var automationDigestInputs = + new SelectedOwnerEmptySourceInputs( + automationReceipt.authorizationBinding(), + automationReceipt.worldInventoryReadEvidence()); + var automationInventoryJson = + automationDigestInputs.ownerSourceInventoryDeclaration().inventory().canonicalJson(); + assertThat(automationInventoryJson).isEqualTo(authoredAutomationInventory.canonicalJson()); + assertThat(persistedEntityReceipt.canonicalVersionId()) + .isEqualTo(gd.target().canonicalVersionId()); + assertThat(automationReceipt.canonicalVersionId()) + .isEqualTo(gd.target().canonicalVersionId()); + String expectedEntityContentDigest = + selectedEmptyPublicationDigest( + "entity-selected-empty-publication-digest/v1", + 3, + gd.target().canonicalTenantId(), gd.target().gameDesignVersionRowId(), - intent.notes(), - publishRequestId, - publicationRequest.derivedWorkflowIdentity()); - assertThat(published.versionState()).isEqualTo(VersionLifecycleState.PUBLISHED); - assertThat( - new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository(gd.dsl()) - .findByPublishWorkflowId(publicationRequest.derivedWorkflowIdentity()) - .orElseThrow() - .getStatus()) - .isEqualTo(net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); + persistedEntityReceipt.canonicalVersionId(), + entityInventoryJson); + String expectedAutomationContentDigest = + selectedEmptyPublicationDigest( + "automation-selected-empty-publication-digest/v1", + 6, + gd.target().canonicalTenantId(), + gd.target().gameDesignVersionRowId(), + automationReceipt.canonicalVersionId(), + automationInventoryJson); + + List selectedReleaseParticipants; + var worldDigestClient = + new WorldManagementClient( + endpoints, + pki.client("game-design-service"), + channels, + BlockingGrpcStubCustomizer.noop()); + var entityDigestClient = + new EntityManagementClient( + endpoints, + pki.client("game-design-service"), + channels, + BlockingGrpcStubCustomizer.noop()); + var automationDigestClient = + new AutomationScriptingClient( + endpoints, + pki.client("game-design-service"), + channels, + BlockingGrpcStubCustomizer.noop()); + var gameLogicGateClient = + new GameLogicClient( + endpoints, + pki.client("game-design-service"), + channels, + BlockingGrpcStubCustomizer.noop()); + var wrongPeerEntityDigestClient = + new EntityManagementClient( + endpoints, + pki.client("world-management-service"), + channels, + BlockingGrpcStubCustomizer.noop()); + var wrongPeerAutomationDigestClient = + new AutomationScriptingClient( + endpoints, + pki.client("world-management-service"), + channels, + BlockingGrpcStubCustomizer.noop()); + try (worldDigestClient; + entityDigestClient; + automationDigestClient; + gameLogicGateClient; + wrongPeerEntityDigestClient; + wrongPeerAutomationDigestClient) { + ReflectionTestUtils.invokeMethod(worldDigestClient, "init"); + ReflectionTestUtils.invokeMethod(entityDigestClient, "init"); + ReflectionTestUtils.invokeMethod(automationDigestClient, "init"); + ReflectionTestUtils.invokeMethod(gameLogicGateClient, "init"); + ReflectionTestUtils.invokeMethod(wrongPeerEntityDigestClient, "init"); + ReflectionTestUtils.invokeMethod(wrongPeerAutomationDigestClient, "init"); + + var entityRowsBeforeWrongPeerDigest = entitySourceRowCounts(entity.dsl()); + var automationRowsBeforeWrongPeerDigest = automationSourceRowCounts(automation.dsl()); + var wrongPeerEntityDigest = + wrongPeerEntityDigestClient.getDraftDesignDigestForVersion(publicationRequest); + var wrongPeerAutomationDigest = + wrongPeerAutomationDigestClient.getDraftDesignDigestForVersion(publicationRequest); + assertThat(wrongPeerEntityDigest.succeeded()).isFalse(); + assertThat(wrongPeerEntityDigest.errorCode()).isEqualTo("PERMISSION_DENIED"); + assertThat(wrongPeerAutomationDigest.succeeded()).isFalse(); + assertThat(wrongPeerAutomationDigest.errorCode()).isEqualTo("PERMISSION_DENIED"); + assertThat(entitySourceRowCounts(entity.dsl())) + .isEqualTo(entityRowsBeforeWrongPeerDigest); + assertThat(automationSourceRowCounts(automation.dsl())) + .isEqualTo(automationRowsBeforeWrongPeerDigest); + + ReflectionTestUtils.setField(gameLogicGateClient, "workloadNamespace", NAMESPACE); + var gate = + new PublishGateServiceImpl( + controlPlaneDigests, + worldDigestClient, + entityDigestClient, + gameLogicGateClient, + automationDigestClient, + gd.dsl(), + gd.transactions(), + NAMESPACE); + selectedReleaseParticipants = + gate.collectSelectedFullVersionParticipantDigests( + publicationVersion, + publicationRequest, + publicationRequest.derivedWorkflowIdentity()); + gate.assertSelectedGatePassed(publicationVersion, selectedReleaseParticipants); + assertThat( + selectedReleaseParticipants.stream() + .map(PublishParticipantDigestDto::participantKey) + .toList()) + .containsExactlyElementsOf( + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()); + + var entityParticipant = + selectedReleaseParticipants.stream() + .filter(digest -> "ENTITY_MANAGEMENT".equals(digest.participantKey())) + .findFirst() + .orElseThrow(); + assertThat(entityParticipant.succeeded()).isTrue(); + assertThat(entityParticipant.scopeValue()).isEqualTo(publicationRequest.versionId()); + assertThat(entityParticipant.baseVersionId()).isNull(); + assertThat(entityParticipant.appliedCommitId()) + .isEqualTo(persistedEntityReceipt.selectedCommitId().toString()); + assertThat(entityParticipant.appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + assertThat(entityParticipant.digestSchemaVersion()).isEqualTo(3); + assertThat(entityParticipant.contentDigest()).isEqualTo(expectedEntityContentDigest); + assertThat(entityParticipant.contentDigest()) + .isNotEqualTo(persistedEntityReceipt.receiptDigest()) + .isNotEqualTo(entityReceipt.selectedSourceDigest()); + + var automationParticipant = + selectedReleaseParticipants.stream() + .filter(digest -> "AUTOMATION_SCRIPTING".equals(digest.participantKey())) + .findFirst() + .orElseThrow(); + assertThat(automationParticipant.succeeded()).isTrue(); + assertThat(automationParticipant.scopeValue()).isEqualTo(publicationRequest.versionId()); + assertThat(automationParticipant.baseVersionId()).isNull(); + assertThat(automationParticipant.appliedCommitId()) + .isEqualTo(automationReceipt.selectedCommitId().toString()); + assertThat(automationParticipant.appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + assertThat(automationParticipant.digestSchemaVersion()).isEqualTo(6); + assertThat(automationParticipant.contentDigest()) + .isEqualTo(expectedAutomationContentDigest); + assertThat(automationParticipant.contentDigest()) + .isNotEqualTo(automationReceipt.receiptDigest()) + .isNotEqualTo(automationReceipt.authorizationBindingDigest()); + + var selectedWorldParticipant = + selectedReleaseParticipants.stream() + .filter(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey())) + .findFirst() + .orElseThrow(); + assertThat(selectedWorldParticipant.appliedCommitId()) + .isEqualTo(selectedCommit.commitId().toString()); + assertThat(selectedWorldParticipant.contentDigest()) + .isEqualTo(retainedWorldDigest.contentDigest()); + assertThat(selectedWorldParticipant.digestSchemaVersion()).isEqualTo(4); + var selectedGameLogicParticipant = + selectedReleaseParticipants.stream() + .filter(digest -> "GAME_LOGIC".equals(digest.participantKey())) + .findFirst() + .orElseThrow(); + assertThat(selectedGameLogicParticipant.appliedCommitId()) + .isEqualTo(actualGameLogicDigest.appliedCommitId()); + assertThat(selectedGameLogicParticipant.contentDigest()) + .isEqualTo(actualGameLogicDigest.contentDigest()); + assertThat(selectedGameLogicParticipant.digestSchemaVersion()) + .isEqualTo(actualGameLogicDigest.digestSchemaVersion()); + assertThat(selectedGameLogicParticipant.abilitySchemaDigest()) + .isEqualTo(actualGameLogicDigest.abilitySchemaDigest()); + var selectedControlPlaneParticipant = + selectedReleaseParticipants.stream() + .filter(digest -> "GAME_DESIGN_CONTROL_PLANE".equals(digest.participantKey())) + .findFirst() + .orElseThrow(); + assertThat(selectedControlPlaneParticipant.appliedCommitId()) + .isEqualTo(actualDesignDigest.appliedCommitId()); + assertThat(selectedControlPlaneParticipant.contentDigest()) + .isEqualTo(actualDesignDigest.contentDigest()); + assertThat(selectedControlPlaneParticipant.digestSchemaVersion()).isEqualTo(2); + + var publisher = + new VersionPublishCommandServiceImpl( + new VersionRepository(gd.dsl()), + new GameRepository(gd.dsl()), + publishAttemptRepository, + mapper, + exporter, + transactionBoundPublishAttempts(gd, realAttemptPersistence), + gate, + controlPlaneDigests, + artifactService, + releaseService, + recordedParticipantDigests); + var published = + publisher.publishSelectedDraftFullVersion( + gd.target().gameDesignVersionTenantKey(), + gd.target().gameDesignVersionRowId(), + intent.notes(), + publishRequestId, + publicationRequest.derivedWorkflowIdentity()); + assertThat(published.versionState()).isEqualTo(VersionLifecycleState.PUBLISHED); + assertThat( + new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( + gd.dsl()) + .findByPublishWorkflowId(publicationRequest.derivedWorkflowIdentity()) + .orElseThrow() + .getStatus()) + .isEqualTo(net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); + } var release = releaseService.getPublishedReleaseBundle( gd.target().gameDesignVersionTenantKey(), gd.target().gameDesignVersionRowId()); - assertThat(release.attestationSchemaVersion()).isEqualTo("v3"); + assertThat(release.attestationSchemaVersion()).isEqualTo("v4"); assertThat(release.worldPublishedStartLocationEvidence()) .isEqualTo(publicationReservation.operation().world()); assertThat(release.worldPublishedStartLocationEvidence().request().digestSchemaVersion()) .isEqualTo(4); assertThat(release.participantDigests().getFirst().digestSchemaVersion()).isEqualTo(4); + assertThat( + release.participantDigests().stream() + .map(digest -> digest.participantKey()) + .toList()) + .containsExactlyElementsOf( + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()); + assertThat( + release.participantDigests().stream() + .map(digest -> digest.digestSchemaVersion()) + .toList()) + .containsExactly(4, 3, 1, 6, 2); + var retainedEntityParticipant = + release.participantDigests().stream() + .filter(digest -> "ENTITY_MANAGEMENT".equals(digest.participantKey())) + .findFirst() + .orElseThrow(); + assertThat(retainedEntityParticipant.scopeValue()) + .isEqualTo(publicationRequest.versionId()); + assertThat(retainedEntityParticipant.appliedCommitId()) + .isEqualTo(persistedEntityReceipt.selectedCommitId().toString()); + assertThat(retainedEntityParticipant.contentDigest()) + .isEqualTo(expectedEntityContentDigest); + assertThat(retainedEntityParticipant.digestSchemaVersion()).isEqualTo(3); + var retainedAutomationParticipant = + release.participantDigests().stream() + .filter(digest -> "AUTOMATION_SCRIPTING".equals(digest.participantKey())) + .findFirst() + .orElseThrow(); + assertThat(retainedAutomationParticipant.scopeValue()) + .isEqualTo(publicationRequest.versionId()); + assertThat(retainedAutomationParticipant.appliedCommitId()) + .isEqualTo(automationReceipt.selectedCommitId().toString()); + assertThat(retainedAutomationParticipant.contentDigest()) + .isEqualTo(expectedAutomationContentDigest); + assertThat(retainedAutomationParticipant.digestSchemaVersion()).isEqualTo(6); var retainedGameLogicParticipant = release.participantDigests().stream() .filter(digest -> "GAME_LOGIC".equals(digest.participantKey())) @@ -2370,8 +2626,7 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex .isEqualTo(actualDesignDigest.appliedCommitId()); assertThat(retainedDesignParticipant.contentDigest()) .isEqualTo(actualDesignDigest.contentDigest()); - assertThat(retainedDesignParticipant.digestSchemaVersion()) - .isEqualTo(actualDesignDigest.digestSchemaVersion()); + assertThat(retainedDesignParticipant.digestSchemaVersion()).isEqualTo(2); assertThat(gd.dsl().fetchCount(DSL.table("published_release_bundle"))).isOne(); assertThat( gd.dsl() @@ -2483,7 +2738,7 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex expectedAuthoredWorldBinding.resultDigest()); assertThat(completeBinding.descriptor()).isEqualTo(expectedAuthoredWorldBinding); completeBinding.releaseAttestation().requireValid(completeBinding.descriptor()); - assertThat(completeBinding.releaseAttestation().schemaVersion()).isEqualTo(3); + assertThat(completeBinding.releaseAttestation().schemaVersion()).isEqualTo(4); assertThat(completeBinding.releaseAttestation().descriptorResultDigest()) .isEqualTo(expectedAuthoredWorldBinding.resultDigest()); assertThat(completeBinding.releaseAttestation().worldStartLocationEvidence()) @@ -2764,50 +3019,6 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex } } - /** - * Entity and Automation participant digests remain stipulated test inputs. Their source receipts - * and Account settlements do not replace those publication participants. World freeze, inventory, - * selector and Game Design and Game Logic source reads come from their actual owner compositions. - * This does not prove complete four-owner publication or activation. - */ - private static List selectedSelectorParticipantDigests( - DraftCommitBinding selectedCommit, - long versionRowId, - PublishParticipantDigestDto worldManagementDigest, - DesignControlPlaneDigestDto gameDesignDigest, - PublishParticipantDigestDto gameLogicDigest) { - return AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - participant -> { - if ("WORLD_MANAGEMENT".equals(participant)) return worldManagementDigest; - if ("GAME_LOGIC".equals(participant)) return gameLogicDigest; - if ("GAME_DESIGN_CONTROL_PLANE".equals(participant)) { - return new PublishParticipantDigestDto( - participant, - gameDesignDigest.scopeValue(), - null, - gameDesignDigest.appliedCommitId(), - gameDesignDigest.contentDigest(), - gameDesignDigest.digestSchemaVersion(), - null, - null, - null); - } - return new PublishParticipantDigestDto( - participant, - Long.toString(versionRowId), - null, - selectedCommit.commitId().toString(), - "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - null, - null, - null); - }) - .toList(); - } - /** Uses the real owner persistence service inside the fixture's explicit READ_COMMITTED tx. */ private static PublishAttemptService transactionBoundPublishAttempts( Store store, PublishAttemptServiceImpl delegate) { @@ -3791,6 +4002,31 @@ private static String sha256(byte[] bytes) { } } + private static String selectedEmptyPublicationDigest( + String domain, + int schemaVersion, + UUID canonicalTenantId, + long gameDesignVersionRowId, + UUID canonicalVersionId, + String canonicalInventoryJson) { + var preimage = new ByteArrayOutputStream(); + appendSelectedPublicationDigestSegment(preimage, domain); + appendSelectedPublicationDigestSegment(preimage, Integer.toString(schemaVersion)); + appendSelectedPublicationDigestSegment(preimage, canonicalTenantId.toString()); + appendSelectedPublicationDigestSegment(preimage, Long.toString(gameDesignVersionRowId)); + appendSelectedPublicationDigestSegment(preimage, canonicalVersionId.toString()); + appendSelectedPublicationDigestSegment(preimage, canonicalInventoryJson); + return sha256(preimage.toByteArray()); + } + + private static void appendSelectedPublicationDigestSegment( + ByteArrayOutputStream preimage, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + preimage.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + preimage.write(':'); + preimage.writeBytes(bytes); + } + private static String changedDigest(String digest) { if (digest == null || !digest.matches("sha256:[0-9a-f]{64}")) { throw new IllegalArgumentException("Expected a sha256-prefixed digest"); @@ -4105,7 +4341,7 @@ private static final class MinioConditionalObjectStore implements AutoCloseable void requireCandidateBeforeWrites(SelectedDraftAssetInventory inventory) { inventoryBytes = inventory.canonicalBytes(); - operationDigest = sha256(inventory.operation().canonicalBytes()); + operationDigest = "sha256:" + sha256(inventory.operation().canonicalBytes()); selectedCommitDigest = inventory.selectedCommit().digest(); inventoryDigest = inventory.digest(); if (!objects().isEmpty()) { @@ -4152,20 +4388,38 @@ public void close() { private void requireExactCandidateBeforePut() { var retained = candidates.readSelectedCandidate(request); - if (inventoryBytes == null - || !request.requestDigest().equals(retained.requestDigest()) - || !Arrays.equals(request.canonicalPreimage(), retained.requestPreimage()) - || !operationDigest.equals(retained.operationDigest()) - || !selectedCommitDigest.equals(retained.selectedCommitDigest()) - || !SelectedDraftAssetInventory.SCHEMA.equals(retained.inventorySchema()) - || !inventoryDigest.equals(retained.inventoryDigest()) - || !Arrays.equals(inventoryBytes, retained.inventoryBytes()) - || !("sha256:" + sha256(retained.inventoryBytes())).equals(retained.inventoryDigest()) - || !("sha256:" + sha256(retained.manifestBytes())) - .equals(retained.manifest().manifestHash())) { - throw new AssertionError( - "Exact durable candidate, inventory and manifest were not readable before object PUT"); - } + assertThat(inventoryBytes) + .as("selected inventory snapshot captured before object PUT") + .isNotNull(); + assertThat(retained.requestDigest()) + .as("durable candidate request digest") + .isEqualTo(request.requestDigest()); + assertThat(Arrays.equals(request.canonicalPreimage(), retained.requestPreimage())) + .as("durable candidate canonical request preimage") + .isTrue(); + assertThat(retained.operationDigest()) + .as("durable candidate operation digest") + .isEqualTo(operationDigest); + assertThat(retained.selectedCommitDigest()) + .as("durable candidate selected commit digest") + .isEqualTo(selectedCommitDigest); + assertThat(retained.inventorySchema()) + .as("durable candidate inventory schema") + .isEqualTo(SelectedDraftAssetInventory.SCHEMA); + assertThat(retained.inventoryDigest()) + .as("durable candidate inventory digest") + .isEqualTo(inventoryDigest); + assertThat(Arrays.equals(inventoryBytes, retained.inventoryBytes())) + .as("durable candidate inventory bytes") + .isTrue(); + assertThat(("sha256:" + sha256(retained.inventoryBytes())).equals(retained.inventoryDigest())) + .as("durable candidate inventory content digest") + .isTrue(); + assertThat( + ("sha256:" + sha256(retained.manifestBytes())) + .equals(retained.manifest().manifestHash())) + .as("durable candidate manifest content digest") + .isTrue(); } private final class CandidateReadbackExecutionInterceptor implements ExecutionInterceptor { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 9842b12d46..1fbe47bea0 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -572,6 +572,122 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD assertThat(bundleCount(fixture.dsl())).isEqualTo(2); } + @Test + void v72PreservesRetainedV3TupleBytesAndExactRetryWithoutPromotion() throws Exception { + Fixture fixture = fixture(MigrationVersion.fromVersion("71")); + Game owner = saveGame(fixture, "retained-v3-profile-source"); + Version version = saveVersion(fixture, owner); + var operation = closureSelectorOperation(fixture, version); + var retained = selectorBundle(version, operation.world()); + retained.setAttestationSchemaVersion("v3"); + var saved = + fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> fixture.releaseBundleRepository().save(retained))); + var tuple = releaseBundleTuple(fixture.dsl(), saved.getId()); + var xmin = bundleXmin(fixture.dsl(), saved.getId()); + migrate(fixture.dataSource(), fixture.schema(), MigrationVersion.fromVersion("72")); + assertThat(releaseBundleTuple(fixture.dsl(), saved.getId())).isEqualTo(tuple); + assertThat(bundleXmin(fixture.dsl(), saved.getId())).isEqualTo(xmin); + var independent = + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(independent).usingRecursiveComparison().isEqualTo(saved); + assertThat( + independent + .getWorldPublishedStartLocationEvidenceJson() + .getBytes(StandardCharsets.UTF_8)) + .containsExactly(operation.world().canonicalBytes()); + assertThat(fixture.releaseBundleRepository().save(retained)) + .usingRecursiveComparison() + .isEqualTo(saved); + var changed = selectorBundle(version, operation.world()); + changed.setAttestationSchemaVersion("v4"); + changed.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString( + PublishedWorldSelectorFixtures.selectedFullParticipants( + version.getId(), operation.world()))); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(releaseBundleTuple(fixture.dsl(), saved.getId())).isEqualTo(tuple); + assertThat(bundleXmin(fixture.dsl(), saved.getId())).isEqualTo(xmin); + } + + @Test + void selectedFullV4StorageRejectsMixedProfilesAndExactlyReplaysOriginalBytes() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selected-v4-profile-source"); + Version version = saveVersion(fixture, owner); + var operation = closureSelectorOperation(fixture, version); + var json = new ObjectMapper(); + var participants = + PublishedWorldSelectorFixtures.selectedFullParticipants(version.getId(), operation.world()); + String original = new String(operation.world().canonicalBytes(), StandardCharsets.UTF_8); + for (int index = 0; index < participants.size(); index++) { + var mixed = + (tools.jackson.databind.node.ArrayNode) + json.readTree(json.writeValueAsString(participants)); + var participant = participants.get(index); + ((tools.jackson.databind.node.ObjectNode) mixed.get(index)) + .put( + "digestSchemaVersion", + participant.digestSchemaVersion() == 1 ? 2 : participant.digestSchemaVersion() - 1); + assertThatThrownBy( + () -> + insertRawSelector( + fixture, version, "v4", original, json.writeValueAsString(mixed))) + .as("mixed storage profile for %s", participant.participantKey()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("selected participant differs from commit/digest/schema"); + assertThat(bundleCount(fixture.dsl())).isZero(); + } + var requested = selectorBundle(version, operation.world()); + requested.setAttestationSchemaVersion("v4"); + requested.setParticipantDigestsJson(json.writeValueAsString(participants)); + var saved = + fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> fixture.releaseBundleRepository().save(requested))); + var tuple = releaseBundleTuple(fixture.dsl(), saved.getId()); + var xmin = bundleXmin(fixture.dsl(), saved.getId()); + var independent = + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(independent).usingRecursiveComparison().isEqualTo(saved); + assertThat(independent.getWorldPublishedStartLocationEvidenceJson()).isEqualTo(original); + assertThat(independent.getParticipantDigestsJson()) + .isEqualTo(json.writeValueAsString(participants)); + assertThat(fixture.releaseBundleRepository().save(requested)) + .usingRecursiveComparison() + .isEqualTo(saved); + var changed = selectorBundle(version, operation.world()); + changed.setAttestationSchemaVersion("v3"); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(releaseBundleTuple(fixture.dsl(), saved.getId())).isEqualTo(tuple); + assertThat(bundleXmin(fixture.dsl(), saved.getId())).isEqualTo(xmin); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + @Test void selectorV2RetainsCompleteOriginalEvidenceAndExactlyReplaysWithoutReplacingRelease() throws Exception { @@ -851,6 +967,38 @@ private WorldPublishedStartLocationEvidence selectorEvidence(Version version) th }); } + /** + * Same canonical GD owner storage as the retained v2 proof, with isolated closure-qualified + * remote inputs. + */ + private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation + closureSelectorOperation(Fixture fixture, Version version) { + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + return fixture + .transactionTemplate() + .execute( + status -> { + try { + return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .retainSourceBackedClosureQualified( + fixture.dsl(), + target, + version.getVersionStateEpoch(), + "ISOLATED remote owner profile upgrade/storage proof"); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + private PublishedReleaseBundle selectorBundle( Version version, WorldPublishedStartLocationEvidence evidence) { PublishedReleaseBundle bundle = bundle(version.getTenantId(), version.getId()); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java index e5653a1757..33f94f86aa 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -1,5 +1,6 @@ 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.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -230,6 +231,60 @@ void returnsImmutableFullBindingUsingTheDescriptorEpochAfterCurrentVersionStateA verifyReadOnlyCallsOnly(); } + @Test + void selectedFullV4AssemblesExactParticipantProfileFromImmutableBundle() throws Exception { + var selector = + PublishedWorldSelectorFixtures.closureEvidence( + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_ID, + PRIVATE_TENANT_KEY, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); + var selected = + new PublishedReleaseBundleDto( + bundle.id(), + bundle.tenantId(), + bundle.versionId(), + bundle.versionNumber(), + "v4", + selector.request().publishWorkflowId(), + bundle.manifestHash(), + bundle.requiredManifestAssetKeys(), + PublishedWorldSelectorFixtures.selectedFullParticipants(VERSION_ID, selector), + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.scriptOnly(), + bundle.scriptPatchVersion(), + bundle.publishedAt(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.publishedReleaseBundleRef(), + bundle.manifestSchemaVersion(), + bundle.artifactDigests(), + selector); + givenBundle(selected); + var result = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + assertEquals(4, result.releaseAttestation().schemaVersion()); + assertThat( + result.releaseAttestation().participantDigests().stream() + .map(participant -> participant.digestSchemaVersion()) + .toList()) + .containsExactly(4, 3, 1, 6, 2); + assertEquals(selector, result.releaseAttestation().worldStartLocationEvidence()); + result.releaseAttestation().requireValid(descriptor); + verifyReadOnlyCallsOnly(); + } + @Test void closureQualifiedSelectorV3AssemblesWorld4ParticipantFromImmutableBundle() throws Exception { var selector = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java index 4d396e0b46..e64e9f6b04 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java @@ -135,6 +135,7 @@ void selectedFullVersionGateUsesCanonicalBindingAndExactReceiptForOwnerReads() { assertEquals(5, digests.size()); assertDoesNotThrow(() -> service.assertSelectedGatePassed(version, digests)); assertEquals(2, digests.get(4).digestSchemaVersion()); + assertEquals(6, digests.get(3).digestSchemaVersion()); assertEquals("b".repeat(64), digests.getFirst().contentDigest()); assertEquals("c".repeat(64), digests.get(4).contentDigest()); verify(selectedPublicationDigestReader).read("test", binding); @@ -155,6 +156,37 @@ void selectedFullVersionGateUsesCanonicalBindingAndExactReceiptForOwnerReads() { .getDraftDesignDigestForVersion(any(PublicationDigestRequestBinding.class)); } + @Test + void selectedFullGateRejectsEveryMixedParticipantProfile() { + var version = selectedVersion(); + var binding = selectedBinding(version); + var receipt = org.mockito.Mockito.mock(SelectedDraftGameLogicReceipt.class); + stubSelectedParticipantDigests(version, binding, receipt); + var participants = + service.collectSelectedFullVersionParticipantDigests( + version, binding, binding.derivedWorkflowIdentity()); + for (int index = 0; index < participants.size(); index++) { + var mixed = new java.util.ArrayList<>(participants); + var participant = mixed.get(index); + mixed.set( + index, + new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion() == 1 ? 2 : participant.digestSchemaVersion() - 1, + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage())); + assertThrows( + PublishGateFailureException.class, + () -> service.assertSelectedGatePassed(version, mixed), + "mixed profile for " + participant.participantKey()); + } + } + @Test void closureQualifiedSelectedGateRequiresWorldDigestSchemaFour() { VersionDto version = selectedVersion(); @@ -740,7 +772,7 @@ void selectedGateRequiresSchemaTwoAndPreservesUnsupportedOwnerDenial() { when(entityManagementClient.getDraftDesignDigestForVersion(binding)) .thenReturn( new PublishParticipantDigestDto( - "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 2, null, null)); + "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 3, null, null)); when(automationScriptingClient.getDraftDesignDigestForVersion(binding)) .thenReturn( new PublishParticipantDigestDto( @@ -781,7 +813,7 @@ private void stubNonGameLogicParticipants( when(entityManagementClient.getDraftDesignDigestForVersion(binding)) .thenReturn( new PublishParticipantDigestDto( - "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 2, null, null)); + "ENTITY_MANAGEMENT", "7", "selected-commit", "entity-digest", 3, null, null)); when(automationScriptingClient.getDraftDesignDigestForVersion(binding)) .thenReturn( new PublishParticipantDigestDto( @@ -789,7 +821,7 @@ private void stubNonGameLogicParticipants( "7", "selected-commit", "automation-digest", - 5, + 6, null, null)); } @@ -802,7 +834,7 @@ private static SelectedDraftPublicationDigestReadService.ReadResult selectedSnap new DesignControlPlaneDigestDto( binding.tenantId(), "7", "selected-commit", "c".repeat(64), 2), new PublishParticipantDigestDto( - "WORLD_MANAGEMENT", "7", "selected-commit", "b".repeat(64), 3, null, null)); + "WORLD_MANAGEMENT", "7", "selected-commit", "b".repeat(64), 4, null, null)); } private static VersionDto selectedVersion() { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 770190f353..c8d4132c3f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -45,10 +45,10 @@ class PublishedReleaseBundleServiceImplTest { private PublishedReleaseBundleServiceImpl service; @Test - void closureSelectorV3PersistsOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults() + void selectedFullV4PersistsOriginalBytesAndRetryReturnsStoredEvidenceWithoutResolvingDefaults() throws Exception { var evidence = closureSelectorEvidence(); - var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + var participants = PublishedWorldSelectorFixtures.selectedFullParticipants(7L, evidence); // ISOLATED source-repository response; this test covers service assembly only. when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenReturn(List.of(validCommandDefinition())); @@ -70,7 +70,7 @@ void closureSelectorV3PersistsOriginalBytesAndRetryReturnsStoredEvidenceWithoutR "genrev-1", participants, evidence); - assertEquals("v3", first.attestationSchemaVersion()); + assertEquals("v4", first.attestationSchemaVersion()); assertThat(first.worldPublishedStartLocationEvidence().canonicalBytes()) .containsExactly(evidence.canonicalBytes()); assertThat(first.commandDefinitions()).containsExactly(validCommandDefinition()); @@ -113,10 +113,10 @@ void closureSelectorV3PersistsOriginalBytesAndRetryReturnsStoredEvidenceWithoutR } @Test - void closureSelectorV3RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest() + void selectedFullV4RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChangedWorldDigest() throws Exception { var evidence = closureSelectorEvidence(); - var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + var participants = PublishedWorldSelectorFixtures.selectedFullParticipants(7L, evidence); var obsolete = new java.util.ArrayList<>(participants); var gd = obsolete.getLast(); obsolete.set( @@ -198,7 +198,96 @@ void closureSelectorV3RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChan } @Test - void closureSelectorV3RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception { + void selectedFullV4RejectsEveryMixedParticipantSchemaBeforeWrite() throws Exception { + var evidence = closureSelectorEvidence(); + var participants = PublishedWorldSelectorFixtures.selectedFullParticipants(7L, evidence); + for (int index = 0; index < participants.size(); index++) { + var mixed = new java.util.ArrayList<>(participants); + var participant = mixed.get(index); + mixed.set( + index, + new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion() == 1 ? 2 : participant.digestSchemaVersion() - 1, + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage())); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + mixed, + evidence)) + .as("mixed profile for %s", participant.participantKey()) + .isInstanceOf(IllegalArgumentException.class); + } + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + } + + @Test + void retainedV3ReadsAndRetriesOriginalBytesButConflictsWithSelectedFullV4() throws Exception { + var evidence = closureSelectorEvidence(); + var retained = new PublishedReleaseBundle(); + retained.setId(11L); + retained.setTenantId("tenant-1"); + retained.setVersionId(7L); + retained.setVersionNumber(selectorVersion().versionNumber()); + retained.setCanonicalTenantId(sourceIdentity().getCanonicalTenantId()); + retained.setCanonicalVersionId(sourceIdentity().getCanonicalVersionId()); + retained.setAttestationSchemaVersion("v3"); + retained.setPublishWorkflowId("publish-workflow"); + retained.setManifestHash(emptyManifest().manifestHash()); + retained.setManifestSchemaVersion(emptyManifest().manifestSchemaVersion()); + retained.setArtifactDigestsJson("[]"); + retained.setRequiredManifestAssetKeysJson("[]"); + retained.setGenerationConfigRevision("genrev-1"); + retained.setCommandDefinitionsJson( + new ObjectMapper().writeValueAsString(List.of(validCommandDefinition()))); + retained.setParticipantDigestsJson( + new ObjectMapper() + .writeValueAsString(PublishedWorldSelectorFixtures.participants(7L, evidence))); + retained.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), StandardCharsets.UTF_8)); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)).thenReturn(Optional.of(retained)); + when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) + .thenReturn(List.of(validCommandDefinition())); + var read = service.getPublishedReleaseBundle("tenant-1", 7L); + assertEquals("v3", read.attestationSchemaVersion()); + assertThat(read.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(evidence.canonicalBytes()); + var retry = + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants(7L, evidence), + evidence); + assertThat(retry).isEqualTo(read); + assertThatThrownBy( + () -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.selectedFullParticipants(7L, evidence), + evidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertEquals("v3", retained.getAttestationSchemaVersion()); + org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); + } + + @Test + void selectedFullV4RequiresSelectedSourceCaptureBeforeBundleWrite() throws Exception { var evidence = closureSelectorEvidence(); when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenThrow(new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); @@ -210,7 +299,7 @@ void closureSelectorV3RequiresSelectedSourceCaptureBeforeBundleWrite() throws Ex "publish-workflow", emptyManifest(), "genrev-1", - PublishedWorldSelectorFixtures.participants(7L, evidence), + PublishedWorldSelectorFixtures.selectedFullParticipants(7L, evidence), evidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index 24bc82d15a..2fbc403946 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -453,7 +453,9 @@ private static int expectedFrozenGraphSchemaVersion( int expectedWorldDigestSchema = switch (release.schemaVersion()) { case AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION -> 3; - case AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION -> 4; + case AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION -> + 4; default -> throw invalid("Retained release has no supported selected World graph profile"); }; diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java index d886387c74..fad1872300 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java @@ -1,5 +1,6 @@ package unit.net.firedevops.firemud.worldmanagement.tenant; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @@ -7,8 +8,11 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.List; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTopologyInputGraph; @@ -57,6 +61,292 @@ void acceptsOnlyClosedFrozenGraphProfilesAndSupportedInboundClosure() { .hasMessageContaining("outside the supported profile"); } + @Test + void mapsRetainedAndSelectedFullAttestationsToTheirFrozenGraphProfiles() throws Exception { + assertThat(expectedFrozenGraphSchemaVersion(release(2))).isEqualTo(2); + assertThat(expectedFrozenGraphSchemaVersion(release(3))).isEqualTo(3); + + var selectedFull = + release(AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + assertThat(selectedFull.participantDigests()) + .extracting(AuthoredWorldReleaseAttestationEvidence.Participant::digestSchemaVersion) + .containsExactly(4, 3, 1, 6, 2); + assertThat(selectedFull.worldStartLocationEvidence()).isNotNull(); + assertThat(selectedFull.worldStartLocationEvidence().request().digestSchemaVersion()) + .isEqualTo(4); + assertThat(selectedFull.worldStartLocationEvidence().request().canonicalTenantId()) + .isEqualTo(selectedFull.canonicalTenantId()); + assertThat(selectedFull.worldStartLocationEvidence().request().canonicalVersionId()) + .isEqualTo(selectedFull.canonicalVersionId()); + assertThat(selectedFull.worldStartLocationEvidence().request().contentDigest()) + .isEqualTo(selectedFull.participantDigests().getFirst().contentDigest()); + assertThat(expectedFrozenGraphSchemaVersion(selectedFull)).isEqualTo(3); + } + + @Test + void rejectsUnsupportedOrMixedSelectedFullAttestationProfiles() throws Exception { + assertThatThrownBy(() -> expectedFrozenGraphSchemaVersion(release(1))) + .hasMessageContaining("no supported selected World graph profile"); + + var selectedFull = + release(AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + assertThatThrownBy( + () -> + selectedFull( + selectedFull, + participantDigestsWithSchema(selectedFull, "ENTITY_MANAGEMENT", 2))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + assertThatThrownBy( + () -> + selectedFull( + selectedFull, + participantDigestsWithSchema(selectedFull, "AUTOMATION_SCRIPTING", 5))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + assertThatThrownBy( + () -> + selectedFull( + selectedFull, + participantDigestsWithSchema(selectedFull, "WORLD_MANAGEMENT", 3))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Participant digest schema is unsupported"); + } + + private static int expectedFrozenGraphSchemaVersion( + AuthoredWorldReleaseAttestationEvidence release) { + try { + Method selector = + WorldCanonicalInstanceLifecycleReadRepository.class.getDeclaredMethod( + "expectedFrozenGraphSchemaVersion", AuthoredWorldReleaseAttestationEvidence.class); + selector.setAccessible(true); + return (int) selector.invoke(null, release); + } catch (InvocationTargetException failure) { + if (failure.getCause() instanceof RuntimeException runtime) throw runtime; + throw new IllegalStateException("Frozen graph schema selection failed", failure.getCause()); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException("Frozen graph schema selector is unavailable", failure); + } + } + + private static AuthoredWorldReleaseAttestationEvidence release(int schemaVersion) + throws Exception { + WorldPublishedStartLocationEvidence selector = + AuthoredWorldReleaseAttestationEvidence.requiresWorldStartLocationEvidence(schemaVersion) + ? selectedWorldEvidence( + schemaVersion + == AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION + || schemaVersion + == AuthoredWorldReleaseAttestationEvidence + .CLOSURE_SELECTOR_SCHEMA_VERSION + ? 4 + : 3) + : null; + String commitId = selector == null ? "test-commit" : selector.request().appliedCommitId(); + UUID tenantId = + selector == null + ? UUID.fromString("11111111-1111-4111-8111-111111111111") + : selector.request().canonicalTenantId(); + UUID versionId = + selector == null + ? UUID.fromString("22222222-2222-4222-8222-222222222222") + : selector.request().canonicalVersionId(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> { + boolean gameLogic = "GAME_LOGIC".equals(owner); + String contentDigest = + "WORLD_MANAGEMENT".equals(owner) && selector != null + ? selector.request().contentDigest() + : "a".repeat(64); + return new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "7", + false, + null, + commitId, + contentDigest, + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, schemaVersion), + gameLogic, + gameLogic ? "sha256:" + "c".repeat(64) : null); + }) + .toList(); + + String descriptorDigest = "sha256:" + "b".repeat(64); + String manifestHash = "sha256:" + "d".repeat(64); + String namespace = selector == null ? "test" : selector.request().targetNamespace(); + String workflow = selector == null ? "test-workflow" : selector.request().publishWorkflowId(); + if (schemaVersion == AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION) { + return AuthoredWorldReleaseAttestationEvidence.create( + namespace, + descriptorDigest, + tenantId, + versionId, + "synthetic-world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "sha256:" + "e".repeat(64), + "test-descriptor", + "test-release", + 1, + workflow, + commitId, + participants, + manifestHash, + 1, + List.of(), + List.of(), + List.of(), + "test-generation-config"); + } + return switch (schemaVersion) { + case AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION -> + AuthoredWorldReleaseAttestationEvidence.create( + namespace, + descriptorDigest, + tenantId, + versionId, + "synthetic-world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "sha256:" + "e".repeat(64), + "test-descriptor", + "test-release", + 1, + workflow, + commitId, + participants, + manifestHash, + 1, + List.of(), + List.of(), + List.of(), + "test-generation-config", + selector); + case AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION -> + AuthoredWorldReleaseAttestationEvidence.createClosureSelector( + namespace, + descriptorDigest, + tenantId, + versionId, + "synthetic-world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "sha256:" + "e".repeat(64), + "test-descriptor", + "test-release", + 1, + workflow, + commitId, + participants, + manifestHash, + 1, + List.of(), + List.of(), + List.of(), + "test-generation-config", + selector); + case AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION -> + AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + namespace, + descriptorDigest, + tenantId, + versionId, + "synthetic-world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "sha256:" + "e".repeat(64), + "test-descriptor", + "test-release", + 1, + workflow, + commitId, + participants, + manifestHash, + 1, + List.of(), + List.of(), + List.of(), + "test-generation-config", + selector); + default -> throw new IllegalArgumentException("Unsupported test release schema"); + }; + } + + private static WorldPublishedStartLocationEvidence selectedWorldEvidence(int schemaVersion) + throws Exception { + // ISOLATED carrier/profile selection only: this stipulates the newer World digest schema. + // It does not recompute a closure digest or prove a physical selected freeze/lifecycle read. + var retained = WorldCanonicalPlayerLocationGrpcServiceTest.publishedSelector("test"); + var request = retained.request(); + if (schemaVersion == request.digestSchemaVersion()) return retained; + var selectedRequest = + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + schemaVersion, + request.worldAffectedTuples()); + return new WorldPublishedStartLocationEvidence( + selectedRequest, + retained.selectorReceiptBytes(), + retained.originalAccountBindingBytes(), + retained.appliedResultBytes()); + } + + private static List + participantDigestsWithSchema( + AuthoredWorldReleaseAttestationEvidence release, String owner, int schemaVersion) { + return release.participantDigests().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + owner.equals(participant.participantKey()) + ? schemaVersion + : participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) + .toList(); + } + + private static AuthoredWorldReleaseAttestationEvidence selectedFull( + AuthoredWorldReleaseAttestationEvidence basis, + List participants) { + return AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + basis.targetNamespace(), + basis.descriptorResultDigest(), + basis.canonicalTenantId(), + basis.canonicalVersionId(), + basis.worldSlug(), + basis.authoredWorldSourceOperationId(), + basis.authoredWorldSourceEvidenceDigest(), + basis.launchDescriptorId(), + basis.publishedReleaseBundleRef(), + basis.versionStateEpoch(), + basis.publishWorkflowId(), + basis.commitId(), + participants, + basis.manifestHash(), + basis.manifestSchemaVersion(), + basis.requiredManifestAssetKeys(), + basis.artifactDigests(), + basis.commandDefinitions(), + basis.generationConfigRevision(), + basis.worldStartLocationEvidence()); + } + private static void validateFrozenGraphProfile(JsonNode graph, int expectedSchemaVersion) { try { Method validator = From fb67a8ec1b4d3e5a20a9f0e4339b4711b760390b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 07:55:24 +1300 Subject: [PATCH 096/129] Compose original Account authorization with World preparation proof --- .../runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 4 + .../world-runtime-and-movement.md | 2 + ...StartSessionAuthorizationProofFixture.java | 503 ++++++++++++ .../entity/ActorIdentity.java | 74 ++ .../entity/ActorIdentityStatus.java | 6 + .../repository/ActorIdentityRepository.java | 105 +++ ...__quarantine_unresolved_actor_identity.sql | 174 +++++ ...ld_actor_identity_indexes_concurrently.sql | 20 + ...tor_identity_indexes_concurrently.sql.conf | 1 + ...5__validate_actor_identity_constraints.sql | 34 + ...tityFoundationPostgresIntegrationTest.java | 299 ++++++++ ...ntakeMigrationPostgresIntegrationTest.java | 29 +- .../entity/ActorIdentityValueTest.java | 108 +++ ...licationExportPostgresIntegrationTest.java | 720 +++++++++++++++--- ...eWorldSelectedPublicationProofFactory.java | 11 +- 17 files changed, 1980 insertions(+), 118 deletions(-) create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java create mode 100644 services/entity-management-service/src/main/resources/db/migration/V3__quarantine_unresolved_actor_identity.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V4__build_actor_identity_indexes_concurrently.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V4__build_actor_identity_indexes_concurrently.sql.conf create mode 100644 services/entity-management-service/src/main/resources/db/migration/V5__validate_actor_identity_constraints.sql create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalActorIdentityFoundationPostgresIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 1da075427e..7f88410913 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -16,7 +16,7 @@ This document defines Entity Management’s runtime model, persistence ownership - The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for rows whose `expires_at` has elapsed, without tenant/namespace/instance predicates or a batch bound. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. - Realm-authored actor entry remains partial: legacy creation and actor rows still expose fixed RPG-oriented fields, policy/descriptor/template resolution and auto-provision idempotency are incomplete, and synthetic-ID/fork-copy proof gaps remain. These target rules do not claim runtime convergence. - The live runtime-instance cleanup path currently deletes room-ground inventory, item stacks, item instances, and container instances by `(tenantId, gameInstanceId)` alone. It does not apply namespace, scope, and holder/container closure or prove S3 classification, so its cleanup acknowledgement is unsafe for replacement until owner-local classification, fencing, and focused proof are complete. -- The live Entity schema does not yet represent the target namespace-stable identity for durable S1/S2 state: `characters` and `actor_resource_states` retain legacy `playable_state_key`, while `inventory`, `character_friend`, `character_equipment`, and durable holder/containment rows omit `playableStateNamespaceId` (and some omit `tenant_id` entirely). The current repositories consequently cannot enforce the target `{tenantId, playableStateNamespaceId, domainObjectId}` identity at the SQL boundary. A convergent migration, legacy-row disposition/backfill evidence, namespace-aware repository predicates, and focused isolation proof remain required; until those are complete, legacy `playable_state_key` rows (including `character_friend` associations reached through them) are not namespace-isolated proof and cutover readers must not treat them as namespace-backed survivor state. This does not change the target contract above. +- Additive V3–V5 prepares canonical actor UUID, Account/tenant UUID, namespace/scope and provenance-disposition columns on `characters`, preserving V1 and the fresh selected-empty catalogue V2 unchanged. Existing actors receive Entity-allocated UUIDs but remain `QUARANTINED` with missing owner provenance; neither their numeric keys nor their legacy `playable_state_key` supplies canonical Account, tenant or namespace evidence. The new read-only `ActorIdentityRepository` selects only the complete exact owner-resolved tuple. It does not promote rows or replace current legacy ingress, mutation, roster or cleanup paths. The focused migration/isolation definition uses explicitly populated owner-resolved rows only as test data, not a producer or retained-association proof. `actor_resource_states` still uses `playable_state_key`; `inventory`, `character_friend`, `character_equipment` and durable holder/containment rows still omit namespace identity (and some omit `tenant_id`). Complete producer and retained-owner association, namespace-aware consumers/mutations, dependent-state retention and physical isolation proof remain required. Legacy rows are not namespace-backed survivor or cutover evidence, and no runtime admission or placement is enabled. - The live `item_stacks` uniqueness constraint includes nullable holder columns, so PostgreSQL can accept duplicate rows for the same tenant/holder/item/fingerprint when another holder column is `NULL`. Inventory and container mutation paths still use find-then-create/save rather than an atomic conflict-safe operation. With no explicit `stackFamilyKey`, source resolution rejects more than one candidate row; with an explicit family key, the current implementation selects the first matching row and does not reject duplicate matches. Target resolution must enforce exactly one matching stack (or fail closed), alongside holder-kind-specific uniqueness or normalized non-null identity, atomic upsert/locking, and concurrent proof. - The current `characterGraph` helper caches `getWithInventory(characterId)` by character ID alone with a TTL and performs no namespace or authoritative version validation. It is not the target namespace-qualified Class A `character-cache:*` contract; until that contract is implemented and proved, this cache is not correctness authority. - `EntityDraftDesignDigestServiceImpl` currently emits `digestSchemaVersion=1` without hashing item `equipmentSlotGroupKey`, while `EquipmentServiceImpl` uses that field for slot compatibility admission. The digest is therefore incomplete for equipment semantics: different slot-group constraints may attest the same content digest. Target convergence adds the normalized field, bumps the schema version, and proves cross-version digest isolation plus publish-gate rejection of a changed constraint. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 77fe40bd77..babd9f60d8 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -216,3 +216,9 @@ Entry format: - Observation: The helper identified JavaScript replacement-string dollar expansion while preparing the patch. The resulting SQL block is excluded from the schema simulator, so successful schema generation would not establish its correctness. - Expected pattern: Preserve literal replacement content with a replacement callback, inspect the resulting complete procedural block, and require actual PostgreSQL migration and negative-case execution separately from generated metadata. - Current status: The helper corrected the literals and new inline `CASE` operands before validation or publication. Physical PostgreSQL parsing and assertion proof remain pending. + +- `2026-10-11`: A compiled jOOQ scalar-read assertion can accidentally bind its result type + - Context: The corrected Entity occupied-key migration fixture compiled and its PostgreSQL cases skipped locally, but exact-source CI failed when its parameterized `fetchValue(sql, String.class, kind, key)` call treated `String.class` as a SQL bind value. + - Observation: A Java `Class` argument is not a typed-result parameter for this string-SQL overload. Compilation and skipped integration tests concealed the mistake; CI failed before the intended assertion rather than disproving the migration. + - Expected pattern: For raw SQL, use an exact `fetchSingle(sql, bindings).get(0, ResultType.class)` read and preserve the complete value assertions. Confirm the case actually executed before granting database proof. + - Current status: The scoped fixture reads are corrected without changing production SQL, the expected typed key set or writer guards. Corrected physical execution remains pending; the controller records the exact failed source and next proof gate. 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 241b209738..d2e99a6900 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,10 @@ The corrected seven-module local gate passes in 5 minutes 7 seconds: complete ch Originating run `38072471688` is terminal failure; its Account integration task was cancelled before any integration XML was captured. Artifact `11677753612` proves only 1,346 Account unit passes; no Account database execution count or PostgreSQL version can be attributed to the cancelled cases. Game Design's owner artifact `11677876709` records 152 integrations, zero skips and one failure (the candidate-digest fixture defect above); Entity artifact `11677281831` records the 13 integrations and sole seed-expectation failure above. The actual tested merge is `3543c22c2b945d553f2f7f19defd5606f469650f`, tree `b046aaa9c0e346eb5faca0698cf968d95829faba`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact `2b763b040c9b4f63baa88bff0c911d3be177abd9` source; the first parent differs from the recorded run-title base. Duplicate dependency-deferred run `38072575546` skips all build/test jobs and supplies no substantive proof. Corrected PostgreSQL CI, production privileges, continuous protection and all four complete Gameplay handoffs remain open. +The corrected source `e0f048e4eb5810eb69581dcb2c74e612cb368a60` has partial originating [Validation run 38075220202](https://github.com/benhook1013/FireMUD/actions/runs/38075220202) evidence, not a completed release handoff. Automation executes 1,196 unit and 94 integration tests on PostgreSQL 18.6 with zero failures, errors or skips, including the four selected-empty repository cases and schema-six snapshot reader. Entity executes 207 units and 15 PostgreSQL 18.6 integrations without skips; all eight repository cases and two additional migration cases pass, while the seed-census test fails in its raw-SQL read helper because a `Class` argument is accidentally bound as a SQL parameter. The local test-only correction uses an explicit typed result read and preserves the production migration, exact typed key set and all assertions. Its integration compilation passes; corrected physical execution remains required. Game Design's cancelled job preserves 550 passing units but no integration XML, so it provides no corrected MinIO, V72 upgrade or genuine native publication proof. Account's originating job is still pending at this checkpoint; neither cancellation nor elapsed time supplies database proof. + +The next construction definition replaces the fixed StartSession Account projection with actual original issue/redemption, complete source-capture and immutable bundle readback, and repeated native mTLS projection reads. It extends the same release to actual World binding, preparation/materialization, PREPARING lifecycle readback and retry; Logging claim evidence, Game Session launch association and continuous Account/Game Session commit protection remain stipulated. Additive Entity V3–V5 preserves the existing catalogue V2 and consumes only the UUID/quarantine read foundation from published source `e3f89c3fd6e2d46a14338ac38fedcb0bd4ccb020`; it does not reinterpret its `PRESEEDED_ONLY` assignment as a player-created or placement producer. The corrected local gate completes in 1m20s: 2,118 unit tests pass (Account 1,346, Entity 210, Game Design 562), 12 non-container Account integrations execute, and 454 container-dependent cases skip (Account 286, Entity 17, Game Design 151). All three module checks, Entity schema generation, fixture/integration compilation, Entity classes-only proof artifact and boot JAR, formatting/static analysis, links and 548 Markdown files pass; unchanged tasks reuse their results. Flyway sanity passes 12 sets and 300 versioned files. These are preparation and local proof, not executed PostgreSQL migration, original projection, composed World materialization, ACTIVE readiness, placement or admission proof. + ## Earlier Construction Checkpoints The current construction replaces the remaining in-process Automation-retention and Account-settlement commands with distinct, unregistered native mTLS transports. The owning [Automation command](../../architecture/microservices/automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) and [Account settlement command](../../architecture/microservices/account-service/api-contracts.md#grpc-apis) retain full original evidence, independent transport correlations, exact request echoes and immutable receipt readback. Receiver authentication derives from each server's configured namespace, not a namespace supplied by the caller. The genuine PostgreSQL fixture defines a fresh native Account reserve → authenticated source read → finalize → Automation retain → Account settle flow, plus wrong-workload no-mutation, exact retry, unchanged rows and post-settlement HELD denial. Its earlier, manually reserved Entity/Automation disclosure fixtures are explicitly aborted before the fresh positive operation; those setup contexts do not establish the positive producer boundary. Entity retention and publication participation, S3 and StartSession projection remain incomplete. 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 07e683ed06..259dbac6e2 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -20,6 +20,8 @@ The separate [canonical hold reconciler](../../../services/world-management-serv ## Packet 4 Status and Proof Gaps +The expanded [genuine selected-publication definition](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java) now composes the retained authored source and frozen World graph, complete immutable Game Design release pair, canonical World binding/assembly, materialization, PREPARING lifecycle readback and exact retry through the Game Session mTLS client. Its Account original issue/redemption and subsequent projection read use actual Account persistence rather than a fixed projection response. Logging claim evidence, Game Session attempt/launch association and the continuously held commit-authority handle remain stipulated. The definition checks peer/default-denial no mutation and unchanged retained source/release evidence; its physical composed execution is still pending. It does not establish ACTIVE readiness, genuinely held cross-owner authority, actor placement, region delivery or runtime activation. + - `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. - `AR-3.1`: [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) records the database lifecycle row/epoch and Temporal coordination boundary. Existing prepare/activate/terminate caveats, including blocking calls and missing stages, remain active gaps. - `GR-2.1` / `AR-3.1`: World termination keeps Entity Management cleanup outside an open World transaction, retains `TERMINATING` while cleanup is pending or fails, and commits local runtime-row cleanup with the `TERMINATED` lifecycle state in one local transaction. [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) owns this current consequence. [WorldLifecycleCommandServiceImplTest](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) covers the local control flow and RPC/transaction separation; live PostgreSQL rollback/crash/concurrency proof is not claimed. The separate terminal fast path still does not compare `terminationRequestId`, as recorded below. diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java new file mode 100644 index 0000000000..b0e0c7bafa --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -0,0 +1,503 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.grpc.BindableService; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import org.jooq.Record; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +/** + * Test-only proof fixture for Account's original human StartSession issuer and one-time redemption. + * + *

Logging's current-claim read response and the supplied Game Session attempt/fence remain + * stipulated inputs. The Account actor, source capture, issuance, reference custody, redemption, + * and later projection read use the real Account owners and retained PostgreSQL rows. The peer + * scopes around issue and redemption are in-process test stipulations, not authenticated producer + * or mTLS proof. + */ +public final class AccountOriginalStartSessionAuthorizationProofFixture { + private static final Duration REFERENCE_LIFETIME = Duration.ofMinutes(5); + private static final Duration RESPONSE_RECOVERY_WINDOW = Duration.ofSeconds(30); + private static final String LOGGING_SERVICE = "logging-admin-service"; + private static final String GAME_SESSION_SERVICE = "game-session-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final Set attemptedControlPlaneRequestIds = new HashSet<>(); + private final AccountControlUiOwnerSourcesFixture accountSources; + private final AccountControlUiOriginalOrderFixture.IssuedCreator creator; + private final String namespace; + private final String loggingPeerUri; + private final String gameSessionPeerUri; + private final AccountStartSessionOperatorAuthorizationRepository repository; + private final AccountStartSessionAuthorityCaptureRepository captureRepository; + private final AccountStartSessionOperatorAuthorizationService authorizationService; + private final StartSessionOperatorAuthorizationGrpcService grpcService; + + public AccountOriginalStartSessionAuthorizationProofFixture( + AccountControlUiOriginalOrderFixture controlUi, Path temporary, String namespace) + throws Exception { + Objects.requireNonNull(controlUi, "Account control-ui fixture is required"); + Objects.requireNonNull(temporary, "temporary test directory is required"); + this.namespace = requireNamespace(namespace); + creator = controlUi.preparedOriginalCreator(); + accountSources = creator.sources(); + + loggingPeerUri = peerUri(namespace, LOGGING_SERVICE); + gameSessionPeerUri = peerUri(namespace, GAME_SESSION_SERVICE); + var claimClient = stipulatedLoggingClaimClient(); + repository = new AccountStartSessionOperatorAuthorizationRepository(accountSources.dsl); + captureRepository = new AccountStartSessionAuthorityCaptureRepository(accountSources.dsl); + authorizationService = + new AccountStartSessionOperatorAuthorizationService( + creator.actors(), + new AccountControlUiIssuanceRepository(accountSources.dsl), + captureRepository, + claimClient, + repository, + fingerprintKeys(), + responseCryptography(temporary), + accountSources.terms, + accountSources.manager, + Clock.systemUTC(), + new SecureRandom(), + loggingPeerUri, + gameSessionPeerUri, + REFERENCE_LIFETIME, + RESPONSE_RECOVERY_WINDOW); + grpcService = new StartSessionOperatorAuthorizationGrpcService(authorizationService, namespace); + } + + /** + * Performs one real Account issue and one real Account redemption for a supplied typed action. + * + *

The action's tenant and namespace must match this retained Account fixture, and its target + * owner account must be the authenticated creator. The reservation owner/fence identify the + * stipulated Logging claim; the Game Session attempt/fence are also stipulated. This method + * returns the exact original post-authorization tuple and durable owner identities, never the + * opaque authorization reference or key material. + */ + public synchronized OriginalStartSession issueAndRedeemOriginal( + String controlPlaneRequestId, + StartSessionOperatorAction action, + UUID reservationOwnerId, + long reservationClaimFence, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence) { + Objects.requireNonNull(action, "canonical StartSession action is required"); + requireActionBinding(action); + requireOwner(reservationOwnerId, "reservationOwnerId"); + requirePositive(reservationClaimFence, "reservationClaimFence"); + requireOwner(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + controlPlaneRequestId, accountSources.account.getAccountUuid(), action); + if (!attemptedControlPlaneRequestIds.add(preTuple.controlPlaneRequestId())) { + throw new IllegalStateException( + "This proof fixture already attempted the original StartSession request"); + } + byte[] preTupleBytes = preTuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + var authorization = + withPeer( + loggingPeerUri, + () -> + authorizationService.issue( + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + creator.compact(), + preTupleBytes, + reservationOwnerId, + reservationClaimFence, + reservationOwnerId, + reservationClaimFence))); + + var sharedReference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + authorization.bundleReference().bundleVersion(), + authorization.bundleReference().sourceVersion(), + authorization.bundleReference().sourceFence(), + authorization.bundleReference().linearization()); + var originalTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + loggingPeerUri, + authorization.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + authorization.authorityEvidenceBundle(), + sharedReference); + + var redemption = + withPeer( + gameSessionPeerUri, + () -> + authorizationService.redeem( + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + preTupleBytes, + authorization.operatorAuthorizationReference(), + authorization.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + gameSessionOwnerAttemptId, + gameSessionOwnerFence))); + assertThat(redemption.replay()).isFalse(); + + var retained = + accountSources.tx( + () -> repository.findByControlPlaneRequestId(controlPlaneRequestId).orElseThrow()); + assertThat(retained.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + assertThat(retained.preAuthorizationTuple()).containsExactly(preTupleBytes); + assertThat(retained.reservationOwnerId()).isEqualTo(reservationOwnerId); + assertThat(retained.reservationClaimFence()).isEqualTo(reservationClaimFence); + assertThat(retained.redemptionRedeemerWorkloadUri()).isEqualTo(gameSessionPeerUri); + assertThat(retained.redemptionOwnerAttemptId()).isEqualTo(gameSessionOwnerAttemptId); + assertThat(retained.redemptionOwnerFence()).isEqualTo(gameSessionOwnerFence); + assertThat(retained.redemptionReferenceFingerprint()) + .isEqualTo(authorization.authorizationReferenceFingerprint()); + assertThat(retained.issuanceOperationId()).isNotNull(); + assertThat(retained.issuanceFence()).isPositive(); + assertThat(retained.bundleReference()).isEqualTo(authorization.bundleReference()); + assertThat(retained.authorityEvidenceBundle()) + .containsExactly(authorization.authorityEvidenceBundle()); + assertThat(retained.authorityEvidenceBundle()) + .containsExactly(originalTuple.authorityEvidenceBundleBytes()); + assertThat(retained.authorizationReferenceFingerprint()) + .isEqualTo(originalTuple.authorizationReferenceFingerprint()); + assertThat(retained.redemptionAuthorityEvidenceBundle()) + .containsExactly(authorization.authorityEvidenceBundle()); + assertPersistedCapture( + preTuple, + reservationOwnerId, + reservationClaimFence, + authorization, + originalTuple, + retained); + + return new OriginalStartSession( + preTuple, + originalTuple, + reservationOwnerId, + reservationClaimFence, + gameSessionOwnerAttemptId, + gameSessionOwnerFence, + retained.issuanceOperationId(), + retained.issuanceFence()); + } + + /** The real Account receiver for the retained redeemed-operation projection. */ + public BindableService grpcService() { + return grpcService; + } + + /** The actual Account UUID for the prepared creator used by this fixture. */ + public UUID creatorAccountId() { + return accountSources.account.getAccountUuid(); + } + + private void assertPersistedCapture( + StartSessionPreAuthorizationReservationTuple preTuple, + UUID reservationOwnerId, + long reservationClaimFence, + AccountStartSessionOperatorAuthorizationService.AuthorizationResponse authorization, + StartSessionPostAuthorizationExecutionTuple originalTuple, + AccountStartSessionOperatorAuthorizationRepository.IssuanceRecord retained) { + AccountStartSessionAuthorityCapture capture = + withPeer( + loggingPeerUri, + () -> + creator + .actors() + .withCurrent( + creator.compact(), + accountSources.tenant, + creator.environment(), + current -> + captureRepository.lockReadExactCurrent( + current, + preTuple, + loggingPeerUri, + reservationOwnerId, + reservationClaimFence))); + + assertThat(capture.controlPlaneRequestId()).isEqualTo(preTuple.controlPlaneRequestId()); + assertThat(capture.bundleReference().bundleVersion()) + .isEqualTo(originalTuple.bundleReference().bundleVersion()); + assertThat(capture.bundleReference().sourceVersion()) + .isEqualTo(originalTuple.bundleReference().sourceVersion()); + assertThat(capture.bundleReference().sourceFence()) + .isEqualTo(originalTuple.bundleReference().sourceFence()); + assertThat(capture.bundleReference().linearization()) + .isEqualTo(originalTuple.bundleReference().linearization()); + assertThat(capture.sourceVersion()) + .isEqualTo(Long.parseLong(authorization.bundleReference().sourceVersion())); + assertThat(capture.sourceFence()) + .isEqualTo(Long.parseLong(authorization.bundleReference().sourceFence())); + assertThat(capture.linearization()).isEqualTo(authorization.bundleReference().linearization()); + assertThat(authorization.bundleReference().sourceVersion()) + .isEqualTo(originalTuple.bundleReference().sourceVersion()); + assertThat(authorization.bundleReference().sourceFence()) + .isEqualTo(originalTuple.bundleReference().sourceFence()); + assertThat(authorization.bundleReference().linearization()) + .isEqualTo(originalTuple.bundleReference().linearization()); + + var authorityBundle = + AccountStartSessionOperatorAuthorityBundle.decode(retained.authorityEvidenceBundle()); + authorityBundle.requireCaptureBinding( + capture, + preTuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + originalTuple.bundleReference())); + assertThat(authorityBundle.issuanceOperationId()).isEqualTo(retained.issuanceOperationId()); + assertThat(authorityBundle.issuanceFence()).isEqualTo(retained.issuanceFence()); + assertThat(authorization.authorityEvidenceBundle()) + .containsExactly(authorityBundle.canonicalBytes()); + + Map snapshot = captureSnapshot(capture); + byte[] preTupleBytes = preTuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + assertThat(snapshot.get("schema")).isEqualTo("account-start-session-authority-snapshot/v1"); + assertThat(snapshot.get("controlPlaneRequestId")).isEqualTo(preTuple.controlPlaneRequestId()); + assertThat(snapshot.get("preAuthorizationTuple")) + .isEqualTo(Base64.getEncoder().encodeToString(preTupleBytes)); + assertThat(snapshot.get("mutationDigest")).isEqualTo(preTuple.mutationDigest()); + assertThat(snapshot.get("accountId")).isEqualTo(preTuple.actor().accountId().toString()); + assertThat(snapshot.get("tenantId")).isEqualTo(preTuple.action().scope().tenantId().toString()); + assertThat(preTuple.action().scope().targetNamespace()).isEqualTo(namespace); + assertThat(snapshot.get("targetOwner")).isEqualTo(GAME_SESSION_SERVICE); + assertThat(snapshot.get("loggingWorkloadUri")).isEqualTo(loggingPeerUri); + assertThat(snapshot.get("reservationOwnerId")).isEqualTo(reservationOwnerId.toString()); + assertThat(snapshot.get("reservationClaimFence")) + .isEqualTo(Long.toString(reservationClaimFence)); + + Record captureRow = + accountSources.dsl.fetchOne( + "SELECT account_uuid, tenant_uuid, target_owner, logging_workload_uri, " + + "reservation_owner_id, reservation_claim_fence, pre_authorization_tuple, " + + "mutation_digest, issuance_fence, issuance_fence_source_version, " + + "canonical_snapshot_bytes, canonical_capture_bytes, source_version, " + + "source_fence, linearization " + + "FROM account_start_session_authority_captures " + + "WHERE control_plane_request_id = ?", + preTuple.controlPlaneRequestId()); + assertThat(captureRow).as("Account's genuine StartSession source capture").isNotNull(); + assertThat(capture.canonicalBytes()) + .containsExactly(captureRow.get("canonical_capture_bytes", byte[].class)); + assertThat(capture.snapshotBytes()) + .containsExactly(captureRow.get("canonical_snapshot_bytes", byte[].class)); + assertThat(captureRow.get("source_version", Long.class)).isEqualTo(capture.sourceVersion()); + assertThat(captureRow.get("source_fence", Long.class)).isEqualTo(capture.sourceFence()); + assertThat(captureRow.get("linearization", String.class)).isEqualTo(capture.linearization()); + assertThat(captureRow.get("account_uuid", UUID.class)).isEqualTo(preTuple.actor().accountId()); + assertThat(captureRow.get("tenant_uuid", UUID.class)) + .isEqualTo(preTuple.action().scope().tenantId()); + assertThat(captureRow.get("target_owner", String.class)).isEqualTo(GAME_SESSION_SERVICE); + assertThat(captureRow.get("logging_workload_uri", String.class)).isEqualTo(loggingPeerUri); + assertThat(captureRow.get("reservation_owner_id", UUID.class)).isEqualTo(reservationOwnerId); + assertThat(captureRow.get("reservation_claim_fence", Long.class)) + .isEqualTo(reservationClaimFence); + assertThat(captureRow.get("pre_authorization_tuple", byte[].class)) + .containsExactly(preTupleBytes); + assertThat(captureRow.get("mutation_digest", String.class)) + .isEqualTo(preTuple.mutationDigest()); + assertThat(snapshot.get("issuanceFence")) + .isEqualTo(Long.toString(captureRow.get("issuance_fence", Long.class))); + assertThat(snapshot.get("issuanceFence")).isEqualTo(Long.toString(retained.issuanceFence())); + assertThat(snapshot.get("issuanceFenceSourceVersion")) + .isEqualTo(Long.toString(captureRow.get("issuance_fence_source_version", Long.class))); + assertThat(retained.issuanceFence()).isEqualTo(authorityBundle.issuanceFence()); + } + + private static Map captureSnapshot(AccountStartSessionAuthorityCapture capture) { + try { + return JSON.readValue(capture.snapshotBytes(), new TypeReference<>() {}); + } catch (Exception malformed) { + throw new IllegalStateException("Account source snapshot is not readable", malformed); + } + } + + private StartSessionReservationEvidenceClient stipulatedLoggingClaimClient() { + var client = mock(StartSessionReservationEvidenceClient.class); + when(client.readCurrentClaimEvidence( + any(StartSessionPreAuthorizationReservationTuple.class), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong(), + eq(StartSessionReservationEvidenceClient.Purpose.ISSUE))) + .thenAnswer( + invocation -> { + var tuple = + invocation.getArgument(0, StartSessionPreAuthorizationReservationTuple.class); + UUID reservationOwnerId = invocation.getArgument(1, UUID.class); + long reservationClaimFence = invocation.getArgument(2, Long.class); + UUID claimOwnerId = invocation.getArgument(3, UUID.class); + long claimFence = invocation.getArgument(4, Long.class); + if (!reservationOwnerId.equals(claimOwnerId) || reservationClaimFence != claimFence) { + throw new IllegalArgumentException( + "Stipulated ISSUE claim must retain the original owner and fence"); + } + return stipulatedClaim( + tuple, reservationOwnerId, reservationClaimFence, Instant.now()); + }); + return client; + } + + private void requireActionBinding(StartSessionOperatorAction action) { + if (!namespace.equals(action.scope().targetNamespace()) + || !accountSources.tenant.equals(action.scope().tenantId()) + || !accountSources.account.getAccountUuid().equals(action.target().ownerAccountId())) { + throw new IllegalArgumentException( + "StartSession action must bind the retained creator, tenant, and workload namespace"); + } + } + + private static ReadCurrentClaimEvidenceResponse stipulatedClaim( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + Instant now) { + return ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + com.google.protobuf.ByteString.copyFrom( + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setMutationDigest(tuple.mutationDigest()) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setClaimOwnerId(reservationOwnerId.toString()) + .setClaimFence(reservationClaimFence) + .setObservedAtEpochMillis(now.minusSeconds(1).toEpochMilli()) + .setClaimExpiresAtEpochMillis(now.plus(Duration.ofMinutes(5)).toEpochMilli()) + .setPurpose( + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) + .build(); + } + + private static AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys() { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) 0x51); + return new AccountOperatorAuthorizationFingerprintKeyring( + () -> + new AccountOperatorAuthorizationFingerprintKeyring.Snapshot( + new AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial( + "test-active", new SecretKeySpec(key, "HmacSHA256")), + List.of()), + Clock.systemUTC(), + Duration.ofMinutes(2)); + } + + private static AccountResponseEnvelopeCryptography responseCryptography(Path temporary) + throws Exception { + Files.createDirectories(temporary); + Path root = Files.createTempDirectory(temporary, "account-start-session-response-envelope-"); + byte[] key = new byte[32]; + Arrays.fill(key, (byte) 0x26); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive test-response " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n", + StandardOpenOption.CREATE_NEW, + StandardOpenOption.WRITE); + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(root.toString()), Clock.systemUTC(), new SecureRandom()); + } + + private static T withPeer(String peerUri, Callable action) { + try (var ignored = AccountControlUiOwnerSourcesFixture.withPeer(peerUri)) { + return action.call(); + } catch (RuntimeException failure) { + throw failure; + } catch (Exception failure) { + throw new IllegalStateException("Stipulated Account owner peer action failed", failure); + } + } + + private static String requireNamespace(String namespace) { + Objects.requireNonNull(namespace, "workload namespace is required"); + new StartSessionOperatorAction.Scope( + UUID.fromString("11111111-1111-4111-8111-111111111111"), namespace); + return namespace; + } + + private static String peerUri(String namespace, String service) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } + + private static void requireOwner(UUID owner, String field) { + Objects.requireNonNull(owner, field + " is required"); + if (new UUID(0L, 0L).equals(owner)) { + throw new IllegalArgumentException(field + " must not be nil"); + } + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) throw new IllegalArgumentException(field + " must be positive"); + } + + /** Exact non-secret identities retained by the original Account issue/redemption. */ + public record OriginalStartSession( + StartSessionPreAuthorizationReservationTuple preAuthorizationTuple, + StartSessionPostAuthorizationExecutionTuple originalTuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + UUID issuanceOperationId, + long issuanceFence) { + public OriginalStartSession { + Objects.requireNonNull(preAuthorizationTuple, "original pre-authorization tuple required"); + Objects.requireNonNull(originalTuple, "original post-authorization tuple required"); + requireOwner(reservationOwnerId, "reservationOwnerId"); + requirePositive(reservationClaimFence, "reservationClaimFence"); + requireOwner(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + requireOwner(issuanceOperationId, "issuanceOperationId"); + requirePositive(issuanceFence, "issuanceFence"); + } + + @Override + public String toString() { + return "OriginalStartSession[controlPlaneRequestId=" + + preAuthorizationTuple.controlPlaneRequestId() + + ", issuanceOperationId=" + + issuanceOperationId + + ", issuanceFence=" + + issuanceFence + + ", original tuple evidence redacted]"; + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java new file mode 100644 index 0000000000..33002613eb --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentity.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.entitymanagement.entity; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.springframework.util.StringUtils; + +/** Canonical Entity-owned actor identity and the provenance disposition that gates its use. */ +public record ActorIdentity( + UUID characterUuid, + UUID accountUuid, + UUID tenantUuid, + UUID playableStateNamespaceId, + PlayableStateScope playableStateScope, + ActorIdentityStatus status, + String quarantineReason) { + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String UUID_PATTERN = + "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"; + + public ActorIdentity { + requireNonNil(characterUuid, "characterUuid"); + requireNonNilWhenPresent(accountUuid, "accountUuid"); + requireNonNilWhenPresent(tenantUuid, "tenantUuid"); + requireNonNilWhenPresent(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(status, "status"); + if (playableStateScope != null) { + requireScope(playableStateScope); + } + if (status == ActorIdentityStatus.OWNER_RESOLVED) { + requireNonNil(accountUuid, "accountUuid"); + requireNonNil(tenantUuid, "tenantUuid"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireScope(playableStateScope); + if (StringUtils.hasText(quarantineReason)) { + throw new IllegalArgumentException( + "owner-resolved identity cannot have a quarantine reason"); + } + } else if (!StringUtils.hasText(quarantineReason)) { + throw new IllegalArgumentException("quarantined identity requires a quarantine reason"); + } + } + + public static UUID parseRequiredUuid(String value, String fieldName) { + if (!StringUtils.hasText(value) || !value.matches(UUID_PATTERN)) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID"); + } + UUID parsed = UUID.fromString(value); + requireNonNil(parsed, fieldName); + return parsed; + } + + private static void requireNonNil(UUID value, String fieldName) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a non-nil UUID"); + } + } + + private static void requireNonNilWhenPresent(UUID value, String fieldName) { + if (value != null && NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must not be the nil UUID"); + } + } + + public static PlayableStateScope requireScope(PlayableStateScope scope) { + if (scope == null + || (scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + && scope != PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) { + throw new IllegalArgumentException("playableStateScope must be owner-resolved"); + } + return scope; + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java new file mode 100644 index 0000000000..67bcce21ee --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/ActorIdentityStatus.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.entitymanagement.entity; + +public enum ActorIdentityStatus { + OWNER_RESOLVED, + QUARANTINED +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java new file mode 100644 index 0000000000..83de1b6c5c --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static net.firedevops.firemud.entitymanagement.jooq.Tables.CHARACTERS; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentity; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; + +/** + * Exact, uncached canonical actor lookup. It intentionally has no write or resolution operation. + */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class ActorIdentityRepository { + private final DSLContext dsl; + + public ActorIdentityRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public List findOwnerResolvedRoster( + String tenantUuid, + String accountUuid, + String playableStateNamespaceId, + PlayableStateScope playableStateScope) { + UUID tenant = ActorIdentity.parseRequiredUuid(tenantUuid, "tenantUuid"); + UUID account = ActorIdentity.parseRequiredUuid(accountUuid, "accountUuid"); + UUID namespace = + ActorIdentity.parseRequiredUuid(playableStateNamespaceId, "playableStateNamespaceId"); + PlayableStateScope scope = ActorIdentity.requireScope(playableStateScope); + return dsl.select( + CHARACTERS.CHARACTER_UUID, + CHARACTERS.ACCOUNT_UUID, + CHARACTERS.TENANT_UUID, + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, + CHARACTERS.PLAYABLE_STATE_SCOPE, + CHARACTERS.ACTOR_IDENTITY_STATUS, + CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON) + .from(CHARACTERS) + .where( + CHARACTERS + .ACTOR_IDENTITY_STATUS + .eq(ActorIdentityStatus.OWNER_RESOLVED.name()) + .and(CHARACTERS.TENANT_UUID.eq(tenant)) + .and(CHARACTERS.ACCOUNT_UUID.eq(account)) + .and(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq(namespace)) + .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(scope.name()))) + .orderBy(CHARACTERS.CHARACTER_UUID.asc()) + .fetch(this::toIdentity); + } + + public Optional findOwnerResolvedActor( + String tenantUuid, + String accountUuid, + String playableStateNamespaceId, + PlayableStateScope playableStateScope, + String characterUuid) { + UUID tenant = ActorIdentity.parseRequiredUuid(tenantUuid, "tenantUuid"); + UUID account = ActorIdentity.parseRequiredUuid(accountUuid, "accountUuid"); + UUID namespace = + ActorIdentity.parseRequiredUuid(playableStateNamespaceId, "playableStateNamespaceId"); + PlayableStateScope scope = ActorIdentity.requireScope(playableStateScope); + UUID requestedCharacter = ActorIdentity.parseRequiredUuid(characterUuid, "characterUuid"); + return Optional.ofNullable( + dsl.select( + CHARACTERS.CHARACTER_UUID, + CHARACTERS.ACCOUNT_UUID, + CHARACTERS.TENANT_UUID, + CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID, + CHARACTERS.PLAYABLE_STATE_SCOPE, + CHARACTERS.ACTOR_IDENTITY_STATUS, + CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON) + .from(CHARACTERS) + .where( + CHARACTERS + .ACTOR_IDENTITY_STATUS + .eq(ActorIdentityStatus.OWNER_RESOLVED.name()) + .and(CHARACTERS.TENANT_UUID.eq(tenant)) + .and(CHARACTERS.ACCOUNT_UUID.eq(account)) + .and(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID.eq(namespace)) + .and(CHARACTERS.PLAYABLE_STATE_SCOPE.eq(scope.name())) + .and(CHARACTERS.CHARACTER_UUID.eq(requestedCharacter))) + .fetchOne(this::toIdentity)); + } + + private ActorIdentity toIdentity(Record record) { + return new ActorIdentity( + record.get(CHARACTERS.CHARACTER_UUID), + record.get(CHARACTERS.ACCOUNT_UUID), + record.get(CHARACTERS.TENANT_UUID), + record.get(CHARACTERS.PLAYABLE_STATE_NAMESPACE_ID), + PlayableStateScope.valueOf(record.get(CHARACTERS.PLAYABLE_STATE_SCOPE)), + ActorIdentityStatus.valueOf(record.get(CHARACTERS.ACTOR_IDENTITY_STATUS)), + record.get(CHARACTERS.ACTOR_IDENTITY_QUARANTINE_REASON)); + } +} diff --git a/services/entity-management-service/src/main/resources/db/migration/V3__quarantine_unresolved_actor_identity.sql b/services/entity-management-service/src/main/resources/db/migration/V3__quarantine_unresolved_actor_identity.sql new file mode 100644 index 0000000000..5afffedd27 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V3__quarantine_unresolved_actor_identity.sql @@ -0,0 +1,174 @@ +-- Add canonical actor identity after the immutable V1/V2 history. Numeric Account/tenant +-- columns remain provenance only; retained rows have no trusted owner UUID mapping. +CREATE TABLE entity_playable_state_namespace_scopes ( + tenant_uuid UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(40) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_entity_playable_state_namespace_scopes + PRIMARY KEY (tenant_uuid, playable_state_namespace_id), + CONSTRAINT ck_entity_playable_state_namespace_scope + CHECK (playable_state_scope IN ( + 'PLAYABLE_STATE_SCOPE_SHARED', + 'PLAYABLE_STATE_SCOPE_ISOLATED' + )), + CONSTRAINT ck_entity_playable_state_namespace_tenant_non_nil + CHECK (tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_entity_playable_state_namespace_id_non_nil + CHECK (playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ux_entity_playable_state_namespace_scope + UNIQUE (tenant_uuid, playable_state_namespace_id, playable_state_scope) +); + +/* [jooq ignore start] */ +CREATE FUNCTION reject_entity_playable_state_namespace_scope_change() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF (NEW.tenant_uuid, NEW.playable_state_namespace_id, NEW.playable_state_scope) + IS DISTINCT FROM + (OLD.tenant_uuid, OLD.playable_state_namespace_id, OLD.playable_state_scope) THEN + RAISE EXCEPTION 'Entity playable-state namespace identity is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_entity_playable_state_namespace_scopes_immutable + BEFORE UPDATE OF tenant_uuid, playable_state_namespace_id, playable_state_scope + ON entity_playable_state_namespace_scopes + FOR EACH ROW + EXECUTE FUNCTION reject_entity_playable_state_namespace_scope_change(); +/* [jooq ignore stop] */ + +ALTER TABLE characters + ADD COLUMN character_uuid UUID, + ADD COLUMN account_uuid UUID, + ADD COLUMN tenant_uuid UUID, + ADD COLUMN playable_state_namespace_id UUID, + ADD COLUMN playable_state_scope VARCHAR(40), + ADD COLUMN actor_identity_status VARCHAR(24) NOT NULL DEFAULT 'QUARANTINED', + ADD COLUMN actor_identity_quarantine_reason VARCHAR(80) + DEFAULT 'OWNER_PROVENANCE_MISSING'; + +UPDATE characters +SET character_uuid = gen_random_uuid(), + actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING'; + +-- This retained-row backfill updates every existing character in one migration transaction. +-- Quiesce Entity character writes for this migration; it is not an online activation procedure. +ALTER TABLE characters + ALTER COLUMN character_uuid SET DEFAULT gen_random_uuid(); + +/* [jooq ignore start] */ +ALTER TABLE characters + ADD CONSTRAINT ck_characters_character_uuid_nonnull + CHECK (character_uuid IS NOT NULL) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_character_uuid_non_nil + CHECK (character_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_status + CHECK (actor_identity_status IN ('OWNER_RESOLVED', 'QUARANTINED')) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_quarantine_reason + CHECK ( + (actor_identity_status = 'QUARANTINED' + AND actor_identity_quarantine_reason IS NOT NULL + AND length(trim(actor_identity_quarantine_reason)) > 0) + OR (actor_identity_status = 'OWNER_RESOLVED' + AND actor_identity_quarantine_reason IS NULL) + ) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_uuid_non_nil + CHECK ( + (account_uuid IS NULL OR account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (tenant_uuid IS NULL OR tenant_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (playable_state_namespace_id IS NULL OR playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID) + ) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_actor_identity_scope + CHECK ( + playable_state_scope IS NULL + OR playable_state_scope IN ( + 'PLAYABLE_STATE_SCOPE_SHARED', + 'PLAYABLE_STATE_SCOPE_ISOLATED' + ) + ) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT ck_characters_owner_resolved_provenance + CHECK ( + actor_identity_status <> 'OWNER_RESOLVED' + OR ( + account_uuid IS NOT NULL + AND tenant_uuid IS NOT NULL + AND playable_state_namespace_id IS NOT NULL + AND playable_state_scope IS NOT NULL + ) + ) NOT VALID; + +ALTER TABLE characters + ADD CONSTRAINT fk_characters_owner_resolved_namespace_scope + FOREIGN KEY (tenant_uuid, playable_state_namespace_id, playable_state_scope) + REFERENCES entity_playable_state_namespace_scopes ( + tenant_uuid, + playable_state_namespace_id, + playable_state_scope + ) NOT VALID; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +CREATE VIEW entity_quarantined_actor_item_instances AS +WITH RECURSIVE retained_item_instances(tenant_id, item_instance_id) AS ( + SELECT item_instance.tenant_id, item_instance.id + FROM item_instances item_instance + JOIN characters actor + ON actor.id = item_instance.character_id + AND actor.actor_identity_status = 'QUARANTINED' + + UNION + + SELECT container.tenant_id, container.item_instance_id + FROM container_instances container + JOIN characters actor + ON actor.id = container.character_id + AND actor.actor_identity_status = 'QUARANTINED' + WHERE container.item_instance_id IS NOT NULL + + UNION + + SELECT child_item.tenant_id, child_item.id + FROM retained_item_instances retained_parent + JOIN container_instances parent_container + ON parent_container.tenant_id = retained_parent.tenant_id + AND parent_container.item_instance_id = retained_parent.item_instance_id + JOIN item_instances child_item + ON child_item.tenant_id = parent_container.tenant_id + AND child_item.container_instance_id = parent_container.id +) +SELECT DISTINCT tenant_id, item_instance_id +FROM retained_item_instances; + +CREATE VIEW entity_quarantined_actor_container_instances AS +SELECT DISTINCT container.tenant_id, container.id AS container_instance_id +FROM container_instances container +JOIN characters actor + ON actor.id = container.character_id + AND actor.actor_identity_status = 'QUARANTINED' + +UNION + +SELECT DISTINCT container.tenant_id, container.id AS container_instance_id +FROM container_instances container +JOIN entity_quarantined_actor_item_instances retained_item + ON retained_item.tenant_id = container.tenant_id + AND retained_item.item_instance_id = container.item_instance_id; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V4__build_actor_identity_indexes_concurrently.sql b/services/entity-management-service/src/main/resources/db/migration/V4__build_actor_identity_indexes_concurrently.sql new file mode 100644 index 0000000000..da86ec481a --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V4__build_actor_identity_indexes_concurrently.sql @@ -0,0 +1,20 @@ +/* [jooq ignore start] */ +CREATE UNIQUE INDEX CONCURRENTLY ux_characters_character_uuid_idx + ON characters (character_uuid); + +CREATE INDEX CONCURRENTLY idx_characters_owner_resolved_roster + ON characters ( + tenant_uuid, + account_uuid, + playable_state_namespace_id, + playable_state_scope, + character_uuid + ) + WHERE actor_identity_status = 'OWNER_RESOLVED'; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +ALTER TABLE characters + ADD CONSTRAINT ux_characters_character_uuid + UNIQUE USING INDEX ux_characters_character_uuid_idx; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V4__build_actor_identity_indexes_concurrently.sql.conf b/services/entity-management-service/src/main/resources/db/migration/V4__build_actor_identity_indexes_concurrently.sql.conf new file mode 100644 index 0000000000..73bd53a146 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V4__build_actor_identity_indexes_concurrently.sql.conf @@ -0,0 +1 @@ +executeInTransaction=false diff --git a/services/entity-management-service/src/main/resources/db/migration/V5__validate_actor_identity_constraints.sql b/services/entity-management-service/src/main/resources/db/migration/V5__validate_actor_identity_constraints.sql new file mode 100644 index 0000000000..0a927a7853 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V5__validate_actor_identity_constraints.sql @@ -0,0 +1,34 @@ +/* [jooq ignore start] */ +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_character_uuid_nonnull; +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_character_uuid_non_nil; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_status; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_quarantine_reason; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_uuid_non_nil; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_actor_identity_scope; + +ALTER TABLE characters + VALIDATE CONSTRAINT ck_characters_owner_resolved_provenance; + +ALTER TABLE characters + VALIDATE CONSTRAINT fk_characters_owner_resolved_namespace_scope; +/* [jooq ignore stop] */ + +-- Take the stronger lock only after all validation scans have completed. The validated +-- non-null check remains present so PostgreSQL can avoid another full-table scan. +ALTER TABLE characters + ALTER COLUMN character_uuid SET NOT NULL; + +/* [jooq ignore start] */ +ALTER TABLE characters + DROP CONSTRAINT ck_characters_character_uuid_nonnull; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalActorIdentityFoundationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalActorIdentityFoundationPostgresIntegrationTest.java new file mode 100644 index 0000000000..4841642c30 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalActorIdentityFoundationPostgresIntegrationTest.java @@ -0,0 +1,299 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; +import net.firedevops.firemud.entitymanagement.entity.Character; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Physical PostgreSQL proof for additive canonical actor identity and legacy quarantine. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalActorIdentityFoundationPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final UUID TENANT_A = uuid("10000000-0000-4000-8000-000000000001"); + private static final UUID TENANT_B = uuid("10000000-0000-4000-8000-000000000002"); + private static final UUID ACCOUNT_A = uuid("20000000-0000-4000-8000-000000000001"); + private static final UUID ACCOUNT_B = uuid("20000000-0000-4000-8000-000000000002"); + private static final UUID NAMESPACE_SHARED = uuid("30000000-0000-4000-8000-000000000001"); + private static final UUID NAMESPACE_ISOLATED = uuid("30000000-0000-4000-8000-000000000002"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DriverManagerDataSource dataSource; + private DSLContext dsl; + + @BeforeEach + void migrateImmutableHistoryBeforeSeedingLegacyActors() { + schema = "entity_actor_identity_" + UUID.randomUUID().toString().replace("-", ""); + dataSource = dataSource(schema); + configureFlyway(MigrationVersion.fromVersion("2")).migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + } + + @AfterEach + void dropIsolatedSchema() { + if (schema != null) { + String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE"); + schema = null; + } + } + + @Test + void retainedNumericRowsAreQuarantinedAndLegacyWriterCannotPromoteThem() { + CharacterRepository legacyWriter = new CharacterRepository(dsl); + Character retained = legacyCharacter(7101L, 8101L, "retained-legacy"); + long retainedId = legacyWriter.save(retained).getId(); + + migrateAll(); + + var migrated = readIdentityRow(retainedId); + UUID retainedCharacterUuid = migrated.get("character_uuid", UUID.class); + assertThat(retainedCharacterUuid).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(migrated.get("account_id", Long.class)).isEqualTo(8101L); + assertThat(migrated.get("tenant_id", Long.class)).isEqualTo(7101L); + assertThat(migrated.get("account_uuid", UUID.class)).isNull(); + assertThat(migrated.get("tenant_uuid", UUID.class)).isNull(); + assertThat(migrated.get("playable_state_namespace_id", UUID.class)).isNull(); + assertThat(migrated.get("actor_identity_status", String.class)) + .isEqualTo(ActorIdentityStatus.QUARANTINED.name()); + assertThat(migrated.get("actor_identity_quarantine_reason", String.class)) + .isEqualTo("OWNER_PROVENANCE_MISSING"); + assertThat( + identityRepository() + .findOwnerResolvedRoster( + TENANT_A.toString(), + ACCOUNT_A.toString(), + NAMESPACE_SHARED.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + + Character writtenByLegacyPath = + legacyWriter.save(legacyCharacter(7102L, 8102L, "new-legacy-path")); + var newlyWritten = readIdentityRow(writtenByLegacyPath.getId()); + assertThat(newlyWritten.get("character_uuid", UUID.class)).isNotNull(); + assertThat(newlyWritten.get("actor_identity_status", String.class)) + .isEqualTo(ActorIdentityStatus.QUARANTINED.name()); + assertThat( + identityRepository() + .findOwnerResolvedActor( + TENANT_A.toString(), + ACCOUNT_A.toString(), + NAMESPACE_SHARED.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + newlyWritten.get("character_uuid", UUID.class).toString())) + .isEmpty(); + + long reservedTenantKey = 9900101L; + dsl.execute( + "INSERT INTO entity_empty_source_numeric_key_reservation " + + "(key_kind, numeric_key, claim_kind) VALUES ('TENANT', ?, 'CANONICAL_EMPTY_SOURCE')", + reservedTenantKey); + assertThatThrownBy( + () -> legacyWriter.save(legacyCharacter(reservedTenantKey, 8103L, "reserved-key"))) + .isInstanceOf(DataAccessException.class); + } + + @Test + void ownerResolvedLookupsFilterExactTenantAccountNamespaceAndScope() { + migrateAll(); + insertNamespace(TENANT_A, NAMESPACE_SHARED, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + insertNamespace(TENANT_A, NAMESPACE_ISOLATED, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED); + insertNamespace(TENANT_B, NAMESPACE_SHARED, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + UUID targetCharacter = uuid("40000000-0000-4000-8000-000000000001"); + UUID otherAccountCharacter = uuid("40000000-0000-4000-8000-000000000002"); + UUID otherNamespaceCharacter = uuid("40000000-0000-4000-8000-000000000003"); + UUID otherTenantCharacter = uuid("40000000-0000-4000-8000-000000000004"); + insertOwnerResolvedActor( + 7201L, + 8201L, + targetCharacter, + TENANT_A, + ACCOUNT_A, + NAMESPACE_SHARED, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + insertOwnerResolvedActor( + 7201L, + 8202L, + otherAccountCharacter, + TENANT_A, + ACCOUNT_B, + NAMESPACE_SHARED, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + insertOwnerResolvedActor( + 7201L, + 8201L, + otherNamespaceCharacter, + TENANT_A, + ACCOUNT_A, + NAMESPACE_ISOLATED, + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED); + insertOwnerResolvedActor( + 7202L, + 8201L, + otherTenantCharacter, + TENANT_B, + ACCOUNT_A, + NAMESPACE_SHARED, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + + ActorIdentityRepository repository = identityRepository(); + assertThat( + repository.findOwnerResolvedRoster( + TENANT_A.toString(), + ACCOUNT_A.toString(), + NAMESPACE_SHARED.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .extracting(identity -> identity.characterUuid()) + .containsExactly(targetCharacter); + assertThat( + repository.findOwnerResolvedRoster( + TENANT_A.toString(), + ACCOUNT_A.toString(), + NAMESPACE_ISOLATED.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + .isEmpty(); + assertThat( + repository.findOwnerResolvedActor( + TENANT_A.toString(), + ACCOUNT_A.toString(), + NAMESPACE_SHARED.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + targetCharacter.toString())) + .map(identity -> identity.characterUuid()) + .contains(targetCharacter); + assertThat( + repository.findOwnerResolvedActor( + TENANT_A.toString(), + ACCOUNT_B.toString(), + NAMESPACE_SHARED.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + targetCharacter.toString())) + .isEmpty(); + assertThat( + repository.findOwnerResolvedActor( + TENANT_B.toString(), + ACCOUNT_A.toString(), + NAMESPACE_SHARED.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + targetCharacter.toString())) + .isEmpty(); + assertThat( + repository.findOwnerResolvedActor( + TENANT_A.toString(), + ACCOUNT_A.toString(), + NAMESPACE_ISOLATED.toString(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED, + targetCharacter.toString())) + .isEmpty(); + } + + private Flyway configureFlyway(MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)); + return (target == null ? configuration : configuration.target(target)).load(); + } + + private void migrateAll() { + configureFlyway(null).migrate(); + } + + private org.jooq.Record readIdentityRow(long id) { + return dsl.fetchOne( + "SELECT id, account_id, tenant_id, character_uuid, account_uuid, tenant_uuid, " + + "playable_state_namespace_id, playable_state_scope, actor_identity_status, " + + "actor_identity_quarantine_reason FROM characters WHERE id = ?", + id); + } + + private void insertNamespace(UUID tenant, UUID namespace, PlayableStateScope scope) { + dsl.execute( + "INSERT INTO entity_playable_state_namespace_scopes " + + "(tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, ?)", + tenant, + namespace, + scope.name()); + } + + private void insertOwnerResolvedActor( + long numericTenant, + long numericAccount, + UUID character, + UUID tenant, + UUID account, + UUID namespace, + PlayableStateScope scope) { + dsl.execute( + "INSERT INTO characters (tenant_id, account_id, playable_state_key, name, " + + "character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, " + + "playable_state_scope, actor_identity_status, actor_identity_quarantine_reason) " + + "VALUES (?, ?, 'identity-fixture', ?, ?, ?, ?, ?, ?, 'OWNER_RESOLVED', NULL)", + numericTenant, + numericAccount, + "canonical-" + character, + character, + account, + tenant, + namespace, + scope.name()); + } + + private ActorIdentityRepository identityRepository() { + return new ActorIdentityRepository(dsl); + } + + private static Character legacyCharacter(long tenantId, long accountId, String name) { + Character character = new Character(); + character.setTenantId(tenantId); + character.setAccountId(accountId); + character.setPlayableStateKey("legacy-numeric"); + character.setName(name); + return character; + } + + private static DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource source = new DriverManagerDataSource(); + source.setDriverClassName("org.postgresql.Driver"); + source.setUrl(postgres.getJdbcUrl()); + source.setUsername(postgres.getUsername()); + source.setPassword(postgres.getPassword()); + if (schema != null) { + source.setSchema(schema); + } + return source; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java index f0f474d148..c58cfdbf19 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -105,11 +105,11 @@ void migrationSeedsActualLegacySourceAndAuditTenantVersionKeys() { assertLegacyKey("TENANT", 61001L); assertLegacyKey("VERSION", 51001L); assertThat( - dsl.fetchValue( - "SELECT COUNT(*) FROM entity_empty_source_numeric_key_reservation " - + "WHERE key_kind = 'VERSION' AND numeric_key = 51001 " - + "AND claim_kind = 'LEGACY_NUMERIC'", - Long.class)) + dsl.fetchSingle( + "SELECT COUNT(*) FROM entity_empty_source_numeric_key_reservation " + + "WHERE key_kind = 'VERSION' AND numeric_key = 51001 " + + "AND claim_kind = 'LEGACY_NUMERIC'") + .get(0, Long.class)) .isEqualTo(1L); } @@ -142,21 +142,24 @@ void unassociatedLegacyKeysRemainWritable() { "INSERT INTO characters (account_id, name, tenant_id) " + "VALUES (3, 'unassociated legacy character', 72001)"); - assertThat(dsl.fetchValue("SELECT COUNT(*) FROM items WHERE tenant_id = 71001", Long.class)) + assertThat( + dsl.fetchSingle("SELECT COUNT(*) FROM items WHERE tenant_id = 71001") + .get(0, Long.class)) .isEqualTo(1L); assertThat( - dsl.fetchValue("SELECT COUNT(*) FROM characters WHERE tenant_id = 72001", Long.class)) + dsl.fetchSingle("SELECT COUNT(*) FROM characters WHERE tenant_id = 72001") + .get(0, Long.class)) .isEqualTo(1L); } private void assertLegacyKey(String kind, long key) { assertThat( - dsl.fetchValue( - "SELECT claim_kind FROM entity_empty_source_numeric_key_reservation " - + "WHERE key_kind = ? AND numeric_key = ?", - String.class, - kind, - key)) + dsl.fetchSingle( + "SELECT claim_kind FROM entity_empty_source_numeric_key_reservation " + + "WHERE key_kind = ? AND numeric_key = ?", + kind, + key) + .get(0, String.class)) .isEqualTo("LEGACY_NUMERIC"); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java new file mode 100644 index 0000000000..e4ec45fe07 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java @@ -0,0 +1,108 @@ +package net.firedevops.firemud.entitymanagement.entity; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import org.junit.jupiter.api.Test; + +class ActorIdentityValueTest { + private static final UUID ACTOR_UUID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_UUID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID TENANT_UUID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID NAMESPACE_UUID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void parsesOnlyCompleteNonNilUuidValues() { + assertEquals(ACTOR_UUID, ActorIdentity.parseRequiredUuid(ACTOR_UUID.toString(), "actor")); + assertThrows( + IllegalArgumentException.class, () -> ActorIdentity.parseRequiredUuid(null, "actor")); + assertThrows( + IllegalArgumentException.class, + () -> ActorIdentity.parseRequiredUuid("not-a-uuid", "actor")); + assertThrows( + IllegalArgumentException.class, + () -> ActorIdentity.parseRequiredUuid("00000000-0000-0000-0000-000000000000", "actor")); + } + + @Test + void ownerResolvedIdentityRequiresExactAccountTenantNamespaceAndScope() { + var identity = + new ActorIdentity( + ACTOR_UUID, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + ActorIdentityStatus.OWNER_RESOLVED, + null); + assertEquals(ActorIdentityStatus.OWNER_RESOLVED, identity.status()); + + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, + null, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + ActorIdentityStatus.OWNER_RESOLVED, + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED, + ActorIdentityStatus.OWNER_RESOLVED, + null)); + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, + ACCOUNT_UUID, + TENANT_UUID, + NAMESPACE_UUID, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + ActorIdentityStatus.OWNER_RESOLVED, + "LEGACY_IDENTITY")); + } + + @Test + void quarantineCanRetainIncompleteSourceProvenanceWithoutCreatingAnAlias() { + var quarantined = + new ActorIdentity( + ACTOR_UUID, + null, + null, + null, + null, + ActorIdentityStatus.QUARANTINED, + "OWNER_PROVENANCE_MISSING"); + assertEquals(ActorIdentityStatus.QUARANTINED, quarantined.status()); + + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + new UUID(0L, 0L), + null, + null, + null, + null, + ActorIdentityStatus.QUARANTINED, + "OWNER_PROVENANCE_MISSING")); + assertThrows( + IllegalArgumentException.class, + () -> + new ActorIdentity( + ACTOR_UUID, ACCOUNT_UUID, null, null, null, ActorIdentityStatus.QUARANTINED, " ")); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index b7a7b45c54..2f8a8befa9 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -4,8 +4,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; -import com.google.protobuf.ByteString; -import com.google.protobuf.Timestamp; import com.google.protobuf.util.JsonFormat; import io.grpc.BindableService; import io.grpc.Context; @@ -14,11 +12,11 @@ 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.stub.StreamObserver; import io.grpc.util.MutableHandlerRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -27,6 +25,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; @@ -39,13 +38,10 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; -import net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference; -import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; -import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; -import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; @@ -109,6 +105,8 @@ import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeAuthorizationClient; import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeRetainClient; import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeSourceReadClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -139,6 +137,9 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeService; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeTerminalReadService; @@ -249,6 +250,16 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceExecutionIdentity; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationAssemblyService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingService; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftCommitOrderVerifier; import net.firedevops.firemud.worldmanagement.tenant.WorldDraftGraphApplicationRepository; @@ -279,6 +290,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mapstruct.factory.Mappers; +import org.mockito.Mockito; import org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -327,13 +339,19 @@ * Design, Entity, World and settlement boundaries over loopback mTLS, with an isolated Entity * PostgreSQL schema and migration path. Entity and Automation publication digests use their native * mTLS selected-empty owner readers and exact retained receipts; nonempty owner publication remains - * outside this proof. The StartSession Account projection remains a test double. MinIO object-store - * I/O is real. The complete launch-binding case wires the actual Game Design handler and World + * outside this proof. StartSession issuance and redemption use the real Account owner and retained + * rows under stipulated Logging current-claim evidence and issuer/redeemer peer contexts; the + * read-only projection uses the real Account receiver over Game Design mTLS. MinIO object-store I/O + * is real. The complete launch-binding case wires the actual Game Design handler and World * Management mTLS client on this fixture's loopback server to the actual owner implementation in an * explicitly established read-only repeatable-read snapshot; unrelated handler dependencies are - * isolated. This fixture does not provide production-mounted certificates or full application - * server wiring, production ingress, Account-projection-backed StartSession admission, runtime - * launch, activation or registration. + * isolated. The World preparation composition reuses the genuine persisted source, frozen graph, + * and complete released pair through actual World owner services and Game Session mTLS, but its + * Game Session launch association and continuous held-Account/Game-Session commit authority are + * explicitly stipulated; the supplied Game Session attempt/fence is not independently proven. This + * does not establish production-authenticated Logging claims, Game Session admission, or launch + * authorization. The fixture does not provide production-mounted certificates or full application + * server wiring, production ingress, runtime launch, activation or registration. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -458,7 +476,6 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var gameLogicHandlers = new MutableHandlerRegistry(); var automationHandlers = new MutableHandlerRegistry(); var entityHandlers = new MutableHandlerRegistry(); - Map startSessionProjections = new ConcurrentHashMap<>(); Server gdServer = startServer(pki, "game-design-service", gdHandlers); Server worldServer = startServer(pki, "world-management-service", worldHandlers); @@ -901,7 +918,10 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new AccountGameLogicIntakeAuthorizationReadGrpcService( accountHeldAuthorizationOwner, NAMESPACE), new AccountGameLogicIntakeSettlementGrpcService(accountSettlementOwner, NAMESPACE)); - register(accountHandlers, accountProjectionDouble(startSessionProjections)); + var startSessionAuthorizationProof = + new AccountOriginalStartSessionAuthorizationProofFixture( + account, temporary.resolve("account-start-session-authorization-proof"), NAMESPACE); + register(accountHandlers, startSessionAuthorizationProof.grpcService()); var glOwner = new GameLogicGameplayRuleIntakeService( @@ -2642,20 +2662,69 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex association.digest()); String controlPlaneRequestId = "genuine-start-session-" + UUID.randomUUID(); UUID ownerAttemptId = UUID.randomUUID(); - long ownerFence = 19L; - var startSessionTuple = - startSessionTuple( - controlPlaneRequestId, - gd.target().canonicalTenantId(), - templateId, + long ownerFence = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); + UUID reservationOwnerId = UUID.randomUUID(); + long reservationClaimFence = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); + var originalStartSessionAction = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(gd.target().canonicalTenantId(), NAMESPACE), + new StartSessionOperatorAction.Target( + templateId, startSessionAuthorizationProof.creatorAccountId()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), "Genuine selected descriptor storage proof"); - startSessionProjections.put( - controlPlaneRequestId, - new StartSessionProjectionBinding(startSessionTuple, ownerAttemptId, ownerFence)); + var originalStartSession = + startSessionAuthorizationProof.issueAndRedeemOriginal( + controlPlaneRequestId, + originalStartSessionAction, + reservationOwnerId, + reservationClaimFence, + ownerAttemptId, + ownerFence); + var startSessionTuple = originalStartSession.originalTuple(); try (var projectionClient = new StartSessionRedeemedOperationProjectionClient( endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { projectionClient.init(); + var accountProjection = + projectionClient.read(startSessionTuple, ownerAttemptId, ownerFence); + assertThat(accountProjection.getControlPlaneRequestId()).isEqualTo(controlPlaneRequestId); + assertThat(accountProjection.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly( + startSessionTuple + .preAuthorizationTuple() + .canonicalJson() + .getBytes(StandardCharsets.UTF_8)); + assertThat(accountProjection.getMutationDigest()) + .isEqualTo(startSessionTuple.preAuthorizationTuple().mutationDigest()); + assertThat(accountProjection.getAuthorizationReferenceFingerprint()) + .isEqualTo(startSessionTuple.authorizationReferenceFingerprint()); + assertThat(accountProjection.getReservationOwnerId()) + .isEqualTo(reservationOwnerId.toString()); + assertThat(accountProjection.getReservationClaimFence()).isEqualTo(reservationClaimFence); + assertThat(accountProjection.getAuthenticatedRedeemerWorkloadIdentity()) + .isEqualTo("spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"); + assertThat(accountProjection.getOwnerAttemptId()).isEqualTo(ownerAttemptId.toString()); + assertThat(accountProjection.getOwnerFence()).isEqualTo(ownerFence); + assertThat(accountProjection.getIssuanceOperationId()) + .isEqualTo(originalStartSession.issuanceOperationId().toString()); + assertThat(accountProjection.getIssuanceFence()) + .isEqualTo(originalStartSession.issuanceFence()); + assertThat(accountProjection.getBundleReference().getBundleVersion()) + .isEqualTo(startSessionTuple.bundleReference().bundleVersion()); + assertThat(accountProjection.getBundleReference().getSourceVersion()) + .isEqualTo(startSessionTuple.bundleReference().sourceVersion()); + assertThat(accountProjection.getBundleReference().getSourceFence()) + .isEqualTo(startSessionTuple.bundleReference().sourceFence()); + assertThat(accountProjection.getBundleReference().getLinearization()) + .isEqualTo(startSessionTuple.bundleReference().linearization()); + assertThat(accountProjection.getAuthorityEvidenceBundle().toByteArray()) + .containsExactly(startSessionTuple.authorityEvidenceBundleBytes()); + assertThat(projectionClient.read(startSessionTuple, ownerAttemptId, ownerFence)) + .isEqualTo(accountProjection); var associationReader = new StartSessionTemplateAssociationReadService( gd.dsl(), gd.transactions(), NAMESPACE, projectionClient, releaseService); @@ -2927,6 +2996,388 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex controlPlaneRequestId)) .containsExactlyElementsOf(completeBindingOwnerRowsBefore); + // This is a composed World materialization proof over the exact source, frozen graph, + // and complete released pair already retained above. Only the Game Session launch-row + // read and the original Account/continuously-held Game Session authorization are + // stipulated here; this fixture does not claim those authorities were genuine. + CompleteLaunchBindingEvidence completeLaunchEvidence = + new CompleteLaunchBindingEvidence( + completeBinding.descriptor(), completeBinding.releaseAttestation()); + UUID canonicalGameInstanceId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + var preparationAssociationRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + NAMESPACE, + gd.target().canonicalTenantId(), + worldSource.worldSlug(), + canonicalGameInstanceId, + controlPlaneRequestId, + completeLaunchEvidence.descriptor().launchDescriptorId(), + completeLaunchEvidence.descriptor().requestDigest(), + completeLaunchEvidence.descriptor().resultDigest(), + completeLaunchEvidence.releaseAttestation().evidenceDigest()); + var stipulatedGameSessionReader = + Mockito.mock(CanonicalGameInstanceLaunchAssociationClient.class); + Mockito.when(stipulatedGameSessionReader.read(Mockito.any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, CanonicalGameInstanceLaunchAssociationReadEvidence.Request.class); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + request, + playableStateNamespaceId, + RealmEntryPolicy.StateScope.SHARED, + true, + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING, + 1L, + completeLaunchEvidence); + }); + + var completeBindingRepository = new WorldCompleteLaunchBindingRepository(world.dsl()); + var canonicalAssociationRepository = + new WorldCanonicalInstanceAssociationRepository( + world.dsl(), completeBindingRepository, worldIntakes, worldIdentities); + var preparationRepository = + new WorldCanonicalInstancePreparationRepository( + world.dsl(), + world.transactions(), + canonicalAssociationRepository, + worldPublicationProof.frozenTopologies(), + Duration.ofSeconds(30)); + var lifecycleRepository = + new WorldCanonicalInstanceLifecycleReadRepository( + world.dsl(), world.transactions(), canonicalAssociationRepository); + try (var worldToGameDesignPreparationClient = + new AuthoredWorldLaunchDescriptorClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + worldToGameDesignPreparationClient.init(); + var completeBindingService = + new WorldCompleteLaunchBindingService( + worldToGameDesignPreparationClient, + completeBindingRepository, + worldIntakes, + world.transactions(), + NAMESPACE, + null, + stipulatedGameSessionReader); + var preparationAssembly = + new WorldCanonicalInstancePreparationAssemblyService( + NAMESPACE, + completeBindingRepository, + worldIntakes, + worldIdentities, + worldPublicationProof.frozenTopologies(), + stipulatedGameSessionReader, + worldToGameDesignPreparationClient); + // The exact StartSession tuple and existing GS attempt/fence are preserved dynamically. + // Only Account participation/fence and the continuously held authority behavior are + // synthetic evidence shape; this does not authenticate either producer. + var syntheticIdentities = + new ConcurrentHashMap(); + var stipulatedHeldAuthority = + (WorldCanonicalInstancePreparationService.CommitAuthorityVerifier) + input -> { + String exactInputJson; + try { + exactInputJson = canonicalPreparationInputJson(input); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException( + "Could not reuse the canonical World preparation input serializer", + failure); + } + WorldCanonicalInstanceExecutionIdentity identity = + syntheticIdentities.computeIfAbsent( + exactInputJson, + ignored -> + new WorldCanonicalInstanceExecutionIdentity( + startSessionTuple.canonicalBytes(), + UUID.randomUUID(), + ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE), + ownerAttemptId, + ownerFence, + input.canonicalGameInstanceId(), + exactInputJson)); + return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + private boolean held = true; + + @Override + public void requireHeld() { + if (!held) { + throw new SecurityException( + "Synthetic StartSession proof handle was released"); + } + } + + @Override + public WorldCanonicalInstanceExecutionIdentity executionIdentity() { + return identity; + } + + @Override + public void close() { + held = false; + } + }; + }; + var preparationService = + new WorldCanonicalInstancePreparationService( + preparationRepository, stipulatedHeldAuthority); + register( + worldHandlers, + new WorldCanonicalInstancePreparationGrpcService( + completeBindingService, + preparationAssembly, + preparationService, + preparationRepository, + lifecycleRepository, + NAMESPACE)); + + var expectedLifecycleRequest = + lifecycleRequest( + preparationAssociationRequest, + completeLaunchEvidence, + playableStateNamespaceId); + var sourceRowsBeforePreparation = + retainedWorldPreparationEvidence( + world, + worldIntakeReceipt.intakeRequestId(), + worldIdentityReceipt.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId, + canonicalGameInstanceId, + completeWorldSelector.request().publicationFence()); + var rowsBeforeWrongPeer = canonicalPreparationRowCounts(world.dsl()); + try (var wrongWorkloadPreparationClient = + new CanonicalWorldInstancePreparationClient( + endpoints, pki.client("account-service"), channels, NAMESPACE)) { + wrongWorkloadPreparationClient.init(); + assertThatThrownBy( + () -> + wrongWorkloadPreparationClient.prepare( + preparationAssociationRequest, expectedLifecycleRequest)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat( + ((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + } + assertThat(canonicalPreparationRowCounts(world.dsl())).isEqualTo(rowsBeforeWrongPeer); + assertThat( + retainedWorldPreparationEvidence( + world, + worldIntakeReceipt.intakeRequestId(), + worldIdentityReceipt.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId, + canonicalGameInstanceId, + completeWorldSelector.request().publicationFence())) + .isEqualTo(sourceRowsBeforePreparation); + + WorldCanonicalInstanceLifecycleEvidence preparedLifecycle; + try (var gameSessionPreparationClient = + new CanonicalWorldInstancePreparationClient( + endpoints, pki.client("game-session-service"), channels, NAMESPACE)) { + gameSessionPreparationClient.init(); + preparedLifecycle = + gameSessionPreparationClient.prepare( + preparationAssociationRequest, expectedLifecycleRequest); + } + + var assembledPreparationInput = + preparationAssembly.assemble( + new WorldCanonicalInstancePreparationAssemblyService.Selector( + gd.target().canonicalTenantId(), + canonicalGameInstanceId, + controlPlaneRequestId)); + var preparationResult = + preparationRepository.readOwnerPreparation(assembledPreparationInput).orElseThrow(); + var stipulatedGameSessionEvidence = assembledPreparationInput.gameSessionReadEvidence(); + var independentLifecycleRead = + lifecycleRepository.read(expectedLifecycleRequest).orElseThrow(); + var selectedReleasedStart = + WorldDraftStartLocationEvidence.fromStored( + completeLaunchEvidence + .releaseAttestation() + .worldStartLocationEvidence() + .selectorReceiptBytes()); + assertThat(preparedLifecycle).isEqualTo(independentLifecycleRead); + assertThat(preparedLifecycle.request()).isEqualTo(expectedLifecycleRequest); + assertThat(preparedLifecycle.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(preparedLifecycle.lifecycleEpoch()).isEqualTo(1L); + assertThat(preparedLifecycle.launchBinding()).isEqualTo(completeLaunchEvidence); + assertThat(stipulatedGameSessionEvidence.currentGameSessionStatus()) + .isEqualTo("STARTING"); + assertThat(stipulatedGameSessionEvidence.currentGameSessionRowVersion()).isEqualTo(1L); + assertThat(stipulatedGameSessionEvidence.playableStateScope()).isEqualTo("SHARED"); + assertThat(stipulatedGameSessionEvidence.publicProduction()).isTrue(); + assertThat(stipulatedGameSessionEvidence.descriptor()) + .isEqualTo(completeLaunchEvidence.descriptor()); + assertThat(stipulatedGameSessionEvidence.releaseAttestation()) + .isEqualTo(completeLaunchEvidence.releaseAttestation()); + assertThat(preparedLifecycle.captureId()) + .isEqualTo(assembledPreparationInput.captureId()); + assertThat(preparedLifecycle.graphSha256()).isEqualTo(preparationResult.graphSha256()); + assertThat(preparedLifecycle.preparationInputDigest()) + .isEqualTo(preparationResult.inputDigest()); + assertThat(preparationResult.storageStatus()).isEqualTo("MATERIALIZED_UNVERIFIED"); + assertThat(preparedLifecycle.startLocation()) + .isEqualTo(selectedReleasedStart.startLocation()); + assertThat(preparedLifecycle.startLocation().tenantId()) + .isEqualTo(gd.target().canonicalTenantId()); + assertThat(preparedLifecycle.startLocation().versionId()) + .isEqualTo(gd.target().canonicalVersionId()); + assertThat( + assembledPreparationInput.topologyPlan().rooms().stream() + .map(room -> room.identity().templateId())) + .contains(preparedLifecycle.startLocation().roomTemplateId()); + assertThat(preparationResult.startLocation()) + .isEqualTo(preparedLifecycle.startLocation()); + assertThat(preparationResult.runtimeRoomInstanceId()) + .isEqualTo(preparedLifecycle.runtimeRoomInstanceId()); + + var rowsAfterFirstPreparation = canonicalPreparationRowCounts(world.dsl()); + assertThat(rowsAfterFirstPreparation.get("world_instance")) + .isGreaterThan(rowsBeforeWrongPeer.get("world_instance")); + assertThat(rowsAfterFirstPreparation.get("world_canonical_instance_preparation")) + .isGreaterThan(rowsBeforeWrongPeer.get("world_canonical_instance_preparation")); + assertThat(rowsAfterFirstPreparation.get("world_canonical_instance_execution")) + .isGreaterThan(rowsBeforeWrongPeer.get("world_canonical_instance_execution")); + var retainedOwnerEvidenceAfterPreparation = + retainedWorldPreparationEvidence( + world, + worldIntakeReceipt.intakeRequestId(), + worldIdentityReceipt.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId, + canonicalGameInstanceId, + completeWorldSelector.request().publicationFence()); + assertThat(retainedOwnerEvidenceAfterPreparation) + .containsEntry( + "worldSourceIntake", sourceRowsBeforePreparation.get("worldSourceIntake")) + .containsEntry( + "worldVersionIdentity", sourceRowsBeforePreparation.get("worldVersionIdentity")) + .containsEntry( + "worldFrozenCapture", sourceRowsBeforePreparation.get("worldFrozenCapture")); + assertThat(retainedOwnerEvidenceAfterPreparation.get("completeLaunchBinding")) + .isNotNull(); + assertThat(retainedOwnerEvidenceAfterPreparation.get("canonicalInstanceAssociation")) + .isNotNull(); + assertThat(retainedOwnerEvidenceAfterPreparation.get("canonicalInstancePreparation")) + .isNotNull(); + assertThat(retainedOwnerEvidenceAfterPreparation.get("canonicalTopologyIdentities")) + .isNotEqualTo("[]"); + assertThat(retainedOwnerEvidenceAfterPreparation.get("canonicalStartLocation")) + .isNotNull(); + assertThat(retainedOwnerEvidenceAfterPreparation.get("worldInstance")).isNotNull(); + + try (var gameSessionPreparationRetryClient = + new CanonicalWorldInstancePreparationClient( + endpoints, pki.client("game-session-service"), channels, NAMESPACE)) { + gameSessionPreparationRetryClient.init(); + assertThat( + gameSessionPreparationRetryClient.prepare( + preparationAssociationRequest, expectedLifecycleRequest)) + .isEqualTo(preparedLifecycle); + } + var retryInput = + preparationAssembly.assemble( + new WorldCanonicalInstancePreparationAssemblyService.Selector( + gd.target().canonicalTenantId(), + canonicalGameInstanceId, + controlPlaneRequestId)); + assertThat(preparationRepository.readOwnerPreparation(retryInput)) + .contains(preparationResult); + assertThat(lifecycleRepository.read(expectedLifecycleRequest)) + .contains(preparedLifecycle); + assertThat(canonicalPreparationRowCounts(world.dsl())) + .isEqualTo(rowsAfterFirstPreparation); + assertThat( + retainedWorldPreparationEvidence( + world, + worldIntakeReceipt.intakeRequestId(), + worldIdentityReceipt.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId, + canonicalGameInstanceId, + completeWorldSelector.request().publicationFence())) + .isEqualTo(retainedOwnerEvidenceAfterPreparation); + assertThat( + completeBindingOwnerRowVersions( + gd.dsl(), + persistedLaunchDescriptor.getId(), + release.id(), + gd.target().gameDesignVersionRowId(), + worldSource.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId)) + .containsExactlyElementsOf(completeBindingOwnerRowsBefore); + + MutableHandlerRegistry defaultDeniedHandlers = new MutableHandlerRegistry(); + register( + defaultDeniedHandlers, + new WorldCanonicalInstancePreparationGrpcService( + completeBindingService, + preparationAssembly, + new WorldCanonicalInstancePreparationService(preparationRepository), + preparationRepository, + lifecycleRepository, + NAMESPACE)); + Server defaultDeniedServer = + startServer(pki, "world-management-service", defaultDeniedHandlers); + try { + var defaultDeniedEndpoints = new ServiceEndpointsProperties(); + defaultDeniedEndpoints.setWorldManagementService(loopback(defaultDeniedServer)); + var countsBeforeDefaultDenied = canonicalPreparationRowCounts(world.dsl()); + var evidenceBeforeDefaultDenied = + retainedWorldPreparationEvidence( + world, + worldIntakeReceipt.intakeRequestId(), + worldIdentityReceipt.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId, + canonicalGameInstanceId, + completeWorldSelector.request().publicationFence()); + try (var defaultDeniedClient = + new CanonicalWorldInstancePreparationClient( + defaultDeniedEndpoints, + pki.client("game-session-service"), + channels, + NAMESPACE)) { + defaultDeniedClient.init(); + assertThatThrownBy( + () -> + defaultDeniedClient.prepare( + preparationAssociationRequest, expectedLifecycleRequest)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat( + ((io.grpc.StatusRuntimeException) failure) + .getStatus() + .getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + } + assertThat(canonicalPreparationRowCounts(world.dsl())) + .isEqualTo(countsBeforeDefaultDenied); + assertThat( + retainedWorldPreparationEvidence( + world, + worldIntakeReceipt.intakeRequestId(), + worldIdentityReceipt.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId, + canonicalGameInstanceId, + completeWorldSelector.request().publicationFence())) + .isEqualTo(evidenceBeforeDefaultDenied); + } finally { + stopAll(defaultDeniedServer); + } + } + var replay = withGameSessionPeer( () -> @@ -2941,15 +3392,16 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(replay.associationRead().request().readRequestId()) .isNotEqualTo(firstDescriptorBinding.associationRead().request().readRequestId()); + // This deliberately synthetic tuple is only a negative mismatch probe; unlike the + // positive path it is not issued by Account and is expected to be rejected by the real + // durable projection receiver. var changedTuple = startSessionTuple( controlPlaneRequestId, gd.target().canonicalTenantId(), templateId, "Changed original StartSession tuple"); - // The fixed Account projection double returns the original operation; these altered - // tuple/attempt/fence requests are rejected before Game Design opens its SQL snapshot. - assertProjectionUnavailable( + assertProjectionRejected( "original operation tuple", () -> withGameSessionPeer( @@ -2962,7 +3414,7 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex pinnedSelection, UUID.randomUUID())))); - assertProjectionUnavailable( + assertProjectionRejected( "owner attempt", () -> withGameSessionPeer( @@ -2970,11 +3422,13 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex descriptorProducer.resolve( startSessionReadRequest( startSessionTuple, - UUID.randomUUID(), + new UUID( + ownerAttemptId.getMostSignificantBits() ^ 1L, + ownerAttemptId.getLeastSignificantBits()), ownerFence, pinnedSelection, UUID.randomUUID())))); - assertProjectionUnavailable( + assertProjectionRejected( "owner fence", () -> withGameSessionPeer( @@ -3090,64 +3544,137 @@ public void markFullVersionFailed(String workflowId, String code, String message }; } - /** Test-only Account projection responder that replays a fixed original tuple and fence. */ - private static BindableService accountProjectionDouble( - Map projections) { - return new StartSessionOperatorAuthorizationServiceGrpc - .StartSessionOperatorAuthorizationServiceImplBase() { - @Override - public void readRedeemedOperationProjection( - ReadRedeemedOperationProjectionRequest request, - StreamObserver responseObserver) { - try { - var requestedPreTuple = - StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( - request - .getCanonicalPreAuthorizationTupleBytes() - .toString(StandardCharsets.UTF_8)); - var original = - Objects.requireNonNull( - projections.get(requestedPreTuple.controlPlaneRequestId()), - "No stipulated Account projection was registered for this logical operation"); - var tuple = original.tuple(); - var preTuple = tuple.preAuthorizationTuple(); - var bundle = - StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); - var reference = tuple.bundleReference(); - Instant redeemedAt = Instant.now().truncatedTo(ChronoUnit.MILLIS); - var response = - ReadRedeemedOperationProjectionResponse.newBuilder() - .setControlPlaneRequestId(preTuple.controlPlaneRequestId()) - .setCanonicalPreAuthorizationTupleBytes( - ByteString.copyFrom(preTuple.canonicalJson(), StandardCharsets.UTF_8)) - .setMutationDigest(preTuple.mutationDigest()) - .setAuthorizationReferenceFingerprint(tuple.authorizationReferenceFingerprint()) - .setReservationOwnerId(tuple.reservationOwnerId().toString()) - .setReservationClaimFence(tuple.reservationClaimFence()) - .setAuthenticatedRedeemerWorkloadIdentity( - "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service") - .setOwnerAttemptId(original.ownerAttemptId().toString()) - .setOwnerFence(original.ownerFence()) - .setReferenceExpiresAt(timestamp(Instant.parse(bundle.authorizationExpiresAt()))) - .setRedeemedAt(timestamp(redeemedAt)) - .setIssuanceOperationId(bundle.issuanceOperationId().toString()) - .setIssuanceFence(Long.parseLong(bundle.issuanceFence())) - .setBundleReference( - AuthorityEvidenceBundleReference.newBuilder() - .setBundleVersion(reference.bundleVersion()) - .setSourceVersion(reference.sourceVersion()) - .setSourceFence(reference.sourceFence()) - .setLinearization(reference.linearization())) - .setAuthorityEvidenceBundle( - ByteString.copyFrom(tuple.authorityEvidenceBundleBytes())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (RuntimeException invalid) { - responseObserver.onError(invalid); - } - } - }; + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector, + CompleteLaunchBindingEvidence completeBinding, + UUID playableStateNamespaceId) { + var descriptor = completeBinding.descriptor(); + var release = completeBinding.releaseAttestation(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + selector.readRequestId(), + selector.targetNamespace(), + selector.canonicalTenantId(), + selector.worldSlug(), + selector.gameInstanceUuid(), + playableStateNamespaceId, + RealmEntryPolicy.StateScope.SHARED.name(), + true, + selector.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + } + + private static String canonicalPreparationInputJson(WorldCanonicalInstancePreparation.Input input) + throws ReflectiveOperationException { + Method serializer = + WorldCanonicalInstancePreparationRepository.class.getDeclaredMethod( + "inputJson", WorldCanonicalInstancePreparation.Input.class); + serializer.setAccessible(true); + return (String) serializer.invoke(null, input); + } + + private static Map canonicalPreparationRowCounts(DSLContext dsl) { + Map counts = new TreeMap<>(); + for (String table : + List.of( + "world_instance", + "region_instance", + "zone_instance", + "room_instance", + "room_instance_exit", + "world_canonical_instance_association", + "world_canonical_instance_preparation", + "world_canonical_instance_topology_identity", + "world_canonical_preparation_start_location", + "world_canonical_instance_execution")) { + var row = dsl.fetchOne("SELECT count(*) FROM " + table); + counts.put(table, Objects.requireNonNull(row).get(0, Long.class)); + } + return counts; + } + + private static Map retainedWorldPreparationEvidence( + Store world, + UUID intakeRequestId, + UUID versionIdentityOperationId, + UUID canonicalTenantId, + String controlPlaneRequestId, + UUID canonicalGameInstanceId, + UUID publicationFence) { + Map evidence = new TreeMap<>(); + evidence.put( + "worldSourceIntake", + nullableRetainedJson( + world.dsl(), + "SELECT to_jsonb(i)::text FROM world_authored_source_intake i WHERE intake_request_id=?", + intakeRequestId)); + evidence.put( + "worldVersionIdentity", + nullableRetainedJson( + world.dsl(), + "SELECT to_jsonb(v)::text FROM world_authored_version_identity v WHERE operation_id=?", + versionIdentityOperationId)); + evidence.put( + "worldFrozenCapture", + nullableRetainedJson( + world.dsl(), + "SELECT to_jsonb(c)::text FROM world_canonical_frozen_topology c WHERE publication_fence=?", + publicationFence)); + evidence.put( + "completeLaunchBinding", + nullableRetainedJson( + world.dsl(), + "SELECT to_jsonb(b)::text FROM world_complete_launch_binding b WHERE target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?", + NAMESPACE, + canonicalTenantId, + controlPlaneRequestId)); + evidence.put( + "canonicalInstanceAssociation", + nullableRetainedJson( + world.dsl(), + "SELECT to_jsonb(a)::text FROM world_canonical_instance_association a WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)); + evidence.put( + "canonicalInstancePreparation", + nullableRetainedJson( + world.dsl(), + "SELECT to_jsonb(p)::text FROM world_canonical_instance_preparation p WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)); + evidence.put( + "canonicalTopologyIdentities", + nullableRetainedJson( + world.dsl(), + "SELECT coalesce(jsonb_agg(to_jsonb(t) ORDER BY family, template_id), '[]'::jsonb)::text FROM world_canonical_instance_topology_identity t WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)); + evidence.put( + "canonicalStartLocation", + nullableRetainedJson( + world.dsl(), + "SELECT to_jsonb(s)::text FROM world_canonical_preparation_start_location s WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)); + evidence.put( + "worldInstance", + nullableRetainedJson( + world.dsl(), + "SELECT to_jsonb(w)::text FROM world_instance w WHERE canonical_game_instance_id=?", + canonicalGameInstanceId)); + evidence.put( + "canonicalExecution", + nullableRetainedJson( + world.dsl(), + "SELECT to_jsonb(e)::text FROM world_canonical_instance_execution e WHERE target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?", + NAMESPACE, + canonicalTenantId, + controlPlaneRequestId)); + return evidence; + } + + private static String nullableRetainedJson(DSLContext dsl, String sql, Object... bindings) { + var row = dsl.resultQuery(sql, bindings).fetchOne(); + return row == null ? null : row.get(0, String.class); } private static StartSessionPostAuthorizationExecutionTuple startSessionTuple( @@ -3274,13 +3801,6 @@ private static StartSessionTemplateAssociationReadEvidence.Request startSessionR selection); } - private static Timestamp timestamp(Instant value) { - return Timestamp.newBuilder() - .setSeconds(value.getEpochSecond()) - .setNanos(value.getNano()) - .build(); - } - private static T withGameSessionPeer(Supplier operation) { var peer = new GrpcPeerIdentity( @@ -3305,18 +3825,18 @@ private static void assertFailedPrecondition(Runnable operation) { .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); } - private static void assertProjectionUnavailable(String rejectedEvidence, Runnable operation) { + private static void assertProjectionRejected(String rejectedEvidence, Runnable operation) { assertThatThrownBy(operation::run) .as( - "Account projection rejects changed %s before the Game Design SQL snapshot", + "Account's durable projection rejects changed %s before the Game Design SQL snapshot", rejectedEvidence) .isInstanceOf(io.grpc.StatusRuntimeException.class) .satisfies( failure -> { var status = ((io.grpc.StatusRuntimeException) failure).getStatus(); - assertThat(status.getCode()).isEqualTo(io.grpc.Status.Code.UNAVAILABLE); + assertThat(status.getCode()).isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION); assertThat(status.getDescription()) - .isEqualTo("Exact redeemed StartSession projection unavailable"); + .isEqualTo("Current Account authorization evidence is unavailable"); }); } @@ -4162,9 +4682,6 @@ CommonGrpcClientProperties properties(Path ca) { } } - private record StartSessionProjectionBinding( - StartSessionPostAuthorizationExecutionTuple tuple, UUID ownerAttemptId, long ownerFence) {} - /** Ephemeral same-namespace mTLS identities for the native owner-service proof fixture. */ private static final class TestPki { private final Path ca; @@ -4204,6 +4721,7 @@ private static final class TestPki { for (String service : List.of( "account-service", + "game-session-service", "game-design-service", "world-management-service", "game-logic-service", diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/GenuineWorldSelectedPublicationProofFactory.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/GenuineWorldSelectedPublicationProofFactory.java index 9fd78a2de9..d8331385fa 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/GenuineWorldSelectedPublicationProofFactory.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/GenuineWorldSelectedPublicationProofFactory.java @@ -22,6 +22,7 @@ public final class GenuineWorldSelectedPublicationProofFactory { private final BindableService freezeAndInventoryService; private final BindableService publishedStartLocationReadService; + private final WorldCanonicalFrozenTopologyRepository frozenTopologies; public GenuineWorldSelectedPublicationProofFactory( String workloadNamespace, @@ -46,11 +47,11 @@ public GenuineWorldSelectedPublicationProofFactory( var topology = new WorldDraftTopologyCommitRepository(dsl, fence, objectMapper); var digestService = createDigestService(dsl, objectMapper); - var frozenTopologyRepository = + frozenTopologies = new WorldCanonicalFrozenTopologyRepository( dsl, new WorldAuthoredGraphSnapshotRepository(dsl), topology, digestService); var canonicalFrozenTopology = - new WorldCanonicalFrozenTopologyService(frozenTopologyRepository, transactionManager); + new WorldCanonicalFrozenTopologyService(frozenTopologies, transactionManager); var selectorCapture = new WorldSelectedPublicationSelectorCapture(workloadNamespace, canonicalFrozenTopology); var authorizationRepository = new WorldSelectedDraftPublicationAuthorizationRepository(dsl); @@ -77,7 +78,7 @@ public GenuineWorldSelectedPublicationProofFactory( new WorldSelectedDraftPublicationFreezeGrpcService( freezeService, inventoryReadService, workloadNamespace); var publishedSelectorRepository = - new WorldPublishedStartLocationRepository(dsl, frozenTopologyRepository, graphApplications); + new WorldPublishedStartLocationRepository(dsl, frozenTopologies, graphApplications); publishedStartLocationReadService = new WorldPublishedStartLocationReadGrpcService( publishedSelectorRepository, workloadNamespace); @@ -91,6 +92,10 @@ public BindableService publishedStartLocationReadService() { return publishedStartLocationReadService; } + public WorldCanonicalFrozenTopologyRepository frozenTopologies() { + return frozenTopologies; + } + private static WorldDraftDesignDigestService createDigestService( DSLContext dsl, ObjectMapper objectMapper) { return new WorldDraftDesignDigestServiceImpl( From 1ef13f1588162c206fb4443a1c36b447e2bdcd4d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 08:29:03 +1300 Subject: [PATCH 097/129] Add exact Account World participation transport and owner composition proof --- .../account-service/api-contracts.md | 2 + .../world-management-service/api-contracts.md | 2 +- ...ame-authoring-publishing-and-activation.md | 4 +- ...sion_world_participation_acquisition.proto | 40 + ...ldParticipationAcquisitionGrpcService.java | 334 ++++++++ ...rldAcquisitionPostgresIntegrationTest.java | 462 +++++++++++ ...rticipationAcquisitionGrpcServiceTest.java | 445 ++++++++++ ...StartSessionAuthorizationProofFixture.java | 35 +- ...onWorldParticipationAcquisitionClient.java | 349 ++++++++ ...articipationAcquisitionClientMtlsTest.java | 761 ++++++++++++++++++ ...licationExportPostgresIntegrationTest.java | 435 ++++++++++ 11 files changed, 2863 insertions(+), 6 deletions(-) create mode 100644 protos/account/v1/start_session_world_participation_acquisition.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcService.java create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcServiceTest.java create mode 100644 services/common-security/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClient.java create mode 100644 services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClientMtlsTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index db008832f9..43a116fbd3 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -209,6 +209,8 @@ The original source capture continues to bind the exact Logging issuer identity. Fresh World participation acquisition first obtains the [Game Session current-original-attempt observation](../../../../protos/game-session/v1/original_start_session_current_attempt_read.proto) outside Account SQL. Account compares its complete original tuple, actual owner mutation and attempt identities, fence, pending phase, unchanged finite lease expiry and exact Account-issued redemption projection; a projection hash alone is insufficient. Only then may its existing current-actor/source callback retain the participation, complete source vector and immutable original-attempt evidence in one Account transaction. Both new acquisition and exact acquisition retry recheck the original lease against the Account database clock after lock waits. A fresh read correlation is not a new durable operation, and independent lookup-only readback must preserve the first observation and exact participation. Historical expiry permits readback only, not new acquisition, renewal or restarted execution. This point-in-time observation is not continuous Game Session claim protection or World admission authority; the through-admission and owner execution proof required by ADR 0047 remains distinct. +The standalone, unregistered [World participation acquisition RPC](../../../../protos/account/v1/start_session_world_participation_acquisition.proto) carries schema version 1, an independent correlation UUID, the exact workload namespace, the complete canonical original post-authorization tuple, actual Game Session mutation/attempt/fence, canonical game-instance UUID, and exact bounded World preparation JSON and digest. The exact configured same-namespace World workload is authenticated before parsing; end-user context and ambient SQL are denied. World does not supply an Account participation ID/fence, redemption projection, lease, or substitute authority assertion. Account resolves and retains those values through its existing acquisition owner. The reply echoes the complete request and carries the Account-assigned participation ID/fence and complete first retained Game Session observation, using the existing observation codec rather than a projection hash. A new correlation on an exact operation retry does not replace that first observation or allocate another participation. The client authenticates Account and exact-compares the request, original tuple, Game Session owner binding and full redemption projection. Transport integrity and a retained observation do not establish a continuously held Game Session claim, World commit permission, or activation; producer and composed physical proof remain gated. + The credential-free `ReadRedeemedOperationProjection` receiver accepts the exact configured same-namespace Game Design peer and the exact original Game Session redeemer under [ADR 0047's restricted original-operation read](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). Before returning the retained projection, Account compares the original request/reservation and redeemed workload/attempt/fence, then revalidates the original actor/JTI, current source and reference expiry. The response contains no credential or renewed permission. Game Session must separately prove its original claim and immutable pin under the owner-local checks required by that contract; this Account read is not World participation or admission. The distinct original-admission producer and independent readback implement [ADR 0047's admission source protection](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection), not the World receiving lifecycle above. The standalone acquisition RPC carries only the complete canonical original post-authorization tuple, the Game Session mutation/attempt/fence, and the complete canonical World hold identity, in addition to its schema version and target namespace; it never accepts a projection, lease expiry, or Account participation coordinates from Game Session. Account resolves the real retained participation ID/fence from its existing historical row within the fresh currentness callback. The retained closed RFC 8785 `account-start-session-admission-protection-request/v1` object continues to have exactly `schema`, `originalPostAuthorizationTupleBytesBase64`, `accountRedemptionProjectionBytesBase64`, `gameSessionOwnerMutationId`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `originalLeaseExpiresAt`, `accountWorldParticipationId`, `accountWorldParticipationFence`, and `worldAdmissionHoldIdentityBytesBase64`. UUIDs are canonical non-nil strings; positive fences are canonical decimal strings bounded by the owner counter type; expiry is the unchanged UTC lease with exactly six fractional digits, retaining PostgreSQL microsecond precision. Base64 members carry exact canonical complete original values, not hashes or caller-selected projections. The complete World hold binds its separate admission request/digest, precondition and canonical target. Unknown, duplicate, trailing, noncanonical, substituted or oversized data is rejected. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index cd7289147e..3655be10a3 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -343,7 +343,7 @@ Termination owner-set and registry-revision snapshot semantics are defined by [I Current implementation notes: -- The first canonical activation seam is now live for the `StartSession` path. +- The live `StartSession` path still uses the legacy numeric `ActivatePreparedWorldInstance` lifecycle transition. The separate canonical UUID activation ledger, service and gRPC adapter are unregistered and default-denied without an explicit held-authority verifier; legacy activation is not proof of that canonical commit boundary. The [World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md) records the remaining genuine producer and activation proof. - World Management persists `world_instance`, `region_instance`, `zone_instance`, `room_instance`, and `room_instance_exit` rows keyed by `(tenantId, gameInstanceId)` and uses `lifecycle_epoch` as the current fence token for prepare/activate/fail/terminate transitions. - `world_event` is now runtime-owned and keyed by `(tenantId, gameInstanceId)` via `region_instance`, rather than hanging off template `region` rows. - `stopSession` now consumes `GetWorldInstanceLifecycle` + `TerminateWorldInstance` rather than the old ping-only shutdown path; Entity Management cleanup runs through `CleanupRuntimeInstance`, and World hard-deletes its own runtime rows (`world_event`, room exits, rooms, zones, regions) before reporting `TERMINATED`. 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 d2e99a6900..d483a1a8f8 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 @@ -14,13 +14,13 @@ The [fresh-empty Entity catalogue](../../architecture/microservices/entity-manag The unregistered Entity and Automation selected-empty publication readers now independently validate their retained owner association and complete receipt in one read-only repeatable-read snapshot. Their content-only digest preimages are independently versioned at Entity 3 and Automation 6; unchanged script patches retain Automation 5. Additive Game Design V72 supports only the new release/attestation v4 profile with ordered schemas World 4, Entity 3, Game Logic 1, Automation 6 and Game Design control plane 2. It does not rewrite retained release schemas 1–3, their participant meanings or canonical bytes. Focused definitions cover exact scope and content, request-independent digest values, snapshot consistency, mixed-profile denial, immutable retry, retained v3 upgrade/readback and downstream World graph-profile selection. The World unit fixture stipulates carrier schemas; it does not establish physical closure recomputation or lifecycle readiness. New readers and runtime ingress remain unregistered. -The genuine release-proof definition composes native Account/Game Design/World/Entity/Automation mTLS boundaries, isolated owner PostgreSQL stores, full provider/receipt readback and retry, Account terminal settlement, and actual selected-owner publication clients and Game Design publish gating rather than fixed participant hashes or a mocked gate. It uses a classes-only Entity proof artifact, not Entity application or migration resources on the Game Design classpath. Source `2b763b040c9b4f63baa88bff0c911d3be177abd9` executes this test against PostgreSQL 18.6 and the Compose-pinned real MinIO image, but fails before object PUT: the test interceptor incorrectly compares raw operation-digest hex with the canonical stored `sha256:` value. The fixture correction preserves conditional `If-None-Match: *`, every exact durable candidate/request/inventory/manifest check and exact object GET, adding bounded field-named diagnostics. Corrected physical export and the new native publication composition remain unproved until they execute successfully. StartSession's Account projection remains an explicit double; neither these definitions nor local container skips close full release, continuous protection, lifecycle readiness or activation. +The genuine release-proof definition composes native Account/Game Design/World/Entity/Automation mTLS boundaries, isolated owner PostgreSQL stores, full provider/receipt readback and retry, Account terminal settlement, and actual selected-owner publication clients and Game Design publish gating rather than fixed participant hashes or a mocked gate. It uses a classes-only Entity proof artifact, not Entity application or migration resources on the Game Design classpath. Source `2b763b040c9b4f63baa88bff0c911d3be177abd9` executes this test against PostgreSQL 18.6 and the Compose-pinned real MinIO image, but fails before object PUT: the test interceptor incorrectly compares raw operation-digest hex with the canonical stored `sha256:` value. The fixture correction preserves conditional `If-None-Match: *`, every exact durable candidate/request/inventory/manifest check and exact object GET, adding bounded field-named diagnostics. Corrected physical export and the new native publication composition remain unproved until they execute successfully. At that source, StartSession's Account projection is an explicit double; the subsequent original-issuer definition below replaces it but has not executed physically. Neither definitions nor local container skips close full release, continuous protection, lifecycle readiness or activation. The corrected seven-module local gate passes in 5 minutes 7 seconds: complete checks, Game Design V72 schema generation, affected integration compilation, Entity's classes-only proof artifact and affected boot JARs complete. Available results total 4,768 unit passes with zero failures, errors or skips: 641 Common Platform, 156 Common Security, 1,346 Account, 207 Entity, 1,206 Automation, 562 Game Design and 650 World; unchanged tasks reuse their results. Account executes 12 non-container integrations, Automation three and World one. Container-dependent definitions skip locally: Account 286, Entity 15, Automation 96, Game Design 151 and World 220, totaling 768 skips. These skips supply no physical V72 upgrade, V138 settlement, same-snapshot owner lookup, corrected seed census, genuine native publication or MinIO execution credit. Flyway sanity passes 12 sets and 297 versioned files. Documentation validation passes all 548 Markdown files and links. The earlier Entity suite's leaked thread-local account was repaired with symmetric test cleanup, without changing production denial guards or canonical-input assertions. Originating run `38072471688` is terminal failure; its Account integration task was cancelled before any integration XML was captured. Artifact `11677753612` proves only 1,346 Account unit passes; no Account database execution count or PostgreSQL version can be attributed to the cancelled cases. Game Design's owner artifact `11677876709` records 152 integrations, zero skips and one failure (the candidate-digest fixture defect above); Entity artifact `11677281831` records the 13 integrations and sole seed-expectation failure above. The actual tested merge is `3543c22c2b945d553f2f7f19defd5606f469650f`, tree `b046aaa9c0e346eb5faca0698cf968d95829faba`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact `2b763b040c9b4f63baa88bff0c911d3be177abd9` source; the first parent differs from the recorded run-title base. Duplicate dependency-deferred run `38072575546` skips all build/test jobs and supplies no substantive proof. Corrected PostgreSQL CI, production privileges, continuous protection and all four complete Gameplay handoffs remain open. -The corrected source `e0f048e4eb5810eb69581dcb2c74e612cb368a60` has partial originating [Validation run 38075220202](https://github.com/benhook1013/FireMUD/actions/runs/38075220202) evidence, not a completed release handoff. Automation executes 1,196 unit and 94 integration tests on PostgreSQL 18.6 with zero failures, errors or skips, including the four selected-empty repository cases and schema-six snapshot reader. Entity executes 207 units and 15 PostgreSQL 18.6 integrations without skips; all eight repository cases and two additional migration cases pass, while the seed-census test fails in its raw-SQL read helper because a `Class` argument is accidentally bound as a SQL parameter. The local test-only correction uses an explicit typed result read and preserves the production migration, exact typed key set and all assertions. Its integration compilation passes; corrected physical execution remains required. Game Design's cancelled job preserves 550 passing units but no integration XML, so it provides no corrected MinIO, V72 upgrade or genuine native publication proof. Account's originating job is still pending at this checkpoint; neither cancellation nor elapsed time supplies database proof. +The corrected source `e0f048e4eb5810eb69581dcb2c74e612cb368a60` has partial originating [Validation run 38075220202](https://github.com/benhook1013/FireMUD/actions/runs/38075220202) evidence, not a completed release handoff. Automation executes 1,196 unit and 94 integration tests on PostgreSQL 18.6 with zero failures, errors or skips, including the four selected-empty repository cases and schema-six snapshot reader. Entity executes 207 units and 15 PostgreSQL 18.6 integrations without skips; all eight repository cases and two additional migration cases pass, while the seed-census test fails in its raw-SQL read helper because a `Class` argument is accidentally bound as a SQL parameter. The local test-only correction uses an explicit typed result read and preserves the production migration, exact typed key set and all assertions. Its integration compilation passes; corrected physical execution remains required. Game Design's cancelled job preserves 550 passing units but no integration XML, so it provides no corrected MinIO, V72 upgrade or genuine native publication proof. Account's originating job is terminal cancelled with a failed Gradle step; its XML capture steps succeeded, but counts and failure attribution have not yet been extracted. Cancellation or elapsed time supplies no database proof. The next construction definition replaces the fixed StartSession Account projection with actual original issue/redemption, complete source-capture and immutable bundle readback, and repeated native mTLS projection reads. It extends the same release to actual World binding, preparation/materialization, PREPARING lifecycle readback and retry; Logging claim evidence, Game Session launch association and continuous Account/Game Session commit protection remain stipulated. Additive Entity V3–V5 preserves the existing catalogue V2 and consumes only the UUID/quarantine read foundation from published source `e3f89c3fd6e2d46a14338ac38fedcb0bd4ccb020`; it does not reinterpret its `PRESEEDED_ONLY` assignment as a player-created or placement producer. The corrected local gate completes in 1m20s: 2,118 unit tests pass (Account 1,346, Entity 210, Game Design 562), 12 non-container Account integrations execute, and 454 container-dependent cases skip (Account 286, Entity 17, Game Design 151). All three module checks, Entity schema generation, fixture/integration compilation, Entity classes-only proof artifact and boot JAR, formatting/static analysis, links and 548 Markdown files pass; unchanged tasks reuse their results. Flyway sanity passes 12 sets and 300 versioned files. These are preparation and local proof, not executed PostgreSQL migration, original projection, composed World materialization, ACTIVE readiness, placement or admission proof. diff --git a/protos/account/v1/start_session_world_participation_acquisition.proto b/protos/account/v1/start_session_world_participation_acquisition.proto new file mode 100644 index 0000000000..183e915188 --- /dev/null +++ b/protos/account/v1/start_session_world_participation_acquisition.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; + +package account.v1; + +import "game-session/v1/original_start_session_current_attempt_read.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone and unregistered. This acquires Account-owned World source protection for one +// original human StartSession and does not establish World execution admission. +service AccountStartSessionWorldParticipationAcquisitionService { + rpc AcquireStartSessionWorldParticipation( + AcquireStartSessionWorldParticipationRequest) + returns (AcquireStartSessionWorldParticipationResponse); +} + +message AcquireStartSessionWorldParticipationRequest { + int32 schema_version = 1; + // Fresh correlation UUID; independent of all retained mutation and authority identities. + string acquisition_request_id = 2; + string target_namespace = 3; + bytes original_post_authorization_tuple = 4; + string game_session_owner_mutation_id = 5; + string game_session_owner_attempt_id = 6; + int64 game_session_owner_fence = 7; + string canonical_game_instance_id = 8; + // Exact bounded World preparation JSON and its digest; these are not caller authority claims. + string preparation_input_json = 9; + string preparation_input_digest = 10; +} + +message AcquireStartSessionWorldParticipationResponse { + // The complete exact request is echoed, including the independent acquisition correlation. + AcquireStartSessionWorldParticipationRequest request = 1; + string account_world_participation_id = 2; + int64 account_world_participation_fence = 3; + // Complete retained first original-attempt response, using the existing Game Session codec. + game_session.v1.ReadOriginalStartSessionCurrentAttemptResponse original_attempt_evidence = 4; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcService.java new file mode 100644 index 0000000000..2d825bb876 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcService.java @@ -0,0 +1,334 @@ +package net.firedevops.firemud.accountservice.service.session; + +import com.google.protobuf.Message; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationAcquisitionServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationResponse; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquiredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquisitionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone unregistered receiver authenticating the exact World peer before request parsing. */ +public final class AccountStartSessionWorldParticipationAcquisitionGrpcService + extends AccountStartSessionWorldParticipationAcquisitionServiceGrpc + .AccountStartSessionWorldParticipationAcquisitionServiceImplBase { + private static final int MAX_REQUEST_BYTES = + WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + + 2 * 1024; + private static final int MAX_RESPONSE_BYTES = + MAX_REQUEST_BYTES + + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES + + 2 * 1024; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + private final AccountStartSessionWorldParticipationAcquisitionService owner; + private final String namespace; + + public AccountStartSessionWorldParticipationAcquisitionGrpcService( + AccountStartSessionWorldParticipationAcquisitionService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "World participation acquisition owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void acquireStartSessionWorldParticipation( + AcquireStartSessionWorldParticipationRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !expectedPeer.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + if (request == null || request.getSerializedSize() > MAX_REQUEST_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + final AcquisitionRequest acquisition; + try { + acquisition = decodeRequest(request, namespace); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + AcquiredParticipation acquired = owner.acquire(acquisition); + AcquireStartSessionWorldParticipationResponse response = + toResponse(request, namespace, acquired); + observer.onNext(response); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.INVALID_ARGUMENT + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + observer.onError(Status.fromCode(code).asRuntimeException()); + } catch (IllegalArgumentException invalidEvidence) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } + + private static AcquisitionRequest decodeRequest( + AcquireStartSessionWorldParticipationRequest request, String expectedNamespace) { + requireClosed(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || request.getSchemaVersion() != 1 + || !GrpcPeerIdentity.isValidNamespace(expectedNamespace) + || !expectedNamespace.equals(request.getTargetNamespace())) { + throw new IllegalArgumentException("Unsupported or oversized World-participation request"); + } + UUID acquisitionId = canonicalUuid(request.getAcquisitionRequestId(), "acquisitionRequestId"); + UUID mutationId = canonicalUuid(request.getGameSessionOwnerMutationId(), "ownerMutationId"); + UUID attemptId = canonicalUuid(request.getGameSessionOwnerAttemptId(), "ownerAttemptId"); + UUID instanceId = canonicalUuid(request.getCanonicalGameInstanceId(), "gameInstanceId"); + if (request.getGameSessionOwnerFence() <= 0L) { + throw new IllegalArgumentException("Game Session owner fence must be positive"); + } + byte[] tupleBytes = request.getOriginalPostAuthorizationTuple().toByteArray(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (tupleBytes.length == 0 + || tupleBytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || !MessageDigest.isEqual(tupleBytes, tuple.canonicalBytes()) + || !StartSessionOperatorAction.ACTION_FAMILY.equals( + tuple.preAuthorizationTuple().actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals( + tuple.preAuthorizationTuple().targetOwner()) + || !expectedNamespace.equals( + tuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw new IllegalArgumentException("Exact canonical original StartSession tuple required"); + } + Set occupied = new HashSet<>(); + occupied.add(mutationId); + occupied.add(attemptId); + occupied.add(instanceId); + occupied.add(tuple.reservationOwnerId()); + occupied.add(tuple.preAuthorizationTuple().actor().accountId()); + occupied.add(tuple.preAuthorizationTuple().action().scope().tenantId()); + occupied.add( + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .issuanceOperationId()); + if (tuple.controlPlaneRequestId().equals(acquisitionId.toString()) + || occupied.contains(acquisitionId)) { + throw new IllegalArgumentException( + "Acquisition correlation must be independent of retained operation identities"); + } + String preparation = request.getPreparationInputJson(); + if (preparation.isBlank() + || !StandardCharsets.UTF_8.newEncoder().canEncode(preparation) + || preparation.getBytes(StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + || !SHA256.matcher(request.getPreparationInputDigest()).matches() + || !request + .getPreparationInputDigest() + .equals(digestPrefixed(preparation.getBytes(StandardCharsets.UTF_8)))) { + throw new IllegalArgumentException( + "Exact bounded World preparation input and digest required"); + } + var canonical = + AcquireStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setAcquisitionRequestId(acquisitionId.toString()) + .setTargetNamespace(expectedNamespace) + .setOriginalPostAuthorizationTuple(request.getOriginalPostAuthorizationTuple()) + .setGameSessionOwnerMutationId(mutationId.toString()) + .setGameSessionOwnerAttemptId(attemptId.toString()) + .setGameSessionOwnerFence(request.getGameSessionOwnerFence()) + .setCanonicalGameInstanceId(instanceId.toString()) + .setPreparationInputJson(preparation) + .setPreparationInputDigest(request.getPreparationInputDigest()) + .build(); + if (!canonical.equals(request)) { + throw new IllegalArgumentException("World-participation request is not canonical"); + } + return new AcquisitionRequest( + tupleBytes, + mutationId, + attemptId, + request.getGameSessionOwnerFence(), + instanceId, + preparation, + request.getPreparationInputDigest()); + } + + private static AcquireStartSessionWorldParticipationResponse toResponse( + AcquireStartSessionWorldParticipationRequest request, + String namespace, + AcquiredParticipation acquired) { + Objects.requireNonNull(acquired, "Acquired Account participation is required"); + StoredParticipation participation = acquired.participation(); + StoredEvidence evidence = acquired.originalAttemptEvidence(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + request.getOriginalPostAuthorizationTuple().toByteArray()); + if (participation.participationFence() <= 0L + || !namespace.equals(participation.targetNamespace()) + || !participation.controlPlaneRequestId().equals(tuple.controlPlaneRequestId()) + || !Arrays.equals( + participation.originalPostAuthorizationTuple(), + request.getOriginalPostAuthorizationTuple().toByteArray()) + || !participation + .canonicalTenantId() + .equals(tuple.preAuthorizationTuple().action().scope().tenantId()) + || !participation + .canonicalGameInstanceId() + .toString() + .equals(request.getCanonicalGameInstanceId()) + || !participation + .gameSessionOwnerAttemptId() + .toString() + .equals(request.getGameSessionOwnerAttemptId()) + || participation.gameSessionOwnerFence() != request.getGameSessionOwnerFence() + || !participation.preparationInputJson().equals(request.getPreparationInputJson()) + || !participation.preparationInputDigest().equals(request.getPreparationInputDigest()) + || !participation.participationId().equals(evidence.participationId()) + || !evidence + .gameSessionOwnerMutationId() + .toString() + .equals(request.getGameSessionOwnerMutationId()) + || !SHA256.matcher(evidence.originalResponseDigest()).matches() + || !evidence + .originalResponseDigest() + .equals(digestPrefixed(evidence.originalResponseBytes()))) { + throw new IllegalArgumentException( + "Acquired Account participation changed its request binding"); + } + ReadOriginalStartSessionCurrentAttemptResponse observation; + try { + byte[] retained = evidence.originalResponseBytes(); + if (retained.length == 0 + || retained.length + > OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Retained original-attempt evidence is oversized"); + } + observation = ReadOriginalStartSessionCurrentAttemptResponse.parseFrom(retained); + } catch (com.google.protobuf.InvalidProtocolBufferException malformed) { + throw new IllegalArgumentException( + "Retained original-attempt evidence is malformed", malformed); + } + var observedRequest = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(observation.getRequest()); + var exactObservation = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + observedRequest, observation); + if (!OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( + exactObservation.phaseState()) + || !namespace.equals(observedRequest.targetNamespace()) + || !Arrays.equals( + request.getOriginalPostAuthorizationTuple().toByteArray(), + observedRequest.canonicalPostAuthorizationTuple()) + || !request + .getGameSessionOwnerMutationId() + .equals(observedRequest.expectedOwnerMutationId().toString()) + || !request + .getGameSessionOwnerAttemptId() + .equals(observedRequest.expectedOwnerAttemptId().toString()) + || request.getGameSessionOwnerFence() != observedRequest.expectedOwnerFence() + || !MessageDigest.isEqual( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + exactObservation.accountRedemptionProjection()) + || !evidence.result().request().equals(exactObservation.request()) + || !evidence + .result() + .originalLeaseExpiresAt() + .equals(exactObservation.originalLeaseExpiresAt()) + || !MessageDigest.isEqual( + evidence.result().accountRedemptionProjection(), + exactObservation.accountRedemptionProjection()) + || !evidence.originalLeaseExpiresAt().equals(exactObservation.originalLeaseExpiresAt()) + || !Arrays.equals( + evidence.originalResponseBytes(), + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(exactObservation) + .toByteArray())) { + throw new IllegalArgumentException("Retained original-attempt evidence changed its binding"); + } + var response = + AcquireStartSessionWorldParticipationResponse.newBuilder() + .setRequest(request) + .setAccountWorldParticipationId(participation.participationId().toString()) + .setAccountWorldParticipationFence(participation.participationFence()) + .setOriginalAttemptEvidence(observation) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("World-participation response exceeds its wire budget"); + } + return response; + } + + private static void requireClosed(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "World-participation " + label + " contains unknown fields"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static String digestPrefixed(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java new file mode 100644 index 0000000000..0078c0ebe7 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java @@ -0,0 +1,462 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquisitionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** Physical Account issuer-to-World-acquisition proof; Game Session evidence stays stipulated. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest { + private static final String NAMESPACE = "original-world-acquisition-proof"; + private static final String WORLD_PEER_URI = + "spiffe://firemud/ns/original-world-acquisition-proof/sa/world-management-service"; + private static final long GAME_TEMPLATE_ID = 42L; + private static final Network NETWORK = Network.newNetwork(); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("original-world-acquisition-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "original-world-acquisition-primary", + "6379"); + + @TempDir Path temporary; + + @Test + void realOriginalIssueRedemptionAndAcquisitionRetainImmutableObservationAndSources() + throws Exception { + try (var controlUi = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + prepareOriginalCreator(controlUi); + var proof = + new AccountOriginalStartSessionAuthorizationProofFixture(controlUi, temporary, NAMESPACE); + UUID accountId = proof.creatorAccountId(); + UUID tenantId = controlUi.tenantId(); + String controlPlaneRequestId = "original-world-acquisition-" + UUID.randomUUID(); + UUID reservationOwnerId = UUID.randomUUID(); + UUID gameSessionAttemptId = UUID.randomUUID(); + UUID gameSessionMutationId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + long reservationClaimFence = 31L; + long gameSessionOwnerFence = 47L; + + var original = + proof.issueAndRedeemOriginal( + controlPlaneRequestId, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, NAMESPACE), + new StartSessionOperatorAction.Target(GAME_TEMPLATE_ID, accountId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "real Account original World acquisition integration proof"), + reservationOwnerId, + reservationClaimFence, + gameSessionAttemptId, + gameSessionOwnerFence); + assertThat(original.originalTuple().preAuthorizationTuple().targetOwner()) + .isEqualTo("game-session-service"); + + Instant stipulatedGameSessionLeaseExpiry = + original.accountReferenceExpiresAt().minusSeconds(30); + assertThat(stipulatedGameSessionLeaseExpiry).isAfter(Instant.now()); + byte[] redemptionProjection = + StartSessionAccountRedemptionProjection.fromOriginalTuple(original.originalTuple()); + List currentAttemptReads = new ArrayList<>(); + OriginalStartSessionCurrentAttemptClient currentAttemptClient = + request -> { + currentAttemptReads.add(request); + return new Result(request, stipulatedGameSessionLeaseExpiry, redemptionProjection); + }; + var acquisitionService = proof.worldParticipationAcquisitionService(currentAttemptClient); + String preparationInput = + preparationInput( + NAMESPACE, tenantId, controlPlaneRequestId, gameInstanceId, GAME_TEMPLATE_ID); + var acquisitionRequest = + new AcquisitionRequest( + original.originalTuple().canonicalBytes(), + gameSessionMutationId, + gameSessionAttemptId, + gameSessionOwnerFence, + gameInstanceId, + preparationInput, + digest(preparationInput)); + + var first = withWorldPeer(() -> acquisitionService.acquire(acquisitionRequest)); + StoredParticipation firstParticipation = first.participation(); + StoredEvidence firstObservation = first.originalAttemptEvidence(); + assertThat(firstParticipation.participationId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(firstParticipation.participationFence()).isPositive(); + assertThat(firstParticipation.originalPostAuthorizationTuple()) + .containsExactly(original.originalTuple().canonicalBytes()); + assertThat(firstParticipation.gameSessionOwnerAttemptId()).isEqualTo(gameSessionAttemptId); + assertThat(firstParticipation.gameSessionOwnerFence()).isEqualTo(gameSessionOwnerFence); + assertThat(firstParticipation.sources()).isNotEmpty(); + assertThat(firstObservation.gameSessionOwnerMutationId()).isEqualTo(gameSessionMutationId); + assertThat(firstObservation.originalLeaseExpiresAt()) + .isEqualTo(stipulatedGameSessionLeaseExpiry); + assertThat(firstObservation.originalResponseBytes()) + .containsExactly( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result( + currentAttemptReads.getFirst(), + stipulatedGameSessionLeaseExpiry, + redemptionProjection)) + .toByteArray()); + + DSLContext dsl = proof.sourceDsl(); + assertPersistedAcquisition( + dsl, original.originalTuple(), firstParticipation, firstObservation); + + // The stipulated Game Session observation is repeated with a newly generated correlation. + // Account's exact-operation retry must preserve the first bytes and participation fence. + var exactRetry = withWorldPeer(() -> acquisitionService.acquire(acquisitionRequest)); + assertThat(currentAttemptReads).hasSize(2); + assertThat(currentAttemptReads.get(0).readRequestId()) + .isNotEqualTo(currentAttemptReads.get(1).readRequestId()); + assertThat(exactRetry.participation().participationId()) + .isEqualTo(firstParticipation.participationId()); + assertThat(exactRetry.participation().participationFence()) + .isEqualTo(firstParticipation.participationFence()); + assertThat(exactRetry.originalAttemptEvidence().originalResponseBytes()) + .containsExactly(firstObservation.originalResponseBytes()); + assertThat(exactRetry.originalAttemptEvidence().result().request().readRequestId()) + .isEqualTo(currentAttemptReads.get(0).readRequestId()); + assertPersistedAcquisition( + dsl, original.originalTuple(), firstParticipation, firstObservation); + + int retainedParticipationCount = + dsl.fetchCount(DSL.table("account_start_session_world_participations")); + int retainedSourceCount = + dsl.fetchCount(DSL.table("account_start_session_world_participation_sources")); + int retainedObservationCount = + dsl.fetchCount(DSL.table("account_start_session_world_original_attempt_evidence")); + + var changedTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + original.originalTuple().preAuthorizationTuple(), + original.originalTuple().authenticatedWorkloadIdentity(), + "arfp/v1/changed-proof/" + "c".repeat(64), + original.originalTuple().reservationOwnerId(), + original.originalTuple().reservationClaimFence(), + original.originalTuple().authorityEvidenceBundleBytes(), + original.originalTuple().bundleReference()); + var changedTupleRequest = + new AcquisitionRequest( + changedTuple.canonicalBytes(), + gameSessionMutationId, + gameSessionAttemptId, + gameSessionOwnerFence, + gameInstanceId, + preparationInput, + digest(preparationInput)); + assertFailedPrecondition( + () -> withWorldPeer(() -> acquisitionService.acquire(changedTupleRequest))); + + var changedOwnerFenceRequest = + new AcquisitionRequest( + original.originalTuple().canonicalBytes(), + gameSessionMutationId, + gameSessionAttemptId, + gameSessionOwnerFence + 1, + gameInstanceId, + preparationInput, + digest(preparationInput)); + assertFailedPrecondition( + () -> withWorldPeer(() -> acquisitionService.acquire(changedOwnerFenceRequest))); + assertThat(dsl.fetchCount(DSL.table("account_start_session_world_participations"))) + .isEqualTo(retainedParticipationCount); + assertThat(dsl.fetchCount(DSL.table("account_start_session_world_participation_sources"))) + .isEqualTo(retainedSourceCount); + assertThat(dsl.fetchCount(DSL.table("account_start_session_world_original_attempt_evidence"))) + .isEqualTo(retainedObservationCount); + + var sourceFixture = controlUi.preparedOriginalCreator().sources(); + String originalRole = + dsl.fetchSingle("SELECT role FROM accounts WHERE account_uuid = ?", accountId) + .get(0, String.class); + assertThatThrownBy(sourceFixture::changeRoleToAdmin) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining( + "StartSession World participation remains pending for a required source"); + assertThat( + dsl.fetchSingle("SELECT role FROM accounts WHERE account_uuid = ?", accountId) + .get(0, String.class)) + .isEqualTo(originalRole); + } + } + + private static void assertPersistedAcquisition( + DSLContext dsl, + StartSessionPostAuthorizationExecutionTuple originalTuple, + StoredParticipation participation, + StoredEvidence observation) { + assertThat(dsl.fetchCount(DSL.table("account_start_session_world_participations"))) + .isEqualTo(1); + assertThat(dsl.fetchCount(DSL.table("account_start_session_world_participation_sources"))) + .isEqualTo(participation.sources().size()); + assertThat(dsl.fetchCount(DSL.table("account_start_session_world_original_attempt_evidence"))) + .isEqualTo(1); + + Record participationRow = + dsl.fetchOne( + "SELECT * FROM account_start_session_world_participations WHERE participation_id = ?", + participation.participationId()); + assertThat(participationRow).isNotNull(); + assertThat(participationRow.get("participation_fence", Long.class)) + .isEqualTo(participation.participationFence()); + assertThat(participationRow.get("original_post_authorization_tuple", byte[].class)) + .containsExactly(originalTuple.canonicalBytes()); + assertThat(participationRow.get("game_session_owner_attempt_id", UUID.class)) + .isEqualTo(participation.gameSessionOwnerAttemptId()); + assertThat(participationRow.get("game_session_owner_fence", Long.class)) + .isEqualTo(participation.gameSessionOwnerFence()); + assertThat(participationRow.get("preparation_input_json", String.class)) + .isEqualTo(participation.preparationInputJson()); + assertThat(participationRow.get("preparation_input_digest", String.class)) + .isEqualTo(participation.preparationInputDigest()); + + var sourceRows = + dsl.fetch( + "SELECT source_key, source_evidence FROM account_start_session_world_participation_sources " + + "WHERE participation_id = ? ORDER BY source_key", + participation.participationId()); + var expectedSources = + participation.sources().stream() + .sorted(Comparator.comparing(source -> source.key())) + .toList(); + assertThat(sourceRows).hasSize(expectedSources.size()); + for (int index = 0; index < expectedSources.size(); index++) { + assertThat(sourceRows.get(index).get("source_key", String.class)) + .isEqualTo(expectedSources.get(index).key()); + assertThat(sourceRows.get(index).get("source_evidence", byte[].class)) + .containsExactly(expectedSources.get(index).canonicalBytes()); + } + + Record evidenceRow = + dsl.fetchOne( + "SELECT game_session_owner_mutation_id, game_session_owner_attempt_id, " + + "game_session_owner_fence, original_lease_expires_at, original_response_bytes, " + + "original_response_digest FROM account_start_session_world_original_attempt_evidence " + + "WHERE participation_id = ?", + participation.participationId()); + assertThat(evidenceRow).isNotNull(); + assertThat(evidenceRow.get("game_session_owner_mutation_id", UUID.class)) + .isEqualTo(observation.gameSessionOwnerMutationId()); + assertThat(evidenceRow.get("game_session_owner_attempt_id", UUID.class)) + .isEqualTo(participation.gameSessionOwnerAttemptId()); + assertThat(evidenceRow.get("game_session_owner_fence", Long.class)) + .isEqualTo(participation.gameSessionOwnerFence()); + assertThat(evidenceRow.get("original_lease_expires_at", OffsetDateTime.class)) + .isEqualTo(OffsetDateTime.ofInstant(observation.originalLeaseExpiresAt(), ZoneOffset.UTC)); + assertThat(evidenceRow.get("original_response_bytes", byte[].class)) + .containsExactly(observation.originalResponseBytes()); + assertThat(evidenceRow.get("original_response_digest", String.class)) + .isEqualTo(observation.originalResponseDigest()); + + try { + var decoded = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + observation.result().request(), + ReadOriginalStartSessionCurrentAttemptResponse.parseFrom( + evidenceRow.get("original_response_bytes", byte[].class))); + assertThat(decoded.request().readRequestId()) + .isEqualTo(observation.result().request().readRequestId()); + assertThat(decoded.accountRedemptionProjection()) + .containsExactly(observation.result().accountRedemptionProjection()); + assertThat(decoded.originalLeaseExpiresAt()).isEqualTo(observation.originalLeaseExpiresAt()); + } catch (com.google.protobuf.InvalidProtocolBufferException malformed) { + throw new AssertionError( + "Retained current-attempt response must be a complete wire value", malformed); + } + } + + private static void prepareOriginalCreator(AccountControlUiOriginalOrderFixture controlUi) { + UUID versionId = UUID.randomUUID(); + String tenantKey = "world-acquisition-proof-tenant"; + var binding = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + controlUi.tenantId(), versionId, 17L, tenantKey, 23L, tenantKey, "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + "GAMEPLAY_RULES", + versionId.toString(), + "GAMEPLAY_RULES", + "all", + "0"))); + controlUi.prepareOriginalDraftOrder(binding, NAMESPACE); + } + + private static String preparationInput( + String namespace, UUID tenantId, String requestId, UUID gameInstanceId, long templateId) + throws Exception { + String descriptorJson = JSON.writeValueAsString(Map.of("gameTemplateId", templateId)); + return JSON.writeValueAsString( + Map.of( + "schemaVersion", + 1, + "identity", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + "original-world-acquisition-proof"), + "gameSessionReadRequest", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + "original-world-acquisition-proof"), + "gameSessionReadEvidence", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "canonicalGameInstanceId", + gameInstanceId.toString(), + "worldSlug", + "original-world-acquisition-proof", + "descriptorJson", + descriptorJson), + "launchBinding", + Map.of( + "targetNamespace", + namespace, + "canonicalTenantId", + tenantId.toString(), + "controlPlaneRequestId", + requestId, + "worldSlug", + "original-world-acquisition-proof"))); + } + + private static String digest(String value) throws Exception { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } + + private static void assertFailedPrecondition(Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + + private static T withWorldPeer(java.util.function.Supplier action) { + try (var ignored = AccountControlUiOwnerSourcesFixture.withPeer(WORLD_PEER_URI)) { + return action.get(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcServiceTest.java new file mode 100644 index 0000000000..302dae7540 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionGrpcServiceTest.java @@ -0,0 +1,445 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.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.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationResponse; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquiredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquisitionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Synthetic receiver proof only; Account persistence and TLS workload identity are mocked. */ +class AccountStartSessionWorldParticipationAcquisitionGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final String WORLD_URI = + "spiffe://firemud/ns/world-runtime/sa/world-management-service"; + private static final UUID ACCOUNT_ID = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TENANT_ID = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID MUTATION_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID ATTEMPT_ID = uuid("4a3fc69f-a18a-4b94-b1d1-2e8b4c3f0e4b"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final long PARTICIPATION_FENCE = 31L; + private static final long GAME_SESSION_FENCE = 37L; + private static final String PREPARATION_JSON = + "{\"selected\":\"immutable source\",\"revision\":3}"; + private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-12T00:00:00Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsWrongPeerNamespaceAndEndUserBeforeInspectingMalformedRequest() { + var owner = mock(AccountStartSessionWorldParticipationAcquisitionService.class); + var service = new AccountStartSessionWorldParticipationAcquisitionGrpcService(owner, NAMESPACE); + var malformed = AcquireStartSessionWorldParticipationRequest.newBuilder().build(); + + assertCode(Status.Code.UNAUTHENTICATED, invoke(service, null, malformed).error); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + service, + identity("spiffe://firemud/ns/world-runtime/sa/game-session-service"), + malformed) + .error); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + service, + identity("spiffe://firemud/ns/default/sa/world-management-service"), + malformed) + .error); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + service, + identity("spiffe://firemud/ns/other-runtime/sa/world-management-service"), + malformed) + .error); + + SessionContext.setContext("123", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, invoke(service, identity(WORLD_URI), malformed).error); + verifyNoInteractions(owner); + } + + @Test + void rejectsAmbientSqlUnknownFieldsAndMalformedBindingsBeforeBackendCall() { + var owner = mock(AccountStartSessionWorldParticipationAcquisitionService.class); + var service = new AccountStartSessionWorldParticipationAcquisitionGrpcService(owner, NAMESPACE); + var valid = request(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(service, identity(WORLD_URI), null).error); + TransactionSynchronizationManager.clear(); + + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + var unsupportedSchema = valid.toBuilder().setSchemaVersion(2).build(); + var wrongNamespace = valid.toBuilder().setTargetNamespace("default").build(); + var malformedUuid = valid.toBuilder().setAcquisitionRequestId("not-a-uuid").build(); + var malformedFence = valid.toBuilder().setGameSessionOwnerFence(0).build(); + var malformedDigest = + valid.toBuilder().setPreparationInputDigest("sha256:" + "0".repeat(64)).build(); + for (var malformed : + List.of( + unknown, + unsupportedSchema, + wrongNamespace, + malformedUuid, + malformedFence, + malformedDigest)) { + assertCode( + Status.Code.INVALID_ARGUMENT, invoke(service, identity(WORLD_URI), malformed).error); + } + assertCode(Status.Code.INVALID_ARGUMENT, invoke(service, identity(WORLD_URI), null).error); + verifyNoInteractions(owner); + } + + @Test + void delegatesExactRequestAndReturnsBoundedFullRetainedObservation() { + var owner = mock(AccountStartSessionWorldParticipationAcquisitionService.class); + var service = new AccountStartSessionWorldParticipationAcquisitionGrpcService(owner, NAMESPACE); + var request = request(); + var expected = acquired(request); + when(owner.acquire(any())).thenReturn(expected); + + var result = invoke(service, identity(WORLD_URI), request); + + assertThat(result.error).isNull(); + assertThat(result.completed).isTrue(); + assertThat(result.response.getRequest()).isEqualTo(request); + assertThat(result.response.getAccountWorldParticipationId()) + .isEqualTo(PARTICIPATION_ID.toString()); + assertThat(result.response.getAccountWorldParticipationFence()).isEqualTo(PARTICIPATION_FENCE); + assertThat(result.response.hasOriginalAttemptEvidence()).isTrue(); + assertThat(result.response.getOriginalAttemptEvidence()) + .isEqualTo( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + expected.originalAttemptEvidence().result())); + assertThat(result.response.getSerializedSize()).isLessThan(1024 * 1024); + + ArgumentCaptor captured = ArgumentCaptor.forClass(AcquisitionRequest.class); + verify(owner).acquire(captured.capture()); + assertThat(captured.getValue().originalPostAuthorizationTuple()) + .containsExactly(request.getOriginalPostAuthorizationTuple().toByteArray()); + assertThat(captured.getValue().gameSessionOwnerMutationId()).isEqualTo(MUTATION_ID); + assertThat(captured.getValue().gameSessionOwnerAttemptId()).isEqualTo(ATTEMPT_ID); + assertThat(captured.getValue().gameSessionOwnerFence()).isEqualTo(GAME_SESSION_FENCE); + assertThat(captured.getValue().canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(captured.getValue().preparationInputJson()).isEqualTo(PREPARATION_JSON); + assertThat(captured.getValue().preparationInputDigest()).isEqualTo(digest(PREPARATION_JSON)); + + var freshCorrelationRequest = + request.toBuilder().setAcquisitionRequestId(UUID.randomUUID().toString()).build(); + var freshCorrelationReply = invoke(service, identity(WORLD_URI), freshCorrelationRequest); + assertThat(freshCorrelationReply.error).isNull(); + assertThat(freshCorrelationReply.completed).isTrue(); + assertThat(freshCorrelationReply.response.getRequest()).isEqualTo(freshCorrelationRequest); + assertThat(freshCorrelationReply.response.getAccountWorldParticipationId()) + .isEqualTo(result.response.getAccountWorldParticipationId()); + assertThat(freshCorrelationReply.response.getAccountWorldParticipationFence()) + .isEqualTo(result.response.getAccountWorldParticipationFence()); + assertThat(freshCorrelationReply.response.getOriginalAttemptEvidence()) + .isEqualTo(result.response.getOriginalAttemptEvidence()); + } + + @Test + void rejectsSubstitutedBackendEvidenceWithoutExposingOwnerDetails() { + var owner = mock(AccountStartSessionWorldParticipationAcquisitionService.class); + var service = new AccountStartSessionWorldParticipationAcquisitionGrpcService(owner, NAMESPACE); + var request = request(); + var correct = acquired(request); + var substituted = + new StoredEvidence( + uuid("11111111-1111-4111-8111-111111111111"), + MUTATION_ID, + correct.originalAttemptEvidence().originalLeaseExpiresAt(), + correct.originalAttemptEvidence().originalResponseBytes(), + correct.originalAttemptEvidence().originalResponseDigest(), + correct.originalAttemptEvidence().result()); + when(owner.acquire(any())) + .thenReturn(new AcquiredParticipation(correct.participation(), substituted)); + + var result = invoke(service, identity(WORLD_URI), request); + + assertCode(Status.Code.FAILED_PRECONDITION, result.error); + assertThat(Status.fromThrowable(result.error).getDescription()).isNull(); + } + + private static Invocation invoke( + AccountStartSessionWorldParticipationAcquisitionGrpcService service, + GrpcPeerIdentity peer, + AcquireStartSessionWorldParticipationRequest request) { + var result = new Invocation(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.acquireStartSessionWorldParticipation(request, result); + } finally { + context.detach(previous); + } + return result; + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, Throwable failure) { + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected); + } + + private static AcquireStartSessionWorldParticipationRequest request() { + var tuple = originalTuple(); + return AcquireStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setAcquisitionRequestId("263a218e-1752-47f2-97c3-6273b2ea9f15") + .setTargetNamespace(NAMESPACE) + .setOriginalPostAuthorizationTuple( + com.google.protobuf.ByteString.copyFrom(tuple.canonicalBytes())) + .setGameSessionOwnerMutationId(MUTATION_ID.toString()) + .setGameSessionOwnerAttemptId(ATTEMPT_ID.toString()) + .setGameSessionOwnerFence(GAME_SESSION_FENCE) + .setCanonicalGameInstanceId(GAME_INSTANCE_ID.toString()) + .setPreparationInputJson(PREPARATION_JSON) + .setPreparationInputDigest(digest(PREPARATION_JSON)) + .build(); + } + + private static AcquiredParticipation acquired(AcquireStartSessionWorldParticipationRequest wire) { + var tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + wire.getOriginalPostAuthorizationTuple().toByteArray()); + var observationRequest = + new Request( + uuid("4d66578e-a7cd-4a37-8cfb-30aa4c0c23b3"), + NAMESPACE, + tuple.canonicalBytes(), + ATTEMPT_ID, + MUTATION_ID, + GAME_SESSION_FENCE); + var observation = + new Result( + observationRequest, + ORIGINAL_LEASE_EXPIRY, + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); + byte[] originalResponse = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observation).toByteArray(); + var participation = + new StoredParticipation( + PARTICIPATION_ID, + PARTICIPATION_FENCE, + tuple.controlPlaneRequestId(), + tuple.canonicalBytes(), + NAMESPACE, + TENANT_ID, + GAME_INSTANCE_ID, + ATTEMPT_ID, + GAME_SESSION_FENCE, + PREPARATION_JSON, + digest(PREPARATION_JSON), + 17L, + OffsetDateTime.parse("2026-10-09T10:20:30.456Z"), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + TENANT_ID.toString(), + "2", + "17", + null, + null, + "synthetic current source".getBytes(StandardCharsets.UTF_8)))); + var evidence = + new StoredEvidence( + PARTICIPATION_ID, + MUTATION_ID, + ORIGINAL_LEASE_EXPIRY, + originalResponse, + digestBytes(originalResponse), + observation); + return new AcquiredParticipation(participation, evidence); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "world-participation-grpc-test", + ACCOUNT_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target( + 91L, uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic World participation transport proof")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String actorId = tuple.actor().accountId().toString(); + String tenantId = tuple.action().scope().tenantId().toString(); + Map value = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-10T00:00:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", "23", + "issuanceEvidence", + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", actorId, + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String digest(String value) { + return digestBytes(value.getBytes(StandardCharsets.UTF_8)); + } + + private static String digestBytes(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Invocation + implements StreamObserver { + private AcquireStartSessionWorldParticipationResponse response; + private Throwable error; + private boolean completed; + + @Override + public void onNext(AcquireStartSessionWorldParticipationResponse value) { + response = value; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The test observer retains the callback failure only for assertions") + public void onError(Throwable failure) { + error = failure; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java index b0e0c7bafa..1a1d504105 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -28,19 +28,24 @@ import javax.crypto.spec.SecretKeySpec; import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import org.jooq.DSLContext; import org.jooq.Record; import tools.jackson.core.type.TypeReference; import tools.jackson.databind.json.JsonMapper; /** - * Test-only proof fixture for Account's original human StartSession issuer and one-time redemption. + * Test-only proof fixture for Account's original human StartSession issuer, one-time redemption, + * and real World participation acquisition composition. * *

Logging's current-claim read response and the supplied Game Session attempt/fence remain * stipulated inputs. The Account actor, source capture, issuance, reference custody, redemption, @@ -215,7 +220,28 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( gameSessionOwnerAttemptId, gameSessionOwnerFence, retained.issuanceOperationId(), - retained.issuanceFence()); + retained.issuanceFence(), + retained.referenceExpiresAt()); + } + + /** Creates the actual Account acquisition owner over this fixture's existing issuer and SQL. */ + public AccountStartSessionWorldParticipationAcquisitionService + worldParticipationAcquisitionService( + OriginalStartSessionCurrentAttemptClient gameSessionClient) { + Objects.requireNonNull( + gameSessionClient, "stipulated Game Session observation client required"); + return new AccountStartSessionWorldParticipationAcquisitionService( + authorizationService, + new AccountStartSessionWorldParticipationRepository(accountSources.dsl), + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(accountSources.dsl), + gameSessionClient, + accountSources.manager, + namespace); + } + + /** Existing fixture SQL context for independent test-only retained-row inspection. */ + public DSLContext sourceDsl() { + return accountSources.dsl; } /** The real Account receiver for the retained redeemed-operation projection. */ @@ -477,7 +503,8 @@ public record OriginalStartSession( UUID gameSessionOwnerAttemptId, long gameSessionOwnerFence, UUID issuanceOperationId, - long issuanceFence) { + long issuanceFence, + Instant accountReferenceExpiresAt) { public OriginalStartSession { Objects.requireNonNull(preAuthorizationTuple, "original pre-authorization tuple required"); Objects.requireNonNull(originalTuple, "original post-authorization tuple required"); @@ -487,6 +514,8 @@ public record OriginalStartSession( requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); requireOwner(issuanceOperationId, "issuanceOperationId"); requirePositive(issuanceFence, "issuanceFence"); + Objects.requireNonNull( + accountReferenceExpiresAt, "original Account reference expiry required"); } @Override diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClient.java new file mode 100644 index 0000000000..6a1f01cf5b --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClient.java @@ -0,0 +1,349 @@ +package net.firedevops.firemud.common.account.startsession; + +import com.google.protobuf.Message; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationAcquisitionServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +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.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client for Account's unregistered World-participation acquisition. */ +public final class AccountStartSessionWorldParticipationAcquisitionClient + extends AbstractReloadingBlockingGrpcClient< + AccountStartSessionWorldParticipationAcquisitionServiceGrpc + .AccountStartSessionWorldParticipationAcquisitionServiceBlockingStub> { + private static final int MAX_REQUEST_BYTES = + WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + + 2 * 1024; + private static final int MAX_RESPONSE_BYTES = + MAX_REQUEST_BYTES + + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.MAX_RESPONSE_BYTES + + 2 * 1024; + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountStartSessionWorldParticipationAcquisitionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountStartSessionWorldParticipationAcquisitionClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning World component explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account World-participation client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account World-participation stub is unavailable"); + } + initialized = true; + } + + /** Acquires and validates the exact original participation response outside ambient SQL. */ + public AcquireStartSessionWorldParticipationResponse acquire( + AcquireStartSessionWorldParticipationRequest request) { + requireWorkloadOnlyContext(); + validateRequest(request, workloadNamespace); + try { + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .acquireStartSessionWorldParticipation(request); + validateResponse(request, workloadNamespace, response); + return response; + } catch (StatusRuntimeException failure) { + throw Status.fromCode(failure.getStatus().getCode()).asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Account returned invalid original StartSession World participation evidence", malformed); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountStartSessionWorldParticipationAcquisitionServiceGrpc + .AccountStartSessionWorldParticipationAcquisitionServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountStartSessionWorldParticipationAcquisitionServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(MAX_RESPONSE_BYTES) + .withMaxOutboundMessageSize(MAX_REQUEST_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountStartSessionWorldParticipationAcquisitionServiceGrpc + .AccountStartSessionWorldParticipationAcquisitionServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account World-participation client is not initialized and available"); + } + return currentStub; + } + + private static void requireWorkloadOnlyContext() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account World-participation acquisition requires no ambient SQL or synchronization"); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException( + "Account World-participation acquisition requires a workload-only caller context"); + } + } + + private static void validateRequest( + AcquireStartSessionWorldParticipationRequest request, String expectedNamespace) { + Objects.requireNonNull(request, "World-participation acquisition request is required"); + requireClosed(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || request.getSchemaVersion() != 1 + || !GrpcPeerIdentity.isValidNamespace(expectedNamespace) + || !expectedNamespace.equals(request.getTargetNamespace())) { + throw new IllegalArgumentException("Unsupported or oversized World-participation request"); + } + UUID acquisitionId = canonicalUuid(request.getAcquisitionRequestId(), "acquisitionRequestId"); + UUID mutationId = canonicalUuid(request.getGameSessionOwnerMutationId(), "ownerMutationId"); + UUID attemptId = canonicalUuid(request.getGameSessionOwnerAttemptId(), "ownerAttemptId"); + UUID instanceId = canonicalUuid(request.getCanonicalGameInstanceId(), "gameInstanceId"); + if (request.getGameSessionOwnerFence() <= 0L) { + throw new IllegalArgumentException("Game Session owner fence must be positive"); + } + byte[] tupleBytes = request.getOriginalPostAuthorizationTuple().toByteArray(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (tupleBytes.length == 0 + || tupleBytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || !MessageDigest.isEqual(tupleBytes, tuple.canonicalBytes()) + || !StartSessionOperatorAction.ACTION_FAMILY.equals( + tuple.preAuthorizationTuple().actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals( + tuple.preAuthorizationTuple().targetOwner()) + || !expectedNamespace.equals( + tuple.preAuthorizationTuple().action().scope().targetNamespace())) { + throw new IllegalArgumentException("Exact canonical original StartSession tuple required"); + } + Set occupied = new HashSet<>(); + occupied.add(mutationId); + occupied.add(attemptId); + occupied.add(instanceId); + occupied.add(tuple.reservationOwnerId()); + occupied.add(tuple.preAuthorizationTuple().actor().accountId()); + occupied.add(tuple.preAuthorizationTuple().action().scope().tenantId()); + occupied.add( + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .issuanceOperationId()); + if (tuple.controlPlaneRequestId().equals(acquisitionId.toString()) + || occupied.contains(acquisitionId)) { + throw new IllegalArgumentException( + "Acquisition correlation must be independent of retained operation identities"); + } + String preparation = request.getPreparationInputJson(); + if (preparation.isBlank() + || !StandardCharsets.UTF_8.newEncoder().canEncode(preparation) + || preparation.getBytes(StandardCharsets.UTF_8).length + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + || !SHA256.matcher(request.getPreparationInputDigest()).matches() + || !request + .getPreparationInputDigest() + .equals(digestPrefixed(preparation.getBytes(StandardCharsets.UTF_8)))) { + throw new IllegalArgumentException( + "Exact bounded World preparation input and digest required"); + } + var canonical = + AcquireStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setAcquisitionRequestId(acquisitionId.toString()) + .setTargetNamespace(expectedNamespace) + .setOriginalPostAuthorizationTuple(request.getOriginalPostAuthorizationTuple()) + .setGameSessionOwnerMutationId(mutationId.toString()) + .setGameSessionOwnerAttemptId(attemptId.toString()) + .setGameSessionOwnerFence(request.getGameSessionOwnerFence()) + .setCanonicalGameInstanceId(instanceId.toString()) + .setPreparationInputJson(preparation) + .setPreparationInputDigest(request.getPreparationInputDigest()) + .build(); + if (!canonical.equals(request)) { + throw new IllegalArgumentException("World-participation request is not canonical"); + } + } + + private static void validateResponse( + AcquireStartSessionWorldParticipationRequest expected, + String expectedNamespace, + AcquireStartSessionWorldParticipationResponse response) { + Objects.requireNonNull(response, "Account World-participation response is required"); + requireClosed(response, "response"); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES + || !response.hasRequest() + || !response.hasOriginalAttemptEvidence()) { + throw new IllegalArgumentException("Missing or oversized World-participation response"); + } + requireClosed(response.getRequest(), "request echo"); + if (!expected.equals(response.getRequest()) + || !expectedNamespace.equals(response.getRequest().getTargetNamespace())) { + throw new IllegalArgumentException("Account changed the exact acquisition request"); + } + canonicalUuid(response.getAccountWorldParticipationId(), "accountWorldParticipationId"); + if (response.getAccountWorldParticipationFence() <= 0L) { + throw new IllegalArgumentException("Account World participation fence must be positive"); + } + var original = + StartSessionPostAuthorizationExecutionTuple.decode( + expected.getOriginalPostAuthorizationTuple().toByteArray()); + var observation = response.getOriginalAttemptEvidence(); + requireClosed(observation, "original attempt evidence"); + var observedRequest = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(observation.getRequest()); + var exactObservation = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + observedRequest, observation); + if (!OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( + exactObservation.phaseState()) + || !expectedNamespace.equals(observedRequest.targetNamespace()) + || !MessageDigest.isEqual( + expected.getOriginalPostAuthorizationTuple().toByteArray(), + observedRequest.canonicalPostAuthorizationTuple()) + || !canonicalUuid(expected.getGameSessionOwnerMutationId(), "ownerMutationId") + .equals(observedRequest.expectedOwnerMutationId()) + || !canonicalUuid(expected.getGameSessionOwnerAttemptId(), "ownerAttemptId") + .equals(observedRequest.expectedOwnerAttemptId()) + || expected.getGameSessionOwnerFence() != observedRequest.expectedOwnerFence() + || !MessageDigest.isEqual( + StartSessionAccountRedemptionProjection.fromOriginalTuple(original), + exactObservation.accountRedemptionProjection()) + || !observation.equals( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(exactObservation))) { + throw new IllegalArgumentException( + "Account changed the original tuple, Game Session attempt, or full redemption projection"); + } + } + + private static void requireClosed(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "World-participation " + label + " contains unknown fields"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static String digestPrefixed(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account World-participation acquisition requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account World-participation acquisition requires file-backed mTLS material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account World-participation " + label + " must be file-backed", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account World-participation " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClientMtlsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClientMtlsTest.java new file mode 100644 index 0000000000..40f394c312 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClientMtlsTest.java @@ -0,0 +1,761 @@ +package net.firedevops.firemud.common.account.startsession; + +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +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 io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.UnaryOperator; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationAcquisitionServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +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.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Socket mTLS client proof with a synthetic mocked Account acquisition backend, not PostgreSQL. */ +class AccountStartSessionWorldParticipationAcquisitionClientMtlsTest { + private static final String NAMESPACE = "world-runtime"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/world-runtime/sa/account-service"; + private static final String WORLD_URI = + "spiffe://firemud/ns/world-runtime/sa/world-management-service"; + private static final String STORE_PASSWORD = "synthetic-world-participation-test-password"; + private static final UUID ACCOUNT_ID = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TENANT_ID = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID MUTATION_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID ATTEMPT_ID = uuid("4a3fc69f-a18a-4b94-b1d1-2e8b4c3f0e4b"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final String PREPARATION_JSON = + "{\"selected\":\"immutable source\",\"revision\":3}"; + private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-12T00:00:00Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir static Path temporaryDirectory; + private static TestPki pki; + private Server server; + private AccountStartSessionWorldParticipationAcquisitionClient client; + + @BeforeAll + static void createSyntheticWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @AfterEach + void stopTransportAndClearThreadState() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void loopbackMtlsReturnsExactBoundParticipationAndCompleteObservation() throws Exception { + var wireRequest = request(NAMESPACE); + var expected = response(wireRequest); + var backend = mock(WorldParticipationAcquisitionBackend.class); + when(backend.acquire(any())).thenReturn(expected); + AtomicInteger handlers = startServer(backend, UnaryOperator.identity()); + client = newClient(server.getPort(), pki.worldClient()); + client.init(); + + var actual = client.acquire(wireRequest); + + assertThat(actual.getRequest()).isEqualTo(wireRequest); + assertThat(actual.getAccountWorldParticipationId()).isEqualTo(PARTICIPATION_ID.toString()); + assertThat(actual.getAccountWorldParticipationFence()).isEqualTo(31L); + assertThat(actual.getOriginalAttemptEvidence()) + .isEqualTo(expected.getOriginalAttemptEvidence()); + assertThat(handlers).hasValue(1); + ArgumentCaptor captured = + ArgumentCaptor.forClass(AcquireStartSessionWorldParticipationRequest.class); + verify(backend).acquire(captured.capture()); + assertThat(captured.getValue()).isEqualTo(wireRequest); + } + + @Test + void rejectsEchoAndOriginalEvidenceSubstitutionFromTheRemotePeer() throws Exception { + var wireRequest = request(NAMESPACE); + var backend = mock(WorldParticipationAcquisitionBackend.class); + when(backend.acquire(any())).thenReturn(response(wireRequest)); + AtomicInteger handlers = + startServer( + backend, + response -> + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setAcquisitionRequestId("11111111-1111-4111-8111-111111111111")) + .build()); + client = newClient(server.getPort(), pki.worldClient()); + client.init(); + assertThatThrownBy(() -> client.acquire(wireRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid original StartSession World participation evidence"); + assertThat(handlers).hasValue(1); + + stopCurrentTransport(); + when(backend.acquire(any())).thenReturn(response(wireRequest)); + handlers = + startServer( + backend, + response -> { + var observation = response.getOriginalAttemptEvidence(); + var changed = + observation.toBuilder() + .setRequest( + observation.getRequest().toBuilder() + .setExpectedOwnerFence( + observation.getRequest().getExpectedOwnerFence() + 1)) + .build(); + return response.toBuilder().setOriginalAttemptEvidence(changed).build(); + }); + client = newClient(server.getPort(), pki.worldClient()); + client.init(); + assertThatThrownBy(() -> client.acquire(wireRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid original StartSession World participation evidence"); + assertThat(handlers).hasValue(1); + } + + @Test + void wrongAuthenticatedWorkloadsAndLocalNamespaceMismatchAreRejected() throws Exception { + var wireRequest = request(NAMESPACE); + var backend = mock(WorldParticipationAcquisitionBackend.class); + AtomicInteger handlers = startServer(backend, UnaryOperator.identity()); + for (TestIdentity identity : List.of(pki.wrongServiceClient(), pki.otherNamespaceClient())) { + client = newClient(server.getPort(), identity); + client.init(); + assertThatThrownBy(() -> client.acquire(wireRequest)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + client.close(); + client = null; + } + assertThat(handlers).hasValue(2); + verifyNoInteractions(backend); + + var validPeerClient = newClient(server.getPort(), pki.worldClient()); + client = validPeerClient; + client.init(); + assertThatThrownBy(() -> client.acquire(request("default"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported or oversized World-participation request"); + assertThat(handlers).hasValue(2); + verifyNoInteractions(backend); + } + + @Test + void wrongAccountServerWorkloadIsRejectedBeforeSendingTheRequest() throws Exception { + var backend = mock(WorldParticipationAcquisitionBackend.class); + AtomicInteger handlers = startServer(backend, UnaryOperator.identity(), pki.wrongServer()); + client = newClient(server.getPort(), pki.worldClient()); + client.init(); + + assertThatThrownBy(() -> client.acquire(request(NAMESPACE))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(handlers).hasValue(0); + verifyNoInteractions(backend); + } + + @Test + void rejectsAmbientSqlAndEndUserContextBeforeSending() throws Exception { + var backend = mock(WorldParticipationAcquisitionBackend.class); + AtomicInteger handlers = startServer(backend, UnaryOperator.identity()); + client = newClient(server.getPort(), pki.worldClient()); + client.init(); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.acquire(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.clear(); + SessionContext.setContext("123", List.of(), Map.of()); + assertThatThrownBy(() -> client.acquire(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only"); + assertThat(handlers).hasValue(0); + verifyNoInteractions(backend); + } + + private AtomicInteger startServer( + WorldParticipationAcquisitionBackend backend, + UnaryOperator responseMutation) + throws Exception { + return startServer(backend, responseMutation, pki.accountServer()); + } + + private AtomicInteger startServer( + WorldParticipationAcquisitionBackend backend, + UnaryOperator responseMutation, + TestIdentity serverIdentity) + throws Exception { + AtomicInteger handlers = new AtomicInteger(); + var service = + new AccountStartSessionWorldParticipationAcquisitionServiceGrpc + .AccountStartSessionWorldParticipationAcquisitionServiceImplBase() { + @Override + public void acquireStartSessionWorldParticipation( + AcquireStartSessionWorldParticipationRequest request, + StreamObserver observer) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (!WORLD_URI.equals(peer.uri()) + || !NAMESPACE.equals(peer.namespace()) + || SessionContext.hasAuthenticatedCallerContext()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + try { + observer.onNext(backend.acquire(request)); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } + }; + ServerInterceptor countHandlers = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + handlers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + ServerInterceptor mutateResponse = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + var transformedCall = + new ForwardingServerCall.SimpleForwardingServerCall(call) { + @Override + @SuppressWarnings("unchecked") + public void sendMessage(RespT message) { + if (message instanceof AcquireStartSessionWorldParticipationResponse response) { + super.sendMessage((RespT) responseMutation.apply(response)); + } else { + super.sendMessage(message); + } + } + }; + return next.startCall(transformedCall, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize(32 * 1024 * 1024) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHandlers, new GrpcPeerIdentityInterceptor(), mutateResponse)) + .build() + .start(); + return handlers; + } + + private AccountStartSessionWorldParticipationAcquisitionClient newClient( + int port, TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + port); + return new AccountStartSessionWorldParticipationAcquisitionClient( + endpoints, + pki.clientProperties(temporaryDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static AcquireStartSessionWorldParticipationRequest request(String namespace) { + return AcquireStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setAcquisitionRequestId("263a218e-1752-47f2-97c3-6273b2ea9f15") + .setTargetNamespace(namespace) + .setOriginalPostAuthorizationTuple(ByteString.copyFrom(originalTuple().canonicalBytes())) + .setGameSessionOwnerMutationId(MUTATION_ID.toString()) + .setGameSessionOwnerAttemptId(ATTEMPT_ID.toString()) + .setGameSessionOwnerFence(37L) + .setCanonicalGameInstanceId(GAME_INSTANCE_ID.toString()) + .setPreparationInputJson(PREPARATION_JSON) + .setPreparationInputDigest(digest(PREPARATION_JSON)) + .build(); + } + + private static AcquireStartSessionWorldParticipationResponse response( + AcquireStartSessionWorldParticipationRequest wire) { + var tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + wire.getOriginalPostAuthorizationTuple().toByteArray()); + var observationRequest = + new Request( + uuid("4d66578e-a7cd-4a37-8cfb-30aa4c0c23b3"), + NAMESPACE, + tuple.canonicalBytes(), + ATTEMPT_ID, + MUTATION_ID, + 37L); + var observation = + new Result( + observationRequest, + ORIGINAL_LEASE_EXPIRY, + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); + return AcquireStartSessionWorldParticipationResponse.newBuilder() + .setRequest(wire) + .setAccountWorldParticipationId(PARTICIPATION_ID.toString()) + .setAccountWorldParticipationFence(31L) + .setOriginalAttemptEvidence( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observation)) + .build(); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "world-participation-mtls-test", + ACCOUNT_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target( + 91L, uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic World participation mTLS proof")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String actorId = tuple.actor().accountId().toString(); + String tenantId = tuple.action().scope().tenantId().toString(); + Map value = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-10T00:00:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", "23", + "issuanceEvidence", + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", actorId, + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String digest(String value) { + return digest(value.getBytes(StandardCharsets.UTF_8)); + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private void stopCurrentTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private interface WorldParticipationAcquisitionBackend { + AcquireStartSessionWorldParticipationResponse acquire( + AcquireStartSessionWorldParticipationRequest request); + } + + private record TestPki( + X509Certificate caCertificate, + TestIdentity accountServer, + TestIdentity wrongServer, + TestIdentity worldClient, + TestIdentity wrongServiceClient, + TestIdentity otherNamespaceClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("world-participation-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD World participation test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("world-participation-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate ca = readCertificate(caFile); + return new TestPki( + ca, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-account-server", + "spiffe://firemud/ns/world-runtime/sa/account-other", + true), + issueIdentity(directory, caStore, caFile, "world-client", WORLD_URI, false), + issueIdentity( + directory, + caStore, + caFile, + "wrong-service-client", + "spiffe://firemud/ns/world-runtime/sa/game-session-service", + false), + issueIdentity( + directory, + caStore, + caFile, + "other-namespace-client", + "spiffe://firemud/ns/other-runtime/sa/world-management-service", + false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain( + writePem( + directory.resolve("client-" + identity.certificate().getSerialNumber() + ".crt"), + "CERTIFICATE", + identity.certificate().getEncoded()) + .toString()); + properties.setPrivateKey( + writePem( + directory.resolve("client-" + identity.certificate().getSerialNumber() + ".key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()) + .toString()); + properties.setCaCert( + writePem( + directory.resolve("trusted-test-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()) + .toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 2f8a8befa9..d6993c6fdc 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -4,9 +4,11 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import com.google.protobuf.ByteString; import com.google.protobuf.util.JsonFormat; import io.grpc.BindableService; import io.grpc.Context; +import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; @@ -112,6 +114,8 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; @@ -138,6 +142,7 @@ import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; @@ -250,6 +255,9 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceExecutionIdentity; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; @@ -269,8 +277,11 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplicationService; import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplyGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldSelectedOwnerInventoryReadProofFixture; +import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; import net.firedevops.firemud.worldmanagement.v1.RoomDesignMutation; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceActivationServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.WorldDesignAggregateType; import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; @@ -3376,6 +3387,365 @@ public void close() { } finally { stopAll(defaultDeniedServer); } + + // The actual PREPARING lifecycle read above passed World's v4 -> World/4 -> graph/3 + // profile checks against the same retained frozen topology and materialization. + var selectedRelease = preparedLifecycle.launchBinding().releaseAttestation(); + assertThat(selectedRelease.schemaVersion()).isEqualTo(4); + assertThat( + selectedRelease.participantDigests().stream() + .map(participant -> participant.digestSchemaVersion()) + .toList()) + .containsExactly(4, 3, 1, 6, 2); + assertThat(completeWorldSelector.request().digestSchemaVersion()).isEqualTo(4); + assertThat(preparedLifecycle.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(preparedLifecycle.startLocation()) + .isEqualTo(selectedReleasedStart.startLocation()); + + var activationRepository = + new WorldCanonicalInstanceActivationRepository( + world.dsl(), world.transactions(), lifecycleRepository); + UUID activationRequestId = UUID.randomUUID(); + var activationRequest = + new WorldCanonicalInstanceActivation.Request( + activationRequestId, preparedLifecycle); + var alternateCorrelationEvidence = + lifecycleRepository + .read(lifecycleRequestWithFreshReadId(expectedLifecycleRequest)) + .orElseThrow(); + assertThat(alternateCorrelationEvidence.lifecycleStatus()).isEqualTo("PREPARING"); + var alternateCorrelationRetry = + new WorldCanonicalInstanceActivation.Request( + activationRequestId, alternateCorrelationEvidence); + assertThat(alternateCorrelationRetry.canonicalRequestBytes()) + .containsExactly(activationRequest.canonicalRequestBytes()); + assertThat( + Arrays.equals( + alternateCorrelationRetry.preparingEvidenceBytes(), + activationRequest.preparingEvidenceBytes())) + .isFalse(); + + var stipulatedGameSessionStartEvidence = + assembledPreparationInput.gameSessionReadEvidence(); + AtomicInteger activationAuthorityChecks = new AtomicInteger(); + AtomicInteger heldActivationChecks = new AtomicInteger(); + AtomicInteger heldActivationCloses = new AtomicInteger(); + var stipulatedActivationVerifier = + (WorldCanonicalInstanceActivationService.ActivationAuthorityVerifier) + candidate -> { + activationAuthorityChecks.incrementAndGet(); + if (!Arrays.equals( + candidate.canonicalRequestBytes(), + activationRequest.canonicalRequestBytes()) + || !"STARTING" + .equals(stipulatedGameSessionStartEvidence.currentGameSessionStatus()) + || !candidate + .preparing() + .launchBinding() + .equals( + new CompleteLaunchBindingEvidence( + stipulatedGameSessionStartEvidence.descriptor(), + stipulatedGameSessionStartEvidence.releaseAttestation()))) { + throw new SecurityException( + "Stipulated activation fixture differs from the exact PREPARING " + + "binding"); + } + return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + private boolean held = true; + + @Override + public void requireHeld() { + if (!held + || !candidate.activationRequestId().equals(activationRequestId) + || !candidate + .requestDigest() + .equals(activationRequest.requestDigest())) { + throw new SecurityException( + "Stipulated activation authority no longer holds for this " + + "operation"); + } + heldActivationChecks.incrementAndGet(); + } + + @Override + public void close() { + held = false; + heldActivationCloses.incrementAndGet(); + } + }; + }; + var activationService = + new WorldCanonicalInstanceActivationService( + activationRepository, stipulatedActivationVerifier); + register( + worldHandlers, + new WorldCanonicalInstanceActivationGrpcService(activationService, NAMESPACE)); + + long activationOperationCountBefore = canonicalActivationOperationCount(world.dsl()); + var preparationRowsBeforeActivation = canonicalPreparationRowCounts(world.dsl()); + var retainedEvidenceBeforeActivation = + retainedWorldPreparationEvidence( + world, + worldIntakeReceipt.intakeRequestId(), + worldIdentityReceipt.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId, + canonicalGameInstanceId, + completeWorldSelector.request().publicationFence()); + assertThat(activationOperationCountBefore).isZero(); + assertThat(lifecycleRepository.read(expectedLifecycleRequest).orElseThrow()) + .isEqualTo(preparedLifecycle); + + try (var wrongWorkloadActivationClient = + canonicalActivationClient(worldServer, pki.client("account-service"), channels)) { + assertThatThrownBy( + () -> + wrongWorkloadActivationClient.activate( + canonicalActivationTransportRequest(activationRequest))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + } + assertThat(activationAuthorityChecks).hasValue(0); + assertThat(canonicalActivationOperationCount(world.dsl())) + .isEqualTo(activationOperationCountBefore); + assertThat(canonicalPreparationRowCounts(world.dsl())) + .isEqualTo(preparationRowsBeforeActivation); + assertThat(lifecycleRepository.read(expectedLifecycleRequest).orElseThrow()) + .isEqualTo(preparedLifecycle); + assertThat( + retainedWorldPreparationEvidence( + world, + worldIntakeReceipt.intakeRequestId(), + worldIdentityReceipt.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId, + canonicalGameInstanceId, + completeWorldSelector.request().publicationFence())) + .isEqualTo(retainedEvidenceBeforeActivation); + + MutableHandlerRegistry defaultDeniedActivationHandlers = new MutableHandlerRegistry(); + register( + defaultDeniedActivationHandlers, + new WorldCanonicalInstanceActivationGrpcService( + new WorldCanonicalInstanceActivationService(activationRepository), NAMESPACE)); + Server defaultDeniedActivationServer = + startServer(pki, "world-management-service", defaultDeniedActivationHandlers); + try { + try (var defaultDeniedActivationClient = + canonicalActivationClient( + defaultDeniedActivationServer, + pki.client("game-session-service"), + channels)) { + assertThatThrownBy( + () -> + defaultDeniedActivationClient.activate( + canonicalActivationTransportRequest(activationRequest))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + } + } finally { + stopAll(defaultDeniedActivationServer); + } + assertThat(activationAuthorityChecks).hasValue(0); + assertThat(canonicalActivationOperationCount(world.dsl())) + .isEqualTo(activationOperationCountBefore); + assertThat(canonicalPreparationRowCounts(world.dsl())) + .isEqualTo(preparationRowsBeforeActivation); + assertThat(lifecycleRepository.read(expectedLifecycleRequest).orElseThrow()) + .isEqualTo(preparedLifecycle); + assertThat( + retainedWorldPreparationEvidence( + world, + worldIntakeReceipt.intakeRequestId(), + worldIdentityReceipt.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId, + canonicalGameInstanceId, + completeWorldSelector.request().publicationFence())) + .isEqualTo(retainedEvidenceBeforeActivation); + + // This explicitly stipulates current producer authority and its operation-specific + // held handle. The fixture's STARTING evidence is the existing mocked Game Session + // association, not a current owner read or continuous Account/GS protection. + try (var gameSessionActivationClient = + canonicalActivationClient( + worldServer, pki.client("game-session-service"), channels)) { + var firstActivationResponse = + gameSessionActivationClient.activate( + canonicalActivationTransportRequest(activationRequest)); + assertThat(firstActivationResponse.getActivationRequestId()) + .isEqualTo(activationRequestId.toString()); + byte[] committedActivationBytes = + firstActivationResponse.getCanonicalResultBytes().toByteArray(); + var committedActivation = + WorldCanonicalInstanceActivation.Result.fromStored(committedActivationBytes); + assertThat(committedActivation.outcome()) + .isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + assertThat(committedActivation.request().canonicalRequestBytes()) + .containsExactly(activationRequest.canonicalRequestBytes()); + assertThat(committedActivation.request().preparingEvidenceBytes()) + .containsExactly(activationRequest.preparingEvidenceBytes()); + assertThat(committedActivation.lifecycleEvidence().lifecycleStatus()) + .isEqualTo("ACTIVE"); + assertThat(committedActivation.lifecycleEvidence().lifecycleEpoch()) + .isEqualTo(preparedLifecycle.lifecycleEpoch() + 1L); + assertThat(committedActivation.lifecycleEvidence().rowVersion()) + .isEqualTo(preparedLifecycle.rowVersion() + 1L); + assertThat(committedActivation.lifecycleEvidence().launchBinding()) + .isEqualTo(completeLaunchEvidence); + assertThat(committedActivation.lifecycleEvidence().startLocation()) + .isEqualTo(selectedReleasedStart.startLocation()); + assertThat(committedActivation.lifecycleEvidence().runtimeRoomInstanceId()) + .isEqualTo(preparedLifecycle.runtimeRoomInstanceId()); + assertThat(committedActivation.lifecycleEvidence().captureId()) + .isEqualTo(preparedLifecycle.captureId()); + assertThat(committedActivation.lifecycleEvidence().graphSha256()) + .isEqualTo(preparedLifecycle.graphSha256()); + assertThat(committedActivation.lifecycleEvidence().preparationInputDigest()) + .isEqualTo(preparedLifecycle.preparationInputDigest()); + assertThat(committedActivation.lifecycleEvidence().operationalRegionAssignments()) + .containsExactlyInAnyOrderEntriesOf( + preparedLifecycle.operationalRegionAssignments()); + assertThat(activationAuthorityChecks).hasValue(1); + assertThat(heldActivationChecks.get()).isGreaterThanOrEqualTo(2); + assertThat(heldActivationCloses).hasValue(1); + assertThat(canonicalActivationOperationCount(world.dsl())) + .isEqualTo(activationOperationCountBefore + 1L); + var preparationRowsAfterActivation = canonicalPreparationRowCounts(world.dsl()); + assertThat(preparationRowsAfterActivation).isEqualTo(preparationRowsBeforeActivation); + + var storedActivation = + activationRepository.readResult(activationRequest).orElseThrow(); + assertThat(storedActivation.canonicalBytes()) + .containsExactly(committedActivationBytes); + var independentActiveRead = + lifecycleRepository + .read(lifecycleRequestWithFreshReadId(expectedLifecycleRequest)) + .orElseThrow(); + assertThat(independentActiveRead.lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(independentActiveRead.lifecycleEpoch()) + .isEqualTo(committedActivation.lifecycleEvidence().lifecycleEpoch()); + assertThat(independentActiveRead.rowVersion()) + .isEqualTo(committedActivation.lifecycleEvidence().rowVersion()); + assertThat(independentActiveRead.launchBinding()).isEqualTo(completeLaunchEvidence); + assertThat(independentActiveRead.startLocation()) + .isEqualTo(selectedReleasedStart.startLocation()); + assertThat(independentActiveRead.captureId()) + .isEqualTo(preparedLifecycle.captureId()); + assertThat(independentActiveRead.graphSha256()) + .isEqualTo(preparedLifecycle.graphSha256()); + assertThat(independentActiveRead.preparationInputDigest()) + .isEqualTo(preparedLifecycle.preparationInputDigest()); + + assertThat( + gameSessionActivationClient + .activate(canonicalActivationTransportRequest(activationRequest)) + .getCanonicalResultBytes() + .toByteArray()) + .containsExactly(committedActivationBytes); + assertThat( + gameSessionActivationClient + .activate(canonicalActivationTransportRequest(alternateCorrelationRetry)) + .getCanonicalResultBytes() + .toByteArray()) + .containsExactly(committedActivationBytes); + assertThat(activationAuthorityChecks).hasValue(1); + assertThat(heldActivationCloses).hasValue(1); + assertThat(canonicalActivationOperationCount(world.dsl())) + .isEqualTo(activationOperationCountBefore + 1L); + assertThat(canonicalPreparationRowCounts(world.dsl())) + .isEqualTo(preparationRowsAfterActivation); + + var changedEvidence = + new WorldCanonicalInstanceLifecycleEvidence( + preparedLifecycle.request(), + preparedLifecycle.launchBinding(), + preparedLifecycle.startLocation(), + preparedLifecycle.runtimeRoomInstanceId(), + preparedLifecycle.lifecycleStatus(), + preparedLifecycle.lifecycleEpoch(), + preparedLifecycle.rowVersion() + 1L, + preparedLifecycle.captureId(), + preparedLifecycle.graphSha256(), + preparedLifecycle.preparationInputDigest(), + preparedLifecycle.operationalRegionAssignments()); + var changedEvidenceRetry = + new WorldCanonicalInstanceActivation.Request( + activationRequestId, changedEvidence); + assertThat(changedEvidenceRetry.activationRequestId()) + .isEqualTo(activationRequest.activationRequestId()); + assertThat( + Arrays.equals( + changedEvidenceRetry.canonicalRequestBytes(), + activationRequest.canonicalRequestBytes())) + .isFalse(); + assertThatThrownBy( + () -> + gameSessionActivationClient.activate( + canonicalActivationTransportRequest(changedEvidenceRetry))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.ALREADY_EXISTS)); + assertThat(activationAuthorityChecks).hasValue(1); + assertThat(canonicalActivationOperationCount(world.dsl())) + .isEqualTo(activationOperationCountBefore + 1L); + assertThat(canonicalPreparationRowCounts(world.dsl())) + .isEqualTo(preparationRowsAfterActivation); + var activeReadAfterConflict = + lifecycleRepository + .read(lifecycleRequestWithFreshReadId(expectedLifecycleRequest)) + .orElseThrow(); + assertThat(activeReadAfterConflict.lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(activeReadAfterConflict.lifecycleEpoch()) + .isEqualTo(independentActiveRead.lifecycleEpoch()); + assertThat(activeReadAfterConflict.rowVersion()) + .isEqualTo(independentActiveRead.rowVersion()); + assertThat(activeReadAfterConflict.launchBinding()) + .isEqualTo(independentActiveRead.launchBinding()); + assertThat(activeReadAfterConflict.startLocation()) + .isEqualTo(independentActiveRead.startLocation()); + } + + var retainedOwnerEvidenceAfterActivation = + retainedWorldPreparationEvidence( + world, + worldIntakeReceipt.intakeRequestId(), + worldIdentityReceipt.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId, + canonicalGameInstanceId, + completeWorldSelector.request().publicationFence()); + assertThat(retainedOwnerEvidenceAfterActivation) + .containsEntry( + "worldSourceIntake", + retainedOwnerEvidenceAfterPreparation.get("worldSourceIntake")) + .containsEntry( + "worldVersionIdentity", + retainedOwnerEvidenceAfterPreparation.get("worldVersionIdentity")) + .containsEntry( + "worldFrozenCapture", + retainedOwnerEvidenceAfterPreparation.get("worldFrozenCapture")) + .containsEntry( + "completeLaunchBinding", + retainedOwnerEvidenceAfterPreparation.get("completeLaunchBinding")); + assertThat( + completeBindingOwnerRowVersions( + gd.dsl(), + persistedLaunchDescriptor.getId(), + release.id(), + gd.target().gameDesignVersionRowId(), + worldSource.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId)) + .containsExactlyElementsOf(completeBindingOwnerRowsBefore); } var replay = @@ -3567,6 +3937,47 @@ private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( release.evidenceDigest()); } + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequestWithFreshReadId( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + return new WorldCanonicalInstanceLifecycleEvidence.Request( + request.schemaVersion(), + UUID.randomUUID(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.publicProduction(), + request.controlPlaneRequestId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest()); + } + + private static ActivateCanonicalWorldInstanceRequest canonicalActivationTransportRequest( + WorldCanonicalInstanceActivation.Request request) { + return ActivateCanonicalWorldInstanceRequest.newBuilder() + .setActivationRequestId(request.activationRequestId().toString()) + .setPreparingLifecycleEvidenceBytes(ByteString.copyFrom(request.preparingEvidenceBytes())) + .build(); + } + + private static CanonicalActivationTransportClient canonicalActivationClient( + Server server, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channels) + throws Exception { + ManagedChannel channel = + channels.buildChannel(loopback(server), server.getPort(), tlsProperties, false); + String expectedWorldPeerUri = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service"; + var stub = + WorldCanonicalInstanceActivationServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedWorldPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedWorldPeerUri)); + return new CanonicalActivationTransportClient(channel, stub); + } + private static String canonicalPreparationInputJson(WorldCanonicalInstancePreparation.Input input) throws ReflectiveOperationException { Method serializer = @@ -3596,6 +4007,11 @@ private static Map canonicalPreparationRowCounts(DSLContext dsl) { return counts; } + private static long canonicalActivationOperationCount(DSLContext dsl) { + var row = dsl.fetchOne("SELECT count(*) FROM world_canonical_instance_activation_operation"); + return Objects.requireNonNull(row).get(0, Long.class); + } + private static Map retainedWorldPreparationEvidence( Store world, UUID intakeRequestId, @@ -4467,6 +4883,25 @@ private static WorldDesignMutationRevision.Builder mutation( .setScopeId(region.toString()); } + private record CanonicalActivationTransportClient( + ManagedChannel channel, + WorldCanonicalInstanceActivationServiceGrpc + .WorldCanonicalInstanceActivationServiceBlockingStub + stub) + implements AutoCloseable { + ActivateCanonicalWorldInstanceResponse activate(ActivateCanonicalWorldInstanceRequest request) { + return stub.withDeadlineAfter(5L, TimeUnit.SECONDS).activateCanonicalWorldInstance(request); + } + + @Override + public void close() throws InterruptedException { + channel.shutdownNow(); + if (!channel.awaitTermination(5, TimeUnit.SECONDS)) { + throw new AssertionError("Canonical activation test client did not terminate"); + } + } + } + private static Server startServer(TestPki pki, String service, MutableHandlerRegistry handlers) throws Exception { var identity = pki.server(service); From 96a8ed2e38b6ae56620e9110ede2dfcfcac351c8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 10:34:22 +1300 Subject: [PATCH 098/129] Bind original owner attempts and authored actor source evidence --- .../runtime-and-data.md | 4 + .../game-design-service/game-templates.md | 8 + .../game-session-service/api-contracts.md | 2 + .../game-session-service/runtime-and-data.md | 2 + .../world-management-service/api-contracts.md | 2 +- .../runtime-and-data.md | 2 + design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 6 + ...e-session-runtime-and-tick-coordination.md | 2 + .../world-runtime-and-movement.md | 2 + .../v1/game_session_service.proto | 28 + .../v1/world_management_service.proto | 12 +- services/account-service/build.gradle.kts | 2 + ...StartSessionReservationEvidenceClient.java | 71 +- ...rldAcquisitionPostgresIntegrationTest.java | 1190 ++++++++++++++--- ...sionReservationEvidenceClientMtlsTest.java | 767 +++++++++++ ...tSessionReservationEvidenceClientTest.java | 442 +----- ...StartSessionAuthorizationProofFixture.java | 107 +- .../common/gamedesign/GameplayRuleSource.java | 5 +- .../publication/AuthoredInitialActorCore.java | 48 + .../common/publication/RealmEntryPolicy.java | 42 +- ...nonicalWorldInstancePreparationClient.java | 20 +- ...icalWorldInstancePreparationGrpcCodec.java | 123 ++ ...tartSessionCurrentAttemptEvidenceTest.java | 193 +++ .../AuthoredInitialActorCoreTest.java | 42 + .../publication/RealmEntryPolicyTest.java | 93 ++ ...orldInstancePreparationClientMtlsTest.java | 79 +- ...WorldInstancePreparationGrpcCodecTest.java | 60 +- ...AuthoredInitialActorCoreSourceBinding.java | 301 +++++ .../StartSessionLaunchDescriptorProducer.java | 107 +- ...licationExportPostgresIntegrationTest.java | 103 +- .../RealmPolicyApplicationTest.java | 50 + ...oredInitialActorCoreSourceBindingTest.java | 558 ++++++++ .../publication/GameplayRuleSourceTest.java | 35 + ...rtSessionLaunchDescriptorProducerTest.java | 173 +++ .../game-session-service/build.gradle.kts | 14 + ...StartSessionOperatorAttemptRepository.java | 934 +++++++++++++ ...tSessionCurrentAttemptReadGrpcService.java | 167 +++ ...essionCurrentAttemptReadWorkloadGuard.java | 46 + ...__start_session_operator_owner_attempt.sql | 100 ++ ...entAttemptReadPostgresIntegrationTest.java | 480 +++++++ ...tSessionOperatorAttemptRepositoryTest.java | 77 ++ ...sionCurrentAttemptReadGrpcServiceTest.java | 459 +++++++ ...onCurrentAttemptReadWorkloadGuardTest.java | 79 ++ .../logging-admin-service/build.gradle.kts | 15 + .../client/GameSessionClient.java | 230 ++++ ...artSessionOperatorAuthorizationClient.java | 460 +++++++ .../StartSessionAuthorizationCoordinator.java | 753 +++++++++++ .../client/GameSessionClientTest.java | 309 +++++ ...onOperatorAuthorizationClientMtlsTest.java | 963 +++++++++++++ ...essionOperatorAuthorizationClientTest.java | 652 +++++++++ ...rtSessionAuthorizationCoordinatorTest.java | 1109 +++++++++++++++ ...rldCanonicalInstanceExecutionIdentity.java | 177 ++- .../WorldCanonicalInstancePreparation.java | 95 ++ ...nonicalInstancePreparationGrpcService.java | 8 +- ...anonicalInstancePreparationRepository.java | 90 +- ...ldCanonicalInstancePreparationService.java | 147 +- ...rtSessionAccountParticipationVerifier.java | 187 +++ ...iginal_start_session_attempt_admission.sql | 583 ++++++++ ...nceAssociationPostgresIntegrationTest.java | 280 ++-- ...anonicalInstanceExecutionTestFixtures.java | 261 +++- ...ncePreparationPostgresIntegrationTest.java | 246 +++- ...aphApplicationPostgresIntegrationTest.java | 118 +- ...calInstancePreparationGrpcServiceTest.java | 188 ++- ...nonicalInstancePreparationServiceTest.java | 18 + ...WorldCanonicalInstancePreparationTest.java | 8 +- ...ssionAccountParticipationVerifierTest.java | 236 ++++ 67 files changed, 13324 insertions(+), 852 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientMtlsTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredInitialActorCore.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredInitialActorCoreTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBinding.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBindingTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuard.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuardTest.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java create mode 100644 services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionAccountParticipationVerifier.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V63__world_original_start_session_attempt_admission.sql create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionAccountParticipationVerifierTest.java diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 7f88410913..0e549c8ed2 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -347,6 +347,8 @@ Game Design carries the complete descriptor as `creationDescriptor` inside a dis The descriptor is not a pre-authored actor template or an `OTHER_ACTOR_TEMPLATE_ROOTS` inventory witness. An empty dependency array does not prove an empty Entity family: every one of the 23 Entity source-census obligations and the complete selected World/inbound closure remains required. Selected-source retention and its original owner receipt must bind the complete six-family Game Design content, including this exact policy and descriptor, to the unchanged finalized Account authorization and World evidence. Parsing or retaining the descriptor alone grants no creation, allocation, publication, placement, admission or activation authority; those producer/consumer and commit proofs remain separate obligations in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The creation input does not supply a display name, initial disposition or runtime presence. Game Design owns the separate [release-authored initial actor core](../game-design-service/game-templates.md#release-authored-initial-actor-core), including exact selected disposition/feedback provenance and retained-schema preservation. Entity must retain that authored binding with the allocated identity rather than substitute an Account name, neutral default or live profile. Generic actors do not require universal RPG statistics or resources, but each applicable Entity family still needs complete typed owner evidence; absent storage is not empty-state proof. + ### Runtime Actor Identity Entity Management owns one persisted runtime actor for every active gameplay being. `actorId` is an opaque canonical gameplay-facing identity; services must not substitute composite reference strings such as `PLAYER:` or re-derive different player/NPC identity forms at each boundary. @@ -364,6 +366,8 @@ The actor is the shared subject for gameplay targeting, effects, stats, conditio - Game Session owns only ephemeral session attachment, protocol state, and player-facing presence projection. - Account Service remains authoritative for account identity and authorization inputs. +Durable actor identity and allocation are separate from admitted Game Session attachment. Before attachment there is no live Game Session presence projection: immutable release data must not author `presenceState`, and Entity must not invent `OFFLINE` or `PRESENT`, or repurpose `ACTIVE`/`AFK`, to fill that gap. Game Session produces runtime presence only through its authenticated lifecycle. A complete runtime-core aggregate that requires presence remains unavailable until that real projection exists; a persisted identity read must not claim to be that aggregate. World-owned placement and occupancy require their own evidence and cannot be inferred from either the actor allocation or session presence. Allocation and runtime use remain denied until their complete initial-core, family, authorization and World-placement proofs are satisfied. + For published targeting predicates whose facts it owns, Entity Management exposes a bounded `TargetingFactSnapshot` for requested `{tenantId, playableStateNamespaceId, playableStateScope, characterId}` actor identities and the current runtime fence where required. The response includes only the requested actor-state facts and an actor-state revision token; it is not a general actor read. Before applying an approved effect plan, Entity Management validates the recorded token for every material Entity-owned fact. If any token is stale, it reports a pre-commit mismatch so Game Logic can discard and re-resolve the plan under the same effect id before any source cost or target mutation commits. Character and NPC records remain the durable domain records for their respective variants. The runtime actor links those records into one gameplay subject model; it does not replace character progression, authored NPC definitions, or World Management location state. diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 18af0c617a..08ddf7b36d 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -12,6 +12,14 @@ creators can quickly spin up new projects without starting from scratch. - **Owner bindings and launch inputs** – typed references to owner-managed content plus any explicitly supported settings. Runtime flags are launch-authoritative inputs, not non-authoritative presentation defaults. - **Administrator provisioning** – not stored in templates. Any future bootstrap flow must use Account-owned account, membership, and grant operations; Game Design does not create administrator authority. +### Release-Authored Initial Actor Core + +For bounded `PLAYER_CREATED` entry, Game Design owns the immutable authored initial-state binding; Entity owns [creation-input validation and durable actor allocation](../entity-management-service/runtime-and-data.md#bounded-player-created-input-descriptor). A closed realm-entry policy schema 3 preserves the existing schema-2 selector, visibility, scope and creation-descriptor fields and adds exactly `initialActorCore: {displayName, dispositionKey}`. Both values must be explicit game-authored source content. Retained policy schemas 1 and 2 and creation-descriptor schema 1 remain byte-exact; neither older policy nor an empty creation input supplies an initial-state default. The complete policy remains bounded to 4,096 canonical UTF-8 bytes. + +The selected source must resolve the exact `dispositionKey` in the release-admitted Game Logic rules and its mandatory authored `FEEDBACK` entry through `safeFeedbackKey`. The binding retains the complete selected tenant, version and source operation, original policy and rule commit/revision identities and canonical source content, policy selectors, descriptor identity/revision and exact disposition/feedback definitions. Independently advancing, mixed or substituted sources are rejected rather than resolved against a live or latest profile. Account names, neutral disposition defaults and runtime profile inheritance are not source evidence. Generic actors require no universal RPG statistics or resources; applicable owner families still need complete typed inventory proof, with empty or not-applicable families qualified explicitly rather than inferred from missing rows. + +`presenceState` is not authored initial state. Before authenticated Game Session attachment there is no live presence projection; this immutable binding must not carry guessed `OFFLINE`/`PRESENT` or repurposed `ACTIVE`/`AFK` values. [Game Session](../game-session-service/runtime-and-data.md#persisted-actor-admission-boundary) owns that runtime projection, while World independently owns placement and occupancy. Source parsing, retention or descriptor validation alone grants no actor allocation, placement, admission or activation; the complete producer, consumer and executed proof gates remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + ## Implementation Status - The launch plugin-selection presence modes remain target-only and unimplemented: a presence-capable selection wrapper/mode, fresh omission or explicit empty resolving to the same immutable empty selection, rollback omission reusing a named target, rollback explicit empty, and explicit non-empty selection are not yet represented in proto/generated clients, launch-descriptor persistence/response, the request digest, service logic, or focused proof. The registered legacy launch-resolution adapter denies requests without the complete canonical source binding; an owner-local source-bound descriptor implementation is not proof of authenticated positive launch ingress. The current implementation does not yet persist, expose, or prove the complete `enabledPluginVersions[]` set for deterministic retry and rollback. The detailed target contract remains below. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 44ed3630df..450409ebe0 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -135,6 +135,8 @@ Service definitions reside in [../../../../protos/game-session/v1](../../../../p ### External Operator Lifecycle Contract +The separate unregistered `ReadOriginalStartSessionCurrentAttempt` read accepts only the exact same-namespace Account workload without end-user context. It returns the complete original pending attempt and attached Account projection only while both the Game Session database-clock owner lease and original Account reference remain unexpired; the owner claim credential stays inside the repository. Account remains the authorization owner under its [operator-authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references). This locked observation performs no renewal, redemption, admission, or durable mutation and does not establish continuous protection through a later owner commit. Source and proof status belong to the [Game Session tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). + **Target state:** External operator mutations enter through the Logging & Admin Service via Gateway. Logging & Admin authenticates the `control-ui` session, records the durable intent and audit context, and calls Account's canonical [`IssueHumanOperatorAuthorizationReference`](../account-service/api-contracts.md#operator-authorization-references) RPC; unattended automation uses the separately typed `IssueAutomationOperatorAuthorizationReference` branch under the restrictions that Account contract defines. Logging & Admin then forwards the opaque bounded reference unchanged with the exact typed action-family request, `actionFamilySchemaId`, `actionFamilySchemaVersion`, same `controlPlaneRequestId`, canonical `mutationDigest/v1` digest, and every scope, target, expected-version, mutation, and audit-reason field declared by that schema to the Game Session owner RPC over its exact mTLS workload identity. Only transport credentials and the authorization reference are excluded from the digest. If generation or privileged-predicate fields are copied outside the Account reference, they are non-authoritative context: Game Session must exclude those forwarded copies from authorization decisions and the mutation digest, or omit them entirely. Logging & Admin may forward the end-user `control-ui` JWT to Account only for reference issuance; it must never forward an end-user JWT or caller-asserted actor identity to Game Session. Game Session recomputes the digest from the exact schema pair and every declared digest input, then calls Account's `RedeemOperatorAuthorization` contract with the exact owner, action family and schema pair, scope, request identity, and digest. Account's returned bounded actor or automation-policy authorization projection is the sole authorization source; Game Session uses that Account-derived projection for audit while independently validating target-domain ownership, runtime fences, and owner-side idempotency. This target path is not currently routable and has no fallback external mutation route. **Current implementation status:** The current OpenAPI surface exposes an owner-local `/sessions*` HTTP family. It uses the service-local control-plane auth boundary, direct edge exposure is denied, and no Logging & Admin external `/sessions*` family is currently available. These owner-local routes are not the canonical external operator ingress or player-admission contract. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index df28765195..3e752e9261 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -58,6 +58,8 @@ Game Session does not persist or allocate the primary actor. It resolves the rea The local runtime stores only active attachment, protocol state, presence, and controller-fence data. A playtest copy is selected by its new fork-local `characterId`; `sourceCharacterId` is not used as authority. Current per-instance lookup, unresolved-character fallback, and complete cross-service proof remain gaps. +An Entity-allocated durable actor does not establish a Game Session attachment or presence projection. Before authenticated attachment, no live projection exists; the immutable authored release must not carry a guessed presence value, and a consumer must not fabricate `OFFLINE`/`PRESENT` or reuse `ACTIVE`/`AFK` as a bootstrap substitute. A complete runtime-core aggregate requiring presence must fail closed until Game Session's authenticated lifecycle supplies that projection. Entity owns the separate authored display-name/disposition provenance and durable identity, while World independently owns placement and occupancy; see [Entity's runtime actor boundary](../entity-management-service/runtime-and-data.md#runtime-actor-identity). + ## Owner-Local Gameplay Restrictions Game Session is the sole runtime enforcement owner for `gameplay_ban`, while Logging & Admin owns fixed-category policy intent, cases, appeals, and audit. The complete category and command contract is [Moderation Policies](../logging-admin-service/moderation-policies.md); this section records Game Session's local state and decision consequences. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 3655be10a3..8449802e8f 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -12,7 +12,7 @@ This API contract is target-state canonical; implementation coverage is partial - The registered `PrepareWorldInstance`, `ActivatePreparedWorldInstance`, `FailPreparedWorldInstance` and `TerminateWorldInstance` handlers allow only verified same-namespace Game Session workload identity before request parsing or owner calls. Missing configuration, missing peer identity and other workloads are denied; shared bearer claims do not substitute. Other pre-admission consumers are not currently allowlisted. This caller guard does not supply the remaining canonical preparation, activation, cleanup or admission proofs. - The standalone canonical initial-placement adapter now defines an Entity Management-only historical terminal-result read. Its proto and handler remain unregistered; the read supplies settlement evidence for the exact immutable placement operation, without admitting gameplay or directly mutating any hold. - The authored-world intake construction reads its complete immutable Game Design source through the exact authenticated owner-read contract in [Game Design API Contracts](../game-design-service/api-contracts.md#authored-world-source-readback). The intake transport remains unregistered and does not authorize source mutation, instance preparation, publication, or runtime admission. -- The separate canonical StartSession preparation construction must use the distinct Account World receiving participation and World-local terminal serialization described in [World runtime/data](runtime-and-data.md#original-startsession-execution-storage). Its typed execution identity is binding data, not authenticated authorization. No runtime RPC or positive producer is registered by these storage seams; the ordinary lifecycle handler's Game Session peer guard does not complete this canonical path. +- The separate canonical StartSession preparation construction must use the distinct Account World receiving participation and World-local terminal serialization described in [World runtime/data](runtime-and-data.md#original-startsession-execution-storage). `PrepareCanonicalWorldInstance` carries the committed launch-association selector and a separate exact original post-authorization tuple with the actual Game Session mutation ID, attempt ID and fence; fresh preparation rejects a selector-only request. Account participation coordinates and its retained first owner-attempt observation come from authenticated Account acquisition, never caller assertions. Its typed execution identity is binding data, not authenticated authorization. No runtime RPC or positive producer is registered by these storage seams; the ordinary lifecycle handler's Game Session peer guard does not complete this canonical path. - A standalone `ReadWorldStartSessionExecutionTerminal` adapter and file-backed mTLS client are constructed but unregistered. The adapter requires the exact same-namespace Account workload without end-user context before parsing, then delegates to the separately verified original-operation recovery read. Its focused unit definitions stipulate that verifier; they do not establish genuine authenticated recovery or settlement. - The unregistered canonical initial-admission hold adapter includes a separate exact hold-state/lifecycle read. The repository reads actual status and current lifecycle in one read-only snapshot; historical identity readback remains unchanged. Focused mock/unit definitions and a synthetic legacy-row PostgreSQL definition are not genuine database-to-RPC or continuous-protection proof. - An unregistered original-operation recovery verifier composes the distinct Account historical participation read with Game Session's historical original tuple, owner attempt, first-selection pin and immutable launch evidence. It compares the exact retained World preparation input without renewing execution authority; mocked composition tests do not prove genuine authenticated producer composition. The unregistered canonical hold reconciler similarly requires exact Game Session terminal evidence and never infers abort from expiry or absence. Detailed proof limits remain in the [World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md). diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index fc704d598d..30f2b57602 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -33,6 +33,8 @@ World Management instances are intended to be replaceable workers over authorita Execution admission, materialization, canonical association and `COMMITTED` publication share one uninterrupted local SQL transaction. The operation/request and canonical-target serialization precede the existing publication and topology locks; the database checks actual current time after lock waits before admitting execution. Network calls occur before SQL, never under these locks. Operational transaction timeouts and cancellation bound resource use, not the physical instant of commit. An execution admitted while the original authorization and owner claim are valid may finish after ingress expiry; expiry never permits another execution transaction, renewed participation or a replacement attempt. +World's fresh admission must bind Account's complete retained original Game Session observation, including the exact owner mutation, attempt, fence and unchanged lease expiry, to its own execution intent. Account assigns the participation identity and fence; the caller cannot supply them or substitute its own projection or expiry. A successful Account acquisition/readback is still point-in-time evidence: World independently checks the applicable original lease and authorization bounds at its actual locked admission point. Retaining the observation does not renew the claim or make a snapshot a continuously held cross-owner lock. The Account source freeze, immutable original owner binding and World-local execution fence retain their distinct responsibilities; the terminal carrier below remains unchanged. + Exact recovery compares the retained full identity and immutable terminal preparation result. Its service read path authenticates the original operation outside SQL, separately from fresh-admission verification, and reads only that stored operation; ingress expiry cannot turn it into renewed execution. Existing constructors deny recovery unless an explicit original-operation verifier is supplied. The unregistered terminal-read adapter accepts only exact same-namespace Account, denies ambient transactions or synchronization, and compares fresh read correlation and every immutable identity field through the closed Common codec. Its file-backed mTLS client checks the exact World peer and applies a bounded call deadline. A separate unregistered verifier composes Account's historical participation read and Game Session's historical original tuple, owner attempt, first-selection pin and immutable launch evidence against the exact retained preparation bytes. It grants no fresh execution authority; genuine producer composition remains unproved. A separate `ABORTED` transaction takes the same operation and target serialization, excludes a live execution and permanently fences later materialization and canonical association. Missing rows, timeouts and rolled-back intermediate states are not abort proof. An unknown outcome remains unresolved until exact `COMMITTED` readback or serialized `ABORTED` proof; Account retains its source protection until authenticated terminal settlement. These storage and transport components do not supply the missing genuine Account participation acquisition or complete authenticated terminal settlement. The canonical preparation service remains unavailable for runtime use until producer, consumer and physical concurrency/recovery proof are complete. The immutable integrity carrier is `world-start-session-execution-terminal/v1`. Its closed RFC 8785 UTF-8 object contains exactly `schema`, `originalPostAuthorizationTupleBase64`, `accountWorldParticipationId`, `accountWorldParticipationFence`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `targetNamespace`, `canonicalTenantId`, `controlPlaneRequestId`, `canonicalGameInstanceId`, `preparationInputDigest`, `preparationInputJson`, `worldExecutionFence`, and `outcome`. The original post-authorization tuple remains byte-exact with `targetOwner=game-session-service`; the duplicated namespace, tenant and request must match it. UUIDs are canonical and non-nil. Each fence is an independently owned positive BIGINT represented as a canonical decimal string; equal numeric values across owners are permitted, not evidence of an alias. Outcomes are only `COMMITTED` or `ABORTED`. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index babd9f60d8..f43937d2fa 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -222,3 +222,9 @@ Entry format: - Observation: A Java `Class` argument is not a typed-result parameter for this string-SQL overload. Compilation and skipped integration tests concealed the mistake; CI failed before the intended assertion rather than disproving the migration. - Expected pattern: For raw SQL, use an exact `fetchSingle(sql, bindings).get(0, ResultType.class)` read and preserve the complete value assertions. Confirm the case actually executed before granting database proof. - Current status: The scoped fixture reads are corrected without changing production SQL, the expected typed key set or writer guards. Corrected physical execution remains pending; the controller records the exact failed source and next proof gate. + +- `2026-10-11`: Guarded brief replacement still needs content readback + - Context: A revision-guarded controller brief update combined an indexed historical tail with a new checkpoint prefix; readback found the retained standing-decision heading missing its two leading heading characters. + - Observation: Revision protection prevented concurrent overwrite but did not prove preservation of the supplied text. A minimal `a—## h` example reproduces the local jq behavior: `index("##")` returns byte offset 4, while slicing from 4 uses character positions and drops both heading characters. The decision paragraph and historical tail remained present. + - Expected pattern: Prefer exact string replacement or splitting at a verified delimiter, then read back both the new checkpoint and retained standing instructions rather than relying on the revision guard alone. + - Current status: The heading was repaired through a second guarded revision and verified present. No standing decision or implementation authorization changed. 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 d483a1a8f8..c79cfd0294 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The current source-construction batch defines actual isolated Logging, Account and Game Session stores for original participation acquisition, a file-backed mTLS Logging claim reader, the Game Session V35 attempt reader, World typed original-operation acquisition with additive V63 admission evidence, and the source-only authored initial actor core described at the [Game Design owner](../../architecture/microservices/game-design-service/game-templates.md#release-authored-initial-actor-core). The producer validates selected schema-three source bindings but does not yet deliver or persist a new actor-allocation handoff. The existing genuine-release-to-World definition still stipulates its Game Session launch association and held acquisition witness; replacing that witness with actual acquisition is the next proof step, not completed proof. No production receiver, credential path, allocation, lifecycle or admission activation is enabled. + +The corrected composed seven-module local gate passes in 6 minutes 4 seconds, including complete checks, proof artifacts, formatting, Checkstyle, SpotBugs, JaCoCo, links, all 548 Markdown files and Flyway sanity for 12 sets/302 versioned files. Fresh XML records 5,603 executed unit cases and 41 executed integration/cross-service cases, with zero failures or errors. Container-dependent cases skip: 17 Game Session unit cases and 880 integration/cross-service cases across the owners. Those skips do not prove PostgreSQL migration/concurrency, actual native owner composition, MinIO export, source protection or activation. Architecture contracts separately pass 228 checks. The proof artifacts exclude borrowed application and migration resources; generated Spring configuration metadata is not application configuration. All four complete Gameplay handoffs remain open. + The accepted admission boundary is [genuine original-COMMIT acknowledgement with conditional independent recovery](../../architecture/microservices/account-service/runtime-and-data.md#original-gameplay-admission-commit-acknowledgement). Guaranteed quiet-primary recovery was an experimental feasibility objective, not an accepted requirement. Published correction `d4ba9edbd418d882a09417cf87bc62ea53e79b9d` removes only the unwired V120 fresh-confirmation JVM calls and prototype writer fixture; additive V136 closes its SQL function and every new receipt INSERT while preserving retained rows, immutable guards, historical readers, V120 finalization stamps and V121 pending fences. The transferred V122 definitions retain concurrency/exact-winner, rollback, binding/forgery/privilege, transaction-independence, unchanged expiry and lost-receipt-acknowledgement obligations. Synthetic pre-V136 rows prove migration preservation only, never historical durability. The exact correction received a commissioned independent zero-finding review and Overseer publication approval; this is not provider-review credit or merge readiness. The failures on older composed candidates are not cleared by wording or unexecuted replacement definitions; corrected PostgreSQL execution remains required. V122 storage/acknowledgement proof does not supply current platform restrictions, complete current Account authority or gameplay admission. The bounded Account correction passes `generateJooq`, the complete Account `check`, integration compilation, affected formatting/static analysis and `bootJar`. Its local gate executes 1,343 unit tests and 12 non-container integration tests; all 283 PostgreSQL-dependent cases skip locally. The substantive originating [Validation run 38067710993](https://github.com/benhook1013/FireMUD/actions/runs/38067710993) now completes successfully, with all 40 jobs passing. Its Account owner artifacts prove 1,343 units and 303 integrations executed with zero skips, failures or errors, including all 13 protected-entry cases and the V136 retained-history/new-write-denial and original-acknowledgement recovery cases. The actual tested merge is `b9d91aa36b2ea9fe85acd98935330c8e8d0f18b8`, tree `498745b64e4cb27c65c68cd7bfe7891e7d0cd023`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact `d4ba9ed` source; the first parent differs from the run title's recorded base. Owner XML artifact `11676209923` reports actual PostgreSQL **16.15** for the 30 lease-persistence and 13 protected-entry cases, not PostgreSQL 18. This is accepted scoped retirement/storage proof, not canonical PG18 fresh-executor proof, production privilege adoption, guaranteed historical recovery or activation. Gameplay owns the separate approved PG18 fresh-original-acknowledgement and insertion-gate convergence, reserved at V139; historical `readDurably` on PG18 remains denied. The duplicate dependency-deferred run supplies no additional proof. @@ -24,6 +28,8 @@ The corrected source `e0f048e4eb5810eb69581dcb2c74e612cb368a60` has partial orig The next construction definition replaces the fixed StartSession Account projection with actual original issue/redemption, complete source-capture and immutable bundle readback, and repeated native mTLS projection reads. It extends the same release to actual World binding, preparation/materialization, PREPARING lifecycle readback and retry; Logging claim evidence, Game Session launch association and continuous Account/Game Session commit protection remain stipulated. Additive Entity V3–V5 preserves the existing catalogue V2 and consumes only the UUID/quarantine read foundation from published source `e3f89c3fd6e2d46a14338ac38fedcb0bd4ccb020`; it does not reinterpret its `PRESEEDED_ONLY` assignment as a player-created or placement producer. The corrected local gate completes in 1m20s: 2,118 unit tests pass (Account 1,346, Entity 210, Game Design 562), 12 non-container Account integrations execute, and 454 container-dependent cases skip (Account 286, Entity 17, Game Design 151). All three module checks, Entity schema generation, fixture/integration compilation, Entity classes-only proof artifact and boot JAR, formatting/static analysis, links and 548 Markdown files pass; unchanged tasks reuse their results. Flyway sanity passes 12 sets and 300 versioned files. These are preparation and local proof, not executed PostgreSQL migration, original projection, composed World materialization, ACTIVE readiness, placement or admission proof. +Construction source `1ef13f1588162c206fb4443a1c36b447e2bdcd4d` adds an unregistered exact same-namespace World-to-Account participation-acquisition RPC/client that preserves the complete original tuple and actual Game Session mutation/attempt/fence; Account assigns the distinct participation and retains the first immutable observation. Four synthetic-receiver tests and five actual loopback socket-mTLS transport tests with a mocked backend pass. The actual Account issue/redemption/capture/acquisition/source-writer-exclusion PostgreSQL definition compiles and is discovered, but its single case is skipped locally. The same genuine Game Design v4 release-test definition composes real World materialization through `PREPARING` with the existing canonical activation ledger/CAS, complete region and binding, readback, and retry; it is also skipped locally and provides no executed proof of that composition, runtime wiring, or readiness. Logging claim, Game Session current-attempt and launch association, and operation-specific held activation authority remain stipulated. The final local gate passes in 3m19s across 167 tasks: 2,073 Account/Common Security/Game Design unit results with zero failures, errors, or skips (unchanged results reused), 12 executed non-container Account integrations, and 438 PostgreSQL-dependent skips (Account 287, Game Design 151); affected module checks, fixture/integration compilation, isolated Account proof JAR, formatting/static/coverage checks, links, and all 548 Markdown files pass. No physical new composition, migration, MinIO, `ACTIVE` readiness, placement/admission, or activation completion is claimed. All four complete Gameplay handoffs remain open; source is locally committed and published `e0` is unchanged. + ## Earlier Construction Checkpoints The current construction replaces the remaining in-process Automation-retention and Account-settlement commands with distinct, unregistered native mTLS transports. The owning [Automation command](../../architecture/microservices/automation-scripting-service/runtime-and-data.md#authored-template-source-inventory) and [Account settlement command](../../architecture/microservices/account-service/api-contracts.md#grpc-apis) retain full original evidence, independent transport correlations, exact request echoes and immutable receipt readback. Receiver authentication derives from each server's configured namespace, not a namespace supplied by the caller. The genuine PostgreSQL fixture defines a fresh native Account reserve → authenticated source read → finalize → Automation retain → Account settle flow, plus wrong-workload no-mutation, exact retry, unchanged rows and post-settlement HELD denial. Its earlier, manually reserved Entity/Automation disclosure fixtures are explicitly aborted before the fresh positive operation; those setup contexts do not establish the positive producer boundary. Entity retention and publication participation, S3 and StartSession projection remain incomplete. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 94bfeb2333..8145be9913 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for Game Session runtime and tick ## Current Status +The construction branch is consuming the Account-only original current-attempt reader from published source `e9a29f43ae47598fdc2cacd8f65cf784ed96e0ea` ([#3153](https://github.com/benhook1013/FireMUD/pull/3153)). Its prerequisite owner-attempt repository and additive V35 are separate from existing canonical runtime admission. Existing Common contracts and the additional admission-terminal proto definitions are preserved. The reader remains unregistered; its exact tuple/projection, database-clock expiry, no-mutation and peer-identity definitions do not prove original production attempt creation, continuous Account protection, admission or activation. Source-local Common/Game Session checks passed, while PostgreSQL cases skipped; receiving-tree validation and physical composed acquisition remain pending. The broader donor template/launch-association integration suite is not part of this bounded reader intake or its proof claim. + This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. Gameplay-session context remains on the implementation-local `sessionctx:*` keys and per-instance binding identity. The target authenticated `session:game:{tenantGameplayTag}:...` family, persisted tenant-tag allocation, and namespace-qualified controller uniqueness are not implemented or end-to-end proved; the canonical tenancy and focused-isolation requirements remain in [Multi-Tenancy](../../architecture/system-architecture-multi-tenancy.md#data-separation-per-service). 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 259dbac6e2..c977f1a4b3 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for world runtime and movement. C This tracker is the permanent reader-facing implementation record for world runtime, room reads, movement, lifecycle orchestration, and Draft topology mutation. Canonical target-state design remains under [design/architecture](../../architecture/README.md). +Canonical preparation now defines the typed original Game Session operation input and an explicit Account participation acquisition adapter before World SQL. Additive V63 retains the exact returned original-attempt observation and checks the unchanged original authorization and Game Session lease against the database clock after admission locks; the legacy untyped entry cannot authorize fresh materialization. This is unregistered source construction, not production wiring or continuous foreign-owner protection. Schema generation succeeds, but physical V63 migration, concurrency and genuine Account-acquisition-to-World execution remain unproved locally; existing positive storage definitions retain explicitly synthetic complete witnesses. The [World owner contract](../../architecture/microservices/world-management-service/runtime-and-data.md#original-startsession-execution-storage) owns the settlement and recovery limits; the [authoring tracker](./game-authoring-publishing-and-activation.md) records composed proof and remaining handoffs. + 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). The unregistered [canonical initial-placement terminal read](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-placement-terminal-readback) returns exact historical operation evidence without current placement authorization. Its [socket mTLS proof](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlacementOutcomeMtlsTest.java) executes against the real handler and a mock owner; it is not database-to-socket or live settlement proof. The [PostgreSQL definition](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java) checks retained `APPLIED`/`CONFLICT` bytes and no mutation when new placement authority is denied; corrected physical execution remains pending. Physical readback after canonical termination remains an explicit World lifecycle/cleanup obligation: the legacy numeric-key termination writer is correctly rejected by the canonical execution-manifest guard and cannot manufacture that test state. Revisit the post-termination proof when the canonical owner transition and required cleanup acknowledgements are implemented; do not bypass the guard or infer termination from missing state. diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index ce60023730..3edd89245a 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -13,6 +13,8 @@ option java_multiple_files = true; service GameSessionService { rpc Ping(PingRequest) returns (PingResponse); rpc StartSession(StartSessionRequest) returns (StartSessionResponse); + rpc AuthorizeStartSession(AuthorizeStartSessionRequest) + returns (AuthorizeStartSessionResponse); rpc StopSession(StopSessionRequest) returns (StopSessionResponse); rpc RestartSession(RestartSessionRequest) returns (RestartSessionResponse); rpc EnqueueCommand(EnqueueCommandRequest) returns (EnqueueCommandResponse); @@ -109,6 +111,32 @@ message StartSessionResponse { shared.v1.ErrorDetail error = 2; } +// Typed non-activating operator handoff. This transport only records Account redemption progress; +// it does not create or start a game instance and does not return a session identifier. +message AuthorizeStartSessionRequest { + bytes canonical_post_authorization_execution_tuple_bytes = 1; + string operator_authorization_reference = 2; +} + +enum StartSessionOwnerAuthorizationProgress { + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_UNSPECIFIED = 0; + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_EXACT_REPLAY = 1; + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS = 2; + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_PROJECTION_ATTACHED = 3; +} + +message AuthorizeStartSessionResponse { + string target_namespace = 1; + string control_plane_request_id = 2; + string mutation_digest = 3; + string owner_attempt_id = 4; + string owner_mutation_id = 5; + int64 owner_fence = 6; + string owner_phase_state = 7; + StartSessionOwnerAuthorizationProgress progress = 8; + shared.v1.ErrorDetail error = 9; +} + message StopSessionRequest { string session_id = 1; } diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index 7a36702ef9..32acb4d549 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -79,7 +79,16 @@ message ReadWorldStartSessionExecutionTerminalResponse { bytes canonical_terminal_bytes = 2; } -// The exact ten-field committed Game Session launch-association selector. +// Exact original Game Session StartSession owner operation. Account participation identity, +// currentness, lease observation and source projection are returned only by Account. +message OriginalStartSessionOperationInput { + bytes original_post_authorization_tuple = 1; + string game_session_owner_mutation_id = 2; + string game_session_owner_attempt_id = 3; + int64 game_session_owner_fence = 4; +} + +// The committed Game Session launch-association selector and separate original operation input. message PrepareCanonicalWorldInstanceRequest { string read_request_id = 1; string target_namespace = 2; @@ -91,6 +100,7 @@ message PrepareCanonicalWorldInstanceRequest { string expected_descriptor_request_digest = 8; string expected_descriptor_result_digest = 9; string expected_release_attestation_evidence_digest = 10; + OriginalStartSessionOperationInput original_start_session_operation = 11; } message PrepareCanonicalWorldInstanceResponse { diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index ef84a5547e..871e9347e8 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -46,6 +46,8 @@ dependencies { testImplementation(libs.grpc.inprocess) testImplementation(testFixtures(project(":account-service"))) integrationTestImplementation(testFixtures(project(":account-service"))) + integrationTestImplementation(project(mapOf("path" to ":game-session-service", "configuration" to "gameSessionClassesProof"))) + integrationTestImplementation(project(mapOf("path" to ":logging-admin-service", "configuration" to "loggingStartSessionClaimProof"))) } // Opt-in proof artifact: never expose Account migrations/application resources to World's tests. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java index 5f57a577e3..bfddea2232 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java @@ -4,6 +4,8 @@ import jakarta.annotation.PostConstruct; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.time.Clock; import java.util.Arrays; import java.util.Objects; @@ -15,6 +17,11 @@ import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; 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.common.grpc.GrpcTlsMaterialResolver; +import net.firedevops.firemud.common.grpc.ResolvedGrpcTlsMaterial; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; @@ -22,6 +29,7 @@ import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Reads and validates Logging/Admin's current StartSession reservation claim snapshot. @@ -38,6 +46,7 @@ public final class StartSessionReservationEvidenceClient private static final UUID NIL_UUID = new UUID(0L, 0L); private final Clock clock; + private final CommonGrpcClientProperties transportTlsProperties; @Autowired public StartSessionReservationEvidenceClient( @@ -61,6 +70,8 @@ public StartSessionReservationEvidenceClient( stubCustomizer, StartSessionReservationEvidenceClient.class); this.clock = Objects.requireNonNull(clock, "clock is required"); + this.transportTlsProperties = + Objects.requireNonNull(tlsProperties, "TLS properties are required").copy(); } @PostConstruct @@ -95,6 +106,7 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( UUID currentClaimOwnerId, long currentClaimFence, Purpose purpose) { + requireNoAmbientSqlOrSynchronization(); Objects.requireNonNull(tuple, "reservation tuple is required"); requireNonNilUuid(reservationOwnerId, "reservationOwnerId"); requireNonNilUuid(currentClaimOwnerId, "currentClaimOwnerId"); @@ -117,10 +129,7 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( .setPurpose(toWirePurpose(purpose)) .build(); - var currentStub = stub(); - if (currentStub == null) { - throw new IllegalStateException("Logging/Admin reservation evidence client is unavailable"); - } + var currentStub = requirePinnedLoggingAdminStub(tuple.action().scope().targetNamespace()); ReadCurrentClaimEvidenceResponse response = currentStub .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) @@ -137,6 +146,60 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( return response; } + private StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + requirePinnedLoggingAdminStub(String targetNamespace) { + String expectedServerUri = loggingAdminServerUri(targetNamespace); + requireFileBackedMtls(); + var currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException("Logging/Admin reservation evidence client is unavailable"); + } + return currentStub + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedServerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedServerUri)); + } + + static String loggingAdminServerUri(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("StartSession target namespace is invalid"); + } + return "spiffe://firemud/ns/" + targetNamespace + "/sa/logging-admin-service"; + } + + private void requireFileBackedMtls() { + if (transportTlsProperties.isPlaintext()) { + throw new IllegalStateException("Logging/Admin reservation evidence requires workload mTLS"); + } + ResolvedGrpcTlsMaterial material; + try { + material = new GrpcTlsMaterialResolver().resolve(transportTlsProperties); + } catch (IOException | RuntimeException ignored) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires readable file-backed workload mTLS"); + } + if (material == null + || !isReadableFile(material.certChain()) + || !isReadableFile(material.privateKey()) + || !isReadableFile(material.caCert())) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires readable file-backed workload mTLS"); + } + } + + private static boolean isReadableFile(ResolvedGrpcTlsMaterial.TlsResource resource) { + Path path = resource == null ? null : resource.watchPath(); + return path != null && Files.isRegularFile(path) && Files.isReadable(path); + } + + private static void requireNoAmbientSqlOrSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires no ambient SQL or synchronization"); + } + } + private void validateResponse( ReadCurrentClaimEvidenceResponse response, StartSessionPreAuthorizationReservationTuple tuple, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java index 0078c0ebe7..ca199bed2d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java @@ -3,38 +3,94 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.grpc.Server; +import io.grpc.ServerInterceptors; import io.grpc.Status; import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; +import java.security.KeyStore; import java.security.MessageDigest; +import java.security.cert.CertificateFactory; +import java.time.Duration; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.ArrayList; +import java.util.Base64; import java.util.Comparator; import java.util.HexFormat; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerAttemptLifecycle; +import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerClaim; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquisitionRequest; import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.GrpcOriginalStartSessionCurrentAttemptClient; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +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.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadGrpcService; import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimEvidence; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceGrpcService; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceLeafApproval; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.PostgreSQLContainer; @@ -42,13 +98,20 @@ import org.testcontainers.junit.jupiter.Testcontainers; import tools.jackson.databind.json.JsonMapper; -/** Physical Account issuer-to-World-acquisition proof; Game Session evidence stays stipulated. */ +/** + * Physical Logging claim-read, Account issuer, and World acquisition proof. The Logging mutation + * capability is provided only by its run-owned-PostgreSQL test fixture, and the Account issuer and + * World caller remain in-process test seams; this point-in-time read does not prove continuous + * cross-service protection of later Account or Game Session commits. + */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest { private static final String NAMESPACE = "original-world-acquisition-proof"; private static final String WORLD_PEER_URI = "spiffe://firemud/ns/original-world-acquisition-proof/sa/world-management-service"; + private static final String LOGGING_READ_METHOD = + "logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence"; private static final long GAME_TEMPLATE_ID = 42L; private static final Network NETWORK = Network.newNetwork(); private static final JsonMapper JSON = JsonMapper.builder().build(); @@ -57,6 +120,14 @@ class AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest { static final PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container + static final PostgreSQLContainer gameSessionPostgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final PostgreSQLContainer loggingPostgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container static final GenericContainer redis = new GenericContainer<>(TestContainerImages.redis()) @@ -98,172 +169,957 @@ class AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest { @Test void realOriginalIssueRedemptionAndAcquisitionRetainImmutableObservationAndSources() throws Exception { - try (var controlUi = - new AccountControlUiOriginalOrderFixture( - postgres.getJdbcUrl(), - postgres.getUsername(), - postgres.getPassword(), - redis.getHost(), - redis.getMappedPort(6379), - temporary)) { - prepareOriginalCreator(controlUi); - var proof = - new AccountOriginalStartSessionAuthorizationProofFixture(controlUi, temporary, NAMESPACE); - UUID accountId = proof.creatorAccountId(); - UUID tenantId = controlUi.tenantId(); - String controlPlaneRequestId = "original-world-acquisition-" + UUID.randomUUID(); - UUID reservationOwnerId = UUID.randomUUID(); - UUID gameSessionAttemptId = UUID.randomUUID(); - UUID gameSessionMutationId = UUID.randomUUID(); - UUID gameInstanceId = UUID.randomUUID(); - long reservationClaimFence = 31L; - long gameSessionOwnerFence = 47L; - - var original = - proof.issueAndRedeemOriginal( - controlPlaneRequestId, - new StartSessionOperatorAction( - StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, - StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(tenantId, NAMESPACE), - new StartSessionOperatorAction.Target(GAME_TEMPLATE_ID, accountId), - StartSessionOperatorAction.ExpectedVersion.ABSENT, - new StartSessionOperatorAction.Mutation( - StartSessionOperatorAction.ClientIp.absent()), - "real Account original World acquisition integration proof"), - reservationOwnerId, - reservationClaimFence, - gameSessionAttemptId, - gameSessionOwnerFence); - assertThat(original.originalTuple().preAuthorizationTuple().targetOwner()) - .isEqualTo("game-session-service"); - - Instant stipulatedGameSessionLeaseExpiry = - original.accountReferenceExpiresAt().minusSeconds(30); - assertThat(stipulatedGameSessionLeaseExpiry).isAfter(Instant.now()); - byte[] redemptionProjection = - StartSessionAccountRedemptionProjection.fromOriginalTuple(original.originalTuple()); - List currentAttemptReads = new ArrayList<>(); - OriginalStartSessionCurrentAttemptClient currentAttemptClient = - request -> { - currentAttemptReads.add(request); - return new Result(request, stipulatedGameSessionLeaseExpiry, redemptionProjection); - }; - var acquisitionService = proof.worldParticipationAcquisitionService(currentAttemptClient); - String preparationInput = - preparationInput( - NAMESPACE, tenantId, controlPlaneRequestId, gameInstanceId, GAME_TEMPLATE_ID); - var acquisitionRequest = - new AcquisitionRequest( - original.originalTuple().canonicalBytes(), - gameSessionMutationId, - gameSessionAttemptId, - gameSessionOwnerFence, - gameInstanceId, - preparationInput, - digest(preparationInput)); - - var first = withWorldPeer(() -> acquisitionService.acquire(acquisitionRequest)); - StoredParticipation firstParticipation = first.participation(); - StoredEvidence firstObservation = first.originalAttemptEvidence(); - assertThat(firstParticipation.participationId()).isNotEqualTo(new UUID(0L, 0L)); - assertThat(firstParticipation.participationFence()).isPositive(); - assertThat(firstParticipation.originalPostAuthorizationTuple()) - .containsExactly(original.originalTuple().canonicalBytes()); - assertThat(firstParticipation.gameSessionOwnerAttemptId()).isEqualTo(gameSessionAttemptId); - assertThat(firstParticipation.gameSessionOwnerFence()).isEqualTo(gameSessionOwnerFence); - assertThat(firstParticipation.sources()).isNotEmpty(); - assertThat(firstObservation.gameSessionOwnerMutationId()).isEqualTo(gameSessionMutationId); - assertThat(firstObservation.originalLeaseExpiresAt()) - .isEqualTo(stipulatedGameSessionLeaseExpiry); - assertThat(firstObservation.originalResponseBytes()) - .containsExactly( - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( - new Result( - currentAttemptReads.getFirst(), - stipulatedGameSessionLeaseExpiry, - redemptionProjection)) - .toByteArray()); - - DSLContext dsl = proof.sourceDsl(); - assertPersistedAcquisition( - dsl, original.originalTuple(), firstParticipation, firstObservation); - - // The stipulated Game Session observation is repeated with a newly generated correlation. - // Account's exact-operation retry must preserve the first bytes and participation fence. - var exactRetry = withWorldPeer(() -> acquisitionService.acquire(acquisitionRequest)); - assertThat(currentAttemptReads).hasSize(2); - assertThat(currentAttemptReads.get(0).readRequestId()) - .isNotEqualTo(currentAttemptReads.get(1).readRequestId()); - assertThat(exactRetry.participation().participationId()) - .isEqualTo(firstParticipation.participationId()); - assertThat(exactRetry.participation().participationFence()) - .isEqualTo(firstParticipation.participationFence()); - assertThat(exactRetry.originalAttemptEvidence().originalResponseBytes()) - .containsExactly(firstObservation.originalResponseBytes()); - assertThat(exactRetry.originalAttemptEvidence().result().request().readRequestId()) - .isEqualTo(currentAttemptReads.get(0).readRequestId()); - assertPersistedAcquisition( - dsl, original.originalTuple(), firstParticipation, firstObservation); - - int retainedParticipationCount = - dsl.fetchCount(DSL.table("account_start_session_world_participations")); - int retainedSourceCount = - dsl.fetchCount(DSL.table("account_start_session_world_participation_sources")); - int retainedObservationCount = - dsl.fetchCount(DSL.table("account_start_session_world_original_attempt_evidence")); - - var changedTuple = - StartSessionPostAuthorizationExecutionTuple.createHuman( - original.originalTuple().preAuthorizationTuple(), - original.originalTuple().authenticatedWorkloadIdentity(), - "arfp/v1/changed-proof/" + "c".repeat(64), - original.originalTuple().reservationOwnerId(), - original.originalTuple().reservationClaimFence(), - original.originalTuple().authorityEvidenceBundleBytes(), - original.originalTuple().bundleReference()); - var changedTupleRequest = - new AcquisitionRequest( - changedTuple.canonicalBytes(), - gameSessionMutationId, - gameSessionAttemptId, - gameSessionOwnerFence, - gameInstanceId, - preparationInput, - digest(preparationInput)); - assertFailedPrecondition( - () -> withWorldPeer(() -> acquisitionService.acquire(changedTupleRequest))); - - var changedOwnerFenceRequest = - new AcquisitionRequest( - original.originalTuple().canonicalBytes(), - gameSessionMutationId, - gameSessionAttemptId, - gameSessionOwnerFence + 1, - gameInstanceId, - preparationInput, - digest(preparationInput)); - assertFailedPrecondition( - () -> withWorldPeer(() -> acquisitionService.acquire(changedOwnerFenceRequest))); - assertThat(dsl.fetchCount(DSL.table("account_start_session_world_participations"))) - .isEqualTo(retainedParticipationCount); - assertThat(dsl.fetchCount(DSL.table("account_start_session_world_participation_sources"))) - .isEqualTo(retainedSourceCount); - assertThat(dsl.fetchCount(DSL.table("account_start_session_world_original_attempt_evidence"))) - .isEqualTo(retainedObservationCount); - - var sourceFixture = controlUi.preparedOriginalCreator().sources(); - String originalRole = - dsl.fetchSingle("SELECT role FROM accounts WHERE account_uuid = ?", accountId) - .get(0, String.class); - assertThatThrownBy(sourceFixture::changeRoleToAdmin) - .isInstanceOf(RuntimeException.class) - .hasMessageContaining( - "StartSession World participation remains pending for a required source"); - assertThat( - dsl.fetchSingle("SELECT role FROM accounts WHERE account_uuid = ?", accountId) - .get(0, String.class)) - .isEqualTo(originalRole); + var pki = + TestPki.create(Files.createDirectories(temporary.resolve("original-start-session-pki"))); + var loggingStore = loggingReservationStore(); + var loggingReadRequests = new CopyOnWriteArrayList(); + var loggingReadResponses = new CopyOnWriteArrayList(); + Path approvedAccountLeaves = temporary.resolve("test-only-approved-account-leaves.txt"); + Files.writeString( + approvedAccountLeaves, + "active=" + certificateSha256(pki.accountClient().certificate()) + "\n", + StandardCharsets.US_ASCII); + Server loggingServer = + loggingClaimServer( + pki, + loggingStore.service(), + approvedAccountLeaves, + loggingReadRequests, + loggingReadResponses); + try { + var claimClient = currentClaimGrpcClient(loggingServer.getPort(), pki); + try (claimClient) { + // Invoke the production client's Spring @PostConstruct lifecycle for this direct fixture. + ReflectionTestUtils.invokeMethod(claimClient, "init"); + var gameSessionStore = gameSessionAttemptStore(); + var readService = + new OriginalStartSessionCurrentAttemptReadGrpcService( + gameSessionStore.repository(), gameSessionStore.transactionManager(), NAMESPACE); + Server gameSessionServer = currentAttemptServer(pki, readService); + try (var grpcClient = currentAttemptGrpcClient(gameSessionServer.getPort(), pki)) { + grpcClient.init(); + try (var controlUi = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + prepareOriginalCreator(controlUi); + var proof = + new AccountOriginalStartSessionAuthorizationProofFixture( + controlUi, temporary, NAMESPACE, claimClient); + UUID accountId = proof.creatorAccountId(); + UUID tenantId = controlUi.tenantId(); + String controlPlaneRequestId = "original-world-acquisition-" + UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + AtomicReference reservedGameSessionClaim = new AtomicReference<>(); + AtomicReference gameSessionOwnerClaim = new AtomicReference<>(); + AtomicReference reservedTupleBytes = new AtomicReference<>(); + + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, NAMESPACE), + new StartSessionOperatorAction.Target(GAME_TEMPLATE_ID, accountId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "real Account original World acquisition integration proof"); + StartSessionPreAuthorizationReservationTuple loggingTuple; + SessionContext.setContext( + accountId.toString(), + List.of(), + Map.of(tenantId.toString(), List.of("tenantAdmin")), + false, + null, + null); + try { + loggingTuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + controlPlaneRequestId, action); + } finally { + SessionContext.clear(); + } + var commonTuple = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(loggingTuple.canonicalJson()); + assertThat(loggingTuple.isAuthorityDerived()).isTrue(); + assertThat(loggingTuple.actor().accountId()).isEqualTo(accountId); + + var defaultRepository = + new StartSessionPreAuthorizationReservationRepository(loggingStore.dsl()); + var defaultService = + new StartSessionPreAuthorizationReservationService(defaultRepository); + assertThatThrownBy(() -> defaultService.acquire(loggingTuple)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("mutations are disabled for production construction"); + assertThatThrownBy( + () -> + defaultRepository.acquire( + loggingTuple, + UUID.randomUUID(), + System.currentTimeMillis(), + System.currentTimeMillis() + + StartSessionPreAuthorizationReservationService.CLAIM_TTL + .toMillis())) + .isInstanceOf(UnsupportedOperationException.class); + + var acquired = loggingStore.service().acquire(loggingTuple); + assertThat(acquired.newlyAcquired()).isTrue(); + assertThat(acquired.claim()).isNotNull(); + assertThat(acquired.snapshot().state()).isEqualTo(State.RESERVED); + assertThat(acquired.snapshot().phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + ClaimEvidence claim = acquired.claim().claimEvidence(); + assertThat(claim.reservationOwnerId()).isEqualTo(claim.currentClaimOwnerId()); + assertThat(claim.reservationClaimFence()).isEqualTo(1L); + assertThat(claim.currentClaimFence()).isEqualTo(1L); + + var duplicateAcquire = loggingStore.service().acquire(loggingTuple); + assertThat(duplicateAcquire.newlyAcquired()).isFalse(); + assertThat(duplicateAcquire.claim()).isNull(); + assertThat(duplicateAcquire.snapshot()).isEqualTo(acquired.snapshot()); + assertThat(loggingReadRequests).isEmpty(); + + var pending = loggingStore.service().markAuthorizationPending(acquired.claim()); + assertThat(pending.mayDispatchAccountAuthorization()).isTrue(); + assertThat(pending.snapshot().phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(pending.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(pending.snapshot().claimState()).isEqualTo(ClaimState.ACTIVE); + assertThat(pending.snapshot().claimPurpose()).isEqualTo(ClaimPurpose.ORIGINAL); + assertThat(pending.snapshot().reservationClaimFence()) + .isEqualTo(claim.reservationClaimFence()); + assertThat(pending.snapshot().claimFence()).isEqualTo(claim.currentClaimFence()); + assertThat(pending.snapshot().claimExpiresAtEpochMillis()) + .isGreaterThan(System.currentTimeMillis()); + Record pendingRow = loggingStore.reservationRow(controlPlaneRequestId); + assertThat(pendingRow.get("pre_authorization_tuple_json", String.class)) + .isEqualTo(loggingTuple.canonicalJson()); + assertThat(pendingRow.get("mutation_digest", String.class)) + .isEqualTo(loggingTuple.mutationDigest()); + assertThat(pendingRow.get("phase", String.class)).isEqualTo("ACCOUNT_AUTHORIZATION"); + assertThat(pendingRow.get("state", String.class)).isEqualTo("AUTHORIZATION_PENDING"); + assertThat(pendingRow.get("reservation_owner_id", UUID.class)) + .isEqualTo(claim.reservationOwnerId()); + assertThat(pendingRow.get("reservation_claim_fence", Long.class)) + .isEqualTo(claim.reservationClaimFence()); + assertThat(pendingRow.get("claim_owner_id", UUID.class)) + .isEqualTo(claim.currentClaimOwnerId()); + assertThat(pendingRow.get("claim_fence", Long.class)) + .isEqualTo(claim.currentClaimFence()); + assertThat(pendingRow.get("claim_state", String.class)).isEqualTo("ACTIVE"); + assertThat(pendingRow.get("claim_purpose", String.class)).isEqualTo("ORIGINAL"); + assertThat( + pendingRow.get("claim_expires_at_epoch_ms", Long.class) + - pendingRow.get("created_at_epoch_ms", Long.class)) + .isEqualTo(StartSessionPreAuthorizationReservationService.CLAIM_TTL.toMillis()); + String pendingReservationRow = loggingStore.reservationRowJson(controlPlaneRequestId); + + // The winning transition is the only authorization dispatch point. This direct Account + // fixture call follows immediately; a duplicate acquisition above had no claim to + // dispatch. + var original = + proof.issueAndRedeemOriginal( + controlPlaneRequestId, + action, + claim.reservationOwnerId(), + claim.reservationClaimFence(), + new OwnerAttemptLifecycle() { + @Override + public OwnerClaim reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + AttemptClaim claim = gameSessionStore.reserve(tuple); + reservedGameSessionClaim.set(claim); + reservedTupleBytes.set(tuple.canonicalBytes()); + OwnerClaim ownerClaim = + new OwnerClaim( + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.ownerFence()); + gameSessionOwnerClaim.set(ownerClaim); + return ownerClaim; + } + + @Override + public void attachAccountRedemptionProjection( + OwnerClaim ownerClaim, + StartSessionPostAuthorizationExecutionTuple tuple) { + AttemptClaim claim = + java.util.Objects.requireNonNull( + reservedGameSessionClaim.get(), + "exact Game Session reservation must precede Account redemption"); + assertThat(ownerClaim.ownerAttemptId()).isEqualTo(claim.ownerAttemptId()); + assertThat(ownerClaim.ownerMutationId()).isEqualTo(claim.ownerMutationId()); + assertThat(ownerClaim.ownerFence()).isEqualTo(claim.ownerFence()); + assertThat(tuple.canonicalBytes()) + .containsExactly(reservedTupleBytes.get()); + var authority = + StartSessionAuthorityEvidenceBundle.decode( + tuple.authorityEvidenceBundleBytes()); + var projection = + new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())); + assertThat(projection.canonicalBytes()) + .containsExactly( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); + var attached = gameSessionStore.attach(claim, projection); + assertThat(attached.accountRedemptionProjection()) + .containsExactly(projection.canonicalBytes()); + } + }); + assertThat(original.originalTuple().preAuthorizationTuple().canonicalJson()) + .isEqualTo(loggingTuple.canonicalJson()); + assertThat(original.originalTuple().preAuthorizationTuple().canonicalJson()) + .isEqualTo(commonTuple.canonicalJson()); + assertThat(loggingReadRequests).hasSize(1); + assertThat(loggingReadResponses).hasSize(1); + ReadCurrentClaimEvidenceRequest readRequest = loggingReadRequests.getFirst(); + ReadCurrentClaimEvidenceResponse readResponse = loggingReadResponses.getFirst(); + assertThat(readRequest.getControlPlaneRequestId()).isEqualTo(controlPlaneRequestId); + assertThat(readRequest.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(loggingTuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + readRequest.getPreAuthorizationTupleJson().toStringUtf8()) + .mutationDigest()) + .isEqualTo(loggingTuple.mutationDigest()); + assertThat(readRequest.getReservationOwnerId()) + .isEqualTo(claim.reservationOwnerId().toString()); + assertThat(readRequest.getReservationClaimFence()) + .isEqualTo(claim.reservationClaimFence()); + assertThat(readRequest.getClaimOwnerId()) + .isEqualTo(claim.currentClaimOwnerId().toString()); + assertThat(readRequest.getClaimFence()).isEqualTo(claim.currentClaimFence()); + assertThat(readRequest.getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(readResponse.getControlPlaneRequestId()).isEqualTo(controlPlaneRequestId); + assertThat(readResponse.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(loggingTuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(readResponse.getMutationDigest()).isEqualTo(loggingTuple.mutationDigest()); + assertThat(readResponse.getReservationOwnerId()) + .isEqualTo(claim.reservationOwnerId().toString()); + assertThat(readResponse.getReservationClaimFence()) + .isEqualTo(claim.reservationClaimFence()); + assertThat(readResponse.getClaimOwnerId()) + .isEqualTo(claim.currentClaimOwnerId().toString()); + assertThat(readResponse.getClaimFence()).isEqualTo(claim.currentClaimFence()); + assertThat(readResponse.getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(readResponse.getClaimExpiresAtEpochMillis()) + .isEqualTo(pending.snapshot().claimExpiresAtEpochMillis()); + assertThat(readResponse.getObservedAtEpochMillis()) + .isLessThan(readResponse.getClaimExpiresAtEpochMillis()); + var persistedPending = loggingStore.service().findExact(loggingTuple).orElseThrow(); + assertThat(persistedPending).isEqualTo(pending.snapshot()); + assertThat(persistedPending.phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(persistedPending.state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(persistedPending.reservationClaimFence()) + .isEqualTo(claim.reservationClaimFence()); + assertThat(persistedPending.claimFence()).isEqualTo(claim.currentClaimFence()); + assertThat(persistedPending.claimExpiresAtEpochMillis()) + .isEqualTo(pending.snapshot().claimExpiresAtEpochMillis()); + assertThat(persistedPending.claimPurpose()).isEqualTo(ClaimPurpose.ORIGINAL); + assertThat(loggingStore.reservationRowJson(controlPlaneRequestId)) + .isEqualTo(pendingReservationRow); + var duplicateAfterIssue = loggingStore.service().acquire(loggingTuple); + assertThat(duplicateAfterIssue.newlyAcquired()).isFalse(); + assertThat(duplicateAfterIssue.claim()).isNull(); + assertThat(duplicateAfterIssue.snapshot()).isEqualTo(persistedPending); + assertThat(loggingReadRequests) + .as("an exact duplicate observes the row without a second Account claim read") + .hasSize(1); + assertThat(loggingStore.reservationRowJson(controlPlaneRequestId)) + .isEqualTo(pendingReservationRow); + OwnerClaim ownerClaim = + java.util.Objects.requireNonNull( + gameSessionOwnerClaim.get(), + "actual Game Session owner claim must be retained"); + UUID gameSessionAttemptId = ownerClaim.ownerAttemptId(); + UUID gameSessionMutationId = ownerClaim.ownerMutationId(); + long gameSessionOwnerFence = ownerClaim.ownerFence(); + assertThat(original.gameSessionOwnerAttemptId()).isEqualTo(gameSessionAttemptId); + assertThat(original.gameSessionOwnerFence()).isEqualTo(gameSessionOwnerFence); + assertThat(original.originalTuple().preAuthorizationTuple().targetOwner()) + .isEqualTo("game-session-service"); + + byte[] redemptionProjection = + StartSessionAccountRedemptionProjection.fromOriginalTuple(original.originalTuple()); + List currentAttemptReads = new ArrayList<>(); + List currentAttemptResults = new ArrayList<>(); + OriginalStartSessionCurrentAttemptClient currentAttemptClient = + request -> { + currentAttemptReads.add(request); + Result observation = grpcClient.read(request); + currentAttemptResults.add(observation); + return observation; + }; + var acquisitionService = + proof.worldParticipationAcquisitionService(currentAttemptClient); + String preparationInput = + preparationInput( + NAMESPACE, tenantId, controlPlaneRequestId, gameInstanceId, GAME_TEMPLATE_ID); + var acquisitionRequest = + new AcquisitionRequest( + original.originalTuple().canonicalBytes(), + gameSessionMutationId, + gameSessionAttemptId, + gameSessionOwnerFence, + gameInstanceId, + preparationInput, + digest(preparationInput)); + + String gameSessionRowBeforeReads = + gameSessionStore.ownerAttemptRowJson(controlPlaneRequestId); + var first = withWorldPeer(() -> acquisitionService.acquire(acquisitionRequest)); + StoredParticipation firstParticipation = first.participation(); + StoredEvidence firstObservation = first.originalAttemptEvidence(); + Result firstGameSessionObservation = currentAttemptResults.getFirst(); + assertThat(firstParticipation.participationId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(firstParticipation.participationFence()).isPositive(); + assertThat(firstParticipation.originalPostAuthorizationTuple()) + .containsExactly(original.originalTuple().canonicalBytes()); + assertThat(firstParticipation.gameSessionOwnerAttemptId()) + .isEqualTo(gameSessionAttemptId); + assertThat(firstParticipation.gameSessionOwnerFence()).isEqualTo(gameSessionOwnerFence); + assertThat(firstParticipation.sources()).isNotEmpty(); + assertThat(firstObservation.gameSessionOwnerMutationId()) + .isEqualTo(gameSessionMutationId); + assertThat(firstObservation.originalLeaseExpiresAt()) + .isEqualTo(firstGameSessionObservation.originalLeaseExpiresAt()); + assertThat(firstGameSessionObservation.phaseState()) + .isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(firstGameSessionObservation.request()) + .isEqualTo(currentAttemptReads.getFirst()); + assertThat(firstGameSessionObservation.request().canonicalPostAuthorizationTuple()) + .containsExactly(original.originalTuple().canonicalBytes()); + assertThat(firstGameSessionObservation.request().expectedOwnerAttemptId()) + .isEqualTo(gameSessionAttemptId); + assertThat(firstGameSessionObservation.request().expectedOwnerMutationId()) + .isEqualTo(gameSessionMutationId); + assertThat(firstGameSessionObservation.request().expectedOwnerFence()) + .isEqualTo(gameSessionOwnerFence); + assertThat(firstGameSessionObservation.accountRedemptionProjection()) + .containsExactly(redemptionProjection); + assertThat(firstGameSessionObservation.originalLeaseExpiresAt()).isAfter(Instant.now()); + assertThat(firstGameSessionObservation.originalLeaseExpiresAt()) + .isBefore(original.accountReferenceExpiresAt()); + Record actualGameSessionRow = gameSessionStore.ownerAttemptRow(controlPlaneRequestId); + assertThat(actualGameSessionRow.get("target_namespace", String.class)) + .isEqualTo(NAMESPACE); + assertThat(actualGameSessionRow.get("control_plane_request_id", String.class)) + .isEqualTo(controlPlaneRequestId); + assertThat(actualGameSessionRow.get("owner_attempt_id", UUID.class)) + .isEqualTo(gameSessionAttemptId); + assertThat(actualGameSessionRow.get("owner_mutation_id", UUID.class)) + .isEqualTo(gameSessionMutationId); + assertThat(actualGameSessionRow.get("owner_fence", Long.class)) + .isEqualTo(gameSessionOwnerFence); + assertThat(actualGameSessionRow.get("phase_state", String.class)) + .isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(actualGameSessionRow.get("post_authorization_execution_tuple", byte[].class)) + .containsExactly(original.originalTuple().canonicalBytes()); + assertThat(actualGameSessionRow.get("account_redemption_projection", byte[].class)) + .containsExactly(redemptionProjection); + assertThat(actualGameSessionRow.get("lease_expires_at", OffsetDateTime.class)) + .isEqualTo( + OffsetDateTime.ofInstant( + firstGameSessionObservation.originalLeaseExpiresAt(), ZoneOffset.UTC)); + assertThat(firstObservation.originalResponseBytes()) + .containsExactly( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + firstGameSessionObservation) + .toByteArray()); + + DSLContext dsl = proof.sourceDsl(); + assertPersistedAcquisition( + dsl, original.originalTuple(), firstParticipation, firstObservation); + + // The actual Game Session observation is repeated with a newly generated correlation. + // Account's exact-operation retry must preserve the first bytes and participation + // fence. + var exactRetry = withWorldPeer(() -> acquisitionService.acquire(acquisitionRequest)); + assertThat(currentAttemptReads).hasSize(2); + assertThat(currentAttemptReads.get(0).readRequestId()) + .isNotEqualTo(currentAttemptReads.get(1).readRequestId()); + assertThat(currentAttemptResults).hasSize(2); + assertThat(currentAttemptResults.get(1).request()) + .isEqualTo(currentAttemptReads.get(1)); + assertThat(currentAttemptResults.get(1).accountRedemptionProjection()) + .containsExactly(redemptionProjection); + assertThat(currentAttemptResults.get(1).originalLeaseExpiresAt()) + .isEqualTo(firstGameSessionObservation.originalLeaseExpiresAt()); + assertThat(exactRetry.participation().participationId()) + .isEqualTo(firstParticipation.participationId()); + assertThat(exactRetry.participation().participationFence()) + .isEqualTo(firstParticipation.participationFence()); + assertThat(exactRetry.originalAttemptEvidence().originalResponseBytes()) + .containsExactly(firstObservation.originalResponseBytes()); + assertThat(exactRetry.originalAttemptEvidence().result().request().readRequestId()) + .isEqualTo(currentAttemptReads.get(0).readRequestId()); + assertPersistedAcquisition( + dsl, original.originalTuple(), firstParticipation, firstObservation); + assertThat(gameSessionStore.ownerAttemptRowJson(controlPlaneRequestId)) + .isEqualTo(gameSessionRowBeforeReads); + + int retainedParticipationCount = + dsl.fetchCount(DSL.table("account_start_session_world_participations")); + int retainedSourceCount = + dsl.fetchCount(DSL.table("account_start_session_world_participation_sources")); + int retainedObservationCount = + dsl.fetchCount(DSL.table("account_start_session_world_original_attempt_evidence")); + + var changedTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + original.originalTuple().preAuthorizationTuple(), + original.originalTuple().authenticatedWorkloadIdentity(), + "arfp/v1/changed-proof/" + "c".repeat(64), + original.originalTuple().reservationOwnerId(), + original.originalTuple().reservationClaimFence(), + original.originalTuple().authorityEvidenceBundleBytes(), + original.originalTuple().bundleReference()); + var changedTupleRequest = + new AcquisitionRequest( + changedTuple.canonicalBytes(), + gameSessionMutationId, + gameSessionAttemptId, + gameSessionOwnerFence, + gameInstanceId, + preparationInput, + digest(preparationInput)); + assertFailedPrecondition( + () -> withWorldPeer(() -> acquisitionService.acquire(changedTupleRequest))); + + var changedOwnerFenceRequest = + new AcquisitionRequest( + original.originalTuple().canonicalBytes(), + gameSessionMutationId, + gameSessionAttemptId, + gameSessionOwnerFence + 1, + gameInstanceId, + preparationInput, + digest(preparationInput)); + assertFailedPrecondition( + () -> withWorldPeer(() -> acquisitionService.acquire(changedOwnerFenceRequest))); + assertThat(dsl.fetchCount(DSL.table("account_start_session_world_participations"))) + .isEqualTo(retainedParticipationCount); + assertThat( + dsl.fetchCount(DSL.table("account_start_session_world_participation_sources"))) + .isEqualTo(retainedSourceCount); + assertThat( + dsl.fetchCount( + DSL.table("account_start_session_world_original_attempt_evidence"))) + .isEqualTo(retainedObservationCount); + assertThat(gameSessionStore.ownerAttemptRowJson(controlPlaneRequestId)) + .isEqualTo(gameSessionRowBeforeReads); + + var sourceFixture = controlUi.preparedOriginalCreator().sources(); + String originalRole = + dsl.fetchSingle("SELECT role FROM accounts WHERE account_uuid = ?", accountId) + .get(0, String.class); + assertThatThrownBy(sourceFixture::changeRoleToAdmin) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining( + "StartSession World participation remains pending for a required source"); + assertThat( + dsl.fetchSingle("SELECT role FROM accounts WHERE account_uuid = ?", accountId) + .get(0, String.class)) + .isEqualTo(originalRole); + } + } finally { + stopCurrentAttemptServer(gameSessionServer); + } + } + } finally { + stopLoggingClaimServer(loggingServer); + } + } + + private static GameSessionAttemptStore gameSessionAttemptStore() throws Exception { + String schema = "account_current_attempt_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(gameSessionPostgres.getJdbcUrl()); + dataSource.setUsername(gameSessionPostgres.getUsername()); + dataSource.setPassword(gameSessionPostgres.getPassword()); + dataSource.setSchema(schema); + Path migrationDirectory = gameSessionMigrationDirectory(); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations("filesystem:" + migrationDirectory) + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + String latestMigration = + java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT version FROM flyway_schema_history WHERE success " + + "ORDER BY installed_rank DESC LIMIT 1"), + "Game Session migration history has no successful version") + .get("version", String.class)); + assertThat(latestMigration).isEqualTo("35"); + var transactionManager = new DataSourceTransactionManager(dataSource); + var transactions = new TransactionTemplate(transactionManager); + return new GameSessionAttemptStore( + dsl, + transactionManager, + transactions, + new GameSessionStartSessionOperatorAttemptRepository(dsl, Duration.ofSeconds(30))); + } + + private static LoggingReservationStore loggingReservationStore() throws Exception { + String schema = "account_logging_claim_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(loggingPostgres.getJdbcUrl()); + dataSource.setUsername(loggingPostgres.getUsername()); + dataSource.setPassword(loggingPostgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations("filesystem:" + loggingMigrationDirectory()) + .target(MigrationVersion.fromVersion("4")) + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + assertThat( + dsl.fetch( + "SELECT version FROM flyway_schema_history WHERE success " + + "ORDER BY installed_rank") + .getValues("version", String.class)) + .containsExactly("1", "2", "3", "4"); + var mutationScope = + StartSessionReservationMutationTestFixtures.forRunOwnedPostgres(loggingPostgres, schema); + return new LoggingReservationStore(dsl, mutationScope.service()); + } + + private static Path loggingMigrationDirectory() throws IOException { + Path current = Path.of("").toAbsolutePath().normalize(); + while (current != null) { + Path candidate = + current.resolve("services/logging-admin-service/src/main/resources/db/migration"); + if (Files.isDirectory(candidate)) return candidate.toRealPath(); + Path siblingService = + current.resolve("../logging-admin-service/src/main/resources/db/migration").normalize(); + if (Files.isDirectory(siblingService)) return siblingService.toRealPath(); + current = current.getParent(); + } + throw new IOException( + "Could not locate the Logging/Admin migration directory from this checkout"); + } + + private static Server loggingClaimServer( + TestPki pki, + StartSessionPreAuthorizationReservationService reservationService, + Path approvedAccountLeaves, + List requests, + List responses) + throws Exception { + StartSessionReservationEvidenceGrpcService receiver = + new StartSessionReservationEvidenceGrpcService( + reservationService, + new StartSessionReservationEvidenceLeafApproval(approvedAccountLeaves.toString()), + NAMESPACE) { + @Override + public void readCurrentClaimEvidence( + ReadCurrentClaimEvidenceRequest request, + StreamObserver responseObserver) { + requests.add(request); + super.readCurrentClaimEvidence( + request, + new StreamObserver<>() { + @Override + public void onNext(ReadCurrentClaimEvidenceResponse response) { + responses.add(response); + responseObserver.onNext(response); + } + + @Override + public void onError(Throwable failure) { + responseObserver.onError(failure); + } + + @Override + public void onCompleted() { + responseObserver.onCompleted(); + } + }); + } + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + pki.loggingAdminServer().certificate().toFile(), + pki.loggingAdminServer().privateKey().toFile()) + .trustManager(pki.caCertificate().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + receiver, + new AuthTokenInterceptor( + new JwtUtil("a".repeat(64), 3_600_000L), Set.of(LOGGING_READ_METHOD)), + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static StartSessionReservationEvidenceClient currentClaimGrpcClient( + int port, TestPki pki) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService("localhost:" + port); + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(pki.accountClient().certificate().toString()); + tls.setPrivateKey(pki.accountClient().privateKey().toString()); + tls.setCaCert(pki.caCertificate().toString()); + return new StartSessionReservationEvidenceClient( + endpoints, + tls, + new GrpcChannelFactory(), + net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer.noop()); + } + + private static void stopLoggingClaimServer(Server server) throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Logging/Admin gRPC server did not terminate"); + } + } + + private static Path gameSessionMigrationDirectory() throws IOException { + Path current = Path.of("").toAbsolutePath().normalize(); + while (current != null) { + Path candidate = + current.resolve("services/game-session-service/src/main/resources/db/migration"); + if (Files.isDirectory(candidate)) return candidate.toRealPath(); + Path siblingService = + current.resolve("../game-session-service/src/main/resources/db/migration").normalize(); + if (Files.isDirectory(siblingService)) return siblingService.toRealPath(); + current = current.getParent(); + } + throw new IOException( + "Could not locate the Game Session migration directory from this checkout"); + } + + private record LoggingReservationStore( + DSLContext dsl, StartSessionPreAuthorizationReservationService service) { + String reservationRowJson(String requestId) { + return java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(reservation)::text FROM " + + "start_session_pre_authorization_reservations AS reservation " + + "WHERE control_plane_request_id = ?", + requestId), + "Logging reservation row") + .get(0, String.class); + } + + Record reservationRow(String requestId) { + return dsl.fetchOne( + "SELECT * FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + requestId); + } + } + + private static Server currentAttemptServer( + TestPki pki, OriginalStartSessionCurrentAttemptReadGrpcService readService) throws Exception { + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + pki.gameSessionServer().certificate().toFile(), + pki.gameSessionServer().privateKey().toFile()) + .trustManager(pki.caCertificate().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(readService, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static GrpcOriginalStartSessionCurrentAttemptClient currentAttemptGrpcClient( + int port, TestPki pki) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("localhost:" + port); + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(pki.accountClient().certificate().toString()); + tls.setPrivateKey(pki.accountClient().privateKey().toString()); + tls.setCaCert(pki.caCertificate().toString()); + return new GrpcOriginalStartSessionCurrentAttemptClient( + endpoints, tls, new GrpcChannelFactory(), NAMESPACE); + } + + private static void stopCurrentAttemptServer(Server server) throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Game Session gRPC server did not terminate"); + } + } + + private record GameSessionAttemptStore( + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + GameSessionStartSessionOperatorAttemptRepository repository) { + AttemptClaim reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + var reservation = + java.util.Objects.requireNonNull( + transactions.execute(status -> repository.reserve(tuple)), + "Game Session owner attempt reservation result"); + assertThat(reservation.disposition()) + .isEqualTo( + GameSessionStartSessionOperatorAttemptRepository.ReservationDisposition + .CLAIM_CREATED); + assertThat(reservation.snapshot().postAuthorizationExecutionTuple()) + .containsExactly(tuple.canonicalBytes()); + return reservation.claim().orElseThrow(); + } + + GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot attach( + AttemptClaim claim, AccountRedemptionProjection projection) { + return java.util.Objects.requireNonNull( + transactions.execute( + status -> repository.attachAccountRedemptionProjection(claim, projection)), + "Game Session projection attachment snapshot"); + } + + String ownerAttemptRowJson(String requestId) { + Record row = + dsl.fetchOne( + "SELECT to_jsonb(attempt)::text FROM " + + "game_session_start_session_operator_attempt AS attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + requestId); + return java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull(row, "Game Session owner attempt row") + .get(0, String.class)); + } + + Record ownerAttemptRow(String requestId) { + return dsl.fetchOne( + "SELECT * FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + requestId); + } + } + + private record TestIdentity(Path certificate, Path privateKey) {} + + /** Test-only identities for the Account-to-Logging and Account-to-Game-Session mTLS proofs. */ + private record TestPki( + Path caCertificate, + TestIdentity gameSessionServer, + TestIdentity loggingAdminServer, + TestIdentity accountClient) { + private static final String PASSWORD = "test-only-current-attempt-password"; + + static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("current-attempt-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD current-attempt integration test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + Path caFile = directory.resolve("current-attempt-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + return new TestPki( + caFile, + issueIdentity( + directory, + caStore, + "game-session-server", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service", + true), + issueIdentity( + directory, + caStore, + "logging-admin-server", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + true), + issueIdentity( + directory, + caStore, + "account-client", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", + false)); + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String extendedKeyUsage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + PASSWORD, + "-keypass", + PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, PASSWORD.toCharArray()); + } + byte[] encodedPrivateKey = + java.util.Objects.requireNonNull( + keyStore.getKey(alias, PASSWORD.toCharArray()), + "Expected ephemeral current-attempt private key") + .getEncoded(); + Path privateKey = directory.resolve(alias + ".key"); + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encodedPrivateKey); + Files.writeString( + privateKey, + "-----BEGIN PRIVATE KEY-----\n" + body + "\n-----END PRIVATE KEY-----\n", + StandardCharsets.US_ASCII); + java.util.Arrays.fill(encodedPrivateKey, (byte) 0); + return new TestIdentity(certificate, privateKey); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("Ephemeral current-attempt test certificate timed out"); + } + process.getInputStream().transferTo(output); + if (process.exitValue() != 0) { + throw new IllegalStateException( + "Current-attempt test keytool failed: " + output.toString(StandardCharsets.UTF_8)); + } + } + } + + private static String certificateSha256(Path certificate) throws Exception { + try (var input = Files.newInputStream(certificate)) { + var parsed = CertificateFactory.getInstance("X.509").generateCertificate(input); + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(parsed.getEncoded())); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientMtlsTest.java new file mode 100644 index 0000000000..a03fd598cc --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientMtlsTest.java @@ -0,0 +1,767 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.UnaryOperator; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic loopback mutual-TLS proof; the handler does not read Logging/Admin owner state. */ +class StartSessionReservationEvidenceClientMtlsTest { + private static final String NAMESPACE = "world-runtime"; + private static final String LOGGING_ADMIN_URI = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/world-runtime/sa/account-service"; + private static final String REQUEST_ID = "start-session-βeta"; + private static final String STORE_PASSWORD = "synthetic-claim-evidence-test"; + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final UUID ACTOR_ID = UUID.fromString("1ea6eb2c-e211-4f4f-a812-14909b9a72b8"); + private static final UUID TENANT_ID = UUID.fromString("5212125e-7d89-4c51-b3a0-bef10e04ccda"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("b2a1a560-5e62-4f61-98bf-dae49ba37a38"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("44997fae-a4c4-45de-8d4f-5e75ad233f0f"); + private static final UUID RECOVERY_OWNER_ID = + UUID.fromString("c8190808-e325-4d8a-9702-fbf5a53d436d"); + + @TempDir static Path temporaryDirectory; + + private static TestPki pki; + private final AtomicInteger handlerCalls = new AtomicInteger(); + private final AtomicInteger callerDenials = new AtomicInteger(); + private final List receivedRequests = + new CopyOnWriteArrayList<>(); + private final AtomicReference> responseMutation = + new AtomicReference<>(UnaryOperator.identity()); + private final AtomicReference responseStatus = new AtomicReference<>(); + private Server server; + private StartSessionReservationEvidenceClient client; + + @BeforeAll + static void createSyntheticWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @AfterEach + void stopTransportAndClearThreadState() throws Exception { + if (client != null) { + client.close(); + client = null; + } + stopServer(); + TransactionSynchronizationManager.clear(); + } + + @Test + void repeatedReadsPreserveTupleClaimPurposeAndFiveSecondDeadline() throws Exception { + startServer(pki.loggingAdminServer()); + client = newClient(pki.accountClient()); + client.init(); + var tuple = tuple(); + + var issueFirst = read(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE); + var issueRetry = read(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE); + var recoveryFirst = read(tuple, StartSessionReservationEvidenceClient.Purpose.RECOVER); + var recoveryRetry = read(tuple, StartSessionReservationEvidenceClient.Purpose.RECOVER); + + assertThat(issueFirst).isEqualTo(issueRetry); + assertThat(recoveryFirst).isEqualTo(recoveryRetry); + assertThat(receivedRequests).hasSize(4); + assertThat(handlerCalls).hasValue(4); + assertThat(receivedRequests) + .allSatisfy( + request -> { + assertThat(request.getControlPlaneRequestId()).isEqualTo(REQUEST_ID); + assertThat(request.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(request.getReservationOwnerId()) + .isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(request.getReservationClaimFence()).isEqualTo(1L); + }); + assertThat(receivedRequests.get(0).getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(receivedRequests.get(1)).isEqualTo(receivedRequests.get(0)); + assertThat(receivedRequests.get(2).getClaimOwnerId()).isEqualTo(RECOVERY_OWNER_ID.toString()); + assertThat(receivedRequests.get(2).getClaimFence()).isEqualTo(3L); + assertThat(receivedRequests.get(2).getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER); + assertThat(receivedRequests.get(3)).isEqualTo(receivedRequests.get(2)); + } + + @Test + void rejectsMismatchedEchoUnknownFieldsAndStaleLeaseTimes() throws Exception { + startServer(pki.loggingAdminServer()); + client = newClient(pki.accountClient()); + client.init(); + var tuple = tuple(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + List> invalidResponses = + List.of( + response -> response.toBuilder().setControlPlaneRequestId("different-request").build(), + response -> + response.toBuilder() + .setPreAuthorizationTupleJson(ByteString.copyFromUtf8("different tuple")) + .build(), + response -> response.toBuilder().setMutationDigest("sha256:" + "0".repeat(64)).build(), + response -> + response.toBuilder().setReservationOwnerId(UUID.randomUUID().toString()).build(), + response -> response.toBuilder().setReservationClaimFence(2L).build(), + response -> response.toBuilder().setClaimOwnerId(UUID.randomUUID().toString()).build(), + response -> response.toBuilder().setClaimFence(2L).build(), + response -> + response.toBuilder() + .setPurpose( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER) + .build(), + response -> response.toBuilder().setObservedAtEpochMillis(0L).build(), + response -> + response.toBuilder().setObservedAtEpochMillis(NOW_EPOCH_MILLIS + 1L).build(), + response -> + response.toBuilder() + .setClaimExpiresAtEpochMillis(response.getObservedAtEpochMillis()) + .build(), + response -> response.toBuilder().setClaimExpiresAtEpochMillis(NOW_EPOCH_MILLIS).build(), + response -> response.toBuilder().setUnknownFields(unknown).build()); + + for (UnaryOperator invalidResponse : invalidResponses) { + responseMutation.set(invalidResponse); + assertThatThrownBy(() -> read(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or mismatched"); + } + assertThat(handlerCalls).hasValue(invalidResponses.size()); + } + + @Test + void rejectsInvalidInputBeforeAnyRpc() throws Exception { + startServer(pki.loggingAdminServer()); + client = newClient(pki.accountClient()); + client.init(); + var tuple = tuple(); + + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + null, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 0L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RECOVERY_OWNER_ID, + 3L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.RECOVER)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(handlerCalls).hasValue(0); + } + + @Test + void propagatesUnavailableAndStaleOwnerStatusesWithoutInterpretingThemAsEvidence() + throws Exception { + startServer(pki.loggingAdminServer()); + client = newClient(pki.accountClient()); + client.init(); + responseStatus.set(Status.UNAVAILABLE); + + assertThatThrownBy(() -> read(tuple(), StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + + responseStatus.set(Status.FAILED_PRECONDITION); + assertThatThrownBy(() -> read(tuple(), StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThat(handlerCalls).hasValue(2); + } + + @Test + void rejectsWrongLoggingServerIdentityEvenWhenCertificateChainsToSameCa() throws Exception { + for (TestIdentity wrongServer : List.of(pki.wrongServiceServer(), pki.wrongNamespaceServer())) { + startServer(wrongServer); + client = newClient(pki.accountClient()); + client.init(); + + assertThatThrownBy(() -> read(tuple(), StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(handlerCalls).hasValue(0); + stopClientAndServer(); + } + } + + @Test + void rejectsWrongAccountCallerServiceAndNamespaceAtSyntheticReceiverBoundary() throws Exception { + startServer(pki.loggingAdminServer()); + for (TestIdentity wrongCaller : List.of(pki.wrongServiceClient(), pki.wrongNamespaceClient())) { + client = newClient(wrongCaller); + client.init(); + + assertThatThrownBy(() -> read(tuple(), StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(handlerCalls).hasValue(0); + assertThat(callerDenials).hasValue(1); + stopClient(); + callerDenials.set(0); + } + } + + @Test + void requiresClientCertificateOnTheSyntheticLoggingServer() throws Exception { + startServer(pki.loggingAdminServer()); + SSLContext trustOnlyContext = SSLContext.getInstance("TLS"); + var trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, STORE_PASSWORD.toCharArray()); + trustStore.setCertificateEntry("trusted-test-ca", pki.caCertificate()); + var trustManagers = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + trustOnlyContext.init(null, trustManagers.getTrustManagers(), new SecureRandom()); + + Throwable failure = + catchThrowable( + () -> { + try (SSLSocket socket = + (SSLSocket) + trustOnlyContext + .getSocketFactory() + .createSocket("127.0.0.1", server.getPort())) { + socket.setSoTimeout(2_000); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + parameters.setProtocols(new String[] {"TLSv1.3"}); + parameters.setApplicationProtocols(new String[] {"h2"}); + socket.setSSLParameters(parameters); + socket.startHandshake(); + socket.getInputStream().read(); + } + }); + + assertThat(failure).isInstanceOf(SSLHandshakeException.class); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue(); + assertThat(handlerCalls).hasValue(0); + } + + @Test + void rejectsPlaintextAndAmbientSqlOrSynchronizationBeforeNetwork() throws Exception { + startServer(pki.loggingAdminServer()); + var plaintextProperties = new CommonGrpcClientProperties(); + plaintextProperties.setPlaintext(true); + client = newClient(plaintextProperties); + client.init(); + assertThatThrownBy(() -> read(tuple(), StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires workload mTLS"); + assertThat(handlerCalls).hasValue(0); + stopClient(); + + var missingFiles = new CommonGrpcClientProperties(); + missingFiles.setPlaintext(false); + client = newClient(missingFiles); + assertThatThrownBy(() -> read(tuple(), StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readable file-backed workload mTLS"); + assertThat(handlerCalls).hasValue(0); + stopClient(); + + client = newClient(pki.accountClient()); + client.init(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> read(tuple(), StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> read(tuple(), StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(handlerCalls).hasValue(0); + } + + private ReadCurrentClaimEvidenceResponse read( + StartSessionPreAuthorizationReservationTuple tuple, + StartSessionReservationEvidenceClient.Purpose purpose) { + boolean issue = purpose == StartSessionReservationEvidenceClient.Purpose.ISSUE; + return client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + issue ? RESERVATION_OWNER_ID : RECOVERY_OWNER_ID, + issue ? 1L : 3L, + purpose); + } + + private void startServer(TestIdentity serverIdentity) throws Exception { + handlerCalls.set(0); + callerDenials.set(0); + receivedRequests.clear(); + responseMutation.set(UnaryOperator.identity()); + responseStatus.set(null); + var service = + new StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceImplBase() { + @Override + public void readCurrentClaimEvidence( + ReadCurrentClaimEvidenceRequest request, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !ACCOUNT_URI.equals(peer.uri())) { + callerDenials.incrementAndGet(); + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + handlerCalls.incrementAndGet(); + receivedRequests.add(request); + var deadline = Context.current().getDeadline(); + if (deadline == null + || deadline.timeRemaining(TimeUnit.MILLISECONDS) <= 0L + || deadline.timeRemaining(TimeUnit.MILLISECONDS) > 5_000L) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + Status failureStatus = responseStatus.get(); + if (failureStatus != null) { + observer.onError(failureStatus.asRuntimeException()); + return; + } + observer.onNext(responseMutation.get().apply(validResponse(request))); + observer.onCompleted(); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .protocols("TLSv1.3") + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private StartSessionReservationEvidenceClient newClient(TestIdentity identity) throws Exception { + return newClient(pki.clientProperties(temporaryDirectory, identity)); + } + + private StartSessionReservationEvidenceClient newClient( + CommonGrpcClientProperties tlsProperties) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService("localhost:" + server.getPort()); + return new StartSessionReservationEvidenceClient( + endpoints, + tlsProperties, + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC)); + } + + private void stopClientAndServer() throws Exception { + stopClient(); + stopServer(); + } + + private void stopClient() throws Exception { + if (client != null) { + client.close(); + client = null; + } + } + + private void stopServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private static ReadCurrentClaimEvidenceResponse validResponse( + ReadCurrentClaimEvidenceRequest request) { + return ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(request.getControlPlaneRequestId()) + .setPreAuthorizationTupleJson(request.getPreAuthorizationTupleJson()) + .setMutationDigest(tuple().mutationDigest()) + .setReservationOwnerId(request.getReservationOwnerId()) + .setReservationClaimFence(request.getReservationClaimFence()) + .setClaimOwnerId(request.getClaimOwnerId()) + .setClaimFence(request.getClaimFence()) + .setClaimExpiresAtEpochMillis(NOW_EPOCH_MILLIS + 30_000L) + .setObservedAtEpochMillis(NOW_EPOCH_MILLIS - 1_000L) + .setPurpose(request.getPurpose()) + .build(); + } + + private static StartSessionPreAuthorizationReservationTuple tuple() { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "reservation evidence client mTLS test"); + return StartSessionPreAuthorizationReservationTuple.createHuman(REQUEST_ID, ACTOR_ID, action); + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity loggingAdminServer, + TestIdentity wrongServiceServer, + TestIdentity wrongNamespaceServer, + TestIdentity accountClient, + TestIdentity wrongServiceClient, + TestIdentity wrongNamespaceClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("claim-evidence-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD claim evidence test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("claim-evidence-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + return new TestPki( + readCertificate(caFile), + issueIdentity(directory, caStore, caFile, "logging-server", LOGGING_ADMIN_URI, true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-service-server", + "spiffe://firemud/ns/world-runtime/sa/account-service", + true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-namespace-server", + "spiffe://firemud/ns/other-runtime/sa/logging-admin-service", + true), + issueIdentity(directory, caStore, caFile, "account-client", ACCOUNT_URI, false), + issueIdentity( + directory, + caStore, + caFile, + "wrong-service-client", + "spiffe://firemud/ns/world-runtime/sa/game-session-service", + false), + issueIdentity( + directory, + caStore, + caFile, + "wrong-namespace-client", + "spiffe://firemud/ns/other-runtime/sa/account-service", + false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve(identity.alias() + ".client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve(identity.alias() + ".client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("claim-evidence-client-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + properties.setPlaintext(false); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] encoded) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded); + Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + return path; + } + + private static void runKeytool(String... arguments) throws Exception { + List command = new ArrayList<>(); + command.add(Path.of(System.getProperty("java.home"), "bin", "keytool").toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + process.getInputStream().transferTo(output); + int exitCode = process.waitFor(); + assertThat(exitCode) + .withFailMessage("keytool failed: %s", output.toString(StandardCharsets.UTF_8)) + .isZero(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java index fbdffb7bb8..15769bc929 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java @@ -7,45 +7,26 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; -import com.google.protobuf.ByteString; -import com.google.protobuf.UnknownFieldSet; -import io.grpc.ManagedChannel; -import io.grpc.Server; -import io.grpc.Status; -import io.grpc.StatusRuntimeException; -import io.grpc.inprocess.InProcessChannelBuilder; -import io.grpc.inprocess.InProcessServerBuilder; -import io.grpc.stub.StreamObserver; import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; -import java.util.ArrayList; -import java.util.List; import java.util.UUID; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; -import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; -import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; -import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; -import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; class StartSessionReservationEvidenceClientTest { - private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; private static final String REQUEST_ID = "start-session-βeta"; private static final UUID ACTOR_ID = UUID.fromString("1ea6eb2c-e211-4f4f-a812-14909b9a72b8"); private static final UUID TENANT_ID = UUID.fromString("5212125e-7d89-4c51-b3a0-bef10e04ccda"); @@ -56,234 +37,66 @@ class StartSessionReservationEvidenceClientTest { private static final UUID RECOVERY_OWNER_ID = UUID.fromString("c8190808-e325-4d8a-9702-fbf5a53d436d"); private static final Clock CLOCK = - Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC); + Clock.fixed(Instant.parse("2027-01-15T08:00:00Z"), ZoneOffset.UTC); private static final String LOGGING_ADMIN_TARGET = "logging-admin.internal:6565"; @Test - void repeatedInProcessReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exception { - StartSessionPreAuthorizationReservationTuple tuple = tuple(); - List requests = new ArrayList<>(); - try (InProcessFixture fixture = - inProcessFixture( - request -> { - requests.add(request); - assertThat(io.grpc.Context.current().getDeadline()).isNotNull(); - return validResponse(request, tuple.mutationDigest()); - })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); - - ReadCurrentClaimEvidenceResponse issueFirst = - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE); - ReadCurrentClaimEvidenceResponse issueRetry = - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE); - ReadCurrentClaimEvidenceResponse recoveryFirst = - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RECOVERY_OWNER_ID, - 3L, - StartSessionReservationEvidenceClient.Purpose.RECOVER); - ReadCurrentClaimEvidenceResponse recoveryRetry = - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RECOVERY_OWNER_ID, - 3L, - StartSessionReservationEvidenceClient.Purpose.RECOVER); - - assertThat(issueFirst).isEqualTo(issueRetry); - assertThat(recoveryFirst).isEqualTo(recoveryRetry); - assertThat(requests).hasSize(4); - assertThat(requests) - .allSatisfy( - request -> { - assertThat(request.getControlPlaneRequestId()).isEqualTo(REQUEST_ID); - assertThat(request.getPreAuthorizationTupleJson().toByteArray()) - .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); - assertThat(request.getReservationOwnerId()) - .isEqualTo(RESERVATION_OWNER_ID.toString()); - assertThat(request.getReservationClaimFence()).isEqualTo(1L); - }); - assertThat(requests.get(0).getPurpose()) - .isEqualTo( - StartSessionReservationEvidencePurpose - .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); - assertThat(requests.get(1)).isEqualTo(requests.get(0)); - assertThat(requests.get(2).getClaimOwnerId()).isEqualTo(RECOVERY_OWNER_ID.toString()); - assertThat(requests.get(2).getClaimFence()).isEqualTo(3L); - assertThat(requests.get(2).getPurpose()) - .isEqualTo( - StartSessionReservationEvidencePurpose - .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER); - assertThat(requests.get(3)).isEqualTo(requests.get(2)); - } + void derivesTheExactLoggingPeerFromTheTupleNamespace() { + assertThat(StartSessionReservationEvidenceClient.loggingAdminServerUri("world-runtime")) + .isEqualTo("spiffe://firemud/ns/world-runtime/sa/logging-admin-service"); + assertThatThrownBy( + () -> StartSessionReservationEvidenceClient.loggingAdminServerUri("bad/namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); } @Test - void rejectsEveryResponseIdentityFieldUnknownFieldsAndStaleTimes() throws Exception { - StartSessionPreAuthorizationReservationTuple tuple = tuple(); - AtomicReference response = new AtomicReference<>(); - try (InProcessFixture fixture = inProcessFixture(request -> response.get())) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); - ReadCurrentClaimEvidenceResponse valid = - validResponse( - request(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE), - tuple.mutationDigest()); - List invalid = - List.of( - valid.toBuilder().setControlPlaneRequestId(UUID.randomUUID().toString()).build(), - valid.toBuilder() - .setPreAuthorizationTupleJson(ByteString.copyFromUtf8("different tuple")) - .build(), - valid.toBuilder().setMutationDigest("sha256:" + "0".repeat(64)).build(), - valid.toBuilder().setReservationOwnerId(UUID.randomUUID().toString()).build(), - valid.toBuilder().setReservationClaimFence(2L).build(), - valid.toBuilder().setClaimOwnerId(UUID.randomUUID().toString()).build(), - valid.toBuilder().setClaimFence(2L).build(), - valid.toBuilder() - .setPurpose( - StartSessionReservationEvidencePurpose - .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER) - .build(), - valid.toBuilder().setObservedAtEpochMillis(0L).build(), - valid.toBuilder().setObservedAtEpochMillis(NOW_EPOCH_MILLIS + 1L).build(), - valid.toBuilder() - .setClaimExpiresAtEpochMillis(valid.getObservedAtEpochMillis()) - .build(), - valid.toBuilder().setClaimExpiresAtEpochMillis(NOW_EPOCH_MILLIS).build(), - valid.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) - .build()) - .build()); - - for (ReadCurrentClaimEvidenceResponse invalidResponse : invalid) { - response.set(invalidResponse); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("stale or mismatched"); - } - } - } - - @Test - void invalidInputIsRejectedBeforeAnyRpc() throws Exception { - StartSessionPreAuthorizationReservationTuple tuple = tuple(); - AtomicInteger calls = new AtomicInteger(); - try (InProcessFixture fixture = - inProcessFixture( - request -> { - calls.incrementAndGet(); - return validResponse(request, tuple.mutationDigest()); - })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); - - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - null, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) - .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 0L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RECOVERY_OWNER_ID, - 3L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.RECOVER)) - .isInstanceOf(IllegalArgumentException.class); - assertThat(calls).hasValue(0); - } - } - - @Test - void propagatesUnavailableAndStaleOwnerStatusesWithoutInterpretingThemAsEvidence() - throws Exception { - StartSessionPreAuthorizationReservationTuple tuple = tuple(); - AtomicReference status = new AtomicReference<>(Status.UNAVAILABLE); - try (InProcessFixture fixture = - inProcessFixture( - request -> { - throw status.get().asRuntimeException(); - })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); - - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) - .isInstanceOf(StatusRuntimeException.class) - .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) - .isEqualTo(Status.Code.UNAVAILABLE); - - status.set(Status.FAILED_PRECONDITION); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) - .isInstanceOf(StatusRuntimeException.class) - .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION); - } + void invalidInputIsRejectedBeforeAnyTransportUse() { + var channelFactory = mock(GrpcChannelFactory.class); + var client = newClient(channelFactory, plaintextProperties()); + var tuple = tuple(); + + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + null, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 0L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RECOVERY_OWNER_ID, + 3L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.RECOVER)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(channelFactory); } @Test @@ -293,18 +106,18 @@ void usesConfiguredLoggingEndpointTlsChannelAndStubCustomizer(@TempDir Path dire endpoints.setLoggingAdminService(LOGGING_ADMIN_TARGET); CommonGrpcClientProperties tls = tlsProperties(directory); GrpcChannelFactory channelFactory = spy(new GrpcChannelFactory()); - AtomicInteger customizerCalls = new AtomicInteger(); - BlockingGrpcStubCustomizer customizer = + var customizer = new AtomicInteger(); + BlockingGrpcStubCustomizer stubCustomizer = new BlockingGrpcStubCustomizer() { @Override public > T customize(T stub) { - customizerCalls.incrementAndGet(); + customizer.incrementAndGet(); return stub; } }; - StartSessionReservationEvidenceClient client = + var client = new StartSessionReservationEvidenceClient( - endpoints, tls, channelFactory, customizer, CLOCK); + endpoints, tls, channelFactory, stubCustomizer, CLOCK); try { client.init(); @@ -312,107 +125,30 @@ public > T customize(T stub) { verify(channelFactory) .buildChannel( eq(LOGGING_ADMIN_TARGET), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); - assertThat(customizerCalls).hasValue(1); + assertThat(customizer).hasValue(1); } finally { client.close(); } } - private static StartSessionReservationEvidenceClient client( - StartSessionReservationEvidenceServiceGrpc.StartSessionReservationEvidenceServiceBlockingStub - stub) - throws Exception { - StartSessionReservationClientTestAccess client = newClient(); - client.installStub(stub); - return client.client(); + private static StartSessionReservationEvidenceClient newClient( + GrpcChannelFactory channelFactory, CommonGrpcClientProperties tlsProperties) { + return new StartSessionReservationEvidenceClient( + new ServiceEndpointsProperties(), + tlsProperties, + channelFactory, + BlockingGrpcStubCustomizer.noop(), + CLOCK); } - private static StartSessionReservationClientTestAccess newClient() { - ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); - CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + private static CommonGrpcClientProperties plaintextProperties() { + var tls = new CommonGrpcClientProperties(); tls.setPlaintext(true); - StartSessionReservationEvidenceClient client = - new StartSessionReservationEvidenceClient( - endpoints, - tls, - mock(GrpcChannelFactory.class), - BlockingGrpcStubCustomizer.noop(), - CLOCK); - return new StartSessionReservationClientTestAccess(client); - } - - private static InProcessFixture inProcessFixture(EvidenceHandler handler) throws Exception { - String serverName = InProcessServerBuilder.generateName(); - Server server = - InProcessServerBuilder.forName(serverName) - .directExecutor() - .addService( - new StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceImplBase() { - @Override - public void readCurrentClaimEvidence( - ReadCurrentClaimEvidenceRequest request, - StreamObserver responseObserver) { - try { - responseObserver.onNext(handler.read(request)); - responseObserver.onCompleted(); - } catch (StatusRuntimeException exception) { - responseObserver.onError(exception); - } - } - }) - .build() - .start(); - ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); - return new InProcessFixture(server, channel); - } - - private static ReadCurrentClaimEvidenceRequest request( - StartSessionPreAuthorizationReservationTuple tuple, - StartSessionReservationEvidenceClient.Purpose purpose) { - return ReadCurrentClaimEvidenceRequest.newBuilder() - .setControlPlaneRequestId(tuple.controlPlaneRequestId()) - .setPreAuthorizationTupleJson( - ByteString.copyFrom(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) - .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) - .setReservationClaimFence(1L) - .setClaimOwnerId( - purpose == StartSessionReservationEvidenceClient.Purpose.ISSUE - ? RESERVATION_OWNER_ID.toString() - : RECOVERY_OWNER_ID.toString()) - .setClaimFence(purpose == StartSessionReservationEvidenceClient.Purpose.ISSUE ? 1L : 3L) - .setPurpose(toWirePurpose(purpose)) - .build(); - } - - private static ReadCurrentClaimEvidenceResponse validResponse( - ReadCurrentClaimEvidenceRequest request, String mutationDigest) { - return ReadCurrentClaimEvidenceResponse.newBuilder() - .setControlPlaneRequestId(request.getControlPlaneRequestId()) - .setPreAuthorizationTupleJson(request.getPreAuthorizationTupleJson()) - .setMutationDigest(mutationDigest) - .setReservationOwnerId(request.getReservationOwnerId()) - .setReservationClaimFence(request.getReservationClaimFence()) - .setClaimOwnerId(request.getClaimOwnerId()) - .setClaimFence(request.getClaimFence()) - .setClaimExpiresAtEpochMillis(NOW_EPOCH_MILLIS + 30_000L) - .setObservedAtEpochMillis(NOW_EPOCH_MILLIS - 1_000L) - .setPurpose(request.getPurpose()) - .build(); - } - - private static StartSessionReservationEvidencePurpose toWirePurpose( - StartSessionReservationEvidenceClient.Purpose purpose) { - return switch (purpose) { - case ISSUE -> - StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE; - case RECOVER -> - StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER; - }; + return tls; } private static StartSessionPreAuthorizationReservationTuple tuple() { - StartSessionOperatorAction action = + var action = new StartSessionOperatorAction( StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, @@ -443,36 +179,4 @@ private static Path copyCertificateResource(String fileName, Path directory) thr } return destination; } - - @FunctionalInterface - private interface EvidenceHandler { - ReadCurrentClaimEvidenceResponse read(ReadCurrentClaimEvidenceRequest request); - } - - private record InProcessFixture(Server server, ManagedChannel channel) implements AutoCloseable { - private StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceBlockingStub - stub() { - return StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel); - } - - @Override - public void close() throws Exception { - channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); - server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); - } - } - - private record StartSessionReservationClientTestAccess( - StartSessionReservationEvidenceClient client) { - private void installStub( - StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceBlockingStub - stub) - throws Exception { - var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); - field.setAccessible(true); - field.set(client, stub); - } - } } diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java index 1a1d504105..fde6bd8b66 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -47,11 +47,14 @@ * Test-only proof fixture for Account's original human StartSession issuer, one-time redemption, * and real World participation acquisition composition. * - *

Logging's current-claim read response and the supplied Game Session attempt/fence remain - * stipulated inputs. The Account actor, source capture, issuance, reference custody, redemption, - * and later projection read use the real Account owners and retained PostgreSQL rows. The peer - * scopes around issue and redemption are in-process test stipulations, not authenticated producer - * or mTLS proof. + *

Logging's current-claim read response remains stipulated in the default constructor; a + * composed proof may inject its actual authenticated claim reader explicitly. The Account actor, + * source capture, issuance, reference custody, redemption, and later projection read use the real + * Account owners and retained PostgreSQL rows. A test may supply a Game Session owner-attempt + * lifecycle so it can reserve the exact issued tuple before redemption and attach the redeemed + * projection after redemption, without introducing Game Session classes into this fixture artifact. + * The peer scopes around issue and redemption are in-process test stipulations, not authenticated + * producer or mTLS proof. */ public final class AccountOriginalStartSessionAuthorizationProofFixture { private static final Duration REFERENCE_LIFETIME = Duration.ofMinutes(5); @@ -74,6 +77,19 @@ public final class AccountOriginalStartSessionAuthorizationProofFixture { public AccountOriginalStartSessionAuthorizationProofFixture( AccountControlUiOriginalOrderFixture controlUi, Path temporary, String namespace) throws Exception { + this(controlUi, temporary, namespace, stipulatedLoggingClaimClient()); + } + + /** + * Supplies the actual authenticated Logging claim reader for a composed owner proof. Existing + * callers retain their explicitly stipulated default; this overload adds no production bypass. + */ + public AccountOriginalStartSessionAuthorizationProofFixture( + AccountControlUiOriginalOrderFixture controlUi, + Path temporary, + String namespace, + StartSessionReservationEvidenceClient claimClient) + throws Exception { Objects.requireNonNull(controlUi, "Account control-ui fixture is required"); Objects.requireNonNull(temporary, "temporary test directory is required"); this.namespace = requireNamespace(namespace); @@ -82,7 +98,7 @@ public AccountOriginalStartSessionAuthorizationProofFixture( loggingPeerUri = peerUri(namespace, LOGGING_SERVICE); gameSessionPeerUri = peerUri(namespace, GAME_SESSION_SERVICE); - var claimClient = stipulatedLoggingClaimClient(); + Objects.requireNonNull(claimClient, "exact Logging claim client is required"); repository = new AccountStartSessionOperatorAuthorizationRepository(accountSources.dsl); captureRepository = new AccountStartSessionAuthorityCaptureRepository(accountSources.dsl); authorizationService = @@ -121,12 +137,48 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( long reservationClaimFence, UUID gameSessionOwnerAttemptId, long gameSessionOwnerFence) { + requireOwner(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + return issueAndRedeemOriginal( + controlPlaneRequestId, + action, + reservationOwnerId, + reservationClaimFence, + new OwnerAttemptLifecycle() { + @Override + public OwnerClaim reserve(StartSessionPostAuthorizationExecutionTuple originalTuple) { + return new OwnerClaim( + gameSessionOwnerAttemptId, UUID.randomUUID(), gameSessionOwnerFence); + } + + @Override + public void attachAccountRedemptionProjection( + OwnerClaim ownerClaim, StartSessionPostAuthorizationExecutionTuple originalTuple) { + // Existing callers may continue to use this fixture with a stipulated owner attempt. + } + }); + } + + /** + * Performs real Account issue and redemption around a test-supplied Game Session owner attempt. + * + *

The callback reserves the exact post-authorization tuple after issue and before Account + * redemption. Once redemption succeeds, the callback receives that same claim and tuple so the + * owning Game Session repository can attach the exact Account projection. Logging claim evidence + * remains stipulated unless the actual reader is injected; the issue/redemption peer identities + * remain stipulated by this Account fixture. + */ + public synchronized OriginalStartSession issueAndRedeemOriginal( + String controlPlaneRequestId, + StartSessionOperatorAction action, + UUID reservationOwnerId, + long reservationClaimFence, + OwnerAttemptLifecycle ownerAttemptLifecycle) { Objects.requireNonNull(action, "canonical StartSession action is required"); + Objects.requireNonNull(ownerAttemptLifecycle, "Game Session owner attempt lifecycle required"); requireActionBinding(action); requireOwner(reservationOwnerId, "reservationOwnerId"); requirePositive(reservationClaimFence, "reservationClaimFence"); - requireOwner(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); - requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); var preTuple = StartSessionPreAuthorizationReservationTuple.createHuman( @@ -165,6 +217,11 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( authorization.authorityEvidenceBundle(), sharedReference); + OwnerClaim ownerClaim = + Objects.requireNonNull( + ownerAttemptLifecycle.reserve(originalTuple), + "Game Session owner attempt reservation returned no claim"); + var redemption = withPeer( gameSessionPeerUri, @@ -176,9 +233,10 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( authorization.authorizationReferenceFingerprint(), reservationOwnerId, reservationClaimFence, - gameSessionOwnerAttemptId, - gameSessionOwnerFence))); + ownerClaim.ownerAttemptId(), + ownerClaim.ownerFence()))); assertThat(redemption.replay()).isFalse(); + ownerAttemptLifecycle.attachAccountRedemptionProjection(ownerClaim, originalTuple); var retained = accountSources.tx( @@ -189,8 +247,8 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( assertThat(retained.reservationOwnerId()).isEqualTo(reservationOwnerId); assertThat(retained.reservationClaimFence()).isEqualTo(reservationClaimFence); assertThat(retained.redemptionRedeemerWorkloadUri()).isEqualTo(gameSessionPeerUri); - assertThat(retained.redemptionOwnerAttemptId()).isEqualTo(gameSessionOwnerAttemptId); - assertThat(retained.redemptionOwnerFence()).isEqualTo(gameSessionOwnerFence); + assertThat(retained.redemptionOwnerAttemptId()).isEqualTo(ownerClaim.ownerAttemptId()); + assertThat(retained.redemptionOwnerFence()).isEqualTo(ownerClaim.ownerFence()); assertThat(retained.redemptionReferenceFingerprint()) .isEqualTo(authorization.authorizationReferenceFingerprint()); assertThat(retained.issuanceOperationId()).isNotNull(); @@ -217,8 +275,8 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( originalTuple, reservationOwnerId, reservationClaimFence, - gameSessionOwnerAttemptId, - gameSessionOwnerFence, + ownerClaim.ownerAttemptId(), + ownerClaim.ownerFence(), retained.issuanceOperationId(), retained.issuanceFence(), retained.referenceExpiresAt()); @@ -229,7 +287,7 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( worldParticipationAcquisitionService( OriginalStartSessionCurrentAttemptClient gameSessionClient) { Objects.requireNonNull( - gameSessionClient, "stipulated Game Session observation client required"); + gameSessionClient, "Game Session current-attempt observation client required"); return new AccountStartSessionWorldParticipationAcquisitionService( authorizationService, new AccountStartSessionWorldParticipationRepository(accountSources.dsl), @@ -254,6 +312,23 @@ public UUID creatorAccountId() { return accountSources.account.getAccountUuid(); } + /** Test-only lifecycle for an owner attempt without a dependency on the Game Session artifact. */ + public interface OwnerAttemptLifecycle { + OwnerClaim reserve(StartSessionPostAuthorizationExecutionTuple originalTuple); + + void attachAccountRedemptionProjection( + OwnerClaim ownerClaim, StartSessionPostAuthorizationExecutionTuple originalTuple); + } + + /** Non-secret owner identities needed by Account redemption and acquisition. */ + public record OwnerClaim(UUID ownerAttemptId, UUID ownerMutationId, long ownerFence) { + public OwnerClaim { + requireOwner(ownerAttemptId, "ownerAttemptId"); + requireOwner(ownerMutationId, "ownerMutationId"); + requirePositive(ownerFence, "ownerFence"); + } + } + private void assertPersistedCapture( StartSessionPreAuthorizationReservationTuple preTuple, UUID reservationOwnerId, @@ -374,7 +449,7 @@ private static Map captureSnapshot(AccountStartSessionAuthorityC } } - private StartSessionReservationEvidenceClient stipulatedLoggingClaimClient() { + private static StartSessionReservationEvidenceClient stipulatedLoggingClaimClient() { var client = mock(StartSessionReservationEvidenceClient.class); when(client.readCurrentClaimEvidence( any(StartSessionPreAuthorizationReservationTuple.class), diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java index da9bb63451..f21b6ecb50 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java @@ -46,7 +46,10 @@ public record Mutation( .filter(value -> value.revisionId().equals(revisionId)) .filter(value -> value.revisionOrder().equals(revisionOrder)) .findFirst() - .orElseThrow(); + .orElseThrow( + () -> + new IllegalArgumentException( + "Rule mutation does not match an original Game Design revision")); String expected; if (operation == OperationKind.UPSERT) { Objects.requireNonNull(definition); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredInitialActorCore.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredInitialActorCore.java new file mode 100644 index 0000000000..696fe36f8c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AuthoredInitialActorCore.java @@ -0,0 +1,48 @@ +package net.firedevops.firemud.common.publication; + +import java.util.LinkedHashMap; +import java.util.Map; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import tools.jackson.databind.JsonNode; + +/** Explicit game-authored initial actor facts, without runtime presence or platform defaults. */ +public record AuthoredInitialActorCore(String displayName, String dispositionKey) { + public AuthoredInitialActorCore { + if (displayName == null + || displayName.isBlank() + || !displayName.equals(displayName.strip()) + || displayName.codePointCount(0, displayName.length()) + > RealmEntryPolicy.MAX_DISPLAY_NAME_CODE_POINTS + || displayName.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("INVALID_ARGUMENT: authored actor displayName is invalid"); + } + GameplayRuleManifest.identifier(dispositionKey); + } + + static AuthoredInitialActorCore parse(JsonNode node) { + if (node == null || !node.isObject() || node.size() != 2) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: initialActorCore must contain exactly its schema fields"); + } + for (String field : new String[] {"displayName", "dispositionKey"}) { + if (!node.has(field)) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: initialActorCore " + field + " is required"); + } + } + JsonNode displayName = node.get("displayName"); + JsonNode dispositionKey = node.get("dispositionKey"); + if (!displayName.isTextual() || !dispositionKey.isTextual()) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: initialActorCore fields must be strings"); + } + return new AuthoredInitialActorCore(displayName.textValue(), dispositionKey.textValue()); + } + + public String canonicalJson() { + Map value = new LinkedHashMap<>(); + value.put("displayName", displayName); + value.put("dispositionKey", dispositionKey); + return GameplayRuleManifest.canonical(value); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java index c5bc8e38fa..e63b0ef044 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/RealmEntryPolicy.java @@ -22,10 +22,12 @@ public record RealmEntryPolicy( StateScope stateScope, EntryPolicy entryPolicy, PlayerCreationDescriptor creationDescriptor, + AuthoredInitialActorCore initialActorCore, String canonicalJson) { public static final String REVISION_KIND = "REALM_ENTRY_POLICY"; public static final int SCHEMA_VERSION = 1; public static final int PLAYER_CREATED_SCHEMA_VERSION = 2; + public static final int AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION = 3; public static final int MAX_JSON_BYTES = 4096; public static final int MAX_SLUG_LENGTH = 64; public static final int MAX_DISPLAY_NAME_CODE_POINTS = 128; @@ -53,6 +55,19 @@ public record RealmEntryPolicy( "stateScope", "entryPolicy", "creationDescriptor"); + private static final Set V3_FIELDS = + Set.of( + "schemaVersion", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "visible", + "publicProduction", + "stateScope", + "entryPolicy", + "creationDescriptor", + "initialActorCore"); private static final Pattern SLUG_PATTERN = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); public RealmEntryPolicy { @@ -60,13 +75,24 @@ public record RealmEntryPolicy( Objects.requireNonNull(entryPolicy, "entryPolicy"); Objects.requireNonNull(canonicalJson, "canonicalJson"); if (schemaVersion == SCHEMA_VERSION) { - if (entryPolicy != EntryPolicy.PRESEEDED_ONLY || creationDescriptor != null) { + if (entryPolicy != EntryPolicy.PRESEEDED_ONLY + || creationDescriptor != null + || initialActorCore != null) { throw invalid("schemaVersion 1 requires PRESEEDED_ONLY without a descriptor"); } } else if (schemaVersion == PLAYER_CREATED_SCHEMA_VERSION) { - if (entryPolicy != EntryPolicy.PLAYER_CREATED || creationDescriptor == null) { + if (entryPolicy != EntryPolicy.PLAYER_CREATED + || creationDescriptor == null + || initialActorCore != null) { throw invalid("schemaVersion 2 requires PLAYER_CREATED with a descriptor"); } + } else if (schemaVersion == AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION) { + if (entryPolicy != EntryPolicy.PLAYER_CREATED + || creationDescriptor == null + || initialActorCore == null) { + throw invalid( + "schemaVersion 3 requires PLAYER_CREATED with a descriptor and initialActorCore"); + } } else { throw invalid("schemaVersion is unsupported"); } @@ -118,6 +144,7 @@ public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { switch (version) { case SCHEMA_VERSION -> V1_FIELDS; case PLAYER_CREATED_SCHEMA_VERSION -> V2_FIELDS; + case AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION -> V3_FIELDS; default -> throw invalid("schemaVersion is unsupported"); }; for (String field : fields) { @@ -139,13 +166,17 @@ public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { if (version == SCHEMA_VERSION && entryPolicy != EntryPolicy.PRESEEDED_ONLY) { throw invalid("schemaVersion 1 supports only PRESEEDED_ONLY"); } - if (version == PLAYER_CREATED_SCHEMA_VERSION && entryPolicy != EntryPolicy.PLAYER_CREATED) { - throw invalid("schemaVersion 2 supports only PLAYER_CREATED"); + if (version >= PLAYER_CREATED_SCHEMA_VERSION && entryPolicy != EntryPolicy.PLAYER_CREATED) { + throw invalid("schemaVersion " + version + " supports only PLAYER_CREATED"); } PlayerCreationDescriptor creationDescriptor = - version == PLAYER_CREATED_SCHEMA_VERSION + version >= PLAYER_CREATED_SCHEMA_VERSION ? PlayerCreationDescriptor.parse(root.get("creationDescriptor").toString()) : null; + AuthoredInitialActorCore initialActorCore = + version == AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION + ? AuthoredInitialActorCore.parse(root.get("initialActorCore")) + : null; return new RealmEntryPolicy( version, @@ -158,6 +189,7 @@ public static RealmEntryPolicy parse(String json, ObjectMapper objectMapper) { stateScope, entryPolicy, creationDescriptor, + initialActorCore, canonicalJson); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClient.java index 3f306a6075..ee6e3173d5 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClient.java @@ -15,7 +15,9 @@ 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.common.world.CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstancePreparationServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Explicit file-backed mTLS client for the unregistered canonical World preparation RPC. */ public final class CanonicalWorldInstancePreparationClient @@ -59,13 +61,19 @@ public synchronized void init() throws SSLException, IOException { initialized = true; } - /** - * Sends the exact committed association selector and validates World-owned lifecycle readback. - */ + /** Sends the exact owner operation outside SQL and validates the full request/readback echo. */ public WorldCanonicalInstanceLifecycleEvidence prepare( - Request request, WorldCanonicalInstanceLifecycleEvidence.Request expectedLifecycleRequest) { + Request request, + OriginalOperationInput operationInput, + WorldCanonicalInstanceLifecycleEvidence.Request expectedLifecycleRequest) { Objects.requireNonNull(request, "request"); + Objects.requireNonNull(operationInput, "operationInput"); Objects.requireNonNull(expectedLifecycleRequest, "expectedLifecycleRequest"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical World preparation must acquire Account participation outside SQL"); + } if (!workloadNamespace.equals(request.targetNamespace()) || !workloadNamespace.equals(expectedLifecycleRequest.targetNamespace())) { throw new IllegalArgumentException( @@ -77,10 +85,10 @@ public WorldCanonicalInstanceLifecycleEvidence prepare( requireStub() .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .prepareCanonicalWorldInstance( - CanonicalWorldInstancePreparationGrpcCodec.toRequest(request)); + CanonicalWorldInstancePreparationGrpcCodec.toRequest(request, operationInput)); try { return CanonicalWorldInstancePreparationGrpcCodec.fromResponse( - request, expectedLifecycleRequest, response); + request, operationInput, expectedLifecycleRequest, response); } catch (IllegalArgumentException invalid) { throw new IllegalStateException( "World returned invalid canonical instance preparation evidence", invalid); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodec.java index 710bf4adc7..58dc492699 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodec.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.common.world; +import com.google.protobuf.ByteString; import com.google.protobuf.Descriptors; import com.google.protobuf.Message; import java.util.List; @@ -35,6 +36,24 @@ public static PrepareCanonicalWorldInstanceRequest toRequest(Request request) { .build(); } + /** Encodes the separate exact original owner operation without caller-supplied Account proof. */ + public static PrepareCanonicalWorldInstanceRequest toRequest( + Request request, OriginalOperationInput operationInput) { + Objects.requireNonNull(operationInput, "operationInput"); + return toRequest(request).toBuilder() + .setOriginalStartSessionOperation( + net.firedevops.firemud.worldmanagement.v1.OriginalStartSessionOperationInput + .newBuilder() + .setOriginalPostAuthorizationTuple( + ByteString.copyFrom(operationInput.originalPostAuthorizationTuple())) + .setGameSessionOwnerMutationId( + operationInput.gameSessionOwnerMutationId().toString()) + .setGameSessionOwnerAttemptId(operationInput.gameSessionOwnerAttemptId().toString()) + .setGameSessionOwnerFence(operationInput.gameSessionOwnerFence()) + .build()) + .build(); + } + /** Decodes the exact selector through the existing validated Game Session request value. */ public static Request fromRequest(PrepareCanonicalWorldInstanceRequest request) { Objects.requireNonNull(request, "request"); @@ -52,6 +71,22 @@ public static Request fromRequest(PrepareCanonicalWorldInstanceRequest request) request.getExpectedReleaseAttestationEvidenceDigest()); } + /** Decodes only the bounded original operation; it does not authenticate the peer or Account. */ + public static OriginalOperationInput fromOriginalOperationRequest( + PrepareCanonicalWorldInstanceRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "PrepareCanonicalWorldInstanceRequest"); + if (!request.hasOriginalStartSessionOperation()) { + throw new IllegalArgumentException("Exact original StartSession owner operation is required"); + } + var operation = request.getOriginalStartSessionOperation(); + return new OriginalOperationInput( + operation.getOriginalPostAuthorizationTuple().toByteArray(), + parseCanonicalNonNilUuid(operation.getGameSessionOwnerMutationId(), "ownerMutationId"), + parseCanonicalNonNilUuid(operation.getGameSessionOwnerAttemptId(), "ownerAttemptId"), + operation.getGameSessionOwnerFence()); + } + /** * Encodes lifecycle evidence only when its inner request and complete pair match the selector. */ @@ -68,6 +103,23 @@ public static PrepareCanonicalWorldInstanceResponse toResponse( .build(); } + /** Response echo preserving both the outer selector and exact original owner operation. */ + public static PrepareCanonicalWorldInstanceResponse toResponse( + Request request, + OriginalOperationInput operationInput, + WorldCanonicalInstanceLifecycleEvidence evidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(operationInput, "operationInput"); + Objects.requireNonNull(evidence, "evidence"); + requireSameBinding(request, evidence.request(), evidence); + ReadWorldCanonicalInstanceLifecycleResponse lifecycle = + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(evidence.request(), evidence); + return PrepareCanonicalWorldInstanceResponse.newBuilder() + .setRequest(toRequest(request, operationInput)) + .setLifecycle(lifecycle) + .build(); + } + /** Validates the exact outer echo and the complete inner lifecycle owner snapshot. */ public static WorldCanonicalInstanceLifecycleEvidence fromResponse( Request request, @@ -83,6 +135,10 @@ public static WorldCanonicalInstanceLifecycleEvidence fromResponse( if (!response.hasRequest()) { throw new IllegalArgumentException("Canonical World preparation request echo is required"); } + if (response.getRequest().hasOriginalStartSessionOperation()) { + throw new IllegalArgumentException( + "Canonical World owner operation must be supplied for exact response validation"); + } if (!response.hasLifecycle()) { throw new IllegalArgumentException("Canonical World lifecycle response is required"); } @@ -100,6 +156,73 @@ public static WorldCanonicalInstanceLifecycleEvidence fromResponse( return evidence; } + /** Validates the exact selector and original-operation request echo before lifecycle decode. */ + public static WorldCanonicalInstanceLifecycleEvidence fromResponse( + Request request, + OriginalOperationInput operationInput, + WorldCanonicalInstanceLifecycleEvidence.Request expectedLifecycleRequest, + PrepareCanonicalWorldInstanceResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(operationInput, "operationInput"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "PrepareCanonicalWorldInstanceResponse"); + if (response.hasError() || !response.hasRequest() || !response.hasLifecycle()) { + throw new IllegalArgumentException( + "Canonical World preparation response must echo the request and lifecycle"); + } + if (!toRequest(request, operationInput).equals(response.getRequest())) { + throw new IllegalArgumentException( + "World changed the exact canonical preparation owner operation"); + } + return fromResponse( + request, + expectedLifecycleRequest, + response.toBuilder().setRequest(toRequest(request)).build()); + } + + /** Closed operation fields supplied by Game Session; Account proof is never accepted here. */ + public static final class OriginalOperationInput { + private final byte[] originalPostAuthorizationTuple; + private final UUID gameSessionOwnerMutationId; + private final UUID gameSessionOwnerAttemptId; + private final long gameSessionOwnerFence; + + public OriginalOperationInput( + byte[] originalPostAuthorizationTuple, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence) { + Objects.requireNonNull(originalPostAuthorizationTuple, "originalPostAuthorizationTuple"); + if (originalPostAuthorizationTuple.length == 0 + || originalPostAuthorizationTuple.length > 262_144) { + throw new IllegalArgumentException("Original StartSession tuple is empty or oversized"); + } + this.originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + this.gameSessionOwnerMutationId = Objects.requireNonNull(gameSessionOwnerMutationId); + this.gameSessionOwnerAttemptId = Objects.requireNonNull(gameSessionOwnerAttemptId); + if (gameSessionOwnerFence <= 0L) { + throw new IllegalArgumentException("Game Session owner fence must be positive"); + } + this.gameSessionOwnerFence = gameSessionOwnerFence; + } + + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + public UUID gameSessionOwnerMutationId() { + return gameSessionOwnerMutationId; + } + + public UUID gameSessionOwnerAttemptId() { + return gameSessionOwnerAttemptId; + } + + public long gameSessionOwnerFence() { + return gameSessionOwnerFence; + } + } + private static void requireSameBinding( Request request, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java new file mode 100644 index 0000000000..45b8a878dd --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java @@ -0,0 +1,193 @@ +package net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class OriginalStartSessionCurrentAttemptEvidenceTest { + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID MUTATION = uuid("03333333-3333-4333-8333-333333333333"); + + @Test + void requestAndResultRetainExactOriginalBytesWithDefensiveCopies() { + StartSessionPostAuthorizationExecutionTuple tuple = CurrentAttemptTestData.tuple(); + byte[] tupleBytes = tuple.canonicalBytes(); + Request request = new Request(READ_ID, "world-runtime", tupleBytes, ATTEMPT, MUTATION, 8L); + tupleBytes[0] ^= 0x7f; + byte[] projection = + "exact-account-projection".getBytes(java.nio.charset.StandardCharsets.UTF_8); + Result result = + new Result(request, java.time.Instant.parse("2030-01-01T00:00:00Z"), projection); + projection[0] ^= 0x7f; + + assertThat(request.canonicalPostAuthorizationTuple()).containsExactly(tuple.canonicalBytes()); + assertThat(request.originalTuple().canonicalBytes()).containsExactly(tuple.canonicalBytes()); + assertThat(result.accountRedemptionProjection()) + .containsExactly( + "exact-account-projection".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + assertThat(result.accountRedemptionProjectionDigest()) + .isEqualTo( + OriginalStartSessionCurrentAttemptEvidence.projectionDigest( + "exact-account-projection".getBytes(java.nio.charset.StandardCharsets.UTF_8))); + assertThat(result.phaseState()) + .isEqualTo(OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE); + } + + @Test + void rejectsChangedNamespaceNilCorrelationAttemptMutationAndNonpositiveFence() { + byte[] tuple = CurrentAttemptTestData.tuple().canonicalBytes(); + assertThatThrownBy(() -> new Request(READ_ID, "other-runtime", tuple, ATTEMPT, MUTATION, 8L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact requested namespace"); + assertThatThrownBy( + () -> new Request(new UUID(0L, 0L), "world-runtime", tuple, ATTEMPT, MUTATION, 8L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new Request(READ_ID, "world-runtime", tuple, new UUID(0L, 0L), MUTATION, 8L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new Request(READ_ID, "world-runtime", tuple, ATTEMPT, new UUID(0L, 0L), 8L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Request(READ_ID, "world-runtime", tuple, ATTEMPT, MUTATION, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive"); + assertThatThrownBy( + () -> + new Result( + new Request(READ_ID, "world-runtime", tuple, ATTEMPT, MUTATION, 8L), + java.time.Instant.EPOCH, + new byte[0])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("projection"); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} + +/** Shared same-package tuple fixture for the two focused codec/model tests. */ +final class CurrentAttemptTestData { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private CurrentAttemptTestData() {} + + static StartSessionPostAuthorizationExecutionTuple tuple() { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "current-attempt-test", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBundle(pre), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = TENANT.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredInitialActorCoreTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredInitialActorCoreTest.java new file mode 100644 index 0000000000..4a45c3bfa5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredInitialActorCoreTest.java @@ -0,0 +1,42 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.json.JsonMapper; + +class AuthoredInitialActorCoreTest { + private static final JsonMapper JSON = + JsonMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build(); + + @Test + void parsesOnlyExplicitDisplayNameAndDispositionKey() throws Exception { + var core = + AuthoredInitialActorCore.parse( + JSON.readTree("{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}")); + + assertThat(core).isEqualTo(new AuthoredInitialActorCore("Wayfarer", "newcomer")); + assertThat(core.canonicalJson()) + .isEqualTo("{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}"); + } + + @Test + void rejectsPresenceAndEveryUnknownMissingOrInvalidCoreField() { + for (String invalid : + new String[] { + "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\",\"presence\":\"OFFLINE\"}", + "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\",\"unknown\":true}", + "{\"displayName\":\"Wayfarer\"}", + "{\"displayName\":\" Wayfarer\",\"dispositionKey\":\"newcomer\"}", + "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"not valid\"}", + "{\"displayName\":\"Other\",\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}" + }) { + assertThatThrownBy(() -> AuthoredInitialActorCore.parse(JSON.readTree(invalid))) + .isInstanceOf(RuntimeException.class); + } + assertThatThrownBy(() -> new AuthoredInitialActorCore("Wayfarer", "not valid")) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java index 0381260b77..54b613772d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java @@ -38,6 +38,14 @@ void preservesV1CanonicalBytesAndPreseededPolicyResult() { void parsesV2PlayerCreatedPolicyAndDescriptorRoundTrip() { var parsed = RealmEntryPolicy.parse(policy(2, "PLAYER_CREATED", descriptor()), JSON); var descriptor = parsed.creationDescriptor(); + String expected = + "{\"creationDescriptor\":{" + + descriptorCanonicalFields() + + "}," + + "\"entryPolicy\":\"PLAYER_CREATED\",\"publicProduction\":true," + + "\"realmDisplayName\":\"Realm\",\"realmSlug\":\"realm\"," + + "\"schemaVersion\":2,\"stateScope\":\"SHARED\",\"visible\":true," + + "\"worldDisplayName\":\"World\",\"worldSlug\":\"world\"}"; assertThat(parsed.schemaVersion()).isEqualTo(RealmEntryPolicy.PLAYER_CREATED_SCHEMA_VERSION); assertThat(parsed.entryPolicy()).isEqualTo(EntryPolicy.PLAYER_CREATED); @@ -47,9 +55,81 @@ void parsesV2PlayerCreatedPolicyAndDescriptorRoundTrip() { assertThat(descriptor.descriptorRevisionId()).isEqualTo(REVISION_ID); assertThat(descriptor.inputKind()).isEqualTo(PlayerCreationDescriptor.INPUT_KIND); assertThat(descriptor.dependencies()).isEmpty(); + assertThat(parsed.canonicalJson()).isEqualTo(expected); + assertThat(parsed.canonicalJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(expected.getBytes(StandardCharsets.UTF_8)); assertThat(RealmEntryPolicy.parseCanonical(parsed.canonicalJson(), JSON)).isEqualTo(parsed); } + @Test + void parsesV3InitialActorCoreWithoutChangingRetainedV1OrV2Bytes() { + String source = + policy(3, "PLAYER_CREATED", descriptor()) + .replace( + "\"entryPolicy\":\"PLAYER_CREATED\"", + "\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}"); + var parsed = RealmEntryPolicy.parse(source, JSON); + String expected = + "{\"creationDescriptor\":{" + + descriptorCanonicalFields() + + "}," + + "\"entryPolicy\":\"PLAYER_CREATED\"," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}," + + "\"publicProduction\":true,\"realmDisplayName\":\"Realm\"," + + "\"realmSlug\":\"realm\",\"schemaVersion\":3," + + "\"stateScope\":\"SHARED\",\"visible\":true," + + "\"worldDisplayName\":\"World\",\"worldSlug\":\"world\"}"; + + assertThat(parsed.schemaVersion()) + .isEqualTo(RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION); + assertThat(parsed.initialActorCore()) + .isEqualTo(new AuthoredInitialActorCore("Wayfarer", "newcomer")); + assertThat(parsed.initialActorCore().canonicalJson()) + .isEqualTo("{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}"); + assertThat(parsed.canonicalJson()).isEqualTo(expected); + assertThat(RealmEntryPolicy.parseCanonical(parsed.canonicalJson(), JSON)).isEqualTo(parsed); + + assertThat(RealmEntryPolicy.parse(policy(1, "PRESEEDED_ONLY", null), JSON).canonicalJson()) + .isEqualTo( + "{\"entryPolicy\":\"PRESEEDED_ONLY\",\"publicProduction\":true," + + "\"realmDisplayName\":\"Realm\",\"realmSlug\":\"realm\"," + + "\"schemaVersion\":1,\"stateScope\":\"SHARED\",\"visible\":true," + + "\"worldDisplayName\":\"World\",\"worldSlug\":\"world\"}"); + assertThat( + RealmEntryPolicy.parse(policy(2, "PLAYER_CREATED", descriptor()), JSON).canonicalJson()) + .doesNotContain("initialActorCore"); + } + + @Test + void rejectsOpenDuplicateMissingAndMalformedSchema3ActorCoreFields() { + String valid = + policy(3, "PLAYER_CREATED", descriptor()) + .replace( + "\"entryPolicy\":\"PLAYER_CREATED\"", + "\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}"); + for (String invalid : + List.of( + valid.replace("\"visible\":true", "\"visible\":true,\"presence\":\"OFFLINE\""), + valid.replace( + "\"initialActorCore\":{", "\"initialActorCore\":{\"presence\":\"OFFLINE\","), + valid.replace( + "\"dispositionKey\":\"newcomer\"", + "\"unknown\":true,\"dispositionKey\":\"newcomer\""), + valid.replace(",\"dispositionKey\":\"newcomer\"", ""), + valid.replace("\"displayName\":\"Wayfarer\"", "\"displayName\":\" Wayfarer\""), + valid.replace("\"dispositionKey\":\"newcomer\"", "\"dispositionKey\":\"not valid\""), + valid.replace( + "\"initialActorCore\":{", + "\"initialActorCore\":{\"displayName\":\"Other\",\"displayName\":\"Wayfarer\","), + policy(3, "PLAYER_CREATED", descriptor()))) { + assertInvalid(invalid); + } + assertInvalid(valid.replace("\"schemaVersion\":3", "\"schemaVersion\":2")); + assertInvalid( + valid.replace("\"entryPolicy\":\"PLAYER_CREATED\"", "\"entryPolicy\":\"PRESEEDED_ONLY\"")); + assertInvalid(valid.replace("\"creationDescriptor\":", "\"creationDescriptor\":null,")); + } + @Test void descriptorSubstitutionChangesPolicyBytesAndDescriptorDigest() { var original = RealmEntryPolicy.parse(policy(2, "PLAYER_CREATED", descriptor()), JSON); @@ -132,6 +212,7 @@ void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { StateScope.SHARED, EntryPolicy.PLAYER_CREATED, null, + null, "{}")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( @@ -147,6 +228,7 @@ void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { StateScope.SHARED, EntryPolicy.PRESEEDED_ONLY, PlayerCreationDescriptor.parse(descriptor()), + null, "{}")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( @@ -162,6 +244,7 @@ void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { StateScope.SHARED, EntryPolicy.PRESEEDED_ONLY, null, + null, "{}")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( @@ -177,6 +260,7 @@ void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { StateScope.SHARED, EntryPolicy.PLAYER_CREATED, null, + null, "{}")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( @@ -192,6 +276,7 @@ void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { StateScope.SHARED, EntryPolicy.PRESEEDED_ONLY, null, + null, "{}")) .isInstanceOf(IllegalArgumentException.class); } @@ -243,6 +328,14 @@ private static String descriptor() { + "\",\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}"; } + private static String descriptorCanonicalFields() { + return "\"dependencies\":[],\"descriptorId\":\"" + + DESCRIPTOR_ID + + "\",\"descriptorRevisionId\":\"" + + REVISION_ID + + "\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1"; + } + private static String padToLimit(String input, int bytes) { return " ".repeat(bytes - input.getBytes(StandardCharsets.UTF_8).length) + input; } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java index 48fd34429d..0af4157c23 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java @@ -40,6 +40,7 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput; import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.PrepareCanonicalWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstancePreparationServiceGrpc; @@ -47,6 +48,7 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Physical socket proof with a transport-only World double, not owner/database proof. */ class CanonicalWorldInstancePreparationClientMtlsTest { @@ -90,17 +92,33 @@ void stopTransport() throws Exception { void exactWorldPeerReturnsCompleteV2LifecycleReadback() throws Exception { WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); Request request = request(evidence); - startServer(pki.worldManagementServer(), request, response(request, evidence)); + var operationInput = originalOperationInput(); + startServer( + pki.worldManagementServer(), + request, + operationInput, + response(request, operationInput, evidence)); client = newClient(server); - assertThatThrownBy(() -> client.prepare(request, evidence.request())) + assertThatThrownBy(() -> client.prepare(request, operationInput, evidence.request())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); assertThat(headers).hasValue(0); assertThat(bodies).hasValue(0); client.init(); - var prepared = client.prepare(request, evidence.request()); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.prepare(request, operationInput, evidence.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside SQL"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + + var prepared = client.prepare(request, operationInput, evidence.request()); assertThat(prepared).isEqualTo(evidence); assertThat(prepared.launchBinding().releaseAttestation().schemaVersion()) .isEqualTo(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); @@ -111,7 +129,7 @@ void exactWorldPeerReturnsCompleteV2LifecycleReadback() throws Exception { assertThat(bodies).hasValue(1); client.close(); - assertThatThrownBy(() -> client.prepare(request, evidence.request())) + assertThatThrownBy(() -> client.prepare(request, operationInput, evidence.request())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); assertThat(headers).hasValue(1); @@ -122,11 +140,12 @@ void exactWorldPeerReturnsCompleteV2LifecycleReadback() throws Exception { void trustedWrongWorkloadOrNamespaceReleasesNoRequestHeadersOrBody() throws Exception { WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); Request request = request(evidence); + var operationInput = originalOperationInput(); for (TestIdentity identity : List.of(pki.wrongWorkloadServer(), pki.otherNamespaceServer())) { - startServer(identity, request, response(request, evidence)); + startServer(identity, request, operationInput, response(request, operationInput, evidence)); client = newClient(server); client.init(); - assertThatThrownBy(() -> client.prepare(request, evidence.request())) + assertThatThrownBy(() -> client.prepare(request, operationInput, evidence.request())) .isInstanceOf(StatusRuntimeException.class) .satisfies( exception -> @@ -142,7 +161,8 @@ void trustedWrongWorkloadOrNamespaceReleasesNoRequestHeadersOrBody() throws Exce void rejectsChangedOuterAndInnerReadbackOverTheSocket() throws Exception { WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); Request request = request(evidence); - PrepareCanonicalWorldInstanceResponse valid = response(request, evidence); + var operationInput = originalOperationInput(); + PrepareCanonicalWorldInstanceResponse valid = response(request, operationInput, evidence); List changedResponses = List.of( valid.toBuilder() @@ -160,10 +180,10 @@ void rejectsChangedOuterAndInnerReadbackOverTheSocket() throws Exception { .build()); for (PrepareCanonicalWorldInstanceResponse changedResponse : changedResponses) { - startServer(pki.worldManagementServer(), request, changedResponse); + startServer(pki.worldManagementServer(), request, operationInput, changedResponse); client = newClient(server); client.init(); - assertThatThrownBy(() -> client.prepare(request, evidence.request())) + assertThatThrownBy(() -> client.prepare(request, operationInput, evidence.request())) .isInstanceOf(IllegalStateException.class) .hasRootCauseInstanceOf(IllegalArgumentException.class); assertThat(headers).hasValue(1); @@ -177,7 +197,12 @@ void rejectsUnsafeTlsAndMismatchedSelectorsBeforeSending(@TempDir Path directory throws Exception { WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); Request request = request(evidence); - startServer(pki.worldManagementServer(), request, response(request, evidence)); + var operationInput = originalOperationInput(); + startServer( + pki.worldManagementServer(), + request, + operationInput, + response(request, operationInput, evidence)); var plaintext = pki.clientProperties(directory); plaintext.setPlaintext(true); @@ -216,26 +241,27 @@ void rejectsUnsafeTlsAndMismatchedSelectorsBeforeSending(@TempDir Path directory .hasMessageContaining("existing readable file"); client = newClient(server); - assertThatThrownBy(() -> client.prepare(request, evidence.request())) + assertThatThrownBy(() -> client.prepare(request, operationInput, evidence.request())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); client.init(); Request otherNamespaceRequest = copyAssociationRequest(request, "other-test"); - assertThatThrownBy(() -> client.prepare(otherNamespaceRequest, evidence.request())) + assertThatThrownBy( + () -> client.prepare(otherNamespaceRequest, operationInput, evidence.request())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("configured workload namespace"); var differentLifecycleRequest = copyLifecycleRequest(evidence.request(), uuid("99999999-9999-4999-8999-999999999999")); - assertThatThrownBy(() -> client.prepare(request, differentLifecycleRequest)) + assertThatThrownBy(() -> client.prepare(request, operationInput, differentLifecycleRequest)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("expected World lifecycle request"); assertThat(headers).hasValue(0); assertThat(bodies).hasValue(0); client.close(); - assertThatThrownBy(() -> client.prepare(request, evidence.request())) + assertThatThrownBy(() -> client.prepare(request, operationInput, evidence.request())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); assertThat(headers).hasValue(0); @@ -245,6 +271,7 @@ void rejectsUnsafeTlsAndMismatchedSelectorsBeforeSending(@TempDir Path directory private void startServer( TestIdentity identity, Request expectedRequest, + OriginalOperationInput expectedOperationInput, PrepareCanonicalWorldInstanceResponse response) throws Exception { headers = new AtomicInteger(); @@ -260,6 +287,16 @@ public void prepareCanonicalWorldInstance( assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(GAME_SESSION_CLIENT_URI); assertThat(CanonicalWorldInstancePreparationGrpcCodec.fromRequest(wire)) .isEqualTo(expectedRequest); + OriginalOperationInput receivedOperationInput = + CanonicalWorldInstancePreparationGrpcCodec.fromOriginalOperationRequest(wire); + assertThat(receivedOperationInput.originalPostAuthorizationTuple()) + .containsExactly(expectedOperationInput.originalPostAuthorizationTuple()); + assertThat(receivedOperationInput.gameSessionOwnerMutationId()) + .isEqualTo(expectedOperationInput.gameSessionOwnerMutationId()); + assertThat(receivedOperationInput.gameSessionOwnerAttemptId()) + .isEqualTo(expectedOperationInput.gameSessionOwnerAttemptId()); + assertThat(receivedOperationInput.gameSessionOwnerFence()) + .isEqualTo(expectedOperationInput.gameSessionOwnerFence()); observer.onNext(response); observer.onCompleted(); } @@ -298,8 +335,18 @@ private CanonicalWorldInstancePreparationClient newClient(Server target) throws } private static PrepareCanonicalWorldInstanceResponse response( - Request request, WorldCanonicalInstanceLifecycleEvidence evidence) { - return CanonicalWorldInstancePreparationGrpcCodec.toResponse(request, evidence); + Request request, + OriginalOperationInput operationInput, + WorldCanonicalInstanceLifecycleEvidence evidence) { + return CanonicalWorldInstancePreparationGrpcCodec.toResponse(request, operationInput, evidence); + } + + private static OriginalOperationInput originalOperationInput() { + return new OriginalOperationInput( + "synthetic original StartSession tuple".getBytes(StandardCharsets.UTF_8), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + 17L); } private static Request request(WorldCanonicalInstanceLifecycleEvidence evidence) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java index a3d3156a73..d41ff97633 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java @@ -21,15 +21,28 @@ class CanonicalWorldInstancePreparationGrpcCodecTest { void roundTripsV2LaunchBindingAndPreservesLargeLifecycleCounters() throws Exception { WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); Request request = request(evidence); + var originalOperation = originalOperation(); - var wireRequest = CanonicalWorldInstancePreparationGrpcCodec.toRequest(request); + var wireRequest = + CanonicalWorldInstancePreparationGrpcCodec.toRequest(request, originalOperation); assertThat(CanonicalWorldInstancePreparationGrpcCodec.fromRequest(wireRequest)) .isEqualTo(request); + var decodedOperation = + CanonicalWorldInstancePreparationGrpcCodec.fromOriginalOperationRequest(wireRequest); + assertThat(decodedOperation.originalPostAuthorizationTuple()) + .containsExactly((byte) 1, (byte) 2, (byte) 3); + assertThat(decodedOperation.gameSessionOwnerMutationId()) + .isEqualTo(originalOperation.gameSessionOwnerMutationId()); + assertThat(decodedOperation.gameSessionOwnerAttemptId()) + .isEqualTo(originalOperation.gameSessionOwnerAttemptId()); + assertThat(decodedOperation.gameSessionOwnerFence()) + .isEqualTo(originalOperation.gameSessionOwnerFence()); - var response = CanonicalWorldInstancePreparationGrpcCodec.toResponse(request, evidence); + var response = + CanonicalWorldInstancePreparationGrpcCodec.toResponse(request, originalOperation, evidence); var decoded = CanonicalWorldInstancePreparationGrpcCodec.fromResponse( - request, evidence.request(), response); + request, originalOperation, evidence.request(), response); assertThat(decoded).isEqualTo(evidence); assertThat(decoded.launchBinding().releaseAttestation().schemaVersion()) .isEqualTo(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); @@ -195,6 +208,47 @@ void requestDecoderUsesExistingCanonicalSelectorValidation() throws Exception { .hasMessageContaining("expectedDescriptorResultDigest"); } + @Test + void originalOperationIsRequiredAndEchoedExactlyForOwnerPreparation() throws Exception { + WorldCanonicalInstanceLifecycleEvidence lifecycle = evidence(); + Request request = request(lifecycle); + var operation = originalOperation(); + var wire = CanonicalWorldInstancePreparationGrpcCodec.toRequest(request, operation); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromOriginalOperationRequest( + CanonicalWorldInstancePreparationGrpcCodec.toRequest(request))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("original StartSession owner operation"); + + var changedOperation = + wire.toBuilder() + .setOriginalStartSessionOperation( + wire.getOriginalStartSessionOperation().toBuilder() + .setGameSessionOwnerFence(operation.gameSessionOwnerFence() + 1)) + .build(); + var changedResponse = + CanonicalWorldInstancePreparationGrpcCodec.toResponse(request, operation, lifecycle) + .toBuilder() + .setRequest(changedOperation) + .build(); + assertThatThrownBy( + () -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, operation, lifecycle.request(), changedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("owner operation"); + } + + private static CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput + originalOperation() { + return new CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput( + new byte[] {1, 2, 3}, + uuid("66666666-6666-4666-8666-666666666666"), + uuid("77777777-7777-4777-8777-777777777777"), + 31L); + } + private static Request request(WorldCanonicalInstanceLifecycleEvidence evidence) { var lifecycleRequest = evidence.request(); return new Request( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBinding.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBinding.java new file mode 100644 index 0000000000..c4a8a85854 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBinding.java @@ -0,0 +1,301 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.publication.AuthoredInitialActorCore; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; + +/** Exact source-only projection for an authored initial actor core in a selected release. */ +public final class AuthoredInitialActorCoreSourceBinding { + public static final String SCHEMA = "game-design-authored-initial-actor-core-source-binding/v1"; + + private final UUID worldSourceOperationId; + private final String worldSourceEvidenceDigest; + private final String expectedWorldSlug; + private final String publicationWorkflowId; + private final DraftCommitBinding selectedCommit; + private final RealmPolicySource.Policy policySource; + private final AuthoredInitialActorCore core; + private final GameplayRuleManifest gameplayManifest; + private final Disposition disposition; + private final Feedback safeFeedback; + private final byte[] canonicalBytes; + private final String digest; + + private AuthoredInitialActorCoreSourceBinding( + UUID worldSourceOperationId, + String worldSourceEvidenceDigest, + String expectedWorldSlug, + String publicationWorkflowId, + byte[] publicationOperationBytes, + byte[] publicationTerminalEvidenceBytes, + DraftCommitBinding selectedCommit, + byte[] policySnapshotBytes, + RealmPolicySource.Policy policySource, + byte[] gameplaySnapshotBytes, + GameplayRuleManifest gameplayManifest, + GameplayRuleSource.Entry dispositionEntry, + Disposition disposition, + GameplayRuleSource.Entry feedbackEntry, + Feedback safeFeedback) { + this.worldSourceOperationId = Objects.requireNonNull(worldSourceOperationId); + this.worldSourceEvidenceDigest = Objects.requireNonNull(worldSourceEvidenceDigest); + this.expectedWorldSlug = Objects.requireNonNull(expectedWorldSlug); + this.publicationWorkflowId = Objects.requireNonNull(publicationWorkflowId); + this.selectedCommit = Objects.requireNonNull(selectedCommit); + this.policySource = Objects.requireNonNull(policySource); + this.core = Objects.requireNonNull(policySource.policy().initialActorCore()); + this.gameplayManifest = Objects.requireNonNull(gameplayManifest); + this.disposition = Objects.requireNonNull(disposition); + this.safeFeedback = Objects.requireNonNull(safeFeedback); + + var target = selectedCommit.target(); + var policy = policySource.policy(); + var descriptor = Objects.requireNonNull(policy.creationDescriptor()); + if (new UUID(0L, 0L).equals(worldSourceOperationId) + || !worldSourceEvidenceDigest.matches("sha256:[0-9a-f]{64}") + || !RealmEntryPolicy.isCanonicalSlug(expectedWorldSlug) + || publicationWorkflowId.isBlank() + || publicationWorkflowId.length() > 256 + || policy.schemaVersion() != RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION + || !policy.worldSlug().equals(expectedWorldSlug) + || policySource.policy().initialActorCore() == null + || !core.dispositionKey().equals(disposition.dispositionKey()) + || !disposition.safeFeedbackKey().equals(safeFeedback.feedbackKey())) { + throw new IllegalArgumentException("Invalid authored initial actor core source binding"); + } + requireBytes(publicationOperationBytes, "selected publication operation"); + requireBytes(publicationTerminalEvidenceBytes, "selected publication terminal evidence"); + requireBytes(policySnapshotBytes, "selected policy source snapshot"); + requireBytes(gameplaySnapshotBytes, "selected GameplayRuleSource snapshot"); + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(output, SCHEMA); + DraftAuthorizationFenceBinding.frame(output, "1"); + DraftAuthorizationFenceBinding.frame(output, worldSourceOperationId.toString()); + DraftAuthorizationFenceBinding.frame(output, worldSourceEvidenceDigest); + DraftAuthorizationFenceBinding.frame(output, expectedWorldSlug); + DraftAuthorizationFenceBinding.frame(output, publicationWorkflowId); + DraftAuthorizationFenceBinding.frame(output, target.canonicalTenantId().toString()); + DraftAuthorizationFenceBinding.frame(output, target.canonicalVersionId().toString()); + DraftAuthorizationFenceBinding.frame(output, Long.toString(target.gameDesignVersionRowId())); + DraftAuthorizationFenceBinding.frame(output, target.gameDesignVersionTenantKey()); + DraftAuthorizationFenceBinding.frame(output, Long.toString(target.sourceGameRowId())); + DraftAuthorizationFenceBinding.frame(output, target.sourceGameTenantKey()); + DraftAuthorizationFenceBinding.frame(output, target.sourceProvenanceKind()); + DraftAuthorizationFenceBinding.frame(output, selectedCommit.commitId().toString()); + DraftAuthorizationFenceBinding.frame(output, selectedCommit.digest()); + DraftAuthorizationFenceBinding.frame(output, selectedCommit.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(output, publicationOperationBytes); + DraftAuthorizationFenceBinding.frame(output, publicationTerminalEvidenceBytes); + DraftAuthorizationFenceBinding.frame(output, policySnapshotBytes); + DraftAuthorizationFenceBinding.frame(output, policySource.commitId().toString()); + DraftAuthorizationFenceBinding.frame(output, policySource.revisionId().toString()); + DraftAuthorizationFenceBinding.frame(output, policySource.logicalRevisionId()); + DraftAuthorizationFenceBinding.frame( + output, policy.canonicalJson().getBytes(StandardCharsets.UTF_8)); + DraftAuthorizationFenceBinding.frame(output, descriptor.descriptorId().toString()); + DraftAuthorizationFenceBinding.frame(output, descriptor.descriptorRevisionId().toString()); + DraftAuthorizationFenceBinding.frame(output, descriptor.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(output, core.canonicalJson()); + DraftAuthorizationFenceBinding.frame(output, gameplaySnapshotBytes); + DraftAuthorizationFenceBinding.frame(output, gameplayManifest.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(output, disposition.dispositionKey()); + DraftAuthorizationFenceBinding.frame( + output, GameplayRuleManifest.canonical(disposition).getBytes(StandardCharsets.UTF_8)); + frameEntry(output, dispositionEntry); + DraftAuthorizationFenceBinding.frame(output, safeFeedback.feedbackKey()); + DraftAuthorizationFenceBinding.frame( + output, GameplayRuleManifest.canonical(safeFeedback).getBytes(StandardCharsets.UTF_8)); + frameEntry(output, feedbackEntry); + canonicalBytes = output.toByteArray(); + digest = CommandSource.sha256(canonicalBytes); + } + + /** + * Resolves schema-3 policies for the exact associated world from the already selected owner + * snapshots. Other worlds remain in the framed source snapshot but are not this association's + * actor core. The caller remains responsible for authenticated owner reads and exact release + * selection before calling this. + */ + public static List resolveAll( + UUID worldSourceOperationId, + String worldSourceEvidenceDigest, + String expectedWorldSlug, + String publicationWorkflowId, + byte[] publicationOperationBytes, + byte[] publicationTerminalEvidenceBytes, + DraftCommitBinding selectedCommit, + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot, + GameplayRuleSnapshot gameplaySnapshot) { + Objects.requireNonNull(selectedCommit, "selectedCommit"); + Objects.requireNonNull(policySnapshot, "policySnapshot"); + Objects.requireNonNull(gameplaySnapshot, "gameplaySnapshot"); + if (!RealmEntryPolicy.isCanonicalSlug(expectedWorldSlug)) { + throw new IllegalArgumentException("Exact selected world scope is required"); + } + if (!selectedCommit.equals(policySnapshot.binding())) { + throw new IllegalArgumentException("Policy source is not from the selected authored commit"); + } + requireBytes(publicationOperationBytes, "selected publication operation"); + requireBytes(publicationTerminalEvidenceBytes, "selected publication terminal evidence"); + byte[] policySnapshotBytes = policySnapshot.canonicalBytes(); + if (!Arrays.equals( + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot.fromStored( + new String(policySnapshotBytes, StandardCharsets.UTF_8)) + .canonicalBytes(), + policySnapshotBytes)) { + throw new IllegalArgumentException("Selected policy source snapshot bytes changed"); + } + + List authoredActorPolicies = + policySnapshot.policies().stream() + .filter(value -> value.policy().worldSlug().equals(expectedWorldSlug)) + .filter( + value -> + value.policy().schemaVersion() + == RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION) + .toList(); + if (authoredActorPolicies.isEmpty()) { + return List.of(); + } + + GameplayRuleSnapshot selectedGameplaySnapshot = + GameplayRuleSnapshot.fromStored(gameplaySnapshot.canonicalJson()); + if (!selectedCommit.equals(selectedGameplaySnapshot.binding()) + || !Arrays.equals( + selectedGameplaySnapshot.canonicalBytes(), gameplaySnapshot.canonicalBytes())) { + throw new IllegalArgumentException( + "GameplayRuleSource snapshot differs from the selected authored commit"); + } + byte[] gameplaySnapshotBytes = selectedGameplaySnapshot.canonicalBytes(); + List gameplayEntries = selectedGameplaySnapshot.entries(); + GameplayRuleManifest manifest = GameplayRuleSource.manifest(gameplayEntries); + + List result = + authoredActorPolicies.stream() + .map( + policy -> { + AuthoredInitialActorCore core = policy.policy().initialActorCore(); + List dispositions = + gameplayEntries.stream() + .filter(value -> value.family() == Family.DISPOSITIONS) + .filter(value -> value.definition().key().equals(core.dispositionKey())) + .toList(); + if (dispositions.size() != 1 + || !(dispositions.getFirst().definition() + instanceof Disposition disposition)) { + throw new IllegalArgumentException( + "Selected authored disposition is absent or ambiguous"); + } + List feedbackEntries = + gameplayEntries.stream() + .filter(value -> value.family() == Family.FEEDBACK) + .filter( + value -> + value.definition().key().equals(disposition.safeFeedbackKey())) + .toList(); + if (feedbackEntries.size() != 1 + || !(feedbackEntries.getFirst().definition() instanceof Feedback feedback)) { + throw new IllegalArgumentException( + "Disposition safeFeedbackKey is absent or ambiguous"); + } + return new AuthoredInitialActorCoreSourceBinding( + worldSourceOperationId, + worldSourceEvidenceDigest, + expectedWorldSlug, + publicationWorkflowId, + publicationOperationBytes, + publicationTerminalEvidenceBytes, + selectedCommit, + policySnapshotBytes, + policy, + gameplaySnapshotBytes, + manifest, + dispositions.getFirst(), + disposition, + feedbackEntries.getFirst(), + feedback); + }) + .toList(); + return List.copyOf(result); + } + + public UUID worldSourceOperationId() { + return worldSourceOperationId; + } + + public String worldSourceEvidenceDigest() { + return worldSourceEvidenceDigest; + } + + public String expectedWorldSlug() { + return expectedWorldSlug; + } + + public String publicationWorkflowId() { + return publicationWorkflowId; + } + + public DraftCommitBinding selectedCommit() { + return selectedCommit; + } + + public RealmPolicySource.Policy policySource() { + return policySource; + } + + public AuthoredInitialActorCore core() { + return core; + } + + public GameplayRuleManifest gameplayManifest() { + return gameplayManifest; + } + + public Disposition disposition() { + return disposition; + } + + public Feedback safeFeedback() { + return safeFeedback; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + private static void frameEntry(ByteArrayOutputStream output, GameplayRuleSource.Entry entry) { + DraftAuthorizationFenceBinding.frame(output, entry.family().name()); + DraftAuthorizationFenceBinding.frame( + output, + GameplayRuleManifest.canonical(entry.definition()).getBytes(StandardCharsets.UTF_8)); + DraftAuthorizationFenceBinding.frame(output, entry.sourceBinding().digest()); + DraftAuthorizationFenceBinding.frame(output, entry.sourceBinding().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(output, entry.revisionOrder()); + DraftAuthorizationFenceBinding.frame(output, entry.revisionId().toString()); + } + + private static void requireBytes(byte[] value, String label) { + if (value == null || value.length == 0) { + throw new IllegalArgumentException("Exact " + label + " bytes are required"); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java index 9a696bb553..f33a80ba30 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java @@ -377,7 +377,7 @@ private CapturedTemplate requireCapturedTemplate(Result exact, long templateId) if (entries.size() != 1) { throw conflict("Exact selected template is missing or duplicated in the committed capture"); } - GameLogicReceiptBinding gameLogicReceipt = requireSelectedGameLogicReceipt(operation); + SelectedGameplayRules selectedGameplayRules = requireSelectedGameLogicReceipt(operation); TemplateConfigSource.Entry entry = entries.getFirst(); if (!entry.config().baseVersionId().equals(exact.association().canonicalVersionId())) { throw conflict("Original captured template base differs from the pinned selected Version"); @@ -417,13 +417,60 @@ private CapturedTemplate requireCapturedTemplate(Result exact, long templateId) || !row.worldSlug().equals(publicAssociation.worldSlug())) { throw conflict("Retained association row differs from the public pinned association"); } - return new CapturedTemplate(unsupported, gameLogicReceipt); + CapturedTemplate capturedTemplate = + new CapturedTemplate( + unsupported, + selectedGameplayRules.receiptBinding(), + selection.selectedCommit(), + capture.policy().snapshot().shared(), + selectedGameplayRules.snapshot(), + operation.workflowId(), + operation.canonicalBytes(), + readback.terminalEvidenceBytes()); + try { + resolveSelectedAuthoredInitialActorCoreSources( + exact.association().sourceOperationId(), + exact.association().sourceEvidenceDigest(), + exact.association().worldSlug(), + capturedTemplate.publicationWorkflowId(), + capturedTemplate.publicationOperationBytes(), + capturedTemplate.publicationTerminalEvidenceBytes(), + capturedTemplate.selectedCommit(), + capturedTemplate.policySnapshot(), + capturedTemplate.gameplayRules()); + } catch (IllegalArgumentException invalidActorCoreSource) { + throw conflict("Selected authored initial actor core differs from exact published source"); + } + return capturedTemplate; + } + + static List resolveSelectedAuthoredInitialActorCoreSources( + UUID worldSourceOperationId, + String worldSourceEvidenceDigest, + String expectedWorldSlug, + String publicationWorkflowId, + byte[] publicationOperationBytes, + byte[] publicationTerminalEvidenceBytes, + net.firedevops.firemud.common.authoring.DraftCommitBinding selectedCommit, + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot, + GameplayRuleSnapshot gameplayRules) { + Objects.requireNonNull(gameplayRules, "gameplayRules"); + return AuthoredInitialActorCoreSourceBinding.resolveAll( + worldSourceOperationId, + worldSourceEvidenceDigest, + expectedWorldSlug, + publicationWorkflowId, + publicationOperationBytes, + publicationTerminalEvidenceBytes, + selectedCommit, + policySnapshot, + gameplayRules); } /** * Exact Game Logic receipt/source join already required by the selected-publication inventory. */ - private GameLogicReceiptBinding requireSelectedGameLogicReceipt( + private SelectedGameplayRules requireSelectedGameLogicReceipt( GameDesignPublicationOperation operation) { var selection = operation.account().input().selection(); var target = selection.target(); @@ -447,11 +494,13 @@ private GameLogicReceiptBinding requireSelectedGameLogicReceipt( selectedRules.canonicalBytes(), receipt.authorization().source().canonicalBytes())) { throw conflict("Retained Game Logic receipt differs from the exact selected source"); } - return new GameLogicReceiptBinding( - selection.intent().publishRequestId(), - selection.digest(), - receipt.authorization().digest(), - receipt.receipt().digest()); + return new SelectedGameplayRules( + selectedRules, + new GameLogicReceiptBinding( + selection.intent().publishRequestId(), + selection.digest(), + receipt.authorization().digest(), + receipt.receipt().digest())); } private void requireReleaseMatches( @@ -1077,9 +1126,49 @@ private record FrozenFailure(String code, String message) { } } - private record CapturedTemplate(String failureMessage, GameLogicReceiptBinding gameLogicReceipt) { + private record CapturedTemplate( + String failureMessage, + GameLogicReceiptBinding gameLogicReceipt, + net.firedevops.firemud.common.authoring.DraftCommitBinding selectedCommit, + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot, + GameplayRuleSnapshot gameplayRules, + String publicationWorkflowId, + byte[] publicationOperationBytes, + byte[] publicationTerminalEvidenceBytes) { private CapturedTemplate { Objects.requireNonNull(gameLogicReceipt, "gameLogicReceipt"); + Objects.requireNonNull(selectedCommit, "selectedCommit"); + Objects.requireNonNull(policySnapshot, "policySnapshot"); + Objects.requireNonNull(gameplayRules, "gameplayRules"); + Objects.requireNonNull(publicationWorkflowId, "publicationWorkflowId"); + publicationOperationBytes = + Objects.requireNonNull(publicationOperationBytes, "publicationOperationBytes").clone(); + publicationTerminalEvidenceBytes = + Objects.requireNonNull( + publicationTerminalEvidenceBytes, "publicationTerminalEvidenceBytes") + .clone(); + if (!selectedCommit.equals(policySnapshot.binding()) + || !selectedCommit.equals(gameplayRules.binding())) { + throw new IllegalArgumentException("Captured source differs from selected commit"); + } + } + + @Override + public byte[] publicationOperationBytes() { + return publicationOperationBytes.clone(); + } + + @Override + public byte[] publicationTerminalEvidenceBytes() { + return publicationTerminalEvidenceBytes.clone(); + } + } + + private record SelectedGameplayRules( + GameplayRuleSnapshot snapshot, GameLogicReceiptBinding receiptBinding) { + private SelectedGameplayRules { + Objects.requireNonNull(snapshot, "snapshot"); + Objects.requireNonNull(receiptBinding, "receiptBinding"); } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index d6993c6fdc..0cbf95860d 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -63,6 +63,7 @@ import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; @@ -109,6 +110,8 @@ import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeSourceReadClient; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -142,6 +145,7 @@ import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationClient; +import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput; import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; @@ -2696,6 +2700,15 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex ownerAttemptId, ownerFence); var startSessionTuple = originalStartSession.originalTuple(); + UUID stipulatedOwnerMutationId = UUID.randomUUID(); + UUID stipulatedOwnerReadRequestId = UUID.randomUUID(); + Instant stipulatedOwnerLeaseExpiry = Instant.now().plusSeconds(900L); + OriginalOperationInput stipulatedOwnerOperation = + new OriginalOperationInput( + startSessionTuple.canonicalBytes(), + stipulatedOwnerMutationId, + ownerAttemptId, + ownerFence); try (var projectionClient = new StartSessionRedeemedOperationProjectionClient( endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { @@ -3007,10 +3020,11 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex controlPlaneRequestId)) .containsExactlyElementsOf(completeBindingOwnerRowsBefore); - // This is a composed World materialization proof over the exact source, frozen graph, - // and complete released pair already retained above. Only the Game Session launch-row - // read and the original Account/continuously-held Game Session authorization are - // stipulated here; this fixture does not claim those authorities were genuine. + // World source, publication and released-pair proof above is genuine. The original + // StartSession tuple and issued owner attempt/fence below are genuine Account + // issue/redemption evidence; the later exact Game Session mutation observation and + // Account participation are stipulated and do not prove acquisition or a continuous + // remote lock. CompleteLaunchBindingEvidence completeLaunchEvidence = new CompleteLaunchBindingEvidence( completeBinding.descriptor(), completeBinding.releaseAttestation()); @@ -3083,14 +3097,28 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex worldPublicationProof.frozenTopologies(), stipulatedGameSessionReader, worldToGameDesignPreparationClient); - // The exact StartSession tuple and existing GS attempt/fence are preserved dynamically. - // Only Account participation/fence and the continuously held authority behavior are - // synthetic evidence shape; this does not authenticate either producer. + // Preserve the exact original tuple and issued Game Session attempt/fence. The owner + // mutation/current-attempt observation and Account participation are explicit + // synthetic downstream evidence; this remains a genuine publication/source/release + // proof, not genuine Account participation acquisition or continuous owner protection. var syntheticIdentities = new ConcurrentHashMap(); + UUID stipulatedParticipationId = UUID.randomUUID(); + long stipulatedParticipationFence = + ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); var stipulatedHeldAuthority = - (WorldCanonicalInstancePreparationService.CommitAuthorityVerifier) - input -> { + (WorldCanonicalInstancePreparationService.OriginalOperationCommitAuthorityVerifier) + (input, operationInput) -> { + if (!MessageDigest.isEqual( + startSessionTuple.canonicalBytes(), + operationInput.originalPostAuthorizationTuple()) + || !stipulatedOwnerMutationId.equals( + operationInput.gameSessionOwnerMutationId()) + || !ownerAttemptId.equals(operationInput.gameSessionOwnerAttemptId()) + || ownerFence != operationInput.gameSessionOwnerFence()) { + throw new SecurityException( + "Synthetic downstream operation differs from genuine issued StartSession evidence"); + } String exactInputJson; try { exactInputJson = canonicalPreparationInputJson(input); @@ -3102,15 +3130,38 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex WorldCanonicalInstanceExecutionIdentity identity = syntheticIdentities.computeIfAbsent( exactInputJson, - ignored -> - new WorldCanonicalInstanceExecutionIdentity( - startSessionTuple.canonicalBytes(), - UUID.randomUUID(), - ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE), - ownerAttemptId, - ownerFence, - input.canonicalGameInstanceId(), - exactInputJson)); + ignored -> { + var observationRequest = + new OriginalStartSessionCurrentAttemptEvidence.Request( + stipulatedOwnerReadRequestId, + NAMESPACE, + startSessionTuple.canonicalBytes(), + ownerAttemptId, + stipulatedOwnerMutationId, + ownerFence); + var observation = + new OriginalStartSessionCurrentAttemptEvidence.Result( + observationRequest, + stipulatedOwnerLeaseExpiry, + StartSessionAccountRedemptionProjection.fromOriginalTuple( + startSessionTuple)); + byte[] observationBytes = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + observation) + .toByteArray(); + return new WorldCanonicalInstanceExecutionIdentity( + startSessionTuple.canonicalBytes(), + stipulatedParticipationId, + stipulatedParticipationFence, + stipulatedOwnerMutationId, + ownerAttemptId, + ownerFence, + observation, + input.canonicalGameInstanceId(), + exactInputJson, + observationBytes); + }); + identity.requireMatches(input, operationInput, exactInputJson); return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { private boolean held = true; @@ -3168,7 +3219,9 @@ public void close() { assertThatThrownBy( () -> wrongWorkloadPreparationClient.prepare( - preparationAssociationRequest, expectedLifecycleRequest)) + preparationAssociationRequest, + stipulatedOwnerOperation, + expectedLifecycleRequest)) .isInstanceOf(io.grpc.StatusRuntimeException.class) .satisfies( failure -> @@ -3195,7 +3248,9 @@ public void close() { gameSessionPreparationClient.init(); preparedLifecycle = gameSessionPreparationClient.prepare( - preparationAssociationRequest, expectedLifecycleRequest); + preparationAssociationRequest, + stipulatedOwnerOperation, + expectedLifecycleRequest); } var assembledPreparationInput = @@ -3291,7 +3346,9 @@ public void close() { gameSessionPreparationRetryClient.init(); assertThat( gameSessionPreparationRetryClient.prepare( - preparationAssociationRequest, expectedLifecycleRequest)) + preparationAssociationRequest, + stipulatedOwnerOperation, + expectedLifecycleRequest)) .isEqualTo(preparedLifecycle); } var retryInput = @@ -3362,7 +3419,9 @@ public void close() { assertThatThrownBy( () -> defaultDeniedClient.prepare( - preparationAssociationRequest, expectedLifecycleRequest)) + preparationAssociationRequest, + stipulatedOwnerOperation, + expectedLifecycleRequest)) .isInstanceOf(io.grpc.StatusRuntimeException.class) .satisfies( failure -> diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java index e1c9fc20da..0fc1c144b2 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyApplicationTest.java @@ -8,6 +8,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; @@ -66,6 +67,55 @@ void presentInheritedCommitRetainsItsExistingUtf8Frame() { assertThat(application.canonicalBytes()).isEqualTo(expected); } + @Test + void schema3ActorCoreAndOriginalPolicyProvenanceSurviveOwnerApplication() { + String policyJson = + "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PLAYER_CREATED\"," + + "\"creationDescriptor\":{\"schemaVersion\":1,\"descriptorId\":\"11111111-1111-4111-8111-111111111111\"," + + "\"descriptorRevisionId\":\"22222222-2222-4222-8222-222222222222\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}"; + String payload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r3", + "policy", + RealmPolicySource.tree(policyJson))); + DraftCommitBinding binding = + DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-commit-0", + List.of( + new RevisionPayload("0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION_ID.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + var policy = RealmPolicySource.revision(binding, binding.revisions().getFirst()); + var snapshot = new RealmPolicySnapshot(binding, "1", List.of(policy)); + var application = new RealmPolicyApplication(freshGenesis(), null, "0", snapshot); + var retained = RealmPolicySnapshot.fromStored(application.snapshot().canonicalJson()); + var retainedPolicy = retained.policies().getFirst(); + + assertThat(retainedPolicy.commitId()).isEqualTo(COMMIT_ID); + assertThat(retainedPolicy.revisionId()).isEqualTo(REVISION_ID); + assertThat(retainedPolicy.logicalRevisionId()).isEqualTo("policy-logical-r3"); + assertThat(retainedPolicy.policy().initialActorCore().displayName()).isEqualTo("Wayfarer"); + assertThat(retainedPolicy.policy().initialActorCore().dispositionKey()).isEqualTo("newcomer"); + assertThat(application.canonicalBytes()).containsSequence(retained.canonicalBytes()); + } + @Test void missingBothGenesisAndInheritedCommitAndInvalidRequiredTextAreRejected() { RealmPolicySnapshot snapshot = snapshot(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBindingTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBindingTest.java new file mode 100644 index 0000000000..e581350a02 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBindingTest.java @@ -0,0 +1,558 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Definition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PrimitiveKind; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stat; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AuthoredInitialActorCoreSourceBindingTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID POLICY_REVISION = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID DISPOSITION_REVISION = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID FEEDBACK_REVISION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID SOURCE_OPERATION = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID GENESIS = uuid("77777777-7777-4777-8777-777777777777"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void bindsExactPolicyAndGameplaySnapshotsWithFullDispositionFeedbackProvenance() { + Fixture fixture = fixture(List.of()); + var binding = fixture.resolve().getFirst(); + + assertThat(binding.core().displayName()).isEqualTo("Wayfarer"); + assertThat(binding.core().dispositionKey()).isEqualTo("newcomer"); + assertThat(binding.expectedWorldSlug()).isEqualTo("world"); + assertThat(binding.disposition().safeFeedbackKey()).isEqualTo("welcome"); + assertThat(binding.safeFeedback().feedbackKey()).isEqualTo("welcome"); + assertThat(binding.gameplayManifest().families()).containsKeys(Family.values()); + for (Family family : Family.values()) { + if (family != Family.DISPOSITIONS && family != Family.FEEDBACK) { + assertThat(binding.gameplayManifest().families().get(family)).isEmpty(); + } + } + assertThat(binding.canonicalBytes()).isNotEmpty(); + assertThat(binding.digest()).matches("sha256:[0-9a-f]{64}"); + assertThat(binding.canonicalBytes()) + .satisfies( + value -> + assertThat(new String(value, StandardCharsets.ISO_8859_1)) + .contains( + new String( + fixture.policy().canonicalJson().getBytes(StandardCharsets.UTF_8), + StandardCharsets.ISO_8859_1))); + assertThat(binding.canonicalBytes()) + .satisfies( + value -> + assertThat(new String(value, StandardCharsets.ISO_8859_1)) + .contains( + new String( + fixture + .gameplaySnapshot() + .canonicalJson() + .getBytes(StandardCharsets.UTF_8), + StandardCharsets.ISO_8859_1))); + } + + @Test + void changedSourceOperationChangesTheBindingAndDifferentWorldDoesNotSubstitute() { + Fixture fixture = fixture(List.of()); + var original = fixture.resolve().getFirst(); + var changedOperation = + resolve( + fixture, + uuid("88888888-8888-4888-8888-888888888888"), + "world", + fixture.policySnapshot(), + fixture.gameplaySnapshot()) + .getFirst(); + + assertThat(changedOperation.digest()).isNotEqualTo(original.digest()); + assertThat( + resolve( + fixture, + SOURCE_OPERATION, + "different-world", + fixture.policySnapshot(), + fixture.gameplaySnapshot())) + .isEmpty(); + } + + @Test + void resolvesOnlyTheAssociatedWorldAndFramesTheFullMixedWorldSnapshot() { + Fixture fixture = withForeignWorldPolicy(fixture(List.of())); + var bindings = + resolve( + fixture, + SOURCE_OPERATION, + "world", + fixture.policySnapshot(), + fixture.gameplaySnapshot()); + + assertThat(bindings).hasSize(1); + assertThat(bindings.getFirst().policySource().policy().worldSlug()).isEqualTo("world"); + assertThat(bindings.getFirst().canonicalBytes()) + .satisfies( + value -> + assertThat(new String(value, StandardCharsets.ISO_8859_1)) + .contains( + new String( + fixture.policySnapshot().canonicalBytes(), + StandardCharsets.ISO_8859_1))); + assertThat(bindings.getFirst().canonicalBytes()) + .satisfies( + value -> + assertThat(new String(value, StandardCharsets.ISO_8859_1)) + .contains("foreign-only")); + } + + @Test + void doesNotSubstituteAValidPolicyForAnotherWorldWhenSelectedWorldHasNoCorePolicy() { + Fixture foreignOnly = + fixtureWithPolicy( + List.of(disposition("newcomer", "welcome")), + List.of(feedback("welcome", "Welcome")), + foreignPolicyJson()); + + assertThat( + resolve( + foreignOnly, + SOURCE_OPERATION, + "world", + foreignOnly.policySnapshot(), + foreignOnly.gameplaySnapshot())) + .isEmpty(); + } + + @Test + void changedReleaseEvidenceOrOriginalPolicyProvenanceChangesTheBinding() { + Fixture fixture = fixture(List.of()); + var original = fixture.resolve().getFirst(); + var changedReleaseSource = + AuthoredInitialActorCoreSourceBinding.resolveAll( + SOURCE_OPERATION, + digest('a'), + "world", + "workflow-1", + bytes("publication operation bytes"), + bytes("changed selected release evidence"), + fixture.binding(), + fixture.policySnapshot(), + fixture.gameplaySnapshot()) + .getFirst(); + + assertThat(changedReleaseSource.digest()).isNotEqualTo(original.digest()); + + var alteredPolicy = + new RealmPolicySource.Policy( + fixture.policySource().commitId(), + fixture.policySource().revisionId(), + "different-logical-revision", + fixture.policy()); + var changedPolicySnapshot = + new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( + fixture.binding(), "1", List.of(alteredPolicy)); + var changedPolicy = + resolve( + fixture, + SOURCE_OPERATION, + "world", + changedPolicySnapshot, + fixture.gameplaySnapshot()) + .getFirst(); + assertThat(changedPolicy.digest()).isNotEqualTo(original.digest()); + } + + @Test + void rejectsPolicyOrRuleSnapshotsFromAnotherSelectedCommit() { + Fixture fixture = fixture(List.of()); + DraftCommitBinding otherCommit = + DraftCommitBinding.create( + fixture.binding().target(), + uuid("99999999-9999-4999-8999-999999999999"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "base-0", + fixture.binding().revisions(), + fixture.binding().affectedUnits()); + + assertThatThrownBy( + () -> + AuthoredInitialActorCoreSourceBinding.resolveAll( + SOURCE_OPERATION, + digest('a'), + "world", + "workflow-1", + bytes("publication operation bytes"), + bytes("release evidence bytes"), + otherCommit, + fixture.policySnapshot(), + fixture.gameplaySnapshot())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("selected authored commit"); + + String changedRuleSnapshot = + fixture + .gameplaySnapshot() + .canonicalJson() + .replace("\"sourceEpoch\":\"1\"", "\"sourceEpoch\":\"2\""); + var changedRuleSource = + resolve( + fixture, + SOURCE_OPERATION, + "world", + fixture.policySnapshot(), + GameplayRuleSnapshot.fromStored(changedRuleSnapshot)) + .getFirst(); + assertThat(changedRuleSource.digest()).isNotEqualTo(fixture.resolve().getFirst().digest()); + } + + @Test + void rejectsAuthoredPresenceAddedToTheClosedSelectedGameplaySnapshot() { + Fixture fixture = fixture(List.of()); + String changedSnapshot = + fixture + .gameplaySnapshot() + .canonicalJson() + .replace("{\"bindingDigest\":", "{\"presence\":\"ACTIVE\",\"bindingDigest\":"); + + assertThatThrownBy(() -> GameplayRuleSnapshot.fromStored(changedSnapshot)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown or missing"); + } + + @Test + void rejectsMissingDispositionOrFeedbackAndPreservesOtherAuthoredRuleFamilies() { + Fixture fixture = fixture(List.of()); + var feedbackOnly = List.of(fixture.entries().getLast()); + var feedbackOnlySnapshot = + GameplayRuleSnapshot.fromStored(snapshot(fixture.binding(), feedbackOnly)); + assertThatThrownBy( + () -> + resolve( + fixture, + SOURCE_OPERATION, + "world", + fixture.policySnapshot(), + feedbackOnlySnapshot)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("disposition is absent"); + + Feedback changedFeedback = feedback("otherWelcome", "Welcome, traveler"); + assertThatThrownBy( + () -> + fixtureWithDefinitions( + List.of(disposition("newcomer", "welcome"), changedFeedback), List.of()) + .resolve()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("FEEDBACK"); + + Stat strength = + new Stat( + "strength", + PrimitiveKind.NUMERIC, + BigDecimal.ONE, + null, + BigDecimal.ZERO, + BigDecimal.TEN, + Visibility.PUBLIC, + List.of()); + Fixture withStat = + fixtureWithDefinitions( + List.of(disposition("newcomer", "welcome"), feedback("welcome", "Welcome")), + List.of(strength)); + var actorCoreSource = withStat.resolve().getFirst(); + assertThat(actorCoreSource.gameplayManifest().families().get(Family.STATS)) + .containsExactly(strength); + assertThat(actorCoreSource.canonicalBytes()).isNotEmpty(); + } + + @Test + void rejectsEntryProvenanceThatDoesNotBelongToItsOriginalRevision() { + Fixture fixture = fixture(List.of()); + GameplayRuleSource.Entry entry = fixture.entries().getFirst(); + assertThatThrownBy( + () -> + new GameplayRuleSource.Entry( + entry.family(), + entry.definition(), + entry.sourceBinding(), + entry.revisionOrder(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("original Game Design revision"); + } + + private static Fixture fixture(List extraDefinitions) { + return fixtureWithDefinitions( + List.of(disposition("newcomer", "welcome"), feedback("welcome", "Welcome")), + extraDefinitions); + } + + private static Fixture fixtureWithDefinitions( + List coreDefinitions, List extraDefinitions) { + return fixtureWithPolicy(coreDefinitions, extraDefinitions, policyJson()); + } + + private static Fixture fixtureWithPolicy( + List coreDefinitions, + List extraDefinitions, + String selectedPolicyJson) { + var policy = RealmEntryPolicy.parse(selectedPolicyJson, JSON); + var policyPayload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r1", + "policy", + RealmPolicySource.tree(policy.canonicalJson()))); + + List definitions = new ArrayList<>(coreDefinitions); + definitions.addAll(extraDefinitions); + var rulePayloads = definitions.stream().map(GameplayRuleSource::upsertPayload).toList(); + List revisions = new ArrayList<>(); + revisions.add( + new RevisionPayload("0", POLICY_REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, policyPayload)); + for (int index = 0; index < rulePayloads.size(); index++) { + UUID revisionId = + index == 0 + ? DISPOSITION_REVISION + : index == 1 ? FEEDBACK_REVISION : uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + revisions.add( + new RevisionPayload( + Integer.toString(index + 1), + revisionId, + Owner.GAME_DESIGN_CONTROL_PLANE, + rulePayloads.get(index))); + } + TargetProof target = + new TargetProof( + TENANT, VERSION, 23L, "private-owner-key", 42L, "private-owner-key", "NEW_GAME_ROW"); + DraftCommitBinding binding = + DraftCommitBinding.create( + target, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + "base-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"), + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + VERSION.toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + RealmPolicySource.Policy policySource = + RealmPolicySource.revision(binding, revisions.getFirst()); + List entries = new ArrayList<>(); + for (int index = 0; index < definitions.size(); index++) { + Definition definition = definitions.get(index); + entries.add( + new GameplayRuleSource.Entry( + definition.family(), + definition, + binding, + Integer.toString(index + 1), + revisions.get(index + 1).revisionId())); + } + List selectedEntries = List.copyOf(entries); + var policySnapshot = + new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( + binding, "1", List.of(policySource)); + String rulesJson = snapshot(binding, selectedEntries); + return new Fixture(binding, policy, policySource, policySnapshot, selectedEntries, rulesJson); + } + + private static Fixture withForeignWorldPolicy(Fixture fixture) { + RealmEntryPolicy foreignPolicy = RealmEntryPolicy.parse(foreignPolicyJson(), JSON); + String foreignPolicyPayload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "foreign-policy-logical-r1", + "policy", + RealmPolicySource.tree(foreignPolicy.canonicalJson()))); + var revisions = new ArrayList<>(fixture.binding().revisions()); + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + uuid("cccccccc-cccc-4ccc-8ccc-dddddddddddd"), + Owner.GAME_DESIGN_CONTROL_PLANE, + foreignPolicyPayload)); + DraftCommitBinding binding = + DraftCommitBinding.create( + fixture.binding().target(), + fixture.binding().requestId(), + fixture.binding().commitId(), + fixture.binding().baseCommitId(), + revisions, + fixture.binding().affectedUnits()); + RealmPolicySource.Policy selectedPolicy = + RealmPolicySource.revision(binding, revisions.getFirst()); + RealmPolicySource.Policy otherWorldPolicy = + RealmPolicySource.revision(binding, revisions.getLast()); + var policySnapshot = + new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( + binding, "1", List.of(selectedPolicy, otherWorldPolicy)); + List entries = + fixture.entries().stream() + .map( + entry -> + new GameplayRuleSource.Entry( + entry.family(), + entry.definition(), + binding, + entry.revisionOrder(), + entry.revisionId())) + .toList(); + return new Fixture( + binding, + fixture.policy(), + selectedPolicy, + policySnapshot, + entries, + snapshot(binding, entries)); + } + + private static List resolve( + Fixture fixture, + UUID sourceOperation, + String expectedWorldSlug, + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot, + GameplayRuleSnapshot gameplaySnapshot) { + return AuthoredInitialActorCoreSourceBinding.resolveAll( + sourceOperation, + digest('a'), + expectedWorldSlug, + "workflow-1", + bytes("publication operation bytes"), + bytes("release evidence bytes"), + fixture.binding(), + policySnapshot, + gameplaySnapshot); + } + + private static String snapshot( + DraftCommitBinding binding, List entries) { + return GameplayRuleManifest.canonical( + Map.of( + "schema", GameplayRuleSnapshot.SCHEMA, + "bindingJson", binding.canonicalJson(), + "bindingDigest", binding.digest(), + "sourceEpoch", "1", + "inheritedCommitId", "", + "genesisReceiptId", GENESIS.toString(), + "manifestJson", GameplayRuleSource.manifest(entries).canonicalJson(), + "entries", entries.stream().map(GameplayRuleSource.Entry::object).toList())); + } + + private static String policyJson() { + return "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PLAYER_CREATED\"," + + "\"creationDescriptor\":{\"schemaVersion\":1,\"descriptorId\":\"11111111-1111-4111-8111-111111111111\"," + + "\"descriptorRevisionId\":\"22222222-2222-4222-8222-222222222222\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}"; + } + + private static String foreignPolicyJson() { + return policyJson() + .replace( + "\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"", + "\"worldSlug\":\"other-world\",\"worldDisplayName\":\"Other World\"") + .replace( + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\"", + "\"realmSlug\":\"other-realm\",\"realmDisplayName\":\"Other Realm\"") + .replace( + "\"visible\":true,\"publicProduction\":true", + "\"visible\":false,\"publicProduction\":false") + .replace( + "\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"", + "\"displayName\":\"Other Wayfarer\",\"dispositionKey\":\"foreign-only\""); + } + + private static Disposition disposition(String key, String feedbackKey) { + return new Disposition(key, List.of(), feedbackKey); + } + + private static Feedback feedback(String key, String message) { + return new Feedback( + key, + "actor.created", + Audience.SOURCE_ACTOR, + "actor.created", + message, + List.of(), + Visibility.PUBLIC, + GameplayRuleManifest.ReplayPolicy.EFFECT_IDEMPOTENT); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private record Fixture( + DraftCommitBinding binding, + RealmEntryPolicy policy, + RealmPolicySource.Policy policySource, + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot, + List entries, + String rulesJson) { + private Fixture { + entries = List.copyOf(entries); + } + + private GameplayRuleSnapshot gameplaySnapshot() { + return GameplayRuleSnapshot.fromStored(rulesJson); + } + + private List resolve() { + return AuthoredInitialActorCoreSourceBindingTest.resolve( + this, SOURCE_OPERATION, "world", policySnapshot, gameplaySnapshot()); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java index 6edb3510ed..8dc7c51ca7 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java @@ -129,6 +129,41 @@ void inheritedCatalogPreservesUnchangedProvenanceAndExplicitDelete() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void authoredDispositionAndRequiredFeedbackRetainTypedSelectedRevisionProvenance() { + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor.created", + Audience.SOURCE_ACTOR, + "actor.created", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + ReplayPolicy.EFFECT_IDEMPOTENT); + var selected = + binding( + List.of( + GameplayRuleSource.upsertPayload(disposition), + GameplayRuleSource.upsertPayload(feedback))); + var entries = GameplayRuleSource.replay(List.of(), selected); + var manifest = GameplayRuleSource.manifest(entries); + + assertThat(manifest.families().keySet()).containsExactlyInAnyOrder(Family.values()); + for (Family family : Family.values()) { + if (family != Family.DISPOSITIONS && family != Family.FEEDBACK) { + assertThat(manifest.families().get(family)).isEmpty(); + } + } + assertThat(manifest.families().get(Family.DISPOSITIONS)).containsExactly(disposition); + assertThat(manifest.families().get(Family.FEEDBACK)).containsExactly(feedback); + assertThat(entries).extracting(GameplayRuleSource.Entry::sourceBinding).containsOnly(selected); + assertThat(entries) + .extracting(GameplayRuleSource.Entry::revisionOrder) + .containsExactly("0", "1"); + } + @Test void incompleteInventoryAndUnresolvedReferencesDenyInsteadOfBecomingEmpty() { var families = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java index 130fd3e083..2ed8a79814 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamedesign.publication; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; @@ -9,12 +10,25 @@ import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ReplayPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; @@ -107,6 +121,165 @@ void delegatesExactReplayToAssociationReaderBeforeOpeningLocalWriteTransaction() verifyNoInteractions(transactions); } + @Test + void selectedSchema3ActorCoreIsResolvedFromExactOwnerSnapshots() { + var fixture = selectedActorCoreSource(); + var resolved = + StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( + uuid("66666666-6666-4666-8666-666666666666"), + digest('a'), + "world", + "selected-workflow", + bytes("selected publication operation"), + bytes("selected publication terminal evidence"), + fixture.binding(), + fixture.policySnapshot(), + fixture.gameplayRules()); + + assertThat(resolved).hasSize(1); + assertThat(resolved.getFirst().core().displayName()).isEqualTo("Wayfarer"); + assertThat(resolved.getFirst().disposition().dispositionKey()).isEqualTo("newcomer"); + assertThat(resolved.getFirst().safeFeedback().feedbackKey()).isEqualTo("welcome"); + assertThat(resolved.getFirst().selectedCommit()).isEqualTo(fixture.binding()); + assertThat(resolved.getFirst().expectedWorldSlug()).isEqualTo("world"); + + assertThat( + StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( + uuid("66666666-6666-4666-8666-666666666666"), + digest('a'), + "different-world", + "selected-workflow", + bytes("selected publication operation"), + bytes("selected publication terminal evidence"), + fixture.binding(), + fixture.policySnapshot(), + fixture.gameplayRules())) + .isEmpty(); + + DraftCommitBinding otherCommit = + DraftCommitBinding.create( + fixture.binding().target(), + uuid("99999999-9999-4999-8999-999999999999"), + uuid("88888888-8888-4888-8888-888888888888"), + "base-commit-0", + fixture.binding().revisions(), + fixture.binding().affectedUnits()); + var changedPolicySnapshot = + new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( + otherCommit, "1", fixture.policySnapshot().policies()); + + assertThatThrownBy( + () -> + StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( + uuid("66666666-6666-4666-8666-666666666666"), + digest('a'), + "world", + "selected-workflow", + bytes("selected publication operation"), + bytes("selected publication terminal evidence"), + fixture.binding(), + changedPolicySnapshot, + fixture.gameplayRules())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("selected authored commit"); + } + + private static SelectedActorCoreFixture selectedActorCoreSource() { + var target = + new TargetProof( + TENANT, VERSION, 23L, "private-owner-key", 42L, "private-owner-key", "NEW_GAME_ROW"); + String policyJson = + "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PLAYER_CREATED\"," + + "\"creationDescriptor\":{\"schemaVersion\":1,\"descriptorId\":\"11111111-1111-4111-8111-111111111111\"," + + "\"descriptorRevisionId\":\"22222222-2222-4222-8222-222222222222\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}"; + String policyPayload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "selected-policy-r3", + "policy", + RealmPolicySource.tree(policyJson))); + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor.created", + Audience.SOURCE_ACTOR, + "actor.created", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + ReplayPolicy.EFFECT_IDEMPOTENT); + List revisions = + List.of( + new RevisionPayload( + "0", + uuid("55555555-5555-4555-8555-555555555555"), + Owner.GAME_DESIGN_CONTROL_PLANE, + policyPayload), + new RevisionPayload( + "1", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(disposition)), + new RevisionPayload( + "2", + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(feedback))); + List affectedUnits = + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"), + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + VERSION.toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0")); + DraftCommitBinding binding = + DraftCommitBinding.create( + target, + uuid("77777777-7777-4777-8777-777777777777"), + COMMIT, + "base-commit-0", + revisions, + affectedUnits); + var policySource = RealmPolicySource.revision(binding, revisions.getFirst()); + var policySnapshot = + new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( + binding, "1", List.of(policySource)); + var rulesSnapshot = + new GameplayRuleSnapshot( + binding, + "1", + null, + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + GameplayRuleSource.replay(List.of(), binding)); + return new SelectedActorCoreFixture(binding, policySnapshot, rulesSnapshot); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private record SelectedActorCoreFixture( + DraftCommitBinding binding, + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot, + GameplayRuleSnapshot gameplayRules) {} + private static void withPeer(Runnable action, String workload) { var peer = new GrpcPeerIdentity( diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index 60ba945a68..c094ce54ce 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -22,6 +22,20 @@ abstract class CreateDirectoriesTask : DefaultTask() { val gameSessionProto = rootDir.resolve("protos/game-session/v1/game_session_service.proto") +// Opt-in cross-owner proof artifact: never place Game Session application/migrations on Account's classpath. +val gameSessionClassesProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("classes-proof") + dependsOn(tasks.named("classes")) + from(sourceSets.main.get().output.classesDirs) +} + +val gameSessionClassesProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(gameSessionClassesProofJar) +} + apply(from = "${rootDir}/gradle/proto-convention.gradle") tasks.named("generateProto") { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java new file mode 100644 index 0000000000..eee3783edc --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java @@ -0,0 +1,934 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.sql.Connection; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unregistered, non-activating durable reservation for one canonical StartSession owner attempt. + * + *

This repository records immutable intent before the Account redemption call. It does not + * perform redemption, infer authority, dispatch a Game Session mutation, or write a business + * result. An expired claim remains pending and cannot be transferred or re-armed here. + */ +public final class GameSessionStartSessionOperatorAttemptRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String TABLE = "game_session_start_session_operator_attempt"; + private static final String OWNER_FENCE_SEQUENCE = + "game_session_start_session_operator_owner_fence_seq"; + private static final Pattern AUTHORIZATION_REFERENCE_FINGERPRINT = + Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Duration MAX_OWNER_CLAIM_LEASE = Duration.ofMinutes(5); + + private final DSLContext dsl; + private final long ownerClaimLeaseMillis; + + public GameSessionStartSessionOperatorAttemptRepository( + DSLContext dsl, Duration ownerClaimLease) { + this.dsl = Objects.requireNonNull(dsl, "dsl is required"); + Objects.requireNonNull(ownerClaimLease, "owner claim lease is required"); + long millis = ownerClaimLease.toMillis(); + if (millis <= 0L || ownerClaimLease.compareTo(MAX_OWNER_CLAIM_LEASE) > 0) { + throw new IllegalArgumentException( + "owner claim lease must be positive and at most five minutes"); + } + this.ownerClaimLeaseMillis = millis; + } + + /** + * Creates one claim or returns the exact existing attempt without granting a second claim. + * Requires a caller-owned, writable READ COMMITTED transaction. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public ReservationResult reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(tuple, "post-authorization tuple is required"); + String namespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + String requestId = tuple.controlPlaneRequestId(); + lockRequestKey(namespace, requestId); + + Record existing = selectAttempt(namespace, requestId, true); + if (existing != null) { + byte[] storedTuple = requiredBytes(existing, "post_authorization_execution_tuple"); + if (!Arrays.equals(storedTuple, tuple.canonicalBytes())) { + throw new StartSessionOperatorAttemptConflictException( + "controlPlaneRequestId is already bound to a different complete post-authorization tuple"); + } + requireStoredProjectionColumnsMatch(existing, tuple); + return new ReservationResult( + ReservationDisposition.EXACT_REPLAY, snapshot(existing), Optional.empty()); + } + + UUID attemptId = newNonNilUuid("ownerAttemptId"); + UUID ownerMutationId = newNonNilUuid("ownerMutationId"); + UUID claimOwnerId = newNonNilUuid("claimOwnerId"); + Record fenceRecord = dsl.fetchOne("SELECT nextval('" + OWNER_FENCE_SEQUENCE + "') AS fence"); + long ownerFence = requiredLong(fenceRecord, "fence"); + if (ownerFence <= 0L) { + throw new IllegalStateException( + "Game Session owner fence sequence did not produce a positive value"); + } + + Record inserted = + dsl.fetchOne( + "INSERT INTO " + + TABLE + + " (target_namespace, control_plane_request_id, canonical_tenant_id, " + + "owner_attempt_id, owner_mutation_id, claim_owner_id, owner_fence, " + + "post_authorization_execution_tuple, mutation_digest, " + + "authorization_reference_fingerprint, lease_expires_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "clock_timestamp() + (?::double precision / 1000.0) * interval '1 second') " + + "RETURNING *", + namespace, + requestId, + tuple.preAuthorizationTuple().action().scope().tenantId(), + attemptId, + ownerMutationId, + claimOwnerId, + ownerFence, + tuple.canonicalBytes(), + tuple.mutationDigest(), + tuple.authorizationReferenceFingerprint(), + ownerClaimLeaseMillis); + if (inserted == null) { + throw new IllegalStateException("Game Session owner attempt insert returned no row"); + } + AttemptClaim claim = + new AttemptClaim( + namespace, requestId, attemptId, ownerMutationId, claimOwnerId, ownerFence); + return new ReservationResult( + ReservationDisposition.CLAIM_CREATED, snapshot(inserted), Optional.of(claim)); + } + + /** + * Validates the exact original claim and returns its durable snapshot. Expired claims are stale; + * they are deliberately not advanced or reallocated. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public AttemptSnapshot validateCurrentClaim(AttemptClaim claim) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(claim, "owner attempt claim is required"); + Record row = selectAttempt(claim.targetNamespace(), claim.controlPlaneRequestId(), true); + requireClaimMatch(row, claim); + requireUnexpired(row); + return snapshot(row); + } + + /** + * Reads the exact original pending attempt under its live database-clock lease and original + * Account authorization-reference expiry. The claim-owner identity is loaded only inside this + * repository and is never returned to the caller. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public AttemptSnapshot readCurrentOriginalAttempt( + OriginalStartSessionCurrentAttemptEvidence.Request request) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(request, "current original-attempt read request is required"); + StartSessionPostAuthorizationExecutionTuple tuple = request.originalTuple(); + String namespace = request.targetNamespace(); + String requestId = tuple.controlPlaneRequestId(); + Record row = selectAttempt(namespace, requestId, true); + if (row == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Exact live original StartSession attempt is unavailable"); + } + + byte[] storedTuple = requiredBytes(row, "post_authorization_execution_tuple"); + if (!Arrays.equals(storedTuple, request.canonicalPostAuthorizationTuple())) { + throw new StartSessionOperatorAttemptConflictException( + "Current original-attempt read differs from the complete StartSession tuple"); + } + StartSessionPostAuthorizationExecutionTuple decodedTuple; + try { + decodedTuple = StartSessionPostAuthorizationExecutionTuple.decode(storedTuple); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Persisted current StartSession owner tuple is malformed", malformed); + } + if (!Arrays.equals(decodedTuple.canonicalBytes(), storedTuple) + || !namespace.equals(requiredText(row, "target_namespace")) + || !requestId.equals(requiredText(row, "control_plane_request_id"))) { + throw new IllegalStateException( + "Persisted current StartSession owner identity is not canonical"); + } + requireStoredProjectionColumnsMatch(row, decodedTuple); + if (!request.expectedOwnerAttemptId().equals(requiredUuid(row, "owner_attempt_id")) + || !request.expectedOwnerMutationId().equals(requiredUuid(row, "owner_mutation_id")) + || request.expectedOwnerFence() != requiredLong(row, "owner_fence")) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Current original-attempt read differs from the stored attempt, mutation, or fence"); + } + if (!"OWNER_EXECUTION_PENDING".equals(requiredText(row, "phase_state"))) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Only the original pending StartSession attempt supports a current lease read"); + } + + // The durable claimant credential is used only to revalidate this locked row internally. + AttemptClaim storedClaim = + new AttemptClaim( + namespace, + requestId, + request.expectedOwnerAttemptId(), + request.expectedOwnerMutationId(), + requiredUuid(row, "claim_owner_id"), + request.expectedOwnerFence()); + AttemptSnapshot current = validateCurrentClaim(storedClaim); + byte[] projection = current.accountRedemptionProjection(); + if (projection == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Original StartSession attempt has no attached Account projection"); + } + AccountRedemptionProjection expectedProjection = projectionFromTuple(decodedTuple); + if (!Arrays.equals(projection, expectedProjection.canonicalBytes())) { + throw new IllegalStateException( + "Attached Account projection differs from the exact current StartSession tuple"); + } + requireProjectionMatches(decodedTuple, expectedProjection); + requireOriginalAuthorityUnexpired(decodedTuple); + return current; + } + + /** + * Reads the immutable identity and attached Account projection for historical reconciliation. It + * does not require a live lease or reference and grants no permission to continue the mutation. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readHistoricalOwnerAttempt( + StartSessionPostAuthorizationExecutionTuple tuple, + UUID expectedOwnerAttemptId, + long expectedOwnerFence) { + requireOutsideOwnerTransaction(); + Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); + requireNonNil(expectedOwnerAttemptId, "expectedOwnerAttemptId"); + if (expectedOwnerFence <= 0L) { + throw new IllegalArgumentException("expectedOwnerFence must be positive"); + } + + String namespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + String requestId = tuple.controlPlaneRequestId(); + Record row = selectAttempt(namespace, requestId, false); + if (row == null) { + return Optional.empty(); + } + + byte[] expectedTuple = tuple.canonicalBytes(); + byte[] storedTuple = requiredBytes(row, "post_authorization_execution_tuple"); + if (!Arrays.equals(storedTuple, expectedTuple)) { + throw new StartSessionOperatorAttemptConflictException( + "Historical owner read differs from the complete original StartSession tuple"); + } + StartSessionPostAuthorizationExecutionTuple decodedTuple; + try { + decodedTuple = StartSessionPostAuthorizationExecutionTuple.decode(storedTuple); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Persisted historical StartSession owner tuple is malformed", malformed); + } + if (!Arrays.equals(decodedTuple.canonicalBytes(), storedTuple) + || !requiredText(row, "target_namespace").equals(namespace) + || !requiredText(row, "control_plane_request_id").equals(requestId)) { + throw new IllegalStateException( + "Persisted historical StartSession owner identity is not canonical"); + } + requireStoredProjectionColumnsMatch(row, decodedTuple); + if (!expectedOwnerAttemptId.equals(requiredUuid(row, "owner_attempt_id")) + || expectedOwnerFence != requiredLong(row, "owner_fence")) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Historical owner read does not match the original owner attempt and fence"); + } + + byte[] storedProjection = optionalBytes(row, "account_redemption_projection"); + if (storedProjection == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Historical StartSession owner attempt has no attached Account projection"); + } + AccountRedemptionProjection expectedProjection = projectionFromTuple(decodedTuple); + if (!Arrays.equals(storedProjection, expectedProjection.canonicalBytes())) { + throw new IllegalStateException( + "Persisted historical Account projection differs from its complete canonical tuple"); + } + requireProjectionMatches(decodedTuple, expectedProjection); + return Optional.of(snapshot(row)); + } + + /** + * Creates a narrow continuation capability for the exact existing pending attempt. This does not + * reconstruct or expose an {@link AttemptClaim}; every use revalidates the stored claim identity. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public EvidenceContinuation beginEvidenceContinuation( + StartSessionPostAuthorizationExecutionTuple tuple) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); + String namespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + Record row = selectAttempt(namespace, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Original StartSession owner attempt is missing and remains reconciliation-only"); + } + byte[] exactTuple = tuple.canonicalBytes(); + if (!Arrays.equals(requiredBytes(row, "post_authorization_execution_tuple"), exactTuple)) { + throw new StartSessionOperatorAttemptConflictException( + "Evidence continuation tuple differs from the original complete StartSession attempt"); + } + if (!"OWNER_EXECUTION_PENDING".equals(requiredText(row, "phase_state"))) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Only the original pending StartSession attempt supports evidence continuation"); + } + requireStoredProjectionColumnsMatch(row, tuple); + requireUnexpired(row); + requireOriginalAuthorityUnexpired(tuple); + byte[] storedProjection = optionalBytes(row, "account_redemption_projection"); + if (storedProjection == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "StartSession attempt has no attached Account projection and remains reconciliation-only"); + } + AccountRedemptionProjection expectedProjection = projectionFromTuple(tuple); + byte[] canonicalProjection = expectedProjection.canonicalBytes(); + if (!Arrays.equals(storedProjection, canonicalProjection)) { + throw new IllegalStateException( + "Persisted Account redemption projection differs from its complete canonical tuple"); + } + requireProjectionMatches(tuple, expectedProjection); + + return new EvidenceContinuation( + requiredText(row, "target_namespace"), + requiredText(row, "control_plane_request_id"), + requiredUuid(row, "owner_attempt_id"), + requiredUuid(row, "owner_mutation_id"), + requiredUuid(row, "claim_owner_id"), + requiredLong(row, "owner_fence"), + exactTuple, + storedProjection); + } + + /** + * Repo-internal capability check. Callers receive only the immutable attempt snapshot, never an + * AttemptClaim that could be reused for redemption or a general mutation. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + AttemptSnapshot validateEvidenceContinuation(EvidenceContinuation continuation) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(continuation, "evidence continuation is required"); + Record row = + selectAttempt(continuation.targetNamespace(), continuation.controlPlaneRequestId(), true); + if (row == null + || !continuation.ownerAttemptId().equals(optionalUuid(row, "owner_attempt_id")) + || !continuation.ownerMutationId().equals(optionalUuid(row, "owner_mutation_id")) + || !continuation.claimOwnerId().equals(optionalUuid(row, "claim_owner_id")) + || continuation.ownerFence() != optionalLong(row, "owner_fence")) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Evidence continuation no longer identifies the original stored owner claim"); + } + if (!"OWNER_EXECUTION_PENDING".equals(requiredText(row, "phase_state"))) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Evidence continuation requires the same pending owner attempt"); + } + requireUnexpired(row); + byte[] currentTuple = requiredBytes(row, "post_authorization_execution_tuple"); + if (!Arrays.equals(currentTuple, continuation.postAuthorizationExecutionTuple())) { + throw new StartSessionOperatorAttemptConflictException( + "Evidence continuation tuple or Account projection differs from the retained attempt"); + } + StartSessionPostAuthorizationExecutionTuple decodedTuple = + StartSessionPostAuthorizationExecutionTuple.decode(currentTuple); + requireOriginalAuthorityUnexpired(decodedTuple); + byte[] currentProjection = optionalBytes(row, "account_redemption_projection"); + if (currentProjection == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Evidence continuation Account projection is no longer attached"); + } + if (!Arrays.equals(currentProjection, continuation.accountRedemptionProjection())) { + throw new StartSessionOperatorAttemptConflictException( + "Evidence continuation tuple or Account projection differs from the retained attempt"); + } + StartSessionPostAuthorizationExecutionTuple tuple = decodedTuple; + if (!Arrays.equals(tuple.canonicalBytes(), currentTuple) + || !tuple.controlPlaneRequestId().equals(continuation.controlPlaneRequestId()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(continuation.targetNamespace())) { + throw new IllegalStateException( + "Evidence continuation tuple is not the canonical original owner identity"); + } + requireStoredProjectionColumnsMatch(row, tuple); + AccountRedemptionProjection expectedProjection = projectionFromTuple(tuple); + if (!Arrays.equals(currentProjection, expectedProjection.canonicalBytes())) { + throw new IllegalStateException( + "Evidence continuation Account projection is not canonical for its tuple"); + } + requireProjectionMatches(tuple, expectedProjection); + return snapshot(row); + } + + /** + * Atomically attaches the exact Account redemption projection to its still-current claim. Replays + * of the same projection return the original snapshot; any substitution conflicts. + */ + @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) + public AttemptSnapshot attachAccountRedemptionProjection( + AttemptClaim claim, AccountRedemptionProjection projection) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(claim, "owner attempt claim is required"); + Objects.requireNonNull(projection, "Account redemption projection is required"); + Record row = selectAttempt(claim.targetNamespace(), claim.controlPlaneRequestId(), true); + requireClaimMatch(row, claim); + requireUnexpired(row); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + requiredBytes(row, "post_authorization_execution_tuple")); + requireProjectionMatches(tuple, projection); + + byte[] existingProjection = optionalBytes(row, "account_redemption_projection"); + byte[] exactProjection = projection.canonicalBytes(); + if (existingProjection != null) { + if (!Arrays.equals(existingProjection, exactProjection)) { + throw new StartSessionOperatorAttemptConflictException( + "Account redemption projection differs from the original exact projection"); + } + return snapshot(row); + } + + Record updated = + dsl.fetchOne( + "UPDATE " + + TABLE + + " SET account_redemption_projection = ? " + + "WHERE target_namespace = ? AND control_plane_request_id = ? " + + "AND owner_attempt_id = ? AND owner_mutation_id = ? " + + "AND claim_owner_id = ? AND owner_fence = ? " + + "AND lease_expires_at > clock_timestamp() " + + "AND account_redemption_projection IS NULL RETURNING *", + exactProjection, + claim.targetNamespace(), + claim.controlPlaneRequestId(), + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.claimOwnerId(), + claim.ownerFence()); + if (updated == null) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Game Session owner attempt claim changed before Account projection attachment"); + } + return snapshot(updated); + } + + private void lockRequestKey(String namespace, String requestId) { + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ?, 0))", namespace, requestId); + } + + private Record selectAttempt(String namespace, String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + namespace, + requestId); + } + + private static void requireStoredProjectionColumnsMatch( + Record row, StartSessionPostAuthorizationExecutionTuple tuple) { + if (!tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .equals(requiredUuid(row, "canonical_tenant_id")) + || !tuple.mutationDigest().equals(requiredText(row, "mutation_digest")) + || !tuple + .authorizationReferenceFingerprint() + .equals(requiredText(row, "authorization_reference_fingerprint"))) { + throw new IllegalStateException( + "Persisted Game Session owner attempt columns differ from its exact canonical tuple"); + } + } + + private static void requireProjectionMatches( + StartSessionPostAuthorizationExecutionTuple tuple, AccountRedemptionProjection projection) { + if (!tuple + .authorizationReferenceFingerprint() + .equals(projection.authorizationReferenceFingerprint()) + || !Arrays.equals( + tuple.authorityEvidenceBundleBytes(), projection.authorityEvidenceBundleBytes()) + || !StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .issuanceOperationId() + .equals(projection.issuanceOperationId()) + || parsePositiveFence(tuple.issuanceFence()) != projection.issuanceFence()) { + throw new StartSessionOperatorAttemptConflictException( + "Account redemption projection is not bound to the exact post-authorization tuple"); + } + } + + private static AccountRedemptionProjection projectionFromTuple( + StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle authority = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + parsePositiveFence(tuple.issuanceFence())); + } + + private static void requireClaimMatch(Record row, AttemptClaim claim) { + if (row == null + || !claim.ownerAttemptId().equals(optionalUuid(row, "owner_attempt_id")) + || !claim.ownerMutationId().equals(optionalUuid(row, "owner_mutation_id")) + || !claim.claimOwnerId().equals(optionalUuid(row, "claim_owner_id")) + || claim.ownerFence() != optionalLong(row, "owner_fence")) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Game Session owner attempt claim is missing or no longer exact"); + } + } + + private void requireUnexpired(Record row) { + Record validity = + dsl.fetchOne( + "SELECT lease_expires_at > clock_timestamp() AS unexpired " + + "FROM " + + TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ?", + requiredText(row, "target_namespace"), + requiredText(row, "control_plane_request_id")); + if (validity == null || !Boolean.TRUE.equals(validity.get("unexpired", Boolean.class))) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Game Session owner attempt claim lease is expired and remains non-replayable"); + } + } + + private static void requireOutsideOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Historical StartSession owner evidence requires a read outside the owner transaction"); + } + } + + private void requireOriginalAuthorityUnexpired( + StartSessionPostAuthorizationExecutionTuple tuple) { + String referenceExpiresAt = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .authorizationExpiresAt(); + Record validity = + dsl.fetchOne("SELECT ?::timestamptz > clock_timestamp() AS unexpired", referenceExpiresAt); + if (validity == null || !Boolean.TRUE.equals(validity.get("unexpired", Boolean.class))) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Original Account authorization reference expired during evidence continuation"); + } + } + + private static AttemptSnapshot snapshot(Record row) { + return new AttemptSnapshot( + requiredText(row, "target_namespace"), + requiredText(row, "control_plane_request_id"), + requiredUuid(row, "canonical_tenant_id"), + requiredUuid(row, "owner_attempt_id"), + requiredUuid(row, "owner_mutation_id"), + requiredLong(row, "owner_fence"), + requiredText(row, "phase_state"), + requiredBytes(row, "post_authorization_execution_tuple"), + optionalBytes(row, "account_redemption_projection"), + requiredInstant(row, "created_at"), + requiredInstant(row, "lease_expires_at")); + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "StartSession owner attempt requires a writable READ COMMITTED owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "StartSession owner attempt requires a writable READ COMMITTED owner transaction"); + } + return null; + }); + Record transaction = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + if (transaction == null + || !"read committed".equals(transaction.get("isolation", String.class)) + || !"off".equals(transaction.get("read_only", String.class))) { + throw new IllegalStateException( + "StartSession owner attempt requires a writable READ COMMITTED owner transaction"); + } + } + + private static long parsePositiveFence(String value) { + try { + long fence = Long.parseLong(value); + if (fence <= 0L || !Long.toString(fence).equals(value)) { + throw new NumberFormatException(); + } + return fence; + } catch (NumberFormatException malformed) { + throw new IllegalArgumentException( + "Account issuance fence is outside the signed owner range"); + } + } + + private static UUID newNonNilUuid(String field) { + UUID value = UUID.randomUUID(); + if (NIL_UUID.equals(value)) { + throw new IllegalStateException("Random UUID source returned nil " + field); + } + return value; + } + + private static String requiredText(Record row, String field) { + String value = row == null ? null : row.get(field, String.class); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner attempt is missing " + field); + } + return value; + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = optionalUuid(row, field); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner attempt is missing " + field); + } + return value; + } + + private static UUID optionalUuid(Record row, String field) { + return row == null ? null : row.get(field, UUID.class); + } + + private static long requiredLong(Record row, String field) { + Long value = optionalLong(row, field); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner attempt is missing " + field); + } + return value; + } + + private static Long optionalLong(Record row, String field) { + return row == null ? null : row.get(field, Long.class); + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = optionalBytes(row, field); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner attempt is missing " + field); + } + return value; + } + + private static byte[] optionalBytes(Record row, String field) { + byte[] value = row == null ? null : row.get(field, byte[].class); + return value == null ? null : value.clone(); + } + + private static Instant requiredInstant(Record row, String field) { + java.time.OffsetDateTime value = + row == null ? null : row.get(field, java.time.OffsetDateTime.class); + if (value == null) { + throw new IllegalStateException("Persisted Game Session owner attempt is missing " + field); + } + return value.toInstant(); + } + + public enum ReservationDisposition { + CLAIM_CREATED, + EXACT_REPLAY + } + + /** Result distinguishes the unique newly minted claim from a replay snapshot. */ + public record ReservationResult( + ReservationDisposition disposition, AttemptSnapshot snapshot, Optional claim) { + public ReservationResult { + Objects.requireNonNull(disposition, "disposition is required"); + Objects.requireNonNull(snapshot, "snapshot is required"); + Objects.requireNonNull(claim, "claim wrapper is required"); + if ((disposition == ReservationDisposition.CLAIM_CREATED) != claim.isPresent()) { + throw new IllegalArgumentException( + "only a newly created owner attempt may return its claim"); + } + } + } + + /** One opaque-in-process capability returned only to the transaction that created the claim. */ + public record AttemptClaim( + String targetNamespace, + String controlPlaneRequestId, + UUID ownerAttemptId, + UUID ownerMutationId, + UUID claimOwnerId, + long ownerFence) { + public AttemptClaim { + Objects.requireNonNull(targetNamespace, "targetNamespace is required"); + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId is required"); + requireNonNil(ownerAttemptId, "ownerAttemptId"); + requireNonNil(ownerMutationId, "ownerMutationId"); + requireNonNil(claimOwnerId, "claimOwnerId"); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + } + } + + /** + * Narrow owner-internal continuation token. Its constructor and all claim-binding accessors are + * private to this repository package; it exposes no claimant credential or redemption API. + */ + public static final class EvidenceContinuation { + private final String targetNamespace; + private final String controlPlaneRequestId; + private final UUID ownerAttemptId; + private final UUID ownerMutationId; + private final UUID claimOwnerId; + private final long ownerFence; + private final byte[] postAuthorizationExecutionTuple; + private final byte[] accountRedemptionProjection; + + private EvidenceContinuation( + String targetNamespace, + String controlPlaneRequestId, + UUID ownerAttemptId, + UUID ownerMutationId, + UUID claimOwnerId, + long ownerFence, + byte[] postAuthorizationExecutionTuple, + byte[] accountRedemptionProjection) { + this.targetNamespace = Objects.requireNonNull(targetNamespace); + this.controlPlaneRequestId = Objects.requireNonNull(controlPlaneRequestId); + this.ownerAttemptId = Objects.requireNonNull(ownerAttemptId); + this.ownerMutationId = Objects.requireNonNull(ownerMutationId); + this.claimOwnerId = Objects.requireNonNull(claimOwnerId); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + this.ownerFence = ownerFence; + this.postAuthorizationExecutionTuple = postAuthorizationExecutionTuple.clone(); + this.accountRedemptionProjection = accountRedemptionProjection.clone(); + } + + String targetNamespace() { + return targetNamespace; + } + + String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + UUID ownerAttemptId() { + return ownerAttemptId; + } + + UUID ownerMutationId() { + return ownerMutationId; + } + + UUID claimOwnerId() { + return claimOwnerId; + } + + long ownerFence() { + return ownerFence; + } + + byte[] postAuthorizationExecutionTuple() { + return postAuthorizationExecutionTuple.clone(); + } + + byte[] accountRedemptionProjection() { + return accountRedemptionProjection.clone(); + } + } + + /** Immutable readback; byte-array accessors never expose the stored record buffer. */ + public static final class AttemptSnapshot { + private final String targetNamespace; + private final String controlPlaneRequestId; + private final UUID canonicalTenantId; + private final UUID ownerAttemptId; + private final UUID ownerMutationId; + private final long ownerFence; + private final String phaseState; + private final byte[] postAuthorizationExecutionTuple; + private final byte[] accountRedemptionProjection; + private final Instant createdAt; + private final Instant leaseExpiresAt; + + private AttemptSnapshot( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + UUID ownerAttemptId, + UUID ownerMutationId, + long ownerFence, + String phaseState, + byte[] postAuthorizationExecutionTuple, + byte[] accountRedemptionProjection, + Instant createdAt, + Instant leaseExpiresAt) { + this.targetNamespace = targetNamespace; + this.controlPlaneRequestId = controlPlaneRequestId; + this.canonicalTenantId = canonicalTenantId; + this.ownerAttemptId = ownerAttemptId; + this.ownerMutationId = ownerMutationId; + this.ownerFence = ownerFence; + this.phaseState = phaseState; + this.postAuthorizationExecutionTuple = postAuthorizationExecutionTuple.clone(); + this.accountRedemptionProjection = + accountRedemptionProjection == null ? null : accountRedemptionProjection.clone(); + this.createdAt = createdAt; + this.leaseExpiresAt = leaseExpiresAt; + } + + public String targetNamespace() { + return targetNamespace; + } + + public String controlPlaneRequestId() { + return controlPlaneRequestId; + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public UUID ownerAttemptId() { + return ownerAttemptId; + } + + public UUID ownerMutationId() { + return ownerMutationId; + } + + public long ownerFence() { + return ownerFence; + } + + public String phaseState() { + return phaseState; + } + + public byte[] postAuthorizationExecutionTuple() { + return postAuthorizationExecutionTuple.clone(); + } + + public byte[] accountRedemptionProjection() { + return accountRedemptionProjection == null ? null : accountRedemptionProjection.clone(); + } + + public Instant createdAt() { + return createdAt; + } + + public Instant leaseExpiresAt() { + return leaseExpiresAt; + } + } + + /** Typed, no-secret Account redemption output persisted only after exact tuple comparison. */ + public record AccountRedemptionProjection( + String authorizationReferenceFingerprint, + byte[] authorityEvidenceBundleBytes, + UUID issuanceOperationId, + long issuanceFence) { + public AccountRedemptionProjection { + if (authorizationReferenceFingerprint == null + || !AUTHORIZATION_REFERENCE_FINGERPRINT + .matcher(authorizationReferenceFingerprint) + .matches()) { + throw new IllegalArgumentException("Account redemption fingerprint is malformed"); + } + authorityEvidenceBundleBytes = + Objects.requireNonNull( + authorityEvidenceBundleBytes, "authority evidence bundle is required") + .clone(); + Objects.requireNonNull(issuanceOperationId, "issuanceOperationId is required"); + if (issuanceOperationId.equals(NIL_UUID) || issuanceFence <= 0L) { + throw new IllegalArgumentException( + "Account redemption identity and fence must be positive"); + } + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundleBytes); + if (!bundle.issuanceOperationId().equals(issuanceOperationId) + || parsePositiveFence(bundle.issuanceFence()) != issuanceFence) { + throw new IllegalArgumentException( + "Account redemption response differs from its exact authority evidence bundle"); + } + } + + @Override + public byte[] authorityEvidenceBundleBytes() { + return authorityEvidenceBundleBytes.clone(); + } + + public byte[] canonicalBytes() { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundleBytes); + Map projection = new LinkedHashMap<>(); + projection.put("projectionSchemaId", "accountStartSessionRedemptionProjection"); + projection.put("projectionSchemaVersion", "1"); + projection.put("authorizationReferenceFingerprint", authorizationReferenceFingerprint); + projection.put("authorityEvidenceBundle", bundle.jsonValue()); + projection.put("issuanceOperationId", issuanceOperationId.toString()); + projection.put("issuanceFence", issuanceFence); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + if (bytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException( + "Account redemption projection exceeds its byte limit"); + } + return bytes; + } catch (java.io.IOException exception) { + throw new IllegalStateException( + "could not encode Account redemption projection", exception); + } + } + } + + public static final class StartSessionOperatorAttemptConflictException + extends IllegalStateException { + public StartSessionOperatorAttemptConflictException(String message) { + super(message); + } + } + + public static final class StaleStartSessionOperatorAttemptClaimException + extends IllegalStateException { + public StaleStartSessionOperatorAttemptClaimException(String message) { + super(message); + } + } + + private static void requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must not be nil"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcService.java new file mode 100644 index 0000000000..0d4428c662 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcService.java @@ -0,0 +1,167 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StartSessionOperatorAttemptConflictException; +import net.firedevops.firemud.gamesession.v1.OriginalStartSessionCurrentAttemptReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionOperations; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Directly constructible, deliberately unregistered current-lease observation producer. + * + *

The response is a point-in-time snapshot. It does not establish continuous Account authority, + * authorize execution, renew the lease, or prove admission or protection of later writes. + */ +public final class OriginalStartSessionCurrentAttemptReadGrpcService + extends OriginalStartSessionCurrentAttemptReadServiceGrpc + .OriginalStartSessionCurrentAttemptReadServiceImplBase { + private final GameSessionStartSessionOperatorAttemptRepository repository; + private final OriginalStartSessionCurrentAttemptReadWorkloadGuard workloadGuard; + private final TransactionOperations ownerReadTransaction; + + public OriginalStartSessionCurrentAttemptReadGrpcService( + GameSessionStartSessionOperatorAttemptRepository repository, + PlatformTransactionManager transactionManager, + String trustedNamespace) { + this(repository, configuredTransaction(transactionManager), trustedNamespace); + } + + OriginalStartSessionCurrentAttemptReadGrpcService( + GameSessionStartSessionOperatorAttemptRepository repository, + TransactionOperations ownerReadTransaction, + String trustedNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.ownerReadTransaction = + Objects.requireNonNull(ownerReadTransaction, "ownerReadTransaction"); + this.workloadGuard = new OriginalStartSessionCurrentAttemptReadWorkloadGuard(trustedNamespace); + } + + @Override + public void readOriginalStartSessionCurrentAttempt( + ReadOriginalStartSessionCurrentAttemptRequest request, + StreamObserver responseObserver) { + Objects.requireNonNull(responseObserver, "responseObserver"); + + OriginalStartSessionCurrentAttemptEvidence.Request decoded; + try { + // Authenticate the peer before inspecting any request bytes. + workloadGuard.requireAccountCurrentAttemptReadCaller(); + if (request == null) { + throw new IllegalArgumentException( + "Current original StartSession read request is required"); + } + decoded = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(request); + workloadGuard.requireConfiguredTargetNamespace(decoded.targetNamespace()); + } catch (AdminAuthorizationException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED.withDescription(denied.getMessage()).asRuntimeException()); + return; + } catch (IllegalArgumentException malformed) { + responseObserver.onError( + Status.INVALID_ARGUMENT.withDescription(malformed.getMessage()).asRuntimeException()); + return; + } + + try { + requireNoAmbientTransaction(); + AttemptSnapshot snapshot = + ownerReadTransaction.execute(status -> repository.readCurrentOriginalAttempt(decoded)); + if (snapshot == null) { + throw new IllegalStateException( + "Current original-attempt read transaction returned no row"); + } + requireExactSnapshot(decoded, snapshot); + var result = + new OriginalStartSessionCurrentAttemptEvidence.Result( + decoded, snapshot.leaseExpiresAt(), snapshot.accountRedemptionProjection()); + ReadOriginalStartSessionCurrentAttemptResponse response = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (StartSessionOperatorAttemptConflictException + | StaleStartSessionOperatorAttemptClaimException unavailable) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription(unavailable.getMessage()) + .asRuntimeException()); + } catch (RuntimeException failure) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Current original StartSession attempt read failed") + .asRuntimeException()); + } + } + + private static TransactionOperations configuredTransaction( + PlatformTransactionManager transactionManager) { + Objects.requireNonNull(transactionManager, "transactionManager"); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + // SELECT FOR UPDATE requires a writable transaction on PostgreSQL; this operation performs no + // INSERT, UPDATE, lease renewal, or other durable mutation. + transaction.setReadOnly(false); + return transaction; + } + + private static void requireExactSnapshot( + OriginalStartSessionCurrentAttemptEvidence.Request request, AttemptSnapshot snapshot) { + var tuple = request.originalTuple(); + if (!request.targetNamespace().equals(snapshot.targetNamespace()) + || !tuple.controlPlaneRequestId().equals(snapshot.controlPlaneRequestId()) + || !request.expectedOwnerAttemptId().equals(snapshot.ownerAttemptId()) + || !request.expectedOwnerMutationId().equals(snapshot.ownerMutationId()) + || request.expectedOwnerFence() != snapshot.ownerFence() + || !OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals(snapshot.phaseState()) + || !Arrays.equals( + request.canonicalPostAuthorizationTuple(), snapshot.postAuthorizationExecutionTuple()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .equals(snapshot.canonicalTenantId()) + || snapshot.leaseExpiresAt() == null + || snapshot.accountRedemptionProjection() == null) { + throw new IllegalStateException( + "Repository returned a different or incomplete current original StartSession attempt"); + } + StartSessionAuthorityEvidenceBundle authority = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + byte[] expectedProjection = + new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())) + .canonicalBytes(); + if (!Arrays.equals(expectedProjection, snapshot.accountRedemptionProjection())) { + throw new IllegalStateException( + "Repository returned an Account projection different from the exact original tuple"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Current original StartSession read requires its own READ COMMITTED transaction"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuard.java new file mode 100644 index 0000000000..63dab74cd2 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuard.java @@ -0,0 +1,46 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.OriginalStartSessionCurrentAttemptReadServiceGrpc; + +/** Exact same-namespace Account workload authorization for the live original-attempt read. */ +public final class OriginalStartSessionCurrentAttemptReadWorkloadGuard { + private static final String METHOD_NAME = + "game_session.v1.OriginalStartSessionCurrentAttemptReadService/" + + "ReadOriginalStartSessionCurrentAttempt"; + private static final String ALLOWED_SERVICE = "account-service"; + + private final String trustedNamespace; + + public OriginalStartSessionCurrentAttemptReadWorkloadGuard(String trustedNamespace) { + this.trustedNamespace = trustedNamespace; + } + + public void requireAccountCurrentAttemptReadCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!METHOD_NAME.equals( + OriginalStartSessionCurrentAttemptReadServiceGrpc + .getReadOriginalStartSessionCurrentAttemptMethod() + .getFullMethodName()) + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || peer == null + || !ALLOWED_SERVICE.equals(peer.service()) + || !trustedNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + trustedNamespace + "/sa/" + ALLOWED_SERVICE) + .equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Current original StartSession evidence requires the exact same-namespace Account workload without caller context"); + } + } + + public void requireConfiguredTargetNamespace(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || !trustedNamespace.equals(targetNamespace)) { + throw new AdminAuthorizationException( + "Current original StartSession attempt target namespace is not configured here"); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql b/services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql new file mode 100644 index 0000000000..bd673c1876 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V35__start_session_operator_owner_attempt.sql @@ -0,0 +1,100 @@ +-- Game Session's non-replayable owner-side reservation for a complete authorized StartSession. +-- This table is intentionally not a runtime-activation or business-mutation switch. +-- [jooq ignore start] +CREATE SEQUENCE game_session_start_session_operator_owner_fence_seq + AS BIGINT START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE NO CYCLE; + +CREATE TABLE game_session_start_session_operator_attempt ( + target_namespace VARCHAR(63) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_tenant_id UUID NOT NULL, + owner_attempt_id UUID NOT NULL, + owner_mutation_id UUID NOT NULL, + claim_owner_id UUID NOT NULL, + owner_fence BIGINT NOT NULL, + post_authorization_execution_tuple BYTEA NOT NULL, + mutation_digest VARCHAR(64) NOT NULL, + authorization_reference_fingerprint VARCHAR(137) NOT NULL, + phase_state VARCHAR(48) NOT NULL DEFAULT 'OWNER_EXECUTION_PENDING', + account_redemption_projection BYTEA, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + lease_expires_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_gs_start_session_operator_attempt + PRIMARY KEY (target_namespace, control_plane_request_id), + CONSTRAINT uq_gs_start_session_operator_attempt_id UNIQUE (owner_attempt_id), + CONSTRAINT uq_gs_start_session_operator_mutation_id UNIQUE (owner_mutation_id), + CONSTRAINT uq_gs_start_session_operator_fence UNIQUE (owner_fence), + CONSTRAINT chk_gs_start_session_operator_attempt_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND octet_length(control_plane_request_id) BETWEEN 1 AND 128 + AND control_plane_request_id !~ '^[[:space:]]*$' + AND control_plane_request_id !~ '[[:cntrl:]]' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND claim_owner_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_fence > 0 + AND lease_expires_at > created_at), + CONSTRAINT chk_gs_start_session_operator_attempt_tuple CHECK ( + octet_length(post_authorization_execution_tuple) BETWEEN 1 AND 262144 + AND mutation_digest ~ '^[0-9a-f]{64}$' + AND authorization_reference_fingerprint + ~ '^arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}$'), + CONSTRAINT chk_gs_start_session_operator_attempt_pending CHECK ( + phase_state = 'OWNER_EXECUTION_PENDING' + AND (account_redemption_projection IS NULL + OR octet_length(account_redemption_projection) BETWEEN 1 AND 262144)) +); + +CREATE FUNCTION enforce_game_session_start_session_operator_attempt_immutable() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Session StartSession owner attempts are immutable' + USING ERRCODE = 'check_violation'; + END IF; + + IF OLD.account_redemption_projection IS NOT NULL + OR NEW.account_redemption_projection IS NULL + OR NEW.target_namespace IS DISTINCT FROM OLD.target_namespace + OR NEW.control_plane_request_id IS DISTINCT FROM OLD.control_plane_request_id + OR NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.owner_attempt_id IS DISTINCT FROM OLD.owner_attempt_id + OR NEW.owner_mutation_id IS DISTINCT FROM OLD.owner_mutation_id + OR NEW.claim_owner_id IS DISTINCT FROM OLD.claim_owner_id + OR NEW.owner_fence IS DISTINCT FROM OLD.owner_fence + OR NEW.post_authorization_execution_tuple IS DISTINCT FROM OLD.post_authorization_execution_tuple + OR NEW.mutation_digest IS DISTINCT FROM OLD.mutation_digest + OR NEW.authorization_reference_fingerprint IS DISTINCT FROM OLD.authorization_reference_fingerprint + OR NEW.phase_state IS DISTINCT FROM OLD.phase_state + OR NEW.created_at IS DISTINCT FROM OLD.created_at + OR NEW.lease_expires_at IS DISTINCT FROM OLD.lease_expires_at THEN + RAISE EXCEPTION 'Game Session StartSession owner attempt evidence is immutable' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_start_session_operator_attempt_immutable + BEFORE UPDATE OR DELETE ON game_session_start_session_operator_attempt + FOR EACH ROW EXECUTE FUNCTION enforce_game_session_start_session_operator_attempt_immutable(); + +CREATE FUNCTION reject_game_session_start_session_operator_attempt_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session StartSession owner attempts cannot be truncated' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER game_session_start_session_operator_attempt_no_truncate + BEFORE TRUNCATE ON game_session_start_session_operator_attempt + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_start_session_operator_attempt_truncate(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java new file mode 100644 index 0000000000..bdc576e1dd --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java @@ -0,0 +1,480 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.file.Path; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** PostgreSQL proof of the exact, observation-only current original StartSession attempt read. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "world-runtime"; + private static final String WORKLOAD = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void currentOriginalAttemptReadReturnsExactAttachedSnapshotWithoutChangingPersistedRow() { + Fixture fixture = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("current-attempt-read-exact"); + AttemptClaim claim = fixture.reserve(tuple).claim().orElseThrow(); + AttemptSnapshot attached = + fixture.attach( + claim, + projection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + Request request = currentAttemptRequest(tuple, claim); + String before = fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId()); + + AttemptSnapshot current = fixture.currentOriginalAttempt(request); + + assertThat(current.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(current.controlPlaneRequestId()).isEqualTo(tuple.controlPlaneRequestId()); + assertThat(current.canonicalTenantId()).isEqualTo(TENANT); + assertThat(current.ownerAttemptId()).isEqualTo(claim.ownerAttemptId()); + assertThat(current.ownerMutationId()).isEqualTo(claim.ownerMutationId()); + assertThat(current.ownerFence()).isEqualTo(claim.ownerFence()); + assertThat(current.phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(current.leaseExpiresAt()).isEqualTo(attached.leaseExpiresAt()); + assertThat(current.postAuthorizationExecutionTuple()).containsExactly(tuple.canonicalBytes()); + assertThat(current.accountRedemptionProjection()) + .containsExactly(attached.accountRedemptionProjection()); + assertThat(fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId())).isEqualTo(before); + } + + @Test + void currentOriginalAttemptReadRejectsExpiredAndUnattachedOrMismatchedEvidenceWithoutMutation() + throws Exception { + Fixture unattached = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple unattachedTuple = + tuple("current-attempt-read-unattached"); + AttemptClaim unattachedClaim = unattached.reserve(unattachedTuple).claim().orElseThrow(); + String unattachedBefore = + unattached.ownerAttemptRowJson(unattachedTuple.controlPlaneRequestId()); + assertThatThrownBy( + () -> + unattached.currentOriginalAttempt( + currentAttemptRequest(unattachedTuple, unattachedClaim))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("no attached Account projection"); + assertThat(unattached.ownerAttemptRowJson(unattachedTuple.controlPlaneRequestId())) + .isEqualTo(unattachedBefore); + + Fixture mismatched = fixture(Duration.ofSeconds(30)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("current-attempt-read-mismatch"); + AttemptClaim claim = mismatched.reserve(tuple).claim().orElseThrow(); + mismatched.attach( + claim, + projection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + String before = mismatched.ownerAttemptRowJson(tuple.controlPlaneRequestId()); + assertThatThrownBy( + () -> + mismatched.currentOriginalAttempt( + currentAttemptRequest( + tuple, + UUID.fromString("1819a1ce-04d2-4e3f-bb64-4a672d4eb711"), + claim.ownerMutationId(), + claim.ownerFence()))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); + assertThatThrownBy( + () -> + mismatched.currentOriginalAttempt( + currentAttemptRequest( + tuple, + claim.ownerAttemptId(), + UUID.fromString("2819a1ce-04d2-4e3f-bb64-4a672d4eb711"), + claim.ownerFence()))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); + assertThatThrownBy( + () -> + mismatched.currentOriginalAttempt( + currentAttemptRequest( + tuple, + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.ownerFence() + 1L))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); + StartSessionPostAuthorizationExecutionTuple changedTuple = + tuple(tuple.controlPlaneRequestId(), "different complete action"); + assertThatThrownBy( + () -> mismatched.currentOriginalAttempt(currentAttemptRequest(changedTuple, claim))) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class); + assertThat(mismatched.ownerAttemptRowJson(tuple.controlPlaneRequestId())).isEqualTo(before); + + Fixture expired = fixture(Duration.ofMillis(500)); + StartSessionPostAuthorizationExecutionTuple expiredTuple = + tuple("current-attempt-read-lease-expired"); + AttemptClaim expiredClaim = expired.reserve(expiredTuple).claim().orElseThrow(); + expired.attach( + expiredClaim, + projection( + expiredTuple.authorizationReferenceFingerprint(), + expiredTuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + Thread.sleep(750L); + String expiredBefore = expired.ownerAttemptRowJson(expiredTuple.controlPlaneRequestId()); + assertThat(expired.leaseExpired(expiredTuple.controlPlaneRequestId())).isTrue(); + assertThatThrownBy( + () -> expired.currentOriginalAttempt(currentAttemptRequest(expiredTuple, expiredClaim))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("expired"); + assertThat(expired.ownerAttemptRowJson(expiredTuple.controlPlaneRequestId())) + .isEqualTo(expiredBefore); + } + + @Test + void currentOriginalAttemptReadRejectsExpiredAccountReferenceWithLiveClaimWithoutMutation() { + Fixture fixture = fixture(Duration.ofMinutes(1)); + StartSessionPostAuthorizationExecutionTuple tuple = + tuple( + "current-attempt-read-reference-expired", + "canonical StartSession owner attempt", + RESERVATION_OWNER, + 19L, + FINGERPRINT, + Instant.now().truncatedTo(ChronoUnit.MILLIS).minusSeconds(5)); + AttemptClaim claim = fixture.reserve(tuple).claim().orElseThrow(); + fixture.attach( + claim, + projection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L)); + String before = fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId()); + assertThat(fixture.leaseExpired(tuple.controlPlaneRequestId())).isFalse(); + + assertThatThrownBy(() -> fixture.currentOriginalAttempt(currentAttemptRequest(tuple, claim))) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("authorization reference expired"); + + assertThat(fixture.leaseExpired(tuple.controlPlaneRequestId())).isFalse(); + assertThat(fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId())).isEqualTo(before); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String requestId) { + return tuple(requestId, "canonical StartSession owner attempt"); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, String auditReason) { + return tuple(requestId, auditReason, RESERVATION_OWNER, 19L); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, String auditReason, UUID reservationOwner, long reservationFence) { + return tuple(requestId, auditReason, reservationOwner, reservationFence, FINGERPRINT); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, + String auditReason, + UUID reservationOwner, + long reservationFence, + String fingerprint) { + return tuple( + requestId, + auditReason, + reservationOwner, + reservationFence, + fingerprint, + Instant.parse("2099-01-01T00:05:00Z")); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, + String auditReason, + UUID reservationOwner, + long reservationFence, + String fingerprint, + Instant authorityExpiresAt) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + WORKLOAD, + fingerprint, + reservationOwner, + reservationFence, + bundle(pre, "17", "sha256:" + "a".repeat(64), authorityExpiresAt), + reference("17")); + } + + private static AccountRedemptionProjection projection( + String fingerprint, byte[] bundle, UUID issuanceOperationId, long issuanceFence) { + return new AccountRedemptionProjection(fingerprint, bundle, issuanceOperationId, issuanceFence); + } + + private static Request currentAttemptRequest( + StartSessionPostAuthorizationExecutionTuple tuple, AttemptClaim claim) { + return currentAttemptRequest( + tuple, claim.ownerAttemptId(), claim.ownerMutationId(), claim.ownerFence()); + } + + private static Request currentAttemptRequest( + StartSessionPostAuthorizationExecutionTuple tuple, + UUID expectedAttemptId, + UUID expectedMutationId, + long expectedFence) { + return new Request( + UUID.fromString("01111111-1111-4111-8111-111111111111"), + NAMESPACE, + tuple.canonicalBytes(), + expectedAttemptId, + expectedMutationId, + expectedFence); + } + + private static byte[] bundle( + StartSessionPreAuthorizationReservationTuple tuple, + String version, + String sourceEvidenceId, + Instant authorityExpiresAt) { + String tenantId = tuple.action().scope().tenantId().toString(); + String targetNamespace = tuple.action().scope().targetNamespace(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + sourceEvidenceId, + "sourceEvidenceVersion", + version, + "projectionStatus", + "CURRENT", + "evaluatedAt", + "1999-01-01T00:00:00Z", + "expiresAt", + authorityExpiresAt.toString()); + Map identity = + Map.of( + "issuanceOperationId", + ISSUANCE_ID.toString(), + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", + tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 2L, + "tenantAuthorityGeneration", + Map.of(tenantId, 3L), + "membershipAuthorityGeneration", + Map.of(tenantId, 4L), + "privateRealmGrantVersions", + List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", targetNamespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException(exception); + } + } + + private static StartSessionAuthorityEvidenceBundle.BundleReference reference(String version) { + return new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, version, "23", "18446744073709551615"); + } + + private static Fixture fixture(Duration claimLease) { + String schema = "gs_current_attempt_read_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway flyway = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load(); + flyway.migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + String latestVersion = + Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT version FROM flyway_schema_history WHERE success " + + "ORDER BY installed_rank DESC LIMIT 1"), + "Game Session migration history has no successful version") + .get("version", String.class)); + assertThat(latestVersion).isEqualTo("35"); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + GameSessionStartSessionOperatorAttemptRepository repository = + new GameSessionStartSessionOperatorAttemptRepository(dsl, claimLease); + return new Fixture(dsl, transactions, repository); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactions, + GameSessionStartSessionOperatorAttemptRepository repository) { + ReservationResult reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + return Objects.requireNonNull( + transactions.execute(status -> repository.reserve(tuple)), + "StartSession attempt reservation result"); + } + + AttemptSnapshot attach(AttemptClaim claim, AccountRedemptionProjection projection) { + return Objects.requireNonNull( + transactions.execute( + status -> repository.attachAccountRedemptionProjection(claim, projection)), + "StartSession attempt projection snapshot"); + } + + AttemptSnapshot currentOriginalAttempt(Request request) { + return Objects.requireNonNull( + transactions.execute(status -> repository.readCurrentOriginalAttempt(request)), + "Current original StartSession attempt snapshot"); + } + + String ownerAttemptRowJson(String requestId) { + org.jooq.Record row = + dsl.fetchOne( + "SELECT to_jsonb(attempt)::text FROM " + + "game_session_start_session_operator_attempt AS attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + requestId); + return Objects.requireNonNull( + Objects.requireNonNull(row, "persisted owner attempt row").get(0, String.class), + "persisted owner attempt row JSON"); + } + + boolean leaseExpired(String requestId) { + var row = + dsl.fetchOne( + "SELECT lease_expires_at <= clock_timestamp() AS expired " + + "FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + requestId); + if (row == null) { + throw new IllegalStateException("persisted owner attempt row missing while checking lease"); + } + return Boolean.TRUE.equals(row.get("expired", Boolean.class)); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java new file mode 100644 index 0000000000..7036635b98 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java @@ -0,0 +1,77 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionStartSessionOperatorAttemptRepositoryTest { + @AfterEach + void clearTransactionSynchronization() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsCallsOutsideWritableOwnerTransactionBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionOperatorAttemptRepository repository = + new GameSessionStartSessionOperatorAttemptRepository(dsl, java.time.Duration.ofSeconds(30)); + + assertThatThrownBy(() -> repository.reserve(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable READ COMMITTED"); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsReadOnlyOwnerTransactionBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionOperatorAttemptRepository repository = + new GameSessionStartSessionOperatorAttemptRepository(dsl, java.time.Duration.ofSeconds(30)); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy(() -> repository.reserve(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable READ COMMITTED"); + + verifyNoInteractions(dsl); + } + + @Test + void currentOriginalAttemptReadRequiresTheCallerOwnedReadCommittedTransaction() { + DSLContext dsl = mock(DSLContext.class); + GameSessionStartSessionOperatorAttemptRepository repository = + new GameSessionStartSessionOperatorAttemptRepository(dsl, java.time.Duration.ofSeconds(30)); + + assertThatThrownBy(() -> repository.readCurrentOriginalAttempt(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable READ COMMITTED"); + + verifyNoInteractions(dsl); + } + + @Test + void requiresAnExplicitlyBoundedClaimLease() { + DSLContext dsl = mock(DSLContext.class); + + assertThatThrownBy( + () -> + new GameSessionStartSessionOperatorAttemptRepository(dsl, java.time.Duration.ZERO)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive and at most five minutes"); + assertThatThrownBy( + () -> + new GameSessionStartSessionOperatorAttemptRepository( + dsl, java.time.Duration.ofMinutes(6))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive and at most five minutes"); + + verifyNoInteractions(dsl); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcServiceTest.java new file mode 100644 index 0000000000..5a1a551770 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcServiceTest.java @@ -0,0 +1,459 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadGrpcService; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import tools.jackson.databind.json.JsonMapper; + +class OriginalStartSessionCurrentAttemptReadGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID READ_ID = UUID.fromString("01111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT = UUID.fromString("02222222-2222-4222-8222-222222222222"); + private static final UUID MUTATION = UUID.fromString("03333333-3333-4333-8333-333333333333"); + private static final long FENCE = 8L; + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void returnsExactPendingSnapshotWithoutMutationRenewalOrRetry() { + Request request = request(NAMESPACE); + byte[] projection = canonicalProjection(request); + Instant leaseExpiry = Instant.parse("2030-01-01T00:00:00.123456789Z"); + AttemptSnapshot snapshot = snapshot(request, leaseExpiry, projection); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + when(repository.readCurrentOriginalAttempt(request)).thenReturn(snapshot); + var service = newService(repository, NAMESPACE); + + RecordingObserver observer = + invokeAs( + service, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request), + "account-service"); + + assertThat(observer.error()).isNull(); + assertThat(observer.completed()).isTrue(); + var decoded = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, observer.response()); + assertThat(decoded.phaseState()).isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(decoded.originalLeaseExpiresAt()).isEqualTo(leaseExpiry); + assertThat(decoded.accountRedemptionProjection()).containsExactly(projection); + assertThat(observer.response().getRequest()) + .isEqualTo(OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request)); + verify(repository).readCurrentOriginalAttempt(request); + verifyNoMoreInteractions(repository); + } + + @Test + void rejectsUnknownAndMalformedRequestsBeforeStorageAndAuthenticatesPeerBeforeDecode() { + Request request = request(NAMESPACE); + var wire = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request); + var unknown = + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + var service = newService(repository, NAMESPACE); + + assertThat(invokeAs(service, unknown, "account-service").status()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + // The same malformed bytes from a disallowed peer must fail at authentication first. + assertThat(invokeAs(service, unknown, "world-management-service").status()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + invokeAs(service, wire.toBuilder().setExpectedOwnerFence(0L).build(), "account-service") + .status()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void rejectsWrongTargetNamespaceAndEndUserContextBeforeStorage() { + Request otherNamespace = request("other-runtime"); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + var service = newService(repository, NAMESPACE); + var wrongNamespace = + invokeAs( + service, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(otherNamespace), + "account-service"); + assertThat(wrongNamespace.status()).isEqualTo(Status.Code.PERMISSION_DENIED); + + var endUser = + invokeAsWithEndUser( + service, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request(NAMESPACE))); + assertThat(endUser.status()).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void rejectsChangedAttemptMutationFenceTupleOrPhaseReturnedByRepository() { + Request request = request(NAMESPACE); + byte[] exactProjection = canonicalProjection(request); + AttemptSnapshot changedAttempt = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), exactProjection); + when(changedAttempt.ownerAttemptId()).thenReturn(uuid("04444444-4444-4444-8444-444444444444")); + AttemptSnapshot changedMutation = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), exactProjection); + when(changedMutation.ownerMutationId()) + .thenReturn(uuid("05555555-5555-4555-8555-555555555555")); + AttemptSnapshot changedFence = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), exactProjection); + when(changedFence.ownerFence()).thenReturn(FENCE + 1); + AttemptSnapshot changedTuple = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), exactProjection); + when(changedTuple.postAuthorizationExecutionTuple()).thenReturn(new byte[] {4}); + AttemptSnapshot changedPhase = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), exactProjection); + when(changedPhase.phaseState()).thenReturn("COMMITTED"); + AttemptSnapshot changedProjection = + snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), new byte[] {2}); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + when(repository.readCurrentOriginalAttempt(ArgumentMatchers.any(Request.class))) + .thenReturn( + changedAttempt, + changedMutation, + changedFence, + changedTuple, + changedPhase, + changedProjection); + var service = newService(repository, NAMESPACE); + AttemptSnapshot[] mismatches = { + changedAttempt, changedMutation, changedFence, changedTuple, changedPhase, changedProjection + }; + for (int index = 0; index < mismatches.length; index++) { + Request freshRequest = + request( + NAMESPACE, uuid(String.format("%08d-4444-4444-8444-%012d", index + 1, index + 1))); + assertThat( + invokeAs( + service, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(freshRequest), + "account-service") + .status()) + .isEqualTo(Status.Code.INTERNAL); + } + verify(repository, org.mockito.Mockito.times(6)) + .readCurrentOriginalAttempt(ArgumentMatchers.any(Request.class)); + verifyNoMoreInteractions(repository); + } + + @Test + void expiredOriginalLeaseRemainsReadOnlyAndReturnsFailedPrecondition() { + Request request = request(NAMESPACE); + GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); + when(repository.readCurrentOriginalAttempt(request)) + .thenThrow( + new StaleStartSessionOperatorAttemptClaimException( + "Game Session owner attempt claim lease is expired")); + var service = newService(repository, NAMESPACE); + + var observer = + invokeAs( + service, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request), + "account-service"); + + assertThat(observer.status()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.response()).isNull(); + verify(repository).readCurrentOriginalAttempt(request); + verifyNoMoreInteractions(repository); + } + + private static OriginalStartSessionCurrentAttemptReadGrpcService newService( + GameSessionStartSessionOperatorAttemptRepository repository, String namespace) { + return new OriginalStartSessionCurrentAttemptReadGrpcService( + repository, immediateTransactionManager(), namespace); + } + + private static PlatformTransactionManager immediateTransactionManager() { + return new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + }; + } + + private static GameSessionStartSessionOperatorAttemptRepository mockRepository() { + return mock(GameSessionStartSessionOperatorAttemptRepository.class); + } + + private static AttemptSnapshot snapshot(Request request, Instant expiry, byte[] projection) { + AttemptSnapshot snapshot = mock(AttemptSnapshot.class); + when(snapshot.targetNamespace()).thenReturn(request.targetNamespace()); + when(snapshot.controlPlaneRequestId()) + .thenReturn(request.originalTuple().controlPlaneRequestId()); + when(snapshot.canonicalTenantId()) + .thenReturn(request.originalTuple().preAuthorizationTuple().action().scope().tenantId()); + when(snapshot.ownerAttemptId()).thenReturn(request.expectedOwnerAttemptId()); + when(snapshot.ownerMutationId()).thenReturn(request.expectedOwnerMutationId()); + when(snapshot.ownerFence()).thenReturn(request.expectedOwnerFence()); + when(snapshot.phaseState()) + .thenReturn(OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE); + when(snapshot.postAuthorizationExecutionTuple()) + .thenReturn(request.canonicalPostAuthorizationTuple()); + when(snapshot.leaseExpiresAt()).thenReturn(expiry); + when(snapshot.accountRedemptionProjection()).thenReturn(projection.clone()); + return snapshot; + } + + private static byte[] canonicalProjection(Request request) { + var tuple = request.originalTuple(); + var authority = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + return new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())) + .canonicalBytes(); + } + + private static Request request(String namespace) { + return request(namespace, READ_ID); + } + + private static Request request(String namespace, UUID readRequestId) { + return new Request( + readRequestId, namespace, tuple(namespace).canonicalBytes(), ATTEMPT, MUTATION, FENCE); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String namespace) { + UUID tenant = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + UUID actor = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + UUID targetOwner = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwner = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + UUID issuanceId = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + UUID tokenJti = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + String fingerprint = "arfp/v1/test-key/" + "b".repeat(64); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "current-attempt-service-test", + actor, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenant, namespace), + new StartSessionOperatorAction.Target(91L, targetOwner), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical StartSession owner attempt")); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actor.toString(), + "controlUiTokenJti", + tokenJti.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + String tenantId = tenant.toString(); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", namespace), + "actionFamily", pre.actionFamily(), + "applicableAccountId", actor.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", issuanceId.toString(), + "controlPlaneRequestId", pre.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + pre.controlPlaneRequestId()), + "mutationDigest", pre.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + byte[] authorityBytes; + try { + authorityBytes = + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(bundle)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + fingerprint, + reservationOwner, + 19L, + authorityBytes, + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static RecordingObserver invokeAs( + OriginalStartSessionCurrentAttemptReadGrpcService service, + ReadOriginalStartSessionCurrentAttemptRequest request, + String serviceName) { + return invokeWithPeer(service, request, serviceName, NAMESPACE, false); + } + + private static RecordingObserver + invokeAsWithEndUser( + OriginalStartSessionCurrentAttemptReadGrpcService service, + ReadOriginalStartSessionCurrentAttemptRequest request) { + return invokeWithPeer(service, request, "account-service", NAMESPACE, true); + } + + private static RecordingObserver invokeWithPeer( + OriginalStartSessionCurrentAttemptReadGrpcService service, + ReadOriginalStartSessionCurrentAttemptRequest request, + String serviceName, + String namespace, + boolean endUser) { + var peer = + new net.firedevops.firemud.common.grpc.GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + serviceName, namespace, serviceName); + Context context = + Context.current() + .withValue(net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + if (endUser) { + SessionContext.setContext("42", List.of("tenantAdmin"), Map.of()); + } + RecordingObserver observer = + new RecordingObserver<>(); + service.readOriginalStartSessionCurrentAttempt(request, observer); + return observer; + } finally { + context.detach(previous); + SessionContext.clear(); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class RecordingObserver implements StreamObserver { + private final AtomicReference response = new AtomicReference<>(); + private final AtomicReference error = new AtomicReference<>(); + private volatile boolean completed; + + @Override + public void onNext(T value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() { + completed = true; + } + + T response() { + return response.get(); + } + + Throwable error() { + return error.get(); + } + + boolean completed() { + return completed; + } + + Status.Code status() { + Throwable failure = error.get(); + return failure instanceof StatusRuntimeException statusFailure + ? statusFailure.getStatus().getCode() + : null; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuardTest.java new file mode 100644 index 0000000000..bb3edc3526 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuardTest.java @@ -0,0 +1,79 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadWorkloadGuard; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class OriginalStartSessionCurrentAttemptReadWorkloadGuardTest { + private static final String NAMESPACE = "gameplay"; + private final OriginalStartSessionCurrentAttemptReadWorkloadGuard guard = + new OriginalStartSessionCurrentAttemptReadWorkloadGuard(NAMESPACE); + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void allowsOnlyExactSameNamespaceAccountWorkloadWithoutEndUserContext() { + assertThatCode( + () -> + withPeer( + "account-service", + NAMESPACE, + () -> { + guard.requireAccountCurrentAttemptReadCaller(); + guard.requireConfiguredTargetNamespace(NAMESPACE); + })) + .doesNotThrowAnyException(); + } + + @Test + void refusesWrongNamespaceWrongServiceEndUserContextAndTargetNamespace() { + assertThatThrownBy( + () -> + withPeer("account-service", "other", guard::requireAccountCurrentAttemptReadCaller)) + .isInstanceOf(AdminAuthorizationException.class); + assertThatThrownBy( + () -> + withPeer( + "world-management-service", + NAMESPACE, + guard::requireAccountCurrentAttemptReadCaller)) + .isInstanceOf(AdminAuthorizationException.class); + assertThatThrownBy( + () -> + withPeer( + "account-service", + NAMESPACE, + () -> { + SessionContext.setContext( + "42", java.util.List.of("tenantAdmin"), java.util.Map.of()); + guard.requireAccountCurrentAttemptReadCaller(); + })) + .isInstanceOf(AdminAuthorizationException.class); + assertThatThrownBy(() -> guard.requireConfiguredTargetNamespace("other")) + .isInstanceOf(AdminAuthorizationException.class); + } + + private static void withPeer(String service, String namespace, 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); + SessionContext.clear(); + } + } +} diff --git a/services/logging-admin-service/build.gradle.kts b/services/logging-admin-service/build.gradle.kts index c3da9c94a7..8239daaaeb 100644 --- a/services/logging-admin-service/build.gradle.kts +++ b/services/logging-admin-service/build.gradle.kts @@ -23,3 +23,18 @@ dependencies { testFixturesImplementation(libs.spring.boot.starter.test) testFixturesImplementation(libs.testcontainers.postgresql) } + +// Opt-in cross-owner proof: exclude Logging application and migration resources from Account. +val loggingStartSessionClaimProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("start-session-claim-proof") + dependsOn(tasks.named("classes"), tasks.named("testFixturesClasses")) + from(sourceSets.main.get().output.classesDirs) + from(sourceSets["testFixtures"].output.classesDirs) +} + +val loggingStartSessionClaimProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(loggingStartSessionClaimProofJar) +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java index 5a0091717b..2b1e102308 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java @@ -2,30 +2,56 @@ import jakarta.annotation.PostConstruct; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; 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.BlockingGrpcStubCustomizer; 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.common.grpc.GrpcTlsMaterialResolver; +import net.firedevops.firemud.common.grpc.ResolvedGrpcTlsMaterial; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionRequest; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionResponse; import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; import net.firedevops.firemud.gamesession.v1.PingRequest; import net.firedevops.firemud.gamesession.v1.PingResponse; +import net.firedevops.firemud.gamesession.v1.StartSessionOwnerAuthorizationProgress; import net.firedevops.firemud.gamesession.v1.StopSessionRequest; import net.firedevops.firemud.gamesession.v1.StopSessionResponse; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.TransientOwnerExecutionHandoff; import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** gRPC client for communicating with the Game Session Service. */ @Component public class GameSessionClient extends AbstractReloadingBlockingGrpcClient< GameSessionServiceGrpc.GameSessionServiceBlockingStub> { + private static final long START_SESSION_HANDOFF_DEADLINE_SECONDS = 5L; + private static final Pattern OPAQUE_OPERATOR_REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + + private final CommonGrpcClientProperties transportTlsProperties; + public GameSessionClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProps, GrpcChannelFactory channelFactory, BlockingGrpcStubCustomizer stubCustomizer) { super(endpoints, tlsProps, channelFactory, stubCustomizer, GameSessionClient.class); + this.transportTlsProperties = tlsProps.copy(); } @PostConstruct @@ -61,4 +87,208 @@ public StopSessionResponse stopSession(long sessionId) { StopSessionRequest.newBuilder().setSessionId(Long.toString(sessionId)).build(); return stub().stopSession(request); } + + /** + * Sends the one transient handoff returned after Logging durably records owner-pending state. + * This method performs exactly one bounded RPC and never retries an ambiguous owner result. + */ + public StartSessionOwnerHandoffResult authorizeStartSession( + TransientOwnerExecutionHandoff handoff) { + requireNoAmbientSqlOrSynchronization(); + Objects.requireNonNull(handoff, "durable Logging owner handoff is required"); + StartSessionPostAuthorizationExecutionTuple tuple = handoff.postAuthorizationTuple(); + String reference = handoff.accountResponse().operatorAuthorizationReference(); + byte[] tupleBytes = tuple.canonicalBytes(); + if (tupleBytes.length == 0 + || tupleBytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || reference == null + || !OPAQUE_OPERATOR_REFERENCE.matcher(reference).matches() + || !tuple + .authenticatedWorkloadIdentity() + .equals(handoff.accountResponse().authenticatedLoggingWorkloadIdentity()) + || !tuple + .authorizationReferenceFingerprint() + .equals(handoff.accountResponse().authorizationReferenceFingerprint()) + || !tuple.bundleReference().equals(handoff.accountResponse().bundleReference()) + || !MessageDigest.isEqual( + tuple.authorityEvidenceBundleBytes(), + handoff.accountResponse().authorityEvidenceBundle())) { + throw new IllegalArgumentException("Logging StartSession handoff is not internally bound"); + } + String targetNamespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Logging StartSession handoff namespace is invalid"); + } + requireFileBackedMtls(); + String expectedServerUri = + "spiffe://firemud/ns/" + targetNamespace + "/sa/game-session-service"; + + AuthorizeStartSessionRequest request = + AuthorizeStartSessionRequest.newBuilder() + .setCanonicalPostAuthorizationExecutionTupleBytes( + com.google.protobuf.ByteString.copyFrom(tupleBytes)) + .setOperatorAuthorizationReference(reference) + .build(); + AuthorizeStartSessionResponse response; + try { + response = + Objects.requireNonNull(stub(), "Game Session client is not initialized") + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedServerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedServerUri)) + .withDeadlineAfter(START_SESSION_HANDOFF_DEADLINE_SECONDS, TimeUnit.SECONDS) + .authorizeStartSession(request); + } catch (io.grpc.StatusRuntimeException ambiguousTransportOutcome) { + throw new AmbiguousOwnerHandoffException(ambiguousTransportOutcome.getStatus().getCode()); + } + return validateOwnerHandoffResponse(tuple, response); + } + + private static void requireNoAmbientSqlOrSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Game Session owner handoff requires no ambient SQL or synchronization"); + } + } + + private void requireFileBackedMtls() { + if (transportTlsProperties.isPlaintext()) { + throw new IllegalStateException("StartSession owner handoff requires workload mTLS"); + } + ResolvedGrpcTlsMaterial material; + try { + material = new GrpcTlsMaterialResolver().resolve(transportTlsProperties); + } catch (IOException | RuntimeException ignored) { + throw new IllegalStateException( + "StartSession owner handoff requires readable file-backed workload mTLS"); + } + if (material == null + || !isReadableFile(material.certChain()) + || !isReadableFile(material.privateKey()) + || !isReadableFile(material.caCert())) { + throw new IllegalStateException( + "StartSession owner handoff requires readable file-backed workload mTLS"); + } + } + + private static boolean isReadableFile(ResolvedGrpcTlsMaterial.TlsResource resource) { + Path path = resource == null ? null : resource.watchPath(); + return path != null && Files.isRegularFile(path) && Files.isReadable(path); + } + + private static StartSessionOwnerHandoffResult validateOwnerHandoffResponse( + StartSessionPostAuthorizationExecutionTuple tuple, AuthorizeStartSessionResponse response) { + Objects.requireNonNull(response, "Game Session owner response is required"); + if (!response.getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException("Game Session returned an unknown owner-handoff response"); + } + if (response.hasError()) { + if (!response.getError().getUnknownFields().asMap().isEmpty()) { + throw new IllegalStateException("Game Session returned an unknown owner-handoff error"); + } + throw new OwnerHandoffRejectedException(response.getError().getCode()); + } + + StartSessionOwnerAuthorizationProgress progress = response.getProgress(); + boolean supportedProgress = + switch (progress) { + case START_SESSION_OWNER_AUTHORIZATION_PROGRESS_EXACT_REPLAY, + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS, + START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_PROJECTION_ATTACHED -> + true; + default -> false; + }; + if (!tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(response.getTargetNamespace()) + || !tuple.controlPlaneRequestId().equals(response.getControlPlaneRequestId()) + || !tuple.mutationDigest().equals(response.getMutationDigest()) + || !canonicalNonNilUuid(response.getOwnerAttemptId()) + || !canonicalNonNilUuid(response.getOwnerMutationId()) + || response.getOwnerFence() <= 0L + || !"OWNER_EXECUTION_PENDING".equals(response.getOwnerPhaseState()) + || !supportedProgress) { + throw new IllegalStateException("Game Session owner response does not match the handoff"); + } + return new StartSessionOwnerHandoffResult( + response.getTargetNamespace(), + response.getControlPlaneRequestId(), + response.getMutationDigest(), + UUID.fromString(response.getOwnerAttemptId()), + UUID.fromString(response.getOwnerMutationId()), + response.getOwnerFence(), + response.getOwnerPhaseState(), + progress); + } + + private static boolean canonicalNonNilUuid(String value) { + if (value == null || !CANONICAL_UUID.matcher(value).matches()) { + return false; + } + try { + UUID parsed = UUID.fromString(value); + return parsed.toString().equals(value) && !parsed.equals(new UUID(0L, 0L)); + } catch (IllegalArgumentException malformed) { + return false; + } + } + + /** Secret-free exact owner echo returned by the bounded StartSession handoff call. */ + public record StartSessionOwnerHandoffResult( + String targetNamespace, + String controlPlaneRequestId, + String mutationDigest, + UUID ownerAttemptId, + UUID ownerMutationId, + long ownerFence, + String ownerPhaseState, + StartSessionOwnerAuthorizationProgress progress) { + public StartSessionOwnerHandoffResult { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + Objects.requireNonNull(mutationDigest, "mutationDigest"); + Objects.requireNonNull(ownerAttemptId, "ownerAttemptId"); + Objects.requireNonNull(ownerMutationId, "ownerMutationId"); + Objects.requireNonNull(ownerPhaseState, "ownerPhaseState"); + Objects.requireNonNull(progress, "progress"); + } + } + + /** Transport ambiguity is surfaced without the raw request or authorization reference. */ + public static final class AmbiguousOwnerHandoffException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final io.grpc.Status.Code statusCode; + + private AmbiguousOwnerHandoffException(io.grpc.Status.Code statusCode) { + super("Game Session owner-handoff outcome is ambiguous; automatic retry was not attempted"); + this.statusCode = Objects.requireNonNull(statusCode, "statusCode"); + } + + public io.grpc.Status.Code statusCode() { + return statusCode; + } + } + + /** Bounded owner rejection code; no response body or transient reference is retained. */ + public static final class OwnerHandoffRejectedException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final String code; + + private OwnerHandoffRejectedException(String code) { + super("Game Session rejected the StartSession owner handoff"); + if (code == null || !code.matches("[A-Z][A-Z0-9_]{0,63}")) { + throw new IllegalArgumentException("owner rejection code is invalid"); + } + this.code = code; + } + + public String code() { + return code; + } + } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java new file mode 100644 index 0000000000..9369cfbd8e --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java @@ -0,0 +1,460 @@ +package net.firedevops.firemud.loggingadmin.client; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +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.common.grpc.GrpcTlsMaterialResolver; +import net.firedevops.firemud.common.grpc.ResolvedGrpcTlsMaterial; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicitly initialized, typed Logging & Admin transport to Account's StartSession issue/recover + * boundary. Issue invokes Account's authorization-issuance mutation; recovery retrieves only the + * exact original Account result. Neither operation activates a local route or authorizes local + * execution. Account owns both operations, and callers must establish the current Logging claim. + */ +public class StartSessionOperatorAuthorizationClient + extends AbstractReloadingBlockingGrpcClient< + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub> { + private static final int MAX_TUPLE_BYTES = 8 * 1_024; + private static final int MAX_REQUEST_BYTES = MAX_TUPLE_BYTES + 16 * 1_024 + 1_024; + private static final int MAX_RESPONSE_BYTES = + StartSessionAuthorityEvidenceBundle.MAX_BUNDLE_BYTES + 2_048; + private static final int MAX_CONTROL_UI_TOKEN_BYTES = 16 * 1_024; + private static final int MAX_REFERENCE_BYTES = 128; + private static final long RPC_DEADLINE_SECONDS = 5L; + private static final Duration MAX_REFERENCE_LIFETIME = Duration.ofMinutes(5); + private static final long MAX_PROTO_TIMESTAMP_SECONDS = 253_402_300_799L; + private static final Pattern OPAQUE_REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final Pattern REFERENCE_FINGERPRINT = + Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); + + private final Clock clock; + private final CommonGrpcClientProperties transportTlsProperties; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Construction validates and copies inputs only; managed channels and watchers are acquired by initialize().") + public StartSessionOperatorAuthorizationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer) { + this(endpoints, tlsProps, channelFactory, stubCustomizer, Clock.systemUTC()); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Construction validates and copies inputs only; managed channels and watchers are acquired by initialize().") + public StartSessionOperatorAuthorizationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + Clock clock) { + super( + endpoints, + tlsProps, + channelFactory, + stubCustomizer, + StartSessionOperatorAuthorizationClient.class); + this.clock = Objects.requireNonNull(clock, "clock is required"); + this.transportTlsProperties = + Objects.requireNonNull(tlsProps, "TLS properties are required").copy(); + } + + /** + * Opens the standard managed TLS channel only when an owning workflow explicitly initializes it. + */ + public void initialize() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + buildStub(io.grpc.ManagedChannel channel) { + return applyStubCustomizer( + StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(MAX_RESPONSE_BYTES) + .withMaxOutboundMessageSize(MAX_REQUEST_BYTES) + .withCompression("gzip")); + } + + /** Issues the original human tenant-admin reference using the current Logging claim tuple. */ + public AuthorizationReference issueHuman( + StartSessionPreAuthorizationReservationTuple tuple, + String controlUiJwt, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + requireNoAmbientSqlOrSynchronization(); + byte[] tupleBytes = canonicalTupleBytes(tuple); + requireVisibleAsciiToken(controlUiJwt); + requireOwnerFence(reservationOwnerId, reservationClaimFence, "reservation owner"); + requireOwnerFence(currentClaimOwnerId, currentClaimFence, "current claim owner"); + IssueHumanOperatorAuthorizationReferenceRequest request = + IssueHumanOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setControlUiJwt(controlUiJwt) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setCurrentClaimOwnerId(currentClaimOwnerId.toString()) + .setCurrentClaimFence(currentClaimFence) + .build(); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException( + "Account authorization request exceeds its supported bound"); + } + IssueHumanOperatorAuthorizationReferenceResponse response = + requirePinnedAccountStub(tuple.action().scope().targetNamespace()) + .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) + .issueHumanOperatorAuthorizationReference(request); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw malformedResponse(); + } + return validateResponse( + response.getOperatorAuthorizationReference(), + response.getAuthorizationReferenceFingerprint(), + response.hasExpiresAt(), + response.getExpiresAt(), + response.getAuthorityEvidenceBundle().toByteArray(), + response.hasBundleReference(), + response.getBundleReference(), + response.getUnknownFields().asMap().isEmpty(), + response.getAuthenticatedLoggingWorkloadIdentity(), + tuple); + } + + /** Looks up and recovers only the exact original issuance response under a fresh claim. */ + public AuthorizationReference recover( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + requireNoAmbientSqlOrSynchronization(); + byte[] tupleBytes = canonicalTupleBytes(tuple); + requireOwnerFence(reservationOwnerId, reservationClaimFence, "reservation owner"); + requireOwnerFence(currentClaimOwnerId, currentClaimFence, "current claim owner"); + RecoverOperatorAuthorizationReferenceRequest request = + RecoverOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setCurrentClaimOwnerId(currentClaimOwnerId.toString()) + .setCurrentClaimFence(currentClaimFence) + .build(); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException( + "Account authorization request exceeds its supported bound"); + } + RecoverOperatorAuthorizationReferenceResponse response = + requirePinnedAccountStub(tuple.action().scope().targetNamespace()) + .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) + .recoverOperatorAuthorizationReference(request); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw malformedResponse(); + } + return validateResponse( + response.getOperatorAuthorizationReference(), + response.getAuthorizationReferenceFingerprint(), + response.hasExpiresAt(), + response.getExpiresAt(), + response.getAuthorityEvidenceBundle().toByteArray(), + response.hasBundleReference(), + response.getBundleReference(), + response.getUnknownFields().asMap().isEmpty(), + response.getAuthenticatedLoggingWorkloadIdentity(), + tuple); + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + requireStub() { + var value = stub(); + if (value == null) { + throw new IllegalStateException("Account authorization client has not been initialized"); + } + return value; + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + requirePinnedAccountStub(String targetNamespace) { + String expectedServerUri = accountServerUri(targetNamespace); + requireFileBackedMtls(); + return requireStub() + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedServerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedServerUri)); + } + + static String accountServerUri(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("StartSession target namespace is invalid"); + } + return "spiffe://firemud/ns/" + targetNamespace + "/sa/account-service"; + } + + private void requireFileBackedMtls() { + if (transportTlsProperties.isPlaintext()) { + throw new IllegalStateException("Account authorization requires workload mTLS"); + } + ResolvedGrpcTlsMaterial material; + try { + material = new GrpcTlsMaterialResolver().resolve(transportTlsProperties); + } catch (IOException | RuntimeException ignored) { + throw new IllegalStateException( + "Account authorization requires readable file-backed workload mTLS"); + } + if (material == null + || !isReadableFile(material.certChain()) + || !isReadableFile(material.privateKey()) + || !isReadableFile(material.caCert())) { + throw new IllegalStateException( + "Account authorization requires readable file-backed workload mTLS"); + } + } + + private static boolean isReadableFile(ResolvedGrpcTlsMaterial.TlsResource resource) { + Path path = resource == null ? null : resource.watchPath(); + return path != null && Files.isRegularFile(path) && Files.isReadable(path); + } + + private AuthorizationReference validateResponse( + String opaqueReference, + String fingerprint, + boolean hasExpiry, + Timestamp expiryTimestamp, + byte[] authorityEvidenceBundle, + boolean hasBundleReference, + AuthorityEvidenceBundleReference wireReference, + boolean hasNoUnknownFields, + String authenticatedLoggingWorkloadIdentity, + StartSessionPreAuthorizationReservationTuple tuple) { + try { + if (!hasNoUnknownFields || !hasExpiry || !hasBundleReference) { + throw malformedResponse(); + } + requireAuthenticatedLoggingIdentity( + authenticatedLoggingWorkloadIdentity, tuple.action().scope().targetNamespace()); + if (!OPAQUE_REFERENCE.matcher(opaqueReference).matches() + || opaqueReference.getBytes(StandardCharsets.UTF_8).length > MAX_REFERENCE_BYTES + || !REFERENCE_FINGERPRINT.matcher(fingerprint).matches()) { + throw malformedResponse(); + } + if (!expiryTimestamp.getUnknownFields().asMap().isEmpty()) { + throw malformedResponse(); + } + Instant expiresAt = exactExpiry(expiryTimestamp); + Instant now = clock.instant(); + if (!expiresAt.isAfter(now)) { + throw new IllegalStateException("Account authorization response is expired"); + } + if (expiresAt.isAfter(now.plus(MAX_REFERENCE_LIFETIME))) { + throw malformedResponse(); + } + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundle); + bundle.requireTupleBinding(tuple); + if (!expiresAt.equals(bundle.expiresAt())) { + throw malformedResponse(); + } + StartSessionAuthorityEvidenceBundle.BundleReference reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + wireReference.getBundleVersion(), + wireReference.getSourceVersion(), + wireReference.getSourceFence(), + wireReference.getLinearization()); + bundle.requireReferenceBinding(reference); + if (!wireReference.getUnknownFields().asMap().isEmpty()) { + throw malformedResponse(); + } + return new AuthorizationReference( + opaqueReference, + fingerprint, + expiresAt, + authorityEvidenceBundle, + reference, + authenticatedLoggingWorkloadIdentity, + bundle); + } catch (IllegalStateException expected) { + throw expected; + } catch (RuntimeException malformed) { + throw malformedResponse(); + } + } + + private static Instant exactExpiry(Timestamp timestamp) { + long seconds = timestamp.getSeconds(); + int nanos = timestamp.getNanos(); + if (seconds <= 0L + || seconds > MAX_PROTO_TIMESTAMP_SECONDS + || nanos < 0 + || nanos >= 1_000_000_000 + || nanos % 1_000_000 != 0) { + throw malformedResponse(); + } + return Instant.ofEpochSecond(seconds, nanos); + } + + private static void requireAuthenticatedLoggingIdentity( + String identityText, String targetNamespace) { + GrpcPeerIdentity identity = + GrpcPeerIdentity.parseUri(identityText) + .orElseThrow(StartSessionOperatorAuthorizationClient::malformedResponse); + if (!identityText.equals(identity.uri()) + || !"logging-admin-service".equals(identity.service()) + || !targetNamespace.equals(identity.namespace())) { + throw malformedResponse(); + } + } + + private static byte[] canonicalTupleBytes(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + byte[] bytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + if (bytes.length == 0 || bytes.length > MAX_TUPLE_BYTES) { + throw new IllegalArgumentException("StartSession tuple exceeds its supported bound"); + } + return bytes; + } + + private static void requireVisibleAsciiToken(String token) { + if (token == null + || token.isEmpty() + || token.getBytes(StandardCharsets.UTF_8).length > MAX_CONTROL_UI_TOKEN_BYTES + || token.chars().anyMatch(value -> value < 0x21 || value > 0x7e)) { + throw new IllegalArgumentException("control-ui token is invalid or over its supported bound"); + } + } + + private static void requireNoAmbientSqlOrSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account authorization requires no ambient SQL or synchronization"); + } + } + + private static void requireOwnerFence(UUID owner, long fence, String field) { + if (owner == null || owner.equals(new UUID(0L, 0L)) || fence <= 0L) { + throw new IllegalArgumentException(field + " and positive fence are required"); + } + } + + private static IllegalStateException malformedResponse() { + return new IllegalStateException( + "Account returned a malformed StartSession authorization response"); + } + + /** Response identity with defensive bundle bytes and a redacted diagnostic representation. */ + public static final class AuthorizationReference { + private final String operatorAuthorizationReference; + private final String authorizationReferenceFingerprint; + private final Instant expiresAt; + private final byte[] authorityEvidenceBundle; + private final StartSessionAuthorityEvidenceBundle.BundleReference bundleReference; + private final String authenticatedLoggingWorkloadIdentity; + private final StartSessionAuthorityEvidenceBundle decodedBundle; + + private AuthorizationReference( + String operatorAuthorizationReference, + String authorizationReferenceFingerprint, + Instant expiresAt, + byte[] authorityEvidenceBundle, + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference, + String authenticatedLoggingWorkloadIdentity, + StartSessionAuthorityEvidenceBundle decodedBundle) { + this.operatorAuthorizationReference = operatorAuthorizationReference; + this.authorizationReferenceFingerprint = authorizationReferenceFingerprint; + this.expiresAt = expiresAt; + this.authorityEvidenceBundle = authorityEvidenceBundle.clone(); + this.bundleReference = bundleReference; + this.authenticatedLoggingWorkloadIdentity = authenticatedLoggingWorkloadIdentity; + this.decodedBundle = decodedBundle; + } + + public String operatorAuthorizationReference() { + return operatorAuthorizationReference; + } + + public String authorizationReferenceFingerprint() { + return authorizationReferenceFingerprint; + } + + public Instant expiresAt() { + return expiresAt; + } + + public byte[] authorityEvidenceBundle() { + return authorityEvidenceBundle.clone(); + } + + public StartSessionAuthorityEvidenceBundle.BundleReference bundleReference() { + return bundleReference; + } + + /** Account's exact authenticated Logging peer identity echoed after successful verification. */ + public String authenticatedLoggingWorkloadIdentity() { + return authenticatedLoggingWorkloadIdentity; + } + + public StartSessionAuthorityEvidenceBundle decodedBundle() { + return decodedBundle; + } + + @Override + public String toString() { + return "AuthorizationReference[operatorAuthorizationReference=, " + + "authorizationReferenceFingerprint=, expiresAt=" + + expiresAt + + ", authorityEvidenceBundle=, bundleReference=" + + bundleReference + + ", authenticatedLoggingWorkloadIdentity=" + + authenticatedLoggingWorkloadIdentity + + "]"; + } + } +} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java new file mode 100644 index 0000000000..d585e513af --- /dev/null +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java @@ -0,0 +1,753 @@ +package net.firedevops.firemud.loggingadmin.operator; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.loggingadmin.client.GameSessionClient; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient.AuthorizationReference; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Acquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizationCompletion; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizedSnapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimEvidence; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimHandle; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionTransition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.PendingTransition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.RecoveryAcquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Coordinates Account authorization and durably records the owner handoff without activating an + * ingress. Explicit dispatch methods forward only a newly committed owner-pending handoff. + * + *

The Account issue call occurs only after the original claim wins the durable pending + * transition. The Account recovery call is read-only and uses a fresh recovery claim. A transient + * owner payload is returned only after both the Account response and the OWNER_EXECUTION_PENDING + * handoff are durable; neither the raw reference nor the forwarded control-ui token is persisted or + * logged here. + */ +public final class StartSessionAuthorizationCoordinator { + private static final int MAX_CONTROL_UI_JWT_BYTES = 16 * 1024; + private static final Pattern OPAQUE_REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final JsonMapper JWT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> JSON_OBJECT = new TypeReference<>() {}; + + private final String configuredNamespace; + private final StartSessionPreAuthorizationReservationService reservations; + private final StartSessionOperatorAuthorizationClient accountClient; + + public StartSessionAuthorizationCoordinator( + String configuredNamespace, + StartSessionPreAuthorizationReservationService reservations, + StartSessionOperatorAuthorizationClient accountClient) { + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("A valid configured workload namespace is required"); + } + this.configuredNamespace = configuredNamespace; + this.reservations = Objects.requireNonNull(reservations, "reservation service is required"); + this.accountClient = Objects.requireNonNull(accountClient, "Account client is required"); + } + + /** Derives the original actor from the current authenticated tenant-admin request context. */ + public Result begin( + String controlPlaneRequestId, + StartSessionOperatorAction action, + String originalControlUiJwt) { + Objects.requireNonNull(action, "typed StartSession action is required"); + String stableRequestId = + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + requireConfiguredNamespace(action); + requireCompactJwtEnvelope(originalControlUiJwt); + // The verified Logging context binds the claimed original actor, but Account alone validates + // the forwarded ControlUI token's current authorization and signature. + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + stableRequestId, action); + return issueHuman(tuple, originalControlUiJwt); + } + + /** Begins human issuance only for the first reservation owner that wins AUTHORIZATION_PENDING. */ + public Result issueHuman( + StartSessionPreAuthorizationReservationTuple tuple, String controlUiJwt) { + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + requireConfiguredNamespace(tuple.action()); + requireCompactJwtEnvelope(controlUiJwt); + StartSessionPreAuthorizationReservationTuple currentTuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + tuple.controlPlaneRequestId(), tuple.action()); + if (!currentTuple.canonicalJson().equals(tuple.canonicalJson())) { + throw new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + return issueHumanFromCurrentContext(currentTuple, controlUiJwt); + } + + private Result issueHumanFromCurrentContext( + StartSessionPreAuthorizationReservationTuple tuple, String controlUiJwt) { + Acquisition acquisition = reservations.acquire(tuple); + Snapshot acquiredSnapshot = acquisition.snapshot(); + requireSnapshotTuple(acquiredSnapshot, tuple); + if (!acquisition.newlyAcquired()) { + return observeExisting(tuple, acquiredSnapshot); + } + + ClaimHandle claim = acquisition.claim(); + if (claim == null || !claimMatchesOriginalReservation(claim, tuple)) { + return Result.outcomeUnknown(acquiredSnapshot, PendingReason.RESERVATION_CLAIM_MISMATCH); + } + + PendingTransition pending; + try { + pending = reservations.markAuthorizationPending(claim); + } catch (RuntimeException transitionFailure) { + return Result.outcomeUnknown( + acquiredSnapshot, PendingReason.PENDING_TRANSITION_OUTCOME_UNKNOWN); + } + if (pending == null || pending.snapshot() == null) { + return Result.outcomeUnknown( + acquiredSnapshot, PendingReason.PENDING_TRANSITION_OUTCOME_UNKNOWN); + } + Snapshot pendingSnapshot = pending.snapshot(); + if (!pending.mayDispatchAccountAuthorization()) { + return observeExisting(tuple, pendingSnapshot); + } + if (!isExactPendingSnapshot(pendingSnapshot, tuple, claim)) { + return Result.outcomeUnknown( + pendingSnapshot, PendingReason.PENDING_TRANSITION_OUTCOME_UNKNOWN); + } + + ClaimEvidence claimEvidence = claim.claimEvidence(); + AuthorizationReference accountResponse; + try { + accountResponse = + accountClient.issueHuman( + sharedTuple(tuple), + controlUiJwt, + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence()); + } catch (RuntimeException ambiguousOrFailedCall) { + return Result.outcomeUnknown(pendingSnapshot, PendingReason.ACCOUNT_ISSUANCE_OUTCOME_UNKNOWN); + } + return persistExactAccountResponse(tuple, claim, accountResponse, pendingSnapshot); + } + + /** Issues the human reference and forwards only this invocation's durable owner-pending win. */ + public OwnerDispatchResult issueHumanAndDispatch( + StartSessionPreAuthorizationReservationTuple tuple, + String controlUiJwt, + GameSessionClient ownerClient) { + Objects.requireNonNull(ownerClient, "Game Session owner client is required"); + return dispatchOwnerPending(issueHuman(tuple, controlUiJwt), ownerClient); + } + + /** Recovers only the original issuance response under a fresh read-only recovery claim. */ + public Result recover(StartSessionPreAuthorizationReservationTuple tuple) { + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + requireConfiguredNamespace(tuple.action()); + Optional acquired = reservations.acquireAuthorizationRecoveryClaim(tuple); + if (acquired.isEmpty()) { + return Result.recoveryUnavailable(); + } + + ClaimHandle claim = acquired.orElseThrow().claim(); + ClaimEvidence claimEvidence = claim.claimEvidence(); + AuthorizationReference accountResponse; + try { + accountResponse = + accountClient.recover( + sharedTuple(tuple), + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence()); + } catch (RuntimeException ambiguousOrFailedCall) { + return Result.outcomeUnknown( + acquired.orElseThrow().snapshot(), PendingReason.ACCOUNT_RECOVERY_OUTCOME_UNKNOWN); + } + return persistExactAccountResponse( + tuple, claim, accountResponse, acquired.orElseThrow().snapshot()); + } + + /** Recovers the original reference and forwards only a newly persisted owner-pending handoff. */ + public OwnerDispatchResult recoverAndDispatch( + StartSessionPreAuthorizationReservationTuple tuple, GameSessionClient ownerClient) { + Objects.requireNonNull(ownerClient, "Game Session owner client is required"); + return dispatchOwnerPending(recover(tuple), ownerClient); + } + + private static OwnerDispatchResult dispatchOwnerPending( + Result authorization, GameSessionClient ownerClient) { + Objects.requireNonNull(authorization, "authorization result is required"); + Objects.requireNonNull(ownerClient, "Game Session owner client is required"); + if (authorization.progress() != Progress.OWNER_EXECUTION_PENDING) { + return new OwnerDispatchResult(authorization.progress(), Optional.empty()); + } + GameSessionClient.StartSessionOwnerHandoffResult ownerEcho = + Objects.requireNonNull( + ownerClient.authorizeStartSession(authorization.handoff()), + "Game Session owner echo is required"); + return new OwnerDispatchResult(authorization.progress(), Optional.of(ownerEcho)); + } + + private Result persistExactAccountResponse( + StartSessionPreAuthorizationReservationTuple tuple, + ClaimHandle claim, + AuthorizationReference accountResponse, + Snapshot lastKnownSnapshot) { + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple; + String transientReference; + try { + if (accountResponse == null) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + transientReference = accountResponse.operatorAuthorizationReference(); + ClaimEvidence claimEvidence = claim.claimEvidence(); + if (transientReference == null || !OPAQUE_REFERENCE.matcher(transientReference).matches()) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + String expectedWorkloadIdentity = + "spiffe://firemud/ns/" + configuredNamespace + "/sa/logging-admin-service"; + if (!expectedWorkloadIdentity.equals( + accountResponse.authenticatedLoggingWorkloadIdentity())) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + postAuthorizationTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + sharedTuple(tuple), + accountResponse.authenticatedLoggingWorkloadIdentity(), + accountResponse.authorizationReferenceFingerprint(), + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + accountResponse.authorityEvidenceBundle(), + accountResponse.bundleReference()); + if (!isExactAccountResult(tuple, claimEvidence, accountResponse, postAuthorizationTuple)) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + } catch (RuntimeException invalidResponse) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + + AuthorizationCompletion completion; + try { + completion = reservations.completeAuthorization(claim, postAuthorizationTuple); + } catch (RuntimeException localCompletionFailure) { + return Result.outcomeUnknown( + lastKnownSnapshot, PendingReason.LOCAL_COMPLETION_OUTCOME_UNKNOWN); + } + if (completion == null || completion.snapshot() == null) { + return Result.outcomeUnknown( + lastKnownSnapshot, PendingReason.LOCAL_COMPLETION_OUTCOME_UNKNOWN); + } + if (!completion.transitioned()) { + return observeExisting(tuple, completion.snapshot().reservationSnapshot()); + } + ClaimEvidence claimEvidence = claim.claimEvidence(); + AuthorizedSnapshot completedSnapshot = completion.snapshot(); + if (!isExactAuthorizedSnapshot( + completedSnapshot, tuple, claim, claimEvidence, postAuthorizationTuple)) { + return Result.outcomeUnknown( + completedSnapshot.reservationSnapshot(), PendingReason.LOCAL_COMPLETION_RESULT_MISMATCH); + } + + Optional readback; + try { + readback = reservations.findAuthorizedExact(tuple); + } catch (RuntimeException readbackFailure) { + return Result.outcomeUnknown( + completedSnapshot.reservationSnapshot(), PendingReason.AUTHORIZATION_READBACK_UNKNOWN); + } + if (readback == null + || readback.isEmpty() + || !sameAuthorizedSnapshot(completedSnapshot, readback.orElseThrow()) + || !isExactAuthorizedSnapshot( + readback.orElseThrow(), tuple, claim, claimEvidence, postAuthorizationTuple)) { + return Result.outcomeUnknown( + completedSnapshot.reservationSnapshot(), PendingReason.AUTHORIZATION_READBACK_MISMATCH); + } + + OwnerExecutionHandoff handoff = new OwnerExecutionHandoff(UUID.randomUUID()); + OwnerExecutionTransition ownerTransition; + try { + ownerTransition = reservations.beginOwnerExecution(claim, postAuthorizationTuple, handoff); + } catch (RuntimeException ownerTransitionFailure) { + return Result.outcomeUnknown( + readback.orElseThrow().reservationSnapshot(), + PendingReason.OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN, + readback); + } + if (ownerTransition == null || ownerTransition.snapshot() == null) { + return Result.outcomeUnknown( + readback.orElseThrow().reservationSnapshot(), + PendingReason.OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN, + readback); + } + if (!ownerTransition.mayDispatch()) { + return Result.alreadyInProgress(ownerTransition.snapshot().reservationSnapshot(), readback); + } + if (!isExactOwnerPendingSnapshot( + ownerTransition.snapshot(), tuple, claim, claimEvidence, postAuthorizationTuple, handoff)) { + return Result.outcomeUnknown( + ownerTransition.snapshot().reservationSnapshot(), + PendingReason.OWNER_PENDING_TRANSITION_RESULT_MISMATCH, + readback); + } + return Result.ownerExecutionPending( + new TransientOwnerExecutionHandoff( + ownerTransition.snapshot().handoff(), accountResponse, postAuthorizationTuple), + ownerTransition.snapshot().reservationSnapshot(), + readback); + } + + private Result observeExisting( + StartSessionPreAuthorizationReservationTuple tuple, Snapshot acquisitionSnapshot) { + Optional readback; + try { + readback = reservations.findAuthorizedExact(tuple); + } catch (RuntimeException unavailable) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_UNKNOWN); + } + if (readback == null) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_UNKNOWN); + } + if (readback.isPresent()) { + AuthorizedSnapshot existing = readback.orElseThrow(); + if (!isBoundAuthorizedSnapshot(existing, tuple)) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_MISMATCH); + } + return Result.alreadyInProgress(existing.reservationSnapshot(), readback); + } + if (acquisitionSnapshot.state() == State.AUTHORIZED + || acquisitionSnapshot.state() == State.OWNER_EXECUTION_PENDING) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_MISMATCH); + } + return Result.alreadyInProgress(acquisitionSnapshot, Optional.empty()); + } + + private boolean isExactAccountResult( + StartSessionPreAuthorizationReservationTuple tuple, + ClaimEvidence claimEvidence, + AuthorizationReference response, + StartSessionPostAuthorizationExecutionTuple postTuple) { + try { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(postTuple.authorityEvidenceBundleBytes()); + if (!response.expiresAt().equals(bundle.expiresAt()) + || !tuple.canonicalJson().equals(postTuple.preAuthorizationTuple().canonicalJson()) + || !tuple.controlPlaneRequestId().equals(postTuple.controlPlaneRequestId()) + || !tuple.mutationDigest().equals(postTuple.mutationDigest()) + || !"human_operator".equals(postTuple.issuanceKind()) + || !claimEvidence.reservationOwnerId().equals(postTuple.reservationOwnerId()) + || claimEvidence.reservationClaimFence() != postTuple.reservationClaimFence()) { + return false; + } + bundle.requireTupleBinding(postTuple.preAuthorizationTuple()); + bundle.requireReferenceBinding(postTuple.bundleReference()); + return true; + } catch (RuntimeException malformedEvidence) { + return false; + } + } + + private static boolean claimMatchesOriginalReservation( + ClaimHandle claim, StartSessionPreAuthorizationReservationTuple tuple) { + ClaimEvidence evidence = claim.claimEvidence(); + return tuple.canonicalJson().equals(claim.tuple().canonicalJson()) + && tuple.mutationDigest().equals(claim.mutationDigest()) + && claim.purpose() == ClaimPurpose.ORIGINAL + && evidence.reservationOwnerId().equals(evidence.currentClaimOwnerId()) + && evidence.reservationClaimFence() == evidence.currentClaimFence() + && evidence.reservationClaimFence() > 0L; + } + + private static boolean isExactPendingSnapshot( + Snapshot snapshot, StartSessionPreAuthorizationReservationTuple tuple, ClaimHandle claim) { + ClaimEvidence evidence = claim.claimEvidence(); + return snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING + && snapshot.claimState() == ClaimState.ACTIVE + && snapshot.claimPurpose() == claim.purpose() + && snapshot.reservationClaimFence() == evidence.reservationClaimFence() + && snapshot.claimFence() == evidence.currentClaimFence() + && tuple.canonicalJson().equals(snapshot.tuple().canonicalJson()) + && tuple.mutationDigest().equals(snapshot.mutationDigest()); + } + + private static boolean isExactAuthorizedSnapshot( + AuthorizedSnapshot snapshot, + StartSessionPreAuthorizationReservationTuple tuple, + ClaimHandle claim, + ClaimEvidence evidence, + StartSessionPostAuthorizationExecutionTuple postTuple) { + return isBoundAuthorizedSnapshot(snapshot, tuple) + && snapshot.reservationSnapshot().phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.reservationSnapshot().state() == State.AUTHORIZED + && snapshot.reservationSnapshot().claimState() == ClaimState.ACTIVE + && snapshot.reservationSnapshot().claimPurpose() == claim.purpose() + && snapshot.reservationSnapshot().claimFence() == evidence.currentClaimFence() + && snapshot.reservationSnapshot().reservationClaimFence() + == evidence.reservationClaimFence() + && snapshot.reservationOwnerId().equals(evidence.reservationOwnerId()) + && snapshot.currentClaimOwnerId().equals(evidence.currentClaimOwnerId()) + && snapshot.handoff() == null + && Arrays.equals( + snapshot.postAuthorizationTuple().canonicalBytes(), postTuple.canonicalBytes()); + } + + private static boolean isExactOwnerPendingSnapshot( + AuthorizedSnapshot snapshot, + StartSessionPreAuthorizationReservationTuple tuple, + ClaimHandle claim, + ClaimEvidence evidence, + StartSessionPostAuthorizationExecutionTuple postTuple, + OwnerExecutionHandoff expectedHandoff) { + return isBoundAuthorizedSnapshot(snapshot, tuple) + && snapshot.reservationSnapshot().phase() == Phase.OWNER_EXECUTION + && snapshot.reservationSnapshot().state() == State.OWNER_EXECUTION_PENDING + && snapshot.reservationSnapshot().claimState() == ClaimState.ACTIVE + && snapshot.reservationSnapshot().claimPurpose() == claim.purpose() + && snapshot.reservationSnapshot().claimFence() == evidence.currentClaimFence() + && snapshot.reservationSnapshot().reservationClaimFence() + == evidence.reservationClaimFence() + && snapshot.reservationOwnerId().equals(evidence.reservationOwnerId()) + && snapshot.currentClaimOwnerId().equals(evidence.currentClaimOwnerId()) + && Arrays.equals( + snapshot.postAuthorizationTuple().canonicalBytes(), postTuple.canonicalBytes()) + && expectedHandoff.equals(snapshot.handoff()); + } + + private static boolean isBoundAuthorizedSnapshot( + AuthorizedSnapshot snapshot, StartSessionPreAuthorizationReservationTuple tuple) { + if (snapshot == null + || !tuple.canonicalJson().equals(snapshot.reservationSnapshot().tuple().canonicalJson()) + || !tuple.mutationDigest().equals(snapshot.reservationSnapshot().mutationDigest()) + || !tuple + .canonicalJson() + .equals(snapshot.postAuthorizationTuple().preAuthorizationTuple().canonicalJson()) + || !tuple + .controlPlaneRequestId() + .equals(snapshot.postAuthorizationTuple().controlPlaneRequestId()) + || !tuple.mutationDigest().equals(snapshot.postAuthorizationTuple().mutationDigest()) + || !"human_operator".equals(snapshot.postAuthorizationTuple().issuanceKind()) + || snapshot.reservationSnapshot().reservationClaimFence() + != snapshot.postAuthorizationTuple().reservationClaimFence() + || !snapshot + .reservationOwnerId() + .equals(snapshot.postAuthorizationTuple().reservationOwnerId()) + || snapshot.reservationSnapshot().state() != State.AUTHORIZED + && snapshot.reservationSnapshot().state() != State.OWNER_EXECUTION_PENDING + || snapshot.reservationSnapshot().phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.reservationSnapshot().state() != State.AUTHORIZED + || snapshot.reservationSnapshot().phase() == Phase.OWNER_EXECUTION + && snapshot.reservationSnapshot().state() != State.OWNER_EXECUTION_PENDING) { + return false; + } + try { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode( + snapshot.postAuthorizationTuple().authorityEvidenceBundleBytes()); + bundle.requireTupleBinding(snapshot.postAuthorizationTuple().preAuthorizationTuple()); + bundle.requireReferenceBinding(snapshot.postAuthorizationTuple().bundleReference()); + return true; + } catch (RuntimeException malformedEvidence) { + return false; + } + } + + private static boolean sameAuthorizedSnapshot( + AuthorizedSnapshot expected, AuthorizedSnapshot actual) { + return expected.reservationSnapshot().equals(actual.reservationSnapshot()) + && Arrays.equals( + expected.postAuthorizationTuple().canonicalBytes(), + actual.postAuthorizationTuple().canonicalBytes()) + && expected.reservationOwnerId().equals(actual.reservationOwnerId()) + && Objects.equals(expected.currentClaimOwnerId(), actual.currentClaimOwnerId()) + && Objects.equals(expected.handoff(), actual.handoff()); + } + + private void requireConfiguredNamespace(StartSessionOperatorAction action) { + if (!configuredNamespace.equals(action.scope().targetNamespace())) { + throw new IllegalArgumentException( + "StartSession target namespace does not match the configured workload namespace"); + } + } + + private static void requireSnapshotTuple( + Snapshot snapshot, StartSessionPreAuthorizationReservationTuple tuple) { + if (snapshot == null + || !tuple.canonicalJson().equals(snapshot.tuple().canonicalJson()) + || !tuple.mutationDigest().equals(snapshot.mutationDigest())) { + throw new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + } + + /** Local envelope validation is not signature validation or current Account authorization. */ + private static void requireCompactJwtEnvelope(String token) { + if (token == null || token.isEmpty() || token.length() > MAX_CONTROL_UI_JWT_BYTES) { + throw malformedJwtEnvelope(); + } + for (int index = 0; index < token.length(); index++) { + if (token.charAt(index) > 0x7f) { + throw malformedJwtEnvelope(); + } + } + String[] segments = token.split("\\.", -1); + if (segments.length != 3 + || segments[0].isEmpty() + || segments[1].isEmpty() + || segments[2].isEmpty()) { + throw malformedJwtEnvelope(); + } + byte[] header = decodeJwtSegment(segments[0]); + byte[] claims = decodeJwtSegment(segments[1]); + byte[] signature = decodeJwtSegment(segments[2]); + if (header == null || claims == null || signature == null || signature.length == 0) { + throw malformedJwtEnvelope(); + } + requireJsonObject(header); + requireJsonObject(claims); + } + + private static byte[] decodeJwtSegment(String segment) { + if (!segment.matches("[A-Za-z0-9_-]+")) { + return null; + } + try { + byte[] decoded = Base64.getUrlDecoder().decode(segment); + return Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(segment) + ? decoded + : null; + } catch (IllegalArgumentException malformed) { + return null; + } + } + + private static void requireJsonObject(byte[] bytes) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + Map object = JWT_JSON.readValue(json, JSON_OBJECT); + if (object == null) { + throw malformedJwtEnvelope(); + } + } catch (IOException | RuntimeException malformed) { + throw malformedJwtEnvelope(); + } + } + + private static IllegalArgumentException malformedJwtEnvelope() { + return new IllegalArgumentException("control-ui JWT envelope is malformed"); + } + + private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + sharedTuple(StartSessionPreAuthorizationReservationTuple tuple) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(tuple.canonicalJson()); + } + + public enum Progress { + OWNER_EXECUTION_PENDING, + ALREADY_IN_PROGRESS, + RECOVERY_UNAVAILABLE, + AUTHORIZATION_OUTCOME_UNKNOWN + } + + /** Contains no response material unless this call won the durable owner-pending transition. */ + public static final class Result { + private final Progress progress; + private final TransientOwnerExecutionHandoff handoff; + private final Snapshot snapshot; + private final Optional authorizedReadback; + private final PendingReason pendingReason; + + private Result( + Progress progress, + TransientOwnerExecutionHandoff handoff, + Snapshot snapshot, + Optional authorizedReadback, + PendingReason pendingReason) { + this.progress = Objects.requireNonNull(progress, "progress is required"); + this.handoff = handoff; + this.snapshot = snapshot; + this.authorizedReadback = + Objects.requireNonNull(authorizedReadback, "authorized readback is required"); + this.pendingReason = pendingReason; + if ((progress == Progress.OWNER_EXECUTION_PENDING) != (handoff != null) + || (progress == Progress.RECOVERY_UNAVAILABLE) != (snapshot == null) + || (progress == Progress.AUTHORIZATION_OUTCOME_UNKNOWN) != (pendingReason != null)) { + throw new IllegalArgumentException( + "authorization result progress and transient material are inconsistent"); + } + } + + private static Result ownerExecutionPending( + TransientOwnerExecutionHandoff handoff, + Snapshot snapshot, + Optional authorizedReadback) { + return new Result( + Progress.OWNER_EXECUTION_PENDING, handoff, snapshot, authorizedReadback, null); + } + + private static Result alreadyInProgress( + Snapshot snapshot, Optional authorizedReadback) { + return new Result( + Progress.ALREADY_IN_PROGRESS, + null, + Objects.requireNonNull(snapshot, "observed snapshot is required"), + authorizedReadback, + null); + } + + private static Result outcomeUnknown(Snapshot snapshot, PendingReason reason) { + return outcomeUnknown(snapshot, reason, Optional.empty()); + } + + private static Result outcomeUnknown( + Snapshot snapshot, PendingReason reason, Optional authorizedReadback) { + return new Result( + Progress.AUTHORIZATION_OUTCOME_UNKNOWN, + null, + Objects.requireNonNull(snapshot, "last known snapshot is required"), + authorizedReadback, + Objects.requireNonNull(reason, "pending reason is required")); + } + + private static Result recoveryUnavailable() { + return new Result(Progress.RECOVERY_UNAVAILABLE, null, null, Optional.empty(), null); + } + + public Progress progress() { + return progress; + } + + public TransientOwnerExecutionHandoff handoff() { + return handoff; + } + + public Snapshot snapshot() { + return snapshot; + } + + public Optional authorizedReadback() { + return authorizedReadback; + } + + public Optional pendingReason() { + return Optional.ofNullable(pendingReason); + } + + @Override + public String toString() { + return "Result[progress=" + + progress + + ", handoff=" + + (handoff == null ? "null" : "") + + ", snapshot=" + + (snapshot == null ? "null" : "") + + ", authorizedReadbackPresent=" + + authorizedReadback.isPresent() + + ", pendingReason=" + + pendingReason + + "]"; + } + } + + public enum PendingReason { + RESERVATION_CLAIM_MISMATCH, + PENDING_TRANSITION_OUTCOME_UNKNOWN, + ACCOUNT_ISSUANCE_OUTCOME_UNKNOWN, + ACCOUNT_RECOVERY_OUTCOME_UNKNOWN, + ACCOUNT_RESPONSE_INVALID, + LOCAL_COMPLETION_OUTCOME_UNKNOWN, + LOCAL_COMPLETION_RESULT_MISMATCH, + AUTHORIZATION_READBACK_UNKNOWN, + AUTHORIZATION_READBACK_MISMATCH, + EXISTING_AUTHORIZATION_READBACK_UNKNOWN, + EXISTING_AUTHORIZATION_READBACK_MISMATCH, + OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN, + OWNER_PENDING_TRANSITION_RESULT_MISMATCH + } + + /** + * Safe composition result: original progress and, only after dispatch, a secret-free owner echo. + */ + public record OwnerDispatchResult( + Progress progress, Optional ownerEcho) { + public OwnerDispatchResult { + Objects.requireNonNull(progress, "progress is required"); + Objects.requireNonNull(ownerEcho, "owner echo optional is required"); + if ((progress == Progress.OWNER_EXECUTION_PENDING) != ownerEcho.isPresent()) { + throw new IllegalArgumentException( + "only a newly committed owner-pending handoff has an owner echo"); + } + } + + @Override + public String toString() { + return "OwnerDispatchResult[progress=" + + progress + + ", ownerEcho=" + + (ownerEcho.isPresent() ? "" : "empty") + + "]"; + } + } + + /** + * Transient caller handoff; its diagnostic representation never includes raw authorization data. + */ + public record TransientOwnerExecutionHandoff( + OwnerExecutionHandoff ownerExecutionHandoff, + AuthorizationReference accountResponse, + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple) { + public TransientOwnerExecutionHandoff { + Objects.requireNonNull(ownerExecutionHandoff, "owner execution handoff is required"); + Objects.requireNonNull(accountResponse, "Account response is required"); + Objects.requireNonNull(postAuthorizationTuple, "post-authorization tuple is required"); + } + + @Override + public String toString() { + return "TransientOwnerExecutionHandoff[ownerExecutionHandoff=" + + ownerExecutionHandoff + + ", accountResponse=, " + + "postAuthorizationTuple=]"; + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java index 16ac0c1060..6298358436 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java @@ -1,18 +1,59 @@ package net.firedevops.firemud.loggingadmin.client; 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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import io.grpc.CallCredentials; +import io.grpc.ClientInterceptor; import io.grpc.ManagedChannel; +import io.grpc.Status; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionRequest; +import net.firedevops.firemud.gamesession.v1.AuthorizeStartSessionResponse; import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; +import net.firedevops.firemud.gamesession.v1.StartSessionOwnerAuthorizationProgress; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient.AuthorizationReference; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.TransientOwnerExecutionHandoff; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; class GameSessionClientTest { + @TempDir private Path tlsDirectory; + + private static final long DEADLINE_SECONDS = 5L; + private static final String OPAQUE_REFERENCE = "A".repeat(43); + private static final String LOGGING_IDENTITY = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OWNER_ID = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID OWNER_ATTEMPT = UUID.fromString("69116466-a576-4fa6-9e11-4c0c6b2a92f0"); + private static final UUID OWNER_MUTATION = + UUID.fromString("89da7d84-12f5-4cf8-b69b-30ba8eb115a4"); @Test void buildStubAppliesInjectedStubCustomizer() { @@ -40,6 +81,270 @@ public > T customize(T candidate) { assertThat(customized.get()).isSameAs(stub); } + @Test + void sendsOneExactTypedHandoffAndValidatesSecretFreeOwnerEcho() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + TransientOwnerExecutionHandoff handoff = handoff(); + StartSessionPostAuthorizationExecutionTuple tuple = handoff.postAuthorizationTuple(); + AuthorizeStartSessionResponse response = + ownerResponse( + tuple, + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS); + when(stub.authorizeStartSession(any())).thenReturn(response); + GameSessionClient client = client(stub); + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(AuthorizeStartSessionRequest.class); + ArgumentCaptor interceptorCaptor = + ArgumentCaptor.forClass(ClientInterceptor[].class); + + GameSessionClient.StartSessionOwnerHandoffResult result = client.authorizeStartSession(handoff); + + verify(stub, times(1)).withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS); + verify(stub, times(1)).authorizeStartSession(requestCaptor.capture()); + verify(stub, never()).stopSession(any()); + assertThat( + requestCaptor + .getValue() + .getCanonicalPostAuthorizationExecutionTupleBytes() + .toByteArray()) + .containsExactly(tuple.canonicalBytes()); + assertThat(requestCaptor.getValue().getOperatorAuthorizationReference()) + .isEqualTo(OPAQUE_REFERENCE); + verify(stub, times(1)).withCallCredentials(any(GrpcServerPeerIdentityCallCredentials.class)); + verify(stub, times(1)).withInterceptors(interceptorCaptor.capture()); + assertThat(interceptorCaptor.getValue()).hasSize(1); + assertThat(interceptorCaptor.getValue()[0]) + .isInstanceOf(GrpcServerPeerIdentityClientInterceptor.class); + assertThat(result.controlPlaneRequestId()).isEqualTo(tuple.controlPlaneRequestId()); + assertThat(result.mutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(result.ownerAttemptId()).isEqualTo(OWNER_ATTEMPT); + assertThat(result.ownerMutationId()).isEqualTo(OWNER_MUTATION); + assertThat(result.ownerFence()).isEqualTo(37L); + assertThat(result.progress()) + .isEqualTo( + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_OUTCOME_AMBIGUOUS); + assertThat(result.toString()).doesNotContain(OPAQUE_REFERENCE); + } + + @Test + void refusesOwnerResponseThatDoesNotEchoTheOriginalTuple() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + TransientOwnerExecutionHandoff handoff = handoff(); + AuthorizeStartSessionResponse substitutedResponse = + ownerResponse( + handoff.postAuthorizationTuple(), + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_EXACT_REPLAY) + .toBuilder() + .setMutationDigest("different-digest") + .build(); + when(stub.authorizeStartSession(any())).thenReturn(substitutedResponse); + + assertThatThrownBy(() -> client(stub).authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match") + .hasMessageNotContaining(OPAQUE_REFERENCE); + verify(stub, times(1)).authorizeStartSession(any()); + } + + @Test + void refusesSensitiveHandoffWithoutReadableFileBackedMtlsBeforeRpc() throws Exception { + TransientOwnerExecutionHandoff handoff = handoff(); + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + + CommonGrpcClientProperties plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> client(stub, plaintext).authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires workload mTLS"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + assertThatThrownBy(() -> client(stub, missingFiles).authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("file-backed workload mTLS"); + + CommonGrpcClientProperties directoryInsteadOfCertificate = fileBackedTlsProperties(); + directoryInsteadOfCertificate.setCertChain(tlsDirectory.toString()); + assertThatThrownBy( + () -> client(stub, directoryInsteadOfCertificate).authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("file-backed workload mTLS"); + + verify(stub, never()).authorizeStartSession(any()); + } + + @Test + void rejectsSubstitutedAccountReferenceBeforeCallingGameSession() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + TransientOwnerExecutionHandoff handoff = handoff(); + when(handoff.accountResponse().authenticatedLoggingWorkloadIdentity()) + .thenReturn("spiffe://firemud/ns/other/sa/logging-admin-service"); + + assertThatThrownBy(() -> client(stub).authorizeStartSession(handoff)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not internally bound") + .hasMessageNotContaining(OPAQUE_REFERENCE); + verify(stub, never()).authorizeStartSession(any()); + } + + @Test + void refusesOwnerHandoffInsideAmbientSqlOrSynchronizationBeforeRpc() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + GameSessionClient client = client(stub); + TransientOwnerExecutionHandoff handoff = handoff(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + + verify(stub, never()).authorizeStartSession(any()); + } + + @Test + void surfacesTransportAmbiguityWithoutAutomaticRetryOrReferenceDisclosure() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + TransientOwnerExecutionHandoff handoff = handoff(); + when(stub.authorizeStartSession(any())) + .thenThrow(Status.DEADLINE_EXCEEDED.asRuntimeException()); + + assertThatThrownBy(() -> client(stub).authorizeStartSession(handoff)) + .isInstanceOf(GameSessionClient.AmbiguousOwnerHandoffException.class) + .hasMessageNotContaining(OPAQUE_REFERENCE); + verify(stub, times(1)).authorizeStartSession(any()); + } + + private GameSessionClient client(GameSessionServiceGrpc.GameSessionServiceBlockingStub stub) { + try { + return client(stub, fileBackedTlsProperties()); + } catch (IOException failure) { + throw new AssertionError("test TLS fixture creation failed", failure); + } + } + + private GameSessionClient client( + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub, CommonGrpcClientProperties grpc) { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + TestGameSessionClient client = + new TestGameSessionClient( + endpoints, + grpc, + mock(GrpcChannelFactory.class), + new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T candidate) { + return candidate; + } + }, + stub); + try { + client.installStubForTest(); + } catch (javax.net.ssl.SSLException failure) { + throw new AssertionError("test stub installation failed", failure); + } + return client; + } + + private CommonGrpcClientProperties fileBackedTlsProperties() throws IOException { + Path certChain = tlsDirectory.resolve("client.crt"); + Path privateKey = tlsDirectory.resolve("client.key"); + Path caCert = tlsDirectory.resolve("ca.crt"); + Files.writeString(certChain, "test-only certificate placeholder"); + Files.writeString(privateKey, "test-only private-key placeholder"); + Files.writeString(caCert, "test-only CA placeholder"); + CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); + grpc.setCertChain(certChain.toString()); + grpc.setPrivateKey(privateKey.toString()); + grpc.setCaCert(caCert.toString()); + return grpc; + } + + private static GameSessionServiceGrpc.GameSessionServiceBlockingStub mockStub() { + var stub = mock(GameSessionServiceGrpc.GameSessionServiceBlockingStub.class); + when(stub.withCallCredentials(any(CallCredentials.class))).thenReturn(stub); + when(stub.withInterceptors(any(ClientInterceptor[].class))).thenReturn(stub); + when(stub.withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static AuthorizeStartSessionResponse ownerResponse( + StartSessionPostAuthorizationExecutionTuple tuple, + StartSessionOwnerAuthorizationProgress progress) { + return AuthorizeStartSessionResponse.newBuilder() + .setTargetNamespace("world-runtime") + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setMutationDigest(tuple.mutationDigest()) + .setOwnerAttemptId(OWNER_ATTEMPT.toString()) + .setOwnerMutationId(OWNER_MUTATION.toString()) + .setOwnerFence(37L) + .setOwnerPhaseState("OWNER_EXECUTION_PENDING") + .setProgress(progress) + .build(); + } + + private static TransientOwnerExecutionHandoff handoff() throws Exception { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Logging Game Session client transport test"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "logging-game-session-client-test", ACTOR_ID, action); + StartSessionPostAuthorizationExecutionTuple tuple = mockTuple(preTuple); + AuthorizationReference accountResponse = mock(AuthorizationReference.class); + String tupleFingerprint = tuple.authorizationReferenceFingerprint(); + byte[] tupleAuthorityEvidenceBundle = tuple.authorityEvidenceBundleBytes(); + StartSessionAuthorityEvidenceBundle.BundleReference tupleBundleReference = + tuple.bundleReference(); + when(accountResponse.operatorAuthorizationReference()).thenReturn(OPAQUE_REFERENCE); + when(accountResponse.authenticatedLoggingWorkloadIdentity()).thenReturn(LOGGING_IDENTITY); + when(accountResponse.authorizationReferenceFingerprint()).thenReturn(tupleFingerprint); + when(accountResponse.authorityEvidenceBundle()).thenReturn(tupleAuthorityEvidenceBundle); + when(accountResponse.bundleReference()).thenReturn(tupleBundleReference); + return new TransientOwnerExecutionHandoff( + new OwnerExecutionHandoff(UUID.fromString("5be93a95-79f3-4c08-9857-dc0848b2185d")), + accountResponse, + tuple); + } + + private static StartSessionPostAuthorizationExecutionTuple mockTuple( + StartSessionPreAuthorizationReservationTuple preTuple) { + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + var tuple = mock(StartSessionPostAuthorizationExecutionTuple.class); + when(tuple.canonicalBytes()).thenReturn(new byte[] {1, 2, 3}); + when(tuple.preAuthorizationTuple()).thenReturn(preTuple); + when(tuple.controlPlaneRequestId()).thenReturn(preTuple.controlPlaneRequestId()); + when(tuple.mutationDigest()).thenReturn(preTuple.mutationDigest()); + when(tuple.authenticatedWorkloadIdentity()).thenReturn(LOGGING_IDENTITY); + when(tuple.authorizationReferenceFingerprint()) + .thenReturn("arfp/v1/test-key/" + "b".repeat(64)); + when(tuple.authorityEvidenceBundleBytes()).thenReturn(new byte[] {4, 5, 6}); + when(tuple.bundleReference()).thenReturn(bundleReference); + return tuple; + } + private static final class TestGameSessionClient extends GameSessionClient { private final GameSessionServiceGrpc.GameSessionServiceBlockingStub stub; @@ -53,6 +358,10 @@ private TestGameSessionClient( this.stub = stub; } + private void installStubForTest() throws javax.net.ssl.SSLException { + reloadChannel(); + } + @Override protected GameSessionServiceGrpc.GameSessionServiceBlockingStub buildStub( ManagedChannel channel) { diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java new file mode 100644 index 0000000000..271ee2c29b --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java @@ -0,0 +1,963 @@ +package net.firedevops.firemud.loggingadmin.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslProvider; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.UnaryOperator; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.test.TlsTestSupport; +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.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Socket-mTLS proof against a synthetic Account handler, not Account issuance or Logging claim + * proof. + */ +class StartSessionOperatorAuthorizationClientMtlsTest { + private static final String NAMESPACE = "logging-test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/logging-test/sa/account-service"; + private static final String LOGGING_URI = + "spiffe://firemud/ns/logging-test/sa/logging-admin-service"; + private static final String STORE_PASSWORD = "synthetic-start-session-authorization-test"; + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("ef5b97ec-3cbe-43dc-a85f-f119060386ab"); + private static final UUID CLAIM_OWNER_ID = + UUID.fromString("9bb650bd-38c2-4dc1-8132-1af107358e60"); + private static final String CONTROL_UI_JWT = "synthetic-original-control-ui-jwt-body-only"; + private static final String OPERATOR_REFERENCE = "a".repeat(43); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final Instant NOW = Instant.parse("2026-10-11T12:00:00Z"); + private static final Instant EXPIRY = NOW.plusSeconds(240); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir static Path temporaryDirectory; + private static TestPki pki; + private Server server; + private StartSessionOperatorAuthorizationClient client; + private AtomicInteger rpcCalls; + private IssueHumanOperatorAuthorizationReferenceRequest receivedIssue; + private RecoverOperatorAuthorizationReferenceRequest receivedRecovery; + + @BeforeAll + static void createSyntheticWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @BeforeEach + void clearAmbientThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @AfterEach + void stopTransportAndClearThreadState() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void issueAndRecoverPreserveTheExactOriginalResponseAndCompleteEvidence() throws Exception { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + var tuple = tuple("synthetic-issue-recover-01"); + + var issued = + client.issueHuman( + tuple, CONTROL_UI_JWT, RESERVATION_OWNER_ID, Long.MAX_VALUE, CLAIM_OWNER_ID, 71L); + var recovered = + client.recover(tuple, RESERVATION_OWNER_ID, Long.MAX_VALUE, CLAIM_OWNER_ID, 71L); + + assertThat(issued.operatorAuthorizationReference()).isEqualTo(OPERATOR_REFERENCE); + assertThat(recovered.operatorAuthorizationReference()).isEqualTo(OPERATOR_REFERENCE); + assertThat(recovered.authorizationReferenceFingerprint()) + .isEqualTo(issued.authorizationReferenceFingerprint()); + assertThat(issued.expiresAt()).isEqualTo(EXPIRY); + assertThat(recovered.expiresAt()).isEqualTo(issued.expiresAt()); + assertThat(recovered.authorityEvidenceBundle()) + .containsExactly(issued.authorityEvidenceBundle()); + assertThat(recovered.bundleReference()).isEqualTo(issued.bundleReference()); + assertThat(issued.authenticatedLoggingWorkloadIdentity()).isEqualTo(LOGGING_URI); + assertThat(recovered.authenticatedLoggingWorkloadIdentity()).isEqualTo(LOGGING_URI); + assertThat(issued.decodedBundle().controlPlaneRequestId()) + .isEqualTo(tuple.controlPlaneRequestId()); + assertThat(issued.toString()).doesNotContain(OPERATOR_REFERENCE, CONTROL_UI_JWT); + assertThat(receivedIssue.getControlUiJwt()).isEqualTo(CONTROL_UI_JWT); + assertThat(receivedIssue.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(receivedIssue.getReservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(receivedIssue.getReservationClaimFence()).isEqualTo(Long.MAX_VALUE); + assertThat(receivedIssue.getCurrentClaimOwnerId()).isEqualTo(CLAIM_OWNER_ID.toString()); + assertThat(receivedIssue.getCurrentClaimFence()).isEqualTo(71L); + assertThat(receivedRecovery.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(receivedIssue.getCanonicalPreAuthorizationTupleBytes().toByteArray()); + assertThat(receivedRecovery.getReservationOwnerId()) + .isEqualTo(receivedIssue.getReservationOwnerId()); + assertThat(receivedRecovery.getReservationClaimFence()) + .isEqualTo(receivedIssue.getReservationClaimFence()); + assertThat(receivedRecovery.getCurrentClaimOwnerId()) + .isEqualTo(receivedIssue.getCurrentClaimOwnerId()); + assertThat(receivedRecovery.getCurrentClaimFence()) + .isEqualTo(receivedIssue.getCurrentClaimFence()); + assertThat(rpcCalls).hasValue(2); + } + + @Test + void rejectsWrongAccountServerServiceAndNamespaceBeforeSendingRequest() throws Exception { + assertWrongServerIdentity( + pki.identity( + "wrong-service-server", "spiffe://firemud/ns/logging-test/sa/account-other", true)); + assertWrongServerIdentity( + pki.identity( + "wrong-namespace-server", "spiffe://firemud/ns/other-test/sa/account-service", true)); + } + + @Test + void rejectsWrongLoggingCallerServiceAndNamespaceAtSyntheticAccountBoundary() throws Exception { + for (TestIdentity caller : + List.of( + pki.identity( + "wrong-service-client", + "spiffe://firemud/ns/logging-test/sa/game-session-service", + false), + pki.identity( + "wrong-namespace-client", + "spiffe://firemud/ns/other-test/sa/logging-admin-service", + false))) { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(caller); + client.initialize(); + + assertThatThrownBy( + () -> + client.issueHuman( + tuple("wrong-caller-" + caller.alias()), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 8L, + CLAIM_OWNER_ID, + 9L)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("PERMISSION_DENIED"); + assertThat(rpcCalls).hasValue(1); + stopServer(); + client.close(); + client = null; + } + } + + @Test + void rejectsUnknownFieldsChangedTupleBindingAndExpirySubstitution() throws Exception { + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + startServer( + pki.accountServer(), + response -> response.toBuilder().setUnknownFields(unknown).build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setAuthorityEvidenceBundle( + ByteString.copyFrom(bundleFor(tuple("different-original-request")))) + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setExpiresAt( + Timestamp.newBuilder().setSeconds(EXPIRY.plusSeconds(1).getEpochSecond())) + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + } + + @Test + void rejectsAuthenticatedLoggingIdentityMismatchAndExpiredEvidence() throws Exception { + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setAuthenticatedLoggingWorkloadIdentity( + "spiffe://firemud/ns/other-test/sa/logging-admin-service") + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setExpiresAt( + Timestamp.newBuilder().setSeconds(NOW.minusSeconds(1).getEpochSecond())) + .setAuthorityEvidenceBundle( + ByteString.copyFrom(bundleFor(tuple("expired-original-request")))) + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + } + + @Test + void deniesIssueAndRecoveryBeforeNetworkUnderSqlOrSynchronization() throws Exception { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + var tuple = tuple("pre-network-denial-01"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_JWT, RESERVATION_OWNER_ID, 1L, CLAIM_OWNER_ID, 2L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + TransactionSynchronizationManager.clear(); + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER_ID, 1L, CLAIM_OWNER_ID, 2L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.clear(); + } + assertThat(rpcCalls).hasValue(0); + } + + @Test + void syntheticMutualTlsRejectsMissingClientCertificateWithSharedTlsAssertion() throws Exception { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + SSLContext trustOnlyContext = SSLContext.getInstance("TLS"); + var trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + trustStore.setCertificateEntry("trusted-test-ca", pki.caCertificate()); + var trustManagers = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + trustOnlyContext.init(null, trustManagers.getTrustManagers(), new SecureRandom()); + + Throwable failure = + catchThrowable( + () -> { + try (SSLSocket socket = + (SSLSocket) + trustOnlyContext + .getSocketFactory() + .createSocket("127.0.0.1", server.getPort())) { + socket.setSoTimeout(2_000); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + parameters.setProtocols(new String[] {"TLSv1.3"}); + parameters.setApplicationProtocols(new String[] {"h2"}); + socket.setSSLParameters(parameters); + socket.startHandshake(); + socket.getInputStream().read(); + } + }); + + assertThat(failure).isInstanceOf(SSLHandshakeException.class); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue(); + assertThat(rpcCalls).hasValue(0); + } + + private void assertWrongServerIdentity(TestIdentity serverIdentity) throws Exception { + startServer(serverIdentity, UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertThatThrownBy( + () -> + client.issueHuman( + tuple("wrong-server-" + serverIdentity.alias()), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 10L, + CLAIM_OWNER_ID, + 11L)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("UNAUTHENTICATED"); + assertThat(rpcCalls).hasValue(0); + stopTransportOnly(); + } + + private void assertInvalidResponse() { + assertThatThrownBy( + () -> + client.issueHuman( + tuple("invalid-account-result-01"), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 12L, + CLAIM_OWNER_ID, + 13L)) + .isInstanceOf(IllegalStateException.class); + assertThat(rpcCalls).hasValue(1); + } + + private void startServer( + TestIdentity serverIdentity, + UnaryOperator issueMutation, + UnaryOperator recoverMutation) + throws Exception { + rpcCalls = new AtomicInteger(); + receivedIssue = null; + receivedRecovery = null; + var service = + new StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceImplBase() { + @Override + public void issueHumanOperatorAuthorizationReference( + IssueHumanOperatorAuthorizationReferenceRequest request, + StreamObserver observer) { + rpcCalls.incrementAndGet(); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !LOGGING_URI.equals(peer.uri()) + || !NAMESPACE.equals(peer.namespace()) + || SessionContext.hasAuthenticatedCallerContext()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + receivedIssue = request.toBuilder().build(); + try { + observer.onNext(issueMutation.apply(issueResponse(request))); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } + + @Override + public void recoverOperatorAuthorizationReference( + RecoverOperatorAuthorizationReferenceRequest request, + StreamObserver observer) { + rpcCalls.incrementAndGet(); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !LOGGING_URI.equals(peer.uri()) + || !NAMESPACE.equals(peer.namespace()) + || SessionContext.hasAuthenticatedCallerContext()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + receivedRecovery = request.toBuilder().build(); + try { + observer.onNext(recoverMutation.apply(recoveryResponse(request))); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } + }; + ServerInterceptor requestMetadataGuard = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (headers.get(Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER)) + != null) { + call.close(Status.PERMISSION_DENIED, new Metadata()); + return new ServerCall.Listener<>() {}; + } + return next.startCall(call, headers); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate()), + SslProvider.JDK) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .protocols("TLSv1.3") + .build()) + .addService( + ServerInterceptors.intercept( + service, requestMetadataGuard, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private void stopTransportOnly() throws Exception { + if (client != null) { + client.close(); + client = null; + } + stopServer(); + } + + private void stopServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private StartSessionOperatorAuthorizationClient newClient(TestIdentity clientIdentity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + server.getPort()); + return new StartSessionOperatorAuthorizationClient( + endpoints, + pki.clientProperties(clientIdentity), + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + Clock.fixed(NOW, java.time.ZoneOffset.UTC)); + } + + private static IssueHumanOperatorAuthorizationReferenceResponse issueResponse( + IssueHumanOperatorAuthorizationReferenceRequest request) { + return IssueHumanOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setExpiresAt(timestamp(EXPIRY)) + .setAuthorityEvidenceBundle(ByteString.copyFrom(bundleFor(tupleFrom(request)))) + .setBundleReference(bundleReference()) + .setAuthenticatedLoggingWorkloadIdentity(LOGGING_URI) + .build(); + } + + private static RecoverOperatorAuthorizationReferenceResponse recoveryResponse( + RecoverOperatorAuthorizationReferenceRequest request) { + return RecoverOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setExpiresAt(timestamp(EXPIRY)) + .setAuthorityEvidenceBundle(ByteString.copyFrom(bundleFor(tupleFrom(request)))) + .setBundleReference(bundleReference()) + .setAuthenticatedLoggingWorkloadIdentity(LOGGING_URI) + .build(); + } + + private static byte[] bundleFor( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = tuple.action().scope().tenantId().toString(); + Map root = + new LinkedHashMap<>( + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", tuple.actor().accountId().toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "c".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + NOW.toString(), + "expiresAt", + EXPIRY.toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", "23", + "issuanceEvidence", + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", tuple.actor().accountId().toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"))); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + } catch (IOException fixtureFailure) { + throw new IllegalStateException( + "Synthetic Account authority bundle fixture could not be encoded", fixtureFailure); + } + } + + private static AuthorityEvidenceBundleReference bundleReference() { + return AuthorityEvidenceBundleReference.newBuilder() + .setBundleVersion(StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION) + .setSourceVersion("17") + .setSourceFence("23") + .setLinearization("18446744073709551615") + .build(); + } + + private static Timestamp timestamp(Instant value) { + return Timestamp.newBuilder() + .setSeconds(value.getEpochSecond()) + .setNanos(value.getNano()) + .build(); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "synthetic Account authorization client transport proof"); + var shared = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .createHuman(requestId, ACTOR_ID, action); + return StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(shared.canonicalJson()); + } + + private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + tupleFrom(IssueHumanOperatorAuthorizationReferenceRequest request) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(request.getCanonicalPreAuthorizationTupleBytes().toStringUtf8()); + } + + private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + tupleFrom(RecoverOperatorAuthorizationReferenceRequest request) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(request.getCanonicalPreAuthorizationTupleBytes().toStringUtf8()); + } + + private record TestIdentity( + String alias, + String workloadUri, + boolean server, + Path store, + Path certificatePem, + Path privateKeyPem, + PrivateKey privateKey, + X509Certificate certificate) {} + + private static final class TestPki { + private final Path directory; + private final Path caStore; + private final Path caCertificatePem; + private final X509Certificate caCertificate; + private final Map identities; + + private TestPki( + Path directory, + Path caStore, + Path caCertificatePem, + X509Certificate caCertificate, + Map identities) { + this.directory = directory; + this.caStore = caStore; + this.caCertificatePem = caCertificatePem; + this.caCertificate = caCertificate; + this.identities = identities; + } + + private static TestPki create(Path directory) throws Exception { + Files.createDirectories(directory); + Path caStore = directory.resolve("start-session-authorization-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD StartSession authorization synthetic test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caCertificate = directory.resolve("start-session-authorization-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caCertificate.toString(), + "-rfc"); + var identities = new LinkedHashMap(); + addIdentity( + identities, + issueIdentity(directory, caStore, caCertificate, "account-server", ACCOUNT_URI, true)); + addIdentity( + identities, + issueIdentity(directory, caStore, caCertificate, "logging-client", LOGGING_URI, false)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-service-server", + "spiffe://firemud/ns/logging-test/sa/account-other", + true)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-namespace-server", + "spiffe://firemud/ns/other-test/sa/account-service", + true)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-service-client", + "spiffe://firemud/ns/logging-test/sa/game-session-service", + false)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-namespace-client", + "spiffe://firemud/ns/other-test/sa/logging-admin-service", + false)); + return new TestPki( + directory, caStore, caCertificate, readCertificate(caCertificate), identities); + } + + private static void addIdentity(Map identities, TestIdentity identity) { + identities.put(identity.alias(), identity); + } + + private TestIdentity accountServer() { + return identities.get("account-server"); + } + + private TestIdentity loggingClient() { + return identities.get("logging-client"); + } + + private TestIdentity identity(String alias, String workloadUri, boolean server) { + TestIdentity identity = identities.get(alias); + if (identity == null + || !identity.workloadUri().equals(workloadUri) + || identity.server() != server) { + throw new IllegalArgumentException("Unexpected synthetic mTLS identity fixture"); + } + return identity; + } + + private X509Certificate caCertificate() { + return caCertificate; + } + + private CommonGrpcClientProperties clientProperties(TestIdentity identity) { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(identity.certificatePem().toString()); + properties.setPrivateKey(identity.privateKeyPem().toString()); + properties.setCaCert(caCertificatePem.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, + Path caStore, + Path caCertificate, + String alias, + String workloadUri, + boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String extendedKeyUsage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caCertificate.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()); + X509Certificate leaf = (X509Certificate) keyStore.getCertificate(alias); + Path certificatePem = + writePem(directory.resolve(alias + "-leaf.pem"), "CERTIFICATE", leaf.getEncoded()); + Path privateKeyPem = + writePem( + directory.resolve(alias + "-private.pem"), "PRIVATE KEY", privateKey.getEncoded()); + return new TestIdentity( + alias, workloadUri, server, store, certificatePem, privateKeyPem, privateKey, leaf); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Path outputFile = Files.createTempFile("firemud-start-session-auth-keytool-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(outputFile.toFile()) + .start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(5, TimeUnit.SECONDS); + throw new IllegalStateException("synthetic workload keytool fixture timed out"); + } + String output = Files.readString(outputFile, StandardCharsets.UTF_8); + if (process.exitValue() != 0) { + throw new IllegalStateException("synthetic workload keytool fixture failed: " + output); + } + } finally { + Files.deleteIfExists(outputFile); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java new file mode 100644 index 0000000000..a90028172f --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java @@ -0,0 +1,652 @@ +package net.firedevops.firemud.loggingadmin.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.CallCredentials; +import io.grpc.ClientInterceptor; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionOperatorAuthorizationClientTest { + @TempDir private Path tlsDirectory; + + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("a137588f-4ac6-45ae-984d-5792bdf934b4"); + private static final UUID CLAIM_OWNER = UUID.fromString("5f63c9bb-8488-428d-87fa-b7b9b79a7a8a"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final String CONTROL_UI_TOKEN = "eyJhbGciOiJub25lIn0.operator-secret"; + private static final String LOGGING_WORKLOAD_IDENTITY = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final String OPAQUE_REFERENCE = "r".repeat(43); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void issueAndRecoverUseExactTupleAndClaimIdentityAndReturnValidatedOriginalBytes() + throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-βeta"); + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + byte[] bundle = bundleBytes(tuple, NOW.plusSeconds(300)); + when(stub.issueHumanOperatorAuthorizationReference(any())) + .thenReturn(issueResponse(tuple, NOW.plusSeconds(300), bundle)); + when(stub.recoverOperatorAuthorizationReference(any())) + .thenReturn(recoverResponse(tuple, NOW.plusSeconds(300), bundle)); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + StartSessionOperatorAuthorizationClient.AuthorizationReference issued = + client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L); + StartSessionOperatorAuthorizationClient.AuthorizationReference recovered = + client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 12L); + + assertThat(issued.operatorAuthorizationReference()).isEqualTo(OPAQUE_REFERENCE); + assertThat(issued.authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(issued.expiresAt()).isEqualTo(NOW.plusSeconds(300)); + assertThat(issued.authorityEvidenceBundle()).containsExactly(bundle); + assertThat(issued.bundleReference().sourceFence()).isEqualTo("23"); + assertThat(issued.authenticatedLoggingWorkloadIdentity()) + .isEqualTo(LOGGING_WORKLOAD_IDENTITY); + assertThat(issued.decodedBundle().controlPlaneRequestId()).isEqualTo("client-βeta"); + assertThat(recovered.authorityEvidenceBundle()).containsExactly(bundle); + assertThat(recovered.operatorAuthorizationReference()).isEqualTo(OPAQUE_REFERENCE); + assertThat(recovered.authenticatedLoggingWorkloadIdentity()) + .isEqualTo(LOGGING_WORKLOAD_IDENTITY); + + byte[] callerBytes = issued.authorityEvidenceBundle(); + callerBytes[0] = (byte) '!'; + assertThat(issued.authorityEvidenceBundle()).containsExactly(bundle); + assertThat(issued.toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); + + var issueCaptor = + org.mockito.ArgumentCaptor.forClass( + IssueHumanOperatorAuthorizationReferenceRequest.class); + verify(stub).issueHumanOperatorAuthorizationReference(issueCaptor.capture()); + assertThat(issueCaptor.getValue().getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(issueCaptor.getValue().getControlUiJwt()).isEqualTo(CONTROL_UI_TOKEN); + assertThat(issueCaptor.getValue().getReservationOwnerId()) + .isEqualTo(RESERVATION_OWNER.toString()); + assertThat(issueCaptor.getValue().getReservationClaimFence()).isEqualTo(9L); + assertThat(issueCaptor.getValue().getCurrentClaimOwnerId()).isEqualTo(CLAIM_OWNER.toString()); + assertThat(issueCaptor.getValue().getCurrentClaimFence()).isEqualTo(11L); + + var recoverCaptor = + org.mockito.ArgumentCaptor.forClass(RecoverOperatorAuthorizationReferenceRequest.class); + verify(stub).recoverOperatorAuthorizationReference(recoverCaptor.capture()); + assertThat(recoverCaptor.getValue().getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(recoverCaptor.getValue().getReservationOwnerId()) + .isEqualTo(RESERVATION_OWNER.toString()); + assertThat(recoverCaptor.getValue().getReservationClaimFence()).isEqualTo(9L); + assertThat(recoverCaptor.getValue().getCurrentClaimOwnerId()) + .isEqualTo(CLAIM_OWNER.toString()); + assertThat(recoverCaptor.getValue().getCurrentClaimFence()).isEqualTo(12L); + + var credentialsCaptor = ArgumentCaptor.forClass(CallCredentials.class); + verify(stub, times(2)).withCallCredentials(credentialsCaptor.capture()); + assertThat(credentialsCaptor.getAllValues()) + .allSatisfy( + credentials -> + assertThat(credentials) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class)); + var interceptorCaptor = ArgumentCaptor.forClass(ClientInterceptor[].class); + verify(stub, times(2)).withInterceptors(interceptorCaptor.capture()); + assertThat(interceptorCaptor.getAllValues()) + .allSatisfy( + interceptors -> { + assertThat(interceptors).hasSize(1); + assertThat(interceptors[0]) + .isInstanceOf(GrpcServerPeerIdentityClientInterceptor.class); + }); + assertThat(StartSessionOperatorAuthorizationClient.accountServerUri("world-runtime")) + .isEqualTo("spiffe://firemud/ns/world-runtime/sa/account-service"); + } + } + + @Test + void accountEndpointIsTakenFromServiceEndpointsAndOnlyTheAccountStubIsCalled() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-endpoint"); + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + byte[] bundle = bundleBytes(tuple, NOW.plusSeconds(300)); + when(stub.issueHumanOperatorAuthorizationReference(any())) + .thenReturn(issueResponse(tuple, NOW.plusSeconds(300), bundle)); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + assertThat(client.accountTarget()).isEqualTo("account-service.operator.svc:6565"); + client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L); + verify(stub).issueHumanOperatorAuthorizationReference(any()); + verify(stub, never()).recoverOperatorAuthorizationReference(any()); + } + } + + @Test + void rejectsMalformedUnknownChangedOrExpiredAccountResponses() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-invalid-response"); + byte[] validBundle = bundleBytes(tuple, NOW.plusSeconds(300)); + IssueHumanOperatorAuthorizationReferenceResponse valid = + issueResponse(tuple, NOW.plusSeconds(300), validBundle); + + assertRejected(tuple, valid.toBuilder().setOperatorAuthorizationReference("bad").build()); + assertRejected(tuple, valid.toBuilder().setAuthorizationReferenceFingerprint("bad").build()); + assertRejected(tuple, valid.toBuilder().clearAuthenticatedLoggingWorkloadIdentity().build()); + assertRejected( + tuple, + valid.toBuilder() + .setAuthenticatedLoggingWorkloadIdentity( + "spiffe://firemud/ns/other/sa/logging-admin-service") + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setAuthenticatedLoggingWorkloadIdentity( + "spiffe://firemud/ns/world-runtime/sa/game-session-service") + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setAuthenticatedLoggingWorkloadIdentity( + "SPIFFE://firemud/ns/world-runtime/sa/logging-admin-service") + .build()); + assertRejected(tuple, valid.toBuilder().setUnknownFields(unknownFields()).build()); + assertRejected(tuple, valid.toBuilder().clearExpiresAt().build()); + assertRejected(tuple, valid.toBuilder().clearBundleReference().build()); + assertRejected( + tuple, + valid.toBuilder() + .setExpiresAt( + timestamp(NOW.plusSeconds(300)).toBuilder() + .setUnknownFields(unknownFields()) + .build()) + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setBundleReference( + valid.getBundleReference().toBuilder().setSourceVersion("18").build()) + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setBundleReference( + valid.getBundleReference().toBuilder().setUnknownFields(unknownFields()).build()) + .build()); + assertRejected(tuple, valid.toBuilder().setExpiresAt(timestamp(NOW.plusSeconds(301))).build()); + assertRejected(tuple, valid.toBuilder().setExpiresAt(timestamp(NOW.minusSeconds(1))).build()); + + RecoverOperatorAuthorizationReferenceResponse validRecovery = + recoverResponse(tuple, NOW.plusSeconds(300), validBundle); + assertRecoverRejected( + tuple, validRecovery.toBuilder().clearAuthenticatedLoggingWorkloadIdentity().build()); + + Map changedTupleBundle = read(validBundle); + object(object(changedTupleBundle.get("issuanceOperationIdentity"))) + .put("mutationDigest", "c".repeat(64)); + assertRejected( + tuple, + valid.toBuilder() + .setAuthorityEvidenceBundle(ByteString.copyFrom(canonical(changedTupleBundle))) + .build()); + + Map extraAssurance = read(validBundle); + object(extraAssurance.get("issuanceEvidence")).put("assurance", "forbidden"); + assertRejected( + tuple, + valid.toBuilder() + .setAuthorityEvidenceBundle(ByteString.copyFrom(canonical(extraAssurance))) + .build()); + } + + @Test + void rejectsInvalidCallerTupleFenceAndTokenBeforeCallingAccount() throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-invalid-request"); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 0L, CLAIM_OWNER, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> client.issueHuman(tuple, "bad token\n", RESERVATION_OWNER, 1L, CLAIM_OWNER, 1L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.recover(tuple, new UUID(0L, 0L), 1L, CLAIM_OWNER, 1L)) + .isInstanceOf(IllegalArgumentException.class); + verify(stub, never()).issueHumanOperatorAuthorizationReference(any()); + verify(stub, never()).recoverOperatorAuthorizationReference(any()); + } + } + + @Test + void refusesIssueAndRecoverWithoutReadableFileBackedMtlsBeforeCallingAccount() throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-missing-mtls"); + + CommonGrpcClientProperties plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + CommonGrpcClientProperties missing = new CommonGrpcClientProperties(); + CommonGrpcClientProperties classpath = new CommonGrpcClientProperties(); + classpath.setCertChain("classpath:application.yml"); + classpath.setPrivateKey("classpath:application.yml"); + classpath.setCaCert("classpath:application.yml"); + CommonGrpcClientProperties directoryInsteadOfCertificate = fileBackedTlsProperties(); + directoryInsteadOfCertificate.setCertChain(tlsDirectory.toString()); + CommonGrpcClientProperties incomplete = fileBackedTlsProperties(); + incomplete.setCaCert(null); + + for (CommonGrpcClientProperties invalidTls : + List.of(plaintext, missing, classpath, directoryInsteadOfCertificate, incomplete)) { + try (TestClient client = new TestClient(stub, invalidTls)) { + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class); + } + } + verify(stub, never()).issueHumanOperatorAuthorizationReference(any()); + verify(stub, never()).recoverOperatorAuthorizationReference(any()); + } + + @Test + void unavailableAccountResponseRemainsUnavailableWithoutCreatingFallback() throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.issueHumanOperatorAuthorizationReference(any())) + .thenThrow(Status.UNAVAILABLE.withDescription("account unavailable").asRuntimeException()); + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-unavailable"); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + Throwable failure = + catchThrowable( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)); + assertThat(failure).isInstanceOf(StatusRuntimeException.class); + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + } + } + + @Test + void deniesIssueAndRecoverBeforeAccountUnderSqlOrSynchronization() throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-no-ambient-transaction"); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clear(); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.clear(); + } + + verify(stub, never()).issueHumanOperatorAuthorizationReference(any()); + verify(stub, never()).recoverOperatorAuthorizationReference(any()); + } + } + + @Test + void rejectsAccountReferenceLifetimeAboveItsConfiguredMaximum() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-overlong-reference"); + assertRejected( + tuple, + issueResponse(tuple, NOW.plusSeconds(301), bundleBytes(tuple, NOW.plusSeconds(301)))); + } + + private void assertRejected( + StartSessionPreAuthorizationReservationTuple tuple, + IssueHumanOperatorAuthorizationReferenceResponse response) + throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.issueHumanOperatorAuthorizationReference(any())).thenReturn(response); + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class); + } + } + + private void assertRecoverRejected( + StartSessionPreAuthorizationReservationTuple tuple, + RecoverOperatorAuthorizationReferenceResponse response) + throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.recoverOperatorAuthorizationReference(any())).thenReturn(response); + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class); + } + } + + private static IssueHumanOperatorAuthorizationReferenceResponse issueResponse( + StartSessionPreAuthorizationReservationTuple tuple, Instant expiry, byte[] bundle) { + return IssueHumanOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(OPAQUE_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setExpiresAt(timestamp(expiry)) + .setAuthorityEvidenceBundle(ByteString.copyFrom(bundle)) + .setBundleReference(reference()) + .setAuthenticatedLoggingWorkloadIdentity(LOGGING_WORKLOAD_IDENTITY) + .build(); + } + + private static RecoverOperatorAuthorizationReferenceResponse recoverResponse( + StartSessionPreAuthorizationReservationTuple tuple, Instant expiry, byte[] bundle) { + return RecoverOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(OPAQUE_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setExpiresAt(timestamp(expiry)) + .setAuthorityEvidenceBundle(ByteString.copyFrom(bundle)) + .setBundleReference(reference()) + .setAuthenticatedLoggingWorkloadIdentity(LOGGING_WORKLOAD_IDENTITY) + .build(); + } + + private static Timestamp timestamp(Instant instant) { + return Timestamp.newBuilder() + .setSeconds(instant.getEpochSecond()) + .setNanos(instant.getNano()) + .build(); + } + + private static AuthorityEvidenceBundleReference reference() { + return AuthorityEvidenceBundleReference.newBuilder() + .setBundleVersion(StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION) + .setSourceVersion("17") + .setSourceFence("23") + .setLinearization("18446744073709551615") + .build(); + } + + private static byte[] bundleBytes( + StartSessionPreAuthorizationReservationTuple tuple, Instant expiry) throws Exception { + String tenantId = TENANT_ID.toString(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + NOW.toString(), + "expiresAt", + expiry.toString()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map bundle = + new LinkedHashMap<>( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence)); + return canonical(bundle); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Logging Account client contract"); + return StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR_ID, action); + } + + private static byte[] canonical(Object value) throws IOException { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static Map read(byte[] bytes) throws IOException { + return JSON.readValue(bytes, new tools.jackson.core.type.TypeReference<>() {}); + } + + @SuppressWarnings("unchecked") + private static Map object(Object value) { + return (Map) value; + } + + private static final class TestClient extends StartSessionOperatorAuthorizationClient { + private final StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub; + + private TestClient( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub, + CommonGrpcClientProperties tlsProperties) + throws Exception { + super( + endpoints(), + tlsProperties, + stubChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + Clock.fixed(NOW, ZoneOffset.UTC)); + this.stub = stub; + when(stub.withCallCredentials(any(CallCredentials.class))).thenReturn(stub); + when(stub.withInterceptors(any(ClientInterceptor[].class))).thenReturn(stub); + String reloadSetting = System.getProperty("firemud.grpc.tls-reload.enabled"); + System.setProperty("firemud.grpc.tls-reload.enabled", "false"); + try { + initialize(); + } finally { + if (reloadSetting == null) { + System.clearProperty("firemud.grpc.tls-reload.enabled"); + } else { + System.setProperty("firemud.grpc.tls-reload.enabled", reloadSetting); + } + } + } + + @Override + protected StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + buildStub(ManagedChannel channel) { + return applyStubCustomizer(stub); + } + + private String accountTarget() { + return configuredTarget(endpoints()); + } + } + + private static ServiceEndpointsProperties endpoints() { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account-service.operator.svc:6565"); + return endpoints; + } + + private CommonGrpcClientProperties fileBackedTlsProperties() throws IOException { + Path certChain = tlsDirectory.resolve("client.crt"); + Path privateKey = tlsDirectory.resolve("client.key"); + Path caCert = tlsDirectory.resolve("ca.crt"); + Files.writeString(certChain, "test-only certificate placeholder"); + Files.writeString(privateKey, "test-only private-key placeholder"); + Files.writeString(caCert, "test-only CA placeholder"); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(certChain.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caCert.toString()); + return properties; + } + + private static GrpcChannelFactory stubChannelFactory() { + ManagedChannel channel = mock(ManagedChannel.class); + return new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive) { + return channel; + } + }; + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java new file mode 100644 index 0000000000..aa085c4d28 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java @@ -0,0 +1,1109 @@ +package net.firedevops.firemud.loggingadmin.operator; + +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.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +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.Status; +import java.io.IOException; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.StartSessionOwnerAuthorizationProgress; +import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; +import net.firedevops.firemud.loggingadmin.client.GameSessionClient; +import net.firedevops.firemud.loggingadmin.client.GameSessionClient.StartSessionOwnerHandoffResult; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient.AuthorizationReference; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.OwnerDispatchResult; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.Progress; +import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.Result; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizedSnapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionAuthorizationCoordinatorTest { + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID ORIGINAL_OWNER = + UUID.fromString("a137588f-4ac6-45ae-984d-5792bdf934b4"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("69116466-a576-4fa6-9e11-4c0c6b2a92f0"); + private static final UUID OWNER_MUTATION_ID = + UUID.fromString("89da7d84-12f5-4cf8-b69b-30ba8eb115a4"); + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final long NOW_MILLIS = NOW.toEpochMilli(); + private static final String CONTROL_UI_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0In0.c2ln"; + private static final String OPAQUE_REFERENCE = "r".repeat(43); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String LOGGING_IDENTITY = + "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final StartSessionPreAuthorizationReservationRepository repository = + mock(StartSessionPreAuthorizationReservationRepository.class); + private final StartSessionPreAuthorizationReservationService reservations = + StartSessionReservationMutationTestFixtures.forMockBackedUnitTest( + repository, Clock.fixed(NOW, ZoneOffset.UTC)); + private final StartSessionOperatorAuthorizationClient accountClient = + mock(StartSessionOperatorAuthorizationClient.class); + private final AtomicReference exactReadback = new AtomicReference<>(); + private final StartSessionAuthorizationCoordinator coordinator = + new StartSessionAuthorizationCoordinator("world-runtime", reservations, accountClient); + + @BeforeEach + void setAuthenticatedTenantAdminContext() { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + } + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientReference() + throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-winner"); + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true), + new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), + eq(CONTROL_UI_TOKEN), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L))) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + + Result first = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + Result duplicate = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(first.progress()).isEqualTo(Progress.OWNER_EXECUTION_PENDING); + assertThat(first.handoff()).isNotNull(); + assertThat(first.handoff().ownerExecutionHandoff().handoffId()).isNotNull(); + assertThat(first.handoff().accountResponse().operatorAuthorizationReference()) + .isEqualTo(OPAQUE_REFERENCE); + assertThat(first.handoff().postAuthorizationTuple().authenticatedWorkloadIdentity()) + .isEqualTo(LOGGING_IDENTITY); + assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + assertThat(duplicate.handoff()).isNull(); + assertThat(duplicate.authorizedReadback()).isPresent(); + assertThat(first.toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); + assertThat(duplicate.toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); + assertThat(first.handoff().toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); + + ArgumentCaptor originalOwner = ArgumentCaptor.forClass(UUID.class); + ArgumentCaptor currentOwner = ArgumentCaptor.forClass(UUID.class); + ArgumentCaptor persistedTuple = ArgumentCaptor.forClass(String.class); + ArgumentCaptor handoffId = ArgumentCaptor.forClass(UUID.class); + InOrder persistenceOrder = inOrder(accountClient, repository); + persistenceOrder + .verify(repository) + .acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L)); + persistenceOrder + .verify(repository) + .markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS)); + persistenceOrder + .verify(accountClient) + .issueHuman( + eq(shared(tuple)), + eq(CONTROL_UI_TOKEN), + originalOwner.capture(), + eq(1L), + currentOwner.capture(), + eq(1L)); + assertThat(originalOwner.getValue()).isEqualTo(currentOwner.getValue()); + verify(accountClient, org.mockito.Mockito.times(1)) + .issueHuman( + eq(shared(tuple)), + eq(CONTROL_UI_TOKEN), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L)); + verify(accountClient, never()).recover(any(), any(), anyLong(), any(), anyLong()); + persistenceOrder + .verify(repository) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + persistedTuple.capture(), + eq(NOW_MILLIS)); + assertThat(persistedTuple.getValue()) + .contains(LOGGING_IDENTITY) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(CONTROL_UI_TOKEN); + persistenceOrder.verify(repository).findAuthorizedExact(eq(tuple)); + persistenceOrder + .verify(repository) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(persistedTuple.getValue()), + handoffId.capture(), + eq(NOW_MILLIS)); + assertThat(handoffId.getValue()).isEqualTo(first.handoff().ownerExecutionHandoff().handoffId()); + } + + @Test + void namespaceJwtAndHumanTenantAdminGuardsRunBeforeStorage() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-input-guards"); + StartSessionOperatorAction action = tuple.action(); + StartSessionOperatorAction wrongNamespaceAction = + new StartSessionOperatorAction( + action.actionFamilySchemaId(), + action.actionFamilySchemaVersion(), + new StartSessionOperatorAction.Scope(TENANT_ID, "other-runtime"), + action.target(), + action.expectedVersion(), + action.mutation(), + action.auditReason()); + + assertThatThrownBy( + () -> + coordinator.begin( + tuple.controlPlaneRequestId(), wrongNamespaceAction, CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> coordinator.begin(tuple.controlPlaneRequestId(), action, "not-a-jwt")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("JWT envelope is malformed"); + assertThatThrownBy( + () -> + coordinator.begin( + tuple.controlPlaneRequestId(), action, CONTROL_UI_TOKEN + ".extra")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("JWT envelope is malformed"); + + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("moderator")), + false, + null, + null); + assertThatThrownBy( + () -> coordinator.begin(tuple.controlPlaneRequestId(), action, CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenantAdmin authority"); + + verifyNoInteractions(repository, accountClient); + } + + @Test + void beginAcceptsCanonicalCompactThreeSegmentJwtEnvelope() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-valid-jwt-envelope"); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); + when(repository.findAuthorizedExact(eq(tuple))).thenReturn(Optional.empty()); + + Result result = + coordinator.begin(tuple.controlPlaneRequestId(), tuple.action(), CONTROL_UI_TOKEN); + + assertThat(CONTROL_UI_TOKEN.split("\\.", -1)).hasSize(3); + assertThat(result.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + verify(repository) + .acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L)); + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + } + + @Test + void changedTupleForExistingRequestConflictsWithoutAccountCall() { + StartSessionPreAuthorizationReservationTuple requested = tuple("coordinator-tuple-conflict"); + StartSessionOperatorAction action = requested.action(); + StartSessionOperatorAction changedAction = + new StartSessionOperatorAction( + action.actionFamilySchemaId(), + action.actionFamilySchemaVersion(), + action.scope(), + new StartSessionOperatorAction.Target(92L, action.target().ownerAccountId()), + action.expectedVersion(), + action.mutation(), + action.auditReason()); + StartSessionPreAuthorizationReservationTuple conflicting = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + requested.controlPlaneRequestId(), changedAction); + Snapshot existing = snapshot(conflicting, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire( + eq(requested), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(existing, false)); + + assertThatThrownBy(() -> coordinator.issueHuman(requested, CONTROL_UI_TOKEN)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + verify(repository, never()) + .markAuthorizationPending( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyLong()); + } + + @Test + void productionReservationMutationRemainsDeniedByDefault() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-default-denial"); + StartSessionPreAuthorizationReservationService productionDefault = + new StartSessionPreAuthorizationReservationService(repository); + + assertThatThrownBy(() -> productionDefault.acquire(tuple)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("disabled for production construction"); + + verifyNoInteractions(repository); + } + + @Test + void missingIndependentAuthorizedReadbackLeavesAuthorizationUnknownAndDoesNotHandoff() + throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-readback-missing"); + stubInitialReservation(tuple); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + when(repository.findAuthorizedExact(eq(tuple))).thenReturn(Optional.empty()); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.AUTHORIZATION_READBACK_MISMATCH); + assertThat(result.snapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(result.handoff()).isNull(); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + } + + @Test + void conflictingIndependentAuthorizedReadbackCannotAdvanceOwnerPending() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-readback-conflict"); + stubInitialReservation(tuple); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + when(repository.findAuthorizedExact(eq(tuple))) + .thenAnswer( + invocation -> { + AuthorizedSnapshot exact = exactReadback.get(); + Snapshot snapshot = exact.reservationSnapshot(); + Snapshot substituted = + new Snapshot( + snapshot.tuple(), + snapshot.mutationDigest(), + snapshot.phase(), + snapshot.state(), + snapshot.reservationClaimFence(), + snapshot.claimFence(), + snapshot.claimExpiresAtEpochMillis() + 1L, + snapshot.claimState(), + snapshot.claimPurpose()); + return Optional.of( + new AuthorizedSnapshot( + substituted, + exact.postAuthorizationTuple(), + exact.reservationOwnerId(), + exact.currentClaimOwnerId(), + exact.handoff())); + }); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.AUTHORIZATION_READBACK_MISMATCH); + assertThat(result.handoff()).isNull(); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + } + + @Test + void recoveryUsesOriginalOwnerAndFreshFenceAndNeverCallsIssue() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-recovery"); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L); + when(repository.acquireRecoveryClaim( + eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + pending, ORIGINAL_OWNER))); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.recover( + eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + + Result result = coordinator.recover(tuple); + + assertThat(result.progress()).isEqualTo(Progress.OWNER_EXECUTION_PENDING); + assertThat(result.handoff().postAuthorizationTuple().reservationOwnerId()) + .isEqualTo(ORIGINAL_OWNER); + ArgumentCaptor currentOwner = ArgumentCaptor.forClass(UUID.class); + verify(accountClient) + .recover(eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), currentOwner.capture(), eq(3L)); + assertThat(currentOwner.getValue()).isNotEqualTo(ORIGINAL_OWNER); + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + } + + @Test + void issueHumanAndDispatchForwardsOnlyAfterDurableOwnerPendingAndOnlyOnce() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-issue-dispatch"); + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); + Snapshot alreadyPending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true), + new StartSessionPreAuthorizationReservationRepository.AcquireResult( + alreadyPending, false)); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult( + alreadyPending, true)); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), + eq(CONTROL_UI_TOKEN), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L))) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + GameSessionClient ownerClient = mock(GameSessionClient.class); + StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); + when(ownerClient.authorizeStartSession(any())).thenReturn(ownerEcho); + + OwnerDispatchResult first = + coordinator.issueHumanAndDispatch(tuple, CONTROL_UI_TOKEN, ownerClient); + OwnerDispatchResult duplicate = + coordinator.issueHumanAndDispatch(tuple, CONTROL_UI_TOKEN, ownerClient); + + assertThat(first.progress()).isEqualTo(Progress.OWNER_EXECUTION_PENDING); + assertThat(first.ownerEcho()).contains(ownerEcho); + assertThat(first.toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); + assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + assertThat(duplicate.ownerEcho()).isEmpty(); + + ArgumentCaptor persistedTuple = ArgumentCaptor.forClass(String.class); + ArgumentCaptor + ownerHandoff = + ArgumentCaptor.forClass( + StartSessionAuthorizationCoordinator.TransientOwnerExecutionHandoff.class); + InOrder dispatchOrder = inOrder(accountClient, repository, ownerClient); + dispatchOrder + .verify(accountClient) + .issueHuman( + eq(shared(tuple)), + eq(CONTROL_UI_TOKEN), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L)); + dispatchOrder + .verify(repository) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + persistedTuple.capture(), + eq(NOW_MILLIS)); + dispatchOrder + .verify(repository) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(persistedTuple.getValue()), + any(UUID.class), + eq(NOW_MILLIS)); + dispatchOrder.verify(ownerClient).authorizeStartSession(ownerHandoff.capture()); + assertThat(ownerHandoff.getValue().postAuthorizationTuple().canonicalJson()) + .isEqualTo(persistedTuple.getValue()); + verify(ownerClient, org.mockito.Mockito.times(1)).authorizeStartSession(any()); + } + + @Test + void recoverAndDispatchForwardsTheOriginalRecoveredOperationOnce() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-recover-dispatch"); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L); + when(repository.acquireRecoveryClaim( + eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + pending, ORIGINAL_OWNER))); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.recover( + eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + GameSessionClient ownerClient = mock(GameSessionClient.class); + StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); + when(ownerClient.authorizeStartSession(any())).thenReturn(ownerEcho); + + OwnerDispatchResult result = coordinator.recoverAndDispatch(tuple, ownerClient); + + assertThat(result.progress()).isEqualTo(Progress.OWNER_EXECUTION_PENDING); + assertThat(result.ownerEcho()).contains(ownerEcho); + InOrder dispatchOrder = inOrder(accountClient, repository, ownerClient); + dispatchOrder + .verify(accountClient) + .recover(eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L)); + dispatchOrder + .verify(repository) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(3L), + anyString(), + eq(NOW_MILLIS)); + dispatchOrder + .verify(repository) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(3L), + anyString(), + any(UUID.class), + eq(NOW_MILLIS)); + dispatchOrder.verify(ownerClient).authorizeStartSession(any()); + verify(ownerClient, org.mockito.Mockito.times(1)).authorizeStartSession(any()); + } + + @Test + void nonWinningAndUnavailableAuthorizationPathsNeverDispatchOwner() { + StartSessionPreAuthorizationReservationTuple duplicateTuple = + tuple("coordinator-dispatch-duplicate"); + Snapshot pending = snapshot(duplicateTuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire( + eq(duplicateTuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); + when(repository.findAuthorizedExact(eq(duplicateTuple))).thenReturn(Optional.empty()); + StartSessionPreAuthorizationReservationTuple unavailableTuple = + tuple("coordinator-dispatch-unavailable"); + when(repository.acquireRecoveryClaim( + eq(unavailableTuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn(Optional.empty()); + GameSessionClient ownerClient = mock(GameSessionClient.class); + + OwnerDispatchResult duplicate = + coordinator.issueHumanAndDispatch(duplicateTuple, CONTROL_UI_TOKEN, ownerClient); + OwnerDispatchResult unavailable = coordinator.recoverAndDispatch(unavailableTuple, ownerClient); + + assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + assertThat(duplicate.ownerEcho()).isEmpty(); + assertThat(unavailable.progress()).isEqualTo(Progress.RECOVERY_UNAVAILABLE); + assertThat(unavailable.ownerEcho()).isEmpty(); + verifyNoInteractions(ownerClient); + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + verify(accountClient, never()).recover(any(), any(), anyLong(), any(), anyLong()); + } + + @Test + void ambiguousOwnerDispatchPropagatesAndExactDuplicateDoesNotRedeliver() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-dispatch-timeout"); + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); + Snapshot alreadyPending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true), + new StartSessionPreAuthorizationReservationRepository.AcquireResult( + alreadyPending, false)); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult( + alreadyPending, true)); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), eq(1L), any(UUID.class), eq(1L))) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + GameSessionClient ownerClient = mock(GameSessionClient.class); + io.grpc.StatusRuntimeException ambiguous = Status.UNAVAILABLE.asRuntimeException(); + when(ownerClient.authorizeStartSession(any())).thenThrow(ambiguous); + + assertThatThrownBy( + () -> coordinator.issueHumanAndDispatch(tuple, CONTROL_UI_TOKEN, ownerClient)) + .isSameAs(ambiguous); + OwnerDispatchResult duplicate = + coordinator.issueHumanAndDispatch(tuple, CONTROL_UI_TOKEN, ownerClient); + + assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + assertThat(duplicate.ownerEcho()).isEmpty(); + verify(ownerClient, org.mockito.Mockito.times(1)).authorizeStartSession(any()); + verify(accountClient, org.mockito.Mockito.times(1)) + .issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), eq(1L), any(UUID.class), eq(1L)); + } + + @Test + void ownerPendingDuplicateCasDoesNotReturnTransientHandoff() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-owner-duplicate"); + stubInitialReservation(tuple); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, false); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + assertThat(result.handoff()).isNull(); + assertThat(result.toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); + verify(repository) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + any(UUID.class), + eq(NOW_MILLIS)); + } + + @Test + void ownerPendingTransitionFailureNeverReturnsTransientPayload() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-owner-stale"); + stubInitialReservation(tuple); + AuthorizationReference response = authorizationReference(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenReturn(response); + stubAuthorizationEnrichment(tuple, true, true); + when(repository.beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + any(UUID.class), + eq(NOW_MILLIS))) + .thenThrow( + new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId())); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason + .OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN); + assertThat(result.handoff()).isNull(); + verify(repository) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + eq(NOW_MILLIS)); + verify(repository) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + any(UUID.class), + eq(NOW_MILLIS)); + } + + @Test + void uncertainAccountCallLeavesPendingAndIsNotRetried() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-timeout"); + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true), + new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + when(repository.findAuthorizedExact(eq(tuple))).thenReturn(Optional.empty()); + + Result first = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + Result duplicate = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(first.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(first.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_ISSUANCE_OUTCOME_UNKNOWN); + assertThat(first.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + + verify(repository, never()) + .completeAuthorization( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), anyLong()); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + verify(accountClient, never()).recover(any(), any(), anyLong(), any(), anyLong()); + verify(accountClient, org.mockito.Mockito.times(1)) + .issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong()); + } + + @Test + void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-mismatch"); + StartSessionPreAuthorizationReservationTuple substituted = tuple("coordinator-substituted"); + stubInitialReservation(tuple); + AuthorizationReference substitutedResponse = authorizationReference(substituted); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenReturn(substitutedResponse); + + Result invalidAccountResult = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(invalidAccountResult.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(invalidAccountResult.pendingReason()) + .contains(StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_RESPONSE_INVALID); + verify(repository, never()) + .completeAuthorization( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), anyLong()); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + + StartSessionPreAuthorizationReservationTuple staleTuple = tuple("coordinator-stale-return"); + stubInitialReservation(staleTuple); + AuthorizationReference staleResponse = authorizationReference(staleTuple); + when(accountClient.issueHuman( + eq(shared(staleTuple)), + anyString(), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong())) + .thenReturn(staleResponse); + when(repository.completeAuthorization( + eq(staleTuple), + eq(staleTuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + eq(NOW_MILLIS))) + .thenThrow( + new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + staleTuple.controlPlaneRequestId())); + + Result staleCompletion = coordinator.issueHuman(staleTuple, CONTROL_UI_TOKEN); + assertThat(staleCompletion.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(staleCompletion.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.LOCAL_COMPLETION_OUTCOME_UNKNOWN); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + } + + private void stubInitialReservation(StartSessionPreAuthorizationReservationTuple tuple) { + Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true)); + when(repository.markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); + } + + private void stubAuthorizationEnrichment( + StartSessionPreAuthorizationReservationTuple tuple, + boolean transitioned, + boolean mayDispatch) { + exactReadback.set(null); + when(repository.completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong(), + anyString(), + eq(NOW_MILLIS))) + .thenAnswer( + invocation -> { + UUID reservationOwner = invocation.getArgument(2); + long reservationFence = invocation.getArgument(3); + UUID currentOwner = invocation.getArgument(4); + long currentFence = invocation.getArgument(5); + String exactPostTupleJson = invocation.getArgument(6); + StartSessionPostAuthorizationExecutionTuple postTuple = + StartSessionPostAuthorizationExecutionTuple.decode( + exactPostTupleJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + Snapshot authorized = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZED, + reservationFence, + currentFence, + NOW_MILLIS + 30_000L, + ClaimState.ACTIVE, + currentOwner.equals(reservationOwner) && currentFence == reservationFence + ? ClaimPurpose.ORIGINAL + : ClaimPurpose.AUTHORIZATION_RECOVERY); + AuthorizedSnapshot authorizedSnapshot = + new AuthorizedSnapshot( + authorized, postTuple, reservationOwner, currentOwner, null); + exactReadback.set(authorizedSnapshot); + return new StartSessionPreAuthorizationReservationRepository + .AuthorizationTransitionResult(authorizedSnapshot, transitioned); + }); + when(repository.findAuthorizedExact(eq(tuple))) + .thenAnswer(invocation -> Optional.ofNullable(exactReadback.get())); + when(repository.beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong(), + anyString(), + any(UUID.class), + eq(NOW_MILLIS))) + .thenAnswer( + invocation -> { + UUID reservationOwner = invocation.getArgument(2); + long reservationFence = invocation.getArgument(3); + UUID currentOwner = invocation.getArgument(4); + long currentFence = invocation.getArgument(5); + String exactPostTupleJson = invocation.getArgument(6); + UUID handoffId = invocation.getArgument(7); + StartSessionPostAuthorizationExecutionTuple postTuple = + StartSessionPostAuthorizationExecutionTuple.decode( + exactPostTupleJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + Snapshot ownerPending = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.OWNER_EXECUTION, + State.OWNER_EXECUTION_PENDING, + reservationFence, + currentFence, + NOW_MILLIS + 30_000L, + ClaimState.ACTIVE, + currentOwner.equals(reservationOwner) && currentFence == reservationFence + ? ClaimPurpose.ORIGINAL + : ClaimPurpose.AUTHORIZATION_RECOVERY); + AuthorizedSnapshot ownerPendingSnapshot = + new AuthorizedSnapshot( + ownerPending, + postTuple, + reservationOwner, + currentOwner, + new OwnerExecutionHandoff(handoffId)); + exactReadback.set(ownerPendingSnapshot); + return new StartSessionPreAuthorizationReservationRepository + .OwnerExecutionTransitionResult(ownerPendingSnapshot, mayDispatch); + }); + } + + private static AuthorizationReference authorizationReference( + StartSessionPreAuthorizationReservationTuple tuple) throws Exception { + AuthorizationReference response = mock(AuthorizationReference.class); + when(response.operatorAuthorizationReference()).thenReturn(OPAQUE_REFERENCE); + when(response.authorizationReferenceFingerprint()).thenReturn(FINGERPRINT); + when(response.expiresAt()).thenReturn(NOW.plusSeconds(300)); + when(response.authorityEvidenceBundle()).thenReturn(bundleBytes(tuple, NOW.plusSeconds(300))); + when(response.bundleReference()).thenReturn(bundleReference()); + when(response.authenticatedLoggingWorkloadIdentity()).thenReturn(LOGGING_IDENTITY); + return response; + } + + private static StartSessionOwnerHandoffResult ownerEcho( + StartSessionPreAuthorizationReservationTuple tuple) { + return new StartSessionOwnerHandoffResult( + tuple.action().scope().targetNamespace(), + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + 7L, + "OWNER_EXECUTION_PENDING", + StartSessionOwnerAuthorizationProgress + .START_SESSION_OWNER_AUTHORIZATION_PROGRESS_ACCOUNT_PROJECTION_ATTACHED); + } + + private static byte[] bundleBytes( + StartSessionPreAuthorizationReservationTuple tuple, Instant expiresAt) throws IOException { + String tenantId = TENANT_ID.toString(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + NOW.toString(), + "expiresAt", + expiresAt.toString()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + } + + private static StartSessionAuthorityEvidenceBundle.BundleReference bundleReference() { + return new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + } + + private static Snapshot snapshot( + StartSessionPreAuthorizationReservationTuple tuple, + State state, + long reservationFence, + long claimFence) { + return new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + state, + reservationFence, + claimFence, + NOW_MILLIS + 30_000L, + ClaimState.ACTIVE, + claimFence == reservationFence + ? ClaimPurpose.ORIGINAL + : ClaimPurpose.AUTHORIZATION_RECOVERY); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "StartSession coordinator unit proof"); + return StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin(requestId, action); + } + + private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + shared(StartSessionPreAuthorizationReservationTuple tuple) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(tuple.canonicalJson()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentity.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentity.java index 9d66b20f10..4df3a8e32b 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentity.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentity.java @@ -5,6 +5,8 @@ import java.util.Arrays; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; @@ -14,10 +16,10 @@ /** * Exact World-local execution identity for one original human StartSession operation. * - *

This is an integrity value, not authenticated Account or Game Session evidence. The only - * production-safe preparation service still denies because no producer supplies it. Its World - * execution fence is allocated and retained by the World repository, independently of the two - * supplied source fences. + *

This is an integrity value, not by itself authenticated Account or Game Session evidence. The + * explicit Account verifier builds the complete form from Account's returned first observation; + * legacy forms remain read-only and cannot admit a fresh write. Its World execution fence is + * allocated and retained by the World repository, independently of the supplied source fences. */ public final class WorldCanonicalInstanceExecutionIdentity { private static final UUID NIL_UUID = new UUID(0L, 0L); @@ -26,7 +28,12 @@ public final class WorldCanonicalInstanceExecutionIdentity { private final UUID accountWorldParticipationId; private final long accountWorldParticipationFence; private final UUID gameSessionOwnerAttemptId; + private final UUID gameSessionOwnerMutationId; private final long gameSessionOwnerFence; + private final Instant originalGameSessionLeaseExpiresAt; + private final UUID originalAttemptReadRequestId; + private final byte[] originalAttemptEvidenceBytes; + private final String originalAttemptEvidenceDigest; private final UUID canonicalGameInstanceId; private final String preparationInputJson; private final String preparationInputDigest; @@ -40,6 +47,56 @@ public WorldCanonicalInstanceExecutionIdentity( long gameSessionOwnerFence, UUID canonicalGameInstanceId, String exactPreparationInputJson) { + this( + originalPostAuthorizationTuple, + accountWorldParticipationId, + accountWorldParticipationFence, + null, + gameSessionOwnerAttemptId, + gameSessionOwnerFence, + null, + canonicalGameInstanceId, + exactPreparationInputJson, + null); + } + + /** Complete identity built only from Account's exact retained current-attempt response. */ + public WorldCanonicalInstanceExecutionIdentity( + byte[] originalPostAuthorizationTuple, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + OriginalStartSessionCurrentAttemptEvidence.Result originalAttemptEvidence, + UUID canonicalGameInstanceId, + String exactPreparationInputJson) { + this( + originalPostAuthorizationTuple, + accountWorldParticipationId, + accountWorldParticipationFence, + Objects.requireNonNull(gameSessionOwnerMutationId, "gameSessionOwnerMutationId"), + gameSessionOwnerAttemptId, + gameSessionOwnerFence, + Objects.requireNonNull(originalAttemptEvidence, "originalAttemptEvidence"), + canonicalGameInstanceId, + exactPreparationInputJson, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(originalAttemptEvidence) + .toByteArray()); + } + + /** Complete identity retaining the exact Account-returned observation protobuf bytes. */ + public WorldCanonicalInstanceExecutionIdentity( + byte[] originalPostAuthorizationTuple, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + OriginalStartSessionCurrentAttemptEvidence.Result originalAttemptEvidence, + UUID canonicalGameInstanceId, + String exactPreparationInputJson, + byte[] originalAttemptEvidenceBytes) { if (originalPostAuthorizationTuple == null || originalPostAuthorizationTuple.length == 0) { throw new IllegalArgumentException("Exact original StartSession tuple is required"); } @@ -51,6 +108,9 @@ public WorldCanonicalInstanceExecutionIdentity( throw new IllegalArgumentException("accountWorldParticipationFence must be positive"); } requireNonNil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + if (gameSessionOwnerMutationId != null) { + requireNonNil(gameSessionOwnerMutationId, "gameSessionOwnerMutationId"); + } if (gameSessionOwnerFence <= 0L) { throw new IllegalArgumentException("gameSessionOwnerFence must be positive"); } @@ -61,7 +121,48 @@ public WorldCanonicalInstanceExecutionIdentity( this.accountWorldParticipationId = accountWorldParticipationId; this.accountWorldParticipationFence = accountWorldParticipationFence; this.gameSessionOwnerAttemptId = gameSessionOwnerAttemptId; + this.gameSessionOwnerMutationId = gameSessionOwnerMutationId; this.gameSessionOwnerFence = gameSessionOwnerFence; + if (originalAttemptEvidence == null) { + if (gameSessionOwnerMutationId != null || originalAttemptEvidenceBytes != null) { + throw new IllegalArgumentException("Account original-attempt observation is incomplete"); + } + this.originalGameSessionLeaseExpiresAt = null; + this.originalAttemptReadRequestId = null; + this.originalAttemptEvidenceBytes = null; + this.originalAttemptEvidenceDigest = null; + } else { + var observationRequest = originalAttemptEvidence.request(); + if (!MessageDigest.isEqual( + this.originalPostAuthorizationTuple, + observationRequest.canonicalPostAuthorizationTuple()) + || !gameSessionOwnerMutationId.equals(observationRequest.expectedOwnerMutationId()) + || !gameSessionOwnerAttemptId.equals(observationRequest.expectedOwnerAttemptId()) + || gameSessionOwnerFence != observationRequest.expectedOwnerFence() + || !OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( + originalAttemptEvidence.phaseState()) + || !decodedTuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(observationRequest.targetNamespace()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals( + decodedTuple.preAuthorizationTuple().targetOwner()) + || originalAttemptEvidenceBytes == null + || !MessageDigest.isEqual( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + originalAttemptEvidence) + .toByteArray(), + originalAttemptEvidenceBytes)) { + throw new IllegalArgumentException( + "Account original-attempt observation differs from the exact owner operation"); + } + this.originalGameSessionLeaseExpiresAt = originalAttemptEvidence.originalLeaseExpiresAt(); + this.originalAttemptReadRequestId = observationRequest.readRequestId(); + this.originalAttemptEvidenceBytes = originalAttemptEvidenceBytes.clone(); + this.originalAttemptEvidenceDigest = digestBytes(originalAttemptEvidenceBytes); + } this.canonicalGameInstanceId = canonicalGameInstanceId; this.preparationInputJson = exactPreparationInputJson; this.preparationInputDigest = digest(exactPreparationInputJson); @@ -100,6 +201,33 @@ public void requireMatches(Input input, String exactPreparationInputJson) { } } + /** Exact owner observation checks required for every fresh materialization admission. */ + public void requireMatches( + Input input, + WorldCanonicalInstancePreparation.OriginalStartSessionOperationInput operationInput, + String exactPreparationInputJson) { + Objects.requireNonNull(operationInput, "operationInput"); + requireMatches(input, exactPreparationInputJson); + operationInput.requireMatches(input, targetNamespace()); + if (!hasOriginalAttemptEvidence() + || !MessageDigest.isEqual( + originalPostAuthorizationTuple, operationInput.originalPostAuthorizationTuple()) + || !gameSessionOwnerMutationId.equals(operationInput.gameSessionOwnerMutationId()) + || !gameSessionOwnerAttemptId.equals(operationInput.gameSessionOwnerAttemptId()) + || gameSessionOwnerFence != operationInput.gameSessionOwnerFence()) { + throw new IllegalArgumentException( + "Account participation does not bind the exact original Game Session owner attempt"); + } + } + + public boolean hasOriginalAttemptEvidence() { + return gameSessionOwnerMutationId != null + && originalGameSessionLeaseExpiresAt != null + && originalAttemptReadRequestId != null + && originalAttemptEvidenceBytes != null + && originalAttemptEvidenceDigest != null; + } + public byte[] originalPostAuthorizationTuple() { return originalPostAuthorizationTuple.clone(); } @@ -120,10 +248,30 @@ public UUID gameSessionOwnerAttemptId() { return gameSessionOwnerAttemptId; } + public UUID gameSessionOwnerMutationId() { + return gameSessionOwnerMutationId; + } + public long gameSessionOwnerFence() { return gameSessionOwnerFence; } + public Instant originalGameSessionLeaseExpiresAt() { + return originalGameSessionLeaseExpiresAt; + } + + public UUID originalAttemptReadRequestId() { + return originalAttemptReadRequestId; + } + + public byte[] originalAttemptEvidenceBytes() { + return originalAttemptEvidenceBytes == null ? null : originalAttemptEvidenceBytes.clone(); + } + + public String originalAttemptEvidenceDigest() { + return originalAttemptEvidenceDigest; + } + public UUID canonicalGameInstanceId() { return canonicalGameInstanceId; } @@ -165,8 +313,14 @@ boolean exactlyMatches(WorldCanonicalInstanceExecutionIdentity other) { originalPostAuthorizationTuple, other.originalPostAuthorizationTuple) && accountWorldParticipationId.equals(other.accountWorldParticipationId) && accountWorldParticipationFence == other.accountWorldParticipationFence + && Objects.equals(gameSessionOwnerMutationId, other.gameSessionOwnerMutationId) && gameSessionOwnerAttemptId.equals(other.gameSessionOwnerAttemptId) && gameSessionOwnerFence == other.gameSessionOwnerFence + && Objects.equals( + originalGameSessionLeaseExpiresAt, other.originalGameSessionLeaseExpiresAt) + && Objects.equals(originalAttemptReadRequestId, other.originalAttemptReadRequestId) + && Arrays.equals(originalAttemptEvidenceBytes, other.originalAttemptEvidenceBytes) + && Objects.equals(originalAttemptEvidenceDigest, other.originalAttemptEvidenceDigest) && canonicalGameInstanceId.equals(other.canonicalGameInstanceId) && preparationInputJson.equals(other.preparationInputJson); } @@ -182,8 +336,13 @@ public int hashCode() { Arrays.hashCode(originalPostAuthorizationTuple), accountWorldParticipationId, accountWorldParticipationFence, + gameSessionOwnerMutationId, gameSessionOwnerAttemptId, gameSessionOwnerFence, + originalGameSessionLeaseExpiresAt, + originalAttemptReadRequestId, + Arrays.hashCode(originalAttemptEvidenceBytes), + originalAttemptEvidenceDigest, canonicalGameInstanceId, preparationInputJson); } @@ -204,4 +363,14 @@ private static String digest(String value) { throw new IllegalStateException("SHA-256 is unavailable", exception); } } + + private static String digestBytes(byte[] value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java index 6cbb1e5145..6fe3004449 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java @@ -1,8 +1,11 @@ package net.firedevops.firemud.worldmanagement.tenant; +import java.util.Arrays; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.world.RoomTemplateRef; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; @@ -18,6 +21,98 @@ public final class WorldCanonicalInstancePreparation { private WorldCanonicalInstancePreparation() {} + /** + * Original Game Session owner-operation input, deliberately separate from assembly selectors. It + * contains no caller-supplied Account participation coordinates or currentness evidence; Account + * returns those only after authenticating and freezing the exact original sources. + */ + public static final class OriginalStartSessionOperationInput { + private final byte[] originalPostAuthorizationTuple; + private final StartSessionPostAuthorizationExecutionTuple decodedTuple; + private final UUID gameSessionOwnerMutationId; + private final UUID gameSessionOwnerAttemptId; + private final long gameSessionOwnerFence; + + public OriginalStartSessionOperationInput( + byte[] originalPostAuthorizationTuple, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence) { + if (originalPostAuthorizationTuple == null + || originalPostAuthorizationTuple.length == 0 + || originalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException("Exact original StartSession tuple is required"); + } + this.originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + this.decodedTuple = + StartSessionPostAuthorizationExecutionTuple.decode(this.originalPostAuthorizationTuple); + if (!Arrays.equals(this.originalPostAuthorizationTuple, decodedTuple.canonicalBytes())) { + throw new IllegalArgumentException("Original StartSession tuple must be canonical"); + } + this.gameSessionOwnerMutationId = + requireNonNil(gameSessionOwnerMutationId, "ownerMutationId"); + this.gameSessionOwnerAttemptId = requireNonNil(gameSessionOwnerAttemptId, "ownerAttemptId"); + if (gameSessionOwnerFence <= 0L) { + throw new IllegalArgumentException("Game Session owner fence must be positive"); + } + this.gameSessionOwnerFence = gameSessionOwnerFence; + var original = decodedTuple.preAuthorizationTuple(); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(original.actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals(original.targetOwner())) { + throw new IllegalArgumentException( + "Original operation must be the human Game Session StartSession tuple"); + } + } + + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + public StartSessionPostAuthorizationExecutionTuple decodedTuple() { + return decodedTuple; + } + + public UUID gameSessionOwnerMutationId() { + return gameSessionOwnerMutationId; + } + + public UUID gameSessionOwnerAttemptId() { + return gameSessionOwnerAttemptId; + } + + public long gameSessionOwnerFence() { + return gameSessionOwnerFence; + } + + /** Binds the original tuple and owner attempt to the separately assembled immutable target. */ + public void requireMatches(Input input, String targetNamespace) { + Objects.requireNonNull(input, "input"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + var original = decodedTuple.preAuthorizationTuple(); + var action = original.action(); + var descriptor = input.completeLaunchBinding().evidence().descriptor(); + var world = input.gameSessionReadEvidence(); + if (!targetNamespace.equals(action.scope().targetNamespace()) + || !targetNamespace.equals(world.targetNamespace()) + || !action.scope().tenantId().equals(world.canonicalTenantId()) + || !decodedTuple.controlPlaneRequestId().equals(world.controlPlaneRequestId()) + || !original.controlPlaneRequestId().equals(world.controlPlaneRequestId()) + || action.target().gameTemplateId() != descriptor.gameTemplateId()) { + throw new IllegalArgumentException( + "Original StartSession tuple differs from the exact assembled World operation"); + } + } + + private static UUID requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + return value; + } + } + /** Complete immutable request to materialize one generation-free selected canonical graph. */ public record Input( WorldCanonicalInstanceAssociation.GameSessionReadRequest gameSessionReadRequest, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java index 85c6758afd..9b4c328efd 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java @@ -65,8 +65,11 @@ public void prepareCanonicalWorldInstance( } CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector; + CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput operationInput; try { selector = CanonicalWorldInstancePreparationGrpcCodec.fromRequest(request); + operationInput = + CanonicalWorldInstancePreparationGrpcCodec.fromOriginalOperationRequest(request); } catch (IllegalArgumentException invalid) { fail( responseObserver, @@ -103,7 +106,7 @@ public void prepareCanonicalWorldInstance( // Exact retries deliberately re-enter prepare so its current source verifier and continuously // held commit authority remain mandatory through the real owner transaction. - Result prepared = preparationService.prepare(input); + Result prepared = preparationService.prepare(input, operationInput); if (prepared == null) { throw new PreparationPreconditionException( "Canonical World preparation returned no committed materialization result"); @@ -121,7 +124,8 @@ public void prepareCanonicalWorldInstance( requireLifecycleMatchesPreparation(lifecycleRequest, input, prepared, lifecycle); PrepareCanonicalWorldInstanceResponse response = - CanonicalWorldInstancePreparationGrpcCodec.toResponse(selector, lifecycle); + CanonicalWorldInstancePreparationGrpcCodec.toResponse( + selector, operationInput, lifecycle); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (SecurityException denied) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java index dc843b0542..3bb2913d10 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -109,8 +109,8 @@ public WorldCanonicalInstancePreparationRepository( /** * Runs the one owner transaction, then independently reads its committed immutable result. The - * supplied continuously held authority handle remains valid through the transaction manager's - * commit path. + * Account source-protection handle remains open through the transaction manager's commit path; + * the stored original Game Session lease is checked separately at actual World admission. */ public Result materialize( Input input, WorldCanonicalInstancePreparationService.HeldCommitAuthority authority) { @@ -121,6 +121,10 @@ public Result materialize( Objects.requireNonNull( authority.executionIdentity(), "Canonical preparation authority returned no typed World execution identity"); + if (!executionIdentity.hasOriginalAttemptEvidence()) { + throw new WorldCanonicalInstancePreparationService.PreparationDeniedException( + "Fresh World admission requires Account's exact original Game Session attempt observation"); + } String inputJson = inputJson(input); String inputDigest = digest(inputJson.getBytes(StandardCharsets.UTF_8)); executionIdentity.requireMatches(input, inputJson); @@ -169,7 +173,7 @@ public Result materialize( authority.requireHeld(); Record beginRow = dsl.fetchOne( - "SELECT world_begin_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_begin_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", inputJson, inputDigest, executionIdentity.originalPostAuthorizationTuple(), @@ -178,7 +182,14 @@ public Result materialize( executionIdentity.gameSessionOwnerAttemptId(), executionIdentity.gameSessionOwnerFence(), executionIdentity.canonicalGameInstanceId(), - intentFence); + intentFence, + executionIdentity.gameSessionOwnerMutationId(), + executionIdentity.originalAttemptReadRequestId(), + OffsetDateTime.ofInstant( + executionIdentity.originalGameSessionLeaseExpiresAt(), + java.time.ZoneOffset.UTC), + executionIdentity.originalAttemptEvidenceBytes(), + executionIdentity.originalAttemptEvidenceDigest()); Long worldExecutionFence = beginRow == null ? null : beginRow.get(0, Long.class); if (worldExecutionFence == null || worldExecutionFence <= 0L) { return null; @@ -239,8 +250,8 @@ public Result materialize( /** * Retains the full immutable operation identity in a short transaction before materialization. - * The record is not permission: every new writer still needs a fresh held verifier and must pass - * the DB-clock check after all V35 locks have been acquired. + * The record is not permission: every new writer still needs a fresh Account participation and + * must pass the DB-clock authorization and owner-lease checks after all V35 locks are acquired. */ private long persistExecutionIntent( String inputJson, @@ -255,7 +266,7 @@ private long persistExecutionIntent( authority.requireHeld(); Record intentRow = dsl.fetchOne( - "SELECT world_persist_canonical_instance_execution_intent(?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -263,7 +274,13 @@ private long persistExecutionIntent( identity.accountWorldParticipationFence(), identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence(), - identity.canonicalGameInstanceId()); + identity.canonicalGameInstanceId(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + OffsetDateTime.ofInstant( + identity.originalGameSessionLeaseExpiresAt(), java.time.ZoneOffset.UTC), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); return intentRow == null ? null : intentRow.get(0, Long.class); }); if (fence == null) { @@ -285,7 +302,7 @@ private Long claimExecutionIntent( authority.requireHeld(); Record claimRow = dsl.fetchOne( - "SELECT world_claim_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_claim_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", identity.preparationInputJson(), identity.preparationInputDigest(), identity.originalPostAuthorizationTuple(), @@ -293,7 +310,13 @@ private Long claimExecutionIntent( identity.accountWorldParticipationFence(), identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence(), - identity.canonicalGameInstanceId()); + identity.canonicalGameInstanceId(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + OffsetDateTime.ofInstant( + identity.originalGameSessionLeaseExpiresAt(), java.time.ZoneOffset.UTC), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); return claimRow == null ? null : claimRow.get(0, Long.class); }); authority.requireHeld(); @@ -312,7 +335,10 @@ public ExecutionLookup readExactExecution(WorldCanonicalInstanceExecutionIdentit "SELECT clock.database_now, e.canonical_game_instance_id, original_post_authorization_tuple, " + "original_post_authorization_tuple_sha256, account_world_participation_id, " + "account_world_participation_fence, game_session_owner_attempt_id, " - + "game_session_owner_fence, preparation_input_digest, preparation_input_json, " + + "game_session_owner_fence, game_session_owner_mutation_id, " + + "original_attempt_read_request_id, original_game_session_lease_expires_at, " + + "original_attempt_evidence_bytes, original_attempt_evidence_sha256, " + + "preparation_input_digest, preparation_input_json, " + "world_execution_fence, operation_state, world_instance_id " + "FROM (SELECT clock_timestamp() AS database_now) clock " + "LEFT JOIN world_canonical_instance_execution e ON e.target_namespace=? " @@ -358,6 +384,26 @@ public ExecutionLookup readExactExecution(WorldCanonicalInstanceExecutionIdentit throw new ConflictingPreparationException( "World execution lookup differs from the exact original full identity"); } + UUID retainedMutationId = row.get("game_session_owner_mutation_id", UUID.class); + UUID retainedObservationRequestId = row.get("original_attempt_read_request_id", UUID.class); + OffsetDateTime retainedLeaseExpiry = + row.get("original_game_session_lease_expires_at", OffsetDateTime.class); + byte[] retainedObservation = row.get("original_attempt_evidence_bytes", byte[].class); + String retainedObservationDigest = row.get("original_attempt_evidence_sha256", String.class); + if (identity.hasOriginalAttemptEvidence()) { + if (!identity.gameSessionOwnerMutationId().equals(retainedMutationId) + || !identity.originalAttemptReadRequestId().equals(retainedObservationRequestId) + || !identity + .originalGameSessionLeaseExpiresAt() + .equals(retainedLeaseExpiry == null ? null : retainedLeaseExpiry.toInstant()) + || !MessageDigest.isEqual( + identity.originalAttemptEvidenceBytes(), + retainedObservation == null ? new byte[0] : retainedObservation) + || !identity.originalAttemptEvidenceDigest().equals(retainedObservationDigest)) { + throw new ConflictingPreparationException( + "World execution lookup differs from the exact Account-returned owner observation"); + } + } long fence = required(row, "world_execution_fence", Long.class); String state = required(row, "operation_state", String.class); Long worldInstanceId = row.get("world_instance_id", Long.class); @@ -448,6 +494,28 @@ public ExecutionOperation recordDurableAbort(WorldCanonicalInstanceExecutionIden status -> { requireWritableReadCommittedTransaction(); applyDatabaseTimeouts(); + if (identity.hasOriginalAttemptEvidence()) { + return dsl.fetchOne( + "SELECT operation_state, world_execution_fence, world_instance_id " + + "FROM world_abort_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.controlPlaneRequestId(), + identity.canonicalGameInstanceId(), + identity.preparationInputJson(), + identity.preparationInputDigest(), + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + OffsetDateTime.ofInstant( + identity.originalGameSessionLeaseExpiresAt(), java.time.ZoneOffset.UTC), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); + } return dsl.fetchOne( "SELECT operation_state, world_execution_fence, world_instance_id " + "FROM world_abort_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java index f38a901ed3..d887f84254 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java @@ -10,33 +10,44 @@ /** * Unregistered, default-denied owner operation for a canonical generation-free world instance. * - *

No fresh-execution verifier is wired in this slice. An authenticated integration must verify - * the same-namespace Game Session producer and exact current Game Design release/terminal source - * before the World transaction begins. The original Account-authorized APPLIED result is immutable - * input evidence; preparation must not reauthorize the creator or reuse Draft/publication - * permission. Its held producer evidence must remain valid through commit. This class is - * deliberately not a Spring component and adds no RPC or public activation path. The separate - * explicitly supplied historical recovery verifier reads retained Account and Game Session - * evidence; it supplies no held authority for another execution. + *

No fresh-execution verifier is supplied by default. An explicitly supplied integration must + * authenticate the same-namespace Game Session peer, acquire Account's exact original + * participation, and bind its retained first owner-attempt observation before the World transaction + * begins. The original Account-authorized APPLIED result is immutable input evidence; preparation + * must not reauthorize the creator or reuse Draft/publication permission. Account's pending + * participation protects its exact source vector through terminal settlement; the unchanged Game + * Session lease is checked at actual World admission and is not treated as a continuous remote + * lock. This class is deliberately not a Spring component and adds no RPC or public activation + * path. The separate explicitly supplied historical recovery verifier reads retained Account and + * Game Session evidence; it supplies no held authority for another execution. */ public final class WorldCanonicalInstancePreparationService { private final WorldCanonicalInstancePreparationRepository repository; - private final CommitAuthorityVerifier verifier; + private final OriginalOperationCommitAuthorityVerifier originalOperationVerifier; private final OriginalOperationRecoveryVerifier recoveryVerifier; /** Constructs the production-safe default: all attempts fail closed. */ public WorldCanonicalInstancePreparationService( WorldCanonicalInstancePreparationRepository repository) { - this( - repository, - WorldCanonicalInstancePreparationService::denyByDefault, - WorldCanonicalInstancePreparationService::denyRecoveryByDefault); + this(repository, null, WorldCanonicalInstancePreparationService::denyRecoveryByDefault, true); } - /** Constructor for an explicitly supplied owner verifier, including labeled synthetic tests. */ + /** Retained legacy constructor; an untyped verifier cannot authorize a fresh execution. */ public WorldCanonicalInstancePreparationService( WorldCanonicalInstancePreparationRepository repository, CommitAuthorityVerifier verifier) { - this(repository, verifier, WorldCanonicalInstancePreparationService::denyRecoveryByDefault); + this(repository, null, WorldCanonicalInstancePreparationService::denyRecoveryByDefault, true); + Objects.requireNonNull(verifier, "verifier"); + } + + /** Constructor for an explicitly supplied verifier of the typed original owner operation. */ + public WorldCanonicalInstancePreparationService( + WorldCanonicalInstancePreparationRepository repository, + OriginalOperationCommitAuthorityVerifier verifier) { + this( + repository, + Objects.requireNonNull(verifier, "verifier"), + WorldCanonicalInstancePreparationService::denyRecoveryByDefault, + true); } /** @@ -47,8 +58,27 @@ public WorldCanonicalInstancePreparationService( WorldCanonicalInstancePreparationRepository repository, CommitAuthorityVerifier verifier, OriginalOperationRecoveryVerifier recoveryVerifier) { + this(repository, null, recoveryVerifier, true); + Objects.requireNonNull(verifier, "verifier"); + } + + /** Constructor for explicit fresh original-owner and recovery verifiers. */ + public WorldCanonicalInstancePreparationService( + WorldCanonicalInstancePreparationRepository repository, + OriginalOperationCommitAuthorityVerifier verifier, + OriginalOperationRecoveryVerifier recoveryVerifier) { + this(repository, Objects.requireNonNull(verifier, "verifier"), recoveryVerifier, true); + } + + private WorldCanonicalInstancePreparationService( + WorldCanonicalInstancePreparationRepository repository, + OriginalOperationCommitAuthorityVerifier originalOperationVerifier, + OriginalOperationRecoveryVerifier recoveryVerifier, + boolean ownerTypedConstructor) { this.repository = Objects.requireNonNull(repository, "repository"); - this.verifier = Objects.requireNonNull(verifier, "verifier"); + if (!ownerTypedConstructor) + throw new IllegalArgumentException("Constructor marker is required"); + this.originalOperationVerifier = originalOperationVerifier; this.recoveryVerifier = Objects.requireNonNull(recoveryVerifier, "recoveryVerifier"); } @@ -63,14 +93,58 @@ public Result prepare(Input input) { throw new IllegalStateException( "Canonical World preparation must verify outside an ambient transaction"); } + throw new PreparationDeniedException( + "Fresh canonical World preparation requires the exact original Game Session owner operation"); + } + + /** + * Decodes the closed transport input before Account acquisition and delegates to the owner path. + */ + public Result prepare( + Input input, + net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationGrpcCodec + .OriginalOperationInput + wireOperationInput) { + Objects.requireNonNull(wireOperationInput, "wireOperationInput"); + return prepare( + input, + new WorldCanonicalInstancePreparation.OriginalStartSessionOperationInput( + wireOperationInput.originalPostAuthorizationTuple(), + wireOperationInput.gameSessionOwnerMutationId(), + wireOperationInput.gameSessionOwnerAttemptId(), + wireOperationInput.gameSessionOwnerFence())); + } + + /** + * Acquires Account's original participation outside World SQL, then admits only the exact + * owner-observation-bound World execution identity. + */ + public Result prepare( + Input input, + WorldCanonicalInstancePreparation.OriginalStartSessionOperationInput operationInput) { + Objects.requireNonNull(input, "input"); + Objects.requireNonNull(operationInput, "operationInput"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical World preparation must verify outside an ambient transaction"); + } WorldCanonicalInstancePreparation.requireGenerationFree(input.topologyPlan()); + if (originalOperationVerifier == null) { + throw new PreparationDeniedException( + "Canonical World preparation has no authenticated Account participation verifier"); + } + operationInput.requireMatches(input, input.gameSessionReadEvidence().targetNamespace()); HeldCommitAuthority held = Objects.requireNonNull( - verifier.verifyAndHold(input), + originalOperationVerifier.verifyAndHold(input, operationInput), "Canonical preparation verifier returned no held commit authority"); try (held) { held.requireHeld(); + held.executionIdentity() + .requireMatches( + input, operationInput, WorldCanonicalInstancePreparationRepository.inputJson(input)); return repository.materialize(input, held); } } @@ -130,22 +204,25 @@ public Optional recoverExactTerminal( : WorldStartSessionExecutionTerminal.Outcome.ABORTED)); } - private static HeldCommitAuthority denyByDefault(Input input) { - throw new PreparationDeniedException( - "Canonical World preparation has no authenticated source/release terminal verifier"); - } - private static void denyRecoveryByDefault(WorldCanonicalInstanceExecutionIdentity identity) { throw new PreparationDeniedException( "Canonical World execution recovery has no authenticated original-operation verifier"); } - /** Performs authenticated producer checks before returning a continuously held local fence. */ + /** Legacy untyped verifier contract; it is not used to admit fresh World materialization. */ @FunctionalInterface public interface CommitAuthorityVerifier { HeldCommitAuthority verifyAndHold(Input input); } + /** Authenticates the typed original tuple and owner attempt before Account acquisition. */ + @FunctionalInterface + public interface OriginalOperationCommitAuthorityVerifier { + HeldCommitAuthority verifyAndHold( + Input input, + WorldCanonicalInstancePreparation.OriginalStartSessionOperationInput operationInput); + } + /** * Authenticates the exact configured same-namespace Game Session producer and verifies the * retained original Account participation, actual Game Session attempt/fence, and immutable @@ -160,18 +237,20 @@ public interface OriginalOperationRecoveryVerifier { } /** - * A verifier-owned, continuously held producer-evidence handle. It stays open throughout the - * World transaction and its commit; implementations must fail closed from {@link #requireHeld()} - * if the source participation/fence they verified is no longer continuously held. + * A verifier-owned handle for the exact Account pending participation and owner observation. It + * stays open through the World transaction and its commit. The Account participation is the + * durable source-protection evidence; the Game Session observation is only an immutable sample, + * and its unchanged lease is independently checked by World SQL at actual admission. * Remote/current-state checks happen before the World transaction; {@code requireHeld()} is a - * local fence/effective-state assertion and must never perform RPC while World holds database - * locks. It must not reapply the original ingress-authority expiry after the V35 SQL admission - * check: an uninterrupted admitted transaction may finish after that bound while the source - * participation remains protected through exact World COMMITTED or durable ABORTED settlement. - * {@link #close()} may release only local resources; it must never release durable Account - * participation merely because this call returned, timed out, or has an uncertain outcome. That - * participation remains protected until an authenticated exact World COMMITTED result or fenced - * durable ABORTED settlement is known. It is not a new Account creator permission. + * local handle assertion and must never perform RPC while World holds database locks. It must not + * reapply the original authorization or Game Session lease expiry after the V35 SQL admission + * check: an uninterrupted admitted transaction may finish after those ingress bounds while the + * Account participation remains protected through exact World COMMITTED or durable ABORTED + * settlement. {@link #close()} may release only local resources; it must never release durable + * Account participation merely because this call returned, timed out, or has an uncertain + * outcome. That participation remains protected until an authenticated exact World COMMITTED + * result or fenced durable ABORTED settlement is known. It is not a new Account creator + * permission. */ public interface HeldCommitAuthority extends AutoCloseable { void requireHeld(); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionAccountParticipationVerifier.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionAccountParticipationVerifier.java new file mode 100644 index 0000000000..253591a1d6 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionAccountParticipationVerifier.java @@ -0,0 +1,187 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.ByteString; +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 net.firedevops.firemud.account.v1.AcquireStartSessionWorldParticipationRequest; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationAcquisitionClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.OriginalStartSessionOperationInput; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService.HeldCommitAuthority; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService.OriginalOperationCommitAuthorityVerifier; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Acquires Account's exact original participation before any World execution transaction. */ +public final class WorldStartSessionAccountParticipationVerifier + implements OriginalOperationCommitAuthorityVerifier { + private final String trustedNamespace; + private final AccountStartSessionWorldParticipationAcquisitionClient accountClient; + + public WorldStartSessionAccountParticipationVerifier( + String trustedNamespace, + AccountStartSessionWorldParticipationAcquisitionClient accountClient) { + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException( + "World workload namespace must be one canonical DNS label"); + } + this.trustedNamespace = trustedNamespace; + this.accountClient = Objects.requireNonNull(accountClient, "accountClient"); + } + + @Override + public HeldCommitAuthority verifyAndHold( + Input input, OriginalStartSessionOperationInput operationInput) { + Objects.requireNonNull(input, "input"); + Objects.requireNonNull(operationInput, "operationInput"); + requireAuthenticatedGameSessionPeer(); + requireNoAmbientTransaction(); + operationInput.requireMatches(input, trustedNamespace); + + String exactPreparationJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + byte[] exactPreparationBytes = exactPreparationJson.getBytes(StandardCharsets.UTF_8); + if (exactPreparationBytes.length > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { + throw new WorldCanonicalInstancePreparationService.PreparationDeniedException( + "Canonical World preparation input exceeds the Account acquisition bound"); + } + String exactPreparationDigest = digestPrefixed(exactPreparationBytes); + UUID acquisitionRequestId = independentRequestId(operationInput, input); + AcquireStartSessionWorldParticipationRequest request = + AcquireStartSessionWorldParticipationRequest.newBuilder() + .setSchemaVersion(1) + .setAcquisitionRequestId(acquisitionRequestId.toString()) + .setTargetNamespace(trustedNamespace) + .setOriginalPostAuthorizationTuple( + ByteString.copyFrom(operationInput.originalPostAuthorizationTuple())) + .setGameSessionOwnerMutationId(operationInput.gameSessionOwnerMutationId().toString()) + .setGameSessionOwnerAttemptId(operationInput.gameSessionOwnerAttemptId().toString()) + .setGameSessionOwnerFence(operationInput.gameSessionOwnerFence()) + .setCanonicalGameInstanceId(input.canonicalGameInstanceId().toString()) + .setPreparationInputJson(exactPreparationJson) + .setPreparationInputDigest(exactPreparationDigest) + .build(); + + // The Account RPC is intentionally complete before World opens any intent/claim/owner SQL. + var response = accountClient.acquire(request); + if (response == null || !response.hasOriginalAttemptEvidence()) { + throw new WorldCanonicalInstancePreparationService.PreparationDeniedException( + "Account returned no retained original Game Session attempt observation"); + } + var observationMessage = response.getOriginalAttemptEvidence(); + var observationRequest = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest( + observationMessage.getRequest()); + var observation = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + observationRequest, observationMessage); + var identity = + new WorldCanonicalInstanceExecutionIdentity( + operationInput.originalPostAuthorizationTuple(), + canonicalUuid(response.getAccountWorldParticipationId()), + response.getAccountWorldParticipationFence(), + operationInput.gameSessionOwnerMutationId(), + operationInput.gameSessionOwnerAttemptId(), + operationInput.gameSessionOwnerFence(), + observation, + input.canonicalGameInstanceId(), + exactPreparationJson, + observationMessage.toByteArray()); + identity.requireMatches(input, operationInput, exactPreparationJson); + return new AcquiredHeldAuthority(identity); + } + + private void requireAuthenticatedGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expected = "spiffe://firemud/ns/" + trustedNamespace + "/sa/game-session-service"; + if (peer == null + || !peer.isService("game-session-service") + || !peer.isInNamespace(trustedNamespace) + || !expected.equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new SecurityException( + "Only the exact same-namespace Game Session workload may acquire Account participation"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account World participation acquisition requires no ambient World transaction"); + } + } + + private static UUID independentRequestId( + OriginalStartSessionOperationInput operationInput, Input input) { + UUID candidate; + do { + candidate = UUID.randomUUID(); + } while (candidate.equals(operationInput.gameSessionOwnerMutationId()) + || candidate.equals(operationInput.gameSessionOwnerAttemptId()) + || candidate.equals(input.canonicalGameInstanceId()) + || candidate.equals(operationInput.decodedTuple().reservationOwnerId()) + || candidate.equals( + operationInput.decodedTuple().preAuthorizationTuple().actor().accountId()) + || candidate.equals( + operationInput.decodedTuple().preAuthorizationTuple().action().scope().tenantId()) + || candidate.toString().equals(operationInput.decodedTuple().controlPlaneRequestId())); + return candidate; + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, "Account participation ID")); + if (parsed.equals(new UUID(0L, 0L)) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Account participation ID is not canonical"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new WorldCanonicalInstancePreparationService.PreparationDeniedException( + "Account returned an invalid World participation identity"); + } + } + + private static String digestPrefixed(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + /** Local handle only; close never settles/releases durable Account protection. */ + private static final class AcquiredHeldAuthority implements HeldCommitAuthority { + private final WorldCanonicalInstanceExecutionIdentity identity; + private boolean closed; + + private AcquiredHeldAuthority(WorldCanonicalInstanceExecutionIdentity identity) { + this.identity = Objects.requireNonNull(identity, "identity"); + } + + @Override + public void requireHeld() { + if (closed || !identity.hasOriginalAttemptEvidence()) { + throw new WorldCanonicalInstancePreparationService.PreparationDeniedException( + "Exact Account participation handle is no longer available locally"); + } + } + + @Override + public WorldCanonicalInstanceExecutionIdentity executionIdentity() { + return identity; + } + + @Override + public void close() { + closed = true; + } + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V63__world_original_start_session_attempt_admission.sql b/services/world-management-service/src/main/resources/db/migration/V63__world_original_start_session_attempt_admission.sql new file mode 100644 index 0000000000..47deee4306 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V63__world_original_start_session_attempt_admission.sql @@ -0,0 +1,583 @@ +-- Fresh World execution intents retain Account's exact first original-attempt observation. +-- Existing V62 rows remain untouched and nullable; missing evidence never becomes migration data. +ALTER TABLE world_canonical_instance_execution + ADD COLUMN game_session_owner_mutation_id UUID, + ADD COLUMN original_attempt_read_request_id UUID, + ADD COLUMN original_game_session_lease_expires_at TIMESTAMPTZ, + ADD COLUMN original_attempt_evidence_bytes BYTEA, + ADD COLUMN original_attempt_evidence_sha256 VARCHAR(71); + +ALTER TABLE world_canonical_instance_execution + ADD CONSTRAINT ck_world_execution_original_attempt_witness + CHECK ( + (game_session_owner_mutation_id IS NULL + AND original_attempt_read_request_id IS NULL + AND original_game_session_lease_expires_at IS NULL + AND original_attempt_evidence_bytes IS NULL + AND original_attempt_evidence_sha256 IS NULL) + OR (game_session_owner_mutation_id IS NOT NULL + AND game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND original_attempt_read_request_id IS NOT NULL + AND original_attempt_read_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND original_game_session_lease_expires_at IS NOT NULL + AND original_attempt_evidence_bytes IS NOT NULL + AND octet_length(original_attempt_evidence_bytes) BETWEEN 1 AND 525824 + AND original_attempt_evidence_sha256 IS NOT NULL + AND original_attempt_evidence_sha256 ~ '^sha256:[0-9a-f]{64}$' + AND original_attempt_evidence_sha256 = 'sha256:' || encode(sha256(original_attempt_evidence_bytes), 'hex')) + ); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_execution FROM PUBLIC; + +-- Fresh operations use this function so the Account-returned exact observation is born with the +-- World-local identity and execution fence. A V62 row with absent witness fields is never upgraded. +CREATE FUNCTION world_persist_canonical_instance_execution_intent_with_original_attempt( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID, + p_game_session_mutation_id UUID, p_attempt_read_request_id UUID, + p_original_game_session_lease_expires_at TIMESTAMPTZ, + p_original_attempt_evidence_bytes BYTEA, p_original_attempt_evidence_sha256 TEXT +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + input JSONB; + tuple_value JSONB; + projection_expiry TIMESTAMPTZ; + v_target_namespace TEXT; + v_canonical_tenant_id UUID; + v_request_id TEXT; + v_world_slug TEXT; + v_game_template_id BIGINT; + prior "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + IF p_game_session_mutation_id IS NULL + OR p_game_session_mutation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_attempt_read_request_id IS NULL + OR p_attempt_read_request_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_original_game_session_lease_expires_at IS NULL + OR p_original_attempt_evidence_bytes IS NULL + OR octet_length(p_original_attempt_evidence_bytes) NOT BETWEEN 1 AND 525824 + OR p_original_attempt_evidence_sha256 IS DISTINCT FROM + 'sha256:' || encode(sha256(p_original_attempt_evidence_bytes), 'hex') THEN + RAISE EXCEPTION 'Exact Account original Game Session attempt observation is required' + USING ERRCODE = '23514'; + END IF; + + input := p_input_json::JSONB; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + v_target_namespace := input->'identity'->>'targetNamespace'; + v_canonical_tenant_id := (input->'identity'->>'canonicalTenantId')::UUID; + v_request_id := input->'identity'->>'controlPlaneRequestId'; + v_world_slug := input->'identity'->>'worldSlug'; + v_game_template_id := (((input->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT; + projection_expiry := (tuple_value->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt')::TIMESTAMPTZ; + + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + v_target_namespace, v_canonical_tenant_id, v_request_id, p_canonical_game_instance_id); + -- Preliminary checks bound the retained intent. Actual admission repeats both expiries only + -- after all V35 owner locks, so a lock wait cannot admit a stale lease. + IF projection_expiry <= clock_timestamp() + OR p_original_game_session_lease_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession authorization or Game Session lease expired before World intent retention' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO prior FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = v_target_namespace + AND e.canonical_tenant_id = v_canonical_tenant_id + AND e.control_plane_request_id = v_request_id + FOR UPDATE; + IF FOUND THEN + IF prior.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR prior.canonical_world_slug IS DISTINCT FROM v_world_slug + OR prior.game_template_id IS DISTINCT FROM v_game_template_id + OR prior.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR prior.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR prior.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR prior.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR prior.game_session_owner_fence IS DISTINCT FROM p_game_session_fence + OR prior.game_session_owner_mutation_id IS DISTINCT FROM p_game_session_mutation_id + OR prior.original_attempt_read_request_id IS DISTINCT FROM p_attempt_read_request_id + OR prior.original_game_session_lease_expires_at IS DISTINCT FROM p_original_game_session_lease_expires_at + OR prior.original_attempt_evidence_bytes IS DISTINCT FROM p_original_attempt_evidence_bytes + OR prior.original_attempt_evidence_sha256 IS DISTINCT FROM p_original_attempt_evidence_sha256 + OR prior.preparation_input_digest IS DISTINCT FROM p_input_digest + OR prior.preparation_input_json IS DISTINCT FROM p_input_json THEN + RAISE EXCEPTION 'World execution request is already bound to a different or incomplete original owner observation' + USING ERRCODE = '23505'; + END IF; + RETURN 0; + END IF; + + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = p_canonical_game_instance_id + OR (p.target_namespace = v_target_namespace + AND p.canonical_tenant_id = v_canonical_tenant_id + AND p.control_plane_request_id = v_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = p_canonical_game_instance_id + OR (a.canonical_target_namespace = v_target_namespace + AND a.canonical_tenant_id = v_canonical_tenant_id + AND a.control_plane_request_id = v_request_id)) THEN + RAISE EXCEPTION 'Historical World materialization has no exact execution identity' + USING ERRCODE = '23514'; + END IF; + + INSERT INTO "${serviceSchema}".world_canonical_instance_execution ( + target_namespace, canonical_tenant_id, control_plane_request_id, + canonical_game_instance_id, canonical_world_slug, game_template_id, + original_post_authorization_tuple, original_post_authorization_tuple_sha256, + account_world_participation_id, account_world_participation_fence, + game_session_owner_attempt_id, game_session_owner_fence, + game_session_owner_mutation_id, original_attempt_read_request_id, + original_game_session_lease_expires_at, original_attempt_evidence_bytes, + original_attempt_evidence_sha256, + preparation_input_digest, preparation_input_json, world_execution_fence, + operation_state) + VALUES ( + v_target_namespace, v_canonical_tenant_id, v_request_id, + p_canonical_game_instance_id, v_world_slug, v_game_template_id, + p_original_tuple, encode(sha256(p_original_tuple), 'hex'), + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, + p_game_session_mutation_id, p_attempt_read_request_id, + p_original_game_session_lease_expires_at, p_original_attempt_evidence_bytes, + p_original_attempt_evidence_sha256, + p_input_digest, p_input_json, + nextval('"${serviceSchema}".world_canonical_instance_execution_fence_seq'), + 'PENDING') + RETURNING world_execution_fence INTO prior.world_execution_fence; + RETURN prior.world_execution_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_persist_canonical_instance_execution_intent_with_original_attempt( + TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID, UUID, UUID, TIMESTAMPTZ, BYTEA, TEXT) FROM PUBLIC; + +-- Fresh claims and execution admission compare the full Account observation, not just the older +-- V62 tuple/participation/attempt projection. +CREATE FUNCTION world_claim_canonical_instance_execution_with_original_attempt( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID, + p_game_session_mutation_id UUID, p_attempt_read_request_id UUID, + p_original_game_session_lease_expires_at TIMESTAMPTZ, + p_original_attempt_evidence_bytes BYTEA, p_original_attempt_evidence_sha256 TEXT +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + result_fence BIGINT; + identity JSONB := p_input_json::JSONB->'identity'; + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + result_fence := "${serviceSchema}".world_claim_canonical_instance_execution( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = identity->>'targetNamespace' + AND e.canonical_tenant_id = (identity->>'canonicalTenantId')::UUID + AND e.control_plane_request_id = identity->>'controlPlaneRequestId' + FOR UPDATE; + IF NOT FOUND + OR operation.game_session_owner_mutation_id IS DISTINCT FROM p_game_session_mutation_id + OR operation.original_attempt_read_request_id IS DISTINCT FROM p_attempt_read_request_id + OR operation.original_game_session_lease_expires_at IS DISTINCT FROM p_original_game_session_lease_expires_at + OR operation.original_attempt_evidence_bytes IS DISTINCT FROM p_original_attempt_evidence_bytes + OR operation.original_attempt_evidence_sha256 IS DISTINCT FROM p_original_attempt_evidence_sha256 THEN + RAISE EXCEPTION 'World execution claim differs from the exact Account owner observation' + USING ERRCODE = '23514'; + END IF; + RETURN result_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_claim_canonical_instance_execution_with_original_attempt( + TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID, UUID, UUID, TIMESTAMPTZ, BYTEA, TEXT) FROM PUBLIC; + +CREATE FUNCTION world_begin_canonical_instance_execution_with_original_attempt( + p_input_json TEXT, p_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_canonical_game_instance_id UUID, p_world_execution_fence BIGINT, + p_game_session_mutation_id UUID, p_attempt_read_request_id UUID, + p_original_game_session_lease_expires_at TIMESTAMPTZ, + p_original_attempt_evidence_bytes BYTEA, p_original_attempt_evidence_sha256 TEXT +) RETURNS BIGINT +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + result_fence BIGINT; + identity JSONB := p_input_json::JSONB->'identity'; + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; +BEGIN + result_fence := "${serviceSchema}".world_begin_canonical_instance_execution( + p_input_json, p_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, + p_canonical_game_instance_id, p_world_execution_fence); + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = identity->>'targetNamespace' + AND e.canonical_tenant_id = (identity->>'canonicalTenantId')::UUID + AND e.control_plane_request_id = identity->>'controlPlaneRequestId' + FOR UPDATE; + IF NOT FOUND + OR operation.game_session_owner_mutation_id IS DISTINCT FROM p_game_session_mutation_id + OR operation.original_attempt_read_request_id IS DISTINCT FROM p_attempt_read_request_id + OR operation.original_game_session_lease_expires_at IS DISTINCT FROM p_original_game_session_lease_expires_at + OR operation.original_attempt_evidence_bytes IS DISTINCT FROM p_original_attempt_evidence_bytes + OR operation.original_attempt_evidence_sha256 IS DISTINCT FROM p_original_attempt_evidence_sha256 THEN + RAISE EXCEPTION 'World execution admission differs from the exact Account owner observation' + USING ERRCODE = '23514'; + END IF; + RETURN result_fence; +END; +$$; +REVOKE ALL ON FUNCTION world_begin_canonical_instance_execution_with_original_attempt( + TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, UUID, BIGINT, UUID, UUID, TIMESTAMPTZ, BYTEA, TEXT) FROM PUBLIC; + +-- Exact durable abort uses the same request/target serialization and binds the Account-returned +-- owner observation when it must create the terminal row. It never settles/releases Account itself. +CREATE FUNCTION world_abort_canonical_instance_execution_with_original_attempt( + p_target_namespace TEXT, p_canonical_tenant_id UUID, p_control_plane_request_id TEXT, + p_canonical_game_instance_id UUID, p_preparation_input_json TEXT, + p_preparation_input_digest TEXT, p_original_tuple BYTEA, + p_account_participation_id UUID, p_account_participation_fence BIGINT, + p_game_session_attempt_id UUID, p_game_session_fence BIGINT, + p_game_session_mutation_id UUID, p_attempt_read_request_id UUID, + p_original_game_session_lease_expires_at TIMESTAMPTZ, + p_original_attempt_evidence_bytes BYTEA, p_original_attempt_evidence_sha256 TEXT +) RETURNS TABLE(operation_state TEXT, world_execution_fence BIGINT, world_instance_id BIGINT) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; + tuple_value JSONB; +BEGIN + PERFORM "${serviceSchema}".world_validate_canonical_instance_execution_input( + p_preparation_input_json, p_preparation_input_digest, p_original_tuple, + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, p_canonical_game_instance_id); + IF p_game_session_mutation_id IS NULL + OR p_game_session_mutation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_attempt_read_request_id IS NULL + OR p_attempt_read_request_id = '00000000-0000-0000-0000-000000000000'::UUID + OR p_original_game_session_lease_expires_at IS NULL + OR p_original_attempt_evidence_bytes IS NULL + OR octet_length(p_original_attempt_evidence_bytes) NOT BETWEEN 1 AND 525824 + OR p_original_attempt_evidence_sha256 IS DISTINCT FROM + 'sha256:' || encode(sha256(p_original_attempt_evidence_bytes), 'hex') THEN + RAISE EXCEPTION 'Exact Account original Game Session attempt observation is required for World abort' + USING ERRCODE = '23514'; + END IF; + tuple_value := convert_from(p_original_tuple, 'UTF8')::JSONB; + IF tuple_value->>'controlPlaneRequestId' IS DISTINCT FROM p_control_plane_request_id + OR tuple_value->'scope'->>'targetNamespace' IS DISTINCT FROM p_target_namespace + OR tuple_value->'scope'->>'tenantId' IS DISTINCT FROM p_canonical_tenant_id::TEXT THEN + RAISE EXCEPTION 'World abort identity differs from the original scoped StartSession tuple' + USING ERRCODE = '23514'; + END IF; + PERFORM "${serviceSchema}".world_lock_canonical_instance_execution( + p_target_namespace, p_canonical_tenant_id, p_control_plane_request_id, + p_canonical_game_instance_id); + PERFORM set_config('world.canonical_abort_namespace', p_target_namespace, TRUE); + PERFORM set_config('world.canonical_abort_tenant', p_canonical_tenant_id::TEXT, TRUE); + PERFORM set_config('world.canonical_abort_request', p_control_plane_request_id, TRUE); + PERFORM set_config('world.canonical_abort_target', p_canonical_game_instance_id::TEXT, TRUE); + PERFORM set_config('world.canonical_abort_mutation', p_game_session_mutation_id::TEXT, TRUE); + PERFORM set_config('world.canonical_abort_attempt_read', p_attempt_read_request_id::TEXT, TRUE); + PERFORM set_config( + 'world.canonical_abort_lease_expiry', + p_original_game_session_lease_expires_at::TEXT, + TRUE); + PERFORM set_config( + 'world.canonical_abort_observation_digest', + p_original_attempt_evidence_sha256, + TRUE); + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = p_target_namespace + AND e.canonical_tenant_id = p_canonical_tenant_id + AND e.control_plane_request_id = p_control_plane_request_id + FOR UPDATE; + IF NOT FOUND THEN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.canonical_game_instance_id = p_canonical_game_instance_id) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = p_canonical_game_instance_id + OR (p.target_namespace = p_target_namespace + AND p.canonical_tenant_id = p_canonical_tenant_id + AND p.control_plane_request_id = p_control_plane_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = p_canonical_game_instance_id + OR (a.canonical_target_namespace = p_target_namespace + AND a.canonical_tenant_id = p_canonical_tenant_id + AND a.control_plane_request_id = p_control_plane_request_id)) THEN + RAISE EXCEPTION 'Historical or conflicting World rows make missing-operation abort unresolved' + USING ERRCODE = '23514'; + END IF; + INSERT INTO "${serviceSchema}".world_canonical_instance_execution ( + target_namespace, canonical_tenant_id, control_plane_request_id, + canonical_game_instance_id, canonical_world_slug, game_template_id, + original_post_authorization_tuple, original_post_authorization_tuple_sha256, + account_world_participation_id, account_world_participation_fence, + game_session_owner_attempt_id, game_session_owner_fence, + game_session_owner_mutation_id, original_attempt_read_request_id, + original_game_session_lease_expires_at, original_attempt_evidence_bytes, + original_attempt_evidence_sha256, + preparation_input_digest, preparation_input_json, world_execution_fence, + operation_state, terminal_at) + VALUES ( + p_target_namespace, p_canonical_tenant_id, p_control_plane_request_id, + p_canonical_game_instance_id, + (p_preparation_input_json::JSONB->'identity'->>'worldSlug'), + (((p_preparation_input_json::JSONB->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT, + p_original_tuple, encode(sha256(p_original_tuple), 'hex'), + p_account_participation_id, p_account_participation_fence, + p_game_session_attempt_id, p_game_session_fence, + p_game_session_mutation_id, p_attempt_read_request_id, + p_original_game_session_lease_expires_at, p_original_attempt_evidence_bytes, + p_original_attempt_evidence_sha256, + p_preparation_input_digest, p_preparation_input_json, + nextval('"${serviceSchema}".world_canonical_instance_execution_fence_seq'), + 'ABORTED', clock_timestamp()) + RETURNING * INTO operation; + END IF; + IF operation.canonical_game_instance_id IS DISTINCT FROM p_canonical_game_instance_id + OR operation.canonical_world_slug IS DISTINCT FROM p_preparation_input_json::JSONB->'identity'->>'worldSlug' + OR operation.game_template_id IS DISTINCT FROM (((p_preparation_input_json::JSONB->'gameSessionReadEvidence'->>'descriptorJson')::JSONB)->>'gameTemplateId')::BIGINT + OR operation.preparation_input_digest IS DISTINCT FROM p_preparation_input_digest + OR operation.preparation_input_json IS DISTINCT FROM p_preparation_input_json + OR operation.original_post_authorization_tuple IS DISTINCT FROM p_original_tuple + OR operation.account_world_participation_id IS DISTINCT FROM p_account_participation_id + OR operation.account_world_participation_fence IS DISTINCT FROM p_account_participation_fence + OR operation.game_session_owner_attempt_id IS DISTINCT FROM p_game_session_attempt_id + OR operation.game_session_owner_fence IS DISTINCT FROM p_game_session_fence + OR operation.game_session_owner_mutation_id IS DISTINCT FROM p_game_session_mutation_id + OR operation.original_attempt_read_request_id IS DISTINCT FROM p_attempt_read_request_id + OR operation.original_game_session_lease_expires_at IS DISTINCT FROM p_original_game_session_lease_expires_at + OR operation.original_attempt_evidence_bytes IS DISTINCT FROM p_original_attempt_evidence_bytes + OR operation.original_attempt_evidence_sha256 IS DISTINCT FROM p_original_attempt_evidence_sha256 THEN + RAISE EXCEPTION 'World abort differs from the exact original full owner-observation identity' + USING ERRCODE = '23514'; + END IF; + IF operation.operation_state = 'PENDING' THEN + IF EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_preparation p + WHERE p.canonical_game_instance_id = operation.canonical_game_instance_id + OR (p.target_namespace = operation.target_namespace + AND p.canonical_tenant_id = operation.canonical_tenant_id + AND p.control_plane_request_id = operation.control_plane_request_id)) + OR EXISTS (SELECT 1 FROM "${serviceSchema}".world_canonical_instance_association a + WHERE a.canonical_game_instance_id = operation.canonical_game_instance_id + OR (a.canonical_target_namespace = operation.target_namespace + AND a.canonical_tenant_id = operation.canonical_tenant_id + AND a.control_plane_request_id = operation.control_plane_request_id)) THEN + RAISE EXCEPTION 'World has unbound materialization rows; operation remains unresolved' + USING ERRCODE = '23514'; + END IF; + UPDATE "${serviceSchema}".world_canonical_instance_execution e + SET operation_state = 'ABORTED', terminal_at = clock_timestamp() + WHERE e.target_namespace = operation.target_namespace + AND e.canonical_tenant_id = operation.canonical_tenant_id + AND e.control_plane_request_id = operation.control_plane_request_id; + operation.operation_state := 'ABORTED'; + ELSIF operation.operation_state NOT IN ('COMMITTED', 'ABORTED') THEN + RAISE EXCEPTION 'World execution is not in a durable terminal state' + USING ERRCODE = '23514'; + END IF; + operation_state := operation.operation_state; + world_execution_fence := operation.world_execution_fence; + world_instance_id := operation.world_instance_id; + RETURN NEXT; +END; +$$; +REVOKE ALL ON FUNCTION world_abort_canonical_instance_execution_with_original_attempt( + TEXT, UUID, TEXT, UUID, TEXT, TEXT, BYTEA, UUID, BIGINT, UUID, BIGINT, + UUID, UUID, TIMESTAMPTZ, BYTEA, TEXT) FROM PUBLIC; + +-- V35 calls this hook only after its publication, target and request locks. The original Account +-- authorization and unchanged Game Session lease must both still be valid at that local admission. +CREATE OR REPLACE FUNCTION world_require_active_canonical_instance_execution( + p_input_json TEXT, p_input_digest TEXT +) RETURNS VOID +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + operation "${serviceSchema}".world_canonical_instance_execution%ROWTYPE; + original_tuple JSONB; + original_expiry TIMESTAMPTZ; +BEGIN + SELECT * INTO operation FROM "${serviceSchema}".world_canonical_instance_execution e + WHERE e.target_namespace = current_setting('world.canonical_execution_namespace', TRUE) + AND e.canonical_tenant_id::TEXT = current_setting('world.canonical_execution_tenant', TRUE) + AND e.control_plane_request_id = current_setting('world.canonical_execution_request', TRUE) + AND e.canonical_game_instance_id::TEXT = current_setting('world.canonical_execution_target', TRUE) + AND e.world_execution_fence::TEXT = current_setting('world.canonical_execution_fence', TRUE) + AND e.preparation_input_digest = p_input_digest + AND e.preparation_input_json = p_input_json + AND e.operation_state = 'EXECUTING' + AND e.active_transaction_id = txid_current(); + IF NOT FOUND + OR operation.game_session_owner_mutation_id IS NULL + OR operation.original_attempt_read_request_id IS NULL + OR operation.original_game_session_lease_expires_at IS NULL + OR operation.original_attempt_evidence_bytes IS NULL + OR operation.original_attempt_evidence_sha256 IS DISTINCT FROM + 'sha256:' || encode(sha256(operation.original_attempt_evidence_bytes), 'hex') THEN + RAISE EXCEPTION 'V35 requires the exact current World and Account owner-observation identity' + USING ERRCODE = '23514'; + END IF; + original_tuple := convert_from(operation.original_post_authorization_tuple, 'UTF8')::JSONB; + original_expiry := (original_tuple->'authorityEvidenceBundle'->'accountProjectionEvidence'->>'expiresAt')::TIMESTAMPTZ; + IF original_expiry <= clock_timestamp() + OR operation.original_game_session_lease_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession authorization or Game Session lease expired before World execution admission' + USING ERRCODE = '23514'; + END IF; +END; +$$; +REVOKE ALL ON FUNCTION world_require_active_canonical_instance_execution(TEXT, TEXT) FROM PUBLIC; + +-- V62's transition guard already serializes each state with its World fence. Replace only the +-- owner-private guard body to make the returned Account witness immutable and require it for every +-- new PENDING intent/claim/admission. Existing rows keep their original null witness values. +CREATE OR REPLACE FUNCTION world_enforce_canonical_instance_execution_transition() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + IF TG_OP = 'UPDATE' THEN + IF NEW.target_namespace IS DISTINCT FROM OLD.target_namespace + OR NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.control_plane_request_id IS DISTINCT FROM OLD.control_plane_request_id + OR NEW.canonical_game_instance_id IS DISTINCT FROM OLD.canonical_game_instance_id + OR NEW.canonical_world_slug IS DISTINCT FROM OLD.canonical_world_slug + OR NEW.game_template_id IS DISTINCT FROM OLD.game_template_id + OR NEW.original_post_authorization_tuple IS DISTINCT FROM OLD.original_post_authorization_tuple + OR NEW.original_post_authorization_tuple_sha256 IS DISTINCT FROM OLD.original_post_authorization_tuple_sha256 + OR NEW.account_world_participation_id IS DISTINCT FROM OLD.account_world_participation_id + OR NEW.account_world_participation_fence IS DISTINCT FROM OLD.account_world_participation_fence + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM OLD.game_session_owner_attempt_id + OR NEW.game_session_owner_fence IS DISTINCT FROM OLD.game_session_owner_fence + OR NEW.game_session_owner_mutation_id IS DISTINCT FROM OLD.game_session_owner_mutation_id + OR NEW.original_attempt_read_request_id IS DISTINCT FROM OLD.original_attempt_read_request_id + OR NEW.original_game_session_lease_expires_at IS DISTINCT FROM OLD.original_game_session_lease_expires_at + OR NEW.original_attempt_evidence_bytes IS DISTINCT FROM OLD.original_attempt_evidence_bytes + OR NEW.original_attempt_evidence_sha256 IS DISTINCT FROM OLD.original_attempt_evidence_sha256 + OR NEW.preparation_input_digest IS DISTINCT FROM OLD.preparation_input_digest + OR NEW.preparation_input_json IS DISTINCT FROM OLD.preparation_input_json + OR NEW.world_execution_fence IS DISTINCT FROM OLD.world_execution_fence + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION 'World execution identity and Account owner witness are immutable' + USING ERRCODE = '23514'; + END IF; + IF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'PENDING' THEN + IF OLD.execution_claimed OR NOT NEW.execution_claimed + OR OLD.active_transaction_id IS DISTINCT FROM NEW.active_transaction_id + OR OLD.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR OLD.terminal_at IS DISTINCT FROM NEW.terminal_at + OR NEW.game_session_owner_mutation_id IS NULL + OR NEW.original_attempt_read_request_id IS NULL + OR NEW.original_game_session_lease_expires_at IS NULL + OR NEW.original_attempt_evidence_bytes IS NULL + OR current_setting('world.canonical_claim_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_claim_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_claim_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_claim_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_claim_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT THEN + RAISE EXCEPTION 'World execution intent may be claimed only once by its exact complete owner observation and serialization fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'EXECUTING' THEN + IF NOT OLD.execution_claimed OR NOT NEW.execution_claimed + OR NEW.active_transaction_id IS DISTINCT FROM txid_current() + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NOT NULL + OR NEW.game_session_owner_mutation_id IS NULL + OR NEW.original_attempt_read_request_id IS NULL + OR NEW.original_game_session_lease_expires_at IS NULL + OR NEW.original_attempt_evidence_bytes IS NULL + OR current_setting('world.canonical_execution_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_execution_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_execution_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_execution_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_execution_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT + OR current_setting('world.canonical_execution_input_digest', TRUE) IS DISTINCT FROM NEW.preparation_input_digest THEN + RAISE EXCEPTION 'World EXECUTING state requires its exact current transaction, complete owner observation and execution fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'PENDING' AND NEW.operation_state = 'ABORTED' THEN + IF NEW.execution_claimed IS DISTINCT FROM OLD.execution_claimed + OR NEW.active_transaction_id IS NOT NULL OR NEW.world_instance_id IS NOT NULL + OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_abort_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_abort_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_abort_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_abort_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR (OLD.game_session_owner_mutation_id IS NOT NULL AND ( + current_setting('world.canonical_abort_mutation', TRUE) IS DISTINCT FROM OLD.game_session_owner_mutation_id::TEXT + OR current_setting('world.canonical_abort_attempt_read', TRUE) IS DISTINCT FROM OLD.original_attempt_read_request_id::TEXT + OR current_setting('world.canonical_abort_lease_expiry', TRUE) IS DISTINCT FROM OLD.original_game_session_lease_expires_at::TEXT + OR current_setting('world.canonical_abort_observation_digest', TRUE) IS DISTINCT FROM OLD.original_attempt_evidence_sha256)) THEN + RAISE EXCEPTION 'World ABORTED state requires its exact serialized terminal fence' + USING ERRCODE = '23514'; + END IF; + ELSIF OLD.operation_state = 'EXECUTING' AND NEW.operation_state = 'COMMITTED' THEN + IF OLD.active_transaction_id IS DISTINCT FROM txid_current() + OR NEW.execution_claimed IS DISTINCT FROM TRUE + OR NEW.active_transaction_id IS NOT NULL + OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_execution_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_execution_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_execution_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_execution_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR current_setting('world.canonical_execution_fence', TRUE) IS DISTINCT FROM NEW.world_execution_fence::TEXT + OR current_setting('world.canonical_execution_input_digest', TRUE) IS DISTINCT FROM NEW.preparation_input_digest + OR NOT "${serviceSchema}".world_execution_has_exact_materialized_result(NEW, NEW.world_instance_id) THEN + RAISE EXCEPTION 'World COMMITTED state requires the current exact V35 preparation and V34 association' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'World execution state transition is not permitted' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.operation_state = 'PENDING' THEN + IF NEW.execution_claimed OR NEW.active_transaction_id IS NOT NULL + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NOT NULL + OR NEW.game_session_owner_mutation_id IS NULL + OR NEW.original_attempt_read_request_id IS NULL + OR NEW.original_game_session_lease_expires_at IS NULL + OR NEW.original_attempt_evidence_bytes IS NULL THEN + RAISE EXCEPTION 'A fresh World execution intent requires its exact Account owner observation' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.operation_state = 'ABORTED' THEN + IF NEW.execution_claimed OR NEW.active_transaction_id IS NOT NULL + OR NEW.world_instance_id IS NOT NULL OR NEW.terminal_at IS NULL + OR current_setting('world.canonical_abort_namespace', TRUE) IS DISTINCT FROM NEW.target_namespace + OR current_setting('world.canonical_abort_tenant', TRUE) IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR current_setting('world.canonical_abort_request', TRUE) IS DISTINCT FROM NEW.control_plane_request_id + OR current_setting('world.canonical_abort_target', TRUE) IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR (NEW.game_session_owner_mutation_id IS NOT NULL AND ( + current_setting('world.canonical_abort_mutation', TRUE) IS DISTINCT FROM NEW.game_session_owner_mutation_id::TEXT + OR current_setting('world.canonical_abort_attempt_read', TRUE) IS DISTINCT FROM NEW.original_attempt_read_request_id::TEXT + OR current_setting('world.canonical_abort_lease_expiry', TRUE) IS DISTINCT FROM NEW.original_game_session_lease_expires_at::TEXT + OR current_setting('world.canonical_abort_observation_digest', TRUE) IS DISTINCT FROM NEW.original_attempt_evidence_sha256)) THEN + RAISE EXCEPTION 'A born-ABORTED World operation requires its exact serialized abort fence' + USING ERRCODE = '23514'; + END IF; + ELSE + RAISE EXCEPTION 'World execution rows must be born PENDING or terminally ABORTED' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_enforce_canonical_instance_execution_transition() FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index 018b66f50a..8fffea0fc8 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -483,8 +483,12 @@ void exactRetryReusesOriginalAssociationAfterReadMetadataChangeWithoutLifecycleM WorldCanonicalInstancePreparation.Input originalInput = preparationInput( fixture, canonicalGameInstanceId, playableStateNamespaceId, "GS_FIXTURE", 1L); + WorldCanonicalInstanceExecutionIdentity originalIdentity = executionIdentity(originalInput); WorldCanonicalInstancePreparation.Result originalPreparation = - preparationService(() -> {}).prepare(originalInput); + preparationService(() -> {}) + .prepare( + originalInput, + WorldCanonicalInstanceExecutionTestFixtures.operationInput(originalIdentity)); long worldInstanceId = originalPreparation.association().worldInstanceId(); WorldCanonicalInstanceAssociation.Claim originalClaim = claim( @@ -991,6 +995,8 @@ void rollsBackCompletePreparationWhenHeldCommitAuthorityIsLostBeforeCommit() { AtomicInteger heldChecks = new AtomicInteger(); AtomicReference executionIdentity = new AtomicReference<>(); + WorldCanonicalInstanceExecutionIdentity syntheticIdentity = + WorldCanonicalInstanceExecutionTestFixtures.identity(input); WorldCanonicalInstancePreparationService service = preparationService( () -> { @@ -999,13 +1005,11 @@ void rollsBackCompletePreparationWhenHeldCommitAuthorityIsLostBeforeCommit() { } }, exactInput -> { - WorldCanonicalInstanceExecutionIdentity created = - WorldCanonicalInstanceExecutionTestFixtures.identity(exactInput); - executionIdentity.set(created); - return created; + executionIdentity.set(syntheticIdentity); + return syntheticIdentity; }); - assertThatThrownBy(() -> service.prepare(input)) + assertThatThrownBy(() -> prepareSynthetic(service, input, syntheticIdentity)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("synthetic held authority lost before commit"); @@ -1028,7 +1032,11 @@ void rollsBackCompletePreparationWhenHeldCommitAuthorityIsLostBeforeCommit() { WorldCanonicalInstanceExecutionIdentity retainedIdentity = executionIdentity.get(); assertThatThrownBy( - () -> preparationService(() -> {}, ignored -> retainedIdentity).prepare(input)) + () -> + prepareSynthetic( + preparationService(() -> {}, ignored -> retainedIdentity), + input, + retainedIdentity)) .isInstanceOf( WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class) .hasMessageContaining("PENDING"); @@ -1042,7 +1050,11 @@ void rollsBackCompletePreparationWhenHeldCommitAuthorityIsLostBeforeCommit() { assertThat(operation.state()) .isEqualTo(WorldCanonicalInstancePreparationRepository.ExecutionState.ABORTED)); assertThatThrownBy( - () -> preparationService(() -> {}, ignored -> retainedIdentity).prepare(input)) + () -> + prepareSynthetic( + preparationService(() -> {}, ignored -> retainedIdentity), + input, + retainedIdentity)) .isInstanceOf( WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class) .hasMessageContaining("ABORTED"); @@ -1057,82 +1069,73 @@ void exactIdentitySubstitutionIsRejectedBeforeAnyNewSourceOrWriterWork() { WorldCanonicalInstanceExecutionIdentity exactIdentity = WorldCanonicalInstanceExecutionTestFixtures.identity(input); WorldCanonicalInstancePreparation.Result committed = - preparationService(() -> {}, ignored -> exactIdentity).prepare(input); + prepareSynthetic( + preparationService(() -> {}, ignored -> exactIdentity), input, exactIdentity); WorldCanonicalInstanceExecutionIdentity substitutedIdentity = - new WorldCanonicalInstanceExecutionIdentity( - exactIdentity.originalPostAuthorizationTuple(), - UUID.randomUUID(), - exactIdentity.accountWorldParticipationFence(), - exactIdentity.gameSessionOwnerAttemptId(), - exactIdentity.gameSessionOwnerFence(), - exactIdentity.canonicalGameInstanceId(), - exactIdentity.preparationInputJson()); + WorldCanonicalInstanceExecutionTestFixtures.withParticipationId( + exactIdentity, UUID.randomUUID()); + SeededPair changedTuplePair = + seedPair( + fixture.source(), + fixture.versionIdentity(), + controlRequest(), + "synthetic-changed-original-start-session-tuple"); + Fixture changedTupleFixture = + new Fixture( + fixture.source(), changedTuplePair.binding(), changedTuplePair.versionIdentity()); + WorldCanonicalInstancePreparation.Input changedTupleInput = + preparationInput( + changedTupleFixture, canonicalGameInstanceId, UUID.randomUUID(), "GS_FIXTURE", 1L); WorldCanonicalInstanceExecutionIdentity changedTupleIdentity = - new WorldCanonicalInstanceExecutionIdentity( - WorldCanonicalInstanceExecutionTestFixtures.identity(input) - .originalPostAuthorizationTuple(), - exactIdentity.accountWorldParticipationId(), - exactIdentity.accountWorldParticipationFence(), - exactIdentity.gameSessionOwnerAttemptId(), - exactIdentity.gameSessionOwnerFence(), - exactIdentity.canonicalGameInstanceId(), - exactIdentity.preparationInputJson()); + WorldCanonicalInstanceExecutionTestFixtures.identity(changedTupleInput); WorldCanonicalInstanceExecutionIdentity changedAccountFence = - new WorldCanonicalInstanceExecutionIdentity( - exactIdentity.originalPostAuthorizationTuple(), - exactIdentity.accountWorldParticipationId(), + WorldCanonicalInstanceExecutionTestFixtures.withFences( + exactIdentity, exactIdentity.accountWorldParticipationFence() + 1L, - exactIdentity.gameSessionOwnerAttemptId(), - exactIdentity.gameSessionOwnerFence(), - exactIdentity.canonicalGameInstanceId(), - exactIdentity.preparationInputJson()); + exactIdentity.gameSessionOwnerFence()); WorldCanonicalInstanceExecutionIdentity changedGameSessionAttempt = - new WorldCanonicalInstanceExecutionIdentity( - exactIdentity.originalPostAuthorizationTuple(), - exactIdentity.accountWorldParticipationId(), - exactIdentity.accountWorldParticipationFence(), - UUID.randomUUID(), - exactIdentity.gameSessionOwnerFence(), - exactIdentity.canonicalGameInstanceId(), - exactIdentity.preparationInputJson()); + WorldCanonicalInstanceExecutionTestFixtures.withOwnerAttemptId( + exactIdentity, UUID.randomUUID()); WorldCanonicalInstanceExecutionIdentity changedGameSessionFence = - new WorldCanonicalInstanceExecutionIdentity( - exactIdentity.originalPostAuthorizationTuple(), - exactIdentity.accountWorldParticipationId(), + WorldCanonicalInstanceExecutionTestFixtures.withFences( + exactIdentity, exactIdentity.accountWorldParticipationFence(), - exactIdentity.gameSessionOwnerAttemptId(), - exactIdentity.gameSessionOwnerFence() + 1L, - exactIdentity.canonicalGameInstanceId(), - exactIdentity.preparationInputJson()); + exactIdentity.gameSessionOwnerFence() + 1L); for (WorldCanonicalInstanceExecutionIdentity substituted : List.of( substitutedIdentity, - changedTupleIdentity, changedAccountFence, changedGameSessionAttempt, changedGameSessionFence)) { - assertThatThrownBy(() -> preparationService(() -> {}, ignored -> substituted).prepare(input)) + assertThatThrownBy( + () -> + prepareSynthetic( + preparationService(() -> {}, ignored -> substituted), input, substituted)) .isInstanceOf( WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class) .hasMessageContaining("full identity"); } + assertThatThrownBy( + () -> + prepareSynthetic( + preparationService(() -> {}, ignored -> changedTupleIdentity), + input, + changedTupleIdentity)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from the exact original StartSession tuple"); + WorldCanonicalInstancePreparation.Input substitutedInput = preparationInput(fixture, canonicalGameInstanceId, UUID.randomUUID(), "GS_FIXTURE", 1L); WorldCanonicalInstanceExecutionIdentity substitutedInputIdentity = - new WorldCanonicalInstanceExecutionIdentity( - exactIdentity.originalPostAuthorizationTuple(), - exactIdentity.accountWorldParticipationId(), - exactIdentity.accountWorldParticipationFence(), - exactIdentity.gameSessionOwnerAttemptId(), - exactIdentity.gameSessionOwnerFence(), - exactIdentity.canonicalGameInstanceId(), - WorldCanonicalInstancePreparationRepository.inputJson(substitutedInput)); + WorldCanonicalInstanceExecutionTestFixtures.identity(substitutedInput); assertThatThrownBy( () -> - preparationService(() -> {}, ignored -> substitutedInputIdentity) - .prepare(substitutedInput)) + prepareSynthetic( + preparationService(() -> {}, ignored -> substitutedInputIdentity), + substitutedInput, + substitutedInputIdentity)) .isInstanceOf( WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class) .hasMessageContaining("full identity"); @@ -1163,8 +1166,10 @@ void worldExecutionFenceIsMonotonicAndDistinctFromSyntheticSourceFences() { withLargeSyntheticSourceFences( WorldCanonicalInstanceExecutionTestFixtures.identity(secondInput)); - preparationService(() -> {}, ignored -> firstIdentity).prepare(firstInput); - preparationService(() -> {}, ignored -> secondIdentity).prepare(secondInput); + prepareSynthetic( + preparationService(() -> {}, ignored -> firstIdentity), firstInput, firstIdentity); + prepareSynthetic( + preparationService(() -> {}, ignored -> secondIdentity), secondInput, secondIdentity); long firstWorldFence = preparationRepository() .readExactExecution(firstIdentity) @@ -1199,7 +1204,10 @@ void durableAbortBlocksFreshServiceV35AndV34Writers() { assertThat(preparationRepository().recordDurableAbort(identity).state()) .isEqualTo(WorldCanonicalInstancePreparationRepository.ExecutionState.ABORTED); - assertThatThrownBy(() -> preparationService(() -> {}, ignored -> identity).prepare(input)) + assertThatThrownBy( + () -> + prepareSynthetic( + preparationService(() -> {}, ignored -> identity), input, identity)) .isInstanceOf( WorldCanonicalInstancePreparationRepository.ConflictingPreparationException.class) .hasMessageContaining("ABORTED"); @@ -1260,7 +1268,7 @@ void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { status -> { Record intentRow = dsl.fetchOne( - "SELECT world_persist_canonical_instance_execution_intent(?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -1268,12 +1276,17 @@ void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { identity.accountWorldParticipationFence(), identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence(), - identity.canonicalGameInstanceId()); + identity.canonicalGameInstanceId(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + identity.originalGameSessionLeaseExpiresAt(), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); Long intentFence = intentRow == null ? null : intentRow.get(0, Long.class); Record claimRow = dsl.fetchOne( - "SELECT world_claim_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_claim_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -1281,11 +1294,16 @@ void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { identity.accountWorldParticipationFence(), identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence(), - identity.canonicalGameInstanceId()); + identity.canonicalGameInstanceId(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + identity.originalGameSessionLeaseExpiresAt(), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); Long claimFence = claimRow == null ? null : claimRow.get(0, Long.class); Record executionRow = dsl.fetchOne( - "SELECT world_begin_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_begin_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -1294,7 +1312,12 @@ void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence(), identity.canonicalGameInstanceId(), - intentFence); + intentFence, + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + identity.originalGameSessionLeaseExpiresAt(), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); Long executionFence = executionRow == null ? null : executionRow.get(0, Long.class); assertThat(claimFence).isEqualTo(intentFence); @@ -1384,7 +1407,7 @@ void admittedExecutionMayFinishAfterIngressExpiryAndThenUsesReadOnlyTerminalReco }, ignored -> identity); - WorldCanonicalInstancePreparation.Result committed = service.prepare(input); + WorldCanonicalInstancePreparation.Result committed = prepareSynthetic(service, input, identity); assertThat(Instant.now()).isAfter(originalExpiry); assertThat(committed.association().identity().canonicalGameInstanceId()) @@ -1452,8 +1475,10 @@ void expiryIsRecheckedByDatabaseClockAfterWaitingOnV35PublicationOwnerLock() thr Future attempt = executor.submit( () -> - preparationService(Duration.ofSeconds(30), () -> {}, ignored -> identity) - .prepare(input)); + prepareSynthetic( + preparationService(Duration.ofSeconds(30), () -> {}, ignored -> identity), + input, + identity)); awaitWorldPreparationLockWait(); awaitInstant(originalExpiry.plusMillis(100)); releaseOwnerRow.countDown(); @@ -1512,8 +1537,10 @@ void databaseLockTimeoutCancelsExecutionWithoutInventingAbortOrRetry() throws Ex Future attempt = executor.submit( () -> - preparationService(Duration.ofSeconds(2), () -> {}, ignored -> identity) - .prepare(input)); + prepareSynthetic( + preparationService(Duration.ofSeconds(2), () -> {}, ignored -> identity), + input, + identity)); awaitWorldPreparationLockWait(); assertThatThrownBy(attempt::get) .satisfies( @@ -1565,7 +1592,7 @@ void concurrentExecutionAndDurableAbortSerializeToCommittedResult() throws Excep try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future execution = - executor.submit(() -> service.prepare(input)); + executor.submit(() -> prepareSynthetic(service, input, identity)); assertThat(associated.await(10, TimeUnit.SECONDS)).isTrue(); CountDownLatch abortStarted = new CountDownLatch(1); Future abort = @@ -1620,11 +1647,11 @@ void concurrentExactPreparationDeniesPendingDuplicateAndRetainsOneOwnerResult() try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future first = - executor.submit(() -> firstService.prepare(exactInput)); + executor.submit(() -> prepareSynthetic(firstService, exactInput, exactIdentity)); try { assertThat(associationRetained.await(10, TimeUnit.SECONDS)).isTrue(); Future duplicate = - executor.submit(() -> secondService.prepare(exactInput)); + executor.submit(() -> prepareSynthetic(secondService, exactInput, exactIdentity)); assertThatThrownBy(() -> duplicate.get(10, TimeUnit.SECONDS)) .isInstanceOfSatisfying( java.util.concurrent.ExecutionException.class, @@ -1906,14 +1933,14 @@ private WorldCanonicalInstancePreparation.Result prepareCanonicalWorldRow( UUID playableStateNamespaceId, String observedGameSessionStatus, long observedGameSessionRowVersion) { - return preparationService(() -> {}) - .prepare( - preparationInput( - fixture, - canonicalGameInstanceId, - playableStateNamespaceId, - observedGameSessionStatus, - observedGameSessionRowVersion)); + WorldCanonicalInstancePreparation.Input input = + preparationInput( + fixture, + canonicalGameInstanceId, + playableStateNamespaceId, + observedGameSessionStatus, + observedGameSessionRowVersion); + return prepareSynthetic(preparationService(() -> {}), input, executionIdentity(input)); } private WorldCanonicalInstancePreparation.Input preparationInput( @@ -1960,16 +1987,18 @@ private WorldCanonicalInstanceExecutionIdentity executionIdentity( ignored -> WorldCanonicalInstanceExecutionTestFixtures.identity(input)); } + private WorldCanonicalInstancePreparation.Result prepareSynthetic( + WorldCanonicalInstancePreparationService service, + WorldCanonicalInstancePreparation.Input input, + WorldCanonicalInstanceExecutionIdentity identity) { + return service.prepare( + input, WorldCanonicalInstanceExecutionTestFixtures.operationInput(identity)); + } + private WorldCanonicalInstanceExecutionIdentity withLargeSyntheticSourceFences( WorldCanonicalInstanceExecutionIdentity identity) { - return new WorldCanonicalInstanceExecutionIdentity( - identity.originalPostAuthorizationTuple(), - identity.accountWorldParticipationId(), - Long.MAX_VALUE - 2, - identity.gameSessionOwnerAttemptId(), - Long.MAX_VALUE - 1, - identity.canonicalGameInstanceId(), - identity.preparationInputJson()); + return WorldCanonicalInstanceExecutionTestFixtures.withFences( + identity, Long.MAX_VALUE - 2, Long.MAX_VALUE - 1); } private WorldCanonicalInstancePreparationService preparationService( @@ -1979,25 +2008,29 @@ private WorldCanonicalInstancePreparationService preparationService( identityFactory) { WorldCanonicalInstancePreparationRepository preparationRepository = preparationRepository(transactionTimeout); - // Synthetic fixture handle only. This does not authenticate GS/GD source or delivery, prove - // APPLIED/IN_SYNC, or supply Account authority. + // Synthetic Account/GS observation and handle only. This proves World storage mechanics, not + // genuine participation acquisition, owner currentness, or continuous remote protection. return new WorldCanonicalInstancePreparationService( preparationRepository, - input -> - new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { - @Override - public WorldCanonicalInstanceExecutionIdentity executionIdentity() { - return identityFactory.apply(input); - } - - @Override - public void requireHeld() { - heldCheck.run(); - } - - @Override - public void close() {} - }); + (input, operationInput) -> { + WorldCanonicalInstanceExecutionIdentity identity = identityFactory.apply(input); + identity.requireMatches( + input, operationInput, WorldCanonicalInstancePreparationRepository.inputJson(input)); + return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { + @Override + public WorldCanonicalInstanceExecutionIdentity executionIdentity() { + return identity; + } + + @Override + public void requireHeld() { + heldCheck.run(); + } + + @Override + public void close() {} + }; + }); } private WorldCanonicalInstancePreparationRepository preparationRepository() { @@ -2012,7 +2045,7 @@ private long retainAndClaimExecutionIntent( status -> { Record intentRow = dsl.fetchOne( - "SELECT world_persist_canonical_instance_execution_intent(?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -2020,11 +2053,16 @@ private long retainAndClaimExecutionIntent( identity.accountWorldParticipationFence(), identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence(), - identity.canonicalGameInstanceId()); + identity.canonicalGameInstanceId(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + identity.originalGameSessionLeaseExpiresAt(), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); Long retainedFence = intentRow == null ? null : intentRow.get(0, Long.class); Record claimRow = dsl.fetchOne( - "SELECT world_claim_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_claim_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -2032,7 +2070,12 @@ private long retainAndClaimExecutionIntent( identity.accountWorldParticipationFence(), identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence(), - identity.canonicalGameInstanceId()); + identity.canonicalGameInstanceId(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + identity.originalGameSessionLeaseExpiresAt(), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); Long claimedFence = claimRow == null ? null : claimRow.get(0, Long.class); assertThat(claimedFence).isEqualTo(retainedFence); return retainedFence; @@ -2047,7 +2090,7 @@ private void beginExecution( long executionFence) { Record begunRow = dsl.fetchOne( - "SELECT world_begin_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_begin_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -2056,7 +2099,12 @@ private void beginExecution( identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence(), identity.canonicalGameInstanceId(), - executionFence); + executionFence, + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + identity.originalGameSessionLeaseExpiresAt(), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); Long begunFence = begunRow == null ? null : begunRow.get(0, Long.class); assertThat(begunFence).isEqualTo(executionFence); } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java index 1669e35fa1..bd8f7e02cc 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTestFixtures.java @@ -1,52 +1,119 @@ package net.firedevops.firemud.worldmanagement.tenant; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.OriginalStartSessionOperationInput; import tools.jackson.databind.json.JsonMapper; -/** Explicitly synthetic World-only fixture identity; it is not Account or Game Session proof. */ +/** + * Wire-valid but synthetic Account and Game Session observation used only by isolated World proofs. + */ final class WorldCanonicalInstanceExecutionTestFixtures { private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Instant DEFAULT_EXPIRY = Instant.parse("2099-01-01T00:15:00Z"); private WorldCanonicalInstanceExecutionTestFixtures() {} static WorldCanonicalInstanceExecutionIdentity identity(Input input) { - return identity(input, Instant.now().plusSeconds(900)); + return identity(input, DEFAULT_EXPIRY); } static WorldCanonicalInstanceExecutionIdentity identity(Input input, Instant expiresAt) { - var world = input.gameSessionReadEvidence(); var descriptor = input.completeLaunchBinding().evidence().descriptor(); - UUID actor = UUID.randomUUID(); + return identity( + input, + operationInput(input.gameSessionReadRequest(), descriptor.gameTemplateId(), expiresAt)); + } + + static WorldCanonicalInstanceExecutionIdentity identity( + Input input, OriginalStartSessionOperationInput operationInput) { + String seed = + operationSeed( + input.gameSessionReadRequest(), + input.completeLaunchBinding().evidence().descriptor().gameTemplateId()); + String exactInputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + var world = input.gameSessionReadEvidence(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + operationInput.originalPostAuthorizationTuple()); + UUID accountParticipationId = stableUuid(seed, "account-participation"); + long accountParticipationFence = 31L; + UUID ownerMutationId = operationInput.gameSessionOwnerMutationId(); + UUID ownerAttemptId = operationInput.gameSessionOwnerAttemptId(); + long ownerFence = operationInput.gameSessionOwnerFence(); + var ownerReadRequest = + new OriginalStartSessionCurrentAttemptEvidence.Request( + stableUuid(seed, "game-session-read-request"), + world.targetNamespace(), + tuple.canonicalBytes(), + ownerAttemptId, + ownerMutationId, + ownerFence); + var observation = + new OriginalStartSessionCurrentAttemptEvidence.Result( + ownerReadRequest, + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .expiresAt(), + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); + byte[] exactObservationBytes = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observation).toByteArray(); + return new WorldCanonicalInstanceExecutionIdentity( + tuple.canonicalBytes(), + accountParticipationId, + accountParticipationFence, + ownerMutationId, + ownerAttemptId, + ownerFence, + observation, + world.canonicalGameInstanceId(), + exactInputJson, + exactObservationBytes); + } + + static OriginalStartSessionOperationInput operationInput( + WorldCanonicalInstanceAssociation.GameSessionReadRequest world, long gameTemplateId) { + return operationInput(world, gameTemplateId, DEFAULT_EXPIRY); + } + + private static OriginalStartSessionOperationInput operationInput( + WorldCanonicalInstanceAssociation.GameSessionReadRequest world, + long gameTemplateId, + Instant expiresAt) { + String seed = operationSeed(world, gameTemplateId); + UUID actor = stableUuid(seed, "actor"); StartSessionOperatorAction action = new StartSessionOperatorAction( StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, new StartSessionOperatorAction.Scope( world.canonicalTenantId(), world.targetNamespace()), - new StartSessionOperatorAction.Target(descriptor.gameTemplateId(), actor), + new StartSessionOperatorAction.Target(gameTemplateId, actor), StartSessionOperatorAction.ExpectedVersion.ABSENT, new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), "synthetic World execution fixture"); StartSessionPreAuthorizationReservationTuple preTuple = StartSessionPreAuthorizationReservationTuple.createHuman( world.controlPlaneRequestId(), actor, action); - byte[] bundle = authorityBundle(preTuple, actor, expiresAt); + byte[] bundle = authorityBundle(preTuple, actor, expiresAt, seed); StartSessionPostAuthorizationExecutionTuple tuple = StartSessionPostAuthorizationExecutionTuple.createHuman( preTuple, "spiffe://firemud/ns/" + world.targetNamespace() + "/sa/logging-admin-service", "arfp/v1/test-key/" + "b".repeat(64), - UUID.randomUUID(), + stableUuid(seed, "reservation-owner"), 19L, bundle, new StartSessionAuthorityEvidenceBundle.BundleReference( @@ -54,20 +121,173 @@ static WorldCanonicalInstanceExecutionIdentity identity(Input input, Instant exp "17", "23", "18446744073709551615")); - return new WorldCanonicalInstanceExecutionIdentity( + return new OriginalStartSessionOperationInput( tuple.canonicalBytes(), - UUID.randomUUID(), - 31L, - UUID.randomUUID(), - 37L, - world.canonicalGameInstanceId(), - WorldCanonicalInstancePreparationRepository.inputJson(input)); + stableUuid(seed, "game-session-mutation"), + stableUuid(seed, "game-session-attempt"), + 37L); + } + + static OriginalStartSessionOperationInput operationInput( + WorldCanonicalInstanceExecutionIdentity identity) { + return new OriginalStartSessionOperationInput( + identity.originalPostAuthorizationTuple(), + identity.gameSessionOwnerMutationId(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence()); + } + + static OwnerOperation ownerOperation(Input input) { + OriginalStartSessionOperationInput operationInput = + operationInput( + input.gameSessionReadRequest(), + input.completeLaunchBinding().evidence().descriptor().gameTemplateId()); + return new OwnerOperation(operationInput, identity(input, operationInput)); + } + + private static String operationSeed( + WorldCanonicalInstanceAssociation.GameSessionReadRequest world, long gameTemplateId) { + return world.targetNamespace() + + ":" + + world.canonicalTenantId() + + ":" + + world.controlPlaneRequestId() + + ":" + + gameTemplateId; + } + + static WorldCanonicalInstanceExecutionIdentity withFences( + WorldCanonicalInstanceExecutionIdentity identity, + long accountParticipationFence, + long ownerFence) { + var previousObservation = observation(identity); + var ownerReadRequest = + new OriginalStartSessionCurrentAttemptEvidence.Request( + identity.originalAttemptReadRequestId(), + identity.targetNamespace(), + identity.originalPostAuthorizationTuple(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerMutationId(), + ownerFence); + var updatedObservation = + new OriginalStartSessionCurrentAttemptEvidence.Result( + ownerReadRequest, + previousObservation.originalLeaseExpiresAt(), + previousObservation.accountRedemptionProjection()); + byte[] updatedObservationBytes = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(updatedObservation) + .toByteArray(); + return new WorldCanonicalInstanceExecutionIdentity( + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + accountParticipationFence, + identity.gameSessionOwnerMutationId(), + identity.gameSessionOwnerAttemptId(), + ownerFence, + updatedObservation, + identity.canonicalGameInstanceId(), + identity.preparationInputJson(), + updatedObservationBytes); + } + + static WorldCanonicalInstanceExecutionIdentity withParticipationId( + WorldCanonicalInstanceExecutionIdentity identity, UUID participationId) { + return copyWithOwnerObservation( + identity, + participationId, + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence()); + } + + static WorldCanonicalInstanceExecutionIdentity withOwnerAttemptId( + WorldCanonicalInstanceExecutionIdentity identity, UUID ownerAttemptId) { + return copyWithOwnerObservation( + identity, + identity.accountWorldParticipationId(), + ownerAttemptId, + identity.gameSessionOwnerFence()); } + static WorldCanonicalInstanceExecutionIdentity withPreparationInputJson( + WorldCanonicalInstanceExecutionIdentity identity, String preparationInputJson) { + return new WorldCanonicalInstanceExecutionIdentity( + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerMutationId(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + observation(identity), + identity.canonicalGameInstanceId(), + preparationInputJson, + identity.originalAttemptEvidenceBytes()); + } + + private static WorldCanonicalInstanceExecutionIdentity copyWithOwnerObservation( + WorldCanonicalInstanceExecutionIdentity identity, + UUID participationId, + UUID ownerAttemptId, + long ownerFence) { + var previousObservation = observation(identity); + var ownerReadRequest = + new OriginalStartSessionCurrentAttemptEvidence.Request( + identity.originalAttemptReadRequestId(), + identity.targetNamespace(), + identity.originalPostAuthorizationTuple(), + ownerAttemptId, + identity.gameSessionOwnerMutationId(), + ownerFence); + var updatedObservation = + new OriginalStartSessionCurrentAttemptEvidence.Result( + ownerReadRequest, + previousObservation.originalLeaseExpiresAt(), + previousObservation.accountRedemptionProjection()); + byte[] updatedObservationBytes = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(updatedObservation) + .toByteArray(); + return new WorldCanonicalInstanceExecutionIdentity( + identity.originalPostAuthorizationTuple(), + participationId, + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerMutationId(), + ownerAttemptId, + ownerFence, + updatedObservation, + identity.canonicalGameInstanceId(), + identity.preparationInputJson(), + updatedObservationBytes); + } + + private static OriginalStartSessionCurrentAttemptEvidence.Result observation( + WorldCanonicalInstanceExecutionIdentity identity) { + try { + var wire = + net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse + .parseFrom(identity.originalAttemptEvidenceBytes()); + return OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(wire.getRequest()), wire); + } catch (com.google.protobuf.InvalidProtocolBufferException malformed) { + throw new IllegalArgumentException( + "Synthetic exact owner observation bytes are malformed", malformed); + } + } + + record OwnerOperation( + OriginalStartSessionOperationInput operationInput, + WorldCanonicalInstanceExecutionIdentity identity) {} + static byte[] authorityBundle( StartSessionPreAuthorizationReservationTuple tuple, UUID actor, Instant expiresAt) { + return authorityBundle(tuple, actor, expiresAt, UUID.randomUUID().toString()); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, + UUID actor, + Instant expiresAt, + String seed) { String tenantId = tuple.action().scope().tenantId().toString(); - Instant now = Instant.now(); + Instant now = expiresAt.minusSeconds(60L); Map projection = Map.of( "sourceType", @@ -84,7 +304,7 @@ static byte[] authorityBundle( canonicalTimestamp(expiresAt)); Map operation = Map.of( - "issuanceOperationId", UUID.randomUUID().toString(), + "issuanceOperationId", stableUuid(seed, "issuance-operation").toString(), "controlPlaneRequestId", tuple.controlPlaneRequestId(), "actionFamilyRequestIdentity", Map.of( @@ -107,7 +327,7 @@ static byte[] authorityBundle( "actorAccountId", actor.toString(), "controlUiTokenJti", - UUID.randomUUID().toString(), + stableUuid(seed, "control-ui-token").toString(), "role", "tenantAdmin", "accountGeneration", @@ -157,4 +377,11 @@ static byte[] authorityBundle( private static String canonicalTimestamp(Instant instant) { return Instant.ofEpochMilli(instant.toEpochMilli()).toString(); } + + private static UUID stableUuid(String seed, String label) { + UUID value = UUID.nameUUIDFromBytes((seed + ":" + label).getBytes(StandardCharsets.UTF_8)); + return value.equals(new UUID(0L, 0L)) + ? UUID.nameUUIDFromBytes((seed + ":" + label + ":nonzero").getBytes(StandardCharsets.UTF_8)) + : value; + } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java index 4b238acf38..148acfd899 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java @@ -162,16 +162,260 @@ void v35PreservesReservedTenantDenialAndExecutionEntrypointsRemainOwnerPrivate() + "AND p.proname IN ('world_prepare_canonical_instance', " + "'world_prepare_canonical_instance_v61_impl', " + "'world_persist_canonical_instance_execution_intent', " + + "'world_persist_canonical_instance_execution_intent_with_original_attempt', " + "'world_claim_canonical_instance_execution', " + + "'world_claim_canonical_instance_execution_with_original_attempt', " + "'world_begin_canonical_instance_execution', " + + "'world_begin_canonical_instance_execution_with_original_attempt', " + "'world_commit_canonical_instance_execution', " - + "'world_abort_canonical_instance_execution') " + + "'world_abort_canonical_instance_execution', " + + "'world_abort_canonical_instance_execution_with_original_attempt', " + + "'world_require_active_canonical_instance_execution') " + "AND acl.grantee = 0 AND acl.privilege_type = 'EXECUTE')"), "Prepare-function access query returned no result") .get(0, Boolean.class)) .isFalse(); } + @Test + void freshWorldIntentCannotBeCreatedWithoutTheAccountOwnerObservation() { + UUID tenant = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + UUID participation = UUID.randomUUID(); + UUID attempt = UUID.randomUUID(); + String request = "missing-owner-observation-" + UUID.randomUUID(); + + assertThatThrownBy( + () -> + dsl.fetchOne( + "INSERT INTO world_canonical_instance_execution (" + + "target_namespace,canonical_tenant_id,control_plane_request_id," + + "canonical_game_instance_id,canonical_world_slug,game_template_id," + + "original_post_authorization_tuple,original_post_authorization_tuple_sha256," + + "account_world_participation_id,account_world_participation_fence," + + "game_session_owner_attempt_id,game_session_owner_fence," + + "preparation_input_digest,preparation_input_json,world_execution_fence,operation_state) " + + "VALUES (?, ?, ?, ?, 'test-world', 1, ?, encode(sha256(?), 'hex'), ?, 1, ?, 1, " + + "'sha256:' || encode(sha256(convert_to('{}','UTF8')), 'hex'), '{}', " + + "nextval('world_canonical_instance_execution_fence_seq'), 'PENDING')", + NAMESPACE, + tenant, + request, + instance, + new byte[] {1}, + new byte[] {1}, + participation, + attempt)) + .isInstanceOf(DataIntegrityViolationException.class) + .rootCause() + .isInstanceOf(PSQLException.class) + .hasMessageContaining("exact Account owner observation"); + } + + @Test + void legacyTerminalFenceCannotAbortAnIntentWithAccountOwnerObservation() { + UUID tenant = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + UUID participation = UUID.randomUUID(); + UUID attempt = UUID.randomUUID(); + UUID mutation = UUID.randomUUID(); + UUID observationRead = UUID.randomUUID(); + String request = "legacy-abort-owner-observation-" + UUID.randomUUID(); + byte[] tuple = new byte[] {1}; + byte[] observation = new byte[] {7, 8, 9}; + String inputJson = "{}"; + String inputDigest = "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a"; + dsl.fetchOne( + "INSERT INTO world_canonical_instance_execution (" + + "target_namespace,canonical_tenant_id,control_plane_request_id," + + "canonical_game_instance_id,canonical_world_slug,game_template_id," + + "original_post_authorization_tuple,original_post_authorization_tuple_sha256," + + "account_world_participation_id,account_world_participation_fence," + + "game_session_owner_attempt_id,game_session_owner_fence," + + "game_session_owner_mutation_id,original_attempt_read_request_id," + + "original_game_session_lease_expires_at,original_attempt_evidence_bytes," + + "original_attempt_evidence_sha256,preparation_input_digest," + + "preparation_input_json,world_execution_fence,operation_state) " + + "VALUES (?, ?, ?, ?, 'test-world', 1, ?, encode(sha256(?), 'hex'), ?, 1, ?, 1, ?, ?, " + + "clock_timestamp() + interval '1 minute', ?, 'sha256:' || encode(sha256(?), 'hex'), ?, ?, " + + "nextval('world_canonical_instance_execution_fence_seq'), 'PENDING')", + NAMESPACE, + tenant, + request, + instance, + tuple, + tuple, + participation, + attempt, + mutation, + observationRead, + observation, + observation, + inputDigest, + inputJson); + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + dsl.fetchOne( + "SELECT set_config('world.canonical_abort_namespace', ?, TRUE)", + NAMESPACE); + dsl.fetchOne( + "SELECT set_config('world.canonical_abort_tenant', ?, TRUE)", + tenant.toString()); + dsl.fetchOne( + "SELECT set_config('world.canonical_abort_request', ?, TRUE)", + request); + dsl.fetchOne( + "SELECT set_config('world.canonical_abort_target', ?, TRUE)", + instance.toString()); + dsl.execute( + "UPDATE world_canonical_instance_execution " + + "SET operation_state='ABORTED', terminal_at=clock_timestamp() " + + "WHERE target_namespace=? AND canonical_tenant_id=? " + + "AND control_plane_request_id=?", + NAMESPACE, + tenant, + request); + return null; + })) + .isInstanceOf(DataIntegrityViolationException.class) + .rootCause() + .isInstanceOf(PSQLException.class) + .hasMessageContaining("World ABORTED state requires its exact serialized terminal fence"); + + assertThat( + dsl.fetchValue( + "SELECT operation_state FROM world_canonical_instance_execution " + + "WHERE target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?", + NAMESPACE, + tenant, + request)) + .isEqualTo("PENDING"); + } + + @Test + void originalOwnerLeaseIsRecheckedAgainstDatabaseClockAtWorldAdmission() { + UUID tenant = UUID.randomUUID(); + UUID instance = UUID.randomUUID(); + UUID participation = UUID.randomUUID(); + UUID attempt = UUID.randomUUID(); + UUID mutation = UUID.randomUUID(); + UUID observationRead = UUID.randomUUID(); + String request = "lease-expiry-admission-" + UUID.randomUUID(); + String inputJson = "{}"; + String inputDigest = "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a"; + byte[] tuple = + ("{\"authorityEvidenceBundle\":{\"accountProjectionEvidence\":{" + + "\"expiresAt\":\"2035-01-01T00:00:00Z\"}}}") + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] observation = new byte[] {7, 8, 9}; + + assertThatThrownBy( + () -> + ownerTransaction() + .execute( + status -> { + dsl.fetchOne( + "INSERT INTO world_canonical_instance_execution (" + + "target_namespace,canonical_tenant_id,control_plane_request_id," + + "canonical_game_instance_id,canonical_world_slug,game_template_id," + + "original_post_authorization_tuple,original_post_authorization_tuple_sha256," + + "account_world_participation_id,account_world_participation_fence," + + "game_session_owner_attempt_id,game_session_owner_fence," + + "game_session_owner_mutation_id,original_attempt_read_request_id," + + "original_game_session_lease_expires_at,original_attempt_evidence_bytes," + + "original_attempt_evidence_sha256,preparation_input_digest," + + "preparation_input_json,world_execution_fence,operation_state) " + + "VALUES (?, ?, ?, ?, 'test-world', 1, ?, encode(sha256(?), 'hex'), " + + "?, 1, ?, 1, ?, ?, clock_timestamp() + interval '50 milliseconds', " + + "?, 'sha256:' || encode(sha256(?), 'hex'), ?, ?, " + + "nextval('world_canonical_instance_execution_fence_seq'), 'PENDING')", + NAMESPACE, + tenant, + request, + instance, + tuple, + tuple, + participation, + attempt, + mutation, + observationRead, + observation, + observation, + inputDigest, + inputJson); + dsl.fetchOne( + "SELECT set_config('world.canonical_claim_namespace', ?, TRUE)", + NAMESPACE); + dsl.fetchOne( + "SELECT set_config('world.canonical_claim_tenant', ?, TRUE)", + tenant.toString()); + dsl.fetchOne( + "SELECT set_config('world.canonical_claim_request', ?, TRUE)", + request); + dsl.fetchOne( + "SELECT set_config('world.canonical_claim_target', ?, TRUE)", + instance.toString()); + dsl.fetchOne( + "SELECT set_config('world.canonical_claim_fence', ?, TRUE)", + Objects.requireNonNull( + dsl.fetchValue( + "SELECT world_execution_fence FROM world_canonical_instance_execution WHERE target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?", + NAMESPACE, + tenant, + request), + "world_execution_fence must exist for the exact preparation attempt") + .toString()); + dsl.execute( + "UPDATE world_canonical_instance_execution SET execution_claimed=TRUE " + + "WHERE target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?", + NAMESPACE, + tenant, + request); + for (String[] setting : + new String[][] { + {"world.canonical_execution_namespace", NAMESPACE}, + {"world.canonical_execution_tenant", tenant.toString()}, + {"world.canonical_execution_request", request}, + {"world.canonical_execution_target", instance.toString()}, + { + "world.canonical_execution_fence", + Objects.requireNonNull( + dsl.fetchValue( + "SELECT world_execution_fence FROM world_canonical_instance_execution WHERE target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?", + NAMESPACE, + tenant, + request), + "world_execution_fence must exist for the exact preparation attempt") + .toString() + }, + {"world.canonical_execution_input_digest", inputDigest} + }) { + dsl.fetchOne("SELECT set_config(?, ?, TRUE)", setting[0], setting[1]); + } + dsl.execute( + "UPDATE world_canonical_instance_execution " + + "SET operation_state='EXECUTING', active_transaction_id=txid_current() " + + "WHERE target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?", + NAMESPACE, + tenant, + request); + dsl.fetchOne("SELECT pg_sleep(0.1)"); + dsl.fetchOne( + "SELECT world_require_active_canonical_instance_execution(?, ?)", + inputJson, + inputDigest); + return null; + })) + .isInstanceOf(DataIntegrityViolationException.class) + .rootCause() + .isInstanceOf(PSQLException.class) + .hasMessageContaining("Game Session lease expired before World execution admission"); + } + private void insertInReservedCanonicalTenant(long tenantKey) { dsl.execute( "INSERT INTO world_instance (tenant_id, game_instance_id, game_template_id, " diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 2249dc9a9d..3990037d93 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -78,6 +78,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationClient; import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationGrpcCodec; +import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; import net.firedevops.firemud.common.world.RoomTemplateRef; @@ -312,7 +313,7 @@ void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRunt var repository = preparationRepository(); var service = preparationComponentWithRetainedTerminal(repository, originalTerminal); - var result = service.prepare(input); + var result = prepareSynthetic(service, input); assertThat(result.startLocation().roomTemplateId()).isEqualTo(lastRoom); assertThat(result.runtimeRoomInstanceId()).isPositive(); assertThat(result.storageStatus()).isEqualTo("MATERIALIZED_UNVERIFIED"); @@ -331,7 +332,7 @@ void releaseSelectorMaterializesItsOriginalRoomAndExactlyRetriesWithSeparateRunt var reassembled = assembly.service().assemble(stableSelector); assertThat(WorldCanonicalInstancePreparationRepository.inputJson(reassembled)) .isEqualTo(WorldCanonicalInstancePreparationRepository.inputJson(input)); - assertThat(service.prepare(reassembled)).isEqualTo(result); + assertThat(prepareSynthetic(service, reassembled)).isEqualTo(result); assertThat(repository.readOwnerPreparation(reassembled)).contains(result); assertThat(preparationRows(input.canonicalGameInstanceId())).containsExactly(before); assertThat(retainedPreparationSourceRows(f, seedInput, frozen)).isEqualTo(sourceRowsBefore); @@ -381,6 +382,8 @@ void authenticatedPreparationAdapterBindsFreshLaunchAndReadsActualPreparingLifec var launchFixture = preparationLaunchFixture(f, frozen, selector, 2L, List.of("LOOK")); var evidence = launchFixture.evidence(); var ownerRequest = launchFixture.ownerRequest(); + OriginalOperationInput syntheticOwnerOperation = + syntheticOwnerOperation(ownerRequest, evidence.descriptor().gameTemplateId()); byte[] originalAppliedRows = retainedApplicationBytes(application); byte[] originalSelectorBytes = selector.canonicalBytes(); var stableSelector = @@ -449,7 +452,9 @@ void authenticatedPreparationAdapterBindsFreshLaunchAndReadsActualPreparingLifec preparationClient(transport, preparationPki.clientProperties(WRONG_WORKLOAD_URI))) { wrongPeerClient.init(); assertThatThrownBy( - () -> wrongPeerClient.prepare(ownerRequest, expectedFirstLifecycleRequest)) + () -> + wrongPeerClient.prepare( + ownerRequest, syntheticOwnerOperation, expectedFirstLifecycleRequest)) .isInstanceOf(StatusRuntimeException.class) .satisfies( failure -> @@ -469,7 +474,8 @@ void authenticatedPreparationAdapterBindsFreshLaunchAndReadsActualPreparingLifec preparationClient( transport, preparationPki.clientProperties(GAME_SESSION_WORKLOAD_URI))) { client.init(); - var firstLifecycle = client.prepare(ownerRequest, expectedFirstLifecycleRequest); + var firstLifecycle = + client.prepare(ownerRequest, syntheticOwnerOperation, expectedFirstLifecycleRequest); assertThat( completeLaunchBindingCount( ownerRequest.targetNamespace(), @@ -570,7 +576,8 @@ void authenticatedPreparationAdapterBindsFreshLaunchAndReadsActualPreparingLifec ownerRequest.expectedReleaseAttestationEvidenceDigest()); var expectedRetryLifecycleRequest = lifecycleReadRequest(retryRequest, evidence, isolatedOwners.playableStateNamespaceId()); - var retryLifecycle = client.prepare(retryRequest, expectedRetryLifecycleRequest); + var retryLifecycle = + client.prepare(retryRequest, syntheticOwnerOperation, expectedRetryLifecycleRequest); var retryInput = isolatedOwners.service().assemble(stableSelector); var retryLifecycleRequest = lifecycleReadRequest( @@ -686,17 +693,17 @@ void canonicalPreparationKeepsOriginalPublicationEpochForLaterReleaseResolution( var repository = preparationRepository(); var service = preparationComponentWithRetainedTerminal(repository, originalTerminal); - assertThatThrownBy(() -> service.prepare(staleInput)) + assertThatThrownBy(() -> prepareSynthetic(service, staleInput)) .isInstanceOf( WorldCanonicalInstancePreparationRepository.InvalidPreparationEvidenceException.class) .hasMessageContaining("ReleaseContent differs"); - assertThatThrownBy(() -> service.prepare(changedReleaseInput)) + assertThatThrownBy(() -> prepareSynthetic(service, changedReleaseInput)) .isInstanceOf( WorldCanonicalInstancePreparationRepository.InvalidPreparationEvidenceException.class) .hasMessageContaining("ReleaseContent differs"); assertThat(count(f, "world_instance")).isZero(); - var prepared = service.prepare(laterInput); + var prepared = prepareSynthetic(service, laterInput); assertThat(prepared.startLocation().roomTemplateId()).isEqualTo(selectedRoom); assertThat(repository.readOwnerPreparation(laterInput)).contains(prepared); assertThat(publicationOwnerPhase(fence)).isEqualTo("PUBLISHED"); @@ -1503,7 +1510,7 @@ void canonicalLifecycleReadRejectsIncompleteOrSubstitutedRegionAssignments() { publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); var input = preparationInput(f, frozen, selector); var preparation = preparationComponent(preparationRepository()); - var materialized = preparation.prepare(input); + var materialized = prepareSynthetic(preparation, input); var associationRepository = associationRepository(); var lifecycleRepository = new WorldCanonicalInstanceLifecycleReadRepository(dsl, manager, associationRepository); @@ -1663,7 +1670,7 @@ void canonicalLifecycleReadRejectsIncompleteOrSubstitutedRegionAssignments() { assertThat(afterDeniedFailure).isEqualTo(preparing); // The real V35 retry preserves immutable preparation history and does not rewrite lifecycle. - assertThat(preparation.prepare(input)).isEqualTo(materialized); + assertThat(prepareSynthetic(preparation, input)).isEqualTo(materialized); var afterRetry = lifecycleRepository.read(request).orElseThrow(); assertThat(afterRetry).isEqualTo(preparing); @@ -3761,7 +3768,7 @@ void selectorPreparationLateFenceLossRollsBackSelectorRuntimeAndAssociationToget var component = new WorldCanonicalInstancePreparationService( preparationRepository(), - ignored -> + (ignored, operationInput) -> new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { public void requireHeld() { if (!TransactionSynchronizationManager.isActualTransactionActive()) { @@ -3827,7 +3834,11 @@ public WorldCanonicalInstanceExecutionIdentity executionIdentity() { public void close() {} }); - assertThatThrownBy(() -> component.prepare(input)) + assertThatThrownBy( + () -> + component.prepare( + input, + WorldCanonicalInstanceExecutionTestFixtures.operationInput(executionIdentity))) .hasMessageContaining("late Account fence loss"); assertThat(initialPreallocationAccepted.get()).isTrue(); for (String table : @@ -4018,15 +4029,8 @@ private void migrateHistoricalSchema(String schema, String version) { private WorldCanonicalInstanceExecutionIdentity syntheticExecutionWithInput( WorldCanonicalInstancePreparation.Input input, String exactInputJson) { - var fixture = WorldCanonicalInstanceExecutionTestFixtures.identity(input); - return new WorldCanonicalInstanceExecutionIdentity( - fixture.originalPostAuthorizationTuple(), - fixture.accountWorldParticipationId(), - fixture.accountWorldParticipationFence(), - fixture.gameSessionOwnerAttemptId(), - fixture.gameSessionOwnerFence(), - fixture.canonicalGameInstanceId(), - exactInputJson); + return WorldCanonicalInstanceExecutionTestFixtures.withPreparationInputJson( + WorldCanonicalInstanceExecutionTestFixtures.identity(input), exactInputJson); } private long beginSyntheticExecution(WorldCanonicalInstanceExecutionIdentity identity) { @@ -4034,7 +4038,7 @@ private long beginSyntheticExecution(WorldCanonicalInstanceExecutionIdentity ide Record persisted = Objects.requireNonNull( dsl.fetchOne( - "SELECT world_persist_canonical_instance_execution_intent(?,?,?,?,?,?,?,?) " + "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?,?,?,?,?,?,?,?,?,?,?,?,?) " + "AS world_execution_fence", identity.preparationInputJson(), identity.preparationInputDigest(), @@ -4043,7 +4047,12 @@ private long beginSyntheticExecution(WorldCanonicalInstanceExecutionIdentity ide identity.accountWorldParticipationFence(), identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence(), - identity.canonicalGameInstanceId()), + identity.canonicalGameInstanceId(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + identity.originalGameSessionLeaseExpiresAt(), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()), "Synthetic World execution intent returned no fence"); Long retainedFence = Objects.requireNonNull( @@ -4052,7 +4061,7 @@ private long beginSyntheticExecution(WorldCanonicalInstanceExecutionIdentity ide Record claimed = Objects.requireNonNull( dsl.fetchOne( - "SELECT world_claim_canonical_instance_execution(?,?,?,?,?,?,?,?) " + "SELECT world_claim_canonical_instance_execution_with_original_attempt(?,?,?,?,?,?,?,?,?,?,?,?,?) " + "AS world_execution_fence", identity.preparationInputJson(), identity.preparationInputDigest(), @@ -4061,13 +4070,18 @@ private long beginSyntheticExecution(WorldCanonicalInstanceExecutionIdentity ide identity.accountWorldParticipationFence(), identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence(), - identity.canonicalGameInstanceId()), + identity.canonicalGameInstanceId(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + identity.originalGameSessionLeaseExpiresAt(), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()), "Synthetic World execution claim returned no fence"); assertThat(claimed.get("world_execution_fence", Long.class)).isEqualTo(retainedFence); Record begun = Objects.requireNonNull( dsl.fetchOne( - "SELECT world_begin_canonical_instance_execution(?,?,?,?,?,?,?,?,?) " + "SELECT world_begin_canonical_instance_execution_with_original_attempt(?,?,?,?,?,?,?,?,?,?,?,?,?,?) " + "AS world_execution_fence", identity.preparationInputJson(), identity.preparationInputDigest(), @@ -4077,7 +4091,12 @@ private long beginSyntheticExecution(WorldCanonicalInstanceExecutionIdentity ide identity.gameSessionOwnerAttemptId(), identity.gameSessionOwnerFence(), identity.canonicalGameInstanceId(), - retainedFence), + retainedFence, + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + identity.originalGameSessionLeaseExpiresAt(), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()), "Synthetic World execution begin returned no fence"); return Objects.requireNonNull( begun.get("world_execution_fence", Long.class), @@ -4199,6 +4218,29 @@ private WorldCanonicalInstancePreparation.Input preparationInput( return preparationInput(f, frozen, selector, 2L, List.of("LOOK")); } + private static OriginalOperationInput syntheticOwnerOperation( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request, long gameTemplateId) { + var worldRequest = + new WorldCanonicalInstanceAssociation.GameSessionReadRequest( + request.readRequestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.gameInstanceUuid(), + request.controlPlaneRequestId(), + request.launchDescriptorId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationEvidenceDigest()); + var synthetic = + WorldCanonicalInstanceExecutionTestFixtures.operationInput(worldRequest, gameTemplateId); + return new OriginalOperationInput( + synthetic.originalPostAuthorizationTuple(), + synthetic.gameSessionOwnerMutationId(), + synthetic.gameSessionOwnerAttemptId(), + synthetic.gameSessionOwnerFence()); + } + private WorldCanonicalInstancePreparation.Input preparationInput( Fixture f, WorldCanonicalFrozenTopology frozen, @@ -4756,13 +4798,15 @@ private WorldCanonicalInstancePreparationService preparationComponent( new LinkedHashMap<>(); return new WorldCanonicalInstancePreparationService( repository, - input -> { + (input, operationInput) -> { completeIsolatedPublicationTerminal(input); String inputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); var executionIdentity = executionIdentities.computeIfAbsent( inputJson, - ignored -> WorldCanonicalInstanceExecutionTestFixtures.identity(input)); + ignored -> + WorldCanonicalInstanceExecutionTestFixtures.identity(input, operationInput)); + executionIdentity.requireMatches(input, operationInput, inputJson); return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { private boolean open = true; @@ -4782,6 +4826,14 @@ public void close() { }); } + private WorldCanonicalInstancePreparation.Result prepareSynthetic( + WorldCanonicalInstancePreparationService service, + WorldCanonicalInstancePreparation.Input input) { + var identity = WorldCanonicalInstanceExecutionTestFixtures.identity(input); + return service.prepare( + input, WorldCanonicalInstanceExecutionTestFixtures.operationInput(identity)); + } + /** * Isolated fixture verifier that preserves and independently reads an already committed V44 * terminal instead of trying to reseal it from a later descriptor resolution. @@ -4802,7 +4854,7 @@ private WorldCanonicalInstancePreparationService preparationComponentWithRetaine new LinkedHashMap<>(); return new WorldCanonicalInstancePreparationService( repository, - input -> { + (input, operationInput) -> { if (verifierInvocations != null) { verifierInvocations.incrementAndGet(); } @@ -4821,7 +4873,9 @@ private WorldCanonicalInstancePreparationService preparationComponentWithRetaine var executionIdentity = executionIdentities.computeIfAbsent( inputJson, - ignored -> WorldCanonicalInstanceExecutionTestFixtures.identity(input)); + ignored -> + WorldCanonicalInstanceExecutionTestFixtures.identity(input, operationInput)); + executionIdentity.requireMatches(input, operationInput, inputJson); return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { private boolean open = true; @@ -5046,7 +5100,7 @@ private PreparedLifecycleFixture materializedLifecycleFixture() { publishedEvidence( publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); var input = preparationInput(f, frozen, selector); - var materialized = preparationComponent(preparationRepository()).prepare(input); + var materialized = prepareSynthetic(preparationComponent(preparationRepository()), input); var lifecycleRepository = new WorldCanonicalInstanceLifecycleReadRepository(dsl, manager, associationRepository()); var readRequest = lifecycleReadRequest(input); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcServiceTest.java index 5781103a89..280ba686c2 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcServiceTest.java @@ -1,6 +1,8 @@ package unit.net.firedevops.firemud.worldmanagement.tenant; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -10,6 +12,8 @@ import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; @@ -19,6 +23,11 @@ import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationGrpcCodec; import net.firedevops.firemud.common.world.RoomTemplateRef; @@ -45,9 +54,11 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; /** Component-only adapter tests; mocked producer and storage results are not PostgreSQL proof. */ class WorldCanonicalInstancePreparationGrpcServiceTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); private static final String NAMESPACE = "test"; private static final UUID TENANT_ID = uuid("22222222-2222-4222-8222-222222222222"); private static final UUID INSTANCE_ID = uuid("33333333-3333-4333-8333-333333333333"); @@ -232,7 +243,9 @@ void freshNonStartingSessionIsDeniedButAnExactHistoricalRetryStillCallsPrepare() Harness retry = new Harness("RUNNING"); when(retry.preparationRepository.readOwnerPreparation(retry.input)) .thenReturn(Optional.of(retry.prepared)); - when(retry.preparation.prepare(retry.input)) + when(retry.preparation.prepare( + eq(retry.input), + any(CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput.class))) .thenThrow( new WorldCanonicalInstancePreparationService.PreparationDeniedException( "held proof denied")); @@ -241,7 +254,10 @@ void freshNonStartingSessionIsDeniedButAnExactHistoricalRetryStillCallsPrepare() call(retry.service, request(retry.selector), peer("game-session-service", NAMESPACE)); assertThat(retryResult.error).isEqualTo(Status.Code.PERMISSION_DENIED); - verify(retry.preparation).prepare(retry.input); + verify(retry.preparation) + .prepare( + eq(retry.input), + any(CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput.class)); verifyNoInteractions(retry.lifecycleRepository); } @@ -263,13 +279,19 @@ void productionDefaultVerifierDeniesWithoutLifecycleSuccessAndNullPrepareResultI verifyNoInteractions(defaultDenied.lifecycleRepository); Harness noResult = new Harness("STARTING"); - when(noResult.preparation.prepare(noResult.input)).thenReturn(null); + when(noResult.preparation.prepare( + eq(noResult.input), + any(CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput.class))) + .thenReturn(null); Collector absent = call(noResult.service, request(noResult.selector), peer("game-session-service", NAMESPACE)); assertThat(absent.error).isEqualTo(Status.Code.FAILED_PRECONDITION); - verify(noResult.preparation).prepare(noResult.input); + verify(noResult.preparation) + .prepare( + eq(noResult.input), + any(CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput.class)); verifyNoInteractions(noResult.lifecycleRepository); } @@ -302,7 +324,10 @@ void bindsBeforeAssemblyThenRequiresExactMaterializationAndIndependentLifecycleR new WorldCanonicalInstancePreparationAssemblyService.Selector( TENANT_ID, INSTANCE_ID, CONTROL_REQUEST_ID)); verify(harness.preparationRepository).readOwnerPreparation(harness.input); - verify(harness.preparation).prepare(harness.input); + verify(harness.preparation) + .prepare( + eq(harness.input), + any(CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput.class)); verify(harness.lifecycleRepository).read(harness.lifecycleRequest); } @@ -322,13 +347,154 @@ void missingOrInconsistentIndependentLifecycleEvidenceIsRejected() { request(inconsistent.selector), peer("game-session-service", NAMESPACE)); assertThat(inconsistentResult.error).isEqualTo(Status.Code.FAILED_PRECONDITION); - verify(missing.preparation).prepare(missing.input); - verify(inconsistent.preparation).prepare(inconsistent.input); + verify(missing.preparation) + .prepare( + eq(missing.input), + any(CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput.class)); + verify(inconsistent.preparation) + .prepare( + eq(inconsistent.input), + any(CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput.class)); } private static PrepareCanonicalWorldInstanceRequest request( CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector) { - return CanonicalWorldInstancePreparationGrpcCodec.toRequest(selector); + return CanonicalWorldInstancePreparationGrpcCodec.toRequest( + selector, + new CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput( + originalTuple(selector), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + 37L)); + } + + private static byte[] originalTuple( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector) { + UUID actor = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope( + selector.canonicalTenantId(), selector.targetNamespace()), + new StartSessionOperatorAction.Target(91L, actor), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "synthetic gRPC preparation request"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + selector.controlPlaneRequestId(), actor, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + selector.targetNamespace() + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "d".repeat(64), + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + 19L, + authorityEvidenceBundle(preTuple, actor, Instant.parse("2030-01-01T00:05:00Z")), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")) + .canonicalBytes(); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple tuple, UUID actor, Instant expiresAt) { + String tenant = tuple.action().scope().tenantId().toString(); + Instant now = expiresAt.minusSeconds(60); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + canonicalTimestamp(now.minusSeconds(30)), + "expiresAt", + canonicalTimestamp(expiresAt)); + Map operationIdentity = + Map.of( + "issuanceOperationId", uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee").toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 2L, + "tenantAuthorityGeneration", + Map.of(tenant, 3L), + "membershipAuthorityGeneration", + Map.of(tenant, 4L), + "privateRealmGrantVersions", + List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actor.toString(), + "controlUiTokenJti", + uuid("ffffffff-ffff-4fff-8fff-ffffffffffff").toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenant, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actor.toString(), + "applicableTenantId", + tenant), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operationIdentity, + "issuanceKind", + "human_operator", + "authorityTuple", + authorityTuple, + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + } catch (IOException exception) { + throw new IllegalStateException("Could not encode the synthetic owner tuple", exception); + } + } + + private static String canonicalTimestamp(Instant instant) { + return Instant.ofEpochMilli(instant.toEpochMilli()).toString(); } private static Collector call( @@ -430,6 +596,7 @@ private Harness(String currentStatus) { when(descriptor.launchDescriptorId()).thenReturn(DESCRIPTOR_ID); when(descriptor.requestDigest()).thenReturn(REQUEST_DIGEST); when(descriptor.resultDigest()).thenReturn(RESULT_DIGEST); + when(descriptor.gameTemplateId()).thenReturn(91L); when(release.targetNamespace()).thenReturn(NAMESPACE); when(release.descriptorResultDigest()).thenReturn(RESULT_DIGEST); when(release.canonicalTenantId()).thenReturn(TENANT_ID); @@ -492,7 +659,10 @@ private Harness(String currentStatus) { when(association.completeLaunchBinding()).thenReturn(binding); when(association.versionIdentity()).thenReturn(versionIdentity); when(preparationRepository.readOwnerPreparation(input)).thenReturn(Optional.empty()); - when(preparation.prepare(input)).thenReturn(prepared); + when(preparation.prepare( + eq(input), + any(CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput.class))) + .thenReturn(prepared); lifecycleRequest = new Request( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java index 7b3472dd9e..df476a7925 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java @@ -131,6 +131,24 @@ void ambientSynchronizationIsDeniedBeforeFreshPreparationVerificationOrStorage() verifyNoInteractions(repository, recoveryVerifier, commitVerifier, input); } + @Test + void freshPreparationWithoutTypedOriginalOwnerInputDeniesEvenWithLegacyVerifier() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var commitVerifier = + mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); + var input = + mock( + net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input + .class); + var service = new WorldCanonicalInstancePreparationService(repository, commitVerifier); + + assertThatThrownBy(() -> service.prepare(input)) + .isInstanceOf(WorldCanonicalInstancePreparationService.PreparationDeniedException.class) + .hasMessageContaining("exact original Game Session owner operation"); + + verifyNoInteractions(repository, commitVerifier, input); + } + @Test void exactRecoveryAuthenticatesThenReturnsTheUnchangedReadOnlyLookup() { var repository = mock(WorldCanonicalInstancePreparationRepository.class); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java index 88521ed104..a8596389b7 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java @@ -255,17 +255,13 @@ void defaultServiceDeniesBeforeRepositoryAccess() { mock(WorldCanonicalInstancePreparationRepository.class); WorldCanonicalInstancePreparation.Input input = mock(WorldCanonicalInstancePreparation.Input.class); - WorldCanonicalInstanceTopologyPlan plan = mock(WorldCanonicalInstanceTopologyPlan.class); - when(input.topologyPlan()).thenReturn(plan); - when(plan.generationRules()).thenReturn(List.of()); - when(plan.spawnBindings()).thenReturn(List.of()); assertThatThrownBy( () -> new WorldCanonicalInstancePreparationService(repository).prepare(input)) .isInstanceOf(WorldCanonicalInstancePreparationService.PreparationDeniedException.class) - .hasMessageContaining("no authenticated source/release terminal verifier"); + .hasMessageContaining("exact original Game Session owner operation"); - verifyNoInteractions(repository); + verifyNoInteractions(input, repository); } private static DuplicateKeyException duplicateKeyFailure(String sqlState, String message) { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionAccountParticipationVerifierTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionAccountParticipationVerifierTest.java new file mode 100644 index 0000000000..dff4e0b170 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionAccountParticipationVerifierTest.java @@ -0,0 +1,236 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationAcquisitionClient; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.Input; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation.OriginalStartSessionOperationInput; +import net.firedevops.firemud.worldmanagement.tenant.WorldStartSessionAccountParticipationVerifier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class WorldStartSessionAccountParticipationVerifierTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String NAMESPACE = "world-runtime"; + private static final UUID TENANT_ID = uuid("11111111-1111-4111-8111-111111111111"); + + @AfterEach + void clearAmbientState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactPeerAndWorkloadOnlyContextAreRequiredBeforeAccountAcquisition() { + var client = mock(AccountStartSessionWorldParticipationAcquisitionClient.class); + var verifier = new WorldStartSessionAccountParticipationVerifier(NAMESPACE, client); + Input input = mock(Input.class); + OriginalStartSessionOperationInput operationInput = operationInput(); + + assertThatThrownBy(() -> verifier.verifyAndHold(input, operationInput)) + .isInstanceOf(SecurityException.class); + verifyNoInteractions(client); + + var wrongPeer = peer("account-service", NAMESPACE); + var context = Context.ROOT.withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer); + Context previous = context.attach(); + try { + assertThatThrownBy(() -> verifier.verifyAndHold(input, operationInput)) + .isInstanceOf(SecurityException.class); + } finally { + context.detach(previous); + } + verifyNoInteractions(client); + + var gameSessionContext = + Context.ROOT.withValue( + GrpcPeerIdentity.CONTEXT_KEY, peer("game-session-service", NAMESPACE)); + previous = gameSessionContext.attach(); + try { + SessionContext.setContext("22222222-2222-4222-8222-222222222222", List.of(), Map.of()); + assertThatThrownBy(() -> verifier.verifyAndHold(input, operationInput)) + .isInstanceOf(SecurityException.class); + } finally { + SessionContext.clear(); + gameSessionContext.detach(previous); + } + verifyNoInteractions(client); + } + + @Test + void ambientWorldTransactionIsRejectedBeforeAccountAcquisition() { + var client = mock(AccountStartSessionWorldParticipationAcquisitionClient.class); + var verifier = new WorldStartSessionAccountParticipationVerifier(NAMESPACE, client); + Input input = mock(Input.class); + OriginalStartSessionOperationInput operationInput = operationInput(); + var context = + Context.ROOT.withValue( + GrpcPeerIdentity.CONTEXT_KEY, peer("game-session-service", NAMESPACE)); + Context previous = context.attach(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> verifier.verifyAndHold(input, operationInput)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient World transaction"); + } finally { + TransactionSynchronizationManager.clear(); + context.detach(previous); + } + verifyNoInteractions(client, input); + } + + private static OriginalStartSessionOperationInput operationInput() { + UUID actor = uuid("33333333-3333-4333-8333-333333333333"); + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(91L, actor), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "synthetic owner-operation input for peer-guard proof"); + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "original-start-session", actor, action); + var postTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "a".repeat(64), + uuid("44444444-4444-4444-8444-444444444444"), + 19L, + authorityEvidenceBundle(preTuple, actor), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + return new OriginalStartSessionOperationInput( + postTuple.canonicalBytes(), + uuid("55555555-5555-4555-8555-555555555555"), + uuid("66666666-6666-4666-8666-666666666666"), + 37L); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple tuple, UUID actor) { + String tenant = tuple.action().scope().tenantId().toString(); + Instant expiresAt = Instant.parse("2030-01-01T00:05:00Z"); + Instant now = expiresAt.minusSeconds(60L); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + canonicalTimestamp(now.minusSeconds(30L)), + "expiresAt", + canonicalTimestamp(expiresAt)); + Map operationIdentity = + Map.of( + "issuanceOperationId", uuid("77777777-7777-4777-8777-777777777777").toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 2L, + "tenantAuthorityGeneration", + Map.of(tenant, 3L), + "membershipAuthorityGeneration", + Map.of(tenant, 4L), + "privateRealmGrantVersions", + List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actor.toString(), + "controlUiTokenJti", + uuid("88888888-8888-4888-8888-888888888888").toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", tenant, "targetNamespace", NAMESPACE), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actor.toString(), + "applicableTenantId", + tenant), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operationIdentity, + "issuanceKind", + "human_operator", + "authorityTuple", + authorityTuple, + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + } catch (IOException exception) { + throw new IllegalStateException("Could not encode the synthetic owner tuple", exception); + } + } + + private static String canonicalTimestamp(Instant instant) { + return Instant.ofEpochMilli(instant.toEpochMilli()).toString(); + } + + private static GrpcPeerIdentity peer(String service, String namespace) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} From d81f4eee09ef5aa81353e7e44630ad5e3d3cf898 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 10:55:30 +1300 Subject: [PATCH 099/129] Compose original owner acquisition and conditional historical recovery proof --- ...ame-authoring-publishing-and-activation.md | 6 +- .../world-runtime-and-movement.md | 2 + ...issionLeasePersistenceIntegrationTest.java | 215 +++++++--- services/game-design-service/build.gradle.kts | 8 + ...licationExportPostgresIntegrationTest.java | 387 ++++++++++-------- 5 files changed, 383 insertions(+), 235 deletions(-) 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 c79cfd0294..c2c33cdd2e 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 @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The current source-construction batch defines actual isolated Logging, Account and Game Session stores for original participation acquisition, a file-backed mTLS Logging claim reader, the Game Session V35 attempt reader, World typed original-operation acquisition with additive V63 admission evidence, and the source-only authored initial actor core described at the [Game Design owner](../../architecture/microservices/game-design-service/game-templates.md#release-authored-initial-actor-core). The producer validates selected schema-three source bindings but does not yet deliver or persist a new actor-allocation handoff. The existing genuine-release-to-World definition still stipulates its Game Session launch association and held acquisition witness; replacing that witness with actual acquisition is the next proof step, not completed proof. No production receiver, credential path, allocation, lifecycle or admission activation is enabled. +The current source-construction batch defines actual isolated Logging, Account and Game Session stores for original participation acquisition, a file-backed mTLS Logging claim reader, the Game Session V35 attempt reader, World typed original-operation acquisition with additive V63 admission evidence, and the source-only authored initial actor core described at the [Game Design owner](../../architecture/microservices/game-design-service/game-templates.md#release-authored-initial-actor-core). The producer validates selected schema-three source bindings but does not yet deliver or persist a new actor-allocation handoff. The genuine-release-to-World definition now reserves the exact original tuple in an isolated Game Session store before Account redemption, attaches the exact redeemed projection afterward, and traverses the native Account-to-Game-Session current-attempt and World-to-Account participation clients and receivers. Its Game Session launch association, Logging claim and some Account caller contexts remain stipulated. Stores, servers and the reusable transport clients are prepared before the unchanged 30-second owner lease; the later descriptor and preparation work must still fit that lease without renewal or rearming. This definition has compiled but has not executed physically, and its acquired observation is not continuous foreign-owner protection. No production receiver, credential path, allocation, lifecycle or admission activation is enabled. + +The historical [Validation run 38075220202](https://github.com/benhook1013/FireMUD/actions/runs/38075220202) tests published source `e0f048e4eb5810eb69581dcb2c74e612cb368a60` through merge `e0e6e6394d51218511cd8e8a8ec72eeffb454fb5`, not the later local construction. Account's 1,683 aggregate cases include one failed concurrent historical acknowledgement-receipt recovery case on PostgreSQL 16.15: the independent reader correctly denies because its observed WAL flush does not cover the insertion fence. That test's unconditional recovery-success expectation is not the accepted conditional recovery contract. The 13 protected-entry and 31 Draft-fence PostgreSQL cases pass physically; the Account job is cancelled after its check fails, so this is neither a green aggregate nor current-source proof. Gameplay's separately qualified PostgreSQL 18 original-acknowledgement proof covers only its fresh storage boundary; it does not establish historical recovery, continuous owner protection or gameplay admission. + +The current test correction permits only complete exact historical receipt recovery or the specific PostgreSQL `23514` WAL-coverage constraint denial; all other failures still propagate. It preserves independent reads, concurrent retry, unchanged stored operation and expiry, and no-remint assertions before and after expiry. The focused Account/Game Design gate passes in 1 minute 30 seconds across 176 tasks, including integration compilation, formatting, static checks, coverage, links and 548 Markdown files. The 1,930 passing unit results are reused from the preceding gate, not fresh executions. Twelve non-container Account integration cases execute; 438 container-dependent cases skip (287 Account and 151 Game Design). Neither the conditional recovery correction nor the native release-to-World composition has corrected physical execution proof yet. The corrected composed seven-module local gate passes in 6 minutes 4 seconds, including complete checks, proof artifacts, formatting, Checkstyle, SpotBugs, JaCoCo, links, all 548 Markdown files and Flyway sanity for 12 sets/302 versioned files. Fresh XML records 5,603 executed unit cases and 41 executed integration/cross-service cases, with zero failures or errors. Container-dependent cases skip: 17 Game Session unit cases and 880 integration/cross-service cases across the owners. Those skips do not prove PostgreSQL migration/concurrency, actual native owner composition, MinIO export, source protection or activation. Architecture contracts separately pass 228 checks. The proof artifacts exclude borrowed application and migration resources; generated Spring configuration metadata is not application configuration. All four complete Gameplay handoffs remain open. 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 c977f1a4b3..6efe2e02e8 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,8 @@ This tracker is the permanent reader-facing implementation record for world runt Canonical preparation now defines the typed original Game Session operation input and an explicit Account participation acquisition adapter before World SQL. Additive V63 retains the exact returned original-attempt observation and checks the unchanged original authorization and Game Session lease against the database clock after admission locks; the legacy untyped entry cannot authorize fresh materialization. This is unregistered source construction, not production wiring or continuous foreign-owner protection. Schema generation succeeds, but physical V63 migration, concurrency and genuine Account-acquisition-to-World execution remain unproved locally; existing positive storage definitions retain explicitly synthetic complete witnesses. The [World owner contract](../../architecture/microservices/world-management-service/runtime-and-data.md#original-startsession-execution-storage) owns the settlement and recovery limits; the [authoring tracker](./game-authoring-publishing-and-activation.md) records composed proof and remaining handoffs. +The genuine Game Design release-to-World PostgreSQL definition now replaces its synthetic acquisition witness with the real Game Session V35 reservation and redeemed projection, native Account current-attempt observation and World participation acquisition. It retains the unchanged finite owner lease and authenticates the explicit transport peers, but its launch association and selected upstream authorization contexts remain stipulated. Local compilation and static checks do not execute this container-dependent composition or prove continuous protection, production wiring or activation. + 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). The unregistered [canonical initial-placement terminal read](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-placement-terminal-readback) returns exact historical operation evidence without current placement authorization. Its [socket mTLS proof](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlacementOutcomeMtlsTest.java) executes against the real handler and a mock owner; it is not database-to-socket or live settlement proof. The [PostgreSQL definition](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java) checks retained `APPLIED`/`CONFLICT` bytes and no mutation when new placement authority is denied; corrected physical execution remains pending. Physical readback after canonical termination remains an explicit World lifecycle/cleanup obligation: the legacy numeric-key termination writer is correctly rejected by the canonical execution-manifest guard and cannot manufacture that test state. Revisit the post-termination proof when the canonical owner transition and required cleanup acknowledgements are implemented; do not bypass the guard or infer termination from missing state. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java index 4bf6be092c..8a45499517 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeasePersistenceIntegrationTest.java @@ -1601,7 +1601,7 @@ void lostOriginalAckReceiptAcknowledgementDeniesWithoutRemintingOriginalProof() } @Test - void originalAckReceiptRecoversExactOriginalProofAfterLostReceiptAcknowledgement() { + void originalAckReceiptReadAfterLostReceiptAckRequiresWalCoverage() { var context = context(null); var original = pending(context, account(context)); UUID decision = UUID.randomUUID(); @@ -1628,51 +1628,40 @@ void originalAckReceiptRecoversExactOriginalProofAfterLostReceiptAcknowledgement assertThat(rowBeforeRecoveryRecord.get("receipt_xid", String.class)) .isNotEqualTo(rowBeforeRecoveryRecord.get("finalization_xid", String.class)); - var recovered = receiptExecutor.read(original, decision); + var sourcesBeforeRecovery = storageSnapshot(context); + var historicalRead = readWithConditionalWalCoverage(receiptExecutor, original, decision); - assertThat(trace.count("receipt-physical-commit")).isEqualTo(2); - assertThat(trace.count("receipt-durable-read")).isEqualTo(1); + assertThat(trace.count("receipt-durable-read")).isGreaterThanOrEqualTo(1); assertThat(trace.count("receipt-exact-read")).isZero(); var lostReceiptCommit = firstEvent(trace, "receipt-physical-commit"); - var historicalRead = firstEvent(trace, "receipt-durable-read"); + var historicalReadEvent = firstEvent(trace, "receipt-durable-read"); assertThat(trace.events().indexOf(lostReceiptCommit)) - .isLessThan(trace.events().indexOf(historicalRead)); - assertThat(historicalRead.connectionId()).isNotEqualTo(lostReceiptCommit.connectionId()); - assertThat(recovered.operation().evidence().canonicalJson()) - .isEqualTo(original.canonicalJson()); - assertThat(recovered.operation().evidence().sha256()).isEqualTo(original.sha256()); - assertThat(recovered.operation().bindingDecisionId()).isEqualTo(decision); - assertThat(recovered.schemaVersion()) - .isEqualTo(rowBeforeRecoveryRecord.get("schema_version", Short.class)); - assertThat(recovered.requestId()).isEqualTo(requestId(original)); - assertThat(recovered.accountId()) - .isEqualTo(rowBeforeRecoveryRecord.get("account_uuid", UUID.class)); - assertThat(recovered.leaseId()).isEqualTo(rowBeforeRecoveryRecord.get("lease_id", UUID.class)); - assertThat(recovered.leaseFence()) - .isEqualTo(rowBeforeRecoveryRecord.get("lease_fence", Long.class)); - assertThat(recovered.evidenceSha256()).isEqualTo(original.sha256()); - assertThat(recovered.bindingDecisionId()).isEqualTo(decision); - assertThat(recovered.expiresAtMs()) - .isEqualTo(rowBeforeRecoveryRecord.get("expires_at_ms", Long.class)); - assertThat(recovered.committedBeforeMs()) - .isEqualTo(rowBeforeRecoveryRecord.get("committed_before_ms", Long.class)) - .isLessThan(recovered.expiresAtMs()); - assertThat(recovered.finalizationXid()) - .isEqualTo(rowBeforeRecoveryRecord.get("finalization_xid", String.class)); - assertThat(recovered.receiptXid()) - .isEqualTo(rowBeforeRecoveryRecord.get("receipt_xid", String.class)); + .isLessThan(trace.events().indexOf(historicalReadEvent)); + assertThat(historicalReadEvent.connectionId()).isNotEqualTo(lostReceiptCommit.connectionId()); + if (historicalRead.receipt() != null) { + assertThat(trace.count("receipt-physical-commit")).isEqualTo(2); + assertHistoricalReceiptMatchesOriginal( + historicalRead.receipt(), original, decision, acknowledgement, rowBeforeRecoveryRecord); + } else { + assertThat(trace.count("receipt-physical-commit")).isEqualTo(1); + assertThat(historicalRead.walCoverageUnavailableDetail()) + .as("Historical recovery was denied because independent WAL coverage was unavailable") + .isNotBlank(); + } assertThat(originalAckReceiptRow(context, original).intoMap()).isEqualTo(rowBeforeRecovery); assertThat(operation(context, original).intoMap()).isEqualTo(operationBeforeRecovery); + assertThat(storageSnapshot(context)).isEqualTo(sourcesBeforeRecovery); assertThatThrownBy(() -> originalExecutor.execute(original, decision)) .hasMessageContaining("Fresh owned Account original COMMIT required"); assertThat(operation(context, original).intoMap()).isEqualTo(operationBeforeRecovery); + assertThat(originalAckReceiptRow(context, original).intoMap()).isEqualTo(rowBeforeRecovery); + assertThat(storageSnapshot(context)).isEqualTo(sourcesBeforeRecovery); assertThat(trace.count("original-physical-commit")).isEqualTo(1); } @Test - void concurrentOriginalAckReceiptRecoveriesRetainExactProofBeforeAndAfterExpiry() - throws Exception { + void concurrentOriginalAckReceiptReadsRequireWalCoverageBeforeAndAfterExpiry() throws Exception { var context = context(null); var original = pending(context, account(context)); UUID decision = UUID.randomUUID(); @@ -1692,48 +1681,46 @@ void concurrentOriginalAckReceiptRecoveriesRetainExactProofBeforeAndAfterExpiry( var operationBeforeRecovery = operation(context, original).intoMap(); var sourcesBeforeRecovery = storageSnapshot(context); - var receiptBeforeRecovery = originalAckReceiptRow(context, original).intoMap(); + var receiptBeforeRecoveryRecord = originalAckReceiptRow(context, original); + var receiptBeforeRecovery = receiptBeforeRecoveryRecord.intoMap(); var start = new CountDownLatch(1); - Callable duplicateRead = + Callable duplicateRead = () -> { if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); - return retrySerialization(() -> receiptExecutor.read(original, decision)); + return retrySerialization( + () -> readWithConditionalWalCoverage(receiptExecutor, original, decision)); }; - AccountGameplayAdmissionOriginalAckReceipt leftReceipt; - AccountGameplayAdmissionOriginalAckReceipt rightReceipt; + HistoricalReceiptRead leftRead; + HistoricalReceiptRead rightRead; try (var executor = Executors.newFixedThreadPool(2)) { var left = executor.submit(duplicateRead); var right = executor.submit(duplicateRead); start.countDown(); - leftReceipt = left.get(30, TimeUnit.SECONDS); - rightReceipt = right.get(30, TimeUnit.SECONDS); + leftRead = left.get(30, TimeUnit.SECONDS); + rightRead = right.get(30, TimeUnit.SECONDS); } assertThat(databaseNow(context)).isLessThan(expiresAt(original)); - assertThat(rightReceipt).isEqualTo(leftReceipt); - assertThat(leftReceipt.operation().evidence().canonicalJson()) - .isEqualTo(original.canonicalJson()); - assertThat(leftReceipt.operation().evidence().sha256()).isEqualTo(original.sha256()); - assertThat(leftReceipt.operation().bindingDecisionId()).isEqualTo(decision); - assertThat(leftReceipt.requestId()).isEqualTo(requestId(original)); - assertThat(leftReceipt.accountId()) - .isEqualTo( - UUID.fromString( - (String) ((Map) original.carrier().get("bindingScope")).get("accountId"))); - assertThat(leftReceipt.leaseId()) - .isEqualTo(UUID.fromString((String) original.carrier().get("leaseId"))); - assertThat(leftReceipt.leaseFence()).isEqualTo(original.leaseFence().longValueExact()); - assertThat(leftReceipt.evidenceSha256()).isEqualTo(original.sha256()); - assertThat(leftReceipt.bindingDecisionId()).isEqualTo(decision); - assertThat(leftReceipt.expiresAtMs()).isEqualTo(expiresAt(original)); - assertThat(leftReceipt.committedBeforeMs()) - .isEqualTo(acknowledgement.committedBeforeMs()) - .isPositive() - .isLessThan(leftReceipt.expiresAtMs()); - assertThat(leftReceipt.finalizationXid()).isEqualTo(acknowledgement.finalizationXid()); - assertThat(leftReceipt.receiptXid()) - .isEqualTo((String) receiptBeforeRecovery.get("receipt_xid")); + if (leftRead.receipt() != null) { + assertHistoricalReceiptMatchesOriginal( + leftRead.receipt(), original, decision, acknowledgement, receiptBeforeRecoveryRecord); + } else { + assertThat(leftRead.walCoverageUnavailableDetail()) + .as("First concurrent historical read was denied for unavailable WAL coverage") + .isNotBlank(); + } + if (rightRead.receipt() != null) { + assertHistoricalReceiptMatchesOriginal( + rightRead.receipt(), original, decision, acknowledgement, receiptBeforeRecoveryRecord); + } else { + assertThat(rightRead.walCoverageUnavailableDetail()) + .as("Second concurrent historical read was denied for unavailable WAL coverage") + .isNotBlank(); + } + if (leftRead.receipt() != null && rightRead.receipt() != null) { + assertThat(rightRead.receipt()).isEqualTo(leftRead.receipt()); + } assertThat(trace.count("original-physical-commit")).isEqualTo(1); assertThat(trace.count("receipt-durable-read")).isGreaterThanOrEqualTo(2); assertThat(trace.count("receipt-exact-read")).isZero(); @@ -1748,12 +1735,19 @@ void concurrentOriginalAckReceiptRecoveriesRetainExactProofBeforeAndAfterExpiry( // The V122 receipt is immutable historical proof; expiry does not restamp or renew it. waitPastDeadline(context, original); - var recoveredAfterExpiry = receiptExecutor.read(original, decision); - assertThat(recoveredAfterExpiry).isEqualTo(leftReceipt); - assertThat(recoveredAfterExpiry.expiresAtMs()).isEqualTo(expiresAt(original)); - assertThat(recoveredAfterExpiry.committedBeforeMs()) - .isEqualTo(acknowledgement.committedBeforeMs()) - .isLessThan(expiresAt(original)); + var readAfterExpiry = readWithConditionalWalCoverage(receiptExecutor, original, decision); + if (readAfterExpiry.receipt() != null) { + assertHistoricalReceiptMatchesOriginal( + readAfterExpiry.receipt(), + original, + decision, + acknowledgement, + receiptBeforeRecoveryRecord); + } else { + assertThat(readAfterExpiry.walCoverageUnavailableDetail()) + .as("Historical read after expiry was denied for unavailable WAL coverage") + .isNotBlank(); + } assertThat(trace.count("original-physical-commit")).isEqualTo(1); assertThat(trace.count("receipt-durable-read")).isGreaterThanOrEqualTo(3); assertThat( @@ -1771,6 +1765,91 @@ void concurrentOriginalAckReceiptRecoveriesRetainExactProofBeforeAndAfterExpiry( assertThat(storageSnapshot(context)).isEqualTo(sourcesBeforeRecovery); } + private record HistoricalReceiptRead( + AccountGameplayAdmissionOriginalAckReceipt receipt, String walCoverageUnavailableDetail) {} + + /** Returns an exact historical proof only when the native reader proves its WAL coverage. */ + private static HistoricalReceiptRead readWithConditionalWalCoverage( + AccountGameplayAdmissionOriginalAckReceiptCommitExecutor executor, + AccountGameplayAdmissionLeaseEvidence original, + UUID decision) { + try { + return new HistoricalReceiptRead(executor.read(original, decision), null); + } catch (RuntimeException failure) { + PSQLException postgresFailure = null; + Throwable cause = failure; + var visited = + java.util.Collections.newSetFromMap(new java.util.IdentityHashMap()); + while (cause != null && visited.add(cause)) { + if (cause instanceof PSQLException candidate) { + postgresFailure = candidate; + break; + } + cause = cause.getCause(); + } + if (postgresFailure == null || !"23514".equals(postgresFailure.getSQLState())) { + throw failure; + } + + var serverError = postgresFailure.getServerErrorMessage(); + if (serverError == null + || !"account_admission_original_ack_receipt_wal_coverage" + .equals(serverError.getConstraint()) + || postgresFailure.getMessage() == null + || !postgresFailure + .getMessage() + .contains("Original Account acknowledgement receipt WAL coverage unavailable")) { + throw failure; + } + String detail = serverError.getDetail(); + assertThat(detail) + .contains("insert_fence=") + .contains("initial_flush=") + .contains("final_flush=") + .contains("unchanged_expiry_ms="); + return new HistoricalReceiptRead(null, detail); + } + } + + private static void assertHistoricalReceiptMatchesOriginal( + AccountGameplayAdmissionOriginalAckReceipt receipt, + AccountGameplayAdmissionLeaseEvidence original, + UUID decision, + AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement acknowledgement, + Record storedReceipt) { + assertThat(receipt.operation().evidence().canonicalJson()).isEqualTo(original.canonicalJson()); + assertThat(receipt.operation().evidence().sha256()).isEqualTo(original.sha256()); + assertThat(receipt.operation().bindingDecisionId()).isEqualTo(decision); + assertThat(receipt.schemaVersion()).isEqualTo(storedReceipt.get("schema_version", Short.class)); + assertThat(receipt.requestId()).isEqualTo(requestId(original)); + var scope = (Map) original.carrier().get("bindingScope"); + assertThat(receipt.accountId()) + .isEqualTo(UUID.fromString((String) scope.get("accountId"))) + .isEqualTo(storedReceipt.get("account_uuid", UUID.class)); + assertThat(receipt.leaseId()) + .isEqualTo(UUID.fromString((String) original.carrier().get("leaseId"))) + .isEqualTo(storedReceipt.get("lease_id", UUID.class)); + assertThat(receipt.leaseFence()) + .isEqualTo(original.leaseFence().longValueExact()) + .isEqualTo(storedReceipt.get("lease_fence", Long.class)); + assertThat(receipt.evidenceSha256()).isEqualTo(original.sha256()); + assertThat(receipt.bindingDecisionId()).isEqualTo(decision); + assertThat(receipt.expiresAtMs()) + .isEqualTo(expiresAt(original)) + .isEqualTo(storedReceipt.get("expires_at_ms", Long.class)); + assertThat(receipt.committedBeforeMs()) + .isEqualTo(storedReceipt.get("committed_before_ms", Long.class)) + .isPositive() + .isLessThan(receipt.expiresAtMs()); + assertThat(receipt.committedBeforeMs()).isEqualTo(acknowledgement.committedBeforeMs()); + assertThat(receipt.finalizationXid()) + .isEqualTo(storedReceipt.get("finalization_xid", String.class)) + .isEqualTo(acknowledgement.finalizationXid()); + assertThat(receipt.receiptXid()) + .isEqualTo(storedReceipt.get("receipt_xid", String.class)) + .isNotEqualTo(receipt.finalizationXid()); + } + private static Record originalAckReceiptRow( Context context, AccountGameplayAdmissionLeaseEvidence original) { return Objects.requireNonNull( diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index 6ba6d1c5f4..b50781ccc9 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -26,6 +26,14 @@ testing { dependencies { integrationTestImplementation(project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof"))) integrationTestImplementation(project(mapOf("path" to ":game-logic-service", "configuration" to "gameLogicClassesProof"))) + integrationTestImplementation( + project( + mapOf( + "path" to ":game-session-service", + "configuration" to "gameSessionClassesProof" + ) + ) + ) integrationTestImplementation( project( mapOf( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 0cbf95860d..4212c30f64 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -18,7 +18,6 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.lang.reflect.Method; import java.net.InetSocketAddress; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -43,9 +42,12 @@ import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerAttemptLifecycle; +import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerClaim; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeTerminalReadService; @@ -63,6 +65,7 @@ import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationAcquisitionClient; import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; @@ -110,8 +113,7 @@ import net.firedevops.firemud.common.gamelogic.GrpcGameLogicIntakeSourceReadClient; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; -import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; -import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.gamesession.GrpcOriginalStartSessionCurrentAttemptClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -251,6 +253,10 @@ import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadGrpcService; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadService; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadGrpcService; import net.firedevops.firemud.test.TestContainerImages; import net.firedevops.firemud.worldmanagement.tenant.GenuineWorldSelectedPublicationProofFactory; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; @@ -263,9 +269,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; -import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceExecutionIdentity; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; -import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationAssemblyService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository; @@ -281,6 +285,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplicationService; import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplyGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldSelectedOwnerInventoryReadProofFixture; +import net.firedevops.firemud.worldmanagement.tenant.WorldStartSessionAccountParticipationVerifier; import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; @@ -361,12 +366,14 @@ * Management mTLS client on this fixture's loopback server to the actual owner implementation in an * explicitly established read-only repeatable-read snapshot; unrelated handler dependencies are * isolated. The World preparation composition reuses the genuine persisted source, frozen graph, - * and complete released pair through actual World owner services and Game Session mTLS, but its - * Game Session launch association and continuous held-Account/Game-Session commit authority are - * explicitly stipulated; the supplied Game Session attempt/fence is not independently proven. This - * does not establish production-authenticated Logging claims, Game Session admission, or launch - * authorization. The fixture does not provide production-mounted certificates or full application - * server wiring, production ingress, runtime launch, activation or registration. + * and complete released pair through actual World owner services. Its original Account tuple is + * issued and redeemed by the real Account owner under stipulated Logging claim and peer contexts; + * Game Session reserves that exact tuple in an isolated V35 store and attaches the exact redeemed + * projection. Account's current-attempt observation and World participation acquisition use their + * native same-namespace mTLS clients and receivers. Game Session launch association remains mocked, + * and Account participation is point-in-time evidence, not a continuous cross-service lock. This + * does not establish production-authenticated Logging claims, full application server wiring, + * production ingress, runtime launch, activation or registration. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -421,6 +428,10 @@ class GenuineSelectedPublicationExportPostgresIntegrationTest { private static final PostgreSQLContainer ACCOUNT_POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container + private static final PostgreSQLContainer GAME_SESSION_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container private static final PostgreSQLContainer GAME_LOGIC_POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); @@ -481,6 +492,7 @@ void closeMinioClient() { void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Exception { var gd = gameDesignStore(); var world = serviceStore(WORLD_POSTGRES, "world-management"); + var gameSessionAttempts = gameSessionAttemptStore(); var gameLogic = serviceStore(GAME_LOGIC_POSTGRES, "game-logic"); var automation = serviceStore(GAME_LOGIC_POSTGRES, "automation-scripting"); var entity = serviceStore(ENTITY_POSTGRES, "entity-management"); @@ -488,33 +500,69 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var gdHandlers = new MutableHandlerRegistry(); var worldHandlers = new MutableHandlerRegistry(); var accountHandlers = new MutableHandlerRegistry(); + var gameSessionHandlers = new MutableHandlerRegistry(); var gameLogicHandlers = new MutableHandlerRegistry(); var automationHandlers = new MutableHandlerRegistry(); var entityHandlers = new MutableHandlerRegistry(); + register( + gameSessionHandlers, + new OriginalStartSessionCurrentAttemptReadGrpcService( + gameSessionAttempts.repository(), gameSessionAttempts.transactionManager(), NAMESPACE)); + Server gdServer = startServer(pki, "game-design-service", gdHandlers); Server worldServer = startServer(pki, "world-management-service", worldHandlers); Server accountServer = startServer(pki, "account-service", accountHandlers); + Server gameSessionServer = startServer(pki, "game-session-service", gameSessionHandlers); Server gameLogicServer = startServer(pki, "game-logic-service", gameLogicHandlers); Server automationServer = startServer(pki, "automation-scripting-service", automationHandlers); Server entityServer = startServer(pki, "entity-management-service", entityHandlers); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService(loopback(accountServer)); + endpoints.setGameDesignService(loopback(gdServer)); + endpoints.setWorldManagementService(loopback(worldServer)); + endpoints.setGameSessionService(loopback(gameSessionServer)); + endpoints.setGameLogicService(loopback(gameLogicServer)); + endpoints.setAutomationScriptingService(loopback(automationServer)); + endpoints.setEntityManagementService(loopback(entityServer)); + var channels = new GrpcChannelFactory(); try (var account = - new AccountControlUiOriginalOrderFixture( - ACCOUNT_POSTGRES.getJdbcUrl(), - ACCOUNT_POSTGRES.getUsername(), - ACCOUNT_POSTGRES.getPassword(), - REDIS.getHost(), - REDIS.getMappedPort(6379), - temporary.resolve("account"), - gd.target().canonicalTenantId())) { - var endpoints = new ServiceEndpointsProperties(); - endpoints.setAccountService(loopback(accountServer)); - endpoints.setGameDesignService(loopback(gdServer)); - endpoints.setWorldManagementService(loopback(worldServer)); - endpoints.setGameLogicService(loopback(gameLogicServer)); - endpoints.setAutomationScriptingService(loopback(automationServer)); - endpoints.setEntityManagementService(loopback(entityServer)); - var channels = new GrpcChannelFactory(); + new AccountControlUiOriginalOrderFixture( + ACCOUNT_POSTGRES.getJdbcUrl(), + ACCOUNT_POSTGRES.getUsername(), + ACCOUNT_POSTGRES.getPassword(), + REDIS.getHost(), + REDIS.getMappedPort(6379), + temporary.resolve("account"), + gd.target().canonicalTenantId()); + var accountToGameSessionCurrentAttemptClient = + new GrpcOriginalStartSessionCurrentAttemptClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var worldToAccountParticipationClient = + new AccountStartSessionWorldParticipationAcquisitionClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var projectionClient = + new StartSessionRedeemedOperationProjectionClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var wrongWorkloadPreparationClient = + new CanonicalWorldInstancePreparationClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var gameSessionPreparationClient = + new CanonicalWorldInstancePreparationClient( + endpoints, pki.client("game-session-service"), channels, NAMESPACE); + var gameSessionPreparationRetryClient = + new CanonicalWorldInstancePreparationClient( + endpoints, pki.client("game-session-service"), channels, NAMESPACE); + var wrongWorkloadActivationClient = + canonicalActivationClient(worldServer, pki.client("account-service"), channels); + var gameSessionActivationClient = + canonicalActivationClient(worldServer, pki.client("game-session-service"), channels)) { + accountToGameSessionCurrentAttemptClient.init(); + worldToAccountParticipationClient.init(); + projectionClient.init(); + wrongWorkloadPreparationClient.init(); + gameSessionPreparationClient.init(); + gameSessionPreparationRetryClient.init(); var automationIntakeRepository = new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); var entityIntakeRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); @@ -937,6 +985,16 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new AccountOriginalStartSessionAuthorizationProofFixture( account, temporary.resolve("account-start-session-authorization-proof"), NAMESPACE); register(accountHandlers, startSessionAuthorizationProof.grpcService()); + var accountWorldParticipationAcquisitionService = + startSessionAuthorizationProof.worldParticipationAcquisitionService( + accountToGameSessionCurrentAttemptClient); + register( + accountHandlers, + new AccountStartSessionWorldParticipationAcquisitionGrpcService( + accountWorldParticipationAcquisitionService, NAMESPACE)); + var worldParticipationVerifier = + new WorldStartSessionAccountParticipationVerifier( + NAMESPACE, worldToAccountParticipationClient); var glOwner = new GameLogicGameplayRuleIntakeService( @@ -2676,8 +2734,6 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex publicationRequest.derivedWorkflowIdentity(), association.digest()); String controlPlaneRequestId = "genuine-start-session-" + UUID.randomUUID(); - UUID ownerAttemptId = UUID.randomUUID(); - long ownerFence = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); UUID reservationOwnerId = UUID.randomUUID(); long reservationClaimFence = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); var originalStartSessionAction = @@ -2691,28 +2747,65 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new StartSessionOperatorAction.Mutation( StartSessionOperatorAction.ClientIp.absent()), "Genuine selected descriptor storage proof"); + AtomicReference reservedOwnerAttempt = new AtomicReference<>(); + AtomicReference reservedTupleBytes = new AtomicReference<>(); var originalStartSession = startSessionAuthorizationProof.issueAndRedeemOriginal( controlPlaneRequestId, originalStartSessionAction, reservationOwnerId, reservationClaimFence, - ownerAttemptId, - ownerFence); + new OwnerAttemptLifecycle() { + @Override + public OwnerClaim reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + AttemptClaim claim = gameSessionAttempts.reserve(tuple); + reservedOwnerAttempt.set(claim); + reservedTupleBytes.set(tuple.canonicalBytes()); + return new OwnerClaim( + claim.ownerAttemptId(), claim.ownerMutationId(), claim.ownerFence()); + } + + @Override + public void attachAccountRedemptionProjection( + OwnerClaim ownerClaim, StartSessionPostAuthorizationExecutionTuple tuple) { + AttemptClaim claim = + Objects.requireNonNull( + reservedOwnerAttempt.get(), + "Exact Game Session reservation must precede Account redemption"); + assertThat(ownerClaim.ownerAttemptId()).isEqualTo(claim.ownerAttemptId()); + assertThat(ownerClaim.ownerMutationId()).isEqualTo(claim.ownerMutationId()); + assertThat(ownerClaim.ownerFence()).isEqualTo(claim.ownerFence()); + assertThat(tuple.canonicalBytes()).containsExactly(reservedTupleBytes.get()); + var authority = + StartSessionAuthorityEvidenceBundle.decode( + tuple.authorityEvidenceBundleBytes()); + var projection = + new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence())); + assertThat(projection.canonicalBytes()) + .containsExactly( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); + var attached = gameSessionAttempts.attach(claim, projection); + assertThat(attached.accountRedemptionProjection()) + .containsExactly(projection.canonicalBytes()); + } + }); var startSessionTuple = originalStartSession.originalTuple(); - UUID stipulatedOwnerMutationId = UUID.randomUUID(); - UUID stipulatedOwnerReadRequestId = UUID.randomUUID(); - Instant stipulatedOwnerLeaseExpiry = Instant.now().plusSeconds(900L); - OriginalOperationInput stipulatedOwnerOperation = + AttemptClaim ownerAttemptClaim = + Objects.requireNonNull(reservedOwnerAttempt.get(), "Actual Game Session owner claim"); + UUID ownerAttemptId = ownerAttemptClaim.ownerAttemptId(); + UUID ownerMutationId = ownerAttemptClaim.ownerMutationId(); + long ownerFence = ownerAttemptClaim.ownerFence(); + assertThat(originalStartSession.gameSessionOwnerAttemptId()).isEqualTo(ownerAttemptId); + assertThat(originalStartSession.gameSessionOwnerFence()).isEqualTo(ownerFence); + assertThat(startSessionTuple.canonicalBytes()).containsExactly(reservedTupleBytes.get()); + OriginalOperationInput originalOwnerOperation = new OriginalOperationInput( - startSessionTuple.canonicalBytes(), - stipulatedOwnerMutationId, - ownerAttemptId, - ownerFence); - try (var projectionClient = - new StartSessionRedeemedOperationProjectionClient( - endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { - projectionClient.init(); + startSessionTuple.canonicalBytes(), ownerMutationId, ownerAttemptId, ownerFence); + { var accountProjection = projectionClient.read(startSessionTuple, ownerAttemptId, ownerFence); assertThat(accountProjection.getControlPlaneRequestId()).isEqualTo(controlPlaneRequestId); @@ -3021,10 +3114,12 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex .containsExactlyElementsOf(completeBindingOwnerRowsBefore); // World source, publication and released-pair proof above is genuine. The original - // StartSession tuple and issued owner attempt/fence below are genuine Account - // issue/redemption evidence; the later exact Game Session mutation observation and - // Account participation are stipulated and do not prove acquisition or a continuous - // remote lock. + // StartSession tuple is issued/redempted by Account under the fixture's stipulated + // Logging claim and peer contexts. Game Session reserves the exact tuple and attaches + // Account's redeemed projection in its isolated V35 repository; Account's current + // attempt observation and World participation acquisition then traverse native + // same-namespace mTLS receivers. Launch association below remains mocked, and retained + // participation is point-in-time evidence, not a continuous remote lock. CompleteLaunchBindingEvidence completeLaunchEvidence = new CompleteLaunchBindingEvidence( completeBinding.descriptor(), completeBinding.releaseAttestation()); @@ -3097,96 +3192,9 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex worldPublicationProof.frozenTopologies(), stipulatedGameSessionReader, worldToGameDesignPreparationClient); - // Preserve the exact original tuple and issued Game Session attempt/fence. The owner - // mutation/current-attempt observation and Account participation are explicit - // synthetic downstream evidence; this remains a genuine publication/source/release - // proof, not genuine Account participation acquisition or continuous owner protection. - var syntheticIdentities = - new ConcurrentHashMap(); - UUID stipulatedParticipationId = UUID.randomUUID(); - long stipulatedParticipationFence = - ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); - var stipulatedHeldAuthority = - (WorldCanonicalInstancePreparationService.OriginalOperationCommitAuthorityVerifier) - (input, operationInput) -> { - if (!MessageDigest.isEqual( - startSessionTuple.canonicalBytes(), - operationInput.originalPostAuthorizationTuple()) - || !stipulatedOwnerMutationId.equals( - operationInput.gameSessionOwnerMutationId()) - || !ownerAttemptId.equals(operationInput.gameSessionOwnerAttemptId()) - || ownerFence != operationInput.gameSessionOwnerFence()) { - throw new SecurityException( - "Synthetic downstream operation differs from genuine issued StartSession evidence"); - } - String exactInputJson; - try { - exactInputJson = canonicalPreparationInputJson(input); - } catch (ReflectiveOperationException failure) { - throw new IllegalStateException( - "Could not reuse the canonical World preparation input serializer", - failure); - } - WorldCanonicalInstanceExecutionIdentity identity = - syntheticIdentities.computeIfAbsent( - exactInputJson, - ignored -> { - var observationRequest = - new OriginalStartSessionCurrentAttemptEvidence.Request( - stipulatedOwnerReadRequestId, - NAMESPACE, - startSessionTuple.canonicalBytes(), - ownerAttemptId, - stipulatedOwnerMutationId, - ownerFence); - var observation = - new OriginalStartSessionCurrentAttemptEvidence.Result( - observationRequest, - stipulatedOwnerLeaseExpiry, - StartSessionAccountRedemptionProjection.fromOriginalTuple( - startSessionTuple)); - byte[] observationBytes = - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( - observation) - .toByteArray(); - return new WorldCanonicalInstanceExecutionIdentity( - startSessionTuple.canonicalBytes(), - stipulatedParticipationId, - stipulatedParticipationFence, - stipulatedOwnerMutationId, - ownerAttemptId, - ownerFence, - observation, - input.canonicalGameInstanceId(), - exactInputJson, - observationBytes); - }); - identity.requireMatches(input, operationInput, exactInputJson); - return new WorldCanonicalInstancePreparationService.HeldCommitAuthority() { - private boolean held = true; - - @Override - public void requireHeld() { - if (!held) { - throw new SecurityException( - "Synthetic StartSession proof handle was released"); - } - } - - @Override - public WorldCanonicalInstanceExecutionIdentity executionIdentity() { - return identity; - } - - @Override - public void close() { - held = false; - } - }; - }; var preparationService = new WorldCanonicalInstancePreparationService( - preparationRepository, stipulatedHeldAuthority); + preparationRepository, worldParticipationVerifier); register( worldHandlers, new WorldCanonicalInstancePreparationGrpcService( @@ -3212,15 +3220,12 @@ public void close() { canonicalGameInstanceId, completeWorldSelector.request().publicationFence()); var rowsBeforeWrongPeer = canonicalPreparationRowCounts(world.dsl()); - try (var wrongWorkloadPreparationClient = - new CanonicalWorldInstancePreparationClient( - endpoints, pki.client("account-service"), channels, NAMESPACE)) { - wrongWorkloadPreparationClient.init(); + { assertThatThrownBy( () -> wrongWorkloadPreparationClient.prepare( preparationAssociationRequest, - stipulatedOwnerOperation, + originalOwnerOperation, expectedLifecycleRequest)) .isInstanceOf(io.grpc.StatusRuntimeException.class) .satisfies( @@ -3242,14 +3247,11 @@ public void close() { .isEqualTo(sourceRowsBeforePreparation); WorldCanonicalInstanceLifecycleEvidence preparedLifecycle; - try (var gameSessionPreparationClient = - new CanonicalWorldInstancePreparationClient( - endpoints, pki.client("game-session-service"), channels, NAMESPACE)) { - gameSessionPreparationClient.init(); + { preparedLifecycle = gameSessionPreparationClient.prepare( preparationAssociationRequest, - stipulatedOwnerOperation, + originalOwnerOperation, expectedLifecycleRequest); } @@ -3340,14 +3342,11 @@ public void close() { .isNotNull(); assertThat(retainedOwnerEvidenceAfterPreparation.get("worldInstance")).isNotNull(); - try (var gameSessionPreparationRetryClient = - new CanonicalWorldInstancePreparationClient( - endpoints, pki.client("game-session-service"), channels, NAMESPACE)) { - gameSessionPreparationRetryClient.init(); + { assertThat( gameSessionPreparationRetryClient.prepare( preparationAssociationRequest, - stipulatedOwnerOperation, + originalOwnerOperation, expectedLifecycleRequest)) .isEqualTo(preparedLifecycle); } @@ -3420,7 +3419,7 @@ public void close() { () -> defaultDeniedClient.prepare( preparationAssociationRequest, - stipulatedOwnerOperation, + originalOwnerOperation, expectedLifecycleRequest)) .isInstanceOf(io.grpc.StatusRuntimeException.class) .satisfies( @@ -3555,8 +3554,7 @@ public void close() { assertThat(lifecycleRepository.read(expectedLifecycleRequest).orElseThrow()) .isEqualTo(preparedLifecycle); - try (var wrongWorkloadActivationClient = - canonicalActivationClient(worldServer, pki.client("account-service"), channels)) { + { assertThatThrownBy( () -> wrongWorkloadActivationClient.activate( @@ -3632,9 +3630,7 @@ public void close() { // This explicitly stipulates current producer authority and its operation-specific // held handle. The fixture's STARTING evidence is the existing mocked Game Session // association, not a current owner read or continuous Account/GS protection. - try (var gameSessionActivationClient = - canonicalActivationClient( - worldServer, pki.client("game-session-service"), channels)) { + { var firstActivationResponse = gameSessionActivationClient.activate( canonicalActivationTransportRequest(activationRequest)); @@ -3898,7 +3894,13 @@ public void close() { } } finally { stopAll( - automationServer, entityServer, gameLogicServer, accountServer, worldServer, gdServer); + automationServer, + entityServer, + gameLogicServer, + gameSessionServer, + accountServer, + worldServer, + gdServer); } } @@ -4037,15 +4039,6 @@ private static CanonicalActivationTransportClient canonicalActivationClient( return new CanonicalActivationTransportClient(channel, stub); } - private static String canonicalPreparationInputJson(WorldCanonicalInstancePreparation.Input input) - throws ReflectiveOperationException { - Method serializer = - WorldCanonicalInstancePreparationRepository.class.getDeclaredMethod( - "inputJson", WorldCanonicalInstancePreparation.Input.class); - serializer.setAccessible(true); - return (String) serializer.invoke(null, input); - } - private static Map canonicalPreparationRowCounts(DSLContext dsl) { Map counts = new TreeMap<>(); for (String table : @@ -4601,6 +4594,40 @@ private static List selectedOwnerReservationSourceRows(DSLContext dsl, U + HexFormat.of().formatHex(row.get("source_evidence", byte[].class))); } + private static GameSessionAttemptStore gameSessionAttemptStore() { + String schema = + "genuine_selected_game_session_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(GAME_SESSION_POSTGRES.getJdbcUrl()); + dataSource.setUsername(GAME_SESSION_POSTGRES.getUsername()); + dataSource.setPassword(GAME_SESSION_POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_game_session") + .locations(migrationLocation("game-session")) + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var v35Migration = + dsl.fetchOne( + "SELECT version FROM flyway_schema_history_game_session " + + "WHERE success AND version = '35'"); + assertThat(v35Migration).isNotNull(); + + var transactionManager = new DataSourceTransactionManager(dataSource); + return new GameSessionAttemptStore( + dsl, + transactionManager, + new TransactionTemplate(transactionManager), + new GameSessionStartSessionOperatorAttemptRepository(dsl, Duration.ofSeconds(30))); + } + private static Store serviceStore(PostgreSQLContainer postgres, String service) { var schema = service.replace('-', '_') + "_" + UUID.randomUUID().toString().replace("-", ""); var data = @@ -5149,6 +5176,34 @@ private static List completeBindingOwnerRowVersions( .get(0, String.class)); } + private record GameSessionAttemptStore( + DSLContext dsl, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + GameSessionStartSessionOperatorAttemptRepository repository) { + AttemptClaim reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + var reservation = + Objects.requireNonNull( + transactions.execute(status -> repository.reserve(tuple)), + "Game Session owner attempt reservation result"); + assertThat(reservation.disposition()) + .isEqualTo( + GameSessionStartSessionOperatorAttemptRepository.ReservationDisposition + .CLAIM_CREATED); + assertThat(reservation.snapshot().postAuthorizationExecutionTuple()) + .containsExactly(tuple.canonicalBytes()); + return reservation.claim().orElseThrow(); + } + + GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot attach( + AttemptClaim claim, AccountRedemptionProjection projection) { + return Objects.requireNonNull( + transactions.execute( + status -> repository.attachAccountRedemptionProjection(claim, projection)), + "Game Session redeemed-projection attachment snapshot"); + } + } + private record Store( DSLContext dsl, DataSourceTransactionManager transactions, From 4b87d3161ae1b13114db3586d3b9df16218773cc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 11:12:49 +1300 Subject: [PATCH 100/129] Retain exact authenticated fresh tenant receipt in Game Session owner association --- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 2 + .../GameDesignFreshTenantCreationClient.java | 184 +++++++ ...ssionFreshTenantAssociationRepository.java | 520 ++++++++++++++++++ ...resh_tenant_complete_creation_evidence.sql | 71 +++ ...calGameplayBindingRuntimeTestFixtures.java | 52 +- ...antAssociationPostgresIntegrationTest.java | 389 +++++++++++++ ...meDesignFreshTenantCreationClientTest.java | 335 +++++++++++ ...nFreshTenantAssociationRepositoryTest.java | 109 ++++ 9 files changed, 1665 insertions(+), 3 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V41__fresh_tenant_complete_creation_evidence.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationPostgresIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index f43937d2fa..fbfecf01d0 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -228,3 +228,9 @@ Entry format: - Observation: Revision protection prevented concurrent overwrite but did not prove preservation of the supplied text. A minimal `a—## h` example reproduces the local jq behavior: `index("##")` returns byte offset 4, while slicing from 4 uses character positions and drops both heading characters. The decision paragraph and historical tail remained present. - Expected pattern: Prefer exact string replacement or splitting at a verified delimiter, then read back both the new checkpoint and retained standing instructions rather than relying on the revision guard alone. - Current status: The heading was repaired through a second guarded revision and verified present. No standing decision or implementation authorization changed. + +- `2026-10-11`: Isolate a silent static-check failure before changing unrelated callers + - Context: A new test channel's no-op `shutdownNow` implementation made SpotBugs report no-effect calls in several existing client tests. After correcting the channel's shutdown state, the production-code task still failed without a visible finding in the ordinary combined output. + - Observation: The isolated owning `spotbugsMain` task with `--info` exposed an unnecessary constructor suppression, rather than another runtime defect. Passing test XML did not make the aggregate validation successful. + - Expected pattern: Keep the existing assertions and static rules; recover the owning task's diagnostic before editing unrelated callers or adding suppressions. Report test execution and aggregate-gate status separately. + - Current status: The channel fixture and unnecessary suppression are corrected, and the canonical Game Session gate passed. Physical PostgreSQL cases remain a separate proof requirement. 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 c2c33cdd2e..df46319336 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 @@ -304,6 +304,8 @@ Official-hosted creator-content acceptance remains partial under [ADR 0180](../. 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. +The unregistered Game Session fresh-tenant composition now reads that exact Game Design receipt before SQL, atomically allocates its own numeric scope and immutable claim/association, and independently reads back the complete committed evidence. Additive V41 retains the full source receipt, including Game Design's distinct operation and request/evidence digests; older partial V25 rows remain unchanged and nonqualifying. Defined storage cases cover exact retry, changed receipt, retained-claim denial, concurrent duplicates, rollback and incomplete-history denial. They mock the Game Design client and do not prove authenticated producer-to-consumer composition. The recipient's complete canonical catalog, published-policy intake and STARTING launch association remain separate open construction obligations; this primitive grants no gameplay admission or runtime activation. + The adjacent authored-world source read now has an exact same-namespace World Management peer guard, closed request decoding, owner-local read of the retained operation, complete receipt/digest validation, and explicit Game Design auth-bypass wiring. Executed unit checks cover allowed and denied peers, caller-context denial, malformed/unknown fields, missing or substituted source, corrupt evidence and unavailable storage; Common client/codec checks cover exact echo and corruption denial. Corrected-state Common/Game Design checks pass locally, but PostgreSQL cases skip without Docker. No genuine end-to-end source registration, World intake, publication provenance, runtime registration, or activation proof is claimed. The canonical owner detail is in [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#authored-world-source-readback); World’s local consequence is in [World Management API contracts](../../architecture/microservices/world-management-service/api-contracts.md#implementation-status). ### Script and plugin transition reconciliation diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClient.java new file mode 100644 index 0000000000..9157338eed --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClient.java @@ -0,0 +1,184 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ClientInterceptors; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.UUID; +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.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered Game Session workload client for exact Game Design fresh-creation readback. */ +public final class GameDesignFreshTenantCreationClient + extends AbstractReloadingBlockingGrpcClient< + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final String workloadNamespace; + private final GrpcServerPeerIdentityClientInterceptor serverPeerIdentityInterceptor; + + public GameDesignFreshTenantCreationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireGameSessionMtls(tlsProperties), + channelFactory, + GameDesignFreshTenantCreationClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.serverPeerIdentityInterceptor = + new GrpcServerPeerIdentityClientInterceptor(gameDesignServerPeerUri(workloadNamespace)); + } + + /** Initializes this client only when the owning Game Session composition explicitly uses it. */ + public void init() throws SSLException, IOException { + initReloadingClient(); + } + + @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) { + return TenantIdentityServiceGrpc.newBlockingStub( + ClientInterceptors.intercept(channel, serverPeerIdentityInterceptor)) + .withCompression("gzip"); + } + + /** + * Reads one immutable receipt from Game Design without opening or joining a Game Session SQL + * transaction. Game Design independently admits only the same-namespace Game Session mTLS peer. + */ + public FreshTenantCreationEvidence resolveCreation( + UUID creationRequestId, String expectedRequestDigest) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Design fresh-tenant evidence must be resolved outside a Game Session transaction"); + } + if (creationRequestId == null || NIL_UUID.equals(creationRequestId)) { + throw new IllegalArgumentException("Canonical nonnil creation request ID is required"); + } + if (!GameTenantCreationDigest.isDigest(expectedRequestDigest)) { + throw new IllegalArgumentException("Canonical expected request digest is required"); + } + + ResolveFreshTenantCreationResponse response = + stub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveFreshTenantCreation( + ResolveFreshTenantCreationRequest.newBuilder() + .setCreationRequestId(creationRequestId.toString()) + .setExpectedRequestDigest(expectedRequestDigest) + .build()); + if (!response.getUnknownFields().asMap().isEmpty()) { + throw invalidOwnerEvidence("Game Design fresh tenant evidence contains unknown fields"); + } + + FreshTenantCreationEvidence evidence; + try { + evidence = + new FreshTenantCreationEvidence( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getCreationRequestId()), + parseCanonicalNonNilUuid(response.getOperationId()), + response.getRequestDigest(), + parseCanonicalNonNilUuid(response.getCanonicalTenantId()), + response.getSourceGameRowId(), + response.getSourceGameTenantKey(), + response.getProvenanceKind(), + response.getEvidenceDigest()); + } catch (IllegalArgumentException exception) { + throw invalidOwnerEvidence("Game Design fresh tenant evidence is invalid", exception); + } + + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !creationRequestId.equals(evidence.creationRequestId()) + || !expectedRequestDigest.equals(evidence.requestDigest())) { + throw invalidOwnerEvidence( + "Game Design fresh tenant evidence differs from the exact request"); + } + return evidence; + } + + private static String gameDesignServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/game-design-service"; + } + + private static UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + throw new IllegalArgumentException("UUID evidence is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("UUID evidence must be canonical lowercase", exception); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("UUID evidence must be canonical and nonnil"); + } + return parsed; + } + + private static IllegalStateException invalidOwnerEvidence(String message) { + return new IllegalStateException(message); + } + + private static IllegalStateException invalidOwnerEvidence(String message, Throwable cause) { + return new IllegalStateException(message, cause); + } + + private static CommonGrpcClientProperties requireGameSessionMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null) { + throw new IllegalArgumentException("Game Session gRPC TLS configuration is required"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Fresh tenant identity reads require Game Session workload mTLS"); + } + if (!hasText(tlsProperties.getCertChain()) + || !hasText(tlsProperties.getPrivateKey()) + || !hasText(tlsProperties.getCaCert())) { + throw new IllegalArgumentException( + "Fresh tenant identity reads require Game Session certificate, key, and CA files"); + } + if (tlsProperties.getCertChain().trim().startsWith("classpath:") + || tlsProperties.getPrivateKey().trim().startsWith("classpath:") + || tlsProperties.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Fresh tenant identity reads require file-backed Game Session workload mTLS"); + } + return tlsProperties; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java new file mode 100644 index 0000000000..201422ae38 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java @@ -0,0 +1,520 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Game Session owner composition for importing one exact fresh Game Design tenant + * receipt into the numeric tenant scope. It reads the remote owner before SQL and independently + * reads the committed immutable association after the write transaction. + */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Trusted internal client, DSL context, and transaction manager are retained privately.") +public final class GameSessionFreshTenantAssociationRepository { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Set EVIDENCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final String ASSOCIATION_SELECT = + "SELECT fresh.target_namespace, fresh.association_request_id, " + + "fresh.source_schema_version, fresh.source_target_namespace, " + + "fresh.source_request_id, fresh.source_canonical_tenant_id, " + + "fresh.canonical_tenant_id, fresh.legacy_game_session_tenant_id, " + + "fresh.source_game_row_id, fresh.source_game_tenant_key, fresh.provenance_kind, " + + "fresh.association_kind, fresh.association_operation_id, " + + "fresh.complete_source_evidence::text AS complete_source_evidence, " + + "claim.target_namespace AS claim_namespace, " + + "claim.canonical_tenant_id AS claim_canonical_tenant_id, " + + "claim.legacy_game_session_tenant_id AS claim_tenant_id, " + + "claim.association_kind AS claim_kind, " + + "claim.reservation_kind AS claim_reservation_kind, " + + "claim.association_operation_id AS claim_operation_id, " + + "claim.association_request_id AS claim_request_id, " + + "reservation.reservation_kind AS reservation_kind " + + "FROM game_session_fresh_tenant_association fresh " + + "LEFT JOIN game_session_tenant_canonical_claim claim " + + "ON claim.target_namespace = fresh.target_namespace " + + "AND claim.canonical_tenant_id = fresh.canonical_tenant_id " + + "LEFT JOIN game_session_tenant_scope_reservation reservation " + + "ON reservation.game_session_tenant_id = fresh.legacy_game_session_tenant_id "; + + private final DSLContext dsl; + private final GameDesignFreshTenantCreationClient gameDesignClient; + private final String workloadNamespace; + private final TransactionTemplate writeTransaction; + private final TransactionTemplate readTransaction; + + public GameSessionFreshTenantAssociationRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + GameDesignFreshTenantCreationClient gameDesignClient, + String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is missing or invalid"); + } + this.workloadNamespace = workloadNamespace; + this.writeTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + this.readTransaction = new TransactionTemplate(transactionManager); + this.readTransaction.setReadOnly(true); + } + + /** + * Resolves the exact authenticated Game Design receipt outside SQL, atomically claims a new Game + * Session numeric tenant ID and association, then independently reads the committed row. Exact + * retries return the original allocation; a changed source receipt or incomplete legacy + * association fails closed. + */ + public FreshTenantAssociation associateFreshTenant( + UUID creationRequestId, String expectedRequestDigest) { + requireNoActiveOwnerTransaction(); + requireExactSelector(creationRequestId, expectedRequestDigest); + + FreshTenantCreationEvidence sourceEvidence = + Objects.requireNonNull( + gameDesignClient.resolveCreation(creationRequestId, expectedRequestDigest), + "Authenticated Game Design fresh-tenant evidence is required"); + requireExactSource(sourceEvidence, creationRequestId, expectedRequestDigest); + + FreshTenantAssociation committed = + writeTransaction.execute(status -> commitAssociation(sourceEvidence)); + if (committed == null) { + throw new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association transaction returned no result"); + } + + FreshTenantAssociation independentReadback = + readTransaction.execute( + status -> + readByCanonicalTenantIdInTransaction(sourceEvidence.canonicalTenantId()) + .orElse(null)); + if (independentReadback == null + || !sourceEvidence.equals(independentReadback.sourceEvidence()) + || !committed.equals(independentReadback)) { + throw new InvalidFreshTenantAssociationException( + "Committed Game Session fresh tenant association failed independent exact readback"); + } + return independentReadback; + } + + /** Reads only complete, internally consistent stored evidence; it never calls Game Design. */ + public Optional readByCanonicalTenantId(UUID canonicalTenantId) { + requireNoActiveOwnerTransaction(); + if (canonicalTenantId == null || isNil(canonicalTenantId)) { + throw new IllegalArgumentException("Canonical tenant UUID must be nonnil"); + } + Optional result = + readTransaction.execute(status -> readByCanonicalTenantIdInTransaction(canonicalTenantId)); + return Objects.requireNonNull(result, "Game Session read transaction returned no result"); + } + + private FreshTenantAssociation commitAssociation(FreshTenantCreationEvidence sourceEvidence) { + requireOwnerTransaction(); + lockSourceIdentity(sourceEvidence); + + Optional prior = + readByRequestIdInTransaction(sourceEvidence.creationRequestId()); + if (prior.isPresent()) { + requireExactSource(sourceEvidence, prior.orElseThrow().sourceEvidence()); + return prior.orElseThrow(); + } + + rejectOrphanOrRetainedClaim(sourceEvidence); + long tenantId = allocateFreshTenantId(); + UUID associationOperationId = newAssociationOperationId(sourceEvidence.operationId()); + + int claimInsertCount = + dsl.execute( + "INSERT INTO game_session_tenant_canonical_claim" + + " (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id," + + " association_kind, reservation_kind, association_operation_id," + + " association_request_id) VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND'," + + " 'FRESH_SOURCE_BOUND', ?, ?)", + sourceEvidence.targetNamespace(), + sourceEvidence.canonicalTenantId(), + tenantId, + associationOperationId, + sourceEvidence.creationRequestId()); + if (claimInsertCount != 1) { + throw new InvalidFreshTenantAssociationException( + "Game Session canonical tenant claim insert did not affect exactly one row"); + } + + int associationInsertCount = + dsl.execute( + "INSERT INTO game_session_fresh_tenant_association" + + " (association_operation_id, target_namespace, association_request_id," + + " source_schema_version, source_target_namespace, source_request_id," + + " source_canonical_tenant_id, canonical_tenant_id," + + " legacy_game_session_tenant_id, source_game_row_id," + + " source_game_tenant_key, provenance_kind, association_kind," + + " complete_source_evidence)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND', ?::jsonb)", + associationOperationId, + sourceEvidence.targetNamespace(), + sourceEvidence.creationRequestId(), + sourceEvidence.schemaVersion(), + sourceEvidence.targetNamespace(), + sourceEvidence.creationRequestId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.canonicalTenantId(), + tenantId, + sourceEvidence.sourceGameRowId(), + sourceEvidence.sourceGameTenantKey(), + sourceEvidence.provenanceKind(), + serializeEvidence(sourceEvidence)); + if (associationInsertCount != 1) { + throw new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association insert did not affect exactly one row"); + } + + FreshTenantAssociation readback = + readByCanonicalTenantIdInTransaction(sourceEvidence.canonicalTenantId()) + .orElseThrow( + () -> + new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association did not read back in its owner transaction")); + requireExactSource(sourceEvidence, readback.sourceEvidence()); + return readback; + } + + private Optional readByCanonicalTenantIdInTransaction( + UUID canonicalTenantId) { + requireOwnerTransaction(); + if (canonicalTenantId == null || isNil(canonicalTenantId)) { + throw new IllegalArgumentException("Canonical tenant UUID must be nonnil"); + } + Record row = + dsl.fetchOne( + ASSOCIATION_SELECT + + "WHERE fresh.target_namespace = ? AND fresh.canonical_tenant_id = ?", + workloadNamespace, + canonicalTenantId); + if (row == null) { + rejectClaimWithoutAssociation(canonicalTenantId, null); + return Optional.empty(); + } + return Optional.of(toAssociation(row)); + } + + private Optional readByRequestIdInTransaction(UUID requestId) { + requireOwnerTransaction(); + Record row = + dsl.fetchOne( + ASSOCIATION_SELECT + + "WHERE fresh.target_namespace = ? AND fresh.association_request_id = ?", + workloadNamespace, + requestId); + if (row == null) { + return Optional.empty(); + } + return Optional.of(toAssociation(row)); + } + + private FreshTenantAssociation toAssociation(Record row) { + try { + String namespace = required(row, "target_namespace", String.class); + UUID canonicalTenantId = required(row, "canonical_tenant_id", UUID.class); + UUID requestId = required(row, "association_request_id", UUID.class); + UUID associationOperationId = required(row, "association_operation_id", UUID.class); + long tenantId = required(row, "legacy_game_session_tenant_id", Long.class); + FreshTenantCreationEvidence sourceEvidence = + parseEvidence(required(row, "complete_source_evidence", String.class)); + + if (!workloadNamespace.equals(namespace) + || !namespace.equals(required(row, "source_target_namespace", String.class)) + || !requestId.equals(required(row, "source_request_id", UUID.class)) + || !canonicalTenantId.equals(required(row, "source_canonical_tenant_id", UUID.class)) + || required(row, "source_schema_version", Integer.class) != sourceEvidence.schemaVersion() + || required(row, "source_game_row_id", Long.class) != sourceEvidence.sourceGameRowId() + || !required(row, "source_game_tenant_key", String.class) + .equals(sourceEvidence.sourceGameTenantKey()) + || !required(row, "provenance_kind", String.class).equals(sourceEvidence.provenanceKind()) + || !"FRESH_SOURCE_BOUND".equals(required(row, "association_kind", String.class)) + || !sourceEvidence.targetNamespace().equals(namespace) + || !sourceEvidence.creationRequestId().equals(requestId) + || !sourceEvidence.canonicalTenantId().equals(canonicalTenantId) + || isNil(associationOperationId) + || associationOperationId.equals(sourceEvidence.operationId()) + || !"FRESH_SOURCE_BOUND".equals(required(row, "claim_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(required(row, "claim_reservation_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(required(row, "reservation_kind", String.class)) + || !namespace.equals(required(row, "claim_namespace", String.class)) + || !canonicalTenantId.equals(required(row, "claim_canonical_tenant_id", UUID.class)) + || tenantId != required(row, "claim_tenant_id", Long.class) + || !associationOperationId.equals(required(row, "claim_operation_id", UUID.class)) + || !requestId.equals(required(row, "claim_request_id", UUID.class))) { + throw new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association differs from its complete source receipt or canonical claim"); + } + return new FreshTenantAssociation( + namespace, canonicalTenantId, tenantId, associationOperationId, sourceEvidence); + } catch (IllegalArgumentException exception) { + throw new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association contains invalid complete source evidence", + exception); + } + } + + private void rejectOrphanOrRetainedClaim(FreshTenantCreationEvidence evidence) { + rejectClaimWithoutAssociation(evidence.canonicalTenantId(), evidence.creationRequestId()); + } + + private void rejectClaimWithoutAssociation(UUID canonicalTenantId, UUID requestId) { + Record claim = + dsl.fetchOne( + "SELECT target_namespace, canonical_tenant_id, legacy_game_session_tenant_id," + + " association_kind, association_request_id FROM game_session_tenant_canonical_claim" + + " WHERE target_namespace = ? AND (canonical_tenant_id = ? OR association_request_id = ?)", + workloadNamespace, + canonicalTenantId, + requestId); + if (claim != null) { + throw new InvalidFreshTenantAssociationException( + "Game Session canonical tenant claim exists without its exact fresh association; retained or partial identity cannot be adopted"); + } + } + + private long allocateFreshTenantId() { + Record reservation = + dsl.fetchOne( + "INSERT INTO game_session_tenant_scope_reservation (reservation_kind)" + + " VALUES ('FRESH_SOURCE_BOUND') RETURNING game_session_tenant_id, reservation_kind"); + if (reservation == null + || !"FRESH_SOURCE_BOUND".equals(required(reservation, "reservation_kind", String.class))) { + throw new InvalidFreshTenantAssociationException( + "Game Session numeric tenant reservation did not allocate a fresh source-bound key"); + } + Long tenantId = required(reservation, "game_session_tenant_id", Long.class); + if (tenantId <= 0) { + throw new InvalidFreshTenantAssociationException( + "Game Session numeric tenant reservation is not positive"); + } + return tenantId; + } + + private void lockSourceIdentity(FreshTenantCreationEvidence evidence) { + List lockKeys = + new ArrayList<>( + List.of( + "fresh-tenant-canonical:" + workloadNamespace + ":" + evidence.canonicalTenantId(), + "fresh-tenant-request:" + workloadNamespace + ":" + evidence.creationRequestId())); + lockKeys.sort(String::compareTo); + for (String key : lockKeys) { + dsl.fetch("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", key); + } + } + + private static UUID newAssociationOperationId(UUID sourceOperationId) { + UUID operationId; + do { + operationId = UUID.randomUUID(); + } while (operationId.equals(sourceOperationId) || isNil(operationId)); + return operationId; + } + + private static String serializeEvidence(FreshTenantCreationEvidence evidence) { + ObjectNode json = JSON.createObjectNode(); + json.put("schemaVersion", evidence.schemaVersion()); + json.put("targetNamespace", evidence.targetNamespace()); + json.put("creationRequestId", evidence.creationRequestId().toString()); + json.put("operationId", evidence.operationId().toString()); + json.put("requestDigest", evidence.requestDigest()); + json.put("canonicalTenantId", evidence.canonicalTenantId().toString()); + json.put("sourceGameRowId", evidence.sourceGameRowId()); + json.put("sourceGameTenantKey", evidence.sourceGameTenantKey()); + json.put("provenanceKind", evidence.provenanceKind()); + json.put("evidenceDigest", evidence.evidenceDigest()); + try { + return JSON.writeValueAsString(json); + } catch (JsonProcessingException exception) { + throw new InvalidFreshTenantAssociationException( + "Complete Game Design source evidence could not be serialized", exception); + } + } + + private static FreshTenantCreationEvidence parseEvidence(String serializedEvidence) { + try { + JsonNode json = JSON.readTree(serializedEvidence); + if (json == null || !json.isObject() || json.size() != EVIDENCE_FIELDS.size()) { + throw new IllegalArgumentException( + "Complete source evidence must be one closed JSON object"); + } + Set fields = new HashSet<>(); + json.fieldNames().forEachRemaining(fields::add); + if (!fields.equals(EVIDENCE_FIELDS)) { + throw new IllegalArgumentException( + "Complete source evidence has an unknown or missing field"); + } + return new FreshTenantCreationEvidence( + requiredInt(json, "schemaVersion"), + requiredText(json, "targetNamespace"), + parseUuid(requiredText(json, "creationRequestId")), + parseUuid(requiredText(json, "operationId")), + requiredText(json, "requestDigest"), + parseUuid(requiredText(json, "canonicalTenantId")), + requiredLong(json, "sourceGameRowId"), + requiredText(json, "sourceGameTenantKey"), + requiredText(json, "provenanceKind"), + requiredText(json, "evidenceDigest")); + } catch (IOException | IllegalArgumentException exception) { + throw new InvalidFreshTenantAssociationException( + "Stored Game Session complete source evidence is malformed or has an invalid digest", + exception); + } + } + + private static String requiredText(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Complete source evidence field must be text: " + field); + } + return value.textValue(); + } + + private static int requiredInt(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException( + "Complete source evidence field must be an integer: " + field); + } + return value.intValue(); + } + + private static long requiredLong(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw new IllegalArgumentException( + "Complete source evidence field must be an integer: " + field); + } + return value.longValue(); + } + + private static UUID parseUuid(String value) { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || isNil(parsed)) { + throw new IllegalArgumentException( + "Complete source evidence UUID must be canonical and nonnil"); + } + return parsed; + } + + private static void requireExactSelector(UUID requestId, String expectedDigest) { + if (requestId == null || isNil(requestId)) { + throw new IllegalArgumentException("Canonical nonnil creation request ID is required"); + } + if (!GameTenantCreationDigest.isDigest(expectedDigest)) { + throw new IllegalArgumentException("Canonical expected request digest is required"); + } + } + + private void requireExactSource( + FreshTenantCreationEvidence evidence, UUID requestId, String expectedDigest) { + if (evidence == null + || !workloadNamespace.equals(evidence.targetNamespace()) + || !requestId.equals(evidence.creationRequestId()) + || !expectedDigest.equals(evidence.requestDigest())) { + throw new InvalidFreshTenantAssociationException( + "Authenticated Game Design receipt differs from the exact Game Session request"); + } + } + + private static void requireExactSource( + FreshTenantCreationEvidence expected, FreshTenantCreationEvidence actual) { + if (!expected.equals(actual)) { + throw new InvalidFreshTenantAssociationException( + "Game Session association retry differs from the complete original Game Design receipt"); + } + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) { + throw new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association is missing required stored evidence: " + field); + } + return value; + } + + private static void requireNoActiveOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Design fresh tenant evidence must be resolved before opening a Game Session transaction"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Session fresh tenant association storage access requires an active owner transaction"); + } + } + + private static boolean isNil(UUID value) { + return value != null && new UUID(0L, 0L).equals(value); + } + + /** Exact immutable Game Session allocation and its complete Game Design owner receipt. */ + public record FreshTenantAssociation( + String targetNamespace, + UUID canonicalTenantId, + long gameSessionTenantId, + UUID associationOperationId, + FreshTenantCreationEvidence sourceEvidence) { + public FreshTenantAssociation { + Objects.requireNonNull(targetNamespace); + Objects.requireNonNull(canonicalTenantId); + Objects.requireNonNull(associationOperationId); + Objects.requireNonNull(sourceEvidence); + if (gameSessionTenantId <= 0 + || isNil(canonicalTenantId) + || isNil(associationOperationId) + || associationOperationId.equals(sourceEvidence.operationId())) { + throw new IllegalArgumentException("Stored fresh tenant association identity is invalid"); + } + } + } + + /** Stored association, canonical claim, or source receipt is incomplete or contradictory. */ + public static final class InvalidFreshTenantAssociationException extends IllegalStateException { + public InvalidFreshTenantAssociationException(String message) { + super(message); + } + + public InvalidFreshTenantAssociationException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V41__fresh_tenant_complete_creation_evidence.sql b/services/game-session-service/src/main/resources/db/migration/V41__fresh_tenant_complete_creation_evidence.sql new file mode 100644 index 0000000000..610e03e803 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V41__fresh_tenant_complete_creation_evidence.sql @@ -0,0 +1,71 @@ +-- Preserve the complete immutable Game Design receipt on new Game Session associations. +-- Historical V25 rows remain nullable and are not reconstructed from their partial columns. +ALTER TABLE game_session_fresh_tenant_association + ADD COLUMN complete_source_evidence JSONB; + +-- [jooq ignore start] +CREATE FUNCTION validate_game_session_fresh_tenant_complete_source_evidence() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + evidence JSONB; +BEGIN + evidence := NEW.complete_source_evidence; + IF evidence IS NULL THEN + RAISE EXCEPTION 'Fresh Game Session tenant association requires complete source evidence' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_fresh_tenant_complete_source_evidence'; + END IF; + IF jsonb_typeof(evidence) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Fresh Game Session tenant source evidence must be an object' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_fresh_tenant_complete_source_evidence'; + END IF; + IF (SELECT COUNT(*) FROM jsonb_object_keys(evidence)) <> 10 + OR NOT (evidence ?& ARRAY[ + 'schemaVersion', 'targetNamespace', 'creationRequestId', 'operationId', + 'requestDigest', 'canonicalTenantId', 'sourceGameRowId', + 'sourceGameTenantKey', 'provenanceKind', 'evidenceDigest' + ]) THEN + RAISE EXCEPTION 'Fresh Game Session tenant source evidence has an incomplete or open shape' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_fresh_tenant_complete_source_evidence'; + END IF; + + IF jsonb_typeof(evidence -> 'schemaVersion') IS DISTINCT FROM 'number' + OR evidence ->> 'schemaVersion' IS DISTINCT FROM NEW.source_schema_version::TEXT + OR jsonb_typeof(evidence -> 'targetNamespace') IS DISTINCT FROM 'string' + OR evidence ->> 'targetNamespace' IS DISTINCT FROM NEW.source_target_namespace + OR NEW.source_target_namespace IS DISTINCT FROM NEW.target_namespace + OR jsonb_typeof(evidence -> 'creationRequestId') IS DISTINCT FROM 'string' + OR evidence ->> 'creationRequestId' IS DISTINCT FROM NEW.source_request_id::TEXT + OR NEW.source_request_id IS DISTINCT FROM NEW.association_request_id + OR jsonb_typeof(evidence -> 'operationId') IS DISTINCT FROM 'string' + OR (evidence ->> 'operationId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR evidence ->> 'operationId' = '00000000-0000-0000-0000-000000000000' + OR jsonb_typeof(evidence -> 'requestDigest') IS DISTINCT FROM 'string' + OR (evidence ->> 'requestDigest') !~ '^sha256:[0-9a-f]{64}$' + OR jsonb_typeof(evidence -> 'canonicalTenantId') IS DISTINCT FROM 'string' + OR evidence ->> 'canonicalTenantId' IS DISTINCT FROM NEW.source_canonical_tenant_id::TEXT + OR NEW.source_canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR jsonb_typeof(evidence -> 'sourceGameRowId') IS DISTINCT FROM 'number' + OR evidence ->> 'sourceGameRowId' IS DISTINCT FROM NEW.source_game_row_id::TEXT + OR jsonb_typeof(evidence -> 'sourceGameTenantKey') IS DISTINCT FROM 'string' + OR evidence ->> 'sourceGameTenantKey' IS DISTINCT FROM NEW.source_game_tenant_key + OR jsonb_typeof(evidence -> 'provenanceKind') IS DISTINCT FROM 'string' + OR evidence ->> 'provenanceKind' IS DISTINCT FROM NEW.provenance_kind + OR jsonb_typeof(evidence -> 'evidenceDigest') IS DISTINCT FROM 'string' + OR (evidence ->> 'evidenceDigest') !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Fresh Game Session tenant source evidence differs from its immutable receipt columns' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_fresh_tenant_complete_source_evidence'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_fresh_tenant_complete_source_evidence_guard + BEFORE INSERT ON game_session_fresh_tenant_association + FOR EACH ROW EXECUTE FUNCTION validate_game_session_fresh_tenant_complete_source_evidence(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index a071511286..d787c2337a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -2,6 +2,8 @@ import java.time.Instant; import java.util.UUID; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; @@ -172,6 +174,37 @@ private static void seedSourceAndCatalog(DSLContext tx, RuntimeTarget target) { } private static void seedFreshTenantAssociation(DSLContext tx, RuntimeTarget target) { + UUID sourceOperationId; + do { + sourceOperationId = UUID.randomUUID(); + } while (sourceOperationId.equals(target.tenantAssociationOperationId())); + String requestDigest = + GameTenantCreationDigest.requestDigest( + target.targetNamespace(), + target.tenantAssociationRequestId(), + target.sourceGameTenantKey(), + "Fixture game", + null); + FreshTenantCreationEvidence syntheticSourceEvidence = + new FreshTenantCreationEvidence( + 1, + target.targetNamespace(), + target.tenantAssociationRequestId(), + sourceOperationId, + requestDigest, + target.canonicalTenantId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + target.targetNamespace(), + target.tenantAssociationRequestId(), + sourceOperationId, + requestDigest, + target.canonicalTenantId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + "NEW_GAME_ROW")); tx.execute( "INSERT INTO game_session_tenant_scope_reservation" + " (game_session_tenant_id, reservation_kind) VALUES (?, 'FRESH_SOURCE_BOUND')", @@ -191,8 +224,13 @@ private static void seedFreshTenantAssociation(DSLContext tx, RuntimeTarget targ + " (association_operation_id, target_namespace, association_request_id," + " source_schema_version, source_target_namespace, source_request_id," + " source_canonical_tenant_id, canonical_tenant_id, legacy_game_session_tenant_id," - + " source_game_row_id, source_game_tenant_key, provenance_kind, association_kind)" - + " VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND')", + + " source_game_row_id, source_game_tenant_key, provenance_kind, association_kind," + + " complete_source_evidence)" + + " VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND'," + + " jsonb_build_object('schemaVersion', 1, 'targetNamespace', ?," + + " 'creationRequestId', ?, 'operationId', ?, 'requestDigest', ?," + + " 'canonicalTenantId', ?, 'sourceGameRowId', ?, 'sourceGameTenantKey', ?," + + " 'provenanceKind', 'NEW_GAME_ROW', 'evidenceDigest', ?))", target.tenantAssociationOperationId(), target.targetNamespace(), target.tenantAssociationRequestId(), @@ -202,7 +240,15 @@ private static void seedFreshTenantAssociation(DSLContext tx, RuntimeTarget targ target.canonicalTenantId(), target.gameSessionTenantId(), target.sourceGameRowId(), - target.sourceGameTenantKey()); + target.sourceGameTenantKey(), + syntheticSourceEvidence.targetNamespace(), + syntheticSourceEvidence.creationRequestId().toString(), + syntheticSourceEvidence.operationId().toString(), + syntheticSourceEvidence.requestDigest(), + syntheticSourceEvidence.canonicalTenantId().toString(), + syntheticSourceEvidence.sourceGameRowId(), + syntheticSourceEvidence.sourceGameTenantKey(), + syntheticSourceEvidence.evidenceDigest()); } private static void seedStartingRuntimeAndLaunch(DSLContext tx, RuntimeTarget target) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationPostgresIntegrationTest.java new file mode 100644 index 0000000000..6087744078 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationPostgresIntegrationTest.java @@ -0,0 +1,389 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.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 java.nio.file.Path; +import java.sql.Connection; +import java.sql.Statement; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CyclicBarrier; +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.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Game Design responses are explicit mocks here; authentication is covered by the client unit + * tests. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionFreshTenantAssociationPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String NAMESPACE = "test"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void commitsCompleteOwnerReceiptAndExactRetryReadsTheOriginalAllocation() throws Exception { + try (Fixture fixture = newFixture(null)) { + FreshTenantCreationEvidence evidence = evidence(UUID.randomUUID(), REQUEST_DIGEST_A); + GameDesignFreshTenantCreationClient client = recordingClient(evidence); + GameSessionFreshTenantAssociationRepository repository = fixture.repository(client); + + var created = + repository.associateFreshTenant(evidence.creationRequestId(), evidence.requestDigest()); + var independentlyRead = + repository.readByCanonicalTenantId(evidence.canonicalTenantId()).orElseThrow(); + var retry = + repository.associateFreshTenant(evidence.creationRequestId(), evidence.requestDigest()); + + assertThat(created.gameSessionTenantId()).isPositive(); + assertThat(created.associationOperationId()).isNotEqualTo(evidence.operationId()); + assertThat(created.sourceEvidence()).isEqualTo(evidence); + assertThat(independentlyRead).isEqualTo(created); + assertThat(retry).isEqualTo(created); + assertThat(count(fixture.dsl(), "game_session_fresh_tenant_association")).isEqualTo(1L); + assertThat(count(fixture.dsl(), "game_session_tenant_canonical_claim")).isEqualTo(1L); + assertThat(count(fixture.dsl(), "game_session_tenant_scope_reservation")).isEqualTo(1L); + verify(client, times(2)) + .resolveCreation(evidence.creationRequestId(), evidence.requestDigest()); + } + } + + @Test + void rejectsChangedSourceReceiptAndMismatchedRequestWithoutCreatingAnotherAssociation() + throws Exception { + try (Fixture fixture = newFixture(null)) { + FreshTenantCreationEvidence original = evidence(UUID.randomUUID(), REQUEST_DIGEST_A); + FreshTenantCreationEvidence changedSource = + evidence(original.creationRequestId(), original.requestDigest(), UUID.randomUUID()); + GameDesignFreshTenantCreationClient client = mock(GameDesignFreshTenantCreationClient.class); + when(client.resolveCreation(any(), anyString())).thenReturn(original, changedSource); + GameSessionFreshTenantAssociationRepository repository = fixture.repository(client); + + var created = repository.associateFreshTenant(original.creationRequestId(), REQUEST_DIGEST_A); + assertThatThrownBy( + () -> repository.associateFreshTenant(original.creationRequestId(), REQUEST_DIGEST_A)) + .isInstanceOf( + GameSessionFreshTenantAssociationRepository.InvalidFreshTenantAssociationException + .class) + .hasMessageContaining("complete original Game Design receipt"); + assertThat(repository.readByCanonicalTenantId(original.canonicalTenantId()).orElseThrow()) + .isEqualTo(created); + assertThat(count(fixture.dsl(), "game_session_fresh_tenant_association")).isEqualTo(1L); + assertThat(count(fixture.dsl(), "game_session_tenant_scope_reservation")).isEqualTo(1L); + + when(client.resolveCreation(original.creationRequestId(), REQUEST_DIGEST_B)) + .thenReturn(original); + assertThatThrownBy( + () -> repository.associateFreshTenant(original.creationRequestId(), REQUEST_DIGEST_B)) + .isInstanceOf( + GameSessionFreshTenantAssociationRepository.InvalidFreshTenantAssociationException + .class) + .hasMessageContaining("exact Game Session request"); + assertThat(count(fixture.dsl(), "game_session_fresh_tenant_association")).isEqualTo(1L); + } + } + + @Test + void refusesToAdoptRetainedCanonicalClaimOrNumericScope() throws Exception { + try (Fixture fixture = newFixture(null)) { + FreshTenantCreationEvidence evidence = evidence(UUID.randomUUID(), REQUEST_DIGEST_A); + fixture + .dsl() + .execute( + "INSERT INTO game_session_tenant_scope_reservation" + + " (game_session_tenant_id, reservation_kind) VALUES (1, 'LEGACY_OCCUPIED')"); + fixture + .dsl() + .execute( + "INSERT INTO game_session_tenant_canonical_claim" + + " (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id," + + " association_kind, reservation_kind, association_operation_id," + + " association_request_id) VALUES (?, ?, 1, 'RETAINED_V8_1'," + + " 'LEGACY_OCCUPIED', ?, ?)", + NAMESPACE, + evidence.canonicalTenantId(), + UUID.randomUUID(), + evidence.creationRequestId()); + GameDesignFreshTenantCreationClient client = recordingClient(evidence); + GameSessionFreshTenantAssociationRepository repository = fixture.repository(client); + + assertThatThrownBy( + () -> + repository.associateFreshTenant( + evidence.creationRequestId(), evidence.requestDigest())) + .isInstanceOf( + GameSessionFreshTenantAssociationRepository.InvalidFreshTenantAssociationException + .class) + .hasMessageContaining("retained or partial identity cannot be adopted"); + assertThat(count(fixture.dsl(), "game_session_fresh_tenant_association")).isZero(); + assertThat(count(fixture.dsl(), "game_session_tenant_scope_reservation")).isEqualTo(1L); + assertThat(count(fixture.dsl(), "game_session_tenant_canonical_claim")).isEqualTo(1L); + } + } + + @Test + void concurrentExactDuplicateRequestsReturnOneCommittedAssociation() throws Exception { + try (Fixture fixture = newFixture(null)) { + FreshTenantCreationEvidence evidence = evidence(UUID.randomUUID(), REQUEST_DIGEST_A); + CyclicBarrier bothOwnerReads = new CyclicBarrier(2); + GameDesignFreshTenantCreationClient client = mock(GameDesignFreshTenantCreationClient.class); + when(client.resolveCreation(evidence.creationRequestId(), evidence.requestDigest())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + bothOwnerReads.await(10, TimeUnit.SECONDS); + return evidence; + }); + GameSessionFreshTenantAssociationRepository repository = fixture.repository(client); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> + repository.associateFreshTenant( + evidence.creationRequestId(), evidence.requestDigest())); + Future second = + executor.submit( + () -> + repository.associateFreshTenant( + evidence.creationRequestId(), evidence.requestDigest())); + + var firstResult = first.get(20, TimeUnit.SECONDS); + var secondResult = second.get(20, TimeUnit.SECONDS); + assertThat(firstResult).isEqualTo(secondResult); + assertThat(count(fixture.dsl(), "game_session_fresh_tenant_association")).isEqualTo(1L); + assertThat(count(fixture.dsl(), "game_session_tenant_canonical_claim")).isEqualTo(1L); + assertThat(count(fixture.dsl(), "game_session_tenant_scope_reservation")).isEqualTo(1L); + } finally { + executor.shutdownNow(); + } + } + } + + @Test + void rollsBackReservationAndCanonicalClaimWhenAssociationInsertFails() throws Exception { + try (Fixture fixture = newFixture(null)) { + fixture + .dsl() + .execute( + "ALTER TABLE game_session_fresh_tenant_association" + + " ADD CONSTRAINT chk_test_reject_fresh_association CHECK (FALSE)"); + FreshTenantCreationEvidence evidence = evidence(UUID.randomUUID(), REQUEST_DIGEST_A); + GameSessionFreshTenantAssociationRepository repository = + fixture.repository(recordingClient(evidence)); + + assertThatThrownBy( + () -> + repository.associateFreshTenant( + evidence.creationRequestId(), evidence.requestDigest())) + .isInstanceOf(RuntimeException.class); + assertThat(count(fixture.dsl(), "game_session_fresh_tenant_association")).isZero(); + assertThat(count(fixture.dsl(), "game_session_tenant_canonical_claim")).isZero(); + assertThat(count(fixture.dsl(), "game_session_tenant_scope_reservation")).isZero(); + } + } + + @Test + void deniesHistoricalV25AssociationWithoutReconstructingMissingSourceReceipt() throws Exception { + try (Fixture fixture = newFixture(MigrationVersion.fromVersion("25"))) { + UUID requestId = UUID.randomUUID(); + UUID canonicalTenantId = UUID.randomUUID(); + UUID associationOperationId = UUID.randomUUID(); + Record reservation = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "INSERT INTO game_session_tenant_scope_reservation (reservation_kind)" + + " VALUES ('FRESH_SOURCE_BOUND') RETURNING game_session_tenant_id"), + "V25 reservation insert returned no generated tenant ID"); + Long tenantId = reservation.get("game_session_tenant_id", Long.class); + fixture + .dsl() + .execute( + "INSERT INTO game_session_tenant_canonical_claim" + + " (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id," + + " association_kind, reservation_kind, association_operation_id," + + " association_request_id) VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND'," + + " 'FRESH_SOURCE_BOUND', ?, ?)", + NAMESPACE, + canonicalTenantId, + tenantId, + associationOperationId, + requestId); + fixture + .dsl() + .execute( + "INSERT INTO game_session_fresh_tenant_association" + + " (association_operation_id, target_namespace, association_request_id," + + " source_schema_version, source_target_namespace, source_request_id," + + " source_canonical_tenant_id, canonical_tenant_id," + + " legacy_game_session_tenant_id, source_game_row_id, source_game_tenant_key," + + " provenance_kind, association_kind)" + + " VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, 9, 'legacy-source-key'," + + " 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND')", + associationOperationId, + NAMESPACE, + requestId, + NAMESPACE, + requestId, + canonicalTenantId, + canonicalTenantId, + tenantId); + fixture.migrateLatest(); + + GameDesignFreshTenantCreationClient client = mock(GameDesignFreshTenantCreationClient.class); + GameSessionFreshTenantAssociationRepository repository = fixture.repository(client); + assertThatThrownBy(() -> repository.readByCanonicalTenantId(canonicalTenantId)) + .isInstanceOf( + GameSessionFreshTenantAssociationRepository.InvalidFreshTenantAssociationException + .class) + .hasMessageContaining("missing required stored evidence: complete_source_evidence"); + verifyNoInteractions(client); + assertThat(count(fixture.dsl(), "game_session_fresh_tenant_association")).isEqualTo(1L); + } + } + + private static GameDesignFreshTenantCreationClient recordingClient( + FreshTenantCreationEvidence evidence) { + GameDesignFreshTenantCreationClient client = mock(GameDesignFreshTenantCreationClient.class); + when(client.resolveCreation(evidence.creationRequestId(), evidence.requestDigest())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return evidence; + }); + return client; + } + + private static FreshTenantCreationEvidence evidence(UUID requestId, String requestDigest) { + return evidence(requestId, requestDigest, UUID.randomUUID()); + } + + private static FreshTenantCreationEvidence evidence( + UUID requestId, String requestDigest, UUID sourceOperationId) { + String sourceKey = "owner-key-" + requestId.toString().substring(0, 8); + long sourceRowId = 91L; + UUID canonicalTenantId = UUID.randomUUID(); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + requestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + requestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW")); + } + + private static long count(DSLContext dsl, String tableName) { + Record row = + Objects.requireNonNull( + dsl.fetchOne("SELECT COUNT(*) AS row_count FROM " + tableName), + "Count query returned no row for table " + tableName); + return row.get("row_count", Long.class); + } + + private static Fixture newFixture(MigrationVersion target) { + String schema = "gs_fresh_tenant_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway flyway = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(target == null ? MigrationVersion.LATEST : target) + .load(); + flyway.migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + schema, dataSource, flyway, dsl, new DataSourceTransactionManager(dataSource)); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + Flyway flyway, + DSLContext dsl, + DataSourceTransactionManager transactionManager) + implements AutoCloseable { + GameSessionFreshTenantAssociationRepository repository( + GameDesignFreshTenantCreationClient client) { + return new GameSessionFreshTenantAssociationRepository( + dsl, transactionManager, client, NAMESPACE); + } + + void migrateLatest() { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + @Override + public void close() throws Exception { + try (Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + } + + private static final String REQUEST_DIGEST_A = "sha256:" + "a".repeat(64); + private static final String REQUEST_DIGEST_B = "sha256:" + "b".repeat(64); +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java new file mode 100644 index 0000000000..b5d66fe89a --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java @@ -0,0 +1,335 @@ +package net.firedevops.firemud.gamesession.client; + +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.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +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.Attributes; +import io.grpc.CallOptions; +import io.grpc.ClientCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +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.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameDesignFreshTenantCreationClientTest { + private static final UUID 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 CANONICAL_TENANT_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String REQUEST_DIGEST = "sha256:" + "a".repeat(64); + private static final String SOURCE_TENANT_KEY = "fresh-owner-key-91"; + private static final long SOURCE_GAME_ROW_ID = 91L; + + @Test + void readsExactImmutableReceiptAndSendsExactRequestWithBoundedDeadline() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveFreshTenantCreation(any())).thenReturn(validResponse()); + GameDesignFreshTenantCreationClient client = newClient(stub); + + FreshTenantCreationEvidence evidence = client.resolveCreation(REQUEST_ID, REQUEST_DIGEST); + + assertThat(evidence.creationRequestId()).isEqualTo(REQUEST_ID); + assertThat(evidence.operationId()).isEqualTo(SOURCE_OPERATION_ID); + assertThat(evidence.requestDigest()).isEqualTo(REQUEST_DIGEST); + assertThat(evidence.canonicalTenantId()).isEqualTo(CANONICAL_TENANT_ID); + assertThat(evidence.sourceGameRowId()).isEqualTo(SOURCE_GAME_ROW_ID); + assertThat(evidence.sourceGameTenantKey()).isEqualTo(SOURCE_TENANT_KEY); + ArgumentCaptor request = + ArgumentCaptor.forClass(ResolveFreshTenantCreationRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).resolveFreshTenantCreation(request.capture()); + assertThat(request.getValue().getCreationRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(request.getValue().getExpectedRequestDigest()).isEqualTo(REQUEST_DIGEST); + } + + @Test + void rejectsMalformedSelectorUnknownResponseFieldsAndMismatchedEvidence() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub unused = mockStub(); + GameDesignFreshTenantCreationClient noCall = newClient(unused); + assertThatThrownBy(() -> noCall.resolveCreation(null, REQUEST_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> noCall.resolveCreation(REQUEST_ID, "bad")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(unused); + + assertRejected( + validResponse().toBuilder().setRequestDigest("sha256:" + "b".repeat(64)).build()); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + assertRejected(validResponse().toBuilder().setUnknownFields(unknown).build()); + assertRejected(validResponse().toBuilder().setProvenanceKind("RETAINED_GAME_V30").build()); + } + + @Test + void refusesRemoteReadInsideAnActiveGameSessionTransaction() throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + GameDesignFreshTenantCreationClient client = newClient(stub); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.resolveCreation(REQUEST_ID, REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside a Game Session transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(stub); + } + + @Test + void requiresFileBackedMtlsAndPinsTheGameDesignServerPeer(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = spy(new GrpcChannelFactory()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design-service.internal:6565"); + CommonGrpcClientProperties tls = mtlsProperties(directory); + GameDesignFreshTenantCreationClient client = + new GameDesignFreshTenantCreationClient(endpoints, tls, channelFactory, "test"); + try { + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design-service.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + assertThat(installedServerPeerUri(client)) + .isEqualTo("spiffe://firemud/ns/test/sa/game-design-service"); + } finally { + client.close(); + } + + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new GameDesignFreshTenantCreationClient( + new ServiceEndpointsProperties(), tls, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesAnOwnerResponseWithoutAuthenticatedGameDesignServerSession(@TempDir Path directory) + throws Exception { + UnauthenticatedResponseChannel channel = new UnauthenticatedResponseChannel(validResponse()); + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel( + anyString(), anyInt(), any(CommonGrpcClientProperties.class), anyBoolean())) + .thenReturn(channel); + GameDesignFreshTenantCreationClient client = + new GameDesignFreshTenantCreationClient( + new ServiceEndpointsProperties(), mtlsProperties(directory), factory, "test"); + try { + client.init(); + assertThatThrownBy(() -> client.resolveCreation(REQUEST_ID, REQUEST_DIGEST)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(channel.lastCallCancelled).isTrue(); + } finally { + client.close(); + } + } + + private static void assertRejected(ResolveFreshTenantCreationResponse response) throws Exception { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = mockStub(); + when(stub.resolveFreshTenantCreation(any())).thenReturn(response); + GameDesignFreshTenantCreationClient client = newClient(stub); + assertThatThrownBy(() -> client.resolveCreation(REQUEST_ID, REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class); + } + + private static GameDesignFreshTenantCreationClient newClient( + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub) throws Exception { + GameDesignFreshTenantCreationClient client = + new GameDesignFreshTenantCreationClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + mock(GrpcChannelFactory.class), + "test"); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static String installedServerPeerUri(GameDesignFreshTenantCreationClient client) + throws Exception { + Field interceptorField = + GameDesignFreshTenantCreationClient.class.getDeclaredField("serverPeerIdentityInterceptor"); + interceptorField.setAccessible(true); + GrpcServerPeerIdentityClientInterceptor interceptor = + (GrpcServerPeerIdentityClientInterceptor) interceptorField.get(client); + Field expectedPeerUriField = + GrpcServerPeerIdentityClientInterceptor.class.getDeclaredField("expectedPeerUri"); + expectedPeerUriField.setAccessible(true); + return (String) expectedPeerUriField.get(interceptor); + } + + private static TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub mockStub() { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = + mock(TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static ResolveFreshTenantCreationResponse validResponse() { + return ResolveFreshTenantCreationResponse.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace("test") + .setCreationRequestId(REQUEST_ID.toString()) + .setOperationId(SOURCE_OPERATION_ID.toString()) + .setRequestDigest(REQUEST_DIGEST) + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setSourceGameRowId(SOURCE_GAME_ROW_ID) + .setSourceGameTenantKey(SOURCE_TENANT_KEY) + .setProvenanceKind("NEW_GAME_ROW") + .setEvidenceDigest( + GameTenantCreationDigest.evidenceDigest( + "test", + REQUEST_ID, + SOURCE_OPERATION_ID, + REQUEST_DIGEST, + CANONICAL_TENANT_ID, + SOURCE_GAME_ROW_ID, + SOURCE_TENANT_KEY, + "NEW_GAME_ROW")) + .build(); + } + + private static CommonGrpcClientProperties mtlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/game-design-server-ca.crt"); + return tls; + } + + private static CommonGrpcClientProperties mtlsProperties(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(copyCertificateResource("dev-cert.pem", directory).toString()); + tls.setPrivateKey(copyCertificateResource("dev-key.pem", directory).toString()); + tls.setCaCert(copyCertificateResource("dev-ca.pem", directory).toString()); + return tls; + } + + private static Path copyCertificateResource(String fileName, Path directory) throws Exception { + Path destination = directory.resolve(fileName); + try (InputStream source = + GameDesignFreshTenantCreationClientTest.class.getResourceAsStream("/certs/" + fileName)) { + if (source == null) { + throw new IllegalStateException("Missing shared TLS test resource: " + fileName); + } + Files.copy(source, destination); + } + return destination; + } + + private static final class UnauthenticatedResponseChannel extends ManagedChannel { + private final byte[] responseBytes; + private boolean lastCallCancelled; + private boolean shutDown; + + private UnauthenticatedResponseChannel(ResolveFreshTenantCreationResponse response) { + this.responseBytes = response.toByteArray(); + } + + @Override + public String authority() { + return "test-authority"; + } + + @Override + public ClientCall newCall( + MethodDescriptor method, CallOptions callOptions) { + return new ClientCall<>() { + @Override + public void start(Listener responseListener, Metadata headers) { + responseListener.onHeaders(new Metadata()); + responseListener.onMessage(method.parseResponse(new ByteArrayInputStream(responseBytes))); + responseListener.onClose(Status.OK, new Metadata()); + } + + @Override + public void request(int numMessages) {} + + @Override + public void cancel(String message, Throwable cause) { + lastCallCancelled = true; + } + + @Override + public void halfClose() {} + + @Override + public void sendMessage(ReqT message) {} + + @Override + public Attributes getAttributes() { + return Attributes.EMPTY; + } + }; + } + + @Override + public ManagedChannel shutdown() { + shutDown = true; + return this; + } + + @Override + public boolean isShutdown() { + return shutDown; + } + + @Override + public boolean isTerminated() { + return shutDown; + } + + @Override + public ManagedChannel shutdownNow() { + shutDown = true; + return this; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return shutDown; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java new file mode 100644 index 0000000000..093b19a1a8 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java @@ -0,0 +1,109 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionFreshTenantAssociationRepositoryTest { + private static final UUID 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 CANONICAL_TENANT_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String REQUEST_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void rejectsInvalidSelectorsBeforeCallingTheRemoteOwnerOrOpeningSql() { + GameDesignFreshTenantCreationClient gameDesignClient = + mock(GameDesignFreshTenantCreationClient.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + GameSessionFreshTenantAssociationRepository repository = + new GameSessionFreshTenantAssociationRepository( + mock(DSLContext.class), transactionManager, gameDesignClient, "test"); + + assertThatThrownBy(() -> repository.associateFreshTenant(null, REQUEST_DIGEST)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> repository.associateFreshTenant(REQUEST_ID, "invalid")) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(gameDesignClient, transactionManager); + } + + @Test + void resolvesSourceOnlyOutsideAnExistingGameSessionTransaction() { + GameDesignFreshTenantCreationClient gameDesignClient = + mock(GameDesignFreshTenantCreationClient.class); + GameSessionFreshTenantAssociationRepository repository = + new GameSessionFreshTenantAssociationRepository( + mock(DSLContext.class), + mock(PlatformTransactionManager.class), + gameDesignClient, + "test"); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> repository.associateFreshTenant(REQUEST_ID, REQUEST_DIGEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("before opening a Game Session transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + verifyNoInteractions(gameDesignClient); + } + + @Test + void refusesOwnerReceiptThatDoesNotMatchTheExactRequestedNamespaceAndDigest() { + GameDesignFreshTenantCreationClient gameDesignClient = + mock(GameDesignFreshTenantCreationClient.class); + when(gameDesignClient.resolveCreation(REQUEST_ID, REQUEST_DIGEST)) + .thenReturn(evidence("other", REQUEST_ID, REQUEST_DIGEST, SOURCE_OPERATION_ID)); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + GameSessionFreshTenantAssociationRepository repository = + new GameSessionFreshTenantAssociationRepository( + mock(DSLContext.class), transactionManager, gameDesignClient, "test"); + + assertThatThrownBy(() -> repository.associateFreshTenant(REQUEST_ID, REQUEST_DIGEST)) + .isInstanceOf( + GameSessionFreshTenantAssociationRepository.InvalidFreshTenantAssociationException + .class) + .hasMessageContaining("exact Game Session request"); + + verify(gameDesignClient).resolveCreation(REQUEST_ID, REQUEST_DIGEST); + verifyNoInteractions(transactionManager); + } + + private static FreshTenantCreationEvidence evidence( + String namespace, UUID requestId, String requestDigest, UUID operationId) { + String sourceKey = "owner-key"; + long sourceRowId = 19L; + return new FreshTenantCreationEvidence( + 1, + namespace, + requestId, + operationId, + requestDigest, + CANONICAL_TENANT_ID, + sourceRowId, + sourceKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + namespace, + requestId, + operationId, + requestDigest, + CANONICAL_TENANT_ID, + sourceRowId, + sourceKey, + "NEW_GAME_ROW")); + } +} From 1c446bbace162c8825cdcaf4a886619579d11e02 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 12:03:36 +1300 Subject: [PATCH 101/129] Retain authenticated published policy in fresh canonical realm catalogs --- .../game-design-service/api-contracts.md | 8 + .../game-session-service/api-contracts.md | 10 + ...ame-authoring-publishing-and-activation.md | 8 +- ...e-session-runtime-and-tick-coordination.md | 2 + ...ssion_published_realm_policy_service.proto | 43 + .../RealmPolicyPublishedEvidence.java | 56 +- .../RealmPolicyPublishedEvidenceCodec.java | 334 +++++ ...sionPublishedRealmPolicyReadGrpcCodec.java | 534 +++++++ ...tSessionLaunchDescriptorGrpcCodecTest.java | 6 +- ...RealmPolicyPublishedEvidenceCodecTest.java | 413 ++++++ ...PublishedRealmPolicyReadGrpcCodecTest.java | 539 +++++++ services/game-design-service/build.gradle.kts | 21 + ...onPublishedRealmPolicyReadGrpcService.java | 174 +++ .../RealmPolicyPublicationRepository.java | 1 + ...essionPublishedRealmPolicyReadService.java | 189 +++ .../GameAuthoredWorldSourceRepository.java | 45 + ...licationExportPostgresIntegrationTest.java | 465 +++++- ...blishedRealmPolicyReadGrpcServiceTest.java | 242 ++++ ...onPublishedRealmPolicyReadServiceTest.java | 301 ++++ .../game-session-service/build.gradle.kts | 16 + .../GameDesignPublishedRealmPolicyClient.java | 164 +++ ...essionCanonicalRealmCatalogRepository.java | 1252 +++++++++++++++++ ...nical_catalog_complete_policy_evidence.sql | 30 + ...calGameplayBindingRuntimeTestFixtures.java | 79 +- ...alRealmCatalogPostgresIntegrationTest.java | 512 +++++++ ...ionCanonicalRealmCatalogProofFixtures.java | 284 ++++ ...anonicalRealmCatalogProofFixturesTest.java | 54 + ...antAssociationPostgresIntegrationTest.java | 4 +- ...eDesignPublishedRealmPolicyClientTest.java | 272 ++++ ...onCanonicalRealmCatalogRepositoryTest.java | 63 + 30 files changed, 6041 insertions(+), 80 deletions(-) create mode 100644 protos/game-design/v1/start_session_published_realm_policy_service.proto rename services/{game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication => common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign}/RealmPolicyPublishedEvidence.java (82%) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionPublishedRealmPolicyReadGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmPolicyPublishedEvidenceCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/StartSessionPublishedRealmPolicyReadGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionPublishedRealmPolicyReadGrpcService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionPublishedRealmPolicyReadService.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionPublishedRealmPolicyReadGrpcServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionPublishedRealmPolicyReadServiceTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V42__canonical_catalog_complete_policy_evidence.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogPostgresIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogProofFixtures.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogProofFixturesTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index e861278930..582c128c31 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -28,6 +28,14 @@ The separate `GameDesignStartSessionLaunchDescriptorService.ResolveStartSessionL `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. +## StartSession Published Realm Policy Read + +The distinct `GameDesignStartSessionPublishedRealmPolicyReadService` is an internal immutable-content handoff to the exact same-namespace Game Session workload, not an extension of the World-only authored-source method or the registered descriptor API. Its [wire contract](../../../../protos/game-design/v1/start_session_published_realm_policy_service.proto) preserves the complete exact-replay template-association request, independent read correlation, descriptor, release attestation and exact retained target provenance. Game Design authenticates the peer and rejects player context before decoding, then uses its existing Account-confirmed association reader before opening the source snapshot. An unavailable or mismatched original-operation confirmation returns no policy content and performs no local source read. A valid descriptor, digest or workload identity alone is insufficient disclosure permission. + +In one independent read-only repeatable-read snapshot, Game Design reads the exact authored source and complete sealed realm-policy set. The source, target, selected commit, workflow, release reference, manifest and complete attestation must agree. The publication epoch must match its retained terminal and cannot be later than the descriptor's version-state epoch; those epochs are not interchangeable. Success echoes the complete request unchanged and carries every original policy identity, canonical policy byte, revision provenance and digest, together with the complete immutable publication backing. Receivers reuse the canonical Game Design-owned carrier and validate each policy digest and the whole set rather than maintaining another policy grammar or selecting a newer release. + +The read does not allocate a realm or namespace, advance a catalog revision, authorize a World mutation, hold current Account authority or admit a player. The construction remains unregistered; its producer, consumer and executed-proof limits belong to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#fresh-tenant-identity-prerequisite). Game Session owns the subsequent [source-backed catalog consequence](../game-session-service/api-contracts.md#fresh-source-backed-canonical-catalog). + ## 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. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 450409ebe0..e304683680 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -26,6 +26,16 @@ Read the pause/status/recovery APIs below as the target-state contract unless th For script transitions, the live boundary includes the exact `scriptPinEpoch` and an atomic current-pin/request-result ledger commit; bounded authoritative history readback and append-only rollout history remain target-state gaps. Target pin and rollback requests require the explicit tagged `expectedCurrentPin` precondition defined in the [Scripting Control Plane API](../../system-architecture-scripting-control-plane-api.md): exactly `UNCONDITIONAL`, `EXPECT_UNPINNED`, or `EXPECT_EPOCH(scriptPinEpoch)`, with the complete tag/value included in the normalized digest. Missing/unknown tags fail validation; a both-absent tuple for a never-pinned instance is valid semantic `UNPINNED` and matches only `EXPECT_UNPINNED`; a partial tuple is invalid owner state, cannot satisfy `EXPECT_UNPINNED` or `EXPECT_EPOCH`, and is rejected/fails closed even for an `UNCONDITIONAL` request. Missing or unreadable authority is not `UNPINNED` and remains unavailable. `UNCONDITIONAL` is only the explicit `platformAdmin` break-glass repair branch with the matrix's `privileged_control` authorization; it skips only current-pin comparison and does not bypass coherent owner state, readiness, or other validation. See [Rollout and Rollback](../../system-architecture-scripting-rollout-and-rollback.md#pin-compare-and-set-preconditions) for the owner semantics. A valid precondition mismatch is deterministic and non-mutating and follows the existing idempotency/history semantics. +## Fresh Source-Backed Canonical Catalog + +Game Session obtains the complete immutable creation receipt and the [Game Design-owned published-policy handoff](../game-design-service/api-contracts.md#startsession-published-realm-policy-read) outside its SQL transaction. It validates the exact workload namespace, canonical tenant, fresh source-row provenance, authored world and selected publication before allocating any local identity. Private numeric tenant keys remain Game Session implementation details; matching numbers, slugs or absent history never establish retained identity. + +The restricted fresh public-production construction requires exactly one visible public-production policy, its explicit `SHARED` scope and the exact source-bound world. It copies that policy's canonical entry-policy value and complete immutable provenance rather than substituting a demo realm, default policy or latest release. In one owner transaction, Game Session retains the authored source, its tenant association, the stable tenant-shared namespace and the new realm catalog; retries compare the complete original evidence and independently read the same committed identities. A historical partial row is not an authenticated complete receipt and is not repaired by inference. Other realm modes and retained migrations remain separate owner work. + +Local request and receipt digests use ADR 0047-style byte-length framing and SHA-256. In fixed order, `gs-authored-world-source-intake-request/v1` binds namespace, intake request UUID, original source operation UUID and original source evidence digest; the validated source digest binds every field of that owner's receipt. `gs-authored-world-source-intake-receipt/v1` binds the request digest and allocated intake operation UUID. `gs-canonical-public-realm-request/v1` binds namespace, catalog request UUID, canonical tenant UUID, intake operation UUID, intake receipt digest, selected policy UUID, policy digest and complete policy-set digest. `gs-canonical-public-realm-receipt/v1` binds the request digest, allocated realm UUID, allocated shared namespace UUID and actual stored catalog revision as a canonical positive decimal. These local digests do not authenticate a caller or replace complete durable evidence readback. + +Catalog creation is not an `OPEN` pointer or a runtime launch. The actual stored catalog revision must subsequently be captured with the exact `STARTING` instance and complete launch association in their owner transaction; neither the initial catalog revision nor an absent pointer proves permission to launch or admit. World lifecycle and initial-bind proof remain independently required. Current implementation and execution limits belong to the [Game Session tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). + ## Service Interactions Game Session communicates with other platform services exclusively via gRPC for gameplay-domain work. Player-delegated calls carry the typed unsigned `PlayerExecutionContext` defined in the authentication architecture, including the required gameplay scope for admission. Downstream services authenticate the concrete mTLS caller, enforce an exact RPC caller allowlist, validate context/request equality and domain scope, and reject client-supplied identity metadata. Routine gameplay calls do not use signed per-action attestations or a generic replay cache; mutations retain their owning command/effect/request idempotency. 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 df46319336..f8c06760ce 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 @@ -6,7 +6,13 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The current source-construction batch defines actual isolated Logging, Account and Game Session stores for original participation acquisition, a file-backed mTLS Logging claim reader, the Game Session V35 attempt reader, World typed original-operation acquisition with additive V63 admission evidence, and the source-only authored initial actor core described at the [Game Design owner](../../architecture/microservices/game-design-service/game-templates.md#release-authored-initial-actor-core). The producer validates selected schema-three source bindings but does not yet deliver or persist a new actor-allocation handoff. The genuine-release-to-World definition now reserves the exact original tuple in an isolated Game Session store before Account redemption, attaches the exact redeemed projection afterward, and traverses the native Account-to-Game-Session current-attempt and World-to-Account participation clients and receivers. Its Game Session launch association, Logging claim and some Account caller contexts remain stipulated. Stores, servers and the reusable transport clients are prepared before the unchanged 30-second owner lease; the later descriptor and preparation work must still fit that lease without renewal or rearming. This definition has compiled but has not executed physically, and its acquired observation is not continuous foreign-owner protection. No production receiver, credential path, allocation, lifecycle or admission activation is enabled. +The unregistered receiving construction retains the complete immutable published realm-policy set in the canonical Game Design-owned carrier, checking every full policy digest, original source capture and terminal publication binding. Its distinct Game Design read requires the existing Account-confirmed exact-replay association before opening the owner source/policy snapshot. Game Session's bounded fresh `NEW_GAME_ROW`, visible public-production `SHARED` producer atomically retains that source, complete policy evidence, shared namespace and catalog, then independently reads back its original identities and actual catalog revision. Additive V42 does not backfill historical catalog rows or restrict the catalog's general scope vocabulary. The genuine-release definition composes the native Game Design creation read into Game Session's fresh association and its Account-confirmed source/policy read into the actual catalog repository and independent readback. That definition has not executed physically; complete producer/consumer and PostgreSQL proof remain required. These components create neither a `STARTING` launch association nor an `OPEN` pointer or gameplay admission. + +The genuine release definition now uses an actual isolated Logging reservation owner and native file-backed mTLS current-claim read instead of fixed Logging claim evidence. Account issuer/redeemer contexts remain explicit fixture stipulations; the current claim is point-in-time evidence, not continuous protection of a later owner commit. The newly composed Logging database and native receiver path has not executed locally. Game Session launch association, uninterrupted commit protection, final owner settlement, lifecycle readiness and activation remain open; no broader handoff is complete from these definitions. + +The corrected Common Platform/Game Design/Game Session gate passes in 1 minute 46 seconds across 216 tasks, including complete affected checks, SQL metadata generation, integration compilation, formatting, static analysis, coverage, links and 548 Markdown files. Passing current results total 3,206 executed unit cases and 28 executed non-container integration/cross-service cases; unchanged tasks reuse the preceding corrected candidate's results. There are 376 skips: 17 Game Session units and 359 container-dependent integration/cross-service cases. All six new catalog PostgreSQL cases and the genuine-release composition skip locally. A non-container fixture case validates the complete canonical carrier framing; it is explicitly synthetic and does not replace physical owner composition. The narrow Game Design fixture artifact contains only its operation record and two fixture families, without repository classes, application configuration or migrations. No Docker, physical PostgreSQL, certificate custody or complete handoff execution is claimed. + +The current source-construction batch defines actual isolated Logging, Account and Game Session stores for original participation acquisition, a file-backed mTLS Logging claim reader, the Game Session V35 attempt reader, World typed original-operation acquisition with additive V63 admission evidence, and the source-only authored initial actor core described at the [Game Design owner](../../architecture/microservices/game-design-service/game-templates.md#release-authored-initial-actor-core). The producer validates selected schema-three source bindings but does not yet deliver or persist a new actor-allocation handoff. The genuine-release-to-World definition reserves the exact original tuple in an isolated Game Session store before Account redemption, attaches the exact redeemed projection afterward, and traverses the native Account-to-Game-Session current-attempt and World-to-Account participation clients and receivers. Its Game Session launch association and some Account caller contexts remain stipulated; the composition replaces the earlier fixed Logging claim and source/catalog stipulations as described above. Stores, servers and the reusable transport clients are prepared before the unchanged 30-second owner lease; the later descriptor and preparation work must still fit that lease without renewal or rearming. The acquisition definition compiled but has not executed physically, and its acquired observation is not continuous foreign-owner protection. No production receiver, credential path, allocation, lifecycle or admission activation is enabled. The historical [Validation run 38075220202](https://github.com/benhook1013/FireMUD/actions/runs/38075220202) tests published source `e0f048e4eb5810eb69581dcb2c74e612cb368a60` through merge `e0e6e6394d51218511cd8e8a8ec72eeffb454fb5`, not the later local construction. Account's 1,683 aggregate cases include one failed concurrent historical acknowledgement-receipt recovery case on PostgreSQL 16.15: the independent reader correctly denies because its observed WAL flush does not cover the insertion fence. That test's unconditional recovery-success expectation is not the accepted conditional recovery contract. The 13 protected-entry and 31 Draft-fence PostgreSQL cases pass physically; the Account job is cancelled after its check fails, so this is neither a green aggregate nor current-source proof. Gameplay's separately qualified PostgreSQL 18 original-acknowledgement proof covers only its fresh storage boundary; it does not establish historical recovery, continuous owner protection or gameplay admission. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 8145be9913..d2401c48d9 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for Game Session runtime and tick ## Current Status +The unregistered fresh-tenant receiver retains Game Design's complete authenticated creation receipt, reserves a private Game Session key and claim atomically, and independently reads back the exact association. Its focused source-local gate passed; all six PostgreSQL cases skipped locally. The fresh public-production catalog batch preserves the complete Game Design-owned published-policy carrier, requires the exact source and one explicit visible `SHARED` policy, and atomically creates the source intake, stable namespace and catalog with complete readback. Additive V42 leaves historical incomplete evidence unavailable rather than backfilling it. A genuine native Game Design-to-Game Session producer/consumer composition is defined but has not executed physically; catalog storage is not a `STARTING` launch, `OPEN` pointer or admission. The [authoring tracker](game-authoring-publishing-and-activation.md#current-status) records the shared producer and proof limits. + The construction branch is consuming the Account-only original current-attempt reader from published source `e9a29f43ae47598fdc2cacd8f65cf784ed96e0ea` ([#3153](https://github.com/benhook1013/FireMUD/pull/3153)). Its prerequisite owner-attempt repository and additive V35 are separate from existing canonical runtime admission. Existing Common contracts and the additional admission-terminal proto definitions are preserved. The reader remains unregistered; its exact tuple/projection, database-clock expiry, no-mutation and peer-identity definitions do not prove original production attempt creation, continuous Account protection, admission or activation. Source-local Common/Game Session checks passed, while PostgreSQL cases skipped; receiving-tree validation and physical composed acquisition remain pending. The broader donor template/launch-association integration suite is not part of this bounded reader intake or its proof claim. This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. diff --git a/protos/game-design/v1/start_session_published_realm_policy_service.proto b/protos/game-design/v1/start_session_published_realm_policy_service.proto new file mode 100644 index 0000000000..dbfcd2fed1 --- /dev/null +++ b/protos/game-design/v1/start_session_published_realm_policy_service.proto @@ -0,0 +1,43 @@ +syntax = "proto3"; + +package game_design.v1; + +import "game-design/v1/game_design_service.proto"; +import "game-design/v1/start_session_template_association_service.proto"; +import "game-design/v1/tenant_identity_service.proto"; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Standalone, unregistered historical-content read for the exact already-authorized +// StartSession replay. The receiver authenticates Game Session and independently confirms the +// Account operation before reading local immutable source or publication evidence. +service GameDesignStartSessionPublishedRealmPolicyReadService { + rpc ReadStartSessionPublishedRealmPolicy(ReadStartSessionPublishedRealmPolicyRequest) + returns (ReadStartSessionPublishedRealmPolicyResponse); +} + +message ReadStartSessionPublishedRealmPolicyRequest { + int32 schema_version = 1; + string target_namespace = 2; + string read_request_id = 3; + // Complete original ExactReplay authorization request; no grammar is copied or reduced here. + game_design.v1.ReadStartSessionTemplateAssociationRequest authorization_request = 4; + // Existing complete closed descriptor and release evidence, unchanged. + gamedesign.v1.LaunchDescriptor launch_descriptor = 5; + gamedesign.v1.AuthoredWorldReleaseAttestationEvidence release_attestation = 6; + // The existing canonical seven-field TargetProof JSON representation, unchanged. + bytes canonical_target_proof_json = 7; +} + +message ReadStartSessionPublishedRealmPolicyResponse { + int32 schema_version = 1; + // Echoes the entire request, including the nested exact Account authorization tuple and fence. + ReadStartSessionPublishedRealmPolicyRequest request = 2; + // Complete independent Account-confirmed association response and its full request echo. + game_design.v1.ReadStartSessionTemplateAssociationResponse authorization_response = 3; + // Existing complete authored-world source response grammar and correlation. + gamedesign.v1.ResolveAuthoredWorldSourceResponse source_evidence = 4; + // Canonical complete immutable policy-set carrier, validated by its existing Common codec. + bytes published_policy_set = 5; +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidence.java similarity index 82% rename from services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java rename to services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidence.java index fc3732a1c4..3c0f67ecbd 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidence.java @@ -1,4 +1,4 @@ -package net.firedevops.firemud.gamedesign.publication; +package net.firedevops.firemud.common.gamedesign; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -9,9 +9,9 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; -import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; -import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; /** Immutable internal evidence associating a frozen source set with its actual sealed release. */ public final class RealmPolicyPublishedEvidence { @@ -73,17 +73,38 @@ public record PublishedSet( || !digest(policySetDigest)) { throw new IllegalArgumentException("Complete bounded policy-set evidence required"); } - RealmPolicySource.ordered(policies.stream().map(Policy::source).toList()); - var operation = GameDesignPublicationOperation.fromStored(operationBytes); + var sources = policies.stream().map(Policy::source).toList(); + if (!RealmPolicySource.ordered(sources).equals(sources)) { + throw new IllegalArgumentException("Canonical published policy source order required"); + } + var operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); if (!operation.account().input().selection().target().equals(target) - || !operation.workflowId().equals(publishWorkflowId)) { + || !operation.world().request().publishWorkflowId().equals(publishWorkflowId)) { throw new IllegalArgumentException("Publication evidence differs from exact TargetProof"); } + var capture = new DraftAuthorizationFenceBinding.FrameReader(captureBytes); + capture.expect("game-design-realm-policy-source-capture/v1"); + byte[] capturedOperationBytes = capture.bytes(); + String snapshotJson = capture.text(); + capture.requireEnd(); + if (!Arrays.equals(capturedOperationBytes, operationBytes)) { + throw new IllegalArgumentException("Policy capture differs from exact operation bytes"); + } + var snapshot = RealmPolicySnapshot.fromStored(snapshotJson); + var selectedCommit = operation.account().input().selection().selectedCommit(); + if (!snapshot.binding().equals(selectedCommit) + || !snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(sourceCommitId) + || !snapshot.sourceEpoch().equals(sourceEpoch)) { + throw new IllegalArgumentException("Policy capture differs from complete published source"); + } var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalEvidenceBytes); - var release = terminal.releaseContent(); if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED - || !Arrays.equals(terminal.operationBytes(), operationBytes) - || !release.canonicalTenantId().equals(target.canonicalTenantId()) + || !Arrays.equals(terminal.operationBytes(), operationBytes)) { + throw new IllegalArgumentException("Terminal release evidence differs from policy set"); + } + var release = terminal.releaseContent(); + if (!release.canonicalTenantId().equals(target.canonicalTenantId()) || !release.canonicalVersionId().equals(target.canonicalVersionId()) || release.versionNumber() != versionNumber || !release.publishedReleaseBundleRef().equals(publishedReleaseBundleRef) @@ -93,6 +114,23 @@ public record PublishedSet( || terminal.publicationVersionStateEpoch() != publicationVersionStateEpoch) { throw new IllegalArgumentException("Terminal release evidence differs from policy set"); } + for (Policy policy : policies) { + if (!policyDigest( + policy.policyId(), + target, + versionNumber, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + policy.source()) + .equals(policy.policyDigest())) { + throw new IllegalArgumentException("Published policy digest differs from full policy"); + } + } + if (!snapshot.policies().equals(sources)) { + throw new IllegalArgumentException("Policy capture differs from complete published source"); + } if (!computePolicySetDigest( target, versionNumber, diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java new file mode 100644 index 0000000000..8f739ea559 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java @@ -0,0 +1,334 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Closed canonical carrier for complete published realm-policy evidence. */ +public final class RealmPolicyPublishedEvidenceCodec { + public static final String SCHEMA = "game-design-published-realm-policy-carrier/v1"; + + /** + * Bounds this complete framed carrier. Existing constituents retain their own limits, including + * the 4 MiB publication operation and at most 128 policies of at most 4 KiB each; original + * capture and terminal bytes remain opaque and exact. Larger assembled envelopes fail closed. + */ + public static final int MAX_ENVELOPE_BYTES = 32 * 1024 * 1024; + + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder(); + private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder(); + + private RealmPolicyPublishedEvidenceCodec() {} + + /** Encodes every field in a closed versioned frame without changing retained evidence bytes. */ + public static byte[] encode(RealmPolicyPublishedEvidence.PublishedSet evidence) { + Objects.requireNonNull(evidence, "evidence"); + long binaryBytes = + (long) evidence.operationBytes().length + + evidence.captureBytes().length + + evidence.terminalEvidenceBytes().length; + if (binaryBytes > MAX_ENVELOPE_BYTES) { + throw new IllegalArgumentException("Published realm-policy carrier exceeds 32 MiB"); + } + byte[] payload = canonicalPayload(evidence).getBytes(StandardCharsets.UTF_8); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, payload); + byte[] encoded = out.toByteArray(); + if (encoded.length > MAX_ENVELOPE_BYTES) { + throw new IllegalArgumentException("Published realm-policy carrier exceeds 32 MiB"); + } + return encoded; + } + + /** Decodes only the complete canonical v1 carrier and revalidates the reconstructed record. */ + public static RealmPolicyPublishedEvidence.PublishedSet decode(byte[] encoded) { + if (encoded == null || encoded.length == 0 || encoded.length > MAX_ENVELOPE_BYTES) { + throw new IllegalArgumentException( + "Complete bounded published realm-policy carrier required"); + } + try { + var reader = new DraftAuthorizationFenceBinding.FrameReader(encoded); + reader.expect(SCHEMA); + byte[] payload = reader.bytes(); + reader.requireEnd(); + String json = strictUtf8(payload); + if (!Arrays.equals(payload, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw new IllegalArgumentException("Noncanonical published realm-policy carrier JSON"); + } + JsonNode root = JSON.readTree(json); + RealmPolicySource.fields( + root, + "schema", + "target", + "versionNumber", + "sourceCommitId", + "sourceEpoch", + "publishedReleaseBundleRef", + "publishedReleaseBundleDigest", + "publishWorkflowId", + "manifestHash", + "publicationVersionStateEpoch", + "operationBytesBase64", + "captureBytesBase64", + "terminalEvidenceBytesBase64", + "policyCount", + "policySetDigest", + "policies"); + if (!SCHEMA.equals(RealmPolicySource.text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported published realm-policy carrier schema"); + } + DraftCommitBinding.TargetProof target = target(root.get("target")); + int versionNumber = positiveInt(root, "versionNumber"); + UUID sourceCommitId = uuid(root, "sourceCommitId"); + String sourceEpoch = RealmPolicySource.text(root, "sourceEpoch"); + if (!sourceEpoch.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical source epoch required"); + } + String publishedReleaseBundleRef = RealmPolicySource.text(root, "publishedReleaseBundleRef"); + String publishedReleaseBundleDigest = + RealmPolicySource.text(root, "publishedReleaseBundleDigest"); + String publishWorkflowId = RealmPolicySource.text(root, "publishWorkflowId"); + String manifestHash = RealmPolicySource.text(root, "manifestHash"); + long publicationVersionStateEpoch = positiveLong(root, "publicationVersionStateEpoch"); + byte[] operationBytes = base64(root, "operationBytesBase64"); + byte[] captureBytes = base64(root, "captureBytesBase64"); + byte[] terminalEvidenceBytes = base64(root, "terminalEvidenceBytesBase64"); + int policyCount = positiveInt(root, "policyCount"); + if (policyCount > RealmPolicySource.MAX_POLICIES) { + throw new IllegalArgumentException("Published policy count exceeds the source limit"); + } + String policySetDigest = RealmPolicySource.text(root, "policySetDigest"); + List policies = policies(root.get("policies")); + var evidence = + new RealmPolicyPublishedEvidence.PublishedSet( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policyCount, + policySetDigest, + policies); + if (!Arrays.equals(encoded, encode(evidence))) { + throw new IllegalArgumentException("Noncanonical published realm-policy carrier frame"); + } + return evidence; + } catch (IOException malformed) { + throw new IllegalArgumentException("Malformed published realm-policy carrier", malformed); + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException invalid) { + throw invalid; + } + throw new IllegalArgumentException("Malformed published realm-policy carrier", malformed); + } + } + + private static String canonicalPayload(RealmPolicyPublishedEvidence.PublishedSet evidence) { + var target = evidence.target(); + var targetJson = + map( + "canonicalTenantId", target.canonicalTenantId().toString(), + "canonicalVersionId", target.canonicalVersionId().toString(), + "gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId()), + "gameDesignVersionTenantKey", target.gameDesignVersionTenantKey(), + "sourceGameRowId", Long.toString(target.sourceGameRowId()), + "sourceGameTenantKey", target.sourceGameTenantKey(), + "sourceProvenanceKind", target.sourceProvenanceKind()); + var policies = + evidence.policies().stream() + .map( + policy -> + map( + "policyId", policy.policyId().toString(), + "source", + map( + "commitId", policy.source().commitId().toString(), + "revisionId", policy.source().revisionId().toString(), + "logicalRevisionId", policy.source().logicalRevisionId(), + "canonicalPolicyJson", policy.source().policy().canonicalJson()), + "policyDigest", policy.policyDigest())) + .toList(); + return RealmPolicySource.canonical( + map( + "schema", SCHEMA, + "target", targetJson, + "versionNumber", Integer.toString(evidence.versionNumber()), + "sourceCommitId", evidence.sourceCommitId().toString(), + "sourceEpoch", evidence.sourceEpoch(), + "publishedReleaseBundleRef", evidence.publishedReleaseBundleRef(), + "publishedReleaseBundleDigest", evidence.publishedReleaseBundleDigest(), + "publishWorkflowId", evidence.publishWorkflowId(), + "manifestHash", evidence.manifestHash(), + "publicationVersionStateEpoch", Long.toString(evidence.publicationVersionStateEpoch()), + "operationBytesBase64", BASE64_ENCODER.encodeToString(evidence.operationBytes()), + "captureBytesBase64", BASE64_ENCODER.encodeToString(evidence.captureBytes()), + "terminalEvidenceBytesBase64", + BASE64_ENCODER.encodeToString(evidence.terminalEvidenceBytes()), + "policyCount", Integer.toString(evidence.policyCount()), + "policySetDigest", evidence.policySetDigest(), + "policies", policies)); + } + + private static DraftCommitBinding.TargetProof target(JsonNode node) { + RealmPolicySource.fields( + node, + "canonicalTenantId", + "canonicalVersionId", + "gameDesignVersionRowId", + "gameDesignVersionTenantKey", + "sourceGameRowId", + "sourceGameTenantKey", + "sourceProvenanceKind"); + return new DraftCommitBinding.TargetProof( + uuid(node, "canonicalTenantId"), + uuid(node, "canonicalVersionId"), + positiveLong(node, "gameDesignVersionRowId"), + RealmPolicySource.text(node, "gameDesignVersionTenantKey"), + positiveLong(node, "sourceGameRowId"), + RealmPolicySource.text(node, "sourceGameTenantKey"), + RealmPolicySource.text(node, "sourceProvenanceKind")); + } + + private static List policies(JsonNode node) { + if (node == null + || !node.isArray() + || node.size() < 1 + || node.size() > RealmPolicySource.MAX_POLICIES) { + throw new IllegalArgumentException("Complete bounded published policy list required"); + } + var result = new ArrayList(node.size()); + for (JsonNode policyNode : node) { + RealmPolicySource.fields(policyNode, "policyId", "source", "policyDigest"); + JsonNode sourceNode = policyNode.get("source"); + RealmPolicySource.fields( + sourceNode, "commitId", "revisionId", "logicalRevisionId", "canonicalPolicyJson"); + RealmEntryPolicy policy = + RealmEntryPolicy.parseCanonical( + RealmPolicySource.text(sourceNode, "canonicalPolicyJson"), JSON); + result.add( + new RealmPolicyPublishedEvidence.Policy( + uuid(policyNode, "policyId"), + new RealmPolicySource.Policy( + uuid(sourceNode, "commitId"), + uuid(sourceNode, "revisionId"), + RealmPolicySource.text(sourceNode, "logicalRevisionId"), + policy), + RealmPolicySource.text(policyNode, "policyDigest"))); + } + return List.copyOf(result); + } + + private static byte[] base64(JsonNode object, String field) { + String encoded = RealmPolicySource.text(object, field); + final byte[] decoded; + try { + decoded = BASE64_DECODER.decode(encoded); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException("Canonical base64 required: " + field, malformed); + } + if (!BASE64_ENCODER.encodeToString(decoded).equals(encoded)) { + throw new IllegalArgumentException("Canonical base64 required: " + field); + } + return decoded; + } + + private static UUID uuid(JsonNode object, String field) { + String encoded = RealmPolicySource.text(object, field); + try { + UUID parsed = UUID.fromString(encoded); + if (!parsed.toString().equals(encoded) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil UUID required: " + field); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException("Canonical non-nil UUID required: " + field, malformed); + } + } + + private static int positiveInt(JsonNode object, String field) { + String value = RealmPolicySource.text(object, field); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical positive counter required: " + field); + } + try { + int parsed = Integer.parseInt(value); + if (parsed <= 0 || !Integer.toString(parsed).equals(value)) { + throw new IllegalArgumentException("Canonical positive counter required: " + field); + } + return parsed; + } catch (NumberFormatException malformed) { + throw new IllegalArgumentException( + "Canonical positive counter required: " + field, malformed); + } + } + + private static long positiveLong(JsonNode object, String field) { + String value = RealmPolicySource.text(object, field); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical positive counter required: " + field); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException("Canonical positive counter required: " + field); + } + return parsed; + } catch (NumberFormatException malformed) { + throw new IllegalArgumentException( + "Canonical positive counter required: " + field, malformed); + } + } + + private static String strictUtf8(byte[] bytes) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } + + private static Map map(Object... entries) { + if (entries.length % 2 != 0) { + throw new IllegalArgumentException("Even carrier key/value entries required"); + } + var result = new LinkedHashMap(); + for (int i = 0; i < entries.length; i += 2) { + result.put((String) entries[i], entries[i + 1]); + } + return result; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionPublishedRealmPolicyReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionPublishedRealmPolicyReadGrpcCodec.java new file mode 100644 index 0000000000..37bcc1300c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionPublishedRealmPolicyReadGrpcCodec.java @@ -0,0 +1,534 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionPublishedRealmPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionPublishedRealmPolicyResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** Closed transport mapping for the authenticated exact StartSession published-policy read. */ +public final class StartSessionPublishedRealmPolicyReadGrpcCodec { + public static final int REQUEST_SCHEMA_VERSION = 1; + public static final int RESPONSE_SCHEMA_VERSION = 1; + + /** 256 KiB exact authorization tuple plus the bounded descriptor/release projection budget. */ + public static final int MAX_REQUEST_WIRE_BYTES = 4 * 1024 * 1024; + + /** 32 MiB policy carrier plus 8 MiB for association, source, and release framing. */ + public static final int MAX_RESPONSE_WIRE_BYTES = + RealmPolicyPublishedEvidenceCodec.MAX_ENVELOPE_BYTES + 8 * 1024 * 1024; + + public static final int MAX_WIRE_BYTES = MAX_RESPONSE_WIRE_BYTES; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + /** Exact request the Game Session caller intends to replay and disclose. */ + public record ReadRequest( + String targetNamespace, + UUID readRequestId, + Request authorizationRequest, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation, + DraftCommitBinding.TargetProof target) { + public ReadRequest { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(readRequestId, "readRequestId"); + Objects.requireNonNull(authorizationRequest, "authorizationRequest"); + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(releaseAttestation, "releaseAttestation"); + Objects.requireNonNull(target, "target"); + requireExactReplay(authorizationRequest); + if (!targetNamespace.equals(authorizationRequest.targetNamespace()) + || !targetNamespace.equals(descriptor.targetNamespace())) { + throw new IllegalArgumentException("Exact same-namespace request required"); + } + if (readRequestId.equals(authorizationRequest.readRequestId()) + || readRequestId.equals(authorizationRequest.ownerAttemptId()) + || readRequestId.equals(descriptor.authoredWorldSourceOperationId()) + || readRequestId.toString().equals(descriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException("Independent canonical read request ID required"); + } + descriptor.requireValid(); + releaseAttestation.requireValid(descriptor); + if (!descriptor.canonicalTenantId().equals(target.canonicalTenantId()) + || !releaseAttestation.canonicalVersionId().equals(target.canonicalVersionId()) + || descriptor.versionId() != target.gameDesignVersionRowId()) { + throw new IllegalArgumentException("Exact descriptor, release, and TargetProof required"); + } + } + } + + /** Structurally decoded request. Descriptor semantics wait until Account confirms the replay. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Generated protobuf messages are immutable; retain the exact original request.") + public record WireRequest( + ReadStartSessionPublishedRealmPolicyRequest message, + UUID readRequestId, + Request authorizationRequest, + DraftCommitBinding.TargetProof target) { + public WireRequest { + Objects.requireNonNull(message, "message"); + Objects.requireNonNull(readRequestId, "readRequestId"); + Objects.requireNonNull(authorizationRequest, "authorizationRequest"); + Objects.requireNonNull(target, "target"); + } + } + + /** Complete validated authorization, source, and published immutable policy response. */ + public record ReadResult( + ReadRequest request, + Result authorizationResult, + AuthoredWorldSourceEvidence sourceEvidence, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + public ReadResult { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(authorizationResult, "authorizationResult"); + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + Objects.requireNonNull(publishedSet, "publishedSet"); + } + } + + private StartSessionPublishedRealmPolicyReadGrpcCodec() {} + + public static ReadStartSessionPublishedRealmPolicyRequest toRequest(ReadRequest request) { + Objects.requireNonNull(request, "request"); + ReadStartSessionPublishedRealmPolicyRequest message = + ReadStartSessionPublishedRealmPolicyRequest.newBuilder() + .setSchemaVersion(REQUEST_SCHEMA_VERSION) + .setTargetNamespace(request.targetNamespace()) + .setReadRequestId(request.readRequestId().toString()) + .setAuthorizationRequest( + StartSessionLaunchDescriptorGrpcCodec.toRequest(request.authorizationRequest())) + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + request.descriptor())) + .setReleaseAttestation( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation( + request.releaseAttestation())) + .setCanonicalTargetProofJson( + com.google.protobuf.ByteString.copyFrom( + RealmPolicyPublishedEvidence.targetProofJson(request.target()), + StandardCharsets.UTF_8)) + .build(); + requireRequestSerializedSize(message); + return message; + } + + /** Decode structure and the unchanged authorization request only after peer authentication. */ + public static WireRequest fromRequest(ReadStartSessionPublishedRealmPolicyRequest message) { + Objects.requireNonNull(message, "message"); + requireNoUnknownFields(message, "ReadStartSessionPublishedRealmPolicyRequest"); + requireRequestSerializedSize(message); + if (message.getSchemaVersion() != REQUEST_SCHEMA_VERSION + || !message.hasAuthorizationRequest() + || !message.hasLaunchDescriptor() + || !message.hasReleaseAttestation() + || message.getCanonicalTargetProofJson().isEmpty()) { + throw new IllegalArgumentException("Complete schema-1 published-policy request required"); + } + Request authorization = + StartSessionLaunchDescriptorGrpcCodec.fromRequest(message.getAuthorizationRequest()); + UUID readRequestId = parseCanonicalNonNilUuid(message.getReadRequestId(), "readRequestId"); + if (!message.getTargetNamespace().equals(authorization.targetNamespace()) + || readRequestId.equals(authorization.readRequestId()) + || readRequestId.equals(authorization.ownerAttemptId())) { + throw new IllegalArgumentException("Exact namespace and independent read ID required"); + } + DraftCommitBinding.TargetProof target = + decodeTargetProof(message.getCanonicalTargetProofJson().toByteArray()); + return new WireRequest(message, readRequestId, authorization, target); + } + + /** + * After Account's exact association read succeeds, reuse the complete launch and release codecs + * to bind every supplied immutable value to that exact association. + */ + public static ReadRequest authorize(WireRequest request, Result authorizationResult) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(authorizationResult, "authorizationResult"); + if (!request.authorizationRequest().equals(authorizationResult.request())) { + throw new IllegalArgumentException("Account-confirmed request differs from exact replay"); + } + var associationResponse = + StartSessionTemplateAssociationReadGrpcCodec.toResponse(authorizationResult); + var descriptorResponse = + ResolveStartSessionLaunchDescriptorResponse.newBuilder() + .setSchemaVersion(StartSessionLaunchDescriptorGrpcCodec.RESPONSE_SCHEMA_VERSION) + .setAssociationRead(associationResponse) + .setLaunchDescriptor(request.message().getLaunchDescriptor()) + .build(); + var resolved = + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + request.authorizationRequest(), descriptorResponse); + if (!(resolved.outcome() instanceof StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome)) { + throw new IllegalArgumentException("Exact launch descriptor required"); + } + var descriptorAndRelease = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteEvidenceMessages( + ((StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome) resolved.outcome()) + .descriptor() + .request(), + request.message().getLaunchDescriptor(), + request.message().getReleaseAttestation()); + if (!descriptorAndRelease + .descriptor() + .equals( + ((StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome) resolved.outcome()) + .descriptor())) { + throw new IllegalArgumentException("Complete descriptor evidence changed during decoding"); + } + ReadRequest authorized = + new ReadRequest( + request.message().getTargetNamespace(), + request.readRequestId(), + request.authorizationRequest(), + descriptorAndRelease.descriptor(), + descriptorAndRelease.releaseAttestation(), + request.target()); + requireAssociationBinding(authorized, authorizationResult); + return authorized; + } + + /** + * Encodes a complete owner result, then runs the exact consumer validation before returning it. + */ + public static ReadStartSessionPublishedRealmPolicyResponse toResponse( + WireRequest wireRequest, + ReadRequest authorizedRequest, + Result authorizationResult, + AuthoredWorldSourceEvidence sourceEvidence, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + Objects.requireNonNull(wireRequest, "wireRequest"); + Objects.requireNonNull(authorizedRequest, "authorizedRequest"); + Objects.requireNonNull(authorizationResult, "authorizationResult"); + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + Objects.requireNonNull(publishedSet, "publishedSet"); + if (!authorizedRequest.authorizationRequest().equals(authorizationResult.request()) + || !authorizedRequest.equals(authorize(wireRequest, authorizationResult))) { + throw new IllegalArgumentException("Exact Account-confirmed request required"); + } + ReadStartSessionPublishedRealmPolicyResponse response = + ReadStartSessionPublishedRealmPolicyResponse.newBuilder() + .setSchemaVersion(RESPONSE_SCHEMA_VERSION) + .setRequest(wireRequest.message()) + .setAuthorizationResponse( + StartSessionTemplateAssociationReadGrpcCodec.toResponse(authorizationResult)) + .setSourceEvidence( + AuthoredWorldSourceGrpcCodec.toReadResponse( + sourceRequest(authorizedRequest), sourceEvidence)) + .setPublishedPolicySet( + com.google.protobuf.ByteString.copyFrom( + RealmPolicyPublishedEvidenceCodec.encode(publishedSet))) + .build(); + requireResponseSerializedSize(response); + fromResponse(wireRequest, response); + return response; + } + + /** + * Validates the whole echo, nested Account correlation, source read, TargetProof, and carrier. + */ + public static ReadResult fromResponse( + WireRequest expectedRequest, ReadStartSessionPublishedRealmPolicyResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadStartSessionPublishedRealmPolicyResponse"); + requireResponseSerializedSize(response); + if (response.getSchemaVersion() != RESPONSE_SCHEMA_VERSION + || !response.hasRequest() + || !response.hasAuthorizationResponse() + || !response.hasSourceEvidence() + || response.getPublishedPolicySet().isEmpty() + || !expectedRequest.message().equals(response.getRequest())) { + throw new IllegalArgumentException("Complete exact published-policy response required"); + } + Result authorizationResult = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + expectedRequest.authorizationRequest(), response.getAuthorizationResponse()); + ReadRequest authorized = authorize(expectedRequest, authorizationResult); + AuthoredWorldSourceEvidence source = + AuthoredWorldSourceGrpcCodec.fromReadResponse( + sourceRequest(authorized), response.getSourceEvidence()); + requireSourceBinding(authorized, source); + RealmPolicyPublishedEvidence.PublishedSet publishedSet = + RealmPolicyPublishedEvidenceCodec.decode(response.getPublishedPolicySet().toByteArray()); + requirePublishedSetBinding(authorized, authorizationResult, source, publishedSet); + return new ReadResult(authorized, authorizationResult, source, publishedSet); + } + + public static AuthoredWorldSourceGrpcCodec.ReadRequest sourceRequest(ReadRequest request) { + Objects.requireNonNull(request, "request"); + return new AuthoredWorldSourceGrpcCodec.ReadRequest( + request.targetNamespace(), + request.readRequestId(), + request.descriptor().authoredWorldSourceOperationId(), + request.descriptor().canonicalTenantId(), + request.descriptor().worldSlug()); + } + + public static AuthoredWorldSourceGrpcCodec.ReadRequest sourceRequest( + WireRequest request, AuthoredWorldLaunchDescriptorEvidence descriptor) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(descriptor, "descriptor"); + return new AuthoredWorldSourceGrpcCodec.ReadRequest( + request.message().getTargetNamespace(), + request.readRequestId(), + descriptor.authoredWorldSourceOperationId(), + descriptor.canonicalTenantId(), + descriptor.worldSlug()); + } + + public static void requireRequestSerializedSize(Message message) { + Objects.requireNonNull(message, "message"); + if (message.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) { + throw new IllegalArgumentException("Published-policy request exceeds the 4 MiB bound"); + } + if (message instanceof ReadStartSessionPublishedRealmPolicyRequest request + && request.hasAuthorizationRequest() + && request.getAuthorizationRequest().getCanonicalPostAuthorizationTuple().size() + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException("Exact StartSession tuple exceeds its canonical bound"); + } + } + + public static void requireResponseSerializedSize(Message message) { + Objects.requireNonNull(message, "message"); + if (message.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) { + throw new IllegalArgumentException("Published-policy response exceeds the 40 MiB bound"); + } + } + + private static void requireAssociationBinding(ReadRequest request, Result authorizationResult) { + var association = authorizationResult.association(); + var release = request.releaseAttestation(); + var descriptor = request.descriptor(); + var replay = + (StartSessionTemplateAssociationReadEvidence.ExactReplay) + request.authorizationRequest().selection(); + if (!authorizationResult.request().equals(request.authorizationRequest()) + || !request.targetNamespace().equals(association.targetNamespace()) + || !request.targetNamespace().equals(release.targetNamespace()) + || !request.targetNamespace().equals(descriptor.targetNamespace()) + || !association.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !association.canonicalTenantId().equals(request.target().canonicalTenantId()) + || !association.canonicalVersionId().equals(replay.canonicalVersionId()) + || !association.canonicalVersionId().equals(release.canonicalVersionId()) + || !association.canonicalVersionId().equals(request.target().canonicalVersionId()) + || association.templateId() != descriptor.gameTemplateId() + || association.templateId() + != request + .authorizationRequest() + .decodedTuple() + .preAuthorizationTuple() + .action() + .target() + .gameTemplateId() + || !association.worldSlug().equals(descriptor.worldSlug()) + || !association.sourceOperationId().equals(descriptor.authoredWorldSourceOperationId()) + || !association.sourceOperationId().equals(release.authoredWorldSourceOperationId()) + || !association + .sourceEvidenceDigest() + .equals(descriptor.authoredWorldSourceEvidenceDigest()) + || !association.sourceEvidenceDigest().equals(release.authoredWorldSourceEvidenceDigest()) + || !association.publishWorkflowId().equals(replay.publishWorkflowId()) + || !association.publishWorkflowId().equals(release.publishWorkflowId()) + || !association.selectedCommitId().equals(replay.selectedCommitId()) + || !association.selectedCommitId().toString().equals(release.commitId()) + || !association.associationDigest().equals(replay.associationDigest()) + || request.target().gameDesignVersionRowId() != descriptor.versionId() + || !descriptor.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef())) { + throw new IllegalArgumentException( + "Account-confirmed association differs from exact descriptor, release, or TargetProof"); + } + var releaseBundle = authorizationResult.releaseBundle(); + if (releaseBundle.getVersionId() != descriptor.versionId() + || !releaseBundle + .getPublishedReleaseBundleRef() + .equals(descriptor.publishedReleaseBundleRef()) + || !releaseBundle.getPublishWorkflowId().equals(release.publishWorkflowId()) + || !releaseBundle.getCanonicalVersionId().equals(release.canonicalVersionId().toString())) { + throw new IllegalArgumentException( + "Association release bundle differs from exact attestation"); + } + } + + private static void requireSourceBinding( + ReadRequest request, AuthoredWorldSourceEvidence source) { + var descriptor = request.descriptor(); + var target = request.target(); + if (!request.targetNamespace().equals(source.targetNamespace()) + || !descriptor.authoredWorldSourceOperationId().equals(source.operationId()) + || !descriptor.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest()) + || !descriptor.canonicalTenantId().equals(source.canonicalTenantId()) + || !descriptor.worldSlug().equals(source.worldSlug()) + || source.sourceGameRowId() != target.sourceGameRowId() + || !source.sourceGameTenantKey().equals(target.sourceGameTenantKey()) + || !source.provenanceKind().equals(target.sourceProvenanceKind())) { + throw new IllegalArgumentException("Exact authored-world source does not match TargetProof"); + } + } + + private static void requirePublishedSetBinding( + ReadRequest request, + Result authorizationResult, + AuthoredWorldSourceEvidence source, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + requireAssociationBinding(request, authorizationResult); + requireSourceBinding(request, source); + var descriptor = request.descriptor(); + var release = request.releaseAttestation(); + var target = request.target(); + if (!target.equals(publishedSet.target()) + || !descriptor.canonicalTenantId().equals(target.canonicalTenantId()) + || !release.canonicalVersionId().equals(target.canonicalVersionId()) + || descriptor.versionId() != target.gameDesignVersionRowId() + || !publishedSet.publishedReleaseBundleRef().equals(descriptor.publishedReleaseBundleRef()) + || !publishedSet.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef()) + || !publishedSet.publishWorkflowId().equals(release.publishWorkflowId()) + || !publishedSet.manifestHash().equals(release.manifestHash()) + || !publishedSet.sourceCommitId().toString().equals(release.commitId()) + || publishedSet.publicationVersionStateEpoch() > descriptor.versionStateEpoch() + || publishedSet.publicationVersionStateEpoch() > release.versionStateEpoch()) { + throw new IllegalArgumentException( + "Published policy set differs from exact TargetProof, release, or publication epoch"); + } + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(publishedSet.terminalEvidenceBytes()); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || terminal.publicationVersionStateEpoch() != publishedSet.publicationVersionStateEpoch() + || !terminal.publishedReleaseBundleRef().equals(publishedSet.publishedReleaseBundleRef()) + || !terminal + .publishedReleaseBundleDigest() + .equals(publishedSet.publishedReleaseBundleDigest()) + || !terminal.releaseContent().publishWorkflowId().equals(release.publishWorkflowId()) + || !terminal.releaseContent().canonicalTenantId().equals(target.canonicalTenantId()) + || !terminal.releaseContent().canonicalVersionId().equals(target.canonicalVersionId())) { + throw new IllegalArgumentException( + "Canonical published terminal does not bind exact policy set"); + } + } + + private static DraftCommitBinding.TargetProof decodeTargetProof(byte[] canonicalJson) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(canonicalJson)) + .toString(); + JsonNode node = JSON.readTree(json); + RealmPolicySource.fields( + node, + "canonicalTenantId", + "canonicalVersionId", + "gameDesignVersionRowId", + "gameDesignVersionTenantKey", + "sourceGameRowId", + "sourceGameTenantKey", + "sourceProvenanceKind"); + DraftCommitBinding.TargetProof target = + new DraftCommitBinding.TargetProof( + parseCanonicalNonNilUuid( + RealmPolicySource.text(node, "canonicalTenantId"), "canonicalTenantId"), + parseCanonicalNonNilUuid( + RealmPolicySource.text(node, "canonicalVersionId"), "canonicalVersionId"), + canonicalPositiveDecimal(node, "gameDesignVersionRowId"), + RealmPolicySource.text(node, "gameDesignVersionTenantKey"), + canonicalPositiveDecimal(node, "sourceGameRowId"), + RealmPolicySource.text(node, "sourceGameTenantKey"), + RealmPolicySource.text(node, "sourceProvenanceKind")); + if (!Arrays.equals( + canonicalJson, + RealmPolicyPublishedEvidence.targetProofJson(target).getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("Noncanonical complete TargetProof required"); + } + return target; + } catch (java.io.IOException invalid) { + throw new IllegalArgumentException("Canonical seven-field TargetProof required", invalid); + } + } + + private static long canonicalPositiveDecimal(JsonNode node, String field) { + String value = RealmPolicySource.text(node, field); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException(field + " must be canonical positive decimal text"); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(field + " must be canonical positive decimal text"); + } + return parsed; + } catch (NumberFormatException invalid) { + throw new IllegalArgumentException(field + " exceeds the positive 64-bit range", invalid); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(Objects.requireNonNull(value, field)); + requireNonNil(parsed, field); + if (!parsed.toString().equals(value)) { + throw new IllegalArgumentException(field + " must be canonical lowercase UUID text"); + } + return parsed; + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID", invalid); + } + } + + private static void requireExactReplay(Request request) { + if (!(request.selection() instanceof StartSessionTemplateAssociationReadEvidence.ExactReplay)) { + throw new IllegalArgumentException("Exact Account-confirmed StartSession replay required"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) continue; + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } + + private static void requireNonNil(UUID value, String field) { + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a non-nil UUID"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java index 2be666331d..0aef2322b5 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java @@ -27,7 +27,7 @@ import org.junit.jupiter.api.Test; import tools.jackson.databind.json.JsonMapper; -class StartSessionLaunchDescriptorGrpcCodecTest { +public class StartSessionLaunchDescriptorGrpcCodecTest { private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); @@ -275,7 +275,7 @@ void rejectsDescriptorFieldsThatDoNotMatchTheOriginalAssociationAndRelease() thr .isInstanceOf(IllegalArgumentException.class); } - private static Fixture fixture() throws Exception { + public static Fixture fixture() throws Exception { var worldEvidence = AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); UUID canonicalVersion = worldEvidence.request().canonicalVersionId(); UUID selectedCommit = uuid(worldEvidence.request().appliedCommitId()); @@ -522,6 +522,6 @@ private static UUID uuid(String value) { return UUID.fromString(value); } - private record Fixture( + public record Fixture( Request request, Result associationRead, AuthoredWorldLaunchDescriptorEvidence descriptor) {} } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmPolicyPublishedEvidenceCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmPolicyPublishedEvidenceCodecTest.java new file mode 100644 index 0000000000..f8234a7b4a --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmPolicyPublishedEvidenceCodecTest.java @@ -0,0 +1,413 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +class RealmPolicyPublishedEvidenceCodecTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final UUID FIRST_POLICY_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SECOND_POLICY_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID FIRST_REVISION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID SECOND_REVISION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void roundTripsCompletePublishedSetAndPreservesEveryFieldAndDefensiveBytes() throws Exception { + var original = publishedSet(); + var encoded = RealmPolicyPublishedEvidenceCodec.encode(original); + var decoded = RealmPolicyPublishedEvidenceCodec.decode(encoded); + + assertThat(RealmPolicyPublishedEvidenceCodec.encode(decoded)).containsExactly(encoded); + assertThat(decoded.target()).isEqualTo(original.target()); + assertThat(decoded.versionNumber()).isEqualTo(original.versionNumber()); + assertThat(decoded.sourceCommitId()).isEqualTo(original.sourceCommitId()); + assertThat(decoded.sourceEpoch()).isEqualTo(original.sourceEpoch()); + assertThat(decoded.publishedReleaseBundleRef()).isEqualTo(original.publishedReleaseBundleRef()); + assertThat(decoded.publishedReleaseBundleDigest()) + .isEqualTo(original.publishedReleaseBundleDigest()); + assertThat(decoded.publishWorkflowId()).isEqualTo(original.publishWorkflowId()); + assertThat(decoded.manifestHash()).isEqualTo(original.manifestHash()); + assertThat(decoded.publicationVersionStateEpoch()) + .isEqualTo(original.publicationVersionStateEpoch()); + assertThat(decoded.operationBytes()).containsExactly(original.operationBytes()); + assertThat(decoded.captureBytes()).containsExactly(original.captureBytes()); + assertThat(decoded.terminalEvidenceBytes()).containsExactly(original.terminalEvidenceBytes()); + assertThat(decoded.policyCount()).isEqualTo(original.policyCount()); + assertThat(decoded.policySetDigest()).isEqualTo(original.policySetDigest()); + assertThat(decoded.policies()).containsExactlyElementsOf(original.policies()); + + byte[] returnedOperation = decoded.operationBytes(); + byte[] returnedCapture = decoded.captureBytes(); + byte[] returnedTerminal = decoded.terminalEvidenceBytes(); + Arrays.fill(returnedOperation, (byte) 0); + Arrays.fill(returnedCapture, (byte) 0); + Arrays.fill(returnedTerminal, (byte) 0); + assertThat(decoded.operationBytes()).containsExactly(original.operationBytes()); + assertThat(decoded.captureBytes()).containsExactly(original.captureBytes()); + assertThat(decoded.terminalEvidenceBytes()).containsExactly(original.terminalEvidenceBytes()); + + byte[] inputOperation = original.operationBytes(); + byte[] inputCapture = original.captureBytes(); + byte[] inputTerminal = original.terminalEvidenceBytes(); + var defensiveCopy = + new RealmPolicyPublishedEvidence.PublishedSet( + original.target(), + original.versionNumber(), + original.sourceCommitId(), + original.sourceEpoch(), + original.publishedReleaseBundleRef(), + original.publishedReleaseBundleDigest(), + original.publishWorkflowId(), + original.manifestHash(), + original.publicationVersionStateEpoch(), + inputOperation, + inputCapture, + inputTerminal, + original.policyCount(), + original.policySetDigest(), + original.policies()); + Arrays.fill(inputOperation, (byte) 0); + Arrays.fill(inputCapture, (byte) 0); + Arrays.fill(inputTerminal, (byte) 0); + assertThat(defensiveCopy.operationBytes()).containsExactly(original.operationBytes()); + assertThat(defensiveCopy.captureBytes()).containsExactly(original.captureBytes()); + assertThat(defensiveCopy.terminalEvidenceBytes()) + .containsExactly(original.terminalEvidenceBytes()); + } + + @Test + void rejectsPolicyPayloadSubstitutionWhenTheOriginalPolicyDigestIsUnchanged() throws Exception { + var original = publishedSet(); + var first = original.policies().getFirst(); + var substitutedSource = + new RealmPolicySource.Policy( + first.source().commitId(), + first.source().revisionId(), + first.source().logicalRevisionId(), + policy("realm-a", "Changed World", true)); + var substituted = + new RealmPolicyPublishedEvidence.Policy( + first.policyId(), substitutedSource, first.policyDigest()); + var changedPolicies = List.of(substituted, original.policies().get(1)); + + assertThatThrownBy( + () -> + copy( + original, original.target(), original.terminalEvidenceBytes(), changedPolicies)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("policy digest"); + } + + @Test + void rejectsPolicyMutationThatRecomputesDigestsButDiffersFromOriginalCapture() throws Exception { + var original = publishedSet(); + var first = original.policies().getFirst(); + var changedSource = + new RealmPolicySource.Policy( + first.source().commitId(), + first.source().revisionId(), + first.source().logicalRevisionId(), + policy("realm-a", "Changed World", true)); + var changedPolicy = + new RealmPolicyPublishedEvidence.Policy( + first.policyId(), + changedSource, + RealmPolicyPublishedEvidence.policyDigest( + first.policyId(), + original.target(), + original.versionNumber(), + original.publishedReleaseBundleRef(), + original.publishedReleaseBundleDigest(), + original.publishWorkflowId(), + original.manifestHash(), + changedSource)); + var changedPolicies = List.of(changedPolicy, original.policies().get(1)); + String changedSetDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + original.target(), + original.versionNumber(), + original.sourceCommitId(), + original.sourceEpoch(), + original.publishedReleaseBundleRef(), + original.publishedReleaseBundleDigest(), + original.publishWorkflowId(), + original.manifestHash(), + original.publicationVersionStateEpoch(), + original.operationBytes(), + original.captureBytes(), + original.terminalEvidenceBytes(), + changedPolicies); + + assertThatThrownBy( + () -> + new RealmPolicyPublishedEvidence.PublishedSet( + original.target(), + original.versionNumber(), + original.sourceCommitId(), + original.sourceEpoch(), + original.publishedReleaseBundleRef(), + original.publishedReleaseBundleDigest(), + original.publishWorkflowId(), + original.manifestHash(), + original.publicationVersionStateEpoch(), + original.operationBytes(), + original.captureBytes(), + original.terminalEvidenceBytes(), + changedPolicies.size(), + changedSetDigest, + changedPolicies)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("capture"); + } + + @Test + void rejectsChangedScopeAndChangedTerminalEvidence() throws Exception { + var original = publishedSet(); + var target = original.target(); + var changedTarget = + new DraftCommitBinding.TargetProof( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + target.canonicalVersionId(), + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()); + assertThatThrownBy( + () -> + copy( + original, changedTarget, original.terminalEvidenceBytes(), original.policies())) + .isInstanceOf(IllegalArgumentException.class); + + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + byte[] noPublicationTerminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.NO_PUBLICATION) + .canonicalBytes(); + assertThatThrownBy( + () -> copy(original, original.target(), noPublicationTerminal, original.policies())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsNoncanonicalSourceOrder() throws Exception { + var original = publishedSet(); + assertThatThrownBy( + () -> + copy( + original, + original.target(), + original.terminalEvidenceBytes(), + List.of(original.policies().get(1), original.policies().getFirst()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source order"); + } + + @Test + void rejectsMalformedUnknownMissingNoncanonicalTrailingAndOversizedInput() throws Exception { + var original = publishedSet(); + byte[] encoded = RealmPolicyPublishedEvidenceCodec.encode(original); + assertThatThrownBy(() -> RealmPolicyPublishedEvidenceCodec.decode(new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + RealmPolicyPublishedEvidenceCodec.decode( + Arrays.copyOf(encoded, encoded.length + 1))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + RealmPolicyPublishedEvidenceCodec.decode( + new byte[RealmPolicyPublishedEvidenceCodec.MAX_ENVELOPE_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class); + + assertRejectedPayload(original, root -> root.put("unsupported", "value")); + assertRejectedPayload(original, root -> root.remove("manifestHash")); + assertRejectedPayload( + original, + root -> + ((ObjectNode) root.get("target")) + .put("canonicalTenantId", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA")); + assertRejectedPayload(original, root -> root.put("versionNumber", "01")); + + byte[] payload = unframe(encoded); + byte[] noncanonicalJson = + (new String(payload, StandardCharsets.UTF_8) + " ").getBytes(StandardCharsets.UTF_8); + assertThatThrownBy(() -> RealmPolicyPublishedEvidenceCodec.decode(frame(noncanonicalJson))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertRejectedPayload( + RealmPolicyPublishedEvidence.PublishedSet evidence, + java.util.function.Consumer mutation) + throws Exception { + var root = + (ObjectNode) JSON.readTree(unframe(RealmPolicyPublishedEvidenceCodec.encode(evidence))); + mutation.accept(root); + byte[] payload = RealmPolicySource.canonical(root).getBytes(StandardCharsets.UTF_8); + assertThatThrownBy(() -> RealmPolicyPublishedEvidenceCodec.decode(frame(payload))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static RealmPolicyPublishedEvidence.PublishedSet publishedSet() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.PUBLISHED); + DraftCommitBinding selectedCommit = operation.account().input().selection().selectedCommit(); + var target = selectedCommit.target(); + var sources = + List.of( + new RealmPolicySource.Policy( + selectedCommit.commitId(), + FIRST_REVISION_ID, + "logical-realm-a", + policy("realm-a", "World", true)), + new RealmPolicySource.Policy( + selectedCommit.commitId(), + SECOND_REVISION_ID, + "logical-realm-b", + policy("realm-b", "World", false))); + var snapshot = + new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( + selectedCommit, "7", sources); + byte[] captureBytes = capture(operation.canonicalBytes(), snapshot.canonicalBytes()); + var release = terminal.releaseContent(); + var policies = + List.of( + new RealmPolicyPublishedEvidence.Policy( + FIRST_POLICY_ID, + sources.getFirst(), + RealmPolicyPublishedEvidence.policyDigest( + FIRST_POLICY_ID, + target, + release.versionNumber(), + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + sources.getFirst())), + new RealmPolicyPublishedEvidence.Policy( + SECOND_POLICY_ID, + sources.get(1), + RealmPolicyPublishedEvidence.policyDigest( + SECOND_POLICY_ID, + target, + release.versionNumber(), + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + sources.get(1)))); + byte[] operationBytes = operation.canonicalBytes(); + byte[] terminalBytes = terminal.canonicalBytes(); + String policySetDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + release.versionNumber(), + selectedCommit.commitId(), + snapshot.sourceEpoch(), + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operationBytes, + captureBytes, + terminalBytes, + policies); + return new RealmPolicyPublishedEvidence.PublishedSet( + target, + release.versionNumber(), + selectedCommit.commitId(), + snapshot.sourceEpoch(), + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operationBytes, + captureBytes, + terminalBytes, + policies.size(), + policySetDigest, + policies); + } + + private static RealmPolicyPublishedEvidence.PublishedSet copy( + RealmPolicyPublishedEvidence.PublishedSet evidence, + DraftCommitBinding.TargetProof target, + byte[] terminalEvidenceBytes, + List policies) { + return new RealmPolicyPublishedEvidence.PublishedSet( + target, + evidence.versionNumber(), + evidence.sourceCommitId(), + evidence.sourceEpoch(), + evidence.publishedReleaseBundleRef(), + evidence.publishedReleaseBundleDigest(), + evidence.publishWorkflowId(), + evidence.manifestHash(), + evidence.publicationVersionStateEpoch(), + evidence.operationBytes(), + evidence.captureBytes(), + terminalEvidenceBytes, + policies.size(), + evidence.policySetDigest(), + policies); + } + + private static RealmEntryPolicy policy( + String realmSlug, String worldDisplayName, boolean production) { + return RealmEntryPolicy.parse( + "{\"entryPolicy\":\"PRESEEDED_ONLY\",\"publicProduction\":" + + production + + ",\"realmDisplayName\":\"" + + realmSlug + + "\",\"realmSlug\":\"" + + realmSlug + + "\",\"schemaVersion\":1,\"stateScope\":\"SHARED\",\"visible\":true," + + "\"worldDisplayName\":\"" + + worldDisplayName + + "\",\"worldSlug\":\"world\"}", + JSON); + } + + private static byte[] capture(byte[] operationBytes, byte[] snapshotBytes) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-realm-policy-source-capture/v1"); + DraftAuthorizationFenceBinding.frame(out, operationBytes); + DraftAuthorizationFenceBinding.frame(out, snapshotBytes); + return out.toByteArray(); + } + + private static byte[] unframe(byte[] encoded) { + var reader = new DraftAuthorizationFenceBinding.FrameReader(encoded); + reader.expect(RealmPolicyPublishedEvidenceCodec.SCHEMA); + byte[] payload = reader.bytes(); + reader.requireEnd(); + return payload; + } + + private static byte[] frame(byte[] payload) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, RealmPolicyPublishedEvidenceCodec.SCHEMA); + DraftAuthorizationFenceBinding.frame(out, payload); + return out.toByteArray(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/StartSessionPublishedRealmPolicyReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/StartSessionPublishedRealmPolicyReadGrpcCodecTest.java new file mode 100644 index 0000000000..1ec30b81a3 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/StartSessionPublishedRealmPolicyReadGrpcCodecTest.java @@ -0,0 +1,539 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodecTest; +import net.firedevops.firemud.common.gamedesign.StartSessionPublishedRealmPolicyReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionPublishedRealmPolicyResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +/** + * Common structural codec units. Vectors combine the existing exact-replay descriptor fixture with + * actual canonical publication operation and terminal bytes; they are not a database, running + * server, or production-producer proof. + */ +class StartSessionPublishedRealmPolicyReadGrpcCodecTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final UUID FIRST_POLICY_ID = + UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID SECOND_POLICY_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID FIRST_REVISION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID SECOND_REVISION_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void roundTripsTheCompleteExactReplayRequestAndOwnerResponseWithoutNestedMockDecoders() + throws Exception { + Fixture fixture = fixture(); + + var decoded = + StartSessionPublishedRealmPolicyReadGrpcCodec.fromResponse( + fixture.wireRequest(), fixture.response()); + + assertThat( + StartSessionPublishedRealmPolicyReadGrpcCodec.fromRequest( + StartSessionPublishedRealmPolicyReadGrpcCodec.toRequest(fixture.request()))) + .isEqualTo(fixture.wireRequest()); + assertThat(decoded.request().targetNamespace()).isEqualTo(fixture.request().targetNamespace()); + assertThat(decoded.request().readRequestId()).isEqualTo(fixture.request().readRequestId()); + assertThat(decoded.request().authorizationRequest()) + .isEqualTo(fixture.request().authorizationRequest()); + assertThat(decoded.request().descriptor()).isEqualTo(fixture.request().descriptor()); + assertThat(decoded.request().releaseAttestation().evidenceDigest()) + .isEqualTo(fixture.request().releaseAttestation().evidenceDigest()); + assertThat(decoded.request().target()).isEqualTo(fixture.request().target()); + assertThat(decoded.authorizationResult().request()) + .isEqualTo(fixture.authorizationResult().request()); + assertThat(decoded.authorizationResult().association().associationDigest()) + .isEqualTo(fixture.authorizationResult().association().associationDigest()); + assertThat(decoded.authorizationResult().association().selectedCommitId()) + .isEqualTo(fixture.authorizationResult().association().selectedCommitId()); + assertThat(decoded.authorizationResult().association().publishWorkflowId()) + .isEqualTo(fixture.authorizationResult().association().publishWorkflowId()); + assertThat(decoded.authorizationResult().releaseBundle()) + .isEqualTo(fixture.authorizationResult().releaseBundle()); + assertThat(decoded.authorizationResult().worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly( + fixture.authorizationResult().worldPublishedStartLocationEvidence().canonicalBytes()); + assertThat(decoded.authorizationResult().phaseEpoch()) + .isEqualTo(fixture.authorizationResult().phaseEpoch()); + assertThat(decoded.sourceEvidence()).isEqualTo(fixture.sourceEvidence()); + assertThat(decoded.publishedSet().target()).isEqualTo(fixture.publishedSet().target()); + assertThat(decoded.publishedSet().sourceCommitId()) + .isEqualTo(fixture.publishedSet().sourceCommitId()); + assertThat(decoded.publishedSet().sourceEpoch()) + .isEqualTo(fixture.publishedSet().sourceEpoch()); + assertThat(decoded.publishedSet().publishedReleaseBundleRef()) + .isEqualTo(fixture.publishedSet().publishedReleaseBundleRef()); + assertThat(decoded.publishedSet().publishedReleaseBundleDigest()) + .isEqualTo(fixture.publishedSet().publishedReleaseBundleDigest()); + assertThat(decoded.publishedSet().publishWorkflowId()) + .isEqualTo(fixture.publishedSet().publishWorkflowId()); + assertThat(decoded.publishedSet().manifestHash()) + .isEqualTo(fixture.publishedSet().manifestHash()); + assertThat(decoded.publishedSet().publicationVersionStateEpoch()) + .isEqualTo(fixture.publishedSet().publicationVersionStateEpoch()); + assertThat(decoded.publishedSet().operationBytes()) + .containsExactly(fixture.publishedSet().operationBytes()); + assertThat(decoded.publishedSet().captureBytes()) + .containsExactly(fixture.publishedSet().captureBytes()); + assertThat(decoded.publishedSet().terminalEvidenceBytes()) + .containsExactly(fixture.publishedSet().terminalEvidenceBytes()); + assertThat(decoded.publishedSet().policies()) + .containsExactlyElementsOf(fixture.publishedSet().policies()); + assertThat(decoded.publishedSet().policySetDigest()) + .isEqualTo(fixture.publishedSet().policySetDigest()); + assertThat(fixture.response().getRequest()).isEqualTo(fixture.wireRequest().message()); + assertThat(fixture.response().getAuthorizationResponse().getRequest()) + .isEqualTo(fixture.wireRequest().message().getAuthorizationRequest()); + assertThat(fixture.authorizationResult().request().selection()) + .isInstanceOf(StartSessionTemplateAssociationReadEvidence.ExactReplay.class); + } + + @Test + void rejectsChangedEchoAuthorizationCorrelationTargetSourceReleaseAndPolicyEvidence() + throws Exception { + Fixture fixture = fixture(); + ReadStartSessionPublishedRealmPolicyResponse response = fixture.response(); + var wireRequest = fixture.wireRequest(); + + var changedEcho = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setReadRequestId("88888888-8888-4888-8888-888888888888")) + .build(); + assertRejected(wireRequest, changedEcho); + + var authorization = response.getAuthorizationResponse(); + var changedAuthorizationCorrelation = + response.toBuilder() + .setAuthorizationResponse( + authorization.toBuilder() + .setRequest( + authorization.getRequest().toBuilder() + .setOwnerFence(authorization.getRequest().getOwnerFence() + 1))) + .build(); + assertRejected(wireRequest, changedAuthorizationCorrelation); + + String targetJson = + new String( + wireRequest.message().getCanonicalTargetProofJson().toByteArray(), + StandardCharsets.UTF_8); + String changedTargetJson = + targetJson.replace( + "\"sourceGameRowId\":\"" + fixture.publishedSet().target().sourceGameRowId() + "\"", + "\"sourceGameRowId\":\"" + + (fixture.publishedSet().target().sourceGameRowId() + 1) + + "\""); + assertThat(changedTargetJson).isNotEqualTo(targetJson); + var changedTargetWire = + StartSessionPublishedRealmPolicyReadGrpcCodec.fromRequest( + wireRequest.message().toBuilder() + .setCanonicalTargetProofJson(ByteString.copyFromUtf8(changedTargetJson)) + .build()); + assertRejected( + changedTargetWire, response.toBuilder().setRequest(changedTargetWire.message()).build()); + + ResolveAuthoredWorldSourceResponse source = response.getSourceEvidence(); + var changedSource = + response.toBuilder() + .setSourceEvidence( + source.toBuilder().setSourceGameRowId(source.getSourceGameRowId() + 1)) + .build(); + assertRejected(wireRequest, changedSource); + + var changedReleaseRequest = + wireRequest.message().toBuilder() + .setReleaseAttestation( + wireRequest.message().getReleaseAttestation().toBuilder() + .setVersionStateEpoch( + wireRequest.message().getReleaseAttestation().getVersionStateEpoch() + 1)) + .build(); + var changedReleaseWire = + StartSessionPublishedRealmPolicyReadGrpcCodec.fromRequest(changedReleaseRequest); + assertRejected( + changedReleaseWire, response.toBuilder().setRequest(changedReleaseWire.message()).build()); + + byte[] changedCarrier = response.getPublishedPolicySet().toByteArray(); + byte[] policyMarker = "\\\"realmSlug\\\":\\\"realm-a\\\"".getBytes(StandardCharsets.UTF_8); + int policyOffset = indexOf(changedCarrier, policyMarker); + assertThat(policyOffset).isGreaterThanOrEqualTo(0); + changedCarrier[policyOffset + policyMarker.length - 3] = (byte) 'z'; + assertRejected( + wireRequest, + response.toBuilder().setPublishedPolicySet(ByteString.copyFrom(changedCarrier)).build()); + } + + @Test + void actualPublicationOperationAndTerminalRemainInsideTheCanonicalCarrier() throws Exception { + RealmPolicyPublishedEvidence.PublishedSet original = publishedSet(); + + byte[] carrier = RealmPolicyPublishedEvidenceCodec.encode(original); + RealmPolicyPublishedEvidence.PublishedSet decoded = + RealmPolicyPublishedEvidenceCodec.decode(carrier); + + assertThat(decoded.target()).isEqualTo(original.target()); + assertThat(decoded.sourceCommitId()).isEqualTo(original.sourceCommitId()); + assertThat(decoded.publishedReleaseBundleRef()).isEqualTo(original.publishedReleaseBundleRef()); + assertThat(decoded.publicationVersionStateEpoch()) + .isEqualTo(original.publicationVersionStateEpoch()); + assertThat(decoded.operationBytes()).containsExactly(original.operationBytes()); + assertThat(decoded.captureBytes()).containsExactly(original.captureBytes()); + assertThat(decoded.terminalEvidenceBytes()).containsExactly(original.terminalEvidenceBytes()); + assertThat(decoded.policies()).containsExactlyElementsOf(original.policies()); + assertThat(RealmPolicyPublishedEvidence.targetProofJson(decoded.target())) + .isEqualTo(RealmPolicyPublishedEvidence.targetProofJson(original.target())); + } + + private static RealmPolicyPublishedEvidence.PublishedSet publishedSet() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.PUBLISHED); + return publishedSet(operation, terminal); + } + + private static RealmPolicyPublishedEvidence.PublishedSet publishedSet( + GameDesignPublicationOperationBinding operation, + net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence terminal) { + DraftCommitBinding selectedCommit = operation.account().input().selection().selectedCommit(); + DraftCommitBinding.TargetProof target = selectedCommit.target(); + var sources = + List.of( + new RealmPolicySource.Policy( + selectedCommit.commitId(), + FIRST_REVISION_ID, + "logical-realm-a", + policy("realm-a", "World", true)), + new RealmPolicySource.Policy( + selectedCommit.commitId(), + SECOND_REVISION_ID, + "logical-realm-b", + policy("realm-b", "World", false))); + var snapshot = + new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( + selectedCommit, "7", sources); + byte[] captureBytes = capture(operation.canonicalBytes(), snapshot.canonicalBytes()); + var release = terminal.releaseContent(); + var policies = + List.of( + new RealmPolicyPublishedEvidence.Policy( + FIRST_POLICY_ID, + sources.getFirst(), + RealmPolicyPublishedEvidence.policyDigest( + FIRST_POLICY_ID, + target, + release.versionNumber(), + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + sources.getFirst())), + new RealmPolicyPublishedEvidence.Policy( + SECOND_POLICY_ID, + sources.get(1), + RealmPolicyPublishedEvidence.policyDigest( + SECOND_POLICY_ID, + target, + release.versionNumber(), + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + sources.get(1)))); + byte[] operationBytes = operation.canonicalBytes(); + byte[] terminalBytes = terminal.canonicalBytes(); + String digest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + release.versionNumber(), + selectedCommit.commitId(), + snapshot.sourceEpoch(), + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operationBytes, + captureBytes, + terminalBytes, + policies); + return new RealmPolicyPublishedEvidence.PublishedSet( + target, + release.versionNumber(), + selectedCommit.commitId(), + snapshot.sourceEpoch(), + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operationBytes, + captureBytes, + terminalBytes, + policies.size(), + digest, + policies); + } + + private static Fixture fixture() throws Exception { + var launch = StartSessionLaunchDescriptorGrpcCodecTest.fixture(); + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.PUBLISHED); + var target = operation.account().input().selection().target(); + var content = terminal.releaseContent(); + var oldRequest = launch.request(); + var oldResult = launch.associationRead(); + var oldAssociation = oldResult.association(); + UUID selectedCommit = UUID.fromString(operation.world().request().appliedCommitId()); + var association = + new StartSessionTemplateAssociationReadEvidence.Association( + oldAssociation.canonicalTenantId(), + oldAssociation.templateId(), + target.canonicalVersionId(), + selectedCommit, + content.publishWorkflowId(), + oldAssociation.publicationSelectionDigest(), + oldAssociation.associationDigest(), + oldAssociation.targetNamespace(), + oldAssociation.intakeRequestId(), + oldAssociation.worldOperationId(), + oldAssociation.sourceOperationId(), + oldAssociation.worldSlug(), + oldAssociation.sourceEvidenceDigest(), + oldAssociation.worldReadRequest(), + oldAssociation.worldReceipt()); + var authorizationRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + oldRequest.schemaVersion(), + oldRequest.targetNamespace(), + oldRequest.readRequestId(), + oldRequest.canonicalPostAuthorizationTuple(), + oldRequest.ownerAttemptId(), + oldRequest.ownerFence(), + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + target.canonicalVersionId(), + selectedCommit, + content.publishWorkflowId(), + association.associationDigest())); + + var originalDescriptor = launch.descriptor(); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + originalDescriptor.request(), + originalDescriptor.launchDescriptorId(), + target.gameDesignVersionRowId(), + false, + null, + originalDescriptor.runtimeFlagsJson(), + content.generationConfigRevision(), + originalDescriptor.versionStateEpoch(), + originalDescriptor.releaseBundleId(), + content.publishedReleaseBundleRef(), + false, + null); + PublishedReleaseBundle releaseBundle = + releaseBundle(oldResult.releaseBundle(), descriptor, content); + var authorizationResult = + new StartSessionTemplateAssociationReadEvidence.Result( + authorizationRequest, + association, + releaseBundle, + operation.world(), + oldResult.phaseEpoch()); + var release = releaseAttestation(descriptor, content, operation.world()); + var request = + new StartSessionPublishedRealmPolicyReadGrpcCodec.ReadRequest( + oldRequest.targetNamespace(), + UUID.fromString("77777777-7777-4777-8777-777777777777"), + authorizationRequest, + descriptor, + release, + target); + var wireRequest = + StartSessionPublishedRealmPolicyReadGrpcCodec.fromRequest( + StartSessionPublishedRealmPolicyReadGrpcCodec.toRequest(request)); + AuthoredWorldSourceEvidence source = oldAssociation.worldReceipt().source(); + RealmPolicyPublishedEvidence.PublishedSet publishedSet = publishedSet(operation, terminal); + assertThat(publishedSet.target()).isEqualTo(target); + var authorized = + StartSessionPublishedRealmPolicyReadGrpcCodec.authorize(wireRequest, authorizationResult); + var response = + StartSessionPublishedRealmPolicyReadGrpcCodec.toResponse( + wireRequest, authorized, authorizationResult, source, publishedSet); + return new Fixture(wireRequest, request, authorizationResult, source, publishedSet, response); + } + + private static PublishedReleaseBundle releaseBundle( + PublishedReleaseBundle original, + AuthoredWorldLaunchDescriptorEvidence descriptor, + GameDesignPublicationTerminalEvidence.ReleaseContent content) { + var builder = + original.toBuilder() + .setId(descriptor.releaseBundleId()) + .setVersionId(descriptor.versionId()) + .setVersionNumber(content.versionNumber()) + .setAttestationSchemaVersion(content.attestationSchemaVersion()) + .setPublishWorkflowId(content.publishWorkflowId()) + .setManifestHash(content.manifestHash()) + .setManifestSchemaVersion(content.manifestSchemaVersion()) + .setGenerationConfigRevision(content.generationConfigRevision()) + .setPublishedReleaseBundleRef(content.publishedReleaseBundleRef()) + .setCanonicalTenantId(content.canonicalTenantId().toString()) + .setCanonicalVersionId(content.canonicalVersionId().toString()) + .clearArtifactDigests() + .clearRequiredManifestAssetKeys() + .clearParticipantDigests() + .clearCommandDefinitions(); + content.artifactDigests().stream() + .map( + artifact -> + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey(artifact.usageKey()) + .setArtifactKind(artifact.artifactKind()) + .setImmutableObjectKey(artifact.immutableObjectKey()) + .setContentDigest(artifact.contentDigest()) + .setContentType(artifact.contentType()) + .setArtifactSchemaVersion(artifact.artifactSchemaVersion()) + .build()) + .forEach(builder::addArtifactDigests); + builder.addAllRequiredManifestAssetKeys(content.requiredManifestAssetKeys()); + content.participantDigests().stream() + .map( + participant -> { + var value = + net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigest() != null) { + value.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + } + return value.build(); + }) + .forEach(builder::addParticipantDigests); + return builder.addAllCommandDefinitions(content.commandDefinitions()).build(); + } + + private static AuthoredWorldReleaseAttestationEvidence releaseAttestation( + AuthoredWorldLaunchDescriptorEvidence descriptor, + GameDesignPublicationTerminalEvidence.ReleaseContent content, + WorldPublishedStartLocationEvidence worldEvidence) { + var participants = + content.participantDigests().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId() != null, + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigest() != null, + participant.abilitySchemaDigest())) + .toList(); + return AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + content.canonicalTenantId(), + content.canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + content.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + content.publishWorkflowId(), + content.participantDigests().getFirst().appliedCommitId(), + participants, + content.manifestHash(), + content.manifestSchemaVersion(), + content.requiredManifestAssetKeys(), + content.artifactDigests(), + content.commandDefinitions(), + content.generationConfigRevision(), + worldEvidence); + } + + private static void assertRejected( + StartSessionPublishedRealmPolicyReadGrpcCodec.WireRequest expected, + ReadStartSessionPublishedRealmPolicyResponse response) { + assertThatThrownBy( + () -> StartSessionPublishedRealmPolicyReadGrpcCodec.fromResponse(expected, response)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static int indexOf(byte[] bytes, byte[] needle) { + for (int offset = 0; offset <= bytes.length - needle.length; offset++) { + boolean matches = true; + for (int index = 0; index < needle.length; index++) { + if (bytes[offset + index] != needle[index]) { + matches = false; + break; + } + } + if (matches) return offset; + } + return -1; + } + + private static RealmEntryPolicy policy( + String realmSlug, String worldDisplayName, boolean production) { + return RealmEntryPolicy.parse( + "{\"entryPolicy\":\"PRESEEDED_ONLY\",\"publicProduction\":" + + production + + ",\"realmDisplayName\":\"" + + realmSlug + + "\",\"realmSlug\":\"" + + realmSlug + + "\",\"schemaVersion\":1,\"stateScope\":\"SHARED\",\"visible\":true," + + "\"worldDisplayName\":\"" + + worldDisplayName + + "\",\"worldSlug\":\"world\"}", + JSON); + } + + private static byte[] capture(byte[] operationBytes, byte[] snapshotBytes) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "game-design-realm-policy-source-capture/v1"); + DraftAuthorizationFenceBinding.frame(out, operationBytes); + DraftAuthorizationFenceBinding.frame(out, snapshotBytes); + return out.toByteArray(); + } + + private record Fixture( + StartSessionPublishedRealmPolicyReadGrpcCodec.WireRequest wireRequest, + StartSessionPublishedRealmPolicyReadGrpcCodec.ReadRequest request, + StartSessionTemplateAssociationReadEvidence.Result authorizationResult, + AuthoredWorldSourceEvidence sourceEvidence, + RealmPolicyPublishedEvidence.PublishedSet publishedSet, + ReadStartSessionPublishedRealmPolicyResponse response) {} +} diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index b50781ccc9..cf81c82855 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -23,8 +23,29 @@ testing { } } +// Narrow classes-only proof artifact for Game Session repository tests. It contains no GD +// application resources or migrations and is built without running GD test or integration tasks. +val gameDesignCanonicalPublicationFixtureProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("canonical-publication-fixture-proof") + dependsOn(tasks.named("compileTestJava")) + from(sourceSets.main.get().output.classesDirs) { + include("net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperation.class") + } + from(sourceSets.test.get().output.classesDirs) { + include("net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures*.class") + include("net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures*.class") + } +} + +val gameDesignCanonicalPublicationFixtureProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + outgoing.artifact(gameDesignCanonicalPublicationFixtureProofJar) +} + dependencies { integrationTestImplementation(project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof"))) + integrationTestImplementation(project(mapOf("path" to ":logging-admin-service", "configuration" to "loggingStartSessionClaimProof"))) integrationTestImplementation(project(mapOf("path" to ":game-logic-service", "configuration" to "gameLogicClassesProof"))) integrationTestImplementation( project( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionPublishedRealmPolicyReadGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionPublishedRealmPolicyReadGrpcService.java new file mode 100644 index 0000000000..c599d70007 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionPublishedRealmPolicyReadGrpcService.java @@ -0,0 +1,174 @@ +package net.firedevops.firemud.gamedesign.draft; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.StartSessionPublishedRealmPolicyReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.publication.StartSessionPublishedRealmPolicyReadService; +import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; +import net.firedevops.firemud.gamedesign.v1.GameDesignStartSessionPublishedRealmPolicyReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionPublishedRealmPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionPublishedRealmPolicyResponse; +import org.jooq.exception.DataAccessException; + +/** Standalone, deliberately unregistered authenticated historical policy-content endpoint. */ +public final class GameDesignStartSessionPublishedRealmPolicyReadGrpcService + extends GameDesignStartSessionPublishedRealmPolicyReadServiceGrpc + .GameDesignStartSessionPublishedRealmPolicyReadServiceImplBase { + private final StartSessionTemplateAssociationReadService associationReader; + private final StartSessionPublishedRealmPolicyReadService publishedPolicyReader; + private final String workloadNamespace; + + public GameDesignStartSessionPublishedRealmPolicyReadGrpcService( + StartSessionTemplateAssociationReadService associationReader, + StartSessionPublishedRealmPolicyReadService publishedPolicyReader, + String workloadNamespace) { + this.associationReader = Objects.requireNonNull(associationReader, "associationReader"); + this.publishedPolicyReader = + Objects.requireNonNull(publishedPolicyReader, "publishedPolicyReader"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readStartSessionPublishedRealmPolicy( + ReadStartSessionPublishedRealmPolicyRequest request, + StreamObserver observer) { + try { + requirePeer(); + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription("Workload-only published-policy read required") + .asRuntimeException(); + } + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + try { + StartSessionPublishedRealmPolicyReadGrpcCodec.requireRequestSerializedSize(request); + } catch (IllegalArgumentException oversized) { + observer.onError( + Status.RESOURCE_EXHAUSTED + .withDescription("Published-policy request exceeds the local wire bound") + .asRuntimeException()); + return; + } + + final StartSessionPublishedRealmPolicyReadGrpcCodec.WireRequest decoded; + try { + decoded = StartSessionPublishedRealmPolicyReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical schema-1 published-policy read required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(request.getTargetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Published-policy namespace differs from peer") + .asRuntimeException()); + return; + } + + final net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .Result + authorizationResult; + try { + // This concrete read independently confirms Account's original operation before its own SQL. + authorizationResult = associationReader.read(decoded.authorizationRequest()); + } catch (StatusRuntimeException deniedOrUnavailable) { + observer.onError( + Status.fromCode(Status.fromThrowable(deniedOrUnavailable).getCode()) + .withDescription("Exact StartSession authorization read denied or unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Exact StartSession authorization read unavailable") + .asRuntimeException()); + return; + } + + final StartSessionPublishedRealmPolicyReadGrpcCodec.ReadRequest authorized; + try { + // No policy/source owner query is reachable until the full Account-confirmed association, + // supplied descriptor, release attestation, and TargetProof agree. + authorized = + StartSessionPublishedRealmPolicyReadGrpcCodec.authorize(decoded, authorizationResult); + } catch (RuntimeException invalidOrConflicting) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact StartSession descriptor or TargetProof is unavailable") + .asRuntimeException()); + return; + } + + final StartSessionPublishedRealmPolicyReadService.ReadResult ownerResult; + try { + ownerResult = + publishedPolicyReader.read( + new StartSessionPublishedRealmPolicyReadService.ReadRequest( + authorized.descriptor(), authorized.releaseAttestation(), authorized.target())); + } catch (StatusRuntimeException deniedOrUnavailable) { + observer.onError( + Status.fromCode(Status.fromThrowable(deniedOrUnavailable).getCode()) + .withDescription("Exact published source and policy read denied or unavailable") + .asRuntimeException()); + return; + } catch (DataAccessException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Published source and policy owner storage unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException invalidOrUnavailable) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact published source or policy evidence is unavailable") + .asRuntimeException()); + return; + } + + try { + ReadStartSessionPublishedRealmPolicyResponse response = + StartSessionPublishedRealmPolicyReadGrpcCodec.toResponse( + decoded, + authorized, + authorizationResult, + ownerResult.sourceEvidence(), + ownerResult.publishedSet()); + observer.onNext(response); + observer.onCompleted(); + } catch (RuntimeException invalidOrOversized) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Complete published-policy evidence could not be returned") + .asRuntimeException()); + } + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java index 580030fbc9..45f5766486 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionPublishedRealmPolicyReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionPublishedRealmPolicyReadService.java new file mode 100644 index 0000000000..21e3c7694e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionPublishedRealmPolicyReadService.java @@ -0,0 +1,189 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Owner-local exact source and immutable published-realm-policy read for a future StartSession + * transport. + */ +public final class StartSessionPublishedRealmPolicyReadService { + private final GameAuthoredWorldSourceRepository sources; + private final RealmPolicyPublicationRepository policies; + private final TransactionTemplate snapshot; + + public StartSessionPublishedRealmPolicyReadService( + GameAuthoredWorldSourceRepository sources, + RealmPolicyPublicationRepository policies, + PlatformTransactionManager transactions) { + this.sources = Objects.requireNonNull(sources, "sources"); + this.policies = Objects.requireNonNull(policies, "policies"); + snapshot = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + snapshot.setName("game-design-start-session-published-realm-policy-read"); + snapshot.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + snapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + snapshot.setReadOnly(true); + } + + /** + * Reads both immutable owner records in one independent snapshot and requires exact agreement + * with the descriptor, full release attestation, and persisted canonical TargetProof. + */ + public ReadResult read(ReadRequest request) { + Objects.requireNonNull(request, "request"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent Game Design REPEATABLE_READ snapshot required") + .asRuntimeException(); + } + + return Objects.requireNonNull( + snapshot.execute(ignored -> readSnapshot(request)), + "Published realm-policy snapshot returned no result"); + } + + private ReadResult readSnapshot(ReadRequest request) { + AuthoredWorldLaunchDescriptorEvidence descriptor = request.descriptor(); + AuthoredWorldReleaseAttestationEvidence release = request.releaseAttestation(); + TargetProof target = request.target(); + + descriptor.requireValid(); + release.requireValid(descriptor); + if (!descriptor.canonicalTenantId().equals(target.canonicalTenantId()) + || !release.canonicalVersionId().equals(target.canonicalVersionId()) + || descriptor.versionId() != target.gameDesignVersionRowId()) { + throw new IllegalStateException("START_SESSION_POLICY_REQUEST_BINDING_CONFLICT"); + } + + AuthoredWorldSourceEvidence source = + sources + .readExactSourceSnapshot( + descriptor.targetNamespace(), + descriptor.authoredWorldSourceOperationId(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceEvidenceDigest()) + .orElseThrow(() -> new IllegalStateException("AUTHORED_WORLD_SOURCE_UNAVAILABLE")); + if (!descriptor.targetNamespace().equals(source.targetNamespace()) + || !descriptor.authoredWorldSourceOperationId().equals(source.operationId()) + || !descriptor.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest()) + || !descriptor.canonicalTenantId().equals(source.canonicalTenantId()) + || !descriptor.worldSlug().equals(source.worldSlug()) + || source.sourceGameRowId() != target.sourceGameRowId() + || !source.sourceGameTenantKey().equals(target.sourceGameTenantKey()) + || !source.provenanceKind().equals(target.sourceProvenanceKind())) { + throw new IllegalStateException("START_SESSION_POLICY_SOURCE_TARGET_CONFLICT"); + } + + RealmPolicyPublishedEvidence.PublishedSet published = + policies + .readPublishedSet(target) + .orElseThrow(() -> new IllegalStateException("PUBLISHED_REALM_POLICY_SET_UNAVAILABLE")); + if (!target.equals(published.target())) { + throw new IllegalStateException("START_SESSION_POLICY_TARGET_PROOF_CONFLICT"); + } + GameDesignPublicationTerminalEvidence terminal = + GameDesignPublicationTerminalEvidence.fromStored(published.terminalEvidenceBytes()); + var content = terminal.releaseContent(); + if (!descriptor.publishedReleaseBundleRef().equals(published.publishedReleaseBundleRef()) + || !release.publishedReleaseBundleRef().equals(published.publishedReleaseBundleRef()) + || !release.publishWorkflowId().equals(published.publishWorkflowId()) + || !release.manifestHash().equals(published.manifestHash()) + || !published.sourceCommitId().toString().equals(release.commitId()) + || published.publicationVersionStateEpoch() > release.versionStateEpoch() + || terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || terminal.publicationVersionStateEpoch() != published.publicationVersionStateEpoch() + || !terminal.publishedReleaseBundleRef().equals(published.publishedReleaseBundleRef()) + || !terminal.publishedReleaseBundleDigest().equals(published.publishedReleaseBundleDigest()) + || published.versionNumber() != content.versionNumber() + || !releaseContentMatches(release, content)) { + throw new IllegalStateException("START_SESSION_POLICY_RELEASE_BINDING_CONFLICT"); + } + return new ReadResult(source, published); + } + + private boolean releaseContentMatches( + AuthoredWorldReleaseAttestationEvidence release, + GameDesignPublicationTerminalEvidence.ReleaseContent content) { + int retainedSchemaVersion = + switch (content.attestationSchemaVersion()) { + case "v2" -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; + case "v3" -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + case "v4" -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; + default -> -1; + }; + if (release.schemaVersion() != retainedSchemaVersion + || !release.canonicalTenantId().equals(content.canonicalTenantId()) + || !release.canonicalVersionId().equals(content.canonicalVersionId()) + || !release.publishedReleaseBundleRef().equals(content.publishedReleaseBundleRef()) + || !release.publishWorkflowId().equals(content.publishWorkflowId()) + || !release.manifestHash().equals(content.manifestHash()) + || release.manifestSchemaVersion() != content.manifestSchemaVersion() + || !release.requiredManifestAssetKeys().equals(content.requiredManifestAssetKeys()) + || !release.artifactDigests().equals(content.artifactDigests()) + || !release.commandDefinitions().equals(content.commandDefinitions()) + || !release.generationConfigRevision().equals(content.generationConfigRevision()) + || !Objects.equals( + release.worldStartLocationEvidence(), content.worldStartLocationEvidence()) + || release.participantDigests().size() != content.participantDigests().size()) { + return false; + } + for (int index = 0; index < release.participantDigests().size(); index++) { + var attested = release.participantDigests().get(index); + var retained = content.participantDigests().get(index); + if (!attested.participantKey().equals(retained.participantKey()) + || !attested.scopeValue().equals(retained.scopeValue()) + || attested.baseVersionIdPresent() != (retained.baseVersionId() != null) + || !Objects.equals(attested.baseVersionId(), retained.baseVersionId()) + || !attested.appliedCommitId().equals(retained.appliedCommitId()) + || !attested.contentDigest().equals(retained.contentDigest()) + || attested.digestSchemaVersion() != retained.digestSchemaVersion() + || attested.abilitySchemaDigestPresent() != (retained.abilitySchemaDigest() != null) + || !Objects.equals(attested.abilitySchemaDigest(), retained.abilitySchemaDigest())) { + return false; + } + } + return true; + } + + /** Exact selector inputs; no source, version, release, or catalog defaults are inferred. */ + public record ReadRequest( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation, + TargetProof target) { + public ReadRequest { + Objects.requireNonNull(descriptor, "descriptor"); + Objects.requireNonNull(releaseAttestation, "releaseAttestation"); + Objects.requireNonNull(target, "target"); + if (!GrpcPeerIdentity.isValidNamespace(descriptor.targetNamespace())) { + throw new IllegalArgumentException("Canonical target namespace required"); + } + if (!net.firedevops.firemud.common.tenant.GameTenantCreationDigest.isDigest( + descriptor.authoredWorldSourceEvidenceDigest())) { + throw new IllegalArgumentException("Canonical authored-world source digest required"); + } + } + } + + public record ReadResult( + AuthoredWorldSourceEvidence sourceEvidence, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + public ReadResult { + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + Objects.requireNonNull(publishedSet, "publishedSet"); + } + } +} 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 index a2a7947737..a5b300401c 100644 --- 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 @@ -263,6 +263,51 @@ public Optional read( return Optional.of(receipt); } + /** + * Reads one exact source receipt from the caller's independent read-only REPEATABLE_READ + * snapshot. Unlike {@link #read}, this method does not suspend that snapshot or read a committed + * outcome from outside it. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional readExactSourceSnapshot( + String targetNamespace, + UUID operationId, + UUID canonicalTenantId, + String worldSlug, + String expectedEvidenceDigest) { + requireOwnerSnapshot(); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireNonNil(operationId, "operationId"); + if (!GameTenantCreationDigest.isDigest(expectedEvidenceDigest)) { + throw new IllegalArgumentException("Expected source evidence digest is not canonical"); + } + + Record record = dsl.selectFrom(OPERATION).where(OPERATION_ID.eq(operationId)).fetchOne(); + if (record == null) { + return Optional.empty(); + } + AuthoredWorldSourceEvidence receipt = toEvidence(record); + if (!targetNamespace.equals(receipt.targetNamespace()) + || !operationId.equals(receipt.operationId()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !worldSlug.equals(receipt.worldSlug())) { + throw new InvalidSourceEvidenceException( + "Authored-world source operation does not match the exact requested scope"); + } + if (!expectedEvidenceDigest.equals(receipt.evidenceDigest())) { + throw new InvalidSourceEvidenceException( + "Authored-world source evidence digest no longer matches the requested binding"); + } + GameSource source = findGameSourceByRow(receipt.sourceGameRowId()); + if (source == null) { + throw new InvalidSourceEvidenceException("Authored-world source game row is missing"); + } + requireConsistentGameSource(source); + requireReceiptSource(receipt, source); + requireTenantBinding(receipt); + return Optional.of(receipt); + } + /** * Reads the exact source receipt and its source-owned version from the caller's owner snapshot. * diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 4212c30f64..01f9bb9036 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -14,6 +14,7 @@ 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.stub.StreamObserver; import io.grpc.util.MutableHandlerRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.io.ByteArrayOutputStream; @@ -25,6 +26,7 @@ import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateFactory; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -35,17 +37,18 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerAttemptLifecycle; import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerClaim; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; @@ -96,8 +99,10 @@ import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.StartSessionPublishedRealmPolicyReadGrpcCodec; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; @@ -137,13 +142,17 @@ import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; import net.firedevops.firemud.common.publication.WorldSelectedOwnerInventoryGrpcClient; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.PublicationReadGuard; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.security.sourceintake.GrpcAutomationSelectedSourceIntakeCommandClient; import net.firedevops.firemud.common.security.sourceintake.GrpcEntitySelectedSourceIntakeCommandClient; import net.firedevops.firemud.common.security.sourceintake.GrpcEntitySelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.security.sourceintake.GrpcSelectedOwnerIntakeAuthorizationProducerClient; import net.firedevops.firemud.common.security.sourceintake.GrpcSelectedOwnerIntakeSettlementClient; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationClient; @@ -170,6 +179,7 @@ import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcomeRepository; import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalReadGrpcService; import net.firedevops.firemud.gamedesign.draft.GameDesignSelectedDraftPublicationReadGrpcService; +import net.firedevops.firemud.gamedesign.draft.GameDesignStartSessionPublishedRealmPolicyReadGrpcService; import net.firedevops.firemud.gamedesign.draft.GameDesignWorldSourceCommitService; import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; @@ -183,6 +193,7 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignSelectedOwnerIntakeSourceGrpcService; import net.firedevops.firemud.gamedesign.publication.GameDesignSelectedOwnerIntakeSourceReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventoryReadService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftControlPlaneDigest; @@ -193,6 +204,7 @@ import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationDigestReadService; import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociationRepository; import net.firedevops.firemud.gamedesign.publication.StartSessionLaunchDescriptorProducer; +import net.firedevops.firemud.gamedesign.publication.StartSessionPublishedRealmPolicyReadService; import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; import net.firedevops.firemud.gamedesign.publication.TemplateConfigSource; import net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository; @@ -253,10 +265,27 @@ import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadGrpcService; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicGameplayRuleIntakeTerminalReadService; import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; +import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadGrpcService; +import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimEvidence; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceGrpcService; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceLeafApproval; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; import net.firedevops.firemud.test.TestContainerImages; import net.firedevops.firemud.worldmanagement.tenant.GenuineWorldSelectedPublicationProofFactory; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeGrpcService; @@ -301,6 +330,7 @@ import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamilyCount; import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -360,20 +390,26 @@ * PostgreSQL schema and migration path. Entity and Automation publication digests use their native * mTLS selected-empty owner readers and exact retained receipts; nonempty owner publication remains * outside this proof. StartSession issuance and redemption use the real Account owner and retained - * rows under stipulated Logging current-claim evidence and issuer/redeemer peer contexts; the - * read-only projection uses the real Account receiver over Game Design mTLS. MinIO object-store I/O - * is real. The complete launch-binding case wires the actual Game Design handler and World - * Management mTLS client on this fixture's loopback server to the actual owner implementation in an - * explicitly established read-only repeatable-read snapshot; unrelated handler dependencies are - * isolated. The World preparation composition reuses the genuine persisted source, frozen graph, - * and complete released pair through actual World owner services. Its original Account tuple is - * issued and redeemed by the real Account owner under stipulated Logging claim and peer contexts; - * Game Session reserves that exact tuple in an isolated V35 store and attaches the exact redeemed - * projection. Account's current-attempt observation and World participation acquisition use their - * native same-namespace mTLS clients and receivers. Game Session launch association remains mocked, - * and Account participation is point-in-time evidence, not a continuous cross-service lock. This - * does not establish production-authenticated Logging claims, full application server wiring, - * production ingress, runtime launch, activation or registration. + * rows under the genuine Logging PostgreSQL reservation owner and its native file-backed mTLS + * current-claim reader; Account issuer/redeemer peer contexts remain stipulated. The read-only + * projection uses the real Account receiver over Game Design mTLS. MinIO object-store I/O is real. + * The complete launch-binding case wires the actual Game Design handler and World Management mTLS + * client on this fixture's loopback server to the actual owner implementation in an explicitly + * established read-only repeatable-read snapshot; unrelated handler dependencies are isolated. The + * World preparation composition reuses the genuine persisted source, frozen graph, and complete + * released pair through actual World owner services. Its original Account tuple is issued and + * redeemed by the real Account owner after the native Logging current-claim read and under + * stipulated Account issuer/redeemer peer contexts; Game Session reserves that exact tuple in an + * isolated V35 store and attaches the exact redeemed projection. Account's current-attempt + * observation and World participation acquisition use their native same-namespace mTLS clients and + * receivers. Game Session also resolves the actual fresh Game Design tenant receipt over mTLS, + * stores and independently reads its numeric tenant association, then reads the actual + * Account-confirmed source and published policy set over mTLS and stores and independently reads + * its canonical public-realm catalog. Game Session launch association remains mocked, and Account + * participation is point-in-time evidence, not a continuous cross-service lock. This does not + * establish production certificate custody, full application server wiring, production ingress, + * runtime launch, activation or registration. The Logging evidence is point-in-time and does not + * lock later Account or Game Session commits. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -440,6 +476,10 @@ class GenuineSelectedPublicationExportPostgresIntegrationTest { private static final PostgreSQLContainer ENTITY_POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container + private static final PostgreSQLContainer LOGGING_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container private static final GenericContainer REDIS = new GenericContainer<>(TestContainerImages.redis()) @@ -493,6 +533,7 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var gd = gameDesignStore(); var world = serviceStore(WORLD_POSTGRES, "world-management"); var gameSessionAttempts = gameSessionAttemptStore(); + var loggingStore = loggingReservationStore(); var gameLogic = serviceStore(GAME_LOGIC_POSTGRES, "game-logic"); var automation = serviceStore(GAME_LOGIC_POSTGRES, "automation-scripting"); var entity = serviceStore(ENTITY_POSTGRES, "entity-management"); @@ -504,6 +545,14 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var gameLogicHandlers = new MutableHandlerRegistry(); var automationHandlers = new MutableHandlerRegistry(); var entityHandlers = new MutableHandlerRegistry(); + var loggingReadRequests = new CopyOnWriteArrayList(); + var loggingReadResponses = new CopyOnWriteArrayList(); + + Path approvedAccountLeaves = temporary.resolve("test-only-approved-account-leaves.txt"); + Files.writeString( + approvedAccountLeaves, + "active=" + certificateSha256(pki.clientCertificate("account-service")) + "\n", + StandardCharsets.US_ASCII); register( gameSessionHandlers, @@ -517,6 +566,13 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex Server gameLogicServer = startServer(pki, "game-logic-service", gameLogicHandlers); Server automationServer = startServer(pki, "automation-scripting-service", automationHandlers); Server entityServer = startServer(pki, "entity-management-service", entityHandlers); + Server loggingServer = + loggingClaimServer( + pki, + loggingStore.service(), + approvedAccountLeaves, + loggingReadRequests, + loggingReadResponses); var endpoints = new ServiceEndpointsProperties(); endpoints.setAccountService(loopback(accountServer)); endpoints.setGameDesignService(loopback(gdServer)); @@ -526,7 +582,8 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex endpoints.setAutomationScriptingService(loopback(automationServer)); endpoints.setEntityManagementService(loopback(entityServer)); var channels = new GrpcChannelFactory(); - try (var account = + try (var loggingClaimClient = currentClaimGrpcClient(loggingServer.getPort(), pki); + var account = new AccountControlUiOriginalOrderFixture( ACCOUNT_POSTGRES.getJdbcUrl(), ACCOUNT_POSTGRES.getUsername(), @@ -553,16 +610,25 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var gameSessionPreparationRetryClient = new CanonicalWorldInstancePreparationClient( endpoints, pki.client("game-session-service"), channels, NAMESPACE); + var gameSessionFreshTenantCreationClient = + new GameDesignFreshTenantCreationClient( + endpoints, pki.client("game-session-service"), channels, NAMESPACE); + var gameSessionPublishedRealmPolicyClient = + new GameDesignPublishedRealmPolicyClient( + endpoints, pki.client("game-session-service"), channels, NAMESPACE); var wrongWorkloadActivationClient = canonicalActivationClient(worldServer, pki.client("account-service"), channels); var gameSessionActivationClient = canonicalActivationClient(worldServer, pki.client("game-session-service"), channels)) { + ReflectionTestUtils.invokeMethod(loggingClaimClient, "init"); accountToGameSessionCurrentAttemptClient.init(); worldToAccountParticipationClient.init(); projectionClient.init(); wrongWorkloadPreparationClient.init(); gameSessionPreparationClient.init(); gameSessionPreparationRetryClient.init(); + gameSessionFreshTenantCreationClient.init(); + gameSessionPublishedRealmPolicyClient.init(); var automationIntakeRepository = new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); var entityIntakeRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); @@ -587,6 +653,21 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new AuthoredWorldVersionStateGrpcService( new AuthoredWorldVersionStateService(gd.transactions(), sourceRepository), NAMESPACE)); + var freshTenantAssociationRepository = + new GameSessionFreshTenantAssociationRepository( + gameSessionAttempts.dsl(), + gameSessionAttempts.transactionManager(), + gameSessionFreshTenantCreationClient, + NAMESPACE); + FreshTenantCreationEvidence creationEvidence = gd.freshTenantCreationEvidence(); + var freshTenantAssociation = + freshTenantAssociationRepository.associateFreshTenant( + creationEvidence.creationRequestId(), creationEvidence.requestDigest()); + assertThat(freshTenantAssociation.sourceEvidence()).isEqualTo(creationEvidence); + assertThat( + freshTenantAssociationRepository.readByCanonicalTenantId( + creationEvidence.canonicalTenantId())) + .contains(freshTenantAssociation); var worldIntakes = new WorldAuthoredSourceIntakeRepository(world.dsl()); var worldIdentities = new WorldAuthoredVersionIdentityRepository(world.dsl()); @@ -983,7 +1064,10 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new AccountGameLogicIntakeSettlementGrpcService(accountSettlementOwner, NAMESPACE)); var startSessionAuthorizationProof = new AccountOriginalStartSessionAuthorizationProofFixture( - account, temporary.resolve("account-start-session-authorization-proof"), NAMESPACE); + account, + temporary.resolve("account-start-session-authorization-proof"), + NAMESPACE, + loggingClaimClient); register(accountHandlers, startSessionAuthorizationProof.grpcService()); var accountWorldParticipationAcquisitionService = startSessionAuthorizationProof.worldParticipationAcquisitionService( @@ -2382,6 +2466,18 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new RevisionRepository(gd.dsl()), new VersionRepository(gd.dsl()), new ObjectMapper()); + var startSessionAssociationReader = + new StartSessionTemplateAssociationReadService( + gd.dsl(), gd.transactions(), NAMESPACE, projectionClient, releaseService); + var startSessionPublishedPolicyReader = + new StartSessionPublishedRealmPolicyReadService( + sourceRepository, + new RealmPolicyPublicationRepository(gd.dsl()), + gd.transactions()); + register( + gdHandlers, + new GameDesignStartSessionPublishedRealmPolicyReadGrpcService( + startSessionAssociationReader, startSessionPublishedPolicyReader, NAMESPACE)); var artifactService = new VersionAssetArtifactServiceImpl( new VersionAssetArtifactRepository(gd.dsl()), @@ -2734,8 +2830,6 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex publicationRequest.derivedWorkflowIdentity(), association.digest()); String controlPlaneRequestId = "genuine-start-session-" + UUID.randomUUID(); - UUID reservationOwnerId = UUID.randomUUID(); - long reservationClaimFence = ThreadLocalRandom.current().nextLong(1L, Long.MAX_VALUE); var originalStartSessionAction = new StartSessionOperatorAction( StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, @@ -2747,6 +2841,72 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new StartSessionOperatorAction.Mutation( StartSessionOperatorAction.ClientIp.absent()), "Genuine selected descriptor storage proof"); + net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple + loggingTuple; + UUID creatorAccountId = startSessionAuthorizationProof.creatorAccountId(); + SessionContext.setContext( + creatorAccountId.toString(), + List.of(), + Map.of(gd.target().canonicalTenantId().toString(), List.of("tenantAdmin")), + false, + null, + null); + try { + loggingTuple = + net.firedevops.firemud.loggingadmin.operator + .StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + controlPlaneRequestId, originalStartSessionAction); + } finally { + SessionContext.clear(); + } + assertThat(loggingTuple.isAuthorityDerived()).isTrue(); + assertThat(loggingTuple.actor().accountId()).isEqualTo(creatorAccountId); + + var defaultLoggingRepository = + new StartSessionPreAuthorizationReservationRepository(loggingStore.dsl()); + var defaultLoggingService = + new StartSessionPreAuthorizationReservationService(defaultLoggingRepository); + assertThatThrownBy(() -> defaultLoggingService.acquire(loggingTuple)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("mutations are disabled for production construction"); + assertThatThrownBy( + () -> + defaultLoggingRepository.acquire( + loggingTuple, + UUID.randomUUID(), + System.currentTimeMillis(), + System.currentTimeMillis() + + StartSessionPreAuthorizationReservationService.CLAIM_TTL.toMillis())) + .isInstanceOf(UnsupportedOperationException.class); + + var loggingAcquisition = loggingStore.service().acquire(loggingTuple); + assertThat(loggingAcquisition.newlyAcquired()).isTrue(); + assertThat(loggingAcquisition.claim()).isNotNull(); + assertThat(loggingAcquisition.snapshot().state()).isEqualTo(State.RESERVED); + assertThat(loggingAcquisition.snapshot().phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + ClaimEvidence loggingClaim = loggingAcquisition.claim().claimEvidence(); + assertThat(loggingClaim.reservationOwnerId()).isEqualTo(loggingClaim.currentClaimOwnerId()); + assertThat(loggingClaim.reservationClaimFence()).isEqualTo(1L); + assertThat(loggingClaim.currentClaimFence()).isEqualTo(1L); + var authorizationPending = + loggingStore.service().markAuthorizationPending(loggingAcquisition.claim()); + assertThat(authorizationPending.mayDispatchAccountAuthorization()).isTrue(); + assertThat(authorizationPending.snapshot().phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(authorizationPending.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(authorizationPending.snapshot().claimState()).isEqualTo(ClaimState.ACTIVE); + assertThat(authorizationPending.snapshot().claimPurpose()).isEqualTo(ClaimPurpose.ORIGINAL); + assertThat(authorizationPending.snapshot().reservationClaimFence()) + .isEqualTo(loggingClaim.reservationClaimFence()); + assertThat(authorizationPending.snapshot().claimFence()) + .isEqualTo(loggingClaim.currentClaimFence()); + assertThat(authorizationPending.snapshot().claimExpiresAtEpochMillis()) + .isGreaterThan(System.currentTimeMillis()); + var pendingLoggingReservation = + loggingStore.service().findExact(loggingTuple).orElseThrow(); + assertThat(pendingLoggingReservation).isEqualTo(authorizationPending.snapshot()); + + UUID reservationOwnerId = loggingClaim.reservationOwnerId(); + long reservationClaimFence = loggingClaim.reservationClaimFence(); AtomicReference reservedOwnerAttempt = new AtomicReference<>(); AtomicReference reservedTupleBytes = new AtomicReference<>(); var originalStartSession = @@ -2793,6 +2953,48 @@ public void attachAccountRedemptionProjection( .containsExactly(projection.canonicalBytes()); } }); + assertThat(originalStartSession.originalTuple().preAuthorizationTuple().canonicalJson()) + .isEqualTo(loggingTuple.canonicalJson()); + assertThat(loggingReadRequests).hasSize(1); + assertThat(loggingReadResponses).hasSize(1); + ReadCurrentClaimEvidenceRequest loggingReadRequest = loggingReadRequests.getFirst(); + ReadCurrentClaimEvidenceResponse loggingReadResponse = loggingReadResponses.getFirst(); + assertThat(loggingReadRequest.getControlPlaneRequestId()).isEqualTo(controlPlaneRequestId); + assertThat(loggingReadRequest.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(loggingTuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(loggingReadRequest.getReservationOwnerId()) + .isEqualTo(loggingClaim.reservationOwnerId().toString()); + assertThat(loggingReadRequest.getReservationClaimFence()) + .isEqualTo(loggingClaim.reservationClaimFence()); + assertThat(loggingReadRequest.getClaimOwnerId()) + .isEqualTo(loggingClaim.currentClaimOwnerId().toString()); + assertThat(loggingReadRequest.getClaimFence()).isEqualTo(loggingClaim.currentClaimFence()); + assertThat(loggingReadRequest.getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(loggingReadResponse.getControlPlaneRequestId()).isEqualTo(controlPlaneRequestId); + assertThat(loggingReadResponse.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(loggingTuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(loggingReadResponse.getMutationDigest()) + .isEqualTo(loggingTuple.mutationDigest()); + assertThat(loggingReadResponse.getReservationOwnerId()) + .isEqualTo(loggingClaim.reservationOwnerId().toString()); + assertThat(loggingReadResponse.getReservationClaimFence()) + .isEqualTo(loggingClaim.reservationClaimFence()); + assertThat(loggingReadResponse.getClaimOwnerId()) + .isEqualTo(loggingClaim.currentClaimOwnerId().toString()); + assertThat(loggingReadResponse.getClaimFence()).isEqualTo(loggingClaim.currentClaimFence()); + assertThat(loggingReadResponse.getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(loggingReadResponse.getClaimExpiresAtEpochMillis()) + .isEqualTo(authorizationPending.snapshot().claimExpiresAtEpochMillis()); + assertThat(loggingReadResponse.getObservedAtEpochMillis()) + .isLessThan(loggingReadResponse.getClaimExpiresAtEpochMillis()); + assertThat(loggingStore.service().findExact(loggingTuple)) + .contains(pendingLoggingReservation); var startSessionTuple = originalStartSession.originalTuple(); AttemptClaim ownerAttemptClaim = Objects.requireNonNull(reservedOwnerAttempt.get(), "Actual Game Session owner claim"); @@ -2842,15 +3044,12 @@ public void attachAccountRedemptionProjection( .containsExactly(startSessionTuple.authorityEvidenceBundleBytes()); assertThat(projectionClient.read(startSessionTuple, ownerAttemptId, ownerFence)) .isEqualTo(accountProjection); - var associationReader = - new StartSessionTemplateAssociationReadService( - gd.dsl(), gd.transactions(), NAMESPACE, projectionClient, releaseService); var descriptorProducer = new StartSessionLaunchDescriptorProducer( gd.dsl(), gd.transactions(), NAMESPACE, - associationReader, + startSessionAssociationReader, releaseService, new ObjectMapper()); var firstDescriptorBinding = @@ -2969,6 +3168,84 @@ public void attachAccountRedemptionProjection( assertThat(completeGameLogicParticipant.abilitySchemaDigest()) .isEqualTo(actualGameLogicDigest.abilitySchemaDigest()); + var publishedPolicyReadRequest = + new StartSessionPublishedRealmPolicyReadGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + startSessionReadRequest( + startSessionTuple, + ownerAttemptId, + ownerFence, + pinnedSelection, + UUID.randomUUID()), + completeBinding.descriptor(), + completeBinding.releaseAttestation(), + gd.target()); + var publishedPolicyRead = + gameSessionPublishedRealmPolicyClient.read(publishedPolicyReadRequest); + assertThat(publishedPolicyRead.request()).isEqualTo(publishedPolicyReadRequest); + assertThat(publishedPolicyRead.authorizationResult().request()) + .isEqualTo(publishedPolicyReadRequest.authorizationRequest()); + assertThat(publishedPolicyRead.authorizationResult().association().associationDigest()) + .isEqualTo(association.digest()); + assertThat(publishedPolicyRead.sourceEvidence()).isEqualTo(worldSource); + assertThat(publishedPolicyRead.publishedSet().target()).isEqualTo(gd.target()); + var actualPublishedPolicy = + publishedPolicyRead.publishedSet().policies().getFirst().source().policy(); + assertThat(actualPublishedPolicy.worldSlug()).isEqualTo(worldSource.worldSlug()); + assertThat(actualPublishedPolicy.worldDisplayName()) + .isEqualTo(worldSource.worldDisplayName()); + assertThat(actualPublishedPolicy.visible()).isTrue(); + assertThat(actualPublishedPolicy.publicProduction()).isTrue(); + assertThat(actualPublishedPolicy.stateScope()) + .isEqualTo(RealmEntryPolicy.StateScope.SHARED); + assertThat(actualPublishedPolicy.entryPolicy()) + .isEqualTo(RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); + + var canonicalRealmCatalogRepository = + new GameSessionCanonicalRealmCatalogRepository( + gameSessionAttempts.dsl(), gameSessionAttempts.transactionManager(), NAMESPACE); + var canonicalRealmCatalog = + canonicalRealmCatalogRepository.establishFreshPublicRealm( + freshTenantAssociation, + publishedPolicyRead.sourceEvidence(), + publishedPolicyRead.publishedSet(), + UUID.randomUUID(), + UUID.randomUUID()); + assertThat(canonicalRealmCatalog.sourceEvidence()).isEqualTo(worldSource); + assertThat(canonicalRealmCatalog.associationSourceEvidence()).isEqualTo(creationEvidence); + assertThat(canonicalRealmCatalog.canonicalTenantId()) + .isEqualTo(gd.target().canonicalTenantId()); + assertThat(canonicalRealmCatalog.gameSessionTenantId()) + .isEqualTo(freshTenantAssociation.gameSessionTenantId()); + assertThat(canonicalRealmCatalog.worldSlug()).isEqualTo(worldSource.worldSlug()); + assertThat(canonicalRealmCatalog.sourceWorldDisplayName()) + .isEqualTo(worldSource.worldDisplayName()); + assertThat(canonicalRealmCatalog.entryPolicy()).isEqualTo("PRESEEDED_ONLY"); + assertThat(canonicalRealmCatalog.catalogRevision()).isPositive(); + assertThat(canonicalRealmCatalog.completePolicySetEvidence()) + .containsExactly( + RealmPolicyPublishedEvidenceCodec.encode(publishedPolicyRead.publishedSet())); + + var independentCanonicalRealmCatalogReadback = + canonicalRealmCatalogRepository + .readByCanonicalTenantId(gd.target().canonicalTenantId()) + .orElseThrow(); + assertThat(independentCanonicalRealmCatalogReadback.realmId()) + .isEqualTo(canonicalRealmCatalog.realmId()); + assertThat(independentCanonicalRealmCatalogReadback.playableStateNamespaceId()) + .isEqualTo(canonicalRealmCatalog.playableStateNamespaceId()); + assertThat(independentCanonicalRealmCatalogReadback.catalogRevision()) + .isEqualTo(canonicalRealmCatalog.catalogRevision()); + assertThat(independentCanonicalRealmCatalogReadback.sourceEvidence()) + .isEqualTo(worldSource); + assertThat(independentCanonicalRealmCatalogReadback.associationSourceEvidence()) + .isEqualTo(creationEvidence); + assertThat(independentCanonicalRealmCatalogReadback.completePolicySetEvidence()) + .containsExactly(canonicalRealmCatalog.completePolicySetEvidence()); + assertThat(independentCanonicalRealmCatalogReadback.publishedSet().policySetDigest()) + .isEqualTo(publishedPolicyRead.publishedSet().policySetDigest()); + var completeBindingRpcRequest = GetLaunchDescriptorRequest.newBuilder() .setRequestId(completeBindingReadRequestId.toString()) @@ -3113,9 +3390,10 @@ public void attachAccountRedemptionProjection( controlPlaneRequestId)) .containsExactlyElementsOf(completeBindingOwnerRowsBefore); - // World source, publication and released-pair proof above is genuine. The original - // StartSession tuple is issued/redempted by Account under the fixture's stipulated - // Logging claim and peer contexts. Game Session reserves the exact tuple and attaches + // World source, publication, released-pair proof, fresh tenant association and + // public-realm catalog above use the actual owners. The original StartSession tuple is + // issued/redeemed by Account after the actual native Logging claim read, under the + // fixture's stipulated Account peer contexts. Game Session reserves the exact tuple and attaches // Account's redeemed projection in its isolated V35 repository; Account's current // attempt observation and World participation acquisition then traverse native // same-namespace mTLS receivers. Launch association below remains mocked, and retained @@ -3900,7 +4178,8 @@ public void close() { gameSessionServer, accountServer, worldServer, - gdServer); + gdServer, + loggingServer); } } @@ -4351,7 +4630,7 @@ private Store gameDesignStore() { savedVersion.getIdentitySourceGameTenantKey(), savedVersion.getIdentitySourceProvenanceKind()); assertThat(new GameDesignSourceRepository(store.dsl()).readGenesis(target)).isPresent(); - return store.withIdentity(target, savedVersion); + return store.withIdentity(target, savedVersion, creation); } private static SelectedOwnerIntakeSourceReadScope selectedOwnerSourceScope( @@ -4628,6 +4907,37 @@ private static GameSessionAttemptStore gameSessionAttemptStore() { new GameSessionStartSessionOperatorAttemptRepository(dsl, Duration.ofSeconds(30))); } + private static LoggingReservationStore loggingReservationStore() { + String schema = "genuine_selected_logging_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(LOGGING_POSTGRES.getJdbcUrl()); + dataSource.setUsername(LOGGING_POSTGRES.getUsername()); + dataSource.setPassword(LOGGING_POSTGRES.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(migrationLocation("logging-admin")) + .target(MigrationVersion.fromVersion("4")) + .load() + .migrate(); + + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + assertThat( + dsl.fetch( + "SELECT version FROM flyway_schema_history WHERE success " + + "ORDER BY installed_rank") + .getValues("version", String.class)) + .containsExactly("1", "2", "3", "4"); + var mutationScope = + StartSessionReservationMutationTestFixtures.forRunOwnedPostgres(LOGGING_POSTGRES, schema); + return new LoggingReservationStore(dsl, mutationScope.service()); + } + private static Store serviceStore(PostgreSQLContainer postgres, String service) { var schema = service.replace('-', '_') + "_" + UUID.randomUUID().toString().replace("-", ""); var data = @@ -4648,7 +4958,7 @@ private static Store serviceStore(PostgreSQLContainer postgres, String servic configuration.set(SQLDialect.POSTGRES); configuration.set(new DataSourceConnectionProvider(new TransactionAwareDataSourceProxy(data))); configuration.set(new SpringTransactionProvider(transactions)); - return new Store(DSL.using(configuration), transactions, null, null); + return new Store(DSL.using(configuration), transactions, null, null, null); } private static String migrationLocation(String service) { @@ -5013,6 +5323,84 @@ private static String loopback(Server server) { return "127.0.0.1:" + server.getPort(); } + private static Server loggingClaimServer( + TestPki pki, + StartSessionPreAuthorizationReservationService reservationService, + Path approvedAccountLeaves, + List requests, + List responses) + throws Exception { + StartSessionReservationEvidenceGrpcService receiver = + new StartSessionReservationEvidenceGrpcService( + reservationService, + new StartSessionReservationEvidenceLeafApproval(approvedAccountLeaves.toString()), + NAMESPACE) { + @Override + public void readCurrentClaimEvidence( + ReadCurrentClaimEvidenceRequest request, + StreamObserver responseObserver) { + requests.add(request); + super.readCurrentClaimEvidence( + request, + new StreamObserver<>() { + @Override + public void onNext(ReadCurrentClaimEvidenceResponse response) { + responses.add(response); + responseObserver.onNext(response); + } + + @Override + public void onError(Throwable failure) { + responseObserver.onError(failure); + } + + @Override + public void onCompleted() { + responseObserver.onCompleted(); + } + }); + } + }; + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + pki.server("logging-admin-service").certificate().toFile(), + pki.server("logging-admin-service").key().toFile()) + .trustManager(pki.ca().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + receiver, + new AuthTokenInterceptor( + new JwtUtil("a".repeat(64), 3_600_000L), + Set.of( + "logging_admin.v1.StartSessionReservationEvidenceService/" + + "ReadCurrentClaimEvidence")), + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static StartSessionReservationEvidenceClient currentClaimGrpcClient( + int port, TestPki pki) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService("127.0.0.1:" + port); + return new StartSessionReservationEvidenceClient( + endpoints, + pki.client("account-service"), + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop()); + } + + private static String certificateSha256(Path certificate) throws Exception { + try (var input = Files.newInputStream(certificate)) { + var parsed = CertificateFactory.getInstance("X.509").generateCertificate(input); + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(parsed.getEncoded())); + } + } + private static void stopAll(Server... servers) throws InterruptedException { for (var server : servers) if (server != null) server.shutdownNow(); var terminated = true; @@ -5208,18 +5596,25 @@ private record Store( DSLContext dsl, DataSourceTransactionManager transactions, TargetProof target, - Version version) { + Version version, + FreshTenantCreationEvidence freshTenantCreationEvidence) { T transaction(Supplier operation) { var transaction = new TransactionTemplate(transactions); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); return transaction.execute(ignored -> operation.get()); } - Store withIdentity(TargetProof target, Version version) { - return new Store(dsl, transactions, target, version); + Store withIdentity( + TargetProof target, + Version version, + FreshTenantCreationEvidence freshTenantCreationEvidence) { + return new Store(dsl, transactions, target, version, freshTenantCreationEvidence); } } + private record LoggingReservationStore( + DSLContext dsl, StartSessionPreAuthorizationReservationService service) {} + private record TestIdentity(Path certificate, Path key) { CommonGrpcClientProperties properties(Path ca) { var result = new CommonGrpcClientProperties(); @@ -5270,6 +5665,7 @@ private static final class TestPki { for (String service : List.of( "account-service", + "logging-admin-service", "game-session-service", "game-design-service", "world-management-service", @@ -5294,6 +5690,11 @@ CommonGrpcClientProperties client(String service) { .properties(ca); } + Path clientCertificate(String service) { + return Objects.requireNonNull(clients.get(service), "unknown test client identity") + .certificate(); + } + private static TestIdentity issue( Path root, String service, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionPublishedRealmPolicyReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionPublishedRealmPolicyReadGrpcServiceTest.java new file mode 100644 index 0000000000..a9ab2f4ada --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionPublishedRealmPolicyReadGrpcServiceTest.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.gamedesign.draft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.StartSessionPublishedRealmPolicyReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.publication.StartSessionPublishedRealmPolicyReadService; +import net.firedevops.firemud.gamedesign.publication.StartSessionTemplateAssociationReadService; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionPublishedRealmPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionPublishedRealmPolicyResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +/** + * Transport denial and ordering proofs; no mocked success is treated as owner producer evidence. + */ +class GameDesignStartSessionPublishedRealmPolicyReadGrpcServiceTest { + private static final String NAMESPACE = "test"; + + private final StartSessionTemplateAssociationReadService associationReader = + mock(StartSessionTemplateAssociationReadService.class); + private final StartSessionPublishedRealmPolicyReadService publishedPolicyReader = + mock(StartSessionPublishedRealmPolicyReadService.class); + private final GameDesignStartSessionPublishedRealmPolicyReadGrpcService service = + new GameDesignStartSessionPublishedRealmPolicyReadGrpcService( + associationReader, publishedPolicyReader, NAMESPACE); + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void authenticatesExactSameNamespacePeerBeforeDecoding() { + var observer = new Collector(); + + try (MockedStatic codec = + Mockito.mockStatic(StartSessionPublishedRealmPolicyReadGrpcCodec.class)) { + service.readStartSessionPublishedRealmPolicy( + ReadStartSessionPublishedRealmPolicyRequest.getDefaultInstance(), observer); + codec.verifyNoInteractions(); + } + + assertThat(observer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(associationReader, publishedPolicyReader); + } + + @Test + void rejectsOtherWorkloadBeforeDecodingOrOwnerReads() { + var observer = + invokeAs( + ReadStartSessionPublishedRealmPolicyRequest.getDefaultInstance(), "account-service"); + + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + verifyNoInteractions(associationReader, publishedPolicyReader); + } + + @Test + void rejectsAuthenticatedUserContextBeforeDecodingOrOwnerReads() { + SessionContext.setContext("123", java.util.List.of(), java.util.Map.of()); + + Collector observer; + try (MockedStatic codec = + Mockito.mockStatic(StartSessionPublishedRealmPolicyReadGrpcCodec.class)) { + observer = + invokeAs( + ReadStartSessionPublishedRealmPolicyRequest.getDefaultInstance(), + "game-session-service"); + codec.verifyNoInteractions(); + } + + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + verifyNoInteractions(associationReader, publishedPolicyReader); + } + + @Test + void AccountDenialReturnsNoContentAndMakesZeroPublishedSourceOrPolicyReads() { + var request = + ReadStartSessionPublishedRealmPolicyRequest.newBuilder() + .setTargetNamespace(NAMESPACE) + .build(); + var authorizationRequest = mock(StartSessionTemplateAssociationReadEvidence.Request.class); + var wireRequest = + new StartSessionPublishedRealmPolicyReadGrpcCodec.WireRequest( + request, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + authorizationRequest, + new DraftCommitBinding.TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 17L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW")); + when(associationReader.read(authorizationRequest)) + .thenThrow(Status.PERMISSION_DENIED.withDescription("denied").asRuntimeException()); + + try (MockedStatic codec = + Mockito.mockStatic(StartSessionPublishedRealmPolicyReadGrpcCodec.class)) { + codec + .when(() -> StartSessionPublishedRealmPolicyReadGrpcCodec.fromRequest(request)) + .thenReturn(wireRequest); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + Mockito.verify(associationReader).read(authorizationRequest); + verifyNoInteractions(publishedPolicyReader); + } + } + + @Test + void AccountUnavailableReturnsNoContentAndMakesZeroPublishedSourceOrPolicyReads() { + var request = + ReadStartSessionPublishedRealmPolicyRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .build(); + var authorizationRequest = mock(StartSessionTemplateAssociationReadEvidence.Request.class); + var wireRequest = wireRequest(request, authorizationRequest); + when(associationReader.read(authorizationRequest)) + .thenThrow(Status.UNAVAILABLE.withDescription("Account unavailable").asRuntimeException()); + + try (MockedStatic codec = + Mockito.mockStatic(StartSessionPublishedRealmPolicyReadGrpcCodec.class)) { + codec + .when(() -> StartSessionPublishedRealmPolicyReadGrpcCodec.fromRequest(request)) + .thenReturn(wireRequest); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + Mockito.verify(associationReader).read(authorizationRequest); + verifyNoInteractions(publishedPolicyReader); + } + } + + @Test + void mismatchedAccountConfirmedOriginalRequestMakesZeroPublishedSourceOrPolicyReads() { + var request = + ReadStartSessionPublishedRealmPolicyRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .build(); + var authorizationRequest = mock(StartSessionTemplateAssociationReadEvidence.Request.class); + var wireRequest = wireRequest(request, authorizationRequest); + var mismatchedRequest = mock(StartSessionTemplateAssociationReadEvidence.Request.class); + var authorizationResult = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + when(authorizationResult.request()).thenReturn(mismatchedRequest); + when(associationReader.read(authorizationRequest)).thenReturn(authorizationResult); + + try (MockedStatic codec = + Mockito.mockStatic(StartSessionPublishedRealmPolicyReadGrpcCodec.class)) { + codec + .when(() -> StartSessionPublishedRealmPolicyReadGrpcCodec.fromRequest(request)) + .thenReturn(wireRequest); + + var observer = invokeAs(request, "game-session-service"); + + assertThat(observer.error).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + Mockito.verify(associationReader).read(authorizationRequest); + verifyNoInteractions(publishedPolicyReader); + } + } + + private static StartSessionPublishedRealmPolicyReadGrpcCodec.WireRequest wireRequest( + ReadStartSessionPublishedRealmPolicyRequest request, + StartSessionTemplateAssociationReadEvidence.Request authorizationRequest) { + return new StartSessionPublishedRealmPolicyReadGrpcCodec.WireRequest( + request, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + authorizationRequest, + new DraftCommitBinding.TargetProof( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 17L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW")); + } + + private Collector invokeAs(ReadStartSessionPublishedRealmPolicyRequest request, String workload) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + workload, NAMESPACE, workload); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + var observer = new Collector(); + service.readStartSessionPublishedRealmPolicy(request, observer); + return observer; + } finally { + context.detach(previous); + } + } + + private static final class Collector + implements StreamObserver { + private ReadStartSessionPublishedRealmPolicyResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadStartSessionPublishedRealmPolicyResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionPublishedRealmPolicyReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionPublishedRealmPolicyReadServiceTest.java new file mode 100644 index 0000000000..410e14182f --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionPublishedRealmPolicyReadServiceTest.java @@ -0,0 +1,301 @@ +package net.firedevops.firemud.gamedesign.publication; + +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.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class StartSessionPublishedRealmPolicyReadServiceTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID VERSION = UUID.randomUUID(); + private static final UUID SOURCE_OPERATION = UUID.randomUUID(); + private static final UUID COMMIT = UUID.randomUUID(); + private static final String SOURCE_DIGEST = "sha256:" + "a".repeat(64); + private static final String RELEASE_DIGEST = "sha256:" + "c".repeat(64); + private static final String WORLD = "foundry"; + private static final long SOURCE_ROW_ID = 41L; + private static final String SOURCE_TENANT_KEY = "private-tenant"; + private static final String PROVENANCE = "NEW_GAME_ROW"; + private static final String RELEASE_REF = "release/immutable-41"; + private static final String WORKFLOW = "publish-workflow-41"; + private static final String MANIFEST = "sha256:" + "b".repeat(64); + private static final String GENERATION = "gen-1"; + + @Test + void readsExactSourceAndSealedPolicyInsideIndependentReadOnlyRepeatableReadSnapshot() { + var sources = mock(GameAuthoredWorldSourceRepository.class); + var policies = mock(RealmPolicyPublicationRepository.class); + var transactions = spy(transactionManager()); + var target = target(); + var descriptor = descriptor(); + var release = release(); + var source = source(); + var published = published(target, COMMIT, 8L); + when(sources.readExactSourceSnapshot(NAMESPACE, SOURCE_OPERATION, TENANT, WORLD, SOURCE_DIGEST)) + .thenReturn(Optional.of(source)); + when(policies.readPublishedSet(target)).thenReturn(Optional.of(published)); + var service = new StartSessionPublishedRealmPolicyReadService(sources, policies, transactions); + + try (var readback = stubTerminal(published, 8L, MANIFEST)) { + var result = + service.read( + new StartSessionPublishedRealmPolicyReadService.ReadRequest( + descriptor, release, target)); + + assertThat(result.sourceEvidence()).isSameAs(source); + assertThat(result.publishedSet()).isSameAs(published); + var order = inOrder(transactions, sources, policies); + order.verify(transactions).getTransaction(any(TransactionDefinition.class)); + order + .verify(sources) + .readExactSourceSnapshot(NAMESPACE, SOURCE_OPERATION, TENANT, WORLD, SOURCE_DIGEST); + order.verify(policies).readPublishedSet(target); + } + } + + @Test + void failsClosedWhenTheExactSourceOrSealedSetIsMissing() { + var sources = mock(GameAuthoredWorldSourceRepository.class); + var policies = mock(RealmPolicyPublicationRepository.class); + var target = target(); + var descriptor = descriptor(); + var release = release(); + when(sources.readExactSourceSnapshot(NAMESPACE, SOURCE_OPERATION, TENANT, WORLD, SOURCE_DIGEST)) + .thenReturn(Optional.empty()); + var service = + new StartSessionPublishedRealmPolicyReadService(sources, policies, transactionManager()); + var request = + new StartSessionPublishedRealmPolicyReadService.ReadRequest(descriptor, release, target); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("AUTHORED_WORLD_SOURCE_UNAVAILABLE"); + verifyNoInteractions(policies); + + var source = source(); + when(sources.readExactSourceSnapshot(NAMESPACE, SOURCE_OPERATION, TENANT, WORLD, SOURCE_DIGEST)) + .thenReturn(Optional.of(source)); + when(policies.readPublishedSet(target)).thenReturn(Optional.empty()); + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("PUBLISHED_REALM_POLICY_SET_UNAVAILABLE"); + } + + @Test + void rejectsReleaseReferenceSubstitution() { + var target = target(); + var descriptor = descriptor(); + var release = release(); + var sources = mock(GameAuthoredWorldSourceRepository.class); + var policies = mock(RealmPolicyPublicationRepository.class); + var published = published(target, COMMIT, 8L); + var source = source(); + when(sources.readExactSourceSnapshot(NAMESPACE, SOURCE_OPERATION, TENANT, WORLD, SOURCE_DIGEST)) + .thenReturn(Optional.of(source)); + when(policies.readPublishedSet(target)).thenReturn(Optional.of(published)); + when(published.publishedReleaseBundleRef()).thenReturn("release/substituted"); + var service = + new StartSessionPublishedRealmPolicyReadService(sources, policies, transactionManager()); + + try (var readback = stubTerminal(published, 8L, MANIFEST)) { + assertReleaseConflict(service, descriptor, release, target); + } + } + + @Test + void rejectsChangedCommitEpochAndReleaseManifestEvidence() { + assertRejectedReadback(COMMIT, 10L, MANIFEST); + assertRejectedReadback(UUID.randomUUID(), 8L, MANIFEST); + assertRejectedReadback(COMMIT, 8L, "sha256:" + "d".repeat(64)); + } + + private static void assertRejectedReadback(UUID commit, long publicationEpoch, String manifest) { + var target = target(); + var descriptor = descriptor(); + var release = release(); + var sources = mock(GameAuthoredWorldSourceRepository.class); + var policies = mock(RealmPolicyPublicationRepository.class); + var published = published(target, commit, publicationEpoch); + var source = source(); + when(sources.readExactSourceSnapshot(NAMESPACE, SOURCE_OPERATION, TENANT, WORLD, SOURCE_DIGEST)) + .thenReturn(Optional.of(source)); + when(policies.readPublishedSet(target)).thenReturn(Optional.of(published)); + var service = + new StartSessionPublishedRealmPolicyReadService(sources, policies, transactionManager()); + + try (var readback = stubTerminal(published, publicationEpoch, manifest)) { + assertReleaseConflict(service, descriptor, release, target); + } + } + + private static void assertReleaseConflict( + StartSessionPublishedRealmPolicyReadService service, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence release, + TargetProof target) { + assertThatThrownBy( + () -> + service.read( + new StartSessionPublishedRealmPolicyReadService.ReadRequest( + descriptor, release, target))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("START_SESSION_POLICY_RELEASE_BINDING_CONFLICT"); + } + + private static ReadbackFixture stubTerminal( + RealmPolicyPublishedEvidence.PublishedSet published, + long publicationEpoch, + String terminalManifest) { + var content = mock(GameDesignPublicationTerminalEvidence.ReleaseContent.class); + when(content.canonicalTenantId()).thenReturn(TENANT); + when(content.canonicalVersionId()).thenReturn(VERSION); + when(content.publishedReleaseBundleRef()).thenReturn(RELEASE_REF); + when(content.versionNumber()).thenReturn(1); + when(content.attestationSchemaVersion()).thenReturn("v2"); + when(content.publishWorkflowId()).thenReturn(WORKFLOW); + when(content.manifestHash()).thenReturn(terminalManifest); + when(content.manifestSchemaVersion()).thenReturn(1); + when(content.requiredManifestAssetKeys()).thenReturn(List.of()); + when(content.artifactDigests()).thenReturn(List.of()); + when(content.commandDefinitions()).thenReturn(List.of()); + when(content.generationConfigRevision()).thenReturn(GENERATION); + when(content.worldStartLocationEvidence()).thenReturn(null); + when(content.participantDigests()).thenReturn(List.of()); + var terminal = mock(GameDesignPublicationTerminalEvidence.class); + when(terminal.releaseContent()).thenReturn(content); + when(terminal.outcome()).thenReturn(GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED); + when(terminal.publicationVersionStateEpoch()).thenReturn(publicationEpoch); + when(terminal.publishedReleaseBundleRef()).thenReturn(RELEASE_REF); + when(terminal.publishedReleaseBundleDigest()).thenReturn(RELEASE_DIGEST); + byte[] bytes = {1}; + when(published.terminalEvidenceBytes()).thenReturn(bytes); + var decoder = Mockito.mockStatic(GameDesignPublicationTerminalEvidence.class); + decoder + .when(() -> GameDesignPublicationTerminalEvidence.fromStored(bytes)) + .thenReturn(terminal); + return new ReadbackFixture(decoder); + } + + private static PlatformTransactionManager transactionManager() { + return new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + var requiredDefinition = + definition == null ? TransactionDefinition.withDefaults() : definition; + assertThat(requiredDefinition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(requiredDefinition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(requiredDefinition.isReadOnly()).isTrue(); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + }; + } + + private static TargetProof target() { + return new TargetProof( + TENANT, VERSION, 17L, SOURCE_TENANT_KEY, SOURCE_ROW_ID, SOURCE_TENANT_KEY, PROVENANCE); + } + + private static AuthoredWorldSourceEvidence source() { + var source = mock(AuthoredWorldSourceEvidence.class); + when(source.targetNamespace()).thenReturn(NAMESPACE); + when(source.operationId()).thenReturn(SOURCE_OPERATION); + when(source.evidenceDigest()).thenReturn(SOURCE_DIGEST); + when(source.canonicalTenantId()).thenReturn(TENANT); + when(source.worldSlug()).thenReturn(WORLD); + when(source.sourceGameRowId()).thenReturn(SOURCE_ROW_ID); + when(source.sourceGameTenantKey()).thenReturn(SOURCE_TENANT_KEY); + when(source.provenanceKind()).thenReturn(PROVENANCE); + return source; + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptor() { + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(descriptor.authoredWorldSourceOperationId()).thenReturn(SOURCE_OPERATION); + when(descriptor.authoredWorldSourceEvidenceDigest()).thenReturn(SOURCE_DIGEST); + when(descriptor.canonicalTenantId()).thenReturn(TENANT); + when(descriptor.worldSlug()).thenReturn(WORLD); + when(descriptor.versionId()).thenReturn(17L); + when(descriptor.versionStateEpoch()).thenReturn(9L); + when(descriptor.publishedReleaseBundleRef()).thenReturn(RELEASE_REF); + return descriptor; + } + + private static AuthoredWorldReleaseAttestationEvidence release() { + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.authoredWorldSourceOperationId()).thenReturn(SOURCE_OPERATION); + when(release.authoredWorldSourceEvidenceDigest()).thenReturn(SOURCE_DIGEST); + when(release.canonicalTenantId()).thenReturn(TENANT); + when(release.canonicalVersionId()).thenReturn(VERSION); + when(release.worldSlug()).thenReturn(WORLD); + when(release.schemaVersion()) + .thenReturn(AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION); + when(release.publishedReleaseBundleRef()).thenReturn(RELEASE_REF); + when(release.versionStateEpoch()).thenReturn(9L); + when(release.publishWorkflowId()).thenReturn(WORKFLOW); + when(release.commitId()).thenReturn(COMMIT.toString()); + when(release.participantDigests()).thenReturn(List.of()); + when(release.manifestHash()).thenReturn(MANIFEST); + when(release.manifestSchemaVersion()).thenReturn(1); + when(release.requiredManifestAssetKeys()).thenReturn(List.of()); + when(release.artifactDigests()).thenReturn(List.of()); + when(release.commandDefinitions()).thenReturn(List.of()); + when(release.generationConfigRevision()).thenReturn(GENERATION); + when(release.worldStartLocationEvidence()).thenReturn(null); + return release; + } + + private static RealmPolicyPublishedEvidence.PublishedSet published( + TargetProof target, UUID sourceCommit, long publicationEpoch) { + var published = mock(RealmPolicyPublishedEvidence.PublishedSet.class); + when(published.target()).thenReturn(target); + when(published.versionNumber()).thenReturn(1); + when(published.sourceCommitId()).thenReturn(sourceCommit); + when(published.publicationVersionStateEpoch()).thenReturn(publicationEpoch); + when(published.publishedReleaseBundleRef()).thenReturn(RELEASE_REF); + when(published.publishedReleaseBundleDigest()).thenReturn(RELEASE_DIGEST); + when(published.publishWorkflowId()).thenReturn(WORKFLOW); + when(published.manifestHash()).thenReturn(MANIFEST); + return published; + } + + private record ReadbackFixture(MockedStatic decoder) + implements AutoCloseable { + @Override + public void close() { + decoder.close(); + } + } +} diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index c094ce54ce..21d01eeeaa 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -73,6 +73,22 @@ dependencies { runtimeOnly(libs.junixsocket.native.common) runtimeOnly(libs.jjwt.impl) runtimeOnly(libs.jjwt.jackson) + testImplementation( + project( + mapOf( + "path" to ":game-design-service", + "configuration" to "gameDesignCanonicalPublicationFixtureProof" + ) + ) + ) + integrationTestImplementation( + project( + mapOf( + "path" to ":game-design-service", + "configuration" to "gameDesignCanonicalPublicationFixtureProof" + ) + ) + ) testFixturesImplementation(project(":entity-management-service")) testFixturesImplementation(project(":game-logic-service")) testFixturesImplementation(project(":social-groups-service")) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java new file mode 100644 index 0000000000..72332e8058 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.gamesession.client; + +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.gamedesign.StartSessionPublishedRealmPolicyReadGrpcCodec; +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.GameDesignStartSessionPublishedRealmPolicyReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for the standalone immutable published-policy read. */ +public final class GameDesignPublishedRealmPolicyClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignStartSessionPublishedRealmPolicyReadServiceGrpc + .GameDesignStartSessionPublishedRealmPolicyReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GameDesignPublishedRealmPolicyClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GameDesignPublishedRealmPolicyClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Game Design published-policy client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Game Design published-policy read stub unavailable"); + } + initialized = true; + } + + /** Returns only fully correlated Account, source, and immutable policy evidence. */ + public StartSessionPublishedRealmPolicyReadGrpcCodec.ReadResult read( + StartSessionPublishedRealmPolicyReadGrpcCodec.ReadRequest request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Game Design published-policy read requires no ambient transaction synchronization"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Game Design published-policy read must use the configured workload namespace"); + } + var wireRequest = StartSessionPublishedRealmPolicyReadGrpcCodec.toRequest(request); + StartSessionPublishedRealmPolicyReadGrpcCodec.requireRequestSerializedSize(wireRequest); + var response = + requireStub() + .withMaxInboundMessageSize( + StartSessionPublishedRealmPolicyReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readStartSessionPublishedRealmPolicy(wireRequest); + StartSessionPublishedRealmPolicyReadGrpcCodec.requireResponseSerializedSize(response); + try { + return StartSessionPublishedRealmPolicyReadGrpcCodec.fromResponse( + StartSessionPublishedRealmPolicyReadGrpcCodec.fromRequest(wireRequest), response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid or mismatched published-policy evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignStartSessionPublishedRealmPolicyReadServiceGrpc + .GameDesignStartSessionPublishedRealmPolicyReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignStartSessionPublishedRealmPolicyReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignStartSessionPublishedRealmPolicyReadServiceGrpc + .GameDesignStartSessionPublishedRealmPolicyReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Design published-policy client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Game Design published-policy read requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Game Design published-policy read requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Game Design published-policy read requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Game Design published-policy read " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Game Design published-policy read " + label + " must be an existing readable file"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java new file mode 100644 index 0000000000..87a70db4e4 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java @@ -0,0 +1,1252 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Game Session owner intake for one fresh public-production SHARED realm. + * + *

The caller must obtain the source and published policy set from authenticated Game Design + * owner reads before calling this class. These typed values and their digests are validated and + * durably retained here, but constructor bytes alone do not authenticate Game Design. This + * repository creates no launch, runtime, activation, or admission state. + */ +public final class GameSessionCanonicalRealmCatalogRepository { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final int INITIAL_CATALOG_REVISION = 1; + private static final Set CREATION_EVIDENCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + + private final DSLContext dsl; + private final String workloadNamespace; + private final TransactionTemplate writeTransaction; + private final TransactionTemplate readTransaction; + + public GameSessionCanonicalRealmCatalogRepository( + DSLContext dsl, PlatformTransactionManager transactionManager, String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is missing or invalid"); + } + this.workloadNamespace = workloadNamespace; + this.writeTransaction = new TransactionTemplate(transactionManager); + this.writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.readTransaction = new TransactionTemplate(transactionManager); + this.readTransaction.setReadOnly(true); + this.readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + /** + * Retains one exact source and sealed policy set, creates the GS-owned source-intake and + * public-production SHARED catalog rows atomically, then independently reads the full result. The + * two request IDs are caller-stable operation selectors; allocated GS operation and realm UUIDs + * are never derived from Game Design identity. + */ + public CanonicalRealmCatalog establishFreshPublicRealm( + FreshTenantAssociation association, + AuthoredWorldSourceEvidence source, + RealmPolicyPublishedEvidence.PublishedSet publishedSet, + UUID intakeRequestId, + UUID catalogRequestId) { + requireNoActiveOwnerTransaction(); + PreparedInput input = + prepareInput(association, source, publishedSet, intakeRequestId, catalogRequestId); + + CanonicalRealmCatalog committed = + writeTransaction.execute(status -> establishInTransaction(input)); + if (committed == null) { + throw new InvalidCanonicalRealmCatalogException( + "Game Session canonical realm transaction returned no result"); + } + + CanonicalRealmCatalog independentReadback = + readTransaction.execute( + status -> + readByCanonicalTenantIdInTransaction(input.source().canonicalTenantId()) + .orElse(null)); + if (independentReadback == null || !matchesInput(independentReadback, input)) { + throw new InvalidCanonicalRealmCatalogException( + "Committed canonical realm catalog failed independent exact source and policy readback"); + } + return independentReadback; + } + + /** Reads only complete, mutually consistent stored evidence and never calls Game Design. */ + public Optional readByCanonicalTenantId(UUID canonicalTenantId) { + requireNoActiveOwnerTransaction(); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + Optional result = + readTransaction.execute(status -> readByCanonicalTenantIdInTransaction(canonicalTenantId)); + return Objects.requireNonNull(result, "Game Session canonical catalog read returned no result"); + } + + private CanonicalRealmCatalog establishInTransaction(PreparedInput input) { + requireOwnerTransaction(); + lockIdentity(input); + verifyStoredFreshAssociation(input.association(), input.source()); + + Optional byTenant = + readByCanonicalTenantIdInTransaction(input.source().canonicalTenantId()); + Optional byRequest = + readByCatalogRequestIdInTransaction(input.catalogRequestId()); + if (byTenant.isPresent() || byRequest.isPresent()) { + if (byTenant.isEmpty() + || byRequest.isEmpty() + || !byTenant.orElseThrow().realmId().equals(byRequest.orElseThrow().realmId()) + || !matchesInput(byTenant.orElseThrow(), input)) { + throw new InvalidCanonicalRealmCatalogException( + "Canonical realm retry differs from the complete original source or published policy evidence"); + } + return byTenant.orElseThrow(); + } + + rejectPartialOrConflictingOwnerRows(input); + rejectRetainedTenant(input.source().canonicalTenantId()); + + String intakeRequestDigest = intakeRequestDigest(input); + UUID intakeOperationId = allocateGsUuid(input.foreignIds()); + String intakeReceiptDigest = intakeReceiptDigest(intakeRequestDigest, intakeOperationId); + String catalogRequestDigest = + catalogRequestDigest(input, intakeOperationId, intakeReceiptDigest); + UUID realmId = allocateGsUuid(union(input.foreignIds(), Set.of(intakeOperationId))); + UUID playableNamespaceId = + allocateGsUuid(union(input.foreignIds(), Set.of(intakeOperationId, realmId))); + String catalogReceiptDigest = + catalogReceiptDigest( + catalogRequestDigest, realmId, playableNamespaceId, INITIAL_CATALOG_REVISION); + + insertSourceBinding(input.source()); + insertSourceIntake(input, intakeOperationId, intakeRequestDigest, intakeReceiptDigest); + insertSharedNamespace( + input, intakeOperationId, intakeRequestDigest, intakeReceiptDigest, playableNamespaceId); + insertCatalog( + input, + intakeOperationId, + intakeRequestDigest, + intakeReceiptDigest, + catalogRequestDigest, + catalogReceiptDigest, + realmId, + playableNamespaceId); + + return readByCanonicalTenantIdInTransaction(input.source().canonicalTenantId()) + .orElseThrow( + () -> + new InvalidCanonicalRealmCatalogException( + "New canonical realm catalog did not read back inside the owner transaction")); + } + + private Optional readByCanonicalTenantIdInTransaction(UUID tenantId) { + requireOwnerTransaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM game_session_canonical_realm_catalog" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + workloadNamespace, + tenantId); + if (row == null) { + rejectOrphanedCatalogPrerequisites(tenantId); + return Optional.empty(); + } + return Optional.of(readCompleteCatalog(row)); + } + + private Optional readByCatalogRequestIdInTransaction(UUID requestId) { + requireOwnerTransaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM game_session_canonical_realm_catalog" + + " WHERE target_namespace = ? AND creation_request_id = ?", + workloadNamespace, + requestId); + if (row == null) { + return Optional.empty(); + } + UUID tenantId = required(row, "canonical_tenant_id", UUID.class); + return readByCanonicalTenantIdInTransaction(tenantId); + } + + private CanonicalRealmCatalog readCompleteCatalog(Record row) { + String namespace = required(row, "target_namespace", String.class); + UUID canonicalTenantId = required(row, "canonical_tenant_id", UUID.class); + String tenantSlug = required(row, "tenant_slug", String.class); + String worldSlug = required(row, "world_slug", String.class); + String worldDisplayName = required(row, "source_world_display_name", String.class); + UUID realmId = required(row, "realm_id", UUID.class); + String realmSlug = required(row, "realm_slug", String.class); + String realmDisplayName = required(row, "realm_display_name", String.class); + UUID playableNamespaceId = required(row, "playable_state_namespace_id", UUID.class); + String entryPolicyName = required(row, "character_creation_policy", String.class); + long catalogRevision = required(row, "catalog_revision", Long.class); + UUID catalogRequestId = required(row, "creation_request_id", UUID.class); + String catalogRequestDigest = required(row, "request_digest", String.class); + String catalogReceiptDigest = required(row, "receipt_digest", String.class); + UUID intakeOperationId = required(row, "source_intake_operation_id", UUID.class); + UUID intakeRequestId = required(row, "source_intake_request_id", UUID.class); + String intakeRequestDigest = required(row, "source_intake_request_digest", String.class); + String intakeReceiptDigest = required(row, "source_intake_receipt_digest", String.class); + int sourceSchemaVersion = required(row, "source_schema_version", Integer.class); + UUID sourceRegistrationRequestId = required(row, "source_registration_request_id", UUID.class); + UUID sourceOperationId = required(row, "source_operation_id", UUID.class); + String sourceRequestDigest = required(row, "source_request_digest", String.class); + long sourceGameRowId = required(row, "source_game_row_id", Long.class); + String sourceGameTenantKey = required(row, "source_game_tenant_key", String.class); + String provenanceKind = required(row, "source_provenance_kind", String.class); + String sourceEvidenceDigest = required(row, "source_evidence_digest", String.class); + byte[] publishedSetBytes = required(row, "complete_policy_set_evidence", byte[].class); + + if (!workloadNamespace.equals(namespace) + || !Boolean.TRUE.equals(required(row, "visible", Boolean.class)) + || !Boolean.TRUE.equals(required(row, "public_production", Boolean.class)) + || !"SHARED".equals(required(row, "state_scope", String.class))) { + throw new InvalidCanonicalRealmCatalogException( + "Stored canonical realm is outside the fresh public-production SHARED scope"); + } + + AuthoredWorldSourceEvidence source; + RealmPolicyPublishedEvidence.PublishedSet publishedSet; + try { + source = + new AuthoredWorldSourceEvidence( + sourceSchemaVersion, + namespace, + sourceRegistrationRequestId, + sourceOperationId, + sourceRequestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + sourceEvidenceDigest); + publishedSet = RealmPolicyPublishedEvidenceCodec.decode(publishedSetBytes); + if (!Arrays.equals( + publishedSetBytes, RealmPolicyPublishedEvidenceCodec.encode(publishedSet))) { + throw new IllegalArgumentException("Stored published policy evidence is not canonical"); + } + } catch (IllegalArgumentException invalid) { + throw new InvalidCanonicalRealmCatalogException( + "Stored canonical realm source or complete policy evidence is invalid", invalid); + } + + verifyStoredSourceBinding(source); + verifyStoredSourceIntake( + source, intakeOperationId, intakeRequestId, intakeRequestDigest, intakeReceiptDigest); + FreshTenantAssociation association = verifyStoredFreshAssociation(source, canonicalTenantId); + verifyStoredSharedNamespace( + source, + intakeOperationId, + intakeRequestId, + intakeRequestDigest, + intakeReceiptDigest, + playableNamespaceId); + + SelectedPolicy selected = selectPolicy(source, publishedSet); + String expectedCatalogRequestDigest = + catalogRequestDigest( + workloadNamespace, + catalogRequestId, + canonicalTenantId, + intakeOperationId, + intakeReceiptDigest, + selected.policyId(), + selected.policyDigest(), + publishedSet.policySetDigest()); + String expectedCatalogReceiptDigest = + catalogReceiptDigest( + expectedCatalogRequestDigest, realmId, playableNamespaceId, catalogRevision); + if (!tenantSlug.equals(source.tenantSlug()) + || !worldSlug.equals(source.worldSlug()) + || !worldDisplayName.equals(source.worldDisplayName()) + || !realmSlug.equals(selected.policy().realmSlug()) + || !realmDisplayName.equals(selected.policy().realmDisplayName()) + || !entryPolicyName.equals(selected.policy().entryPolicy().name()) + || !catalogRequestDigest.equals(expectedCatalogRequestDigest) + || !catalogReceiptDigest.equals(expectedCatalogReceiptDigest)) { + throw new InvalidCanonicalRealmCatalogException( + "Stored canonical realm receipt differs from exact source, selected policy, or actual revision"); + } + + verifyStoredCatalogSourceColumns( + row, source, intakeOperationId, intakeRequestId, intakeRequestDigest, intakeReceiptDigest); + + return new CanonicalRealmCatalog( + workloadNamespace, + canonicalTenantId, + association.gameSessionTenantId(), + association.associationOperationId(), + association.sourceEvidence(), + source, + intakeRequestId, + intakeOperationId, + intakeRequestDigest, + intakeReceiptDigest, + catalogRequestId, + catalogRequestDigest, + catalogReceiptDigest, + realmId, + playableNamespaceId, + tenantSlug, + worldSlug, + realmSlug, + realmDisplayName, + worldDisplayName, + entryPolicyName, + catalogRevision, + publishedSetBytes, + publishedSet); + } + + private void verifyStoredSourceBinding(AuthoredWorldSourceEvidence source) { + Record binding = + dsl.fetchOne( + "SELECT target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id," + + " source_game_tenant_key, provenance_kind" + + " FROM game_session_authored_world_tenant_source_binding" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + workloadNamespace, + source.canonicalTenantId()); + if (binding == null + || !workloadNamespace.equals(required(binding, "target_namespace", String.class)) + || !source.canonicalTenantId().equals(required(binding, "canonical_tenant_id", UUID.class)) + || !source.tenantSlug().equals(required(binding, "tenant_slug", String.class)) + || source.sourceGameRowId() != required(binding, "source_game_row_id", Long.class) + || !source + .sourceGameTenantKey() + .equals(required(binding, "source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(required(binding, "provenance_kind", String.class))) { + throw new InvalidCanonicalRealmCatalogException( + "Canonical realm has no exact immutable fresh tenant source binding"); + } + } + + private void verifyStoredSourceIntake( + AuthoredWorldSourceEvidence source, + UUID operationId, + UUID requestId, + String requestDigest, + String receiptDigest) { + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake" + + " WHERE target_namespace = ? AND operation_id = ?", + workloadNamespace, + operationId); + String expectedRequestDigest = + intakeRequestDigest( + workloadNamespace, requestId, source.operationId(), source.evidenceDigest()); + String expectedReceiptDigest = intakeReceiptDigest(expectedRequestDigest, operationId); + if (intake == null + || required(intake, "schema_version", Integer.class) != 1 + || required(intake, "source_schema_version", Integer.class) != source.schemaVersion() + || !workloadNamespace.equals(required(intake, "target_namespace", String.class)) + || !requestId.equals(required(intake, "intake_request_id", UUID.class)) + || !requestDigest.equals(required(intake, "request_digest", String.class)) + || !expectedRequestDigest.equals(requestDigest) + || !source + .registrationRequestId() + .equals(required(intake, "source_registration_request_id", UUID.class)) + || !source.operationId().equals(required(intake, "source_operation_id", UUID.class)) + || !source.requestDigest().equals(required(intake, "source_request_digest", String.class)) + || !source.canonicalTenantId().equals(required(intake, "canonical_tenant_id", UUID.class)) + || !source.tenantSlug().equals(required(intake, "tenant_slug", String.class)) + || !source.worldSlug().equals(required(intake, "world_slug", String.class)) + || !source.worldDisplayName().equals(required(intake, "world_display_name", String.class)) + || source.sourceGameRowId() != required(intake, "source_game_row_id", Long.class) + || !source + .sourceGameTenantKey() + .equals(required(intake, "source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(required(intake, "source_provenance_kind", String.class)) + || !source.evidenceDigest().equals(required(intake, "source_evidence_digest", String.class)) + || !receiptDigest.equals(required(intake, "receipt_digest", String.class)) + || !expectedReceiptDigest.equals(receiptDigest)) { + throw new InvalidCanonicalRealmCatalogException( + "Canonical realm source intake differs from complete original Game Design source evidence"); + } + } + + private FreshTenantAssociation verifyStoredFreshAssociation( + AuthoredWorldSourceEvidence source, UUID canonicalTenantId) { + Record row = + dsl.fetchOne( + "SELECT fresh.target_namespace, fresh.association_request_id," + + " fresh.source_schema_version, fresh.source_target_namespace," + + " fresh.source_request_id, fresh.source_canonical_tenant_id," + + " fresh.canonical_tenant_id, fresh.legacy_game_session_tenant_id," + + " fresh.source_game_row_id, fresh.source_game_tenant_key, fresh.provenance_kind," + + " fresh.association_kind, fresh.association_operation_id," + + " fresh.complete_source_evidence::text AS complete_source_evidence," + + " claim.target_namespace AS claim_namespace," + + " claim.canonical_tenant_id AS claim_canonical_tenant_id," + + " claim.legacy_game_session_tenant_id AS claim_tenant_id," + + " claim.association_kind AS claim_kind," + + " claim.reservation_kind AS claim_reservation_kind," + + " claim.association_operation_id AS claim_operation_id," + + " claim.association_request_id AS claim_request_id," + + " reservation.reservation_kind AS reservation_kind" + + " FROM game_session_fresh_tenant_association fresh" + + " LEFT JOIN game_session_tenant_canonical_claim claim" + + " ON claim.target_namespace = fresh.target_namespace" + + " AND claim.canonical_tenant_id = fresh.canonical_tenant_id" + + " LEFT JOIN game_session_tenant_scope_reservation reservation" + + " ON reservation.game_session_tenant_id = fresh.legacy_game_session_tenant_id" + + " WHERE fresh.target_namespace = ? AND fresh.canonical_tenant_id = ?", + workloadNamespace, + canonicalTenantId); + if (row == null) { + throw new InvalidCanonicalRealmCatalogException( + "Fresh canonical realm requires an existing complete Game Session tenant association"); + } + try { + String requestIdText = required(row, "association_request_id", UUID.class).toString(); + UUID associationOperationId = required(row, "association_operation_id", UUID.class); + UUID tenantId = required(row, "canonical_tenant_id", UUID.class); + long numericTenantId = required(row, "legacy_game_session_tenant_id", Long.class); + FreshTenantCreationEvidence creation = + parseCreationEvidence(required(row, "complete_source_evidence", String.class)); + if (!workloadNamespace.equals(required(row, "target_namespace", String.class)) + || !workloadNamespace.equals(required(row, "source_target_namespace", String.class)) + || !requestIdText.equals(required(row, "source_request_id", UUID.class).toString()) + || !tenantId.equals(required(row, "source_canonical_tenant_id", UUID.class)) + || required(row, "source_schema_version", Integer.class) != creation.schemaVersion() + || required(row, "source_game_row_id", Long.class) != creation.sourceGameRowId() + || !required(row, "source_game_tenant_key", String.class) + .equals(creation.sourceGameTenantKey()) + || !required(row, "provenance_kind", String.class).equals(creation.provenanceKind()) + || !"FRESH_SOURCE_BOUND".equals(required(row, "association_kind", String.class)) + || !creation.targetNamespace().equals(workloadNamespace) + || !creation + .creationRequestId() + .equals(required(row, "association_request_id", UUID.class)) + || !creation.canonicalTenantId().equals(tenantId) + || !creation.targetNamespace().equals(source.targetNamespace()) + || !creation.canonicalTenantId().equals(source.canonicalTenantId()) + || creation.sourceGameRowId() != source.sourceGameRowId() + || !creation.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !creation.provenanceKind().equals(source.provenanceKind()) + || !"FRESH_SOURCE_BOUND".equals(required(row, "claim_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(required(row, "claim_reservation_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(required(row, "reservation_kind", String.class)) + || !workloadNamespace.equals(required(row, "claim_namespace", String.class)) + || !tenantId.equals(required(row, "claim_canonical_tenant_id", UUID.class)) + || numericTenantId != required(row, "claim_tenant_id", Long.class) + || !associationOperationId.equals(required(row, "claim_operation_id", UUID.class)) + || !required(row, "association_request_id", UUID.class) + .equals(required(row, "claim_request_id", UUID.class)) + || associationOperationId.equals(creation.operationId())) { + throw new InvalidCanonicalRealmCatalogException( + "Stored fresh tenant association differs from complete source receipt or canonical claim"); + } + return new FreshTenantAssociation( + workloadNamespace, tenantId, numericTenantId, associationOperationId, creation); + } catch (IllegalArgumentException invalid) { + throw new InvalidCanonicalRealmCatalogException( + "Stored fresh tenant association contains invalid complete source evidence", invalid); + } + } + + private void verifyStoredFreshAssociation( + FreshTenantAssociation expected, AuthoredWorldSourceEvidence source) { + FreshTenantAssociation actual = + verifyStoredFreshAssociation(source, expected.canonicalTenantId()); + if (!expected.equals(actual)) { + throw new InvalidCanonicalRealmCatalogException( + "Supplied fresh tenant association is not the exact committed Game Session owner row"); + } + } + + private void verifyStoredSharedNamespace( + AuthoredWorldSourceEvidence source, + UUID intakeOperationId, + UUID intakeRequestId, + String intakeRequestDigest, + String intakeReceiptDigest, + UUID playableNamespaceId) { + Record row = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + workloadNamespace, + source.canonicalTenantId()); + if (row == null + || row.get("tenant_id", Long.class) != null + || !playableNamespaceId.equals(required(row, "playable_state_namespace_id", UUID.class)) + || !source.canonicalTenantId().equals(required(row, "canonical_tenant_id", UUID.class)) + || !workloadNamespace.equals(required(row, "target_namespace", String.class)) + || !intakeOperationId.equals(required(row, "source_intake_operation_id", UUID.class)) + || required(row, "source_intake_schema_version", Integer.class) != 1 + || !intakeRequestId.equals(required(row, "source_intake_request_id", UUID.class)) + || !intakeRequestDigest.equals(required(row, "source_intake_request_digest", String.class)) + || !intakeReceiptDigest.equals(required(row, "source_intake_receipt_digest", String.class)) + || required(row, "source_schema_version", Integer.class) != source.schemaVersion() + || !source + .registrationRequestId() + .equals(required(row, "source_registration_request_id", UUID.class)) + || !source.operationId().equals(required(row, "source_operation_id", UUID.class)) + || !source.requestDigest().equals(required(row, "source_request_digest", String.class)) + || source.sourceGameRowId() != required(row, "source_game_row_id", Long.class) + || !source + .sourceGameTenantKey() + .equals(required(row, "source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(required(row, "source_provenance_kind", String.class)) + || !source.evidenceDigest().equals(required(row, "source_evidence_digest", String.class))) { + throw new InvalidCanonicalRealmCatalogException( + "Canonical realm SHARED namespace does not retain the exact complete source intake"); + } + } + + private void verifyStoredCatalogSourceColumns( + Record row, + AuthoredWorldSourceEvidence source, + UUID intakeOperationId, + UUID intakeRequestId, + String intakeRequestDigest, + String intakeReceiptDigest) { + if (!source.targetNamespace().equals(required(row, "target_namespace", String.class)) + || !source.canonicalTenantId().equals(required(row, "canonical_tenant_id", UUID.class)) + || !source.tenantSlug().equals(required(row, "tenant_slug", String.class)) + || !source.worldSlug().equals(required(row, "world_slug", String.class)) + || !source + .worldDisplayName() + .equals(required(row, "source_world_display_name", String.class)) + || !intakeOperationId.equals(required(row, "source_intake_operation_id", UUID.class)) + || required(row, "source_intake_schema_version", Integer.class) != 1 + || !intakeRequestId.equals(required(row, "source_intake_request_id", UUID.class)) + || !intakeRequestDigest.equals(required(row, "source_intake_request_digest", String.class)) + || !intakeReceiptDigest.equals(required(row, "source_intake_receipt_digest", String.class)) + || required(row, "source_schema_version", Integer.class) != source.schemaVersion() + || !source + .registrationRequestId() + .equals(required(row, "source_registration_request_id", UUID.class)) + || !source.operationId().equals(required(row, "source_operation_id", UUID.class)) + || !source.requestDigest().equals(required(row, "source_request_digest", String.class)) + || source.sourceGameRowId() != required(row, "source_game_row_id", Long.class) + || !source + .sourceGameTenantKey() + .equals(required(row, "source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(required(row, "source_provenance_kind", String.class)) + || !source.evidenceDigest().equals(required(row, "source_evidence_digest", String.class))) { + throw new InvalidCanonicalRealmCatalogException( + "Canonical realm catalog columns differ from exact complete source intake evidence"); + } + } + + private void rejectPartialOrConflictingOwnerRows(PreparedInput input) { + AuthoredWorldSourceEvidence source = input.source(); + Record binding = + dsl.fetchOne( + "SELECT canonical_tenant_id FROM game_session_authored_world_tenant_source_binding" + + " WHERE target_namespace = ? AND (canonical_tenant_id = ? OR tenant_slug = ?" + + " OR source_game_row_id = ?)", + workloadNamespace, + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId()); + Record intake = + dsl.fetchOne( + "SELECT operation_id FROM game_session_authored_world_source_intake" + + " WHERE target_namespace = ? AND (intake_request_id = ?" + + " OR source_registration_request_id = ? OR source_operation_id = ?" + + " OR canonical_tenant_id = ?)", + workloadNamespace, + input.intakeRequestId(), + source.registrationRequestId(), + source.operationId(), + source.canonicalTenantId()); + Record shared = + dsl.fetchOne( + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + workloadNamespace, + source.canonicalTenantId()); + Record request = + dsl.fetchOne( + "SELECT realm_id FROM game_session_canonical_realm_catalog" + + " WHERE target_namespace = ? AND creation_request_id = ?", + workloadNamespace, + input.catalogRequestId()); + if (binding != null || intake != null || shared != null || request != null) { + throw new InvalidCanonicalRealmCatalogException( + "Partial, prior, or cross-tenant canonical owner rows cannot be adopted as a fresh catalog request"); + } + } + + private void rejectOrphanedCatalogPrerequisites(UUID canonicalTenantId) { + Record binding = + dsl.fetchOne( + "SELECT canonical_tenant_id FROM game_session_authored_world_tenant_source_binding" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + workloadNamespace, + canonicalTenantId); + Record intake = + dsl.fetchOne( + "SELECT operation_id FROM game_session_authored_world_source_intake" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + workloadNamespace, + canonicalTenantId); + Record shared = + dsl.fetchOne( + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + workloadNamespace, + canonicalTenantId); + Record catalog = + dsl.fetchOne( + "SELECT realm_id FROM game_session_canonical_realm_catalog" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + workloadNamespace, + canonicalTenantId); + if (binding != null || intake != null || shared != null || catalog != null) { + throw new InvalidCanonicalRealmCatalogException( + "Incomplete historical or partial canonical realm owner rows fail closed"); + } + } + + private void rejectRetainedTenant(UUID canonicalTenantId) { + Record retained = + dsl.fetchOne( + "SELECT canonical_tenant_id FROM game_session_retained_tenant_association" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + workloadNamespace, + canonicalTenantId); + if (retained != null) { + throw new InvalidCanonicalRealmCatalogException( + "Retained numeric tenant authority cannot be adopted by fresh canonical realm intake"); + } + } + + private void insertSourceBinding(AuthoredWorldSourceEvidence source) { + requireOne( + dsl.execute( + "INSERT INTO game_session_authored_world_tenant_source_binding" + + " (target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id," + + " source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", + workloadNamespace, + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()), + "authored-world tenant source binding"); + } + + private void insertSourceIntake( + PreparedInput input, UUID intakeOperationId, String requestDigest, String receiptDigest) { + AuthoredWorldSourceEvidence source = input.source(); + requireOne( + dsl.execute( + "INSERT INTO game_session_authored_world_source_intake" + + " (operation_id, schema_version, target_namespace, intake_request_id, request_digest," + + " source_schema_version, source_registration_request_id, source_operation_id," + + " source_request_digest, canonical_tenant_id, tenant_slug, world_slug," + + " world_display_name, source_game_row_id, source_game_tenant_key," + + " source_provenance_kind, source_evidence_digest, receipt_digest)" + + " VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + intakeOperationId, + workloadNamespace, + input.intakeRequestId(), + requestDigest, + source.schemaVersion(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + receiptDigest), + "authored-world source intake"); + } + + private void insertSharedNamespace( + PreparedInput input, + UUID intakeOperationId, + String intakeRequestDigest, + String intakeReceiptDigest, + UUID playableNamespaceId) { + AuthoredWorldSourceEvidence source = input.source(); + requireOne( + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace" + + " (tenant_id, playable_state_namespace_id, canonical_tenant_id, target_namespace," + + " source_intake_operation_id, source_intake_schema_version, source_intake_request_id," + + " source_intake_request_digest, source_intake_receipt_digest, source_schema_version," + + " source_registration_request_id, source_operation_id, source_request_digest," + + " source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest)" + + " VALUES (NULL, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + playableNamespaceId, + source.canonicalTenantId(), + workloadNamespace, + intakeOperationId, + input.intakeRequestId(), + intakeRequestDigest, + intakeReceiptDigest, + source.schemaVersion(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()), + "canonical tenant SHARED namespace"); + } + + private void insertCatalog( + PreparedInput input, + UUID intakeOperationId, + String intakeRequestDigest, + String intakeReceiptDigest, + String catalogRequestDigest, + String catalogReceiptDigest, + UUID realmId, + UUID playableNamespaceId) { + AuthoredWorldSourceEvidence source = input.source(); + SelectedPolicy selected = input.selectedPolicy(); + requireOne( + dsl.execute( + "INSERT INTO game_session_canonical_realm_catalog" + + " (target_namespace, canonical_tenant_id, tenant_slug, world_slug, realm_id," + + " realm_slug, realm_display_name, visible, public_production, state_scope," + + " playable_state_namespace_id, character_creation_policy, catalog_revision," + + " creation_request_id, request_digest, receipt_digest, source_intake_operation_id," + + " source_intake_schema_version, source_intake_request_id, source_intake_request_digest," + + " source_intake_receipt_digest, source_schema_version, source_registration_request_id," + + " source_operation_id, source_request_digest, source_world_display_name," + + " source_game_row_id, source_game_tenant_key, source_provenance_kind," + + " source_evidence_digest, complete_policy_set_evidence)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + workloadNamespace, + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + realmId, + selected.policy().realmSlug(), + selected.policy().realmDisplayName(), + playableNamespaceId, + selected.policy().entryPolicy().name(), + INITIAL_CATALOG_REVISION, + input.catalogRequestId(), + catalogRequestDigest, + catalogReceiptDigest, + intakeOperationId, + input.intakeRequestId(), + intakeRequestDigest, + intakeReceiptDigest, + source.schemaVersion(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + input.publishedSetBytes()), + "canonical public-production realm catalog"); + } + + private void lockIdentity(PreparedInput input) { + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ?, 1))", + workloadNamespace, + input.source().canonicalTenantId().toString()); + List requestLocks = + List.of( + "canonical-realm-intake:" + workloadNamespace + ":" + input.intakeRequestId(), + "canonical-realm-request:" + workloadNamespace + ":" + input.catalogRequestId()) + .stream() + .sorted() + .toList(); + for (String key : requestLocks) { + dsl.fetch("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", key); + } + } + + private PreparedInput prepareInput( + FreshTenantAssociation association, + AuthoredWorldSourceEvidence source, + RealmPolicyPublishedEvidence.PublishedSet publishedSet, + UUID intakeRequestId, + UUID catalogRequestId) { + Objects.requireNonNull(association, "association"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(publishedSet, "publishedSet"); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(catalogRequestId, "catalogRequestId"); + FreshTenantCreationEvidence creation = association.sourceEvidence(); + if (!workloadNamespace.equals(association.targetNamespace()) + || !workloadNamespace.equals(source.targetNamespace()) + || !association.canonicalTenantId().equals(source.canonicalTenantId()) + || !workloadNamespace.equals(creation.targetNamespace()) + || !association.canonicalTenantId().equals(creation.canonicalTenantId()) + || creation.sourceGameRowId() != source.sourceGameRowId() + || !creation.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !creation.provenanceKind().equals(source.provenanceKind()) + || !"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidCanonicalRealmCatalogException( + "Fresh tenant association and authored-world source differ in exact namespace, tenant, or NEW_GAME_ROW identity"); + } + SelectedPolicy selected = selectPolicy(source, publishedSet); + byte[] policyBytes; + RealmPolicyPublishedEvidence.PublishedSet decoded; + try { + policyBytes = RealmPolicyPublishedEvidenceCodec.encode(publishedSet); + decoded = RealmPolicyPublishedEvidenceCodec.decode(policyBytes); + if (!Arrays.equals(policyBytes, RealmPolicyPublishedEvidenceCodec.encode(decoded))) { + throw new IllegalArgumentException( + "Published policy evidence changed across canonical encoding"); + } + } catch (IllegalArgumentException invalid) { + throw new InvalidCanonicalRealmCatalogException( + "Complete canonical published policy evidence is required", invalid); + } + HashSet foreignIds = new HashSet<>(); + foreignIds.add(creation.creationRequestId()); + foreignIds.add(creation.operationId()); + foreignIds.add(creation.canonicalTenantId()); + foreignIds.add(association.associationOperationId()); + foreignIds.add(source.registrationRequestId()); + foreignIds.add(source.operationId()); + foreignIds.add(publishedSet.target().canonicalTenantId()); + foreignIds.add(publishedSet.target().canonicalVersionId()); + foreignIds.add(publishedSet.sourceCommitId()); + publishedSet.policies().forEach(policy -> foreignIds.add(policy.policyId())); + foreignIds.add(intakeRequestId); + foreignIds.add(catalogRequestId); + return new PreparedInput( + association, + source, + decoded, + selected, + intakeRequestId, + catalogRequestId, + policyBytes, + Set.copyOf(foreignIds)); + } + + private static SelectedPolicy selectPolicy( + AuthoredWorldSourceEvidence source, RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + GameDesignPublicationOperationBinding publicationOperation = + GameDesignPublicationOperationBinding.fromStored(publishedSet.operationBytes()); + if (!publishedSet.target().canonicalTenantId().equals(source.canonicalTenantId()) + || publishedSet.target().sourceGameRowId() != source.sourceGameRowId() + || !publishedSet.target().sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !publishedSet.target().sourceProvenanceKind().equals(source.provenanceKind()) + || !publicationOperation + .world() + .request() + .targetNamespace() + .equals(source.targetNamespace()) + || !"NEW_GAME_ROW".equals(publishedSet.target().sourceProvenanceKind())) { + throw new InvalidCanonicalRealmCatalogException( + "Published policy target or operation namespace differs from exact fresh authored-world source identity"); + } + List publicPolicies = + publishedSet.policies().stream() + .filter( + policy -> + policy.source().policy().visible() + && policy.source().policy().publicProduction()) + .toList(); + if (publishedSet.policyCount() != publishedSet.policies().size() + || publicPolicies.size() != 1) { + throw new InvalidCanonicalRealmCatalogException( + "Exactly one complete visible public-production policy is required"); + } + RealmPolicyPublishedEvidence.Policy selected = publicPolicies.getFirst(); + RealmEntryPolicy policy = selected.source().policy(); + if (policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || !source.worldSlug().equals(policy.worldSlug()) + || !source.worldDisplayName().equals(policy.worldDisplayName())) { + throw new InvalidCanonicalRealmCatalogException( + "Public-production policy must exactly match authored world and use SHARED state scope"); + } + return new SelectedPolicy(selected.policyId(), selected.policyDigest(), policy); + } + + private static boolean matchesInput(CanonicalRealmCatalog stored, PreparedInput input) { + return stored.targetNamespace().equals(input.source().targetNamespace()) + && stored.canonicalTenantId().equals(input.source().canonicalTenantId()) + && stored.gameSessionTenantId() == input.association().gameSessionTenantId() + && stored + .tenantAssociationOperationId() + .equals(input.association().associationOperationId()) + && stored.associationSourceEvidence().equals(input.association().sourceEvidence()) + && stored.sourceEvidence().equals(input.source()) + && stored.intakeRequestId().equals(input.intakeRequestId()) + && stored.catalogRequestId().equals(input.catalogRequestId()) + && stored.realmSlug().equals(input.selectedPolicy().policy().realmSlug()) + && stored.realmDisplayName().equals(input.selectedPolicy().policy().realmDisplayName()) + && stored.entryPolicy().equals(input.selectedPolicy().policy().entryPolicy().name()) + && Arrays.equals(stored.completePolicySetEvidence(), input.publishedSetBytes()); + } + + private static String intakeRequestDigest(PreparedInput input) { + return intakeRequestDigest( + input.source().targetNamespace(), + input.intakeRequestId(), + input.source().operationId(), + input.source().evidenceDigest()); + } + + private static String intakeRequestDigest( + String namespace, UUID intakeRequestId, UUID sourceOperationId, String sourceEvidenceDigest) { + return digest( + "gs-authored-world-source-intake-request/v1", + namespace, + intakeRequestId.toString(), + sourceOperationId.toString(), + sourceEvidenceDigest); + } + + private static String intakeReceiptDigest(String requestDigest, UUID intakeOperationId) { + return digest( + "gs-authored-world-source-intake-receipt/v1", requestDigest, intakeOperationId.toString()); + } + + private String catalogRequestDigest( + PreparedInput input, UUID intakeOperationId, String intakeReceiptDigest) { + return catalogRequestDigest( + workloadNamespace, + input.catalogRequestId(), + input.source().canonicalTenantId(), + intakeOperationId, + intakeReceiptDigest, + input.selectedPolicy().policyId(), + input.selectedPolicy().policyDigest(), + input.publishedSet().policySetDigest()); + } + + private static String catalogRequestDigest( + String namespace, + UUID catalogRequestId, + UUID canonicalTenantId, + UUID intakeOperationId, + String intakeReceiptDigest, + UUID policyId, + String policyDigest, + String policySetDigest) { + return digest( + "gs-canonical-public-realm-request/v1", + namespace, + catalogRequestId.toString(), + canonicalTenantId.toString(), + intakeOperationId.toString(), + intakeReceiptDigest, + policyId.toString(), + policyDigest, + policySetDigest); + } + + private static String catalogReceiptDigest( + String requestDigest, UUID realmId, UUID playableNamespaceId, long catalogRevision) { + return digest( + "gs-canonical-public-realm-receipt/v1", + requestDigest, + realmId.toString(), + playableNamespaceId.toString(), + Long.toString(catalogRevision)); + } + + private static String digest(String... segments) { + try { + MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); + sha256.update(frame(segments)); + return "sha256:" + HexFormat.of().formatHex(sha256.digest()); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + /** ADR0047 UTF-8 byte-length framing; every input segment has an unambiguous byte boundary. */ + private static byte[] frame(String... segments) { + ByteArrayOutputStream result = new ByteArrayOutputStream(); + for (String segment : segments) { + byte[] bytes = strictUtf8(segment); + result.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8)); + result.write(':'); + result.writeBytes(bytes); + } + return result.toByteArray(); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest segment"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(java.nio.CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException invalidUtf8) { + throw new InvalidCanonicalRealmCatalogException( + "Canonical owner digest input must be valid UTF-8", invalidUtf8); + } + } + + private static UUID allocateGsUuid(Set excluded) { + UUID allocated; + do { + allocated = UUID.randomUUID(); + } while (NIL_UUID.equals(allocated) || excluded.contains(allocated)); + return allocated; + } + + private static Set union(Set values, Set more) { + HashSet union = new HashSet<>(values); + union.addAll(more); + return Set.copyOf(union); + } + + private static FreshTenantCreationEvidence parseCreationEvidence(String serializedEvidence) { + try { + JsonNode json = JSON.readTree(serializedEvidence); + if (json == null || !json.isObject() || json.size() != CREATION_EVIDENCE_FIELDS.size()) { + throw new IllegalArgumentException( + "Complete creation evidence must be one closed JSON object"); + } + HashSet fields = new HashSet<>(); + json.fieldNames().forEachRemaining(fields::add); + if (!fields.equals(CREATION_EVIDENCE_FIELDS)) { + throw new IllegalArgumentException( + "Complete creation evidence has unknown or missing fields"); + } + return new FreshTenantCreationEvidence( + requiredInt(json, "schemaVersion"), + requiredText(json, "targetNamespace"), + parseUuid(requiredText(json, "creationRequestId")), + parseUuid(requiredText(json, "operationId")), + requiredText(json, "requestDigest"), + parseUuid(requiredText(json, "canonicalTenantId")), + requiredLong(json, "sourceGameRowId"), + requiredText(json, "sourceGameTenantKey"), + requiredText(json, "provenanceKind"), + requiredText(json, "evidenceDigest")); + } catch (IOException | IllegalArgumentException invalid) { + throw new InvalidCanonicalRealmCatalogException( + "Stored complete Game Design creation evidence is invalid", invalid); + } + } + + private static String requiredText(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Complete creation evidence field must be text: " + field); + } + return value.textValue(); + } + + private static int requiredInt(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException( + "Complete creation evidence field must be an integer: " + field); + } + return value.intValue(); + } + + private static long requiredLong(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw new IllegalArgumentException( + "Complete creation evidence field must be an integer: " + field); + } + return value.longValue(); + } + + private static UUID parseUuid(String value) { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException( + "Complete creation evidence UUID must be canonical and nonnil"); + } + return parsed; + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) { + throw new InvalidCanonicalRealmCatalogException( + "Stored canonical realm catalog is missing required evidence: " + field); + } + return value; + } + + private static void requireOne(int affectedRows, String label) { + if (affectedRows != 1) { + throw new InvalidCanonicalRealmCatalogException( + "Game Session " + label + " insert did not affect exactly one row"); + } + } + + private static void requireNonNil(UUID id, String label) { + if (id == null || NIL_UUID.equals(id)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + } + + private static void requireNoActiveOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authenticated Game Design reads must complete before opening a Game Session owner transaction"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Session canonical realm storage access requires an active owner transaction"); + } + } + + private record PreparedInput( + FreshTenantAssociation association, + AuthoredWorldSourceEvidence source, + RealmPolicyPublishedEvidence.PublishedSet publishedSet, + SelectedPolicy selectedPolicy, + UUID intakeRequestId, + UUID catalogRequestId, + byte[] publishedSetBytes, + Set foreignIds) { + private PreparedInput { + publishedSetBytes = publishedSetBytes.clone(); + foreignIds = Set.copyOf(foreignIds); + } + + @Override + public byte[] publishedSetBytes() { + return publishedSetBytes.clone(); + } + } + + private record SelectedPolicy(UUID policyId, String policyDigest, RealmEntryPolicy policy) {} + + /** Complete GS-owned source intake and catalog receipt, including the exact stored policy set. */ + public record CanonicalRealmCatalog( + String targetNamespace, + UUID canonicalTenantId, + long gameSessionTenantId, + UUID tenantAssociationOperationId, + FreshTenantCreationEvidence associationSourceEvidence, + AuthoredWorldSourceEvidence sourceEvidence, + UUID intakeRequestId, + UUID intakeOperationId, + String intakeRequestDigest, + String intakeReceiptDigest, + UUID catalogRequestId, + String catalogRequestDigest, + String catalogReceiptDigest, + UUID realmId, + UUID playableStateNamespaceId, + String tenantSlug, + String worldSlug, + String realmSlug, + String realmDisplayName, + String sourceWorldDisplayName, + String entryPolicy, + long catalogRevision, + byte[] completePolicySetEvidence, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + public CanonicalRealmCatalog { + Objects.requireNonNull(targetNamespace); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(tenantAssociationOperationId, "tenantAssociationOperationId"); + Objects.requireNonNull(associationSourceEvidence); + Objects.requireNonNull(sourceEvidence); + requireNonNil(intakeRequestId, "intakeRequestId"); + requireNonNil(intakeOperationId, "intakeOperationId"); + Objects.requireNonNull(intakeRequestDigest); + Objects.requireNonNull(intakeReceiptDigest); + requireNonNil(catalogRequestId, "catalogRequestId"); + Objects.requireNonNull(catalogRequestDigest); + Objects.requireNonNull(catalogReceiptDigest); + requireNonNil(realmId, "realmId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(tenantSlug); + Objects.requireNonNull(worldSlug); + Objects.requireNonNull(realmSlug); + Objects.requireNonNull(realmDisplayName); + Objects.requireNonNull(sourceWorldDisplayName); + Objects.requireNonNull(entryPolicy); + if (gameSessionTenantId <= 0 || catalogRevision <= 0) { + throw new IllegalArgumentException( + "Positive GS tenant allocation and catalog revision required"); + } + completePolicySetEvidence = + Objects.requireNonNull(completePolicySetEvidence, "completePolicySetEvidence").clone(); + if (completePolicySetEvidence.length == 0) { + throw new IllegalArgumentException("Complete published policy evidence required"); + } + Objects.requireNonNull(publishedSet, "publishedSet"); + } + + @Override + public byte[] completePolicySetEvidence() { + return completePolicySetEvidence.clone(); + } + } + + public static final class InvalidCanonicalRealmCatalogException extends IllegalStateException { + public InvalidCanonicalRealmCatalogException(String message) { + super(message); + } + + public InvalidCanonicalRealmCatalogException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V42__canonical_catalog_complete_policy_evidence.sql b/services/game-session-service/src/main/resources/db/migration/V42__canonical_catalog_complete_policy_evidence.sql new file mode 100644 index 0000000000..23e4dd0fa4 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V42__canonical_catalog_complete_policy_evidence.sql @@ -0,0 +1,30 @@ +-- Preserve the complete immutable Game Design publication policy set that authorized a fresh +-- public-production realm. Historical V23 catalog rows remain readable as historical catalog +-- state but are deliberately not reconstructed or adopted as complete published evidence. +ALTER TABLE game_session_canonical_realm_catalog + ADD COLUMN complete_policy_set_evidence BYTEA; + +ALTER TABLE game_session_canonical_realm_catalog + ADD CONSTRAINT chk_gs_canonical_realm_catalog_complete_policy_evidence + CHECK (complete_policy_set_evidence IS NULL OR octet_length(complete_policy_set_evidence) > 0); + +-- [jooq ignore start] +CREATE FUNCTION require_game_session_canonical_realm_complete_policy_evidence() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.complete_policy_set_evidence IS NULL + OR octet_length(NEW.complete_policy_set_evidence) = 0 THEN + RAISE EXCEPTION 'New canonical realm catalog row requires complete published policy evidence' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_canonical_realm_catalog_complete_policy_evidence'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_realm_requires_complete_policy_evidence + BEFORE INSERT ON game_session_canonical_realm_catalog + FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_realm_complete_policy_evidence(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index d787c2337a..3394daab4d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -10,7 +10,11 @@ import org.jooq.DSLContext; import org.jooq.impl.DSL; -/** Shared PostgreSQL fixtures for lease-bound binding tests that require a real launch target. */ +/** + * Shared PostgreSQL storage fixtures for lease-bound binding tests that require a real launch + * target. Upstream Game Design source, authorization, and publication authority are synthetic test + * stipulations; these seeded rows do not prove authenticated Game Design owner transport. + */ public final class CanonicalGameplayBindingRuntimeTestFixtures { private static final String SHA256 = "sha256:" + "a".repeat(64); private static final String RAW_SHA256 = "a".repeat(64); @@ -81,15 +85,20 @@ public static RuntimeTarget seedRunningLaunch( } private static void seedSourceAndCatalog(DSLContext tx, RuntimeTarget target) { + GameSessionCanonicalRealmCatalogProofFixtures.Proof proof = + GameSessionCanonicalRealmCatalogProofFixtures.forRuntimeTarget(target); + var source = proof.source(); + var publishedPolicy = proof.publishedSet().policies().getFirst().source().policy(); + tx.execute( "INSERT INTO game_session_authored_world_tenant_source_binding" + " (target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id," + " source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, 'NEW_GAME_ROW')", target.targetNamespace(), - target.canonicalTenantId(), - target.tenantSlug(), - target.sourceGameRowId(), - target.sourceGameTenantKey()); + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey()); tx.execute( "INSERT INTO game_session_authored_world_source_intake" @@ -103,16 +112,16 @@ private static void seedSourceAndCatalog(DSLContext tx, RuntimeTarget target) { target.targetNamespace(), target.sourceIntakeRequestId(), SHA256, - target.sourceRegistrationRequestId(), - target.sourceOperationId(), - SHA256, - target.canonicalTenantId(), - target.tenantSlug(), - target.worldSlug(), - target.worldDisplayName(), - target.sourceGameRowId(), - target.sourceGameTenantKey(), - SHA256, + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.evidenceDigest(), SHA256); tx.execute( @@ -131,12 +140,12 @@ private static void seedSourceAndCatalog(DSLContext tx, RuntimeTarget target) { target.sourceIntakeRequestId(), SHA256, SHA256, - target.sourceRegistrationRequestId(), - target.sourceOperationId(), - SHA256, - target.sourceGameRowId(), - target.sourceGameTenantKey(), - SHA256); + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.evidenceDigest()); tx.execute( "INSERT INTO game_session_canonical_realm_catalog" @@ -147,16 +156,18 @@ private static void seedSourceAndCatalog(DSLContext tx, RuntimeTarget target) { + " source_intake_schema_version, source_intake_request_id, source_intake_request_digest," + " source_intake_receipt_digest, source_schema_version, source_registration_request_id," + " source_operation_id, source_request_digest, source_world_display_name," - + " source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, 'PLAYER_CHOICE', 1, ?, ?, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?)", + + " source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest," + + " complete_policy_set_evidence)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, ?, 1, ?, ?, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)", target.targetNamespace(), target.canonicalTenantId(), target.tenantSlug(), target.worldSlug(), target.realmId(), - target.realmSlug(), - target.realmDisplayName(), + publishedPolicy.realmSlug(), + publishedPolicy.realmDisplayName(), target.playableStateNamespaceId(), + publishedPolicy.entryPolicy().name(), target.catalogCreationRequestId(), SHA256, SHA256, @@ -164,13 +175,15 @@ private static void seedSourceAndCatalog(DSLContext tx, RuntimeTarget target) { target.sourceIntakeRequestId(), SHA256, SHA256, - target.sourceRegistrationRequestId(), - target.sourceOperationId(), - SHA256, - target.worldDisplayName(), - target.sourceGameRowId(), - target.sourceGameTenantKey(), - SHA256); + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + proof.completePolicySetBytes()); } private static void seedFreshTenantAssociation(DSLContext tx, RuntimeTarget target) { @@ -437,7 +450,7 @@ private static RuntimeTarget create( 1L, SHA256, terminalAt, - "PLAYER_CHOICE", + "PRESEEDED_ONLY", gameInstanceId + 50_000L, "source-" + shortToken, UUID.randomUUID(), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogPostgresIntegrationTest.java new file mode 100644 index 0000000000..8c53ff2816 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogPostgresIntegrationTest.java @@ -0,0 +1,512 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.Statement; +import java.util.Objects; +import java.util.UUID; +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.gamesession.client.GameDesignFreshTenantCreationClient; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociation; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL owner-storage proof only. Game Design owner responses and the complete synthetic + * source/publication carriers are stipulated fixtures; this suite does not prove GD transport + * authentication or producer-side persisted selection. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalRealmCatalogPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String NAMESPACE = "test"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void commitsCompleteSourceAndPolicyEvidenceAndExactRetryReturnsActualStoredRevision() + throws Exception { + try (Fixture fixture = newFixture(null)) { + FreshTenantAssociation association = createFreshAssociation(fixture); + GameSessionCanonicalRealmCatalogProofFixtures.Proof proof = + GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(association); + UUID intakeRequestId = UUID.randomUUID(); + UUID catalogRequestId = UUID.randomUUID(); + var repository = fixture.catalogRepository(); + + var created = + repository.establishFreshPublicRealm( + association, proof.source(), proof.publishedSet(), intakeRequestId, catalogRequestId); + var independent = + repository.readByCanonicalTenantId(association.canonicalTenantId()).orElseThrow(); + var retry = + repository.establishFreshPublicRealm( + association, proof.source(), proof.publishedSet(), intakeRequestId, catalogRequestId); + + assertThat(created.canonicalTenantId()).isEqualTo(association.canonicalTenantId()); + assertThat(created.gameSessionTenantId()).isEqualTo(association.gameSessionTenantId()); + assertThat(created.tenantAssociationOperationId()) + .isEqualTo(association.associationOperationId()); + assertThat(created.sourceEvidence()).isEqualTo(proof.source()); + assertThat(created.associationSourceEvidence()).isEqualTo(association.sourceEvidence()); + assertThat(created.entryPolicy()).isEqualTo("PRESEEDED_ONLY"); + assertThat(created.realmSlug()).isEqualTo("main"); + assertThat(created.catalogRevision()).isPositive(); + assertThat(created.completePolicySetEvidence()) + .containsExactly(proof.completePolicySetBytes()); + assertThat(independent.realmId()).isEqualTo(created.realmId()); + assertThat(independent.catalogRevision()).isEqualTo(created.catalogRevision()); + assertThat(independent.completePolicySetEvidence()) + .containsExactly(created.completePolicySetEvidence()); + assertThat(retry.realmId()).isEqualTo(created.realmId()); + assertThat(retry.playableStateNamespaceId()).isEqualTo(created.playableStateNamespaceId()); + assertThat(retry.catalogRevision()).isEqualTo(created.catalogRevision()); + assertThat(count(fixture.dsl(), "game_session_authored_world_tenant_source_binding")) + .isEqualTo(1L); + assertThat(count(fixture.dsl(), "game_session_authored_world_source_intake")).isEqualTo(1L); + assertThat(count(fixture.dsl(), "gameplay_tenant_shared_playable_state_namespace")) + .isEqualTo(1L); + assertThat(count(fixture.dsl(), "game_session_canonical_realm_catalog")).isEqualTo(1L); + + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "INSERT INTO game_session_canonical_realm_catalog" + + " (target_namespace, canonical_tenant_id, tenant_slug, world_slug, realm_id," + + " realm_slug, realm_display_name, visible, public_production, state_scope," + + " playable_state_namespace_id, character_creation_policy, catalog_revision," + + " creation_request_id, request_digest, receipt_digest, source_intake_operation_id," + + " source_intake_schema_version, source_intake_request_id, source_intake_request_digest," + + " source_intake_receipt_digest, source_schema_version, source_registration_request_id," + + " source_operation_id, source_request_digest, source_world_display_name," + + " source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest)" + + " SELECT target_namespace, canonical_tenant_id, tenant_slug, world_slug, realm_id," + + " realm_slug, realm_display_name, visible, public_production, state_scope," + + " playable_state_namespace_id, character_creation_policy, catalog_revision," + + " creation_request_id, request_digest, receipt_digest, source_intake_operation_id," + + " source_intake_schema_version, source_intake_request_id, source_intake_request_digest," + + " source_intake_receipt_digest, source_schema_version, source_registration_request_id," + + " source_operation_id, source_request_digest, source_world_display_name," + + " source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest" + + " FROM game_session_canonical_realm_catalog" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + association.canonicalTenantId())) + .hasMessageContaining("requires complete published policy evidence"); + } + } + + @Test + void rejectsChangedSourceOnStableRequestAndDoesNotCreateAnotherCatalog() throws Exception { + try (Fixture fixture = newFixture(null)) { + FreshTenantAssociation association = createFreshAssociation(fixture); + var firstProof = + GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(association); + var changedProof = + GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(association); + UUID intakeRequestId = UUID.randomUUID(); + UUID catalogRequestId = UUID.randomUUID(); + var repository = fixture.catalogRepository(); + var original = + repository.establishFreshPublicRealm( + association, + firstProof.source(), + firstProof.publishedSet(), + intakeRequestId, + catalogRequestId); + + assertThatThrownBy( + () -> + repository.establishFreshPublicRealm( + association, + changedProof.source(), + changedProof.publishedSet(), + intakeRequestId, + catalogRequestId)) + .isInstanceOf( + GameSessionCanonicalRealmCatalogRepository.InvalidCanonicalRealmCatalogException + .class) + .hasMessageContaining("retry differs from the complete original source"); + assertThat( + repository + .readByCanonicalTenantId(association.canonicalTenantId()) + .orElseThrow() + .realmId()) + .isEqualTo(original.realmId()); + assertThat(count(fixture.dsl(), "game_session_authored_world_source_intake")).isEqualTo(1L); + assertThat(count(fixture.dsl(), "game_session_canonical_realm_catalog")).isEqualTo(1L); + } + } + + @Test + void rejectsIsolatedPolicyBeforeOpeningTheOwnerTransaction() throws Exception { + try (Fixture fixture = newFixture(null)) { + FreshTenantAssociation association = createFreshAssociation(fixture); + var shared = GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(association); + var isolated = + GameSessionCanonicalRealmCatalogProofFixtures.isolatedForSource(shared.source()); + var repository = fixture.catalogRepository(); + + assertThatThrownBy( + () -> + repository.establishFreshPublicRealm( + association, + isolated.source(), + isolated.publishedSet(), + UUID.randomUUID(), + UUID.randomUUID())) + .isInstanceOf( + GameSessionCanonicalRealmCatalogRepository.InvalidCanonicalRealmCatalogException + .class) + .hasMessageContaining("use SHARED state scope"); + assertThat(count(fixture.dsl(), "game_session_authored_world_tenant_source_binding")) + .isZero(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + } + + @Test + void rejectsPublicationOperationFromAnotherNamespaceBeforeOpeningTheOwnerTransaction() + throws Exception { + try (Fixture fixture = newFixture(null)) { + String otherNamespace = "other"; + UUID canonicalTenantId = UUID.randomUUID(); + FreshTenantCreationEvidence creation = + freshCreationEvidence(otherNamespace, UUID.randomUUID(), canonicalTenantId); + FreshTenantAssociation association = + new FreshTenantAssociation( + otherNamespace, canonicalTenantId, 73L, UUID.randomUUID(), creation); + var proof = GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(association); + var repository = + new GameSessionCanonicalRealmCatalogRepository( + fixture.dsl(), fixture.transactionManager(), otherNamespace); + + assertThatThrownBy( + () -> + repository.establishFreshPublicRealm( + association, + proof.source(), + proof.publishedSet(), + UUID.randomUUID(), + UUID.randomUUID())) + .isInstanceOf( + GameSessionCanonicalRealmCatalogRepository.InvalidCanonicalRealmCatalogException + .class) + .hasMessageContaining("operation namespace"); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(count(fixture.dsl(), "game_session_authored_world_tenant_source_binding")) + .isZero(); + } + } + + @Test + void rollsBackBindingIntakeNamespaceAndCatalogTogetherWhenCatalogInsertFails() throws Exception { + try (Fixture fixture = newFixture(null)) { + FreshTenantAssociation association = createFreshAssociation(fixture); + var proof = GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(association); + fixture + .dsl() + .execute( + "ALTER TABLE game_session_canonical_realm_catalog" + + " ADD CONSTRAINT chk_test_reject_canonical_catalog CHECK (FALSE)"); + + assertThatThrownBy( + () -> + fixture + .catalogRepository() + .establishFreshPublicRealm( + association, + proof.source(), + proof.publishedSet(), + UUID.randomUUID(), + UUID.randomUUID())) + .isInstanceOf(RuntimeException.class); + assertThat(count(fixture.dsl(), "game_session_authored_world_tenant_source_binding")) + .isZero(); + assertThat(count(fixture.dsl(), "game_session_authored_world_source_intake")).isZero(); + assertThat(count(fixture.dsl(), "gameplay_tenant_shared_playable_state_namespace")).isZero(); + assertThat(count(fixture.dsl(), "game_session_canonical_realm_catalog")).isZero(); + assertThat(count(fixture.dsl(), "game_session_fresh_tenant_association")).isEqualTo(1L); + } + } + + @Test + void deniesHistoricalV23CatalogWithoutReconstructingMissingPublishedSetEvidence() + throws Exception { + try (Fixture fixture = newFixture(MigrationVersion.fromVersion("41"))) { + FreshTenantAssociation association = createFreshAssociation(fixture); + var proof = GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(association); + seedHistoricalV23CatalogWithoutPolicyEvidence(fixture.dsl(), proof); + fixture.migrateLatest(); + + assertThatThrownBy( + () -> + fixture + .catalogRepository() + .readByCanonicalTenantId(association.canonicalTenantId())) + .isInstanceOf( + GameSessionCanonicalRealmCatalogRepository.InvalidCanonicalRealmCatalogException + .class) + .hasMessageContaining("complete_policy_set_evidence"); + assertThat(count(fixture.dsl(), "game_session_canonical_realm_catalog")).isEqualTo(1L); + Record retainedCatalog = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT complete_policy_set_evidence IS NULL AS missing FROM" + + " game_session_canonical_realm_catalog" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + association.canonicalTenantId()), + "Historical catalog must survive migration"); + assertThat(retainedCatalog.get("missing", Boolean.class)).isTrue(); + } + } + + private static FreshTenantAssociation createFreshAssociation(Fixture fixture) { + UUID requestId = UUID.randomUUID(); + FreshTenantCreationEvidence evidence = freshCreationEvidence(requestId, UUID.randomUUID()); + GameDesignFreshTenantCreationClient client = mock(GameDesignFreshTenantCreationClient.class); + when(client.resolveCreation(requestId, evidence.requestDigest())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return evidence; + }); + return fixture + .associationRepository(client) + .associateFreshTenant(requestId, evidence.requestDigest()); + } + + private static FreshTenantCreationEvidence freshCreationEvidence( + UUID creationRequestId, UUID canonicalTenantId) { + return freshCreationEvidence(NAMESPACE, creationRequestId, canonicalTenantId); + } + + private static FreshTenantCreationEvidence freshCreationEvidence( + String namespace, UUID creationRequestId, UUID canonicalTenantId) { + String sourceKey = "owner-key-" + creationRequestId.toString().substring(0, 8); + long sourceRowId = Math.abs(creationRequestId.getMostSignificantBits() % 1_000_000L) + 1L; + UUID sourceOperationId = UUID.randomUUID(); + String requestDigest = + GameTenantCreationDigest.requestDigest( + namespace, creationRequestId, sourceKey, "Fixture game", null); + return new FreshTenantCreationEvidence( + 1, + namespace, + creationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + namespace, + creationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW")); + } + + private static void seedHistoricalV23CatalogWithoutPolicyEvidence( + DSLContext dsl, GameSessionCanonicalRealmCatalogProofFixtures.Proof proof) { + AuthoredWorldSourceEvidence source = proof.source(); + UUID intakeOperationId = UUID.randomUUID(); + UUID intakeRequestId = UUID.randomUUID(); + UUID realmId = UUID.randomUUID(); + UUID sharedNamespaceId = UUID.randomUUID(); + UUID catalogRequestId = UUID.randomUUID(); + String digest = "sha256:" + "a".repeat(64); + var selected = proof.publishedSet().policies().getFirst().source().policy(); + dsl.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute( + "INSERT INTO game_session_authored_world_tenant_source_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()); + tx.execute( + "INSERT INTO game_session_authored_world_source_intake" + + " (operation_id, schema_version, target_namespace, intake_request_id, request_digest," + + " source_schema_version, source_registration_request_id, source_operation_id," + + " source_request_digest, canonical_tenant_id, tenant_slug, world_slug, world_display_name," + + " source_game_row_id, source_game_tenant_key, source_provenance_kind," + + " source_evidence_digest, receipt_digest)" + + " VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + intakeOperationId, + source.targetNamespace(), + intakeRequestId, + digest, + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + digest); + tx.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace" + + " (tenant_id, playable_state_namespace_id, canonical_tenant_id, target_namespace," + + " source_intake_operation_id, source_intake_schema_version, source_intake_request_id," + + " source_intake_request_digest, source_intake_receipt_digest, source_schema_version," + + " source_registration_request_id, source_operation_id, source_request_digest," + + " source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest)" + + " VALUES (NULL, ?, ?, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?)", + sharedNamespaceId, + source.canonicalTenantId(), + source.targetNamespace(), + intakeOperationId, + intakeRequestId, + digest, + digest, + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + tx.execute( + "INSERT INTO game_session_canonical_realm_catalog" + + " (target_namespace, canonical_tenant_id, tenant_slug, world_slug, realm_id," + + " realm_slug, realm_display_name, visible, public_production, state_scope," + + " playable_state_namespace_id, character_creation_policy, catalog_revision," + + " creation_request_id, request_digest, receipt_digest, source_intake_operation_id," + + " source_intake_schema_version, source_intake_request_id, source_intake_request_digest," + + " source_intake_receipt_digest, source_schema_version, source_registration_request_id," + + " source_operation_id, source_request_digest, source_world_display_name," + + " source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, ?, 1, ?, ?, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + realmId, + selected.realmSlug(), + selected.realmDisplayName(), + sharedNamespaceId, + selected.entryPolicy().name(), + catalogRequestId, + digest, + digest, + intakeOperationId, + intakeRequestId, + digest, + digest, + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + }); + } + + private static long count(DSLContext dsl, String tableName) { + Record row = + Objects.requireNonNull(dsl.fetchOne("SELECT COUNT(*) AS row_count FROM " + tableName)); + return Objects.requireNonNull(row.get("row_count", Long.class)); + } + + private static Fixture newFixture(MigrationVersion migrationVersion) { + String schema = "gs_canonical_realm_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(migrationVersion == null ? MigrationVersion.LATEST : migrationVersion) + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture(schema, dataSource, dsl, new DataSourceTransactionManager(dataSource)); + } + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager transactionManager) + implements AutoCloseable { + GameSessionFreshTenantAssociationRepository associationRepository( + GameDesignFreshTenantCreationClient client) { + return new GameSessionFreshTenantAssociationRepository( + dsl, transactionManager, client, NAMESPACE); + } + + GameSessionCanonicalRealmCatalogRepository catalogRepository() { + return new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE); + } + + void migrateLatest() { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + @Override + public void close() throws Exception { + try (Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogProofFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogProofFixtures.java new file mode 100644 index 0000000000..000fb39cc9 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogProofFixtures.java @@ -0,0 +1,284 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation; +import net.firedevops.firemud.gamedesign.publication.IsolatedPublicationOperationFixtures; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociation; +import tools.jackson.databind.json.JsonMapper; + +/** + * Test-only storage evidence. Authenticated Game Design reads, registration completion, and the + * actual owner publications are synthetic stipulations, so these fixtures prove neither GD + * transport authentication nor a producer's real persisted row selection. + */ +final class GameSessionCanonicalRealmCatalogProofFixtures { + private static final String POLICY_DIGEST = "sha256:" + "a".repeat(64); + private static final String MANIFEST_HASH = "sha256:" + "b".repeat(64); + private static final String NON_WORLD_CONTENT_DIGEST = "c".repeat(64); + private static final String GAME_LOGIC_ABILITY_DIGEST = "sha256:" + "d".repeat(64); + private static final tools.jackson.databind.ObjectMapper JSON = JsonMapper.builder().build(); + + private GameSessionCanonicalRealmCatalogProofFixtures() {} + + static Proof forRuntimeTarget(RuntimeTarget target) { + AuthoredWorldSourceEvidence source = + source( + target.targetNamespace(), + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.worldDisplayName(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceRegistrationRequestId(), + target.sourceOperationId()); + return publishedSet(source); + } + + static Proof forFreshAssociation(FreshTenantAssociation association) { + String suffix = association.canonicalTenantId().toString().substring(0, 8); + AuthoredWorldSourceEvidence source = + source( + association.targetNamespace(), + association.canonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Fixture World " + suffix, + association.sourceEvidence().sourceGameRowId(), + association.sourceEvidence().sourceGameTenantKey(), + UUID.randomUUID(), + UUID.randomUUID()); + return publishedSet(source, RealmEntryPolicy.StateScope.SHARED); + } + + static Proof isolatedForSource(AuthoredWorldSourceEvidence source) { + return publishedSet(source, RealmEntryPolicy.StateScope.ISOLATED); + } + + private static AuthoredWorldSourceEvidence source( + String namespace, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + long sourceGameRowId, + String sourceGameTenantKey, + UUID registrationRequestId, + UUID operationId) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + namespace, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + return new AuthoredWorldSourceEvidence( + 1, + namespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + namespace, + registrationRequestId, + operationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW")); + } + + private static Proof publishedSet(AuthoredWorldSourceEvidence source) { + return publishedSet(source, RealmEntryPolicy.StateScope.SHARED); + } + + private static Proof publishedSet( + AuthoredWorldSourceEvidence source, RealmEntryPolicy.StateScope stateScope) { + TargetProof target = + new TargetProof( + source.canonicalTenantId(), + UUID.randomUUID(), + Math.addExact(source.sourceGameRowId(), 1L), + source.sourceGameTenantKey(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + GameDesignPublicationOperation operation; + try { + operation = IsolatedPublicationOperationFixtures.fresh(target); + } catch (Exception invalidFixture) { + throw new IllegalStateException( + "Synthetic publication operation fixture is invalid", invalidFixture); + } + + var selectedCommit = operation.account().input().selection().selectedCommit(); + String policyJson = + RealmPolicySource.canonical( + Map.of( + "schemaVersion", + 1, + "worldSlug", + source.worldSlug(), + "worldDisplayName", + source.worldDisplayName(), + "realmSlug", + "main", + "realmDisplayName", + "Main Realm", + "visible", + true, + "publicProduction", + true, + "stateScope", + stateScope.name(), + "entryPolicy", + "PRESEEDED_ONLY")); + RealmEntryPolicy entryPolicy = RealmEntryPolicy.parse(policyJson, JSON); + RealmPolicySource.Policy policySource = + new RealmPolicySource.Policy( + selectedCommit.commitId(), UUID.randomUUID(), "synthetic-main-policy", entryPolicy); + RealmPolicySnapshot capture = + new RealmPolicySnapshot(selectedCommit, "1", List.of(policySource)); + + String bundleRef = "fixture-publication/" + source.canonicalTenantId(); + var worldRequest = operation.world().request(); + long publicationEpoch = Math.addExact(worldRequest.versionStateEpoch(), 1L); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(target.gameDesignVersionRowId()), + null, + worldRequest.appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) + ? worldRequest.contentDigest() + : NON_WORLD_CONTENT_DIGEST, + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner) ? GAME_LOGIC_ABILITY_DIGEST : null, + null, + null)) + .toList(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + source.canonicalTenantId(), + target.canonicalVersionId(), + bundleRef, + 1, + "v2", + worldRequest.publishWorkflowId(), + MANIFEST_HASH, + 1, + List.of(), + List.of(), + participants, + List.of(), + "generation-fixture", + operation.world()); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED, + release, + publicationEpoch); + + UUID policyId = UUID.randomUUID(); + String policyDigest = + RealmPolicyPublishedEvidence.policyDigest( + policyId, + target, + release.versionNumber(), + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + policySource); + RealmPolicyPublishedEvidence.Policy publishedPolicy = + new RealmPolicyPublishedEvidence.Policy(policyId, policySource, policyDigest); + byte[] operationBytes = operation.canonicalBytes(); + var captureFrame = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + captureFrame, "game-design-realm-policy-source-capture/v1"); + DraftAuthorizationFenceBinding.frame(captureFrame, operationBytes); + DraftAuthorizationFenceBinding.frame(captureFrame, capture.canonicalBytes()); + byte[] captureBytes = captureFrame.toByteArray(); + byte[] terminalBytes = terminal.canonicalBytes(); + List policies = List.of(publishedPolicy); + String setDigest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + release.versionNumber(), + policySource.commitId(), + "1", + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + publicationEpoch, + operationBytes, + captureBytes, + terminalBytes, + policies); + var publishedSet = + new RealmPolicyPublishedEvidence.PublishedSet( + target, + release.versionNumber(), + policySource.commitId(), + "1", + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + publicationEpoch, + operationBytes, + captureBytes, + terminalBytes, + policies.size(), + setDigest, + policies); + return new Proof(source, publishedSet); + } + + record Proof( + AuthoredWorldSourceEvidence source, RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + Proof { + if (source == null || publishedSet == null) { + throw new IllegalArgumentException( + "Complete synthetic source and policy evidence required"); + } + } + + byte[] completePolicySetBytes() { + return RealmPolicyPublishedEvidenceCodec.encode(publishedSet); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogProofFixturesTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogProofFixturesTest.java new file mode 100644 index 0000000000..79452e77d7 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogProofFixturesTest.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociation; +import org.junit.jupiter.api.Test; + +/** Verifies synthetic storage fixtures without Docker; it does not authenticate their producer. */ +class GameSessionCanonicalRealmCatalogProofFixturesTest { + @Test + void syntheticCatalogSetupRetainsTheCompleteCanonicalCaptureAndTerminal() { + UUID requestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + String requestDigest = "sha256:" + "a".repeat(64); + String sourceKey = "synthetic-source-key"; + var creation = + new FreshTenantCreationEvidence( + 1, + "test", + requestId, + sourceOperationId, + requestDigest, + tenantId, + 91L, + sourceKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "test", + requestId, + sourceOperationId, + requestDigest, + tenantId, + 91L, + sourceKey, + "NEW_GAME_ROW")); + var association = new FreshTenantAssociation("test", tenantId, 7L, UUID.randomUUID(), creation); + var fixture = GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(association); + + var decoded = RealmPolicyPublishedEvidenceCodec.decode(fixture.completePolicySetBytes()); + + assertThat(decoded.target().canonicalTenantId()).isEqualTo(tenantId); + assertThat(decoded.operationBytes()).containsExactly(fixture.publishedSet().operationBytes()); + assertThat(decoded.captureBytes()).containsExactly(fixture.publishedSet().captureBytes()); + assertThat(decoded.terminalEvidenceBytes()) + .containsExactly(fixture.publishedSet().terminalEvidenceBytes()); + assertThat(RealmPolicyPublishedEvidenceCodec.encode(decoded)) + .containsExactly(fixture.completePolicySetBytes()); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationPostgresIntegrationTest.java index 6087744078..d94ade6cc9 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationPostgresIntegrationTest.java @@ -40,8 +40,8 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Game Design responses are explicit mocks here; authentication is covered by the client unit - * tests. + * Game Design responses are explicit mocks here. Client unit tests prove configured peer pinning + * and unauthenticated-response rejection, not a genuine authenticated Game Design-to-SQL flow. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java new file mode 100644 index 0000000000..7eae7711e0 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java @@ -0,0 +1,272 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +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 io.grpc.stub.AbstractStub; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.StartSessionPublishedRealmPolicyReadGrpcCodec; +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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.gamedesign.v1.GameDesignStartSessionPublishedRealmPolicyReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionPublishedRealmPolicyRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionPublishedRealmPolicyResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Transport configuration and fail-closed client tests; no mocked reply is owner producer proof. + */ +class GameDesignPublishedRealmPolicyClientTest { + @AfterEach + void clearAmbientTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresReadableFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + for (String badPath : + java.util.List.of( + "", + "classpath:client.crt", + directory.resolve("absent.crt").toString(), + directory.toString())) { + var invalid = tls(directory); + invalid.setCertChain(badPath); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), invalid, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + var noKey = tls(directory); + noKey.setPrivateKey(null); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), noKey, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + var noCa = tls(directory); + noCa.setCaCert(null); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), noCa, factory, "test")) + .isInstanceOf(IllegalArgumentException.class); + var valid = tls(directory); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), valid, factory, "Test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void closedClientCannotInitializeOrRead(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + var client = newClient(directory, factory); + client.close(); + + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + + var request = mock(StartSessionPublishedRealmPolicyReadGrpcCodec.ReadRequest.class); + when(request.targetNamespace()).thenReturn("test"); + try (MockedStatic codec = + Mockito.mockStatic(StartSessionPublishedRealmPolicyReadGrpcCodec.class)) { + codec + .when(() -> StartSessionPublishedRealmPolicyReadGrpcCodec.toRequest(request)) + .thenReturn(ReadStartSessionPublishedRealmPolicyRequest.getDefaultInstance()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + } + verifyNoInteractions(factory); + } + + @Test + void rejectsAmbientTransactionOrSynchronizationBeforeCodecAndTransport(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var client = newClient(directory, factory); + var stub = mockStub(); + setStub(client, stub); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try (MockedStatic codec = + Mockito.mockStatic(StartSessionPublishedRealmPolicyReadGrpcCodec.class)) { + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction synchronization"); + codec.verifyNoInteractions(); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try (MockedStatic codec = + Mockito.mockStatic(StartSessionPublishedRealmPolicyReadGrpcCodec.class)) { + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction synchronization"); + codec.verifyNoInteractions(); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(stub); + client.close(); + } + + @Test + void pinsExactGameDesignPeerAndAppliesLocalBoundsAndDeadline(@TempDir Path directory) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("design.internal:6565"); + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(factory.buildChannel( + eq("design.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new GameDesignPublishedRealmPolicyClient(endpoints, tls(directory), factory, "test"); + try { + client.init(); + AbstractStub initialized = initializedStub(client); + assertThat(initialized.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + assertThat(readField(initialized.getCallOptions().getCredentials(), "expectedPeerUri")) + .isEqualTo("spiffe://firemud/ns/test/sa/game-design-service"); + + var stub = mockStub(); + setStub(client, stub); + var request = mock(StartSessionPublishedRealmPolicyReadGrpcCodec.ReadRequest.class); + when(request.targetNamespace()).thenReturn("test"); + when(stub.readStartSessionPublishedRealmPolicy(any())) + .thenReturn(ReadStartSessionPublishedRealmPolicyResponse.getDefaultInstance()); + + try (MockedStatic codec = + Mockito.mockStatic(StartSessionPublishedRealmPolicyReadGrpcCodec.class)) { + codec + .when(() -> StartSessionPublishedRealmPolicyReadGrpcCodec.toRequest(request)) + .thenReturn(ReadStartSessionPublishedRealmPolicyRequest.getDefaultInstance()); + codec + .when( + () -> + StartSessionPublishedRealmPolicyReadGrpcCodec.fromResponse( + isNull(), any(ReadStartSessionPublishedRealmPolicyResponse.class))) + .thenThrow(new IllegalArgumentException("transport-only test response")); + + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid or mismatched published-policy evidence"); + + verify(stub) + .withMaxInboundMessageSize( + StartSessionPublishedRealmPolicyReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).readStartSessionPublishedRealmPolicy(any()); + codec.verify(() -> StartSessionPublishedRealmPolicyReadGrpcCodec.toRequest(request)); + codec.verify( + () -> + StartSessionPublishedRealmPolicyReadGrpcCodec.requireRequestSerializedSize( + any(ReadStartSessionPublishedRealmPolicyRequest.class))); + codec.verify( + () -> + StartSessionPublishedRealmPolicyReadGrpcCodec.requireResponseSerializedSize( + any(ReadStartSessionPublishedRealmPolicyResponse.class))); + codec.verify( + () -> + StartSessionPublishedRealmPolicyReadGrpcCodec.fromResponse( + isNull(), any(ReadStartSessionPublishedRealmPolicyResponse.class))); + } + } finally { + client.close(); + } + verify(channel).shutdown(); + } + + private static GameDesignPublishedRealmPolicyClient newClient( + Path directory, GrpcChannelFactory factory) throws Exception { + return new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), tls(directory), factory, "test"); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain( + Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + properties.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "private key").toString()); + properties.setCaCert( + Files.writeString(directory.resolve("ca.crt"), "CA certificate").toString()); + return properties; + } + + private static GameDesignStartSessionPublishedRealmPolicyReadServiceGrpc + .GameDesignStartSessionPublishedRealmPolicyReadServiceBlockingStub + mockStub() { + var stub = + mock( + GameDesignStartSessionPublishedRealmPolicyReadServiceGrpc + .GameDesignStartSessionPublishedRealmPolicyReadServiceBlockingStub.class); + when(stub.withMaxInboundMessageSize( + StartSessionPublishedRealmPolicyReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES)) + .thenReturn(stub); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static AbstractStub initializedStub(GameDesignPublishedRealmPolicyClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + return (AbstractStub) field.get(client); + } + + private static void setStub( + GameDesignPublishedRealmPolicyClient client, + GameDesignStartSessionPublishedRealmPolicyReadServiceGrpc + .GameDesignStartSessionPublishedRealmPolicyReadServiceBlockingStub + stub) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + + private static Object readField(Object target, String name) throws ReflectiveOperationException { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java new file mode 100644 index 0000000000..b762d920a0 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java @@ -0,0 +1,63 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionCanonicalRealmCatalogRepositoryTest { + @Test + void rejectsInvalidNamespaceBeforeAnyStorageTransaction() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + + assertThatThrownBy( + () -> + new GameSessionCanonicalRealmCatalogRepository( + dsl, transactionManager, "Not a DNS label")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload namespace"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void rejectsNilTenantSelectorBeforeStartingTheReadTransaction() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var repository = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, "test"); + + assertThatThrownBy(() -> repository.readByCanonicalTenantId(new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonicalTenantId"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void refusesToOpenTheOwnerBoundaryInsideAnExistingTransaction() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var repository = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, "test"); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + repository.establishFreshPublicRealm( + null, null, null, UUID.randomUUID(), UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("before opening a Game Session owner transaction"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + verifyNoInteractions(dsl, transactionManager); + } +} From 261085d40c318afc41056093a6af205b9b888764 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 12:03:51 +1300 Subject: [PATCH 102/129] Apply canonical formatting to owner-proof comment --- ...enuineSelectedPublicationExportPostgresIntegrationTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 01f9bb9036..46350818e7 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -3393,7 +3393,8 @@ public void attachAccountRedemptionProjection( // World source, publication, released-pair proof, fresh tenant association and // public-realm catalog above use the actual owners. The original StartSession tuple is // issued/redeemed by Account after the actual native Logging claim read, under the - // fixture's stipulated Account peer contexts. Game Session reserves the exact tuple and attaches + // fixture's stipulated Account peer contexts. Game Session reserves the exact tuple and + // attaches // Account's redeemed projection in its isolated V35 repository; Account's current // attempt observation and World participation acquisition then traverse native // same-namespace mTLS receivers. Launch association below remains mocked, and retained From 09dc2a13094774ed0c34572a42521ab90fb0cb13 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 12:56:34 +1300 Subject: [PATCH 103/129] Retain exact canonical STARTING launch and World catalog evidence --- .../runtime-and-data.md | 2 +- .../game-session-service/api-contracts.md | 6 + .../runtime-and-data.md | 4 + ...ame-authoring-publishing-and-activation.md | 8 +- ...e-session-runtime-and-tick-coordination.md | 2 + .../world-runtime-and-movement.md | 2 + .../v1/game_session_service.proto | 4 + ...InstanceLaunchAssociationReadEvidence.java | 6 + ...nstanceLaunchAssociationReadGrpcCodec.java | 106 +- ...nceLaunchAssociationReadGrpcCodecTest.java | 297 ++++++ ...licationExportPostgresIntegrationTest.java | 154 ++- ...sionCanonicalInstanceLaunchRepository.java | 959 ++++++++++++++++++ ...essionCanonicalRealmCatalogRepository.java | 8 + ...tanceLaunchAssociationReadGrpcService.java | 129 +++ ...anonical_launch_exact_catalog_identity.sql | 68 ++ ...calGameplayBindingRuntimeTestFixtures.java | 53 +- ...InstanceLaunchPostgresIntegrationTest.java | 486 +++++++++ ...nCanonicalInstanceLaunchProofFixtures.java | 294 ++++++ ...CanonicalInstanceLaunchRepositoryTest.java | 116 +++ ...onCanonicalRealmCatalogRepositoryTest.java | 15 + ...eLaunchAssociationReadGrpcServiceTest.java | 186 ++++ ...alAdmissionHoldFinalizationRepository.java | 2 + ...nonicalInitialAdmissionHoldRepository.java | 2 + .../WorldCanonicalInstanceAssociation.java | 10 + ...anonicalInstanceAssociationRepository.java | 22 +- ...onicalInstanceLifecycleReadRepository.java | 39 +- ...anceOriginalOperationRecoveryVerifier.java | 114 ++- ...calInstancePreparationAssemblyService.java | 2 + ...anonicalInstancePreparationRepository.java | 6 +- ...world_launch_captured_catalog_identity.sql | 280 +++++ ...nceAssociationPostgresIntegrationTest.java | 226 ++++- ...ncePreparationPostgresIntegrationTest.java | 7 +- ...aphApplicationPostgresIntegrationTest.java | 223 +++- ...dCanonicalPlayerLocationHoldProofTest.java | 2 + ...missionHoldFinalizationRepositoryTest.java | 2 + ...calInitialAdmissionHoldRepositoryTest.java | 23 +- ...WorldCanonicalInstanceAssociationTest.java | 37 + ...OriginalOperationRecoveryVerifierTest.java | 80 +- ...nstancePreparationAssemblyServiceTest.java | 4 + ...WorldCompleteLaunchBindingServiceTest.java | 2 + 40 files changed, 3781 insertions(+), 207 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcService.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V43__canonical_launch_exact_catalog_identity.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchProofFixtures.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V64__world_launch_captured_catalog_identity.sql diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 0e549c8ed2..ce6bc40a39 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -343,7 +343,7 @@ Copies into an isolated playtest namespace allocate a new fork-local `characterI The closed descriptor for the bounded `PLAYER_CREATED` input shape contains exactly `schemaVersion: 1`, a canonical nonzero UUID `descriptorId`, a separately persisted authored nonzero UUID `descriptorRevisionId`, `inputKind: "EMPTY_OBJECT"`, and an explicit empty `dependencies` array. Its canonical representation is RFC 8785 JSON; its content digest is SHA-256 over those complete canonical UTF-8 bytes. Both identities are authored provenance, never aliases of an Account identity, private numeric key, published Version or inherited policy revision. This descriptor validates only an explicitly present canonical `{}` creation input. Missing, absent, `null`, nonempty or non-object input and unknown descriptor fields, kinds, versions or dependencies deny; there is no fixed RPG-field fallback. A future nonempty input or dependency family requires its own typed owner contract and inventory proof before acceptance. -Game Design carries the complete descriptor as `creationDescriptor` inside a distinct closed realm-entry policy `schemaVersion: 2` with `entryPolicy: "PLAYER_CREATED"`. All existing selector/display/visibility/scope fields remain required; the entire policy retains its 4,096-byte UTF-8 limit. The retained schema-1 `PRESEEDED_ONLY` representation remains byte-exact and carries no descriptor. Schema 1 cannot be reinterpreted as player-created evidence, and this bounded schema 2 does not supply an auto-provision template. The authenticated selected-source scope binds the canonical tenant and Version; policy selectors bind the exact world and realm. Game Design retains the original policy commit and authored policy revision independently of the descriptor revision through its source snapshot, application, inheritance and exact readback. Changed identities or descriptor bytes are changed evidence, not an equivalent retry. +Game Design carries the complete descriptor as `creationDescriptor` in the closed `PLAYER_CREATED` realm-entry policy. The [release-authored initial actor core](../game-design-service/game-templates.md#release-authored-initial-actor-core) requires policy schema three for fresh actor allocation, retaining its exact display name and selected disposition/mandatory feedback provenance with the descriptor. The earlier schema-two descriptor-only policy and schema-one `PRESEEDED_ONLY` policy retain their original bytes; neither may be reinterpreted as complete fresh actor-core evidence, and no auto-provision template is supplied by the bounded player-created descriptor. All selector/display/visibility/scope fields remain required, and the entire policy retains its 4,096-byte UTF-8 limit. The authenticated selected-source scope binds the canonical tenant and Version; policy selectors bind the exact world and realm. Game Design retains the original policy commit and authored policy revision independently of the descriptor revision through its source snapshot, application, inheritance and exact readback. Changed identities or descriptor bytes are changed evidence, not an equivalent retry. The descriptor is not a pre-authored actor template or an `OTHER_ACTOR_TEMPLATE_ROOTS` inventory witness. An empty dependency array does not prove an empty Entity family: every one of the 23 Entity source-census obligations and the complete selected World/inbound closure remains required. Selected-source retention and its original owner receipt must bind the complete six-family Game Design content, including this exact policy and descriptor, to the unchanged finalized Account authorization and World evidence. Parsing or retaining the descriptor alone grants no creation, allocation, publication, placement, admission or activation authority; those producer/consumer and commit proofs remain separate obligations in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index e304683680..e5585510a9 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -36,6 +36,12 @@ Local request and receipt digests use ADR 0047-style byte-length framing and SHA Catalog creation is not an `OPEN` pointer or a runtime launch. The actual stored catalog revision must subsequently be captured with the exact `STARTING` instance and complete launch association in their owner transaction; neither the initial catalog revision nor an absent pointer proves permission to launch or admit. World lifecycle and initial-bind proof remain independently required. Current implementation and execution limits belong to the [Game Session tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). +### Canonical STARTING Launch Association + +Game Session commits the exact original Account post-authorization tuple, unchanged complete Game Design descriptor/release pair, actual complete catalog identity and new `STARTING` runtime row in one owner transaction. It allocates the opaque runtime UUID once; retries recover that same identity rather than resolving a newer release or catalog. The association retains the catalog creation request, source-intake operation/request, canonical realm UUID, stable namespace/scope and actual catalog revision captured at launch. Independent readback must agree with every original binding. Typed input validation and storage do not themselves prove current Account protection, World readiness or admission authority. + +`GetCanonicalGameInstanceLaunchAssociation` accepts only the verified same-namespace World Management workload without authenticated end-user context. Its independent read identity is separate from the original control-plane operation. The exact original selector and expected descriptor/release digests select the immutable association; the response echoes that selector and returns the complete pair, captured canonical realm UUID/catalog revision, namespace/scope and current runtime status/row version from one owner snapshot. The current runtime projection is not World lifecycle authority. A missing or historically incomplete association produces no successful qualified result; neither a default catalog revision nor a lookup of today's catalog repairs absent launch evidence. This read grants no mutation, lease renewal, runtime admission or activation. + ## Service Interactions Game Session communicates with other platform services exclusively via gRPC for gameplay-domain work. Player-delegated calls carry the typed unsigned `PlayerExecutionContext` defined in the authentication architecture, including the required gameplay scope for admission. Downstream services authenticate the concrete mTLS caller, enforce an exact RPC caller allowlist, validate context/request equality and domain scope, and reject client-supplied identity metadata. Routine gameplay calls do not use signed per-action attestations or a generic replay cache; mutations retain their owning command/effect/request idempotency. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 30f2b57602..d4f2d480c4 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -29,6 +29,10 @@ World Management instances are intended to be replaceable workers over authorita ### Original StartSession execution storage +World consumes the [Game Session-owned launch association](../game-session-service/api-contracts.md#canonical-starting-launch-association) through its exact authenticated owner read. World retains the captured canonical realm UUID and actual catalog revision with the insert-born canonical instance association and preparation input; neither a current catalog lookup nor a caller's initial-admission revision may replace that launch evidence. Initial-admission hold acquisition and finalization compare their realm and catalog revision to this retained association as well as the existing target, namespace, version and lifecycle proof. This does not make a Game Session runtime status World lifecycle authority. + +Additive catalog-identity storage preserves historical associations and original preparation bytes without inventing missing evidence. New complete association records use schema two; preparation-input schema three represents the no-selector form, while schema four carries the original start-location selector. A structurally defined no-selector input does not qualify the current complete fresh lifecycle path, which still requires the accepted selected release and complete original selector proof; this extension does not newly admit receipt-less legacy releases. Existing descriptor, release, original operator tuple and terminal-carrier schemas retain their own meanings. Historically incomplete launch/catalog evidence remains unqualified for this complete preparation path; it is not repaired by a default revision or reinterpretation of retained bytes. + [ADR 0047's World receiving participation](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation) owns the authorization and expiry contract. World's local consequence is a durable execution record bound to the complete original StartSession post-authorization tuple, the distinct Account World participation ID/fence, the actual Game Session owner attempt/fence, the canonical target and the exact preparation input. The input retains the original authenticated source, immutable launch descriptor, release and selected publication evidence; neither a publication receipt nor a Game Design projection is a launch permission. World allocates its own positive monotonic execution fence, not an alias of any supplied fence. Execution admission, materialization, canonical association and `COMMITTED` publication share one uninterrupted local SQL transaction. The operation/request and canonical-target serialization precede the existing publication and topology locks; the database checks actual current time after lock waits before admitting execution. Network calls occur before SQL, never under these locks. Operational transaction timeouts and cancellation bound resource use, not the physical instant of commit. An execution admitted while the original authorization and owner claim are valid may finish after ingress expiry; expiry never permits another execution transaction, renewed participation or a replacement attempt. 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 f8c06760ce..da84945afc 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 @@ -6,13 +6,15 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The unregistered receiving construction retains the complete immutable published realm-policy set in the canonical Game Design-owned carrier, checking every full policy digest, original source capture and terminal publication binding. Its distinct Game Design read requires the existing Account-confirmed exact-replay association before opening the owner source/policy snapshot. Game Session's bounded fresh `NEW_GAME_ROW`, visible public-production `SHARED` producer atomically retains that source, complete policy evidence, shared namespace and catalog, then independently reads back its original identities and actual catalog revision. Additive V42 does not backfill historical catalog rows or restrict the catalog's general scope vocabulary. The genuine-release definition composes the native Game Design creation read into Game Session's fresh association and its Account-confirmed source/policy read into the actual catalog repository and independent readback. That definition has not executed physically; complete producer/consumer and PostgreSQL proof remain required. These components create neither a `STARTING` launch association nor an `OPEN` pointer or gameplay admission. +The source-local composition replaces the stipulated Game Session launch association with its actual owner STARTING transaction, exact original-tuple/catalog retention and native World-to-Game-Session readback. World carries the actual captured realm/catalog revision into its preparation and association rather than inventing a revision. The corrected Common Platform/Game Session/World/Game Design complete gate passes in 2 minutes 37 seconds across 241 tasks, with 32 executed and 209 up-to-date. Available corrected XML records 3,880 executed unit cases and 29 executed non-container integration/cross-service cases, with zero failures or errors; unchanged tasks reuse earlier successful corrected-state results. There are 603 skips: 17 Game Session unit cases and 586 container-dependent integration/cross-service cases, including all three new launch PostgreSQL cases and the genuine native composition. Both schema-generation checks, integration compilation, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass. Architecture contracts separately pass 228 checks, and Flyway sanity passes 12 sets/306 versioned files. These are local compilation, unit and static results, not physical migration or native owner execution. Account issuer/redeemer fixture contexts and the continuously held commit-authority verifier remain explicit stipulations. All four complete handoffs, lifecycle readiness, actor placement and gameplay admission remain open. -The genuine release definition now uses an actual isolated Logging reservation owner and native file-backed mTLS current-claim read instead of fixed Logging claim evidence. Account issuer/redeemer contexts remain explicit fixture stipulations; the current claim is point-in-time evidence, not continuous protection of a later owner commit. The newly composed Logging database and native receiver path has not executed locally. Game Session launch association, uninterrupted commit protection, final owner settlement, lifecycle readiness and activation remain open; no broader handoff is complete from these definitions. +The unregistered receiving construction retains the complete immutable published realm-policy set in the canonical Game Design-owned carrier, checking every full policy digest, original source capture and terminal publication binding. Its distinct Game Design read requires the existing Account-confirmed exact-replay association before opening the owner source/policy snapshot. Game Session's bounded fresh `NEW_GAME_ROW`, visible public-production `SHARED` producer atomically retains that source, complete policy evidence, shared namespace and catalog, then independently reads back its original identities and actual catalog revision. Additive V42 does not backfill historical catalog rows or restrict the catalog's general scope vocabulary. The genuine-release definition composes the native Game Design creation read into Game Session's fresh association and its Account-confirmed source/policy read into the actual catalog repository and independent readback. That definition has not executed physically; complete producer/consumer and PostgreSQL proof remain required. The catalog-only producer grants neither launch nor admission authority; the separate STARTING owner construction above remains unregistered and physically unproved. + +The genuine release definition now uses an actual isolated Logging reservation owner and native file-backed mTLS current-claim read instead of fixed Logging claim evidence. Account issuer/redeemer contexts remain explicit fixture stipulations; the current claim is point-in-time evidence, not continuous protection of a later owner commit. The newly composed Logging database and native receiver path has not executed locally. Physical launch-association composition, uninterrupted commit protection, final owner settlement, lifecycle readiness and activation remain open; no broader handoff is complete from these definitions. The corrected Common Platform/Game Design/Game Session gate passes in 1 minute 46 seconds across 216 tasks, including complete affected checks, SQL metadata generation, integration compilation, formatting, static analysis, coverage, links and 548 Markdown files. Passing current results total 3,206 executed unit cases and 28 executed non-container integration/cross-service cases; unchanged tasks reuse the preceding corrected candidate's results. There are 376 skips: 17 Game Session units and 359 container-dependent integration/cross-service cases. All six new catalog PostgreSQL cases and the genuine-release composition skip locally. A non-container fixture case validates the complete canonical carrier framing; it is explicitly synthetic and does not replace physical owner composition. The narrow Game Design fixture artifact contains only its operation record and two fixture families, without repository classes, application configuration or migrations. No Docker, physical PostgreSQL, certificate custody or complete handoff execution is claimed. -The current source-construction batch defines actual isolated Logging, Account and Game Session stores for original participation acquisition, a file-backed mTLS Logging claim reader, the Game Session V35 attempt reader, World typed original-operation acquisition with additive V63 admission evidence, and the source-only authored initial actor core described at the [Game Design owner](../../architecture/microservices/game-design-service/game-templates.md#release-authored-initial-actor-core). The producer validates selected schema-three source bindings but does not yet deliver or persist a new actor-allocation handoff. The genuine-release-to-World definition reserves the exact original tuple in an isolated Game Session store before Account redemption, attaches the exact redeemed projection afterward, and traverses the native Account-to-Game-Session current-attempt and World-to-Account participation clients and receivers. Its Game Session launch association and some Account caller contexts remain stipulated; the composition replaces the earlier fixed Logging claim and source/catalog stipulations as described above. Stores, servers and the reusable transport clients are prepared before the unchanged 30-second owner lease; the later descriptor and preparation work must still fit that lease without renewal or rearming. The acquisition definition compiled but has not executed physically, and its acquired observation is not continuous foreign-owner protection. No production receiver, credential path, allocation, lifecycle or admission activation is enabled. +The current source-construction batch defines actual isolated Logging, Account and Game Session stores for original participation acquisition, a file-backed mTLS Logging claim reader, the Game Session V35 attempt reader, World typed original-operation acquisition with additive V63 admission evidence, and the source-only authored initial actor core described at the [Game Design owner](../../architecture/microservices/game-design-service/game-templates.md#release-authored-initial-actor-core). The producer validates selected schema-three source bindings but does not yet deliver or persist a new actor-allocation handoff. The genuine-release-to-World definition reserves the exact original tuple in an isolated Game Session store before Account redemption, attaches the exact redeemed projection afterward, and traverses the native Account-to-Game-Session current-attempt and World-to-Account participation clients and receivers. The new STARTING construction replaces its stipulated launch association; some Account caller contexts and the continuous commit-protection verifier remain stipulated. The composition also replaces the earlier fixed Logging claim and source/catalog stipulations as described above. Stores, servers and the reusable transport clients are prepared before the unchanged 30-second owner lease; the later descriptor and preparation work must still fit that lease without renewal or rearming. The acquisition definition compiled but has not executed physically, and its acquired observation is not continuous foreign-owner protection. No production receiver, credential path, allocation, lifecycle or admission activation is enabled. The historical [Validation run 38075220202](https://github.com/benhook1013/FireMUD/actions/runs/38075220202) tests published source `e0f048e4eb5810eb69581dcb2c74e612cb368a60` through merge `e0e6e6394d51218511cd8e8a8ec72eeffb454fb5`, not the later local construction. Account's 1,683 aggregate cases include one failed concurrent historical acknowledgement-receipt recovery case on PostgreSQL 16.15: the independent reader correctly denies because its observed WAL flush does not cover the insertion fence. That test's unconditional recovery-success expectation is not the accepted conditional recovery contract. The 13 protected-entry and 31 Draft-fence PostgreSQL cases pass physically; the Account job is cancelled after its check fails, so this is neither a green aggregate nor current-source proof. Gameplay's separately qualified PostgreSQL 18 original-acknowledgement proof covers only its fresh storage boundary; it does not establish historical recovery, continuous owner protection or gameplay admission. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index d2401c48d9..47b6a0cf40 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for Game Session runtime and tick ## Current Status +The unregistered canonical STARTING launch construction now defines one owner transaction retaining the unchanged original Account tuple, complete Game Design descriptor/release pair, actual source-backed catalog identity and newly allocated opaque runtime UUID. Additive V43 keeps historical V26 rows incomplete rather than backfilling them. Independent launch readback and an exact same-namespace World-only receiver expose the captured realm/catalog revision alongside the complete original binding. Complete local module checks pass, including the new unit definitions and compilation of the native genuine-release composition. All three new launch PostgreSQL cases skip without Docker; their migration, atomicity and exact-retry behavior remain physically unproved. Storage and authenticated readback do not establish current Account protection, World ACTIVE readiness, an OPEN pointer or gameplay admission; all runtime registration and activation remain denied. The [authoring tracker](game-authoring-publishing-and-activation.md#current-status) records the composed counts and remaining handoffs. + The unregistered fresh-tenant receiver retains Game Design's complete authenticated creation receipt, reserves a private Game Session key and claim atomically, and independently reads back the exact association. Its focused source-local gate passed; all six PostgreSQL cases skipped locally. The fresh public-production catalog batch preserves the complete Game Design-owned published-policy carrier, requires the exact source and one explicit visible `SHARED` policy, and atomically creates the source intake, stable namespace and catalog with complete readback. Additive V42 leaves historical incomplete evidence unavailable rather than backfilling it. A genuine native Game Design-to-Game Session producer/consumer composition is defined but has not executed physically; catalog storage is not a `STARTING` launch, `OPEN` pointer or admission. The [authoring tracker](game-authoring-publishing-and-activation.md#current-status) records the shared producer and proof limits. The construction branch is consuming the Account-only original current-attempt reader from published source `e9a29f43ae47598fdc2cacd8f65cf784ed96e0ea` ([#3153](https://github.com/benhook1013/FireMUD/pull/3153)). Its prerequisite owner-attempt repository and additive V35 are separate from existing canonical runtime admission. Existing Common contracts and the additional admission-terminal proto definitions are preserved. The reader remains unregistered; its exact tuple/projection, database-clock expiry, no-mutation and peer-identity definitions do not prove original production attempt creation, continuous Account protection, admission or activation. Source-local Common/Game Session checks passed, while PostgreSQL cases skipped; receiving-tree validation and physical composed acquisition remain pending. The broader donor template/launch-association integration suite is not part of this bounded reader intake or its proof claim. 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 6efe2e02e8..d5dc4a0b16 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +The unregistered launch-composition batch retains the actual Game Session launch-captured realm UUID and catalog revision through World preparation, insert-born instance association, lifecycle/recovery readback and initial-admission hold comparisons. Additive V64 preserves old association and preparation bytes while requiring complete catalog identity for new work; historical missing fields are not inferred or backfilled. Complete local World checks pass with 656 unit cases and one non-container integration case executed; all 224 container-dependent integration cases skip. New storage and mismatch definitions therefore remain physically unproved. The genuine-release definition compiles with the actual Game Session STARTING writer and native exact-owner launch reader instead of a mocked launch result; Account caller contexts and continuous commit-protection verification remain stipulated. This is not ACTIVE readiness, placement, authenticated settlement or activation proof. The [authoring tracker](game-authoring-publishing-and-activation.md#current-status) records the full composed gate. + This tracker is the permanent reader-facing implementation record for world runtime, room reads, movement, lifecycle orchestration, and Draft topology mutation. Canonical target-state design remains under [design/architecture](../../architecture/README.md). Canonical preparation now defines the typed original Game Session operation input and an explicit Account participation acquisition adapter before World SQL. Additive V63 retains the exact returned original-attempt observation and checks the unchanged original authorization and Game Session lease against the database clock after admission locks; the legacy untyped entry cannot authorize fresh materialization. This is unregistered source construction, not production wiring or continuous foreign-owner protection. Schema generation succeeds, but physical V63 migration, concurrency and genuine Account-acquisition-to-World execution remain unproved locally; existing positive storage definitions retain explicitly synthetic complete witnesses. The [World owner contract](../../architecture/microservices/world-management-service/runtime-and-data.md#original-startsession-execution-storage) owns the settlement and recovery limits; the [authoring tracker](./game-authoring-publishing-and-activation.md) records composed proof and remaining handoffs. diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 3edd89245a..3112b7632c 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -638,6 +638,10 @@ message GetCanonicalGameInstanceLaunchAssociationResponse { gamedesign.v1.AuthoredWorldReleaseAttestationEvidence release_attestation = 16; shared.v1.ErrorDetail error = 17; bool public_production = 18; + // Non-nil realm identity captured with this immutable launch association. + string canonical_realm_id = 19; + // Positive catalog revision captured with that same launch association. + int64 catalog_revision = 20; } message GetGameplayCommandStatusRequest { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java index a72c3401d3..ddc77c72f6 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java @@ -61,6 +61,8 @@ public record Result( UUID playableStateNamespaceId, RealmEntryPolicy.StateScope playableStateScope, boolean publicProduction, + UUID canonicalRealmId, + long catalogRevision, CurrentGameInstanceStatus currentGameInstanceStatus, long currentRowVersion, CompleteLaunchBindingEvidence launchBindingEvidence) { @@ -74,6 +76,10 @@ public record Result( if (!publicProduction) { throw new IllegalArgumentException("Launch association read requires public production"); } + requireNonNil(canonicalRealmId, "canonicalRealmId"); + if (catalogRevision <= 0) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } Objects.requireNonNull(currentGameInstanceStatus, "currentGameInstanceStatus"); if (currentRowVersion < 0) { throw new IllegalArgumentException("currentRowVersion must not be negative"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java index b11c479e75..4d8e4d44ae 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java @@ -17,7 +17,10 @@ import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; -/** Closed request mapping and strict exact-readback validation for the Game Session owner API. */ +/** + * Closed request/result mapping and strict exact-readback validation for the Game Session owner + * API. + */ public final class CanonicalGameInstanceLaunchAssociationReadGrpcCodec { private static final UUID NIL_UUID = new UUID(0L, 0L); @@ -25,6 +28,7 @@ private CanonicalGameInstanceLaunchAssociationReadGrpcCodec() {} public static GetCanonicalGameInstanceLaunchAssociationRequest toRequest(Request request) { Objects.requireNonNull(request, "request"); + requireIndependentReadIdentity(request); return GetCanonicalGameInstanceLaunchAssociationRequest.newBuilder() .setReadRequestId(request.readRequestId().toString()) .setTargetNamespace(request.targetNamespace()) @@ -40,6 +44,71 @@ public static GetCanonicalGameInstanceLaunchAssociationRequest toRequest(Request .build(); } + /** Decodes only the closed exact selector; decoding does not authenticate its caller. */ + public static Request fromRequest(GetCanonicalGameInstanceLaunchAssociationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "GetCanonicalGameInstanceLaunchAssociation request"); + try { + Request decoded = + new Request( + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getGameInstanceUuid(), "gameInstanceUuid"), + request.getControlPlaneRequestId(), + request.getLaunchDescriptorId(), + request.getExpectedDescriptorRequestDigest(), + request.getExpectedDescriptorResultDigest(), + request.getExpectedReleaseAttestationEvidenceDigest()); + requireIndependentReadIdentity(decoded); + if (!toRequest(decoded).equals(request)) { + throw new IllegalArgumentException("Canonical launch association request is not canonical"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Exact canonical launch association request required", malformed); + } + } + + /** Encodes and revalidates the complete exact association read result. */ + public static GetCanonicalGameInstanceLaunchAssociationResponse toResponse(Result result) { + Objects.requireNonNull(result, "result"); + Request request = result.request(); + CompleteLaunchBindingEvidence binding = result.launchBindingEvidence(); + var completeRequest = completeBindingRequest(request); + var completeResponse = + AuthoredWorldLaunchDescriptorGrpcCodec.toCompleteResponse(completeRequest, binding); + var response = + GetCanonicalGameInstanceLaunchAssociationResponse.newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setGameInstanceUuid(request.gameInstanceUuid().toString()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setLaunchDescriptorId(request.launchDescriptorId()) + .setDescriptorRequestDigest(request.expectedDescriptorRequestDigest()) + .setDescriptorResultDigest(request.expectedDescriptorResultDigest()) + .setReleaseAttestationEvidenceDigest(request.expectedReleaseAttestationEvidenceDigest()) + .setPlayableStateNamespaceId(result.playableStateNamespaceId().toString()) + .setPlayableStateScope(result.playableStateScope().name()) + .setCurrentGameInstanceStatus(result.currentGameInstanceStatus().name()) + .setCurrentRowVersion(result.currentRowVersion()) + .setLaunchDescriptor(completeResponse.getLaunchDescriptor()) + .setReleaseAttestation(completeResponse.getReleaseAttestation()) + .setPublicProduction(result.publicProduction()) + .setCanonicalRealmId(result.canonicalRealmId().toString()) + .setCatalogRevision(result.catalogRevision()) + .build(); + if (!result.equals(fromResponse(request, response))) { + throw new IllegalArgumentException( + "Canonical launch association result did not survive its closed wire mapping"); + } + return response; + } + /** Validates all ten request echoes and the complete unchanged descriptor/release evidence. */ public static Result fromResponse( Request expectedRequest, GetCanonicalGameInstanceLaunchAssociationResponse response) { @@ -91,15 +160,7 @@ public static Result fromResponse( throw new IllegalArgumentException( "Game Session must return the complete descriptor and release attestation pair"); } - var completeRequest = - GetLaunchDescriptorRequest.newBuilder() - .setRequestId(expectedRequest.readRequestId().toString()) - .setCanonicalTenantId(expectedRequest.canonicalTenantId().toString()) - .setWorldSlug(expectedRequest.worldSlug()) - .setControlPlaneRequestId(expectedRequest.controlPlaneRequestId()) - .setExpectedRequestDigest(expectedRequest.expectedDescriptorRequestDigest()) - .setExpectedResultDigest(expectedRequest.expectedDescriptorResultDigest()) - .build(); + var completeRequest = completeBindingRequest(expectedRequest); var completeResponse = GetCompleteLaunchBindingResponse.newBuilder() .setRequestId(response.getReadRequestId()) @@ -125,6 +186,11 @@ public static Result fromResponse( if (!response.getPublicProduction()) { throw new IllegalArgumentException("Canonical launch association requires public production"); } + UUID canonicalRealmId = + parseCanonicalNonNilUuid(response.getCanonicalRealmId(), "canonicalRealmId"); + if (response.getCatalogRevision() <= 0) { + throw new IllegalArgumentException("Catalog revision is missing or invalid"); + } CurrentGameInstanceStatus status; try { @@ -140,11 +206,31 @@ public static Result fromResponse( playableStateNamespaceId, scope, response.getPublicProduction(), + canonicalRealmId, + response.getCatalogRevision(), status, response.getCurrentRowVersion(), binding); } + private static GetLaunchDescriptorRequest completeBindingRequest(Request request) { + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setExpectedRequestDigest(request.expectedDescriptorRequestDigest()) + .setExpectedResultDigest(request.expectedDescriptorResultDigest()) + .build(); + } + + private static void requireIndependentReadIdentity(Request request) { + if (request.readRequestId().toString().equals(request.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Launch association read identity must remain separate from the original request"); + } + } + private static void requireEcho(String expected, String actual, String field) { if (actual.isEmpty() || !expected.equals(actual)) { throw new IllegalArgumentException( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java new file mode 100644 index 0000000000..1364b768e3 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java @@ -0,0 +1,297 @@ +package net.firedevops.firemud.common.gamesession; + +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.Locale; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodecTest; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Result; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import org.junit.jupiter.api.Test; + +class CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest { + private static final UUID READ_ID = uuid("10000000-0000-4000-8000-000000000001"); + private static final UUID GAME_INSTANCE_ID = uuid("20000000-0000-4000-8000-000000000002"); + private static final UUID PLAYABLE_NAMESPACE_ID = uuid("30000000-0000-4000-8000-000000000003"); + private static final UUID REALM_ID = uuid("40000000-0000-4000-8000-abcd00000004"); + + @Test + void roundTripsTheIndependentReadSelectorAndCompleteCapturedBinding() throws Exception { + Fixture fixture = fixture(); + + var wireRequest = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toRequest(fixture.request()); + var decodedRequest = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromRequest(wireRequest); + var response = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toResponse(fixture.result()); + var decoded = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), response); + + assertThat(decodedRequest).isEqualTo(fixture.request()); + assertThat(decodedRequest.readRequestId().toString()) + .isNotEqualTo(fixture.request().controlPlaneRequestId()); + assertThat(decodedRequest.readRequestId()) + .isNotEqualTo( + fixture.result().launchBindingEvidence().descriptor().authoredWorldSourceOperationId()); + assertThat(decodedRequest.controlPlaneRequestId()) + .isEqualTo(fixture.request().controlPlaneRequestId()); + assertThat(decoded).isEqualTo(fixture.result()); + assertThat(decoded.canonicalRealmId()).isEqualTo(REALM_ID); + assertThat(decoded.catalogRevision()).isEqualTo(17L); + assertThat(response.hasLaunchDescriptor()).isTrue(); + assertThat(response.hasReleaseAttestation()).isTrue(); + + var expectedPair = + AuthoredWorldLaunchDescriptorGrpcCodec.toCompleteResponse( + completeBindingRequest(fixture.request()), fixture.result().launchBindingEvidence()); + assertThat(response.getLaunchDescriptor()).isEqualTo(expectedPair.getLaunchDescriptor()); + assertThat(response.getReleaseAttestation()).isEqualTo(expectedPair.getReleaseAttestation()); + } + + @Test + void rejectsMissingMalformedNilAndNoncanonicalRealmIdentity() throws Exception { + Fixture fixture = fixture(); + var response = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toResponse(fixture.result()); + + assertThatThrownBy(() -> result(fixture, new UUID(0L, 0L), 17L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonicalRealmId"); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), response.toBuilder().clearCanonicalRealmId().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), + response.toBuilder().setCanonicalRealmId("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), + response.toBuilder() + .setCanonicalRealmId(REALM_ID.toString().toUpperCase(Locale.ROOT)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), + response.toBuilder().setCanonicalRealmId(new UUID(0L, 0L).toString()).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMissingZeroAndNegativeCatalogRevision() throws Exception { + Fixture fixture = fixture(); + var response = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toResponse(fixture.result()); + + assertThatThrownBy(() -> result(fixture, REALM_ID, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("catalogRevision"); + assertThatThrownBy(() -> result(fixture, REALM_ID, -1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("catalogRevision"); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), response.toBuilder().clearCatalogRevision().build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Catalog revision"); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), response.toBuilder().setCatalogRevision(-1L).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Catalog revision"); + } + + @Test + void rejectsChangedOriginalEchoMissingPairAndUnknownFields() throws Exception { + Fixture fixture = fixture(); + var response = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toResponse(fixture.result()); + + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), + response.toBuilder().setControlPlaneRequestId("changed").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("controlPlaneRequestId echo changed"); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), response.toBuilder().clearLaunchDescriptor().build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete descriptor and release attestation pair"); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), response.toBuilder().clearReleaseAttestation().build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("complete descriptor and release attestation pair"); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), response.toBuilder().setUnknownFields(unknown(91)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromRequest( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toRequest(fixture.request()) + .toBuilder() + .setUnknownFields(unknown(92)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + @Test + void rejectsUnknownNestedDescriptorAndReleaseEvidence() throws Exception { + Fixture fixture = fixture(); + var response = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toResponse(fixture.result()); + var unknownDescriptor = + response.toBuilder() + .setLaunchDescriptor( + response.getLaunchDescriptor().toBuilder().setUnknownFields(unknown(93)).build()) + .build(); + var unknownRelease = + response.toBuilder() + .setReleaseAttestation( + response.getReleaseAttestation().toBuilder().setUnknownFields(unknown(94)).build()) + .build(); + + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), unknownDescriptor)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + fixture.request(), unknownRelease)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + private static Fixture fixture() throws Exception { + var launchFixture = StartSessionLaunchDescriptorGrpcCodecTest.fixture(); + AuthoredWorldLaunchDescriptorEvidence descriptor = launchFixture.descriptor(); + var selector = launchFixture.associationRead().worldPublishedStartLocationEvidence(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + selector); + var binding = new CompleteLaunchBindingEvidence(descriptor, release); + Request request = + new Request( + READ_ID, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + GAME_INSTANCE_ID, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + Result result = + new Result( + request, + PLAYABLE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + REALM_ID, + 17L, + CurrentGameInstanceStatus.STARTING, + 12L, + binding); + return new Fixture(request, result); + } + + private static Result result(Fixture fixture, UUID canonicalRealmId, long catalogRevision) { + Result original = fixture.result(); + return new Result( + original.request(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.publicProduction(), + canonicalRealmId, + catalogRevision, + original.currentGameInstanceStatus(), + original.currentRowVersion(), + original.launchBindingEvidence()); + } + + private static GetLaunchDescriptorRequest completeBindingRequest(Request request) { + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setExpectedRequestDigest(request.expectedDescriptorRequestDigest()) + .setExpectedResultDigest(request.expectedDescriptorResultDigest()) + .build(); + } + + private static UnknownFieldSet unknown(int fieldNumber) { + return UnknownFieldSet.newBuilder() + .addField(fieldNumber, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture(Request request, Result result) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 46350818e7..a0b69b95ed 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -267,11 +267,13 @@ import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameInstanceLaunchAssociationReadGrpcService; import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadGrpcService; import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; @@ -340,7 +342,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mapstruct.factory.Mappers; -import org.mockito.Mockito; import org.springframework.boot.jooq.autoconfigure.SpringTransactionProvider; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -405,11 +406,13 @@ * receivers. Game Session also resolves the actual fresh Game Design tenant receipt over mTLS, * stores and independently reads its numeric tenant association, then reads the actual * Account-confirmed source and published policy set over mTLS and stores and independently reads - * its canonical public-realm catalog. Game Session launch association remains mocked, and Account - * participation is point-in-time evidence, not a continuous cross-service lock. This does not - * establish production certificate custody, full application server wiring, production ingress, - * runtime launch, activation or registration. The Logging evidence is point-in-time and does not - * lock later Account or Game Session commits. + * its canonical public-realm catalog. Game Session creates and independently reads the exact + * STARTING runtime/launch association with its captured catalog revision, and World consumes that + * evidence through the native exact-peer Game Session reader. Account participation is + * point-in-time evidence, not a continuous cross-service lock. Activation authority remains an + * explicit fixture stipulation. This does not establish production certificate custody, full + * application server wiring, production ingress, runtime launch, activation or registration. The + * Logging evidence is point-in-time and does not lock later Account or Game Session commits. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -616,6 +619,15 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var gameSessionPublishedRealmPolicyClient = new GameDesignPublishedRealmPolicyClient( endpoints, pki.client("game-session-service"), channels, NAMESPACE); + var worldToGameSessionLaunchClient = + new CanonicalGameInstanceLaunchAssociationClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var wrongWorkloadLaunchClient = + new CanonicalGameInstanceLaunchAssociationClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var worldToGameDesignPreparationClient = + new AuthoredWorldLaunchDescriptorClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); var wrongWorkloadActivationClient = canonicalActivationClient(worldServer, pki.client("account-service"), channels); var gameSessionActivationClient = @@ -629,6 +641,9 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex gameSessionPreparationRetryClient.init(); gameSessionFreshTenantCreationClient.init(); gameSessionPublishedRealmPolicyClient.init(); + worldToGameSessionLaunchClient.init(); + wrongWorkloadLaunchClient.init(); + worldToGameDesignPreparationClient.init(); var automationIntakeRepository = new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); var entityIntakeRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); @@ -3394,16 +3409,44 @@ public void attachAccountRedemptionProjection( // public-realm catalog above use the actual owners. The original StartSession tuple is // issued/redeemed by Account after the actual native Logging claim read, under the // fixture's stipulated Account peer contexts. Game Session reserves the exact tuple and - // attaches - // Account's redeemed projection in its isolated V35 repository; Account's current + // attaches Account's redeemed projection in its isolated V35 repository; Account's + // current // attempt observation and World participation acquisition then traverse native - // same-namespace mTLS receivers. Launch association below remains mocked, and retained + // same-namespace mTLS receivers. The launch below is produced and independently read by + // Game Session, then consumed through its exact-peer native reader. Retained Account // participation is point-in-time evidence, not a continuous remote lock. CompleteLaunchBindingEvidence completeLaunchEvidence = new CompleteLaunchBindingEvidence( completeBinding.descriptor(), completeBinding.releaseAttestation()); - UUID canonicalGameInstanceId = UUID.randomUUID(); - UUID playableStateNamespaceId = UUID.randomUUID(); + var canonicalLaunchRepository = + new GameSessionCanonicalInstanceLaunchRepository( + gameSessionAttempts.dsl(), + gameSessionAttempts.transactionManager(), + NAMESPACE, + canonicalRealmCatalogRepository); + var canonicalLaunch = + canonicalLaunchRepository.createStartingLaunch( + startSessionTuple, completeLaunchEvidence, canonicalRealmCatalog); + var canonicalLaunchRetry = + canonicalLaunchRepository.createStartingLaunch( + startSessionTuple, completeLaunchEvidence, canonicalRealmCatalog); + UUID canonicalGameInstanceId = canonicalLaunch.gameInstanceUuid(); + UUID playableStateNamespaceId = canonicalLaunch.playableStateNamespaceId(); + assertThat(canonicalLaunchRetry.gameInstanceUuid()).isEqualTo(canonicalGameInstanceId); + assertThat(canonicalLaunchRetry.gameInstanceId()) + .isEqualTo(canonicalLaunch.gameInstanceId()); + assertThat(canonicalLaunch.originalStartSessionTuple()) + .containsExactly(startSessionTuple.canonicalBytes()); + assertThat(canonicalLaunch.launchBindingEvidence()).isEqualTo(completeLaunchEvidence); + assertThat(canonicalLaunch.canonicalRealmId()).isEqualTo(canonicalRealmCatalog.realmId()); + assertThat(canonicalLaunch.catalogRevision()) + .isEqualTo(canonicalRealmCatalog.catalogRevision()); + assertThat(playableStateNamespaceId) + .isEqualTo(canonicalRealmCatalog.playableStateNamespaceId()); + register( + gameSessionHandlers, + new CanonicalGameInstanceLaunchAssociationReadGrpcService( + canonicalLaunchRepository, NAMESPACE)); var preparationAssociationRequest = new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( UUID.randomUUID(), @@ -3416,24 +3459,37 @@ public void attachAccountRedemptionProjection( completeLaunchEvidence.descriptor().requestDigest(), completeLaunchEvidence.descriptor().resultDigest(), completeLaunchEvidence.releaseAttestation().evidenceDigest()); - var stipulatedGameSessionReader = - Mockito.mock(CanonicalGameInstanceLaunchAssociationClient.class); - Mockito.when(stipulatedGameSessionReader.read(Mockito.any())) - .thenAnswer( - invocation -> { - var request = - invocation.getArgument( - 0, CanonicalGameInstanceLaunchAssociationReadEvidence.Request.class); - return new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( - request, - playableStateNamespaceId, - RealmEntryPolicy.StateScope.SHARED, - true, - CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus - .STARTING, - 1L, - completeLaunchEvidence); - }); + var independentCanonicalLaunch = + canonicalLaunchRepository + .readByLaunchIdentity(preparationAssociationRequest) + .orElseThrow(); + assertThat(independentCanonicalLaunch.gameInstanceUuid()) + .isEqualTo(canonicalGameInstanceId); + assertThat(independentCanonicalLaunch.canonicalRealmId()) + .isEqualTo(canonicalRealmCatalog.realmId()); + assertThat(independentCanonicalLaunch.catalogRevision()) + .isEqualTo(canonicalRealmCatalog.catalogRevision()); + assertThat(independentCanonicalLaunch.originalStartSessionTuple()) + .containsExactly(canonicalLaunch.originalStartSessionTuple()); + assertThatThrownBy(() -> wrongWorkloadLaunchClient.read(preparationAssociationRequest)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + var nativeLaunchRead = worldToGameSessionLaunchClient.read(preparationAssociationRequest); + assertThat(nativeLaunchRead.request()).isEqualTo(preparationAssociationRequest); + assertThat(nativeLaunchRead.canonicalRealmId()) + .isEqualTo(canonicalRealmCatalog.realmId()); + assertThat(nativeLaunchRead.catalogRevision()) + .isEqualTo(canonicalRealmCatalog.catalogRevision()); + assertThat(nativeLaunchRead.playableStateNamespaceId()) + .isEqualTo(playableStateNamespaceId); + assertThat(nativeLaunchRead.launchBindingEvidence()).isEqualTo(completeLaunchEvidence); + assertThat(nativeLaunchRead.currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING); var completeBindingRepository = new WorldCompleteLaunchBindingRepository(world.dsl()); var canonicalAssociationRepository = @@ -3449,10 +3505,7 @@ public void attachAccountRedemptionProjection( var lifecycleRepository = new WorldCanonicalInstanceLifecycleReadRepository( world.dsl(), world.transactions(), canonicalAssociationRepository); - try (var worldToGameDesignPreparationClient = - new AuthoredWorldLaunchDescriptorClient( - endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { - worldToGameDesignPreparationClient.init(); + { var completeBindingService = new WorldCompleteLaunchBindingService( worldToGameDesignPreparationClient, @@ -3461,7 +3514,7 @@ public void attachAccountRedemptionProjection( world.transactions(), NAMESPACE, null, - stipulatedGameSessionReader); + worldToGameSessionLaunchClient); var preparationAssembly = new WorldCanonicalInstancePreparationAssemblyService( NAMESPACE, @@ -3469,7 +3522,7 @@ public void attachAccountRedemptionProjection( worldIntakes, worldIdentities, worldPublicationProof.frozenTopologies(), - stipulatedGameSessionReader, + worldToGameSessionLaunchClient, worldToGameDesignPreparationClient); var preparationService = new WorldCanonicalInstancePreparationService( @@ -3542,7 +3595,7 @@ public void attachAccountRedemptionProjection( controlPlaneRequestId)); var preparationResult = preparationRepository.readOwnerPreparation(assembledPreparationInput).orElseThrow(); - var stipulatedGameSessionEvidence = assembledPreparationInput.gameSessionReadEvidence(); + var retainedGameSessionEvidence = assembledPreparationInput.gameSessionReadEvidence(); var independentLifecycleRead = lifecycleRepository.read(expectedLifecycleRequest).orElseThrow(); var selectedReleasedStart = @@ -3556,14 +3609,23 @@ public void attachAccountRedemptionProjection( assertThat(preparedLifecycle.lifecycleStatus()).isEqualTo("PREPARING"); assertThat(preparedLifecycle.lifecycleEpoch()).isEqualTo(1L); assertThat(preparedLifecycle.launchBinding()).isEqualTo(completeLaunchEvidence); - assertThat(stipulatedGameSessionEvidence.currentGameSessionStatus()) + assertThat(retainedGameSessionEvidence.currentGameSessionStatus()) .isEqualTo("STARTING"); - assertThat(stipulatedGameSessionEvidence.currentGameSessionRowVersion()).isEqualTo(1L); - assertThat(stipulatedGameSessionEvidence.playableStateScope()).isEqualTo("SHARED"); - assertThat(stipulatedGameSessionEvidence.publicProduction()).isTrue(); - assertThat(stipulatedGameSessionEvidence.descriptor()) + assertThat(retainedGameSessionEvidence.currentGameSessionRowVersion()) + .isEqualTo(canonicalLaunch.currentRowVersion()); + assertThat(retainedGameSessionEvidence.canonicalRealmId()) + .isEqualTo(canonicalRealmCatalog.realmId()); + assertThat(retainedGameSessionEvidence.catalogRevision()) + .isEqualTo(canonicalRealmCatalog.catalogRevision()); + assertThat(preparationResult.association().identity().canonicalRealmId()) + .isEqualTo(canonicalRealmCatalog.realmId()); + assertThat(preparationResult.association().identity().catalogRevision()) + .isEqualTo(canonicalRealmCatalog.catalogRevision()); + assertThat(retainedGameSessionEvidence.playableStateScope()).isEqualTo("SHARED"); + assertThat(retainedGameSessionEvidence.publicProduction()).isTrue(); + assertThat(retainedGameSessionEvidence.descriptor()) .isEqualTo(completeLaunchEvidence.descriptor()); - assertThat(stipulatedGameSessionEvidence.releaseAttestation()) + assertThat(retainedGameSessionEvidence.releaseAttestation()) .isEqualTo(completeLaunchEvidence.releaseAttestation()); assertThat(preparedLifecycle.captureId()) .isEqualTo(assembledPreparationInput.captureId()); @@ -3762,7 +3824,7 @@ public void attachAccountRedemptionProjection( activationRequest.preparingEvidenceBytes())) .isFalse(); - var stipulatedGameSessionStartEvidence = + var retainedGameSessionStartEvidence = assembledPreparationInput.gameSessionReadEvidence(); AtomicInteger activationAuthorityChecks = new AtomicInteger(); AtomicInteger heldActivationChecks = new AtomicInteger(); @@ -3775,14 +3837,14 @@ public void attachAccountRedemptionProjection( candidate.canonicalRequestBytes(), activationRequest.canonicalRequestBytes()) || !"STARTING" - .equals(stipulatedGameSessionStartEvidence.currentGameSessionStatus()) + .equals(retainedGameSessionStartEvidence.currentGameSessionStatus()) || !candidate .preparing() .launchBinding() .equals( new CompleteLaunchBindingEvidence( - stipulatedGameSessionStartEvidence.descriptor(), - stipulatedGameSessionStartEvidence.releaseAttestation()))) { + retainedGameSessionStartEvidence.descriptor(), + retainedGameSessionStartEvidence.releaseAttestation()))) { throw new SecurityException( "Stipulated activation fixture differs from the exact PREPARING " + "binding"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java new file mode 100644 index 0000000000..7823b150ad --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java @@ -0,0 +1,959 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.CanonicalRealmCatalog; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Game Session owner storage for one complete canonical launch. + * + *

Inputs are integrity-checked values obtained by the original StartSession composition; this + * repository does not authenticate their producers, repeat Account authorization, or admit a World + * instance. It atomically creates only the durable Game Session STARTING row and its V26 launch + * association, then proves the exact committed owner state in a separate read transaction. + */ +public final class GameSessionCanonicalInstanceLaunchRepository { + private static final ObjectMapper JSON = + new ObjectMapper().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final String workloadNamespace; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final TransactionTemplate writeTransaction; + private final TransactionTemplate readTransaction; + + public GameSessionCanonicalInstanceLaunchRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + String workloadNamespace, + GameSessionCanonicalRealmCatalogRepository catalogRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is missing or invalid"); + } + this.workloadNamespace = workloadNamespace; + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.writeTransaction = new TransactionTemplate(transactionManager); + this.writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.readTransaction = new TransactionTemplate(transactionManager); + this.readTransaction.setReadOnly(true); + this.readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + /** + * Creates one fresh canonical runtime allocation or returns its exact existing request retry. + * + *

The opaque Game Instance UUID is allocated inside the owner transaction only after the + * namespace/request lock and exact-retry lookup. The original tuple and complete descriptor / + * release pair are retained without projecting or reconstructing either value. + */ + public CanonicalInstanceLaunch createStartingLaunch( + StartSessionPostAuthorizationExecutionTuple originalTuple, + CompleteLaunchBindingEvidence completeLaunchBindingEvidence, + CanonicalRealmCatalog expectedCatalog) { + requireNoActiveOwnerTransaction(); + PreparedLaunch input = + prepareInput(originalTuple, completeLaunchBindingEvidence, expectedCatalog); + + CanonicalInstanceLaunch committed = + writeTransaction.execute(status -> createInTransaction(input)); + if (committed == null) { + throw new InvalidCanonicalInstanceLaunchException( + "Game Session canonical launch transaction returned no result"); + } + + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector = + independentReadSelector(input, committed.gameInstanceUuid()); + CanonicalInstanceLaunch independentReadback = + readByLaunchIdentity(selector) + .orElseThrow( + () -> + new InvalidCanonicalInstanceLaunchException( + "Committed canonical launch association is unavailable on independent readback")); + if (!matchesInput(independentReadback, input)) { + throw new InvalidCanonicalInstanceLaunchException( + "Committed canonical launch failed independent exact tuple, binding, runtime, or catalog readback"); + } + return independentReadback; + } + + /** Reads complete immutable launch evidence and the current Game Instance row in one snapshot. */ + public Optional readByLaunchIdentity( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request) { + requireNoActiveOwnerTransaction(); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new InvalidCanonicalInstanceLaunchException( + "Launch-association namespace differs from the configured Game Session owner"); + } + Optional result = + readTransaction.execute(status -> readByLaunchIdentityInTransaction(request)); + return Objects.requireNonNull( + result, "Game Session launch read transaction returned no result"); + } + + private CanonicalInstanceLaunch createInTransaction(PreparedLaunch input) { + requireOwnerTransaction(); + lockIdentity(input); + + CanonicalRealmCatalog actualCatalog = + catalogRepository + .readByCanonicalTenantIdInOwnerTransaction(input.expectedCatalog().canonicalTenantId()) + .orElseThrow( + () -> + new InvalidCanonicalInstanceLaunchException( + "Complete source-backed canonical catalog is unavailable in the launch transaction")); + requireSameCatalog(input.expectedCatalog(), actualCatalog); + validateTupleBindingCatalogAndDescriptor(input.originalTuple(), input.binding(), actualCatalog); + + Record existing = + readLaunchRowByOperationInTransaction(input.originalTuple().controlPlaneRequestId(), true); + if (existing != null) { + CanonicalInstanceLaunch retained = readLaunchRow(existing, false); + if (!matchesInput(retained, input)) { + throw new InvalidCanonicalInstanceLaunchException( + "Original StartSession request is already bound to different complete launch evidence"); + } + return retained; + } + + rejectOrphanedRunOwnedInstance(input); + UUID gameInstanceUuid = newNonNilUuid(); + long startingRowVersion = 0L; + long gameInstanceId = insertStartingGameInstance(input, gameInstanceUuid, startingRowVersion); + insertLaunchAssociation( + input, actualCatalog, gameInstanceId, gameInstanceUuid, startingRowVersion); + + Record inserted = + readLaunchRowByOperationInTransaction(input.originalTuple().controlPlaneRequestId(), false); + if (inserted == null) { + throw new InvalidCanonicalInstanceLaunchException( + "New Game Session STARTING instance and launch association did not read back in their owner transaction"); + } + return readLaunchRow(inserted, true); + } + + private Optional readByLaunchIdentityInTransaction( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request) { + requireOwnerTransaction(); + Record row = readLaunchRowByOperationInTransaction(request.controlPlaneRequestId(), false); + if (row == null) { + return Optional.empty(); + } + CanonicalInstanceLaunch launch = readLaunchRow(row, false); + requireRequestMatchesLaunch(request, launch); + return Optional.of(launch); + } + + private Record readLaunchRowByOperationInTransaction( + String controlPlaneRequestId, boolean forUpdate) { + requireOwnerTransaction(); + String suffix = forUpdate ? " FOR UPDATE OF launch" : ""; + return dsl.fetchOne( + "SELECT launch.*, runtime.status AS gs_current_status," + + " runtime.row_version AS gs_current_row_version," + + " runtime.game_instance_uuid AS gs_runtime_instance_uuid," + + " runtime.tenant_id AS gs_runtime_tenant_id," + + " runtime.runtime_version AS gs_runtime_version," + + " runtime.owner_account_uuid AS gs_runtime_owner_account_uuid," + + " runtime.game_template_id AS gs_runtime_game_template_id," + + " runtime.launch_descriptor_id AS gs_runtime_launch_descriptor_id," + + " runtime.version_id AS gs_runtime_version_id," + + " runtime.release_bundle_id AS gs_runtime_release_bundle_id," + + " runtime.generation_config_revision AS gs_runtime_generation_config_revision," + + " runtime.version_state_epoch AS gs_runtime_version_state_epoch," + + " runtime.run_owned_start_request_id AS gs_runtime_request_id," + + " runtime.run_owned_start_request_digest AS gs_runtime_request_digest," + + " runtime.run_owned_start_published_release_bundle_ref AS gs_runtime_release_ref," + + " launch.complete_launch_binding_evidence::text AS gs_complete_launch_binding_json" + + " FROM game_session_canonical_instance_launch launch" + + " LEFT JOIN game_instances runtime" + + " ON runtime.tenant_id = launch.game_session_tenant_id" + + " AND runtime.id = launch.game_instance_id" + + " AND runtime.game_instance_uuid = launch.game_instance_uuid" + + " WHERE launch.target_namespace = ? AND launch.control_plane_request_id = ?" + + suffix, + workloadNamespace, + controlPlaneRequestId); + } + + private CanonicalInstanceLaunch readLaunchRow(Record row, boolean requireStartingAtCapture) { + String namespace = required(row, "target_namespace", String.class); + String controlPlaneRequestId = required(row, "control_plane_request_id", String.class); + long gameSessionTenantId = required(row, "game_session_tenant_id", Long.class); + UUID canonicalTenantId = required(row, "canonical_tenant_id", UUID.class); + UUID tenantAssociationOperationId = + required(row, "tenant_association_operation_id", UUID.class); + UUID tenantAssociationRequestId = required(row, "tenant_association_request_id", UUID.class); + int sourceSchemaVersion = required(row, "tenant_source_schema_version", Integer.class); + String sourceTargetNamespace = required(row, "tenant_source_target_namespace", String.class); + UUID sourceRequestId = required(row, "tenant_source_request_id", UUID.class); + UUID sourceCanonicalTenantId = required(row, "tenant_source_canonical_tenant_id", UUID.class); + long sourceGameRowId = required(row, "tenant_source_game_row_id", Long.class); + String sourceGameTenantKey = required(row, "tenant_source_game_tenant_key", String.class); + String sourceProvenanceKind = required(row, "tenant_source_provenance_kind", String.class); + String associationKind = required(row, "tenant_association_kind", String.class); + long gameInstanceId = required(row, "game_instance_id", Long.class); + UUID gameInstanceUuid = required(row, "game_instance_uuid", UUID.class); + UUID canonicalRealmId = required(row, "canonical_realm_id", UUID.class); + String worldSlug = required(row, "world_slug", String.class); + UUID playableStateNamespaceId = required(row, "playable_state_namespace_id", UUID.class); + String playableStateScopeName = required(row, "playable_state_scope", String.class); + boolean publicProduction = required(row, "public_production", Boolean.class); + long capturedStartingRowVersion = required(row, "captured_starting_row_version", Long.class); + long gameTemplateId = required(row, "game_template_id", Long.class); + String launchDescriptorId = required(row, "launch_descriptor_id", String.class); + long versionId = required(row, "version_id", Long.class); + long releaseBundleId = required(row, "release_bundle_id", Long.class); + String generationConfigRevision = required(row, "generation_config_revision", String.class); + long versionStateEpoch = required(row, "version_state_epoch", Long.class); + String bindingJson = required(row, "gs_complete_launch_binding_json", String.class); + byte[] originalTupleBytes = required(row, "original_start_session_tuple", byte[].class); + UUID catalogCreationRequestId = required(row, "catalog_creation_request_id", UUID.class); + long catalogRevision = required(row, "catalog_revision", Long.class); + UUID catalogSourceIntakeOperationId = + required(row, "catalog_source_intake_operation_id", UUID.class); + UUID catalogSourceIntakeRequestId = + required(row, "catalog_source_intake_request_id", UUID.class); + + if (!workloadNamespace.equals(namespace) + || !"FRESH_SOURCE_BOUND".equals(associationKind) + || sourceSchemaVersion != 1 + || !namespace.equals(sourceTargetNamespace) + || !sourceRequestId.equals(tenantAssociationRequestId) + || !canonicalTenantId.equals(sourceCanonicalTenantId) + || !"NEW_GAME_ROW".equals(sourceProvenanceKind) + || gameSessionTenantId <= 0L + || gameInstanceId <= 0L + || capturedStartingRowVersion < 0L + || catalogRevision <= 0L) { + throw new InvalidCanonicalInstanceLaunchException( + "Stored canonical launch source identity, scope, or captured catalog key is incomplete"); + } + + Long runtimeTenantId = nullable(row, "gs_runtime_tenant_id", Long.class); + Long currentRowVersion = nullable(row, "gs_current_row_version", Long.class); + String status = nullable(row, "gs_current_status", String.class); + UUID runtimeUuid = nullable(row, "gs_runtime_instance_uuid", UUID.class); + if (runtimeTenantId == null + || currentRowVersion == null + || status == null + || runtimeUuid == null + || runtimeTenantId != gameSessionTenantId + || !gameInstanceUuid.equals(runtimeUuid) + || currentRowVersion < capturedStartingRowVersion) { + throw new InvalidCanonicalInstanceLaunchException( + "Stored canonical launch association has no exact current Game Instance row"); + } + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus typedStatus = + parseStatus(status); + if (requireStartingAtCapture + && (typedStatus + != CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING + || currentRowVersion != capturedStartingRowVersion)) { + throw new InvalidCanonicalInstanceLaunchException( + "New canonical launch must capture the exact STARTING Game Instance row version"); + } + + CompleteLaunchBindingEvidence binding = decodeBinding(bindingJson); + StartSessionPostAuthorizationExecutionTuple originalTuple = decodeTuple(originalTupleBytes); + CanonicalRealmCatalog catalog = + catalogRepository + .readByCanonicalTenantIdInOwnerTransaction(canonicalTenantId) + .orElseThrow( + () -> + new InvalidCanonicalInstanceLaunchException( + "Stored canonical launch source-backed catalog is unavailable")); + requireStoredCatalogIdentity( + row, + catalog, + canonicalRealmId, + worldSlug, + playableStateNamespaceId, + catalogCreationRequestId, + catalogRevision, + catalogSourceIntakeOperationId, + catalogSourceIntakeRequestId); + AuthoredWorldSourceEvidence launchSource = catalog.sourceEvidence(); + validateTupleBindingCatalogAndDescriptor(originalTuple, binding, catalog); + requireAssociationBinding( + namespace, + controlPlaneRequestId, + canonicalTenantId, + gameSessionTenantId, + tenantAssociationOperationId, + tenantAssociationRequestId, + sourceSchemaVersion, + sourceTargetNamespace, + sourceRequestId, + sourceCanonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + sourceProvenanceKind, + gameInstanceId, + gameInstanceUuid, + canonicalRealmId, + worldSlug, + playableStateNamespaceId, + playableStateScopeName, + publicProduction, + capturedStartingRowVersion, + gameTemplateId, + launchDescriptorId, + versionId, + releaseBundleId, + generationConfigRevision, + versionStateEpoch, + originalTuple, + binding, + row, + launchSource, + catalog); + + return new CanonicalInstanceLaunch( + namespace, + controlPlaneRequestId, + gameSessionTenantId, + canonicalTenantId, + gameInstanceId, + gameInstanceUuid, + canonicalRealmId, + playableStateNamespaceId, + RealmEntryPolicy.StateScope.valueOf(playableStateScopeName), + publicProduction, + typedStatus, + currentRowVersion, + capturedStartingRowVersion, + catalogCreationRequestId, + catalogRevision, + catalogSourceIntakeOperationId, + catalogSourceIntakeRequestId, + binding, + originalTupleBytes, + catalog); + } + + private void requireAssociationBinding( + String namespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + long gameSessionTenantId, + UUID tenantAssociationOperationId, + UUID tenantAssociationRequestId, + int sourceSchemaVersion, + String sourceTargetNamespace, + UUID sourceRequestId, + UUID sourceCanonicalTenantId, + long sourceGameRowId, + String sourceGameTenantKey, + String sourceProvenanceKind, + long gameInstanceId, + UUID gameInstanceUuid, + UUID canonicalRealmId, + String worldSlug, + UUID playableStateNamespaceId, + String playableStateScopeName, + boolean publicProduction, + long capturedStartingRowVersion, + long gameTemplateId, + String launchDescriptorId, + long versionId, + long releaseBundleId, + String generationConfigRevision, + long versionStateEpoch, + StartSessionPostAuthorizationExecutionTuple tuple, + CompleteLaunchBindingEvidence binding, + Record row, + AuthoredWorldSourceEvidence source, + CanonicalRealmCatalog catalog) { + var descriptor = binding.descriptor(); + FreshTenantCreationEvidence fresh = catalog.associationSourceEvidence(); + if (!namespace.equals(catalog.targetNamespace()) + || !canonicalTenantId.equals(catalog.canonicalTenantId()) + || gameSessionTenantId != catalog.gameSessionTenantId() + || !tenantAssociationOperationId.equals(catalog.tenantAssociationOperationId()) + || !tenantAssociationRequestId.equals(fresh.creationRequestId()) + || sourceSchemaVersion != fresh.schemaVersion() + || !sourceTargetNamespace.equals(fresh.targetNamespace()) + || !sourceRequestId.equals(fresh.creationRequestId()) + || !sourceCanonicalTenantId.equals(fresh.canonicalTenantId()) + || sourceGameRowId != fresh.sourceGameRowId() + || !sourceGameTenantKey.equals(fresh.sourceGameTenantKey()) + || !sourceProvenanceKind.equals(fresh.provenanceKind()) + || !source.equals(catalog.sourceEvidence()) + || !worldSlug.equals(catalog.worldSlug()) + || !canonicalRealmId.equals(catalog.realmId()) + || !playableStateNamespaceId.equals(catalog.playableStateNamespaceId()) + || !"SHARED".equals(playableStateScopeName) + || !publicProduction + || !controlPlaneRequestId.equals(tuple.controlPlaneRequestId()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !canonicalTenantId.equals(tuple.preAuthorizationTuple().action().scope().tenantId()) + || !namespace.equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || tuple.preAuthorizationTuple().action().target().gameTemplateId() != gameTemplateId + || !tuple + .preAuthorizationTuple() + .action() + .target() + .ownerAccountId() + .equals(nullable(row, "gs_runtime_owner_account_uuid", UUID.class)) + || descriptor.gameTemplateId() != gameTemplateId + || !descriptor.launchDescriptorId().equals(launchDescriptorId) + || descriptor.versionId() != versionId + || descriptor.releaseBundleId() != releaseBundleId + || !descriptor.generationConfigRevision().equals(generationConfigRevision) + || descriptor.versionStateEpoch() != versionStateEpoch + || descriptor.authoredWorldSourceOperationId().equals(source.operationId()) == false + || !descriptor.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest()) + || !descriptor + .publishedReleaseBundleRef() + .equals(required(row, "gs_runtime_release_ref", String.class)) + || !Long.toString(descriptor.versionId()) + .equals(required(row, "gs_runtime_version", String.class)) + || required(row, "gs_runtime_game_template_id", Long.class) != gameTemplateId + || !descriptor + .launchDescriptorId() + .equals(required(row, "gs_runtime_launch_descriptor_id", String.class)) + || required(row, "gs_runtime_version_id", Long.class) != versionId + || required(row, "gs_runtime_release_bundle_id", Long.class) != releaseBundleId + || !descriptor + .generationConfigRevision() + .equals(required(row, "gs_runtime_generation_config_revision", String.class)) + || required(row, "gs_runtime_version_state_epoch", Long.class) != versionStateEpoch + || gameInstanceId <= 0L + || NIL_UUID.equals(tenantAssociationOperationId) + || NIL_UUID.equals(gameInstanceUuid) + || capturedStartingRowVersion < 0L + || required(row, "gs_runtime_tenant_id", Long.class) != gameSessionTenantId + || !gameInstanceUuid.equals(required(row, "gs_runtime_instance_uuid", UUID.class)) + || !controlPlaneRequestId.equals(required(row, "gs_runtime_request_id", String.class)) + || !tuple + .mutationDigest() + .equals(required(row, "gs_runtime_request_digest", String.class))) { + throw new InvalidCanonicalInstanceLaunchException( + "Stored canonical launch association differs from the exact original tuple, complete binding, or source-backed catalog"); + } + } + + private void requireStoredCatalogIdentity( + Record row, + CanonicalRealmCatalog catalog, + UUID canonicalRealmId, + String worldSlug, + UUID playableStateNamespaceId, + UUID catalogCreationRequestId, + long catalogRevision, + UUID catalogSourceIntakeOperationId, + UUID catalogSourceIntakeRequestId) { + if (!catalog.targetNamespace().equals(required(row, "target_namespace", String.class)) + || !catalog.canonicalTenantId().equals(required(row, "canonical_tenant_id", UUID.class)) + || !catalog.realmId().equals(canonicalRealmId) + || !catalog.worldSlug().equals(worldSlug) + || !catalog.playableStateNamespaceId().equals(playableStateNamespaceId) + || !catalog.catalogRequestId().equals(catalogCreationRequestId) + || catalog.catalogRevision() != catalogRevision + || !catalog.intakeOperationId().equals(catalogSourceIntakeOperationId) + || !catalog.intakeRequestId().equals(catalogSourceIntakeRequestId) + || !catalog.worldSlug().equals(required(row, "world_slug", String.class)) + || !"SHARED".equals(required(row, "playable_state_scope", String.class)) + || !Boolean.TRUE.equals(required(row, "public_production", Boolean.class))) { + throw new InvalidCanonicalInstanceLaunchException( + "Stored launch catalog identity is not the exact actual complete catalog key and revision"); + } + } + + private void lockIdentity(PreparedLaunch input) { + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ?, 1))", + workloadNamespace, + input.expectedCatalog().canonicalTenantId().toString()); + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + "canonical-instance-launch:" + + workloadNamespace + + ":" + + input.originalTuple().controlPlaneRequestId()); + } + + private void rejectOrphanedRunOwnedInstance(PreparedLaunch input) { + String requestId = input.originalTuple().controlPlaneRequestId(); + Record orphan = + dsl.fetchOne( + "SELECT id FROM game_instances WHERE tenant_id = ?" + + " AND run_owned_start_request_id = ? FOR UPDATE", + input.expectedCatalog().gameSessionTenantId(), + requestId); + if (orphan != null) { + throw new InvalidCanonicalInstanceLaunchException( + "Original StartSession request has a retained Game Instance without its exact canonical launch association"); + } + } + + private long insertStartingGameInstance( + PreparedLaunch input, UUID gameInstanceUuid, long startingRowVersion) { + var descriptor = input.binding().descriptor(); + Record inserted = + dsl.fetchOne( + "INSERT INTO game_instances" + + " (tenant_id, runtime_version, owner_account_id," + + " owner_account_uuid, status, row_version, game_instance_uuid, game_template_id," + + " launch_descriptor_id, version_id, release_bundle_id, generation_config_revision," + + " version_state_epoch, run_owned_start_request_id," + + " run_owned_start_request_digest, run_owned_start_published_release_bundle_ref)" + + " VALUES (?, ?, NULL, ?, 'STARTING', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + + " RETURNING id", + input.expectedCatalog().gameSessionTenantId(), + Long.toString(descriptor.versionId()), + input.originalTuple().preAuthorizationTuple().action().target().ownerAccountId(), + startingRowVersion, + gameInstanceUuid, + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.generationConfigRevision(), + descriptor.versionStateEpoch(), + input.originalTuple().controlPlaneRequestId(), + input.originalTuple().mutationDigest(), + descriptor.publishedReleaseBundleRef()); + return required(inserted, "id", Long.class); + } + + private void insertLaunchAssociation( + PreparedLaunch input, + CanonicalRealmCatalog catalog, + long gameInstanceId, + UUID gameInstanceUuid, + long startingRowVersion) { + FreshTenantCreationEvidence fresh = catalog.associationSourceEvidence(); + var descriptor = input.binding().descriptor(); + String bindingJson = encodeBinding(input.binding()); + requireOne( + dsl.execute( + "INSERT INTO game_session_canonical_instance_launch" + + " (target_namespace, control_plane_request_id, game_session_tenant_id," + + " canonical_tenant_id, tenant_association_operation_id, tenant_association_request_id," + + " tenant_source_schema_version, tenant_source_target_namespace, tenant_source_request_id," + + " tenant_source_canonical_tenant_id, tenant_source_game_row_id," + + " tenant_source_game_tenant_key, tenant_source_provenance_kind, tenant_association_kind," + + " game_instance_id, game_instance_uuid, canonical_realm_id, world_slug," + + " playable_state_namespace_id, playable_state_scope, public_production," + + " captured_starting_row_version, game_template_id, launch_descriptor_id, version_id," + + " release_bundle_id, generation_config_revision, version_state_epoch," + + " complete_launch_binding_evidence, original_start_session_tuple," + + " catalog_creation_request_id, catalog_revision, catalog_source_intake_operation_id," + + " catalog_source_intake_request_id)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND'," + + " ?, ?, ?, ?, ?, 'SHARED', TRUE, ?, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?)", + workloadNamespace, + input.originalTuple().controlPlaneRequestId(), + catalog.gameSessionTenantId(), + catalog.canonicalTenantId(), + catalog.tenantAssociationOperationId(), + fresh.creationRequestId(), + fresh.schemaVersion(), + fresh.targetNamespace(), + fresh.creationRequestId(), + fresh.canonicalTenantId(), + fresh.sourceGameRowId(), + fresh.sourceGameTenantKey(), + fresh.provenanceKind(), + gameInstanceId, + gameInstanceUuid, + catalog.realmId(), + catalog.worldSlug(), + catalog.playableStateNamespaceId(), + startingRowVersion, + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.generationConfigRevision(), + descriptor.versionStateEpoch(), + bindingJson, + input.originalTuple().canonicalBytes(), + catalog.catalogRequestId(), + catalog.catalogRevision(), + catalog.intakeOperationId(), + catalog.intakeRequestId()), + "canonical instance launch association"); + } + + private PreparedLaunch prepareInput( + StartSessionPostAuthorizationExecutionTuple originalTuple, + CompleteLaunchBindingEvidence completeLaunchBindingEvidence, + CanonicalRealmCatalog expectedCatalog) { + Objects.requireNonNull(originalTuple, "originalTuple"); + Objects.requireNonNull(completeLaunchBindingEvidence, "completeLaunchBindingEvidence"); + Objects.requireNonNull(expectedCatalog, "expectedCatalog"); + final StartSessionPostAuthorizationExecutionTuple decoded; + try { + decoded = StartSessionPostAuthorizationExecutionTuple.decode(originalTuple.canonicalBytes()); + if (!Arrays.equals(decoded.canonicalBytes(), originalTuple.canonicalBytes())) { + throw new IllegalArgumentException( + "Original StartSession tuple is not exact canonical evidence"); + } + completeLaunchBindingEvidence.descriptor().requireValid(); + completeLaunchBindingEvidence + .releaseAttestation() + .requireValid(completeLaunchBindingEvidence.descriptor()); + validateTupleBindingCatalogAndDescriptor( + decoded, completeLaunchBindingEvidence, expectedCatalog); + } catch (IllegalArgumentException invalid) { + throw new InvalidCanonicalInstanceLaunchException( + "Original tuple, complete descriptor/release pair, or source-backed catalog is invalid", + invalid); + } + if (!workloadNamespace.equals(expectedCatalog.targetNamespace())) { + throw new InvalidCanonicalInstanceLaunchException( + "Canonical launch catalog belongs to another Game Session namespace"); + } + return new PreparedLaunch(decoded, completeLaunchBindingEvidence, expectedCatalog); + } + + private void validateTupleBindingCatalogAndDescriptor( + StartSessionPostAuthorizationExecutionTuple tuple, + CompleteLaunchBindingEvidence binding, + CanonicalRealmCatalog catalog) { + var descriptor = binding.descriptor(); + var release = binding.releaseAttestation(); + var action = tuple.preAuthorizationTuple().action(); + AuthoredWorldSourceEvidence source = catalog.sourceEvidence(); + if (!"human_operator".equals(tuple.issuanceKind()) + || !"StartSession".equals(tuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(tuple.preAuthorizationTuple().targetOwner()) + || !workloadNamespace.equals( + tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !catalog + .targetNamespace() + .equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !catalog.canonicalTenantId().equals(action.scope().tenantId()) + || !tuple.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !catalog.targetNamespace().equals(descriptor.targetNamespace()) + || !catalog.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !catalog.worldSlug().equals(descriptor.worldSlug()) + || !source.operationId().equals(descriptor.authoredWorldSourceOperationId()) + || !source.evidenceDigest().equals(descriptor.authoredWorldSourceEvidenceDigest()) + || action.target().gameTemplateId() != descriptor.gameTemplateId() + || !catalog.canonicalTenantId().equals(release.canonicalTenantId()) + || !catalog.targetNamespace().equals(release.targetNamespace()) + || !catalog.worldSlug().equals(release.worldSlug()) + || !source.operationId().equals(release.authoredWorldSourceOperationId()) + || !source.evidenceDigest().equals(release.authoredWorldSourceEvidenceDigest()) + || !descriptor.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef()) + || !catalog.canonicalTenantId().equals(catalog.sourceEvidence().canonicalTenantId()) + || !catalog.targetNamespace().equals(catalog.sourceEvidence().targetNamespace()) + || catalog.catalogRevision() <= 0L + || catalog.gameSessionTenantId() <= 0L) { + throw new InvalidCanonicalInstanceLaunchException( + "Original StartSession tuple, selected release pair, and complete canonical catalog identity disagree"); + } + } + + private boolean matchesInput(CanonicalInstanceLaunch launch, PreparedLaunch input) { + return launch.targetNamespace().equals(workloadNamespace) + && launch.controlPlaneRequestId().equals(input.originalTuple().controlPlaneRequestId()) + && launch.canonicalTenantId().equals(input.expectedCatalog().canonicalTenantId()) + && launch.gameSessionTenantId() == input.expectedCatalog().gameSessionTenantId() + && Arrays.equals(launch.originalStartSessionTuple(), input.originalTuple().canonicalBytes()) + && launch.launchBindingEvidence().equals(input.binding()) + && sameCatalog(launch.canonicalRealmCatalog(), input.expectedCatalog()); + } + + private static boolean sameCatalog(CanonicalRealmCatalog left, CanonicalRealmCatalog right) { + return left.targetNamespace().equals(right.targetNamespace()) + && left.canonicalTenantId().equals(right.canonicalTenantId()) + && left.gameSessionTenantId() == right.gameSessionTenantId() + && left.tenantAssociationOperationId().equals(right.tenantAssociationOperationId()) + && left.associationSourceEvidence().equals(right.associationSourceEvidence()) + && left.sourceEvidence().equals(right.sourceEvidence()) + && left.intakeRequestId().equals(right.intakeRequestId()) + && left.intakeOperationId().equals(right.intakeOperationId()) + && left.intakeRequestDigest().equals(right.intakeRequestDigest()) + && left.intakeReceiptDigest().equals(right.intakeReceiptDigest()) + && left.catalogRequestId().equals(right.catalogRequestId()) + && left.catalogRequestDigest().equals(right.catalogRequestDigest()) + && left.catalogReceiptDigest().equals(right.catalogReceiptDigest()) + && left.realmId().equals(right.realmId()) + && left.playableStateNamespaceId().equals(right.playableStateNamespaceId()) + && left.tenantSlug().equals(right.tenantSlug()) + && left.worldSlug().equals(right.worldSlug()) + && left.realmSlug().equals(right.realmSlug()) + && left.realmDisplayName().equals(right.realmDisplayName()) + && left.sourceWorldDisplayName().equals(right.sourceWorldDisplayName()) + && left.entryPolicy().equals(right.entryPolicy()) + && left.catalogRevision() == right.catalogRevision() + && MessageDigest.isEqual( + left.completePolicySetEvidence(), right.completePolicySetEvidence()) + && MessageDigest.isEqual( + RealmPolicyPublishedEvidenceCodec.encode(left.publishedSet()), + RealmPolicyPublishedEvidenceCodec.encode(right.publishedSet())); + } + + private static void requireSameCatalog( + CanonicalRealmCatalog expected, CanonicalRealmCatalog actual) { + if (!sameCatalog(expected, actual)) { + throw new InvalidCanonicalInstanceLaunchException( + "Exact pre-read canonical catalog evidence changed before launch storage"); + } + } + + private static void requireRequestMatchesLaunch( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request request, + CanonicalInstanceLaunch launch) { + var descriptor = launch.launchBindingEvidence().descriptor(); + var release = launch.launchBindingEvidence().releaseAttestation(); + if (!request.targetNamespace().equals(launch.targetNamespace()) + || !request.canonicalTenantId().equals(launch.canonicalTenantId()) + || !request.worldSlug().equals(launch.canonicalRealmCatalog().worldSlug()) + || !request.gameInstanceUuid().equals(launch.gameInstanceUuid()) + || !request.controlPlaneRequestId().equals(launch.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request.expectedReleaseAttestationEvidenceDigest().equals(release.evidenceDigest())) { + throw new InvalidCanonicalInstanceLaunchException( + "Exact canonical launch read selector differs from the retained owner evidence"); + } + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request independentReadSelector( + PreparedLaunch input, UUID gameInstanceUuid) { + UUID requestId; + do { + requestId = newNonNilUuid(); + } while (requestId.equals(input.binding().descriptor().authoredWorldSourceOperationId()) + || requestId.toString().equals(input.originalTuple().controlPlaneRequestId())); + var descriptor = input.binding().descriptor(); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + requestId, + input.expectedCatalog().targetNamespace(), + input.expectedCatalog().canonicalTenantId(), + descriptor.worldSlug(), + gameInstanceUuid, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + input.binding().releaseAttestation().evidenceDigest()); + } + + private static CompleteLaunchBindingEvidence decodeBinding(String json) { + try { + CompleteLaunchBindingEvidence evidence = + JSON.readValue(json, CompleteLaunchBindingEvidence.class); + evidence.descriptor().requireValid(); + evidence.releaseAttestation().requireValid(evidence.descriptor()); + return evidence; + } catch (JsonProcessingException | IllegalArgumentException malformed) { + throw new InvalidCanonicalInstanceLaunchException( + "Stored complete descriptor and release-attestation pair is malformed", malformed); + } + } + + private static String encodeBinding(CompleteLaunchBindingEvidence evidence) { + try { + evidence.descriptor().requireValid(); + evidence.releaseAttestation().requireValid(evidence.descriptor()); + return JSON.writeValueAsString(evidence); + } catch (JsonProcessingException | IllegalArgumentException invalid) { + throw new InvalidCanonicalInstanceLaunchException( + "Complete descriptor and release-attestation pair cannot be retained", invalid); + } + } + + private static StartSessionPostAuthorizationExecutionTuple decodeTuple(byte[] bytes) { + try { + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(bytes); + if (!Arrays.equals(bytes, tuple.canonicalBytes())) { + throw new IllegalArgumentException("Stored original StartSession tuple is not exact"); + } + return tuple; + } catch (IllegalArgumentException malformed) { + throw new InvalidCanonicalInstanceLaunchException( + "Stored original StartSession post-authorization tuple is missing or malformed", + malformed); + } + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + parseStatus(String value) { + try { + return CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.valueOf( + value); + } catch (IllegalArgumentException unknown) { + throw new InvalidCanonicalInstanceLaunchException( + "Stored Game Instance has an unsupported current lifecycle status", unknown); + } + } + + private static UUID newNonNilUuid() { + UUID value = UUID.randomUUID(); + if (NIL_UUID.equals(value)) { + throw new IllegalStateException("Game Session UUID allocator returned nil"); + } + return value; + } + + private static void requireNoActiveOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical launch owner operation requires its own independent transaction"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Session canonical launch storage access requires an active owner transaction"); + } + } + + private static T required(Record row, String field, Class type) { + if (row == null) { + throw new InvalidCanonicalInstanceLaunchException( + "Game Session canonical launch storage returned no row"); + } + T value = row.get(field, type); + if (value == null) { + throw new InvalidCanonicalInstanceLaunchException( + "Stored canonical launch is missing required evidence: " + field); + } + return value; + } + + private static T nullable(Record row, String field, Class type) { + return row == null ? null : row.get(field, type); + } + + private static void requireOne(int affectedRows, String label) { + if (affectedRows != 1) { + throw new InvalidCanonicalInstanceLaunchException( + "Game Session " + label + " insert did not affect exactly one row"); + } + } + + private record PreparedLaunch( + StartSessionPostAuthorizationExecutionTuple originalTuple, + CompleteLaunchBindingEvidence binding, + CanonicalRealmCatalog expectedCatalog) {} + + /** Complete immutable launch association, its live GS row, and the exact catalog snapshot. */ + public record CanonicalInstanceLaunch( + String targetNamespace, + String controlPlaneRequestId, + long gameSessionTenantId, + UUID canonicalTenantId, + long gameInstanceId, + UUID gameInstanceUuid, + UUID canonicalRealmId, + UUID playableStateNamespaceId, + RealmEntryPolicy.StateScope playableStateScope, + boolean publicProduction, + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + currentGameInstanceStatus, + long currentRowVersion, + long capturedStartingRowVersion, + UUID catalogCreationRequestId, + long catalogRevision, + UUID catalogSourceIntakeOperationId, + UUID catalogSourceIntakeRequestId, + CompleteLaunchBindingEvidence launchBindingEvidence, + byte[] originalStartSessionTuple, + CanonicalRealmCatalog canonicalRealmCatalog) { + public CanonicalInstanceLaunch { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + requirePositive(gameSessionTenantId, "gameSessionTenantId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requirePositive(gameInstanceId, "gameInstanceId"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + requireNonNil(canonicalRealmId, "canonicalRealmId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + if (playableStateScope != RealmEntryPolicy.StateScope.SHARED || !publicProduction) { + throw new IllegalArgumentException( + "Canonical launch requires public-production SHARED scope"); + } + Objects.requireNonNull(currentGameInstanceStatus, "currentGameInstanceStatus"); + if (currentRowVersion < 0L || capturedStartingRowVersion < 0L) { + throw new IllegalArgumentException("Canonical launch row versions must not be negative"); + } + requireNonNil(catalogCreationRequestId, "catalogCreationRequestId"); + requirePositive(catalogRevision, "catalogRevision"); + requireNonNil(catalogSourceIntakeOperationId, "catalogSourceIntakeOperationId"); + requireNonNil(catalogSourceIntakeRequestId, "catalogSourceIntakeRequestId"); + Objects.requireNonNull(launchBindingEvidence, "launchBindingEvidence"); + launchBindingEvidence.descriptor().requireValid(); + launchBindingEvidence.releaseAttestation().requireValid(launchBindingEvidence.descriptor()); + originalStartSessionTuple = + Objects.requireNonNull(originalStartSessionTuple, "originalStartSessionTuple").clone(); + if (originalStartSessionTuple.length == 0 + || originalStartSessionTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException("Complete original StartSession tuple bytes required"); + } + Objects.requireNonNull(canonicalRealmCatalog, "canonicalRealmCatalog"); + if (!canonicalTenantId.equals(canonicalRealmCatalog.canonicalTenantId()) + || !canonicalRealmId.equals(canonicalRealmCatalog.realmId()) + || catalogRevision != canonicalRealmCatalog.catalogRevision() + || !catalogCreationRequestId.equals(canonicalRealmCatalog.catalogRequestId()) + || !catalogSourceIntakeOperationId.equals(canonicalRealmCatalog.intakeOperationId()) + || !catalogSourceIntakeRequestId.equals(canonicalRealmCatalog.intakeRequestId())) { + throw new IllegalArgumentException( + "Launch result differs from the actual complete catalog key"); + } + } + + @Override + public byte[] originalStartSessionTuple() { + return originalStartSessionTuple.clone(); + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) { + throw new IllegalArgumentException(field + " must be positive"); + } + } + + private static void requireNonNil(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a nonnil UUID"); + } + } + } + + public static final class InvalidCanonicalInstanceLaunchException extends IllegalStateException { + public InvalidCanonicalInstanceLaunchException(String message) { + super(message); + } + + public InvalidCanonicalInstanceLaunchException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java index 87a70db4e4..b01d0bdbb7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java @@ -123,6 +123,14 @@ public Optional readByCanonicalTenantId(UUID canonicalTen return Objects.requireNonNull(result, "Game Session canonical catalog read returned no result"); } + /** Reads complete stored catalog evidence inside another Game Session owner transaction. */ + Optional readByCanonicalTenantIdInOwnerTransaction( + UUID canonicalTenantId) { + requireOwnerTransaction(); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + return readByCanonicalTenantIdInTransaction(canonicalTenantId); + } + private CanonicalRealmCatalog establishInTransaction(PreparedInput input) { requireOwnerTransaction(); lockIdentity(input); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcService.java new file mode 100644 index 0000000000..ee0ad3af15 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcService.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Standalone, deliberately unregistered historical launch-association reader. Its current runtime + * projection is neither World lifecycle authority nor authorization for admission or mutation. + */ +public final class CanonicalGameInstanceLaunchAssociationReadGrpcService + extends GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceImplBase { + private final GameSessionCanonicalInstanceLaunchRepository repository; + private final String workloadNamespace; + + public CanonicalGameInstanceLaunchAssociationReadGrpcService( + GameSessionCanonicalInstanceLaunchRepository repository, String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void getCanonicalGameInstanceLaunchAssociation( + GetCanonicalGameInstanceLaunchAssociationRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "observer"); + try { + // Authenticate before parsing the selector or reaching owner storage. + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified World Management workload required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service") + .equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World Management workload required") + .asRuntimeException(); + } + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final CanonicalGameInstanceLaunchAssociationReadEvidence.Request decoded; + if (request == null) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Complete canonical launch-association selector required") + .asRuntimeException()); + return; + } + try { + decoded = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Complete canonical launch-association selector required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Launch-association namespace differs from configured owner") + .asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Independent Game Session launch snapshot required") + .asRuntimeException()); + return; + } + + try { + var retained = repository.readByLaunchIdentity(decoded); + if (retained.isEmpty()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact complete launch association is unavailable") + .asRuntimeException()); + return; + } + var association = retained.orElseThrow(); + var result = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + decoded, + association.playableStateNamespaceId(), + association.playableStateScope(), + association.publicProduction(), + association.canonicalRealmId(), + association.catalogRevision(), + association.currentGameInstanceStatus(), + association.currentRowVersion(), + association.launchBindingEvidence()); + observer.onNext(CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toResponse(result)); + observer.onCompleted(); + } catch (DataAccessException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Session launch owner storage unavailable") + .asRuntimeException()); + } catch (RuntimeException incompleteOrConflicting) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Complete exact launch owner evidence is unavailable") + .asRuntimeException()); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V43__canonical_launch_exact_catalog_identity.sql b/services/game-session-service/src/main/resources/db/migration/V43__canonical_launch_exact_catalog_identity.sql new file mode 100644 index 0000000000..368bdf1847 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V43__canonical_launch_exact_catalog_identity.sql @@ -0,0 +1,68 @@ +-- Keep the complete original operator tuple and exact source-backed catalog identity with each +-- newly created canonical launch. Retained V26 rows remain unqualified and are not backfilled. +ALTER TABLE game_session_canonical_instance_launch + ADD COLUMN original_start_session_tuple BYTEA, + ADD COLUMN catalog_creation_request_id UUID, + ADD COLUMN catalog_revision BIGINT, + ADD COLUMN catalog_source_intake_operation_id UUID, + ADD COLUMN catalog_source_intake_request_id UUID, + ADD CONSTRAINT chk_gs_canonical_instance_launch_original_tuple + CHECK (original_start_session_tuple IS NULL + OR octet_length(original_start_session_tuple) BETWEEN 1 AND 262144), + ADD CONSTRAINT chk_gs_canonical_instance_launch_catalog_identity + CHECK ((original_start_session_tuple IS NULL + AND catalog_creation_request_id IS NULL + AND catalog_revision IS NULL + AND catalog_source_intake_operation_id IS NULL + AND catalog_source_intake_request_id IS NULL) + OR (original_start_session_tuple IS NOT NULL + AND catalog_creation_request_id IS NOT NULL + AND catalog_revision IS NOT NULL + AND catalog_revision > 0 + AND catalog_source_intake_operation_id IS NOT NULL + AND catalog_source_intake_request_id IS NOT NULL + AND catalog_source_intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_source_intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID)); +ALTER TABLE game_session_canonical_realm_catalog + ADD CONSTRAINT uq_gs_canonical_realm_catalog_exact_launch_key + UNIQUE (target_namespace, canonical_tenant_id, realm_id, creation_request_id, + catalog_revision, source_intake_operation_id, source_intake_request_id); + +ALTER TABLE game_session_canonical_instance_launch + ADD CONSTRAINT fk_gs_canonical_instance_launch_exact_catalog + FOREIGN KEY (target_namespace, canonical_tenant_id, canonical_realm_id, + catalog_creation_request_id, catalog_revision, + catalog_source_intake_operation_id, catalog_source_intake_request_id) + REFERENCES game_session_canonical_realm_catalog + (target_namespace, canonical_tenant_id, realm_id, creation_request_id, + catalog_revision, source_intake_operation_id, source_intake_request_id); + +-- Historical rows are intentionally permitted to retain all five nullable fields. Every new +-- launch, however, must be source-backed and revision-qualified at insertion time. +-- [jooq ignore start] +CREATE FUNCTION require_complete_canonical_launch_catalog_identity() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.original_start_session_tuple IS NULL + OR octet_length(NEW.original_start_session_tuple) NOT BETWEEN 1 AND 262144 + OR NEW.catalog_creation_request_id IS NULL + OR NEW.catalog_revision IS NULL + OR NEW.catalog_revision <= 0 + OR NEW.catalog_source_intake_operation_id IS NULL + OR NEW.catalog_source_intake_request_id IS NULL + OR NEW.catalog_source_intake_operation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.catalog_source_intake_request_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'New canonical instance launch requires the complete original tuple and exact catalog identity' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_canonical_instance_launch_catalog_identity'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_instance_launch_complete_catalog_identity + BEFORE INSERT ON game_session_canonical_instance_launch + FOR EACH ROW EXECUTE FUNCTION require_complete_canonical_launch_catalog_identity(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index 3394daab4d..f8af5c4830 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -265,22 +265,34 @@ private static void seedFreshTenantAssociation(DSLContext tx, RuntimeTarget targ } private static void seedStartingRuntimeAndLaunch(DSLContext tx, RuntimeTarget target) { + GameSessionCanonicalRealmCatalogProofFixtures.Proof catalogProof = + GameSessionCanonicalRealmCatalogProofFixtures.forRuntimeTarget(target); + GameSessionCanonicalInstanceLaunchProofFixtures.SyntheticLaunchProof launchProof = + GameSessionCanonicalInstanceLaunchProofFixtures.forRuntimeTarget( + target, catalogProof.source()); + var descriptor = launchProof.completeLaunchBindingEvidence().descriptor(); + tx.execute( "INSERT INTO game_instances" - + " (id, tenant_id, runtime_version, owner_account_id, status, row_version," + + " (id, tenant_id, runtime_version, owner_account_id, owner_account_uuid, status, row_version," + " game_instance_uuid, game_template_id, launch_descriptor_id, version_id," + " release_bundle_id, generation_config_revision, version_state_epoch," + " run_owned_start_request_id, run_owned_start_request_digest," + " run_owned_start_published_release_bundle_ref, run_owned_start_preparing_epoch," + " run_owned_start_active_epoch)" - + " VALUES (?, ?, 'fixture-runtime', 99, 'STARTING', 1, ?, 1, ?, 1, 1, ?, 1, ?, ?, ?, 1, 2)", + + " VALUES (?, ?, ?, NULL, ?, 'STARTING', 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)", target.gameInstanceId(), target.gameSessionTenantId(), + Long.toString(descriptor.versionId()), + launchProof.originalTuple().preAuthorizationTuple().action().target().ownerAccountId(), target.gameInstanceUuid(), + descriptor.gameTemplateId(), target.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), target.generationConfigRevision(), target.controlPlaneRequestId(), - RAW_SHA256, + launchProof.originalTuple().mutationDigest(), target.publishedReleaseBundleRef()); tx.execute( @@ -294,15 +306,11 @@ private static void seedStartingRuntimeAndLaunch(DSLContext tx, RuntimeTarget ta + " playable_state_namespace_id, playable_state_scope, public_production," + " captured_starting_row_version, game_template_id, launch_descriptor_id, version_id," + " release_bundle_id, generation_config_revision, version_state_epoch," - + " complete_launch_binding_evidence)" + + " complete_launch_binding_evidence, original_start_session_tuple," + + " catalog_creation_request_id, catalog_revision, catalog_source_intake_operation_id," + + " catalog_source_intake_request_id)" + " VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND'," - + " ?, ?, ?, ?, ?, 'SHARED', TRUE, 1, 1, ?, 1, 1, ?, 1," - + " jsonb_build_object('descriptor', jsonb_build_object('targetNamespace', ?," - + " 'controlPlaneRequestId', ?, 'canonicalTenantId', ?, 'worldSlug', ?," - + " 'gameTemplateId', '1', 'launchDescriptorId', ?, 'versionId', '1'," - + " 'releaseBundleId', '1', 'generationConfigRevision', ?, 'versionStateEpoch', '1'," - + " 'publishedReleaseBundleRef', ?), 'releaseAttestation'," - + " jsonb_build_object('canonicalVersionId', ?)))", + + " ?, ?, ?, ?, ?, 'SHARED', TRUE, 1, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?)", target.targetNamespace(), target.controlPlaneRequestId(), target.gameSessionTenantId(), @@ -319,16 +327,19 @@ private static void seedStartingRuntimeAndLaunch(DSLContext tx, RuntimeTarget ta target.realmId(), target.worldSlug(), target.playableStateNamespaceId(), - target.launchDescriptorId(), - target.generationConfigRevision(), - target.targetNamespace(), - target.controlPlaneRequestId(), - target.canonicalTenantId().toString(), - target.worldSlug(), - target.launchDescriptorId(), - target.generationConfigRevision(), - target.publishedReleaseBundleRef(), - target.canonicalVersionId().toString()); + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.generationConfigRevision(), + descriptor.versionStateEpoch(), + GameSessionCanonicalInstanceLaunchProofFixtures.completeLaunchBindingJson( + launchProof.completeLaunchBindingEvidence()), + launchProof.originalTuple().canonicalBytes(), + target.catalogCreationRequestId(), + target.catalogRevision(), + target.sourceIntakeOperationId(), + target.sourceIntakeRequestId()); } public record RuntimeTarget( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java new file mode 100644 index 0000000000..0731dc2fca --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java @@ -0,0 +1,486 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.Statement; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchProofFixtures.SyntheticLaunchProof; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository.CanonicalInstanceLaunch; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository.InvalidCanonicalInstanceLaunchException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.CanonicalRealmCatalog; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociation; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof of atomic original StartSession owner allocation and exact retained readback. + * Synthetic Account tuple, descriptor/release, and Game Design source/catalog values are storage + * inputs only; this suite proves neither authenticated producer transport nor current + * authorization. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalInstanceLaunchPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String NAMESPACE = "test"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void atomicallyCreatesStartingPairAndExactRetryKeepsAllocationAfterLifecycleAdvance() + throws Exception { + try (Fixture fixture = newFixture(null)) { + LaunchInputs inputs = prepareLaunch(fixture); + CanonicalInstanceLaunch created = + inputs + .repository() + .createStartingLaunch( + inputs.proof().originalTuple(), + inputs.proof().completeLaunchBindingEvidence(), + inputs.catalog()); + + assertThat(created.currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING); + assertThat(created.currentRowVersion()).isZero(); + assertThat(created.capturedStartingRowVersion()).isZero(); + assertThat(created.originalStartSessionTuple()) + .containsExactly(inputs.proof().originalTuple().canonicalBytes()); + assertThat(created.catalogRevision()).isEqualTo(inputs.catalog().catalogRevision()); + assertThat(created.catalogCreationRequestId()).isEqualTo(inputs.catalog().catalogRequestId()); + assertThat(created.catalogSourceIntakeOperationId()) + .isEqualTo(inputs.catalog().intakeOperationId()); + assertThat( + countByRequest( + fixture.dsl(), + "game_instances", + "run_owned_start_request_id", + created.controlPlaneRequestId())) + .isEqualTo(1L); + assertThat( + countByRequest( + fixture.dsl(), + "game_session_canonical_instance_launch", + "control_plane_request_id", + created.controlPlaneRequestId())) + .isEqualTo(1L); + + var independent = + inputs + .repository() + .readByLaunchIdentity( + selector(inputs.proof(), inputs.catalog(), created.gameInstanceUuid())) + .orElseThrow(); + assertThat(independent.gameInstanceUuid()).isEqualTo(created.gameInstanceUuid()); + assertThat(independent.catalogRevision()).isEqualTo(inputs.catalog().catalogRevision()); + assertThat(independent.launchBindingEvidence()) + .isEqualTo(inputs.proof().completeLaunchBindingEvidence()); + + assertThat( + fixture + .dsl() + .execute( + "UPDATE game_instances SET status = 'RUNNING', row_version = row_version + 1" + + " WHERE tenant_id = ? AND id = ?", + created.gameSessionTenantId(), + created.gameInstanceId())) + .isEqualTo(1); + CanonicalInstanceLaunch retry = + inputs + .repository() + .createStartingLaunch( + inputs.proof().originalTuple(), + inputs.proof().completeLaunchBindingEvidence(), + inputs.catalog()); + assertThat(retry.gameInstanceUuid()).isEqualTo(created.gameInstanceUuid()); + assertThat(retry.currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.RUNNING); + assertThat(retry.currentRowVersion()).isEqualTo(created.capturedStartingRowVersion() + 1L); + assertThat(retry.capturedStartingRowVersion()) + .isEqualTo(created.capturedStartingRowVersion()); + + var changedTuple = + GameSessionCanonicalInstanceLaunchProofFixtures.withAuditReason( + inputs.proof().originalTuple(), "substituted retry tuple"); + assertThatThrownBy( + () -> + inputs + .repository() + .createStartingLaunch( + changedTuple, + inputs.proof().completeLaunchBindingEvidence(), + inputs.catalog())) + .isInstanceOf(InvalidCanonicalInstanceLaunchException.class) + .hasMessageContaining("already bound to different complete launch evidence"); + assertThat( + countByRequest( + fixture.dsl(), + "game_instances", + "run_owned_start_request_id", + created.controlPlaneRequestId())) + .isEqualTo(1L); + } + } + + @Test + void rollsBackRuntimeAllocationWhenAtomicLaunchAssociationInsertFails() throws Exception { + try (Fixture fixture = newFixture(null)) { + LaunchInputs inputs = prepareLaunch(fixture); + fixture + .dsl() + .execute( + "ALTER TABLE game_session_canonical_instance_launch" + + " ADD CONSTRAINT chk_test_reject_canonical_launch CHECK (FALSE)"); + + assertThatThrownBy( + () -> + inputs + .repository() + .createStartingLaunch( + inputs.proof().originalTuple(), + inputs.proof().completeLaunchBindingEvidence(), + inputs.catalog())) + .isInstanceOf(RuntimeException.class); + assertThat( + countByRequest( + fixture.dsl(), + "game_instances", + "run_owned_start_request_id", + inputs.proof().originalTuple().controlPlaneRequestId())) + .isZero(); + assertThat( + countByRequest( + fixture.dsl(), + "game_session_canonical_instance_launch", + "control_plane_request_id", + inputs.proof().originalTuple().controlPlaneRequestId())) + .isZero(); + } + } + + @Test + void retainedV42LaunchWithoutCapturedTupleRemainsNullAndCannotBeUpgradedByRetry() + throws Exception { + try (Fixture fixture = newFixture(MigrationVersion.fromVersion("42"))) { + LaunchInputs inputs = prepareLaunch(fixture); + UUID retainedUuid = UUID.randomUUID(); + long retainedInstanceId = insertHistoricalV26Pair(fixture.dsl(), inputs, retainedUuid); + fixture.migrateLatest(); + + var currentCatalog = + fixture + .catalogRepository() + .readByCanonicalTenantId(inputs.catalog().canonicalTenantId()) + .orElseThrow(); + var repository = fixture.launchRepository(); + assertThatThrownBy( + () -> + repository.createStartingLaunch( + inputs.proof().originalTuple(), + inputs.proof().completeLaunchBindingEvidence(), + currentCatalog)) + .isInstanceOf(InvalidCanonicalInstanceLaunchException.class) + .hasMessageContaining("original_start_session_tuple"); + + Record retained = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT original_start_session_tuple IS NULL AS tuple_missing," + + " catalog_revision IS NULL AS revision_missing" + + " FROM game_session_canonical_instance_launch" + + " WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + inputs.proof().originalTuple().controlPlaneRequestId())); + assertThat(retained.get("tuple_missing", Boolean.class)).isTrue(); + assertThat(retained.get("revision_missing", Boolean.class)).isTrue(); + assertThat( + countByRequest( + fixture.dsl(), + "game_instances", + "run_owned_start_request_id", + inputs.proof().originalTuple().controlPlaneRequestId())) + .isEqualTo(1L); + assertThat(retainedInstanceId).isPositive(); + } + } + + private static LaunchInputs prepareLaunch(Fixture fixture) { + FreshTenantAssociation association = createFreshAssociation(fixture); + var catalogProof = + GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(association); + CanonicalRealmCatalog catalog = + fixture + .catalogRepository() + .establishFreshPublicRealm( + association, + catalogProof.source(), + catalogProof.publishedSet(), + UUID.randomUUID(), + UUID.randomUUID()); + String operationId = "original-start-session-" + UUID.randomUUID(); + long gameTemplateId = 91L; + String descriptorId = "launch-" + UUID.randomUUID(); + String releaseRef = "fixture-release/" + UUID.randomUUID(); + SyntheticLaunchProof proof = + GameSessionCanonicalInstanceLaunchProofFixtures.create( + NAMESPACE, + operationId, + association.canonicalTenantId(), + catalog.worldSlug(), + catalog.sourceEvidence(), + gameTemplateId, + 13L, + 17L, + descriptorId, + "generation-fixture", + 2L, + releaseRef); + return new LaunchInputs(catalog, proof, fixture.launchRepository()); + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector( + SyntheticLaunchProof proof, CanonicalRealmCatalog catalog, UUID gameInstanceUuid) { + var descriptor = proof.completeLaunchBindingEvidence().descriptor(); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + catalog.targetNamespace(), + catalog.canonicalTenantId(), + catalog.worldSlug(), + gameInstanceUuid, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + proof.completeLaunchBindingEvidence().releaseAttestation().evidenceDigest()); + } + + private static long insertHistoricalV26Pair( + DSLContext dsl, LaunchInputs inputs, UUID gameInstanceUuid) { + var tuple = inputs.proof().originalTuple(); + var descriptor = inputs.proof().completeLaunchBindingEvidence().descriptor(); + CanonicalRealmCatalog catalog = inputs.catalog(); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + Record runtime = + tx.fetchOne( + "INSERT INTO game_instances" + + " (tenant_id, runtime_version, owner_account_id, owner_account_uuid, status," + + " row_version, game_instance_uuid, game_template_id, launch_descriptor_id, version_id," + + " release_bundle_id, generation_config_revision, version_state_epoch," + + " run_owned_start_request_id, run_owned_start_request_digest," + + " run_owned_start_published_release_bundle_ref)" + + " VALUES (?, ?, NULL, ?, 'STARTING', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + catalog.gameSessionTenantId(), + Long.toString(descriptor.versionId()), + tuple.preAuthorizationTuple().action().target().ownerAccountId(), + gameInstanceUuid, + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.generationConfigRevision(), + descriptor.versionStateEpoch(), + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + descriptor.publishedReleaseBundleRef()); + long instanceId = Objects.requireNonNull(runtime).get("id", Long.class); + FreshTenantCreationEvidence fresh = catalog.associationSourceEvidence(); + var binding = + GameSessionCanonicalInstanceLaunchProofFixtures.completeLaunchBindingJson( + inputs.proof().completeLaunchBindingEvidence()); + tx.execute( + "INSERT INTO game_session_canonical_instance_launch" + + " (target_namespace, control_plane_request_id, game_session_tenant_id, canonical_tenant_id," + + " tenant_association_operation_id, tenant_association_request_id," + + " tenant_source_schema_version, tenant_source_target_namespace, tenant_source_request_id," + + " tenant_source_canonical_tenant_id, tenant_source_game_row_id, tenant_source_game_tenant_key," + + " tenant_source_provenance_kind, tenant_association_kind, game_instance_id, game_instance_uuid," + + " canonical_realm_id, world_slug, playable_state_namespace_id, playable_state_scope," + + " public_production, captured_starting_row_version, game_template_id, launch_descriptor_id," + + " version_id, release_bundle_id, generation_config_revision, version_state_epoch," + + " complete_launch_binding_evidence)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND'," + + " ?, ?, ?, ?, ?, 'SHARED', TRUE, 0, ?, ?, ?, ?, ?, ?, ?::jsonb)", + NAMESPACE, + tuple.controlPlaneRequestId(), + catalog.gameSessionTenantId(), + catalog.canonicalTenantId(), + catalog.tenantAssociationOperationId(), + fresh.creationRequestId(), + fresh.schemaVersion(), + fresh.targetNamespace(), + fresh.creationRequestId(), + fresh.canonicalTenantId(), + fresh.sourceGameRowId(), + fresh.sourceGameTenantKey(), + fresh.provenanceKind(), + instanceId, + gameInstanceUuid, + catalog.realmId(), + catalog.worldSlug(), + catalog.playableStateNamespaceId(), + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.generationConfigRevision(), + descriptor.versionStateEpoch(), + binding); + return instanceId; + }); + } + + private static FreshTenantAssociation createFreshAssociation(Fixture fixture) { + UUID requestId = UUID.randomUUID(); + UUID canonicalTenantId = UUID.randomUUID(); + FreshTenantCreationEvidence evidence = freshCreationEvidence(requestId, canonicalTenantId); + GameDesignFreshTenantCreationClient client = mock(GameDesignFreshTenantCreationClient.class); + when(client.resolveCreation(requestId, evidence.requestDigest())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return evidence; + }); + return fixture + .associationRepository(client) + .associateFreshTenant(requestId, evidence.requestDigest()); + } + + private static FreshTenantCreationEvidence freshCreationEvidence( + UUID creationRequestId, UUID canonicalTenantId) { + String sourceKey = "launch-owner-key-" + creationRequestId.toString().substring(0, 8); + long sourceRowId = Math.abs(creationRequestId.getMostSignificantBits() % 1_000_000L) + 1L; + UUID sourceOperationId = UUID.randomUUID(); + String requestDigest = + GameTenantCreationDigest.requestDigest( + NAMESPACE, creationRequestId, sourceKey, "Launch fixture game", null); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + creationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + creationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW")); + } + + private static long countByRequest( + DSLContext dsl, String table, String requestColumn, String requestId) { + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COUNT(*) AS row_count FROM " + table + " WHERE " + requestColumn + " = ?", + requestId)); + return Objects.requireNonNull(row.get("row_count", Long.class)); + } + + private static Fixture newFixture(MigrationVersion migrationVersion) { + String schema = "gs_canonical_launch_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(migrationVersion == null ? MigrationVersion.LATEST : migrationVersion) + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture(schema, dataSource, dsl, new DataSourceTransactionManager(dataSource)); + } + + private record LaunchInputs( + CanonicalRealmCatalog catalog, + SyntheticLaunchProof proof, + GameSessionCanonicalInstanceLaunchRepository repository) {} + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager transactionManager) + implements AutoCloseable { + GameSessionFreshTenantAssociationRepository associationRepository( + GameDesignFreshTenantCreationClient client) { + return new GameSessionFreshTenantAssociationRepository( + dsl, transactionManager, client, NAMESPACE); + } + + GameSessionCanonicalRealmCatalogRepository catalogRepository() { + return new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE); + } + + GameSessionCanonicalInstanceLaunchRepository launchRepository() { + return new GameSessionCanonicalInstanceLaunchRepository( + dsl, transactionManager, NAMESPACE, catalogRepository()); + } + + void migrateLatest() { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + @Override + public void close() throws Exception { + try (Connection connection = dataSource.getConnection(); + Statement statement = connection.createStatement()) { + statement.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchProofFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchProofFixtures.java new file mode 100644 index 0000000000..d8db1f8ead --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchProofFixtures.java @@ -0,0 +1,294 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; + +/** + * Structurally complete but synthetic StartSession and release values for Game Session storage + * tests. These values are test stipulations only; they do not prove authenticated Account or Game + * Design owner transport, current authorization, or publication provenance. + */ +final class GameSessionCanonicalInstanceLaunchProofFixtures { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID CONTROL_UI_TOKEN_ID = + UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String RAW_SHA256 = "d".repeat(64); + private static final String SHA256 = "sha256:" + RAW_SHA256; + + private GameSessionCanonicalInstanceLaunchProofFixtures() {} + + static SyntheticLaunchProof forRuntimeTarget( + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target, + AuthoredWorldSourceEvidence source) { + return create( + target.targetNamespace(), + target.controlPlaneRequestId(), + target.canonicalTenantId(), + target.worldSlug(), + source, + 1L, + 1L, + 1L, + target.launchDescriptorId(), + target.generationConfigRevision(), + 1L, + target.publishedReleaseBundleRef()); + } + + static SyntheticLaunchProof create( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + AuthoredWorldSourceEvidence source, + long gameTemplateId, + long versionId, + long releaseBundleId, + String launchDescriptorId, + String generationConfigRevision, + long versionStateEpoch, + String publishedReleaseBundleRef) { + var tuple = tuple(targetNamespace, controlPlaneRequestId, canonicalTenantId, gameTemplateId); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + source.operationId(), + source.evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + launchDescriptorId, + versionId, + false, + null, + "{}", + generationConfigRevision, + versionStateEpoch, + releaseBundleId, + publishedReleaseBundleRef, + false, + null); + String commitId = "synthetic-selected-release-commit"; + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + participantKey -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participantKey, + Long.toString(versionId), + false, + null, + commitId, + RAW_SHA256, + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey), + "GAME_LOGIC".equals(participantKey), + "GAME_LOGIC".equals(participantKey) ? SHA256 : null)) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + targetNamespace, + descriptor.resultDigest(), + canonicalTenantId, + UUID.randomUUID(), + worldSlug, + source.operationId(), + source.evidenceDigest(), + launchDescriptorId, + publishedReleaseBundleRef, + versionStateEpoch, + "synthetic-publish-workflow", + commitId, + participants, + SHA256, + 1, + List.of(), + List.of(), + List.of(), + generationConfigRevision); + return new SyntheticLaunchProof(tuple, new CompleteLaunchBindingEvidence(descriptor, release)); + } + + static UUID targetOwnerId() { + return TARGET_OWNER_ID; + } + + static StartSessionPostAuthorizationExecutionTuple withAuditReason( + StartSessionPostAuthorizationExecutionTuple original, String auditReason) { + var previous = original.preAuthorizationTuple(); + var previousAction = previous.action(); + var changedAction = + new StartSessionOperatorAction( + previousAction.actionFamilySchemaId(), + previousAction.actionFamilySchemaVersion(), + previousAction.scope(), + previousAction.target(), + previousAction.expectedVersion(), + previousAction.mutation(), + auditReason); + var changedPreTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + previous.controlPlaneRequestId(), previous.actor().accountId(), changedAction); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + changedPreTuple, + original.authenticatedWorkloadIdentity(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + bundle(changedPreTuple), + original.bundleReference()); + } + + static String completeLaunchBindingJson(CompleteLaunchBindingEvidence binding) { + try { + return JSON.writeValueAsString(binding); + } catch (IOException invalid) { + throw new IllegalStateException("Synthetic launch binding cannot be serialized", invalid); + } + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + long gameTemplateId) { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(canonicalTenantId, targetNamespace), + new StartSessionOperatorAction.Target(gameTemplateId, TARGET_OWNER_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "synthetic canonical launch storage fixture"); + var pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + controlPlaneRequestId, ACTOR_ID, action); + var reference = + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + targetNamespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + RESERVATION_OWNER_ID, + 19L, + bundle(pre), + reference); + } + + private static byte[] bundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = tuple.action().scope().tenantId().toString(); + String targetNamespace = tuple.action().scope().targetNamespace(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", targetNamespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + "2099-01-01T00:00:00Z", + "expiresAt", + "2099-01-01T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + ISSUANCE_OPERATION_ID.toString(), + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 2L, + "tenantAuthorityGeneration", + Map.of(tenantId, 3L), + "membershipAuthorityGeneration", + Map.of(tenantId, 4L), + "privateRealmGrantVersions", + List.of()), + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + CONTROL_UI_TOKEN_ID.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException("Synthetic Account bundle cannot be serialized", invalid); + } + } + + record SyntheticLaunchProof( + StartSessionPostAuthorizationExecutionTuple originalTuple, + CompleteLaunchBindingEvidence completeLaunchBindingEvidence) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepositoryTest.java new file mode 100644 index 0000000000..ce3b369c87 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepositoryTest.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionCanonicalInstanceLaunchRepositoryTest { + private static final String NAMESPACE = "test"; + + @AfterEach + void clearAmbientState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void rejectsInvalidNamespaceBeforeStorage() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var catalogs = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE); + + assertThatThrownBy( + () -> + new GameSessionCanonicalInstanceLaunchRepository( + dsl, transactionManager, "Not a DNS label", catalogs)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload namespace"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void refusesToCreateInsideAnExistingOwnerTransactionBeforeReadingInputs() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var catalogs = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE); + var repository = + new GameSessionCanonicalInstanceLaunchRepository( + dsl, transactionManager, NAMESPACE, catalogs); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.createStartingLaunch(null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent transaction"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void refusesToReadInsideAnExistingOwnerTransactionBeforeStorage() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var catalogs = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE); + var repository = + new GameSessionCanonicalInstanceLaunchRepository( + dsl, transactionManager, NAMESPACE, catalogs); + TransactionSynchronizationManager.setActualTransactionActive(true); + var request = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + NAMESPACE, + UUID.randomUUID(), + "world", + UUID.randomUUID(), + "operation", + "descriptor", + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + + assertThatThrownBy(() -> repository.readByLaunchIdentity(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent transaction"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void rejectsSelectorForAnotherNamespaceBeforeOpeningReadTransaction() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var catalogs = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE); + var repository = + new GameSessionCanonicalInstanceLaunchRepository( + dsl, transactionManager, NAMESPACE, catalogs); + var request = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + "other", + UUID.randomUUID(), + "world", + UUID.randomUUID(), + "operation", + "descriptor", + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + + assertThatThrownBy(() -> repository.readByLaunchIdentity(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from the configured"); + + verifyNoInteractions(dsl, transactionManager); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java index b762d920a0..ef4d654c1e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java @@ -60,4 +60,19 @@ void refusesToOpenTheOwnerBoundaryInsideAnExistingTransaction() { verifyNoInteractions(dsl, transactionManager); } + + @Test + void ownerTransactionCatalogReadRejectsMissingOwnerTransactionBeforeStorage() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var repository = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, "test"); + + assertThatThrownBy( + () -> repository.readByCanonicalTenantIdInOwnerTransaction(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires an active owner transaction"); + + verifyNoInteractions(dsl, transactionManager); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcServiceTest.java new file mode 100644 index 0000000000..0cc7a0dae4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcServiceTest.java @@ -0,0 +1,186 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameInstanceLaunchAssociationReadGrpcService; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic dispatch/denial proof; genuine owner and mTLS composition is a separate PG fixture. */ +class CanonicalGameInstanceLaunchAssociationReadGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + private final GameSessionCanonicalInstanceLaunchRepository repository = + mock(GameSessionCanonicalInstanceLaunchRepository.class); + private final CanonicalGameInstanceLaunchAssociationReadGrpcService service = + new CanonicalGameInstanceLaunchAssociationReadGrpcService(repository, NAMESPACE); + + @AfterEach + void clearAmbientState() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Test + void missingAuthenticatedPeerRejectsEvenMalformedInputBeforeStorage() { + var observer = new RecordingObserver(); + Context.ROOT.run( + () -> + service.getCanonicalGameInstanceLaunchAssociation( + GetCanonicalGameInstanceLaunchAssociationRequest.getDefaultInstance(), observer)); + assertDenied(observer, Status.Code.UNAUTHENTICATED); + verifyNoInteractions(repository); + } + + @Test + void wrongWorkloadAndNamespaceRejectBeforeDecodeOrStorage() { + for (var uri : + List.of( + "spiffe://firemud/ns/world-runtime/sa/account-service", + "spiffe://firemud/ns/other-runtime/sa/world-management-service")) { + assertDenied( + invoke(uri, GetCanonicalGameInstanceLaunchAssociationRequest.getDefaultInstance()), + Status.Code.PERMISSION_DENIED); + } + verifyNoInteractions(repository); + } + + @Test + void endUserContextCannotBorrowWorldWorkloadAuthorization() { + SessionContext.setContext("42", List.of("tenantAdmin"), Map.of()); + assertDenied(invokeWorld(wire()), Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void configuredOwnerNamespaceRejectsDifferentSelectorBeforeStorage() { + assertDenied( + invokeWorld(wire().toBuilder().setTargetNamespace("other-runtime").build()), + Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void malformedAndUnknownFieldsDenyBeforeStorage() { + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + for (var request : + List.of( + GetCanonicalGameInstanceLaunchAssociationRequest.getDefaultInstance(), + wire().toBuilder().setUnknownFields(unknown).build(), + wire().toBuilder().setGameInstanceUuid(new UUID(0L, 0L).toString()).build())) { + assertDenied(invokeWorld(request), Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(repository); + } + + @Test + void ambientTransactionCannotTurnReadIntoCallerOwnedExecution() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertDenied(invokeWorld(wire()), Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(repository); + } + + @Test + void absentAssociationIsNotSuccessOrInferredAbort() { + var expected = request(); + when(repository.readByLaunchIdentity(expected)).thenReturn(Optional.empty()); + assertDenied(invokeWorld(wire()), Status.Code.FAILED_PRECONDITION); + verify(repository).readByLaunchIdentity(expected); + verifyNoMoreInteractions(repository); + } + + @Test + void unavailableOwnerCannotManufactureHistoricalEvidence() { + var expected = request(); + when(repository.readByLaunchIdentity(expected)) + .thenThrow(new DataAccessException("test-only unavailable storage")); + assertDenied(invokeWorld(wire()), Status.Code.UNAVAILABLE); + verify(repository).readByLaunchIdentity(expected); + verifyNoMoreInteractions(repository); + } + + private RecordingObserver invokeWorld(GetCanonicalGameInstanceLaunchAssociationRequest wire) { + return invoke("spiffe://firemud/ns/world-runtime/sa/world-management-service", wire); + } + + private RecordingObserver invoke( + String uri, GetCanonicalGameInstanceLaunchAssociationRequest wire) { + var observer = new RecordingObserver(); + var peer = GrpcPeerIdentity.parseUri(uri).orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> service.getCanonicalGameInstanceLaunchAssociation(wire, observer)); + return observer; + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request request() { + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("01111111-1111-4111-8111-111111111111"), + NAMESPACE, + UUID.fromString("02222222-2222-4222-8222-222222222222"), + "world", + UUID.fromString("03333333-3333-4333-8333-333333333333"), + "test-original-operation", + "test-original-descriptor", + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + } + + private static GetCanonicalGameInstanceLaunchAssociationRequest wire() { + return CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toRequest(request()); + } + + private static void assertDenied(RecordingObserver observer, Status.Code status) { + assertThat(observer.response).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(observer.error).isNotNull(); + assertThat(observer.error).isEqualTo(status); + } + + private static final class RecordingObserver + implements StreamObserver { + private GetCanonicalGameInstanceLaunchAssociationResponse response; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(GetCanonicalGameInstanceLaunchAssociationResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepository.java index a2a4fbcd50..b983ececdf 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepository.java @@ -286,6 +286,8 @@ private HoldIdentity verifyStoredIdentity( || !request.playableStateNamespaceId().equals(canonical.playableStateNamespaceId()) || !request.playableStateScope().equals(canonical.playableStateScope()) || !request.canonicalGameInstanceId().equals(canonical.canonicalGameInstanceId()) + || !request.realmId().equals(canonical.canonicalRealmId()) + || request.expectedCatalogRevision() != canonical.catalogRevision() || !request.canonicalVersionId().equals(association.canonicalVersionId()) || required(row, "tenant_id", Long.class) != privateKeys.privateTenantKey() || required(row, "game_instance_id", Long.class) != privateKeys.privateGameInstanceKey() diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java index 4653f3b887..e8fa2b1abb 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java @@ -560,6 +560,8 @@ private static boolean associationMatchesRequest( && request.playableStateNamespaceId().equals(identity.playableStateNamespaceId()) && request.playableStateScope().equals(identity.playableStateScope()) && request.canonicalGameInstanceId().equals(identity.canonicalGameInstanceId()) + && request.realmId().equals(identity.canonicalRealmId()) + && request.expectedCatalogRevision() == identity.catalogRevision() && request.canonicalVersionId().equals(association.canonicalVersionId()); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java index 26a18707dd..c36825fd80 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociation.java @@ -62,6 +62,8 @@ public record CanonicalIdentity( UUID playableStateNamespaceId, String playableStateScope, boolean publicProduction, + UUID canonicalRealmId, + long catalogRevision, String controlPlaneRequestId) { public CanonicalIdentity { requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); @@ -72,6 +74,8 @@ public record CanonicalIdentity( Objects.requireNonNull(worldSlug, "worldSlug"); AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireNonNil(canonicalRealmId, "canonicalRealmId"); + requirePositive(catalogRevision, "catalogRevision"); if (!"SHARED".equals(playableStateScope)) { throw new IllegalArgumentException( "This association slice accepts SHARED only; ISOLATED/playtest identity requires the missing lifecycle/generation carrier"); @@ -135,6 +139,8 @@ public record GameSessionReadEvidence( UUID playableStateNamespaceId, String playableStateScope, boolean publicProduction, + UUID canonicalRealmId, + long catalogRevision, String currentGameSessionStatus, long currentGameSessionRowVersion, AuthoredWorldLaunchDescriptorEvidence descriptor, @@ -144,6 +150,8 @@ public record GameSessionReadEvidence( AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireNonNil(canonicalRealmId, "canonicalRealmId"); + requirePositive(catalogRevision, "catalogRevision"); requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); requireText(launchDescriptorId, "launchDescriptorId", 64); requireDigest(descriptorRequestDigest, "descriptorRequestDigest"); @@ -185,6 +193,8 @@ public CanonicalIdentity canonicalIdentity() { playableStateNamespaceId, playableStateScope, publicProduction, + canonicalRealmId, + catalogRevision, controlPlaneRequestId); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java index d34748d9c6..b57b5f0e5b 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java @@ -52,6 +52,8 @@ public final class WorldCanonicalInstanceAssociationRepository { private static final Field PLAYABLE_STATE_SCOPE = field("playable_state_scope", String.class); private static final Field PUBLIC_PRODUCTION = field("public_production", Boolean.class); + private static final Field CANONICAL_REALM_ID = field("canonical_realm_id", UUID.class); + private static final Field CATALOG_REVISION = field("catalog_revision", Long.class); private static final Field PLAYTEST_LIFECYCLE_ID = field("playtest_lifecycle_id", UUID.class); private static final Field PLAYTEST_STATE_GENERATION = @@ -135,6 +137,10 @@ public final class WorldCanonicalInstanceAssociationRepository { field("playable_state_scope", String.class); private static final Field INSTANCE_PUBLIC_PRODUCTION = field("public_production", Boolean.class); + private static final Field INSTANCE_CANONICAL_REALM_ID = + field("canonical_realm_id", UUID.class); + private static final Field INSTANCE_CATALOG_REVISION = + field("catalog_revision", Long.class); private static final Field INSTANCE_PLAYTEST_LIFECYCLE_ID = field("playtest_lifecycle_id", UUID.class); private static final Field INSTANCE_PLAYTEST_STATE_GENERATION = @@ -294,7 +300,7 @@ public void retainClaimInOwnerTransaction(WorldCanonicalInstanceAssociation.Clai int inserted = dsl.insertInto(ASSOCIATION) - .set(SCHEMA_VERSION, (short) 1) + .set(SCHEMA_VERSION, (short) 2) .set(CANONICAL_GAME_INSTANCE_ID, claim.canonicalGameInstanceId()) .set(CANONICAL_TARGET_NAMESPACE, claim.targetNamespace()) .set(CANONICAL_TENANT_ID, claim.canonicalTenantId()) @@ -302,6 +308,8 @@ public void retainClaimInOwnerTransaction(WorldCanonicalInstanceAssociation.Clai .set(PLAYABLE_STATE_NAMESPACE_ID, claim.playableStateNamespaceId()) .set(PLAYABLE_STATE_SCOPE, claim.playableStateScope()) .set(PUBLIC_PRODUCTION, claim.identity().publicProduction()) + .set(CANONICAL_REALM_ID, claim.identity().canonicalRealmId()) + .set(CATALOG_REVISION, claim.identity().catalogRevision()) .set(PLAYTEST_LIFECYCLE_ID, (UUID) null) .set(PLAYTEST_STATE_GENERATION, (Long) null) .set(CONTROL_PLANE_REQUEST_ID, claim.controlPlaneRequestId()) @@ -405,9 +413,9 @@ private WorldCanonicalInstanceAssociation toAssociation( Record row, boolean inOwnerSnapshot, boolean inActivationTransaction) { try { short schemaVersion = required(row, SCHEMA_VERSION); - if (schemaVersion != 1) { + if (schemaVersion != 2) { throw new IllegalArgumentException( - "Unsupported World canonical instance association schema"); + "Historical World canonical instance association lacks launch-captured catalog identity"); } String namespace = required(row, CANONICAL_TARGET_NAMESPACE); UUID tenantId = required(row, CANONICAL_TENANT_ID); @@ -469,6 +477,8 @@ private WorldCanonicalInstanceAssociation toAssociation( required(row, PLAYABLE_STATE_NAMESPACE_ID), required(row, PLAYABLE_STATE_SCOPE), required(row, PUBLIC_PRODUCTION), + required(row, CANONICAL_REALM_ID), + required(row, CATALOG_REVISION), controlRequestId); if (row.get(PLAYTEST_LIFECYCLE_ID) != null || row.get(PLAYTEST_STATE_GENERATION) != null) { throw new InvalidAssociationEvidenceException( @@ -671,7 +681,7 @@ private static void requireStoredAssociationColumns( var source = completeLaunchBinding.sourceIntakeReceipt(); var descriptor = completeLaunchBinding.descriptor(); var release = completeLaunchBinding.evidence().releaseAttestation(); - if (required(row, SCHEMA_VERSION) != 1 + if (required(row, SCHEMA_VERSION) != 2 || !Objects.equals( required(row, CANONICAL_GAME_INSTANCE_ID), identity.canonicalGameInstanceId()) || !Objects.equals(required(row, CANONICAL_TARGET_NAMESPACE), identity.targetNamespace()) @@ -681,6 +691,8 @@ private static void requireStoredAssociationColumns( required(row, PLAYABLE_STATE_NAMESPACE_ID), identity.playableStateNamespaceId()) || !Objects.equals(required(row, PLAYABLE_STATE_SCOPE), identity.playableStateScope()) || !Objects.equals(required(row, PUBLIC_PRODUCTION), identity.publicProduction()) + || !Objects.equals(required(row, CANONICAL_REALM_ID), identity.canonicalRealmId()) + || !Objects.equals(required(row, CATALOG_REVISION), identity.catalogRevision()) || row.get(PLAYTEST_LIFECYCLE_ID) != null || row.get(PLAYTEST_STATE_GENERATION) != null || !Objects.equals( @@ -739,6 +751,8 @@ private void requireInsertBornIdentity( row.get(INSTANCE_PLAYABLE_STATE_NAMESPACE_ID), identity.playableStateNamespaceId()) || !Objects.equals(row.get(INSTANCE_PLAYABLE_STATE_SCOPE), identity.playableStateScope()) || !Objects.equals(row.get(INSTANCE_PUBLIC_PRODUCTION), identity.publicProduction()) + || !Objects.equals(row.get(INSTANCE_CANONICAL_REALM_ID), identity.canonicalRealmId()) + || !Objects.equals(row.get(INSTANCE_CATALOG_REVISION), identity.catalogRevision()) || row.get(INSTANCE_PLAYTEST_LIFECYCLE_ID) != null || row.get(INSTANCE_PLAYTEST_STATE_GENERATION) != null || !Objects.equals( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index 2fbc403946..bcb35b6438 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -43,7 +43,7 @@ * admission permission. */ public final class WorldCanonicalInstanceLifecycleReadRepository { - private static final Set INPUT_FIELDS = + private static final Set INPUT_FIELDS_WITHOUT_START_LOCATION = Set.of( "schemaVersion", "identity", @@ -52,8 +52,12 @@ public final class WorldCanonicalInstanceLifecycleReadRepository { "launchBinding", "versionIdentity", "sourceIntake", - "topology", - "worldStartLocationEvidenceBase64"); + "topology"); + private static final Set INPUT_FIELDS_WITH_START_LOCATION = + java.util.stream.Stream.concat( + INPUT_FIELDS_WITHOUT_START_LOCATION.stream(), + java.util.stream.Stream.of("worldStartLocationEvidenceBase64")) + .collect(java.util.stream.Collectors.toUnmodifiableSet()); private static final JsonMapper CLOSED_JSON = JsonMapper.builder() .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) @@ -248,6 +252,8 @@ private void requireInputIdentity( identity, "playableStateNamespaceId", request.playableStateNamespaceId().toString()); requireText(identity, "playableStateScope", request.playableStateScope()); requireBoolean(identity, "publicProduction", request.publicProduction()); + requireText(identity, "canonicalRealmId", association.identity().canonicalRealmId().toString()); + requireInteger(identity, "catalogRevision", association.identity().catalogRevision()); requireText(identity, "controlPlaneRequestId", request.controlPlaneRequestId()); JsonNode gsRequest = requiredObject(input, "gameSessionReadRequest"); @@ -278,6 +284,9 @@ private void requireInputIdentity( gsEvidence, "playableStateNamespaceId", request.playableStateNamespaceId().toString()); requireText(gsEvidence, "playableStateScope", request.playableStateScope()); requireBoolean(gsEvidence, "publicProduction", request.publicProduction()); + requireText( + gsEvidence, "canonicalRealmId", association.identity().canonicalRealmId().toString()); + requireInteger(gsEvidence, "catalogRevision", association.identity().catalogRevision()); requireText(gsEvidence, "descriptorRequestDigest", request.expectedDescriptorRequestDigest()); requireText(gsEvidence, "descriptorResultDigest", request.expectedDescriptorResultDigest()); requireText( @@ -730,6 +739,11 @@ private Record readLifecycleRow( || !request .playableStateNamespaceId() .equals(required(row, "playable_state_namespace_id", UUID.class)) + || !association + .identity() + .canonicalRealmId() + .equals(required(row, "canonical_realm_id", UUID.class)) + || association.identity().catalogRevision() != required(row, "catalog_revision", Long.class) || !request.playableStateScope().equals(required(row, "playable_state_scope", String.class)) || request.publicProduction() != required(row, "public_production", Boolean.class) || !request @@ -778,9 +792,22 @@ private static boolean matchesRequest( private static JsonNode parseInput(String inputJson) { try { JsonNode input = CLOSED_JSON.readTree(inputJson); - requireFields(input, INPUT_FIELDS, "Retained World preparation input"); - if (intValue(input, "schemaVersion") != 2) { - throw invalid("Receipt-less retained V1 preparation cannot produce lifecycle evidence"); + if (input == null || !input.isObject()) { + throw invalid("Retained World preparation input must be an object"); + } + int schemaVersion = intValue(input, "schemaVersion"); + if (schemaVersion != 3 && schemaVersion != 4) { + throw invalid( + "Historical preparation input without launch-captured catalog identity cannot produce lifecycle evidence"); + } + requireFields( + input, + schemaVersion == 4 + ? INPUT_FIELDS_WITH_START_LOCATION + : INPUT_FIELDS_WITHOUT_START_LOCATION, + "Retained World preparation input"); + if (schemaVersion == 3 && input.has("worldStartLocationEvidenceBase64")) { + throw invalid("Schema-3 preparation cannot contain start-location evidence"); } if (!CLOSED_JSON.writeValueAsString(input).equals(inputJson)) { throw invalid("Retained World preparation input is not in its original closed form"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java index bd3bebf787..3c6a883d52 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java @@ -333,10 +333,10 @@ static RetainedPreparation parse(String preparationInputJson) { throw denied("Exact retained World preparation input must be an object"); } int schemaVersion = Math.toIntExact(number(root, "schemaVersion", true)); - if (schemaVersion != 1 && schemaVersion != 2) { + if (schemaVersion < 1 || schemaVersion > 4) { throw denied("Unsupported retained World preparation input schema"); } - if (schemaVersion == 1) { + if (schemaVersion == 1 || schemaVersion == 3) { fields( root, "root", @@ -363,7 +363,7 @@ static RetainedPreparation parse(String preparationInputJson) { "worldStartLocationEvidenceBase64"); } String selector = null; - if (schemaVersion == 2) { + if (schemaVersion == 2 || schemaVersion == 4) { if (root.size() != 9 || !root.has("worldStartLocationEvidenceBase64")) { throw denied("Schema-2 World preparation input requires its start-location evidence"); } @@ -378,21 +378,39 @@ static RetainedPreparation parse(String preparationInputJson) { throw denied("Retained World start-location evidence is malformed", malformed); } } else if (root.size() != 8) { - throw denied("Schema-1 World preparation input has an unsupported root shape"); + throw denied("World preparation input has an unsupported root shape"); } JsonNode identity = root.get("identity"); - fields( - identity, - "identity", - "canonicalGameInstanceId", - "targetNamespace", - "canonicalTenantId", - "worldSlug", - "playableStateNamespaceId", - "playableStateScope", - "publicProduction", - "controlPlaneRequestId"); + if (schemaVersion <= 2) { + fields( + identity, + "identity", + "canonicalGameInstanceId", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "playableStateNamespaceId", + "playableStateScope", + "publicProduction", + "controlPlaneRequestId"); + } else { + fields( + identity, + "identity", + "canonicalGameInstanceId", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "playableStateNamespaceId", + "playableStateScope", + "publicProduction", + "canonicalRealmId", + "catalogRevision", + "controlPlaneRequestId"); + uuid(identity, "canonicalRealmId"); + number(identity, "catalogRevision", true); + } uuid(identity, "canonicalGameInstanceId"); uuid(identity, "canonicalTenantId"); uuid(identity, "playableStateNamespaceId"); @@ -416,23 +434,47 @@ static RetainedPreparation parse(String preparationInputJson) { "expectedDescriptorResultDigest", "expectedReleaseAttestationEvidenceDigest"); JsonNode evidence = root.get("gameSessionReadEvidence"); - fields( - evidence, - "gameSessionReadEvidence", - "targetNamespace", - "canonicalTenantId", - "worldSlug", - "canonicalGameInstanceId", - "controlPlaneRequestId", - "launchDescriptorId", - "descriptorRequestDigest", - "descriptorResultDigest", - "releaseAttestationEvidenceDigest", - "playableStateNamespaceId", - "playableStateScope", - "publicProduction", - "descriptorJson", - "releaseAttestationJson"); + if (schemaVersion <= 2) { + fields( + evidence, + "gameSessionReadEvidence", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "canonicalGameInstanceId", + "controlPlaneRequestId", + "launchDescriptorId", + "descriptorRequestDigest", + "descriptorResultDigest", + "releaseAttestationEvidenceDigest", + "playableStateNamespaceId", + "playableStateScope", + "publicProduction", + "descriptorJson", + "releaseAttestationJson"); + } else { + fields( + evidence, + "gameSessionReadEvidence", + "targetNamespace", + "canonicalTenantId", + "worldSlug", + "canonicalGameInstanceId", + "controlPlaneRequestId", + "launchDescriptorId", + "descriptorRequestDigest", + "descriptorResultDigest", + "releaseAttestationEvidenceDigest", + "playableStateNamespaceId", + "playableStateScope", + "publicProduction", + "canonicalRealmId", + "catalogRevision", + "descriptorJson", + "releaseAttestationJson"); + uuid(evidence, "canonicalRealmId"); + number(evidence, "catalogRevision", true); + } for (String field : new String[] {"canonicalTenantId", "canonicalGameInstanceId"}) { uuid(request, field); uuid(evidence, field); @@ -744,6 +786,14 @@ void requireCrossOwnerReadSelectors() { != bool(gameSessionReadEvidence, "publicProduction")) { throw denied("Retained World state namespace differs from Game Session evidence"); } + if (schemaVersion >= 3 + && (!uuid(this.identity, "canonicalRealmId") + .equals(uuid(gameSessionReadEvidence, "canonicalRealmId")) + || number(this.identity, "catalogRevision", true) + != number(gameSessionReadEvidence, "catalogRevision", true))) { + throw denied( + "Retained World launch-captured catalog identity differs between identity and Game Session evidence"); + } if (number(launchBinding, "schemaVersion", true) != 1L || number(versionIdentity, "schemaVersion", true) != 1L diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java index 6ace8ac482..e019c56565 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java @@ -282,6 +282,8 @@ static WorldCanonicalInstanceAssociation.GameSessionReadEvidence associationToWo result.playableStateNamespaceId(), result.playableStateScope().name(), result.publicProduction(), + result.canonicalRealmId(), + result.catalogRevision(), result.currentGameInstanceStatus().name(), result.currentRowVersion(), pair.descriptor(), diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java index 3bb2913d10..eb1b16ab49 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -1018,7 +1018,7 @@ static String inputJson(Input input) { Map root = object( "schemaVersion", - launch.evidence().releaseAttestation().worldStartLocationEvidence() == null ? 1 : 2, + launch.evidence().releaseAttestation().worldStartLocationEvidence() == null ? 3 : 4, "identity", object( "canonicalGameInstanceId", evidence.canonicalGameInstanceId().toString(), @@ -1028,6 +1028,8 @@ static String inputJson(Input input) { "playableStateNamespaceId", evidence.playableStateNamespaceId().toString(), "playableStateScope", evidence.playableStateScope(), "publicProduction", evidence.publicProduction(), + "canonicalRealmId", evidence.canonicalRealmId().toString(), + "catalogRevision", evidence.catalogRevision(), "controlPlaneRequestId", evidence.controlPlaneRequestId()), "gameSessionReadRequest", object( @@ -1055,6 +1057,8 @@ static String inputJson(Input input) { "playableStateNamespaceId", evidence.playableStateNamespaceId().toString(), "playableStateScope", evidence.playableStateScope(), "publicProduction", evidence.publicProduction(), + "canonicalRealmId", evidence.canonicalRealmId().toString(), + "catalogRevision", evidence.catalogRevision(), "descriptorJson", evidenceJson(evidence.descriptor()), "releaseAttestationJson", evidenceJson(evidence.releaseAttestation())), "launchBinding", diff --git a/services/world-management-service/src/main/resources/db/migration/V64__world_launch_captured_catalog_identity.sql b/services/world-management-service/src/main/resources/db/migration/V64__world_launch_captured_catalog_identity.sql new file mode 100644 index 0000000000..2d88138426 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V64__world_launch_captured_catalog_identity.sql @@ -0,0 +1,280 @@ +-- Retain the exact Game Session launch-captured realm/catalog tuple. Historical World rows and +-- original preparation bytes remain unchanged; only new canonical associations/preparations can +-- carry this complete identity. +ALTER TABLE world_instance + ADD COLUMN canonical_realm_id UUID, + ADD COLUMN catalog_revision BIGINT, + ADD CONSTRAINT ck_world_instance_launch_catalog_identity CHECK ( + (canonical_realm_id IS NULL AND catalog_revision IS NULL) + OR (canonical_realm_id IS NOT NULL + AND canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_revision IS NOT NULL + AND catalog_revision > 0) + ); + +ALTER TABLE world_instance + ADD CONSTRAINT uq_world_instance_canonical_catalog_association_fk + UNIQUE ( + id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id, + canonical_realm_id, + catalog_revision + ); + +ALTER TABLE world_canonical_instance_association + ADD COLUMN canonical_realm_id UUID, + ADD COLUMN catalog_revision BIGINT; + +ALTER TABLE world_canonical_instance_association + DROP CONSTRAINT ck_world_canonical_instance_association_schema; + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT ck_world_canonical_instance_association_schema CHECK ( + (schema_version = 1 AND canonical_realm_id IS NULL AND catalog_revision IS NULL) + OR (schema_version = 2 + AND canonical_realm_id IS NOT NULL + AND canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_revision IS NOT NULL + AND catalog_revision > 0) + ); + +ALTER TABLE world_canonical_instance_association + ADD CONSTRAINT fk_world_canonical_instance_association_catalog_world_row + FOREIGN KEY ( + world_instance_id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id, + canonical_realm_id, + catalog_revision + ) REFERENCES world_instance ( + id, + canonical_game_instance_id, + canonical_target_namespace, + canonical_tenant_id, + canonical_world_slug, + playable_state_namespace_id, + playable_state_scope, + public_production, + control_plane_request_id, + canonical_launch_binding_operation_id, + canonical_realm_id, + catalog_revision + ) ON DELETE RESTRICT; + +-- Keep V34 insert-born immutability, while allowing old retained rows to stay NULL and requiring +-- the complete captured pair on every new canonical World instance insert. +-- [jooq ignore start] +DO $migration$ +DECLARE + original TEXT; + null_identity_anchor TEXT := $anchor$ OR NEW.canonical_launch_binding_operation_id IS NOT NULL THEN$anchor$; + immutable_anchor TEXT := $anchor$ OR OLD.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id THEN$anchor$; + insert_anchor TEXT := $anchor$ IF NEW.canonical_game_instance_id IS NULL THEN + RETURN NEW; + END IF;$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_validate_canonical_prepare_identity()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,null_identity_anchor,'')))/length(null_identity_anchor) <> 1 + OR (length(original)-length(replace(original,immutable_anchor,'')))/length(immutable_anchor) <> 1 + OR (length(original)-length(replace(original,insert_anchor,'')))/length(insert_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V34 canonical World identity trigger anchor'; + END IF; + original := replace(original, + null_identity_anchor, + $replacement$ OR NEW.canonical_launch_binding_operation_id IS NOT NULL + OR NEW.canonical_realm_id IS NOT NULL + OR NEW.catalog_revision IS NOT NULL THEN$replacement$); + original := replace(original, + immutable_anchor, + $replacement$ OR OLD.canonical_launch_binding_operation_id + IS DISTINCT FROM NEW.canonical_launch_binding_operation_id + OR OLD.canonical_realm_id IS DISTINCT FROM NEW.canonical_realm_id + OR OLD.catalog_revision IS DISTINCT FROM NEW.catalog_revision THEN$replacement$); + original := replace(original, + insert_anchor, + $replacement$ IF NEW.canonical_game_instance_id IS NULL THEN + RETURN NEW; + END IF; + IF NEW.canonical_realm_id IS NULL + OR NEW.canonical_realm_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.catalog_revision IS NULL + OR NEW.catalog_revision <= 0 THEN + RAISE EXCEPTION 'New canonical World instance requires launch-captured realm and catalog revision' + USING ERRCODE = '23514'; + END IF;$replacement$); + EXECUTE original; +END; +$migration$; + +-- Association schema 1 remains historical and incomplete; all new association inserts use schema 2 +-- and must exactly match the catalog identity on their insert-born World row. +DO $migration$ +DECLARE + original TEXT; + begin_anchor TEXT := $anchor$BEGIN + SELECT * INTO instance FROM world_instance WHERE id = NEW.world_instance_id FOR KEY SHARE;$anchor$; + equality_anchor TEXT := $anchor$ OR instance.public_production IS DISTINCT FROM NEW.public_production$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_validate_canonical_instance_association()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,begin_anchor,'')))/length(begin_anchor) <> 1 + OR (length(original)-length(replace(original,equality_anchor,'')))/length(equality_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V34 canonical association trigger anchor'; + END IF; + original := replace(original, + begin_anchor, + $replacement$BEGIN + IF NEW.schema_version IS DISTINCT FROM 2 + OR NEW.canonical_realm_id IS NULL + OR NEW.canonical_realm_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.catalog_revision IS NULL + OR NEW.catalog_revision <= 0 THEN + RAISE EXCEPTION 'New canonical World association requires complete launch-captured catalog identity' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO instance FROM world_instance WHERE id = NEW.world_instance_id FOR KEY SHARE;$replacement$); + original := replace(original, + equality_anchor, + $replacement$ OR instance.public_production IS DISTINCT FROM NEW.public_production + OR instance.canonical_realm_id IS DISTINCT FROM NEW.canonical_realm_id + OR instance.catalog_revision IS DISTINCT FROM NEW.catalog_revision$replacement$); + EXECUTE original; +END; +$migration$; + +-- Keep V62's protected execution wrapper intact. Widen only its private V61 implementation, which +-- retains the V35/V40/V42/V61 owner guards, plus the selector verifier they call. +DO $migration$ +DECLARE + original TEXT; + schema_anchor TEXT := $anchor$ IF p->>'schemaVersion' IS NULL OR p->>'schemaVersion' NOT IN ('1','2') THEN$anchor$; + identity_anchor TEXT := $anchor$ OR ident->>'publicProduction' IS DISTINCT FROM gs_evidence->>'publicProduction'$anchor$; + row_anchor TEXT := $anchor$ 'canonical_launch_binding_operation_id', binding_row.binding_operation_id));$anchor$; + retry_anchor TEXT := $anchor$ IF p->>'schemaVersion' = '2' AND NOT EXISTS ($anchor$; + release_profile_anchor TEXT := $anchor$ AND binding_row.release_attestation_json::JSONB->>'schemaVersion' IN ('2', '3') + AND participant->>'digestSchemaVersion' = CASE + binding_row.release_attestation_json::JSONB->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' ELSE NULL END + AND binding_row.release_attestation_json::JSONB->'worldStartLocationEvidence'->'request'->>'digestSchemaVersion' + = capture_row.freeze_request_json::JSONB->>'digestSchemaVersion'$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_prepare_canonical_instance_v61_impl(text,text)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,schema_anchor,'')))/length(schema_anchor) <> 1 + OR (length(original)-length(replace(original,identity_anchor,'')))/length(identity_anchor) <> 1 + OR (length(original)-length(replace(original,row_anchor,'')))/length(row_anchor) <> 1 + OR (length(original)-length(replace(original,retry_anchor,'')))/length(retry_anchor) <> 1 + OR (length(original)-length(replace(original,release_profile_anchor,'')))/length(release_profile_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V61 implementation preparation guard anchor'; + END IF; + original := replace(original,schema_anchor, + $replacement$ IF p->>'schemaVersion' IS NULL OR p->>'schemaVersion' NOT IN ('3','4') THEN$replacement$); + original := replace(original,identity_anchor, + $replacement$ OR ident->>'publicProduction' IS DISTINCT FROM gs_evidence->>'publicProduction' + OR ident->>'canonicalRealmId' IS NULL + OR ident->>'canonicalRealmId' IS DISTINCT FROM gs_evidence->>'canonicalRealmId' + OR (ident->>'canonicalRealmId')::UUID = '00000000-0000-0000-0000-000000000000'::UUID + OR ident->>'canonicalRealmId' IS DISTINCT FROM (ident->>'canonicalRealmId')::UUID::TEXT + OR jsonb_typeof(ident->'catalogRevision') IS DISTINCT FROM 'number' + OR ident->>'catalogRevision' !~ '^[1-9][0-9]*$' + OR ident->>'catalogRevision' IS DISTINCT FROM gs_evidence->>'catalogRevision'$replacement$); + original := replace(original,row_anchor, + $replacement$ 'canonical_launch_binding_operation_id', binding_row.binding_operation_id, + 'canonical_realm_id', (ident->>'canonicalRealmId')::UUID, + 'catalog_revision', (ident->>'catalogRevision')::BIGINT));$replacement$); + original := replace(original,retry_anchor, + $replacement$ IF p->>'schemaVersion' = '4' AND NOT EXISTS ($replacement$); + original := replace(original,release_profile_anchor, + $replacement$ AND binding_row.release_attestation_json::JSONB->>'schemaVersion' IN ('2', '3', '4') + AND participant->>'digestSchemaVersion' = CASE + binding_row.release_attestation_json::JSONB->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' WHEN '4' THEN '4' ELSE NULL END + AND binding_row.release_attestation_json::JSONB->'worldStartLocationEvidence'->'request'->>'digestSchemaVersion' + = capture_row.freeze_request_json::JSONB->>'digestSchemaVersion'$replacement$); + EXECUTE original; +END; +$migration$; + +-- Preserve the V61 retained schema-2/3 selector semantics and add the accepted selected-full +-- schema-4 attestation with its exact World/4 selector. Historical preparation v1/v2 remain inert. +DO $migration$ +DECLARE + original TEXT; + no_location_anchor TEXT := $anchor$ IF input->>'schemaVersion' = '1' THEN$anchor$; + with_location_anchor TEXT := $anchor$ IF input->>'schemaVersion' IS DISTINCT FROM '2' + OR binding->>'schemaVersion' IS NULL + OR binding->>'schemaVersion' NOT IN ('2', '3') + OR input->>'worldStartLocationEvidenceBase64' IS NULL$anchor$; + selector_digest_anchor TEXT := $anchor$ OR selected->>'digestSchemaVersion' IS DISTINCT FROM (CASE binding->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' ELSE NULL END)$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_require_preparation_start_location(jsonb,jsonb,uuid)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,no_location_anchor,'')))/length(no_location_anchor) <> 1 + OR (length(original)-length(replace(original,with_location_anchor,'')))/length(with_location_anchor) <> 1 + OR (length(original)-length(replace(original,selector_digest_anchor,'')))/length(selector_digest_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V42 preparation selector schema anchor'; + END IF; + original := replace(original,no_location_anchor, + $replacement$ IF input->>'schemaVersion' = '3' THEN$replacement$); + original := replace(original, + with_location_anchor, + $replacement$ IF input->>'schemaVersion' IS DISTINCT FROM '4' + OR binding->>'schemaVersion' IS NULL + OR binding->>'schemaVersion' NOT IN ('2', '3', '4') + OR input->>'worldStartLocationEvidenceBase64' IS NULL$replacement$); + original := replace(original,selector_digest_anchor, + $replacement$ OR selected->>'digestSchemaVersion' IS DISTINCT FROM (CASE binding->>'schemaVersion' + WHEN '2' THEN '3' WHEN '3' THEN '4' WHEN '4' THEN '4' ELSE NULL END)$replacement$); + EXECUTE original; +END; +$migration$; + +-- Keep the V42 start-location retention/readback trigger scoped to schema 4 only. +DO $migration$ +DECLARE + original TEXT; + retain_anchor TEXT := $anchor$ IF NEW.input_json::JSONB->>'schemaVersion' = '1' THEN RETURN NEW; END IF;$anchor$; + guard_anchor TEXT := $anchor$ IF original->>'schemaVersion' IS DISTINCT FROM '2'$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_retain_preparation_start_location()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,retain_anchor,'')))/length(retain_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V42 start-location retention anchor'; + END IF; + original := replace(original,retain_anchor, + $replacement$ IF NEW.input_json::JSONB->>'schemaVersion' = '3' THEN RETURN NEW; END IF;$replacement$); + EXECUTE original; + + SELECT pg_get_functiondef('"${serviceSchema}".world_guard_preparation_start_location()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,guard_anchor,'')))/length(guard_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V42 start-location guard anchor'; + END IF; + original := replace(original,guard_anchor, + $replacement$ IF original->>'schemaVersion' IS DISTINCT FROM '4'$replacement$); + EXECUTE original; +END; +$migration$; + +REVOKE ALL ON FUNCTION world_validate_canonical_prepare_identity() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_validate_canonical_instance_association() FROM PUBLIC; +REVOKE ALL ON FUNCTION world_prepare_canonical_instance(TEXT,TEXT) FROM PUBLIC; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index 8fffea0fc8..3e7b718b68 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -116,6 +116,7 @@ class WorldCanonicalInstanceAssociationPostgresIntegrationTest { private static final String NAMESPACE = "firemud"; private static final long VERSION_EPOCH = 7L; + private static final long FIXTURE_CATALOG_REVISION = 1L; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @@ -252,6 +253,12 @@ private void assertReleaseCheckpointSubstitutionDenied(boolean changeCommit) { @Test void retainsFullCanonicalAssociationAndReadsItAfterTheOwnerCommit() { Fixture fixture = fixture(); + var selectedFullRelease = fixture.binding().evidence().releaseAttestation(); + assertThat(selectedFullRelease.schemaVersion()) + .isEqualTo(AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + assertThat(selectedFullRelease.participantDigests()) + .extracting(AuthoredWorldReleaseAttestationEvidence.Participant::digestSchemaVersion) + .containsExactly(4, 3, 1, 6, 2); UUID canonicalGameInstanceId = UUID.randomUUID(); UUID playableStateNamespaceId = UUID.randomUUID(); WorldCanonicalInstancePreparation.Result preparation = @@ -300,7 +307,7 @@ void retainsFullCanonicalAssociationAndReadsItAfterTheOwnerCommit() { dsl.fetchOne( "SELECT canonical_game_instance_id, canonical_target_namespace, canonical_tenant_id, " + "canonical_world_slug, playable_state_namespace_id, playable_state_scope, " - + "public_production, " + + "public_production, canonical_realm_id, catalog_revision, schema_version, " + "playtest_lifecycle_id, playtest_state_generation, control_plane_request_id, " + "world_instance_id, local_tenant_key, local_version_key, " + "canonical_launch_binding_operation_id, version_identity_operation_id, " @@ -320,6 +327,11 @@ void retainsFullCanonicalAssociationAndReadsItAfterTheOwnerCommit() { .isEqualTo(playableStateNamespaceId); assertThat(row.get("playable_state_scope", String.class)).isEqualTo("SHARED"); assertThat(row.get("public_production", Boolean.class)).isTrue(); + assertThat(row.get("canonical_realm_id", UUID.class)) + .isEqualTo(stored.identity().canonicalRealmId()); + assertThat(row.get("catalog_revision", Long.class)) + .isEqualTo(stored.identity().catalogRevision()); + assertThat(row.get("schema_version", Short.class)).isEqualTo((short) 2); assertThat(row.get("playtest_lifecycle_id", UUID.class)).isNull(); assertThat(row.get("playtest_state_generation", Long.class)).isNull(); assertThat(row.get("world_instance_id", Long.class)).isEqualTo(worldInstanceId); @@ -344,9 +356,14 @@ void retainsFullCanonicalAssociationAndReadsItAfterTheOwnerCommit() { Record worldRow = Objects.requireNonNull( dsl.fetchOne( - "SELECT public_production FROM world_instance WHERE id = ?", worldInstanceId), + "SELECT public_production, canonical_realm_id, catalog_revision FROM world_instance WHERE id = ?", + worldInstanceId), "canonical World instance row missing after committed readback"); assertThat(worldRow.get("public_production", Boolean.class)).isTrue(); + assertThat(worldRow.get("canonical_realm_id", UUID.class)) + .isEqualTo(stored.identity().canonicalRealmId()); + assertThat(worldRow.get("catalog_revision", Long.class)) + .isEqualTo(stored.identity().catalogRevision()); long privateGameInstanceKey = Objects.requireNonNull( dsl.fetchOne( @@ -522,6 +539,34 @@ void exactRetryReusesOriginalAssociationAfterReadMetadataChangeWithoutLifecycleM ownerTransaction() .executeWithoutResult(status -> associationRepository.retainClaimInOwnerTransaction(retry)); + WorldCanonicalInstanceAssociation.Claim changedRealm = + claimWithCatalogIdentity( + retry, + UUID.fromString("a6b99113-8bc9-4de3-a620-ec5648c92f80"), + retry.gameSessionRead().catalogRevision()); + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + associationRepository.retainClaimInOwnerTransaction(changedRealm))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class); + WorldCanonicalInstanceAssociation.Claim changedCatalogRevision = + claimWithCatalogIdentity( + retry, + retry.gameSessionRead().canonicalRealmId(), + retry.gameSessionRead().catalogRevision() + 1L); + assertThatThrownBy( + () -> + ownerTransaction() + .executeWithoutResult( + status -> + associationRepository.retainClaimInOwnerTransaction( + changedCatalogRevision))) + .isInstanceOf( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException.class); + assertThat(associationRepository.readOwnerAssociation(canonicalGameInstanceId)) .contains(original); assertThat(associationCount(canonicalGameInstanceId)).isEqualTo(1L); @@ -539,6 +584,34 @@ void exactRetryReusesOriginalAssociationAfterReadMetadataChangeWithoutLifecycleM assertThat(retry.gameSessionRead().currentGameSessionStatus()).isEqualTo("GS_RETRIED_FIXTURE"); } + @Test + void selectedFullReleaseRejectsMixedWorldParticipantSchema() { + Fixture fixture = fixture(); + var release = fixture.binding().evidence().releaseAttestation(); + assertThat(release.schemaVersion()) + .isEqualTo(AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + var mixedParticipants = + release.participantDigests().stream() + .map( + participant -> + "WORLD_MANAGEMENT".equals(participant.participantKey()) + ? new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + 3, + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest()) + : participant) + .toList(); + + assertThatThrownBy(() -> selectedFullWithParticipants(release, mixedParticipants)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void rejectsChangedRequestEchoDescriptorAttestationAndPlayableScopeWithoutMutation() { Fixture fixture = fixture(); @@ -654,6 +727,8 @@ void rejectsChangedRequestEchoDescriptorAttestationAndPlayableScopeWithoutMutati UUID.randomUUID(), "SHARED", true, + response.canonicalRealmId(), + response.catalogRevision(), response.currentGameSessionStatus(), response.currentGameSessionRowVersion(), response.descriptor(), @@ -681,6 +756,8 @@ void rejectsChangedRequestEchoDescriptorAttestationAndPlayableScopeWithoutMutati response.playableStateNamespaceId(), "ISOLATED", true, + UUID.randomUUID(), + 1L, response.currentGameSessionStatus(), response.currentGameSessionRowVersion(), response.descriptor(), @@ -738,6 +815,8 @@ void rejectsMissingPublicProductionAndPrivatePlaytestClassificationBeforeMutatio playableStateNamespaceId, "ISOLATED", true, + UUID.randomUUID(), + 1L, "GS_FIXTURE", 1L, fixture.binding().descriptor(), @@ -2451,6 +2530,7 @@ private ReleaseContent isolatedReleaseContent(WorldCanonicalInstancePreparation. switch (release.schemaVersion()) { case AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION -> "v2"; case AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION -> "v3"; + case AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION -> "v4"; default -> throw new IllegalStateException( "Selected World fixture has no matching release-content schema"); @@ -2911,12 +2991,60 @@ private WorldCanonicalInstanceAssociation.GameSessionReadEvidence responseFor( playableStateNamespaceId, "SHARED", publicProduction, + syntheticCanonicalRealmId(evidence), + FIXTURE_CATALOG_REVISION, status, rowVersion, descriptor, release); } + private static UUID syntheticCanonicalRealmId(CompleteLaunchBindingEvidence evidence) { + var descriptor = evidence.descriptor(); + String stableFixtureIdentity = + "world-canonical-realm-fixture/v1/" + + descriptor.targetNamespace() + + "/" + + descriptor.canonicalTenantId() + + "/" + + descriptor.worldSlug(); + return UUID.nameUUIDFromBytes(stableFixtureIdentity.getBytes(StandardCharsets.UTF_8)); + } + + private static WorldCanonicalInstanceAssociation.Claim claimWithCatalogIdentity( + WorldCanonicalInstanceAssociation.Claim original, + UUID canonicalRealmId, + long catalogRevision) { + var evidence = original.gameSessionRead(); + var changedEvidence = + new WorldCanonicalInstanceAssociation.GameSessionReadEvidence( + evidence.readRequestId(), + evidence.targetNamespace(), + evidence.canonicalTenantId(), + evidence.worldSlug(), + evidence.canonicalGameInstanceId(), + evidence.controlPlaneRequestId(), + evidence.launchDescriptorId(), + evidence.descriptorRequestDigest(), + evidence.descriptorResultDigest(), + evidence.releaseAttestationEvidenceDigest(), + evidence.playableStateNamespaceId(), + evidence.playableStateScope(), + evidence.publicProduction(), + canonicalRealmId, + catalogRevision, + evidence.currentGameSessionStatus(), + evidence.currentGameSessionRowVersion(), + evidence.descriptor(), + evidence.releaseAttestation()); + return new WorldCanonicalInstanceAssociation.Claim( + original.gameSessionRequest(), + changedEvidence, + original.worldInstanceId(), + original.completeLaunchBinding(), + original.versionIdentity()); + } + private long associationCount(UUID canonicalGameInstanceId) { return Objects.requireNonNull( dsl.fetchOne( @@ -3000,7 +3128,7 @@ private static AuthoredWorldReleaseAttestationEvidence attestation( ? AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION : switch (selector.request().digestSchemaVersion()) { case 3 -> AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION; - case 4 -> AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION; + case 4 -> AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; default -> throw new IllegalArgumentException( "World selector has no paired release-attestation profile"); @@ -3021,9 +3149,23 @@ private static AuthoredWorldReleaseAttestationEvidence attestation( List participants = List.of( worldParticipant, - participant("ENTITY_MANAGEMENT", 2, "b", false, descriptor.versionId(), commit), + participant( + "ENTITY_MANAGEMENT", + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + "ENTITY_MANAGEMENT", attestationSchemaVersion), + "b", + false, + descriptor.versionId(), + commit), participant("GAME_LOGIC", 1, "c", true, descriptor.versionId(), commit), - participant("AUTOMATION_SCRIPTING", 5, "d", false, descriptor.versionId(), commit), + participant( + "AUTOMATION_SCRIPTING", + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + "AUTOMATION_SCRIPTING", attestationSchemaVersion), + "d", + false, + descriptor.versionId(), + commit), participant( "GAME_DESIGN_CONTROL_PLANE", AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( @@ -3078,6 +3220,30 @@ private static AuthoredWorldReleaseAttestationEvidence attestation( descriptor.generationConfigRevision(), selector); } + if (attestationSchemaVersion + == AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION) { + return AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + NAMESPACE, + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersionId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + digest(manifestHashDigit), + 1, + List.of(), + List.of(), + List.of("look"), + descriptor.generationConfigRevision(), + selector); + } return AuthoredWorldReleaseAttestationEvidence.create( NAMESPACE, descriptor.resultDigest(), @@ -3168,6 +3334,30 @@ private static AuthoredWorldReleaseAttestationEvidence releaseWithWorldCheckpoin release.generationConfigRevision(), release.worldStartLocationEvidence()); } + if (release.schemaVersion() + == AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION) { + return AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + checkpoint.publishWorkflowId(), + checkpoint.appliedCommitId(), + participants, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision(), + release.worldStartLocationEvidence()); + } return AuthoredWorldReleaseAttestationEvidence.create( release.targetNamespace(), release.descriptorResultDigest(), @@ -3191,6 +3381,32 @@ private static AuthoredWorldReleaseAttestationEvidence releaseWithWorldCheckpoin release.worldStartLocationEvidence()); } + private static AuthoredWorldReleaseAttestationEvidence selectedFullWithParticipants( + AuthoredWorldReleaseAttestationEvidence release, + List participants) { + return AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + release.publishWorkflowId(), + release.commitId(), + participants, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision(), + release.worldStartLocationEvidence()); + } + private static AuthoredWorldReleaseAttestationEvidence.Participant participant( String owner, int schema, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java index 148acfd899..738cff335e 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java @@ -39,18 +39,21 @@ properties = "spring.grpc.server.port=0") class WorldCanonicalInstancePreparationPostgresIntegrationTest { @Test - void selectorGuardPreservesInertV1ShapeAndDeniesPromotionOrMissingV2BeforeAllocation() { + void selectorGuardAcceptsStructuralV3NoSelectorAndDeniesV1OrIncompleteV2BeforeAllocation() { long before = Objects.requireNonNull(dsl.fetchOne("SELECT count(*) FROM world_instance")) .get(0, Long.class); UUID absentCapture = UUID.randomUUID(); + // V64 keeps schema 3 as the structural no-selector form. This helper-level shape does not + // qualify the complete fresh lifecycle path or prove a receipt-less release is admissible. dsl.fetchOne( "SELECT world_require_preparation_start_location(?::jsonb,?::jsonb,?)", - "{\"schemaVersion\":1}", + "{\"schemaVersion\":3}", "{\"schemaVersion\":1}", absentCapture); for (String input : java.util.List.of( + "{\"schemaVersion\":1}", "{\"schemaVersion\":2}", "{\"schemaVersion\":1,\"worldStartLocationEvidenceBase64\":\"e30=\"}")) { assertThatThrownBy( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 3990037d93..407d2dd55a 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -2150,14 +2150,14 @@ void canonicalInitialAdmissionHoldAcquiresFromRealActiveLifecycleAndRetainsPendi assertThat(active.lifecycleEpoch()).isEqualTo(activation.lifecycleEvidence().lifecycleEpoch()); assertThat(active.rowVersion()).isEqualTo(activation.lifecycleEvidence().rowVersion()); - UUID realmId = UUID.randomUUID(); + var launchIdentity = fixture.materialized().association().identity(); String requestId = "canonical-admission-" + UUID.randomUUID(); Request request = new Request( active.request().targetNamespace(), active.request().canonicalTenantId(), active.request().worldSlug(), - realmId, + launchIdentity.canonicalRealmId(), active.request().playableStateNamespaceId(), active.request().playableStateScope(), active.request().canonicalGameInstanceId(), @@ -2166,7 +2166,7 @@ void canonicalInitialAdmissionHoldAcquiresFromRealActiveLifecycleAndRetainsPendi requestId, "a".repeat(64), InitialAdmissionOrigin.NO_PRIOR_POINTER, - 1L, + launchIdentity.catalogRevision(), null); var repository = new WorldCanonicalInitialAdmissionHoldRepository( @@ -2242,28 +2242,43 @@ void canonicalInitialAdmissionHoldAcquiresFromRealActiveLifecycleAndRetainsPendi .isTrue(); assertThat( new InitialAdmissionBindHoldRepository(dsl) - .hasNonterminalForRealm(privateKeys.privateTenantKey(), realmId.toString())) + .hasNonterminalForRealm( + privateKeys.privateTenantKey(), request.realmId().toString())) .isTrue(); - UUID closedRealmId = UUID.randomUUID(); + PreparedLifecycleFixture closedFixture = materializedLifecycleFixture(); + var closedActivation = + canonicalActivationService(closedFixture, ignored -> stipulatedActivationAuthority()) + .activate( + new WorldCanonicalInstanceActivation.Request( + UUID.randomUUID(), closedFixture.preparing())); + assertThat(closedActivation.outcome()) + .isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + var closedActive = + closedFixture + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(closedActivation.lifecycleEvidence().request())) + .orElseThrow(); + var closedLaunchIdentity = closedFixture.materialized().association().identity(); + var closedPrivateKeys = closedFixture.materialized().association().worldPrepareFields(); // Acquiring this tagged PENDING hold does not prove Game Session's never-OPEN origin. Request expectClosedRequest = new Request( - request.targetNamespace(), - request.canonicalTenantId(), - request.worldSlug(), - closedRealmId, - request.playableStateNamespaceId(), - request.playableStateScope(), - request.canonicalGameInstanceId(), - request.canonicalVersionId(), - request.activeLifecycleEpoch(), + closedActive.request().targetNamespace(), + closedActive.request().canonicalTenantId(), + closedActive.request().worldSlug(), + closedLaunchIdentity.canonicalRealmId(), + closedActive.request().playableStateNamespaceId(), + closedActive.request().playableStateScope(), + closedActive.request().canonicalGameInstanceId(), + closedActive.request().canonicalVersionId(), + closedActive.lifecycleEpoch(), "canonical-admission-closed-" + UUID.randomUUID(), "b".repeat(64), InitialAdmissionOrigin.EXPECT_CLOSED, - 2L, + closedLaunchIdentity.catalogRevision(), 7L); - var expectClosed = repository.acquire(expectClosedRequest, active.request()); + var expectClosed = repository.acquire(expectClosedRequest, closedActive.request()); assertThat(expectClosed.request()).isEqualTo(expectClosedRequest); var storedExpectClosed = Objects.requireNonNull( @@ -2272,7 +2287,7 @@ void canonicalInitialAdmissionHoldAcquiresFromRealActiveLifecycleAndRetainsPendi + "expected_prior_pointer_version, canonical_request_bytes, " + "hold_binding_digest FROM initial_admission_bind_hold " + "WHERE tenant_id = ? AND initial_admission_request_id = ?", - privateKeys.privateTenantKey(), + closedPrivateKeys.privateTenantKey(), expectClosedRequest.initialAdmissionRequestId())); assertThat(storedExpectClosed.get("expected_no_prior_pointer", Boolean.class)).isFalse(); assertThat(storedExpectClosed.get("initial_admission_origin", String.class)) @@ -2341,7 +2356,8 @@ void canonicalInitialAdmissionHoldAcquiresFromRealActiveLifecycleAndRetainsPendi .isTrue(); assertThat( new InitialAdmissionBindHoldRepository(dsl) - .hasNonterminalForRealm(privateKeys.privateTenantKey(), realmId.toString())) + .hasNonterminalForRealm( + privateKeys.privateTenantKey(), request.realmId().toString())) .isTrue(); assertOrigin(); } @@ -2364,10 +2380,16 @@ void canonicalHoldReconciliationUsesTypedBoundedPagesAndLegacyFinderExcludesType Request firstRequest = canonicalReconciliationHoldRequest( - active, "canonical-reconcile-first-" + UUID.randomUUID(), "c".repeat(64)); + active, + fixture.materialized().association().identity(), + "canonical-reconcile-first-" + UUID.randomUUID(), + "c".repeat(64)); Request secondRequest = canonicalReconciliationHoldRequest( - active, "canonical-reconcile-second-" + UUID.randomUUID(), "d".repeat(64)); + active, + fixture.materialized().association().identity(), + "canonical-reconcile-second-" + UUID.randomUUID(), + "d".repeat(64)); var repository = new WorldCanonicalInitialAdmissionHoldRepository( dsl, manager, associationRepository(), fixture.lifecycleRepository()); @@ -2469,12 +2491,15 @@ dsl, manager, associationRepository(), fixture.lifecycleRepository()), } private static Request canonicalReconciliationHoldRequest( - WorldCanonicalInstanceLifecycleEvidence active, String requestId, String requestDigest) { + WorldCanonicalInstanceLifecycleEvidence active, + WorldCanonicalInstanceAssociation.CanonicalIdentity launchIdentity, + String requestId, + String requestDigest) { return new Request( active.request().targetNamespace(), active.request().canonicalTenantId(), active.request().worldSlug(), - UUID.randomUUID(), + launchIdentity.canonicalRealmId(), active.request().playableStateNamespaceId(), active.request().playableStateScope(), active.request().canonicalGameInstanceId(), @@ -2483,7 +2508,7 @@ private static Request canonicalReconciliationHoldRequest( requestId, requestDigest, InitialAdmissionOrigin.NO_PRIOR_POINTER, - 1L, + launchIdentity.catalogRevision(), null); } @@ -4103,47 +4128,128 @@ private long beginSyntheticExecution(WorldCanonicalInstanceExecutionIdentity ide "Synthetic World execution begin omitted its fence"); } - /** Executes the real V35/V42 owner SQL path for selector-null V1 migration history. */ - private WorldCanonicalInstancePreparation.Result prepareV1ThroughOwnerFunction( + /** Executes the V35/V42 owner SQL path only on explicit V41/V42 historical schemas. */ + private HistoricalPreparationResult prepareV1ThroughOwnerFunction( WorldCanonicalInstancePreparation.Input input) { - String inputJson = WorldCanonicalInstancePreparationRepository.inputJson(input); + String inputJson = historicalV1PreparationInputJson(input); byte[] inputBytes = inputJson.getBytes(StandardCharsets.UTF_8); - Long worldInstanceId = + Record ownerResult = Objects.requireNonNull( ownerTransaction() .execute( status -> { - var row = + Record row = Objects.requireNonNull( dsl.fetchOne( "SELECT * FROM world_prepare_canonical_instance(?, ?)", inputJson, sha256Digest(inputBytes)), "V35/V42 owner preparation function returned no row"); - Long allocatedWorldInstanceId = + long allocatedWorldInstanceId = + Objects.requireNonNull( + row.get("world_instance_id", Long.class), + "V35/V42 owner preparation result omitted world_instance_id") + .longValue(); + String associationSelect = + "SELECT 1::SMALLINT AS schema_version,wi.canonical_game_instance_id," + + "wi.canonical_target_namespace,wi.canonical_tenant_id,wi.canonical_world_slug," + + "wi.playable_state_namespace_id,wi.playable_state_scope,wi.public_production," + + "wi.playtest_lifecycle_id,wi.playtest_state_generation," + + "wi.control_plane_request_id,wi.id AS world_instance_id," + + "b.binding_operation_id AS canonical_launch_binding_operation_id," + + "v.operation_id AS version_identity_operation_id,b.canonical_version_id," + + "wi.tenant_id AS local_tenant_key,wi.game_instance_id AS private_game_instance_key," + + "wi.game_template_id,wi.launch_descriptor_id,wi.version_id AS local_version_key," + + "wi.script_patch_version,wi.runtime_flags_json,wi.generation_config_revision," + + "wi.release_bundle_id,wi.published_release_bundle_ref,wi.version_state_epoch," + + "wi.remap_set_id,b.intake_operation_id,b.intake_request_id,b.source_operation_id," + + "b.source_evidence_digest,s.request_digest AS intake_request_digest," + + "b.intake_receipt_digest,b.descriptor_request_digest,b.descriptor_result_digest," + + "b.release_attestation_digest FROM world_instance wi " + + "JOIN world_complete_launch_binding b " + + "ON b.binding_operation_id=wi.canonical_launch_binding_operation_id " + + "JOIN world_authored_version_identity v ON v.operation_id=? " + + "JOIN world_authored_source_intake s ON s.operation_id=b.intake_operation_id " + + "WHERE wi.id=?"; + Record expectedAssociation = Objects.requireNonNull( - row.get("world_instance_id", Long.class), - "V35/V42 owner preparation result omitted world_instance_id"); - var claim = - new WorldCanonicalInstanceAssociation.Claim( - input.gameSessionReadRequest(), - input.gameSessionReadEvidence(), - allocatedWorldInstanceId.longValue(), - input.completeLaunchBinding(), - input.versionIdentity()); - associationRepository().retainClaimInOwnerTransaction(claim); - return allocatedWorldInstanceId; + dsl.fetchOne( + associationSelect, + input.versionIdentity().operationId(), + allocatedWorldInstanceId), + "V34 historical fixture could not resolve its exact association fields"); + Record retainedAssociation = + dsl.fetchOne( + "SELECT * FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id = ?", + input.canonicalGameInstanceId()); + if (retainedAssociation == null) { + int inserted = + dsl.execute( + "INSERT INTO world_canonical_instance_association (" + + "schema_version,canonical_game_instance_id,canonical_target_namespace," + + "canonical_tenant_id,canonical_world_slug,playable_state_namespace_id," + + "playable_state_scope,public_production,playtest_lifecycle_id," + + "playtest_state_generation,control_plane_request_id,world_instance_id," + + "canonical_launch_binding_operation_id,version_identity_operation_id," + + "canonical_version_id,local_tenant_key,private_game_instance_key," + + "game_template_id,launch_descriptor_id,local_version_key,script_patch_version," + + "runtime_flags_json,generation_config_revision,release_bundle_id," + + "published_release_bundle_ref,version_state_epoch,remap_set_id," + + "intake_operation_id,intake_request_id,source_operation_id,source_evidence_digest," + + "intake_request_digest,intake_receipt_digest,descriptor_request_digest," + + "descriptor_result_digest,release_attestation_digest) " + + associationSelect, + input.versionIdentity().operationId(), + allocatedWorldInstanceId); + if (inserted != 1) { + throw new IllegalStateException( + "V34 historical fixture failed to retain its schema-1 association"); + } + retainedAssociation = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id = ?", + input.canonicalGameInstanceId()), + "V34 historical fixture association was not retained"); + } + if (!Arrays.equals( + expectedAssociation.intoArray(), retainedAssociation.intoArray())) { + throw new IllegalStateException( + "V34 historical fixture retry differs from its full retained schema-1 association"); + } + return row; }), - "V35/V42 owner transaction returned no allocated world_instance_id"); - var result = - preparationRepository() - .readOwnerPreparation(input) - .orElseThrow( - () -> - new IllegalStateException( - "V35/V42 owner preparation has no exact committed readback")); - assertThat(result.association().worldInstanceId()).isEqualTo(worldInstanceId.longValue()); - return result; + "V35/V42 historical owner transaction returned no preparation result"); + return new HistoricalPreparationResult( + Objects.requireNonNull( + ownerResult.get("world_instance_id", Long.class), + "V35/V42 owner preparation result omitted world_instance_id"), + Objects.requireNonNull( + ownerResult.get("private_game_instance_key", Long.class), + "V35/V42 owner preparation result omitted private_game_instance_key"), + null, + null); + } + + private String historicalV1PreparationInputJson(WorldCanonicalInstancePreparation.Input input) { + try { + var root = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(WorldCanonicalInstancePreparationRepository.inputJson(input)); + root.put("schemaVersion", 1); + var identity = (tools.jackson.databind.node.ObjectNode) root.get("identity"); + identity.remove("canonicalRealmId"); + identity.remove("catalogRevision"); + var evidence = (tools.jackson.databind.node.ObjectNode) root.get("gameSessionReadEvidence"); + evidence.remove("canonicalRealmId"); + evidence.remove("catalogRevision"); + return mapper.writeValueAsString(root); + } catch (tools.jackson.core.JacksonException malformed) { + throw new IllegalStateException( + "Could not construct original schema-1 fixture bytes", malformed); + } } private Map preparationHistoryRows() { @@ -4296,6 +4402,8 @@ private WorldCanonicalInstancePreparation.Input preparationInput( UUID.randomUUID(), "SHARED", true, + UUID.randomUUID(), + 1L, "PREPARING", 1L, descriptor, @@ -4481,6 +4589,8 @@ private PreparationAssemblyFixture preparationAssemblyFixture( playableStateNamespaceId, RealmEntryPolicy.StateScope.SHARED, true, + UUID.randomUUID(), + 1L, CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus .STARTING, 1L, @@ -5132,10 +5242,9 @@ private PlacementFixture initialPlayerLocationFixture(InitialAdmissionOrigin ori .orElseThrow(); assertThat(activeEvidence.lifecycleStatus()).isEqualTo("ACTIVE"); - UUID realmId = UUID.randomUUID(); + var launchIdentity = lifecycleFixture.materialized().association().identity(); String initialAdmissionRequestId = "placement-admission-" + UUID.randomUUID(); String initialAdmissionRequestDigest = "f".repeat(64); - long catalogRevision = origin == InitialAdmissionOrigin.NO_PRIOR_POINTER ? 1L : 2L; // EXPECT_CLOSED is an upstream stipulation here, not owner proof the realm was never OPEN. Long expectedPriorPointerVersion = origin == InitialAdmissionOrigin.EXPECT_CLOSED ? 7L : null; Request holdRequest = @@ -5143,7 +5252,7 @@ private PlacementFixture initialPlayerLocationFixture(InitialAdmissionOrigin ori activeEvidence.request().targetNamespace(), activeEvidence.request().canonicalTenantId(), activeEvidence.request().worldSlug(), - realmId, + launchIdentity.canonicalRealmId(), activeEvidence.request().playableStateNamespaceId(), activeEvidence.request().playableStateScope(), activeEvidence.request().canonicalGameInstanceId(), @@ -5152,7 +5261,7 @@ private PlacementFixture initialPlayerLocationFixture(InitialAdmissionOrigin ori initialAdmissionRequestId, initialAdmissionRequestDigest, origin, - catalogRevision, + launchIdentity.catalogRevision(), expectedPriorPointerVersion); var holdRepository = new WorldCanonicalInitialAdmissionHoldRepository( @@ -8227,6 +8336,12 @@ private record Fixture( private record HistoricalSchemaFixture( String schema, WorldDraftGraphApplicationPostgresIntegrationTest database) {} + private record HistoricalPreparationResult( + long worldInstanceId, + long privateGameInstanceKey, + RoomTemplateRef startLocation, + Long runtimeRoomInstanceId) {} + private record ActivationProof( WorldCanonicalInstanceActivation.Request request, WorldCanonicalInstanceActivation.Result result) {} diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationHoldProofTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationHoldProofTest.java index 0edb0d8be4..8520e4e765 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationHoldProofTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalPlayerLocationHoldProofTest.java @@ -157,6 +157,8 @@ private static Fixture fixture( namespace, "SHARED", true, + realm, + 3L, "launch-request")); var request = mock(WorldCanonicalInitialPlayerLocation.Request.class); when(request.initialAdmissionOrigin()) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepositoryTest.java index 8d28ac62c9..6382f2df97 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldFinalizationRepositoryTest.java @@ -234,6 +234,8 @@ private static WorldCanonicalInstanceAssociation association() { PLAYABLE_NAMESPACE, "SHARED", true, + REALM, + 12L, "control-request"); var prepare = new WorldCanonicalInstanceAssociation.WorldPrepareFields( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java index bcc89028d3..f4083e2790 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepositoryTest.java @@ -116,6 +116,17 @@ void changedRequestAndLegacyUnmappedCollisionAreDenied() { verify(legacyFixture.dsl, never()).execute(anyString(), any(Object[].class)); } + @Test + void suppliedCatalogRevisionMustEqualLaunchCapturedAssociationRevision() { + Request request = request(REQUEST_DIGEST, InitialAdmissionOrigin.NO_PRIOR_POINTER, null, 13L); + Fixture fixture = fixture(request, activeLifecycle("ACTIVE", 7L), null); + + assertThatThrownBy(() -> fixture.repository.acquire(request, selector(request))) + .isInstanceOf(WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException.class) + .hasMessageContaining("persisted association"); + verify(fixture.dsl, never()).execute(anyString(), any(Object[].class)); + } + @Test void incompleteMetadataBadBindingDigestAndSubstitutedScopeAreDenied() { Request request = noPriorRequest(); @@ -503,6 +514,8 @@ private static WorldCanonicalInstanceAssociation association() { PLAYABLE_NAMESPACE, "SHARED", true, + REALM, + 12L, "control-request"); WorldPrepareFields prepareFields = new WorldPrepareFields( @@ -566,6 +579,14 @@ private static Request expectClosedRequest(long pointerVersion) { private static Request request( String digest, InitialAdmissionOrigin origin, Long priorPointerVersion) { + return request(digest, origin, priorPointerVersion, 12L); + } + + private static Request request( + String digest, + InitialAdmissionOrigin origin, + Long priorPointerVersion, + long expectedCatalogRevision) { return new Request( "prod", TENANT, @@ -579,7 +600,7 @@ private static Request request( REQUEST_ID, digest, origin, - 12L, + expectedCatalogRevision, priorPointerVersion); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java index 3bff8b942a..b2b5a19f81 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationTest.java @@ -87,8 +87,45 @@ void canonicalIdentityRequiresExplicitPublicProductionClassification() { UUID.randomUUID(), "SHARED", false, + UUID.randomUUID(), + 1L, "synthetic-control-request")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("explicit public-production evidence"); } + + @Test + void canonicalIdentityRequiresLaunchCapturedRealmAndPositiveCatalogRevision() { + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + UUID.randomUUID(), + "firemud", + UUID.randomUUID(), + "fixture-world", + UUID.randomUUID(), + "SHARED", + true, + new UUID(0L, 0L), + 1L, + "synthetic-control-request")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonicalRealmId"); + + assertThatThrownBy( + () -> + new WorldCanonicalInstanceAssociation.CanonicalIdentity( + UUID.randomUUID(), + "firemud", + UUID.randomUUID(), + "fixture-world", + UUID.randomUUID(), + "SHARED", + true, + UUID.randomUUID(), + 0L, + "synthetic-control-request")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("catalogRevision"); + } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java index cae1775dac..66b38ed7a1 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java @@ -49,6 +49,7 @@ class WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest { private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); private static final UUID GAME_INSTANCE = uuid("23232323-2323-4323-8323-232323232323"); private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID CANONICAL_REALM = uuid("88888888-8888-4888-8888-888888888888"); private static final UUID PARTICIPATION_ID = uuid("13131313-1313-4313-8313-131313131313"); private static final UUID ATTEMPT_ID = uuid("12121212-1212-4121-8121-121212121212"); private static final UUID VERSION_ID = uuid("22222222-2222-4222-8222-222222222222"); @@ -75,6 +76,27 @@ void acceptsSerializerShapedSchemaTwoHistoricalEvidence() { acceptsExactHistoricalOwnerEvidenceAndUsesFreshReadCorrelations(fixture(false, true)); } + @Test + void newSchemaRequiresIdentityAndGameSessionEvidenceToRetainTheSameCatalogRevision() + throws Exception { + Fixture fixture = fixture(false); + assertThat(fixture.preparationInputJson()).contains("\"schemaVersion\":3"); + var changed = + (tools.jackson.databind.node.ObjectNode) JSON.readTree(fixture.preparationInputJson()); + ((tools.jackson.databind.node.ObjectNode) changed.get("gameSessionReadEvidence")) + .put("catalogRevision", 10L); + String changedInput = json(changed); + when(fixture.identity().preparationInputJson()).thenReturn(changedInput); + when(fixture.identity().preparationInputDigest()) + .thenReturn(sha256(changedInput.getBytes(StandardCharsets.UTF_8))); + + var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); + var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + + assertDenied(verifier(account, gameSession), fixture.identity()); + verifyNoInteractions(account, gameSession); + } + private void acceptsExactHistoricalOwnerEvidenceAndUsesFreshReadCorrelations(Fixture fixture) { var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); @@ -308,16 +330,21 @@ void ambientSqlAndSynchronizationAreRejectedBeforeOwnerReads() { } private static Fixture fixture(boolean alternateDescriptor) { - return fixture(alternateDescriptor, false); + return fixture(alternateDescriptor, false, true); } private static Fixture fixture(boolean alternateDescriptor, boolean selectedSchema) { + return fixture(alternateDescriptor, selectedSchema, false); + } + + private static Fixture fixture( + boolean alternateDescriptor, boolean selectedSchema, boolean capturedCatalog) { WorldPublishedStartLocationEvidence selector = selectedSchema ? retainedWorldSelector() : null; WorldAuthoredSourceIntakeReceipt source = sourceReceipt(false, selector == null ? null : selector.request().intakeRequestId()); AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(source, alternateDescriptor); AuthoredWorldReleaseAttestationEvidence release = release(descriptor, selector); - return fixture(source, descriptor, release, selector); + return fixture(source, descriptor, release, selector, capturedCatalog); } private static WorldPublishedStartLocationEvidence retainedWorldSelector() { @@ -334,22 +361,16 @@ private static Fixture fixtureWithSubstitutedSource() { AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(originalSource, false); AuthoredWorldReleaseAttestationEvidence release = release(descriptor); WorldAuthoredSourceIntakeReceipt substitutedSource = sourceReceipt(true); - return fixture(substitutedSource, descriptor, release); - } - - private static Fixture fixture( - WorldAuthoredSourceIntakeReceipt retainedSource, - AuthoredWorldLaunchDescriptorEvidence descriptor, - AuthoredWorldReleaseAttestationEvidence release) { - return fixture(retainedSource, descriptor, release, null); + return fixture(substitutedSource, descriptor, release, null, true); } private static Fixture fixture( WorldAuthoredSourceIntakeReceipt retainedSource, AuthoredWorldLaunchDescriptorEvidence descriptor, AuthoredWorldReleaseAttestationEvidence release, - WorldPublishedStartLocationEvidence selector) { - String input = preparationInput(descriptor, release, retainedSource, selector); + WorldPublishedStartLocationEvidence selector, + boolean capturedCatalog) { + String input = preparationInput(descriptor, release, retainedSource, selector, capturedCatalog); WorldCanonicalInstanceExecutionIdentity identity = mock(WorldCanonicalInstanceExecutionIdentity.class); when(identity.originalPostAuthorizationTuple()).thenReturn(ORIGINAL_TUPLE.clone()); @@ -557,7 +578,8 @@ private static String preparationInput( AuthoredWorldLaunchDescriptorEvidence descriptor, AuthoredWorldReleaseAttestationEvidence release, WorldAuthoredSourceIntakeReceipt source, - WorldPublishedStartLocationEvidence selector) { + WorldPublishedStartLocationEvidence selector, + boolean capturedCatalog) { Map identity = map( "canonicalGameInstanceId", @@ -576,6 +598,10 @@ private static String preparationInput( true, "controlPlaneRequestId", "start-session-control-request"); + if (capturedCatalog) { + identity.put("canonicalRealmId", CANONICAL_REALM.toString()); + identity.put("catalogRevision", 9L); + } Map readRequest = map( "targetNamespace", NAMESPACE, @@ -603,6 +629,10 @@ private static String preparationInput( "publicProduction", true, "descriptorJson", json(descriptor), "releaseAttestationJson", json(release)); + if (capturedCatalog) { + readEvidence.put("canonicalRealmId", CANONICAL_REALM.toString()); + readEvidence.put("catalogRevision", 9L); + } Map launch = map( "schemaVersion", 1, @@ -718,14 +748,22 @@ private static String preparationInput( 0); Map root = map( - "schemaVersion", selector == null ? 1 : 2, - "identity", identity, - "gameSessionReadRequest", readRequest, - "gameSessionReadEvidence", readEvidence, - "launchBinding", launch, - "versionIdentity", versionIdentity, - "sourceIntake", sourceIntake, - "topology", topology); + "schemaVersion", + capturedCatalog ? (selector == null ? 3 : 4) : (selector == null ? 1 : 2), + "identity", + identity, + "gameSessionReadRequest", + readRequest, + "gameSessionReadEvidence", + readEvidence, + "launchBinding", + launch, + "versionIdentity", + versionIdentity, + "sourceIntake", + sourceIntake, + "topology", + topology); if (selector != null) { root.put( "worldStartLocationEvidenceBase64", diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java index acb2b19a45..5c0a3ab7f6 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java @@ -213,6 +213,8 @@ void acceptsOnlyTheExactGameSessionSelectorAndCompleteStoredPair() { assertThat(worldEvidence.canonicalGameInstanceId()).isEqualTo(INSTANCE_ID); assertThat(worldEvidence.playableStateScope()).isEqualTo("SHARED"); assertThat(worldEvidence.publicProduction()).isTrue(); + assertThat(worldEvidence.canonicalRealmId()).isEqualTo(matching.canonicalRealmId()); + assertThat(worldEvidence.catalogRevision()).isEqualTo(matching.catalogRevision()); var changedInstanceRequest = gameSessionRequest(stored, UUID.randomUUID()); var changedInstanceResult = gameSessionResult(changedInstanceRequest, stored); @@ -304,6 +306,8 @@ private static CanonicalGameInstanceLaunchAssociationReadEvidence.Result gameSes UUID.randomUUID(), RealmEntryPolicy.StateScope.SHARED, true, + UUID.randomUUID(), + 1L, CurrentGameInstanceStatus.RUNNING, 17L, binding); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java index cd587cd7a8..3b0641943c 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java @@ -960,6 +960,8 @@ private static CommittedLaunchFixture committedLaunchFixture() { UUID.fromString("abababab-abab-4bab-8bab-abababababab"), RealmEntryPolicy.StateScope.SHARED, true, + UUID.fromString("cdcdcdcd-cdcd-4dcd-8dcd-cdcdcdcdcdcd"), + 7L, CurrentGameInstanceStatus.RUNNING, 7L, pair); From 07d639bb304f82a6f16005ec69362b07bc257f07 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 13:57:00 +1300 Subject: [PATCH 104/129] Bind original initial-admission terminal to complete Account protection --- ...dmin-as-external-operator-write-ingress.md | 4 + .../account-service/api-contracts.md | 2 + .../game-session-service/api-contracts.md | 4 +- .../world-management-service/api-contracts.md | 10 +- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 4 + ...e-session-runtime-and-tick-coordination.md | 2 + ...StartSessionAuthorizationProofFixture.java | 30 + ...AuthoredInitialActorCoreSourceBinding.java | 313 ++- .../gamelogic/GameplayRuleSelectedSource.java | 78 +- ...oredInitialActorCoreSourceBindingTest.java | 134 +- .../StartSessionLaunchDescriptorProducer.java | 94 +- ...lInitialAdmissionHoldTransportFixture.java | 186 ++ ...licationExportPostgresIntegrationTest.java | 203 +- ...rtSessionLaunchDescriptorProducerTest.java | 103 + ...onCanonicalInitialAdmissionRepository.java | 2148 +++++++++++++++++ ...ssionAdmissionTerminalReadGrpcService.java | 143 ++ ..._initial_admission_terminal_protection.sql | 559 +++++ ...nonicalInitialAdmissionRepositoryTest.java | 60 + ...nAdmissionTerminalReadGrpcServiceTest.java | 484 ++++ 20 files changed, 4473 insertions(+), 94 deletions(-) rename services/{game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication => common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign}/AuthoredInitialActorCoreSourceBinding.java (50%) rename services/{game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication => common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign}/AuthoredInitialActorCoreSourceBindingTest.java (79%) create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/CanonicalInitialAdmissionHoldTransportFixture.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInitialAdmissionRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionAdmissionTerminalReadGrpcService.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V44__canonical_initial_admission_terminal_protection.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInitialAdmissionRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionAdmissionTerminalReadGrpcServiceTest.java diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 12755d712f..aeb85f7a27 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -111,6 +111,10 @@ World owns a durable operation row and a separate monotonic execution fence that Expiry forbids dispatch of a new owner attempt, opening or restarting the World SQL transaction, reacquiring or renewing participation, renewing or reissuing the reference, or re-redeeming it. After a crash or unknown outcome following expiry, World may perform only an exact read-only lookup of the original durable operation: return `COMMITTED` only for the exact stored tuple, or record/return `ABORTED` only through the serialized fence after proving no in-flight or later commit; otherwise remain unresolved, retain source protection, and deny mutation retry. The original operation cannot be retried as a new mutation after expiry or uncertainty. The [implementation tracker](../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) distinguishes World-local execution storage from the still-missing genuine Account participation and authenticated recovery producer. This target contract grants no positive StartSession admission or runtime-activation approval; execution must remain unavailable until those boundaries and proofs exist. +#### Original World Activation Protection + +The original StartSession flow has a distinct [Account activation-purpose protection](../microservices/account-service/api-contracts.md#operator-authorization-references) through World's later initial activation compare-and-set. Preparation `COMMITTED` retains its existing meaning and cannot stand in for completed activation; the ACTIVE-only admission protection below is not activation authority. The Account owner contract defines acquisition under unchanged, still-valid original authority and immutable source participation through exact authenticated activation settlement. The [World owner contract](../microservices/world-management-service/api-contracts.md#canonical-initial-activation-protection) defines the local transaction, exact ACTIVE terminal and definitive abort exclusion. Neither boundary renews an expired original operation or enables runtime activation before its complete proof. + #### Original StartSession Admission Source Protection Account owns a distinct source-protection lifecycle through the original Game Session admission commit. World receiving participation ends only at its own authenticated World terminal outcome; its settlement does not settle this admission protection. A retained finite Game Session attempt observation is not continuous source protection or current claim authority. Account retains the complete unchanged original post-authorization tuple and Account redemption projection, actual Game Session mutation/attempt/fence and original finite lease expiry, original World participation ID/fence, complete canonical World initial-admission hold identity, and exact original Account capture reference and source vector under a separate immutable protection ID and positive fence. The World initial-admission request identity and original control-plane request identity remain distinct and are both bound rather than aliased. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 43a116fbd3..9cc72747e5 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -181,6 +181,8 @@ The distinct [`AccountSelectedOwnerIntakeSourceReadService.ReadSourceScope`](../ ### Operator Authorization References +The original StartSession flow has a distinct Account-owned **activation-purpose protection**, separate from the World preparation participation and the later ACTIVE-only Game Session admission protection. Preparation `COMMITTED` retains its existing meaning and does not prove activation. Before World opens its activation transaction, Account acquires this protection under still-valid original authority, binding the unchanged complete source vector and original tuple, exact current Game Session attempt/mutation/fence and finite original lease, actual `STARTING` launch, exact `PREPARING` owner evidence and activation operation identity. It does not issue, renew, redeem or restart authority. Source participation stays pending through World's exact activation compare-and-set. Account may settle only from authenticated exact `ACTIVE` terminal evidence or a positively fenced `ABORTED` result that excludes later activation for the same operation; timeout, expiry, absence, ambiguous evidence and generic handle `close()` cannot release it. Exact committed recovery reuses immutable identities and results without authorizing new work. The [World activation consequence](../world-management-service/api-contracts.md#canonical-initial-activation-protection) owns its local transaction and terminal exclusion. Producer/consumer, crash, expiry and settlement proof remain required before activation is enabled; implementation status belongs to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + `IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, and the immutable `authorityEvidenceBundle/v1`; Account never exposes that evidence through an external route, logs, audit text, or client-visible response. `IssueAutomationOperatorAuthorizationReferenceRequest` contains no workload identity field: Account derives `workloadIdentity` from the authenticated mTLS transport peer and rejects any serialized or caller-supplied substitute. It contains `automation_policy_id`, `automation_policy_version`, target owner service, typed target scope, action family, action-family schema identifier/version, `controlPlaneRequestId`, and canonical `mutationDigest`, with no account, end-user token, or human identity. The target request is `non_moderation`-only: published schema pairs must select the branch with `action_category` absent, moderation schema pairs are rejected before issuance, and no concrete schema pairs are published while the route remains target-not-routable. For the supported tenant-scoped branch, Account binds the exact `tenant_generation`; global-role or `privileged_control` authority is rejected rather than inferred. The exact authenticated internal response has the same opaque reference, fingerprint, expiry, and immutable authority-evidence shape; its stored binding includes the authenticated workload and policy evidence plus the applicable generation predicate. `controlPlaneRequestId` and `mutationDigest/v1` cannot be reused for moderation; any future moderation automation contract must declare dedicated request identity, digest, and idempotency semantics with `controlPlaneRequestId` correlation-only. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index e5585510a9..1ff8920e22 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -66,10 +66,12 @@ Lost responses reconcile through the exact hold identity and authoritative World ### Initial admission bind -The first admission-pointer bind for a realm is a separate owner transaction from replacement cutover. Game Session owns a durable attempt ledger with one stable request identity and canonical digest, plus the terminal outcome `COMMITTED` or `ABORTED`. Its initial pointer transaction must prove that no pointer exists for the exact `{tenantId, realmId}` and atomically bind the World-issued initial-bind hold identity/fence, the same request identity/digest, `{tenantId, realmId, playableStateNamespaceId, playableStateScope}`, target `gameInstanceId`/`versionId` and exact `ACTIVE` lifecycle epoch, and `catalogRevision` with the new pointer and matching append-only audit event. The durable `COMMITTED` attempt outcome commits in that same transaction. This owner-side no-prior-pointer check is not replaced by a bootstrap snapshot, startup configuration, public raw-pointer RPC, or external operator write bypass. +The first admission-pointer bind for a realm is a separate owner transaction from replacement cutover. Game Session owns a durable attempt ledger with one stable initial-admission request identity and canonical digest, plus the terminal outcome `COMMITTED` or `ABORTED`. Its initial pointer transaction atomically proves the exact [World hold origin precondition](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract): either `NO_PRIOR_POINTER`, or `EXPECT_CLOSED` for the exact targetless, canonical catalog-created pointer that has never been OPEN. Missing historical records alone do not prove that precondition. The transaction binds the World-issued initial-bind hold identity/fence, the same request identity/digest, `{tenantId, realmId, playableStateNamespaceId, playableStateScope}`, target `gameInstanceId`/`versionId` and exact `ACTIVE` lifecycle epoch, and `catalogRevision` with the new or advanced pointer and matching append-only audit event. It advances `pointerVersion` and commits the durable `COMMITTED` attempt outcome in that same transaction. A previously OPEN pointer requires the separate reopen/replacement boundary, not initial admission. Bootstrap snapshots, startup configuration, public raw-pointer RPCs and external operator writes cannot replace the owner precondition or transaction. An exact retry or post-restart recovery reuses the same attempt and hold identities and reconciles the durable attempt, pointer, and audit. Game Session may record `ABORTED` only as a durable terminal outcome that prevents any later commit for that same attempt. World may accept that exact, authenticated owner-readback outcome bound to the same hold and tuple as abort proof; pointer absence, `NOT_FOUND`, `PENDING`, unavailable reads, mismatched tuple/audit, or contradictory evidence is not proof. World finalization requires an authenticated exact Game Session owner readback of the same hold and request identity/digest, tuple, committed pointer, matching audit, and `COMMITTED` outcome. Ambiguous results remain termination-fenced while automatic reconciliation retries; elapsed time does not release the World hold. See the World-owned [initial admission bind hold contract](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract). +The original StartSession terminal ledger retains the complete [Account admission-protection evidence](../account-service/api-contracts.md#operator-authorization-references), unchanged original tuple/projection/lease, actual Game Session owner attempt/mutation/fence and exact catalog/launch binding. The initial-admission request ID is distinct from the original `controlPlaneRequestId`; the durable intent links them. Fresh mutation requires the original current claim and unchanged lease after owner lock waits. Historical exact terminal recovery neither renews the lease nor authorizes a mutation. The owner-local terminal `proofDigest` is prefixed SHA-256 over ADR 0047-style byte-length frames in this fixed order: domain `game-session-canonical-initial-admission-terminal/v1`, complete canonical Account protection evidence bytes, bare canonical initial-admission request digest, outcome name, actual pointer row ID, committed pointer version, audit event ID, stored terminal time as UTC with six fractional digits, and abort reason. Counters use canonical decimal strings; abort omits pointer/audit values as empty frames, while commit uses an empty abort-reason frame. The digest itself is excluded. Independent readback recomputes that digest from immutable owner evidence and verifies the actual pointer/audit or positive durable abort exclusion. A digest or caller echo alone is not authenticated owner proof; the Account-facing read requires the exact configured Account workload. Implementation and physical composition remain gated in the [Game Session tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). + The local run-owned Compose fixture path now reaches this owner transaction through a scheduled Game Session coordinator, explicitly disabled by default. It accepts only a read-only capability file bound to the claimed run and Compose project, one stable operation ID, the fixed demo/production fixture, and the exact development Game Session workload leaf and CA fingerprints; host input supplies no runtime ID, lifecycle epoch, catalog revision, pointer, or World hold identity. Game Session resolves and validates the published Game Design launch descriptor, durably reserves the matching launch identity, and drives World prepare/activate with exact epoch readback so a restart resumes the same launch. The coordinator persists the initial-bind intent before requesting the World hold, then uses the owner-local pointer/audit/outcome transaction and World’s authenticated owner-proof reconciliation; bounded retries reuse the same operation identity, and ambiguous evidence keeps the World termination fence closed. This path is a local Compose fixture bootstrap, not the accepted Account `JOIN` transaction or a production activation path; realm identity and admission-pointer authority remain defined by the [Multi-Tenancy contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract), and explicit join remains owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). See the [run-owned player-flow smoke boundary](../../system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). Cross-service database race/restart proof remains outstanding; implementation and proof state are tracked in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) and [validation workflow](../../../developer-workflows/validation-and-runtime-proof.md). The existing cutover transaction and [replacement hold contract](../world-management-service/api-contracts.md#replacement-cutover-hold-contract) remain distinct; the canonical initial-bind contract is owned by [World](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract). ## Session Front-End and Lease-Owner Routing diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 8449802e8f..7c075a3b3a 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -313,13 +313,13 @@ The authoritative `expiresAt` is a diagnostic and repair trigger only. Expiry ne World Management owns a separate durable one-shot hold for the first admission-pointer bind of an already active realm runtime. It closes the race between proving the target `ACTIVE` and Game Session committing the realm's first admission pointer. It is not a replacement cutover hold, does not add a `world_instance` lifecycle state, and does not make the initial bind a distributed transaction. The normal termination request identity, frozen owner set and registry revision, idempotent cleanup acknowledgements, and final lifecycle compare-and-set remain required after the hold is safely resolved. -One initial-bind execution records one stable control-plane request identity and canonical request digest, one opaque hold identity and equality-only World fence, and the exact `{tenantId, realmId, playableStateNamespaceId, playableStateScope}` binding, the initial no-prior-pointer condition, target `gameInstanceId` and `versionId`, exact target `ACTIVE` lifecycle epoch, and `catalogRevision`. The canonical digest binds the immutable request and realm-target tuple. Exact acquire, read, finalize, abort-proof, and reconciliation retries reuse that identity and fence; a conflicting request cannot silently reuse or replace the hold. The initial-bind condition is distinct from replacement's expected prior pointer/version and does not authorize replacing an existing pointer. +One initial-bind execution records one stable initial-admission request identity and canonical request digest, one opaque hold identity and equality-only World fence, and the exact `{tenantId, realmId, playableStateNamespaceId, playableStateScope}` binding, target `gameInstanceId` and `versionId`, exact target `ACTIVE` lifecycle epoch, and `catalogRevision`. Its origin precondition is either `NO_PRIOR_POINTER` or `EXPECT_CLOSED(pointerVersion, catalogRevision)`. The latter is restricted to the exact targetless, canonical catalog-created pointer that has never been OPEN, as proved atomically by Game Session; missing historical records alone are insufficient. The canonical digest binds the complete scope, origin precondition and realm-target tuple. Exact acquire, read, finalize, abort-proof, and reconciliation retries reuse that identity and fence; a conflicting request cannot silently reuse or replace the hold. Creating the targetless CLOSED catalog pointer needs no ACTIVE-instance hold. Previously OPEN pointers require separate reopen/replacement compatibility and closure/drain proof; this hold cannot bypass that boundary. World acquires the hold in its own database transaction by serializing on the target lifecycle row, checking the exact `ACTIVE` state and epoch, and rejecting a conflicting nonterminal hold. It does not make remote Game Session or catalog reads inside that transaction. Every termination compare-and-set for the target instance, whether initiated by ordinary shutdown or another lifecycle path, must honor absence of a nonterminal initial-bind or replacement hold under the same database serialization. While either hold is nonterminal, termination remains pending and retryable and cannot advance the lifecycle epoch. Once the initial hold is finalized or safely aborted, the existing termination and all-owner cleanup contract continues unchanged. -Game Session owns the initial-bind attempt outcome and the admission pointer. It may create the first pointer only when its local transaction proves that no pointer previously existed for the exact `{tenantId, realmId}` and binds the same hold identity/fence, request identity/digest, namespace/scope, target instance/`versionId`, `ACTIVE` epoch, and `catalogRevision`. That transaction atomically commits the pointer, its matching append-only audit event, and the durable attempt outcome `COMMITTED`. Startup configuration, an admission snapshot, a public raw-pointer RPC, or an external operator write bypass is not lifecycle authority and cannot substitute for this owner transaction. +Game Session owns the initial-bind attempt outcome and the admission pointer. Its local transaction proves the exact origin precondition for `{tenantId, realmId}` and binds the same hold identity/fence, request identity/digest, namespace/scope, target instance/`versionId`, `ACTIVE` epoch, and `catalogRevision`. It atomically creates or advances the pointer, increments `pointerVersion`, and commits its matching append-only audit event and durable attempt outcome `COMMITTED`. Startup configuration, an admission snapshot, a public raw-pointer RPC, or an external operator write bypass is not lifecycle authority and cannot substitute for this owner transaction. -World finalizes only after an authenticated exact Game Session owner readback proves the same hold and request identity/digest, complete realm-target tuple, no-prior-pointer transition, committed pointer, matching audit event, and durable `COMMITTED` outcome. Definitive abort requires an authenticated exact readback of the durable `ABORTED` outcome bound to that same hold and tuple, with storage semantics that prevent any later commit for that attempt; World may then safely abort the hold. Pointer absence, a snapshot, `NOT_FOUND`, `PENDING`, an unavailable read, a tuple or audit mismatch, or contradictory evidence is not abort proof and never releases the hold. Any ambiguous or mismatched result leaves termination fenced and is reconciled automatically from the durable World hold and Game Session attempt record after retries, response loss, or process restart. Timeouts are repair triggers only; no hold is auto-released by elapsed time. +World finalizes only after an authenticated exact Game Session owner readback proves the same hold and request identity/digest, complete realm-target tuple, exact origin transition, committed pointer, matching audit event, and durable `COMMITTED` outcome. Definitive abort requires an authenticated exact readback of the durable `ABORTED` outcome bound to that same hold and tuple, with storage semantics that prevent any later commit for that attempt; World may then safely abort the hold. Pointer absence, a snapshot, `NOT_FOUND`, `PENDING`, an unavailable read, a tuple or audit mismatch, or contradictory evidence is not abort proof and never releases the hold. Any ambiguous or mismatched result leaves termination fenced and is reconciled automatically from the durable World hold and Game Session attempt record after retries, response loss, or process restart. Timeouts are repair triggers only; no hold is auto-released by elapsed time. Current implementation includes the typed `AcquireInitialAdmissionBindHold` RPC restricted to the authenticated Game Session workload, the separate durable World hold record, lifecycle-row serialization that blocks termination while the hold is unresolved, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The run-owned local Compose fixture coordinator now reaches this hold after Game Session records its durable initial-bind intent; the World-owned reconciler resolves it only from authenticated exact owner proof. This remains an opt-in fixture path, not a change to the hold contract or a production activation path. PostgreSQL race/restart proof remains outstanding, and unavailable or mismatched owner evidence continues to fence termination. See the [Game Session initial-admission implementation status](../game-session-service/api-contracts.md#initial-admission-bind), [World Runtime and Movement tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md) for implementation anchors and current proof state, and the [validation and runtime proof workflow](../../../developer-workflows/validation-and-runtime-proof.md) for check selection. The replacement hold contract above remains separate. @@ -327,6 +327,10 @@ Overdue hold diagnostics are observational. World Management emits `world_initia Operator procedure: use the scoped World reconciliation log fields to identify the exact hold, then inspect that World hold and the corresponding authenticated Game Session owner-read evidence against the complete bound identity in this contract. If owner transport or workload identity is unavailable, repair that dependency and retry through the existing scheduled reconciler using the same hold identity. Only exact authenticated `COMMITTED` or definitive `ABORTED` owner proof may resolve the hold. Never edit either database directly, release a hold because its diagnostic age elapsed, fabricate an abort, or use a raw pointer as proof; unavailable or mismatched evidence continues to fence termination. +## Canonical Initial Activation Protection + +World's canonical initial `PREPARING → ACTIVE` transaction consumes the distinct [Account activation-purpose protection](../account-service/api-contracts.md#operator-authorization-references) for the unchanged original StartSession flow. Preparation `COMMITTED`, a current launch read or an ACTIVE-only initial-admission hold cannot substitute. All authenticated Account and Game Session owner reads occur before World SQL. Under its local lifecycle serialization, World exact-compares the retained original binding, `STARTING` launch, `PREPARING` evidence, activation identity and unchanged finite lease, including revalidation after lock waits, before the fenced compare-and-set. It atomically retains the exact terminal result with that transition and exposes authenticated immutable readback for Account settlement. A definitive activation abort must durably exclude any later activation for that same operation; missing rows, pending outcomes, elapsed time and failed reads are not abort proof. Historical recovery returns the original result only, without renewing authority or authorizing another transition. Canonical activation remains denied until genuine producer/consumer and crash, expiry and settlement proof passes; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) owns that implementation gap. + ## Instance Termination Contract World Management owns the authoritative lifecycle row and monotonic epoch for `gameInstanceId` rows. The lifecycle state, owner registry, cleanup acknowledgements, and Temporal boundary are owned by [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); this section records the World API consequence. Teardown is cross-service: diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index fbfecf01d0..fcb2554407 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -234,3 +234,9 @@ Entry format: - Observation: The isolated owning `spotbugsMain` task with `--info` exposed an unnecessary constructor suppression, rather than another runtime defect. Passing test XML did not make the aggregate validation successful. - Expected pattern: Keep the existing assertions and static rules; recover the owning task's diagnostic before editing unrelated callers or adding suppressions. Report test execution and aggregate-gate status separately. - Current status: The channel fixture and unnecessary suppression are corrected, and the canonical Game Session gate passed. Physical PostgreSQL cases remain a separate proof requirement. + +- `2026-10-11`: Repeated missing-field brief replacement was recovered from exact controller history + - Context: Document again selected absent JSON `body` instead of string-valued `brief` while recording the activation decision. The temporary payload contained `null` and an addendum, replacing the standing brief at revision 406 despite the earlier documented lesson. + - Observation: A revision guard proves concurrency safety, not payload completeness. Missing-field fallback must not be used for a required standing brief. + - Expected pattern: Assert that `brief` is a nonempty string before constructing any replacement, and verify preserved content after publication. Use the exact stored revision for recovery rather than reconstructing instructions from memory. + - Current status: Restored the complete revision-405 brief, including Overseer's new standing activation direction, through guarded revision 407. Readback matches the preserved text apart from one final newline; no implementation or authorization was lost. Overseer was notified. 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 da84945afc..9d8b672ba2 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The current construction batch moves the authored initial actor-core source value to Common, adds strict canonical decoding and returns immutable exact bindings from both fresh and stored descriptor success. This is source integrity and an in-memory producer result: the existing descriptor transport still does not carry it, and Entity has no post-publication durable core consumer or allocation proof. Entity's immutable pre-publication EMPTY-source receipt must not be rewritten as post-publication core evidence. The genuine fixture additionally defines native World initial-hold and Account admission-protection acquisition, pending denial, Game Session durable abort and Account exact settlement retry; it has not executed physically and does not establish successful admission. The approved distinct [Account activation-purpose protection](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [World terminal boundary](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-activation-protection) remain to be implemented and proved. Preparation COMMITTED and ACTIVE-only admission semantics remain unchanged, and activation stays denied. + +Corrected complete Common Platform/Account/Game Session/Game Design checks pass in 4 minutes 45 seconds across 243 tasks, with 57 executed and 186 up-to-date. Available corrected-state XML records 4,593 executed unit cases and 40 executed non-container integration/cross-service cases, with zero failures or errors; the final run reuses the immediately preceding passing Common and Account test results. There are 666 skips: 17 Game Session unit cases and 649 container-dependent integration/cross-service cases, including the native genuine-release/admission/settlement composition. Integration compilation, generated SQL metadata, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass; architecture contracts separately pass 228 checks, and Flyway sanity passes 12 sets/307 versioned files. This is local compilation, unit and static proof, not physical PostgreSQL migration, complete original authority, successful OPEN admission, World hold release or runtime activation proof. + The source-local composition replaces the stipulated Game Session launch association with its actual owner STARTING transaction, exact original-tuple/catalog retention and native World-to-Game-Session readback. World carries the actual captured realm/catalog revision into its preparation and association rather than inventing a revision. The corrected Common Platform/Game Session/World/Game Design complete gate passes in 2 minutes 37 seconds across 241 tasks, with 32 executed and 209 up-to-date. Available corrected XML records 3,880 executed unit cases and 29 executed non-container integration/cross-service cases, with zero failures or errors; unchanged tasks reuse earlier successful corrected-state results. There are 603 skips: 17 Game Session unit cases and 586 container-dependent integration/cross-service cases, including all three new launch PostgreSQL cases and the genuine native composition. Both schema-generation checks, integration compilation, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass. Architecture contracts separately pass 228 checks, and Flyway sanity passes 12 sets/306 versioned files. These are local compilation, unit and static results, not physical migration or native owner execution. Account issuer/redeemer fixture contexts and the continuously held commit-authority verifier remain explicit stipulations. All four complete handoffs, lifecycle readiness, actor placement and gameplay admission remain open. The unregistered receiving construction retains the complete immutable published realm-policy set in the canonical Game Design-owned carrier, checking every full policy digest, original source capture and terminal publication binding. Its distinct Game Design read requires the existing Account-confirmed exact-replay association before opening the owner source/policy snapshot. Game Session's bounded fresh `NEW_GAME_ROW`, visible public-production `SHARED` producer atomically retains that source, complete policy evidence, shared namespace and catalog, then independently reads back its original identities and actual catalog revision. Additive V42 does not backfill historical catalog rows or restrict the catalog's general scope vocabulary. The genuine-release definition composes the native Game Design creation read into Game Session's fresh association and its Account-confirmed source/policy read into the actual catalog repository and independent readback. That definition has not executed physically; complete producer/consumer and PostgreSQL proof remain required. The catalog-only producer grants neither launch nor admission authority; the separate STARTING owner construction above remains unregistered and physically unproved. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 47b6a0cf40..a441691349 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for Game Session runtime and tick ## Current Status +The current unregistered canonical initial-admission construction retains the complete original Account protection on the existing V28 intent/terminal boundary through additive V44, with exact V43 launch/catalog and V35 attempt linkage. Its Account-only terminal reader denies missing or pending evidence and independently verifies immutable terminal evidence. The native genuine-release fixture now defines real World initial-hold acquisition, Account protection acquisition, pending no-settlement, durable Game Session abort and exact Account settlement retry. Complete local module checks pass, including 1,988 executed Game Session unit cases and 28 non-container integration/cross-service cases; 17 unit cases and 211 container-dependent cases skip without Docker. The native Game Design composition also skips and has not executed physically. This does not prove the positive runtime transition or OPEN-pointer commit, release the World hold, or enable admission; the existing RUNNING commit prerequisite remains intact. The [authoring tracker](game-authoring-publishing-and-activation.md#current-status) records the composed scope, exact local proof and remaining handoffs. + The unregistered canonical STARTING launch construction now defines one owner transaction retaining the unchanged original Account tuple, complete Game Design descriptor/release pair, actual source-backed catalog identity and newly allocated opaque runtime UUID. Additive V43 keeps historical V26 rows incomplete rather than backfilling them. Independent launch readback and an exact same-namespace World-only receiver expose the captured realm/catalog revision alongside the complete original binding. Complete local module checks pass, including the new unit definitions and compilation of the native genuine-release composition. All three new launch PostgreSQL cases skip without Docker; their migration, atomicity and exact-retry behavior remain physically unproved. Storage and authenticated readback do not establish current Account protection, World ACTIVE readiness, an OPEN pointer or gameplay admission; all runtime registration and activation remain denied. The [authoring tracker](game-authoring-publishing-and-activation.md#current-status) records the composed counts and remaining handoffs. The unregistered fresh-tenant receiver retains Game Design's complete authenticated creation receipt, reserves a private Game Session key and claim atomically, and independently reads back the exact association. Its focused source-local gate passed; all six PostgreSQL cases skipped locally. The fresh public-production catalog batch preserves the complete Game Design-owned published-policy carrier, requires the exact source and one explicit visible `SHARED` policy, and atomically creates the source intake, stable namespace and catalog with complete readback. Additive V42 leaves historical incomplete evidence unavailable rather than backfilling it. A genuine native Game Design-to-Game Session producer/consumer composition is defined but has not executed physically; catalog storage is not a `STARTING` launch, `OPEN` pointer or admission. The [authoring tracker](game-authoring-publishing-and-activation.md#current-status) records the shared producer and proof limits. diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java index fde6bd8b66..41af2b6065 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -27,10 +27,12 @@ import java.util.concurrent.Callable; import javax.crypto.spec.SecretKeySpec; import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalReadClient; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; @@ -297,6 +299,34 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( namespace); } + /** Creates the actual Account admission-protection acquirer over this fixture's retained rows. */ + public AccountStartSessionAdmissionProtectionAcquisitionService + admissionProtectionAcquisitionService( + OriginalStartSessionCurrentAttemptClient gameSessionClient) { + Objects.requireNonNull( + gameSessionClient, "Game Session current-attempt observation client required"); + return new AccountStartSessionAdmissionProtectionAcquisitionService( + authorizationService, + new AccountStartSessionWorldParticipationRepository(accountSources.dsl), + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(accountSources.dsl), + new AccountStartSessionAdmissionProtectionRepository(accountSources.dsl), + gameSessionClient, + accountSources.manager, + namespace); + } + + /** Creates the actual Account terminal settler over this fixture's same retained rows. */ + public AccountStartSessionAdmissionProtectionSettlementService + admissionProtectionSettlementService( + OriginalStartSessionAdmissionTerminalReadClient gameSessionClient) { + Objects.requireNonNull(gameSessionClient, "Game Session terminal-read client required"); + return new AccountStartSessionAdmissionProtectionSettlementService( + new AccountStartSessionAdmissionProtectionRepository(accountSources.dsl), + gameSessionClient, + accountSources.manager, + namespace); + } + /** Existing fixture SQL context for independent test-only retained-row inspection. */ public DSLContext sourceDsl() { return accountSources.dsl; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java similarity index 50% rename from services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBinding.java rename to services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java index c4a8a85854..3fe51441ba 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBinding.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java @@ -1,6 +1,10 @@ -package net.firedevops.firemud.gamedesign.publication; +package net.firedevops.firemud.common.gamedesign; import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; @@ -8,13 +12,11 @@ import java.util.UUID; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; -import net.firedevops.firemud.common.gamedesign.CommandSource; -import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; -import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.publication.AuthoredInitialActorCore; import net.firedevops.firemud.common.publication.RealmEntryPolicy; @@ -140,7 +142,7 @@ public static List resolveAll( byte[] publicationTerminalEvidenceBytes, DraftCommitBinding selectedCommit, net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot, - GameplayRuleSnapshot gameplaySnapshot) { + GameplayRuleSelectedSource gameplaySnapshot) { Objects.requireNonNull(selectedCommit, "selectedCommit"); Objects.requireNonNull(policySnapshot, "policySnapshot"); Objects.requireNonNull(gameplaySnapshot, "gameplaySnapshot"); @@ -173,17 +175,13 @@ public static List resolveAll( return List.of(); } - GameplayRuleSnapshot selectedGameplaySnapshot = - GameplayRuleSnapshot.fromStored(gameplaySnapshot.canonicalJson()); - if (!selectedCommit.equals(selectedGameplaySnapshot.binding()) - || !Arrays.equals( - selectedGameplaySnapshot.canonicalBytes(), gameplaySnapshot.canonicalBytes())) { + if (!selectedCommit.equals(gameplaySnapshot.binding())) { throw new IllegalArgumentException( "GameplayRuleSource snapshot differs from the selected authored commit"); } - byte[] gameplaySnapshotBytes = selectedGameplaySnapshot.canonicalBytes(); - List gameplayEntries = selectedGameplaySnapshot.entries(); - GameplayRuleManifest manifest = GameplayRuleSource.manifest(gameplayEntries); + byte[] gameplaySnapshotBytes = gameplaySnapshot.canonicalBytes(); + List gameplayEntries = gameplaySnapshot.entries(); + GameplayRuleManifest manifest = gameplaySnapshot.manifest(); List result = authoredActorPolicies.stream() @@ -234,6 +232,191 @@ public static List resolveAll( return List.copyOf(result); } + /** + * Decodes and independently reconstructs the exact source frame. This validates structure and + * digest consistency only; it does not authenticate the producer or grant runtime authority. + */ + public static AuthoredInitialActorCoreSourceBinding fromStored( + byte[] originalCanonicalBytes, String expectedDigest) { + byte[] stored = requireBytes(originalCanonicalBytes, "authored actor core binding").clone(); + if (expectedDigest == null + || !expectedDigest.matches("sha256:[0-9a-f]{64}") + || !CommandSource.sha256(stored).equals(expectedDigest)) { + throw new IllegalArgumentException("Authored actor core binding digest differs"); + } + + FrameReader reader = new FrameReader(stored); + reader.expect(SCHEMA); + reader.expect("1"); + UUID worldSourceOperationId = reader.uuid(); + String worldSourceEvidenceDigest = reader.text(); + String expectedWorldSlug = reader.text(); + String publicationWorkflowId = reader.text(); + + String tenantId = reader.text(); + String versionId = reader.text(); + String versionRowId = reader.text(); + String versionTenantKey = reader.text(); + String sourceGameRowId = reader.text(); + String sourceGameTenantKey = reader.text(); + String sourceProvenanceKind = reader.text(); + UUID selectedCommitId = reader.uuid(); + String selectedCommitDigest = reader.text(); + byte[] selectedCommitBytes = reader.bytes(); + DraftCommitBinding selectedCommit; + try { + selectedCommit = + DraftCommitBinding.fromStored(strictUtf8(selectedCommitBytes), selectedCommitDigest); + } catch (IllegalStateException corrupt) { + throw new IllegalArgumentException("Selected commit source is corrupt", corrupt); + } + var target = selectedCommit.target(); + requireFrameEquals(target.canonicalTenantId().toString(), tenantId, "tenant"); + requireFrameEquals(target.canonicalVersionId().toString(), versionId, "version"); + requireFrameEquals( + Long.toString(target.gameDesignVersionRowId()), versionRowId, "Game Design version row"); + requireFrameEquals(target.gameDesignVersionTenantKey(), versionTenantKey, "version tenant key"); + requireFrameEquals(Long.toString(target.sourceGameRowId()), sourceGameRowId, "source game row"); + requireFrameEquals(target.sourceGameTenantKey(), sourceGameTenantKey, "source game tenant key"); + requireFrameEquals(target.sourceProvenanceKind(), sourceProvenanceKind, "source provenance"); + if (!selectedCommit.commitId().equals(selectedCommitId) + || !Arrays.equals(selectedCommit.canonicalBytes(), selectedCommitBytes)) { + throw new IllegalArgumentException("Selected commit frame differs from its canonical source"); + } + + byte[] publicationOperationBytes = reader.bytes(); + byte[] publicationTerminalEvidenceBytes = reader.bytes(); + byte[] policySnapshotBytes = reader.bytes(); + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot; + try { + policySnapshot = + net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot.fromStored( + strictUtf8(policySnapshotBytes)); + } catch (IllegalStateException corrupt) { + throw new IllegalArgumentException("Policy source snapshot is corrupt", corrupt); + } + if (!selectedCommit.equals(policySnapshot.binding()) + || !Arrays.equals(policySnapshot.canonicalBytes(), policySnapshotBytes)) { + throw new IllegalArgumentException("Policy snapshot differs from the selected commit"); + } + + UUID policyCommitId = reader.uuid(); + UUID policyRevisionId = reader.uuid(); + String policyLogicalRevisionId = reader.text(); + byte[] policyBytes = reader.bytes(); + String policyJson = strictUtf8(policyBytes); + List matchingPolicies = + policySnapshot.policies().stream() + .filter(value -> value.commitId().equals(policyCommitId)) + .filter(value -> value.revisionId().equals(policyRevisionId)) + .filter(value -> value.logicalRevisionId().equals(policyLogicalRevisionId)) + .filter(value -> value.policy().canonicalJson().equals(policyJson)) + .toList(); + if (matchingPolicies.size() != 1) { + throw new IllegalArgumentException("Policy source is absent or ambiguous in its snapshot"); + } + RealmPolicySource.Policy policySource = matchingPolicies.getFirst(); + var policy = policySource.policy(); + if (policy.schemaVersion() != RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PLAYER_CREATED + || policy.creationDescriptor() == null + || policy.initialActorCore() == null) { + throw new IllegalArgumentException("Schema-three authored actor core policy is required"); + } + var descriptor = policy.creationDescriptor(); + requireFrameEquals(descriptor.descriptorId(), reader.uuid().toString(), "descriptor identity"); + requireFrameEquals( + descriptor.descriptorRevisionId(), reader.uuid().toString(), "descriptor revision"); + byte[] descriptorBytes = reader.bytes(); + if (!Arrays.equals(descriptor.canonicalBytes(), descriptorBytes)) { + throw new IllegalArgumentException("Descriptor bytes differ from the authored policy"); + } + String coreJson = reader.text(); + AuthoredInitialActorCore core = Objects.requireNonNull(policy.initialActorCore()); + if (!core.canonicalJson().equals(coreJson)) { + throw new IllegalArgumentException("Actor core differs from the authored policy"); + } + + byte[] gameplaySnapshotBytes = reader.bytes(); + GameplayRuleSelectedSource gameplaySnapshot; + try { + gameplaySnapshot = new GameplayRuleSelectedSource(strictUtf8(gameplaySnapshotBytes)); + } catch (IllegalStateException corrupt) { + throw new IllegalArgumentException("Gameplay rule source snapshot is corrupt", corrupt); + } + if (!selectedCommit.equals(gameplaySnapshot.binding()) + || !Arrays.equals(gameplaySnapshot.canonicalBytes(), gameplaySnapshotBytes)) { + throw new IllegalArgumentException("Gameplay rules differ from the selected commit"); + } + byte[] manifestBytes = reader.bytes(); + if (!Arrays.equals(gameplaySnapshot.manifest().canonicalBytes(), manifestBytes)) { + throw new IllegalArgumentException("Gameplay manifest differs from its selected source"); + } + + String dispositionKey = reader.text(); + byte[] dispositionBytes = reader.bytes(); + EntryFrame dispositionFrame = reader.entry(); + String feedbackKey = reader.text(); + byte[] feedbackBytes = reader.bytes(); + EntryFrame feedbackFrame = reader.entry(); + reader.requireEnd(); + + List entries = gameplaySnapshot.entries(); + List dispositions = + entries.stream() + .filter(value -> value.family() == Family.DISPOSITIONS) + .filter(value -> value.definition().key().equals(core.dispositionKey())) + .toList(); + if (dispositions.size() != 1 + || !(dispositions.getFirst().definition() instanceof Disposition disposition) + || !disposition.dispositionKey().equals(dispositionKey) + || !Arrays.equals( + GameplayRuleManifest.canonical(disposition).getBytes(StandardCharsets.UTF_8), + dispositionBytes)) { + throw new IllegalArgumentException("Selected disposition differs from its source entry"); + } + GameplayRuleSource.Entry dispositionEntry = dispositions.getFirst(); + requireEntryFrame(dispositionFrame, dispositionEntry); + + List feedbackEntries = + entries.stream() + .filter(value -> value.family() == Family.FEEDBACK) + .filter(value -> value.definition().key().equals(disposition.safeFeedbackKey())) + .toList(); + if (feedbackEntries.size() != 1 + || !(feedbackEntries.getFirst().definition() instanceof Feedback safeFeedback) + || !safeFeedback.feedbackKey().equals(feedbackKey) + || !Arrays.equals( + GameplayRuleManifest.canonical(safeFeedback).getBytes(StandardCharsets.UTF_8), + feedbackBytes)) { + throw new IllegalArgumentException("Mandatory FEEDBACK differs from its source entry"); + } + GameplayRuleSource.Entry feedbackEntry = feedbackEntries.getFirst(); + requireEntryFrame(feedbackFrame, feedbackEntry); + + AuthoredInitialActorCoreSourceBinding decoded = + new AuthoredInitialActorCoreSourceBinding( + worldSourceOperationId, + worldSourceEvidenceDigest, + expectedWorldSlug, + publicationWorkflowId, + publicationOperationBytes, + publicationTerminalEvidenceBytes, + selectedCommit, + policySnapshotBytes, + policySource, + gameplaySnapshotBytes, + gameplaySnapshot.manifest(), + dispositionEntry, + disposition, + feedbackEntry, + safeFeedback); + if (!Arrays.equals(decoded.canonicalBytes, stored) || !decoded.digest.equals(expectedDigest)) { + throw new IllegalArgumentException("Authored actor core binding bytes changed on decode"); + } + return decoded; + } + public UUID worldSourceOperationId() { return worldSourceOperationId; } @@ -293,9 +476,111 @@ private static void frameEntry(ByteArrayOutputStream output, GameplayRuleSource. DraftAuthorizationFenceBinding.frame(output, entry.revisionId().toString()); } - private static void requireBytes(byte[] value, String label) { + private static void requireEntryFrame(EntryFrame frame, GameplayRuleSource.Entry entry) { + if (!frame.family().equals(entry.family().name()) + || !Arrays.equals( + frame.definitionBytes(), + GameplayRuleManifest.canonical(entry.definition()).getBytes(StandardCharsets.UTF_8)) + || !frame.sourceBindingDigest().equals(entry.sourceBinding().digest()) + || !Arrays.equals(frame.sourceBindingBytes(), entry.sourceBinding().canonicalBytes()) + || !frame.revisionOrder().equals(entry.revisionOrder()) + || !frame.revisionId().equals(entry.revisionId().toString())) { + throw new IllegalArgumentException("Selected rule entry provenance differs"); + } + } + + private static void requireFrameEquals(String expected, String actual, String label) { + if (!Objects.equals(expected, actual)) { + throw new IllegalArgumentException("Authored actor core " + label + " frame differs"); + } + } + + private static String strictUtf8(byte[] value) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(value)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IllegalArgumentException( + "Authored actor core source contains invalid UTF-8", malformed); + } + } + + private static byte[] requireBytes(byte[] value, String label) { if (value == null || value.length == 0) { throw new IllegalArgumentException("Exact " + label + " bytes are required"); } + return value; + } + + private record EntryFrame( + String family, + byte[] definitionBytes, + String sourceBindingDigest, + byte[] sourceBindingBytes, + String revisionOrder, + String revisionId) {} + + private static final class FrameReader { + private final byte[] stored; + private int offset; + + private FrameReader(byte[] stored) { + this.stored = stored; + } + + private void expect(String expected) { + if (!expected.equals(text())) { + throw new IllegalArgumentException("Unsupported authored actor core source frame"); + } + } + + private String text() { + return strictUtf8(bytes()); + } + + private UUID uuid() { + String value = text(); + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException("Canonical UUID frame required", invalid); + } + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil UUID frame required"); + } + return parsed; + } + + private byte[] bytes() { + if (stored.length - offset < Integer.BYTES) { + throw new IllegalArgumentException("Incomplete authored actor core frame length"); + } + int length = + ByteBuffer.wrap(stored, offset, Integer.BYTES).order(ByteOrder.BIG_ENDIAN).getInt(); + offset += Integer.BYTES; + if (length < 0 || length > stored.length - offset) { + throw new IllegalArgumentException("Invalid authored actor core frame length"); + } + byte[] value = Arrays.copyOfRange(stored, offset, offset + length); + offset += length; + return value; + } + + private EntryFrame entry() { + String family = text(); + Family.valueOf(family); + return new EntryFrame(family, bytes(), text(), bytes(), text(), text()); + } + + private void requireEnd() { + if (offset != stored.length) { + throw new IllegalArgumentException("Trailing authored actor core source bytes"); + } + } } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java index 1cf9399f79..1a6e1514c5 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java @@ -8,6 +8,7 @@ import java.util.Set; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; /** Closed GD owner export. Structure and digest are not authentication of its producer. */ public record GameplayRuleSelectedSource(String snapshotJson) { @@ -40,6 +41,45 @@ public record GameplayRuleSelectedSource(String snapshotJson) { new EnumMap<>(GameplayRuleManifest.Family.class); for (var family : GameplayRuleManifest.Family.values()) inventory.put(family, new ArrayList<>()); + for (var entry : parseEntries(root, binding)) + inventory.get(entry.family()).add(entry.definition()); + if (!manifest.equals(new GameplayRuleManifest(inventory)) + || !snapshotJson.equals(GameplayRuleManifest.canonical(root))) + throw new IllegalArgumentException("Selected manifest differs from complete snapshot"); + } + + public DraftCommitBinding binding() { + var root = GameplayRuleManifest.tree(snapshotJson); + return DraftCommitBinding.fromStored(text(root, "bindingJson"), text(root, "bindingDigest")); + } + + public GameplayRuleManifest manifest() { + return GameplayRuleManifest.fromStored( + text(GameplayRuleManifest.tree(snapshotJson), "manifestJson")); + } + + /** Exact immutable owner entries after the constructor's complete closed-source validation. */ + public List entries() { + return parseEntries(GameplayRuleManifest.tree(snapshotJson), binding()); + } + + public byte[] canonicalBytes() { + return snapshotJson.getBytes(StandardCharsets.UTF_8); + } + + public String digest() { + return GameplayRuleManifest.sha256(canonicalBytes()); + } + + private static String text(tools.jackson.databind.JsonNode node, String name) { + if (!node.path(name).isTextual()) + throw new IllegalArgumentException("Text source field required"); + return node.path(name).textValue(); + } + + private static List parseEntries( + tools.jackson.databind.JsonNode root, DraftCommitBinding binding) { + List result = new ArrayList<>(); for (var entry : root.path("entries")) { GameplayRuleManifest.fields( entry, @@ -54,8 +94,8 @@ public record GameplayRuleSelectedSource(String snapshotJson) { var origin = DraftCommitBinding.fromStored( text(entry, "sourceBindingJson"), text(entry, "sourceBindingDigest")); - if (!origin.target().equals(binding.target()) - || !text(entry, "revisionOrder").matches("0|[1-9][0-9]*")) + String revisionOrder = text(entry, "revisionOrder"); + if (!origin.target().equals(binding.target()) || !revisionOrder.matches("0|[1-9][0-9]*")) throw new IllegalArgumentException("Selected rule provenance differs"); String revisionId = text(entry, "revisionId"); DraftAuthorizationFenceBinding.canonicalUuid(revisionId); @@ -67,40 +107,16 @@ public record GameplayRuleSelectedSource(String snapshotJson) { revision -> revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE && revision.revisionId().toString().equals(revisionId) - && revision.revisionOrder().equals(text(entry, "revisionOrder")) + && revision.revisionOrder().equals(revisionOrder) && expectedPayload.equals( GameplayRuleManifest.canonical( GameplayRuleManifest.tree(revision.payload())))); if (!originalRevision) throw new IllegalArgumentException("Rule entry lacks exact original UPSERT revision"); - inventory.get(family).add(definition); + result.add( + new GameplayRuleSource.Entry( + family, definition, origin, revisionOrder, java.util.UUID.fromString(revisionId))); } - if (!manifest.equals(new GameplayRuleManifest(inventory)) - || !snapshotJson.equals(GameplayRuleManifest.canonical(root))) - throw new IllegalArgumentException("Selected manifest differs from complete snapshot"); - } - - public DraftCommitBinding binding() { - var root = GameplayRuleManifest.tree(snapshotJson); - return DraftCommitBinding.fromStored(text(root, "bindingJson"), text(root, "bindingDigest")); - } - - public GameplayRuleManifest manifest() { - return GameplayRuleManifest.fromStored( - text(GameplayRuleManifest.tree(snapshotJson), "manifestJson")); - } - - public byte[] canonicalBytes() { - return snapshotJson.getBytes(StandardCharsets.UTF_8); - } - - public String digest() { - return GameplayRuleManifest.sha256(canonicalBytes()); - } - - private static String text(tools.jackson.databind.JsonNode node, String name) { - if (!node.path(name).isTextual()) - throw new IllegalArgumentException("Text source field required"); - return node.path(name).textValue(); + return List.copyOf(result); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java similarity index 79% rename from services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBindingTest.java rename to services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java index e581350a02..c359e041bc 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreSourceBindingTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java @@ -1,21 +1,22 @@ -package net.firedevops.firemud.gamedesign.publication; +package net.firedevops.firemud.common.gamedesign; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.io.ByteArrayOutputStream; import java.math.BigDecimal; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; -import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; -import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Definition; @@ -25,6 +26,7 @@ import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PrimitiveKind; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stat; import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import org.junit.jupiter.api.Test; import tools.jackson.databind.json.JsonMapper; @@ -73,11 +75,99 @@ void bindsExactPolicyAndGameplaySnapshotsWithFullDispositionFeedbackProvenance() new String( fixture .gameplaySnapshot() - .canonicalJson() + .snapshotJson() .getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1))); } + @Test + void strictDecoderRoundTripsExactBindingAndDefensivelyCopiesItsBytes() { + var original = fixture(List.of()).resolve().getFirst(); + byte[] bytes = original.canonicalBytes(); + var decoded = AuthoredInitialActorCoreSourceBinding.fromStored(bytes, original.digest()); + + assertThat(decoded.canonicalBytes()).isEqualTo(bytes); + assertThat(decoded.digest()).isEqualTo(original.digest()); + assertThat(decoded.core()).isEqualTo(original.core()); + assertThat(decoded.disposition()).isEqualTo(original.disposition()); + assertThat(decoded.safeFeedback()).isEqualTo(original.safeFeedback()); + + bytes[0] ^= 0x01; + assertThat(decoded.canonicalBytes()).isEqualTo(original.canonicalBytes()); + byte[] exposed = decoded.canonicalBytes(); + exposed[0] ^= 0x01; + assertThat(decoded.canonicalBytes()).isEqualTo(original.canonicalBytes()); + assertThatThrownBy( + () -> + AuthoredInitialActorCoreSourceBinding.fromStored( + original.canonicalBytes(), digest('0'))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest differs"); + } + + @Test + void strictDecoderRejectsUnknownSchemaTrailingFramesAndSubstitutedPolicySource() { + var original = fixture(List.of()).resolve().getFirst(); + byte[] canonicalBytes = original.canonicalBytes(); + + var unknownSchema = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(unknownSchema, "unknown-authored-core-binding/v9"); + byte[] unknownBytes = unknownSchema.toByteArray(); + assertThatThrownBy( + () -> + AuthoredInitialActorCoreSourceBinding.fromStored( + unknownBytes, CommandSource.sha256(unknownBytes))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source frame"); + + var trailingFrame = new ByteArrayOutputStream(); + trailingFrame.writeBytes(canonicalBytes); + DraftAuthorizationFenceBinding.frame(trailingFrame, "unexpected"); + byte[] trailingBytes = trailingFrame.toByteArray(); + assertThatThrownBy( + () -> + AuthoredInitialActorCoreSourceBinding.fromStored( + trailingBytes, CommandSource.sha256(trailingBytes))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Trailing"); + + List frames = splitFrames(canonicalBytes); + String policySnapshot = new String(frames.get(18), StandardCharsets.UTF_8); + assertThat(policySnapshot).contains("Wayfarer"); + frames.set(18, policySnapshot.replace("Wayfarer", "Wanderer").getBytes(StandardCharsets.UTF_8)); + byte[] substitutedBytes = joinFrames(frames); + assertThatThrownBy( + () -> + AuthoredInitialActorCoreSourceBinding.fromStored( + substitutedBytes, CommandSource.sha256(substitutedBytes))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Policy source"); + + frames = splitFrames(canonicalBytes); + String gameplaySnapshot = new String(frames.get(27), StandardCharsets.UTF_8); + assertThat(gameplaySnapshot).contains("newcomer"); + frames.set( + 27, gameplaySnapshot.replace("newcomer", "intruder").getBytes(StandardCharsets.UTF_8)); + byte[] corruptRulesBytes = joinFrames(frames); + assertThatThrownBy( + () -> + AuthoredInitialActorCoreSourceBinding.fromStored( + corruptRulesBytes, CommandSource.sha256(corruptRulesBytes))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Gameplay rule source"); + + var changedSelectedCommit = withForeignWorldPolicy(fixture(List.of())).resolve().getFirst(); + frames = splitFrames(canonicalBytes); + frames.set(27, splitFrames(changedSelectedCommit.canonicalBytes()).get(27)); + byte[] changedRulesBytes = joinFrames(frames); + assertThatThrownBy( + () -> + AuthoredInitialActorCoreSourceBinding.fromStored( + changedRulesBytes, CommandSource.sha256(changedRulesBytes))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Gameplay rules differ"); + } + @Test void changedSourceOperationChangesTheBindingAndDifferentWorldDoesNotSubstitute() { Fixture fixture = fixture(List.of()); @@ -217,7 +307,7 @@ void rejectsPolicyOrRuleSnapshotsFromAnotherSelectedCommit() { String changedRuleSnapshot = fixture .gameplaySnapshot() - .canonicalJson() + .snapshotJson() .replace("\"sourceEpoch\":\"1\"", "\"sourceEpoch\":\"2\""); var changedRuleSource = resolve( @@ -225,7 +315,7 @@ void rejectsPolicyOrRuleSnapshotsFromAnotherSelectedCommit() { SOURCE_OPERATION, "world", fixture.policySnapshot(), - GameplayRuleSnapshot.fromStored(changedRuleSnapshot)) + new GameplayRuleSelectedSource(changedRuleSnapshot)) .getFirst(); assertThat(changedRuleSource.digest()).isNotEqualTo(fixture.resolve().getFirst().digest()); } @@ -236,10 +326,10 @@ void rejectsAuthoredPresenceAddedToTheClosedSelectedGameplaySnapshot() { String changedSnapshot = fixture .gameplaySnapshot() - .canonicalJson() + .snapshotJson() .replace("{\"bindingDigest\":", "{\"presence\":\"ACTIVE\",\"bindingDigest\":"); - assertThatThrownBy(() -> GameplayRuleSnapshot.fromStored(changedSnapshot)) + assertThatThrownBy(() -> new GameplayRuleSelectedSource(changedSnapshot)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unknown or missing"); } @@ -249,7 +339,7 @@ void rejectsMissingDispositionOrFeedbackAndPreservesOtherAuthoredRuleFamilies() Fixture fixture = fixture(List.of()); var feedbackOnly = List.of(fixture.entries().getLast()); var feedbackOnlySnapshot = - GameplayRuleSnapshot.fromStored(snapshot(fixture.binding(), feedbackOnly)); + new GameplayRuleSelectedSource(snapshot(fixture.binding(), feedbackOnly)); assertThatThrownBy( () -> resolve( @@ -454,7 +544,7 @@ private static List resolve( UUID sourceOperation, String expectedWorldSlug, net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot policySnapshot, - GameplayRuleSnapshot gameplaySnapshot) { + GameplayRuleSelectedSource gameplaySnapshot) { return AuthoredInitialActorCoreSourceBinding.resolveAll( sourceOperation, digest('a'), @@ -471,7 +561,7 @@ private static String snapshot( DraftCommitBinding binding, List entries) { return GameplayRuleManifest.canonical( Map.of( - "schema", GameplayRuleSnapshot.SCHEMA, + "schema", "game-design-gameplay-rule-source-snapshot/v1", "bindingJson", binding.canonicalJson(), "bindingDigest", binding.digest(), "sourceEpoch", "1", @@ -481,6 +571,24 @@ private static String snapshot( "entries", entries.stream().map(GameplayRuleSource.Entry::object).toList())); } + private static List splitFrames(byte[] encoded) { + List result = new ArrayList<>(); + ByteBuffer input = ByteBuffer.wrap(encoded); + while (input.hasRemaining()) { + int length = input.getInt(); + byte[] value = new byte[length]; + input.get(value); + result.add(value); + } + return result; + } + + private static byte[] joinFrames(List frames) { + ByteArrayOutputStream result = new ByteArrayOutputStream(); + for (byte[] frame : frames) DraftAuthorizationFenceBinding.frame(result, frame); + return result.toByteArray(); + } + private static String policyJson() { return "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," @@ -546,8 +654,8 @@ private record Fixture( entries = List.copyOf(entries); } - private GameplayRuleSnapshot gameplaySnapshot() { - return GameplayRuleSnapshot.fromStored(rulesJson); + private GameplayRuleSelectedSource gameplaySnapshot() { + return new GameplayRuleSelectedSource(rulesJson); } private List resolve() { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java index f33a80ba30..ca085d16c2 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java @@ -8,6 +8,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; @@ -15,6 +16,7 @@ import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; @@ -219,7 +221,8 @@ private OwnerOutcome writeOrRead( requireSuccessfulDescriptor(descriptor); ResolvedLaunchDescriptorDto resolved = readStored(descriptor, descriptorRequest, requestJson, source, sourceJson); - return OwnerOutcome.succeeded(new ResolvedBinding(exactRequest, exact, resolved)); + return OwnerOutcome.succeeded( + new ResolvedBinding(exactRequest, exact, resolved, capturedTemplate.actorCoreBindings())); } if (descriptors @@ -333,7 +336,8 @@ private OwnerOutcome writeOrRead( } ResolvedLaunchDescriptorDto resolved = readStored(persisted, descriptorRequest, requestJson, source, sourceJson); - return OwnerOutcome.succeeded(new ResolvedBinding(exactRequest, exact, resolved)); + return OwnerOutcome.succeeded( + new ResolvedBinding(exactRequest, exact, resolved, capturedTemplate.actorCoreBindings())); } private CapturedTemplate requireCapturedTemplate(Result exact, long templateId) { @@ -417,31 +421,34 @@ private CapturedTemplate requireCapturedTemplate(Result exact, long templateId) || !row.worldSlug().equals(publicAssociation.worldSlug())) { throw conflict("Retained association row differs from the public pinned association"); } - CapturedTemplate capturedTemplate = - new CapturedTemplate( - unsupported, - selectedGameplayRules.receiptBinding(), - selection.selectedCommit(), - capture.policy().snapshot().shared(), - selectedGameplayRules.snapshot(), - operation.workflowId(), - operation.canonicalBytes(), - readback.terminalEvidenceBytes()); + var policySnapshot = capture.policy().snapshot().shared(); + var gameplayRules = selectedGameplayRules.snapshot(); + List actorCoreBindings; try { - resolveSelectedAuthoredInitialActorCoreSources( - exact.association().sourceOperationId(), - exact.association().sourceEvidenceDigest(), - exact.association().worldSlug(), - capturedTemplate.publicationWorkflowId(), - capturedTemplate.publicationOperationBytes(), - capturedTemplate.publicationTerminalEvidenceBytes(), - capturedTemplate.selectedCommit(), - capturedTemplate.policySnapshot(), - capturedTemplate.gameplayRules()); + actorCoreBindings = + resolveSelectedAuthoredInitialActorCoreSources( + exact.association().sourceOperationId(), + exact.association().sourceEvidenceDigest(), + exact.association().worldSlug(), + operation.workflowId(), + operation.canonicalBytes(), + readback.terminalEvidenceBytes(), + selection.selectedCommit(), + policySnapshot, + gameplayRules); } catch (IllegalArgumentException invalidActorCoreSource) { throw conflict("Selected authored initial actor core differs from exact published source"); } - return capturedTemplate; + return new CapturedTemplate( + unsupported, + selectedGameplayRules.receiptBinding(), + selection.selectedCommit(), + policySnapshot, + gameplayRules, + operation.workflowId(), + operation.canonicalBytes(), + readback.terminalEvidenceBytes(), + actorCoreBindings); } static List resolveSelectedAuthoredInitialActorCoreSources( @@ -464,7 +471,7 @@ static List resolveSelectedAuthoredInitia publicationTerminalEvidenceBytes, selectedCommit, policySnapshot, - gameplayRules); + new GameplayRuleSelectedSource(gameplayRules.canonicalJson())); } /** @@ -1065,14 +1072,19 @@ private static StatusRuntimeException conflict(String description) { } /** - * Returned to the caller so Game Session can atomically pin this descriptor with the association. + * Exact selected-release descriptor and its independently validated authored actor-core sources. */ public record ResolvedBinding( - Request request, Result associationRead, ResolvedLaunchDescriptorDto descriptor) { + Request request, + Result associationRead, + ResolvedLaunchDescriptorDto descriptor, + List actorCoreBindings) { public ResolvedBinding { Objects.requireNonNull(request, "request"); Objects.requireNonNull(associationRead, "associationRead"); Objects.requireNonNull(descriptor, "descriptor"); + actorCoreBindings = + List.copyOf(Objects.requireNonNull(actorCoreBindings, "actorCoreBindings")); if (!request.equals(associationRead.request()) || !request .decodedTuple() @@ -1091,6 +1103,31 @@ public record ResolvedBinding( throw new IllegalArgumentException( "Resolved descriptor differs from exact StartSession binding"); } + var association = associationRead.association(); + var authoredWorld = descriptor.authoredWorldBinding(); + for (var actorCore : actorCoreBindings) { + var selected = actorCore.selectedCommit(); + if (!actorCore.worldSourceOperationId().equals(association.sourceOperationId()) + || !actorCore.worldSourceEvidenceDigest().equals(association.sourceEvidenceDigest()) + || !actorCore.expectedWorldSlug().equals(association.worldSlug()) + || !actorCore.publicationWorkflowId().equals(association.publishWorkflowId()) + || !selected.target().canonicalTenantId().equals(association.canonicalTenantId()) + || !selected.target().canonicalVersionId().equals(association.canonicalVersionId()) + || !selected.commitId().equals(association.selectedCommitId()) + || !actorCore.expectedWorldSlug().equals(authoredWorld.worldSlug()) + || !actorCore + .worldSourceOperationId() + .equals(authoredWorld.authoredWorldSourceOperationId()) + || !actorCore + .worldSourceEvidenceDigest() + .equals(authoredWorld.authoredWorldSourceEvidenceDigest()) + || !selected.target().canonicalTenantId().equals(authoredWorld.canonicalTenantId()) + || selected.target().gameDesignVersionRowId() != authoredWorld.versionId() + || association.templateId() != authoredWorld.gameTemplateId()) { + throw new IllegalArgumentException( + "Authored actor core differs from the exact selected StartSession release"); + } + } } } @@ -1134,7 +1171,8 @@ private record CapturedTemplate( GameplayRuleSnapshot gameplayRules, String publicationWorkflowId, byte[] publicationOperationBytes, - byte[] publicationTerminalEvidenceBytes) { + byte[] publicationTerminalEvidenceBytes, + List actorCoreBindings) { private CapturedTemplate { Objects.requireNonNull(gameLogicReceipt, "gameLogicReceipt"); Objects.requireNonNull(selectedCommit, "selectedCommit"); @@ -1147,6 +1185,8 @@ private record CapturedTemplate( Objects.requireNonNull( publicationTerminalEvidenceBytes, "publicationTerminalEvidenceBytes") .clone(); + actorCoreBindings = + List.copyOf(Objects.requireNonNull(actorCoreBindings, "actorCoreBindings")); if (!selectedCommit.equals(policySnapshot.binding()) || !selectedCommit.equals(gameplayRules.binding())) { throw new IllegalArgumentException("Captured source differs from selected commit"); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/CanonicalInitialAdmissionHoldTransportFixture.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/CanonicalInitialAdmissionHoldTransportFixture.java new file mode 100644 index 0000000000..8cecad0025 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/CanonicalInitialAdmissionHoldTransportFixture.java @@ -0,0 +1,186 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +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.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.v1.AcquireCanonicalInitialAdmissionHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInitialAdmissionHoldServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS transport for the native original-admission integration proof. */ +final class CanonicalInitialAdmissionHoldTransportFixture implements AutoCloseable { + private static final int MAX_REQUEST_BYTES = 64 * 1024; + private static final int MAX_RESPONSE_BYTES = 64 * 1024; + private static final long DEADLINE_SECONDS = 5L; + + private final ManagedChannel channel; + private final WorldCanonicalInitialAdmissionHoldServiceGrpc + .WorldCanonicalInitialAdmissionHoldServiceBlockingStub + stub; + private final String workloadNamespace; + private boolean closed; + + CanonicalInitialAdmissionHoldTransportFixture( + String endpoint, + int port, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) + throws SSLException { + if (endpoint == null || endpoint.isBlank()) { + throw new IllegalArgumentException("World Management endpoint is required"); + } + if (port <= 0 || port > 65535) { + throw new IllegalArgumentException("World Management port must be valid"); + } + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = namespace; + this.channel = + Objects.requireNonNull(channels, "gRPC channel factory required") + .buildChannel(endpoint, port, requireFileBackedMutualTls(tls), false); + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + this.stub = + WorldCanonicalInitialAdmissionHoldServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(MAX_RESPONSE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)); + } + + HoldIdentity acquire( + Request request, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleSelector) { + if (closed) { + throw new IllegalStateException("World initial-admission hold transport is closed"); + } + Objects.requireNonNull(request, "complete World initial-admission hold request required"); + Objects.requireNonNull(lifecycleSelector, "complete World lifecycle read selector required"); + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException( + "World initial-admission hold transport requires a workload-only caller context"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World initial-admission hold acquisition must run outside ambient SQL"); + } + requireConfiguredTarget(request, lifecycleSelector); + + var wireRequest = + AcquireCanonicalInitialAdmissionHoldRequest.newBuilder() + .setCanonicalHoldRequestBytes( + com.google.protobuf.ByteString.copyFrom(request.canonicalRequestBytes())) + .setCanonicalLifecycleReadRequestBytes( + com.google.protobuf.ByteString.copyFrom(lifecycleSelector.canonicalBytes())) + .build(); + requireBound(wireRequest.getSerializedSize(), MAX_REQUEST_BYTES, "hold request"); + var response = + stub.withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS) + .acquireCanonicalInitialAdmissionHold(wireRequest); + requireBound(response.getSerializedSize(), MAX_RESPONSE_BYTES, "hold response"); + if (!response.getUnknownFields().asMap().isEmpty() + || response.getHoldIdentityBytes().isEmpty()) { + throw new IllegalStateException("World returned an incomplete canonical hold response"); + } + + byte[] retainedBytes = response.getHoldIdentityBytes().toByteArray(); + HoldIdentity identity; + try { + identity = HoldIdentity.fromStored(retainedBytes); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException("World returned an invalid canonical hold identity", invalid); + } + if (!request.equals(identity.request()) + || !Arrays.equals(request.canonicalRequestBytes(), identity.canonicalRequestBytes()) + || !workloadNamespace.equals(identity.request().targetNamespace())) { + throw new IllegalStateException( + "World returned a hold identity substituted from the exact request or namespace"); + } + return identity; + } + + @Override + public void close() throws InterruptedException { + if (closed) { + return; + } + closed = true; + channel.shutdownNow(); + if (!channel.awaitTermination(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("World initial-admission hold channel did not terminate"); + } + } + + private void requireConfiguredTarget( + Request request, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleSelector) { + if (!workloadNamespace.equals(request.targetNamespace()) + || !workloadNamespace.equals(lifecycleSelector.targetNamespace())) { + throw new IllegalArgumentException( + "World hold and lifecycle selectors must use the configured namespace"); + } + if (!request.canonicalTenantId().equals(lifecycleSelector.canonicalTenantId()) + || !request.worldSlug().equals(lifecycleSelector.worldSlug()) + || !request.playableStateNamespaceId().equals(lifecycleSelector.playableStateNamespaceId()) + || !request.playableStateScope().equals(lifecycleSelector.playableStateScope()) + || !request.canonicalGameInstanceId().equals(lifecycleSelector.canonicalGameInstanceId()) + || !request.canonicalVersionId().equals(lifecycleSelector.canonicalVersionId()) + || !lifecycleSelector.publicProduction()) { + throw new IllegalArgumentException( + "World lifecycle selector differs from the complete initial-admission hold target"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMutualTls( + CommonGrpcClientProperties tls) { + if (tls == null || tls.isPlaintext()) { + throw new IllegalArgumentException("World initial-admission hold transport requires mTLS"); + } + requireReadableFile(tls.getCertChain(), "certificate chain"); + requireReadableFile(tls.getPrivateKey(), "private key"); + requireReadableFile(tls.getCaCert(), "CA certificate"); + return tls; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "World initial-admission hold transport requires file-backed TLS material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World initial-admission hold transport requires file-backed TLS material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World initial-admission hold " + label + " must be file-backed", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World initial-admission hold " + label + " must be an existing readable file"); + } + } + + private static void requireBound(int size, int maximum, String field) { + if (size <= 0 || size > maximum) { + throw new IllegalArgumentException(field + " is empty or exceeds its byte bound"); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index a0b69b95ed..1e3e3213c4 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -68,6 +68,7 @@ import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionAcquisitionGrpcClient; import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationAcquisitionClient; import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; @@ -410,9 +411,13 @@ * STARTING runtime/launch association with its captured catalog revision, and World consumes that * evidence through the native exact-peer Game Session reader. Account participation is * point-in-time evidence, not a continuous cross-service lock. Activation authority remains an - * explicit fixture stipulation. This does not establish production certificate custody, full - * application server wiring, production ingress, runtime launch, activation or registration. The - * Logging evidence is point-in-time and does not lock later Account or Game Session commits. + * explicit fixture stipulation. The added admission path uses the actual World initial hold, + * Account protection acquisition, Account-only Game Session terminal read and Account settlement. + * It proves pending denial and a durable original abort without opening the CLOSED pointer; it does + * not prove the positive RUNNING transition, settle the World hold or supply activation authority. + * This does not establish production certificate custody, full application server wiring, + * production ingress, runtime launch, activation or registration. The Logging evidence is + * point-in-time and does not lock later Account or Game Session commits. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -598,6 +603,13 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var accountToGameSessionCurrentAttemptClient = new GrpcOriginalStartSessionCurrentAttemptClient( endpoints, pki.client("account-service"), channels, NAMESPACE); + var accountToGameSessionTerminalClient = + new net.firedevops.firemud.common.gamesession + .GrpcOriginalStartSessionAdmissionTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var gameSessionToAccountAdmissionClient = + new AccountStartSessionAdmissionProtectionAcquisitionGrpcClient( + endpoints, pki.client("game-session-service"), channels, NAMESPACE); var worldToAccountParticipationClient = new AccountStartSessionWorldParticipationAcquisitionClient( endpoints, pki.client("world-management-service"), channels, NAMESPACE); @@ -630,10 +642,19 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex endpoints, pki.client("world-management-service"), channels, NAMESPACE); var wrongWorkloadActivationClient = canonicalActivationClient(worldServer, pki.client("account-service"), channels); + var gameSessionInitialHoldClient = + new CanonicalInitialAdmissionHoldTransportFixture( + loopback(worldServer), + worldServer.getPort(), + pki.client("game-session-service"), + channels, + NAMESPACE); var gameSessionActivationClient = canonicalActivationClient(worldServer, pki.client("game-session-service"), channels)) { ReflectionTestUtils.invokeMethod(loggingClaimClient, "init"); accountToGameSessionCurrentAttemptClient.init(); + accountToGameSessionTerminalClient.init(); + gameSessionToAccountAdmissionClient.init(); worldToAccountParticipationClient.init(); projectionClient.init(); wrongWorkloadPreparationClient.init(); @@ -1084,6 +1105,16 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex NAMESPACE, loggingClaimClient); register(accountHandlers, startSessionAuthorizationProof.grpcService()); + var accountAdmissionProtectionAcquisition = + startSessionAuthorizationProof.admissionProtectionAcquisitionService( + accountToGameSessionCurrentAttemptClient); + var accountAdmissionProtectionSettlement = + startSessionAuthorizationProof.admissionProtectionSettlementService( + accountToGameSessionTerminalClient); + register( + accountHandlers, + new AccountStartSessionAdmissionProtectionAcquisitionGrpcService( + accountAdmissionProtectionAcquisition, NAMESPACE)); var accountWorldParticipationAcquisitionService = startSessionAuthorizationProof.worldParticipationAcquisitionService( accountToGameSessionCurrentAttemptClient); @@ -3447,6 +3478,19 @@ public void attachAccountRedemptionProjection( gameSessionHandlers, new CanonicalGameInstanceLaunchAssociationReadGrpcService( canonicalLaunchRepository, NAMESPACE)); + var canonicalAdmissionRepository = + new net.firedevops.firemud.gamesession.repository + .GameSessionCanonicalInitialAdmissionRepository( + gameSessionAttempts.dsl(), + gameSessionAttempts.transactionManager(), + NAMESPACE, + gameSessionAttempts.repository(), + canonicalRealmCatalogRepository); + register( + gameSessionHandlers, + new net.firedevops.firemud.gamesession.service.impl + .OriginalStartSessionAdmissionTerminalReadGrpcService( + canonicalAdmissionRepository, NAMESPACE)); var preparationAssociationRequest = new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( UUID.randomUUID(), @@ -3969,8 +4013,9 @@ public void close() { .isEqualTo(retainedEvidenceBeforeActivation); // This explicitly stipulates current producer authority and its operation-specific - // held handle. The fixture's STARTING evidence is the existing mocked Game Session - // association, not a current owner read or continuous Account/GS protection. + // held handle. STARTING association evidence comes from the actual Game Session + // launch owner and native authenticated read above, but that retained observation is + // not continuous Account/GS protection through the World activation commit. { var firstActivationResponse = gameSessionActivationClient.activate( @@ -4108,6 +4153,154 @@ public void close() { .isEqualTo(independentActiveRead.launchBinding()); assertThat(activeReadAfterConflict.startLocation()) .isEqualTo(independentActiveRead.startLocation()); + + // Genuine GS/Account terminal recovery below is deliberately an abort, not + // successful admission: the real launch still remains STARTING. World activation + // authority above remains stipulated and is not promoted by these owner results. + var closedPointer = + Objects.requireNonNull( + gameSessionAttempts + .dsl() + .fetchOne( + "SELECT pointer_version, admission_state, game_instance_id" + + " FROM gameplay_admission_pointer" + + " WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ?", + NAMESPACE, + canonicalRealmCatalog.canonicalTenantId(), + canonicalRealmCatalog.realmId()), + "Actual catalog-created CLOSED pointer required"); + assertThat(closedPointer.get("admission_state", String.class)).isEqualTo("CLOSED"); + assertThat(closedPointer.get("game_instance_id", Long.class)).isNull(); + long expectedClosedVersion = closedPointer.get("pointer_version", Long.class); + String initialAdmissionRequestId = UUID.randomUUID().toString(); + var holdRequest = + canonicalAdmissionRepository.beginIntent( + ownerAttemptClaim, + new net.firedevops.firemud.gamesession.repository + .GameSessionCanonicalInitialAdmissionRepository.IntentInput( + canonicalLaunch, + activeReadAfterConflict, + initialAdmissionRequestId, + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest + .OriginKind.EXPECT_CLOSED, + expectedClosedVersion)); + var initialHoldRepository = + new net.firedevops.firemud.worldmanagement.tenant + .WorldCanonicalInitialAdmissionHoldRepository( + world.dsl(), + world.transactions(), + canonicalAssociationRepository, + lifecycleRepository); + register( + worldHandlers, + new net.firedevops.firemud.worldmanagement.tenant + .WorldCanonicalInitialAdmissionHoldGrpcService( + initialHoldRepository, NAMESPACE)); + var acquiredHold = + gameSessionInitialHoldClient.acquire( + holdRequest, activeReadAfterConflict.request()); + assertThat(initialHoldRepository.readIdentity(holdRequest)).contains(acquiredHold); + assertThat( + gameSessionInitialHoldClient.acquire( + holdRequest, activeReadAfterConflict.request())) + .isEqualTo(acquiredHold); + var attachedAdmission = + canonicalAdmissionRepository.attachWorldHold(ownerAttemptClaim, acquiredHold); + assertThat(attachedAdmission.initialAdmissionRequestId()) + .isEqualTo(initialAdmissionRequestId); + assertThat(initialAdmissionRequestId).isNotEqualTo(controlPlaneRequestId); + var protectionInput = + new net.firedevops.firemud.common.account.startsession + .AccountStartSessionAdmissionProtectionAcquisitionInput( + startSessionTuple.canonicalBytes(), + ownerMutationId, + ownerAttemptId, + ownerFence, + acquiredHold); + var acquiredProtection = gameSessionToAccountAdmissionClient.acquire(protectionInput); + assertThat( + gameSessionToAccountAdmissionClient.acquire(protectionInput).canonicalBytes()) + .containsExactly(acquiredProtection.canonicalBytes()); + var terminalSelector = + new net.firedevops.firemud.common.gamesession + .OriginalStartSessionAdmissionTerminalRequest( + acquiredProtection.canonicalBytes()); + assertThat(canonicalAdmissionRepository.readTerminal(terminalSelector)).isEmpty(); + assertThatThrownBy(() -> accountToGameSessionTerminalClient.read(terminalSelector)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + assertThatThrownBy( + () -> + accountAdmissionProtectionSettlement.settle( + acquiredProtection.accountProtectionId(), + acquiredProtection.accountProtectionFence())) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThat( + startSessionAuthorizationProof + .sourceDsl() + .fetchCount( + DSL.table("account_start_session_admission_protection_settlements"), + DSL.field("protection_id") + .eq(acquiredProtection.accountProtectionId()))) + .isZero(); + var abortedAdmission = + canonicalAdmissionRepository.abort( + ownerAttemptClaim, + acquiredProtection, + "No original positive admission committed"); + assertThat(abortedAdmission.ownerProof().outcome()) + .isEqualTo( + net.firedevops.firemud.common.world + .GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + assertThat(abortedAdmission.ownerProof().positiveDurableAbort()).isTrue(); + assertThat(accountToGameSessionTerminalClient.read(terminalSelector).canonicalBytes()) + .containsExactly(abortedAdmission.canonicalBytes()); + var settledAdmissionProtection = + accountAdmissionProtectionSettlement.settle( + acquiredProtection.accountProtectionId(), + acquiredProtection.accountProtectionFence()); + assertThat(settledAdmissionProtection.outcome()) + .isEqualTo(abortedAdmission.ownerProof().outcome()); + assertThat( + accountAdmissionProtectionSettlement + .settle( + acquiredProtection.accountProtectionId(), + acquiredProtection.accountProtectionFence()) + .settlement() + .canonicalBytes()) + .containsExactly(settledAdmissionProtection.settlement().canonicalBytes()); + assertThatThrownBy( + () -> + canonicalAdmissionRepository.commit( + ownerAttemptClaim, acquiredProtection)) + .isInstanceOf(IllegalStateException.class); + var pointerAfterAbort = + Objects.requireNonNull( + gameSessionAttempts + .dsl() + .fetchOne( + "SELECT pointer_version, admission_state, game_instance_id" + + " FROM gameplay_admission_pointer" + + " WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ?", + NAMESPACE, + canonicalRealmCatalog.canonicalTenantId(), + canonicalRealmCatalog.realmId())); + assertThat(pointerAfterAbort.get("admission_state", String.class)) + .isEqualTo("CLOSED"); + assertThat(pointerAfterAbort.get("pointer_version", Long.class)) + .isEqualTo(expectedClosedVersion); + assertThat(pointerAfterAbort.get("game_instance_id", Long.class)).isNull(); + assertThat( + canonicalLaunchRepository + .readByLaunchIdentity(preparationAssociationRequest) + .orElseThrow() + .currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING); } var retainedOwnerEvidenceAfterActivation = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java index 2ed8a79814..a8d39d5bab 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java @@ -11,6 +11,7 @@ import io.grpc.StatusRuntimeException; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; @@ -19,6 +20,8 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; @@ -35,6 +38,7 @@ import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; @@ -142,6 +146,7 @@ void selectedSchema3ActorCoreIsResolvedFromExactOwnerSnapshots() { assertThat(resolved.getFirst().safeFeedback().feedbackKey()).isEqualTo("welcome"); assertThat(resolved.getFirst().selectedCommit()).isEqualTo(fixture.binding()); assertThat(resolved.getFirst().expectedWorldSlug()).isEqualTo("world"); + assertThatThrownBy(resolved::clear).isInstanceOf(UnsupportedOperationException.class); assertThat( StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( @@ -184,6 +189,104 @@ void selectedSchema3ActorCoreIsResolvedFromExactOwnerSnapshots() { .hasMessageContaining("selected authored commit"); } + @Test + void resolvedBindingDefensivelyRetainsSelectedActorCoreAndRejectsChangedReleaseProvenance() { + var fixture = selectedActorCoreSource(); + UUID sourceOperation = uuid("66666666-6666-4666-8666-666666666666"); + List sourceBindings = + StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( + sourceOperation, + digest('a'), + "world", + "selected-workflow", + bytes("selected publication operation"), + bytes("selected publication terminal evidence"), + fixture.binding(), + fixture.policySnapshot(), + fixture.gameplayRules()); + var mutableBindings = new ArrayList<>(sourceBindings); + var resolved = + resolvedBinding(mutableBindings, sourceOperation, "world", COMMIT, "selected-workflow"); + + mutableBindings.clear(); + assertThat(resolved.actorCoreBindings()).hasSize(1); + assertThat(resolved.actorCoreBindings().getFirst().canonicalBytes()) + .isEqualTo(sourceBindings.getFirst().canonicalBytes()); + assertThatThrownBy(resolved.actorCoreBindings()::clear) + .isInstanceOf(UnsupportedOperationException.class); + + assertThatThrownBy( + () -> + resolvedBinding( + sourceBindings, + uuid("77777777-7777-4777-8777-777777777777"), + "world", + COMMIT, + "selected-workflow")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected StartSession release"); + assertThatThrownBy( + () -> + resolvedBinding( + sourceBindings, sourceOperation, "other-world", COMMIT, "selected-workflow")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected StartSession release"); + assertThatThrownBy( + () -> + resolvedBinding( + sourceBindings, + sourceOperation, + "world", + uuid("88888888-8888-4888-8888-888888888888"), + "selected-workflow")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected StartSession release"); + assertThatThrownBy( + () -> + resolvedBinding(sourceBindings, sourceOperation, "world", COMMIT, "other-workflow")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected StartSession release"); + } + + private static StartSessionLaunchDescriptorProducer.ResolvedBinding resolvedBinding( + List actorCoreBindings, + UUID associationSourceOperationId, + String descriptorWorldSlug, + UUID associationSelectedCommitId, + String associationWorkflowId) { + var request = request(new ExactReplay(VERSION, COMMIT, "selected-workflow", digest('a'))); + var association = mock(StartSessionTemplateAssociationReadEvidence.Association.class); + when(association.canonicalTenantId()).thenReturn(TENANT); + when(association.templateId()).thenReturn(91L); + when(association.canonicalVersionId()).thenReturn(VERSION); + when(association.selectedCommitId()).thenReturn(associationSelectedCommitId); + when(association.publishWorkflowId()).thenReturn(associationWorkflowId); + when(association.sourceOperationId()).thenReturn(associationSourceOperationId); + when(association.sourceEvidenceDigest()).thenReturn(digest('a')); + when(association.worldSlug()).thenReturn("world"); + + var associationRead = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + when(associationRead.request()).thenReturn(request); + when(associationRead.association()).thenReturn(association); + + var authoredWorld = mock(AuthoredWorldLaunchDescriptorEvidence.class); + when(authoredWorld.worldSlug()).thenReturn(descriptorWorldSlug); + when(authoredWorld.authoredWorldSourceOperationId()) + .thenReturn(uuid("66666666-6666-4666-8666-666666666666")); + when(authoredWorld.authoredWorldSourceEvidenceDigest()).thenReturn(digest('a')); + when(authoredWorld.canonicalTenantId()).thenReturn(TENANT); + when(authoredWorld.versionId()).thenReturn(23L); + when(authoredWorld.gameTemplateId()).thenReturn(91L); + + var descriptor = mock(ResolvedLaunchDescriptorDto.class); + when(descriptor.controlPlaneRequestId()).thenReturn("launch-descriptor-test"); + when(descriptor.canonicalTenantId()).thenReturn(TENANT.toString()); + when(descriptor.gameTemplateId()).thenReturn(91L); + when(descriptor.authoredWorldBinding()).thenReturn(authoredWorld); + return new StartSessionLaunchDescriptorProducer.ResolvedBinding( + request, associationRead, descriptor, actorCoreBindings); + } + private static SelectedActorCoreFixture selectedActorCoreSource() { var target = new TargetProof( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInitialAdmissionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInitialAdmissionRepository.java new file mode 100644 index 0000000000..4606fce290 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInitialAdmissionRepository.java @@ -0,0 +1,2148 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionRequest; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalResult; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.CanonicalRealmCatalog; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Non-activating Game Session owner for one canonical first-OPEN admission. + * + *

This owner composes existing launch, lifecycle, original-attempt, World-hold, Account + * protection, and V28 pointer/audit records. Its byte decoding and SQL checks provide integrity, + * not remote Account or World authentication. The caller remains responsible for authenticating + * those producers and for settling Account only from this repository's independently read exact + * terminal result. + */ +public final class GameSessionCanonicalInitialAdmissionRepository { + private static final String INTENT_TABLE = "game_session_canonical_initial_admission_intent"; + private static final String ATTEMPT_TABLE = "game_session_canonical_initial_admission_attempt"; + private static final String TERMINAL_DIGEST_DOMAIN = + "game-session-canonical-initial-admission-terminal/v1"; + private static final DateTimeFormatter MICROS_UTC = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final String workloadNamespace; + private final GameSessionStartSessionOperatorAttemptRepository originalAttemptRepository; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final TransactionTemplate writeTransaction; + private final TransactionTemplate readTransaction; + + public GameSessionCanonicalInitialAdmissionRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + String workloadNamespace, + GameSessionStartSessionOperatorAttemptRepository originalAttemptRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is missing or invalid"); + } + this.workloadNamespace = workloadNamespace; + this.originalAttemptRepository = + Objects.requireNonNull(originalAttemptRepository, "originalAttemptRepository"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.writeTransaction = new TransactionTemplate(transactionManager); + this.writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.readTransaction = new TransactionTemplate(transactionManager); + this.readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.readTransaction.setReadOnly(true); + } + + /** + * Persists the exact V28 hold intent before World acquisition and returns its immutable request. + * No remote call is made here. An exact retry returns the previously retained request. + */ + public WorldCanonicalInitialAdmissionHold.Request beginIntent( + AttemptClaim claim, IntentInput input) { + requireOutsideOwnerTransaction(); + Objects.requireNonNull(claim, "claim"); + Objects.requireNonNull(input, "input"); + PreparedIntent prepared = prepareIntent(input); + WorldCanonicalInitialAdmissionHold.Request result = + writeTransaction.execute(status -> beginIntentInTransaction(claim, prepared)); + if (result == null) { + throw invalid("Initial-admission intent transaction returned no request"); + } + WorldCanonicalInitialAdmissionHold.Request readback = + readTransaction.execute(status -> readIntentRequest(prepared)); + if (readback == null + || !Arrays.equals(result.canonicalRequestBytes(), readback.canonicalRequestBytes())) { + throw invalid("Committed initial-admission intent differs on independent readback"); + } + return readback; + } + + /** + * Attaches the exact World-issued immutable hold identity to the V28 intent and creates its one + * PENDING V28 owner row. This records identity only; it does not assert hold activity or admit a + * player. + */ + public CanonicalInitialAdmissionRequest attachWorldHold( + AttemptClaim claim, WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity) { + requireOutsideOwnerTransaction(); + Objects.requireNonNull(claim, "claim"); + Objects.requireNonNull(holdIdentity, "holdIdentity"); + CanonicalInitialAdmissionRequest result = + writeTransaction.execute(status -> attachWorldHoldInTransaction(claim, holdIdentity)); + if (result == null) { + throw invalid("Initial-admission hold attachment transaction returned no request"); + } + return result; + } + + /** Terminalizes the exact held first-OPEN intent as COMMITTED. */ + public OriginalStartSessionAdmissionTerminalResult commit( + AttemptClaim claim, AccountStartSessionAdmissionProtectionEvidence protectionEvidence) { + return terminalize(claim, protectionEvidence, TerminalAction.COMMIT, null); + } + + /** + * Records only a definitive V28 ABORTED outcome. The SQL owner guard must prove that the original + * origin remains excluded before this result is durable. + */ + public OriginalStartSessionAdmissionTerminalResult abort( + AttemptClaim claim, + AccountStartSessionAdmissionProtectionEvidence protectionEvidence, + String reason) { + requireText(reason, "reason", 500); + return terminalize(claim, protectionEvidence, TerminalAction.ABORT, reason); + } + + /** + * Independently reads one exact terminal result. An absent or PENDING attempt is empty; a + * terminal-but-incomplete, mismatched, or corrupt owner record is an error. + */ + public Optional readTerminal( + OriginalStartSessionAdmissionTerminalRequest request) { + requireOutsideOwnerTransaction(); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw invalid("Terminal selector namespace differs from this Game Session owner"); + } + Optional result = + readTransaction.execute(status -> readTerminalInTransaction(request)); + return Objects.requireNonNull(result, "Terminal read transaction returned no result"); + } + + private OriginalStartSessionAdmissionTerminalResult terminalize( + AttemptClaim claim, + AccountStartSessionAdmissionProtectionEvidence protectionEvidence, + TerminalAction action, + String abortReason) { + requireOutsideOwnerTransaction(); + Objects.requireNonNull(claim, "claim"); + Objects.requireNonNull(protectionEvidence, "protectionEvidence"); + OriginalStartSessionAdmissionTerminalRequest selector = + new OriginalStartSessionAdmissionTerminalRequest(protectionEvidence.canonicalBytes()); + + // Exact historical terminal recovery is deliberately the first operation. It does not + // extend or revalidate the already elapsed original claim/lease. + Optional existing = readTerminal(selector); + if (existing.isPresent()) { + return requireRequestedTerminal(existing.get(), action, abortReason); + } + + TerminalWriteResult written = + writeTransaction.execute( + status -> terminalizeInTransaction(claim, protectionEvidence, action, abortReason)); + if (written == null) { + throw invalid("Initial-admission terminal transaction returned no result"); + } + Optional independent = readTerminal(selector); + if (independent.isEmpty()) { + throw invalid("Terminal owner write has no independent exact terminal readback"); + } + return requireRequestedTerminal(independent.get(), action, abortReason); + } + + private TerminalWriteResult terminalizeInTransaction( + AttemptClaim claim, + AccountStartSessionAdmissionProtectionEvidence evidence, + TerminalAction action, + String abortReason) { + requireWritableReadCommittedOwnerTransaction(); + AccountStartSessionAdmissionProtectionRequest protection = evidence.request(); + WorldCanonicalInitialAdmissionHold.HoldIdentity hold = protection.worldAdmissionHoldIdentity(); + WorldCanonicalInitialAdmissionHold.Request holdRequest = hold.request(); + String initialRequestId = holdRequest.initialAdmissionRequestId(); + String controlRequestId = protection.originalTuple().controlPlaneRequestId(); + String namespace = workloadNamespace; + + lockRequest(namespace, initialRequestId); + lockTenantAndLaunch(namespace, holdRequest.canonicalTenantId(), controlRequestId); + + Record intent = selectIntent(namespace, initialRequestId, true); + Record attempt = selectInitialAttempt(namespace, initialRequestId, true); + if (intent == null || attempt == null) { + throw invalid("Exact attached initial-admission intent and owner attempt are unavailable"); + } + if (isTerminal(requiredText(attempt, "status"))) { + // A concurrent exact retry won the request lock. Do no further work or claim check here; + // the public method performs a new independent terminal read after this transaction ends. + return TerminalWriteResult.ALREADY_TERMINAL; + } + if (!"PENDING".equals(requiredText(attempt, "status"))) { + throw invalid("Initial-admission attempt is not in its one pending state"); + } + + requireIntentAndHoldMatch(intent, attempt, hold); + AttemptSnapshot original = + validateOriginalClaim(claim, protection.originalTuple().canonicalBytes()); + requireProtectionMatchesCurrent(evidence, original); + lockAdmissionRealm(namespace, holdRequest.canonicalTenantId(), holdRequest.realmId()); + // Lock the current canonical pointer/origin and catalog after the request, tenant/launch, and + // original owner rows. Recheck the original DB-clock lease after all of these possible waits. + Record prior = selectPriorOrigin(holdRequest, true); + Record catalog = lockCatalogRow(intent); + verifyIntentLaunchCatalog(intent, catalog); + AttemptSnapshot finalCurrent = + validateOriginalClaim(claim, protection.originalTuple().canonicalBytes()); + requireProtectionMatchesCurrent(evidence, finalCurrent); + + if (action == TerminalAction.COMMIT) { + commitPointerAndAttempt(claim, attempt, intent, holdRequest, evidence, prior, catalog); + } else { + requireAbortExclusion(holdRequest, intent, prior); + updateAttemptAborted(claim, attempt, intent, evidence, abortReason, prior); + } + return TerminalWriteResult.WRITTEN; + } + + private WorldCanonicalInitialAdmissionHold.Request beginIntentInTransaction( + AttemptClaim claim, PreparedIntent prepared) { + requireWritableReadCommittedOwnerTransaction(); + WorldCanonicalInitialAdmissionHold.Request request = prepared.holdRequest(); + String namespace = workloadNamespace; + String initialRequestId = request.initialAdmissionRequestId(); + lockRequest(namespace, initialRequestId); + lockTenantAndLaunch( + namespace, request.canonicalTenantId(), prepared.launch().controlPlaneRequestId()); + requireActualLaunchAndCatalog(prepared.launch()); + validateOriginalClaim(claim, prepared.launch().originalStartSessionTuple()); + lockAdmissionRealm(namespace, request.canonicalTenantId(), request.realmId()); + validateOriginalClaim(claim, prepared.launch().originalStartSessionTuple()); + + Record existing = selectIntent(namespace, initialRequestId, true); + if (existing != null) { + requireIntentMatchesPrepared(existing, prepared); + return WorldCanonicalInitialAdmissionHold.Request.fromStored( + requiredBytes(existing, "canonical_hold_request_bytes")); + } + dsl.execute( + "INSERT INTO " + + INTENT_TABLE + + " (target_namespace, initial_admission_request_id, request_digest, canonical_tenant_id," + + " world_slug, realm_id, playable_state_namespace_id, playable_state_scope," + + " catalog_visible, catalog_public_production, catalog_revision," + + " catalog_creation_request_id, catalog_request_digest, catalog_receipt_digest," + + " tenant_association_operation_id, game_session_tenant_id, canonical_game_instance_id," + + " game_instance_id, canonical_version_id, runtime_version_id, control_plane_request_id," + + " launch_descriptor_id, captured_starting_row_version, current_row_version," + + " descriptor_request_digest, descriptor_result_digest, release_attestation_digest," + + " catalog_source_intake_operation_id, catalog_source_intake_request_id," + + " original_start_session_tuple, canonical_hold_request_bytes, canonical_lifecycle_request_bytes," + + " state, created_at, updated_at)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " ?, ?, ?, ?, 'PENDING_HOLD', clock_timestamp(), clock_timestamp())", + namespace, + initialRequestId, + prepared.holdRequest().initialAdmissionRequestDigest(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.expectedCatalogRevision(), + prepared.launch().catalogCreationRequestId(), + prepared.catalog().catalogRequestDigest(), + prepared.catalog().catalogReceiptDigest(), + prepared.catalog().tenantAssociationOperationId(), + prepared.launch().gameSessionTenantId(), + prepared.launch().gameInstanceUuid(), + prepared.launch().gameInstanceId(), + request.canonicalVersionId(), + prepared.launch().launchBindingEvidence().descriptor().versionId(), + prepared.launch().controlPlaneRequestId(), + prepared.launch().launchBindingEvidence().descriptor().launchDescriptorId(), + prepared.launch().capturedStartingRowVersion(), + prepared.launch().currentRowVersion(), + prepared.launch().launchBindingEvidence().descriptor().requestDigest(), + prepared.launch().launchBindingEvidence().descriptor().resultDigest(), + prepared.launch().launchBindingEvidence().releaseAttestation().evidenceDigest(), + prepared.catalog().intakeOperationId(), + prepared.catalog().intakeRequestId(), + prepared.launch().originalStartSessionTuple(), + request.canonicalRequestBytes(), + prepared.lifecycle().request().canonicalBytes()); + Record inserted = selectIntent(namespace, initialRequestId, false); + if (inserted == null) { + throw invalid( + "New canonical initial-admission intent did not read back in its owner transaction"); + } + requireIntentMatchesPrepared(inserted, prepared); + validateOriginalClaim(claim, prepared.launch().originalStartSessionTuple()); + return request; + } + + private CanonicalInitialAdmissionRequest attachWorldHoldInTransaction( + AttemptClaim claim, WorldCanonicalInitialAdmissionHold.HoldIdentity hold) { + requireWritableReadCommittedOwnerTransaction(); + WorldCanonicalInitialAdmissionHold.Request request = hold.request(); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw invalid("World hold request namespace differs from this owner"); + } + String initialRequestId = request.initialAdmissionRequestId(); + lockRequest(workloadNamespace, initialRequestId); + lockTenantAndLaunch( + workloadNamespace, request.canonicalTenantId(), controlRequestForIntent(initialRequestId)); + Record intent = selectIntent(workloadNamespace, initialRequestId, true); + if (intent == null) { + throw invalid("World hold has no previously persisted Game Session intent"); + } + requireIntentRequestMatchesHold(intent, hold); + validateOriginalClaim(claim, requiredBytes(intent, "original_start_session_tuple")); + lockAdmissionRealm(workloadNamespace, request.canonicalTenantId(), request.realmId()); + validateOriginalClaim(claim, requiredBytes(intent, "original_start_session_tuple")); + + byte[] exactHoldBytes = hold.canonicalBytes(); + String state = requiredText(intent, "state"); + if ("HOLD_ATTACHED".equals(state) || "TERMINAL".equals(state)) { + byte[] retainedHold = requiredBytes(intent, "hold_identity_bytes"); + if (!Arrays.equals(retainedHold, exactHoldBytes)) { + throw invalid("Initial-admission intent already retains a different World hold identity"); + } + Record existing = selectInitialAttempt(workloadNamespace, initialRequestId, true); + if (existing == null) { + throw invalid("Attached World hold has no V28 owner attempt"); + } + return ownerRequest(existing); + } + if (!"PENDING_HOLD".equals(state) + || optionalBytes(intent, "hold_identity_bytes") != null + || optionalInstant(intent, "terminal_at") != null) { + throw invalid("Initial-admission intent is not awaiting its one World hold identity"); + } + + Record existingAttempt = selectInitialAttempt(workloadNamespace, initialRequestId, true); + if (existingAttempt != null) { + throw invalid("PENDING_HOLD intent already has an owner attempt"); + } + dsl.execute( + "INSERT INTO " + + ATTEMPT_TABLE + + " (target_namespace, initial_admission_request_id, request_digest, canonical_tenant_id," + + " world_slug, realm_id, playable_state_namespace_id, playable_state_scope," + + " canonical_game_instance_id, canonical_version_id, game_session_tenant_id, game_instance_id," + + " runtime_version_id, expected_catalog_revision, origin_kind, expected_prior_pointer_version," + + " active_lifecycle_epoch, hold_id, hold_fence, hold_binding_digest, status, created_at, updated_at)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING'," + + " clock_timestamp(), clock_timestamp())", + workloadNamespace, + initialRequestId, + request.initialAdmissionRequestDigest(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + requiredLong(intent, "game_session_tenant_id"), + requiredLong(intent, "game_instance_id"), + requiredLong(intent, "runtime_version_id"), + request.expectedCatalogRevision(), + request.initialAdmissionOrigin().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + hold.holdId(), + hold.holdFence(), + hold.holdBindingDigest()); + int updated = + dsl.execute( + "UPDATE " + + INTENT_TABLE + + " SET hold_identity_bytes = ?, state = 'HOLD_ATTACHED', updated_at = clock_timestamp()" + + " WHERE target_namespace = ? AND initial_admission_request_id = ? AND state = 'PENDING_HOLD'" + + " AND hold_identity_bytes IS NULL AND terminal_at IS NULL", + exactHoldBytes, + workloadNamespace, + initialRequestId); + if (updated != 1) { + throw invalid("World hold identity was not attached to exactly one pending intent"); + } + Record inserted = selectInitialAttempt(workloadNamespace, initialRequestId, false); + if (inserted == null) { + throw invalid("New canonical initial-admission owner attempt did not read back"); + } + requireAttemptMatchesIntent(inserted, intent, hold); + validateOriginalClaim(claim, requiredBytes(intent, "original_start_session_tuple")); + return ownerRequest(inserted); + } + + private void commitPointerAndAttempt( + AttemptClaim claim, + Record attempt, + Record intent, + WorldCanonicalInitialAdmissionHold.Request holdRequest, + AccountStartSessionAdmissionProtectionEvidence evidence, + Record prior, + Record catalog) { + requireNoPriorTerminalEvidence(attempt); + Instant terminalAt = databaseClock(); + long pointerVersion; + long pointerId; + UUID priorRequestId = null; + String priorRequestDigest = null; + Long priorEventId = null; + if (holdRequest.initialAdmissionOrigin() + == WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER) { + requireNoPriorOrigin(holdRequest); + pointerVersion = 1L; + pointerId = + insertOpenPointer(intent, attempt, holdRequest, catalog, terminalAt, pointerVersion); + } else { + if (prior == null) { + throw invalid("Expected canonical never-open CLOSED pointer origin is unavailable"); + } + requireClosedPriorOrigin(prior, intent, holdRequest); + pointerVersion = Math.addExact(holdRequest.expectedPriorPointerVersion(), 1L); + pointerId = + promoteClosedPointer( + prior, intent, attempt, holdRequest, catalog, terminalAt, pointerVersion); + priorRequestId = requiredUuid(prior, "prior_request_id"); + priorRequestDigest = requiredText(prior, "prior_request_digest"); + priorEventId = requiredLong(prior, "prior_audit_event_id"); + } + long auditEventId = + insertOpenPointerEvent(intent, attempt, holdRequest, catalog, terminalAt, pointerVersion); + AttemptSnapshot current = + validateOriginalClaim(claim, evidence.request().originalPostAuthorizationTupleBytes()); + requireProtectionMatchesCurrent(evidence, current); + int updated = + dsl.execute( + "UPDATE " + + ATTEMPT_TABLE + + " SET status = 'COMMITTED', pointer_id = ?, pointer_version = ?, audit_event_id = ?," + + " prior_pointer_request_id = ?, prior_pointer_request_digest = ?," + + " prior_pointer_audit_event_id = ?, account_protection_evidence_version = 1," + + " account_protection_id = ?, account_protection_fence = ?, original_owner_attempt_id = ?," + + " original_owner_mutation_id = ?, original_owner_fence = ?," + + " account_protection_evidence_bytes = ?, terminal_at = ?, updated_at = ?" + + " WHERE target_namespace = ? AND initial_admission_request_id = ? AND status = 'PENDING'", + pointerId, + pointerVersion, + auditEventId, + priorRequestId, + priorRequestDigest, + priorEventId, + evidence.accountProtectionId(), + evidence.accountProtectionFence(), + evidence.request().gameSessionOwnerAttemptId(), + evidence.request().gameSessionOwnerMutationId(), + evidence.request().gameSessionOwnerFence(), + evidence.canonicalBytes(), + terminalAt, + terminalAt, + requiredText(attempt, "target_namespace"), + requiredText(attempt, "initial_admission_request_id")); + if (updated != 1) { + throw invalid("Canonical initial-admission attempt was not pending at commit"); + } + updateIntentTerminal(intent, terminalAt); + } + + private long insertOpenPointer( + Record intent, + Record attempt, + WorldCanonicalInitialAdmissionHold.Request request, + Record catalog, + Instant terminalAt, + long pointerVersion) { + Record inserted = + dsl.fetchOne( + "INSERT INTO gameplay_admission_pointer (world_slug, world_display_name, realm_slug," + + " realm_display_name, tenant_id, game_instance_id, pointer_version, visible," + + " requires_character_selection, state_scope, character_creation_policy, last_updated_by," + + " last_update_reason, created_at, updated_at, public_production_realm, representation_version," + + " target_namespace, canonical_tenant_id, admission_state, realm_id, playable_state_namespace_id," + + " canonical_game_instance_id, canonical_version_id, runtime_version_id, initial_admission_request_id," + + " initial_admission_request_digest, initial_admission_origin_kind, initial_admission_prior_pointer_version," + + " initial_admission_active_epoch, initial_admission_hold_id, initial_admission_hold_fence," + + " initial_admission_hold_binding_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, 'SHARED', ?," + + " 'game-session-canonical-initial-admission', 'World-held initial admission', ?, ?, TRUE, 3," + + " ?, ?, 'OPEN', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + requiredText(intent, "world_slug"), + requiredText(catalog, "source_world_display_name"), + requiredText(catalog, "realm_slug"), + requiredText(catalog, "realm_display_name"), + requiredLong(intent, "game_session_tenant_id"), + requiredLong(intent, "game_instance_id"), + pointerVersion, + requiredBoolean(catalog, "visible"), + requiredText(catalog, "character_creation_policy"), + terminalAt.atOffset(ZoneOffset.UTC).toLocalDateTime(), + terminalAt.atOffset(ZoneOffset.UTC).toLocalDateTime(), + requiredText(intent, "target_namespace"), + requiredUuid(intent, "canonical_tenant_id"), + requiredUuid(intent, "realm_id"), + requiredUuid(intent, "playable_state_namespace_id"), + requiredUuid(intent, "canonical_game_instance_id"), + requiredUuid(intent, "canonical_version_id"), + requiredLong(intent, "runtime_version_id"), + requiredText(intent, "initial_admission_request_id"), + requiredText(attempt, "request_digest"), + request.initialAdmissionOrigin().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + requiredUuid(attempt, "hold_id"), + requiredUuid(attempt, "hold_fence"), + requiredText(attempt, "hold_binding_digest")); + return requiredLong(inserted, "id"); + } + + private long promoteClosedPointer( + Record prior, + Record intent, + Record attempt, + WorldCanonicalInitialAdmissionHold.Request request, + Record catalog, + Instant terminalAt, + long pointerVersion) { + int updated = + dsl.execute( + "UPDATE gameplay_admission_pointer SET representation_version = 3," + + " playable_state_namespace_id = ?, admission_state = 'OPEN', tenant_id = ?, game_instance_id = ?," + + " pointer_version = ?, world_slug = ?, realm_slug = ?, world_display_name = ?, realm_display_name = ?," + + " visible = ?, public_production_realm = TRUE, requires_character_selection = NULL," + + " state_scope = 'SHARED', character_creation_policy = ?," + + " last_updated_by = 'game-session-canonical-initial-admission'," + + " last_update_reason = 'World-held initial admission', updated_at = ?," + + " canonical_game_instance_id = ?, canonical_version_id = ?, runtime_version_id = ?," + + " initial_admission_request_id = ?, initial_admission_request_digest = ?," + + " initial_admission_origin_kind = 'EXPECT_CLOSED', initial_admission_prior_pointer_version = ?," + + " initial_admission_active_epoch = ?, initial_admission_hold_id = ?, initial_admission_hold_fence = ?," + + " initial_admission_hold_binding_digest = ? WHERE id = ? AND representation_version = 2" + + " AND admission_state = 'CLOSED' AND pointer_version = 1", + requiredUuid(intent, "playable_state_namespace_id"), + requiredLong(intent, "game_session_tenant_id"), + requiredLong(intent, "game_instance_id"), + pointerVersion, + requiredText(intent, "world_slug"), + requiredText(catalog, "realm_slug"), + requiredText(catalog, "source_world_display_name"), + requiredText(catalog, "realm_display_name"), + requiredBoolean(catalog, "visible"), + requiredText(catalog, "character_creation_policy"), + terminalAt.atOffset(ZoneOffset.UTC).toLocalDateTime(), + requiredUuid(intent, "canonical_game_instance_id"), + requiredUuid(intent, "canonical_version_id"), + requiredLong(intent, "runtime_version_id"), + requiredText(intent, "initial_admission_request_id"), + requiredText(attempt, "request_digest"), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + requiredUuid(attempt, "hold_id"), + requiredUuid(attempt, "hold_fence"), + requiredText(attempt, "hold_binding_digest"), + requiredLong(prior, "pointer_id")); + if (updated != 1) { + throw invalid("Exact canonical CLOSED pointer was not promoted by the first-OPEN owner"); + } + return requiredLong(prior, "pointer_id"); + } + + private long insertOpenPointerEvent( + Record intent, + Record attempt, + WorldCanonicalInitialAdmissionHold.Request request, + Record catalog, + Instant terminalAt, + long pointerVersion) { + Record inserted = + dsl.fetchOne( + "INSERT INTO gameplay_admission_pointer_event (world_slug, realm_slug, world_display_name," + + " realm_display_name, tenant_id, game_instance_id, pointer_version, visible," + + " requires_character_selection, state_scope, character_creation_policy, actor_principal, reason," + + " control_plane_request_id, occurred_at, prepared_version_upgrade_id, public_production_realm," + + " representation_version, target_namespace, canonical_tenant_id, admission_state, catalog_revision," + + " realm_id, playable_state_namespace_id, canonical_game_instance_id, canonical_version_id," + + " runtime_version_id, initial_admission_request_id, initial_admission_request_digest," + + " initial_admission_origin_kind, initial_admission_prior_pointer_version," + + " initial_admission_active_epoch, initial_admission_hold_id, initial_admission_hold_fence," + + " initial_admission_hold_binding_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, 'SHARED', ?," + + " 'game-session-canonical-initial-admission', 'World-held initial admission', ?, ?, NULL, TRUE, 3," + + " ?, ?, 'OPEN', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + requiredText(intent, "world_slug"), + requiredText(catalog, "realm_slug"), + requiredText(catalog, "source_world_display_name"), + requiredText(catalog, "realm_display_name"), + requiredLong(intent, "game_session_tenant_id"), + requiredLong(intent, "game_instance_id"), + pointerVersion, + requiredBoolean(catalog, "visible"), + requiredText(catalog, "character_creation_policy"), + requiredText(intent, "initial_admission_request_id"), + terminalAt.atOffset(ZoneOffset.UTC).toLocalDateTime(), + requiredText(intent, "target_namespace"), + requiredUuid(intent, "canonical_tenant_id"), + requiredLong(intent, "catalog_revision"), + requiredUuid(intent, "realm_id"), + requiredUuid(intent, "playable_state_namespace_id"), + requiredUuid(intent, "canonical_game_instance_id"), + requiredUuid(intent, "canonical_version_id"), + requiredLong(intent, "runtime_version_id"), + requiredText(intent, "initial_admission_request_id"), + requiredText(attempt, "request_digest"), + request.initialAdmissionOrigin().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + requiredUuid(attempt, "hold_id"), + requiredUuid(attempt, "hold_fence"), + requiredText(attempt, "hold_binding_digest")); + return requiredLong(inserted, "id"); + } + + private void updateAttemptAborted( + AttemptClaim claim, + Record attempt, + Record intent, + AccountStartSessionAdmissionProtectionEvidence evidence, + String reason, + Record prior) { + requireNoPriorTerminalEvidence(attempt); + UUID priorRequestId = null; + String priorDigest = null; + Long priorEventId = null; + if ("EXPECT_CLOSED".equals(requiredText(attempt, "origin_kind"))) { + if (prior == null) { + throw invalid("Definitive abort requires the exact canonical never-open CLOSED origin"); + } + requireClosedPriorOrigin( + prior, intent, evidence.request().worldAdmissionHoldIdentity().request()); + priorRequestId = requiredUuid(prior, "prior_request_id"); + priorDigest = requiredText(prior, "prior_request_digest"); + priorEventId = requiredLong(prior, "prior_audit_event_id"); + } else { + requireNoPriorOrigin(evidence.request().worldAdmissionHoldIdentity().request()); + } + AttemptSnapshot current = + validateOriginalClaim(claim, evidence.request().originalPostAuthorizationTupleBytes()); + requireProtectionMatchesCurrent(evidence, current); + Instant terminalAt = databaseClock(); + int updated = + dsl.execute( + "UPDATE " + + ATTEMPT_TABLE + + " SET status = 'ABORTED', prior_pointer_request_id = ?, prior_pointer_request_digest = ?," + + " prior_pointer_audit_event_id = ?, abort_reason = ?, account_protection_evidence_version = 1," + + " account_protection_id = ?, account_protection_fence = ?, original_owner_attempt_id = ?," + + " original_owner_mutation_id = ?, original_owner_fence = ?," + + " account_protection_evidence_bytes = ?, terminal_at = ?, updated_at = ?" + + " WHERE target_namespace = ? AND initial_admission_request_id = ? AND status = 'PENDING'", + priorRequestId, + priorDigest, + priorEventId, + reason, + evidence.accountProtectionId(), + evidence.accountProtectionFence(), + evidence.request().gameSessionOwnerAttemptId(), + evidence.request().gameSessionOwnerMutationId(), + evidence.request().gameSessionOwnerFence(), + evidence.canonicalBytes(), + terminalAt, + terminalAt, + requiredText(attempt, "target_namespace"), + requiredText(attempt, "initial_admission_request_id")); + if (updated != 1) { + throw invalid("Canonical initial-admission attempt was not pending at abort"); + } + updateIntentTerminal(intent, terminalAt); + } + + private void updateIntentTerminal(Record intent, Instant terminalAt) { + int updated = + dsl.execute( + "UPDATE " + + INTENT_TABLE + + " SET state = 'TERMINAL', terminal_at = ?, updated_at = ?" + + " WHERE target_namespace = ? AND initial_admission_request_id = ?" + + " AND state = 'HOLD_ATTACHED' AND hold_identity_bytes IS NOT NULL AND terminal_at IS NULL", + terminalAt, + terminalAt, + requiredText(intent, "target_namespace"), + requiredText(intent, "initial_admission_request_id")); + if (updated != 1) { + throw invalid("Terminal owner result was not attached to exactly one held intent"); + } + } + + private Optional readTerminalInTransaction( + OriginalStartSessionAdmissionTerminalRequest selector) { + requireReadOnlyRepeatableReadOwnerTransaction(); + AccountStartSessionAdmissionProtectionEvidence requestedEvidence = + selector.protectionEvidence(); + AccountStartSessionAdmissionProtectionRequest protection = requestedEvidence.request(); + WorldCanonicalInitialAdmissionHold.HoldIdentity hold = protection.worldAdmissionHoldIdentity(); + WorldCanonicalInitialAdmissionHold.Request holdRequest = hold.request(); + String namespace = selector.targetNamespace(); + String initialRequestId = holdRequest.initialAdmissionRequestId(); + + Record intent = selectIntent(namespace, initialRequestId, false); + if (intent == null) { + if (selectInitialAttempt(namespace, initialRequestId, false) != null) { + throw invalid("Canonical V28 owner attempt exists without its required immutable intent"); + } + return Optional.empty(); + } + Record attempt = selectInitialAttempt(namespace, initialRequestId, false); + if (attempt == null) { + if ("PENDING_HOLD".equals(requiredText(intent, "state")) + && optionalBytes(intent, "hold_identity_bytes") == null) { + return Optional.empty(); + } + throw invalid("Attached or terminal intent has no canonical V28 owner attempt"); + } + requireIntentAndHoldMatch(intent, attempt, hold); + String status = requiredText(attempt, "status"); + byte[] storedProtection = optionalBytes(attempt, "account_protection_evidence_bytes"); + Integer evidenceVersion = nullableInteger(attempt, "account_protection_evidence_version"); + if ("PENDING".equals(status)) { + if (storedProtection != null + || evidenceVersion != null + || isTerminal(requiredText(intent, "state"))) { + throw invalid( + "PENDING initial-admission owner has incomplete or terminal Account evidence"); + } + return Optional.empty(); + } + if (!isTerminal(status) + || storedProtection == null + || evidenceVersion == null + || evidenceVersion != 1 + || !Arrays.equals(storedProtection, selector.canonicalBytes()) + || !Arrays.equals(storedProtection, requestedEvidence.canonicalBytes()) + || !"TERMINAL".equals(requiredText(intent, "state"))) { + throw invalid( + "Terminal V28 owner result lacks exact complete retained Account protection evidence"); + } + requireV44EvidenceLinkage(attempt, intent, storedProtection, requestedEvidence); + requireIntentLaunchCatalogInReadback(intent); + requireOriginalAttemptHistoricalMatch(attempt, requestedEvidence); + + Instant terminalAt = requiredInstant(attempt, "terminal_at"); + if (terminalAt.getNano() % 1_000 != 0 + || !terminalAt.equals(requiredInstant(intent, "terminal_at"))) { + throw invalid( + "Terminal owner and intent timestamps are not the exact stored database instant"); + } + String digest; + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome; + Long pointerVersion = nullableLong(attempt, "pointer_version"); + Long auditEventId = nullableLong(attempt, "audit_event_id"); + if ("COMMITTED".equals(status)) { + outcome = GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED; + if (pointerVersion == null || auditEventId == null) { + throw invalid("COMMITTED terminal owner row has no pointer version and audit event"); + } + requireCommittedPointerAuditReadback(attempt, intent); + digest = requiredText(attempt, "commit_proof_digest"); + if (optionalText(attempt, "abort_proof_digest") != null + || optionalText(attempt, "abort_reason") != null) { + throw invalid("COMMITTED owner row also carries abort evidence"); + } + } else { + outcome = GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED; + if (pointerVersion != null || auditEventId != null) { + throw invalid("ABORTED terminal owner row carries commit pointer fields"); + } + requirePositiveDurableAbortReadback(attempt, intent); + digest = requiredText(attempt, "abort_proof_digest"); + requireText(requiredText(attempt, "abort_reason"), "persisted abort reason", 500); + if (optionalText(attempt, "commit_proof_digest") != null) { + throw invalid("ABORTED owner row also carries commit proof"); + } + } + String expectedDigest = + terminalDigest( + storedProtection, + requiredText(attempt, "request_digest"), + outcome.name(), + nullableLong(attempt, "pointer_id"), + pointerVersion, + auditEventId, + terminalAt, + "ABORTED".equals(status) ? requiredText(attempt, "abort_reason") : ""); + if (!expectedDigest.equals(digest)) { + throw invalid( + "Stored terminal digest does not rederive from complete immutable owner evidence"); + } + boolean durableAbort = + outcome == GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED; + GameSessionCanonicalInitialAdmissionOwnerProof ownerProof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, outcome, pointerVersion, auditEventId, digest, durableAbort, terminalAt); + return Optional.of(new OriginalStartSessionAdmissionTerminalResult(selector, ownerProof)); + } + + private void requireCommittedPointerAuditReadback(Record attempt, Record intent) { + Record row = + dsl.fetchOne( + "SELECT p.id AS pointer_id, e.id AS audit_event_id FROM gameplay_admission_pointer p" + + " JOIN gameplay_admission_pointer_event e ON e.id = ? AND e.representation_version = 3" + + " JOIN game_session_canonical_realm_catalog c ON c.target_namespace = p.target_namespace" + + " AND c.canonical_tenant_id = p.canonical_tenant_id AND c.realm_id = p.realm_id" + + " AND c.world_slug = p.world_slug AND c.catalog_revision = p.catalog_revision" + + " AND c.playable_state_namespace_id = p.playable_state_namespace_id" + + " JOIN game_session_canonical_instance_launch l ON l.target_namespace = p.target_namespace" + + " AND l.game_instance_uuid = p.canonical_game_instance_id AND l.control_plane_request_id = ?" + + " WHERE p.id = ? AND p.representation_version = 3 AND p.target_namespace = ?" + + " AND p.canonical_tenant_id = ? AND p.realm_id = ? AND p.world_slug = ?" + + " AND p.playable_state_namespace_id = ? AND p.state_scope = ?" + + " AND p.canonical_game_instance_id = ? AND p.canonical_version_id = ?" + + " AND p.runtime_version_id = ? AND p.tenant_id = ? AND p.game_instance_id = ?" + + " AND p.pointer_version = ? AND p.catalog_revision = ? AND p.admission_state = 'OPEN'" + + " AND p.initial_admission_request_id = ? AND p.initial_admission_request_digest = ?" + + " AND p.initial_admission_origin_kind = ?" + + " AND p.initial_admission_prior_pointer_version IS NOT DISTINCT FROM ?" + + " AND p.initial_admission_active_epoch = ? AND p.initial_admission_hold_id = ?" + + " AND p.initial_admission_hold_fence = ? AND p.initial_admission_hold_binding_digest = ?" + + " AND p.updated_at = (?::timestamptz AT TIME ZONE 'UTC')" + + " AND e.target_namespace = p.target_namespace AND e.canonical_tenant_id = p.canonical_tenant_id" + + " AND e.realm_id = p.realm_id AND e.world_slug = p.world_slug" + + " AND e.playable_state_namespace_id = p.playable_state_namespace_id" + + " AND e.canonical_game_instance_id = p.canonical_game_instance_id" + + " AND e.canonical_version_id = p.canonical_version_id" + + " AND e.runtime_version_id = p.runtime_version_id AND e.tenant_id = p.tenant_id" + + " AND e.game_instance_id = p.game_instance_id AND e.pointer_version = p.pointer_version" + + " AND e.catalog_revision = p.catalog_revision AND e.admission_state = 'OPEN'" + + " AND e.control_plane_request_id = p.initial_admission_request_id" + + " AND e.initial_admission_request_id = p.initial_admission_request_id" + + " AND e.initial_admission_request_digest = p.initial_admission_request_digest" + + " AND e.initial_admission_origin_kind = p.initial_admission_origin_kind" + + " AND e.initial_admission_prior_pointer_version IS NOT DISTINCT FROM p.initial_admission_prior_pointer_version" + + " AND e.initial_admission_active_epoch = p.initial_admission_active_epoch" + + " AND e.initial_admission_hold_id = p.initial_admission_hold_id" + + " AND e.initial_admission_hold_fence = p.initial_admission_hold_fence" + + " AND e.initial_admission_hold_binding_digest = p.initial_admission_hold_binding_digest" + + " AND e.occurred_at = (?::timestamptz AT TIME ZONE 'UTC')" + + " AND e.prepared_version_upgrade_id IS NULL" + + " AND c.visible = p.visible AND c.public_production = p.public_production_realm" + + " AND c.character_creation_policy = p.character_creation_policy" + + " AND l.canonical_tenant_id = p.canonical_tenant_id AND l.canonical_realm_id = p.realm_id" + + " AND l.world_slug = p.world_slug AND l.playable_state_namespace_id = p.playable_state_namespace_id" + + " AND l.game_session_tenant_id = p.tenant_id AND l.game_instance_id = p.game_instance_id" + + " AND l.version_id = p.runtime_version_id AND l.public_production IS TRUE" + + " AND l.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId'" + + " = p.canonical_version_id::text", + requiredLong(attempt, "audit_event_id"), + requiredText(intent, "control_plane_request_id"), + requiredLong(attempt, "pointer_id"), + requiredText(attempt, "target_namespace"), + requiredUuid(attempt, "canonical_tenant_id"), + requiredUuid(attempt, "realm_id"), + requiredText(attempt, "world_slug"), + requiredUuid(attempt, "playable_state_namespace_id"), + requiredText(attempt, "playable_state_scope"), + requiredUuid(attempt, "canonical_game_instance_id"), + requiredUuid(attempt, "canonical_version_id"), + requiredLong(attempt, "runtime_version_id"), + requiredLong(attempt, "game_session_tenant_id"), + requiredLong(attempt, "game_instance_id"), + requiredLong(attempt, "pointer_version"), + requiredLong(attempt, "expected_catalog_revision"), + requiredText(attempt, "initial_admission_request_id"), + requiredText(attempt, "request_digest"), + requiredText(attempt, "origin_kind"), + nullableLong(attempt, "expected_prior_pointer_version"), + requiredLong(attempt, "active_lifecycle_epoch"), + requiredUuid(attempt, "hold_id"), + requiredUuid(attempt, "hold_fence"), + requiredText(attempt, "hold_binding_digest"), + requiredInstant(attempt, "terminal_at"), + requiredInstant(attempt, "terminal_at")); + if (row == null + || !sameRequiredLongValue(row, "pointer_id", attempt, "pointer_id") + || !sameRequiredLongValue(row, "audit_event_id", attempt, "audit_event_id")) { + throw invalid( + "COMMITTED owner does not independently match its exact V28 pointer and audit event"); + } + requireCommittedPriorOriginReadback(attempt); + if (requiredLong(attempt, "pointer_version") + != ("NO_PRIOR_POINTER".equals(requiredText(attempt, "origin_kind")) + ? 1L + : Math.addExact(requiredLong(attempt, "expected_prior_pointer_version"), 1L))) { + throw invalid("COMMITTED pointer version does not advance its exact origin precondition"); + } + } + + private void requireCommittedPriorOriginReadback(Record attempt) { + String originKind = requiredText(attempt, "origin_kind"); + UUID priorRequestUuid = optionalUuid(attempt, "prior_pointer_request_id"); + String priorRequestDigest = optionalText(attempt, "prior_pointer_request_digest"); + Long priorAuditEventId = nullableLong(attempt, "prior_pointer_audit_event_id"); + Long expectedPriorPointerVersion = nullableLong(attempt, "expected_prior_pointer_version"); + if ("NO_PRIOR_POINTER".equals(originKind)) { + if (priorRequestUuid != null + || priorRequestDigest != null + || priorAuditEventId != null + || expectedPriorPointerVersion != null) { + throw invalid("COMMITTED NO_PRIOR_POINTER owner retained prior-origin evidence"); + } + return; + } + if (!"EXPECT_CLOSED".equals(originKind) + || priorRequestUuid == null + || priorRequestDigest == null + || priorAuditEventId == null + || !Long.valueOf(1L).equals(expectedPriorPointerVersion)) { + throw invalid("COMMITTED EXPECT_CLOSED owner lacks its exact closed-origin identity"); + } + Record prior = + dsl.fetchOne( + "SELECT origin.request_id AS prior_request_id, origin.request_digest AS prior_request_digest," + + " origin.audit_event_id AS prior_audit_event_id, origin.catalog_revision AS prior_catalog_revision," + + " origin.pointer_version AS prior_pointer_version," + + " origin.catalog_creation_request_id AS prior_catalog_creation_request_id," + + " event.id AS prior_event_id FROM game_session_canonical_closed_admission_pointer_request origin" + + " JOIN gameplay_admission_pointer_event event ON event.id = origin.audit_event_id" + + " AND event.representation_version = 2 AND event.admission_state = 'CLOSED'" + + " AND event.pointer_version = 1 AND event.target_namespace = origin.target_namespace" + + " AND event.canonical_tenant_id = origin.canonical_tenant_id AND event.realm_id = origin.realm_id" + + " AND event.catalog_revision = origin.catalog_revision" + + " AND event.control_plane_request_id = origin.request_id::text" + + " AND event.prepared_version_upgrade_id IS NULL" + + " JOIN game_session_canonical_realm_catalog catalog" + + " ON catalog.target_namespace = origin.target_namespace" + + " AND catalog.canonical_tenant_id = origin.canonical_tenant_id" + + " AND catalog.realm_id = origin.realm_id" + + " AND catalog.catalog_revision = origin.catalog_revision" + + " AND catalog.creation_request_id = origin.catalog_creation_request_id" + + " AND catalog.world_slug = event.world_slug AND catalog.realm_slug = event.realm_slug" + + " AND catalog.visible IS TRUE AND catalog.public_production IS TRUE" + + " WHERE origin.target_namespace = ? AND origin.request_id = ?" + + " AND origin.request_digest = ? AND origin.audit_event_id = ?" + + " AND origin.canonical_tenant_id = ? AND origin.realm_id = ?" + + " AND origin.catalog_creation_request_id = ? AND origin.catalog_revision = ?" + + " AND origin.admission_state = 'CLOSED' AND origin.pointer_version = 1", + requiredText(attempt, "target_namespace"), + priorRequestUuid, + priorRequestDigest, + priorAuditEventId, + requiredUuid(attempt, "canonical_tenant_id"), + requiredUuid(attempt, "realm_id"), + requiredUuid(attempt, "catalog_creation_request_id"), + requiredLong(attempt, "expected_catalog_revision")); + if (prior == null + || !priorRequestUuid.equals(requiredUuid(prior, "prior_request_id")) + || !priorRequestDigest.equals(requiredText(prior, "prior_request_digest")) + || priorAuditEventId.longValue() != requiredLong(prior, "prior_audit_event_id") + || priorAuditEventId.longValue() != requiredLong(prior, "prior_event_id") + || requiredLong(prior, "prior_catalog_revision") + != requiredLong(attempt, "expected_catalog_revision") + || requiredLong(prior, "prior_pointer_version") != 1L + || !requiredUuid(prior, "prior_catalog_creation_request_id") + .equals(requiredUuid(attempt, "catalog_creation_request_id"))) { + throw invalid( + "COMMITTED EXPECT_CLOSED owner does not retain its exact immutable CLOSED request and audit evidence"); + } + } + + private void requirePositiveDurableAbortReadback(Record attempt, Record intent) { + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin origin = + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.valueOf( + requiredText(attempt, "origin_kind")); + String namespace = requiredText(attempt, "target_namespace"); + String requestId = requiredText(attempt, "initial_admission_request_id"); + if (dsl.fetchExists( + dsl.selectOne() + .from("gameplay_admission_pointer") + .where( + "representation_version = 3 AND target_namespace = ? AND initial_admission_request_id = ?", + namespace, + requestId)) + || dsl.fetchExists( + dsl.selectOne() + .from("gameplay_admission_pointer_event") + .where( + "representation_version = 3 AND target_namespace = ? AND initial_admission_request_id = ?", + namespace, + requestId))) { + throw invalid("ABORTED owner has a matching first-OPEN pointer or audit event"); + } + if (origin == WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER) { + boolean conflicts = + dsl.fetchExists( + dsl.selectOne() + .from("gameplay_admission_pointer") + .where( + "realm_id = ? OR (target_namespace = ? AND canonical_tenant_id = ?)" + + " OR (world_slug = ? AND realm_slug = ?) OR (tenant_id = ? AND game_instance_id = ?)", + requiredUuid(attempt, "realm_id"), + namespace, + requiredUuid(attempt, "canonical_tenant_id"), + requiredText(attempt, "world_slug"), + requiredText(intent, "realm_slug"), + requiredLong(attempt, "game_session_tenant_id"), + requiredLong(attempt, "game_instance_id"))) + || dsl.fetchExists( + dsl.selectOne() + .from("gameplay_admission_pointer_event") + .where( + "realm_id = ? OR (target_namespace = ? AND canonical_tenant_id = ?)" + + " OR (world_slug = ? AND realm_slug = ?) OR (tenant_id = ? AND game_instance_id = ?)", + requiredUuid(attempt, "realm_id"), + namespace, + requiredUuid(attempt, "canonical_tenant_id"), + requiredText(attempt, "world_slug"), + requiredText(intent, "realm_slug"), + requiredLong(attempt, "game_session_tenant_id"), + requiredLong(attempt, "game_instance_id"))) + || dsl.fetchExists( + dsl.selectOne() + .from("game_session_canonical_closed_admission_pointer_request") + .where( + "target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ?", + namespace, + requiredUuid(attempt, "canonical_tenant_id"), + requiredUuid(attempt, "realm_id"))) + || dsl.fetchExists( + dsl.selectOne() + .from("gameplay_initial_admission_bind_catalog") + .where( + "tenant_id = ? AND (realm_id = ? OR (world_slug = ? AND realm_slug = ?))", + requiredLong(attempt, "game_session_tenant_id"), + requiredUuid(attempt, "realm_id"), + requiredText(attempt, "world_slug"), + requiredText(intent, "realm_slug"))) + || dsl.fetchExists( + dsl.selectOne() + .from("gameplay_initial_admission_bind_attempt") + .where( + "tenant_id = ? AND (realm_id = ? OR game_instance_id = ?)", + requiredLong(attempt, "game_session_tenant_id"), + requiredUuid(attempt, "realm_id"), + requiredLong(attempt, "game_instance_id"))); + if (conflicts) { + throw invalid( + "NO_PRIOR_POINTER abort is not positively durable while a competing origin exists"); + } + return; + } + Record prior = + selectPriorOrigin( + WorldCanonicalInitialAdmissionHold.Request.fromStored( + requiredBytes(intent, "canonical_hold_request_bytes")), + false); + if (prior == null) { + throw invalid( + "ABORTED EXPECT_CLOSED owner lacks the exact canonical never-open CLOSED origin"); + } + requireClosedPriorOrigin( + prior, + intent, + WorldCanonicalInitialAdmissionHold.Request.fromStored( + requiredBytes(intent, "canonical_hold_request_bytes"))); + } + + private void requireV44EvidenceLinkage( + Record attempt, + Record intent, + byte[] evidenceBytes, + AccountStartSessionAdmissionProtectionEvidence evidence) { + if (!Arrays.equals(requiredBytes(attempt, "account_protection_evidence_bytes"), evidenceBytes) + || !Integer.valueOf(1) + .equals(nullableInteger(attempt, "account_protection_evidence_version")) + || !evidence.accountProtectionId().equals(requiredUuid(attempt, "account_protection_id")) + || evidence.accountProtectionFence() != requiredLong(attempt, "account_protection_fence") + || !evidence + .request() + .gameSessionOwnerAttemptId() + .equals(requiredUuid(attempt, "original_owner_attempt_id")) + || !evidence + .request() + .gameSessionOwnerMutationId() + .equals(requiredUuid(attempt, "original_owner_mutation_id")) + || evidence.request().gameSessionOwnerFence() + != requiredLong(attempt, "original_owner_fence") + || !requiredText(intent, "control_plane_request_id") + .equals(evidence.request().originalTuple().controlPlaneRequestId()) + || !Arrays.equals( + requiredBytes(intent, "original_start_session_tuple"), + evidence.request().originalPostAuthorizationTupleBytes())) { + throw invalid( + "V44 complete Account evidence is not bound to the exact V28 intent and V35 original owner"); + } + } + + private void requireIntentLaunchCatalogInReadback(Record intent) { + Record launch = + selectLaunchWithBinding( + requiredText(intent, "target_namespace"), + requiredText(intent, "control_plane_request_id"), + false); + Record catalog = + dsl.fetchOne( + "SELECT * FROM game_session_canonical_realm_catalog WHERE target_namespace = ?" + + " AND canonical_tenant_id = ? AND realm_id = ?", + requiredText(intent, "target_namespace"), + requiredUuid(intent, "canonical_tenant_id"), + requiredUuid(intent, "realm_id")); + if (launch == null || catalog == null) { + throw invalid("Terminal intent no longer has its exact retained launch/catalog records"); + } + requireIntentMatchesLaunchAndCatalog(intent, launch, catalog); + } + + private void requireActualLaunchAndCatalog( + GameSessionCanonicalInstanceLaunchRepository.CanonicalInstanceLaunch launch) { + Record actual = + dsl.fetchOne( + "SELECT * FROM game_session_canonical_instance_launch WHERE target_namespace = ?" + + " AND control_plane_request_id = ? FOR UPDATE", + workloadNamespace, + launch.controlPlaneRequestId()); + Record catalogRow = + dsl.fetchOne( + "SELECT * FROM game_session_canonical_realm_catalog WHERE target_namespace = ?" + + " AND canonical_tenant_id = ? AND realm_id = ? FOR UPDATE", + workloadNamespace, + launch.canonicalTenantId(), + launch.canonicalRealmId()); + CanonicalRealmCatalog catalog = + catalogRepository + .readByCanonicalTenantIdInOwnerTransaction(launch.canonicalTenantId()) + .orElseThrow(() -> invalid("Exact source-backed launch catalog is unavailable")); + if (actual == null || catalogRow == null) { + throw invalid( + "Exact canonical launch or catalog row is unavailable in the owner transaction"); + } + requireLaunchMatches(launch, actual); + requireCatalogMatches(launch, catalogRow, catalog); + } + + private Record lockCatalogRow(Record intent) { + Record catalog = + dsl.fetchOne( + "SELECT * FROM game_session_canonical_realm_catalog WHERE target_namespace = ?" + + " AND canonical_tenant_id = ? AND realm_id = ? FOR UPDATE", + requiredText(intent, "target_namespace"), + requiredUuid(intent, "canonical_tenant_id"), + requiredUuid(intent, "realm_id")); + if (catalog == null) { + throw invalid("Exact initial-admission source-backed catalog row is unavailable"); + } + return catalog; + } + + private void verifyIntentLaunchCatalog(Record intent, Record catalog) { + Record launch = + selectLaunchWithBinding( + requiredText(intent, "target_namespace"), + requiredText(intent, "control_plane_request_id"), + true); + if (launch == null) { + throw invalid("Exact canonical launch association is unavailable at terminal write"); + } + requireIntentMatchesLaunchAndCatalog(intent, launch, catalog); + } + + private void requireIntentMatchesLaunchAndCatalog(Record intent, Record launch, Record catalog) { + if (!requiredText(intent, "target_namespace").equals(requiredText(launch, "target_namespace")) + || !requiredText(intent, "control_plane_request_id") + .equals(requiredText(launch, "control_plane_request_id")) + || !Arrays.equals( + requiredBytes(launch, "original_start_session_tuple"), + requiredBytes(intent, "original_start_session_tuple")) + || !requiredUuid(intent, "canonical_tenant_id") + .equals(requiredUuid(launch, "canonical_tenant_id")) + || !requiredUuid(intent, "realm_id").equals(requiredUuid(launch, "canonical_realm_id")) + || !requiredText(intent, "world_slug").equals(requiredText(launch, "world_slug")) + || !requiredUuid(intent, "playable_state_namespace_id") + .equals(requiredUuid(launch, "playable_state_namespace_id")) + || !requiredUuid(intent, "canonical_game_instance_id") + .equals(requiredUuid(launch, "game_instance_uuid")) + || !requiredText(intent, "playable_state_scope") + .equals(requiredText(launch, "playable_state_scope")) + || !requiredBoolean(launch, "public_production") + || requiredLong(intent, "game_session_tenant_id") + != requiredLong(launch, "game_session_tenant_id") + || requiredLong(intent, "game_instance_id") != requiredLong(launch, "game_instance_id") + || requiredLong(intent, "runtime_version_id") != requiredLong(launch, "version_id") + || !requiredUuid(intent, "tenant_association_operation_id") + .equals(requiredUuid(launch, "tenant_association_operation_id")) + || !requiredText(intent, "launch_descriptor_id") + .equals(requiredText(launch, "launch_descriptor_id")) + || requiredLong(intent, "captured_starting_row_version") + != requiredLong(launch, "captured_starting_row_version") + || !requiredText(intent, "descriptor_request_digest") + .equals(requiredText(launch, "launch_descriptor_request_digest")) + || !requiredText(intent, "descriptor_result_digest") + .equals(requiredText(launch, "launch_descriptor_result_digest")) + || !requiredText(intent, "release_attestation_digest") + .equals(requiredText(launch, "launch_release_attestation_digest")) + || !requiredUuid(intent, "catalog_source_intake_operation_id") + .equals(requiredUuid(launch, "catalog_source_intake_operation_id")) + || !requiredUuid(intent, "catalog_source_intake_request_id") + .equals(requiredUuid(launch, "catalog_source_intake_request_id")) + || !requiredUuid(intent, "catalog_creation_request_id") + .equals(requiredUuid(launch, "catalog_creation_request_id")) + || requiredLong(intent, "catalog_revision") != requiredLong(launch, "catalog_revision") + || !requiredUuid(intent, "canonical_tenant_id") + .equals(requiredUuid(catalog, "canonical_tenant_id")) + || !requiredUuid(intent, "realm_id").equals(requiredUuid(catalog, "realm_id")) + || requiredLong(intent, "catalog_revision") != requiredLong(catalog, "catalog_revision") + || !requiredUuid(intent, "catalog_creation_request_id") + .equals(requiredUuid(catalog, "creation_request_id")) + || !requiredUuid(intent, "catalog_source_intake_operation_id") + .equals(requiredUuid(catalog, "source_intake_operation_id")) + || !requiredUuid(intent, "catalog_source_intake_request_id") + .equals(requiredUuid(catalog, "source_intake_request_id")) + || !requiredText(intent, "catalog_request_digest") + .equals(requiredText(catalog, "request_digest")) + || !requiredText(intent, "catalog_receipt_digest") + .equals(requiredText(catalog, "receipt_digest")) + || !requiredBoolean(catalog, "visible") + || !requiredBoolean(catalog, "public_production") + || !"SHARED".equals(requiredText(catalog, "state_scope"))) { + throw invalid("Retained initial-admission intent differs from its actual V43 launch/catalog"); + } + } + + private void requireLaunchMatches( + GameSessionCanonicalInstanceLaunchRepository.CanonicalInstanceLaunch expected, + Record actual) { + if (!expected.targetNamespace().equals(requiredText(actual, "target_namespace")) + || !expected + .controlPlaneRequestId() + .equals(requiredText(actual, "control_plane_request_id")) + || !expected.canonicalTenantId().equals(requiredUuid(actual, "canonical_tenant_id")) + || !expected.gameInstanceUuid().equals(requiredUuid(actual, "game_instance_uuid")) + || !expected.canonicalRealmId().equals(requiredUuid(actual, "canonical_realm_id")) + || !expected + .playableStateNamespaceId() + .equals(requiredUuid(actual, "playable_state_namespace_id")) + || expected.gameSessionTenantId() != requiredLong(actual, "game_session_tenant_id") + || expected.gameInstanceId() != requiredLong(actual, "game_instance_id") + || expected.catalogRevision() != requiredLong(actual, "catalog_revision") + || !Arrays.equals( + expected.originalStartSessionTuple(), + requiredBytes(actual, "original_start_session_tuple"))) { + throw invalid("Supplied canonical launch differs from its actual immutable V43 row"); + } + } + + private void requireCatalogMatches( + GameSessionCanonicalInstanceLaunchRepository.CanonicalInstanceLaunch launch, + Record actual, + CanonicalRealmCatalog typed) { + if (!typed.canonicalTenantId().equals(requiredUuid(actual, "canonical_tenant_id")) + || !typed.realmId().equals(requiredUuid(actual, "realm_id")) + || !typed.worldSlug().equals(requiredText(actual, "world_slug")) + || !typed + .playableStateNamespaceId() + .equals(requiredUuid(actual, "playable_state_namespace_id")) + || !typed.catalogRequestId().equals(requiredUuid(actual, "creation_request_id")) + || !typed.intakeOperationId().equals(requiredUuid(actual, "source_intake_operation_id")) + || !typed.intakeRequestId().equals(requiredUuid(actual, "source_intake_request_id")) + || typed.catalogRevision() != requiredLong(actual, "catalog_revision") + || launch.catalogRevision() != requiredLong(actual, "catalog_revision") + || !requiredBoolean(actual, "visible") + || !requiredBoolean(actual, "public_production") + || !"SHARED".equals(requiredText(actual, "state_scope"))) { + throw invalid("Source-backed canonical catalog differs from exact launch catalog identity"); + } + } + + private void requireIntentMatchesPrepared(Record intent, PreparedIntent prepared) { + WorldCanonicalInitialAdmissionHold.Request stored = + WorldCanonicalInitialAdmissionHold.Request.fromStored( + requiredBytes(intent, "canonical_hold_request_bytes")); + var launch = prepared.launch(); + var catalog = prepared.catalog(); + if (!Arrays.equals( + stored.canonicalRequestBytes(), prepared.holdRequest().canonicalRequestBytes()) + || !requiredText(intent, "target_namespace").equals(workloadNamespace) + || !requiredText(intent, "initial_admission_request_id") + .equals(prepared.holdRequest().initialAdmissionRequestId()) + || !requiredText(intent, "request_digest") + .equals(prepared.holdRequest().initialAdmissionRequestDigest()) + || !requiredUuid(intent, "canonical_tenant_id").equals(launch.canonicalTenantId()) + || !requiredText(intent, "world_slug").equals(catalog.worldSlug()) + || !requiredUuid(intent, "realm_id").equals(launch.canonicalRealmId()) + || !requiredUuid(intent, "playable_state_namespace_id") + .equals(launch.playableStateNamespaceId()) + || !requiredText(intent, "playable_state_scope").equals(launch.playableStateScope().name()) + || !requiredBoolean(intent, "catalog_visible") + || !requiredBoolean(intent, "catalog_public_production") + || requiredLong(intent, "catalog_revision") != launch.catalogRevision() + || !requiredUuid(intent, "catalog_creation_request_id") + .equals(launch.catalogCreationRequestId()) + || !requiredText(intent, "catalog_request_digest").equals(catalog.catalogRequestDigest()) + || !requiredText(intent, "catalog_receipt_digest").equals(catalog.catalogReceiptDigest()) + || !requiredUuid(intent, "tenant_association_operation_id") + .equals(catalog.tenantAssociationOperationId()) + || requiredLong(intent, "game_session_tenant_id") != launch.gameSessionTenantId() + || !requiredUuid(intent, "canonical_game_instance_id").equals(launch.gameInstanceUuid()) + || requiredLong(intent, "game_instance_id") != launch.gameInstanceId() + || !requiredUuid(intent, "canonical_version_id") + .equals(launch.launchBindingEvidence().releaseAttestation().canonicalVersionId()) + || requiredLong(intent, "runtime_version_id") + != launch.launchBindingEvidence().descriptor().versionId() + || !requiredText(intent, "control_plane_request_id").equals(launch.controlPlaneRequestId()) + || !requiredText(intent, "launch_descriptor_id") + .equals(launch.launchBindingEvidence().descriptor().launchDescriptorId()) + || requiredLong(intent, "captured_starting_row_version") + != launch.capturedStartingRowVersion() + || requiredLong(intent, "current_row_version") != launch.currentRowVersion() + || !requiredText(intent, "descriptor_request_digest") + .equals(launch.launchBindingEvidence().descriptor().requestDigest()) + || !requiredText(intent, "descriptor_result_digest") + .equals(launch.launchBindingEvidence().descriptor().resultDigest()) + || !requiredText(intent, "release_attestation_digest") + .equals(launch.launchBindingEvidence().releaseAttestation().evidenceDigest()) + || !Arrays.equals( + requiredBytes(intent, "canonical_lifecycle_request_bytes"), + prepared.lifecycle().request().canonicalBytes()) + || !Arrays.equals( + requiredBytes(intent, "original_start_session_tuple"), + prepared.launch().originalStartSessionTuple()) + || !requiredUuid(intent, "catalog_source_intake_operation_id") + .equals(prepared.catalog().intakeOperationId()) + || !requiredUuid(intent, "catalog_source_intake_request_id") + .equals(catalog.intakeRequestId())) { + throw invalid( + "Initial-admission request ID is already bound to different exact intent bytes"); + } + } + + private void requireIntentRequestMatchesHold( + Record intent, WorldCanonicalInitialAdmissionHold.HoldIdentity hold) { + if (!Arrays.equals( + requiredBytes(intent, "canonical_hold_request_bytes"), hold.canonicalRequestBytes()) + || !Arrays.equals( + requiredBytes(intent, "original_start_session_tuple"), + requiredBytes(intent, "launch_original_start_session_tuple")) + || !requiredText(intent, "target_namespace").equals(hold.request().targetNamespace()) + || !requiredText(intent, "initial_admission_request_id") + .equals(hold.request().initialAdmissionRequestId())) { + throw invalid("World hold response differs from the exact previously persisted request"); + } + } + + private void requireIntentAndHoldMatch( + Record intent, Record attempt, WorldCanonicalInitialAdmissionHold.HoldIdentity hold) { + requireIntentRequestMatchesHold(intent, hold); + if (!Arrays.equals(requiredBytes(intent, "hold_identity_bytes"), hold.canonicalBytes()) + || !"HOLD_ATTACHED".equals(requiredText(intent, "state")) + && !"TERMINAL".equals(requiredText(intent, "state"))) { + throw invalid("Intent does not retain the exact acquired World hold identity"); + } + requireAttemptMatchesIntent(attempt, intent, hold); + } + + private void requireAttemptMatchesIntent( + Record attempt, Record intent, WorldCanonicalInitialAdmissionHold.HoldIdentity hold) { + WorldCanonicalInitialAdmissionHold.Request request = hold.request(); + if (!requiredText(attempt, "target_namespace").equals(requiredText(intent, "target_namespace")) + || !requiredText(attempt, "initial_admission_request_id") + .equals(requiredText(intent, "initial_admission_request_id")) + || !requiredText(attempt, "request_digest").equals(request.initialAdmissionRequestDigest()) + || !requiredUuid(attempt, "canonical_tenant_id").equals(request.canonicalTenantId()) + || !requiredUuid(attempt, "realm_id").equals(request.realmId()) + || !requiredText(attempt, "world_slug").equals(request.worldSlug()) + || !requiredUuid(attempt, "playable_state_namespace_id") + .equals(request.playableStateNamespaceId()) + || !requiredUuid(attempt, "canonical_game_instance_id") + .equals(request.canonicalGameInstanceId()) + || !requiredUuid(attempt, "canonical_version_id").equals(request.canonicalVersionId()) + || requiredLong(attempt, "game_session_tenant_id") + != requiredLong(intent, "game_session_tenant_id") + || requiredLong(attempt, "game_instance_id") != requiredLong(intent, "game_instance_id") + || requiredLong(attempt, "runtime_version_id") != requiredLong(intent, "runtime_version_id") + || requiredLong(attempt, "expected_catalog_revision") != request.expectedCatalogRevision() + || !requiredText(attempt, "origin_kind").equals(request.initialAdmissionOrigin().name()) + || !Objects.equals( + nullableLong(attempt, "expected_prior_pointer_version"), + request.expectedPriorPointerVersion()) + || requiredLong(attempt, "active_lifecycle_epoch") != request.activeLifecycleEpoch() + || !requiredUuid(attempt, "hold_id").equals(hold.holdId()) + || !requiredUuid(attempt, "hold_fence").equals(hold.holdFence()) + || !requiredText(attempt, "hold_binding_digest").equals(hold.holdBindingDigest())) { + throw invalid("V28 attempt does not match its exact V28 intent and World hold identity"); + } + } + + private void requireProtectionMatchesCurrent( + AccountStartSessionAdmissionProtectionEvidence evidence, AttemptSnapshot current) { + AccountStartSessionAdmissionProtectionRequest request = evidence.request(); + if (!Arrays.equals( + request.originalPostAuthorizationTupleBytes(), + current.postAuthorizationExecutionTuple()) + || !Arrays.equals( + request.accountRedemptionProjectionBytes(), current.accountRedemptionProjection()) + || !request.gameSessionOwnerAttemptId().equals(current.ownerAttemptId()) + || !request.gameSessionOwnerMutationId().equals(current.ownerMutationId()) + || request.gameSessionOwnerFence() != current.ownerFence() + || !request.originalLeaseExpiresAt().equals(current.leaseExpiresAt()) + || !request.originalTuple().controlPlaneRequestId().equals(current.controlPlaneRequestId()) + || !workloadNamespace.equals(current.targetNamespace())) { + throw invalid( + "Complete Account protection evidence differs from the live original V35 claim/projection/lease"); + } + } + + private AttemptSnapshot validateOriginalClaim(AttemptClaim claim, byte[] expectedTuple) { + if (!workloadNamespace.equals(claim.targetNamespace())) { + throw invalid("Original StartSession claim namespace differs from this owner"); + } + AttemptSnapshot claimSnapshot = originalAttemptRepository.validateCurrentClaim(claim); + if (!Arrays.equals(expectedTuple, claimSnapshot.postAuthorizationExecutionTuple())) { + throw invalid("Original StartSession claim is not bound to the exact canonical launch tuple"); + } + OriginalStartSessionCurrentAttemptEvidence.Request currentRequest = + new OriginalStartSessionCurrentAttemptEvidence.Request( + UUID.randomUUID(), + workloadNamespace, + expectedTuple, + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.ownerFence()); + AttemptSnapshot current = originalAttemptRepository.readCurrentOriginalAttempt(currentRequest); + if (!claimSnapshot.ownerAttemptId().equals(current.ownerAttemptId()) + || !claimSnapshot.ownerMutationId().equals(current.ownerMutationId()) + || claimSnapshot.ownerFence() != current.ownerFence() + || !claimSnapshot.leaseExpiresAt().equals(current.leaseExpiresAt())) { + throw invalid( + "Current original StartSession attempt changed while admission evidence was read"); + } + return current; + } + + private PreparedIntent prepareIntent(IntentInput input) { + var launch = input.launch(); + var lifecycle = input.lifecycle(); + requireText(input.initialAdmissionRequestId(), "initialAdmissionRequestId", 120); + if (!workloadNamespace.equals(launch.targetNamespace()) + || !workloadNamespace.equals(lifecycle.request().targetNamespace()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() <= 0 + || !launch.canonicalTenantId().equals(lifecycle.request().canonicalTenantId()) + || !launch.gameInstanceUuid().equals(lifecycle.request().canonicalGameInstanceId()) + || !launch.playableStateNamespaceId().equals(lifecycle.request().playableStateNamespaceId()) + || !launch.controlPlaneRequestId().equals(lifecycle.request().controlPlaneRequestId()) + || !launch.launchBindingEvidence().equals(lifecycle.launchBinding()) + || !lifecycle + .request() + .canonicalVersionId() + .equals(launch.launchBindingEvidence().releaseAttestation().canonicalVersionId()) + || !lifecycle + .request() + .expectedDescriptorRequestDigest() + .equals(launch.launchBindingEvidence().descriptor().requestDigest()) + || !lifecycle + .request() + .expectedDescriptorResultDigest() + .equals(launch.launchBindingEvidence().descriptor().resultDigest()) + || !lifecycle + .request() + .expectedReleaseAttestationDigest() + .equals(launch.launchBindingEvidence().releaseAttestation().evidenceDigest())) { + throw invalid( + "World ACTIVE lifecycle evidence differs from the exact source-backed launch binding"); + } + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(launch.originalStartSessionTuple()); + if (!tuple.controlPlaneRequestId().equals(launch.controlPlaneRequestId())) { + throw invalid( + "Canonical launch original tuple differs from its control-plane request identity"); + } + if (input.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER + && input.expectedPriorPointerVersion() != null + || input.originKind() == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED + && (input.expectedPriorPointerVersion() == null + || input.expectedPriorPointerVersion() != 1L)) { + throw invalid( + "Initial-admission origin must be NO_PRIOR_POINTER or exact never-open version-1 CLOSED"); + } + CanonicalRealmCatalog catalog = launch.canonicalRealmCatalog(); + UUID canonicalVersionId = + launch.launchBindingEvidence().releaseAttestation().canonicalVersionId(); + String digest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + workloadNamespace, + launch.canonicalTenantId(), + catalog.worldSlug(), + launch.canonicalRealmId(), + launch.playableStateNamespaceId(), + launch.playableStateScope().name(), + launch.gameInstanceUuid(), + canonicalVersionId, + lifecycle.lifecycleEpoch(), + launch.catalogRevision(), + input.originKind(), + input.expectedPriorPointerVersion(), + input.initialAdmissionRequestId()); + WorldCanonicalInitialAdmissionHold.Request holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + workloadNamespace, + launch.canonicalTenantId(), + catalog.worldSlug(), + launch.canonicalRealmId(), + launch.playableStateNamespaceId(), + launch.playableStateScope().name(), + launch.gameInstanceUuid(), + canonicalVersionId, + lifecycle.lifecycleEpoch(), + input.initialAdmissionRequestId(), + digest, + input.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER + ? WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER + : WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.EXPECT_CLOSED, + launch.catalogRevision(), + input.expectedPriorPointerVersion()); + return new PreparedIntent(launch, lifecycle, catalog, holdRequest); + } + + private WorldCanonicalInitialAdmissionHold.Request readIntentRequest(PreparedIntent prepared) { + requireReadOnlyRepeatableReadOwnerTransaction(); + Record intent = + selectIntent(workloadNamespace, prepared.holdRequest().initialAdmissionRequestId(), false); + if (intent == null) { + throw invalid("Committed initial-admission intent is missing on independent readback"); + } + requireIntentMatchesPrepared(intent, prepared); + return WorldCanonicalInitialAdmissionHold.Request.fromStored( + requiredBytes(intent, "canonical_hold_request_bytes")); + } + + private CanonicalInitialAdmissionRequest ownerRequest(Record attempt) { + return new CanonicalInitialAdmissionRequest( + requiredText(attempt, "target_namespace"), + requiredUuid(attempt, "canonical_tenant_id"), + requiredText(attempt, "world_slug"), + requiredUuid(attempt, "realm_id"), + requiredUuid(attempt, "playable_state_namespace_id"), + requiredText(attempt, "playable_state_scope"), + requiredUuid(attempt, "canonical_game_instance_id"), + requiredUuid(attempt, "canonical_version_id"), + requiredLong(attempt, "active_lifecycle_epoch"), + requiredLong(attempt, "expected_catalog_revision"), + CanonicalInitialAdmissionRequest.OriginKind.valueOf(requiredText(attempt, "origin_kind")), + nullableLong(attempt, "expected_prior_pointer_version"), + requiredText(attempt, "initial_admission_request_id"), + requiredText(attempt, "request_digest"), + requiredUuid(attempt, "hold_id"), + requiredUuid(attempt, "hold_fence"), + requiredText(attempt, "hold_binding_digest")); + } + + private Record selectPriorOrigin( + WorldCanonicalInitialAdmissionHold.Request request, boolean forUpdate) { + if (request.initialAdmissionOrigin() + != WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.EXPECT_CLOSED) { + return null; + } + return dsl.fetchOne( + "SELECT p.id AS pointer_id, p.created_at AS pointer_created_at, origin.request_id AS prior_request_id," + + " origin.request_digest AS prior_request_digest, origin.audit_event_id AS prior_audit_event_id," + + " origin.catalog_revision AS prior_catalog_revision, origin.pointer_version AS prior_pointer_version," + + " origin.catalog_creation_request_id AS prior_catalog_creation_request_id" + + " FROM gameplay_admission_pointer p JOIN game_session_canonical_closed_admission_pointer_request origin" + + " ON origin.target_namespace = p.target_namespace AND origin.canonical_tenant_id = p.canonical_tenant_id" + + " AND origin.realm_id = p.realm_id JOIN gameplay_admission_pointer_event event" + + " ON event.id = origin.audit_event_id AND event.representation_version = 2" + + " AND event.admission_state = 'CLOSED' AND event.pointer_version = 1" + + " AND event.target_namespace = origin.target_namespace" + + " AND event.canonical_tenant_id = origin.canonical_tenant_id AND event.realm_id = origin.realm_id" + + " AND event.catalog_revision = origin.catalog_revision" + + " AND event.control_plane_request_id = origin.request_id::text" + + " WHERE p.representation_version = 2 AND p.admission_state = 'CLOSED'" + + " AND p.pointer_version = ? AND p.catalog_revision = ?" + + " AND p.target_namespace = ? AND p.canonical_tenant_id = ? AND p.realm_id = ?" + + (forUpdate ? " FOR UPDATE OF p" : ""), + request.expectedPriorPointerVersion(), + request.expectedCatalogRevision(), + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId()); + } + + private void requireClosedPriorOrigin( + Record prior, Record intent, WorldCanonicalInitialAdmissionHold.Request request) { + if (prior == null + || request.initialAdmissionOrigin() + != WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.EXPECT_CLOSED + || !Long.valueOf(1L).equals(requiredLong(prior, "prior_pointer_version")) + || requiredLong(prior, "prior_catalog_revision") != request.expectedCatalogRevision() + || !requiredUuid(prior, "prior_catalog_creation_request_id") + .equals(requiredUuid(intent, "catalog_creation_request_id"))) { + throw invalid("Origin is not the exact canonical never-open version-1 CLOSED pointer"); + } + } + + private void requireNoPriorOrigin(WorldCanonicalInitialAdmissionHold.Request request) { + if (request.initialAdmissionOrigin() + != WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER) { + return; + } + if (dsl.fetchExists( + dsl.selectOne() + .from("gameplay_admission_pointer") + .where( + "realm_id = ? OR (target_namespace = ? AND canonical_tenant_id = ?)" + + " OR (world_slug = ? AND realm_slug = ?) OR (tenant_id = ? AND game_instance_id = ?)", + request.realmId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + requiredTextByRealm(request, "realm_slug"), + gameSessionTenantId(request), + gameInstanceId(request))) + || dsl.fetchExists( + dsl.selectOne() + .from("gameplay_admission_pointer_event") + .where( + "realm_id = ? OR (target_namespace = ? AND canonical_tenant_id = ?)" + + " OR (world_slug = ? AND realm_slug = ?) OR (tenant_id = ? AND game_instance_id = ?)", + request.realmId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + requiredTextByRealm(request, "realm_slug"), + gameSessionTenantId(request), + gameInstanceId(request))) + || dsl.fetchExists( + dsl.selectOne() + .from("game_session_canonical_closed_admission_pointer_request") + .where( + "target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ?", + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId())) + || dsl.fetchExists( + dsl.selectOne() + .from("gameplay_initial_admission_bind_catalog") + .where( + "tenant_id = ? AND (realm_id = ? OR (world_slug = ? AND realm_slug = ?))", + gameSessionTenantId(request), + request.realmId(), + request.worldSlug(), + requiredTextByRealm(request, "realm_slug"))) + || dsl.fetchExists( + dsl.selectOne() + .from("gameplay_initial_admission_bind_attempt") + .where( + "tenant_id = ? AND (realm_id = ? OR game_instance_id = ?)", + gameSessionTenantId(request), + request.realmId(), + gameInstanceId(request)))) { + throw invalid("NO_PRIOR_POINTER conflicts with retained canonical admission evidence"); + } + } + + private String requiredTextByRealm( + WorldCanonicalInitialAdmissionHold.Request request, String field) { + Record row = + dsl.fetchOne( + "SELECT realm_slug FROM game_session_canonical_realm_catalog WHERE target_namespace = ?" + + " AND canonical_tenant_id = ? AND realm_id = ?", + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId()); + return requiredText(row, field); + } + + private long gameSessionTenantId(WorldCanonicalInitialAdmissionHold.Request request) { + Record row = + dsl.fetchOne( + "SELECT game_session_tenant_id FROM game_session_canonical_initial_admission_intent" + + " WHERE target_namespace = ? AND initial_admission_request_id = ?", + request.targetNamespace(), + request.initialAdmissionRequestId()); + return requiredLong(row, "game_session_tenant_id"); + } + + private long gameInstanceId(WorldCanonicalInitialAdmissionHold.Request request) { + Record row = + dsl.fetchOne( + "SELECT game_instance_id FROM game_session_canonical_initial_admission_intent" + + " WHERE target_namespace = ? AND initial_admission_request_id = ?", + request.targetNamespace(), + request.initialAdmissionRequestId()); + return requiredLong(row, "game_instance_id"); + } + + private void requireAbortExclusion( + WorldCanonicalInitialAdmissionHold.Request request, Record intent, Record prior) { + if (request.initialAdmissionOrigin() + == WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER) { + requireNoPriorOrigin(request); + } else { + requireClosedPriorOrigin(prior, intent, request); + } + } + + private void requireNoPriorTerminalEvidence(Record attempt) { + if (optionalLong(attempt, "pointer_id") != null + || optionalLong(attempt, "pointer_version") != null + || optionalLong(attempt, "audit_event_id") != null + || optionalInstant(attempt, "terminal_at") != null + || optionalText(attempt, "commit_proof_digest") != null + || optionalText(attempt, "abort_proof_digest") != null + || optionalText(attempt, "abort_reason") != null) { + throw invalid("PENDING initial-admission attempt already contains terminal evidence"); + } + } + + private void lockRequest(String namespace, String requestId) { + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended('canonical-initial-admission-request:' || ? || ':' || ?, 0))", + namespace, + requestId); + } + + private void lockTenantAndLaunch( + String namespace, UUID canonicalTenantId, String controlRequestId) { + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ?, 1))", + namespace, + canonicalTenantId.toString()); + Record launch = + dsl.fetchOne( + "SELECT target_namespace FROM game_session_canonical_instance_launch" + + " WHERE target_namespace = ? AND control_plane_request_id = ? FOR UPDATE", + namespace, + controlRequestId); + if (launch == null) { + throw invalid("Canonical launch row is unavailable for the initial-admission owner"); + } + } + + private void lockAdmissionRealm(String namespace, UUID tenantId, UUID realmId) { + dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended('canonical-initial-admission-realm:' || ? || ':' || ? || ':' || ?, 2))", + namespace, + tenantId.toString(), + realmId.toString()); + } + + private Record selectIntent(String namespace, String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT i.*, l.original_start_session_tuple AS launch_original_start_session_tuple," + + " c.realm_slug AS realm_slug, c.source_world_display_name AS source_world_display_name" + + " FROM " + + INTENT_TABLE + + " i" + + " LEFT JOIN game_session_canonical_instance_launch l ON l.target_namespace = i.target_namespace" + + " AND l.control_plane_request_id = i.control_plane_request_id" + + " LEFT JOIN game_session_canonical_realm_catalog c ON c.target_namespace = i.target_namespace" + + " AND c.canonical_tenant_id = i.canonical_tenant_id AND c.realm_id = i.realm_id" + + " WHERE i.target_namespace = ? AND i.initial_admission_request_id = ?" + + (forUpdate ? " FOR UPDATE OF i" : ""), + namespace, + requestId); + } + + private Record selectLaunchWithBinding( + String namespace, String controlRequestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT l.*," + + " l.complete_launch_binding_evidence -> 'descriptor' ->> 'requestDigest'" + + " AS launch_descriptor_request_digest," + + " l.complete_launch_binding_evidence -> 'descriptor' ->> 'resultDigest'" + + " AS launch_descriptor_result_digest," + + " l.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest'" + + " AS launch_release_attestation_digest FROM game_session_canonical_instance_launch l" + + " WHERE l.target_namespace = ? AND l.control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE OF l" : ""), + namespace, + controlRequestId); + } + + private Record selectInitialAttempt(String namespace, String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + ATTEMPT_TABLE + + " WHERE target_namespace = ? AND initial_admission_request_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + namespace, + requestId); + } + + private String controlRequestForIntent(String initialRequestId) { + Record row = selectIntent(workloadNamespace, initialRequestId, false); + if (row == null) { + throw invalid("Initial-admission intent is missing before launch lock acquisition"); + } + return requiredText(row, "control_plane_request_id"); + } + + private static String terminalDigest( + byte[] accountEvidence, + String requestDigest, + String outcome, + Long pointerId, + Long pointerVersion, + Long auditEventId, + Instant terminalAt, + String abortReason) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream framed = new DataOutputStream(bytes)) { + frame(framed, TERMINAL_DIGEST_DOMAIN.getBytes(StandardCharsets.UTF_8)); + frame(framed, accountEvidence); + frame(framed, requestDigest.getBytes(StandardCharsets.UTF_8)); + frame(framed, outcome.getBytes(StandardCharsets.UTF_8)); + frame( + framed, (pointerId == null ? "" : pointerId.toString()).getBytes(StandardCharsets.UTF_8)); + frame( + framed, + (pointerVersion == null ? "" : pointerVersion.toString()) + .getBytes(StandardCharsets.UTF_8)); + frame( + framed, + (auditEventId == null ? "" : auditEventId.toString()).getBytes(StandardCharsets.UTF_8)); + frame(framed, MICROS_UTC.format(terminalAt).getBytes(StandardCharsets.UTF_8)); + frame(framed, abortReason.getBytes(StandardCharsets.UTF_8)); + } catch (IOException impossible) { + throw new IllegalStateException("Unable to frame terminal owner proof", impossible); + } + try { + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void frame(DataOutputStream output, byte[] value) throws IOException { + output.writeInt(value.length); + output.write(value); + } + + private OriginalStartSessionAdmissionTerminalResult requireRequestedTerminal( + OriginalStartSessionAdmissionTerminalResult result, TerminalAction requested, String reason) { + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome actual = result.ownerProof().outcome(); + if (requested == TerminalAction.COMMIT + && actual != GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + throw invalid("Exact original initial-admission terminal is ABORTED, not COMMITTED"); + } + if (requested == TerminalAction.ABORT + && actual != GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED) { + throw invalid("Exact original initial-admission terminal is COMMITTED, not ABORTED"); + } + if (requested == TerminalAction.ABORT) { + Optional storedReason = readStoredAbortReason(result.request()); + if (storedReason.isEmpty() || !storedReason.get().equals(reason)) { + throw invalid("Exact original ABORTED terminal has a different persisted abort reason"); + } + } + return result; + } + + private Optional readStoredAbortReason( + OriginalStartSessionAdmissionTerminalRequest request) { + return readTransaction.execute( + status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + WorldCanonicalInitialAdmissionHold.Request hold = + request.protectionEvidence().request().worldAdmissionHoldIdentity().request(); + Record row = + selectInitialAttempt( + request.targetNamespace(), hold.initialAdmissionRequestId(), false); + if (row == null || !"ABORTED".equals(requiredText(row, "status"))) { + return Optional.empty(); + } + return Optional.of(requiredText(row, "abort_reason")); + }); + } + + private void requireOriginalAttemptHistoricalMatch( + Record terminalAttempt, AccountStartSessionAdmissionProtectionEvidence evidence) { + AccountStartSessionAdmissionProtectionRequest protection = evidence.request(); + Record original = + dsl.fetchOne( + "SELECT * FROM game_session_start_session_operator_attempt WHERE target_namespace = ?" + + " AND control_plane_request_id = ?", + workloadNamespace, + protection.originalTuple().controlPlaneRequestId()); + if (original == null + || !"OWNER_EXECUTION_PENDING".equals(requiredText(original, "phase_state")) + || !requiredUuid(original, "owner_attempt_id") + .equals(protection.gameSessionOwnerAttemptId()) + || !requiredUuid(original, "owner_mutation_id") + .equals(protection.gameSessionOwnerMutationId()) + || requiredLong(original, "owner_fence") != protection.gameSessionOwnerFence() + || !requiredUuid(terminalAttempt, "original_owner_attempt_id") + .equals(requiredUuid(original, "owner_attempt_id")) + || !requiredUuid(terminalAttempt, "original_owner_mutation_id") + .equals(requiredUuid(original, "owner_mutation_id")) + || requiredLong(terminalAttempt, "original_owner_fence") + != requiredLong(original, "owner_fence") + || !requiredUuid(original, "canonical_tenant_id") + .equals(requiredUuid(terminalAttempt, "canonical_tenant_id")) + || !Arrays.equals( + requiredBytes(original, "post_authorization_execution_tuple"), + protection.originalPostAuthorizationTupleBytes()) + || !Arrays.equals( + requiredBytes(original, "account_redemption_projection"), + protection.accountRedemptionProjectionBytes()) + || !requiredInstant(original, "lease_expires_at") + .equals(protection.originalLeaseExpiresAt())) { + throw invalid( + "Terminal readback does not match the retained exact V35 tuple, projection, owner, and lease"); + } + } + + private Instant databaseClock() { + Record row = dsl.fetchOne("SELECT clock_timestamp() AS terminal_at"); + return requiredInstant(row, "terminal_at"); + } + + private void requireOutsideOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical initial-admission public APIs own their independent transactions"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical initial admission requires writable READ COMMITTED"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() + != java.sql.Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical initial admission requires writable READ COMMITTED"); + } + return null; + }); + Record row = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation," + + " current_setting('transaction_read_only') AS read_only"); + if (row == null + || !"read committed".equals(requiredText(row, "isolation")) + || !"off".equals(requiredText(row, "read_only"))) { + throw new IllegalStateException( + "Canonical initial admission requires writable READ COMMITTED"); + } + } + + private void requireReadOnlyRepeatableReadOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Terminal readback requires read-only REPEATABLE READ"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() + != java.sql.Connection.TRANSACTION_REPEATABLE_READ) { + throw new IllegalStateException("Terminal readback requires read-only REPEATABLE READ"); + } + return null; + }); + Record row = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation," + + " current_setting('transaction_read_only') AS read_only"); + if (row == null + || !"repeatable read".equals(requiredText(row, "isolation")) + || !"on".equals(requiredText(row, "read_only"))) { + throw new IllegalStateException("Terminal readback requires read-only REPEATABLE READ"); + } + } + + private static boolean isTerminal(String status) { + return "COMMITTED".equals(status) || "ABORTED".equals(status); + } + + private static String requiredText(Record row, String field) { + String value = row == null ? null : row.get(field, String.class); + if (value == null) { + throw invalid("Persisted initial-admission owner is missing " + field); + } + return value; + } + + private static String optionalText(Record row, String field) { + return row == null ? null : row.get(field, String.class); + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row == null ? null : row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) { + throw invalid("Persisted initial-admission owner is missing or has nil " + field); + } + return value; + } + + private static UUID optionalUuid(Record row, String field) { + return row == null ? null : row.get(field, UUID.class); + } + + private static long requiredLong(Record row, String field) { + Long value = optionalLong(row, field); + if (value == null) { + throw invalid("Persisted initial-admission owner is missing " + field); + } + return value.longValue(); + } + + static boolean sameRequiredLongValue( + Record left, String leftField, Record right, String rightField) { + return requiredLong(left, leftField) == requiredLong(right, rightField); + } + + private static Long optionalLong(Record row, String field) { + return row == null ? null : row.get(field, Long.class); + } + + private static Integer requiredInteger(Record row, String field) { + Integer value = nullableInteger(row, field); + if (value == null) { + throw invalid("Persisted initial-admission owner is missing " + field); + } + return value; + } + + private static Integer nullableInteger(Record row, String field) { + return row == null ? null : row.get(field, Integer.class); + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = optionalBytes(row, field); + if (value == null) { + throw invalid("Persisted initial-admission owner is missing " + field); + } + return value; + } + + private static byte[] optionalBytes(Record row, String field) { + byte[] value = row == null ? null : row.get(field, byte[].class); + return value == null ? null : value.clone(); + } + + private static boolean requiredBoolean(Record row, String field) { + Boolean value = row == null ? null : row.get(field, Boolean.class); + if (value == null) { + throw invalid("Persisted initial-admission owner is missing " + field); + } + return value; + } + + private static Instant requiredInstant(Record row, String field) { + java.time.OffsetDateTime value = + row == null ? null : row.get(field, java.time.OffsetDateTime.class); + if (value == null) { + throw invalid("Persisted initial-admission owner is missing " + field); + } + return value.toInstant(); + } + + private static Instant optionalInstant(Record row, String field) { + java.time.OffsetDateTime value = + row == null ? null : row.get(field, java.time.OffsetDateTime.class); + return value == null ? null : value.toInstant(); + } + + private static Long nullableLong(Record row, String field) { + return row == null ? null : row.get(field, Long.class); + } + + private static void requireText(String value, String field, int maxLength) { + if (value == null || value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(field + " must be nonblank and within its bound"); + } + } + + private static InvalidCanonicalInitialAdmissionException invalid(String message) { + return new InvalidCanonicalInitialAdmissionException(message); + } + + /** Exact caller-supplied pre-admission evidence; decoding remains integrity-only. */ + public record IntentInput( + GameSessionCanonicalInstanceLaunchRepository.CanonicalInstanceLaunch launch, + WorldCanonicalInstanceLifecycleEvidence lifecycle, + String initialAdmissionRequestId, + CanonicalInitialAdmissionRequest.OriginKind originKind, + Long expectedPriorPointerVersion) { + public IntentInput { + Objects.requireNonNull(launch, "launch"); + Objects.requireNonNull(lifecycle, "lifecycle"); + Objects.requireNonNull(initialAdmissionRequestId, "initialAdmissionRequestId"); + Objects.requireNonNull(originKind, "originKind"); + } + } + + private record PreparedIntent( + GameSessionCanonicalInstanceLaunchRepository.CanonicalInstanceLaunch launch, + WorldCanonicalInstanceLifecycleEvidence lifecycle, + CanonicalRealmCatalog catalog, + WorldCanonicalInitialAdmissionHold.Request holdRequest) {} + + private enum TerminalAction { + COMMIT, + ABORT + } + + private enum TerminalWriteResult { + WRITTEN, + ALREADY_TERMINAL + } + + public static final class InvalidCanonicalInitialAdmissionException + extends IllegalStateException { + public InvalidCanonicalInitialAdmissionException(String message) { + super(message); + } + + public InvalidCanonicalInitialAdmissionException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionAdmissionTerminalReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionAdmissionTerminalReadGrpcService.java new file mode 100644 index 0000000000..59d1c2084c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionAdmissionTerminalReadGrpcService.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.v1.OriginalStartSessionAdmissionTerminalReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionAdmissionTerminalResponse; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Deliberately unregistered Account-facing reader for exact original-admission terminal proof. */ +public final class OriginalStartSessionAdmissionTerminalReadGrpcService + extends OriginalStartSessionAdmissionTerminalReadServiceGrpc + .OriginalStartSessionAdmissionTerminalReadServiceImplBase { + private static final String METHOD_NAME = + "game_session.v1.OriginalStartSessionAdmissionTerminalReadService/" + + "ReadOriginalStartSessionAdmissionTerminal"; + private static final String ACCOUNT_SERVICE = "account-service"; + + private final GameSessionCanonicalInitialAdmissionRepository repository; + private final String workloadNamespace; + + public OriginalStartSessionAdmissionTerminalReadGrpcService( + GameSessionCanonicalInitialAdmissionRepository repository, String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readOriginalStartSessionAdmissionTerminal( + ReadOriginalStartSessionAdmissionTerminalRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "observer"); + + try { + // Authenticate the exact Account workload before inspecting request bytes or storage. + requireAccountWorkload(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + if (request == null) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Complete original-admission terminal selector required") + .asRuntimeException()); + return; + } + + final net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalRequest + decoded; + try { + decoded = OriginalStartSessionAdmissionTerminalGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Complete canonical original-admission terminal selector required") + .asRuntimeException()); + return; + } + + if (!workloadNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Terminal selector namespace differs from configured owner") + .asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Independent Game Session terminal snapshot required") + .asRuntimeException()); + return; + } + + try { + var retained = repository.readTerminal(decoded); + if (retained.isEmpty()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact terminal owner evidence is unavailable") + .asRuntimeException()); + return; + } + var result = retained.orElseThrow(); + if (!decoded.equals(result.request())) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Terminal owner evidence differs from complete Account evidence") + .asRuntimeException()); + return; + } + observer.onNext(OriginalStartSessionAdmissionTerminalGrpcCodec.toResponse(result)); + observer.onCompleted(); + } catch (DataAccessException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Session terminal owner storage unavailable") + .asRuntimeException()); + } catch (IllegalArgumentException | IllegalStateException incompleteOrConflicting) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Complete exact terminal owner evidence is unavailable") + .asRuntimeException()); + } + } + + private void requireAccountWorkload() { + var peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !METHOD_NAME.equals( + OriginalStartSessionAdmissionTerminalReadServiceGrpc + .getReadOriginalStartSessionAdmissionTerminalMethod() + .getFullMethodName()) + || peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified same-namespace Account workload required") + .asRuntimeException(); + } + if (!ACCOUNT_SERVICE.equals(peer.service()) + || !workloadNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/" + ACCOUNT_SERVICE) + .equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Account workload without end-user context required") + .asRuntimeException(); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V44__canonical_initial_admission_terminal_protection.sql b/services/game-session-service/src/main/resources/db/migration/V44__canonical_initial_admission_terminal_protection.sql new file mode 100644 index 0000000000..ef093cb726 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V44__canonical_initial_admission_terminal_protection.sql @@ -0,0 +1,559 @@ +-- Retain complete Account source-protection evidence on the existing V28 terminal owner row. +-- Historical V28 rows remain nullable and are not backfilled or adopted as original attempts. +-- V35's original-attempt relation is intentionally absent from the jOOQ DDL simulator. +-- Keep only its cross-relation constraints out of simulation; all V28 columns stay visible. +-- [jooq ignore start] +ALTER TABLE game_session_start_session_operator_attempt + ADD CONSTRAINT uq_gs_start_session_operator_namespace_attempt + UNIQUE (target_namespace, owner_attempt_id); +-- [jooq ignore stop] + +ALTER TABLE game_session_canonical_initial_admission_intent + ADD COLUMN catalog_source_intake_operation_id UUID, + ADD COLUMN catalog_source_intake_request_id UUID, + ADD COLUMN original_start_session_tuple BYTEA, + ADD CONSTRAINT chk_gs_initial_admission_intent_v44_launch_evidence + CHECK ((catalog_source_intake_operation_id IS NULL + AND catalog_source_intake_request_id IS NULL + AND original_start_session_tuple IS NULL) + OR (catalog_source_intake_operation_id IS NOT NULL + AND catalog_source_intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_source_intake_request_id IS NOT NULL + AND catalog_source_intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND original_start_session_tuple IS NOT NULL + AND octet_length(original_start_session_tuple) BETWEEN 1 AND 262144)); + +-- V28's procedural owner-ledger creation is also absent from simulated metadata. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_initial_admission_attempt + ADD COLUMN account_protection_evidence_version INTEGER, + ADD COLUMN account_protection_id UUID, + ADD COLUMN account_protection_fence BIGINT, + ADD COLUMN original_owner_attempt_id UUID, + ADD COLUMN original_owner_mutation_id UUID, + ADD COLUMN original_owner_fence BIGINT, + ADD COLUMN account_protection_evidence_bytes BYTEA, + ADD CONSTRAINT chk_gs_initial_admission_account_protection_evidence_complete + CHECK ( + (account_protection_evidence_version IS NULL + AND account_protection_id IS NULL + AND account_protection_fence IS NULL + AND original_owner_attempt_id IS NULL + AND original_owner_mutation_id IS NULL + AND original_owner_fence IS NULL + AND account_protection_evidence_bytes IS NULL) + OR (account_protection_evidence_version = 1 + AND account_protection_id IS NOT NULL + AND account_protection_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_protection_fence > 0 + AND original_owner_attempt_id IS NOT NULL + AND original_owner_mutation_id IS NOT NULL + AND original_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND original_owner_fence > 0 + AND account_protection_evidence_bytes IS NOT NULL + AND octet_length(account_protection_evidence_bytes) BETWEEN 1 AND 8388608)), + ADD CONSTRAINT chk_gs_initial_admission_terminal_requires_protection + CHECK (status = 'PENDING' + OR account_protection_evidence_version IS NULL + OR account_protection_evidence_version = 1); + +CREATE UNIQUE INDEX uq_gs_initial_admission_protected_original_attempt + ON game_session_canonical_initial_admission_attempt (target_namespace, original_owner_attempt_id) + WHERE original_owner_attempt_id IS NOT NULL; +CREATE UNIQUE INDEX uq_gs_initial_admission_account_protection + ON game_session_canonical_initial_admission_attempt (target_namespace, account_protection_id) + WHERE account_protection_id IS NOT NULL; + +ALTER TABLE game_session_canonical_initial_admission_attempt + ADD CONSTRAINT fk_gs_initial_admission_original_owner + FOREIGN KEY (target_namespace, original_owner_attempt_id) + REFERENCES game_session_start_session_operator_attempt (target_namespace, owner_attempt_id); + +CREATE FUNCTION require_game_session_canonical_initial_admission_account_terminal_evidence() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + selected_intent game_session_canonical_initial_admission_intent%ROWTYPE; + selected_launch game_session_canonical_instance_launch%ROWTYPE; + selected_catalog game_session_canonical_realm_catalog%ROWTYPE; + selected_original game_session_start_session_operator_attempt%ROWTYPE; + evidence_json JSONB; + evidence_request_bytes BYTEA; + evidence_request JSONB; + evidence_tuple_bytes BYTEA; + evidence_projection_bytes BYTEA; + evidence_hold_bytes BYTEA; + hold_json JSONB; + hold_request_json JSONB; + expected_request_digest TEXT; + digest_bytes BYTEA; + domain_bytes BYTEA; + empty_bytes BYTEA := ''::BYTEA; + field_bytes BYTEA; + terminal_at_text TEXT; +BEGIN + IF TG_TABLE_NAME = 'game_session_canonical_initial_admission_intent' THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Canonical initial-admission intents are durable survivor evidence' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'PENDING_HOLD' + OR NEW.hold_identity_bytes IS NOT NULL + OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'New canonical initial-admission intents must begin before World hold acquisition' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO selected_launch + FROM game_session_canonical_instance_launch + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = NEW.control_plane_request_id; + SELECT * INTO selected_catalog + FROM game_session_canonical_realm_catalog + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND realm_id = NEW.realm_id; + BEGIN + hold_request_json := convert_from(NEW.canonical_hold_request_bytes, 'UTF8')::JSONB; + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'New initial-admission intent request bytes are not structurally readable' + USING ERRCODE = '23514'; + END; + IF hold_request_json ->> 'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR jsonb_typeof(hold_request_json -> 'request') IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'New initial-admission intent request has an unsupported schema or shape' + USING ERRCODE = '23514'; + END IF; + digest_bytes := ''::BYTEA; + domain_bytes := convert_to('game-session-canonical-initial-admission/v1', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'targetNamespace', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'canonicalTenantId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'worldSlug', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'realmId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'playableStateNamespaceId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'playableStateScope', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'canonicalGameInstanceId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'canonicalVersionId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'activeLifecycleEpoch', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'expectedCatalogRevision', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'initialAdmissionOrigin', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(hold_request_json -> 'request' ->> 'expectedPriorPointerVersion', ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'initialAdmissionRequestId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + expected_request_digest := encode(sha256(digest_bytes), 'hex'); + IF NEW.original_start_session_tuple IS NULL + OR octet_length(NEW.original_start_session_tuple) NOT BETWEEN 1 AND 262144 + OR selected_launch.target_namespace IS NULL + OR selected_catalog.target_namespace IS NULL + OR selected_launch.original_start_session_tuple IS DISTINCT FROM NEW.original_start_session_tuple + OR selected_launch.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR selected_launch.canonical_realm_id IS DISTINCT FROM NEW.realm_id + OR selected_launch.world_slug IS DISTINCT FROM NEW.world_slug + OR selected_launch.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR selected_launch.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR selected_launch.game_instance_uuid IS DISTINCT FROM NEW.canonical_game_instance_id + OR selected_launch.game_session_tenant_id IS DISTINCT FROM NEW.game_session_tenant_id + OR selected_launch.game_instance_id IS DISTINCT FROM NEW.game_instance_id + OR selected_launch.version_id IS DISTINCT FROM NEW.runtime_version_id + OR selected_launch.tenant_association_operation_id IS DISTINCT FROM NEW.tenant_association_operation_id + OR selected_launch.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR selected_launch.captured_starting_row_version IS DISTINCT FROM NEW.captured_starting_row_version + OR selected_launch.complete_launch_binding_evidence -> 'descriptor' ->> 'requestDigest' + IS DISTINCT FROM NEW.descriptor_request_digest + OR selected_launch.complete_launch_binding_evidence -> 'descriptor' ->> 'resultDigest' + IS DISTINCT FROM NEW.descriptor_result_digest + OR selected_launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest' + IS DISTINCT FROM NEW.release_attestation_digest + OR selected_launch.catalog_creation_request_id IS DISTINCT FROM NEW.catalog_creation_request_id + OR selected_launch.catalog_revision IS DISTINCT FROM NEW.catalog_revision + OR selected_launch.catalog_source_intake_operation_id IS DISTINCT FROM NEW.catalog_source_intake_operation_id + OR selected_launch.catalog_source_intake_request_id IS DISTINCT FROM NEW.catalog_source_intake_request_id + OR selected_catalog.world_slug IS DISTINCT FROM NEW.world_slug + OR selected_catalog.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR selected_catalog.catalog_revision IS DISTINCT FROM NEW.catalog_revision + OR selected_catalog.creation_request_id IS DISTINCT FROM NEW.catalog_creation_request_id + OR selected_catalog.source_intake_operation_id IS DISTINCT FROM NEW.catalog_source_intake_operation_id + OR selected_catalog.source_intake_request_id IS DISTINCT FROM NEW.catalog_source_intake_request_id + OR selected_catalog.request_digest IS DISTINCT FROM NEW.catalog_request_digest + OR selected_catalog.receipt_digest IS DISTINCT FROM NEW.catalog_receipt_digest + OR selected_catalog.visible IS DISTINCT FROM TRUE + OR selected_catalog.public_production IS DISTINCT FROM TRUE + OR selected_catalog.state_scope IS DISTINCT FROM 'SHARED' + OR hold_request_json -> 'request' ->> 'targetNamespace' IS DISTINCT FROM NEW.target_namespace + OR hold_request_json -> 'request' ->> 'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR hold_request_json -> 'request' ->> 'worldSlug' IS DISTINCT FROM NEW.world_slug + OR hold_request_json -> 'request' ->> 'realmId' IS DISTINCT FROM NEW.realm_id::TEXT + OR hold_request_json -> 'request' ->> 'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR hold_request_json -> 'request' ->> 'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR hold_request_json -> 'request' ->> 'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR hold_request_json -> 'request' ->> 'canonicalVersionId' + IS DISTINCT FROM (NEW.canonical_version_id)::TEXT + OR hold_request_json -> 'request' ->> 'initialAdmissionRequestId' IS DISTINCT FROM NEW.initial_admission_request_id + OR hold_request_json -> 'request' ->> 'initialAdmissionRequestDigest' IS DISTINCT FROM NEW.request_digest + OR hold_request_json -> 'request' ->> 'expectedCatalogRevision' IS DISTINCT FROM NEW.catalog_revision::TEXT + OR (hold_request_json -> 'request' ->> 'initialAdmissionOrigin' + IS DISTINCT FROM 'NO_PRIOR_POINTER' + AND hold_request_json -> 'request' ->> 'initialAdmissionOrigin' + IS DISTINCT FROM 'EXPECT_CLOSED') + OR (hold_request_json -> 'request' ->> 'initialAdmissionOrigin' = 'NO_PRIOR_POINTER' + AND hold_request_json -> 'request' ->> 'expectedPriorPointerVersion' IS NOT NULL) + OR (hold_request_json -> 'request' ->> 'initialAdmissionOrigin' = 'EXPECT_CLOSED' + AND hold_request_json -> 'request' ->> 'expectedPriorPointerVersion' IS DISTINCT FROM '1') + OR hold_request_json -> 'request' ->> 'activeLifecycleEpoch' IS NULL + OR hold_request_json -> 'request' ->> 'activeLifecycleEpoch' !~ '^[1-9][0-9]{0,18}$' + OR NEW.request_digest <> expected_request_digest + THEN + RAISE EXCEPTION 'New initial-admission intent must retain the exact V43 launch tuple and catalog binding' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF (to_jsonb(NEW) - 'state' - 'updated_at' - 'terminal_at' - 'hold_identity_bytes') + IS DISTINCT FROM + (to_jsonb(OLD) - 'state' - 'updated_at' - 'terminal_at' - 'hold_identity_bytes') THEN + RAISE EXCEPTION 'Canonical initial-admission intent identity is immutable' + USING ERRCODE = '23514'; + END IF; + IF OLD.state = 'PENDING_HOLD' + AND NEW.state = 'HOLD_ATTACHED' + AND OLD.hold_identity_bytes IS NULL + AND NEW.hold_identity_bytes IS NOT NULL + AND NEW.terminal_at IS NULL THEN + RETURN NEW; + END IF; + IF OLD.state = 'HOLD_ATTACHED' + AND NEW.state = 'TERMINAL' + AND OLD.hold_identity_bytes IS NOT NULL + AND NEW.hold_identity_bytes = OLD.hold_identity_bytes + AND NEW.terminal_at IS NOT NULL + AND EXISTS ( + SELECT 1 FROM game_session_canonical_initial_admission_attempt attempt + WHERE attempt.target_namespace = NEW.target_namespace + AND attempt.initial_admission_request_id = NEW.initial_admission_request_id + AND attempt.status IN ('COMMITTED', 'ABORTED') + AND attempt.account_protection_evidence_version = 1 + AND attempt.account_protection_evidence_bytes IS NOT NULL + AND attempt.terminal_at = NEW.terminal_at) + THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Canonical initial-admission intent permits only one exact hold attach and terminal transition' + USING ERRCODE = '23514'; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Canonical initial-admission attempts cannot be deleted' + USING ERRCODE = '23514'; + END IF; + + IF TG_OP = 'INSERT' AND NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'New canonical initial-admission attempts must begin PENDING' + USING ERRCODE = '23514'; + END IF; + + IF NEW.status = 'PENDING' THEN + IF NEW.account_protection_evidence_version IS NOT NULL + OR NEW.account_protection_id IS NOT NULL + OR NEW.account_protection_fence IS NOT NULL + OR NEW.original_owner_attempt_id IS NOT NULL + OR NEW.original_owner_mutation_id IS NOT NULL + OR NEW.original_owner_fence IS NOT NULL + OR NEW.account_protection_evidence_bytes IS NOT NULL THEN + RAISE EXCEPTION 'PENDING initial-admission attempts cannot carry terminal Account protection' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status NOT IN ('COMMITTED', 'ABORTED') + OR NEW.account_protection_evidence_version IS DISTINCT FROM 1 + OR NEW.account_protection_id IS NULL + OR NEW.account_protection_fence IS NULL + OR NEW.account_protection_fence <= 0 + OR NEW.original_owner_attempt_id IS NULL + OR NEW.original_owner_mutation_id IS NULL + OR NEW.original_owner_fence IS NULL + OR NEW.original_owner_fence <= 0 + OR NEW.account_protection_evidence_bytes IS NULL + OR octet_length(NEW.account_protection_evidence_bytes) NOT BETWEEN 1 AND 8388608 + THEN + RAISE EXCEPTION 'New canonical initial-admission terminal requires complete retained Account protection evidence' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_initial_admission_terminal_requires_protection'; + END IF; + + IF TG_OP = 'UPDATE' + AND (OLD.status <> 'PENDING' + OR OLD.account_protection_evidence_version IS NOT NULL + OR OLD.account_protection_id IS NOT NULL + OR OLD.account_protection_fence IS NOT NULL + OR OLD.original_owner_attempt_id IS NOT NULL + OR OLD.original_owner_mutation_id IS NOT NULL + OR OLD.original_owner_fence IS NOT NULL + OR OLD.account_protection_evidence_bytes IS NOT NULL) + THEN + RAISE EXCEPTION 'Terminal Account protection evidence is immutable' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO selected_intent + FROM game_session_canonical_initial_admission_intent + WHERE target_namespace = NEW.target_namespace + AND initial_admission_request_id = NEW.initial_admission_request_id; + SELECT * INTO selected_launch + FROM game_session_canonical_instance_launch + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = selected_intent.control_plane_request_id; + SELECT * INTO selected_catalog + FROM game_session_canonical_realm_catalog + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND realm_id = NEW.realm_id; + SELECT * INTO selected_original + FROM game_session_start_session_operator_attempt + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = selected_intent.control_plane_request_id + AND owner_attempt_id = NEW.original_owner_attempt_id; + + IF selected_intent.target_namespace IS NULL + OR selected_intent.state <> 'HOLD_ATTACHED' + OR selected_intent.terminal_at IS NOT NULL + OR selected_intent.hold_identity_bytes IS NULL + OR selected_launch.target_namespace IS NULL + OR selected_catalog.target_namespace IS NULL + OR selected_original.target_namespace IS NULL + OR selected_original.phase_state <> 'OWNER_EXECUTION_PENDING' + OR selected_intent.request_digest <> NEW.request_digest + OR selected_intent.canonical_tenant_id <> NEW.canonical_tenant_id + OR selected_intent.world_slug <> NEW.world_slug + OR selected_intent.realm_id <> NEW.realm_id + OR selected_intent.playable_state_namespace_id <> NEW.playable_state_namespace_id + OR selected_intent.playable_state_scope <> NEW.playable_state_scope + OR selected_intent.canonical_game_instance_id <> NEW.canonical_game_instance_id + OR selected_intent.canonical_version_id <> NEW.canonical_version_id + OR selected_intent.game_session_tenant_id <> NEW.game_session_tenant_id + OR selected_intent.game_instance_id <> NEW.game_instance_id + OR selected_intent.runtime_version_id <> NEW.runtime_version_id + OR selected_intent.catalog_revision <> NEW.expected_catalog_revision + OR selected_intent.control_plane_request_id <> selected_original.control_plane_request_id + OR selected_launch.original_start_session_tuple <> selected_original.post_authorization_execution_tuple + OR selected_launch.original_start_session_tuple IS NULL + OR selected_intent.original_start_session_tuple IS DISTINCT FROM selected_launch.original_start_session_tuple + OR selected_intent.launch_descriptor_id <> selected_launch.launch_descriptor_id + OR selected_intent.captured_starting_row_version <> selected_launch.captured_starting_row_version + OR selected_launch.complete_launch_binding_evidence -> 'descriptor' ->> 'requestDigest' + IS DISTINCT FROM selected_intent.descriptor_request_digest + OR selected_launch.complete_launch_binding_evidence -> 'descriptor' ->> 'resultDigest' + IS DISTINCT FROM selected_intent.descriptor_result_digest + OR selected_launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest' + IS DISTINCT FROM selected_intent.release_attestation_digest + OR selected_intent.tenant_association_operation_id <> selected_launch.tenant_association_operation_id + OR selected_intent.catalog_source_intake_operation_id <> selected_launch.catalog_source_intake_operation_id + OR selected_intent.catalog_source_intake_request_id <> selected_launch.catalog_source_intake_request_id + OR selected_original.owner_mutation_id <> NEW.original_owner_mutation_id + OR selected_original.owner_fence <> NEW.original_owner_fence + OR selected_original.lease_expires_at <= clock_timestamp() + OR selected_original.canonical_tenant_id <> NEW.canonical_tenant_id + OR selected_catalog.creation_request_id <> selected_intent.catalog_creation_request_id + OR selected_catalog.catalog_revision <> selected_intent.catalog_revision + OR selected_catalog.source_intake_operation_id <> selected_intent.catalog_source_intake_operation_id + OR selected_catalog.source_intake_request_id <> selected_intent.catalog_source_intake_request_id + OR selected_catalog.request_digest <> selected_intent.catalog_request_digest + OR selected_catalog.receipt_digest <> selected_intent.catalog_receipt_digest + OR selected_launch.catalog_creation_request_id <> selected_catalog.creation_request_id + OR selected_launch.catalog_revision <> selected_catalog.catalog_revision + OR selected_launch.catalog_source_intake_operation_id <> selected_catalog.source_intake_operation_id + OR selected_launch.catalog_source_intake_request_id <> selected_catalog.source_intake_request_id + OR selected_launch.playable_state_scope <> selected_catalog.state_scope + OR selected_launch.public_production IS NOT TRUE + OR selected_catalog.visible IS NOT TRUE + OR selected_catalog.public_production IS NOT TRUE + OR selected_catalog.state_scope <> 'SHARED' + THEN + RAISE EXCEPTION 'Terminal Account protection is not linked to the exact V28 intent, V43 launch/catalog, and V35 original owner' + USING ERRCODE = '23514'; + END IF; + + BEGIN + evidence_json := convert_from(NEW.account_protection_evidence_bytes, 'UTF8')::JSONB; + evidence_request_bytes := decode(evidence_json ->> 'requestBytesBase64', 'base64'); + evidence_request := convert_from(evidence_request_bytes, 'UTF8')::JSONB; + evidence_tuple_bytes := decode(evidence_request ->> 'originalPostAuthorizationTupleBytesBase64', 'base64'); + evidence_projection_bytes := decode(evidence_request ->> 'accountRedemptionProjectionBytesBase64', 'base64'); + evidence_hold_bytes := decode(evidence_request ->> 'worldAdmissionHoldIdentityBytesBase64', 'base64'); + hold_json := convert_from(evidence_hold_bytes, 'UTF8')::JSONB; + hold_request_json := convert_from(decode(hold_json ->> 'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Terminal Account protection evidence bytes are not structurally readable' + USING ERRCODE = '23514'; + END; + + IF evidence_json ->> 'schema' IS DISTINCT FROM 'account-start-session-admission-protection-evidence/v1' + OR jsonb_typeof(evidence_json -> 'sourceEvidenceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(evidence_json -> 'sourceEvidenceVector') < 1 + OR evidence_request ->> 'schema' IS DISTINCT FROM 'account-start-session-admission-protection-request/v1' + OR evidence_json ->> 'accountProtectionId' IS DISTINCT FROM NEW.account_protection_id::TEXT + OR evidence_json ->> 'accountProtectionFence' IS DISTINCT FROM NEW.account_protection_fence::TEXT + OR evidence_request ->> 'gameSessionOwnerAttemptId' IS DISTINCT FROM NEW.original_owner_attempt_id::TEXT + OR evidence_request ->> 'gameSessionOwnerMutationId' IS DISTINCT FROM NEW.original_owner_mutation_id::TEXT + OR evidence_request ->> 'gameSessionOwnerFence' IS DISTINCT FROM NEW.original_owner_fence::TEXT + OR evidence_request ->> 'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(selected_original.lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR evidence_tuple_bytes IS DISTINCT FROM selected_original.post_authorization_execution_tuple + OR evidence_tuple_bytes IS DISTINCT FROM selected_launch.original_start_session_tuple + OR evidence_projection_bytes IS DISTINCT FROM selected_original.account_redemption_projection + OR selected_original.account_redemption_projection IS NULL + OR evidence_hold_bytes IS DISTINCT FROM selected_intent.hold_identity_bytes + OR hold_json ->> 'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' + OR hold_json ->> 'holdId' IS DISTINCT FROM NEW.hold_id::TEXT + OR hold_json ->> 'holdFence' IS DISTINCT FROM NEW.hold_fence::TEXT + OR hold_json ->> 'holdBindingDigest' IS DISTINCT FROM NEW.hold_binding_digest + OR hold_request_json ->> 'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR jsonb_typeof(hold_request_json -> 'request') IS DISTINCT FROM 'object' + OR hold_request_json -> 'request' ->> 'targetNamespace' IS DISTINCT FROM NEW.target_namespace + OR hold_request_json -> 'request' ->> 'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR hold_request_json -> 'request' ->> 'worldSlug' IS DISTINCT FROM NEW.world_slug + OR hold_request_json -> 'request' ->> 'realmId' IS DISTINCT FROM NEW.realm_id::TEXT + OR hold_request_json -> 'request' ->> 'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR hold_request_json -> 'request' ->> 'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR hold_request_json -> 'request' ->> 'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR hold_request_json -> 'request' ->> 'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR hold_request_json -> 'request' ->> 'activeLifecycleEpoch' IS DISTINCT FROM NEW.active_lifecycle_epoch::TEXT + OR hold_request_json -> 'request' ->> 'initialAdmissionRequestId' IS DISTINCT FROM NEW.initial_admission_request_id + OR hold_request_json -> 'request' ->> 'initialAdmissionRequestDigest' IS DISTINCT FROM NEW.request_digest + OR hold_request_json -> 'request' ->> 'initialAdmissionOrigin' IS DISTINCT FROM NEW.origin_kind + OR hold_request_json -> 'request' ->> 'expectedCatalogRevision' IS DISTINCT FROM NEW.expected_catalog_revision::TEXT + OR COALESCE(hold_request_json -> 'request' ->> 'expectedPriorPointerVersion', '') + IS DISTINCT FROM COALESCE(NEW.expected_prior_pointer_version::TEXT, '') + OR decode(hold_json ->> 'requestBytesBase64', 'base64') IS DISTINCT FROM selected_intent.canonical_hold_request_bytes + THEN + RAISE EXCEPTION 'Full Account protection evidence differs from its exact tuple, projection, lease, V35 owner, or World hold' + USING ERRCODE = '23514'; + END IF; + + -- Re-derive the established CanonicalInitialAdmissionRequest digest from the exact V28 fields + -- using the same int32 big-endian UTF-8 byte-length framing as ADR0047 and the Java owner. + digest_bytes := ''::BYTEA; + domain_bytes := convert_to('game-session-canonical-initial-admission/v1', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.target_namespace, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.canonical_tenant_id::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.world_slug, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.realm_id::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.playable_state_namespace_id::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.playable_state_scope, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.canonical_game_instance_id::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.canonical_version_id::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.active_lifecycle_epoch::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.expected_catalog_revision::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.origin_kind, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(NEW.expected_prior_pointer_version::TEXT, ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.initial_admission_request_id, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + expected_request_digest := encode(sha256(digest_bytes), 'hex'); + IF NEW.request_digest <> expected_request_digest THEN + RAISE EXCEPTION 'Canonical initial-admission request digest does not bind the exact V28 fields' + USING ERRCODE = '23514'; + END IF; + + IF NEW.status = 'COMMITTED' THEN + IF NEW.pointer_id IS NULL OR NEW.pointer_version IS NULL OR NEW.audit_event_id IS NULL + OR NEW.abort_reason IS NOT NULL OR NEW.abort_proof_digest IS NOT NULL THEN + RAISE EXCEPTION 'COMMITTED initial-admission terminal fields are incomplete or mixed' + USING ERRCODE = '23514'; + END IF; + terminal_at_text := to_char(NEW.terminal_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'); + ELSE + IF NEW.pointer_id IS NOT NULL OR NEW.pointer_version IS NOT NULL OR NEW.audit_event_id IS NOT NULL + OR NEW.abort_reason IS NULL OR NEW.commit_proof_digest IS NOT NULL THEN + RAISE EXCEPTION 'ABORTED initial-admission terminal fields are incomplete or mixed' + USING ERRCODE = '23514'; + END IF; + terminal_at_text := to_char(NEW.terminal_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'); + END IF; + + digest_bytes := ''::BYTEA; + domain_bytes := convert_to('game-session-canonical-initial-admission-terminal/v1', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + digest_bytes := digest_bytes || int4send(octet_length(NEW.account_protection_evidence_bytes)) + || NEW.account_protection_evidence_bytes; + domain_bytes := convert_to(NEW.request_digest, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.status, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(NEW.pointer_id::TEXT, ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(NEW.pointer_version::TEXT, ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(NEW.audit_event_id::TEXT, ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(terminal_at_text, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(NEW.abort_reason, ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + IF NEW.status = 'COMMITTED' THEN + NEW.commit_proof_digest := 'sha256:' || encode(sha256(digest_bytes), 'hex'); + ELSE + NEW.abort_proof_digest := 'sha256:' || encode(sha256(digest_bytes), 'hex'); + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_initial_admission_v44_terminal_evidence +BEFORE INSERT OR UPDATE ON game_session_canonical_initial_admission_attempt +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_initial_admission_account_terminal_evidence(); + +CREATE TRIGGER game_session_canonical_initial_admission_intent_v44_immutable +BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_initial_admission_intent +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_initial_admission_account_terminal_evidence(); + +CREATE FUNCTION reject_game_session_canonical_initial_admission_protection_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_session_canonical_initial_admission_attempt + WHERE account_protection_evidence_bytes IS NOT NULL) + OR EXISTS (SELECT 1 FROM game_session_canonical_initial_admission_intent + WHERE hold_identity_bytes IS NOT NULL) THEN + RAISE EXCEPTION 'Canonical initial-admission Account protection evidence cannot be truncated' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER game_session_canonical_initial_admission_protection_no_truncate +BEFORE TRUNCATE ON game_session_canonical_initial_admission_attempt +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_initial_admission_protection_truncate(); +CREATE TRIGGER game_session_canonical_initial_admission_intent_no_truncate +BEFORE TRUNCATE ON game_session_canonical_initial_admission_intent +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_initial_admission_protection_truncate(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInitialAdmissionRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInitialAdmissionRepositoryTest.java new file mode 100644 index 0000000000..7530cb6b68 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInitialAdmissionRepositoryTest.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionCanonicalInitialAdmissionRepositoryTest { + @Test + void retainedDatabaseIdentifiersCompareByNumericValuePastBoxCache() { + Record readback = mock(Record.class); + Record ownerAttempt = mock(Record.class); + Long readbackId = Long.valueOf(128L); + Long ownerId = Long.valueOf(128L); + when(readback.get("pointer_id", Long.class)).thenReturn(readbackId); + when(ownerAttempt.get("pointer_id", Long.class)).thenReturn(ownerId); + + assertThat(readbackId).isNotSameAs(ownerId); + assertThat( + GameSessionCanonicalInitialAdmissionRepository.sameRequiredLongValue( + readback, "pointer_id", ownerAttempt, "pointer_id")) + .isTrue(); + + when(ownerAttempt.get("pointer_id", Long.class)).thenReturn(Long.valueOf(129L)); + assertThat( + GameSessionCanonicalInitialAdmissionRepository.sameRequiredLongValue( + readback, "pointer_id", ownerAttempt, "pointer_id")) + .isFalse(); + } + + @Test + void publicOwnerReadRejectsAmbientTransactionBeforeStorage() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var repository = + new GameSessionCanonicalInitialAdmissionRepository( + dsl, + transactionManager, + "test", + mock(GameSessionStartSessionOperatorAttemptRepository.class), + mock(GameSessionCanonicalRealmCatalogRepository.class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> repository.readTerminal(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("own their independent transactions"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + verifyNoInteractions(dsl, transactionManager); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionAdmissionTerminalReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionAdmissionTerminalReadGrpcServiceTest.java new file mode 100644 index 0000000000..ffc5dfd4ab --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionAdmissionTerminalReadGrpcServiceTest.java @@ -0,0 +1,484 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalGrpcCodec; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalResult; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionAdmissionTerminalReadGrpcService; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionAdmissionTerminalRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionAdmissionTerminalResponse; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** Mocked owner dispatch proof only; genuine owner and mTLS composition requires native proof. */ +class OriginalStartSessionAdmissionTerminalReadGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID MUTATION = uuid("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"); + private static final UUID ATTEMPT = uuid("ec13cc04-ec15-4eb8-a018-c2c5e8da65f8"); + private static final UUID PARTICIPATION = uuid("47b3be7f-a32f-4e19-8916-8c3b8da07a82"); + private static final UUID HOLD_ID = uuid("0db7344a-1e67-4b95-905a-83dc9c472f0c"); + private static final UUID HOLD_FENCE = uuid("52a14272-f9e4-4f67-97c9-62247b5fbcc1"); + private static final UUID PROTECTION_ID = uuid("6b763f1d-c5bc-4080-b499-d29debc0a7b8"); + private static final String PROOF_DIGEST = "sha256:" + "e".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final GameSessionCanonicalInitialAdmissionRepository repository = + mock(GameSessionCanonicalInitialAdmissionRepository.class); + private final OriginalStartSessionAdmissionTerminalReadGrpcService service = + new OriginalStartSessionAdmissionTerminalReadGrpcService(repository, NAMESPACE); + + @AfterEach + void clearAmbientState() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void missingPeerIsUnauthenticatedBeforeMalformedRequestOrStorage() { + var observer = new RecordingObserver(); + Context.ROOT.run( + () -> + service.readOriginalStartSessionAdmissionTerminal( + ReadOriginalStartSessionAdmissionTerminalRequest.getDefaultInstance(), observer)); + assertDenied(observer, Status.Code.UNAUTHENTICATED); + verifyNoInteractions(repository); + } + + @Test + void wrongOrCrossNamespacePeerAndEndUserContextAreDeniedBeforeStorage() { + for (String uri : + List.of( + "spiffe://firemud/ns/world-runtime/sa/world-management-service", + "spiffe://firemud/ns/other-runtime/sa/account-service")) { + assertDenied( + invoke(uri, ReadOriginalStartSessionAdmissionTerminalRequest.getDefaultInstance()), + Status.Code.PERMISSION_DENIED); + } + + SessionContext.setContext("42", List.of("tenantAdmin"), Map.of()); + assertDenied(invokeAccount(wire()), Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void malformedUnknownAndConfiguredNamespaceSubstitutionAreDenied() { + var unknown = + wire().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertDenied( + invokeAccount(ReadOriginalStartSessionAdmissionTerminalRequest.getDefaultInstance()), + Status.Code.INVALID_ARGUMENT); + assertDenied(invokeAccount(unknown), Status.Code.INVALID_ARGUMENT); + assertDenied( + invoke("spiffe://firemud/ns/other-runtime/sa/account-service", wire()), + Status.Code.PERMISSION_DENIED); + assertDenied( + invoke( + new OriginalStartSessionAdmissionTerminalReadGrpcService(repository, "other-runtime"), + "spiffe://firemud/ns/other-runtime/sa/account-service", + wire()), + Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void ambientTransactionAndSynchronizationAreRejectedBeforeOwnerRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertDenied(invokeAccount(wire()), Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertDenied(invokeAccount(wire()), Status.Code.FAILED_PRECONDITION); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions(repository); + } + + @Test + void absentOrPendingOwnerOutcomeIsNotTerminalOrInferredAbort() { + var expected = request(); + when(repository.readTerminal(expected)).thenReturn(Optional.empty()); + assertDenied(invokeAccount(wire()), Status.Code.FAILED_PRECONDITION); + verify(repository).readTerminal(expected); + verifyNoMoreInteractions(repository); + } + + @Test + void unavailableOwnerStorageCannotManufactureTerminalEvidence() { + var expected = request(); + when(repository.readTerminal(expected)) + .thenThrow(new DataAccessException("test-only unavailable storage")); + assertDenied(invokeAccount(wire()), Status.Code.UNAVAILABLE); + verify(repository).readTerminal(expected); + verifyNoMoreInteractions(repository); + } + + @Test + void conflictingReturnedAccountBindingIsRejected() { + var conflictingRequest = mock(OriginalStartSessionAdmissionTerminalRequest.class); + when(conflictingRequest.canonicalBytes()).thenReturn(new byte[] {1}); + var result = mock(OriginalStartSessionAdmissionTerminalResult.class); + when(result.request()).thenReturn(conflictingRequest); + when(repository.readTerminal(ArgumentMatchers.any())).thenReturn(Optional.of(result)); + + assertDenied(invokeAccount(wire()), Status.Code.FAILED_PRECONDITION); + verify(repository).readTerminal(request()); + verifyNoMoreInteractions(repository); + } + + @Test + void returnsExactTerminalOwnerEncodingForCompleteAccountEvidence() { + var expected = request(); + var result = + terminalResult(expected, GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + when(repository.readTerminal(expected)).thenReturn(Optional.of(result)); + + var observer = invokeAccount(wire()); + + assertThat(observer.error()).isNull(); + assertThat(observer.completed()).isTrue(); + assertThat(observer.response()) + .isEqualTo(OriginalStartSessionAdmissionTerminalGrpcCodec.toResponse(result)); + var decoded = + OriginalStartSessionAdmissionTerminalGrpcCodec.fromResponse(expected, observer.response()); + assertThat(decoded.canonicalBytes()).containsExactly(result.canonicalBytes()); + verify(repository).readTerminal(expected); + verifyNoMoreInteractions(repository); + } + + private RecordingObserver invokeAccount( + ReadOriginalStartSessionAdmissionTerminalRequest request) { + return invoke("spiffe://firemud/ns/world-runtime/sa/account-service", request); + } + + private RecordingObserver invoke( + String uri, ReadOriginalStartSessionAdmissionTerminalRequest request) { + return invoke(service, uri, request); + } + + private RecordingObserver invoke( + OriginalStartSessionAdmissionTerminalReadGrpcService target, + String uri, + ReadOriginalStartSessionAdmissionTerminalRequest request) { + var observer = new RecordingObserver(); + var peer = net.firedevops.firemud.common.grpc.GrpcPeerIdentity.parseUri(uri).orElseThrow(); + Context.current() + .withValue(net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> target.readOriginalStartSessionAdmissionTerminal(request, observer)); + return observer; + } + + private ReadOriginalStartSessionAdmissionTerminalRequest wire() { + return OriginalStartSessionAdmissionTerminalGrpcCodec.toRequest(request()); + } + + private static OriginalStartSessionAdmissionTerminalRequest request() { + return new OriginalStartSessionAdmissionTerminalRequest(evidence().canonicalBytes()); + } + + private static net.firedevops.firemud.common.account.startsession + .AccountStartSessionAdmissionProtectionEvidence + evidence() { + var tuple = originalTuple(); + var protectionRequest = + net.firedevops.firemud.common.account.startsession + .AccountStartSessionAdmissionProtectionRequest.create( + tuple.canonicalBytes(), + net.firedevops.firemud.common.account.startsession + .StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + MUTATION, + ATTEMPT, + 21L, + Instant.parse("2026-10-09T10:20:30.456Z"), + PARTICIPATION, + 22L, + hold(tuple)); + byte[] capture = + canonical( + Map.of( + "schema", + net.firedevops.firemud.common.account.startsession + .AccountStartSessionAdmissionProtectionEvidence.SOURCE_CAPTURE_REFERENCE_SCHEMA, + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "capturedAt", + "2026-10-09T10:11:12.123Z", + "bundleReference", + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "sourceVersion", + "17", + "sourceFence", + "23", + "linearization", + "18446744073709551615"), + "snapshotSha256", + "d".repeat(64))); + return net.firedevops.firemud.common.account.startsession + .AccountStartSessionAdmissionProtectionEvidence.create( + protectionRequest, + PROTECTION_ID, + 23L, + capture, + sha256(capture), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + TENANT.toString(), + "2", + "17", + null, + null, + "exact account source".getBytes(StandardCharsets.UTF_8)))); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple() { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "terminal-read-test", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical original StartSession admission attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + return canonical( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of("tenantId", TENANT.toString(), "targetNamespace", NAMESPACE), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + ACTOR.toString(), + "applicableTenantId", + TENANT.toString()), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + "2026-10-09T00:00:00Z", + "expiresAt", + "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 2L, + "tenantAuthorityGeneration", + Map.of(TENANT.toString(), 3L), + "membershipAuthorityGeneration", + Map.of(TENANT.toString(), 4L), + "privateRealmGrantVersions", + List.of()), + "membershipVersion", + Map.of(TENANT.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"))); + } + + private static WorldCanonicalInitialAdmissionHold.HoldIdentity hold( + StartSessionPostAuthorizationExecutionTuple tuple) { + return new WorldCanonicalInitialAdmissionHold.HoldIdentity( + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "earth", + uuid("3916f423-2870-426a-a8aa-5e3f97412613"), + uuid("54e6094e-11bb-4f4c-93ee-a52f715b530b"), + "SHARED", + uuid("a55b2e10-9a24-4adb-adb8-6fc66fe3b8e9"), + uuid("d7280ec0-5979-4b62-8418-e9f139415184"), + 3L, + tuple.controlPlaneRequestId(), + "c".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null), + HOLD_ID, + HOLD_FENCE); + } + + private static OriginalStartSessionAdmissionTerminalResult terminalResult( + OriginalStartSessionAdmissionTerminalRequest request, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome outcome) { + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + request.protectionEvidence().request().worldAdmissionHoldIdentity(), + outcome, + 1L, + 23L, + PROOF_DIGEST, + false, + Instant.parse("2026-10-09T10:20:30Z")); + return new OriginalStartSessionAdmissionTerminalResult(request, proof); + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static void assertDenied(RecordingObserver observer, Status.Code status) { + assertThat(observer.response()).isNull(); + assertThat(observer.completed()).isFalse(); + assertThat(observer.error()).isEqualTo(status); + } + + private static final class RecordingObserver + implements StreamObserver { + private ReadOriginalStartSessionAdmissionTerminalResponse response; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadOriginalStartSessionAdmissionTerminalResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + + ReadOriginalStartSessionAdmissionTerminalResponse response() { + return response; + } + + Status.Code error() { + return error; + } + + boolean completed() { + return completed; + } + } +} From a336f4245a46742bda991eba73addf31dcc689b5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:55:42 +1300 Subject: [PATCH 105/129] Bind original activation protection and retained authored-core owner handoffs --- .../account-service/api-contracts.md | 8 + .../runtime-and-data.md | 4 +- .../game-design-service/game-templates.md | 8 + .../game-session-service/runtime-and-data.md | 4 + .../world-management-service/api-contracts.md | 8 +- ...ame-authoring-publishing-and-activation.md | 8 +- ...on_activation_protection_acquisition.proto | 37 + ...ion_activation_protection_settlement.proto | 36 + .../v1/authored_initial_actor_core_read.proto | 40 + ...al_start_session_launch_read_service.proto | 30 + ...art_session_activation_terminal_read.proto | 27 + ...l_start_session_protected_activation.proto | 28 + ...SessionActivationProtectionRepository.java | 874 ++++++++++++ ...ationProtectionAcquisitionGrpcService.java | 101 ++ ...ctivationProtectionAcquisitionService.java | 472 +++++++ ...vationProtectionSettlementGrpcService.java | 95 ++ ...ActivationProtectionSettlementService.java | 263 ++++ ...al_start_session_activation_protection.sql | 391 ++++++ ...ssion_activation_protection_settlement.sql | 235 ++++ ...tionProtectionPostgresIntegrationTest.java | 1021 ++++++++++++++ ...ionActivationProtectionRepositoryTest.java | 198 +++ ...nProtectionAcquisitionGrpcServiceTest.java | 141 ++ ...ationProtectionAcquisitionServiceTest.java | 133 ++ ...onProtectionSettlementGrpcServiceTest.java | 165 +++ ...vationProtectionSettlementServiceTest.java | 287 ++++ ...StartSessionAuthorizationProofFixture.java | 36 + ...ActivationProtectionAcquisitionClient.java | 11 + ...ivationProtectionAcquisitionGrpcCodec.java | 272 ++++ ...nActivationProtectionAcquisitionInput.java | 110 ++ ...rtSessionActivationProtectionEvidence.java | 478 +++++++ ...artSessionActivationProtectionRequest.java | 644 +++++++++ ...nActivationProtectionSettlementClient.java | 7 + ...ctivationProtectionSettlementEvidence.java | 40 + ...tivationProtectionSettlementGrpcCodec.java | 290 ++++ ...onActivationProtectionSettlementInput.java | 32 + ...artSessionAdmissionProtectionEvidence.java | 5 +- ...ActivationProtectionAcquisitionClient.java | 164 +++ ...nActivationProtectionSettlementClient.java | 165 +++ .../AuthoredInitialActorCoreProjection.java | 614 +++++++++ .../AuthoredInitialActorCoreReadClient.java | 10 + .../AuthoredInitialActorCoreReadEvidence.java | 163 +++ ...AuthoredInitialActorCoreReadGrpcCodec.java | 137 ++ ...AuthoredInitialActorCoreSourceBinding.java | 14 + ...rpcAuthoredInitialActorCoreReadClient.java | 146 ++ ...cOriginalStartSessionLaunchReadClient.java | 164 +++ .../OriginalStartSessionLaunchReadClient.java | 10 + ...riginalStartSessionLaunchReadEvidence.java | 363 +++++ ...iginalStartSessionLaunchReadGrpcCodec.java | 111 ++ ...rtSessionActivationTerminalReadClient.java | 149 ++ ...StartSessionProtectedActivationClient.java | 155 +++ ...tartSessionActivationTerminalEvidence.java | 371 +++++ ...rtSessionActivationTerminalReadClient.java | 8 + ...essionActivationTerminalReadGrpcCodec.java | 204 +++ ...artSessionActivationTerminalReadInput.java | 48 + ...StartSessionProtectedActivationClient.java | 12 + ...rtSessionProtectedActivationGrpcCodec.java | 163 +++ ...ionProtectionAcquisitionGrpcCodecTest.java | 111 ++ ...tionProtectionSettlementGrpcCodecTest.java | 143 ++ ...vationProtectionAcquisitionClientTest.java | 83 ++ ...ivationProtectionSettlementClientTest.java | 92 ++ ...uthoredInitialActorCoreProjectionTest.java | 403 ++++++ ...nTemplateAssociationReadGrpcCodecTest.java | 32 + ...ginalStartSessionLaunchReadClientTest.java | 82 ++ ...nalStartSessionLaunchReadEvidenceTest.java | 273 ++++ ...ssionActivationProtectionEvidenceTest.java | 958 +++++++++++++ ...ssionActivationTerminalReadClientTest.java | 94 ++ ...tSessionProtectedActivationClientTest.java | 78 ++ ...SessionActivationTerminalEvidenceTest.java | 507 +++++++ ...onActivationTerminalReadGrpcCodecTest.java | 44 + ...ssionProtectedActivationGrpcCodecTest.java | 113 ++ ...etainedAuthoredActorCoreSourceService.java | 216 +++ ...nedAuthoredActorCoreSourceServiceTest.java | 264 ++++ .../AuthoredInitialActorCoreReadService.java | 436 ++++++ ...pcAuthoredInitialActorCoreReadService.java | 105 ++ .../StartSessionLaunchDescriptorProducer.java | 130 +- ...SessionTemplateAssociationReadService.java | 43 +- ...AuthoredActorCoreProjectionRepository.java | 322 +++++ ...al_start_session_actor_core_projection.sql | 387 ++++++ ...licationExportPostgresIntegrationTest.java | 819 +++++++++-- ...CoreProjectionPostgresIntegrationTest.java | 201 +++ ...thoredInitialActorCoreReadServiceTest.java | 90 ++ ...thoredInitialActorCoreReadServiceTest.java | 91 ++ ...rtSessionLaunchDescriptorProducerTest.java | 101 +- ...oredActorCoreProjectionRepositoryTest.java | 304 ++++ ...nAuthoredActorCoreRetentionRepository.java | 385 ++++++ ...sionCanonicalInstanceLaunchRepository.java | 42 + ...sionAuthoredActorCoreRetentionService.java | 486 +++++++ ...inalStartSessionLaunchReadGrpcService.java | 143 ++ ...d_original_start_session_authored_core.sql | 181 +++ ...rCoreRetentionPostgresIntegrationTest.java | 432 ++++++ ...AuthoredActorCoreRetentionServiceTest.java | 544 ++++++++ ...InstanceLaunchPostgresIntegrationTest.java | 40 + ...horedActorCoreRetentionRepositoryTest.java | 83 ++ ...CanonicalInstanceLaunchRepositoryTest.java | 70 + ...StartSessionLaunchReadGrpcServiceTest.java | 302 ++++ ...CanonicalInstanceActivationRepository.java | 833 ++++++++++- ...rldCanonicalInstanceActivationService.java | 80 +- ...sionActivationTerminalReadGrpcService.java | 112 ++ ...SessionProtectedActivationGrpcService.java | 115 ++ ...tartSessionProtectedActivationService.java | 95 ++ ...nal_start_session_protected_activation.sql | 367 +++++ ...aphApplicationPostgresIntegrationTest.java | 1223 +++++++++++++---- ...otectedActivationAcquisitionMatchTest.java | 65 + ...nicalInstanceActivationRepositoryTest.java | 14 + ...anonicalInstanceActivationServiceTest.java | 59 +- ...ActivationTerminalReadGrpcServiceTest.java | 118 ++ ...ionProtectedActivationGrpcServiceTest.java | 124 ++ ...SessionProtectedActivationServiceTest.java | 200 +++ 108 files changed, 21834 insertions(+), 511 deletions(-) create mode 100644 protos/account/v1/start_session_activation_protection_acquisition.proto create mode 100644 protos/account/v1/start_session_activation_protection_settlement.proto create mode 100644 protos/game-design/v1/authored_initial_actor_core_read.proto create mode 100644 protos/game-session/v1/original_start_session_launch_read_service.proto create mode 100644 protos/world-management/v1/original_start_session_activation_terminal_read.proto create mode 100644 protos/world-management/v1/original_start_session_protected_activation.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcService.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementService.java create mode 100644 services/account-service/src/main/resources/db/migration/V161__original_start_session_activation_protection.sql create mode 100644 services/account-service/src/main/resources/db/migration/V162__original_start_session_activation_protection_settlement.sql create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepositoryTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcServiceTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionInput.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionRequest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementInput.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcAuthoredInitialActorCoreReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionLaunchReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadInput.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjectionTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionLaunchReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/AccountStartSessionActivationProtectionEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodecTest.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceService.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepository.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V73__retained_original_start_session_actor_core_projection.sql create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadServiceTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepositoryTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAuthoredActorCoreRetentionService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionLaunchReadGrpcService.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V45__retained_original_start_session_authored_core.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionLaunchReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationService.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V65__original_start_session_protected_activation.sql create mode 100644 services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldProtectedActivationAcquisitionMatchTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcServiceTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 9cc72747e5..44774269a5 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -183,6 +183,14 @@ The distinct [`AccountSelectedOwnerIntakeSourceReadService.ReadSourceScope`](../ The original StartSession flow has a distinct Account-owned **activation-purpose protection**, separate from the World preparation participation and the later ACTIVE-only Game Session admission protection. Preparation `COMMITTED` retains its existing meaning and does not prove activation. Before World opens its activation transaction, Account acquires this protection under still-valid original authority, binding the unchanged complete source vector and original tuple, exact current Game Session attempt/mutation/fence and finite original lease, actual `STARTING` launch, exact `PREPARING` owner evidence and activation operation identity. It does not issue, renew, redeem or restart authority. Source participation stays pending through World's exact activation compare-and-set. Account may settle only from authenticated exact `ACTIVE` terminal evidence or a positively fenced `ABORTED` result that excludes later activation for the same operation; timeout, expiry, absence, ambiguous evidence and generic handle `close()` cannot release it. Exact committed recovery reuses immutable identities and results without authorizing new work. The [World activation consequence](../world-management-service/api-contracts.md#canonical-initial-activation-protection) owns its local transaction and terminal exclusion. Producer/consumer, crash, expiry and settlement proof remain required before activation is enabled; implementation status belongs to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). +The activation-only closed RFC 8785 request `account-start-session-activation-protection-request/v1` has exactly `schema`, `originalPostAuthorizationTupleBytesBase64`, `accountRedemptionProjectionBytesBase64`, `gameSessionOwnerMutationId`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `originalLeaseExpiresAt`, `accountWorldParticipationId`, `accountWorldParticipationFence`, `gameSessionLaunchReadEvidenceBytesBase64`, `worldActivationRequestId`, and `preparingEvidenceBytesBase64`. It retains both complete authenticated owner observations, not a digest-only summary. Account derives the projection, lease and participation from its actual original records and authenticated current-attempt read, never caller assertions. UUIDs are non-nil canonical values, fences are positive canonical decimal strings, and timestamps preserve exact UTC microseconds. The actual Game Session row must be `STARTING`; its retained original tuple, full descriptor/release, namespace/scope and public-production target must match World's `PREPARING` evidence. World additionally checks the captured realm/catalog against its actual retained owner association at the commit boundary. The stable operation identity excludes only the two transport read correlation IDs; the full first request retains them unchanged, and an exact retry cannot overwrite the first receipt with newer observations. + +The closed `account-start-session-activation-protection-evidence/v1` has exactly `schema`, `requestBytesBase64`, `accountProtectionId`, `accountProtectionFence`, `acquiredAt`, `originalSourceCaptureReferenceBytesBase64`, `originalSourceCaptureReferenceSha256`, and `sourceEvidenceVector`. It preserves the original Account capture reference and all exact source children in canonical key order. Account's positive protection fence and acquisition time belong to its durable owner record; acquisition must precede the unchanged original lease expiry. New activation-carrier construction accepts at most 64 MiB of complete World `PREPARING` evidence, 144 MiB of canonical request, and 200 MiB of canonical evidence including nested base64 overhead. The World child bound is specific to this new Account carrier, not an existing global World API limit; larger values deny without truncation. The existing 41 MiB Game Session result, 256 KiB tuple/capture and 4 MiB source-vector bounds remain independent. Strict decoding rejects unknown, duplicate, trailing, noncanonical, oversized or cross-bound values and proves only integrity, never authentication, currentness, source exclusion or activation. + +The distinct internal `AcquireOriginalStartSessionActivationProtection` method authenticates the exact same-namespace World workload before decoding, with no authenticated end-user context or ambient owner transaction. Its closed version-1 input carries exactly one occurrence of each `schema_version`, `target_namespace`, `original_post_authorization_tuple`, `game_session_owner_mutation_id`, `game_session_owner_attempt_id`, `game_session_owner_fence`, `activation_request_id`, and `world_preparing_evidence`. It cannot supply Account's derived projection, lease, capture, participation or source evidence. Account independently reads the actual Game Session attempt and launch outside SQL, then revalidates original Account authority and source exclusion through its owner commit and independent readback. The response contains only the full first canonical protection receipt, unchanged on exact retry. File-backed mTLS pins the Account recipient; this method has a 60-second deadline, 65 MiB request-wire bound and 200 MiB plus 64 bytes response-wire bound. These limits do not extend the original finite lease or widen any global transport policy. Missing or inconsistent owner evidence denies acquisition. Generated-message decoding proves the closed field occurrences and exact canonical child bytes, not the original protobuf frame's byte encoding; the optional raw-frame validator has a separate exact re-encoding check. Runtime registration and genuine authenticated composition remain activation gates. + +The distinct internal `SettleOriginalStartSessionActivationProtection` method authenticates the exact same-namespace World workload before decoding its lookup-only version-1 request. The request has exactly one occurrence of `schema_version`, `target_namespace`, `settlement_request_id`, `account_protection_id`, and `account_protection_fence`; it carries no asserted World outcome, expiry-based release or replacement authority. Account loads the full first durable protection and obtains the exact [World terminal receipt](../world-management-service/api-contracts.md#canonical-initial-activation-protection) through authenticated owner read outside Account SQL. Within its own transaction, source-key locks precede the protection-row lock; settlement retains the complete original request, capture, ordered source children and exact World result, then requires independent exact readback. The response has exactly one occurrence of `schema_version`, `settlement_request_id`, `account_protection_id`, `account_protection_fence`, `settled_at`, and `terminal_evidence_canonical_bytes`. The response echoes lookup correlation while preserving the original full terminal and PostgreSQL-microsecond settlement time. Historical lookup and exact settlement recovery may outlive the unchanged original lease; they cannot acquire fresh protection or restart activation. Missing or ambiguous terminal evidence leaves the source hold pending. File-backed mTLS pins Account; the method has a 180-second deadline, 512-byte request-wire bound and 768 MiB plus 256 bytes response-wire bound. These carrier-specific limits do not widen global server limits or prove native composition, custody, physical durability or activation readiness. + `IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, and the immutable `authorityEvidenceBundle/v1`; Account never exposes that evidence through an external route, logs, audit text, or client-visible response. `IssueAutomationOperatorAuthorizationReferenceRequest` contains no workload identity field: Account derives `workloadIdentity` from the authenticated mTLS transport peer and rejects any serialized or caller-supplied substitute. It contains `automation_policy_id`, `automation_policy_version`, target owner service, typed target scope, action family, action-family schema identifier/version, `controlPlaneRequestId`, and canonical `mutationDigest`, with no account, end-user token, or human identity. The target request is `non_moderation`-only: published schema pairs must select the branch with `action_category` absent, moderation schema pairs are rejected before issuance, and no concrete schema pairs are published while the route remains target-not-routable. For the supported tenant-scoped branch, Account binds the exact `tenant_generation`; global-role or `privileged_control` authority is rejected rather than inferred. The exact authenticated internal response has the same opaque reference, fingerprint, expiry, and immutable authority-evidence shape; its stored binding includes the authenticated workload and policy evidence plus the applicable generation predicate. `controlPlaneRequestId` and `mutationDigest/v1` cannot be reused for moderation; any future moderation automation contract must declare dedicated request identity, digest, and idempotency semantics with `controlPlaneRequestId` correlation-only. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index ce6bc40a39..007f88656d 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -4,6 +4,8 @@ This document defines Entity Management’s runtime model, persistence ownership ## Implementation Status +The unregistered post-publication authored-core consumer independently reads Game Design through the exact authenticated owner-read client outside Entity SQL, then corroborates the selected source against Entity's retained receipt and the release's immutable Entity participant digest in the existing read-only snapshot. It returns the unchanged qualified result; it neither rewrites the pre-publication `COMMITTED_EMPTY` receipt nor allocates an actor. Its focused tests use mocked reads, so genuine authenticated composition and physical database proof remain open. The complete projection contract remains owned by [Game Design](../game-design-service/game-templates.md#owner-qualified-authored-core-projection), with capability and proof status in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + - The current crafting REST adapter is runtime-reachable legacy implementation drift, not a supported or advertised boundary: the crafting paths and schemas are omitted from the ping-only authoritative OpenAPI, whose root `security: []` applies only to the health contract, so the adapter remains unsupported/nonconformant. The deployed interceptor requires any `AUTHENTICATED` bearer because this non-public path is not in the public-route list, but neither layer provides tenant binding; there is no controller `SessionContext` tenant guard. `CraftingServiceImpl` trusts the DTO's `tenantId`, `resultItemId`, and ingredient item IDs; `CraftingRecipeRepository.findWithIngredientsById` and the update branch use recipe ID alone, while ingredient loading also uses recipe ID alone. The tenant-qualified list methods first select IDs but then re-enter that unqualified lookup, so they are not evidence of an end-to-end tenant predicate. Existing crafting tests do not establish caller-tenant authorization, cross-tenant recipe isolation, or same-tenant result/ingredient ownership. - World-owned `character_location` and `npc_location` tables plus their authoritative movement, occupancy, and read/write paths are target-only. They are absent from the current schema, migrations, and runtime; `room_instance` is topology rather than actor location, and a Game Session room binding is not World location authority. Entity Management must not add competing location persistence or treat a cache/projection as authoritative. - **Target crafting boundary:** require authenticated caller context and exact tenant authorization before any recipe operation, derive the target tenant rather than treating request `tenantId` as authority, and make recipe read/update and ingredient load/update predicates tenant-qualified. Validate that the result item and every ingredient item belong to the target tenant and the same applicable version/Draft scope before writing. A missing context, tenant mismatch, recipe mismatch, or cross-tenant item reference fails closed before any recipe or ingredient mutation; the target negative proof must exercise each case. @@ -347,7 +349,7 @@ Game Design carries the complete descriptor as `creationDescriptor` in the close The descriptor is not a pre-authored actor template or an `OTHER_ACTOR_TEMPLATE_ROOTS` inventory witness. An empty dependency array does not prove an empty Entity family: every one of the 23 Entity source-census obligations and the complete selected World/inbound closure remains required. Selected-source retention and its original owner receipt must bind the complete six-family Game Design content, including this exact policy and descriptor, to the unchanged finalized Account authorization and World evidence. Parsing or retaining the descriptor alone grants no creation, allocation, publication, placement, admission or activation authority; those producer/consumer and commit proofs remain separate obligations in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). -The creation input does not supply a display name, initial disposition or runtime presence. Game Design owns the separate [release-authored initial actor core](../game-design-service/game-templates.md#release-authored-initial-actor-core), including exact selected disposition/feedback provenance and retained-schema preservation. Entity must retain that authored binding with the allocated identity rather than substitute an Account name, neutral default or live profile. Generic actors do not require universal RPG statistics or resources, but each applicable Entity family still needs complete typed owner evidence; absent storage is not empty-state proof. +The creation input does not supply a display name, initial disposition or runtime presence. Game Design owns the separate [release-authored initial actor core](../game-design-service/game-templates.md#release-authored-initial-actor-core), including exact selected disposition/feedback provenance and retained-schema preservation. Entity must independently authenticate and read Game Design's [owner-qualified authored-core projection](../game-design-service/game-templates.md#owner-qualified-authored-core-projection), exact-compare it with the original selected launch, and retain that unchanged binding separately from its pre-publication `EMPTY` receipt. Neither a Game Session forwarding assertion nor a binding digest alone establishes this source. Entity must retain that authored binding with the allocated identity rather than substitute an Account name, neutral default or live profile. Generic actors do not require universal RPG statistics or resources, but each applicable Entity family still needs complete typed owner evidence; absent storage is not empty-state proof. ### Runtime Actor Identity diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 08ddf7b36d..db8193c7e2 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -18,6 +18,14 @@ For bounded `PLAYER_CREATED` entry, Game Design owns the immutable authored init The selected source must resolve the exact `dispositionKey` in the release-admitted Game Logic rules and its mandatory authored `FEEDBACK` entry through `safeFeedbackKey`. The binding retains the complete selected tenant, version and source operation, original policy and rule commit/revision identities and canonical source content, policy selectors, descriptor identity/revision and exact disposition/feedback definitions. Independently advancing, mixed or substituted sources are rejected rather than resolved against a live or latest profile. Account names, neutral disposition defaults and runtime profile inheritance are not source evidence. Generic actors require no universal RPG statistics or resources; applicable owner families still need complete typed inventory proof, with empty or not-applicable families qualified explicitly rather than inferred from missing rows. +#### Owner-Qualified Authored-Core Projection + +Game Design retains and validates the full private publication, source-capture and association binding. The separate closed, versioned authored-core read returns only the owner-validated public projection: canonical tenant and Version, exact world/source operation and evidence digest, selected commit and publication workflow, a durably retained binding identity and its complete original binding digest, complete schema-three policy and its original commit/revision/logical-revision identities, the authored core and exact `EMPTY_OBJECT` descriptor, and the exact disposition and mandatory feedback definitions with each original source commit/digest, revision identity/order and definition digest. A selected snapshot may legitimately inherit a policy or rule from an earlier commit in that exact source scope; retain its original provenance rather than relabeling it or requiring it to originate in the selected commit. Preserve all applicable policies and their original ordering; do not select a convenient first match. Neither the full private binding bytes, publication operation/capture bytes, private numeric target keys nor complete Draft commit source payloads are disclosed. The retained binding identity is Game Design-owned durable evidence, not a newly allocated response identity. Changed sources or public values conflict with the retained binding; digest-only answers are insufficient. + +The qualified read also binds and echoes the complete original Account post-authorization request, actual Game Session attempt/fence and exact selected association, descriptor and release. Reuse the existing Account-confirmed original-operation owner-read qualification before Game Design SQL; a workload certificate, forwarded projection or matching digest alone is not authorization. Game Session retains the unchanged qualified response against its actual launch. Entity authenticates its own independent Game Design read of that same retained source rather than trusting a Game Session forwarding assertion; Game Design independently verifies the read's applicable original-operation authorization. Missing, ambiguous or conflicting request, attempt, association, release or retained binding evidence denies without repairing or reselecting source. This read does not change Entity's pre-publication `EMPTY` receipt or authorize allocation, presence, placement, admission or activation. Its producer, transport, retention and physical proof status belongs in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + +The separate internal `ReadAuthoredInitialActorCore` method accepts only the already-pinned exact-replay association request. It authenticates the exact same-namespace Game Session or Entity workload before decoding, rejects end-user context and ambient owner transactions, and reuses Account original-operation verification before entering the same read-only owner snapshot. The existing association RPC remains restricted to Game Session; this method-specific Entity read does not broaden it. The closed RFC 8785 `game-design-authored-initial-actor-core-read/v1` result contains exactly `schema`, `request`, `associationRead`, `launchDescriptor`, and ordered `projections`; the first three evidence values after the schema retain their exact public protobuf bytes as base64, and each projection carries its complete canonical public bytes and digest. The result's digest binds this whole envelope, not a summary of the source. The per-projection canonical limit is 1 MiB, the whole canonical result independently admits at most 8 MiB, and the response-wire limit is 16 MiB. Exact empty projection lists are valid only when the actual retained owner policy/source snapshot proves them; absence of retained bindings is not proof of emptiness. File-backed mTLS pins Game Design and the client has a five-second deadline. Parsed-message validation checks unknown fields, exact request echoes and canonical evidence children, not duplicate singular fields in the original protobuf frame. Oversize or inconsistent values deny intact; no limit or successful read enables actor allocation or runtime activation. + `presenceState` is not authored initial state. Before authenticated Game Session attachment there is no live presence projection; this immutable binding must not carry guessed `OFFLINE`/`PRESENT` or repurposed `ACTIVE`/`AFK` values. [Game Session](../game-session-service/runtime-and-data.md#persisted-actor-admission-boundary) owns that runtime projection, while World independently owns placement and occupancy. Source parsing, retention or descriptor validation alone grants no actor allocation, placement, admission or activation; the complete producer, consumer and executed proof gates remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). ## Implementation Status diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 3e752e9261..43f997a1dd 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,6 +10,8 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: +- The unregistered original StartSession authored-core retention service and additive V45 retain the unchanged Game Design result against the actual launch and exact original finite owner attempt. Its ordering and synthetic-source PostgreSQL definitions do not establish authenticated producer/consumer composition, actor allocation, attachment, placement or activation. Remote source reads occur outside owner SQL; final retention rechecks the same pending attempt under its owner lock. Exact retained readback does not renew the lease or dispatch another source read. See the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) for proof limits. + - Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet; prepared `String` account-identity carriers still contain numeric row-id text and do not prove UUID consumption. Opaque internal carrier preparation and its retained-record/proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). - The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings. @@ -58,6 +60,8 @@ Game Session does not persist or allocate the primary actor. It resolves the rea The local runtime stores only active attachment, protocol state, presence, and controller-fence data. A playtest copy is selected by its new fork-local `characterId`; `sourceCharacterId` is not used as authority. Current per-instance lookup, unresolved-character fallback, and complete cross-service proof remain gaps. +For original StartSession source retention, Game Session binds Game Design's unchanged [owner-qualified authored-core projection](../game-design-service/game-templates.md#owner-qualified-authored-core-projection) to its actual immutable launch and exact original operation/attempt, selected association, descriptor and release. It does not reconstruct or expose private Game Design proof, pick a newer policy, allocate an actor or authorize Entity through forwarding. Entity independently reads the same authenticated retained Game Design source; missing or conflicting source evidence leaves actor allocation and runtime use denied. + An Entity-allocated durable actor does not establish a Game Session attachment or presence projection. Before authenticated attachment, no live projection exists; the immutable authored release must not carry a guessed presence value, and a consumer must not fabricate `OFFLINE`/`PRESENT` or reuse `ACTIVE`/`AFK` as a bootstrap substitute. A complete runtime-core aggregate requiring presence must fail closed until Game Session's authenticated lifecycle supplies that projection. Entity owns the separate authored display-name/disposition provenance and durable identity, while World independently owns placement and occupancy; see [Entity's runtime actor boundary](../entity-management-service/runtime-and-data.md#runtime-actor-identity). ## Owner-Local Gameplay Restrictions diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 7c075a3b3a..458ec36d78 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -331,6 +331,12 @@ Operator procedure: use the scoped World reconciliation log fields to identify t World's canonical initial `PREPARING → ACTIVE` transaction consumes the distinct [Account activation-purpose protection](../account-service/api-contracts.md#operator-authorization-references) for the unchanged original StartSession flow. Preparation `COMMITTED`, a current launch read or an ACTIVE-only initial-admission hold cannot substitute. All authenticated Account and Game Session owner reads occur before World SQL. Under its local lifecycle serialization, World exact-compares the retained original binding, `STARTING` launch, `PREPARING` evidence, activation identity and unchanged finite lease, including revalidation after lock waits, before the fenced compare-and-set. It atomically retains the exact terminal result with that transition and exposes authenticated immutable readback for Account settlement. A definitive activation abort must durably exclude any later activation for that same operation; missing rows, pending outcomes, elapsed time and failed reads are not abort proof. Historical recovery returns the original result only, without renewing authority or authorizing another transition. Canonical activation remains denied until genuine producer/consumer and crash, expiry and settlement proof passes; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) owns that implementation gap. +The standalone `WorldOriginalStartSessionProtectedActivationService.ActivateOriginalStartSessionProtected` transport authenticates the exact same-namespace Game Session workload and rejects end-user context or ambient transactions before decoding. Its closed schema-version-1 request contains exactly one occurrence each of `schemaVersion`, `targetNamespace`, and the unchanged complete Account `acquisitionInput`; the response contains exactly one `schemaVersion` and complete immutable `terminalEvidence`. An exact stored terminal is returned before Account acquisition. A matching `PENDING` operation is unresolved and cannot reacquire authority or restart its lifecycle transaction. Only an absent original operation may acquire the distinct protection from authenticated Account before World SQL. Closing a process-local handle never settles or releases that durable protection. The file-backed mTLS client pins World, uses a 300-second transport deadline, and independently enforces a 65 MiB + 128-byte request bound and a 768 MiB + 64-byte response bound; that deadline neither extends the original lease nor authorizes retrying execution. This transport remains unregistered and does not raise global message limits. + +The separate `WorldOriginalStartSessionActivationTerminalReadService.ReadOriginalStartSessionActivationTerminalEvidence` authenticates the exact same-namespace Account workload before parsing. Its closed request carries exactly one schema version, namespace, non-nil read correlation UUID, and full retained first Account protection; its response echoes that UUID and returns the complete unchanged World terminal. Missing, pending, conflicting or substituted protection supplies no settlement result. The independent read uses the retained operation and execution fence without requiring fresh execution authority, renewing the original lease or performing activation. It is distinct from preparation terminal recovery and from the Account settlement mutation. Its carrier-specific request bound is the 200 MiB Account evidence limit plus 256 bytes and its response bound is the 768 MiB World terminal limit plus 64 bytes; runtime registration and genuine physical composition remain open. + +The closed RFC 8785 `world-original-start-session-activation-terminal-evidence/v1` receipt has exactly `schema`, `activationRequestId`, `accountProtectionId`, `accountProtectionFence`, `worldActivationFence`, `accountProtectionEvidenceBytesBase64`, `activationResultBytesBase64`, and `activationResultSha256`. It retains the full first Account protection and full original World activation request/result, including historical owner-read correlation IDs, rather than projecting either to a digest. World allocates the positive execution fence in its durable operation row; terminal commit and fenced abort serialize against that same row. Only an exact `COMMITTED` result with its resulting `ACTIVE` lifecycle or a positively fenced immutable `ABORTED` result is terminal. The receipt's own integrity checks do not authenticate that row or prove commit; Account must obtain the receipt from authenticated exact World owner readback before settlement. The intermediate World result has a 384 MiB denial bound; the enclosing receipt independently admits at most 768 MiB including the full Account evidence and all nested base64 expansion. Both bounds apply, so satisfying the intermediate bound does not imply that the enclosing receipt fits. These are carrier-specific denial bounds, not increases to any runtime transport limit. Oversize evidence is rejected intact, never truncated. Retained legacy activation results remain historical evidence and cannot be reinterpreted as this protected terminal. + ## Instance Termination Contract World Management owns the authoritative lifecycle row and monotonic epoch for `gameInstanceId` rows. The lifecycle state, owner registry, cleanup acknowledgements, and Temporal boundary are owned by [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); this section records the World API consequence. Teardown is cross-service: @@ -347,7 +353,7 @@ Termination owner-set and registry-revision snapshot semantics are defined by [I Current implementation notes: -- The live `StartSession` path still uses the legacy numeric `ActivatePreparedWorldInstance` lifecycle transition. The separate canonical UUID activation ledger, service and gRPC adapter are unregistered and default-denied without an explicit held-authority verifier; legacy activation is not proof of that canonical commit boundary. The [World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md) records the remaining genuine producer and activation proof. +- The live `StartSession` path still uses the legacy numeric `ActivatePreparedWorldInstance` lifecycle transition. The separate canonical UUID activation ledger and native protected producer are unregistered; a request-only caller or legacy held-authority verifier cannot authorize fresh canonical activation. The new boundary requires the distinct authenticated Account activation-purpose protection described above, whose complete physical producer/consumer proof remains open. Legacy activation is not proof of that canonical commit boundary. The [World implementation tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md) records the remaining genuine producer and activation proof. - World Management persists `world_instance`, `region_instance`, `zone_instance`, `room_instance`, and `room_instance_exit` rows keyed by `(tenantId, gameInstanceId)` and uses `lifecycle_epoch` as the current fence token for prepare/activate/fail/terminate transitions. - `world_event` is now runtime-owned and keyed by `(tenantId, gameInstanceId)` via `region_instance`, rather than hanging off template `region` rows. - `stopSession` now consumes `GetWorldInstanceLifecycle` + `TerminateWorldInstance` rather than the old ping-only shutdown path; Entity Management cleanup runs through `CleanupRuntimeInstance`, and World hard-deletes its own runtime rows (`world_event`, room exits, rooms, zones, regions) before reporting `TERMINATED`. 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 9d8b672ba2..56ec622bb7 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 @@ -6,9 +6,13 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The current construction batch moves the authored initial actor-core source value to Common, adds strict canonical decoding and returns immutable exact bindings from both fresh and stored descriptor success. This is source integrity and an in-memory producer result: the existing descriptor transport still does not carry it, and Entity has no post-publication durable core consumer or allocation proof. Entity's immutable pre-publication EMPTY-source receipt must not be rewritten as post-publication core evidence. The genuine fixture additionally defines native World initial-hold and Account admission-protection acquisition, pending denial, Game Session durable abort and Account exact settlement retry; it has not executed physically and does not establish successful admission. The approved distinct [Account activation-purpose protection](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) and [World terminal boundary](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-activation-protection) remain to be implemented and proved. Preparation COMMITTED and ACTIVE-only admission semantics remain unchanged, and activation stays denied. +The activation/projection construction passes the corrected complete Common Platform, Account, Game Session, Game Design, World and Entity checks in 45 seconds across 287 tasks, with 25 executed and 262 up-to-date. Available corrected-state XML records 5,563 executed unit cases and 44 executed non-container integration/cross-service cases, with zero failures or errors; unchanged tasks reuse successful corrected-state results from the immediately preceding checks. There are 915 skips: 17 Game Session unit cases and 898 container-dependent integration/cross-service cases, including the genuine native composition and new migrations. Strict XML readback separately proves all three Game Session retention-ordering cases and all five Entity authored-core consumer cases executed without skips. Integration compilation, generated SQL metadata, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass; Flyway sanity passes 12 sets/312 versioned files, public gRPC method and proto-time contracts pass, and architecture contracts passed 228 checks before the final status-only wording. This is local code, unit and static proof, not physical migration, successful authenticated native activation/settlement, actual actor allocation/placement/delivery, or runtime readiness. -Corrected complete Common Platform/Account/Game Session/Game Design checks pass in 4 minutes 45 seconds across 243 tasks, with 57 executed and 186 up-to-date. Available corrected-state XML records 4,593 executed unit cases and 40 executed non-container integration/cross-service cases, with zero failures or errors; the final run reuses the immediately preceding passing Common and Account test results. There are 666 skips: 17 Game Session unit cases and 649 container-dependent integration/cross-service cases, including the native genuine-release/admission/settlement composition. Integration compilation, generated SQL metadata, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass; architecture contracts separately pass 228 checks, and Flyway sanity passes 12 sets/307 versioned files. This is local compilation, unit and static proof, not physical PostgreSQL migration, complete original authority, successful OPEN admission, World hold release or runtime activation proof. +The current unregistered construction adds the distinct [Account activation-purpose protection](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), its immutable source vector and authenticated acquisition, protected World operation storage and [exact terminal readback](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-activation-protection), and append-only Account terminal settlement. Their complete authenticated producer/consumer composition and physical PostgreSQL proof remain open; synthetic storage rows and mocked holder checks do not establish those gates. Request-only fresh activation is denied, while exact retained legacy outcomes remain historical evidence. Preparation COMMITTED and ACTIVE-only admission semantics remain unchanged, and runtime activation stays denied. + +Game Design now constructs durable, ordered minimal authored-core projections beside the actual immutable descriptor owner, retaining the full private source proof locally. Its separate unregistered read reuses Account-confirmed original-operation qualification and the same owner snapshot to return the exact public request, association, descriptor, release and projections; it does not repair historical rows or expose the private publication/capture bytes through the descriptor. Unregistered Game Session V45 retention binds the unchanged qualified result to the actual launch, full original tuple and exact finite pending attempt, rechecking that attempt under the owner lock after the remote read. Exact retained retries return the first bytes without another source read or lease renewal. Its service-ordering tests use mocked clients and a synthetic launch, and its standalone PostgreSQL definitions use synthetic source bytes; neither establishes authenticated producer composition. The genuine fixture additionally defines retention using its actual Game Session store, original owner readback and native Game Design client, but that composition has not executed physically. The genuine native Game Design read definition currently returns the selected source's actual EMPTY projection, not a fabricated nonempty actor core. Entity's unregistered independent post-publication consumer corroborates its direct authenticated read against the local retained source and immutable release participant digest; its five focused mocked-client unit cases execute successfully, while its added genuine fixture composition is unexecuted. Real allocation, placement and operational-region delivery remain open. Entity's immutable pre-publication EMPTY-source receipt cannot become post-publication core evidence. The genuine fixture defines native protected activation and exact Account terminal settlement, but remains unexecuted physically and does not establish successful admission or World hold release. + +At the preceding published checkpoint `07d639bb304f82a6f16005ec69362b07bc257f07`, complete Common Platform/Account/Game Session/Game Design checks passed in 4 minutes 45 seconds across 243 tasks, with 57 executed and 186 up-to-date. Available corrected-state XML recorded 4,593 executed unit cases and 40 executed non-container integration/cross-service cases, with zero failures or errors; the final run reused the immediately preceding passing Common and Account test results. There were 666 skips: 17 Game Session unit cases and 649 container-dependent integration/cross-service cases, including the native genuine-release/admission/settlement composition. Integration compilation, generated SQL metadata, formatting, Checkstyle, SpotBugs, coverage, links and Markdown passed; architecture contracts separately passed 228 checks, and Flyway sanity passed 12 sets/307 versioned files. This proves the earlier local compilation, unit and static boundary, not the new activation/projection construction, physical PostgreSQL migration, complete original authority, successful OPEN admission, World hold release or runtime activation. The source-local composition replaces the stipulated Game Session launch association with its actual owner STARTING transaction, exact original-tuple/catalog retention and native World-to-Game-Session readback. World carries the actual captured realm/catalog revision into its preparation and association rather than inventing a revision. The corrected Common Platform/Game Session/World/Game Design complete gate passes in 2 minutes 37 seconds across 241 tasks, with 32 executed and 209 up-to-date. Available corrected XML records 3,880 executed unit cases and 29 executed non-container integration/cross-service cases, with zero failures or errors; unchanged tasks reuse earlier successful corrected-state results. There are 603 skips: 17 Game Session unit cases and 586 container-dependent integration/cross-service cases, including all three new launch PostgreSQL cases and the genuine native composition. Both schema-generation checks, integration compilation, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass. Architecture contracts separately pass 228 checks, and Flyway sanity passes 12 sets/306 versioned files. These are local compilation, unit and static results, not physical migration or native owner execution. Account issuer/redeemer fixture contexts and the continuously held commit-authority verifier remain explicit stipulations. All four complete handoffs, lifecycle readiness, actor placement and gameplay admission remain open. diff --git a/protos/account/v1/start_session_activation_protection_acquisition.proto b/protos/account/v1/start_session_activation_protection_acquisition.proto new file mode 100644 index 0000000000..48631cd4e8 --- /dev/null +++ b/protos/account/v1/start_session_activation_protection_acquisition.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered World-to-Account source-protection acquisition for the original +// StartSession activation. It does not activate World or settle/release Account protection. +service AccountStartSessionActivationProtectionAcquisitionService { + rpc AcquireOriginalStartSessionActivationProtection( + AcquireOriginalStartSessionActivationProtectionRequest) + returns (AcquireOriginalStartSessionActivationProtectionResponse); +} + +// Each repeated field must occur exactly once. Repetition is intentional: protobuf singular +// fields discard duplicate occurrences during parsing, while these closed transport fields must +// reject duplicates at the receiver. +message AcquireOriginalStartSessionActivationProtectionRequest { + repeated int32 schema_version = 1; + repeated string target_namespace = 2; + repeated bytes original_post_authorization_tuple = 3; + repeated string game_session_owner_mutation_id = 4; + repeated string game_session_owner_attempt_id = 5; + // Canonical positive unsigned-decimal text; parsed only if it fits a positive signed Java long. + repeated string game_session_owner_fence = 6; + repeated string activation_request_id = 7; + // Exact complete canonical World PREPARING evidence. The 64 MiB limit belongs only to this + // new Account activation carrier and does not widen the World lifecycle API's limits. + repeated bytes world_preparing_evidence = 8; +} + +message AcquireOriginalStartSessionActivationProtectionResponse { + // Exactly one complete canonical AccountStartSessionActivationProtectionEvidence value. + // Its existing 200 MiB limit is preserved; this RPC adds only protobuf framing headroom. + repeated bytes evidence_canonical_bytes = 1; +} diff --git a/protos/account/v1/start_session_activation_protection_settlement.proto b/protos/account/v1/start_session_activation_protection_settlement.proto new file mode 100644 index 0000000000..ceca9052d9 --- /dev/null +++ b/protos/account/v1/start_session_activation_protection_settlement.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered World-to-Account historical activation settlement. The request is +// lookup-only: it supplies no terminal result, currentness claim, or release instruction. +service AccountStartSessionActivationProtectionSettlementService { + rpc SettleOriginalStartSessionActivationProtection( + SettleOriginalStartSessionActivationProtectionRequest) + returns (SettleOriginalStartSessionActivationProtectionResponse); +} + +// Each repeated field must occur exactly once. Repetition is intentional so duplicate scalar +// occurrences survive generated parsing and can be rejected by the closed receiver. +message SettleOriginalStartSessionActivationProtectionRequest { + repeated int32 schema_version = 1; + repeated string target_namespace = 2; + repeated string settlement_request_id = 3; + repeated string account_protection_id = 4; + // Canonical positive unsigned-decimal text bounded by a positive signed Java long. + repeated string account_protection_fence = 5; +} + +message SettleOriginalStartSessionActivationProtectionResponse { + repeated int32 schema_version = 1; + repeated string settlement_request_id = 2; + repeated string account_protection_id = 3; + repeated string account_protection_fence = 4; + // Exact canonical UTC instant with six fractional digits from the immutable Account row. + repeated string settled_at = 5; + // Complete immutable World terminal receipt, never a digest-only substitute. + repeated bytes terminal_evidence_canonical_bytes = 6; +} diff --git a/protos/game-design/v1/authored_initial_actor_core_read.proto b/protos/game-design/v1/authored_initial_actor_core_read.proto new file mode 100644 index 0000000000..961d4ed1fc --- /dev/null +++ b/protos/game-design/v1/authored_initial_actor_core_read.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; + +package game_design.v1; + +import "game-design/v1/start_session_template_association_service.proto"; +import "game-design/v1/game_design_service.proto"; + +option java_package = "net.firedevops.firemud.gamedesign.v1"; +option java_multiple_files = true; + +// Standalone, unregistered read of the minimal authored initial actor core. The +// server authenticates Game Session or Entity before decoding and independently +// rechecks the original Account operation. This read is evidence, not admission. +service GameDesignAuthoredInitialActorCoreReadService { + rpc ReadAuthoredInitialActorCore(ReadAuthoredInitialActorCoreRequest) + returns (ReadAuthoredInitialActorCoreResponse); +} + +message ReadAuthoredInitialActorCoreRequest { + // Exact Game Session-pinned association request in ExactReplay mode. + ReadStartSessionTemplateAssociationRequest association_request = 1; +} + +message ReadAuthoredInitialActorCoreProjection { + // Closed RFC 8785 public projection; private proof bytes are never transported. + bytes canonical_projection_bytes = 1; + string projection_digest = 2; +} + +message ReadAuthoredInitialActorCoreResponse { + int32 schema_version = 1; + ReadStartSessionTemplateAssociationRequest request = 2; + ReadStartSessionTemplateAssociationResponse association_read = 3; + gamedesign.v1.LaunchDescriptor launch_descriptor = 4; + repeated ReadAuthoredInitialActorCoreProjection projections = 5; + // Canonical closed result envelope and its digest bind the exact echo and + // ordered public projection list; they do not authenticate the producer. + bytes canonical_result_bytes = 6; + string result_digest = 7; +} diff --git a/protos/game-session/v1/original_start_session_launch_read_service.proto b/protos/game-session/v1/original_start_session_launch_read_service.proto new file mode 100644 index 0000000000..c94a29aee3 --- /dev/null +++ b/protos/game-session/v1/original_start_session_launch_read_service.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package game_session.v1; + +option java_multiple_files = true; +option java_package = "net.firedevops.firemud.gamesession.v1"; +option java_outer_classname = "OriginalStartSessionLaunchReadServiceProto"; + +import "game-session/v1/game_session_service.proto"; + +// Account-only original StartSession readback. This API is deliberately distinct from the +// World-only canonical launch association reader and does not grant lifecycle or admission +// authority. +service OriginalStartSessionLaunchReadService { + rpc ReadOriginalStartSessionLaunch(ReadOriginalStartSessionLaunchRequest) + returns (ReadOriginalStartSessionLaunchResponse); +} + +message ReadOriginalStartSessionLaunchRequest { + uint32 schema_version = 1; + GetCanonicalGameInstanceLaunchAssociationRequest selector = 2; + bytes original_post_authorization_tuple_bytes = 3; +} + +message ReadOriginalStartSessionLaunchResponse { + uint32 schema_version = 1; + ReadOriginalStartSessionLaunchRequest request = 2; + GetCanonicalGameInstanceLaunchAssociationResponse launch = 3; + bytes retained_original_post_authorization_tuple_bytes = 4; +} diff --git a/protos/world-management/v1/original_start_session_activation_terminal_read.proto b/protos/world-management/v1/original_start_session_activation_terminal_read.proto new file mode 100644 index 0000000000..b05e6c2a88 --- /dev/null +++ b/protos/world-management/v1/original_start_session_activation_terminal_read.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Standalone authenticated World-owner read of one exact original activation terminal receipt. +service WorldOriginalStartSessionActivationTerminalReadService { + rpc ReadOriginalStartSessionActivationTerminalEvidence( + ReadOriginalStartSessionActivationTerminalEvidenceRequest) + returns (ReadOriginalStartSessionActivationTerminalEvidenceResponse); +} + +// Repeated fields preserve duplicate-field evidence for receiver-side fail-closed validation. +message ReadOriginalStartSessionActivationTerminalEvidenceRequest { + repeated int32 schema_version = 1; + repeated string target_namespace = 2; + repeated string read_request_id = 3; + repeated bytes account_protection_evidence = 4; +} + +message ReadOriginalStartSessionActivationTerminalEvidenceResponse { + repeated string read_request_id = 1; + // Complete immutable World receipt; the existing 768 MiB evidence cap is not widened. + repeated bytes terminal_evidence = 2; +} diff --git a/protos/world-management/v1/original_start_session_protected_activation.proto b/protos/world-management/v1/original_start_session_protected_activation.proto new file mode 100644 index 0000000000..526fda9828 --- /dev/null +++ b/protos/world-management/v1/original_start_session_protected_activation.proto @@ -0,0 +1,28 @@ +syntax = "proto3"; + +package worldmanagement.v1; + +import "account/v1/start_session_activation_protection_acquisition.proto"; + +option java_multiple_files = true; +option java_package = "net.firedevops.firemud.worldmanagement.v1"; + +// Standalone same-namespace Game Session entrypoint. Intentionally not runtime-registered. +service WorldOriginalStartSessionProtectedActivationService { + rpc ActivateOriginalStartSessionProtected( + ActivateOriginalStartSessionProtectedRequest) + returns (ActivateOriginalStartSessionProtectedResponse); +} + +// The nested Account request is reused without narrowing its original execution bindings. +message ActivateOriginalStartSessionProtectedRequest { + repeated int32 schema_version = 1; + repeated string target_namespace = 2; + repeated account.v1.AcquireOriginalStartSessionActivationProtectionRequest + acquisition_input = 3; +} + +message ActivateOriginalStartSessionProtectedResponse { + repeated int32 schema_version = 1; + repeated bytes terminal_evidence = 2; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java new file mode 100644 index 0000000000..195428b105 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java @@ -0,0 +1,874 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Comparator; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionAuthorityCapture; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionRequest; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable Account storage for distinct original StartSession World-activation source protection. + * + *

The caller must already be inside the existing authenticated Account currentness callback. + * This repository accepts no producer authority: SQL rechecks the retained Account redemption, + * committed V129 preparation, V131 attempt observation, source capture, target and finite lease + * after canonical source locks. The retained Common request then verifies the exact Game Session + * STARTING and World PREPARING evidence. Terminal settlement is separately append-only and never + * mutates this original protection row. + */ +@Repository +public class AccountStartSessionActivationProtectionRepository { + private static final String PROTECTIONS = "account_start_session_activation_protections"; + private static final String SOURCES = "account_start_session_activation_protection_sources"; + private static final String CAPTURES = "account_start_session_authority_captures"; + private static final String SETTLEMENTS = + "account_start_session_activation_protection_settlements"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Set PROTECTION_COLUMNS = + Set.of( + "activation_protection_id", + "activation_protection_fence", + "control_plane_request_id", + "account_world_participation_id", + "account_world_participation_fence", + "original_post_authorization_tuple", + "account_redemption_projection", + "game_session_owner_mutation_id", + "game_session_owner_attempt_id", + "game_session_owner_fence", + "original_lease_expires_at", + "target_namespace", + "canonical_tenant_id", + "canonical_game_instance_id", + "world_activation_request_id", + "game_session_launch_read_evidence", + "world_preparing_evidence", + "capture_source_version", + "capture_source_fence", + "capture_sha256", + "capture_reference_bytes", + "capture_reference_sha256", + "operation_identity_bytes", + "operation_identity_digest", + "request_binding_bytes", + "request_binding_digest", + "producer_xid", + "acquired_at"); + private static final Set SOURCE_COLUMNS = + Set.of("activation_protection_id", "source_key", "source_evidence"); + private static final Set CAPTURE_COLUMNS = + Set.of( + "control_plane_request_id", + "source_version", + "source_fence", + "snapshot_sha256", + "canonical_sha256", + "canonical_capture_bytes", + "canonical_snapshot_bytes"); + private static final Set SETTLEMENT_COLUMNS = + Set.of( + "activation_protection_id", + "activation_protection_fence", + "world_activation_request_id", + "world_activation_fence", + "outcome", + "account_protection_evidence_bytes", + "terminal_bytes", + "terminal_digest", + "settled_at"); + private static final Set SNAPSHOT_FIELDS = + Set.of( + "schema", + "controlPlaneRequestId", + "preAuthorizationTuple", + "mutationDigest", + "accountId", + "tenantId", + "targetOwner", + "loggingWorkloadUri", + "reservationOwnerId", + "reservationClaimFence", + "controlUiOperationId", + "controlUiTokenJti", + "controlUiTokenHash", + "controlUiSignerReceipt", + "controlUiSignerReceiptSha256", + "sourceVectorEvidence", + "sourceVector", + "outboxCheckpoints", + "authorityTuple", + "membershipVersion", + "accountIdentitySource", + "issuanceFence", + "issuanceFenceSourceVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Preserve the injected DSLContext precondition; this transactional repository is " + + "proxyable and owns no resources.") + public AccountStartSessionActivationProtectionRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Creates the first exact activation protection or returns its immutable winner. + * + *

Only the stable operation identity is used for retry equality. If either owner read uses a + * new correlation UUID, this returns the first full request and receipt unchanged rather than + * replacing its historical IDs. Database identity, fence and acquisition time are generated by + * PostgreSQL. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AccountStartSessionActivationProtectionEvidence createOrReadExact( + AccountStartSessionActivationProtectionRequest request, + AccountStartSessionAuthorityCapture capture) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(request, "exact activation protection request is required"); + Objects.requireNonNull(capture, "exact current Account capture is required"); + + assertCurrent(request); + CaptureValue currentCapture = captureFromRow(selectCapture(request, false)); + requireCaptureMatches(capture, currentCapture, request); + List expectedSources = sourceVector(currentCapture.snapshotBytes(), request); + + Record existing = selectByRequestId(request.originalTuple().controlPlaneRequestId()); + if (existing != null) { + return decodeAndRequireSameOperation(existing, request, currentCapture, expectedSources); + } + + int inserted = insert(request, currentCapture); + Record winner = selectByRequestId(request.originalTuple().controlPlaneRequestId()); + if (winner == null) throw unavailable(); + UUID protectionId = requiredUuid(winner, "activation_protection_id"); + if (inserted == 1) insertSources(protectionId, expectedSources); + AccountStartSessionActivationProtectionEvidence evidence = + decodeAndRequireSameOperation(winner, request, currentCapture, expectedSources); + if (inserted == 1 && !protectionId.equals(evidence.accountProtectionId())) throw unavailable(); + return evidence; + } + + /** + * Lookup-only current read for an independent Account readback transaction. It never inserts, + * renews or substitutes the retained first request, and refuses an expired original lease. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findExact( + AccountStartSessionActivationProtectionRequest request) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(request, "exact activation protection request is required"); + assertCurrent(request); + Record row = selectByRequestId(request.originalTuple().controlPlaneRequestId()); + if (row == null) return Optional.empty(); + CaptureValue capture = captureFromRow(selectCapture(request, false)); + List expectedSources = sourceVector(capture.snapshotBytes(), request); + return Optional.of(decodeAndRequireSameOperation(row, request, capture, expectedSources)); + } + + /** + * Lookup-only historical read used solely to resolve an already acquired activation protection. + * It validates the full immutable request, capture and source vector without checking + * currentness, original lease expiry, or changing the source hold. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findHistoricalExact( + UUID protectionId, long protectionFence) { + requireWritableReadCommittedTransaction(); + if (protectionId == null || NIL_UUID.equals(protectionId) || protectionFence <= 0L) { + throw unavailable(); + } + Record row = selectById(protectionId, false); + if (row == null) return Optional.empty(); + if (!protectionId.equals(requiredUuid(row, "activation_protection_id")) + || protectionFence != positive(requiredLong(row, "activation_protection_fence"))) { + throw unavailable(); + } + AccountStartSessionActivationProtectionRequest request; + try { + request = + AccountStartSessionActivationProtectionRequest.decode( + requiredBytes(row, "request_binding_bytes")); + } catch (RuntimeException malformed) { + throw unavailable(); + } + Record captureRow = selectCapture(request, false); + if (captureRow == null) throw unavailable(); + CaptureValue capture = captureFromRow(captureRow); + if (!request.originalTuple().controlPlaneRequestId().equals(capture.controlPlaneRequestId())) { + throw unavailable(); + } + List expectedSources = sourceVector(capture.snapshotBytes(), request); + return Optional.of(decodeAndRequireSameOperation(row, request, capture, expectedSources)); + } + + /** + * Appends the exact authenticated World terminal receipt after source-key locks, then returns the + * immutable database winner. Historical settlement deliberately ignores lease expiry. + */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSettlement settleExact( + WorldOriginalStartSessionActivationTerminalEvidence terminal) { + requireWritableReadCommittedTransaction(); + Objects.requireNonNull(terminal, "World activation terminal evidence is required"); + AccountStartSessionActivationProtectionEvidence expected = terminal.accountProtectionEvidence(); + UUID protectionId = expected.accountProtectionId(); + long protectionFence = expected.accountProtectionFence(); + + lockOriginalSourceRows(expected); + Record locked = selectById(protectionId, true); + if (locked == null + || !protectionId.equals(requiredUuid(locked, "activation_protection_id")) + || protectionFence != positive(requiredLong(locked, "activation_protection_fence"))) { + throw unavailable(); + } + AccountStartSessionActivationProtectionEvidence retained = + findHistoricalExact(protectionId, protectionFence) + .orElseThrow(AccountStartSessionActivationProtectionRepository::unavailable); + requireSameEvidence(expected, retained); + + dsl.execute( + "INSERT INTO " + + SETTLEMENTS + + " (activation_protection_id, activation_protection_fence, " + + "world_activation_request_id, world_activation_fence, outcome, " + + "account_protection_evidence_bytes, terminal_bytes, terminal_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (activation_protection_id) DO NOTHING", + protectionId, + protectionFence, + terminal.activationRequestId(), + terminal.worldActivationFence(), + terminal.outcome().name(), + expected.canonicalBytes(), + terminal.canonicalBytes(), + terminal.terminalDigest()); + StoredSettlement stored = + readSettlementExact(protectionId, protectionFence, retained) + .orElseThrow(AccountStartSessionActivationProtectionRepository::unavailable); + if (!Arrays.equals(terminal.canonicalBytes(), stored.terminal().canonicalBytes()) + || !terminal.terminalDigest().equals(stored.terminal().terminalDigest()) + || terminal.outcome() != stored.outcome()) { + throw conflict(); + } + return stored; + } + + /** Historical exact settlement lookup; no currentness or lease-expiry check is performed. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findSettlementExact(UUID protectionId, long protectionFence) { + requireWritableReadCommittedTransaction(); + Optional evidence = + findHistoricalExact(protectionId, protectionFence); + if (evidence.isEmpty()) return Optional.empty(); + return readSettlementExact(protectionId, protectionFence, evidence.orElseThrow()); + } + + void assertCurrent(AccountStartSessionActivationProtectionRequest request) { + if (!"STARTING" + .equals( + request.gameSessionLaunchReadEvidence().launch().currentGameInstanceStatus().name()) + || !"PREPARING".equals(request.worldActivationRequest().preparing().lifecycleStatus())) { + throw unavailable(); + } + byte[] operationBytes = request.operationIdentityBytes(); + String digest = digestPrefixed(operationBytes); + if (!request.requestDigest().equals(digest)) throw conflict(); + dsl.execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + request.canonicalBytes(), + operationBytes, + digest); + } + + private int insert(AccountStartSessionActivationProtectionRequest request, CaptureValue capture) { + var tuple = request.originalTuple(); + var scope = tuple.preAuthorizationTuple().action().scope(); + var worldRequest = request.worldActivationRequest(); + return dsl.execute( + "INSERT INTO " + + PROTECTIONS + + " (control_plane_request_id, account_world_participation_id, " + + "account_world_participation_fence, original_post_authorization_tuple, " + + "account_redemption_projection, game_session_owner_mutation_id, " + + "game_session_owner_attempt_id, game_session_owner_fence, original_lease_expires_at, " + + "target_namespace, canonical_tenant_id, canonical_game_instance_id, " + + "world_activation_request_id, game_session_launch_read_evidence, " + + "world_preparing_evidence, " + + "capture_source_version, capture_source_fence, capture_sha256, " + + "capture_reference_bytes, capture_reference_sha256, operation_identity_bytes, " + + "operation_identity_digest, request_binding_bytes, request_binding_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?, ?, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (control_plane_request_id) DO NOTHING", + tuple.controlPlaneRequestId(), + request.accountWorldParticipationId(), + request.accountWorldParticipationFence(), + request.originalPostAuthorizationTupleBytes(), + request.accountRedemptionProjectionBytes(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + OffsetDateTime.ofInstant(request.originalLeaseExpiresAt(), ZoneOffset.UTC), + scope.targetNamespace(), + scope.tenantId(), + worldRequest.canonicalGameInstanceId(), + worldRequest.activationRequestId(), + request.gameSessionLaunchReadEvidence().canonicalBytes(), + worldRequest.preparingEvidenceBytes(), + capture.sourceVersion(), + capture.sourceFence(), + capture.canonicalSha256(), + capture.canonicalBytes(), + capture.canonicalSha256(), + request.operationIdentityBytes(), + digestPrefixed(request.operationIdentityBytes()), + request.canonicalBytes(), + digestPrefixed(request.canonicalBytes())); + } + + private void insertSources(UUID protectionId, List sources) { + for (SourceEvidence source : sources) { + dsl.execute( + "INSERT INTO " + + SOURCES + + " (activation_protection_id, source_key, source_evidence) VALUES (?, ?, ?)", + protectionId, + source.key(), + source.canonicalBytes()); + } + } + + private AccountStartSessionActivationProtectionEvidence decodeAndRequireSameOperation( + Record row, + AccountStartSessionActivationProtectionRequest expectedRequest, + CaptureValue expectedCapture, + List expectedSources) { + try { + requireColumns(row, PROTECTION_COLUMNS, "activation protection"); + UUID protectionId = requiredUuid(row, "activation_protection_id"); + long protectionFence = positive(requiredLong(row, "activation_protection_fence")); + String requestId = requiredString(row, "control_plane_request_id"); + byte[] tupleBytes = requiredBytes(row, "original_post_authorization_tuple"); + byte[] projectionBytes = requiredBytes(row, "account_redemption_projection"); + UUID ownerMutation = requiredUuid(row, "game_session_owner_mutation_id"); + UUID ownerAttempt = requiredUuid(row, "game_session_owner_attempt_id"); + long ownerFence = positive(requiredLong(row, "game_session_owner_fence")); + Instant leaseExpiry = requiredTimestamp(row, "original_lease_expires_at").toInstant(); + UUID participationId = requiredUuid(row, "account_world_participation_id"); + long participationFence = positive(requiredLong(row, "account_world_participation_fence")); + String namespace = requiredString(row, "target_namespace"); + UUID tenant = requiredUuid(row, "canonical_tenant_id"); + UUID gameInstance = requiredUuid(row, "canonical_game_instance_id"); + UUID activationRequestId = requiredUuid(row, "world_activation_request_id"); + byte[] launchBytes = requiredBytes(row, "game_session_launch_read_evidence"); + byte[] preparingBytes = requiredBytes(row, "world_preparing_evidence"); + long captureVersion = positive(requiredLong(row, "capture_source_version")); + long captureFence = positive(requiredLong(row, "capture_source_fence")); + String captureDigest = requiredString(row, "capture_sha256"); + byte[] captureReference = requiredBytes(row, "capture_reference_bytes"); + String captureReferenceDigest = requiredString(row, "capture_reference_sha256"); + byte[] operationBytes = requiredBytes(row, "operation_identity_bytes"); + String operationDigest = requiredString(row, "operation_identity_digest"); + byte[] requestBytes = requiredBytes(row, "request_binding_bytes"); + String requestDigest = requiredString(row, "request_binding_digest"); + positive(requiredLong(row, "producer_xid")); + Instant acquiredAt = requiredTimestamp(row, "acquired_at").toInstant(); + + AccountStartSessionActivationProtectionRequest retainedRequest; + try { + retainedRequest = AccountStartSessionActivationProtectionRequest.decode(requestBytes); + } catch (RuntimeException malformed) { + throw unavailable(); + } + requireSameOperationIdentity(expectedRequest.operationIdentityBytes(), operationBytes); + requireSameOperationIdentity( + expectedRequest.operationIdentityBytes(), retainedRequest.operationIdentityBytes()); + var tuple = retainedRequest.originalTuple(); + var worldRequest = retainedRequest.worldActivationRequest(); + if (!tuple.controlPlaneRequestId().equals(requestId) + || !Arrays.equals(tupleBytes, retainedRequest.originalPostAuthorizationTupleBytes()) + || !Arrays.equals(projectionBytes, retainedRequest.accountRedemptionProjectionBytes()) + || !ownerMutation.equals(retainedRequest.gameSessionOwnerMutationId()) + || !ownerAttempt.equals(retainedRequest.gameSessionOwnerAttemptId()) + || ownerFence != retainedRequest.gameSessionOwnerFence() + || !leaseExpiry.equals(retainedRequest.originalLeaseExpiresAt()) + || !participationId.equals(retainedRequest.accountWorldParticipationId()) + || participationFence != retainedRequest.accountWorldParticipationFence() + || !namespace.equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !tenant.equals(tuple.preAuthorizationTuple().action().scope().tenantId()) + || !gameInstance.equals(worldRequest.canonicalGameInstanceId()) + || !activationRequestId.equals(worldRequest.activationRequestId()) + || !Arrays.equals( + launchBytes, retainedRequest.gameSessionLaunchReadEvidence().canonicalBytes()) + || !Arrays.equals(preparingBytes, worldRequest.preparingEvidenceBytes()) + || captureVersion != expectedCapture.sourceVersion() + || captureFence != expectedCapture.sourceFence() + || !captureDigest.equals(expectedCapture.canonicalSha256()) + || !Arrays.equals(captureReference, expectedCapture.canonicalBytes()) + || !captureReferenceDigest.equals(expectedCapture.canonicalSha256()) + || !Arrays.equals(requestBytes, retainedRequest.canonicalBytes()) + || !requestDigest.equals(digestPrefixed(requestBytes)) + || !operationDigest.equals(digestPrefixed(operationBytes))) { + throw conflict(); + } + + List storedSources = readSources(protectionId); + requireExactSources(expectedSources, storedSources); + return AccountStartSessionActivationProtectionEvidence.create( + retainedRequest, + protectionId, + protectionFence, + acquiredAt, + captureReference, + captureReferenceDigest, + storedSources); + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && ("Original StartSession activation protection is unavailable" + .equals(state.getMessage()) + || "Original StartSession activation protection conflicts with its immutable binding" + .equals(state.getMessage()))) { + throw state; + } + throw unavailable(); + } + } + + private List readSources(UUID protectionId) { + var rows = + dsl.fetch("SELECT * FROM " + SOURCES + " WHERE activation_protection_id = ?", protectionId); + List sources = new ArrayList<>(rows.size()); + for (Record row : rows) { + requireColumns(row, SOURCE_COLUMNS, "activation protection source"); + if (!protectionId.equals(requiredUuid(row, "activation_protection_id"))) throw unavailable(); + String key = requiredString(row, "source_key"); + byte[] bytes = requiredBytes(row, "source_evidence"); + SourceEvidence source; + try { + source = SourceEvidence.fromStored(bytes); + } catch (RuntimeException malformed) { + throw unavailable(); + } + if (!key.equals(source.key()) || bytes.length == 0 || bytes.length > 131_072) { + throw unavailable(); + } + sources.add(source); + } + sources.sort(Comparator.comparing(SourceEvidence::key)); + if (sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { + throw unavailable(); + } + return List.copyOf(sources); + } + + private Record selectByRequestId(String requestId) { + return dsl.fetchOne( + "SELECT * FROM " + PROTECTIONS + " WHERE control_plane_request_id = ?", requestId); + } + + private Record selectById(UUID protectionId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + PROTECTIONS + + " WHERE activation_protection_id = ?" + + (forUpdate ? " FOR UPDATE NOWAIT" : ""), + protectionId); + } + + private void lockOriginalSourceRows(AccountStartSessionActivationProtectionEvidence evidence) { + List ordered = + evidence.sourceEvidenceVector().stream() + .sorted(Comparator.comparing(SourceEvidence::key)) + .toList(); + for (SourceEvidence source : ordered) { + Record lock = + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks " + + "WHERE source_key = ? FOR UPDATE NOWAIT", + source.key()); + if (lock == null || !source.key().equals(requiredString(lock, "source_key"))) { + throw unavailable(); + } + } + } + + private Optional readSettlementExact( + UUID protectionId, + long protectionFence, + AccountStartSessionActivationProtectionEvidence expectedEvidence) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + SETTLEMENTS + " WHERE activation_protection_id = ?", protectionId); + if (row == null) return Optional.empty(); + try { + requireColumns(row, SETTLEMENT_COLUMNS, "activation protection settlement"); + if (!protectionId.equals(requiredUuid(row, "activation_protection_id")) + || protectionFence != positive(requiredLong(row, "activation_protection_fence"))) { + throw unavailable(); + } + UUID activationRequestId = requiredUuid(row, "world_activation_request_id"); + long worldFence = positive(requiredLong(row, "world_activation_fence")); + String outcome = requiredString(row, "outcome"); + byte[] evidenceBytes = requiredBytes(row, "account_protection_evidence_bytes"); + byte[] terminalBytes = requiredBytes(row, "terminal_bytes"); + String digest = requiredString(row, "terminal_digest"); + Instant settledAt = requiredTimestamp(row, "settled_at").toInstant(); + if (!digest.equals(digestPrefixed(terminalBytes)) + || !MessageDigest.isEqual(expectedEvidence.canonicalBytes(), evidenceBytes)) { + throw conflict(); + } + WorldOriginalStartSessionActivationTerminalEvidence terminal = + WorldOriginalStartSessionActivationTerminalEvidence.decode(terminalBytes); + if (!Arrays.equals(terminalBytes, terminal.canonicalBytes()) + || !digest.equals(terminal.terminalDigest()) + || !activationRequestId.equals(terminal.activationRequestId()) + || worldFence != terminal.worldActivationFence() + || !outcome.equals(terminal.outcome().name()) + || !MessageDigest.isEqual( + evidenceBytes, terminal.accountProtectionEvidence().canonicalBytes())) { + throw conflict(); + } + requireSameEvidence(expectedEvidence, terminal.accountProtectionEvidence()); + return Optional.of(new StoredSettlement(terminal, settledAt)); + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && ("Original StartSession activation protection is unavailable" + .equals(state.getMessage()) + || "Original StartSession activation protection conflicts with its immutable binding" + .equals(state.getMessage()))) { + throw state; + } + throw unavailable(); + } + } + + private static void requireSameEvidence( + AccountStartSessionActivationProtectionEvidence expected, + AccountStartSessionActivationProtectionEvidence actual) { + if (!MessageDigest.isEqual(expected.canonicalBytes(), actual.canonicalBytes())) + throw conflict(); + } + + private Record selectCapture( + AccountStartSessionActivationProtectionRequest request, boolean forUpdate) { + return dsl.fetchOne( + "SELECT control_plane_request_id, source_version, source_fence, snapshot_sha256, " + + "canonical_sha256, " + + "canonical_capture_bytes, canonical_snapshot_bytes FROM " + + CAPTURES + + " WHERE control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE NOWAIT" : ""), + request.originalTuple().controlPlaneRequestId()); + } + + private CaptureValue captureFromRow(Record row) { + requireColumns(row, CAPTURE_COLUMNS, "Account source capture"); + try { + String requestId = requiredString(row, "control_plane_request_id"); + long version = positive(requiredLong(row, "source_version")); + long fence = positive(requiredLong(row, "source_fence")); + String snapshotDigest = requiredString(row, "snapshot_sha256"); + String captureDigest = requiredString(row, "canonical_sha256"); + byte[] reference = requiredBytes(row, "canonical_capture_bytes"); + byte[] snapshot = requiredBytes(row, "canonical_snapshot_bytes"); + return new CaptureValue( + requestId, version, fence, snapshotDigest, captureDigest, reference, snapshot); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static void requireCaptureMatches( + AccountStartSessionAuthorityCapture expected, + CaptureValue actual, + AccountStartSessionActivationProtectionRequest request) { + requireSameCaptureBinding( + request.originalTuple().controlPlaneRequestId(), + expected.sourceVersion(), + expected.sourceFence(), + expected.canonicalSha256(), + actual.controlPlaneRequestId(), + actual.sourceVersion(), + actual.sourceFence(), + actual.canonicalSha256()); + if (!expected.snapshotSha256().equals(actual.snapshotSha256()) + || !Arrays.equals(expected.snapshotBytes(), actual.snapshotBytes()) + || !Arrays.equals(expected.canonicalBytes(), actual.canonicalBytes())) { + throw conflict(); + } + } + + private static List sourceVector( + byte[] snapshotBytes, AccountStartSessionActivationProtectionRequest request) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(snapshotBytes)) + .toString(); + if (!Arrays.equals(snapshotBytes, Rfc8785CanonicalJson.canonicalizeUtf8(json))) + throw unavailable(); + Object decoded = JSON.readValue(json, Object.class); + if (!(decoded instanceof Map snapshot) + || !SNAPSHOT_FIELDS.equals(snapshot.keySet()) + || !"account-start-session-authority-snapshot/v1".equals(snapshot.get("schema")) + || !request + .originalTuple() + .controlPlaneRequestId() + .equals(snapshot.get("controlPlaneRequestId")) + || !(snapshot.get("sourceVector") instanceof List encoded) + || encoded.isEmpty()) { + throw unavailable(); + } + List sources = new ArrayList<>(encoded.size()); + Set keys = new HashSet<>(); + String previousKey = null; + for (Object item : encoded) { + if (!(item instanceof String base64)) throw unavailable(); + byte[] bytes = Base64.getDecoder().decode(base64); + if (!Base64.getEncoder().encodeToString(bytes).equals(base64)) throw unavailable(); + SourceEvidence source = SourceEvidence.fromStored(bytes); + if (bytes.length == 0 + || bytes.length > 131_072 + || !keys.add(source.key()) + || (previousKey != null && previousKey.compareTo(source.key()) >= 0)) { + throw unavailable(); + } + previousKey = source.key(); + sources.add(source); + } + return List.copyOf(sources); + } catch (IOException | RuntimeException malformed) { + if (malformed instanceof IllegalStateException state + && "Original StartSession activation protection is unavailable" + .equals(state.getMessage())) { + throw state; + } + throw new IllegalStateException( + "Original StartSession activation protection is unavailable", malformed); + } + } + + static void requireExactSources(List expected, List actual) { + if (actual.size() != expected.size()) throw conflict(); + for (int index = 0; index < expected.size(); index++) { + SourceEvidence left = expected.get(index); + SourceEvidence right = actual.get(index); + if (!left.key().equals(right.key()) + || !Arrays.equals(left.canonicalBytes(), right.canonicalBytes())) throw conflict(); + } + } + + static void requireSameOperationIdentity(byte[] expected, byte[] actual) { + if (expected == null + || expected.length == 0 + || actual == null + || !MessageDigest.isEqual(expected, actual)) { + throw conflict(); + } + } + + static void requireSameCaptureBinding( + String expectedRequestId, + long expectedVersion, + long expectedFence, + String expectedDigest, + String actualRequestId, + long actualVersion, + long actualFence, + String actualDigest) { + if (expectedRequestId == null + || !expectedRequestId.equals(actualRequestId) + || expectedVersion <= 0L + || expectedVersion != actualVersion + || expectedFence <= 0L + || expectedFence != actualFence + || expectedDigest == null + || !expectedDigest.equals(actualDigest)) { + throw conflict(); + } + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + }); + } + + private static void requireColumns(Record row, Set expected, String label) { + Set actual = new HashSet<>(); + Arrays.stream(row.fields()).forEach(field -> actual.add(field.getName())); + if (!actual.equals(expected)) { + throw new IllegalStateException(label + " has an unknown or missing database column"); + } + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || NIL_UUID.equals(value)) throw unavailable(); + return value; + } + + private static String requiredString(Record row, String field) { + String value = row.get(field, String.class); + if (value == null) throw unavailable(); + return value; + } + + private static byte[] requiredBytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null) throw unavailable(); + return value; + } + + private static Long requiredLong(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null) throw unavailable(); + return value; + } + + private static OffsetDateTime requiredTimestamp(Record row, String field) { + OffsetDateTime value = row.get(field, OffsetDateTime.class); + if (value == null) throw unavailable(); + return value; + } + + private static long positive(long value) { + if (value <= 0L) throw unavailable(); + return value; + } + + private static String digestPrefixed(byte[] bytes) { + return "sha256:" + digestHex(bytes); + } + + private static String digestHex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Original StartSession activation protection is unavailable"); + } + + private static IllegalStateException conflict() { + return new IllegalStateException( + "Original StartSession activation protection conflicts with its immutable binding"); + } + + /** Immutable result of one authenticated World terminal resolution. */ + public record StoredSettlement( + WorldOriginalStartSessionActivationTerminalEvidence terminal, Instant settledAt) { + public StoredSettlement { + Objects.requireNonNull(terminal, "terminal evidence is required"); + Objects.requireNonNull(settledAt, "settledAt is required"); + } + + public UUID protectionId() { + return terminal.accountProtectionEvidence().accountProtectionId(); + } + + public long protectionFence() { + return terminal.accountProtectionEvidence().accountProtectionFence(); + } + + public WorldCanonicalInstanceActivation.Outcome outcome() { + return terminal.outcome(); + } + } + + private record CaptureValue( + String controlPlaneRequestId, + long sourceVersion, + long sourceFence, + String snapshotSha256, + String canonicalSha256, + byte[] canonicalBytes, + byte[] snapshotBytes) { + private CaptureValue { + if (controlPlaneRequestId == null + || sourceVersion <= 0L + || sourceFence <= 0L + || snapshotSha256 == null + || canonicalSha256 == null + || canonicalBytes == null + || canonicalBytes.length == 0 + || snapshotBytes == null + || snapshotBytes.length == 0 + || !snapshotSha256.equals(digestHex(snapshotBytes)) + || !canonicalSha256.equals(digestHex(canonicalBytes))) { + throw unavailable(); + } + canonicalBytes = canonicalBytes.clone(); + snapshotBytes = snapshotBytes.clone(); + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public byte[] snapshotBytes() { + return snapshotBytes.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcService.java new file mode 100644 index 0000000000..6e601089c7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcService.java @@ -0,0 +1,101 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountStartSessionActivationProtectionAcquisitionServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionActivationProtectionRequest; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionActivationProtectionResponse; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone unregistered receiver: authenticate exact World before request decoding or SQL. */ +public final class AccountStartSessionActivationProtectionAcquisitionGrpcService + extends AccountStartSessionActivationProtectionAcquisitionServiceGrpc + .AccountStartSessionActivationProtectionAcquisitionServiceImplBase { + private final AccountStartSessionActivationProtectionAcquisitionService owner; + private final String namespace; + + public AccountStartSessionActivationProtectionAcquisitionGrpcService( + AccountStartSessionActivationProtectionAcquisitionService owner, String namespace) { + this.owner = + Objects.requireNonNull(owner, "activation protection acquisition owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void acquireOriginalStartSessionActivationProtection( + AcquireOriginalStartSessionActivationProtectionRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer is required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !expectedPeer.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() + > AccountStartSessionActivationProtectionAcquisitionGrpcCodec.MAX_REQUEST_WIRE_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + final AccountStartSessionActivationProtectionAcquisitionInput input; + try { + input = + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( + request, namespace); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var evidence = + owner.acquire( + new AccountStartSessionActivationProtectionAcquisitionService.AcquisitionRequest( + input.originalPostAuthorizationTuple(), + input.gameSessionOwnerMutationId(), + input.gameSessionOwnerAttemptId(), + input.gameSessionOwnerFence(), + input.worldActivationRequest())); + var response = + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toResponse( + input, namespace, evidence); + observer.onNext(response); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.INVALID_ARGUMENT + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + observer.onError(Status.fromCode(code).asRuntimeException()); + } catch (IllegalArgumentException invalidEvidence) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionService.java new file mode 100644 index 0000000000..b4f6ddd0b4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionService.java @@ -0,0 +1,472 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Account composition that acquires the distinct source protection for one exact + * original StartSession World activation. + * + *

Each call authenticates the same-namespace World workload, obtains fresh Game Session + * current-attempt and original STARTING-launch readbacks outside Account SQL, and then revalidates + * the original Account authority and locked source capture through its existing issuer callback. + * V129 participation, its COMMITTED preparation terminal, and the retained V131 owner observation + * supply the historical binding; caller-provided lease, projection, or participation coordinates + * are never trusted. This composition performs acquisition and immutable readback only: it does not + * settle, release, renew, or re-arm protection, nor register a transport endpoint. + */ +public final class AccountStartSessionActivationProtectionAcquisitionService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AccountStartSessionOperatorAuthorizationService issuer; + private final AccountStartSessionWorldParticipationRepository participationRepository; + private final AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptRepository; + private final AccountStartSessionActivationProtectionRepository protectionRepository; + private final OriginalStartSessionCurrentAttemptClient currentAttemptClient; + private final OriginalStartSessionLaunchReadClient launchReadClient; + private final TransactionTemplate readbackTransaction; + private final String workloadNamespace; + + public AccountStartSessionActivationProtectionAcquisitionService( + AccountStartSessionOperatorAuthorizationService issuer, + AccountStartSessionWorldParticipationRepository participationRepository, + AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptRepository, + AccountStartSessionActivationProtectionRepository protectionRepository, + OriginalStartSessionCurrentAttemptClient currentAttemptClient, + OriginalStartSessionLaunchReadClient launchReadClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.issuer = + Objects.requireNonNull(issuer, "original Account StartSession issuer is required"); + this.participationRepository = + Objects.requireNonNull( + participationRepository, "World participation repository is required"); + this.attemptRepository = + Objects.requireNonNull( + attemptRepository, "original-attempt evidence repository is required"); + this.protectionRepository = + Objects.requireNonNull( + protectionRepository, "activation protection repository is required"); + this.currentAttemptClient = + Objects.requireNonNull( + currentAttemptClient, "Game Session current-attempt client is required"); + this.launchReadClient = + Objects.requireNonNull(launchReadClient, "Game Session launch-read client is required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + readbackTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + readbackTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readbackTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readbackTransaction.setReadOnly(false); + } + + /** + * Acquires or recovers the first immutable protection receipt, then independently reads it back. + * A retry may use new owner read correlation IDs but cannot change the stable activation + * operation, original source capture, owner attempt, or finite lease. + */ + public AccountStartSessionActivationProtectionEvidence acquire(AcquisitionRequest request) { + requireWorldPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(request, "activation protection acquisition request is required"); + + byte[] tupleBytes = request.originalPostAuthorizationTuple(); + StartSessionPostAuthorizationExecutionTuple tuple = decodeOriginalTuple(tupleBytes); + WorldCanonicalInstanceActivation.Request activation = request.worldActivationRequest(); + if (activation == null) throw denied("Exact World PREPARING activation statement is required"); + requireOriginalBinding(tuple, request, activation); + requireNonnil(request.gameSessionOwnerMutationId(), "Game Session owner mutation ID"); + requireNonnil(request.gameSessionOwnerAttemptId(), "Game Session owner attempt ID"); + requirePositive(request.gameSessionOwnerFence(), "Game Session owner fence"); + + Request currentAttemptRequest = + new Request( + freshReadId(tuple, activation, request), + workloadNamespace, + tupleBytes, + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerFence()); + + // Both owner observations are independent and happen before opening Account SQL. They are + // evidence inputs, not authority; the currentness callback below remains the local authority. + requireNoAmbientTransaction(); + Result currentAttempt = currentAttemptClient.read(currentAttemptRequest); + requireNoAmbientTransaction(); + Result exactCurrentAttempt = exactCurrentAttempt(currentAttemptRequest, currentAttempt, tuple); + + UUID launchReadId = + freshReadId(tuple, activation, request, currentAttemptRequest.readRequestId()); + OriginalStartSessionLaunchReadEvidence.Request launchRequest = + new OriginalStartSessionLaunchReadEvidence.Request( + launchSelector(activation.preparing(), launchReadId), tupleBytes); + requireNoAmbientTransaction(); + OriginalStartSessionLaunchReadEvidence.Result observedLaunch = + launchReadClient.read(launchRequest); + requireNoAmbientTransaction(); + OriginalStartSessionLaunchReadEvidence.Result exactLaunch = + exactLaunch(launchRequest, observedLaunch); + + AccountStartSessionActivationProtectionEvidence committed = + issuer.withCurrentWorldReceivingParticipationCurrentness( + tupleBytes, + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + capture -> { + StoredParticipation participation = + participationRepository + .findHistoricalForOriginalTuple(tupleBytes) + .orElseThrow( + () -> + denied("Exact original COMMITTED World preparation is unavailable")); + requireParticipationBinding(tuple, request, activation, participation); + + var settlement = + participationRepository + .findSettlementExact( + participation.participationId(), participation.participationFence()) + .orElseThrow( + () -> denied("Original World preparation terminal is unavailable")); + if (settlement.outcome() != WorldStartSessionExecutionTerminal.Outcome.COMMITTED) { + throw denied("Original World preparation is not COMMITTED"); + } + + StoredEvidence retained = + attemptRepository + .findHistoricalExact(participation, currentAttemptRequest) + .orElseThrow( + () -> + denied( + "Exact original Game Session current-attempt evidence is unavailable")); + requireUnchangedAttempt( + participation, currentAttemptRequest, tuple, exactCurrentAttempt, retained); + + AccountStartSessionActivationProtectionRequest exactRequest = + AccountStartSessionActivationProtectionRequest.create( + tupleBytes, + exactCurrentAttempt.accountRedemptionProjection(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + exactCurrentAttempt.originalLeaseExpiresAt(), + participation.participationId(), + participation.participationFence(), + exactLaunch, + activation); + return protectionRepository.createOrReadExact(exactRequest, capture); + }); + + requireNoAmbientTransaction(); + AccountStartSessionActivationProtectionEvidence readback = + Objects.requireNonNull( + readbackTransaction.execute( + ignored -> + protectionRepository + .findExact(committed.request()) + .orElseThrow( + () -> + denied( + "Committed exact Account activation protection is not readable"))), + "Account activation protection readback transaction returned no result"); + if (!MessageDigest.isEqual(committed.canonicalBytes(), readback.canonicalBytes())) { + throw denied("Committed Account activation protection readback differs"); + } + return readback; + } + + private Result exactCurrentAttempt( + Request expected, Result observed, StartSessionPostAuthorizationExecutionTuple tuple) { + if (observed == null) { + throw denied("Exact current original Game Session attempt evidence is unavailable"); + } + try { + Result exact = + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + expected, OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observed)); + if (!OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals(exact.phaseState()) + || !sameRequest(expected, exact.request(), true) + || !MessageDigest.isEqual( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + exact.accountRedemptionProjection())) { + throw denied("Current Game Session attempt or Account redemption projection differs"); + } + return exact; + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact current original Game Session attempt evidence is malformed") + .withCause(malformed) + .asRuntimeException(); + } + } + + private static OriginalStartSessionLaunchReadEvidence.Result exactLaunch( + OriginalStartSessionLaunchReadEvidence.Request expected, + OriginalStartSessionLaunchReadEvidence.Result observed) { + if (observed == null) { + throw denied("Exact original Game Session STARTING launch read is unavailable"); + } + try { + OriginalStartSessionLaunchReadEvidence.Result exact = + OriginalStartSessionLaunchReadGrpcCodec.fromResponse( + expected, OriginalStartSessionLaunchReadGrpcCodec.toResponse(observed)); + if (exact.launch().currentGameInstanceStatus() + != CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING) { + throw denied("Original Game Session launch is not STARTING"); + } + return exact; + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact original Game Session launch read is malformed") + .withCause(malformed) + .asRuntimeException(); + } + } + + private static void requireUnchangedAttempt( + StoredParticipation participation, + Request expectedRequest, + StartSessionPostAuthorizationExecutionTuple tuple, + Result observed, + StoredEvidence retained) { + if (retained == null + || !participation.participationId().equals(retained.participationId()) + || !expectedRequest.expectedOwnerMutationId().equals(retained.gameSessionOwnerMutationId()) + || !sameRequest(expectedRequest, retained.result().request(), false) + || !sameResult(observed, retained.result()) + || !OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals( + retained.result().phaseState()) + || !retained.originalLeaseExpiresAt().equals(observed.originalLeaseExpiresAt()) + || !MessageDigest.isEqual( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + retained.result().accountRedemptionProjection())) { + throw denied("Current Game Session attempt or finite original lease differs from V131"); + } + } + + private static void requireParticipationBinding( + StartSessionPostAuthorizationExecutionTuple tuple, + AcquisitionRequest request, + WorldCanonicalInstanceActivation.Request activation, + StoredParticipation participation) { + if (!tuple.controlPlaneRequestId().equals(participation.controlPlaneRequestId()) + || !Arrays.equals(tuple.canonicalBytes(), participation.originalPostAuthorizationTuple()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(participation.targetNamespace()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .equals(participation.canonicalTenantId()) + || !activation.canonicalGameInstanceId().equals(participation.canonicalGameInstanceId()) + || !request.gameSessionOwnerAttemptId().equals(participation.gameSessionOwnerAttemptId()) + || request.gameSessionOwnerFence() != participation.gameSessionOwnerFence()) { + throw denied( + "Historical World participation differs from the original tuple and owner attempt"); + } + } + + private void requireOriginalBinding( + StartSessionPostAuthorizationExecutionTuple tuple, + AcquisitionRequest request, + WorldCanonicalInstanceActivation.Request activation) { + var pre = tuple.preAuthorizationTuple(); + var scope = pre.action().scope(); + var preparing = activation.preparing(); + var world = preparing.request(); + if (!"StartSession".equals(pre.actionFamily()) + || !"game-session-service".equals(pre.targetOwner()) + || !workloadNamespace.equals(scope.targetNamespace()) + || !scope.targetNamespace().equals(world.targetNamespace()) + || !scope.tenantId().equals(world.canonicalTenantId()) + || !tuple.controlPlaneRequestId().equals(world.controlPlaneRequestId()) + || !"PREPARING".equals(preparing.lifecycleStatus()) + || !activation.canonicalGameInstanceId().equals(world.canonicalGameInstanceId()) + || !tuple + .controlPlaneRequestId() + .equals(activation.preparing().launchBinding().descriptor().controlPlaneRequestId())) { + throw denied("Exact original StartSession tuple and World PREPARING identity required"); + } + requireNonnil(request.gameSessionOwnerMutationId(), "Game Session owner mutation ID"); + requireNonnil(request.gameSessionOwnerAttemptId(), "Game Session owner attempt ID"); + requirePositive(request.gameSessionOwnerFence(), "Game Session owner fence"); + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request launchSelector( + WorldCanonicalInstanceLifecycleEvidence preparing, UUID readRequestId) { + var request = preparing.request(); + var descriptor = preparing.launchBinding().descriptor(); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + readRequestId, + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest()); + } + + private static StartSessionPostAuthorizationExecutionTuple decodeOriginalTuple( + byte[] tupleBytes) { + if (tupleBytes == null) throw denied("Complete original StartSession tuple is required"); + try { + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (!Arrays.equals(tupleBytes, tuple.canonicalBytes())) { + throw denied("Original StartSession tuple is not exact canonical bytes"); + } + return tuple; + } catch (IllegalArgumentException malformed) { + throw Status.FAILED_PRECONDITION + .withDescription("Complete canonical original StartSession tuple required") + .withCause(malformed) + .asRuntimeException(); + } + } + + private static UUID freshReadId( + StartSessionPostAuthorizationExecutionTuple tuple, + WorldCanonicalInstanceActivation.Request activation, + AcquisitionRequest request, + UUID... additionalOccupied) { + Set occupied = new HashSet<>(); + occupied.addAll( + List.of( + tuple.reservationOwnerId(), + tuple.preAuthorizationTuple().actor().accountId(), + tuple.preAuthorizationTuple().action().scope().tenantId(), + activation.activationRequestId(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerAttemptId())); + occupied.addAll(Arrays.asList(additionalOccupied)); + UUID result; + do { + result = UUID.randomUUID(); + } while (occupied.contains(result)); + return result; + } + + private void requireWorldPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified World workload identity required") + .asRuntimeException(); + } + String expectedUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !workloadNamespace.equals(peer.namespace()) + || !expectedUri.equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace World workload without end-user context required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Activation protection acquisition requires owner reads outside Account SQL") + .asRuntimeException(); + } + } + + private static boolean sameResult(Result left, Result right) { + return left.originalLeaseExpiresAt().equals(right.originalLeaseExpiresAt()) + && sameRequest(left.request(), right.request(), false) + && Arrays.equals(left.accountRedemptionProjection(), right.accountRedemptionProjection()); + } + + private static boolean sameRequest(Request left, Request right, boolean compareReadId) { + return (!compareReadId || left.readRequestId().equals(right.readRequestId())) + && left.targetNamespace().equals(right.targetNamespace()) + && Arrays.equals( + left.canonicalPostAuthorizationTuple(), right.canonicalPostAuthorizationTuple()) + && left.expectedOwnerAttemptId().equals(right.expectedOwnerAttemptId()) + && left.expectedOwnerMutationId().equals(right.expectedOwnerMutationId()) + && left.expectedOwnerFence() == right.expectedOwnerFence(); + } + + private static void requireNonnil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw denied(name + " must be a canonical non-nil UUID"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) throw denied(name + " must be positive"); + } + + private static StatusRuntimeException denied(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } + + /** + * Raw caller statement; owner lease, projection, participation and capture are never supplied. + */ + public record AcquisitionRequest( + byte[] originalPostAuthorizationTuple, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + WorldCanonicalInstanceActivation.Request worldActivationRequest) { + public AcquisitionRequest { + originalPostAuthorizationTuple = + originalPostAuthorizationTuple == null ? null : originalPostAuthorizationTuple.clone(); + } + + @Override + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple == null ? null : originalPostAuthorizationTuple.clone(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcService.java new file mode 100644 index 0000000000..c2de35d5a9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcService.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountStartSessionActivationProtectionSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionActivationProtectionRequest; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionActivationProtectionResponse; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionSettlementEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionSettlementGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionSettlementInput; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone unregistered settlement receiver: authenticate exact World before parsing. */ +public final class AccountStartSessionActivationProtectionSettlementGrpcService + extends AccountStartSessionActivationProtectionSettlementServiceGrpc + .AccountStartSessionActivationProtectionSettlementServiceImplBase { + private final AccountStartSessionActivationProtectionSettlementService owner; + private final String namespace; + + public AccountStartSessionActivationProtectionSettlementGrpcService( + AccountStartSessionActivationProtectionSettlementService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "activation settlement owner required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void settleOriginalStartSessionActivationProtection( + SettleOriginalStartSessionActivationProtectionRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer required"); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !expectedPeer.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() + > AccountStartSessionActivationProtectionSettlementGrpcCodec.MAX_REQUEST_WIRE_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + final AccountStartSessionActivationProtectionSettlementInput input; + try { + input = + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( + request, namespace); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var stored = owner.settle(input.accountProtectionId(), input.accountProtectionFence()); + var evidence = + new AccountStartSessionActivationProtectionSettlementEvidence( + input.settlementRequestId(), stored.terminal(), stored.settledAt()); + observer.onNext( + AccountStartSessionActivationProtectionSettlementGrpcCodec.toResponse(input, evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.INVALID_ARGUMENT + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + observer.onError(Status.fromCode(code).asRuntimeException()); + } catch (IllegalArgumentException invalidEvidence) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementService.java new file mode 100644 index 0000000000..52b932420f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementService.java @@ -0,0 +1,263 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository.StoredSettlement; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalReadClient; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalReadInput; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered, default-denied Account settlement composition for one original activation hold. + * + *

Only the exact same-namespace World workload may request recovery. Historical Account + * authority is read without currentness or lease checks; authenticated World terminal evidence is + * fetched outside Account SQL, then source locks precede immutable settlement storage. Absence, + * timeout, generic close, and original expiry never settle or release protection. + */ +public final class AccountStartSessionActivationProtectionSettlementService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final AccountStartSessionActivationProtectionRepository repository; + private final WorldOriginalStartSessionActivationTerminalReadClient worldClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + public AccountStartSessionActivationProtectionSettlementService( + AccountStartSessionActivationProtectionRepository repository, + WorldOriginalStartSessionActivationTerminalReadClient worldClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = + Objects.requireNonNull(repository, "activation protection repository required"); + this.worldClient = Objects.requireNonNull(worldClient, "World terminal client required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager required")); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** + * Settles or recovers one exact historical protection. Selectors convey no authority; all remote + * lookup identity is derived from the retained Account receipt. + */ + public StoredSettlement settle(UUID protectionId, long protectionFence) { + requireAuthenticatedWorldPeer(); + requireNoAuthenticatedEndUser(); + requireNoAmbientTransaction(); + if (protectionId == null || NIL_UUID.equals(protectionId) || protectionFence <= 0L) { + throw Status.INVALID_ARGUMENT + .withDescription("Non-nil Account protection ID and positive fence required") + .asRuntimeException(); + } + + Lookup lookup = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> { + AccountStartSessionActivationProtectionEvidence evidence = + repository + .findHistoricalExact(protectionId, protectionFence) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Exact historical activation protection is unavailable") + .asRuntimeException()); + requireExactProtection(evidence, protectionId, protectionFence); + if (!workloadNamespace.equals( + evidence + .request() + .originalTuple() + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Activation protection namespace differs from Account configuration") + .asRuntimeException(); + } + Optional prior = + repository.findSettlementExact(protectionId, protectionFence); + return new Lookup(evidence, prior.orElse(null)); + }), + "Account historical activation transaction returned no result"); + if (lookup.priorSettlement() != null) { + return requireReceipt( + lookup.priorSettlement(), lookup.evidence(), protectionId, protectionFence); + } + + WorldOriginalStartSessionActivationTerminalReadInput input = + new WorldOriginalStartSessionActivationTerminalReadInput( + UUID.randomUUID(), lookup.evidence()); + input.requireTargetNamespace(workloadNamespace); + requireNoAmbientTransaction(); + WorldOriginalStartSessionActivationTerminalEvidence terminal = worldClient.read(input); + requireNoAmbientTransaction(); + if (terminal == null) { + throw Status.FAILED_PRECONDITION + .withDescription( + "World has no exact original activation terminal; Account protection remains pending") + .asRuntimeException(); + } + if (!MessageDigest.isEqual( + lookup.evidence().canonicalBytes(), + terminal.accountProtectionEvidence().canonicalBytes())) { + throw Status.FAILED_PRECONDITION + .withDescription( + "World terminal evidence differs from the full first Account protection receipt") + .asRuntimeException(); + } + requireExactTerminal(terminal, lookup.evidence()); + + requireNoAmbientTransaction(); + StoredSettlement committed = + Objects.requireNonNull( + ownerTransaction.execute(ignored -> repository.settleExact(terminal)), + "Account terminal settlement transaction returned no receipt"); + requireReceipt(committed, lookup.evidence(), protectionId, protectionFence); + if (!Arrays.equals(terminal.canonicalBytes(), committed.terminal().canonicalBytes()) + || !terminal.terminalDigest().equals(committed.terminal().terminalDigest()) + || terminal.outcome() != committed.outcome()) { + throw Status.FAILED_PRECONDITION + .withDescription("Account stored a different World activation terminal value") + .asRuntimeException(); + } + + // The independent lookup distinguishes a confirmed durable receipt from an ambiguous commit + // or lost response. It cannot write, adopt, renew, or release the source protection. + requireNoAmbientTransaction(); + StoredSettlement readback = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository + .findSettlementExact(protectionId, protectionFence) + .orElseThrow( + () -> + Status.FAILED_PRECONDITION + .withDescription( + "Committed activation settlement is not readable") + .asRuntimeException())), + "Account activation settlement readback returned no receipt"); + requireReceipt(readback, lookup.evidence(), protectionId, protectionFence); + if (!sameSettlement(committed, readback)) { + throw Status.FAILED_PRECONDITION + .withDescription("Committed Account activation settlement readback differs") + .asRuntimeException(); + } + return readback; + } + + private void requireAuthenticatedWorldPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expected = "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Authenticated World workload identity is required") + .asRuntimeException(); + } + if (!expected.equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription( + "Only the exact same-namespace World workload may resolve activation protection") + .asRuntimeException(); + } + } + + private static void requireNoAuthenticatedEndUser() { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription("Internal activation settlement rejects end-user context") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Activation settlement requires independent owner transactions") + .asRuntimeException(); + } + } + + private static void requireExactProtection( + AccountStartSessionActivationProtectionEvidence evidence, + UUID protectionId, + long protectionFence) { + if (!protectionId.equals(evidence.accountProtectionId()) + || protectionFence != evidence.accountProtectionFence()) { + throw Status.FAILED_PRECONDITION + .withDescription("Historical activation protection differs from its lookup identity") + .asRuntimeException(); + } + } + + private static void requireExactTerminal( + WorldOriginalStartSessionActivationTerminalEvidence terminal, + AccountStartSessionActivationProtectionEvidence evidence) { + if (!evidence + .request() + .worldActivationRequest() + .activationRequestId() + .equals(terminal.activationRequestId()) + || terminal.worldActivationFence() <= 0L + || terminal.outcome() == null) { + throw Status.FAILED_PRECONDITION + .withDescription("World activation terminal receipt is not the exact protected operation") + .asRuntimeException(); + } + } + + private static StoredSettlement requireReceipt( + StoredSettlement receipt, + AccountStartSessionActivationProtectionEvidence evidence, + UUID protectionId, + long protectionFence) { + Objects.requireNonNull(receipt, "stored Account settlement receipt required"); + WorldOriginalStartSessionActivationTerminalEvidence terminal = + Objects.requireNonNull(receipt.terminal(), "stored World terminal required"); + if (!protectionId.equals(receipt.protectionId()) + || protectionFence != receipt.protectionFence() + || receipt.outcome() != terminal.outcome() + || !MessageDigest.isEqual( + evidence.canonicalBytes(), terminal.accountProtectionEvidence().canonicalBytes())) { + throw Status.FAILED_PRECONDITION + .withDescription("Stored settlement differs from exact historical activation protection") + .asRuntimeException(); + } + return receipt; + } + + private static boolean sameSettlement(StoredSettlement left, StoredSettlement right) { + return left.protectionId().equals(right.protectionId()) + && left.protectionFence() == right.protectionFence() + && left.outcome() == right.outcome() + && left.settledAt().equals(right.settledAt()) + && left.terminal().terminalDigest().equals(right.terminal().terminalDigest()) + && Arrays.equals(left.terminal().canonicalBytes(), right.terminal().canonicalBytes()); + } + + private record Lookup( + AccountStartSessionActivationProtectionEvidence evidence, StoredSettlement priorSettlement) {} +} diff --git a/services/account-service/src/main/resources/db/migration/V161__original_start_session_activation_protection.sql b/services/account-service/src/main/resources/db/migration/V161__original_start_session_activation_protection.sql new file mode 100644 index 0000000000..a1ef4bb545 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V161__original_start_session_activation_protection.sql @@ -0,0 +1,391 @@ +-- Distinct Account-owned source protection through the exact original World activation. +-- This is immutable storage only: it authenticates no owner and has no release or +-- settlement path. A future exact ACTIVE/ABORTED terminal contract must add that separately. +CREATE TABLE account_start_session_activation_protections ( + activation_protection_id UUID PRIMARY KEY DEFAULT gen_random_uuid() + CHECK (activation_protection_id <> '00000000-0000-0000-0000-000000000000'::UUID), + activation_protection_fence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE + CHECK (activation_protection_fence > 0), + control_plane_request_id VARCHAR(128) NOT NULL UNIQUE + REFERENCES account_start_session_authority_captures(control_plane_request_id) ON DELETE RESTRICT, + account_world_participation_id UUID NOT NULL UNIQUE + REFERENCES account_start_session_world_participations(participation_id) ON DELETE RESTRICT, + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + original_post_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + account_redemption_projection BYTEA NOT NULL + CHECK (octet_length(account_redemption_projection) BETWEEN 1 AND 135168), + game_session_owner_mutation_id UUID NOT NULL UNIQUE + CHECK (game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_attempt_id UUID NOT NULL + CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + original_lease_expires_at TIMESTAMPTZ NOT NULL CHECK (isfinite(original_lease_expires_at)), + target_namespace VARCHAR(63) NOT NULL + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + canonical_tenant_id UUID NOT NULL + REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id) ON DELETE RESTRICT, + canonical_game_instance_id UUID NOT NULL + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + world_activation_request_id UUID NOT NULL + CHECK (world_activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_launch_read_evidence BYTEA NOT NULL + CHECK (octet_length(game_session_launch_read_evidence) BETWEEN 1 AND 42991616), + world_preparing_evidence BYTEA NOT NULL + CHECK (octet_length(world_preparing_evidence) BETWEEN 1 AND 67108864), + capture_source_version BIGINT NOT NULL CHECK (capture_source_version > 0), + capture_source_fence BIGINT NOT NULL CHECK (capture_source_fence > 0), + capture_sha256 VARCHAR(64) NOT NULL CHECK (capture_sha256 ~ '^[0-9a-f]{64}$'), + capture_reference_bytes BYTEA NOT NULL + CHECK (octet_length(capture_reference_bytes) BETWEEN 1 AND 262144), + capture_reference_sha256 VARCHAR(64) NOT NULL + CHECK (capture_reference_sha256 ~ '^[0-9a-f]{64}$'), + operation_identity_bytes BYTEA NOT NULL + CHECK (octet_length(operation_identity_bytes) BETWEEN 1 AND 150994944), + operation_identity_digest VARCHAR(71) NOT NULL UNIQUE + CHECK (operation_identity_digest = 'sha256:' || encode(sha256(operation_identity_bytes), 'hex')), + request_binding_bytes BYTEA NOT NULL + CHECK (octet_length(request_binding_bytes) BETWEEN 1 AND 150994944), + request_binding_digest VARCHAR(71) NOT NULL + CHECK (request_binding_digest = 'sha256:' || encode(sha256(request_binding_bytes), 'hex')), + producer_xid BIGINT NOT NULL DEFAULT txid_current(), + acquired_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CHECK (isfinite(acquired_at) AND acquired_at < original_lease_expires_at), + CHECK (capture_sha256 = capture_reference_sha256) +); + +CREATE TABLE account_start_session_activation_protection_sources ( + activation_protection_id UUID NOT NULL + REFERENCES account_start_session_activation_protections(activation_protection_id) ON DELETE RESTRICT, + source_key VARCHAR(2048) NOT NULL + CHECK (length(source_key) > 0 AND octet_length(source_key) <= 2048) + REFERENCES account_draft_authorization_source_locks(source_key), + source_evidence BYTEA NOT NULL CHECK (octet_length(source_evidence) BETWEEN 1 AND 131072), + PRIMARY KEY (activation_protection_id, source_key) +); +CREATE INDEX account_ss_activation_sources_by_key + ON account_start_session_activation_protection_sources(source_key, activation_protection_id); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_activation_assert_current( + request_bytes BYTEA, + operation_bytes BYTEA, + operation_digest TEXT, + require_complete BOOLEAN +) RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +DECLARE + capture account_start_session_authority_captures%ROWTYPE; + world_parent account_start_session_world_participations%ROWTYPE; + observation account_start_session_world_original_attempt_evidence%ROWTYPE; + authorization_row account_start_session_operator_authorizations%ROWTYPE; + retained account_start_session_activation_protections%ROWTYPE; + snapshot_value JSONB; + request_value JSONB; + tuple_value JSONB; + projection_value JSONB; + preparing_value JSONB; + preparing_request JSONB; + source_value JSONB; + source_bytes BYTEA; + source_key_value TEXT; + tuple_bytes BYTEA; + projection_bytes BYTEA; + preparing_bytes BYTEA; + control_request_id TEXT; + requested_participation_id UUID; + keys TEXT[]; + retained_found BOOLEAN := FALSE; +BEGIN + IF octet_length(request_bytes) NOT BETWEEN 1 AND 150994944 + OR octet_length(operation_bytes) NOT BETWEEN 1 AND 150994944 + OR operation_digest IS DISTINCT FROM 'sha256:' || encode(sha256(operation_bytes), 'hex') THEN + RAISE EXCEPTION 'Original StartSession activation request or operation identity is invalid' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(request_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(request_value) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(request_value)) <> 12 + OR NOT (request_value ?& ARRAY[ + 'schema', 'originalPostAuthorizationTupleBytesBase64', + 'accountRedemptionProjectionBytesBase64', 'gameSessionOwnerMutationId', + 'gameSessionOwnerAttemptId', 'gameSessionOwnerFence', 'originalLeaseExpiresAt', + 'accountWorldParticipationId', 'accountWorldParticipationFence', + 'gameSessionLaunchReadEvidenceBytesBase64', 'worldActivationRequestId', + 'preparingEvidenceBytesBase64']) + OR EXISTS (SELECT 1 FROM jsonb_each(request_value) field WHERE jsonb_typeof(field.value) <> 'string') + OR request_value->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' THEN + RAISE EXCEPTION 'Original StartSession activation request has an unsupported shape' + USING ERRCODE = '23514'; + END IF; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + tuple_value := convert_from(tuple_bytes, 'UTF8')::JSONB; + control_request_id := tuple_value->>'controlPlaneRequestId'; + requested_participation_id := (request_value->>'accountWorldParticipationId')::UUID; + + -- Source-key locks are acquired in the canonical V129 order before any retained owner, + -- World or activation-protection row is locked. + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_request_id; + snapshot_value := convert_from(capture.canonical_snapshot_bytes, 'UTF8')::JSONB; + IF snapshot_value->>'schema' IS DISTINCT FROM 'account-start-session-authority-snapshot/v1' + OR snapshot_value->>'controlPlaneRequestId' IS DISTINCT FROM control_request_id THEN + RAISE EXCEPTION 'Activation protection requires the exact original Account source snapshot' + USING ERRCODE = '23514'; + END IF; + keys := account_start_session_world_participation_lock_sources(snapshot_value); + PERFORM account_start_session_world_participation_assert_exclusive(keys, snapshot_value); + + SELECT * INTO STRICT capture FROM account_start_session_authority_captures + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT world_parent FROM account_start_session_world_participations + WHERE account_start_session_world_participations.participation_id = requested_participation_id + FOR UPDATE NOWAIT; + SELECT * INTO STRICT observation FROM account_start_session_world_original_attempt_evidence + WHERE participation_id = world_parent.participation_id FOR UPDATE NOWAIT; + SELECT * INTO STRICT authorization_row FROM account_start_session_operator_authorizations + WHERE control_plane_request_id = control_request_id FOR UPDATE NOWAIT; + SELECT * INTO retained FROM account_start_session_activation_protections + WHERE account_start_session_activation_protections.control_plane_request_id = control_request_id + FOR UPDATE NOWAIT; + retained_found := FOUND; + + preparing_value := convert_from(preparing_bytes, 'UTF8')::JSONB; + preparing_request := preparing_value->'request'; + projection_value := convert_from(projection_bytes, 'UTF8')::JSONB; + IF request_value->>'gameSessionOwnerMutationId' IS DISTINCT FROM observation.game_session_owner_mutation_id::TEXT + OR request_value->>'gameSessionOwnerAttemptId' IS DISTINCT FROM observation.game_session_owner_attempt_id::TEXT + OR request_value->>'gameSessionOwnerFence' IS DISTINCT FROM observation.game_session_owner_fence::TEXT + OR request_value->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(observation.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR request_value->>'accountWorldParticipationId' IS DISTINCT FROM world_parent.participation_id::TEXT + OR request_value->>'accountWorldParticipationFence' IS DISTINCT FROM world_parent.participation_fence::TEXT + OR world_parent.control_plane_request_id IS DISTINCT FROM control_request_id + OR world_parent.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR world_parent.game_session_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR world_parent.game_session_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + OR observation.target_namespace IS DISTINCT FROM world_parent.target_namespace + OR NOT EXISTS ( + SELECT 1 FROM account_start_session_world_participation_settlements settlement + WHERE settlement.participation_id = world_parent.participation_id + AND settlement.outcome = 'COMMITTED') + OR preparing_value->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR preparing_value->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR preparing_request->>'controlPlaneRequestId' IS DISTINCT FROM control_request_id + OR preparing_request->>'targetNamespace' IS DISTINCT FROM world_parent.target_namespace + OR preparing_request->>'canonicalTenantId' IS DISTINCT FROM world_parent.canonical_tenant_id::TEXT + OR preparing_request->>'canonicalGameInstanceId' IS DISTINCT FROM world_parent.canonical_game_instance_id::TEXT + OR capture.source_version <= 0 OR capture.source_fence <= 0 THEN + RAISE EXCEPTION 'Activation protection differs from committed original World preparation or attempt' + USING ERRCODE = '23514'; + END IF; + + -- Retain the original Account issuance/redemption tuple and complete projection exactly. + IF capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') + OR capture.snapshot_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_snapshot_bytes), 'hex') + OR capture.pre_authorization_tuple IS DISTINCT FROM authorization_row.pre_authorization_tuple + OR capture.issuance_fence IS DISTINCT FROM authorization_row.issuance_fence + OR authorization_row.status IS DISTINCT FROM 'REDEEMED' + OR authorization_row.redemption_owner_attempt_id IS DISTINCT FROM observation.game_session_owner_attempt_id + OR authorization_row.redemption_owner_fence IS DISTINCT FROM observation.game_session_owner_fence + OR authorization_row.redemption_reference_fingerprint IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR authorization_row.redemption_authority_evidence_bundle IS DISTINCT FROM authorization_row.authority_evidence_bundle + OR tuple_value->'preAuthorizationReservationTuple' IS DISTINCT FROM convert_from(authorization_row.pre_authorization_tuple, 'UTF8')::JSONB + OR tuple_value->>'authorizationReferenceFingerprint' IS DISTINCT FROM authorization_row.authorization_reference_fingerprint + OR tuple_value->>'issuanceFence' IS DISTINCT FROM authorization_row.issuance_fence::TEXT + OR tuple_value->'authorityEvidenceBundle' IS DISTINCT FROM convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB + OR projection_value IS DISTINCT FROM jsonb_build_object( + 'projectionSchemaId', 'accountStartSessionRedemptionProjection', + 'projectionSchemaVersion', '1', + 'authorizationReferenceFingerprint', authorization_row.authorization_reference_fingerprint, + 'authorityEvidenceBundle', convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB, + 'issuanceOperationId', authorization_row.issuance_operation_id::TEXT, + 'issuanceFence', authorization_row.issuance_fence) + OR capture.canonical_sha256 IS DISTINCT FROM encode(sha256(capture.canonical_capture_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection differs from original Account redemption or capture' + USING ERRCODE = '23514'; + END IF; + + IF retained_found AND ( + retained.operation_identity_bytes IS DISTINCT FROM operation_bytes + OR retained.operation_identity_digest IS DISTINCT FROM operation_digest + OR retained.account_world_participation_id IS DISTINCT FROM world_parent.participation_id + OR retained.account_world_participation_fence IS DISTINCT FROM world_parent.participation_fence) THEN + RAISE EXCEPTION 'Original StartSession activation protection conflicts with its immutable binding' + USING ERRCODE = '23514'; + END IF; + + -- The typed Common carrier validates the closed Game Session STARTING result and exact + -- World PREPARING evidence. SQL independently checks finite original authority only after + -- all canonical source and owner/protection row locks have completed. + IF observation.original_lease_expires_at IS DISTINCT FROM + (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR observation.original_lease_expires_at <= clock_timestamp() + OR authorization_row.reference_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Original StartSession activation protection lease is stale or expired' + USING ERRCODE = '23514'; + END IF; + + PERFORM account_start_session_world_participation_assert_sources(world_parent.participation_id, snapshot_value); + IF require_complete THEN + IF (SELECT count(*) FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id) + <> jsonb_array_length(snapshot_value->'sourceVector') THEN + RAISE EXCEPTION 'Activation protection has incomplete or extra source children' + USING ERRCODE = '23514'; + END IF; + FOR source_value IN SELECT value FROM jsonb_array_elements(snapshot_value->'sourceVector') LOOP + source_bytes := decode(source_value #>> '{}', 'base64'); + source_key_value := account_start_session_world_participation_source_key(source_bytes); + IF NOT EXISTS (SELECT 1 FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = retained.activation_protection_id + AND source_key = source_key_value AND source_evidence = source_bytes) THEN + RAISE EXCEPTION 'Activation protection source child differs from original capture' + USING ERRCODE = '23514'; + END IF; + END LOOP; + END IF; +END; +$$; + +CREATE FUNCTION account_ss_activation_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + request_value JSONB; + tuple_bytes BYTEA; + projection_bytes BYTEA; + launch_bytes BYTEA; + preparing_bytes BYTEA; +BEGIN + IF NEW.producer_xid IS DISTINCT FROM txid_current() + OR NEW.capture_sha256 IS DISTINCT FROM encode(sha256(NEW.capture_reference_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection must retain its producer capture transaction and digest' + USING ERRCODE = '23514'; + END IF; + request_value := convert_from(NEW.request_binding_bytes, 'UTF8')::JSONB; + tuple_bytes := decode(request_value->>'originalPostAuthorizationTupleBytesBase64', 'base64'); + projection_bytes := decode(request_value->>'accountRedemptionProjectionBytesBase64', 'base64'); + launch_bytes := decode(request_value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'); + preparing_bytes := decode(request_value->>'preparingEvidenceBytesBase64', 'base64'); + IF NEW.control_plane_request_id IS DISTINCT FROM + (convert_from(tuple_bytes, 'UTF8')::JSONB->>'controlPlaneRequestId') + OR NEW.original_post_authorization_tuple IS DISTINCT FROM tuple_bytes + OR NEW.account_redemption_projection IS DISTINCT FROM projection_bytes + OR NEW.game_session_owner_mutation_id IS DISTINCT FROM (request_value->>'gameSessionOwnerMutationId')::UUID + OR NEW.game_session_owner_attempt_id IS DISTINCT FROM (request_value->>'gameSessionOwnerAttemptId')::UUID + OR NEW.game_session_owner_fence IS DISTINCT FROM (request_value->>'gameSessionOwnerFence')::BIGINT + OR NEW.original_lease_expires_at IS DISTINCT FROM (request_value->>'originalLeaseExpiresAt')::TIMESTAMPTZ + OR NEW.account_world_participation_id IS DISTINCT FROM (request_value->>'accountWorldParticipationId')::UUID + OR NEW.account_world_participation_fence IS DISTINCT FROM (request_value->>'accountWorldParticipationFence')::BIGINT + OR NEW.world_activation_request_id IS DISTINCT FROM (request_value->>'worldActivationRequestId')::UUID + OR NEW.game_session_launch_read_evidence IS DISTINCT FROM launch_bytes + OR NEW.world_preparing_evidence IS DISTINCT FROM preparing_bytes + OR NEW.request_binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.request_binding_bytes), 'hex') + OR NEW.operation_identity_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.operation_identity_bytes), 'hex') THEN + RAISE EXCEPTION 'Activation protection does not retain its exact canonical request fields' + USING ERRCODE = '23514'; + END IF; + PERFORM account_ss_activation_assert_current( + NEW.request_binding_bytes, NEW.operation_identity_bytes, NEW.operation_identity_digest, FALSE); + IF NOT EXISTS ( + SELECT 1 FROM account_start_session_authority_captures capture + WHERE capture.control_plane_request_id = NEW.control_plane_request_id + AND capture.source_version = NEW.capture_source_version + AND capture.source_fence = NEW.capture_source_fence + AND capture.canonical_sha256 = NEW.capture_sha256 + AND capture.canonical_capture_bytes = NEW.capture_reference_bytes + AND NEW.target_namespace = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'targetNamespace') + AND NEW.canonical_tenant_id = (convert_from(tuple_bytes, 'UTF8')::JSONB + ->'preAuthorizationReservationTuple'->'scope'->>'tenantId')::UUID + AND NEW.canonical_game_instance_id = (convert_from(preparing_bytes, 'UTF8')::JSONB + ->'request'->>'canonicalGameInstanceId')::UUID + AND NEW.capture_reference_sha256 = encode(sha256(NEW.capture_reference_bytes), 'hex')) THEN + RAISE EXCEPTION 'Activation protection capture or target differs from the exact current request' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_source_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE producer BIGINT; +BEGIN + SELECT producer_xid INTO STRICT producer FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + IF producer IS DISTINCT FROM txid_current() + OR account_start_session_world_participation_source_key(NEW.source_evidence) IS DISTINCT FROM NEW.source_key THEN + RAISE EXCEPTION 'Activation protection sources must be exact same-producer children' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE original account_start_session_activation_protections%ROWTYPE; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + PERFORM account_ss_activation_assert_current( + original.request_binding_bytes, original.operation_identity_bytes, + original.operation_identity_digest, TRUE); + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_ss_activation_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation protection is immutable and has no settlement path' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_activation_validate BEFORE INSERT ON account_start_session_activation_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_insert_guard(); +CREATE TRIGGER account_ss_activation_immutable BEFORE UPDATE OR DELETE ON account_start_session_activation_protections + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_no_truncate BEFORE TRUNCATE ON account_start_session_activation_protections + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_sources_validate BEFORE INSERT ON account_start_session_activation_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_source_insert_guard(); +CREATE TRIGGER account_ss_activation_sources_immutable BEFORE UPDATE OR DELETE ON account_start_session_activation_protection_sources + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE TRIGGER account_ss_activation_sources_no_truncate BEFORE TRUNCATE ON account_start_session_activation_protection_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_no_mutation(); +CREATE CONSTRAINT TRIGGER account_ss_activation_complete AFTER INSERT ON account_start_session_activation_protections + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION account_ss_activation_complete_guard(); + +-- Existing assembled source-writer guards call this helper after locking their canonical +-- source keys. Keep every V133 admission check and add the permanently pending activation rows. +CREATE OR REPLACE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; + PERFORM protection.activation_protection_id + FROM account_start_session_activation_protections protection + JOIN account_start_session_activation_protection_sources source + ON source.activation_protection_id = protection.activation_protection_id + WHERE source.source_key = ANY(source_keys) + ORDER BY protection.activation_protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession activation protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V162__original_start_session_activation_protection_settlement.sql b/services/account-service/src/main/resources/db/migration/V162__original_start_session_activation_protection_settlement.sql new file mode 100644 index 0000000000..fa4b061f51 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V162__original_start_session_activation_protection_settlement.sql @@ -0,0 +1,235 @@ +-- Append-only resolution of the distinct original StartSession activation source protection. +-- Only an exact authenticated World ACTIVE or fenced ABORTED terminal receipt may be recorded; +-- expiry, missing World state, timeout, generic close, and absence are not terminal outcomes. +CREATE TABLE account_start_session_activation_protection_settlements ( + activation_protection_id UUID PRIMARY KEY + REFERENCES account_start_session_activation_protections(activation_protection_id) ON DELETE RESTRICT, + activation_protection_fence BIGINT NOT NULL CHECK (activation_protection_fence > 0), + world_activation_request_id UUID NOT NULL + CHECK (world_activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + world_activation_fence BIGINT NOT NULL CHECK (world_activation_fence > 0), + outcome VARCHAR(16) NOT NULL CHECK (outcome IN ('COMMITTED', 'ABORTED')), + account_protection_evidence_bytes BYTEA NOT NULL + CHECK (octet_length(account_protection_evidence_bytes) BETWEEN 1 AND 209715264), + terminal_bytes BYTEA NOT NULL + CHECK (octet_length(terminal_bytes) BETWEEN 1 AND 805306368), + terminal_digest VARCHAR(71) NOT NULL + CHECK (terminal_digest = 'sha256:' || encode(sha256(terminal_bytes), 'hex')), + settled_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() + CHECK (isfinite(settled_at)) +); + +-- [jooq ignore start] +CREATE FUNCTION account_ss_activation_settlement_insert_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + original account_start_session_activation_protections%ROWTYPE; + terminal JSONB; + protection_evidence JSONB; + protection_request JSONB; + protection_request_bytes BYTEA; + result_value JSONB; + result_bytes BYTEA; + result_request_bytes BYTEA; + preparing_bytes BYTEA; + preparing_value JSONB; + preparing_request JSONB; + expected_preparing JSONB; + expected_activation_request JSONB; + expected_source_vector JSONB; + source_count BIGINT; + evidence_base64 TEXT; +BEGIN + SELECT * INTO STRICT original FROM account_start_session_activation_protections + WHERE activation_protection_id = NEW.activation_protection_id; + terminal := convert_from(NEW.terminal_bytes, 'UTF8')::JSONB; + evidence_base64 := replace(replace(encode(NEW.account_protection_evidence_bytes, 'base64'), E'\n', ''), E'\r', ''); + protection_evidence := convert_from(NEW.account_protection_evidence_bytes, 'UTF8')::JSONB; + protection_request_bytes := decode(protection_evidence->>'requestBytesBase64', 'base64'); + protection_request := convert_from(protection_request_bytes, 'UTF8')::JSONB; + preparing_bytes := decode(protection_request->>'preparingEvidenceBytesBase64', 'base64'); + preparing_value := convert_from(preparing_bytes, 'UTF8')::JSONB; + preparing_request := preparing_value->'request'; + expected_preparing := jsonb_set( + preparing_value, '{request}', preparing_request - 'readRequestId', FALSE); + expected_activation_request := jsonb_build_object( + 'schema', 'world-canonical-instance-activation-request/v1', + 'activationRequestId', original.world_activation_request_id::TEXT, + 'preparingEvidence', expected_preparing); + result_bytes := decode(terminal->>'activationResultBytesBase64', 'base64'); + result_value := convert_from(result_bytes, 'UTF8')::JSONB; + result_request_bytes := decode(result_value->>'requestBytesBase64', 'base64'); + SELECT count(*) INTO source_count + FROM account_start_session_activation_protection_sources + WHERE activation_protection_id = original.activation_protection_id; + SELECT COALESCE( + jsonb_agg( + to_jsonb(replace(replace(encode(source.source_evidence, 'base64'), E'\n', ''), E'\r', '')) + ORDER BY source.source_key), + '[]'::JSONB) + INTO expected_source_vector + FROM account_start_session_activation_protection_sources source + WHERE source.activation_protection_id = original.activation_protection_id; + IF NEW.activation_protection_fence IS DISTINCT FROM original.activation_protection_fence + OR NEW.world_activation_request_id IS DISTINCT FROM original.world_activation_request_id + OR NEW.terminal_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.terminal_bytes), 'hex') + OR jsonb_typeof(protection_evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(protection_evidence)) <> 8 + OR NOT (protection_evidence ?& ARRAY[ + 'schema', 'requestBytesBase64', 'accountProtectionId', 'accountProtectionFence', + 'acquiredAt', 'originalSourceCaptureReferenceBytesBase64', + 'originalSourceCaptureReferenceSha256', 'sourceEvidenceVector']) + OR protection_evidence->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-evidence/v1' + OR protection_evidence->>'accountProtectionId' IS DISTINCT FROM original.activation_protection_id::TEXT + OR protection_evidence->>'accountProtectionFence' IS DISTINCT FROM original.activation_protection_fence::TEXT + OR protection_evidence->>'acquiredAt' IS DISTINCT FROM + to_char(original.acquired_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR protection_evidence->>'requestBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.request_binding_bytes, 'base64'), E'\n', ''), E'\r', '') + OR protection_request_bytes IS DISTINCT FROM original.request_binding_bytes + OR jsonb_typeof(protection_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(protection_request)) <> 12 + OR NOT (protection_request ?& ARRAY[ + 'schema', 'originalPostAuthorizationTupleBytesBase64', + 'accountRedemptionProjectionBytesBase64', 'gameSessionOwnerMutationId', + 'gameSessionOwnerAttemptId', 'gameSessionOwnerFence', 'originalLeaseExpiresAt', + 'accountWorldParticipationId', 'accountWorldParticipationFence', + 'gameSessionLaunchReadEvidenceBytesBase64', 'worldActivationRequestId', + 'preparingEvidenceBytesBase64']) + OR protection_request->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' + OR decode(protection_request->>'originalPostAuthorizationTupleBytesBase64', 'base64') + IS DISTINCT FROM original.original_post_authorization_tuple + OR decode(protection_request->>'accountRedemptionProjectionBytesBase64', 'base64') + IS DISTINCT FROM original.account_redemption_projection + OR protection_request->>'gameSessionOwnerMutationId' + IS DISTINCT FROM original.game_session_owner_mutation_id::TEXT + OR protection_request->>'gameSessionOwnerAttemptId' + IS DISTINCT FROM original.game_session_owner_attempt_id::TEXT + OR protection_request->>'gameSessionOwnerFence' + IS DISTINCT FROM original.game_session_owner_fence::TEXT + OR protection_request->>'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(original.original_lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR protection_request->>'accountWorldParticipationId' + IS DISTINCT FROM original.account_world_participation_id::TEXT + OR protection_request->>'accountWorldParticipationFence' + IS DISTINCT FROM original.account_world_participation_fence::TEXT + OR decode(protection_request->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64') + IS DISTINCT FROM original.game_session_launch_read_evidence + OR protection_request->>'worldActivationRequestId' IS DISTINCT FROM original.world_activation_request_id::TEXT + OR protection_request->>'preparingEvidenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.world_preparing_evidence, 'base64'), E'\n', ''), E'\r', '') + OR protection_evidence->>'originalSourceCaptureReferenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.capture_reference_bytes, 'base64'), E'\n', ''), E'\r', '') + OR protection_evidence->>'originalSourceCaptureReferenceSha256' IS DISTINCT FROM + encode(sha256(original.capture_reference_bytes), 'hex') + OR original.capture_reference_sha256 IS DISTINCT FROM + encode(sha256(original.capture_reference_bytes), 'hex') + OR jsonb_typeof(protection_evidence->'sourceEvidenceVector') IS DISTINCT FROM 'array' + OR source_count <= 0 + OR jsonb_array_length(protection_evidence->'sourceEvidenceVector') IS DISTINCT FROM source_count + OR protection_evidence->'sourceEvidenceVector' IS DISTINCT FROM expected_source_vector + OR EXISTS ( + SELECT 1 FROM account_start_session_activation_protection_sources source + WHERE source.activation_protection_id = original.activation_protection_id + AND account_start_session_world_participation_source_key(source.source_evidence) + IS DISTINCT FROM source.source_key) + OR jsonb_typeof(terminal) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(terminal)) <> 8 + OR NOT (terminal ?& ARRAY[ + 'schema', 'activationRequestId', 'accountProtectionId', 'accountProtectionFence', + 'worldActivationFence', 'accountProtectionEvidenceBytesBase64', + 'activationResultBytesBase64', 'activationResultSha256']) + OR terminal->>'schema' IS DISTINCT FROM 'world-original-start-session-activation-terminal-evidence/v1' + OR terminal->>'activationRequestId' IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR terminal->>'accountProtectionId' IS DISTINCT FROM NEW.activation_protection_id::TEXT + OR terminal->>'accountProtectionFence' IS DISTINCT FROM NEW.activation_protection_fence::TEXT + OR terminal->>'worldActivationFence' IS DISTINCT FROM NEW.world_activation_fence::TEXT + OR terminal->>'accountProtectionEvidenceBytesBase64' IS DISTINCT FROM evidence_base64 + OR terminal->>'activationResultSha256' IS DISTINCT FROM encode(sha256(result_bytes), 'hex') + OR result_value IS NULL + OR jsonb_typeof(result_value) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(result_value)) <> 8 + OR NOT (result_value ?& ARRAY[ + 'schema', 'activationRequestId', 'requestDigest', 'requestBytesBase64', + 'preparingEvidenceBytesBase64', 'outcome', 'terminalCode', + 'lifecycleEvidenceBytesBase64']) + OR result_value->>'schema' IS DISTINCT FROM 'world-canonical-instance-activation-result/v1' + OR result_value->>'activationRequestId' IS DISTINCT FROM NEW.world_activation_request_id::TEXT + OR result_value->>'requestDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(result_request_bytes), 'hex') + OR convert_from(result_request_bytes, 'UTF8')::JSONB IS DISTINCT FROM expected_activation_request + OR result_value->>'requestBytesBase64' IS DISTINCT FROM + replace(replace(encode(result_request_bytes, 'base64'), E'\n', ''), E'\r', '') + OR result_value->>'preparingEvidenceBytesBase64' IS DISTINCT FROM + replace(replace(encode(original.world_preparing_evidence, 'base64'), E'\n', ''), E'\r', '') + OR result_value->>'outcome' IS DISTINCT FROM NEW.outcome + OR (NEW.outcome = 'COMMITTED' AND result_value->'terminalCode' IS DISTINCT FROM 'null'::JSONB) + OR (NEW.outcome = 'ABORTED' + AND (jsonb_typeof(result_value->'terminalCode') IS DISTINCT FROM 'string' + OR length(result_value->>'terminalCode') = 0)) THEN + RAISE EXCEPTION 'Activation settlement must retain the exact terminal receipt for its protection' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_ss_activation_settlement_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation settlement is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_ss_activation_settlement_validate + BEFORE INSERT ON account_start_session_activation_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_settlement_insert_guard(); +CREATE TRIGGER account_ss_activation_settlement_immutable + BEFORE UPDATE OR DELETE ON account_start_session_activation_protection_settlements + FOR EACH ROW EXECUTE FUNCTION account_ss_activation_settlement_no_mutation(); +CREATE TRIGGER account_ss_activation_settlement_no_truncate + BEFORE TRUNCATE ON account_start_session_activation_protection_settlements + FOR EACH STATEMENT EXECUTE FUNCTION account_ss_activation_settlement_no_mutation(); + +CREATE OR REPLACE FUNCTION account_ss_activation_no_mutation() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Original StartSession activation protection is immutable; terminal settlement is separate and append-only' + USING ERRCODE = '23514'; +END; +$$; + +-- Preserve the V133 admission-protection branch and settle activation source guards only when an +-- exact terminal receipt exists. Existing V129 source writers already call this shared function. +CREATE OR REPLACE FUNCTION account_ss_admission_assert_no_pending(source_keys TEXT[]) +RETURNS VOID LANGUAGE plpgsql VOLATILE STRICT AS $$ +BEGIN + PERFORM protection.protection_id + FROM account_start_session_admission_protections protection + JOIN account_start_session_admission_protection_sources source + ON source.protection_id = protection.protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT account_ss_admission_is_settled(protection.protection_id) + ORDER BY protection.protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession admission protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; + + PERFORM protection.activation_protection_id + FROM account_start_session_activation_protections protection + JOIN account_start_session_activation_protection_sources source + ON source.activation_protection_id = protection.activation_protection_id + WHERE source.source_key = ANY(source_keys) + AND NOT EXISTS ( + SELECT 1 FROM account_start_session_activation_protection_settlements settlement + WHERE settlement.activation_protection_id = protection.activation_protection_id) + ORDER BY protection.activation_protection_id FOR UPDATE OF protection NOWAIT; + IF FOUND THEN + RAISE EXCEPTION 'Original StartSession activation protection remains pending for a required source' + USING ERRCODE = '55P03'; + END IF; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java new file mode 100644 index 0000000000..70708c0c42 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -0,0 +1,1021 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** + * Runs V161/V162 against the actual Account PostgreSQL schema and assembled source-writer guard. + * The integrity and currentness fixtures seed related owner rows with producer triggers disabled; + * they prove SQL currentness/exclusion/immutability only, not authenticated activation-protection + * production. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountStartSessionActivationProtectionPostgresIntegrationTest { + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void databaseOwnsProtectionIdentityAndPendingProtectionBlocksSourceWriters() throws Exception { + Fixture fixture = fixture(); + UUID participationId = UUID.randomUUID(); + UUID ownerMutationId = UUID.randomUUID(); + UUID ownerAttemptId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + UUID activationRequestId = UUID.randomUUID(); + byte[] captureReference = bytes("capture-reference"); + byte[] operationIdentity = bytes("{\"schema\":\"activation-operation-test/v1\"}"); + String captureDigest = hash(captureReference); + String operationDigest = "sha256:" + hash(operationIdentity); + OffsetDateTime expiry = + fixture + .dsl() + .fetchSingle("SELECT clock_timestamp() - INTERVAL '1 minute'") + .get(0, OffsetDateTime.class); + OffsetDateTime acquiredAt = expiry.minusMinutes(1); + String expiryText = timestamp(expiry); + SourceEvidence sourceEvidence = + new SourceEvidence( + SourceKind.ACCOUNT, + tenantId.toString(), + "2", + "17", + null, + null, + bytes("captured activation source")); + String sourceKey = sourceEvidence.key(); + byte[] sourceEvidenceBytes = sourceEvidence.canonicalBytes(); + byte[] tuple = bytes("synthetic original tuple"); + byte[] projection = bytes("synthetic Account redemption projection"); + byte[] launchRead = bytes("synthetic authenticated STARTING launch read"); + byte[] preparingEvidence = + jsonBytes( + Map.of( + "schema", + "world-canonical-instance-lifecycle-evidence/v1", + "request", + Map.of( + "readRequestId", + UUID.randomUUID().toString(), + "controlPlaneRequestId", + fixture.requestId(), + "targetNamespace", + "test", + "canonicalTenantId", + tenantId.toString(), + "canonicalGameInstanceId", + gameInstanceId.toString()), + "lifecycleStatus", + "PREPARING", + "lifecycleEpoch", + 12, + "rowVersion", + 19)); + byte[] requestBinding = + activationRequest( + tuple, + projection, + ownerMutationId, + ownerAttemptId, + 11L, + expiryText, + participationId, + 7L, + launchRead, + activationRequestId, + preparingEvidence); + String requestDigest = "sha256:" + hash(requestBinding); + + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceKey); + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + insert( + fixture.dsl(), + "account_start_session_activation_protections", + "control_plane_request_id", + fixture.requestId(), + "account_world_participation_id", + participationId, + "account_world_participation_fence", + 7L, + "original_post_authorization_tuple", + tuple, + "account_redemption_projection", + projection, + "game_session_owner_mutation_id", + ownerMutationId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + 11L, + "original_lease_expires_at", + expiry, + "acquired_at", + acquiredAt, + "target_namespace", + "test", + "canonical_tenant_id", + tenantId, + "canonical_game_instance_id", + gameInstanceId, + "world_activation_request_id", + activationRequestId, + "game_session_launch_read_evidence", + launchRead, + "world_preparing_evidence", + preparingEvidence, + "capture_source_version", + 13L, + "capture_source_fence", + 17L, + "capture_sha256", + captureDigest, + "capture_reference_bytes", + captureReference, + "capture_reference_sha256", + captureDigest, + "operation_identity_bytes", + operationIdentity, + "operation_identity_digest", + operationDigest, + "request_binding_bytes", + requestBinding, + "request_binding_digest", + requestDigest); + var parent = + fixture + .dsl() + .fetchSingle( + "SELECT activation_protection_id, activation_protection_fence, " + + "acquired_at " + + "FROM account_start_session_activation_protections " + + "WHERE control_plane_request_id = ?", + fixture.requestId()); + UUID id = parent.get("activation_protection_id", UUID.class); + insert( + fixture.dsl(), + "account_start_session_activation_protection_sources", + "activation_protection_id", + id, + "source_key", + sourceKey, + "source_evidence", + sourceEvidenceBytes); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + + var stored = + fixture + .dsl() + .fetchSingle( + "SELECT activation_protection_id, activation_protection_fence, acquired_at " + + "FROM account_start_session_activation_protections " + + "WHERE operation_identity_digest = ?", + operationDigest); + UUID id = stored.get("activation_protection_id", UUID.class); + assertThat(id).isNotNull().isNotEqualTo(new UUID(0L, 0L)); + assertThat(stored.get("activation_protection_fence", Long.class)).isPositive(); + assertThat(stored.get("acquired_at", OffsetDateTime.class)).isNotNull(); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_activation_protections " + + "SET acquired_at = acquired_at " + + "WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("immutable; terminal settlement is separate"); + + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(" + + "ARRAY[?]::text[])", + sourceKey))) + .hasMessageContaining("Original StartSession activation protection remains pending"); + + // This synthetic SQL receipt proves only that V162 permits a source writer after an immutable + // terminal-shaped row is committed. It is not a typed receipt or authenticated World producer + // proof. The original Account lease is deliberately expired before this settlement insert. + OffsetDateTime retainedAcquiredAt = stored.get("acquired_at", OffsetDateTime.class); + long protectionFence = stored.get("activation_protection_fence", Long.class); + byte[] accountEvidenceBytes = + accountEvidence( + id, + protectionFence, + retainedAcquiredAt, + requestBinding, + captureReference, + sourceEvidenceBytes); + byte[] activationResultBytes = + activationResult(activationRequestId, preparingEvidence, "COMMITTED"); + + Map changedCapture = readJson(accountEvidenceBytes); + byte[] wrongCapture = bytes("substituted capture reference"); + changedCapture.put( + "originalSourceCaptureReferenceBytesBase64", + Base64.getEncoder().encodeToString(wrongCapture)); + changedCapture.put("originalSourceCaptureReferenceSha256", hash(wrongCapture)); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedCapture), + activationResultBytes); + + Map changedRequest = readJson(accountEvidenceBytes); + changedRequest.put( + "requestBytesBase64", + Base64.getEncoder().encodeToString(bytes("{\"schema\":\"substituted-request/v1\"}"))); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedRequest), + activationResultBytes); + + Map changedSources = readJson(accountEvidenceBytes); + changedSources.put( + "sourceEvidenceVector", + java.util.List.of(Base64.getEncoder().encodeToString(bytes("substituted source")))); + assertSettlementInsertRejected( + fixture, + id, + protectionFence, + activationRequestId, + accountEvidenceBytes(changedSources), + activationResultBytes); + + byte[] terminalBytes = + terminalBytes( + id, protectionFence, activationRequestId, accountEvidenceBytes, activationResultBytes); + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + id, + "activation_protection_fence", + protectionFence, + "world_activation_request_id", + activationRequestId, + "world_activation_fence", + 29L, + "outcome", + "COMMITTED", + "account_protection_evidence_bytes", + accountEvidenceBytes, + "terminal_bytes", + terminalBytes, + "terminal_digest", + "sha256:" + hash(terminalBytes))); + + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_activation_protection_settlements " + + "SET outcome = outcome WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("activation settlement is immutable"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "DELETE FROM account_start_session_activation_protection_settlements " + + "WHERE activation_protection_id = ?", + id))) + .hasMessageContaining("activation settlement is immutable"); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "TRUNCATE account_start_session_activation_protection_settlements"))) + .hasMessageContaining("activation settlement is immutable"); + + for (String guard : + new String[] { + "account_control_ui_hold_required_sources(text[])", + "account_draft_authorization_source_change_guard()", + "account_hosted_terms_disclosure_handoff_guard()" + }) { + String guardDefinition = + fixture + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", guard) + .get(0, String.class); + assertThat(guardDefinition) + .contains("account_ss_admission_assert_no_pending") + .contains("account_start_session_world_participations"); + } + String pendingProtectionDefinition = + fixture + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef('account_ss_admission_assert_no_pending(text[])'::regprocedure)") + .get(0, String.class); + assertThat(pendingProtectionDefinition) + .contains("account_start_session_admission_protection_sources") + .contains("account_ss_admission_is_settled") + .contains("account_start_session_activation_protection_settlements"); + } + + @Test + void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() throws Exception { + Fixture fixture = fixture(); + CurrentnessCase valid = currentnessCase(fixture, Instant.now().plusSeconds(60)); + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + valid.requestBytes(), + valid.operationIdentityBytes(), + valid.operationIdentityDigest())); + + byte[] changedAttempt = + activationRequest(valid, UUID.randomUUID().toString(), valid.expiryText(), "PREPARING"); + assertCurrentnessRejected(fixture, changedAttempt, valid.operationIdentityBytes()); + + byte[] changedWorldState = + activationRequest(valid, valid.ownerAttemptId().toString(), valid.expiryText(), "ACTIVE"); + assertCurrentnessRejected(fixture, changedWorldState, valid.operationIdentityBytes()); + + Fixture expiredFixture = fixture(); + CurrentnessCase expired = currentnessCase(expiredFixture, Instant.now().minusSeconds(1)); + assertCurrentnessRejected( + expiredFixture, expired.requestBytes(), expired.operationIdentityBytes()); + } + + private static void assertSettlementInsertRejected( + Fixture fixture, + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes) { + byte[] terminalBytes = + terminalBytes( + protectionId, + protectionFence, + activationRequestId, + protectionEvidenceBytes, + activationResultBytes); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + protectionId, + "activation_protection_fence", + protectionFence, + "world_activation_request_id", + activationRequestId, + "world_activation_fence", + 29L, + "outcome", + "COMMITTED", + "account_protection_evidence_bytes", + protectionEvidenceBytes, + "terminal_bytes", + terminalBytes, + "terminal_digest", + "sha256:" + hash(terminalBytes)))) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); + } + + private static byte[] accountEvidence( + UUID protectionId, + long protectionFence, + OffsetDateTime acquiredAt, + byte[] requestBytes, + byte[] captureReference, + byte[] sourceEvidence) + throws Exception { + Map value = new LinkedHashMap<>(); + value.put("schema", "account-start-session-activation-protection-evidence/v1"); + value.put("requestBytesBase64", Base64.getEncoder().encodeToString(requestBytes)); + value.put("accountProtectionId", protectionId.toString()); + value.put("accountProtectionFence", Long.toString(protectionFence)); + value.put("acquiredAt", timestamp(acquiredAt)); + value.put( + "originalSourceCaptureReferenceBytesBase64", + Base64.getEncoder().encodeToString(captureReference)); + value.put("originalSourceCaptureReferenceSha256", hash(captureReference)); + value.put( + "sourceEvidenceVector", + java.util.List.of(Base64.getEncoder().encodeToString(sourceEvidence))); + return jsonBytes(value); + } + + private static byte[] accountEvidenceBytes(Map value) throws Exception { + return jsonBytes(value); + } + + private static byte[] activationResult( + UUID activationRequestId, byte[] preparingEvidence, String outcome) throws Exception { + Map preparing = readJson(preparingEvidence); + @SuppressWarnings("unchecked") + Map lifecycleRequest = (Map) preparing.get("request"); + lifecycleRequest.remove("readRequestId"); + Map activationRequest = new LinkedHashMap<>(); + activationRequest.put("schema", "world-canonical-instance-activation-request/v1"); + activationRequest.put("activationRequestId", activationRequestId.toString()); + activationRequest.put("preparingEvidence", preparing); + byte[] activationRequestBytes = jsonBytes(activationRequest); + + Map result = new LinkedHashMap<>(); + result.put("schema", "world-canonical-instance-activation-result/v1"); + result.put("activationRequestId", activationRequestId.toString()); + result.put("requestDigest", "sha256:" + hash(activationRequestBytes)); + result.put("requestBytesBase64", Base64.getEncoder().encodeToString(activationRequestBytes)); + result.put( + "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(preparingEvidence)); + result.put("outcome", outcome); + result.put("terminalCode", "COMMITTED".equals(outcome) ? null : "FENCED_ABORT"); + result.put( + "lifecycleEvidenceBytesBase64", + Base64.getEncoder().encodeToString(bytes("synthetic ACTIVE"))); + return jsonBytes(result); + } + + private static byte[] terminalBytes( + UUID protectionId, + long protectionFence, + UUID activationRequestId, + byte[] protectionEvidenceBytes, + byte[] activationResultBytes) { + Map terminal = new LinkedHashMap<>(); + terminal.put("schema", "world-original-start-session-activation-terminal-evidence/v1"); + terminal.put("activationRequestId", activationRequestId.toString()); + terminal.put("accountProtectionId", protectionId.toString()); + terminal.put("accountProtectionFence", Long.toString(protectionFence)); + terminal.put("worldActivationFence", "29"); + terminal.put( + "accountProtectionEvidenceBytesBase64", + Base64.getEncoder().encodeToString(protectionEvidenceBytes)); + terminal.put( + "activationResultBytesBase64", Base64.getEncoder().encodeToString(activationResultBytes)); + terminal.put("activationResultSha256", hash(activationResultBytes)); + try { + return jsonBytes(terminal); + } catch (Exception impossible) { + throw new IllegalStateException("Synthetic terminal receipt must be canonical", impossible); + } + } + + private static Map readJson(byte[] bytes) throws Exception { + return JSON.readValue(bytes, new tools.jackson.core.type.TypeReference<>() {}); + } + + private static String timestamp(OffsetDateTime value) { + return DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") + .withZone(ZoneOffset.UTC) + .format(value.toInstant()); + } + + private static void assertCurrentnessRejected( + Fixture fixture, byte[] requestBytes, byte[] operationIdentityBytes) { + String operationDigest = "sha256:" + hash(operationIdentityBytes); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + requestBytes, + operationIdentityBytes, + operationDigest))) + .isInstanceOf(RuntimeException.class) + .satisfies( + failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); + } + + private static CurrentnessCase currentnessCase(Fixture fixture, Instant originalLease) + throws Exception { + UUID tenantId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + UUID participationId = UUID.randomUUID(); + UUID ownerMutationId = UUID.randomUUID(); + UUID ownerAttemptId = UUID.randomUUID(); + UUID activationRequestId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID issuanceOperationId = UUID.randomUUID(); + long ownerFence = 11L; + long issuanceFence = 9L; + long sourceVersion = 13L; + long sourceFence = 17L; + String requestId = "original-activation/" + UUID.randomUUID(); + String fingerprint = "arfp/v1/activation-test/" + "a".repeat(64); + OffsetDateTime dbNow = + fixture.dsl().fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class); + Instant normalizedNow = dbNow.toInstant().truncatedTo(ChronoUnit.MICROS); + Instant normalizedLease = originalLease.truncatedTo(ChronoUnit.MICROS); + Instant issuedAt = normalizedNow.minusSeconds(10); + Instant redeemedAt = normalizedNow.minusSeconds(5); + Instant referenceExpiry = normalizedNow.plusSeconds(180); + Instant responseExpiry = normalizedNow.plusSeconds(220); + String expiryText = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'") + .withZone(ZoneOffset.UTC) + .format(normalizedLease); + + byte[] preAuthorization = bytes("{}"); + byte[] authorityBundle = bytes("{}"); + byte[] tuple = + jsonBytes( + Map.of( + "controlPlaneRequestId", + requestId, + "preAuthorizationReservationTuple", + Map.of(), + "authorizationReferenceFingerprint", + fingerprint, + "issuanceFence", + Long.toString(issuanceFence), + "authorityEvidenceBundle", + Map.of())); + byte[] projection = + jsonBytes( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + fingerprint, + "authorityEvidenceBundle", + Map.of(), + "issuanceOperationId", + issuanceOperationId.toString(), + "issuanceFence", + issuanceFence)); + SourceEvidence sourceEvidence = + new SourceEvidence( + SourceKind.ACCOUNT, + tenantId.toString(), + "2", + "17", + null, + null, + bytes("activation-source")); + String sourceKey = sourceEvidence.key(); + byte[] snapshot = + jsonBytes( + Map.of( + "schema", + "account-start-session-authority-snapshot/v1", + "controlPlaneRequestId", + requestId, + "sourceVector", + java.util.List.of( + Base64.getEncoder().encodeToString(sourceEvidence.canonicalBytes())))); + byte[] captureReference = bytes("{}"); + String captureDigest = hash(captureReference); + String snapshotDigest = hash(snapshot); + byte[] attemptBytes = bytes("synthetic-current-original-attempt"); + String preparationInput = "{}"; + String preparationDigest = "sha256:" + hash(bytes(preparationInput)); + + byte[] worldPreparing = + jsonBytes( + Map.of( + "schema", + "world-canonical-instance-lifecycle-evidence/v1", + "request", + Map.of( + "controlPlaneRequestId", + requestId, + "targetNamespace", + "test", + "canonicalTenantId", + tenantId.toString(), + "canonicalGameInstanceId", + gameInstanceId.toString()), + "lifecycleStatus", + "PREPARING")); + byte[] launchRead = bytes("synthetic exact STARTING read"); + byte[] operationIdentity = bytes("activation operation identity"); + String operationDigest = "sha256:" + hash(operationIdentity); + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceKey); + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + insert( + fixture.dsl(), + "account_start_session_authority_captures", + "control_plane_request_id", + requestId, + "account_uuid", + accountId, + "tenant_uuid", + tenantId, + "target_owner", + "game-session-service", + "logging_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "pre_authorization_tuple", + preAuthorization, + "mutation_digest", + "c".repeat(64), + "control_ui_operation_id", + UUID.randomUUID(), + "control_ui_token_jti", + UUID.randomUUID(), + "control_ui_token_hash", + "d".repeat(64), + "control_ui_signer_receipt_sha256", + "e".repeat(64), + "issuance_fence", + issuanceFence, + "issuance_fence_source_version", + sourceVersion, + "captured_at", + OffsetDateTime.ofInstant( + normalizedNow.truncatedTo(ChronoUnit.MILLIS), ZoneOffset.UTC), + "snapshot_sha256", + snapshotDigest, + "canonical_snapshot_bytes", + snapshot, + "source_version", + sourceVersion, + "source_fence", + sourceFence, + "linearization", + "19", + "canonical_sha256", + captureDigest, + "canonical_capture_bytes", + captureReference); + insert( + fixture.dsl(), + "account_start_session_operator_authorizations", + "control_plane_request_id", + requestId, + "pre_authorization_tuple", + preAuthorization, + "mutation_digest", + "c".repeat(64), + "issuance_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "issuance_operation_id", + issuanceOperationId, + "issuance_fence", + issuanceFence, + "bundle_version", + "authorityEvidenceBundle/v1", + "bundle_source_version", + Long.toString(sourceVersion), + "bundle_source_fence", + Long.toString(sourceFence), + "bundle_linearization", + "19", + "authority_evidence_bundle", + authorityBundle, + "authorization_reference_fingerprint", + fingerprint, + "encrypted_response_envelope", + bytes("synthetic response"), + "issued_at", + OffsetDateTime.ofInstant(issuedAt, ZoneOffset.UTC), + "reference_expires_at", + OffsetDateTime.ofInstant(referenceExpiry, ZoneOffset.UTC), + "response_envelope_expires_at", + OffsetDateTime.ofInstant(responseExpiry, ZoneOffset.UTC), + "status", + "REDEEMED", + "redemption_redeemer_workload_uri", + "spiffe://firemud/ns/test/sa/game-session-service", + "redemption_owner_attempt_id", + ownerAttemptId, + "redemption_owner_fence", + ownerFence, + "redeemed_at", + OffsetDateTime.ofInstant(redeemedAt, ZoneOffset.UTC), + "redemption_reference_fingerprint", + fingerprint, + "redemption_authority_evidence_bundle", + authorityBundle); + insert( + fixture.dsl(), + "account_start_session_world_participations", + "participation_id", + participationId, + "control_plane_request_id", + requestId, + "original_post_authorization_tuple", + tuple, + "target_namespace", + "test", + "canonical_tenant_id", + tenantId, + "canonical_game_instance_id", + gameInstanceId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + ownerFence, + "preparation_input_json", + preparationInput, + "preparation_input_digest", + preparationDigest); + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + participationId, + "source_key", + sourceKey, + "source_evidence", + sourceEvidence.canonicalBytes()); + insert( + fixture.dsl(), + "account_start_session_world_original_attempt_evidence", + "participation_id", + participationId, + "target_namespace", + "test", + "game_session_owner_mutation_id", + ownerMutationId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + ownerFence, + "original_lease_expires_at", + OffsetDateTime.ofInstant(normalizedLease, ZoneOffset.UTC), + "original_response_bytes", + attemptBytes, + "original_response_digest", + "sha256:" + hash(attemptBytes)); + insert( + fixture.dsl(), + "account_start_session_world_participation_settlements", + "participation_id", + participationId, + "outcome", + "COMMITTED", + "world_execution_fence", + 3L, + "terminal_bytes", + bytes("synthetic committed preparation"), + "terminal_digest", + "sha256:" + hash(bytes("synthetic committed preparation"))); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + byte[] requestBytes = + activationRequest( + tuple, + projection, + ownerMutationId, + ownerAttemptId, + ownerFence, + expiryText, + participationId, + fixture + .dsl() + .fetchSingle( + "SELECT participation_fence FROM account_start_session_world_participations " + + "WHERE participation_id = ?", + participationId) + .get("participation_fence", Long.class), + launchRead, + activationRequestId, + worldPreparing); + return new CurrentnessCase( + requestBytes, operationIdentity, operationDigest, ownerAttemptId, expiryText); + } + + private static byte[] activationRequest( + CurrentnessCase current, String ownerAttemptId, String expiry, String worldStatus) + throws Exception { + Map root = + JSON.readValue(current.requestBytes(), new tools.jackson.core.type.TypeReference<>() {}); + root.put("gameSessionOwnerAttemptId", ownerAttemptId); + root.put("originalLeaseExpiresAt", expiry); + byte[] preparing = + Base64.getDecoder().decode((String) root.get("preparingEvidenceBytesBase64")); + Map world = + JSON.readValue(preparing, new tools.jackson.core.type.TypeReference<>() {}); + world.put("lifecycleStatus", worldStatus); + root.put("preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(jsonBytes(world))); + return jsonBytes(root); + } + + private static byte[] activationRequest( + byte[] tuple, + byte[] projection, + UUID ownerMutationId, + UUID ownerAttemptId, + long ownerFence, + String expiry, + UUID participationId, + long participationFence, + byte[] launchRead, + UUID activationRequestId, + byte[] preparingEvidence) + throws Exception { + Map value = new LinkedHashMap<>(); + value.put("schema", "account-start-session-activation-protection-request/v1"); + value.put( + "originalPostAuthorizationTupleBytesBase64", Base64.getEncoder().encodeToString(tuple)); + value.put( + "accountRedemptionProjectionBytesBase64", Base64.getEncoder().encodeToString(projection)); + value.put("gameSessionOwnerMutationId", ownerMutationId.toString()); + value.put("gameSessionOwnerAttemptId", ownerAttemptId.toString()); + value.put("gameSessionOwnerFence", Long.toString(ownerFence)); + value.put("originalLeaseExpiresAt", expiry); + value.put("accountWorldParticipationId", participationId.toString()); + value.put("accountWorldParticipationFence", Long.toString(participationFence)); + value.put( + "gameSessionLaunchReadEvidenceBytesBase64", Base64.getEncoder().encodeToString(launchRead)); + value.put("worldActivationRequestId", activationRequestId.toString()); + value.put( + "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(preparingEvidence)); + byte[] result = jsonBytes(value); + return result; + } + + private static byte[] jsonBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static Fixture fixture() { + String schema = "ss_activation_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + String requestId = "activation-test/" + UUID.randomUUID(); + return new Fixture(dsl, transaction, requestId); + } + + private static void insert(DSLContext dsl, String table, Object... fields) { + Map, Object> values = new java.util.LinkedHashMap<>(); + for (int index = 0; index < fields.length; index += 2) { + values.put(DSL.field(DSL.name((String) fields[index])), fields[index + 1]); + } + dsl.insertInto(DSL.table(DSL.name(table))).set(values).execute(); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String hash(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private record Fixture(DSLContext dsl, TransactionTemplate transaction, String requestId) {} + + private record CurrentnessCase( + byte[] requestBytes, + byte[] operationIdentityBytes, + String operationIdentityDigest, + UUID ownerAttemptId, + String expiryText) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepositoryTest.java new file mode 100644 index 0000000000..d61072b707 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepositoryTest.java @@ -0,0 +1,198 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionRequest; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Storage comparison and dispatch-integrity tests. The mocked typed request proves no producer + * authority; PostgreSQL source exclusion and currentness SQL are covered by integration fixtures. + */ +class AccountStartSessionActivationProtectionRepositoryTest { + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void lookupRequiresCallerOwnedWritableReadCommittedTransactionBeforeDatabaseAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountStartSessionActivationProtectionRepository repository = + new AccountStartSessionActivationProtectionRepository(dsl); + + assertThatThrownBy(() -> repository.findExact(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account READ_COMMITTED transaction required"); + + verifyNoInteractions(dsl); + } + + @Test + void historicalResolutionAndSettlementRequireIndependentOwnerTransactionBeforeDatabaseAccess() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountStartSessionActivationProtectionRepository(dsl); + + assertThatThrownBy(() -> repository.findHistoricalExact(UUID.randomUUID(), 7L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account READ_COMMITTED transaction required"); + assertThatThrownBy(() -> repository.findSettlementExact(UUID.randomUUID(), 7L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account READ_COMMITTED transaction required"); + assertThatThrownBy(() -> repository.settleExact(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account READ_COMMITTED transaction required"); + + verifyNoInteractions(dsl); + } + + @Test + void exactPrefixedCommonRequestDigestReachesCurrentnessSql() throws Exception { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountStartSessionActivationProtectionRepository(dsl); + byte[] operationIdentity = "stable operation identity".getBytes(StandardCharsets.UTF_8); + byte[] fullRequest = "full request retaining read UUIDs".getBytes(StandardCharsets.UTF_8); + String requestDigest = "sha256:" + sha256(operationIdentity); + AccountStartSessionActivationProtectionRequest request = + mockedRequest(fullRequest, operationIdentity, requestDigest); + + repository.assertCurrent(request); + + verify(dsl) + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + fullRequest, + operationIdentity, + requestDigest); + } + + @Test + void unprefixedDigestIsRejectedBeforeCurrentnessSql() throws Exception { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountStartSessionActivationProtectionRepository(dsl); + byte[] operationIdentity = "stable operation identity".getBytes(StandardCharsets.UTF_8); + AccountStartSessionActivationProtectionRequest request = + mockedRequest( + "full request".getBytes(StandardCharsets.UTF_8), + operationIdentity, + sha256(operationIdentity)); + + assertThatThrownBy(() -> repository.assertCurrent(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with its immutable binding"); + + verifyNoInteractions(dsl); + } + + @Test + void operationRetryUsesStableIdentityRatherThanReplacingFirstFullRequest() { + byte[] firstFullRequest = "first read UUIDs".getBytes(StandardCharsets.UTF_8); + byte[] retryFullRequest = "fresh read UUIDs".getBytes(StandardCharsets.UTF_8); + byte[] stableOperationIdentity = "normalized operation".getBytes(StandardCharsets.UTF_8); + + assertThat(firstFullRequest).isNotEqualTo(retryFullRequest); + AccountStartSessionActivationProtectionRepository.requireSameOperationIdentity( + stableOperationIdentity, stableOperationIdentity.clone()); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionRepository.requireSameOperationIdentity( + stableOperationIdentity, "changed activation".getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with its immutable binding"); + } + + @Test + void changedCaptureBindingConflictsBeforeAnyReceiptCanBeReturned() { + AccountStartSessionActivationProtectionRepository.requireSameCaptureBinding( + "original-request", 19L, 23L, "a".repeat(64), "original-request", 19L, 23L, "a".repeat(64)); + + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionRepository.requireSameCaptureBinding( + "original-request", + 19L, + 23L, + "a".repeat(64), + "original-request", + 20L, + 23L, + "b".repeat(64))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with its immutable binding"); + } + + @Test + void sourceChildrenMustMatchTheCompleteCanonicalEvidenceVector() { + SourceEvidence first = source("captured source bytes"); + SourceEvidence sameKeyChangedValue = source("substituted source bytes"); + + AccountStartSessionActivationProtectionRepository.requireExactSources( + List.of(first), List.of(first)); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionRepository.requireExactSources( + List.of(first), List.of(sameKeyChangedValue))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with its immutable binding"); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionRepository.requireExactSources( + List.of(first), List.of())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with its immutable binding"); + } + + private static SourceEvidence source(String value) { + return new SourceEvidence( + SourceKind.ACCOUNT, + UUID.fromString("12d1a4d7-b8c9-4b36-853f-7e658d06d30f").toString(), + "2", + "17", + null, + null, + value.getBytes(StandardCharsets.UTF_8)); + } + + private static AccountStartSessionActivationProtectionRequest mockedRequest( + byte[] fullRequest, byte[] operationIdentity, String requestDigest) { + var request = mock(AccountStartSessionActivationProtectionRequest.class); + var launchEvidence = mock(OriginalStartSessionLaunchReadEvidence.Result.class); + var launch = mock(CanonicalGameInstanceLaunchAssociationReadEvidence.Result.class); + var activation = mock(WorldCanonicalInstanceActivation.Request.class); + var preparing = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(request.gameSessionLaunchReadEvidence()).thenReturn(launchEvidence); + when(launchEvidence.launch()).thenReturn(launch); + when(launch.currentGameInstanceStatus()).thenReturn(CurrentGameInstanceStatus.STARTING); + when(request.worldActivationRequest()).thenReturn(activation); + when(activation.preparing()).thenReturn(preparing); + when(preparing.lifecycleStatus()).thenReturn("PREPARING"); + when(request.operationIdentityBytes()).thenReturn(operationIdentity); + when(request.requestDigest()).thenReturn(requestDigest); + when(request.canonicalBytes()).thenReturn(fullRequest); + return request; + } + + private static String sha256(byte[] value) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcServiceTest.java new file mode 100644 index 0000000000..6d4c48fdea --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcServiceTest.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionActivationProtectionRequest; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionActivationProtectionResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Receiver ordering denials; synthetic peer context is not authenticated transport proof. */ +class AccountStartSessionActivationProtectionAcquisitionGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final String WORLD_URI = + "spiffe://firemud/ns/world-runtime/sa/world-management-service"; + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsMissingWrongNamespaceAndWrongWorkloadBeforeDecoding() { + var owner = mock(AccountStartSessionActivationProtectionAcquisitionService.class); + var service = + new AccountStartSessionActivationProtectionAcquisitionGrpcService(owner, NAMESPACE); + var malformed = AcquireOriginalStartSessionActivationProtectionRequest.newBuilder().build(); + + assertCode(Status.Code.UNAUTHENTICATED, invoke(service, null, malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + service, + identity("spiffe://firemud/ns/other-runtime/sa/world-management-service"), + malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + service, identity("spiffe://firemud/ns/world-runtime/sa/account-service"), malformed)); + + SessionContext.setContext("authenticated-user", java.util.List.of(), java.util.Map.of()); + assertCode(Status.Code.PERMISSION_DENIED, invoke(service, identity(WORLD_URI), malformed)); + verifyNoInteractions(owner); + } + + @Test + void rejectsAmbientSqlAndClosedEnvelopeErrorsBeforeAcquisition() { + var owner = mock(AccountStartSessionActivationProtectionAcquisitionService.class); + var service = + new AccountStartSessionActivationProtectionAcquisitionGrpcService(owner, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(service, identity(WORLD_URI), null)); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(service, identity(WORLD_URI), null)); + TransactionSynchronizationManager.clearSynchronization(); + + assertCode(Status.Code.INVALID_ARGUMENT, invoke(service, identity(WORLD_URI), null)); + var duplicate = + AcquireOriginalStartSessionActivationProtectionRequest.newBuilder() + .addSchemaVersion(1) + .addSchemaVersion(1) + .build(); + assertCode(Status.Code.INVALID_ARGUMENT, invoke(service, identity(WORLD_URI), duplicate)); + var unknown = + AcquireOriginalStartSessionActivationProtectionRequest.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertCode(Status.Code.INVALID_ARGUMENT, invoke(service, identity(WORLD_URI), unknown)); + verifyNoInteractions(owner); + } + + private static Invocation invoke( + AccountStartSessionActivationProtectionAcquisitionGrpcService service, + GrpcPeerIdentity peer, + AcquireOriginalStartSessionActivationProtectionRequest request) { + var result = new Invocation(); + Context context = Context.current(); + if (peer != null) { + context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + } + Context previous = context.attach(); + try { + service.acquireOriginalStartSessionActivationProtection(request, result); + } finally { + context.detach(previous); + } + return result; + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, Invocation invocation) { + assertThat(invocation.error).isNotNull(); + assertThat(invocation.error.statusRuntimeException()).isTrue(); + assertThat(invocation.error.code()).isEqualTo(expected); + assertThat(invocation.response).isNull(); + assertThat(invocation.completed).isFalse(); + } + + private record ObservedError(boolean statusRuntimeException, Status.Code code) {} + + private static final class Invocation + implements StreamObserver { + private AcquireOriginalStartSessionActivationProtectionResponse response; + private ObservedError error; + private boolean completed; + + @Override + public void onNext(AcquireOriginalStartSessionActivationProtectionResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = + new ObservedError( + failure instanceof StatusRuntimeException, Status.fromThrowable(failure).getCode()); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionServiceTest.java new file mode 100644 index 0000000000..cbf5b5353e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionServiceTest.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadClient; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mocked ordering and denial checks only; no producer, currentness, or physical-source proof. */ +class AccountStartSessionActivationProtectionAcquisitionServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID MUTATION_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ATTEMPT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactWorldPeerBeforeTupleOrActivationDecoding() { + Harness harness = new Harness(); + + assertCode( + Status.Code.UNAUTHENTICATED, () -> harness.service.acquire(harness.malformedRequest)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("other-runtime", () -> harness.service.acquire(harness.malformedRequest))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + peer( + "world-runtime", + "game-session-service", + () -> harness.service.acquire(harness.malformedRequest))); + + verifyNoInteractions(harness.issuer); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptRepository); + verifyNoInteractions(harness.protectionRepository); + verifyNoInteractions(harness.currentAttemptClient); + verifyNoInteractions(harness.launchReadClient); + } + + @Test + void rejectsAmbientAccountSqlBeforeDecodingOrEitherRemoteOwnerRead() { + Harness harness = new Harness(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + peer( + NAMESPACE, + "world-management-service", + () -> harness.service.acquire(harness.malformedRequest))); + + verifyNoInteractions(harness.issuer); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptRepository); + verifyNoInteractions(harness.protectionRepository); + verifyNoInteractions(harness.currentAttemptClient); + verifyNoInteractions(harness.launchReadClient); + } + + private static T peer(String namespace, java.util.function.Supplier action) { + return peer(namespace, "world-management-service", action); + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var identity = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow(); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, identity); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static final class Harness { + final AccountStartSessionOperatorAuthorizationService issuer = + mock(AccountStartSessionOperatorAuthorizationService.class); + final AccountStartSessionWorldParticipationRepository participationRepository = + mock(AccountStartSessionWorldParticipationRepository.class); + final AccountStartSessionWorldOriginalAttemptEvidenceRepository attemptRepository = + mock(AccountStartSessionWorldOriginalAttemptEvidenceRepository.class); + final AccountStartSessionActivationProtectionRepository protectionRepository = + mock(AccountStartSessionActivationProtectionRepository.class); + final OriginalStartSessionCurrentAttemptClient currentAttemptClient = + mock(OriginalStartSessionCurrentAttemptClient.class); + final OriginalStartSessionLaunchReadClient launchReadClient = + mock(OriginalStartSessionLaunchReadClient.class); + final AccountStartSessionActivationProtectionAcquisitionService service = + new AccountStartSessionActivationProtectionAcquisitionService( + issuer, + participationRepository, + attemptRepository, + protectionRepository, + currentAttemptClient, + launchReadClient, + mock(PlatformTransactionManager.class), + NAMESPACE); + final AccountStartSessionActivationProtectionAcquisitionService.AcquisitionRequest + malformedRequest = + new AccountStartSessionActivationProtectionAcquisitionService.AcquisitionRequest( + new byte[] {1, 2, 3}, MUTATION_ID, ATTEMPT_ID, 7L, null); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcServiceTest.java new file mode 100644 index 0000000000..e52b413ce9 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcServiceTest.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionActivationProtectionRequest; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionActivationProtectionResponse; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionSettlementGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionSettlementInput; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Receiver ordering and dispatch tests; synthetic peer context is not authenticated TLS proof. */ +class AccountStartSessionActivationProtectionSettlementGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final String WORLD_URI = + "spiffe://firemud/ns/world-runtime/sa/world-management-service"; + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactWorldPeerBeforeMalformedRequestParsing() { + var owner = mock(AccountStartSessionActivationProtectionSettlementService.class); + var receiver = + new AccountStartSessionActivationProtectionSettlementGrpcService(owner, NAMESPACE); + var malformed = SettleOriginalStartSessionActivationProtectionRequest.newBuilder().build(); + + assertCode(Status.Code.UNAUTHENTICATED, invoke(receiver, null, malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, + identity("spiffe://firemud/ns/other-runtime/sa/world-management-service"), + malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, identity("spiffe://firemud/ns/world-runtime/sa/account-service"), malformed)); + SessionContext.setContext("authenticated-user", java.util.List.of(), java.util.Map.of()); + assertCode(Status.Code.PERMISSION_DENIED, invoke(receiver, identity(WORLD_URI), malformed)); + verifyNoInteractions(owner); + } + + @Test + void rejectsAmbientSqlAndClosedEnvelopeErrorsBeforeOwnerCall() { + var owner = mock(AccountStartSessionActivationProtectionSettlementService.class); + var receiver = + new AccountStartSessionActivationProtectionSettlementGrpcService(owner, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, identity(WORLD_URI), null)); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, identity(WORLD_URI), null)); + TransactionSynchronizationManager.clearSynchronization(); + + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, identity(WORLD_URI), null)); + var duplicate = + SettleOriginalStartSessionActivationProtectionRequest.newBuilder() + .addSchemaVersion(1) + .addSchemaVersion(1) + .build(); + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, identity(WORLD_URI), duplicate)); + var unknown = + SettleOriginalStartSessionActivationProtectionRequest.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, identity(WORLD_URI), unknown)); + verifyNoInteractions(owner); + } + + @Test + void passesOnlyTheExactProtectionLookupIdentityToTheOwner() { + var owner = mock(AccountStartSessionActivationProtectionSettlementService.class); + UUID protectionId = UUID.fromString("61380051-04b0-48ef-95c4-31f6acb80884"); + when(owner.settle(protectionId, 37L)).thenThrow(Status.UNAVAILABLE.asRuntimeException()); + var receiver = + new AccountStartSessionActivationProtectionSettlementGrpcService(owner, NAMESPACE); + var request = + AccountStartSessionActivationProtectionSettlementGrpcCodec.toRequest( + new AccountStartSessionActivationProtectionSettlementInput( + NAMESPACE, + UUID.fromString("7bd3571a-e943-45e2-a266-4c99db2bd836"), + protectionId, + 37L)); + + var invocation = invoke(receiver, identity(WORLD_URI), request); + assertCode(Status.Code.UNAVAILABLE, invocation); + verify(owner).settle(protectionId, 37L); + } + + private static Invocation invoke( + AccountStartSessionActivationProtectionSettlementGrpcService receiver, + GrpcPeerIdentity peer, + SettleOriginalStartSessionActivationProtectionRequest request) { + var result = new Invocation(); + Context context = Context.current(); + if (peer != null) { + context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + } + Context previous = context.attach(); + try { + receiver.settleOriginalStartSessionActivationProtection(request, result); + } finally { + context.detach(previous); + } + return result; + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, Invocation invocation) { + assertThat(invocation.error).isNotNull(); + assertThat(invocation.error.statusRuntimeException()).isTrue(); + assertThat(invocation.error.code()).isEqualTo(expected); + assertThat(invocation.response).isNull(); + assertThat(invocation.completed).isFalse(); + } + + private record ObservedError(boolean statusRuntimeException, Status.Code code) {} + + private static final class Invocation + implements StreamObserver { + private SettleOriginalStartSessionActivationProtectionResponse response; + private ObservedError error; + private boolean completed; + + @Override + public void onNext(SettleOriginalStartSessionActivationProtectionResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = + new ObservedError( + failure instanceof StatusRuntimeException, Status.fromThrowable(failure).getCode()); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementServiceTest.java new file mode 100644 index 0000000000..a881514376 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementServiceTest.java @@ -0,0 +1,287 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository.StoredSettlement; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalReadClient; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalReadInput; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mocked composition/order proofs only; no authenticated producer or physical-source proof. */ +class AccountStartSessionActivationProtectionSettlementServiceTest { + private static final String NAMESPACE = "world-runtime"; + + @AfterEach + void clearContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactWorldPeerBeforeValidatingLookupSelectors() { + Harness harness = new Harness(); + assertCode(Status.Code.UNAUTHENTICATED, () -> harness.service.settle(null, 0L)); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("other-runtime", () -> harness.service.settle(null, 0L))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + peer("world-runtime", "game-session-service", () -> harness.service.settle(null, 0L))); + + verifyNoInteractions(harness.repository, harness.worldClient); + } + + @Test + void rejectsEndUserAndAmbientAccountTransactionBeforeOwnerOrWorldRead() { + Harness harness = new Harness(); + SessionContext.setContext("authenticated-user", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer(NAMESPACE, () -> harness.service.settle(null, 0L))); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> peer(NAMESPACE, () -> harness.service.settle(null, 0L))); + verifyNoInteractions(harness.repository, harness.worldClient); + } + + @Test + void resolvesExpiredHistoricalProtectionOnlyFromWorldThenReturnsIndependentReadback() { + Harness harness = new Harness(); + harness.prepareNoPriorSettlement(); + StoredSettlement first = + new StoredSettlement(harness.terminal, Instant.parse("2026-10-11T01:02:03Z")); + when(harness.repository.settleExact(harness.terminal)).thenReturn(first); + when(harness.repository.findSettlementExact(harness.protectionId, Harness.PROTECTION_FENCE)) + .thenReturn(Optional.empty(), Optional.of(first)); + when(harness.worldClient.read(any(WorldOriginalStartSessionActivationTerminalReadInput.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + WorldOriginalStartSessionActivationTerminalReadInput input = + invocation.getArgument(0); + assertThat(input.protectionEvidence().canonicalBytes()) + .containsExactly(harness.evidenceBytes); + return harness.terminal; + }); + + StoredSettlement actual = + peer( + NAMESPACE, + () -> harness.service.settle(harness.protectionId, Harness.PROTECTION_FENCE)); + + assertThat(actual.terminal().canonicalBytes()).containsExactly(harness.terminalBytes); + verify(harness.repository).settleExact(harness.terminal); + verify(harness.worldClient) + .read(any(WorldOriginalStartSessionActivationTerminalReadInput.class)); + } + + @Test + void missingWorldTerminalNeverSettlesOrReleasesAccountProtection() { + Harness harness = new Harness(); + harness.prepareNoPriorSettlement(); + when(harness.worldClient.read(any(WorldOriginalStartSessionActivationTerminalReadInput.class))) + .thenReturn(null); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + peer( + NAMESPACE, + () -> harness.service.settle(harness.protectionId, Harness.PROTECTION_FENCE))); + + verify(harness.repository, never()).settleExact(any()); + } + + @Test + void worldReadTimeoutNeverSettlesOrReleasesAccountProtection() { + Harness harness = new Harness(); + harness.prepareNoPriorSettlement(); + when(harness.worldClient.read(any(WorldOriginalStartSessionActivationTerminalReadInput.class))) + .thenThrow(Status.DEADLINE_EXCEEDED.asRuntimeException()); + + assertCode( + Status.Code.DEADLINE_EXCEEDED, + () -> + peer( + NAMESPACE, + () -> harness.service.settle(harness.protectionId, Harness.PROTECTION_FENCE))); + + verify(harness.repository, never()).settleExact(any()); + } + + @Test + void priorExactReceiptRecoversResponseLossWithoutAnotherWorldRead() { + Harness harness = new Harness(); + StoredSettlement prior = + new StoredSettlement(harness.terminal, Instant.parse("2026-10-11T01:02:03Z")); + when(harness.repository.findHistoricalExact(harness.protectionId, Harness.PROTECTION_FENCE)) + .thenReturn(Optional.of(harness.evidence)); + when(harness.repository.findSettlementExact(harness.protectionId, Harness.PROTECTION_FENCE)) + .thenReturn(Optional.of(prior)); + + StoredSettlement recovered = + peer( + NAMESPACE, + () -> harness.service.settle(harness.protectionId, Harness.PROTECTION_FENCE)); + + assertThat(recovered.terminal().canonicalBytes()).containsExactly(harness.terminalBytes); + verifyNoInteractions(harness.worldClient); + verify(harness.repository, never()).settleExact(any()); + } + + @Test + void mismatchedWorldReceiptAndUnmatchedReadbackNeverReturnAsSettlement() { + Harness mismatch = new Harness(); + mismatch.prepareNoPriorSettlement(); + AccountStartSessionActivationProtectionEvidence otherEvidence = + mock(AccountStartSessionActivationProtectionEvidence.class); + when(otherEvidence.canonicalBytes()).thenReturn("different Account receipt".getBytes()); + when(mismatch.terminal.accountProtectionEvidence()).thenReturn(otherEvidence); + when(mismatch.worldClient.read(any(WorldOriginalStartSessionActivationTerminalReadInput.class))) + .thenReturn(mismatch.terminal); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + peer( + NAMESPACE, + () -> mismatch.service.settle(mismatch.protectionId, Harness.PROTECTION_FENCE))); + verify(mismatch.repository, never()).settleExact(any()); + + Harness readback = new Harness(); + readback.prepareNoPriorSettlement(); + StoredSettlement committed = + new StoredSettlement(readback.terminal, Instant.parse("2026-10-11T01:02:03Z")); + when(readback.repository.settleExact(readback.terminal)).thenReturn(committed); + when(readback.repository.findSettlementExact(readback.protectionId, Harness.PROTECTION_FENCE)) + .thenReturn(Optional.empty(), Optional.empty()); + when(readback.worldClient.read(any(WorldOriginalStartSessionActivationTerminalReadInput.class))) + .thenReturn(readback.terminal); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + peer( + NAMESPACE, + () -> readback.service.settle(readback.protectionId, Harness.PROTECTION_FENCE))); + } + + private static void assertCode(Status.Code expected, Runnable action) { + org.assertj.core.api.Assertions.assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static T peer(String namespace, java.util.function.Supplier action) { + return peer(namespace, "world-management-service", action); + } + + private static T peer( + String namespace, String service, java.util.function.Supplier action) { + var identity = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, identity); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private static final class Harness { + final UUID protectionId = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + static final long PROTECTION_FENCE = 17L; + final UUID activationId = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + final byte[] evidenceBytes = "exact historical Account evidence".getBytes(); + final byte[] terminalBytes = "exact World terminal receipt".getBytes(); + final AccountStartSessionActivationProtectionRepository repository = + mock(AccountStartSessionActivationProtectionRepository.class); + final WorldOriginalStartSessionActivationTerminalReadClient worldClient = + mock(WorldOriginalStartSessionActivationTerminalReadClient.class); + final AccountStartSessionActivationProtectionEvidence evidence = + mock( + AccountStartSessionActivationProtectionEvidence.class, + org.mockito.Mockito.withSettings() + .defaultAnswer(org.mockito.Mockito.RETURNS_DEEP_STUBS)); + final WorldOriginalStartSessionActivationTerminalEvidence terminal = + mock(WorldOriginalStartSessionActivationTerminalEvidence.class); + final AccountStartSessionActivationProtectionSettlementService service = + new AccountStartSessionActivationProtectionSettlementService( + repository, worldClient, new TestTransactions(), NAMESPACE); + + Harness() { + when(evidence.accountProtectionId()).thenReturn(protectionId); + when(evidence.accountProtectionFence()).thenReturn(PROTECTION_FENCE); + when(evidence.canonicalBytes()).thenReturn(evidenceBytes); + when(evidence + .request() + .originalTuple() + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace()) + .thenReturn(NAMESPACE); + when(evidence.request().worldActivationRequest().activationRequestId()) + .thenReturn(activationId); + when(terminal.accountProtectionEvidence()).thenReturn(evidence); + when(terminal.activationRequestId()).thenReturn(activationId); + when(terminal.worldActivationFence()).thenReturn(29L); + when(terminal.outcome()).thenReturn(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + when(terminal.canonicalBytes()).thenReturn(terminalBytes); + when(terminal.terminalDigest()).thenReturn("sha256:" + "a".repeat(64)); + } + + void prepareNoPriorSettlement() { + when(repository.findHistoricalExact(protectionId, PROTECTION_FENCE)) + .thenReturn(Optional.of(evidence)); + when(repository.findSettlementExact(protectionId, PROTECTION_FENCE)) + .thenReturn(Optional.empty(), Optional.empty()); + } + } + + private static final class TestTransactions extends AbstractPlatformTransactionManager { + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) {} + + @Override + protected void doCommit(DefaultTransactionStatus status) {} + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java index 41af2b6065..ffe632502b 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -27,6 +27,7 @@ import java.util.concurrent.Callable; import javax.crypto.spec.SecretKeySpec; import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionAdmissionProtectionRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; @@ -34,10 +35,12 @@ import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalReadClient; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadClient; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalReadClient; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; import org.jooq.DSLContext; @@ -327,6 +330,39 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( namespace); } + /** + * Creates the actual distinct World-activation protection acquirer over retained Account rows. + */ + public AccountStartSessionActivationProtectionAcquisitionService + activationProtectionAcquisitionService( + OriginalStartSessionCurrentAttemptClient gameSessionCurrentAttemptClient, + OriginalStartSessionLaunchReadClient gameSessionLaunchReadClient) { + Objects.requireNonNull( + gameSessionCurrentAttemptClient, "Game Session current-attempt client required"); + Objects.requireNonNull(gameSessionLaunchReadClient, "Game Session launch-read client required"); + return new AccountStartSessionActivationProtectionAcquisitionService( + authorizationService, + new AccountStartSessionWorldParticipationRepository(accountSources.dsl), + new AccountStartSessionWorldOriginalAttemptEvidenceRepository(accountSources.dsl), + new AccountStartSessionActivationProtectionRepository(accountSources.dsl), + gameSessionCurrentAttemptClient, + gameSessionLaunchReadClient, + accountSources.manager, + namespace); + } + + /** Creates the actual historical activation settler over this fixture's retained Account rows. */ + public AccountStartSessionActivationProtectionSettlementService + activationProtectionSettlementService( + WorldOriginalStartSessionActivationTerminalReadClient worldTerminalReadClient) { + Objects.requireNonNull(worldTerminalReadClient, "World terminal-read client required"); + return new AccountStartSessionActivationProtectionSettlementService( + new AccountStartSessionActivationProtectionRepository(accountSources.dsl), + worldTerminalReadClient, + accountSources.manager, + namespace); + } + /** Existing fixture SQL context for independent test-only retained-row inspection. */ public DSLContext sourceDsl() { return accountSources.dsl; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionClient.java new file mode 100644 index 0000000000..c6f10e3640 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionClient.java @@ -0,0 +1,11 @@ +package net.firedevops.firemud.common.account.startsession; + +/** Explicit World-side seam for asking Account to retain its original activation source lock. */ +public interface AccountStartSessionActivationProtectionAcquisitionClient { + /** + * Acquires or recovers Account's immutable first receipt for the exact activation statement. + * Returned evidence is integrity-checked but does not prove World-side PREPARING currentness. + */ + AccountStartSessionActivationProtectionEvidence acquire( + AccountStartSessionActivationProtectionAcquisitionInput input); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodec.java new file mode 100644 index 0000000000..c76d6d69f3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodec.java @@ -0,0 +1,272 @@ +package net.firedevops.firemud.common.account.startsession; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionActivationProtectionRequest; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionActivationProtectionResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; + +/** Closed bounded protobuf encoding for Account's original StartSession activation protection. */ +public final class AccountStartSessionActivationProtectionAcquisitionGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 65 * 1024 * 1024; + + /** Existing complete evidence cap plus only protobuf tag/length framing headroom. */ + public static final int MAX_RESPONSE_WIRE_BYTES = + AccountStartSessionActivationProtectionEvidence.MAX_CANONICAL_BYTES + 64; + + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountStartSessionActivationProtectionAcquisitionGrpcCodec() {} + + public static AcquireOriginalStartSessionActivationProtectionRequest toRequest( + AccountStartSessionActivationProtectionAcquisitionInput input, String targetNamespace) { + Objects.requireNonNull(input, "activation protection acquisition input is required"); + requireNamespace(targetNamespace); + input.requireTargetNamespace(targetNamespace); + var request = + AcquireOriginalStartSessionActivationProtectionRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addTargetNamespace(targetNamespace) + .addOriginalPostAuthorizationTuple( + ByteString.copyFrom(input.originalPostAuthorizationTuple())) + .addGameSessionOwnerMutationId(input.gameSessionOwnerMutationId().toString()) + .addGameSessionOwnerAttemptId(input.gameSessionOwnerAttemptId().toString()) + .addGameSessionOwnerFence(Long.toString(input.gameSessionOwnerFence())) + .addActivationRequestId(input.worldActivationRequest().activationRequestId().toString()) + .addWorldPreparingEvidence( + ByteString.copyFrom(input.worldActivationRequest().preparingEvidenceBytes())) + .build(); + requireRequestBudget(request); + return request; + } + + /** + * Parses only after the receiver authenticates its exact same-namespace World peer. Repeated + * scalar fields let the generated object preserve and reject duplicate occurrences. + */ + public static AccountStartSessionActivationProtectionAcquisitionInput fromRequest( + AcquireOriginalStartSessionActivationProtectionRequest request, String expectedNamespace) { + Objects.requireNonNull(request, "activation protection acquisition request is required"); + requireClosed(request, "request"); + requireRequestBudget(request); + if (request.getSchemaVersionCount() != 1 + || request.getTargetNamespaceCount() != 1 + || request.getOriginalPostAuthorizationTupleCount() != 1 + || request.getGameSessionOwnerMutationIdCount() != 1 + || request.getGameSessionOwnerAttemptIdCount() != 1 + || request.getGameSessionOwnerFenceCount() != 1 + || request.getActivationRequestIdCount() != 1 + || request.getWorldPreparingEvidenceCount() != 1 + || request.getSchemaVersion(0) != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(expectedNamespace) + || !expectedNamespace.equals(request.getTargetNamespace(0))) { + throw invalid("Unsupported schema, duplicate field, or target namespace"); + } + + byte[] tupleBytes = request.getOriginalPostAuthorizationTuple(0).toByteArray(); + byte[] preparingBytes = request.getWorldPreparingEvidence(0).toByteArray(); + if (tupleBytes.length == 0 + || tupleBytes.length + > net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple + .MAX_CANONICAL_TUPLE_BYTES + || preparingBytes.length == 0 + || preparingBytes.length + > AccountStartSessionActivationProtectionRequest.MAX_WORLD_PREPARING_EVIDENCE_BYTES) { + throw invalid("Original tuple or complete World PREPARING evidence is missing or oversized"); + } + var input = + new AccountStartSessionActivationProtectionAcquisitionInput( + tupleBytes, + canonicalUuid(request.getGameSessionOwnerMutationId(0), "gameSessionOwnerMutationId"), + canonicalUuid(request.getGameSessionOwnerAttemptId(0), "gameSessionOwnerAttemptId"), + canonicalPositiveLong(request.getGameSessionOwnerFence(0), "gameSessionOwnerFence"), + new WorldCanonicalInstanceActivation.Request( + canonicalUuid(request.getActivationRequestId(0), "activationRequestId"), + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence + .fromStored(preparingBytes))); + input.requireTargetNamespace(expectedNamespace); + if (!toRequest(input, expectedNamespace).equals(request)) { + throw invalid("Activation protection request is not the exact canonical tuple"); + } + return input; + } + + /** + * Optional raw-wire parser for contexts that receive the protobuf frame directly. Generated gRPC + * service methods receive a parsed message, so the server additionally uses repeated-field counts + * to preserve duplicate detection at that boundary. + */ + public static AccountStartSessionActivationProtectionAcquisitionInput fromRequestWireBytes( + byte[] exactCanonicalWireBytes, String expectedNamespace) { + Objects.requireNonNull(exactCanonicalWireBytes, "exact request wire bytes are required"); + if (exactCanonicalWireBytes.length == 0 + || exactCanonicalWireBytes.length > MAX_REQUEST_WIRE_BYTES) { + throw invalid("Activation protection request exceeds its wire budget"); + } + try { + var request = + AcquireOriginalStartSessionActivationProtectionRequest.parseFrom(exactCanonicalWireBytes); + AccountStartSessionActivationProtectionAcquisitionInput input = + fromRequest(request, expectedNamespace); + if (!Arrays.equals( + exactCanonicalWireBytes, toRequest(input, expectedNamespace).toByteArray())) { + throw invalid("Activation protection request wire bytes are not canonical"); + } + return input; + } catch (InvalidProtocolBufferException malformed) { + throw invalid("Activation protection request wire bytes are malformed", malformed); + } + } + + public static AcquireOriginalStartSessionActivationProtectionResponse toResponse( + AccountStartSessionActivationProtectionAcquisitionInput input, + String targetNamespace, + AccountStartSessionActivationProtectionEvidence evidence) { + requireEvidenceMatchesInput(input, targetNamespace, evidence); + var response = + AcquireOriginalStartSessionActivationProtectionResponse.newBuilder() + .addEvidenceCanonicalBytes(ByteString.copyFrom(evidence.canonicalBytes())) + .build(); + requireResponseBudget(response); + return response; + } + + /** Validates full canonical evidence and returns its first immutable receipt bytes unchanged. */ + public static AccountStartSessionActivationProtectionEvidence fromResponse( + AccountStartSessionActivationProtectionAcquisitionInput input, + String targetNamespace, + AcquireOriginalStartSessionActivationProtectionResponse response) { + Objects.requireNonNull(input, "activation protection acquisition input is required"); + Objects.requireNonNull(response, "activation protection acquisition response is required"); + requireClosed(response, "response"); + requireResponseBudget(response); + if (response.getEvidenceCanonicalBytesCount() != 1) { + throw invalid("Activation protection response must contain one evidence receipt"); + } + AccountStartSessionActivationProtectionEvidence evidence = + AccountStartSessionActivationProtectionEvidence.decode( + response.getEvidenceCanonicalBytes(0).toByteArray()); + requireEvidenceMatchesInput(input, targetNamespace, evidence); + return evidence; + } + + public static AccountStartSessionActivationProtectionEvidence fromResponseWireBytes( + AccountStartSessionActivationProtectionAcquisitionInput input, + String targetNamespace, + byte[] exactCanonicalWireBytes) { + Objects.requireNonNull(exactCanonicalWireBytes, "response wire bytes are required"); + if (exactCanonicalWireBytes.length == 0 + || exactCanonicalWireBytes.length > MAX_RESPONSE_WIRE_BYTES) { + throw invalid("Activation protection response exceeds its wire budget"); + } + try { + var response = + AcquireOriginalStartSessionActivationProtectionResponse.parseFrom( + exactCanonicalWireBytes); + AccountStartSessionActivationProtectionEvidence evidence = + fromResponse(input, targetNamespace, response); + if (!Arrays.equals( + exactCanonicalWireBytes, toResponse(input, targetNamespace, evidence).toByteArray())) { + throw invalid("Activation protection response wire bytes are not canonical"); + } + return evidence; + } catch (InvalidProtocolBufferException malformed) { + throw invalid("Activation protection response wire bytes are malformed", malformed); + } + } + + private static void requireEvidenceMatchesInput( + AccountStartSessionActivationProtectionAcquisitionInput input, + String targetNamespace, + AccountStartSessionActivationProtectionEvidence evidence) { + Objects.requireNonNull(input, "activation protection acquisition input is required"); + Objects.requireNonNull(evidence, "activation protection evidence is required"); + requireNamespace(targetNamespace); + input.requireTargetNamespace(targetNamespace); + var retained = evidence.request(); + var retainedActivation = retained.worldActivationRequest(); + var requestedActivation = input.worldActivationRequest(); + if (!Arrays.equals( + input.originalPostAuthorizationTuple(), retained.originalPostAuthorizationTupleBytes()) + || !input.gameSessionOwnerMutationId().equals(retained.gameSessionOwnerMutationId()) + || !input.gameSessionOwnerAttemptId().equals(retained.gameSessionOwnerAttemptId()) + || input.gameSessionOwnerFence() != retained.gameSessionOwnerFence() + || !requestedActivation + .activationRequestId() + .equals(retainedActivation.activationRequestId()) + || !MessageDigest.isEqual( + requestedActivation.canonicalRequestBytes(), retainedActivation.canonicalRequestBytes()) + || !targetNamespace.equals( + retained.originalTuple().preAuthorizationTuple().action().scope().targetNamespace())) { + throw invalid("Account evidence changed the exact original activation acquisition binding"); + } + } + + private static void requireRequestBudget( + AcquireOriginalStartSessionActivationProtectionRequest request) { + if (request.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) { + throw invalid("Activation protection request exceeds its wire budget"); + } + } + + private static void requireResponseBudget( + AcquireOriginalStartSessionActivationProtectionResponse response) { + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || response.getEvidenceCanonicalBytesCount() != 1 + || response.getEvidenceCanonicalBytes(0).isEmpty() + || response.getEvidenceCanonicalBytes(0).size() + > AccountStartSessionActivationProtectionEvidence.MAX_CANONICAL_BYTES) { + throw invalid("Activation protection evidence is missing or exceeds its wire budget"); + } + } + + private static void requireClosed(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid("Activation protection " + label + " contains unsupported fields"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static long canonicalPositiveLong(String value, String field) { + if (value == null || !value.matches("[1-9][0-9]{0,18}")) { + throw invalid(field + " must be canonical positive unsigned decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException overflow) { + throw invalid(field + " exceeds the supported positive fence range", overflow); + } + } + + private static void requireNamespace(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw invalid("Target namespace must be one canonical DNS label"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionInput.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionInput.java new file mode 100644 index 0000000000..824a4cc4c7 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionInput.java @@ -0,0 +1,110 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; + +/** + * Exact caller-carried World statement for Account's original StartSession activation protection. + */ +public record AccountStartSessionActivationProtectionAcquisitionInput( + byte[] originalPostAuthorizationTuple, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + WorldCanonicalInstanceActivation.Request worldActivationRequest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public AccountStartSessionActivationProtectionAcquisitionInput { + Objects.requireNonNull( + originalPostAuthorizationTuple, "original StartSession tuple is required"); + if (originalPostAuthorizationTuple.length == 0 + || originalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException("Original StartSession tuple is missing or oversized"); + } + originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + var tuple = StartSessionPostAuthorizationExecutionTuple.decode(originalPostAuthorizationTuple); + if (!Arrays.equals(originalPostAuthorizationTuple, tuple.canonicalBytes())) { + throw new IllegalArgumentException( + "Original StartSession tuple must be exact canonical bytes"); + } + if (!"StartSession".equals(tuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(tuple.preAuthorizationTuple().targetOwner())) { + throw new IllegalArgumentException("Original human StartSession tuple is required"); + } + gameSessionOwnerMutationId = + requireNonNil(gameSessionOwnerMutationId, "Game Session owner mutation ID"); + gameSessionOwnerAttemptId = + requireNonNil(gameSessionOwnerAttemptId, "Game Session owner attempt ID"); + if (gameSessionOwnerFence <= 0L) { + throw new IllegalArgumentException("Game Session owner fence must be positive"); + } + Objects.requireNonNull(worldActivationRequest, "exact World activation request is required"); + + byte[] preparingBytes = worldActivationRequest.preparingEvidenceBytes(); + if (preparingBytes.length == 0 + || preparingBytes.length + > AccountStartSessionActivationProtectionRequest.MAX_WORLD_PREPARING_EVIDENCE_BYTES) { + throw new IllegalArgumentException("World PREPARING evidence is missing or oversized"); + } + WorldCanonicalInstanceLifecycleEvidence preparing = + WorldCanonicalInstanceLifecycleEvidence.fromStored(preparingBytes); + if (!Arrays.equals(preparingBytes, preparing.canonicalBytes())) { + throw new IllegalArgumentException("World PREPARING evidence must be exact canonical bytes"); + } + worldActivationRequest = + new WorldCanonicalInstanceActivation.Request( + worldActivationRequest.activationRequestId(), preparing); + + var scope = tuple.preAuthorizationTuple().action().scope(); + var world = preparing.request(); + if (!scope.targetNamespace().equals(world.targetNamespace()) + || !scope.tenantId().equals(world.canonicalTenantId()) + || !tuple.controlPlaneRequestId().equals(world.controlPlaneRequestId()) + || !tuple + .controlPlaneRequestId() + .equals(preparing.launchBinding().descriptor().controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Original tuple and complete World PREPARING identity differ"); + } + // The authored descriptor does not allocate a runtime instance. Account must separately + // prove the instance identity against its authenticated read of the actual GS launch. + } + + @Override + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + /** Requires the configured workload namespace to match both complete original values. */ + public void requireTargetNamespace(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !StartSessionPostAuthorizationExecutionTuple.decode(originalPostAuthorizationTuple) + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(targetNamespace) + || !worldActivationRequest + .preparing() + .request() + .targetNamespace() + .equals(targetNamespace)) { + throw new IllegalArgumentException( + "Target namespace differs from the original tuple or World PREPARING evidence"); + } + } + + private static UUID requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label + " is required"); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + return value; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionEvidence.java new file mode 100644 index 0000000000..f626132481 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionEvidence.java @@ -0,0 +1,478 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Canonical integrity evidence for one Account StartSession activation-protection value. + * + *

This carrier retains the full request, independently acquired Account protection identity, + * exact original capture reference, and complete canonical source-evidence vector. It proves only + * supplied-byte integrity and structural binding; it does not authenticate Account or World, prove + * owner currentness, or establish write exclusion. + */ +public final class AccountStartSessionActivationProtectionEvidence { + public static final String SCHEMA = "account-start-session-activation-protection-evidence/v1"; + + /** + * Aggregate closed-envelope bound: Base64 expansion of the 144 MiB full request is 192 MiB; the + * existing 4 MiB source-vector and 256 KiB capture-reference caps add about 5.7 MiB after Base64 + * expansion, leaving room for the fixed JSON envelope. This is a bound on this new Account value + * only, not a transport limit. + */ + public static final int MAX_CANONICAL_BYTES = 200 * 1024 * 1024; + + private static final String OPERATION_IDENTITY_SCHEMA = + "account-start-session-activation-protection-evidence-operation-identity/v1"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POSITIVE_LONG = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern MICROS_UTC = + Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{6}Z"); + private static final DateTimeFormatter MICROS_FORMAT = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC); + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "requestBytesBase64", + "accountProtectionId", + "accountProtectionFence", + "acquiredAt", + "originalSourceCaptureReferenceBytesBase64", + "originalSourceCaptureReferenceSha256", + "sourceEvidenceVector"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountStartSessionActivationProtectionRequest request; + private final UUID accountProtectionId; + private final long accountProtectionFence; + private final Instant acquiredAt; + private final byte[] originalSourceCaptureReferenceBytes; + private final String originalSourceCaptureReferenceSha256; + private final List sourceEvidenceVector; + private final byte[] canonicalBytes; + private final byte[] operationIdentityBytes; + + private AccountStartSessionActivationProtectionEvidence( + AccountStartSessionActivationProtectionRequest request, + UUID accountProtectionId, + long accountProtectionFence, + Instant acquiredAt, + byte[] originalSourceCaptureReferenceBytes, + String originalSourceCaptureReferenceSha256, + List sourceEvidenceVector, + byte[] canonicalBytes, + byte[] operationIdentityBytes) { + this.request = request; + this.accountProtectionId = accountProtectionId; + this.accountProtectionFence = accountProtectionFence; + this.acquiredAt = acquiredAt; + this.originalSourceCaptureReferenceBytes = originalSourceCaptureReferenceBytes.clone(); + this.originalSourceCaptureReferenceSha256 = originalSourceCaptureReferenceSha256; + this.sourceEvidenceVector = List.copyOf(sourceEvidenceVector); + this.canonicalBytes = canonicalBytes.clone(); + this.operationIdentityBytes = operationIdentityBytes.clone(); + } + + /** Creates canonical evidence while retaining the exact Account capture and complete sources. */ + public static AccountStartSessionActivationProtectionEvidence create( + AccountStartSessionActivationProtectionRequest request, + UUID accountProtectionId, + long accountProtectionFence, + Instant acquiredAt, + byte[] exactOriginalSourceCaptureReferenceBytes, + String originalSourceCaptureReferenceSha256, + List sourceEvidenceVector) { + Objects.requireNonNull(request, "request is required"); + requireNonNil(accountProtectionId, "accountProtectionId"); + requirePositive(accountProtectionFence, "accountProtectionFence"); + Objects.requireNonNull(acquiredAt, "acquiredAt is required"); + String acquiredAtText = canonicalAcquiredAt(acquiredAt); + if (!acquiredAt.isBefore(request.originalLeaseExpiresAt())) { + throw invalid("Account protection must be acquired before the original lease expires"); + } + + byte[] captureReferenceBytes = + bounded( + exactOriginalSourceCaptureReferenceBytes, + AccountStartSessionAdmissionProtectionEvidence.MAX_CAPTURE_REFERENCE_BYTES, + "original Account source capture reference"); + String captureReferenceDigest = requireDigest(originalSourceCaptureReferenceSha256); + if (!captureReferenceDigest.equals(sha256(captureReferenceBytes))) { + throw invalid("Original Account source capture reference digest differs from its bytes"); + } + AccountStartSessionAdmissionProtectionEvidence.requireCaptureReferenceBinding( + captureReferenceBytes, request.originalTuple()); + + List sources = + AccountStartSessionAdmissionProtectionEvidence.canonicalSourceVector(sourceEvidenceVector); + byte[] canonical = + encode( + request.canonicalBytes(), + accountProtectionId, + accountProtectionFence, + acquiredAtText, + captureReferenceBytes, + captureReferenceDigest, + sources); + byte[] operationIdentity = + encodeOperationIdentity( + request.operationIdentityBytes(), + accountProtectionId, + accountProtectionFence, + acquiredAtText, + captureReferenceBytes, + captureReferenceDigest, + sources); + return new AccountStartSessionActivationProtectionEvidence( + request, + accountProtectionId, + accountProtectionFence, + acquiredAt, + captureReferenceBytes, + captureReferenceDigest, + sources, + canonical, + operationIdentity); + } + + /** Strictly decodes one whole canonical bounded evidence value; decoding grants no authority. */ + public static AccountStartSessionActivationProtectionEvidence decode(byte[] exactCanonicalBytes) { + byte[] stored = + bounded(exactCanonicalBytes, MAX_CANONICAL_BYTES, "activation protection evidence"); + try { + String json = strictUtf8(stored); + requireCanonicalJson(stored, json, "activation protection evidence"); + Map root = JSON.readValue(json, new TypeReference<>() {}); + requireExactFields(root, ROOT_FIELDS, "activation protection evidence"); + if (!SCHEMA.equals(string(root.get("schema"), "schema"))) { + throw invalid("Unsupported Account activation protection evidence schema"); + } + Object rawSources = root.get("sourceEvidenceVector"); + if (!(rawSources instanceof List encodedSources)) { + throw invalid("sourceEvidenceVector must be an array"); + } + if (encodedSources.isEmpty() + || encodedSources.size() + > AccountStartSessionAdmissionProtectionEvidence.MAX_SOURCE_EVIDENCE_COUNT) { + throw invalid("sourceEvidenceVector is empty or exceeds its item limit"); + } + List sources = new ArrayList<>(encodedSources.size()); + for (int index = 0; index < encodedSources.size(); index++) { + sources.add( + SourceEvidence.fromStored( + decodeBase64(encodedSources.get(index), "sourceEvidenceVector[" + index + "]"))); + } + AccountStartSessionActivationProtectionEvidence result = + create( + AccountStartSessionActivationProtectionRequest.decode( + decodeBase64(root.get("requestBytesBase64"), "requestBytesBase64")), + canonicalUuid(root.get("accountProtectionId"), "accountProtectionId"), + positiveLong(root.get("accountProtectionFence"), "accountProtectionFence"), + parseAcquiredAt(string(root.get("acquiredAt"), "acquiredAt")), + decodeBase64( + root.get("originalSourceCaptureReferenceBytesBase64"), + "originalSourceCaptureReferenceBytesBase64"), + string( + root.get("originalSourceCaptureReferenceSha256"), + "originalSourceCaptureReferenceSha256"), + sources); + if (!MessageDigest.isEqual(stored, result.canonicalBytes)) { + throw invalid("Account activation protection evidence members are inconsistent"); + } + return result; + } catch (IllegalArgumentException expected) { + throw expected; + } catch (IOException | RuntimeException malformed) { + throw invalid("Account activation protection evidence is malformed"); + } + } + + public AccountStartSessionActivationProtectionRequest request() { + return request; + } + + public UUID accountProtectionId() { + return accountProtectionId; + } + + public long accountProtectionFence() { + return accountProtectionFence; + } + + public Instant acquiredAt() { + return acquiredAt; + } + + public byte[] originalSourceCaptureReferenceBytes() { + return originalSourceCaptureReferenceBytes.clone(); + } + + public String originalSourceCaptureReferenceSha256() { + return originalSourceCaptureReferenceSha256; + } + + public List sourceEvidenceVector() { + return List.copyOf(sourceEvidenceVector); + } + + /** Full exact storage bytes, retaining both transient owner-read correlation UUIDs. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** + * Stable retry identity retains source/protection values and normalizes only owner read UUIDs. + */ + public byte[] operationIdentityBytes() { + return operationIdentityBytes.clone(); + } + + public String requestDigest() { + return "sha256:" + sha256(operationIdentityBytes); + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof AccountStartSessionActivationProtectionEvidence that + && Arrays.equals(canonicalBytes, that.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + private static byte[] encode( + byte[] requestBytes, + UUID protectionId, + long protectionFence, + String acquiredAt, + byte[] captureReferenceBytes, + String captureReferenceDigest, + List sources) { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("requestBytesBase64", Base64.getEncoder().encodeToString(requestBytes)); + value.put("accountProtectionId", protectionId.toString()); + value.put("accountProtectionFence", Long.toString(protectionFence)); + value.put("acquiredAt", acquiredAt); + value.put( + "originalSourceCaptureReferenceBytesBase64", + Base64.getEncoder().encodeToString(captureReferenceBytes)); + value.put("originalSourceCaptureReferenceSha256", captureReferenceDigest); + value.put( + "sourceEvidenceVector", + sources.stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()); + return canonicalJson(value, MAX_CANONICAL_BYTES, "Account activation protection evidence"); + } + + private static byte[] encodeOperationIdentity( + byte[] requestOperationIdentityBytes, + UUID protectionId, + long protectionFence, + String acquiredAt, + byte[] captureReferenceBytes, + String captureReferenceDigest, + List sources) { + Map value = new LinkedHashMap<>(); + value.put("schema", OPERATION_IDENTITY_SCHEMA); + value.put( + "requestOperationIdentityBytesBase64", + Base64.getEncoder().encodeToString(requestOperationIdentityBytes)); + value.put("accountProtectionId", protectionId.toString()); + value.put("accountProtectionFence", Long.toString(protectionFence)); + value.put("acquiredAt", acquiredAt); + value.put( + "originalSourceCaptureReferenceBytesBase64", + Base64.getEncoder().encodeToString(captureReferenceBytes)); + value.put("originalSourceCaptureReferenceSha256", captureReferenceDigest); + value.put( + "sourceEvidenceVector", + sources.stream() + .map(source -> Base64.getEncoder().encodeToString(source.canonicalBytes())) + .toList()); + return canonicalJson( + value, MAX_CANONICAL_BYTES, "Account activation evidence operation identity"); + } + + private static byte[] canonicalJson(Map value, int maximum, String label) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (canonical.length > maximum) throw invalid(label + " exceeds its byte limit"); + return canonical; + } catch (IOException impossible) { + throw new IllegalStateException(label + " cannot be encoded", impossible); + } + } + + private static byte[] decodeBase64(Object value, String field) { + String text = string(value, field); + try { + byte[] decoded = Base64.getDecoder().decode(text); + if (!Base64.getEncoder().encodeToString(decoded).equals(text)) { + throw invalid(field + " must use canonical Base64"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is malformed Base64"); + } + } + + private static byte[] bounded(byte[] value, int maximum, String name) { + if (value == null || value.length == 0 || value.length > maximum) { + throw invalid(name + " is absent or exceeds its byte limit"); + } + return value.clone(); + } + + private static String canonicalAcquiredAt(Instant value) { + if (value.getNano() % 1_000 != 0) { + throw invalid("acquiredAt must use exact UTC microsecond precision"); + } + String text = MICROS_FORMAT.format(value); + if (!MICROS_UTC.matcher(text).matches()) { + throw invalid("acquiredAt must use canonical UTC microsecond text"); + } + return text; + } + + private static Instant parseAcquiredAt(String value) { + if (!MICROS_UTC.matcher(value).matches()) { + throw invalid("acquiredAt must use canonical UTC microsecond text"); + } + try { + Instant parsed = Instant.parse(value); + if (!MICROS_FORMAT.format(parsed).equals(value)) { + throw invalid("acquiredAt must use canonical UTC microsecond text"); + } + return parsed; + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException expected) throw expected; + throw invalid("acquiredAt is malformed"); + } + } + + private static String requireDigest(String value) { + if (value == null || !SHA256.matcher(value).matches()) { + throw invalid("originalSourceCaptureReferenceSha256 must be lowercase SHA-256 hex"); + } + return value; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static long positiveLong(Object value, String field) { + String text = string(value, field); + if (!POSITIVE_LONG.matcher(text).matches()) { + throw invalid(field + " must be a positive canonical signed 64-bit decimal string"); + } + try { + long parsed = Long.parseLong(text); + if (parsed <= 0L || !Long.toString(parsed).equals(text)) { + throw invalid(field + " must be a positive canonical signed 64-bit decimal string"); + } + return parsed; + } catch (NumberFormatException malformed) { + throw invalid(field + " is outside the supported signed 64-bit range"); + } + } + + private static UUID canonicalUuid(Object value, String field) { + String text = string(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || NIL_UUID.equals(parsed)) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (NIL_UUID.equals(value)) throw invalid(field + " must be a non-nil UUID"); + return value; + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) throw invalid(field + " must be positive"); + } + + private static String string(Object value, String field) { + if (!(value instanceof String text)) throw invalid(field + " must be a string"); + return text; + } + + private static void requireExactFields( + Map value, Set expected, String label) { + if (value == null || !value.keySet().equals(expected)) { + throw invalid(label + " has missing or unsupported fields"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw invalid("Account activation protection evidence is not valid UTF-8"); + } + } + + private static void requireCanonicalJson(byte[] originalBytes, String json, String label) + throws IOException { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!MessageDigest.isEqual(canonical, originalBytes)) { + throw invalid(label + " is not canonical RFC 8785 JSON"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionRequest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionRequest.java new file mode 100644 index 0000000000..f93b857ece --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionRequest.java @@ -0,0 +1,644 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Exact integrity-only inputs for Account source protection through original StartSession World + * activation. + * + *

This carrier preserves the complete original tuple, Account projection, finite original Game + * Session lease, exact Game Session launch read, and exact World PREPARING activation request. It + * does not authenticate either owner, establish current source state, or grant activation or + * gameplay admission. + */ +public final class AccountStartSessionActivationProtectionRequest { + public static final String SCHEMA = "account-start-session-activation-protection-request/v1"; + + /** + * New Account-carrier acceptance bound for one complete World PREPARING child. The existing World + * lifecycle evidence has no whole-envelope byte cap; Account rejects larger children rather than + * truncating or reinterpreting them. This is not a World transport limit. + */ + public static final int MAX_WORLD_PREPARING_EVIDENCE_BYTES = 64 * 1024 * 1024; + + /** + * Aggregate closed-envelope bound: Base64 expansion of the existing 41 MiB launch-result and 256 + * KiB tuple caps, this carrier's 64 MiB PREPARING child cap, and the existing Account projection + * cap is about 140.6 MiB; the remaining space covers the fixed JSON envelope. This bounds this + * new Account value only and does not change any owner transport limit. + */ + public static final int MAX_CANONICAL_BYTES = 144 * 1024 * 1024; + + public static final int MAX_PROJECTION_BYTES = + AccountStartSessionAdmissionProtectionRequest.MAX_PROJECTION_BYTES; + + private static final String OPERATION_IDENTITY_SCHEMA = + "account-start-session-activation-protection-operation-identity/v1"; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POSITIVE_LONG = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern MICROS_UTC = + Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{6}Z"); + private static final DateTimeFormatter MICROS_FORMAT = + DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC); + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "originalPostAuthorizationTupleBytesBase64", + "accountRedemptionProjectionBytesBase64", + "gameSessionOwnerMutationId", + "gameSessionOwnerAttemptId", + "gameSessionOwnerFence", + "originalLeaseExpiresAt", + "accountWorldParticipationId", + "accountWorldParticipationFence", + "gameSessionLaunchReadEvidenceBytesBase64", + "worldActivationRequestId", + "preparingEvidenceBytesBase64"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final byte[] originalPostAuthorizationTupleBytes; + private final byte[] accountRedemptionProjectionBytes; + private final UUID gameSessionOwnerMutationId; + private final UUID gameSessionOwnerAttemptId; + private final long gameSessionOwnerFence; + private final Instant originalLeaseExpiresAt; + private final UUID accountWorldParticipationId; + private final long accountWorldParticipationFence; + private final OriginalStartSessionLaunchReadEvidence.Result gameSessionLaunchReadEvidence; + private final WorldCanonicalInstanceActivation.Request worldActivationRequest; + private final StartSessionPostAuthorizationExecutionTuple originalTuple; + private final byte[] canonicalBytes; + private final byte[] operationIdentityBytes; + + private AccountStartSessionActivationProtectionRequest( + byte[] originalPostAuthorizationTupleBytes, + byte[] accountRedemptionProjectionBytes, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + Instant originalLeaseExpiresAt, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + OriginalStartSessionLaunchReadEvidence.Result gameSessionLaunchReadEvidence, + WorldCanonicalInstanceActivation.Request worldActivationRequest, + StartSessionPostAuthorizationExecutionTuple originalTuple, + byte[] canonicalBytes, + byte[] operationIdentityBytes) { + this.originalPostAuthorizationTupleBytes = originalPostAuthorizationTupleBytes.clone(); + this.accountRedemptionProjectionBytes = accountRedemptionProjectionBytes.clone(); + this.gameSessionOwnerMutationId = gameSessionOwnerMutationId; + this.gameSessionOwnerAttemptId = gameSessionOwnerAttemptId; + this.gameSessionOwnerFence = gameSessionOwnerFence; + this.originalLeaseExpiresAt = originalLeaseExpiresAt; + this.accountWorldParticipationId = accountWorldParticipationId; + this.accountWorldParticipationFence = accountWorldParticipationFence; + this.gameSessionLaunchReadEvidence = gameSessionLaunchReadEvidence; + this.worldActivationRequest = worldActivationRequest; + this.originalTuple = originalTuple; + this.canonicalBytes = canonicalBytes.clone(); + this.operationIdentityBytes = operationIdentityBytes.clone(); + } + + /** + * Creates one full request and validates the exact original-to-STARTING-to-PREPARING bindings. + */ + public static AccountStartSessionActivationProtectionRequest create( + byte[] exactCanonicalOriginalPostAuthorizationTupleBytes, + byte[] exactCanonicalAccountRedemptionProjectionBytes, + UUID gameSessionOwnerMutationId, + UUID gameSessionOwnerAttemptId, + long gameSessionOwnerFence, + Instant originalLeaseExpiresAt, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, + OriginalStartSessionLaunchReadEvidence.Result gameSessionLaunchReadEvidence, + WorldCanonicalInstanceActivation.Request worldActivationRequest) { + byte[] tupleBytes = + bounded( + exactCanonicalOriginalPostAuthorizationTupleBytes, + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES, + "original post-authorization tuple"); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + if (!Arrays.equals(tupleBytes, tuple.canonicalBytes())) { + throw invalid("Original post-authorization tuple bytes are not exact canonical bytes"); + } + + byte[] projectionBytes = + bounded( + exactCanonicalAccountRedemptionProjectionBytes, + MAX_PROJECTION_BYTES, + "Account redemption projection"); + byte[] expectedProjection = StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple); + if (!MessageDigest.isEqual(expectedProjection, projectionBytes)) { + throw invalid("Complete Account redemption projection differs from the original tuple"); + } + + requireNonNil(gameSessionOwnerMutationId, "gameSessionOwnerMutationId"); + requireNonNil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); + requirePositive(gameSessionOwnerFence, "gameSessionOwnerFence"); + Objects.requireNonNull(originalLeaseExpiresAt, "originalLeaseExpiresAt is required"); + String expiryText = canonicalExpiry(originalLeaseExpiresAt); + requireNonNil(accountWorldParticipationId, "accountWorldParticipationId"); + requirePositive(accountWorldParticipationFence, "accountWorldParticipationFence"); + Objects.requireNonNull(gameSessionLaunchReadEvidence, "gameSessionLaunchReadEvidence"); + Objects.requireNonNull(worldActivationRequest, "worldActivationRequest"); + + byte[] launchBytes = + bounded( + gameSessionLaunchReadEvidence.canonicalBytes(), + OriginalStartSessionLaunchReadEvidence.MAX_RESULT_BYTES, + "Game Session launch read evidence"); + OriginalStartSessionLaunchReadEvidence.Result decodedLaunch = + OriginalStartSessionLaunchReadEvidence.Result.decode(launchBytes); + byte[] preparingBytes = + bounded( + worldActivationRequest.preparingEvidenceBytes(), + MAX_WORLD_PREPARING_EVIDENCE_BYTES, + "World PREPARING evidence"); + WorldCanonicalInstanceLifecycleEvidence preparing = + WorldCanonicalInstanceLifecycleEvidence.fromStored(preparingBytes); + if (!Arrays.equals(preparingBytes, preparing.canonicalBytes())) { + throw invalid("World PREPARING evidence bytes are not exact canonical bytes"); + } + WorldCanonicalInstanceActivation.Request decodedActivation = + new WorldCanonicalInstanceActivation.Request( + worldActivationRequest.activationRequestId(), preparing); + if (!Arrays.equals( + decodedActivation.preparingEvidenceBytes(), + worldActivationRequest.preparingEvidenceBytes())) { + throw invalid("World activation request differs from its complete PREPARING evidence"); + } + + requireExactOriginalStartBinding(tupleBytes, tuple, decodedLaunch, decodedActivation); + byte[] canonical = + encode( + tupleBytes, + projectionBytes, + gameSessionOwnerMutationId, + gameSessionOwnerAttemptId, + gameSessionOwnerFence, + expiryText, + accountWorldParticipationId, + accountWorldParticipationFence, + launchBytes, + decodedActivation.activationRequestId(), + preparingBytes); + byte[] operationIdentity = + encodeOperationIdentity( + tupleBytes, + projectionBytes, + gameSessionOwnerMutationId, + gameSessionOwnerAttemptId, + gameSessionOwnerFence, + expiryText, + accountWorldParticipationId, + accountWorldParticipationFence, + decodedLaunch.operationIdentityBytes(), + decodedActivation.activationRequestId(), + decodedActivation.canonicalRequestBytes()); + return new AccountStartSessionActivationProtectionRequest( + tupleBytes, + projectionBytes, + gameSessionOwnerMutationId, + gameSessionOwnerAttemptId, + gameSessionOwnerFence, + originalLeaseExpiresAt, + accountWorldParticipationId, + accountWorldParticipationFence, + decodedLaunch, + decodedActivation, + tuple, + canonical, + operationIdentity); + } + + /** Strictly decodes one complete canonical bounded request; decoding grants no authority. */ + public static AccountStartSessionActivationProtectionRequest decode(byte[] exactCanonicalBytes) { + byte[] stored = + bounded(exactCanonicalBytes, MAX_CANONICAL_BYTES, "activation protection request"); + try { + String json = strictUtf8(stored); + requireCanonicalJson(stored, json, "activation protection request"); + Map root = JSON.readValue(json, new TypeReference<>() {}); + requireExactFields(root, ROOT_FIELDS, "activation protection request"); + if (!SCHEMA.equals(string(root.get("schema"), "schema"))) { + throw invalid("Unsupported Account activation protection request schema"); + } + byte[] preparingBytes = + bounded( + decodeBase64( + root.get("preparingEvidenceBytesBase64"), "preparingEvidenceBytesBase64"), + MAX_WORLD_PREPARING_EVIDENCE_BYTES, + "World PREPARING evidence"); + WorldCanonicalInstanceLifecycleEvidence preparing = + WorldCanonicalInstanceLifecycleEvidence.fromStored(preparingBytes); + AccountStartSessionActivationProtectionRequest result = + create( + decodeBase64( + root.get("originalPostAuthorizationTupleBytesBase64"), + "originalPostAuthorizationTupleBytesBase64"), + decodeBase64( + root.get("accountRedemptionProjectionBytesBase64"), + "accountRedemptionProjectionBytesBase64"), + canonicalUuid(root.get("gameSessionOwnerMutationId"), "gameSessionOwnerMutationId"), + canonicalUuid(root.get("gameSessionOwnerAttemptId"), "gameSessionOwnerAttemptId"), + positiveLong(root.get("gameSessionOwnerFence"), "gameSessionOwnerFence"), + parseExpiry(string(root.get("originalLeaseExpiresAt"), "originalLeaseExpiresAt")), + canonicalUuid(root.get("accountWorldParticipationId"), "accountWorldParticipationId"), + positiveLong( + root.get("accountWorldParticipationFence"), "accountWorldParticipationFence"), + OriginalStartSessionLaunchReadEvidence.Result.decode( + decodeBase64( + root.get("gameSessionLaunchReadEvidenceBytesBase64"), + "gameSessionLaunchReadEvidenceBytesBase64")), + new WorldCanonicalInstanceActivation.Request( + canonicalUuid(root.get("worldActivationRequestId"), "worldActivationRequestId"), + preparing)); + if (!MessageDigest.isEqual(stored, result.canonicalBytes)) { + throw invalid("Account activation protection request members are inconsistent"); + } + return result; + } catch (IllegalArgumentException expected) { + throw expected; + } catch (IOException | RuntimeException malformed) { + throw invalid("Account activation protection request is malformed"); + } + } + + public byte[] originalPostAuthorizationTupleBytes() { + return originalPostAuthorizationTupleBytes.clone(); + } + + public byte[] accountRedemptionProjectionBytes() { + return accountRedemptionProjectionBytes.clone(); + } + + public UUID gameSessionOwnerMutationId() { + return gameSessionOwnerMutationId; + } + + public UUID gameSessionOwnerAttemptId() { + return gameSessionOwnerAttemptId; + } + + public long gameSessionOwnerFence() { + return gameSessionOwnerFence; + } + + public Instant originalLeaseExpiresAt() { + return originalLeaseExpiresAt; + } + + public UUID accountWorldParticipationId() { + return accountWorldParticipationId; + } + + public long accountWorldParticipationFence() { + return accountWorldParticipationFence; + } + + public OriginalStartSessionLaunchReadEvidence.Result gameSessionLaunchReadEvidence() { + return gameSessionLaunchReadEvidence; + } + + public WorldCanonicalInstanceActivation.Request worldActivationRequest() { + return worldActivationRequest; + } + + public StartSessionPostAuthorizationExecutionTuple originalTuple() { + return originalTuple; + } + + /** Full exact storage bytes, retaining both transient owner-read correlation UUIDs. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** Stable retry identity; only the two owner transport read UUIDs are normalized. */ + public byte[] operationIdentityBytes() { + return operationIdentityBytes.clone(); + } + + public String requestDigest() { + return sha256(operationIdentityBytes); + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof AccountStartSessionActivationProtectionRequest that + && Arrays.equals(canonicalBytes, that.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + + private static void requireExactOriginalStartBinding( + byte[] tupleBytes, + StartSessionPostAuthorizationExecutionTuple tuple, + OriginalStartSessionLaunchReadEvidence.Result launchEvidence, + WorldCanonicalInstanceActivation.Request activationRequest) { + if (!Arrays.equals(tupleBytes, launchEvidence.request().originalPostAuthorizationTupleBytes()) + || !Arrays.equals( + tupleBytes, launchEvidence.retainedOriginalPostAuthorizationTupleBytes())) { + throw invalid("Game Session launch read does not retain the exact original tuple bytes"); + } + CanonicalGameInstanceLaunchAssociationReadEvidence.Result launch = launchEvidence.launch(); + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector = launch.request(); + WorldCanonicalInstanceLifecycleEvidence preparing = activationRequest.preparing(); + var worldRequest = preparing.request(); + var action = tuple.preAuthorizationTuple().action(); + var scope = action.scope(); + var descriptor = launch.launchBindingEvidence().descriptor(); + var release = launch.launchBindingEvidence().releaseAttestation(); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals( + tuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(tuple.preAuthorizationTuple().targetOwner()) + || !scope.targetNamespace().equals(selector.targetNamespace()) + || !scope.tenantId().equals(selector.canonicalTenantId()) + || !tuple.controlPlaneRequestId().equals(selector.controlPlaneRequestId()) + || tuple.preAuthorizationTuple().action().target().gameTemplateId() + != descriptor.gameTemplateId()) { + throw invalid("Original StartSession tuple differs from the exact launch scope"); + } + if (launch.currentGameInstanceStatus() + != CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING) { + throw invalid("Original activation protection requires the exact Game Session STARTING row"); + } + if (launch.currentRowVersion() < 0L) { + throw invalid("Game Session STARTING rowVersion must be nonnegative"); + } + if (!selector.equals(launchEvidence.request().selector()) + || !selector.targetNamespace().equals(worldRequest.targetNamespace()) + || !selector.canonicalTenantId().equals(worldRequest.canonicalTenantId()) + || !selector.worldSlug().equals(worldRequest.worldSlug()) + || !selector.gameInstanceUuid().equals(worldRequest.canonicalGameInstanceId()) + || !selector.controlPlaneRequestId().equals(worldRequest.controlPlaneRequestId()) + || !selector + .expectedDescriptorRequestDigest() + .equals(worldRequest.expectedDescriptorRequestDigest()) + || !selector + .expectedDescriptorResultDigest() + .equals(worldRequest.expectedDescriptorResultDigest()) + || !selector + .expectedReleaseAttestationEvidenceDigest() + .equals(worldRequest.expectedReleaseAttestationDigest()) + || !selector.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !worldRequest.canonicalVersionId().equals(release.canonicalVersionId()) + || !worldRequest.playableStateNamespaceId().equals(launch.playableStateNamespaceId()) + || !worldRequest.playableStateScope().equals(launch.playableStateScope().name()) + || worldRequest.publicProduction() != launch.publicProduction() + || !preparing.launchBinding().equals(launch.launchBindingEvidence()) + || !activationRequest.canonicalGameInstanceId().equals(selector.gameInstanceUuid())) { + throw invalid("Game Session STARTING and World PREPARING evidence do not bind exactly"); + } + } + + private static byte[] encode( + byte[] tupleBytes, + byte[] projectionBytes, + UUID ownerMutationId, + UUID ownerAttemptId, + long ownerFence, + String leaseExpiry, + UUID participationId, + long participationFence, + byte[] launchEvidenceBytes, + UUID activationRequestId, + byte[] preparingEvidenceBytes) { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put( + "originalPostAuthorizationTupleBytesBase64", + Base64.getEncoder().encodeToString(tupleBytes)); + value.put( + "accountRedemptionProjectionBytesBase64", + Base64.getEncoder().encodeToString(projectionBytes)); + value.put("gameSessionOwnerMutationId", ownerMutationId.toString()); + value.put("gameSessionOwnerAttemptId", ownerAttemptId.toString()); + value.put("gameSessionOwnerFence", Long.toString(ownerFence)); + value.put("originalLeaseExpiresAt", leaseExpiry); + value.put("accountWorldParticipationId", participationId.toString()); + value.put("accountWorldParticipationFence", Long.toString(participationFence)); + value.put( + "gameSessionLaunchReadEvidenceBytesBase64", + Base64.getEncoder().encodeToString(launchEvidenceBytes)); + value.put("worldActivationRequestId", activationRequestId.toString()); + value.put( + "preparingEvidenceBytesBase64", Base64.getEncoder().encodeToString(preparingEvidenceBytes)); + return canonicalJson(value, MAX_CANONICAL_BYTES, "Account activation protection request"); + } + + private static byte[] encodeOperationIdentity( + byte[] tupleBytes, + byte[] projectionBytes, + UUID ownerMutationId, + UUID ownerAttemptId, + long ownerFence, + String leaseExpiry, + UUID participationId, + long participationFence, + byte[] launchOperationIdentityBytes, + UUID activationRequestId, + byte[] activationOperationIdentityBytes) { + Map value = new LinkedHashMap<>(); + value.put("schema", OPERATION_IDENTITY_SCHEMA); + value.put( + "originalPostAuthorizationTupleBytesBase64", + Base64.getEncoder().encodeToString(tupleBytes)); + value.put( + "accountRedemptionProjectionBytesBase64", + Base64.getEncoder().encodeToString(projectionBytes)); + value.put("gameSessionOwnerMutationId", ownerMutationId.toString()); + value.put("gameSessionOwnerAttemptId", ownerAttemptId.toString()); + value.put("gameSessionOwnerFence", Long.toString(ownerFence)); + value.put("originalLeaseExpiresAt", leaseExpiry); + value.put("accountWorldParticipationId", participationId.toString()); + value.put("accountWorldParticipationFence", Long.toString(participationFence)); + value.put( + "gameSessionLaunchReadOperationIdentityBytesBase64", + Base64.getEncoder().encodeToString(launchOperationIdentityBytes)); + value.put("worldActivationRequestId", activationRequestId.toString()); + value.put( + "worldActivationOperationIdentityBytesBase64", + Base64.getEncoder().encodeToString(activationOperationIdentityBytes)); + return canonicalJson(value, MAX_CANONICAL_BYTES, "Account activation operation identity"); + } + + private static byte[] canonicalJson(Map value, int maximum, String label) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (canonical.length > maximum) throw invalid(label + " exceeds its byte limit"); + return canonical; + } catch (IOException impossible) { + throw new IllegalStateException(label + " cannot be encoded", impossible); + } + } + + private static byte[] decodeBase64(Object value, String field) { + String text = string(value, field); + try { + byte[] decoded = Base64.getDecoder().decode(text); + if (!Base64.getEncoder().encodeToString(decoded).equals(text)) { + throw invalid(field + " must use canonical Base64"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is malformed Base64"); + } + } + + private static byte[] bounded(byte[] value, int maximum, String name) { + if (value == null || value.length == 0 || value.length > maximum) { + throw invalid(name + " is absent or exceeds its byte limit"); + } + return value.clone(); + } + + private static String canonicalExpiry(Instant value) { + if (value.getNano() % 1_000 != 0) { + throw invalid("originalLeaseExpiresAt must use exact microsecond precision"); + } + String text = MICROS_FORMAT.format(value); + if (!MICROS_UTC.matcher(text).matches()) { + throw invalid("originalLeaseExpiresAt must use canonical UTC microsecond text"); + } + return text; + } + + private static Instant parseExpiry(String value) { + if (!MICROS_UTC.matcher(value).matches()) { + throw invalid("originalLeaseExpiresAt must use canonical UTC microsecond text"); + } + try { + Instant parsed = Instant.parse(value); + if (!MICROS_FORMAT.format(parsed).equals(value)) { + throw invalid("originalLeaseExpiresAt must use canonical UTC microsecond text"); + } + return parsed; + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException expected) throw expected; + throw invalid("originalLeaseExpiresAt is malformed"); + } + } + + private static long positiveLong(Object value, String field) { + String text = string(value, field); + if (!POSITIVE_LONG.matcher(text).matches()) { + throw invalid(field + " must be a positive canonical signed 64-bit decimal string"); + } + try { + long parsed = Long.parseLong(text); + if (parsed <= 0L || !Long.toString(parsed).equals(text)) { + throw invalid(field + " must be a positive canonical signed 64-bit decimal string"); + } + return parsed; + } catch (NumberFormatException malformed) { + throw invalid(field + " is outside the supported signed 64-bit range"); + } + } + + private static UUID canonicalUuid(Object value, String field) { + String text = string(value, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || NIL_UUID.equals(parsed)) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field + " is required"); + if (NIL_UUID.equals(value)) throw invalid(field + " must be a non-nil UUID"); + return value; + } + + private static void requirePositive(long value, String field) { + if (value <= 0L) throw invalid(field + " must be positive"); + } + + private static String sha256(byte[] value) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static String string(Object value, String field) { + if (!(value instanceof String text)) throw invalid(field + " must be a string"); + return text; + } + + private static void requireExactFields( + Map value, Set expected, String label) { + if (value == null || !value.keySet().equals(expected)) { + throw invalid(label + " has missing or unsupported fields"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw invalid("Account activation protection request is not valid UTF-8"); + } + } + + private static void requireCanonicalJson(byte[] originalBytes, String json, String label) + throws IOException { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(json); + if (!MessageDigest.isEqual(canonical, originalBytes)) { + throw invalid(label + " is not canonical RFC 8785 JSON"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementClient.java new file mode 100644 index 0000000000..0b3e002c82 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementClient.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.common.account.startsession; + +/** Authenticated lookup-only client for Account's exact immutable activation settlement. */ +public interface AccountStartSessionActivationProtectionSettlementClient { + AccountStartSessionActivationProtectionSettlementEvidence settle( + AccountStartSessionActivationProtectionSettlementInput input); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementEvidence.java new file mode 100644 index 0000000000..3e037e49ae --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementEvidence.java @@ -0,0 +1,40 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; + +/** Full immutable Account settlement identity and the exact World terminal receipt it retained. */ +public record AccountStartSessionActivationProtectionSettlementEvidence( + UUID settlementRequestId, + WorldOriginalStartSessionActivationTerminalEvidence terminal, + Instant settledAt) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public AccountStartSessionActivationProtectionSettlementEvidence { + Objects.requireNonNull(settlementRequestId, "settlement correlation ID required"); + if (NIL_UUID.equals(settlementRequestId)) { + throw new IllegalArgumentException("Settlement correlation ID must be non-nil"); + } + Objects.requireNonNull(terminal, "complete World terminal receipt required"); + Objects.requireNonNull(settledAt, "Account settlement timestamp required"); + if (settledAt.getNano() % 1_000 != 0) { + throw new IllegalArgumentException( + "Account settlement timestamp must preserve PostgreSQL microseconds"); + } + if (terminal.outcome() != WorldCanonicalInstanceActivation.Outcome.COMMITTED + && terminal.outcome() != WorldCanonicalInstanceActivation.Outcome.ABORTED) { + throw new IllegalArgumentException("Exact terminal activation outcome required"); + } + } + + public UUID accountProtectionId() { + return terminal.accountProtectionEvidence().accountProtectionId(); + } + + public long accountProtectionFence() { + return terminal.accountProtectionEvidence().accountProtectionFence(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodec.java new file mode 100644 index 0000000000..fcace0b333 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodec.java @@ -0,0 +1,290 @@ +package net.firedevops.firemud.common.account.startsession; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.util.Arrays; +import java.util.Locale; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionActivationProtectionRequest; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionActivationProtectionResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; + +/** Closed, bounded protobuf mapping for Account's exact original activation settlement receipt. */ +public final class AccountStartSessionActivationProtectionSettlementGrpcCodec { + /** Small selector only; no caller-supplied terminal bytes are accepted. */ + public static final int MAX_REQUEST_WIRE_BYTES = 512; + + /** Existing full World receipt cap plus bounded protobuf wrapper framing and identity fields. */ + public static final int MAX_RESPONSE_WIRE_BYTES = + WorldOriginalStartSessionActivationTerminalEvidence.MAX_CANONICAL_BYTES + 256; + + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final DateTimeFormatter UTC_MICROS = + new DateTimeFormatterBuilder() + .appendPattern("uuuu-MM-dd'T'HH:mm:ss") + .appendLiteral('.') + .appendFraction(java.time.temporal.ChronoField.NANO_OF_SECOND, 6, 6, false) + .appendLiteral('Z') + .toFormatter(Locale.ROOT) + .withZone(ZoneOffset.UTC); + + private AccountStartSessionActivationProtectionSettlementGrpcCodec() {} + + public static SettleOriginalStartSessionActivationProtectionRequest toRequest( + AccountStartSessionActivationProtectionSettlementInput input) { + Objects.requireNonNull(input, "activation settlement input required"); + var request = + SettleOriginalStartSessionActivationProtectionRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addTargetNamespace(input.targetNamespace()) + .addSettlementRequestId(input.settlementRequestId().toString()) + .addAccountProtectionId(input.accountProtectionId().toString()) + .addAccountProtectionFence(Long.toString(input.accountProtectionFence())) + .build(); + requireRequestBudget(request); + return request; + } + + /** Must be called only after exact same-namespace World peer authentication. */ + public static AccountStartSessionActivationProtectionSettlementInput fromRequest( + SettleOriginalStartSessionActivationProtectionRequest request, String expectedNamespace) { + Objects.requireNonNull(request, "activation settlement request required"); + requireClosed(request, "request"); + requireRequestBudget(request); + if (request.getSchemaVersionCount() != 1 + || request.getTargetNamespaceCount() != 1 + || request.getSettlementRequestIdCount() != 1 + || request.getAccountProtectionIdCount() != 1 + || request.getAccountProtectionFenceCount() != 1 + || request.getSchemaVersion(0) != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(expectedNamespace) + || !expectedNamespace.equals(request.getTargetNamespace(0))) { + throw invalid("Unsupported schema, duplicate field, or target namespace"); + } + var input = + new AccountStartSessionActivationProtectionSettlementInput( + expectedNamespace, + canonicalUuid(request.getSettlementRequestId(0), "settlementRequestId"), + canonicalUuid(request.getAccountProtectionId(0), "accountProtectionId"), + canonicalPositiveLong(request.getAccountProtectionFence(0))); + if (!toRequest(input).equals(request)) { + throw invalid("Activation settlement request is not its exact closed encoding"); + } + return input; + } + + public static AccountStartSessionActivationProtectionSettlementEvidence fromResponse( + AccountStartSessionActivationProtectionSettlementInput input, + SettleOriginalStartSessionActivationProtectionResponse response) { + Objects.requireNonNull(input, "activation settlement input required"); + Objects.requireNonNull(response, "activation settlement response required"); + requireClosed(response, "response"); + requireResponseBudget(response); + if (response.getSchemaVersionCount() != 1 + || response.getSettlementRequestIdCount() != 1 + || response.getAccountProtectionIdCount() != 1 + || response.getAccountProtectionFenceCount() != 1 + || response.getSettledAtCount() != 1 + || response.getTerminalEvidenceCanonicalBytesCount() != 1 + || response.getSchemaVersion(0) != SCHEMA_VERSION + || !input.settlementRequestId().toString().equals(response.getSettlementRequestId(0)) + || !input.accountProtectionId().toString().equals(response.getAccountProtectionId(0)) + || !Long.toString(input.accountProtectionFence()) + .equals(response.getAccountProtectionFence(0))) { + throw invalid("Activation settlement response identity differs from its request"); + } + Instant settledAt = canonicalInstant(response.getSettledAt(0)); + byte[] terminalBytes = response.getTerminalEvidenceCanonicalBytes(0).toByteArray(); + if (terminalBytes.length == 0 + || terminalBytes.length + > WorldOriginalStartSessionActivationTerminalEvidence.MAX_CANONICAL_BYTES) { + throw invalid("Complete World terminal receipt is missing or oversized"); + } + var terminal = WorldOriginalStartSessionActivationTerminalEvidence.decode(terminalBytes); + if (!Arrays.equals(terminalBytes, terminal.canonicalBytes()) + || !input + .accountProtectionId() + .equals(terminal.accountProtectionEvidence().accountProtectionId()) + || input.accountProtectionFence() + != terminal.accountProtectionEvidence().accountProtectionFence() + || !input + .targetNamespace() + .equals( + terminal + .accountProtectionEvidence() + .request() + .originalTuple() + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace())) { + throw invalid("Full World terminal receipt differs from the exact Account protection"); + } + var evidence = + new AccountStartSessionActivationProtectionSettlementEvidence( + input.settlementRequestId(), terminal, settledAt); + if (!toResponse(evidence).equals(response)) { + throw invalid("Activation settlement response is not its exact closed encoding"); + } + return evidence; + } + + /** Encodes only complete settlement evidence returned by the Account owner service. */ + public static SettleOriginalStartSessionActivationProtectionResponse toResponse( + AccountStartSessionActivationProtectionSettlementInput input, + AccountStartSessionActivationProtectionSettlementEvidence evidence) { + Objects.requireNonNull(input, "activation settlement input required"); + Objects.requireNonNull(evidence, "durable Account settlement evidence required"); + if (!input.settlementRequestId().equals(evidence.settlementRequestId()) + || !input.accountProtectionId().equals(evidence.accountProtectionId()) + || input.accountProtectionFence() != evidence.accountProtectionFence() + || !input + .targetNamespace() + .equals( + evidence + .terminal() + .accountProtectionEvidence() + .request() + .originalTuple() + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace())) { + throw invalid("Durable settlement differs from the exact request identity"); + } + return toResponse(evidence); + } + + public static AccountStartSessionActivationProtectionSettlementEvidence fromResponseWireBytes( + AccountStartSessionActivationProtectionSettlementInput input, byte[] wireBytes) { + if (wireBytes == null || wireBytes.length == 0 || wireBytes.length > MAX_RESPONSE_WIRE_BYTES) { + throw invalid("Activation settlement response exceeds its wire budget"); + } + try { + var response = SettleOriginalStartSessionActivationProtectionResponse.parseFrom(wireBytes); + var evidence = fromResponse(input, response); + if (!Arrays.equals(wireBytes, toResponse(evidence).toByteArray())) { + throw invalid("Activation settlement response wire bytes are not canonical"); + } + return evidence; + } catch (InvalidProtocolBufferException malformed) { + throw invalid("Activation settlement response wire bytes are malformed", malformed); + } + } + + public static AccountStartSessionActivationProtectionSettlementInput fromRequestWireBytes( + byte[] wireBytes, String expectedNamespace) { + if (wireBytes == null || wireBytes.length == 0 || wireBytes.length > MAX_REQUEST_WIRE_BYTES) { + throw invalid("Activation settlement request exceeds its wire budget"); + } + try { + var request = SettleOriginalStartSessionActivationProtectionRequest.parseFrom(wireBytes); + var input = fromRequest(request, expectedNamespace); + if (!Arrays.equals(wireBytes, toRequest(input).toByteArray())) { + throw invalid("Activation settlement request wire bytes are not canonical"); + } + return input; + } catch (InvalidProtocolBufferException malformed) { + throw invalid("Activation settlement request wire bytes are malformed", malformed); + } + } + + private static SettleOriginalStartSessionActivationProtectionResponse toResponse( + AccountStartSessionActivationProtectionSettlementEvidence evidence) { + var response = + SettleOriginalStartSessionActivationProtectionResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addSettlementRequestId(evidence.settlementRequestId().toString()) + .addAccountProtectionId(evidence.accountProtectionId().toString()) + .addAccountProtectionFence(Long.toString(evidence.accountProtectionFence())) + .addSettledAt(UTC_MICROS.format(evidence.settledAt())) + .addTerminalEvidenceCanonicalBytes( + ByteString.copyFrom(evidence.terminal().canonicalBytes())) + .build(); + requireResponseBudget(response); + return response; + } + + private static void requireRequestBudget( + SettleOriginalStartSessionActivationProtectionRequest request) { + if (request.getSerializedSize() <= 0 || request.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) { + throw invalid("Activation settlement request exceeds its wire budget"); + } + } + + private static void requireResponseBudget( + SettleOriginalStartSessionActivationProtectionResponse response) { + if (response.getSerializedSize() <= 0 + || response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || response.getTerminalEvidenceCanonicalBytesCount() != 1 + || response.getTerminalEvidenceCanonicalBytes(0).isEmpty() + || response.getTerminalEvidenceCanonicalBytes(0).size() + > WorldOriginalStartSessionActivationTerminalEvidence.MAX_CANONICAL_BYTES) { + throw invalid("Complete World terminal receipt is missing or exceeds its wire budget"); + } + } + + private static void requireClosed(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid("Activation settlement " + label + " contains unsupported fields"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static long canonicalPositiveLong(String text) { + if (text == null || !POSITIVE_DECIMAL.matcher(text).matches()) { + throw invalid("Account protection fence must be positive canonical decimal text"); + } + try { + long value = Long.parseLong(text); + if (value <= 0L || !Long.toString(value).equals(text)) { + throw invalid("Account protection fence must fit a positive signed long"); + } + return value; + } catch (NumberFormatException malformed) { + throw invalid("Account protection fence must fit a positive signed long", malformed); + } + } + + private static Instant canonicalInstant(String text) { + try { + Instant value = Instant.parse(text); + if (value.getNano() % 1_000 != 0 || !UTC_MICROS.format(value).equals(text)) { + throw invalid("Account settlement timestamp must be exact UTC microseconds"); + } + return value; + } catch (RuntimeException malformed) { + throw invalid("Account settlement timestamp must be exact UTC microseconds", malformed); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException("Original StartSession activation settlement " + message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException( + "Original StartSession activation settlement " + message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementInput.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementInput.java new file mode 100644 index 0000000000..8aeb7df8e8 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementInput.java @@ -0,0 +1,32 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Lookup-only selector for exact historical settlement of one Account activation protection. */ +public record AccountStartSessionActivationProtectionSettlementInput( + String targetNamespace, + UUID settlementRequestId, + UUID accountProtectionId, + long accountProtectionFence) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public AccountStartSessionActivationProtectionSettlementInput { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Account target namespace required"); + } + requireNonNil(settlementRequestId, "Settlement request correlation ID"); + requireNonNil(accountProtectionId, "Account protection ID"); + if (accountProtectionFence <= 0L) { + throw new IllegalArgumentException("Account protection fence must be positive"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label + " required"); + 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/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java index ac669858e2..c038a6b8aa 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java @@ -250,8 +250,7 @@ private static byte[] encode( } } - private static List canonicalSourceVector( - List sourceEvidenceVector) { + static List canonicalSourceVector(List sourceEvidenceVector) { Objects.requireNonNull(sourceEvidenceVector, "sourceEvidenceVector is required"); if (sourceEvidenceVector.isEmpty() || sourceEvidenceVector.size() > MAX_SOURCE_EVIDENCE_COUNT) { throw invalid("sourceEvidenceVector is empty or exceeds its item limit"); @@ -279,7 +278,7 @@ private static List canonicalSourceVector( return List.copyOf(sources); } - private static void requireCaptureReferenceBinding( + static void requireCaptureReferenceBinding( byte[] exactReferenceBytes, StartSessionPostAuthorizationExecutionTuple tuple) { try { String json = strictUtf8(exactReferenceBytes); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClient.java new file mode 100644 index 0000000000..ae50ffe8ae --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClient.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.common.account.startsession; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountStartSessionActivationProtectionAcquisitionServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client pinned to the same-namespace Account SPIFFE peer. */ +public final class GrpcAccountStartSessionActivationProtectionAcquisitionClient + extends AbstractReloadingBlockingGrpcClient< + AccountStartSessionActivationProtectionAcquisitionServiceGrpc + .AccountStartSessionActivationProtectionAcquisitionServiceBlockingStub> + implements AccountStartSessionActivationProtectionAcquisitionClient { + private static final long CALL_DEADLINE_SECONDS = 60L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcAccountStartSessionActivationProtectionAcquisitionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcAccountStartSessionActivationProtectionAcquisitionClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes this explicit dependency only when its owning World service starts it. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account activation protection client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account activation protection client has no gRPC stub"); + } + initialized = true; + } + + @Override + public AccountStartSessionActivationProtectionEvidence acquire( + AccountStartSessionActivationProtectionAcquisitionInput input) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account activation protection acquisition requires no ambient owner transaction"); + } + var currentStub = requireStub(); + Objects.requireNonNull(input, "activation protection acquisition input is required"); + input.requireTargetNamespace(workloadNamespace); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .acquireOriginalStartSessionActivationProtection( + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toRequest( + input, workloadNamespace)); + try { + return AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromResponse( + input, workloadNamespace, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid original StartSession activation protection evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountStartSessionActivationProtectionAcquisitionServiceGrpc + .AccountStartSessionActivationProtectionAcquisitionServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountStartSessionActivationProtectionAcquisitionServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountStartSessionActivationProtectionAcquisitionServiceGrpc + .AccountStartSessionActivationProtectionAcquisitionServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account activation protection client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Account activation protection requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account activation protection requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account activation protection requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account activation protection " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account activation protection " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClient.java new file mode 100644 index 0000000000..15efced355 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClient.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.common.account.startsession; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountStartSessionActivationProtectionSettlementServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client pinned to Account in the configured namespace. */ +public final class GrpcAccountStartSessionActivationProtectionSettlementClient + extends AbstractReloadingBlockingGrpcClient< + AccountStartSessionActivationProtectionSettlementServiceGrpc + .AccountStartSessionActivationProtectionSettlementServiceBlockingStub> + implements AccountStartSessionActivationProtectionSettlementClient { + private static final long CALL_DEADLINE_SECONDS = 180L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcAccountStartSessionActivationProtectionSettlementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcAccountStartSessionActivationProtectionSettlementClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "World workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes this explicit dependency only when its owning World service starts it. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account activation settlement client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account activation settlement client has no gRPC stub"); + } + initialized = true; + } + + @Override + public AccountStartSessionActivationProtectionSettlementEvidence settle( + AccountStartSessionActivationProtectionSettlementInput input) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account activation settlement requires no ambient World transaction"); + } + Objects.requireNonNull(input, "activation settlement input required"); + if (!workloadNamespace.equals(input.targetNamespace())) { + throw new IllegalArgumentException("Account activation settlement target namespace differs"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .settleOriginalStartSessionActivationProtection( + AccountStartSessionActivationProtectionSettlementGrpcCodec.toRequest(input)); + try { + return AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid original StartSession activation settlement evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountStartSessionActivationProtectionSettlementServiceGrpc + .AccountStartSessionActivationProtectionSettlementServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountStartSessionActivationProtectionSettlementServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + AccountStartSessionActivationProtectionSettlementGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountStartSessionActivationProtectionSettlementServiceGrpc + .AccountStartSessionActivationProtectionSettlementServiceBlockingStub + requireStub() { + var current = stub(); + if (closed || !initialized || current == null) { + throw new IllegalStateException( + "Account activation settlement client is not initialized and available"); + } + return current; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Account activation settlement requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account activation settlement requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account activation settlement requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account activation settlement " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account activation settlement " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java new file mode 100644 index 0000000000..001968e0cd --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjection.java @@ -0,0 +1,614 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AuthoredInitialActorCore; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed, public-field projection of one retained authored initial actor core source binding. + * + *

This value carries source identity and content needed by a qualified owner read. It does not + * carry the private publication operation, source capture, terminal, selected commit bytes, or + * private target keys. Its digest is integrity metadata, not authentication of its producer. + */ +public final class AuthoredInitialActorCoreProjection { + public static final String SCHEMA = "game-design-authored-initial-actor-core-projection/v1"; + public static final int MAX_BYTES = 1_048_576; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern REVISION_ORDER = Pattern.compile("0|[1-9][0-9]*"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final UUID bindingId; + private final String bindingDigest; + private final UUID canonicalTenantId; + private final UUID canonicalVersionId; + private final UUID worldSourceOperationId; + private final String worldSourceEvidenceDigest; + private final String worldSlug; + private final String publicationWorkflowId; + private final UUID selectedCommitId; + private final String selectedCommitDigest; + private final Policy policy; + private final AuthoredCore core; + private final Descriptor descriptor; + private final RuleDefinition disposition; + private final RuleDefinition safeFeedback; + private final byte[] canonicalBytes; + private final String digest; + + private AuthoredInitialActorCoreProjection( + UUID bindingId, + String bindingDigest, + UUID canonicalTenantId, + UUID canonicalVersionId, + UUID worldSourceOperationId, + String worldSourceEvidenceDigest, + String worldSlug, + String publicationWorkflowId, + UUID selectedCommitId, + String selectedCommitDigest, + Policy policy, + AuthoredCore core, + Descriptor descriptor, + RuleDefinition disposition, + RuleDefinition safeFeedback) { + this.bindingId = nonNil(bindingId, "bindingId"); + this.bindingDigest = requireDigest(bindingDigest, "bindingDigest"); + this.canonicalTenantId = nonNil(canonicalTenantId, "canonicalTenantId"); + this.canonicalVersionId = nonNil(canonicalVersionId, "canonicalVersionId"); + this.worldSourceOperationId = nonNil(worldSourceOperationId, "worldSourceOperationId"); + this.worldSourceEvidenceDigest = + requireDigest(worldSourceEvidenceDigest, "worldSourceEvidenceDigest"); + if (!RealmEntryPolicy.isCanonicalSlug(worldSlug)) { + throw invalid("Canonical worldSlug required"); + } + this.worldSlug = worldSlug; + this.publicationWorkflowId = boundedText(publicationWorkflowId, 256, "publicationWorkflowId"); + this.selectedCommitId = nonNil(selectedCommitId, "selectedCommitId"); + this.selectedCommitDigest = requireDigest(selectedCommitDigest, "selectedCommitDigest"); + this.policy = Objects.requireNonNull(policy, "policy"); + this.core = Objects.requireNonNull(core, "core"); + this.descriptor = Objects.requireNonNull(descriptor, "descriptor"); + this.disposition = Objects.requireNonNull(disposition, "disposition"); + this.safeFeedback = Objects.requireNonNull(safeFeedback, "safeFeedback"); + requireCrossLinks(); + this.canonicalBytes = canonicalJson().getBytes(StandardCharsets.UTF_8); + if (canonicalBytes.length > MAX_BYTES) { + throw invalid("Projection exceeds its 1 MiB bound"); + } + this.digest = CommandSource.sha256(canonicalBytes); + } + + /** + * Builds the projection only from a fully validated private source binding. The owner supplies + * its retained nonzero binding ID; this method does not allocate or authenticate that identity. + */ + public static AuthoredInitialActorCoreProjection fromValidatedBinding( + UUID bindingId, AuthoredInitialActorCoreSourceBinding binding) { + Objects.requireNonNull(binding, "validated source binding is required"); + var selectedCommit = binding.selectedCommit(); + var target = selectedCommit.target(); + var policySource = binding.policySource(); + var policyJson = policySource.policy().canonicalJson(); + var descriptorValue = policySource.policy().creationDescriptor(); + return new AuthoredInitialActorCoreProjection( + bindingId, + binding.digest(), + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.worldSourceOperationId(), + binding.worldSourceEvidenceDigest(), + binding.expectedWorldSlug(), + binding.publicationWorkflowId(), + selectedCommit.commitId(), + selectedCommit.digest(), + new Policy( + policySource.commitId(), + policySource.revisionId(), + policySource.logicalRevisionId(), + policyJson, + CommandSource.sha256(policyJson.getBytes(StandardCharsets.UTF_8))), + new AuthoredCore(binding.core().canonicalJson()), + new Descriptor(descriptorValue.canonicalJson(), descriptorValue.digest()), + ruleDefinition(binding.dispositionSource()), + ruleDefinition(binding.safeFeedbackSource())); + } + + /** Decodes a closed canonical projection and verifies its exact public-content digest. */ + public static AuthoredInitialActorCoreProjection fromStored( + byte[] storedBytes, String expectedDigest) { + if (storedBytes == null || storedBytes.length == 0 || storedBytes.length > MAX_BYTES) { + throw invalid("Complete bounded projection bytes required"); + } + if (expectedDigest == null + || !SHA256.matcher(expectedDigest).matches() + || !CommandSource.sha256(storedBytes).equals(expectedDigest)) { + throw invalid("Projection digest differs"); + } + + final String storedJson = strictUtf8(storedBytes); + final JsonNode root; + try { + root = JSON.readTree(storedJson); + } catch (RuntimeException malformed) { + throw invalid("Projection must be valid unambiguous JSON", malformed); + } + if (root == null || !root.isObject()) { + throw invalid("Projection must be an object"); + } + byte[] canonical = canonicalJsonBytes(storedJson); + if (!Arrays.equals(canonical, storedBytes)) { + throw invalid("Projection JSON is not RFC 8785 canonical"); + } + fields( + root, + "schema", + "bindingId", + "bindingDigest", + "canonicalTenantId", + "canonicalVersionId", + "worldSourceOperationId", + "worldSourceEvidenceDigest", + "worldSlug", + "publicationWorkflowId", + "selectedCommitId", + "selectedCommitDigest", + "policy", + "core", + "descriptor", + "disposition", + "safeFeedback"); + if (!SCHEMA.equals(text(root, "schema"))) { + throw invalid("Unsupported projection schema"); + } + var value = + new AuthoredInitialActorCoreProjection( + uuid(root, "bindingId"), + text(root, "bindingDigest"), + uuid(root, "canonicalTenantId"), + uuid(root, "canonicalVersionId"), + uuid(root, "worldSourceOperationId"), + text(root, "worldSourceEvidenceDigest"), + text(root, "worldSlug"), + text(root, "publicationWorkflowId"), + uuid(root, "selectedCommitId"), + text(root, "selectedCommitDigest"), + policy(root.get("policy")), + core(root.get("core")), + descriptor(root.get("descriptor")), + rule(root.get("disposition")), + rule(root.get("safeFeedback"))); + if (!Arrays.equals(value.canonicalBytes, storedBytes) || !value.digest.equals(expectedDigest)) { + throw invalid("Projection changed during canonical reconstruction"); + } + return value; + } + + private void requireCrossLinks() { + RealmEntryPolicy parsedPolicy = parsePolicy(policy.canonicalJson()); + if (policy.commitId().equals(NIL_UUID) + || !worldSlug.equals(parsedPolicy.worldSlug()) + || parsedPolicy.schemaVersion() + != RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION + || parsedPolicy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PLAYER_CREATED + || !core.displayName().equals(parsedPolicy.initialActorCore().displayName()) + || !core.dispositionKey().equals(parsedPolicy.initialActorCore().dispositionKey()) + || !core.canonicalJson().equals(parsedPolicy.initialActorCore().canonicalJson()) + || !descriptor.canonicalJson().equals(parsedPolicy.creationDescriptor().canonicalJson()) + || !policy + .contentDigest() + .equals( + CommandSource.sha256(policy.canonicalJson().getBytes(StandardCharsets.UTF_8)))) { + throw invalid("Projection source, policy, core, or descriptor bindings differ"); + } + var dispositionValue = definition(Family.DISPOSITIONS, disposition); + var feedbackValue = definition(Family.FEEDBACK, safeFeedback); + if (!(dispositionValue instanceof GameplayRuleManifest.Disposition selectedDisposition) + || !(feedbackValue instanceof GameplayRuleManifest.Feedback selectedFeedback) + || !selectedDisposition.dispositionKey().equals(core.dispositionKey()) + || !selectedDisposition.safeFeedbackKey().equals(selectedFeedback.feedbackKey())) { + throw invalid("Disposition and mandatory feedback source bindings differ"); + } + var parsedDescriptor = PlayerCreationDescriptor.parse(descriptor.canonicalJson()); + if (!descriptor.digest().equals(parsedDescriptor.digest())) { + throw invalid("Descriptor content digest differs"); + } + } + + private String canonicalJson() { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("bindingId", bindingId.toString()); + value.put("bindingDigest", bindingDigest); + value.put("canonicalTenantId", canonicalTenantId.toString()); + value.put("canonicalVersionId", canonicalVersionId.toString()); + value.put("worldSourceOperationId", worldSourceOperationId.toString()); + value.put("worldSourceEvidenceDigest", worldSourceEvidenceDigest); + value.put("worldSlug", worldSlug); + value.put("publicationWorkflowId", publicationWorkflowId); + value.put("selectedCommitId", selectedCommitId.toString()); + value.put("selectedCommitDigest", selectedCommitDigest); + value.put("policy", policy.object()); + value.put("core", core.object()); + value.put("descriptor", descriptor.object()); + value.put("disposition", disposition.object()); + value.put("safeFeedback", safeFeedback.object()); + return CommandSource.canonical(value); + } + + private static RuleDefinition ruleDefinition(GameplayRuleSource.Entry source) { + String definitionJson = GameplayRuleManifest.canonical(source.definition()); + return new RuleDefinition( + source.definition().key(), + definitionJson, + CommandSource.sha256(definitionJson.getBytes(StandardCharsets.UTF_8)), + source.sourceBinding().commitId(), + source.sourceBinding().digest(), + source.revisionId(), + source.revisionOrder()); + } + + private static Policy policy(JsonNode node) { + fields( + node, + "commitId", + "revisionId", + "logicalRevisionId", + "canonicalPolicyJson", + "contentDigest"); + return new Policy( + uuid(node, "commitId"), + uuid(node, "revisionId"), + text(node, "logicalRevisionId"), + text(node, "canonicalPolicyJson"), + text(node, "contentDigest")); + } + + private static AuthoredCore core(JsonNode node) { + fields(node, "canonicalJson"); + return new AuthoredCore(text(node, "canonicalJson")); + } + + private static Descriptor descriptor(JsonNode node) { + fields(node, "canonicalJson", "digest"); + return new Descriptor(text(node, "canonicalJson"), text(node, "digest")); + } + + private static RuleDefinition rule(JsonNode node) { + fields( + node, + "key", + "definitionJson", + "definitionDigest", + "sourceCommitId", + "sourceCommitDigest", + "revisionId", + "revisionOrder"); + return new RuleDefinition( + text(node, "key"), + text(node, "definitionJson"), + text(node, "definitionDigest"), + uuid(node, "sourceCommitId"), + text(node, "sourceCommitDigest"), + uuid(node, "revisionId"), + text(node, "revisionOrder")); + } + + private static GameplayRuleManifest.Definition definition(Family family, RuleDefinition rule) { + JsonNode parsed; + try { + parsed = JSON.readTree(rule.definitionJson()); + } catch (RuntimeException malformed) { + throw invalid("Rule definition JSON is invalid", malformed); + } + if (parsed == null || !parsed.isObject()) { + throw invalid("Rule definition must be an object"); + } + byte[] canonical = canonicalJsonBytes(rule.definitionJson()); + if (!Arrays.equals(canonical, rule.definitionJson().getBytes(StandardCharsets.UTF_8)) + || !GameplayRuleManifest.canonical(parsed).equals(rule.definitionJson())) { + throw invalid("Rule definition is not canonical"); + } + var value = GameplayRuleManifest.definition(family, rule.definitionJson()); + if (!value.key().equals(rule.key()) + || !rule.definitionDigest().equals(CommandSource.sha256(canonical))) { + throw invalid("Rule definition digest or key differs"); + } + return value; + } + + private static RealmEntryPolicy parsePolicy(String json) { + try { + JsonNode parsed = JSON.readTree(json); + if (parsed == null || !parsed.isObject()) { + throw invalid("Policy must be an object"); + } + if (!Arrays.equals( + Rfc8785CanonicalJson.canonicalizeUtf8(json), json.getBytes(StandardCharsets.UTF_8))) { + throw invalid("Policy JSON is not canonical"); + } + return RealmEntryPolicy.parse(json, JSON); + } catch (IOException | RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException invalid) { + throw invalid; + } + throw invalid("Policy JSON is invalid", malformed); + } + } + + private static void fields(JsonNode node, String... names) { + if (node == null || !node.isObject() || node.size() != names.length) { + throw invalid("Closed projection fields required"); + } + for (String name : names) { + if (!node.has(name)) { + throw invalid("Missing projection field: " + name); + } + } + } + + private static String text(JsonNode node, String name) { + JsonNode value = node.get(name); + if (value == null || !value.isTextual()) { + throw invalid("Text projection field required: " + name); + } + return value.textValue(); + } + + private static UUID uuid(JsonNode node, String name) { + String value = text(node, name); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw invalid("Canonical nonzero UUID required: " + name); + } + return parsed; + } catch (IllegalArgumentException malformed) { + if (malformed.getMessage() != null + && malformed.getMessage().startsWith("Canonical nonzero UUID")) { + throw malformed; + } + throw invalid("Canonical nonzero UUID required: " + name, malformed); + } + } + + private static UUID nonNil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw invalid("Canonical nonzero UUID required: " + name); + } + return value; + } + + private static String requireDigest(String value, String name) { + if (value == null || !SHA256.matcher(value).matches()) { + throw invalid("Canonical SHA-256 digest required: " + name); + } + return value; + } + + private static String boundedText(String value, int maxLength, String name) { + if (value == null + || value.isBlank() + || value.length() > maxLength + || !StandardCharsets.UTF_8.newEncoder().canEncode(value)) { + throw invalid("Bounded nonempty text required: " + name); + } + return value; + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString(); + } catch (java.nio.charset.CharacterCodingException malformed) { + throw invalid("Projection bytes are not valid UTF-8", malformed); + } + } + + private static byte[] canonicalJsonBytes(String json) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(json); + } catch (IOException malformed) { + throw invalid("Projection content is not valid canonical JSON", malformed); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } + + public UUID bindingId() { + return bindingId; + } + + public String bindingDigest() { + return bindingDigest; + } + + public UUID canonicalTenantId() { + return canonicalTenantId; + } + + public UUID canonicalVersionId() { + return canonicalVersionId; + } + + public UUID worldSourceOperationId() { + return worldSourceOperationId; + } + + public String worldSourceEvidenceDigest() { + return worldSourceEvidenceDigest; + } + + public String worldSlug() { + return worldSlug; + } + + public String publicationWorkflowId() { + return publicationWorkflowId; + } + + public UUID selectedCommitId() { + return selectedCommitId; + } + + public String selectedCommitDigest() { + return selectedCommitDigest; + } + + public Policy policy() { + return policy; + } + + public AuthoredCore core() { + return core; + } + + public Descriptor descriptor() { + return descriptor; + } + + public RuleDefinition disposition() { + return disposition; + } + + public RuleDefinition safeFeedback() { + return safeFeedback; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + public record Policy( + UUID commitId, + UUID revisionId, + String logicalRevisionId, + String canonicalJson, + String contentDigest) { + public Policy { + nonNil(commitId, "policy commitId"); + nonNil(revisionId, "policy revisionId"); + logicalRevisionId = boundedText(logicalRevisionId, 128, "policy logicalRevisionId"); + Objects.requireNonNull(canonicalJson, "canonical policy JSON"); + requireDigest(contentDigest, "policy contentDigest"); + } + + private Map object() { + return Map.of( + "commitId", commitId.toString(), + "revisionId", revisionId.toString(), + "logicalRevisionId", logicalRevisionId, + "canonicalPolicyJson", canonicalJson, + "contentDigest", contentDigest); + } + } + + public record AuthoredCore(String canonicalJson) { + public AuthoredCore { + Objects.requireNonNull(canonicalJson, "canonical authored core JSON"); + parseCore(canonicalJson); + } + + public String displayName() { + return parseCore(canonicalJson).displayName(); + } + + public String dispositionKey() { + return parseCore(canonicalJson).dispositionKey(); + } + + private Map object() { + return Map.of("canonicalJson", canonicalJson); + } + } + + private static AuthoredInitialActorCore parseCore(String json) { + try { + JsonNode node = JSON.readTree(json); + fields(node, "displayName", "dispositionKey"); + String canonical = GameplayRuleManifest.canonical(node); + if (!canonical.equals(json)) { + throw invalid("Authored core JSON is not canonical"); + } + return new AuthoredInitialActorCore(text(node, "displayName"), text(node, "dispositionKey")); + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException invalid) { + throw invalid; + } + throw invalid("Authored core JSON is invalid", malformed); + } + } + + public record Descriptor(String canonicalJson, String digest) { + public Descriptor { + Objects.requireNonNull(canonicalJson, "canonical descriptor JSON"); + requireDigest(digest, "descriptor digest"); + } + + private Map object() { + return Map.of("canonicalJson", canonicalJson, "digest", digest); + } + } + + public record RuleDefinition( + String key, + String definitionJson, + String definitionDigest, + UUID sourceCommitId, + String sourceCommitDigest, + UUID revisionId, + String revisionOrder) { + public RuleDefinition { + boundedText(key, 128, "rule key"); + Objects.requireNonNull(definitionJson, "canonical definition JSON"); + requireDigest(definitionDigest, "definitionDigest"); + nonNil(sourceCommitId, "rule sourceCommitId"); + requireDigest(sourceCommitDigest, "rule sourceCommitDigest"); + nonNil(revisionId, "rule revisionId"); + if (revisionOrder == null || !REVISION_ORDER.matcher(revisionOrder).matches()) { + throw invalid("Canonical rule revisionOrder required"); + } + } + + private Map object() { + return Map.of( + "key", key, + "definitionJson", definitionJson, + "definitionDigest", definitionDigest, + "sourceCommitId", sourceCommitId.toString(), + "sourceCommitDigest", sourceCommitDigest, + "revisionId", revisionId.toString(), + "revisionOrder", revisionOrder); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClient.java new file mode 100644 index 0000000000..0755a700c9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClient.java @@ -0,0 +1,10 @@ +package net.firedevops.firemud.common.gamedesign; + +/** Explicit client for the standalone authenticated Game Design authored-core read. */ +public interface AuthoredInitialActorCoreReadClient extends AutoCloseable { + AuthoredInitialActorCoreReadEvidence.ReadResult read( + AuthoredInitialActorCoreReadEvidence.ReadRequest request); + + @Override + void close() throws Exception; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidence.java new file mode 100644 index 0000000000..a631903c9f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidence.java @@ -0,0 +1,163 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Message; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Closed public integrity value for an authenticated authored-core source read. */ +public final class AuthoredInitialActorCoreReadEvidence { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_RESULT_BYTES = 8 * 1024 * 1024; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private AuthoredInitialActorCoreReadEvidence() {} + + /** The input is the exact already-pinned original request, never an initial selector. */ + public record ReadRequest(Request associationRequest) { + public ReadRequest { + Objects.requireNonNull(associationRequest, "associationRequest"); + if (!(associationRequest.selection() instanceof ExactReplay)) { + throw new IllegalArgumentException("Exact pinned association replay is required"); + } + } + } + + /** + * Complete public projection with the exact immutable request and owner evidence. Construction + * validates canonical integrity and cross-correlation only; this value and its digest do not + * authenticate the producer. + */ + public static final class ReadResult { + private final Request request; + private final Result associationRead; + private final AuthoredWorldLaunchDescriptorEvidence descriptor; + private final List projections; + private final byte[] canonicalBytes; + private final String digest; + + public ReadResult( + Request request, + Result associationRead, + AuthoredWorldLaunchDescriptorEvidence descriptor, + List projections) { + this.request = Objects.requireNonNull(request, "request"); + this.associationRead = Objects.requireNonNull(associationRead, "associationRead"); + this.descriptor = Objects.requireNonNull(descriptor, "descriptor"); + this.projections = List.copyOf(Objects.requireNonNull(projections, "projections")); + requirePublicCorrelation(); + canonicalBytes = encodeCanonical(); + if (canonicalBytes.length == 0 || canonicalBytes.length > MAX_RESULT_BYTES) { + throw new IllegalArgumentException("Authored-core read result exceeds its closed bound"); + } + digest = sha256(canonicalBytes); + } + + public Request request() { + return request; + } + + public Result associationRead() { + return associationRead; + } + + public AuthoredWorldLaunchDescriptorEvidence descriptor() { + return descriptor; + } + + public List projections() { + return projections; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + private void requirePublicCorrelation() { + if (!request.equals(associationRead.request()) + || !(request.selection() instanceof ExactReplay replay) + || !replay.canonicalVersionId().equals(associationRead.association().canonicalVersionId()) + || !replay.selectedCommitId().equals(associationRead.association().selectedCommitId()) + || !replay.publishWorkflowId().equals(associationRead.association().publishWorkflowId()) + || !replay + .associationDigest() + .equals(associationRead.association().associationDigest())) { + throw new IllegalArgumentException( + "Association result differs from exact core-read request"); + } + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + request, associationRead, descriptor); + Set bindingIds = new java.util.HashSet<>(); + var association = associationRead.association(); + for (AuthoredInitialActorCoreProjection projection : projections) { + Objects.requireNonNull(projection, "projection"); + if (!bindingIds.add(projection.bindingId()) + || !projection.worldSourceOperationId().equals(association.sourceOperationId()) + || !projection.worldSourceEvidenceDigest().equals(association.sourceEvidenceDigest()) + || !projection.worldSlug().equals(association.worldSlug()) + || !projection.publicationWorkflowId().equals(association.publishWorkflowId()) + || !projection.canonicalTenantId().equals(association.canonicalTenantId()) + || !projection.canonicalVersionId().equals(association.canonicalVersionId()) + || !projection.selectedCommitId().equals(association.selectedCommitId())) { + throw new IllegalArgumentException( + "Projection differs from exact association or descriptor"); + } + } + } + + private byte[] encodeCanonical() { + Map value = new LinkedHashMap<>(); + value.put("schema", "game-design-authored-initial-actor-core-read/v1"); + value.put("request", base64(StartSessionTemplateAssociationReadGrpcCodec.toRequest(request))); + value.put( + "associationRead", + base64(StartSessionTemplateAssociationReadGrpcCodec.toResponse(associationRead))); + value.put( + "launchDescriptor", + base64(AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptor))); + List> ordered = new ArrayList<>(projections.size()); + for (AuthoredInitialActorCoreProjection projection : projections) { + Map item = new LinkedHashMap<>(); + item.put( + "canonicalProjection", Base64.getEncoder().encodeToString(projection.canonicalBytes())); + item.put("digest", projection.digest()); + ordered.add(item); + } + value.put("projections", ordered); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception invalid) { + throw new IllegalArgumentException("Cannot encode canonical authored-core result", invalid); + } + } + + private static String base64(Message message) { + return Base64.getEncoder().encodeToString(message.toByteArray()); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodec.java new file mode 100644 index 0000000000..49d34e8118 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodec.java @@ -0,0 +1,137 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.security.MessageDigest; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreProjection; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreRequest; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; + +/** Closed mapping for the authenticated, ordered authored initial actor-core projection. */ +public final class AuthoredInitialActorCoreReadGrpcCodec { + public static final int MAX_RESPONSE_WIRE_BYTES = 16 * 1024 * 1024; + + private AuthoredInitialActorCoreReadGrpcCodec() {} + + public static ReadAuthoredInitialActorCoreRequest toRequest(ReadRequest request) { + Objects.requireNonNull(request, "request"); + return ReadAuthoredInitialActorCoreRequest.newBuilder() + .setAssociationRequest( + StartSessionTemplateAssociationReadGrpcCodec.toRequest(request.associationRequest())) + .build(); + } + + public static ReadRequest fromRequest(ReadAuthoredInitialActorCoreRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "ReadAuthoredInitialActorCoreRequest"); + if (!request.hasAssociationRequest()) { + throw new IllegalArgumentException("Exact association replay request is required"); + } + return new ReadRequest( + StartSessionTemplateAssociationReadGrpcCodec.fromRequest(request.getAssociationRequest())); + } + + public static ReadAuthoredInitialActorCoreResponse toResponse(ReadResult result) { + Objects.requireNonNull(result, "result"); + ReadAuthoredInitialActorCoreRequest request = toRequest(new ReadRequest(result.request())); + var associationRead = + StartSessionTemplateAssociationReadGrpcCodec.toResponse(result.associationRead()); + var descriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(result.descriptor()); + var builder = + ReadAuthoredInitialActorCoreResponse.newBuilder() + .setSchemaVersion(AuthoredInitialActorCoreReadEvidence.SCHEMA_VERSION) + .setRequest(request.getAssociationRequest()) + .setAssociationRead(associationRead) + .setLaunchDescriptor(descriptor) + .setCanonicalResultBytes( + com.google.protobuf.ByteString.copyFrom(result.canonicalBytes())) + .setResultDigest(result.digest()); + for (AuthoredInitialActorCoreProjection projection : result.projections()) { + builder.addProjections( + ReadAuthoredInitialActorCoreProjection.newBuilder() + .setCanonicalProjectionBytes( + com.google.protobuf.ByteString.copyFrom(projection.canonicalBytes())) + .setProjectionDigest(projection.digest())); + } + ReadAuthoredInitialActorCoreResponse response = builder.build(); + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) { + throw new IllegalArgumentException("Authored-core response exceeds its bounded wire size"); + } + fromResponse(result.request(), response); + return response; + } + + public static ReadResult fromResponse( + Request expectedRequest, ReadAuthoredInitialActorCoreResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ReadAuthoredInitialActorCoreResponse"); + if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || response.getSchemaVersion() != AuthoredInitialActorCoreReadEvidence.SCHEMA_VERSION + || !response.hasRequest() + || !response.hasAssociationRead() + || !response.hasLaunchDescriptor() + || response.getCanonicalResultBytes().isEmpty()) { + throw new IllegalArgumentException("Complete bounded authored-core read response required"); + } + Request echoed = + StartSessionTemplateAssociationReadGrpcCodec.fromRequest(response.getRequest()); + if (!expectedRequest.equals(echoed)) { + throw new IllegalArgumentException("Authored-core read changed the exact request echo"); + } + var associationRead = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + expectedRequest, response.getAssociationRead()); + var descriptorEnvelope = + ResolveStartSessionLaunchDescriptorResponse.newBuilder() + .setSchemaVersion(StartSessionLaunchDescriptorGrpcCodec.RESPONSE_SCHEMA_VERSION) + .setAssociationRead(response.getAssociationRead()) + .setLaunchDescriptor(response.getLaunchDescriptor()) + .build(); + var resolved = + StartSessionLaunchDescriptorGrpcCodec.fromResponse(expectedRequest, descriptorEnvelope); + var descriptor = + ((StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome) resolved.outcome()).descriptor(); + List projections = + response.getProjectionsList().stream() + .map( + projection -> + AuthoredInitialActorCoreProjection.fromStored( + projection.getCanonicalProjectionBytes().toByteArray(), + projection.getProjectionDigest())) + .toList(); + ReadResult result = new ReadResult(expectedRequest, associationRead, descriptor, projections); + byte[] canonical = response.getCanonicalResultBytes().toByteArray(); + if (canonical.length > AuthoredInitialActorCoreReadEvidence.MAX_RESULT_BYTES + || !MessageDigest.isEqual(canonical, result.canonicalBytes()) + || !result.digest().equals(response.getResultDigest())) { + throw new IllegalArgumentException( + "Authored-core result digest or canonical complete content differs"); + } + return result; + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (Map.Entry field : message.getAllFields().entrySet()) { + if (field.getKey().getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) continue; + if (field.getKey().isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + field.getKey().getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + field.getKey().getName()); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java index 3fe51441ba..3162346168 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java @@ -34,6 +34,8 @@ public final class AuthoredInitialActorCoreSourceBinding { private final GameplayRuleManifest gameplayManifest; private final Disposition disposition; private final Feedback safeFeedback; + private final GameplayRuleSource.Entry dispositionSource; + private final GameplayRuleSource.Entry safeFeedbackSource; private final byte[] canonicalBytes; private final String digest; @@ -63,6 +65,8 @@ private AuthoredInitialActorCoreSourceBinding( this.gameplayManifest = Objects.requireNonNull(gameplayManifest); this.disposition = Objects.requireNonNull(disposition); this.safeFeedback = Objects.requireNonNull(safeFeedback); + this.dispositionSource = Objects.requireNonNull(dispositionEntry); + this.safeFeedbackSource = Objects.requireNonNull(feedbackEntry); var target = selectedCommit.target(); var policy = policySource.policy(); @@ -457,6 +461,16 @@ public Feedback safeFeedback() { return safeFeedback; } + /** Exact authored source entry for the selected disposition, including its original revision. */ + public GameplayRuleSource.Entry dispositionSource() { + return dispositionSource; + } + + /** Exact authored source entry for the mandatory feedback, including its original revision. */ + public GameplayRuleSource.Entry safeFeedbackSource() { + return safeFeedbackSource; + } + public byte[] canonicalBytes() { return canonicalBytes.clone(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcAuthoredInitialActorCoreReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcAuthoredInitialActorCoreReadClient.java new file mode 100644 index 0000000000..443403c440 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GrpcAuthoredInitialActorCoreReadClient.java @@ -0,0 +1,146 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignAuthoredInitialActorCoreReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client pinned to the same-namespace Game Design workload. */ +public final class GrpcAuthoredInitialActorCoreReadClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignAuthoredInitialActorCoreReadServiceGrpc + .GameDesignAuthoredInitialActorCoreReadServiceBlockingStub> + implements AuthoredInitialActorCoreReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcAuthoredInitialActorCoreReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcAuthoredInitialActorCoreReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("Authored-core read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) throw new IllegalStateException("Authored-core read client has no stub"); + initialized = true; + } + + @Override + public AuthoredInitialActorCoreReadEvidence.ReadResult read( + AuthoredInitialActorCoreReadEvidence.ReadRequest request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Authored-core read requires no ambient transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.associationRequest().targetNamespace())) { + throw new IllegalArgumentException( + "Authored-core read namespace differs from client identity"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readAuthoredInitialActorCore(AuthoredInitialActorCoreReadGrpcCodec.toRequest(request)); + try { + return AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + request.associationRequest(), response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design returned invalid authored-core evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignAuthoredInitialActorCoreReadServiceGrpc + .GameDesignAuthoredInitialActorCoreReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expected = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignAuthoredInitialActorCoreReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(AuthoredInitialActorCoreReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expected)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expected)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignAuthoredInitialActorCoreReadServiceGrpc + .GameDesignAuthoredInitialActorCoreReadServiceBlockingStub + requireStub() { + var current = stub(); + if (closed || !initialized || current == null) { + throw new IllegalStateException("Authored-core read client is not initialized"); + } + return current; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties properties) { + if (properties == null || properties.isPlaintext()) { + throw new IllegalArgumentException("Authored-core reads require workload mTLS"); + } + requireReadableFile(properties.getCertChain(), "certificate chain"); + requireReadableFile(properties.getPrivateKey(), "private key"); + requireReadableFile(properties.getCaCert(), "CA certificate"); + return properties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.startsWith("classpath:")) { + throw new IllegalArgumentException("Authored-core reads require file-backed TLS material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Invalid file-backed " + label, invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException("Authored-core " + label + " must be a readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionLaunchReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionLaunchReadClient.java new file mode 100644 index 0000000000..0e5291f9a6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionLaunchReadClient.java @@ -0,0 +1,164 @@ +package net.firedevops.firemud.common.gamesession; + +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.gamesession.v1.OriginalStartSessionLaunchReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client pinned to the same-namespace Game Session SPIFFE peer. */ +public final class GrpcOriginalStartSessionLaunchReadClient + extends AbstractReloadingBlockingGrpcClient< + OriginalStartSessionLaunchReadServiceGrpc.OriginalStartSessionLaunchReadServiceBlockingStub> + implements OriginalStartSessionLaunchReadClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcOriginalStartSessionLaunchReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcOriginalStartSessionLaunchReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes this explicit dependency only when its owning service starts it. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Original StartSession launch read client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Original StartSession launch read client has no gRPC stub"); + } + initialized = true; + } + + @Override + public OriginalStartSessionLaunchReadEvidence.Result read( + OriginalStartSessionLaunchReadEvidence.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Original StartSession launch read requires no ambient owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.selector().targetNamespace())) { + throw new IllegalArgumentException( + "Original StartSession launch request must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readOriginalStartSessionLaunch( + OriginalStartSessionLaunchReadGrpcCodec.toRequest(request)); + try { + return OriginalStartSessionLaunchReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Session returned invalid original StartSession launch evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected OriginalStartSessionLaunchReadServiceGrpc + .OriginalStartSessionLaunchReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + return OriginalStartSessionLaunchReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(OriginalStartSessionLaunchReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private OriginalStartSessionLaunchReadServiceGrpc + .OriginalStartSessionLaunchReadServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Original StartSession launch read client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Original StartSession launch 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( + "Original StartSession launch reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Original StartSession launch reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Original StartSession launch " + label + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Original StartSession launch " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadClient.java new file mode 100644 index 0000000000..1c823d6773 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadClient.java @@ -0,0 +1,10 @@ +package net.firedevops.firemud.common.gamesession; + +/** + * Reads exact original Account StartSession launch and retained tuple evidence from Game Session. + */ +public interface OriginalStartSessionLaunchReadClient { + /** Reads one exact original launch without granting currentness or lifecycle authority. */ + OriginalStartSessionLaunchReadEvidence.Result read( + OriginalStartSessionLaunchReadEvidence.Request request); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadEvidence.java new file mode 100644 index 0000000000..87b9e0cf95 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadEvidence.java @@ -0,0 +1,363 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionLaunchRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionLaunchResponse; + +/** + * Closed exact request and owner readback for an original Account StartSession launch. + * + *

This carrier validates bytes and tuple-to-launch correlation only. It does not authenticate + * either owner, prove currentness, require a lifecycle state, or grant lifecycle/admission + * authority. + */ +public final class OriginalStartSessionLaunchReadEvidence { + public static final int SCHEMA_VERSION = 1; + public static final int MAX_REQUEST_BYTES = + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + 8 * 1_024; + public static final int MAX_RESULT_BYTES = 41 * 1024 * 1024; + + private static final UUID NORMALIZED_READ_REQUEST_ID = + UUID.fromString("00000000-0000-0000-0000-000000000001"); + + private OriginalStartSessionLaunchReadEvidence() {} + + /** Exact selector and complete original tuple presented to the Account-only Game Session API. */ + public static final class Request { + private final CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector; + private final byte[] originalPostAuthorizationTupleBytes; + private final byte[] canonicalBytes; + + public Request( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector, + byte[] originalPostAuthorizationTupleBytes) { + this.selector = Objects.requireNonNull(selector, "selector"); + this.originalPostAuthorizationTupleBytes = + boundedTuple(originalPostAuthorizationTupleBytes, "original post-authorization tuple"); + requireTupleSelectorCorrelation(this.selector, this.originalPostAuthorizationTupleBytes); + this.canonicalBytes = encodeRequest(this.selector, this.originalPostAuthorizationTupleBytes); + } + + /** Strictly decodes one complete bounded canonical request; decoding grants no authority. */ + public static Request decode(byte[] exactCanonicalBytes) { + byte[] stored = boundedRequest(exactCanonicalBytes); + try { + ReadOriginalStartSessionLaunchRequest wire = + ReadOriginalStartSessionLaunchRequest.parseFrom(stored); + requireNoUnknownFields(wire, "original StartSession launch read request"); + if (wire.getSchemaVersion() != SCHEMA_VERSION || !wire.hasSelector()) { + throw invalid("Original StartSession launch read request schema or selector is invalid"); + } + var selector = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromRequest(wire.getSelector()); + Request result = + new Request(selector, wire.getOriginalPostAuthorizationTupleBytes().toByteArray()); + if (!Arrays.equals(stored, result.canonicalBytes)) { + throw invalid("Original StartSession launch read request is not canonical"); + } + return result; + } catch (IllegalArgumentException expected) { + throw expected; + } catch (Exception malformed) { + throw invalid("Original StartSession launch read request is malformed"); + } + } + + public CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector() { + return selector; + } + + public byte[] originalPostAuthorizationTupleBytes() { + return originalPostAuthorizationTupleBytes.clone(); + } + + /** Full canonical bytes retain the transient owner read identifier. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** Stable operation bytes normalize only the selector's transient read identifier. */ + public byte[] operationIdentityBytes() { + return encodeRequest( + withReadRequestId(selector, normalizedReadRequestId(selector)), + originalPostAuthorizationTupleBytes); + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof Request that && Arrays.equals(canonicalBytes, that.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + } + + /** Exact Game Session owner result and the tuple bytes actually retained in its row. */ + public static final class Result { + private final Request request; + private final CanonicalGameInstanceLaunchAssociationReadEvidence.Result launch; + private final byte[] retainedOriginalPostAuthorizationTupleBytes; + private final byte[] canonicalBytes; + + public Result( + Request request, + CanonicalGameInstanceLaunchAssociationReadEvidence.Result launch, + byte[] retainedOriginalPostAuthorizationTupleBytes) { + this.request = Objects.requireNonNull(request, "request"); + this.launch = Objects.requireNonNull(launch, "launch"); + this.retainedOriginalPostAuthorizationTupleBytes = + boundedTuple( + retainedOriginalPostAuthorizationTupleBytes, + "retained original post-authorization tuple"); + if (!request.selector().equals(launch.request()) + || !Arrays.equals( + request.originalPostAuthorizationTupleBytes(), + this.retainedOriginalPostAuthorizationTupleBytes)) { + throw invalid("Game Session launch read does not echo the exact selector and tuple"); + } + requireTupleLaunchCorrelation(request.originalPostAuthorizationTupleBytes(), launch); + this.canonicalBytes = encodeResult(this, false); + } + + /** Strictly decodes one complete bounded result including the full launch readback. */ + public static Result decode(byte[] exactCanonicalBytes) { + byte[] stored = boundedResult(exactCanonicalBytes); + try { + ReadOriginalStartSessionLaunchResponse wire = + ReadOriginalStartSessionLaunchResponse.parseFrom(stored); + requireNoUnknownFields(wire, "original StartSession launch read response"); + if (wire.getSchemaVersion() != SCHEMA_VERSION || !wire.hasRequest() || !wire.hasLaunch()) { + throw invalid("Original StartSession launch read response schema or evidence is invalid"); + } + Request request = Request.decode(wire.getRequest().toByteArray()); + var launch = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + request.selector(), wire.getLaunch()); + Result result = + new Result( + request, + launch, + wire.getRetainedOriginalPostAuthorizationTupleBytes().toByteArray()); + if (!Arrays.equals(stored, result.canonicalBytes)) { + throw invalid("Original StartSession launch read result is not canonical"); + } + return result; + } catch (IllegalArgumentException expected) { + throw expected; + } catch (Exception malformed) { + throw invalid("Original StartSession launch read result is malformed"); + } + } + + public Request request() { + return request; + } + + public CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector() { + return request.selector(); + } + + public CanonicalGameInstanceLaunchAssociationReadEvidence.Result launch() { + return launch; + } + + public byte[] retainedOriginalPostAuthorizationTupleBytes() { + return retainedOriginalPostAuthorizationTupleBytes.clone(); + } + + /** Full canonical result retains both selector and owner-response read identifiers. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + /** Stable operation bytes normalize only the selector's transient read identifier. */ + public byte[] operationIdentityBytes() { + return encodeResult(this, true); + } + + @Override + public boolean equals(Object other) { + return this == other + || other instanceof Result that && Arrays.equals(canonicalBytes, that.canonicalBytes); + } + + @Override + public int hashCode() { + return Arrays.hashCode(canonicalBytes); + } + } + + private static byte[] encodeRequest( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector, byte[] tupleBytes) { + var message = + ReadOriginalStartSessionLaunchRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setSelector(CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toRequest(selector)) + .setOriginalPostAuthorizationTupleBytes( + com.google.protobuf.ByteString.copyFrom(tupleBytes)) + .build(); + if (message.getSerializedSize() > MAX_REQUEST_BYTES) { + throw invalid("Original StartSession launch read request exceeds its byte limit"); + } + return message.toByteArray(); + } + + private static byte[] encodeResult(Result result, boolean normalizeReadRequestId) { + var selector = result.request().selector(); + if (normalizeReadRequestId) { + selector = withReadRequestId(selector, normalizedReadRequestId(selector)); + } + var requestMessage = + ReadOriginalStartSessionLaunchRequest.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setSelector(CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toRequest(selector)) + .setOriginalPostAuthorizationTupleBytes( + com.google.protobuf.ByteString.copyFrom( + result.request().originalPostAuthorizationTupleBytes())) + .build(); + var launchMessage = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toResponse(result.launch()); + if (normalizeReadRequestId) { + launchMessage = + launchMessage.toBuilder().setReadRequestId(selector.readRequestId().toString()).build(); + } + var message = + ReadOriginalStartSessionLaunchResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setRequest(requestMessage) + .setLaunch(launchMessage) + .setRetainedOriginalPostAuthorizationTupleBytes( + com.google.protobuf.ByteString.copyFrom( + result.retainedOriginalPostAuthorizationTupleBytes())) + .build(); + if (message.getSerializedSize() > MAX_RESULT_BYTES) { + throw invalid("Original StartSession launch read result exceeds its byte limit"); + } + return message.toByteArray(); + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request withReadRequestId( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector, UUID readRequestId) { + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + readRequestId, + selector.targetNamespace(), + selector.canonicalTenantId(), + selector.worldSlug(), + selector.gameInstanceUuid(), + selector.controlPlaneRequestId(), + selector.launchDescriptorId(), + selector.expectedDescriptorRequestDigest(), + selector.expectedDescriptorResultDigest(), + selector.expectedReleaseAttestationEvidenceDigest()); + } + + private static UUID normalizedReadRequestId( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector) { + long suffix = 1L; + UUID normalized = NORMALIZED_READ_REQUEST_ID; + while (normalized.toString().equals(selector.controlPlaneRequestId())) { + normalized = new UUID(0L, ++suffix); + } + return normalized; + } + + private static void requireTupleSelectorCorrelation( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector, byte[] tupleBytes) { + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + var preAuthorization = tuple.preAuthorizationTuple(); + var action = preAuthorization.action(); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(preAuthorization.actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals(preAuthorization.targetOwner()) + || !tuple.controlPlaneRequestId().equals(selector.controlPlaneRequestId()) + || !action.scope().targetNamespace().equals(selector.targetNamespace()) + || !action.scope().tenantId().equals(selector.canonicalTenantId())) { + throw invalid("Original StartSession tuple differs from the exact launch selector"); + } + } + + private static void requireTupleLaunchCorrelation( + byte[] tupleBytes, CanonicalGameInstanceLaunchAssociationReadEvidence.Result launch) { + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes); + AuthoredWorldLaunchDescriptorEvidence descriptor = launch.launchBindingEvidence().descriptor(); + var preAuthorization = tuple.preAuthorizationTuple(); + var action = preAuthorization.action(); + var selector = launch.request(); + if (!StartSessionOperatorAction.ACTION_FAMILY.equals(preAuthorization.actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals(preAuthorization.targetOwner()) + || !tuple.controlPlaneRequestId().equals(selector.controlPlaneRequestId()) + || !action.scope().targetNamespace().equals(selector.targetNamespace()) + || !action.scope().tenantId().equals(selector.canonicalTenantId()) + || action.target().gameTemplateId() != descriptor.gameTemplateId() + || !selector.targetNamespace().equals(descriptor.targetNamespace()) + || !selector.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !selector.worldSlug().equals(descriptor.worldSlug()) + || !selector.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId())) { + throw invalid("Original StartSession tuple and complete launch binding differ"); + } + } + + private static byte[] boundedTuple(byte[] bytes, String label) { + if (bytes == null + || bytes.length == 0 + || bytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw invalid(label + " is empty or exceeds its byte limit"); + } + byte[] copy = bytes.clone(); + StartSessionPostAuthorizationExecutionTuple decoded = + StartSessionPostAuthorizationExecutionTuple.decode(copy); + if (!Arrays.equals(copy, decoded.canonicalBytes())) { + throw invalid(label + " is not its exact canonical byte representation"); + } + return copy; + } + + private static byte[] boundedRequest(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_REQUEST_BYTES) { + throw invalid("Complete bounded original StartSession launch read request required"); + } + return bytes.clone(); + } + + private static byte[] boundedResult(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_RESULT_BYTES) { + throw invalid("Complete bounded original StartSession launch read result required"); + } + return bytes.clone(); + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid(label + " contains unsupported fields"); + } + for (var field : message.getAllFields().entrySet()) { + Descriptors.FieldDescriptor descriptor = field.getKey(); + if (descriptor.getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) { + continue; + } + if (descriptor.isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + descriptor.getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + descriptor.getName()); + } + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadGrpcCodec.java new file mode 100644 index 0000000000..2999e074f1 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadGrpcCodec.java @@ -0,0 +1,111 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.Descriptors; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionLaunchRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionLaunchResponse; + +/** Closed bounded wire mapping for the Account-only exact original StartSession launch read. */ +public final class OriginalStartSessionLaunchReadGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = + OriginalStartSessionLaunchReadEvidence.MAX_REQUEST_BYTES; + public static final int MAX_RESPONSE_WIRE_BYTES = + OriginalStartSessionLaunchReadEvidence.MAX_RESULT_BYTES; + + private OriginalStartSessionLaunchReadGrpcCodec() {} + + public static ReadOriginalStartSessionLaunchRequest toRequest( + OriginalStartSessionLaunchReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + byte[] exactCanonicalBytes = request.canonicalBytes(); + requireSize(exactCanonicalBytes.length, MAX_REQUEST_WIRE_BYTES, "request"); + try { + ReadOriginalStartSessionLaunchRequest wire = + ReadOriginalStartSessionLaunchRequest.parseFrom(exactCanonicalBytes); + requireNoUnknownFields(wire, "original StartSession launch read request"); + if (!java.util.Arrays.equals(exactCanonicalBytes, wire.toByteArray())) { + throw new IllegalArgumentException("Original StartSession launch request is not canonical"); + } + return wire; + } catch (java.io.IOException malformed) { + throw new IllegalArgumentException( + "Original StartSession launch request is malformed", malformed); + } + } + + /** Decodes a complete closed request; this operation does not authenticate its caller. */ + public static OriginalStartSessionLaunchReadEvidence.Request fromRequest( + ReadOriginalStartSessionLaunchRequest request) { + Objects.requireNonNull(request, "request"); + requireSize(request.getSerializedSize(), MAX_REQUEST_WIRE_BYTES, "request"); + requireNoUnknownFields(request, "original StartSession launch read request"); + return OriginalStartSessionLaunchReadEvidence.Request.decode(request.toByteArray()); + } + + public static ReadOriginalStartSessionLaunchResponse toResponse( + OriginalStartSessionLaunchReadEvidence.Result result) { + Objects.requireNonNull(result, "result"); + byte[] exactCanonicalBytes = result.canonicalBytes(); + requireSize(exactCanonicalBytes.length, MAX_RESPONSE_WIRE_BYTES, "response"); + try { + ReadOriginalStartSessionLaunchResponse wire = + ReadOriginalStartSessionLaunchResponse.parseFrom(exactCanonicalBytes); + requireNoUnknownFields(wire, "original StartSession launch read response"); + if (!java.util.Arrays.equals(exactCanonicalBytes, wire.toByteArray())) { + throw new IllegalArgumentException( + "Original StartSession launch response is not canonical"); + } + return wire; + } catch (java.io.IOException malformed) { + throw new IllegalArgumentException( + "Original StartSession launch response is malformed", malformed); + } + } + + /** + * Validates the complete echoed request, launch projection, and actual retained original tuple. + */ + public static OriginalStartSessionLaunchReadEvidence.Result fromResponse( + OriginalStartSessionLaunchReadEvidence.Request expectedRequest, + ReadOriginalStartSessionLaunchResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireSize(response.getSerializedSize(), MAX_RESPONSE_WIRE_BYTES, "response"); + requireNoUnknownFields(response, "original StartSession launch read response"); + OriginalStartSessionLaunchReadEvidence.Result result = + OriginalStartSessionLaunchReadEvidence.Result.decode(response.toByteArray()); + if (!expectedRequest.equals(result.request()) || !toResponse(result).equals(response)) { + throw new IllegalArgumentException( + "Game Session original StartSession launch read changed the exact request"); + } + return result; + } + + private static void requireSize(int size, int maximum, String label) { + if (size <= 0 || size > maximum) { + throw new IllegalArgumentException( + "Original StartSession launch read " + label + " is empty or exceeds its byte limit"); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + for (var field : message.getAllFields().entrySet()) { + Descriptors.FieldDescriptor descriptor = field.getKey(); + if (descriptor.getJavaType() != Descriptors.FieldDescriptor.JavaType.MESSAGE) { + continue; + } + if (descriptor.isRepeated()) { + for (Object nested : (List) field.getValue()) { + requireNoUnknownFields((Message) nested, label + "." + descriptor.getName()); + } + } else { + requireNoUnknownFields((Message) field.getValue(), label + "." + descriptor.getName()); + } + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClient.java new file mode 100644 index 0000000000..c542e60004 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClient.java @@ -0,0 +1,149 @@ +package net.firedevops.firemud.common.world; + +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.WorldOriginalStartSessionActivationTerminalReadServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client pinned to World in the configured namespace. */ +public final class GrpcWorldOriginalStartSessionActivationTerminalReadClient + extends AbstractReloadingBlockingGrpcClient< + WorldOriginalStartSessionActivationTerminalReadServiceGrpc + .WorldOriginalStartSessionActivationTerminalReadServiceBlockingStub> + implements WorldOriginalStartSessionActivationTerminalReadClient { + private static final long CALL_DEADLINE_SECONDS = 180L; + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcWorldOriginalStartSessionActivationTerminalReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcWorldOriginalStartSessionActivationTerminalReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace must be canonical"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("World terminal read client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) + throw new IllegalStateException("World terminal read client has no gRPC stub"); + initialized = true; + } + + @Override + public WorldOriginalStartSessionActivationTerminalEvidence read( + WorldOriginalStartSessionActivationTerminalReadInput input) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World terminal read requires no ambient Account transaction"); + } + Objects.requireNonNull(input, "World terminal read input required"); + input.requireTargetNamespace(workloadNamespace); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readOriginalStartSessionActivationTerminalEvidence( + WorldOriginalStartSessionActivationTerminalReadGrpcCodec.toRequest( + input, workloadNamespace)); + try { + return WorldOriginalStartSessionActivationTerminalReadGrpcCodec.fromResponse(input, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid activation terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldOriginalStartSessionActivationTerminalReadServiceGrpc + .WorldOriginalStartSessionActivationTerminalReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldOriginalStartSessionActivationTerminalReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + WorldOriginalStartSessionActivationTerminalReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldOriginalStartSessionActivationTerminalReadServiceGrpc + .WorldOriginalStartSessionActivationTerminalReadServiceBlockingStub + requireStub() { + var current = stub(); + if (closed || !initialized || current == null) { + throw new IllegalStateException( + "World terminal read client is not initialized and available"); + } + return current; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties properties) { + if (properties == null || properties.isPlaintext()) { + throw new IllegalArgumentException("World terminal reads require workload mTLS"); + } + requireReadableFile(properties.getCertChain(), "certificate chain"); + requireReadableFile(properties.getPrivateKey(), "private key"); + requireReadableFile(properties.getCaCert(), "CA certificate"); + return properties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException("World terminal reads require file-backed TLS material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("World terminal " + label + " path is invalid", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException("World terminal " + label + " must be a readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClient.java new file mode 100644 index 0000000000..6984086f2d --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClient.java @@ -0,0 +1,155 @@ +package net.firedevops.firemud.common.world; + +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.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +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.WorldOriginalStartSessionProtectedActivationServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS client pinned to same-namespace World; intentionally not runtime-wired. */ +public final class GrpcWorldOriginalStartSessionProtectedActivationClient + extends AbstractReloadingBlockingGrpcClient< + WorldOriginalStartSessionProtectedActivationServiceGrpc + .WorldOriginalStartSessionProtectedActivationServiceBlockingStub> + implements WorldOriginalStartSessionProtectedActivationClient { + private static final long CALL_DEADLINE_SECONDS = 300L; + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcWorldOriginalStartSessionProtectedActivationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcWorldOriginalStartSessionProtectedActivationClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("World workload namespace must be canonical"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) throw new IllegalStateException("World protected activation client is closed"); + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World protected activation client has no gRPC stub"); + } + initialized = true; + } + + @Override + public WorldOriginalStartSessionActivationTerminalEvidence activate( + AccountStartSessionActivationProtectionAcquisitionInput input) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World protected activation requires no ambient Game Session transaction"); + } + Objects.requireNonNull(input, "activation acquisition input required"); + input.requireTargetNamespace(workloadNamespace); + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .activateOriginalStartSessionProtected( + WorldOriginalStartSessionProtectedActivationGrpcCodec.toRequest( + input, workloadNamespace)); + try { + return WorldOriginalStartSessionProtectedActivationGrpcCodec.fromResponse( + input, workloadNamespace, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid protected activation evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldOriginalStartSessionProtectedActivationServiceGrpc + .WorldOriginalStartSessionProtectedActivationServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldOriginalStartSessionProtectedActivationServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + WorldOriginalStartSessionProtectedActivationGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldOriginalStartSessionProtectedActivationServiceGrpc + .WorldOriginalStartSessionProtectedActivationServiceBlockingStub + requireStub() { + var current = stub(); + if (closed || !initialized || current == null) { + throw new IllegalStateException( + "World protected activation client is not initialized and available"); + } + return current; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties properties) { + if (properties == null || properties.isPlaintext()) { + throw new IllegalArgumentException("World protected activation requires workload mTLS"); + } + requireReadableFile(properties.getCertChain(), "certificate chain"); + requireReadableFile(properties.getPrivateKey(), "private key"); + requireReadableFile(properties.getCaCert(), "CA certificate"); + return properties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "World protected activation requires file-backed TLS material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World protected activation " + label + " path is invalid", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World protected activation " + label + " must be a readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalEvidence.java new file mode 100644 index 0000000000..189b2487aa --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalEvidence.java @@ -0,0 +1,371 @@ +package net.firedevops.firemud.common.world; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionRequest; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable, integrity-only World terminal receipt for one original StartSession activation. + * + *

The receipt preserves the complete first Account activation-protection carrier, the full + * original World activation result (including its original transport read correlations), and + * World's positive durable activation fence. Decoding validates bytes and cross-binding only; it + * does not authenticate Account or World, establish currentness, or itself prove that a database + * committed the referenced fence. An authenticated owner read must supply that provenance before + * Account may settle source protection. + */ +public final class WorldOriginalStartSessionActivationTerminalEvidence { + public static final String SCHEMA = + "world-original-start-session-activation-terminal-evidence/v1"; + + /** + * Maximum World result is derived from its three independently bounded Base64 children: 144 MiB + * normalized request, 64 MiB PREPARING evidence, and 64 MiB lifecycle evidence. Their 272 MiB + * total expands to at most 362 2/3 MiB inside the result, so a 384 MiB result cap leaves room for + * its JSON envelope. The outer receipt then Base64-encodes at most 200 MiB Account evidence plus + * at most 362 2/3 MiB result, or about 750 2/9 MiB plus fixed JSON overhead; 768 MiB is the + * enclosing canonical limit. + */ + public static final int MAX_CANONICAL_BYTES = 768 * 1024 * 1024; + + public static final int MAX_ACTIVATION_RESULT_BYTES = 384 * 1024 * 1024; + public static final int MAX_LIFECYCLE_EVIDENCE_BYTES = 64 * 1024 * 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "activationRequestId", + "accountProtectionId", + "accountProtectionFence", + "worldActivationFence", + "accountProtectionEvidenceBytesBase64", + "activationResultBytesBase64", + "activationResultSha256"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private final AccountStartSessionActivationProtectionEvidence accountProtectionEvidence; + private final WorldCanonicalInstanceActivation.Result activationResult; + private final long worldActivationFence; + private final byte[] canonicalBytes; + private final String terminalDigest; + + private WorldOriginalStartSessionActivationTerminalEvidence( + AccountStartSessionActivationProtectionEvidence accountProtectionEvidence, + WorldCanonicalInstanceActivation.Result activationResult, + long worldActivationFence, + byte[] canonicalBytes) { + this.accountProtectionEvidence = accountProtectionEvidence; + this.activationResult = activationResult; + this.worldActivationFence = worldActivationFence; + this.canonicalBytes = canonicalBytes.clone(); + this.terminalDigest = sha256(canonicalBytes); + } + + /** Creates a full receipt from the exact original protection and World terminal values. */ + public static WorldOriginalStartSessionActivationTerminalEvidence create( + AccountStartSessionActivationProtectionEvidence accountProtectionEvidence, + WorldCanonicalInstanceActivation.Result activationResult, + long worldActivationFence) { + Objects.requireNonNull(accountProtectionEvidence, "accountProtectionEvidence"); + Objects.requireNonNull(activationResult, "activationResult"); + if (worldActivationFence <= 0L) { + throw invalid("World activation fence must be positive"); + } + requireExactBinding(accountProtectionEvidence, activationResult); + byte[] accountBytes = accountProtectionEvidence.canonicalBytes(); + byte[] resultBytes = activationResult.canonicalBytes(); + requireChildBounds(accountProtectionEvidence, activationResult, accountBytes, resultBytes); + byte[] canonical = + encode( + activationResult.request().activationRequestId(), + accountProtectionEvidence.accountProtectionId(), + accountProtectionEvidence.accountProtectionFence(), + worldActivationFence, + accountBytes, + resultBytes, + sha256(resultBytes)); + return new WorldOriginalStartSessionActivationTerminalEvidence( + accountProtectionEvidence, activationResult, worldActivationFence, canonical); + } + + /** Strictly decodes one exact canonical terminal receipt; decoding grants no authority. */ + public static WorldOriginalStartSessionActivationTerminalEvidence decode( + byte[] exactCanonicalBytes) { + byte[] stored = bounded(exactCanonicalBytes, MAX_CANONICAL_BYTES, "terminal evidence"); + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(stored)) + .toString(); + requireCanonicalJson(stored, json); + JsonNode root = JSON.readTree(json); + requireFields(root); + if (!SCHEMA.equals(text(root, "schema"))) { + throw invalid("Unsupported World activation terminal evidence schema"); + } + byte[] accountBytes = decodeBase64(root, "accountProtectionEvidenceBytesBase64"); + byte[] resultBytes = + bounded( + decodeBase64(root, "activationResultBytesBase64"), + MAX_ACTIVATION_RESULT_BYTES, + "activation result"); + if (!SHA256.matcher(text(root, "activationResultSha256")).matches() + || !text(root, "activationResultSha256").equals(sha256(resultBytes))) { + throw invalid("World activation result digest differs from its exact bytes"); + } + AccountStartSessionActivationProtectionEvidence accountEvidence = + AccountStartSessionActivationProtectionEvidence.decode(accountBytes); + WorldCanonicalInstanceActivation.Result result = + WorldCanonicalInstanceActivation.Result.fromStored(resultBytes); + requireChildBounds(accountEvidence, result, accountBytes, resultBytes); + UUID activationRequestId = canonicalUuid(root, "activationRequestId"); + UUID accountProtectionId = canonicalUuid(root, "accountProtectionId"); + long accountProtectionFence = positiveLong(root, "accountProtectionFence"); + long worldActivationFence = positiveLong(root, "worldActivationFence"); + if (!activationRequestId.equals(result.request().activationRequestId()) + || !accountProtectionId.equals(accountEvidence.accountProtectionId()) + || accountProtectionFence != accountEvidence.accountProtectionFence()) { + throw invalid("World activation terminal identity differs from its retained Account proof"); + } + requireExactBinding(accountEvidence, result); + WorldOriginalStartSessionActivationTerminalEvidence decoded = + new WorldOriginalStartSessionActivationTerminalEvidence( + accountEvidence, result, worldActivationFence, stored); + if (!MessageDigest.isEqual(stored, decoded.canonicalBytes)) { + throw invalid("World activation terminal evidence is not its exact canonical encoding"); + } + return decoded; + } catch (IllegalArgumentException expected) { + throw expected; + } catch (IOException | RuntimeException malformed) { + throw invalid("World activation terminal evidence is malformed"); + } + } + + public AccountStartSessionActivationProtectionEvidence accountProtectionEvidence() { + return accountProtectionEvidence; + } + + public WorldCanonicalInstanceActivation.Result activationResult() { + return activationResult; + } + + public long worldActivationFence() { + return worldActivationFence; + } + + public UUID activationRequestId() { + return activationResult.request().activationRequestId(); + } + + public WorldCanonicalInstanceActivation.Outcome outcome() { + return activationResult.outcome(); + } + + /** SHA-256 of this complete immutable receipt. */ + public String terminalDigest() { + return terminalDigest; + } + + /** Exact retained receipt bytes, including original first-request read correlations. */ + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + private static void requireExactBinding( + AccountStartSessionActivationProtectionEvidence accountEvidence, + WorldCanonicalInstanceActivation.Result result) { + var protectedRequest = accountEvidence.request().worldActivationRequest(); + if (!protectedRequest.activationRequestId().equals(result.request().activationRequestId()) + || !Arrays.equals( + protectedRequest.canonicalRequestBytes(), result.request().canonicalRequestBytes()) + || !Arrays.equals( + protectedRequest.preparingEvidenceBytes(), result.request().preparingEvidenceBytes())) { + throw invalid( + "World terminal result differs from the original Account-protected activation request"); + } + if (result.outcome() == WorldCanonicalInstanceActivation.Outcome.COMMITTED) { + if (!"ACTIVE".equals(result.lifecycleEvidence().lifecycleStatus()) + || result.lifecycleEvidence().lifecycleEpoch() + != Math.addExact(result.request().expectedLifecycleEpoch(), 1L) + || result.lifecycleEvidence().rowVersion() + != Math.addExact(result.request().expectedRowVersion(), 1L)) { + throw invalid("Committed World activation terminal evidence is not the exact ACTIVE CAS"); + } + } else if (result.terminalCode() == null || result.terminalCode().isBlank()) { + throw invalid("Fenced World activation ABORTED evidence requires a terminal code"); + } + } + + private static void requireChildBounds( + AccountStartSessionActivationProtectionEvidence accountEvidence, + WorldCanonicalInstanceActivation.Result result, + byte[] accountBytes, + byte[] resultBytes) { + bounded( + accountBytes, + AccountStartSessionActivationProtectionEvidence.MAX_CANONICAL_BYTES, + "Account protection evidence"); + bounded( + accountEvidence.request().canonicalBytes(), + AccountStartSessionActivationProtectionRequest.MAX_CANONICAL_BYTES, + "Account protection request"); + bounded( + accountEvidence.request().worldActivationRequest().preparingEvidenceBytes(), + AccountStartSessionActivationProtectionRequest.MAX_WORLD_PREPARING_EVIDENCE_BYTES, + "PREPARING evidence"); + bounded( + result.request().canonicalRequestBytes(), + AccountStartSessionActivationProtectionRequest.MAX_CANONICAL_BYTES, + "normalized World activation request"); + bounded( + result.lifecycleEvidence().canonicalBytes(), + MAX_LIFECYCLE_EVIDENCE_BYTES, + "lifecycle evidence"); + bounded(resultBytes, MAX_ACTIVATION_RESULT_BYTES, "activation result"); + } + + private static byte[] encode( + UUID activationRequestId, + UUID accountProtectionId, + long accountProtectionFence, + long worldActivationFence, + byte[] accountEvidenceBytes, + byte[] resultBytes, + String resultDigest) { + Map value = new LinkedHashMap<>(); + value.put("schema", SCHEMA); + value.put("activationRequestId", activationRequestId.toString()); + value.put("accountProtectionId", accountProtectionId.toString()); + value.put("accountProtectionFence", Long.toString(accountProtectionFence)); + value.put("worldActivationFence", Long.toString(worldActivationFence)); + value.put( + "accountProtectionEvidenceBytesBase64", + Base64.getEncoder().encodeToString(accountEvidenceBytes)); + value.put("activationResultBytesBase64", Base64.getEncoder().encodeToString(resultBytes)); + value.put("activationResultSha256", resultDigest); + try { + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + if (bytes.length > MAX_CANONICAL_BYTES) { + throw invalid("World activation terminal evidence exceeds its byte limit"); + } + return bytes; + } catch (IOException impossible) { + throw new IllegalStateException( + "World activation terminal evidence cannot be encoded", impossible); + } + } + + private static void requireFields(JsonNode node) { + if (node == null || !node.isObject() || node.size() != ROOT_FIELDS.size()) { + throw invalid("World activation terminal evidence has an invalid closed object shape"); + } + for (String field : node.propertyNames()) { + if (!ROOT_FIELDS.contains(field)) + throw invalid("World activation terminal evidence has an unknown field"); + } + } + + private static UUID canonicalUuid(JsonNode node, String field) { + String text = text(node, field); + try { + UUID value = UUID.fromString(text); + if (!value.toString().equals(text) || NIL_UUID.equals(value)) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + return value; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical lowercase non-nil UUID"); + } + } + + private static long positiveLong(JsonNode node, String field) { + String text = text(node, field); + if (!text.matches("[1-9][0-9]{0,18}")) { + throw invalid(field + " must be a positive canonical signed 64-bit decimal string"); + } + try { + long value = Long.parseLong(text); + if (value <= 0L || !Long.toString(value).equals(text)) { + throw invalid(field + " must be a positive canonical signed 64-bit decimal string"); + } + return value; + } catch (NumberFormatException malformed) { + throw invalid(field + " is outside the supported signed 64-bit range"); + } + } + + private static String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) throw invalid(field + " must be text"); + return value.textValue(); + } + + private static byte[] decodeBase64(JsonNode node, String field) { + String value = text(node, field); + try { + byte[] bytes = Base64.getDecoder().decode(value); + if (!Base64.getEncoder().encodeToString(bytes).equals(value)) { + throw invalid(field + " must use canonical Base64"); + } + return bytes; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is malformed Base64"); + } + } + + private static byte[] bounded(byte[] value, int maximum, String label) { + if (value == null || value.length == 0 || value.length > maximum) { + throw invalid("World activation " + label + " is absent or exceeds its byte limit"); + } + return value.clone(); + } + + private static void requireCanonicalJson(byte[] bytes, String json) throws IOException { + if (!MessageDigest.isEqual(Rfc8785CanonicalJson.canonicalizeUtf8(json), bytes)) { + throw invalid("World activation terminal evidence is not canonical RFC 8785 JSON"); + } + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadClient.java new file mode 100644 index 0000000000..29bbb4e2cb --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadClient.java @@ -0,0 +1,8 @@ +package net.firedevops.firemud.common.world; + +/** Reads one exact immutable original activation terminal from the authenticated World owner. */ +public interface WorldOriginalStartSessionActivationTerminalReadClient { + /** Returns the exact first World receipt, or {@code null} when World has no terminal receipt. */ + WorldOriginalStartSessionActivationTerminalEvidence read( + WorldOriginalStartSessionActivationTerminalReadInput input); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodec.java new file mode 100644 index 0000000000..2706efe210 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodec.java @@ -0,0 +1,204 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalStartSessionActivationTerminalEvidenceRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalStartSessionActivationTerminalEvidenceResponse; + +/** Closed bounded protobuf mapping for exact World original activation terminal reads. */ +public final class WorldOriginalStartSessionActivationTerminalReadGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = + AccountStartSessionActivationProtectionEvidence.MAX_CANONICAL_BYTES + 256; + public static final int MAX_RESPONSE_WIRE_BYTES = + WorldOriginalStartSessionActivationTerminalEvidence.MAX_CANONICAL_BYTES + 64; + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private WorldOriginalStartSessionActivationTerminalReadGrpcCodec() {} + + public static ReadOriginalStartSessionActivationTerminalEvidenceRequest toRequest( + WorldOriginalStartSessionActivationTerminalReadInput input, String namespace) { + Objects.requireNonNull(input, "World terminal read input required"); + requireNamespace(namespace); + input.requireTargetNamespace(namespace); + var request = + ReadOriginalStartSessionActivationTerminalEvidenceRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addTargetNamespace(namespace) + .addReadRequestId(input.readRequestId().toString()) + .addAccountProtectionEvidence( + ByteString.copyFrom(input.protectionEvidence().canonicalBytes())) + .build(); + requireRequestBudget(request); + return request; + } + + /** Call only after the receiver has authenticated the exact same-namespace Account peer. */ + public static WorldOriginalStartSessionActivationTerminalReadInput fromRequest( + ReadOriginalStartSessionActivationTerminalEvidenceRequest request, String expectedNamespace) { + if (request == null) throw invalid("request is missing"); + requireClosed(request, "request"); + requireRequestBudget(request); + if (request.getSchemaVersionCount() != 1 + || request.getTargetNamespaceCount() != 1 + || request.getReadRequestIdCount() != 1 + || request.getAccountProtectionEvidenceCount() != 1 + || request.getSchemaVersion(0) != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(expectedNamespace) + || !expectedNamespace.equals(request.getTargetNamespace(0))) { + throw invalid("Unsupported schema, duplicate field, or namespace"); + } + byte[] evidenceBytes = request.getAccountProtectionEvidence(0).toByteArray(); + if (evidenceBytes.length == 0 + || evidenceBytes.length + > AccountStartSessionActivationProtectionEvidence.MAX_CANONICAL_BYTES) { + throw invalid("Complete Account activation protection evidence is missing or oversized"); + } + var input = + new WorldOriginalStartSessionActivationTerminalReadInput( + canonicalUuid(request.getReadRequestId(0)), + AccountStartSessionActivationProtectionEvidence.decode(evidenceBytes)); + input.requireTargetNamespace(expectedNamespace); + if (!toRequest(input, expectedNamespace).equals(request)) { + throw invalid("World terminal read request is not its exact closed encoding"); + } + return input; + } + + public static ReadOriginalStartSessionActivationTerminalEvidenceResponse toResponse( + WorldOriginalStartSessionActivationTerminalReadInput input, + WorldOriginalStartSessionActivationTerminalEvidence terminal) { + requireTerminalMatches(input, terminal); + var response = + ReadOriginalStartSessionActivationTerminalEvidenceResponse.newBuilder() + .addReadRequestId(input.readRequestId().toString()) + .addTerminalEvidence(ByteString.copyFrom(terminal.canonicalBytes())) + .build(); + requireResponseBudget(response); + return response; + } + + /** Validates and returns the complete first immutable World receipt unchanged. */ + public static WorldOriginalStartSessionActivationTerminalEvidence fromResponse( + WorldOriginalStartSessionActivationTerminalReadInput input, + ReadOriginalStartSessionActivationTerminalEvidenceResponse response) { + Objects.requireNonNull(input, "World terminal read input required"); + Objects.requireNonNull(response, "World terminal read response required"); + requireClosed(response, "response"); + requireResponseBudget(response); + if (response.getReadRequestIdCount() != 1 + || response.getTerminalEvidenceCount() != 1 + || !input.readRequestId().toString().equals(response.getReadRequestId(0))) { + throw invalid("World terminal response correlation is missing or changed"); + } + WorldOriginalStartSessionActivationTerminalEvidence terminal = + WorldOriginalStartSessionActivationTerminalEvidence.decode( + response.getTerminalEvidence(0).toByteArray()); + requireTerminalMatches(input, terminal); + if (!toResponse(input, terminal).equals(response)) { + throw invalid("World terminal response is not its exact closed encoding"); + } + return terminal; + } + + public static WorldOriginalStartSessionActivationTerminalReadInput fromRequestWireBytes( + byte[] wireBytes, String namespace) { + if (wireBytes == null || wireBytes.length == 0 || wireBytes.length > MAX_REQUEST_WIRE_BYTES) { + throw invalid("World terminal request exceeds its wire limit"); + } + try { + var wire = ReadOriginalStartSessionActivationTerminalEvidenceRequest.parseFrom(wireBytes); + var input = fromRequest(wire, namespace); + if (!Arrays.equals(wireBytes, toRequest(input, namespace).toByteArray())) { + throw invalid("World terminal request wire bytes are not canonical"); + } + return input; + } catch (InvalidProtocolBufferException malformed) { + throw invalid("World terminal request wire bytes are malformed", malformed); + } + } + + public static WorldOriginalStartSessionActivationTerminalEvidence fromResponseWireBytes( + WorldOriginalStartSessionActivationTerminalReadInput input, byte[] wireBytes) { + if (wireBytes == null || wireBytes.length == 0 || wireBytes.length > MAX_RESPONSE_WIRE_BYTES) { + throw invalid("World terminal response exceeds its wire limit"); + } + try { + var wire = ReadOriginalStartSessionActivationTerminalEvidenceResponse.parseFrom(wireBytes); + var terminal = fromResponse(input, wire); + if (!Arrays.equals(wireBytes, toResponse(input, terminal).toByteArray())) { + throw invalid("World terminal response wire bytes are not canonical"); + } + return terminal; + } catch (InvalidProtocolBufferException malformed) { + throw invalid("World terminal response wire bytes are malformed", malformed); + } + } + + private static void requireTerminalMatches( + WorldOriginalStartSessionActivationTerminalReadInput input, + WorldOriginalStartSessionActivationTerminalEvidence terminal) { + Objects.requireNonNull(terminal, "World terminal receipt required"); + if (!Arrays.equals( + input.protectionEvidence().canonicalBytes(), + terminal.accountProtectionEvidence().canonicalBytes())) { + throw invalid("World terminal receipt is not bound to the requested full Account evidence"); + } + input.requireTargetNamespace(input.targetNamespace()); + } + + private static void requireRequestBudget( + ReadOriginalStartSessionActivationTerminalEvidenceRequest request) { + if (request.getSerializedSize() <= 0 || request.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) { + throw invalid("World terminal request exceeds its wire limit"); + } + } + + private static void requireResponseBudget( + ReadOriginalStartSessionActivationTerminalEvidenceResponse response) { + if (response.getSerializedSize() <= 0 + || response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || response.getTerminalEvidenceCount() != 1 + || response.getTerminalEvidence(0).isEmpty() + || response.getTerminalEvidence(0).size() + > WorldOriginalStartSessionActivationTerminalEvidence.MAX_CANONICAL_BYTES) { + throw invalid("World terminal evidence is missing or exceeds its existing byte limit"); + } + } + + private static void requireClosed(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid("World terminal " + label + " contains unsupported fields"); + } + } + + private static UUID canonicalUuid(String value) { + try { + UUID id = UUID.fromString(value); + if (!id.toString().equals(value) || NIL_UUID.equals(id)) + throw invalid("Invalid read correlation ID"); + return id; + } catch (IllegalArgumentException malformed) { + throw invalid("Invalid read correlation ID", malformed); + } + } + + private static void requireNamespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw invalid("Invalid World target namespace"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException("Original activation terminal read " + message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException("Original activation terminal read " + message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadInput.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadInput.java new file mode 100644 index 0000000000..0a53f50cc6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadInput.java @@ -0,0 +1,48 @@ +package net.firedevops.firemud.common.world; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Exact lookup-only World read selector derived from retained Account activation evidence. */ +public final class WorldOriginalStartSessionActivationTerminalReadInput { + private final UUID readRequestId; + private final AccountStartSessionActivationProtectionEvidence protectionEvidence; + + public WorldOriginalStartSessionActivationTerminalReadInput( + UUID readRequestId, AccountStartSessionActivationProtectionEvidence protectionEvidence) { + if (readRequestId == null || new UUID(0L, 0L).equals(readRequestId)) { + throw new IllegalArgumentException("Non-nil World terminal-read correlation ID required"); + } + this.readRequestId = readRequestId; + this.protectionEvidence = + Objects.requireNonNull(protectionEvidence, "Account protection evidence required"); + } + + public UUID readRequestId() { + return readRequestId; + } + + public AccountStartSessionActivationProtectionEvidence protectionEvidence() { + return protectionEvidence; + } + + public String targetNamespace() { + return protectionEvidence + .request() + .originalTuple() + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace(); + } + + public void requireTargetNamespace(String expectedNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(expectedNamespace) + || !expectedNamespace.equals(targetNamespace())) { + throw new IllegalArgumentException( + "World terminal read namespace differs from retained evidence"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationClient.java new file mode 100644 index 0000000000..fedd7f84d9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationClient.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.common.world; + +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; + +/** Explicit Game Session-side client for World's standalone protected-activation boundary. */ +public interface WorldOriginalStartSessionProtectedActivationClient { + /** + * Sends the exact Account acquisition statement and returns World's full immutable first receipt. + */ + WorldOriginalStartSessionActivationTerminalEvidence activate( + AccountStartSessionActivationProtectionAcquisitionInput input); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodec.java new file mode 100644 index 0000000000..09bff5bbb2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodec.java @@ -0,0 +1,163 @@ +package net.firedevops.firemud.common.world; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.worldmanagement.v1.ActivateOriginalStartSessionProtectedRequest; +import net.firedevops.firemud.worldmanagement.v1.ActivateOriginalStartSessionProtectedResponse; + +/** + * Closed, bounded World transport mapping that preserves the complete Account acquisition input. + */ +public final class WorldOriginalStartSessionProtectedActivationGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = 65 * 1024 * 1024 + 128; + public static final int MAX_RESPONSE_WIRE_BYTES = + WorldOriginalStartSessionActivationTerminalEvidence.MAX_CANONICAL_BYTES + 64; + private static final int SCHEMA_VERSION = 1; + + private WorldOriginalStartSessionProtectedActivationGrpcCodec() {} + + public static ActivateOriginalStartSessionProtectedRequest toRequest( + AccountStartSessionActivationProtectionAcquisitionInput input, String namespace) { + Objects.requireNonNull(input, "activation acquisition input required"); + requireNamespace(namespace); + input.requireTargetNamespace(namespace); + var request = + ActivateOriginalStartSessionProtectedRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addTargetNamespace(namespace) + .addAcquisitionInput( + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toRequest( + input, namespace)) + .build(); + requireRequestBudget(request); + return request; + } + + /** Call only after exact same-namespace Game Session workload authentication. */ + public static AccountStartSessionActivationProtectionAcquisitionInput fromRequest( + ActivateOriginalStartSessionProtectedRequest request, String expectedNamespace) { + Objects.requireNonNull(request, "protected activation request required"); + requireClosed(request, "request"); + requireRequestBudget(request); + if (request.getSchemaVersionCount() != 1 + || request.getTargetNamespaceCount() != 1 + || request.getAcquisitionInputCount() != 1 + || request.getSchemaVersion(0) != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(expectedNamespace) + || !expectedNamespace.equals(request.getTargetNamespace(0))) { + throw invalid("Unsupported schema, duplicate field, or target namespace"); + } + AccountStartSessionActivationProtectionAcquisitionInput input = + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( + request.getAcquisitionInput(0), expectedNamespace); + if (!toRequest(input, expectedNamespace).equals(request)) { + throw invalid("Protected activation request is not its exact closed encoding"); + } + return input; + } + + public static ActivateOriginalStartSessionProtectedResponse toResponse( + AccountStartSessionActivationProtectionAcquisitionInput input, + String namespace, + WorldOriginalStartSessionActivationTerminalEvidence terminal) { + requireTerminalMatches(input, namespace, terminal); + var response = + ActivateOriginalStartSessionProtectedResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addTerminalEvidence(ByteString.copyFrom(terminal.canonicalBytes())) + .build(); + requireResponseBudget(response); + return response; + } + + /** + * Returns the complete retained first terminal receipt without rewriting its read correlations. + */ + public static WorldOriginalStartSessionActivationTerminalEvidence fromResponse( + AccountStartSessionActivationProtectionAcquisitionInput input, + String namespace, + ActivateOriginalStartSessionProtectedResponse response) { + Objects.requireNonNull(input, "activation acquisition input required"); + Objects.requireNonNull(response, "protected activation response required"); + requireClosed(response, "response"); + requireResponseBudget(response); + if (response.getSchemaVersionCount() != 1 + || response.getSchemaVersion(0) != SCHEMA_VERSION + || response.getTerminalEvidenceCount() != 1) { + throw invalid("Unsupported schema or missing exact World terminal evidence"); + } + byte[] bytes = response.getTerminalEvidence(0).toByteArray(); + if (bytes.length == 0 + || bytes.length > WorldOriginalStartSessionActivationTerminalEvidence.MAX_CANONICAL_BYTES) { + throw invalid("World terminal evidence is missing or oversized"); + } + WorldOriginalStartSessionActivationTerminalEvidence terminal = + WorldOriginalStartSessionActivationTerminalEvidence.decode(bytes); + requireTerminalMatches(input, namespace, terminal); + if (!toResponse(input, namespace, terminal).equals(response)) { + throw invalid("Protected activation response is not its exact closed encoding"); + } + return terminal; + } + + private static void requireTerminalMatches( + AccountStartSessionActivationProtectionAcquisitionInput input, + String namespace, + WorldOriginalStartSessionActivationTerminalEvidence terminal) { + Objects.requireNonNull(input, "activation acquisition input required"); + Objects.requireNonNull(terminal, "World terminal evidence required"); + requireNamespace(namespace); + input.requireTargetNamespace(namespace); + // The Account codec compares the caller's full tuple, GS mutation/attempt/fence, activation + // identity, and stable PREPARING request. It deliberately tolerates only World read correlation + // normalization and does not replace the first Account receipt carried by the terminal. + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toResponse( + input, namespace, terminal.accountProtectionEvidence()); + var requested = input.worldActivationRequest(); + var terminalRequest = terminal.activationResult().request(); + if (!requested.activationRequestId().equals(terminal.activationRequestId()) + || !Arrays.equals( + requested.canonicalRequestBytes(), terminalRequest.canonicalRequestBytes())) { + throw invalid("World terminal differs from the exact caller activation statement"); + } + } + + private static void requireRequestBudget(ActivateOriginalStartSessionProtectedRequest request) { + if (request.getSerializedSize() <= 0 || request.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) { + throw invalid("World protected activation request exceeds its wire limit"); + } + } + + private static void requireResponseBudget( + ActivateOriginalStartSessionProtectedResponse response) { + if (response.getSerializedSize() <= 0 + || response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || response.getTerminalEvidenceCount() != 1 + || response.getTerminalEvidence(0).isEmpty() + || response.getTerminalEvidence(0).size() + > WorldOriginalStartSessionActivationTerminalEvidence.MAX_CANONICAL_BYTES) { + throw invalid("World activation terminal response exceeds its carrier-specific wire limit"); + } + } + + private static void requireClosed(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid("World protected activation " + label + " contains unsupported fields"); + } + } + + private static void requireNamespace(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw invalid("Target namespace is invalid"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException("World protected activation " + message); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodecTest.java new file mode 100644 index 0000000000..8a8c4f3de1 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodecTest.java @@ -0,0 +1,111 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionActivationProtectionRequest; +import org.junit.jupiter.api.Test; + +/** Closed-envelope denial tests; no World or Account producer authentication is claimed. */ +class AccountStartSessionActivationProtectionAcquisitionGrpcCodecTest { + private static final String NAMESPACE = "world-runtime"; + private static final String MUTATION = "11111111-1111-4111-8111-111111111111"; + private static final String ATTEMPT = "22222222-2222-4222-8222-222222222222"; + private static final String ACTIVATION = "33333333-3333-4333-8333-333333333333"; + + @Test + void rejectsDuplicateAndUnknownRequestFieldsBeforeDecodingOwnerBytes() { + var duplicate = + AcquireOriginalStartSessionActivationProtectionRequest.newBuilder() + .addSchemaVersion(1) + .addSchemaVersion(1) + .build(); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( + duplicate, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate field"); + + var unknown = + AcquireOriginalStartSessionActivationProtectionRequest.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( + unknown, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + @Test + void rejectsNonCanonicalFenceTextAndRawDuplicateOccurrences() { + var nonCanonicalFence = minimallyPopulatedRequest("01"); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( + nonCanonicalFence, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical positive unsigned decimal"); + + var duplicateSchemaWire = + AcquireOriginalStartSessionActivationProtectionRequest.newBuilder() + .addSchemaVersion(1) + .addSchemaVersion(1) + .build() + .toByteArray(); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequestWireBytes( + duplicateSchemaWire, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate field"); + } + + @Test + void rejectsMismatchedTargetAndUnusableOriginalEvidence() { + var request = + AcquireOriginalStartSessionActivationProtectionRequest.newBuilder() + .addSchemaVersion(1) + .addTargetNamespace("other-runtime") + .addOriginalPostAuthorizationTuple(ByteString.copyFrom(new byte[] {1})) + .addGameSessionOwnerMutationId(MUTATION) + .addGameSessionOwnerAttemptId(ATTEMPT) + .addGameSessionOwnerFence("7") + .addActivationRequestId(ACTIVATION) + .addWorldPreparingEvidence(ByteString.copyFrom(new byte[] {1})) + .build(); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( + request, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("target namespace"); + + assertThatThrownBy( + () -> + new AccountStartSessionActivationProtectionAcquisitionInput( + new byte[] {1}, UUID.fromString(MUTATION), UUID.fromString(ATTEMPT), 7L, null)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AcquireOriginalStartSessionActivationProtectionRequest minimallyPopulatedRequest( + String fence) { + return AcquireOriginalStartSessionActivationProtectionRequest.newBuilder() + .addSchemaVersion(1) + .addTargetNamespace(NAMESPACE) + .addOriginalPostAuthorizationTuple(ByteString.copyFrom(new byte[] {1})) + .addGameSessionOwnerMutationId(MUTATION) + .addGameSessionOwnerAttemptId(ATTEMPT) + .addGameSessionOwnerFence(fence) + .addActivationRequestId(ACTIVATION) + .addWorldPreparingEvidence(ByteString.copyFrom(new byte[] {1})) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodecTest.java new file mode 100644 index 0000000000..0931b0e2cd --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodecTest.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionActivationProtectionResponse; +import org.junit.jupiter.api.Test; + +/** Closed selector and response-binding denials; no authenticated terminal producer proof. */ +class AccountStartSessionActivationProtectionSettlementGrpcCodecTest { + private static final String NAMESPACE = "world-runtime"; + + @Test + void roundTripsOnlyExactLookupIdentity() { + var input = input(); + var request = AccountStartSessionActivationProtectionSettlementGrpcCodec.toRequest(input); + var decoded = + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest(request, NAMESPACE); + + assertThat(decoded).isEqualTo(input); + assertThat(request.getSerializedSize()) + .isLessThanOrEqualTo( + AccountStartSessionActivationProtectionSettlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); + } + + @Test + void rejectsDuplicateUnknownChangedAndNoncanonicalRequestFields() { + var valid = AccountStartSessionActivationProtectionSettlementGrpcCodec.toRequest(input()); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( + valid.toBuilder().addAccountProtectionFence("18").build(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( + valid.toBuilder().setTargetNamespace(0, "other-runtime").build(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( + valid.toBuilder().setAccountProtectionFence(0, "018").build(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( + valid.toBuilder() + .setSettlementRequestId(0, "00000000-0000-0000-0000-000000000000") + .build(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void responseMustEchoRequestIdentityAndContainCompleteTerminalBytes() { + var input = input(); + var validShape = + SettleOriginalStartSessionActivationProtectionResponse.newBuilder() + .addSchemaVersion(1) + .addSettlementRequestId(input.settlementRequestId().toString()) + .addAccountProtectionId(input.accountProtectionId().toString()) + .addAccountProtectionFence(Long.toString(input.accountProtectionFence())) + .addSettledAt("2026-10-11T00:00:00.000001Z") + .addTerminalEvidenceCanonicalBytes(ByteString.copyFromUtf8("{}")) + .build(); + + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, + validShape.toBuilder() + .setSettlementRequestId(0, UUID.randomUUID().toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("identity"); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, validShape.toBuilder().setAccountProtectionFence(0, "19").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("identity"); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, + validShape.toBuilder() + .setAccountProtectionId(0, UUID.randomUUID().toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("identity"); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, + validShape.toBuilder().addSettledAt("2026-10-11T00:00:00.000001Z").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("identity"); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, + validShape.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, + validShape.toBuilder() + .setTerminalEvidenceCanonicalBytes(0, ByteString.EMPTY) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AccountStartSessionActivationProtectionSettlementInput input() { + return new AccountStartSessionActivationProtectionSettlementInput( + NAMESPACE, + UUID.fromString("9a7b466e-8db0-4dfc-9244-8047d5b2f662"), + UUID.fromString("51f0c814-5f0c-4c75-9de8-77dc6b265c4a"), + 18L); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClientTest.java new file mode 100644 index 0000000000..f5f5958e05 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClientTest.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import java.io.IOException; +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 org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Client construction and boundary denials; no remote Account call or TLS identity proof. */ +class GrpcAccountStartSessionActivationProtectionAcquisitionClientTest { + @TempDir Path temporaryDirectory; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsPlaintextClasspathAndMissingMaterial() { + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> client(plaintext)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var classpath = new CommonGrpcClientProperties(); + classpath.setCertChain("classpath:client.pem"); + classpath.setPrivateKey("/tmp/key.pem"); + classpath.setCaCert("/tmp/ca.pem"); + assertThatThrownBy(() -> client(classpath)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + assertThatThrownBy(() -> client(new CommonGrpcClientProperties())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + } + + @Test + void rejectsUninitializedUseAndAnyAmbientTransactionBeforeRequestHandling() throws IOException { + var client = client(fileBackedProperties()); + assertThatThrownBy(() -> client.acquire(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.acquire(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.acquire(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + TransactionSynchronizationManager.clearSynchronization(); + } + + private GrpcAccountStartSessionActivationProtectionAcquisitionClient client( + CommonGrpcClientProperties tls) { + return new GrpcAccountStartSessionActivationProtectionAcquisitionClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "world-runtime"); + } + + private CommonGrpcClientProperties fileBackedProperties() throws IOException { + Path certificate = Files.createFile(temporaryDirectory.resolve("client.pem")); + Path privateKey = Files.createFile(temporaryDirectory.resolve("client-key.pem")); + Path ca = Files.createFile(temporaryDirectory.resolve("ca.pem")); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(ca.toString()); + return properties; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClientTest.java new file mode 100644 index 0000000000..5fc10ff1a1 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionSettlementClientTest.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import java.io.IOException; +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.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Construction and local boundary denials; no authenticated Account transport proof. */ +class GrpcAccountStartSessionActivationProtectionSettlementClientTest { + @TempDir Path temporaryDirectory; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsPlaintextClasspathAndMissingMaterial() { + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> client(plaintext)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var classpath = new CommonGrpcClientProperties(); + classpath.setCertChain("classpath:client.pem"); + classpath.setPrivateKey("/tmp/key.pem"); + classpath.setCaCert("/tmp/ca.pem"); + assertThatThrownBy(() -> client(classpath)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + assertThatThrownBy(() -> client(new CommonGrpcClientProperties())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + } + + @Test + void rejectsUninitializedUseAmbientTransactionsAndChangedNamespace() throws IOException { + var client = client(fileBackedProperties()); + assertThatThrownBy(() -> client.settle(input("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + assertThatThrownBy(() -> client.settle(input("other-runtime"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.settle(input("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient World transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.settle(input("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient World transaction"); + TransactionSynchronizationManager.clearSynchronization(); + } + + private GrpcAccountStartSessionActivationProtectionSettlementClient client( + CommonGrpcClientProperties tls) { + return new GrpcAccountStartSessionActivationProtectionSettlementClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "world-runtime"); + } + + private CommonGrpcClientProperties fileBackedProperties() throws IOException { + Path certificate = Files.createFile(temporaryDirectory.resolve("client.pem")); + Path privateKey = Files.createFile(temporaryDirectory.resolve("client-key.pem")); + Path ca = Files.createFile(temporaryDirectory.resolve("ca.pem")); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + + private static AccountStartSessionActivationProtectionSettlementInput input(String namespace) { + return new AccountStartSessionActivationProtectionSettlementInput( + namespace, UUID.randomUUID(), UUID.randomUUID(), 1L); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjectionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjectionTest.java new file mode 100644 index 0000000000..4a3ce79a53 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjectionTest.java @@ -0,0 +1,403 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; + +class AuthoredInitialActorCoreProjectionTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final UUID SELECTED_COMMIT = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID POLICY_REVISION = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID DISPOSITION_REVISION = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID FEEDBACK_REVISION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID BINDING_ID = uuid("abababab-abab-4bab-8bab-abababababab"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void roundTripsClosedProjectionAndPreservesExactPublicSourceProvenance() { + var projection = projection(); + var decoded = + AuthoredInitialActorCoreProjection.fromStored( + projection.canonicalBytes(), projection.digest()); + + assertThat(decoded.bindingId()).isEqualTo(BINDING_ID); + assertThat(decoded.bindingDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(decoded.canonicalTenantId()).isEqualTo(TENANT); + assertThat(decoded.canonicalVersionId()).isEqualTo(VERSION); + assertThat(decoded.selectedCommitId()).isEqualTo(COMMIT); + assertThat(decoded.policy().revisionId()).isEqualTo(POLICY_REVISION); + assertThat(decoded.core().displayName()).isEqualTo("Wayfarer"); + assertThat(decoded.descriptor().canonicalJson()).contains("\"inputKind\":\"EMPTY_OBJECT\""); + assertThat(decoded.disposition().revisionId()).isEqualTo(DISPOSITION_REVISION); + assertThat(decoded.disposition().revisionOrder()).isEqualTo("1"); + assertThat(decoded.disposition().definitionDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(decoded.disposition().sourceCommitDigest()) + .isEqualTo(decoded.selectedCommitDigest()); + assertThat(decoded.safeFeedback().revisionId()).isEqualTo(FEEDBACK_REVISION); + assertThat(decoded.safeFeedback().revisionOrder()).isEqualTo("2"); + assertThat(decoded.canonicalBytes()).isEqualTo(projection.canonicalBytes()); + } + + @Test + void roundTripsInheritedPolicyAndRuleOriginsDistinctFromSelectedCommit() { + var origin = sourceBinding(); + var source = inheritedSourceBinding(origin); + var projection = AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, source); + var decoded = + AuthoredInitialActorCoreProjection.fromStored( + projection.canonicalBytes(), projection.digest()); + + assertThat(decoded.selectedCommitId()).isEqualTo(SELECTED_COMMIT); + assertThat(decoded.selectedCommitId()).isNotEqualTo(origin.selectedCommit().commitId()); + assertThat(decoded.policy().commitId()).isEqualTo(origin.policySource().commitId()); + assertThat(decoded.policy().revisionId()).isEqualTo(POLICY_REVISION); + assertThat(decoded.disposition().sourceCommitId()).isEqualTo(COMMIT); + assertThat(decoded.disposition().sourceCommitDigest()) + .isEqualTo(origin.selectedCommit().digest()); + assertThat(decoded.disposition().revisionId()).isEqualTo(DISPOSITION_REVISION); + assertThat(decoded.safeFeedback().sourceCommitId()).isEqualTo(COMMIT); + assertThat(decoded.safeFeedback().sourceCommitDigest()) + .isEqualTo(origin.selectedCommit().digest()); + assertThat(decoded.safeFeedback().revisionId()).isEqualTo(FEEDBACK_REVISION); + assertThat(decoded.selectedCommitDigest()).isEqualTo(source.selectedCommit().digest()); + } + + @Test + void returnsImmutableEntryProvenanceAndDefensivelyCopiesProjectionBytes() { + var source = sourceBinding(); + byte[] sourceBytes = source.canonicalBytes(); + String sourceDigest = source.digest(); + var projection = AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, source); + byte[] bytes = projection.canonicalBytes(); + bytes[0] ^= 1; + assertThat(projection.canonicalBytes()).isNotEqualTo(bytes); + + var disposition = source.dispositionSource(); + var feedback = source.safeFeedbackSource(); + assertThat(disposition.revisionId()).isEqualTo(DISPOSITION_REVISION); + assertThat(feedback.revisionId()).isEqualTo(FEEDBACK_REVISION); + assertThat(disposition.sourceBinding().digest()).isEqualTo(source.selectedCommit().digest()); + assertThat(source.canonicalBytes()).isEqualTo(sourceBytes); + assertThat(source.digest()).isEqualTo(sourceDigest); + assertThatThrownBy( + () -> ((Disposition) disposition.definition()).deniedAdmissionTags().add("changed")) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(((Disposition) disposition.definition()).deniedAdmissionTags()).isEmpty(); + } + + @Test + void rejectsChangedFieldsDigestUnknownDuplicateAndTrailingInput() { + var projection = projection(); + String json = new String(projection.canonicalBytes(), StandardCharsets.UTF_8); + + byte[] changedTenant = + json.replace(TENANT.toString(), "99999999-9999-4999-8999-999999999999") + .getBytes(StandardCharsets.UTF_8); + assertRejected(changedTenant, projection.digest()); + assertThatThrownBy( + () -> + AuthoredInitialActorCoreProjection.fromStored( + projection.canonicalBytes(), digest('0'))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest differs"); + + byte[] unknown = canonicalize(json.substring(0, json.length() - 1) + ",\"unknown\":true}"); + assertRejected(unknown, CommandSource.sha256(unknown)); + + byte[] duplicate = + json.replaceFirst("\\\"schema\\\":", "\\\"schema\\\":\\\"duplicate\\\",\\\"schema\\\":") + .getBytes(StandardCharsets.UTF_8); + assertRejected(duplicate, CommandSource.sha256(duplicate)); + + byte[] trailing = (json + " true").getBytes(StandardCharsets.UTF_8); + assertRejected(trailing, CommandSource.sha256(trailing)); + } + + @Test + void rejectsPolicyCoreDescriptorAndRuleCrossSubstitution() { + var projection = projection(); + String json = new String(projection.canonicalBytes(), StandardCharsets.UTF_8); + + String changedCore = json.replaceFirst("Wayfarer", "Wanderer"); + assertRejected(canonicalize(changedCore), null); + + String changedDescriptor = json.replace("EMPTY_OBJECT", "NONEMPTY_OBJECT"); + assertRejected(canonicalize(changedDescriptor), null); + + String changedRuleKey = replaceLast(json, "\"key\":\"welcome\"", "\"key\":\"different\""); + assertRejected(canonicalize(changedRuleKey), null); + + String changedRuleDefinition = json.replace("Welcome, traveler.", "Welcome home."); + assertRejected(canonicalize(changedRuleDefinition), null); + + String changedPolicyContent = json.replace("World", "Other World"); + assertRejected(canonicalize(changedPolicyContent), null); + } + + @Test + void rejectsSelfConsistentFeedbackNotSelectedByDisposition() throws Exception { + var projection = projection(); + ObjectNode root = + (ObjectNode) JSON.readTree(new String(projection.canonicalBytes(), StandardCharsets.UTF_8)); + ObjectNode feedback = (ObjectNode) root.get("safeFeedback"); + ObjectNode definition = (ObjectNode) JSON.readTree(feedback.path("definitionJson").asText()); + definition.put("feedbackKey", "other_feedback"); + String definitionJson = GameplayRuleManifest.canonical(definition); + feedback.put("definitionJson", definitionJson); + feedback.put( + "definitionDigest", CommandSource.sha256(definitionJson.getBytes(StandardCharsets.UTF_8))); + feedback.put("key", "other_feedback"); + + assertRejected(canonicalize(CommandSource.canonical(root)), null); + } + + @Test + void projectionOmitsPrivateCommitTargetsAndPublicationCaptureBytes() { + var source = sourceBinding(); + var projection = AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, source); + String publicJson = new String(projection.canonicalBytes(), StandardCharsets.UTF_8); + + assertThat(publicJson) + .doesNotContain("private-owner-key") + .doesNotContain("publication operation bytes") + .doesNotContain("selected release evidence") + .doesNotContain("gameplay-rule-source-snapshot") + .doesNotContain("sourceBindingJson") + .doesNotContain("operationBytesBase64") + .doesNotContain("captureBytesBase64"); + assertThat(publicJson).contains(source.digest()); + } + + private static void assertRejected(byte[] bytes, String digest) { + String verifiedDigest = digest == null ? CommandSource.sha256(bytes) : digest; + assertThatThrownBy(() -> AuthoredInitialActorCoreProjection.fromStored(bytes, verifiedDigest)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static byte[] canonicalize(String json) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(json); + } catch (java.io.IOException malformed) { + throw new IllegalStateException("Invalid projection test JSON", malformed); + } + } + + private static String replaceLast(String value, String oldText, String newText) { + int index = value.lastIndexOf(oldText); + if (index < 0) throw new IllegalStateException("Expected test source text was absent"); + return value.substring(0, index) + newText + value.substring(index + oldText.length()); + } + + private static AuthoredInitialActorCoreProjection projection() { + return AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, sourceBinding()); + } + + private static AuthoredInitialActorCoreSourceBinding sourceBinding() { + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PLAYER_CREATED\",\"creationDescriptor\":{" + + "\"schemaVersion\":1,\"descriptorId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\"," + + "\"descriptorRevisionId\":\"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}", + JSON); + var policyPayload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r1", + "policy", + RealmPolicySource.tree(policy.canonicalJson()))); + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor_created", + Audience.SOURCE_ACTOR, + "welcome_message", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + GameplayRuleManifest.ReplayPolicy.EFFECT_IDEMPOTENT); + List revisions = + List.of( + new RevisionPayload( + "0", POLICY_REVISION, Owner.GAME_DESIGN_CONTROL_PLANE, policyPayload), + new RevisionPayload( + "1", + DISPOSITION_REVISION, + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(disposition)), + new RevisionPayload( + "2", + FEEDBACK_REVISION, + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(feedback))); + TargetProof target = + new TargetProof( + TENANT, VERSION, 23L, "private-owner-key", 42L, "private-owner-key", "NEW_GAME_ROW"); + DraftCommitBinding commit = + DraftCommitBinding.create( + target, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + COMMIT, + "base-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"), + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + VERSION.toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + var selectedPolicy = RealmPolicySource.revision(commit, revisions.getFirst()); + var policySnapshot = new RealmPolicySnapshot(commit, "1", List.of(selectedPolicy)); + var dispositionEntry = + new GameplayRuleSource.Entry( + Family.DISPOSITIONS, disposition, commit, "1", DISPOSITION_REVISION); + var feedbackEntry = + new GameplayRuleSource.Entry(Family.FEEDBACK, feedback, commit, "2", FEEDBACK_REVISION); + var gameplay = + new GameplayRuleSelectedSource( + gameplaySnapshot(commit, List.of(dispositionEntry, feedbackEntry))); + return AuthoredInitialActorCoreSourceBinding.resolveAll( + uuid("66666666-6666-4666-8666-666666666666"), + digest('a'), + "world", + "workflow-1", + bytes("publication operation bytes"), + bytes("selected release evidence"), + commit, + policySnapshot, + gameplay) + .getFirst(); + } + + private static AuthoredInitialActorCoreSourceBinding inheritedSourceBinding( + AuthoredInitialActorCoreSourceBinding origin) { + var selectedCommit = + DraftCommitBinding.create( + origin.selectedCommit().target(), + uuid("88888888-8888-4888-8888-888888888888"), + SELECTED_COMMIT, + origin.selectedCommit().commitId().toString(), + List.of( + new RevisionPayload( + "0", + uuid("77777777-7777-4777-8777-777777777778"), + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.deletePayload("obsolete-command"))), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + CommandSource.SCOPE, + VERSION.toString(), + CommandSource.SCOPE, + CommandSource.SCOPE_ID, + "0"))); + var policySnapshot = + new RealmPolicySnapshot(selectedCommit, "2", List.of(origin.policySource())); + var gameplaySnapshot = + new GameplayRuleSelectedSource( + gameplaySnapshot( + selectedCommit, List.of(origin.dispositionSource(), origin.safeFeedbackSource()))); + return AuthoredInitialActorCoreSourceBinding.resolveAll( + uuid("66666666-6666-4666-8666-666666666666"), + digest('a'), + "world", + "workflow-inherited", + bytes("publication operation bytes"), + bytes("selected release evidence"), + selectedCommit, + policySnapshot, + gameplaySnapshot) + .getFirst(); + } + + private static String gameplaySnapshot( + DraftCommitBinding binding, List entries) { + Map families = new java.util.LinkedHashMap<>(); + for (Family family : Family.values()) { + families.put( + family.name(), + entries.stream() + .filter(value -> value.family() == family) + .map(GameplayRuleSource.Entry::definition) + .toList()); + } + var manifest = + GameplayRuleManifest.fromStored( + GameplayRuleManifest.canonical( + Map.of("schema", GameplayRuleManifest.SCHEMA, "families", families))); + Map snapshot = new java.util.LinkedHashMap<>(); + snapshot.put("schema", "game-design-gameplay-rule-source-snapshot/v1"); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", "1"); + snapshot.put("inheritedCommitId", ""); + snapshot.put("genesisReceiptId", "77777777-7777-4777-8777-777777777777"); + snapshot.put("manifestJson", manifest.canonicalJson()); + snapshot.put( + "entries", + entries.stream() + .map( + entry -> + Map.of( + "family", entry.family().name(), + "definitionJson", GameplayRuleManifest.canonical(entry.definition()), + "sourceBindingJson", entry.sourceBinding().canonicalJson(), + "sourceBindingDigest", entry.sourceBinding().digest(), + "revisionOrder", entry.revisionOrder(), + "revisionId", entry.revisionId().toString())) + .toList()); + return CommandSource.canonical(snapshot); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java index acb7bce812..d99325b054 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java @@ -75,6 +75,38 @@ void initialAndExactReplayHaveClosedDeterministicRequestVectors() { assertThat(replayWire.getExactReplay().getAssociationDigest()).isEqualTo(digest('a')); } + @Test + void authoredCoreReadAcceptsOnlyTheCompletePinnedAssociationRequest() { + var replay = + request(new ExactReplay(VERSION, COMMIT, "template-publish-workflow-1", digest('a'))); + var typed = new AuthoredInitialActorCoreReadEvidence.ReadRequest(replay); + var wire = AuthoredInitialActorCoreReadGrpcCodec.toRequest(typed); + + assertThat(AuthoredInitialActorCoreReadGrpcCodec.fromRequest(wire).associationRequest()) + .isEqualTo(replay); + assertThatThrownBy( + () -> + new AuthoredInitialActorCoreReadEvidence.ReadRequest( + request(new InitialConfigured()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Exact pinned association replay"); + + var unknown = + wire.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1L) + .build()) + .build()) + .build(); + assertThatThrownBy(() -> AuthoredInitialActorCoreReadGrpcCodec.fromRequest(unknown)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + @Test void rejectsMissingSelectionUnknownFieldsNoncanonicalIdsAndChangedNamespace() { var valid = diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionLaunchReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionLaunchReadClientTest.java new file mode 100644 index 0000000000..d3f4a1e97e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/GrpcOriginalStartSessionLaunchReadClientTest.java @@ -0,0 +1,82 @@ +package net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.io.IOException; +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 org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GrpcOriginalStartSessionLaunchReadClientTest { + private GrpcOriginalStartSessionLaunchReadClient client; + + @AfterEach + void closeClientAndClearTransactionContext() throws Exception { + if (client != null) { + client.close(); + client = null; + } + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresFileBackedMtlsExplicitInitializationAndNoAmbientTransaction(@TempDir Path dir) + throws Exception { + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = fileBackedMtls(dir); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, factory, "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var request = OriginalStartSessionLaunchReadEvidenceTest.requestForClientTest(); + client = newClient(fileBackedMtls(dir), factory, request.selector().targetNamespace()); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient owner transaction"); + verifyNoInteractions(factory); + } + + @Test + void rejectsAnotherConfiguredNamespaceBeforeTransport(@TempDir Path dir) throws Exception { + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + var request = OriginalStartSessionLaunchReadEvidenceTest.requestForClientTest(); + String otherNamespace = + "other-runtime".equals(request.selector().targetNamespace()) + ? "different-runtime" + : "other-runtime"; + client = newClient(fileBackedMtls(dir), factory, otherNamespace); + + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(factory); + } + + private GrpcOriginalStartSessionLaunchReadClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory factory, String namespace) { + return new GrpcOriginalStartSessionLaunchReadClient( + new ServiceEndpointsProperties(), tls, factory, namespace); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws IOException { + 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/gamesession/OriginalStartSessionLaunchReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadEvidenceTest.java new file mode 100644 index 0000000000..c6692fd659 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionLaunchReadEvidenceTest.java @@ -0,0 +1,273 @@ +package net.firedevops.firemud.common.gamesession; + +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.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodecTest; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.Result; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.Test; + +class OriginalStartSessionLaunchReadEvidenceTest { + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID NEXT_READ_ID = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID GAME_INSTANCE_ID = uuid("03333333-3333-4333-8333-333333333333"); + private static final UUID PLAYABLE_NAMESPACE_ID = uuid("04444444-4444-4444-8444-444444444444"); + private static final UUID REALM_ID = uuid("05555555-5555-4555-8555-555555555555"); + + static OriginalStartSessionLaunchReadEvidence.Request requestForClientTest() throws Exception { + return fixture().request(); + } + + @Test + void requestAndResultNormalizeOnlyTheTransientSelectorReadId() throws Exception { + Fixture fixture = fixture(); + var nextSelector = selector(fixture.request().selector(), NEXT_READ_ID); + var nextRequest = + new OriginalStartSessionLaunchReadEvidence.Request(nextSelector, fixture.tupleBytes()); + var nextLaunch = launch(fixture.result().launch(), nextSelector); + var nextResult = + new OriginalStartSessionLaunchReadEvidence.Result( + nextRequest, nextLaunch, fixture.tupleBytes()); + + assertThat( + OriginalStartSessionLaunchReadEvidence.Request.decode( + fixture.request().canonicalBytes())) + .isEqualTo(fixture.request()); + assertThat(nextRequest.canonicalBytes()).isNotEqualTo(fixture.request().canonicalBytes()); + assertThat(nextRequest.operationIdentityBytes()) + .containsExactly(fixture.request().operationIdentityBytes()); + var originalSelector = fixture.request().selector(); + var changedSelector = + new Request( + originalSelector.readRequestId(), + originalSelector.targetNamespace(), + originalSelector.canonicalTenantId(), + originalSelector.worldSlug(), + originalSelector.gameInstanceUuid(), + originalSelector.controlPlaneRequestId(), + originalSelector.launchDescriptorId(), + originalSelector.expectedDescriptorRequestDigest(), + "sha256:" + "e".repeat(64), + originalSelector.expectedReleaseAttestationEvidenceDigest()); + var changedRequest = + new OriginalStartSessionLaunchReadEvidence.Request(changedSelector, fixture.tupleBytes()); + assertThat(changedRequest.operationIdentityBytes()) + .isNotEqualTo(fixture.request().operationIdentityBytes()); + assertThat( + OriginalStartSessionLaunchReadEvidence.Result.decode(fixture.result().canonicalBytes())) + .isEqualTo(fixture.result()); + assertThat(nextResult.canonicalBytes()).isNotEqualTo(fixture.result().canonicalBytes()); + assertThat(nextResult.operationIdentityBytes()) + .containsExactly(fixture.result().operationIdentityBytes()); + assertThat(nextResult.operationIdentityBytes()) + .isNotEqualTo( + new OriginalStartSessionLaunchReadEvidence.Result( + fixture.request(), + launch( + fixture.result().launch(), + selector( + fixture.request().selector(), + fixture.request().selector().readRequestId()), + fixture.result().launch().currentRowVersion() + 1L), + fixture.tupleBytes()) + .operationIdentityBytes()); + } + + @Test + void resultRejectsDifferentSelectorOrRetainedTuple() throws Exception { + Fixture fixture = fixture(); + byte[] changedTuple = fixture.tupleBytes().clone(); + changedTuple[changedTuple.length - 2] ^= 0x01; + + assertThatThrownBy( + () -> + new OriginalStartSessionLaunchReadEvidence.Result( + fixture.request(), fixture.result().launch(), changedTuple)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new OriginalStartSessionLaunchReadEvidence.Result( + new OriginalStartSessionLaunchReadEvidence.Request( + selector(fixture.request().selector(), NEXT_READ_ID), fixture.tupleBytes()), + fixture.result().launch(), + fixture.tupleBytes())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selector"); + } + + @Test + void grpcCodecRoundTripsTheFullTupleAndRejectsChangedEchoesAndUnknownFields() throws Exception { + Fixture fixture = fixture(); + var wireRequest = OriginalStartSessionLaunchReadGrpcCodec.toRequest(fixture.request()); + var wireResponse = OriginalStartSessionLaunchReadGrpcCodec.toResponse(fixture.result()); + + assertThat(OriginalStartSessionLaunchReadGrpcCodec.fromRequest(wireRequest)) + .isEqualTo(fixture.request()); + assertThat( + OriginalStartSessionLaunchReadGrpcCodec.fromResponse(fixture.request(), wireResponse)) + .isEqualTo(fixture.result()); + assertThat(wireResponse.getRetainedOriginalPostAuthorizationTupleBytes().toByteArray()) + .containsExactly(fixture.tupleBytes()); + + assertThatThrownBy( + () -> + OriginalStartSessionLaunchReadGrpcCodec.fromRequest( + wireRequest.toBuilder().setUnknownFields(unknown(91)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + OriginalStartSessionLaunchReadGrpcCodec.fromResponse( + fixture.request(), + wireResponse.toBuilder().setUnknownFields(unknown(92)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + OriginalStartSessionLaunchReadGrpcCodec.fromResponse( + fixture.request(), + wireResponse.toBuilder() + .setRetainedOriginalPostAuthorizationTupleBytes( + com.google.protobuf.ByteString.copyFromUtf8("different")) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static Fixture fixture() throws Exception { + var launchFixture = StartSessionLaunchDescriptorGrpcCodecTest.fixture(); + AuthoredWorldLaunchDescriptorEvidence descriptor = launchFixture.descriptor(); + var publishedLocation = launchFixture.associationRead().worldPublishedStartLocationEvidence(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + publishedLocation.request().appliedCommitId(), + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + publishedLocation.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + publishedLocation.request().publishWorkflowId(), + publishedLocation.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + publishedLocation); + var binding = new CompleteLaunchBindingEvidence(descriptor, release); + Request selector = + new Request( + READ_ID, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + GAME_INSTANCE_ID, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + Result launch = + new Result( + selector, + PLAYABLE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + REALM_ID, + 17L, + CurrentGameInstanceStatus.STARTING, + 12L, + binding); + byte[] tupleBytes = launchFixture.request().decodedTuple().canonicalBytes(); + var request = new OriginalStartSessionLaunchReadEvidence.Request(selector, tupleBytes); + return new Fixture( + request, + new OriginalStartSessionLaunchReadEvidence.Result(request, launch, tupleBytes), + tupleBytes); + } + + private static Request selector(Request original, UUID readRequestId) { + return new Request( + readRequestId, + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + original.gameInstanceUuid(), + original.controlPlaneRequestId(), + original.launchDescriptorId(), + original.expectedDescriptorRequestDigest(), + original.expectedDescriptorResultDigest(), + original.expectedReleaseAttestationEvidenceDigest()); + } + + private static Result launch(Result original, Request request) { + return launch(original, request, original.currentRowVersion()); + } + + private static Result launch(Result original, Request request, long rowVersion) { + return new Result( + request, + original.playableStateNamespaceId(), + original.playableStateScope(), + original.publicProduction(), + original.canonicalRealmId(), + original.catalogRevision(), + original.currentGameInstanceStatus(), + rowVersion, + original.launchBindingEvidence()); + } + + private static UnknownFieldSet unknown(int number) { + return UnknownFieldSet.newBuilder() + .addField(number, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + OriginalStartSessionLaunchReadEvidence.Request request, + OriginalStartSessionLaunchReadEvidence.Result result, + byte[] tupleBytes) { + private Fixture { + tupleBytes = tupleBytes.clone(); + } + + @Override + public byte[] tupleBytes() { + return tupleBytes.clone(); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/AccountStartSessionActivationProtectionEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/AccountStartSessionActivationProtectionEvidenceTest.java new file mode 100644 index 0000000000..4071ce60d6 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/AccountStartSessionActivationProtectionEvidenceTest.java @@ -0,0 +1,958 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.Test; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.json.JsonMapper; + +/** Structural integrity tests; fixtures establish no authenticated owner or live source lock. */ +class AccountStartSessionActivationProtectionEvidenceTest { + private static final UUID GAME_INSTANCE_ID = uuid("12121212-1212-4212-8212-121212121212"); + private static final UUID PLAYABLE_STATE_NAMESPACE_ID = + uuid("23232323-2323-4232-8232-232323232323"); + private static final UUID REALM_ID = uuid("34343434-3434-4343-8343-343434343434"); + private static final UUID GAME_SESSION_MUTATION = uuid("45454545-4545-4454-8454-454545454545"); + private static final UUID GAME_SESSION_ATTEMPT = uuid("56565656-5656-4565-8565-565656565656"); + private static final UUID ACCOUNT_PARTICIPATION = uuid("67676767-6767-4676-8676-676767676767"); + private static final UUID ACCOUNT_PROTECTION = uuid("78787878-7878-4878-8878-787878787878"); + private static final UUID ACTIVATION_ID = uuid("89898989-8989-4898-8898-898989898989"); + private static final Instant ORIGINAL_LEASE_EXPIRY = Instant.parse("2026-10-09T10:20:30.456789Z"); + private static final Instant ACQUIRED_AT = Instant.parse("2026-10-09T10:11:12.123Z"); + private static final UUID GS_READ_ID = uuid("90909090-9090-4090-8090-909090909090"); + private static final UUID WORLD_READ_ID = uuid("a1a1a1a1-a1a1-41a1-81a1-a1a1a1a1a1a1"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void acquisitionCodecRetainsTheCompleteFirstReceiptAcrossReadCorrelationRetries() + throws Exception { + Fixture fixture = fixture(); + var tuple = originalTuple(fixture); + var first = + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 0L, + CurrentGameInstanceStatus.STARTING); + var firstEvidence = + evidence( + first, + captureReference(tuple), + List.of(source(fixture.selector.canonicalTenantId(), "source"))); + var input = + new AccountStartSessionActivationProtectionAcquisitionInput( + tuple.canonicalBytes(), + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + first.gameSessionOwnerFence(), + first.worldActivationRequest()); + String namespace = fixture.selector.targetNamespace(); + var wire = + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toRequest(input, namespace); + var decoded = + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequestWireBytes( + wire.toByteArray(), namespace); + assertThat(decoded.originalPostAuthorizationTuple()).containsExactly(tuple.canonicalBytes()); + assertThat(decoded.worldActivationRequest().preparingEvidenceBytes()) + .containsExactly(first.worldActivationRequest().preparingEvidenceBytes()); + + var retry = + request( + fixture, + tuple, + UUID.randomUUID(), + UUID.randomUUID(), + ACTIVATION_ID, + 0L, + CurrentGameInstanceStatus.STARTING); + var retryInput = + new AccountStartSessionActivationProtectionAcquisitionInput( + tuple.canonicalBytes(), + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + first.gameSessionOwnerFence(), + retry.worldActivationRequest()); + var response = + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toResponse( + retryInput, namespace, firstEvidence); + var returned = + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromResponseWireBytes( + retryInput, namespace, response.toByteArray()); + assertThat(returned.canonicalBytes()).containsExactly(firstEvidence.canonicalBytes()); + assertThat(returned.request().worldActivationRequest().preparingEvidenceBytes()) + .containsExactly(first.worldActivationRequest().preparingEvidenceBytes()) + .isNotEqualTo(retry.worldActivationRequest().preparingEvidenceBytes()); + } + + @Test + void acquisitionCodecRejectsAChangedActivationOrOwnerAttempt() throws Exception { + Fixture fixture = fixture(); + var tuple = originalTuple(fixture); + var first = + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 0L, + CurrentGameInstanceStatus.STARTING); + var firstEvidence = + evidence( + first, + captureReference(tuple), + List.of(source(fixture.selector.canonicalTenantId(), "source"))); + String namespace = fixture.selector.targetNamespace(); + var differentActivation = + new AccountStartSessionActivationProtectionAcquisitionInput( + tuple.canonicalBytes(), + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + first.gameSessionOwnerFence(), + new WorldCanonicalInstanceActivation.Request( + UUID.randomUUID(), first.worldActivationRequest().preparing())); + var differentAttempt = + new AccountStartSessionActivationProtectionAcquisitionInput( + tuple.canonicalBytes(), + GAME_SESSION_MUTATION, + UUID.randomUUID(), + first.gameSessionOwnerFence(), + first.worldActivationRequest()); + for (var changed : List.of(differentActivation, differentAttempt)) { + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toResponse( + changed, namespace, firstEvidence)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact original activation acquisition binding"); + } + } + + @Test + void roundTripsFullOriginalLaunchPreparingAndAccountSourceEvidence() throws Exception { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(fixture); + AccountStartSessionActivationProtectionRequest request = + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING); + byte[] capture = captureReference(tuple); + SourceEvidence source = source(fixture.selector.canonicalTenantId(), "complete-source-before"); + AccountStartSessionActivationProtectionEvidence evidence = + evidence(request, capture, List.of(source)); + + AccountStartSessionActivationProtectionRequest decodedRequest = + AccountStartSessionActivationProtectionRequest.decode(request.canonicalBytes()); + AccountStartSessionActivationProtectionEvidence decodedEvidence = + AccountStartSessionActivationProtectionEvidence.decode(evidence.canonicalBytes()); + + assertThat(decodedRequest.canonicalBytes()).containsExactly(request.canonicalBytes()); + assertThat(request.requestDigest()) + .isEqualTo("sha256:" + sha256(request.operationIdentityBytes())); + assertThat(decodedRequest.gameSessionLaunchReadEvidence().canonicalBytes()) + .containsExactly(request.gameSessionLaunchReadEvidence().canonicalBytes()); + assertThat(decodedRequest.worldActivationRequest().preparingEvidenceBytes()) + .containsExactly(request.worldActivationRequest().preparingEvidenceBytes()); + assertThat(decodedRequest.originalPostAuthorizationTupleBytes()) + .containsExactly(tuple.canonicalBytes()); + assertThat(decodedEvidence.canonicalBytes()).containsExactly(evidence.canonicalBytes()); + assertThat(decodedEvidence.request()).isEqualTo(request); + assertThat(decodedEvidence.accountProtectionId()).isEqualTo(ACCOUNT_PROTECTION); + assertThat(decodedEvidence.accountProtectionFence()).isEqualTo(Long.MAX_VALUE); + assertThat(decodedEvidence.acquiredAt()).isEqualTo(ACQUIRED_AT); + assertThat(decodedEvidence.originalSourceCaptureReferenceBytes()).containsExactly(capture); + assertThat(decodedEvidence.originalSourceCaptureReferenceSha256()).isEqualTo(sha256(capture)); + assertThat(decodedEvidence.sourceEvidenceVector()) + .extracting(SourceEvidence::key) + .containsExactly("ACCOUNT:" + fixture.selector.canonicalTenantId()); + + byte[] escapedRequestBytes = request.canonicalBytes(); + escapedRequestBytes[0] ^= 1; + byte[] escapedCaptureBytes = evidence.originalSourceCaptureReferenceBytes(); + escapedCaptureBytes[0] ^= 1; + assertThat(request.canonicalBytes()).containsExactly(decodedRequest.canonicalBytes()); + assertThat(evidence.originalSourceCaptureReferenceBytes()).containsExactly(capture); + } + + @Test + void normalizesOnlyGameSessionAndWorldReadCorrelationIdsInRetryIdentity() throws Exception { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(fixture); + AccountStartSessionActivationProtectionRequest original = + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING); + AccountStartSessionActivationProtectionRequest retry = + request( + fixture, + tuple, + uuid("b2b2b2b2-b2b2-42b2-82b2-b2b2b2b2b2b2"), + uuid("c3c3c3c3-c3c3-43c3-83c3-c3c3c3c3c3c3"), + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING); + + assertThat(retry.operationIdentityBytes()).containsExactly(original.operationIdentityBytes()); + assertThat(retry.requestDigest()).isEqualTo(original.requestDigest()); + assertThat(retry.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); + assertThat(retry).isNotEqualTo(original); + + byte[] capture = captureReference(tuple); + var originalEvidence = + evidence( + original, capture, List.of(source(fixture.selector.canonicalTenantId(), "source"))); + var retryEvidence = + evidence(retry, capture, List.of(source(fixture.selector.canonicalTenantId(), "source"))); + assertThat(retryEvidence.operationIdentityBytes()) + .containsExactly(originalEvidence.operationIdentityBytes()); + assertThat(retryEvidence.requestDigest()).isEqualTo(originalEvidence.requestDigest()); + assertThat(retryEvidence.canonicalBytes()).isNotEqualTo(originalEvidence.canonicalBytes()); + } + + @Test + void substantiveTupleRowActivationAndSourceChangesChangeStableIdentity() throws Exception { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(fixture); + var original = + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING); + var changedRow = + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 8L, + CurrentGameInstanceStatus.STARTING); + var changedActivation = + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + uuid("d4d4d4d4-d4d4-44d4-84d4-d4d4d4d4d4d4"), + 7L, + CurrentGameInstanceStatus.STARTING); + var changedTuple = + request( + fixture, + originalTuple(fixture, "a different original audit reason"), + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING); + Fixture changedDescriptorFixture = fixture("another-launch-descriptor"); + var changedDescriptor = + request( + changedDescriptorFixture, + originalTuple(changedDescriptorFixture), + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING); + + assertThat(changedRow.operationIdentityBytes()).isNotEqualTo(original.operationIdentityBytes()); + assertThat(changedActivation.operationIdentityBytes()) + .isNotEqualTo(original.operationIdentityBytes()); + assertThat(changedTuple.operationIdentityBytes()) + .isNotEqualTo(original.operationIdentityBytes()); + assertThat(changedDescriptor.operationIdentityBytes()) + .isNotEqualTo(original.operationIdentityBytes()); + + byte[] capture = captureReference(tuple); + var originalEvidence = + evidence( + original, + capture, + List.of(source(fixture.selector.canonicalTenantId(), "source-before"))); + var changedSourceEvidence = + evidence( + original, + capture, + List.of(source(fixture.selector.canonicalTenantId(), "source-after"))); + assertThat(changedSourceEvidence.operationIdentityBytes()) + .isNotEqualTo(originalEvidence.operationIdentityBytes()); + } + + @Test + void rejectsSubstitutedProjectionLeaseOwnerStateCaptureAndCanonicalBytes() throws Exception { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(fixture); + byte[] projection = StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple); + byte[] substitutedProjection = projection.clone(); + substitutedProjection[substitutedProjection.length - 2] ^= 1; + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionRequest.create( + tuple.canonicalBytes(), + substitutedProjection, + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + 1L, + ORIGINAL_LEASE_EXPIRY, + ACCOUNT_PARTICIPATION, + 2L, + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING) + .gameSessionLaunchReadEvidence(), + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING) + .worldActivationRequest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("projection differs"); + + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionRequest.create( + tuple.canonicalBytes(), + projection, + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + 1L, + ORIGINAL_LEASE_EXPIRY.plusNanos(1), + ACCOUNT_PARTICIPATION, + 2L, + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING) + .gameSessionLaunchReadEvidence(), + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING) + .worldActivationRequest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("microsecond"); + + assertThatThrownBy( + () -> + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.RUNNING)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("STARTING"); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionRequest.create( + tuple.canonicalBytes(), + projection, + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + 1L, + ORIGINAL_LEASE_EXPIRY, + new UUID(0L, 0L), + 2L, + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING) + .gameSessionLaunchReadEvidence(), + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING) + .worldActivationRequest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + + var valid = + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING); + Map extra = readObject(valid.canonicalBytes()); + extra.put("unsupportedAuthority", "must not be retained"); + assertThatThrownBy( + () -> AccountStartSessionActivationProtectionRequest.decode(canonical(extra))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + byte[] noncanonical = Arrays.copyOf(valid.canonicalBytes(), valid.canonicalBytes().length + 1); + noncanonical[noncanonical.length - 1] = (byte) ' '; + assertThatThrownBy(() -> AccountStartSessionActivationProtectionRequest.decode(noncanonical)) + .isInstanceOf(IllegalArgumentException.class); + + var malformedEvidence = + evidence( + valid, + captureReference(tuple), + List.of(source(fixture.selector.canonicalTenantId(), "source"))); + Map extraEvidenceField = readObject(malformedEvidence.canonicalBytes()); + extraEvidenceField.put("unsupported", "field"); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionEvidence.decode( + canonical(extraEvidenceField))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + request( + fixture, + originalTuple(fixture, "another-world-runtime", "namespace substitution"), + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void acceptsTheActualFreshStartingLaunchAtRowVersionZero() throws Exception { + Fixture fixture = fixture(); + var request = + request( + fixture, + originalTuple(fixture), + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 0L, + CurrentGameInstanceStatus.STARTING); + assertThat(request.gameSessionLaunchReadEvidence().launch().currentRowVersion()).isZero(); + assertThat( + AccountStartSessionActivationProtectionRequest.decode(request.canonicalBytes()) + .canonicalBytes()) + .containsExactly(request.canonicalBytes()); + } + + @Test + void rejectsChangedCaptureAndAcquisitionAfterOriginalLease() throws Exception { + Fixture fixture = fixture(); + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(fixture); + var request = + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING); + byte[] capture = captureReference(tuple); + SourceEvidence source = source(fixture.selector.canonicalTenantId(), "source"); + assertThatThrownBy(() -> evidence(request, capture, List.of(source), ORIGINAL_LEASE_EXPIRY)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("before the original lease expires"); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + 1L, + ACQUIRED_AT, + capture, + "0".repeat(64), + List.of(source))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest differs"); + Map malformed = readObject(capture); + malformed.put("controlPlaneRequestId", "another-original-request"); + byte[] wrongCapture = canonical(malformed); + assertThatThrownBy( + () -> + AccountStartSessionActivationProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + 1L, + ACQUIRED_AT, + wrongCapture, + sha256(wrongCapture), + List.of(source))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("another original request"); + } + + private static AccountStartSessionActivationProtectionEvidence evidence( + AccountStartSessionActivationProtectionRequest request, + byte[] capture, + List sources) { + return evidence(request, capture, sources, ACQUIRED_AT); + } + + private static AccountStartSessionActivationProtectionEvidence evidence( + AccountStartSessionActivationProtectionRequest request, + byte[] capture, + List sources, + Instant acquiredAt) { + return AccountStartSessionActivationProtectionEvidence.create( + request, ACCOUNT_PROTECTION, Long.MAX_VALUE, acquiredAt, capture, sha256(capture), sources); + } + + private static AccountStartSessionActivationProtectionRequest request( + Fixture fixture, + StartSessionPostAuthorizationExecutionTuple tuple, + UUID gsReadId, + UUID worldReadId, + UUID activationId, + long gameSessionRowVersion, + CurrentGameInstanceStatus status) { + var gsRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + gsReadId, + fixture.selector.targetNamespace(), + fixture.selector.canonicalTenantId(), + fixture.selector.worldSlug(), + fixture.selector.gameInstanceUuid(), + fixture.selector.controlPlaneRequestId(), + fixture.selector.launchDescriptorId(), + fixture.selector.expectedDescriptorRequestDigest(), + fixture.selector.expectedDescriptorResultDigest(), + fixture.selector.expectedReleaseAttestationEvidenceDigest()); + var gsResult = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + gsRequest, + fixture.launch.playableStateNamespaceId(), + fixture.launch.playableStateScope(), + fixture.launch.publicProduction(), + fixture.launch.canonicalRealmId(), + fixture.launch.catalogRevision(), + status, + gameSessionRowVersion, + fixture.binding); + var launchRequest = + new OriginalStartSessionLaunchReadEvidence.Request(gsRequest, tuple.canonicalBytes()); + var launchEvidence = + new OriginalStartSessionLaunchReadEvidence.Result( + launchRequest, gsResult, tuple.canonicalBytes()); + + var oldRequest = fixture.preparing.request(); + var worldRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + oldRequest.schemaVersion(), + worldReadId, + oldRequest.targetNamespace(), + oldRequest.canonicalTenantId(), + oldRequest.worldSlug(), + oldRequest.canonicalGameInstanceId(), + oldRequest.playableStateNamespaceId(), + oldRequest.playableStateScope(), + oldRequest.publicProduction(), + oldRequest.controlPlaneRequestId(), + oldRequest.canonicalVersionId(), + oldRequest.expectedDescriptorRequestDigest(), + oldRequest.expectedDescriptorResultDigest(), + oldRequest.expectedReleaseAttestationDigest()); + var preparing = + new WorldCanonicalInstanceLifecycleEvidence( + worldRequest, + fixture.preparing.launchBinding(), + fixture.preparing.startLocation(), + fixture.preparing.runtimeRoomInstanceId(), + fixture.preparing.lifecycleStatus(), + fixture.preparing.lifecycleEpoch(), + fixture.preparing.rowVersion(), + fixture.preparing.captureId(), + fixture.preparing.graphSha256(), + fixture.preparing.preparationInputDigest(), + fixture.preparing.operationalRegionAssignments()); + var activation = new WorldCanonicalInstanceActivation.Request(activationId, preparing); + + return AccountStartSessionActivationProtectionRequest.create( + tuple.canonicalBytes(), + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + Long.MAX_VALUE, + ORIGINAL_LEASE_EXPIRY, + ACCOUNT_PARTICIPATION, + Long.MAX_VALUE, + launchEvidence, + activation); + } + + private static Fixture fixture() throws Exception { + return fixture("activation-test-launch-descriptor"); + } + + private static Fixture fixture(String launchDescriptorId) throws Exception { + WorldPublishedStartLocationEvidence selected = + WorldPublishedStartLocationGrpcCodecTest.evidence(); + var selectedRequest = selected.request(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selectedRequest.targetNamespace(), + "activation-original-request", + selectedRequest.canonicalTenantId(), + "activation-test-world", + uuid("abababab-abab-4bab-8bab-abababababab"), + "sha256:" + "1".repeat(64), + 91L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + launchDescriptorId, + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selectedRequest.appliedCommitId(), + selectedRequest.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "2".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selectedRequest.canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selectedRequest.publishWorkflowId(), + selectedRequest.appliedCommitId(), + participants, + "sha256:" + "3".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selected); + CompleteLaunchBindingEvidence binding = new CompleteLaunchBindingEvidence(descriptor, release); + WorldDraftStartLocationEvidence selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selected.selectorReceiptBytes()); + UUID activationReadId = WORLD_READ_ID; + var worldRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + activationReadId, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + GAME_INSTANCE_ID, + PLAYABLE_STATE_NAMESPACE_ID, + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + WorldCanonicalInstanceLifecycleEvidence preparing = + new WorldCanonicalInstanceLifecycleEvidence( + worldRequest, + binding, + selectorReceipt.startLocation(), + 1042L, + "PREPARING", + 3L, + 0L, + uuid("bcbcbcbc-bcbc-4bcb-8bcb-bcbcbcbcbcbc"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "4".repeat(64), + Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + var gsRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + GS_READ_ID, + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + GAME_INSTANCE_ID, + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var gsResult = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + gsRequest, + PLAYABLE_STATE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + REALM_ID, + 17L, + CurrentGameInstanceStatus.STARTING, + 7L, + binding); + return new Fixture(gsRequest, gsResult, binding, preparing); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(Fixture fixture) { + return originalTuple(fixture, "original StartSession activation attempt"); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple( + Fixture fixture, String auditReason) { + return originalTuple(fixture, fixture.selector.targetNamespace(), auditReason); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple( + Fixture fixture, String namespace, String auditReason) { + var request = fixture.selector; + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "activation-original-request", + uuid("a4f5f4eb-8243-4d42-903a-33495456a622"), + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(request.canonicalTenantId(), namespace), + new StartSessionOperatorAction.Target( + fixture.binding.descriptor().gameTemplateId(), + uuid("dededede-dede-4ede-8ede-dededededede")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + auditReason)); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "5".repeat(64), + uuid("efefefef-efef-4fef-8fef-efefefefefef"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = tuple.action().scope().tenantId().toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", "a4f5f4eb-8243-4d42-903a-33495456a622", + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenant, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + "a4f5f4eb-8243-4d42-903a-33495456a622", + "applicableTenantId", + tenant), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence); + return canonical(bundle); + } + + private static SourceEvidence source(UUID tenant, String sourceValue) { + return new SourceEvidence( + SourceKind.ACCOUNT, + tenant.toString(), + "2", + "17", + null, + null, + sourceValue.getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static byte[] captureReference(StartSessionPostAuthorizationExecutionTuple tuple) { + return canonical( + Map.of( + "schema", "account-start-session-authority-capture/v1", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "capturedAt", "2026-10-09T10:11:12.123Z", + "bundleReference", + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "sourceVersion", tuple.bundleReference().sourceVersion(), + "sourceFence", tuple.bundleReference().sourceFence(), + "linearization", tuple.bundleReference().linearization()), + "snapshotSha256", "6".repeat(64))); + } + + private static Map readObject(byte[] bytes) throws IOException { + return JSON.readValue(bytes, new TypeReference<>() {}); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector, + CanonicalGameInstanceLaunchAssociationReadEvidence.Result launch, + CompleteLaunchBindingEvidence binding, + WorldCanonicalInstanceLifecycleEvidence preparing) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClientTest.java new file mode 100644 index 0000000000..b0c558ac3d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClientTest.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +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; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * mTLS configuration denial checks only; no live World endpoint or authenticated peer is implied. + */ +class GrpcWorldOriginalStartSessionActivationTerminalReadClientTest { + @Test + void requiresExplicitFileBackedMtlsBeforeAnyTransport(@TempDir Path directory) throws Exception { + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = fileBacked(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcWorldOriginalStartSessionActivationTerminalReadClient( + new ServiceEndpointsProperties(), plaintext, factory, "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + CommonGrpcClientProperties classpath = new CommonGrpcClientProperties(); + classpath.setCertChain("classpath:client.crt"); + classpath.setPrivateKey("/tmp/key"); + classpath.setCaCert("/tmp/ca"); + assertThatThrownBy( + () -> + new GrpcWorldOriginalStartSessionActivationTerminalReadClient( + new ServiceEndpointsProperties(), classpath, factory, "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + verifyNoInteractions(factory); + } + + @Test + void requiresExplicitInitializationAndNoAmbientAccountSql(@TempDir Path directory) + throws Exception { + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + var evidence = + mock( + AccountStartSessionActivationProtectionEvidence.class, + org.mockito.Mockito.withSettings() + .defaultAnswer(org.mockito.Mockito.RETURNS_DEEP_STUBS)); + when(evidence + .request() + .originalTuple() + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace()) + .thenReturn("world-runtime"); + var input = + new WorldOriginalStartSessionActivationTerminalReadInput(UUID.randomUUID(), evidence); + var client = + new GrpcWorldOriginalStartSessionActivationTerminalReadClient( + new ServiceEndpointsProperties(), fileBacked(directory), factory, "world-runtime"); + try { + assertThatThrownBy(() -> client.read(input)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(input)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient Account transaction"); + verifyNoInteractions(factory); + } finally { + TransactionSynchronizationManager.clear(); + client.close(); + } + } + + private static CommonGrpcClientProperties fileBacked(Path directory) throws IOException { + 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/world/GrpcWorldOriginalStartSessionProtectedActivationClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClientTest.java new file mode 100644 index 0000000000..fa52de1e2d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClientTest.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +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; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** File-backed mTLS/client lifecycle denial checks only; no live World endpoint is implied. */ +class GrpcWorldOriginalStartSessionProtectedActivationClientTest { + @Test + void requiresExplicitFileBackedMtlsBeforeAnyTransport(@TempDir Path directory) throws Exception { + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = fileBacked(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcWorldOriginalStartSessionProtectedActivationClient( + new ServiceEndpointsProperties(), plaintext, factory, "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + CommonGrpcClientProperties classpath = new CommonGrpcClientProperties(); + classpath.setCertChain("classpath:client.crt"); + classpath.setPrivateKey("/tmp/key"); + classpath.setCaCert("/tmp/ca"); + assertThatThrownBy( + () -> + new GrpcWorldOriginalStartSessionProtectedActivationClient( + new ServiceEndpointsProperties(), classpath, factory, "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + verifyNoInteractions(factory); + } + + @Test + void requiresInitializationAndNoAmbientGameSessionTransaction(@TempDir Path directory) + throws Exception { + GrpcChannelFactory factory = mock(GrpcChannelFactory.class); + var input = mock(AccountStartSessionActivationProtectionAcquisitionInput.class); + var client = + new GrpcWorldOriginalStartSessionProtectedActivationClient( + new ServiceEndpointsProperties(), fileBacked(directory), factory, "world-runtime"); + try { + doNothing().when(input).requireTargetNamespace("world-runtime"); + assertThatThrownBy(() -> client.activate(input)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.activate(input)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient Game Session transaction"); + verifyNoInteractions(factory); + } finally { + TransactionSynchronizationManager.clear(); + client.close(); + } + } + + private static CommonGrpcClientProperties fileBacked(Path directory) throws IOException { + 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/world/WorldOriginalStartSessionActivationTerminalEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalEvidenceTest.java new file mode 100644 index 0000000000..77ec920e5b --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalEvidenceTest.java @@ -0,0 +1,507 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +/** Integrity and exact-copy tests; no authenticated producer or committed database is implied. */ +class WorldOriginalStartSessionActivationTerminalEvidenceTest { + private static final UUID ACCOUNT_PROTECTION = uuid("78787878-7878-4878-8878-787878787878"); + private static final UUID ACTIVATION_ID = uuid("89898989-8989-4898-8898-898989898989"); + private static final long ACCOUNT_FENCE = 19L; + private static final long WORLD_FENCE = 23L; + private static final Instant LEASE = Instant.parse("2026-10-09T10:20:30.456789Z"); + private static final Instant ACQUIRED = Instant.parse("2026-10-09T10:11:12.123Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void roundTripsFullAccountProtectionAndBothExactWorldTerminalOutcomes() throws Exception { + Fixture fixture = fixture(); + var request = accountRequest(fixture); + byte[] capture = captureReference(originalTuple(fixture)); + var protection = + AccountStartSessionActivationProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + ACCOUNT_FENCE, + ACQUIRED, + capture, + sha256(capture), + List.of(source(fixture.launchRequest().canonicalTenantId()))); + + var active = nextActive(request.worldActivationRequest().preparing()); + var committedResult = + new WorldCanonicalInstanceActivation.Result( + request.worldActivationRequest(), + WorldCanonicalInstanceActivation.Outcome.COMMITTED, + null, + active); + var committed = + WorldOriginalStartSessionActivationTerminalEvidence.create( + protection, committedResult, WORLD_FENCE); + var decodedCommitted = + WorldOriginalStartSessionActivationTerminalEvidence.decode(committed.canonicalBytes()); + + assertThat(decodedCommitted.canonicalBytes()).containsExactly(committed.canonicalBytes()); + assertThat(decodedCommitted.accountProtectionEvidence().canonicalBytes()) + .containsExactly(protection.canonicalBytes()); + assertThat(decodedCommitted.activationResult().canonicalBytes()) + .containsExactly(committedResult.canonicalBytes()); + assertThat(decodedCommitted.activationResult().request().preparingEvidenceBytes()) + .containsExactly(request.worldActivationRequest().preparingEvidenceBytes()); + assertThat(decodedCommitted.worldActivationFence()).isEqualTo(WORLD_FENCE); + assertThat(decodedCommitted.outcome()) + .isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + + var abortedResult = + new WorldCanonicalInstanceActivation.Result( + request.worldActivationRequest(), + WorldCanonicalInstanceActivation.Outcome.ABORTED, + "POSITIVE_FENCED_ABORT", + request.worldActivationRequest().preparing()); + var aborted = + WorldOriginalStartSessionActivationTerminalEvidence.create( + protection, abortedResult, WORLD_FENCE + 1L); + var decodedAborted = + WorldOriginalStartSessionActivationTerminalEvidence.decode(aborted.canonicalBytes()); + assertThat(decodedAborted.canonicalBytes()).containsExactly(aborted.canonicalBytes()); + assertThat(decodedAborted.outcome()) + .isEqualTo(WorldCanonicalInstanceActivation.Outcome.ABORTED); + assertThat(decodedAborted.activationResult().terminalCode()).isEqualTo("POSITIVE_FENCED_ABORT"); + } + + @Test + void rejectsMissingFenceChangedResultAndAlteredReceiptIdentity() throws Exception { + Fixture fixture = fixture(); + var request = accountRequest(fixture); + byte[] capture = captureReference(originalTuple(fixture)); + var protection = + AccountStartSessionActivationProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + ACCOUNT_FENCE, + ACQUIRED, + capture, + sha256(capture), + List.of(source(fixture.launchRequest().canonicalTenantId()))); + var committed = + new WorldCanonicalInstanceActivation.Result( + request.worldActivationRequest(), + WorldCanonicalInstanceActivation.Outcome.COMMITTED, + null, + nextActive(request.worldActivationRequest().preparing())); + + assertThatThrownBy( + () -> + WorldOriginalStartSessionActivationTerminalEvidence.create( + protection, committed, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("positive"); + var changedRequest = + new WorldCanonicalInstanceActivation.Request( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request.worldActivationRequest().preparing()); + var substitutedResult = + new WorldCanonicalInstanceActivation.Result( + changedRequest, + WorldCanonicalInstanceActivation.Outcome.COMMITTED, + null, + nextActive(changedRequest.preparing())); + assertThatThrownBy( + () -> + WorldOriginalStartSessionActivationTerminalEvidence.create( + protection, substitutedResult, WORLD_FENCE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs from the original Account-protected"); + + byte[] exact = + WorldOriginalStartSessionActivationTerminalEvidence.create( + protection, committed, WORLD_FENCE) + .canonicalBytes(); + var root = JSON.readValue(exact, Map.class); + root.put("accountProtectionId", "99999999-9999-4999-8999-999999999999"); + byte[] forgedIdentity = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + assertThatThrownBy( + () -> WorldOriginalStartSessionActivationTerminalEvidence.decode(forgedIdentity)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("identity differs"); + } + + private static WorldCanonicalInstanceLifecycleEvidence nextActive( + WorldCanonicalInstanceLifecycleEvidence preparing) { + return new WorldCanonicalInstanceLifecycleEvidence( + preparing.request(), + preparing.launchBinding(), + preparing.startLocation(), + preparing.runtimeRoomInstanceId(), + "ACTIVE", + preparing.lifecycleEpoch() + 1L, + preparing.rowVersion() + 1L, + preparing.captureId(), + preparing.graphSha256(), + preparing.preparationInputDigest(), + preparing.operationalRegionAssignments()); + } + + private static AccountStartSessionActivationProtectionRequest accountRequest(Fixture fixture) { + var tuple = originalTuple(fixture); + var original = fixture.preparing().request(); + var gsRequest = fixture.launchRequest(); + var gsResult = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + gsRequest, + fixture.playableNamespaceId(), + RealmEntryPolicy.StateScope.SHARED, + true, + fixture.realmId(), + fixture.catalogRevision(), + CurrentGameInstanceStatus.STARTING, + 0L, + fixture.binding()); + var launchRequest = + new OriginalStartSessionLaunchReadEvidence.Request(gsRequest, tuple.canonicalBytes()); + var launchRead = + new OriginalStartSessionLaunchReadEvidence.Result( + launchRequest, gsResult, tuple.canonicalBytes()); + var worldRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + original.schemaVersion(), + uuid("a1a1a1a1-a1a1-41a1-81a1-a1a1a1a1a1a1"), + original.targetNamespace(), + original.canonicalTenantId(), + original.worldSlug(), + original.canonicalGameInstanceId(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.publicProduction(), + original.controlPlaneRequestId(), + original.canonicalVersionId(), + original.expectedDescriptorRequestDigest(), + original.expectedDescriptorResultDigest(), + original.expectedReleaseAttestationDigest()); + var preparing = + new WorldCanonicalInstanceLifecycleEvidence( + worldRequest, + fixture.preparing().launchBinding(), + fixture.preparing().startLocation(), + fixture.preparing().runtimeRoomInstanceId(), + "PREPARING", + fixture.preparing().lifecycleEpoch(), + 0L, + fixture.preparing().captureId(), + fixture.preparing().graphSha256(), + fixture.preparing().preparationInputDigest(), + fixture.preparing().operationalRegionAssignments()); + var worldActivation = new WorldCanonicalInstanceActivation.Request(ACTIVATION_ID, preparing); + return AccountStartSessionActivationProtectionRequest.create( + tuple.canonicalBytes(), + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + uuid("45454545-4545-4454-8454-454545454545"), + uuid("56565656-5656-4565-8565-565656565656"), + 11L, + LEASE, + uuid("67676767-6767-4676-8676-676767676767"), + 13L, + launchRead, + worldActivation); + } + + private static Fixture fixture() throws Exception { + var selected = WorldPublishedStartLocationGrpcCodecTest.evidence(); + var selector = selected.request(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + selector.targetNamespace(), + "terminal-evidence-control-request", + selector.canonicalTenantId(), + "terminal-evidence-world", + uuid("abababab-abab-4bab-8bab-abababababab"), + "sha256:" + "1".repeat(64), + 91L, + false, + null, + false, + null, + false, + null, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "terminal-evidence-launch", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "release-bundle", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.appliedCommitId(), + selector.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "2".repeat(64) : null)) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.publishWorkflowId(), + selector.appliedCommitId(), + participants, + "sha256:" + "3".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selected); + var binding = new CompleteLaunchBindingEvidence(descriptor, release); + var selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selected.selectorReceiptBytes()); + var worldRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + uuid("90909090-9090-4090-8090-909090909090"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + uuid("12121212-1212-4212-8212-121212121212"), + uuid("23232323-2323-4232-8232-232323232323"), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + release.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var preparing = + new WorldCanonicalInstanceLifecycleEvidence( + worldRequest, + binding, + selectorReceipt.startLocation(), + 1042L, + "PREPARING", + 3L, + 0L, + uuid("bcbcbcbc-bcbc-4bcb-8bcb-bcbcbcbcbcbc"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "4".repeat(64), + Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + var gsRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + uuid("a2a2a2a2-a2a2-42a2-82a2-a2a2a2a2a2a2"), + descriptor.targetNamespace(), + descriptor.canonicalTenantId(), + descriptor.worldSlug(), + worldRequest.canonicalGameInstanceId(), + descriptor.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + return new Fixture( + preparing, + binding, + gsRequest, + uuid("23232323-2323-4232-8232-232323232323"), + uuid("34343434-3434-4343-8343-343434343434"), + 17L); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(Fixture fixture) { + var request = fixture.launchRequest(); + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + request.controlPlaneRequestId(), + uuid("a4f5f4eb-8243-4d42-903a-33495456a622"), + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope( + request.canonicalTenantId(), request.targetNamespace()), + new StartSessionOperatorAction.Target( + fixture.binding().descriptor().gameTemplateId(), + uuid("dededede-dede-4ede-8ede-dededededede")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "World activation terminal evidence fixture")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + request.targetNamespace() + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "5".repeat(64), + uuid("efefefef-efef-4fef-8fef-efefefefefef"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String tenant = tuple.action().scope().tenantId().toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()); + Map issuance = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", "a4f5f4eb-8243-4d42-903a-33495456a622", + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map scope = + Map.of( + "scope", + Map.of("tenantId", tenant, "targetNamespace", tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + "a4f5f4eb-8243-4d42-903a-33495456a622", + "applicableTenantId", + tenant); + return canonical( + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", scope, + "accountProjectionEvidence", projection, + "issuanceOperationIdentity", operation, + "issuanceKind", "human_operator", + "authorityTuple", authority, + "membershipVersion", Map.of(tenant, 5L), + "issuanceFence", "23", + "issuanceEvidence", issuance)); + } + + private static byte[] captureReference(StartSessionPostAuthorizationExecutionTuple tuple) { + return canonical( + Map.of( + "schema", "account-start-session-authority-capture/v1", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "capturedAt", "2026-10-09T10:11:12.123Z", + "bundleReference", + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "sourceVersion", tuple.bundleReference().sourceVersion(), + "sourceFence", tuple.bundleReference().sourceFence(), + "linearization", tuple.bundleReference().linearization()), + "snapshotSha256", "6".repeat(64))); + } + + private static SourceEvidence source(UUID tenant) { + return new SourceEvidence( + SourceKind.ACCOUNT, + tenant.toString(), + "2", + "17", + null, + null, + "activation-source-snapshot".getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + WorldCanonicalInstanceLifecycleEvidence preparing, + CompleteLaunchBindingEvidence binding, + CanonicalGameInstanceLaunchAssociationReadEvidence.Request launchRequest, + UUID playableNamespaceId, + UUID realmId, + long catalogRevision) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..f0f7f806e0 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodecTest.java @@ -0,0 +1,44 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalStartSessionActivationTerminalEvidenceRequest; +import org.junit.jupiter.api.Test; + +/** Closed-envelope denial tests; no authenticated World producer or physical receipt is implied. */ +class WorldOriginalStartSessionActivationTerminalReadGrpcCodecTest { + @Test + void rejectsDuplicateFieldsBeforeEvidenceDecoding() { + var duplicate = + ReadOriginalStartSessionActivationTerminalEvidenceRequest.newBuilder() + .addSchemaVersion(1) + .addSchemaVersion(1) + .build(); + + assertThatThrownBy( + () -> + WorldOriginalStartSessionActivationTerminalReadGrpcCodec.fromRequest( + duplicate, "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate field"); + } + + @Test + void rejectsUnknownFieldsBeforeEvidenceDecoding() { + var unknown = + ReadOriginalStartSessionActivationTerminalEvidenceRequest.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + + assertThatThrownBy( + () -> + WorldOriginalStartSessionActivationTerminalReadGrpcCodec.fromRequest( + unknown, "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodecTest.java new file mode 100644 index 0000000000..03f5190f44 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodecTest.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.common.world; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +import net.firedevops.firemud.worldmanagement.v1.ActivateOriginalStartSessionProtectedRequest; +import net.firedevops.firemud.worldmanagement.v1.ActivateOriginalStartSessionProtectedResponse; +import org.junit.jupiter.api.Test; + +/** + * Closed-envelope tests; mock inputs do not prove authenticated acquisition or a terminal write. + */ +class WorldOriginalStartSessionProtectedActivationGrpcCodecTest { + @Test + void outerCarrierPreservesTheCompleteAccountAcquisitionRequestWithoutNarrowing() { + var input = mockInput(); + var nested = + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toRequest( + input, "world-runtime"); + + var request = + WorldOriginalStartSessionProtectedActivationGrpcCodec.toRequest(input, "world-runtime"); + + assertThat(request.getSchemaVersionList()).containsExactly(1); + assertThat(request.getTargetNamespaceList()).containsExactly("world-runtime"); + assertThat(request.getAcquisitionInputList()).containsExactly(nested); + assertThat(request.getSerializedSize()) + .isLessThanOrEqualTo( + WorldOriginalStartSessionProtectedActivationGrpcCodec.MAX_REQUEST_WIRE_BYTES); + } + + @Test + void rejectsDuplicateUnknownOrMissingOuterFieldsBeforeInputUse() { + var nested = + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toRequest( + mockInput(), "world-runtime"); + var duplicate = + ActivateOriginalStartSessionProtectedRequest.newBuilder() + .addSchemaVersion(1) + .addSchemaVersion(1) + .addTargetNamespace("world-runtime") + .addAcquisitionInput(nested) + .build(); + assertThatThrownBy( + () -> + WorldOriginalStartSessionProtectedActivationGrpcCodec.fromRequest( + duplicate, "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate"); + + var unknown = + ActivateOriginalStartSessionProtectedRequest.newBuilder() + .addSchemaVersion(1) + .addTargetNamespace("world-runtime") + .addAcquisitionInput(nested) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + assertThatThrownBy( + () -> + WorldOriginalStartSessionProtectedActivationGrpcCodec.fromRequest( + unknown, "world-runtime")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + assertThatThrownBy( + () -> + WorldOriginalStartSessionProtectedActivationGrpcCodec.fromRequest( + ActivateOriginalStartSessionProtectedRequest.getDefaultInstance(), + "world-runtime")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMissingResponseReceiptAndOversizedResponseCarrier() { + var empty = + ActivateOriginalStartSessionProtectedResponse.newBuilder().addSchemaVersion(1).build(); + assertThatThrownBy( + () -> + WorldOriginalStartSessionProtectedActivationGrpcCodec.fromResponse( + mockInput(), "world-runtime", empty)) + .isInstanceOf(IllegalArgumentException.class); + + assertThat(WorldOriginalStartSessionProtectedActivationGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .isEqualTo(WorldOriginalStartSessionActivationTerminalEvidence.MAX_CANONICAL_BYTES + 64); + } + + private static AccountStartSessionActivationProtectionAcquisitionInput mockInput() { + var input = mock(AccountStartSessionActivationProtectionAcquisitionInput.class); + var activation = mock(WorldCanonicalInstanceActivation.Request.class); + doNothing().when(input).requireTargetNamespace("world-runtime"); + when(input.originalPostAuthorizationTuple()).thenReturn(new byte[] {1, 2, 3}); + when(input.gameSessionOwnerMutationId()) + .thenReturn(UUID.fromString("11111111-1111-4111-8111-111111111111")); + when(input.gameSessionOwnerAttemptId()) + .thenReturn(UUID.fromString("22222222-2222-4222-8222-222222222222")); + when(input.gameSessionOwnerFence()).thenReturn(3L); + when(input.worldActivationRequest()).thenReturn(activation); + when(activation.activationRequestId()) + .thenReturn(UUID.fromString("33333333-3333-4333-8333-333333333333")); + when(activation.preparingEvidenceBytes()).thenReturn(new byte[] {4, 5, 6}); + return input; + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceService.java new file mode 100644 index 0000000000..22a8e3b96b --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceService.java @@ -0,0 +1,216 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Entity consumer for Game Design's independently authenticated authored-core read. + */ +public final class EntityRetainedAuthoredActorCoreSourceService { + private static final String ENTITY_RELEASE_SCHEMA = + "v" + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; + + private final String configuredNamespace; + private final AuthoredInitialActorCoreReadClient gameDesignClient; + private final EntityEmptySelectedSourceIntakeRepository repository; + + public EntityRetainedAuthoredActorCoreSourceService( + String configuredNamespace, + AuthoredInitialActorCoreReadClient gameDesignClient, + EntityEmptySelectedSourceIntakeRepository repository) { + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("Configured Entity namespace is required"); + } + this.configuredNamespace = configuredNamespace; + this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + } + + /** + * Obtains the exact already-pinned read directly from Game Design, then corroborates it against + * Entity's retained selected source and the immutable Entity participant in that selected + * release. The returned object is the unchanged public result from the authenticated client. + */ + public AuthoredInitialActorCoreReadEvidence.ReadResult read( + AuthoredInitialActorCoreReadEvidence.ReadRequest request) { + Objects.requireNonNull(request, "authored-core read request is required"); + requireNoAmbientOwnerSql(); + + Request associationRequest = request.associationRequest(); + if (!configuredNamespace.equals(associationRequest.targetNamespace()) + || !(associationRequest.selection() instanceof ExactReplay)) { + throw denied("Exact same-namespace pinned Game Design read is required"); + } + + // This is a direct workload-authenticated read. No Entity owner transaction may surround it. + AuthoredInitialActorCoreReadEvidence.ReadResult publicResult = gameDesignClient.read(request); + if (publicResult == null || !associationRequest.equals(publicResult.request())) { + throw denied("Game Design authored-core read differs from the exact original request"); + } + Result associationRead = publicResult.associationRead(); + if (associationRead == null || !associationRequest.equals(associationRead.request())) { + throw denied("Game Design association read differs from the exact original request"); + } + + Association association = associationRead.association(); + PublishedReleaseBundle release = associationRead.releaseBundle(); + if (association == null || release == null) { + throw denied("Game Design selected association or release is unavailable"); + } + if (release.getVersionId() <= 0L) { + throw denied("Selected release has no canonical Version row"); + } + + // COMMITTED_EMPTY is only Entity's pre-publication source receipt. The public Game Design read + // remains the independent authored-core evidence; this receipt only correlates its selection. + // The repository resolves every association in a read-only repeatable-read snapshot. + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.readPublicationScope( + configuredNamespace, association.canonicalTenantId(), release.getVersionId()); + requireExactReleaseAndSource(associationRequest, association, release, receipt); + requireExactProjections(publicResult.projections(), association, receipt); + return publicResult; + } + + private void requireExactReleaseAndSource( + Request request, + Association association, + PublishedReleaseBundle release, + EntityEmptySelectedSourceIntakeReceipt receipt) { + if (receipt == null) { + throw denied("Entity retained selected-source receipt is unavailable"); + } + ExactReplay replay = (ExactReplay) request.selection(); + var authorization = receipt.authorizationBinding(); + var selected = authorization.selected(); + var target = selected.target(); + var worldRead = receipt.inputs().worldInventoryReadEvidence(); + var worldInventory = worldRead.inventory(); + var worldOwner = worldInventory.publicEvidence().ownerScope(); + var worldReceipt = association.worldReceipt(); + var worldSelection = + worldRead.request().freezeEvidence().request().accountBinding().input().selection(); + + if (!configuredNamespace.equals(receipt.targetNamespace()) + || !configuredNamespace.equals(authorization.targetNamespace()) + || authorization.owner() != Owner.ENTITY_MANAGEMENT + || !association.canonicalTenantId().equals(receipt.canonicalTenantId()) + || !association.canonicalVersionId().equals(receipt.canonicalVersionId()) + || !association.selectedCommitId().equals(receipt.selectedCommitId()) + || !replay.canonicalVersionId().equals(receipt.canonicalVersionId()) + || !replay.selectedCommitId().equals(receipt.selectedCommitId()) + || !replay.publishWorkflowId().equals(association.publishWorkflowId()) + || !replay.associationDigest().equals(association.associationDigest()) + || !receipt.canonicalTenantId().equals(target.canonicalTenantId()) + || !receipt.canonicalVersionId().equals(target.canonicalVersionId()) + || target.gameDesignVersionRowId() != release.getVersionId() + || !selected.commitId().equals(receipt.selectedCommitId()) + || !configuredNamespace.equals(association.targetNamespace()) + || !association.intakeRequestId().equals(worldOwner.intakeRequestId()) + || !association.worldOperationId().equals(worldOwner.intakeOperationId()) + || !association.publicationSelectionDigest().equals(worldSelection.digest()) + || !worldReceipt.targetNamespace().equals(worldOwner.targetNamespace()) + || !worldReceipt.canonicalTenantId().equals(worldOwner.canonicalTenantId()) + || !worldReceipt.intakeRequestId().equals(worldOwner.intakeRequestId()) + || !worldReceipt.operationId().equals(worldOwner.intakeOperationId()) + || !worldReceipt.sourceOperationId().equals(worldOwner.sourceOperationId()) + || !worldReceipt.sourceEvidenceDigest().equals(worldOwner.sourceEvidenceDigest()) + || !worldReceipt.receiptDigest().equals(worldOwner.intakeReceiptDigest()) + || !release.getCanonicalTenantId().equals(receipt.canonicalTenantId().toString()) + || !release.getCanonicalVersionId().equals(receipt.canonicalVersionId().toString()) + || release.getVersionId() != target.gameDesignVersionRowId() + || !release.getPublishWorkflowId().equals(association.publishWorkflowId()) + || !ENTITY_RELEASE_SCHEMA.equals(release.getAttestationSchemaVersion()) + || !association.sourceOperationId().equals(worldOwner.sourceOperationId()) + || !association.sourceEvidenceDigest().equals(worldOwner.sourceEvidenceDigest()) + || !receipt.canonicalTenantId().equals(worldOwner.canonicalTenantId()) + || !receipt.canonicalVersionId().equals(worldOwner.canonicalVersionId()) + || !receipt + .selectedCommitId() + .toString() + .equals( + receipt + .inputs() + .worldInventoryReadEvidence() + .request() + .freezeEvidence() + .acknowledgement() + .appliedCommitId()) + || !receipt.operationId().equals(authorization.operationId()) + || !receipt.fenceId().equals(authorization.fenceId()) + || !receipt.intakeRequestId().equals(authorization.intakeRequestId())) { + throw denied("Entity receipt differs from the exact selected source operation or release"); + } + + String expectedEntityDigest = + EntitySelectedEmptyPublicationDigestService.contentDigest( + receipt.canonicalTenantId(), + target.gameDesignVersionRowId(), + receipt.canonicalVersionId(), + receipt.inputs().ownerSourceInventoryDeclaration().entityInventory().canonicalJson()); + List matchingEntityParticipants = + release.getParticipantDigestsList().stream() + .filter(value -> "ENTITY_MANAGEMENT".equals(value.getParticipantKey())) + .toList(); + if (matchingEntityParticipants.size() != 1) { + throw denied("Selected release has no unique immutable Entity participant digest"); + } + ParticipantDigest entityParticipant = matchingEntityParticipants.getFirst(); + if (!Long.toString(target.gameDesignVersionRowId()).equals(entityParticipant.getScopeValue()) + || !receipt.selectedCommitId().toString().equals(entityParticipant.getAppliedCommitId()) + || entityParticipant.getDigestSchemaVersion() + != EntitySelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION + || !expectedEntityDigest.equals(entityParticipant.getContentDigest()) + || entityParticipant.hasAbilitySchemaDigest()) { + throw denied("Selected release Entity digest differs from the retained Entity receipt"); + } + } + + private static void requireExactProjections( + List projections, + Association association, + EntityEmptySelectedSourceIntakeReceipt receipt) { + if (projections == null) { + throw denied("Game Design authored-core projection list is unavailable"); + } + String selectedCommitDigest = receipt.authorizationBinding().selected().digest(); + for (AuthoredInitialActorCoreProjection projection : projections) { + if (projection == null + || !projection.canonicalTenantId().equals(receipt.canonicalTenantId()) + || !projection.canonicalVersionId().equals(receipt.canonicalVersionId()) + || !projection.selectedCommitId().equals(receipt.selectedCommitId()) + || !projection.selectedCommitDigest().equals(selectedCommitDigest) + || !projection.worldSourceOperationId().equals(association.sourceOperationId()) + || !projection.worldSourceEvidenceDigest().equals(association.sourceEvidenceDigest()) + || !projection.worldSlug().equals(association.worldSlug()) + || !projection.publicationWorkflowId().equals(association.publishWorkflowId())) { + throw denied("Authored-core projection differs from Entity's exact retained source"); + } + } + } + + private static void requireNoAmbientOwnerSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw denied("Entity authored-core consumption requires no ambient owner SQL"); + } + } + + private static IllegalStateException denied(String message) { + return new IllegalStateException(message); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java new file mode 100644 index 0000000000..de9f583b39 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java @@ -0,0 +1,264 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +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 java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +import org.junit.jupiter.api.Test; + +class EntityRetainedAuthoredActorCoreSourceServiceTest { + private static final String NAMESPACE = "test"; + private static final String WORKFLOW = "selected-publish-workflow"; + private static final String WORLD_SLUG = "retained-world"; + private static final String ASSOCIATION_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void exactRetryReturnsUnchangedDirectResultAfterIndependentOwnerSnapshotRead() { + Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + ReadSetup setup = readSetup(fixture); + AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class); + EntityEmptySelectedSourceIntakeRepository repository = + mock(EntityEmptySelectedSourceIntakeRepository.class); + when(client.read(setup.request())).thenReturn(setup.result()); + when(repository.readPublicationScope( + NAMESPACE, + fixture.receipt().canonicalTenantId(), + fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId())) + .thenReturn(fixture.receipt()); + var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository); + + var first = service.read(setup.request()); + var retry = service.read(setup.request()); + + assertThat(first).isSameAs(setup.result()); + assertThat(retry).isSameAs(setup.result()); + var inOrder = inOrder(client, repository); + inOrder.verify(client).read(setup.request()); + inOrder + .verify(repository) + .readPublicationScope( + NAMESPACE, + fixture.receipt().canonicalTenantId(), + fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId()); + inOrder.verify(client).read(setup.request()); + inOrder + .verify(repository) + .readPublicationScope( + NAMESPACE, + fixture.receipt().canonicalTenantId(), + fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId()); + verifyNoMoreInteractions(client, repository); + } + + @Test + void deniesAReadResultThatSubstitutesTheOriginalOperationBeforeEntitySql() { + Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + ReadSetup setup = readSetup(fixture); + AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class); + EntityEmptySelectedSourceIntakeRepository repository = + mock(EntityEmptySelectedSourceIntakeRepository.class); + var substituted = mock(AuthoredInitialActorCoreReadEvidence.ReadResult.class); + when(substituted.request()).thenReturn(mock(Request.class)); + when(client.read(setup.request())).thenReturn(substituted); + var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository); + + assertThatThrownBy(() -> service.read(setup.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact original request"); + + verify(client).read(setup.request()); + verifyNoInteractions(repository); + } + + @Test + void deniesMixedProjectionSourceEvenWhenTheEntityReleaseDigestMatches() { + Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + ReadSetup setup = readSetup(fixture); + when(setup.projection().worldSourceOperationId()).thenReturn(UUID.randomUUID()); + AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class); + EntityEmptySelectedSourceIntakeRepository repository = + mock(EntityEmptySelectedSourceIntakeRepository.class); + when(client.read(setup.request())).thenReturn(setup.result()); + when(repository.readPublicationScope( + NAMESPACE, + fixture.receipt().canonicalTenantId(), + fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId())) + .thenReturn(fixture.receipt()); + var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository); + + assertThatThrownBy(() -> service.read(setup.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact retained source"); + } + + @Test + void deniesReleaseWithDifferentImmutableEntityRecipientDigest() { + Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + ReadSetup setup = readSetup(fixture); + PublishedReleaseBundle changedRelease = + setup.release().toBuilder() + .clearParticipantDigests() + .addParticipantDigests(entityParticipant(fixture.receipt(), "0".repeat(64))) + .build(); + when(setup.associationRead().releaseBundle()).thenReturn(changedRelease); + AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class); + EntityEmptySelectedSourceIntakeRepository repository = + mock(EntityEmptySelectedSourceIntakeRepository.class); + when(client.read(setup.request())).thenReturn(setup.result()); + when(repository.readPublicationScope( + NAMESPACE, + fixture.receipt().canonicalTenantId(), + fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId())) + .thenReturn(fixture.receipt()); + var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository); + + assertThatThrownBy(() -> service.read(setup.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("release Entity digest"); + } + + @Test + void deniesUnavailableAuthenticatedGameDesignEvidenceWithoutLocalRead() { + ReadSetup setup = readSetup(EntitySelectedSourceIntakeTerminalReadFixtures.create()); + AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class); + EntityEmptySelectedSourceIntakeRepository repository = + mock(EntityEmptySelectedSourceIntakeRepository.class); + when(client.read(setup.request())).thenThrow(new IllegalStateException("read unavailable")); + var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository); + + assertThatThrownBy(() -> service.read(setup.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("read unavailable"); + + verifyNoInteractions(repository); + } + + private static ReadSetup readSetup(Fixture fixture) { + EntityEmptySelectedSourceIntakeReceipt receipt = fixture.receipt(); + ExactReplay replay = + new ExactReplay( + receipt.canonicalVersionId(), receipt.selectedCommitId(), WORKFLOW, ASSOCIATION_DIGEST); + Request originalRequest = mock(Request.class); + when(originalRequest.targetNamespace()).thenReturn(NAMESPACE); + when(originalRequest.selection()).thenReturn(replay); + var request = new AuthoredInitialActorCoreReadEvidence.ReadRequest(originalRequest); + + PublicOwnerScope worldOwner = + receipt.inputs().worldInventoryReadEvidence().inventory().publicEvidence().ownerScope(); + Association association = mock(Association.class); + when(association.canonicalTenantId()).thenReturn(receipt.canonicalTenantId()); + when(association.canonicalVersionId()).thenReturn(receipt.canonicalVersionId()); + when(association.selectedCommitId()).thenReturn(receipt.selectedCommitId()); + when(association.publishWorkflowId()).thenReturn(WORKFLOW); + when(association.associationDigest()).thenReturn(ASSOCIATION_DIGEST); + when(association.targetNamespace()).thenReturn(NAMESPACE); + when(association.intakeRequestId()).thenReturn(worldOwner.intakeRequestId()); + when(association.worldOperationId()).thenReturn(worldOwner.intakeOperationId()); + when(association.publicationSelectionDigest()) + .thenReturn( + receipt + .inputs() + .worldInventoryReadEvidence() + .request() + .freezeEvidence() + .request() + .accountBinding() + .input() + .selection() + .digest()); + when(association.sourceOperationId()).thenReturn(worldOwner.sourceOperationId()); + when(association.sourceEvidenceDigest()).thenReturn(worldOwner.sourceEvidenceDigest()); + when(association.worldSlug()).thenReturn(WORLD_SLUG); + PublicReceipt worldReceipt = mock(PublicReceipt.class); + when(worldReceipt.targetNamespace()).thenReturn(worldOwner.targetNamespace()); + when(worldReceipt.canonicalTenantId()).thenReturn(worldOwner.canonicalTenantId()); + when(worldReceipt.intakeRequestId()).thenReturn(worldOwner.intakeRequestId()); + when(worldReceipt.operationId()).thenReturn(worldOwner.intakeOperationId()); + when(worldReceipt.sourceOperationId()).thenReturn(worldOwner.sourceOperationId()); + when(worldReceipt.sourceEvidenceDigest()).thenReturn(worldOwner.sourceEvidenceDigest()); + when(worldReceipt.receiptDigest()).thenReturn(worldOwner.intakeReceiptDigest()); + when(association.worldReceipt()).thenReturn(worldReceipt); + + ParticipantDigest entityParticipant = entityParticipant(receipt, null); + PublishedReleaseBundle release = + PublishedReleaseBundle.newBuilder() + .setVersionId( + receipt.authorizationBinding().selected().target().gameDesignVersionRowId()) + .setAttestationSchemaVersion("v4") + .setPublishWorkflowId(WORKFLOW) + .setCanonicalTenantId(receipt.canonicalTenantId().toString()) + .setCanonicalVersionId(receipt.canonicalVersionId().toString()) + .addParticipantDigests(entityParticipant) + .build(); + Result associationRead = mock(Result.class); + when(associationRead.request()).thenReturn(originalRequest); + when(associationRead.association()).thenReturn(association); + when(associationRead.releaseBundle()).thenReturn(release); + + AuthoredInitialActorCoreProjection projection = mock(AuthoredInitialActorCoreProjection.class); + when(projection.canonicalTenantId()).thenReturn(receipt.canonicalTenantId()); + when(projection.canonicalVersionId()).thenReturn(receipt.canonicalVersionId()); + when(projection.selectedCommitId()).thenReturn(receipt.selectedCommitId()); + when(projection.selectedCommitDigest()) + .thenReturn(receipt.authorizationBinding().selected().digest()); + when(projection.worldSourceOperationId()).thenReturn(worldOwner.sourceOperationId()); + when(projection.worldSourceEvidenceDigest()).thenReturn(worldOwner.sourceEvidenceDigest()); + when(projection.worldSlug()).thenReturn(WORLD_SLUG); + when(projection.publicationWorkflowId()).thenReturn(WORKFLOW); + + AuthoredInitialActorCoreReadEvidence.ReadResult result = + mock(AuthoredInitialActorCoreReadEvidence.ReadResult.class); + when(result.request()).thenReturn(originalRequest); + when(result.associationRead()).thenReturn(associationRead); + when(result.projections()).thenReturn(List.of(projection)); + return new ReadSetup(request, result, associationRead, release, projection); + } + + private static ParticipantDigest entityParticipant( + EntityEmptySelectedSourceIntakeReceipt receipt, String replacementDigest) { + var target = receipt.authorizationBinding().selected().target(); + String inventoryJson = + receipt.inputs().ownerSourceInventoryDeclaration().entityInventory().canonicalJson(); + String contentDigest = + EntitySelectedEmptyPublicationDigestService.contentDigest( + receipt.canonicalTenantId(), + target.gameDesignVersionRowId(), + receipt.canonicalVersionId(), + inventoryJson); + return ParticipantDigest.newBuilder() + .setParticipantKey("ENTITY_MANAGEMENT") + .setScopeValue(Long.toString(target.gameDesignVersionRowId())) + .setAppliedCommitId(receipt.selectedCommitId().toString()) + .setContentDigest(replacementDigest == null ? contentDigest : replacementDigest) + .setDigestSchemaVersion(EntitySelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION) + .build(); + } + + private record ReadSetup( + AuthoredInitialActorCoreReadEvidence.ReadRequest request, + AuthoredInitialActorCoreReadEvidence.ReadResult result, + Result associationRead, + PublishedReleaseBundle release, + AuthoredInitialActorCoreProjection projection) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadService.java new file mode 100644 index 0000000000..08e88b0dd3 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadService.java @@ -0,0 +1,436 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionAuthoredActorCoreProjectionRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository.Binding; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; +import tools.jackson.databind.ObjectMapper; + +/** + * Standalone, read-only authenticated authored-core projection. It never invokes descriptor + * resolution or repairs missing owner/projection rows. + */ +public final class AuthoredInitialActorCoreReadService { + private static final String EMPTY_RUNTIME_FLAGS = "{}"; + private static final String RUNTIME_SURFACE_EMPTY_V1 = "EMPTY_V1"; + + private final String workloadNamespace; + private final StartSessionTemplateAssociationReadService associationReader; + private final GameAuthoredWorldSourceRepository worldSources; + private final LaunchDescriptorRepository descriptors; + private final StartSessionLaunchDescriptorRepository descriptorBindings; + private final StartSessionAuthoredActorCoreProjectionRepository projections; + private final GameDesignPublicationOperationRepository publicationOperations; + private final GameDesignSourceRepository sourceRepository; + private final SelectedDraftTemplateWorldSourceAssociationRepository associations; + private final SelectedDraftGameLogicReceiptRepository gameLogicReceipts; + private final GameplayRuleSourceRepository gameplayRules; + private final ObjectMapper objectMapper; + + public AuthoredInitialActorCoreReadService( + DSLContext dsl, + String workloadNamespace, + StartSessionTemplateAssociationReadService associationReader, + ObjectMapper objectMapper) { + Objects.requireNonNull(dsl, "dsl"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + this.associationReader = Objects.requireNonNull(associationReader, "associationReader"); + this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper"); + worldSources = new GameAuthoredWorldSourceRepository(dsl); + descriptors = new LaunchDescriptorRepository(dsl); + descriptorBindings = new StartSessionLaunchDescriptorRepository(dsl); + projections = new StartSessionAuthoredActorCoreProjectionRepository(dsl); + publicationOperations = new GameDesignPublicationOperationRepository(dsl); + sourceRepository = new GameDesignSourceRepository(dsl); + associations = new SelectedDraftTemplateWorldSourceAssociationRepository(dsl); + gameLogicReceipts = new SelectedDraftGameLogicReceiptRepository(dsl); + gameplayRules = new GameplayRuleSourceRepository(dsl); + } + + /** Caller authorization occurs before request correlation checks or the local snapshot. */ + public ReadResult read(ReadRequest request) { + associationReader.requireAuthoredInitialActorCorePeer(); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.associationRequest().targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("Authored-core request namespace differs from Game Design") + .asRuntimeException(); + } + try { + return associationReader.readForAuthoredInitialActorCore( + request.associationRequest(), exact -> readOwner(exact, request.associationRequest())); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (DataAccessException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Game Design authored-core owner storage unavailable") + .withCause(unavailable) + .asRuntimeException(); + } catch (RuntimeException invalid) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Exact retained authored-core owner evidence is unavailable or conflicting") + .withCause(invalid) + .asRuntimeException(); + } + } + + private ReadResult readOwner(Result exact, Request request) { + StartSessionPostAuthorizationExecutionTuple tuple = request.decodedTuple(); + var action = tuple.preAuthorizationTuple().action(); + Association association = exact.association(); + if (!(request.selection() instanceof ExactReplay replay) + || !request.equals(exact.request()) + || !replay.canonicalVersionId().equals(association.canonicalVersionId()) + || !replay.selectedCommitId().equals(association.selectedCommitId()) + || !replay.publishWorkflowId().equals(association.publishWorkflowId()) + || !replay.associationDigest().equals(association.associationDigest()) + || !action.scope().tenantId().equals(association.canonicalTenantId()) + || action.target().gameTemplateId() != association.templateId()) { + throw conflict("Account-gated association differs from the exact original request"); + } + + AuthoredWorldSourceEvidence source = + worldSources + .read( + association.sourceOperationId(), + association.canonicalTenantId(), + association.worldSlug(), + workloadNamespace) + .orElseThrow(() -> conflict("Exact registered Game Design source is unavailable")); + requireSourceMatches(association, source); + + String requestId = tuple.controlPlaneRequestId(); + Binding owner = + descriptorBindings + .find(workloadNamespace, association.canonicalTenantId(), requestId) + .orElseThrow( + () -> conflict("Retained StartSession descriptor owner binding is missing")); + LaunchDescriptor descriptor = + descriptors + .findBoundByRequest(workloadNamespace, association.canonicalTenantId(), requestId) + .orElseThrow(() -> conflict("Retained StartSession descriptor row is missing")); + if (!Objects.equals(owner.descriptorRowId(), descriptor.getId())) { + throw conflict("Descriptor binding does not point at the actual immutable descriptor row"); + } + + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = + descriptorRequest(request, association); + String originalRequestJson = writeJson(descriptorRequest); + String sourceEvidenceJson = writeJson(source); + requireSuccessfulDescriptor( + descriptor, source, descriptorRequest, originalRequestJson, sourceEvidenceJson); + + CapturedSources captured = requireCapturedSources(exact, association.templateId()); + requireOwnerBinding(owner, descriptor, request, exact, source, captured.gameLogicReceipt()); + List retained = + projections.replayExact(owner, captured.actorCoreBindings()); + return new ReadResult(request, exact, evidence(descriptor, descriptorRequest), retained); + } + + private CapturedSources requireCapturedSources(Result exact, long templateId) { + Association association = exact.association(); + var readback = + publicationOperations + .read(association.publishWorkflowId()) + .orElseThrow(() -> conflict("Exact selected publication operation is unavailable")); + var operation = readback.operation(); + var selection = operation.account().input().selection(); + if (!"PUBLISHED".equals(readback.outcome()) + || !operation.workflowId().equals(association.publishWorkflowId()) + || !operation.tenantKey().equals(selection.target().gameDesignVersionTenantKey()) + || operation.versionId() != selection.target().gameDesignVersionRowId() + || !selection.target().canonicalTenantId().equals(association.canonicalTenantId()) + || !selection.target().canonicalVersionId().equals(association.canonicalVersionId()) + || !selection.selectedCommit().commitId().equals(association.selectedCommitId()) + || readback.terminalEvidenceBytes() == null) { + throw conflict("Published operation differs from the pinned association"); + } + GameDesignPublicationTerminalEvidence terminal = + GameDesignPublicationTerminalEvidence.fromStored(readback.terminalEvidenceBytes()); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operation.canonicalBytes()) + || terminal.releaseContent() == null + || terminal.publicationVersionStateEpoch() <= 0L) { + throw conflict("Exact selected publication terminal evidence is incomplete"); + } + GameDesignSourceRepository.Capture capture = + sourceRepository + .readCapture(operation) + .orElseThrow(() -> conflict("Complete selected publication capture is unavailable")); + var templateCapture = capture.templateConfig(); + if (!templateCapture.snapshot().binding().equals(selection.selectedCommit())) { + throw conflict("Selected template capture differs from its publication commit"); + } + List templateEntries = + templateCapture.snapshot().entries().stream() + .filter(entry -> Long.parseLong(entry.templateId()) == templateId) + .toList(); + if (templateEntries.size() != 1 + || !templateEntries + .getFirst() + .config() + .baseVersionId() + .equals(association.canonicalVersionId())) { + throw conflict("Exact selected template entry is missing, duplicated or misbound"); + } + + SelectedGameplayRules selectedRules = requireSelectedGameLogic(operation); + List associationRows = + associations.readExact(operation, templateCapture).stream() + .filter(value -> value.templateId() == templateId) + .toList(); + if (associationRows.size() != 1) { + throw conflict("Exact immutable template source association is missing or ambiguous"); + } + var row = associationRows.getFirst(); + if (!row.canonicalTenantId().equals(association.canonicalTenantId()) + || row.templateId() != association.templateId() + || !row.canonicalVersionId().equals(association.canonicalVersionId()) + || !row.selectedCommitId().equals(association.selectedCommitId()) + || !row.publishWorkflowId().equals(association.publishWorkflowId()) + || !row.digest().equals(association.associationDigest()) + || !row.targetNamespace().equals(association.targetNamespace()) + || !row.sourceOperationId().equals(association.sourceOperationId()) + || !row.sourceEvidenceDigest().equals(association.sourceEvidenceDigest()) + || !row.worldSlug().equals(association.worldSlug())) { + throw conflict("Retained private association differs from its public pinned result"); + } + List actorBindings = + StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.worldSlug(), + operation.workflowId(), + operation.canonicalBytes(), + readback.terminalEvidenceBytes(), + selection.selectedCommit(), + capture.policy().snapshot().shared(), + selectedRules.snapshot()); + return new CapturedSources(actorBindings, selectedRules.receiptBinding()); + } + + private SelectedGameplayRules requireSelectedGameLogic(GameDesignPublicationOperation operation) { + var selection = operation.account().input().selection(); + var target = selection.target(); + var publicationRequest = + PublicationDigestRequestBinding.full( + selection.intent().canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + selection.intent().publishRequestId()); + SelectedDraftGameLogicReceipt receipt = + gameLogicReceipts + .readForPublication(publicationRequest) + .orElseThrow(() -> conflict("Exact retained Game Logic source receipt is unavailable")); + GameplayRuleSnapshot snapshot = + gameplayRules + .readSnapshot(target, selection.selectedCommit().commitId()) + .orElseThrow(() -> conflict("Exact selected Game Logic source is unavailable")); + if (!Arrays.equals(selection.canonicalBytes(), receipt.selection().canonicalBytes()) + || !selection.selectedCommit().equals(snapshot.binding()) + || !Arrays.equals( + snapshot.canonicalBytes(), receipt.authorization().source().canonicalBytes())) { + throw conflict("Retained Game Logic receipt differs from the selected source"); + } + return new SelectedGameplayRules( + snapshot, + new GameLogicReceiptBinding( + selection.intent().publishRequestId(), + selection.digest(), + receipt.authorization().digest(), + receipt.receipt().digest())); + } + + private void requireOwnerBinding( + Binding owner, + LaunchDescriptor descriptor, + Request request, + Result exact, + AuthoredWorldSourceEvidence source, + GameLogicReceiptBinding logic) { + Association association = exact.association(); + if (!Objects.equals(owner.targetNamespace(), workloadNamespace) + || !Objects.equals(owner.canonicalTenantId(), association.canonicalTenantId()) + || !Objects.equals( + owner.controlPlaneRequestId(), request.decodedTuple().controlPlaneRequestId()) + || !Objects.equals(owner.descriptorRowId(), descriptor.getId()) + || !Objects.equals(owner.releaseBundleId(), exact.releaseBundle().getId()) + || !Objects.equals(owner.versionStateEpoch(), descriptor.getVersionStateEpoch()) + || !Arrays.equals( + owner.canonicalPostAuthorizationTuple(), request.canonicalPostAuthorizationTuple()) + || !Objects.equals(owner.ownerAttemptId(), request.ownerAttemptId()) + || !Objects.equals(owner.ownerFence(), request.ownerFence()) + || !Objects.equals(owner.gameTemplateId(), association.templateId()) + || !Objects.equals(owner.canonicalVersionId(), association.canonicalVersionId()) + || !Objects.equals(owner.selectedCommitId(), association.selectedCommitId()) + || !Objects.equals(owner.publishWorkflowId(), association.publishWorkflowId()) + || !Objects.equals( + owner.publicationSelectionDigest(), association.publicationSelectionDigest()) + || !Objects.equals(owner.associationDigest(), association.associationDigest()) + || !Objects.equals(owner.sourceOperationId(), association.sourceOperationId()) + || !Objects.equals(owner.sourceEvidenceDigest(), association.sourceEvidenceDigest()) + || !Objects.equals(owner.worldSlug(), association.worldSlug()) + || !Objects.equals(owner.referencePhaseEpoch(), exact.phaseEpoch()) + || !Objects.equals(owner.runtimeSurface(), RUNTIME_SURFACE_EMPTY_V1) + || !Objects.equals(owner.gameLogicPublishRequestId(), logic.publishRequestId()) + || !Objects.equals(owner.gameLogicSelectionDigest(), logic.selectionDigest()) + || !Objects.equals(owner.gameLogicAuthorizationDigest(), logic.authorizationDigest()) + || !Objects.equals(owner.gameLogicReceiptDigest(), logic.receiptDigest()) + || !Arrays.equals( + owner.associationReadResponseBytes(), + StartSessionTemplateAssociationReadGrpcCodec.toResponse(exact).toByteArray()) + || !Objects.equals(source.operationId(), owner.sourceOperationId()) + || !Objects.equals(source.evidenceDigest(), owner.sourceEvidenceDigest())) { + throw conflict("Immutable StartSession descriptor owner binding differs from exact read"); + } + } + + private void requireSuccessfulDescriptor( + LaunchDescriptor descriptor, + AuthoredWorldSourceEvidence source, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + String sourceJson) { + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || descriptor.getDescriptorSchemaVersion() == null + || descriptor.getDescriptorSchemaVersion() + != AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !Objects.equals(descriptor.getTenantId(), source.sourceGameTenantKey()) + || request.gameTemplateId() != descriptor.getGameTemplateId() + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || descriptor.getScriptPatchVersion() != null + || descriptor.getRemapSetId() != null + || !EMPTY_RUNTIME_FLAGS.equals(descriptor.getRuntimeFlagsJson())) { + throw conflict("Stored descriptor is not the exact successful immutable binding"); + } + } + + private AuthoredWorldLaunchDescriptorEvidence evidence( + LaunchDescriptor descriptor, AuthoredWorldLaunchDescriptorEvidence.Request request) { + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptor.getLaunchDescriptorId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion() != null, + descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getVersionStateEpoch(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getRemapSetId() != null, + descriptor.getRemapSetId()); + evidence.requireValid(); + if (!evidence.resultDigest().equals(descriptor.getResultDigest())) { + throw conflict("Stored descriptor result digest differs from its complete content"); + } + return evidence; + } + + private AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest( + Request request, Association association) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + request.targetNamespace(), + request.decodedTuple().controlPlaneRequestId(), + association.canonicalTenantId(), + association.worldSlug(), + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.templateId(), + false, + null, + false, + null, + false, + null, + true, + EMPTY_RUNTIME_FLAGS); + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception invalid) { + throw new IllegalStateException("Cannot encode exact retained descriptor evidence", invalid); + } + } + + private void requireSourceMatches(Association association, AuthoredWorldSourceEvidence source) { + if (!workloadNamespace.equals(source.targetNamespace()) + || !association.targetNamespace().equals(source.targetNamespace()) + || !association.canonicalTenantId().equals(source.canonicalTenantId()) + || !association.sourceOperationId().equals(source.operationId()) + || !association.sourceEvidenceDigest().equals(source.evidenceDigest()) + || !association.worldSlug().equals(source.worldSlug()) + || !"NEW_GAME_ROW".equals(source.provenanceKind()) + || source.sourceGameRowId() <= 0L + || source.sourceGameTenantKey() == null + || source.sourceGameTenantKey().isBlank()) { + throw conflict("Exact association source differs from registered source evidence"); + } + } + + private static StatusRuntimeException conflict(String description) { + return Status.FAILED_PRECONDITION.withDescription(description).asRuntimeException(); + } + + private record CapturedSources( + List actorCoreBindings, + GameLogicReceiptBinding gameLogicReceipt) { + private CapturedSources { + actorCoreBindings = List.copyOf(actorCoreBindings); + Objects.requireNonNull(gameLogicReceipt, "gameLogicReceipt"); + } + } + + private record SelectedGameplayRules( + GameplayRuleSnapshot snapshot, GameLogicReceiptBinding receiptBinding) {} + + private record GameLogicReceiptBinding( + String publishRequestId, + String selectionDigest, + String authorizationDigest, + String receiptDigest) {} +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadService.java new file mode 100644 index 0000000000..6d7ac0a068 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadService.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.gamedesign.publication; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.v1.GameDesignAuthoredInitialActorCoreReadServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreRequest; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreResponse; + +/** Standalone, unregistered workload-authenticated authored-core projection endpoint. */ +public final class GrpcAuthoredInitialActorCoreReadService + extends GameDesignAuthoredInitialActorCoreReadServiceGrpc + .GameDesignAuthoredInitialActorCoreReadServiceImplBase { + public static final int MAX_REQUEST_WIRE_BYTES = 128 * 1024; + private final AuthoredInitialActorCoreReadService service; + private final String workloadNamespace; + + public GrpcAuthoredInitialActorCoreReadService( + AuthoredInitialActorCoreReadService service, String workloadNamespace) { + this.service = Objects.requireNonNull(service, "service"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Design workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readAuthoredInitialActorCore( + ReadAuthoredInitialActorCoreRequest request, + StreamObserver observer) { + try { + requirePeer(); + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription("Workload-only authored-core read required") + .asRuntimeException(); + } + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + if (request.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) { + observer.onError( + Status.RESOURCE_EXHAUSTED + .withDescription("Authored-core request exceeds its bounded wire size") + .asRuntimeException()); + return; + } + + final ReadRequest decoded; + try { + decoded = AuthoredInitialActorCoreReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Exact canonical authored-core replay request required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(decoded.associationRequest().targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Authored-core target namespace differs from peer") + .asRuntimeException()); + return; + } + try { + observer.onNext(AuthoredInitialActorCoreReadGrpcCodec.toResponse(service.read(decoded))); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + observer.onError( + Status.fromCode(Status.fromThrowable(failure).getCode()) + .withDescription("Exact authored-core owner read denied or unavailable") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Design authored-core owner read unavailable") + .asRuntimeException()); + } + } + + private void requirePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified same-namespace Game Session or Entity workload required") + .asRuntimeException(); + } + String expectedPrefix = "spiffe://firemud/ns/" + workloadNamespace + "/sa/"; + if (!workloadNamespace.equals(peer.namespace()) + || !("game-session-service".equals(peer.service()) + || "entity-management-service".equals(peer.service())) + || !(expectedPrefix + peer.service()).equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session or Entity workload required") + .asRuntimeException(); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java index ca085d16c2..570b207007 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java @@ -8,6 +8,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; @@ -29,6 +30,7 @@ import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionAuthoredActorCoreProjectionRepository; import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository.Binding; import net.firedevops.firemud.gamedesign.repository.VersionRepository; @@ -61,6 +63,7 @@ public final class StartSessionLaunchDescriptorProducer { private final GameAuthoredWorldSourceRepository authoredWorldSources; private final LaunchDescriptorRepository descriptors; private final StartSessionLaunchDescriptorRepository bindings; + private final StartSessionAuthoredActorCoreProjectionRepository actorCoreProjections; private final VersionRepository versions; private final TemplateReferenceRepository templateReferences; private final GameDesignPublicationOperationRepository publicationOperations; @@ -92,6 +95,7 @@ public StartSessionLaunchDescriptorProducer( authoredWorldSources = new GameAuthoredWorldSourceRepository(dsl); descriptors = new LaunchDescriptorRepository(dsl); bindings = new StartSessionLaunchDescriptorRepository(dsl); + actorCoreProjections = new StartSessionAuthoredActorCoreProjectionRepository(dsl); versions = new VersionRepository(dsl); templateReferences = new TemplateReferenceRepository(dsl); publicationOperations = new GameDesignPublicationOperationRepository(dsl); @@ -205,6 +209,8 @@ private OwnerOutcome writeOrRead( descriptorRequest, source, capturedTemplate.gameLogicReceipt()); + List retainedActorCoreProjections = + replayActorCoreProjections(storedBinding.orElseThrow(), capturedTemplate); if (LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus())) { if (capturedTemplate.failureMessage() == null) { throw conflict( @@ -222,7 +228,7 @@ private OwnerOutcome writeOrRead( ResolvedLaunchDescriptorDto resolved = readStored(descriptor, descriptorRequest, requestJson, source, sourceJson); return OwnerOutcome.succeeded( - new ResolvedBinding(exactRequest, exact, resolved, capturedTemplate.actorCoreBindings())); + new ResolvedBinding(exactRequest, exact, resolved, retainedActorCoreProjections)); } if (descriptors @@ -330,6 +336,8 @@ private OwnerOutcome writeOrRead( descriptorRequest, source, capturedTemplate.gameLogicReceipt()); + List retainedActorCoreProjections = + insertActorCoreProjections(persistedBinding, capturedTemplate); if (deterministicFailure) { return OwnerOutcome.failed( new FrozenFailure(INVALID_TEMPLATE_CONFIGURATION, UNSUPPORTED_CAPTURE_MESSAGE)); @@ -337,7 +345,29 @@ private OwnerOutcome writeOrRead( ResolvedLaunchDescriptorDto resolved = readStored(persisted, descriptorRequest, requestJson, source, sourceJson); return OwnerOutcome.succeeded( - new ResolvedBinding(exactRequest, exact, resolved, capturedTemplate.actorCoreBindings())); + new ResolvedBinding(exactRequest, exact, resolved, retainedActorCoreProjections)); + } + + private List replayActorCoreProjections( + Binding binding, CapturedTemplate capturedTemplate) { + try { + return actorCoreProjections.replayExact(binding, capturedTemplate.actorCoreBindings()); + } catch ( + StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException + invalid) { + throw conflict("Retained authored actor-core projection differs from exact source"); + } + } + + private List insertActorCoreProjections( + Binding binding, CapturedTemplate capturedTemplate) { + try { + return actorCoreProjections.insertForNewOwner(binding, capturedTemplate.actorCoreBindings()); + } catch ( + StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException + invalid) { + throw conflict("New authored actor-core projection conflicts with retained owner storage"); + } } private CapturedTemplate requireCapturedTemplate(Result exact, long templateId) { @@ -365,6 +395,7 @@ private CapturedTemplate requireCapturedTemplate(Result exact, long templateId) || terminal.publicationVersionStateEpoch() <= 0L) { throw conflict("Exact selected publication terminal evidence is incomplete"); } + requireTerminalMatchesExactRelease(exact, terminal); GameDesignSourceRepository.Capture capture = sourceRepository .readCapture(operation) @@ -1052,6 +1083,66 @@ private GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent( dto.worldPublishedStartLocationEvidence()); } + private GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent(Result exact) { + var bundle = exact.releaseBundle(); + if (!bundle.hasManifestSchemaVersion()) { + throw conflict("Exact Account-pinned release bundle lacks its manifest schema"); + } + List participants = + bundle.getParticipantDigestsList().stream() + .map( + value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.getParticipantKey(), + value.getScopeValue(), + null, + value.getAppliedCommitId(), + value.getContentDigest(), + value.getDigestSchemaVersion(), + value.hasAbilitySchemaDigest() ? value.getAbilitySchemaDigest() : null, + null, + null)) + .toList(); + List + artifacts = + bundle.getArtifactDigestsList().stream() + .map( + value -> + new net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence.Artifact( + value.getUsageKey(), + value.getArtifactKind(), + value.getImmutableObjectKey(), + value.getContentDigest(), + value.getContentType(), + value.getArtifactSchemaVersion())) + .toList(); + return new GameDesignPublicationTerminalEvidence.ReleaseContent( + UUID.fromString(bundle.getCanonicalTenantId()), + UUID.fromString(bundle.getCanonicalVersionId()), + bundle.getPublishedReleaseBundleRef(), + bundle.getVersionNumber(), + bundle.getAttestationSchemaVersion(), + bundle.getPublishWorkflowId(), + bundle.getManifestHash(), + bundle.getManifestSchemaVersion(), + artifacts, + bundle.getRequiredManifestAssetKeysList(), + participants, + bundle.getCommandDefinitionsList(), + bundle.getGenerationConfigRevision(), + exact.worldPublishedStartLocationEvidence()); + } + + private void requireTerminalMatchesExactRelease( + Result exact, GameDesignPublicationTerminalEvidence terminal) { + if (terminal.releaseContent() == null + || !Arrays.equals( + terminal.releaseContent().canonicalBytes(), releaseContent(exact).canonicalBytes())) { + throw conflict("Private source binding release differs from exact pinned Account release"); + } + } + private void requirePeer() { var peer = GrpcPeerIdentity.current(); if (peer == null) { @@ -1072,19 +1163,21 @@ private static StatusRuntimeException conflict(String description) { } /** - * Exact selected-release descriptor and its independently validated authored actor-core sources. + * Internal result pairing an exact selected-release descriptor with minimal retained projections. + * Projection construction validates canonical integrity, not producer authentication; the + * producer returns this result only after its owner path cross-checks the private source proofs. */ public record ResolvedBinding( Request request, Result associationRead, ResolvedLaunchDescriptorDto descriptor, - List actorCoreBindings) { + List actorCoreProjections) { public ResolvedBinding { Objects.requireNonNull(request, "request"); Objects.requireNonNull(associationRead, "associationRead"); Objects.requireNonNull(descriptor, "descriptor"); - actorCoreBindings = - List.copyOf(Objects.requireNonNull(actorCoreBindings, "actorCoreBindings")); + actorCoreProjections = + List.copyOf(Objects.requireNonNull(actorCoreProjections, "actorCoreProjections")); if (!request.equals(associationRead.request()) || !request .decodedTuple() @@ -1105,24 +1198,31 @@ public record ResolvedBinding( } var association = associationRead.association(); var authoredWorld = descriptor.authoredWorldBinding(); - for (var actorCore : actorCoreBindings) { - var selected = actorCore.selectedCommit(); + if (actorCoreProjections.stream() + .map(AuthoredInitialActorCoreProjection::bindingId) + .distinct() + .count() + != actorCoreProjections.size()) { + throw new IllegalArgumentException( + "Authored actor-core projection identities must be unique"); + } + for (var actorCore : actorCoreProjections) { if (!actorCore.worldSourceOperationId().equals(association.sourceOperationId()) || !actorCore.worldSourceEvidenceDigest().equals(association.sourceEvidenceDigest()) - || !actorCore.expectedWorldSlug().equals(association.worldSlug()) + || !actorCore.worldSlug().equals(association.worldSlug()) || !actorCore.publicationWorkflowId().equals(association.publishWorkflowId()) - || !selected.target().canonicalTenantId().equals(association.canonicalTenantId()) - || !selected.target().canonicalVersionId().equals(association.canonicalVersionId()) - || !selected.commitId().equals(association.selectedCommitId()) - || !actorCore.expectedWorldSlug().equals(authoredWorld.worldSlug()) + || !actorCore.canonicalTenantId().equals(association.canonicalTenantId()) + || !actorCore.canonicalVersionId().equals(association.canonicalVersionId()) + || !actorCore.selectedCommitId().equals(association.selectedCommitId()) + || !actorCore.worldSlug().equals(authoredWorld.worldSlug()) || !actorCore .worldSourceOperationId() .equals(authoredWorld.authoredWorldSourceOperationId()) || !actorCore .worldSourceEvidenceDigest() .equals(authoredWorld.authoredWorldSourceEvidenceDigest()) - || !selected.target().canonicalTenantId().equals(authoredWorld.canonicalTenantId()) - || selected.target().gameDesignVersionRowId() != authoredWorld.versionId() + || !actorCore.canonicalTenantId().equals(authoredWorld.canonicalTenantId()) + || !actorCore.canonicalVersionId().equals(association.canonicalVersionId()) || association.templateId() != authoredWorld.gameTemplateId()) { throw new IllegalArgumentException( "Authored actor core differs from the exact selected StartSession release"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java index 634024b0b7..8c05a8c6e7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java @@ -9,6 +9,7 @@ import java.util.List; import java.util.Objects; import java.util.UUID; +import java.util.function.Function; import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; import net.firedevops.firemud.common.authoring.DraftCommitBinding; @@ -21,6 +22,7 @@ import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; @@ -106,6 +108,21 @@ public StartSessionTemplateAssociationReadService( */ public Result read(Request request) { requirePeer(); + return readAuthorized(request, Function.identity()); + } + + /** + * Core-read-only qualification for one same-namespace Game Session or Entity caller. The exact + * Account operation is still verified by this Game Design workload before opening the snapshot; + * the callback runs within that same read-only snapshot with the exact association result. + */ + T readForAuthoredInitialActorCore(Request request, Function ownerRead) { + requireAuthoredInitialActorCorePeer(); + Objects.requireNonNull(ownerRead, "ownerRead"); + return readAuthorized(request, ownerRead); + } + + private T readAuthorized(Request request, Function ownerRead) { Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw Status.PERMISSION_DENIED @@ -137,7 +154,8 @@ public Result read(Request request) { try { return Objects.requireNonNull( - snapshot.execute(ignored -> readSnapshot(request, tuple)), + snapshot.execute( + ignored -> ownerRead.apply(Objects.requireNonNull(readSnapshot(request, tuple)))), "StartSession association snapshot returned no result"); } catch (StatusRuntimeException failure) { throw failure; @@ -663,6 +681,29 @@ private void requirePeer() { } } + void requireAuthoredInitialActorCorePeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified same-namespace Game Session or Entity workload required") + .asRuntimeException(); + } + String expectedPrefix = "spiffe://firemud/ns/" + workloadNamespace + "/sa/"; + if (!workloadNamespace.equals(peer.namespace()) + || !("game-session-service".equals(peer.service()) + || "entity-management-service".equals(peer.service())) + || !(expectedPrefix + peer.service()).equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session or Entity workload required") + .asRuntimeException(); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription("Workload-only authored-core read required") + .asRuntimeException(); + } + } + @FunctionalInterface interface AccountProjectionReader { ReadRedeemedOperationProjectionResponse read( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepository.java new file mode 100644 index 0000000000..7ec3e62e2e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepository.java @@ -0,0 +1,322 @@ +package net.firedevops.firemud.gamedesign.repository; + +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository.Binding; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Insert-only authored actor-core proofs owned by one retained StartSession descriptor binding. */ +public final class StartSessionAuthoredActorCoreProjectionRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Table TABLE = + DSL.table(DSL.name("game_design_start_session_authored_actor_core_projection")); + 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 CONTROL_PLANE_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + private static final Field DESCRIPTOR_ROW_ID = + DSL.field(DSL.name("launch_descriptor_row_id"), Long.class); + private static final Field POLICY_ORDER = + DSL.field(DSL.name("policy_order"), Integer.class); + private static final Field BINDING_ID = DSL.field(DSL.name("binding_id"), UUID.class); + private static final Field SOURCE_BINDING_BYTES = + DSL.field(DSL.name("source_binding_bytes"), byte[].class); + private static final Field SOURCE_BINDING_DIGEST = + DSL.field(DSL.name("source_binding_digest"), String.class); + private static final Field PROJECTION_BYTES = + DSL.field(DSL.name("projection_bytes"), byte[].class); + private static final Field PROJECTION_DIGEST = + DSL.field(DSL.name("projection_digest"), String.class); + private static final Field CREATED_AT = + DSL.field(DSL.name("created_at"), Timestamp.class); + + private final DSLContext dsl; + + public StartSessionAuthoredActorCoreProjectionRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Allocates each Game Design binding identity only for a new owner row, inside its transaction. + * The caller must first complete its exact retained-owner retry check. + */ + public List insertForNewOwner( + Binding owner, List sourceBindings) { + requireTransaction(); + requireOwner(owner); + List sources = + List.copyOf(Objects.requireNonNull(sourceBindings, "sourceBindings")); + if (!findByOwner(owner).isEmpty()) { + throw new RetainedProjectionConflictException( + "Authored actor-core projection rows already exist for a new descriptor owner"); + } + + for (int index = 0; index < sources.size(); index++) { + AuthoredInitialActorCoreSourceBinding source = + requireSourceMatchesOwner(owner, sources.get(index)); + UUID bindingId = UUID.randomUUID(); + AuthoredInitialActorCoreProjection projection = + AuthoredInitialActorCoreProjection.fromValidatedBinding(bindingId, source); + byte[] sourceBytes = source.canonicalBytes(); + String sourceDigest = source.digest(); + byte[] projectionBytes = projection.canonicalBytes(); + + int inserted = + dsl.insertInto(TABLE) + .set(TARGET_NAMESPACE, owner.targetNamespace()) + .set(CANONICAL_TENANT_ID, owner.canonicalTenantId()) + .set(CONTROL_PLANE_REQUEST_ID, owner.controlPlaneRequestId()) + .set(DESCRIPTOR_ROW_ID, owner.descriptorRowId()) + .set(POLICY_ORDER, index) + .set(BINDING_ID, bindingId) + .set(SOURCE_BINDING_BYTES, sourceBytes) + .set(SOURCE_BINDING_DIGEST, sourceDigest) + .set(PROJECTION_BYTES, projectionBytes) + .set(PROJECTION_DIGEST, projection.digest()) + .onConflictDoNothing() + .execute(); + if (inserted != 1) { + throw new RetainedProjectionConflictException( + "Authored actor-core projection identity conflicted during new owner insertion"); + } + } + + return validateReplay(findByOwner(owner), sources, owner); + } + + /** Replays only a complete exact retained proof set; this method never repairs missing rows. */ + public List replayExact( + Binding owner, List sourceBindings) { + requireOwner(owner); + return validateReplay( + findByOwner(owner), + List.copyOf(Objects.requireNonNull(sourceBindings, "sourceBindings")), + owner); + } + + public List findByOwner(Binding owner) { + requireOwner(owner); + return List.copyOf( + dsl.selectFrom(TABLE) + .where( + TARGET_NAMESPACE + .eq(owner.targetNamespace()) + .and(CANONICAL_TENANT_ID.eq(owner.canonicalTenantId())) + .and(CONTROL_PLANE_REQUEST_ID.eq(owner.controlPlaneRequestId())) + .and(DESCRIPTOR_ROW_ID.eq(owner.descriptorRowId()))) + .orderBy(POLICY_ORDER.asc()) + .fetch(this::toRetainedProjection)); + } + + static List validateReplay( + List retained, + List sourceBindings, + Binding owner) { + Objects.requireNonNull(retained, "retained"); + List sources = + List.copyOf(Objects.requireNonNull(sourceBindings, "sourceBindings")); + requireOwner(owner); + if (sources.isEmpty()) { + if (!retained.isEmpty()) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core proofs differ from the exact source policy set"); + } + return List.of(); + } + if (retained.isEmpty()) { + throw new MissingRetainedProjectionException( + "Retained descriptor has no authored actor-core proof for its applicable policies"); + } + if (retained.size() != sources.size()) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core proof count differs from the exact source policy set"); + } + + Set bindingIds = new HashSet<>(); + List result = new ArrayList<>(sources.size()); + for (int index = 0; index < sources.size(); index++) { + RetainedProjection row = retained.get(index); + AuthoredInitialActorCoreSourceBinding source = + requireSourceMatchesOwner(owner, sources.get(index)); + if (row.policyOrder() != index + || !owner.targetNamespace().equals(row.targetNamespace()) + || !owner.canonicalTenantId().equals(row.canonicalTenantId()) + || !owner.controlPlaneRequestId().equals(row.controlPlaneRequestId()) + || !owner.descriptorRowId().equals(row.descriptorRowId()) + || !bindingIds.add(row.bindingId())) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core proof owner identity or order changed"); + } + + AuthoredInitialActorCoreSourceBinding storedSource; + AuthoredInitialActorCoreProjection projection; + try { + storedSource = + AuthoredInitialActorCoreSourceBinding.fromStored( + row.sourceBindingBytes(), row.sourceBindingDigest()); + projection = + AuthoredInitialActorCoreProjection.fromStored( + row.projectionBytes(), row.projectionDigest()); + } catch (IllegalArgumentException | IllegalStateException corrupt) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core proof bytes or digests are corrupt", corrupt); + } + if (!Arrays.equals(storedSource.canonicalBytes(), source.canonicalBytes()) + || !storedSource.digest().equals(source.digest()) + || !projection.bindingId().equals(row.bindingId()) + || !projection.bindingDigest().equals(source.digest())) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core private source proof differs from the exact source"); + } + + AuthoredInitialActorCoreProjection expected = + AuthoredInitialActorCoreProjection.fromValidatedBinding(row.bindingId(), source); + if (!Arrays.equals(expected.canonicalBytes(), row.projectionBytes()) + || !expected.digest().equals(row.projectionDigest()) + || !Arrays.equals(projection.canonicalBytes(), expected.canonicalBytes())) { + throw new RetainedProjectionConflictException( + "Retained authored actor-core projection differs from the exact private source"); + } + result.add(projection); + } + return List.copyOf(result); + } + + private RetainedProjection toRetainedProjection(Record row) { + Timestamp createdAt = row.get(CREATED_AT, Timestamp.class); + return new RetainedProjection( + row.get(TARGET_NAMESPACE), + row.get(CANONICAL_TENANT_ID), + row.get(CONTROL_PLANE_REQUEST_ID), + row.get(DESCRIPTOR_ROW_ID), + row.get(POLICY_ORDER), + row.get(BINDING_ID), + row.get(SOURCE_BINDING_BYTES), + row.get(SOURCE_BINDING_DIGEST), + row.get(PROJECTION_BYTES), + row.get(PROJECTION_DIGEST), + createdAt == null ? null : createdAt.toLocalDateTime()); + } + + private static AuthoredInitialActorCoreSourceBinding requireSourceMatchesOwner( + Binding owner, AuthoredInitialActorCoreSourceBinding source) { + Objects.requireNonNull(source, "source binding"); + AuthoredInitialActorCoreSourceBinding decoded; + try { + decoded = + AuthoredInitialActorCoreSourceBinding.fromStored( + source.canonicalBytes(), source.digest()); + } catch (IllegalArgumentException | IllegalStateException corrupt) { + throw new RetainedProjectionConflictException( + "Authored actor-core source binding failed complete canonical reconstruction", corrupt); + } + var selected = decoded.selectedCommit(); + if (!Objects.equals(owner.canonicalTenantId(), selected.target().canonicalTenantId()) + || !Objects.equals(owner.canonicalVersionId(), selected.target().canonicalVersionId()) + || !Objects.equals(owner.selectedCommitId(), selected.commitId()) + || !Objects.equals(owner.sourceOperationId(), decoded.worldSourceOperationId()) + || !Objects.equals(owner.sourceEvidenceDigest(), decoded.worldSourceEvidenceDigest()) + || !Objects.equals(owner.worldSlug(), decoded.expectedWorldSlug()) + || !Objects.equals(owner.publishWorkflowId(), decoded.publicationWorkflowId()) + || owner.releaseBundleId() == null + || owner.releaseBundleId() <= 0L + || !Arrays.equals(decoded.canonicalBytes(), source.canonicalBytes()) + || !decoded.digest().equals(source.digest())) { + throw new RetainedProjectionConflictException( + "Authored actor-core source binding differs from the exact descriptor owner identity"); + } + return decoded; + } + + private static void requireOwner(Binding owner) { + Objects.requireNonNull(owner, "owner binding"); + if (owner.targetNamespace() == null + || owner.targetNamespace().isBlank() + || owner.canonicalTenantId() == null + || owner.controlPlaneRequestId() == null + || owner.controlPlaneRequestId().isBlank() + || owner.descriptorRowId() == null + || owner.descriptorRowId() <= 0L + || owner.releaseBundleId() == null + || owner.releaseBundleId() <= 0L) { + throw new IllegalArgumentException("Exact retained descriptor owner binding required"); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored actor-core identity allocation requires the descriptor owner transaction"); + } + } + + /** Complete immutable source and projection proof keyed to the actual descriptor owner row. */ + public record RetainedProjection( + String targetNamespace, + UUID canonicalTenantId, + String controlPlaneRequestId, + Long descriptorRowId, + Integer policyOrder, + UUID bindingId, + byte[] sourceBindingBytes, + String sourceBindingDigest, + byte[] projectionBytes, + String projectionDigest, + LocalDateTime createdAt) { + public RetainedProjection { + sourceBindingBytes = cloneBytes(sourceBindingBytes); + projectionBytes = cloneBytes(projectionBytes); + } + + @Override + public byte[] sourceBindingBytes() { + return cloneBytes(sourceBindingBytes); + } + + @Override + public byte[] projectionBytes() { + return cloneBytes(projectionBytes); + } + + private static byte[] cloneBytes(byte[] value) { + return value == null ? null : value.clone(); + } + } + + public static class RetainedProjectionConflictException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + public RetainedProjectionConflictException(String message) { + super(message); + } + + public RetainedProjectionConflictException(String message, Throwable cause) { + super(message, cause); + } + } + + public static final class MissingRetainedProjectionException + extends RetainedProjectionConflictException { + private static final long serialVersionUID = 1L; + + public MissingRetainedProjectionException(String message) { + super(message); + } + } +} diff --git a/services/game-design-service/src/main/resources/db/migration/V73__retained_original_start_session_actor_core_projection.sql b/services/game-design-service/src/main/resources/db/migration/V73__retained_original_start_session_actor_core_projection.sql new file mode 100644 index 0000000000..69f3f36aa4 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V73__retained_original_start_session_actor_core_projection.sql @@ -0,0 +1,387 @@ +-- Game Design retains a private, complete source binding beside the public minimal projection. +-- No old descriptor is backfilled: pre-V73 owners have no provable GD-allocated binding identity. +ALTER TABLE game_design_start_session_launch_descriptor_binding + ADD CONSTRAINT uq_gd_start_session_launch_descriptor_owner + UNIQUE (target_namespace, canonical_tenant_id, control_plane_request_id, + launch_descriptor_row_id); + +CREATE TABLE game_design_start_session_authored_actor_core_projection ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + control_plane_request_id VARCHAR(255) NOT NULL, + launch_descriptor_row_id BIGINT NOT NULL, + policy_order INTEGER NOT NULL, + binding_id UUID NOT NULL UNIQUE, + source_binding_bytes BYTEA NOT NULL, + source_binding_digest VARCHAR(71) NOT NULL, + projection_bytes BYTEA NOT NULL, + projection_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gd_start_session_actor_core_projection PRIMARY KEY ( + target_namespace, canonical_tenant_id, control_plane_request_id, + launch_descriptor_row_id, policy_order), + CONSTRAINT fk_gd_start_session_actor_core_projection_owner FOREIGN KEY ( + target_namespace, canonical_tenant_id, control_plane_request_id, launch_descriptor_row_id) + REFERENCES game_design_start_session_launch_descriptor_binding ( + target_namespace, canonical_tenant_id, control_plane_request_id, launch_descriptor_row_id) + ON DELETE RESTRICT, + CONSTRAINT fk_gd_start_session_actor_core_projection_descriptor FOREIGN KEY ( + launch_descriptor_row_id) REFERENCES launch_descriptor (id) ON DELETE RESTRICT, + CONSTRAINT ck_gd_start_session_actor_core_projection_shape CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND control_plane_request_id !~ '^[[:space:]]*$' + AND launch_descriptor_row_id > 0 + AND policy_order BETWEEN 0 AND 127 + AND binding_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND octet_length(source_binding_bytes) BETWEEN 1 AND 16777216 + AND source_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(projection_bytes) BETWEEN 1 AND 1048576 + AND projection_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- [jooq ignore start] +-- Parse the same four-byte big-endian length frames used by the private Common source value. +CREATE FUNCTION gd_start_session_actor_core_source_frame_count(payload BYTEA) RETURNS INTEGER AS $$ +DECLARE offset_bytes INTEGER := 0; frame_length BIGINT; frame_count INTEGER := 0; +BEGIN + WHILE offset_bytes < octet_length(payload) LOOP + IF offset_bytes + 4 > octet_length(payload) THEN + RAISE EXCEPTION 'truncated authored actor-core source frame' USING ERRCODE = 'check_violation'; + END IF; + frame_length := get_byte(payload, offset_bytes)::BIGINT * 16777216 + + get_byte(payload, offset_bytes + 1)::BIGINT * 65536 + + get_byte(payload, offset_bytes + 2)::BIGINT * 256 + + get_byte(payload, offset_bytes + 3); + offset_bytes := offset_bytes + 4; + IF frame_length > octet_length(payload) - offset_bytes THEN + RAISE EXCEPTION 'invalid authored actor-core source frame length' USING ERRCODE = 'check_violation'; + END IF; + offset_bytes := offset_bytes + frame_length::INTEGER; + frame_count := frame_count + 1; + END LOOP; + IF offset_bytes <> octet_length(payload) THEN + RAISE EXCEPTION 'trailing authored actor-core source bytes' USING ERRCODE = 'check_violation'; + END IF; + RETURN frame_count; +END; +$$ LANGUAGE plpgsql IMMUTABLE STRICT; + +CREATE FUNCTION guard_gd_start_session_actor_core_projection() RETURNS trigger AS $$ +DECLARE owner game_design_start_session_launch_descriptor_binding%ROWTYPE; + descriptor launch_descriptor%ROWTYPE; + association game_design_selected_template_world_source_association%ROWTYPE; + source_operation game_design_authored_world_source_operations%ROWTYPE; + publication game_design_publication_operation%ROWTYPE; + release published_release_bundle%ROWTYPE; + commit_row game_design_draft_commit%ROWTYPE; + policy_snapshot game_design_realm_policy_snapshot%ROWTYPE; + policy_capture game_design_realm_policy_capture%ROWTYPE; + gameplay_snapshot game_design_gameplay_rule_snapshot%ROWTYPE; + private_source BYTEA; public_projection JSONB; policy_projection JSONB; + disposition_projection JSONB; feedback_projection JSONB; + disposition_binding JSONB; feedback_binding JSONB; + policy_json TEXT; disposition_json TEXT; feedback_json TEXT; expected_order INTEGER; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'authored actor-core projection proofs are insert-only and retained' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO STRICT owner + FROM game_design_start_session_launch_descriptor_binding + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND control_plane_request_id = NEW.control_plane_request_id + AND launch_descriptor_row_id = NEW.launch_descriptor_row_id; + SELECT * INTO STRICT descriptor FROM launch_descriptor WHERE id = NEW.launch_descriptor_row_id; + SELECT * INTO STRICT association + FROM game_design_selected_template_world_source_association + WHERE canonical_tenant_id = owner.canonical_tenant_id + AND canonical_version_id = owner.canonical_version_id + AND commit_id = owner.selected_commit_id + AND template_id = owner.game_template_id; + SELECT * INTO STRICT source_operation + FROM game_design_authored_world_source_operations + WHERE operation_id = owner.source_operation_id; + SELECT * INTO STRICT publication + FROM game_design_publication_operation + WHERE publish_workflow_id = owner.publish_workflow_id; + SELECT * INTO STRICT release FROM published_release_bundle WHERE id = owner.release_bundle_id; + SELECT * INTO STRICT commit_row + FROM game_design_draft_commit + WHERE canonical_tenant_id = owner.canonical_tenant_id + AND canonical_version_id = owner.canonical_version_id + AND commit_id = owner.selected_commit_id; + SELECT * INTO STRICT policy_snapshot + FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = owner.canonical_tenant_id + AND canonical_version_id = owner.canonical_version_id + AND commit_id = owner.selected_commit_id; + SELECT * INTO STRICT policy_capture + FROM game_design_realm_policy_capture + WHERE canonical_tenant_id = owner.canonical_tenant_id + AND canonical_version_id = owner.canonical_version_id + AND publish_workflow_id = owner.publish_workflow_id; + SELECT * INTO STRICT gameplay_snapshot + FROM game_design_gameplay_rule_snapshot + WHERE canonical_tenant_id = owner.canonical_tenant_id + AND canonical_version_id = owner.canonical_version_id + AND commit_id = owner.selected_commit_id; + + private_source := NEW.source_binding_bytes; + IF gd_start_session_actor_core_source_frame_count(private_source) <> 45 + OR NEW.source_binding_digest IS DISTINCT FROM 'sha256:' || encode(sha256(private_source), 'hex') + OR NEW.projection_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.projection_bytes), 'hex') THEN + RAISE EXCEPTION 'authored actor-core source or projection digest/frame count differs' + USING ERRCODE = 'check_violation'; + END IF; + public_projection := convert_from(NEW.projection_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(public_projection) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(public_projection)) <> 16 + OR (public_projection - ARRAY['schema', 'bindingId', 'bindingDigest', 'canonicalTenantId', + 'canonicalVersionId', 'worldSourceOperationId', 'worldSourceEvidenceDigest', 'worldSlug', + 'publicationWorkflowId', 'selectedCommitId', 'selectedCommitDigest', 'policy', 'core', + 'descriptor', 'disposition', 'safeFeedback']) IS DISTINCT FROM '{}'::JSONB THEN + RAISE EXCEPTION 'authored actor-core public projection must have its closed minimal shape' + USING ERRCODE = 'check_violation'; + END IF; + + IF convert_from(published_world_selector_frame(private_source, 0), 'UTF8') + IS DISTINCT FROM 'game-design-authored-initial-actor-core-source-binding/v1' + OR convert_from(published_world_selector_frame(private_source, 1), 'UTF8') IS DISTINCT FROM '1' + OR convert_from(published_world_selector_frame(private_source, 2), 'UTF8') + IS DISTINCT FROM owner.source_operation_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 3), 'UTF8') + IS DISTINCT FROM owner.source_evidence_digest + OR convert_from(published_world_selector_frame(private_source, 4), 'UTF8') + IS DISTINCT FROM owner.world_slug + OR convert_from(published_world_selector_frame(private_source, 5), 'UTF8') + IS DISTINCT FROM owner.publish_workflow_id + OR convert_from(published_world_selector_frame(private_source, 6), 'UTF8') + IS DISTINCT FROM owner.canonical_tenant_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 7), 'UTF8') + IS DISTINCT FROM owner.canonical_version_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 8), 'UTF8') + IS DISTINCT FROM commit_row.game_design_version_row_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 9), 'UTF8') + IS DISTINCT FROM commit_row.game_design_version_tenant_key + OR convert_from(published_world_selector_frame(private_source, 10), 'UTF8') + IS DISTINCT FROM commit_row.source_game_row_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 11), 'UTF8') + IS DISTINCT FROM commit_row.source_game_tenant_key + OR convert_from(published_world_selector_frame(private_source, 12), 'UTF8') + IS DISTINCT FROM commit_row.source_provenance_kind + OR convert_from(published_world_selector_frame(private_source, 13), 'UTF8') + IS DISTINCT FROM owner.selected_commit_id::TEXT + OR convert_from(published_world_selector_frame(private_source, 14), 'UTF8') + IS DISTINCT FROM commit_row.input_digest + OR published_world_selector_frame(private_source, 15) IS DISTINCT FROM convert_to(commit_row.binding_json, 'UTF8') + OR published_world_selector_frame(private_source, 16) IS DISTINCT FROM publication.request_bytes + OR published_world_selector_frame(private_source, 17) IS DISTINCT FROM publication.terminal_evidence_bytes + OR published_world_selector_frame(private_source, 18) IS DISTINCT FROM convert_to(policy_snapshot.snapshot_json, 'UTF8') + OR published_world_selector_frame(private_source, 27) IS DISTINCT FROM convert_to(gameplay_snapshot.snapshot_json, 'UTF8') + OR policy_capture.commit_id IS DISTINCT FROM owner.selected_commit_id + OR policy_capture.operation_bytes IS DISTINCT FROM publication.request_bytes + OR policy_capture.terminal_evidence_bytes IS DISTINCT FROM publication.terminal_evidence_bytes + OR policy_capture.release_content_bytes IS DISTINCT FROM publication.release_content_bytes + OR publication.outcome IS DISTINCT FROM 'PUBLISHED' + OR publication.version_id IS DISTINCT FROM commit_row.game_design_version_row_id + OR publication.tenant_id IS DISTINCT FROM commit_row.game_design_version_tenant_key + OR publication.release_content_bytes IS DISTINCT FROM publication_release_content(release) + OR publication.published_release_bundle_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(publication.release_content_bytes), 'hex') + OR release.id IS DISTINCT FROM owner.release_bundle_id + OR release.publish_workflow_id IS DISTINCT FROM owner.publish_workflow_id + OR release.version_id IS DISTINCT FROM commit_row.game_design_version_row_id + OR release.canonical_tenant_id IS DISTINCT FROM owner.canonical_tenant_id + OR release.canonical_version_id IS DISTINCT FROM owner.canonical_version_id + OR association.association_digest IS DISTINCT FROM owner.association_digest + OR association.source_operation_id IS DISTINCT FROM owner.source_operation_id + OR association.source_evidence_digest IS DISTINCT FROM owner.source_evidence_digest + OR association.world_slug IS DISTINCT FROM owner.world_slug + OR association.publish_workflow_id IS DISTINCT FROM owner.publish_workflow_id + OR source_operation.target_namespace IS DISTINCT FROM owner.target_namespace + OR source_operation.canonical_tenant_id IS DISTINCT FROM owner.canonical_tenant_id + OR source_operation.world_slug IS DISTINCT FROM owner.world_slug + OR source_operation.evidence_digest IS DISTINCT FROM owner.source_evidence_digest + OR descriptor.target_namespace IS DISTINCT FROM owner.target_namespace + OR descriptor.canonical_tenant_id IS DISTINCT FROM owner.canonical_tenant_id + OR descriptor.control_plane_request_id IS DISTINCT FROM owner.control_plane_request_id + OR descriptor.authored_world_source_operation_id IS DISTINCT FROM owner.source_operation_id + OR descriptor.authored_world_source_evidence_digest IS DISTINCT FROM owner.source_evidence_digest + OR descriptor.world_slug IS DISTINCT FROM owner.world_slug + OR descriptor.outcome_status NOT IN ('SUCCESS', 'FAILED') + OR (descriptor.outcome_status = 'SUCCESS' AND ( + owner.runtime_surface IS DISTINCT FROM 'EMPTY_V1' + OR descriptor.release_bundle_id IS DISTINCT FROM owner.release_bundle_id + OR descriptor.version_id IS DISTINCT FROM release.version_id)) + OR (descriptor.outcome_status = 'FAILED' + AND owner.runtime_surface IS DISTINCT FROM 'UNSUPPORTED_CAPTURE_V1') THEN + RAISE EXCEPTION 'private authored actor-core proof differs from descriptor, source, association, commit, or pinned release' + USING ERRCODE = 'check_violation'; + END IF; + + policy_json := convert_from(published_world_selector_frame(private_source, 22), 'UTF8'); + disposition_json := convert_from(published_world_selector_frame(private_source, 30), 'UTF8'); + feedback_json := convert_from(published_world_selector_frame(private_source, 38), 'UTF8'); + policy_projection := public_projection->'policy'; + disposition_projection := public_projection->'disposition'; + feedback_projection := public_projection->'safeFeedback'; + disposition_binding := convert_from(published_world_selector_frame(private_source, 34), 'UTF8')::JSONB; + feedback_binding := convert_from(published_world_selector_frame(private_source, 42), 'UTF8')::JSONB; + SELECT (ordered.policy_order)::INTEGER INTO expected_order + FROM ( + SELECT policy_item->>'commitId' AS commit_id, + policy_item->>'revisionId' AS revision_id, + policy_item->>'logicalRevisionId' AS logical_revision_id, + row_number() OVER ( + ORDER BY policy_item->'policy'->>'worldSlug', policy_item->'policy'->>'realmSlug') - 1 + AS policy_order + FROM jsonb_array_elements(policy_snapshot.snapshot_json::JSONB->'policies') policy_item + WHERE policy_item->'policy'->>'worldSlug' = owner.world_slug + AND policy_item->'policy'->'schemaVersion' = '3'::JSONB + AND policy_item->'policy'->>'initialActorCore' IS NOT NULL + ) ordered + WHERE ordered.commit_id = convert_from(published_world_selector_frame(private_source, 19), 'UTF8') + AND ordered.revision_id = convert_from(published_world_selector_frame(private_source, 20), 'UTF8') + AND ordered.logical_revision_id = convert_from(published_world_selector_frame(private_source, 21), 'UTF8'); + IF public_projection->>'schema' IS DISTINCT FROM 'game-design-authored-initial-actor-core-projection/v1' + OR public_projection->>'bindingId' IS DISTINCT FROM NEW.binding_id::TEXT + OR public_projection->>'bindingDigest' IS DISTINCT FROM NEW.source_binding_digest + OR public_projection->>'canonicalTenantId' IS DISTINCT FROM owner.canonical_tenant_id::TEXT + OR public_projection->>'canonicalVersionId' IS DISTINCT FROM owner.canonical_version_id::TEXT + OR public_projection->>'worldSourceOperationId' IS DISTINCT FROM owner.source_operation_id::TEXT + OR public_projection->>'worldSourceEvidenceDigest' IS DISTINCT FROM owner.source_evidence_digest + OR public_projection->>'worldSlug' IS DISTINCT FROM owner.world_slug + OR public_projection->>'publicationWorkflowId' IS DISTINCT FROM owner.publish_workflow_id + OR public_projection->>'selectedCommitId' IS DISTINCT FROM owner.selected_commit_id::TEXT + OR public_projection->>'selectedCommitDigest' IS DISTINCT FROM commit_row.input_digest + OR (SELECT count(*) FROM jsonb_object_keys(policy_projection)) <> 5 + OR (policy_projection - ARRAY['commitId', 'revisionId', 'logicalRevisionId', 'canonicalPolicyJson', 'contentDigest']) + IS DISTINCT FROM '{}'::JSONB + OR policy_projection->>'commitId' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 19), 'UTF8') + OR policy_projection->>'revisionId' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 20), 'UTF8') + OR policy_projection->>'logicalRevisionId' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 21), 'UTF8') + OR policy_projection->>'canonicalPolicyJson' IS DISTINCT FROM policy_json + OR policy_projection->>'contentDigest' IS DISTINCT FROM 'sha256:' || encode(sha256(convert_to(policy_json, 'UTF8')), 'hex') + OR expected_order IS DISTINCT FROM NEW.policy_order + OR NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(policy_snapshot.snapshot_json::JSONB->'policies') policy_item + WHERE policy_item->>'commitId' = convert_from(published_world_selector_frame(private_source, 19), 'UTF8') + AND policy_item->>'revisionId' = convert_from(published_world_selector_frame(private_source, 20), 'UTF8') + AND policy_item->>'logicalRevisionId' = convert_from(published_world_selector_frame(private_source, 21), 'UTF8') + AND policy_item->'policy' = policy_json::JSONB) + OR (public_projection->'core' - ARRAY['canonicalJson']) IS DISTINCT FROM '{}'::JSONB + OR public_projection->'core'->>'canonicalJson' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 26), 'UTF8') + OR (public_projection->'descriptor' - ARRAY['canonicalJson', 'digest']) IS DISTINCT FROM '{}'::JSONB + OR public_projection->'descriptor'->>'canonicalJson' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 25), 'UTF8') + OR public_projection->'descriptor'->>'digest' IS DISTINCT FROM + 'sha256:' || encode(sha256(published_world_selector_frame(private_source, 25)), 'hex') + OR (SELECT count(*) FROM jsonb_object_keys(disposition_projection)) <> 7 + OR (disposition_projection - ARRAY['key', 'definitionJson', 'definitionDigest', 'sourceCommitId', + 'sourceCommitDigest', 'revisionId', 'revisionOrder']) IS DISTINCT FROM '{}'::JSONB + OR disposition_projection->>'key' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 29), 'UTF8') + OR disposition_projection->>'definitionJson' IS DISTINCT FROM disposition_json + OR convert_from(published_world_selector_frame(private_source, 31), 'UTF8') IS DISTINCT FROM 'DISPOSITIONS' + OR published_world_selector_frame(private_source, 32) IS DISTINCT FROM + published_world_selector_frame(private_source, 30) + OR NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(gameplay_snapshot.snapshot_json::JSONB->'entries') rule_entry + WHERE rule_entry = jsonb_build_object( + 'family', 'DISPOSITIONS', + 'definitionJson', convert_from(published_world_selector_frame(private_source, 32), 'UTF8'), + 'sourceBindingJson', convert_from(published_world_selector_frame(private_source, 34), 'UTF8'), + 'sourceBindingDigest', convert_from(published_world_selector_frame(private_source, 33), 'UTF8'), + 'revisionOrder', convert_from(published_world_selector_frame(private_source, 35), 'UTF8'), + 'revisionId', convert_from(published_world_selector_frame(private_source, 36), 'UTF8'))) + OR disposition_projection->>'definitionDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(convert_to(disposition_json, 'UTF8')), 'hex') + OR disposition_projection->>'sourceCommitId' IS DISTINCT FROM disposition_binding->>'commitId' + OR disposition_projection->>'sourceCommitDigest' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 33), 'UTF8') + OR disposition_projection->>'revisionId' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 36), 'UTF8') + OR disposition_projection->>'revisionOrder' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 35), 'UTF8') + OR disposition_projection->>'sourceCommitDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(published_world_selector_frame(private_source, 34)), 'hex') + OR (SELECT count(*) FROM jsonb_object_keys(feedback_projection)) <> 7 + OR (feedback_projection - ARRAY['key', 'definitionJson', 'definitionDigest', 'sourceCommitId', + 'sourceCommitDigest', 'revisionId', 'revisionOrder']) IS DISTINCT FROM '{}'::JSONB + OR feedback_projection->>'key' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 37), 'UTF8') + OR feedback_projection->>'definitionJson' IS DISTINCT FROM feedback_json + OR convert_from(published_world_selector_frame(private_source, 39), 'UTF8') IS DISTINCT FROM 'FEEDBACK' + OR published_world_selector_frame(private_source, 40) IS DISTINCT FROM + published_world_selector_frame(private_source, 38) + OR NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(gameplay_snapshot.snapshot_json::JSONB->'entries') rule_entry + WHERE rule_entry = jsonb_build_object( + 'family', 'FEEDBACK', + 'definitionJson', convert_from(published_world_selector_frame(private_source, 40), 'UTF8'), + 'sourceBindingJson', convert_from(published_world_selector_frame(private_source, 42), 'UTF8'), + 'sourceBindingDigest', convert_from(published_world_selector_frame(private_source, 41), 'UTF8'), + 'revisionOrder', convert_from(published_world_selector_frame(private_source, 43), 'UTF8'), + 'revisionId', convert_from(published_world_selector_frame(private_source, 44), 'UTF8'))) + OR feedback_projection->>'definitionDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(convert_to(feedback_json, 'UTF8')), 'hex') + OR feedback_projection->>'sourceCommitId' IS DISTINCT FROM feedback_binding->>'commitId' + OR feedback_projection->>'sourceCommitDigest' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 41), 'UTF8') + OR feedback_projection->>'revisionId' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 44), 'UTF8') + OR feedback_projection->>'revisionOrder' IS DISTINCT FROM convert_from(published_world_selector_frame(private_source, 43), 'UTF8') + OR feedback_projection->>'sourceCommitDigest' IS DISTINCT FROM + 'sha256:' || encode(sha256(published_world_selector_frame(private_source, 42)), 'hex') THEN + RAISE EXCEPTION 'public actor-core projection differs from exact source or leaks an open proof shape' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION verify_gd_start_session_actor_core_projection_set() RETURNS trigger AS $$ +DECLARE policy_snapshot game_design_realm_policy_snapshot%ROWTYPE; + expected_count BIGINT; retained_count BIGINT; +BEGIN + SELECT * INTO STRICT policy_snapshot + FROM game_design_realm_policy_snapshot + WHERE canonical_tenant_id = NEW.canonical_tenant_id + AND canonical_version_id = NEW.canonical_version_id + AND commit_id = NEW.selected_commit_id; + SELECT count(*) INTO expected_count + FROM jsonb_array_elements(policy_snapshot.snapshot_json::JSONB->'policies') policy_item + WHERE policy_item->'policy'->>'worldSlug' = NEW.world_slug + AND policy_item->'policy'->'schemaVersion' = '3'::JSONB + AND policy_item->'policy'->>'initialActorCore' IS NOT NULL; + SELECT count(*) INTO retained_count + FROM game_design_start_session_authored_actor_core_projection proof + WHERE proof.target_namespace = NEW.target_namespace + AND proof.canonical_tenant_id = NEW.canonical_tenant_id + AND proof.control_plane_request_id = NEW.control_plane_request_id + AND proof.launch_descriptor_row_id = NEW.launch_descriptor_row_id; + IF expected_count IS DISTINCT FROM retained_count THEN + RAISE EXCEPTION 'new descriptor owner must retain every applicable authored actor-core proof in order' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_start_session_actor_core_projection + BEFORE INSERT OR UPDATE OR DELETE ON game_design_start_session_authored_actor_core_projection + FOR EACH ROW EXECUTE FUNCTION guard_gd_start_session_actor_core_projection(); + +CREATE FUNCTION reject_gd_start_session_actor_core_projection_truncate() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'authored actor-core projection proofs are retained' USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trg_gd_start_session_actor_core_projection_no_truncate + BEFORE TRUNCATE ON game_design_start_session_authored_actor_core_projection + FOR EACH STATEMENT EXECUTE FUNCTION reject_gd_start_session_actor_core_projection_truncate(); + +CREATE CONSTRAINT TRIGGER trg_gd_start_session_actor_core_projection_complete_owner_set + AFTER INSERT ON game_design_start_session_launch_descriptor_binding + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION verify_gd_start_session_actor_core_projection_set(); +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 1e3e3213c4..5af0582b8c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -68,8 +68,12 @@ import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSettlementEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadEvidence; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionSettlementInput; import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionAcquisitionGrpcClient; import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationAcquisitionClient; +import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionActivationProtectionAcquisitionClient; +import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionActivationProtectionSettlementClient; import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; @@ -95,16 +99,21 @@ import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence; import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.GrpcAuthoredInitialActorCoreReadClient; import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; import net.firedevops.firemud.common.gamedesign.RealmPolicySource; import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.gamedesign.StartSessionPublishedRealmPolicyReadGrpcCodec; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; import net.firedevops.firemud.common.gamelogic.GameLogicGameplayRuleIntakeTerminal; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationEvidence; import net.firedevops.firemud.common.gamelogic.GameLogicIntakeAuthorizationReadClient; @@ -120,6 +129,10 @@ import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.gamesession.GrpcOriginalStartSessionCurrentAttemptClient; +import net.firedevops.firemud.common.gamesession.GrpcOriginalStartSessionLaunchReadClient; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -158,12 +171,16 @@ import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationClient; import net.firedevops.firemud.common.world.CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput; +import net.firedevops.firemud.common.world.GrpcWorldOriginalStartSessionActivationTerminalReadClient; +import net.firedevops.firemud.common.world.GrpcWorldOriginalStartSessionProtectedActivationClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionProtectedActivationGrpcCodec; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeService; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeTerminalReadService; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityRetainedAuthoredActorCoreSourceService; import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestGrpcReceiver; import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestService; import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedSourceIntakeCommandGrpcService; @@ -189,11 +206,13 @@ import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.mapper.VersionMapper; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.publication.AuthoredInitialActorCoreReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadGrpcService; import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignSelectedOwnerIntakeSourceGrpcService; import net.firedevops.firemud.gamedesign.publication.GameDesignSelectedOwnerIntakeSourceReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; +import net.firedevops.firemud.gamedesign.publication.GrpcAuthoredInitialActorCoreReadService; import net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventory; import net.firedevops.firemud.gamedesign.publication.SelectedDraftAssetInventoryReadService; @@ -222,6 +241,8 @@ import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.RecordedParticipantDigestRepository; import net.firedevops.firemud.gamedesign.repository.RevisionRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionAuthoredActorCoreProjectionRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository; import net.firedevops.firemud.gamedesign.repository.VersionAssetPurgeWorkflowRepository; @@ -268,6 +289,7 @@ import net.firedevops.firemud.gamelogic.sourceintake.GameLogicPublicationSourceReadService; import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; @@ -275,7 +297,9 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; import net.firedevops.firemud.gamesession.service.impl.CanonicalGameInstanceLaunchAssociationReadGrpcService; +import net.firedevops.firemud.gamesession.service.impl.GameSessionAuthoredActorCoreRetentionService; import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadGrpcService; +import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionLaunchReadGrpcService; import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimEvidence; @@ -316,6 +340,9 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldDraftTerminalReadGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplicationService; import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalDraftGraphApplyGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionActivationTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationService; import net.firedevops.firemud.worldmanagement.tenant.WorldSelectedOwnerInventoryReadProofFixture; import net.firedevops.firemud.worldmanagement.tenant.WorldStartSessionAccountParticipationVerifier; import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceRequest; @@ -410,14 +437,16 @@ * its canonical public-realm catalog. Game Session creates and independently reads the exact * STARTING runtime/launch association with its captured catalog revision, and World consumes that * evidence through the native exact-peer Game Session reader. Account participation is - * point-in-time evidence, not a continuous cross-service lock. Activation authority remains an - * explicit fixture stipulation. The added admission path uses the actual World initial hold, - * Account protection acquisition, Account-only Game Session terminal read and Account settlement. - * It proves pending denial and a durable original abort without opening the CLOSED pointer; it does - * not prove the positive RUNNING transition, settle the World hold or supply activation authority. + * point-in-time evidence, not a continuous cross-service lock. The distinct activation-purpose + * Account source protection is acquired by the actual unregistered World producer over + * same-namespace mTLS before World's native PREPARING-to-ACTIVE CAS; Account then settles the exact + * authenticated World terminal over mTLS. The added admission path uses the actual World initial + * hold, Account protection acquisition, Account-only Game Session terminal read and Account + * settlement. It proves pending denial and a durable original abort without opening the CLOSED + * pointer; it does not prove the positive RUNNING transition or settle the World admission hold. * This does not establish production certificate custody, full application server wiring, - * production ingress, runtime launch, activation or registration. The Logging evidence is - * point-in-time and does not lock later Account or Game Session commits. + * production ingress, runtime launch, activation registration, or admission. The Logging evidence + * is point-in-time and does not lock later Account or Game Session commits. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -607,9 +636,21 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex new net.firedevops.firemud.common.gamesession .GrpcOriginalStartSessionAdmissionTerminalReadClient( endpoints, pki.client("account-service"), channels, NAMESPACE); + var accountToGameSessionLaunchReadClient = + new GrpcOriginalStartSessionLaunchReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var accountToWorldActivationTerminalReadClient = + new GrpcWorldOriginalStartSessionActivationTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); var gameSessionToAccountAdmissionClient = new AccountStartSessionAdmissionProtectionAcquisitionGrpcClient( endpoints, pki.client("game-session-service"), channels, NAMESPACE); + var worldToAccountActivationProtectionClient = + new GrpcAccountStartSessionActivationProtectionAcquisitionClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var worldToAccountActivationSettlementClient = + new GrpcAccountStartSessionActivationProtectionSettlementClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); var worldToAccountParticipationClient = new AccountStartSessionWorldParticipationAcquisitionClient( endpoints, pki.client("world-management-service"), channels, NAMESPACE); @@ -631,6 +672,15 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var gameSessionPublishedRealmPolicyClient = new GameDesignPublishedRealmPolicyClient( endpoints, pki.client("game-session-service"), channels, NAMESPACE); + var gameSessionToGameDesignAuthoredCoreClient = + new GrpcAuthoredInitialActorCoreReadClient( + endpoints, pki.client("game-session-service"), channels, NAMESPACE); + var entityToGameDesignAuthoredCoreClient = + new GrpcAuthoredInitialActorCoreReadClient( + endpoints, pki.client("entity-management-service"), channels, NAMESPACE); + var unauthorizedAccountToGameDesignAuthoredCoreClient = + new GrpcAuthoredInitialActorCoreReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); var worldToGameSessionLaunchClient = new CanonicalGameInstanceLaunchAssociationClient( endpoints, pki.client("world-management-service"), channels, NAMESPACE); @@ -642,6 +692,12 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex endpoints, pki.client("world-management-service"), channels, NAMESPACE); var wrongWorkloadActivationClient = canonicalActivationClient(worldServer, pki.client("account-service"), channels); + var gameSessionToWorldProtectedActivationClient = + new GrpcWorldOriginalStartSessionProtectedActivationClient( + endpoints, pki.client("game-session-service"), channels, NAMESPACE); + var wrongWorkloadProtectedActivationClient = + new GrpcWorldOriginalStartSessionProtectedActivationClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); var gameSessionInitialHoldClient = new CanonicalInitialAdmissionHoldTransportFixture( loopback(worldServer), @@ -654,6 +710,10 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex ReflectionTestUtils.invokeMethod(loggingClaimClient, "init"); accountToGameSessionCurrentAttemptClient.init(); accountToGameSessionTerminalClient.init(); + accountToGameSessionLaunchReadClient.init(); + accountToWorldActivationTerminalReadClient.init(); + worldToAccountActivationProtectionClient.init(); + worldToAccountActivationSettlementClient.init(); gameSessionToAccountAdmissionClient.init(); worldToAccountParticipationClient.init(); projectionClient.init(); @@ -662,9 +722,14 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex gameSessionPreparationRetryClient.init(); gameSessionFreshTenantCreationClient.init(); gameSessionPublishedRealmPolicyClient.init(); + gameSessionToGameDesignAuthoredCoreClient.init(); + entityToGameDesignAuthoredCoreClient.init(); + unauthorizedAccountToGameDesignAuthoredCoreClient.init(); worldToGameSessionLaunchClient.init(); wrongWorkloadLaunchClient.init(); worldToGameDesignPreparationClient.init(); + gameSessionToWorldProtectedActivationClient.init(); + wrongWorkloadProtectedActivationClient.init(); var automationIntakeRepository = new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); var entityIntakeRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); @@ -1115,6 +1180,18 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex accountHandlers, new AccountStartSessionAdmissionProtectionAcquisitionGrpcService( accountAdmissionProtectionAcquisition, NAMESPACE)); + var accountActivationProtectionAcquisition = + startSessionAuthorizationProof.activationProtectionAcquisitionService( + accountToGameSessionCurrentAttemptClient, accountToGameSessionLaunchReadClient); + var accountActivationProtectionSettlement = + startSessionAuthorizationProof.activationProtectionSettlementService( + accountToWorldActivationTerminalReadClient); + register( + accountHandlers, + new AccountStartSessionActivationProtectionAcquisitionGrpcService( + accountActivationProtectionAcquisition, NAMESPACE), + new AccountStartSessionActivationProtectionSettlementGrpcService( + accountActivationProtectionSettlement, NAMESPACE)); var accountWorldParticipationAcquisitionService = startSessionAuthorizationProof.worldParticipationAcquisitionService( accountToGameSessionCurrentAttemptClient); @@ -2515,6 +2592,12 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex var startSessionAssociationReader = new StartSessionTemplateAssociationReadService( gd.dsl(), gd.transactions(), NAMESPACE, projectionClient, releaseService); + register( + gdHandlers, + new GrpcAuthoredInitialActorCoreReadService( + new AuthoredInitialActorCoreReadService( + gd.dsl(), NAMESPACE, startSessionAssociationReader, new ObjectMapper()), + NAMESPACE)); var startSessionPublishedPolicyReader = new StartSessionPublishedRealmPolicyReadService( sourceRepository, @@ -3053,6 +3136,7 @@ public void attachAccountRedemptionProjection( OriginalOperationInput originalOwnerOperation = new OriginalOperationInput( startSessionTuple.canonicalBytes(), ownerMutationId, ownerAttemptId, ownerFence); + StartSessionTemplateAssociationReadEvidence.Result firstStartSessionSelection; { var accountProjection = projectionClient.read(startSessionTuple, ownerAttemptId, ownerFence); @@ -3090,6 +3174,17 @@ public void attachAccountRedemptionProjection( .containsExactly(startSessionTuple.authorityEvidenceBundleBytes()); assertThat(projectionClient.read(startSessionTuple, ownerAttemptId, ownerFence)) .isEqualTo(accountProjection); + var firstSelectionRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + StartSessionTemplateAssociationReadEvidence.SCHEMA_VERSION, + NAMESPACE, + UUID.randomUUID(), + startSessionTuple.canonicalBytes(), + ownerAttemptId, + ownerFence, + new StartSessionTemplateAssociationReadEvidence.InitialConfigured()); + firstStartSessionSelection = + withGameSessionPeer(() -> startSessionAssociationReader.read(firstSelectionRequest)); var descriptorProducer = new StartSessionLaunchDescriptorProducer( gd.dsl(), @@ -3113,6 +3208,144 @@ public void attachAccountRedemptionProjection( assertThat(firstDescriptorBinding.descriptor().launchDescriptorId()).isNotBlank(); assertThat(firstDescriptorBinding.associationRead().association().associationDigest()) .isEqualTo(association.digest()); + assertThat(firstStartSessionSelection.association()) + .isEqualTo(firstDescriptorBinding.associationRead().association()); + assertThat(firstStartSessionSelection.releaseBundle()) + .isEqualTo(firstDescriptorBinding.associationRead().releaseBundle()); + assertThat(firstStartSessionSelection.worldPublishedStartLocationEvidence()) + .isEqualTo( + firstDescriptorBinding.associationRead().worldPublishedStartLocationEvidence()); + assertThat(firstStartSessionSelection.phaseEpoch()) + .isEqualTo(firstDescriptorBinding.associationRead().phaseEpoch()); + var retainedDescriptorOwner = + new StartSessionLaunchDescriptorRepository(gd.dsl()) + .find(NAMESPACE, gd.target().canonicalTenantId(), controlPlaneRequestId) + .orElseThrow(); + var actorCoreProjectionRepository = + new StartSessionAuthoredActorCoreProjectionRepository(gd.dsl()); + var retainedActorCoreProofsBeforeRead = + actorCoreProjectionRepository.findByOwner(retainedDescriptorOwner); + assertThat(retainedActorCoreProofsBeforeRead).isEmpty(); + assertThat(expectedPolicy.policy().entryPolicy()) + .isEqualTo(RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); + assertThat(expectedPolicy.policy().canonicalJson()).doesNotContain("initialActorCore"); + + var authoredCoreReadRequest = + new AuthoredInitialActorCoreReadEvidence.ReadRequest( + firstDescriptorBinding.request()); + var gameSessionAuthoredCoreRead = + gameSessionToGameDesignAuthoredCoreClient.read(authoredCoreReadRequest); + assertThat(gameSessionAuthoredCoreRead.request()) + .isEqualTo(firstDescriptorBinding.request()); + assertThat(gameSessionAuthoredCoreRead.request().canonicalPostAuthorizationTuple()) + .containsExactly(startSessionTuple.canonicalBytes()); + assertThat(gameSessionAuthoredCoreRead.request().ownerAttemptId()) + .isEqualTo(ownerAttemptId); + assertThat(gameSessionAuthoredCoreRead.request().ownerFence()).isEqualTo(ownerFence); + assertThat(gameSessionAuthoredCoreRead.associationRead()) + .isEqualTo(firstDescriptorBinding.associationRead()); + assertThat( + gameSessionAuthoredCoreRead.associationRead().association().associationDigest()) + .isEqualTo(association.digest()); + assertThat(gameSessionAuthoredCoreRead.associationRead().releaseBundle()) + .isEqualTo(firstDescriptorBinding.associationRead().releaseBundle()); + assertThat(gameSessionAuthoredCoreRead.descriptor().launchDescriptorId()) + .isEqualTo(firstDescriptorBinding.descriptor().launchDescriptorId()); + assertThat(gameSessionAuthoredCoreRead.descriptor().requestDigest()) + .isEqualTo( + firstDescriptorBinding.descriptor().authoredWorldBinding().requestDigest()); + assertThat(gameSessionAuthoredCoreRead.descriptor().resultDigest()) + .isEqualTo(firstDescriptorBinding.descriptor().authoredWorldBinding().resultDigest()); + assertThat(gameSessionAuthoredCoreRead.projections()).isEmpty(); + assertThat(firstDescriptorBinding.actorCoreProjections()).isEmpty(); + var exactGameSessionAuthoredCoreRetry = + gameSessionToGameDesignAuthoredCoreClient.read(authoredCoreReadRequest); + assertThat(exactGameSessionAuthoredCoreRetry.canonicalBytes()) + .containsExactly(gameSessionAuthoredCoreRead.canonicalBytes()); + var entityAuthoredCoreRead = + entityToGameDesignAuthoredCoreClient.read(authoredCoreReadRequest); + assertThat(entityAuthoredCoreRead.canonicalBytes()) + .containsExactly(gameSessionAuthoredCoreRead.canonicalBytes()); + var entityRetainedAuthoredCoreSourceService = + new EntityRetainedAuthoredActorCoreSourceService( + NAMESPACE, entityToGameDesignAuthoredCoreClient, entityIntakeRepository); + var entityCorroboratedAuthoredCoreRead = + entityRetainedAuthoredCoreSourceService.read(authoredCoreReadRequest); + assertThat(entityCorroboratedAuthoredCoreRead.canonicalBytes()) + .containsExactly(entityAuthoredCoreRead.canonicalBytes()); + assertThat(entityCorroboratedAuthoredCoreRead.projections()).isEmpty(); + var exactEntityCorroboratedAuthoredCoreRetry = + entityRetainedAuthoredCoreSourceService.read(authoredCoreReadRequest); + assertThat(exactEntityCorroboratedAuthoredCoreRetry.canonicalBytes()) + .containsExactly(entityCorroboratedAuthoredCoreRead.canonicalBytes()); + String publicAuthoredCoreResult = + new String(gameSessionAuthoredCoreRead.canonicalBytes(), StandardCharsets.UTF_8); + assertThat(publicAuthoredCoreResult) + .doesNotContain("privateTargetProof") + .doesNotContain("terminalEvidenceBytes") + .doesNotContain("sourceCaptureBytes") + .doesNotContain("publicationOperationBytes"); + assertThat(actorCoreProjectionRepository.findByOwner(retainedDescriptorOwner)) + .containsExactlyElementsOf(retainedActorCoreProofsBeforeRead); + + var substitutedTuple = + startSessionTuple( + "genuine-authored-core-substitute-" + UUID.randomUUID(), + gd.target().canonicalTenantId(), + templateId, + "Substituted authored-core original tuple"); + var substitutedTupleRead = + new AuthoredInitialActorCoreReadEvidence.ReadRequest( + startSessionReadRequest( + substitutedTuple, + ownerAttemptId, + ownerFence, + pinnedSelection, + UUID.randomUUID())); + assertThatThrownBy( + () -> gameSessionToGameDesignAuthoredCoreClient.read(substitutedTupleRead)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + + var substitutedSelection = + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + pinnedSelection.canonicalVersionId(), + pinnedSelection.selectedCommitId(), + pinnedSelection.publishWorkflowId(), + changedDigest(pinnedSelection.associationDigest())); + var substitutedSelectionRead = + new AuthoredInitialActorCoreReadEvidence.ReadRequest( + startSessionReadRequest( + startSessionTuple, + ownerAttemptId, + ownerFence, + substitutedSelection, + UUID.randomUUID())); + assertThatThrownBy( + () -> gameSessionToGameDesignAuthoredCoreClient.read(substitutedSelectionRead)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + + assertThatThrownBy( + () -> + new AuthoredInitialActorCoreReadEvidence.ReadRequest( + startSessionReadRequest( + startSessionTuple, + ownerAttemptId, + ownerFence, + new StartSessionTemplateAssociationReadEvidence.InitialConfigured(), + UUID.randomUUID()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + unauthorizedAccountToGameDesignAuthoredCoreClient.read( + authoredCoreReadRequest)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + assertThat(actorCoreProjectionRepository.findByOwner(retainedDescriptorOwner)) + .containsExactlyElementsOf(retainedActorCoreProofsBeforeRead); + var expectedAuthoredWorldBinding = firstDescriptorBinding.descriptor().authoredWorldBinding(); @@ -3474,10 +3707,162 @@ public void attachAccountRedemptionProjection( .isEqualTo(canonicalRealmCatalog.catalogRevision()); assertThat(playableStateNamespaceId) .isEqualTo(canonicalRealmCatalog.playableStateNamespaceId()); + var preparationAssociationRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + NAMESPACE, + gd.target().canonicalTenantId(), + canonicalLaunch.canonicalRealmCatalog().worldSlug(), + canonicalLaunch.gameInstanceUuid(), + canonicalLaunch.controlPlaneRequestId(), + canonicalLaunch.launchBindingEvidence().descriptor().launchDescriptorId(), + canonicalLaunch.launchBindingEvidence().descriptor().requestDigest(), + canonicalLaunch.launchBindingEvidence().descriptor().resultDigest(), + canonicalLaunch.launchBindingEvidence().releaseAttestation().evidenceDigest()); + + // Reuse the original InitialConfigured owner selection above. This local owner readback + // is not an authenticated historical-evidence RPC. + + var originalCurrentAttemptRequest = + new OriginalStartSessionCurrentAttemptEvidence.Request( + UUID.randomUUID(), + NAMESPACE, + startSessionTuple.canonicalBytes(), + ownerAttemptId, + ownerMutationId, + ownerFence); + var currentOwnerAttemptBeforeRetention = + Objects.requireNonNull( + gameSessionAttempts.transactions.execute( + status -> + gameSessionAttempts.repository.readCurrentOriginalAttempt( + originalCurrentAttemptRequest)), + "Actual retained Game Session owner attempt"); + assertThat(currentOwnerAttemptBeforeRetention.accountRedemptionProjection()) + .containsExactly( + StartSessionAccountRedemptionProjection.fromOriginalTuple(startSessionTuple)); + + var retainedDescriptorPin = + new StartSessionLaunchDescriptorGrpcCodec.Resolved( + firstDescriptorBinding.associationRead(), + new StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome( + firstDescriptorBinding.descriptor().authoredWorldBinding())); + var retainedLaunchAssociation = + new HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation( + canonicalLaunch.targetNamespace(), + canonicalLaunch.canonicalTenantId(), + canonicalLaunch.canonicalRealmCatalog().worldSlug(), + canonicalLaunch.gameInstanceUuid(), + canonicalLaunch.controlPlaneRequestId(), + canonicalLaunch.launchBindingEvidence().descriptor().launchDescriptorId(), + canonicalLaunch.playableStateNamespaceId(), + canonicalLaunch.playableStateScope(), + canonicalLaunch.publicProduction(), + canonicalLaunch.capturedStartingRowVersion(), + canonicalLaunch.launchBindingEvidence()); + var historicalOwnerEvidence = + new HistoricalOriginalStartSessionOwnerEvidence.Result( + new HistoricalOriginalStartSessionOwnerEvidence.Request( + preparationAssociationRequest, ownerAttemptId, ownerFence), + startSessionTuple, + ownerAttemptId, + ownerFence, + currentOwnerAttemptBeforeRetention.accountRedemptionProjection(), + firstStartSessionSelection, + retainedDescriptorPin, + retainedLaunchAssociation, + HistoricalOriginalStartSessionOwnerEvidence.sha256( + StartSessionTemplateAssociationReadGrpcCodec.toRequest( + firstStartSessionSelection.request()) + .toByteArray()), + HistoricalOriginalStartSessionOwnerEvidence.sha256( + StartSessionTemplateAssociationReadGrpcCodec.toResponse( + firstStartSessionSelection) + .toByteArray()), + HistoricalOriginalStartSessionOwnerEvidence.sha256( + StartSessionLaunchDescriptorGrpcCodec.toRequest( + firstDescriptorBinding.request()) + .toByteArray()), + HistoricalOriginalStartSessionOwnerEvidence.sha256( + StartSessionLaunchDescriptorGrpcCodec.toResponse( + firstDescriptorBinding.request(), + firstDescriptorBinding.associationRead(), + new StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome( + firstDescriptorBinding.descriptor().authoredWorldBinding())) + .toByteArray())); + + var authoredCoreRetentionRepository = + new GameSessionAuthoredActorCoreRetentionRepository( + gameSessionAttempts.dsl(), gameSessionAttempts.transactionManager(), NAMESPACE); + var retainedGameDesignReadCalls = new AtomicInteger(); + AuthoredInitialActorCoreReadClient observedGameDesignCoreClient = + new AuthoredInitialActorCoreReadClient() { + @Override + public AuthoredInitialActorCoreReadEvidence.ReadResult read( + AuthoredInitialActorCoreReadEvidence.ReadRequest request) { + retainedGameDesignReadCalls.incrementAndGet(); + return gameSessionToGameDesignAuthoredCoreClient.read(request); + } + + @Override + public void close() {} + }; + var authoredCoreRetentionService = + new GameSessionAuthoredActorCoreRetentionService( + NAMESPACE, + canonicalLaunchRepository, + gameSessionAttempts.repository(), + observedGameDesignCoreClient, + authoredCoreRetentionRepository, + gameSessionAttempts.transactionManager()); + var firstRetainedAuthoredCore = + authoredCoreRetentionService.retain( + historicalOwnerEvidence, originalCurrentAttemptRequest); + assertThat(firstRetainedAuthoredCore.candidate().canonicalSourceResultBytes()) + .containsExactly(gameSessionAuthoredCoreRead.canonicalBytes()); + assertThat(firstRetainedAuthoredCore.candidate().originalPostAuthorizationTuple()) + .containsExactly(startSessionTuple.canonicalBytes()); + assertThat(firstRetainedAuthoredCore.candidate().gameInstanceUuid()) + .isEqualTo(canonicalLaunch.gameInstanceUuid()); + assertThat(firstRetainedAuthoredCore.candidate().ownerAttemptId()) + .isEqualTo(ownerAttemptId); + assertThat(firstRetainedAuthoredCore.candidate().ownerMutationId()) + .isEqualTo(ownerMutationId); + assertThat(firstRetainedAuthoredCore.candidate().ownerFence()).isEqualTo(ownerFence); + assertThat(firstRetainedAuthoredCore.candidate().ownerLeaseExpiresAt()) + .isEqualTo(currentOwnerAttemptBeforeRetention.leaseExpiresAt()); + assertThat(gameSessionAuthoredCoreRead.projections()).isEmpty(); + assertThat(retainedGameDesignReadCalls).hasValue(1); + var independentRetainedAuthoredCore = + authoredCoreRetentionRepository + .readByOriginalOperation(NAMESPACE, controlPlaneRequestId) + .orElseThrow(); + assertThat(independentRetainedAuthoredCore.candidate().canonicalSourceResultBytes()) + .containsExactly(gameSessionAuthoredCoreRead.canonicalBytes()); + var exactRetainedAuthoredCoreRetry = + authoredCoreRetentionService.retain( + historicalOwnerEvidence, originalCurrentAttemptRequest); + assertThat(exactRetainedAuthoredCoreRetry.candidate().canonicalSourceResultBytes()) + .containsExactly( + independentRetainedAuthoredCore.candidate().canonicalSourceResultBytes()); + assertThat(retainedGameDesignReadCalls).hasValue(1); + var currentOwnerAttemptAfterRetention = + Objects.requireNonNull( + gameSessionAttempts.transactions.execute( + status -> + gameSessionAttempts.repository.readCurrentOriginalAttempt( + originalCurrentAttemptRequest)), + "Current Game Session owner attempt after authored-core retention"); + assertThat(currentOwnerAttemptAfterRetention.leaseExpiresAt()) + .isEqualTo(currentOwnerAttemptBeforeRetention.leaseExpiresAt()); + register( gameSessionHandlers, new CanonicalGameInstanceLaunchAssociationReadGrpcService( canonicalLaunchRepository, NAMESPACE)); + register( + gameSessionHandlers, + new OriginalStartSessionLaunchReadGrpcService(canonicalLaunchRepository, NAMESPACE)); var canonicalAdmissionRepository = new net.firedevops.firemud.gamesession.repository .GameSessionCanonicalInitialAdmissionRepository( @@ -3491,18 +3876,6 @@ public void attachAccountRedemptionProjection( new net.firedevops.firemud.gamesession.service.impl .OriginalStartSessionAdmissionTerminalReadGrpcService( canonicalAdmissionRepository, NAMESPACE)); - var preparationAssociationRequest = - new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( - UUID.randomUUID(), - NAMESPACE, - gd.target().canonicalTenantId(), - worldSource.worldSlug(), - canonicalGameInstanceId, - controlPlaneRequestId, - completeLaunchEvidence.descriptor().launchDescriptorId(), - completeLaunchEvidence.descriptor().requestDigest(), - completeLaunchEvidence.descriptor().resultDigest(), - completeLaunchEvidence.releaseAttestation().evidenceDigest()); var independentCanonicalLaunch = canonicalLaunchRepository .readByLaunchIdentity(preparationAssociationRequest) @@ -3534,6 +3907,32 @@ public void attachAccountRedemptionProjection( .isEqualTo( CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus .STARTING); + var originalStartSessionLaunchReadRequest = + new OriginalStartSessionLaunchReadEvidence.Request( + preparationAssociationRequest, startSessionTuple.canonicalBytes()); + var originalStartSessionLaunchRead = + accountToGameSessionLaunchReadClient.read(originalStartSessionLaunchReadRequest); + assertThat(originalStartSessionLaunchRead.request()) + .isEqualTo(originalStartSessionLaunchReadRequest); + assertThat(originalStartSessionLaunchRead.retainedOriginalPostAuthorizationTupleBytes()) + .containsExactly(startSessionTuple.canonicalBytes()); + assertThat(originalStartSessionLaunchRead.launch().request()) + .isEqualTo(preparationAssociationRequest); + assertThat(originalStartSessionLaunchRead.launch().currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING); + assertThat(originalStartSessionLaunchRead.launch().launchBindingEvidence()) + .isEqualTo(completeLaunchEvidence); + assertThat(originalStartSessionLaunchRead.launch().canonicalRealmId()) + .isEqualTo(canonicalRealmCatalog.realmId()); + assertThat(originalStartSessionLaunchRead.launch().catalogRevision()) + .isEqualTo(canonicalRealmCatalog.catalogRevision()); + assertThat( + accountToGameSessionLaunchReadClient + .read(originalStartSessionLaunchReadRequest) + .canonicalBytes()) + .containsExactly(originalStartSessionLaunchRead.canonicalBytes()); var completeBindingRepository = new WorldCompleteLaunchBindingRepository(world.dsl()); var canonicalAssociationRepository = @@ -3868,61 +4267,35 @@ public void attachAccountRedemptionProjection( activationRequest.preparingEvidenceBytes())) .isFalse(); - var retainedGameSessionStartEvidence = - assembledPreparationInput.gameSessionReadEvidence(); - AtomicInteger activationAuthorityChecks = new AtomicInteger(); - AtomicInteger heldActivationChecks = new AtomicInteger(); - AtomicInteger heldActivationCloses = new AtomicInteger(); - var stipulatedActivationVerifier = - (WorldCanonicalInstanceActivationService.ActivationAuthorityVerifier) - candidate -> { - activationAuthorityChecks.incrementAndGet(); - if (!Arrays.equals( - candidate.canonicalRequestBytes(), - activationRequest.canonicalRequestBytes()) - || !"STARTING" - .equals(retainedGameSessionStartEvidence.currentGameSessionStatus()) - || !candidate - .preparing() - .launchBinding() - .equals( - new CompleteLaunchBindingEvidence( - retainedGameSessionStartEvidence.descriptor(), - retainedGameSessionStartEvidence.releaseAttestation()))) { - throw new SecurityException( - "Stipulated activation fixture differs from the exact PREPARING " - + "binding"); - } - return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { - private boolean held = true; - - @Override - public void requireHeld() { - if (!held - || !candidate.activationRequestId().equals(activationRequestId) - || !candidate - .requestDigest() - .equals(activationRequest.requestDigest())) { - throw new SecurityException( - "Stipulated activation authority no longer holds for this " - + "operation"); - } - heldActivationChecks.incrementAndGet(); - } - - @Override - public void close() { - held = false; - heldActivationCloses.incrementAndGet(); - } - }; - }; var activationService = - new WorldCanonicalInstanceActivationService( - activationRepository, stipulatedActivationVerifier); + new WorldCanonicalInstanceActivationService(activationRepository); + var protectedActivationService = + new WorldOriginalStartSessionProtectedActivationService( + activationRepository, + activationService, + worldToAccountActivationProtectionClient, + NAMESPACE); + var activationInput = + new AccountStartSessionActivationProtectionAcquisitionInput( + startSessionTuple.canonicalBytes(), + ownerMutationId, + ownerAttemptId, + ownerFence, + activationRequest); + assertThat(activationInput.worldActivationRequest().canonicalRequestBytes()) + .containsExactly(activationRequest.canonicalRequestBytes()); + assertThat( + WorldOriginalStartSessionProtectedActivationGrpcCodec.toRequest( + activationInput, NAMESPACE) + .getSerializedSize()) + .isLessThanOrEqualTo(20 * 1024 * 1024); register( worldHandlers, - new WorldCanonicalInstanceActivationGrpcService(activationService, NAMESPACE)); + new WorldCanonicalInstanceActivationGrpcService(activationService, NAMESPACE), + new WorldOriginalStartSessionProtectedActivationGrpcService( + protectedActivationService, NAMESPACE), + new WorldOriginalStartSessionActivationTerminalReadGrpcService( + activationService, NAMESPACE)); long activationOperationCountBefore = canonicalActivationOperationCount(world.dsl()); var preparationRowsBeforeActivation = canonicalPreparationRowCounts(world.dsl()); @@ -3950,7 +4323,19 @@ public void close() { assertThat(io.grpc.Status.fromThrowable(failure).getCode()) .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); } - assertThat(activationAuthorityChecks).hasValue(0); + assertThatThrownBy( + () -> wrongWorkloadProtectedActivationClient.activate(activationInput)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount(DSL.table("account_start_session_activation_protections"))) + .isZero(); assertThat(canonicalActivationOperationCount(world.dsl())) .isEqualTo(activationOperationCountBefore); assertThat(canonicalPreparationRowCounts(world.dsl())) @@ -3994,7 +4379,6 @@ public void close() { } finally { stopAll(defaultDeniedActivationServer); } - assertThat(activationAuthorityChecks).hasValue(0); assertThat(canonicalActivationOperationCount(world.dsl())) .isEqualTo(activationOperationCountBefore); assertThat(canonicalPreparationRowCounts(world.dsl())) @@ -4012,20 +4396,69 @@ public void close() { completeWorldSelector.request().publicationFence())) .isEqualTo(retainedEvidenceBeforeActivation); - // This explicitly stipulates current producer authority and its operation-specific - // held handle. STARTING association evidence comes from the actual Game Session - // launch owner and native authenticated read above, but that retained observation is - // not continuous Account/GS protection through the World activation commit. + // The request-only World activation endpoint remains default-denied even for the + // authenticated Game Session peer. Only the separate protected producer may acquire + // Account's distinct source protection and perform the PREPARING-to-ACTIVE CAS. + assertThatThrownBy( + () -> + gameSessionActivationClient.activate( + canonicalActivationTransportRequest(activationRequest))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + assertThat(canonicalActivationOperationCount(world.dsl())) + .isEqualTo(activationOperationCountBefore); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount(DSL.table("account_start_session_activation_protections"))) + .isZero(); + + // The World owner obtains a first full Account protection receipt over authenticated + // mTLS, then commits the exact local PREPARING-to-ACTIVE CAS. No source vector or + // Account authority is stipulated or supplied by this fixture. { - var firstActivationResponse = - gameSessionActivationClient.activate( - canonicalActivationTransportRequest(activationRequest)); - assertThat(firstActivationResponse.getActivationRequestId()) - .isEqualTo(activationRequestId.toString()); - byte[] committedActivationBytes = - firstActivationResponse.getCanonicalResultBytes().toByteArray(); - var committedActivation = - WorldCanonicalInstanceActivation.Result.fromStored(committedActivationBytes); + var firstTerminal = + gameSessionToWorldProtectedActivationClient.activate(activationInput); + var firstProtection = firstTerminal.accountProtectionEvidence(); + byte[] firstTerminalBytes = firstTerminal.canonicalBytes(); + byte[] firstProtectionBytes = firstProtection.canonicalBytes(); + var protectedRequest = firstProtection.request(); + assertThat(protectedRequest.originalPostAuthorizationTupleBytes()) + .containsExactly(startSessionTuple.canonicalBytes()); + assertThat(protectedRequest.gameSessionOwnerMutationId()).isEqualTo(ownerMutationId); + assertThat(protectedRequest.gameSessionOwnerAttemptId()).isEqualTo(ownerAttemptId); + assertThat(protectedRequest.gameSessionOwnerFence()).isEqualTo(ownerFence); + assertThat(protectedRequest.worldActivationRequest().canonicalRequestBytes()) + .containsExactly(activationRequest.canonicalRequestBytes()); + assertThat(protectedRequest.worldActivationRequest().preparingEvidenceBytes()) + .containsExactly(activationRequest.preparingEvidenceBytes()); + assertThat( + protectedRequest + .gameSessionLaunchReadEvidence() + .retainedOriginalPostAuthorizationTupleBytes()) + .containsExactly(startSessionTuple.canonicalBytes()); + assertThat(protectedRequest.gameSessionLaunchReadEvidence().operationIdentityBytes()) + .containsExactly(originalStartSessionLaunchRead.operationIdentityBytes()); + assertThat( + protectedRequest + .gameSessionLaunchReadEvidence() + .launch() + .currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING); + assertThat(protectedRequest.originalLeaseExpiresAt()) + .isAfter(firstProtection.acquiredAt()); + assertThat(firstProtection.originalSourceCaptureReferenceBytes()).isNotEmpty(); + assertThat(firstProtection.sourceEvidenceVector()).isNotEmpty(); + assertThat(firstProtection.accountProtectionFence()).isPositive(); + assertThat(firstTerminal.activationRequestId()).isEqualTo(activationRequestId); + assertThat(firstTerminal.worldActivationFence()).isPositive(); + var committedActivation = firstTerminal.activationResult(); assertThat(committedActivation.outcome()) .isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); assertThat(committedActivation.request().canonicalRequestBytes()) @@ -4053,18 +4486,38 @@ public void close() { assertThat(committedActivation.lifecycleEvidence().operationalRegionAssignments()) .containsExactlyInAnyOrderEntriesOf( preparedLifecycle.operationalRegionAssignments()); - assertThat(activationAuthorityChecks).hasValue(1); - assertThat(heldActivationChecks.get()).isGreaterThanOrEqualTo(2); - assertThat(heldActivationCloses).hasValue(1); assertThat(canonicalActivationOperationCount(world.dsl())) .isEqualTo(activationOperationCountBefore + 1L); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount(DSL.table("account_start_session_activation_protections"))) + .isOne(); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount( + DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount( + DSL.table("account_start_session_activation_protection_sources"))) + .isEqualTo(firstProtection.sourceEvidenceVector().size()); var preparationRowsAfterActivation = canonicalPreparationRowCounts(world.dsl()); assertThat(preparationRowsAfterActivation).isEqualTo(preparationRowsBeforeActivation); - var storedActivation = - activationRepository.readResult(activationRequest).orElseThrow(); - assertThat(storedActivation.canonicalBytes()) - .containsExactly(committedActivationBytes); + var protectedActivationReadback = + activationRepository + .readProtectedActivationByAcquisitionInput(activationInput) + .orElseThrow(); + assertThat(protectedActivationReadback.pending()).isFalse(); + assertThat(protectedActivationReadback.terminalEvidence().canonicalBytes()) + .containsExactly(firstTerminalBytes); var independentActiveRead = lifecycleRepository .read(lifecycleRequestWithFreshReadId(expectedLifecycleRequest)) @@ -4084,24 +4537,121 @@ public void close() { assertThat(independentActiveRead.preparationInputDigest()) .isEqualTo(preparedLifecycle.preparationInputDigest()); + var exactProtectedRetry = + gameSessionToWorldProtectedActivationClient.activate(activationInput); + assertThat(exactProtectedRetry.canonicalBytes()).containsExactly(firstTerminalBytes); + var alternateCorrelationInput = + new AccountStartSessionActivationProtectionAcquisitionInput( + startSessionTuple.canonicalBytes(), + ownerMutationId, + ownerAttemptId, + ownerFence, + alternateCorrelationRetry); + var alternateCorrelationProtectedRetry = + gameSessionToWorldProtectedActivationClient.activate(alternateCorrelationInput); + assertThat(alternateCorrelationProtectedRetry.canonicalBytes()) + .containsExactly(firstTerminalBytes); assertThat( - gameSessionActivationClient - .activate(canonicalActivationTransportRequest(activationRequest)) - .getCanonicalResultBytes() - .toByteArray()) - .containsExactly(committedActivationBytes); - assertThat( - gameSessionActivationClient - .activate(canonicalActivationTransportRequest(alternateCorrelationRetry)) - .getCanonicalResultBytes() - .toByteArray()) - .containsExactly(committedActivationBytes); - assertThat(activationAuthorityChecks).hasValue(1); - assertThat(heldActivationCloses).hasValue(1); + alternateCorrelationProtectedRetry + .accountProtectionEvidence() + .canonicalBytes()) + .containsExactly(firstProtectionBytes); assertThat(canonicalActivationOperationCount(world.dsl())) .isEqualTo(activationOperationCountBefore + 1L); assertThat(canonicalPreparationRowCounts(world.dsl())) .isEqualTo(preparationRowsAfterActivation); + assertThat( + retainedWorldPreparationEvidence( + world, + worldIntakeReceipt.intakeRequestId(), + worldIdentityReceipt.operationId(), + gd.target().canonicalTenantId(), + controlPlaneRequestId, + canonicalGameInstanceId, + completeWorldSelector.request().publicationFence())) + .isEqualTo(retainedEvidenceBeforeActivation); + + var changedTuple = + startSessionTuple( + controlPlaneRequestId, + gd.target().canonicalTenantId(), + startSessionTuple.preAuthorizationTuple().action().target().gameTemplateId(), + "changed activation tuple must not reuse retained protection"); + var changedTupleInput = + new AccountStartSessionActivationProtectionAcquisitionInput( + changedTuple.canonicalBytes(), + ownerMutationId, + ownerAttemptId, + ownerFence, + activationRequest); + assertThatThrownBy( + () -> gameSessionToWorldProtectedActivationClient.activate(changedTupleInput)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + var changedAttemptInput = + new AccountStartSessionActivationProtectionAcquisitionInput( + startSessionTuple.canonicalBytes(), + ownerMutationId, + UUID.randomUUID(), + ownerFence, + activationRequest); + assertThatThrownBy( + () -> + gameSessionToWorldProtectedActivationClient.activate(changedAttemptInput)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + var changedFenceInput = + new AccountStartSessionActivationProtectionAcquisitionInput( + startSessionTuple.canonicalBytes(), + ownerMutationId, + ownerAttemptId, + ownerFence + 1L, + activationRequest); + assertThatThrownBy( + () -> gameSessionToWorldProtectedActivationClient.activate(changedFenceInput)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + var changedActivationRequest = + new WorldCanonicalInstanceActivation.Request( + UUID.randomUUID(), preparedLifecycle); + var changedActivationInput = + new AccountStartSessionActivationProtectionAcquisitionInput( + startSessionTuple.canonicalBytes(), + ownerMutationId, + ownerAttemptId, + ownerFence, + changedActivationRequest); + assertThatThrownBy( + () -> + gameSessionToWorldProtectedActivationClient.activate( + changedActivationInput)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount(DSL.table("account_start_session_activation_protections"))) + .isOne(); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount( + DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); var changedEvidence = new WorldCanonicalInstanceLifecycleEvidence( @@ -4128,14 +4678,18 @@ public void close() { .isFalse(); assertThatThrownBy( () -> - gameSessionActivationClient.activate( - canonicalActivationTransportRequest(changedEvidenceRetry))) + gameSessionToWorldProtectedActivationClient.activate( + new AccountStartSessionActivationProtectionAcquisitionInput( + startSessionTuple.canonicalBytes(), + ownerMutationId, + ownerAttemptId, + ownerFence, + changedEvidenceRetry))) .isInstanceOf(io.grpc.StatusRuntimeException.class) .satisfies( failure -> assertThat(io.grpc.Status.fromThrowable(failure).getCode()) - .isEqualTo(io.grpc.Status.Code.ALREADY_EXISTS)); - assertThat(activationAuthorityChecks).hasValue(1); + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); assertThat(canonicalActivationOperationCount(world.dsl())) .isEqualTo(activationOperationCountBefore + 1L); assertThat(canonicalPreparationRowCounts(world.dsl())) @@ -4154,9 +4708,50 @@ public void close() { assertThat(activeReadAfterConflict.startLocation()) .isEqualTo(independentActiveRead.startLocation()); + var settledActivation = + worldToAccountActivationSettlementClient.settle( + new AccountStartSessionActivationProtectionSettlementInput( + NAMESPACE, + UUID.randomUUID(), + firstProtection.accountProtectionId(), + firstProtection.accountProtectionFence())); + assertThat(settledActivation.accountProtectionId()) + .isEqualTo(firstProtection.accountProtectionId()); + assertThat(settledActivation.accountProtectionFence()) + .isEqualTo(firstProtection.accountProtectionFence()); + assertThat(settledActivation.terminal().canonicalBytes()) + .containsExactly(firstTerminalBytes); + assertThat(settledActivation.settledAt()).isNotNull(); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount( + DSL.table("account_start_session_activation_protection_settlements"))) + .isOne(); + var settledActivationRetry = + worldToAccountActivationSettlementClient.settle( + new AccountStartSessionActivationProtectionSettlementInput( + NAMESPACE, + UUID.randomUUID(), + firstProtection.accountProtectionId(), + firstProtection.accountProtectionFence())); + assertThat(settledActivationRetry.terminal().canonicalBytes()) + .containsExactly(firstTerminalBytes); + assertThat(settledActivationRetry.settledAt()) + .isEqualTo(settledActivation.settledAt()); + assertThat( + accountAccess + .sources() + .dsl + .fetchCount( + DSL.table("account_start_session_activation_protection_settlements"))) + .isOne(); + // Genuine GS/Account terminal recovery below is deliberately an abort, not - // successful admission: the real launch still remains STARTING. World activation - // authority above remains stipulated and is not promoted by these owner results. + // successful admission: the real launch still remains STARTING. The Account + // activation-purpose source protection above is separately settled by the exact + // authenticated World ACTIVE receipt. var closedPointer = Objects.requireNonNull( gameSessionAttempts diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java new file mode 100644 index 0000000000..32ca3cce44 --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java @@ -0,0 +1,201 @@ +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.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.LocalDateTime; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.repository.StartSessionAuthoredActorCoreProjectionRepository; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository.Binding; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL migration/storage proof; the synthetic row is not authenticated source authority. */ +@Testcontainers(disabledWithoutDocker = true) +class StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest { + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + + @Container + static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void migratesOwnerKeyReadsSyntheticRetainedStorageAndRejectsMutation() throws Exception { + String schema = "gd_actor_core_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()) + .load() + .migrate(); + + UUID tenantId = UUID.randomUUID(); + UUID bindingId = UUID.randomUUID(); + String requestId = "synthetic-actor-core-owner"; + byte[] sourceBytes = new byte[] {1, 2, 3, 4}; + byte[] projectionBytes = "{\"synthetic\":true}".getBytes(StandardCharsets.UTF_8); + String sourceDigest = sha256(sourceBytes); + String projectionDigest = sha256(projectionBytes); + Binding owner = owner(tenantId, requestId); + + try (Connection connection = dataSource.getConnection()) { + setSearchPath(connection, schema); + connection.setAutoCommit(false); + try (Statement statement = connection.createStatement()) { + // Seed physical retained storage without claiming this synthetic row passed the owner or + // source-authentication triggers; normal application connections never change this role. + statement.execute("SET LOCAL session_replication_role = replica"); + } + try (PreparedStatement statement = + connection.prepareStatement( + "INSERT INTO game_design_start_session_authored_actor_core_projection " + + "(target_namespace, canonical_tenant_id, control_plane_request_id, " + + "launch_descriptor_row_id, policy_order, binding_id, source_binding_bytes, " + + "source_binding_digest, projection_bytes, projection_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")) { + statement.setString(1, owner.targetNamespace()); + statement.setObject(2, tenantId); + statement.setString(3, requestId); + statement.setLong(4, owner.descriptorRowId()); + statement.setInt(5, 0); + statement.setObject(6, bindingId); + statement.setBytes(7, sourceBytes); + statement.setString(8, sourceDigest); + statement.setBytes(9, projectionBytes); + statement.setString(10, projectionDigest); + assertThat(statement.executeUpdate()).isEqualTo(1); + } + + DSLContext dsl = DSL.using(connection, SQLDialect.POSTGRES); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM pg_constraint " + + "WHERE conrelid = to_regclass(" + + "'game_design_start_session_authored_actor_core_projection') " + + "AND contype = 'f'", + Integer.class)) + .isEqualTo(2); + var retained = new StartSessionAuthoredActorCoreProjectionRepository(dsl).findByOwner(owner); + assertThat(retained).hasSize(1); + assertThat(retained.getFirst().targetNamespace()).isEqualTo(owner.targetNamespace()); + assertThat(retained.getFirst().canonicalTenantId()).isEqualTo(tenantId); + assertThat(retained.getFirst().controlPlaneRequestId()).isEqualTo(requestId); + assertThat(retained.getFirst().descriptorRowId()).isEqualTo(owner.descriptorRowId()); + assertThat(retained.getFirst().bindingId()).isEqualTo(bindingId); + assertThat(retained.getFirst().sourceBindingBytes()).isEqualTo(sourceBytes); + assertThat(retained.getFirst().sourceBindingDigest()).isEqualTo(sourceDigest); + assertThat(retained.getFirst().projectionBytes()).isEqualTo(projectionBytes); + assertThat(retained.getFirst().projectionDigest()).isEqualTo(projectionDigest); + connection.commit(); + } + + assertThatThrownBy( + () -> + mutate( + dataSource, + schema, + "UPDATE game_design_start_session_authored_actor_core_projection SET policy_order = 1")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("insert-only"); + assertThatThrownBy( + () -> + mutate( + dataSource, + schema, + "DELETE FROM game_design_start_session_authored_actor_core_projection")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("insert-only"); + assertThatThrownBy( + () -> + mutate( + dataSource, + schema, + "TRUNCATE game_design_start_session_authored_actor_core_projection")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("retained"); + } + + private static DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(POSTGRES.getJdbcUrl()); + dataSource.setUsername(POSTGRES.getUsername()); + dataSource.setPassword(POSTGRES.getPassword()); + return dataSource; + } + + private static Binding owner(UUID tenantId, String requestId) { + return new Binding( + "world-runtime", + tenantId, + requestId, + 987654321L, + 123456789L, + 3L, + new byte[] {1}, + UUID.randomUUID(), + 1L, + 7L, + UUID.randomUUID(), + UUID.randomUUID(), + "synthetic-workflow", + digest('a'), + digest('b'), + UUID.randomUUID(), + digest('c'), + "synthetic-world", + 1L, + "EMPTY_V1", + "synthetic-game-logic-request", + digest('d'), + digest('e'), + digest('f'), + new byte[] {1}, + LocalDateTime.of(2026, 10, 11, 0, 0)); + } + + private static void setSearchPath(Connection connection, String schema) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute("SET search_path TO " + schema); + } + } + + private static void mutate(DriverManagerDataSource dataSource, String schema, String sql) { + try (Connection connection = dataSource.getConnection()) { + setSearchPath(connection, schema); + DSL.using(connection, SQLDialect.POSTGRES).execute(sql); + } catch (SQLException failure) { + throw new IllegalStateException("Could not open PostgreSQL mutation connection", failure); + } + } + + private static String sha256(byte[] bytes) throws java.security.NoSuchAlgorithmException { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(bytes); + return "sha256:" + java.util.HexFormat.of().formatHex(digest); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadServiceTest.java new file mode 100644 index 0000000000..6f3f7146eb --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/AuthoredInitialActorCoreReadServiceTest.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.function.Supplier; +import net.firedevops.firemud.common.account.StartSessionRedeemedOperationProjectionClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence.ReadRequest; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.springframework.transaction.PlatformTransactionManager; +import tools.jackson.databind.json.JsonMapper; + +class AuthoredInitialActorCoreReadServiceTest { + private final DSLContext dsl = mock(DSLContext.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final StartSessionRedeemedOperationProjectionClient account = + mock(StartSessionRedeemedOperationProjectionClient.class); + private final PublishedReleaseBundleService releases = mock(PublishedReleaseBundleService.class); + private final StartSessionTemplateAssociationReadService associationReader = + new StartSessionTemplateAssociationReadService( + dsl, transactions, "world-runtime", account, releases); + private final AuthoredInitialActorCoreReadService service = + new AuthoredInitialActorCoreReadService( + dsl, "world-runtime", associationReader, JsonMapper.builder().build()); + + @Test + void authenticatesExactCoreReadWorkloadBeforeRequestOrStorageChecks() { + assertThatThrownBy(() -> service.read((ReadRequest) null)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + + verifyNoInteractions(dsl, transactions, account, releases); + } + + @Test + void rejectsDifferentNamespaceWorkloadBeforeRequestAndOwnerStorage() { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/other-runtime/sa/entity-management-service", + "other-runtime", + "entity-management-service"); + withPeer(peer, () -> service.read((ReadRequest) null)); + verifyNoInteractions(dsl, transactions, account, releases); + } + + @Test + void deniesAuthenticatedEndUserContextAfterAuthenticatingExactWorkload() { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/world-runtime/sa/entity-management-service", + "world-runtime", + "entity-management-service"); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try (MockedStatic sessionContext = mockStatic(SessionContext.class)) { + sessionContext.when(SessionContext::hasAuthenticatedCallerContext).thenReturn(true); + assertThatThrownBy(() -> service.read((ReadRequest) null)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(dsl, transactions, account, releases); + } finally { + context.detach(previous); + } + } + + private static void withPeer(GrpcPeerIdentity peer, Supplier operation) { + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + assertThatThrownBy(operation::get) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + context.detach(previous); + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadServiceTest.java new file mode 100644 index 0000000000..c1b4ab7c6f --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GrpcAuthoredInitialActorCoreReadServiceTest.java @@ -0,0 +1,91 @@ +package unit.net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.publication.AuthoredInitialActorCoreReadService; +import net.firedevops.firemud.gamedesign.publication.GrpcAuthoredInitialActorCoreReadService; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreRequest; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreResponse; +import org.junit.jupiter.api.Test; + +class GrpcAuthoredInitialActorCoreReadServiceTest { + private final AuthoredInitialActorCoreReadService owner = + mock(AuthoredInitialActorCoreReadService.class); + private final GrpcAuthoredInitialActorCoreReadService service = + new GrpcAuthoredInitialActorCoreReadService(owner, "world-runtime"); + + @Test + void rejectsMissingWorkloadIdentityBeforeDecodingOrCallingOwner() { + var observer = new Collector(); + service.readAuthoredInitialActorCore( + ReadAuthoredInitialActorCoreRequest.getDefaultInstance(), observer); + assertThat(observer.error).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(owner); + } + + @Test + void rejectsOtherWorkloadsBeforeDecodingOrCallingOwner() { + var observer = invokeAs("account-service"); + assertThat(observer.error).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + verifyNoInteractions(owner); + } + + @Test + void permitsOnlyExactSameNamespaceGameSessionAndEntityIdentities() { + for (String workload : new String[] {"game-session-service", "entity-management-service"}) { + var observer = invokeAs(workload); + assertThat(observer.error).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(observer.value).isNull(); + assertThat(observer.completed).isFalse(); + } + verifyNoInteractions(owner); + } + + private Collector invokeAs(String workload) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/world-runtime/sa/" + workload, "world-runtime", workload); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + var observer = new Collector(); + service.readAuthoredInitialActorCore( + ReadAuthoredInitialActorCoreRequest.getDefaultInstance(), observer); + return observer; + } finally { + context.detach(previous); + } + } + + private static final class Collector + implements StreamObserver { + private ReadAuthoredInitialActorCoreResponse value; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadAuthoredInitialActorCoreResponse response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java index a8d39d5bab..dac2bbfc24 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; @@ -140,11 +141,17 @@ void selectedSchema3ActorCoreIsResolvedFromExactOwnerSnapshots() { fixture.policySnapshot(), fixture.gameplayRules()); - assertThat(resolved).hasSize(1); + assertThat(resolved).hasSize(2); + assertThat(resolved.get(0).policySource().policy().realmSlug()).isEqualTo("realm-a"); + assertThat(resolved.get(1).policySource().policy().realmSlug()).isEqualTo("realm-z"); assertThat(resolved.getFirst().core().displayName()).isEqualTo("Wayfarer"); assertThat(resolved.getFirst().disposition().dispositionKey()).isEqualTo("newcomer"); assertThat(resolved.getFirst().safeFeedback().feedbackKey()).isEqualTo("welcome"); assertThat(resolved.getFirst().selectedCommit()).isEqualTo(fixture.binding()); + assertThat(resolved.getFirst().policySource().commitId()) + .isNotEqualTo(fixture.binding().commitId()); + assertThat(resolved.getFirst().dispositionSource().sourceBinding().commitId()) + .isNotEqualTo(fixture.binding().commitId()); assertThat(resolved.getFirst().expectedWorldSlug()).isEqualTo("world"); assertThatThrownBy(resolved::clear).isInstanceOf(UnsupportedOperationException.class); @@ -190,7 +197,7 @@ void selectedSchema3ActorCoreIsResolvedFromExactOwnerSnapshots() { } @Test - void resolvedBindingDefensivelyRetainsSelectedActorCoreAndRejectsChangedReleaseProvenance() { + void resolvedBindingDefensivelyRetainsMinimalActorCoreProjectionAndRejectsChangedProvenance() { var fixture = selectedActorCoreSource(); UUID sourceOperation = uuid("66666666-6666-4666-8666-666666666666"); List sourceBindings = @@ -209,10 +216,24 @@ void resolvedBindingDefensivelyRetainsSelectedActorCoreAndRejectsChangedReleaseP resolvedBinding(mutableBindings, sourceOperation, "world", COMMIT, "selected-workflow"); mutableBindings.clear(); - assertThat(resolved.actorCoreBindings()).hasSize(1); - assertThat(resolved.actorCoreBindings().getFirst().canonicalBytes()) - .isEqualTo(sourceBindings.getFirst().canonicalBytes()); - assertThatThrownBy(resolved.actorCoreBindings()::clear) + assertThat(resolved.actorCoreProjections()).hasSize(2); + assertThat(resolved.actorCoreProjections().get(0).policy().canonicalJson()) + .contains("\"realmSlug\":\"realm-a\""); + assertThat(resolved.actorCoreProjections().get(1).policy().canonicalJson()) + .contains("\"realmSlug\":\"realm-z\""); + assertThat(resolved.actorCoreProjections().getFirst().policy().commitId()) + .isNotEqualTo(resolved.actorCoreProjections().getFirst().selectedCommitId()); + assertThat(resolved.actorCoreProjections().getFirst().disposition().sourceCommitId()) + .isNotEqualTo(resolved.actorCoreProjections().getFirst().selectedCommitId().toString()); + assertThat(resolved.actorCoreProjections().getFirst().bindingDigest()) + .isEqualTo(sourceBindings.getFirst().digest()); + assertThat( + new String( + resolved.actorCoreProjections().getFirst().canonicalBytes(), + StandardCharsets.UTF_8)) + .doesNotContain("selected publication operation") + .doesNotContain("selected publication terminal evidence"); + assertThatThrownBy(resolved.actorCoreProjections()::clear) .isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy( @@ -283,8 +304,19 @@ private static StartSessionLaunchDescriptorProducer.ResolvedBinding resolvedBind when(descriptor.canonicalTenantId()).thenReturn(TENANT.toString()); when(descriptor.gameTemplateId()).thenReturn(91L); when(descriptor.authoredWorldBinding()).thenReturn(authoredWorld); + // Structural projection fixtures only; Common integrity checks do not authenticate a producer. + List projections = + java.util.stream.IntStream.range(0, actorCoreBindings.size()) + .mapToObj( + index -> + AuthoredInitialActorCoreProjection.fromValidatedBinding( + UUID.nameUUIDFromBytes( + (index + ":" + actorCoreBindings.get(index).digest()) + .getBytes(StandardCharsets.UTF_8)), + actorCoreBindings.get(index))) + .toList(); return new StartSessionLaunchDescriptorProducer.ResolvedBinding( - request, associationRead, descriptor, actorCoreBindings); + request, associationRead, descriptor, projections); } private static SelectedActorCoreFixture selectedActorCoreSource() { @@ -293,12 +325,19 @@ private static SelectedActorCoreFixture selectedActorCoreSource() { TENANT, VERSION, 23L, "private-owner-key", 42L, "private-owner-key", "NEW_GAME_ROW"); String policyJson = "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," - + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"realmSlug\":\"realm-z\",\"realmDisplayName\":\"Realm Z\",\"visible\":true," + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PLAYER_CREATED\"," + "\"creationDescriptor\":{\"schemaVersion\":1,\"descriptorId\":\"11111111-1111-4111-8111-111111111111\"," + "\"descriptorRevisionId\":\"22222222-2222-4222-8222-222222222222\"," + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}"; + String earlierPolicyJson = + policyJson + .replace("realm-z", "realm-a") + .replace("Realm Z", "Realm A") + .replace("11111111-1111-4111-8111-111111111111", "12111111-1111-4111-8111-111111111111") + .replace( + "22222222-2222-4222-8222-222222222222", "23222222-2222-4222-8222-222222222222"); String policyPayload = RealmPolicySource.canonical( Map.of( @@ -328,11 +367,23 @@ private static SelectedActorCoreFixture selectedActorCoreSource() { policyPayload), new RevisionPayload( "1", + uuid("56555555-5555-4555-8555-555555555556"), + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "selected-policy-r2", + "policy", + RealmPolicySource.tree(earlierPolicyJson)))), + new RevisionPayload( + "2", uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), Owner.GAME_DESIGN_CONTROL_PLANE, GameplayRuleSource.upsertPayload(disposition)), new RevisionPayload( - "2", + "3", uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), Owner.GAME_DESIGN_CONTROL_PLANE, GameplayRuleSource.upsertPayload(feedback))); @@ -352,25 +403,45 @@ private static SelectedActorCoreFixture selectedActorCoreSource() { GameplayRuleSource.SCOPE, GameplayRuleSource.SCOPE_ID, "0")); - DraftCommitBinding binding = + DraftCommitBinding originBinding = DraftCommitBinding.create( target, uuid("77777777-7777-4777-8777-777777777777"), - COMMIT, + uuid("abababab-abab-4bab-8bab-abababababab"), "base-commit-0", revisions, affectedUnits); - var policySource = RealmPolicySource.revision(binding, revisions.getFirst()); + DraftCommitBinding binding = + DraftCommitBinding.create( + target, + uuid("88888888-8888-4888-8888-888888888888"), + COMMIT, + originBinding.commitId().toString(), + List.of( + new RevisionPayload( + "0", + uuid("98989898-9898-4989-8989-989898989898"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, "WORLD_REVISION", "world", "WORLD", "world", "0"))); + var policySources = + List.of( + RealmPolicySource.revision(originBinding, revisions.get(0)), + RealmPolicySource.revision(originBinding, revisions.get(1))); var policySnapshot = new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( - binding, "1", List.of(policySource)); + binding, "1", policySources); + List inheritedRules = + GameplayRuleSource.replay(List.of(), originBinding); var rulesSnapshot = new GameplayRuleSnapshot( binding, "1", - null, + originBinding.commitId(), uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), - GameplayRuleSource.replay(List.of(), binding)); + GameplayRuleSource.replay(inheritedRules, binding)); return new SelectedActorCoreFixture(binding, policySnapshot, rulesSnapshot); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepositoryTest.java new file mode 100644 index 0000000000..e352692494 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepositoryTest.java @@ -0,0 +1,304 @@ +package net.firedevops.firemud.gamedesign.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.LocalDateTime; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ReplayPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.gamedesign.repository.StartSessionAuthoredActorCoreProjectionRepository.RetainedProjection; +import net.firedevops.firemud.gamedesign.repository.StartSessionLaunchDescriptorRepository.Binding; +import org.junit.jupiter.api.Test; + +class StartSessionAuthoredActorCoreProjectionRepositoryTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID SOURCE_OPERATION = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID BINDING_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID ATTEMPT = uuid("66666666-6666-4666-8666-666666666666"); + private static final String REQUEST_ID = "actor-core-owner-request"; + private static final String WORKFLOW = "published-workflow"; + private static final String SOURCE_DIGEST = digest('a'); + + @Test + void replaysExactFullPrivateProofAndSameProjectionIdentityWithoutReselection() { + AuthoredInitialActorCoreSourceBinding source = sourceBinding("original terminal evidence"); + AuthoredInitialActorCoreProjection projection = + AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, source); + RetainedProjection retained = retained(owner(), source, projection, 0); + + var replay = + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(retained), List.of(source), owner()); + + assertThat(replay).hasSize(1); + assertThat(replay.getFirst().bindingId()).isEqualTo(BINDING_ID); + assertThat(replay.getFirst().canonicalBytes()).isEqualTo(projection.canonicalBytes()); + assertThat(retained.sourceBindingBytes()).isEqualTo(source.canonicalBytes()); + assertThat(retained.projectionBytes()).isEqualTo(projection.canonicalBytes()); + } + + @Test + void deniesHistoricalMissingProofAndFullPrivateContentConflict() { + AuthoredInitialActorCoreSourceBinding source = sourceBinding("original terminal evidence"); + AuthoredInitialActorCoreProjection projection = + AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, source); + + assertThatThrownBy( + () -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(), List.of(source), owner())) + .isInstanceOf( + StartSessionAuthoredActorCoreProjectionRepository.MissingRetainedProjectionException + .class); + + AuthoredInitialActorCoreSourceBinding changed = + sourceBinding("different but internally well-formed terminal evidence"); + assertThatThrownBy( + () -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(retained(owner(), source, projection, 0)), List.of(changed), owner())) + .isInstanceOf( + StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException + .class) + .hasMessageContaining("private source proof differs"); + } + + @Test + void deniesIncompleteOrReorderedOwnerProofSets() { + AuthoredInitialActorCoreSourceBinding source = sourceBinding("original terminal evidence"); + AuthoredInitialActorCoreProjection projection = + AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, source); + RetainedProjection wrongOrder = retained(owner(), source, projection, 1); + + assertThatThrownBy( + () -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(wrongOrder), List.of(source), owner())) + .isInstanceOf( + StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException + .class) + .hasMessageContaining("owner identity or order changed"); + + assertThatThrownBy( + () -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(retained(owner(), source, projection, 0)), + List.of(source, source), + owner())) + .isInstanceOf( + StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException + .class) + .hasMessageContaining("count differs"); + } + + private static RetainedProjection retained( + Binding owner, + AuthoredInitialActorCoreSourceBinding source, + AuthoredInitialActorCoreProjection projection, + int policyOrder) { + return new RetainedProjection( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.controlPlaneRequestId(), + owner.descriptorRowId(), + policyOrder, + projection.bindingId(), + source.canonicalBytes(), + source.digest(), + projection.canonicalBytes(), + projection.digest(), + LocalDateTime.of(2026, 10, 11, 0, 0)); + } + + private static Binding owner() { + return new Binding( + NAMESPACE, + TENANT, + REQUEST_ID, + 81L, + 91L, + 3L, + bytes("original complete Account tuple"), + ATTEMPT, + 2L, + 7L, + VERSION, + COMMIT, + WORKFLOW, + digest('b'), + digest('c'), + SOURCE_OPERATION, + SOURCE_DIGEST, + "world", + 4L, + "EMPTY_V1", + "game-logic-publish-request", + digest('d'), + digest('e'), + digest('f'), + bytes("original association response"), + LocalDateTime.of(2026, 10, 11, 0, 0)); + } + + private static AuthoredInitialActorCoreSourceBinding sourceBinding(String terminalText) { + var target = + new TargetProof( + TENANT, VERSION, 23L, "private-owner-key", 42L, "private-owner-key", "NEW_GAME_ROW"); + String policyJson = + "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PLAYER_CREATED\"," + + "\"creationDescriptor\":{\"schemaVersion\":1,\"descriptorId\":\"77777777-7777-4777-8777-777777777777\"," + + "\"descriptorRevisionId\":\"88888888-8888-4888-8888-888888888888\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}"; + var policyPayload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r1", + "policy", + RealmPolicySource.tree(policyJson))); + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor.created", + Audience.SOURCE_ACTOR, + "actor.created", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + ReplayPolicy.EFFECT_IDEMPOTENT); + List revisions = + List.of( + new RevisionPayload( + "0", + uuid("99999999-9999-4999-8999-999999999999"), + Owner.GAME_DESIGN_CONTROL_PLANE, + policyPayload), + new RevisionPayload( + "1", + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(disposition)), + new RevisionPayload( + "2", + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(feedback))); + DraftCommitBinding commit = + DraftCommitBinding.create( + target, + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + COMMIT, + "base-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"), + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + VERSION.toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + RealmPolicySnapshot policySnapshot = + new RealmPolicySnapshot( + commit, "1", List.of(RealmPolicySource.revision(commit, revisions.getFirst()))); + var rules = GameplayRuleSource.replay(List.of(), commit); + GameplayRuleSelectedSource gameplaySnapshot = selectedGameplaySource(commit, rules); + return AuthoredInitialActorCoreSourceBinding.resolveAll( + SOURCE_OPERATION, + SOURCE_DIGEST, + "world", + WORKFLOW, + bytes("original publication request bytes"), + bytes(terminalText), + commit, + policySnapshot, + gameplaySnapshot) + .getFirst(); + } + + private static GameplayRuleSelectedSource selectedGameplaySource( + DraftCommitBinding binding, List entries) { + Map> families = new LinkedHashMap<>(); + for (Family family : Family.values()) { + families.put( + family, + entries.stream() + .filter(entry -> entry.family() == family) + .map(GameplayRuleSource.Entry::definition) + .toList()); + } + GameplayRuleManifest manifest = new GameplayRuleManifest(families); + Map snapshot = new LinkedHashMap<>(); + snapshot.put("schema", "game-design-gameplay-rule-source-snapshot/v1"); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", "1"); + snapshot.put("inheritedCommitId", ""); + snapshot.put("genesisReceiptId", "dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + snapshot.put("manifestJson", manifest.canonicalJson()); + snapshot.put( + "entries", + entries.stream() + .map( + entry -> + Map.of( + "family", entry.family().name(), + "definitionJson", GameplayRuleManifest.canonical(entry.definition()), + "sourceBindingJson", entry.sourceBinding().canonicalJson(), + "sourceBindingDigest", entry.sourceBinding().digest(), + "revisionOrder", entry.revisionOrder(), + "revisionId", entry.revisionId().toString())) + .toList()); + return new GameplayRuleSelectedSource(CommandSource.canonical(snapshot)); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java new file mode 100644 index 0000000000..7f6b2e74f6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java @@ -0,0 +1,385 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered, append-only Game Session retention for the exact public Game Design authored-core + * result belonging to one original StartSession launch and owner attempt. + * + *

This repository persists only the already-authenticated public result and its exact owner + * bindings. It does not authenticate Game Design, select a policy, allocate an actor, or grant + * runtime authority. + */ +public final class GameSessionAuthoredActorCoreRetentionRepository { + private static final String TABLE = + "game_session_original_start_session_authored_actor_core_retention"; + + private final DSLContext dsl; + private final String workloadNamespace; + private final TransactionTemplate readTransaction; + + public GameSessionAuthoredActorCoreRetentionRepository( + DSLContext dsl, PlatformTransactionManager transactionManager, String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + readTransaction = new TransactionTemplate(transactionManager); + readTransaction.setReadOnly(true); + readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + /** Reads the immutable row by original operation identity in an independent owner snapshot. */ + public Optional readByOriginalOperation( + String targetNamespace, String controlPlaneRequestId) { + requireNoOwnerTransaction(); + requireIdentity(targetNamespace, controlPlaneRequestId); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Authored-core retention read differs from configured Game Session workload namespace"); + } + Optional result = + readTransaction.execute( + status -> { + Record row = select(targetNamespace, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(snapshot(row)); + }); + return Objects.requireNonNull(result, "Authored-core retention read returned no result"); + } + + /** + * Appends or exact-replays one result inside the caller's writable owner transaction. The caller + * must have locked and revalidated the original live attempt in this same transaction. + */ + public StoredSource retainInOwnerTransaction(Candidate candidate) { + requireOwnerTransaction(); + Objects.requireNonNull(candidate, "retention candidate"); + requireIdentity(candidate.targetNamespace(), candidate.controlPlaneRequestId()); + if (!workloadNamespace.equals(candidate.targetNamespace())) { + throw new IllegalArgumentException( + "Authored-core retention namespace differs from configured Game Session owner"); + } + + dsl.execute( + "INSERT INTO " + + TABLE + + " (target_namespace, control_plane_request_id, canonical_tenant_id, " + + "game_instance_uuid, owner_attempt_id, owner_mutation_id, owner_fence, " + + "owner_lease_expires_at, original_post_authorization_tuple, " + + "account_redemption_projection, account_redemption_projection_digest, " + + "canonical_version_id, selected_commit_id, publish_workflow_id, association_digest, " + + "world_source_operation_id, world_source_evidence_digest, world_slug, " + + "launch_descriptor_id, descriptor_request_digest, descriptor_result_digest, " + + "release_attestation_evidence_digest, source_read_request_bytes, " + + "canonical_source_result_bytes, source_result_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (target_namespace, control_plane_request_id) DO NOTHING", + candidate.targetNamespace(), + candidate.controlPlaneRequestId(), + candidate.canonicalTenantId(), + candidate.gameInstanceUuid(), + candidate.ownerAttemptId(), + candidate.ownerMutationId(), + candidate.ownerFence(), + candidate.ownerLeaseExpiresAt(), + candidate.originalPostAuthorizationTuple(), + candidate.accountRedemptionProjection(), + candidate.accountRedemptionProjectionDigest(), + candidate.canonicalVersionId(), + candidate.selectedCommitId(), + candidate.publishWorkflowId(), + candidate.associationDigest(), + candidate.worldSourceOperationId(), + candidate.worldSourceEvidenceDigest(), + candidate.worldSlug(), + candidate.launchDescriptorId(), + candidate.descriptorRequestDigest(), + candidate.descriptorResultDigest(), + candidate.releaseAttestationEvidenceDigest(), + candidate.sourceReadRequestBytes(), + candidate.canonicalSourceResultBytes(), + candidate.sourceResultDigest()); + + Record row = select(candidate.targetNamespace(), candidate.controlPlaneRequestId()); + if (row == null) { + throw new IllegalStateException("Authored-core retention row did not read back"); + } + StoredSource stored = snapshot(row); + requireExactCandidate(candidate, stored.candidate()); + return stored; + } + + private Record select(String targetNamespace, String controlPlaneRequestId) { + return dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE target_namespace = ? AND control_plane_request_id = ?", + targetNamespace, + controlPlaneRequestId); + } + + private StoredSource snapshot(Record row) { + Candidate candidate = + new Candidate( + required(row, "target_namespace", String.class), + required(row, "control_plane_request_id", String.class), + required(row, "canonical_tenant_id", UUID.class), + required(row, "game_instance_uuid", UUID.class), + required(row, "owner_attempt_id", UUID.class), + required(row, "owner_mutation_id", UUID.class), + required(row, "owner_fence", Long.class), + required(row, "owner_lease_expires_at", java.time.OffsetDateTime.class).toInstant(), + required(row, "original_post_authorization_tuple", byte[].class), + required(row, "account_redemption_projection", byte[].class), + required(row, "account_redemption_projection_digest", String.class), + required(row, "canonical_version_id", UUID.class), + required(row, "selected_commit_id", UUID.class), + required(row, "publish_workflow_id", String.class), + required(row, "association_digest", String.class), + required(row, "world_source_operation_id", UUID.class), + required(row, "world_source_evidence_digest", String.class), + required(row, "world_slug", String.class), + required(row, "launch_descriptor_id", String.class), + required(row, "descriptor_request_digest", String.class), + required(row, "descriptor_result_digest", String.class), + required(row, "release_attestation_evidence_digest", String.class), + required(row, "source_read_request_bytes", byte[].class), + required(row, "canonical_source_result_bytes", byte[].class), + required(row, "source_result_digest", String.class)); + Instant retainedAt = required(row, "retained_at", java.time.OffsetDateTime.class).toInstant(); + return new StoredSource(candidate, retainedAt); + } + + private static void requireExactCandidate(Candidate expected, Candidate stored) { + if (!expected.targetNamespace().equals(stored.targetNamespace()) + || !expected.controlPlaneRequestId().equals(stored.controlPlaneRequestId()) + || !expected.canonicalTenantId().equals(stored.canonicalTenantId()) + || !expected.gameInstanceUuid().equals(stored.gameInstanceUuid()) + || !expected.ownerAttemptId().equals(stored.ownerAttemptId()) + || !expected.ownerMutationId().equals(stored.ownerMutationId()) + || expected.ownerFence() != stored.ownerFence() + || !expected.ownerLeaseExpiresAt().equals(stored.ownerLeaseExpiresAt()) + || !arraysEqual( + expected.originalPostAuthorizationTuple(), stored.originalPostAuthorizationTuple()) + || !arraysEqual( + expected.accountRedemptionProjection(), stored.accountRedemptionProjection()) + || !expected + .accountRedemptionProjectionDigest() + .equals(stored.accountRedemptionProjectionDigest()) + || !expected.canonicalVersionId().equals(stored.canonicalVersionId()) + || !expected.selectedCommitId().equals(stored.selectedCommitId()) + || !expected.publishWorkflowId().equals(stored.publishWorkflowId()) + || !expected.associationDigest().equals(stored.associationDigest()) + || !expected.worldSourceOperationId().equals(stored.worldSourceOperationId()) + || !expected.worldSourceEvidenceDigest().equals(stored.worldSourceEvidenceDigest()) + || !expected.worldSlug().equals(stored.worldSlug()) + || !expected.launchDescriptorId().equals(stored.launchDescriptorId()) + || !expected.descriptorRequestDigest().equals(stored.descriptorRequestDigest()) + || !expected.descriptorResultDigest().equals(stored.descriptorResultDigest()) + || !expected + .releaseAttestationEvidenceDigest() + .equals(stored.releaseAttestationEvidenceDigest()) + || !arraysEqual(expected.sourceReadRequestBytes(), stored.sourceReadRequestBytes()) + || !arraysEqual(expected.canonicalSourceResultBytes(), stored.canonicalSourceResultBytes()) + || !expected.sourceResultDigest().equals(stored.sourceResultDigest())) { + throw new IllegalStateException( + "Original StartSession authored-core retention conflicts with its first exact result"); + } + } + + private void requireIdentity(String targetNamespace, String controlPlaneRequestId) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Game Session namespace required"); + } + if (controlPlaneRequestId == null + || controlPlaneRequestId.isBlank() + || controlPlaneRequestId.length() > 128) { + throw new IllegalArgumentException( + "Canonical original StartSession request identity required"); + } + } + + private static void requireNoOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Authored-core retention read requires an independent owner snapshot"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Authored-core retention requires a writable caller-owned owner transaction"); + } + } + + private static T required(Record row, String field, Class type) { + T value = row == null ? null : row.get(field, type); + if (value == null) { + throw new IllegalStateException("Retained authored-core result is missing " + field); + } + return value; + } + + private static boolean arraysEqual(byte[] left, byte[] right) { + return MessageDigest.isEqual(left, right); + } + + /** + * One exact append candidate, including the unchanged canonical result returned by Game Design. + */ + public record Candidate( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + UUID gameInstanceUuid, + UUID ownerAttemptId, + UUID ownerMutationId, + long ownerFence, + Instant ownerLeaseExpiresAt, + byte[] originalPostAuthorizationTuple, + byte[] accountRedemptionProjection, + String accountRedemptionProjectionDigest, + UUID canonicalVersionId, + UUID selectedCommitId, + String publishWorkflowId, + String associationDigest, + UUID worldSourceOperationId, + String worldSourceEvidenceDigest, + String worldSlug, + String launchDescriptorId, + String descriptorRequestDigest, + String descriptorResultDigest, + String releaseAttestationEvidenceDigest, + byte[] sourceReadRequestBytes, + byte[] canonicalSourceResultBytes, + String sourceResultDigest) { + public Candidate { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(controlPlaneRequestId, "controlPlaneRequestId"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(gameInstanceUuid, "gameInstanceUuid"); + Objects.requireNonNull(ownerAttemptId, "ownerAttemptId"); + Objects.requireNonNull(ownerMutationId, "ownerMutationId"); + Objects.requireNonNull(ownerLeaseExpiresAt, "ownerLeaseExpiresAt"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + Objects.requireNonNull(selectedCommitId, "selectedCommitId"); + Objects.requireNonNull(publishWorkflowId, "publishWorkflowId"); + Objects.requireNonNull(associationDigest, "associationDigest"); + Objects.requireNonNull(worldSourceOperationId, "worldSourceOperationId"); + Objects.requireNonNull(worldSourceEvidenceDigest, "worldSourceEvidenceDigest"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(launchDescriptorId, "launchDescriptorId"); + Objects.requireNonNull(descriptorRequestDigest, "descriptorRequestDigest"); + Objects.requireNonNull(descriptorResultDigest, "descriptorResultDigest"); + Objects.requireNonNull(releaseAttestationEvidenceDigest, "releaseAttestationEvidenceDigest"); + Objects.requireNonNull( + accountRedemptionProjectionDigest, "accountRedemptionProjectionDigest"); + Objects.requireNonNull(sourceResultDigest, "sourceResultDigest"); + originalPostAuthorizationTuple = + copyBounded(originalPostAuthorizationTuple, 262_144, "original tuple"); + accountRedemptionProjection = + copyBounded(accountRedemptionProjection, 262_144, "Account projection"); + sourceReadRequestBytes = copyBounded(sourceReadRequestBytes, 524_288, "source read request"); + canonicalSourceResultBytes = + copyBounded( + canonicalSourceResultBytes, + AuthoredInitialActorCoreReadEvidence.MAX_RESULT_BYTES, + "canonical source result"); + if (ownerFence <= 0L) { + throw new IllegalArgumentException("ownerFence must be positive"); + } + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(originalPostAuthorizationTuple); + if (!tuple.controlPlaneRequestId().equals(controlPlaneRequestId) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(targetNamespace) + || !tuple.preAuthorizationTuple().action().scope().tenantId().equals(canonicalTenantId)) { + throw new IllegalArgumentException("Retention identity differs from the original tuple"); + } + if (!sha256Hex(accountRedemptionProjection).equals(accountRedemptionProjectionDigest)) { + throw new IllegalArgumentException("Account projection digest differs from exact bytes"); + } + if (!sha256(canonicalSourceResultBytes).equals(sourceResultDigest)) { + throw new IllegalArgumentException( + "Source result digest differs from exact canonical bytes"); + } + } + + @Override + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + @Override + public byte[] accountRedemptionProjection() { + return accountRedemptionProjection.clone(); + } + + @Override + public byte[] sourceReadRequestBytes() { + return sourceReadRequestBytes.clone(); + } + + @Override + public byte[] canonicalSourceResultBytes() { + return canonicalSourceResultBytes.clone(); + } + } + + /** Immutable independent owner readback. */ + public record StoredSource(Candidate candidate, Instant retainedAt) { + public StoredSource { + Objects.requireNonNull(candidate, "candidate"); + Objects.requireNonNull(retainedAt, "retainedAt"); + } + } + + private static byte[] copyBounded(byte[] value, int maximum, String label) { + Objects.requireNonNull(value, label); + if (value.length == 0 || value.length > maximum) { + throw new IllegalArgumentException("Complete bounded " + label + " bytes required"); + } + return value.clone(); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static String sha256Hex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java index 7823b150ad..5490b9799a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; @@ -114,6 +115,47 @@ public Optional readByLaunchIdentity( result, "Game Session launch read transaction returned no result"); } + /** + * Reads the complete launch and verifies its retained original tuple in the same independent + * repeatable-read snapshot. + */ + public Optional readByOriginalTuple( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector, + byte[] exactOriginalPostAuthorizationTupleBytes) { + requireNoActiveOwnerTransaction(); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Original tuple launch read requires an independent owner synchronization"); + } + Objects.requireNonNull(selector, "selector"); + if (!workloadNamespace.equals(selector.targetNamespace())) { + throw new InvalidCanonicalInstanceLaunchException( + "Launch-association namespace differs from the configured Game Session owner"); + } + OriginalStartSessionLaunchReadEvidence.Request exactRequest = + new OriginalStartSessionLaunchReadEvidence.Request( + selector, exactOriginalPostAuthorizationTupleBytes); + Optional result = + readTransaction.execute( + status -> { + Optional retained = + readByLaunchIdentityInTransaction(selector); + if (retained.isEmpty()) { + return Optional.empty(); + } + CanonicalInstanceLaunch launch = retained.orElseThrow(); + if (!Arrays.equals( + exactRequest.originalPostAuthorizationTupleBytes(), + launch.originalStartSessionTuple())) { + throw new InvalidCanonicalInstanceLaunchException( + "Retained original StartSession tuple differs from the exact requested bytes"); + } + return Optional.of(launch); + }); + return Objects.requireNonNull( + result, "Game Session original tuple launch read transaction returned no result"); + } + private CanonicalInstanceLaunch createInTransaction(PreparedLaunch input) { requireOwnerTransaction(); lockIdentity(input); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAuthoredActorCoreRetentionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAuthoredActorCoreRetentionService.java new file mode 100644 index 0000000000..72a718d88f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAuthoredActorCoreRetentionService.java @@ -0,0 +1,486 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.Candidate; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.StoredSource; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository.CanonicalInstanceLaunch; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StartSessionOperatorAttemptConflictException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionOperations; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered composition that retains the exact authenticated Game Design authored-core result + * against its actual Game Session launch and original live owner attempt. + * + *

The result is observation evidence only. An empty projection list remains an exact retained + * source result and does not grant Entity allocation, presence, placement, admission, or activation + * authority. + */ +public final class GameSessionAuthoredActorCoreRetentionService { + private final String workloadNamespace; + private final GameSessionCanonicalInstanceLaunchRepository launches; + private final GameSessionStartSessionOperatorAttemptRepository attempts; + private final AuthoredInitialActorCoreReadClient gameDesign; + private final GameSessionAuthoredActorCoreRetentionRepository retention; + private final TransactionOperations currentAttemptTransaction; + private final TransactionOperations retentionTransaction; + + public GameSessionAuthoredActorCoreRetentionService( + String workloadNamespace, + GameSessionCanonicalInstanceLaunchRepository launches, + GameSessionStartSessionOperatorAttemptRepository attempts, + AuthoredInitialActorCoreReadClient gameDesign, + GameSessionAuthoredActorCoreRetentionRepository retention, + PlatformTransactionManager transactionManager) { + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + this.launches = Objects.requireNonNull(launches, "launches"); + this.attempts = Objects.requireNonNull(attempts, "attempts"); + this.gameDesign = Objects.requireNonNull(gameDesign, "gameDesign"); + this.retention = Objects.requireNonNull(retention, "retention"); + Objects.requireNonNull(transactionManager, "transactionManager"); + currentAttemptTransaction = writableReadCommitted(transactionManager); + retentionTransaction = writableReadCommitted(transactionManager); + } + + /** + * Reads, authenticates, and retains the exact owner-qualified result for one complete historical + * original selection. Exact retries return the first retained bytes, including an empty result, + * without extending the lease or repeating the remote source read. + */ + public StoredSource retain( + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + OriginalStartSessionCurrentAttemptEvidence.Request currentAttemptRequest) { + requireNoAmbientTransaction(); + Objects.requireNonNull(historical, "historical owner evidence"); + Objects.requireNonNull(currentAttemptRequest, "current original-attempt request"); + requireHistoricalAttemptMatch(historical, currentAttemptRequest); + + var historicalRequest = historical.request(); + var associationRequest = historical.descriptorPin().associationRead().request(); + var sourceReadRequest = + new AuthoredInitialActorCoreReadEvidence.ReadRequest(associationRequest); + byte[] sourceReadRequestBytes = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(associationRequest).toByteArray(); + byte[] accountProjection = historical.accountRedemptionProjection(); + String requestId = historical.originalTuple().controlPlaneRequestId(); + + var existing = retention.readByOriginalOperation(workloadNamespace, requestId); + if (existing.isPresent()) { + StoredSource stored = existing.orElseThrow(); + requireStoredRetryMatches( + stored, historical, currentAttemptRequest, sourceReadRequestBytes, accountProjection); + return stored; + } + + CanonicalInstanceLaunch launch = + launches + .readByOriginalTuple( + historicalRequest.associationSelector(), + historical.originalTuple().canonicalBytes()) + .orElseThrow( + () -> + new IllegalStateException( + "Exact actual Game Session launch association is unavailable")); + requireLaunchMatchesHistorical(launch, historical); + + AttemptSnapshot firstAttempt = readCurrentAttempt(currentAttemptRequest); + requireAttemptMatchesHistorical(firstAttempt, historical, currentAttemptRequest); + + requireNoAmbientTransaction(); + AuthoredInitialActorCoreReadEvidence.ReadResult source = gameDesign.read(sourceReadRequest); + requireSourceMatches(launch, historical, sourceReadRequest, source); + Candidate candidate = + candidate(launch, historical, firstAttempt, sourceReadRequestBytes, source); + + StoredSource committed = + retentionTransaction.execute( + status -> { + AttemptSnapshot finalAttempt = + readCurrentAttemptInOwnerTransaction(currentAttemptRequest); + requireSameLiveAttempt(firstAttempt, finalAttempt); + return retention.retainInOwnerTransaction(candidate); + }); + if (committed == null) { + throw new IllegalStateException("Authored-core retention transaction returned no row"); + } + + StoredSource independentReadback = + retention + .readByOriginalOperation(workloadNamespace, requestId) + .orElseThrow( + () -> + new IllegalStateException( + "Committed authored-core source retention is unavailable on independent readback")); + requireSameStoredSource(candidate, committed, independentReadback); + return independentReadback; + } + + private AttemptSnapshot readCurrentAttempt( + OriginalStartSessionCurrentAttemptEvidence.Request request) { + AttemptSnapshot snapshot = + currentAttemptTransaction.execute(status -> readCurrentAttemptInOwnerTransaction(request)); + if (snapshot == null) { + throw new IllegalStateException("Current original-attempt transaction returned no row"); + } + return snapshot; + } + + private AttemptSnapshot readCurrentAttemptInOwnerTransaction( + OriginalStartSessionCurrentAttemptEvidence.Request request) { + AttemptSnapshot snapshot = attempts.readCurrentOriginalAttempt(request); + requireCurrentAttemptSnapshot(request, snapshot); + return snapshot; + } + + private Candidate candidate( + CanonicalInstanceLaunch launch, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + AttemptSnapshot attempt, + byte[] sourceReadRequestBytes, + AuthoredInitialActorCoreReadEvidence.ReadResult source) { + var association = source.associationRead().association(); + var descriptor = launch.launchBindingEvidence().descriptor(); + var release = launch.launchBindingEvidence().releaseAttestation(); + return new Candidate( + workloadNamespace, + launch.controlPlaneRequestId(), + launch.canonicalTenantId(), + launch.gameInstanceUuid(), + attempt.ownerAttemptId(), + attempt.ownerMutationId(), + attempt.ownerFence(), + attempt.leaseExpiresAt(), + historical.originalTuple().canonicalBytes(), + attempt.accountRedemptionProjection(), + OriginalStartSessionCurrentAttemptEvidence.projectionDigest( + attempt.accountRedemptionProjection()), + association.canonicalVersionId(), + association.selectedCommitId(), + association.publishWorkflowId(), + association.associationDigest(), + association.sourceOperationId(), + association.sourceEvidenceDigest(), + association.worldSlug(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest(), + sourceReadRequestBytes, + source.canonicalBytes(), + source.digest()); + } + + private void requireHistoricalAttemptMatch( + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + OriginalStartSessionCurrentAttemptEvidence.Request request) { + var tuple = historical.originalTuple(); + var action = tuple.preAuthorizationTuple().action(); + if (!workloadNamespace.equals(request.targetNamespace()) + || !workloadNamespace.equals(historical.request().associationSelector().targetNamespace()) + || !action.scope().targetNamespace().equals(workloadNamespace) + || !tuple.controlPlaneRequestId().equals(request.originalTuple().controlPlaneRequestId()) + || !Arrays.equals(tuple.canonicalBytes(), request.canonicalPostAuthorizationTuple()) + || !historical.ownerAttemptId().equals(request.expectedOwnerAttemptId()) + || historical.ownerFence() != request.expectedOwnerFence() + || !tuple + .controlPlaneRequestId() + .equals(historical.request().associationSelector().controlPlaneRequestId()) + || !action + .scope() + .tenantId() + .equals(historical.request().associationSelector().canonicalTenantId()) + || !Arrays.equals( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + historical.accountRedemptionProjection())) { + throw new StartSessionOperatorAttemptConflictException( + "Historical source selection differs from the exact original attempt or tuple"); + } + } + + private void requireLaunchMatchesHistorical( + CanonicalInstanceLaunch launch, + HistoricalOriginalStartSessionOwnerEvidence.Result historical) { + var retained = historical.launchAssociation(); + if (!workloadNamespace.equals(launch.targetNamespace()) + || !launch.targetNamespace().equals(retained.targetNamespace()) + || !launch.canonicalTenantId().equals(retained.canonicalTenantId()) + || !launch.canonicalRealmCatalog().worldSlug().equals(retained.worldSlug()) + || !launch.gameInstanceUuid().equals(retained.gameInstanceUuid()) + || !launch.controlPlaneRequestId().equals(retained.controlPlaneRequestId()) + || !launch + .launchBindingEvidence() + .descriptor() + .launchDescriptorId() + .equals(retained.launchDescriptorId()) + || !launch.playableStateNamespaceId().equals(retained.playableStateNamespaceId()) + || launch.playableStateScope() != retained.playableStateScope() + || launch.publicProduction() != retained.publicProduction() + || launch.capturedStartingRowVersion() != retained.capturedStartingRowVersion() + || !launch.launchBindingEvidence().equals(retained.launchBindingEvidence())) { + throw new StartSessionOperatorAttemptConflictException( + "Actual immutable launch differs from the historical selected descriptor or release"); + } + } + + private void requireAttemptMatchesHistorical( + AttemptSnapshot attempt, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + OriginalStartSessionCurrentAttemptEvidence.Request request) { + requireCurrentAttemptSnapshot(request, attempt); + if (!historical.ownerAttemptId().equals(attempt.ownerAttemptId()) + || historical.ownerFence() != attempt.ownerFence() + || !Arrays.equals( + historical.accountRedemptionProjection(), attempt.accountRedemptionProjection())) { + throw new StartSessionOperatorAttemptConflictException( + "Current owner attempt differs from the historical Account and selection evidence"); + } + } + + private void requireSourceMatches( + CanonicalInstanceLaunch launch, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + AuthoredInitialActorCoreReadEvidence.ReadRequest expected, + AuthoredInitialActorCoreReadEvidence.ReadResult source) { + Objects.requireNonNull(source, "authenticated Game Design source result"); + var sourceRequest = expected.associationRequest(); + var selection = source.associationRead().association(); + var expectedSelection = historical.firstSelection().association(); + var descriptor = launch.launchBindingEvidence().descriptor(); + if (!sourceRequest.equals(source.request()) + || !sourceRequest.equals(source.associationRead().request()) + || !selection.equals(expectedSelection) + || !source.descriptor().equals(descriptor) + || !source + .associationRead() + .releaseBundle() + .equals(historical.descriptorPin().associationRead().releaseBundle())) { + throw new StartSessionOperatorAttemptConflictException( + "Authenticated Game Design result differs from the exact original association or launch binding"); + } + requireSelectedReleaseMatches( + selection, + source.associationRead().releaseBundle(), + source.associationRead().worldPublishedStartLocationEvidence(), + descriptor, + launch.launchBindingEvidence().releaseAttestation()); + } + + private static void requireSelectedReleaseMatches( + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .Association + association, + PublishedReleaseBundle bundle, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence worldStart, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence attestation) { + descriptor.requireValid(); + attestation.requireValid(descriptor); + if (!association.canonicalTenantId().equals(attestation.canonicalTenantId()) + || !association.canonicalVersionId().equals(attestation.canonicalVersionId()) + || !association.selectedCommitId().toString().equals(attestation.commitId()) + || !association.publishWorkflowId().equals(attestation.publishWorkflowId()) + || !association.sourceOperationId().equals(attestation.authoredWorldSourceOperationId()) + || !association + .sourceEvidenceDigest() + .equals(attestation.authoredWorldSourceEvidenceDigest()) + || !association.worldSlug().equals(attestation.worldSlug()) + || !Objects.equals(worldStart, attestation.worldStartLocationEvidence()) + || bundle.getId() != descriptor.releaseBundleId() + || bundle.getVersionId() != descriptor.versionId() + || bundle.getIsScriptOnly() + || !bundle.getPublishedReleaseBundleRef().equals(descriptor.publishedReleaseBundleRef()) + || !bundle.getCanonicalTenantId().equals(attestation.canonicalTenantId().toString()) + || !bundle.getCanonicalVersionId().equals(attestation.canonicalVersionId().toString()) + || !bundle.getPublishWorkflowId().equals(attestation.publishWorkflowId()) + || !bundle.getAttestationSchemaVersion().equals("v" + attestation.schemaVersion()) + || !bundle.getManifestHash().equals(attestation.manifestHash()) + || !bundle.hasManifestSchemaVersion() + || bundle.getManifestSchemaVersion() != attestation.manifestSchemaVersion() + || !bundle + .getRequiredManifestAssetKeysList() + .equals(attestation.requiredManifestAssetKeys()) + || !bundle.getGenerationConfigRevision().equals(attestation.generationConfigRevision()) + || !bundle.getCommandDefinitionsList().equals(attestation.commandDefinitions()) + || bundle.getParticipantDigestsCount() != attestation.participantDigests().size() + || bundle.getArtifactDigestsCount() != attestation.artifactDigests().size()) { + throw new StartSessionOperatorAttemptConflictException( + "Selected Game Design release differs from the complete retained launch attestation"); + } + for (int index = 0; index < bundle.getParticipantDigestsCount(); index++) { + ParticipantDigest participant = bundle.getParticipantDigests(index); + AuthoredWorldReleaseAttestationEvidence.Participant expected = + attestation.participantDigests().get(index); + if (!participant.getParticipantKey().equals(expected.participantKey()) + || !participant.getScopeValue().equals(expected.scopeValue()) + || !participant.getAppliedCommitId().equals(expected.appliedCommitId()) + || !participant.getContentDigest().equals(expected.contentDigest()) + || participant.getDigestSchemaVersion() != expected.digestSchemaVersion() + || participant.hasAbilitySchemaDigest() != expected.abilitySchemaDigestPresent() + || (participant.hasAbilitySchemaDigest() + && !participant.getAbilitySchemaDigest().equals(expected.abilitySchemaDigest()))) { + throw new StartSessionOperatorAttemptConflictException( + "Selected release participant evidence differs from the retained launch attestation"); + } + } + for (int index = 0; index < bundle.getArtifactDigestsCount(); index++) { + PublishedArtifactDigest artifact = bundle.getArtifactDigests(index); + AuthoredWorldReleaseAttestationEvidence.Artifact expected = + attestation.artifactDigests().get(index); + if (!artifact.getUsageKey().equals(expected.usageKey()) + || !artifact.getArtifactKind().equals(expected.artifactKind()) + || !artifact.getImmutableObjectKey().equals(expected.immutableObjectKey()) + || !artifact.getContentDigest().equals(expected.contentDigest()) + || !artifact.getContentType().equals(expected.contentType()) + || artifact.getArtifactSchemaVersion() != expected.artifactSchemaVersion()) { + throw new StartSessionOperatorAttemptConflictException( + "Selected release artifacts differ from the retained launch attestation"); + } + } + } + + private static void requireCurrentAttemptSnapshot( + OriginalStartSessionCurrentAttemptEvidence.Request request, AttemptSnapshot snapshot) { + Objects.requireNonNull(snapshot, "current original-attempt snapshot"); + var tuple = request.originalTuple(); + if (!request.targetNamespace().equals(snapshot.targetNamespace()) + || !tuple.controlPlaneRequestId().equals(snapshot.controlPlaneRequestId()) + || !request.expectedOwnerAttemptId().equals(snapshot.ownerAttemptId()) + || !request.expectedOwnerMutationId().equals(snapshot.ownerMutationId()) + || request.expectedOwnerFence() != snapshot.ownerFence() + || !OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals(snapshot.phaseState()) + || !Arrays.equals( + request.canonicalPostAuthorizationTuple(), snapshot.postAuthorizationExecutionTuple()) + || !tuple + .preAuthorizationTuple() + .action() + .scope() + .tenantId() + .equals(snapshot.canonicalTenantId()) + || snapshot.leaseExpiresAt() == null + || snapshot.accountRedemptionProjection() == null + || !Arrays.equals( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + snapshot.accountRedemptionProjection())) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Exact live pending original StartSession attempt and Account projection are required"); + } + } + + private static void requireSameLiveAttempt(AttemptSnapshot before, AttemptSnapshot after) { + if (!before.targetNamespace().equals(after.targetNamespace()) + || !before.controlPlaneRequestId().equals(after.controlPlaneRequestId()) + || !before.canonicalTenantId().equals(after.canonicalTenantId()) + || !before.ownerAttemptId().equals(after.ownerAttemptId()) + || !before.ownerMutationId().equals(after.ownerMutationId()) + || before.ownerFence() != after.ownerFence() + || !before.phaseState().equals(after.phaseState()) + || !before.leaseExpiresAt().equals(after.leaseExpiresAt()) + || !Arrays.equals( + before.postAuthorizationExecutionTuple(), after.postAuthorizationExecutionTuple()) + || !Arrays.equals( + before.accountRedemptionProjection(), after.accountRedemptionProjection())) { + throw new StaleStartSessionOperatorAttemptClaimException( + "Original StartSession attempt changed during authenticated Game Design read"); + } + } + + private static void requireStoredRetryMatches( + StoredSource stored, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + OriginalStartSessionCurrentAttemptEvidence.Request request, + byte[] sourceReadRequestBytes, + byte[] accountProjection) { + Candidate candidate = stored.candidate(); + var association = historical.firstSelection().association(); + var descriptor = historical.launchAssociation().launchBindingEvidence().descriptor(); + var release = historical.launchAssociation().launchBindingEvidence().releaseAttestation(); + if (!candidate.targetNamespace().equals(request.targetNamespace()) + || !candidate + .controlPlaneRequestId() + .equals(request.originalTuple().controlPlaneRequestId()) + || !candidate + .canonicalTenantId() + .equals(request.originalTuple().preAuthorizationTuple().action().scope().tenantId()) + || !candidate.ownerAttemptId().equals(request.expectedOwnerAttemptId()) + || !candidate.ownerMutationId().equals(request.expectedOwnerMutationId()) + || candidate.ownerFence() != request.expectedOwnerFence() + || !Arrays.equals( + candidate.originalPostAuthorizationTuple(), request.canonicalPostAuthorizationTuple()) + || !Arrays.equals(candidate.accountRedemptionProjection(), accountProjection) + || !Arrays.equals(candidate.sourceReadRequestBytes(), sourceReadRequestBytes) + || !candidate.canonicalVersionId().equals(association.canonicalVersionId()) + || !candidate.selectedCommitId().equals(association.selectedCommitId()) + || !candidate.publishWorkflowId().equals(association.publishWorkflowId()) + || !candidate.associationDigest().equals(association.associationDigest()) + || !candidate.worldSourceOperationId().equals(association.sourceOperationId()) + || !candidate.worldSourceEvidenceDigest().equals(association.sourceEvidenceDigest()) + || !candidate.worldSlug().equals(association.worldSlug()) + || !candidate.launchDescriptorId().equals(descriptor.launchDescriptorId()) + || !candidate.descriptorRequestDigest().equals(descriptor.requestDigest()) + || !candidate.descriptorResultDigest().equals(descriptor.resultDigest()) + || !candidate.releaseAttestationEvidenceDigest().equals(release.evidenceDigest())) { + throw new StartSessionOperatorAttemptConflictException( + "Original StartSession authored-core retry differs from the first retained request"); + } + } + + private static void requireSameStoredSource( + Candidate candidate, StoredSource committed, StoredSource readback) { + if (!committed.retainedAt().equals(readback.retainedAt()) + || !committed + .candidate() + .sourceResultDigest() + .equals(readback.candidate().sourceResultDigest()) + || !committed.candidate().sourceResultDigest().equals(candidate.sourceResultDigest()) + || !MessageDigest.isEqual( + committed.candidate().canonicalSourceResultBytes(), + readback.candidate().canonicalSourceResultBytes()) + || !MessageDigest.isEqual( + candidate.canonicalSourceResultBytes(), + readback.candidate().canonicalSourceResultBytes())) { + throw new IllegalStateException( + "Committed authored-core source failed exact independent readback"); + } + } + + private static TransactionOperations writableReadCommitted( + PlatformTransactionManager transactionManager) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + transaction.setReadOnly(false); + return transaction; + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Authenticated Game Design authored-core read must remain outside Game Session SQL"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionLaunchReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionLaunchReadGrpcService.java new file mode 100644 index 0000000000..9132f7f0e5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionLaunchReadGrpcService.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.v1.OriginalStartSessionLaunchReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionLaunchRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionLaunchResponse; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Directly constructible, deliberately unregistered Account-only read of the original StartSession + * Game Session launch and its actual retained tuple. + * + *

This read returns a current row projection only. It does not require STARTING, grant lifecycle + * authority, or authorize activation/admission. + */ +public final class OriginalStartSessionLaunchReadGrpcService + extends OriginalStartSessionLaunchReadServiceGrpc + .OriginalStartSessionLaunchReadServiceImplBase { + private final GameSessionCanonicalInstanceLaunchRepository repository; + private final String workloadNamespace; + + public OriginalStartSessionLaunchReadGrpcService( + GameSessionCanonicalInstanceLaunchRepository repository, String workloadNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readOriginalStartSessionLaunch( + ReadOriginalStartSessionLaunchRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "observer"); + + try { + // Authenticate the exact Account workload before decoding caller-controlled fields. + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified same-namespace Account workload required") + .asRuntimeException(); + } + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + if (!"account-service".equals(peer.service()) + || !workloadNamespace.equals(peer.namespace()) + || !expectedPeerUri.equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace Account workload without caller context required") + .asRuntimeException(); + } + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + if (request == null) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Complete original StartSession launch read request required") + .asRuntimeException()); + return; + } + final OriginalStartSessionLaunchReadEvidence.Request decoded; + try { + decoded = OriginalStartSessionLaunchReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Complete canonical original StartSession launch request required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(decoded.selector().targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Original launch target differs from configured Game Session owner") + .asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Independent Game Session original launch snapshot required") + .asRuntimeException()); + return; + } + + try { + var retained = + repository.readByOriginalTuple( + decoded.selector(), decoded.originalPostAuthorizationTupleBytes()); + if (retained.isEmpty()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact original StartSession launch association is unavailable") + .asRuntimeException()); + return; + } + var association = retained.orElseThrow(); + var launch = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + decoded.selector(), + association.playableStateNamespaceId(), + association.playableStateScope(), + association.publicProduction(), + association.canonicalRealmId(), + association.catalogRevision(), + association.currentGameInstanceStatus(), + association.currentRowVersion(), + association.launchBindingEvidence()); + var result = + new OriginalStartSessionLaunchReadEvidence.Result( + decoded, launch, association.originalStartSessionTuple()); + observer.onNext(OriginalStartSessionLaunchReadGrpcCodec.toResponse(result)); + observer.onCompleted(); + } catch (DataAccessException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Session original launch owner storage unavailable") + .asRuntimeException()); + } catch (RuntimeException incompleteOrConflicting) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Complete exact original launch owner evidence is unavailable") + .asRuntimeException()); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V45__retained_original_start_session_authored_core.sql b/services/game-session-service/src/main/resources/db/migration/V45__retained_original_start_session_authored_core.sql new file mode 100644 index 0000000000..06bbb9b7eb --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V45__retained_original_start_session_authored_core.sql @@ -0,0 +1,181 @@ +-- Retain Game Design's exact public authored-core result against its original launch and +-- attempt. The row is source evidence only; it does not authorize allocation or runtime use. +CREATE TABLE game_session_original_start_session_authored_actor_core_retention ( + target_namespace VARCHAR(63) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_tenant_id UUID NOT NULL, + game_instance_uuid UUID NOT NULL, + owner_attempt_id UUID NOT NULL, + owner_mutation_id UUID NOT NULL, + owner_fence BIGINT NOT NULL, + owner_lease_expires_at TIMESTAMPTZ NOT NULL, + original_post_authorization_tuple BYTEA NOT NULL, + account_redemption_projection BYTEA NOT NULL, + account_redemption_projection_digest VARCHAR(64) NOT NULL, + canonical_version_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + publish_workflow_id VARCHAR(256) NOT NULL, + association_digest VARCHAR(71) NOT NULL, + world_source_operation_id UUID NOT NULL, + world_source_evidence_digest VARCHAR(71) NOT NULL, + world_slug VARCHAR(120) NOT NULL, + launch_descriptor_id VARCHAR(128) NOT NULL, + descriptor_request_digest VARCHAR(71) NOT NULL, + descriptor_result_digest VARCHAR(71) NOT NULL, + release_attestation_evidence_digest VARCHAR(71) NOT NULL, + source_read_request_bytes BYTEA NOT NULL, + canonical_source_result_bytes BYTEA NOT NULL, + source_result_digest VARCHAR(71) NOT NULL, + retained_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT pk_gs_original_start_session_actor_core_retention + PRIMARY KEY (target_namespace, control_plane_request_id), + CONSTRAINT uq_gs_original_start_session_actor_core_instance + UNIQUE (target_namespace, game_instance_uuid), + CONSTRAINT uq_gs_original_start_session_actor_core_attempt + UNIQUE (owner_attempt_id), + CONSTRAINT fk_gs_original_start_session_actor_core_launch + FOREIGN KEY (target_namespace, control_plane_request_id) + REFERENCES game_session_canonical_instance_launch + (target_namespace, control_plane_request_id) ON DELETE RESTRICT, + CONSTRAINT ck_gs_original_start_session_actor_core_identity CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND control_plane_request_id !~ '^[[:space:]]*$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_fence > 0 + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND publish_workflow_id !~ '^[[:space:]]*$' + AND world_source_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND launch_descriptor_id !~ '^[[:space:]]*$'), + CONSTRAINT ck_gs_original_start_session_actor_core_content CHECK ( + octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144 + AND octet_length(account_redemption_projection) BETWEEN 1 AND 262144 + AND account_redemption_projection_digest ~ '^[0-9a-f]{64}$' + AND account_redemption_projection_digest = encode(sha256(account_redemption_projection), 'hex') + AND association_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND release_attestation_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(source_read_request_bytes) BETWEEN 1 AND 524288 + AND octet_length(canonical_source_result_bytes) BETWEEN 1 AND 8388608 + AND source_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_result_digest = 'sha256:' || encode(sha256(canonical_source_result_bytes), 'hex')) +); + +-- V35's original-attempt table is intentionally hidden from jOOQ's DDL simulator. Keep the +-- durable relational binding in PostgreSQL while excluding only this cross-relation constraint. +-- [jooq ignore start] +ALTER TABLE game_session_original_start_session_authored_actor_core_retention + ADD CONSTRAINT fk_gs_original_start_session_actor_core_attempt + FOREIGN KEY (target_namespace, control_plane_request_id) + REFERENCES game_session_start_session_operator_attempt + (target_namespace, control_plane_request_id) ON DELETE RESTRICT; +-- [jooq ignore stop] + +-- New rows must join the exact complete launch and still-live original pending attempt. The +-- authenticated source result is independently validated in Game Session before it reaches SQL. +-- [jooq ignore start] +CREATE FUNCTION guard_gs_original_start_session_actor_core_retention() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE launch game_session_canonical_instance_launch%ROWTYPE; + attempt game_session_start_session_operator_attempt%ROWTYPE; + source_result JSONB; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Session authored-core source retention is immutable and append-only' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO STRICT launch + FROM game_session_canonical_instance_launch + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = NEW.control_plane_request_id; + SELECT * INTO STRICT attempt + FROM game_session_start_session_operator_attempt + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = NEW.control_plane_request_id; + + source_result := convert_from(NEW.canonical_source_result_bytes, 'UTF8')::JSONB; + IF launch.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR launch.game_instance_uuid IS DISTINCT FROM NEW.game_instance_uuid + OR launch.original_start_session_tuple IS DISTINCT FROM + NEW.original_post_authorization_tuple + OR launch.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR launch.world_slug IS DISTINCT FROM NEW.world_slug + OR launch.complete_launch_binding_evidence -> 'descriptor' ->> 'requestDigest' + IS DISTINCT FROM NEW.descriptor_request_digest + OR launch.complete_launch_binding_evidence -> 'descriptor' ->> 'resultDigest' + IS DISTINCT FROM NEW.descriptor_result_digest + OR launch.complete_launch_binding_evidence -> 'descriptor' ->> 'authoredWorldSourceOperationId' + IS DISTINCT FROM NEW.world_source_operation_id::TEXT + OR launch.complete_launch_binding_evidence -> 'descriptor' ->> 'authoredWorldSourceEvidenceDigest' + IS DISTINCT FROM NEW.world_source_evidence_digest + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest' + IS DISTINCT FROM NEW.release_attestation_evidence_digest + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'commitId' + IS DISTINCT FROM NEW.selected_commit_id::TEXT + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'publishWorkflowId' + IS DISTINCT FROM NEW.publish_workflow_id + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'authoredWorldSourceOperationId' + IS DISTINCT FROM NEW.world_source_operation_id::TEXT + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'authoredWorldSourceEvidenceDigest' + IS DISTINCT FROM NEW.world_source_evidence_digest + OR launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'worldSlug' + IS DISTINCT FROM NEW.world_slug + OR attempt.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR attempt.owner_attempt_id IS DISTINCT FROM NEW.owner_attempt_id + OR attempt.owner_mutation_id IS DISTINCT FROM NEW.owner_mutation_id + OR attempt.owner_fence IS DISTINCT FROM NEW.owner_fence + OR attempt.post_authorization_execution_tuple IS DISTINCT FROM + NEW.original_post_authorization_tuple + OR attempt.account_redemption_projection IS DISTINCT FROM + NEW.account_redemption_projection + OR attempt.phase_state IS DISTINCT FROM 'OWNER_EXECUTION_PENDING' + OR attempt.lease_expires_at IS DISTINCT FROM NEW.owner_lease_expires_at + OR attempt.lease_expires_at <= clock_timestamp() + OR jsonb_typeof(source_result) IS DISTINCT FROM 'object' + OR source_result ->> 'schema' IS DISTINCT FROM + 'game-design-authored-initial-actor-core-read/v1' + OR (SELECT count(*) FROM jsonb_object_keys(source_result)) <> 5 + OR jsonb_typeof(source_result -> 'request') IS DISTINCT FROM 'string' + OR decode(source_result ->> 'request', 'base64') IS DISTINCT FROM + NEW.source_read_request_bytes + OR jsonb_typeof(source_result -> 'associationRead') IS DISTINCT FROM 'string' + OR jsonb_typeof(source_result -> 'launchDescriptor') IS DISTINCT FROM 'string' + OR jsonb_typeof(source_result -> 'projections') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'Authored-core retention differs from the exact live launch, attempt, or closed result' + USING ERRCODE = '23514', + CONSTRAINT = 'ck_gs_original_start_session_actor_core_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_original_start_session_actor_core_retention_guard + BEFORE INSERT OR UPDATE OR DELETE + ON game_session_original_start_session_authored_actor_core_retention + FOR EACH ROW EXECUTE FUNCTION guard_gs_original_start_session_actor_core_retention(); + +CREATE FUNCTION reject_gs_original_start_session_actor_core_retention_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session authored-core source retention cannot be truncated' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER game_session_original_start_session_actor_core_retention_no_truncate + BEFORE TRUNCATE ON game_session_original_start_session_authored_actor_core_retention + FOR EACH STATEMENT EXECUTE FUNCTION reject_gs_original_start_session_actor_core_retention_truncate(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java new file mode 100644 index 0000000000..9917450052 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java @@ -0,0 +1,432 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Duration; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.Candidate; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.StoredSource; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchProofFixtures.SyntheticLaunchProof; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.CanonicalRealmCatalog; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociation; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** + * PostgreSQL proof of append-only exact authored-core retention, including a valid empty result. + * Synthetic result bytes prove storage binding only, not authenticated Game Design transport. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest { + private static final String NAMESPACE = "test"; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void retainsExactEmptyOwnerResultAndRejectsConflictOrMutation() throws Exception { + try (Fixture fixture = newFixture()) { + LaunchInputs launch = fixture.createLaunch(); + var attempt = fixture.createAttempt(launch.proof().originalTuple()); + var selector = exactReplayRequest(launch, attempt.claim()); + byte[] requestBytes = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(selector).toByteArray(); + byte[] sourceBytes = canonicalEmptyResult(requestBytes); + Candidate candidate = candidate(launch, attempt, requestBytes, sourceBytes); + + StoredSource first = + Objects.requireNonNull( + fixture + .transactions() + .execute( + status -> fixture.retentionRepository().retainInOwnerTransaction(candidate))); + StoredSource independent = + fixture + .retentionRepository() + .readByOriginalOperation( + NAMESPACE, launch.proof().originalTuple().controlPlaneRequestId()) + .orElseThrow(); + + assertThat(first.candidate().canonicalSourceResultBytes()).containsExactly(sourceBytes); + assertThat(independent.candidate().canonicalSourceResultBytes()).containsExactly(sourceBytes); + assertThat(independent.candidate().sourceResultDigest()) + .isEqualTo(candidate.sourceResultDigest()); + assertThat(independent.retainedAt()).isEqualTo(first.retainedAt()); + assertThat(new String(sourceBytes, java.nio.charset.StandardCharsets.UTF_8)) + .contains("\"projections\":[]"); + + byte[] conflictingBytes = canonicalEmptyResult(requestBytes, "different exact result"); + Candidate conflict = candidate(launch, attempt, requestBytes, conflictingBytes); + assertThatThrownBy( + () -> + fixture + .transactions() + .execute( + status -> + fixture.retentionRepository().retainInOwnerTransaction(conflict))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts with its first exact result"); + assertThat( + fixture + .retentionRepository() + .readByOriginalOperation( + NAMESPACE, launch.proof().originalTuple().controlPlaneRequestId()) + .orElseThrow() + .candidate() + .canonicalSourceResultBytes()) + .containsExactly(sourceBytes); + + String where = + " WHERE target_namespace = '" + + NAMESPACE + + "' AND control_plane_request_id = '" + + launch.proof().originalTuple().controlPlaneRequestId() + + "'"; + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_session_original_start_session_authored_actor_core_retention" + + " SET source_result_digest = 'sha256:' || repeat('0', 64)" + + where)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_session_original_start_session_authored_actor_core_retention" + + where)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "TRUNCATE game_session_original_start_session_authored_actor_core_retention")) + .isInstanceOf(RuntimeException.class); + } + } + + private static Candidate candidate( + LaunchInputs launch, AttemptInputs attempt, byte[] requestBytes, byte[] sourceBytes) { + var tuple = launch.proof().originalTuple(); + var binding = launch.proof().completeLaunchBindingEvidence(); + var release = binding.releaseAttestation(); + return new Candidate( + NAMESPACE, + tuple.controlPlaneRequestId(), + launch.catalog().canonicalTenantId(), + launch.gameInstanceUuid(), + attempt.snapshot().ownerAttemptId(), + attempt.snapshot().ownerMutationId(), + attempt.snapshot().ownerFence(), + attempt.snapshot().leaseExpiresAt(), + tuple.canonicalBytes(), + attempt.snapshot().accountRedemptionProjection(), + OriginalStartSessionCurrentAttemptEvidence.projectionDigest( + attempt.snapshot().accountRedemptionProjection()), + release.canonicalVersionId(), + UUID.fromString(release.commitId()), + release.publishWorkflowId(), + associationDigest(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.worldSlug(), + binding.descriptor().launchDescriptorId(), + binding.descriptor().requestDigest(), + binding.descriptor().resultDigest(), + release.evidenceDigest(), + requestBytes, + sourceBytes, + sha256(sourceBytes)); + } + + private static StartSessionTemplateAssociationReadEvidence.Request exactReplayRequest( + LaunchInputs launch, AttemptClaim claim) { + var tuple = launch.proof().originalTuple(); + var release = launch.proof().completeLaunchBindingEvidence().releaseAttestation(); + return new StartSessionTemplateAssociationReadEvidence.Request( + StartSessionTemplateAssociationReadEvidence.SCHEMA_VERSION, + NAMESPACE, + UUID.randomUUID(), + tuple.canonicalBytes(), + claim.ownerAttemptId(), + claim.ownerFence(), + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + release.canonicalVersionId(), + UUID.fromString(release.commitId()), + release.publishWorkflowId(), + associationDigest())); + } + + private static byte[] canonicalEmptyResult(byte[] requestBytes) { + return canonicalEmptyResult(requestBytes, ""); + } + + private static byte[] canonicalEmptyResult(byte[] requestBytes, String associationRead) { + Map result = + Map.of( + "schema", "game-design-authored-initial-actor-core-read/v1", + "request", Base64.getEncoder().encodeToString(requestBytes), + "associationRead", Base64.getEncoder().encodeToString(associationRead.getBytes()), + "launchDescriptor", Base64.getEncoder().encodeToString("descriptor".getBytes()), + "projections", List.of()); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(result)); + } catch (IOException invalid) { + throw new IllegalStateException("Cannot serialize empty source fixture", invalid); + } + } + + private static String associationDigest() { + return "sha256:" + "1".repeat(64); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static SyntheticLaunchProof launchProof(CanonicalRealmCatalog catalog) { + String operationId = "retained-authored-core-" + UUID.randomUUID(); + var stipulation = + GameSessionCanonicalInstanceLaunchProofFixtures.create( + NAMESPACE, + operationId, + catalog.canonicalTenantId(), + catalog.worldSlug(), + catalog.sourceEvidence(), + 91L, + 13L, + 17L, + "launch-" + UUID.randomUUID(), + "generation-fixture", + 2L, + "fixture-release/" + UUID.randomUUID()); + var descriptor = stipulation.completeLaunchBindingEvidence().descriptor(); + String commitId = UUID.randomUUID().toString(); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + participantKey -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participantKey, + Long.toString(descriptor.versionId()), + false, + null, + commitId, + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey), + "GAME_LOGIC".equals(participantKey), + "GAME_LOGIC".equals(participantKey) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + catalog.canonicalTenantId(), + UUID.randomUUID(), + catalog.worldSlug(), + catalog.sourceEvidence().operationId(), + catalog.sourceEvidence().evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "synthetic-publish-workflow", + commitId, + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new SyntheticLaunchProof( + stipulation.originalTuple(), new CompleteLaunchBindingEvidence(descriptor, release)); + } + + private static Fixture newFixture() { + String schema = "gs_authored_core_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture(schema, dataSource, dsl, new DataSourceTransactionManager(dataSource)); + } + + private record LaunchInputs( + CanonicalRealmCatalog catalog, SyntheticLaunchProof proof, UUID gameInstanceUuid) {} + + private record AttemptInputs( + AttemptClaim claim, + GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot snapshot) {} + + private record Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager transactionManager) + implements AutoCloseable { + TransactionTemplate transactions() { + return new TransactionTemplate(transactionManager); + } + + GameSessionAuthoredActorCoreRetentionRepository retentionRepository() { + return new GameSessionAuthoredActorCoreRetentionRepository( + dsl, transactionManager, NAMESPACE); + } + + LaunchInputs createLaunch() { + FreshTenantAssociation fresh = createFreshAssociation(); + var catalogProof = GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(fresh); + CanonicalRealmCatalog catalog = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE) + .establishFreshPublicRealm( + fresh, + catalogProof.source(), + catalogProof.publishedSet(), + UUID.randomUUID(), + UUID.randomUUID()); + SyntheticLaunchProof proof = launchProof(catalog); + var launches = + new GameSessionCanonicalInstanceLaunchRepository( + dsl, + transactionManager, + NAMESPACE, + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE)); + var created = + launches.createStartingLaunch( + proof.originalTuple(), proof.completeLaunchBindingEvidence(), catalog); + return new LaunchInputs(catalog, proof, created.gameInstanceUuid()); + } + + AttemptInputs createAttempt( + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple tuple) { + var repository = + new GameSessionStartSessionOperatorAttemptRepository(dsl, Duration.ofMinutes(5)); + var claim = + Objects.requireNonNull( + transactions().execute(status -> repository.reserve(tuple)), + "owner attempt reservation") + .claim() + .orElseThrow(); + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + AccountRedemptionProjection projection = + new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + Long.parseLong(bundle.issuanceFence())); + var attached = + Objects.requireNonNull( + transactions() + .execute( + status -> repository.attachAccountRedemptionProjection(claim, projection)), + "attached Account projection"); + return new AttemptInputs(claim, attached); + } + + private FreshTenantAssociation createFreshAssociation() { + UUID requestId = UUID.randomUUID(); + UUID canonicalTenantId = UUID.randomUUID(); + String sourceKey = "authored-core-owner-key-" + requestId.toString().substring(0, 8); + long sourceRowId = Math.abs(requestId.getMostSignificantBits() % 1_000_000L) + 1L; + UUID sourceOperationId = UUID.randomUUID(); + String requestDigest = + GameTenantCreationDigest.requestDigest( + NAMESPACE, requestId, sourceKey, "Retention fixture game", null); + FreshTenantCreationEvidence evidence = + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + requestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + requestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + sourceRowId, + sourceKey, + "NEW_GAME_ROW")); + GameDesignFreshTenantCreationClient client = mock(GameDesignFreshTenantCreationClient.class); + when(client.resolveCreation(requestId, evidence.requestDigest())).thenReturn(evidence); + return new GameSessionFreshTenantAssociationRepository( + dsl, transactionManager, client, NAMESPACE) + .associateFreshTenant(requestId, evidence.requestDigest()); + } + + @Override + public void close() throws Exception { + try (var connection = dataSource.getConnection(); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionServiceTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionServiceTest.java new file mode 100644 index 0000000000..266715a43c --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionServiceTest.java @@ -0,0 +1,544 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.Candidate; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.StoredSource; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchProofFixtures.SyntheticLaunchProof; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository.CanonicalInstanceLaunch; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.CanonicalRealmCatalog; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; +import net.firedevops.firemud.gamesession.service.impl.GameSessionAuthoredActorCoreRetentionService; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Service-ordering proof over the existing synthetic canonical launch fixture and mocked owner + * clients. It does not prove authenticated Game Design transport or mTLS behavior. + */ +class GameSessionAuthoredActorCoreRetentionServiceTest { + private static final String NAMESPACE = "test"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void exactRetainedRetryReturnsFirstEmptyBytesWithoutRemoteReadOrLeaseRenewal() throws Exception { + TestInputs inputs = inputs(); + byte[] firstBytes = emptyCanonicalSourceBytes(sourceRequestBytes(inputs)); + Candidate first = candidate(inputs, firstBytes); + StoredSource stored = new StoredSource(first, Instant.parse("2026-01-02T03:04:05Z")); + when(inputs + .retention() + .readByOriginalOperation(NAMESPACE, inputs.tuple().controlPlaneRequestId())) + .thenReturn(Optional.of(stored)); + + StoredSource result = + inputs.service().retain(inputs.historical(), inputs.currentAttemptRequest()); + + assertThat(result).isSameAs(stored); + assertThat(result.candidate().canonicalSourceResultBytes()).containsExactly(firstBytes); + assertThat(new String(firstBytes, java.nio.charset.StandardCharsets.UTF_8)) + .contains("\"projections\":[]"); + verify(inputs.retention()) + .readByOriginalOperation(NAMESPACE, inputs.tuple().controlPlaneRequestId()); + verifyNoInteractions( + inputs.launches(), inputs.attempts(), inputs.gameDesign(), inputs.transactionManager()); + } + + @Test + void changedCurrentAttemptAfterSourceReadDeniesBeforeRetentionInsert() throws Exception { + TestInputs inputs = inputs(); + when(inputs + .retention() + .readByOriginalOperation(NAMESPACE, inputs.tuple().controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(inputs + .launches() + .readByOriginalTuple( + inputs.historical().request().associationSelector(), + inputs.tuple().canonicalBytes())) + .thenReturn(Optional.of(inputs.launch())); + AttemptSnapshot original = snapshot(inputs, inputs.ownerMutationId()); + AttemptSnapshot changed = snapshot(inputs, UUID.randomUUID()); + when(inputs.attempts().readCurrentOriginalAttempt(inputs.currentAttemptRequest())) + .thenReturn(original, changed); + stubAuthenticatedSourceResult(inputs, inputs.binding().descriptor()); + + assertThatThrownBy( + () -> inputs.service().retain(inputs.historical(), inputs.currentAttemptRequest())) + .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) + .hasMessageContaining("Exact live pending original StartSession attempt"); + + verify(inputs.gameDesign()).read(any(AuthoredInitialActorCoreReadEvidence.ReadRequest.class)); + verify(inputs.attempts(), times(2)).readCurrentOriginalAttempt(inputs.currentAttemptRequest()); + verify(inputs.retention(), never()).retainInOwnerTransaction(any(Candidate.class)); + } + + @Test + void sourceDescriptorThatDiffersFromActualLaunchDeniesBeforeRetentionInsert() throws Exception { + TestInputs inputs = inputs(); + when(inputs + .retention() + .readByOriginalOperation(NAMESPACE, inputs.tuple().controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(inputs + .launches() + .readByOriginalTuple( + inputs.historical().request().associationSelector(), + inputs.tuple().canonicalBytes())) + .thenReturn(Optional.of(inputs.launch())); + AttemptSnapshot original = snapshot(inputs, inputs.ownerMutationId()); + when(inputs.attempts().readCurrentOriginalAttempt(inputs.currentAttemptRequest())) + .thenReturn(original); + AuthoredWorldLaunchDescriptorEvidence mismatchedDescriptor = + mock(AuthoredWorldLaunchDescriptorEvidence.class); + stubAuthenticatedSourceResult(inputs, mismatchedDescriptor); + + assertThatThrownBy( + () -> inputs.service().retain(inputs.historical(), inputs.currentAttemptRequest())) + .isInstanceOf( + net.firedevops.firemud.gamesession.repository + .GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class) + .hasMessageContaining("exact original association or launch binding"); + + verify(inputs.gameDesign()).read(any(AuthoredInitialActorCoreReadEvidence.ReadRequest.class)); + verify(inputs.attempts()).readCurrentOriginalAttempt(inputs.currentAttemptRequest()); + verify(inputs.retention(), never()).retainInOwnerTransaction(any(Candidate.class)); + } + + private static TestInputs inputs() throws Exception { + UUID tenantId = UUID.randomUUID(); + String worldSlug = "retention-fixture-world"; + UUID sourceOperationId = UUID.randomUUID(); + UUID registrationRequestId = UUID.randomUUID(); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + tenantId, + "retention-fixture-tenant", + worldSlug, + "Retention Fixture"); + AuthoredWorldSourceEvidence sourceEvidence = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + "retention-fixture-tenant", + worldSlug, + "Retention Fixture", + 91L, + "retention-fixture-key", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + "retention-fixture-tenant", + worldSlug, + "Retention Fixture", + 91L, + "retention-fixture-key", + "NEW_GAME_ROW")); + SyntheticLaunchProof fixtureProof = + GameSessionCanonicalInstanceLaunchProofFixtures.create( + NAMESPACE, + "retained-authored-core-" + UUID.randomUUID(), + tenantId, + worldSlug, + sourceEvidence, + 91L, + 13L, + 17L, + "retention-descriptor-" + UUID.randomUUID(), + "generation-fixture", + 2L, + "fixture-release/" + UUID.randomUUID()); + SyntheticLaunchProof proof = withUuidCommit(fixtureProof, sourceEvidence); + var tuple = proof.originalTuple(); + var binding = proof.completeLaunchBindingEvidence(); + var descriptor = binding.descriptor(); + var release = binding.releaseAttestation(); + UUID ownerAttemptId = UUID.randomUUID(); + UUID ownerMutationId = UUID.randomUUID(); + long ownerFence = 7L; + UUID gameInstanceUuid = UUID.randomUUID(); + UUID playableNamespaceId = UUID.randomUUID(); + String associationDigest = "sha256:" + "1".repeat(64); + + var selector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + NAMESPACE, + tenantId, + worldSlug, + gameInstanceUuid, + tuple.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var exactRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + StartSessionTemplateAssociationReadEvidence.SCHEMA_VERSION, + NAMESPACE, + UUID.randomUUID(), + tuple.canonicalBytes(), + ownerAttemptId, + ownerFence, + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + release.canonicalVersionId(), + UUID.fromString(release.commitId()), + release.publishWorkflowId(), + associationDigest)); + var historicalRequest = + new HistoricalOriginalStartSessionOwnerEvidence.Request( + selector, ownerAttemptId, ownerFence); + byte[] accountProjection = StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple); + + var selection = mock(StartSessionTemplateAssociationReadEvidence.Association.class); + when(selection.canonicalTenantId()).thenReturn(tenantId); + when(selection.canonicalVersionId()).thenReturn(release.canonicalVersionId()); + when(selection.selectedCommitId()).thenReturn(UUID.fromString(release.commitId())); + when(selection.publishWorkflowId()).thenReturn(release.publishWorkflowId()); + when(selection.associationDigest()).thenReturn(associationDigest); + when(selection.sourceOperationId()).thenReturn(sourceOperationId); + when(selection.sourceEvidenceDigest()).thenReturn(sourceEvidence.evidenceDigest()); + when(selection.worldSlug()).thenReturn(worldSlug); + var firstSelection = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + when(firstSelection.association()).thenReturn(selection); + + PublishedReleaseBundle bundle = releaseBundle(binding); + var pinnedAssociationRead = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + when(pinnedAssociationRead.request()).thenReturn(exactRequest); + when(pinnedAssociationRead.releaseBundle()).thenReturn(bundle); + var descriptorPin = + new StartSessionLaunchDescriptorGrpcCodec.Resolved( + pinnedAssociationRead, + new StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome(descriptor)); + var launchAssociation = + new HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation( + NAMESPACE, + tenantId, + worldSlug, + gameInstanceUuid, + tuple.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + playableNamespaceId, + RealmEntryPolicy.StateScope.SHARED, + true, + 0L, + binding); + var historical = mock(HistoricalOriginalStartSessionOwnerEvidence.Result.class); + when(historical.request()).thenReturn(historicalRequest); + when(historical.originalTuple()).thenReturn(tuple); + when(historical.ownerAttemptId()).thenReturn(ownerAttemptId); + when(historical.ownerFence()).thenReturn(ownerFence); + when(historical.accountRedemptionProjection()).thenReturn(accountProjection); + when(historical.firstSelection()).thenReturn(firstSelection); + when(historical.descriptorPin()).thenReturn(descriptorPin); + when(historical.launchAssociation()).thenReturn(launchAssociation); + + CanonicalRealmCatalog catalog = mock(CanonicalRealmCatalog.class); + when(catalog.worldSlug()).thenReturn(worldSlug); + CanonicalInstanceLaunch launch = mock(CanonicalInstanceLaunch.class); + when(launch.targetNamespace()).thenReturn(NAMESPACE); + when(launch.controlPlaneRequestId()).thenReturn(tuple.controlPlaneRequestId()); + when(launch.canonicalTenantId()).thenReturn(tenantId); + when(launch.gameInstanceUuid()).thenReturn(gameInstanceUuid); + when(launch.canonicalRealmCatalog()).thenReturn(catalog); + when(launch.launchBindingEvidence()).thenReturn(binding); + when(launch.playableStateNamespaceId()).thenReturn(playableNamespaceId); + when(launch.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(launch.publicProduction()).thenReturn(true); + when(launch.capturedStartingRowVersion()).thenReturn(0L); + + UUID readId = UUID.randomUUID(); + var currentAttemptRequest = + new OriginalStartSessionCurrentAttemptEvidence.Request( + readId, NAMESPACE, tuple.canonicalBytes(), ownerAttemptId, ownerMutationId, ownerFence); + AttemptSnapshot attempt = mock(AttemptSnapshot.class); + Instant leaseExpiresAt = Instant.now().plusSeconds(300); + when(attempt.targetNamespace()).thenReturn(NAMESPACE); + when(attempt.controlPlaneRequestId()).thenReturn(tuple.controlPlaneRequestId()); + when(attempt.canonicalTenantId()).thenReturn(tenantId); + when(attempt.ownerAttemptId()).thenReturn(ownerAttemptId); + when(attempt.ownerMutationId()).thenReturn(ownerMutationId); + when(attempt.ownerFence()).thenReturn(ownerFence); + when(attempt.phaseState()).thenReturn(OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE); + when(attempt.postAuthorizationExecutionTuple()).thenReturn(tuple.canonicalBytes()); + when(attempt.accountRedemptionProjection()).thenReturn(accountProjection); + when(attempt.leaseExpiresAt()).thenReturn(leaseExpiresAt); + + var launches = mock(GameSessionCanonicalInstanceLaunchRepository.class); + var attempts = mock(GameSessionStartSessionOperatorAttemptRepository.class); + var gameDesign = mock(AuthoredInitialActorCoreReadClient.class); + var retention = mock(GameSessionAuthoredActorCoreRetentionRepository.class); + var transactionManager = mock(PlatformTransactionManager.class); + TransactionStatus status = mock(TransactionStatus.class); + when(transactionManager.getTransaction(any(TransactionDefinition.class))).thenReturn(status); + doNothing().when(transactionManager).commit(status); + doNothing().when(transactionManager).rollback(status); + var service = + new GameSessionAuthoredActorCoreRetentionService( + NAMESPACE, launches, attempts, gameDesign, retention, transactionManager); + return new TestInputs( + tuple, + binding, + ownerAttemptId, + ownerMutationId, + ownerFence, + gameInstanceUuid, + exactRequest, + currentAttemptRequest, + historical, + launch, + attempt, + launches, + attempts, + gameDesign, + retention, + transactionManager, + service); + } + + private static void stubAuthenticatedSourceResult( + TestInputs inputs, AuthoredWorldLaunchDescriptorEvidence sourceDescriptor) throws Exception { + PublishedReleaseBundle bundle = releaseBundle(inputs.binding()); + var retainedAssociation = inputs.historical().firstSelection().association(); + var associationRead = mock(StartSessionTemplateAssociationReadEvidence.Result.class); + when(associationRead.request()).thenReturn(inputs.associationRequest()); + when(associationRead.association()).thenReturn(retainedAssociation); + when(associationRead.releaseBundle()).thenReturn(bundle); + when(associationRead.worldPublishedStartLocationEvidence()).thenReturn(null); + var source = mock(AuthoredInitialActorCoreReadEvidence.ReadResult.class); + byte[] bytes = emptyCanonicalSourceBytes(sourceRequestBytes(inputs)); + when(source.request()).thenReturn(inputs.associationRequest()); + when(source.associationRead()).thenReturn(associationRead); + when(source.descriptor()).thenReturn(sourceDescriptor); + when(source.canonicalBytes()).thenReturn(bytes); + when(source.digest()).thenReturn(sha256(bytes)); + when(inputs.gameDesign().read(any(AuthoredInitialActorCoreReadEvidence.ReadRequest.class))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return source; + }); + } + + private static AttemptSnapshot snapshot(TestInputs inputs, UUID mutationId) { + AttemptSnapshot snapshot = mock(AttemptSnapshot.class); + when(snapshot.targetNamespace()).thenReturn(NAMESPACE); + when(snapshot.controlPlaneRequestId()).thenReturn(inputs.tuple().controlPlaneRequestId()); + when(snapshot.canonicalTenantId()) + .thenReturn(inputs.tuple().preAuthorizationTuple().action().scope().tenantId()); + when(snapshot.ownerAttemptId()).thenReturn(inputs.ownerAttemptId()); + when(snapshot.ownerMutationId()).thenReturn(mutationId); + when(snapshot.ownerFence()).thenReturn(inputs.ownerFence()); + when(snapshot.phaseState()) + .thenReturn(OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE); + when(snapshot.postAuthorizationExecutionTuple()).thenReturn(inputs.tuple().canonicalBytes()); + when(snapshot.accountRedemptionProjection()) + .thenReturn(StartSessionAccountRedemptionProjection.fromOriginalTuple(inputs.tuple())); + when(snapshot.leaseExpiresAt()).thenReturn(Instant.now().plusSeconds(300)); + return snapshot; + } + + private static Candidate candidate(TestInputs inputs, byte[] bytes) throws Exception { + var release = inputs.binding().releaseAttestation(); + var descriptor = inputs.binding().descriptor(); + byte[] projection = StartSessionAccountRedemptionProjection.fromOriginalTuple(inputs.tuple()); + byte[] requestBytes = + StartSessionTemplateAssociationReadGrpcCodec.toRequest(inputs.associationRequest()) + .toByteArray(); + return new Candidate( + NAMESPACE, + inputs.tuple().controlPlaneRequestId(), + inputs.tuple().preAuthorizationTuple().action().scope().tenantId(), + inputs.gameInstanceUuid(), + inputs.ownerAttemptId(), + inputs.ownerMutationId(), + inputs.ownerFence(), + Instant.parse("2026-01-01T00:00:00Z"), + inputs.tuple().canonicalBytes(), + projection, + OriginalStartSessionCurrentAttemptEvidence.projectionDigest(projection), + release.canonicalVersionId(), + UUID.fromString(release.commitId()), + release.publishWorkflowId(), + "sha256:" + "1".repeat(64), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.worldSlug(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest(), + requestBytes, + bytes, + sha256(bytes)); + } + + private static SyntheticLaunchProof withUuidCommit( + SyntheticLaunchProof stipulation, AuthoredWorldSourceEvidence source) { + var descriptor = stipulation.completeLaunchBindingEvidence().descriptor(); + String commitId = UUID.randomUUID().toString(); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + key -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + key, + Long.toString(descriptor.versionId()), + false, + null, + commitId, + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + key), + "GAME_LOGIC".equals(key), + "GAME_LOGIC".equals(key) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + UUID.randomUUID(), + descriptor.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "synthetic-publish-workflow", + commitId, + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new SyntheticLaunchProof( + stipulation.originalTuple(), new CompleteLaunchBindingEvidence(descriptor, release)); + } + + private static PublishedReleaseBundle releaseBundle(CompleteLaunchBindingEvidence binding) { + var descriptor = binding.descriptor(); + var release = binding.releaseAttestation(); + var builder = + PublishedReleaseBundle.newBuilder() + .setId(descriptor.releaseBundleId()) + .setVersionId(descriptor.versionId()) + .setIsScriptOnly(false) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setCanonicalTenantId(release.canonicalTenantId().toString()) + .setCanonicalVersionId(release.canonicalVersionId().toString()) + .setPublishWorkflowId(release.publishWorkflowId()) + .setAttestationSchemaVersion("v" + release.schemaVersion()) + .setManifestHash(release.manifestHash()) + .setManifestSchemaVersion(release.manifestSchemaVersion()) + .setGenerationConfigRevision(release.generationConfigRevision()) + .addAllRequiredManifestAssetKeys(release.requiredManifestAssetKeys()) + .addAllCommandDefinitions(release.commandDefinitions()); + for (AuthoredWorldReleaseAttestationEvidence.Participant expected : + release.participantDigests()) { + var participant = + ParticipantDigest.newBuilder() + .setParticipantKey(expected.participantKey()) + .setScopeValue(expected.scopeValue()) + .setAppliedCommitId(expected.appliedCommitId()) + .setContentDigest(expected.contentDigest()) + .setDigestSchemaVersion(expected.digestSchemaVersion()); + if (expected.abilitySchemaDigestPresent()) { + participant.setAbilitySchemaDigest(expected.abilitySchemaDigest()); + } + builder.addParticipantDigests(participant); + } + return builder.build(); + } + + private static byte[] sourceRequestBytes(TestInputs inputs) { + return StartSessionTemplateAssociationReadGrpcCodec.toRequest(inputs.associationRequest()) + .toByteArray(); + } + + private static byte[] emptyCanonicalSourceBytes(byte[] requestBytes) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString( + java.util.Map.of( + "schema", "game-design-authored-initial-actor-core-read/v1", + "request", Base64.getEncoder().encodeToString(requestBytes), + "associationRead", "fixture-association", + "launchDescriptor", "fixture-descriptor", + "projections", List.of()))); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private record TestInputs( + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple tuple, + CompleteLaunchBindingEvidence binding, + UUID ownerAttemptId, + UUID ownerMutationId, + long ownerFence, + UUID gameInstanceUuid, + StartSessionTemplateAssociationReadEvidence.Request associationRequest, + OriginalStartSessionCurrentAttemptEvidence.Request currentAttemptRequest, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + CanonicalInstanceLaunch launch, + AttemptSnapshot attempt, + GameSessionCanonicalInstanceLaunchRepository launches, + GameSessionStartSessionOperatorAttemptRepository attempts, + AuthoredInitialActorCoreReadClient gameDesign, + GameSessionAuthoredActorCoreRetentionRepository retention, + PlatformTransactionManager transactionManager, + GameSessionAuthoredActorCoreRetentionService service) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java index 0731dc2fca..b09e5d9d6c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java @@ -103,6 +103,34 @@ void atomicallyCreatesStartingPairAndExactRetryKeepsAllocationAfterLifecycleAdva assertThat(independent.launchBindingEvidence()) .isEqualTo(inputs.proof().completeLaunchBindingEvidence()); + var originalTupleRead = + inputs + .repository() + .readByOriginalTuple( + selector(inputs.proof(), inputs.catalog(), created.gameInstanceUuid()), + inputs.proof().originalTuple().canonicalBytes()) + .orElseThrow(); + assertThat(originalTupleRead.originalStartSessionTuple()) + .containsExactly(inputs.proof().originalTuple().canonicalBytes()); + assertThat(originalTupleRead.currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING); + assertThat(originalTupleRead.currentRowVersion()).isZero(); + + var mismatchedTuple = + GameSessionCanonicalInstanceLaunchProofFixtures.withAuditReason( + inputs.proof().originalTuple(), "different original tuple bytes"); + assertThatThrownBy( + () -> + inputs + .repository() + .readByOriginalTuple( + selector(inputs.proof(), inputs.catalog(), created.gameInstanceUuid()), + mismatchedTuple.canonicalBytes())) + .isInstanceOf(InvalidCanonicalInstanceLaunchException.class) + .hasMessageContaining("Retained original StartSession tuple differs"); + assertThat( fixture .dsl() @@ -126,6 +154,18 @@ void atomicallyCreatesStartingPairAndExactRetryKeepsAllocationAfterLifecycleAdva assertThat(retry.currentRowVersion()).isEqualTo(created.capturedStartingRowVersion() + 1L); assertThat(retry.capturedStartingRowVersion()) .isEqualTo(created.capturedStartingRowVersion()); + var currentOriginalTupleRead = + inputs + .repository() + .readByOriginalTuple( + selector(inputs.proof(), inputs.catalog(), created.gameInstanceUuid()), + inputs.proof().originalTuple().canonicalBytes()) + .orElseThrow(); + assertThat(currentOriginalTupleRead.currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.RUNNING); + assertThat(currentOriginalTupleRead.currentRowVersion()) + .isEqualTo(created.capturedStartingRowVersion() + 1L); var changedTuple = GameSessionCanonicalInstanceLaunchProofFixtures.withAuditReason( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepositoryTest.java new file mode 100644 index 0000000000..bed811662f --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepositoryTest.java @@ -0,0 +1,83 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionAuthoredActorCoreRetentionRepositoryTest { + private static final String NAMESPACE = "test"; + + @AfterEach + void clearAmbientTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void rejectsInvalidWorkloadNamespaceBeforeStorage() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + + assertThatThrownBy( + () -> + new GameSessionAuthoredActorCoreRetentionRepository( + dsl, transactionManager, "Not a DNS label")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload namespace"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void independentReadRejectsAmbientOwnerTransactionBeforeInspectingIdentityOrStorage() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var repository = + new GameSessionAuthoredActorCoreRetentionRepository(dsl, transactionManager, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.readByOriginalOperation(null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent owner snapshot"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void appendRequiresCallerOwnedWritableTransactionBeforeInspectingCandidate() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var repository = + new GameSessionAuthoredActorCoreRetentionRepository(dsl, transactionManager, NAMESPACE); + + assertThatThrownBy(() -> repository.retainInOwnerTransaction(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable caller-owned owner transaction"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void invalidReadIdentityIsRejectedBeforeOpeningSnapshot() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var repository = + new GameSessionAuthoredActorCoreRetentionRepository(dsl, transactionManager, NAMESPACE); + + assertThatThrownBy( + () -> repository.readByOriginalOperation("other", UUID.randomUUID().toString())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured Game Session workload namespace"); + + verifyNoInteractions(dsl, transactionManager); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepositoryTest.java index ce3b369c87..5c93080ff9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepositoryTest.java @@ -18,6 +18,9 @@ class GameSessionCanonicalInstanceLaunchRepositoryTest { @AfterEach void clearAmbientState() { TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } } @Test @@ -85,6 +88,73 @@ void refusesToReadInsideAnExistingOwnerTransactionBeforeStorage() { verifyNoInteractions(dsl, transactionManager); } + @Test + void originalTupleReadRequiresAnIndependentSnapshotBeforeInspectingInputs() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var catalogs = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE); + var repository = + new GameSessionCanonicalInstanceLaunchRepository( + dsl, transactionManager, NAMESPACE, catalogs); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.readByOriginalTuple(null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent transaction"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void originalTupleReadRejectsAmbientSynchronizationBeforeInspectingInputs() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var catalogs = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE); + var repository = + new GameSessionCanonicalInstanceLaunchRepository( + dsl, transactionManager, NAMESPACE, catalogs); + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy(() -> repository.readByOriginalTuple(null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("independent owner synchronization"); + + verifyNoInteractions(dsl, transactionManager); + } + + @Test + void originalTupleReadRejectsForeignNamespaceBeforeOpeningSnapshot() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + var catalogs = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE); + var repository = + new GameSessionCanonicalInstanceLaunchRepository( + dsl, transactionManager, NAMESPACE, catalogs); + var selector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + "other", + UUID.randomUUID(), + "world", + UUID.randomUUID(), + "operation", + "descriptor", + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + + assertThatThrownBy(() -> repository.readByOriginalTuple(selector, null)) + .isInstanceOf( + GameSessionCanonicalInstanceLaunchRepository.InvalidCanonicalInstanceLaunchException + .class) + .hasMessageContaining("differs from the configured"); + + verifyNoInteractions(dsl, transactionManager); + } + @Test void rejectsSelectorForAnotherNamespaceBeforeOpeningReadTransaction() { DSLContext dsl = mock(DSLContext.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionLaunchReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionLaunchReadGrpcServiceTest.java new file mode 100644 index 0000000000..60cba6d3ff --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionLaunchReadGrpcServiceTest.java @@ -0,0 +1,302 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.AdditionalMatchers.aryEq; +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.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionLaunchReadGrpcService; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionLaunchRequest; +import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionLaunchResponse; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Mocked owner dispatch proof; independent owner storage and authenticated mTLS remain separate. + */ +class OriginalStartSessionLaunchReadGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); + private static final UUID GAME_INSTANCE = uuid("02222222-2222-4222-8222-222222222222"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final GameSessionCanonicalInstanceLaunchRepository repository = + mock(GameSessionCanonicalInstanceLaunchRepository.class); + private final OriginalStartSessionLaunchReadGrpcService service = + new OriginalStartSessionLaunchReadGrpcService(repository, NAMESPACE); + + @AfterEach + void clearAmbientState() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void missingPeerRejectsMalformedInputBeforeStorage() { + var observer = new RecordingObserver(); + Context.ROOT.run( + () -> + service.readOriginalStartSessionLaunch( + ReadOriginalStartSessionLaunchRequest.getDefaultInstance(), observer)); + assertDenied(observer, Status.Code.UNAUTHENTICATED); + verifyNoInteractions(repository); + } + + @Test + void onlyExactSameNamespaceAccountWithoutEndUserContextIsAccepted() { + for (String uri : + List.of( + "spiffe://firemud/ns/world-runtime/sa/world-management-service", + "spiffe://firemud/ns/other-runtime/sa/account-service")) { + assertDenied( + invoke(uri, ReadOriginalStartSessionLaunchRequest.getDefaultInstance()), + Status.Code.PERMISSION_DENIED); + } + SessionContext.setContext("42", List.of("tenantAdmin"), Map.of()); + assertDenied(invokeAccount(wire(request(NAMESPACE))), Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + } + + @Test + void malformedAndUnknownRequestsFailBeforeOwnerStorage() { + var valid = wire(request(NAMESPACE)); + var unknown = + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertDenied( + invokeAccount(ReadOriginalStartSessionLaunchRequest.getDefaultInstance()), + Status.Code.INVALID_ARGUMENT); + assertDenied(invokeAccount(unknown), Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(repository); + } + + @Test + void configuredNamespaceAndAmbientSynchronizationAreRejectedBeforeOwnerStorage() { + assertDenied(invokeAccount(wire(request("other-runtime"))), Status.Code.PERMISSION_DENIED); + + TransactionSynchronizationManager.initSynchronization(); + assertDenied(invokeAccount(wire(request(NAMESPACE))), Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(repository); + } + + @Test + void exactTupleIsForwardedAndMissingOwnerAssociationDoesNotBecomeEvidence() { + var request = request(NAMESPACE); + when(repository.readByOriginalTuple( + eq(request.selector()), aryEq(request.originalPostAuthorizationTupleBytes()))) + .thenReturn(Optional.empty()); + + assertDenied(invokeAccount(wire(request)), Status.Code.FAILED_PRECONDITION); + + verify(repository) + .readByOriginalTuple( + eq(request.selector()), aryEq(request.originalPostAuthorizationTupleBytes())); + } + + @Test + void storageFailureCannotManufactureAnOwnerReadback() { + var request = request(NAMESPACE); + when(repository.readByOriginalTuple( + eq(request.selector()), aryEq(request.originalPostAuthorizationTupleBytes()))) + .thenThrow(new DataAccessException("test-only owner storage failure")); + + assertDenied(invokeAccount(wire(request)), Status.Code.UNAVAILABLE); + verify(repository) + .readByOriginalTuple( + eq(request.selector()), aryEq(request.originalPostAuthorizationTupleBytes())); + } + + private RecordingObserver invokeAccount(ReadOriginalStartSessionLaunchRequest wire) { + return invoke("spiffe://firemud/ns/world-runtime/sa/account-service", wire); + } + + private RecordingObserver invoke(String uri, ReadOriginalStartSessionLaunchRequest wire) { + var observer = new RecordingObserver(); + var peer = GrpcPeerIdentity.parseUri(uri).orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> service.readOriginalStartSessionLaunch(wire, observer)); + return observer; + } + + private static OriginalStartSessionLaunchReadEvidence.Request request(String namespace) { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(namespace); + var selector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + READ_ID, + namespace, + TENANT, + "world", + GAME_INSTANCE, + tuple.controlPlaneRequestId(), + "launch-descriptor", + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + return new OriginalStartSessionLaunchReadEvidence.Request(selector, tuple.canonicalBytes()); + } + + private static ReadOriginalStartSessionLaunchRequest wire( + OriginalStartSessionLaunchReadEvidence.Request request) { + return OriginalStartSessionLaunchReadGrpcCodec.toRequest(request); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String namespace) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "original-launch-read-service-test", + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact Account original launch read")); + String tenant = TENANT.toString(); + Map bundle = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenant, "targetNamespace", namespace), + "actionFamily", pre.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenant), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "d".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", pre.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + pre.controlPlaneRequestId()), + "mutationDigest", pre.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenant, 3L), + "membershipAuthorityGeneration", Map.of(tenant, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenant, 5L), + "issuanceFence", "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + byte[] authorityBytes; + try { + authorityBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + authorityBytes, + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static void assertDenied(RecordingObserver observer, Status.Code expected) { + assertThat(observer.response).isNull(); + assertThat(observer.completed).isFalse(); + assertThat(observer.error).isEqualTo(expected); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class RecordingObserver + implements StreamObserver { + private ReadOriginalStartSessionLaunchResponse response; + private Status.Code error; + private boolean completed; + + @Override + public void onNext(ReadOriginalStartSessionLaunchResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java index 74d5c02b8a..89748351dc 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java @@ -3,12 +3,18 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Connection; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import java.util.Arrays; import java.util.HexFormat; import java.util.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.transaction.PlatformTransactionManager; @@ -52,93 +58,790 @@ public Optional readResult( readTransaction.execute( status -> { requireReadOnlyRepeatableReadTransaction(); + // The old request-only transport path may replay retained V43 proofs, but it must + // not disclose a new V65 protected terminal without the exact Account protection + // identity that binds the receipt. + if (dsl.fetchOne( + "SELECT 1 FROM world_canonical_instance_activation_fence " + + "WHERE activation_request_id=?", + request.activationRequestId()) + != null) { + return null; + } return readResultInCurrentTransaction(request).orElse(null); })); } /** - * Commits one exact PREPARING-to-ACTIVE CAS or stores a terminal stale-precondition result. The - * caller has already verified remote/current authorities outside this transaction. + * Exact historical terminal lookup for Account settlement. Pending, absent, or legacy V43-only + * operation rows are deliberately not returned as activation-terminal proof. */ - public WorldCanonicalInstanceActivation.Result activate( - WorldCanonicalInstanceActivation.Request request, + public Optional readTerminalEvidence( + AccountStartSessionActivationProtectionEvidence protection) { + Objects.requireNonNull(protection, "protection"); + requireNoActiveTransaction("World original StartSession activation terminal read"); + return Optional.ofNullable( + readTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + Record row = + activationFence( + protection.request().worldActivationRequest().activationRequestId()); + if (row == null) return null; + requireSameProtectionIdentity(row, protection); + String state = required(row, "operation_state", String.class); + if ("PENDING".equals(state)) return null; + byte[] terminalBytes = required(row, "terminal_evidence_bytes", byte[].class); + if (!required(row, "terminal_evidence_digest", String.class) + .equals(digest(terminalBytes))) { + throw new InvalidActivationEvidenceException( + "Stored original StartSession activation terminal digest is inconsistent"); + } + try { + WorldOriginalStartSessionActivationTerminalEvidence terminal = + WorldOriginalStartSessionActivationTerminalEvidence.decode(terminalBytes); + if (terminal.worldActivationFence() + != required(row, "world_activation_fence", Long.class) + || !terminal + .activationRequestId() + .equals(protection.request().worldActivationRequest().activationRequestId()) + || !terminal + .accountProtectionEvidence() + .requestDigest() + .equals(protection.requestDigest()) + || !terminal.outcome().name().equals(state)) { + throw new InvalidActivationEvidenceException( + "Stored World activation terminal differs from its durable operation fence"); + } + return terminal; + } catch (IllegalArgumentException invalid) { + throw new InvalidActivationEvidenceException( + "Stored World activation terminal evidence is invalid", invalid); + } + })); + } + + /** + * Read-only terminal-first recovery for an exact caller acquisition statement. This lookup does + * not acquire Account authority, check lease currentness, or restart a PENDING operation. + * Correlation IDs normalized by the activation request identity remain those of the first stored + * protection receipt and terminal result. + */ + public Optional readProtectedActivationByAcquisitionInput( + AccountStartSessionActivationProtectionAcquisitionInput input) { + Objects.requireNonNull(input, "activation protection acquisition input"); + requireNoActiveTransaction("World protected activation recovery read"); + return Optional.ofNullable( + readTransaction.execute( + status -> { + requireReadOnlyRepeatableReadTransaction(); + var activation = input.worldActivationRequest(); + UUID activationId = activation.activationRequestId(); + UUID gameInstanceId = activation.canonicalGameInstanceId(); + Record row = + dsl.fetchOne( + "SELECT * FROM world_canonical_instance_activation_fence " + + "WHERE activation_request_id=? OR canonical_game_instance_id=?", + activationId, + gameInstanceId); + if (row != null) { + byte[] firstEvidenceBytes = + required(row, "account_protection_evidence_bytes", byte[].class); + if (!required(row, "account_protection_evidence_digest", String.class) + .equals(digest(firstEvidenceBytes))) { + throw new InvalidActivationEvidenceException( + "Stored Account activation protection digest is inconsistent"); + } + AccountStartSessionActivationProtectionEvidence firstProtection; + try { + firstProtection = + AccountStartSessionActivationProtectionEvidence.decode(firstEvidenceBytes); + } catch (IllegalArgumentException invalid) { + throw new InvalidActivationEvidenceException( + "Stored Account activation protection is invalid", invalid); + } + requireSameProtectionIdentity(row, firstProtection); + requireSameAcquisitionInput(input, firstProtection); + String state = required(row, "operation_state", String.class); + if ("PENDING".equals(state)) return ProtectedActivationReadback.pendingReadback(); + byte[] terminalBytes = required(row, "terminal_evidence_bytes", byte[].class); + if (!required(row, "terminal_evidence_digest", String.class) + .equals(digest(terminalBytes))) { + throw new InvalidActivationEvidenceException( + "Stored World activation terminal digest is inconsistent"); + } + WorldOriginalStartSessionActivationTerminalEvidence terminal = + decodeTerminal(terminalBytes); + byte[] resultBytes = required(row, "terminal_result_bytes", byte[].class); + if (!required(row, "terminal_result_digest", String.class) + .equals(digest(resultBytes))) { + throw new InvalidActivationEvidenceException( + "Stored World activation result digest is inconsistent"); + } + if (!Arrays.equals( + firstProtection.canonicalBytes(), + terminal.accountProtectionEvidence().canonicalBytes()) + || !Arrays.equals(resultBytes, terminal.activationResult().canonicalBytes()) + || !terminal.activationRequestId().equals(activationId) + || !terminal.outcome().name().equals(state) + || terminal.worldActivationFence() + != required(row, "world_activation_fence", Long.class)) { + throw new InvalidActivationEvidenceException( + "Stored World terminal differs from its original protected activation"); + } + return ProtectedActivationReadback.terminal(terminal); + } + + // V43-only results are retained history, not upgradeable protected receipts. Fail + // locally before asking Account to create a new protection operation. + if (dsl.fetchOne( + "SELECT 1 FROM world_canonical_instance_activation_operation " + + "WHERE activation_request_id=? " + + "OR (canonical_game_instance_id=? AND outcome='COMMITTED')", + activationId, + gameInstanceId) + != null) { + throw new ActivationConflictException( + "A retained legacy World activation result cannot be upgraded to protected activation"); + } + return null; + })); + } + + static void requireSameAcquisitionInput( + AccountStartSessionActivationProtectionAcquisitionInput input, + AccountStartSessionActivationProtectionEvidence protection) { + var request = protection.request(); + var activation = request.worldActivationRequest(); + var requestedActivation = input.worldActivationRequest(); + if (!Arrays.equals( + input.originalPostAuthorizationTuple(), request.originalPostAuthorizationTupleBytes()) + || !input.gameSessionOwnerMutationId().equals(request.gameSessionOwnerMutationId()) + || !input.gameSessionOwnerAttemptId().equals(request.gameSessionOwnerAttemptId()) + || input.gameSessionOwnerFence() != request.gameSessionOwnerFence() + || !requestedActivation.activationRequestId().equals(activation.activationRequestId()) + || !Arrays.equals( + requestedActivation.canonicalRequestBytes(), activation.canonicalRequestBytes())) { + throw new ActivationConflictException( + "World activation retry changed its exact original caller acquisition statement"); + } + } + + /** Result of a terminal-first lookup; a PENDING value must never trigger fresh acquisition. */ + public record ProtectedActivationReadback( + boolean pending, WorldOriginalStartSessionActivationTerminalEvidence terminalEvidence) { + public ProtectedActivationReadback { + if (pending == (terminalEvidence != null)) { + throw new IllegalArgumentException( + "Protected activation readback must be exactly PENDING or a full terminal receipt"); + } + } + + private static ProtectedActivationReadback pendingReadback() { + return new ProtectedActivationReadback(true, null); + } + + private static ProtectedActivationReadback terminal( + WorldOriginalStartSessionActivationTerminalEvidence terminalEvidence) { + return new ProtectedActivationReadback(false, Objects.requireNonNull(terminalEvidence)); + } + } + + /** + * Retains the exact first Account activation-protection receipt before attempting the lifecycle + * CAS. Replays compare stable identity (which normalizes only owner-read correlations) and never + * replace the first receipt. + */ + private ActivationIntent beginProtectedActivation( + AccountStartSessionActivationProtectionEvidence protection) { + return writeTransaction.execute( + status -> { + requireWritableTransaction(); + lockActivationOperation(protection); + UUID activationId = protection.request().worldActivationRequest().activationRequestId(); + Record prior = activationFenceForUpdate(activationId); + if (prior != null) { + requireSameProtectionIdentity(prior, protection); + return intent(prior, false); + } + requireNoLegacyActivationResult(protection); + requireLocalProtectedActivationBinding(protection, true); + Record inserted = insertActivationFence(protection); + return intent( + Objects.requireNonNull(inserted, "World activation fence insert returned no row"), + true); + }); + } + + /** + * Creates or completes one protected initial activation. The Account protection remains pending + * until its caller consumes the exact returned terminal through Account's authenticated owner + * settlement path; this repository does not release it. + */ + public WorldOriginalStartSessionActivationTerminalEvidence activateProtected( + AccountStartSessionActivationProtectionEvidence protection, WorldCanonicalInstanceActivationService.HeldActivationAuthority held) { - Objects.requireNonNull(request, "request"); + Objects.requireNonNull(protection, "protection"); Objects.requireNonNull(held, "held"); - requireNoActiveTransaction("World canonical activation"); - return writeTransaction.execute( + requireNoActiveTransaction("World protected canonical activation"); + ActivationIntent intent = beginProtectedActivation(protection); + if (!"PENDING".equals(intent.operationState())) { + return decodeTerminal(intent.terminalEvidenceBytes()); + } + if (!intent.createdByThisInvocation()) { + throw new WorldCanonicalInstanceActivationService.ActivationDeniedException( + "An existing pending World activation intent cannot be restarted; only exact terminal readback or a positive fenced abort may continue"); + } + AccountStartSessionActivationProtectionEvidence firstProtection = + AccountStartSessionActivationProtectionEvidence.decode( + intent.accountProtectionEvidenceBytes()); + WorldCanonicalInstanceActivation.Request request = + firstProtection.request().worldActivationRequest(); + try { + writeTransaction.execute( + status -> { + requireWritableTransaction(); + held.requireHeld(); + lockActivationOperation(firstProtection); + Record fence = activationFenceForUpdate(request.activationRequestId()); + if (fence == null) { + throw new InvalidActivationEvidenceException( + "Protected World activation lost its durable operation fence"); + } + requireSameProtectionIdentity(fence, firstProtection); + String state = required(fence, "operation_state", String.class); + if (!"PENDING".equals(state)) return null; + + WorldCanonicalInstanceLifecycleEvidence current = + lifecycleRepository + .readForActivationInOwnerTransaction(request.preparing().request()) + .orElseThrow( + () -> + new ActivationConflictException( + "Protected World activation no longer has its exact materialized owner association")); + requireLocalProtectedActivationBinding( + firstProtection, false, required(fence, "world_execution_fence", Long.class)); + requireLeaseStillValidAfterLocalLockWait(fence); + + Optional oldResult = + readResultInCurrentTransaction(request); + if (oldResult.isPresent()) { + throw new ActivationConflictException( + "A legacy or independently terminal World activation result cannot be upgraded to Account-protected proof"); + } + boolean exactPrecondition = exactPreparingPrecondition(request, current); + if (!exactPrecondition) { + WorldCanonicalInstanceActivation.Result aborted = + new WorldCanonicalInstanceActivation.Result( + request, + WorldCanonicalInstanceActivation.Outcome.ABORTED, + "PRECONDITION_FAILED", + current); + insertResult(request, aborted); + completeActivationFence( + fence, + firstProtection, + aborted, + WorldCanonicalInstanceActivation.Outcome.ABORTED); + held.requireHeld(); + return null; + } + + WorldCanonicalInstanceLifecycleEvidence predicted = + nextActiveEvidence(request, current); + WorldCanonicalInstanceActivation.Result committed = + new WorldCanonicalInstanceActivation.Result( + request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, predicted); + insertResult(request, committed); + held.requireHeld(); + int updated = + dsl.execute( + "UPDATE world_instance SET status='ACTIVE', lifecycle_epoch=lifecycle_epoch+1, " + + "row_version=row_version+1, updated_at=clock_timestamp() " + + "WHERE id=(SELECT world_instance_id FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=? AND schema_version=2 " + + "AND canonical_realm_id=? AND catalog_revision=?) " + + "AND canonical_game_instance_id=? AND canonical_realm_id=? AND catalog_revision=? " + + "AND status='PREPARING' AND lifecycle_epoch=? AND row_version=?", + request.canonicalGameInstanceId(), + firstProtection + .request() + .gameSessionLaunchReadEvidence() + .launch() + .canonicalRealmId(), + firstProtection + .request() + .gameSessionLaunchReadEvidence() + .launch() + .catalogRevision(), + request.canonicalGameInstanceId(), + firstProtection + .request() + .gameSessionLaunchReadEvidence() + .launch() + .canonicalRealmId(), + firstProtection + .request() + .gameSessionLaunchReadEvidence() + .launch() + .catalogRevision(), + request.expectedLifecycleEpoch(), + request.expectedRowVersion()); + if (updated != 1) { + throw new ActivationConflictException( + "Protected World lifecycle changed before its exact activation compare-and-set"); + } + WorldCanonicalInstanceLifecycleEvidence actual = + lifecycleRepository + .readForActivationInOwnerTransaction(request.preparing().request()) + .orElseThrow( + () -> + new InvalidActivationEvidenceException( + "Protected World activation lost its owner readback")); + if (!Arrays.equals(predicted.canonicalBytes(), actual.canonicalBytes())) { + throw new InvalidActivationEvidenceException( + "Protected World activation result differs from its exact committed owner readback"); + } + completeActivationFence( + fence, + firstProtection, + committed, + WorldCanonicalInstanceActivation.Outcome.COMMITTED); + held.requireHeld(); + return null; + }); + } catch (RuntimeException outcomeUncertain) { + Optional terminal = + readTerminalEvidence(protection); + if (terminal.isPresent()) return terminal.orElseThrow(); + throw outcomeUncertain; + } + return readTerminalEvidence(protection) + .orElseThrow( + () -> + new InvalidActivationEvidenceException( + "Protected World activation transaction committed without exact terminal readback")); + } + + /** + * Positively fences an activation as ABORTED under the same operation and lifecycle locks used by + * activation. It is not called for timeout, expiry, missing evidence, or a failed owner read. + */ + public WorldOriginalStartSessionActivationTerminalEvidence abortProtected( + AccountStartSessionActivationProtectionEvidence protection, String terminalCode) { + Objects.requireNonNull(protection, "protection"); + requireTerminalCode(terminalCode); + requireNoActiveTransaction("World protected canonical activation abort"); + writeTransaction.execute( status -> { requireWritableTransaction(); - held.requireHeld(); + lockActivationOperation(protection); + UUID activationId = protection.request().worldActivationRequest().activationRequestId(); + Record fence = activationFenceForUpdate(activationId); + if (fence == null) { + requireNoLegacyActivationResult(protection); + requireLocalProtectedActivationBinding(protection, false); + fence = insertActivationFence(protection); + } else { + requireSameProtectionIdentity(fence, protection); + } + if (!"PENDING".equals(required(fence, "operation_state", String.class))) return null; + WorldCanonicalInstanceActivation.Request request = + AccountStartSessionActivationProtectionEvidence.decode( + required(fence, "account_protection_evidence_bytes", byte[].class)) + .request() + .worldActivationRequest(); WorldCanonicalInstanceLifecycleEvidence current = lifecycleRepository .readForActivationInOwnerTransaction(request.preparing().request()) .orElseThrow( () -> new ActivationConflictException( - "Canonical World activation no longer has its exact materialized owner association")); - Optional existing = + "Cannot fence activation without exact current World lifecycle evidence")); + requireLocalProtectedActivationBinding( + AccountStartSessionActivationProtectionEvidence.decode( + required(fence, "account_protection_evidence_bytes", byte[].class)), + false, + required(fence, "world_execution_fence", Long.class)); + Optional oldResult = readResultInCurrentTransaction(request); - if (existing.isPresent()) return existing.orElseThrow(); - - boolean exactPrecondition = - "PREPARING".equals(current.lifecycleStatus()) - && current.lifecycleEpoch() == request.expectedLifecycleEpoch() - && current.rowVersion() == request.expectedRowVersion() - && Arrays.equals( - request.canonicalRequestBytes(), - new WorldCanonicalInstanceActivation.Request( - request.activationRequestId(), current) - .canonicalRequestBytes()); - if (!exactPrecondition) { - WorldCanonicalInstanceActivation.Result aborted = - new WorldCanonicalInstanceActivation.Result( - request, - WorldCanonicalInstanceActivation.Outcome.ABORTED, - "PRECONDITION_FAILED", - current); - insertResult(request, aborted); - held.requireHeld(); - return aborted; - } - - WorldCanonicalInstanceLifecycleEvidence predicted = nextActiveEvidence(request, current); - WorldCanonicalInstanceActivation.Result committed = - new WorldCanonicalInstanceActivation.Result( - request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, predicted); - insertResult(request, committed); - held.requireHeld(); - int updated = - dsl.execute( - "UPDATE world_instance SET status='ACTIVE', lifecycle_epoch=lifecycle_epoch+1, " - + "row_version=row_version+1, updated_at=CURRENT_TIMESTAMP " - + "WHERE id=(SELECT world_instance_id FROM world_canonical_instance_association " - + "WHERE canonical_game_instance_id=?) AND canonical_game_instance_id=? " - + "AND status='PREPARING' AND lifecycle_epoch=? AND row_version=?", - request.canonicalGameInstanceId(), - request.canonicalGameInstanceId(), - request.expectedLifecycleEpoch(), - request.expectedRowVersion()); - if (updated != 1) { + if (oldResult.isPresent()) { throw new ActivationConflictException( - "Canonical World lifecycle changed before its exact activation compare-and-set"); + "Existing unprotected World activation result cannot be converted into a fenced abort"); } - WorldCanonicalInstanceLifecycleEvidence actual = - lifecycleRepository - .readForActivationInOwnerTransaction(request.preparing().request()) - .orElseThrow( - () -> - new InvalidActivationEvidenceException( - "Canonical World activation lost its owner readback")); - if (!Arrays.equals(predicted.canonicalBytes(), actual.canonicalBytes())) { - throw new InvalidActivationEvidenceException( - "Canonical World activation result differs from its exact committed owner readback"); - } - held.requireHeld(); - return committed; + WorldCanonicalInstanceActivation.Result aborted = + new WorldCanonicalInstanceActivation.Result( + request, WorldCanonicalInstanceActivation.Outcome.ABORTED, terminalCode, current); + insertResult(request, aborted); + completeActivationFence( + fence, + AccountStartSessionActivationProtectionEvidence.decode( + required(fence, "account_protection_evidence_bytes", byte[].class)), + aborted, + WorldCanonicalInstanceActivation.Outcome.ABORTED); + return null; }); + return readTerminalEvidence(protection) + .orElseThrow( + () -> + new InvalidActivationEvidenceException( + "Serialized World activation abort committed without exact terminal readback")); } + /** + * Commits one exact PREPARING-to-ACTIVE CAS or stores a terminal stale-precondition result. The + * caller has already verified remote/current authorities outside this transaction. + */ + public WorldCanonicalInstanceActivation.Result activate( + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceActivationService.HeldActivationAuthority held) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(held, "held"); + requireNoActiveTransaction("World canonical activation"); + throw new WorldCanonicalInstanceActivationService.ActivationDeniedException( + "Fresh canonical activation requires complete Account activation-purpose protection evidence"); + } + + private Record activationFence(UUID activationRequestId) { + return dsl.fetchOne( + "SELECT * FROM world_canonical_instance_activation_fence WHERE activation_request_id=?", + activationRequestId); + } + + private Record activationFenceForUpdate(UUID activationRequestId) { + return dsl.fetchOne( + "SELECT * FROM world_canonical_instance_activation_fence WHERE activation_request_id=? FOR UPDATE", + activationRequestId); + } + + private static ActivationIntent intent(Record row, boolean createdByThisInvocation) { + return new ActivationIntent( + required(row, "world_activation_fence", Long.class), + required(row, "operation_state", String.class), + required(row, "account_protection_evidence_bytes", byte[].class), + row.get("terminal_evidence_bytes", byte[].class), + createdByThisInvocation); + } + + private Record insertActivationFence(AccountStartSessionActivationProtectionEvidence protection) { + var request = protection.request(); + var worldRequest = request.worldActivationRequest(); + var scope = worldRequest.preparing().request(); + var launch = request.gameSessionLaunchReadEvidence().launch(); + byte[] accountBytes = protection.canonicalBytes(); + byte[] tupleBytes = request.originalPostAuthorizationTupleBytes(); + byte[] preparingBytes = worldRequest.preparingEvidenceBytes(); + Record inserted = + dsl.fetchOne( + "INSERT INTO world_canonical_instance_activation_fence (" + + "activation_request_id,protection_operation_digest,account_protection_id,account_protection_fence," + + "account_protection_evidence_bytes,account_protection_evidence_digest,source_capture_reference_digest," + + "target_namespace,canonical_tenant_id,control_plane_request_id,canonical_world_slug,canonical_game_instance_id," + + "original_post_authorization_tuple,account_world_participation_id,account_world_participation_fence," + + "game_session_owner_mutation_id,game_session_owner_attempt_id,game_session_owner_fence," + + "original_game_session_lease_expires_at,canonical_realm_id,catalog_revision," + + "expected_lifecycle_epoch,expected_row_version,preparing_evidence_bytes,world_execution_fence," + + "world_instance_id,world_activation_fence,operation_state) " + + "SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?," + + "e.world_execution_fence,e.world_instance_id," + + "nextval('world_canonical_instance_activation_fence_seq'),'PENDING' " + + "FROM world_canonical_instance_execution e " + + "JOIN world_canonical_instance_association a ON a.canonical_game_instance_id=e.canonical_game_instance_id " + + "JOIN world_instance w ON w.id=a.world_instance_id " + + "JOIN world_canonical_instance_preparation p ON p.canonical_game_instance_id=a.canonical_game_instance_id " + + "WHERE e.target_namespace=? AND e.canonical_tenant_id=? AND e.control_plane_request_id=? " + + "AND e.canonical_world_slug=? " + + "AND e.canonical_game_instance_id=? AND e.original_post_authorization_tuple=? " + + "AND e.account_world_participation_id=? AND e.account_world_participation_fence=? " + + "AND e.game_session_owner_mutation_id=? AND e.game_session_owner_attempt_id=? " + + "AND e.game_session_owner_fence=? AND e.original_game_session_lease_expires_at=? " + + "AND e.operation_state='COMMITTED' AND e.world_instance_id=w.id " + + "AND a.schema_version=2 AND a.canonical_realm_id=? AND a.catalog_revision=? " + + "AND w.canonical_realm_id=a.canonical_realm_id AND w.catalog_revision=a.catalog_revision " + + "AND p.input_digest=e.preparation_input_digest AND p.input_digest=? " + + "AND p.input_json::jsonb->'identity'->>'canonicalRealmId'=a.canonical_realm_id::text " + + "AND p.input_json::jsonb->'identity'->>'catalogRevision'=a.catalog_revision::text " + + "ON CONFLICT DO NOTHING " + + "RETURNING *", + worldRequest.activationRequestId(), + protection.requestDigest(), + protection.accountProtectionId(), + protection.accountProtectionFence(), + accountBytes, + digest(accountBytes), + protection.originalSourceCaptureReferenceSha256(), + scope.targetNamespace(), + scope.canonicalTenantId(), + scope.controlPlaneRequestId(), + scope.worldSlug(), + worldRequest.canonicalGameInstanceId(), + tupleBytes, + request.accountWorldParticipationId(), + request.accountWorldParticipationFence(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + OffsetDateTime.ofInstant(request.originalLeaseExpiresAt(), ZoneOffset.UTC), + launch.canonicalRealmId(), + launch.catalogRevision(), + worldRequest.expectedLifecycleEpoch(), + worldRequest.preparing().rowVersion(), + preparingBytes, + scope.targetNamespace(), + scope.canonicalTenantId(), + scope.controlPlaneRequestId(), + scope.worldSlug(), + worldRequest.canonicalGameInstanceId(), + tupleBytes, + request.accountWorldParticipationId(), + request.accountWorldParticipationFence(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + OffsetDateTime.ofInstant(request.originalLeaseExpiresAt(), ZoneOffset.UTC), + launch.canonicalRealmId(), + launch.catalogRevision(), + worldRequest.preparing().preparationInputDigest()); + if (inserted == null) { + throw new ActivationConflictException( + "Another activation operation already owns this canonical instance, or the proof does not match the committed original execution, schema-2 owner association, realm/catalog, or preparation"); + } + return inserted; + } + + private void lockActivationOperation(AccountStartSessionActivationProtectionEvidence protection) { + var request = protection.request(); + var world = request.worldActivationRequest(); + var scope = world.preparing().request(); + dsl.fetchOne( + "SELECT world_lock_canonical_instance_execution(?,?,?,?)", + scope.targetNamespace(), + scope.canonicalTenantId(), + scope.controlPlaneRequestId(), + scope.canonicalGameInstanceId()); + } + + private void requireSameProtectionIdentity( + Record row, AccountStartSessionActivationProtectionEvidence protection) { + byte[] firstBytes = required(row, "account_protection_evidence_bytes", byte[].class); + if (!required(row, "protection_operation_digest", String.class) + .equals(protection.requestDigest()) + || !required(row, "account_protection_id", UUID.class) + .equals(protection.accountProtectionId()) + || required(row, "account_protection_fence", Long.class) + != protection.accountProtectionFence() + || !required(row, "account_protection_evidence_digest", String.class) + .equals(digest(firstBytes))) { + throw new ActivationConflictException( + "World activation identity is already bound to different Account protection evidence"); + } + try { + var first = AccountStartSessionActivationProtectionEvidence.decode(firstBytes); + if (!Arrays.equals(first.operationIdentityBytes(), protection.operationIdentityBytes()) + || !first.acquiredAt().equals(protection.acquiredAt()) + || !first + .originalSourceCaptureReferenceSha256() + .equals(protection.originalSourceCaptureReferenceSha256()) + || !Arrays.equals( + first.originalSourceCaptureReferenceBytes(), + protection.originalSourceCaptureReferenceBytes()) + || !sameSourceEvidenceVector(first, protection) + || !first.requestDigest().equals(protection.requestDigest()) + || !Arrays.equals( + first.request().worldActivationRequest().canonicalRequestBytes(), + protection.request().worldActivationRequest().canonicalRequestBytes())) { + throw new ActivationConflictException( + "World activation retry changed its original protection or activation identity"); + } + } catch (IllegalArgumentException invalid) { + throw new InvalidActivationEvidenceException( + "Stored original Account activation protection is invalid", invalid); + } + } + + private static boolean sameSourceEvidenceVector( + AccountStartSessionActivationProtectionEvidence first, + AccountStartSessionActivationProtectionEvidence retry) { + var firstSources = first.sourceEvidenceVector(); + var retrySources = retry.sourceEvidenceVector(); + if (firstSources.size() != retrySources.size()) return false; + for (int index = 0; index < firstSources.size(); index++) { + if (!Arrays.equals( + firstSources.get(index).canonicalBytes(), retrySources.get(index).canonicalBytes())) { + return false; + } + } + return true; + } + + private void requireNoLegacyActivationResult( + AccountStartSessionActivationProtectionEvidence protection) { + UUID activationId = protection.request().worldActivationRequest().activationRequestId(); + UUID gameInstanceId = protection.request().worldActivationRequest().canonicalGameInstanceId(); + if (dsl.fetchOne( + "SELECT 1 FROM world_canonical_instance_activation_operation " + + "WHERE activation_request_id=? OR (canonical_game_instance_id=? AND outcome='COMMITTED')", + activationId, + gameInstanceId) + != null) { + throw new ActivationConflictException( + "A retained legacy or independently committed World activation cannot be upgraded to Account-protected activation"); + } + } + + private void requireLocalProtectedActivationBinding( + AccountStartSessionActivationProtectionEvidence protection, boolean requireLiveLease) { + requireLocalProtectedActivationBinding(protection, requireLiveLease, null); + } + + private void requireLocalProtectedActivationBinding( + AccountStartSessionActivationProtectionEvidence protection, + boolean requireLiveLease, + Long expectedWorldExecutionFence) { + var request = protection.request(); + var world = request.worldActivationRequest(); + var scope = world.preparing().request(); + var launch = request.gameSessionLaunchReadEvidence().launch(); + Record row = + dsl.fetchOne( + "SELECT e.world_execution_fence,e.original_game_session_lease_expires_at " + + "FROM world_canonical_instance_execution e " + + "JOIN world_canonical_instance_association a ON a.canonical_game_instance_id=e.canonical_game_instance_id " + + "JOIN world_instance w ON w.id=a.world_instance_id " + + "JOIN world_canonical_instance_preparation p ON p.canonical_game_instance_id=a.canonical_game_instance_id " + + "WHERE e.target_namespace=? AND e.canonical_tenant_id=? AND e.control_plane_request_id=? " + + "AND e.canonical_world_slug=? " + + "AND e.canonical_game_instance_id=? AND e.original_post_authorization_tuple=? " + + "AND e.account_world_participation_id=? AND e.account_world_participation_fence=? " + + "AND e.game_session_owner_mutation_id=? AND e.game_session_owner_attempt_id=? " + + "AND e.game_session_owner_fence=? AND e.original_game_session_lease_expires_at=? " + + "AND e.operation_state='COMMITTED' AND e.world_instance_id=w.id " + + "AND a.schema_version=2 AND a.canonical_realm_id=? AND a.catalog_revision=? " + + "AND w.canonical_realm_id=a.canonical_realm_id AND w.catalog_revision=a.catalog_revision " + + "AND p.input_digest=e.preparation_input_digest AND p.input_digest=? " + + "AND p.input_json::jsonb->'identity'->>'canonicalRealmId'=a.canonical_realm_id::text " + + "AND p.input_json::jsonb->'identity'->>'catalogRevision'=a.catalog_revision::text", + scope.targetNamespace(), + scope.canonicalTenantId(), + scope.controlPlaneRequestId(), + scope.worldSlug(), + scope.canonicalGameInstanceId(), + request.originalPostAuthorizationTupleBytes(), + request.accountWorldParticipationId(), + request.accountWorldParticipationFence(), + request.gameSessionOwnerMutationId(), + request.gameSessionOwnerAttemptId(), + request.gameSessionOwnerFence(), + OffsetDateTime.ofInstant(request.originalLeaseExpiresAt(), ZoneOffset.UTC), + launch.canonicalRealmId(), + launch.catalogRevision(), + world.preparing().preparationInputDigest()); + if (row == null) { + throw new ActivationConflictException( + "Account activation protection differs from the exact committed World execution, schema-2 local realm/catalog association, or preparation"); + } + if (expectedWorldExecutionFence != null + && required(row, "world_execution_fence", Long.class).longValue() + != expectedWorldExecutionFence.longValue()) { + throw new ActivationConflictException( + "World activation intent differs from the durable original execution fence"); + } + if (requireLiveLease) requireLeaseStillValid(row); + } + + private void requireLeaseStillValidAfterLocalLockWait(Record fence) { + Record row = + dsl.fetchOne( + "SELECT clock_timestamp() < ?::timestamptz AS valid", + required(fence, "original_game_session_lease_expires_at", OffsetDateTime.class)); + if (row == null || !Boolean.TRUE.equals(required(row, "valid", Boolean.class))) { + throw new WorldCanonicalInstanceActivationService.ActivationDeniedException( + "Original Game Session lease expired before World activation admission; only exact readback or fenced abort may continue"); + } + } + + private void requireLeaseStillValid(Record ownerRow) { + Record row = + dsl.fetchOne( + "SELECT clock_timestamp() < ?::timestamptz AS valid", + required(ownerRow, "original_game_session_lease_expires_at", OffsetDateTime.class)); + if (row == null || !Boolean.TRUE.equals(required(row, "valid", Boolean.class))) { + throw new WorldCanonicalInstanceActivationService.ActivationDeniedException( + "Original Game Session lease expired before World activation intent retention"); + } + } + + private void completeActivationFence( + Record fence, + AccountStartSessionActivationProtectionEvidence firstProtection, + WorldCanonicalInstanceActivation.Result result, + WorldCanonicalInstanceActivation.Outcome outcome) { + WorldOriginalStartSessionActivationTerminalEvidence terminal = + WorldOriginalStartSessionActivationTerminalEvidence.create( + firstProtection, result, required(fence, "world_activation_fence", Long.class)); + byte[] resultBytes = result.canonicalBytes(); + byte[] terminalBytes = terminal.canonicalBytes(); + int changed = + dsl.execute( + "UPDATE world_canonical_instance_activation_fence SET operation_state=?, " + + "terminal_result_bytes=?, terminal_result_digest=?, terminal_evidence_bytes=?, " + + "terminal_evidence_digest=?, terminal_at=clock_timestamp() " + + "WHERE activation_request_id=? AND world_activation_fence=? AND operation_state='PENDING'", + outcome.name(), + resultBytes, + digest(resultBytes), + terminalBytes, + digest(terminalBytes), + result.request().activationRequestId(), + required(fence, "world_activation_fence", Long.class)); + if (changed != 1) { + throw new ActivationConflictException( + "World activation terminal fence changed before its immutable terminal write"); + } + } + + private static WorldOriginalStartSessionActivationTerminalEvidence decodeTerminal(byte[] bytes) { + if (bytes == null) { + throw new InvalidActivationEvidenceException( + "World activation fence is terminal without immutable terminal evidence"); + } + try { + return WorldOriginalStartSessionActivationTerminalEvidence.decode(bytes); + } catch (IllegalArgumentException invalid) { + throw new InvalidActivationEvidenceException( + "Stored World activation terminal evidence is invalid", invalid); + } + } + + private static boolean exactPreparingPrecondition( + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceLifecycleEvidence current) { + return "PREPARING".equals(current.lifecycleStatus()) + && current.lifecycleEpoch() == request.expectedLifecycleEpoch() + && current.rowVersion() == request.expectedRowVersion() + && Arrays.equals( + request.canonicalRequestBytes(), + new WorldCanonicalInstanceActivation.Request(request.activationRequestId(), current) + .canonicalRequestBytes()); + } + + private static void requireTerminalCode(String terminalCode) { + if (terminalCode == null + || terminalCode.isBlank() + || terminalCode.length() > 64 + || !terminalCode.equals(terminalCode.trim())) { + throw new IllegalArgumentException( + "World activation terminal code must be 1 to 64 trimmed characters"); + } + } + + private record ActivationIntent( + long worldActivationFence, + String operationState, + byte[] accountProtectionEvidenceBytes, + byte[] terminalEvidenceBytes, + boolean createdByThisInvocation) {} + private Optional readResultInCurrentTransaction( WorldCanonicalInstanceActivation.Request request) { Record row = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java index 7e8b8c6932..80962eaa80 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java @@ -1,7 +1,10 @@ package net.firedevops.firemud.worldmanagement.tenant; import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; import org.springframework.transaction.support.TransactionSynchronizationManager; /** @@ -10,27 +13,31 @@ */ public final class WorldCanonicalInstanceActivationService { private final WorldCanonicalInstanceActivationRepository repository; - private final ActivationAuthorityVerifier verifier; /** - * Production-safe default: new activations remain denied until an explicit verifier is supplied. + * Production-safe default: request-only transports cannot start activation without the distinct + * authenticated Account activation-purpose protection path and its held source authority. */ public WorldCanonicalInstanceActivationService( WorldCanonicalInstanceActivationRepository repository) { - this(repository, WorldCanonicalInstanceActivationService::denyByDefault); + this.repository = Objects.requireNonNull(repository, "repository"); } - /** Constructor for an explicitly supplied owner verifier, including isolated proof fixtures. */ + /** + * Retained only for existing isolated callers. A request-only World verifier is no longer + * sufficient authority to start a fresh activation; fresh activation requires the distinct + * Account activation-purpose protection path below. + */ public WorldCanonicalInstanceActivationService( - WorldCanonicalInstanceActivationRepository repository, ActivationAuthorityVerifier verifier) { + WorldCanonicalInstanceActivationRepository repository, ActivationAuthorityVerifier ignored) { this.repository = Objects.requireNonNull(repository, "repository"); - this.verifier = Objects.requireNonNull(verifier, "verifier"); + Objects.requireNonNull(ignored, "verifier"); } /** - * Replays an exact immutable prior result without rechecking current lifecycle state. A new - * operation verifies all remote/current authority outside World transactions and keeps its - * operation-specific local fence held through commit. + * Replays an exact retained legacy result. Request-only fresh activation is denied: it cannot + * carry Account's distinct source-protection receipt, and this path intentionally cannot expose + * the new protected terminal result without that receipt. */ public WorldCanonicalInstanceActivation.Result activate( WorldCanonicalInstanceActivation.Request request) { @@ -38,23 +45,49 @@ public WorldCanonicalInstanceActivation.Result activate( requireNoActiveTransaction(); var prior = repository.readResult(request); if (prior.isPresent()) return prior.orElseThrow(); + throw new ActivationDeniedException( + "Fresh canonical activation requires complete Account activation-purpose protection evidence"); + } - HeldActivationAuthority held = - Objects.requireNonNull( - verifier.verifyAndHold(request), - "Canonical activation verifier returned no held operation authority"); + /** + * Runs the local storage/CAS half using an authority held by the separately authenticated + * activation-protection producer. The supplied integrity evidence does not itself authenticate + * Account or prove currentness; {@code held} must come from that separate owner boundary. + */ + public WorldOriginalStartSessionActivationTerminalEvidence activateProtected( + AccountStartSessionActivationProtectionEvidence protection, HeldActivationAuthority held) { + Objects.requireNonNull(protection, "protection"); + Objects.requireNonNull(held, "held"); + requireNoActiveTransaction(); try (held) { held.requireHeld(); - WorldCanonicalInstanceActivation.Result result = repository.activate(request, held); + WorldOriginalStartSessionActivationTerminalEvidence terminal = + repository.activateProtected(protection, held); held.requireHeld(); - return result; + return terminal; } } - private static HeldActivationAuthority denyByDefault( - WorldCanonicalInstanceActivation.Request request) { - throw new ActivationDeniedException( - "Canonical World activation has no authenticated current source/release and Account operation-authority verifier"); + /** + * Reads only an exact immutable terminal receipt for the same Account protection identity. + * Callers must authenticate its World provenance before treating it as settlement proof. + */ + public Optional readTerminalEvidence( + AccountStartSessionActivationProtectionEvidence protection) { + Objects.requireNonNull(protection, "protection"); + requireNoActiveTransaction(); + return repository.readTerminalEvidence(protection); + } + + /** + * Positively records an exact ABORTED terminal under the same durable World operation fence. It + * does not settle or release Account source protection. + */ + public WorldOriginalStartSessionActivationTerminalEvidence abortProtected( + AccountStartSessionActivationProtectionEvidence protection, String terminalCode) { + Objects.requireNonNull(protection, "protection"); + requireNoActiveTransaction(); + return repository.abortProtected(protection, terminalCode); } private static void requireNoActiveTransaction() { @@ -65,11 +98,18 @@ private static void requireNoActiveTransaction() { } @FunctionalInterface + /** + * Legacy request-only verifier retained for source compatibility; it cannot authorize a write. + */ public interface ActivationAuthorityVerifier { HeldActivationAuthority verifyAndHold(WorldCanonicalInstanceActivation.Request request); } - /** Distinct, operation-specific fence; a Draft/publication fence is not activation authority. */ + /** + * Distinct, operation-specific activation authority supplied by the Account-side producer. + * Closing this local handle releases only local resources; it must never settle or release + * Account's source-protection hold. + */ public interface HeldActivationAuthority extends AutoCloseable { void requireHeld(); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcService.java new file mode 100644 index 0000000000..e42dfb4ffe --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcService.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalReadInput; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalStartSessionActivationTerminalEvidenceRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalStartSessionActivationTerminalEvidenceResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldOriginalStartSessionActivationTerminalReadServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone authenticated World terminal-read adapter; intentionally not runtime-registered. */ +public final class WorldOriginalStartSessionActivationTerminalReadGrpcService + extends WorldOriginalStartSessionActivationTerminalReadServiceGrpc + .WorldOriginalStartSessionActivationTerminalReadServiceImplBase { + private final WorldCanonicalInstanceActivationService activationService; + private final String trustedNamespace; + + public WorldOriginalStartSessionActivationTerminalReadGrpcService( + WorldCanonicalInstanceActivationService activationService, String trustedNamespace) { + this.activationService = Objects.requireNonNull(activationService, "activationService"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readOriginalStartSessionActivationTerminalEvidence( + ReadOriginalStartSessionActivationTerminalEvidenceRequest request, + StreamObserver observer) { + if (!requireAuthenticatedAccountPeer(observer)) return; + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail( + observer, + Status.FAILED_PRECONDITION, + "World terminal reads require independent owner operations"); + return; + } + + WorldOriginalStartSessionActivationTerminalReadInput input; + try { + input = + WorldOriginalStartSessionActivationTerminalReadGrpcCodec.fromRequest( + request, trustedNamespace); + } catch (IllegalArgumentException invalid) { + fail( + observer, + Status.INVALID_ARGUMENT, + "A complete exact Account protection read is required"); + return; + } + + WorldOriginalStartSessionActivationTerminalEvidence terminal; + try { + terminal = activationService.readTerminalEvidence(input.protectionEvidence()).orElse(null); + } catch (TransientDataAccessException unavailable) { + fail(observer, Status.UNAVAILABLE, "World activation terminal storage is unavailable"); + return; + } catch (DataAccessException failure) { + fail(observer, Status.INTERNAL, "World activation terminal storage failed"); + return; + } catch (RuntimeException failure) { + fail(observer, Status.INTERNAL, "World activation terminal read failed"); + return; + } + if (terminal == null) { + fail( + observer, + Status.FAILED_PRECONDITION, + "World has no exact terminal receipt; Account protection remains pending"); + return; + } + try { + ReadOriginalStartSessionActivationTerminalEvidenceResponse response = + WorldOriginalStartSessionActivationTerminalReadGrpcCodec.toResponse(input, terminal); + observer.onNext(response); + observer.onCompleted(); + } catch (IllegalArgumentException mismatch) { + fail( + observer, + Status.FAILED_PRECONDITION, + "World terminal receipt differs from the exact Account protection read"); + } + } + + private boolean requireAuthenticatedAccountPeer(StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expectedUri = "spiffe://firemud/ns/" + trustedNamespace + "/sa/account-service"; + if (peer != null + && expectedUri.equals(peer.uri()) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + fail( + observer, + Status.PERMISSION_DENIED, + "Only the exact same-namespace Account workload without end-user context is allowed"); + return false; + } + + private static void fail(StreamObserver observer, Status status, String description) { + observer.onError(status.withDescription(description).asRuntimeException()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcService.java new file mode 100644 index 0000000000..5a2c772cfd --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcService.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionProtectedActivationGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.ActivateOriginalStartSessionProtectedRequest; +import net.firedevops.firemud.worldmanagement.v1.ActivateOriginalStartSessionProtectedResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldOriginalStartSessionProtectedActivationServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.TransientDataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Same-namespace authenticated adapter; deliberately not registered in production runtime wiring. + */ +public final class WorldOriginalStartSessionProtectedActivationGrpcService + extends WorldOriginalStartSessionProtectedActivationServiceGrpc + .WorldOriginalStartSessionProtectedActivationServiceImplBase { + private final WorldOriginalStartSessionProtectedActivationService activationService; + private final String trustedNamespace; + + public WorldOriginalStartSessionProtectedActivationGrpcService( + WorldOriginalStartSessionProtectedActivationService activationService, + String trustedNamespace) { + this.activationService = Objects.requireNonNull(activationService, "activationService"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void activateOriginalStartSessionProtected( + ActivateOriginalStartSessionProtectedRequest request, + StreamObserver observer) { + if (!requireAuthenticatedGameSessionPeer(observer)) return; + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail( + observer, + Status.FAILED_PRECONDITION, + "World protected activation requires independent owner operations"); + return; + } + + final AccountStartSessionActivationProtectionAcquisitionInput input; + try { + input = + WorldOriginalStartSessionProtectedActivationGrpcCodec.fromRequest( + request, trustedNamespace); + } catch (IllegalArgumentException invalid) { + fail( + observer, + Status.INVALID_ARGUMENT, + "A complete exact original activation input is required"); + return; + } + + final WorldOriginalStartSessionActivationTerminalEvidence terminal; + try { + terminal = activationService.activate(input); + } catch (WorldOriginalStartSessionProtectedActivationService.PendingActivationException + | WorldCanonicalInstanceActivationRepository.ActivationConflictException + | WorldCanonicalInstanceActivationService.ActivationDeniedException denied) { + fail(observer, Status.FAILED_PRECONDITION, "World protected activation is not admissible"); + return; + } catch (IllegalArgumentException invalid) { + fail(observer, Status.INVALID_ARGUMENT, "World protected activation input is invalid"); + return; + } catch (TransientDataAccessException unavailable) { + fail(observer, Status.UNAVAILABLE, "World protected activation storage is unavailable"); + return; + } catch (DataAccessException failure) { + fail(observer, Status.INTERNAL, "World protected activation storage failed"); + return; + } catch (RuntimeException failure) { + fail(observer, Status.INTERNAL, "World protected activation failed"); + return; + } + + try { + var response = + WorldOriginalStartSessionProtectedActivationGrpcCodec.toResponse( + input, trustedNamespace, terminal); + observer.onNext(response); + observer.onCompleted(); + } catch (IllegalArgumentException mismatch) { + fail(observer, Status.INTERNAL, "World protected activation terminal failed exact readback"); + } + } + + private boolean requireAuthenticatedGameSessionPeer(StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + String expectedUri = "spiffe://firemud/ns/" + trustedNamespace + "/sa/game-session-service"; + if (peer != null + && expectedUri.equals(peer.uri()) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + fail( + observer, + Status.PERMISSION_DENIED, + "Only the exact same-namespace Game Session workload without end-user context is allowed"); + return false; + } + + private static void fail(StreamObserver observer, Status status, String description) { + observer.onError(status.withDescription(description).asRuntimeException()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationService.java new file mode 100644 index 0000000000..e4f7c9d63d --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationService.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Objects; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionClient; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered orchestration boundary for authenticated original StartSession protection. */ +public final class WorldOriginalStartSessionProtectedActivationService { + private final WorldCanonicalInstanceActivationRepository activationRepository; + private final WorldCanonicalInstanceActivationService activationService; + private final AccountStartSessionActivationProtectionAcquisitionClient accountProtectionClient; + private final String trustedNamespace; + + public WorldOriginalStartSessionProtectedActivationService( + WorldCanonicalInstanceActivationRepository activationRepository, + WorldCanonicalInstanceActivationService activationService, + AccountStartSessionActivationProtectionAcquisitionClient accountProtectionClient, + String trustedNamespace) { + this.activationRepository = + Objects.requireNonNull(activationRepository, "activationRepository"); + this.activationService = Objects.requireNonNull(activationService, "activationService"); + this.accountProtectionClient = + Objects.requireNonNull(accountProtectionClient, "accountProtectionClient"); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("World workload namespace is invalid"); + } + this.trustedNamespace = trustedNamespace; + } + + /** + * Returns an exact historical terminal before contacting Account. An existing PENDING operation + * remains owned by its first invocation and can never be restarted by a later request. + */ + public WorldOriginalStartSessionActivationTerminalEvidence activate( + AccountStartSessionActivationProtectionAcquisitionInput input) { + Objects.requireNonNull(input, "activation acquisition input required"); + requireNoAmbientTransaction(); + input.requireTargetNamespace(trustedNamespace); + + var prior = activationRepository.readProtectedActivationByAcquisitionInput(input); + if (prior.isPresent()) { + var readback = prior.orElseThrow(); + if (readback.pending()) { + throw new PendingActivationException( + "World activation is already PENDING; it cannot reacquire authority or restart its lifecycle CAS"); + } + return readback.terminalEvidence(); + } + + // The distinct Account protection is acquired before any World writable transaction. This + // interface is the authenticated Account workload client; the carrier itself is integrity-only. + var protection = accountProtectionClient.acquire(input); + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toResponse( + input, trustedNamespace, protection); + + // The durable Account pending source guard spans World begin/CAS/terminal persistence. Closing + // this process-local handle intentionally performs no settlement or remote release. + WorldCanonicalInstanceActivationService.HeldActivationAuthority held = + new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + private boolean closed; + + @Override + public void requireHeld() { + if (closed) { + throw new WorldCanonicalInstanceActivationService.ActivationDeniedException( + "Local activation invocation authority is closed"); + } + } + + @Override + public void close() { + closed = true; + } + }; + return activationService.activateProtected(protection, held); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "World protected activation must acquire Account authority outside an ambient owner transaction"); + } + } + + public static final class PendingActivationException extends IllegalStateException { + public PendingActivationException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V65__original_start_session_protected_activation.sql b/services/world-management-service/src/main/resources/db/migration/V65__original_start_session_protected_activation.sql new file mode 100644 index 0000000000..e254d4ea91 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V65__original_start_session_protected_activation.sql @@ -0,0 +1,367 @@ +-- World activation intent is bound to the distinct Account StartSession protection receipt before +-- the PREPARING-to-ACTIVE lifecycle CAS. Historical V43 operation rows remain untouched. +CREATE SEQUENCE world_canonical_instance_activation_fence_seq AS BIGINT MINVALUE 1; + +CREATE TABLE world_canonical_instance_activation_fence ( + activation_request_id UUID PRIMARY KEY, + protection_operation_digest VARCHAR(71) NOT NULL + CHECK (protection_operation_digest ~ '^sha256:[0-9a-f]{64}$'), + account_protection_id UUID NOT NULL + CHECK (account_protection_id <> '00000000-0000-0000-0000-000000000000'::UUID), + account_protection_fence BIGINT NOT NULL CHECK (account_protection_fence > 0), + account_protection_evidence_bytes BYTEA NOT NULL + CHECK (octet_length(account_protection_evidence_bytes) BETWEEN 1 AND 209715200), + account_protection_evidence_digest VARCHAR(71) NOT NULL + CHECK (account_protection_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_protection_evidence_digest = + 'sha256:' || encode(sha256(account_protection_evidence_bytes), 'hex')), + source_capture_reference_digest VARCHAR(64) NOT NULL + CHECK (source_capture_reference_digest ~ '^[0-9a-f]{64}$'), + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_world_slug VARCHAR(120) NOT NULL, + canonical_game_instance_id UUID NOT NULL UNIQUE + CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::UUID), + original_post_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144), + account_world_participation_id UUID NOT NULL + CHECK (account_world_participation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + account_world_participation_fence BIGINT NOT NULL CHECK (account_world_participation_fence > 0), + game_session_owner_mutation_id UUID NOT NULL + CHECK (game_session_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_attempt_id UUID NOT NULL + CHECK (game_session_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID), + game_session_owner_fence BIGINT NOT NULL CHECK (game_session_owner_fence > 0), + original_game_session_lease_expires_at TIMESTAMPTZ NOT NULL, + canonical_realm_id UUID NOT NULL + CHECK (canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID), + catalog_revision BIGINT NOT NULL CHECK (catalog_revision > 0), + expected_lifecycle_epoch BIGINT NOT NULL CHECK (expected_lifecycle_epoch > 0), + expected_row_version BIGINT NOT NULL CHECK (expected_row_version >= 0), + preparing_evidence_bytes BYTEA NOT NULL + CHECK (octet_length(preparing_evidence_bytes) BETWEEN 1 AND 67108864), + world_execution_fence BIGINT NOT NULL UNIQUE CHECK (world_execution_fence > 0), + world_instance_id BIGINT NOT NULL REFERENCES world_instance(id) ON DELETE RESTRICT, + world_activation_fence BIGINT NOT NULL UNIQUE CHECK (world_activation_fence > 0), + operation_state VARCHAR(16) NOT NULL CHECK (operation_state IN ('PENDING', 'COMMITTED', 'ABORTED')), + terminal_result_bytes BYTEA, + terminal_result_digest VARCHAR(71), + terminal_evidence_bytes BYTEA, + terminal_evidence_digest VARCHAR(71), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + terminal_at TIMESTAMPTZ, + CONSTRAINT ck_world_activation_fence_request_id_non_nil + CHECK (activation_request_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT ck_world_activation_fence_terminal_shape CHECK ( + (operation_state = 'PENDING' + AND terminal_result_bytes IS NULL AND terminal_result_digest IS NULL + AND terminal_evidence_bytes IS NULL AND terminal_evidence_digest IS NULL + AND terminal_at IS NULL) + OR (operation_state IN ('COMMITTED', 'ABORTED') + AND terminal_result_bytes IS NOT NULL + AND octet_length(terminal_result_bytes) BETWEEN 1 AND 402653184 + AND terminal_result_digest IS NOT NULL + AND terminal_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND terminal_result_digest = 'sha256:' || encode(sha256(terminal_result_bytes), 'hex') + AND terminal_evidence_bytes IS NOT NULL + AND octet_length(terminal_evidence_bytes) BETWEEN 1 AND 805306368 + AND terminal_evidence_digest IS NOT NULL + AND terminal_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND terminal_evidence_digest = 'sha256:' || encode(sha256(terminal_evidence_bytes), 'hex') + AND terminal_at IS NOT NULL) + ) +); + +CREATE INDEX idx_world_activation_fence_terminal + ON world_canonical_instance_activation_fence(operation_state, world_instance_id); + +-- [jooq ignore start] +REVOKE ALL ON world_canonical_instance_activation_fence FROM PUBLIC; +REVOKE ALL ON SEQUENCE world_canonical_instance_activation_fence_seq FROM PUBLIC; + +-- V43 deliberately rejected the V64 schema-2 association because it lacked the launch-captured +-- realm/catalog pair. Widen only its old schema discriminator and preserve schema-1 history exactly. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ AND a.schema_version=1$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V43 schema-1 activation guard'; + END IF; + original := replace(original, anchor, $replacement$ AND a.schema_version IN (1,2) + AND (a.schema_version=1 OR ( + a.canonical_realm_id IS NOT NULL + AND a.catalog_revision IS NOT NULL + AND w.canonical_realm_id=a.canonical_realm_id + AND w.catalog_revision=a.catalog_revision + AND p.input_json::JSONB->'identity'->>'canonicalRealmId'=a.canonical_realm_id::TEXT + AND p.input_json::JSONB->'identity'->>'catalogRevision'=a.catalog_revision::TEXT))$replacement$); + EXECUTE original; +END; +$migration$; + +CREATE FUNCTION world_validate_original_start_session_activation_fence() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + account_evidence JSONB; + account_request JSONB; + preparing JSONB; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'World original StartSession activation fences are immutable and retained' + USING ERRCODE = '55000'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.operation_state IS DISTINCT FROM 'PENDING' + OR NEW.terminal_result_bytes IS NOT NULL OR NEW.terminal_result_digest IS NOT NULL + OR NEW.terminal_evidence_bytes IS NOT NULL OR NEW.terminal_evidence_digest IS NOT NULL + OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'World activation fence must be retained as PENDING before its exact terminal' + USING ERRCODE = '23514'; + END IF; + account_evidence := convert_from(NEW.account_protection_evidence_bytes, 'UTF8')::JSONB; + preparing := convert_from(NEW.preparing_evidence_bytes, 'UTF8')::JSONB; + IF jsonb_typeof(account_evidence) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(account_evidence)) <> 8 + OR account_evidence->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-evidence/v1' + OR account_evidence->>'accountProtectionId' IS DISTINCT FROM NEW.account_protection_id::TEXT + OR account_evidence->>'accountProtectionFence' IS DISTINCT FROM NEW.account_protection_fence::TEXT + OR account_evidence->>'originalSourceCaptureReferenceSha256' + IS DISTINCT FROM NEW.source_capture_reference_digest + OR NEW.source_capture_reference_digest IS DISTINCT FROM + encode(sha256(decode(account_evidence->>'originalSourceCaptureReferenceBytesBase64','base64')), 'hex') + OR jsonb_typeof(account_evidence->'sourceEvidenceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(account_evidence->'sourceEvidenceVector') < 1 THEN + RAISE EXCEPTION 'World activation fence does not retain a complete exact Account protection receipt' + USING ERRCODE = '23514'; + END IF; + account_request := convert_from( + decode(account_evidence->>'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + IF jsonb_typeof(account_request) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(account_request)) <> 12 + OR account_request->>'schema' IS DISTINCT FROM 'account-start-session-activation-protection-request/v1' + OR decode(account_request->>'originalPostAuthorizationTupleBytesBase64', 'base64') + IS DISTINCT FROM NEW.original_post_authorization_tuple + OR account_request->>'gameSessionOwnerMutationId' IS DISTINCT FROM NEW.game_session_owner_mutation_id::TEXT + OR account_request->>'gameSessionOwnerAttemptId' IS DISTINCT FROM NEW.game_session_owner_attempt_id::TEXT + OR account_request->>'gameSessionOwnerFence' IS DISTINCT FROM NEW.game_session_owner_fence::TEXT + OR (account_request->>'originalLeaseExpiresAt')::TIMESTAMPTZ + IS DISTINCT FROM NEW.original_game_session_lease_expires_at + OR account_request->>'accountWorldParticipationId' IS DISTINCT FROM NEW.account_world_participation_id::TEXT + OR account_request->>'accountWorldParticipationFence' IS DISTINCT FROM NEW.account_world_participation_fence::TEXT + OR account_request->>'worldActivationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR decode(account_request->>'preparingEvidenceBytesBase64', 'base64') + IS DISTINCT FROM NEW.preparing_evidence_bytes + OR preparing->>'schema' IS DISTINCT FROM 'world-canonical-instance-lifecycle-evidence/v1' + OR preparing->>'lifecycleStatus' IS DISTINCT FROM 'PREPARING' + OR preparing->>'lifecycleEpoch' IS DISTINCT FROM NEW.expected_lifecycle_epoch::TEXT + OR preparing->>'rowVersion' IS DISTINCT FROM NEW.expected_row_version::TEXT + OR preparing->'request'->>'targetNamespace' IS DISTINCT FROM NEW.target_namespace + OR preparing->'request'->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR preparing->'request'->>'worldSlug' IS DISTINCT FROM NEW.canonical_world_slug + OR preparing->'request'->>'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR preparing->'request'->>'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT THEN + RAISE EXCEPTION 'World activation fence identity differs from the complete Account original request' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM world_canonical_instance_execution e + JOIN world_canonical_instance_association a + ON a.canonical_game_instance_id=e.canonical_game_instance_id + JOIN world_instance w ON w.id=a.world_instance_id + JOIN world_canonical_instance_preparation p + ON p.canonical_game_instance_id=a.canonical_game_instance_id + WHERE e.target_namespace=NEW.target_namespace + AND e.canonical_tenant_id=NEW.canonical_tenant_id + AND e.control_plane_request_id=NEW.control_plane_request_id + AND e.canonical_world_slug=NEW.canonical_world_slug + AND e.canonical_game_instance_id=NEW.canonical_game_instance_id + AND e.original_post_authorization_tuple=NEW.original_post_authorization_tuple + AND e.account_world_participation_id=NEW.account_world_participation_id + AND e.account_world_participation_fence=NEW.account_world_participation_fence + AND e.game_session_owner_mutation_id=NEW.game_session_owner_mutation_id + AND e.game_session_owner_attempt_id=NEW.game_session_owner_attempt_id + AND e.game_session_owner_fence=NEW.game_session_owner_fence + AND e.original_game_session_lease_expires_at=NEW.original_game_session_lease_expires_at + AND e.operation_state='COMMITTED' + AND e.world_execution_fence=NEW.world_execution_fence + AND e.world_instance_id=NEW.world_instance_id + AND a.world_instance_id=NEW.world_instance_id + AND a.schema_version=2 + AND a.canonical_realm_id=NEW.canonical_realm_id + AND a.catalog_revision=NEW.catalog_revision + AND w.canonical_game_instance_id=a.canonical_game_instance_id + AND w.canonical_realm_id=a.canonical_realm_id + AND w.catalog_revision=a.catalog_revision + AND p.input_digest=e.preparation_input_digest + AND p.input_digest=preparing->>'preparationInputDigest' + AND p.input_json::JSONB->'identity'->>'canonicalRealmId'=a.canonical_realm_id::TEXT + AND p.input_json::JSONB->'identity'->>'catalogRevision'=a.catalog_revision::TEXT + AND p.input_json::JSONB->>'schemaVersion'='4' + ) THEN + RAISE EXCEPTION 'World activation fence differs from the committed original execution, schema-2 realm/catalog, or exact preparation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF OLD.operation_state IS DISTINCT FROM 'PENDING' + OR NEW.operation_state NOT IN ('COMMITTED', 'ABORTED') + OR (to_jsonb(NEW) - ARRAY['operation_state','terminal_result_bytes','terminal_result_digest', + 'terminal_evidence_bytes','terminal_evidence_digest','terminal_at']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['operation_state','terminal_result_bytes','terminal_result_digest', + 'terminal_evidence_bytes','terminal_evidence_digest','terminal_at']) + OR NEW.terminal_result_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_result_bytes), 'hex') + OR NEW.terminal_evidence_digest IS DISTINCT FROM + 'sha256:' || encode(sha256(NEW.terminal_evidence_bytes), 'hex') + OR NEW.terminal_at IS NULL THEN + RAISE EXCEPTION 'World activation intent permits one immutable PENDING-to-terminal transition only' + USING ERRCODE = '55000'; + END IF; + IF NEW.terminal_result_bytes IS NULL OR NEW.terminal_evidence_bytes IS NULL + OR NEW.terminal_result_digest IS NULL OR NEW.terminal_evidence_digest IS NULL THEN + RAISE EXCEPTION 'World activation terminal fence requires complete immutable result and evidence bytes' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_validate_original_start_session_activation_fence() FROM PUBLIC; +CREATE TRIGGER trg_world_original_start_session_activation_fence + BEFORE INSERT OR UPDATE OR DELETE ON world_canonical_instance_activation_fence + FOR EACH ROW EXECUTE FUNCTION world_validate_original_start_session_activation_fence(); + +CREATE FUNCTION world_reject_original_start_session_activation_fence_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'World original StartSession activation fences are immutable and retained' + USING ERRCODE = '55000'; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_reject_original_start_session_activation_fence_truncate() FROM PUBLIC; +CREATE TRIGGER trg_world_original_start_session_activation_fence_no_truncate + BEFORE TRUNCATE ON world_canonical_instance_activation_fence + FOR EACH STATEMENT EXECUTE FUNCTION world_reject_original_start_session_activation_fence_truncate(); + +-- Every new V43 result, including a direct SQL insert, must belong to the exact pending protected +-- operation. The pre-existing operation rows are not rewritten or revalidated. +CREATE FUNCTION world_require_protected_canonical_activation_operation() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + fence "${serviceSchema}".world_canonical_instance_activation_fence%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'World canonical activation operation evidence is immutable' + USING ERRCODE = '55000'; + END IF; + SELECT * INTO fence FROM "${serviceSchema}".world_canonical_instance_activation_fence + WHERE activation_request_id=NEW.activation_request_id FOR UPDATE; + IF NOT FOUND + OR fence.operation_state IS DISTINCT FROM 'PENDING' + OR fence.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR fence.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR fence.expected_lifecycle_epoch IS DISTINCT FROM NEW.expected_lifecycle_epoch + OR fence.expected_row_version IS DISTINCT FROM NEW.expected_row_version + OR fence.preparing_evidence_bytes IS DISTINCT FROM NEW.preparing_evidence_bytes + OR NEW.request_bytes IS DISTINCT FROM + decode(convert_from(NEW.result_bytes, 'UTF8')::JSONB->>'requestBytesBase64','base64') + OR convert_from(NEW.result_bytes, 'UTF8')::JSONB->>'requestDigest' IS DISTINCT FROM NEW.request_digest THEN + RAISE EXCEPTION 'New World activation result lacks its exact pending Account-protected operation fence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +REVOKE ALL ON FUNCTION world_require_protected_canonical_activation_operation() FROM PUBLIC; +CREATE TRIGGER trg_world_require_protected_canonical_activation_operation + BEFORE INSERT ON world_canonical_instance_activation_operation + FOR EACH ROW EXECUTE FUNCTION world_require_protected_canonical_activation_operation(); + +CREATE FUNCTION world_require_original_start_session_activation_terminal() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + result JSONB; + terminal JSONB; +BEGIN + IF NEW.operation_state='PENDING' THEN RETURN NULL; END IF; + result := convert_from(NEW.terminal_result_bytes, 'UTF8')::JSONB; + terminal := convert_from(NEW.terminal_evidence_bytes, 'UTF8')::JSONB; + IF NOT EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_canonical_instance_activation_operation o + WHERE o.activation_request_id=NEW.activation_request_id + AND o.canonical_game_instance_id=NEW.canonical_game_instance_id + AND o.world_instance_id=NEW.world_instance_id + AND o.outcome=NEW.operation_state + AND o.result_bytes=NEW.terminal_result_bytes + AND o.result_digest=NEW.terminal_result_digest + AND o.request_bytes=decode(result->>'requestBytesBase64','base64') + AND o.preparing_evidence_bytes=NEW.preparing_evidence_bytes + ) OR jsonb_typeof(terminal) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(terminal)) <> 8 + OR terminal->>'schema' IS DISTINCT FROM 'world-original-start-session-activation-terminal-evidence/v1' + OR terminal->>'activationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR terminal->>'accountProtectionId' IS DISTINCT FROM NEW.account_protection_id::TEXT + OR terminal->>'accountProtectionFence' IS DISTINCT FROM NEW.account_protection_fence::TEXT + OR terminal->>'worldActivationFence' IS DISTINCT FROM NEW.world_activation_fence::TEXT + OR decode(terminal->>'accountProtectionEvidenceBytesBase64','base64') + IS DISTINCT FROM NEW.account_protection_evidence_bytes + OR decode(terminal->>'activationResultBytesBase64','base64') + IS DISTINCT FROM NEW.terminal_result_bytes + OR terminal->>'activationResultSha256' IS DISTINCT FROM NEW.terminal_result_digest + OR result->>'activationRequestId' IS DISTINCT FROM NEW.activation_request_id::TEXT + OR result->>'outcome' IS DISTINCT FROM NEW.operation_state THEN + RAISE EXCEPTION 'World terminal receipt is not the exact Account protection and committed lifecycle operation' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_require_original_start_session_activation_terminal() FROM PUBLIC; +CREATE CONSTRAINT TRIGGER trg_world_original_start_session_activation_terminal + AFTER INSERT OR UPDATE ON world_canonical_instance_activation_fence + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_original_start_session_activation_terminal(); + +CREATE FUNCTION world_require_protected_activation_fence_for_operation() +RETURNS TRIGGER +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +DECLARE + fence "${serviceSchema}".world_canonical_instance_activation_fence%ROWTYPE; +BEGIN + SELECT * INTO fence FROM "${serviceSchema}".world_canonical_instance_activation_fence + WHERE activation_request_id=NEW.activation_request_id; + IF NOT FOUND + OR fence.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR fence.world_instance_id IS DISTINCT FROM NEW.world_instance_id + OR fence.operation_state IS DISTINCT FROM NEW.outcome THEN + RAISE EXCEPTION 'World activation lifecycle result cannot commit without its exact protected terminal fence' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +REVOKE ALL ON FUNCTION world_require_protected_activation_fence_for_operation() FROM PUBLIC; +CREATE CONSTRAINT TRIGGER trg_world_protected_activation_operation_terminal + AFTER INSERT ON world_canonical_instance_activation_operation + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION world_require_protected_activation_fence_for_operation(); +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 407d2dd55a..1c7c2a553b 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -23,6 +23,7 @@ import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; import java.time.OffsetDateTime; @@ -42,7 +43,13 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionRequest; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -58,6 +65,8 @@ import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -92,6 +101,7 @@ import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsEvidence; import net.firedevops.firemud.common.world.WorldPublishedSpawnRequirementsGrpcCodec; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; @@ -1740,7 +1750,7 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni fixture.materialized().association().worldInstanceId()); return null; })) - .hasMessageContaining("must include its exact ACTIVE lifecycle CAS before commit"); + .hasMessageContaining("lacks its exact pending Account-protected operation fence"); assertThat( Objects.requireNonNull( dsl.fetchOne( @@ -1753,50 +1763,49 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni var first = new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var alternatePreparing = + fixture + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(fixture.preparing().request())) + .orElseThrow(); var second = - new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); - CountDownLatch bothAuthoritiesChecked = new CountDownLatch(2); - AtomicInteger verifierCalls = new AtomicInteger(); - var service = - canonicalActivationService( + new WorldCanonicalInstanceActivation.Request( + first.activationRequestId(), alternatePreparing); + var firstProtection = activationProtection(fixture, first); + var secondProtection = + activationProtection( fixture, - request -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - verifierCalls.incrementAndGet(); - bothAuthoritiesChecked.countDown(); - await(bothAuthoritiesChecked); - return stipulatedActivationAuthority(); - }); - ExecutorService executor = Executors.newFixedThreadPool(2); - WorldCanonicalInstanceActivation.Result firstResult; - WorldCanonicalInstanceActivation.Result secondResult; - try { - Future firstFuture = - executor.submit(() -> service.activate(first)); - Future secondFuture = - executor.submit(() -> service.activate(second)); - firstResult = firstFuture.get(45, TimeUnit.SECONDS); - secondResult = secondFuture.get(45, TimeUnit.SECONDS); - } finally { - executor.shutdownNow(); - } - - assertThat(verifierCalls).hasValue(2); - assertThat(List.of(firstResult.outcome(), secondResult.outcome())) - .containsExactlyInAnyOrder( - WorldCanonicalInstanceActivation.Outcome.COMMITTED, - WorldCanonicalInstanceActivation.Outcome.ABORTED); - var committed = - firstResult.outcome() == WorldCanonicalInstanceActivation.Outcome.COMMITTED - ? firstResult - : secondResult; - var aborted = committed == firstResult ? secondResult : firstResult; + second, + alternatePreparing.request().readRequestId(), + UUID.randomUUID(), + fixture.materialized().association().identity().canonicalRealmId(), + fixture.materialized().association().identity().catalogRevision(), + Instant.parse("2026-10-10T12:00:00Z"), + "7".repeat(64), + List.of(activationSource(fixture, SourceKind.ACCOUNT))); + var service = + new WorldCanonicalInstanceActivationService( + new WorldCanonicalInstanceActivationRepository( + dsl, manager, fixture.lifecycleRepository())); + var firstResult = + service + .activateProtected(firstProtection, stipulatedActivationAuthority()) + .activationResult(); + var secondResult = + service + .activateProtected(secondProtection, stipulatedActivationAuthority()) + .activationResult(); + + assertThat(firstResult.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + assertThat(secondResult.outcome()) + .isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + assertThat(secondResult.canonicalBytes()).containsExactly(firstResult.canonicalBytes()); + var committed = firstResult; assertThat(committed.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); assertThat(committed.lifecycleEvidence().lifecycleEpoch()) .isEqualTo(fixture.preparing().lifecycleEpoch() + 1L); assertThat(committed.lifecycleEvidence().rowVersion()) .isEqualTo(fixture.preparing().rowVersion() + 1L); - assertThat(aborted.terminalCode()).isEqualTo("PRECONDITION_FAILED"); var active = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); assertThat(active.lifecycleStatus()).isEqualTo("ACTIVE"); assertThat(active.lifecycleEpoch()).isEqualTo(committed.lifecycleEvidence().lifecycleEpoch()); @@ -1809,12 +1818,15 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni var repository = new WorldCanonicalInstanceActivationRepository(dsl, manager, fixture.lifecycleRepository()); - assertThat(repository.readResult(committed.request()).orElseThrow().canonicalBytes()) - .containsExactly(committed.canonicalBytes()); - int callsAfterFirstAttempt = verifierCalls.get(); - assertThat(service.activate(committed.request()).canonicalBytes()) + assertThat(repository.readResult(committed.request())).isEmpty(); + var terminal = repository.readTerminalEvidence(firstProtection).orElseThrow(); + assertThat(terminal.activationResult().canonicalBytes()) .containsExactly(committed.canonicalBytes()); - assertThat(verifierCalls).hasValue(callsAfterFirstAttempt); + assertThat(terminal.accountProtectionEvidence().canonicalBytes()) + .containsExactly(firstProtection.canonicalBytes()); + assertThatThrownBy(() -> service.activate(committed.request())) + .isInstanceOf(WorldCanonicalInstanceActivationService.ActivationDeniedException.class) + .hasMessageContaining("complete Account activation-purpose protection evidence"); var changedExpectedVersion = new WorldCanonicalInstanceLifecycleEvidence( fixture.preparing().request(), @@ -1831,10 +1843,56 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni var changedRetry = new WorldCanonicalInstanceActivation.Request( committed.request().activationRequestId(), changedExpectedVersion); - assertThatThrownBy(() -> service.activate(changedRetry)) + var changedProtection = activationProtection(fixture, changedRetry); + assertThatThrownBy( + () -> service.activateProtected(changedProtection, stipulatedActivationAuthority())) .isInstanceOf(WorldCanonicalInstanceActivationRepository.ActivationConflictException.class) - .hasMessageContaining("reused with changed immutable bindings"); - assertThat(verifierCalls).hasValue(callsAfterFirstAttempt); + .hasMessageContaining("already bound to different Account protection evidence"); + + UUID worldReadId = first.preparing().request().readRequestId(); + UUID gameSessionReadId = fixture.input().gameSessionReadRequest().readRequestId(); + var changedAcquisition = + activationProtection( + fixture, + first, + worldReadId, + gameSessionReadId, + fixture.materialized().association().identity().canonicalRealmId(), + fixture.materialized().association().identity().catalogRevision(), + Instant.parse("2026-10-10T12:00:01Z"), + "7".repeat(64), + List.of(activationSource(fixture, SourceKind.ACCOUNT))); + var changedCapture = + activationProtection( + fixture, + first, + worldReadId, + gameSessionReadId, + fixture.materialized().association().identity().canonicalRealmId(), + fixture.materialized().association().identity().catalogRevision(), + Instant.parse("2026-10-10T12:00:00Z"), + "8".repeat(64), + List.of(activationSource(fixture, SourceKind.ACCOUNT))); + var changedSourceVector = + activationProtection( + fixture, + first, + worldReadId, + gameSessionReadId, + fixture.materialized().association().identity().canonicalRealmId(), + fixture.materialized().association().identity().catalogRevision(), + Instant.parse("2026-10-10T12:00:00Z"), + "7".repeat(64), + List.of( + activationSource(fixture, SourceKind.ACCOUNT), + activationSource(fixture, SourceKind.TENANT))); + for (var substituted : List.of(changedAcquisition, changedCapture, changedSourceVector)) { + assertThatThrownBy( + () -> service.activateProtected(substituted, stipulatedActivationAuthority())) + .isInstanceOf( + WorldCanonicalInstanceActivationRepository.ActivationConflictException.class) + .hasMessageContaining("retry changed its original protection or activation identity"); + } // The single-use activation capability was consumed; its retained ledger cannot authorize a // second raw lifecycle update. @@ -1859,9 +1917,10 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni .hasMessageContaining("no exact transaction execution manifest"); assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) .isEqualTo(active); - assertThat(service.activate(committed.request()).canonicalBytes()) - .containsExactly(committed.canonicalBytes()); - assertThat(verifierCalls).hasValue(callsAfterFirstAttempt); + assertThat(service.readTerminalEvidence(firstProtection).orElseThrow().canonicalBytes()) + .containsExactly(terminal.canonicalBytes()); + assertThat(terminal.accountProtectionEvidence().canonicalBytes()) + .containsExactly(firstProtection.canonicalBytes()); assertThat(preparationRows(fixture.input().canonicalGameInstanceId())) .containsExactly(preparationBefore); assertOrigin(); @@ -1869,73 +1928,342 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni @Test void canonicalActivationRawSqlRejectsIncompleteOrSubstitutedOperationalRegionAssignments() { - PreparedLifecycleFixture fixture = materializedLifecycleFixture(); - var assignments = fixture.preparing().operationalRegionAssignments(); - assertThat(assignments).isNotEmpty().hasSize(1); - var first = assignments.entrySet().iterator().next(); - - Map missing = new LinkedHashMap<>(assignments); - missing.remove(first.getKey()); - UUID missingCanonicalId = UUID.randomUUID(); - while (assignments.containsKey(missingCanonicalId) - || assignments.containsValue(missingCanonicalId)) { - missingCanonicalId = UUID.randomUUID(); - } - missing.put(missingCanonicalId, first.getValue()); - Map extra = new LinkedHashMap<>(assignments); - UUID extraCanonicalId = UUID.randomUUID(); - while (assignments.containsKey(extraCanonicalId) - || assignments.containsValue(extraCanonicalId)) { - extraCanonicalId = UUID.randomUUID(); - } - UUID extraOperationalId = UUID.randomUUID(); - while (assignments.containsKey(extraOperationalId) - || assignments.containsValue(extraOperationalId) - || extraCanonicalId.equals(extraOperationalId)) { - extraOperationalId = UUID.randomUUID(); - } - extra.put(extraCanonicalId, extraOperationalId); - Map substituted = new LinkedHashMap<>(assignments); - UUID substitutedOperationalId = UUID.randomUUID(); - while (assignments.containsKey(substitutedOperationalId) - || assignments.containsValue(substitutedOperationalId) - || first.getKey().equals(substitutedOperationalId)) { - substitutedOperationalId = UUID.randomUUID(); - } - substituted.put(first.getKey(), substitutedOperationalId); - - ownerTransaction() - .execute( - status -> { - int index = 0; - for (Map invalidAssignments : List.of(missing, extra, substituted)) { - var proof = rawCommittedActivationProofWithAssignments(fixture, invalidAssignments); - String savepoint = "invalid_activation_region_map_" + index++; - dsl.execute("SAVEPOINT " + savepoint); + for (int invalidKind = 0; invalidKind < 3; invalidKind++) { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var assignments = fixture.preparing().operationalRegionAssignments(); + assertThat(assignments).isNotEmpty().hasSize(1); + var first = assignments.entrySet().iterator().next(); + Map invalidAssignments = new LinkedHashMap<>(assignments); + if (invalidKind == 0) { + invalidAssignments.remove(first.getKey()); + invalidAssignments.put(UUID.randomUUID(), first.getValue()); + } else if (invalidKind == 1) { + invalidAssignments.put(UUID.randomUUID(), UUID.randomUUID()); + } else { + invalidAssignments.put(first.getKey(), UUID.randomUUID()); + } + var proof = rawCommittedActivationProofWithAssignments(fixture, invalidAssignments); + var protection = activationProtection(fixture, proof.request()); + retainPendingActivationIntent(fixture, protection); + ownerTransaction() + .execute( + status -> { + dsl.execute("SAVEPOINT invalid_activation_region_map"); assertThatThrownBy( () -> insertRawActivationOperation( proof, fixture.materialized().association().worldInstanceId())) .hasMessageContaining("exact complete operational REGION assignment map"); - dsl.execute("ROLLBACK TO SAVEPOINT " + savepoint); + dsl.execute("ROLLBACK TO SAVEPOINT invalid_activation_region_map"); assertThat( activationOperationCountForRequest(proof.request().activationRequestId())) .isZero(); assertThat(activationManifestCountForRequest(proof.request().activationRequestId())) .isZero(); - } - return null; - }); + return null; + }); + + var retained = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(retained.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(retained.operationalRegionAssignments()).containsExactlyEntriesOf(assignments); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + } + assertOrigin(); + } + + @Test + void canonicalActivationRequiresExactLocalSchemaTwoRealmAndCatalog() { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var request = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var service = + new WorldCanonicalInstanceActivationService( + new WorldCanonicalInstanceActivationRepository( + dsl, manager, fixture.lifecycleRepository())); + UUID actualRealm = fixture.materialized().association().identity().canonicalRealmId(); + long actualCatalog = fixture.materialized().association().identity().catalogRevision(); + + var substitutedRealm = + activationProtection( + fixture, + request, + request.preparing().request().readRequestId(), + fixture.input().gameSessionReadRequest().readRequestId(), + UUID.randomUUID(), + actualCatalog, + Instant.parse("2026-10-10T12:00:00Z"), + "7".repeat(64), + List.of(activationSource(fixture, SourceKind.ACCOUNT))); + var substitutedCatalog = + activationProtection( + fixture, + request, + request.preparing().request().readRequestId(), + fixture.input().gameSessionReadRequest().readRequestId(), + actualRealm, + actualCatalog + 1L, + Instant.parse("2026-10-10T12:00:00Z"), + "7".repeat(64), + List.of(activationSource(fixture, SourceKind.ACCOUNT))); + + for (var protection : List.of(substitutedRealm, substitutedCatalog)) { + assertThatThrownBy( + () -> service.activateProtected(protection, stipulatedActivationAuthority())) + .isInstanceOf( + WorldCanonicalInstanceActivationRepository.ActivationConflictException.class) + .hasMessageContaining("does not match the committed original execution"); + } + assertThat(activationOperationCountForRequest(request.activationRequestId())).isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_fence WHERE canonical_game_instance_id=?", + request.canonicalGameInstanceId())) + .get(0, Long.class)) + .isZero(); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(fixture.preparing()); + assertOrigin(); + } + + @Test + void distinctConcurrentActivationIdsCannotClaimOrMutateOneCanonicalInstance() throws Exception { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var firstRequest = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var secondRequest = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var firstProtection = activationProtection(fixture, firstRequest); + var secondProtection = activationProtection(fixture, secondRequest); + var service = + new WorldCanonicalInstanceActivationService( + new WorldCanonicalInstanceActivationRepository( + dsl, manager, fixture.lifecycleRepository())); + CountDownLatch bothReady = new CountDownLatch(2); + ExecutorService executor = Executors.newFixedThreadPool(2); + Object firstOutcome; + Object secondOutcome; + try { + Future firstFuture = + executor.submit( + () -> { + try { + return service.activateProtected( + firstProtection, barrierActivationAuthority(bothReady)); + } catch (RuntimeException failure) { + return failure; + } + }); + Future secondFuture = + executor.submit( + () -> { + try { + return service.activateProtected( + secondProtection, barrierActivationAuthority(bothReady)); + } catch (RuntimeException failure) { + return failure; + } + }); + firstOutcome = firstFuture.get(45, TimeUnit.SECONDS); + secondOutcome = secondFuture.get(45, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + } - var retained = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); - assertThat(retained.lifecycleStatus()).isEqualTo("PREPARING"); - assertThat(retained.operationalRegionAssignments()).containsExactlyEntriesOf(assignments); + List outcomes = List.of(firstOutcome, secondOutcome); + assertThat( + outcomes.stream() + .filter(WorldOriginalStartSessionActivationTerminalEvidence.class::isInstance)) + .hasSize(1); + assertThat(outcomes.stream().filter(RuntimeException.class::isInstance)).hasSize(1); + RuntimeException rejected = + (RuntimeException) + outcomes.stream().filter(RuntimeException.class::isInstance).findFirst().orElseThrow(); + assertThat(rejected) + .isInstanceOf(WorldCanonicalInstanceActivationRepository.ActivationConflictException.class); + WorldOriginalStartSessionActivationTerminalEvidence winner = + (WorldOriginalStartSessionActivationTerminalEvidence) + outcomes.stream() + .filter(WorldOriginalStartSessionActivationTerminalEvidence.class::isInstance) + .findFirst() + .orElseThrow(); + assertThat(winner.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_fence WHERE canonical_game_instance_id=?", + fixture.input().canonicalGameInstanceId())) + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + activationOperationCountForRequest(firstRequest.activationRequestId()) + + activationOperationCountForRequest(secondRequest.activationRequestId())) + .isEqualTo(1L); + var active = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); + assertThat(active.lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(active.lifecycleEpoch()).isEqualTo(fixture.preparing().lifecycleEpoch() + 1L); + assertThat(active.rowVersion()).isEqualTo(fixture.preparing().rowVersion() + 1L); assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); assertOrigin(); } @Test - void canonicalActivationTransportRequiresGameSessionAndReplaysImmutableOwnerResult() + void positiveAbortSerializesBeforeWaitingActivationAndExcludesItsLaterCommit() throws Exception { + PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var request = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var protection = activationProtection(fixture, request); + var service = + new WorldCanonicalInstanceActivationService( + new WorldCanonicalInstanceActivationRepository( + dsl, manager, fixture.lifecycleRepository())); + AtomicInteger heldChecks = new AtomicInteger(); + CountDownLatch activationWaitingForLock = new CountDownLatch(1); + CountDownLatch continueActivation = new CountDownLatch(1); + var held = + new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() { + if (heldChecks.incrementAndGet() == 2) { + activationWaitingForLock.countDown(); + await(continueActivation); + } + } + + public void close() {} + }; + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future activationFuture = + executor.submit(() -> service.activateProtected(protection, held)); + await(activationWaitingForLock); + var aborted = service.abortProtected(protection, "POSITIVE_ABORT_WON_SERIALIZATION"); + assertThat(aborted.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.ABORTED); + continueActivation.countDown(); + var activationReadback = activationFuture.get(45, TimeUnit.SECONDS); + assertThat(activationReadback.canonicalBytes()).containsExactly(aborted.canonicalBytes()); + assertThat(activationReadback.activationResult().terminalCode()) + .isEqualTo("POSITIVE_ABORT_WON_SERIALIZATION"); + assertThat(activationOperationCountForRequest(request.activationRequestId())).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_state FROM world_canonical_instance_activation_fence WHERE activation_request_id=?", + request.activationRequestId())) + .get("operation_state", String.class)) + .isEqualTo("ABORTED"); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(fixture.preparing()); + assertThat(service.abortProtected(protection, "IGNORED_AFTER_TERMINAL").canonicalBytes()) + .containsExactly(aborted.canonicalBytes()); + } finally { + continueActivation.countDown(); + executor.shutdownNow(); + } + assertOrigin(); + } + + @Test + void freshActivationWaitingPastOriginalLeaseCannotAdmitCasButCanBePositivelyAborted() + throws Exception { + var leaseFixture = materializedLifecycleFixtureWithLease(Duration.ofSeconds(10)); + PreparedLifecycleFixture fixture = leaseFixture.fixture(); + var request = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var protection = activationProtection(fixture, request, leaseFixture.identity()); + var service = + new WorldCanonicalInstanceActivationService( + new WorldCanonicalInstanceActivationRepository( + dsl, manager, fixture.lifecycleRepository())); + AtomicInteger heldChecks = new AtomicInteger(); + AtomicLong activationBackendPid = new AtomicLong(); + CountDownLatch activationAtCas = new CountDownLatch(1); + CountDownLatch continueActivation = new CountDownLatch(1); + CountDownLatch lockHeld = new CountDownLatch(1); + CountDownLatch releaseLock = new CountDownLatch(1); + var held = + new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() { + if (heldChecks.incrementAndGet() == 2) { + activationBackendPid.set( + Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Long.class)); + activationAtCas.countDown(); + await(continueActivation); + } + } + + public void close() {} + }; + var execution = fixture.preparing().request(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future activationFuture = + executor.submit( + () -> { + try { + return service.activateProtected(protection, held); + } catch (RuntimeException failure) { + return failure; + } + }); + await(activationAtCas); + Future lockHolder = + executor.submit( + () -> + ownerTransaction() + .execute( + status -> { + dsl.fetchOne( + "SELECT world_lock_canonical_instance_execution(?,?,?,?)", + execution.targetNamespace(), + execution.canonicalTenantId(), + execution.controlPlaneRequestId(), + execution.canonicalGameInstanceId()); + lockHeld.countDown(); + await(releaseLock); + return null; + })); + await(lockHeld); + continueActivation.countDown(); + awaitPostgresAdvisoryLockWait(activationBackendPid.get()); + long millisUntilExpiry = + Math.max(0L, Duration.between(Instant.now(), leaseFixture.leaseExpiresAt()).toMillis()); + Thread.sleep(millisUntilExpiry + 250L); + releaseLock.countDown(); + + Object outcome = activationFuture.get(45, TimeUnit.SECONDS); + assertThat(outcome) + .isInstanceOf(WorldCanonicalInstanceActivationService.ActivationDeniedException.class); + assertThat((RuntimeException) outcome) + .hasMessageContaining("lease expired before World activation admission"); + assertThat(activationOperationCountForRequest(request.activationRequestId())).isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_state FROM world_canonical_instance_activation_fence WHERE activation_request_id=?", + request.activationRequestId())) + .get("operation_state", String.class)) + .isEqualTo("PENDING"); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(fixture.preparing()); + + var aborted = service.abortProtected(protection, "POSITIVE_ABORT_AFTER_LEASE_EXPIRY"); + assertThat(aborted.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.ABORTED); + assertThat(service.readTerminalEvidence(protection).orElseThrow().canonicalBytes()) + .containsExactly(aborted.canonicalBytes()); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(fixture.preparing()); + assertThat(lockHolder.isDone()).isTrue(); + } finally { + continueActivation.countDown(); + releaseLock.countDown(); + executor.shutdownNow(); + } + assertOrigin(); + } + + @Test + void canonicalActivationRequestOnlyTransportRequiresGameSessionAndCannotDiscloseProtectedResult() throws Exception { PreparedLifecycleFixture fixture = materializedLifecycleFixture(); var alternatePreparing = @@ -1959,17 +2287,16 @@ void canonicalActivationTransportRequiresGameSessionAndReplaysImmutableOwnerResu equivalentRetry.preparingEvidenceBytes(), originalRequest.preparingEvidenceBytes())) .isFalse(); - // This isolated fixture stipulates upstream held source/release/Account authority only; it is - // not live Account authorization. The socket independently proves Game Session mTLS identity, - // while World performs the actual lifecycle CAS and immutable operation write. + // The request-only transport remains a peer-authenticated legacy adapter, not an activation + // protection transport. The storage proof below uses complete synthetic Account evidence and + // a stipulated held authority; neither is live Account authorization. AtomicInteger authorityChecks = new AtomicInteger(); - var activationService = - canonicalActivationService( - fixture, - ignored -> { - authorityChecks.incrementAndGet(); - return stipulatedActivationAuthority(); - }); + WorldCanonicalInstanceActivationService.ActivationAuthorityVerifier verifier = + ignored -> { + authorityChecks.incrementAndGet(); + return stipulatedActivationAuthority(); + }; + var activationService = canonicalActivationService(fixture, verifier); var adapter = new WorldCanonicalInstanceActivationGrpcService(activationService, NAMESPACE); WorldPreparationTestWorkloadPki pki = WorldPreparationTestWorkloadPki.create(temporaryDirectory); @@ -1995,88 +2322,54 @@ void canonicalActivationTransportRequiresGameSessionAndReplaysImmutableOwnerResu assertThat(preparationRows(fixture.input().canonicalGameInstanceId())) .containsExactly(preparationBefore); + var protection = activationProtection(fixture, originalRequest); + var activationTerminal = + activationService.activateProtected(protection, verifier.verifyAndHold(originalRequest)); + var firstResult = activationTerminal.activationResult(); + assertThat(firstResult.outcome()) + .isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + assertThat(firstResult.request().preparingEvidenceBytes()) + .containsExactly(originalRequest.preparingEvidenceBytes()); + assertThat(firstResult.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(firstResult.lifecycleEvidence().lifecycleEpoch()) + .isEqualTo(fixture.preparing().lifecycleEpoch() + 1L); + assertThat(firstResult.lifecycleEvidence().rowVersion()) + .isEqualTo(fixture.preparing().rowVersion() + 1L); + assertThat(authorityChecks).hasValue(1); + assertThat(activationOperationCountForRequest(activationRequestId)).isEqualTo(1L); + assertThat(activationManifestCountForRequest(activationRequestId)).isZero(); + assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + + var repository = + new WorldCanonicalInstanceActivationRepository( + dsl, manager, fixture.lifecycleRepository()); + assertThat(repository.readResult(originalRequest)).isEmpty(); + assertThat(repository.readTerminalEvidence(protection).orElseThrow().canonicalBytes()) + .containsExactly(activationTerminal.canonicalBytes()); + var current = + fixture + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(fixture.readRequest())) + .orElseThrow(); + assertThat(current.lifecycleStatus()).isEqualTo("ACTIVE"); + assertThat(current.lifecycleEpoch()) + .isEqualTo(firstResult.lifecycleEvidence().lifecycleEpoch()); + assertThat(current.rowVersion()).isEqualTo(firstResult.lifecycleEvidence().rowVersion()); + try (var gameSession = activationTransportClient(transport, pki.clientProperties(GAME_SESSION_WORKLOAD_URI))) { - var firstResponse = gameSession.activate(wireRequest); - assertThat(firstResponse.getActivationRequestId()) - .isEqualTo(activationRequestId.toString()); - byte[] immutableResultBytes = firstResponse.getCanonicalResultBytes().toByteArray(); - var firstResult = WorldCanonicalInstanceActivation.Result.fromStored(immutableResultBytes); - assertThat(firstResult.outcome()) - .isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); - assertThat(firstResult.request().canonicalRequestBytes()) - .containsExactly(originalRequest.canonicalRequestBytes()); - assertThat(firstResult.request().preparingEvidenceBytes()) - .containsExactly(originalRequest.preparingEvidenceBytes()); - assertThat(firstResult.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); - assertThat(firstResult.lifecycleEvidence().lifecycleEpoch()) - .isEqualTo(fixture.preparing().lifecycleEpoch() + 1L); - assertThat(firstResult.lifecycleEvidence().rowVersion()) - .isEqualTo(fixture.preparing().rowVersion() + 1L); - assertThat(authorityChecks).hasValue(1); - assertThat(activationOperationCountForRequest(activationRequestId)).isEqualTo(1L); - assertThat(activationManifestCountForRequest(activationRequestId)).isZero(); - assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); - var storedResult = - new WorldCanonicalInstanceActivationRepository( - dsl, manager, fixture.lifecycleRepository()) - .readResult(originalRequest) - .orElseThrow(); - assertThat(storedResult.canonicalBytes()).containsExactly(immutableResultBytes); - - // A separate owner read with fresh correlation establishes current ACTIVE state; the - // immutable activation result remains the historical operation result. - var current = - fixture - .lifecycleRepository() - .read(lifecycleRequestWithFreshReadId(fixture.readRequest())) - .orElseThrow(); - assertThat(current.lifecycleStatus()).isEqualTo("ACTIVE"); - assertThat(current.lifecycleEpoch()) - .isEqualTo(firstResult.lifecycleEvidence().lifecycleEpoch()); - assertThat(current.rowVersion()).isEqualTo(firstResult.lifecycleEvidence().rowVersion()); - assertThat(current.request().readRequestId()) - .isNotEqualTo(firstResult.lifecycleEvidence().request().readRequestId()); - - var exactRetry = gameSession.activate(wireRequest); - assertThat(exactRetry.getCanonicalResultBytes().toByteArray()) - .containsExactly(immutableResultBytes); - var alternateCorrelationRetry = - gameSession.activate(activationTransportRequest(equivalentRetry)); - assertThat(alternateCorrelationRetry.getCanonicalResultBytes().toByteArray()) - .containsExactly(immutableResultBytes); - assertThat(authorityChecks).hasValue(1); - assertThat( - WorldCanonicalInstanceActivation.Result.fromStored( - alternateCorrelationRetry.getCanonicalResultBytes().toByteArray()) - .request() - .preparingEvidenceBytes()) - .containsExactly(originalRequest.preparingEvidenceBytes()); - - var changedExpectedVersion = - new WorldCanonicalInstanceLifecycleEvidence( - fixture.preparing().request(), - fixture.preparing().launchBinding(), - fixture.preparing().startLocation(), - fixture.preparing().runtimeRoomInstanceId(), - "PREPARING", - fixture.preparing().lifecycleEpoch(), - fixture.preparing().rowVersion() + 1L, - fixture.preparing().captureId(), - fixture.preparing().graphSha256(), - fixture.preparing().preparationInputDigest(), - fixture.preparing().operationalRegionAssignments()); - // Reusing the same operation ID with a changed normalized expected version is a conflict - // probe, not evidence that the persisted PREPARING row had that version. - var changedRequest = - new WorldCanonicalInstanceActivation.Request( - activationRequestId, changedExpectedVersion); - assertThatThrownBy(() -> gameSession.activate(activationTransportRequest(changedRequest))) + assertThatThrownBy(() -> gameSession.activate(wireRequest)) .isInstanceOf(StatusRuntimeException.class) .satisfies( error -> assertThat(((StatusRuntimeException) error).getStatus().getCode()) - .isEqualTo(Status.Code.ALREADY_EXISTS)); + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThatThrownBy(() -> gameSession.activate(activationTransportRequest(equivalentRetry))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(((StatusRuntimeException) error).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(authorityChecks).hasValue(1); assertThat(activationOperationCountForRequest(activationRequestId)).isEqualTo(1L); assertThat(activationManifestCountForRequest(activationRequestId)).isZero(); @@ -2105,24 +2398,41 @@ void canonicalActivationTransportRequiresGameSessionAndReplaysImmutableOwnerResu void canonicalActivationStoresStaleFailedOutcomeAndFreshLifecycleReadRemainsCurrent() { PreparedLifecycleFixture fixture = materializedLifecycleFixture(); var service = canonicalActivationService(fixture, ignored -> stipulatedActivationAuthority()); - var firstRequest = - new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); - var current = service.activate(firstRequest); - assertThat(current.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); - assertThat(current.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); + var stalePreparing = + new WorldCanonicalInstanceLifecycleEvidence( + fixture.preparing().request(), + fixture.preparing().launchBinding(), + fixture.preparing().startLocation(), + fixture.preparing().runtimeRoomInstanceId(), + "PREPARING", + fixture.preparing().lifecycleEpoch(), + fixture.preparing().rowVersion() + 1L, + fixture.preparing().captureId(), + fixture.preparing().graphSha256(), + fixture.preparing().preparationInputDigest(), + fixture.preparing().operationalRegionAssignments()); var staleRequest = - new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); - - var aborted = service.activate(staleRequest); + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), stalePreparing); + var protection = activationProtection(fixture, staleRequest); + var aborted = + service.activateProtected(protection, stipulatedActivationAuthority()).activationResult(); assertThat(aborted.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.ABORTED); assertThat(aborted.terminalCode()).isEqualTo("PRECONDITION_FAILED"); assertThat(aborted.lifecycleEvidence().canonicalBytes()) - .containsExactly(current.lifecycleEvidence().canonicalBytes()); + .containsExactly(fixture.preparing().canonicalBytes()); assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) - .isEqualTo(current.lifecycleEvidence()); - assertThat(service.activate(staleRequest).canonicalBytes()) + .isEqualTo(fixture.preparing()); + assertThat( + service + .activateProtected(protection, stipulatedActivationAuthority()) + .activationResult() + .canonicalBytes()) .containsExactly(aborted.canonicalBytes()); + assertThat(service.readTerminalEvidence(protection).orElseThrow().outcome()) + .isEqualTo(WorldCanonicalInstanceActivation.Outcome.ABORTED); + assertThatThrownBy(() -> service.activate(staleRequest)) + .isInstanceOf(WorldCanonicalInstanceActivationService.ActivationDeniedException.class); assertThat(activationOperationCountForRequest(staleRequest.activationRequestId())) .isEqualTo(1L); assertThat(activationManifestCountForRequest(staleRequest.activationRequestId())).isZero(); @@ -2134,10 +2444,10 @@ void canonicalInitialAdmissionHoldAcquiresFromRealActiveLifecycleAndRetainsPendi PreparedLifecycleFixture fixture = materializedLifecycleFixture(); // World storage/CAS is real; upstream activation authority remains an isolated fixture. var activation = - canonicalActivationService(fixture, ignored -> stipulatedActivationAuthority()) - .activate( - new WorldCanonicalInstanceActivation.Request( - UUID.randomUUID(), fixture.preparing())); + activateProtected( + fixture, + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()), + ignored -> stipulatedActivationAuthority()); assertThat(activation.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); assertThat(activation.lifecycleEvidence().lifecycleStatus()).isEqualTo("ACTIVE"); @@ -2248,10 +2558,11 @@ void canonicalInitialAdmissionHoldAcquiresFromRealActiveLifecycleAndRetainsPendi PreparedLifecycleFixture closedFixture = materializedLifecycleFixture(); var closedActivation = - canonicalActivationService(closedFixture, ignored -> stipulatedActivationAuthority()) - .activate( - new WorldCanonicalInstanceActivation.Request( - UUID.randomUUID(), closedFixture.preparing())); + activateProtected( + closedFixture, + new WorldCanonicalInstanceActivation.Request( + UUID.randomUUID(), closedFixture.preparing()), + ignored -> stipulatedActivationAuthority()); assertThat(closedActivation.outcome()) .isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); var closedActive = @@ -2367,10 +2678,10 @@ void canonicalHoldReconciliationUsesTypedBoundedPagesAndLegacyFinderExcludesType PreparedLifecycleFixture fixture = materializedLifecycleFixture(); // World lifecycle/association and hold storage are real; activation authority is stipulated. var activation = - canonicalActivationService(fixture, ignored -> stipulatedActivationAuthority()) - .activate( - new WorldCanonicalInstanceActivation.Request( - UUID.randomUUID(), fixture.preparing())); + activateProtected( + fixture, + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()), + ignored -> stipulatedActivationAuthority()); assertThat(activation.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); var active = fixture @@ -2540,6 +2851,8 @@ void canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas( net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( mapper.writeValueAsString(normalizedRequest)); String forgedRequestDigest = sha256Digest(forgedRequestBytes); + var protection = activationProtection(fixture, activationRequest); + retainPendingActivationIntent(fixture, protection); var forgedActive = (tools.jackson.databind.node.ObjectNode) mapper.readTree(forgedPreparingBytes); @@ -2594,7 +2907,8 @@ void canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas( activationRequest.expectedRowVersion() + 1L, forgedResultBytes, sha256Digest(forgedResultBytes))) - .hasMessageContaining("differs from immutable World association"); + .hasMessageContaining( + "lacks its exact pending Account-protected operation fence"); dsl.execute("ROLLBACK TO SAVEPOINT forged_world_activation"); // V35's reserved-tenant guard denies a raw write without an activation manifest. dsl.execute("SAVEPOINT forged_active_cas"); @@ -2621,56 +2935,61 @@ void canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas( assertThat(lifecycle.lifecycleStatus()).isEqualTo("PREPARING"); assertThat(lifecycle.lifecycleEpoch()).isEqualTo(activationRequest.expectedLifecycleEpoch()); assertThat(lifecycle.rowVersion()).isEqualTo(activationRequest.expectedRowVersion()); + assertThat( + new WorldCanonicalInstanceActivationService( + new WorldCanonicalInstanceActivationRepository( + dsl, manager, fixture.lifecycleRepository())) + .abortProtected(protection, "FORGED_OWNER_PROOF_REJECTED") + .outcome()) + .isEqualTo(WorldCanonicalInstanceActivation.Outcome.ABORTED); assertOrigin(); } @Test - void lostHeldAuthorityAfterOperationInsertRollsBackActivationAndLedger() { + void lostHeldAuthorityLeavesPendingIntentThatOnlyFencedAbortCanClose() { PreparedLifecycleFixture fixture = materializedLifecycleFixture(); var request = new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var protection = activationProtection(fixture, request); AtomicBoolean lossInjectedAfterOperationInsert = new AtomicBoolean(); - var service = - canonicalActivationService( - fixture, - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { - public void requireHeld() { - if (!TransactionSynchronizationManager.isActualTransactionActive()) return; - long operationCount = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", - request.activationRequestId())) - .get(0, Long.class); - long manifestCount = - activationManifestCountForRequest(request.activationRequestId()); - if (operationCount != 1L || manifestCount != 1L) return; - - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - var lifecycleRow = - dsl.fetchOne( - "SELECT status, lifecycle_epoch, row_version FROM world_instance WHERE id=?", - fixture.materialized().association().worldInstanceId()); - assertThat(lifecycleRow).isNotNull(); - assertThat(lifecycleRow.get("status", String.class)).isEqualTo("PREPARING"); - assertThat(lifecycleRow.get("lifecycle_epoch", Long.class)) - .isEqualTo(request.expectedLifecycleEpoch()); - assertThat(lifecycleRow.get("row_version", Long.class)) - .isEqualTo(request.expectedRowVersion()); - assertThat(operationCount).isEqualTo(1L); - assertThat(manifestCount).isEqualTo(1L); - lossInjectedAfterOperationInsert.set(true); - throw new IllegalStateException("stipulated activation authority loss"); - } + WorldCanonicalInstanceActivationService.ActivationAuthorityVerifier verifier = + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) return; + long operationCount = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + request.activationRequestId())) + .get(0, Long.class); + long manifestCount = activationManifestCountForRequest(request.activationRequestId()); + if (operationCount != 1L || manifestCount != 1L) return; + + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + var lifecycleRow = + dsl.fetchOne( + "SELECT status, lifecycle_epoch, row_version FROM world_instance WHERE id=?", + fixture.materialized().association().worldInstanceId()); + assertThat(lifecycleRow).isNotNull(); + assertThat(lifecycleRow.get("status", String.class)).isEqualTo("PREPARING"); + assertThat(lifecycleRow.get("lifecycle_epoch", Long.class)) + .isEqualTo(request.expectedLifecycleEpoch()); + assertThat(lifecycleRow.get("row_version", Long.class)) + .isEqualTo(request.expectedRowVersion()); + assertThat(operationCount).isEqualTo(1L); + assertThat(manifestCount).isEqualTo(1L); + lossInjectedAfterOperationInsert.set(true); + throw new IllegalStateException("stipulated activation authority loss"); + } - public void close() {} - }; - }); + public void close() {} + }; + }; + var service = canonicalActivationService(fixture, verifier); - assertThatThrownBy(() -> service.activate(request)) + assertThatThrownBy(() -> service.activateProtected(protection, verifier.verifyAndHold(request))) .hasMessageContaining("stipulated activation authority loss"); assertThat(lossInjectedAfterOperationInsert).isTrue(); var current = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); @@ -2686,48 +3005,97 @@ public void close() {} .isZero(); assertThat(activationManifestCountForRequest(request.activationRequestId())).isZero(); assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_state FROM world_canonical_instance_activation_fence WHERE activation_request_id=?", + request.activationRequestId())) + .get("operation_state", String.class)) + .isEqualTo("PENDING"); + assertThat(service.readTerminalEvidence(protection)).isEmpty(); + assertThatThrownBy(() -> service.activateProtected(protection, stipulatedActivationAuthority())) + .isInstanceOf(WorldCanonicalInstanceActivationService.ActivationDeniedException.class) + .hasMessageContaining("existing pending World activation intent cannot be restarted"); + assertThat(activationOperationCountForRequest(request.activationRequestId())).isZero(); + + var aborted = service.abortProtected(protection, "POSITIVE_FENCED_ABORT"); + assertThat(aborted.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.ABORTED); + assertThat(aborted.activationResult().terminalCode()).isEqualTo("POSITIVE_FENCED_ABORT"); + assertThat(activationOperationCountForRequest(request.activationRequestId())).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_state FROM world_canonical_instance_activation_fence WHERE activation_request_id=?", + request.activationRequestId())) + .get("operation_state", String.class)) + .isEqualTo("ABORTED"); + assertThat( + service + .activateProtected(protection, stipulatedActivationAuthority()) + .activationResult() + .canonicalBytes()) + .containsExactly(aborted.activationResult().canonicalBytes()); + + var laterRequest = + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), fixture.preparing()); + var laterProtection = activationProtection(fixture, laterRequest); + assertThatThrownBy( + () -> service.activateProtected(laterProtection, stipulatedActivationAuthority())) + .isInstanceOf(RuntimeException.class); + assertThat(activationOperationCountForRequest(laterRequest.activationRequestId())).isZero(); + assertThat(fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow()) + .isEqualTo(fixture.preparing()); assertOrigin(); } @Test void activationExecutionManifestRequiresExactTransactionInstanceAndRowSnapshots() { PreparedLifecycleFixture fixture = materializedLifecycleFixture(); + var proof = rawCommittedActivationProof(fixture); + var protection = activationProtection(fixture, proof.request()); + retainPendingActivationIntent(fixture, protection); String exactUpdate = "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + "row_version=row_version+1,updated_at=CURRENT_TIMESTAMP WHERE id=?"; assertActivationManifestMismatch( fixture, + proof, "activation_manifest_wrong_tx", "UPDATE world_canonical_activation_execution_manifest SET transaction_id=transaction_id+1 " + "WHERE activation_request_id=?", exactUpdate); assertActivationManifestMismatch( fixture, + proof, "activation_manifest_wrong_instance", "UPDATE world_canonical_activation_execution_manifest SET world_instance_id=world_instance_id+1 " + "WHERE activation_request_id=?", exactUpdate); assertActivationManifestMismatch( fixture, + proof, "activation_manifest_extra_old_field", "UPDATE world_canonical_activation_execution_manifest SET expected_old=expected_old || '{\"extra\":true}'::JSONB " + "WHERE activation_request_id=?", exactUpdate); assertActivationManifestMismatch( fixture, + proof, "activation_manifest_extra_new_field", "UPDATE world_canonical_activation_execution_manifest SET expected_new=expected_new || '{\"extra\":true}'::JSONB " + "WHERE activation_request_id=?", exactUpdate); assertActivationManifestMismatch( fixture, + proof, "activation_manifest_wrong_next_epoch", null, "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+2," + "row_version=row_version+1,updated_at=CURRENT_TIMESTAMP WHERE id=?"); assertActivationManifestMismatch( fixture, + proof, "activation_manifest_wrong_next_version", null, "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," @@ -2736,6 +3104,13 @@ void activationExecutionManifestRequiresExactTransactionInstanceAndRowSnapshots( var current = fixture.lifecycleRepository().read(fixture.readRequest()).orElseThrow(); assertThat(current).isEqualTo(fixture.preparing()); assertThat(activationManifestCount(fixture.input().canonicalGameInstanceId())).isZero(); + assertThat( + new WorldCanonicalInstanceActivationService( + new WorldCanonicalInstanceActivationRepository( + dsl, manager, fixture.lifecycleRepository())) + .abortProtected(protection, "MANIFEST_MUTATION_PROOFS_COMPLETE") + .outcome()) + .isEqualTo(WorldCanonicalInstanceActivation.Outcome.ABORTED); assertOrigin(); } @@ -5170,10 +5545,10 @@ private AccountPublicationAuthorizationBinding isolatedPublicationAccountBinding ActivePlayerAdmissionFixture activePlayerAdmissionFixture() { var prepared = materializedLifecycleFixture(); var activation = - canonicalActivationService(prepared, ignored -> stipulatedActivationAuthority()) - .activate( - new WorldCanonicalInstanceActivation.Request( - UUID.randomUUID(), prepared.preparing())); + activateProtected( + prepared, + new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), prepared.preparing()), + ignored -> stipulatedActivationAuthority()); assertThat(activation.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); var current = prepared @@ -5222,6 +5597,45 @@ private PreparedLifecycleFixture materializedLifecycleFixture() { input, materialized, lifecycleRepository, readRequest, preparing); } + private LeaseBoundPreparedLifecycleFixture materializedLifecycleFixtureWithLease( + Duration validFor) { + Fixture f = fixture(); + var original = application(generationFreePlan(f)); + var selectedRoom = + original.plan().graph().nodes().stream() + .filter( + node -> + node.mutation().getAggregateType() + == WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) + .map(node -> node.templateId()) + .toList() + .getLast(); + var applied = withStartRoom(original, selectedRoom); + appliedComponent().apply(applied); + var frozen = captureForTerminal(applied.plan(), applied.operation().accountBindingBytes()); + var selector = + publishedEvidence( + publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = preparationInput(f, frozen, selector); + // Start the finite source lease immediately before the real preparation/owner write. + Instant expiresAt = Instant.now().plus(validFor); + var identity = WorldCanonicalInstanceExecutionTestFixtures.identity(input, expiresAt); + var operationInput = WorldCanonicalInstanceExecutionTestFixtures.operationInput(identity); + var materialized = preparationComponent(preparationRepository()).prepare(input, operationInput); + var lifecycleRepository = + new WorldCanonicalInstanceLifecycleReadRepository(dsl, manager, associationRepository()); + var readRequest = lifecycleReadRequest(input); + var preparing = lifecycleRepository.read(readRequest).orElseThrow(); + assertThat(preparing.lifecycleStatus()).isEqualTo("PREPARING"); + assertThat(preparing.startLocation().roomTemplateId()).isEqualTo(selectedRoom); + assertThat(preparing.runtimeRoomInstanceId()).isEqualTo(materialized.runtimeRoomInstanceId()); + return new LeaseBoundPreparedLifecycleFixture( + new PreparedLifecycleFixture( + input, materialized, lifecycleRepository, readRequest, preparing), + identity, + expiresAt); + } + /** Actual materialization and activation with only upstream owner authority stipulated. */ private PlacementFixture initialPlayerLocationFixture() { return initialPlayerLocationFixture(InitialAdmissionOrigin.NO_PRIOR_POINTER); @@ -5230,10 +5644,11 @@ private PlacementFixture initialPlayerLocationFixture() { private PlacementFixture initialPlayerLocationFixture(InitialAdmissionOrigin origin) { PreparedLifecycleFixture lifecycleFixture = materializedLifecycleFixture(); var activation = - canonicalActivationService(lifecycleFixture, ignored -> stipulatedActivationAuthority()) - .activate( - new WorldCanonicalInstanceActivation.Request( - UUID.randomUUID(), lifecycleFixture.preparing())); + activateProtected( + lifecycleFixture, + new WorldCanonicalInstanceActivation.Request( + UUID.randomUUID(), lifecycleFixture.preparing()), + ignored -> stipulatedActivationAuthority()); assertThat(activation.outcome()).isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); var activeEvidence = lifecycleFixture @@ -5535,8 +5950,262 @@ private WorldCanonicalInstanceActivationService canonicalActivationService( verifier); } + private WorldCanonicalInstanceActivation.Result activateProtected( + PreparedLifecycleFixture fixture, + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceActivationService.ActivationAuthorityVerifier verifier) { + var protection = activationProtection(fixture, request); + var held = verifier.verifyAndHold(request); + return new WorldCanonicalInstanceActivationService( + new WorldCanonicalInstanceActivationRepository( + dsl, manager, fixture.lifecycleRepository())) + .activateProtected(protection, held) + .activationResult(); + } + + private void retainPendingActivationIntent( + PreparedLifecycleFixture fixture, + AccountStartSessionActivationProtectionEvidence protection) { + AtomicInteger heldChecks = new AtomicInteger(); + var held = + new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() { + if (heldChecks.incrementAndGet() == 2) { + throw new IllegalStateException("stipulated crash after pending intent retention"); + } + } + + public void close() {} + }; + assertThatThrownBy( + () -> + new WorldCanonicalInstanceActivationService( + new WorldCanonicalInstanceActivationRepository( + dsl, manager, fixture.lifecycleRepository())) + .activateProtected(protection, held)) + .hasMessageContaining("stipulated crash after pending intent retention"); + UUID activationId = protection.request().worldActivationRequest().activationRequestId(); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_state FROM world_canonical_instance_activation_fence WHERE activation_request_id=?", + activationId)) + .get("operation_state", String.class)) + .isEqualTo("PENDING"); + assertThat(activationOperationCountForRequest(activationId)).isZero(); + } + + private AccountStartSessionActivationProtectionEvidence activationProtection( + PreparedLifecycleFixture fixture, WorldCanonicalInstanceActivation.Request request) { + return activationProtection( + fixture, + request, + request.preparing().request().readRequestId(), + fixture.input().gameSessionReadRequest().readRequestId(), + fixture.materialized().association().identity().canonicalRealmId(), + fixture.materialized().association().identity().catalogRevision(), + Instant.parse("2026-10-10T12:00:00Z"), + "7".repeat(64), + List.of(activationSource(fixture, SourceKind.ACCOUNT))); + } + + private AccountStartSessionActivationProtectionEvidence activationProtection( + PreparedLifecycleFixture fixture, + WorldCanonicalInstanceActivation.Request request, + WorldCanonicalInstanceExecutionIdentity identity) { + return activationProtection( + fixture, + request, + request.preparing().request().readRequestId(), + fixture.input().gameSessionReadRequest().readRequestId(), + fixture.materialized().association().identity().canonicalRealmId(), + fixture.materialized().association().identity().catalogRevision(), + Instant.parse("2026-10-10T12:00:00Z"), + "7".repeat(64), + List.of(activationSource(fixture, SourceKind.ACCOUNT)), + identity); + } + + private AccountStartSessionActivationProtectionEvidence activationProtection( + PreparedLifecycleFixture fixture, + WorldCanonicalInstanceActivation.Request originalRequest, + UUID worldReadRequestId, + UUID gameSessionReadRequestId, + UUID realmId, + long catalogRevision, + Instant acquiredAt, + String captureSnapshotDigest, + List sourceVector) { + return activationProtection( + fixture, + originalRequest, + worldReadRequestId, + gameSessionReadRequestId, + realmId, + catalogRevision, + acquiredAt, + captureSnapshotDigest, + sourceVector, + WorldCanonicalInstanceExecutionTestFixtures.identity(fixture.input())); + } + + private AccountStartSessionActivationProtectionEvidence activationProtection( + PreparedLifecycleFixture fixture, + WorldCanonicalInstanceActivation.Request originalRequest, + UUID worldReadRequestId, + UUID gameSessionReadRequestId, + UUID realmId, + long catalogRevision, + Instant acquiredAt, + String captureSnapshotDigest, + List sourceVector, + WorldCanonicalInstanceExecutionIdentity identity) { + var preparation = originalRequest.preparing(); + var originalWorldRequest = preparation.request(); + var worldReadRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + originalWorldRequest.schemaVersion(), + worldReadRequestId, + originalWorldRequest.targetNamespace(), + originalWorldRequest.canonicalTenantId(), + originalWorldRequest.worldSlug(), + originalWorldRequest.canonicalGameInstanceId(), + originalWorldRequest.playableStateNamespaceId(), + originalWorldRequest.playableStateScope(), + originalWorldRequest.publicProduction(), + originalWorldRequest.controlPlaneRequestId(), + originalWorldRequest.canonicalVersionId(), + originalWorldRequest.expectedDescriptorRequestDigest(), + originalWorldRequest.expectedDescriptorResultDigest(), + originalWorldRequest.expectedReleaseAttestationDigest()); + var retryPreparing = + new WorldCanonicalInstanceLifecycleEvidence( + worldReadRequest, + preparation.launchBinding(), + preparation.startLocation(), + preparation.runtimeRoomInstanceId(), + preparation.lifecycleStatus(), + preparation.lifecycleEpoch(), + preparation.rowVersion(), + preparation.captureId(), + preparation.graphSha256(), + preparation.preparationInputDigest(), + preparation.operationalRegionAssignments()); + var worldActivation = + new WorldCanonicalInstanceActivation.Request( + originalRequest.activationRequestId(), retryPreparing); + + var tupleBytes = identity.originalPostAuthorizationTuple(); + var tuple = identity.decodedTuple(); + var worldRead = fixture.input().gameSessionReadRequest(); + var launchRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + gameSessionReadRequestId, + worldRead.targetNamespace(), + worldRead.canonicalTenantId(), + worldRead.worldSlug(), + worldRead.canonicalGameInstanceId(), + worldRead.controlPlaneRequestId(), + worldRead.launchDescriptorId(), + worldRead.expectedDescriptorRequestDigest(), + worldRead.expectedDescriptorResultDigest(), + worldRead.expectedReleaseAttestationEvidenceDigest()); + var launchResult = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + launchRequest, + fixture.materialized().association().identity().playableStateNamespaceId(), + RealmEntryPolicy.StateScope.SHARED, + true, + realmId, + catalogRevision, + CurrentGameInstanceStatus.STARTING, + 0L, + retryPreparing.launchBinding()); + var fullLaunchRequest = + new OriginalStartSessionLaunchReadEvidence.Request(launchRequest, tupleBytes); + var fullLaunchResult = + new OriginalStartSessionLaunchReadEvidence.Result( + fullLaunchRequest, launchResult, tupleBytes); + var accountRequest = + AccountStartSessionActivationProtectionRequest.create( + tupleBytes, + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + identity.gameSessionOwnerMutationId(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.originalGameSessionLeaseExpiresAt(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + fullLaunchResult, + worldActivation); + byte[] capture = activationCaptureReference(tuple, captureSnapshotDigest); + UUID protectionId = + UUID.nameUUIDFromBytes( + ("world-activation-protection:" + originalRequest.activationRequestId()) + .getBytes(StandardCharsets.UTF_8)); + return AccountStartSessionActivationProtectionEvidence.create( + accountRequest, protectionId, 1L, acquiredAt, capture, sha256Hex(capture), sourceVector); + } + + private SourceEvidence activationSource(PreparedLifecycleFixture fixture, SourceKind kind) { + var identity = WorldCanonicalInstanceExecutionTestFixtures.identity(fixture.input()); + String scopeId = + switch (kind) { + case ACCOUNT -> + identity.decodedTuple().preAuthorizationTuple().actor().accountId().toString(); + case TENANT -> + fixture.materialized().association().identity().canonicalTenantId().toString(); + default -> throw new IllegalArgumentException("Unsupported activation source kind"); + }; + return new SourceEvidence( + kind, + scopeId, + "1", + "1", + null, + null, + identity.accountWorldParticipationId().toString().getBytes(StandardCharsets.UTF_8)); + } + + private byte[] activationCaptureReference( + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple tuple, + String snapshotDigest) { + Map value = + Map.of( + "schema", + "account-start-session-authority-capture/v1", + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "capturedAt", + "2026-10-10T12:00:00.000Z", + "bundleReference", + Map.of( + "bundleVersion", tuple.bundleReference().bundleVersion(), + "sourceVersion", tuple.bundleReference().sourceVersion(), + "sourceFence", tuple.bundleReference().sourceFence(), + "linearization", tuple.bundleReference().linearization()), + "snapshotSha256", + snapshotDigest); + try { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + mapper.writeValueAsString(value)); + } catch (java.io.IOException malformed) { + throw new IllegalStateException( + "Synthetic activation capture reference is invalid", malformed); + } + } + + private static String sha256Hex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + private void assertActivationManifestMismatch( PreparedLifecycleFixture fixture, + ActivationProof proof, String savepoint, String manifestTamperSql, String attemptedUpdateSql) { @@ -5544,7 +6213,6 @@ private void assertActivationManifestMismatch( .execute( status -> { dsl.execute("SAVEPOINT " + savepoint); - var proof = rawCommittedActivationProof(fixture); insertRawActivationOperation( proof, fixture.materialized().association().worldInstanceId()); if (manifestTamperSql != null) { @@ -8260,6 +8928,38 @@ private static void await(CountDownLatch latch) { } } + private static WorldCanonicalInstanceActivationService.HeldActivationAuthority + barrierActivationAuthority(CountDownLatch barrier) { + AtomicBoolean firstCheck = new AtomicBoolean(true); + return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() { + if (firstCheck.compareAndSet(true, false)) { + barrier.countDown(); + await(barrier); + } + } + + public void close() {} + }; + } + + private void awaitPostgresAdvisoryLockWait(long backendPid) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + boolean waiting = false; + do { + Record result = + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_locks WHERE pid=? AND locktype='advisory' AND NOT granted) AS waiting", + backendPid); + waiting = result != null && Boolean.TRUE.equals(result.get("waiting", Boolean.class)); + if (waiting) return; + Thread.sleep(25L); + } while (System.nanoTime() < deadline); + assertThat(waiting) + .as("activation backend must be waiting for the serialized owner lock") + .isTrue(); + } + private static final class PreparationCollector implements StreamObserver { private PrepareCanonicalWorldInstanceResponse value; @@ -8382,6 +9082,11 @@ private record PreparedLifecycleFixture( WorldCanonicalInstanceLifecycleEvidence.Request readRequest, WorldCanonicalInstanceLifecycleEvidence preparing) {} + private record LeaseBoundPreparedLifecycleFixture( + PreparedLifecycleFixture fixture, + WorldCanonicalInstanceExecutionIdentity identity, + Instant leaseExpiresAt) {} + /** Ephemeral identities for the physical World terminal-read mTLS boundary only. */ private static final class WorldTerminalReadTestPki { private final Path caCertificate; diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldProtectedActivationAcquisitionMatchTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldProtectedActivationAcquisitionMatchTest.java new file mode 100644 index 0000000000..a4a14f89b2 --- /dev/null +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldProtectedActivationAcquisitionMatchTest.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import org.junit.jupiter.api.Test; + +/** + * Direct comparison tests for the terminal-first request identity; no database or authentication is + * implied. + */ +class WorldProtectedActivationAcquisitionMatchTest { + @Test + void acceptsOnlyTheStableOriginalTupleOwnerAttemptFenceAndPreparingIdentity() { + var input = + mock( + AccountStartSessionActivationProtectionAcquisitionInput.class, + org.mockito.Mockito.withSettings() + .defaultAnswer(org.mockito.Mockito.RETURNS_DEEP_STUBS)); + var evidence = + mock( + AccountStartSessionActivationProtectionEvidence.class, + org.mockito.Mockito.withSettings() + .defaultAnswer(org.mockito.Mockito.RETURNS_DEEP_STUBS)); + when(input.originalPostAuthorizationTuple()).thenReturn(new byte[] {1, 2, 3}); + when(input.gameSessionOwnerMutationId()) + .thenReturn(UUID.fromString("11111111-1111-4111-8111-111111111111")); + when(input.gameSessionOwnerAttemptId()) + .thenReturn(UUID.fromString("22222222-2222-4222-8222-222222222222")); + when(input.gameSessionOwnerFence()).thenReturn(5L); + when(input.worldActivationRequest().activationRequestId()) + .thenReturn(UUID.fromString("33333333-3333-4333-8333-333333333333")); + when(input.worldActivationRequest().canonicalRequestBytes()).thenReturn(new byte[] {4, 5, 6}); + + when(evidence.request().originalPostAuthorizationTupleBytes()).thenReturn(new byte[] {1, 2, 3}); + when(evidence.request().gameSessionOwnerMutationId()) + .thenReturn(UUID.fromString("11111111-1111-4111-8111-111111111111")); + when(evidence.request().gameSessionOwnerAttemptId()) + .thenReturn(UUID.fromString("22222222-2222-4222-8222-222222222222")); + when(evidence.request().gameSessionOwnerFence()).thenReturn(5L); + when(evidence.request().worldActivationRequest().activationRequestId()) + .thenReturn(UUID.fromString("33333333-3333-4333-8333-333333333333")); + when(evidence.request().worldActivationRequest().canonicalRequestBytes()) + .thenReturn(new byte[] {4, 5, 6}); + + assertThatCode( + () -> + WorldCanonicalInstanceActivationRepository.requireSameAcquisitionInput( + input, evidence)) + .doesNotThrowAnyException(); + + when(input.originalPostAuthorizationTuple()).thenReturn(new byte[] {9}); + assertThatThrownBy( + () -> + WorldCanonicalInstanceActivationRepository.requireSameAcquisitionInput( + input, evidence)) + .isInstanceOf(WorldCanonicalInstanceActivationRepository.ActivationConflictException.class) + .hasMessageContaining("changed its exact original caller acquisition statement"); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java index 2e741f40bf..8f6433409e 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java @@ -7,6 +7,7 @@ import java.nio.charset.StandardCharsets; import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; @@ -61,6 +62,19 @@ public void close() {} verifyNoInteractions(dsl, manager, lifecycle); } + @Test + void protectedActivationRecoveryRejectsAmbientTransactionBeforeAnyRead() { + var repository = new WorldCanonicalInstanceActivationRepository(dsl, manager, lifecycle); + var input = mock(AccountStartSessionActivationProtectionAcquisitionInput.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.readProtectedActivationByAcquisitionInput(input)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("must not join an ambient transaction"); + + verifyNoInteractions(dsl, manager, lifecycle); + } + private static WorldCanonicalInstanceActivation.Request request() { var lifecycleRequest = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); when(lifecycleRequest.canonicalGameInstanceId()) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java index be148c3177..524b1709bb 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java @@ -12,8 +12,11 @@ import java.nio.charset.StandardCharsets; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; import org.junit.jupiter.api.Test; @@ -31,7 +34,7 @@ void defaultVerifierDeniesNewOperationAfterReadOnlyLedgerMiss() { assertThatThrownBy(() -> service.activate(request)) .isInstanceOf(WorldCanonicalInstanceActivationService.ActivationDeniedException.class) - .hasMessageContaining("no authenticated current source/release"); + .hasMessageContaining("complete Account activation-purpose protection evidence"); verify(repository).readResult(request); verify(repository, never()).activate(eq(request), any()); @@ -56,32 +59,54 @@ void exactPriorResultReplaysWithoutConsultingCurrentAuthority() { } @Test - void aNewOperationChecksAndHoldsAuthorityOutsideTheOwnerTransaction() { + void retainedRequestOnlyVerifierCannotAuthorizeFreshActivation() { var repository = mock(WorldCanonicalInstanceActivationRepository.class); var request = request(); - var result = mock(WorldCanonicalInstanceActivation.Result.class); - var closed = new java.util.concurrent.atomic.AtomicBoolean(); + var verifierCalls = new AtomicInteger(); var service = new WorldCanonicalInstanceActivationService( repository, ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { - public void requireHeld() { - assertThat(closed.get()).isFalse(); - } - - public void close() { - closed.set(true); - } - }; + verifierCalls.incrementAndGet(); + throw new AssertionError("legacy request-only verifier cannot authorize a write"); }); when(repository.readResult(request)).thenReturn(Optional.empty()); - when(repository.activate(eq(request), any())).thenReturn(result); - assertThat(service.activate(request)).isSameAs(result); + assertThatThrownBy(() -> service.activate(request)) + .isInstanceOf(WorldCanonicalInstanceActivationService.ActivationDeniedException.class) + .hasMessageContaining("complete Account activation-purpose protection evidence"); + assertThat(verifierCalls).hasValue(0); + verify(repository).readResult(request); + verify(repository, never()).activate(eq(request), any()); + } + + @Test + void protectedOperationHoldsItsDistinctAuthorityAroundTheOwnerCas() { + var repository = mock(WorldCanonicalInstanceActivationRepository.class); + var protection = mock(AccountStartSessionActivationProtectionEvidence.class); + var terminal = mock(WorldOriginalStartSessionActivationTerminalEvidence.class); + var heldChecks = new AtomicInteger(); + var closed = new java.util.concurrent.atomic.AtomicBoolean(); + var held = + new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(closed.get()).isFalse(); + heldChecks.incrementAndGet(); + } + + public void close() { + closed.set(true); + } + }; + when(repository.activateProtected(eq(protection), any())).thenReturn(terminal); + var service = new WorldCanonicalInstanceActivationService(repository); + + assertThat(service.activateProtected(protection, held)).isSameAs(terminal); + + assertThat(heldChecks).hasValue(2); assertThat(closed.get()).isTrue(); - verify(repository).activate(eq(request), any()); + verify(repository).activateProtected(eq(protection), eq(held)); } private static WorldCanonicalInstanceActivation.Request request() { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcServiceTest.java new file mode 100644 index 0000000000..aca262e4a7 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcServiceTest.java @@ -0,0 +1,118 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionActivationTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalStartSessionActivationTerminalEvidenceRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalStartSessionActivationTerminalEvidenceResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Receiver denial ordering only; synthetic TLS context is not authenticated transport proof. */ +class WorldOriginalStartSessionActivationTerminalReadGrpcServiceTest { + @AfterEach + void clearContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsWrongOrMissingAccountPeerBeforeRequestDecodeOrOwnerRead() { + var owner = mock(WorldCanonicalInstanceActivationService.class); + var service = + new WorldOriginalStartSessionActivationTerminalReadGrpcService(owner, "world-runtime"); + + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + service, + null, + ReadOriginalStartSessionActivationTerminalEvidenceRequest.getDefaultInstance())); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke(service, peer("spiffe://firemud/ns/other-runtime/sa/account-service"), null)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke(service, peer("spiffe://firemud/ns/world-runtime/sa/game-session-service"), null)); + verifyNoInteractions(owner); + + assertCode( + Status.Code.INVALID_ARGUMENT, + invoke(service, peer("spiffe://firemud/ns/world-runtime/sa/account-service"), null)); + verifyNoInteractions(owner); + } + + @Test + void rejectsEndUserAndAmbientSqlBeforeDecodingOrOwnerRead() { + var owner = mock(WorldCanonicalInstanceActivationService.class); + var service = + new WorldOriginalStartSessionActivationTerminalReadGrpcService(owner, "world-runtime"); + SessionContext.setContext("authenticated-user", java.util.List.of(), java.util.Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke(service, peer("spiffe://firemud/ns/world-runtime/sa/account-service"), null)); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + invoke(service, peer("spiffe://firemud/ns/world-runtime/sa/account-service"), null)); + verifyNoInteractions(owner); + } + + private static FailureObservation invoke( + WorldOriginalStartSessionActivationTerminalReadGrpcService service, + GrpcPeerIdentity peer, + ReadOriginalStartSessionActivationTerminalEvidenceRequest request) { + var observer = new Collector(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.readOriginalStartSessionActivationTerminalEvidence(request, observer); + } finally { + context.detach(previous); + } + return new FailureObservation(observer.failureCode, observer.failureWasStatusRuntimeException); + } + + private static GrpcPeerIdentity peer(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, FailureObservation failure) { + assertThat(failure.failureWasStatusRuntimeException()).isTrue(); + assertThat(failure.failureCode()).isEqualTo(expected); + } + + private record FailureObservation( + Status.Code failureCode, boolean failureWasStatusRuntimeException) {} + + private static final class Collector + implements StreamObserver { + private Status.Code failureCode; + private boolean failureWasStatusRuntimeException; + + @Override + public void onNext(ReadOriginalStartSessionActivationTerminalEvidenceResponse value) {} + + @Override + public void onError(Throwable failure) { + failureCode = Status.fromThrowable(failure).getCode(); + failureWasStatusRuntimeException = failure instanceof StatusRuntimeException; + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcServiceTest.java new file mode 100644 index 0000000000..5dcd9a5dc7 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcServiceTest.java @@ -0,0 +1,124 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationService; +import net.firedevops.firemud.worldmanagement.v1.ActivateOriginalStartSessionProtectedRequest; +import net.firedevops.firemud.worldmanagement.v1.ActivateOriginalStartSessionProtectedResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Adapter authentication ordering only; synthetic peer contexts are not physical mTLS proof. */ +class WorldOriginalStartSessionProtectedActivationGrpcServiceTest { + @AfterEach + void clearContext() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsWrongOrMissingGameSessionPeerBeforeDecodeOrOwnerCalls() { + var owner = mock(WorldOriginalStartSessionProtectedActivationService.class); + var service = + new WorldOriginalStartSessionProtectedActivationGrpcService(owner, "world-runtime"); + var malformed = ActivateOriginalStartSessionProtectedRequest.getDefaultInstance(); + + assertCode(Status.Code.PERMISSION_DENIED, invoke(service, null, malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + service, peer("spiffe://firemud/ns/other-runtime/sa/game-session-service"), malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke(service, peer("spiffe://firemud/ns/world-runtime/sa/account-service"), malformed)); + verifyNoInteractions(owner); + } + + @Test + void rejectsEndUserAndAmbientTransactionBeforeDecodeOrOwnerCalls() { + var owner = mock(WorldOriginalStartSessionProtectedActivationService.class); + var service = + new WorldOriginalStartSessionProtectedActivationGrpcService(owner, "world-runtime"); + var caller = peer("spiffe://firemud/ns/world-runtime/sa/game-session-service"); + var malformed = ActivateOriginalStartSessionProtectedRequest.getDefaultInstance(); + + SessionContext.setContext("authenticated-user", java.util.List.of(), java.util.Map.of()); + assertCode(Status.Code.PERMISSION_DENIED, invoke(service, caller, malformed)); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(service, caller, malformed)); + verifyNoInteractions(owner); + } + + @Test + void exactWorkloadWithMalformedCarrierFailsBeforeOwnerOperation() { + var owner = mock(WorldOriginalStartSessionProtectedActivationService.class); + var service = + new WorldOriginalStartSessionProtectedActivationGrpcService(owner, "world-runtime"); + + assertCode( + Status.Code.INVALID_ARGUMENT, + invoke( + service, + peer("spiffe://firemud/ns/world-runtime/sa/game-session-service"), + ActivateOriginalStartSessionProtectedRequest.getDefaultInstance())); + verifyNoInteractions(owner); + } + + private static FailureObservation invoke( + WorldOriginalStartSessionProtectedActivationGrpcService service, + GrpcPeerIdentity peer, + ActivateOriginalStartSessionProtectedRequest request) { + var observer = new Collector(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.activateOriginalStartSessionProtected(request, observer); + } finally { + context.detach(previous); + } + return new FailureObservation(observer.failureCode, observer.failureWasStatusRuntimeException); + } + + private static GrpcPeerIdentity peer(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, FailureObservation failure) { + assertThat(failure.failureWasStatusRuntimeException()).isTrue(); + assertThat(failure.failureCode()).isEqualTo(expected); + } + + private record FailureObservation( + Status.Code failureCode, boolean failureWasStatusRuntimeException) {} + + private static final class Collector + implements StreamObserver { + private Status.Code failureCode; + private boolean failureWasStatusRuntimeException; + + @Override + public void onNext(ActivateOriginalStartSessionProtectedResponse value) {} + + @Override + public void onError(Throwable failure) { + failureCode = Status.fromThrowable(failure).getCode(); + failureWasStatusRuntimeException = failure instanceof StatusRuntimeException; + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java new file mode 100644 index 0000000000..2790aeb3af --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java @@ -0,0 +1,200 @@ +package unit.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.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionClient; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Mock-only ordering and retry tests; no authenticated Account or committed World DB is implied. + */ +class WorldOriginalStartSessionProtectedActivationServiceTest { + private final WorldCanonicalInstanceActivationRepository repository = + mock(WorldCanonicalInstanceActivationRepository.class); + private final WorldCanonicalInstanceActivationService activation = + mock(WorldCanonicalInstanceActivationService.class); + private final AccountStartSessionActivationProtectionAcquisitionClient account = + mock(AccountStartSessionActivationProtectionAcquisitionClient.class); + private final WorldOriginalStartSessionProtectedActivationService service = + new WorldOriginalStartSessionProtectedActivationService( + repository, activation, account, "world-runtime"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactHistoricalTerminalReturnsFirstReceiptWithoutFreshAccountAcquisition() { + var input = mock(AccountStartSessionActivationProtectionAcquisitionInput.class); + var terminal = mock(WorldOriginalStartSessionActivationTerminalEvidence.class); + doNothing().when(input).requireTargetNamespace("world-runtime"); + when(repository.readProtectedActivationByAcquisitionInput(input)) + .thenReturn( + Optional.of( + new WorldCanonicalInstanceActivationRepository.ProtectedActivationReadback( + false, terminal))); + + assertThat(service.activate(input)).isSameAs(terminal); + + verifyNoInteractions(account, activation); + } + + @Test + void existingPendingOperationNeverReacquiresOrRestarts() { + var input = mock(AccountStartSessionActivationProtectionAcquisitionInput.class); + doNothing().when(input).requireTargetNamespace("world-runtime"); + when(repository.readProtectedActivationByAcquisitionInput(input)) + .thenReturn( + Optional.of( + new WorldCanonicalInstanceActivationRepository.ProtectedActivationReadback( + true, null))); + + assertThatThrownBy(() -> service.activate(input)) + .isInstanceOf( + WorldOriginalStartSessionProtectedActivationService.PendingActivationException.class) + .hasMessageContaining("cannot reacquire authority or restart"); + + verifyNoInteractions(account, activation); + } + + @Test + void changedCallerIdentityConflictIsTerminalFirstAndDoesNotAcquireAccount() { + var input = mock(AccountStartSessionActivationProtectionAcquisitionInput.class); + doNothing().when(input).requireTargetNamespace("world-runtime"); + when(repository.readProtectedActivationByAcquisitionInput(input)) + .thenThrow( + new WorldCanonicalInstanceActivationRepository.ActivationConflictException( + "changed exact activation identity")); + + assertThatThrownBy(() -> service.activate(input)) + .isInstanceOf(WorldCanonicalInstanceActivationRepository.ActivationConflictException.class); + + verifyNoInteractions(account, activation); + } + + @Test + void ambientTransactionIsDeniedBeforeTerminalReadOrAccountAcquisition() { + var input = mock(AccountStartSessionActivationProtectionAcquisitionInput.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> service.activate(input)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an ambient owner transaction"); + + verifyNoInteractions(repository, account, activation); + } + + @Test + void absentOperationAcquiresAndComparesCompleteCallerBindingBeforeProtectedCas() { + var input = matchingInput(); + var protection = matchingEvidence(input); + var terminal = mock(WorldOriginalStartSessionActivationTerminalEvidence.class); + when(repository.readProtectedActivationByAcquisitionInput(input)).thenReturn(Optional.empty()); + when(account.acquire(input)).thenReturn(protection); + when(activation.activateProtected(eq(protection), any())) + .thenAnswer( + call -> { + WorldCanonicalInstanceActivationService.HeldActivationAuthority held = + call.getArgument(1); + held.requireHeld(); + held.close(); + assertThatThrownBy(held::requireHeld) + .isInstanceOf( + WorldCanonicalInstanceActivationService.ActivationDeniedException.class); + return terminal; + }); + + assertThat(service.activate(input)).isSameAs(terminal); + + verify(account).acquire(input); + verify(activation).activateProtected(eq(protection), any()); + verify(repository).readProtectedActivationByAcquisitionInput(input); + } + + @Test + void accountReceiptChangingOriginalTupleIsDeniedBeforeWorldWrite() { + var input = matchingInput(); + var protection = matchingEvidence(input); + when(repository.readProtectedActivationByAcquisitionInput(input)).thenReturn(Optional.empty()); + when(account.acquire(input)).thenReturn(protection); + when(protection.request().originalPostAuthorizationTupleBytes()).thenReturn(new byte[] {99}); + + assertThatThrownBy(() -> service.activate(input)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed the exact original activation acquisition binding"); + + verify(activation, never()).activateProtected(any(), any()); + } + + private static AccountStartSessionActivationProtectionAcquisitionInput matchingInput() { + var input = mock(AccountStartSessionActivationProtectionAcquisitionInput.class); + var request = mock(WorldCanonicalInstanceActivation.Request.class); + doNothing().when(input).requireTargetNamespace("world-runtime"); + when(input.originalPostAuthorizationTuple()).thenReturn(new byte[] {1, 2, 3}); + when(input.gameSessionOwnerMutationId()) + .thenReturn(UUID.fromString("11111111-1111-4111-8111-111111111111")); + when(input.gameSessionOwnerAttemptId()) + .thenReturn(UUID.fromString("22222222-2222-4222-8222-222222222222")); + when(input.gameSessionOwnerFence()).thenReturn(3L); + when(input.worldActivationRequest()).thenReturn(request); + when(request.activationRequestId()) + .thenReturn(UUID.fromString("33333333-3333-4333-8333-333333333333")); + when(request.canonicalRequestBytes()).thenReturn(new byte[] {4, 5, 6}); + return input; + } + + private static AccountStartSessionActivationProtectionEvidence matchingEvidence( + AccountStartSessionActivationProtectionAcquisitionInput input) { + var originalTuple = input.originalPostAuthorizationTuple(); + var ownerMutationId = input.gameSessionOwnerMutationId(); + var ownerAttemptId = input.gameSessionOwnerAttemptId(); + var ownerFence = input.gameSessionOwnerFence(); + var activationRequest = input.worldActivationRequest(); + var activationRequestId = activationRequest.activationRequestId(); + var activationRequestBytes = activationRequest.canonicalRequestBytes(); + var evidence = + mock( + AccountStartSessionActivationProtectionEvidence.class, + org.mockito.Mockito.withSettings() + .defaultAnswer(org.mockito.Mockito.RETURNS_DEEP_STUBS)); + when(evidence.request().originalPostAuthorizationTupleBytes()).thenReturn(originalTuple); + when(evidence.request().gameSessionOwnerMutationId()).thenReturn(ownerMutationId); + when(evidence.request().gameSessionOwnerAttemptId()).thenReturn(ownerAttemptId); + when(evidence.request().gameSessionOwnerFence()).thenReturn(ownerFence); + when(evidence + .request() + .originalTuple() + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace()) + .thenReturn("world-runtime"); + when(evidence.request().worldActivationRequest().activationRequestId()) + .thenReturn(activationRequestId); + when(evidence.request().worldActivationRequest().canonicalRequestBytes()) + .thenReturn(activationRequestBytes); + when(evidence.canonicalBytes()).thenReturn(new byte[] {7, 8, 9}); + return evidence; + } +} From 11ebb6e8f5a98267b7de53f4f5c3fa63c4bdf5bb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:17:44 +1300 Subject: [PATCH 106/129] Fix current-attempt fixture collision and preserve authored source proof --- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 6 +- ...onCurrentAttemptEvidenceGrpcCodecTest.java | 124 ----- ...licationExportPostgresIntegrationTest.java | 431 +++++++++++++++-- ...aphApplicationPostgresIntegrationTest.java | 451 ++++++++++++++++++ 5 files changed, 846 insertions(+), 172 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index fcb2554407..f44580a517 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -240,3 +240,9 @@ Entry format: - Observation: A revision guard proves concurrency safety, not payload completeness. Missing-field fallback must not be used for a required standing brief. - Expected pattern: Assert that `brief` is a nonempty string before constructing any replacement, and verify preserved content after publication. Use the exact stored revision for recovery rather than reconstructing instructions from memory. - Current status: Restored the complete revision-405 brief, including Overseer's new standing activation direction, through guarded revision 407. Readback matches the preserved text apart from one final newline; no implementation or authorization was lost. Overseer was notified. + +- `2026-10-11`: Reused local compilation can miss duplicate test-helper definitions + - Context: Exact-head PR #3105 CI run 38106738131 failed Common Platform compilation because two same-package test files both declared `CurrentAttemptTestData`, despite the preceding local combined gate passing with reused task outputs. + - Observation: The fixture bodies were semantically identical, but fresh javac rejects the duplicate class. The precise local incremental/cache mechanism is not established; a successful reused result did not establish fresh compilation of the combined source set. + - Expected pattern: Consolidate same-package helpers at one owner, and force the affected compilation after this kind of integration discrepancy without deleting caches or weakening tests. Distinguish reused local results from fresh CI execution. + - Current status: The redundant helper was removed while both tests retain the same canonical tuple. Forced Common Platform checks passed with 715 executed tests and no skips or failures; replacement exact-head CI remains a separate evidence requirement. 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 56ec622bb7..90ddad7715 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 @@ -6,11 +6,13 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Exact published source `a336f4245a46742bda991eba73addf31dcc689b5` has a confirmed Common Platform compilation failure in [Validation run 38106738131](https://github.com/benhook1013/FireMUD/actions/runs/38106738131): two same-package test files declared `CurrentAttemptTestData`. The duplicate fixture is removed without changing its tuple or assertions. Forced fresh Common Platform checks pass in 3 minutes 51 seconds, including 715 executed tests with zero skips, failures or errors; 28 of 29 tasks execute. Replacement exact-head CI remains a separate requirement. The preceding reused local results below did not establish that failed source's fresh CI compilation. + The activation/projection construction passes the corrected complete Common Platform, Account, Game Session, Game Design, World and Entity checks in 45 seconds across 287 tasks, with 25 executed and 262 up-to-date. Available corrected-state XML records 5,563 executed unit cases and 44 executed non-container integration/cross-service cases, with zero failures or errors; unchanged tasks reuse successful corrected-state results from the immediately preceding checks. There are 915 skips: 17 Game Session unit cases and 898 container-dependent integration/cross-service cases, including the genuine native composition and new migrations. Strict XML readback separately proves all three Game Session retention-ordering cases and all five Entity authored-core consumer cases executed without skips. Integration compilation, generated SQL metadata, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass; Flyway sanity passes 12 sets/312 versioned files, public gRPC method and proto-time contracts pass, and architecture contracts passed 228 checks before the final status-only wording. This is local code, unit and static proof, not physical migration, successful authenticated native activation/settlement, actual actor allocation/placement/delivery, or runtime readiness. -The current unregistered construction adds the distinct [Account activation-purpose protection](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), its immutable source vector and authenticated acquisition, protected World operation storage and [exact terminal readback](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-activation-protection), and append-only Account terminal settlement. Their complete authenticated producer/consumer composition and physical PostgreSQL proof remain open; synthetic storage rows and mocked holder checks do not establish those gates. Request-only fresh activation is denied, while exact retained legacy outcomes remain historical evidence. Preparation COMMITTED and ACTIVE-only admission semantics remain unchanged, and runtime activation stays denied. +The current unregistered construction adds the distinct [Account activation-purpose protection](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references), its immutable source vector and authenticated acquisition, protected World operation storage and [exact terminal readback](../../architecture/microservices/world-management-service/api-contracts.md#canonical-initial-activation-protection), and append-only Account terminal settlement. Their complete authenticated producer/consumer composition and physical PostgreSQL proof remain open; synthetic storage rows and mocked holder checks do not establish those gates. Request-only fresh activation is denied, while exact retained legacy outcomes remain historical evidence. A synthetic V42-origin/V52-evolved activation definition checks immutable operation preservation through V64/V65, historical exact replay and rejection of protected adoption without inventing realm/catalog values. It does not prove original pre-V52 11-field lifecycle-result readability: the current closed decoder requires the later operational-region map, and that earlier retained-format gap remains open. Preparation COMMITTED and ACTIVE-only admission semantics remain unchanged, and runtime activation stays denied. -Game Design now constructs durable, ordered minimal authored-core projections beside the actual immutable descriptor owner, retaining the full private source proof locally. Its separate unregistered read reuses Account-confirmed original-operation qualification and the same owner snapshot to return the exact public request, association, descriptor, release and projections; it does not repair historical rows or expose the private publication/capture bytes through the descriptor. Unregistered Game Session V45 retention binds the unchanged qualified result to the actual launch, full original tuple and exact finite pending attempt, rechecking that attempt under the owner lock after the remote read. Exact retained retries return the first bytes without another source read or lease renewal. Its service-ordering tests use mocked clients and a synthetic launch, and its standalone PostgreSQL definitions use synthetic source bytes; neither establishes authenticated producer composition. The genuine fixture additionally defines retention using its actual Game Session store, original owner readback and native Game Design client, but that composition has not executed physically. The genuine native Game Design read definition currently returns the selected source's actual EMPTY projection, not a fabricated nonempty actor core. Entity's unregistered independent post-publication consumer corroborates its direct authenticated read against the local retained source and immutable release participant digest; its five focused mocked-client unit cases execute successfully, while its added genuine fixture composition is unexecuted. Real allocation, placement and operational-region delivery remain open. Entity's immutable pre-publication EMPTY-source receipt cannot become post-publication core evidence. The genuine fixture defines native protected activation and exact Account terminal settlement, but remains unexecuted physically and does not establish successful admission or World hold release. +Game Design now constructs durable, ordered minimal authored-core projections beside the actual immutable descriptor owner, retaining the full private source proof locally. Its separate unregistered read reuses Account-confirmed original-operation qualification and the same owner snapshot to return the exact public request, association, descriptor, release and projections; it does not repair historical rows or expose the private publication/capture bytes through the descriptor. Unregistered Game Session V45 retention binds the unchanged qualified result to the actual launch, full original tuple and exact finite pending attempt, rechecking that attempt under the owner lock after the remote read. Exact retained retries return the first bytes without another source read or lease renewal. Its service-ordering tests use mocked clients and a synthetic launch, and its standalone PostgreSQL definitions use synthetic source bytes; neither establishes authenticated producer composition. The genuine fixture additionally defines retention using its actual Game Session store, original owner readback and native Game Design client, but that composition has not executed physically. The genuine native source definition preserves its original PRESEEDED_ONLY EMPTY projection and adds a separate PLAYER_CREATED scenario authored in a new selected commit: schema-three policy, exact EMPTY_OBJECT descriptor, disposition and mandatory feedback revisions, complete template references, native Game Design read, unchanged Game Session retention and independent Entity readback. The 23-family empty source census remains separate from actor allocation. The corrected Game Design local gate passes, but both genuine scenarios remain container-skipped; no nonempty actor allocation, current player authority or physical source-composition success is established. Entity's unregistered independent post-publication consumer corroborates its direct authenticated read against the local retained source and immutable release participant digest; its five focused mocked-client unit cases execute successfully, while its added genuine fixture composition is unexecuted. Real allocation, placement and operational-region delivery remain open. Entity's immutable pre-publication EMPTY-source receipt cannot become post-publication core evidence. The genuine fixture defines native protected activation and exact Account terminal settlement, but remains unexecuted physically and does not establish successful admission or World hold release. At the preceding published checkpoint `07d639bb304f82a6f16005ec69362b07bc257f07`, complete Common Platform/Account/Game Session/Game Design checks passed in 4 minutes 45 seconds across 243 tasks, with 57 executed and 186 up-to-date. Available corrected-state XML recorded 4,593 executed unit cases and 40 executed non-container integration/cross-service cases, with zero failures or errors; the final run reused the immediately preceding passing Common and Account test results. There were 666 skips: 17 Game Session unit cases and 649 container-dependent integration/cross-service cases, including the native genuine-release/admission/settlement composition. Integration compilation, generated SQL metadata, formatting, Checkstyle, SpotBugs, coverage, links and Markdown passed; architecture contracts separately passed 228 checks, and Flyway sanity passed 12 sets/307 versioned files. This proves the earlier local compilation, unit and static boundary, not the new activation/projection construction, physical PostgreSQL migration, complete original authority, successful OPEN admission, World hold release or runtime activation. diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java index 2b68de8450..9823f3fb02 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java @@ -5,20 +5,11 @@ import com.google.protobuf.Timestamp; import com.google.protobuf.UnknownFieldSet; -import java.io.IOException; import java.time.Instant; -import java.util.List; -import java.util.Map; import java.util.UUID; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; -import net.firedevops.firemud.common.operator.StartSessionOperatorAction; -import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; -import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import org.junit.jupiter.api.Test; -import tools.jackson.databind.json.JsonMapper; class OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest { private static final UUID READ_ID = uuid("01111111-1111-4111-8111-111111111111"); @@ -177,118 +168,3 @@ private static UUID uuid(String value) { return UUID.fromString(value); } } - -/** Minimal synthetic StartSession tuple fixture shared by the two focused transport tests. */ -final class CurrentAttemptTestData { - private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); - private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); - private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); - private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); - private static final UUID ISSUANCE_ID = uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); - private static final UUID TOKEN_JTI = uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"); - private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); - private static final JsonMapper JSON = JsonMapper.builder().build(); - - private CurrentAttemptTestData() {} - - static StartSessionPostAuthorizationExecutionTuple tuple() { - StartSessionPreAuthorizationReservationTuple pre = - StartSessionPreAuthorizationReservationTuple.createHuman( - "current-attempt-test", - ACTOR, - new StartSessionOperatorAction( - StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, - StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(TENANT, "world-runtime"), - new StartSessionOperatorAction.Target(91L, TARGET_OWNER), - StartSessionOperatorAction.ExpectedVersion.ABSENT, - new StartSessionOperatorAction.Mutation( - StartSessionOperatorAction.ClientIp.absent()), - "canonical StartSession owner attempt")); - return StartSessionPostAuthorizationExecutionTuple.createHuman( - pre, - "spiffe://firemud/ns/world-runtime/sa/logging-admin-service", - FINGERPRINT, - RESERVATION_OWNER, - 19L, - authorityBundle(pre), - new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "17", - "23", - "18446744073709551615")); - } - - private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { - String tenant = TENANT.toString(); - Map value = - Map.of( - "bundleVersion", - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "authorityScope", - Map.of( - "scope", Map.of("tenantId", tenant, "targetNamespace", "world-runtime"), - "actionFamily", tuple.actionFamily(), - "applicableAccountId", ACTOR.toString(), - "applicableTenantId", tenant), - "accountProjectionEvidence", - Map.of( - "sourceType", "ACCOUNT", - "sourceEvidenceId", digest('a'), - "sourceEvidenceVersion", "17", - "projectionStatus", "CURRENT", - "evaluatedAt", "2026-10-09T00:00:00Z", - "expiresAt", "2026-10-09T00:05:00Z"), - "issuanceOperationIdentity", - Map.of( - "issuanceOperationId", ISSUANCE_ID.toString(), - "controlPlaneRequestId", tuple.controlPlaneRequestId(), - "actionFamilyRequestIdentity", - Map.of( - "requestIdentityKind", - "controlPlaneRequestId", - "requestId", - tuple.controlPlaneRequestId()), - "mutationDigest", tuple.mutationDigest()), - "issuanceKind", - "human_operator", - "authorityTuple", - Map.of( - "issuerAuthGeneration", 1L, - "accountAuthorityGeneration", 2L, - "tenantAuthorityGeneration", Map.of(tenant, 3L), - "membershipAuthorityGeneration", Map.of(tenant, 4L), - "privateRealmGrantVersions", List.of()), - "membershipVersion", - Map.of(tenant, 5L), - "issuanceFence", - "23", - "issuanceEvidence", - Map.of( - "evidenceType", - StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, - "actorAccountId", - ACTOR.toString(), - "controlUiTokenJti", - TOKEN_JTI.toString(), - "role", - "tenantAdmin", - "accountGeneration", - "2", - "tenantGeneration", - "3")); - try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); - } catch (IOException invalid) { - throw new IllegalStateException(invalid); - } - } - - private static String digest(char value) { - return "sha256:" + String.valueOf(value).repeat(64); - } - - private static UUID uuid(String value) { - return UUID.fromString(value); - } -} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 5af0582b8c..d58227db02 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -99,6 +99,7 @@ import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence; import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; @@ -149,6 +150,7 @@ import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; @@ -457,6 +459,9 @@ class GenuineSelectedPublicationExportPostgresIntegrationTest { private static final String MINIO_ACCESS_KEY = "firemud-test"; private static final String MINIO_SECRET_KEY = "firemud-test-secret"; private static final String MINIO_BUCKET = "genuine-selected-export-test"; + private static final String PLAYER_CREATED_DISPLAY_NAME = "Genuine Traveler"; + private static final String PLAYER_CREATED_DISPOSITION_KEY = "genuine-selected-newcomer"; + private static final String PLAYER_CREATED_FEEDBACK_KEY = "genuine-selected-welcome"; private static final Region MINIO_REGION = Region.US_EAST_1; private static final Network NETWORK = Network.newNetwork(); private static final Map ENTITY_EMPTY_ONLY_PROVIDER_TABLES = @@ -567,6 +572,19 @@ void closeMinioClient() { @Test void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Exception { + runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( + GenuineActorCoreScenario.PRESEEDED_ONLY_EMPTY_CORE); + } + + @Test + void realPlayerCreatedAuthoredCoreSourceReceiptInventoryAndExportAreExactAndRetryable() + throws Exception { + runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( + GenuineActorCoreScenario.PLAYER_CREATED); + } + + private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( + GenuineActorCoreScenario actorCoreScenario) throws Exception { var gd = gameDesignStore(); var world = serviceStore(WORLD_POSTGRES, "world-management"); var gameSessionAttempts = gameSessionAttemptStore(); @@ -979,7 +997,8 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex sourceAsset.getId(), sourceAsset.getFileName(), worldSource.worldSlug(), - worldSource.worldDisplayName()); + worldSource.worldDisplayName(), + actorCoreScenario); var originalWorldDeclarations = selectedCommit.revisions().stream() .filter(revision -> revision.owner() == Owner.WORLD_MANAGEMENT) @@ -1420,6 +1439,43 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(selectedSources.policy().binding()).isEqualTo(selectedCommit); assertThat(RealmPolicySource.ordered(selectedSources.policy().policies())) .containsExactly(expectedPolicy); + assertThat(expectedPolicy.policy().entryPolicy()) + .isEqualTo(actorCoreScenario.entryPolicy()); + if (actorCoreScenario.hasAuthoredInitialActorCore()) { + assertThat(expectedPolicy.policy().schemaVersion()) + .isEqualTo(RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION); + assertThat(expectedPolicy.policy().initialActorCore().displayName()) + .isEqualTo(PLAYER_CREATED_DISPLAY_NAME); + assertThat(expectedPolicy.policy().initialActorCore().dispositionKey()) + .isEqualTo(PLAYER_CREATED_DISPOSITION_KEY); + var creationDescriptor = expectedPolicy.policy().creationDescriptor(); + assertThat(creationDescriptor.schemaVersion()) + .isEqualTo(PlayerCreationDescriptor.SCHEMA_VERSION); + assertThat(creationDescriptor.descriptorId()).isNotEqualTo(new UUID(0L, 0L).toString()); + assertThat(creationDescriptor.descriptorRevisionId()) + .isNotEqualTo(new UUID(0L, 0L).toString()); + assertThat(creationDescriptor.descriptorId()) + .isNotEqualTo(creationDescriptor.descriptorRevisionId()); + assertThat(creationDescriptor.inputKind()).isEqualTo(PlayerCreationDescriptor.INPUT_KIND); + assertThat(creationDescriptor.dependencies()).isEmpty(); + } else { + assertThat(expectedPolicy.policy().canonicalJson()).doesNotContain("initialActorCore"); + } + var selectedGameplayEntries = selectedSources.gameplay().entries(); + assertThat(selectedGameplayEntries) + .hasSize(actorCoreScenario.hasAuthoredInitialActorCore() ? 3 : 1); + assertThat(selectedGameplayEntries) + .extracting(entry -> entry.family().name() + ":" + entry.definition().key()) + .containsExactlyElementsOf( + actorCoreScenario.hasAuthoredInitialActorCore() + ? List.of( + "ADMISSION_TAGS:genuine-selected-export", + "DISPOSITIONS:" + PLAYER_CREATED_DISPOSITION_KEY, + "FEEDBACK:" + PLAYER_CREATED_FEEDBACK_KEY) + : List.of("ADMISSION_TAGS:genuine-selected-export")); + assertThat(selectedGameplayEntries) + .extracting(GameplayRuleSource.Entry::sourceBinding) + .containsOnly(selectedCommit); var ownerIntakeSourceRepository = new GameDesignSourceRepository(gd.dsl()); var sourceRowsBeforeExport = selectedOwnerSourceRowCounts(gd.dsl()); @@ -1583,6 +1639,14 @@ void realSelectedSourceReceiptInventoryAndExportAreExactAndRetryable() throws Ex assertThat(templateSource.canonicalJson()) .contains("\"schema\":\"game-design-template-config-source-snapshot/v2\""); assertThat(templateSource.entries()).hasSize(1); + assertThat(templateSource.entries().getFirst().config().gameplayInputs()) + .containsExactlyElementsOf( + selectedGameplayEntries.stream() + .map( + entry -> + new TemplateConfigSource.GameplayInput( + entry.family(), entry.definition().key(), entry.revisionId())) + .toList()); var selectedTemplateMutations = TemplateConfigSource.mutations(selectedCommit); var authoredAutomationInventory = automationSourceInventory(); var authoredEntityInventory = entitySourceInventory(); @@ -3225,10 +3289,27 @@ public void attachAccountRedemptionProjection( new StartSessionAuthoredActorCoreProjectionRepository(gd.dsl()); var retainedActorCoreProofsBeforeRead = actorCoreProjectionRepository.findByOwner(retainedDescriptorOwner); - assertThat(retainedActorCoreProofsBeforeRead).isEmpty(); - assertThat(expectedPolicy.policy().entryPolicy()) - .isEqualTo(RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); - assertThat(expectedPolicy.policy().canonicalJson()).doesNotContain("initialActorCore"); + if (actorCoreScenario.hasAuthoredInitialActorCore()) { + assertSameAuthoredCoreProjectionBytes( + retainedActorCoreProofsBeforeRead.stream() + .map( + row -> + AuthoredInitialActorCoreProjection.fromStored( + row.projectionBytes(), row.projectionDigest())) + .toList(), + firstDescriptorBinding.actorCoreProjections()); + } else { + assertThat(retainedActorCoreProofsBeforeRead).isEmpty(); + assertThat(expectedPolicy.policy().entryPolicy()) + .isEqualTo(RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); + assertThat(expectedPolicy.policy().canonicalJson()).doesNotContain("initialActorCore"); + } + assertActorCoreScenarioProjection( + actorCoreScenario, + firstDescriptorBinding.actorCoreProjections(), + selectedCommit, + expectedPolicy, + selectedGameplayEntries); var authoredCoreReadRequest = new AuthoredInitialActorCoreReadEvidence.ReadRequest( @@ -3256,8 +3337,19 @@ public void attachAccountRedemptionProjection( firstDescriptorBinding.descriptor().authoredWorldBinding().requestDigest()); assertThat(gameSessionAuthoredCoreRead.descriptor().resultDigest()) .isEqualTo(firstDescriptorBinding.descriptor().authoredWorldBinding().resultDigest()); - assertThat(gameSessionAuthoredCoreRead.projections()).isEmpty(); - assertThat(firstDescriptorBinding.actorCoreProjections()).isEmpty(); + if (!actorCoreScenario.hasAuthoredInitialActorCore()) { + assertThat(gameSessionAuthoredCoreRead.projections()).isEmpty(); + assertThat(firstDescriptorBinding.actorCoreProjections()).isEmpty(); + } + assertSameAuthoredCoreProjectionBytes( + gameSessionAuthoredCoreRead.projections(), + firstDescriptorBinding.actorCoreProjections()); + assertActorCoreScenarioProjection( + actorCoreScenario, + gameSessionAuthoredCoreRead.projections(), + selectedCommit, + expectedPolicy, + selectedGameplayEntries); var exactGameSessionAuthoredCoreRetry = gameSessionToGameDesignAuthoredCoreClient.read(authoredCoreReadRequest); assertThat(exactGameSessionAuthoredCoreRetry.canonicalBytes()) @@ -3266,6 +3358,14 @@ public void attachAccountRedemptionProjection( entityToGameDesignAuthoredCoreClient.read(authoredCoreReadRequest); assertThat(entityAuthoredCoreRead.canonicalBytes()) .containsExactly(gameSessionAuthoredCoreRead.canonicalBytes()); + assertSameAuthoredCoreProjectionBytes( + entityAuthoredCoreRead.projections(), gameSessionAuthoredCoreRead.projections()); + assertActorCoreScenarioProjection( + actorCoreScenario, + entityAuthoredCoreRead.projections(), + selectedCommit, + expectedPolicy, + selectedGameplayEntries); var entityRetainedAuthoredCoreSourceService = new EntityRetainedAuthoredActorCoreSourceService( NAMESPACE, entityToGameDesignAuthoredCoreClient, entityIntakeRepository); @@ -3273,7 +3373,15 @@ public void attachAccountRedemptionProjection( entityRetainedAuthoredCoreSourceService.read(authoredCoreReadRequest); assertThat(entityCorroboratedAuthoredCoreRead.canonicalBytes()) .containsExactly(entityAuthoredCoreRead.canonicalBytes()); - assertThat(entityCorroboratedAuthoredCoreRead.projections()).isEmpty(); + assertSameAuthoredCoreProjectionBytes( + entityCorroboratedAuthoredCoreRead.projections(), + entityAuthoredCoreRead.projections()); + assertActorCoreScenarioProjection( + actorCoreScenario, + entityCorroboratedAuthoredCoreRead.projections(), + selectedCommit, + expectedPolicy, + selectedGameplayEntries); var exactEntityCorroboratedAuthoredCoreRetry = entityRetainedAuthoredCoreSourceService.read(authoredCoreReadRequest); assertThat(exactEntityCorroboratedAuthoredCoreRetry.canonicalBytes()) @@ -3286,7 +3394,8 @@ public void attachAccountRedemptionProjection( .doesNotContain("sourceCaptureBytes") .doesNotContain("publicationOperationBytes"); assertThat(actorCoreProjectionRepository.findByOwner(retainedDescriptorOwner)) - .containsExactlyElementsOf(retainedActorCoreProofsBeforeRead); + .usingRecursiveComparison() + .isEqualTo(retainedActorCoreProofsBeforeRead); var substitutedTuple = startSessionTuple( @@ -3344,7 +3453,8 @@ public void attachAccountRedemptionProjection( assertThat(io.grpc.Status.fromThrowable(failure).getCode()) .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); assertThat(actorCoreProjectionRepository.findByOwner(retainedDescriptorOwner)) - .containsExactlyElementsOf(retainedActorCoreProofsBeforeRead); + .usingRecursiveComparison() + .isEqualTo(retainedActorCoreProofsBeforeRead); var expectedAuthoredWorldBinding = firstDescriptorBinding.descriptor().authoredWorldBinding(); @@ -3471,6 +3581,7 @@ public void attachAccountRedemptionProjection( assertThat(publishedPolicyRead.publishedSet().target()).isEqualTo(gd.target()); var actualPublishedPolicy = publishedPolicyRead.publishedSet().policies().getFirst().source().policy(); + assertThat(actualPublishedPolicy).isEqualTo(expectedPolicy.policy()); assertThat(actualPublishedPolicy.worldSlug()).isEqualTo(worldSource.worldSlug()); assertThat(actualPublishedPolicy.worldDisplayName()) .isEqualTo(worldSource.worldDisplayName()); @@ -3479,7 +3590,7 @@ public void attachAccountRedemptionProjection( assertThat(actualPublishedPolicy.stateScope()) .isEqualTo(RealmEntryPolicy.StateScope.SHARED); assertThat(actualPublishedPolicy.entryPolicy()) - .isEqualTo(RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY); + .isEqualTo(actorCoreScenario.entryPolicy()); var canonicalRealmCatalogRepository = new GameSessionCanonicalRealmCatalogRepository( @@ -3500,7 +3611,8 @@ public void attachAccountRedemptionProjection( assertThat(canonicalRealmCatalog.worldSlug()).isEqualTo(worldSource.worldSlug()); assertThat(canonicalRealmCatalog.sourceWorldDisplayName()) .isEqualTo(worldSource.worldDisplayName()); - assertThat(canonicalRealmCatalog.entryPolicy()).isEqualTo("PRESEEDED_ONLY"); + assertThat(canonicalRealmCatalog.entryPolicy()) + .isEqualTo(actorCoreScenario.entryPolicy().name()); assertThat(canonicalRealmCatalog.catalogRevision()).isPositive(); assertThat(canonicalRealmCatalog.completePolicySetEvidence()) .containsExactly( @@ -3831,7 +3943,12 @@ public void close() {} assertThat(firstRetainedAuthoredCore.candidate().ownerFence()).isEqualTo(ownerFence); assertThat(firstRetainedAuthoredCore.candidate().ownerLeaseExpiresAt()) .isEqualTo(currentOwnerAttemptBeforeRetention.leaseExpiresAt()); - assertThat(gameSessionAuthoredCoreRead.projections()).isEmpty(); + assertActorCoreScenarioProjection( + actorCoreScenario, + gameSessionAuthoredCoreRead.projections(), + selectedCommit, + expectedPolicy, + selectedGameplayEntries); assertThat(retainedGameDesignReadCalls).hasValue(1); var independentRetainedAuthoredCore = authoredCoreRetentionRepository @@ -4943,6 +5060,8 @@ public void close() {} pinnedSelection, UUID.randomUUID()))); assertThat(replay.descriptor()).isEqualTo(firstDescriptorBinding.descriptor()); + assertSameAuthoredCoreProjectionBytes( + replay.actorCoreProjections(), firstDescriptorBinding.actorCoreProjections()); assertThat(replay.associationRead().request().readRequestId()) .isNotEqualTo(firstDescriptorBinding.associationRead().request().readRequestId()); @@ -5034,6 +5153,114 @@ public void close() {} } } + private static void assertSameAuthoredCoreProjectionBytes( + List actual, + List expected) { + assertThat(actual.size()).isEqualTo(expected.size()); + for (int index = 0; index < actual.size(); index++) { + assertThat(actual.get(index).canonicalBytes()) + .containsExactly(expected.get(index).canonicalBytes()); + } + } + + private static void assertActorCoreScenarioProjection( + GenuineActorCoreScenario scenario, + List projections, + DraftCommitBinding selectedCommit, + RealmPolicySource.Policy selectedPolicy, + List selectedGameplayEntries) { + if (!scenario.hasAuthoredInitialActorCore()) { + assertThat(projections).isEmpty(); + return; + } + + assertThat(selectedPolicy.commitId()).isEqualTo(selectedCommit.commitId()); + assertThat(selectedPolicy.policy().schemaVersion()) + .isEqualTo(RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION); + assertThat(selectedPolicy.policy().entryPolicy()) + .isEqualTo(RealmEntryPolicy.EntryPolicy.PLAYER_CREATED); + assertThat(selectedPolicy.policy().initialActorCore().displayName()) + .isEqualTo(PLAYER_CREATED_DISPLAY_NAME); + assertThat(selectedPolicy.policy().initialActorCore().dispositionKey()) + .isEqualTo(PLAYER_CREATED_DISPOSITION_KEY); + + var dispositionSource = + selectedGameplayEntries.stream() + .filter(entry -> entry.family() == GameplayRuleManifest.Family.DISPOSITIONS) + .filter(entry -> entry.definition().key().equals(PLAYER_CREATED_DISPOSITION_KEY)) + .findFirst() + .orElseThrow(); + var feedbackSource = + selectedGameplayEntries.stream() + .filter(entry -> entry.family() == GameplayRuleManifest.Family.FEEDBACK) + .filter(entry -> entry.definition().key().equals(PLAYER_CREATED_FEEDBACK_KEY)) + .findFirst() + .orElseThrow(); + assertThat(dispositionSource.definition()) + .isEqualTo( + new GameplayRuleManifest.Disposition( + PLAYER_CREATED_DISPOSITION_KEY, List.of(), PLAYER_CREATED_FEEDBACK_KEY)); + assertThat(feedbackSource.definition()) + .isEqualTo( + new GameplayRuleManifest.Feedback( + PLAYER_CREATED_FEEDBACK_KEY, + "actor.created", + GameplayRuleManifest.Audience.SOURCE_ACTOR, + "actor.created", + "Welcome, traveler.", + List.of(), + GameplayRuleManifest.Visibility.PUBLIC, + GameplayRuleManifest.ReplayPolicy.EFFECT_IDEMPOTENT)); + + var expectedDescriptor = selectedPolicy.policy().creationDescriptor(); + assertThat(expectedDescriptor.schemaVersion()) + .isEqualTo(PlayerCreationDescriptor.SCHEMA_VERSION); + assertThat(expectedDescriptor.inputKind()).isEqualTo(PlayerCreationDescriptor.INPUT_KIND); + assertThat(expectedDescriptor.dependencies()).isEmpty(); + assertThat(expectedDescriptor.descriptorId()) + .isNotEqualTo(expectedDescriptor.descriptorRevisionId()); + assertThat(projections) + .singleElement() + .satisfies( + projection -> { + assertThat(projection.canonicalTenantId()) + .isEqualTo(selectedCommit.target().canonicalTenantId()); + assertThat(projection.canonicalVersionId()) + .isEqualTo(selectedCommit.target().canonicalVersionId()); + assertThat(projection.selectedCommitId()).isEqualTo(selectedCommit.commitId()); + assertThat(projection.selectedCommitDigest()).isEqualTo(selectedCommit.digest()); + assertThat(projection.policy().commitId()).isEqualTo(selectedPolicy.commitId()); + assertThat(projection.policy().revisionId()).isEqualTo(selectedPolicy.revisionId()); + assertThat(projection.policy().logicalRevisionId()) + .isEqualTo(selectedPolicy.logicalRevisionId()); + assertThat(projection.policy().canonicalJson()) + .isEqualTo(selectedPolicy.policy().canonicalJson()); + assertThat(projection.core().displayName()).isEqualTo(PLAYER_CREATED_DISPLAY_NAME); + assertThat(projection.core().dispositionKey()) + .isEqualTo(PLAYER_CREATED_DISPOSITION_KEY); + assertThat(projection.descriptor().canonicalJson()) + .isEqualTo(expectedDescriptor.canonicalJson()); + assertThat(projection.descriptor().digest()).isEqualTo(expectedDescriptor.digest()); + assertRuleRevisionProvenance( + projection.disposition(), dispositionSource, selectedCommit); + assertRuleRevisionProvenance( + projection.safeFeedback(), feedbackSource, selectedCommit); + }); + } + + private static void assertRuleRevisionProvenance( + AuthoredInitialActorCoreProjection.RuleDefinition projection, + GameplayRuleSource.Entry source, + DraftCommitBinding selectedCommit) { + assertThat(projection.key()).isEqualTo(source.definition().key()); + assertThat(projection.definitionJson()) + .isEqualTo(GameplayRuleManifest.canonical(source.definition())); + assertThat(projection.sourceCommitId()).isEqualTo(selectedCommit.commitId()); + assertThat(projection.sourceCommitDigest()).isEqualTo(selectedCommit.digest()); + assertThat(projection.revisionId()).isEqualTo(source.revisionId()); + assertThat(projection.revisionOrder()).isEqualTo(source.revisionOrder()); + } + /** Uses the real owner persistence service inside the fixture's explicit READ_COMMITTED tx. */ private static PublishAttemptService transactionBoundPublishAttempts( Store store, PublishAttemptServiceImpl delegate) { @@ -5828,7 +6055,12 @@ private static String migrationLocation(String service) { } private static DraftCommitBinding binding( - TargetProof target, long assetId, String fileName, String worldSlug, String worldDisplayName) + TargetProof target, + long assetId, + String fileName, + String worldSlug, + String worldDisplayName, + GenuineActorCoreScenario actorCoreScenario) throws Exception { UUID commit = UUID.randomUUID(); UUID region = UUID.randomUUID(); @@ -5899,6 +6131,19 @@ private static DraftCommitBinding binding( var revisions = new ArrayList(); var units = new ArrayList(); UUID gameplayRuleRevisionId = UUID.randomUUID(); + UUID dispositionRevisionId = + actorCoreScenario.hasAuthoredInitialActorCore() ? UUID.randomUUID() : null; + UUID feedbackRevisionId = + actorCoreScenario.hasAuthoredInitialActorCore() ? UUID.randomUUID() : null; + var gameplayInputs = new ArrayList(); + gameplayInputs.add( + Map.of( + "family", + GameplayRuleManifest.Family.ADMISSION_TAGS.name(), + "key", + "genuine-selected-export", + "revisionId", + gameplayRuleRevisionId.toString())); revisions.add( new RevisionPayload( "0", @@ -5906,6 +6151,49 @@ private static DraftCommitBinding binding( Owner.GAME_DESIGN_CONTROL_PLANE, GameplayRuleSource.upsertPayload( new GameplayRuleManifest.AdmissionTag("genuine-selected-export")))); + if (actorCoreScenario.hasAuthoredInitialActorCore()) { + var disposition = + new GameplayRuleManifest.Disposition( + PLAYER_CREATED_DISPOSITION_KEY, List.of(), PLAYER_CREATED_FEEDBACK_KEY); + var feedback = + new GameplayRuleManifest.Feedback( + PLAYER_CREATED_FEEDBACK_KEY, + "actor.created", + GameplayRuleManifest.Audience.SOURCE_ACTOR, + "actor.created", + "Welcome, traveler.", + List.of(), + GameplayRuleManifest.Visibility.PUBLIC, + GameplayRuleManifest.ReplayPolicy.EFFECT_IDEMPOTENT); + gameplayInputs.add( + Map.of( + "family", + GameplayRuleManifest.Family.DISPOSITIONS.name(), + "key", + PLAYER_CREATED_DISPOSITION_KEY, + "revisionId", + dispositionRevisionId.toString())); + gameplayInputs.add( + Map.of( + "family", + GameplayRuleManifest.Family.FEEDBACK.name(), + "key", + PLAYER_CREATED_FEEDBACK_KEY, + "revisionId", + feedbackRevisionId.toString())); + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + dispositionRevisionId, + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(disposition))); + revisions.add( + new RevisionPayload( + Integer.toString(revisions.size()), + feedbackRevisionId, + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(feedback))); + } units.add( new AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, @@ -5916,7 +6204,7 @@ private static DraftCommitBinding binding( "0")); revisions.add( new RevisionPayload( - "1", + Integer.toString(revisions.size()), UUID.randomUUID(), Owner.GAME_DESIGN_CONTROL_PLANE, AssetSource.upsertPayload( @@ -5935,7 +6223,8 @@ private static DraftCommitBinding binding( Integer.toString(revisions.size()), realmPolicyRevisionId, Owner.GAME_DESIGN_CONTROL_PLANE, - realmPolicyRevisionPayload(worldSlug, worldDisplayName, realmPolicyRevisionId))); + realmPolicyRevisionPayload( + worldSlug, worldDisplayName, realmPolicyRevisionId, actorCoreScenario))); units.add( new AffectedUnit( Owner.GAME_DESIGN_CONTROL_PLANE, @@ -5946,15 +6235,23 @@ private static DraftCommitBinding binding( "0")); var templateConfig = new TemplateConfigSource.Config( - "{\"schemaVersion\":1,\"baseVersionId\":\"" - + target.canonicalVersionId() - + "\",\"world\":{\"regions\":[],\"rooms\":[]}," - + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[{" - + "\"family\":\"ADMISSION_TAGS\",\"key\":\"genuine-selected-export\"," - + "\"revisionId\":\"" - + gameplayRuleRevisionId - + "\"}]},\"automation\":{\"scripts\":[]," - + "\"scriptPatch\":{\"presence\":\"ABSENT\"}},\"supportedSettings\":[]}"); + new ObjectMapper() + .writeValueAsString( + Map.of( + "schemaVersion", + 1, + "baseVersionId", + target.canonicalVersionId().toString(), + "world", + Map.of("regions", List.of(), "rooms", List.of()), + "entity", + Map.of("items", List.of(), "npcs", List.of()), + "gameLogic", + Map.of("inputs", gameplayInputs), + "automation", + Map.of("scripts", List.of(), "scriptPatch", Map.of("presence", "ABSENT")), + "supportedSettings", + List.of()))); revisions.add( new RevisionPayload( Integer.toString(revisions.size()), @@ -6017,28 +6314,48 @@ private static DraftCommitBinding binding( } private static String realmPolicyRevisionPayload( - String worldSlug, String worldDisplayName, UUID revisionId) throws Exception { + String worldSlug, + String worldDisplayName, + UUID revisionId, + GenuineActorCoreScenario actorCoreScenario) + throws Exception { var mapper = new ObjectMapper(); - var policyInput = - Map.of( - "schemaVersion", - 1, - "worldSlug", - worldSlug, - "worldDisplayName", - worldDisplayName, - "realmSlug", - "genuine-selected-export", - "realmDisplayName", - "Genuine Selected Export", - "visible", - true, - "publicProduction", - true, - "stateScope", - RealmEntryPolicy.StateScope.SHARED.name(), - "entryPolicy", - RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY.name()); + var policyInput = new java.util.LinkedHashMap(); + policyInput.put( + "schemaVersion", + actorCoreScenario.hasAuthoredInitialActorCore() + ? RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION + : RealmEntryPolicy.SCHEMA_VERSION); + policyInput.put("worldSlug", worldSlug); + policyInput.put("worldDisplayName", worldDisplayName); + policyInput.put("realmSlug", "genuine-selected-export"); + policyInput.put("realmDisplayName", "Genuine Selected Export"); + policyInput.put("visible", true); + policyInput.put("publicProduction", true); + policyInput.put("stateScope", RealmEntryPolicy.StateScope.SHARED.name()); + policyInput.put("entryPolicy", actorCoreScenario.entryPolicy().name()); + if (actorCoreScenario.hasAuthoredInitialActorCore()) { + UUID descriptorId = UUID.randomUUID(); + UUID descriptorRevisionId = UUID.randomUUID(); + while (descriptorId.equals(descriptorRevisionId)) { + descriptorRevisionId = UUID.randomUUID(); + } + policyInput.put( + "creationDescriptor", + Map.of( + "schemaVersion", PlayerCreationDescriptor.SCHEMA_VERSION, + "descriptorId", descriptorId.toString(), + "descriptorRevisionId", descriptorRevisionId.toString(), + "inputKind", PlayerCreationDescriptor.INPUT_KIND, + "dependencies", List.of())); + policyInput.put( + "initialActorCore", + Map.of( + "displayName", + PLAYER_CREATED_DISPLAY_NAME, + "dispositionKey", + PLAYER_CREATED_DISPOSITION_KEY)); + } var policy = RealmEntryPolicy.parse(mapper.writeValueAsString(policyInput), mapper); var revision = Map.of( @@ -6050,6 +6367,28 @@ private static String realmPolicyRevisionPayload( StandardCharsets.UTF_8); } + private enum GenuineActorCoreScenario { + PRESEEDED_ONLY_EMPTY_CORE(RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY, false), + PLAYER_CREATED(RealmEntryPolicy.EntryPolicy.PLAYER_CREATED, true); + + private final RealmEntryPolicy.EntryPolicy entryPolicy; + private final boolean authoredInitialActorCore; + + GenuineActorCoreScenario( + RealmEntryPolicy.EntryPolicy entryPolicy, boolean authoredInitialActorCore) { + this.entryPolicy = entryPolicy; + this.authoredInitialActorCore = authoredInitialActorCore; + } + + RealmEntryPolicy.EntryPolicy entryPolicy() { + return entryPolicy; + } + + boolean hasAuthoredInitialActorCore() { + return authoredInitialActorCore; + } + } + private static AutomationAuthoredSourceInventoryDeclaration automationSourceInventory() { return AutomationAuthoredSourceInventoryDeclaration.parse( "{\"schema\":\"automation-authored-source-inventory/v1\"," diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 1c7c2a553b..6b3aae2909 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -44,6 +44,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionRequest; import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; @@ -4151,6 +4152,257 @@ void inertV1PreparationRetainsOriginalBytesAndCannotGainSelectorOnRetry() throws historical.assertOrigin(); } + @Test + void v65UpgradeRetainsV52EvolvedLegacyActivationBytesWithoutProtectedAdoption() { + HistoricalSchemaFixture schema = historicalSchemaAt("world_v42_legacy_activation", "42"); + WorldDraftGraphApplicationPostgresIntegrationTest historical = schema.database(); + Fixture f = historical.fixture(); + var application = + historical.application( + historical.withoutInboundSourceClosure(historical.generationFreePlan(f))); + historical.retainHistoricalApplication(application); + var frozen = historical.captureHistoricalUnqualified(application.plan()); + var selector = + historical.publishedEvidence( + historical.publishedSelectors().readCommitted(frozen.request().freeze()).orElseThrow()); + var input = historical.preparationInput(f, frozen, selector); + + // This is a synthetic, storage-only historical fixture. Its V42 source/freeze/selector owner + // rows feed the original V2 preparation path after V45 has installed the real operational + // REGION identity writer; it then runs the V43 activation table through its later V52-evolved + // guard and lifecycle manifest/CAS. It does not authenticate Account or Game Session, + // establish current source authority, or prove the genuine StartSession producer. V52 adds the + // map to the closed lifecycle carrier; the retained result below is intentionally that evolved + // V43 table format, not a claim that a pre-V52 11-field result is readable by today's 12-field + // Java decoder. + String historicalInputJson = historical.historicalV2PreparationInputJson(input); + var historicalInput = historical.mapper.readTree(historicalInputJson); + assertThat(historicalInput.path("schemaVersion").asInt()).isEqualTo(2); + assertThat(historicalInput.path("identity").has("canonicalRealmId")).isFalse(); + assertThat(historicalInput.path("identity").has("catalogRevision")).isFalse(); + assertThat(historicalInput.path("gameSessionReadEvidence").has("canonicalRealmId")).isFalse(); + assertThat(historicalInput.path("gameSessionReadEvidence").has("catalogRevision")).isFalse(); + assertThat(historicalInput.path("worldStartLocationEvidenceBase64").asText()) + .isEqualTo(java.util.Base64.getEncoder().encodeToString(selector.canonicalBytes())); + + historical.migrateHistoricalSchema(schema.schema(), "43"); + historical.migrateHistoricalSchema(schema.schema(), "45"); + var preparation = historical.prepareV2ThroughOwnerFunction(input); + byte[] preparationRowsBeforeRetry = historical.preparationRows(input.canonicalGameInstanceId()); + assertThat(historical.prepareV2ThroughOwnerFunction(input)).isEqualTo(preparation); + assertThat(historical.preparationRows(input.canonicalGameInstanceId())) + .containsExactly(preparationRowsBeforeRetry); + assertThat(preparation.startLocation()) + .isEqualTo( + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) + .startLocation()); + assertThat(preparation.runtimeRoomInstanceId()).isPositive(); + var associationAtV45 = + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT schema_version FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())); + assertThat(associationAtV45.get("schema_version", Short.class)).isEqualTo((short) 1); + assertThat( + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT input_json::JSONB->>'schemaVersion' FROM " + + "world_canonical_instance_preparation WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, String.class)) + .isEqualTo("2"); + + historical.migrateHistoricalSchema(schema.schema(), "52"); + var preparing = historical.historicalLifecycleEvidence(input, preparation, "PREPARING"); + assertThat(preparing.lifecycleEpoch()).isPositive(); + assertThat(preparing.rowVersion()).isGreaterThanOrEqualTo(0L); + assertThat(preparing.operationalRegionAssignments()).isNotEmpty(); + var request = new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), preparing); + var active = + new WorldCanonicalInstanceLifecycleEvidence( + preparing.request(), + preparing.launchBinding(), + preparing.startLocation(), + preparing.runtimeRoomInstanceId(), + "ACTIVE", + preparing.lifecycleEpoch() + 1L, + preparing.rowVersion() + 1L, + preparing.captureId(), + preparing.graphSha256(), + preparing.preparationInputDigest(), + preparing.operationalRegionAssignments()); + var result = + new WorldCanonicalInstanceActivation.Result( + request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, active); + var proof = new ActivationProof(request, result); + + historical + .ownerTransaction() + .execute( + status -> { + historical.insertRawActivationOperation(proof, preparation.worldInstanceId()); + int changed = + historical.dsl.execute( + "UPDATE world_instance SET status='ACTIVE', lifecycle_epoch=lifecycle_epoch+1, " + + "row_version=row_version+1, updated_at=CURRENT_TIMESTAMP " + + "WHERE id=(SELECT world_instance_id FROM " + + "world_canonical_instance_association WHERE canonical_game_instance_id=?) " + + "AND canonical_game_instance_id=? AND status='PREPARING' " + + "AND lifecycle_epoch=? AND row_version=?", + request.canonicalGameInstanceId(), + request.canonicalGameInstanceId(), + request.expectedLifecycleEpoch(), + request.expectedRowVersion()); + if (changed != 1) { + throw new IllegalStateException( + "Historical V43 activation did not win its exact lifecycle compare-and-set"); + } + return null; + }); + assertThat(historical.activationOperationCountForRequest(request.activationRequestId())) + .isEqualTo(1L); + assertThat(historical.activationManifestCountForRequest(request.activationRequestId())) + .isZero(); + assertThat( + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT status,lifecycle_epoch,row_version FROM world_instance WHERE id=?", + preparation.worldInstanceId())) + .get("status", String.class)) + .isEqualTo("ACTIVE"); + + byte[] firstRequestBytes = request.canonicalRequestBytes(); + byte[] firstPreparingBytes = request.preparingEvidenceBytes(); + byte[] firstResultBytes = result.canonicalBytes(); + Record firstOperation = + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT request_digest,request_bytes,preparing_evidence_bytes,outcome,terminal_code," + + "result_lifecycle_epoch,result_row_version,result_bytes,result_digest " + + "FROM world_canonical_instance_activation_operation WHERE activation_request_id=?", + request.activationRequestId())); + assertThat(firstOperation.get("request_bytes", byte[].class)) + .containsExactly(firstRequestBytes); + assertThat(firstOperation.get("preparing_evidence_bytes", byte[].class)) + .containsExactly(firstPreparingBytes); + assertThat(firstOperation.get("result_bytes", byte[].class)).containsExactly(firstResultBytes); + assertThat(firstOperation.get("request_digest", String.class)) + .isEqualTo(sha256Digest(firstRequestBytes)); + assertThat(firstOperation.get("result_digest", String.class)) + .isEqualTo(sha256Digest(firstResultBytes)); + assertThat(firstOperation.get("outcome", String.class)).isEqualTo("COMMITTED"); + assertThat(firstOperation.get("terminal_code", String.class)).isNull(); + assertThat(firstOperation.get("result_lifecycle_epoch", Long.class)) + .isEqualTo(active.lifecycleEpoch()); + assertThat(firstOperation.get("result_row_version", Long.class)).isEqualTo(active.rowVersion()); + String operationJsonBeforeUpgrade = + historical + .rowJson( + "SELECT to_jsonb(o)::text FROM world_canonical_instance_activation_operation o " + + "WHERE activation_request_id=?", + request.activationRequestId()) + .getFirst(); + String associationJsonBeforeUpgrade = + historical + .rowJson( + "SELECT (to_jsonb(a)-'canonical_realm_id'-'catalog_revision')::text " + + "FROM world_canonical_instance_association a " + + "WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId()) + .getFirst(); + String activeWorldJsonBeforeUpgrade = + historical + .rowJson( + "SELECT (to_jsonb(w)-'canonical_realm_id'-'catalog_revision')::text " + + "FROM world_instance w WHERE id=?", + preparation.worldInstanceId()) + .getFirst(); + + historical.migrateHistoricalSchema(schema.schema(), "64"); + var associationAtV64 = + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT schema_version,canonical_realm_id,catalog_revision " + + "FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())); + assertThat(associationAtV64.get("schema_version", Short.class)).isEqualTo((short) 1); + assertThat(associationAtV64.get("canonical_realm_id", UUID.class)).isNull(); + assertThat(associationAtV64.get("catalog_revision", Long.class)).isNull(); + var worldAtV64 = + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT canonical_realm_id,catalog_revision FROM world_instance WHERE id=?", + preparation.worldInstanceId())); + assertThat(worldAtV64.get("canonical_realm_id", UUID.class)).isNull(); + assertThat(worldAtV64.get("catalog_revision", Long.class)).isNull(); + historical.migrateHistoricalSchema(schema.schema(), "65"); + + var associationAtV65 = + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT schema_version,canonical_realm_id,catalog_revision " + + "FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())); + assertThat(associationAtV65.get("schema_version", Short.class)).isEqualTo((short) 1); + assertThat(associationAtV65.get("canonical_realm_id", UUID.class)).isNull(); + assertThat(associationAtV65.get("catalog_revision", Long.class)).isNull(); + var worldAtV65 = + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT canonical_realm_id,catalog_revision FROM world_instance WHERE id=?", + preparation.worldInstanceId())); + assertThat(worldAtV65.get("canonical_realm_id", UUID.class)).isNull(); + assertThat(worldAtV65.get("catalog_revision", Long.class)).isNull(); + + assertThat( + historical.rowJson( + "SELECT to_jsonb(o)::text FROM world_canonical_instance_activation_operation o " + + "WHERE activation_request_id=?", + request.activationRequestId())) + .containsExactly(operationJsonBeforeUpgrade); + assertThat( + historical.rowJson( + "SELECT (to_jsonb(a)-'canonical_realm_id'-'catalog_revision')::text " + + "FROM world_canonical_instance_association a " + + "WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .containsExactly(associationJsonBeforeUpgrade); + assertThat( + historical.rowJson( + "SELECT (to_jsonb(w)-'canonical_realm_id'-'catalog_revision')::text " + + "FROM world_instance w WHERE id=?", + preparation.worldInstanceId())) + .containsExactly(activeWorldJsonBeforeUpgrade); + + var repository = + new WorldCanonicalInstanceActivationRepository( + historical.dsl, + historical.manager, + new WorldCanonicalInstanceLifecycleReadRepository( + historical.dsl, historical.manager, historical.associationRepository())); + var service = new WorldCanonicalInstanceActivationService(repository); + assertThat(service.activate(request).canonicalBytes()).containsExactly(firstResultBytes); + var freshRequest = new WorldCanonicalInstanceActivation.Request(UUID.randomUUID(), preparing); + assertThatThrownBy(() -> service.activate(freshRequest)) + .isInstanceOf(WorldCanonicalInstanceActivationService.ActivationDeniedException.class); + + var originalIdentity = WorldCanonicalInstanceExecutionTestFixtures.identity(input); + var acquisitionInput = + new AccountStartSessionActivationProtectionAcquisitionInput( + originalIdentity.originalPostAuthorizationTuple(), + originalIdentity.gameSessionOwnerMutationId(), + originalIdentity.gameSessionOwnerAttemptId(), + originalIdentity.gameSessionOwnerFence(), + request); + assertThatThrownBy(() -> repository.readProtectedActivationByAcquisitionInput(acquisitionInput)) + .isInstanceOf(WorldCanonicalInstanceActivationRepository.ActivationConflictException.class) + .hasMessageContaining("retained legacy World activation result cannot be upgraded"); + historical.assertOrigin(); + } + @Test void selectorPreparationLateFenceLossRollsBackSelectorRuntimeAndAssociationTogether() { Fixture f = fixture(); @@ -4627,6 +4879,205 @@ private String historicalV1PreparationInputJson(WorldCanonicalInstancePreparatio } } + /** Executes the V42-compatible schema-2 selector path after V45 adds fresh REGION identities. */ + private HistoricalPreparationResult prepareV2ThroughOwnerFunction( + WorldCanonicalInstancePreparation.Input input) { + String inputJson = historicalV2PreparationInputJson(input); + byte[] inputBytes = inputJson.getBytes(StandardCharsets.UTF_8); + Record ownerResult = + Objects.requireNonNull( + ownerTransaction() + .execute( + status -> { + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM world_prepare_canonical_instance(?, ?)", + inputJson, + sha256Digest(inputBytes)), + "V42/V45 owner preparation function returned no row"); + long worldInstanceId = + Objects.requireNonNull( + row.get("world_instance_id", Long.class), + "V42 owner preparation omitted world_instance_id") + .longValue(); + retainHistoricalSchemaOneAssociation(input, worldInstanceId); + return row; + }), + "V42/V45 historical selector preparation transaction returned no result"); + long worldInstanceId = + Objects.requireNonNull( + ownerResult.get("world_instance_id", Long.class), + "V42/V45 owner preparation omitted world_instance_id") + .longValue(); + long privateGameInstanceKey = + Objects.requireNonNull( + ownerResult.get("private_game_instance_key", Long.class), + "V42/V45 owner preparation omitted private_game_instance_key") + .longValue(); + WorldPublishedStartLocationEvidence selector = + Objects.requireNonNull( + input + .completeLaunchBinding() + .evidence() + .releaseAttestation() + .worldStartLocationEvidence(), + "V2 historical preparation requires its original selected ROOM evidence"); + RoomTemplateRef startLocation = + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()).startLocation(); + Record retainedStartLocation = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT runtime_room_instance_id FROM world_canonical_preparation_start_location " + + "WHERE canonical_game_instance_id=? AND world_instance_id=?", + input.canonicalGameInstanceId(), + worldInstanceId), + "V42/V45 selector trigger did not retain the original ROOM mapping"); + return new HistoricalPreparationResult( + worldInstanceId, + privateGameInstanceKey, + startLocation, + Objects.requireNonNull( + retainedStartLocation.get("runtime_room_instance_id", Long.class), + "V42 selector row omitted runtime_room_instance_id")); + } + + private String historicalV2PreparationInputJson(WorldCanonicalInstancePreparation.Input input) { + try { + var root = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(WorldCanonicalInstancePreparationRepository.inputJson(input)); + root.put("schemaVersion", 2); + var identity = (tools.jackson.databind.node.ObjectNode) root.get("identity"); + identity.remove("canonicalRealmId"); + identity.remove("catalogRevision"); + var evidence = (tools.jackson.databind.node.ObjectNode) root.get("gameSessionReadEvidence"); + evidence.remove("canonicalRealmId"); + evidence.remove("catalogRevision"); + return mapper.writeValueAsString(root); + } catch (tools.jackson.core.JacksonException malformed) { + throw new IllegalStateException( + "Could not construct original schema-2 selector fixture bytes", malformed); + } + } + + /** Retains the complete schema-1 association accepted by V43 for this historical V42 row. */ + private void retainHistoricalSchemaOneAssociation( + WorldCanonicalInstancePreparation.Input input, long worldInstanceId) { + String associationSelect = + "SELECT 1::SMALLINT AS schema_version,wi.canonical_game_instance_id," + + "wi.canonical_target_namespace,wi.canonical_tenant_id,wi.canonical_world_slug," + + "wi.playable_state_namespace_id,wi.playable_state_scope,wi.public_production," + + "wi.playtest_lifecycle_id,wi.playtest_state_generation," + + "wi.control_plane_request_id,wi.id AS world_instance_id," + + "b.binding_operation_id AS canonical_launch_binding_operation_id," + + "v.operation_id AS version_identity_operation_id,b.canonical_version_id," + + "wi.tenant_id AS local_tenant_key,wi.game_instance_id AS private_game_instance_key," + + "wi.game_template_id,wi.launch_descriptor_id,wi.version_id AS local_version_key," + + "wi.script_patch_version,wi.runtime_flags_json,wi.generation_config_revision," + + "wi.release_bundle_id,wi.published_release_bundle_ref,wi.version_state_epoch," + + "wi.remap_set_id,b.intake_operation_id,b.intake_request_id,b.source_operation_id," + + "b.source_evidence_digest,s.request_digest AS intake_request_digest," + + "b.intake_receipt_digest,b.descriptor_request_digest,b.descriptor_result_digest," + + "b.release_attestation_digest FROM world_instance wi " + + "JOIN world_complete_launch_binding b " + + "ON b.binding_operation_id=wi.canonical_launch_binding_operation_id " + + "JOIN world_authored_version_identity v ON v.operation_id=? " + + "JOIN world_authored_source_intake s ON s.operation_id=b.intake_operation_id " + + "WHERE wi.id=?"; + Record expectedAssociation = + Objects.requireNonNull( + dsl.fetchOne(associationSelect, input.versionIdentity().operationId(), worldInstanceId), + "V34 historical fixture could not resolve exact schema-1 association fields"); + Record retainedAssociation = + dsl.fetchOne( + "SELECT * FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId()); + if (retainedAssociation == null) { + int inserted = + dsl.execute( + "INSERT INTO world_canonical_instance_association (" + + "schema_version,canonical_game_instance_id,canonical_target_namespace," + + "canonical_tenant_id,canonical_world_slug,playable_state_namespace_id," + + "playable_state_scope,public_production,playtest_lifecycle_id," + + "playtest_state_generation,control_plane_request_id,world_instance_id," + + "canonical_launch_binding_operation_id,version_identity_operation_id," + + "canonical_version_id,local_tenant_key,private_game_instance_key," + + "game_template_id,launch_descriptor_id,local_version_key,script_patch_version," + + "runtime_flags_json,generation_config_revision,release_bundle_id," + + "published_release_bundle_ref,version_state_epoch,remap_set_id," + + "intake_operation_id,intake_request_id,source_operation_id,source_evidence_digest," + + "intake_request_digest,intake_receipt_digest,descriptor_request_digest," + + "descriptor_result_digest,release_attestation_digest) " + + associationSelect, + input.versionIdentity().operationId(), + worldInstanceId); + if (inserted != 1) { + throw new IllegalStateException( + "V34 historical fixture failed to retain its schema-1 association"); + } + retainedAssociation = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT * FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId()), + "V34 historical fixture association was not retained"); + } + if (!Arrays.equals(expectedAssociation.intoArray(), retainedAssociation.intoArray())) { + throw new IllegalStateException( + "V34 historical fixture association differs from its exact schema-1 owner row"); + } + } + + private WorldCanonicalInstanceLifecycleEvidence historicalLifecycleEvidence( + WorldCanonicalInstancePreparation.Input input, + HistoricalPreparationResult preparation, + String lifecycleStatus) { + Record prepared = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT capture_id,graph_sha256,input_digest FROM " + + "world_canonical_instance_preparation WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId()), + "Historical V2 preparation row was not retained"); + Record world = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT status,lifecycle_epoch,row_version FROM world_instance WHERE id=?", + preparation.worldInstanceId()), + "Historical V2 World instance row was not retained"); + Map regionAssignments = new LinkedHashMap<>(); + for (Record region : + dsl.fetch( + "SELECT m.runtime_identity AS canonical_region_id,r.operational_region_id " + + "FROM world_canonical_instance_topology_identity m " + + "JOIN region_instance r ON r.id=m.runtime_row_id " + + "WHERE m.world_instance_id=? AND m.canonical_game_instance_id=? " + + "AND m.family='REGION' ORDER BY m.runtime_identity", + preparation.worldInstanceId(), + input.canonicalGameInstanceId())) { + UUID canonicalRegionId = required(region, "canonical_region_id", UUID.class); + UUID operationalRegionId = required(region, "operational_region_id", UUID.class); + if (regionAssignments.putIfAbsent(canonicalRegionId, operationalRegionId) != null) { + throw new IllegalStateException("Historical V2 REGION identity is duplicated"); + } + } + return new WorldCanonicalInstanceLifecycleEvidence( + lifecycleReadRequest(input), + input.completeLaunchBinding().evidence(), + preparation.startLocation(), + Objects.requireNonNull(preparation.runtimeRoomInstanceId()), + lifecycleStatus, + required(world, "lifecycle_epoch", Long.class), + required(world, "row_version", Long.class), + required(prepared, "capture_id", UUID.class), + required(prepared, "graph_sha256", String.class), + required(prepared, "input_digest", String.class), + regionAssignments); + } + private Map preparationHistoryRows() { Map result = new LinkedHashMap<>(); for (String table : From 99d375dd0137a655a6b58b7466da254b7b7b827d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:29:29 +1300 Subject: [PATCH 107/129] test(account): prove activation protection mTLS boundaries --- ...ame-authoring-publishing-and-activation.md | 2 + ...tionProtectionAcquisitionGrpcMtlsTest.java | 1267 +++++++++++++++++ ...ationProtectionSettlementGrpcMtlsTest.java | 291 ++++ 3 files changed, 1560 insertions(+) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcMtlsTest.java 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 90ddad7715..738f160215 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Account's distinct activation-protection acquisition and settlement receivers now have eight executed loopback-mTLS cases: exact same-namespace World callers preserve full canonical receipt/terminal bytes and lookup correlation, trusted wrong-service or wrong-namespace callers reach no owner, missing certificates reach neither handler nor owner, and authenticated end-user context reaches no owner. These tests use file-backed test certificates and mocked Account owners; they prove transport enforcement, not current Account authorization, source exclusion, PostgreSQL settlement or World activation. The corrected full Account check passes in 2 minutes 41 seconds, including formatting, Checkstyle, SpotBugs and coverage, with 1,385 unit cases executed and zero skips, failures or errors. Its unchanged integration task reuses the preceding results: twelve non-container cases executed and 289 container cases skipped. The initial five failures were invalid synthetic selected-release fixtures; the correction supplies the complete closed selector and APPLIED-v2 graph evidence without changing production guards or weakening assertions. Runtime registration and genuine producer/consumer proof remain denied. Gameplay owns the separate explicit current-player authority producer needed for nonempty `PLAYER_CREATED` allocation; launch creator authority cannot substitute. + Exact published source `a336f4245a46742bda991eba73addf31dcc689b5` has a confirmed Common Platform compilation failure in [Validation run 38106738131](https://github.com/benhook1013/FireMUD/actions/runs/38106738131): two same-package test files declared `CurrentAttemptTestData`. The duplicate fixture is removed without changing its tuple or assertions. Forced fresh Common Platform checks pass in 3 minutes 51 seconds, including 715 executed tests with zero skips, failures or errors; 28 of 29 tasks execute. Replacement exact-head CI remains a separate requirement. The preceding reused local results below did not establish that failed source's fresh CI compilation. The activation/projection construction passes the corrected complete Common Platform, Account, Game Session, Game Design, World and Entity checks in 45 seconds across 287 tasks, with 25 executed and 262 up-to-date. Available corrected-state XML records 5,563 executed unit cases and 44 executed non-container integration/cross-service cases, with zero failures or errors; unchanged tasks reuse successful corrected-state results from the immediately preceding checks. There are 915 skips: 17 Game Session unit cases and 898 container-dependent integration/cross-service cases, including the genuine native composition and new migrations. Strict XML readback separately proves all three Game Session retention-ordering cases and all five Entity authored-core consumer cases executed without skips. Integration compilation, generated SQL metadata, formatting, Checkstyle, SpotBugs, coverage, links and Markdown pass; Flyway sanity passes 12 sets/312 versioned files, public gRPC method and proto-time contracts pass, and architecture contracts passed 228 checks before the final status-only wording. This is local code, unit and static proof, not physical migration, successful authenticated native activation/settlement, actual actor allocation/placement/delivery, or runtime readiness. diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java new file mode 100644 index 0000000000..6ba5fd7634 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java @@ -0,0 +1,1267 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +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.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountStartSessionActivationProtectionAcquisitionServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionActivationProtectionRequest; +import net.firedevops.firemud.account.v1.AcquireOriginalStartSessionActivationProtectionResponse; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionActivationProtectionAcquisitionGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionActivationProtectionAcquisitionService; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionRequest; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionEvidence; +import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionActivationProtectionAcquisitionClient; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.test.TlsTestSupport; +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.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Physical loopback mTLS transport-only proof for the unregistered Account activation-protection + * receiver. The mocked Account owner proves no Account authority, SQL, or World activation. + */ +class AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest { + private static final String NAMESPACE = "world-runtime"; + private static final String WORLD_URI = + "spiffe://firemud/ns/world-runtime/sa/world-management-service"; + private static final UUID PROTECTION_ID = uuid("6b763f1d-c5bc-4080-b499-d29debc0a7b8"); + private static final long PROTECTION_FENCE = 23L; + + @TempDir static Path temporaryDirectory; + + private static TestPki pki; + + @BeforeAll + static void generateTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactSameNamespaceWorldPeerAcquiresTheExactFirstReceiptWithTheCommonClient() + throws Exception { + var fixture = Fixtures.create(); + var owner = mock(AccountStartSessionActivationProtectionAcquisitionService.class); + when(owner.acquire(any())).thenReturn(fixture.accountEvidence()); + try (TransportServer server = startServer(owner, false); + var client = newClient(server.port(), pki.worldClient())) { + client.init(); + + var actual = client.acquire(fixture.input()); + + assertThat(actual.canonicalBytes()) + .containsExactly(fixture.accountEvidence().canonicalBytes()); + assertThat(actual.request().canonicalBytes()) + .containsExactly(fixture.accountEvidence().request().canonicalBytes()); + assertThat(server.handlerCalls()).hasValue(1); + ArgumentCaptor + captured = + ArgumentCaptor.forClass( + AccountStartSessionActivationProtectionAcquisitionService.AcquisitionRequest + .class); + verify(owner).acquire(captured.capture()); + assertThat(captured.getValue().originalPostAuthorizationTuple()) + .containsExactly(fixture.input().originalPostAuthorizationTuple()); + assertThat(captured.getValue().gameSessionOwnerMutationId()) + .isEqualTo(fixture.input().gameSessionOwnerMutationId()); + assertThat(captured.getValue().gameSessionOwnerAttemptId()) + .isEqualTo(fixture.input().gameSessionOwnerAttemptId()); + assertThat(captured.getValue().gameSessionOwnerFence()) + .isEqualTo(fixture.input().gameSessionOwnerFence()); + assertThat(captured.getValue().worldActivationRequest().canonicalRequestBytes()) + .containsExactly(fixture.input().worldActivationRequest().canonicalRequestBytes()); + assertThat(captured.getValue().worldActivationRequest().preparingEvidenceBytes()) + .containsExactly(fixture.input().worldActivationRequest().preparingEvidenceBytes()); + } + } + + @Test + void trustedWrongServiceAndNamespacePeersAreDeniedBeforeOwnerInteraction() throws Exception { + var fixture = Fixtures.create(); + for (TestIdentity identity : List.of(pki.wrongServiceClient(), pki.otherNamespaceClient())) { + var owner = mock(AccountStartSessionActivationProtectionAcquisitionService.class); + try (TransportServer server = startServer(owner, false); + var client = newClient(server.port(), identity)) { + client.init(); + + assertThatThrownBy(() -> client.acquire(fixture.input())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(1); + verifyNoInteractions(owner); + } + } + } + + @Test + void missingClientCertificateIsRejectedByTlsBeforeHandlerOrOwner() throws Exception { + var owner = mock(AccountStartSessionActivationProtectionAcquisitionService.class); + var fixture = Fixtures.create(); + try (TransportServer server = startServer(owner, false); + ClientTransport client = newClientWithoutIdentity(server.port())) { + var request = + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toRequest( + fixture.input(), NAMESPACE); + assertThatThrownBy(() -> client.acquire(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "missing client certificate must fail during TLS negotiation: %s", + failure) + .isTrue()); + + assertThat(server.handlerCalls()).hasValue(0); + verifyNoInteractions(owner); + } + } + + @Test + void authenticatedEndUserContextIsDeniedAtHandlerBeforeOwnerInteraction() throws Exception { + var owner = mock(AccountStartSessionActivationProtectionAcquisitionService.class); + var fixture = Fixtures.create(); + try (TransportServer server = startServer(owner, true); + var client = newClient(server.port(), pki.worldClient())) { + client.init(); + + assertThatThrownBy(() -> client.acquire(fixture.input())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).hasValue(1); + verifyNoInteractions(owner); + } + } + + private static TransportServer startServer( + AccountStartSessionActivationProtectionAcquisitionService owner, boolean injectEndUserContext) + throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + var service = + new AccountStartSessionActivationProtectionAcquisitionGrpcService(owner, NAMESPACE); + ServerInterceptor countHandlerCalls = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + handlerCalls.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + ServerInterceptor endUserContext = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + var delegate = next.startCall(call, metadata); + if (!injectEndUserContext) return delegate; + return new io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener<>( + delegate) { + @Override + public void onHalfClose() { + SessionContext.setContext("123", List.of(), Map.of()); + try { + super.onHalfClose(); + } finally { + SessionContext.clear(); + } + } + }; + } + }; + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.accountServer().privateKey(), pki.accountServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, + countHandlerCalls, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor(), + endUserContext)) + .build() + .start(); + return new TransportServer(server, handlerCalls); + } + + private static GrpcAccountStartSessionActivationProtectionAcquisitionClient newClient( + int port, TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + return new GrpcAccountStartSessionActivationProtectionAcquisitionClient( + endpoints, + pki.clientProperties(temporaryDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ClientTransport newClientWithoutIdentity(int port) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCaCert(pki.caCertificatePem().toString()); + ManagedChannel channel = + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false); + return new ClientTransport(channel); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record TransportServer(Server server, AtomicInteger handlerCalls) + implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private AcquireOriginalStartSessionActivationProtectionResponse acquire( + AcquireOriginalStartSessionActivationProtectionRequest request) { + return AccountStartSessionActivationProtectionAcquisitionServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .acquireOriginalStartSessionActivationProtection(request); + } + + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC client did not terminate"); + } + } + } + + /** Canonical structured values for transport testing; owners and authorities remain mocked. */ + static final class Fixtures { + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID GAME_INSTANCE = uuid("12121212-1212-4212-8212-121212121212"); + private static final UUID PLAYABLE_NAMESPACE = uuid("23232323-2323-4232-8232-232323232323"); + private static final UUID REALM = uuid("34343434-3434-4343-8343-343434343434"); + private static final UUID VERSION = uuid("34343434-3434-4343-8343-343434343435"); + private static final UUID SOURCE_OPERATION = uuid("34343434-3434-4343-8343-343434343436"); + private static final UUID ROOM_TEMPLATE = uuid("34343434-3434-4343-8343-343434343437"); + private static final UUID PARTICIPATION = uuid("47b3be7f-a32f-4e19-8916-8c3b8da07a82"); + private static final UUID MUTATION = uuid("f1a3ab1e-9147-4667-b6c4-6eb5119e8a31"); + private static final UUID ATTEMPT = uuid("ec13cc04-ec15-4eb8-a018-c2c5e8da65f8"); + private static final UUID ACTIVATION = uuid("c0f491b5-7acb-4eb4-943b-29e387401a55"); + private static final UUID GAME_SESSION_READ = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID WORLD_READ = uuid("b20d71ee-0c8e-4672-8abf-ff08b3d7153e"); + private static final UUID START_LOCATION_READ = uuid("0c69ec92-9e37-4f1a-8fc2-956d1093e2b2"); + private static final UUID SELECTOR_OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID SELECTOR_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID SELECTOR_COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID SELECTOR_FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID SELECTOR_ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID SELECTOR_READ_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID SELECTOR_VERSION_IDENTITY_OPERATION = + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final UUID SELECTOR_INTAKE_ID = SELECTOR_FENCE_ID; + private static final UUID SELECTOR_INTAKE_OPERATION_ID = SELECTOR_ACTOR_ID; + private static final UUID SELECTOR_PUBLICATION_FENCE = + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID SELECTOR_REGION_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID SELECTOR_ZONE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID SELECTOR_REGION_REVISION_ID = + uuid("12345678-1234-4234-8234-123456789001"); + private static final UUID SELECTOR_ZONE_REVISION_ID = + uuid("12345678-1234-4234-8234-123456789002"); + private static final UUID SELECTOR_ROOM_REVISION_ID = + uuid("12345678-1234-4234-8234-123456789003"); + private static final String CONTROL_REQUEST = "activation-transport-original-request"; + private static final String WORLD_SLUG = "activation-transport-world"; + private static final Instant ORIGINAL_LEASE_EXPIRY = + Instant.parse("2026-10-09T10:20:30.456789Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private Fixtures() {} + + static TransportFixture create() { + var world = worldFixture(); + var tuple = originalTuple(world); + var input = + new AccountStartSessionActivationProtectionAcquisitionInput( + tuple.canonicalBytes(), MUTATION, ATTEMPT, 21L, world.activation()); + var gameSessionReadRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + GAME_SESSION_READ, + NAMESPACE, + TENANT, + WORLD_SLUG, + GAME_INSTANCE, + CONTROL_REQUEST, + world.descriptor().launchDescriptorId(), + world.descriptor().requestDigest(), + world.descriptor().resultDigest(), + world.release().evidenceDigest()); + var gameSessionReadResult = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + gameSessionReadRequest, + PLAYABLE_NAMESPACE, + RealmEntryPolicy.StateScope.SHARED, + true, + REALM, + 17L, + CurrentGameInstanceStatus.STARTING, + 7L, + world.binding()); + var launchReadRequest = + new OriginalStartSessionLaunchReadEvidence.Request( + gameSessionReadRequest, tuple.canonicalBytes()); + var launchReadResult = + new OriginalStartSessionLaunchReadEvidence.Result( + launchReadRequest, gameSessionReadResult, tuple.canonicalBytes()); + var accountRequest = + AccountStartSessionActivationProtectionRequest.create( + tuple.canonicalBytes(), + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + MUTATION, + ATTEMPT, + 21L, + ORIGINAL_LEASE_EXPIRY, + PARTICIPATION, + 22L, + launchReadResult, + world.activation()); + byte[] capture = captureReference(tuple); + var accountEvidence = + AccountStartSessionActivationProtectionEvidence.create( + accountRequest, + PROTECTION_ID, + PROTECTION_FENCE, + Instant.parse("2026-10-09T10:11:12.123000Z"), + capture, + sha256(capture), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + TENANT.toString(), + "2", + "17", + null, + null, + "original Account source evidence".getBytes(StandardCharsets.UTF_8)))); + var active = + new WorldCanonicalInstanceLifecycleEvidence( + world.preparing().request(), + world.preparing().launchBinding(), + world.preparing().startLocation(), + world.preparing().runtimeRoomInstanceId(), + "ACTIVE", + world.preparing().lifecycleEpoch() + 1L, + world.preparing().rowVersion() + 1L, + world.preparing().captureId(), + world.preparing().graphSha256(), + world.preparing().preparationInputDigest(), + world.preparing().operationalRegionAssignments()); + var result = + new WorldCanonicalInstanceActivation.Result( + world.activation(), WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, active); + var terminal = + WorldOriginalStartSessionActivationTerminalEvidence.create(accountEvidence, result, 29L); + return new TransportFixture(input, accountEvidence, terminal); + } + + private static WorldFixture worldFixture() { + WorldPublishedStartLocationEvidence selected = selectedWorldStartLocation(); + var selectedRequest = selected.request(); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + CONTROL_REQUEST, + TENANT, + WORLD_SLUG, + SOURCE_OPERATION, + "sha256:" + "1".repeat(64), + 91L, + false, + null, + false, + null, + false, + null, + false, + null); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + "activation-transport-descriptor", + 42L, + false, + null, + "{}", + "generation-revision", + 9L, + 7L, + "activation-transport-release", + false, + null); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selectedRequest.appliedCommitId(), + selectedRequest.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "2".repeat(64) : null)) + .toList(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT, + selectedRequest.canonicalVersionId(), + WORLD_SLUG, + SOURCE_OPERATION, + "sha256:" + "1".repeat(64), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selectedRequest.publishWorkflowId(), + selectedRequest.appliedCommitId(), + participants, + "sha256:" + "3".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision(), + selected); + var binding = new CompleteLaunchBindingEvidence(descriptor, release); + var selectorReceipt = + WorldDraftStartLocationEvidence.fromStored(selected.selectorReceiptBytes()); + var startLocation = selectorReceipt.startLocation(); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + START_LOCATION_READ, + NAMESPACE, + TENANT, + WORLD_SLUG, + GAME_INSTANCE, + PLAYABLE_NAMESPACE, + "SHARED", + true, + CONTROL_REQUEST, + VERSION, + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var preparing = + new WorldCanonicalInstanceLifecycleEvidence( + lifecycleRequest, + binding, + startLocation, + 1042L, + "PREPARING", + 3L, + 0L, + uuid("bcbcbcbc-abab-4bcb-8bcb-bcbcbcbcbcbc"), + selectorReceipt.graphDigest().substring("sha256:".length()), + "sha256:" + "5".repeat(64), + Map.of( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"))); + var activation = new WorldCanonicalInstanceActivation.Request(ACTIVATION, preparing); + return new WorldFixture(descriptor, release, binding, preparing, activation); + } + + /** Complete Account-bound World APPLIED-v2 selection carrier with the canonical ROOM row. */ + private static WorldPublishedStartLocationEvidence selectedWorldStartLocation() { + try { + DraftCommitBinding draft = selectedWorldDraft(); + byte[] accountBytes = selectedAccountBinding(draft); + var terminalRequest = + new WorldDraftTerminalReadEvidence.Request( + WorldDraftTerminalReadEvidence.Request.SCHEMA_VERSION, + NAMESPACE, + SELECTOR_READ_ID, + accountBytes); + var readback = selectedWorldReadback(terminalRequest, draft); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + NAMESPACE, + TENANT, + VERSION, + SELECTOR_INTAKE_ID, + SELECTOR_PUBLICATION_FENCE, + "activation-transport-publication-request", + "a".repeat(64), + 5L, + "activation-transport-publish-workflow", + draft.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var applied = JSON.readTree(readback.result()); + byte[] receipt = + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + return new WorldPublishedStartLocationEvidence( + request, receipt, readback.fullBinding(), readback.result()); + } catch (Exception invalidFixture) { + throw new IllegalStateException( + "Canonical selected World transport fixture is invalid", invalidFixture); + } + } + + private static DraftCommitBinding selectedWorldDraft() throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", + TENANT.toString(), + "versionId", + VERSION.toString(), + "startLocation", + Map.of( + "tenantId", TENANT.toString(), + "versionId", VERSION.toString(), + "roomTemplateId", ROOM_TEMPLATE.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return DraftCommitBinding.create( + new TargetProof(TENANT, VERSION, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + SELECTOR_REQUEST_ID, + SELECTOR_COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + SELECTOR_REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + SELECTOR_REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + SELECTOR_REGION_ID, + declaration)), + new RevisionPayload( + "1", + SELECTOR_ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + SELECTOR_ZONE_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", + SELECTOR_ZONE_ID, + null)), + new RevisionPayload( + "2", + SELECTOR_ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + SELECTOR_ROOM_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", + ROOM_TEMPLATE, + null))), + List.of( + affected("REGION", SELECTOR_REGION_ID, "REGION_SUBTREE", SELECTOR_REGION_ID), + affected("ZONE", SELECTOR_ZONE_ID, "REGION_SUBTREE", SELECTOR_REGION_ID), + affected("ROOM", ROOM_TEMPLATE, "ZONE_SUBTREE", SELECTOR_ZONE_ID)) + .stream() + .flatMap(List::stream) + .toList()); + } + + private static String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) throws Exception { + Map payload = new LinkedHashMap<>(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", SELECTOR_COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private static List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private static byte[] selectedAccountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + SELECTOR_OPERATION_ID, + SELECTOR_REQUEST_ID, + SELECTOR_COMMIT_ID, + SELECTOR_FENCE_ID, + SELECTOR_ACTOR_ID, + TENANT, + VERSION, + "base-1", + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + SELECTOR_ACTOR_ID.toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback selectedWorldReadback( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var account = request.accountBinding(); + var operation = new ByteArrayOutputStream(); + var frames = new DataOutputStream(operation); + frame(frames, "world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) frame(frames, id.toString()); + frame(frames, draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + SELECTOR_VERSION_IDENTITY_OPERATION.toString(), + Long.toString(draft.target().gameDesignVersionRowId()), + SELECTOR_INTAKE_ID.toString(), + SELECTOR_INTAKE_OPERATION_ID.toString(), + "a".repeat(64), + SOURCE_OPERATION.toString(), + "b".repeat(64), + "c".repeat(64))) frame(frames, value); + frame(frames, "sha256:" + sha256(request.originalAccountBinding())); + frame(frames, request.originalAccountBinding()); + + byte[] graph = selectedGraphBytes(request, draft); + String graphDigest = "sha256:" + sha256(graph); + var receipt = + WorldDraftStartLocationEvidence.create( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + "sha256:" + sha256(request.originalAccountBinding()), + draft.digest(), + new RoomTemplateRef(TENANT, VERSION, ROOM_TEMPLATE), + graphDigest); + Map result = new LinkedHashMap<>(); + result.put("schema", "world-draft-graph-applied/v2"); + result.put("status", "APPLIED"); + result.put( + "operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + result.put( + "startLocationReceiptBase64", + Base64.getEncoder().encodeToString(receipt.canonicalBytes())); + result.put("startLocationReceiptDigest", receipt.receiptDigest()); + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + "1")) + .toList()); + var readback = + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + request.originalAccountBinding(), + canonical(result)); + var response = WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(readback)); + return WorldDraftTerminalReadGrpcCodec.fromResponse(request, response) + .ownerReadback() + .orElseThrow(); + } + + private static byte[] selectedGraphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + Map root = new LinkedHashMap<>(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + List> rows = new ArrayList<>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + var mapping = new LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put( + "family", + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", "")); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put( + "version_identity_operation_id", SELECTOR_VERSION_IDENTITY_OPERATION.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private static void frame(DataOutputStream output, String value) throws IOException { + frame(output, value.getBytes(StandardCharsets.UTF_8)); + } + + private static void frame(DataOutputStream output, byte[] value) throws IOException { + output.writeInt(value.length); + output.write(value); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(WorldFixture world) { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + CONTROL_REQUEST, + ACTOR, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "canonical original StartSession activation transport attempt")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + uuid("efefefef-efef-4fef-8fef-efefefefefef"), + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map operation = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(TENANT.toString(), 3L), + "membershipAuthorityGeneration", Map.of(TENANT.toString(), 4L), + "privateRealmGrantVersions", List.of()); + Map issuanceEvidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", ACTOR.toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + return canonical( + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", TENANT.toString(), "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", TENANT.toString()), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(TENANT.toString(), 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuanceEvidence)); + } + + private static byte[] captureReference(StartSessionPostAuthorizationExecutionTuple tuple) { + return canonical( + Map.of( + "schema", + AccountStartSessionAdmissionProtectionEvidence.SOURCE_CAPTURE_REFERENCE_SCHEMA, + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "capturedAt", + "2026-10-09T10:11:12.123Z", + "bundleReference", + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "sourceVersion", "17", + "sourceFence", "23", + "linearization", "18446744073709551615"), + "snapshotSha256", + "d".repeat(64))); + } + + private static byte[] canonical(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + } + + record TransportFixture( + AccountStartSessionActivationProtectionAcquisitionInput input, + AccountStartSessionActivationProtectionEvidence accountEvidence, + WorldOriginalStartSessionActivationTerminalEvidence terminal) {} + + private record WorldFixture( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence release, + CompleteLaunchBindingEvidence binding, + WorldCanonicalInstanceLifecycleEvidence preparing, + WorldCanonicalInstanceActivation.Request activation) {} + + record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + record TestPki( + X509Certificate caCertificate, + Path caCertificatePem, + TestIdentity accountServer, + TestIdentity worldClient, + TestIdentity wrongServiceClient, + TestIdentity otherNamespaceClient) { + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final String ACCOUNT_URI = + "spiffe://firemud/ns/world-runtime/sa/account-service"; + private static final String WRONG_SERVICE_URI = + "spiffe://firemud/ns/world-runtime/sa/game-session-service"; + private static final String OTHER_NAMESPACE_URI = + "spiffe://firemud/ns/other-runtime/sa/world-management-service"; + + static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("activation-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD Account activation test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("activation-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + caFile, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "world-management-client", WORLD_URI, false), + issueIdentity( + directory, caStore, caFile, "wrong-service-client", WRONG_SERVICE_URI, false), + issueIdentity( + directory, caStore, caFile, "other-namespace-client", OTHER_NAMESPACE_URI, false)); + } + + CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + Path certificate = + writePem( + directory.resolve(identity.alias() + ".crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve(identity.alias() + ".key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(certificate.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(caCertificatePem.toString()); + tls.setPlaintext(false); + return tls; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String extendedKeyUsage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + ArrayList command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcMtlsTest.java new file mode 100644 index 0000000000..1e122301da --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcMtlsTest.java @@ -0,0 +1,291 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.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 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.net.InetSocketAddress; +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountStartSessionActivationProtectionSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionActivationProtectionRequest; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionActivationProtectionResponse; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository.StoredSettlement; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionActivationProtectionSettlementGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionActivationProtectionSettlementService; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionSettlementGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionSettlementInput; +import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionActivationProtectionSettlementClient; +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.security.SessionContext; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Physical loopback mTLS transport-only proof for the unregistered Account settlement receiver. The + * mocked Account owner proves no Account authority, SQL, or World activation. + */ +class AccountStartSessionActivationProtectionSettlementGrpcMtlsTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID PROTECTION_ID = UUID.fromString("6b763f1d-c5bc-4080-b499-d29debc0a7b8"); + private static final long PROTECTION_FENCE = 23L; + private static final UUID SETTLEMENT_REQUEST_ID = + UUID.fromString("70fa5422-85c8-4704-b516-229e130fedcc"); + + @TempDir static Path temporaryDirectory; + + private static AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.TestPki pki; + + @BeforeAll + static void generateTrustedWorkloadCertificates() throws Exception { + pki = + AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.TestPki.create( + temporaryDirectory); + } + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactSameNamespaceWorldPeerSettlesAndReturnsExactCorrelationAndTerminalBytes() + throws Exception { + var fixture = AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.Fixtures.create(); + Instant settledAt = Instant.parse("2026-10-11T01:02:03.000004Z"); + var stored = new StoredSettlement(fixture.terminal(), settledAt); + var owner = mock(AccountStartSessionActivationProtectionSettlementService.class); + when(owner.settle(PROTECTION_ID, PROTECTION_FENCE)).thenReturn(stored); + try (TransportServer server = startServer(owner, false); + var client = newClient(server.port(), pki.worldClient())) { + client.init(); + var input = + new AccountStartSessionActivationProtectionSettlementInput( + NAMESPACE, SETTLEMENT_REQUEST_ID, PROTECTION_ID, PROTECTION_FENCE); + + var actual = client.settle(input); + + assertThat(actual.settlementRequestId()).isEqualTo(SETTLEMENT_REQUEST_ID); + assertThat(actual.accountProtectionId()).isEqualTo(PROTECTION_ID); + assertThat(actual.accountProtectionFence()).isEqualTo(PROTECTION_FENCE); + assertThat(actual.settledAt()).isEqualTo(settledAt); + assertThat(actual.terminal().canonicalBytes()) + .containsExactly(fixture.terminal().canonicalBytes()); + assertThat(server.handlerCalls()).hasValue(1); + verify(owner).settle(PROTECTION_ID, PROTECTION_FENCE); + } + } + + @Test + void trustedWrongServiceAndNamespacePeersAreDeniedBeforeOwnerInteraction() throws Exception { + var input = + new AccountStartSessionActivationProtectionSettlementInput( + NAMESPACE, SETTLEMENT_REQUEST_ID, PROTECTION_ID, PROTECTION_FENCE); + for (var identity : List.of(pki.wrongServiceClient(), pki.otherNamespaceClient())) { + var owner = mock(AccountStartSessionActivationProtectionSettlementService.class); + try (TransportServer server = startServer(owner, false); + var client = newClient(server.port(), identity)) { + client.init(); + + assertThatThrownBy(() -> client.settle(input)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(1); + verifyNoInteractions(owner); + } + } + } + + @Test + void missingClientCertificateIsRejectedByTlsBeforeHandlerOrOwner() throws Exception { + var owner = mock(AccountStartSessionActivationProtectionSettlementService.class); + try (TransportServer server = startServer(owner, false); + ClientTransport client = newClientWithoutIdentity(server.port())) { + var input = + new AccountStartSessionActivationProtectionSettlementInput( + NAMESPACE, SETTLEMENT_REQUEST_ID, PROTECTION_ID, PROTECTION_FENCE); + var request = AccountStartSessionActivationProtectionSettlementGrpcCodec.toRequest(input); + + assertThatThrownBy(() -> client.settle(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "missing client certificate must fail during TLS negotiation: %s", + failure) + .isTrue()); + + assertThat(server.handlerCalls()).hasValue(0); + verifyNoInteractions(owner); + } + } + + @Test + void authenticatedEndUserContextIsDeniedAtHandlerBeforeOwnerInteraction() throws Exception { + var owner = mock(AccountStartSessionActivationProtectionSettlementService.class); + try (TransportServer server = startServer(owner, true); + var client = newClient(server.port(), pki.worldClient())) { + client.init(); + var input = + new AccountStartSessionActivationProtectionSettlementInput( + NAMESPACE, SETTLEMENT_REQUEST_ID, PROTECTION_ID, PROTECTION_FENCE); + + assertThatThrownBy(() -> client.settle(input)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).hasValue(1); + verifyNoInteractions(owner); + } + } + + private static TransportServer startServer( + AccountStartSessionActivationProtectionSettlementService owner, boolean injectEndUserContext) + throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + var service = + new AccountStartSessionActivationProtectionSettlementGrpcService(owner, NAMESPACE); + ServerInterceptor countHandlerCalls = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + handlerCalls.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + ServerInterceptor endUserContext = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + var delegate = next.startCall(call, metadata); + if (!injectEndUserContext) return delegate; + return new io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener<>( + delegate) { + @Override + public void onHalfClose() { + SessionContext.setContext("123", List.of(), Map.of()); + try { + super.onHalfClose(); + } finally { + SessionContext.clear(); + } + } + }; + } + }; + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.accountServer().privateKey(), pki.accountServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, + countHandlerCalls, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor(), + endUserContext)) + .build() + .start(); + return new TransportServer(server, handlerCalls); + } + + private static GrpcAccountStartSessionActivationProtectionSettlementClient newClient( + int port, + AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + return new GrpcAccountStartSessionActivationProtectionSettlementClient( + endpoints, + pki.clientProperties(temporaryDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ClientTransport newClientWithoutIdentity(int port) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCaCert(pki.caCertificatePem().toString()); + ManagedChannel channel = + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false); + return new ClientTransport(channel); + } + + private record TransportServer(Server server, AtomicInteger handlerCalls) + implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private SettleOriginalStartSessionActivationProtectionResponse settle( + SettleOriginalStartSessionActivationProtectionRequest request) { + return AccountStartSessionActivationProtectionSettlementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .settleOriginalStartSessionActivationProtection(request); + } + + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC client did not terminate"); + } + } + } +} From 4dd7ed01d29a13eb806c45d1e005a9623163416f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:36:57 +1300 Subject: [PATCH 108/129] docs(world): align placement status and region bootstrap ownership --- .../entity-management-service/api-contracts.md | 2 +- .../entity-management-service/runtime-and-data.md | 2 +- .../world-management-service/runtime-and-data.md | 14 +++++++------- design/architecture/system-architecture-ticks.md | 2 ++ 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index da5e28da77..748f0ea754 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -187,4 +187,4 @@ The current contract still leaves player command orchestration, authored stat/co - **Live:** The seeded `firemud.look.rooms` entries provide the visible entities for the demo rooms, `ListRoomEntities` is wired into Game Logic's `ResolveLook`, and the resulting instrumentation is captured in [`look-instrumentation.md`](../../../project-management/slice-support/look-instrumentation.md). - **Stubbed:** Real-time behaviors such as item respawns, stealth/aura-driven visibility, and inventory states still rely on static fixtures so regression tests remain reproducible. -- **Deferred:** Future slices may consume read-only location metadata from the target `character_location` and `npc_location` tables, which are World Management-owned and currently absent; Entity Management is not the location authority and must not create competing tables or fields. Those slices will support multi-instance visibility rules and surface richer context hints (combat alerts, quest markers) while keeping the public DTO focused on display data. +- **Deferred:** Future slices may consume read-only location metadata from World Management. Its [canonical initial-placement contract](../world-management-service/api-contracts.md) has bounded V46 `character_location` storage, but general current-location transitions, occupancy reads, and `npc_location` remain absent; Entity Management is not the location authority and must not create competing tables or fields. Those slices will support multi-instance visibility rules and surface richer context hints (combat alerts, quest markers) while keeping the public DTO focused on display data. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 007f88656d..1ce5a7fb74 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -7,7 +7,7 @@ This document defines Entity Management’s runtime model, persistence ownership The unregistered post-publication authored-core consumer independently reads Game Design through the exact authenticated owner-read client outside Entity SQL, then corroborates the selected source against Entity's retained receipt and the release's immutable Entity participant digest in the existing read-only snapshot. It returns the unchanged qualified result; it neither rewrites the pre-publication `COMMITTED_EMPTY` receipt nor allocates an actor. Its focused tests use mocked reads, so genuine authenticated composition and physical database proof remain open. The complete projection contract remains owned by [Game Design](../game-design-service/game-templates.md#owner-qualified-authored-core-projection), with capability and proof status in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). - The current crafting REST adapter is runtime-reachable legacy implementation drift, not a supported or advertised boundary: the crafting paths and schemas are omitted from the ping-only authoritative OpenAPI, whose root `security: []` applies only to the health contract, so the adapter remains unsupported/nonconformant. The deployed interceptor requires any `AUTHENTICATED` bearer because this non-public path is not in the public-route list, but neither layer provides tenant binding; there is no controller `SessionContext` tenant guard. `CraftingServiceImpl` trusts the DTO's `tenantId`, `resultItemId`, and ingredient item IDs; `CraftingRecipeRepository.findWithIngredientsById` and the update branch use recipe ID alone, while ingredient loading also uses recipe ID alone. The tenant-qualified list methods first select IDs but then re-enter that unqualified lookup, so they are not evidence of an end-to-end tenant predicate. Existing crafting tests do not establish caller-tenant authorization, cross-tenant recipe isolation, or same-tenant result/ingredient ownership. -- World-owned `character_location` and `npc_location` tables plus their authoritative movement, occupancy, and read/write paths are target-only. They are absent from the current schema, migrations, and runtime; `room_instance` is topology rather than actor location, and a Game Session room binding is not World location authority. Entity Management must not add competing location persistence or treat a cache/projection as authoritative. +- World owns canonical player placement under its [API contract](../world-management-service/api-contracts.md). V46 provides bounded initial-player-placement storage in `character_location` and an immutable operation receipt; this is not a general movement/location-transition or occupancy path. `npc_location` and general occupancy persistence/read-write paths remain absent. `room_instance` is topology rather than actor location, and a Game Session room binding is not World location authority. Entity Management must not add competing location persistence or treat a cache/projection as authoritative. - **Target crafting boundary:** require authenticated caller context and exact tenant authorization before any recipe operation, derive the target tenant rather than treating request `tenantId` as authority, and make recipe read/update and ingredient load/update predicates tenant-qualified. Validate that the result item and every ingredient item belong to the target tenant and the same applicable version/Draft scope before writing. A missing context, tenant mismatch, recipe mismatch, or cross-tenant item reference fails closed before any recipe or ingredient mutation; the target negative proof must exercise each case. - Current runtime item/equipment/container mutation RPCs that carry an `effectId` use `entity_mutation_effects` as the domain-local replay table. Entity Management records the applied protobuf response for `{tenantId, effectId}` and returns that stored response on duplicate delivery so `GET`, `DROP`, `PUT`, `TAKE`, `WEAR`, and `REMOVE` do not double-apply after Game Session replay or retry. Requests with a blank `effectId` bypass this table and execute directly; that fallback is current compatibility behavior, not a safe gameplay admission path. This is the current durable effect-replay guard, not a replacement tick-watermark implementation. - The `entitymanagement.mutation.effect.execution{operation,effect_status}` metric distinguishes first apply, replay/no-op, in-progress conflict, reported reuse outcome, and unreadable stored-response outcomes. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index d4f2d480c4..33f68cfc8c 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -63,10 +63,10 @@ World templates follow the same stability rules as entity templates: ## Character Location Ownership -Target ownership (not current storage): World Management is the authoritative owner of character and NPC location for each game instance. The current implementation has live `room_instance` topology and a Game Session room-binding seam, but no authoritative character/NPC location or occupancy persistence. +World Management is the target authoritative owner of character and NPC location for each game instance. Current storage includes the bounded V46 initial-player-placement row in `character_location` and its immutable operation receipt; it does not provide the general location-transition/movement, NPC-location, or occupancy persistence and read/write paths. The row records the initial runtime room, but does not establish a general live-presence or movement authority. -- Target owner tables such as `character_location` and `npc_location` would live in this service’s schema and be written only by World Management logic as part of movement, instancing, and world-creation flows invoked by Game Session; those tables and the write family are absent from the current schema, migrations, and runtime implementation. -- Once implemented, other services, including Entity Management and Game Session, will treat those tables as read-only and rely on World Management gRPC APIs or cached projections. Current room reads and the Game Session binding do not establish that target authority. +- The [World API contract](./api-contracts.md) owns canonical initial player placement. V46 adds `character_location` and `world_canonical_initial_player_location_operation` for that bounded first-placement operation; the placement transport remains unregistered and its service denies by default without a held authenticated authority verifier. General movement/location transitions, `npc_location`, and occupancy remain target-only and absent from the current schema and runtime implementation. +- Other services, including Entity Management and Game Session, treat World-owned location data as read-only and rely on World Management APIs or cached projections. Current room reads and the Game Session binding do not establish general location or occupancy authority. - Target rule: derived caches or denormalized views of location must be refreshed from World Management rather than persisting independent authoritative location fields. Target ownership: World Management is the fact owner for targeting predicates over location, occupancy, range, and mutable room state. Its bounded `TargetingFactSnapshot` responses contain only the compiled source/candidate facts for the requested `RoomInstanceRef` scope and a current world location/version token. For `DROP` and `PICKUP`, the target attestation carries `regionId` from Game Session's durable region authority alongside `RoomInstanceRef`, `regionEpoch`, `executorFence`, the same root `EffectId`, and the unchanged immutable `requestDigest`; World validates its own token and rejects mismatched scope, epoch, or fence. The canonical barrier, Game Logic re-resolution, and Entity commit binding are defined in [Transaction Strategies](../../system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section) and [ADR 0054](../../decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md). The current proto/request and focused proof do not yet demonstrate this path. @@ -75,7 +75,7 @@ Target ownership: World Management is the fact owner for targeting predicates ov Movement, drops, pickups, and room presence are cross-service by design: -- Target: World Management is authoritative for occupancy/location and room-scoped persistent ambient state keyed by runtime `RoomInstanceRef`; current `room_instance` topology and ambient rows do not include the absent character/NPC location or occupancy write family. Weather is an explicit exception while its target aggregate remains unresolved: the owner must choose and accept a region-scoped or room-scoped selector before any Weather identity or mutation can be defined. Weather mutation admission and reconciliation remain fenced and non-mutating until that selector is accepted, including writes represented by `world_event` and `region_instance.weather`. Initial Weather scheduling during world creation and generic `WEATHER_CHANGE` event scheduling/application follow the same rule: while the selector is unresolved they are explicitly deferred and non-mutating, so no Weather event row is inserted or processed and `region_instance.weather` is not changed. +- Target: World Management is authoritative for occupancy/location and room-scoped persistent ambient state keyed by runtime `RoomInstanceRef`. The bounded V46 initial-player-placement row exists, but current `room_instance` topology and ambient rows do not provide general character-location transitions, NPC location, or occupancy reads/writes. Weather is an explicit exception while its target aggregate remains unresolved: the owner must choose and accept a region-scoped or room-scoped selector before any Weather identity or mutation can be defined. Weather mutation admission and reconciliation remain fenced and non-mutating until that selector is accepted, including writes represented by `world_event` and `region_instance.weather`. Initial Weather scheduling during world creation and generic `WEATHER_CHANGE` event scheduling/application follow the same rule: while the selector is unresolved they are explicitly deferred and non-mutating, so no Weather event row is inserted or processed and `region_instance.weather` is not changed. - Entity Management is authoritative for containment and item instances, including synthetic room-ground containers keyed by the same `RoomInstanceRef`. - All spatial effects must carry the target `RoomInstanceRef` and a canonical tick root `EffectId`; correctness-sensitive mutations also carry exact epoch and relevant owner-state preconditions. - `DROP` and `PICKUP` use the canonical Game Session barrier/attestation sequence before the Entity-local holder commit; World Management owns only the World fact validation and attestation issuance. The binding and handoff rules are defined in [Transaction Strategies](../../system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section) and [ADR 0054](../../decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md). The current proto/request and focused proof do not yet demonstrate this validation path. @@ -128,7 +128,7 @@ When changing Redis usage or adding prefixes here, follow the [Redis Design Chec - `world_instance_status`, or equivalent lifecycle state, tracks the ADR 0123 transitions `PREPARING -> ACTIVE`, `PREPARING -> FAILED_PRE_ACTIVATION`, `PREPARING -> TERMINATING`, `FAILED_PRE_ACTIVATION -> TERMINATING`, `ACTIVE -> TERMINATING`, and `TERMINATING -> TERMINATED`. - `FAILED_PRE_ACTIVATION` is terminal for admission by that `gameInstanceId`, not proof that cleanup completed; separate owner-scoped cleanup progress may continue. Recovery is modeled as provisioning a new `gameInstanceId` and rerunning world creation. - `world_instance_lifecycle_lock`, or equivalent fenced token, enforces single-writer lifecycle transitions per `(tenantId, gameInstanceId)`. -- Target-only: `character_location` and `npc_location` would record current rooms and instance occupancy. These tables are absent from the current schema and runtime; live `room_instance` rows describe topology, while the Game Session room binding is not authoritative World location. +- V46 `character_location` records bounded initial player placement, backed by an immutable placement-operation receipt. General current-location transitions, `npc_location`, and occupancy persistence remain target-only/absent; live `room_instance` rows describe topology, while the Game Session room binding is not authoritative World location. ### Replacement cutover hold ownership @@ -173,13 +173,13 @@ The exhaustive S1/S2/S3 rules, unknown-state fail-closed behavior, namespace mod - current `world_instance` lifecycle rows (lifecycle/provisioning state, not replacement payload); - `region_instance`, `zone_instance`, `room_instance`, `room_instance_exit`; - legacy `instance` rows (explicit replacement mapping `EXCLUDED`; cleanup is the separate zone-scoped legacy-instance operation, not parent `InstanceTermination`); - - Target-only/absent in the current initial slice: `character_location`, `npc_location`, and occupancy rows; + - Existing S3 runtime location consequence: the bounded initial-placement `character_location` row; separate immutable `world_canonical_initial_player_location_operation` receipts remain distinct evidence and are not assigned a replacement cleanup classification here; target-only/absent: general location-transition, `npc_location`, and occupancy families; - ambient runtime state such as weather, door state, hazard state, instanced events, and instance-scoped schedules; - `world_event` rows tied to a specific `gameInstanceId`. - Target-only/absent in current persistence: `population_schedule_instance` rows keyed by `gameInstanceId`; - Target-only/absent in current persistence: runtime-instance `generation_run` rows, which are diagnostic or provenance only if later recorded. -Local consequence: the current World-owned runtime persistence includes `world_instance` lifecycle rows, `region_instance`, `zone_instance`, `room_instance`, `room_instance_exit`, and `world_event`; ambient behavior is only partial in the current slice because `region_instance.weather` and the Weather event storage exist, while new Weather scheduling and retained Weather application are now fail-closed. The target Weather path remains fenced and non-mutating until its selector and typed effect contract are accepted; door/hazard state, instanced-event state, and instance-scoped schedules are target-only or absent. Target-only/absent `population_schedule_instance` is classified `S3` when implemented, and target-only/absent runtime-instance `generation_run` remains diagnostic/provenance only if later recorded, never replacement payload; the legacy `instance` family is likewise explicitly `S3` but excluded from replacement mapping, and its separate cleanup operation is not lifecycle cleanup. The target-only location/occupancy families would also be `S3` when implemented, and no World-owned initial-slice family is mandatory `S2`. World Management must not silently copy room ambient state, occupancy, scheduled world events, generated instance topology, `population_schedule_instance` rows, runtime-instance `generation_run` rows, or legacy `instance` rows into the target instance. Any new family must be registered with its owner, classification, mapping/application contract where applicable, cleanup operation, and freshness evidence before launch or cutover can use it. The live first validation cut remains shallow: it checks a cutover-eligible source lifecycle and retained topology, but does not prove the complete ADR 0122 preflight. +Local consequence: the current World-owned runtime persistence includes `world_instance` lifecycle rows, `region_instance`, `zone_instance`, `room_instance`, `room_instance_exit`, `world_event`, and the bounded V46 initial-placement `character_location` row; the separate immutable `world_canonical_initial_player_location_operation` receipts are operation evidence, with no S1/S2/S3 cleanup classification or retention proof implied here. Ambient behavior is only partial in the current slice because `region_instance.weather` and the Weather event storage exist, while new Weather scheduling and retained Weather application are now fail-closed. The target Weather path remains fenced and non-mutating until its selector and typed effect contract are accepted; door/hazard state, instanced-event state, and instance-scoped schedules are target-only or absent. Target-only/absent `population_schedule_instance` is classified `S3` when implemented, and target-only/absent runtime-instance `generation_run` remains diagnostic/provenance only if later recorded, never replacement payload; the legacy `instance` family is likewise explicitly `S3` but excluded from replacement mapping, and its separate cleanup operation is not lifecycle cleanup. The bounded initial-placement `character_location` row is existing S3 location storage; general location-transition, NPC-location, and occupancy families remain target-only/absent and would be S3 when implemented. No World-owned initial-slice family is mandatory S2. World Management must not silently copy room ambient state, occupancy, scheduled world events, generated instance topology, `population_schedule_instance` rows, runtime-instance `generation_run` rows, or legacy `instance` rows into the target instance. Any new family must be registered with its owner, classification, mapping/application contract where applicable, cleanup operation, and freshness evidence before launch or cutover can use it. The live first validation cut remains shallow: it checks a cutover-eligible source lifecycle and retained topology, but does not prove the complete ADR 0122 preflight. ## Digest Input Manifest diff --git a/design/architecture/system-architecture-ticks.md b/design/architecture/system-architecture-ticks.md index 4abf7abc50..ff0c9f02f9 100644 --- a/design/architecture/system-architecture-ticks.md +++ b/design/architecture/system-architecture-ticks.md @@ -210,6 +210,8 @@ The target executor: Other workers may be running but do not process ticks for that region while the lease is held. See `system-architecture-tick-concepts-and-invariants.md` for the full authority and lease model. +First timeline bootstrap is Game Session lease-owner work performed on demand from World's exact authenticated operational-region assignments, not a launcher-created default executor or a separate ownerless preparation path. Only a genuinely absent, fully qualified `` timeline may start at `regionEpoch = 1` and `lastCommittedTickId = -1`, making the first tick `tickId = 0`. The owner atomically installs the actual fresh durable executor fence for that lease acquisition and revalidates that same lease; neither possession of a lease nor the assignment read alone establishes admission or mutation authority. Retained timelines and replay checkpoints remain unchanged across restart or ownership handoff: missing or contradictory qualification denies bootstrap, and synthetic region IDs or reset-on-restart are forbidden. This is the target first-creation rule, not proof that the current instance-scoped implementation has shipped region bootstrap. + The current-live durable ownership boundary remains instance-scoped at `{tenantId, gameInstanceId}`. Its `RuntimeOwnershipStatus` row carries the selected runtime region fields and opaque `executorFence`, but it is not yet a separate durable ownership row for every region. The region-scoped lease and target-state `GetRegionTickStatus` model above must not be treated as replacing that live instance-scoped boundary until the target surfaces are shipped. ### Ownership Identities and Fences From ff8bcf489e824da34e0fe8a087046b96161572aa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:47:35 +1300 Subject: [PATCH 109/129] test(world): prove protected activation transport identity guards --- ...ame-authoring-publishing-and-activation.md | 2 + ...ionActivationTerminalReadGrpcMtlsTest.java | 201 +++++ ...essionProtectedActivationGrpcMtlsTest.java | 835 ++++++++++++++++++ 3 files changed, 1038 insertions(+) create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcMtlsTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java 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 738f160215..55ff28bc48 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +World's unregistered protected-activation and activation-terminal-read receivers now have eight executed loopback-mTLS cases using their real handlers and file-backed Common clients: exact same-namespace Game Session and Account callers respectively retain complete canonical terminal/protection bytes and request correlation; trusted wrong-service or wrong-namespace certificates and authenticated end-user context reach no owner; missing client certificates reach neither handler nor owner. The World owners are mocked and the evidence is synthetic, so these cases prove transport enforcement, not genuine source authorization, PostgreSQL activation, fenced abort or Account settlement. The corrected full World check passes in 1 minute 4 seconds with 678 unit cases executed and zero skips, failures or errors, including all eight new cases, formatting, Checkstyle, SpotBugs and coverage. Its unchanged integration task reuses prior results: one non-container case executed and 229 container-dependent cases skipped. Initial test-local channel-cleanup and digest-fixture failures were corrected without changing production guards or assertions. All four complete handoffs remain open; runtime registration and activation remain denied. + Account's distinct activation-protection acquisition and settlement receivers now have eight executed loopback-mTLS cases: exact same-namespace World callers preserve full canonical receipt/terminal bytes and lookup correlation, trusted wrong-service or wrong-namespace callers reach no owner, missing certificates reach neither handler nor owner, and authenticated end-user context reaches no owner. These tests use file-backed test certificates and mocked Account owners; they prove transport enforcement, not current Account authorization, source exclusion, PostgreSQL settlement or World activation. The corrected full Account check passes in 2 minutes 41 seconds, including formatting, Checkstyle, SpotBugs and coverage, with 1,385 unit cases executed and zero skips, failures or errors. Its unchanged integration task reuses the preceding results: twelve non-container cases executed and 289 container cases skipped. The initial five failures were invalid synthetic selected-release fixtures; the correction supplies the complete closed selector and APPLIED-v2 graph evidence without changing production guards or weakening assertions. Runtime registration and genuine producer/consumer proof remain denied. Gameplay owns the separate explicit current-player authority producer needed for nonempty `PLAYER_CREATED` allocation; launch creator authority cannot substitute. Exact published source `a336f4245a46742bda991eba73addf31dcc689b5` has a confirmed Common Platform compilation failure in [Validation run 38106738131](https://github.com/benhook1013/FireMUD/actions/runs/38106738131): two same-package test files declared `CurrentAttemptTestData`. The duplicate fixture is removed without changing its tuple or assertions. Forced fresh Common Platform checks pass in 3 minutes 51 seconds, including 715 executed tests with zero skips, failures or errors; 28 of 29 tasks execute. Replacement exact-head CI remains a separate requirement. The preceding reused local results below did not establish that failed source's fresh CI compilation. diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcMtlsTest.java new file mode 100644 index 0000000000..53a6e4ebba --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcMtlsTest.java @@ -0,0 +1,201 @@ +package unit.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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.nio.file.Path; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.world.GrpcWorldOriginalStartSessionActivationTerminalReadClient; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalReadInput; +import net.firedevops.firemud.test.TlsTestSupport; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionActivationTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalStartSessionActivationTerminalEvidenceResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldOriginalStartSessionActivationTerminalReadServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Loopback mTLS transport proof only; the World owner is mocked and remains unregistered. */ +class WorldOriginalStartSessionActivationTerminalReadGrpcMtlsTest { + @TempDir Path temporaryDirectory; + + @Test + void sameNamespaceAccountCertificateReturnsExactCanonicalTerminalAndCorrelation() + throws Exception { + var fixture = WorldOriginalStartSessionActivationTransportTestSupport.fixture(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var input = + new WorldOriginalStartSessionActivationTerminalReadInput( + java.util.UUID.fromString("a0a0a0a0-a0a0-40a0-80a0-a0a0a0a0a0a0"), + fixture.protection()); + var owner = mock(WorldCanonicalInstanceActivationService.class); + when(owner.readTerminalEvidence(any())).thenReturn(Optional.of(fixture.terminal())); + var service = new WorldOriginalStartSessionActivationTerminalReadGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + var sentResponse = new AtomicReference(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, false, sentResponse::set); + GrpcWorldOriginalStartSessionActivationTerminalReadClient client = + WorldOriginalStartSessionActivationTransportTestSupport.terminalReadClient( + pki, temporaryDirectory, server.port(), pki.accountClient())) { + client.init(); + + var actual = client.read(input); + + assertThat(handlerCalls).hasValue(1); + assertThat(actual.canonicalBytes()).containsExactly(fixture.terminal().canonicalBytes()); + assertThat(actual.accountProtectionEvidence().canonicalBytes()) + .containsExactly(fixture.protection().canonicalBytes()); + assertThat(actual.activationResult().canonicalBytes()) + .containsExactly(fixture.terminal().activationResult().canonicalBytes()); + assertThat(actual.activationRequestId()).isEqualTo(fixture.terminal().activationRequestId()); + assertThat(actual.outcome()) + .isEqualTo( + net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation.Outcome + .COMMITTED); + + assertThat(sentResponse.get()) + .isInstanceOf(ReadOriginalStartSessionActivationTerminalEvidenceResponse.class); + var response = + (ReadOriginalStartSessionActivationTerminalEvidenceResponse) sentResponse.get(); + assertThat(response.getReadRequestIdList()).containsExactly(input.readRequestId().toString()); + assertThat(response.getTerminalEvidenceList()) + .containsExactly(ByteString.copyFrom(fixture.terminal().canonicalBytes())); + + var captured = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.common.account.startsession + .AccountStartSessionActivationProtectionEvidence.class); + verify(owner).readTerminalEvidence(captured.capture()); + assertThat(captured.getValue().canonicalBytes()) + .containsExactly(fixture.protection().canonicalBytes()); + } + } + + @Test + void trustedWrongServiceAndWrongNamespaceCertificatesAreDeniedBeforeOwner() throws Exception { + var fixture = WorldOriginalStartSessionActivationTransportTestSupport.fixture(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var input = + new WorldOriginalStartSessionActivationTerminalReadInput( + java.util.UUID.fromString("a1a1a1a1-a1a1-41a1-81a1-a1a1a1a1a1a1"), + fixture.protection()); + var owner = mock(WorldCanonicalInstanceActivationService.class); + var service = new WorldOriginalStartSessionActivationTerminalReadGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, false, null)) { + for (var identity : + java.util.List.of(pki.gameSessionClient(), pki.otherNamespaceAccountClient())) { + try (var client = + WorldOriginalStartSessionActivationTransportTestSupport.terminalReadClient( + pki, temporaryDirectory, server.port(), identity)) { + client.init(); + + assertThatThrownBy(() -> client.read(input)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + } + } + + assertThat(handlerCalls).hasValue(2); + verifyNoInteractions(owner); + } + + @Test + void missingClientCertificateIsRejectedByTlsBeforeHandlerOrOwner() throws Exception { + var fixture = WorldOriginalStartSessionActivationTransportTestSupport.fixture(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var input = + new WorldOriginalStartSessionActivationTerminalReadInput( + java.util.UUID.fromString("a2a2a2a2-a2a2-42a2-82a2-a2a2a2a2a2a2"), + fixture.protection()); + var owner = mock(WorldCanonicalInstanceActivationService.class); + var service = new WorldOriginalStartSessionActivationTerminalReadGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, false, null); + var unauthenticatedClient = + WorldOriginalStartSessionActivationTransportTestSupport.clientWithoutIdentity( + pki, server.port())) { + var request = + WorldOriginalStartSessionActivationTerminalReadGrpcCodec.toRequest(input, "test"); + + assertThatThrownBy( + () -> + WorldOriginalStartSessionActivationTerminalReadServiceGrpc.newBlockingStub( + unauthenticatedClient.channel()) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .readOriginalStartSessionActivationTerminalEvidence(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "missing client certificate must fail during TLS negotiation: %s", + failure) + .isTrue()); + } + + assertThat(handlerCalls).hasValue(0); + verifyNoInteractions(owner); + } + + @Test + void authenticatedEndUserContextIsDeniedBeforeOwner() throws Exception { + var fixture = WorldOriginalStartSessionActivationTransportTestSupport.fixture(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var input = + new WorldOriginalStartSessionActivationTerminalReadInput( + java.util.UUID.fromString("a3a3a3a3-a3a3-43a3-83a3-a3a3a3a3a3a3"), + fixture.protection()); + var owner = mock(WorldCanonicalInstanceActivationService.class); + var service = new WorldOriginalStartSessionActivationTerminalReadGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, true, null); + GrpcWorldOriginalStartSessionActivationTerminalReadClient client = + WorldOriginalStartSessionActivationTransportTestSupport.terminalReadClient( + pki, temporaryDirectory, server.port(), pki.accountClient())) { + client.init(); + + assertThatThrownBy(() -> client.read(input)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + + assertThat(handlerCalls).hasValue(1); + verifyNoInteractions(owner); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java new file mode 100644 index 0000000000..8f571275a3 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java @@ -0,0 +1,835 @@ +package unit.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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; +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 java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionAcquisitionInput; +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.world.GrpcWorldOriginalStartSessionProtectedActivationClient; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionProtectedActivationGrpcCodec; +import net.firedevops.firemud.test.TlsTestSupport; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationService; +import net.firedevops.firemud.worldmanagement.v1.ActivateOriginalStartSessionProtectedResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldOriginalStartSessionProtectedActivationServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; + +/** Loopback mTLS transport proof only; the World owner is mocked and remains unregistered. */ +class WorldOriginalStartSessionProtectedActivationGrpcMtlsTest { + @TempDir Path temporaryDirectory; + + @Test + void sameNamespaceGameSessionCertificateReturnsExactCanonicalTerminal() throws Exception { + var fixture = WorldOriginalStartSessionActivationTransportTestSupport.fixture(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var owner = mock(WorldOriginalStartSessionProtectedActivationService.class); + when(owner.activate(any())).thenReturn(fixture.terminal()); + var service = new WorldOriginalStartSessionProtectedActivationGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + var sentResponse = new AtomicReference(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, false, sentResponse::set); + var client = + WorldOriginalStartSessionActivationTransportTestSupport.protectedClient( + pki, temporaryDirectory, server.port(), pki.gameSessionClient())) { + client.init(); + + WorldOriginalStartSessionActivationTerminalEvidence actual = client.activate(fixture.input()); + + assertThat(handlerCalls).hasValue(1); + assertThat(actual.canonicalBytes()).containsExactly(fixture.terminal().canonicalBytes()); + assertThat(actual.accountProtectionEvidence().canonicalBytes()) + .containsExactly(fixture.protection().canonicalBytes()); + assertThat(actual.activationResult().canonicalBytes()) + .containsExactly(fixture.terminal().activationResult().canonicalBytes()); + assertThat(actual.activationRequestId()) + .isEqualTo(fixture.input().worldActivationRequest().activationRequestId()); + assertThat(actual.outcome()) + .isEqualTo( + net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation.Outcome + .COMMITTED); + + assertThat(sentResponse.get()) + .isInstanceOf(ActivateOriginalStartSessionProtectedResponse.class); + var response = (ActivateOriginalStartSessionProtectedResponse) sentResponse.get(); + assertThat(response.getSchemaVersionList()).containsExactly(1); + assertThat(response.getTerminalEvidenceList()) + .containsExactly(ByteString.copyFrom(fixture.terminal().canonicalBytes())); + + ArgumentCaptor captured = + ArgumentCaptor.forClass(AccountStartSessionActivationProtectionAcquisitionInput.class); + verify(owner).activate(captured.capture()); + assertThat(captured.getValue().originalPostAuthorizationTuple()) + .containsExactly(fixture.input().originalPostAuthorizationTuple()); + assertThat(captured.getValue().gameSessionOwnerMutationId()) + .isEqualTo(fixture.input().gameSessionOwnerMutationId()); + assertThat(captured.getValue().gameSessionOwnerAttemptId()) + .isEqualTo(fixture.input().gameSessionOwnerAttemptId()); + assertThat(captured.getValue().gameSessionOwnerFence()) + .isEqualTo(fixture.input().gameSessionOwnerFence()); + assertThat(captured.getValue().worldActivationRequest().canonicalRequestBytes()) + .containsExactly(fixture.input().worldActivationRequest().canonicalRequestBytes()); + assertThat(captured.getValue().worldActivationRequest().preparingEvidenceBytes()) + .containsExactly(fixture.input().worldActivationRequest().preparingEvidenceBytes()); + } + } + + @Test + void trustedWrongServiceAndWrongNamespaceCertificatesAreDeniedBeforeOwner() throws Exception { + var fixture = WorldOriginalStartSessionActivationTransportTestSupport.fixture(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var owner = mock(WorldOriginalStartSessionProtectedActivationService.class); + var service = new WorldOriginalStartSessionProtectedActivationGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, false, null)) { + for (var identity : + java.util.List.of(pki.accountClient(), pki.otherNamespaceGameSessionClient())) { + try (var client = + WorldOriginalStartSessionActivationTransportTestSupport.protectedClient( + pki, temporaryDirectory, server.port(), identity)) { + client.init(); + + assertThatThrownBy(() -> client.activate(fixture.input())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + } + } + + assertThat(handlerCalls).hasValue(2); + verifyNoInteractions(owner); + } + + @Test + void missingClientCertificateIsRejectedByTlsBeforeHandlerOrOwner() throws Exception { + var fixture = WorldOriginalStartSessionActivationTransportTestSupport.fixture(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var owner = mock(WorldOriginalStartSessionProtectedActivationService.class); + var service = new WorldOriginalStartSessionProtectedActivationGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, false, null); + var unauthenticatedClient = + WorldOriginalStartSessionActivationTransportTestSupport.clientWithoutIdentity( + pki, server.port())) { + var request = + WorldOriginalStartSessionProtectedActivationGrpcCodec.toRequest(fixture.input(), "test"); + + assertThatThrownBy( + () -> + WorldOriginalStartSessionProtectedActivationServiceGrpc.newBlockingStub( + unauthenticatedClient.channel()) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .activateOriginalStartSessionProtected(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "missing client certificate must fail during TLS negotiation: %s", + failure) + .isTrue()); + } + + assertThat(handlerCalls).hasValue(0); + verifyNoInteractions(owner); + } + + @Test + void authenticatedEndUserContextIsDeniedBeforeOwner() throws Exception { + var fixture = WorldOriginalStartSessionActivationTransportTestSupport.fixture(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var owner = mock(WorldOriginalStartSessionProtectedActivationService.class); + var service = new WorldOriginalStartSessionProtectedActivationGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, true, null); + var client = + WorldOriginalStartSessionActivationTransportTestSupport.protectedClient( + pki, temporaryDirectory, server.port(), pki.gameSessionClient())) { + client.init(); + + assertThatThrownBy(() -> client.activate(fixture.input())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + + assertThat(handlerCalls).hasValue(1); + verifyNoInteractions(owner); + } +} + +/** Shared only by the two assigned World activation transport tests. */ +final class WorldOriginalStartSessionActivationTransportTestSupport { + static final String NAMESPACE = "test"; + private static final java.util.concurrent.atomic.AtomicLong CERTIFICATE_SERIAL = + new java.util.concurrent.atomic.AtomicLong(1L); + private static final tools.jackson.databind.json.JsonMapper JSON = + tools.jackson.databind.json.JsonMapper.builder().build(); + + private WorldOriginalStartSessionActivationTransportTestSupport() {} + + /** + * Canonical synthetic wire fixture only; it establishes no real Account authority or owner state. + */ + static Fixture fixture() throws Exception { + var existing = + WorldCanonicalPlayerLocationGrpcServiceTest.fixture( + NAMESPACE, "c0c0c0c0-c0c0-40c0-80c0-c0c0c0c0c0c0"); + var active = existing.lifecycleEvidence(); + var lifecycleRequest = active.request(); + var binding = active.launchBinding(); + var descriptor = binding.descriptor(); + var release = binding.releaseAttestation(); + var preparing = + new net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence( + lifecycleRequest, + binding, + active.startLocation(), + active.runtimeRoomInstanceId(), + "PREPARING", + active.lifecycleEpoch(), + active.rowVersion(), + active.captureId(), + active.graphSha256(), + active.preparationInputDigest(), + active.operationalRegionAssignments()); + var activation = + new net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation.Request( + java.util.UUID.fromString("d0d0d0d0-d0d0-40d0-80d0-d0d0d0d0d0d0"), preparing); + var tuple = originalTuple(lifecycleRequest, descriptor.gameTemplateId()); + var launchRequest = + new net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + java.util.UUID.fromString("e0e0e0e0-e0e0-40e0-80e0-e0e0e0e0e0e0"), + lifecycleRequest.targetNamespace(), + lifecycleRequest.canonicalTenantId(), + lifecycleRequest.worldSlug(), + lifecycleRequest.canonicalGameInstanceId(), + lifecycleRequest.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var launchResult = + new net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + launchRequest, + lifecycleRequest.playableStateNamespaceId(), + net.firedevops.firemud.common.publication.RealmEntryPolicy.StateScope.SHARED, + true, + java.util.UUID.fromString("f0f0f0f0-f0f0-40f0-80f0-f0f0f0f0f0f0"), + 17L, + net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING, + 7L, + binding); + var launchReadRequest = + new net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence + .Request(launchRequest, tuple.canonicalBytes()); + var launchRead = + new net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence.Result( + launchReadRequest, launchResult, tuple.canonicalBytes()); + var input = + new AccountStartSessionActivationProtectionAcquisitionInput( + tuple.canonicalBytes(), + java.util.UUID.fromString("11111111-1111-4111-8111-111111111111"), + java.util.UUID.fromString("22222222-2222-4222-8222-222222222222"), + 21L, + activation); + var request = + net.firedevops.firemud.common.account.startsession + .AccountStartSessionActivationProtectionRequest.create( + tuple.canonicalBytes(), + net.firedevops.firemud.common.account.startsession + .StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple), + input.gameSessionOwnerMutationId(), + input.gameSessionOwnerAttemptId(), + input.gameSessionOwnerFence(), + java.time.Instant.parse("2099-01-01T00:05:00Z"), + java.util.UUID.fromString("33333333-3333-4333-8333-333333333333"), + 22L, + launchRead, + activation); + byte[] capture = captureReference(tuple); + var protection = + net.firedevops.firemud.common.account.startsession + .AccountStartSessionActivationProtectionEvidence.create( + request, + java.util.UUID.fromString("44444444-4444-4444-8444-444444444444"), + 23L, + java.time.Instant.parse("2099-01-01T00:01:12.123000Z"), + capture, + sha256(capture), + java.util.List.of( + new net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding + .SourceEvidence( + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding + .SourceKind.ACCOUNT, + lifecycleRequest.canonicalTenantId().toString(), + "2", + "17", + null, + null, + "synthetic transport source snapshot" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)))); + var activeResult = + new net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence( + lifecycleRequest, + binding, + active.startLocation(), + active.runtimeRoomInstanceId(), + "ACTIVE", + preparing.lifecycleEpoch() + 1L, + preparing.rowVersion() + 1L, + preparing.captureId(), + preparing.graphSha256(), + preparing.preparationInputDigest(), + preparing.operationalRegionAssignments()); + var activationResult = + new net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation.Result( + activation, + net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation.Outcome.COMMITTED, + null, + activeResult); + var terminal = + WorldOriginalStartSessionActivationTerminalEvidence.create( + protection, activationResult, 29L); + return new Fixture(input, protection, terminal); + } + + private static net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple + originalTuple( + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.Request world, + long gameTemplateId) + throws Exception { + var action = + new net.firedevops.firemud.common.operator.StartSessionOperatorAction( + net.firedevops.firemud.common.operator.StartSessionOperatorAction + .ACTION_FAMILY_SCHEMA_ID, + net.firedevops.firemud.common.operator.StartSessionOperatorAction + .ACTION_FAMILY_SCHEMA_VERSION, + new net.firedevops.firemud.common.operator.StartSessionOperatorAction.Scope( + world.canonicalTenantId(), world.targetNamespace()), + new net.firedevops.firemud.common.operator.StartSessionOperatorAction.Target( + gameTemplateId, java.util.UUID.fromString("55555555-5555-4555-8555-555555555555")), + net.firedevops.firemud.common.operator.StartSessionOperatorAction.ExpectedVersion + .ABSENT, + new net.firedevops.firemud.common.operator.StartSessionOperatorAction.Mutation( + net.firedevops.firemud.common.operator.StartSessionOperatorAction.ClientIp + .absent()), + "World activation transport fixture with mocked owners"); + var preTuple = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .createHuman( + world.controlPlaneRequestId(), + java.util.UUID.fromString("66666666-6666-4666-8666-666666666666"), + action); + return net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple + .createHuman( + preTuple, + "spiffe://firemud/ns/" + world.targetNamespace() + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "5".repeat(64), + java.util.UUID.fromString("77777777-7777-4777-8777-777777777777"), + 19L, + authorityBundle(preTuple), + new net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle + .BundleReference( + net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle + .BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple tuple) + throws Exception { + String tenant = tuple.action().scope().tenantId().toString(); + var projection = + java.util.Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2099-01-01T00:00:00Z", + "expiresAt", "2099-01-01T00:05:00Z"); + var operation = + java.util.Map.of( + "issuanceOperationId", "88888888-8888-4888-8888-888888888888", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + java.util.Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + var authority = + java.util.Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 2L, + "tenantAuthorityGeneration", + java.util.Map.of(tenant, 3L), + "membershipAuthorityGeneration", + java.util.Map.of(tenant, 4L), + "privateRealmGrantVersions", + java.util.List.of()); + var issuance = + java.util.Map.of( + "evidenceType", + net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle + .HUMAN_EVIDENCE_TYPE, + "actorAccountId", + "66666666-6666-4666-8666-666666666666", + "controlUiTokenJti", + "99999999-9999-4999-8999-999999999999", + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + var scope = + java.util.Map.of( + "scope", + java.util.Map.of( + "tenantId", tenant, "targetNamespace", tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + "66666666-6666-4666-8666-666666666666", + "applicableTenantId", + tenant); + return canonical( + java.util.Map.of( + "bundleVersion", + net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle + .BUNDLE_VERSION, + "authorityScope", + scope, + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + operation, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + java.util.Map.of(tenant, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + issuance)); + } + + private static byte[] captureReference( + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple tuple) + throws Exception { + return canonical( + java.util.Map.of( + "schema", + "account-start-session-authority-capture/v1", + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "capturedAt", + "2099-01-01T00:01:12.123Z", + "bundleReference", + java.util.Map.of( + "bundleVersion", + tuple.bundleReference().bundleVersion(), + "sourceVersion", + tuple.bundleReference().sourceVersion(), + "sourceFence", + tuple.bundleReference().sourceFence(), + "linearization", + tuple.bundleReference().linearization()), + "snapshotSha256", + "b".repeat(64))); + } + + private static byte[] canonical(Object value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] value) throws Exception { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } + + static TransportServer startServer( + TestPki pki, + io.grpc.BindableService service, + AtomicInteger handlerCalls, + boolean injectEndUserContext, + java.util.function.Consumer responseCapture) + throws Exception { + java.util.List interceptors = new java.util.ArrayList<>(); + interceptors.add( + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + handlerCalls.incrementAndGet(); + return next.startCall(call, headers); + } + }); + interceptors.add(new GrpcPeerIdentityInterceptor()); + if (responseCapture != null) { + interceptors.add( + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + return next.startCall( + new io.grpc.ForwardingServerCall.SimpleForwardingServerCall(call) { + @Override + public void sendMessage(RespT message) { + responseCapture.accept(message); + super.sendMessage(message); + } + }, + headers); + } + }); + } + if (injectEndUserContext) { + interceptors.add( + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + var delegate = next.startCall(call, headers); + return new io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener<>( + delegate) { + @Override + public void onHalfClose() { + net.firedevops.firemud.common.security.SessionContext.setContext( + "authenticated-user", java.util.List.of(), java.util.Map.of()); + try { + super.onHalfClose(); + } finally { + net.firedevops.firemud.common.security.SessionContext.clear(); + } + } + }; + } + }); + } + var 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( + io.grpc.ServerInterceptors.intercept( + service, interceptors.toArray(io.grpc.ServerInterceptor[]::new))) + .build() + .start(); + return new TransportServer(server, handlerCalls); + } + + static GrpcWorldOriginalStartSessionProtectedActivationClient protectedClient( + TestPki pki, Path directory, int port, TestIdentity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + port); + return new GrpcWorldOriginalStartSessionProtectedActivationClient( + endpoints, pki.clientProperties(directory, identity), new GrpcChannelFactory(), NAMESPACE); + } + + static net.firedevops.firemud.common.world + .GrpcWorldOriginalStartSessionActivationTerminalReadClient + terminalReadClient(TestPki pki, Path directory, int port, TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + port); + return new net.firedevops.firemud.common.world + .GrpcWorldOriginalStartSessionActivationTerminalReadClient( + endpoints, pki.clientProperties(directory, identity), new GrpcChannelFactory(), NAMESPACE); + } + + static UnauthenticatedClient clientWithoutIdentity(TestPki pki, int port) throws Exception { + return new UnauthenticatedClient( + NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", port)) + .sslContext(GrpcSslContexts.forClient().trustManager(pki.caCertificate()).build()) + .build()); + } + + record Fixture( + AccountStartSessionActivationProtectionAcquisitionInput input, + net.firedevops.firemud.common.account.startsession + .AccountStartSessionActivationProtectionEvidence + protection, + WorldOriginalStartSessionActivationTerminalEvidence terminal) {} + + record TransportServer(io.grpc.Server server, AtomicInteger handlerCalls) + implements AutoCloseable { + int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback World gRPC server did not terminate"); + } + } + } + + record UnauthenticatedClient(ManagedChannel channel) implements AutoCloseable { + @Override + public void close() throws InterruptedException { + channel.shutdownNow(); + if (!channel.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Unauthenticated loopback gRPC client did not terminate"); + } + } + } + + record TestIdentity( + String alias, + java.security.PrivateKey privateKey, + java.security.cert.X509Certificate certificate) {} + + record TestPki( + java.security.cert.X509Certificate caCertificate, + Path caCertificatePem, + TestIdentity worldServer, + TestIdentity gameSessionClient, + TestIdentity accountClient, + TestIdentity otherNamespaceGameSessionClient, + TestIdentity otherNamespaceAccountClient) { + static TestPki create(Path directory) throws Exception { + if (java.security.Security.getProvider( + org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME) + == null) { + java.security.Security.addProvider( + new org.bouncycastle.jce.provider.BouncyCastleProvider()); + } + var caKeys = keyPair(); + var caName = + new org.bouncycastle.asn1.x500.X500Name("CN=World Activation Test CA, O=FireMUD Test"); + var caCertificate = + issueCertificate( + caName, caKeys.getPublic(), caName, caKeys.getPrivate(), true, null, false); + Path caPem = + writePem( + directory.resolve("world-activation-test-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + return new TestPki( + caCertificate, + caPem, + issueIdentity( + caName, + caKeys.getPrivate(), + "world-server", + "spiffe://firemud/ns/test/sa/world-management-service", + true), + issueIdentity( + caName, + caKeys.getPrivate(), + "game-session", + "spiffe://firemud/ns/test/sa/game-session-service", + false), + issueIdentity( + caName, + caKeys.getPrivate(), + "account", + "spiffe://firemud/ns/test/sa/account-service", + false), + issueIdentity( + caName, + caKeys.getPrivate(), + "other-game-session", + "spiffe://firemud/ns/other/sa/game-session-service", + false), + issueIdentity( + caName, + caKeys.getPrivate(), + "other-account", + "spiffe://firemud/ns/other/sa/account-service", + false)); + } + + CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + writePem( + directory.resolve(identity.alias() + ".crt"), + "CERTIFICATE", + identity.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + writePem( + directory.resolve(identity.alias() + ".key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()) + .toString()); + tls.setCaCert(caCertificatePem.toString()); + tls.setPlaintext(false); + return tls; + } + + private static TestIdentity issueIdentity( + org.bouncycastle.asn1.x500.X500Name caName, + java.security.PrivateKey caKey, + String alias, + String uri, + boolean server) + throws Exception { + var keys = keyPair(); + return new TestIdentity( + alias, + keys.getPrivate(), + issueCertificate( + new org.bouncycastle.asn1.x500.X500Name("CN=" + alias), + keys.getPublic(), + caName, + caKey, + false, + uri, + server)); + } + + private static java.security.KeyPair keyPair() throws Exception { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private static java.security.cert.X509Certificate issueCertificate( + org.bouncycastle.asn1.x500.X500Name subject, + java.security.PublicKey publicKey, + org.bouncycastle.asn1.x500.X500Name issuer, + java.security.PrivateKey issuerKey, + boolean ca, + String workloadUri, + boolean server) + throws Exception { + var builder = + new org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder( + issuer, + java.math.BigInteger.valueOf(CERTIFICATE_SERIAL.getAndIncrement()), + java.util.Date.from(java.time.Instant.now().minusSeconds(60)), + java.util.Date.from(java.time.Instant.now().plusSeconds(86_400)), + subject, + publicKey); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.basicConstraints, + true, + new org.bouncycastle.asn1.x509.BasicConstraints(ca)); + if (ca) { + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage( + org.bouncycastle.asn1.x509.KeyUsage.keyCertSign + | org.bouncycastle.asn1.x509.KeyUsage.cRLSign)); + } else { + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.keyUsage, + true, + new org.bouncycastle.asn1.x509.KeyUsage( + org.bouncycastle.asn1.x509.KeyUsage.digitalSignature + | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment)); + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.extendedKeyUsage, + false, + new org.bouncycastle.asn1.x509.ExtendedKeyUsage( + server + ? org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_serverAuth + : org.bouncycastle.asn1.x509.KeyPurposeId.id_kp_clientAuth)); + if (workloadUri != null) { + builder.addExtension( + org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, + false, + new org.bouncycastle.asn1.x509.GeneralNames( + new org.bouncycastle.asn1.x509.GeneralName[] { + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.uniformResourceIdentifier, + workloadUri), + new org.bouncycastle.asn1.x509.GeneralName( + org.bouncycastle.asn1.x509.GeneralName.iPAddress, "127.0.0.1") + })); + } + } + var signer = + new org.bouncycastle.operator.jcajce.JcaContentSignerBuilder("SHA256withRSA") + .setProvider(org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME) + .build(issuerKey); + return new org.bouncycastle.cert.jcajce.JcaX509CertificateConverter() + .setProvider(org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME) + .getCertificate(builder.build(signer)); + } + + private static Path writePem(Path path, String label, byte[] bytes) throws Exception { + String body = java.util.Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return java.nio.file.Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + java.nio.charset.StandardCharsets.US_ASCII); + } + } +} From ab1e52117f299f321606a98a5aa3602dc42e4b3f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:04:08 +1300 Subject: [PATCH 110/129] test(account): use native original authorization transport in release proof --- ...ame-authoring-publishing-and-activation.md | 4 +- ...StartSessionAuthorizationProofFixture.java | 161 ++++++++++++++---- ...licationExportPostgresIntegrationTest.java | 157 +++++++++++++++-- 3 files changed, 268 insertions(+), 54 deletions(-) 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 55ff28bc48..090096c7ac 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The genuine-release definition now issues the original StartSession authorization through the existing Logging & Admin file-backed mTLS client and redeems it through an exact Account-pinned Game Session channel. Both scenarios preserve the actual Account owner, Logging reservation, original Game Session attempt, exact authority bundle and independent Account readback; their issue/redemption peer contexts are no longer stipulated. The corrected Account/Game Design check passes in 1 minute 21 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. The unchanged unit tasks reuse 1,970 passing results; twelve non-container Account integration cases execute, while 289 Account and all 153 Game Design container cases skip, including both genuine-release scenarios. This advances the proof definition, not executed PostgreSQL/mTLS composition. Game Session's durable first-selection/descriptor-pin producer and World preparation historical recovery/settlement remain open; runtime registration and activation remain denied. + World's unregistered protected-activation and activation-terminal-read receivers now have eight executed loopback-mTLS cases using their real handlers and file-backed Common clients: exact same-namespace Game Session and Account callers respectively retain complete canonical terminal/protection bytes and request correlation; trusted wrong-service or wrong-namespace certificates and authenticated end-user context reach no owner; missing client certificates reach neither handler nor owner. The World owners are mocked and the evidence is synthetic, so these cases prove transport enforcement, not genuine source authorization, PostgreSQL activation, fenced abort or Account settlement. The corrected full World check passes in 1 minute 4 seconds with 678 unit cases executed and zero skips, failures or errors, including all eight new cases, formatting, Checkstyle, SpotBugs and coverage. Its unchanged integration task reuses prior results: one non-container case executed and 229 container-dependent cases skipped. Initial test-local channel-cleanup and digest-fixture failures were corrected without changing production guards or assertions. All four complete handoffs remain open; runtime registration and activation remain denied. Account's distinct activation-protection acquisition and settlement receivers now have eight executed loopback-mTLS cases: exact same-namespace World callers preserve full canonical receipt/terminal bytes and lookup correlation, trusted wrong-service or wrong-namespace callers reach no owner, missing certificates reach neither handler nor owner, and authenticated end-user context reaches no owner. These tests use file-backed test certificates and mocked Account owners; they prove transport enforcement, not current Account authorization, source exclusion, PostgreSQL settlement or World activation. The corrected full Account check passes in 2 minutes 41 seconds, including formatting, Checkstyle, SpotBugs and coverage, with 1,385 unit cases executed and zero skips, failures or errors. Its unchanged integration task reuses the preceding results: twelve non-container cases executed and 289 container cases skipped. The initial five failures were invalid synthetic selected-release fixtures; the correction supplies the complete closed selector and APPLIED-v2 graph evidence without changing production guards or weakening assertions. Runtime registration and genuine producer/consumer proof remain denied. Gameplay owns the separate explicit current-player authority producer needed for nonempty `PLAYER_CREATED` allocation; launch creator authority cannot substitute. @@ -24,7 +26,7 @@ The source-local composition replaces the stipulated Game Session launch associa The unregistered receiving construction retains the complete immutable published realm-policy set in the canonical Game Design-owned carrier, checking every full policy digest, original source capture and terminal publication binding. Its distinct Game Design read requires the existing Account-confirmed exact-replay association before opening the owner source/policy snapshot. Game Session's bounded fresh `NEW_GAME_ROW`, visible public-production `SHARED` producer atomically retains that source, complete policy evidence, shared namespace and catalog, then independently reads back its original identities and actual catalog revision. Additive V42 does not backfill historical catalog rows or restrict the catalog's general scope vocabulary. The genuine-release definition composes the native Game Design creation read into Game Session's fresh association and its Account-confirmed source/policy read into the actual catalog repository and independent readback. That definition has not executed physically; complete producer/consumer and PostgreSQL proof remain required. The catalog-only producer grants neither launch nor admission authority; the separate STARTING owner construction above remains unregistered and physically unproved. -The genuine release definition now uses an actual isolated Logging reservation owner and native file-backed mTLS current-claim read instead of fixed Logging claim evidence. Account issuer/redeemer contexts remain explicit fixture stipulations; the current claim is point-in-time evidence, not continuous protection of a later owner commit. The newly composed Logging database and native receiver path has not executed locally. Physical launch-association composition, uninterrupted commit protection, final owner settlement, lifecycle readiness and activation remain open; no broader handoff is complete from these definitions. +The genuine release definition uses an actual isolated Logging reservation owner and native file-backed mTLS current-claim read instead of fixed Logging claim evidence, with native Account issue/redemption as recorded above. The current claim is point-in-time evidence, not continuous protection of a later owner commit. The newly composed Logging database and native receiver path has not executed locally. Physical launch-association composition, uninterrupted commit protection, final owner settlement, lifecycle readiness and activation remain open; no broader handoff is complete from these definitions. The corrected Common Platform/Game Design/Game Session gate passes in 1 minute 46 seconds across 216 tasks, including complete affected checks, SQL metadata generation, integration compilation, formatting, static analysis, coverage, links and 548 Markdown files. Passing current results total 3,206 executed unit cases and 28 executed non-container integration/cross-service cases; unchanged tasks reuse the preceding corrected candidate's results. There are 376 skips: 17 Game Session units and 359 container-dependent integration/cross-service cases. All six new catalog PostgreSQL cases and the genuine-release composition skip locally. A non-container fixture case validates the complete canonical carrier framing; it is explicitly synthetic and does not replace physical owner composition. The narrow Game Design fixture artifact contains only its operation record and two fixture families, without repository classes, application configuration or migrations. No Docker, physical PostgreSQL, certificate custody or complete handoff execution is claimed. diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java index ffe632502b..4c2d69f715 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -58,8 +58,8 @@ * Account owners and retained PostgreSQL rows. A test may supply a Game Session owner-attempt * lifecycle so it can reserve the exact issued tuple before redemption and attach the redeemed * projection after redemption, without introducing Game Session classes into this fixture artifact. - * The peer scopes around issue and redemption are in-process test stipulations, not authenticated - * producer or mTLS proof. + * Existing overloads retain their in-process stipulated peer scopes; composed proofs may supply an + * authenticated issue/redemption transport while preserving the same Account owner flow. */ public final class AccountOriginalStartSessionAuthorizationProofFixture { private static final Duration REFERENCE_LIFETIME = Duration.ofMinutes(5); @@ -179,6 +179,26 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( UUID reservationOwnerId, long reservationClaimFence, OwnerAttemptLifecycle ownerAttemptLifecycle) { + return issueAndRedeemOriginal( + controlPlaneRequestId, + action, + reservationOwnerId, + reservationClaimFence, + ownerAttemptLifecycle, + null); + } + + /** + * Performs the same Account-owned issue/redemption flow through a caller-supplied authenticated + * transport. The owner-attempt reservation remains between issue and redemption. + */ + public synchronized OriginalStartSession issueAndRedeemOriginal( + String controlPlaneRequestId, + StartSessionOperatorAction action, + UUID reservationOwnerId, + long reservationClaimFence, + OwnerAttemptLifecycle ownerAttemptLifecycle, + OriginalStartSessionAuthorizationTransport transport) { Objects.requireNonNull(action, "canonical StartSession action is required"); Objects.requireNonNull(ownerAttemptLifecycle, "Game Session owner attempt lifecycle required"); requireActionBinding(action); @@ -193,25 +213,39 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( "This proof fixture already attempted the original StartSession request"); } byte[] preTupleBytes = preTuple.canonicalJson().getBytes(StandardCharsets.UTF_8); - var authorization = - withPeer( - loggingPeerUri, - () -> - authorizationService.issue( - new AccountStartSessionOperatorAuthorizationService.IssueRequest( - creator.compact(), - preTupleBytes, - reservationOwnerId, - reservationClaimFence, - reservationOwnerId, - reservationClaimFence))); - - var sharedReference = - new StartSessionAuthorityEvidenceBundle.BundleReference( - authorization.bundleReference().bundleVersion(), - authorization.bundleReference().sourceVersion(), - authorization.bundleReference().sourceFence(), - authorization.bundleReference().linearization()); + IssuedAuthorization authorization; + if (transport == null) { + var directAuthorization = + withPeer( + loggingPeerUri, + () -> + authorizationService.issue( + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + creator.compact(), + preTupleBytes, + reservationOwnerId, + reservationClaimFence, + reservationOwnerId, + reservationClaimFence))); + authorization = + new IssuedAuthorization( + directAuthorization.operatorAuthorizationReference(), + directAuthorization.authorizationReferenceFingerprint(), + directAuthorization.authorityEvidenceBundle(), + new StartSessionAuthorityEvidenceBundle.BundleReference( + directAuthorization.bundleReference().bundleVersion(), + directAuthorization.bundleReference().sourceVersion(), + directAuthorization.bundleReference().sourceFence(), + directAuthorization.bundleReference().linearization())); + } else { + authorization = + Objects.requireNonNull( + transport.issue( + preTuple, creator.compact(), reservationOwnerId, reservationClaimFence), + "Authenticated Account issue transport returned no authorization"); + } + + var sharedReference = authorization.bundleReference(); var originalTuple = StartSessionPostAuthorizationExecutionTuple.createHuman( preTuple, @@ -227,20 +261,28 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( ownerAttemptLifecycle.reserve(originalTuple), "Game Session owner attempt reservation returned no claim"); - var redemption = - withPeer( - gameSessionPeerUri, - () -> - authorizationService.redeem( - new AccountStartSessionOperatorAuthorizationService.RedeemRequest( - preTupleBytes, - authorization.operatorAuthorizationReference(), - authorization.authorizationReferenceFingerprint(), - reservationOwnerId, - reservationClaimFence, - ownerClaim.ownerAttemptId(), - ownerClaim.ownerFence()))); - assertThat(redemption.replay()).isFalse(); + boolean replay; + if (transport == null) { + var redemption = + withPeer( + gameSessionPeerUri, + () -> + authorizationService.redeem( + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + preTupleBytes, + authorization.operatorAuthorizationReference(), + authorization.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + ownerClaim.ownerAttemptId(), + ownerClaim.ownerFence()))); + replay = redemption.replay(); + } else { + replay = + transport.redeem( + preTupleBytes, authorization, reservationOwnerId, reservationClaimFence, ownerClaim); + } + assertThat(replay).isFalse(); ownerAttemptLifecycle.attachAccountRedemptionProjection(ownerClaim, originalTuple); var retained = @@ -258,7 +300,14 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( .isEqualTo(authorization.authorizationReferenceFingerprint()); assertThat(retained.issuanceOperationId()).isNotNull(); assertThat(retained.issuanceFence()).isPositive(); - assertThat(retained.bundleReference()).isEqualTo(authorization.bundleReference()); + assertThat(retained.bundleReference().bundleVersion()) + .isEqualTo(authorization.bundleReference().bundleVersion()); + assertThat(retained.bundleReference().sourceVersion()) + .isEqualTo(authorization.bundleReference().sourceVersion()); + assertThat(retained.bundleReference().sourceFence()) + .isEqualTo(authorization.bundleReference().sourceFence()); + assertThat(retained.bundleReference().linearization()) + .isEqualTo(authorization.bundleReference().linearization()); assertThat(retained.authorityEvidenceBundle()) .containsExactly(authorization.authorityEvidenceBundle()); assertThat(retained.authorityEvidenceBundle()) @@ -386,6 +435,44 @@ void attachAccountRedemptionProjection( OwnerClaim ownerClaim, StartSessionPostAuthorizationExecutionTuple originalTuple); } + /** Authenticated issue and redemption calls used by a composed transport proof. */ + public interface OriginalStartSessionAuthorizationTransport { + IssuedAuthorization issue( + StartSessionPreAuthorizationReservationTuple tuple, + String controlUiJwt, + UUID reservationOwnerId, + long reservationClaimFence); + + boolean redeem( + byte[] canonicalPreAuthorizationTupleBytes, + IssuedAuthorization authorization, + UUID reservationOwnerId, + long reservationClaimFence, + OwnerClaim ownerClaim); + } + + /** Exact Account issue response fields needed to form the original execution tuple. */ + public record IssuedAuthorization( + String operatorAuthorizationReference, + String authorizationReferenceFingerprint, + byte[] authorityEvidenceBundle, + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference) { + public IssuedAuthorization { + Objects.requireNonNull(operatorAuthorizationReference, "Account reference is required"); + Objects.requireNonNull( + authorizationReferenceFingerprint, "Account reference fingerprint is required"); + authorityEvidenceBundle = + Objects.requireNonNull(authorityEvidenceBundle, "Account authority bundle is required") + .clone(); + Objects.requireNonNull(bundleReference, "Account bundle reference is required"); + } + + @Override + public byte[] authorityEvidenceBundle() { + return authorityEvidenceBundle.clone(); + } + } + /** Non-secret owner identities needed by Account redemption and acquisition. */ public record OwnerClaim(UUID ownerAttemptId, UUID ownerMutationId, long ownerFence) { public OwnerClaim { @@ -399,7 +486,7 @@ private void assertPersistedCapture( StartSessionPreAuthorizationReservationTuple preTuple, UUID reservationOwnerId, long reservationClaimFence, - AccountStartSessionOperatorAuthorizationService.AuthorizationResponse authorization, + IssuedAuthorization authorization, StartSessionPostAuthorizationExecutionTuple originalTuple, AccountStartSessionOperatorAuthorizationRepository.IssuanceRecord retained) { AccountStartSessionAuthorityCapture capture = diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index d58227db02..b4cad08d55 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -46,9 +46,13 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; import net.firedevops.firemud.accountservice.authordraft.AccountDraftCommitOrderReadGrpcService; import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.IssuedAuthorization; +import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OriginalStartSessionAuthorizationTransport; import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerAttemptLifecycle; import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerClaim; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; @@ -303,6 +307,7 @@ import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadGrpcService; import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionLaunchReadGrpcService; import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; +import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimEvidence; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; @@ -422,21 +427,21 @@ * mTLS selected-empty owner readers and exact retained receipts; nonempty owner publication remains * outside this proof. StartSession issuance and redemption use the real Account owner and retained * rows under the genuine Logging PostgreSQL reservation owner and its native file-backed mTLS - * current-claim reader; Account issuer/redeemer peer contexts remain stipulated. The read-only - * projection uses the real Account receiver over Game Design mTLS. MinIO object-store I/O is real. - * The complete launch-binding case wires the actual Game Design handler and World Management mTLS - * client on this fixture's loopback server to the actual owner implementation in an explicitly - * established read-only repeatable-read snapshot; unrelated handler dependencies are isolated. The - * World preparation composition reuses the genuine persisted source, frozen graph, and complete - * released pair through actual World owner services. Its original Account tuple is issued and - * redeemed by the real Account owner after the native Logging current-claim read and under - * stipulated Account issuer/redeemer peer contexts; Game Session reserves that exact tuple in an - * isolated V35 store and attaches the exact redeemed projection. Account's current-attempt - * observation and World participation acquisition use their native same-namespace mTLS clients and - * receivers. Game Session also resolves the actual fresh Game Design tenant receipt over mTLS, - * stores and independently reads its numeric tenant association, then reads the actual - * Account-confirmed source and published policy set over mTLS and stores and independently reads - * its canonical public-realm catalog. Game Session creates and independently reads the exact + * current-claim reader; issue uses the existing Logging/Admin mTLS client and redemption uses a + * Game Session mTLS stub pinned to Account. The read-only projection uses the real Account receiver + * over Game Design mTLS. MinIO object-store I/O is real. The complete launch-binding case wires the + * actual Game Design handler and World Management mTLS client on this fixture's loopback server to + * the actual owner implementation in an explicitly established read-only repeatable-read snapshot; + * unrelated handler dependencies are isolated. The World preparation composition reuses the genuine + * persisted source, frozen graph, and complete released pair through actual World owner services. + * Its original Account tuple is issued and redeemed by the real Account owner after the native + * Logging current-claim read through exact same-namespace Account transports; Game Session reserves + * that exact tuple in an isolated V35 store and attaches the exact redeemed projection. Account's + * current-attempt observation and World participation acquisition use their native same-namespace + * mTLS clients and receivers. Game Session also resolves the actual fresh Game Design tenant + * receipt over mTLS, stores and independently reads its numeric tenant association, then reads the + * actual Account-confirmed source and published policy set over mTLS and stores and independently + * reads its canonical public-realm catalog. Game Session creates and independently reads the exact * STARTING runtime/launch association with its captured catalog revision, and World consumes that * evidence through the native exact-peer Game Session reader. Account participation is * point-in-time evidence, not a continuous cross-service lock. The distinct activation-purpose @@ -638,6 +643,8 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( endpoints.setEntityManagementService(loopback(entityServer)); var channels = new GrpcChannelFactory(); try (var loggingClaimClient = currentClaimGrpcClient(loggingServer.getPort(), pki); + var startSessionAuthorizationTransport = + new NativeAccountStartSessionAuthorizationTransport(endpoints, pki, channels); var account = new AccountControlUiOriginalOrderFixture( ACCOUNT_POSTGRES.getJdbcUrl(), @@ -3145,7 +3152,8 @@ public void attachAccountRedemptionProjection( assertThat(attached.accountRedemptionProjection()) .containsExactly(projection.canonicalBytes()); } - }); + }, + startSessionAuthorizationTransport); assertThat(originalStartSession.originalTuple().preAuthorizationTuple().canonicalJson()) .isEqualTo(loggingTuple.canonicalJson()); assertThat(loggingReadRequests).hasSize(1); @@ -6583,6 +6591,123 @@ private static StartSessionReservationEvidenceClient currentClaimGrpcClient( BlockingGrpcStubCustomizer.noop()); } + /** Native file-backed mTLS transport for the real Account original StartSession owner. */ + private static final class NativeAccountStartSessionAuthorizationTransport + implements OriginalStartSessionAuthorizationTransport, AutoCloseable { + private final StartSessionOperatorAuthorizationClient issuer; + private final ManagedChannel redeemerChannel; + private final StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + redeemer; + + NativeAccountStartSessionAuthorizationTransport( + ServiceEndpointsProperties endpoints, TestPki pki, GrpcChannelFactory channels) + throws IOException { + var issueClient = + new StartSessionOperatorAuthorizationClient( + endpoints, + pki.client("logging-admin-service"), + channels, + BlockingGrpcStubCustomizer.noop()); + ManagedChannel channel = null; + try { + issueClient.initialize(); + channel = + channels.buildChannel( + endpoints.getAccountService(), 6565, pki.client("game-session-service"), false); + } catch (Exception failure) { + try { + issueClient.close(); + } catch (Exception closeFailure) { + failure.addSuppressed(closeFailure); + } + if (channel != null) channel.shutdownNow(); + throw failure; + } + + issuer = issueClient; + redeemerChannel = channel; + String expectedAccountPeer = "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service"; + redeemer = + StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(redeemerChannel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedAccountPeer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedAccountPeer)); + } + + @Override + public IssuedAuthorization issue( + StartSessionPreAuthorizationReservationTuple tuple, + String controlUiJwt, + UUID reservationOwnerId, + long reservationClaimFence) { + var issued = + issuer.issueHuman( + tuple, + controlUiJwt, + reservationOwnerId, + reservationClaimFence, + reservationOwnerId, + reservationClaimFence); + return new IssuedAuthorization( + issued.operatorAuthorizationReference(), + issued.authorizationReferenceFingerprint(), + issued.authorityEvidenceBundle(), + issued.bundleReference()); + } + + @Override + public boolean redeem( + byte[] canonicalPreAuthorizationTupleBytes, + IssuedAuthorization authorization, + UUID reservationOwnerId, + long reservationClaimFence, + OwnerClaim ownerClaim) { + var response = + redeemer + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .redeemOperatorAuthorization( + RedeemOperatorAuthorizationRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes( + ByteString.copyFrom(canonicalPreAuthorizationTupleBytes)) + .setOperatorAuthorizationReference( + authorization.operatorAuthorizationReference()) + .setAuthorizationReferenceFingerprint( + authorization.authorizationReferenceFingerprint()) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setOwnerAttemptId(ownerClaim.ownerAttemptId().toString()) + .setOwnerFence(ownerClaim.ownerFence()) + .build()); + var authority = + StartSessionAuthorityEvidenceBundle.decode(authorization.authorityEvidenceBundle()); + if (!response.getUnknownFields().asMap().isEmpty() + || !authorization + .authorizationReferenceFingerprint() + .equals(response.getAuthorizationReferenceFingerprint()) + || !Arrays.equals( + authorization.authorityEvidenceBundle(), + response.getAuthorityEvidenceBundle().toByteArray()) + || !authority.issuanceOperationId().toString().equals(response.getIssuanceOperationId()) + || !authority.issuanceFence().equals(Long.toString(response.getIssuanceFence()))) { + throw new IllegalStateException( + "Account redemption response differs from the exact issued authority bundle"); + } + return response.getReplay(); + } + + @Override + public void close() throws IOException, InterruptedException { + try { + issuer.close(); + } finally { + redeemerChannel.shutdownNow(); + if (!redeemerChannel.awaitTermination(5, TimeUnit.SECONDS)) { + throw new AssertionError("Account StartSession redemption channel did not terminate"); + } + } + } + } + private static String certificateSha256(Path certificate) throws Exception { try (var input = Files.newInputStream(certificate)) { var parsed = CertificateFactory.getInstance("X.509").generateCertificate(input); From dc5c0fadc26a1a332086a29e9c8fcb7e54c064f1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:05:09 +1300 Subject: [PATCH 111/129] docs(world): own character-create lifecycle protection boundary --- .../world-management-service/api-contracts.md | 8 ++++++++ .../world-management-service/runtime-and-data.md | 1 + .../implementation-tracking/world-runtime-and-movement.md | 1 + 3 files changed, 10 insertions(+) diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 458ec36d78..da9d105046 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -337,6 +337,14 @@ The separate `WorldOriginalStartSessionActivationTerminalReadService.ReadOrigina The closed RFC 8785 `world-original-start-session-activation-terminal-evidence/v1` receipt has exactly `schema`, `activationRequestId`, `accountProtectionId`, `accountProtectionFence`, `worldActivationFence`, `accountProtectionEvidenceBytesBase64`, `activationResultBytesBase64`, and `activationResultSha256`. It retains the full first Account protection and full original World activation request/result, including historical owner-read correlation IDs, rather than projecting either to a digest. World allocates the positive execution fence in its durable operation row; terminal commit and fenced abort serialize against that same row. Only an exact `COMMITTED` result with its resulting `ACTIVE` lifecycle or a positively fenced immutable `ABORTED` result is terminal. The receipt's own integrity checks do not authenticate that row or prove commit; Account must obtain the receipt from authenticated exact World owner readback before settlement. The intermediate World result has a 384 MiB denial bound; the enclosing receipt independently admits at most 768 MiB including the full Account evidence and all nested base64 expansion. Both bounds apply, so satisfying the intermediate bound does not imply that the enclosing receipt fits. These are carrier-specific denial bounds, not increases to any runtime transport limit. Oversize evidence is rejected intact, never truncated. Retained legacy activation results remain historical evidence and cannot be reinterpreted as this protected terminal. +## CHARACTER_CREATE Protection Contract + +World participates in Entity-owned character creation through a distinct World protection purpose tied to the same explicit operation, digest, and exact immutable target carried by Gameplay. Entity remains the only actor creator and owns the creation result. World protection does not allocate an actor, authorize creation policy or input, or grant gameplay admission. The Gameplay carrier is still being defined; this contract intentionally defines no carrier fields, schema, transport, or inferred StartSession bindings. + +This purpose is separate from the canonical initial activation protection and the initial-admission bind hold; neither existing protection identity nor its terminal outcome can substitute for `CHARACTER_CREATE` evidence. + +The protection authority is finite and cannot be renewed or reacquired to restart an unresolved operation. World must serialize protection and its terminalization with the target `world_instance` lifecycle row. Every lifecycle compare-and-set that could invalidate the target, including termination, must fail closed while that operation remains unresolved. World may settle the protection only from an authenticated exact Entity `COMMITTED` result or a positively fenced definitive `ABORTED` result that prevents a later commit for the same operation. Both outcomes must match the retained operation, digest, and complete target. Missing evidence, `PENDING`, absence, timeout, expiry, or an unavailable, mismatched, or contradictory owner read leaves the protection unresolved and the lifecycle fence in place. A read or hold alone grants no creation or admission authority. The World implementation and focused race/restart proof remain open in the [World Runtime and Movement tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md). + ## Instance Termination Contract World Management owns the authoritative lifecycle row and monotonic epoch for `gameInstanceId` rows. The lifecycle state, owner registry, cleanup acknowledgements, and Temporal boundary are owned by [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); this section records the World API consequence. Teardown is cross-service: diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 33f68cfc8c..fa419f31f8 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -126,6 +126,7 @@ When changing Redis usage or adding prefixes here, follow the [Redis Design Chec - `region_instance`, `zone_instance`, `room_instance`, and `room_instance_exit` materialize topology for a running game instance based on the chosen version and any runtime procedural generation. - `instance` is the live legacy temporary-zone-copy table used for instanced gameplay. Its rows are tenant-scoped zone children (`zone_id`, `owner_account_id`, `created_at`, `expires_at`) and are not keyed by the modern `gameInstanceId`; its current `expires_at` job deletes rows directly. This is implementation drift, not the ADR 0123 `world_instance` lifecycle, and `expires_at` does not authorize a transition of the parent game instance. For replacement classification, the family is explicitly `S3` and **excluded from replacement mapping/cutover**: it is not copied into a target instance, and a replacement report must state that exclusion rather than claiming exhaustive mapping for this legacy family. Target cleanup either migrates the temporary content into a complete `world_instance` with its own `gameInstanceId` and fenced `InstanceTermination`, or retains a separate zone-scoped idempotent cleanup contract that cannot terminate the parent. - `world_instance_status`, or equivalent lifecycle state, tracks the ADR 0123 transitions `PREPARING -> ACTIVE`, `PREPARING -> FAILED_PRE_ACTIVATION`, `PREPARING -> TERMINATING`, `FAILED_PRE_ACTIVATION -> TERMINATING`, `ACTIVE -> TERMINATING`, and `TERMINATING -> TERMINATED`. +- A pending World `CHARACTER_CREATE` protection is a separate operation hold, not a lifecycle state. While it spans Entity's commit, incompatible lifecycle compare-and-sets for that target must serialize on the same `world_instance` row and remain fenced until exact terminal evidence resolves the hold. The carrier, storage, and authenticated terminal path are not implemented; see the [World protection contract](./api-contracts.md#character_create-protection-contract) and [World Runtime and Movement tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md). - `FAILED_PRE_ACTIVATION` is terminal for admission by that `gameInstanceId`, not proof that cleanup completed; separate owner-scoped cleanup progress may continue. Recovery is modeled as provisioning a new `gameInstanceId` and rerunning world creation. - `world_instance_lifecycle_lock`, or equivalent fenced token, enforces single-writer lifecycle transitions per `(tenantId, gameInstanceId)`. - V46 `character_location` records bounded initial player placement, backed by an immutable placement-operation receipt. General current-location transitions, `npc_location`, and occupancy persistence remain target-only/absent; live `room_instance` rows describe topology, while the Game Session room binding is not authoritative World location. 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 d5dc4a0b16..ba2847fb5c 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -125,6 +125,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif ## Active Gaps +- World `CHARACTER_CREATE` protection is not implemented. Gameplay has not yet defined its carrier, so World has no distinct operation-bound protection storage, authenticated exact Entity terminal read/settlement path, lifecycle compare-and-set fence for the unresolved cross-owner operation, or focused race/restart proof. Entity remains the actor creator; World holds unresolved protection through Entity commit and resolves it only from exact authenticated `COMMITTED` or positively fenced definitive `ABORTED` evidence. Absence, timeout, expiry, or unavailable evidence cannot release the fence. See the [World protection contract](../../architecture/microservices/world-management-service/api-contracts.md#character_create-protection-contract). - TICK-04 confirms World ownership of topology, location, occupancy, and ambient room state. Authoritative character/session location mutation remains open; DROP/PICKUP require World validation of its own stale-rejecting `TargetingFactSnapshot` location/version token plus Game Session protection of the ordered execution under the actor/executor fence before Entity commits, but the current proto and proof do not cover it. Current Game Session room binding is not that authority. - Broader travel, pathfinding, combat adjacency, richer movement failure semantics, and additional client polish are outside the completed directional-movement baseline. From 1dcb173efe9670557e4db182ae5df10c04d95e79 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:31:09 +1300 Subject: [PATCH 112/129] Retain original launch selection and compose authenticated historical settlement proof --- .../game-session-service/api-contracts.md | 6 + .../game-session-service/runtime-and-data.md | 2 + ...ame-authoring-publishing-and-activation.md | 6 +- ...StartSessionAuthorizationProofFixture.java | 49 ++ ...licationExportPostgresIntegrationTest.java | 432 ++++++++++++++-- ...sionCanonicalInstanceLaunchRepository.java | 78 +++ ...nalStartSessionSelectionPinRepository.java | 461 ++++++++++++++++++ ...StartSessionOperatorAttemptRepository.java | 18 + ...iginalStartSessionSelectionPinService.java | 215 ++++++++ ...rtSessionOwnerEvidenceReadGrpcService.java | 136 ++++++ ...__original_start_session_selection_pin.sql | 135 +++++ ...rCoreRetentionPostgresIntegrationTest.java | 279 ++++++++++- ...alStartSessionSelectionPinServiceTest.java | 140 ++++++ ...ssionOwnerEvidenceReadGrpcServiceTest.java | 106 ++++ 14 files changed, 2023 insertions(+), 40 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionSelectionPinRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionOriginalStartSessionSelectionPinService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V46__original_start_session_selection_pin.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionOriginalStartSessionSelectionPinServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 1ff8920e22..4de87cb173 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -42,6 +42,12 @@ Game Session commits the exact original Account post-authorization tuple, unchan `GetCanonicalGameInstanceLaunchAssociation` accepts only the verified same-namespace World Management workload without authenticated end-user context. Its independent read identity is separate from the original control-plane operation. The exact original selector and expected descriptor/release digests select the immutable association; the response echoes that selector and returns the complete pair, captured canonical realm UUID/catalog revision, namespace/scope and current runtime status/row version from one owner snapshot. The current runtime projection is not World lifecycle authority. A missing or historically incomplete association produces no successful qualified result; neither a default catalog revision nor a lookup of today's catalog repairs absent launch evidence. This read grants no mutation, lease renewal, runtime admission or activation. +### Immutable Original Selection and Historical Recovery Read + +Game Session retains the exact first `InitialConfigured` selection request/response and its exact-replay descriptor-pin request/response, with their original correlation IDs and byte digests, against the existing Account-attached original tuple, owner attempt/fence and immutable launch association. New retention requires that same pending attempt under its original database-clock lease; it cannot allocate or renew a claim, reselect a release, or backfill historical rows from current Game Design reads. The restricted continuation rules remain owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). + +The deliberately unregistered `ReadHistoricalOriginalStartSessionOwnerEvidence` receiver accepts only the exact same-namespace World workload without end-user context. It reads the existing immutable pin, original Account projection/attempt, and immutable launch association in one independent repeatable-read snapshot, returning the closed historical evidence with the exact requested selector. Missing pins, changed attempts, mismatched source or descriptor digests and incomplete launch bindings fail closed; mutable runtime status is not historical evidence. The read grants no current lease, execution, mutation or admission authority and cannot create or repair a pin. Its consumer is World's [original-operation recovery boundary](../world-management-service/api-contracts.md#implementation-status); executed producer/consumer and PostgreSQL proof remain tracked in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + ## Service Interactions Game Session communicates with other platform services exclusively via gRPC for gameplay-domain work. Player-delegated calls carry the typed unsigned `PlayerExecutionContext` defined in the authentication architecture, including the required gameplay scope for admission. Downstream services authenticate the concrete mTLS caller, enforce an exact RPC caller allowlist, validate context/request equality and domain scope, and reject client-supplied identity metadata. Routine gameplay calls do not use signed per-action attestations or a generic replay cache; mutations retain their owning command/effect/request idempotency. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 43f997a1dd..7ab849ce9a 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -12,6 +12,8 @@ The sections below define the target-state runtime contract. Current implementat - The unregistered original StartSession authored-core retention service and additive V45 retain the unchanged Game Design result against the actual launch and exact original finite owner attempt. Its ordering and synthetic-source PostgreSQL definitions do not establish authenticated producer/consumer composition, actor allocation, attachment, placement or activation. Remote source reads occur outside owner SQL; final retention rechecks the same pending attempt under its owner lock. Exact retained readback does not renew the lease or dispatch another source read. See the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) for proof limits. +- Additive V46 and the unregistered selection-pin owner retain the first selection and descriptor request/result bytes immutably, with exact attempt/launch correlation. Historical reconstruction reads the pin, original attempt and immutable launch in one owner snapshot, without repairing absent history or consuming mutable runtime status as authority. See the [Game Session historical-read contract](./api-contracts.md#immutable-original-selection-and-historical-recovery-read) and [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) for the remaining producer/consumer and PostgreSQL proof gates; this storage does not enable runtime paths. + - Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet; prepared `String` account-identity carriers still contain numeric row-id text and do not prove UUID consumption. Opaque internal carrier preparation and its retained-record/proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). - The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings. 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 090096c7ac..b15f6aeee7 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 @@ -6,7 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The genuine-release definition now issues the original StartSession authorization through the existing Logging & Admin file-backed mTLS client and redeems it through an exact Account-pinned Game Session channel. Both scenarios preserve the actual Account owner, Logging reservation, original Game Session attempt, exact authority bundle and independent Account readback; their issue/redemption peer contexts are no longer stipulated. The corrected Account/Game Design check passes in 1 minute 21 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. The unchanged unit tasks reuse 1,970 passing results; twelve non-container Account integration cases execute, while 289 Account and all 153 Game Design container cases skip, including both genuine-release scenarios. This advances the proof definition, not executed PostgreSQL/mTLS composition. Game Session's durable first-selection/descriptor-pin producer and World preparation historical recovery/settlement remain open; runtime registration and activation remain denied. +The genuine-release definition now obtains the first Game Design selection and exact-replay descriptor through file-backed Game Session mTLS, retains their unchanged request/result bytes through the additive Game Session V46 owner, and independently reads the historical pin through the exact World workload. That unregistered producer reconstructs the immutable pin, original Account-attached attempt and launch in one repeatable-read owner snapshot; missing history is not repaired from current reads or mutable runtime status. The definition also composes World's original-operation recovery with native World-to-Account and World-to-Game Session reads, and Account's exact terminal settlement with native Account-to-World readback. Account source protection must remain pending after World `COMMITTED` until the original participation ID/fence is durably settled and independently read back. The unregistered settlement owner's local invocation still supplies a test peer context; its remote terminal evidence uses the actual authenticated World client. These definitions retain the original tuple and finite lease and do not enable a runtime path. Neither compiled definitions nor synthetic storage/transport cases prove the complete genuine handoff. + +The corrected consolidated Account, Game Session and Game Design check passes in 1 minute 50 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. Game Session executes 2,005 unit cases, including all four new pin/receiver denial and snapshot cases; seventeen pre-existing unit cases skip. Account and Game Design reuse 1,970 passing unit results. Account executes twelve non-container integration cases and skips 289 container cases; Game Design skips all 153 container cases, including both genuine-release scenarios. Game Session's unchanged integration and cross-service tasks reuse thirty and one executed cases respectively, with 175 and 38 skipped. The V46 storage case and positive native historical-recovery/settlement composition have not executed against PostgreSQL. jOOQ schema generation and the 313-file Flyway numbering check pass, but neither establishes migration execution. No positive historical reconstruction is claimed from the older mocked authored-core service fixture. + +Original StartSession authorization is issued through the existing Logging & Admin file-backed mTLS client and redeemed through an exact Account-pinned Game Session channel. Both scenarios preserve the actual Account owner, Logging reservation, original Game Session attempt, exact authority bundle and independent Account readback; their issue/redemption peer contexts are no longer stipulated. The preceding corrected Account/Game Design check passed in 1 minute 21 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. It reused 1,970 passing unit results and executed twelve non-container Account integration cases; 289 Account and all 153 Game Design container cases skipped, including both genuine-release scenarios. Physical source/selection/preparation/settlement composition, real Entity assignment/placement and operational-region delivery remain open. All four handoffs remain incomplete; runtime registration and activation remain denied. World's unregistered protected-activation and activation-terminal-read receivers now have eight executed loopback-mTLS cases using their real handlers and file-backed Common clients: exact same-namespace Game Session and Account callers respectively retain complete canonical terminal/protection bytes and request correlation; trusted wrong-service or wrong-namespace certificates and authenticated end-user context reach no owner; missing client certificates reach neither handler nor owner. The World owners are mocked and the evidence is synthetic, so these cases prove transport enforcement, not genuine source authorization, PostgreSQL activation, fenced abort or Account settlement. The corrected full World check passes in 1 minute 4 seconds with 678 unit cases executed and zero skips, failures or errors, including all eight new cases, formatting, Checkstyle, SpotBugs and coverage. Its unchanged integration task reuses prior results: one non-container case executed and 229 container-dependent cases skipped. Initial test-local channel-cleanup and digest-fixture failures were corrected without changing production guards or assertions. All four complete handoffs remain open; runtime registration and activation remain denied. diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java index 4c2d69f715..8ad2d1f7d8 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -22,6 +22,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; @@ -32,6 +33,8 @@ import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredSettlement; import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; import net.firedevops.firemud.common.gamesession.OriginalStartSessionAdmissionTerminalReadClient; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptClient; @@ -41,10 +44,12 @@ import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalReadClient; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadClient; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; import org.jooq.DSLContext; import org.jooq.Record; +import org.springframework.transaction.support.TransactionTemplate; import tools.jackson.core.type.TypeReference; import tools.jackson.databind.json.JsonMapper; @@ -351,6 +356,50 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( namespace); } + /** Creates Account's actual same-namespace World-only historical participation receiver. */ + public BindableService worldParticipationHistoricalReadGrpcService() { + var repository = new AccountStartSessionWorldParticipationRepository(accountSources.dsl); + var owner = + new AccountStartSessionWorldParticipationHistoricalReadService( + repository, accountSources.manager, namespace); + return new AccountStartSessionWorldParticipationHistoricalReadGrpcService(owner, namespace); + } + + /** Creates the actual exact-terminal Account settler over this fixture's retained rows. */ + public AccountStartSessionWorldParticipationSettlementService worldParticipationSettlementService( + WorldStartSessionExecutionTerminalReadClient worldClient) { + Objects.requireNonNull(worldClient, "World terminal-read client required"); + return new AccountStartSessionWorldParticipationSettlementService( + new AccountStartSessionWorldParticipationRepository(accountSources.dsl), + worldClient, + accountSources.manager, + namespace); + } + + /** + * Reads the exact durable participation coordinates for this tuple without creating authority. + */ + public Optional worldParticipationForOriginalTuple(byte[] tupleBytes) { + Objects.requireNonNull(tupleBytes, "original StartSession tuple bytes required"); + var repository = new AccountStartSessionWorldParticipationRepository(accountSources.dsl); + var transaction = new TransactionTemplate(accountSources.manager); + return Objects.requireNonNull( + transaction.execute(ignored -> repository.findHistoricalForOriginalTuple(tupleBytes)), + "Account original-tuple participation lookup returned no optional"); + } + + /** Independently reads one durable exact terminal settlement without retrying its mutation. */ + public Optional worldParticipationSettlementExact( + UUID participationId, long participationFence) { + Objects.requireNonNull(participationId, "World participation id required"); + var repository = new AccountStartSessionWorldParticipationRepository(accountSources.dsl); + var transaction = new TransactionTemplate(accountSources.manager); + return Objects.requireNonNull( + transaction.execute( + ignored -> repository.findSettlementExact(participationId, participationFence)), + "Account exact World settlement lookup returned no optional"); + } + /** Creates the actual Account admission-protection acquirer over this fixture's retained rows. */ public AccountStartSessionAdmissionProtectionAcquisitionService admissionProtectionAcquisitionService( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index b4cad08d55..62974f2c3e 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -76,6 +76,7 @@ import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionSettlementInput; import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionAcquisitionGrpcClient; import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationAcquisitionClient; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadClient; import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionActivationProtectionAcquisitionClient; import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionActivationProtectionSettlementClient; import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; @@ -136,6 +137,7 @@ import net.firedevops.firemud.common.gamesession.GrpcOriginalStartSessionCurrentAttemptClient; import net.firedevops.firemud.common.gamesession.GrpcOriginalStartSessionLaunchReadClient; import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidenceReadClient; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; @@ -183,6 +185,7 @@ import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldOriginalStartSessionProtectedActivationGrpcCodec; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadClient; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeService; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeTerminalReadService; @@ -203,11 +206,14 @@ import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalOutcomeRepository; import net.firedevops.firemud.gamedesign.draft.GameDesignDraftTerminalReadGrpcService; import net.firedevops.firemud.gamedesign.draft.GameDesignSelectedDraftPublicationReadGrpcService; +import net.firedevops.firemud.gamedesign.draft.GameDesignStartSessionLaunchDescriptorGrpcService; import net.firedevops.firemud.gamedesign.draft.GameDesignStartSessionPublishedRealmPolicyReadGrpcService; +import net.firedevops.firemud.gamedesign.draft.GameDesignStartSessionTemplateAssociationReadGrpcService; import net.firedevops.firemud.gamedesign.draft.GameDesignWorldSourceCommitService; import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.entity.GameAsset; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.mapper.VersionMapper; @@ -283,7 +289,11 @@ import net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.VersionAssetExportCandidateServiceImpl; import net.firedevops.firemud.gamedesign.service.impl.VersionPublishCommandServiceImpl; +import net.firedevops.firemud.gamedesign.v1.GameDesignStartSessionLaunchDescriptorServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GameDesignStartSessionTemplateAssociationReadServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.WorldDesignMutationRevision; import net.firedevops.firemud.gamelogic.service.GameLogicDraftDesignDigestService; import net.firedevops.firemud.gamelogic.service.impl.GameLogicGrpcService; @@ -299,11 +309,15 @@ import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionOriginalStartSessionSelectionPinRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionOriginalStartSessionSelectionPinRepository.Candidate; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; import net.firedevops.firemud.gamesession.service.impl.CanonicalGameInstanceLaunchAssociationReadGrpcService; import net.firedevops.firemud.gamesession.service.impl.GameSessionAuthoredActorCoreRetentionService; +import net.firedevops.firemud.gamesession.service.impl.GameSessionOriginalStartSessionSelectionPinService; +import net.firedevops.firemud.gamesession.service.impl.HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService; import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionCurrentAttemptReadGrpcService; import net.firedevops.firemud.gamesession.service.impl.OriginalStartSessionLaunchReadGrpcService; import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; @@ -333,6 +347,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceOriginalOperationRecoveryVerifier; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationAssemblyService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository; @@ -352,6 +367,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationService; import net.firedevops.firemud.worldmanagement.tenant.WorldSelectedOwnerInventoryReadProofFixture; import net.firedevops.firemud.worldmanagement.tenant.WorldStartSessionAccountParticipationVerifier; +import net.firedevops.firemud.worldmanagement.tenant.WorldStartSessionExecutionTerminalReadGrpcService; import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.ActivateCanonicalWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.RegionDesignMutation; @@ -645,6 +661,17 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( try (var loggingClaimClient = currentClaimGrpcClient(loggingServer.getPort(), pki); var startSessionAuthorizationTransport = new NativeAccountStartSessionAuthorizationTransport(endpoints, pki, channels); + var gameDesignStartSessionReadTransport = + new NativeGameDesignStartSessionReadTransport(endpoints, pki, channels); + var worldToAccountParticipationHistoryClient = + new AccountStartSessionWorldParticipationHistoricalReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var worldToGameSessionOwnerEvidenceClient = + new HistoricalOriginalStartSessionOwnerEvidenceReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var accountToWorldExecutionTerminalClient = + new WorldStartSessionExecutionTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); var account = new AccountControlUiOriginalOrderFixture( ACCOUNT_POSTGRES.getJdbcUrl(), @@ -733,6 +760,12 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( var gameSessionActivationClient = canonicalActivationClient(worldServer, pki.client("game-session-service"), channels)) { ReflectionTestUtils.invokeMethod(loggingClaimClient, "init"); + worldToAccountParticipationHistoryClient.init(); + worldToGameSessionOwnerEvidenceClient.init(); + accountToWorldExecutionTerminalClient.init(); + var originalOperationRecoveryVerifier = + new WorldCanonicalInstanceOriginalOperationRecoveryVerifier( + worldToAccountParticipationHistoryClient, worldToGameSessionOwnerEvidenceClient); accountToGameSessionCurrentAttemptClient.init(); accountToGameSessionTerminalClient.init(); accountToGameSessionLaunchReadClient.init(); @@ -1195,7 +1228,10 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( temporary.resolve("account-start-session-authorization-proof"), NAMESPACE, loggingClaimClient); - register(accountHandlers, startSessionAuthorizationProof.grpcService()); + register( + accountHandlers, + startSessionAuthorizationProof.grpcService(), + startSessionAuthorizationProof.worldParticipationHistoricalReadGrpcService()); var accountAdmissionProtectionAcquisition = startSessionAuthorizationProof.admissionProtectionAcquisitionService( accountToGameSessionCurrentAttemptClient); @@ -1221,6 +1257,9 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( var accountWorldParticipationAcquisitionService = startSessionAuthorizationProof.worldParticipationAcquisitionService( accountToGameSessionCurrentAttemptClient); + var accountWorldParticipationSettlementService = + startSessionAuthorizationProof.worldParticipationSettlementService( + accountToWorldExecutionTerminalClient); register( accountHandlers, new AccountStartSessionWorldParticipationAcquisitionGrpcService( @@ -2663,6 +2702,45 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( var startSessionAssociationReader = new StartSessionTemplateAssociationReadService( gd.dsl(), gd.transactions(), NAMESPACE, projectionClient, releaseService); + var descriptorProducer = + new StartSessionLaunchDescriptorProducer( + gd.dsl(), + gd.transactions(), + NAMESPACE, + startSessionAssociationReader, + releaseService, + new ObjectMapper()); + register( + gdHandlers, + new GameDesignStartSessionTemplateAssociationReadGrpcService( + startSessionAssociationReader, NAMESPACE), + new GameDesignStartSessionLaunchDescriptorGrpcService(descriptorProducer, NAMESPACE)); + var canonicalRealmCatalogRepository = + new GameSessionCanonicalRealmCatalogRepository( + gameSessionAttempts.dsl(), gameSessionAttempts.transactionManager(), NAMESPACE); + var canonicalLaunchRepository = + new GameSessionCanonicalInstanceLaunchRepository( + gameSessionAttempts.dsl(), + gameSessionAttempts.transactionManager(), + NAMESPACE, + canonicalRealmCatalogRepository); + var selectionPinRepository = + new GameSessionOriginalStartSessionSelectionPinRepository( + gameSessionAttempts.dsl(), + gameSessionAttempts.transactionManager(), + gameSessionAttempts.repository(), + NAMESPACE); + var selectionPinService = + new GameSessionOriginalStartSessionSelectionPinService( + selectionPinRepository, + gameSessionAttempts.repository(), + canonicalLaunchRepository, + gameSessionAttempts.transactionManager(), + NAMESPACE); + register( + gameSessionHandlers, + new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService( + selectionPinService, NAMESPACE)); register( gdHandlers, new GrpcAuthoredInitialActorCoreReadService( @@ -3255,26 +3333,49 @@ public void attachAccountRedemptionProjection( ownerAttemptId, ownerFence, new StartSessionTemplateAssociationReadEvidence.InitialConfigured()); - firstStartSessionSelection = - withGameSessionPeer(() -> startSessionAssociationReader.read(firstSelectionRequest)); - var descriptorProducer = - new StartSessionLaunchDescriptorProducer( - gd.dsl(), - gd.transactions(), - NAMESPACE, - startSessionAssociationReader, - releaseService, - new ObjectMapper()); + var firstSelectionCall = + gameDesignStartSessionReadTransport.readInitialSelection(firstSelectionRequest); + firstStartSessionSelection = firstSelectionCall.result(); + var firstDescriptorRequest = + startSessionReadRequest( + startSessionTuple, + ownerAttemptId, + ownerFence, + pinnedSelection, + UUID.randomUUID()); + var firstDescriptorCall = + gameDesignStartSessionReadTransport.resolveDescriptor(firstDescriptorRequest); + var firstDescriptorEvidence = firstDescriptorCall.result(); + assertThat(firstDescriptorEvidence.outcome()) + .isInstanceOf(StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome.class); + var authoredWorldLaunchDescriptor = + ((StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome) + firstDescriptorEvidence.outcome()) + .descriptor(); + var firstDescriptorRead = + gameSessionToGameDesignAuthoredCoreClient.read( + new AuthoredInitialActorCoreReadEvidence.ReadRequest(firstDescriptorRequest)); + var descriptorDto = + new ResolvedLaunchDescriptorDto( + authoredWorldLaunchDescriptor.launchDescriptorId(), + authoredWorldLaunchDescriptor.canonicalTenantId().toString(), + authoredWorldLaunchDescriptor.gameTemplateId(), + authoredWorldLaunchDescriptor.controlPlaneRequestId(), + authoredWorldLaunchDescriptor.versionId(), + authoredWorldLaunchDescriptor.scriptPatchVersion(), + authoredWorldLaunchDescriptor.runtimeFlagsJson(), + authoredWorldLaunchDescriptor.generationConfigRevision(), + authoredWorldLaunchDescriptor.versionStateEpoch(), + authoredWorldLaunchDescriptor.releaseBundleId(), + authoredWorldLaunchDescriptor.publishedReleaseBundleRef(), + authoredWorldLaunchDescriptor.remapSetId(), + authoredWorldLaunchDescriptor); var firstDescriptorBinding = - withGameSessionPeer( - () -> - descriptorProducer.resolve( - startSessionReadRequest( - startSessionTuple, - ownerAttemptId, - ownerFence, - pinnedSelection, - UUID.randomUUID()))); + new StartSessionLaunchDescriptorProducer.ResolvedBinding( + firstDescriptorRequest, + firstDescriptorEvidence.associationRead(), + descriptorDto, + firstDescriptorRead.projections()); assertThat(firstDescriptorBinding.descriptor().versionId()) .isEqualTo(gd.target().gameDesignVersionRowId()); assertThat(firstDescriptorBinding.descriptor().launchDescriptorId()).isNotBlank(); @@ -3322,8 +3423,7 @@ public void attachAccountRedemptionProjection( var authoredCoreReadRequest = new AuthoredInitialActorCoreReadEvidence.ReadRequest( firstDescriptorBinding.request()); - var gameSessionAuthoredCoreRead = - gameSessionToGameDesignAuthoredCoreClient.read(authoredCoreReadRequest); + var gameSessionAuthoredCoreRead = firstDescriptorRead; assertThat(gameSessionAuthoredCoreRead.request()) .isEqualTo(firstDescriptorBinding.request()); assertThat(gameSessionAuthoredCoreRead.request().canonicalPostAuthorizationTuple()) @@ -3600,9 +3700,6 @@ public void attachAccountRedemptionProjection( assertThat(actualPublishedPolicy.entryPolicy()) .isEqualTo(actorCoreScenario.entryPolicy()); - var canonicalRealmCatalogRepository = - new GameSessionCanonicalRealmCatalogRepository( - gameSessionAttempts.dsl(), gameSessionAttempts.transactionManager(), NAMESPACE); var canonicalRealmCatalog = canonicalRealmCatalogRepository.establishFreshPublicRealm( freshTenantAssociation, @@ -3802,12 +3899,6 @@ public void attachAccountRedemptionProjection( CompleteLaunchBindingEvidence completeLaunchEvidence = new CompleteLaunchBindingEvidence( completeBinding.descriptor(), completeBinding.releaseAttestation()); - var canonicalLaunchRepository = - new GameSessionCanonicalInstanceLaunchRepository( - gameSessionAttempts.dsl(), - gameSessionAttempts.transactionManager(), - NAMESPACE, - canonicalRealmCatalogRepository); var canonicalLaunch = canonicalLaunchRepository.createStartingLaunch( startSessionTuple, completeLaunchEvidence, canonicalRealmCatalog); @@ -3840,8 +3931,8 @@ public void attachAccountRedemptionProjection( canonicalLaunch.launchBindingEvidence().descriptor().resultDigest(), canonicalLaunch.launchBindingEvidence().releaseAttestation().evidenceDigest()); - // Reuse the original InitialConfigured owner selection above. This local owner readback - // is not an authenticated historical-evidence RPC. + // Build the pin from the original native owner reads above. Independently resolve the + // retained result through the authenticated historical-evidence RPC below. var originalCurrentAttemptRequest = new OriginalStartSessionCurrentAttemptEvidence.Request( @@ -3910,6 +4001,53 @@ public void attachAccountRedemptionProjection( new StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome( firstDescriptorBinding.descriptor().authoredWorldBinding())) .toByteArray())); + var retainedFirstSelectionPin = + selectionPinService.retainFirst( + new Candidate( + historicalOwnerEvidence, + ownerMutationId, + firstSelectionCall.requestBytes(), + firstSelectionCall.responseBytes(), + firstDescriptorCall.requestBytes(), + firstDescriptorCall.responseBytes())); + assertThat(retainedFirstSelectionPin.ownerAttemptId()).isEqualTo(ownerAttemptId); + assertThat(retainedFirstSelectionPin.ownerMutationId()).isEqualTo(ownerMutationId); + assertThat(retainedFirstSelectionPin.ownerFence()).isEqualTo(ownerFence); + assertThat(retainedFirstSelectionPin.ownerLeaseExpiresAt()) + .isEqualTo(currentOwnerAttemptBeforeRetention.leaseExpiresAt()); + assertThat(retainedFirstSelectionPin.initialSelectionRequestBytes()) + .containsExactly(firstSelectionCall.requestBytes()); + assertThat(retainedFirstSelectionPin.initialSelectionResponseBytes()) + .containsExactly(firstSelectionCall.responseBytes()); + assertThat(retainedFirstSelectionPin.descriptorPinRequestBytes()) + .containsExactly(firstDescriptorCall.requestBytes()); + assertThat(retainedFirstSelectionPin.descriptorPinResponseBytes()) + .containsExactly(firstDescriptorCall.responseBytes()); + var retainedOwnerEvidence = + worldToGameSessionOwnerEvidenceClient.read(historicalOwnerEvidence.request()); + assertThat(retainedOwnerEvidence.request()).isEqualTo(historicalOwnerEvidence.request()); + assertThat(retainedOwnerEvidence.originalTuple().canonicalBytes()) + .containsExactly(startSessionTuple.canonicalBytes()); + assertThat(retainedOwnerEvidence.ownerAttemptId()).isEqualTo(ownerAttemptId); + assertThat(retainedOwnerEvidence.ownerFence()).isEqualTo(ownerFence); + assertThat(retainedOwnerEvidence.accountRedemptionProjection()) + .containsExactly(currentOwnerAttemptBeforeRetention.accountRedemptionProjection()); + assertThat(retainedOwnerEvidence.firstSelection().request()) + .isEqualTo(firstSelectionRequest); + assertThat(retainedOwnerEvidence.firstSelection().association()) + .isEqualTo(firstStartSessionSelection.association()); + assertThat(retainedOwnerEvidence.descriptorPin().outcome()) + .isEqualTo(firstDescriptorEvidence.outcome()); + assertThat(retainedOwnerEvidence.launchAssociation()) + .isEqualTo(historicalOwnerEvidence.launchAssociation()); + assertThat(retainedOwnerEvidence.templateAssociationRequestDigest()) + .isEqualTo(retainedFirstSelectionPin.initialSelectionRequestDigest()); + assertThat(retainedOwnerEvidence.templateAssociationResponseDigest()) + .isEqualTo(retainedFirstSelectionPin.initialSelectionResponseDigest()); + assertThat(retainedOwnerEvidence.descriptorPinRequestDigest()) + .isEqualTo(retainedFirstSelectionPin.descriptorPinRequestDigest()); + assertThat(retainedOwnerEvidence.descriptorPinResponseDigest()) + .isEqualTo(retainedFirstSelectionPin.descriptorPinResponseDigest()); var authoredCoreRetentionRepository = new GameSessionAuthoredActorCoreRetentionRepository( @@ -3937,7 +4075,7 @@ public void close() {} gameSessionAttempts.transactionManager()); var firstRetainedAuthoredCore = authoredCoreRetentionService.retain( - historicalOwnerEvidence, originalCurrentAttemptRequest); + retainedOwnerEvidence, originalCurrentAttemptRequest); assertThat(firstRetainedAuthoredCore.candidate().canonicalSourceResultBytes()) .containsExactly(gameSessionAuthoredCoreRead.canonicalBytes()); assertThat(firstRetainedAuthoredCore.candidate().originalPostAuthorizationTuple()) @@ -3966,7 +4104,7 @@ public void close() {} .containsExactly(gameSessionAuthoredCoreRead.canonicalBytes()); var exactRetainedAuthoredCoreRetry = authoredCoreRetentionService.retain( - historicalOwnerEvidence, originalCurrentAttemptRequest); + retainedOwnerEvidence, originalCurrentAttemptRequest); assertThat(exactRetainedAuthoredCoreRetry.candidate().canonicalSourceResultBytes()) .containsExactly( independentRetainedAuthoredCore.candidate().canonicalSourceResultBytes()); @@ -4094,7 +4232,9 @@ public void close() {} worldToGameDesignPreparationClient); var preparationService = new WorldCanonicalInstancePreparationService( - preparationRepository, worldParticipationVerifier); + preparationRepository, + worldParticipationVerifier, + originalOperationRecoveryVerifier); register( worldHandlers, new WorldCanonicalInstancePreparationGrpcService( @@ -4103,7 +4243,9 @@ public void close() {} preparationService, preparationRepository, lifecycleRepository, - NAMESPACE)); + NAMESPACE), + new WorldStartSessionExecutionTerminalReadGrpcService( + preparationService, NAMESPACE)); var expectedLifecycleRequest = lifecycleRequest( @@ -4155,6 +4297,108 @@ public void close() {} expectedLifecycleRequest); } + var exactAccountParticipation = + startSessionAuthorizationProof + .worldParticipationForOriginalTuple(startSessionTuple.canonicalBytes()) + .orElseThrow(); + assertThat(exactAccountParticipation.originalPostAuthorizationTuple()) + .containsExactly(startSessionTuple.canonicalBytes()); + assertThat(exactAccountParticipation.gameSessionOwnerAttemptId()) + .isEqualTo(ownerAttemptId); + assertThat(exactAccountParticipation.gameSessionOwnerFence()).isEqualTo(ownerFence); + assertThat(exactAccountParticipation.canonicalGameInstanceId()) + .isEqualTo(canonicalGameInstanceId); + assertThat(exactAccountParticipation.preparationInputDigest()) + .isEqualTo( + "sha256:" + + sha256( + exactAccountParticipation + .preparationInputJson() + .getBytes(StandardCharsets.UTF_8))); + assertThat(exactAccountParticipation.sourceVector()).isNotEmpty(); + assertThat( + startSessionAuthorizationProof.worldParticipationSettlementExact( + exactAccountParticipation.participationId(), + exactAccountParticipation.participationFence())) + .isEmpty(); + var committedWorldTerminalRequest = + new net.firedevops.firemud.common.world + .WorldStartSessionExecutionTerminalReadRequest( + UUID.randomUUID(), + NAMESPACE, + startSessionTuple.canonicalBytes(), + exactAccountParticipation.participationId(), + exactAccountParticipation.participationFence(), + ownerAttemptId, + ownerFence, + canonicalGameInstanceId, + exactAccountParticipation.preparationInputJson()); + var committedWorldTerminal = + accountToWorldExecutionTerminalClient.read(committedWorldTerminalRequest); + assertThat(committedWorldTerminal.outcome()) + .isEqualTo( + net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal.Outcome + .COMMITTED); + assertThat(committedWorldTerminal.accountWorldParticipationId()) + .isEqualTo(exactAccountParticipation.participationId()); + assertThat(committedWorldTerminal.accountWorldParticipationFence()) + .isEqualTo(exactAccountParticipation.participationFence()); + var accountParticipationAfterWorldCommit = + startSessionAuthorizationProof + .worldParticipationForOriginalTuple(startSessionTuple.canonicalBytes()) + .orElseThrow(); + assertThat(accountParticipationAfterWorldCommit.participationId()) + .isEqualTo(exactAccountParticipation.participationId()); + assertThat(accountParticipationAfterWorldCommit.participationFence()) + .isEqualTo(exactAccountParticipation.participationFence()); + assertThat(accountParticipationAfterWorldCommit.sourceVector()) + .containsExactlyElementsOf(exactAccountParticipation.sourceVector()); + var protectedCreatorSources = account.preparedOriginalCreator().sources(); + String creatorRoleBeforeSettlement = + startSessionAuthorizationProof + .sourceDsl() + .fetchSingle( + "SELECT role FROM accounts WHERE account_uuid = ?", + startSessionAuthorizationProof.creatorAccountId()) + .get(0, String.class); + assertThatThrownBy(protectedCreatorSources::changeRoleToAdmin) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining( + "StartSession World participation remains pending for a required source"); + assertThat( + startSessionAuthorizationProof + .sourceDsl() + .fetchSingle( + "SELECT role FROM accounts WHERE account_uuid = ?", + startSessionAuthorizationProof.creatorAccountId()) + .get(0, String.class)) + .isEqualTo(creatorRoleBeforeSettlement); + assertThat( + startSessionAuthorizationProof.worldParticipationSettlementExact( + exactAccountParticipation.participationId(), + exactAccountParticipation.participationFence())) + .isEmpty(); + var settledWorldParticipation = + withWorldPeer( + () -> + accountWorldParticipationSettlementService.settle( + exactAccountParticipation.participationId(), + exactAccountParticipation.participationFence())); + assertThat(settledWorldParticipation.participationId()) + .isEqualTo(exactAccountParticipation.participationId()); + assertThat(settledWorldParticipation.outcome()) + .isEqualTo(committedWorldTerminal.outcome()); + assertThat(settledWorldParticipation.terminalBytes()) + .containsExactly(committedWorldTerminal.canonicalBytes()); + var independentlySettledWorldParticipation = + startSessionAuthorizationProof + .worldParticipationSettlementExact( + exactAccountParticipation.participationId(), + exactAccountParticipation.participationFence()) + .orElseThrow(); + assertThat(independentlySettledWorldParticipation.terminalBytes()) + .containsExactly(settledWorldParticipation.terminalBytes()); + var assembledPreparationInput = preparationAssembly.assemble( new WorldCanonicalInstancePreparationAssemblyService.Selector( @@ -5649,6 +5893,21 @@ private static T withGameSessionPeer(Supplier operation) { } } + private static T withWorldPeer(Supplier operation) { + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", + NAMESPACE, + "world-management-service"); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return operation.get(); + } finally { + context.detach(previous); + } + } + private static void assertFailedPrecondition(Runnable operation) { assertThatThrownBy(operation::run) .isInstanceOf(io.grpc.StatusRuntimeException.class) @@ -6591,6 +6850,105 @@ private static StartSessionReservationEvidenceClient currentClaimGrpcClient( BlockingGrpcStubCustomizer.noop()); } + /** Native Game Session-to-Game Design reads for the exact first selection and descriptor pin. */ + private static final class NativeGameDesignStartSessionReadTransport implements AutoCloseable { + private final ManagedChannel channel; + private final GameDesignStartSessionTemplateAssociationReadServiceGrpc + .GameDesignStartSessionTemplateAssociationReadServiceBlockingStub + selectionStub; + private final GameDesignStartSessionLaunchDescriptorServiceGrpc + .GameDesignStartSessionLaunchDescriptorServiceBlockingStub + descriptorStub; + + NativeGameDesignStartSessionReadTransport( + ServiceEndpointsProperties endpoints, TestPki pki, GrpcChannelFactory channels) + throws IOException { + channel = + channels.buildChannel( + endpoints.getGameDesignService(), 6565, pki.client("game-session-service"), false); + String expectedPeer = "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service"; + selectionStub = + GameDesignStartSessionTemplateAssociationReadServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeer)); + descriptorStub = + GameDesignStartSessionLaunchDescriptorServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeer)); + } + + InitialSelectionCall readInitialSelection( + StartSessionTemplateAssociationReadEvidence.Request request) { + var wireRequest = StartSessionTemplateAssociationReadGrpcCodec.toRequest(request); + ReadStartSessionTemplateAssociationResponse wireResponse = + selectionStub + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .readStartSessionTemplateAssociation(wireRequest); + var result = StartSessionTemplateAssociationReadGrpcCodec.fromResponse(request, wireResponse); + return new InitialSelectionCall( + result, wireRequest.toByteArray(), wireResponse.toByteArray()); + } + + DescriptorPinCall resolveDescriptor( + StartSessionTemplateAssociationReadEvidence.Request request) { + var wireRequest = StartSessionLaunchDescriptorGrpcCodec.toRequest(request); + ResolveStartSessionLaunchDescriptorResponse wireResponse = + descriptorStub + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .resolveStartSessionLaunchDescriptor(wireRequest); + var result = StartSessionLaunchDescriptorGrpcCodec.fromResponse(request, wireResponse); + return new DescriptorPinCall(result, wireRequest.toByteArray(), wireResponse.toByteArray()); + } + + @Override + public void close() throws InterruptedException { + channel.shutdownNow(); + if (!channel.awaitTermination(5L, TimeUnit.SECONDS)) { + throw new AssertionError("Game Design StartSession read channel did not terminate"); + } + } + } + + private record InitialSelectionCall( + StartSessionTemplateAssociationReadEvidence.Result result, + byte[] requestBytes, + byte[] responseBytes) { + private InitialSelectionCall { + requestBytes = requestBytes.clone(); + responseBytes = responseBytes.clone(); + } + + @Override + public byte[] requestBytes() { + return requestBytes.clone(); + } + + @Override + public byte[] responseBytes() { + return responseBytes.clone(); + } + } + + private record DescriptorPinCall( + StartSessionLaunchDescriptorGrpcCodec.Resolved result, + byte[] requestBytes, + byte[] responseBytes) { + private DescriptorPinCall { + requestBytes = requestBytes.clone(); + responseBytes = responseBytes.clone(); + } + + @Override + public byte[] requestBytes() { + return requestBytes.clone(); + } + + @Override + public byte[] responseBytes() { + return responseBytes.clone(); + } + } + /** Native file-backed mTLS transport for the real Account original StartSession owner. */ private static final class NativeAccountStartSessionAuthorizationTransport implements OriginalStartSessionAuthorizationTransport, AutoCloseable { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java index 5490b9799a..6d71f1db16 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java @@ -11,6 +11,7 @@ import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; import net.firedevops.firemud.common.gamesession.OriginalStartSessionLaunchReadEvidence; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.publication.RealmEntryPolicy; @@ -156,6 +157,83 @@ public Optional readByOriginalTuple( result, "Game Session original tuple launch read transaction returned no result"); } + /** + * Reads only immutable launch-association columns inside a caller-owned historical snapshot. + * Mutable Game Instance lifecycle state and the current owner-attempt phase are not consulted. + */ + public Optional + readHistoricalAssociationInOwnerTransaction( + CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector, + byte[] exactOriginalPostAuthorizationTupleBytes) { + requireOwnerTransaction(); + Objects.requireNonNull(selector, "selector"); + if (!workloadNamespace.equals(selector.targetNamespace())) { + throw new InvalidCanonicalInstanceLaunchException( + "Launch-association namespace differs from the configured Game Session owner"); + } + byte[] exactTuple = + Objects.requireNonNull(exactOriginalPostAuthorizationTupleBytes, "exact original tuple") + .clone(); + StartSessionPostAuthorizationExecutionTuple decoded = + StartSessionPostAuthorizationExecutionTuple.decode(exactTuple); + if (!Arrays.equals(decoded.canonicalBytes(), exactTuple)) { + throw new InvalidCanonicalInstanceLaunchException( + "Historical original StartSession tuple is not canonical"); + } + Record row = + dsl.fetchOne( + "SELECT target_namespace, canonical_tenant_id, world_slug, game_instance_uuid," + + " control_plane_request_id, launch_descriptor_id, playable_state_namespace_id," + + " playable_state_scope, public_production, captured_starting_row_version," + + " complete_launch_binding_evidence::text AS gs_complete_launch_binding_json," + + " original_start_session_tuple" + + " FROM game_session_canonical_instance_launch" + + " WHERE target_namespace = ? AND control_plane_request_id = ?", + selector.targetNamespace(), + selector.controlPlaneRequestId()); + if (row == null) return Optional.empty(); + String namespace = required(row, "target_namespace", String.class); + UUID tenantId = required(row, "canonical_tenant_id", UUID.class); + String worldSlug = required(row, "world_slug", String.class); + UUID instanceUuid = required(row, "game_instance_uuid", UUID.class); + String requestId = required(row, "control_plane_request_id", String.class); + String descriptorId = required(row, "launch_descriptor_id", String.class); + byte[] storedTuple = required(row, "original_start_session_tuple", byte[].class); + if (!namespace.equals(selector.targetNamespace()) + || !tenantId.equals(selector.canonicalTenantId()) + || !worldSlug.equals(selector.worldSlug()) + || !instanceUuid.equals(selector.gameInstanceUuid()) + || !requestId.equals(selector.controlPlaneRequestId()) + || !descriptorId.equals(selector.launchDescriptorId()) + || !Arrays.equals(storedTuple, exactTuple)) { + throw new InvalidCanonicalInstanceLaunchException( + "Historical launch association differs from its exact original selector and tuple"); + } + RealmEntryPolicy.StateScope scope; + try { + scope = + RealmEntryPolicy.StateScope.valueOf(required(row, "playable_state_scope", String.class)); + } catch (RuntimeException invalid) { + throw new InvalidCanonicalInstanceLaunchException( + "Historical launch playable-state scope is malformed", invalid); + } + CompleteLaunchBindingEvidence binding = + decodeBinding(required(row, "gs_complete_launch_binding_json", String.class)); + return Optional.of( + new HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation( + namespace, + tenantId, + worldSlug, + instanceUuid, + requestId, + descriptorId, + required(row, "playable_state_namespace_id", UUID.class), + scope, + required(row, "public_production", Boolean.class), + required(row, "captured_starting_row_version", Long.class), + binding)); + } + private CanonicalInstanceLaunch createInTransaction(PreparedLaunch input) { requireOwnerTransaction(); lockIdentity(input); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionSelectionPinRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionSelectionPinRepository.java new file mode 100644 index 0000000000..376aefa91b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionSelectionPinRepository.java @@ -0,0 +1,461 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Immutable Game Session owner storage for the original first selection and descriptor pin. */ +public final class GameSessionOriginalStartSessionSelectionPinRepository { + private static final String TABLE = "game_session_original_start_session_selection_pin"; + + private final DSLContext dsl; + private final String workloadNamespace; + private final GameSessionStartSessionOperatorAttemptRepository attempts; + private final TransactionTemplate readTransaction; + + public GameSessionOriginalStartSessionSelectionPinRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + GameSessionStartSessionOperatorAttemptRepository attempts, + String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(transactionManager, "transactionManager"); + this.attempts = Objects.requireNonNull(attempts, "original attempt repository is required"); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + readTransaction = new TransactionTemplate(transactionManager); + readTransaction.setReadOnly(true); + readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + /** + * Appends the first pin only while the same original Account-attached attempt is pending and + * unexpired. Exact retries return the first bytes; a changed request or response conflicts. + */ + public StoredPin retainFirstInOwnerTransaction(Candidate candidate) { + requireOwnerTransaction(); + Objects.requireNonNull(candidate, "selection pin candidate is required"); + requireIdentity(candidate.targetNamespace(), candidate.controlPlaneRequestId()); + if (!workloadNamespace.equals(candidate.targetNamespace())) { + throw new IllegalArgumentException( + "Selection pin differs from configured Game Session owner"); + } + + Record first = select(candidate.targetNamespace(), candidate.controlPlaneRequestId()); + if (first != null) { + StoredPin retained = snapshot(first); + requireSameCandidate(candidate, retained); + return retained; + } + + var tuple = StartSessionPostAuthorizationExecutionTuple.decode(candidate.originalTupleBytes()); + var continuation = attempts.beginEvidenceContinuation(tuple); + var attempt = attempts.validateEvidenceContinuation(continuation); + if (!attempt.ownerAttemptId().equals(candidate.ownerAttemptId()) + || !attempt.ownerMutationId().equals(candidate.ownerMutationId()) + || attempt.ownerFence() != candidate.ownerFence() + || !Arrays.equals(attempt.postAuthorizationExecutionTuple(), candidate.originalTupleBytes()) + || !Arrays.equals( + attempt.accountRedemptionProjection(), candidate.accountRedemptionProjection())) { + throw conflict("Selection pin does not match the exact live original owner attempt"); + } + + dsl.execute( + "INSERT INTO " + + TABLE + + " (target_namespace, control_plane_request_id, canonical_tenant_id, " + + "game_instance_uuid, launch_descriptor_id, owner_attempt_id, owner_mutation_id, " + + "owner_fence, owner_lease_expires_at, original_post_authorization_tuple, " + + "account_redemption_projection, initial_selection_request_bytes, " + + "initial_selection_request_digest, initial_selection_response_bytes, " + + "initial_selection_response_digest, descriptor_pin_request_bytes, " + + "descriptor_pin_request_digest, descriptor_pin_response_bytes, " + + "descriptor_pin_response_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (target_namespace, control_plane_request_id) DO NOTHING", + candidate.targetNamespace(), + candidate.controlPlaneRequestId(), + candidate.canonicalTenantId(), + candidate.gameInstanceUuid(), + candidate.launchDescriptorId(), + attempt.ownerAttemptId(), + attempt.ownerMutationId(), + attempt.ownerFence(), + java.time.OffsetDateTime.ofInstant(attempt.leaseExpiresAt(), java.time.ZoneOffset.UTC), + candidate.originalTupleBytes(), + candidate.accountRedemptionProjection(), + candidate.initialSelectionRequestBytes(), + candidate.initialSelectionRequestDigest(), + candidate.initialSelectionResponseBytes(), + candidate.initialSelectionResponseDigest(), + candidate.descriptorPinRequestBytes(), + candidate.descriptorPinRequestDigest(), + candidate.descriptorPinResponseBytes(), + candidate.descriptorPinResponseDigest()); + + Record row = select(candidate.targetNamespace(), candidate.controlPlaneRequestId()); + if (row == null) throw unavailable(); + StoredPin stored = snapshot(row); + requireSameCandidate(candidate, stored); + return stored; + } + + /** Reads the already-retained first pin; it never creates or repairs one. */ + public Optional readByOriginalOperation( + String targetNamespace, String controlPlaneRequestId) { + requireNoOwnerTransaction(); + requireIdentity(targetNamespace, controlPlaneRequestId); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Selection pin read differs from configured Game Session owner"); + } + Optional result = + Objects.requireNonNull( + readTransaction.execute( + ignored -> { + Record row = select(targetNamespace, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(snapshot(row)); + }), + "Selection pin historical read returned no optional"); + return result; + } + + /** Read-only pin lookup for composition with the attempt and launch in one owner snapshot. */ + public Optional readByOriginalOperationInOwnerTransaction( + String targetNamespace, String controlPlaneRequestId) { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Active Game Session historical owner snapshot required"); + } + requireIdentity(targetNamespace, controlPlaneRequestId); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Selection pin read differs from configured Game Session owner"); + } + Record row = select(targetNamespace, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(snapshot(row)); + } + + private Record select(String targetNamespace, String controlPlaneRequestId) { + return dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE target_namespace = ? AND control_plane_request_id = ?", + targetNamespace, + controlPlaneRequestId); + } + + private StoredPin snapshot(Record row) { + return new StoredPin( + required(row, "target_namespace", String.class), + required(row, "control_plane_request_id", String.class), + required(row, "canonical_tenant_id", UUID.class), + required(row, "game_instance_uuid", UUID.class), + required(row, "launch_descriptor_id", String.class), + required(row, "owner_attempt_id", UUID.class), + required(row, "owner_mutation_id", UUID.class), + required(row, "owner_fence", Long.class), + required(row, "owner_lease_expires_at", java.time.OffsetDateTime.class).toInstant(), + required(row, "original_post_authorization_tuple", byte[].class), + required(row, "account_redemption_projection", byte[].class), + required(row, "initial_selection_request_bytes", byte[].class), + required(row, "initial_selection_request_digest", String.class), + required(row, "initial_selection_response_bytes", byte[].class), + required(row, "initial_selection_response_digest", String.class), + required(row, "descriptor_pin_request_bytes", byte[].class), + required(row, "descriptor_pin_request_digest", String.class), + required(row, "descriptor_pin_response_bytes", byte[].class), + required(row, "descriptor_pin_response_digest", String.class), + required(row, "retained_at", java.time.OffsetDateTime.class).toInstant()); + } + + private static void requireSameCandidate(Candidate expected, StoredPin stored) { + if (!expected.targetNamespace().equals(stored.targetNamespace()) + || !expected.controlPlaneRequestId().equals(stored.controlPlaneRequestId()) + || !expected.canonicalTenantId().equals(stored.canonicalTenantId()) + || !expected.gameInstanceUuid().equals(stored.gameInstanceUuid()) + || !expected.launchDescriptorId().equals(stored.launchDescriptorId()) + || !expected.ownerAttemptId().equals(stored.ownerAttemptId()) + || !expected.ownerMutationId().equals(stored.ownerMutationId()) + || expected.ownerFence() != stored.ownerFence() + || !Arrays.equals(expected.originalTupleBytes(), stored.originalTupleBytes()) + || !Arrays.equals( + expected.accountRedemptionProjection(), stored.accountRedemptionProjection()) + || !Arrays.equals( + expected.initialSelectionRequestBytes(), stored.initialSelectionRequestBytes()) + || !expected.initialSelectionRequestDigest().equals(stored.initialSelectionRequestDigest()) + || !Arrays.equals( + expected.initialSelectionResponseBytes(), stored.initialSelectionResponseBytes()) + || !expected + .initialSelectionResponseDigest() + .equals(stored.initialSelectionResponseDigest()) + || !Arrays.equals(expected.descriptorPinRequestBytes(), stored.descriptorPinRequestBytes()) + || !expected.descriptorPinRequestDigest().equals(stored.descriptorPinRequestDigest()) + || !Arrays.equals( + expected.descriptorPinResponseBytes(), stored.descriptorPinResponseBytes()) + || !expected.descriptorPinResponseDigest().equals(stored.descriptorPinResponseDigest())) { + throw conflict("Original StartSession selection pin conflicts with its first retained bytes"); + } + } + + private static void requireIdentity(String targetNamespace, String requestId) { + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Game Session namespace required"); + } + if (requestId == null || requestId.isBlank() || requestId.length() > 128) { + throw new IllegalArgumentException( + "Canonical original StartSession request identity required"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable caller-owned Game Session transaction required"); + } + } + + private static void requireNoOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Historical selection pin read requires an independent snapshot"); + } + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) throw unavailable(); + return value; + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException(message); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Exact original StartSession selection pin is unavailable"); + } + + private static String digest(byte[] value) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static byte[] copy(byte[] value, String field) { + Objects.requireNonNull(value, field); + if (value.length == 0) throw new IllegalArgumentException(field + " cannot be empty"); + return value.clone(); + } + + /** Exact external request/result bytes from the original Game Design reads. */ + public record Candidate( + HistoricalOriginalStartSessionOwnerEvidence.Result evidence, + UUID ownerMutationId, + byte[] initialSelectionRequestBytes, + byte[] initialSelectionResponseBytes, + byte[] descriptorPinRequestBytes, + byte[] descriptorPinResponseBytes) { + public Candidate { + Objects.requireNonNull(evidence, "complete historical original StartSession evidence"); + Objects.requireNonNull(ownerMutationId, "original owner mutation id"); + initialSelectionRequestBytes = + copy(initialSelectionRequestBytes, "initial selection request"); + initialSelectionResponseBytes = + copy(initialSelectionResponseBytes, "initial selection response"); + descriptorPinRequestBytes = copy(descriptorPinRequestBytes, "descriptor pin request"); + descriptorPinResponseBytes = copy(descriptorPinResponseBytes, "descriptor pin response"); + requireCanonicalWire( + evidence.firstSelection().request(), + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .toRequest(evidence.firstSelection().request()), + initialSelectionRequestBytes, + "initial selection request"); + requireCanonicalWire( + evidence.firstSelection(), + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec + .toResponse(evidence.firstSelection()), + initialSelectionResponseBytes, + "initial selection response"); + var descriptorRequest = evidence.descriptorPin().associationRead().request(); + requireCanonicalWire( + descriptorRequest, + net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec.toRequest( + descriptorRequest), + descriptorPinRequestBytes, + "descriptor pin request"); + requireCanonicalWire( + evidence.descriptorPin(), + net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec.toResponse( + descriptorRequest, + evidence.descriptorPin().associationRead(), + evidence.descriptorPin().outcome()), + descriptorPinResponseBytes, + "descriptor pin response"); + } + + public String targetNamespace() { + return evidence.request().associationSelector().targetNamespace(); + } + + public String controlPlaneRequestId() { + return evidence.originalTuple().controlPlaneRequestId(); + } + + public UUID canonicalTenantId() { + return evidence.request().associationSelector().canonicalTenantId(); + } + + public UUID gameInstanceUuid() { + return evidence.request().associationSelector().gameInstanceUuid(); + } + + public String launchDescriptorId() { + return evidence.request().associationSelector().launchDescriptorId(); + } + + public UUID ownerAttemptId() { + return evidence.ownerAttemptId(); + } + + public UUID ownerMutationId() { + return ownerMutationId; + } + + public long ownerFence() { + return evidence.ownerFence(); + } + + public byte[] originalTupleBytes() { + return evidence.originalTuple().canonicalBytes(); + } + + public byte[] accountRedemptionProjection() { + return evidence.accountRedemptionProjection(); + } + + public String initialSelectionRequestDigest() { + return digest(initialSelectionRequestBytes); + } + + public String initialSelectionResponseDigest() { + return digest(initialSelectionResponseBytes); + } + + public String descriptorPinRequestDigest() { + return digest(descriptorPinRequestBytes); + } + + public String descriptorPinResponseDigest() { + return digest(descriptorPinResponseBytes); + } + + @Override + public byte[] initialSelectionRequestBytes() { + return initialSelectionRequestBytes.clone(); + } + + @Override + public byte[] initialSelectionResponseBytes() { + return initialSelectionResponseBytes.clone(); + } + + @Override + public byte[] descriptorPinRequestBytes() { + return descriptorPinRequestBytes.clone(); + } + + @Override + public byte[] descriptorPinResponseBytes() { + return descriptorPinResponseBytes.clone(); + } + } + + private static void requireCanonicalWire( + Object evidence, com.google.protobuf.Message canonical, byte[] bytes, String field) { + Objects.requireNonNull(evidence, field + " evidence"); + if (!Arrays.equals(canonical.toByteArray(), bytes)) { + throw new IllegalArgumentException( + field + " bytes differ from the closed canonical evidence"); + } + } + + public record StoredPin( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + UUID gameInstanceUuid, + String launchDescriptorId, + UUID ownerAttemptId, + UUID ownerMutationId, + long ownerFence, + Instant ownerLeaseExpiresAt, + byte[] originalTupleBytes, + byte[] accountRedemptionProjection, + byte[] initialSelectionRequestBytes, + String initialSelectionRequestDigest, + byte[] initialSelectionResponseBytes, + String initialSelectionResponseDigest, + byte[] descriptorPinRequestBytes, + String descriptorPinRequestDigest, + byte[] descriptorPinResponseBytes, + String descriptorPinResponseDigest, + Instant retainedAt) { + public StoredPin { + originalTupleBytes = originalTupleBytes.clone(); + accountRedemptionProjection = accountRedemptionProjection.clone(); + initialSelectionRequestBytes = initialSelectionRequestBytes.clone(); + initialSelectionResponseBytes = initialSelectionResponseBytes.clone(); + descriptorPinRequestBytes = descriptorPinRequestBytes.clone(); + descriptorPinResponseBytes = descriptorPinResponseBytes.clone(); + } + + @Override + public byte[] originalTupleBytes() { + return originalTupleBytes.clone(); + } + + @Override + public byte[] accountRedemptionProjection() { + return accountRedemptionProjection.clone(); + } + + @Override + public byte[] initialSelectionRequestBytes() { + return initialSelectionRequestBytes.clone(); + } + + @Override + public byte[] initialSelectionResponseBytes() { + return initialSelectionResponseBytes.clone(); + } + + @Override + public byte[] descriptorPinRequestBytes() { + return descriptorPinRequestBytes.clone(); + } + + @Override + public byte[] descriptorPinResponseBytes() { + return descriptorPinResponseBytes.clone(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java index eee3783edc..ee99047353 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java @@ -218,6 +218,24 @@ public Optional readHistoricalOwnerAttempt( UUID expectedOwnerAttemptId, long expectedOwnerFence) { requireOutsideOwnerTransaction(); + return readHistoricalOwnerAttemptExact(tuple, expectedOwnerAttemptId, expectedOwnerFence); + } + + /** Same immutable historical read for composition inside one owner repeatable-read snapshot. */ + public Optional readHistoricalOwnerAttemptInOwnerTransaction( + StartSessionPostAuthorizationExecutionTuple tuple, + UUID expectedOwnerAttemptId, + long expectedOwnerFence) { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Active Game Session owner snapshot required"); + } + return readHistoricalOwnerAttemptExact(tuple, expectedOwnerAttemptId, expectedOwnerFence); + } + + private Optional readHistoricalOwnerAttemptExact( + StartSessionPostAuthorizationExecutionTuple tuple, + UUID expectedOwnerAttemptId, + long expectedOwnerFence) { Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); requireNonNil(expectedOwnerAttemptId, "expectedOwnerAttemptId"); if (expectedOwnerFence <= 0L) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionOriginalStartSessionSelectionPinService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionOriginalStartSessionSelectionPinService.java new file mode 100644 index 0000000000..d636dbf661 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionOriginalStartSessionSelectionPinService.java @@ -0,0 +1,215 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository.CanonicalInstanceLaunch; +import net.firedevops.firemud.gamesession.repository.GameSessionOriginalStartSessionSelectionPinRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionOriginalStartSessionSelectionPinRepository.Candidate; +import net.firedevops.firemud.gamesession.repository.GameSessionOriginalStartSessionSelectionPinRepository.StoredPin; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Owner-local immutable first-selection retention and historical reconstruction. */ +public final class GameSessionOriginalStartSessionSelectionPinService { + private final GameSessionOriginalStartSessionSelectionPinRepository pins; + private final GameSessionStartSessionOperatorAttemptRepository attempts; + private final GameSessionCanonicalInstanceLaunchRepository launches; + private final String workloadNamespace; + private final TransactionTemplate writeTransaction; + private final TransactionTemplate readTransaction; + + public GameSessionOriginalStartSessionSelectionPinService( + GameSessionOriginalStartSessionSelectionPinRepository pins, + GameSessionStartSessionOperatorAttemptRepository attempts, + GameSessionCanonicalInstanceLaunchRepository launches, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.pins = Objects.requireNonNull(pins, "pins"); + this.attempts = Objects.requireNonNull(attempts, "attempts"); + this.launches = Objects.requireNonNull(launches, "launches"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + writeTransaction = new TransactionTemplate(transactionManager); + writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + readTransaction = new TransactionTemplate(transactionManager); + readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + readTransaction.setReadOnly(true); + readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + } + + /** + * Stores exact first-read bytes after all remote reads have completed. The owner repository then + * locks and revalidates the same pending Account-attached attempt and its original live lease. + */ + public StoredPin retainFirst(Candidate candidate) { + Objects.requireNonNull(candidate, "candidate"); + requireConfiguredOwner(candidate.targetNamespace()); + HistoricalOriginalStartSessionOwnerEvidence.Result evidence = candidate.evidence(); + var selector = evidence.request().associationSelector(); + var launch = + launches + .readByOriginalTuple(selector, evidence.originalTuple().canonicalBytes()) + .orElseThrow( + () -> + new IllegalStateException("Exact original Game Session launch is unavailable")); + requireLaunchMatches(evidence.launchAssociation(), launch); + StoredPin retained = + writeTransaction.execute(status -> pins.retainFirstInOwnerTransaction(candidate)); + return Objects.requireNonNull(retained, "Game Session selection-pin write returned no row"); + } + + /** Reconstructs only an already-retained pin and its exact V35/V26 owner correlations. */ + public Optional readHistorical( + HistoricalOriginalStartSessionOwnerEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireConfiguredOwner(request.associationSelector().targetNamespace()); + return Objects.requireNonNull( + readTransaction.execute(status -> readHistoricalInSnapshot(request)), + "Game Session historical selection read returned no optional"); + } + + private Optional readHistoricalInSnapshot( + HistoricalOriginalStartSessionOwnerEvidence.Request request) { + var selector = request.associationSelector(); + Optional stored = + pins.readByOriginalOperationInOwnerTransaction( + selector.targetNamespace(), selector.controlPlaneRequestId()); + if (stored.isEmpty()) return Optional.empty(); + StoredPin pin = stored.orElseThrow(); + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode(pin.originalTupleBytes()); + var attempt = + attempts + .readHistoricalOwnerAttemptInOwnerTransaction( + tuple, request.expectedOwnerAttemptId(), request.expectedOwnerFence()) + .orElseThrow( + () -> + new IllegalStateException( + "Exact original Game Session owner attempt is unavailable")); + if (!attempt.ownerMutationId().equals(pin.ownerMutationId()) + || !attempt.ownerAttemptId().equals(pin.ownerAttemptId()) + || attempt.ownerFence() != pin.ownerFence() + || !Arrays.equals(attempt.postAuthorizationExecutionTuple(), pin.originalTupleBytes()) + || !Arrays.equals( + attempt.accountRedemptionProjection(), pin.accountRedemptionProjection())) { + throw new IllegalStateException( + "Historical pin differs from the exact retained owner attempt"); + } + var launchAssociation = + launches + .readHistoricalAssociationInOwnerTransaction(selector, pin.originalTupleBytes()) + .orElseThrow( + () -> + new IllegalStateException("Exact original Game Session launch is unavailable")); + if (!pin.targetNamespace().equals(selector.targetNamespace()) + || !pin.controlPlaneRequestId().equals(selector.controlPlaneRequestId()) + || !pin.canonicalTenantId().equals(selector.canonicalTenantId()) + || !pin.gameInstanceUuid().equals(selector.gameInstanceUuid()) + || !pin.launchDescriptorId().equals(selector.launchDescriptorId()) + || !pin.ownerAttemptId().equals(request.expectedOwnerAttemptId()) + || pin.ownerFence() != request.expectedOwnerFence()) { + throw new IllegalStateException( + "Historical pin differs from the complete requested selector"); + } + + var initialRequest = parseAssociationRequest(pin.initialSelectionRequestBytes()); + var initialEvidence = + StartSessionTemplateAssociationReadGrpcCodec.fromResponse( + StartSessionTemplateAssociationReadGrpcCodec.fromRequest(initialRequest), + parseAssociationResponse(pin.initialSelectionResponseBytes())); + var descriptorRequest = + StartSessionLaunchDescriptorGrpcCodec.fromRequest( + parseAssociationRequest(pin.descriptorPinRequestBytes())); + var descriptorPin = + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + descriptorRequest, parseDescriptorResponse(pin.descriptorPinResponseBytes())); + return Optional.of( + new HistoricalOriginalStartSessionOwnerEvidence.Result( + request, + tuple, + attempt.ownerAttemptId(), + attempt.ownerFence(), + attempt.accountRedemptionProjection(), + initialEvidence, + descriptorPin, + launchAssociation, + pin.initialSelectionRequestDigest(), + pin.initialSelectionResponseDigest(), + pin.descriptorPinRequestDigest(), + pin.descriptorPinResponseDigest())); + } + + private void requireConfiguredOwner(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Historical selector differs from configured Game Session owner"); + } + } + + private static void requireLaunchMatches( + HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation expected, + CanonicalInstanceLaunch actual) { + if (!expected.targetNamespace().equals(actual.targetNamespace()) + || !expected.canonicalTenantId().equals(actual.canonicalTenantId()) + || !expected.worldSlug().equals(actual.canonicalRealmCatalog().worldSlug()) + || !expected.gameInstanceUuid().equals(actual.gameInstanceUuid()) + || !expected.controlPlaneRequestId().equals(actual.controlPlaneRequestId()) + || !expected + .launchDescriptorId() + .equals(actual.launchBindingEvidence().descriptor().launchDescriptorId()) + || !expected.playableStateNamespaceId().equals(actual.playableStateNamespaceId()) + || expected.playableStateScope() != actual.playableStateScope() + || expected.publicProduction() != actual.publicProduction() + || expected.capturedStartingRowVersion() != actual.capturedStartingRowVersion() + || !expected.launchBindingEvidence().equals(actual.launchBindingEvidence())) { + throw new IllegalStateException( + "First selection pin differs from its exact retained Game Session launch"); + } + } + + private static net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest + parseAssociationRequest(byte[] bytes) { + try { + return net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest + .parseFrom(bytes); + } catch (InvalidProtocolBufferException malformed) { + throw new IllegalStateException( + "Retained StartSession selection request is malformed", malformed); + } + } + + private static net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse + parseAssociationResponse(byte[] bytes) { + try { + return net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationResponse + .parseFrom(bytes); + } catch (InvalidProtocolBufferException malformed) { + throw new IllegalStateException( + "Retained StartSession selection response is malformed", malformed); + } + } + + private static net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse + parseDescriptorResponse(byte[] bytes) { + try { + return net.firedevops.firemud.gamedesign.v1.ResolveStartSessionLaunchDescriptorResponse + .parseFrom(bytes); + } catch (InvalidProtocolBufferException malformed) { + throw new IllegalStateException( + "Retained StartSession descriptor response is malformed", malformed); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java new file mode 100644 index 0000000000..1c8913ac6c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java @@ -0,0 +1,136 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceRequest; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceResponse; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Deliberately unregistered same-namespace World-only historical owner evidence reader. */ +public final class HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService + extends HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc + .HistoricalOriginalStartSessionOwnerEvidenceReadServiceImplBase { + private static final String METHOD_NAME = + "game_session.v1.HistoricalOriginalStartSessionOwnerEvidenceReadService/" + + "ReadHistoricalOriginalStartSessionOwnerEvidence"; + private static final String WORLD_SERVICE = "world-management-service"; + + private final GameSessionOriginalStartSessionSelectionPinService service; + private final String workloadNamespace; + + public HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService( + GameSessionOriginalStartSessionSelectionPinService service, String workloadNamespace) { + this.service = Objects.requireNonNull(service, "service"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void readHistoricalOriginalStartSessionOwnerEvidence( + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "observer"); + try { + requireWorldManagementWorkload(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + if (request == null) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Complete historical original StartSession selector required") + .asRuntimeException()); + return; + } + final net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence + .Request + decoded; + try { + decoded = HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Complete canonical historical StartSession selector required") + .asRuntimeException()); + return; + } + if (!workloadNamespace.equals(decoded.associationSelector().targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Historical selector differs from configured Game Session owner") + .asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Independent Game Session historical snapshot required") + .asRuntimeException()); + return; + } + try { + var result = service.readHistorical(decoded); + if (result.isEmpty()) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact retained historical StartSession pin is unavailable") + .asRuntimeException()); + return; + } + var evidence = result.orElseThrow(); + if (!decoded.equals(evidence.request())) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Historical owner evidence differs from the complete selector") + .asRuntimeException()); + return; + } + observer.onNext(HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toResponse(evidence)); + observer.onCompleted(); + } catch (DataAccessException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Game Session historical owner storage unavailable") + .asRuntimeException()); + } catch (IllegalArgumentException | IllegalStateException incompleteOrConflicting) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Complete exact historical StartSession evidence is unavailable") + .asRuntimeException()); + } + } + + private void requireWorldManagementWorkload() { + var peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !METHOD_NAME.equals( + HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc + .getReadHistoricalOriginalStartSessionOwnerEvidenceMethod() + .getFullMethodName()) + || peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified same-namespace World Management workload required") + .asRuntimeException(); + } + if (!WORLD_SERVICE.equals(peer.service()) + || !workloadNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/" + WORLD_SERVICE).equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED + .withDescription( + "Exact same-namespace World Management workload without end-user context required") + .asRuntimeException(); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V46__original_start_session_selection_pin.sql b/services/game-session-service/src/main/resources/db/migration/V46__original_start_session_selection_pin.sql new file mode 100644 index 0000000000..51eb497875 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V46__original_start_session_selection_pin.sql @@ -0,0 +1,135 @@ +-- Retain the exact first Game Design selection and descriptor pin for one original StartSession. +-- This is immutable historical evidence; it creates no claim, launch, or runtime authority. +CREATE TABLE game_session_original_start_session_selection_pin ( + target_namespace VARCHAR(63) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + canonical_tenant_id UUID NOT NULL, + game_instance_uuid UUID NOT NULL, + launch_descriptor_id VARCHAR(128) NOT NULL, + owner_attempt_id UUID NOT NULL, + owner_mutation_id UUID NOT NULL, + owner_fence BIGINT NOT NULL, + owner_lease_expires_at TIMESTAMPTZ NOT NULL, + original_post_authorization_tuple BYTEA NOT NULL, + account_redemption_projection BYTEA NOT NULL, + initial_selection_request_bytes BYTEA NOT NULL, + initial_selection_request_digest VARCHAR(71) NOT NULL, + initial_selection_response_bytes BYTEA NOT NULL, + initial_selection_response_digest VARCHAR(71) NOT NULL, + descriptor_pin_request_bytes BYTEA NOT NULL, + descriptor_pin_request_digest VARCHAR(71) NOT NULL, + descriptor_pin_response_bytes BYTEA NOT NULL, + descriptor_pin_response_digest VARCHAR(71) NOT NULL, + retained_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT pk_gs_original_start_session_selection_pin + PRIMARY KEY (target_namespace, control_plane_request_id), + CONSTRAINT uq_gs_original_start_session_selection_pin_attempt UNIQUE (owner_attempt_id), + CONSTRAINT fk_gs_original_start_session_selection_pin_launch + FOREIGN KEY (target_namespace, control_plane_request_id) + REFERENCES game_session_canonical_instance_launch + (target_namespace, control_plane_request_id) ON DELETE RESTRICT, + CONSTRAINT ck_gs_original_start_session_selection_pin_identity CHECK ( + target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND control_plane_request_id !~ '^[[:space:]]*$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND launch_descriptor_id !~ '^[[:space:]]*$' + AND owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND owner_fence > 0), + CONSTRAINT ck_gs_original_start_session_selection_pin_bytes CHECK ( + octet_length(original_post_authorization_tuple) BETWEEN 1 AND 262144 + AND octet_length(account_redemption_projection) BETWEEN 1 AND 262144 + AND octet_length(initial_selection_request_bytes) BETWEEN 1 AND 524288 + AND octet_length(initial_selection_response_bytes) BETWEEN 1 AND 8388608 + AND octet_length(descriptor_pin_request_bytes) BETWEEN 1 AND 524288 + AND octet_length(descriptor_pin_response_bytes) BETWEEN 1 AND 8388608 + AND initial_selection_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND initial_selection_request_digest = + 'sha256:' || encode(sha256(initial_selection_request_bytes), 'hex') + AND initial_selection_response_digest ~ '^sha256:[0-9a-f]{64}$' + AND initial_selection_response_digest = + 'sha256:' || encode(sha256(initial_selection_response_bytes), 'hex') + AND descriptor_pin_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_pin_request_digest = + 'sha256:' || encode(sha256(descriptor_pin_request_bytes), 'hex') + AND descriptor_pin_response_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_pin_response_digest = + 'sha256:' || encode(sha256(descriptor_pin_response_bytes), 'hex')) +); + +-- V35 is hidden from jOOQ's DDL simulator; preserve the PostgreSQL relation while excluding +-- only this cross-relation constraint from simulation, as in V45. +-- [jooq ignore start] +ALTER TABLE game_session_original_start_session_selection_pin + ADD CONSTRAINT fk_gs_original_start_session_selection_pin_attempt + FOREIGN KEY (target_namespace, control_plane_request_id) + REFERENCES game_session_start_session_operator_attempt + (target_namespace, control_plane_request_id) ON DELETE RESTRICT; +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE FUNCTION guard_gs_original_start_session_selection_pin() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE launch game_session_canonical_instance_launch%ROWTYPE; + attempt game_session_start_session_operator_attempt%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Game Session original selection pin is immutable and append-only' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO STRICT launch + FROM game_session_canonical_instance_launch + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = NEW.control_plane_request_id; + SELECT * INTO STRICT attempt + FROM game_session_start_session_operator_attempt + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = NEW.control_plane_request_id; + + IF launch.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR launch.game_instance_uuid IS DISTINCT FROM NEW.game_instance_uuid + OR launch.original_start_session_tuple IS DISTINCT FROM + NEW.original_post_authorization_tuple + OR launch.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR attempt.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR attempt.owner_attempt_id IS DISTINCT FROM NEW.owner_attempt_id + OR attempt.owner_mutation_id IS DISTINCT FROM NEW.owner_mutation_id + OR attempt.owner_fence IS DISTINCT FROM NEW.owner_fence + OR attempt.post_authorization_execution_tuple IS DISTINCT FROM + NEW.original_post_authorization_tuple + OR attempt.account_redemption_projection IS DISTINCT FROM + NEW.account_redemption_projection + OR attempt.phase_state IS DISTINCT FROM 'OWNER_EXECUTION_PENDING' + OR attempt.lease_expires_at IS DISTINCT FROM NEW.owner_lease_expires_at + OR attempt.lease_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION 'Selection pin differs from exact live launch or original owner attempt' + USING ERRCODE = '23514', + CONSTRAINT = 'ck_gs_original_start_session_selection_pin_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_original_start_session_selection_pin_guard + BEFORE INSERT OR UPDATE OR DELETE + ON game_session_original_start_session_selection_pin + FOR EACH ROW EXECUTE FUNCTION guard_gs_original_start_session_selection_pin(); + +CREATE FUNCTION reject_gs_original_start_session_selection_pin_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session original selection pin cannot be truncated' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER game_session_original_start_session_selection_pin_no_truncate + BEFORE TRUNCATE ON game_session_original_start_session_selection_pin + FOR EACH STATEMENT EXECUTE FUNCTION reject_gs_original_start_session_selection_pin_truncate(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java index 9917450052..2a46e362dd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; @@ -40,6 +41,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -148,6 +150,274 @@ void retainsExactEmptyOwnerResultAndRejectsConflictOrMutation() throws Exception } } + @Test + void originalSelectionPinIsAppendOnlyAndBoundToTheExactLiveAttemptAndLaunch() throws Exception { + try (Fixture fixture = newFixture()) { + LaunchInputs launch = fixture.createLaunch(); + AttemptInputs attempt = fixture.createAttempt(launch.proof().originalTuple()); + var tuple = launch.proof().originalTuple(); + byte[] selectionRequest = new byte[] {1}; + byte[] selectionResponse = new byte[] {2}; + byte[] descriptorRequest = new byte[] {3}; + byte[] descriptorResponse = new byte[] {4}; + String operationId = tuple.controlPlaneRequestId(); + var owner = attempt.snapshot(); + var attemptRepository = + new GameSessionStartSessionOperatorAttemptRepository( + fixture.dsl(), Duration.ofMinutes(5)); + assertThatThrownBy( + () -> + attemptRepository.readHistoricalOwnerAttempt( + tuple, UUID.randomUUID(), owner.ownerFence())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + attemptRepository.readHistoricalOwnerAttempt( + tuple, owner.ownerAttemptId(), owner.ownerFence() + 1)) + .isInstanceOf(IllegalStateException.class); + var launchRepository = + new GameSessionCanonicalInstanceLaunchRepository( + fixture.dsl(), + fixture.transactionManager(), + NAMESPACE, + new GameSessionCanonicalRealmCatalogRepository( + fixture.dsl(), fixture.transactionManager(), NAMESPACE)); + var exactSelector = historicalSelector(launch); + var mismatchedSelector = + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + exactSelector.targetNamespace(), + exactSelector.canonicalTenantId(), + "other-world", + exactSelector.gameInstanceUuid(), + exactSelector.controlPlaneRequestId(), + exactSelector.launchDescriptorId(), + exactSelector.expectedDescriptorRequestDigest(), + exactSelector.expectedDescriptorResultDigest(), + exactSelector.expectedReleaseAttestationEvidenceDigest()); + TransactionTemplate readSnapshot = new TransactionTemplate(fixture.transactionManager()); + readSnapshot.setReadOnly(true); + readSnapshot.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThatThrownBy( + () -> + readSnapshot.execute( + status -> + launchRepository.readHistoricalAssociationInOwnerTransaction( + mismatchedSelector, tuple.canonicalBytes()))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + insertSelectionPin( + fixture, + launch, + attempt, + UUID.randomUUID(), + selectionRequest, + selectionResponse, + descriptorRequest, + descriptorResponse)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + insertSelectionPin( + fixture, + launch, + attempt, + launch.catalog().canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + owner.ownerFence(), + selectionRequest, + selectionResponse, + descriptorRequest, + descriptorResponse)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + insertSelectionPin( + fixture, + launch, + attempt, + launch.catalog().canonicalTenantId(), + owner.ownerAttemptId(), + owner.ownerMutationId(), + owner.ownerFence() + 1, + selectionRequest, + selectionResponse, + descriptorRequest, + descriptorResponse)) + .isInstanceOf(RuntimeException.class); + insertSelectionPin( + fixture, + launch, + attempt, + launch.catalog().canonicalTenantId(), + selectionRequest, + selectionResponse, + descriptorRequest, + descriptorResponse); + + var retained = + fixture + .dsl() + .fetchOne( + "SELECT initial_selection_request_bytes, descriptor_pin_response_bytes" + + " FROM game_session_original_start_session_selection_pin" + + " WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + operationId); + assertThat(retained.get("initial_selection_request_bytes", byte[].class)) + .containsExactly(selectionRequest); + assertThat(retained.get("descriptor_pin_response_bytes", byte[].class)) + .containsExactly(descriptorResponse); + String where = + " WHERE target_namespace = '" + + NAMESPACE + + "' AND control_plane_request_id = '" + + operationId + + "'"; + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "UPDATE game_session_original_start_session_selection_pin" + + " SET initial_selection_response_digest = 'sha256:' || repeat('0', 64)" + + where)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute( + "DELETE FROM game_session_original_start_session_selection_pin" + where)) + .isInstanceOf(RuntimeException.class); + assertThatThrownBy( + () -> + fixture + .dsl() + .execute("TRUNCATE game_session_original_start_session_selection_pin")) + .isInstanceOf(RuntimeException.class); + } + + try (Fixture fixture = newFixture()) { + LaunchInputs launch = fixture.createLaunch(); + AttemptInputs expiringAttempt = + fixture.createAttempt(launch.proof().originalTuple(), Duration.ofSeconds(2)); + Thread.sleep(Duration.ofMillis(2200).toMillis()); + assertThatThrownBy( + () -> + insertSelectionPin( + fixture, + launch, + expiringAttempt, + launch.catalog().canonicalTenantId(), + new byte[] {11}, + new byte[] {12}, + new byte[] {13}, + new byte[] {14})) + .isInstanceOf(RuntimeException.class); + var retainedCount = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT count(*) AS retained FROM game_session_original_start_session_selection_pin"), + "expired-attempt selection-pin count query returned no row"); + assertThat(retainedCount.get("retained", Long.class)).isZero(); + } + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request historicalSelector( + LaunchInputs launch) { + var tuple = launch.proof().originalTuple(); + var descriptor = launch.proof().completeLaunchBindingEvidence().descriptor(); + var release = launch.proof().completeLaunchBindingEvidence().releaseAttestation(); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + NAMESPACE, + launch.catalog().canonicalTenantId(), + launch.catalog().worldSlug(), + launch.gameInstanceUuid(), + tuple.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + } + + private static void insertSelectionPin( + Fixture fixture, + LaunchInputs launch, + AttemptInputs attempt, + UUID canonicalTenantId, + byte[] selectionRequest, + byte[] selectionResponse, + byte[] descriptorRequest, + byte[] descriptorResponse) { + var owner = attempt.snapshot(); + insertSelectionPin( + fixture, + launch, + attempt, + canonicalTenantId, + owner.ownerAttemptId(), + owner.ownerMutationId(), + owner.ownerFence(), + selectionRequest, + selectionResponse, + descriptorRequest, + descriptorResponse); + } + + private static void insertSelectionPin( + Fixture fixture, + LaunchInputs launch, + AttemptInputs attempt, + UUID canonicalTenantId, + UUID ownerAttemptId, + UUID ownerMutationId, + long ownerFence, + byte[] selectionRequest, + byte[] selectionResponse, + byte[] descriptorRequest, + byte[] descriptorResponse) { + var tuple = launch.proof().originalTuple(); + var owner = attempt.snapshot(); + fixture + .dsl() + .execute( + "INSERT INTO game_session_original_start_session_selection_pin" + + " (target_namespace, control_plane_request_id, canonical_tenant_id," + + " game_instance_uuid, launch_descriptor_id, owner_attempt_id, owner_mutation_id," + + " owner_fence, owner_lease_expires_at, original_post_authorization_tuple," + + " account_redemption_projection, initial_selection_request_bytes," + + " initial_selection_request_digest, initial_selection_response_bytes," + + " initial_selection_response_digest, descriptor_pin_request_bytes," + + " descriptor_pin_request_digest, descriptor_pin_response_bytes," + + " descriptor_pin_response_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + NAMESPACE, + tuple.controlPlaneRequestId(), + canonicalTenantId, + launch.gameInstanceUuid(), + launch.proof().completeLaunchBindingEvidence().descriptor().launchDescriptorId(), + ownerAttemptId, + ownerMutationId, + ownerFence, + java.time.OffsetDateTime.ofInstant(owner.leaseExpiresAt(), java.time.ZoneOffset.UTC), + tuple.canonicalBytes(), + owner.accountRedemptionProjection(), + selectionRequest, + sha256(selectionRequest), + selectionResponse, + sha256(selectionResponse), + descriptorRequest, + sha256(descriptorRequest), + descriptorResponse, + sha256(descriptorResponse)); + } + private static Candidate candidate( LaunchInputs launch, AttemptInputs attempt, byte[] requestBytes, byte[] sourceBytes) { var tuple = launch.proof().originalTuple(); @@ -360,8 +630,13 @@ LaunchInputs createLaunch() { AttemptInputs createAttempt( net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple tuple) { - var repository = - new GameSessionStartSessionOperatorAttemptRepository(dsl, Duration.ofMinutes(5)); + return createAttempt(tuple, Duration.ofMinutes(5)); + } + + AttemptInputs createAttempt( + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple tuple, + Duration leaseDuration) { + var repository = new GameSessionStartSessionOperatorAttemptRepository(dsl, leaseDuration); var claim = Objects.requireNonNull( transactions().execute(status -> repository.reserve(tuple)), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionOriginalStartSessionSelectionPinServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionOriginalStartSessionSelectionPinServiceTest.java new file mode 100644 index 0000000000..2d542ba55d --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionOriginalStartSessionSelectionPinServiceTest.java @@ -0,0 +1,140 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionOriginalStartSessionSelectionPinRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.service.impl.GameSessionOriginalStartSessionSelectionPinService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.DefaultTransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionOriginalStartSessionSelectionPinServiceTest { + private static final String NAMESPACE = "gameplay"; + private final GameSessionOriginalStartSessionSelectionPinRepository pins = + mock(GameSessionOriginalStartSessionSelectionPinRepository.class); + private final GameSessionStartSessionOperatorAttemptRepository attempts = + mock(GameSessionStartSessionOperatorAttemptRepository.class); + private final GameSessionCanonicalInstanceLaunchRepository launches = + mock(GameSessionCanonicalInstanceLaunchRepository.class); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void missingPinIsNotReconstructedAndLookupUsesOneReadOnlyRepeatableReadSnapshot() { + var txManager = new ObservingTransactionManager(); + var selector = selector(NAMESPACE); + var request = + new HistoricalOriginalStartSessionOwnerEvidence.Request(selector, UUID.randomUUID(), 7); + when(pins.readByOriginalOperationInOwnerTransaction( + NAMESPACE, selector.controlPlaneRequestId())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + return Optional.empty(); + }); + var service = + new GameSessionOriginalStartSessionSelectionPinService( + pins, attempts, launches, txManager, NAMESPACE); + + assertThat(service.readHistorical(request)).isEmpty(); + assertThat(txManager.lastReadOnly).isTrue(); + assertThat(txManager.lastIsolation).isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + verify(pins) + .readByOriginalOperationInOwnerTransaction(NAMESPACE, selector.controlPlaneRequestId()); + verifyNoInteractions(attempts, launches); + } + + @Test + void crossNamespaceRequestCannotReachThePinOrOwnerReaders() { + var txManager = new ObservingTransactionManager(); + var selector = selector("other"); + var service = + new GameSessionOriginalStartSessionSelectionPinService( + pins, attempts, launches, txManager, NAMESPACE); + + assertThatThrownBy( + () -> + service.readHistorical( + new HistoricalOriginalStartSessionOwnerEvidence.Request( + selector, UUID.randomUUID(), 7))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured Game Session owner"); + verifyNoInteractions(pins, attempts, launches); + assertThat(txManager.lastIsolation).isZero(); + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector( + String namespace) { + return new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + namespace, + UUID.randomUUID(), + "test-world", + UUID.randomUUID(), + "original-operation", + "descriptor", + "sha256:" + "1".repeat(64), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + } + + private static final class ObservingTransactionManager implements PlatformTransactionManager { + private boolean lastReadOnly; + private int lastIsolation; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + TransactionDefinition effectiveDefinition = + definition == null ? new DefaultTransactionDefinition() : definition; + lastReadOnly = effectiveDefinition.isReadOnly(); + lastIsolation = effectiveDefinition.getIsolationLevel(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(lastReadOnly); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(lastIsolation); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + clear(); + } + + @Override + public void rollback(TransactionStatus status) { + clear(); + } + + private static void clear() { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java new file mode 100644 index 0000000000..c82f1801cd --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java @@ -0,0 +1,106 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.ArrayList; +import java.util.List; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.service.impl.GameSessionOriginalStartSessionSelectionPinService; +import net.firedevops.firemud.gamesession.service.impl.HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceRequest; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest { + private static final String NAMESPACE = "gameplay"; + private final GameSessionOriginalStartSessionSelectionPinService service = + mock(GameSessionOriginalStartSessionSelectionPinService.class); + private final HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService receiver = + new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService(service, NAMESPACE); + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void onlyExactSameNamespaceWorldWorkloadMayReachRequestDecoding() { + for (String uri : + List.of( + "spiffe://firemud/ns/gameplay/sa/account-service", + "spiffe://firemud/ns/other/sa/world-management-service", + "spiffe://firemud/ns/gameplay/sa/game-session-service")) { + RecordingObserver observer = invoke(uri, false); + assertThat(observer.status()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + RecordingObserver missingPeer = invoke(null, false); + assertThat(missingPeer.status()).isEqualTo(Status.Code.UNAUTHENTICATED); + RecordingObserver endUserContext = + invoke("spiffe://firemud/ns/gameplay/sa/world-management-service", true); + assertThat(endUserContext.status()).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(service); + } + + @Test + void authenticatedWorldPeerIsStillRequiredToSendTheClosedCanonicalRequest() { + RecordingObserver observer = + invoke("spiffe://firemud/ns/gameplay/sa/world-management-service", false); + assertThat(observer.status()).isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(service); + } + + private RecordingObserver invoke(String uri, boolean endUserContext) { + RecordingObserver observer = new RecordingObserver(); + Runnable call = + () -> + receiver.readHistoricalOriginalStartSessionOwnerEvidence( + ReadHistoricalOriginalStartSessionOwnerEvidenceRequest.getDefaultInstance(), + observer); + if (uri == null) { + call.run(); + return observer; + } + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(uri).orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> { + if (endUserContext) { + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + } + call.run(); + }); + return observer; + } + + private static final class RecordingObserver + implements StreamObserver { + private final List responses = + new ArrayList<>(); + private Status.Code errorCode; + + @Override + public void onNext(ReadHistoricalOriginalStartSessionOwnerEvidenceResponse response) { + responses.add(response); + } + + @Override + public void onError(Throwable throwable) { + errorCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() {} + + Status.Code status() { + return errorCode; + } + } +} From cfdb697f6ffd0f110f81cb76e2657badc1dc0df7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:51:48 +1300 Subject: [PATCH 113/129] Compose original World participation settlement through authenticated Account transport --- .../account-service/api-contracts.md | 4 + .../account-service/runtime-and-data.md | 2 + ...ame-authoring-publishing-and-activation.md | 6 +- ...ssion_world_participation_settlement.proto | 36 ++ ...rldParticipationSettlementGrpcService.java | 107 +++++ ...ldParticipationSettlementGrpcMtlsTest.java | 275 ++++++++++++ ...articipationSettlementGrpcServiceTest.java | 165 +++++++ ...StartSessionAuthorizationProofFixture.java | 7 + ...ionWorldParticipationSettlementClient.java | 9 + ...nWorldParticipationSettlementEvidence.java | 33 ++ ...WorldParticipationSettlementGrpcCodec.java | 267 ++++++++++++ ...sionWorldParticipationSettlementInput.java | 32 ++ ...ionWorldParticipationSettlementClient.java | 171 ++++++++ ...dParticipationSettlementGrpcCodecTest.java | 410 ++++++++++++++++++ ...orldParticipationSettlementClientTest.java | 104 +++++ ...licationExportPostgresIntegrationTest.java | 78 ++-- 16 files changed, 1676 insertions(+), 30 deletions(-) create mode 100644 protos/account/v1/start_session_world_participation_settlement.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementInput.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClient.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClientTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 44774269a5..727f4752db 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -221,6 +221,10 @@ Fresh World participation acquisition first obtains the [Game Session current-or The standalone, unregistered [World participation acquisition RPC](../../../../protos/account/v1/start_session_world_participation_acquisition.proto) carries schema version 1, an independent correlation UUID, the exact workload namespace, the complete canonical original post-authorization tuple, actual Game Session mutation/attempt/fence, canonical game-instance UUID, and exact bounded World preparation JSON and digest. The exact configured same-namespace World workload is authenticated before parsing; end-user context and ambient SQL are denied. World does not supply an Account participation ID/fence, redemption projection, lease, or substitute authority assertion. Account resolves and retains those values through its existing acquisition owner. The reply echoes the complete request and carries the Account-assigned participation ID/fence and complete first retained Game Session observation, using the existing observation codec rather than a projection hash. A new correlation on an exact operation retry does not replace that first observation or allocate another participation. The client authenticates Account and exact-compares the request, original tuple, Game Session owner binding and full redemption projection. Transport integrity and a retained observation do not establish a continuously held Game Session claim, World commit permission, or activation; producer and composed physical proof remain gated. +The standalone, unregistered `SettleOriginalStartSessionWorldParticipation` transport uses the existing World-participation settlement owner, not a caller-provided outcome. Its closed schema-version-1 request contains the exact target namespace, an independent settlement correlation UUID, and the original Account participation ID and positive fence. The receiver authenticates the exact configured same-namespace World workload and rejects end-user context before parsing; ambient SQL is denied. Every protobuf member occurs exactly once; unknown, duplicate, oversized and noncanonical values are rejected. UUIDs are canonical non-nil strings and the fence is canonical positive decimal text bounded by Account's signed-long counter. + +Account independently resolves its complete retained participation, obtains authenticated exact World terminal evidence outside SQL, serializes settlement with the original source protection, and performs lookup-only durable readback. The reply echoes the request correlation and participation ID/fence and includes the complete canonical `world-start-session-execution-terminal/v1` bytes and the original Account settlement timestamp as a UTC instant with exactly six fractional digits. The consumer authenticates Account, validates the full terminal and exact namespace/participation binding, and rejects a substituted correlation, fence or outcome. A new correlation on an exact retry returns the same committed terminal and timestamp; it cannot allocate another participation or change the settlement. Missing or `PENDING` owner evidence remains unresolved and protected; expiry, timeout and absence cannot settle. This historical transport creates no fresh execution, activation or admission permission and remains unregistered pending the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status)'s producer/consumer and physical proof gates. + The credential-free `ReadRedeemedOperationProjection` receiver accepts the exact configured same-namespace Game Design peer and the exact original Game Session redeemer under [ADR 0047's restricted original-operation read](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). Before returning the retained projection, Account compares the original request/reservation and redeemed workload/attempt/fence, then revalidates the original actor/JTI, current source and reference expiry. The response contains no credential or renewed permission. Game Session must separately prove its original claim and immutable pin under the owner-local checks required by that contract; this Account read is not World participation or admission. The distinct original-admission producer and independent readback implement [ADR 0047's admission source protection](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#original-startsession-admission-source-protection), not the World receiving lifecycle above. The standalone acquisition RPC carries only the complete canonical original post-authorization tuple, the Game Session mutation/attempt/fence, and the complete canonical World hold identity, in addition to its schema version and target namespace; it never accepts a projection, lease expiry, or Account participation coordinates from Game Session. Account resolves the real retained participation ID/fence from its existing historical row within the fresh currentness callback. The retained closed RFC 8785 `account-start-session-admission-protection-request/v1` object continues to have exactly `schema`, `originalPostAuthorizationTupleBytesBase64`, `accountRedemptionProjectionBytesBase64`, `gameSessionOwnerMutationId`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `originalLeaseExpiresAt`, `accountWorldParticipationId`, `accountWorldParticipationFence`, and `worldAdmissionHoldIdentityBytesBase64`. UUIDs are canonical non-nil strings; positive fences are canonical decimal strings bounded by the owner counter type; expiry is the unchanged UTC lease with exactly six fractional digits, retaining PostgreSQL microsecond precision. Base64 members carry exact canonical complete original values, not hashes or caller-selected projections. The complete World hold binds its separate admission request/digest, precondition and canonical target. Unknown, duplicate, trailing, noncanonical, substituted or oversized data is rejected. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fb802423f9..adfb502ae9 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The unregistered original-World participation settlement receiver and file-backed World client use the existing Account settlement owner and immutable receipt storage. The request selects only the original participation; Account reads the exact World terminal independently and returns the complete retained terminal and settlement time. The genuine-release fixture now defines this native World-to-Account call instead of supplying a local test peer. This is construction, not executed PostgreSQL composition or runtime activation; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records proof and remaining gates. The [Account API contract](./api-contracts.md#operator-authorization-references) owns the closed transport and retry rules. + Account V40 adds owner-proven sequence-zero source baselines to the inherited V30–V39 authority-storage and retention-safety foundation. New repository-created Accounts and a genuinely new issuer receive these baselines; retained rows are not backfilled. Exact security-relevant Account updates compose source generation, issuance fence, canonical event, and current readback in their owner transaction. The owner-local first-JOIN producer/coordinator retains membership, pair/event, audit, and terminal-operation evidence. These persistence primitives do not provide public JOIN, target-currentness protection, or runtime wiring. Reconciled V40/source-currentness/coordinator proof remains pending; see the [Player Access and Session implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). Hard deletion remains denied, revoked grants remain tombstones, and this stage does not enable signer provisioning, LOGIN, PLAY, or activation. Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of the current Account/profile-local and legacy tenant exports expose that persisted UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and new registration audit payloads use the same UUID. Profile and tenant DTO identifiers, authentication results, JWT subjects, and downstream consumers remain unchanged; the current export is still partial Account/profile-local data, not the canonical portable export. The Account-local UUID-to-row resolver also remains confined to Account. The closed consumer boundary is incomplete: shared `SessionContext.currentAccountIdOrNull()` still requires numeric claims and is used by `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, and Social & Groups current-account authorization; Game Session control-plane owner authorization also compares numeric owner IDs. These consumers are outside this Account-owned slice, so no UUID-authentication or downstream-consumer proof is claimed. Focused repository and retained-row migration integration cases are present, but local PostgreSQL execution is unavailable while Docker is disabled; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index b15f6aeee7..b1d63684e5 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 @@ -6,9 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The genuine-release definition now obtains the first Game Design selection and exact-replay descriptor through file-backed Game Session mTLS, retains their unchanged request/result bytes through the additive Game Session V46 owner, and independently reads the historical pin through the exact World workload. That unregistered producer reconstructs the immutable pin, original Account-attached attempt and launch in one repeatable-read owner snapshot; missing history is not repaired from current reads or mutable runtime status. The definition also composes World's original-operation recovery with native World-to-Account and World-to-Game Session reads, and Account's exact terminal settlement with native Account-to-World readback. Account source protection must remain pending after World `COMMITTED` until the original participation ID/fence is durably settled and independently read back. The unregistered settlement owner's local invocation still supplies a test peer context; its remote terminal evidence uses the actual authenticated World client. These definitions retain the original tuple and finite lease and do not enable a runtime path. Neither compiled definitions nor synthetic storage/transport cases prove the complete genuine handoff. +The genuine-release definition now obtains the first Game Design selection and exact-replay descriptor through file-backed Game Session mTLS, retains their unchanged request/result bytes through the additive Game Session V46 owner, and independently reads the historical pin through the exact World workload. That unregistered producer reconstructs the immutable pin, original Account-attached attempt and launch in one repeatable-read owner snapshot; missing history is not repaired from current reads or mutable runtime status. The definition also composes World's original-operation recovery with native World-to-Account and World-to-Game Session reads, and Account's exact terminal settlement with native Account-to-World readback. Account source protection must remain pending after World `COMMITTED` until the original participation ID/fence is durably settled and independently read back. The distinct unregistered [Account settlement transport](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) now replaces the local test-peer invocation with the file-backed World-to-Account client. The definition compares complete terminal bytes and the original settlement timestamp against independent World and Account reads, then uses a new correlation ID to prove immutable retry and one durable receipt. These definitions retain the original tuple and finite lease and do not enable a runtime path. Neither compiled definitions nor synthetic storage/transport cases prove the complete genuine handoff. -The corrected consolidated Account, Game Session and Game Design check passes in 1 minute 50 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. Game Session executes 2,005 unit cases, including all four new pin/receiver denial and snapshot cases; seventeen pre-existing unit cases skip. Account and Game Design reuse 1,970 passing unit results. Account executes twelve non-container integration cases and skips 289 container cases; Game Design skips all 153 container cases, including both genuine-release scenarios. Game Session's unchanged integration and cross-service tasks reuse thirty and one executed cases respectively, with 175 and 38 skipped. The V46 storage case and positive native historical-recovery/settlement composition have not executed against PostgreSQL. jOOQ schema generation and the 313-file Flyway numbering check pass, but neither establishes migration execution. No positive historical reconstruction is claimed from the older mocked authored-core service fixture. +The corrected Common Platform, Account and Game Design settlement-transport check passes in 3 minutes 24 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. Account executes 1,392 unit cases, including the three new receiver-ordering cases and four loopback-mTLS cases. The latter use the real file-backed client and receiver with an unresolved mocked owner: exact World identity reaches the lookup, trusted wrong-service or wrong-namespace certificates and authenticated end-user context reach no owner, and a missing certificate fails during TLS before the handler. Common Platform and Game Design reuse 722 and 585 passing unit results, including seven executed new closed-codec and local-client cases from the immediately preceding run. Account's unchanged integration task reuses twelve non-container executions and 289 skips; all 153 Game Design integration cases skip, including both genuine native settlement scenarios. The initial integration-compile failure was two removed imports still required by separate Game Session descriptor probes; restoring those imports changed no guards or assertions. Public gRPC allowlists, proto-time fields and Flyway numbering for twelve sets and 313 files pass. This is transport, compilation, unit and static proof, not genuine PostgreSQL settlement or runtime readiness. + +The preceding consolidated Account, Game Session and Game Design pin check passed in 1 minute 50 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. Game Session executed 2,005 unit cases, including all four new pin/receiver denial and snapshot cases; seventeen pre-existing unit cases skipped. Account and Game Design reused 1,970 passing unit results. Account executed twelve non-container integration cases and skipped 289 container cases; Game Design skipped all 153 container cases, including both genuine-release scenarios. Game Session's unchanged integration and cross-service tasks reused thirty and one executed cases respectively, with 175 and 38 skipped. The V46 storage case and positive native historical-recovery/settlement composition have not executed against PostgreSQL. jOOQ schema generation and the 313-file Flyway numbering check pass, but neither establishes migration execution. No positive historical reconstruction is claimed from the older mocked authored-core service fixture. Original StartSession authorization is issued through the existing Logging & Admin file-backed mTLS client and redeemed through an exact Account-pinned Game Session channel. Both scenarios preserve the actual Account owner, Logging reservation, original Game Session attempt, exact authority bundle and independent Account readback; their issue/redemption peer contexts are no longer stipulated. The preceding corrected Account/Game Design check passed in 1 minute 21 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. It reused 1,970 passing unit results and executed twelve non-container Account integration cases; 289 Account and all 153 Game Design container cases skipped, including both genuine-release scenarios. Physical source/selection/preparation/settlement composition, real Entity assignment/placement and operational-region delivery remain open. All four handoffs remain incomplete; runtime registration and activation remain denied. diff --git a/protos/account/v1/start_session_world_participation_settlement.proto b/protos/account/v1/start_session_world_participation_settlement.proto new file mode 100644 index 0000000000..5548e85dc7 --- /dev/null +++ b/protos/account/v1/start_session_world_participation_settlement.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered World-to-Account historical participation settlement. The request is +// lookup-only: it supplies no terminal result, currentness claim, or release instruction. +service AccountStartSessionWorldParticipationSettlementService { + rpc SettleOriginalStartSessionWorldParticipation( + SettleOriginalStartSessionWorldParticipationRequest) + returns (SettleOriginalStartSessionWorldParticipationResponse); +} + +// Each repeated field must occur exactly once. Repetition preserves duplicate scalar occurrences +// so the closed receiver can reject them after parsing. +message SettleOriginalStartSessionWorldParticipationRequest { + repeated int32 schema_version = 1; + repeated string target_namespace = 2; + repeated string settlement_request_id = 3; + repeated string account_world_participation_id = 4; + // Canonical positive unsigned-decimal text bounded by a positive signed Java long. + repeated string account_world_participation_fence = 5; +} + +message SettleOriginalStartSessionWorldParticipationResponse { + repeated int32 schema_version = 1; + repeated string settlement_request_id = 2; + repeated string account_world_participation_id = 3; + repeated string account_world_participation_fence = 4; + // Exact canonical UTC instant with six fractional digits from the immutable Account row. + repeated string settled_at = 5; + // Complete immutable World terminal, never a digest-only substitute. + repeated bytes terminal_evidence_canonical_bytes = 6; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcService.java new file mode 100644 index 0000000000..a1ebf3dba7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcService.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationSettlementEvidence; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationSettlementGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationSettlementInput; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone unregistered receiver for exact historical World participation settlement. */ +public final class AccountStartSessionWorldParticipationSettlementGrpcService + extends AccountStartSessionWorldParticipationSettlementServiceGrpc + .AccountStartSessionWorldParticipationSettlementServiceImplBase { + private final AccountStartSessionWorldParticipationSettlementService owner; + private final String namespace; + + public AccountStartSessionWorldParticipationSettlementGrpcService( + AccountStartSessionWorldParticipationSettlementService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "World participation settlement owner required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void settleOriginalStartSessionWorldParticipation( + SettleOriginalStartSessionWorldParticipationRequest request, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer required"); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + String expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + if (SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !expectedPeer.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + if (request == null + || request.getSerializedSize() + > AccountStartSessionWorldParticipationSettlementGrpcCodec.MAX_REQUEST_WIRE_BYTES) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + final AccountStartSessionWorldParticipationSettlementInput input; + try { + input = + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest(request, namespace); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var stored = + owner.settle(input.accountWorldParticipationId(), input.accountWorldParticipationFence()); + WorldStartSessionExecutionTerminal terminal = + WorldStartSessionExecutionTerminal.fromStored(stored.terminalBytes()); + if (!stored.participationId().equals(input.accountWorldParticipationId()) + || !terminal.accountWorldParticipationId().equals(input.accountWorldParticipationId()) + || terminal.accountWorldParticipationFence() != input.accountWorldParticipationFence() + || !namespace.equals(terminal.targetNamespace()) + || !terminal.digest().equals(stored.terminalDigest()) + || terminal.outcome() != stored.outcome() + || terminal.worldExecutionFence() != stored.worldExecutionFence()) { + throw new IllegalArgumentException("Stored terminal settlement evidence is inconsistent"); + } + var evidence = + new AccountStartSessionWorldParticipationSettlementEvidence( + input.settlementRequestId(), terminal, stored.settledAt().toInstant()); + observer.onNext( + AccountStartSessionWorldParticipationSettlementGrpcCodec.toResponse(input, evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.INVALID_ARGUMENT + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + observer.onError(Status.fromCode(code).asRuntimeException()); + } catch (IllegalArgumentException invalidEvidence) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java new file mode 100644 index 0000000000..1af354a445 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java @@ -0,0 +1,275 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.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 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.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionWorldParticipationRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationSettlementGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationSettlementService; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationSettlementInput; +import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionWorldParticipationSettlementClient; +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.security.SessionContext; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Loopback mTLS receiver proof with a mocked Account settlement owner. */ +class AccountStartSessionWorldParticipationSettlementGrpcMtlsTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID PARTICIPATION_ID = + UUID.fromString("5bb41395-a183-4ce5-9343-cd0995ba3b48"); + private static final long PARTICIPATION_FENCE = 43L; + private static final UUID SETTLEMENT_REQUEST_ID = + UUID.fromString("10d5b75a-7c46-4890-834e-4c6547458d94"); + + @TempDir static Path temporaryDirectory; + + private static AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.TestPki pki; + + @BeforeAll + static void generateTrustedWorkloadCertificates() throws Exception { + pki = + AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.TestPki.create( + temporaryDirectory); + } + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactWorldClientReachesReceiverAndPassesOnlyTheRetainedLookupToOwner() throws Exception { + var owner = mock(AccountStartSessionWorldParticipationSettlementService.class); + when(owner.settle(PARTICIPATION_ID, PARTICIPATION_FENCE)) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + try (TransportServer server = startServer(owner, false); + var client = newClient(server.port(), pki.worldClient())) { + client.init(); + + assertThatThrownBy(() -> client.settle(input())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + + assertThat(server.handlerCalls()).hasValue(1); + verify(owner).settle(PARTICIPATION_ID, PARTICIPATION_FENCE); + } + } + + @Test + void trustedWrongServiceAndNamespaceCertificatesAreDeniedBeforeOwnerInteraction() + throws Exception { + for (var identity : List.of(pki.wrongServiceClient(), pki.otherNamespaceClient())) { + var owner = mock(AccountStartSessionWorldParticipationSettlementService.class); + try (TransportServer server = startServer(owner, false); + var client = newClient(server.port(), identity)) { + client.init(); + + assertThatThrownBy(() -> client.settle(input())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(1); + verifyNoInteractions(owner); + } + } + } + + @Test + void missingClientCertificateFailsDuringTlsBeforeHandlerOrOwner() throws Exception { + var owner = mock(AccountStartSessionWorldParticipationSettlementService.class); + try (TransportServer server = startServer(owner, false); + ClientTransport client = newClientWithoutIdentity(server.port())) { + var request = + net.firedevops.firemud.common.account.startsession + .AccountStartSessionWorldParticipationSettlementGrpcCodec.toRequest(input()); + + assertThatThrownBy(() -> client.settle(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "missing client certificate must fail during TLS negotiation: %s", + failure) + .isTrue()); + + assertThat(server.handlerCalls()).hasValue(0); + verifyNoInteractions(owner); + } + } + + @Test + void authenticatedEndUserContextIsDeniedAtReceiverBeforeOwnerInteraction() throws Exception { + var owner = mock(AccountStartSessionWorldParticipationSettlementService.class); + try (TransportServer server = startServer(owner, true); + var client = newClient(server.port(), pki.worldClient())) { + client.init(); + + assertThatThrownBy(() -> client.settle(input())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).hasValue(1); + verifyNoInteractions(owner); + } + } + + private static AccountStartSessionWorldParticipationSettlementInput input() { + return new AccountStartSessionWorldParticipationSettlementInput( + NAMESPACE, SETTLEMENT_REQUEST_ID, PARTICIPATION_ID, PARTICIPATION_FENCE); + } + + private static TransportServer startServer( + AccountStartSessionWorldParticipationSettlementService owner, boolean injectEndUserContext) + throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + var service = new AccountStartSessionWorldParticipationSettlementGrpcService(owner, NAMESPACE); + ServerInterceptor countHandlerCalls = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + handlerCalls.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + ServerInterceptor endUserContext = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + var delegate = next.startCall(call, metadata); + if (!injectEndUserContext) return delegate; + return new io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener<>( + delegate) { + @Override + public void onHalfClose() { + SessionContext.setContext("authenticated-user", List.of(), Map.of()); + try { + super.onHalfClose(); + } finally { + SessionContext.clear(); + } + } + }; + } + }; + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.accountServer().privateKey(), pki.accountServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, + countHandlerCalls, + new net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor(), + endUserContext)) + .build() + .start(); + return new TransportServer(server, handlerCalls); + } + + private static GrpcAccountStartSessionWorldParticipationSettlementClient newClient( + int port, + AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + return new GrpcAccountStartSessionWorldParticipationSettlementClient( + endpoints, + pki.clientProperties(temporaryDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ClientTransport newClientWithoutIdentity(int port) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCaCert(pki.caCertificatePem().toString()); + ManagedChannel channel = + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false); + return new ClientTransport(channel); + } + + private record TransportServer(Server server, AtomicInteger handlerCalls) + implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private void settle(SettleOriginalStartSessionWorldParticipationRequest request) { + AccountStartSessionWorldParticipationSettlementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .settleOriginalStartSessionWorldParticipation(request); + } + + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback gRPC client did not terminate"); + } + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcServiceTest.java new file mode 100644 index 0000000000..95ca5bd8e0 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcServiceTest.java @@ -0,0 +1,165 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionWorldParticipationResponse; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationSettlementGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationSettlementService; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationSettlementGrpcCodec; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationSettlementInput; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Receiver ordering and dispatch tests; synthetic peer context is not authenticated TLS proof. */ +class AccountStartSessionWorldParticipationSettlementGrpcServiceTest { + private static final String NAMESPACE = "world-runtime"; + private static final String WORLD_URI = + "spiffe://firemud/ns/world-runtime/sa/world-management-service"; + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactWorldPeerBeforeMalformedRequestParsing() { + var owner = mock(AccountStartSessionWorldParticipationSettlementService.class); + var receiver = new AccountStartSessionWorldParticipationSettlementGrpcService(owner, NAMESPACE); + var malformed = SettleOriginalStartSessionWorldParticipationRequest.newBuilder().build(); + + assertCode(Status.Code.UNAUTHENTICATED, invoke(receiver, null, malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, + identity("spiffe://firemud/ns/other-runtime/sa/world-management-service"), + malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, identity("spiffe://firemud/ns/world-runtime/sa/account-service"), malformed)); + SessionContext.setContext("authenticated-user", List.of(), Map.of()); + assertCode(Status.Code.PERMISSION_DENIED, invoke(receiver, identity(WORLD_URI), malformed)); + verifyNoInteractions(owner); + } + + @Test + void rejectsAmbientSqlAndClosedEnvelopeErrorsBeforeOwnerCall() { + var owner = mock(AccountStartSessionWorldParticipationSettlementService.class); + var receiver = new AccountStartSessionWorldParticipationSettlementGrpcService(owner, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, identity(WORLD_URI), null)); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, identity(WORLD_URI), null)); + TransactionSynchronizationManager.clearSynchronization(); + + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, identity(WORLD_URI), null)); + var duplicate = + SettleOriginalStartSessionWorldParticipationRequest.newBuilder() + .addSchemaVersion(1) + .addSchemaVersion(1) + .build(); + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, identity(WORLD_URI), duplicate)); + var unknown = + SettleOriginalStartSessionWorldParticipationRequest.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, identity(WORLD_URI), unknown)); + verifyNoInteractions(owner); + } + + @Test + void validClosedWorldRequestReachesOwnerAndUnresolvedFailureHasNoResponse() { + var owner = mock(AccountStartSessionWorldParticipationSettlementService.class); + UUID participationId = UUID.fromString("5bb41395-a183-4ce5-9343-cd0995ba3b48"); + when(owner.settle(participationId, 43L)).thenThrow(Status.UNAVAILABLE.asRuntimeException()); + var receiver = new AccountStartSessionWorldParticipationSettlementGrpcService(owner, NAMESPACE); + var request = + AccountStartSessionWorldParticipationSettlementGrpcCodec.toRequest( + new AccountStartSessionWorldParticipationSettlementInput( + NAMESPACE, + UUID.fromString("10d5b75a-7c46-4890-834e-4c6547458d94"), + participationId, + 43L)); + + assertCode(Status.Code.UNAVAILABLE, invoke(receiver, identity(WORLD_URI), request)); + verify(owner).settle(participationId, 43L); + } + + private static Invocation invoke( + AccountStartSessionWorldParticipationSettlementGrpcService receiver, + GrpcPeerIdentity peer, + SettleOriginalStartSessionWorldParticipationRequest request) { + var result = new Invocation(); + Context context = Context.current(); + if (peer != null) { + context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + } + Context previous = context.attach(); + try { + receiver.settleOriginalStartSessionWorldParticipation(request, result); + } finally { + context.detach(previous); + } + return result; + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, Invocation invocation) { + assertThat(invocation.error).isNotNull(); + assertThat(invocation.error.statusRuntimeException()).isTrue(); + assertThat(invocation.error.code()).isEqualTo(expected); + assertThat(invocation.response).isNull(); + assertThat(invocation.completed).isFalse(); + } + + private record ObservedError(boolean statusRuntimeException, Status.Code code) {} + + private static final class Invocation + implements StreamObserver { + private SettleOriginalStartSessionWorldParticipationResponse response; + private ObservedError error; + private boolean completed; + + @Override + public void onNext(SettleOriginalStartSessionWorldParticipationResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = + new ObservedError( + failure instanceof StatusRuntimeException, Status.fromThrowable(failure).getCode()); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java index 8ad2d1f7d8..728895fda0 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -376,6 +376,13 @@ public AccountStartSessionWorldParticipationSettlementService worldParticipation namespace); } + /** Creates the actual Account settlement receiver for same-namespace World mTLS calls. */ + public BindableService worldParticipationSettlementGrpcService( + WorldStartSessionExecutionTerminalReadClient worldClient) { + return new AccountStartSessionWorldParticipationSettlementGrpcService( + worldParticipationSettlementService(worldClient), namespace); + } + /** * Reads the exact durable participation coordinates for this tuple without creating authority. */ diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementClient.java new file mode 100644 index 0000000000..2a190c3b8a --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementClient.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.common.account.startsession; + +/** + * Authenticated lookup-only client for Account's exact immutable World participation settlement. + */ +public interface AccountStartSessionWorldParticipationSettlementClient { + AccountStartSessionWorldParticipationSettlementEvidence settle( + AccountStartSessionWorldParticipationSettlementInput input); +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementEvidence.java new file mode 100644 index 0000000000..4e7d338cbb --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementEvidence.java @@ -0,0 +1,33 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; + +/** Full immutable Account settlement identity and the exact World terminal it retained. */ +public record AccountStartSessionWorldParticipationSettlementEvidence( + UUID settlementRequestId, WorldStartSessionExecutionTerminal terminal, Instant settledAt) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public AccountStartSessionWorldParticipationSettlementEvidence { + Objects.requireNonNull(settlementRequestId, "settlement correlation ID required"); + if (NIL_UUID.equals(settlementRequestId)) { + throw new IllegalArgumentException("Settlement correlation ID must be non-nil"); + } + Objects.requireNonNull(terminal, "complete World terminal required"); + Objects.requireNonNull(settledAt, "Account settlement timestamp required"); + if (settledAt.getNano() % 1_000 != 0) { + throw new IllegalArgumentException( + "Account settlement timestamp must preserve PostgreSQL microseconds"); + } + } + + public UUID accountWorldParticipationId() { + return terminal.accountWorldParticipationId(); + } + + public long accountWorldParticipationFence() { + return terminal.accountWorldParticipationFence(); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodec.java new file mode 100644 index 0000000000..4633b8f953 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodec.java @@ -0,0 +1,267 @@ +package net.firedevops.firemud.common.account.startsession; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.util.Arrays; +import java.util.Locale; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionWorldParticipationRequest; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; + +/** Closed, bounded protobuf mapping for Account's exact original World participation receipt. */ +public final class AccountStartSessionWorldParticipationSettlementGrpcCodec { + /** Small selector only; no caller-supplied terminal bytes are accepted. */ + public static final int MAX_REQUEST_WIRE_BYTES = 512; + + /** Existing complete World terminal cap plus bounded protobuf framing and identity fields. */ + public static final int MAX_RESPONSE_WIRE_BYTES = + WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + 256; + + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final DateTimeFormatter UTC_MICROS = + new DateTimeFormatterBuilder() + .appendPattern("uuuu-MM-dd'T'HH:mm:ss") + .appendLiteral('.') + .appendFraction(java.time.temporal.ChronoField.NANO_OF_SECOND, 6, 6, false) + .appendLiteral('Z') + .toFormatter(Locale.ROOT) + .withZone(ZoneOffset.UTC); + + private AccountStartSessionWorldParticipationSettlementGrpcCodec() {} + + public static SettleOriginalStartSessionWorldParticipationRequest toRequest( + AccountStartSessionWorldParticipationSettlementInput input) { + Objects.requireNonNull(input, "World participation settlement input required"); + var request = + SettleOriginalStartSessionWorldParticipationRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addTargetNamespace(input.targetNamespace()) + .addSettlementRequestId(input.settlementRequestId().toString()) + .addAccountWorldParticipationId(input.accountWorldParticipationId().toString()) + .addAccountWorldParticipationFence( + Long.toString(input.accountWorldParticipationFence())) + .build(); + requireRequestBudget(request); + return request; + } + + /** Must be called only after exact same-namespace World peer authentication. */ + public static AccountStartSessionWorldParticipationSettlementInput fromRequest( + SettleOriginalStartSessionWorldParticipationRequest request, String expectedNamespace) { + Objects.requireNonNull(request, "World participation settlement request required"); + requireClosed(request, "request"); + requireRequestBudget(request); + if (request.getSchemaVersionCount() != 1 + || request.getTargetNamespaceCount() != 1 + || request.getSettlementRequestIdCount() != 1 + || request.getAccountWorldParticipationIdCount() != 1 + || request.getAccountWorldParticipationFenceCount() != 1 + || request.getSchemaVersion(0) != SCHEMA_VERSION + || !GrpcPeerIdentity.isValidNamespace(expectedNamespace) + || !expectedNamespace.equals(request.getTargetNamespace(0))) { + throw invalid("Unsupported schema, duplicate field, or target namespace"); + } + var input = + new AccountStartSessionWorldParticipationSettlementInput( + expectedNamespace, + canonicalUuid(request.getSettlementRequestId(0), "settlementRequestId"), + canonicalUuid(request.getAccountWorldParticipationId(0), "accountWorldParticipationId"), + canonicalPositiveLong(request.getAccountWorldParticipationFence(0))); + if (!toRequest(input).equals(request)) { + throw invalid("World participation settlement request is not its exact closed encoding"); + } + return input; + } + + /** Encodes only complete settlement evidence returned by the Account owner service. */ + public static SettleOriginalStartSessionWorldParticipationResponse toResponse( + AccountStartSessionWorldParticipationSettlementInput input, + AccountStartSessionWorldParticipationSettlementEvidence evidence) { + Objects.requireNonNull(input, "World participation settlement input required"); + Objects.requireNonNull(evidence, "durable Account settlement evidence required"); + WorldStartSessionExecutionTerminal terminal = evidence.terminal(); + if (!input.settlementRequestId().equals(evidence.settlementRequestId()) + || !input.accountWorldParticipationId().equals(terminal.accountWorldParticipationId()) + || input.accountWorldParticipationFence() != terminal.accountWorldParticipationFence() + || !input.targetNamespace().equals(terminal.targetNamespace())) { + throw invalid("Durable settlement differs from the exact request identity"); + } + var response = + SettleOriginalStartSessionWorldParticipationResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addSettlementRequestId(evidence.settlementRequestId().toString()) + .addAccountWorldParticipationId(terminal.accountWorldParticipationId().toString()) + .addAccountWorldParticipationFence( + Long.toString(terminal.accountWorldParticipationFence())) + .addSettledAt(UTC_MICROS.format(evidence.settledAt())) + .addTerminalEvidenceCanonicalBytes(ByteString.copyFrom(terminal.canonicalBytes())) + .build(); + requireResponseBudget(response); + return response; + } + + public static AccountStartSessionWorldParticipationSettlementEvidence fromResponse( + AccountStartSessionWorldParticipationSettlementInput input, + SettleOriginalStartSessionWorldParticipationResponse response) { + Objects.requireNonNull(input, "World participation settlement input required"); + Objects.requireNonNull(response, "World participation settlement response required"); + requireClosed(response, "response"); + requireResponseBudget(response); + if (response.getSchemaVersionCount() != 1 + || response.getSettlementRequestIdCount() != 1 + || response.getAccountWorldParticipationIdCount() != 1 + || response.getAccountWorldParticipationFenceCount() != 1 + || response.getSettledAtCount() != 1 + || response.getTerminalEvidenceCanonicalBytesCount() != 1 + || response.getSchemaVersion(0) != SCHEMA_VERSION + || !input.settlementRequestId().toString().equals(response.getSettlementRequestId(0)) + || !input + .accountWorldParticipationId() + .toString() + .equals(response.getAccountWorldParticipationId(0)) + || !Long.toString(input.accountWorldParticipationFence()) + .equals(response.getAccountWorldParticipationFence(0))) { + throw invalid("World participation settlement response identity differs from its request"); + } + Instant settledAt = canonicalInstant(response.getSettledAt(0)); + byte[] terminalBytes = response.getTerminalEvidenceCanonicalBytes(0).toByteArray(); + if (terminalBytes.length == 0 + || terminalBytes.length > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { + throw invalid("Complete World terminal is missing or oversized"); + } + WorldStartSessionExecutionTerminal terminal = + WorldStartSessionExecutionTerminal.fromStored(terminalBytes); + if (!Arrays.equals(terminalBytes, terminal.canonicalBytes()) + || !input.accountWorldParticipationId().equals(terminal.accountWorldParticipationId()) + || input.accountWorldParticipationFence() != terminal.accountWorldParticipationFence() + || !input.targetNamespace().equals(terminal.targetNamespace())) { + throw invalid("Full World terminal differs from the exact Account participation"); + } + var evidence = + new AccountStartSessionWorldParticipationSettlementEvidence( + input.settlementRequestId(), terminal, settledAt); + if (!toResponse(input, evidence).equals(response)) { + throw invalid("World participation settlement response is not its exact closed encoding"); + } + return evidence; + } + + public static AccountStartSessionWorldParticipationSettlementEvidence fromResponseWireBytes( + AccountStartSessionWorldParticipationSettlementInput input, byte[] wireBytes) { + if (wireBytes == null || wireBytes.length == 0 || wireBytes.length > MAX_RESPONSE_WIRE_BYTES) { + throw invalid("World participation settlement response exceeds its wire budget"); + } + try { + var response = SettleOriginalStartSessionWorldParticipationResponse.parseFrom(wireBytes); + var evidence = fromResponse(input, response); + if (!Arrays.equals(wireBytes, toResponse(input, evidence).toByteArray())) { + throw invalid("World participation settlement response wire bytes are not canonical"); + } + return evidence; + } catch (InvalidProtocolBufferException malformed) { + throw invalid("World participation settlement response wire bytes are malformed", malformed); + } + } + + public static AccountStartSessionWorldParticipationSettlementInput fromRequestWireBytes( + byte[] wireBytes, String expectedNamespace) { + if (wireBytes == null || wireBytes.length == 0 || wireBytes.length > MAX_REQUEST_WIRE_BYTES) { + throw invalid("World participation settlement request exceeds its wire budget"); + } + try { + var request = SettleOriginalStartSessionWorldParticipationRequest.parseFrom(wireBytes); + var input = fromRequest(request, expectedNamespace); + if (!Arrays.equals(wireBytes, toRequest(input).toByteArray())) { + throw invalid("World participation settlement request wire bytes are not canonical"); + } + return input; + } catch (InvalidProtocolBufferException malformed) { + throw invalid("World participation settlement request wire bytes are malformed", malformed); + } + } + + private static void requireRequestBudget( + SettleOriginalStartSessionWorldParticipationRequest request) { + if (request.getSerializedSize() <= 0 || request.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) { + throw invalid("World participation settlement request exceeds its wire budget"); + } + } + + private static void requireResponseBudget( + SettleOriginalStartSessionWorldParticipationResponse response) { + if (response.getSerializedSize() <= 0 + || response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES + || response.getTerminalEvidenceCanonicalBytesCount() != 1 + || response.getTerminalEvidenceCanonicalBytes(0).isEmpty() + || response.getTerminalEvidenceCanonicalBytes(0).size() + > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { + throw invalid("Complete World terminal is missing or exceeds its wire budget"); + } + } + + private static void requireClosed(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid("World participation settlement " + label + " contains unsupported fields"); + } + } + + private static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw invalid(field + " must be a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " must be a canonical non-nil UUID", malformed); + } + } + + private static long canonicalPositiveLong(String text) { + if (text == null || !POSITIVE_DECIMAL.matcher(text).matches()) { + throw invalid("Account World participation fence must be positive canonical decimal text"); + } + try { + long value = Long.parseLong(text); + if (value <= 0L || !Long.toString(value).equals(text)) { + throw invalid("Account World participation fence must fit a positive signed long"); + } + return value; + } catch (NumberFormatException malformed) { + throw invalid("Account World participation fence must fit a positive signed long", malformed); + } + } + + private static Instant canonicalInstant(String text) { + try { + Instant value = Instant.parse(text); + if (value.getNano() % 1_000 != 0 || !UTC_MICROS.format(value).equals(text)) { + throw invalid("Account settlement timestamp must be exact UTC microseconds"); + } + return value; + } catch (RuntimeException malformed) { + throw invalid("Account settlement timestamp must be exact UTC microseconds", malformed); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException( + "Original StartSession World participation settlement " + message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException( + "Original StartSession World participation settlement " + message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementInput.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementInput.java new file mode 100644 index 0000000000..d43e94d09c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementInput.java @@ -0,0 +1,32 @@ +package net.firedevops.firemud.common.account.startsession; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Lookup-only selector for exact historical settlement of one Account World participation. */ +public record AccountStartSessionWorldParticipationSettlementInput( + String targetNamespace, + UUID settlementRequestId, + UUID accountWorldParticipationId, + long accountWorldParticipationFence) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public AccountStartSessionWorldParticipationSettlementInput { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Account target namespace required"); + } + requireNonNil(settlementRequestId, "Settlement request correlation ID"); + requireNonNil(accountWorldParticipationId, "Account World participation ID"); + if (accountWorldParticipationFence <= 0L) { + throw new IllegalArgumentException("Account World participation fence must be positive"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label + " required"); + 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/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClient.java new file mode 100644 index 0000000000..ad556bbbb2 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClient.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.common.account.startsession; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountStartSessionWorldParticipationSettlementServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client pinned to Account in the configured World namespace. */ +public final class GrpcAccountStartSessionWorldParticipationSettlementClient + extends AbstractReloadingBlockingGrpcClient< + AccountStartSessionWorldParticipationSettlementServiceGrpc + .AccountStartSessionWorldParticipationSettlementServiceBlockingStub> + implements AccountStartSessionWorldParticipationSettlementClient { + private static final long CALL_DEADLINE_SECONDS = 180L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public GrpcAccountStartSessionWorldParticipationSettlementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + GrpcAccountStartSessionWorldParticipationSettlementClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "World workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes this explicit dependency only when an owning World service starts it. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account World participation settlement client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Account World participation settlement client has no gRPC stub"); + } + initialized = true; + } + + @Override + public AccountStartSessionWorldParticipationSettlementEvidence settle( + AccountStartSessionWorldParticipationSettlementInput input) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account World participation settlement requires no ambient World transaction"); + } + Objects.requireNonNull(input, "World participation settlement input required"); + if (!workloadNamespace.equals(input.targetNamespace())) { + throw new IllegalArgumentException( + "Account World participation settlement target namespace differs"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .settleOriginalStartSessionWorldParticipation( + AccountStartSessionWorldParticipationSettlementGrpcCodec.toRequest(input)); + try { + return AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse(input, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned invalid original StartSession World participation settlement evidence", + invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountStartSessionWorldParticipationSettlementServiceGrpc + .AccountStartSessionWorldParticipationSettlementServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountStartSessionWorldParticipationSettlementServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + AccountStartSessionWorldParticipationSettlementGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountStartSessionWorldParticipationSettlementServiceGrpc + .AccountStartSessionWorldParticipationSettlementServiceBlockingStub + requireStub() { + var current = stub(); + if (closed || !initialized || current == null) { + throw new IllegalStateException( + "Account World participation settlement client is not initialized and available"); + } + return current; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Account World participation settlement requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account World participation settlement requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account World participation settlement requires file-backed certificate, key, and CA " + + "material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account World participation settlement " + + label + + " must be a readable file-backed path", + invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account World participation settlement " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodecTest.java new file mode 100644 index 0000000000..8a20fde8ef --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodecTest.java @@ -0,0 +1,410 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleOriginalStartSessionWorldParticipationResponse; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; +import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal.Outcome; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +/** Closed selector and response-binding cases using a real canonical World terminal value. */ +class AccountStartSessionWorldParticipationSettlementGrpcCodecTest { + private static final String NAMESPACE = "world-runtime"; + private static final UUID TENANT = uuid("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID PARTICIPATION_ID = uuid("a8c1e8c8-f237-41b7-918d-ec2281bcac10"); + private static final UUID GAME_SESSION_ATTEMPT_ID = uuid("b9d2f9d9-0438-42c8-829e-fd3392cd9d21"); + private static final UUID GAME_INSTANCE_ID = uuid("c0e30aea-1549-43d9-93af-0e44a3deae32"); + private static final UUID SETTLEMENT_REQUEST_ID = uuid("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"); + private static final String CONTROL_PLANE_REQUEST_ID = "world-settlement-original-request"; + private static final String PREPARATION_INPUT = "{ \"immutable\": true }"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void roundTripsOnlyExactLookupIdentityAndCompleteCanonicalTerminal() { + var input = input(); + var request = AccountStartSessionWorldParticipationSettlementGrpcCodec.toRequest(input); + var decodedRequest = + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest(request, NAMESPACE); + + assertThat(decodedRequest).isEqualTo(input); + assertThat(request.getAllFields()).hasSize(5); + assertThat(request.getSerializedSize()) + .isLessThanOrEqualTo( + AccountStartSessionWorldParticipationSettlementGrpcCodec.MAX_REQUEST_WIRE_BYTES); + assertThat(request.getAccountWorldParticipationId(0)).isEqualTo(PARTICIPATION_ID.toString()); + + var terminal = terminal(NAMESPACE, PARTICIPATION_ID, 31L, Outcome.COMMITTED); + var evidence = + new AccountStartSessionWorldParticipationSettlementEvidence( + SETTLEMENT_REQUEST_ID, terminal, Instant.parse("2026-10-11T00:00:00.000001Z")); + var response = + AccountStartSessionWorldParticipationSettlementGrpcCodec.toResponse(input, evidence); + var decoded = + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse(input, response); + var wireDecoded = + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponseWireBytes( + input, response.toByteArray()); + + assertThat(response.getAllFields()).hasSize(6); + assertThat(decoded.settlementRequestId()).isEqualTo(SETTLEMENT_REQUEST_ID); + assertThat(decoded.accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(decoded.accountWorldParticipationFence()).isEqualTo(31L); + assertThat(decoded.terminal().outcome()).isEqualTo(Outcome.COMMITTED); + assertThat(decoded.terminal().canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(decoded.settledAt()).isEqualTo(Instant.parse("2026-10-11T00:00:00.000001Z")); + assertThat(wireDecoded.settlementRequestId()).isEqualTo(decoded.settlementRequestId()); + assertThat(wireDecoded.terminal().canonicalBytes()) + .containsExactly(decoded.terminal().canonicalBytes()); + assertThat(wireDecoded.settledAt()).isEqualTo(decoded.settledAt()); + } + + @Test + void rejectsDuplicateUnknownChangedAndNoncanonicalRequestFields() { + var input = input(); + var request = AccountStartSessionWorldParticipationSettlementGrpcCodec.toRequest(input); + + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder().addAccountWorldParticipationFence("32").build(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder().setTargetNamespace(0, "another-runtime").build(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder().setAccountWorldParticipationFence(0, "031").build(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder() + .setAccountWorldParticipationFence(0, "9223372036854775808") + .build(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder() + .setSettlementRequestId(0, "00000000-0000-0000-0000-000000000000") + .build(), + NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil UUID"); + + byte[] noncanonicalWire = + java.util.Arrays.copyOf( + AccountStartSessionWorldParticipationSettlementGrpcCodec.toRequest(input).toByteArray(), + request.getSerializedSize() + 1); + noncanonicalWire[noncanonicalWire.length - 1] = 0; + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequestWireBytes( + noncanonicalWire, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void responseMustEchoLookupIdentityAndBindTerminalToParticipationAndNamespace() { + var input = input(); + var terminal = terminal(NAMESPACE, PARTICIPATION_ID, 31L, Outcome.ABORTED); + var valid = response(input, terminal, "2026-10-11T00:00:00.000001Z"); + + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + valid.toBuilder() + .setSettlementRequestId( + 0, uuid("e2a52c0c-c71f-4900-b1f2-c78f8b512a63").toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("identity"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + valid.toBuilder().setSettledAt(0, "2026-10-11T00:00:00.000000001Z").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("microseconds"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + response( + input, + terminal( + NAMESPACE, + uuid("e2a52c0c-c71f-4900-b1f2-c78f8b512a63"), + 31L, + Outcome.COMMITTED), + "2026-10-11T00:00:00.000001Z"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact Account participation"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + response( + input, + terminal(NAMESPACE, PARTICIPATION_ID, 32L, Outcome.COMMITTED), + "2026-10-11T00:00:00.000001Z"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact Account participation"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + response( + input, + terminal("another-runtime", PARTICIPATION_ID, 31L, Outcome.COMMITTED), + "2026-10-11T00:00:00.000001Z"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact Account participation"); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + valid.toBuilder() + .setTerminalEvidenceCanonicalBytes(0, ByteString.copyFromUtf8("{}")) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsIncompleteEvidenceAndTimestampPrecisionLoss() { + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationSettlementEvidence( + SETTLEMENT_REQUEST_ID, + terminal(NAMESPACE, PARTICIPATION_ID, 31L, Outcome.COMMITTED), + Instant.parse("2026-10-11T00:00:00.000000001Z"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("preserve PostgreSQL microseconds"); + + var input = input(); + var incomplete = + SettleOriginalStartSessionWorldParticipationResponse.newBuilder() + .addSchemaVersion(1) + .addSettlementRequestId(SETTLEMENT_REQUEST_ID.toString()) + .addAccountWorldParticipationId(PARTICIPATION_ID.toString()) + .addAccountWorldParticipationFence("31") + .addSettledAt("2026-10-11T00:00:00.000001Z") + .addTerminalEvidenceCanonicalBytes(ByteString.EMPTY) + .build(); + assertThatThrownBy( + () -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, incomplete)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AccountStartSessionWorldParticipationSettlementInput input() { + return new AccountStartSessionWorldParticipationSettlementInput( + NAMESPACE, SETTLEMENT_REQUEST_ID, PARTICIPATION_ID, 31L); + } + + private static SettleOriginalStartSessionWorldParticipationResponse response( + AccountStartSessionWorldParticipationSettlementInput input, + WorldStartSessionExecutionTerminal terminal, + String settledAt) { + return SettleOriginalStartSessionWorldParticipationResponse.newBuilder() + .addSchemaVersion(1) + .addSettlementRequestId(input.settlementRequestId().toString()) + .addAccountWorldParticipationId(input.accountWorldParticipationId().toString()) + .addAccountWorldParticipationFence(Long.toString(input.accountWorldParticipationFence())) + .addSettledAt(settledAt) + .addTerminalEvidenceCanonicalBytes(ByteString.copyFrom(terminal.canonicalBytes())) + .build(); + } + + private static WorldStartSessionExecutionTerminal terminal( + String namespace, UUID participationId, long participationFence, Outcome outcome) { + StartSessionPostAuthorizationExecutionTuple tuple = originalTuple(namespace); + return new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + participationId, + participationFence, + GAME_SESSION_ATTEMPT_ID, + 37L, + namespace, + TENANT, + CONTROL_PLANE_REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + outcome); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(String namespace) { + UUID actor = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); + UUID targetOwner = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + UUID reservationOwner = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + CONTROL_PLANE_REQUEST_ID, + actor, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, targetOwner), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic World participation settlement codec test")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + reservationOwner, + 19L, + authorityBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { + String actorId = tuple.actor().accountId().toString(); + String tenantId = tuple.action().scope().tenantId().toString(); + Map projection = + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"); + Map issuanceIdentity = + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map humanEvidence = + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", actorId, + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"); + Map bundle = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + issuanceIdentity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + humanEvidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String digest(String value) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClientTest.java new file mode 100644 index 0000000000..312e66ce2d --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClientTest.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.common.account.startsession; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import java.io.IOException; +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.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Construction and local boundary denials; no authenticated Account transport proof. */ +class GrpcAccountStartSessionWorldParticipationSettlementClientTest { + @TempDir Path temporaryDirectory; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsPlaintextClasspathAndMissingMaterial() { + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> client(plaintext)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + var classpath = new CommonGrpcClientProperties(); + classpath.setCertChain("classpath:client.pem"); + classpath.setPrivateKey("/tmp/key.pem"); + classpath.setCaCert("/tmp/ca.pem"); + assertThatThrownBy(() -> client(classpath)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + assertThatThrownBy(() -> client(new CommonGrpcClientProperties())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + } + + @Test + void rejectsUninitializedUseAmbientTransactionsAndChangedNamespace() throws IOException { + var client = client(fileBackedProperties()); + assertThatThrownBy(() -> client.settle(input("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + assertThatThrownBy(() -> client.settle(input("another-runtime"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.settle(input("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient World transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.settle(input("world-runtime"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient World transaction"); + TransactionSynchronizationManager.clearSynchronization(); + } + + @Test + void closePreventsExplicitInitialization() throws IOException { + var client = client(fileBackedProperties()); + client.close(); + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + } + + private GrpcAccountStartSessionWorldParticipationSettlementClient client( + CommonGrpcClientProperties tls) { + return new GrpcAccountStartSessionWorldParticipationSettlementClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "world-runtime"); + } + + private CommonGrpcClientProperties fileBackedProperties() throws IOException { + Path certificate = Files.createFile(temporaryDirectory.resolve("client.pem")); + Path privateKey = Files.createFile(temporaryDirectory.resolve("client-key.pem")); + Path ca = Files.createFile(temporaryDirectory.resolve("ca.pem")); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + + private static AccountStartSessionWorldParticipationSettlementInput input(String namespace) { + return new AccountStartSessionWorldParticipationSettlementInput( + namespace, + UUID.fromString("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"), + UUID.fromString("a8c1e8c8-f237-41b7-918d-ec2281bcac10"), + 31L); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 62974f2c3e..4d530d7376 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -77,8 +77,10 @@ import net.firedevops.firemud.common.account.startsession.AccountStartSessionAdmissionProtectionAcquisitionGrpcClient; import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationAcquisitionClient; import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadClient; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationSettlementInput; import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionActivationProtectionAcquisitionClient; import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionActivationProtectionSettlementClient; +import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionWorldParticipationSettlementClient; import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderClient; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; @@ -672,6 +674,9 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( var accountToWorldExecutionTerminalClient = new WorldStartSessionExecutionTerminalReadClient( endpoints, pki.client("account-service"), channels, NAMESPACE); + var worldToAccountParticipationSettlementClient = + new GrpcAccountStartSessionWorldParticipationSettlementClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); var account = new AccountControlUiOriginalOrderFixture( ACCOUNT_POSTGRES.getJdbcUrl(), @@ -763,6 +768,7 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( worldToAccountParticipationHistoryClient.init(); worldToGameSessionOwnerEvidenceClient.init(); accountToWorldExecutionTerminalClient.init(); + worldToAccountParticipationSettlementClient.init(); var originalOperationRecoveryVerifier = new WorldCanonicalInstanceOriginalOperationRecoveryVerifier( worldToAccountParticipationHistoryClient, worldToGameSessionOwnerEvidenceClient); @@ -1257,13 +1263,12 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( var accountWorldParticipationAcquisitionService = startSessionAuthorizationProof.worldParticipationAcquisitionService( accountToGameSessionCurrentAttemptClient); - var accountWorldParticipationSettlementService = - startSessionAuthorizationProof.worldParticipationSettlementService( - accountToWorldExecutionTerminalClient); register( accountHandlers, new AccountStartSessionWorldParticipationAcquisitionGrpcService( - accountWorldParticipationAcquisitionService, NAMESPACE)); + accountWorldParticipationAcquisitionService, NAMESPACE), + startSessionAuthorizationProof.worldParticipationSettlementGrpcService( + accountToWorldExecutionTerminalClient)); var worldParticipationVerifier = new WorldStartSessionAccountParticipationVerifier( NAMESPACE, worldToAccountParticipationClient); @@ -4378,17 +4383,23 @@ public void close() {} exactAccountParticipation.participationId(), exactAccountParticipation.participationFence())) .isEmpty(); + var settlementRequestId = UUID.randomUUID(); var settledWorldParticipation = - withWorldPeer( - () -> - accountWorldParticipationSettlementService.settle( - exactAccountParticipation.participationId(), - exactAccountParticipation.participationFence())); - assertThat(settledWorldParticipation.participationId()) + worldToAccountParticipationSettlementClient.settle( + new AccountStartSessionWorldParticipationSettlementInput( + NAMESPACE, + settlementRequestId, + exactAccountParticipation.participationId(), + exactAccountParticipation.participationFence())); + assertThat(settledWorldParticipation.settlementRequestId()) + .isEqualTo(settlementRequestId); + assertThat(settledWorldParticipation.accountWorldParticipationId()) .isEqualTo(exactAccountParticipation.participationId()); - assertThat(settledWorldParticipation.outcome()) + assertThat(settledWorldParticipation.accountWorldParticipationFence()) + .isEqualTo(exactAccountParticipation.participationFence()); + assertThat(settledWorldParticipation.terminal().outcome()) .isEqualTo(committedWorldTerminal.outcome()); - assertThat(settledWorldParticipation.terminalBytes()) + assertThat(settledWorldParticipation.terminal().canonicalBytes()) .containsExactly(committedWorldTerminal.canonicalBytes()); var independentlySettledWorldParticipation = startSessionAuthorizationProof @@ -4397,7 +4408,33 @@ public void close() {} exactAccountParticipation.participationFence()) .orElseThrow(); assertThat(independentlySettledWorldParticipation.terminalBytes()) - .containsExactly(settledWorldParticipation.terminalBytes()); + .containsExactly(settledWorldParticipation.terminal().canonicalBytes()); + assertThat(independentlySettledWorldParticipation.settledAt().toInstant()) + .isEqualTo(settledWorldParticipation.settledAt()); + + var retrySettlementRequestId = UUID.randomUUID(); + assertThat(retrySettlementRequestId).isNotEqualTo(settlementRequestId); + var retriedWorldParticipation = + worldToAccountParticipationSettlementClient.settle( + new AccountStartSessionWorldParticipationSettlementInput( + NAMESPACE, + retrySettlementRequestId, + exactAccountParticipation.participationId(), + exactAccountParticipation.participationFence())); + assertThat(retriedWorldParticipation.settlementRequestId()) + .isEqualTo(retrySettlementRequestId); + assertThat(retriedWorldParticipation.terminal().canonicalBytes()) + .containsExactly(settledWorldParticipation.terminal().canonicalBytes()); + assertThat(retriedWorldParticipation.settledAt()) + .isEqualTo(settledWorldParticipation.settledAt()); + assertThat( + startSessionAuthorizationProof + .sourceDsl() + .fetchCount( + DSL.table("account_start_session_world_participation_settlements"), + DSL.field("participation_id", UUID.class) + .eq(exactAccountParticipation.participationId()))) + .isOne(); var assembledPreparationInput = preparationAssembly.assemble( @@ -5893,21 +5930,6 @@ private static T withGameSessionPeer(Supplier operation) { } } - private static T withWorldPeer(Supplier operation) { - var peer = - new GrpcPeerIdentity( - "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", - NAMESPACE, - "world-management-service"); - Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); - Context previous = context.attach(); - try { - return operation.get(); - } finally { - context.detach(previous); - } - } - private static void assertFailedPrecondition(Runnable operation) { assertThatThrownBy(operation::run) .isInstanceOf(io.grpc.StatusRuntimeException.class) From ec76512da83379439fe92d0687dec85d5fe3d137 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:04:42 +1300 Subject: [PATCH 114/129] Prove native historical owner transport and exact descriptor replay --- ...ame-authoring-publishing-and-activation.md | 4 +- ...licationExportPostgresIntegrationTest.java | 87 ++-- ...tSessionOwnerEvidenceReadGrpcMtlsTest.java | 447 ++++++++++++++++++ 3 files changed, 502 insertions(+), 36 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java 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 b1d63684e5..ad073ef866 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 @@ -6,11 +6,11 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The genuine-release definition now obtains the first Game Design selection and exact-replay descriptor through file-backed Game Session mTLS, retains their unchanged request/result bytes through the additive Game Session V46 owner, and independently reads the historical pin through the exact World workload. That unregistered producer reconstructs the immutable pin, original Account-attached attempt and launch in one repeatable-read owner snapshot; missing history is not repaired from current reads or mutable runtime status. The definition also composes World's original-operation recovery with native World-to-Account and World-to-Game Session reads, and Account's exact terminal settlement with native Account-to-World readback. Account source protection must remain pending after World `COMMITTED` until the original participation ID/fence is durably settled and independently read back. The distinct unregistered [Account settlement transport](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) now replaces the local test-peer invocation with the file-backed World-to-Account client. The definition compares complete terminal bytes and the original settlement timestamp against independent World and Account reads, then uses a new correlation ID to prove immutable retry and one durable receipt. These definitions retain the original tuple and finite lease and do not enable a runtime path. Neither compiled definitions nor synthetic storage/transport cases prove the complete genuine handoff. +The genuine-release definition now obtains the first Game Design selection and exact-replay descriptor through file-backed Game Session mTLS, retains their unchanged request/result bytes through the additive Game Session V46 owner, and independently reads the historical pin through the exact World workload. The later descriptor replay and changed-selection denial now also use that native transport; replay separately reads the complete authored-core projections and compares their exact bytes. Three tuple, attempt and fence negatives deliberately remain local owner probes to retain their precise Account-origin denial assertions, not transport proof. That unregistered producer reconstructs the immutable pin, original Account-attached attempt and launch in one repeatable-read owner snapshot; missing history is not repaired from current reads or mutable runtime status. The definition also composes World's original-operation recovery with native World-to-Account and World-to-Game Session reads, and Account's exact terminal settlement with native Account-to-World readback. Account source protection must remain pending after World `COMMITTED` until the original participation ID/fence is durably settled and independently read back. The distinct unregistered [Account settlement transport](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) now replaces the local test-peer invocation with the file-backed World-to-Account client. The definition compares complete terminal bytes and the original settlement timestamp against independent World and Account reads, then uses a new correlation ID to prove immutable retry and one durable receipt. These definitions retain the original tuple and finite lease and do not enable a runtime path. Neither compiled definitions nor synthetic storage/transport cases prove the complete genuine handoff. The corrected Common Platform, Account and Game Design settlement-transport check passes in 3 minutes 24 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. Account executes 1,392 unit cases, including the three new receiver-ordering cases and four loopback-mTLS cases. The latter use the real file-backed client and receiver with an unresolved mocked owner: exact World identity reaches the lookup, trusted wrong-service or wrong-namespace certificates and authenticated end-user context reach no owner, and a missing certificate fails during TLS before the handler. Common Platform and Game Design reuse 722 and 585 passing unit results, including seven executed new closed-codec and local-client cases from the immediately preceding run. Account's unchanged integration task reuses twelve non-container executions and 289 skips; all 153 Game Design integration cases skip, including both genuine native settlement scenarios. The initial integration-compile failure was two removed imports still required by separate Game Session descriptor probes; restoring those imports changed no guards or assertions. Public gRPC allowlists, proto-time fields and Flyway numbering for twelve sets and 313 files pass. This is transport, compilation, unit and static proof, not genuine PostgreSQL settlement or runtime readiness. -The preceding consolidated Account, Game Session and Game Design pin check passed in 1 minute 50 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. Game Session executed 2,005 unit cases, including all four new pin/receiver denial and snapshot cases; seventeen pre-existing unit cases skipped. Account and Game Design reused 1,970 passing unit results. Account executed twelve non-container integration cases and skipped 289 container cases; Game Design skipped all 153 container cases, including both genuine-release scenarios. Game Session's unchanged integration and cross-service tasks reused thirty and one executed cases respectively, with 175 and 38 skipped. The V46 storage case and positive native historical-recovery/settlement composition have not executed against PostgreSQL. jOOQ schema generation and the 313-file Flyway numbering check pass, but neither establishes migration execution. No positive historical reconstruction is claimed from the older mocked authored-core service fixture. +The corrected Game Session and Game Design historical-transport check passes in 1 minute 3 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. Game Session executes 2,010 unit cases; seventeen pre-existing unit cases skip. All five new loopback-mTLS tests execute, covering seven scenarios through the real historical receiver and file-backed World client: the exact World peer reaches the unresolved mocked owner; wrong-service and wrong-namespace callers, missing client certificates and end-user context reach no owner; trusted wrong-service and wrong-namespace Game Session servers are rejected by the client's exact workload pin before owner access. The wrong-namespace server retains the Game Session service identity, isolating namespace denial. These are transport and denial proofs, not positive historical reconstruction. Game Design reuses 585 passing unit results and all 153 skipped integration cases, including both genuine scenarios whose native replay definitions compile. Game Session's unchanged integration and cross-service tasks reuse thirty and one executions respectively, with 175 and 38 skips. The initial test-compile failure was a missing receiver import and an invalid generic-interceptor lambda; their correction weakens no assertion or production guard. The preceding pin check executed all four local pin/receiver denial and snapshot cases, but the V46 storage case and positive native historical-recovery/settlement composition have not executed against PostgreSQL. jOOQ schema generation and the 313-file Flyway numbering check pass, but neither establishes migration execution. No positive historical reconstruction is claimed from the older mocked authored-core service fixture. Original StartSession authorization is issued through the existing Logging & Admin file-backed mTLS client and redeemed through an exact Account-pinned Game Session channel. Both scenarios preserve the actual Account owner, Logging reservation, original Game Session attempt, exact authority bundle and independent Account readback; their issue/redemption peer contexts are no longer stipulated. The preceding corrected Account/Game Design check passed in 1 minute 21 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. It reused 1,970 passing unit results and executed twelve non-container Account integration cases; 289 Account and all 153 Game Design container cases skipped, including both genuine-release scenarios. Physical source/selection/preparation/settlement composition, real Entity assignment/placement and operational-region delivery remain open. All four handoffs remain incomplete; runtime registration and activation remain denied. diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 4d530d7376..df11e16e53 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -110,6 +110,7 @@ import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; @@ -3360,21 +3361,7 @@ public void attachAccountRedemptionProjection( var firstDescriptorRead = gameSessionToGameDesignAuthoredCoreClient.read( new AuthoredInitialActorCoreReadEvidence.ReadRequest(firstDescriptorRequest)); - var descriptorDto = - new ResolvedLaunchDescriptorDto( - authoredWorldLaunchDescriptor.launchDescriptorId(), - authoredWorldLaunchDescriptor.canonicalTenantId().toString(), - authoredWorldLaunchDescriptor.gameTemplateId(), - authoredWorldLaunchDescriptor.controlPlaneRequestId(), - authoredWorldLaunchDescriptor.versionId(), - authoredWorldLaunchDescriptor.scriptPatchVersion(), - authoredWorldLaunchDescriptor.runtimeFlagsJson(), - authoredWorldLaunchDescriptor.generationConfigRevision(), - authoredWorldLaunchDescriptor.versionStateEpoch(), - authoredWorldLaunchDescriptor.releaseBundleId(), - authoredWorldLaunchDescriptor.publishedReleaseBundleRef(), - authoredWorldLaunchDescriptor.remapSetId(), - authoredWorldLaunchDescriptor); + var descriptorDto = resolvedLaunchDescriptorDto(authoredWorldLaunchDescriptor); var firstDescriptorBinding = new StartSessionLaunchDescriptorProducer.ResolvedBinding( firstDescriptorRequest, @@ -5338,16 +5325,29 @@ public void close() {} .containsExactlyElementsOf(completeBindingOwnerRowsBefore); } + var replayRequest = + startSessionReadRequest( + startSessionTuple, + ownerAttemptId, + ownerFence, + pinnedSelection, + UUID.randomUUID()); + var replayCall = gameDesignStartSessionReadTransport.resolveDescriptor(replayRequest); + assertThat(replayCall.result().outcome()) + .isInstanceOf(StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome.class); + var replayDescriptor = + ((StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome) + replayCall.result().outcome()) + .descriptor(); + var replayActorCoreRead = + gameSessionToGameDesignAuthoredCoreClient.read( + new AuthoredInitialActorCoreReadEvidence.ReadRequest(replayRequest)); var replay = - withGameSessionPeer( - () -> - descriptorProducer.resolve( - startSessionReadRequest( - startSessionTuple, - ownerAttemptId, - ownerFence, - pinnedSelection, - UUID.randomUUID()))); + new StartSessionLaunchDescriptorProducer.ResolvedBinding( + replayRequest, + replayCall.result().associationRead(), + resolvedLaunchDescriptorDto(replayDescriptor), + replayActorCoreRead.projections()); assertThat(replay.descriptor()).isEqualTo(firstDescriptorBinding.descriptor()); assertSameAuthoredCoreProjectionBytes( replay.actorCoreProjections(), firstDescriptorBinding.actorCoreProjections()); @@ -5357,6 +5357,9 @@ public void close() {} // This deliberately synthetic tuple is only a negative mismatch probe; unlike the // positive path it is not issued by Account and is expected to be rejected by the real // durable projection receiver. + // The remaining tuple, attempt, and fence probes stay local so their exact Account + // denial detail remains observable; they are owner-negative evidence, not transport + // proof. var changedTuple = startSessionTuple( controlPlaneRequestId, @@ -5408,17 +5411,15 @@ public void close() {} selectedCommit.commitId(), publicationRequest.derivedWorkflowIdentity(), "sha256:" + "0".repeat(64)); + var changedSelectionRequest = + startSessionReadRequest( + startSessionTuple, + ownerAttemptId, + ownerFence, + changedSelection, + UUID.randomUUID()); assertFailedPrecondition( - () -> - withGameSessionPeer( - () -> - descriptorProducer.resolve( - startSessionReadRequest( - startSessionTuple, - ownerAttemptId, - ownerFence, - changedSelection, - UUID.randomUUID())))); + () -> gameDesignStartSessionReadTransport.resolveDescriptor(changedSelectionRequest)); } assertThat(gd.dsl().fetchCount(DSL.table("launch_descriptor"))).isOne(); assertThat( @@ -5442,6 +5443,24 @@ public void close() {} } } + private static ResolvedLaunchDescriptorDto resolvedLaunchDescriptorDto( + AuthoredWorldLaunchDescriptorEvidence evidence) { + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + private static void assertSameAuthoredCoreProjectionBytes( List actual, List expected) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java new file mode 100644 index 0000000000..9725f0287b --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java @@ -0,0 +1,447 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ForwardingServerCallListener; +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 java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidenceReadClient; +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.SessionContext; +import net.firedevops.firemud.gamesession.service.impl.GameSessionOriginalStartSessionSelectionPinService; +import net.firedevops.firemud.gamesession.service.impl.HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService; +import net.firedevops.firemud.gamesession.v1.HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadHistoricalOriginalStartSessionOwnerEvidenceRequest; +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.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Real loopback mTLS transport proof for the deliberately unregistered historical reader. */ +class HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest { + private static final String NAMESPACE = "gameplay"; + private static final String WORLD_URI = + "spiffe://firemud/ns/gameplay/sa/world-management-service"; + private static final String WRONG_SERVICE_URI = "spiffe://firemud/ns/gameplay/sa/account-service"; + private static final String WRONG_NAMESPACE_URI = + "spiffe://firemud/ns/other/sa/world-management-service"; + private static final String GAME_SESSION_URI = + "spiffe://firemud/ns/gameplay/sa/game-session-service"; + private static final String WRONG_SERVER_NAMESPACE_URI = + "spiffe://firemud/ns/other/sa/game-session-service"; + private static final HistoricalOriginalStartSessionOwnerEvidence.Request REQUEST = request(); + + @TempDir static Path tempDirectory; + + private static TestPki pki; + private final GameSessionOriginalStartSessionSelectionPinService owner = + mock(GameSessionOriginalStartSessionSelectionPinService.class); + private Server server; + private ManagedChannel noCertificateChannel; + + @BeforeAll + static void createTestPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + KeyPair authorityKey = keyPair(); + X500Name authorityName = new X500Name("CN=Historical reader test CA, O=FireMUD Test"); + X509Certificate authorityCertificate = + issueCertificate( + authorityName, + authorityKey.getPublic(), + authorityName, + authorityKey.getPrivate(), + true, + null, + false); + pki = + new TestPki( + authorityCertificate, + issueIdentity(authorityName, authorityKey.getPrivate(), "world", WORLD_URI, false), + issueIdentity( + authorityName, + authorityKey.getPrivate(), + "wrong-service", + WRONG_SERVICE_URI, + false), + issueIdentity( + authorityName, + authorityKey.getPrivate(), + "wrong-namespace", + WRONG_NAMESPACE_URI, + false), + issueIdentity( + authorityName, + authorityKey.getPrivate(), + "wrong-service-server", + WRONG_SERVICE_URI, + true), + issueIdentity( + authorityName, + authorityKey.getPrivate(), + "wrong-namespace-server", + WRONG_SERVER_NAMESPACE_URI, + true), + issueIdentity( + authorityName, authorityKey.getPrivate(), "game-session", GAME_SESSION_URI, true)); + } + + @AfterEach + void stopTransportAndClearAuthContext() throws Exception { + if (noCertificateChannel != null) { + noCertificateChannel.shutdownNow(); + assertThat(noCertificateChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + noCertificateChannel = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + SessionContext.clear(); + } + + @Test + void exactSameNamespaceWorldClientReachesReceiverAndOwnerFailureDeniesRead() throws Exception { + when(owner.readHistorical(REQUEST)).thenReturn(java.util.Optional.empty()); + startReceiver(false); + + try (var client = newClient(pki.world())) { + client.init(); + assertThatThrownBy(() -> client.read(REQUEST)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + + verify(owner).readHistorical(REQUEST); + } + + @Test + void trustedWrongServiceAndWrongNamespaceCertificatesNeverReachOwner() throws Exception { + startReceiver(false); + + for (TestIdentity identity : List.of(pki.wrongService(), pki.wrongNamespace())) { + try (var client = newClient(identity)) { + client.init(); + assertThatThrownBy(() -> client.read(REQUEST)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + } + + verifyNoInteractions(owner); + } + + @Test + void trustedWrongServiceAndWrongNamespaceServerPeersAreRejectedBeforeOwnerAccess() + throws Exception { + for (TestIdentity serverIdentity : + List.of(pki.wrongServiceServer(), pki.wrongNamespaceServer())) { + startReceiver(serverIdentity, false); + try (var client = newClient(pki.world())) { + client.init(); + assertThatThrownBy(() -> client.read(REQUEST)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + } + stopReceiver(); + } + + verifyNoInteractions(owner); + } + + @Test + void missingClientCertificateIsRejectedByTlsBeforeOwnerAccess() throws Exception { + startReceiver(false); + noCertificateChannel = + NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forClient().trustManager(pki.caCertificate())) + .build()) + .build(); + + assertThatThrownBy( + () -> + HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc.newBlockingStub( + noCertificateChannel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .readHistoricalOriginalStartSessionOwnerEvidence(toWireRequest())) + .satisfies( + failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as("server requires a trusted client certificate") + .isTrue()); + + verifyNoInteractions(owner); + } + + @Test + void authenticatedWorldPeerWithEndUserContextNeverReachesOwner() throws Exception { + startReceiver(true); + + try (var client = newClient(pki.world())) { + client.init(); + assertThatThrownBy(() -> client.read(REQUEST)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + + verifyNoInteractions(owner); + } + + private void startReceiver(boolean injectEndUserContext) throws Exception { + startReceiver(pki.gameSession(), injectEndUserContext); + } + + private void startReceiver(TestIdentity serverIdentity, boolean injectEndUserContext) + throws Exception { + var receiver = new HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService(owner, NAMESPACE); + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext(serverTlsContext(serverIdentity)) + .addService( + ServerInterceptors.intercept( + receiver, + new GrpcPeerIdentityInterceptor(), + endUserContextInterceptor(injectEndUserContext))); + server = builder.build().start(); + } + + private void stopReceiver() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private HistoricalOriginalStartSessionOwnerEvidenceReadClient newClient(TestIdentity identity) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("127.0.0.1:" + server.getPort()); + return new HistoricalOriginalStartSessionOwnerEvidenceReadClient( + endpoints, pki.clientProperties(identity), new GrpcChannelFactory(), NAMESPACE); + } + + private io.grpc.netty.shaded.io.netty.handler.ssl.SslContext serverTlsContext( + TestIdentity serverIdentity) throws Exception { + return GrpcSslContexts.configure( + SslContextBuilder.forServer(serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build(); + } + + private static io.grpc.ServerInterceptor endUserContextInterceptor(boolean inject) { + return new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + return new ForwardingServerCallListener.SimpleForwardingServerCallListener( + next.startCall(call, headers)) { + @Override + public void onHalfClose() { + if (inject) { + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + } + try { + super.onHalfClose(); + } finally { + SessionContext.clear(); + } + } + }; + } + }; + } + + private static HistoricalOriginalStartSessionOwnerEvidence.Request request() { + return new HistoricalOriginalStartSessionOwnerEvidence.Request( + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.fromString("11111111-1111-4111-8111-111111111111"), + NAMESPACE, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "world", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + "start-session-request", + "launch-descriptor", + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)), + UUID.fromString("44444444-4444-4444-8444-444444444444"), + 9L); + } + + private static ReadHistoricalOriginalStartSessionOwnerEvidenceRequest toWireRequest() { + return net.firedevops.firemud.common.gamesession + .HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.toRequest(REQUEST); + } + + private static KeyPair keyPair() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + return generator.generateKeyPair(); + } + + private static TestIdentity issueIdentity( + X500Name authorityName, + PrivateKey authorityKey, + String commonName, + String workloadUri, + boolean server) + throws Exception { + KeyPair pair = keyPair(); + X500Name subject = new X500Name("CN=" + commonName + ", O=FireMUD Test"); + X509Certificate certificate = + issueCertificate( + subject, pair.getPublic(), authorityName, authorityKey, false, workloadUri, server); + return new TestIdentity(commonName, pair.getPrivate(), certificate); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + PrivateKey issuerKey, + boolean ca, + String workloadUri, + boolean server) + throws Exception { + long serial = Math.abs(UUID.randomUUID().getMostSignificantBits()) + 1L; + var builder = + new JcaX509v3CertificateBuilder( + issuer, + java.math.BigInteger.valueOf(serial), + new java.util.Date(System.currentTimeMillis() - 60_000L), + new java.util.Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(ca ? KeyUsage.keyCertSign | KeyUsage.cRLSign : KeyUsage.digitalSignature)); + if (workloadUri != null) { + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + server ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth)); + builder.addExtension( + Extension.subjectAlternativeName, + false, + new GeneralNames( + new GeneralName[] { + new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri), + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1") + })); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerKey))); + } + + private record TestIdentity(String name, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity world, + TestIdentity wrongService, + TestIdentity wrongNamespace, + TestIdentity wrongServiceServer, + TestIdentity wrongNamespaceServer, + TestIdentity gameSession) { + private CommonGrpcClientProperties clientProperties(TestIdentity identity) + throws IOException, CertificateEncodingException { + Path cert = + writePem(identity.name() + ".crt", "CERTIFICATE", identity.certificate().getEncoded()); + Path key = + writePem(identity.name() + ".key", "PRIVATE KEY", identity.privateKey().getEncoded()); + Path ca = writePem("test-ca.crt", "CERTIFICATE", caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(cert.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + + private Path writePem(String filename, String label, byte[] bytes) throws IOException { + String encoded = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + Path path = tempDirectory.resolve(filename); + Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + encoded + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + return path; + } + } +} From 378b67cbbf0134b2366a526e394f4211e1fa37fa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:23:31 +1300 Subject: [PATCH 115/129] Prove native Account selected-publication order transport and exact retry --- ...ame-authoring-publishing-and-activation.md | 2 + ...ctedDraftPublicationOrderGrpcMtlsTest.java | 578 ++++++++++++++++++ .../AccountControlUiOriginalOrderFixture.java | 12 + ...licationExportPostgresIntegrationTest.java | 165 +++-- 4 files changed, 716 insertions(+), 41 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java 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 ad073ef866..fcb11abd18 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The genuine-release definition now acquires its distinct selected-publication order through the real file-backed Game Design-to-Account client and unregistered Account producer, rather than a local incoming-peer context. Account captures its environment internally and strictly rereads the immutable Game Design selection before its existing authorization transaction. A fresh-correlation retry compares complete canonical order bytes, operation and fence identities, one retained authorization row and unchanged held-source keys. Upstream Account actor, identity, platform and legal inputs remain test-created; neither this definition nor its compilation proves live authority or agreement. The affected Account/Game Design full check passes in 3 minutes 51 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. Account executes 1,397 unit cases and twelve non-container integration cases without failures, errors or skips; 289 container-dependent integration cases skip. All five new native loopback-mTLS tests execute across seven scenarios through the actual producer and client: the exact Game Design peer reaches environment capture and an unresolved mocked owner; wrong-service and wrong-namespace callers, missing client certificates and missing protected creator metadata reach no owner; trusted wrong-service and wrong-namespace Account servers fail the client's exact workload pin. These prove transport and denial, not a successful durable authorization. Game Design reuses 585 passing unit results and skips all 153 integration cases, including both genuine scenarios. Physical source, release, preparation and settlement composition, real Entity placement and operational-region delivery remain open; no runtime path is registered or enabled. + The genuine-release definition now obtains the first Game Design selection and exact-replay descriptor through file-backed Game Session mTLS, retains their unchanged request/result bytes through the additive Game Session V46 owner, and independently reads the historical pin through the exact World workload. The later descriptor replay and changed-selection denial now also use that native transport; replay separately reads the complete authored-core projections and compares their exact bytes. Three tuple, attempt and fence negatives deliberately remain local owner probes to retain their precise Account-origin denial assertions, not transport proof. That unregistered producer reconstructs the immutable pin, original Account-attached attempt and launch in one repeatable-read owner snapshot; missing history is not repaired from current reads or mutable runtime status. The definition also composes World's original-operation recovery with native World-to-Account and World-to-Game Session reads, and Account's exact terminal settlement with native Account-to-World readback. Account source protection must remain pending after World `COMMITTED` until the original participation ID/fence is durably settled and independently read back. The distinct unregistered [Account settlement transport](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) now replaces the local test-peer invocation with the file-backed World-to-Account client. The definition compares complete terminal bytes and the original settlement timestamp against independent World and Account reads, then uses a new correlation ID to prove immutable retry and one durable receipt. These definitions retain the original tuple and finite lease and do not enable a runtime path. Neither compiled definitions nor synthetic storage/transport cases prove the complete genuine handoff. The corrected Common Platform, Account and Game Design settlement-transport check passes in 3 minutes 24 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. Account executes 1,392 unit cases, including the three new receiver-ordering cases and four loopback-mTLS cases. The latter use the real file-backed client and receiver with an unresolved mocked owner: exact World identity reaches the lookup, trusted wrong-service or wrong-namespace certificates and authenticated end-user context reach no owner, and a missing certificate fails during TLS before the handler. Common Platform and Game Design reuse 722 and 585 passing unit results, including seven executed new closed-codec and local-client cases from the immediately preceding run. Account's unchanged integration task reuses twelve non-container executions and 289 skips; all 153 Game Design integration cases skip, including both genuine native settlement scenarios. The initial integration-compile failure was two removed imports still required by separate Game Session descriptor probes; restoring those imports changed no guards or assertions. Public gRPC allowlists, proto-time fields and Flyway numbering for twelve sets and 313 files pass. This is transport, compilation, unit and static proof, not genuine PostgreSQL settlement or runtime readiness. diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java new file mode 100644 index 0000000000..ed43b1f7a7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java @@ -0,0 +1,578 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +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.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationOrderGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationOrderService; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Native loopback mTLS transport proof for the unregistered selected-publication producer. */ +class AccountSelectedDraftPublicationOrderGrpcMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_ACCOUNT_URI = + "spiffe://firemud/ns/other-test/sa/account-service"; + private static final String WRONG_SERVER_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String WRONG_CLIENT_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_NAMESPACE_CLIENT_URI = + "spiffe://firemud/ns/other-test/sa/game-design-service"; + + @TempDir static Path temporaryDirectory; + private static TestPki pki; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @Test + void authenticatedGameDesignClientReachesEnvironmentCaptureThenUnresolvedOwner() + throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenThrow(Status.FAILED_PRECONDITION.asRuntimeException()); + + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + var client = newClient(server.port(), pki.gameDesignClient())) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + + assertThat(server.handlerCalls()).hasValue(1); + var calls = inOrder(terms, owner); + calls.verify(terms).captureCurrentEnvironmentBoundary(); + calls.verify(owner).authorize(eq(CREDENTIAL), any(), same(captured)); + } + } + + @Test + void trustedWrongServiceAndNamespaceGameDesignCallersAreDeniedBeforeCapture() throws Exception { + for (TestIdentity identity : List.of(pki.wrongServiceClient(), pki.otherNamespaceClient())) { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + var client = newClient(server.port(), identity)) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(1); + verifyNoInteractions(terms, owner); + } + } + } + + @Test + void missingClientCertificateFailsTlsBeforeReceiverOrOwner() throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + ClientTransport client = newClientWithoutIdentity(server.port())) { + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request()); + + assertThatThrownBy(() -> client.authorize(wire)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "missing client certificate must fail during TLS negotiation: %s", + failure) + .isTrue()); + + assertThat(server.handlerCalls()).hasValue(0); + verifyNoInteractions(terms, owner); + } + } + + @Test + void creatorCredentialMetadataIsRequiredBeforeEnvironmentCapture() throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + ClientTransport client = newClientWithIdentity(server.port(), pki.gameDesignClient())) { + assertThatThrownBy( + () -> client.authorize(AccountSelectedPublicationOrderGrpcCodec.toRequest(request()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + assertThat(server.handlerCalls()).hasValue(1); + verifyNoInteractions(terms, owner); + } + } + + @Test + void clientRejectsTrustedWrongServiceAndNamespaceAccountServerIdentities() throws Exception { + for (TestIdentity identity : List.of(pki.wrongServiceServer(), pki.otherNamespaceServer())) { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(identity, owner, terms); + var client = newClient(server.port(), pki.gameDesignClient())) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(0); + verifyNoInteractions(terms, owner); + } + } + } + + private static TransportServer startServer( + TestIdentity serverIdentity, + AccountSelectedDraftPublicationOrderService owner, + AccountHostedTermsService terms) + throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + ServerInterceptor countHandlerCalls = + new ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + handlerCalls.incrementAndGet(); + return next.startCall(call, headers); + } + }; + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new AccountSelectedDraftPublicationOrderGrpcService(owner, terms, NAMESPACE), + countHandlerCalls, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new TransportServer(server, handlerCalls); + } + + private static AccountSelectedPublicationOrderClient newClient(int port, TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + return new AccountSelectedPublicationOrderClient( + endpoints, + pki.clientProperties(temporaryDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ClientTransport newClientWithoutIdentity(int port) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCaCert(pki.caCertificatePem().toString()); + ManagedChannel channel = + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false); + return new ClientTransport(channel); + } + + private static ClientTransport newClientWithIdentity(int port, TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var channel = + new GrpcChannelFactory() + .buildChannel( + endpoints.getAccountService(), + 6565, + pki.clientProperties(temporaryDirectory, identity), + false); + return new ClientTransport(channel); + } + + private static AccountSelectedPublicationOrderGrpcCodec.Request request() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19, "tenant-key", 42, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "fixture", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, CREDENTIAL); + } + + private static final String CREDENTIAL = "original.secret.credential"; + + private record TransportServer(Server server, AtomicInteger handlerCalls) + implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private void authorize( + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest request) { + AccountSelectedPublicationOrderServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .authorizeSelectedPublication(request); + } + + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback gRPC client did not terminate"); + } + } + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + Path caCertificatePem, + TestIdentity accountServer, + TestIdentity wrongServiceServer, + TestIdentity otherNamespaceServer, + TestIdentity gameDesignClient, + TestIdentity wrongServiceClient, + TestIdentity otherNamespaceClient) { + private static final String STORE_PASSWORD = "test-only-store-password"; + + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("selected-publication-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD selected publication test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("selected-publication-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + var ca = readCertificate(caFile); + return new TestPki( + ca, + caFile, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "wrong-service-server", WRONG_SERVER_URI, true), + issueIdentity( + directory, caStore, caFile, "other-namespace-server", WRONG_ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false), + issueIdentity( + directory, caStore, caFile, "wrong-service-client", WRONG_CLIENT_URI, false), + issueIdentity( + directory, + caStore, + caFile, + "other-namespace-client", + OTHER_NAMESPACE_CLIENT_URI, + false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + writePem( + directory.resolve(identity.alias() + ".client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + writePem( + directory.resolve(identity.alias() + ".client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()) + .toString()); + tls.setCaCert(caCertificatePem.toString()); + tls.setPlaintext(false); + return tls; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + alias, + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + ArrayList command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { + process.destroyForcibly(); + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n"); + } + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 6776a5a194..8517209c2d 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.grpc.BindableService; import io.grpc.Context; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; @@ -437,6 +438,17 @@ public AccountPublicationAuthorizationBinding authorizePublication( } } + /** Real unregistered Account selected-publication producer with internally captured terms. */ + public BindableService selectedPublicationOrderProducer( + AuthoredDraftPublishSelectionReadClient selectionClient, String namespace) { + var owner = + new AccountPublicationAuthorizationService( + actors, f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + var composition = + new AccountSelectedDraftPublicationOrderService(selectionClient, owner, namespace); + return new AccountSelectedDraftPublicationOrderGrpcService(composition, f.terms, namespace); + } + /** Real exact retained-order read owner; no publication registration or settlement is implied. */ public AccountPublicationAuthorizationReadService heldPublicationOwner(String namespace) { return new AccountPublicationAuthorizationReadService( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index df11e16e53..16f36b14a4 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -157,6 +157,8 @@ import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; @@ -428,34 +430,36 @@ * Real original GD+World source settlement and Account/GL intake-to-GD-receipt, followed by actual * selected inventory/export, the owner-local publication finalizer, descriptor SQL storage, and the * owner-local complete launch-binding read. The distinct Account publication order comes from the - * actual Account owner fixture; its inbound Game Design peer and upstream selection/platform/legal - * evidence are supplied by test context. The immutable selection read and held-order reads use - * loopback mTLS. World freeze, immutable inventory and published selector use their actual owner - * services over loopback mTLS, with the canonical frozen selector captured owner-locally from the - * committed freeze and retained APPLIED graph. Entity/Automation source disclosure uses the genuine - * Account issuer and retained preliminary reservations, then loopback mTLS for both the Account - * permission hop and the Game Design source hop. Automation additionally composes real Account - * finalization, the actual recipient-specific World closure/inventory reader, the Automation - * empty-source receipt owner, and Account terminal settlement. Its positive Account authorization - * command creates a fresh reservation through the native producer. Automation retention and Account - * settlement each traverse their native command receivers over loopback mTLS. The earlier - * disclosure/abort setup uses stipulated incoming Game Design peer contexts and is not either - * positive authorization operation. Entity retention also traverses the native Account, Game - * Design, Entity, World and settlement boundaries over loopback mTLS, with an isolated Entity - * PostgreSQL schema and migration path. Entity and Automation publication digests use their native - * mTLS selected-empty owner readers and exact retained receipts; nonempty owner publication remains - * outside this proof. StartSession issuance and redemption use the real Account owner and retained - * rows under the genuine Logging PostgreSQL reservation owner and its native file-backed mTLS - * current-claim reader; issue uses the existing Logging/Admin mTLS client and redemption uses a - * Game Session mTLS stub pinned to Account. The read-only projection uses the real Account receiver - * over Game Design mTLS. MinIO object-store I/O is real. The complete launch-binding case wires the - * actual Game Design handler and World Management mTLS client on this fixture's loopback server to - * the actual owner implementation in an explicitly established read-only repeatable-read snapshot; - * unrelated handler dependencies are isolated. The World preparation composition reuses the genuine - * persisted source, frozen graph, and complete released pair through actual World owner services. - * Its original Account tuple is issued and redeemed by the real Account owner after the native - * Logging current-claim read through exact same-namespace Account transports; Game Session reserves - * that exact tuple in an isolated V35 store and attaches the exact redeemed projection. Account's + * actual Account owner fixture over same-namespace Game Design mTLS; Account captures hosted terms + * internally and strictly rereads the immutable selection from Game Design over mTLS. Its upstream + * Account actor, identity, platform and legal inputs remain test-created and do not prove live + * authority or agreement. Held-order reads also use loopback mTLS. World freeze, immutable + * inventory and published selector use their actual owner services over loopback mTLS, with the + * canonical frozen selector captured owner-locally from the committed freeze and retained APPLIED + * graph. Entity/Automation source disclosure uses the genuine Account issuer and retained + * preliminary reservations, then loopback mTLS for both the Account permission hop and the Game + * Design source hop. Automation additionally composes real Account finalization, the actual + * recipient-specific World closure/inventory reader, the Automation empty-source receipt owner, and + * Account terminal settlement. Its positive Account authorization command creates a fresh + * reservation through the native producer. Automation retention and Account settlement each + * traverse their native command receivers over loopback mTLS. The earlier disclosure/abort setup + * uses stipulated incoming Game Design peer contexts and is not either positive authorization + * operation. Entity retention also traverses the native Account, Game Design, Entity, World and + * settlement boundaries over loopback mTLS, with an isolated Entity PostgreSQL schema and migration + * path. Entity and Automation publication digests use their native mTLS selected-empty owner + * readers and exact retained receipts; nonempty owner publication remains outside this proof. + * StartSession issuance and redemption use the real Account owner and retained rows under the + * genuine Logging PostgreSQL reservation owner and its native file-backed mTLS current-claim + * reader; issue uses the existing Logging/Admin mTLS client and redemption uses a Game Session mTLS + * stub pinned to Account. The read-only projection uses the real Account receiver over Game Design + * mTLS. MinIO object-store I/O is real. The complete launch-binding case wires the actual Game + * Design handler and World Management mTLS client on this fixture's loopback server to the actual + * owner implementation in an explicitly established read-only repeatable-read snapshot; unrelated + * handler dependencies are isolated. The World preparation composition reuses the genuine persisted + * source, frozen graph, and complete released pair through actual World owner services. Its + * original Account tuple is issued and redeemed by the real Account owner after the native Logging + * current-claim read through exact same-namespace Account transports; Game Session reserves that + * exact tuple in an isolated V35 store and attaches the exact redeemed projection. Account's * current-attempt observation and World participation acquisition use their native same-namespace * mTLS clients and receivers. Game Session also resolves the actual fresh Game Design tenant * receipt over mTLS, stores and independently reads its numeric tenant association, then reads the @@ -664,6 +668,9 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( try (var loggingClaimClient = currentClaimGrpcClient(loggingServer.getPort(), pki); var startSessionAuthorizationTransport = new NativeAccountStartSessionAuthorizationTransport(endpoints, pki, channels); + var accountSelectedPublicationOrderClient = + new AccountSelectedPublicationOrderClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); var gameDesignStartSessionReadTransport = new NativeGameDesignStartSessionReadTransport(endpoints, pki, channels); var worldToAccountParticipationHistoryClient = @@ -766,6 +773,7 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( var gameSessionActivationClient = canonicalActivationClient(worldServer, pki.client("game-session-service"), channels)) { ReflectionTestUtils.invokeMethod(loggingClaimClient, "init"); + accountSelectedPublicationOrderClient.init(); worldToAccountParticipationHistoryClient.init(); worldToGameSessionOwnerEvidenceClient.init(); accountToWorldExecutionTerminalClient.init(); @@ -1119,7 +1127,8 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( NAMESPACE), NAMESPACE), account.selectedOwnerIntakeAuthorizationProducerReceiver( - observedAccountToGdSource, NAMESPACE)); + observedAccountToGdSource, NAMESPACE), + account.selectedPublicationOrderProducer(accountSelectionReadClient, NAMESPACE)); var coordinator = new DraftCommitCoordinatorRepository(gd.dsl()); var gdTerminals = new GameDesignDraftTerminalOutcomeRepository(gd.dsl()); @@ -1749,13 +1758,86 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( var selectionBinding = AuthoredDraftPublishSelectionBinding.fromStored( selection.canonicalJson(), selection.digest()); + var accountPublicationRowsBefore = + accountAccess + .sources() + .dsl + .fetch( + "SELECT operation_id, binding FROM account_selected_publication_authorizations" + + " WHERE tenant_uuid = ? AND publish_request_id = ?", + selection.intent().canonicalTenantId(), + selection.intent().publishRequestId()); + assertThat(accountPublicationRowsBefore).isEmpty(); + var accountPublicationRequest = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selectionBinding, originalOrder.originalCreatorCredential()); var accountPublicationOrder = - account.authorizePublication(selectionBinding, accountSelectionReadClient, NAMESPACE); + accountSelectedPublicationOrderClient.authorize(accountPublicationRequest); assertThat(accountPublicationOrder.input().selection().canonicalBytes()) .containsExactly(selection.canonicalBytes()); assertThat(accountPublicationOrder.operationId()).isNotEqualTo(original.operationId()); assertThat(accountPublicationOrder.fenceId()).isNotEqualTo(original.fenceId()); account.assertPublicationSourcesHeld(accountPublicationOrder); + var accountPublicationRowsAfterFirst = + accountAccess + .sources() + .dsl + .fetch( + "SELECT operation_id, binding FROM account_selected_publication_authorizations" + + " WHERE tenant_uuid = ? AND publish_request_id = ?", + selection.intent().canonicalTenantId(), + selection.intent().publishRequestId()); + assertThat(accountPublicationRowsAfterFirst).hasSize(1); + var accountPublicationSourceKeysAfterFirst = + accountAccess + .sources() + .dsl + .fetch( + "SELECT source_key FROM account_selected_publication_sources" + + " WHERE operation_id = ? ORDER BY source_key", + accountPublicationOrder.operationId()) + .stream() + .map(row -> row.get("source_key", String.class)) + .toList(); + var accountPublicationRetryRequest = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selectionBinding, originalOrder.originalCreatorCredential()); + assertThat(accountPublicationRetryRequest.requestId()) + .isNotEqualTo(accountPublicationRequest.requestId()); + var accountPublicationRetry = + accountSelectedPublicationOrderClient.authorize(accountPublicationRetryRequest); + assertThat(accountPublicationRetry.canonicalBytes()) + .containsExactly(accountPublicationOrder.canonicalBytes()); + assertThat(accountPublicationRetry.operationId()) + .isEqualTo(accountPublicationOrder.operationId()); + assertThat(accountPublicationRetry.fenceId()).isEqualTo(accountPublicationOrder.fenceId()); + var accountPublicationRowsAfterRetry = + accountAccess + .sources() + .dsl + .fetch( + "SELECT operation_id, binding FROM account_selected_publication_authorizations" + + " WHERE tenant_uuid = ? AND publish_request_id = ?", + selection.intent().canonicalTenantId(), + selection.intent().publishRequestId()); + assertThat(accountPublicationRowsAfterRetry).hasSize(1); + assertThat(accountPublicationRowsAfterRetry.get(0).get("operation_id", UUID.class)) + .isEqualTo(accountPublicationOrder.operationId()); + assertThat(accountPublicationRowsAfterRetry.get(0).get("binding", byte[].class)) + .containsExactly(accountPublicationOrder.canonicalBytes()); + var accountPublicationSourceKeysAfterRetry = + accountAccess + .sources() + .dsl + .fetch( + "SELECT source_key FROM account_selected_publication_sources" + + " WHERE operation_id = ? ORDER BY source_key", + accountPublicationOrder.operationId()) + .stream() + .map(row -> row.get("source_key", String.class)) + .toList(); + assertThat(accountPublicationSourceKeysAfterRetry) + .containsExactlyElementsOf(accountPublicationSourceKeysAfterFirst); var intakeRequest = GameLogicIntakeAuthorizationEvidence.Request.create( NAMESPACE, UUID.randomUUID(), selection.selectedCommit()); @@ -3879,15 +3961,14 @@ public void attachAccountRedemptionProjection( .containsExactlyElementsOf(completeBindingOwnerRowsBefore); // World source, publication, released-pair proof, fresh tenant association and - // public-realm catalog above use the actual owners. The original StartSession tuple is - // issued/redeemed by Account after the actual native Logging claim read, under the - // fixture's stipulated Account peer contexts. Game Session reserves the exact tuple and - // attaches Account's redeemed projection in its isolated V35 repository; Account's - // current - // attempt observation and World participation acquisition then traverse native - // same-namespace mTLS receivers. The launch below is produced and independently read by - // Game Session, then consumed through its exact-peer native reader. Retained Account - // participation is point-in-time evidence, not a continuous remote lock. + // public-realm catalog above use the actual owners. After the actual native Logging claim + // read, the original StartSession tuple is issued through the Logging/Admin mTLS client + // and redeemed through the Game Session stub pinned to Account. Game Session reserves the + // exact tuple and attaches Account's redeemed projection in its isolated V35 repository; + // Account's current-attempt observation and World participation acquisition then traverse + // native same-namespace mTLS receivers. The launch below is produced and independently + // read by Game Session, then consumed through its exact-peer native reader. Retained + // Account participation is point-in-time evidence, not a continuous remote lock. CompleteLaunchBindingEvidence completeLaunchEvidence = new CompleteLaunchBindingEvidence( completeBinding.descriptor(), completeBinding.releaseAttestation()); @@ -4811,8 +4892,10 @@ public void close() {} .isZero(); // The World owner obtains a first full Account protection receipt over authenticated - // mTLS, then commits the exact local PREPARING-to-ACTIVE CAS. No source vector or - // Account authority is stipulated or supplied by this fixture. + // mTLS, then commits the exact local PREPARING-to-ACTIVE CAS. The activation caller + // supplies neither Account's source vector nor its protection receipt; the upstream + // Account actor, identity, and hosted-terms inputs used by this test fixture remain + // test-created. { var firstTerminal = gameSessionToWorldProtectedActivationClient.activate(activationInput); From 419404eb2a9d9f48325f52985dbfc07a8bc3d7be Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 19:19:04 +1300 Subject: [PATCH 116/129] Complete native selected publication and exact Account settlement transport --- .../account-service/api-contracts.md | 4 + .../world-management-service/api-contracts.md | 4 + ...ame-authoring-publishing-and-activation.md | 6 + ...ected_publication_settlement_service.proto | 31 ++ ...lication_terminal_completion_service.proto | 34 ++ ...ectedPublicationSettlementGrpcService.java | 97 ++++++ ...rldAcquisitionPostgresIntegrationTest.java | 1 + ...dPublicationSettlementGrpcServiceTest.java | 142 ++++++++ .../AccountControlUiOriginalOrderFixture.java | 22 ++ ...ntSelectedPublicationSettlementClient.java | 157 +++++++++ ...electedPublicationSettlementGrpcCodec.java | 244 ++++++++++++++ ...ldPublicationTerminalCompletionClient.java | 159 +++++++++ ...ublicationTerminalCompletionGrpcCodec.java | 238 +++++++++++++ ...tedPublicationSettlementGrpcCodecTest.java | 198 +++++++++++ ...cationTerminalCompletionGrpcCodecTest.java | 212 ++++++++++++ ...licationExportPostgresIntegrationTest.java | 168 ++++++++- ...licationTerminalCompletionGrpcService.java | 124 +++++++ .../WorldPublicationTerminalService.java | 11 + ...DesignPublicationTerminalVerifierTest.java | 6 +- ...essionProtectedActivationGrpcMtlsTest.java | 39 ++- ...icationTerminalCompletionGrpcMtlsTest.java | 319 ++++++++++++++++++ ...tionTerminalCompletionGrpcServiceTest.java | 137 ++++++++ 22 files changed, 2344 insertions(+), 9 deletions(-) create mode 100644 protos/account/v1/selected_publication_settlement_service.proto create mode 100644 protos/world-management/v1/publication_terminal_completion_service.proto create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcService.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcMtlsTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcServiceTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 727f4752db..a9520326ac 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -90,6 +90,10 @@ Account acquires this distinct publication order from the authenticated acting a Settlement compares two distinct authenticated owner results: Game Design's original immutable terminal and World's independently committed terminal for the same complete publication operation. `PUBLISHED` must agree with World `PUBLISHED`; Game Design `NO_PUBLICATION` must agree with World `ABORTED`. Both must bind the same complete original operation and terminal bytes, including the original authenticated World inventory under the [Game Design operation binding](../game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state); incomplete historical evidence cannot authorize a new settlement. Account obtains the owner reads outside SQL, then serializes its immutable settlement receipt with the original order and sorted source locks. Only that exact committed receipt removes this order's pending participation; it does not rewrite the original authorization or clear another operation. Read correlation IDs are not settlement mutation identities: exact retries replay the original receipt even when new owner-read correlations are used. Once settled, an external `HELD` read must deny; internal exact historical validation remains available for recovery without minting fresh authority. Any disagreement or unresolved owner result preserves participation and grants no admission. +The standalone, unregistered [`AccountSelectedPublicationSettlementService.SettleSelectedPublication`](../../../../protos/account/v1/selected_publication_settlement_service.proto) carries the complete original operation, closed schema version 1, exact namespace and a fresh nonzero transport correlation UUID. Account authenticates the exact same-namespace Game Design workload before decoding and rejects authenticated end-user context; caller-supplied owner outcomes are not accepted. Its existing settlement owner obtains both independent authenticated terminal reads outside SQL, commits the original immutable receipt, and independently reads it back before returning. The response echoes the complete request and original `account-selected-publication-settlement/v1` receipt; the client checks its full Account binding, operation, Game Design terminal, World phase and World terminal, not merely an outcome or digest. Correlation changes do not change the durable settlement identity. Registration, complete transport message budgets and executed producer/consumer proof remain separate gates in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); successful historical recovery grants no runtime admission. + +This transport bounds each complete serialized request and response to 32 MiB, including the unchanged receipt and complete request echo. The full receipt repeats owner evidence; a terminal that fits another transport does not necessarily fit this response. Oversized results deny delivery without truncating or rewriting the stored receipt, minting another operation or claiming successful readback. This transport limit does not change canonical retained-content schemas. Future registration must prove compatible server and dependent owner-read budgets, not merely configure this client's receive limit. + The selected-order composition authenticates the exact same-namespace Game Design caller, obtains the [immutable selected-Draft owner read](../game-design-service/api-contracts.md#immutable-selected-draft-publication-read) outside Account SQL, then passes the unchanged creator credential and exact retained selection to Account's current-actor/source-hold owner transaction. `SELECTED` alone is not actor authorization. No database lock may span that read, and unavailable or substituted selection evidence cannot create an order. Implementation and executed proof remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). The standalone, unregistered [`AccountSelectedPublicationOrderService.AuthorizeSelectedPublication`](../../../../protos/account/v1/selected_publication_order_service.proto) producer accepts schema version 1, the exact target namespace, a fresh nonzero transport correlation UUID and complete canonical selected-Draft bytes. The unchanged original creator credential travels only in protected, method-specific per-call metadata, never in protobuf request or response text; metadata must not be logged. Only the verified same-namespace Game Design workload may call it; Account authenticates before accessing or decoding credential metadata, decoding the request or capturing authority, and World has no producer permission. The receiver binds its credential interceptor internally; missing, duplicate, malformed or oversized credentials deny without owner mutation. Account captures its current environment boundary internally and validates it through the existing owner transaction; no caller-supplied environment or currentness value is authority. The response echoes the complete non-secret request tuple and exact canonical Account authorization binding, never the credential. Transport correlation does not change the durable publication identity: retry retains the original order, source evidence and fence. Unknown or noncanonical fields, changed response correlation or selection, unavailable currentness and substituted server identity fail closed. Calls require file-backed mutual TLS with exact Account server identity, a bounded five-second deadline and no ambient SQL transaction. Future registration must account for the transport metadata budget; a lower server limit still fails closed rather than truncating credentials. This transport defines no runtime registration or production environment-authority provider. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index da9d105046..d1026dcc63 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -142,6 +142,10 @@ Terminal retries are exact only when the complete request, digest, fence, outcom First terminal completion and every terminal retry/readback must also compare the complete distinct Account publication-order bytes, operation ID and fence against the immutable qualification retained with the first World freeze. The older Account Draft `COMMIT_ORDER` inside the World application evidence is not that publication order. The [complete Game Design operation binding](../game-design-service/version-control.md#publication-freeze-and-owner-handoff-target-state) includes World's original canonical public inventory and digest; World compares that complete projection with its own retained inventory, not a caller reconstruction or later source sample. An unqualified historical freeze cannot be upgraded by supplying later terminal evidence. World verifies the original Game Design terminal through an authenticated owner read outside SQL; that immutable result remains historical evidence through the local commit, not a remote Account lock or permission to release Account source participation. +The standalone, unregistered [`WorldPublicationTerminalCompletionService.CompleteVersionPublication`](../../../../protos/world-management/v1/publication_terminal_completion_service.proto) transports this same owner operation. Its closed schema-version-1 request carries the exact namespace, a fresh nonzero transport correlation UUID, complete original operation bytes and complete Game Design terminal bytes. World authenticates the exact same-namespace Game Design workload before decoding and rejects authenticated end-user context. The complete operation carries the original tenant, version, publication request/workflow, digest, fence and qualified inventory; no caller-selected field subset replaces that binding. The receiver independently reads Game Design through the existing verifier before owner SQL and returns only the exact terminal retained by World, echoing the complete request. A fresh correlation does not allocate another publication or fence. `FROZEN`, a release object, or a supplied terminal alone is not World completion. Runtime registration and physical composition proof remain gated in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + +This transport bounds each complete serialized request and response to 32 MiB, including echo fields and framing. That is a transport admission limit, not a new canonical release-content limit: an operation whose complete request or result cannot fit fails closed without truncation, alternate evidence or a claimed completion response. Future registration must align the server receive limit and all dependent owner-read budgets; a client receive limit alone is not that proof. + Account settlement requires a separate World-authenticated terminal read. Its versioned request binds the namespace, non-nil read correlation ID, complete original publication operation and exact expected Game Design terminal bytes; those bytes identify the lookup and do not prove a World commit. Only the authenticated same-namespace Account workload may call it, and World must authenticate that caller before decoding or reading storage. World returns the exact request and original stored terminal bytes only after its own independent owner snapshot proves the qualified attempt and matching terminal phase (`PUBLISHED` or `ABORTED`). Missing, pending, unqualified, substituted, corrupt or unavailable owner evidence supplies no settlement result. The read never completes publication, releases an Account hold or authorizes admission; registration and executed proof remain separately gated in the implementation tracker. World Management also exposes a read-only design-time synchronization surface so Game Design can validate convergence before publish: 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 fcb11abd18..ba0d72d265 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 @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Selected publication now has distinct unregistered Game Design-to-World completion and Game Design-to-Account settlement transports. World independently authenticates and reads the complete immutable Game Design terminal through its existing verifier before committing its local terminal; Account independently reads both owners outside SQL before serializing settlement against the original source authorization. Closed codecs verify complete operation echoes, terminal evidence and the existing six-frame Account receipt. Fresh transport correlation does not replace the original operation or permit another mutation. Both genuine-release definitions compose these native handoffs after actual publication and before StartSession, with independent Account receipt and timestamp readback; they remain container-dependent definitions until physically executed. The 32 MiB per-message budgets are transport limits, not a canonical terminal-content cap, and do not qualify dependent terminal readers or production registration. Runtime paths remain unregistered and denied. + +The corrected four-module check passes in 2 minutes 44 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. World freshly executes 688 unit cases, including seven loopback-mTLS completion cases and three receiver-denial cases; Common Platform, Account and Game Design reuse 730, 1,399 and 585 successful unit results from the preceding run. The new Common codecs' eight cases and Account receiver's two cases executed in that preceding run. Thus the corrected state has 3,402 passing unit cases, with no unit skips. Account freshly executes twelve non-container integration cases and skips 289 container cases; World reuses one execution and 229 skips; Game Design skips all 153 integration cases, including both genuine-release scenarios. Initial fixture compilation failures were invalid channel cleanup/TLS argument order and a duplicate local variable; the repairs changed no guards or assertions. World loopback success uses a mocked owner and synthetic terminal evidence: it proves exact-peer transport, not durable publication completion. The numbered-history correction compiles but its PostgreSQL cases remain unexecuted locally. All four genuine handoffs remain open pending physical composition, real Entity placement and operational-region delivery. + +Exact source `378b67cbbf0134b2366a526e394f4211e1fa37fa` failed [Validation run 38114653346](https://github.com/benhook1013/FireMUD/actions/runs/38114653346) in `AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest`: the Logging fixture included Flyway's successful, versionless schema-creation entry in its numbered migration assertion. The correction excludes only versionless history while preserving the exact versions 1 through 4 assertion, and applies to the same query in the genuine-release fixture. The reported Account job was cancelled; draft-fence XML was absent. This failed run establishes neither current-source physical qualification nor complete genuine handoff proof. + The genuine-release definition now acquires its distinct selected-publication order through the real file-backed Game Design-to-Account client and unregistered Account producer, rather than a local incoming-peer context. Account captures its environment internally and strictly rereads the immutable Game Design selection before its existing authorization transaction. A fresh-correlation retry compares complete canonical order bytes, operation and fence identities, one retained authorization row and unchanged held-source keys. Upstream Account actor, identity, platform and legal inputs remain test-created; neither this definition nor its compilation proves live authority or agreement. The affected Account/Game Design full check passes in 3 minutes 51 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. Account executes 1,397 unit cases and twelve non-container integration cases without failures, errors or skips; 289 container-dependent integration cases skip. All five new native loopback-mTLS tests execute across seven scenarios through the actual producer and client: the exact Game Design peer reaches environment capture and an unresolved mocked owner; wrong-service and wrong-namespace callers, missing client certificates and missing protected creator metadata reach no owner; trusted wrong-service and wrong-namespace Account servers fail the client's exact workload pin. These prove transport and denial, not a successful durable authorization. Game Design reuses 585 passing unit results and skips all 153 integration cases, including both genuine scenarios. Physical source, release, preparation and settlement composition, real Entity placement and operational-region delivery remain open; no runtime path is registered or enabled. The genuine-release definition now obtains the first Game Design selection and exact-replay descriptor through file-backed Game Session mTLS, retains their unchanged request/result bytes through the additive Game Session V46 owner, and independently reads the historical pin through the exact World workload. The later descriptor replay and changed-selection denial now also use that native transport; replay separately reads the complete authored-core projections and compares their exact bytes. Three tuple, attempt and fence negatives deliberately remain local owner probes to retain their precise Account-origin denial assertions, not transport proof. That unregistered producer reconstructs the immutable pin, original Account-attached attempt and launch in one repeatable-read owner snapshot; missing history is not repaired from current reads or mutable runtime status. The definition also composes World's original-operation recovery with native World-to-Account and World-to-Game Session reads, and Account's exact terminal settlement with native Account-to-World readback. Account source protection must remain pending after World `COMMITTED` until the original participation ID/fence is durably settled and independently read back. The distinct unregistered [Account settlement transport](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references) now replaces the local test-peer invocation with the file-backed World-to-Account client. The definition compares complete terminal bytes and the original settlement timestamp against independent World and Account reads, then uses a new correlation ID to prove immutable retry and one durable receipt. These definitions retain the original tuple and finite lease and do not enable a runtime path. Neither compiled definitions nor synthetic storage/transport cases prove the complete genuine handoff. diff --git a/protos/account/v1/selected_publication_settlement_service.proto b/protos/account/v1/selected_publication_settlement_service.proto new file mode 100644 index 0000000000..205166bb73 --- /dev/null +++ b/protos/account/v1/selected_publication_settlement_service.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone authenticated settlement of one exact selected-publication authorization. +service AccountSelectedPublicationSettlementService { + rpc SettleSelectedPublication(SettleSelectedPublicationRequest) + returns (SettleSelectedPublicationResponse); +} + +message SettleSelectedPublicationRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Independent transport correlation; the retained Account order remains the settlement key. + string request_id = 3; + // Complete canonical game-design-publication-operation/v2 bytes. + bytes original_operation = 4; +} + +message SettleSelectedPublicationResponse { + // Exact unchanged request echo. + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + bytes original_operation = 4; + // Existing six-frame account-selected-publication-settlement/v1 receipt. + bytes settlement_receipt = 5; +} diff --git a/protos/world-management/v1/publication_terminal_completion_service.proto b/protos/world-management/v1/publication_terminal_completion_service.proto new file mode 100644 index 0000000000..8f2d180e3a --- /dev/null +++ b/protos/world-management/v1/publication_terminal_completion_service.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +package world_management.v1; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Standalone authenticated completion of one exact World publication freeze. +service WorldPublicationTerminalCompletionService { + rpc CompleteVersionPublication(CompleteVersionPublicationRequest) + returns (CompleteVersionPublicationResponse); +} + +message CompleteVersionPublicationRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Independent transport correlation; the original operation remains the mutation identity. + string request_id = 3; + // Complete canonical game-design-publication-operation/v2 bytes. + bytes original_operation = 4; + // Complete canonical immutable Game Design terminal bound to the original operation. + bytes game_design_terminal_evidence = 5; +} + +message CompleteVersionPublicationResponse { + // The complete original request tuple is echoed byte-for-byte. + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + bytes original_operation = 4; + bytes game_design_terminal_evidence = 5; + // The exact terminal result retained by the World owner. + bytes stored_terminal_evidence = 6; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java new file mode 100644 index 0000000000..56eb571a39 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementGrpcCodec; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementGrpcCodec.Request; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone unregistered authenticated ingress for exact selected-publication settlement. */ +public final class AccountSelectedPublicationSettlementGrpcService + extends AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceImplBase { + private final AccountSelectedDraftPublicationSettlementService owner; + private final String namespace; + + public AccountSelectedPublicationSettlementGrpcService( + AccountSelectedDraftPublicationSettlementService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-publication settlement owner required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void settleSelectedPublication( + SettleSelectedPublicationRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + if (SessionContext.hasAuthenticatedCallerContext() + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + if (wire == null + || wire.getSerializedSize() + > AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + + final Request request; + try { + request = AccountSelectedPublicationSettlementGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + + try { + byte[] receipt = owner.settle(request.originalOperation()); + observer.onNext(AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.INVALID_ARGUMENT + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + deny(observer, Status.fromCode(code)); + } catch (IllegalArgumentException invalidEvidence) { + deny(observer, Status.FAILED_PRECONDITION); + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + } + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError( + status + .withDescription("Account selected-publication settlement denied or unavailable") + .asRuntimeException()); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java index ca199bed2d..a0d111343d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java @@ -703,6 +703,7 @@ private static LoggingReservationStore loggingReservationStore() throws Exceptio assertThat( dsl.fetch( "SELECT version FROM flyway_schema_history WHERE success " + + "AND version IS NOT NULL " + "ORDER BY installed_rank") .getValues("version", String.class)) .containsExactly("1", "2", "3", "4"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java new file mode 100644 index 0000000000..285cca35ad --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java @@ -0,0 +1,142 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationSettlementService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedPublicationSettlementGrpcService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Receiver identity/ordering units; synthetic peer context is not authenticated TLS proof. */ +class AccountSelectedPublicationSettlementGrpcServiceTest { + private static final String NAMESPACE = "publication-runtime"; + private static final String GAME_DESIGN_URI = + "spiffe://firemud/ns/publication-runtime/sa/game-design-service"; + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactGameDesignBeforeMalformedRequestOrOwnerAccess() { + var owner = mock(AccountSelectedDraftPublicationSettlementService.class); + var receiver = new AccountSelectedPublicationSettlementGrpcService(owner, NAMESPACE); + var malformed = SettleSelectedPublicationRequest.getDefaultInstance(); + + assertCode(Status.Code.UNAUTHENTICATED, invoke(receiver, null, malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, + identity("spiffe://firemud/ns/other-runtime/sa/game-design-service"), + malformed)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, + identity("spiffe://firemud/ns/publication-runtime/sa/" + workload), + malformed)); + } + SessionContext.setContext("test-user", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, invoke(receiver, identity(GAME_DESIGN_URI), malformed)); + verifyNoInteractions(owner); + } + + @Test + void deniesAmbientSqlAndClosedEnvelopeErrorsBeforeOwnerCall() { + var owner = mock(AccountSelectedDraftPublicationSettlementService.class); + var receiver = new AccountSelectedPublicationSettlementGrpcService(owner, NAMESPACE); + var peer = identity(GAME_DESIGN_URI); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, peer, null)); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, peer, null)); + TransactionSynchronizationManager.clearSynchronization(); + + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, peer, null)); + var unknown = + SettleSelectedPublicationRequest.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, peer, unknown)); + verifyNoInteractions(owner); + } + + private static Invocation invoke( + AccountSelectedPublicationSettlementGrpcService receiver, + GrpcPeerIdentity peer, + SettleSelectedPublicationRequest request) { + var result = new Invocation(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + receiver.settleSelectedPublication(request, result); + } finally { + context.detach(previous); + } + return result; + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, Invocation invocation) { + assertThat(invocation.error).isNotNull(); + assertThat(invocation.error.statusRuntimeException()).isTrue(); + assertThat(invocation.error.code()).isEqualTo(expected); + assertThat(invocation.response).isNull(); + assertThat(invocation.completed).isFalse(); + } + + private record ObservedError(boolean statusRuntimeException, Status.Code code) {} + + private static final class Invocation + implements StreamObserver { + private SettleSelectedPublicationResponse response; + private ObservedError error; + private boolean completed; + + @Override + public void onNext(SettleSelectedPublicationResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = + new ObservedError( + failure instanceof StatusRuntimeException, Status.fromThrowable(failure).getCode()); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index 8517209c2d..2330928cd5 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -344,6 +344,13 @@ public void assertOriginalDraftOrderPending(DraftAuthorizationFenceBinding origi assertThat(f.tx(() -> f.fences.readSettlement(original)).name()).isEqualTo("PENDING"); } + /** Reads the independent original Draft settlement without re-running its reconciliation. */ + public void assertOriginalDraftOrderSettled(DraftAuthorizationFenceBinding original) { + var retained = f.tx(() -> f.fences.read(original)); + assertThat(retained.binding()).isEqualTo(original.canonicalBytes()); + assertThat(f.tx(() -> f.fences.readSettlement(original)).name()).isEqualTo("COMMITTED"); + } + /** Uses only actual authenticated terminal clients; it never installs constructed readbacks. */ public void reconcileOriginalDraft( DraftAuthorizationFenceBinding original, @@ -455,6 +462,21 @@ public AccountPublicationAuthorizationReadService heldPublicationOwner(String na new AccountPublicationAuthorizationRepository(f.dsl), f.manager, namespace); } + /** Real unregistered selected-publication settlement receiver over both authenticated owners. */ + public BindableService selectedPublicationSettlementReceiver( + net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadClient gameDesign, + net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient world, + String namespace) { + var owner = + new AccountSelectedDraftPublicationSettlementService( + new AccountPublicationAuthorizationRepository(f.dsl), + gameDesign, + world, + f.manager, + namespace); + return new AccountSelectedPublicationSettlementGrpcService(owner, namespace); + } + /** * Verifies the complete original publication/source vector and guarded mutation denial. The * original Draft is also pending, so writer denial does not isolate publication as its sole diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java new file mode 100644 index 0000000000..279e17b75c --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java @@ -0,0 +1,157 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationSettlementServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for Account-owned selected-publication settlement. */ +public final class AccountSelectedPublicationSettlementClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AccountSelectedPublicationSettlementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AccountSelectedPublicationSettlementClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Account publication settlement client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Account publication settlement stub unavailable"); + } + initialized = true; + } + + /** Returns the exact original six-frame receipt after Account peer and receipt validation. */ + public byte[] settle(AccountSelectedPublicationSettlementGrpcCodec.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account publication settlement requires no owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account publication settlement must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .settleSelectedPublication( + AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); + try { + return AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned an invalid publication settlement receipt", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountSelectedPublicationSettlementServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip") + .withMaxInboundMessageSize(AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Account publication settlement client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Account publication settlement requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Account publication settlement requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Account publication settlement requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "Account publication settlement " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Account publication settlement " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java new file mode 100644 index 0000000000..a9ccc03f4f --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java @@ -0,0 +1,244 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed Account-owned selected-publication settlement transport and receipt validation. */ +public final class AccountSelectedPublicationSettlementGrpcCodec { + /** Shared per-message protobuf budget; oversized complete six-frame receipts fail closed. */ + public static final int MAX_MESSAGE_BYTES = 32 * 1024 * 1024; + + private static final int MESSAGE_ENVELOPE_OVERHEAD_RESERVE = 256; + private static final String RECEIPT_SCHEMA = "account-selected-publication-settlement/v1"; + + private AccountSelectedPublicationSettlementGrpcCodec() {} + + public static SettleSelectedPublicationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var wire = + SettleSelectedPublicationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .build(); + requireWireBudget(wire); + return wire; + } + + /** Receiver authenticates the exact Game Design peer before decoding this request. */ + public static Request fromRequest(SettleSelectedPublicationRequest request) { + Objects.requireNonNull(request, "request"); + requireWireBudget(request); + noUnknownFields(request); + try { + return new Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + canonicalUuid(request.getRequestId()), + request.getOriginalOperation().toByteArray()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Account publication settlement request is invalid", malformed); + } + } + + /** Emits only an exact original receipt whose six canonical frames agree with the request. */ + public static SettleSelectedPublicationResponse toResponse(Request request, byte[] receipt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(receipt, "receipt"); + if ((long) receipt.length + request.originalOperation().length + > MAX_MESSAGE_BYTES - MESSAGE_ENVELOPE_OVERHEAD_RESERVE) { + throw new IllegalArgumentException( + "Account publication settlement response exceeds the 32 MiB wire budget"); + } + var response = + SettleSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setSettlementReceipt(ByteString.copyFrom(receipt)) + .build(); + requireWireBudget(response); + validateReceipt(request, receipt); + return response; + } + + /** Verifies the full echo and returns the exact canonical Account settlement receipt. */ + public static byte[] fromResponse(Request request, SettleSelectedPublicationResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireWireBudget(response); + noUnknownFields(response); + if (response.getSchemaVersion() != request.schemaVersion() + || !request.targetNamespace().equals(response.getTargetNamespace()) + || !request.requestId().toString().equals(response.getRequestId()) + || !Arrays.equals( + request.originalOperation(), response.getOriginalOperation().toByteArray())) { + throw new IllegalArgumentException( + "Account changed the exact publication settlement request"); + } + byte[] receipt = response.getSettlementReceipt().toByteArray(); + validateReceipt(request, receipt); + return receipt.clone(); + } + + private static void validateReceipt(Request request, byte[] receipt) { + if (receipt == null || receipt.length == 0 || receipt.length > MAX_MESSAGE_BYTES) { + throw new IllegalArgumentException( + "Complete bounded Account publication settlement receipt required"); + } + final byte[] accountBinding; + final byte[] originalOperation; + final byte[] gameDesignTerminalBytes; + final String worldOutcome; + final byte[] worldTerminalBytes; + try { + var reader = new DraftAuthorizationFenceBinding.FrameReader(receipt); + reader.expect(RECEIPT_SCHEMA); + accountBinding = reader.bytes(); + originalOperation = reader.bytes(); + gameDesignTerminalBytes = reader.bytes(); + worldOutcome = reader.text(); + worldTerminalBytes = reader.bytes(); + reader.requireEnd(); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Canonical six-frame Account publication settlement receipt required", malformed); + } + + GameDesignPublicationOperationBinding operation; + GameDesignPublicationTerminalEvidence terminal; + try { + operation = GameDesignPublicationOperationBinding.fromStored(request.originalOperation()); + terminal = GameDesignPublicationTerminalEvidence.fromStored(gameDesignTerminalBytes); + GameDesignPublicationTerminalEvidence.fromStored(worldTerminalBytes); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Account receipt lacks complete canonical publication evidence", malformed); + } + String expectedWorldOutcome = + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + if (!Arrays.equals(accountBinding, operation.account().canonicalBytes()) + || !Arrays.equals(originalOperation, request.originalOperation()) + || !Arrays.equals(terminal.operationBytes(), originalOperation) + || !Arrays.equals(gameDesignTerminalBytes, terminal.canonicalBytes()) + || !Arrays.equals(worldTerminalBytes, gameDesignTerminalBytes) + || !expectedWorldOutcome.equals(worldOutcome)) { + throw new IllegalArgumentException( + "Account settlement receipt differs from the exact operation, terminal, or World outcome"); + } + + var canonical = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(canonical, RECEIPT_SCHEMA); + DraftAuthorizationFenceBinding.frame(canonical, accountBinding); + DraftAuthorizationFenceBinding.frame(canonical, originalOperation); + DraftAuthorizationFenceBinding.frame(canonical, gameDesignTerminalBytes); + DraftAuthorizationFenceBinding.frame(canonical, worldOutcome); + DraftAuthorizationFenceBinding.frame(canonical, worldTerminalBytes); + if (!Arrays.equals(receipt, canonical.toByteArray())) { + throw new IllegalArgumentException("Noncanonical Account publication settlement receipt"); + } + } + + private static void requireWireBudget(Message message) { + if (message.getSerializedSize() > MAX_MESSAGE_BYTES) { + throw new IllegalArgumentException( + "Account publication settlement exceeds the 32 MiB wire budget"); + } + } + + private static void noUnknownFields(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Account publication settlement has unsupported fields"); + } + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil request UUID required"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException("Canonical non-nil request UUID required", malformed); + } + } + + /** Request correlation is fresh per transport call and is not the retained settlement key. */ + public record Request( + int schemaVersion, String targetNamespace, UUID requestId, byte[] originalOperation) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported Account publication settlement schema"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + if (requestId == null || requestId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Non-nil canonical request identity required"); + } + if (originalOperation == null || originalOperation.length == 0) { + throw new IllegalArgumentException("Complete original publication operation required"); + } + if (originalOperation.length > GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES) { + throw new IllegalArgumentException("Original publication operation exceeds 4 MiB"); + } + originalOperation = originalOperation.clone(); + GameDesignPublicationOperationBinding operation; + try { + operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Complete canonical original publication operation required", malformed); + } + if (!Arrays.equals(originalOperation, operation.canonicalBytes())) { + throw new IllegalArgumentException( + "Exact canonical original publication operation required"); + } + if (!targetNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException( + "Original publication operation differs from the Account workload namespace"); + } + } + + public static Request create(String targetNamespace, byte[] originalOperation) { + return new Request(SCHEMA_VERSION, targetNamespace, UUID.randomUUID(), originalOperation); + } + + @Override + public byte[] originalOperation() { + return originalOperation.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && requestId.equals(that.requestId) + && Arrays.equals(originalOperation, that.originalOperation); + } + + @Override + public int hashCode() { + return 31 * Objects.hash(schemaVersion, targetNamespace, requestId) + + Arrays.hashCode(originalOperation); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionClient.java new file mode 100644 index 0000000000..ed4f3c40ea --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionClient.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.common.publication; + +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.gamedesign.GameDesignPublicationTerminalEvidence; +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.WorldPublicationTerminalCompletionServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit file-backed mTLS client for World-owned publication terminal completion. */ +public final class WorldPublicationTerminalCompletionClient + extends AbstractReloadingBlockingGrpcClient< + WorldPublicationTerminalCompletionServiceGrpc + .WorldPublicationTerminalCompletionServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public WorldPublicationTerminalCompletionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + WorldPublicationTerminalCompletionClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("World publication completion client is closed"); + } + if (initialized) return; + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("World publication completion stub unavailable"); + } + initialized = true; + } + + /** Returns only the exact fully validated terminal retained by the World owner. */ + public GameDesignPublicationTerminalEvidence complete( + WorldPublicationTerminalCompletionGrpcCodec.Request request) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("World publication completion requires no owner transaction"); + } + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "World publication completion must use the configured workload namespace"); + } + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .completeVersionPublication( + WorldPublicationTerminalCompletionGrpcCodec.toRequest(request)); + try { + return WorldPublicationTerminalCompletionGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "World returned invalid publication terminal evidence", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected WorldPublicationTerminalCompletionServiceGrpc + .WorldPublicationTerminalCompletionServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service"; + return WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip") + .withMaxInboundMessageSize(WorldPublicationTerminalCompletionGrpcCodec.MAX_MESSAGE_BYTES); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private WorldPublicationTerminalCompletionServiceGrpc + .WorldPublicationTerminalCompletionServiceBlockingStub + requireStub() { + var currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "World publication completion client is not initialized and available"); + } + return currentStub; + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("World publication completion 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 publication completion requires file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "World publication completion requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException( + "World publication completion " + label + " must be a file-backed path", invalid); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "World publication completion " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java new file mode 100644 index 0000000000..91a5cecbc6 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java @@ -0,0 +1,238 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationRequest; +import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationResponse; + +/** Closed World-owned publication completion transport and exact result validation. */ +public final class WorldPublicationTerminalCompletionGrpcCodec { + /** Shared per-message protobuf budget; oversized complete operations/results fail closed. */ + public static final int MAX_MESSAGE_BYTES = 32 * 1024 * 1024; + + // Reserve the small envelope fields and protobuf tags/lengths before canonical decoding. + private static final int MESSAGE_ENVELOPE_OVERHEAD_RESERVE = 256; + + private WorldPublicationTerminalCompletionGrpcCodec() {} + + public static CompleteVersionPublicationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var wire = + CompleteVersionPublicationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setGameDesignTerminalEvidence( + ByteString.copyFrom(request.gameDesignTerminalEvidence())) + .build(); + requireWireBudget(wire); + return wire; + } + + /** Receiver authenticates the exact Game Design peer before decoding this request. */ + public static Request fromRequest(CompleteVersionPublicationRequest request) { + Objects.requireNonNull(request, "request"); + requireWireBudget(request); + noUnknownFields(request); + try { + return new Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + canonicalUuid(request.getRequestId()), + request.getOriginalOperation().toByteArray(), + request.getGameDesignTerminalEvidence().toByteArray()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "World publication completion request is invalid", malformed); + } + } + + /** Emits the retained World result only when it is the exact requested Game Design terminal. */ + public static CompleteVersionPublicationResponse toResponse( + Request request, GameDesignPublicationTerminalEvidence terminal) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(terminal, "terminal"); + byte[] terminalBytes = terminal.canonicalBytes(); + requireExactTerminal(request, terminalBytes); + // The full terminal appears once in the request echo and once as the stored result. + if ((long) request.originalOperation().length + 2L * terminalBytes.length + > MAX_MESSAGE_BYTES - MESSAGE_ENVELOPE_OVERHEAD_RESERVE) { + throw new IllegalArgumentException( + "World publication completion response exceeds the 32 MiB wire budget"); + } + var response = + CompleteVersionPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setGameDesignTerminalEvidence( + ByteString.copyFrom(request.gameDesignTerminalEvidence())) + .setStoredTerminalEvidence(ByteString.copyFrom(terminalBytes)) + .build(); + requireWireBudget(response); + return response; + } + + /** Verifies full request echo and returns the fully decoded retained terminal result. */ + public static GameDesignPublicationTerminalEvidence fromResponse( + Request request, CompleteVersionPublicationResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireWireBudget(response); + noUnknownFields(response); + if (response.getSchemaVersion() != request.schemaVersion() + || !request.targetNamespace().equals(response.getTargetNamespace()) + || !request.requestId().toString().equals(response.getRequestId()) + || !Arrays.equals( + request.originalOperation(), response.getOriginalOperation().toByteArray()) + || !Arrays.equals( + request.gameDesignTerminalEvidence(), + response.getGameDesignTerminalEvidence().toByteArray())) { + throw new IllegalArgumentException("World changed the exact publication completion request"); + } + byte[] terminalBytes = response.getStoredTerminalEvidence().toByteArray(); + requireExactTerminal(request, terminalBytes); + return GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + } + + private static void requireExactTerminal(Request request, byte[] terminalBytes) { + final GameDesignPublicationTerminalEvidence terminal; + try { + terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Complete canonical publication terminal required", malformed); + } + if (!Arrays.equals(request.originalOperation(), terminal.operationBytes()) + || !Arrays.equals(request.gameDesignTerminalEvidence(), terminal.canonicalBytes())) { + throw new IllegalArgumentException( + "World publication terminal differs from the exact requested operation or evidence"); + } + } + + private static void requireWireBudget(Message message) { + if (message.getSerializedSize() > MAX_MESSAGE_BYTES) { + throw new IllegalArgumentException( + "World publication completion exceeds the 32 MiB wire budget"); + } + } + + private static void noUnknownFields(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("World publication completion has unsupported fields"); + } + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil request UUID required"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException("Canonical non-nil request UUID required", malformed); + } + } + + /** Request correlation is fresh per transport call and is not the mutation identity. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID requestId, + byte[] originalOperation, + byte[] gameDesignTerminalEvidence) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported World publication completion schema"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace required"); + } + if (requestId == null || requestId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Non-nil canonical request identity required"); + } + if (originalOperation == null || originalOperation.length == 0) { + throw new IllegalArgumentException("Complete original publication operation required"); + } + if (originalOperation.length > GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES) { + throw new IllegalArgumentException("Original publication operation exceeds 4 MiB"); + } + if (gameDesignTerminalEvidence == null || gameDesignTerminalEvidence.length == 0) { + throw new IllegalArgumentException("Complete Game Design terminal evidence required"); + } + if ((long) originalOperation.length + gameDesignTerminalEvidence.length + > MAX_MESSAGE_BYTES - MESSAGE_ENVELOPE_OVERHEAD_RESERVE) { + throw new IllegalArgumentException( + "World publication completion exceeds the 32 MiB wire budget"); + } + originalOperation = originalOperation.clone(); + gameDesignTerminalEvidence = gameDesignTerminalEvidence.clone(); + GameDesignPublicationOperationBinding operation; + GameDesignPublicationTerminalEvidence terminal; + try { + operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); + terminal = GameDesignPublicationTerminalEvidence.fromStored(gameDesignTerminalEvidence); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Complete canonical publication operation and terminal required", malformed); + } + if (!Arrays.equals(originalOperation, operation.canonicalBytes()) + || !Arrays.equals(gameDesignTerminalEvidence, terminal.canonicalBytes()) + || !Arrays.equals(originalOperation, terminal.operationBytes())) { + throw new IllegalArgumentException( + "Game Design terminal differs from the complete original operation"); + } + if (!targetNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException( + "Original publication operation differs from the World workload namespace"); + } + } + + public static Request create( + String targetNamespace, byte[] originalOperation, byte[] gameDesignTerminalEvidence) { + return new Request( + SCHEMA_VERSION, + targetNamespace, + UUID.randomUUID(), + originalOperation, + gameDesignTerminalEvidence); + } + + @Override + public byte[] originalOperation() { + return originalOperation.clone(); + } + + @Override + public byte[] gameDesignTerminalEvidence() { + return gameDesignTerminalEvidence.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && requestId.equals(that.requestId) + && Arrays.equals(originalOperation, that.originalOperation) + && Arrays.equals(gameDesignTerminalEvidence, that.gameDesignTerminalEvidence); + } + + @Override + public int hashCode() { + int result = Objects.hash(schemaVersion, targetNamespace, requestId); + result = 31 * result + Arrays.hashCode(originalOperation); + return 31 * result + Arrays.hashCode(gameDesignTerminalEvidence); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java new file mode 100644 index 0000000000..5183aa5dcd --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java @@ -0,0 +1,198 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationSettlementGrpcCodecTest { + @Test + void roundTripsBothCanonicalSixFrameReceiptsAndUsesIndependentCorrelation() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + for (Outcome outcome : Outcome.values()) { + var terminal = GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, outcome); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var decoded = + AccountSelectedPublicationSettlementGrpcCodec.fromRequest( + AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); + assertThat(decoded).isEqualTo(request); + + byte[] receipt = receipt(operation, terminal, null, null, null, null); + var response = AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt); + assertThat(AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, response)) + .containsExactly(receipt); + + var fresh = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat(fresh.originalOperation()).containsExactly(request.originalOperation()); + } + } + + @Test + void rejectsMalformedAndNoncanonicalRequestsAndUnknownFields() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var wire = AccountSelectedPublicationSettlementGrpcCodec.toRequest(request); + for (SettleSelectedPublicationRequest invalid : + List.of( + wire.toBuilder().setUnknownFields(unknown()).build(), + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + wire.toBuilder().setRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA").build(), + wire.toBuilder().setRequestId("1-1-1-1-1").build(), + wire.toBuilder().clearOriginalOperation().build(), + wire.toBuilder() + .setOriginalOperation( + wire.getOriginalOperation().concat(ByteString.copyFrom(new byte[] {0}))) + .build(), + wire.toBuilder().setOriginalOperation(ByteString.copyFrom(new byte[] {1})).build())) { + assertThatThrownBy(() -> AccountSelectedPublicationSettlementGrpcCodec.fromRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", + new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("4 MiB"); + } + + @Test + void rejectsChangedRequestEchoUnknownFieldsAndChangedOrNoncanonicalReceiptFrames() + throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.NO_PUBLICATION); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var changedOperation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var changedTerminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal( + changedOperation, Outcome.PUBLISHED); + var sameOperationOtherOutcome = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.PUBLISHED); + byte[] receipt = receipt(operation, terminal, null, null, null, null); + var response = AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt); + var changedBinding = new byte[] {1, 2, 3}; + byte[] wrongOutcome = receipt(operation, terminal, "PUBLISHED", null, null, null); + byte[] wrongBinding = receipt(operation, terminal, null, changedBinding, null, null); + byte[] wrongOperation = + receipt(operation, terminal, null, null, changedOperation.canonicalBytes(), null); + byte[] wrongTerminal = receipt(operation, changedTerminal, null, null, null, null); + byte[] wrongWorldTerminal = + receipt(operation, terminal, null, null, null, sameOperationOtherOutcome.canonicalBytes()); + for (var invalid : + List.of( + response.toBuilder().setUnknownFields(unknown()).build(), + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder() + .setOriginalOperation(ByteString.copyFrom(changedOperation.canonicalBytes())) + .build(), + response.toBuilder().clearSettlementReceipt().build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongOutcome)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongBinding)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongOperation)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongTerminal)).build(), + response.toBuilder() + .setSettlementReceipt(ByteString.copyFrom(wrongWorldTerminal)) + .build(), + response.toBuilder() + .setSettlementReceipt( + response.getSettlementReceipt().concat(ByteString.copyFrom(new byte[] {0}))) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, wrongOutcome)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void enforcesCompleteSerializedMessageBudgetBeforeReceiptDecoding() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + byte[] oversizedReceipt = + new byte[AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES]; + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, oversizedReceipt)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("32 MiB"); + + var oversizedResponse = + SettleSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setSettlementReceipt(ByteString.copyFrom(oversizedReceipt)) + .build(); + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.fromResponse( + request, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("32 MiB"); + } + + private static byte[] receipt( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence terminal, + String outcomeOverride, + byte[] accountBindingOverride, + byte[] operationOverride, + byte[] worldTerminalOverride) { + String outcome = + outcomeOverride == null + ? terminal.outcome() == Outcome.PUBLISHED ? "PUBLISHED" : "ABORTED" + : outcomeOverride; + byte[] accountBinding = + accountBindingOverride == null + ? operation.account().canonicalBytes() + : accountBindingOverride; + byte[] operationBytes = + operationOverride == null ? operation.canonicalBytes() : operationOverride; + byte[] worldTerminal = + worldTerminalOverride == null ? terminal.canonicalBytes() : worldTerminalOverride; + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, accountBinding); + DraftAuthorizationFenceBinding.frame(out, operationBytes); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome); + DraftAuthorizationFenceBinding.frame(out, worldTerminal); + return out.toByteArray(); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java new file mode 100644 index 0000000000..d6a5b17569 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationRequest; +import org.junit.jupiter.api.Test; + +class WorldPublicationTerminalCompletionGrpcCodecTest { + @Test + void roundTripsBothTerminalOutcomesAndUsesIndependentTransportCorrelation() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + for (Outcome outcome : Outcome.values()) { + var terminal = GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, outcome); + var request = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), terminal.canonicalBytes()); + var decoded = + WorldPublicationTerminalCompletionGrpcCodec.fromRequest( + WorldPublicationTerminalCompletionGrpcCodec.toRequest(request)); + assertThat(decoded).isEqualTo(request); + + var response = WorldPublicationTerminalCompletionGrpcCodec.toResponse(request, terminal); + var first = WorldPublicationTerminalCompletionGrpcCodec.fromResponse(request, response); + var retry = WorldPublicationTerminalCompletionGrpcCodec.fromResponse(request, response); + assertThat(first.canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(retry.outcome()).isEqualTo(outcome); + assertThat(response.getRequestId()).isEqualTo(request.requestId().toString()); + + var fresh = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), terminal.canonicalBytes()); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat(fresh.originalOperation()).containsExactly(request.originalOperation()); + } + } + + @Test + void rejectsMalformedAndNoncanonicalRequestsAndUnknownFields() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.NO_PUBLICATION); + var request = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), terminal.canonicalBytes()); + var wire = WorldPublicationTerminalCompletionGrpcCodec.toRequest(request); + for (CompleteVersionPublicationRequest invalid : + List.of( + wire.toBuilder().setUnknownFields(unknown()).build(), + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + wire.toBuilder().setRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA").build(), + wire.toBuilder().setRequestId("1-1-1-1-1").build(), + wire.toBuilder().clearOriginalOperation().build(), + wire.toBuilder() + .setOriginalOperation( + wire.getOriginalOperation().concat(ByteString.copyFrom(new byte[] {0}))) + .build(), + wire.toBuilder() + .setGameDesignTerminalEvidence( + wire.getGameDesignTerminalEvidence() + .concat(ByteString.copyFrom(new byte[] {0}))) + .build(), + wire.toBuilder() + .setGameDesignTerminalEvidence(ByteString.copyFrom(new byte[] {1})) + .build())) { + assertThatThrownBy(() -> WorldPublicationTerminalCompletionGrpcCodec.fromRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + assertThatThrownBy( + () -> + new WorldPublicationTerminalCompletionGrpcCodec.Request( + 2, + "test", + UUID.randomUUID(), + operation.canonicalBytes(), + terminal.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsChangedEchoStoredTerminalAndOverBudgetCompleteMessages() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var changedOperation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var terminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.NO_PUBLICATION); + var changedTerminal = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal( + changedOperation, Outcome.PUBLISHED); + var request = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), terminal.canonicalBytes()); + var response = WorldPublicationTerminalCompletionGrpcCodec.toResponse(request, terminal); + for (var invalid : + List.of( + response.toBuilder().setUnknownFields(unknown()).build(), + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder() + .setOriginalOperation(ByteString.copyFrom(changedOperation.canonicalBytes())) + .build(), + response.toBuilder() + .setGameDesignTerminalEvidence( + ByteString.copyFrom(changedTerminal.canonicalBytes())) + .build(), + response.toBuilder().clearStoredTerminalEvidence().build(), + response.toBuilder() + .setStoredTerminalEvidence(ByteString.copyFrom(changedTerminal.canonicalBytes())) + .build(), + response.toBuilder() + .setStoredTerminalEvidence( + response + .getStoredTerminalEvidence() + .concat(ByteString.copyFrom(new byte[] {0}))) + .build())) { + assertThatThrownBy( + () -> WorldPublicationTerminalCompletionGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> WorldPublicationTerminalCompletionGrpcCodec.toResponse(request, changedTerminal)) + .isInstanceOf(IllegalArgumentException.class); + + var oversizedRequest = + CompleteVersionPublicationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setGameDesignTerminalEvidence( + ByteString.copyFrom( + new byte[WorldPublicationTerminalCompletionGrpcCodec.MAX_MESSAGE_BYTES])) + .build(); + assertThatThrownBy( + () -> WorldPublicationTerminalCompletionGrpcCodec.fromRequest(oversizedRequest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("32 MiB"); + + var oversizedResponse = + response.toBuilder() + .setStoredTerminalEvidence( + ByteString.copyFrom( + new byte[WorldPublicationTerminalCompletionGrpcCodec.MAX_MESSAGE_BYTES])) + .build(); + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionGrpcCodec.fromResponse( + request, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("32 MiB"); + } + + @Test + void requestMayFitWhenItsRepeatedTerminalResponseDoesNot() throws Exception { + var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); + var base = + GameDesignPublicationTerminalReadGrpcCodecTest.terminal(operation, Outcome.PUBLISHED); + var release = base.releaseContent(); + var largeRelease = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + release.canonicalTenantId(), + release.canonicalVersionId(), + release.publishedReleaseBundleRef(), + release.versionNumber(), + release.attestationSchemaVersion(), + release.publishWorkflowId(), + release.manifestHash(), + release.manifestSchemaVersion(), + release.artifactDigests(), + release.requiredManifestAssetKeys(), + release.participantDigests(), + List.of("x".repeat(17 * 1024 * 1024)), + release.generationConfigRevision(), + release.worldStartLocationEvidence()); + var largeTerminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + Outcome.PUBLISHED, + largeRelease, + base.publicationVersionStateEpoch()); + var request = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), largeTerminal.canonicalBytes()); + + assertThat(WorldPublicationTerminalCompletionGrpcCodec.toRequest(request).getSerializedSize()) + .isLessThan(WorldPublicationTerminalCompletionGrpcCodec.MAX_MESSAGE_BYTES); + assertThatThrownBy( + () -> WorldPublicationTerminalCompletionGrpcCodec.toResponse(request, largeTerminal)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("response exceeds"); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 16f36b14a4..7215d44491 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -113,6 +113,7 @@ import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamedesign.GrpcAuthoredInitialActorCoreReadClient; import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; @@ -157,13 +158,22 @@ import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementGrpcCodec; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadEvidence; import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalCompletionClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalCompletionGrpcCodec; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; @@ -226,6 +236,9 @@ import net.firedevops.firemud.gamedesign.publication.AuthoredInitialActorCoreReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadGrpcService; import net.firedevops.firemud.gamedesign.publication.GameDesignGameplayRuleSourceReadService; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationRepository; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadGrpcService; +import net.firedevops.firemud.gamedesign.publication.GameDesignPublicationTerminalReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignSelectedOwnerIntakeSourceGrpcService; import net.firedevops.firemud.gamedesign.publication.GameDesignSelectedOwnerIntakeSourceReadService; import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; @@ -370,6 +383,11 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionActivationTerminalReadGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalCompletionGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalReadService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalService; import net.firedevops.firemud.worldmanagement.tenant.WorldSelectedOwnerInventoryReadProofFixture; import net.firedevops.firemud.worldmanagement.tenant.WorldStartSessionAccountParticipationVerifier; import net.firedevops.firemud.worldmanagement.tenant.WorldStartSessionExecutionTerminalReadGrpcService; @@ -671,6 +689,21 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( var accountSelectedPublicationOrderClient = new AccountSelectedPublicationOrderClient( endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var accountToGameDesignPublicationTerminalReadClient = + new GameDesignPublicationTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var accountToWorldPublicationTerminalReadClient = + new WorldPublicationTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var worldToGameDesignPublicationTerminalReadClient = + new GameDesignPublicationTerminalReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var gameDesignToWorldPublicationTerminalCompletionClient = + new WorldPublicationTerminalCompletionClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); + var gameDesignToAccountPublicationSettlementClient = + new AccountSelectedPublicationSettlementClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE); var gameDesignStartSessionReadTransport = new NativeGameDesignStartSessionReadTransport(endpoints, pki, channels); var worldToAccountParticipationHistoryClient = @@ -774,6 +807,11 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( canonicalActivationClient(worldServer, pki.client("game-session-service"), channels)) { ReflectionTestUtils.invokeMethod(loggingClaimClient, "init"); accountSelectedPublicationOrderClient.init(); + accountToGameDesignPublicationTerminalReadClient.init(); + accountToWorldPublicationTerminalReadClient.init(); + worldToGameDesignPublicationTerminalReadClient.init(); + gameDesignToWorldPublicationTerminalCompletionClient.init(); + gameDesignToAccountPublicationSettlementClient.init(); worldToAccountParticipationHistoryClient.init(); worldToGameSessionOwnerEvidenceClient.init(); accountToWorldExecutionTerminalClient.init(); @@ -1128,7 +1166,11 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( NAMESPACE), account.selectedOwnerIntakeAuthorizationProducerReceiver( observedAccountToGdSource, NAMESPACE), - account.selectedPublicationOrderProducer(accountSelectionReadClient, NAMESPACE)); + account.selectedPublicationOrderProducer(accountSelectionReadClient, NAMESPACE), + account.selectedPublicationSettlementReceiver( + accountToGameDesignPublicationTerminalReadClient, + accountToWorldPublicationTerminalReadClient, + NAMESPACE)); var coordinator = new DraftCommitCoordinatorRepository(gd.dsl()); var gdTerminals = new GameDesignDraftTerminalOutcomeRepository(gd.dsl()); @@ -1138,6 +1180,14 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( register( gdHandlers, new GameDesignSelectedDraftPublicationReadGrpcService(selectionRepository, NAMESPACE)); + register( + gdHandlers, + new GameDesignPublicationTerminalReadGrpcService( + new GameDesignPublicationTerminalReadService( + new GameDesignPublicationOperationRepository(gd.dsl()), + gd.transactions(), + NAMESPACE), + NAMESPACE)); var worldFence = new WorldDesignPublicationFenceRepository(world.dsl(), worldIntakes); register( worldHandlers, @@ -1160,7 +1210,18 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( register( worldHandlers, worldPublicationProof.freezeAndInventoryService(), - worldPublicationProof.publishedStartLocationReadService()); + worldPublicationProof.publishedStartLocationReadService(), + new WorldPublicationTerminalReadGrpcService( + new WorldPublicationTerminalReadService( + new WorldPublicationTerminalRepository(world.dsl(), world.transactions()), + NAMESPACE), + NAMESPACE), + new WorldPublicationTerminalCompletionGrpcService( + WorldPublicationTerminalService.authenticated( + new WorldPublicationTerminalRepository(world.dsl(), world.transactions()), + worldToGameDesignPublicationTerminalReadClient, + NAMESPACE), + NAMESPACE)); var worldApplicationService = new WorldDraftGraphApplicationService( worldApplications, @@ -3188,6 +3249,106 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( .fetchCount(DSL.table("game_design_start_session_launch_descriptor_binding"))) .isZero(); + byte[] originalPublicationOperation = publicationReservation.operation().canonicalBytes(); + var originalPublicationBinding = + GameDesignPublicationOperationBinding.fromStored(originalPublicationOperation); + var gameDesignTerminalRequest = + GameDesignPublicationTerminalReadEvidence.Request.create( + NAMESPACE, originalPublicationBinding); + var gameDesignTerminalRead = + accountToGameDesignPublicationTerminalReadClient.read(gameDesignTerminalRequest); + var gameDesignPublicationTerminal = gameDesignTerminalRead.terminalEvidence(); + assertThat(gameDesignTerminalRead.request()).isEqualTo(gameDesignTerminalRequest); + assertThat(gameDesignPublicationTerminal.operationBytes()) + .containsExactly(originalPublicationOperation); + assertThat(gameDesignPublicationTerminal.outcome()) + .isEqualTo(GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED); + + var worldCompletionRequest = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + NAMESPACE, + originalPublicationOperation, + gameDesignPublicationTerminal.canonicalBytes()); + var worldPublicationTerminal = + gameDesignToWorldPublicationTerminalCompletionClient.complete(worldCompletionRequest); + var worldCompletionRetryRequest = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + NAMESPACE, + originalPublicationOperation, + gameDesignPublicationTerminal.canonicalBytes()); + assertThat(worldCompletionRetryRequest.requestId()) + .isNotEqualTo(worldCompletionRequest.requestId()); + var worldPublicationTerminalRetry = + gameDesignToWorldPublicationTerminalCompletionClient.complete( + worldCompletionRetryRequest); + assertThat(worldPublicationTerminal.canonicalBytes()) + .containsExactly(gameDesignPublicationTerminal.canonicalBytes()); + assertThat(worldPublicationTerminalRetry.canonicalBytes()) + .containsExactly(worldPublicationTerminal.canonicalBytes()); + + var publicationSettlementRequest = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, originalPublicationOperation); + var settledPublicationReceipt = + gameDesignToAccountPublicationSettlementClient.settle(publicationSettlementRequest); + var initialSelectedPublicationSettlement = + accountAccess + .sources() + .dsl + .fetchOne( + "SELECT receipt, settled_at FROM account_selected_publication_settlements " + + "WHERE operation_id = ?", + accountPublicationOrder.operationId()); + assertThat(initialSelectedPublicationSettlement).isNotNull(); + assertThat(initialSelectedPublicationSettlement.get("receipt", byte[].class)) + .containsExactly(settledPublicationReceipt); + var accountSettlementRetryRequest = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, originalPublicationOperation); + assertThat(accountSettlementRetryRequest.requestId()) + .isNotEqualTo(publicationSettlementRequest.requestId()); + var settledPublicationReceiptRetry = + gameDesignToAccountPublicationSettlementClient.settle(accountSettlementRetryRequest); + assertThat(settledPublicationReceiptRetry).containsExactly(settledPublicationReceipt); + var selectedPublicationSettlementRows = + accountAccess + .sources() + .dsl + .fetch( + "SELECT operation_id, fence_id, account_binding, publication_operation, " + + "game_design_outcome, game_design_terminal, world_outcome, " + + "world_terminal, receipt, settled_at " + + "FROM account_selected_publication_settlements WHERE operation_id = ?", + accountPublicationOrder.operationId()); + assertThat(selectedPublicationSettlementRows).hasSize(1); + var selectedPublicationSettlement = selectedPublicationSettlementRows.getFirst(); + assertThat(selectedPublicationSettlement.get("operation_id", UUID.class)) + .isEqualTo(accountPublicationOrder.operationId()); + assertThat(selectedPublicationSettlement.get("fence_id", UUID.class)) + .isEqualTo(accountPublicationOrder.fenceId()); + assertThat(selectedPublicationSettlement.get("account_binding", byte[].class)) + .containsExactly(accountPublicationOrder.canonicalBytes()); + assertThat(selectedPublicationSettlement.get("publication_operation", byte[].class)) + .containsExactly(originalPublicationOperation); + assertThat(selectedPublicationSettlement.get("game_design_outcome", String.class)) + .isEqualTo("PUBLISHED"); + assertThat(selectedPublicationSettlement.get("game_design_terminal", byte[].class)) + .containsExactly(gameDesignPublicationTerminal.canonicalBytes()); + assertThat(selectedPublicationSettlement.get("world_outcome", String.class)) + .isEqualTo("PUBLISHED"); + assertThat(selectedPublicationSettlement.get("world_terminal", byte[].class)) + .containsExactly(worldPublicationTerminal.canonicalBytes()); + assertThat(selectedPublicationSettlement.get("receipt", byte[].class)) + .containsExactly(settledPublicationReceipt); + assertThat(selectedPublicationSettlement.get("settled_at")) + .isEqualTo(initialSelectedPublicationSettlement.get("settled_at")); + assertFailedPrecondition( + () -> + gdAccountPublicationReadClient.read( + AccountPublicationAuthorizationReadEvidence.Request.create( + NAMESPACE, accountPublicationOrder))); + account.assertOriginalDraftOrderSettled(original); + var association = retainedTemplateAssociations.getFirst(); var pinnedSelection = new StartSessionTemplateAssociationReadEvidence.ExactReplay( @@ -6399,6 +6560,7 @@ private static LoggingReservationStore loggingReservationStore() { assertThat( dsl.fetch( "SELECT version FROM flyway_schema_history WHERE success " + + "AND version IS NOT NULL " + "ORDER BY installed_rank") .getValues("version", String.class)) .containsExactly("1", "2", "3", "4"); @@ -6884,7 +7046,7 @@ private static Server startServer(TestPki pki, String service, MutableHandlerReg var identity = pki.server(service); return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .fallbackHandlerRegistry(handlers) - .maxInboundMessageSize(20 * 1024 * 1024) + .maxInboundMessageSize(WorldPublicationTerminalCompletionGrpcCodec.MAX_MESSAGE_BYTES) .maxInboundMetadataSize(AccountOriginalDraftOrderGrpcCodec.MAX_METADATA_BYTES) .sslContext( GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcService.java new file mode 100644 index 0000000000..3703f6d9fb --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcService.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalCompletionGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationRequest; +import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationResponse; +import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalCompletionServiceGrpc; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Standalone Game Design-authenticated terminal handoff; deliberately not registered at runtime. + */ +public final class WorldPublicationTerminalCompletionGrpcService + extends WorldPublicationTerminalCompletionServiceGrpc + .WorldPublicationTerminalCompletionServiceImplBase { + private final WorldPublicationTerminalService owner; + private final String workloadNamespace; + + public WorldPublicationTerminalCompletionGrpcService( + WorldPublicationTerminalService owner, String workloadNamespace) { + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical World workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + @Override + public void completeVersionPublication( + CompleteVersionPublicationRequest request, + StreamObserver observer) { + if (!requireAuthenticatedGameDesignPeer(observer)) return; + + final WorldPublicationTerminalCompletionGrpcCodec.Request decoded; + try { + decoded = WorldPublicationTerminalCompletionGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + observer, + Status.INVALID_ARGUMENT, + "Canonical World publication terminal completion is required"); + return; + } + if (!workloadNamespace.equals(decoded.targetNamespace())) { + fail( + observer, + Status.PERMISSION_DENIED, + "World publication terminal namespace differs from the owner"); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail( + observer, + Status.FAILED_PRECONDITION, + "World publication terminal requires independent owner operations"); + return; + } + + final GameDesignPublicationTerminalEvidence committed; + try { + committed = owner.complete(decoded.originalOperation(), decoded.gameDesignTerminalEvidence()); + } catch (StatusRuntimeException failure) { + observer.onError(failure); + return; + } catch (DataAccessException | org.springframework.dao.DataAccessException unavailable) { + fail(observer, Status.UNAVAILABLE, "World publication terminal storage is unavailable"); + return; + } catch (IllegalArgumentException | IllegalStateException | SecurityException rejected) { + fail( + observer, + Status.FAILED_PRECONDITION, + "World could not verify or commit the exact Game Design publication terminal"); + return; + } catch (RuntimeException failure) { + fail(observer, Status.INTERNAL, "World publication terminal completion failed"); + return; + } + + final CompleteVersionPublicationResponse response; + try { + response = WorldPublicationTerminalCompletionGrpcCodec.toResponse(decoded, committed); + } catch (RuntimeException inconsistent) { + fail( + observer, + Status.INTERNAL, + "World publication terminal did not produce an exact canonical readback"); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private boolean requireAuthenticatedGameDesignPeer(StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + fail(observer, Status.UNAUTHENTICATED, "Verified workload identity required"); + return false; + } + String expectedUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + if (expectedUri.equals(peer.uri()) + && peer.isService("game-design-service") + && peer.isInNamespace(workloadNamespace) + && !SessionContext.hasAuthenticatedCallerContext()) { + return true; + } + fail( + observer, + Status.PERMISSION_DENIED, + "Only the exact same-namespace Game Design workload without end-user context is allowed"); + return false; + } + + private static void fail(StreamObserver observer, Status status, String description) { + observer.onError(status.withDescription(description).asRuntimeException()); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java index faa87bc113..cf4602fff0 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalService.java @@ -2,6 +2,7 @@ import java.util.Objects; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.GameDesignPublicationTerminalReadClient; import org.springframework.transaction.support.TransactionSynchronizationManager; /** Standalone, default-denied receiver for one authenticated Game Design terminal publication. */ @@ -23,6 +24,16 @@ public WorldPublicationTerminalService( this.verifier = Objects.requireNonNull(verifier, "verifier"); } + /** Constructs the existing exact Game Design verifier for an explicitly assembled fixture. */ + public static WorldPublicationTerminalService authenticated( + WorldPublicationTerminalRepository repository, + GameDesignPublicationTerminalReadClient terminalReadClient, + String workloadNamespace) { + return new WorldPublicationTerminalService( + repository, + new WorldGameDesignPublicationTerminalVerifier(workloadNamespace, terminalReadClient)); + } + /** * Authenticates and reconciles the producer before opening the World owner transaction. The * continuously held fence is checked locally through commit; no remote call occurs under locks. diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java index f810ca21fa..35f1b2abde 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java @@ -62,7 +62,7 @@ import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; -class WorldGameDesignPublicationTerminalVerifierTest { +public class WorldGameDesignPublicationTerminalVerifierTest { private static final String NAMESPACE = "test"; @AfterEach @@ -209,7 +209,7 @@ private static T withPeer(GrpcPeerIdentity identity, Callable task) throw return Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, identity).call(task); } - private static GameDesignPublicationOperationBinding operation() throws Exception { + public static GameDesignPublicationOperationBinding operation() throws Exception { // Canonical structural inputs only; this fixture does not stipulate real owner commits or // source holds. var upstream = freshGraphRequest(); @@ -309,7 +309,7 @@ private static GameDesignPublicationOperationBinding operation() throws Exceptio account, world, IsolatedWorldPublicationInventoryFixtures.stipulated(account, world)); } - private static GameDesignPublicationTerminalEvidence terminal( + public static GameDesignPublicationTerminalEvidence terminal( GameDesignPublicationOperationBinding operation, Outcome outcome) { if (outcome == Outcome.NO_PUBLICATION) { return new GameDesignPublicationTerminalEvidence( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java index 8f571275a3..0fe5ba00e2 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java @@ -203,7 +203,7 @@ void authenticatedEndUserContextIsDeniedBeforeOwner() throws Exception { } } -/** Shared only by the two assigned World activation transport tests. */ +/** Shared by World activation and publication-completion transport tests. */ final class WorldOriginalStartSessionActivationTransportTestSupport { static final String NAMESPACE = "test"; private static final java.util.concurrent.atomic.AtomicLong CERTIFICATE_SERIAL = @@ -513,6 +513,18 @@ static TransportServer startServer( boolean injectEndUserContext, java.util.function.Consumer responseCapture) throws Exception { + return startServer( + pki, pki.worldServer(), service, handlerCalls, injectEndUserContext, responseCapture); + } + + static TransportServer startServer( + TestPki pki, + TestIdentity serverIdentity, + io.grpc.BindableService service, + AtomicInteger handlerCalls, + boolean injectEndUserContext, + java.util.function.Consumer responseCapture) + throws Exception { java.util.List interceptors = new java.util.ArrayList<>(); interceptors.add( new io.grpc.ServerInterceptor() { @@ -576,7 +588,7 @@ public void onHalfClose() { .sslContext( GrpcSslContexts.configure( SslContextBuilder.forServer( - pki.worldServer().privateKey(), pki.worldServer().certificate())) + serverIdentity.privateKey(), serverIdentity.certificate())) .trustManager(pki.caCertificate()) .clientAuth(ClientAuth.REQUIRE) .build()) @@ -655,10 +667,13 @@ record TestPki( java.security.cert.X509Certificate caCertificate, Path caCertificatePem, TestIdentity worldServer, + TestIdentity otherNamespaceWorldServer, TestIdentity gameSessionClient, TestIdentity accountClient, + TestIdentity gameDesignClient, TestIdentity otherNamespaceGameSessionClient, - TestIdentity otherNamespaceAccountClient) { + TestIdentity otherNamespaceAccountClient, + TestIdentity otherNamespaceGameDesignClient) { static TestPki create(Path directory) throws Exception { if (java.security.Security.getProvider( org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME) @@ -686,6 +701,12 @@ static TestPki create(Path directory) throws Exception { "world-server", "spiffe://firemud/ns/test/sa/world-management-service", true), + issueIdentity( + caName, + caKeys.getPrivate(), + "other-world-server", + "spiffe://firemud/ns/other/sa/world-management-service", + true), issueIdentity( caName, caKeys.getPrivate(), @@ -698,6 +719,12 @@ static TestPki create(Path directory) throws Exception { "account", "spiffe://firemud/ns/test/sa/account-service", false), + issueIdentity( + caName, + caKeys.getPrivate(), + "game-design", + "spiffe://firemud/ns/test/sa/game-design-service", + false), issueIdentity( caName, caKeys.getPrivate(), @@ -709,6 +736,12 @@ static TestPki create(Path directory) throws Exception { caKeys.getPrivate(), "other-account", "spiffe://firemud/ns/other/sa/account-service", + false), + issueIdentity( + caName, + caKeys.getPrivate(), + "other-game-design", + "spiffe://firemud/ns/other/sa/game-design-service", false)); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcMtlsTest.java new file mode 100644 index 0000000000..17b1288e41 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcMtlsTest.java @@ -0,0 +1,319 @@ +package unit.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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +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 java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalCompletionClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalCompletionGrpcCodec; +import net.firedevops.firemud.test.TlsTestSupport; +import net.firedevops.firemud.worldmanagement.tenant.WorldGameDesignPublicationTerminalVerifierTest; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalCompletionGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalService; +import net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalCompletionServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Real loopback mTLS transport proof; World storage is mocked except for default-deny checks. */ +class WorldPublicationTerminalCompletionGrpcMtlsTest { + @TempDir Path temporaryDirectory; + + @Test + void sameNamespaceGameDesignCertificateReturnsExactStoredTerminalOnRetry() throws Exception { + var operation = WorldGameDesignPublicationTerminalVerifierTest.operation(); + var terminal = + WorldGameDesignPublicationTerminalVerifierTest.terminal(operation, Outcome.PUBLISHED); + var request = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), terminal.canonicalBytes()); + var owner = mock(WorldPublicationTerminalService.class); + when(owner.complete(any(), any())).thenReturn(terminal); + var service = new WorldPublicationTerminalCompletionGrpcService(owner, "test"); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var handlerCalls = new AtomicInteger(); + var capturedResponse = new AtomicReference(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, false, capturedResponse::set); + var client = worldClient(pki, server.port())) { + client.init(); + var first = client.complete(request); + var retry = client.complete(request); + + assertThat(first.canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(retry.canonicalBytes()).containsExactly(terminal.canonicalBytes()); + assertThat(handlerCalls).hasValue(2); + assertThat(capturedResponse.get()) + .isEqualTo(WorldPublicationTerminalCompletionGrpcCodec.toResponse(request, terminal)); + + var operationCaptor = org.mockito.ArgumentCaptor.forClass(byte[].class); + var terminalCaptor = org.mockito.ArgumentCaptor.forClass(byte[].class); + verify(owner, times(2)).complete(operationCaptor.capture(), terminalCaptor.capture()); + assertThat(operationCaptor.getAllValues()) + .allSatisfy(bytes -> assertThat(bytes).containsExactly(operation.canonicalBytes())); + assertThat(terminalCaptor.getAllValues()) + .allSatisfy(bytes -> assertThat(bytes).containsExactly(terminal.canonicalBytes())); + } + } + + @Test + void wrongWorkloadAndNamespaceCertificatesAreDeniedBeforeOwner() throws Exception { + var input = request(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var owner = mock(WorldPublicationTerminalService.class); + var service = new WorldPublicationTerminalCompletionGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, false, null)) { + for (var identity : + java.util.List.of(pki.accountClient(), pki.otherNamespaceGameDesignClient())) { + try (var channel = managedChannel(pki, server.port(), identity)) { + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub( + channel.channel()) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .completeVersionPublication(input.wire())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + } + } + + assertThat(handlerCalls).hasValue(2); + verifyNoInteractions(owner); + } + + @Test + void requestNamespaceMustMatchTheAuthenticatedWorldOwner() throws Exception { + var input = request(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var owner = mock(WorldPublicationTerminalService.class); + var service = new WorldPublicationTerminalCompletionGrpcService(owner, "other"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, pki.otherNamespaceWorldServer(), service, handlerCalls, false, null); + var channel = managedChannel(pki, server.port(), pki.otherNamespaceGameDesignClient())) { + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub(channel.channel()) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .completeVersionPublication(input.wire())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + + assertThat(handlerCalls).hasValue(1); + verifyNoInteractions(owner); + } + + @Test + void clientPinsExactWorldPeerBeforeSendingRequest() throws Exception { + var input = request(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var owner = mock(WorldPublicationTerminalService.class); + var service = new WorldPublicationTerminalCompletionGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, pki.otherNamespaceWorldServer(), service, handlerCalls, false, null); + var client = worldClient(pki, server.port())) { + client.init(); + assertThatThrownBy(() -> client.complete(input.request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + } + + assertThat(handlerCalls).hasValue(0); + verifyNoInteractions(owner); + } + + @Test + void authenticatedEndUserContextIsDeniedBeforeOwner() throws Exception { + var input = request(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var owner = mock(WorldPublicationTerminalService.class); + var service = new WorldPublicationTerminalCompletionGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, true, null); + var channel = managedChannel(pki, server.port(), pki.gameDesignClient())) { + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub(channel.channel()) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .completeVersionPublication(input.wire())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + + assertThat(handlerCalls).hasValue(1); + verifyNoInteractions(owner); + } + + @Test + void defaultMissingVerifierFailsClosedWithoutOwnerStorage() throws Exception { + var input = request(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var repository = mock(WorldPublicationTerminalRepository.class); + var owner = new WorldPublicationTerminalService(repository); + var service = new WorldPublicationTerminalCompletionGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, false, null); + var channel = managedChannel(pki, server.port(), pki.gameDesignClient())) { + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub(channel.channel()) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .completeVersionPublication(input.wire())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + + assertThat(handlerCalls).hasValue(1); + verifyNoInteractions(repository); + } + + @Test + void missingClientCertificateIsRejectedDuringTlsBeforeHandlerOrOwner() throws Exception { + var input = request(); + var pki = + WorldOriginalStartSessionActivationTransportTestSupport.TestPki.create(temporaryDirectory); + var owner = mock(WorldPublicationTerminalService.class); + var service = new WorldPublicationTerminalCompletionGrpcService(owner, "test"); + var handlerCalls = new AtomicInteger(); + + try (var server = + WorldOriginalStartSessionActivationTransportTestSupport.startServer( + pki, service, handlerCalls, false, null); + var unauthenticatedClient = + WorldOriginalStartSessionActivationTransportTestSupport.clientWithoutIdentity( + pki, server.port())) { + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub( + unauthenticatedClient.channel()) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .completeVersionPublication(input.wire())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + } + + assertThat(handlerCalls).hasValue(0); + verifyNoInteractions(owner); + } + + private static RequestFixture request() throws Exception { + GameDesignPublicationOperationBinding operation = + WorldGameDesignPublicationTerminalVerifierTest.operation(); + GameDesignPublicationTerminalEvidence terminal = + WorldGameDesignPublicationTerminalVerifierTest.terminal(operation, Outcome.PUBLISHED); + var request = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), terminal.canonicalBytes()); + return new RequestFixture( + request, WorldPublicationTerminalCompletionGrpcCodec.toRequest(request)); + } + + private static ManagedChannel channel( + WorldOriginalStartSessionActivationTransportTestSupport.TestPki pki, + int port, + WorldOriginalStartSessionActivationTransportTestSupport.TestIdentity identity) + throws Exception { + return NettyChannelBuilder.forAddress(new InetSocketAddress("127.0.0.1", port)) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager(identity.privateKey(), identity.certificate()) + .build()) + .build(); + } + + private static ManagedChannelResource managedChannel( + WorldOriginalStartSessionActivationTransportTestSupport.TestPki pki, + int port, + WorldOriginalStartSessionActivationTransportTestSupport.TestIdentity identity) + throws Exception { + return new ManagedChannelResource(channel(pki, port, identity)); + } + + private WorldPublicationTerminalCompletionClient worldClient( + WorldOriginalStartSessionActivationTransportTestSupport.TestPki pki, int port) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + port); + return new WorldPublicationTerminalCompletionClient( + endpoints, + pki.clientProperties(temporaryDirectory, pki.gameDesignClient()), + new GrpcChannelFactory(), + "test"); + } + + private record RequestFixture( + WorldPublicationTerminalCompletionGrpcCodec.Request request, + net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationRequest wire) {} + + private record ManagedChannelResource(ManagedChannel channel) implements AutoCloseable { + @Override + public void close() throws InterruptedException { + channel.shutdownNow(); + if (!channel.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback gRPC client did not terminate"); + } + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcServiceTest.java new file mode 100644 index 0000000000..70ea366b0f --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcServiceTest.java @@ -0,0 +1,137 @@ +package unit.net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +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 net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalCompletionGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalService; +import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationRequest; +import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Receiver boundary units; positive workload identity is exercised with loopback mTLS separately. + */ +class WorldPublicationTerminalCompletionGrpcServiceTest { + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void rejectsMissingWrongServiceAndWrongNamespaceBeforeDecodingOrOwnerCalls() { + var owner = mock(WorldPublicationTerminalService.class); + var service = new WorldPublicationTerminalCompletionGrpcService(owner, "test"); + var malformed = CompleteVersionPublicationRequest.getDefaultInstance(); + + assertFailure(Status.Code.UNAUTHENTICATED, invoke(service, null, malformed)); + assertFailure( + Status.Code.PERMISSION_DENIED, + invoke(service, peer("test", "game-session-service"), malformed)); + assertFailure( + Status.Code.PERMISSION_DENIED, + invoke(service, peer("other", "game-design-service"), malformed)); + verifyNoInteractions(owner); + } + + @Test + void rejectsEndUserContextBeforeDecodingOrOwnerCalls() { + var owner = mock(WorldPublicationTerminalService.class); + var service = new WorldPublicationTerminalCompletionGrpcService(owner, "test"); + SessionContext.setContext("authenticated-user", java.util.List.of(), java.util.Map.of()); + + assertFailure( + Status.Code.PERMISSION_DENIED, + invoke( + service, + peer("test", "game-design-service"), + CompleteVersionPublicationRequest.getDefaultInstance())); + verifyNoInteractions(owner); + } + + @Test + void authenticatedMalformedAndUnknownFieldRequestsFailBeforeOwnerCalls() { + var owner = mock(WorldPublicationTerminalService.class); + var service = new WorldPublicationTerminalCompletionGrpcService(owner, "test"); + var peer = peer("test", "game-design-service"); + var malformed = CompleteVersionPublicationRequest.getDefaultInstance(); + var unknown = + malformed.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + + assertFailure(Status.Code.INVALID_ARGUMENT, invoke(service, peer, malformed)); + assertFailure(Status.Code.INVALID_ARGUMENT, invoke(service, peer, unknown)); + verifyNoInteractions(owner); + } + + private static void assertFailure(Status.Code expected, Observation observation) { + assertThat(observation.code()).isEqualTo(expected); + assertThat(observation.response()).isNull(); + assertThat(observation.completed()).isFalse(); + } + + private static Observation invoke( + WorldPublicationTerminalCompletionGrpcService service, + GrpcPeerIdentity peer, + CompleteVersionPublicationRequest request) { + var observer = new Collector(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + service.completeVersionPublication(request, observer); + } finally { + context.detach(previous); + } + return new Observation( + observer.failure == null ? null : Status.fromThrowable(observer.failure).getCode(), + observer.response, + observer.completed); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service); + } + + private record Observation( + Status.Code code, CompleteVersionPublicationResponse response, boolean completed) {} + + private static final class Collector + implements StreamObserver { + private CompleteVersionPublicationResponse response; + private Throwable failure; + private boolean completed; + + @Override + public void onNext(CompleteVersionPublicationResponse value) { + response = value; + } + + @Override + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The test collector retains the original failure for status assertions.") + public void onError(Throwable error) { + failure = error; + } + + @Override + public void onCompleted() { + completed = true; + } + } +} From 5eb437e331c37f068d1894d32b71e721478cee7b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:06:04 +1300 Subject: [PATCH 117/129] Repair original-attempt SQL and historical composition fixtures --- design/project-management/ai-observations.md | 6 ++ ...ame-authoring-publishing-and-activation.md | 6 +- ...rldAcquisitionPostgresIntegrationTest.java | 2 +- ...anonicalInstancePreparationRepository.java | 4 +- ...nceAssociationPostgresIntegrationTest.java | 13 +-- ...aphApplicationPostgresIntegrationTest.java | 83 ++++++++++++++++++- ...gionAssignmentPostgresIntegrationTest.java | 21 +++-- 7 files changed, 117 insertions(+), 18 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index f44580a517..b22f32bab9 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -246,3 +246,9 @@ Entry format: - Observation: The fixture bodies were semantically identical, but fresh javac rejects the duplicate class. The precise local incremental/cache mechanism is not established; a successful reused result did not establish fresh compilation of the combined source set. - Expected pattern: Consolidate same-package helpers at one owner, and force the affected compilation after this kind of integration discrepancy without deleting caches or weakening tests. Distinguish reused local results from fresh CI execution. - Current status: The redundant helper was removed while both tests retain the same canonical tuple. Forced Common Platform checks passed with 715 executed tests and no skips or failures; replacement exact-head CI remains a separate evidence requirement. + +- `2026-10-11`: Raw jOOQ timestamp binds can conceal an existing PostgreSQL function + - Context: Exact-source #3105 physical World tests reported an undefined retained-attempt persistence routine even though V63 had installed it. The reported argument types showed a character-varying lease expiry where the function requires TIMESTAMPTZ; the separate durable-abort call has the same boundary. + - Observation: An OffsetDateTime Java argument and successful compilation do not prove the timestamp type used by the raw SQL overload. Container-skipped tests leave PostgreSQL function resolution untested. The truncated routine name alone does not establish a missing migration. + - Expected pattern: Compare the complete PostgreSQL signature with the reported JDBC argument types, cast the exact timestamp parameter at the call boundary, and preserve its value and the migration bytes. Inspect placeholder count and position after editing long SQL calls; compilation alone cannot catch an omitted placeholder. + - Current status: The persistence and abort call-boundary corrections pass affected local checks; parent inspection corrected a malformed abort placeholder edit before validation. Corrected physical execution and the separately reported failures remain unqualified. 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 ba0d72d265..1d09d0e51e 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 @@ -6,9 +6,13 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Exact source `419404eb2a9d9f48325f52985dbfc07a8bc3d7be` failed [Validation run 38117670759](https://github.com/benhook1013/FireMUD/actions/runs/38117670759). Originating World XML records 230 integration executions, 62 failures and no skips; 53 failures expose or assert against the retained-attempt persistence function's timestamp signature mismatch. A separate abort call has the same timestamp-binding defect. Four lock-wait or concurrency-latch failures may cascade from failed persistence, while the adapter's `INTERNAL` response has no retained exact cause attribution; they remain unresolved until corrected physical execution. Other failures expose stale V63 diagnostic expectations and historical fixture prerequisites or row-shape comparisons. The Account composition logs an exact migration-head assertion of 35 against the applied Game Session head 46 before cancellation; its uploaded unit artifact contains no failed integration suite and supplies no positive composition proof. The bounded repairs preserve migration checksums, original authority and finite leases. The tested merge is `0c14304153a3c47af945379d4e6381a5c364c39e`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, rather than intended held parent `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`. This is exact-source failure evidence, not intended-base qualification. Corrected physical source/release/preparation/settlement proof, genuine Entity placement and operational-region delivery remain open. + +The source repairs explicitly cast the unchanged original-attempt lease expiry at the persistence and abort SQL call boundaries, align V63 denial diagnostics, and retain the Account fixture’s strict latest Game Session migration assertion at V46. The legacy V45 fixture now supplies its required V44 terminal through existing database triggers and an atomic exact-fence owner transition, with terminal/operation byte readback; its stipulated inventory is synthetic storage evidence and adds no V53 Account qualification. The region-history fixture compares all original World fields and separately asserts that both V64 catalog fields remain null. Local affected Account/World/Game Design full checks cover 2,672 passing unit results (688 World executions; 1,399 Account and 585 Game Design results reused), thirteen non-container integration executions and 671 container skips. Those skips include the failed physical boundaries and genuine compositions; they provide no corrected PostgreSQL or intended-base proof. + Selected publication now has distinct unregistered Game Design-to-World completion and Game Design-to-Account settlement transports. World independently authenticates and reads the complete immutable Game Design terminal through its existing verifier before committing its local terminal; Account independently reads both owners outside SQL before serializing settlement against the original source authorization. Closed codecs verify complete operation echoes, terminal evidence and the existing six-frame Account receipt. Fresh transport correlation does not replace the original operation or permit another mutation. Both genuine-release definitions compose these native handoffs after actual publication and before StartSession, with independent Account receipt and timestamp readback; they remain container-dependent definitions until physically executed. The 32 MiB per-message budgets are transport limits, not a canonical terminal-content cap, and do not qualify dependent terminal readers or production registration. Runtime paths remain unregistered and denied. -The corrected four-module check passes in 2 minutes 44 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. World freshly executes 688 unit cases, including seven loopback-mTLS completion cases and three receiver-denial cases; Common Platform, Account and Game Design reuse 730, 1,399 and 585 successful unit results from the preceding run. The new Common codecs' eight cases and Account receiver's two cases executed in that preceding run. Thus the corrected state has 3,402 passing unit cases, with no unit skips. Account freshly executes twelve non-container integration cases and skips 289 container cases; World reuses one execution and 229 skips; Game Design skips all 153 integration cases, including both genuine-release scenarios. Initial fixture compilation failures were invalid channel cleanup/TLS argument order and a duplicate local variable; the repairs changed no guards or assertions. World loopback success uses a mocked owner and synthetic terminal evidence: it proves exact-peer transport, not durable publication completion. The numbered-history correction compiles but its PostgreSQL cases remain unexecuted locally. All four genuine handoffs remain open pending physical composition, real Entity placement and operational-region delivery. +The previous four-module checkpoint passes in 2 minutes 44 seconds, including integration compilation, formatting, Checkstyle, SpotBugs and coverage. World freshly executes 688 unit cases, including seven loopback-mTLS completion cases and three receiver-denial cases; Common Platform, Account and Game Design reuse 730, 1,399 and 585 successful unit results from the preceding run. The new Common codecs' eight cases and Account receiver's two cases executed in that preceding run. Thus the corrected state has 3,402 passing unit cases, with no unit skips. Account freshly executes twelve non-container integration cases and skips 289 container cases; World reuses one execution and 229 skips; Game Design skips all 153 integration cases, including both genuine-release scenarios. Initial fixture compilation failures were invalid channel cleanup/TLS argument order and a duplicate local variable; the repairs changed no guards or assertions. World loopback success uses a mocked owner and synthetic terminal evidence: it proves exact-peer transport, not durable publication completion. The numbered-history correction compiles but its PostgreSQL cases remain unexecuted locally. All four genuine handoffs remain open pending physical composition, real Entity placement and operational-region delivery. Exact source `378b67cbbf0134b2366a526e394f4211e1fa37fa` failed [Validation run 38114653346](https://github.com/benhook1013/FireMUD/actions/runs/38114653346) in `AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest`: the Logging fixture included Flyway's successful, versionless schema-creation entry in its numbered migration assertion. The correction excludes only versionless history while preserving the exact versions 1 through 4 assertion, and applies to the same query in the genuine-release fixture. The reported Account job was cancelled; draft-fence XML was absent. This failed run establishes neither current-source physical qualification nor complete genuine handoff proof. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java index a0d111343d..03bd1dd994 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java @@ -670,7 +670,7 @@ private static GameSessionAttemptStore gameSessionAttemptStore() throws Exceptio + "ORDER BY installed_rank DESC LIMIT 1"), "Game Session migration history has no successful version") .get("version", String.class)); - assertThat(latestMigration).isEqualTo("35"); + assertThat(latestMigration).isEqualTo("46"); var transactionManager = new DataSourceTransactionManager(dataSource); var transactions = new TransactionTemplate(transactionManager); return new GameSessionAttemptStore( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java index eb1b16ab49..a0002dd53c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -266,7 +266,7 @@ private long persistExecutionIntent( authority.requireHeld(); Record intentRow = dsl.fetchOne( - "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -497,7 +497,7 @@ public ExecutionOperation recordDurableAbort(WorldCanonicalInstanceExecutionIden if (identity.hasOriginalAttemptEvidence()) { return dsl.fetchOne( "SELECT operation_state, world_execution_fence, world_instance_id " - + "FROM world_abort_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + "FROM world_abort_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", identity.targetNamespace(), identity.canonicalTenantId(), identity.controlPlaneRequestId(), diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index 3e7b718b68..8d632557f9 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -1303,7 +1303,8 @@ void durableAbortBlocksFreshServiceV35AndV34Writers() { "SELECT * FROM world_prepare_canonical_instance(?, ?)", inputJson, inputDigest)) .isInstanceOf(DataIntegrityViolationException.class) .rootCause() - .hasMessageContaining("exact current World execution identity and fence"); + .hasMessageContaining( + "V35 requires the exact current World and Account owner-observation identity"); assertThatThrownBy( () -> dsl.execute("INSERT INTO world_canonical_instance_association DEFAULT VALUES")) .isInstanceOf(DataIntegrityViolationException.class) @@ -1338,7 +1339,8 @@ void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { "SELECT * FROM world_prepare_canonical_instance(?, ?)", inputJson, inputDigest)) .isInstanceOf(DataIntegrityViolationException.class) .rootCause() - .hasMessageContaining("exact current World execution identity and fence"); + .hasMessageContaining( + "V35 requires the exact current World and Account owner-observation identity"); assertThatThrownBy( () -> @@ -1347,7 +1349,7 @@ void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { status -> { Record intentRow = dsl.fetchOne( - "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -1411,7 +1413,8 @@ void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { })) .isInstanceOf(DataIntegrityViolationException.class) .rootCause() - .hasMessageContaining("exact current World execution identity and fence"); + .hasMessageContaining( + "V35 requires the exact current World and Account owner-observation identity"); assertThat(preparationCount(identity.canonicalGameInstanceId())).isZero(); assertThat(associationCount(identity.canonicalGameInstanceId())).isZero(); } @@ -2124,7 +2127,7 @@ private long retainAndClaimExecutionIntent( status -> { Record intentRow = dsl.fetchOne( - "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 6b3aae2909..0fd0cd3602 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -4187,6 +4187,87 @@ void v65UpgradeRetainsV52EvolvedLegacyActivationBytesWithoutProtectedAdoption() historical.migrateHistoricalSchema(schema.schema(), "43"); historical.migrateHistoricalSchema(schema.schema(), "45"); + // This synthetic V44 terminal retains the exact historical World source and selector. Its + // stipulated inventory carrier permits the legacy schema to store the complete operation + // bytes without adding a V53 Account qualification row or claiming current authority. + var historicalLaunchEvidence = input.completeLaunchBinding().evidence(); + var historicalRelease = historicalLaunchEvidence.releaseAttestation(); + var historicalWorldEvidence = + Objects.requireNonNull(historicalRelease.worldStartLocationEvidence()); + var historicalSelection = + historical.publicationSelection( + input.topologyPlan().sourceBinding().plan(), + historicalWorldEvidence.request().publicationRequestId(), + historicalWorldEvidence.request().versionStateEpoch()); + assertThat(historicalSelection.digest()) + .isEqualTo("sha256:" + historicalWorldEvidence.request().requestDigest()); + var historicalAccountBinding = + historical.isolatedPublicationAccountBinding( + historicalWorldEvidence.originalAccountBindingBytes(), + historicalSelection, + historicalWorldEvidence.request().publicationRequestId()); + var historicalInventory = + net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures.stipulated( + historicalAccountBinding, historicalWorldEvidence); + var historicalOperation = + new GameDesignPublicationOperationBinding( + historicalAccountBinding, historicalWorldEvidence, historicalInventory); + var historicalTerminal = + new GameDesignPublicationTerminalEvidence( + historicalOperation.canonicalBytes(), + Outcome.PUBLISHED, + historical.isolatedReleaseContent(input), + historicalRelease.versionStateEpoch()); + var historicalTerminalRequest = + WorldPublicationTerminal.Request.fromStored(historicalTerminal.canonicalBytes()); + UUID historicalPublicationFence = historicalWorldEvidence.request().publicationFence(); + historical + .ownerTransaction() + .execute( + status -> { + historical.insertPublicationTerminal(historicalTerminalRequest); + Record attempt = + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT local_tenant_key,version_id " + + "FROM world_design_publication_fence_attempt " + + "WHERE publication_fence=? AND target_namespace=? " + + "AND canonical_tenant_id=? AND canonical_version_id=?", + historicalPublicationFence, + historicalWorldEvidence.request().targetNamespace(), + historicalWorldEvidence.request().canonicalTenantId(), + historicalWorldEvidence.request().canonicalVersionId()), + "V44 historical terminal has no exact retained publication attempt"); + int updated = + historical.dsl.execute( + "UPDATE world_design_publication_fence_owner " + + "SET owner_freeze_phase='PUBLISHED' " + + "WHERE target_namespace=? AND canonical_tenant_id=? " + + "AND local_tenant_key=? AND version_id=? " + + "AND owner_freeze_phase='FROZEN' AND current_publication_fence=?", + historicalWorldEvidence.request().targetNamespace(), + historicalWorldEvidence.request().canonicalTenantId(), + attempt.get("local_tenant_key", Long.class), + attempt.get("version_id", Long.class), + historicalPublicationFence); + if (updated != 1) { + throw new IllegalStateException( + "V44 historical terminal lost its exact FROZEN publication owner"); + } + return null; + }); + assertThat(historical.publicationOwnerPhase(historicalPublicationFence)).isEqualTo("PUBLISHED"); + assertThat(historical.publicationTerminalCount(historicalPublicationFence)).isEqualTo(1L); + assertThat(historical.publicationTerminalBytes(historicalPublicationFence)) + .containsExactly(historicalTerminalRequest.terminalBytes()); + Record retainedHistoricalTerminal = + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT operation_bytes FROM world_design_publication_terminal " + + "WHERE publication_fence=?", + historicalPublicationFence)); + assertThat(retainedHistoricalTerminal.get("operation_bytes", byte[].class)) + .containsExactly(historicalTerminalRequest.operationBytes()); var preparation = historical.prepareV2ThroughOwnerFunction(input); byte[] preparationRowsBeforeRetry = historical.preparationRows(input.canonicalGameInstanceId()); assertThat(historical.prepareV2ThroughOwnerFunction(input)).isEqualTo(preparation); @@ -4690,7 +4771,7 @@ private long beginSyntheticExecution(WorldCanonicalInstanceExecutionIdentity ide Record persisted = Objects.requireNonNull( dsl.fetchOne( - "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?,?,?,?,?,?,?,?,?,?,?,?,?) " + "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?,?,?,?,?,?,?,?,?,?,CAST(? AS TIMESTAMPTZ),?,?) " + "AS world_execution_fence", identity.preparationInputJson(), identity.preparationInputDigest(), diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java index dfe2ca69e2..6c65df6531 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java @@ -301,14 +301,19 @@ void v44ToV45RetainsLegacyRegionAndPreparationOwnerFunctionIdentity() throws Exc assertThat(retainedRegion.get("original_row", Boolean.class)).isTrue(); assertThat(retainedRegion.get("unassigned", Boolean.class)).isTrue(); assertThat(retainedRegion.get("canonical_id", UUID.class)).isEqualTo(canonicalRegionId); - assertThat( - Objects.requireNonNull( - retained.fetchOne( - "SELECT to_jsonb(w) = ?::jsonb FROM world_instance w WHERE id = ?", - worldBefore, - worldId)) - .get(0, Boolean.class)) - .isTrue(); + var retainedWorld = + Objects.requireNonNull( + retained.fetchOne( + "SELECT (to_jsonb(w) - 'canonical_realm_id' - 'catalog_revision') = " + + "(?::jsonb - 'canonical_realm_id' - 'catalog_revision') AS original_row, " + + "canonical_realm_id IS NULL AS realm_uninferred, " + + "catalog_revision IS NULL AS catalog_uninferred " + + "FROM world_instance w WHERE id = ?", + worldBefore, + worldId)); + assertThat(retainedWorld.get("original_row", Boolean.class)).isTrue(); + assertThat(retainedWorld.get("realm_uninferred", Boolean.class)).isTrue(); + assertThat(retainedWorld.get("catalog_uninferred", Boolean.class)).isTrue(); assertThat( Objects.requireNonNull( retained.fetchOne( From 22d7344de44feb2b8cc312f404f93b658f6c433b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:49:40 +1300 Subject: [PATCH 118/129] Fix original lease SQL typing and retained gameplay fixture reset --- design/project-management/ai-observations.md | 6 + ...ame-authoring-publishing-and-activation.md | 8 ++ .../GameplayCrossServiceStack.java | 120 +++++++++++------- ...CanonicalInstanceActivationRepository.java | 6 +- ...anonicalInstancePreparationRepository.java | 4 +- ...nceAssociationPostgresIntegrationTest.java | 8 +- ...aphApplicationPostgresIntegrationTest.java | 4 +- 7 files changed, 102 insertions(+), 54 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index b22f32bab9..443695d096 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -252,3 +252,9 @@ Entry format: - Observation: An OffsetDateTime Java argument and successful compilation do not prove the timestamp type used by the raw SQL overload. Container-skipped tests leave PostgreSQL function resolution untested. The truncated routine name alone does not establish a missing migration. - Expected pattern: Compare the complete PostgreSQL signature with the reported JDBC argument types, cast the exact timestamp parameter at the call boundary, and preserve its value and the migration bytes. Inspect placeholder count and position after editing long SQL calls; compilation alone cannot catch an omitted placeholder. - Current status: The persistence and abort call-boundary corrections pass affected local checks; parent inspection corrected a malformed abort placeholder edit before validation. Corrected physical execution and the separately reported failures remain unqualified. + +- `2026-10-11`: Read originating JUnit stderr before attributing a failed rollback + - Context: Game Session and TCP physical tests reported a closed JDBC connection during shared-fixture rollback; the initiating SQL error was absent from the fetched job log but retained in the Multiplayer JUnit system-err section. + - Observation: SQLSTATE 0A000 caused Hikari to discard the connection after an explicit reset omitted a new retained foreign-key child. The subsequent rollback error concealed that primary failure in the ordinary stack trace. An unchanged fixture file did not exclude companion drift from source-owned migrations. + - Expected pattern: Inspect the originating XML failure, system-out and system-err before declaring the primary cause unavailable or environmental. Compare the full source schema and immediate foreign-key/immutable-guard descendants with disposable reset SQL; preserve production guards and exact transactional restoration rather than using CASCADE or a broad trigger bypass. + - Current status: The primary failure is attributed, and the bounded fixture correction is prepared. Local container-skipped checks cannot qualify the corrected physical reset or gameplay assertions. 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 1d09d0e51e..72c8ff36a2 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 @@ -6,6 +6,14 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Exact source `5eb437e331c37f068d1894d32b71e721478cee7b` has further physical failure evidence in [Validation run 38127177941](https://github.com/benhook1013/FireMUD/actions/runs/38127177941). World originating integration XML records 230 tests, 59 failures, zero errors and no skips. Retained-attempt claim still binds a character-varying expiry at argument 11 against V63 TIMESTAMPTZ; the same untyped boundary remained in begin and adjacent exact activation predicates. The bounded follow-up makes every original-lease SQL binding in the preparation/activation owners and direct fixtures explicit without changing values, argument order, expiry, authority or migration bytes. Other failures include lock-wait and later container-connectivity fallout; a single timestamp cause is not established for all 59. The V63 durable-abort denial, V65 retention of V52-evolved historical activation bytes and V44-to-V45 region/history preservation cases pass physically on this source, while the direct V35 wrong-fence case remains blocked at claim. These are scoped synthetic owner/storage proofs, not genuine authority or complete handoff proof. + +The same run records 39 Game Session cross-service failures and fourteen of seventeen TCP cases failing. Originating Multiplayer JUnit stderr retains SQLSTATE `0A000`: the shared disposable reset omits the V45 authored-core retention foreign-key child of canonical launch, and failed rollback then reports a closed connection. The source also owns V46 selection-pin retention. The fixture correction includes both exact child tables and their named immutable TRUNCATE guards in the existing atomic reset, validates and restores each original enabled state before and after commit, and uses PostgreSQL name semantics for overlong identifiers. It changes no production guard or schema and adds no CASCADE. No current TCP UnknownHost cause is established. + +The run ended in failure. Account, Game Design and Entity were canceled: their uploaded unit results are 1,399, 585 and 215 cases respectively, with zero failures or skips, and remain partial evidence. Account exceeded the 30-minute job limit after reaching integrationTest; its log names no individual test, SQL error or narrower cause, and both the required Draft authorization fence XML and all integration XML are absent. Cancellation identifies missing proof, not a source-specific defect or successful composition. Game Design and Entity likewise supply no completed integration proof. + +Direct GitHub commit readback and job logs identify actual tested merge `d94d7c26a685bfc23493325d7141372e52765b68` with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source. The preliminary intended-parent claim is superseded; held parent `1a8eefe6824c20b8b07a6d6adadda2ad154476e0` remains unqualified. Document owns scoped CI qualification after the later User correction restoring lane-owned CI. Corrected physical follow-up, genuine source/release/preparation/settlement composition and actual Entity/operational-region handoffs remain open. + Exact source `419404eb2a9d9f48325f52985dbfc07a8bc3d7be` failed [Validation run 38117670759](https://github.com/benhook1013/FireMUD/actions/runs/38117670759). Originating World XML records 230 integration executions, 62 failures and no skips; 53 failures expose or assert against the retained-attempt persistence function's timestamp signature mismatch. A separate abort call has the same timestamp-binding defect. Four lock-wait or concurrency-latch failures may cascade from failed persistence, while the adapter's `INTERNAL` response has no retained exact cause attribution; they remain unresolved until corrected physical execution. Other failures expose stale V63 diagnostic expectations and historical fixture prerequisites or row-shape comparisons. The Account composition logs an exact migration-head assertion of 35 against the applied Game Session head 46 before cancellation; its uploaded unit artifact contains no failed integration suite and supplies no positive composition proof. The bounded repairs preserve migration checksums, original authority and finite leases. The tested merge is `0c14304153a3c47af945379d4e6381a5c364c39e`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the exact source, rather than intended held parent `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`. This is exact-source failure evidence, not intended-base qualification. Corrected physical source/release/preparation/settlement proof, genuine Entity placement and operational-region delivery remain open. The source repairs explicitly cast the unchanged original-attempt lease expiry at the persistence and abort SQL call boundaries, align V63 denial diagnostics, and retain the Account fixture’s strict latest Game Session migration assertion at V46. The legacy V45 fixture now supplies its required V44 terminal through existing database triggers and an atomic exact-fence owner transition, with terminal/operation byte readback; its stipulated inventory is synthetic storage evidence and adds no V53 Account qualification. The region-history fixture compares all original World fields and separately asserts that both V64 catalog fields remain null. Local affected Account/World/Game Design full checks cover 2,672 passing unit results (688 World executions; 1,399 Account and 585 Game Design results reused), thirteen non-container integration executions and 671 container skips. Those skips include the failed physical boundaries and genuine compositions; they provide no corrected PostgreSQL or intended-base proof. diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 7971ae90de..e6be6fd296 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -54,6 +54,17 @@ public final class GameplayCrossServiceStack implements AutoCloseable { static final String SYNTHETIC_LOAD_WORLD_PREFIX = "demo-player-"; static final String SYNTHETIC_LOAD_ACTOR = "test/gameplay-load"; + private static final List BASELINE_TRUNCATE_GUARDS = + List.of( + new TruncateGuard( + "game_session_canonical_instance_launch", + "game_session_canonical_instance_launch_no_truncate"), + new TruncateGuard( + "game_session_original_start_session_authored_actor_core_retention", + "game_session_original_start_session_actor_core_retention_no_truncate"), + new TruncateGuard( + "game_session_original_start_session_selection_pin", + "game_session_original_start_session_selection_pin_no_truncate")); private final AccountRuntimeStubServer accountStub; private final GameDesignStubServer gameDesignStub; @@ -212,27 +223,36 @@ public long freshGameplayBaseline( } jdbc.execute("TRUNCATE TABLE runtime_region_status RESTART IDENTITY"); // This is a disposable Testcontainers baseline reset, not runtime/bootstrap behavior. Keep - // the FK descendants explicit and temporarily suspend only the launch-evidence TRUNCATE guard - // inside the same transaction; the production migration and all application SQL retain it. + // the FK descendants explicit and temporarily suspend only the exact launch-evidence guards + // inside the same transaction; the production migrations and application SQL retain them. TransactionTemplate baselineReset = new TransactionTemplate(gameSession.bean(PlatformTransactionManager.class)); - String originalLaunchGuardState = - baselineReset.execute( - status -> { - String originalState = canonicalLaunchTruncateGuardState(jdbc); - if (!"O".equals(originalState) && !"A".equals(originalState)) { - throw new IllegalStateException( - "Expected exactly one canonical launch TRUNCATE guard enabled during" - + " disposable gameplay fixture reset; observed " - + originalState); - } - jdbc.execute( - "ALTER TABLE game_session_canonical_instance_launch " - + "DISABLE TRIGGER game_session_canonical_instance_launch_no_truncate"); - requireCanonicalLaunchTruncateGuardState(jdbc, "D"); - jdbc.execute( - """ + Map originalGuardStates = + Objects.requireNonNull( + baselineReset.execute( + status -> { + Map originalStates = new LinkedHashMap<>(); + for (TruncateGuard guard : BASELINE_TRUNCATE_GUARDS) { + String originalState = truncateGuardState(jdbc, guard); + if (!"O".equals(originalState) && !"A".equals(originalState)) { + throw new IllegalStateException( + "Expected exactly one enabled TRUNCATE guard during disposable gameplay" + + " fixture reset for " + + guard + + "; observed " + + originalState); + } + originalStates.put(guard, originalState); + } + for (TruncateGuard guard : BASELINE_TRUNCATE_GUARDS) { + setTruncateGuardState(jdbc, guard, "DISABLE"); + requireTruncateGuardState(jdbc, guard, "D"); + } + jdbc.execute( + """ TRUNCATE TABLE + game_session_original_start_session_authored_actor_core_retention, + game_session_original_start_session_selection_pin, game_session_canonical_closed_admission_pointer_request, gameplay_initial_admission_bind_attempt, game_session_canonical_initial_admission_intent, @@ -243,15 +263,21 @@ public long freshGameplayBaseline( game_instances RESTART IDENTITY """); - // PostgreSQL rolls back this transactional trigger change if TRUNCATE fails, - // preserving - // the real guard failure instead of masking it with a re-enable attempt on an aborted - // transaction. - restoreCanonicalLaunchTruncateGuard(jdbc, originalState); - requireCanonicalLaunchTruncateGuardState(jdbc, originalState); - return originalState; - }); - requireCanonicalLaunchTruncateGuardState(jdbc, originalLaunchGuardState); + // PostgreSQL rolls back this transactional trigger change if TRUNCATE fails, + // preserving + // the real guard failure instead of masking it with a re-enable attempt on an + // aborted + // transaction. + for (Map.Entry entry : originalStates.entrySet()) { + setTruncateGuardState(jdbc, entry.getKey(), entry.getValue()); + requireTruncateGuardState(jdbc, entry.getKey(), entry.getValue()); + } + return Map.copyOf(originalStates); + }), + "Disposable baseline reset returned no original guard states"); + for (TruncateGuard guard : BASELINE_TRUNCATE_GUARDS) { + requireTruncateGuardState(jdbc, guard, originalGuardStates.get(guard)); + } if (characterIds.length > 0) { clearScreenBuffers(tenantId, gameplayInstanceId, characterIds); } @@ -265,56 +291,64 @@ public long freshGameplayBaseline( return gameInstanceId; } - private static String canonicalLaunchTruncateGuardState(JdbcTemplate jdbc) { + private static String truncateGuardState(JdbcTemplate jdbc, TruncateGuard guard) { + // Match PostgreSQL's identifier truncation for the overlong V45/V46 trigger names. List states = jdbc.query( """ SELECT tgenabled::text FROM pg_trigger - WHERE tgrelid = 'game_session_canonical_instance_launch'::regclass - AND tgname = 'game_session_canonical_instance_launch_no_truncate' + WHERE tgrelid = CAST(? AS regclass) + AND tgname = CAST(? AS name) AND NOT tgisinternal """, - (row, rowNumber) -> row.getString(1)); + (row, rowNumber) -> row.getString(1), + guard.tableName(), + guard.triggerName()); if (states.size() != 1 || (!"O".equals(states.getFirst()) && !"A".equals(states.getFirst()) && !"D".equals(states.getFirst()))) { throw new IllegalStateException( - "Expected exactly one canonical launch TRUNCATE guard in O, A, or D state during" - + " disposable gameplay fixture reset; observed " + "Expected exactly one TRUNCATE guard in O, A, or D state during disposable gameplay" + + " fixture reset for " + + guard + + "; observed " + states); } return states.getFirst(); } - private static void requireCanonicalLaunchTruncateGuardState( - JdbcTemplate jdbc, String expectedState) { - String observedState = canonicalLaunchTruncateGuardState(jdbc); + private static void requireTruncateGuardState( + JdbcTemplate jdbc, TruncateGuard guard, String expectedState) { + String observedState = truncateGuardState(jdbc, guard); if (!expectedState.equals(observedState)) { throw new IllegalStateException( - "Expected canonical launch TRUNCATE guard state " + "Expected TRUNCATE guard state " + expectedState - + " during disposable gameplay fixture reset; observed " + + " during disposable gameplay fixture reset for " + + guard + + "; observed " + observedState); } } - private static void restoreCanonicalLaunchTruncateGuard(JdbcTemplate jdbc, String state) { + private static void setTruncateGuardState(JdbcTemplate jdbc, TruncateGuard guard, String state) { String enableMode = switch (state) { + case "DISABLE" -> "DISABLE"; case "O" -> "ENABLE"; case "A" -> "ENABLE ALWAYS"; default -> throw new IllegalStateException( - "Cannot restore unsupported canonical launch TRUNCATE guard state " + state); + "Cannot set unsupported TRUNCATE guard state " + state + " for " + guard); }; jdbc.execute( - "ALTER TABLE game_session_canonical_instance_launch " - + enableMode - + " TRIGGER game_session_canonical_instance_launch_no_truncate"); + "ALTER TABLE " + guard.tableName() + " " + enableMode + " TRIGGER " + guard.triggerName()); } + private record TruncateGuard(String tableName, String triggerName) {} + private void clearDefaultDemoAdmissionBinding(JdbcTemplate jdbc, long tenantId) { String requestId = defaultDemoRequestId(tenantId); TransactionTemplate transaction = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java index 89748351dc..20221f3fd3 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java @@ -542,7 +542,7 @@ private Record insertActivationFence(AccountStartSessionActivationProtectionEvid + "original_game_session_lease_expires_at,canonical_realm_id,catalog_revision," + "expected_lifecycle_epoch,expected_row_version,preparing_evidence_bytes,world_execution_fence," + "world_instance_id,world_activation_fence,operation_state) " - + "SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?," + + "SELECT ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,CAST(? AS TIMESTAMPTZ),?,?,?,?,?," + "e.world_execution_fence,e.world_instance_id," + "nextval('world_canonical_instance_activation_fence_seq'),'PENDING' " + "FROM world_canonical_instance_execution e " @@ -554,7 +554,7 @@ private Record insertActivationFence(AccountStartSessionActivationProtectionEvid + "AND e.canonical_game_instance_id=? AND e.original_post_authorization_tuple=? " + "AND e.account_world_participation_id=? AND e.account_world_participation_fence=? " + "AND e.game_session_owner_mutation_id=? AND e.game_session_owner_attempt_id=? " - + "AND e.game_session_owner_fence=? AND e.original_game_session_lease_expires_at=? " + + "AND e.game_session_owner_fence=? AND e.original_game_session_lease_expires_at=CAST(? AS TIMESTAMPTZ) " + "AND e.operation_state='COMMITTED' AND e.world_instance_id=w.id " + "AND a.schema_version=2 AND a.canonical_realm_id=? AND a.catalog_revision=? " + "AND w.canonical_realm_id=a.canonical_realm_id AND w.catalog_revision=a.catalog_revision " @@ -714,7 +714,7 @@ private void requireLocalProtectedActivationBinding( + "AND e.canonical_game_instance_id=? AND e.original_post_authorization_tuple=? " + "AND e.account_world_participation_id=? AND e.account_world_participation_fence=? " + "AND e.game_session_owner_mutation_id=? AND e.game_session_owner_attempt_id=? " - + "AND e.game_session_owner_fence=? AND e.original_game_session_lease_expires_at=? " + + "AND e.game_session_owner_fence=? AND e.original_game_session_lease_expires_at=CAST(? AS TIMESTAMPTZ) " + "AND e.operation_state='COMMITTED' AND e.world_instance_id=w.id " + "AND a.schema_version=2 AND a.canonical_realm_id=? AND a.catalog_revision=? " + "AND w.canonical_realm_id=a.canonical_realm_id AND w.catalog_revision=a.catalog_revision " diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java index a0002dd53c..e09271e303 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -173,7 +173,7 @@ public Result materialize( authority.requireHeld(); Record beginRow = dsl.fetchOne( - "SELECT world_begin_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_begin_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", inputJson, inputDigest, executionIdentity.originalPostAuthorizationTuple(), @@ -302,7 +302,7 @@ private Long claimExecutionIntent( authority.requireHeld(); Record claimRow = dsl.fetchOne( - "SELECT world_claim_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_claim_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", identity.preparationInputJson(), identity.preparationInputDigest(), identity.originalPostAuthorizationTuple(), diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index 8d632557f9..5ab5010200 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -1367,7 +1367,7 @@ void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { intentRow == null ? null : intentRow.get(0, Long.class); Record claimRow = dsl.fetchOne( - "SELECT world_claim_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_claim_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -1384,7 +1384,7 @@ void directV35WriterRequiresTheExactCurrentWorldExecutionFence() { Long claimFence = claimRow == null ? null : claimRow.get(0, Long.class); Record executionRow = dsl.fetchOne( - "SELECT world_begin_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_begin_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -2144,7 +2144,7 @@ private long retainAndClaimExecutionIntent( Long retainedFence = intentRow == null ? null : intentRow.get(0, Long.class); Record claimRow = dsl.fetchOne( - "SELECT world_claim_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_claim_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), @@ -2172,7 +2172,7 @@ private void beginExecution( long executionFence) { Record begunRow = dsl.fetchOne( - "SELECT world_begin_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "SELECT world_begin_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", inputJson, inputDigest, identity.originalPostAuthorizationTuple(), diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 0fd0cd3602..3b578b503f 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -4794,7 +4794,7 @@ private long beginSyntheticExecution(WorldCanonicalInstanceExecutionIdentity ide Record claimed = Objects.requireNonNull( dsl.fetchOne( - "SELECT world_claim_canonical_instance_execution_with_original_attempt(?,?,?,?,?,?,?,?,?,?,?,?,?) " + "SELECT world_claim_canonical_instance_execution_with_original_attempt(?,?,?,?,?,?,?,?,?,?,CAST(? AS TIMESTAMPTZ),?,?) " + "AS world_execution_fence", identity.preparationInputJson(), identity.preparationInputDigest(), @@ -4814,7 +4814,7 @@ private long beginSyntheticExecution(WorldCanonicalInstanceExecutionIdentity ide Record begun = Objects.requireNonNull( dsl.fetchOne( - "SELECT world_begin_canonical_instance_execution_with_original_attempt(?,?,?,?,?,?,?,?,?,?,?,?,?,?) " + "SELECT world_begin_canonical_instance_execution_with_original_attempt(?,?,?,?,?,?,?,?,?,?,?,CAST(? AS TIMESTAMPTZ),?,?) " + "AS world_execution_fence", identity.preparationInputJson(), identity.preparationInputDigest(), From 14a97f2f98024f3b6e307d0331981c44cff327a0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 11 Oct 2026 23:41:40 +1300 Subject: [PATCH 119/129] Align canonical activation schemas and complete catalog SQL bindings --- design/project-management/ai-observations.md | 7 +++ ...ame-authoring-publishing-and-activation.md | 6 +++ ...essionCanonicalRealmCatalogRepository.java | 2 +- ...calGameplayBindingRuntimeTestFixtures.java | 2 +- ...entAttemptReadPostgresIntegrationTest.java | 2 +- ...anonical_activation_preparation_schema.sql | 38 +++++++++++++++ ...nceAssociationPostgresIntegrationTest.java | 3 +- ...aphApplicationPostgresIntegrationTest.java | 48 +++++++++++++++++-- 8 files changed, 101 insertions(+), 7 deletions(-) create mode 100644 services/world-management-service/src/main/resources/db/migration/V66__canonical_activation_preparation_schema.sql diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 443695d096..e4c6dca1b9 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -258,3 +258,10 @@ Entry format: - Observation: SQLSTATE 0A000 caused Hikari to discard the connection after an explicit reset omitted a new retained foreign-key child. The subsequent rollback error concealed that primary failure in the ordinary stack trace. An unchanged fixture file did not exclude companion drift from source-owned migrations. - Expected pattern: Inspect the originating XML failure, system-out and system-err before declaring the primary cause unavailable or environmental. Compare the full source schema and immediate foreign-key/immutable-guard descendants with disposable reset SQL; preserve production guards and exact transactional restoration rather than using CASCADE or a broad trigger bypass. - Current status: The primary failure is attributed, and the bounded fixture correction is prepared. Local container-skipped checks cannot qualify the corrected physical reset or gameplay assertions. + - Outcome (2026-10-11): Published source 22d7344 executes all 39 Game Session and seventeen TCP cross-service cases without failure or skips in run38129815927. This qualifies the corrected disposable reset and its exact guard restoration within those fixtures; it does not qualify the separately failed owner integrations or genuine multi-owner handoffs. + +- `2026-10-11`: Check the complete SQL predicate when retained schemas evolve + - Context: After World lease SQL bindings were repaired, 35 physical activation cases reached an older broad guard that still required preparation schema 2, while the canonical fresh schema-2 association carries selector-bearing preparation schema 4. + - Observation: V65 had qualified the association and protected Account/catalog binding but left the older preparation discriminator unchanged. Passing compilation and synthetic units concealed this contradiction until PostgreSQL reached that predicate. + - Expected pattern: Trace the complete guard against each retained association and payload schema, correlate their accepted historical/current forms, and preserve other binding checks, immutable data and migration checksums. Additive function replacement should require one exact anchor and preserve function identity and grants. + - Current status: The exact production drift is attributed; additive V66 and focused historical/current proof definitions are prepared. Corrected physical activation and the independent sanitized adapter failure remain unqualified. 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 72c8ff36a2..cf1345b1bc 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 @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Exact source `22d7344de44feb2b8cc312f404f93b658f6c433b` ended red in [Validation run 38129815927](https://github.com/benhook1013/FireMUD/actions/runs/38129815927). World originating XML executes 230 integrations with 40 failures, zero errors and no skips. Thirty-five directly hit the V43 activation guard's preparation-schema-2 predicate despite the current complete fresh association using selector-bearing preparation schema 4. The follow-up additive V66 migration correlates retained schema-1 association/preparation-2 history and fresh schema-2 association/preparation-4 without rewriting old migrations or data, changing function identity/grants, admitting no-selector schema 3, or dropping V52 operational-region and V65 Account/catalog checks. Five other failures remain distinct: stale original-tuple and Account-protection diagnostics, a fixture-generated realm UUID changing between exact owner reads, a concurrent activation winner absent after the guard failure, and a sanitized preparation adapter FAILED_PRECONDITION without a retained inner cause. The stable per-fixture realm and diagnostic repairs preserve full exact-byte and zero-write assertions; the concurrent result and adapter still require separately attributed corrected physical proof. + +Game Session uploads 2,031 passing units, 208 integration cases with nineteen failures and 39 passing cross-service cases, although its overall Gradle job exceeds the 20-minute limit. Sixteen integration failures expose a 31-column/30-expression catalog INSERT in the production owner or its direct fixture; three strictly expect V35 after applying V46. The bounded correction supplies the missing final complete-policy-evidence bind with every original value and column order unchanged, and asserts the exact current migration checkpoint. TCP completes 192 units, seven integrations and seventeen cross-service cases with zero failures, errors or skips. The corrected disposable retained-child reset therefore has scoped physical gameplay fixture proof, while the failed catalog and activation boundaries remain open. Game Logic completes 115 units and nine integrations without failure; neither result proves the genuine selected release or Entity delivery handoff. + +Account is canceled during integrationTest at its 30-minute job limit, retaining 1,399 passing units and no integration or required Draft authorization fence XML. Game Design and Entity are canceled with 585 and 215 passing unit cases respectively; the two genuine export definitions and their native completion/settlement assertions are absent from the available evidence. Direct runner checkout and GitHub commit readback give merge `a0c957101eb4544e9b1c67937620f26924afacfb`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and exact source `22d7344`. Held intended parent `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`, genuine source/release/preparation/settlement composition, actual Entity/CharacterCreate and operational-region handoffs remain unqualified. All four handoffs, five checklist outcomes and Major route remain open; broader Unit 1B remains paused. + Exact source `5eb437e331c37f068d1894d32b71e721478cee7b` has further physical failure evidence in [Validation run 38127177941](https://github.com/benhook1013/FireMUD/actions/runs/38127177941). World originating integration XML records 230 tests, 59 failures, zero errors and no skips. Retained-attempt claim still binds a character-varying expiry at argument 11 against V63 TIMESTAMPTZ; the same untyped boundary remained in begin and adjacent exact activation predicates. The bounded follow-up makes every original-lease SQL binding in the preparation/activation owners and direct fixtures explicit without changing values, argument order, expiry, authority or migration bytes. Other failures include lock-wait and later container-connectivity fallout; a single timestamp cause is not established for all 59. The V63 durable-abort denial, V65 retention of V52-evolved historical activation bytes and V44-to-V45 region/history preservation cases pass physically on this source, while the direct V35 wrong-fence case remains blocked at claim. These are scoped synthetic owner/storage proofs, not genuine authority or complete handoff proof. The same run records 39 Game Session cross-service failures and fourteen of seventeen TCP cases failing. Originating Multiplayer JUnit stderr retains SQLSTATE `0A000`: the shared disposable reset omits the V45 authored-core retention foreign-key child of canonical launch, and failed rollback then reports a closed connection. The source also owns V46 selection-pin retention. The fixture correction includes both exact child tables and their named immutable TRUNCATE guards in the existing atomic reset, validates and restores each original enabled state before and after commit, and uses PostgreSQL name semantics for overlong identifiers. It changes no production guard or schema and adds no CASCADE. No current TCP UnknownHost cause is established. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java index b01d0bdbb7..57e251b85a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java @@ -772,7 +772,7 @@ private void insertCatalog( + " source_operation_id, source_request_digest, source_world_display_name," + " source_game_row_id, source_game_tenant_key, source_provenance_kind," + " source_evidence_digest, complete_policy_set_evidence)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + " VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", workloadNamespace, source.canonicalTenantId(), source.tenantSlug(), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index f8af5c4830..c2b113cd0e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -158,7 +158,7 @@ private static void seedSourceAndCatalog(DSLContext tx, RuntimeTarget target) { + " source_operation_id, source_request_digest, source_world_display_name," + " source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest," + " complete_policy_set_evidence)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, ?, 1, ?, ?, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)", + + " VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, ?, 1, ?, ?, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?)", target.targetNamespace(), target.canonicalTenantId(), target.tenantSlug(), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java index bdc576e1dd..f0f9363eeb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java @@ -418,7 +418,7 @@ private static Fixture fixture(Duration claimLease) { + "ORDER BY installed_rank DESC LIMIT 1"), "Game Session migration history has no successful version") .get("version", String.class)); - assertThat(latestVersion).isEqualTo("35"); + assertThat(latestVersion).isEqualTo("46"); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); diff --git a/services/world-management-service/src/main/resources/db/migration/V66__canonical_activation_preparation_schema.sql b/services/world-management-service/src/main/resources/db/migration/V66__canonical_activation_preparation_schema.sql new file mode 100644 index 0000000000..3f2b392775 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V66__canonical_activation_preparation_schema.sql @@ -0,0 +1,38 @@ +-- Keep canonical activation's preparation schema correlated with the retained association schema. +-- V43 required schema-1 association/schema-2 preparation. V65 admits the schema-2 association and +-- its captured realm/catalog identity, whose selector-bearing preparation input is schema four. +-- [jooq ignore start] +DO $migration$ +DECLARE + definition TEXT; + original_oid OID; + original_acl ACLITEM[]; + old_fragment TEXT := $$AND p.input_json::JSONB->>'schemaVersion'='2'$$; + new_fragment TEXT := $replacement$AND ( + (a.schema_version=1 AND p.input_json::JSONB->>'schemaVersion'='2') + OR (a.schema_version=2 AND p.input_json::JSONB->>'schemaVersion'='4') + )$replacement$; +BEGIN + SELECT p.oid, p.proacl + INTO STRICT original_oid, original_acl + FROM pg_proc p + WHERE p.oid = '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE; + SELECT pg_get_functiondef( + '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE) + INTO STRICT definition; + + IF (length(definition)-length(replace(definition, old_fragment, '')))/length(old_fragment) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one V65 canonical activation preparation schema discriminator'; + END IF; + definition := replace(definition, old_fragment, new_fragment); + + EXECUTE definition; + IF '"${serviceSchema}".world_validate_canonical_activation_operation()'::REGPROCEDURE + IS DISTINCT FROM original_oid + OR (SELECT p.proacl FROM pg_proc p WHERE p.oid = original_oid) + IS DISTINCT FROM original_acl THEN + RAISE EXCEPTION 'Canonical activation guard replacement changed function identity or grants'; + END IF; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java index 5ab5010200..bee7990597 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationPostgresIntegrationTest.java @@ -1203,7 +1203,8 @@ void exactIdentitySubstitutionIsRejectedBeforeAnyNewSourceOrWriterWork() { input, changedTupleIdentity)) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("differs from the exact original StartSession tuple"); + .hasMessageContaining( + "Original StartSession tuple differs from the exact assembled World operation"); WorldCanonicalInstancePreparation.Input substitutedInput = preparationInput(fixture, canonicalGameInstanceId, UUID.randomUUID(), "GS_FIXTURE", 1L); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index 3b578b503f..c87d3f9098 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -2012,7 +2012,9 @@ void canonicalActivationRequiresExactLocalSchemaTwoRealmAndCatalog() { () -> service.activateProtected(protection, stipulatedActivationAuthority())) .isInstanceOf( WorldCanonicalInstanceActivationRepository.ActivationConflictException.class) - .hasMessageContaining("does not match the committed original execution"); + .hasMessageContaining( + "Account activation protection differs from the exact committed World execution, " + + "schema-2 local realm/catalog association, or preparation"); } assertThat(activationOperationCountForRequest(request.activationRequestId())).isZero(); assertThat( @@ -4153,7 +4155,7 @@ void inertV1PreparationRetainsOriginalBytesAndCannotGainSelectorOnRetry() throws } @Test - void v65UpgradeRetainsV52EvolvedLegacyActivationBytesWithoutProtectedAdoption() { + void v66UpgradeRetainsV52EvolvedLegacyActivationBytesWithoutProtectedAdoption() { HistoricalSchemaFixture schema = historicalSchemaAt("world_v42_legacy_activation", "42"); WorldDraftGraphApplicationPostgresIntegrationTest historical = schema.database(); Fixture f = historical.fixture(); @@ -4438,12 +4440,51 @@ void v65UpgradeRetainsV52EvolvedLegacyActivationBytesWithoutProtectedAdoption() assertThat(worldAtV65.get("canonical_realm_id", UUID.class)).isNull(); assertThat(worldAtV65.get("catalog_revision", Long.class)).isNull(); + Record activationGuardAtV65 = + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT p.oid::bigint AS function_oid,p.proacl::text AS function_acl " + + "FROM pg_proc p WHERE p.oid=to_regprocedure " + + "(current_schema() || '.world_validate_canonical_activation_operation()')")); + historical.migrateHistoricalSchema(schema.schema(), "66"); + Record activationGuardAtV66 = + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT p.oid::bigint AS function_oid,p.proacl::text AS function_acl " + + "FROM pg_proc p WHERE p.oid=to_regprocedure " + + "(current_schema() || '.world_validate_canonical_activation_operation()')")); + assertThat(activationGuardAtV66.get("function_oid", Long.class)) + .isEqualTo(activationGuardAtV65.get("function_oid", Long.class)); + assertThat(activationGuardAtV66.get("function_acl", String.class)) + .isEqualTo(activationGuardAtV65.get("function_acl", String.class)); + var associationAtV66 = + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT schema_version,canonical_realm_id,catalog_revision " + + "FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())); + assertThat(associationAtV66.get("schema_version", Short.class)).isEqualTo((short) 1); + assertThat(associationAtV66.get("canonical_realm_id", UUID.class)).isNull(); + assertThat(associationAtV66.get("catalog_revision", Long.class)).isNull(); + assertThat( + Objects.requireNonNull( + historical.dsl.fetchOne( + "SELECT input_json::JSONB->>'schemaVersion' FROM " + + "world_canonical_instance_preparation " + + "WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId())) + .get(0, String.class)) + .isEqualTo("2"); + assertThat( historical.rowJson( "SELECT to_jsonb(o)::text FROM world_canonical_instance_activation_operation o " + "WHERE activation_request_id=?", request.activationRequestId())) .containsExactly(operationJsonBeforeUpgrade); + assertThat(historical.preparationRows(input.canonicalGameInstanceId())) + .containsExactly(preparationRowsBeforeRetry); assertThat( historical.rowJson( "SELECT (to_jsonb(a)-'canonical_realm_id'-'catalog_revision')::text " @@ -5485,6 +5526,7 @@ private PreparationAssemblyFixture preparationAssemblyFixture( Mockito.when(gameDesign.getComplete(Mockito.any())).thenReturn(returnedPair); var gameSession = Mockito.mock(CanonicalGameInstanceLaunchAssociationClient.class); + UUID canonicalRealmId = UUID.randomUUID(); Mockito.when(gameSession.read(Mockito.any())) .thenAnswer( invocation -> { @@ -5496,7 +5538,7 @@ private PreparationAssemblyFixture preparationAssemblyFixture( playableStateNamespaceId, RealmEntryPolicy.StateScope.SHARED, true, - UUID.randomUUID(), + canonicalRealmId, 1L, CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus .STARTING, From 95f073974124c28d75d8c9708a5a611e998173b9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 00:22:24 +1300 Subject: [PATCH 120/129] fix(gameplay): align protected activation and original-owner SQL --- design/project-management/ai-observations.md | 7 +++++++ .../game-authoring-publishing-and-activation.md | 6 ++++++ ...AuthoredActorCoreProjectionPostgresIntegrationTest.java | 5 ++--- .../GameSessionAuthoredActorCoreRetentionRepository.java | 2 +- ...eSessionOriginalStartSessionSelectionPinRepository.java | 2 +- .../CanonicalGameplayBindingRuntimeTestFixtures.java | 1 + ...nAuthoredActorCoreRetentionPostgresIntegrationTest.java | 2 +- .../tenant/WorldCanonicalInstanceActivationRepository.java | 3 ++- .../WorldDraftGraphApplicationPostgresIntegrationTest.java | 4 +++- 9 files changed, 24 insertions(+), 8 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index e4c6dca1b9..5b1d86b34b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -265,3 +265,10 @@ Entry format: - Observation: V65 had qualified the association and protected Account/catalog binding but left the older preparation discriminator unchanged. Passing compilation and synthetic units concealed this contradiction until PostgreSQL reached that predicate. - Expected pattern: Trace the complete guard against each retained association and payload schema, correlate their accepted historical/current forms, and preserve other binding checks, immutable data and migration checksums. Additive function replacement should require one exact anchor and preserve function identity and grants. - Current status: The exact production drift is attributed; additive V66 and focused historical/current proof definitions are prepared. Corrected physical activation and the independent sanitized adapter failure remain unqualified. + - Outcome (2026-10-12): Source14a CI38132870825 passes V66 historical bytes/OID/ACL, exact realm/catalog, selector retry and authenticated preparation-adapter cases. The prior sanitized adapter's precise inner cause remains unknown. Twenty-nine activation cases reach a separate exact execution-manifest timestamp mismatch; those and the concurrent winner outcome remain open. + +- `2026-10-12`: Exact execution manifests require identical row timestamps + - Context: Source14a physical World activation reaches its valid protected CAS, but the reserved-tenant guard reports no exact transaction execution manifest. V43 predicts the new row with `CURRENT_TIMESTAMP`; the repository instead writes `clock_timestamp()`. + - Observation: Both expressions use the database clock but produce different row bytes. Exact `expected_new` JSON equality fails before the existing manifest can be consumed, so the later fail-closed numeric-tenant guard is a consequence rather than evidence of unauthorized fixture tenant creation. + - Expected pattern: Trace the manifest producer, exact consumer and actual mutation before changing an acceptance guard. Make the row timestamp identical to the manifest while preserving independent physical-clock finite-lease checks; transaction timestamps are not a substitute for current expiry evaluation. + - Current status: The one-expression CAS correction and an independent forged-namespace diagnostic alignment are prepared; all execution guards, migration bytes and physical-clock eligibility checks remain intact. Corrected PostgreSQL activation and concurrent winner proof require the next normal source CI. 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 cf1345b1bc..62e267ff3e 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 @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Exact source `14a97f2f98024f3b6e307d0331981c44cff327a0` ended red in [Validation run 38132870825](https://github.com/benhook1013/FireMUD/actions/runs/38132870825). World executes 688 passing units and 230 integrations with 31 failures, no errors or skips. The V66 historical bytes/function OID/ACL case, exact realm/catalog and execution-fence checks, independent database-clock lease rechecks, selector retry, and authenticated preparation adapter now pass as scoped physical proof. Twenty-nine failures reach the protected activation CAS but cannot consume its exact execution manifest: V43 predicts `updated_at` with `CURRENT_TIMESTAMP`, while the repository writes `clock_timestamp()`. The narrow follow-up makes that one row timestamp identical to the existing manifest, retaining every execution guard, immutable migration and separate physical-clock expiry check. A concurrent activation test with zero winners remains a possible cascade rather than an independently proven common cause. A forged-namespace test correctly fails the earlier immutable association/launch/preparation/ROOM guard; its diagnostic is aligned while the forgery, raw-CAS denial and zero-write assertions remain intact. + +Game Session executes 2,031 passing units, 208 integrations with eleven failures and 39 passing cross-service cases, without errors or skips. Nine failures expose the runtime fixture's missing `version_state_epoch` bind among fourteen placeholders; the follow-up supplies the exact descriptor epoch without shifting later values. Two authored-core retention cases expose an untyped original lease expiry at the raw SQL boundary. The retention and selection-pin owner INSERTs and direct selection-pin fixture now cast only that unchanged expiry to TIMESTAMPTZ; no lease, authority, schema or guard changes. Game Design retains 585 passing units and one originating-log synthetic-storage failure comparing Integer `2` with PostgreSQL Long `2`; the follow-up removes the unused SQL-binding argument and asserts exact `2L`. Its integration task is canceled at the twenty-minute job limit without integration XML. Both genuine selected export definitions and the genuine Game Logic intake definition remain absent from the available evidence. Entity likewise has 215 passing units and canceled integration without XML. Cancellation does not establish the count failure as the timeout's cause or supply either owner's genuine composition proof. + +Account completes in 28m22s within its unchanged thirty-minute limit: 1,399 units and all 309 integrations pass with no errors or skips. The required Draft authorization fence artifact contains 31 of those integration cases, including both once-only World/restart-reconciliation anchors; it is duplicate evidence, not an additional test count. Native selected-order producer/read transport, exact two-authenticated-owner settlement, atomic rollback and lost-ACK replay anchors also pass. Their test-created upstream authority and owner terminal inputs do not establish all four genuine handoffs. TCP's 192 units, seven integrations and seventeen cross-service cases and Game Logic's 115 units and nine integrations all pass. Direct run and Git commit readback identify tested merge `2acf950e64cf1e69d71d434aef05f24ba10f9b9e` with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and exact source `14a97f2f`, despite the event payload naming intended base `1a8eefe6824c20b8b07a6d6adadda2ad154476e0`. Intended-parent qualification, corrected activation/retention/count physical proof, genuine selected release, protected Entity/CharacterCreate and operational-region delivery remain open. Gameplay's published passive carrier/parser prerequisite supplies no protected producer or terminal handoff. All four handoffs, five checklist outcomes and Major route remain open; broader Unit 1B remains paused. + Exact source `22d7344de44feb2b8cc312f404f93b658f6c433b` ended red in [Validation run 38129815927](https://github.com/benhook1013/FireMUD/actions/runs/38129815927). World originating XML executes 230 integrations with 40 failures, zero errors and no skips. Thirty-five directly hit the V43 activation guard's preparation-schema-2 predicate despite the current complete fresh association using selector-bearing preparation schema 4. The follow-up additive V66 migration correlates retained schema-1 association/preparation-2 history and fresh schema-2 association/preparation-4 without rewriting old migrations or data, changing function identity/grants, admitting no-selector schema 3, or dropping V52 operational-region and V65 Account/catalog checks. Five other failures remain distinct: stale original-tuple and Account-protection diagnostics, a fixture-generated realm UUID changing between exact owner reads, a concurrent activation winner absent after the guard failure, and a sanitized preparation adapter FAILED_PRECONDITION without a retained inner cause. The stable per-fixture realm and diagnostic repairs preserve full exact-byte and zero-write assertions; the concurrent result and adapter still require separately attributed corrected physical proof. Game Session uploads 2,031 passing units, 208 integration cases with nineteen failures and 39 passing cross-service cases, although its overall Gradle job exceeds the 20-minute limit. Sixteen integration failures expose a 31-column/30-expression catalog INSERT in the production owner or its direct fixture; three strictly expect V35 after applying V46. The bounded correction supplies the missing final complete-policy-evidence bind with every original value and column order unchanged, and asserts the exact current migration checkpoint. TCP completes 192 units, seven integrations and seventeen cross-service cases with zero failures, errors or skips. The corrected disposable retained-child reset therefore has scoped physical gameplay fixture proof, while the failed catalog and activation boundaries remain open. Game Logic completes 115 units and nine integrations without failure; neither result proves the genuine selected release or Entity delivery handoff. diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java index 32ca3cce44..41944c145e 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java @@ -94,9 +94,8 @@ void migratesOwnerKeyReadsSyntheticRetainedStorageAndRejectsMutation() throws Ex "SELECT count(*) FROM pg_constraint " + "WHERE conrelid = to_regclass(" + "'game_design_start_session_authored_actor_core_projection') " - + "AND contype = 'f'", - Integer.class)) - .isEqualTo(2); + + "AND contype = 'f'")) + .isEqualTo(2L); var retained = new StartSessionAuthoredActorCoreProjectionRepository(dsl).findByOwner(owner); assertThat(retained).hasSize(1); assertThat(retained.getFirst().targetNamespace()).isEqualTo(owner.targetNamespace()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java index 7f6b2e74f6..a895828277 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java @@ -90,7 +90,7 @@ public StoredSource retainInOwnerTransaction(Candidate candidate) { + "launch_descriptor_id, descriptor_request_digest, descriptor_result_digest, " + "release_attestation_evidence_digest, source_read_request_bytes, " + "canonical_source_result_bytes, source_result_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + "ON CONFLICT (target_namespace, control_plane_request_id) DO NOTHING", candidate.targetNamespace(), candidate.controlPlaneRequestId(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionSelectionPinRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionSelectionPinRepository.java index 376aefa91b..3b590a224a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionSelectionPinRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionSelectionPinRepository.java @@ -87,7 +87,7 @@ public StoredPin retainFirstInOwnerTransaction(Candidate candidate) { + "initial_selection_response_digest, descriptor_pin_request_bytes, " + "descriptor_pin_request_digest, descriptor_pin_response_bytes, " + "descriptor_pin_response_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + "ON CONFLICT (target_namespace, control_plane_request_id) DO NOTHING", candidate.targetNamespace(), candidate.controlPlaneRequestId(), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index c2b113cd0e..4a9afddf75 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -291,6 +291,7 @@ private static void seedStartingRuntimeAndLaunch(DSLContext tx, RuntimeTarget ta descriptor.versionId(), descriptor.releaseBundleId(), target.generationConfigRevision(), + descriptor.versionStateEpoch(), target.controlPlaneRequestId(), launchProof.originalTuple().mutationDigest(), target.publishedReleaseBundleRef()); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java index 2a46e362dd..33d172ec0a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java @@ -396,7 +396,7 @@ private static void insertSelectionPin( + " initial_selection_response_digest, descriptor_pin_request_bytes," + " descriptor_pin_request_digest, descriptor_pin_response_bytes," + " descriptor_pin_response_digest)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", NAMESPACE, tuple.controlPlaneRequestId(), canonicalTenantId, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java index 20221f3fd3..8255f6f2c5 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java @@ -354,10 +354,11 @@ public WorldOriginalStartSessionActivationTerminalEvidence activateProtected( request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, predicted); insertResult(request, committed); held.requireHeld(); + // V43's exact execution manifest predicts this row with the transaction timestamp. int updated = dsl.execute( "UPDATE world_instance SET status='ACTIVE', lifecycle_epoch=lifecycle_epoch+1, " - + "row_version=row_version+1, updated_at=clock_timestamp() " + + "row_version=row_version+1, updated_at=CURRENT_TIMESTAMP " + "WHERE id=(SELECT world_instance_id FROM world_canonical_instance_association " + "WHERE canonical_game_instance_id=? AND schema_version=2 " + "AND canonical_realm_id=? AND catalog_revision=?) " diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index c87d3f9098..b6044f3cfc 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -2910,8 +2910,10 @@ void canonicalActivationRejectsSelfConsistentForgedOwnerBindingsBeforeActiveCas( activationRequest.expectedRowVersion() + 1L, forgedResultBytes, sha256Digest(forgedResultBytes))) + // The forged namespace is rejected by V43's earlier immutable-binding guard. .hasMessageContaining( - "lacks its exact pending Account-protected operation fence"); + "Canonical activation proof differs from immutable World association, " + + "launch, preparation, or ROOM bindings"); dsl.execute("ROLLBACK TO SAVEPOINT forged_world_activation"); // V35's reserved-tenant guard denies a raw write without an activation manifest. dsl.execute("SAVEPOINT forged_active_cas"); From f613be6d66e8da4836ef08c431f73ef93d82eb34 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 01:13:33 +1300 Subject: [PATCH 121/129] Align protected launch and World hold proof fixtures with owner guards --- design/project-management/ai-observations.md | 1 + ...ame-authoring-publishing-and-activation.md | 6 ++ ...calGameplayBindingRuntimeTestFixtures.java | 7 ++- ...aphApplicationPostgresIntegrationTest.java | 56 +++++++++++++++++-- 4 files changed, 64 insertions(+), 6 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 5b1d86b34b..10cc6db906 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -272,3 +272,4 @@ Entry format: - Observation: Both expressions use the database clock but produce different row bytes. Exact `expected_new` JSON equality fails before the existing manifest can be consumed, so the later fail-closed numeric-tenant guard is a consequence rather than evidence of unauthorized fixture tenant creation. - Expected pattern: Trace the manifest producer, exact consumer and actual mutation before changing an acceptance guard. Make the row timestamp identical to the manifest while preserving independent physical-clock finite-lease checks; transaction timestamps are not a substitute for current expiry evaluation. - Current status: The one-expression CAS correction and an independent forged-namespace diagnostic alignment are prepared; all execution guards, migration bytes and physical-clock eligibility checks remain intact. Corrected PostgreSQL activation and concurrent winner proof require the next normal source CI. + - Outcome (2026-10-12): Source95f CI38135328459 passes the concurrent single-winner activation, forged-owner zero-write denial and both independent database-clock expiry negatives. The former 29 execution-manifest failures disappear. The whole positive activation/replay case fails later at a changed-protection diagnostic; two hold-fixture failures remain separate. This is scoped corrected PostgreSQL proof on actual merge e037c33f with parent fe15a31, not intended-parent qualification or a genuine four-owner handoff. 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 62e267ff3e..eafb5d13ac 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 @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Exact source `95f073974124c28d75d8c9708a5a611e998173b9` ends red in [Validation run 38135328459](https://github.com/benhook1013/FireMUD/actions/runs/38135328459). World executes 688 passing units and 230 integrations with three failures, no errors or skips. The concurrent single-winner activation, self-consistent forged-owner zero-write denial, V66 historical bytes/function OID/ACL, authenticated preparation adapter and both independent physical-clock expiry cases pass. These qualify the corrected transaction-timestamp CAS boundary within their fixtures. The whole positive activation/replay case still fails at a later changed-Account-evidence diagnostic; its successful earlier CAS is not a passing whole-case result. A second diagnostic expects hold identity reuse where an earlier exact persisted-association check correctly rejects a changed catalog revision. The bounded follow-up preserves that catalog negative and separately exercises changed-digest identity reuse. The reconciliation fixture attempts two pending holds for one tenant/realm, conflicting with V23's existing unique nonterminal-realm index; its correction uses two independently materialized and activated real World targets, with stipulated activation authority, retaining exact readback, bounded pages, namespace denial and legacy exclusion. + +Game Session executes 2,031 passing units, 208 integrations with six failures and 39 passing cross-service cases, without errors or skips. Both exact authored-core retention and selection-pin cases pass, qualifying the corrected unchanged expiry SQL binds. Five failures expose a fixture promoting its launch to RUNNING without the preparing/active epochs required by the exact lease-bound decision guard. The follow-up supplies those exact stipulated World epochs in the existing promotion, keeping STARTING epochs null and all production guards unchanged. The sixth failure is in `CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest`, inherited only from the actual tested parent and absent from this source and the held intended parent. Its opaque `01`/`02` hold/lifecycle request bytes fail the current structural guard. Canonical typed width-fixture ownership and reconciliation are routed to Gameplay/Overseer; no parent import or topology change is inferred. + +Account again passes 1,399 units and all 309 integrations, with no errors or skips; the separately required 31-case Draft authorization fence artifact duplicates those integrations. Selected-order producer/read, both-owner settlement and atomic lost-ACK recovery anchors remain scoped proof with stipulated upstream authority and owner inputs. Game Design passes 585 units but is canceled before integration XML, leaving the corrected count assertion, genuine selected exports and intake unqualified. Entity's canceled job also supplies no genuine handoff proof. The actual tested merge is `e037c33fab40801aaabeff907b86276d7d48029e`, ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and exact source `95f07397`; intended parent `1a8eefe6824c20b8b07a6d6adadda2ad154476e0` remains unqualified. All four genuine handoffs, five checklist outcomes and Major route remain open. Protected CharacterCreate/Entity and operational-region producer handoffs remain Gameplay-owned; broader Unit 1B stays paused. + Exact source `14a97f2f98024f3b6e307d0331981c44cff327a0` ended red in [Validation run 38132870825](https://github.com/benhook1013/FireMUD/actions/runs/38132870825). World executes 688 passing units and 230 integrations with 31 failures, no errors or skips. The V66 historical bytes/function OID/ACL case, exact realm/catalog and execution-fence checks, independent database-clock lease rechecks, selector retry, and authenticated preparation adapter now pass as scoped physical proof. Twenty-nine failures reach the protected activation CAS but cannot consume its exact execution manifest: V43 predicts `updated_at` with `CURRENT_TIMESTAMP`, while the repository writes `clock_timestamp()`. The narrow follow-up makes that one row timestamp identical to the existing manifest, retaining every execution guard, immutable migration and separate physical-clock expiry check. A concurrent activation test with zero winners remains a possible cascade rather than an independently proven common cause. A forged-namespace test correctly fails the earlier immutable association/launch/preparation/ROOM guard; its diagnostic is aligned while the forgery, raw-CAS denial and zero-write assertions remain intact. Game Session executes 2,031 passing units, 208 integrations with eleven failures and 39 passing cross-service cases, without errors or skips. Nine failures expose the runtime fixture's missing `version_state_epoch` bind among fourteen placeholders; the follow-up supplies the exact descriptor epoch without shifting later values. Two authored-core retention cases expose an untyped original lease expiry at the raw SQL boundary. The retention and selection-pin owner INSERTs and direct selection-pin fixture now cast only that unchanged expiry to TIMESTAMPTZ; no lease, authority, schema or guard changes. Game Design retains 585 passing units and one originating-log synthetic-storage failure comparing Integer `2` with PostgreSQL Long `2`; the follow-up removes the unused SQL-binding argument and asserts exact `2L`. Its integration task is canceled at the twenty-minute job limit without integration XML. Both genuine selected export definitions and the genuine Game Logic intake definition remain absent from the available evidence. Entity likewise has 215 passing units and canceled integration without XML. Cancellation does not establish the count failure as the timeout's cause or supply either owner's genuine composition proof. diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index 4a9afddf75..0db05fc359 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -76,8 +76,13 @@ public static RuntimeTarget seedRunningLaunch( seedSourceAndCatalog(tx, target); seedFreshTenantAssociation(tx, target); seedStartingRuntimeAndLaunch(tx, target); + // The fixture reaches RUNNING with the exact stipulated World ACTIVE epoch. tx.execute( - "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", + "UPDATE game_instances SET status = 'RUNNING'," + + " run_owned_start_preparing_epoch = ?, run_owned_start_active_epoch = ?" + + " WHERE tenant_id = ? AND id = ?", + target.activeWorldEpoch() - 1, + target.activeWorldEpoch(), target.gameSessionTenantId(), target.gameInstanceId()); }); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java index b6044f3cfc..2dc563abea 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationPostgresIntegrationTest.java @@ -1892,7 +1892,8 @@ void canonicalActivationCommitsOneOwnerCasAndReplaysWhileLegacyTerminationIsDeni () -> service.activateProtected(substituted, stipulatedActivationAuthority())) .isInstanceOf( WorldCanonicalInstanceActivationRepository.ActivationConflictException.class) - .hasMessageContaining("retry changed its original protection or activation identity"); + .hasMessageContaining( + "World activation identity is already bound to different Account protection evidence"); } // The single-use activation capability was consumed; its retained ledger cannot authorize a @@ -2660,7 +2661,28 @@ void canonicalInitialAdmissionHoldAcquiresFromRealActiveLifecycleAndRetainsPendi request.expectedPriorPointerVersion()); assertThatThrownBy(() -> repository.acquire(changedBinding, active.request())) .isInstanceOf(WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException.class) - .hasMessageContaining("request identity was reused with changed bindings"); + .hasMessageContaining( + "Canonical World initial-admission request differs from its persisted association"); + Request changedRequestDigest = + new Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + request.activeLifecycleEpoch(), + request.initialAdmissionRequestId(), + "b".repeat(64), + request.initialAdmissionOrigin(), + request.expectedCatalogRevision(), + request.expectedPriorPointerVersion()); + assertThatThrownBy(() -> repository.acquire(changedRequestDigest, active.request())) + .isInstanceOf(WorldCanonicalInitialAdmissionHoldRepository.HoldConflictException.class) + .hasMessageContaining( + "Canonical World initial-admission request identity was reused with changed bindings"); assertThat(repository.readIdentity(request).orElseThrow().canonicalBytes()) .containsExactly(acquired.canonicalBytes()); assertThat( @@ -2691,6 +2713,30 @@ void canonicalHoldReconciliationUsesTypedBoundedPagesAndLegacyFinderExcludesType .lifecycleRepository() .read(lifecycleRequestWithFreshReadId(activation.lifecycleEvidence().request())) .orElseThrow(); + PreparedLifecycleFixture secondFixture = materializedLifecycleFixture(); + var secondActivation = + activateProtected( + secondFixture, + new WorldCanonicalInstanceActivation.Request( + UUID.randomUUID(), secondFixture.preparing()), + ignored -> stipulatedActivationAuthority()); + assertThat(secondActivation.outcome()) + .isEqualTo(WorldCanonicalInstanceActivation.Outcome.COMMITTED); + var secondActive = + secondFixture + .lifecycleRepository() + .read(lifecycleRequestWithFreshReadId(secondActivation.lifecycleEvidence().request())) + .orElseThrow(); + var firstAssociation = fixture.materialized().association(); + var secondAssociation = secondFixture.materialized().association(); + assertThat(secondActive.request().targetNamespace()) + .isEqualTo(active.request().targetNamespace()); + assertThat(secondAssociation.identity().canonicalRealmId()) + .isNotEqualTo(firstAssociation.identity().canonicalRealmId()); + assertThat(secondAssociation.identity().canonicalGameInstanceId()) + .isNotEqualTo(firstAssociation.identity().canonicalGameInstanceId()); + assertThat(secondAssociation.worldPrepareFields().privateTenantKey()) + .isNotEqualTo(firstAssociation.worldPrepareFields().privateTenantKey()); Request firstRequest = canonicalReconciliationHoldRequest( @@ -2700,15 +2746,15 @@ void canonicalHoldReconciliationUsesTypedBoundedPagesAndLegacyFinderExcludesType "c".repeat(64)); Request secondRequest = canonicalReconciliationHoldRequest( - active, - fixture.materialized().association().identity(), + secondActive, + secondAssociation.identity(), "canonical-reconcile-second-" + UUID.randomUUID(), "d".repeat(64)); var repository = new WorldCanonicalInitialAdmissionHoldRepository( dsl, manager, associationRepository(), fixture.lifecycleRepository()); HoldIdentity first = repository.acquire(firstRequest, active.request()); - HoldIdentity second = repository.acquire(secondRequest, active.request()); + HoldIdentity second = repository.acquire(secondRequest, secondActive.request()); // A different valid namespace sees no rows from this real canonical namespace. assertThat(repository.findReconciliationCandidates("otherworld", null, 8)).isEmpty(); From 65da9400d6d366cdc65841c46292bd822af0d1e5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 02:02:53 +1300 Subject: [PATCH 122/129] Align inherited admission fixtures with exact typed launch identities --- design/project-management/ai-observations.md | 7 ++ ...ame-authoring-publishing-and-activation.md | 4 + ...tentRequestIdMigrationIntegrationTest.java | 93 +++++++++++++++++-- ...nCanonicalInstanceLaunchProofFixtures.java | 35 ++++++- 4 files changed, 131 insertions(+), 8 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 10cc6db906..e6c0366d66 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -162,6 +162,7 @@ Entry format: - Observation: The separate substantive Validation run 37928625721 was still executing on the same head; metadata and required runs use distinct concurrency groups. The body edit had not cancelled it. A pending-proof metadata failure is neither a runtime failure nor evidence that no physical validation was dispatched. - Expected pattern: Before requesting replacement CI or routing a dispatch failure, inspect enough same-head runs to distinguish substantive execution from newer metadata preservation, then assign one observer to the actual execution transition. - Current status: Wider read-only inspection established the active run, and the parent corrected the Overseer request. A sole sentinel owns its outcome; no replacement run or workflow/topology change was made. + - Outcome (2026-10-12): The same six-result selection mistake recurred after f613 publication: metadata run38138514591 has no source tests, while original same-head run38138480779 remains active. The parent corrected the native checkpoint, verified the first sentinel had stopped, and assigned one fresh observer to the original run. The standing brief now explicitly requires sufficient exact-head Validation coverage before selecting the observer; no manual rerun or workflow change occurred. - `2026-10-10`: Validate required controller fields before replacing a standing brief - Context: Document read the absent JSON field `body` instead of the required `brief` field when appending an accepted disposition through guarded `jobs revise`. @@ -273,3 +274,9 @@ Entry format: - Expected pattern: Trace the manifest producer, exact consumer and actual mutation before changing an acceptance guard. Make the row timestamp identical to the manifest while preserving independent physical-clock finite-lease checks; transaction timestamps are not a substitute for current expiry evaluation. - Current status: The one-expression CAS correction and an independent forged-namespace diagnostic alignment are prepared; all execution guards, migration bytes and physical-clock eligibility checks remain intact. Corrected PostgreSQL activation and concurrent winner proof require the next normal source CI. - Outcome (2026-10-12): Source95f CI38135328459 passes the concurrent single-winner activation, forged-owner zero-write denial and both independent database-clock expiry negatives. The former 29 execution-manifest failures disappear. The whole positive activation/replay case fails later at a changed-protection diagnostic; two hold-fixture failures remain separate. This is scoped corrected PostgreSQL proof on actual merge e037c33f with parent fe15a31, not intended-parent qualification or a genuine four-owner handoff. + +- `2026-10-12`: A broad exact-identity guard can conceal multiple fixture mismatches + - Context: PR #3105's five lease-bound Game Session fixtures still fail the exact RUNNING/candidate guard after their missing World epochs are supplied. + - Observation: The merged fixture independently generates the candidate canonical version and release-attestation canonical version. Both epoch and version equality are required by the complete guard; fixing one failed predicate does not establish the remaining fixture identity. Originating XML names only the generic guard, not the actual UUID values. + - Expected pattern: Trace every exact guard predicate through the actual tested merge's fixture builders before publishing a repair. Keep the source-proven mismatch separate from directly recorded database values and require corrected physical execution. + - Current status: The existing synthetic launch builder is corrected to carry the runtime target's canonical version. No production guard, lease or owner authority changes; local container skips provide no corrected physical proof. 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 eafb5d13ac..1c98362116 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 @@ -6,6 +6,10 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Published source remains `f613be6d66e8da4836ef08c431f73ef93d82eb34`. Its original [Validation run 38138480779](https://github.com/benhook1013/FireMUD/actions/runs/38138480779) ends red, testing virtual merge `464560fa9ca9cb5bf197eadedf0113bc9eee652a`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source. Its tree `4464ad0867ef631d54a90dd429e8ed2c0e650969` exactly matches the approved local pre-fixture normal merge `f3b28e3ad8767c00df6fa7d1ffc1cb8458bf67e6`, which carries the 33 parent paths without conflict. Published parent `fe15a31f274b1c9850dd388e83faf540916ee8a3` is now the current intended parent; `1a8eefe6824c20b8b07a6d6adadda2ad154476e0` remains historical unqualified evidence. Newer metadata-preservation run `38138514591` performs no source tests and supplies no physical proof. + +Game Session's original f613 XML records 2,278 cases across 226 suites, six failures, no errors or skips. Five exact RUNNING/candidate-identity failures survive the shared promotion's preparing/active epoch correction. Source tracing finds another inconsistent fixture field: the runtime target and release-attestation builder independently generate canonical version UUIDs, while the complete guard requires their equality. The test-only builder correction carries the runtime target's canonical version into its release attestation; all other synthetic callers retain their existing behavior and production guards remain unchanged. The originating XML names the generic guard, so the source trace establishes a definite fixture mismatch rather than recording the failed predicate's actual UUID values; corrected physical execution is still required. The sixth failure is the inherited request-ID width fixture's opaque hold/lifecycle bytes. Its local correction uses typed World hold/lifecycle request bytes, matching Game Session request digest and the exact retained launch tuple, source-intake identities and binding digests required by V44. It preserves 121/128 successful insertion boundaries and 129-character SQLSTATE `22001` rejection, unchanged owner guards and migrations. Gate66 passes local affected Game Session/Common Security/World checks and documentation validation, but skips 445 container cases; the corrected width case has no physical execution credit. Affected canonical validation precedes coherent publication. World f613 executes 688 units and all 230 integrations successfully, including all 69 cases in the draft-graph suite and the three repaired activation/hold/reconciliation cases. Its separate 230-case owner artifact duplicates the integration results. Automation executes 1,206 units and 99 integrations successfully. Account, Game Design and Entity are canceled with only 1,399, 585 and 215 passing unit results respectively, no integration XML; Account also has no required Draft authorization fence capture. Both genuine Game Design export cases and the corrected PostgreSQL count remain unqualified. These scoped passing World/Automation fixtures do not establish genuine upstream authority or complete handoffs. No base-name, queue, runtime or broader Unit 1B change follows. + Exact source `95f073974124c28d75d8c9708a5a611e998173b9` ends red in [Validation run 38135328459](https://github.com/benhook1013/FireMUD/actions/runs/38135328459). World executes 688 passing units and 230 integrations with three failures, no errors or skips. The concurrent single-winner activation, self-consistent forged-owner zero-write denial, V66 historical bytes/function OID/ACL, authenticated preparation adapter and both independent physical-clock expiry cases pass. These qualify the corrected transaction-timestamp CAS boundary within their fixtures. The whole positive activation/replay case still fails at a later changed-Account-evidence diagnostic; its successful earlier CAS is not a passing whole-case result. A second diagnostic expects hold identity reuse where an earlier exact persisted-association check correctly rejects a changed catalog revision. The bounded follow-up preserves that catalog negative and separately exercises changed-digest identity reuse. The reconciliation fixture attempts two pending holds for one tenant/realm, conflicting with V23's existing unique nonterminal-realm index; its correction uses two independently materialized and activated real World targets, with stipulated activation authority, retaining exact readback, bounded pages, namespace denial and legacy exclusion. Game Session executes 2,031 passing units, 208 integrations with six failures and 39 passing cross-service cases, without errors or skips. Both exact authored-core retention and selection-pin cases pass, qualifying the corrected unchanged expiry SQL binds. Five failures expose a fixture promoting its launch to RUNNING without the preparing/active epochs required by the exact lease-bound decision guard. The follow-up supplies those exact stipulated World epochs in the existing promotion, keeping STARTING epochs null and all production guards unchanged. The sixth failure is in `CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest`, inherited only from the actual tested parent and absent from this source and the held intended parent. Its opaque `01`/`02` hold/lifecycle request bytes fail the current structural guard. Canonical typed width-fixture ownership and reconciliation are routed to Gameplay/Overseer; no parent import or topology change is inferred. diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java index efc760bdd8..486816e1f3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java @@ -5,6 +5,9 @@ import java.nio.file.Path; import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingRuntimeTestFixtures; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -66,6 +69,77 @@ private static int insertIntent( DSLContext dsl, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target, String requestId) { + // Read the exact synthetic owner launch row so this width proof retains the same tuple and + // complete binding evidence as the V44 insert guard. + var launch = + dsl.fetchOne( + "SELECT captured_starting_row_version, original_start_session_tuple," + + " complete_launch_binding_evidence -> 'descriptor' ->> 'requestDigest' AS descriptor_request_digest," + + " complete_launch_binding_evidence -> 'descriptor' ->> 'resultDigest' AS descriptor_result_digest," + + " complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest' AS release_attestation_digest" + + " FROM game_session_canonical_instance_launch" + + " WHERE target_namespace = ? AND control_plane_request_id = ?", + target.targetNamespace(), + target.controlPlaneRequestId()); + assertThat(launch).isNotNull(); + long capturedStartingRowVersion = launch.get("captured_starting_row_version", Long.class); + byte[] originalStartSessionTuple = launch.get("original_start_session_tuple", byte[].class); + String descriptorRequestDigest = launch.get("descriptor_request_digest", String.class); + String descriptorResultDigest = launch.get("descriptor_result_digest", String.class); + String releaseAttestationDigest = launch.get("release_attestation_digest", String.class); + + // World accepts the 128-character durable identity width. The 129-character case is rejected + // by the database column width before its row trigger evaluates the canonical request bytes. + String canonicalRequestId = requestId.length() > 128 ? requestId.substring(0, 128) : requestId; + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.gameInstanceUuid(), + target.canonicalVersionId(), + target.activeWorldEpoch(), + target.catalogRevision(), + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + canonicalRequestId); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.gameInstanceUuid(), + target.canonicalVersionId(), + target.activeWorldEpoch(), + canonicalRequestId, + requestDigest, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + target.catalogRevision(), + null); + byte[] lifecycleRequestBytes = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.randomUUID(), + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + target.gameInstanceUuid(), + target.playableStateNamespaceId(), + target.playableStateScope(), + true, + target.controlPlaneRequestId(), + target.canonicalVersionId(), + descriptorRequestDigest, + descriptorResultDigest, + releaseAttestationDigest) + .canonicalBytes(); + return dsl.execute( "INSERT INTO game_session_canonical_initial_admission_intent" + " (target_namespace, initial_admission_request_id, request_digest," @@ -76,15 +150,16 @@ private static int insertIntent( + " canonical_game_instance_id, game_instance_id, canonical_version_id," + " runtime_version_id, control_plane_request_id, launch_descriptor_id," + " captured_starting_row_version, current_row_version, descriptor_request_digest," - + " descriptor_result_digest, release_attestation_digest, canonical_hold_request_bytes," + + " descriptor_result_digest, release_attestation_digest, catalog_source_intake_operation_id," + + " catalog_source_intake_request_id, original_start_session_tuple, canonical_hold_request_bytes," + " canonical_lifecycle_request_bytes, hold_identity_bytes, state, created_at," + " updated_at, terminal_at)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," - + " 0, 1, ?, ?, ?, decode('01', 'hex'), decode('02', 'hex'), NULL, 'PENDING_HOLD'," + + " ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, NULL, 'PENDING_HOLD'," + " now(), now(), NULL)", target.targetNamespace(), requestId, - RAW_SHA256, + requestDigest, target.canonicalTenantId(), target.worldSlug(), target.realmId(), @@ -102,9 +177,15 @@ private static int insertIntent( target.runtimeVersionId(), target.controlPlaneRequestId(), target.launchDescriptorId(), - SHA256, - SHA256, - SHA256); + capturedStartingRowVersion, + descriptorRequestDigest, + descriptorResultDigest, + releaseAttestationDigest, + target.sourceIntakeOperationId(), + target.sourceIntakeRequestId(), + originalStartSessionTuple, + holdRequest.canonicalRequestBytes(), + lifecycleRequestBytes); } private static void migrate(String schema, DriverManagerDataSource dataSource) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchProofFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchProofFixtures.java index d8db1f8ead..2f9fee405b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchProofFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchProofFixtures.java @@ -51,7 +51,8 @@ static SyntheticLaunchProof forRuntimeTarget( target.launchDescriptorId(), target.generationConfigRevision(), 1L, - target.publishedReleaseBundleRef()); + target.publishedReleaseBundleRef(), + target.canonicalVersionId()); } static SyntheticLaunchProof create( @@ -67,6 +68,36 @@ static SyntheticLaunchProof create( String generationConfigRevision, long versionStateEpoch, String publishedReleaseBundleRef) { + return create( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + source, + gameTemplateId, + versionId, + releaseBundleId, + launchDescriptorId, + generationConfigRevision, + versionStateEpoch, + publishedReleaseBundleRef, + UUID.randomUUID()); + } + + private static SyntheticLaunchProof create( + String targetNamespace, + String controlPlaneRequestId, + UUID canonicalTenantId, + String worldSlug, + AuthoredWorldSourceEvidence source, + long gameTemplateId, + long versionId, + long releaseBundleId, + String launchDescriptorId, + String generationConfigRevision, + long versionStateEpoch, + String publishedReleaseBundleRef, + UUID canonicalVersionId) { var tuple = tuple(targetNamespace, controlPlaneRequestId, canonicalTenantId, gameTemplateId); var descriptorRequest = new AuthoredWorldLaunchDescriptorEvidence.Request( @@ -121,7 +152,7 @@ static SyntheticLaunchProof create( targetNamespace, descriptor.resultDigest(), canonicalTenantId, - UUID.randomUUID(), + canonicalVersionId, worldSlug, source.operationId(), source.evidenceDigest(), From 167e95c703bc98c36e3cb98cc985d6613a908067 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 03:00:50 +1300 Subject: [PATCH 123/129] Expose live progress for canceled owner integration tests --- build.gradle.kts | 12 ++++++++++++ design/project-management/ai-observations.md | 7 +++++++ .../game-authoring-publishing-and-activation.md | 10 ++++++++-- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index d1d8d11363..326df8e654 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -312,6 +312,18 @@ subprojects { showCauses = true showStackTraces = true } + + if (name == "integrationTest" + && project.name in + setOf("account-service", "game-design-service", "entity-management-service")) { + testLogging { + // Keep active integration-test boundaries visible when cancellation precedes XML. + events("started", "passed", "failed", "skipped") + minGranularity = 0 + maxGranularity = -1 + showStandardStreams = false + } + } } tasks.test { diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index e6c0366d66..1c33456645 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -280,3 +280,10 @@ Entry format: - Observation: The merged fixture independently generates the candidate canonical version and release-attestation canonical version. Both epoch and version equality are required by the complete guard; fixing one failed predicate does not establish the remaining fixture identity. Originating XML names only the generic guard, not the actual UUID values. - Expected pattern: Trace every exact guard predicate through the actual tested merge's fixture builders before publishing a repair. Keep the source-proven mismatch separate from directly recorded database values and require corrected physical execution. - Current status: The existing synthetic launch builder is corrected to carry the runtime target's canonical version. No production guard, lease or owner authority changes; local container skips provide no corrected physical proof. + - Outcome (2026-10-12): Source65da original CI38141635503 executes all six repaired Game Session cases and all 2,278 service cases without failure, error or skip on actual merge d8c74777 with intended parent fe15. This qualifies the synthetic fixture correction; three other owners' integration cancellations and genuine handoffs remain separate open proof obligations. + +- `2026-10-12`: Canceled integration tasks need live boundaries before complete XML exists + - Context: Source65da CI38141635503 cancels Account, Game Design and Entity during integrationTest after generation, compilation and passing units; their artifact steps retain no integration XML. + - Observation: Full failure-detail logging and canceled-run HTML/XML capture do not record a currently active worker, class or method. Task-entry timestamps bound elapsed integration time but cannot identify a hanging fixture, assertion, container startup or cleanup. + - Expected pattern: Reuse the existing Gradle Test start/completion events only for affected integration owners, suppress standard streams and preserve complete failure details. Keep worker/class/nested-test boundaries visible without adding a parallel report family or changing test selection, budgets or guards. + - Current status: The scoped existing-hook addition passes canonical affected checks and freshly rerun integration tasks. Local logs show worker/class/method starts and completions for each affected owner with streams suppressed; twelve non-container cases pass and 459 container cases skip. Missing owner PostgreSQL integration and genuine handoff proof remains separate; subsequent exact-source execution must identify the actual boundary before any timing repair is inferred. 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 1c98362116..08933dfd96 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 @@ -6,9 +6,15 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Published source remains `f613be6d66e8da4836ef08c431f73ef93d82eb34`. Its original [Validation run 38138480779](https://github.com/benhook1013/FireMUD/actions/runs/38138480779) ends red, testing virtual merge `464560fa9ca9cb5bf197eadedf0113bc9eee652a`, with ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source. Its tree `4464ad0867ef631d54a90dd429e8ed2c0e650969` exactly matches the approved local pre-fixture normal merge `f3b28e3ad8767c00df6fa7d1ffc1cb8458bf67e6`, which carries the 33 parent paths without conflict. Published parent `fe15a31f274b1c9850dd388e83faf540916ee8a3` is now the current intended parent; `1a8eefe6824c20b8b07a6d6adadda2ad154476e0` remains historical unqualified evidence. Newer metadata-preservation run `38138514591` performs no source tests and supplies no physical proof. +Published source `65da9400d6d366cdc65841c46292bd822af0d1e5` is physically exercised in [Validation run 38141635503](https://github.com/benhook1013/FireMUD/actions/runs/38141635503). Actual checkout merge `d8c7477757c13e7b25e44817e1f1e4db90b6d123` has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source; its tree `0099f9afed468fe2a30b6ca9546dba361e2d84cf` equals the source tree. Current intended parent fe15 is qualified for the executed scopes; historical `1a8eefe6824c20b8b07a6d6adadda2ad154476e0` remains prior unqualified evidence. The approved normal merge carries the 33 parent paths without conflict and changes no base name or queue topology. -Game Session's original f613 XML records 2,278 cases across 226 suites, six failures, no errors or skips. Five exact RUNNING/candidate-identity failures survive the shared promotion's preparing/active epoch correction. Source tracing finds another inconsistent fixture field: the runtime target and release-attestation builder independently generate canonical version UUIDs, while the complete guard requires their equality. The test-only builder correction carries the runtime target's canonical version into its release attestation; all other synthetic callers retain their existing behavior and production guards remain unchanged. The originating XML names the generic guard, so the source trace establishes a definite fixture mismatch rather than recording the failed predicate's actual UUID values; corrected physical execution is still required. The sixth failure is the inherited request-ID width fixture's opaque hold/lifecycle bytes. Its local correction uses typed World hold/lifecycle request bytes, matching Game Session request digest and the exact retained launch tuple, source-intake identities and binding digests required by V44. It preserves 121/128 successful insertion boundaries and 129-character SQLSTATE `22001` rejection, unchanged owner guards and migrations. Gate66 passes local affected Game Session/Common Security/World checks and documentation validation, but skips 445 container cases; the corrected width case has no physical execution credit. Affected canonical validation precedes coherent publication. World f613 executes 688 units and all 230 integrations successfully, including all 69 cases in the draft-graph suite and the three repaired activation/hold/reconciliation cases. Its separate 230-case owner artifact duplicates the integration results. Automation executes 1,206 units and 99 integrations successfully. Account, Game Design and Entity are canceled with only 1,399, 585 and 215 passing unit results respectively, no integration XML; Account also has no required Draft authorization fence capture. Both genuine Game Design export cases and the corrected PostgreSQL count remain unqualified. These scoped passing World/Automation fixtures do not establish genuine upstream authority or complete handoffs. No base-name, queue, runtime or broader Unit 1B change follows. +Game Session executes 2,031 units, 208 integrations and 39 cross-service cases, all passing with no errors or skips. All six repaired cases pass: one exact lease-bound runtime decision, four binding-inventory cases and the request-ID width test. The inspected source of that passing width case asserts 121/128-character insertion success and 129-character SQLSTATE `22001` rejection; XML records the named test's result rather than its individual SQL inputs. The synthetic launch builder now carries its runtime target's canonical version into the release attestation, alongside the earlier exact RUNNING preparing/active epochs. The inherited width fixture retains typed World hold/lifecycle bytes, matching request digest and exact V44 launch/catalog tuple. This closes the scoped fixture gaps with production guards, migrations, leases and positive/negative assertions preserved; stipulated upstream authority does not establish genuine handoffs. + +World executes 688 units and all 230 integrations successfully, including all 69 draft-graph cases and the three repaired activation/hold/reconciliation cases. Its separate 230-case owner XML is duplicate evidence. Automation executes 1,206 units and 99 integrations successfully. The overall run ends canceled, and the required gate fails because the build-and-test matrix is canceled: Account reaches its thirty-minute limit, while Game Design and Entity reach their twenty-minute limits during integrationTest. They retain only 1,399, 585 and 215 passing unit results respectively, with no owner integration XML; Account also lacks required Draft authorization fence PostgreSQL XML. Both genuine Game Design exports, the corrected PostgreSQL count and current Account/Entity integrations remain unqualified. Retained logs show no narrower assertion failure or stack trace; the timeout does not establish a source defect. Scoped passing fixtures do not supply actual protected CharacterCreate/Entity, operational-region or complete original-authority handoffs. All four genuine handoffs, five checklist outcomes and Major route remain open; broader Unit 1B stays paused. + +The bounded diagnostic follow-up uses the existing Gradle Test logging hook for only Account, Game Design and Entity integration tasks. It records worker, class and nested test starts/completions, suppresses standard streams and retains existing full failure details and artifact capture. Retained task-entry-to-cancellation intervals are 19m01s for Account, 7m37s for Game Design and 14m21s for Entity; they reveal no individual assertion, active class or cleanup cause. Existing #3149 failure details do not fill that live-progress gap. The follow-up preserves exact tasks, selection, assertions, fixtures, guards, retries, budgets, fullCheck and required gates; it adds no generic tool or report family. Only actual subsequent progress and owner XML can support a narrower timing repair or missing genuine proof. Local gate69 passes the three affected owner checks, freshly rerun integrations, links and all 548 Markdown files in 5m37s across 197 tasks. It verifies worker/class/method STARTED and completion events for each owner with standard streams suppressed; 2,199 fresh unit cases and twelve non-container integration cases pass, while 459 container cases skip. These skips do not qualify the missing owner PostgreSQL, genuine exports or complete handoffs. + +Local gate66 passes the reconciled-parent Game Session generation/check, Common Security and World checks, formatting and documentation validation in 4m49s across 191 tasks, with 2,866 fresh unit passes, seventeen unit skips, 32 non-container passes and 445 container skips. Flyway sanity passes twelve sets and 315 versioned files. The affected fixture/documentation gate67 passes in 1m18s across 135 tasks, freshly compiling integrations and executing thirty non-container cases while 178 container cases skip; its unit and cross-service results are reused from gate66. Those local skips supply no physical proof by themselves. Earlier f613 [run 38138480779](https://github.com/benhook1013/FireMUD/actions/runs/38138480779) exposed the six failures repaired here, and its pre-fixture tree exactly matched the approved local parent merge. Newer metadata-preservation runs perform no source tests and supply no physical proof. Exact source `95f073974124c28d75d8c9708a5a611e998173b9` ends red in [Validation run 38135328459](https://github.com/benhook1013/FireMUD/actions/runs/38135328459). World executes 688 passing units and 230 integrations with three failures, no errors or skips. The concurrent single-winner activation, self-consistent forged-owner zero-write denial, V66 historical bytes/function OID/ACL, authenticated preparation adapter and both independent physical-clock expiry cases pass. These qualify the corrected transaction-timestamp CAS boundary within their fixtures. The whole positive activation/replay case still fails at a later changed-Account-evidence diagnostic; its successful earlier CAS is not a passing whole-case result. A second diagnostic expects hold identity reuse where an earlier exact persisted-association check correctly rejects a changed catalog revision. The bounded follow-up preserves that catalog negative and separately exercises changed-digest identity reuse. The reconciliation fixture attempts two pending holds for one tenant/realm, conflicting with V23's existing unique nonterminal-realm index; its correction uses two independently materialized and activated real World targets, with stipulated activation authority, retaining exact readback, bounded pages, namespace denial and legacy exclusion. From 4870115c25c771bd88948106bcbf5ff0350774b0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 03:14:26 +1300 Subject: [PATCH 124/129] Preserve global logging contract while tracing owner integrations --- build.gradle.kts | 11 +++++++---- design/project-management/ai-observations.md | 2 ++ .../game-authoring-publishing-and-activation.md | 4 +++- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 326df8e654..b87c138d0e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -312,10 +312,14 @@ subprojects { showCauses = true showStackTraces = true } + } - if (name == "integrationTest" - && project.name in - setOf("account-service", "game-design-service", "entity-management-service")) { + tasks.withType() + .matching { + it.name == "integrationTest" && + project.name in setOf("account-service", "game-design-service", "entity-management-service") + } + .configureEach { testLogging { // Keep active integration-test boundaries visible when cancellation precedes XML. events("started", "passed", "failed", "skipped") @@ -324,7 +328,6 @@ subprojects { showStandardStreams = false } } - } tasks.test { useJUnitPlatform() diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 1c33456645..0029ee6d82 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -287,3 +287,5 @@ Entry format: - Observation: Full failure-detail logging and canceled-run HTML/XML capture do not record a currently active worker, class or method. Task-entry timestamps bound elapsed integration time but cannot identify a hanging fixture, assertion, container startup or cleanup. - Expected pattern: Reuse the existing Gradle Test start/completion events only for affected integration owners, suppress standard streams and preserve complete failure details. Keep worker/class/nested-test boundaries visible without adding a parallel report family or changing test selection, budgets or guards. - Current status: The scoped existing-hook addition passes canonical affected checks and freshly rerun integration tasks. Local logs show worker/class/method starts and completions for each affected owner with streams suppressed; twelve non-container cases pass and 459 container cases skip. Missing owner PostgreSQL integration and genuine handoff proof remains separate; subsequent exact-source execution must identify the actual boundary before any timing repair is inferred. + + - Follow-up (2026-10-12): Diagnostic source167e95 fails the existing lightweight-scope contract after all 24 classifier subtests pass. Its matcher expects the global failure logger immediately before the enclosing task configuration closes; an adjacent scoped hook is overcaptured and reported as an inherited-event override. The canonical Gradle and event-emission proof did not cover this affected shell contract. Preserve the original global block, configure the approved scoped events separately, and run the existing contract before the next checkpoint; do not relax the global logging invariant or the contract. The separate filtered configuration passes the unchanged shell contract, all 24 classifier cases and canonical owner checks; fresh local integration logs preserve the intended boundaries and stream suppression. Actual replacement-source CI and genuine owner proof remain pending. 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 08933dfd96..a128d70cf8 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 @@ -6,7 +6,9 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Published source `65da9400d6d366cdc65841c46292bd822af0d1e5` is physically exercised in [Validation run 38141635503](https://github.com/benhook1013/FireMUD/actions/runs/38141635503). Actual checkout merge `d8c7477757c13e7b25e44817e1f1e4db90b6d123` has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source; its tree `0099f9afed468fe2a30b6ca9546dba361e2d84cf` equals the source tree. Current intended parent fe15 is qualified for the executed scopes; historical `1a8eefe6824c20b8b07a6d6adadda2ad154476e0` remains prior unqualified evidence. The approved normal merge carries the 33 parent paths without conflict and changes no base name or queue topology. +Diagnostic source `167e95c703bc98c36e3cb98cc985d6613a908067` adds the scoped existing progress hook. Its [original Validation run 38145482141](https://github.com/benhook1013/FireMUD/actions/runs/38145482141) immediately fails the existing lightweight-scope contract: the matcher spans the global failure logger through the adjacent scoped conditional and mistakes the integration event settings for a global inherited-event override. All 24 classifier subtests pass. The root-only follow-up preserves the original global failure-details block and applies the same approved integration settings in a separate filtered Test task configuration; the contract, task selection, budgets and gates remain unchanged. The unchanged lightweight-scope contract passes all 24 classifier cases and its full contract; canonical gate71 passes the three owner checks and fresh integration event-emission proof in 1m11s across 197 tasks. All affected worker/class/method boundaries and stream suppression are verified again; twelve non-container cases pass and 459 container cases skip, while the 2,199 unit results are reused from gate69. Links and all 548 Markdown files pass. This remains local observability proof, not physical owner handoff credit. The remaining matrix must finish and supply exact-source owner proof independently. Local logger proof and previous source65 physical results do not qualify this diagnostic source or its follow-up. + +Previous source `65da9400d6d366cdc65841c46292bd822af0d1e5` is physically exercised in [Validation run 38141635503](https://github.com/benhook1013/FireMUD/actions/runs/38141635503). Actual checkout merge `d8c7477757c13e7b25e44817e1f1e4db90b6d123` has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source; its tree `0099f9afed468fe2a30b6ca9546dba361e2d84cf` equals the source tree. Current intended parent fe15 is qualified for the executed scopes; historical `1a8eefe6824c20b8b07a6d6adadda2ad154476e0` remains prior unqualified evidence. The approved normal merge carries the 33 parent paths without conflict and changes no base name or queue topology. Game Session executes 2,031 units, 208 integrations and 39 cross-service cases, all passing with no errors or skips. All six repaired cases pass: one exact lease-bound runtime decision, four binding-inventory cases and the request-ID width test. The inspected source of that passing width case asserts 121/128-character insertion success and 129-character SQLSTATE `22001` rejection; XML records the named test's result rather than its individual SQL inputs. The synthetic launch builder now carries its runtime target's canonical version into the release attestation, alongside the earlier exact RUNNING preparing/active epochs. The inherited width fixture retains typed World hold/lifecycle bytes, matching request digest and exact V44 launch/catalog tuple. This closes the scoped fixture gaps with production guards, migrations, leases and positive/negative assertions preserved; stipulated upstream authority does not establish genuine handoffs. From e509053dc2b1efbee7b05f2342983b6ed5d1cecf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 03:39:26 +1300 Subject: [PATCH 125/129] Record bounded owner progress from diagnostic source CI --- design/project-management/ai-observations.md | 2 ++ .../game-authoring-publishing-and-activation.md | 8 +++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 0029ee6d82..05f57409f4 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -289,3 +289,5 @@ Entry format: - Current status: The scoped existing-hook addition passes canonical affected checks and freshly rerun integration tasks. Local logs show worker/class/method starts and completions for each affected owner with streams suppressed; twelve non-container cases pass and 459 container cases skip. Missing owner PostgreSQL integration and genuine handoff proof remains separate; subsequent exact-source execution must identify the actual boundary before any timing repair is inferred. - Follow-up (2026-10-12): Diagnostic source167e95 fails the existing lightweight-scope contract after all 24 classifier subtests pass. Its matcher expects the global failure logger immediately before the enclosing task configuration closes; an adjacent scoped hook is overcaptured and reported as an inherited-event override. The canonical Gradle and event-emission proof did not cover this affected shell contract. Preserve the original global block, configure the approved scoped events separately, and run the existing contract before the next checkpoint; do not relax the global logging invariant or the contract. The separate filtered configuration passes the unchanged shell contract, all 24 classifier cases and canonical owner checks; fresh local integration logs preserve the intended boundaries and stream suppression. Actual replacement-source CI and genuine owner proof remain pending. + + - Physical outcome (2026-10-12): Source167 original run38145482141 ends failure. Existing events preserve 31 Account DAF, four Account Game Logic intake, one authenticated publication producer/readers, three Game Design World source/application/recovery and one genuine Game Logic intake method PASSED despite missing integration XML after cancellation. Account’s terminal-owner method and Game Design’s selected-export method only STARTED, while Entity stops progressing after a class start with no method. Keep these bounded results separate from aggregate task success and test-only upstream inputs; the logs still establish no source-owned timing fix or complete genuine handoff. 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 a128d70cf8..05f1608756 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 @@ -6,7 +6,13 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Diagnostic source `167e95c703bc98c36e3cb98cc985d6613a908067` adds the scoped existing progress hook. Its [original Validation run 38145482141](https://github.com/benhook1013/FireMUD/actions/runs/38145482141) immediately fails the existing lightweight-scope contract: the matcher spans the global failure logger through the adjacent scoped conditional and mistakes the integration event settings for a global inherited-event override. All 24 classifier subtests pass. The root-only follow-up preserves the original global failure-details block and applies the same approved integration settings in a separate filtered Test task configuration; the contract, task selection, budgets and gates remain unchanged. The unchanged lightweight-scope contract passes all 24 classifier cases and its full contract; canonical gate71 passes the three owner checks and fresh integration event-emission proof in 1m11s across 197 tasks. All affected worker/class/method boundaries and stream suppression are verified again; twelve non-container cases pass and 459 container cases skip, while the 2,199 unit results are reused from gate69. Links and all 548 Markdown files pass. This remains local observability proof, not physical owner handoff credit. The remaining matrix must finish and supply exact-source owner proof independently. Local logger proof and previous source65 physical results do not qualify this diagnostic source or its follow-up. +Diagnostic source `167e95c703bc98c36e3cb98cc985d6613a908067` adds the scoped existing progress hook. Its [original Validation run 38145482141](https://github.com/benhook1013/FireMUD/actions/runs/38145482141) immediately fails the existing lightweight-scope contract: the matcher spans the global failure logger through the adjacent scoped conditional and mistakes the integration event settings for a global inherited-event override. All 24 classifier subtests pass. The root-only follow-up preserves the original global failure-details block and applies the same approved integration settings in a separate filtered Test task configuration; the contract, task selection, budgets and gates remain unchanged. The unchanged lightweight-scope contract passes all 24 classifier cases and its full contract; canonical gate71 passes the three owner checks and fresh integration event-emission proof in 1m11s across 197 tasks. All affected worker/class/method boundaries and stream suppression are verified again; twelve non-container cases pass and 459 container cases skip, while the 2,199 unit results are reused from gate69. Links and all 548 Markdown files pass. This remains local observability proof, not physical owner handoff credit. The original run ends failure with the confirmed contract failure, three canceled owner jobs and failed Validation Gate; the replacement needs independent exact-source qualification. Local logger proof and previous source65 physical results do not qualify this diagnostic source or its follow-up. + +Source167 actual tested merge `f5a02d83a7914e83e8d090d76d786105851ad9af` has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and source167; tree `5b77a51e1dcbca7f474646d47dedae8d65bd21fc` equals the source tree. Its XML proves Game Session 2,278 cases (2,031 unit, 208 integration, 39 cross-service), World 918 (688 unit, 230 integration) and Automation 1,305 (1,206 unit, 99 integration), all passing without errors or skips. All six repaired Game Session cases and World’s 69-case draft-graph suite pass; separate World owner XML duplicates the 230 integrations and is counted once. The named width test's exact SQL boundaries remain supported by the pinned source assertions, rather than separately recorded XML inputs. + +Current source167 Account, Game Design and Entity retain only 1,399, 585 and 215 passing unit cases, with no integration XML or required Account DAF artifact. Live logs nevertheless record 31 distinct DAF methods PASSED, four Account Game Logic intake methods PASSED and the authenticated publication producer/readers method PASSED at 14:33:00Z. Account’s later `twoAuthenticatedTerminalOwnersSettleActualAccountOrderAndReadBackAfterCommit()` only starts at 14:33:00Z before cancellation at 14:33:38Z. Game Design’s three genuine World source/application/recovery methods pass at 14:18:35Z, 14:18:49Z and 14:19:03Z, and its genuine Game Logic intake passes at 14:19:19Z. Their inspected source exercises actual producer/apply transports, persisted APPLIED outcomes, exact retry and authenticated terminal reconciliation, while explicitly test-only upstream creator/legal/signer inputs and stipulated preliminary peer reservations remain outside that transport proof. These are bounded method-level physical results, not clean aggregate integration tasks or complete four-handoff/Major/production proof. + +Game Design’s selected export method starts at 14:19:33Z without a recorded result before cancellation at 14:23:16Z; its large composed flow does not show whether export, MinIO or later launch/session checks were reached. Entity’s integration task starts at 14:07:33Z and `ContainerInstanceLocationIntegrationTest` at 14:07:36Z, with no method event before cancellation at 14:22:37Z and its twenty-minute job cap. The source/captures do not distinguish container startup from Spring context/migrations or another class setup step. Account’s last terminal-owner method has only about 38 seconds before cancellation; that interval establishes no assertion or hang cause. No source-owned timing fix is established for these cancellations. Preserve budgets/guards and avoid speculative fixture/runtime changes or new diagnostic machinery; genuine selected export/count, actual terminal-owner completion, protected Entity producer/readback and operational-region delivery remain open. Previous source `65da9400d6d366cdc65841c46292bd822af0d1e5` is physically exercised in [Validation run 38141635503](https://github.com/benhook1013/FireMUD/actions/runs/38141635503). Actual checkout merge `d8c7477757c13e7b25e44817e1f1e4db90b6d123` has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and the source; its tree `0099f9afed468fe2a30b6ca9546dba361e2d84cf` equals the source tree. Current intended parent fe15 is qualified for the executed scopes; historical `1a8eefe6824c20b8b07a6d6adadda2ad154476e0` remains prior unqualified evidence. The approved normal merge carries the 33 parent paths without conflict and changes no base name or queue topology. From d4930385b225da62c1f7900fdeda16b27a656984 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 07:28:30 +1300 Subject: [PATCH 126/129] Repair selected-publication owner profiles and reuse validated terminal evidence --- design/project-management/ai-observations.md | 47 ++++++ ...ame-authoring-publishing-and-activation.md | 28 ++++ ...untPublicationAuthorizationRepository.java | 4 +- ...ctedDraftPublicationSettlementService.java | 14 +- ...63__selected_inventory_closure_profile.sql | 81 ++++++++++ ...rraysMigrationPostgresIntegrationTest.java | 153 +++++++++++++++++- ...DraftPublicationSettlementServiceTest.java | 1 + ...StartSessionLaunchDescriptorGrpcCodec.java | 4 +- ...esignPublicationTerminalReadGrpcCodec.java | 22 +-- ...ublicationTerminalCompletionGrpcCodec.java | 22 +-- .../WorldPublicationTerminalReadEvidence.java | 16 +- ...WorldPublicationTerminalReadGrpcCodec.java | 17 +- ...ldPublicationTerminalReadEvidenceTest.java | 15 ++ ...tyEmptySelectedSourceIntakeRepository.java | 10 +- .../src/main/resources/application.yml | 3 + ...tityFoundationPostgresIntegrationTest.java | 21 ++- ...ntakeMigrationPostgresIntegrationTest.java | 39 +++-- ...takeRepositoryPostgresIntegrationTest.java | 60 +++++-- .../src/test/resources/application.yml | 4 + ..._release_original_account_owner_schema.sql | 23 +++ ...licationExportPostgresIntegrationTest.java | 150 ++++++++++++++--- ...nventoryProfileUpgradeIntegrationTest.java | 53 +++++- ...GameDesignPublicationTerminalVerifier.java | 19 ++- .../tenant/WorldPublicationTerminal.java | 2 +- .../WorldPublicationTerminalReadService.java | 8 +- 25 files changed, 689 insertions(+), 127 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V163__selected_inventory_closure_profile.sql create mode 100644 services/game-design-service/src/main/resources/db/migration/V74__restore_selected_release_original_account_owner_schema.sql diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 05f57409f4..3c25dae27c 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -291,3 +291,50 @@ Entry format: - Follow-up (2026-10-12): Diagnostic source167e95 fails the existing lightweight-scope contract after all 24 classifier subtests pass. Its matcher expects the global failure logger immediately before the enclosing task configuration closes; an adjacent scoped hook is overcaptured and reported as an inherited-event override. The canonical Gradle and event-emission proof did not cover this affected shell contract. Preserve the original global block, configure the approved scoped events separately, and run the existing contract before the next checkpoint; do not relax the global logging invariant or the contract. The separate filtered configuration passes the unchanged shell contract, all 24 classifier cases and canonical owner checks; fresh local integration logs preserve the intended boundaries and stream suppression. Actual replacement-source CI and genuine owner proof remain pending. - Physical outcome (2026-10-12): Source167 original run38145482141 ends failure. Existing events preserve 31 Account DAF, four Account Game Logic intake, one authenticated publication producer/readers, three Game Design World source/application/recovery and one genuine Game Logic intake method PASSED despite missing integration XML after cancellation. Account’s terminal-owner method and Game Design’s selected-export method only STARTED, while Entity stops progressing after a class start with no method. Keep these bounded results separate from aggregate task success and test-only upstream inputs; the logs still establish no source-owned timing fix or complete genuine handoff. + +- `2026-10-12`: Nontransactional index migrations also need compatible Flyway advisory locking + - Context: Restored local Docker allowed focused proof of the previously canceled Entity setup on source e509. An owned-worker thread dump located the wait in Flyway migration execution; the isolated PostgreSQL activity showed Entity V4's concurrent UUID index waiting on Flyway's own idle schema-history transaction. + - Observation: The existing `executeInTransaction=false` migration sidecar controls the SQL migration transaction, while Flyway separately defaults to transactional PostgreSQL advisory locking. That lock transaction can prevent `CREATE INDEX CONCURRENTLY` from completing. The selected-export fixture migrates the same Entity chain before any export. + - Expected pattern: Use [Flyway's documented session-level advisory lock setting](https://documentation.red-gate.com/flyway/reference/configuration/flyway-namespace/flyway-postgresql-namespace/flyway-postgresql-transactional-lock-setting) on the owning service startup and direct test migration paths that execute the concurrent index. Preserve applied migration bytes, concurrent indexing, constraints and serialization; do not widen timeouts or replace the index operation to hide the wait. + - Current status: The scoped Entity runtime/test configuration and direct fixture correction is prepared. The Spring test's own `application.yml` shadows the main resource, so the lock setting must also be present in that existing test configuration. Fresh PostgreSQL execution is required before claiming recovery; the canceled diagnostic runs did not reach selected export or establish a completed handoff. + - Outcome (2026-10-13): The canonical Entity full check passes in 54 seconds after fresh execution of all 17 PostgreSQL integration cases with no failures, errors or skips. The Spring startup and direct migrations complete with session-level locking, while immutable migration bytes remain unchanged. Receipt metadata compares TIMESTAMPTZ values by instant without changing canonical receipt bytes; UTC retention and Pacific/Auckland read/replay pass. This qualifies owner-local recovery, not genuine protected producer, placement or operational-region handoffs. + +- `2026-10-13`: Persisted test reports can predate a failed validation invocation + - Context: A focused Entity check failed during integration-source compilation, leaving earlier integration XML in the build directory. Reading that XML without checking task execution produced an incorrect fresh-result report. + - Observation: Existing XML is not evidence that the current invocation executed its tests; a compilation or other prerequisite failure can leave previous results intact. + - Expected pattern: Correlate the canonical invocation log, test-task execution markers and report timestamps before attributing XML to a source or run. Retain reused results as reused, and report prerequisite failures without manufacturing a fresh integration outcome. + - Outcome: The incorrect attribution was corrected. The next invocation actually executed all 17 Entity PostgreSQL integrations successfully; its later SpotBugs fixture finding remained a separate full-check failure. + +- `2026-10-13`: Recreating a migration-owned function can erase an earlier forward correction + - Context: Fresh selected-release composition passes owner retention and S3 export/retry, then PostgreSQL rejects its original Account fence. The fixture explicitly asserts the genuine producer returns canonical v2. V71 had admitted that version alongside retained v1; V72 recreates the whole release function with the earlier v1-only predicate. + - Observation: Successfully applying both migrations does not prove the later complete function definition preserves the earlier correction. Exact Java owner evidence still reaches the regressed database predicate. + - Expected pattern: Restore the established predicate with a forward migration, preserve applied checksums and retained bytes, and verify the current function's other guards and identity remain intact. Include the complete current chain in physical upgrade and composition proof rather than treating an earlier passing migration boundary as current evidence. + - Current status: The bounded V74 correction and existing upgrade proof are being prepared; no release guard or authority is relaxed beyond restoring V71's canonical v1/v2 support. Corrected fresh composition remains required. + +- `2026-10-13`: Nested terminal handoffs can repeatedly decode the same immutable evidence + - Context: Both selected-release scenarios persist the release, then hit the unchanged five-second World completion deadline. Three owned worker snapshots show World request canonical decoding, World awaiting the independent Game Design terminal read, and Game Design reparsing its already-validated terminal while encoding the response. + - Observation: The terminal parser already validates its embedded complete operation; comparing the separately supplied operation to that canonical embedded operation proves the same relation without parsing it again. An immutable validated owner terminal can also be checked against the response request directly; incoming untrusted wire bytes still require strict parsing. The snapshots establish CPU work at those stages, not a measured whole-call cause or absence of all database waits. + - Expected pattern: Remove only demonstrated duplicate decoding of validated immutable values, retaining exact byte and namespace comparisons, defensive copies, message bounds, independent owner reads and workload authentication. Keep existing deadlines and reject malformed or substituted wire evidence with the existing negative proof. + - Current status: The two scoped codec reductions are prepared and parent-inspected; focused unit, physical composition and canonical checks await Gameplay's explicitly reserved front validation slot release. No timeout recovery or completed World/Account handoff is claimed yet. + +- `2026-10-13`: Shared operation profiles must converge at every receiving owner + - Context: Genuine selected export retains a closure-qualified inventory-v2 operation. One scenario completes World publication and exact retry, then Account settlement reports sanitized `UNAVAILABLE`. A separate read-only call sends the same actual operation bytes to Account's installed SQL validator and obtains SQLSTATE `23514` for unknown public inventory members. + - Observation: Account's current V94/V127 function still requires the historical inventory-v1, 16-member source model. Game Design's V70 already pairs that profile with inventory-v2, its 17-member model and exact empty inbound closure. A successful producer or another owner's validator does not establish the receiving SQL boundary accepts the canonical current profile. The sanitized transport failure alone cannot establish that the SQL path was reached. + - Expected pattern: Trace the entire receiving migration chain, prove the actual owner function on the original bytes, and add a guarded forward correction preserving historical data, function identity, checksums and every unrelated relationship check. Coordinate migration versions with concurrent owners before editing. + - Current status: Gameplay confirms this gap is absent from its front fixes and authorizes forward Account V163 after this branch's V162. The paired-profile correction and focused retained-data proof are in preparation; complete selected composition and the separate second-scenario World deadline remain open. + +- `2026-10-13`: A refused fixture connection is separate from a later owner deadline + - Context: The combined owner gate passes Common Platform and Entity, then Game Design selected scenarios fail in Game Session PostgreSQL setup with a refused connection. The same focused selected composition later advances through release and World completion without a connection configuration change. + - Observation: Docker events show no recorded OOM event in the inspected interval; signal-9 container exits occur during the ordinary post-failure cleanup. Those cleanup exits do not prove the earlier refused connection's cause. The successful later setup does not establish why the earlier connection failed. + - Expected pattern: Preserve the original logs and event interval, keep the setup failure separate from later runtime assertions, and avoid guessing a network, host, PostgreSQL-major or timeout correction from one sanitized boundary. + - Current status: The setup cause remains unestablished. The next focused invocation reaches bounded World completion/retry and the separate Account profile defect; no fixture connection, deadline or database setting is changed to explain the earlier event. + +- `2026-10-13`: Procedural function patches require physical installation proof + - Context: Metadata generation accepts the targeted jOOQ-ignore block in the prepared Account forward migration. Fresh World owner fixtures fail when PostgreSQL executes the patched function definition, reporting SQLSTATE `42601`. + - Observation: The new unparenthesized CASE expression sits inside a PL/pgSQL IF condition; generation and Java compilation do not parse that function body. Its model-shape CASE already sits inside parentheses. The physical failure precedes the intended inventory and owner assertions. + - Expected pattern: Parenthesize the expression without changing its profile semantics, update the existing exact-function expectation, and run the smallest owning PostgreSQL installation proof before a broader receiving-owner gate. Keep metadata success separate from SQL execution and do not reuse stale XML after an interrupted run. + - Current status: The count expression and expected upgrade definition are corrected. Focused Account installation proof is in progress. The failed combined run freshly passes Common Platform's 730 units/full check and World's 688 units, but its World integration aggregate and later tasks remain unqualified. A separate observed Spring migration wait has no established cause; only the owned run was stopped through canonical cleanup. + + - Outcome (2026-10-13): Parenthesizing the count CASE installs successfully in the existing five-case PostgreSQL migration suite, preserving the exact intended function delta, OID, prior checksums and V127 ordering guards. The next receiving-owner gate also passes the actual closure-profile SQL input and all seven rejection cases in both selected scenarios. Their authenticated World completion and exact retry pass; Account's outer settlement deadline remains separate and unresolved. + + - Further outcome (2026-10-13): Scoped typed-value reuse and single strict response decoding pass fresh Common Platform and Account unit proof, the existing authenticated two-owner PostgreSQL settlement case, and the actual empty-core selected scenario's Account settlement, exact retry and committed readbacks. That scenario advances to a separate Game Design descriptor-read deadline; the player-created scenario still times out at Account settlement. These partial results do not establish a universal timeout cause or recovery, and no timed-out owner commit outcome is inferred. 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 05f1608756..ccbf2a2b9b 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 @@ -6,6 +6,34 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The existing draft [PR #3105](https://github.com/benhook1013/FireMUD/pull/3105) remains on the approved parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`. Restored local Docker exposes and repairs a concrete Entity setup self-wait: the concurrent V4 index waited on Flyway's own transactional advisory-lock connection. The service startup, shadowing Spring test configuration and direct migration fixtures now select session-level advisory locking. Applied migration bytes, concurrent indexing and constraints remain unchanged. Entity receipt metadata compares PostgreSQL TIMESTAMPTZ values by instant, preserving immutable canonical receipt bytes and all identity/digest guards. The pre-V3 quarantine fixture seeds its retained numeric row using the historical schema before exercising the current writer after migration. + +The canonical Entity `check -PfullCheck` passes locally in 54 seconds, freshly executing all 17 PostgreSQL integration cases with zero failures, errors or skips. That includes both Spring startup cases, the complete 23-family EMPTY retention/readback/retry and constraint/rollback/snapshot negatives, UTC retention followed by Pacific/Auckland read/replay, and retained-row quarantine. Its 215 passing units are reused from the preceding fresh unit execution. This is owner-local physical proof of the correction, not protected Account-to-Entity producer, placement or operational-region proof. Earlier failed compilation left stale integration XML; those reports are not fresh results of that failed invocation. + +The selected-export fixture counts logical S3 GET executions once while preserving conditional PUT transmission checks, durable candidate verification, the exact four-readback assertion and actual stored-byte readbacks. Each scenario uses its own empty MinIO bucket. Forward V74 restores V71's existing canonical Account-v1/v2 predicate after V72 recreated the function with v1-only acceptance; V71, V72 and existing V73 bytes remain unchanged. The fresh PostgreSQL upgrade case passes through V74, proving the exact predicate-only function delta, stable OID, unchanged checksums for every prior migration, retained historical operation bytes and the existing inventory negatives. + +The next combined local gate freshly passes Common Platform's 730 units and full check, Entity's 215 units and 17 PostgreSQL integrations with its full check, and Game Design's 585 units. The Game Design V74 upgrade case passes, while the two selected scenarios fail earlier in Game Session PostgreSQL setup with a refused connection. That invocation therefore does not physically qualify the prepared codec correction; its later Game Design static and documentation tasks remain unrun. + +A subsequent focused invocation passes the V74 upgrade again. Its empty-core selected scenario completes the actual World publication-completion call and exact new-correlation retry under the unchanged five-second deadline, with identical terminal bytes, then receives a sanitized Account selected-publication settlement `UNAVAILABLE`. The player-created scenario still reaches the World completion deadline. This is bounded World completion/retry proof for one scenario, not a passing whole composition or universal deadline repair. Three earlier owned worker snapshots locate canonical decoding in the World request and nested Game Design terminal read/response; they do not measure the whole call or exclude other waits. The prepared codec changes remove repeated decoding of validated immutable evidence while preserving strict incoming-wire parsing, exact equality, namespace, bounds, workload authentication and independent owner reads. The follow-up also reuses the immutable terminal in World’s typed request and its local held-authentication token; each held check still rejects a closed token and compares the exact original operation. World response decoding returns its single strictly validated result instead of reparsing those same wire bytes. The expanded World completion correction is physically exercised in both selected scenarios below; the whole composition remains incomplete. + +The actual original selected-publication bytes independently fail Account's real `require_selected_inventory_operation_v2` SQL validator with SQLSTATE `23514`, reporting incomplete or unknown public inventory members. The current Account chain still admits only the historical inventory-v1/16-member model, while the canonical closure-qualified operation has inventory-v2/17-member model, graph schema 3 and digest schema 4. Game Design already enforces the paired historical/current profiles. Gameplay confirms that its fronts do not repair this gap and authorizes a new forward Account V163 after this branch's V162. The narrow V163 correction and focused V162-to-V163 installation proof are prepared. The corrected migration now passes the five-case owning PostgreSQL suite, including the physical V162-to-V163 installation; its initial syntax failure and corrected result are distinguished below. That proof checks the exact function-definition delta, stable OID, all prior migration checksums and retained V127 ordering/width guards; it does not itself create historical owner rows. Existing Account publication cases supply the historical profile and settlement relationships, while the actual selected operation supplies the closure-qualified SQL boundary. Applied migration bytes, retained operation bytes, exact empty-closure restrictions and all other relationship guards remain required. The direct SQL failure establishes the Account profile defect; the earlier sanitized settlement response alone does not prove it reached that SQL boundary. The aggregate selected composition remains failed and Account's complete selected-publication settlement remains unqualified on this prepared source. + +The expanded correction's next physical gate freshly passes Common Platform's 730 units and full check, and World's 688 units. Two World fixture methods then fail while installing new Account V163 with PostgreSQL syntax error `42601`; Game Design and the selected Account tasks do not run. Account metadata generation had completed but deliberately ignored the procedural block, so it supplied no SQL execution proof. The corrected count predicate now parenthesizes its CASE expression inside the PL/pgSQL IF condition, without changing the paired-profile semantics. Focused PostgreSQL installation passes all five owning cases in 49 seconds, with no failures, errors or skips; metadata generation also passes. This qualifies the corrected installation and function delta, not complete owner composition. The remaining World worker was observed waiting in Spring Flyway migration startup, with no owning test-method frame or established wait cause. The owned failed run ended through canonical SIGTERM cleanup; its old integration XML is stale and cannot qualify the 230-case World suite. World aggregate integration/static checks and later documentation checks remain incomplete. + +The subsequent focused receiving-owner gate freshly passes Account's 1,399 units and 13 PostgreSQL cases (five migration and eight original-publication cases), plus Game Design's 585 units and current release upgrade. Both actual selected scenarios pass Account's current-profile SQL validation and seven SQLSTATE `23514` negatives with unchanged original Account and World bytes. Both complete authenticated World publication completion and exact new-correlation retry under the unchanged five-second deadline, with identical terminal bytes. They then time out at the outer Account selected-publication settlement call. This establishes the receiving SQL and both World completion/retry boundaries in those fixtures, not complete Account settlement; a timeout does not establish whether the owner committed. No Account handler snapshot was captured, so its exact CPU, nested-read or SQL wait phase remains unknown. Source inspection identifies repeated decoding of already validated immutable operation/terminal values. The prepared Account service reuses the strict Game Design client’s immutable terminal, and the repository reuses its immutable typed operation and terminal while still strictly parsing the raw World payload. Game Design response decoding now relies on the existing carrier’s single strict parse and exact-canonical/request checks. These reductions await fresh execution; strict incoming-wire/storage parsing, independent owner reads, exact comparisons, source protection, transaction boundaries and deadlines remain intact. They do not establish the timeout’s exact phase or cause. The failed gate does not reach the focused World fixture, remaining static checks or documentation tasks. + +The next variant freshly passes Common Platform's 730 units and full check, Account's 1,399 units and 14 focused PostgreSQL/mTLS cases, and Game Design's 585 units plus current release upgrade. Both selected scenarios again pass the current-profile SQL and World completion/retry phases. The empty-core case now also passes the actual authenticated Account settlement, different-correlation retry, one retained immutable receipt and independent committed readback assertions before advancing through the Account StartSession projection and initial Game Design template-association read. It then times out at Game Design's authenticated StartSession descriptor read. The player-created case still times out at Account settlement. This is bounded Account settlement/recovery proof for the empty-core fixture, not universal deadline repair or a passing whole case. The two remaining deadline phases have no captured owner stack or established CPU/SQL cause. The gate ends failed after 15m25s and does not execute its later World fixture, static or documentation tasks. Its local slot is released to Gameplay's active front proof; further heavy validation waits for that actual release while scoped source diagnosis continues. + +The next prepared reduction removes repeated original-operation decoding from the World terminal-read request and receiver, derives the outgoing World phase from its validated immutable terminal, and derives Account's expected World phase from its validated Game Design terminal. The World request retains its defensive record API, exact terminal/operation and namespace checks, and an explicit four-MiB original-operation bound; a focused rejection test covers an oversized operation before terminal parsing. The descriptor encoder validates the exact association and descriptor bindings and recursive unknown-field rejection without decoding its own freshly constructed response. Its actual receiving decoder remains unchanged. The next boundary gate freshly passes Common Platform's 731 units/full check and World's 688 units plus the focused PostgreSQL/mTLS independent-owner read. Account's 1,399 units execute with three failures because the stipulated typed-terminal fixture omitted its World-evidence accessor. That fixture now supplies the same existing World evidence, preserving every negative and transaction assertion. The corrected gate freshly passes Account's 1,399 units and 16 focused PostgreSQL/mTLS cases, Game Design's 585 units, the affected owner static checks and link validation. Its Common and World test outputs reuse the preceding run. Markdown validation alone fails on five extra blank lines in the new observations; those lines are corrected before the next documentation and selected-composition gate. The complete World integration aggregate remains unqualified. The following selected-composition gate passes corrected links and all 548 Markdown files, plus the physical release upgrade, then fails both scenarios after 6m23s at the same remaining boundaries: empty-core descriptor resolution and player-created Account settlement. Both scenarios again exercise the current-profile SQL negatives and exact World completion/retry; empty-core again exercises Account settlement/recovery before descriptor resolution. Three bounded owned-worker snapshots capture earlier selected-intake SQL or local inventory parsing, not either timed-out handler. They establish no deadline cause or timed-out commit outcome. The latest reductions are qualified within the focused owner boundaries, not as universal timeout repairs; the coherent source checkpoint retains the failed aggregate and genuine authority holds. These are partial latest-source results, with no remaining deadline cause inferred. Gameplay's actual terminal release and Overseer resumption authorize the prepared local gate; no new branch parent or genuine authority handoff is adopted. + +All four genuine handoffs, five checklist outcomes and incoming Major remain open; actual protected producer/carrier, authenticated terminal and operational-region handoffs remain Gameplay-owned dependencies. A complete selected scenario also deliberately uses admission abort recovery with its launch remaining `STARTING`; it cannot establish successful Entity placement or region delivery. Production Game Design reads remain default-denied except the approved isolated run-owned actual-owner fixture entrypoint. Broader Unit 1B stays paused. + +Published source `e509053dc2b1efbee7b05f2342983b6ed5d1cecf` has separate [original CI evidence](https://github.com/benhook1013/FireMUD/actions/runs/38148097880): its actual tested merge `f2336acd4392a68cd48590602938d956bb1f8882` has ordered parents `[fe15a31f274b1c9850dd388e83faf540916ee8a3,e509053dc2b1efbee7b05f2342983b6ed5d1cecf]`, and its tree equals the published source. Account freshly executes 1,399 units and all 309 PostgreSQL integrations without failures, errors or skips, including the authenticated two-owner terminal settlement/readback; the separate owner artifact duplicates those integrations. Game Design and Entity cancel at unchanged limits before integration XML; bounded Game Design World-source and Game Logic methods pass in the live log. Game Session, World and Automation test tasks restore cached outputs, which are not fresh physical execution in that attempt. The canceled matrix and failed required gate leave the aggregate source CI incomplete; this historical CI does not validate the new local correction. + +## Prior Source Checkpoints + +These entries retain earlier source-pinned reports. XML totals alone do not establish fresh execution when the corresponding test-task cache provenance is unavailable; a named live `PASSED` event qualifies only its inspected method. Interpret those historical execution descriptions within this limit, separately from the verified fresh and reused results above. + Diagnostic source `167e95c703bc98c36e3cb98cc985d6613a908067` adds the scoped existing progress hook. Its [original Validation run 38145482141](https://github.com/benhook1013/FireMUD/actions/runs/38145482141) immediately fails the existing lightweight-scope contract: the matcher spans the global failure logger through the adjacent scoped conditional and mistakes the integration event settings for a global inherited-event override. All 24 classifier subtests pass. The root-only follow-up preserves the original global failure-details block and applies the same approved integration settings in a separate filtered Test task configuration; the contract, task selection, budgets and gates remain unchanged. The unchanged lightweight-scope contract passes all 24 classifier cases and its full contract; canonical gate71 passes the three owner checks and fresh integration event-emission proof in 1m11s across 197 tasks. All affected worker/class/method boundaries and stream suppression are verified again; twelve non-container cases pass and 459 container cases skip, while the 2,199 unit results are reused from gate69. Links and all 548 Markdown files pass. This remains local observability proof, not physical owner handoff credit. The original run ends failure with the confirmed contract failure, three canceled owner jobs and failed Validation Gate; the replacement needs independent exact-source qualification. Local logger proof and previous source65 physical results do not qualify this diagnostic source or its follow-up. Source167 actual tested merge `f5a02d83a7914e83e8d090d76d786105851ad9af` has ordered parents `fe15a31f274b1c9850dd388e83faf540916ee8a3` and source167; tree `5b77a51e1dcbca7f474646d47dedae8d65bd21fc` equals the source tree. Its XML proves Game Session 2,278 cases (2,031 unit, 208 integration, 39 cross-service), World 918 (688 unit, 230 integration) and Automation 1,305 (1,206 unit, 99 integration), all passing without errors or skips. All six repaired Game Session cases and World’s 69-case draft-graph suite pass; separate World owner XML duplicates the 230 integrations and is counted once. The named width test's exact SQL boundaries remain supported by the pinned source assertions, rather than separately recorded XML inputs. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java index 148de988bc..ec61455a67 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java @@ -195,8 +195,8 @@ public byte[] settle( String worldOutcome, byte[] worldTerminalEvidence) { requireTransaction(); - operation = GameDesignPublicationOperationBinding.fromStored(operation.canonicalBytes()); - gameDesign = GameDesignPublicationTerminalEvidence.fromStored(gameDesign.canonicalBytes()); + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(gameDesign, "gameDesign"); var world = GameDesignPublicationTerminalEvidence.fromStored(worldTerminalEvidence); String expectedPhase = gameDesign.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java index 53bb5ffb78..93f8d571ce 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java @@ -60,14 +60,10 @@ public byte[] settle(byte[] originalOperation) { var gameDesignRequest = GameDesignPublicationTerminalReadEvidence.Request.create(workloadNamespace, operation); var gameDesign = gameDesignClient.read(gameDesignRequest); - if (gameDesign == null - || !gameDesignRequest.equals(gameDesign.request()) - || gameDesign.terminalEvidence() == null) { + var terminal = gameDesign == null ? null : gameDesign.terminalEvidence(); + if (gameDesign == null || !gameDesignRequest.equals(gameDesign.request()) || terminal == null) { throw new IllegalStateException("Game Design terminal differs from exact owner read request"); } - var terminal = - GameDesignPublicationTerminalEvidence.fromStored( - gameDesign.terminalEvidence().canonicalBytes()); if (!Arrays.equals(operation.canonicalBytes(), terminal.operationBytes())) { throw new IllegalStateException("Game Design terminal substitutes original operation"); } @@ -76,9 +72,13 @@ public byte[] settle(byte[] originalOperation) { WorldPublicationTerminalReadEvidence.Request.create( workloadNamespace, operation.canonicalBytes(), terminal.canonicalBytes()); var world = worldClient.read(worldRequest); + var expectedWorldOutcome = + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED + : WorldPublicationTerminalReadEvidence.WorldOutcome.ABORTED; if (world == null || !worldRequest.equals(world.request()) - || world.worldOutcome() != worldRequest.expectedWorldOutcome() + || world.worldOutcome() != expectedWorldOutcome || world.terminalEvidence() == null || !Arrays.equals(operation.canonicalBytes(), world.terminalEvidence().operationBytes()) || !Arrays.equals(terminal.canonicalBytes(), world.terminalEvidence().canonicalBytes()) diff --git a/services/account-service/src/main/resources/db/migration/V163__selected_inventory_closure_profile.sql b/services/account-service/src/main/resources/db/migration/V163__selected_inventory_closure_profile.sql new file mode 100644 index 0000000000..49af3fb8ac --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V163__selected_inventory_closure_profile.sql @@ -0,0 +1,81 @@ +-- Preserve the original Account inventory/v1 profile and admit only the exact +-- closure-qualified inventory/v2 profile. Retained operation bytes stay immutable. +-- [jooq ignore start] +DO $migration$ +DECLARE + inventory_function REGPROCEDURE := + '"${serviceSchema}".require_selected_inventory_operation_v2(bytea)'::REGPROCEDURE; + original_definition TEXT; + model_shape_anchor TEXT := $anchor$ (model, ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'])$anchor$; + model_shape_replacement TEXT := $replacement$ (model, CASE + WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + THEN ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs','inboundSourceClosure'] + ELSE ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'] + END)$replacement$; + inventory_profile_anchor TEXT := $anchor$ OR inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$anchor$; + inventory_profile_replacement TEXT := $replacement$ OR NOT ((inventory->>'schema' = 'world-selected-publication-artifact-inventory/v1' + AND inventory->'schemaVersion' = '1'::JSONB) + OR (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB)) + OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$replacement$; + model_count_anchor TEXT := $anchor$ OR (SELECT count(*) FROM jsonb_object_keys(model)) <> 16$anchor$; + model_count_replacement TEXT := $replacement$ OR (SELECT count(*) FROM jsonb_object_keys(model)) <> (CASE + WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB THEN 17 + ELSE 16 + END)$replacement$; + profile_anchor TEXT := $anchor$ OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB$anchor$; + profile_replacement TEXT := $replacement$ OR ((inventory->>'schema' = 'world-selected-publication-artifact-inventory/v1' + AND inventory->'schemaVersion' = '1'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + AND model->'graphSchemaVersion' = '2'::JSONB + AND checkpoint->'digestSchemaVersion' = '3'::JSONB + AND selector->'request'->'digestSchemaVersion' = '3'::JSONB + AND NOT (model ? 'inboundSourceClosure')) + OR (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1' + AND model->'graphSchemaVersion' = '3'::JSONB + AND checkpoint->'digestSchemaVersion' = '4'::JSONB + AND selector->'request'->'digestSchemaVersion' = '4'::JSONB + AND model ?& ARRAY['modelId', 'graphSchemaVersion', 'graphDigest', + 'topologyResultDigest', 'familyCounts', 'regionGeneratorInputs', + 'generationRuleFields', 'regionFields', 'zoneFields', 'roomFields', + 'roomExitFields', 'spawnBindingFields', 'spawnBindingInputs', + 'generationRuleInputCount', 'spawnBindingCount', 'appliedEpochs', + 'inboundSourceClosure'] + AND model->'inboundSourceClosure' IS NOT DISTINCT FROM + '{"schemaVersion":1,"familyCounts":[{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING","count":0}]}'::JSONB)) IS NOT TRUE$replacement$; +BEGIN + SELECT pg_get_functiondef(inventory_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, model_shape_anchor, ''))) + / length(model_shape_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, inventory_profile_anchor, ''))) + / length(inventory_profile_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, model_count_anchor, ''))) + / length(model_count_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, profile_anchor, ''))) + / length(profile_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V162 Account selected inventory profile guards'; + END IF; + original_definition := replace(original_definition, model_shape_anchor, model_shape_replacement); + original_definition := replace(original_definition, inventory_profile_anchor, inventory_profile_replacement); + original_definition := replace(original_definition, model_count_anchor, model_count_replacement); + original_definition := replace(original_definition, profile_anchor, profile_replacement); + IF (length(original_definition) - length(replace(original_definition, model_shape_replacement, ''))) + / length(model_shape_replacement) <> 1 + OR (length(original_definition) - length(replace(original_definition, inventory_profile_replacement, ''))) + / length(inventory_profile_replacement) <> 1 + OR (length(original_definition) - length(replace(original_definition, model_count_replacement, ''))) + / length(model_count_replacement) <> 1 + OR (length(original_definition) - length(replace(original_definition, profile_replacement, ''))) + / length(profile_replacement) <> 1 THEN + RAISE EXCEPTION 'Expected exact V163 Account selected inventory profile guards'; + END IF; + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSelectedInventoryEmptyArraysMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSelectedInventoryEmptyArraysMigrationPostgresIntegrationTest.java index eb39b3b184..ab0daa1c56 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSelectedInventoryEmptyArraysMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSelectedInventoryEmptyArraysMigrationPostgresIntegrationTest.java @@ -16,7 +16,7 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -/** Physical V127 installation proof for both known V126 inventory guard shapes. */ +/** Physical Account selected-inventory migration and retained-ordering guard proof. */ @Testcontainers(disabledWithoutDocker = true) class AccountSelectedInventoryEmptyArraysMigrationPostgresIntegrationTest { private static final String HISTORY_TABLE = ".flyway_schema_history"; @@ -95,6 +95,28 @@ void rejectsADuplicatedOrderingGuardAndRollsBackV127() { }); } + @Test + void upgradesV162ToPairedClosureProfileWithoutChangingOtherGuardsOrHistory() { + withVersion162( + context -> { + String before = functionDefinition(context); + Long originalOid = functionOid(context); + Map originalChecksums = migrationChecksums(context); + assertCanonicalOrderingGuards(before); + + migrateTo163(context); + + String after = functionDefinition(context); + assertVersionApplied(context, "163"); + assertThat(after).isEqualTo(expectedV163Definition(before)); + assertThat(functionOid(context)).isEqualTo(originalOid); + assertThat(migrationChecksums(context)).containsAllEntriesOf(originalChecksums); + assertThat(migrationChecksums(context)).containsKeys("162", "163"); + assertCanonicalOrderingGuards(after); + assertThat(sourceKeyLength(context)).isEqualTo(2048); + }); + } + private static void withVersion126(Consumer proof) { String schema = "selected_inventory_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = @@ -112,6 +134,23 @@ private static void withVersion126(Consumer proof) { } } + private static void withVersion162(Consumer proof) { + String schema = "selected_inventory_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + JdbcTemplate jdbc = new JdbcTemplate(dataSource); + try { + migration(dataSource, schema, "162").migrate(); + TestContext context = new TestContext(schema, jdbc, dataSource); + assertVersionApplied(context, "162"); + assertVersionNotApplied(context, "163"); + proof.accept(context); + } finally { + jdbc.execute("DROP SCHEMA IF EXISTS " + quotedSchema(schema) + " CASCADE"); + } + } + private static Flyway migration( DriverManagerDataSource dataSource, String schema, String targetVersion) { return Flyway.configure() @@ -128,6 +167,10 @@ private static void migrateTo127(TestContext context) { migration(context.dataSource(), context.schema(), "127").migrate(); } + private static void migrateTo163(TestContext context) { + migration(context.dataSource(), context.schema(), "163").migrate(); + } + private static void assertV127RejectedWithoutChangingV126(TestContext context) { assertThatThrownBy(() -> migrateTo127(context)) .hasStackTraceContaining( @@ -145,6 +188,114 @@ private static String functionDefinition(TestContext context) { .queryForObject("SELECT pg_get_functiondef(?::regprocedure)", String.class, signature)); } + private static Long functionOid(TestContext context) { + String signature = + quotedSchema(context.schema()) + ".require_selected_inventory_operation_v2(bytea)"; + return Objects.requireNonNull( + context + .jdbc() + .queryForObject("SELECT ?::regprocedure::oid::bigint", Long.class, signature)); + } + + private static Map migrationChecksums(TestContext context) { + var checksums = new java.util.HashMap(); + context + .jdbc() + .query( + "SELECT version, checksum FROM " + + quotedSchema(context.schema()) + + HISTORY_TABLE + + " WHERE version IS NOT NULL AND success", + row -> { + checksums.put(row.getString("version"), row.getInt("checksum")); + }); + return Map.copyOf(checksums); + } + + private static String expectedV163Definition(String before) { + String expected = replaceExactlyOnce(before, modelShapeAnchor(), modelShapeReplacement()); + expected = + replaceExactlyOnce(expected, inventoryProfileAnchor(), inventoryProfileReplacement()); + expected = replaceExactlyOnce(expected, modelCountAnchor(), modelCountReplacement()); + return replaceExactlyOnce(expected, profileAnchor(), profileReplacement()); + } + + private static String modelShapeAnchor() { + return " (model, ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest'," + + "'familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields'," + + "'roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount'," + + "'spawnBindingCount','appliedEpochs'])"; + } + + private static String modelShapeReplacement() { + return " (model, CASE\n" + + " WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2'\n" + + " AND inventory->'schemaVersion' = '2'::JSONB\n" + + " THEN ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest'," + + "'familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields'," + + "'roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount'," + + "'spawnBindingCount','appliedEpochs','inboundSourceClosure']\n" + + " ELSE ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest'," + + "'familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields'," + + "'roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount'," + + "'spawnBindingCount','appliedEpochs']\n" + + " END)"; + } + + private static String inventoryProfileAnchor() { + return " OR inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1'\n" + + " OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'"; + } + + private static String inventoryProfileReplacement() { + return " OR NOT ((inventory->>'schema' = 'world-selected-publication-artifact-inventory/v1'\n" + + " AND inventory->'schemaVersion' = '1'::JSONB)\n" + + " OR (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2'\n" + + " AND inventory->'schemaVersion' = '2'::JSONB))\n" + + " OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'"; + } + + private static String modelCountAnchor() { + return " OR (SELECT count(*) FROM jsonb_object_keys(model)) <> 16"; + } + + private static String modelCountReplacement() { + return " OR (SELECT count(*) FROM jsonb_object_keys(model)) <> (CASE\n" + + " WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2'\n" + + " AND inventory->'schemaVersion' = '2'::JSONB THEN 17\n" + + " ELSE 16\n" + + " END)"; + } + + private static String profileAnchor() { + return " OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1'\n" + + " OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB"; + } + + private static String profileReplacement() { + return " OR ((inventory->>'schema' = 'world-selected-publication-artifact-inventory/v1'\n" + + " AND inventory->'schemaVersion' = '1'::JSONB\n" + + " AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1'\n" + + " AND model->'graphSchemaVersion' = '2'::JSONB\n" + + " AND checkpoint->'digestSchemaVersion' = '3'::JSONB\n" + + " AND selector->'request'->'digestSchemaVersion' = '3'::JSONB\n" + + " AND NOT (model ? 'inboundSourceClosure'))\n" + + " OR (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2'\n" + + " AND inventory->'schemaVersion' = '2'::JSONB\n" + + " AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1'\n" + + " AND model->'graphSchemaVersion' = '3'::JSONB\n" + + " AND checkpoint->'digestSchemaVersion' = '4'::JSONB\n" + + " AND selector->'request'->'digestSchemaVersion' = '4'::JSONB\n" + + " AND model ?& ARRAY['modelId', 'graphSchemaVersion', 'graphDigest',\n" + + " 'topologyResultDigest', 'familyCounts', 'regionGeneratorInputs',\n" + + " 'generationRuleFields', 'regionFields', 'zoneFields', 'roomFields',\n" + + " 'roomExitFields', 'spawnBindingFields', 'spawnBindingInputs',\n" + + " 'generationRuleInputCount', 'spawnBindingCount', 'appliedEpochs',\n" + + " 'inboundSourceClosure']\n" + + " AND model->'inboundSourceClosure' IS NOT DISTINCT FROM\n" + + " '{\"schemaVersion\":1,\"familyCounts\":[{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT\",\"count\":0},{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT\",\"count\":0},{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION\",\"count\":0},{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING\",\"count\":0},{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK\",\"count\":0},{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE\",\"count\":0},{\"family\":\"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING\",\"count\":0}]}'::JSONB)) IS NOT TRUE"; + } + private static void executeFunctionDefinition(TestContext context, String definition) { context.jdbc().execute(definition); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java index 0d17f37a4f..4351974231 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java @@ -327,6 +327,7 @@ private static final class CodecOutputs implements AutoCloseable { when(worldRequest.targetNamespace()).thenReturn("test"); when(terminal.canonicalBytes()).thenReturn(terminalBytes); when(terminal.operationBytes()).thenReturn(operationBytes); + when(terminal.worldEvidence()).thenReturn(world); when(terminal.outcome()).thenReturn(outcome); operations .when(() -> GameDesignPublicationOperationBinding.fromStored(operationBytes)) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java index 0445572e45..c18ce1d5c3 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodec.java @@ -90,7 +90,7 @@ public static ResolveStartSessionLaunchDescriptorResponse toFailureResponse( return toResponse(expectedRequest, associationRead, new ApplicationFailure(code, message)); } - /** Encodes one complete result and runs the same closed decoder used by receiving callers. */ + /** Encodes one complete result after validating its typed bindings and closed wire fields. */ public static ResolveStartSessionLaunchDescriptorResponse toResponse( Request expectedRequest, Result associationRead, Outcome outcome) { requireAssociationBinding(expectedRequest, associationRead); @@ -114,7 +114,7 @@ public static ResolveStartSessionLaunchDescriptorResponse toResponse( throw new IllegalArgumentException("Unsupported StartSession descriptor outcome"); } ResolveStartSessionLaunchDescriptorResponse response = builder.build(); - fromResponse(expectedRequest, response); + requireNoUnknownFields(response, "ResolveStartSessionLaunchDescriptorResponse"); return response; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodec.java index 20eb3fb2d2..f667988c68 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodec.java @@ -40,13 +40,16 @@ public static ReadPublicationTerminalResponse toResponse( GameDesignPublicationTerminalEvidence terminal) { Objects.requireNonNull(request, "request"); Objects.requireNonNull(terminal, "terminal"); - requireExactTerminal(request, terminal.canonicalBytes()); + byte[] terminalBytes = terminal.canonicalBytes(); + if (!Arrays.equals(request.originalOperation(), terminal.operationBytes())) { + throw new IllegalArgumentException("Terminal evidence differs from the original operation"); + } return ReadPublicationTerminalResponse.newBuilder() .setSchemaVersion(request.schemaVersion()) .setTargetNamespace(request.targetNamespace()) .setReadRequestId(request.readRequestId().toString()) .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) - .setTerminalEvidence(ByteString.copyFrom(terminal.canonicalBytes())) + .setTerminalEvidence(ByteString.copyFrom(terminalBytes)) .build(); } @@ -64,23 +67,14 @@ static GameDesignPublicationTerminalReadEvidence fromResponse( throw new IllegalArgumentException("Game Design changed the exact publication terminal read"); } byte[] originalTerminal = response.getTerminalEvidence().toByteArray(); - requireExactTerminal(request, originalTerminal); - return new GameDesignPublicationTerminalReadEvidence(request, originalTerminal); - } - - private static void requireExactTerminal( - GameDesignPublicationTerminalReadEvidence.Request request, byte[] bytes) { - final GameDesignPublicationTerminalEvidence terminal; try { - terminal = GameDesignPublicationTerminalEvidence.fromStored(bytes); + // The carrier performs strict canonical decoding and exact operation comparison once. + return new GameDesignPublicationTerminalReadEvidence(request, originalTerminal); } catch (RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException invalid) throw invalid; throw new IllegalArgumentException( "Complete canonical original terminal evidence required", malformed); } - if (!Arrays.equals(request.originalOperation(), terminal.operationBytes()) - || !Arrays.equals(bytes, terminal.canonicalBytes())) { - throw new IllegalArgumentException("Terminal evidence differs from the original operation"); - } } private static void noUnknownFields(Message message) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java index 91a5cecbc6..8e799ce14c 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java @@ -59,7 +59,11 @@ public static CompleteVersionPublicationResponse toResponse( Objects.requireNonNull(request, "request"); Objects.requireNonNull(terminal, "terminal"); byte[] terminalBytes = terminal.canonicalBytes(); - requireExactTerminal(request, terminalBytes); + if (!Arrays.equals(request.originalOperation(), terminal.operationBytes()) + || !Arrays.equals(request.gameDesignTerminalEvidence(), terminalBytes)) { + throw new IllegalArgumentException( + "World publication terminal differs from the exact requested operation or evidence"); + } // The full terminal appears once in the request echo and once as the stored result. if ((long) request.originalOperation().length + 2L * terminalBytes.length > MAX_MESSAGE_BYTES - MESSAGE_ENVELOPE_OVERHEAD_RESERVE) { @@ -98,11 +102,11 @@ public static GameDesignPublicationTerminalEvidence fromResponse( throw new IllegalArgumentException("World changed the exact publication completion request"); } byte[] terminalBytes = response.getStoredTerminalEvidence().toByteArray(); - requireExactTerminal(request, terminalBytes); - return GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); + return requireExactTerminal(request, terminalBytes); } - private static void requireExactTerminal(Request request, byte[] terminalBytes) { + private static GameDesignPublicationTerminalEvidence requireExactTerminal( + Request request, byte[] terminalBytes) { final GameDesignPublicationTerminalEvidence terminal; try { terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalBytes); @@ -115,6 +119,7 @@ private static void requireExactTerminal(Request request, byte[] terminalBytes) throw new IllegalArgumentException( "World publication terminal differs from the exact requested operation or evidence"); } + return terminal; } private static void requireWireBudget(Message message) { @@ -177,22 +182,19 @@ public record Request( } originalOperation = originalOperation.clone(); gameDesignTerminalEvidence = gameDesignTerminalEvidence.clone(); - GameDesignPublicationOperationBinding operation; GameDesignPublicationTerminalEvidence terminal; try { - operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); terminal = GameDesignPublicationTerminalEvidence.fromStored(gameDesignTerminalEvidence); } catch (RuntimeException malformed) { throw new IllegalArgumentException( "Complete canonical publication operation and terminal required", malformed); } - if (!Arrays.equals(originalOperation, operation.canonicalBytes()) - || !Arrays.equals(gameDesignTerminalEvidence, terminal.canonicalBytes()) - || !Arrays.equals(originalOperation, terminal.operationBytes())) { + if (!Arrays.equals(originalOperation, terminal.operationBytes()) + || !Arrays.equals(gameDesignTerminalEvidence, terminal.canonicalBytes())) { throw new IllegalArgumentException( "Game Design terminal differs from the complete original operation"); } - if (!targetNamespace.equals(operation.world().request().targetNamespace())) { + if (!targetNamespace.equals(terminal.worldEvidence().request().targetNamespace())) { throw new IllegalArgumentException( "Original publication operation differs from the World workload namespace"); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidence.java index 1b588e7027..359f44c85d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidence.java @@ -85,8 +85,11 @@ public record Request( if (readRequestId == null || readRequestId.equals(new UUID(0L, 0L))) { throw new IllegalArgumentException("Non-nil canonical read request identity required"); } - if (originalOperation == null || originalOperation.length == 0) { - throw new IllegalArgumentException("Complete original publication operation required"); + if (originalOperation == null + || originalOperation.length == 0 + || originalOperation.length > GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES) { + throw new IllegalArgumentException( + "Complete bounded original publication operation required"); } if (expectedGameDesignTerminalEvidence == null || expectedGameDesignTerminalEvidence.length == 0) { @@ -94,23 +97,20 @@ public record Request( } originalOperation = originalOperation.clone(); expectedGameDesignTerminalEvidence = expectedGameDesignTerminalEvidence.clone(); - GameDesignPublicationOperationBinding operation; GameDesignPublicationTerminalEvidence terminal; try { - operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); terminal = GameDesignPublicationTerminalEvidence.fromStored(expectedGameDesignTerminalEvidence); } catch (RuntimeException malformed) { throw new IllegalArgumentException( "Canonical complete publication operation and terminal evidence required", malformed); } - if (!Arrays.equals(originalOperation, operation.canonicalBytes()) - || !Arrays.equals(expectedGameDesignTerminalEvidence, terminal.canonicalBytes()) - || !Arrays.equals(originalOperation, terminal.operationBytes())) { + if (!Arrays.equals(originalOperation, terminal.operationBytes()) + || !Arrays.equals(expectedGameDesignTerminalEvidence, terminal.canonicalBytes())) { throw new IllegalArgumentException( "Expected terminal evidence differs from the exact original operation"); } - if (!targetNamespace.equals(operation.world().request().targetNamespace())) { + if (!targetNamespace.equals(terminal.worldEvidence().request().targetNamespace())) { throw new IllegalArgumentException( "Original publication operation differs from the World workload namespace"); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodec.java index 4b57f0268b..87725b04a5 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadGrpcCodec.java @@ -52,9 +52,16 @@ public static ReadPublicationTerminalResponse toResponse( GameDesignPublicationTerminalEvidence terminal) { Objects.requireNonNull(request, "request"); Objects.requireNonNull(terminal, "terminal"); - var evidence = - WorldPublicationTerminalReadEvidence.fromOwnerRead( - request, request.expectedWorldOutcome(), terminal.canonicalBytes()); + byte[] terminalBytes = terminal.canonicalBytes(); + if (!Arrays.equals(request.originalOperation(), terminal.operationBytes()) + || !Arrays.equals(request.expectedGameDesignTerminalEvidence(), terminalBytes)) { + throw new IllegalArgumentException( + "World terminal read differs from the exact operation, terminal, or owner phase"); + } + WorldOutcome outcome = + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldOutcome.PUBLISHED + : WorldOutcome.ABORTED; return ReadPublicationTerminalResponse.newBuilder() .setSchemaVersion(request.schemaVersion()) .setTargetNamespace(request.targetNamespace()) @@ -62,8 +69,8 @@ public static ReadPublicationTerminalResponse toResponse( .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) .setExpectedGameDesignTerminalEvidence( ByteString.copyFrom(request.expectedGameDesignTerminalEvidence())) - .setWorldOutcome(toWireOutcome(evidence.worldOutcome())) - .setWorldTerminalEvidence(ByteString.copyFrom(evidence.worldTerminalEvidence())) + .setWorldOutcome(toWireOutcome(outcome)) + .setWorldTerminalEvidence(ByteString.copyFrom(terminalBytes)) .build(); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java index 9570fe748c..5e47ad9abb 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java @@ -8,6 +8,21 @@ import org.junit.jupiter.api.Test; class WorldPublicationTerminalReadEvidenceTest { + @Test + void rejectsAnOversizedOriginalOperationBeforeParsingTheTerminal() { + assertThatThrownBy( + () -> + new WorldPublicationTerminalReadEvidence.Request( + 1, + "test", + UUID.randomUUID(), + new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1], + new byte[] {1})) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Complete bounded original publication operation required") + .hasNoCause(); + } + @Test void retainsExactRequestAndWorldOutcomeForPublishedAndAborted() throws Exception { var operation = GameDesignPublicationTerminalReadGrpcCodecTest.operation(); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java index 229daf2da3..bd1bd518e7 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java @@ -734,11 +734,11 @@ private static Optional readValidated( || !Objects.equals(row.get(14, String.class), receipt.worldReadRequestDigest()) || !Objects.equals(row.get(15, String.class), receipt.worldClosureDigest()) || !Objects.equals(row.get(16, String.class), receipt.receiptDigest()) - || !Objects.equals(row.get(17, OffsetDateTime.class), receipt.retainedAt()) + || !sameInstant(row.get(17, OffsetDateTime.class), receipt.retainedAt()) || !Objects.equals(row.get(18, String.class), receipt.requestDigest()) || !Objects.equals(row.get(19, String.class), receipt.schemaDigest()) || !Objects.equals(row.get(20, String.class), receipt.receiptDigest()) - || !Objects.equals(row.get(22, OffsetDateTime.class), receipt.retainedAt())) { + || !sameInstant(row.get(22, OffsetDateTime.class), receipt.retainedAt())) { throw new IllegalStateException("Entity association differs from its immutable receipt"); } requirePersistedEmptyOnlyProviderStates(tx, receipt); @@ -746,6 +746,10 @@ private static Optional readValidated( return Optional.of(receipt); } + private static boolean sameInstant(OffsetDateTime actual, OffsetDateTime expected) { + return actual != null && expected != null && actual.toInstant().equals(expected.toInstant()); + } + private static void requirePersistedEmptyOnlyProviderStates( DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { for (var state : receipt.familyStates()) { @@ -778,7 +782,7 @@ private static void requirePersistedEmptyOnlyProviderStates( row.get(6, String.class), receipt.selectedSourceRevisionBindingDigest()) || !Objects.equals(row.get(7, String.class), receipt.worldClosureDigest()) || !Objects.equals(row.get(8, String.class), receipt.providerStateDigest(state.family())) - || !Objects.equals(row.get(9, OffsetDateTime.class), receipt.retainedAt())) { + || !sameInstant(row.get(9, OffsetDateTime.class), receipt.retainedAt())) { throw new IllegalStateException( "Entity EMPTY-only provider readback is missing or differs for " + state.family()); } diff --git a/services/entity-management-service/src/main/resources/application.yml b/services/entity-management-service/src/main/resources/application.yml index d3b5e99641..f6f33d6e48 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -3,6 +3,9 @@ spring: name: entity-management-service flyway: enabled: true + postgresql: + # V4 builds indexes concurrently; keep Flyway's advisory lock outside a transaction. + transactional-lock: false schemas: ${SERVICE_SCHEMA:public} locations: classpath:db/migration,classpath:db/migration/saga defaultSchema: ${SERVICE_SCHEMA:public} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalActorIdentityFoundationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalActorIdentityFoundationPostgresIntegrationTest.java index 4841642c30..892a28c39f 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalActorIdentityFoundationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalActorIdentityFoundationPostgresIntegrationTest.java @@ -5,6 +5,7 @@ import java.nio.file.Path; import java.util.Map; +import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.entitymanagement.entity.ActorIdentityStatus; import net.firedevops.firemud.entitymanagement.entity.Character; @@ -12,6 +13,7 @@ import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; @@ -65,9 +67,18 @@ void dropIsolatedSchema() { @Test void retainedNumericRowsAreQuarantinedAndLegacyWriterCannotPromoteThem() { - CharacterRepository legacyWriter = new CharacterRepository(dsl); - Character retained = legacyCharacter(7101L, 8101L, "retained-legacy"); - long retainedId = legacyWriter.save(retained).getId(); + long retainedId = + Objects.requireNonNull( + dsl.fetchSingle( + "INSERT INTO characters (tenant_id, account_id, playable_state_key, name, " + + "body_layout_key, level, experience, strength, agility, intelligence, stamina, " + + "health, mana, last_login_at, version) " + + "VALUES (?, ?, 'legacy-numeric', ?, 'DEFAULT', 0, 0, 0, 0, 0, 0, 0, 0, NULL, 0) " + + "RETURNING id", + 7101L, + 8101L, + "retained-legacy") + .get("id", Long.class)); migrateAll(); @@ -92,6 +103,7 @@ void retainedNumericRowsAreQuarantinedAndLegacyWriterCannotPromoteThem() { PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .isEmpty(); + CharacterRepository legacyWriter = new CharacterRepository(dsl); Character writtenByLegacyPath = legacyWriter.save(legacyCharacter(7102L, 8102L, "new-legacy-path")); var newlyWritten = readIdentityRow(writtenByLegacyPath.getId()); @@ -221,6 +233,9 @@ private Flyway configureFlyway(MigrationVersion target) { .schemas(schema) .defaultSchema(schema) .placeholders(Map.of("serviceSchema", schema)); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); return (target == null ? configuration : configuration.target(target)).load(); } diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java index c58cfdbf19..42bf19b2f5 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -9,6 +9,7 @@ import java.util.UUID; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; @@ -39,14 +40,17 @@ class EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest { void seedLegacyRowsBeforeV2() { schema = "entity_empty_source_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); - Flyway.configure() - .dataSource(dataSource) - .locations(MIGRATION_LOCATION) - .schemas(schema) - .defaultSchema(schema) - .target("1") - .load() - .migrate(); + var legacyFlywayConfiguration = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .target("1"); + legacyFlywayConfiguration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + legacyFlywayConfiguration.load().migrate(); DSLContext legacyDsl = DSL.using(dataSource, SQLDialect.POSTGRES); // Synthetic pre-V2 rows exercise migration occupancy only. They are not selected-source @@ -60,14 +64,17 @@ void seedLegacyRowsBeforeV2() { + "source_holder_kind, destination_holder_kind) " + "VALUES (61001, 99001, 1, 'MOVE', 'legacy-audit', 'UNKNOWN', 'UNKNOWN')"); - Flyway.configure() - .dataSource(dataSource) - .locations(MIGRATION_LOCATION) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .load() - .migrate(); + var flywayConfiguration = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)); + flywayConfiguration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + flywayConfiguration.load().migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); } diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java index 783c5a6dbb..b6d3b24321 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java @@ -13,6 +13,7 @@ import java.util.Locale; import java.util.Map; import java.util.Objects; +import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -22,6 +23,7 @@ import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestService; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; import org.jooq.DSLContext; import org.jooq.ExecuteContext; import org.jooq.SQLDialect; @@ -32,6 +34,8 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -72,14 +76,17 @@ class EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest { void migrateFreshIsolatedSchema() { schema = "entity_empty_source_repo_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); - Flyway.configure() - .dataSource(dataSource) - .locations(MIGRATION_LOCATION) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .load() - .migrate(); + var flywayConfiguration = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)); + flywayConfiguration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + flywayConfiguration.load().migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); repository = new EntityEmptySelectedSourceIntakeRepository(dsl); } @@ -95,6 +102,7 @@ void dropIsolatedSchema() { } @Test + @ResourceLock(Resources.TIME_ZONE) void persistsAllTwentyThreeExplicitEmptyStatesAndReplaysOriginalReceiptBytes() { var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); var inputs = fixture.inputs(); @@ -110,7 +118,14 @@ void persistsAllTwentyThreeExplicitEmptyStatesAndReplaysOriginalReceiptBytes() { .allSatisfy(count -> assertThat(count.count()).isZero()); String requestDigest = requestDigest(fixture); - EntityEmptySelectedSourceIntakeReceipt first = repository.retainFresh(inputs, requestDigest); + TimeZone originalTimeZone = TimeZone.getDefault(); + EntityEmptySelectedSourceIntakeReceipt first; + try { + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + first = repository.retainFresh(inputs, requestDigest); + } finally { + TimeZone.setDefault(originalTimeZone); + } assertThat(first.familyStates()) .hasSize(23) .allSatisfy( @@ -150,12 +165,16 @@ void persistsAllTwentyThreeExplicitEmptyStatesAndReplaysOriginalReceiptBytes() { for (String table : EMPTY_ONLY_TABLES) { assertThat(rowCount("SELECT COUNT(*) FROM " + table)).as(table).isEqualTo(1L); } - assertThat( - repository - .read(first.targetNamespace(), first.intakeRequestId()) - .orElseThrow() - .canonicalBytes()) - .containsExactly(first.canonicalBytes()); + EntityEmptySelectedSourceIntakeReceipt readBack; + try { + TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Auckland")); + readBack = repository.read(first.targetNamespace(), first.intakeRequestId()).orElseThrow(); + } finally { + TimeZone.setDefault(originalTimeZone); + } + assertThat(readBack.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(readBack.receiptDigest()).isEqualTo(first.receiptDigest()); + assertThat(readBack.retainedAt().toInstant()).isEqualTo(first.retainedAt().toInstant()); assertThatThrownBy( () -> @@ -172,9 +191,16 @@ void persistsAllTwentyThreeExplicitEmptyStatesAndReplaysOriginalReceiptBytes() { EntityEmptySelectedSourceIntakePostgresFixture.withFreshWorldReadCorrelation(fixture); assertThat(retry.worldEvidence().request().readRequestId()) .isNotEqualTo(fixture.worldEvidence().request().readRequestId()); - EntityEmptySelectedSourceIntakeReceipt replay = - repository.retainFresh(retry.inputs(), requestDigest(retry)); + EntityEmptySelectedSourceIntakeReceipt replay; + try { + TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Auckland")); + replay = repository.retainFresh(retry.inputs(), requestDigest(retry)); + } finally { + TimeZone.setDefault(originalTimeZone); + } assertThat(replay.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(replay.receiptDigest()).isEqualTo(first.receiptDigest()); + assertThat(replay.retainedAt().toInstant()).isEqualTo(first.retainedAt().toInstant()); assertThat(replay.worldReadRequestId()).isEqualTo(first.worldReadRequestId()); var changed = EntityEmptySelectedSourceIntakePostgresFixture.create("2"); diff --git a/services/entity-management-service/src/test/resources/application.yml b/services/entity-management-service/src/test/resources/application.yml index ec1671a55b..cd57d6839c 100644 --- a/services/entity-management-service/src/test/resources/application.yml +++ b/services/entity-management-service/src/test/resources/application.yml @@ -1,3 +1,7 @@ FIREMUD_GRPC_CERT_CHAIN_PATH: classpath:certs/dev-cert.pem FIREMUD_GRPC_PRIVATE_KEY_PATH: classpath:certs/dev-key.pem FIREMUD_GRPC_CA_CERT_PATH: classpath:certs/dev-ca.pem +spring: + flyway: + postgresql: + transactional-lock: false diff --git a/services/game-design-service/src/main/resources/db/migration/V74__restore_selected_release_original_account_owner_schema.sql b/services/game-design-service/src/main/resources/db/migration/V74__restore_selected_release_original_account_owner_schema.sql new file mode 100644 index 0000000000..61d8ec885b --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V74__restore_selected_release_original_account_owner_schema.sql @@ -0,0 +1,23 @@ +-- Restore the V71 Account schema predicate after V72 replaces the full release guard. +-- Keep every exact owner-byte, selector, applied-result, receipt and participant check unchanged. +-- [jooq ignore start] +DO $migration$ +DECLARE + evidence_function REGPROCEDURE := '"${serviceSchema}".enforce_published_world_start_location_evidence()'::REGPROCEDURE; + original_definition TEXT; + schema_anchor TEXT := $anchor$ OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') IS DISTINCT FROM 'account-draft-authorization-fence/v1'$anchor$; + schema_replacement TEXT := $replacement$ OR (convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') + IS DISTINCT FROM 'account-draft-authorization-fence/v1' + AND convert_from(published_world_selector_frame(account_bytes, 0),'UTF8') + IS DISTINCT FROM 'account-draft-authorization-fence/v2')$replacement$; +BEGIN + SELECT pg_get_functiondef(evidence_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, schema_anchor, ''))) + / length(schema_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact V72 selected-release Account schema guard'; + END IF; + original_definition := replace(original_definition, schema_anchor, schema_replacement); + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index 7215d44491..f088d86f61 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -27,6 +27,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateFactory; +import java.sql.SQLException; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -45,6 +46,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; import java.util.function.Supplier; import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; @@ -407,6 +409,7 @@ import net.firedevops.firemud.worldmanagement.v1.ZoneDesignMutation; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -443,6 +446,8 @@ import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.S3Object; import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; /** * Real original GD+World source settlement and Account/GL intake-to-GD-receipt, followed by actual @@ -3250,8 +3255,75 @@ private void runRealSelectedSourceReceiptInventoryAndExportAreExactAndRetryable( .isZero(); byte[] originalPublicationOperation = publicationReservation.operation().canonicalBytes(); + accountAccess + .sources() + .dsl + .fetch( + "SELECT require_selected_inventory_operation_v2(?)", originalPublicationOperation); var originalPublicationBinding = GameDesignPublicationOperationBinding.fromStored(originalPublicationOperation); + assertSelectedInventoryProfileRejected( + accountAccess.sources().dsl, + rebindSelectedInventory( + originalPublicationBinding, + inventory -> { + inventory.put("schema", "world-selected-publication-artifact-inventory/v1"); + inventory.put("schemaVersion", 1); + })); + assertSelectedInventoryProfileRejected( + accountAccess.sources().dsl, + rebindSelectedInventory( + originalPublicationBinding, + inventory -> + ((ObjectNode) inventory.get("sourceModel")).put("unknownSourceFamily", true))); + assertSelectedInventoryProfileRejected( + accountAccess.sources().dsl, + rebindSelectedInventory( + originalPublicationBinding, + inventory -> + ((ArrayNode) + inventory + .get("sourceModel") + .get("inboundSourceClosure") + .get("familyCounts")) + .remove(0))); + assertSelectedInventoryProfileRejected( + accountAccess.sources().dsl, + rebindSelectedInventory( + originalPublicationBinding, + inventory -> + ((ObjectNode) + inventory + .get("sourceModel") + .get("inboundSourceClosure") + .get("familyCounts") + .get(0)) + .put("count", 1))); + assertSelectedInventoryProfileRejected( + accountAccess.sources().dsl, + rebindSelectedInventory( + originalPublicationBinding, + inventory -> + ((ObjectNode) inventory.get("sourceModel")).remove("inboundSourceClosure"))); + assertSelectedInventoryProfileRejected( + accountAccess.sources().dsl, + rebindSelectedInventory( + originalPublicationBinding, + inventory -> + ((ObjectNode) + inventory + .get("sourceModel") + .get("inboundSourceClosure") + .get("familyCounts") + .get(0)) + .put("family", "WORLD_INBOUND_SOURCE_FAMILY_UNKNOWN"))); + assertSelectedInventoryProfileRejected( + accountAccess.sources().dsl, + rebindSelectedInventory( + originalPublicationBinding, + inventory -> + ((ObjectNode) inventory.get("sourceModel").get("inboundSourceClosure")) + .put("unknownFamily", true))); var gameDesignTerminalRequest = GameDesignPublicationTerminalReadEvidence.Request.create( NAMESPACE, originalPublicationBinding); @@ -6575,15 +6647,20 @@ private static Store serviceStore(PostgreSQLContainer postgres, String servic new DriverManagerDataSource( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); data.setSchema(schema); - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history_" + service.replace('-', '_')) - .placeholders(Map.of("serviceSchema", schema)) - .locations(migrationLocation(service)) - .load() - .migrate(); + var flyway = + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history_" + service.replace('-', '_')) + .placeholders(Map.of("serviceSchema", schema)) + .locations(migrationLocation(service)); + if ("entity-management".equals(service)) { + flyway + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + } + flyway.load().migrate(); var transactions = new DataSourceTransactionManager(data); var configuration = new DefaultConfiguration(); configuration.set(SQLDialect.POSTGRES); @@ -7390,6 +7467,35 @@ private static String sha256(byte[] bytes) { } } + private static byte[] rebindSelectedInventory( + GameDesignPublicationOperationBinding operation, Consumer mutation) + throws IOException { + var mapper = new ObjectMapper(); + var inventory = (ObjectNode) mapper.readTree(operation.inventory().canonicalBytes()); + mutation.accept(inventory); + byte[] inventoryBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(mapper.writeValueAsString(inventory)); + var rebound = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(rebound, GameDesignPublicationOperationBinding.SCHEMA); + DraftAuthorizationFenceBinding.frame(rebound, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(rebound, operation.world().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(rebound, inventoryBytes); + DraftAuthorizationFenceBinding.frame(rebound, "sha256:" + sha256(inventoryBytes)); + return rebound.toByteArray(); + } + + private static void assertSelectedInventoryProfileRejected( + org.jooq.DSLContext accountDsl, byte[] operationBytes) { + assertThatThrownBy( + () -> + accountDsl.fetch( + "SELECT require_selected_inventory_operation_v2(?)", operationBytes)) + .rootCause() + .isInstanceOf(SQLException.class) + .satisfies( + failure -> assertThat(((SQLException) failure).getSQLState()).isEqualTo("23514")); + } + private static String selectedEmptyPublicationDigest( String domain, int schemaVersion, @@ -7733,6 +7839,7 @@ private static final class MinioConditionalObjectStore implements AutoCloseable private final PublicationDigestRequestBinding request; private final AtomicInteger puts = new AtomicInteger(); private final AtomicInteger gets = new AtomicInteger(); + private final String bucket; private final URI endpoint; private final S3Client client; private byte[] inventoryBytes; @@ -7744,6 +7851,7 @@ private static final class MinioConditionalObjectStore implements AutoCloseable VersionAssetExportCandidateService candidates, PublicationDigestRequestBinding request) { this.candidates = candidates; this.request = request; + this.bucket = MINIO_BUCKET + "-" + UUID.randomUUID().toString().replace("-", ""); endpoint = URI.create("http://" + MINIO.getHost() + ":" + MINIO.getMappedPort(9000)); client = S3Client.builder() @@ -7759,7 +7867,7 @@ private static final class MinioConditionalObjectStore implements AutoCloseable new CandidateReadbackExecutionInterceptor())) .build(); try { - client.createBucket(CreateBucketRequest.builder().bucket(MINIO_BUCKET).build()); + client.createBucket(CreateBucketRequest.builder().bucket(bucket).build()); } catch (RuntimeException failure) { client.close(); throw failure; @@ -7781,7 +7889,7 @@ String endpoint() { } String bucket() { - return MINIO_BUCKET; + return bucket; } S3Client client() { @@ -7789,14 +7897,12 @@ S3Client client() { } List objects() { - return client - .listObjectsV2(ListObjectsV2Request.builder().bucket(MINIO_BUCKET).build()) - .contents(); + return client.listObjectsV2(ListObjectsV2Request.builder().bucket(bucket).build()).contents(); } StoredObject objectAt(String key) { var observed = - client.getObjectAsBytes(GetObjectRequest.builder().bucket(MINIO_BUCKET).key(key).build()); + client.getObjectAsBytes(GetObjectRequest.builder().bucket(bucket).key(key).build()); return new StoredObject(observed.asByteArray(), observed.response().contentType()); } @@ -7850,19 +7956,25 @@ private void requireExactCandidateBeforePut() { } private final class CandidateReadbackExecutionInterceptor implements ExecutionInterceptor { + @Override + public void beforeExecution( + software.amazon.awssdk.core.interceptor.Context.BeforeExecution context, + ExecutionAttributes executionAttributes) { + if (context.request() instanceof GetObjectRequest get && bucket.equals(get.bucket())) { + gets.incrementAndGet(); + } + } + @Override public void beforeTransmission( software.amazon.awssdk.core.interceptor.Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { if (context.request() instanceof PutObjectRequest put) { - if (!MINIO_BUCKET.equals(put.bucket()) || !"*".equals(put.ifNoneMatch())) { + if (!bucket.equals(put.bucket()) || !"*".equals(put.ifNoneMatch())) { throw new AssertionError("Selected object PUT was not conditional to the test bucket"); } puts.incrementAndGet(); requireExactCandidateBeforePut(); - } else if (context.request() instanceof GetObjectRequest get - && MINIO_BUCKET.equals(get.bucket())) { - gets.incrementAndGet(); } } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java index 337d8c5828..61b1b1eba9 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/SelectedInventoryProfileUpgradeIntegrationTest.java @@ -37,11 +37,19 @@ import org.testcontainers.junit.jupiter.Testcontainers; import tools.jackson.databind.ObjectMapper; -/** Physical V69-to-V71 upgrade proof using isolated, explicitly synthetic upstream evidence. */ +/** Physical V69-to-V74 upgrade proof using isolated, explicitly synthetic upstream evidence. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class SelectedInventoryProfileUpgradeIntegrationTest { private static final ObjectMapper JSON = new ObjectMapper(); + private static final String V72_ACCOUNT_SCHEMA_GUARD = + " OR convert_from(published_world_selector_frame(account_bytes, 0),'UTF8')" + + " IS DISTINCT FROM 'account-draft-authorization-fence/v1'"; + private static final String V74_ACCOUNT_SCHEMA_GUARD = + " OR (convert_from(published_world_selector_frame(account_bytes, 0),'UTF8')\n" + + " IS DISTINCT FROM 'account-draft-authorization-fence/v1'\n" + + " AND convert_from(published_world_selector_frame(account_bytes, 0),'UTF8')\n" + + " IS DISTINCT FROM 'account-draft-authorization-fence/v2')"; @Container static final PostgreSQLContainer POSTGRES = @@ -107,11 +115,26 @@ void forwardUpgradePreservesRetainedV1OperationAndAdmitsOnlyPairedProfiles() thr // The actual V56 validator is still installed at V69 and must accept the historical bytes. dsl.fetch("SELECT require_selected_inventory_operation_v2(?)", originalOperationBytes); - flyway(dataSource, schema, null).migrate(); + flyway(dataSource, schema, "72").migrate(); + FunctionSnapshot afterV72 = selectedEvidenceFunction(dsl, schema); + flyway(dataSource, schema, "73").migrate(); + FunctionSnapshot beforeV74 = selectedEvidenceFunction(dsl, schema); + assertThat(beforeV74.definition()).isEqualTo(afterV72.definition()); + assertThat(beforeV74.oid()).isEqualTo(afterV72.oid()); + Map beforeV74MigrationChecksums = migrationChecksums(dsl); + String expectedV74Definition = + replaceExactlyOnce( + beforeV74.definition(), V72_ACCOUNT_SCHEMA_GUARD, V74_ACCOUNT_SCHEMA_GUARD); + + flyway(dataSource, schema, "74").migrate(); + FunctionSnapshot afterV74 = selectedEvidenceFunction(dsl, schema); + assertThat(afterV74.definition()).isEqualTo(expectedV74Definition); + assertThat(afterV74.oid()).isEqualTo(beforeV74.oid()); Map upgradedMigrationChecksums = migrationChecksums(dsl); assertThat(upgradedMigrationChecksums).containsAllEntriesOf(originalMigrationChecksums); - assertThat(upgradedMigrationChecksums).containsKeys("70", "71"); + assertThat(upgradedMigrationChecksums).containsAllEntriesOf(beforeV74MigrationChecksums); + assertThat(upgradedMigrationChecksums).containsKeys("70", "71", "72", "73", "74"); assertThat(readOperationBytes(dsl, historicalV1.workflowId())) .containsExactly(originalOperationBytes); var repository = new GameDesignPublicationOperationRepository(dsl); @@ -223,6 +246,30 @@ private static Map migrationChecksums(DSLContext dsl) { return checksums; } + private static FunctionSnapshot selectedEvidenceFunction(DSLContext dsl, String schema) { + var row = + dsl.fetchSingle( + "SELECT p.oid::bigint AS function_oid, pg_get_functiondef(p.oid) AS definition " + + "FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace " + + "WHERE n.nspname = ? AND p.proname = ? " + + "AND pg_get_function_identity_arguments(p.oid) = ''", + schema, + "enforce_published_world_start_location_evidence"); + return new FunctionSnapshot( + java.util.Objects.requireNonNull(row.get("function_oid", Long.class), "function_oid"), + java.util.Objects.requireNonNull(row.get("definition", String.class), "definition")); + } + + private static String replaceExactlyOnce(String value, String anchor, String replacement) { + int start = value.indexOf(anchor); + if (start < 0 || value.indexOf(anchor, start + anchor.length()) >= 0) { + throw new AssertionError("V72 Account schema guard does not match exactly once"); + } + return value.substring(0, start) + replacement + value.substring(start + anchor.length()); + } + + private record FunctionSnapshot(long oid, String definition) {} + private static byte[] rebindInventory( GameDesignPublicationOperation operation, java.util.function.Consumer mutation) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifier.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifier.java index cefffe8e4b..b2edf1d968 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifier.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifier.java @@ -63,10 +63,9 @@ public WorldPublicationTerminalService.VerifiedTerminal authenticateAndVerifyAnd throw new SecurityException( "Authenticated Game Design terminal differs from the submitted exact operation or result"); } - WorldPublicationTerminal.Request worldRequest = - WorldPublicationTerminal.Request.fromStored(terminal.canonicalBytes()); + WorldPublicationTerminal.Request worldRequest = new WorldPublicationTerminal.Request(terminal); return new WorldPublicationTerminalService.VerifiedTerminal( - worldRequest, new ExactTerminalReadAuthority(operationBytes, terminal.canonicalBytes())); + worldRequest, new ExactTerminalReadAuthority(operationBytes, worldRequest)); } private void requireAuthenticatedGameDesignCaller() { @@ -91,22 +90,22 @@ private static void requireNoAmbientTransaction() { private static final class ExactTerminalReadAuthority implements WorldPublicationTerminalService.HeldTerminalAuthority { private final byte[] operationBytes; - private final byte[] terminalBytes; + private final WorldPublicationTerminal.Request terminal; private final AtomicBoolean open = new AtomicBoolean(true); - private ExactTerminalReadAuthority(byte[] operationBytes, byte[] terminalBytes) { + private ExactTerminalReadAuthority( + byte[] operationBytes, WorldPublicationTerminal.Request terminal) { this.operationBytes = operationBytes.clone(); - this.terminalBytes = terminalBytes.clone(); + // Reuse the immutable result whose complete bytes were compared before creating authority. + this.terminal = Objects.requireNonNull(terminal, "terminal"); } @Override public void requireHeld() { if (!open.get() || operationBytes.length == 0 - || terminalBytes.length == 0 - || !Arrays.equals( - operationBytes, - WorldPublicationTerminal.Request.fromStored(terminalBytes).operationBytes())) { + || terminal.terminalBytes().length == 0 + || !Arrays.equals(operationBytes, terminal.operationBytes())) { throw new IllegalStateException( "Exact authenticated Game Design terminal read authority is no longer valid"); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java index 343ea45c12..9bd07cad80 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminal.java @@ -24,7 +24,7 @@ public static Request request(byte[] terminalBytes) { public record Request(GameDesignPublicationTerminalEvidence evidence) { public Request { Objects.requireNonNull(evidence, "evidence"); - evidence = GameDesignPublicationTerminalEvidence.fromStored(evidence.canonicalBytes()); + // The final evidence type already validates and defensively retains its canonical bytes. } public WorldPublishedStartLocationEvidence worldEvidence() { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java index 408db6ba92..bf22a938e4 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java @@ -6,7 +6,6 @@ import java.util.Objects; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; import org.springframework.dao.DataAccessException; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -42,10 +41,8 @@ public GameDesignPublicationTerminalEvidence read( .asRuntimeException(); } - final GameDesignPublicationOperationBinding operation; final WorldPublicationTerminal.Request terminalRequest; try { - operation = GameDesignPublicationOperationBinding.fromStored(request.originalOperation()); terminalRequest = WorldPublicationTerminal.request(request.expectedGameDesignTerminalEvidence()); } catch (RuntimeException malformed) { @@ -53,11 +50,10 @@ public GameDesignPublicationTerminalEvidence read( .withDescription("Canonical original publication operation and terminal are required") .asRuntimeException(); } - if (!Arrays.equals(operation.canonicalBytes(), request.originalOperation()) - || !Arrays.equals(terminalRequest.operationBytes(), request.originalOperation()) + if (!Arrays.equals(terminalRequest.operationBytes(), request.originalOperation()) || !Arrays.equals( terminalRequest.terminalBytes(), request.expectedGameDesignTerminalEvidence()) - || !workloadNamespace.equals(operation.world().request().targetNamespace())) { + || !workloadNamespace.equals(terminalRequest.worldEvidence().request().targetNamespace())) { throw Status.FAILED_PRECONDITION .withDescription("World terminal lookup differs from the exact original publication") .asRuntimeException(); From c6caccf64d3205f2f58a968b9b3a5c9291c1fef8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:00:49 +1300 Subject: [PATCH 127/129] Retain exact Account StartSession tuples across receiving owners --- ...dmin-as-external-operator-write-ingress.md | 4 + .../account-service/api-contracts.md | 4 +- .../game-session-service/api-contracts.md | 2 + .../logging-admin-service/api-contracts.md | 4 + design/project-management/ai-observations.md | 20 + ...ame-authoring-publishing-and-activation.md | 2 + .../player-access-and-session.md | 2 + ...start_session_operator_authorization.proto | 6 + ...art_session_world_participation_read.proto | 13 +- services/account-service/build.gradle.kts | 1 + ...StartSessionReservationEvidenceClient.java | 1 - ...orldOriginalAttemptEvidenceRepository.java | 40 +- ...ssionOperatorAuthorizationGrpcService.java | 65 +- ...rtSessionOperatorAuthorizationService.java | 186 ++- ...articipationHistoricalReadGrpcService.java | 3 +- ...rldParticipationHistoricalReadService.java | 21 +- ...ttemptEvidencePostgresIntegrationTest.java | 17 +- ...rldAcquisitionPostgresIntegrationTest.java | 1105 ++++++++++------- ...dParticipationPostgresIntegrationTest.java | 109 +- ...sionReservationEvidenceClientMtlsTest.java | 20 +- ...tSessionReservationEvidenceClientTest.java | 79 ++ ...OriginalAttemptEvidenceRepositoryTest.java | 17 +- ...nOperatorAuthorizationGrpcServiceTest.java | 82 +- ...ssionOperatorAuthorizationServiceTest.java | 69 +- ...ldParticipationAcquisitionServiceTest.java | 44 +- ...cipationHistoricalReadGrpcServiceTest.java | 66 +- ...articipationHistoricalReadServiceTest.java | 134 +- ...StartSessionAuthorizationProofFixture.java | 105 +- .../common-platform-core/build.gradle.kts | 3 + ...orldParticipationHistoricalReadClient.java | 8 +- ...ldParticipationHistoricalReadEvidence.java | 54 +- ...dParticipationHistoricalReadGrpcCodec.java | 23 +- ...rldParticipationHistoricalReadRequest.java | 91 +- ...artSessionAccountRedemptionProjection.java | 66 +- ...icalOriginalStartSessionOwnerEvidence.java | 8 +- ...essionCurrentAttemptEvidenceGrpcCodec.java | 18 + ...essionPostAuthorizationExecutionTuple.java | 57 +- ...essionAdmissionProtectionEvidenceTest.java | 9 +- ...ParticipationHistoricalReadClientTest.java | 57 +- ...ticipationHistoricalReadGrpcCodecTest.java | 197 ++- ...rtSessionCurrentAttemptClientMtlsTest.java | 3 +- ...onCurrentAttemptEvidenceGrpcCodecTest.java | 13 +- ...essionAccountRedemptionProjectionTest.java | 172 +++ ...onPostAuthorizationExecutionTupleTest.java | 59 +- ...SessionAuthorityEvidenceBundleFixture.java | 139 +++ ...licationExportPostgresIntegrationTest.java | 30 +- .../StartSessionOperatorRedemptionClient.java | 328 +++++ ...sionCanonicalInstanceLaunchRepository.java | 39 + ...StartSessionOperatorAttemptRepository.java | 113 +- ...tSessionCurrentAttemptReadGrpcService.java | 18 +- ...rCoreRetentionPostgresIntegrationTest.java | 30 +- ...InstanceLaunchPostgresIntegrationTest.java | 190 +++ ...entAttemptReadPostgresIntegrationTest.java | 157 ++- ...ssionOperatorRedemptionClientMtlsTest.java | 605 +++++++++ ...rtSessionOperatorRedemptionClientTest.java | 570 +++++++++ ...sionCurrentAttemptReadGrpcServiceTest.java | 33 +- .../logging-admin-service/build.gradle.kts | 1 + ...artSessionOperatorAuthorizationClient.java | 43 +- .../StartSessionAuthorizationCoordinator.java | 9 +- ...onOperatorAuthorizationClientMtlsTest.java | 83 +- ...essionOperatorAuthorizationClientTest.java | 148 +-- ...rtSessionAuthorizationCoordinatorTest.java | 275 ++-- .../world-management-service/build.gradle.kts | 1 + ...anceOriginalOperationRecoveryVerifier.java | 27 +- ...OriginalOperationRecoveryVerifierTest.java | 188 ++- 65 files changed, 4864 insertions(+), 1222 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/StartSessionAccountRedemptionProjectionTest.java create mode 100644 services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleFixture.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index aeb85f7a27..8863328288 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -101,6 +101,10 @@ After Game Session has redeemed the original human StartSession reference and al The sole additional reader is the exact configured original same-namespace Game Session redeemer, for restricted owner-internal continuation under the same stored, unexpired `PENDING` claim, original attempt/fence and complete tuple. Game Session must read remotely outside SQL, then lock and recheck its original owner operation and database-clock claim expiry at the actual association statement. Only exact replay of an existing immutable selection pin is permitted; this read cannot create a new pin, expose a general replay-created claim, renew or transfer a claim, create another attempt/fence/reference, mutate a domain or authorize admission. Expired, unattached or ambiguous operations remain reconciliation-only. This exception does not widen the distinct World receiving participation or change the original `targetOwner=game-session-service`. +Account-derived original tuple evidence and exact capture-reference comparison are defined by the [Account authorization-reference contract](../microservices/account-service/api-contracts.md#operator-authorization-references). Logging & Admin persists and hands off those unchanged owner-returned bytes; the integrity carrier does not replace authenticated Account evidence or authorize runtime execution. + +Within ADR 0048's `postAuthorizationExecutionTuple/v1`, production encoding of `reservationClaimFence` uses a number for positive values through `9007199254740991` and the canonical decimal string for larger values through `9223372036854775807`; each value has exactly one accepted spelling. Small-value strings, unsafe JSON numbers (including exactly `9007199254740992`), malformed strings, and values outside the signed 64-bit range fail closed for current execution. Consumers preserve all original stored bytes and do not reconstruct, upgrade, or infer a canonical value from historical JSON spelling; historical tuples with unsafe numeric fence values are not current-execution evidence. This representation rule applies only to `reservationClaimFence`: the other authority-tuple fields and independent `membershipVersion` retain their own exact source guards. It does not change the tuple version or authorize SQL changes, backfill, JWT scalar conversion, or authority-map shape changes; ADR 0048 remains the owner of the complete tuple definition. + #### StartSession World Receiving Participation For the human StartSession flow, Account owns a separate same-namespace World receiving-participation lifecycle for protecting the exact source through World execution. Only the exact authenticated same-namespace `world-management-service` workload may receive and use this participation for its canonical World target. The original Account-issued StartSession authorization and immutable typed `targetOwner=game-session-service` remain unchanged. Account binds its distinct World participation purpose, stable participation ID, and positive participation fence to the exact original canonical complete `postAuthorizationExecutionTuple` and issuance record, including the original reservation owner and claim fence; the actual redeemed Game Session `ownerAttemptId` and `ownerFence`; the exact authenticated Game Design descriptor, release, and source association; and the canonical World target. This participation is not a replacement issuance or a second authority record. It does not issue, renew, or re-redeem the original authorization reference, change its target owner, create another Game Session attempt, or turn the Game Design projection into permission. Neither the `Redeemed StartSession Projection Read` above nor settled publication hold/settlement evidence authorizes StartSession execution in World or substitutes for this participation. diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index a9520326ac..5c81a3f3a9 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -185,6 +185,8 @@ The distinct [`AccountSelectedOwnerIntakeSourceReadService.ReadSourceScope`](../ ### Operator Authorization References +ISSUE, RECOVER and REDEEM return the complete original Account-derived canonical post-authorization tuple alongside their existing authorization evidence. Account reconstructs that tuple from the immutable issuance and capture binding, independently of caller-supplied tuple bytes; all four original bundle-reference fields (`bundleVersion`, `sourceVersion`, `sourceFence`, `linearization`) remain exact. The retained encrypted recovery payload keeps its original five fields and bytes. Logging & Admin compares the full returned tuple before completing its reservation and persists/hands off those Account-returned bytes. Game Session compares them at redemption, retains the bounded complete owner tuple, and checks the same independent retained evidence again before fresh launch preparation. A schema/source-version integrity check, two caller copies, or equality between the independent source and issuance fences cannot establish this owner binding. The tuple evidence grants no separate execution or activation authority. + The original StartSession flow has a distinct Account-owned **activation-purpose protection**, separate from the World preparation participation and the later ACTIVE-only Game Session admission protection. Preparation `COMMITTED` retains its existing meaning and does not prove activation. Before World opens its activation transaction, Account acquires this protection under still-valid original authority, binding the unchanged complete source vector and original tuple, exact current Game Session attempt/mutation/fence and finite original lease, actual `STARTING` launch, exact `PREPARING` owner evidence and activation operation identity. It does not issue, renew, redeem or restart authority. Source participation stays pending through World's exact activation compare-and-set. Account may settle only from authenticated exact `ACTIVE` terminal evidence or a positively fenced `ABORTED` result that excludes later activation for the same operation; timeout, expiry, absence, ambiguous evidence and generic handle `close()` cannot release it. Exact committed recovery reuses immutable identities and results without authorizing new work. The [World activation consequence](../world-management-service/api-contracts.md#canonical-initial-activation-protection) owns its local transaction and terminal exclusion. Producer/consumer, crash, expiry and settlement proof remain required before activation is enabled; implementation status belongs to the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). The activation-only closed RFC 8785 request `account-start-session-activation-protection-request/v1` has exactly `schema`, `originalPostAuthorizationTupleBytesBase64`, `accountRedemptionProjectionBytesBase64`, `gameSessionOwnerMutationId`, `gameSessionOwnerAttemptId`, `gameSessionOwnerFence`, `originalLeaseExpiresAt`, `accountWorldParticipationId`, `accountWorldParticipationFence`, `gameSessionLaunchReadEvidenceBytesBase64`, `worldActivationRequestId`, and `preparingEvidenceBytesBase64`. It retains both complete authenticated owner observations, not a digest-only summary. Account derives the projection, lease and participation from its actual original records and authenticated current-attempt read, never caller assertions. UUIDs are non-nil canonical values, fences are positive canonical decimal strings, and timestamps preserve exact UTC microseconds. The actual Game Session row must be `STARTING`; its retained original tuple, full descriptor/release, namespace/scope and public-production target must match World's `PREPARING` evidence. World additionally checks the captured realm/catalog against its actual retained owner association at the commit boundary. The stable operation identity excludes only the two transport read correlation IDs; the full first request retains them unchanged, and an exact retry cannot overwrite the first receipt with newer observations. @@ -217,7 +219,7 @@ Error precedence is canonical: (1) Account authenticates the exact immediate mTL These RPCs and schemas are accepted target state but are not present in the current Account proto or implementation. Logging & Admin remains the external operator ingress and durable intent/audit coordinator, Account remains the authorization authority and owner of original-reference retention, and the domain service remains the mutation owner. -For StartSession, Account's existing human authorization-reference issuer remains the sole issuer and the original reference retains `targetOwner=game-session-service`. The distinct Account-owned same-namespace World receiving-participation and source-protection lifecycle is defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation); this API contract adds no replacement issuer, reference-renewal, or re-redemption path. The Game Design projection read and publication hold/settlement producers remain separate and grant no StartSession World permission. The standalone, unregistered [historical participation read](../../../../protos/account/v1/start_session_world_participation_read.proto) authenticates the exact configured same-namespace World workload and returns only the retained original identity from an independent Account transaction. Its fresh read correlation and original participation ID/fence are lookup selectors, not fresh authority; expiry or settlement cannot renew the reference, restart execution or manufacture an abort. Unregistered repository, currentness, historical-read and exact-terminal settlement components do not establish a complete genuine participation producer or World admission; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records their remaining producer, consumer and physical proof gates. +For StartSession, Account's existing human authorization-reference issuer remains the sole issuer and the original reference retains `targetOwner=game-session-service`. The distinct Account-owned same-namespace World receiving-participation and source-protection lifecycle is defined by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#startsession-world-receiving-participation); this API contract adds no replacement issuer, reference-renewal, or re-redemption path. The Game Design projection read and publication hold/settlement producers remain separate and grant no StartSession World permission. The standalone, unregistered [historical participation read](../../../../protos/account/v1/start_session_world_participation_read.proto) authenticates the exact configured same-namespace World workload and returns only the retained original identity from an independent Account transaction. Its fresh read correlation and complete unchanged original post-authorization tuple select the retained participation; Account returns the original participation ID and fence for the World receiver to compare against its retained identity. These historical fields are not fresh authority; expiry or settlement cannot renew the reference, restart execution or manufacture an abort. Unregistered repository, currentness, historical-read and exact-terminal settlement components do not establish a complete genuine participation producer or World admission; the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) records their remaining producer, consumer and physical proof gates. The original source capture continues to bind the exact Logging issuer identity. Account's authenticated World receiving lookup compares that retained identity and the complete original tuple/current-source capture without treating Logging as the current caller: the receiving method authenticates the exact configured same-namespace World workload and rejects end-user context. This distinct lookup cannot allocate or replace a capture, issue or redeem a reference, or skip the source, bundle, original-attempt, lease and commit-bound participation checks. Issuance and Logging-owned recovery retain their original Logging caller requirement. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 4de87cb173..4ba95194fc 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -159,6 +159,8 @@ Service definitions reside in [../../../../protos/game-session/v1](../../../../p ### External Operator Lifecycle Contract +Original StartSession redemption retains the complete canonical tuple independently returned by Account under the [Account authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references), once and within the existing 256 KiB bound. Current attempt reads and fresh launch allocation compare that retained owner evidence with the complete original tuple and reject legacy scalar-only projections. Exact historical owner reads preserve and validate retained legacy scalar bytes without rewriting them or granting fresh authority; exact existing launch retries replay their original allocation before any fresh-allocation check. This distinction does not renew the original reference, lease or participation. + The separate unregistered `ReadOriginalStartSessionCurrentAttempt` read accepts only the exact same-namespace Account workload without end-user context. It returns the complete original pending attempt and attached Account projection only while both the Game Session database-clock owner lease and original Account reference remain unexpired; the owner claim credential stays inside the repository. Account remains the authorization owner under its [operator-authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references). This locked observation performs no renewal, redemption, admission, or durable mutation and does not establish continuous protection through a later owner commit. Source and proof status belong to the [Game Session tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). **Target state:** External operator mutations enter through the Logging & Admin Service via Gateway. Logging & Admin authenticates the `control-ui` session, records the durable intent and audit context, and calls Account's canonical [`IssueHumanOperatorAuthorizationReference`](../account-service/api-contracts.md#operator-authorization-references) RPC; unattended automation uses the separately typed `IssueAutomationOperatorAuthorizationReference` branch under the restrictions that Account contract defines. Logging & Admin then forwards the opaque bounded reference unchanged with the exact typed action-family request, `actionFamilySchemaId`, `actionFamilySchemaVersion`, same `controlPlaneRequestId`, canonical `mutationDigest/v1` digest, and every scope, target, expected-version, mutation, and audit-reason field declared by that schema to the Game Session owner RPC over its exact mTLS workload identity. Only transport credentials and the authorization reference are excluded from the digest. If generation or privileged-predicate fields are copied outside the Account reference, they are non-authoritative context: Game Session must exclude those forwarded copies from authorization decisions and the mutation digest, or omit them entirely. Logging & Admin may forward the end-user `control-ui` JWT to Account only for reference issuance; it must never forward an end-user JWT or caller-asserted actor identity to Game Session. Game Session recomputes the digest from the exact schema pair and every declared digest input, then calls Account's `RedeemOperatorAuthorization` contract with the exact owner, action family and schema pair, scope, request identity, and digest. Account's returned bounded actor or automation-policy authorization projection is the sole authorization source; Game Session uses that Account-derived projection for audit while independently validating target-domain ownership, runtime fences, and owner-side idempotency. This target path is not currently routable and has no fallback external mutation route. diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index a69e13d2ef..51477d802a 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -2,6 +2,10 @@ This document defines the Logging & Admin Service REST and gRPC surfaces, authentication classes, and endpoint availability expectations. +## Original StartSession Authorization Evidence + +Before completing an original StartSession reservation, Logging & Admin compares the complete Account-returned tuple to its exact reserved operation and validated response, then persists and hands off those unchanged Account bytes. ISSUE, recovery and ambiguous outcomes retain the same durable reservation/readback rules; no response permits a caller-derived replacement tuple. The [Account authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references) owns the complete tuple and capture-reference binding. This receiver remains subject to its existing authentication, finite expiry, transport and unavailable-runtime boundaries. + ## Account Audit Ingress and Receipt The canonical Account-to-Logging & Admin audit ingress is the existing `logging_admin.v1.LoggingAdminService/CreateLogEvent` RPC, converged in place rather than duplicated as a parallel ingress. It is a non-destructive internal service RPC, not an operator/admin mutation. Account is the producer and source authority for account state; Logging & Admin owns the receiver-side audit envelope, durable receipt/readback, deduplication, and audit projection. The audit ingress follows only shared envelope fundamentals (stable identity, event type/schema, producer occurrence time, and at-least-once/idempotent delivery) from [Session Behavior](../../system-architecture-session-behavior.md); it does **not** inherit that document's membership-specific field set or `eventDigest` grammar. Internal workload identity and method authorization follow [Authentication](../../system-architecture-authentication.md) and [gRPC](../../system-architecture-grpc.md#tls-requirements). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 3c25dae27c..f17aeb5cce 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -338,3 +338,23 @@ Entry format: - Outcome (2026-10-13): Parenthesizing the count CASE installs successfully in the existing five-case PostgreSQL migration suite, preserving the exact intended function delta, OID, prior checksums and V127 ordering guards. The next receiving-owner gate also passes the actual closure-profile SQL input and all seven rejection cases in both selected scenarios. Their authenticated World completion and exact retry pass; Account's outer settlement deadline remains separate and unresolved. - Further outcome (2026-10-13): Scoped typed-value reuse and single strict response decoding pass fresh Common Platform and Account unit proof, the existing authenticated two-owner PostgreSQL settlement case, and the actual empty-core selected scenario's Account settlement, exact retry and committed readbacks. That scenario advances to a separate Game Design descriptor-read deadline; the player-created scenario still times out at Account settlement. These partial results do not establish a universal timeout cause or recovery, and no timed-out owner commit outcome is inferred. + +## 2026-10-13 — Verify source roles during selective contract adoption + +A bounded helper initially reversed receiver and donor facts while reading a two-point diff, producing a false schema-drift report. Root checked the two exact named Git blobs, rejected those conclusions, and required a corrected map before adopting source. A pinned checkout and verified postimage hashes do not establish which side owns a dependency or guard; verify consequential role claims against explicit receiver and donor objects. Incidental broad temporary-directory searching also crossed a delegated read boundary; retain named inputs and the exact check allowlist during investigation. No incorrect schema change or review/CI mutation was applied. + +Qualification outcome (2026-10-13): Root native validation also catches missing test imports/mappers, an unnecessary checked-exception catch, a creation-race mock that confuses fresh and retained references, and fixtures that allocate before retaining the newly required owner evidence. Root corrects those test boundaries while preserving negative assertions and complete validation. A shared projection test copied from the donor uses a different package from this checkout's package-private test data; root places it in the existing canonical test package before compilation. Helper edit completion supplies no compilation or physical-proof credit; qualify the actual receiver classpath and execution order. + +## 2026-10-13 — Exact fences cannot rely on canonical JSON numbers beyond binary64 precision + +The original StartSession socket-mTLS positive fixture sends `Long.MAX_VALUE` as a reservation fence. Adding the independently returned full Account tuple exposes an existing representation defect in the [shared tuple encoder](../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java): it writes that fence as a JSON number, while strict decode requires an exact positive signed 64-bit integer. The installed JCS 1.1 canonicalizer maps `9223372036854775807` to `9223372036854776000`, and maps `9007199254740993` to `9007199254740992`; the latter also demonstrates identity aliasing. Creation of canonical bytes therefore does not prove exact typed round-trip binding. + +Preserve the large-fence positive proof and immutable historical bytes. Do not turn the fixture green by choosing a smaller fence, weakening strict decoding or introducing an undocumented numeric cap. Canonical representation and supported range require owner adjudication, followed by focused round-trip and transport proof; no new encoding, schema, migration or historical rewrite has been applied while that decision is pending. + +Outcome (2026-10-13): Overseer decision 1251 selects one tuple-version-1 spelling per reservation fence: JSON numbers through `9007199254740991`, exact decimal strings above that through `Long.MAX_VALUE`, safe numeric historical bytes preserved and high numeric history denied without reencoding or inferred pre-JCS values. Gameplay owns the shared correction in existing PR #3183; Document must adopt its exact published source. Authority and membership scalars retain their owner-defined representation and recursive exactness guards. The original socket-mTLS success proof now covers both `9007199254740993` and `Long.MAX_VALUE`; corrected source and fresh proof remain pending. + +Transport outcome (2026-10-13): The actual loopback mTLS probe receives `9007199254740992` for request fence `9007199254740993`; canonical byte comparisons alone had not exposed that typed-value loss. The independently expected decoded-fence assertion fails, while the `Long.MAX_VALUE` response is rejected. Six other transport cases pass. These are synthetic Account-handler transport results, not genuine issuance or runtime authority; the shared published correction and its receiving proof remain pending. + +Receiving correction outcome (2026-10-13): The exact published #3183 correction at `a66918116e44cd4d19777bff64f6528b87b3ecac` is selectively adopted into #3105. Fresh focused receiving proof passes both formerly failing wide-fence mTLS cases, all eight transport cases, ten shared tuple/projection cases and five native Game Session current-owner/replay PostgreSQL cases. Independent decoded-value assertions confirm the adjacent-wide and maximum decimal strings; no historical bytes, tuple version, authority-map shapes or SQL guards are changed. Broader receiving composition proof remains separate and pending. + +Physical owner extension (2026-10-13): All three Account PostgreSQL/mTLS cases pass: the original fence-one Logging claim read plus World acquisition and separate adjacent-wide/maximum Account capture, issuance, redemption and Game Session reservation/projection replay. Logging issue and Game Session redemption use production typed clients to the real Account gRPC owner. The physical Logging original reservation schema starts at fence one, so wide claim-reader inputs remain explicitly stipulated; no SQL trigger or mutation guard is bypassed. Creator, legal, signer and custody inputs remain test-only. These focused results do not qualify the complete selected composition or close genuine producer, terminal, placement or region-delivery handoffs. 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 ccbf2a2b9b..bea0243098 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +The original StartSession receiving construction locally carries the independently Account-returned full tuple through issue/recovery, Logging completion/handoff, Game Session redemption retention and the fresh native launch-allocation check. Current use rejects scalar-only Account projections; exact historical reads preserve retained legacy bytes without granting new authority. World historical participation lookup uses the complete original tuple and checks Account-returned coordinates against its retained identity. The exact published [PR #3183](https://github.com/benhook1013/FireMUD/pull/3183) correction at `a66918116e44cd4d19777bff64f6528b87b3ecac` is selectively adopted under Overseer decision 1251, preserving Root's combined pin/launch graph and migration history. Receiving focused proof passes ten shared-core cases, eight Logging mTLS cases and five native Game Session owner/replay PostgreSQL cases, with zero failures, errors or skips. Both adjacent-wide and maximum reservation fences retain their exact typed value and canonical decimal-string spelling; safe numeric and byte-preserved historical guards remain. The separate real Account mTLS/storage extension passes all three physical cases: adjacent-wide and maximum fences traverse the production Logging issue and Game Session redemption clients, real Account capture/issuance/redemption storage and Game Session projection retention/replay; the original fence-one case also uses the actual Logging claim reader and World acquisition owner. Broader receiving qualification passes the canonical full checks for Common Platform, Account, Logging, Game Session and World on this selective correction. Fresh originating reports contain 739 Common units; 1,402 Account units and eight selected PostgreSQL cases; 263 Logging units and all 24 PostgreSQL cases; 2,043 Game Session units, 12 selected PostgreSQL cases and 39 cross-service cases; and 691 World units plus all 230 PostgreSQL cases, all with zero failures, errors or skips. Game Design integration compilation, links and Markdown lint also pass; complete Account/Game Session integration suites and the selected Game Design composition are outside this passing aggregate. Logging's physical original reservation schema requires fence 1; wider claim-reader inputs in the Account proof remain explicitly stipulated and do not demonstrate a physical Logging allocator. Prior independent Account, Game Session and World gates qualify their exercised boundaries only. Both prior changed selected-export scenarios reach the unchanged five-second Game Design descriptor-read deadline after Account settlement/retry/readbacks, original ISSUE/REDEEM tuple receiving and initial association assertions; their whole composition remains failed, and the timeout cause remains unestablished. The newly adopted validated immutable-bundle caching will receive a fresh composition check. Donor proof and synthetic upstream fixture authority do not close any genuine owner handoff or runtime activation gate below. + The existing draft [PR #3105](https://github.com/benhook1013/FireMUD/pull/3105) remains on the approved parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`. Restored local Docker exposes and repairs a concrete Entity setup self-wait: the concurrent V4 index waited on Flyway's own transactional advisory-lock connection. The service startup, shadowing Spring test configuration and direct migration fixtures now select session-level advisory locking. Applied migration bytes, concurrent indexing and constraints remain unchanged. Entity receipt metadata compares PostgreSQL TIMESTAMPTZ values by instant, preserving immutable canonical receipt bytes and all identity/digest guards. The pre-V3 quarantine fixture seeds its retained numeric row using the historical schema before exercising the current writer after migration. The canonical Entity `check -PfullCheck` passes locally in 54 seconds, freshly executing all 17 PostgreSQL integration cases with zero failures, errors or skips. That includes both Spring startup cases, the complete 23-family EMPTY retention/readback/retry and constraint/rollback/snapshot negatives, UTC retention followed by Pacific/Auckland read/replay, and retained-row quarantine. Its 215 passing units are reused from the preceding fresh unit execution. This is owner-local physical proof of the correction, not protected Account-to-Entity producer, placement or operational-region proof. Earlier failed compilation left stale integration XML; those reports are not fresh results of that failed invocation. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 41ca797414..76b1cec46f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The original StartSession receiving construction selectively adopts the published [PR #3183](https://github.com/benhook1013/FireMUD/pull/3183) correction at `a66918116e44cd4d19777bff64f6528b87b3ecac` into the existing [PR #3105](https://github.com/benhook1013/FireMUD/pull/3105) composition. Its exact reservation-fence representation is owned by [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); safe original numeric bytes remain unchanged, while wide values use exact decimal strings and unsafe numeric history fails closed. Focused receiving proof passes the shared tuple/projection cases, maximum and adjacent-wide Logging mTLS value assertions and the existing combined Game Session owner reservation/replay PostgreSQL boundary. Real Account storage/transport composition also passes its original physical Logging-claim/World-acquisition case and two wide-fence Account/Game Session retention cases; the wide claim reader remains explicitly stipulated. The canonical broader receiving checks pass for Common Platform, Account, Logging, Game Session and World, with the selected Account/Game Session PostgreSQL scopes recorded in the authoring tracker. This passing aggregate excludes the selected Game Design composition and the complete Account/Game Session integration suites. Donor proof does not qualify this receiving composition. Genuine owner/region handoffs and runtime activation remain open in the [authoring tracker](game-authoring-publishing-and-activation.md#current-status). + The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. Earlier Account checkpoints `d619948920469228814d8d2ef60f9dac8672e7ea` and `f086de2896f885e33745d1482872ec2ae1c480c2` have reported green required CI, including full-stack Smoke. Reported local validation passed 535 Account unit tests, integration-test source compilation, and documentation checks; local physical PostgreSQL validation was not run. The newer reconciled head `5deaf573be3774b4eb8285ff857907f03b2ba5e0` and subsequent retained-source denial correction do not inherit an exact-head green claim. The correction passed 249 focused Account unit tests, integration-test source compilation, and documentation checks; exact-head required CI and physical PostgreSQL proof remain pending. diff --git a/protos/account/v1/start_session_operator_authorization.proto b/protos/account/v1/start_session_operator_authorization.proto index 7f781d5515..e3271740b4 100644 --- a/protos/account/v1/start_session_operator_authorization.proto +++ b/protos/account/v1/start_session_operator_authorization.proto @@ -60,6 +60,8 @@ message IssueHumanOperatorAuthorizationReferenceResponse { AuthorityEvidenceBundleReference bundle_reference = 5; // Exact Logging/Admin SPIFFE identity verified from the authenticated request TLS peer. string authenticated_logging_workload_identity = 6; + // Account-derived canonical original postAuthorizationExecutionTuple/v1 bytes. + bytes original_account_post_authorization_tuple = 7; } message RecoverOperatorAuthorizationReferenceResponse { @@ -70,6 +72,8 @@ message RecoverOperatorAuthorizationReferenceResponse { AuthorityEvidenceBundleReference bundle_reference = 5; // Exact Logging/Admin SPIFFE identity verified from the authenticated request TLS peer. string authenticated_logging_workload_identity = 6; + // Exact original tuple re-derived from Account's retained issuance record and capture. + bytes original_account_post_authorization_tuple = 7; } message RedeemOperatorAuthorizationResponse { @@ -78,6 +82,8 @@ message RedeemOperatorAuthorizationResponse { string issuance_operation_id = 3; uint64 issuance_fence = 4; bool replay = 5; + // Exact original tuple re-derived from Account's durable issuance record. + bytes original_account_post_authorization_tuple = 6; } // Read-only projection of the exact original operation after its owner redemption. diff --git a/protos/account/v1/start_session_world_participation_read.proto b/protos/account/v1/start_session_world_participation_read.proto index 0260e1508c..9af63d3dc6 100644 --- a/protos/account/v1/start_session_world_participation_read.proto +++ b/protos/account/v1/start_session_world_participation_read.proto @@ -4,8 +4,9 @@ package account.v1; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; -// Standalone and unregistered. This exact historical read neither admits execution nor renews -// Account authority; World must separately authenticate its original Game Session operation. +// Standalone and unregistered. This exact historical read resolves retained participation +// coordinates from the unchanged original tuple; it neither admits execution nor renews Account +// authority. World must separately authenticate its original Game Session operation. service AccountStartSessionWorldParticipationHistoricalReadService { rpc ReadHistoricalStartSessionWorldParticipation( ReadHistoricalStartSessionWorldParticipationRequest) @@ -16,17 +17,19 @@ message ReadHistoricalStartSessionWorldParticipationRequest { int32 schema_version = 1; string read_request_id = 2; string target_namespace = 3; - string account_world_participation_id = 4; - int64 account_world_participation_fence = 5; + reserved 4, 5; + bytes original_post_authorization_tuple = 6; } message ReadHistoricalStartSessionWorldParticipationResponse { ReadHistoricalStartSessionWorldParticipationRequest request = 1; - bytes original_post_authorization_tuple = 2; + reserved 2; string game_session_owner_attempt_id = 3; int64 game_session_owner_fence = 4; string canonical_game_instance_id = 5; // Byte-for-byte retained World preparation JSON, not fresh admission or currentness evidence. string preparation_input_json = 6; string preparation_input_digest = 7; + string account_world_participation_id = 8; + int64 account_world_participation_fence = 9; } diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 871e9347e8..f3d59eb160 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -19,6 +19,7 @@ configurations.named("testFixturesImplementation") { } dependencies { + testImplementation(testFixtures(project(":common-platform-core"))) testFixturesImplementation(platform(libs.spring.boot.dependencies)) testFixturesImplementation(project(":common-platform-core")) testFixturesImplementation(project(":common-security")) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java index bfddea2232..0918039bf2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java @@ -220,7 +220,6 @@ private void validateResponse( || response.getClaimFence() != currentClaimFence || response.getPurpose() != toWirePurpose(purpose) || response.getObservedAtEpochMillis() <= 0L - || response.getObservedAtEpochMillis() > localNowEpochMillis || response.getClaimExpiresAtEpochMillis() <= response.getObservedAtEpochMillis() || response.getClaimExpiresAtEpochMillis() <= localNowEpochMillis) { throw new IllegalStateException( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java index 66cdfcceec..9d04d6e75a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java @@ -11,19 +11,17 @@ import java.util.Arrays; import java.util.Comparator; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptResponse; import org.jooq.DSLContext; @@ -32,7 +30,6 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; -import tools.jackson.databind.json.JsonMapper; /** * Immutable storage for the exact observation of the original live Game Session StartSession @@ -69,7 +66,6 @@ public class AccountStartSessionWorldOriginalAttemptEvidenceRepository { "original_response_digest"); private static final Set SOURCE_COLUMNS = Set.of("participation_id", "source_key", "source_evidence"); - private static final JsonMapper JSON = JsonMapper.builder().build(); private final DSLContext dsl; @@ -146,6 +142,12 @@ public Optional findCurrentExact( if (row == null) return Optional.empty(); StoredEvidence stored = decodeStoredEvidence(row, locked); requireSameSemanticRequest(expectedRequest, stored.result().request()); + try { + StartSessionAccountRedemptionProjection.requireCurrentBinding( + stored.result().accountRedemptionProjection(), expectedRequest.originalTuple()); + } catch (IllegalArgumentException missingOwnerEvidence) { + throw unavailable(); + } requireLeaseCurrent(stored.originalLeaseExpiresAt()); return Optional.of(stored); } @@ -353,7 +355,8 @@ private static Result decodeResponseFromStoredBytes( Request echoedRequest = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest(response.getRequest()); Result result = - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse(echoedRequest, response); + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRetainedHistoricalResponse( + echoedRequest, response); if (!Arrays.equals( OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(result).toByteArray(), responseBytes)) { @@ -416,28 +419,9 @@ static void requireSameSemanticRequest(Request expected, Request actual) { private static boolean accountProjectionMatches( StartSessionPostAuthorizationExecutionTuple tuple, byte[] projectionBytes) { try { - StartSessionAuthorityEvidenceBundle bundle = - StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); - long issuanceFence = Long.parseLong(tuple.issuanceFence()); - if (issuanceFence <= 0L) return false; - byte[] expected = - Rfc8785CanonicalJson.canonicalizeUtf8( - JSON.writeValueAsString( - Map.of( - "projectionSchemaId", - "accountStartSessionRedemptionProjection", - "projectionSchemaVersion", - "1", - "authorizationReferenceFingerprint", - tuple.authorizationReferenceFingerprint(), - "authorityEvidenceBundle", - bundle.jsonValue(), - "issuanceOperationId", - bundle.issuanceOperationId().toString(), - "issuanceFence", - issuanceFence))); - return Arrays.equals(expected, projectionBytes); - } catch (IOException | RuntimeException malformed) { + StartSessionAccountRedemptionProjection.requireHistoricalBinding(projectionBytes, tuple); + return true; + } catch (RuntimeException malformed) { return false; } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java index 416a7328d8..80d36090a8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java @@ -25,7 +25,6 @@ import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; -import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorityBundle.BundleReference; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.AuthorizationResponse; @@ -33,7 +32,10 @@ import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RecoverRequest; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemRequest; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedemptionResult; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.security.SessionContext; import org.jooq.exception.DataAccessException; @@ -56,6 +58,8 @@ public final class StartSessionOperatorAuthorizationGrpcService private static final int MAX_CONTROL_UI_JWT_BYTES = 16 * 1024; private static final int MAX_AUTHORIZATION_REFERENCE_BYTES = 128; private static final int MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES = 128 * 1024; + private static final int MAX_POST_AUTHORIZATION_TUPLE_BYTES = + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES; private static final int MAX_FINGERPRINT_BYTES = 137; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final String AUTHORIZATION_REFERENCE = "[A-Za-z0-9_-]{43}"; @@ -379,7 +383,7 @@ private static void rejectUnknownFields(boolean requestHasNoUnknownFields) { private static IssueHumanOperatorAuthorizationReferenceResponse toIssueResponse( AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) { - requireResponse(response); + requireResponse(response, authenticatedLoggingWorkloadIdentity); return IssueHumanOperatorAuthorizationReferenceResponse.newBuilder() .setOperatorAuthorizationReference(response.operatorAuthorizationReference()) .setAuthorizationReferenceFingerprint(response.authorizationReferenceFingerprint()) @@ -387,12 +391,14 @@ private static IssueHumanOperatorAuthorizationReferenceResponse toIssueResponse( .setAuthorityEvidenceBundle(ByteString.copyFrom(response.authorityEvidenceBundle())) .setBundleReference(toWireBundleReference(response.bundleReference())) .setAuthenticatedLoggingWorkloadIdentity(authenticatedLoggingWorkloadIdentity) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom(response.originalAccountPostAuthorizationTuple())) .build(); } private static RecoverOperatorAuthorizationReferenceResponse toRecoverResponse( AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) { - requireResponse(response); + requireResponse(response, authenticatedLoggingWorkloadIdentity); return RecoverOperatorAuthorizationReferenceResponse.newBuilder() .setOperatorAuthorizationReference(response.operatorAuthorizationReference()) .setAuthorizationReferenceFingerprint(response.authorizationReferenceFingerprint()) @@ -400,10 +406,13 @@ private static RecoverOperatorAuthorizationReferenceResponse toRecoverResponse( .setAuthorityEvidenceBundle(ByteString.copyFrom(response.authorityEvidenceBundle())) .setBundleReference(toWireBundleReference(response.bundleReference())) .setAuthenticatedLoggingWorkloadIdentity(authenticatedLoggingWorkloadIdentity) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom(response.originalAccountPostAuthorizationTuple())) .build(); } - private static void requireResponse(AuthorizationResponse response) { + private static void requireResponse( + AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) { if (response == null || response.operatorAuthorizationReference() == null || response.operatorAuthorizationReference().getBytes(StandardCharsets.UTF_8).length @@ -420,10 +429,35 @@ private static void requireResponse(AuthorizationResponse response) { || response.authorityEvidenceBundle() == null || response.authorityEvidenceBundle().length == 0 || response.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES - || response.bundleReference() == null) { + || response.bundleReference() == null + || response.originalAccountPostAuthorizationTuple() == null + || response.originalAccountPostAuthorizationTuple().length == 0 + || response.originalAccountPostAuthorizationTuple().length + > MAX_POST_AUTHORIZATION_TUPLE_BYTES) { throw new IllegalStateException( "Account produced an invalid StartSession authorization result"); } + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + response.originalAccountPostAuthorizationTuple()); + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(response.authorityEvidenceBundle()); + bundle.requireTupleBinding(tuple.preAuthorizationTuple()); + bundle.requireReferenceBinding(tuple.bundleReference()); + var tupleReference = tuple.bundleReference(); + BundleReference responseReference = response.bundleReference(); + if (!tuple + .authorizationReferenceFingerprint() + .equals(response.authorizationReferenceFingerprint()) + || !Arrays.equals(tuple.authorityEvidenceBundleBytes(), bundle.canonicalBytes()) + || !tupleReference.bundleVersion().equals(responseReference.bundleVersion()) + || !tupleReference.sourceVersion().equals(responseReference.sourceVersion()) + || !tupleReference.sourceFence().equals(responseReference.sourceFence()) + || !tupleReference.linearization().equals(responseReference.linearization()) + || !tuple.authenticatedWorkloadIdentity().equals(authenticatedLoggingWorkloadIdentity)) { + throw new IllegalStateException( + "Account authorization result differs from its original owner tuple"); + } } private static AuthorityEvidenceBundleReference toWireBundleReference(BundleReference reference) { @@ -449,15 +483,34 @@ private static RedeemOperatorAuthorizationResponse toRedeemResponse(RedemptionRe || result.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES || result.issuanceOperationId() == null || NIL_UUID.equals(result.issuanceOperationId()) - || result.issuanceFence() <= 0L) { + || result.issuanceFence() <= 0L + || result.originalAccountPostAuthorizationTuple() == null + || result.originalAccountPostAuthorizationTuple().length == 0 + || result.originalAccountPostAuthorizationTuple().length + > MAX_POST_AUTHORIZATION_TUPLE_BYTES) { throw new IllegalStateException("Account produced an invalid StartSession redemption result"); } + StartSessionPostAuthorizationExecutionTuple tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + result.originalAccountPostAuthorizationTuple()); + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(result.authorityEvidenceBundle()); + if (!tuple + .authorizationReferenceFingerprint() + .equals(result.authorizationReferenceFingerprint()) + || !Arrays.equals(tuple.authorityEvidenceBundleBytes(), bundle.canonicalBytes()) + || !Long.toString(result.issuanceFence()).equals(bundle.issuanceFence()) + || !result.issuanceOperationId().equals(bundle.issuanceOperationId())) { + throw new IllegalStateException("Account redemption differs from its original owner tuple"); + } return RedeemOperatorAuthorizationResponse.newBuilder() .setAuthorizationReferenceFingerprint(result.authorizationReferenceFingerprint()) .setAuthorityEvidenceBundle(ByteString.copyFrom(result.authorityEvidenceBundle())) .setIssuanceOperationId(result.issuanceOperationId().toString()) .setIssuanceFence(result.issuanceFence()) .setReplay(result.replay()) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom(result.originalAccountPostAuthorizationTuple())) .build(); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java index f651d5b0ad..b43f953507 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java @@ -24,7 +24,6 @@ import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceRecord; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; -import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.Status; import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService.Current; import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.Stored; @@ -314,7 +313,9 @@ public AuthorizationResponse issue(IssueRequest request) { requireFreshClaimEvidence(claim); return new IssueOutcome(created.created(), created.issuance()); }); - if (outcome.created()) return candidate.response(); + if (outcome.created()) { + return authorizationResponse(candidate.response(), outcome.issuance()); + } AuthorizationResponse originalResponse = openOriginalResponse(tuple, outcome.issuance()); var winnerEnvironment = hostedTerms.captureCurrentEnvironmentBoundary(); @@ -551,7 +552,10 @@ public RedemptionResult redeem(RedeemRequest request) { request.canonicalTupleBytes(), request.reservationOwnerId(), request.reservationClaimFence()); - if (sameAttemptReplay && originalResponse.isEmpty()) { + Instant currentInstant = clock.instant(); + if (sameAttemptReplay + && (originalResponse.isEmpty() + || !currentInstant.isBefore(observed.referenceExpiresAt()))) { bundle.requireCurrentSnapshotForExactReplay( current.source(), current.stored(), @@ -565,26 +569,36 @@ public RedemptionResult redeem(RedeemRequest request) { tuple, AccountStartSessionOperatorAuthorityBundle.fromSharedReference( observed.bundleReference()), - clock.instant()); + currentInstant); } - RedemptionResult result = - repository.redeemExact( - new RedemptionRequest( - tuple.controlPlaneRequestId(), - request.canonicalTupleBytes(), - observed.authorizationReferenceFingerprint(), - observed.reservationOwnerId(), - observed.reservationClaimFence(), - gameSessionPeerUri, - request.ownerAttemptId(), - request.ownerFence(), - observed.authorityEvidenceBundle(), - Instant.ofEpochMilli(clock.millis()))); + net.firedevops.firemud.accountservice.repository + .AccountStartSessionOperatorAuthorizationRepository.RedemptionResult + result = + repository.redeemExact( + new RedemptionRequest( + tuple.controlPlaneRequestId(), + request.canonicalTupleBytes(), + observed.authorizationReferenceFingerprint(), + observed.reservationOwnerId(), + observed.reservationClaimFence(), + gameSessionPeerUri, + request.ownerAttemptId(), + request.ownerFence(), + observed.authorityEvidenceBundle(), + currentInstant)); requireRedemptionProjection(result, observed); if (sameAttemptReplay != result.replay()) { throw denied("Account returned a changed one-time redemption outcome"); } - return result; + StartSessionPostAuthorizationExecutionTuple originalTuple = + postAuthorizationTuple(exact); + return new RedemptionResult( + result.authorizationReferenceFingerprint(), + result.authorityEvidenceBundle(), + result.issuanceOperationId(), + result.issuanceFence(), + result.replay(), + originalTuple.canonicalBytes()); }); } finally { Arrays.fill(referenceBytes, (byte) 0); @@ -861,8 +875,8 @@ private PreparedIssuance prepareIssuance( try { String fingerprint = fingerprintKeys.fingerprintForIssue(ReferenceKind.HUMAN_OPERATOR, referenceBytes); - AuthorizationResponse response = - new AuthorizationResponse( + StoredAuthorizationResponse response = + new StoredAuthorizationResponse( authorizationReference, fingerprint, referenceExpiresAt, @@ -922,9 +936,8 @@ private AuthorizationResponse openOriginalResponse( record.issuanceFence(), bundle), record.responseEnvelopeExpiresAt()); - AuthorizationResponse response = decodeResponse(plaintext); - requireResponseMatchesRecord(response, record); - return response; + StoredAuthorizationResponse response = decodeResponse(plaintext); + return authorizationResponse(response, record); } finally { if (plaintext != null) Arrays.fill(plaintext, (byte) 0); } @@ -950,9 +963,8 @@ private Optional tryOpenOriginalResponse( record.issuanceFence(), bundle), record.responseEnvelopeExpiresAt()); - AuthorizationResponse response = decodeResponse(plaintext); - requireResponseMatchesRecord(response, record); - return Optional.of(response); + StoredAuthorizationResponse response = decodeResponse(plaintext); + return Optional.of(authorizationResponse(response, record)); } catch (AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException expired) { return Optional.empty(); } finally { @@ -982,7 +994,7 @@ private Binding responseBinding( bundle.canonicalBytes()); } - private static byte[] encodeResponse(AuthorizationResponse response) { + private static byte[] encodeResponse(StoredAuthorizationResponse response) { return AccountControlUiAuthority.canonical( Map.of( "operatorAuthorizationReference", response.operatorAuthorizationReference(), @@ -995,7 +1007,7 @@ private static byte[] encodeResponse(AuthorizationResponse response) { "bundleReference", response.bundleReference().asJsonValue())); } - private static AuthorizationResponse decodeResponse(byte[] exactBytes) { + private static StoredAuthorizationResponse decodeResponse(byte[] exactBytes) { try { String json = new String(exactBytes, StandardCharsets.UTF_8); Map root = JSON.readValue(json, new TypeReference<>() {}); @@ -1012,12 +1024,12 @@ private static AuthorizationResponse decodeResponse(byte[] exactBytes) { root.get("bundleReference")); byte[] canonical = encodeResponse( - new AuthorizationResponse( + new StoredAuthorizationResponse( reference, fingerprint, expiresAt, bundleBytes, sourceReference)); if (!MessageDigest.isEqual(canonical, exactBytes)) { throw denied("Original response envelope is not canonical"); } - return new AuthorizationResponse( + return new StoredAuthorizationResponse( reference, fingerprint, expiresAt, bundleBytes, sourceReference); } catch (IllegalStateException failure) { throw failure; @@ -1026,7 +1038,8 @@ private static AuthorizationResponse decodeResponse(byte[] exactBytes) { } } - private void requireResponseMatchesRecord(AuthorizationResponse response, IssuanceRecord record) { + private void requireResponseMatchesRecord( + StoredAuthorizationResponse response, IssuanceRecord record) { var bundle = AccountStartSessionOperatorAuthorityBundle.decode(record.authorityEvidenceBundle()); if (!response @@ -1060,6 +1073,43 @@ private void requireResponseMatchesRecord(AuthorizationResponse response, Issuan } } + private AuthorizationResponse authorizationResponse( + StoredAuthorizationResponse response, IssuanceRecord record) { + requireResponseMatchesRecord(response, record); + return new AuthorizationResponse( + response.operatorAuthorizationReference(), + response.authorizationReferenceFingerprint(), + response.expiresAt(), + response.authorityEvidenceBundle(), + response.bundleReference(), + postAuthorizationTuple(record).canonicalBytes()); + } + + /** Builds the complete public owner tuple only from Account's immutable original record. */ + private static StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple( + IssuanceRecord record) { + Objects.requireNonNull(record, "retained Account issuance record is required"); + StartSessionPreAuthorizationReservationTuple tuple = + decodeTuple(record.preAuthorizationTuple()); + AccountStartSessionOperatorAuthorityBundle bundle = + AccountStartSessionOperatorAuthorityBundle.decode(record.authorityEvidenceBundle()); + var reference = record.bundleReference(); + bundle.requireTupleBinding(tuple); + if (!tuple.controlPlaneRequestId().equals(record.controlPlaneRequestId()) + || !tuple.mutationDigest().equals(record.mutationDigest()) + || bundle.issuanceFence() != record.issuanceFence()) { + throw denied("Retained Account issuance binding is inconsistent"); + } + return StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + record.issuanceWorkloadUri(), + record.authorizationReferenceFingerprint(), + record.reservationOwnerId(), + record.reservationClaimFence(), + record.authorityEvidenceBundle(), + reference); + } + private static void requireSameCurrent(Current expected, Current observed) { if (!sameCurrentSource(expected.source(), observed.source()) || !sameControlUiIssuance(expected.stored(), observed.stored())) { @@ -1135,7 +1185,10 @@ private static String bundleSourceVersion(AccountStartSessionOperatorAuthorityBu } private static void requireRedemptionProjection( - RedemptionResult result, IssuanceRecord issuance) { + net.firedevops.firemud.accountservice.repository + .AccountStartSessionOperatorAuthorizationRepository.RedemptionResult + result, + IssuanceRecord issuance) { if (!issuance .authorizationReferenceFingerprint() .equals(result.authorizationReferenceFingerprint()) @@ -1178,7 +1231,7 @@ private void requireFreshClaimEvidence(ReadCurrentClaimEvidenceResponse evidence long observedAt = evidence.getObservedAtEpochMillis(); long expiresAt = evidence.getClaimExpiresAtEpochMillis(); long now = clock.millis(); - if (observedAt <= 0L || expiresAt <= observedAt || now < observedAt || now >= expiresAt) { + if (observedAt <= 0L || expiresAt <= observedAt || now >= expiresAt) { throw denied("Logging/Admin StartSession claim evidence is stale or contradictory"); } } @@ -1439,7 +1492,7 @@ private record IssuePreparation( private record PreparedIssuance( AccountStartSessionOperatorAuthorityBundle bundle, - AuthorizationResponse response, + StoredAuthorizationResponse response, IssuanceCandidate candidate) { private PreparedIssuance { Objects.requireNonNull(bundle, "authority bundle is required"); @@ -1588,13 +1641,16 @@ public record AuthorizationResponse( String authorizationReferenceFingerprint, Instant expiresAt, byte[] authorityEvidenceBundle, - AccountStartSessionOperatorAuthorityBundle.BundleReference bundleReference) { + AccountStartSessionOperatorAuthorityBundle.BundleReference bundleReference, + byte[] originalAccountPostAuthorizationTuple) { public AuthorizationResponse { requireReference(operatorAuthorizationReference); requireFingerprint(authorizationReferenceFingerprint); Objects.requireNonNull(expiresAt, "reference expiry is required"); authorityEvidenceBundle = copy(authorityEvidenceBundle); Objects.requireNonNull(bundleReference, "source bundle reference is required"); + originalAccountPostAuthorizationTuple = copy(originalAccountPostAuthorizationTuple); + StartSessionPostAuthorizationExecutionTuple.decode(originalAccountPostAuthorizationTuple); } @Override @@ -1602,12 +1658,72 @@ public byte[] authorityEvidenceBundle() { return copy(authorityEvidenceBundle); } + @Override + public byte[] originalAccountPostAuthorizationTuple() { + return copy(originalAccountPostAuthorizationTuple); + } + @Override public String toString() { return "AuthorizationResponse[reference, bundle, and fingerprint redacted]"; } } + /** Private five-field plaintext used only inside the unchanged encrypted recovery envelope. */ + private record StoredAuthorizationResponse( + String operatorAuthorizationReference, + String authorizationReferenceFingerprint, + Instant expiresAt, + byte[] authorityEvidenceBundle, + AccountStartSessionOperatorAuthorityBundle.BundleReference bundleReference) { + private StoredAuthorizationResponse { + requireReference(operatorAuthorizationReference); + requireFingerprint(authorizationReferenceFingerprint); + Objects.requireNonNull(expiresAt, "reference expiry is required"); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + Objects.requireNonNull(bundleReference, "source bundle reference is required"); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + } + + /** Public redemption result with the independently reconstructed original Account tuple. */ + public record RedemptionResult( + String authorizationReferenceFingerprint, + byte[] authorityEvidenceBundle, + UUID issuanceOperationId, + long issuanceFence, + boolean replay, + byte[] originalAccountPostAuthorizationTuple) { + public RedemptionResult { + authorityEvidenceBundle = copy(authorityEvidenceBundle); + originalAccountPostAuthorizationTuple = copy(originalAccountPostAuthorizationTuple); + StartSessionPostAuthorizationExecutionTuple.decode(originalAccountPostAuthorizationTuple); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public byte[] originalAccountPostAuthorizationTuple() { + return copy(originalAccountPostAuthorizationTuple); + } + + @Override + public String toString() { + return "RedemptionResult[issuanceOperationId=" + + issuanceOperationId + + ", replay=" + + replay + + ", authority and tuple redacted]"; + } + } + public static final class NotFoundException extends RuntimeException { public NotFoundException() { super("No original StartSession operator authorization exists"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcService.java index 1586df3f5b..6076e92065 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcService.java @@ -11,7 +11,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; -/** Standalone unregistered same-namespace Account historical participation receiver. */ +/** Standalone unregistered same-namespace Account historical tuple-to-participation receiver. */ public final class AccountStartSessionWorldParticipationHistoricalReadGrpcService extends AccountStartSessionWorldParticipationHistoricalReadServiceGrpc .AccountStartSessionWorldParticipationHistoricalReadServiceImplBase { @@ -27,6 +27,7 @@ public AccountStartSessionWorldParticipationHistoricalReadGrpcService( this.workloadNamespace = workloadNamespace; } + /** Resolves retained coordinates only after authenticating World without end-user context. */ @Override public void readHistoricalStartSessionWorldParticipation( ReadHistoricalStartSessionWorldParticipationRequest request, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java index 330757f791..231b98da08 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java @@ -40,7 +40,7 @@ public AccountStartSessionWorldParticipationHistoricalReadService( } /** - * Reads the exact retained row by its independent participation ID and fence, including after + * Resolves the exact retained participation from its complete original tuple, including after * original ingress expiry or prior immutable terminal settlement. */ public AccountStartSessionWorldParticipationHistoricalReadEvidence read( @@ -60,9 +60,7 @@ public AccountStartSessionWorldParticipationHistoricalReadEvidence read( ownerTransaction.execute( ignored -> repository - .findHistoricalExact( - request.accountWorldParticipationId(), - request.accountWorldParticipationFence()) + .findHistoricalForOriginalTuple(request.originalPostAuthorizationTuple()) .orElseThrow( () -> Status.FAILED_PRECONDITION @@ -71,17 +69,24 @@ public AccountStartSessionWorldParticipationHistoricalReadEvidence read( .asRuntimeException())), "Account historical participation transaction returned no result"); - if (!participation.participationId().equals(request.accountWorldParticipationId()) - || participation.participationFence() != request.accountWorldParticipationFence() + if (!java.security.MessageDigest.isEqual( + participation.originalPostAuthorizationTuple(), + request.originalPostAuthorizationTuple()) + || !request + .decodedOriginalTuple() + .controlPlaneRequestId() + .equals(participation.controlPlaneRequestId()) || !workloadNamespace.equals(participation.targetNamespace())) { throw Status.FAILED_PRECONDITION - .withDescription("Stored World participation differs from the exact historical lookup") + .withDescription( + "Stored World participation differs from the complete original tuple lookup") .asRuntimeException(); } try { return new AccountStartSessionWorldParticipationHistoricalReadEvidence( request, - participation.originalPostAuthorizationTuple(), + participation.participationId(), + participation.participationFence(), participation.gameSessionOwnerAttemptId(), participation.gameSessionOwnerFence(), participation.canonicalGameInstanceId(), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java index c5f2906af8..3797f6e313 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java @@ -559,22 +559,7 @@ private static Request request(Fixture fixture, UUID readId) { } private static byte[] accountProjection(StartSessionPostAuthorizationExecutionTuple tuple) { - StartSessionAuthorityEvidenceBundle bundle = - StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); - return AccountControlUiAuthority.canonical( - Map.of( - "projectionSchemaId", - "accountStartSessionRedemptionProjection", - "projectionSchemaVersion", - "1", - "authorizationReferenceFingerprint", - tuple.authorizationReferenceFingerprint(), - "authorityEvidenceBundle", - bundle.jsonValue(), - "issuanceOperationId", - bundle.issuanceOperationId().toString(), - "issuanceFence", - 9L)); + return tuple.canonicalBytes(); } private static Instant databaseNow(DSLContext dsl) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java index 03bd1dd994..a1600c09e8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionWorldAcquisitionPostgresIntegrationTest.java @@ -38,6 +38,8 @@ import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldOriginalAttemptEvidenceRepository.StoredEvidence; import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; +import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.IssuedAuthorization; +import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OriginalStartSessionAuthorizationTransport; import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerAttemptLifecycle; import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerClaim; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationAcquisitionService.AcquisitionRequest; @@ -49,6 +51,7 @@ import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; @@ -86,6 +89,8 @@ import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -100,9 +105,10 @@ /** * Physical Logging claim-read, Account issuer, and World acquisition proof. The Logging mutation - * capability is provided only by its run-owned-PostgreSQL test fixture, and the Account issuer and - * World caller remain in-process test seams; this point-in-time read does not prove continuous - * cross-service protection of later Account or Game Session commits. + * capability is provided only by its run-owned-PostgreSQL test fixture. Production Logging issue + * and Game Session redemption clients call the real Account issuer over mutual TLS. Creator, legal, + * signer, and custody inputs remain test-only; the World caller remains in-process. This + * point-in-time read does not prove continuous protection of later commits. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -218,420 +224,439 @@ void realOriginalIssueRedemptionAndAcquisitionRetainImmutableObservationAndSourc AtomicReference gameSessionOwnerClaim = new AtomicReference<>(); AtomicReference reservedTupleBytes = new AtomicReference<>(); - var action = - new StartSessionOperatorAction( - StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, - StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(tenantId, NAMESPACE), - new StartSessionOperatorAction.Target(GAME_TEMPLATE_ID, accountId), - StartSessionOperatorAction.ExpectedVersion.ABSENT, - new StartSessionOperatorAction.Mutation( - StartSessionOperatorAction.ClientIp.absent()), - "real Account original World acquisition integration proof"); - StartSessionPreAuthorizationReservationTuple loggingTuple; - SessionContext.setContext( - accountId.toString(), - List.of(), - Map.of(tenantId.toString(), List.of("tenantAdmin")), - false, - null, - null); - try { - loggingTuple = - StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( - controlPlaneRequestId, action); - } finally { - SessionContext.clear(); + try (var transport = + new AccountAuthorizationTransport(pki, proof, reservedGameSessionClaim)) { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, NAMESPACE), + new StartSessionOperatorAction.Target(GAME_TEMPLATE_ID, accountId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "real Account original World acquisition integration proof"); + StartSessionPreAuthorizationReservationTuple loggingTuple; + SessionContext.setContext( + accountId.toString(), + List.of(), + Map.of(tenantId.toString(), List.of("tenantAdmin")), + false, + null, + null); + try { + loggingTuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + controlPlaneRequestId, action); + } finally { + SessionContext.clear(); + } + var commonTuple = + net.firedevops.firemud.common.operator + .StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + loggingTuple.canonicalJson()); + assertThat(loggingTuple.isAuthorityDerived()).isTrue(); + assertThat(loggingTuple.actor().accountId()).isEqualTo(accountId); + + var defaultRepository = + new StartSessionPreAuthorizationReservationRepository(loggingStore.dsl()); + var defaultService = + new StartSessionPreAuthorizationReservationService(defaultRepository); + assertThatThrownBy(() -> defaultService.acquire(loggingTuple)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("mutations are disabled for production construction"); + assertThatThrownBy( + () -> + defaultRepository.acquire( + loggingTuple, + UUID.randomUUID(), + System.currentTimeMillis(), + System.currentTimeMillis() + + StartSessionPreAuthorizationReservationService.CLAIM_TTL + .toMillis())) + .isInstanceOf(UnsupportedOperationException.class); + + var acquired = loggingStore.service().acquire(loggingTuple); + assertThat(acquired.newlyAcquired()).isTrue(); + assertThat(acquired.claim()).isNotNull(); + assertThat(acquired.snapshot().state()).isEqualTo(State.RESERVED); + assertThat(acquired.snapshot().phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + ClaimEvidence claim = acquired.claim().claimEvidence(); + assertThat(claim.reservationOwnerId()).isEqualTo(claim.currentClaimOwnerId()); + assertThat(claim.reservationClaimFence()).isEqualTo(1L); + assertThat(claim.currentClaimFence()).isEqualTo(1L); + + var duplicateAcquire = loggingStore.service().acquire(loggingTuple); + assertThat(duplicateAcquire.newlyAcquired()).isFalse(); + assertThat(duplicateAcquire.claim()).isNull(); + assertThat(duplicateAcquire.snapshot()).isEqualTo(acquired.snapshot()); + assertThat(loggingReadRequests).isEmpty(); + + var pending = loggingStore.service().markAuthorizationPending(acquired.claim()); + assertThat(pending.mayDispatchAccountAuthorization()).isTrue(); + assertThat(pending.snapshot().phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(pending.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(pending.snapshot().claimState()).isEqualTo(ClaimState.ACTIVE); + assertThat(pending.snapshot().claimPurpose()).isEqualTo(ClaimPurpose.ORIGINAL); + assertThat(pending.snapshot().reservationClaimFence()) + .isEqualTo(claim.reservationClaimFence()); + assertThat(pending.snapshot().claimFence()).isEqualTo(claim.currentClaimFence()); + assertThat(pending.snapshot().claimExpiresAtEpochMillis()) + .isGreaterThan(System.currentTimeMillis()); + Record pendingRow = loggingStore.reservationRow(controlPlaneRequestId); + assertThat(pendingRow.get("pre_authorization_tuple_json", String.class)) + .isEqualTo(loggingTuple.canonicalJson()); + assertThat(pendingRow.get("mutation_digest", String.class)) + .isEqualTo(loggingTuple.mutationDigest()); + assertThat(pendingRow.get("phase", String.class)).isEqualTo("ACCOUNT_AUTHORIZATION"); + assertThat(pendingRow.get("state", String.class)).isEqualTo("AUTHORIZATION_PENDING"); + assertThat(pendingRow.get("reservation_owner_id", UUID.class)) + .isEqualTo(claim.reservationOwnerId()); + assertThat(pendingRow.get("reservation_claim_fence", Long.class)) + .isEqualTo(claim.reservationClaimFence()); + assertThat(pendingRow.get("claim_owner_id", UUID.class)) + .isEqualTo(claim.currentClaimOwnerId()); + assertThat(pendingRow.get("claim_fence", Long.class)) + .isEqualTo(claim.currentClaimFence()); + assertThat(pendingRow.get("claim_state", String.class)).isEqualTo("ACTIVE"); + assertThat(pendingRow.get("claim_purpose", String.class)).isEqualTo("ORIGINAL"); + assertThat( + pendingRow.get("claim_expires_at_epoch_ms", Long.class) + - pendingRow.get("created_at_epoch_ms", Long.class)) + .isEqualTo(StartSessionPreAuthorizationReservationService.CLAIM_TTL.toMillis()); + String pendingReservationRow = loggingStore.reservationRowJson(controlPlaneRequestId); + + // The winning transition is the only authorization dispatch point. This direct + // Account + // authenticated Account call follows immediately; a duplicate acquisition above had + // no claim to + // dispatch. + var original = + proof.issueAndRedeemOriginal( + controlPlaneRequestId, + action, + claim.reservationOwnerId(), + claim.reservationClaimFence(), + new OwnerAttemptLifecycle() { + @Override + public OwnerClaim reserve( + StartSessionPostAuthorizationExecutionTuple tuple) { + AttemptClaim claim = gameSessionStore.reserve(tuple); + reservedGameSessionClaim.set(claim); + reservedTupleBytes.set(tuple.canonicalBytes()); + OwnerClaim ownerClaim = + new OwnerClaim( + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.ownerFence()); + gameSessionOwnerClaim.set(ownerClaim); + return ownerClaim; + } + + @Override + public void attachAccountRedemptionProjection( + OwnerClaim ownerClaim, + StartSessionPostAuthorizationExecutionTuple tuple, + byte[] originalAccountPostAuthorizationTuple) { + AttemptClaim claim = + java.util.Objects.requireNonNull( + reservedGameSessionClaim.get(), + "exact Game Session reservation must precede Account redemption"); + assertThat(ownerClaim.ownerAttemptId()).isEqualTo(claim.ownerAttemptId()); + assertThat(ownerClaim.ownerMutationId()) + .isEqualTo(claim.ownerMutationId()); + assertThat(ownerClaim.ownerFence()).isEqualTo(claim.ownerFence()); + assertThat(tuple.canonicalBytes()) + .containsExactly(reservedTupleBytes.get()); + assertThat(originalAccountPostAuthorizationTuple) + .containsExactly(tuple.canonicalBytes()); + var authority = + StartSessionAuthorityEvidenceBundle.decode( + tuple.authorityEvidenceBundleBytes()); + var projection = + new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence()), + originalAccountPostAuthorizationTuple); + assertThat(projection.canonicalBytes()) + .containsExactly( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); + var attached = gameSessionStore.attach(claim, projection); + assertThat(attached.accountRedemptionProjection()) + .containsExactly(projection.canonicalBytes()); + } + }, + transport); + assertThat(original.originalTuple().preAuthorizationTuple().canonicalJson()) + .isEqualTo(loggingTuple.canonicalJson()); + assertThat(original.originalTuple().preAuthorizationTuple().canonicalJson()) + .isEqualTo(commonTuple.canonicalJson()); + assertThat(loggingReadRequests).hasSize(1); + assertThat(loggingReadResponses).hasSize(1); + ReadCurrentClaimEvidenceRequest readRequest = loggingReadRequests.getFirst(); + ReadCurrentClaimEvidenceResponse readResponse = loggingReadResponses.getFirst(); + assertThat(readRequest.getControlPlaneRequestId()).isEqualTo(controlPlaneRequestId); + assertThat(readRequest.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(loggingTuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + readRequest.getPreAuthorizationTupleJson().toStringUtf8()) + .mutationDigest()) + .isEqualTo(loggingTuple.mutationDigest()); + assertThat(readRequest.getReservationOwnerId()) + .isEqualTo(claim.reservationOwnerId().toString()); + assertThat(readRequest.getReservationClaimFence()) + .isEqualTo(claim.reservationClaimFence()); + assertThat(readRequest.getClaimOwnerId()) + .isEqualTo(claim.currentClaimOwnerId().toString()); + assertThat(readRequest.getClaimFence()).isEqualTo(claim.currentClaimFence()); + assertThat(readRequest.getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(readResponse.getControlPlaneRequestId()).isEqualTo(controlPlaneRequestId); + assertThat(readResponse.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(loggingTuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(readResponse.getMutationDigest()).isEqualTo(loggingTuple.mutationDigest()); + assertThat(readResponse.getReservationOwnerId()) + .isEqualTo(claim.reservationOwnerId().toString()); + assertThat(readResponse.getReservationClaimFence()) + .isEqualTo(claim.reservationClaimFence()); + assertThat(readResponse.getClaimOwnerId()) + .isEqualTo(claim.currentClaimOwnerId().toString()); + assertThat(readResponse.getClaimFence()).isEqualTo(claim.currentClaimFence()); + assertThat(readResponse.getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(readResponse.getClaimExpiresAtEpochMillis()) + .isEqualTo(pending.snapshot().claimExpiresAtEpochMillis()); + assertThat(readResponse.getObservedAtEpochMillis()) + .isLessThan(readResponse.getClaimExpiresAtEpochMillis()); + var persistedPending = loggingStore.service().findExact(loggingTuple).orElseThrow(); + assertThat(persistedPending).isEqualTo(pending.snapshot()); + assertThat(persistedPending.phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(persistedPending.state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(persistedPending.reservationClaimFence()) + .isEqualTo(claim.reservationClaimFence()); + assertThat(persistedPending.claimFence()).isEqualTo(claim.currentClaimFence()); + assertThat(persistedPending.claimExpiresAtEpochMillis()) + .isEqualTo(pending.snapshot().claimExpiresAtEpochMillis()); + assertThat(persistedPending.claimPurpose()).isEqualTo(ClaimPurpose.ORIGINAL); + assertThat(loggingStore.reservationRowJson(controlPlaneRequestId)) + .isEqualTo(pendingReservationRow); + var duplicateAfterIssue = loggingStore.service().acquire(loggingTuple); + assertThat(duplicateAfterIssue.newlyAcquired()).isFalse(); + assertThat(duplicateAfterIssue.claim()).isNull(); + assertThat(duplicateAfterIssue.snapshot()).isEqualTo(persistedPending); + assertThat(loggingReadRequests) + .as("an exact duplicate observes the row without a second Account claim read") + .hasSize(1); + assertThat(loggingStore.reservationRowJson(controlPlaneRequestId)) + .isEqualTo(pendingReservationRow); + OwnerClaim ownerClaim = + java.util.Objects.requireNonNull( + gameSessionOwnerClaim.get(), + "actual Game Session owner claim must be retained"); + UUID gameSessionAttemptId = ownerClaim.ownerAttemptId(); + UUID gameSessionMutationId = ownerClaim.ownerMutationId(); + long gameSessionOwnerFence = ownerClaim.ownerFence(); + assertThat(original.gameSessionOwnerAttemptId()).isEqualTo(gameSessionAttemptId); + assertThat(original.gameSessionOwnerFence()).isEqualTo(gameSessionOwnerFence); + assertThat(original.originalTuple().preAuthorizationTuple().targetOwner()) + .isEqualTo("game-session-service"); + + byte[] redemptionProjection = + StartSessionAccountRedemptionProjection.fromOriginalTuple( + original.originalTuple()); + List currentAttemptReads = new ArrayList<>(); + List currentAttemptResults = new ArrayList<>(); + OriginalStartSessionCurrentAttemptClient currentAttemptClient = + request -> { + currentAttemptReads.add(request); + Result observation = grpcClient.read(request); + currentAttemptResults.add(observation); + return observation; + }; + var acquisitionService = + proof.worldParticipationAcquisitionService(currentAttemptClient); + String preparationInput = + preparationInput( + NAMESPACE, tenantId, controlPlaneRequestId, gameInstanceId, GAME_TEMPLATE_ID); + var acquisitionRequest = + new AcquisitionRequest( + original.originalTuple().canonicalBytes(), + gameSessionMutationId, + gameSessionAttemptId, + gameSessionOwnerFence, + gameInstanceId, + preparationInput, + digest(preparationInput)); + + String gameSessionRowBeforeReads = + gameSessionStore.ownerAttemptRowJson(controlPlaneRequestId); + var first = withWorldPeer(() -> acquisitionService.acquire(acquisitionRequest)); + StoredParticipation firstParticipation = first.participation(); + StoredEvidence firstObservation = first.originalAttemptEvidence(); + Result firstGameSessionObservation = currentAttemptResults.getFirst(); + assertThat(firstParticipation.participationId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(firstParticipation.participationFence()).isPositive(); + assertThat(firstParticipation.originalPostAuthorizationTuple()) + .containsExactly(original.originalTuple().canonicalBytes()); + assertThat(firstParticipation.gameSessionOwnerAttemptId()) + .isEqualTo(gameSessionAttemptId); + assertThat(firstParticipation.gameSessionOwnerFence()) + .isEqualTo(gameSessionOwnerFence); + assertThat(firstParticipation.sources()).isNotEmpty(); + assertThat(firstObservation.gameSessionOwnerMutationId()) + .isEqualTo(gameSessionMutationId); + assertThat(firstObservation.originalLeaseExpiresAt()) + .isEqualTo(firstGameSessionObservation.originalLeaseExpiresAt()); + assertThat(firstGameSessionObservation.phaseState()) + .isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat(firstGameSessionObservation.request()) + .isEqualTo(currentAttemptReads.getFirst()); + assertThat(firstGameSessionObservation.request().canonicalPostAuthorizationTuple()) + .containsExactly(original.originalTuple().canonicalBytes()); + assertThat(firstGameSessionObservation.request().expectedOwnerAttemptId()) + .isEqualTo(gameSessionAttemptId); + assertThat(firstGameSessionObservation.request().expectedOwnerMutationId()) + .isEqualTo(gameSessionMutationId); + assertThat(firstGameSessionObservation.request().expectedOwnerFence()) + .isEqualTo(gameSessionOwnerFence); + assertThat(firstGameSessionObservation.accountRedemptionProjection()) + .containsExactly(redemptionProjection); + assertThat(firstGameSessionObservation.originalLeaseExpiresAt()) + .isAfter(Instant.now()); + assertThat(firstGameSessionObservation.originalLeaseExpiresAt()) + .isBefore(original.accountReferenceExpiresAt()); + Record actualGameSessionRow = gameSessionStore.ownerAttemptRow(controlPlaneRequestId); + assertThat(actualGameSessionRow.get("target_namespace", String.class)) + .isEqualTo(NAMESPACE); + assertThat(actualGameSessionRow.get("control_plane_request_id", String.class)) + .isEqualTo(controlPlaneRequestId); + assertThat(actualGameSessionRow.get("owner_attempt_id", UUID.class)) + .isEqualTo(gameSessionAttemptId); + assertThat(actualGameSessionRow.get("owner_mutation_id", UUID.class)) + .isEqualTo(gameSessionMutationId); + assertThat(actualGameSessionRow.get("owner_fence", Long.class)) + .isEqualTo(gameSessionOwnerFence); + assertThat(actualGameSessionRow.get("phase_state", String.class)) + .isEqualTo("OWNER_EXECUTION_PENDING"); + assertThat( + actualGameSessionRow.get("post_authorization_execution_tuple", byte[].class)) + .containsExactly(original.originalTuple().canonicalBytes()); + assertThat(actualGameSessionRow.get("account_redemption_projection", byte[].class)) + .containsExactly(redemptionProjection); + assertThat(actualGameSessionRow.get("lease_expires_at", OffsetDateTime.class)) + .isEqualTo( + OffsetDateTime.ofInstant( + firstGameSessionObservation.originalLeaseExpiresAt(), ZoneOffset.UTC)); + assertThat(firstObservation.originalResponseBytes()) + .containsExactly( + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + firstGameSessionObservation) + .toByteArray()); + + DSLContext dsl = proof.sourceDsl(); + assertPersistedAcquisition( + dsl, original.originalTuple(), firstParticipation, firstObservation); + + // The actual Game Session observation is repeated with a newly generated correlation. + // Account's exact-operation retry must preserve the first bytes and participation + // fence. + var exactRetry = withWorldPeer(() -> acquisitionService.acquire(acquisitionRequest)); + assertThat(currentAttemptReads).hasSize(2); + assertThat(currentAttemptReads.get(0).readRequestId()) + .isNotEqualTo(currentAttemptReads.get(1).readRequestId()); + assertThat(currentAttemptResults).hasSize(2); + assertThat(currentAttemptResults.get(1).request()) + .isEqualTo(currentAttemptReads.get(1)); + assertThat(currentAttemptResults.get(1).accountRedemptionProjection()) + .containsExactly(redemptionProjection); + assertThat(currentAttemptResults.get(1).originalLeaseExpiresAt()) + .isEqualTo(firstGameSessionObservation.originalLeaseExpiresAt()); + assertThat(exactRetry.participation().participationId()) + .isEqualTo(firstParticipation.participationId()); + assertThat(exactRetry.participation().participationFence()) + .isEqualTo(firstParticipation.participationFence()); + assertThat(exactRetry.originalAttemptEvidence().originalResponseBytes()) + .containsExactly(firstObservation.originalResponseBytes()); + assertThat(exactRetry.originalAttemptEvidence().result().request().readRequestId()) + .isEqualTo(currentAttemptReads.get(0).readRequestId()); + assertPersistedAcquisition( + dsl, original.originalTuple(), firstParticipation, firstObservation); + assertThat(gameSessionStore.ownerAttemptRowJson(controlPlaneRequestId)) + .isEqualTo(gameSessionRowBeforeReads); + + int retainedParticipationCount = + dsl.fetchCount(DSL.table("account_start_session_world_participations")); + int retainedSourceCount = + dsl.fetchCount(DSL.table("account_start_session_world_participation_sources")); + int retainedObservationCount = + dsl.fetchCount( + DSL.table("account_start_session_world_original_attempt_evidence")); + + var changedTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + original.originalTuple().preAuthorizationTuple(), + original.originalTuple().authenticatedWorkloadIdentity(), + "arfp/v1/changed-proof/" + "c".repeat(64), + original.originalTuple().reservationOwnerId(), + original.originalTuple().reservationClaimFence(), + original.originalTuple().authorityEvidenceBundleBytes(), + original.originalTuple().bundleReference()); + var changedTupleRequest = + new AcquisitionRequest( + changedTuple.canonicalBytes(), + gameSessionMutationId, + gameSessionAttemptId, + gameSessionOwnerFence, + gameInstanceId, + preparationInput, + digest(preparationInput)); + assertFailedPrecondition( + () -> withWorldPeer(() -> acquisitionService.acquire(changedTupleRequest))); + + var changedOwnerFenceRequest = + new AcquisitionRequest( + original.originalTuple().canonicalBytes(), + gameSessionMutationId, + gameSessionAttemptId, + gameSessionOwnerFence + 1, + gameInstanceId, + preparationInput, + digest(preparationInput)); + assertFailedPrecondition( + () -> withWorldPeer(() -> acquisitionService.acquire(changedOwnerFenceRequest))); + assertThat(dsl.fetchCount(DSL.table("account_start_session_world_participations"))) + .isEqualTo(retainedParticipationCount); + assertThat( + dsl.fetchCount( + DSL.table("account_start_session_world_participation_sources"))) + .isEqualTo(retainedSourceCount); + assertThat( + dsl.fetchCount( + DSL.table("account_start_session_world_original_attempt_evidence"))) + .isEqualTo(retainedObservationCount); + assertThat(gameSessionStore.ownerAttemptRowJson(controlPlaneRequestId)) + .isEqualTo(gameSessionRowBeforeReads); + + var sourceFixture = controlUi.preparedOriginalCreator().sources(); + String originalRole = + dsl.fetchSingle("SELECT role FROM accounts WHERE account_uuid = ?", accountId) + .get(0, String.class); + assertThatThrownBy(sourceFixture::changeRoleToAdmin) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining( + "StartSession World participation remains pending for a required source"); + assertThat( + dsl.fetchSingle("SELECT role FROM accounts WHERE account_uuid = ?", accountId) + .get(0, String.class)) + .isEqualTo(originalRole); } - var commonTuple = - net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple - .fromCanonicalJson(loggingTuple.canonicalJson()); - assertThat(loggingTuple.isAuthorityDerived()).isTrue(); - assertThat(loggingTuple.actor().accountId()).isEqualTo(accountId); - - var defaultRepository = - new StartSessionPreAuthorizationReservationRepository(loggingStore.dsl()); - var defaultService = - new StartSessionPreAuthorizationReservationService(defaultRepository); - assertThatThrownBy(() -> defaultService.acquire(loggingTuple)) - .isInstanceOf(UnsupportedOperationException.class) - .hasMessageContaining("mutations are disabled for production construction"); - assertThatThrownBy( - () -> - defaultRepository.acquire( - loggingTuple, - UUID.randomUUID(), - System.currentTimeMillis(), - System.currentTimeMillis() - + StartSessionPreAuthorizationReservationService.CLAIM_TTL - .toMillis())) - .isInstanceOf(UnsupportedOperationException.class); - - var acquired = loggingStore.service().acquire(loggingTuple); - assertThat(acquired.newlyAcquired()).isTrue(); - assertThat(acquired.claim()).isNotNull(); - assertThat(acquired.snapshot().state()).isEqualTo(State.RESERVED); - assertThat(acquired.snapshot().phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); - ClaimEvidence claim = acquired.claim().claimEvidence(); - assertThat(claim.reservationOwnerId()).isEqualTo(claim.currentClaimOwnerId()); - assertThat(claim.reservationClaimFence()).isEqualTo(1L); - assertThat(claim.currentClaimFence()).isEqualTo(1L); - - var duplicateAcquire = loggingStore.service().acquire(loggingTuple); - assertThat(duplicateAcquire.newlyAcquired()).isFalse(); - assertThat(duplicateAcquire.claim()).isNull(); - assertThat(duplicateAcquire.snapshot()).isEqualTo(acquired.snapshot()); - assertThat(loggingReadRequests).isEmpty(); - - var pending = loggingStore.service().markAuthorizationPending(acquired.claim()); - assertThat(pending.mayDispatchAccountAuthorization()).isTrue(); - assertThat(pending.snapshot().phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); - assertThat(pending.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); - assertThat(pending.snapshot().claimState()).isEqualTo(ClaimState.ACTIVE); - assertThat(pending.snapshot().claimPurpose()).isEqualTo(ClaimPurpose.ORIGINAL); - assertThat(pending.snapshot().reservationClaimFence()) - .isEqualTo(claim.reservationClaimFence()); - assertThat(pending.snapshot().claimFence()).isEqualTo(claim.currentClaimFence()); - assertThat(pending.snapshot().claimExpiresAtEpochMillis()) - .isGreaterThan(System.currentTimeMillis()); - Record pendingRow = loggingStore.reservationRow(controlPlaneRequestId); - assertThat(pendingRow.get("pre_authorization_tuple_json", String.class)) - .isEqualTo(loggingTuple.canonicalJson()); - assertThat(pendingRow.get("mutation_digest", String.class)) - .isEqualTo(loggingTuple.mutationDigest()); - assertThat(pendingRow.get("phase", String.class)).isEqualTo("ACCOUNT_AUTHORIZATION"); - assertThat(pendingRow.get("state", String.class)).isEqualTo("AUTHORIZATION_PENDING"); - assertThat(pendingRow.get("reservation_owner_id", UUID.class)) - .isEqualTo(claim.reservationOwnerId()); - assertThat(pendingRow.get("reservation_claim_fence", Long.class)) - .isEqualTo(claim.reservationClaimFence()); - assertThat(pendingRow.get("claim_owner_id", UUID.class)) - .isEqualTo(claim.currentClaimOwnerId()); - assertThat(pendingRow.get("claim_fence", Long.class)) - .isEqualTo(claim.currentClaimFence()); - assertThat(pendingRow.get("claim_state", String.class)).isEqualTo("ACTIVE"); - assertThat(pendingRow.get("claim_purpose", String.class)).isEqualTo("ORIGINAL"); - assertThat( - pendingRow.get("claim_expires_at_epoch_ms", Long.class) - - pendingRow.get("created_at_epoch_ms", Long.class)) - .isEqualTo(StartSessionPreAuthorizationReservationService.CLAIM_TTL.toMillis()); - String pendingReservationRow = loggingStore.reservationRowJson(controlPlaneRequestId); - - // The winning transition is the only authorization dispatch point. This direct Account - // fixture call follows immediately; a duplicate acquisition above had no claim to - // dispatch. - var original = - proof.issueAndRedeemOriginal( - controlPlaneRequestId, - action, - claim.reservationOwnerId(), - claim.reservationClaimFence(), - new OwnerAttemptLifecycle() { - @Override - public OwnerClaim reserve(StartSessionPostAuthorizationExecutionTuple tuple) { - AttemptClaim claim = gameSessionStore.reserve(tuple); - reservedGameSessionClaim.set(claim); - reservedTupleBytes.set(tuple.canonicalBytes()); - OwnerClaim ownerClaim = - new OwnerClaim( - claim.ownerAttemptId(), - claim.ownerMutationId(), - claim.ownerFence()); - gameSessionOwnerClaim.set(ownerClaim); - return ownerClaim; - } - - @Override - public void attachAccountRedemptionProjection( - OwnerClaim ownerClaim, - StartSessionPostAuthorizationExecutionTuple tuple) { - AttemptClaim claim = - java.util.Objects.requireNonNull( - reservedGameSessionClaim.get(), - "exact Game Session reservation must precede Account redemption"); - assertThat(ownerClaim.ownerAttemptId()).isEqualTo(claim.ownerAttemptId()); - assertThat(ownerClaim.ownerMutationId()).isEqualTo(claim.ownerMutationId()); - assertThat(ownerClaim.ownerFence()).isEqualTo(claim.ownerFence()); - assertThat(tuple.canonicalBytes()) - .containsExactly(reservedTupleBytes.get()); - var authority = - StartSessionAuthorityEvidenceBundle.decode( - tuple.authorityEvidenceBundleBytes()); - var projection = - new AccountRedemptionProjection( - tuple.authorizationReferenceFingerprint(), - tuple.authorityEvidenceBundleBytes(), - authority.issuanceOperationId(), - Long.parseLong(tuple.issuanceFence())); - assertThat(projection.canonicalBytes()) - .containsExactly( - StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); - var attached = gameSessionStore.attach(claim, projection); - assertThat(attached.accountRedemptionProjection()) - .containsExactly(projection.canonicalBytes()); - } - }); - assertThat(original.originalTuple().preAuthorizationTuple().canonicalJson()) - .isEqualTo(loggingTuple.canonicalJson()); - assertThat(original.originalTuple().preAuthorizationTuple().canonicalJson()) - .isEqualTo(commonTuple.canonicalJson()); - assertThat(loggingReadRequests).hasSize(1); - assertThat(loggingReadResponses).hasSize(1); - ReadCurrentClaimEvidenceRequest readRequest = loggingReadRequests.getFirst(); - ReadCurrentClaimEvidenceResponse readResponse = loggingReadResponses.getFirst(); - assertThat(readRequest.getControlPlaneRequestId()).isEqualTo(controlPlaneRequestId); - assertThat(readRequest.getPreAuthorizationTupleJson().toByteArray()) - .containsExactly(loggingTuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); - assertThat( - StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( - readRequest.getPreAuthorizationTupleJson().toStringUtf8()) - .mutationDigest()) - .isEqualTo(loggingTuple.mutationDigest()); - assertThat(readRequest.getReservationOwnerId()) - .isEqualTo(claim.reservationOwnerId().toString()); - assertThat(readRequest.getReservationClaimFence()) - .isEqualTo(claim.reservationClaimFence()); - assertThat(readRequest.getClaimOwnerId()) - .isEqualTo(claim.currentClaimOwnerId().toString()); - assertThat(readRequest.getClaimFence()).isEqualTo(claim.currentClaimFence()); - assertThat(readRequest.getPurpose()) - .isEqualTo( - StartSessionReservationEvidencePurpose - .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); - assertThat(readResponse.getControlPlaneRequestId()).isEqualTo(controlPlaneRequestId); - assertThat(readResponse.getPreAuthorizationTupleJson().toByteArray()) - .containsExactly(loggingTuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); - assertThat(readResponse.getMutationDigest()).isEqualTo(loggingTuple.mutationDigest()); - assertThat(readResponse.getReservationOwnerId()) - .isEqualTo(claim.reservationOwnerId().toString()); - assertThat(readResponse.getReservationClaimFence()) - .isEqualTo(claim.reservationClaimFence()); - assertThat(readResponse.getClaimOwnerId()) - .isEqualTo(claim.currentClaimOwnerId().toString()); - assertThat(readResponse.getClaimFence()).isEqualTo(claim.currentClaimFence()); - assertThat(readResponse.getPurpose()) - .isEqualTo( - StartSessionReservationEvidencePurpose - .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); - assertThat(readResponse.getClaimExpiresAtEpochMillis()) - .isEqualTo(pending.snapshot().claimExpiresAtEpochMillis()); - assertThat(readResponse.getObservedAtEpochMillis()) - .isLessThan(readResponse.getClaimExpiresAtEpochMillis()); - var persistedPending = loggingStore.service().findExact(loggingTuple).orElseThrow(); - assertThat(persistedPending).isEqualTo(pending.snapshot()); - assertThat(persistedPending.phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); - assertThat(persistedPending.state()).isEqualTo(State.AUTHORIZATION_PENDING); - assertThat(persistedPending.reservationClaimFence()) - .isEqualTo(claim.reservationClaimFence()); - assertThat(persistedPending.claimFence()).isEqualTo(claim.currentClaimFence()); - assertThat(persistedPending.claimExpiresAtEpochMillis()) - .isEqualTo(pending.snapshot().claimExpiresAtEpochMillis()); - assertThat(persistedPending.claimPurpose()).isEqualTo(ClaimPurpose.ORIGINAL); - assertThat(loggingStore.reservationRowJson(controlPlaneRequestId)) - .isEqualTo(pendingReservationRow); - var duplicateAfterIssue = loggingStore.service().acquire(loggingTuple); - assertThat(duplicateAfterIssue.newlyAcquired()).isFalse(); - assertThat(duplicateAfterIssue.claim()).isNull(); - assertThat(duplicateAfterIssue.snapshot()).isEqualTo(persistedPending); - assertThat(loggingReadRequests) - .as("an exact duplicate observes the row without a second Account claim read") - .hasSize(1); - assertThat(loggingStore.reservationRowJson(controlPlaneRequestId)) - .isEqualTo(pendingReservationRow); - OwnerClaim ownerClaim = - java.util.Objects.requireNonNull( - gameSessionOwnerClaim.get(), - "actual Game Session owner claim must be retained"); - UUID gameSessionAttemptId = ownerClaim.ownerAttemptId(); - UUID gameSessionMutationId = ownerClaim.ownerMutationId(); - long gameSessionOwnerFence = ownerClaim.ownerFence(); - assertThat(original.gameSessionOwnerAttemptId()).isEqualTo(gameSessionAttemptId); - assertThat(original.gameSessionOwnerFence()).isEqualTo(gameSessionOwnerFence); - assertThat(original.originalTuple().preAuthorizationTuple().targetOwner()) - .isEqualTo("game-session-service"); - - byte[] redemptionProjection = - StartSessionAccountRedemptionProjection.fromOriginalTuple(original.originalTuple()); - List currentAttemptReads = new ArrayList<>(); - List currentAttemptResults = new ArrayList<>(); - OriginalStartSessionCurrentAttemptClient currentAttemptClient = - request -> { - currentAttemptReads.add(request); - Result observation = grpcClient.read(request); - currentAttemptResults.add(observation); - return observation; - }; - var acquisitionService = - proof.worldParticipationAcquisitionService(currentAttemptClient); - String preparationInput = - preparationInput( - NAMESPACE, tenantId, controlPlaneRequestId, gameInstanceId, GAME_TEMPLATE_ID); - var acquisitionRequest = - new AcquisitionRequest( - original.originalTuple().canonicalBytes(), - gameSessionMutationId, - gameSessionAttemptId, - gameSessionOwnerFence, - gameInstanceId, - preparationInput, - digest(preparationInput)); - - String gameSessionRowBeforeReads = - gameSessionStore.ownerAttemptRowJson(controlPlaneRequestId); - var first = withWorldPeer(() -> acquisitionService.acquire(acquisitionRequest)); - StoredParticipation firstParticipation = first.participation(); - StoredEvidence firstObservation = first.originalAttemptEvidence(); - Result firstGameSessionObservation = currentAttemptResults.getFirst(); - assertThat(firstParticipation.participationId()).isNotEqualTo(new UUID(0L, 0L)); - assertThat(firstParticipation.participationFence()).isPositive(); - assertThat(firstParticipation.originalPostAuthorizationTuple()) - .containsExactly(original.originalTuple().canonicalBytes()); - assertThat(firstParticipation.gameSessionOwnerAttemptId()) - .isEqualTo(gameSessionAttemptId); - assertThat(firstParticipation.gameSessionOwnerFence()).isEqualTo(gameSessionOwnerFence); - assertThat(firstParticipation.sources()).isNotEmpty(); - assertThat(firstObservation.gameSessionOwnerMutationId()) - .isEqualTo(gameSessionMutationId); - assertThat(firstObservation.originalLeaseExpiresAt()) - .isEqualTo(firstGameSessionObservation.originalLeaseExpiresAt()); - assertThat(firstGameSessionObservation.phaseState()) - .isEqualTo("OWNER_EXECUTION_PENDING"); - assertThat(firstGameSessionObservation.request()) - .isEqualTo(currentAttemptReads.getFirst()); - assertThat(firstGameSessionObservation.request().canonicalPostAuthorizationTuple()) - .containsExactly(original.originalTuple().canonicalBytes()); - assertThat(firstGameSessionObservation.request().expectedOwnerAttemptId()) - .isEqualTo(gameSessionAttemptId); - assertThat(firstGameSessionObservation.request().expectedOwnerMutationId()) - .isEqualTo(gameSessionMutationId); - assertThat(firstGameSessionObservation.request().expectedOwnerFence()) - .isEqualTo(gameSessionOwnerFence); - assertThat(firstGameSessionObservation.accountRedemptionProjection()) - .containsExactly(redemptionProjection); - assertThat(firstGameSessionObservation.originalLeaseExpiresAt()).isAfter(Instant.now()); - assertThat(firstGameSessionObservation.originalLeaseExpiresAt()) - .isBefore(original.accountReferenceExpiresAt()); - Record actualGameSessionRow = gameSessionStore.ownerAttemptRow(controlPlaneRequestId); - assertThat(actualGameSessionRow.get("target_namespace", String.class)) - .isEqualTo(NAMESPACE); - assertThat(actualGameSessionRow.get("control_plane_request_id", String.class)) - .isEqualTo(controlPlaneRequestId); - assertThat(actualGameSessionRow.get("owner_attempt_id", UUID.class)) - .isEqualTo(gameSessionAttemptId); - assertThat(actualGameSessionRow.get("owner_mutation_id", UUID.class)) - .isEqualTo(gameSessionMutationId); - assertThat(actualGameSessionRow.get("owner_fence", Long.class)) - .isEqualTo(gameSessionOwnerFence); - assertThat(actualGameSessionRow.get("phase_state", String.class)) - .isEqualTo("OWNER_EXECUTION_PENDING"); - assertThat(actualGameSessionRow.get("post_authorization_execution_tuple", byte[].class)) - .containsExactly(original.originalTuple().canonicalBytes()); - assertThat(actualGameSessionRow.get("account_redemption_projection", byte[].class)) - .containsExactly(redemptionProjection); - assertThat(actualGameSessionRow.get("lease_expires_at", OffsetDateTime.class)) - .isEqualTo( - OffsetDateTime.ofInstant( - firstGameSessionObservation.originalLeaseExpiresAt(), ZoneOffset.UTC)); - assertThat(firstObservation.originalResponseBytes()) - .containsExactly( - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( - firstGameSessionObservation) - .toByteArray()); - - DSLContext dsl = proof.sourceDsl(); - assertPersistedAcquisition( - dsl, original.originalTuple(), firstParticipation, firstObservation); - - // The actual Game Session observation is repeated with a newly generated correlation. - // Account's exact-operation retry must preserve the first bytes and participation - // fence. - var exactRetry = withWorldPeer(() -> acquisitionService.acquire(acquisitionRequest)); - assertThat(currentAttemptReads).hasSize(2); - assertThat(currentAttemptReads.get(0).readRequestId()) - .isNotEqualTo(currentAttemptReads.get(1).readRequestId()); - assertThat(currentAttemptResults).hasSize(2); - assertThat(currentAttemptResults.get(1).request()) - .isEqualTo(currentAttemptReads.get(1)); - assertThat(currentAttemptResults.get(1).accountRedemptionProjection()) - .containsExactly(redemptionProjection); - assertThat(currentAttemptResults.get(1).originalLeaseExpiresAt()) - .isEqualTo(firstGameSessionObservation.originalLeaseExpiresAt()); - assertThat(exactRetry.participation().participationId()) - .isEqualTo(firstParticipation.participationId()); - assertThat(exactRetry.participation().participationFence()) - .isEqualTo(firstParticipation.participationFence()); - assertThat(exactRetry.originalAttemptEvidence().originalResponseBytes()) - .containsExactly(firstObservation.originalResponseBytes()); - assertThat(exactRetry.originalAttemptEvidence().result().request().readRequestId()) - .isEqualTo(currentAttemptReads.get(0).readRequestId()); - assertPersistedAcquisition( - dsl, original.originalTuple(), firstParticipation, firstObservation); - assertThat(gameSessionStore.ownerAttemptRowJson(controlPlaneRequestId)) - .isEqualTo(gameSessionRowBeforeReads); - - int retainedParticipationCount = - dsl.fetchCount(DSL.table("account_start_session_world_participations")); - int retainedSourceCount = - dsl.fetchCount(DSL.table("account_start_session_world_participation_sources")); - int retainedObservationCount = - dsl.fetchCount(DSL.table("account_start_session_world_original_attempt_evidence")); - - var changedTuple = - StartSessionPostAuthorizationExecutionTuple.createHuman( - original.originalTuple().preAuthorizationTuple(), - original.originalTuple().authenticatedWorkloadIdentity(), - "arfp/v1/changed-proof/" + "c".repeat(64), - original.originalTuple().reservationOwnerId(), - original.originalTuple().reservationClaimFence(), - original.originalTuple().authorityEvidenceBundleBytes(), - original.originalTuple().bundleReference()); - var changedTupleRequest = - new AcquisitionRequest( - changedTuple.canonicalBytes(), - gameSessionMutationId, - gameSessionAttemptId, - gameSessionOwnerFence, - gameInstanceId, - preparationInput, - digest(preparationInput)); - assertFailedPrecondition( - () -> withWorldPeer(() -> acquisitionService.acquire(changedTupleRequest))); - - var changedOwnerFenceRequest = - new AcquisitionRequest( - original.originalTuple().canonicalBytes(), - gameSessionMutationId, - gameSessionAttemptId, - gameSessionOwnerFence + 1, - gameInstanceId, - preparationInput, - digest(preparationInput)); - assertFailedPrecondition( - () -> withWorldPeer(() -> acquisitionService.acquire(changedOwnerFenceRequest))); - assertThat(dsl.fetchCount(DSL.table("account_start_session_world_participations"))) - .isEqualTo(retainedParticipationCount); - assertThat( - dsl.fetchCount(DSL.table("account_start_session_world_participation_sources"))) - .isEqualTo(retainedSourceCount); - assertThat( - dsl.fetchCount( - DSL.table("account_start_session_world_original_attempt_evidence"))) - .isEqualTo(retainedObservationCount); - assertThat(gameSessionStore.ownerAttemptRowJson(controlPlaneRequestId)) - .isEqualTo(gameSessionRowBeforeReads); - - var sourceFixture = controlUi.preparedOriginalCreator().sources(); - String originalRole = - dsl.fetchSingle("SELECT role FROM accounts WHERE account_uuid = ?", accountId) - .get(0, String.class); - assertThatThrownBy(sourceFixture::changeRoleToAdmin) - .isInstanceOf(RuntimeException.class) - .hasMessageContaining( - "StartSession World participation remains pending for a required source"); - assertThat( - dsl.fetchSingle("SELECT role FROM accounts WHERE account_uuid = ?", accountId) - .get(0, String.class)) - .isEqualTo(originalRole); } } finally { stopCurrentAttemptServer(gameSessionServer); @@ -642,6 +667,229 @@ public void attachAccountRedemptionProjection( } } + /** Wide claims are stipulated: Logging's physical original-reservation schema starts at one. */ + @ParameterizedTest + @ValueSource(longs = {9_007_199_254_740_993L, Long.MAX_VALUE}) + void wideOriginalFenceRetainsExactAccountAndGameSessionEvidenceOverMutualTls(long fence) + throws Exception { + var pki = TestPki.create(Files.createDirectories(temporary.resolve("wide-fence-pki"))); + var gameSessionStore = gameSessionAttemptStore(); + try (var controlUi = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary)) { + prepareOriginalCreator(controlUi); + // The default fixture explicitly stipulates only the upstream Logging claim reader. + var proof = + new AccountOriginalStartSessionAuthorizationProofFixture(controlUi, temporary, NAMESPACE); + var claim = new AtomicReference(); + try (var transport = new AccountAuthorizationTransport(pki, proof, claim)) { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(controlUi.tenantId(), NAMESPACE), + new StartSessionOperatorAction.Target(GAME_TEMPLATE_ID, proof.creatorAccountId()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "test-only wide original reservation fence transport and storage proof"); + String requestId = "wide-original-fence-" + UUID.randomUUID(); + var original = + proof.issueAndRedeemOriginal( + requestId, + action, + UUID.randomUUID(), + fence, + new OwnerAttemptLifecycle() { + @Override + public OwnerClaim reserve(StartSessionPostAuthorizationExecutionTuple tuple) { + assertThat(tuple.reservationClaimFence()).isEqualTo(fence); + claim.set(gameSessionStore.reserve(tuple)); + return new OwnerClaim( + claim.get().ownerAttemptId(), + claim.get().ownerMutationId(), + claim.get().ownerFence()); + } + + @Override + public void attachAccountRedemptionProjection( + OwnerClaim owner, + StartSessionPostAuthorizationExecutionTuple tuple, + byte[] independentlyReturnedTuple) { + assertThat(independentlyReturnedTuple).containsExactly(tuple.canonicalBytes()); + var bundle = + StartSessionAuthorityEvidenceBundle.decode( + tuple.authorityEvidenceBundleBytes()); + var projection = + new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence()), + independentlyReturnedTuple); + gameSessionStore.attach(claim.get(), projection); + String before = gameSessionStore.ownerAttemptRowJson(requestId); + assertThat( + gameSessionStore + .attach(claim.get(), projection) + .accountRedemptionProjection()) + .containsExactly( + StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); + assertThat(gameSessionStore.ownerAttemptRowJson(requestId)).isEqualTo(before); + } + }, + transport); + byte[] tupleBytes = original.originalTuple().canonicalBytes(); + assertThat(new String(tupleBytes, StandardCharsets.UTF_8)) + .contains("\"reservationClaimFence\":\"" + fence + "\""); + assertThat( + StartSessionPostAuthorizationExecutionTuple.decode(tupleBytes) + .reservationClaimFence()) + .isEqualTo(fence); + Record row = gameSessionStore.ownerAttemptRow(requestId); + assertThat(row.get("post_authorization_execution_tuple", byte[].class)) + .containsExactly(tupleBytes); + assertThat(row.get("account_redemption_projection", byte[].class)) + .containsExactly( + StartSessionAccountRedemptionProjection.fromOriginalTuple( + original.originalTuple())); + } + } + } + + private static final class AccountAuthorizationTransport + implements OriginalStartSessionAuthorizationTransport, AutoCloseable { + private final Server server; + private final net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient + issueClient; + private final net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClient + redeemClient; + private final AtomicReference actualClaim; + + AccountAuthorizationTransport( + TestPki pki, + AccountOriginalStartSessionAuthorizationProofFixture proof, + AtomicReference actualClaim) + throws Exception { + this.actualClaim = actualClaim; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + pki.accountServer().certificate().toFile(), + pki.accountServer().privateKey().toFile()) + .trustManager(pki.caCertificate().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + proof.grpcService(), new GrpcPeerIdentityInterceptor())) + .build() + .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + issueClient = + new net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient( + endpoints, + clientTls(pki, pki.loggingClient()), + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop()); + redeemClient = + new net.firedevops.firemud.gamesession.client.StartSessionOperatorRedemptionClient( + endpoints, + clientTls(pki, pki.gameSessionClient()), + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE); + try { + issueClient.initialize(); + redeemClient.initialize(); + } catch (Exception failure) { + close(); + throw failure; + } + } + + @Override + public IssuedAuthorization issue( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple tuple, + String token, + UUID owner, + long fence) { + var issued = issueClient.issueHuman(tuple, token, owner, fence, owner, fence); + assertThat(issued.postAuthorizationTuple().reservationClaimFence()).isEqualTo(fence); + return new IssuedAuthorization( + issued.operatorAuthorizationReference(), + issued.authorizationReferenceFingerprint(), + issued.authorityEvidenceBundle(), + issued.bundleReference(), + issued.postAuthorizationTuple().canonicalBytes()); + } + + @Override + public AccountStartSessionOperatorAuthorizationService.RedemptionResult redeem( + byte[] preTupleBytes, + IssuedAuthorization issued, + UUID owner, + long fence, + OwnerClaim ownerClaim) { + var tuple = + StartSessionPostAuthorizationExecutionTuple.decode( + issued.originalAccountPostAuthorizationTuple()); + assertThat(tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8)) + .containsExactly(preTupleBytes); + assertThat(tuple.reservationOwnerId()).isEqualTo(owner); + assertThat(tuple.reservationClaimFence()).isEqualTo(fence); + AttemptClaim claim = + java.util.Objects.requireNonNull( + actualClaim.get(), "actual Game Session reservation required"); + assertThat(claim.ownerAttemptId()).isEqualTo(ownerClaim.ownerAttemptId()); + assertThat(claim.ownerMutationId()).isEqualTo(ownerClaim.ownerMutationId()); + assertThat(claim.ownerFence()).isEqualTo(ownerClaim.ownerFence()); + var result = redeemClient.redeem(tuple, issued.operatorAuthorizationReference(), claim); + var projection = result.projection(); + assertThat(projection.originalAccountPostAuthorizationTuple()) + .containsExactly(issued.originalAccountPostAuthorizationTuple()); + return new AccountStartSessionOperatorAuthorizationService.RedemptionResult( + projection.authorizationReferenceFingerprint(), + projection.authorityEvidenceBundleBytes(), + projection.issuanceOperationId(), + projection.issuanceFence(), + result.accountReplay(), + projection.originalAccountPostAuthorizationTuple()); + } + + private static CommonGrpcClientProperties clientTls(TestPki pki, TestIdentity identity) { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(identity.certificate().toString()); + tls.setPrivateKey(identity.privateKey().toString()); + tls.setCaCert(pki.caCertificate().toString()); + return tls; + } + + @Override + public void close() throws Exception { + try { + redeemClient.close(); + } finally { + try { + issueClient.close(); + } finally { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC server did not terminate"); + } + } + } + } + } + private static GameSessionAttemptStore gameSessionAttemptStore() throws Exception { String schema = "account_current_attempt_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); @@ -928,12 +1176,15 @@ Record ownerAttemptRow(String requestId) { private record TestIdentity(Path certificate, Path privateKey) {} - /** Test-only identities for the Account-to-Logging and Account-to-Game-Session mTLS proofs. */ + /** Test-only identities for the Account, Logging, and Game Session mutual-TLS proof calls. */ private record TestPki( Path caCertificate, TestIdentity gameSessionServer, TestIdentity loggingAdminServer, - TestIdentity accountClient) { + TestIdentity accountClient, + TestIdentity accountServer, + TestIdentity loggingClient, + TestIdentity gameSessionClient) { private static final String PASSWORD = "test-only-current-attempt-password"; static TestPki create(Path directory) throws Exception { @@ -995,6 +1246,24 @@ static TestPki create(Path directory) throws Exception { caStore, "account-client", "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", + false), + issueIdentity( + directory, + caStore, + "account-server", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", + true), + issueIdentity( + directory, + caStore, + "logging-client", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + false), + issueIdentity( + directory, + caStore, + "game-session-client", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service", false)); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java index 409efce42e..0fa912ad0d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java @@ -10,6 +10,7 @@ import java.nio.file.Path; import java.security.MessageDigest; import java.security.SecureRandom; +import java.sql.SQLException; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -211,6 +212,8 @@ void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() t reservationClaimFence, reservationOwnerId, reservationClaimFence))); + var issuedRecord = + account.tx(() -> operatorRepository.findByControlPlaneRequestId(requestId).orElseThrow()); // The exact Account issuance result becomes the original post-authorization tuple. The // target owner is still Game Session; World is only the same-namespace receiver. @@ -227,23 +230,64 @@ void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() t authorization.bundleReference().sourceVersion(), authorization.bundleReference().sourceFence(), authorization.bundleReference().linearization())); + assertThat(authorization.originalAccountPostAuthorizationTuple()) + .containsExactly(originalTuple.canonicalBytes()); assertThat(originalTuple.preAuthorizationTuple().targetOwner()) .isEqualTo("game-session-service"); + UUID recoveryClaimOwnerId = UUID.randomUUID(); + long recoveryClaimFence = reservationClaimFence + 1L; + var recoveryClaim = + claim.toBuilder() + .setClaimOwnerId(recoveryClaimOwnerId.toString()) + .setClaimFence(recoveryClaimFence) + .setPurpose( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER) + .build(); + when(claimClient.readCurrentClaimEvidence( + preAuthorizationTuple, + reservationOwnerId, + reservationClaimFence, + recoveryClaimOwnerId, + recoveryClaimFence, + StartSessionReservationEvidenceClient.Purpose.RECOVER)) + .thenReturn(recoveryClaim); + var recovered = + withPeer( + LOGGING_PEER_URI, + () -> + operatorAuthorization.recover( + new AccountStartSessionOperatorAuthorizationService.RecoverRequest( + preAuthorizationTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + reservationOwnerId, + reservationClaimFence, + recoveryClaimOwnerId, + recoveryClaimFence))); + assertThat(recovered.originalAccountPostAuthorizationTuple()) + .containsExactly(originalTuple.canonicalBytes()); + var recoveredRecord = + account.tx(() -> operatorRepository.findByControlPlaneRequestId(requestId).orElseThrow()); + assertThat(recoveredRecord.encryptedResponseEnvelope()) + .containsExactly(issuedRecord.encryptedResponseEnvelope()); + // Account performs its real one-time redemption. The Game Session peer and attempt/fence // are stipulated test inputs, not evidence from an authenticated Game Session producer. - withPeer( - GAME_SESSION_PEER_URI, - () -> - operatorAuthorization.redeem( - new AccountStartSessionOperatorAuthorizationService.RedeemRequest( - preAuthorizationTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), - authorization.operatorAuthorizationReference(), - authorization.authorizationReferenceFingerprint(), - reservationOwnerId, - reservationClaimFence, - gameSessionAttemptId, - gameSessionOwnerFence))); + var redemption = + withPeer( + GAME_SESSION_PEER_URI, + () -> + operatorAuthorization.redeem( + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + preAuthorizationTuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + recovered.operatorAuthorizationReference(), + recovered.authorizationReferenceFingerprint(), + reservationOwnerId, + reservationClaimFence, + gameSessionAttemptId, + gameSessionOwnerFence))); + assertThat(redemption.originalAccountPostAuthorizationTuple()) + .containsExactly(originalTuple.canonicalBytes()); var redeemed = account.tx(() -> operatorRepository.findByControlPlaneRequestId(requestId).orElseThrow()); @@ -252,6 +296,8 @@ void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() t assertThat(redeemed.redemptionOwnerAttemptId()).isEqualTo(gameSessionAttemptId); assertThat(redeemed.redemptionOwnerFence()).isEqualTo(gameSessionOwnerFence); assertThat(redeemed.issuanceFence()).isPositive(); + assertThat(redeemed.encryptedResponseEnvelope()) + .containsExactly(issuedRecord.encryptedResponseEnvelope()); var repository = new AccountStartSessionWorldParticipationRepository(account.dsl); var initialCapture = @@ -446,13 +492,13 @@ void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() t assertThatThrownBy(() -> account.tx(() -> repository.settleExact(conflictingTerminal))) .isInstanceOf(IllegalStateException.class) .hasMessage("StartSession World participation conflicts with its immutable binding"); - assertThatThrownBy( - () -> - account.dsl.execute( - "UPDATE account_start_session_world_participation_settlements " - + "SET outcome = 'ABORTED' WHERE participation_id = ?", - first.participationId())) - .isInstanceOf(RuntimeException.class); + assertGuardRejected( + () -> + account.dsl.execute( + "UPDATE account_start_session_world_participation_settlements " + + "SET outcome = 'ABORTED' WHERE participation_id = ?", + first.participationId()), + "StartSession World participation evidence is append-only"); assertThat( account.tx( () -> @@ -503,6 +549,31 @@ void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() t } } + private static void assertGuardRejected( + org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String expectedDiagnostic) { + assertThatThrownBy(action) + .satisfies( + failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Participation settlement guard rejection must be a PostgreSQL exception", + sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); + } + + private static SQLException findSqlException(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) return sqlException; + } + throw new AssertionError("Guard rejection must retain its SQL exception", failure); + } + private static Candidate candidate( StartSessionPostAuthorizationExecutionTuple originalTuple, AccountStartSessionAuthorityCapture capture, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientMtlsTest.java index a03fd598cc..3d32f7ecd5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientMtlsTest.java @@ -179,8 +179,6 @@ void rejectsMismatchedEchoUnknownFieldsAndStaleLeaseTimes() throws Exception { .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER) .build(), response -> response.toBuilder().setObservedAtEpochMillis(0L).build(), - response -> - response.toBuilder().setObservedAtEpochMillis(NOW_EPOCH_MILLIS + 1L).build(), response -> response.toBuilder() .setClaimExpiresAtEpochMillis(response.getObservedAtEpochMillis()) @@ -197,6 +195,24 @@ void rejectsMismatchedEchoUnknownFieldsAndStaleLeaseTimes() throws Exception { assertThat(handlerCalls).hasValue(invalidResponses.size()); } + @Test + void acceptsFutureObservationWhenProducerIntervalAndAccountExpiryAreLive() throws Exception { + startServer(pki.loggingAdminServer()); + client = newClient(pki.accountClient()); + client.init(); + responseMutation.set( + response -> response.toBuilder().setObservedAtEpochMillis(NOW_EPOCH_MILLIS + 1L).build()); + + ReadCurrentClaimEvidenceResponse evidence = + read(tuple(), StartSessionReservationEvidenceClient.Purpose.ISSUE); + + assertThat(evidence.getObservedAtEpochMillis()).isEqualTo(NOW_EPOCH_MILLIS + 1L); + assertThat(evidence.getClaimExpiresAtEpochMillis()) + .isGreaterThan(evidence.getObservedAtEpochMillis()) + .isGreaterThan(NOW_EPOCH_MILLIS); + assertThat(handlerCalls).hasValue(1); + } + @Test void rejectsInvalidInputBeforeAnyRpc() throws Exception { startServer(pki.loggingAdminServer()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java index 15769bc929..4e185fe238 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java @@ -8,21 +8,31 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import com.google.protobuf.ByteString; +import io.grpc.CallCredentials; +import io.grpc.ClientInterceptor; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.UUID; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -131,6 +141,75 @@ public > T customize(T stub) { } } + @Test + void acceptsFutureProducerObservationButStillRejectsClaimExpiredAtLocalNow( + @TempDir Path directory) throws Exception { + long localNow = CLOCK.millis(); + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + var stub = + mock( + StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub.class); + when(stub.withCallCredentials(any(CallCredentials.class))).thenReturn(stub); + when(stub.withInterceptors(any(ClientInterceptor[].class))).thenReturn(stub); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + ReadCurrentClaimEvidenceResponse futureObservation = + evidenceResponse(tuple, localNow + 1L, localNow + 30_000L); + ReadCurrentClaimEvidenceResponse expiresAtLocalNow = + evidenceResponse(tuple, localNow - 1L, localNow); + when(stub.readCurrentClaimEvidence(any())).thenReturn(futureObservation, expiresAtLocalNow); + + StartSessionReservationEvidenceClient client = + new StartSessionReservationEvidenceClient( + new ServiceEndpointsProperties(), + tlsProperties(directory), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + CLOCK); + var stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + + assertThat( + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isEqualTo(futureObservation); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or mismatched"); + } + + private static ReadCurrentClaimEvidenceResponse evidenceResponse( + StartSessionPreAuthorizationReservationTuple tuple, long observedAt, long expiresAt) { + return ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setMutationDigest(tuple.mutationDigest()) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(1L) + .setClaimOwnerId(RESERVATION_OWNER_ID.toString()) + .setClaimFence(1L) + .setObservedAtEpochMillis(observedAt) + .setClaimExpiresAtEpochMillis(expiresAt) + .setPurpose( + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) + .build(); + } + private static StartSessionReservationEvidenceClient newClient( GrpcChannelFactory channelFactory, CommonGrpcClientProperties tlsProperties) { return new StartSessionReservationEvidenceClient( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java index 147fa56e34..e597aa3c19 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java @@ -341,22 +341,7 @@ private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTup } private static byte[] accountProjection(StartSessionPostAuthorizationExecutionTuple tuple) { - StartSessionAuthorityEvidenceBundle bundle = - StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); - return AccountControlUiAuthority.canonical( - Map.of( - "projectionSchemaId", - "accountStartSessionRedemptionProjection", - "projectionSchemaVersion", - "1", - "authorizationReferenceFingerprint", - tuple.authorizationReferenceFingerprint(), - "authorityEvidenceBundle", - bundle.jsonValue(), - "issuanceOperationId", - bundle.issuanceOperationId().toString(), - "issuanceFence", - 9L)); + return tuple.canonicalBytes(); } private static String sha256Hex(byte[] bytes) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java index 4cb252a6ab..4e98f95cec 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java @@ -28,7 +28,6 @@ import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; -import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorityBundle; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; @@ -38,7 +37,11 @@ import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemRequest; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; @@ -68,6 +71,7 @@ class StartSessionOperatorAuthorizationGrpcServiceTest { UUID.fromString("43221254-3728-47a4-b15d-37542871e685"); private static final UUID ISSUANCE_OPERATION_ID = UUID.fromString("4fa8b657-c6ed-4797-b61d-66083f582198"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); private final AccountStartSessionOperatorAuthorizationService ownerService = mock(AccountStartSessionOperatorAuthorizationService.class); private final StartSessionOperatorAuthorizationGrpcService service = @@ -110,8 +114,13 @@ void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { when(ownerService.recover(any())).thenReturn(authorization); when(ownerService.redeem(any())) .thenReturn( - new RedemptionResult( - FINGERPRINT, bytes("redemption-bundle"), ISSUANCE_OPERATION_ID, 9L, true)); + new AccountStartSessionOperatorAuthorizationService.RedemptionResult( + FINGERPRINT, + authorization.authorityEvidenceBundle(), + ISSUANCE_OPERATION_ID, + 9L, + true, + authorization.originalAccountPostAuthorizationTuple())); TestObserver issueObserver = callIssue(issueRequest(tupleBytes), LOGGING_URI); @@ -123,7 +132,7 @@ void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { assertThat(issueObserver.value.getExpiresAt().getSeconds()) .isEqualTo(Instant.parse("2026-10-09T00:03:00Z").getEpochSecond()); assertThat(issueObserver.value.getAuthorityEvidenceBundle().toByteArray()) - .containsExactly(bytes("authority-bundle")); + .containsExactly(authorityBundleBytes()); assertThat(issueObserver.value.getBundleReference().getBundleVersion()) .isEqualTo(AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION); assertThat(issueObserver.value.getBundleReference().getSourceVersion()).isEqualTo("17"); @@ -131,6 +140,8 @@ void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { assertThat(issueObserver.value.getBundleReference().getLinearization()).isEqualTo("3"); assertThat(issueObserver.value.getAuthenticatedLoggingWorkloadIdentity()) .isEqualTo(LOGGING_URI); + assertThat(issueObserver.value.getOriginalAccountPostAuthorizationTuple().toByteArray()) + .containsExactly(authorization.originalAccountPostAuthorizationTuple()); var issueCaptor = org.mockito.ArgumentCaptor.forClass(IssueRequest.class); verify(ownerService).issue(issueCaptor.capture()); @@ -149,6 +160,8 @@ void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { .isEqualTo(AUTHORIZATION_REFERENCE); assertThat(recoverObserver.value.getAuthenticatedLoggingWorkloadIdentity()) .isEqualTo(LOGGING_URI); + assertThat(recoverObserver.value.getOriginalAccountPostAuthorizationTuple().toByteArray()) + .containsExactly(authorization.originalAccountPostAuthorizationTuple()); var recoverCaptor = org.mockito.ArgumentCaptor.forClass(RecoverRequest.class); verify(ownerService).recover(recoverCaptor.capture()); assertThat(recoverCaptor.getValue().canonicalTupleBytes()).containsExactly(tupleBytes); @@ -162,11 +175,13 @@ void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { assertThat(redeemObserver.failure).isNull(); assertThat(redeemObserver.value.getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); assertThat(redeemObserver.value.getAuthorityEvidenceBundle().toByteArray()) - .containsExactly(bytes("redemption-bundle")); + .containsExactly(authorityBundleBytes()); assertThat(redeemObserver.value.getIssuanceOperationId()) .isEqualTo(ISSUANCE_OPERATION_ID.toString()); assertThat(redeemObserver.value.getIssuanceFence()).isEqualTo(9L); assertThat(redeemObserver.value.getReplay()).isTrue(); + assertThat(redeemObserver.value.getOriginalAccountPostAuthorizationTuple().toByteArray()) + .containsExactly(authorization.originalAccountPostAuthorizationTuple()); var redeemCaptor = org.mockito.ArgumentCaptor.forClass(RedeemRequest.class); verify(ownerService).redeem(redeemCaptor.capture()); assertThat(redeemCaptor.getValue().canonicalTupleBytes()).containsExactly(tupleBytes); @@ -219,7 +234,7 @@ void readsExactRedeemedOperationProjectionWithoutCredentialMaterial() { assertThat(response.getBundleReference().getSourceFence()).isEqualTo("4"); assertThat(response.getBundleReference().getLinearization()).isEqualTo("3"); assertThat(response.getAuthorityEvidenceBundle().toByteArray()) - .containsExactly(bytes("authority-bundle")); + .containsExactly(authorityBundleBytes()); assertThat(response.toString()).doesNotContain(CONTROL_UI_JWT, AUTHORIZATION_REFERENCE); var readCaptor = @@ -514,7 +529,7 @@ private static RedeemedOperationProjection redeemedOperationProjection(byte[] tu 9L, new AccountStartSessionOperatorAuthorityBundle.BundleReference( AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION, "17", "4", "3"), - bytes("authority-bundle")); + authorityBundleBytes()); } private static byte[] canonicalTupleBytes() { @@ -522,7 +537,7 @@ private static byte[] canonicalTupleBytes() { new StartSessionOperatorAction( StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(TENANT_ID, "tenant-runtime"), + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), new StartSessionOperatorAction.Target(42L, TARGET_ACCOUNT_ID), StartSessionOperatorAction.ExpectedVersion.ABSENT, new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), @@ -534,13 +549,58 @@ private static byte[] canonicalTupleBytes() { } private static AuthorizationResponse authorizationResponse() { + byte[] bundleBytes = authorityBundleBytes(); + var bundleReference = + new AccountStartSessionOperatorAuthorityBundle.BundleReference( + AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION, "17", "4", "3"); + var tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(canonicalTupleBytes(), StandardCharsets.UTF_8)); + byte[] originalTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + LOGGING_URI, + FINGERPRINT, + RESERVATION_OWNER_ID, + 3L, + bundleBytes, + new StartSessionAuthorityEvidenceBundle.BundleReference( + bundleReference.bundleVersion(), + bundleReference.sourceVersion(), + bundleReference.sourceFence(), + bundleReference.linearization())) + .canonicalBytes(); return new AuthorizationResponse( AUTHORIZATION_REFERENCE, FINGERPRINT, Instant.parse("2026-10-09T00:03:00Z"), - bytes("authority-bundle"), - new AccountStartSessionOperatorAuthorityBundle.BundleReference( - AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION, "17", "4", "3")); + bundleBytes, + bundleReference, + originalTuple); + } + + private static byte[] authorityBundleBytes() { + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(canonicalTupleBytes(), StandardCharsets.UTF_8)); + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + ISSUANCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2026-10-09T00:00:00Z"), + Instant.parse("2026-10-09T00:03:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 9L, + TOKEN_JTI, + "2", + "3")); } private static UnknownFieldSet unknownFields() { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java index 5930ef7e95..6010c4aac7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java @@ -301,6 +301,16 @@ void successfulIssueLocksTheSameCommittedCaptureBeforeWritingIssuedRecord() { .isEqualTo( AccountStartSessionOperatorAuthorityBundle.fromSharedReference( harness.capture().bundleReference())); + var originalTuple = + StartSessionPostAuthorizationExecutionTuple.decode( + response.get().originalAccountPostAuthorizationTuple()); + assertThat(originalTuple.preAuthorizationTuple()).isEqualTo(harness.tuple()); + assertThat(originalTuple.authenticatedWorkloadIdentity()).isEqualTo(LOGGING_PEER); + assertThat(originalTuple.reservationOwnerId()).isEqualTo(harness.reservationOwnerId()); + assertThat(originalTuple.reservationClaimFence()).isEqualTo(10L); + assertThat(originalTuple.bundleReference().sourceFence()).isEqualTo("31"); + assertThat(Long.parseLong(originalTuple.issuanceFence())) + .isNotEqualTo(Long.parseLong(originalTuple.bundleReference().sourceFence())); var candidateCaptor = org.mockito.ArgumentCaptor.forClass( @@ -391,6 +401,8 @@ void exactIssueRetryAndRecoveryReturnStoredResponseWithoutReminting() { .containsExactly(harness.originalResponse().authorityEvidenceBundle()); assertThat(response.bundleReference()) .isEqualTo(harness.originalResponse().bundleReference()); + assertThat(response.originalAccountPostAuthorizationTuple()) + .containsExactly(harness.originalResponse().originalAccountPostAuthorizationTuple()); } assertThat(harness.randomCalls()).hasValue(0); verify(harness.repository(), never()).createOrReadExact(any()); @@ -1380,7 +1392,7 @@ void worldCurrentnessRejectsPostTupleFingerprintAndOwnerAttemptSubstitution() { } @Test - void expiredOrFutureOriginalClaimEvidenceStopsBeforeCaptureAndPrivateCrypto() { + void expiredOrContradictoryClaimEvidenceStopsButFutureObservationWithLiveExpiryIsAccepted() { MutableClock expiredClock = new MutableClock(NOW); IssueHarness expired = issueHarness(false, false, expiredClock, NOW.minusSeconds(1), NOW); loggingContext() @@ -1400,17 +1412,18 @@ void expiredOrFutureOriginalClaimEvidenceStopsBeforeCaptureAndPrivateCrypto() { MutableClock futureClock = new MutableClock(NOW); IssueHarness future = issueHarness(false, false, futureClock, NOW.plusSeconds(1), NOW.plusSeconds(30)); - loggingContext() - .run( - () -> - assertThatThrownBy(() -> future.service().issue(future.issueRequest())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("claim evidence is stale or contradictory")); - - assertThat(future.randomCalls()).hasValue(0); - verify(future.captureRepository(), never()) + AtomicReference + futureResponse = new AtomicReference<>(); + loggingContext().run(() -> futureResponse.set(future.service().issue(future.issueRequest()))); + + assertThat(futureResponse.get()).isNotNull(); + assertThat(futureResponse.get().expiresAt()).isEqualTo(NOW.plusSeconds(60)); + assertThat(futureResponse.get().originalAccountPostAuthorizationTuple()).isNotEmpty(); + assertThat(future.randomCalls()).hasValue(1); + verify(future.captureRepository()) .prepareOrReadExact(any(), any(), anyString(), any(), anyLong()); - verifyNoInteractions(future.fingerprintKeys(), future.responseCrypto()); + verify(future.fingerprintKeys()).fingerprintForIssue(any(), any()); + verify(future.responseCrypto()).encrypt(any(), any(), any()); verify(future.claims(), times(1)) .readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), eq(Purpose.ISSUE)); @@ -1588,9 +1601,18 @@ private static IssueHarness issueHarness( invocation -> { assertThat(invocation.getArgument(0)) .isEqualTo(ReferenceKind.HUMAN_OPERATOR); - assertThat(invocation.getArgument(1)) - .containsExactly("A".repeat(43).getBytes(StandardCharsets.US_ASCII)); - assertThat(invocation.getArgument(2)).isEqualTo(originalFingerprint); + String actualFingerprint = invocation.getArgument(2); + String freshFingerprint = "arfp/v1/test-key/" + "b".repeat(64); + assertThat(actualFingerprint).isIn(originalFingerprint, freshFingerprint); + // A fresh request can lose the create race and return the retained response. + byte[] expectedReference = + (actualFingerprint.equals(originalFingerprint) + ? "A".repeat(43) + : Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(fill(32, (byte) 0x5a))) + .getBytes(StandardCharsets.US_ASCII); + assertThat(invocation.getArgument(1)).containsExactly(expectedReference); assertThat(invocation.getArgument(3)).isEqualTo(NOW.plusSeconds(60)); assertThat(invocation.getArgument(4)).isEqualTo(NOW.plusSeconds(80)); return true; @@ -1808,6 +1830,13 @@ private static AuthorizationFixture originalAuthorizationFixture( "expiresAt", referenceExpiresAt.toString(), "authorityEvidenceBundle", bundle.jsonValue(), "bundleReference", bundle.referenceForCapture(capture).asJsonValue()); + assertThat(responseValue) + .containsOnlyKeys( + "operatorAuthorizationReference", + "authorizationReferenceFingerprint", + "expiresAt", + "authorityEvidenceBundle", + "bundleReference"); byte[] responseBytes = AccountControlUiAuthority.canonical(responseValue); var response = new AccountStartSessionOperatorAuthorizationService.AuthorizationResponse( @@ -1815,7 +1844,17 @@ private static AuthorizationFixture originalAuthorizationFixture( fingerprint, referenceExpiresAt, bundle.canonicalBytes(), - bundle.referenceForCapture(capture)); + bundle.referenceForCapture(capture), + StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + LOGGING_PEER, + fingerprint, + reservationOwnerId, + 10L, + bundle.canonicalBytes(), + AccountStartSessionOperatorAuthorityBundle.toSharedReference( + bundle.referenceForCapture(capture))) + .canonicalBytes()); var record = new IssuanceRecord( tuple.controlPlaneRequestId(), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java index c0ed07f307..00e970b236 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java @@ -290,6 +290,24 @@ void rejectsChangedAccountRedemptionProjectionBeforeCurrentnessOrWrites() { assertThat(harness.readbackTransactions.begins).isZero(); } + @Test + void rejectsLegacyScalarProjectionBeforeCurrentnessOrWrites() { + Harness harness = new Harness(); + harness.configureClientResult(legacyScalarProjection(harness.tuple)); + + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> harness.service.acquire(request(null)))); + + assertThat(harness.steps).containsExactly("remote-read"); + verify(harness.issuer, times(0)) + .withCurrentWorldReceivingParticipationCurrentness( + any(byte[].class), eq(GAME_SESSION_ATTEMPT_ID), eq(GAME_SESSION_FENCE), any()); + verifyNoInteractions(harness.participationRepository); + verifyNoInteractions(harness.attemptEvidenceRepository); + assertThat(harness.readbackTransactions.begins).isZero(); + } + @Test void rejectsChangedCommittedSourceVectorDuringIndependentReadbackWithoutRetryWrite() { Harness harness = new Harness(); @@ -445,6 +463,21 @@ private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTup private static byte[] projection( StartSessionPostAuthorizationExecutionTuple tuple, Map additionalFields) { + if (additionalFields.isEmpty()) { + return tuple.canonicalBytes(); + } + @SuppressWarnings("unchecked") + Map tupleValue = JSON.readValue(tuple.canonicalBytes(), Map.class); + var changed = new java.util.LinkedHashMap<>(tupleValue); + changed.putAll(additionalFields); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(changed)); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static byte[] legacyScalarProjection(StartSessionPostAuthorizationExecutionTuple tuple) { var bundle = StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); Map projection = Map.of( @@ -454,17 +487,8 @@ private static byte[] projection( "authorityEvidenceBundle", bundle.jsonValue(), "issuanceOperationId", bundle.issuanceOperationId().toString(), "issuanceFence", Long.parseLong(tuple.issuanceFence())); - if (additionalFields.isEmpty()) { - try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); - } catch (java.io.IOException impossible) { - throw new IllegalStateException(impossible); - } - } - var changed = new java.util.LinkedHashMap<>(projection); - changed.putAll(additionalFields); try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(changed)); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); } catch (java.io.IOException impossible) { throw new IllegalStateException(impossible); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest.java index 338f6d5365..702d7b45f1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadGrpcServiceTest.java @@ -4,14 +4,23 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; +import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; import io.grpc.Context; import io.grpc.Status; import io.grpc.stub.StreamObserver; +import java.time.Instant; +import java.util.UUID; import java.util.function.Consumer; import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationRequest; import net.firedevops.firemud.account.v1.ReadHistoricalStartSessionWorldParticipationResponse; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.security.SessionContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -75,8 +84,7 @@ void bindsConfiguredNamespaceBeforeClosedRequestCodecAndRejectsUnknownOrWrongVer .setSchemaVersion(1) .setReadRequestId("d1f41bfb-265a-4f3b-8b2a-124cba20ce43") .setTargetNamespace("other-runtime") - .setAccountWorldParticipationId("a8c1e8c8-f237-41b7-918d-ec2281bcac10") - .setAccountWorldParticipationFence(31L) + .setOriginalPostAuthorizationTuple(ByteString.copyFrom(originalTupleBytes())) .build(); var wrongVersion = validWire().toBuilder().setSchemaVersion(2).build(); UnknownFieldSet unknown = @@ -123,11 +131,61 @@ private static ReadHistoricalStartSessionWorldParticipationRequest validWire() { .setSchemaVersion(1) .setReadRequestId("d1f41bfb-265a-4f3b-8b2a-124cba20ce43") .setTargetNamespace(NAMESPACE) - .setAccountWorldParticipationId("a8c1e8c8-f237-41b7-918d-ec2281bcac10") - .setAccountWorldParticipationFence(31L) + .setOriginalPostAuthorizationTuple(ByteString.copyFrom(originalTupleBytes())) .build(); } + private static byte[] originalTupleBytes() { + UUID tenantId = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + UUID actorId = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + UUID targetAccountId = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "historical-read-wire-original", + actorId, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, NAMESPACE), + new StartSessionOperatorAction.Target(91L, targetAccountId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "historical read wire test")); + byte[] bundle = + StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + preTuple, + new Values( + UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2026-10-09T00:00:00Z"), + Instant.parse("2026-10-09T00:03:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + bundle, + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")) + .canonicalBytes(); + } + private void invoke( ReadHistoricalStartSessionWorldParticipationRequest request, StreamObserver observer) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java index 5650893e1b..8ac8b4508e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -12,7 +13,9 @@ import io.grpc.Status; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; +import java.time.Instant; import java.time.OffsetDateTime; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; @@ -22,8 +25,9 @@ import net.firedevops.firemud.accountservice.repository.AccountStartSessionWorldParticipationRepository.StoredParticipation; import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationHistoricalReadRequest; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; @@ -34,7 +38,6 @@ import org.springframework.transaction.support.AbstractPlatformTransactionManager; import org.springframework.transaction.support.DefaultTransactionStatus; import org.springframework.transaction.support.TransactionSynchronizationManager; -import tools.jackson.databind.json.JsonMapper; /** Mocked owner-storage boundary only; no PostgreSQL or authenticated Game Session proof. */ class AccountStartSessionWorldParticipationHistoricalReadServiceTest { @@ -47,7 +50,6 @@ class AccountStartSessionWorldParticipationHistoricalReadServiceTest { private static final long GAME_SESSION_FENCE = 37L; private static final String PREPARATION_INPUT = "{ \"historical\" : \"retained exactly\", \"revision\": 1 }\n"; - private static final JsonMapper JSON = JsonMapper.builder().build(); private final AccountStartSessionWorldParticipationRepository repository = mock(AccountStartSessionWorldParticipationRepository.class); @@ -96,7 +98,8 @@ void deniesAmbientSqlOrSynchronizationBeforeValidatingRequestOrStartingOwnerTran void readsExactHistoryAfterIngressExpiryAndPriorSettlementWithoutCurrentnessOrMutation() throws Exception { StoredParticipation expired = participation(true); - when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + when(repository.findHistoricalForOriginalTuple( + argThat(bytes -> Arrays.equals(bytes, originalTupleBytes())))) .thenAnswer( call -> { assertWritableReadCommittedTransaction(); @@ -112,8 +115,10 @@ void readsExactHistoryAfterIngressExpiryAndPriorSettlementWithoutCurrentnessOrMu var evidence = authorized(() -> service.read(request())); assertThat(evidence.request()).isEqualTo(request()); - assertThat(evidence.originalPostAuthorizationTuple()) + assertThat(evidence.request().originalPostAuthorizationTuple()) .containsExactly(expired.originalPostAuthorizationTuple()); + assertThat(evidence.accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(evidence.accountWorldParticipationFence()).isEqualTo(PARTICIPATION_FENCE); assertThat(evidence.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); assertThat(evidence.gameSessionOwnerFence()).isEqualTo(GAME_SESSION_FENCE); assertThat(evidence.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); @@ -122,13 +127,16 @@ void readsExactHistoryAfterIngressExpiryAndPriorSettlementWithoutCurrentnessOrMu assertThat(transactions.begins).isEqualTo(1); assertThat(transactions.commits).isEqualTo(1); assertNoSql(); - verify(repository).findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE); + verify(repository) + .findHistoricalForOriginalTuple( + argThat(bytes -> Arrays.equals(bytes, originalTupleBytes()))); verifyNoMoreInteractions(repository); } @Test - void absentMismatchedNamespaceAndMismatchedRetainedIdentityFailClosed() { - when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + void absentMismatchedNamespaceAndMismatchedOriginalTupleFailClosed() { + when(repository.findHistoricalForOriginalTuple( + argThat(bytes -> Arrays.equals(bytes, originalTupleBytes())))) .thenReturn(Optional.empty()); assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.read(request()))); assertThat(transactions.commits).isZero(); @@ -136,7 +144,8 @@ void absentMismatchedNamespaceAndMismatchedRetainedIdentityFailClosed() { TransactionSynchronizationManager.clear(); transactions.resetCounts(); - when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + when(repository.findHistoricalForOriginalTuple( + argThat(bytes -> Arrays.equals(bytes, originalTupleBytes())))) .thenReturn( Optional.of( participation(false, "other-runtime", PARTICIPATION_ID, PARTICIPATION_FENCE))); @@ -145,7 +154,8 @@ void absentMismatchedNamespaceAndMismatchedRetainedIdentityFailClosed() { TransactionSynchronizationManager.clear(); transactions.resetCounts(); - when(repository.findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) + when(repository.findHistoricalForOriginalTuple( + argThat(bytes -> Arrays.equals(bytes, originalTupleBytes())))) .thenReturn( Optional.of( participation(false, NAMESPACE, PARTICIPATION_ID, PARTICIPATION_FENCE + 1L))); @@ -159,14 +169,21 @@ void absentMismatchedNamespaceAndMismatchedRetainedIdentityFailClosed() { () -> service.read( new AccountStartSessionWorldParticipationHistoricalReadRequest( - READ_ID, "other-runtime", PARTICIPATION_ID, PARTICIPATION_FENCE)))); + READ_ID, + "other-runtime", + originalTuple("other-runtime", true).canonicalBytes())))); verify(repository, org.mockito.Mockito.times(3)) - .findHistoricalExact(PARTICIPATION_ID, PARTICIPATION_FENCE); + .findHistoricalForOriginalTuple( + argThat(bytes -> Arrays.equals(bytes, originalTupleBytes()))); + } + + private static byte[] originalTupleBytes() { + return originalTuple(NAMESPACE, true).canonicalBytes(); } private AccountStartSessionWorldParticipationHistoricalReadRequest request() { return new AccountStartSessionWorldParticipationHistoricalReadRequest( - READ_ID, NAMESPACE, PARTICIPATION_ID, PARTICIPATION_FENCE); + READ_ID, NAMESPACE, originalTupleBytes()); } private static StoredParticipation participation(boolean expired) { @@ -228,85 +245,24 @@ private static StartSessionPostAuthorizationExecutionTuple originalTuple( private static byte[] authorityBundle( StartSessionPreAuthorizationReservationTuple tuple, boolean expired) { - String actorId = tuple.actor().accountId().toString(); - String tenantId = tuple.action().scope().tenantId().toString(); - Map projection = - Map.of( - "sourceType", - "ACCOUNT", - "sourceEvidenceId", + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), "sha256:" + "a".repeat(64), - "sourceEvidenceVersion", "17", - "projectionStatus", "CURRENT", - "evaluatedAt", - expired ? "2020-01-01T00:00:00Z" : "2026-10-09T00:00:00Z", - "expiresAt", - expired ? "2020-01-02T00:00:00Z" : "2026-10-10T00:00:00Z"); - Map operation = - Map.of( - "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", - "controlPlaneRequestId", tuple.controlPlaneRequestId(), - "actionFamilyRequestIdentity", - Map.of( - "requestIdentityKind", - "controlPlaneRequestId", - "requestId", - tuple.controlPlaneRequestId()), - "mutationDigest", tuple.mutationDigest()); - Map authority = - Map.of( - "issuerAuthGeneration", 1L, - "accountAuthorityGeneration", 2L, - "tenantAuthorityGeneration", Map.of(tenantId, 3L), - "membershipAuthorityGeneration", Map.of(tenantId, 4L), - "privateRealmGrantVersions", List.of()); - Map human = - Map.of( - "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, - "actorAccountId", actorId, - "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", - "role", "tenantAdmin", - "accountGeneration", "2", - "tenantGeneration", "3"); - Map value = - Map.of( - "bundleVersion", - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "authorityScope", - Map.of( - "scope", - Map.of( - "tenantId", - tenantId, - "targetNamespace", - tuple.action().scope().targetNamespace()), - "actionFamily", - tuple.actionFamily(), - "applicableAccountId", - actorId, - "applicableTenantId", - tenantId), - "accountProjectionEvidence", - projection, - "issuanceOperationIdentity", - operation, - "issuanceKind", - "human_operator", - "authorityTuple", - authority, - "membershipVersion", - Map.of(tenantId, 5L), - "issuanceFence", - "23", - "issuanceEvidence", - human); - try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); - } catch (java.io.IOException impossible) { - throw new IllegalStateException(impossible); - } + Instant.parse(expired ? "2020-01-01T00:00:00Z" : "2026-10-09T00:00:00Z"), + Instant.parse(expired ? "2020-01-02T00:00:00Z" : "2026-10-10T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); } private static T authorized(Supplier action) { diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java index 728895fda0..103212d324 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -163,7 +163,9 @@ public OwnerClaim reserve(StartSessionPostAuthorizationExecutionTuple originalTu @Override public void attachAccountRedemptionProjection( - OwnerClaim ownerClaim, StartSessionPostAuthorizationExecutionTuple originalTuple) { + OwnerClaim ownerClaim, + StartSessionPostAuthorizationExecutionTuple originalTuple, + byte[] originalAccountPostAuthorizationTuple) { // Existing callers may continue to use this fixture with a stipulated owner attempt. } }); @@ -241,7 +243,8 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( directAuthorization.bundleReference().bundleVersion(), directAuthorization.bundleReference().sourceVersion(), directAuthorization.bundleReference().sourceFence(), - directAuthorization.bundleReference().linearization())); + directAuthorization.bundleReference().linearization()), + directAuthorization.originalAccountPostAuthorizationTuple()); } else { authorization = Objects.requireNonNull( @@ -250,25 +253,24 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( "Authenticated Account issue transport returned no authorization"); } - var sharedReference = authorization.bundleReference(); - var originalTuple = - StartSessionPostAuthorizationExecutionTuple.createHuman( + byte[] originalAccountPostAuthorizationTuple = + authorization.originalAccountPostAuthorizationTuple(); + StartSessionPostAuthorizationExecutionTuple originalTuple = + requireIssuedTupleBinding( preTuple, - loggingPeerUri, - authorization.authorizationReferenceFingerprint(), + authorization, + originalAccountPostAuthorizationTuple, reservationOwnerId, - reservationClaimFence, - authorization.authorityEvidenceBundle(), - sharedReference); + reservationClaimFence); OwnerClaim ownerClaim = Objects.requireNonNull( ownerAttemptLifecycle.reserve(originalTuple), "Game Session owner attempt reservation returned no claim"); - boolean replay; + AccountStartSessionOperatorAuthorizationService.RedemptionResult redemption; if (transport == null) { - var redemption = + redemption = withPeer( gameSessionPeerUri, () -> @@ -281,14 +283,35 @@ public synchronized OriginalStartSession issueAndRedeemOriginal( reservationClaimFence, ownerClaim.ownerAttemptId(), ownerClaim.ownerFence()))); - replay = redemption.replay(); } else { - replay = - transport.redeem( - preTupleBytes, authorization, reservationOwnerId, reservationClaimFence, ownerClaim); + redemption = + Objects.requireNonNull( + transport.redeem( + preTupleBytes, + authorization, + reservationOwnerId, + reservationClaimFence, + ownerClaim), + "Authenticated Account redemption transport returned no result"); + } + var issuedBundle = + StartSessionAuthorityEvidenceBundle.decode(authorization.authorityEvidenceBundle()); + if (!authorization + .authorizationReferenceFingerprint() + .equals(redemption.authorizationReferenceFingerprint()) + || !Arrays.equals( + authorization.authorityEvidenceBundle(), redemption.authorityEvidenceBundle()) + || !issuedBundle.issuanceOperationId().equals(redemption.issuanceOperationId()) + || !issuedBundle.issuanceFence().equals(Long.toString(redemption.issuanceFence()))) { + throw new IllegalStateException( + "Account redemption response differs from the exact issued tuple" + + " or authorization evidence"); } - assertThat(replay).isFalse(); - ownerAttemptLifecycle.attachAccountRedemptionProjection(ownerClaim, originalTuple); + assertThat(redemption.originalAccountPostAuthorizationTuple()) + .containsExactly(originalAccountPostAuthorizationTuple); + assertThat(redemption.replay()).isFalse(); + ownerAttemptLifecycle.attachAccountRedemptionProjection( + ownerClaim, originalTuple, originalAccountPostAuthorizationTuple.clone()); var retained = accountSources.tx( @@ -487,8 +510,11 @@ public UUID creatorAccountId() { public interface OwnerAttemptLifecycle { OwnerClaim reserve(StartSessionPostAuthorizationExecutionTuple originalTuple); + /** Receives the exact ISSUE tuple bytes after Account's REDEEM tuple echo has been compared. */ void attachAccountRedemptionProjection( - OwnerClaim ownerClaim, StartSessionPostAuthorizationExecutionTuple originalTuple); + OwnerClaim ownerClaim, + StartSessionPostAuthorizationExecutionTuple originalTuple, + byte[] originalAccountPostAuthorizationTuple); } /** Authenticated issue and redemption calls used by a composed transport proof. */ @@ -499,7 +525,7 @@ IssuedAuthorization issue( UUID reservationOwnerId, long reservationClaimFence); - boolean redeem( + AccountStartSessionOperatorAuthorizationService.RedemptionResult redeem( byte[] canonicalPreAuthorizationTupleBytes, IssuedAuthorization authorization, UUID reservationOwnerId, @@ -507,12 +533,13 @@ boolean redeem( OwnerClaim ownerClaim); } - /** Exact Account issue response fields needed to form the original execution tuple. */ + /** Account issue response fields and exact independently returned original owner tuple. */ public record IssuedAuthorization( String operatorAuthorizationReference, String authorizationReferenceFingerprint, byte[] authorityEvidenceBundle, - StartSessionAuthorityEvidenceBundle.BundleReference bundleReference) { + StartSessionAuthorityEvidenceBundle.BundleReference bundleReference, + byte[] originalAccountPostAuthorizationTuple) { public IssuedAuthorization { Objects.requireNonNull(operatorAuthorizationReference, "Account reference is required"); Objects.requireNonNull( @@ -521,12 +548,46 @@ public record IssuedAuthorization( Objects.requireNonNull(authorityEvidenceBundle, "Account authority bundle is required") .clone(); Objects.requireNonNull(bundleReference, "Account bundle reference is required"); + originalAccountPostAuthorizationTuple = + Objects.requireNonNull( + originalAccountPostAuthorizationTuple, "Account original owner tuple is required") + .clone(); } @Override public byte[] authorityEvidenceBundle() { return authorityEvidenceBundle.clone(); } + + @Override + public byte[] originalAccountPostAuthorizationTuple() { + return originalAccountPostAuthorizationTuple.clone(); + } + } + + private StartSessionPostAuthorizationExecutionTuple requireIssuedTupleBinding( + StartSessionPreAuthorizationReservationTuple preTuple, + IssuedAuthorization authorization, + byte[] exactAccountTupleBytes, + UUID reservationOwnerId, + long reservationClaimFence) { + StartSessionPostAuthorizationExecutionTuple accountTuple = + StartSessionPostAuthorizationExecutionTuple.decode(exactAccountTupleBytes); + if (!Arrays.equals(accountTuple.canonicalBytes(), exactAccountTupleBytes) + || !preTuple.canonicalJson().equals(accountTuple.preAuthorizationTuple().canonicalJson()) + || !loggingPeerUri.equals(accountTuple.authenticatedWorkloadIdentity()) + || !authorization + .authorizationReferenceFingerprint() + .equals(accountTuple.authorizationReferenceFingerprint()) + || !reservationOwnerId.equals(accountTuple.reservationOwnerId()) + || reservationClaimFence != accountTuple.reservationClaimFence() + || !Arrays.equals( + authorization.authorityEvidenceBundle(), accountTuple.authorityEvidenceBundleBytes()) + || !authorization.bundleReference().equals(accountTuple.bundleReference())) { + throw new IllegalStateException( + "Account's exact issued owner tuple differs from the original request or response"); + } + return accountTuple; } /** Non-secret owner identities needed by Account redemption and acquisition. */ diff --git a/services/common-platform-core/build.gradle.kts b/services/common-platform-core/build.gradle.kts index 7a433ad11a..500cce749d 100644 --- a/services/common-platform-core/build.gradle.kts +++ b/services/common-platform-core/build.gradle.kts @@ -1,5 +1,6 @@ plugins { `java-library` + `java-test-fixtures` } apply(from = "${rootDir}/gradle/proto-convention.gradle") @@ -28,4 +29,6 @@ dependencies { testImplementation(libs.grpc.spring.boot.starter) testImplementation(libs.spring.boot.starter.test) testImplementation(testFixtures(project(":common-test-support"))) + testFixturesApi(platform(libs.spring.boot.dependencies)) + testFixturesApi("tools.jackson.core:jackson-databind") } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java index 74ce234a98..568f7ca3b0 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClient.java @@ -18,7 +18,8 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; /** - * Explicit file-backed mTLS client for Account's unregistered historical World participation read. + * Explicit file-backed mTLS client for Account's unregistered historical World participation lookup + * by the complete unchanged original StartSession tuple. */ public final class AccountStartSessionWorldParticipationHistoricalReadClient extends AbstractReloadingBlockingGrpcClient< @@ -59,7 +60,10 @@ public synchronized void init() throws SSLException, IOException { initialized = true; } - /** Reads only the exact retained Account row; it does not admit or renew World execution. */ + /** + * Resolves retained participation coordinates from the exact original tuple; this does not admit + * or renew World execution. + */ public AccountStartSessionWorldParticipationHistoricalReadEvidence read( AccountStartSessionWorldParticipationHistoricalReadRequest request) { Objects.requireNonNull(request, "historical participation request is required"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadEvidence.java index f263bc9aad..200500dd34 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadEvidence.java @@ -2,18 +2,16 @@ import java.util.Objects; import java.util.UUID; -import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminalReadRequest; -/** - * Account-derived immutable historical participation fields for exact World reconciliation. - * - *

This carrier is not currentness, admission, producer authentication, or renewed permission. - */ +/** Account-derived immutable historical participation fields for exact World reconciliation. */ public final class AccountStartSessionWorldParticipationHistoricalReadEvidence { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private final AccountStartSessionWorldParticipationHistoricalReadRequest request; - private final byte[] originalPostAuthorizationTuple; + private final UUID accountWorldParticipationId; + private final long accountWorldParticipationFence; private final UUID gameSessionOwnerAttemptId; private final long gameSessionOwnerFence; private final UUID canonicalGameInstanceId; @@ -22,28 +20,28 @@ public final class AccountStartSessionWorldParticipationHistoricalReadEvidence { public AccountStartSessionWorldParticipationHistoricalReadEvidence( AccountStartSessionWorldParticipationHistoricalReadRequest request, - byte[] originalPostAuthorizationTuple, + UUID accountWorldParticipationId, + long accountWorldParticipationFence, UUID gameSessionOwnerAttemptId, long gameSessionOwnerFence, UUID canonicalGameInstanceId, String preparationInputJson, String preparationInputDigest) { this.request = Objects.requireNonNull(request, "historical participation request is required"); - Objects.requireNonNull(originalPostAuthorizationTuple, "original tuple is required"); - if (originalPostAuthorizationTuple.length == 0 - || originalPostAuthorizationTuple.length - > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { - throw new IllegalArgumentException("Original StartSession tuple is missing or oversized"); + this.accountWorldParticipationId = + requireNonNil(accountWorldParticipationId, "accountWorldParticipationId"); + if (accountWorldParticipationFence <= 0L) { + throw new IllegalArgumentException("Account World participation fence must be positive"); } - this.originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + this.accountWorldParticipationFence = accountWorldParticipationFence; this.gameSessionOwnerAttemptId = - Objects.requireNonNull(gameSessionOwnerAttemptId, "Game Session attempt is required"); + requireNonNil(gameSessionOwnerAttemptId, "gameSessionOwnerAttemptId"); if (gameSessionOwnerFence <= 0L) { throw new IllegalArgumentException("Game Session owner fence must be positive"); } this.gameSessionOwnerFence = gameSessionOwnerFence; this.canonicalGameInstanceId = - Objects.requireNonNull(canonicalGameInstanceId, "canonical Game Instance ID is required"); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); this.preparationInputJson = Objects.requireNonNull(preparationInputJson, "exact preparation input is required"); this.preparationInputDigest = @@ -55,9 +53,9 @@ public AccountStartSessionWorldParticipationHistoricalReadEvidence( new WorldStartSessionExecutionTerminalReadRequest( request.readRequestId(), request.targetNamespace(), - this.originalPostAuthorizationTuple, - request.accountWorldParticipationId(), - request.accountWorldParticipationFence(), + request.originalPostAuthorizationTuple(), + this.accountWorldParticipationId, + this.accountWorldParticipationFence, this.gameSessionOwnerAttemptId, this.gameSessionOwnerFence, this.canonicalGameInstanceId, @@ -77,8 +75,12 @@ public AccountStartSessionWorldParticipationHistoricalReadRequest request() { return request; } - public byte[] originalPostAuthorizationTuple() { - return originalPostAuthorizationTuple.clone(); + public UUID accountWorldParticipationId() { + return accountWorldParticipationId; + } + + public long accountWorldParticipationFence() { + return accountWorldParticipationFence; } public UUID gameSessionOwnerAttemptId() { @@ -106,6 +108,16 @@ public String preparationInputDigest() { public String toString() { return "AccountStartSessionWorldParticipationHistoricalReadEvidence[request=" + request + + ", accountWorldParticipationId=" + + accountWorldParticipationId + ", preparationInput=]"; } + + private static UUID requireNonNil(UUID value, String field) { + Objects.requireNonNull(value, field); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical non-nil UUID"); + } + return value; + } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.java index dee08b1460..e8677558c1 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.java @@ -11,7 +11,8 @@ /** Closed protobuf adapter for Account's historical World participation read. */ public final class AccountStartSessionWorldParticipationHistoricalReadGrpcCodec { - public static final int MAX_REQUEST_WIRE_BYTES = 1024; + public static final int MAX_REQUEST_WIRE_BYTES = + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + 1024; public static final int MAX_RESPONSE_WIRE_BYTES = WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES @@ -30,8 +31,8 @@ public static ReadHistoricalStartSessionWorldParticipationRequest toRequest( AccountStartSessionWorldParticipationHistoricalReadRequest.SCHEMA_VERSION) .setReadRequestId(request.readRequestId().toString()) .setTargetNamespace(request.targetNamespace()) - .setAccountWorldParticipationId(request.accountWorldParticipationId().toString()) - .setAccountWorldParticipationFence(request.accountWorldParticipationFence()) + .setOriginalPostAuthorizationTuple( + ByteString.copyFrom(request.originalPostAuthorizationTuple())) .build(); if (result.getSerializedSize() > MAX_REQUEST_WIRE_BYTES) { throw new IllegalArgumentException("Historical participation request exceeds its wire limit"); @@ -52,8 +53,7 @@ public static AccountStartSessionWorldParticipationHistoricalReadRequest fromReq return new AccountStartSessionWorldParticipationHistoricalReadRequest( canonicalUuid(request.getReadRequestId(), "readRequestId"), request.getTargetNamespace(), - canonicalUuid(request.getAccountWorldParticipationId(), "accountWorldParticipationId"), - request.getAccountWorldParticipationFence()); + request.getOriginalPostAuthorizationTuple().toByteArray()); } public static ReadHistoricalStartSessionWorldParticipationResponse toResponse( @@ -64,13 +64,13 @@ public static ReadHistoricalStartSessionWorldParticipationResponse toResponse( var response = ReadHistoricalStartSessionWorldParticipationResponse.newBuilder() .setRequest(toRequest(request)) - .setOriginalPostAuthorizationTuple( - ByteString.copyFrom(evidence.originalPostAuthorizationTuple())) .setGameSessionOwnerAttemptId(evidence.gameSessionOwnerAttemptId().toString()) .setGameSessionOwnerFence(evidence.gameSessionOwnerFence()) .setCanonicalGameInstanceId(evidence.canonicalGameInstanceId().toString()) .setPreparationInputJson(evidence.preparationInputJson()) .setPreparationInputDigest(evidence.preparationInputDigest()) + .setAccountWorldParticipationId(evidence.accountWorldParticipationId().toString()) + .setAccountWorldParticipationFence(evidence.accountWorldParticipationFence()) .build(); if (response.getSerializedSize() > MAX_RESPONSE_WIRE_BYTES) { throw new IllegalArgumentException( @@ -91,19 +91,14 @@ public static AccountStartSessionWorldParticipationHistoricalReadEvidence fromRe AccountStartSessionWorldParticipationHistoricalReadRequest echoedRequest = fromRequest(response.getRequest()); requireSameRequest(request, echoedRequest); - byte[] originalTuple = response.getOriginalPostAuthorizationTuple().toByteArray(); - if (originalTuple.length == 0 - || originalTuple.length - > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { - throw new IllegalArgumentException("Original StartSession tuple is missing or oversized"); - } if (response.getPreparationInputJson().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES) { throw new IllegalArgumentException("Historical preparation input exceeds its byte limit"); } return new AccountStartSessionWorldParticipationHistoricalReadEvidence( echoedRequest, - originalTuple, + canonicalUuid(response.getAccountWorldParticipationId(), "accountWorldParticipationId"), + response.getAccountWorldParticipationFence(), canonicalUuid(response.getGameSessionOwnerAttemptId(), "gameSessionOwnerAttemptId"), response.getGameSessionOwnerFence(), canonicalUuid(response.getCanonicalGameInstanceId(), "canonicalGameInstanceId"), diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadRequest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadRequest.java index a9e1359062..b281971b9f 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadRequest.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadRequest.java @@ -1,39 +1,100 @@ package net.firedevops.firemud.common.account.startsession; +import java.util.Arrays; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; -/** Exact lookup identity for one historical Account World StartSession participation. */ -public record AccountStartSessionWorldParticipationHistoricalReadRequest( - UUID readRequestId, - String targetNamespace, - UUID accountWorldParticipationId, - long accountWorldParticipationFence) { +/** Exact original-operation identity for one historical Account World participation lookup. */ +public final class AccountStartSessionWorldParticipationHistoricalReadRequest { public static final int SCHEMA_VERSION = 1; private static final UUID NIL_UUID = new UUID(0L, 0L); - public AccountStartSessionWorldParticipationHistoricalReadRequest { - requireNonNil(readRequestId, "readRequestId"); + private final UUID readRequestId; + private final String targetNamespace; + private final byte[] originalPostAuthorizationTuple; + private final StartSessionPostAuthorizationExecutionTuple decodedOriginalTuple; + + public AccountStartSessionWorldParticipationHistoricalReadRequest( + UUID readRequestId, String targetNamespace, byte[] originalPostAuthorizationTuple) { + this.readRequestId = requireNonNil(readRequestId, "readRequestId"); if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); } - Objects.requireNonNull(accountWorldParticipationId, "accountWorldParticipationId"); - if (NIL_UUID.equals(accountWorldParticipationId)) { + this.targetNamespace = targetNamespace; + Objects.requireNonNull(originalPostAuthorizationTuple, "original tuple is required"); + if (originalPostAuthorizationTuple.length == 0 + || originalPostAuthorizationTuple.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { throw new IllegalArgumentException( - "accountWorldParticipationId must be a canonical non-nil UUID"); + "Complete original StartSession tuple is empty or oversized"); } - if (readRequestId.equals(accountWorldParticipationId)) { + this.originalPostAuthorizationTuple = originalPostAuthorizationTuple.clone(); + this.decodedOriginalTuple = + StartSessionPostAuthorizationExecutionTuple.decode(this.originalPostAuthorizationTuple); + if (!Arrays.equals( + this.originalPostAuthorizationTuple, this.decodedOriginalTuple.canonicalBytes()) + || !StartSessionOperatorAction.ACTION_FAMILY.equals( + this.decodedOriginalTuple.preAuthorizationTuple().actionFamily()) + || !StartSessionOperatorAction.OWNER_SERVICE.equals( + this.decodedOriginalTuple.preAuthorizationTuple().targetOwner()) + || !targetNamespace.equals( + this.decodedOriginalTuple.preAuthorizationTuple().action().scope().targetNamespace())) { throw new IllegalArgumentException( - "readRequestId must be fresh and distinct from the participation ID"); + "Complete canonical tuple must identify the original StartSession for this namespace"); } - if (accountWorldParticipationFence <= 0L) { + + if (this.readRequestId.equals(this.decodedOriginalTuple.reservationOwnerId())) { throw new IllegalArgumentException( - "accountWorldParticipationFence must be a positive signed 64-bit integer"); + "readRequestId must be fresh and distinct from the reservation owner"); } } + public UUID readRequestId() { + return readRequestId; + } + + public String targetNamespace() { + return targetNamespace; + } + + public byte[] originalPostAuthorizationTuple() { + return originalPostAuthorizationTuple.clone(); + } + + public StartSessionPostAuthorizationExecutionTuple decodedOriginalTuple() { + return decodedOriginalTuple; + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof AccountStartSessionWorldParticipationHistoricalReadRequest that)) { + return false; + } + return readRequestId.equals(that.readRequestId) + && targetNamespace.equals(that.targetNamespace) + && Arrays.equals(originalPostAuthorizationTuple, that.originalPostAuthorizationTuple); + } + + @Override + public int hashCode() { + return 31 * Objects.hash(readRequestId, targetNamespace) + + Arrays.hashCode(originalPostAuthorizationTuple); + } + + @Override + public String toString() { + return "AccountStartSessionWorldParticipationHistoricalReadRequest[readRequestId=" + + readRequestId + + ", targetNamespace=" + + targetNamespace + + ", originalTuple=]"; + } + private static UUID requireNonNil(UUID value, String field) { Objects.requireNonNull(value, field); if (NIL_UUID.equals(value)) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.java index 5c6f4335f1..870697565d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/StartSessionAccountRedemptionProjection.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.common.account.startsession; import java.io.IOException; +import java.util.Arrays; import java.util.Map; import java.util.Objects; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; @@ -8,22 +9,77 @@ import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import tools.jackson.databind.json.JsonMapper; -/** Canonical full Account projection used by original StartSession redemption. */ +/** Retained original Account tuple evidence for StartSession redemption. */ public final class StartSessionAccountRedemptionProjection { private static final JsonMapper JSON = JsonMapper.builder().build(); private StartSessionAccountRedemptionProjection() {} /** - * Derives the complete canonical Account redemption projection from the original tuple. + * Retains the complete canonical tuple returned by Account without duplicating its bundle. * - *

The issuance fence remains a JSON number, matching the original projection bytes. This value - * proves integrity and tuple binding only; it does not establish Account authentication, - * currentness, or a live reservation claim. + *

Account authentication and provenance must be established by the receiving boundary before + * calling this method. Serialization alone does not establish currentness or a live claim. */ public static byte[] fromOriginalTuple( StartSessionPostAuthorizationExecutionTuple originalTuple) { Objects.requireNonNull(originalTuple, "originalTuple is required"); + return decodeOwnerTuple(originalTuple.canonicalBytes()).canonicalBytes(); + } + + /** + * Decodes complete owner evidence; legacy scalar projections are insufficient for current use. + */ + public static StartSessionPostAuthorizationExecutionTuple decodeOwnerTuple(byte[] projection) { + requireBounded(projection); + StartSessionPostAuthorizationExecutionTuple ownerTuple = + StartSessionPostAuthorizationExecutionTuple.decode(projection); + if (!Arrays.equals(ownerTuple.canonicalBytes(), projection)) { + throw new IllegalArgumentException("Original Account tuple projection is not canonical"); + } + return ownerTuple; + } + + /** + * Compares the stored or independently returned owner evidence to the complete incoming tuple. + */ + public static void requireCurrentBinding( + byte[] projection, StartSessionPostAuthorizationExecutionTuple expectedTuple) { + Objects.requireNonNull(expectedTuple, "expectedTuple is required"); + if (!Arrays.equals( + decodeOwnerTuple(projection).canonicalBytes(), expectedTuple.canonicalBytes())) { + throw new IllegalArgumentException( + "Original Account tuple projection differs from the exact tuple"); + } + } + + /** + * Validates historical bytes without replacing them or upgrading old evidence to current + * authority. Legacy scalar-v1 evidence remains readable only at historical boundaries. + */ + public static void requireHistoricalBinding( + byte[] projection, StartSessionPostAuthorizationExecutionTuple expectedTuple) { + Objects.requireNonNull(expectedTuple, "expectedTuple is required"); + requireBounded(projection); + if (!Arrays.equals(projection, expectedTuple.canonicalBytes()) + && !Arrays.equals(projection, legacyHistoricalProjection(expectedTuple))) { + throw new IllegalArgumentException( + "Historical Account projection differs from the exact tuple"); + } + } + + private static void requireBounded(byte[] projection) { + Objects.requireNonNull(projection, "Account redemption projection is required"); + if (projection.length == 0 + || projection.length + > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { + throw new IllegalArgumentException( + "Account redemption projection is empty or exceeds its bound"); + } + } + + private static byte[] legacyHistoricalProjection( + StartSessionPostAuthorizationExecutionTuple originalTuple) { StartSessionAuthorityEvidenceBundle bundle = StartSessionAuthorityEvidenceBundle.decode(originalTuple.authorityEvidenceBundleBytes()); long issuanceFence; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java index 90713a3df8..b2603989af 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidence.java @@ -208,14 +208,14 @@ private void requireCoherentEvidence() { || !selector.controlPlaneRequestId().equals(launchAssociation.controlPlaneRequestId()) || !selector.launchDescriptorId().equals(launchAssociation.launchDescriptorId()) || !request.expectedOwnerAttemptId().equals(ownerAttemptId) - || request.expectedOwnerFence() != ownerFence - || !Arrays.equals( - StartSessionAccountRedemptionProjection.fromOriginalTuple(originalTuple), - accountRedemptionProjection)) { + || request.expectedOwnerFence() != ownerFence) { throw new IllegalArgumentException( "Historical StartSession tuple, projection, attempt, or association selector differs"); } + StartSessionAccountRedemptionProjection.requireHistoricalBinding( + accountRedemptionProjection, originalTuple); + var selectionRequest = firstSelection.request(); if (selectionRequest.schemaVersion() != StartSessionTemplateAssociationReadEvidence.SCHEMA_VERSION diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.java index 8dca147f44..d61861ee79 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.java @@ -5,6 +5,7 @@ import java.time.Instant; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Request; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence.Result; import net.firedevops.firemud.gamesession.v1.ReadOriginalStartSessionCurrentAttemptRequest; @@ -90,6 +91,23 @@ public static ReadOriginalStartSessionCurrentAttemptResponse toResponse(Result r public static Result fromResponse( Request expectedRequest, ReadOriginalStartSessionCurrentAttemptResponse response) { + Result result = decodeResponse(expectedRequest, response); + StartSessionAccountRedemptionProjection.requireCurrentBinding( + result.accountRedemptionProjection(), expectedRequest.originalTuple()); + return result; + } + + /** Decodes immutable historical response bytes only; this grants no current continuation. */ + public static Result fromRetainedHistoricalResponse( + Request expectedRequest, ReadOriginalStartSessionCurrentAttemptResponse response) { + Result result = decodeResponse(expectedRequest, response); + StartSessionAccountRedemptionProjection.requireHistoricalBinding( + result.accountRedemptionProjection(), expectedRequest.originalTuple()); + return result; + } + + private static Result decodeResponse( + Request expectedRequest, ReadOriginalStartSessionCurrentAttemptResponse response) { Objects.requireNonNull(expectedRequest, "expectedRequest"); Objects.requireNonNull(response, "response"); if (response.getSerializedSize() > MAX_RESPONSE_BYTES diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java index e4a0e3cf00..fb7945a7df 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java @@ -28,6 +28,7 @@ public final class StartSessionPostAuthorizationExecutionTuple { public static final String TUPLE_SCHEMA_VERSION = "1"; public static final int MAX_CANONICAL_TUPLE_BYTES = 256 * 1_024; + private static final long MAX_SAFE_JSON_INTEGER = 9_007_199_254_740_991L; private static final Pattern AUTHORIZATION_REFERENCE_FINGERPRINT = Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); private static final Set ROOT_FIELDS = @@ -70,7 +71,7 @@ public final class StartSessionPostAuthorizationExecutionTuple { private final String authorizationReferenceFingerprint; private final UUID reservationOwnerId; private final long reservationClaimFence; - private final byte[] authorityEvidenceBundleBytes; + private final StartSessionAuthorityEvidenceBundle authorityEvidenceBundle; private final StartSessionAuthorityEvidenceBundle.BundleReference bundleReference; private final byte[] canonicalBytes; @@ -80,7 +81,7 @@ private StartSessionPostAuthorizationExecutionTuple( String authorizationReferenceFingerprint, UUID reservationOwnerId, long reservationClaimFence, - byte[] authorityEvidenceBundleBytes, + StartSessionAuthorityEvidenceBundle authorityEvidenceBundle, StartSessionAuthorityEvidenceBundle.BundleReference bundleReference, byte[] canonicalBytes) { this.preAuthorizationTuple = preAuthorizationTuple; @@ -88,7 +89,7 @@ private StartSessionPostAuthorizationExecutionTuple( this.authorizationReferenceFingerprint = authorizationReferenceFingerprint; this.reservationOwnerId = reservationOwnerId; this.reservationClaimFence = reservationClaimFence; - this.authorityEvidenceBundleBytes = authorityEvidenceBundleBytes.clone(); + this.authorityEvidenceBundle = authorityEvidenceBundle; this.bundleReference = bundleReference; this.canonicalBytes = canonicalBytes.clone(); } @@ -118,7 +119,6 @@ public static StartSessionPostAuthorizationExecutionTuple createHuman( StartSessionAuthorityEvidenceBundle.decode(exactCanonicalAuthorityEvidenceBundle); bundle.requireTupleBinding(preAuthorizationTuple); bundle.requireReferenceBinding(bundleReference); - byte[] bundleBytes = bundle.canonicalBytes(); byte[] canonical = encode( preAuthorizationTuple, @@ -134,7 +134,7 @@ public static StartSessionPostAuthorizationExecutionTuple createHuman( authorizationReferenceFingerprint, reservationOwnerId, reservationClaimFence, - bundleBytes, + bundle, bundleReference, canonical); } @@ -195,7 +195,7 @@ public static StartSessionPostAuthorizationExecutionTuple decode(byte[] exactCan root.get("authorizationReferenceFingerprint"), "authorizationReferenceFingerprint"), canonicalUuid(root.get("reservationOwnerId"), "reservationOwnerId"), - positiveLong(root.get("reservationClaimFence"), "reservationClaimFence"), + reservationClaimFence(root.get("reservationClaimFence")), bundleBytes, reference); if (!TUPLE_SCHEMA_ID.equals(string(root.get("tupleSchemaId"), "tupleSchemaId")) @@ -243,21 +243,19 @@ public long reservationClaimFence() { } public String issuanceFence() { - return StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundleBytes).issuanceFence(); + return authorityEvidenceBundle.issuanceFence(); } public Map authorityTuple() { - return StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundleBytes) - .authorityTuple(); + return authorityEvidenceBundle.authorityTuple(); } public Map membershipVersion() { - return StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundleBytes) - .membershipVersion(); + return authorityEvidenceBundle.membershipVersion(); } public byte[] authorityEvidenceBundleBytes() { - return authorityEvidenceBundleBytes.clone(); + return authorityEvidenceBundle.canonicalBytes(); } public StartSessionAuthorityEvidenceBundle.BundleReference bundleReference() { @@ -308,7 +306,7 @@ private static byte[] encode( root.put("membershipVersion", bundle.membershipVersion()); root.put("issuanceFence", bundle.issuanceFence()); root.put("reservationOwnerId", reservationOwnerId.toString()); - root.put("reservationClaimFence", reservationClaimFence); + root.put("reservationClaimFence", reservationClaimFenceJsonValue(reservationClaimFence)); root.put("authorityEvidenceBundle", bundle.jsonValue()); root.put( "authorityEvidenceBundleReference", @@ -424,18 +422,37 @@ private static UUID canonicalUuid(Object value, String field) { } } - private static long positiveLong(Object value, String field) { - if (!(value instanceof Number number)) { - throw invalid(field + " must be a positive integer"); + private static Object reservationClaimFenceJsonValue(long value) { + return value <= MAX_SAFE_JSON_INTEGER ? value : Long.toString(value); + } + + private static long reservationClaimFence(Object value) { + if (value instanceof Number number) { + long parsed = parseReservationClaimFence(number.toString()); + if (parsed > MAX_SAFE_JSON_INTEGER) { + throw invalid("reservationClaimFence numeric value exceeds the safe JSON integer range"); + } + return parsed; } + if (value instanceof String text) { + long parsed = parseReservationClaimFence(text); + if (parsed <= MAX_SAFE_JSON_INTEGER) { + throw invalid("reservationClaimFence string value must exceed the safe JSON integer range"); + } + return parsed; + } + throw invalid("reservationClaimFence must be a positive integer or canonical decimal string"); + } + + private static long parseReservationClaimFence(String value) { try { - long parsed = Long.parseLong(number.toString()); - if (parsed <= 0L || !Long.toString(parsed).equals(number.toString())) { - throw invalid(field + " must be a positive canonical integer"); + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw invalid("reservationClaimFence must be positive and canonically encoded"); } return parsed; } catch (NumberFormatException malformed) { - throw invalid(field + " must be a positive signed 64-bit integer"); + throw invalid("reservationClaimFence must fit a positive signed 64-bit integer"); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java index 70e9d99eda..472ec9e50d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java @@ -38,16 +38,15 @@ class AccountStartSessionAdmissionProtectionEvidenceTest { private static final JsonMapper JSON = JsonMapper.builder().build(); @Test - void redemptionProjectionRetainsTheOriginalNumericIssuanceFenceRepresentation() - throws IOException { + void currentRedemptionProjectionRetainsTheCompleteCanonicalOwnerTuple() throws IOException { StartSessionPostAuthorizationExecutionTuple tuple = originalTuple("admission-projection"); byte[] projection = StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple); Map projectionValue = readObject(projection); - Object issuanceFence = projectionValue.get("issuanceFence"); - assertThat(issuanceFence).isInstanceOf(Number.class); - assertThat(((Number) issuanceFence).toString()).isEqualTo("23"); + assertThat(projection).containsExactly(tuple.canonicalBytes()); + assertThat(projectionValue.get("issuanceFence")).isEqualTo("23"); + StartSessionAccountRedemptionProjection.requireCurrentBinding(projection, tuple); assertThat(((Map) projectionValue.get("authorityEvidenceBundle")).get("issuanceFence")) .isEqualTo("23"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java index b5795f3343..af82ce8558 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java @@ -4,10 +4,17 @@ import java.nio.file.Files; import java.nio.file.Path; +import java.time.Instant; 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 net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -99,8 +106,54 @@ private static AccountStartSessionWorldParticipationHistoricalReadRequest reques return new AccountStartSessionWorldParticipationHistoricalReadRequest( UUID.fromString("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"), namespace, - UUID.fromString("a8c1e8c8-f237-41b7-918d-ec2281bcac10"), - 31L); + originalTuple(namespace).canonicalBytes()); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple(String namespace) { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "historical-client-original-request", + UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"), + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope( + UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"), namespace), + new StartSessionOperatorAction.Target( + 91L, UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic historical client boundary test")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"), + 19L, + StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + preTuple, + new Values( + UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2020-01-01T00:00:00Z"), + Instant.parse("2020-01-02T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); } private static CommonGrpcClientProperties fileBacked(Path directory) throws Exception { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java index 553dde81d2..cd5c2aba44 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java @@ -4,20 +4,18 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.UnknownFieldSet; -import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; -import java.util.List; -import java.util.Map; +import java.time.Instant; import java.util.UUID; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.world.WorldStartSessionExecutionTerminal; import org.junit.jupiter.api.Test; -import tools.jackson.databind.json.JsonMapper; class AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest { private static final String NAMESPACE = "world-runtime"; @@ -28,10 +26,9 @@ class AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest { private static final UUID READ_ID = uuid("d1f41bfb-265a-4f3b-8b2a-124cba20ce43"); private static final String PREPARATION_INPUT = "{ \"identity\" : \"retained original input\", \"revision\": 3 }\n"; - private static final JsonMapper JSON = JsonMapper.builder().build(); @Test - void roundTripsOnlyTheExactHistoricalRequestAndAccountRetainedFields() { + void roundTripsTheCompleteOriginalTupleAndResolvedHistoricalCoordinates() { var request = request(); var evidence = evidence(request); @@ -43,13 +40,15 @@ void roundTripsOnlyTheExactHistoricalRequestAndAccountRetainedFields() { var response = AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse(request, evidence); - assertThat(response.getAllFields()).hasSize(7); + assertThat(response.getAllFields()).hasSize(8); var decoded = AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( request, response); assertThat(decoded.request()).isEqualTo(request); - assertThat(decoded.originalPostAuthorizationTuple()) - .containsExactly(evidence.originalPostAuthorizationTuple()); + assertThat(decoded.request().originalPostAuthorizationTuple()) + .containsExactly(request.originalPostAuthorizationTuple()); + assertThat(decoded.accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(decoded.accountWorldParticipationFence()).isEqualTo(31L); assertThat(decoded.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); assertThat(decoded.gameSessionOwnerFence()).isEqualTo(37L); assertThat(decoded.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); @@ -58,7 +57,7 @@ void roundTripsOnlyTheExactHistoricalRequestAndAccountRetainedFields() { } @Test - void rejectsUnknownFieldsUnsupportedVersionMalformedIdsAndNonpositiveFences() { + void rejectsUnknownFieldsUnsupportedVersionMalformedReadIdAndIncompleteTuple() { var request = request(); UnknownFieldSet unknown = unknown(); var wire = AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toRequest(request); @@ -81,18 +80,44 @@ void rejectsUnknownFieldsUnsupportedVersionMalformedIdsAndNonpositiveFences() { wire.toBuilder().setReadRequestId(READ_ID + " ").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical non-nil UUID"); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, NAMESPACE, new byte[0])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("empty or oversized"); assertThatThrownBy( () -> AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( - wire.toBuilder().setAccountWorldParticipationFence(0L).build())) + wire.toBuilder() + .setOriginalPostAuthorizationTuple(com.google.protobuf.ByteString.EMPTY) + .build())) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("positive"); + .hasMessageContaining("empty or oversized"); + } + + @Test + void rejectsOnlyReservationOwnerCollisionAtRequestBoundary() { + var original = originalTuple(NAMESPACE); assertThatThrownBy( () -> new AccountStartSessionWorldParticipationHistoricalReadRequest( - READ_ID, NAMESPACE, READ_ID, 31L)) + original.reservationOwnerId(), NAMESPACE, original.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("distinct"); + .hasMessageContaining("distinct from the reservation owner"); + + for (UUID requestId : + new UUID[] { + original.preAuthorizationTuple().actor().accountId(), + TENANT, + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f") + }) { + assertThat( + new AccountStartSessionWorldParticipationHistoricalReadRequest( + requestId, NAMESPACE, original.canonicalBytes()) + .readRequestId()) + .isEqualTo(requestId); + } } @Test @@ -105,7 +130,9 @@ void rejectsChangedRequestEchoUnknownResponseAndInconsistentRetainedIdentity() { var changedEcho = response.toBuilder() .setRequest( - response.getRequest().toBuilder().setTargetNamespace("other-runtime").build()) + response.getRequest().toBuilder() + .setReadRequestId("0fd3d542-a9f8-4b8f-b1df-79413650126c") + .build()) .build(); assertThatThrownBy( () -> @@ -133,16 +160,11 @@ void rejectsChangedRequestEchoUnknownResponseAndInconsistentRetainedIdentity() { () -> AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse( request, - new AccountStartSessionWorldParticipationHistoricalReadEvidence( - request, - originalTuple("other-runtime").canonicalBytes(), - GAME_SESSION_ATTEMPT_ID, - 37L, - GAME_INSTANCE_ID, - PREPARATION_INPUT, - digest(PREPARATION_INPUT)))) + evidence( + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, NAMESPACE, originalTuple(NAMESPACE, 20L).canonicalBytes())))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("differs from the exact original"); + .hasMessageContaining("changed the exact"); } @Test @@ -153,7 +175,8 @@ void rejectsOversizedPreparationInputAndTupleAtClosedCarrierBoundary() { () -> new AccountStartSessionWorldParticipationHistoricalReadEvidence( request, - originalTuple(NAMESPACE).canonicalBytes(), + PARTICIPATION_ID, + 31L, GAME_SESSION_ATTEMPT_ID, 37L, GAME_INSTANCE_ID, @@ -161,34 +184,42 @@ void rejectsOversizedPreparationInputAndTupleAtClosedCarrierBoundary() { digest(oversized))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("byte limit"); + assertThatThrownBy( + () -> + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, + NAMESPACE, + new byte + [StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("empty or oversized"); assertThatThrownBy( () -> new AccountStartSessionWorldParticipationHistoricalReadEvidence( request, - new byte - [net.firedevops.firemud.common.operator - .StartSessionPostAuthorizationExecutionTuple - .MAX_CANONICAL_TUPLE_BYTES - + 1], + PARTICIPATION_ID, + 0L, GAME_SESSION_ATTEMPT_ID, 37L, GAME_INSTANCE_ID, PREPARATION_INPUT, digest(PREPARATION_INPUT))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("oversized"); + .hasMessageContaining("fence must be positive"); } private static AccountStartSessionWorldParticipationHistoricalReadRequest request() { return new AccountStartSessionWorldParticipationHistoricalReadRequest( - READ_ID, NAMESPACE, PARTICIPATION_ID, 31L); + READ_ID, NAMESPACE, originalTuple(NAMESPACE).canonicalBytes()); } private static AccountStartSessionWorldParticipationHistoricalReadEvidence evidence( AccountStartSessionWorldParticipationHistoricalReadRequest request) { return new AccountStartSessionWorldParticipationHistoricalReadEvidence( request, - originalTuple(NAMESPACE).canonicalBytes(), + PARTICIPATION_ID, + 31L, GAME_SESSION_ATTEMPT_ID, 37L, GAME_INSTANCE_ID, @@ -197,6 +228,11 @@ private static AccountStartSessionWorldParticipationHistoricalReadEvidence evide } private static StartSessionPostAuthorizationExecutionTuple originalTuple(String namespace) { + return originalTuple(namespace, 19L); + } + + private static StartSessionPostAuthorizationExecutionTuple originalTuple( + String namespace, long reservationClaimFence) { UUID actor = uuid("a4f5f4eb-8243-4d42-903a-33495456a622"); UUID targetOwner = uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); UUID reservationOwner = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); @@ -219,7 +255,7 @@ private static StartSessionPostAuthorizationExecutionTuple originalTuple(String "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", "arfp/v1/test-key/" + "b".repeat(64), reservationOwner, - 19L, + reservationClaimFence, authorityBundle(preTuple), new StartSessionAuthorityEvidenceBundle.BundleReference( StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, @@ -229,79 +265,24 @@ private static StartSessionPostAuthorizationExecutionTuple originalTuple(String } private static byte[] authorityBundle(StartSessionPreAuthorizationReservationTuple tuple) { - String actorId = tuple.actor().accountId().toString(); - String tenantId = tuple.action().scope().tenantId().toString(); - Map projection = - Map.of( - "sourceType", "ACCOUNT", - "sourceEvidenceId", "sha256:" + "a".repeat(64), - "sourceEvidenceVersion", "17", - "projectionStatus", "CURRENT", - "evaluatedAt", "2020-01-01T00:00:00Z", - "expiresAt", "2020-01-02T00:00:00Z"); - Map issuanceIdentity = - Map.of( - "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", - "controlPlaneRequestId", tuple.controlPlaneRequestId(), - "actionFamilyRequestIdentity", - Map.of( - "requestIdentityKind", - "controlPlaneRequestId", - "requestId", - tuple.controlPlaneRequestId()), - "mutationDigest", tuple.mutationDigest()); - Map authority = - Map.of( - "issuerAuthGeneration", 1L, - "accountAuthorityGeneration", 2L, - "tenantAuthorityGeneration", Map.of(tenantId, 3L), - "membershipAuthorityGeneration", Map.of(tenantId, 4L), - "privateRealmGrantVersions", List.of()); - Map humanEvidence = - Map.of( - "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, - "actorAccountId", actorId, - "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", - "role", "tenantAdmin", - "accountGeneration", "2", - "tenantGeneration", "3"); - Map bundle = - Map.of( - "bundleVersion", - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "authorityScope", - Map.of( - "scope", - Map.of( - "tenantId", - tenantId, - "targetNamespace", - tuple.action().scope().targetNamespace()), - "actionFamily", - tuple.actionFamily(), - "applicableAccountId", - actorId, - "applicableTenantId", - tenantId), - "accountProjectionEvidence", - projection, - "issuanceOperationIdentity", - issuanceIdentity, - "issuanceKind", - "human_operator", - "authorityTuple", - authority, - "membershipVersion", - Map.of(tenantId, 5L), - "issuanceFence", - "23", - "issuanceEvidence", - humanEvidence); - try { - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); - } catch (IOException impossible) { - throw new IllegalStateException(impossible); - } + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2020-01-01T00:00:00Z"), + Instant.parse("2020-01-02T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); } private static UnknownFieldSet unknown() { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java index f069bcd89e..95f5d2beb1 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java @@ -52,8 +52,7 @@ class OriginalStartSessionCurrentAttemptClientMtlsTest { private static final String OTHER_CLIENT_URI = "spiffe://firemud/ns/world-runtime/sa/entity-management-service"; private static final String STORE_PASSWORD = "test-only-store-password"; - private static final byte[] PROJECTION = - "synthetic-attached-account-projection".getBytes(StandardCharsets.UTF_8); + private static final byte[] PROJECTION = CurrentAttemptTestData.tuple().canonicalBytes(); @TempDir static Path tempDirectory; diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java index 9823f3fb02..ef029b3266 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java @@ -19,8 +19,7 @@ class OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest { @Test void roundTripsExactRequestPendingPhaseProjectionAndOriginalExpiry() { Request request = request(); - byte[] projection = - "attached-account-projection".getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] projection = request.originalTuple().canonicalBytes(); Result result = new Result(request, Instant.parse("2030-01-01T00:00:00.123456789Z"), projection); var wireRequest = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toRequest(request); @@ -65,7 +64,10 @@ void rejectsUnknownFieldsUnsupportedSchemaInvalidFenceAndChangedEcho() { var response = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( - new Result(request, Instant.parse("2030-01-01T00:00:00Z"), new byte[] {1, 2, 3})); + new Result( + request, + Instant.parse("2030-01-01T00:00:00Z"), + request.originalTuple().canonicalBytes())); var changedEcho = response.toBuilder() .setRequest( @@ -85,7 +87,10 @@ void rejectsWrongPhaseDigestResponseAndTimestampShapes() { Request request = request(); var valid = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( - new Result(request, Instant.parse("2030-01-01T00:00:00Z"), new byte[] {1, 2, 3})); + new Result( + request, + Instant.parse("2030-01-01T00:00:00Z"), + request.originalTuple().canonicalBytes())); var unknownResponse = valid.toBuilder() .setUnknownFields( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/StartSessionAccountRedemptionProjectionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/StartSessionAccountRedemptionProjectionTest.java new file mode 100644 index 0000000000..00d24a70a0 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/StartSessionAccountRedemptionProjectionTest.java @@ -0,0 +1,172 @@ +package net.firedevops.firemud.common.gamesession; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class StartSessionAccountRedemptionProjectionTest { + @Test + void retainsExactlyTheCompleteOwnerTupleWithinTheExistingByteBound() { + var original = CurrentAttemptTestData.tuple(); + byte[] retained = StartSessionAccountRedemptionProjection.fromOriginalTuple(original); + assertThat(retained).containsExactly(original.canonicalBytes()); + assertThat(retained.length) + .isLessThanOrEqualTo(StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES); + assertThatCode( + () -> StartSessionAccountRedemptionProjection.requireCurrentBinding(retained, original)) + .doesNotThrowAnyException(); + retained[0] ^= 1; + assertThat(original.canonicalBytes()[0]).isEqualTo((byte) '{'); + } + + @Test + void exactLargeFencesRemainDistinctAcrossCurrentOwnerProjectionReplay() { + var baseline = CurrentAttemptTestData.tuple(); + for (long fence : + new long[] { + 9_007_199_254_740_991L, 9_007_199_254_740_992L, 9_007_199_254_740_993L, Long.MAX_VALUE + }) { + var original = withReservationFence(baseline, fence); + byte[] retained = StartSessionAccountRedemptionProjection.fromOriginalTuple(original); + assertThat(retained).containsExactly(original.canonicalBytes()); + assertThat( + StartSessionAccountRedemptionProjection.decodeOwnerTuple(retained) + .reservationClaimFence()) + .isEqualTo(fence); + assertThatCode( + () -> + StartSessionAccountRedemptionProjection.requireCurrentBinding(retained, original)) + .doesNotThrowAnyException(); + assertThat(StartSessionAccountRedemptionProjection.fromOriginalTuple(original)) + .containsExactly(retained); + + var changed = withReservationFence(baseline, fence == Long.MAX_VALUE ? fence - 1 : fence + 1); + assertThatThrownBy( + () -> + StartSessionAccountRedemptionProjection.requireCurrentBinding(retained, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static StartSessionPostAuthorizationExecutionTuple withReservationFence( + StartSessionPostAuthorizationExecutionTuple original, long fence) { + return StartSessionPostAuthorizationExecutionTuple.createHuman( + original.preAuthorizationTuple(), + original.authenticatedWorkloadIdentity(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + fence, + original.authorityEvidenceBundleBytes(), + original.bundleReference()); + } + + @Test + void independentlyRetainedOwnerTupleRejectsSourceFenceAndLinearizationSubstitutions() { + var original = CurrentAttemptTestData.tuple(); + byte[] ownerEvidence = original.canonicalBytes(); + var reference = original.bundleReference(); + for (var changedReference : + new StartSessionAuthorityEvidenceBundle.BundleReference[] { + new StartSessionAuthorityEvidenceBundle.BundleReference( + reference.bundleVersion(), + reference.sourceVersion(), + "24", + reference.linearization()), + new StartSessionAuthorityEvidenceBundle.BundleReference( + reference.bundleVersion(), + reference.sourceVersion(), + reference.sourceFence(), + "18446744073709551614") + }) { + var substituted = + StartSessionPostAuthorizationExecutionTuple.createHuman( + original.preAuthorizationTuple(), + original.authenticatedWorkloadIdentity(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.authorityEvidenceBundleBytes(), + changedReference); + assertThatThrownBy( + () -> + StartSessionAccountRedemptionProjection.requireCurrentBinding( + ownerEvidence, substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs"); + assertThatThrownBy( + () -> + StartSessionAccountRedemptionProjection.requireHistoricalBinding( + ownerEvidence, substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("differs"); + } + } + + @Test + void ownerEvidenceRejectsChangedBundleVersionAndSourceVersion() throws Exception { + var original = CurrentAttemptTestData.tuple(); + String json = new String(original.canonicalBytes(), StandardCharsets.UTF_8); + for (String changed : + new String[] { + json.replace( + "\"bundleVersion\":\"authorityEvidenceBundle/v1\"", + "\"bundleVersion\":\"authorityEvidenceBundle/v2\""), + json.replace("\"sourceVersion\":\"17\"", "\"sourceVersion\":\"18\"") + }) { + assertThat(changed).isNotEqualTo(json); + byte[] candidate = Rfc8785CanonicalJson.canonicalizeUtf8(changed); + assertThatThrownBy( + () -> + StartSessionAccountRedemptionProjection.requireCurrentBinding( + candidate, original)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void scalarV1ProjectionRemainsBytePreservedHistoricalEvidenceAndFailsCurrentUse() + throws Exception { + var original = CurrentAttemptTestData.tuple(); + var bundle = + StartSessionAuthorityEvidenceBundle.decode(original.authorityEvidenceBundleBytes()); + byte[] oldBytes = + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder() + .build() + .writeValueAsString( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + original.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + Long.parseLong(original.issuanceFence())))); + byte[] before = oldBytes.clone(); + assertThatCode( + () -> + StartSessionAccountRedemptionProjection.requireHistoricalBinding( + oldBytes, original)) + .doesNotThrowAnyException(); + assertThat(oldBytes).containsExactly(before); + assertThatThrownBy( + () -> StartSessionAccountRedemptionProjection.requireCurrentBinding(oldBytes, original)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> StartSessionAccountRedemptionProjection.decodeOwnerTuple(new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java index 067ace1439..cf1aea88d5 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java @@ -115,10 +115,60 @@ void returnsDefensiveEvidenceCopiesAndRejectsNonCanonicalOrUnknownTupleFields() .isInstanceOf(IllegalArgumentException.class); } + @Test + void encodesReservationClaimFenceExactlyAcrossTheSafeJsonIntegerBoundary() throws Exception { + long[] values = { + 9_007_199_254_740_991L, 9_007_199_254_740_992L, 9_007_199_254_740_993L, Long.MAX_VALUE + }; + + for (long value : values) { + byte[] bytes = create("post-tuple-fence-" + value, value).canonicalBytes(); + Map root = JSON.readValue(bytes, Map.class); + Object encodedFence = root.get("reservationClaimFence"); + if (value <= 9_007_199_254_740_991L) { + assertThat(encodedFence).isInstanceOf(Number.class); + assertThat(encodedFence.toString()).isEqualTo(Long.toString(value)); + } else { + assertThat(encodedFence).isEqualTo(Long.toString(value)); + } + + StartSessionPostAuthorizationExecutionTuple decoded = + StartSessionPostAuthorizationExecutionTuple.decode(bytes); + assertThat(decoded.reservationClaimFence()).isEqualTo(value); + assertThat(decoded.canonicalBytes()).containsExactly(bytes); + assertThat( + StartSessionPostAuthorizationExecutionTuple.decode(decoded.canonicalBytes()) + .canonicalBytes()) + .containsExactly(bytes); + } + } + + @Test + void rejectsUnsafeLegacyNumericAndNoncanonicalStringReservationClaimFences() throws Exception { + byte[][] unsafeNumericValues = { + tupleBytesWithFence(9_007_199_254_740_992L), tupleBytesWithFence(Long.MAX_VALUE) + }; + for (byte[] bytes : unsafeNumericValues) { + assertThatThrownBy(() -> StartSessionPostAuthorizationExecutionTuple.decode(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } + + for (String encodedFence : + List.of("19", "01", "+9007199254740992", "9223372036854775808", "")) { + byte[] bytes = tupleBytesWithFence(encodedFence); + assertThatThrownBy(() -> StartSessionPostAuthorizationExecutionTuple.decode(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } + } + private static StartSessionPostAuthorizationExecutionTuple create(String requestId) { + return create(requestId, 19L); + } + + private static StartSessionPostAuthorizationExecutionTuple create(String requestId, long fence) { StartSessionPreAuthorizationReservationTuple pre = preTuple(requestId); return StartSessionPostAuthorizationExecutionTuple.createHuman( - pre, WORKLOAD, FINGERPRINT, RESERVATION_OWNER, 19L, bundle(pre, "17"), reference("17")); + pre, WORKLOAD, FINGERPRINT, RESERVATION_OWNER, fence, bundle(pre, "17"), reference("17")); } private static StartSessionPreAuthorizationReservationTuple preTuple(String requestId) { @@ -216,6 +266,13 @@ private static byte[] tupleBytes(StartSessionPostAuthorizationExecutionTuple tup return tuple.canonicalBytes(); } + private static byte[] tupleBytesWithFence(Object fence) throws IOException { + Map root = + JSON.readValue(create("post-tuple-fence-legacy").canonicalBytes(), Map.class); + root.put("reservationClaimFence", fence); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + } + private static void assertJsonNumber(Object actual, long expected) { assertThat(actual).isInstanceOf(Number.class); assertThat(((Number) actual).longValue()).isEqualTo(expected); diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleFixture.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleFixture.java new file mode 100644 index 0000000000..2bbc707a18 --- /dev/null +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleFixture.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.common.operator; + +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Test data builder for canonical human StartSession authority evidence bundles. */ +public final class StartSessionAuthorityEvidenceBundleFixture { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private StartSessionAuthorityEvidenceBundleFixture() {} + + /** Values which vary across synthetic authority-bundle scenarios. */ + public record Values( + UUID issuanceOperationId, + String sourceEvidenceId, + String sourceEvidenceVersion, + String projectionStatus, + Instant evaluatedAt, + Instant expiresAt, + long issuerAuthGeneration, + long accountAuthorityGeneration, + long tenantAuthorityGeneration, + long membershipAuthorityGeneration, + long membershipVersion, + long issuanceFence, + UUID controlUiTokenJti, + String accountGeneration, + String tenantGeneration) { + public Values { + Objects.requireNonNull(issuanceOperationId); + Objects.requireNonNull(sourceEvidenceId); + Objects.requireNonNull(sourceEvidenceVersion); + Objects.requireNonNull(projectionStatus); + Objects.requireNonNull(evaluatedAt); + Objects.requireNonNull(expiresAt); + Objects.requireNonNull(controlUiTokenJti); + Objects.requireNonNull(accountGeneration); + Objects.requireNonNull(tenantGeneration); + } + } + + /** Builds canonical bytes without invoking the production decoder or its validation rules. */ + public static byte[] canonicalBytes( + StartSessionPreAuthorizationReservationTuple tuple, Values values) { + Objects.requireNonNull(tuple); + Objects.requireNonNull(values); + String actorId = tuple.actor().accountId().toString(); + String tenantId = tuple.action().scope().tenantId().toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", + tuple.actionFamily(), + "applicableAccountId", + actorId, + "applicableTenantId", + tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + values.sourceEvidenceId(), + "sourceEvidenceVersion", + values.sourceEvidenceVersion(), + "projectionStatus", + values.projectionStatus(), + "evaluatedAt", + values.evaluatedAt().toString(), + "expiresAt", + values.expiresAt().toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", + values.issuanceOperationId().toString(), + "controlPlaneRequestId", + tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", + tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", + values.issuerAuthGeneration(), + "accountAuthorityGeneration", + values.accountAuthorityGeneration(), + "tenantAuthorityGeneration", + Map.of(tenantId, values.tenantAuthorityGeneration()), + "membershipAuthorityGeneration", + Map.of(tenantId, values.membershipAuthorityGeneration()), + "privateRealmGrantVersions", + List.of()), + "membershipVersion", + Map.of(tenantId, values.membershipVersion()), + "issuanceFence", + Long.toString(values.issuanceFence()), + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + actorId, + "controlUiTokenJti", + values.controlUiTokenJti().toString(), + "role", + "tenantAdmin", + "accountGeneration", + values.accountGeneration(), + "tenantGeneration", + values.tenantGeneration())); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java index f088d86f61..afb6b9a768 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GenuineSelectedPublicationExportPostgresIntegrationTest.java @@ -57,6 +57,7 @@ import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OriginalStartSessionAuthorizationTransport; import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerAttemptLifecycle; import net.firedevops.firemud.accountservice.service.session.AccountOriginalStartSessionAuthorizationProofFixture.OwnerClaim; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedemptionResult; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeTerminalReadService; @@ -3526,7 +3527,9 @@ public OwnerClaim reserve(StartSessionPostAuthorizationExecutionTuple tuple) { @Override public void attachAccountRedemptionProjection( - OwnerClaim ownerClaim, StartSessionPostAuthorizationExecutionTuple tuple) { + OwnerClaim ownerClaim, + StartSessionPostAuthorizationExecutionTuple tuple, + byte[] originalAccountPostAuthorizationTuple) { AttemptClaim claim = Objects.requireNonNull( reservedOwnerAttempt.get(), @@ -3535,6 +3538,8 @@ public void attachAccountRedemptionProjection( assertThat(ownerClaim.ownerMutationId()).isEqualTo(claim.ownerMutationId()); assertThat(ownerClaim.ownerFence()).isEqualTo(claim.ownerFence()); assertThat(tuple.canonicalBytes()).containsExactly(reservedTupleBytes.get()); + assertThat(originalAccountPostAuthorizationTuple) + .containsExactly(tuple.canonicalBytes()); var authority = StartSessionAuthorityEvidenceBundle.decode( tuple.authorityEvidenceBundleBytes()); @@ -3543,7 +3548,10 @@ public void attachAccountRedemptionProjection( tuple.authorizationReferenceFingerprint(), tuple.authorityEvidenceBundleBytes(), authority.issuanceOperationId(), - Long.parseLong(tuple.issuanceFence())); + Long.parseLong(tuple.issuanceFence()), + originalAccountPostAuthorizationTuple); + assertThat(projection.canonicalBytes()) + .containsExactly(originalAccountPostAuthorizationTuple); assertThat(projection.canonicalBytes()) .containsExactly( StartSessionAccountRedemptionProjection.fromOriginalTuple(tuple)); @@ -7373,11 +7381,12 @@ public IssuedAuthorization issue( issued.operatorAuthorizationReference(), issued.authorizationReferenceFingerprint(), issued.authorityEvidenceBundle(), - issued.bundleReference()); + issued.bundleReference(), + issued.postAuthorizationTuple().canonicalBytes()); } @Override - public boolean redeem( + public RedemptionResult redeem( byte[] canonicalPreAuthorizationTupleBytes, IssuedAuthorization authorization, UUID reservationOwnerId, @@ -7405,15 +7414,24 @@ public boolean redeem( || !authorization .authorizationReferenceFingerprint() .equals(response.getAuthorizationReferenceFingerprint()) + || !Arrays.equals( + authorization.originalAccountPostAuthorizationTuple(), + response.getOriginalAccountPostAuthorizationTuple().toByteArray()) || !Arrays.equals( authorization.authorityEvidenceBundle(), response.getAuthorityEvidenceBundle().toByteArray()) || !authority.issuanceOperationId().toString().equals(response.getIssuanceOperationId()) || !authority.issuanceFence().equals(Long.toString(response.getIssuanceFence()))) { throw new IllegalStateException( - "Account redemption response differs from the exact issued authority bundle"); + "Account redemption response differs from the exact issued owner tuple"); } - return response.getReplay(); + return new RedemptionResult( + response.getAuthorizationReferenceFingerprint(), + response.getAuthorityEvidenceBundle().toByteArray(), + authority.issuanceOperationId(), + response.getIssuanceFence(), + response.getReplay(), + response.getOriginalAccountPostAuthorizationTuple().toByteArray()); } @Override diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java new file mode 100644 index 0000000000..d44f089ffa --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java @@ -0,0 +1,328 @@ +package net.firedevops.firemud.gamesession.client; + +import com.google.protobuf.ByteString; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +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.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Typed Game Session client for Account's StartSession redemption RPC. An owning workflow must + * construct and initialize this transport explicitly; it is not registered as a runtime bean. + * + *

This transport does not acquire claims, retry ambiguous redemption, issue references, dispatch + * a mutation, or transition an owner attempt to a terminal result. The raw reference exists only in + * the bounded in-flight request object. + */ +public class StartSessionOperatorRedemptionClient + extends AbstractReloadingBlockingGrpcClient< + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub> { + private static final int MAX_PRE_AUTHORIZATION_TUPLE_BYTES = 8 * 1_024; + private static final int MAX_AUTHORIZATION_REFERENCE_BYTES = 128; + private static final long REDEMPTION_DEADLINE_SECONDS = 5L; + private static final Pattern OPAQUE_REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final Pattern AUTHORIZATION_REFERENCE_FINGERPRINT = + Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); + private static final Pattern CANONICAL_UUID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final String workloadNamespace; + private final Clock clock; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "This constructor validates input only; managed channels are acquired later by initialize().") + public StartSessionOperatorRedemptionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + String workloadNamespace) { + this(endpoints, tlsProps, channelFactory, stubCustomizer, workloadNamespace, Clock.systemUTC()); + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "This constructor validates input only; managed channels are acquired later by initialize().") + public StartSessionOperatorRedemptionClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + String workloadNamespace, + Clock clock) { + super( + endpoints, + requireMutualTls(tlsProps), + channelFactory, + stubCustomizer, + StartSessionOperatorRedemptionClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + /** + * Opens the managed mutual-TLS channel only when an owning workflow explicitly initializes it. + */ + public void initialize() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return applyStubCustomizer( + StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel) + .withCompression("gzip")) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)); + } + + /** + * Redeems once for the exact newly-created Game Session owner claim. Transport ambiguity is + * propagated unchanged; this method never retries or alters the pending owner record. + */ + public RedemptionResult redeem( + StartSessionPostAuthorizationExecutionTuple tuple, + String transientOperatorAuthorizationReference, + AttemptClaim actualGameSessionClaim) { + Objects.requireNonNull(tuple, "complete post-authorization tuple is required"); + Objects.requireNonNull(actualGameSessionClaim, "Game Session owner attempt claim is required"); + requireNoAmbientSqlTransaction(); + requireExactClaimBinding(tuple, actualGameSessionClaim); + requireConfiguredNamespace(tuple, actualGameSessionClaim); + requireOpaqueReference(transientOperatorAuthorizationReference); + requireUnexpiredTupleEvidence(tuple); + + byte[] canonicalPreTuple = + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8); + if (canonicalPreTuple.length == 0 + || canonicalPreTuple.length > MAX_PRE_AUTHORIZATION_TUPLE_BYTES) { + throw new IllegalArgumentException( + "canonical StartSession pre-authorization tuple is over its bound"); + } + RedeemOperatorAuthorizationRequest request = + RedeemOperatorAuthorizationRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(canonicalPreTuple)) + .setOperatorAuthorizationReference(transientOperatorAuthorizationReference) + .setAuthorizationReferenceFingerprint(tuple.authorizationReferenceFingerprint()) + .setReservationOwnerId(tuple.reservationOwnerId().toString()) + .setReservationClaimFence(tuple.reservationClaimFence()) + .setOwnerAttemptId(actualGameSessionClaim.ownerAttemptId().toString()) + .setOwnerFence(actualGameSessionClaim.ownerFence()) + .build(); + + var response = + requireStub() + .withDeadlineAfter(REDEMPTION_DEADLINE_SECONDS, TimeUnit.SECONDS) + .redeemOperatorAuthorization(request); + AccountRedemptionProjection projection = validateResponse(response, tuple); + return new RedemptionResult(actualGameSessionClaim, projection, response.getReplay()); + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + requireStub() { + var value = stub(); + if (value == null) { + throw new IllegalStateException( + "Account StartSession redemption client has not been explicitly initialized"); + } + return value; + } + + private static void requireNoAmbientSqlTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account StartSession redemption RPC must run outside an owner SQL transaction"); + } + } + + private AccountRedemptionProjection validateResponse( + RedeemOperatorAuthorizationResponse response, + StartSessionPostAuthorizationExecutionTuple tuple) { + try { + if (response == null || !response.getUnknownFields().asMap().isEmpty()) { + throw malformedResponse(); + } + String fingerprint = response.getAuthorizationReferenceFingerprint(); + if (fingerprint == null + || !AUTHORIZATION_REFERENCE_FINGERPRINT.matcher(fingerprint).matches()) { + throw malformedResponse(); + } + + byte[] originalAccountTuple = + response.getOriginalAccountPostAuthorizationTuple().toByteArray(); + StartSessionAccountRedemptionProjection.requireCurrentBinding(originalAccountTuple, tuple); + StartSessionPostAuthorizationExecutionTuple accountTuple = + StartSessionAccountRedemptionProjection.decodeOwnerTuple(originalAccountTuple); + byte[] responseBundle = response.getAuthorityEvidenceBundle().toByteArray(); + byte[] originalBundle = accountTuple.authorityEvidenceBundleBytes(); + if (responseBundle.length == 0 || !Arrays.equals(responseBundle, originalBundle)) { + throw malformedResponse(); + } + if (!accountTuple.authorizationReferenceFingerprint().equals(fingerprint)) { + throw malformedResponse(); + } + UUID issuanceOperationId = canonicalNonNilUuid(response.getIssuanceOperationId()); + long issuanceFence = response.getIssuanceFence(); + if (issuanceFence <= 0L) { + throw malformedResponse(); + } + + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(responseBundle); + bundle.requireTupleBinding(accountTuple.preAuthorizationTuple()); + bundle.requireReferenceBinding(accountTuple.bundleReference()); + if (!bundle.issuanceOperationId().equals(issuanceOperationId) + || !accountTuple.issuanceFence().equals(Long.toString(issuanceFence)) + || !bundle.issuanceFence().equals(Long.toString(issuanceFence)) + || !bundle.expiresAt().isAfter(clock.instant())) { + throw malformedResponse(); + } + return new AccountRedemptionProjection( + fingerprint, responseBundle, issuanceOperationId, issuanceFence, originalAccountTuple); + } catch (IllegalStateException expected) { + throw expected; + } catch (RuntimeException malformed) { + throw malformedResponse(); + } + } + + private void requireUnexpiredTupleEvidence(StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + bundle.requireTupleBinding(tuple.preAuthorizationTuple()); + bundle.requireReferenceBinding(tuple.bundleReference()); + if (!bundle.expiresAt().isAfter(clock.instant())) { + throw new IllegalStateException("Account StartSession authorization evidence has expired"); + } + } + + private static void requireExactClaimBinding( + StartSessionPostAuthorizationExecutionTuple tuple, AttemptClaim claim) { + if (!tuple + .preAuthorizationTuple() + .action() + .scope() + .targetNamespace() + .equals(claim.targetNamespace()) + || !tuple.controlPlaneRequestId().equals(claim.controlPlaneRequestId()) + || claim.ownerAttemptId().equals(NIL_UUID) + || claim.ownerMutationId().equals(NIL_UUID) + || claim.claimOwnerId().equals(NIL_UUID) + || claim.ownerFence() <= 0L) { + throw new IllegalArgumentException( + "Game Session owner attempt claim differs from the complete StartSession tuple"); + } + } + + private void requireConfiguredNamespace( + StartSessionPostAuthorizationExecutionTuple tuple, AttemptClaim claim) { + if (!workloadNamespace.equals(tuple.preAuthorizationTuple().action().scope().targetNamespace()) + || !workloadNamespace.equals(claim.targetNamespace())) { + throw new IllegalArgumentException( + "Account StartSession redemption must use the configured workload namespace"); + } + } + + private static void requireOpaqueReference(String value) { + if (value == null + || !OPAQUE_REFERENCE.matcher(value).matches() + || value.getBytes(StandardCharsets.UTF_8).length > MAX_AUTHORIZATION_REFERENCE_BYTES) { + throw new IllegalArgumentException("transient Account authorization reference is malformed"); + } + } + + private static UUID canonicalNonNilUuid(String value) { + if (value == null || !CANONICAL_UUID.matcher(value).matches()) { + throw malformedResponse(); + } + try { + UUID parsed = UUID.fromString(value); + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { + throw malformedResponse(); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw malformedResponse(); + } + } + + private static CommonGrpcClientProperties requireMutualTls( + CommonGrpcClientProperties tlsProperties) { + Objects.requireNonNull(tlsProperties, "gRPC TLS properties are required"); + if (tlsProperties.isPlaintext() + || blank(tlsProperties.getCertChain()) + || blank(tlsProperties.getPrivateKey()) + || blank(tlsProperties.getCaCert())) { + throw new IllegalArgumentException( + "Account StartSession redemption requires configured mutual TLS credentials and CA"); + } + return tlsProperties; + } + + private static boolean blank(String value) { + return value == null || value.isBlank(); + } + + private static IllegalStateException malformedResponse() { + return new IllegalStateException( + "Account returned a malformed or tuple-substituted StartSession redemption projection"); + } + + /** Successful response bound to the exact locally reserved owner claim, without raw secret. */ + public record RedemptionResult( + AttemptClaim gameSessionClaim, + AccountRedemptionProjection projection, + boolean accountReplay) { + public RedemptionResult { + Objects.requireNonNull(gameSessionClaim, "Game Session owner claim is required"); + Objects.requireNonNull(projection, "Account redemption projection is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java index 6d71f1db16..ed53c65939 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java @@ -8,6 +8,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; @@ -259,6 +260,9 @@ private CanonicalInstanceLaunch createInTransaction(PreparedLaunch input) { return retained; } + // Retained launch retries replay above; this exact owner tuple guard applies only to fresh + // rows. + requireRetainedCurrentAccountTuple(input); rejectOrphanedRunOwnedInstance(input); UUID gameInstanceUuid = newNonNilUuid(); long startingRowVersion = 0L; @@ -275,6 +279,41 @@ private CanonicalInstanceLaunch createInTransaction(PreparedLaunch input) { return readLaunchRow(inserted, true); } + private void requireRetainedCurrentAccountTuple(PreparedLaunch input) { + requireOwnerTransaction(); + Record ownerAttempt = + dsl.fetchOne( + "SELECT post_authorization_execution_tuple, account_redemption_projection" + + " FROM game_session_start_session_operator_attempt" + + " WHERE target_namespace = ? AND control_plane_request_id = ? FOR UPDATE", + workloadNamespace, + input.originalTuple().controlPlaneRequestId()); + if (ownerAttempt == null) { + throw new InvalidCanonicalInstanceLaunchException( + "Exact Game Session original StartSession owner attempt is unavailable for fresh launch"); + } + + byte[] retainedTuple = ownerAttempt.get("post_authorization_execution_tuple", byte[].class); + if (retainedTuple == null + || !Arrays.equals(retainedTuple, input.originalTuple().canonicalBytes())) { + throw new InvalidCanonicalInstanceLaunchException( + "Retained Game Session original StartSession tuple differs from the exact incoming tuple"); + } + byte[] accountProjection = ownerAttempt.get("account_redemption_projection", byte[].class); + if (accountProjection == null) { + throw new InvalidCanonicalInstanceLaunchException( + "Exact Game Session original StartSession owner attempt has no full Account tuple"); + } + try { + StartSessionAccountRedemptionProjection.requireCurrentBinding( + accountProjection, input.originalTuple()); + } catch (IllegalArgumentException malformedOrLegacy) { + throw new InvalidCanonicalInstanceLaunchException( + "Retained Account redemption evidence is not the exact current full tuple", + malformedOrLegacy); + } + } + private Optional readByLaunchIdentityInTransaction( CanonicalGameInstanceLaunchAssociationReadEvidence.Request request) { requireOwnerTransaction(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java index ee99047353..03387354ba 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java @@ -4,14 +4,12 @@ import java.time.Duration; import java.time.Instant; import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import org.jooq.DSLContext; @@ -20,7 +18,6 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; -import tools.jackson.databind.json.JsonMapper; /** * Unregistered, non-activating durable reservation for one canonical StartSession owner attempt. @@ -36,7 +33,6 @@ public final class GameSessionStartSessionOperatorAttemptRepository { "game_session_start_session_operator_owner_fence_seq"; private static final Pattern AUTHORIZATION_REFERENCE_FINGERPRINT = Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); - private static final JsonMapper JSON = JsonMapper.builder().build(); private static final Duration MAX_OWNER_CLAIM_LEASE = Duration.ofMinutes(5); private final DSLContext dsl; @@ -198,12 +194,7 @@ public AttemptSnapshot readCurrentOriginalAttempt( throw new StaleStartSessionOperatorAttemptClaimException( "Original StartSession attempt has no attached Account projection"); } - AccountRedemptionProjection expectedProjection = projectionFromTuple(decodedTuple); - if (!Arrays.equals(projection, expectedProjection.canonicalBytes())) { - throw new IllegalStateException( - "Attached Account projection differs from the exact current StartSession tuple"); - } - requireProjectionMatches(decodedTuple, expectedProjection); + requireCurrentProjectionMatches(projection, decodedTuple); requireOriginalAuthorityUnexpired(decodedTuple); return current; } @@ -280,12 +271,13 @@ private Optional readHistoricalOwnerAttemptExact( throw new StaleStartSessionOperatorAttemptClaimException( "Historical StartSession owner attempt has no attached Account projection"); } - AccountRedemptionProjection expectedProjection = projectionFromTuple(decodedTuple); - if (!Arrays.equals(storedProjection, expectedProjection.canonicalBytes())) { + try { + StartSessionAccountRedemptionProjection.requireHistoricalBinding( + storedProjection, decodedTuple); + } catch (IllegalArgumentException malformed) { throw new IllegalStateException( - "Persisted historical Account projection differs from its complete canonical tuple"); + "Persisted historical Account projection differs from the exact tuple", malformed); } - requireProjectionMatches(decodedTuple, expectedProjection); return Optional.of(snapshot(row)); } @@ -321,13 +313,7 @@ public EvidenceContinuation beginEvidenceContinuation( throw new StaleStartSessionOperatorAttemptClaimException( "StartSession attempt has no attached Account projection and remains reconciliation-only"); } - AccountRedemptionProjection expectedProjection = projectionFromTuple(tuple); - byte[] canonicalProjection = expectedProjection.canonicalBytes(); - if (!Arrays.equals(storedProjection, canonicalProjection)) { - throw new IllegalStateException( - "Persisted Account redemption projection differs from its complete canonical tuple"); - } - requireProjectionMatches(tuple, expectedProjection); + requireCurrentProjectionMatches(storedProjection, tuple); return new EvidenceContinuation( requiredText(row, "target_namespace"), @@ -393,12 +379,7 @@ AttemptSnapshot validateEvidenceContinuation(EvidenceContinuation continuation) "Evidence continuation tuple is not the canonical original owner identity"); } requireStoredProjectionColumnsMatch(row, tuple); - AccountRedemptionProjection expectedProjection = projectionFromTuple(tuple); - if (!Arrays.equals(currentProjection, expectedProjection.canonicalBytes())) { - throw new IllegalStateException( - "Evidence continuation Account projection is not canonical for its tuple"); - } - requireProjectionMatches(tuple, expectedProjection); + requireCurrentProjectionMatches(currentProjection, tuple); return snapshot(row); } @@ -486,31 +467,19 @@ private static void requireStoredProjectionColumnsMatch( } } - private static void requireProjectionMatches( - StartSessionPostAuthorizationExecutionTuple tuple, AccountRedemptionProjection projection) { - if (!tuple - .authorizationReferenceFingerprint() - .equals(projection.authorizationReferenceFingerprint()) - || !Arrays.equals( - tuple.authorityEvidenceBundleBytes(), projection.authorityEvidenceBundleBytes()) - || !StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) - .issuanceOperationId() - .equals(projection.issuanceOperationId()) - || parsePositiveFence(tuple.issuanceFence()) != projection.issuanceFence()) { + private static void requireCurrentProjectionMatches( + byte[] projection, StartSessionPostAuthorizationExecutionTuple tuple) { + try { + StartSessionAccountRedemptionProjection.requireCurrentBinding(projection, tuple); + } catch (IllegalArgumentException malformedOrLegacy) { throw new StartSessionOperatorAttemptConflictException( - "Account redemption projection is not bound to the exact post-authorization tuple"); + "Account redemption projection is missing, legacy, malformed, or bound to another tuple"); } } - private static AccountRedemptionProjection projectionFromTuple( - StartSessionPostAuthorizationExecutionTuple tuple) { - StartSessionAuthorityEvidenceBundle authority = - StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); - return new AccountRedemptionProjection( - tuple.authorizationReferenceFingerprint(), - tuple.authorityEvidenceBundleBytes(), - authority.issuanceOperationId(), - parsePositiveFence(tuple.issuanceFence())); + private static void requireProjectionMatches( + StartSessionPostAuthorizationExecutionTuple tuple, AccountRedemptionProjection projection) { + requireCurrentProjectionMatches(projection.originalAccountPostAuthorizationTuple(), tuple); } private static void requireClaimMatch(Record row, AttemptClaim claim) { @@ -874,7 +843,8 @@ public record AccountRedemptionProjection( String authorizationReferenceFingerprint, byte[] authorityEvidenceBundleBytes, UUID issuanceOperationId, - long issuanceFence) { + long issuanceFence, + byte[] originalAccountPostAuthorizationTuple) { public AccountRedemptionProjection { if (authorizationReferenceFingerprint == null || !AUTHORIZATION_REFERENCE_FINGERPRINT @@ -886,6 +856,11 @@ public record AccountRedemptionProjection( Objects.requireNonNull( authorityEvidenceBundleBytes, "authority evidence bundle is required") .clone(); + originalAccountPostAuthorizationTuple = + Objects.requireNonNull( + originalAccountPostAuthorizationTuple, + "independently returned Account owner tuple is required") + .clone(); Objects.requireNonNull(issuanceOperationId, "issuanceOperationId is required"); if (issuanceOperationId.equals(NIL_UUID) || issuanceFence <= 0L) { throw new IllegalArgumentException( @@ -898,6 +873,18 @@ public record AccountRedemptionProjection( throw new IllegalArgumentException( "Account redemption response differs from its exact authority evidence bundle"); } + StartSessionPostAuthorizationExecutionTuple ownerTuple = + StartSessionAccountRedemptionProjection.decodeOwnerTuple( + originalAccountPostAuthorizationTuple); + if (!Arrays.equals(ownerTuple.canonicalBytes(), originalAccountPostAuthorizationTuple) + || !ownerTuple + .authorizationReferenceFingerprint() + .equals(authorizationReferenceFingerprint) + || !Arrays.equals(ownerTuple.authorityEvidenceBundleBytes(), authorityEvidenceBundleBytes) + || !ownerTuple.issuanceFence().equals(Long.toString(issuanceFence))) { + throw new IllegalArgumentException( + "Account redemption projection fields differ from the independently returned tuple"); + } } @Override @@ -905,27 +892,13 @@ public byte[] authorityEvidenceBundleBytes() { return authorityEvidenceBundleBytes.clone(); } + @Override + public byte[] originalAccountPostAuthorizationTuple() { + return originalAccountPostAuthorizationTuple.clone(); + } + public byte[] canonicalBytes() { - StartSessionAuthorityEvidenceBundle bundle = - StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundleBytes); - Map projection = new LinkedHashMap<>(); - projection.put("projectionSchemaId", "accountStartSessionRedemptionProjection"); - projection.put("projectionSchemaVersion", "1"); - projection.put("authorizationReferenceFingerprint", authorizationReferenceFingerprint); - projection.put("authorityEvidenceBundle", bundle.jsonValue()); - projection.put("issuanceOperationId", issuanceOperationId.toString()); - projection.put("issuanceFence", issuanceFence); - try { - byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); - if (bytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES) { - throw new IllegalArgumentException( - "Account redemption projection exceeds its byte limit"); - } - return bytes; - } catch (java.io.IOException exception) { - throw new IllegalStateException( - "could not encode Account redemption projection", exception); - } + return originalAccountPostAuthorizationTuple(); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcService.java index 0d4428c662..488f5cb3ee 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcService.java @@ -4,12 +4,11 @@ import io.grpc.stub.StreamObserver; import java.util.Arrays; import java.util.Objects; +import net.firedevops.firemud.common.account.startsession.StartSessionAccountRedemptionProjection; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence; import net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidenceGrpcCodec; -import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; -import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StaleStartSessionOperatorAttemptClaimException; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.StartSessionOperatorAttemptConflictException; @@ -142,19 +141,8 @@ private static void requireExactSnapshot( throw new IllegalStateException( "Repository returned a different or incomplete current original StartSession attempt"); } - StartSessionAuthorityEvidenceBundle authority = - StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); - byte[] expectedProjection = - new AccountRedemptionProjection( - tuple.authorizationReferenceFingerprint(), - tuple.authorityEvidenceBundleBytes(), - authority.issuanceOperationId(), - Long.parseLong(tuple.issuanceFence())) - .canonicalBytes(); - if (!Arrays.equals(expectedProjection, snapshot.accountRedemptionProjection())) { - throw new IllegalStateException( - "Repository returned an Account projection different from the exact original tuple"); - } + StartSessionAccountRedemptionProjection.requireCurrentBinding( + snapshot.accountRedemptionProjection(), tuple); } private static void requireNoAmbientTransaction() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java index 33d172ec0a..b1bb23566a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java @@ -68,7 +68,7 @@ class GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest { void retainsExactEmptyOwnerResultAndRejectsConflictOrMutation() throws Exception { try (Fixture fixture = newFixture()) { LaunchInputs launch = fixture.createLaunch(); - var attempt = fixture.createAttempt(launch.proof().originalTuple()); + var attempt = launch.attempt(); var selector = exactReplayRequest(launch, attempt.claim()); byte[] requestBytes = StartSessionTemplateAssociationReadGrpcCodec.toRequest(selector).toByteArray(); @@ -154,7 +154,7 @@ void retainsExactEmptyOwnerResultAndRejectsConflictOrMutation() throws Exception void originalSelectionPinIsAppendOnlyAndBoundToTheExactLiveAttemptAndLaunch() throws Exception { try (Fixture fixture = newFixture()) { LaunchInputs launch = fixture.createLaunch(); - AttemptInputs attempt = fixture.createAttempt(launch.proof().originalTuple()); + AttemptInputs attempt = launch.attempt(); var tuple = launch.proof().originalTuple(); byte[] selectionRequest = new byte[] {1}; byte[] selectionResponse = new byte[] {2}; @@ -301,9 +301,8 @@ void originalSelectionPinIsAppendOnlyAndBoundToTheExactLiveAttemptAndLaunch() th } try (Fixture fixture = newFixture()) { - LaunchInputs launch = fixture.createLaunch(); - AttemptInputs expiringAttempt = - fixture.createAttempt(launch.proof().originalTuple(), Duration.ofSeconds(2)); + LaunchInputs launch = fixture.createLaunch(Duration.ofSeconds(2)); + AttemptInputs expiringAttempt = launch.attempt(); Thread.sleep(Duration.ofMillis(2200).toMillis()); assertThatThrownBy( () -> @@ -583,7 +582,10 @@ private static Fixture newFixture() { } private record LaunchInputs( - CanonicalRealmCatalog catalog, SyntheticLaunchProof proof, UUID gameInstanceUuid) {} + CanonicalRealmCatalog catalog, + SyntheticLaunchProof proof, + UUID gameInstanceUuid, + AttemptInputs attempt) {} private record AttemptInputs( AttemptClaim claim, @@ -605,6 +607,10 @@ GameSessionAuthoredActorCoreRetentionRepository retentionRepository() { } LaunchInputs createLaunch() { + return createLaunch(Duration.ofMinutes(5)); + } + + LaunchInputs createLaunch(Duration leaseDuration) { FreshTenantAssociation fresh = createFreshAssociation(); var catalogProof = GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(fresh); CanonicalRealmCatalog catalog = @@ -616,6 +622,7 @@ LaunchInputs createLaunch() { UUID.randomUUID(), UUID.randomUUID()); SyntheticLaunchProof proof = launchProof(catalog); + AttemptInputs attempt = createAttempt(proof.originalTuple(), leaseDuration); var launches = new GameSessionCanonicalInstanceLaunchRepository( dsl, @@ -625,12 +632,7 @@ LaunchInputs createLaunch() { var created = launches.createStartingLaunch( proof.originalTuple(), proof.completeLaunchBindingEvidence(), catalog); - return new LaunchInputs(catalog, proof, created.gameInstanceUuid()); - } - - AttemptInputs createAttempt( - net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple tuple) { - return createAttempt(tuple, Duration.ofMinutes(5)); + return new LaunchInputs(catalog, proof, created.gameInstanceUuid(), attempt); } AttemptInputs createAttempt( @@ -650,7 +652,9 @@ AttemptInputs createAttempt( tuple.authorizationReferenceFingerprint(), tuple.authorityEvidenceBundleBytes(), bundle.issuanceOperationId(), - Long.parseLong(bundle.issuanceFence())); + Long.parseLong(bundle.issuanceFence()), + tuple.canonicalBytes()); + // Synthetic Account fixture: the retained tuple is exact, but this does not prove RPC origin. var attached = Objects.requireNonNull( transactions() diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java index b09e5d9d6c..bf64511530 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchPostgresIntegrationTest.java @@ -5,12 +5,18 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.io.IOException; import java.nio.file.Path; import java.sql.Connection; import java.sql.Statement; +import java.time.Duration; +import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; @@ -19,6 +25,8 @@ import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository.InvalidCanonicalInstanceLaunchException; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.CanonicalRealmCatalog; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociation; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -31,9 +39,11 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; /** * PostgreSQL proof of atomic original StartSession owner allocation and exact retained readback. @@ -47,6 +57,7 @@ class GameSessionCanonicalInstanceLaunchPostgresIntegrationTest { private static final String MIGRATION_LOCATION = "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); private static final String NAMESPACE = "test"; + private static final JsonMapper JSON = JsonMapper.builder().build(); @Container static PostgreSQLContainer postgres = @@ -226,6 +237,59 @@ void rollsBackRuntimeAllocationWhenAtomicLaunchAssociationInsertFails() throws E } } + @Test + void freshAllocationRequiresRetainedFullAccountTupleBeforeCreatingRuntime() throws Exception { + try (Fixture fixture = newFixture(null)) { + for (OwnerEvidenceMode mode : + new OwnerEvidenceMode[] { + OwnerEvidenceMode.ABSENT, OwnerEvidenceMode.UNATTACHED, OwnerEvidenceMode.LEGACY_SCALAR + }) { + LaunchInputs inputs = prepareLaunch(fixture, mode); + + assertThatThrownBy( + () -> + inputs + .repository() + .createStartingLaunch( + inputs.proof().originalTuple(), + inputs.proof().completeLaunchBindingEvidence(), + inputs.catalog())) + .isInstanceOf(InvalidCanonicalInstanceLaunchException.class) + .hasMessageContaining(mode.expectedFailure()); + assertNoAllocation(fixture, inputs.proof().originalTuple().controlPlaneRequestId()); + } + } + } + + @Test + void freshAllocationRejectsSourceFenceAndLinearizationSubstitution() throws Exception { + try (Fixture fixture = newFixture(null)) { + for (boolean changeSourceFence : new boolean[] {true, false}) { + LaunchInputs inputs = prepareLaunch(fixture); + StartSessionPostAuthorizationExecutionTuple original = inputs.proof().originalTuple(); + StartSessionPostAuthorizationExecutionTuple substituted = + withBundleReference( + original, + changeSourceFence ? "24" : original.bundleReference().sourceFence(), + changeSourceFence + ? original.bundleReference().linearization() + : "18446744073709551614"); + + assertThatThrownBy( + () -> + inputs + .repository() + .createStartingLaunch( + substituted, + inputs.proof().completeLaunchBindingEvidence(), + inputs.catalog())) + .isInstanceOf(InvalidCanonicalInstanceLaunchException.class) + .hasMessageContaining("differs from the exact incoming tuple"); + assertNoAllocation(fixture, original.controlPlaneRequestId()); + } + } + } + @Test void retainedV42LaunchWithoutCapturedTupleRemainsNullAndCannotBeUpgradedByRetry() throws Exception { @@ -275,6 +339,10 @@ void retainedV42LaunchWithoutCapturedTupleRemainsNullAndCannotBeUpgradedByRetry( } private static LaunchInputs prepareLaunch(Fixture fixture) { + return prepareLaunch(fixture, OwnerEvidenceMode.ATTACHED); + } + + private static LaunchInputs prepareLaunch(Fixture fixture, OwnerEvidenceMode ownerEvidenceMode) { FreshTenantAssociation association = createFreshAssociation(fixture); var catalogProof = GameSessionCanonicalRealmCatalogProofFixtures.forFreshAssociation(association); @@ -305,9 +373,114 @@ private static LaunchInputs prepareLaunch(Fixture fixture) { "generation-fixture", 2L, releaseRef); + attachSyntheticOwnerEvidence(fixture, proof.originalTuple(), ownerEvidenceMode); return new LaunchInputs(catalog, proof, fixture.launchRepository()); } + private static void attachSyntheticOwnerEvidence( + Fixture fixture, StartSessionPostAuthorizationExecutionTuple tuple, OwnerEvidenceMode mode) { + if (mode == OwnerEvidenceMode.ABSENT) return; + + GameSessionStartSessionOperatorAttemptRepository attempts = + new GameSessionStartSessionOperatorAttemptRepository(fixture.dsl(), Duration.ofMinutes(5)); + TransactionTemplate ownerTransaction = new TransactionTemplate(fixture.transactionManager()); + AttemptClaim claim = + Objects.requireNonNull( + ownerTransaction.execute(status -> attempts.reserve(tuple)), + "synthetic owner attempt reservation") + .claim() + .orElseThrow(); + if (mode == OwnerEvidenceMode.UNATTACHED) return; + + if (mode == OwnerEvidenceMode.LEGACY_SCALAR) { + int attached = + fixture + .dsl() + .execute( + "UPDATE game_session_start_session_operator_attempt" + + " SET account_redemption_projection = ?" + + " WHERE target_namespace = ? AND control_plane_request_id = ?" + + " AND account_redemption_projection IS NULL", + legacyScalarProjection(tuple), + NAMESPACE, + tuple.controlPlaneRequestId()); + assertThat(attached).isEqualTo(1); + return; + } + + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + AccountRedemptionProjection syntheticProjection = + new AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence()), + tuple.canonicalBytes()); + // The fixture models a synthetic Account response; exact bytes do not prove RPC origin. + Objects.requireNonNull( + ownerTransaction.execute( + status -> attempts.attachAccountRedemptionProjection(claim, syntheticProjection)), + "synthetic Account tuple attachment"); + } + + private static byte[] legacyScalarProjection(StartSessionPostAuthorizationExecutionTuple tuple) { + // Schema-v1 is synthesized only to verify historical compatibility and current fail-closed + // behavior. + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + Map projection = + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + Long.parseLong(tuple.issuanceFence())); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + } catch (IOException malformed) { + throw new IllegalStateException( + "Could not encode a legacy scalar Account projection", malformed); + } + } + + private static StartSessionPostAuthorizationExecutionTuple withBundleReference( + StartSessionPostAuthorizationExecutionTuple original, + String sourceFence, + String linearization) { + var reference = original.bundleReference(); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + original.preAuthorizationTuple(), + original.authenticatedWorkloadIdentity(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.authorityEvidenceBundleBytes(), + new StartSessionAuthorityEvidenceBundle.BundleReference( + reference.bundleVersion(), reference.sourceVersion(), sourceFence, linearization)); + } + + private static void assertNoAllocation(Fixture fixture, String requestId) { + assertThat( + countByRequest( + fixture.dsl(), "game_instances", "run_owned_start_request_id", requestId)) + .isZero(); + assertThat( + countByRequest( + fixture.dsl(), + "game_session_canonical_instance_launch", + "control_plane_request_id", + requestId)) + .isZero(); + } + private static CanonicalGameInstanceLaunchAssociationReadEvidence.Request selector( SyntheticLaunchProof proof, CanonicalRealmCatalog catalog, UUID gameInstanceUuid) { var descriptor = proof.completeLaunchBindingEvidence().descriptor(); @@ -483,6 +656,23 @@ private record LaunchInputs( SyntheticLaunchProof proof, GameSessionCanonicalInstanceLaunchRepository repository) {} + private enum OwnerEvidenceMode { + ATTACHED(""), + ABSENT("unavailable for fresh launch"), + UNATTACHED("no full Account tuple"), + LEGACY_SCALAR("not the exact current full tuple"); + + private final String expectedFailure; + + OwnerEvidenceMode(String expectedFailure) { + this.expectedFailure = expectedFailure; + } + + String expectedFailure() { + return expectedFailure; + } + } + private record Fixture( String schema, DriverManagerDataSource dataSource, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java index f0f9363eeb..68f260ac6f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest.java @@ -39,7 +39,10 @@ import org.testcontainers.junit.jupiter.Testcontainers; import tools.jackson.databind.json.JsonMapper; -/** PostgreSQL proof of the exact, observation-only current original StartSession attempt read. */ +/** + * PostgreSQL proof of exact original-attempt reads. Synthetic Account projection bytes prove + * persistence and readback binding only, not Account RPC provenance. + */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class OriginalStartSessionCurrentAttemptReadPostgresIntegrationTest { @@ -71,6 +74,7 @@ void currentOriginalAttemptReadReturnsExactAttachedSnapshotWithoutChangingPersis fixture.attach( claim, projection( + tuple, tuple.authorizationReferenceFingerprint(), tuple.authorityEvidenceBundleBytes(), ISSUANCE_ID, @@ -94,6 +98,92 @@ void currentOriginalAttemptReadReturnsExactAttachedSnapshotWithoutChangingPersis assertThat(fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId())).isEqualTo(before); } + @Test + void exactLargeReservationFencesSurviveOwnerReservationAndProjectionReplay() { + for (long fence : + new long[] { + 9_007_199_254_740_991L, 9_007_199_254_740_992L, 9_007_199_254_740_993L, Long.MAX_VALUE + }) { + Fixture fixture = fixture(Duration.ofSeconds(30)); + var baseline = tuple("operator-attempt-large-fence-" + fence); + var tuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + baseline.preAuthorizationTuple(), + baseline.authenticatedWorkloadIdentity(), + baseline.authorizationReferenceFingerprint(), + baseline.reservationOwnerId(), + fence, + baseline.authorityEvidenceBundleBytes(), + baseline.bundleReference()); + var reserved = fixture.reserve(tuple); + AttemptClaim claim = reserved.claim().orElseThrow(); + byte[] originalBytes = tuple.canonicalBytes(); + var accountProjection = + projection( + tuple, + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + ISSUANCE_ID, + 23L); + AttemptSnapshot attached = fixture.attach(claim, accountProjection); + AttemptSnapshot replayed = fixture.attach(claim, accountProjection); + String retainedRow = fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId()); + + assertThat(replayed.postAuthorizationExecutionTuple()).containsExactly(originalBytes); + assertThat(replayed.accountRedemptionProjection()) + .containsExactly(attached.accountRedemptionProjection()); + assertThat( + StartSessionPostAuthorizationExecutionTuple.decode( + replayed.postAuthorizationExecutionTuple()) + .reservationClaimFence()) + .isEqualTo(fence); + assertThat(fixture.reserve(tuple).disposition()) + .isEqualTo( + GameSessionStartSessionOperatorAttemptRepository.ReservationDisposition.EXACT_REPLAY); + assertThat(fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId())).isEqualTo(retainedRow); + assertThat(fixture.dsl().fetchCount(DSL.table("game_session_start_session_operator_attempt"))) + .isEqualTo(1); + assertThat(fixture.dsl().fetchCount(DSL.table("game_instances"))).isZero(); + assertThat(fixture.dsl().fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + } + } + + @Test + void historicalReadPreservesLegacyScalarBytesWhileCurrentReadFailsClosed() { + Fixture fixture = fixture(Duration.ofMinutes(1)); + StartSessionPostAuthorizationExecutionTuple tuple = tuple("historical-scalar-v1"); + UUID ownerAttemptId = UUID.randomUUID(); + UUID ownerMutationId = UUID.randomUUID(); + long ownerFence = 1L; + byte[] legacyScalarProjection = legacyScalarProjection(tuple); + fixture.insertLegacyAttempt( + tuple, + ownerAttemptId, + ownerMutationId, + UUID.randomUUID(), + ownerFence, + legacyScalarProjection); + String before = fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId()); + + AttemptSnapshot historical = + fixture + .repository() + .readHistoricalOwnerAttempt(tuple, ownerAttemptId, ownerFence) + .orElseThrow(); + + assertThat(historical.accountRedemptionProjection()).containsExactly(legacyScalarProjection); + assertThat(fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId())).isEqualTo(before); + assertThatThrownBy( + () -> + fixture.currentOriginalAttempt( + currentAttemptRequest(tuple, ownerAttemptId, ownerMutationId, ownerFence))) + .isInstanceOf( + GameSessionStartSessionOperatorAttemptRepository + .StartSessionOperatorAttemptConflictException.class) + .hasMessageContaining("legacy"); + assertThat(fixture.ownerAttemptRowJson(tuple.controlPlaneRequestId())).isEqualTo(before); + } + @Test void currentOriginalAttemptReadRejectsExpiredAndUnattachedOrMismatchedEvidenceWithoutMutation() throws Exception { @@ -118,6 +208,7 @@ void currentOriginalAttemptReadRejectsExpiredAndUnattachedOrMismatchedEvidenceWi mismatched.attach( claim, projection( + tuple, tuple.authorizationReferenceFingerprint(), tuple.authorityEvidenceBundleBytes(), ISSUANCE_ID, @@ -166,6 +257,7 @@ void currentOriginalAttemptReadRejectsExpiredAndUnattachedOrMismatchedEvidenceWi expired.attach( expiredClaim, projection( + expiredTuple, expiredTuple.authorizationReferenceFingerprint(), expiredTuple.authorityEvidenceBundleBytes(), ISSUANCE_ID, @@ -196,6 +288,7 @@ void currentOriginalAttemptReadRejectsExpiredAccountReferenceWithLiveClaimWithou fixture.attach( claim, projection( + tuple, tuple.authorizationReferenceFingerprint(), tuple.authorityEvidenceBundleBytes(), ISSUANCE_ID, @@ -269,8 +362,37 @@ private static StartSessionPostAuthorizationExecutionTuple tuple( } private static AccountRedemptionProjection projection( - String fingerprint, byte[] bundle, UUID issuanceOperationId, long issuanceFence) { - return new AccountRedemptionProjection(fingerprint, bundle, issuanceOperationId, issuanceFence); + StartSessionPostAuthorizationExecutionTuple tuple, + String fingerprint, + byte[] bundle, + UUID issuanceOperationId, + long issuanceFence) { + return new AccountRedemptionProjection( + fingerprint, bundle, issuanceOperationId, issuanceFence, tuple.canonicalBytes()); + } + + private static byte[] legacyScalarProjection(StartSessionPostAuthorizationExecutionTuple tuple) { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + Map projection = + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + bundle.jsonValue(), + "issuanceOperationId", + bundle.issuanceOperationId().toString(), + "issuanceFence", + Long.parseLong(tuple.issuanceFence())); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + } catch (IOException malformed) { + throw new IllegalStateException("Could not encode a legacy scalar projection", malformed); + } } private static Request currentAttemptRequest( @@ -450,6 +572,35 @@ AttemptSnapshot currentOriginalAttempt(Request request) { "Current original StartSession attempt snapshot"); } + void insertLegacyAttempt( + StartSessionPostAuthorizationExecutionTuple tuple, + UUID ownerAttemptId, + UUID ownerMutationId, + UUID claimOwnerId, + long ownerFence, + byte[] legacyProjection) { + dsl.execute( + "INSERT INTO game_session_start_session_operator_attempt" + + " (target_namespace, control_plane_request_id, canonical_tenant_id," + + " owner_attempt_id, owner_mutation_id, claim_owner_id, owner_fence," + + " post_authorization_execution_tuple, mutation_digest," + + " authorization_reference_fingerprint, account_redemption_projection," + + " lease_expires_at)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " clock_timestamp() + interval '5 minutes')", + NAMESPACE, + tuple.controlPlaneRequestId(), + tuple.preAuthorizationTuple().action().scope().tenantId(), + ownerAttemptId, + ownerMutationId, + claimOwnerId, + ownerFence, + tuple.canonicalBytes(), + tuple.mutationDigest(), + tuple.authorizationReferenceFingerprint(), + legacyProjection); + } + String ownerAttemptRowJson(String requestId) { org.jooq.Record row = dsl.fetchOne( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java new file mode 100644 index 0000000000..0628386957 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java @@ -0,0 +1,605 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.google.protobuf.ByteString; +import io.grpc.CallCredentials; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.AbstractStub; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +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 tools.jackson.databind.json.JsonMapper; + +/** Physical socket proof that redemption reaches only the exact same-namespace Account workload. */ +class StartSessionOperatorRedemptionClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String WRONG_NAMESPACE_URI = "spiffe://firemud/ns/other/sa/account-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String REFERENCE = "A".repeat(43); + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID ACTOR_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID TARGET_OWNER_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("52345678-1234-4234-8234-123456789abc"); + private static final UUID OWNER_MUTATION_ID = + UUID.fromString("62345678-1234-4234-8234-123456789abc"); + private static final UUID CLAIM_OWNER_ID = + UUID.fromString("72345678-1234-4234-8234-123456789abc"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); + private static final UUID CONTROL_UI_JTI = + UUID.fromString("92345678-1234-4234-8234-123456789abc"); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final long RESERVATION_FENCE = 4L; + private static final long OWNER_FENCE = 9L; + private static final long ISSUANCE_FENCE = 23L; + private static final Clock FIXED_CLOCK = + Clock.fixed(Instant.parse("2026-10-09T00:00:00Z"), ZoneOffset.UTC); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir static Path temporaryDirectory; + + private static TestPki pki; + private Server server; + private StartSessionOperatorRedemptionClient client; + private AtomicInteger rpcStarts; + private AtomicInteger applicationCalls; + private AtomicReference receivedPeer; + private AtomicReference receivedRequest; + + @BeforeAll + static void createLocalTestCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void redeemsOverSocketMtlsWithExactSameNamespaceAccountPeer() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(); + startServer(pki.accountServer(), tuple); + client = newClient(server); + client.initialize(); + + var result = client.redeem(tuple, REFERENCE, claim()); + + assertThat(result.gameSessionClaim()).isEqualTo(claim()); + assertThat(result.projection().authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(result.projection().issuanceOperationId()).isEqualTo(ISSUANCE_OPERATION_ID); + assertThat(result.projection().issuanceFence()).isEqualTo(ISSUANCE_FENCE); + assertThat(result.toString()).doesNotContain(REFERENCE); + assertThat(rpcStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + assertThat(receivedPeer.get()) + .isNotNull() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(GAME_SESSION_URI); + assertThat(receivedRequest.get().getOperatorAuthorizationReference()).isEqualTo(REFERENCE); + } + + @Test + void sameCaWrongWorkloadAndWrongNamespaceAccountServersReceiveNoRedemptionRpc() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(); + for (TestIdentity wrongServer : + List.of(pki.wrongWorkloadServer(), pki.wrongNamespaceServer())) { + startServer(wrongServer, tuple); + client = newClient(server); + client.initialize(); + + Throwable failure = catchThrowable(() -> client.redeem(tuple, REFERENCE, claim())); + + assertThat(failure) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + thrown -> + assertThat(((StatusRuntimeException) thrown).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)) + .hasMessageNotContaining(REFERENCE); + assertThat(rpcStarts).hasValue(0); + assertThat(applicationCalls).hasValue(0); + assertThat(receivedRequest.get()).isNull(); + stopTransport(); + } + } + + private void startServer( + TestIdentity serverIdentity, StartSessionPostAuthorizationExecutionTuple tuple) + throws Exception { + rpcStarts = new AtomicInteger(); + applicationCalls = new AtomicInteger(); + receivedPeer = new AtomicReference<>(); + receivedRequest = new AtomicReference<>(); + var service = + new StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceImplBase() { + @Override + public void redeemOperatorAuthorization( + RedeemOperatorAuthorizationRequest request, + StreamObserver observer) { + applicationCalls.incrementAndGet(); + receivedPeer.set(GrpcPeerIdentity.current()); + receivedRequest.set(request); + observer.onNext(response(tuple)); + observer.onCompleted(); + } + }; + ServerInterceptor countRpcStarts = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + rpcStarts.incrementAndGet(); + return next.startCall(call, headers); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countRpcStarts, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private StartSessionOperatorRedemptionClient newClient(Server target) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + target.getPort()); + return new StartSessionOperatorRedemptionClient( + endpoints, + pki.clientProperties(temporaryDirectory), + new GrpcChannelFactory(), + customizerThatReplacesCallCredentials(), + NAMESPACE, + FIXED_CLOCK); + } + + private static BlockingGrpcStubCustomizer customizerThatReplacesCallCredentials() { + return new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T stub) { + return stub.withCallCredentials( + new CallCredentials() { + @Override + public void applyRequestMetadata( + RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { + applier.apply(new Metadata()); + } + }); + } + }; + } + + private static RedeemOperatorAuthorizationResponse response( + StartSessionPostAuthorizationExecutionTuple tuple) { + return RedeemOperatorAuthorizationResponse.newBuilder() + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setAuthorityEvidenceBundle(ByteString.copyFrom(tuple.authorityEvidenceBundleBytes())) + .setIssuanceOperationId(ISSUANCE_OPERATION_ID.toString()) + .setIssuanceFence(ISSUANCE_FENCE) + .setOriginalAccountPostAuthorizationTuple(ByteString.copyFrom(tuple.canonicalBytes())) + .setReplay(false) + .build(); + } + + private static AttemptClaim claim() { + return new AttemptClaim( + NAMESPACE, + "socket-redemption-request", + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + CLAIM_OWNER_ID, + OWNER_FENCE); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple() { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "socket mTLS redemption peer identity proof"); + StartSessionPreAuthorizationReservationTuple preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + "socket-redemption-request", ACTOR_ID, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/test/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER_ID, + RESERVATION_FENCE, + authorityEvidenceBundle(preTuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + Long.toString(ISSUANCE_FENCE), + "18446744073709551615")); + } + + private static byte[] authorityEvidenceBundle( + StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = TENANT_ID.toString(); + Map value = + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", NAMESPACE), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR_ID.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + "2026-10-09T00:00:00Z", + "expiresAt", + "2026-10-10T00:00:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", ISSUANCE_OPERATION_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", Long.toString(ISSUANCE_FENCE), + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR_ID.toString(), + "controlUiTokenJti", + CONTROL_UI_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException malformed) { + throw new IllegalStateException("could not encode test Account authority bundle", malformed); + } + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity accountServer, + TestIdentity wrongWorkloadServer, + TestIdentity wrongNamespaceServer, + TestIdentity gameSessionClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("redemption-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD redemption client test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("redemption-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-workload-account-server", + WRONG_WORKLOAD_URI, + true), + issueIdentity( + directory, + caStore, + caFile, + "wrong-namespace-account-server", + WRONG_NAMESPACE_URI, + true), + issueIdentity( + directory, caStore, caFile, "game-session-client", GAME_SESSION_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) throws Exception { + Path clientCertificate = + writePem( + directory.resolve("game-session-client.crt"), + "CERTIFICATE", + gameSessionClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-session-client.key"), + "PRIVATE KEY", + gameSessionClient.privateKey().getEncoded()); + Path trustCa = + writePem( + directory.resolve("redemption-client-trust-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(trustCa.toString()); + properties.setPlaintext(false); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + List command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("keytool timed out"); + } + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java new file mode 100644 index 0000000000..c0411d5de5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java @@ -0,0 +1,570 @@ +package net.firedevops.firemud.gamesession.client; + +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.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Contract tests use synthetic Account responses and do not prove remote authorization provenance. + */ +class StartSessionOperatorRedemptionClientTest { + private static final UUID TENANT = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID TARGET_OWNER = UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER = + UUID.fromString("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final UUID OWNER_ATTEMPT = UUID.fromString("69116466-a576-4fa6-9e11-4c0c6b2a92f0"); + private static final UUID OWNER_MUTATION = + UUID.fromString("89da7d84-12f5-4cf8-b69b-30ba8eb115a4"); + private static final UUID CLAIM_OWNER = UUID.fromString("31f85ac3-e621-4c38-a207-0e5aab116d34"); + private static final UUID ISSUANCE_ID = UUID.fromString("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"); + private static final UUID TOKEN_JTI = UUID.fromString("a681bba7-c215-4cf1-a35b-14348912cbdc"); + private static final String NAMESPACE = "world-runtime"; + private static final String REQUEST_ID = "redemption-client-request"; + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String OPAQUE_REFERENCE = "A".repeat(43); + private static final Clock CURRENT_CLOCK = + Clock.fixed(Instant.parse("2026-10-09T00:00:00Z"), ZoneOffset.UTC); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @AfterEach + void clearTransactionSynchronization() { + TransactionSynchronizationManager.clear(); + } + + @Test + void sendsExactPreTupleReservationAndActualGameSessionAttemptClaimOnce() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + AttemptClaim claim = claim(REQUEST_ID); + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class))) + .thenReturn(validResponse(tuple)); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + + StartSessionOperatorRedemptionClient.RedemptionResult result = + client.redeem(tuple, OPAQUE_REFERENCE, claim); + + var requestCaptor = + org.mockito.ArgumentCaptor.forClass(RedeemOperatorAuthorizationRequest.class); + verify(stub, times(1)).redeemOperatorAuthorization(requestCaptor.capture()); + RedeemOperatorAuthorizationRequest request = requestCaptor.getValue(); + assertThat(request.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly( + tuple.preAuthorizationTuple().canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(request.getOperatorAuthorizationReference()).isEqualTo(OPAQUE_REFERENCE); + assertThat(request.getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(request.getReservationOwnerId()).isEqualTo(RESERVATION_OWNER.toString()); + assertThat(request.getReservationClaimFence()).isEqualTo(19L); + assertThat(request.getOwnerAttemptId()).isEqualTo(OWNER_ATTEMPT.toString()); + assertThat(request.getOwnerFence()).isEqualTo(37L); + assertThat(result.gameSessionClaim()).isEqualTo(claim); + assertThat(result.accountReplay()).isFalse(); + AccountRedemptionProjection projection = result.projection(); + assertThat(projection.authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(projection.authorityEvidenceBundleBytes()) + .containsExactly(tuple.authorityEvidenceBundleBytes()); + assertThat(projection.issuanceOperationId()).isEqualTo(ISSUANCE_ID); + assertThat(projection.issuanceFence()).isEqualTo(23L); + assertThat(projection.originalAccountPostAuthorizationTuple()) + .containsExactly(tuple.canonicalBytes()); + assertThat(projection.canonicalBytes()).containsExactly(tuple.canonicalBytes()); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsIndependentAccountTupleWithChangedFenceOrLinearization() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + assertRejected( + tuple, validResponse(tuple, tupleWithReference(tuple, "24", "18446744073709551615"))); + assertRejected( + tuple, validResponse(tuple, tupleWithReference(tuple, "23", "18446744073709551614"))); + } + + @Test + void rejectsIndependentAccountTupleWithChangedBundleVersionOrSourceVersion() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + String sourceVersionSubstitution = + tuple.canonicalJson().replace("\"sourceVersion\":\"17\"", "\"sourceVersion\":\"18\""); + assertRejected( + tuple, validResponse(tuple, sourceVersionSubstitution.getBytes(StandardCharsets.UTF_8))); + + String bundleVersionSubstitution = + tuple + .canonicalJson() + .replace( + "\"bundleVersion\":\"" + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION + "\"", + "\"bundleVersion\":\"unsupported\""); + assertRejected( + tuple, validResponse(tuple, bundleVersionSubstitution.getBytes(StandardCharsets.UTF_8))); + } + + @Test + void acceptsCanonicalIndependentOwnerTupleOnAccountReplay() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class))) + .thenReturn(validResponse(tuple).toBuilder().setReplay(true).build()); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + + var result = client.redeem(tuple, OPAQUE_REFERENCE, claim(REQUEST_ID)); + + assertThat(result.accountReplay()).isTrue(); + assertThat(result.projection().canonicalBytes()).containsExactly(tuple.canonicalBytes()); + verify(stub, times(1)) + .redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class)); + } + + @Test + void rejectsMismatchedClaimAndExpiredAuthorityBeforeCallingAccount() throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + + assertThatThrownBy( + () -> + client.redeem( + tuple, + OPAQUE_REFERENCE, + new AttemptClaim( + "another-namespace", + REQUEST_ID, + OWNER_ATTEMPT, + OWNER_MUTATION, + CLAIM_OWNER, + 37L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("claim differs"); + + StartSessionPostAuthorizationExecutionTuple expired = + tuple(REQUEST_ID, "2026-10-09T00:00:00Z", "2026-10-09T00:00:30Z"); + StartSessionOperatorRedemptionClient expiredClient = + newClient(stub, Clock.fixed(Instant.parse("2026-10-09T00:01:00Z"), ZoneOffset.UTC)); + assertThatThrownBy(() -> expiredClient.redeem(expired, OPAQUE_REFERENCE, claim(REQUEST_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("expired"); + verifyNoInteractions(stub); + } + + @Test + void rejectsTupleAndClaimOutsideConfiguredNamespaceBeforeCallingAccount() { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + StartSessionPostAuthorizationExecutionTuple otherNamespaceTuple = tuple(REQUEST_ID, "other"); + + assertThatThrownBy( + () -> client.redeem(otherNamespaceTuple, OPAQUE_REFERENCE, claim(REQUEST_ID, "other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace") + .hasMessageNotContaining(OPAQUE_REFERENCE); + verifyNoInteractions(stub); + } + + @Test + void rejectsAmbientSqlTransactionOrSynchronizationBeforeCallingAccount() { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.redeem(tuple, OPAQUE_REFERENCE, claim(REQUEST_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an owner SQL transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.redeem(tuple, OPAQUE_REFERENCE, claim(REQUEST_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside an owner SQL transaction"); + verifyNoInteractions(stub); + } + + @Test + void rejectsMalformedMissingUnknownAndSubstitutedAccountProjectionFields() throws Exception { + StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); + assertRejected(tuple, RedeemOperatorAuthorizationResponse.getDefaultInstance()); + + assertRejected( + tuple, + validResponse(tuple).toBuilder() + .setAuthorizationReferenceFingerprint("arfp/v1/other/" + "c".repeat(64)) + .build()); + assertRejected( + tuple, validResponse(tuple).toBuilder().setIssuanceOperationId("not-a-uuid").build()); + assertRejected(tuple, validResponse(tuple).toBuilder().setIssuanceFence(24L).build()); + assertRejected( + tuple, + validResponse(tuple).toBuilder() + .setAuthorityEvidenceBundle( + ByteString.copyFrom( + bundle( + tuple.preAuthorizationTuple(), + "18", + "2026-10-09T00:00:00Z", + "2026-10-09T00:05:00Z"))) + .build()); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + assertRejected(tuple, validResponse(tuple).toBuilder().setUnknownFields(unknown).build()); + } + + @Test + void letsRedemptionTimeoutRemainAmbiguousWithoutAutomaticRetryOrTerminalization() { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + StatusRuntimeException timeout = + new StatusRuntimeException(Status.DEADLINE_EXCEEDED.withDescription("ambiguous response")); + when(stub.redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class))) + .thenThrow(timeout); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + + assertThatThrownBy(() -> client.redeem(tuple(REQUEST_ID), OPAQUE_REFERENCE, claim(REQUEST_ID))) + .isSameAs(timeout); + + verify(stub, times(1)) + .redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class)); + } + + @Test + void refusesPlaintextOrMissingMutualTlsCredentialsAndDoesNotInitializeByConstruction() { + CommonGrpcClientProperties plaintext = tlsProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new StartSessionOperatorRedemptionClient( + new ServiceEndpointsProperties(), + plaintext, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + CURRENT_CLOCK)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mutual TLS"); + + CommonGrpcClientProperties missingIdentity = new CommonGrpcClientProperties(); + missingIdentity.setCaCert("ca.pem"); + assertThatThrownBy( + () -> + new StartSessionOperatorRedemptionClient( + new ServiceEndpointsProperties(), + missingIdentity, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + CURRENT_CLOCK)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mutual TLS"); + + StartSessionOperatorRedemptionClient uninitialized = newClient(null, CURRENT_CLOCK); + assertThatThrownBy( + () -> uninitialized.redeem(tuple(REQUEST_ID), OPAQUE_REFERENCE, claim(REQUEST_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("explicitly initialized"); + + assertThatThrownBy( + () -> + new StartSessionOperatorRedemptionClient( + new ServiceEndpointsProperties(), + tlsProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + "Invalid_Namespace", + CURRENT_CLOCK)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + } + + private static void assertRejected( + StartSessionPostAuthorizationExecutionTuple tuple, + RedeemOperatorAuthorizationResponse response) + throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class))) + .thenReturn(response); + StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); + assertThatThrownBy(() -> client.redeem(tuple, OPAQUE_REFERENCE, claim(REQUEST_ID))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("malformed or tuple-substituted"); + verify(stub, times(1)) + .redeemOperatorAuthorization(any(RedeemOperatorAuthorizationRequest.class)); + } + + private static StartSessionOperatorRedemptionClient newClient( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub, + Clock clock) { + StartSessionOperatorRedemptionClient client = + new StartSessionOperatorRedemptionClient( + new ServiceEndpointsProperties(), + tlsProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + clock); + if (stub != null) { + setStub(client, stub); + } + return client; + } + + private static CommonGrpcClientProperties tlsProperties() { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain("client-chain.pem"); + tls.setPrivateKey("client-key.pem"); + tls.setCaCert("account-ca.pem"); + tls.setPlaintext(false); + return tls; + } + + private static void setStub( + StartSessionOperatorRedemptionClient client, + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub) { + try { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } catch (ReflectiveOperationException exception) { + throw new AssertionError(exception); + } + } + + private static AttemptClaim claim(String requestId) { + return claim(requestId, NAMESPACE); + } + + private static AttemptClaim claim(String requestId, String namespace) { + return new AttemptClaim(namespace, requestId, OWNER_ATTEMPT, OWNER_MUTATION, CLAIM_OWNER, 37L); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple(String requestId) { + return tuple(requestId, "2026-10-09T00:00:00Z", "2026-10-09T00:05:00Z"); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, String evaluatedAt, String expiresAt) { + return tuple(requestId, evaluatedAt, expiresAt, NAMESPACE); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, String namespace) { + return tuple(requestId, "2026-10-09T00:00:00Z", "2026-10-09T00:05:00Z", namespace); + } + + private static StartSessionPostAuthorizationExecutionTuple tuple( + String requestId, String evaluatedAt, String expiresAt, String namespace) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, namespace), + new StartSessionOperatorAction.Target(91L, TARGET_OWNER), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "Game Session Account redemption client contract"); + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman(requestId, ACTOR, action); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + bundle(pre, "17", evaluatedAt, expiresAt), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static RedeemOperatorAuthorizationResponse validResponse( + StartSessionPostAuthorizationExecutionTuple tuple) { + return validResponse(tuple, tuple.canonicalBytes()); + } + + private static RedeemOperatorAuthorizationResponse validResponse( + StartSessionPostAuthorizationExecutionTuple tuple, + StartSessionPostAuthorizationExecutionTuple accountTuple) { + return validResponse(tuple, accountTuple.canonicalBytes()); + } + + private static RedeemOperatorAuthorizationResponse validResponse( + StartSessionPostAuthorizationExecutionTuple tuple, byte[] accountTupleBytes) { + return RedeemOperatorAuthorizationResponse.newBuilder() + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setAuthorityEvidenceBundle(ByteString.copyFrom(tuple.authorityEvidenceBundleBytes())) + .setIssuanceOperationId(ISSUANCE_ID.toString()) + .setIssuanceFence(23L) + .setOriginalAccountPostAuthorizationTuple(ByteString.copyFrom(accountTupleBytes)) + .setReplay(false) + .build(); + } + + private static StartSessionPostAuthorizationExecutionTuple tupleWithReference( + StartSessionPostAuthorizationExecutionTuple original, + String sourceFence, + String linearization) { + var reference = original.bundleReference(); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + original.preAuthorizationTuple(), + original.authenticatedWorkloadIdentity(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.authorityEvidenceBundleBytes(), + new StartSessionAuthorityEvidenceBundle.BundleReference( + reference.bundleVersion(), reference.sourceVersion(), sourceFence, linearization)); + } + + private static byte[] bundle( + StartSessionPreAuthorizationReservationTuple tuple, + String sourceVersion, + String evaluatedAt, + String expiresAt) { + String tenantId = TENANT.toString(); + String namespace = tuple.action().scope().targetNamespace(); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "a".repeat(64), + "sourceEvidenceVersion", + sourceVersion, + "projectionStatus", + "CURRENT", + "evaluatedAt", + evaluatedAt, + "expiresAt", + expiresAt); + Map identity = + Map.of( + "issuanceOperationId", ISSUANCE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map authority = + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()); + Map evidence = + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + ACTOR.toString(), + "controlUiTokenJti", + TOKEN_JTI.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3"); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantId, "targetNamespace", namespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", ACTOR.toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + projection, + "issuanceOperationIdentity", + identity, + "issuanceKind", + "human_operator", + "authorityTuple", + authority, + "membershipVersion", + Map.of(tenantId, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + evidence); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException(exception); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcServiceTest.java index 5a1a551770..4760d58f76 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadGrpcServiceTest.java @@ -44,6 +44,7 @@ import tools.jackson.databind.json.JsonMapper; class OriginalStartSessionCurrentAttemptReadGrpcServiceTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); private static final String NAMESPACE = "world-runtime"; private static final UUID READ_ID = UUID.fromString("01111111-1111-4111-8111-111111111111"); private static final UUID ATTEMPT = UUID.fromString("02222222-2222-4222-8222-222222222222"); @@ -152,7 +153,10 @@ void rejectsChangedAttemptMutationFenceTupleOrPhaseReturnedByRepository() { snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), exactProjection); when(changedPhase.phaseState()).thenReturn("COMMITTED"); AttemptSnapshot changedProjection = - snapshot(request, Instant.parse("2030-01-01T00:00:00Z"), new byte[] {2}); + snapshot( + request, + Instant.parse("2030-01-01T00:00:00Z"), + legacyScalarProjection(request.originalTuple())); GameSessionStartSessionOperatorAttemptRepository repository = mockRepository(); when(repository.readCurrentOriginalAttempt(ArgumentMatchers.any(Request.class))) .thenReturn( @@ -257,10 +261,35 @@ private static byte[] canonicalProjection(Request request) { tuple.authorizationReferenceFingerprint(), tuple.authorityEvidenceBundleBytes(), authority.issuanceOperationId(), - Long.parseLong(tuple.issuanceFence())) + Long.parseLong(tuple.issuanceFence()), + tuple.canonicalBytes()) .canonicalBytes(); } + private static byte[] legacyScalarProjection(StartSessionPostAuthorizationExecutionTuple tuple) { + var authority = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + Map projection = + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + tuple.authorizationReferenceFingerprint(), + "authorityEvidenceBundle", + authority.jsonValue(), + "issuanceOperationId", + authority.issuanceOperationId().toString(), + "issuanceFence", + Long.parseLong(tuple.issuanceFence())); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(projection)); + } catch (IOException malformed) { + throw new IllegalStateException("Could not encode a legacy scalar projection", malformed); + } + } + private static Request request(String namespace) { return request(namespace, READ_ID); } diff --git a/services/logging-admin-service/build.gradle.kts b/services/logging-admin-service/build.gradle.kts index 8239daaaeb..34ca3bd9f7 100644 --- a/services/logging-admin-service/build.gradle.kts +++ b/services/logging-admin-service/build.gradle.kts @@ -13,6 +13,7 @@ firemudJooq { } dependencies { + testImplementation(testFixtures(project(":common-platform-core"))) testImplementation(libs.grpc.inprocess) testImplementation(libs.grpc.netty.shaded) testImplementation(testFixtures(project(":logging-admin-service"))) diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java index 9369cfbd8e..326b429520 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java @@ -32,6 +32,7 @@ import net.firedevops.firemud.common.grpc.GrpcTlsMaterialResolver; import net.firedevops.firemud.common.grpc.ResolvedGrpcTlsMaterial; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -48,7 +49,9 @@ public class StartSessionOperatorAuthorizationClient private static final int MAX_TUPLE_BYTES = 8 * 1_024; private static final int MAX_REQUEST_BYTES = MAX_TUPLE_BYTES + 16 * 1_024 + 1_024; private static final int MAX_RESPONSE_BYTES = - StartSessionAuthorityEvidenceBundle.MAX_BUNDLE_BYTES + 2_048; + StartSessionAuthorityEvidenceBundle.MAX_BUNDLE_BYTES + + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + + 2_048; private static final int MAX_CONTROL_UI_TOKEN_BYTES = 16 * 1_024; private static final int MAX_REFERENCE_BYTES = 128; private static final long RPC_DEADLINE_SECONDS = 5L; @@ -165,6 +168,9 @@ public AuthorizationReference issueHuman( response.getBundleReference(), response.getUnknownFields().asMap().isEmpty(), response.getAuthenticatedLoggingWorkloadIdentity(), + response.getOriginalAccountPostAuthorizationTuple().toByteArray(), + reservationOwnerId, + reservationClaimFence, tuple); } @@ -208,6 +214,9 @@ public AuthorizationReference recover( response.getBundleReference(), response.getUnknownFields().asMap().isEmpty(), response.getAuthenticatedLoggingWorkloadIdentity(), + response.getOriginalAccountPostAuthorizationTuple().toByteArray(), + reservationOwnerId, + reservationClaimFence, tuple); } @@ -273,6 +282,9 @@ private AuthorizationReference validateResponse( AuthorityEvidenceBundleReference wireReference, boolean hasNoUnknownFields, String authenticatedLoggingWorkloadIdentity, + byte[] originalAccountPostAuthorizationTuple, + UUID reservationOwnerId, + long reservationClaimFence, StartSessionPreAuthorizationReservationTuple tuple) { try { if (!hasNoUnknownFields || !hasExpiry || !hasBundleReference) { @@ -312,6 +324,21 @@ private AuthorizationReference validateResponse( if (!wireReference.getUnknownFields().asMap().isEmpty()) { throw malformedResponse(); } + StartSessionPostAuthorizationExecutionTuple expectedTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + authenticatedLoggingWorkloadIdentity, + fingerprint, + reservationOwnerId, + reservationClaimFence, + authorityEvidenceBundle, + reference); + StartSessionPostAuthorizationExecutionTuple accountTuple = + StartSessionPostAuthorizationExecutionTuple.decode(originalAccountPostAuthorizationTuple); + if (!java.security.MessageDigest.isEqual( + expectedTuple.canonicalBytes(), accountTuple.canonicalBytes())) { + throw malformedResponse(); + } return new AuthorizationReference( opaqueReference, fingerprint, @@ -319,7 +346,8 @@ private AuthorizationReference validateResponse( authorityEvidenceBundle, reference, authenticatedLoggingWorkloadIdentity, - bundle); + bundle, + accountTuple); } catch (IllegalStateException expected) { throw expected; } catch (RuntimeException malformed) { @@ -398,6 +426,7 @@ public static final class AuthorizationReference { private final StartSessionAuthorityEvidenceBundle.BundleReference bundleReference; private final String authenticatedLoggingWorkloadIdentity; private final StartSessionAuthorityEvidenceBundle decodedBundle; + private final StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple; private AuthorizationReference( String operatorAuthorizationReference, @@ -406,7 +435,8 @@ private AuthorizationReference( byte[] authorityEvidenceBundle, StartSessionAuthorityEvidenceBundle.BundleReference bundleReference, String authenticatedLoggingWorkloadIdentity, - StartSessionAuthorityEvidenceBundle decodedBundle) { + StartSessionAuthorityEvidenceBundle decodedBundle, + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple) { this.operatorAuthorizationReference = operatorAuthorizationReference; this.authorizationReferenceFingerprint = authorizationReferenceFingerprint; this.expiresAt = expiresAt; @@ -414,6 +444,7 @@ private AuthorizationReference( this.bundleReference = bundleReference; this.authenticatedLoggingWorkloadIdentity = authenticatedLoggingWorkloadIdentity; this.decodedBundle = decodedBundle; + this.postAuthorizationTuple = postAuthorizationTuple; } public String operatorAuthorizationReference() { @@ -445,6 +476,11 @@ public StartSessionAuthorityEvidenceBundle decodedBundle() { return decodedBundle; } + /** Exact canonical tuple authored by Account from its retained original issuance evidence. */ + public StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple() { + return postAuthorizationTuple; + } + @Override public String toString() { return "AuthorizationReference[operatorAuthorizationReference=, " @@ -454,6 +490,7 @@ public String toString() { + bundleReference + ", authenticatedLoggingWorkloadIdentity=" + authenticatedLoggingWorkloadIdentity + + ", postAuthorizationTuple=" + "]"; } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java index d585e513af..251d523285 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java @@ -4,6 +4,7 @@ import java.nio.ByteBuffer; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; import java.util.Arrays; import java.util.Base64; import java.util.Map; @@ -239,7 +240,7 @@ private Result persistExactAccountResponse( accountResponse.authenticatedLoggingWorkloadIdentity())) { return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); } - postAuthorizationTuple = + StartSessionPostAuthorizationExecutionTuple expectedTuple = StartSessionPostAuthorizationExecutionTuple.createHuman( sharedTuple(tuple), accountResponse.authenticatedLoggingWorkloadIdentity(), @@ -248,7 +249,11 @@ private Result persistExactAccountResponse( claimEvidence.reservationClaimFence(), accountResponse.authorityEvidenceBundle(), accountResponse.bundleReference()); - if (!isExactAccountResult(tuple, claimEvidence, accountResponse, postAuthorizationTuple)) { + postAuthorizationTuple = accountResponse.postAuthorizationTuple(); + if (postAuthorizationTuple == null + || !MessageDigest.isEqual( + expectedTuple.canonicalBytes(), postAuthorizationTuple.canonicalBytes()) + || !isExactAccountResult(tuple, claimEvidence, accountResponse, postAuthorizationTuple)) { return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); } } catch (RuntimeException invalidResponse) { diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java index 271ee2c29b..3b699a6ed4 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java @@ -62,6 +62,7 @@ import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.test.TlsTestSupport; @@ -70,6 +71,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.json.JsonMapper; @@ -132,8 +135,10 @@ void stopTransportAndClearThreadState() throws Exception { TransactionSynchronizationManager.clear(); } - @Test - void issueAndRecoverPreserveTheExactOriginalResponseAndCompleteEvidence() throws Exception { + @ParameterizedTest + @ValueSource(longs = {9_007_199_254_740_993L, Long.MAX_VALUE}) + void issueAndRecoverPreserveTheExactOriginalResponseAndCompleteEvidence(long reservationFence) + throws Exception { startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); client = newClient(pki.loggingClient()); client.initialize(); @@ -141,9 +146,9 @@ void issueAndRecoverPreserveTheExactOriginalResponseAndCompleteEvidence() throws var issued = client.issueHuman( - tuple, CONTROL_UI_JWT, RESERVATION_OWNER_ID, Long.MAX_VALUE, CLAIM_OWNER_ID, 71L); + tuple, CONTROL_UI_JWT, RESERVATION_OWNER_ID, reservationFence, CLAIM_OWNER_ID, 71L); var recovered = - client.recover(tuple, RESERVATION_OWNER_ID, Long.MAX_VALUE, CLAIM_OWNER_ID, 71L); + client.recover(tuple, RESERVATION_OWNER_ID, reservationFence, CLAIM_OWNER_ID, 71L); assertThat(issued.operatorAuthorizationReference()).isEqualTo(OPERATOR_REFERENCE); assertThat(recovered.operatorAuthorizationReference()).isEqualTo(OPERATOR_REFERENCE); @@ -154,6 +159,21 @@ void issueAndRecoverPreserveTheExactOriginalResponseAndCompleteEvidence() throws assertThat(recovered.authorityEvidenceBundle()) .containsExactly(issued.authorityEvidenceBundle()); assertThat(recovered.bundleReference()).isEqualTo(issued.bundleReference()); + assertThat(issued.postAuthorizationTuple().canonicalBytes()) + .containsExactly(originalTupleBytes(tuple, RESERVATION_OWNER_ID, reservationFence)); + assertThat(recovered.postAuthorizationTuple().canonicalBytes()) + .containsExactly(issued.postAuthorizationTuple().canonicalBytes()); + assertThat(issued.postAuthorizationTuple().reservationOwnerId()) + .isEqualTo(RESERVATION_OWNER_ID); + assertThat(issued.postAuthorizationTuple().reservationClaimFence()).isEqualTo(reservationFence); + assertThat(recovered.postAuthorizationTuple().reservationClaimFence()) + .isEqualTo(reservationFence); + Map encodedTuple = + JSON.readValue(issued.postAuthorizationTuple().canonicalBytes(), Map.class); + assertThat(encodedTuple.get("reservationClaimFence")) + .isEqualTo(Long.toString(reservationFence)); + assertThat(issued.bundleReference().sourceFence()) + .isNotEqualTo(issued.postAuthorizationTuple().issuanceFence()); assertThat(issued.authenticatedLoggingWorkloadIdentity()).isEqualTo(LOGGING_URI); assertThat(recovered.authenticatedLoggingWorkloadIdentity()).isEqualTo(LOGGING_URI); assertThat(issued.decodedBundle().controlPlaneRequestId()) @@ -163,7 +183,7 @@ void issueAndRecoverPreserveTheExactOriginalResponseAndCompleteEvidence() throws assertThat(receivedIssue.getCanonicalPreAuthorizationTupleBytes().toByteArray()) .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); assertThat(receivedIssue.getReservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID.toString()); - assertThat(receivedIssue.getReservationClaimFence()).isEqualTo(Long.MAX_VALUE); + assertThat(receivedIssue.getReservationClaimFence()).isEqualTo(reservationFence); assertThat(receivedIssue.getCurrentClaimOwnerId()).isEqualTo(CLAIM_OWNER_ID.toString()); assertThat(receivedIssue.getCurrentClaimFence()).isEqualTo(71L); assertThat(receivedRecovery.getCanonicalPreAuthorizationTupleBytes().toByteArray()) @@ -251,6 +271,27 @@ void rejectsUnknownFieldsChangedTupleBindingAndExpirySubstitution() throws Excep assertInvalidResponse(); stopTransportOnly(); + for (UnaryOperator substitute : + List.>of( + response -> response.toBuilder().clearOriginalAccountPostAuthorizationTuple().build(), + response -> + response.toBuilder() + .setBundleReference( + response.getBundleReference().toBuilder().setSourceFence("25")) + .build(), + response -> + response.toBuilder() + .setBundleReference( + response.getBundleReference().toBuilder() + .setLinearization("18446744073709551614")) + .build())) { + startServer(pki.accountServer(), substitute, UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + } + startServer( pki.accountServer(), response -> @@ -513,6 +554,12 @@ private static IssueHumanOperatorAuthorizationReferenceResponse issueResponse( .setAuthorityEvidenceBundle(ByteString.copyFrom(bundleFor(tupleFrom(request)))) .setBundleReference(bundleReference()) .setAuthenticatedLoggingWorkloadIdentity(LOGGING_URI) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + originalTupleBytes( + tupleFrom(request), + UUID.fromString(request.getReservationOwnerId()), + request.getReservationClaimFence()))) .build(); } @@ -525,9 +572,33 @@ private static RecoverOperatorAuthorizationReferenceResponse recoveryResponse( .setAuthorityEvidenceBundle(ByteString.copyFrom(bundleFor(tupleFrom(request)))) .setBundleReference(bundleReference()) .setAuthenticatedLoggingWorkloadIdentity(LOGGING_URI) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + originalTupleBytes( + tupleFrom(request), + UUID.fromString(request.getReservationOwnerId()), + request.getReservationClaimFence()))) .build(); } + private static byte[] originalTupleBytes( + StartSessionPreAuthorizationReservationTuple tuple, UUID reservationOwner, long fence) { + var reference = bundleReference(); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + LOGGING_URI, + FINGERPRINT, + reservationOwner, + fence, + bundleFor(tuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + reference.getBundleVersion(), + reference.getSourceVersion(), + reference.getSourceFence(), + reference.getLinearization())) + .canonicalBytes(); + } + private static byte[] bundleFor( net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple tuple) { String tenantId = tuple.action().scope().tenantId().toString(); @@ -601,7 +672,7 @@ private static AuthorityEvidenceBundleReference bundleReference() { return AuthorityEvidenceBundleReference.newBuilder() .setBundleVersion(StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION) .setSourceVersion("17") - .setSourceFence("23") + .setSourceFence("24") .setLinearization("18446744073709551615") .build(); } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java index a90028172f..dd42d41ebe 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java @@ -25,7 +25,6 @@ import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -44,7 +43,10 @@ import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -99,12 +101,18 @@ void issueAndRecoverUseExactTupleAndClaimIdentityAndReturnValidatedOriginalBytes assertThat(issued.authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); assertThat(issued.expiresAt()).isEqualTo(NOW.plusSeconds(300)); assertThat(issued.authorityEvidenceBundle()).containsExactly(bundle); - assertThat(issued.bundleReference().sourceFence()).isEqualTo("23"); + assertThat(issued.bundleReference().sourceFence()).isEqualTo("24"); assertThat(issued.authenticatedLoggingWorkloadIdentity()) .isEqualTo(LOGGING_WORKLOAD_IDENTITY); assertThat(issued.decodedBundle().controlPlaneRequestId()).isEqualTo("client-βeta"); + assertThat(issued.postAuthorizationTuple().canonicalBytes()) + .containsExactly(postTupleBytes(tuple, bundle, sharedReference())); + assertThat(issued.postAuthorizationTuple().bundleReference().sourceFence()) + .isNotEqualTo(issued.postAuthorizationTuple().issuanceFence()); assertThat(recovered.authorityEvidenceBundle()).containsExactly(bundle); assertThat(recovered.operatorAuthorizationReference()).isEqualTo(OPAQUE_REFERENCE); + assertThat(recovered.postAuthorizationTuple().canonicalBytes()) + .containsExactly(postTupleBytes(tuple, bundle, sharedReference())); assertThat(recovered.authenticatedLoggingWorkloadIdentity()) .isEqualTo(LOGGING_WORKLOAD_IDENTITY); @@ -213,6 +221,7 @@ void rejectsMalformedUnknownChangedOrExpiredAccountResponses() throws Exception assertRejected(tuple, valid.toBuilder().setUnknownFields(unknownFields()).build()); assertRejected(tuple, valid.toBuilder().clearExpiresAt().build()); assertRejected(tuple, valid.toBuilder().clearBundleReference().build()); + assertRejected(tuple, valid.toBuilder().clearOriginalAccountPostAuthorizationTuple().build()); assertRejected( tuple, valid.toBuilder() @@ -227,6 +236,34 @@ void rejectsMalformedUnknownChangedOrExpiredAccountResponses() throws Exception .setBundleReference( valid.getBundleReference().toBuilder().setSourceVersion("18").build()) .build()); + assertRejected( + tuple, + valid.toBuilder() + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + postTupleBytes( + tuple, + validBundle, + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "25", + "18446744073709551615")))) + .build()); + assertRejected( + tuple, + valid.toBuilder() + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + postTupleBytes( + tuple, + validBundle, + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "24", + "18446744073709551614")))) + .build()); assertRejected( tuple, valid.toBuilder() @@ -433,6 +470,8 @@ private static IssueHumanOperatorAuthorizationReferenceResponse issueResponse( .setAuthorityEvidenceBundle(ByteString.copyFrom(bundle)) .setBundleReference(reference()) .setAuthenticatedLoggingWorkloadIdentity(LOGGING_WORKLOAD_IDENTITY) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom(postTupleBytes(tuple, bundle, sharedReference()))) .build(); } @@ -445,6 +484,8 @@ private static RecoverOperatorAuthorizationReferenceResponse recoverResponse( .setAuthorityEvidenceBundle(ByteString.copyFrom(bundle)) .setBundleReference(reference()) .setAuthenticatedLoggingWorkloadIdentity(LOGGING_WORKLOAD_IDENTITY) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom(postTupleBytes(tuple, bundle, sharedReference()))) .build(); } @@ -457,86 +498,47 @@ private static Timestamp timestamp(Instant instant) { private static AuthorityEvidenceBundleReference reference() { return AuthorityEvidenceBundleReference.newBuilder() - .setBundleVersion(StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION) - .setSourceVersion("17") - .setSourceFence("23") - .setLinearization("18446744073709551615") + .setBundleVersion(sharedReference().bundleVersion()) + .setSourceVersion(sharedReference().sourceVersion()) + .setSourceFence(sharedReference().sourceFence()) + .setLinearization(sharedReference().linearization()) .build(); } + private static StartSessionAuthorityEvidenceBundle.BundleReference sharedReference() { + return new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "18446744073709551615"); + } + + private static byte[] postTupleBytes( + StartSessionPreAuthorizationReservationTuple tuple, + byte[] bundle, + StartSessionAuthorityEvidenceBundle.BundleReference reference) { + return StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, LOGGING_WORKLOAD_IDENTITY, FINGERPRINT, RESERVATION_OWNER, 9L, bundle, reference) + .canonicalBytes(); + } + private static byte[] bundleBytes( StartSessionPreAuthorizationReservationTuple tuple, Instant expiry) throws Exception { - String tenantId = TENANT_ID.toString(); - Map projection = - Map.of( - "sourceType", - "ACCOUNT", - "sourceEvidenceId", + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + tuple, + new Values( + ISSUANCE_ID, "sha256:" + "a".repeat(64), - "sourceEvidenceVersion", "17", - "projectionStatus", "CURRENT", - "evaluatedAt", - NOW.toString(), - "expiresAt", - expiry.toString()); - Map authority = - Map.of( - "issuerAuthGeneration", 1L, - "accountAuthorityGeneration", 2L, - "tenantAuthorityGeneration", Map.of(tenantId, 3L), - "membershipAuthorityGeneration", Map.of(tenantId, 4L), - "privateRealmGrantVersions", List.of()); - Map evidence = - Map.of( - "evidenceType", - StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, - "actorAccountId", - ACTOR_ID.toString(), - "controlUiTokenJti", - TOKEN_JTI.toString(), - "role", - "tenantAdmin", - "accountGeneration", + NOW, + expiry, + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + TOKEN_JTI, "2", - "tenantGeneration", - "3"); - Map bundle = - new LinkedHashMap<>( - Map.of( - "bundleVersion", - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "authorityScope", - Map.of( - "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), - "actionFamily", tuple.actionFamily(), - "applicableAccountId", ACTOR_ID.toString(), - "applicableTenantId", tenantId), - "accountProjectionEvidence", - projection, - "issuanceOperationIdentity", - Map.of( - "issuanceOperationId", ISSUANCE_ID.toString(), - "controlPlaneRequestId", tuple.controlPlaneRequestId(), - "actionFamilyRequestIdentity", - Map.of( - "requestIdentityKind", - "controlPlaneRequestId", - "requestId", - tuple.controlPlaneRequestId()), - "mutationDigest", tuple.mutationDigest()), - "issuanceKind", - "human_operator", - "authorityTuple", - authority, - "membershipVersion", - Map.of(tenantId, 5L), - "issuanceFence", - "23", - "issuanceEvidence", - evidence)); - return canonical(bundle); + "3")); } private static UnknownFieldSet unknownFields() { diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java index aa085c4d28..73b73c970d 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java @@ -14,7 +14,6 @@ import static org.mockito.Mockito.when; import io.grpc.Status; -import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; @@ -23,8 +22,9 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.security.SessionContext; @@ -50,7 +50,6 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; -import tools.jackson.databind.json.JsonMapper; class StartSessionAuthorizationCoordinatorTest { private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); @@ -72,7 +71,6 @@ class StartSessionAuthorizationCoordinatorTest { private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); private static final String LOGGING_IDENTITY = "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; - private static final JsonMapper JSON = JsonMapper.builder().build(); private final StartSessionPreAuthorizationReservationRepository repository = mock(StartSessionPreAuthorizationReservationRepository.class); @@ -121,7 +119,6 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere eq(NOW_MILLIS))) .thenReturn( new StartSessionPreAuthorizationReservationRepository.TransitionResult(pending, true)); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), eq(CONTROL_UI_TOKEN), @@ -129,7 +126,12 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere eq(1L), any(UUID.class), eq(1L))) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); Result first = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); @@ -210,6 +212,13 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere .contains(LOGGING_IDENTITY) .doesNotContain(OPAQUE_REFERENCE) .doesNotContain(CONTROL_UI_TOKEN); + assertThat(persistedTuple.getValue()) + .isEqualTo(first.handoff().postAuthorizationTuple().canonicalJson()); + assertThat( + StartSessionPostAuthorizationExecutionTuple.decode( + persistedTuple.getValue().getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .canonicalBytes()) + .containsExactly(first.handoff().postAuthorizationTuple().canonicalBytes()); persistenceOrder.verify(repository).findAuthorizedExact(eq(tuple)); persistenceOrder .verify(repository) @@ -342,10 +351,14 @@ void missingIndependentAuthorizedReadbackLeavesAuthorizationUnknownAndDoesNotHan throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-readback-missing"); stubInitialReservation(tuple); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); when(repository.findAuthorizedExact(eq(tuple))).thenReturn(Optional.empty()); @@ -366,10 +379,14 @@ void missingIndependentAuthorizedReadbackLeavesAuthorizationUnknownAndDoesNotHan void conflictingIndependentAuthorizedReadbackCannotAdvanceOwnerPending() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-readback-conflict"); stubInitialReservation(tuple); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); when(repository.findAuthorizedExact(eq(tuple))) .thenAnswer( @@ -418,10 +435,14 @@ void recoveryUsesOriginalOwnerAndFreshFenceAndNeverCallsIssue() throws Exception Optional.of( new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( pending, ORIGINAL_OWNER))); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.recover( eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(1), + ((Number) invocation.getArgument(2)).longValue())); stubAuthorizationEnrichment(tuple, true, true); Result result = coordinator.recover(tuple); @@ -458,7 +479,6 @@ void issueHumanAndDispatchForwardsOnlyAfterDurableOwnerPendingAndOnlyOnce() thro .thenReturn( new StartSessionPreAuthorizationReservationRepository.TransitionResult( alreadyPending, true)); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), eq(CONTROL_UI_TOKEN), @@ -466,7 +486,12 @@ void issueHumanAndDispatchForwardsOnlyAfterDurableOwnerPendingAndOnlyOnce() thro eq(1L), any(UUID.class), eq(1L))) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); GameSessionClient ownerClient = mock(GameSessionClient.class); StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); @@ -540,10 +565,14 @@ void recoverAndDispatchForwardsTheOriginalRecoveredOperationOnce() throws Except Optional.of( new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( pending, ORIGINAL_OWNER))); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.recover( eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(1), + ((Number) invocation.getArgument(2)).longValue())); stubAuthorizationEnrichment(tuple, true, true); GameSessionClient ownerClient = mock(GameSessionClient.class); StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); @@ -636,10 +665,14 @@ void ambiguousOwnerDispatchPropagatesAndExactDuplicateDoesNotRedeliver() throws .thenReturn( new StartSessionPreAuthorizationReservationRepository.TransitionResult( alreadyPending, true)); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), eq(1L), any(UUID.class), eq(1L))) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); GameSessionClient ownerClient = mock(GameSessionClient.class); io.grpc.StatusRuntimeException ambiguous = Status.UNAVAILABLE.asRuntimeException(); @@ -663,10 +696,14 @@ void ambiguousOwnerDispatchPropagatesAndExactDuplicateDoesNotRedeliver() throws void ownerPendingDuplicateCasDoesNotReturnTransientHandoff() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-owner-duplicate"); stubInitialReservation(tuple); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, false); Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); @@ -694,10 +731,14 @@ void ownerPendingDuplicateCasDoesNotReturnTransientHandoff() throws Exception { void ownerPendingTransitionFailureNeverReturnsTransientPayload() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-owner-stale"); stubInitialReservation(tuple); - AuthorizationReference response = authorizationReference(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenReturn(response); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); when(repository.beginOwnerExecution( eq(tuple), @@ -795,10 +836,14 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-mismatch"); StartSessionPreAuthorizationReservationTuple substituted = tuple("coordinator-substituted"); stubInitialReservation(tuple); - AuthorizationReference substitutedResponse = authorizationReference(substituted); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenReturn(substitutedResponse); + .thenAnswer( + invocation -> + authorizationReference( + substituted, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); Result invalidAccountResult = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); @@ -814,7 +859,6 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr StartSessionPreAuthorizationReservationTuple staleTuple = tuple("coordinator-stale-return"); stubInitialReservation(staleTuple); - AuthorizationReference staleResponse = authorizationReference(staleTuple); when(accountClient.issueHuman( eq(shared(staleTuple)), anyString(), @@ -822,7 +866,12 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr anyLong(), any(UUID.class), anyLong())) - .thenReturn(staleResponse); + .thenAnswer( + invocation -> + authorizationReference( + staleTuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); when(repository.completeAuthorization( eq(staleTuple), eq(staleTuple.mutationDigest()), @@ -846,6 +895,69 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); } + @Test + void sourceFenceAndLinearizationMismatchesNeverReachLoggingCompletion() throws Exception { + List alteredTupleReferences = + List.of( + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "25", + "18446744073709551615"), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "24", + "18446744073709551614")); + int caseNumber = 0; + for (var alteredReference : alteredTupleReferences) { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("coordinator-capture-reference-mismatch-" + caseNumber++); + stubInitialReservation(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), + anyString(), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong())) + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue(), + alteredReference)); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains(StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_RESPONSE_INVALID); + verify(repository, never()) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + eq(NOW_MILLIS)); + verify(repository, never()) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + any(UUID.class), + eq(NOW_MILLIS)); + } + } + private void stubInitialReservation(StartSessionPreAuthorizationReservationTuple tuple) { Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); @@ -958,14 +1070,37 @@ private void stubAuthorizationEnrichment( } private static AuthorizationReference authorizationReference( - StartSessionPreAuthorizationReservationTuple tuple) throws Exception { + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwner, + long reservationFence) + throws Exception { + return authorizationReference(tuple, reservationOwner, reservationFence, bundleReference()); + } + + private static AuthorizationReference authorizationReference( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwner, + long reservationFence, + StartSessionAuthorityEvidenceBundle.BundleReference tupleReference) + throws Exception { AuthorizationReference response = mock(AuthorizationReference.class); when(response.operatorAuthorizationReference()).thenReturn(OPAQUE_REFERENCE); when(response.authorizationReferenceFingerprint()).thenReturn(FINGERPRINT); when(response.expiresAt()).thenReturn(NOW.plusSeconds(300)); - when(response.authorityEvidenceBundle()).thenReturn(bundleBytes(tuple, NOW.plusSeconds(300))); + byte[] bundle = bundleBytes(tuple, NOW.plusSeconds(300)); + when(response.authorityEvidenceBundle()).thenReturn(bundle); when(response.bundleReference()).thenReturn(bundleReference()); when(response.authenticatedLoggingWorkloadIdentity()).thenReturn(LOGGING_IDENTITY); + when(response.postAuthorizationTuple()) + .thenReturn( + StartSessionPostAuthorizationExecutionTuple.createHuman( + shared(tuple), + LOGGING_IDENTITY, + FINGERPRINT, + reservationOwner, + reservationFence, + bundle, + tupleReference)); return response; } @@ -984,82 +1119,30 @@ private static StartSessionOwnerHandoffResult ownerEcho( } private static byte[] bundleBytes( - StartSessionPreAuthorizationReservationTuple tuple, Instant expiresAt) throws IOException { - String tenantId = TENANT_ID.toString(); - Map projection = - Map.of( - "sourceType", - "ACCOUNT", - "sourceEvidenceId", + StartSessionPreAuthorizationReservationTuple tuple, Instant expiresAt) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + shared(tuple), + new Values( + ISSUANCE_ID, "sha256:" + "a".repeat(64), - "sourceEvidenceVersion", "17", - "projectionStatus", "CURRENT", - "evaluatedAt", - NOW.toString(), - "expiresAt", - expiresAt.toString()); - Map authority = - Map.of( - "issuerAuthGeneration", 1L, - "accountAuthorityGeneration", 2L, - "tenantAuthorityGeneration", Map.of(tenantId, 3L), - "membershipAuthorityGeneration", Map.of(tenantId, 4L), - "privateRealmGrantVersions", List.of()); - Map evidence = - Map.of( - "evidenceType", - StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, - "actorAccountId", - ACTOR_ID.toString(), - "controlUiTokenJti", - TOKEN_JTI.toString(), - "role", - "tenantAdmin", - "accountGeneration", + NOW, + expiresAt, + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + TOKEN_JTI, "2", - "tenantGeneration", - "3"); - Map bundle = - Map.of( - "bundleVersion", - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "authorityScope", - Map.of( - "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), - "actionFamily", tuple.actionFamily(), - "applicableAccountId", ACTOR_ID.toString(), - "applicableTenantId", tenantId), - "accountProjectionEvidence", - projection, - "issuanceOperationIdentity", - Map.of( - "issuanceOperationId", ISSUANCE_ID.toString(), - "controlPlaneRequestId", tuple.controlPlaneRequestId(), - "actionFamilyRequestIdentity", - Map.of( - "requestIdentityKind", - "controlPlaneRequestId", - "requestId", - tuple.controlPlaneRequestId()), - "mutationDigest", tuple.mutationDigest()), - "issuanceKind", - "human_operator", - "authorityTuple", - authority, - "membershipVersion", - Map.of(tenantId, 5L), - "issuanceFence", - "23", - "issuanceEvidence", - evidence); - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + "3")); } private static StartSessionAuthorityEvidenceBundle.BundleReference bundleReference() { return new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "18446744073709551615"); } private static Snapshot snapshot( diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index 40b725fd86..4493baed0d 100644 --- a/services/world-management-service/build.gradle.kts +++ b/services/world-management-service/build.gradle.kts @@ -21,6 +21,7 @@ firemudJooq { dependencies { integrationTestImplementation(project(mapOf("path" to ":account-service", "configuration" to "accountOriginalOrderProof"))) implementation(project(":common-security")) + testImplementation(testFixtures(project(":common-platform-core"))) testImplementation(libs.bouncycastle.pkix) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java index 3c6a883d52..a762b7ce62 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifier.java @@ -79,13 +79,11 @@ public void verifyOriginalOperation(WorldCanonicalInstanceExecutionIdentity iden freshReadId( identity.accountWorldParticipationId(), identity.gameSessionOwnerAttemptId(), - identity.canonicalGameInstanceId()); + identity.canonicalGameInstanceId(), + identity.decodedTuple().reservationOwnerId()); AccountStartSessionWorldParticipationHistoricalReadRequest accountRequest = new AccountStartSessionWorldParticipationHistoricalReadRequest( - accountReadId, - identity.targetNamespace(), - identity.accountWorldParticipationId(), - identity.accountWorldParticipationFence()); + accountReadId, identity.targetNamespace(), identity.originalPostAuthorizationTuple()); AccountStartSessionWorldParticipationHistoricalReadEvidence accountEvidence = accountClient.read(accountRequest); if (accountEvidence == null) { @@ -124,15 +122,16 @@ private static void requireAccountEvidence( AccountStartSessionWorldParticipationHistoricalReadRequest expectedRequest, AccountStartSessionWorldParticipationHistoricalReadEvidence actual) { if (!expectedRequest.equals(actual.request()) - || !Arrays.equals( - identity.originalPostAuthorizationTuple(), actual.originalPostAuthorizationTuple()) + || !identity.accountWorldParticipationId().equals(actual.accountWorldParticipationId()) + || identity.accountWorldParticipationFence() != actual.accountWorldParticipationFence() || !identity.gameSessionOwnerAttemptId().equals(actual.gameSessionOwnerAttemptId()) || identity.gameSessionOwnerFence() != actual.gameSessionOwnerFence() || !identity.canonicalGameInstanceId().equals(actual.canonicalGameInstanceId()) || !identity.preparationInputJson().equals(actual.preparationInputJson()) || !identity.preparationInputDigest().equals(actual.preparationInputDigest())) { throw denied( - "Account historical participation differs from the complete original World execution tuple"); + "Account historical participation differs from the complete original World execution" + + " tuple"); } } @@ -147,7 +146,8 @@ private static void requireGameSessionEvidence( || !identity.gameSessionOwnerAttemptId().equals(actual.ownerAttemptId()) || identity.gameSessionOwnerFence() != actual.ownerFence()) { throw denied( - "Game Session historical evidence differs from the exact original tuple or owner attempt"); + "Game Session historical evidence differs from the exact original tuple or owner" + + " attempt"); } HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation association = @@ -179,7 +179,8 @@ private static void requireGameSessionEvidence( || !retained.sameJsonValue( retained.gameSessionReadEvidence().get("releaseAttestationJson"), release)) { throw denied( - "Game Session descriptor or release attestation differs from the exact retained preparation input"); + "Game Session descriptor or release attestation differs from the exact retained" + + " preparation input"); } retained.requireLaunchBindingAndSource(descriptor, release); } @@ -203,7 +204,8 @@ private static void requireFirstSelectionMatches( || !text(retained.sourceIntake, "sourceEvidenceDigest") .equals(firstSelection.sourceEvidenceDigest())) { throw denied( - "Game Session first-selection pin differs from the exact retained World release and source"); + "Game Session first-selection pin differs from the exact retained World release and" + + " source"); } } @@ -792,7 +794,8 @@ void requireCrossOwnerReadSelectors() { || number(this.identity, "catalogRevision", true) != number(gameSessionReadEvidence, "catalogRevision", true))) { throw denied( - "Retained World launch-captured catalog identity differs between identity and Game Session evidence"); + "Retained World launch-captured catalog identity differs between identity and Game" + + " Session evidence"); } if (number(launchBinding, "schemaVersion", true) != 1L diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java index 66b38ed7a1..c4f7a61da8 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java @@ -10,6 +10,7 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; +import java.time.Instant; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -26,7 +27,12 @@ import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence.LaunchAssociation; import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidenceReadClient; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; @@ -58,8 +64,12 @@ class WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest { private static final long ACCOUNT_FENCE = 31L; private static final long GAME_SESSION_FENCE = 37L; private static final long GAME_TEMPLATE_ID = 91L; - private static final byte[] ORIGINAL_TUPLE = - "synthetic-original-start-session-tuple".getBytes(StandardCharsets.UTF_8); + private static final UUID RESERVATION_OWNER = uuid("7c005b65-fcb1-4ac9-a714-f3d0f449edcf"); + private static final StartSessionPostAuthorizationExecutionTuple ORIGINAL_OPERATION = + originalOperation("start-session-control-request"); + private static final byte[] ORIGINAL_TUPLE = ORIGINAL_OPERATION.canonicalBytes(); + private static final byte[] CHANGED_TUPLE = + originalOperation("start-session-changed-request").canonicalBytes(); @AfterEach void clearAmbientTransactionState() { @@ -127,12 +137,13 @@ private void acceptsExactHistoricalOwnerEvidenceAndUsesFreshReadCorrelations(Fix AccountStartSessionWorldParticipationHistoricalReadRequest.class); verify(account).read(accountRequest.capture()); assertThat(accountRequest.getValue().targetNamespace()).isEqualTo(NAMESPACE); - assertThat(accountRequest.getValue().accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); - assertThat(accountRequest.getValue().accountWorldParticipationFence()).isEqualTo(ACCOUNT_FENCE); + assertThat(accountRequest.getValue().originalPostAuthorizationTuple()) + .containsExactly(ORIGINAL_TUPLE); assertThat(accountRequest.getValue().readRequestId()) .isNotEqualTo(PARTICIPATION_ID) .isNotEqualTo(ATTEMPT_ID) - .isNotEqualTo(GAME_INSTANCE); + .isNotEqualTo(GAME_INSTANCE) + .isNotEqualTo(RESERVATION_OWNER); var gameSessionRequest = org.mockito.ArgumentCaptor.forClass( @@ -153,8 +164,7 @@ void rejectsAccountTupleAttemptOrFenceSubstitutionBeforeGameSessionRead() { Fixture fixture = fixture(false); var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); - byte[] tuple = - substitution == 0 ? "changed tuple".getBytes(StandardCharsets.UTF_8) : ORIGINAL_TUPLE; + byte[] tuple = substitution == 0 ? CHANGED_TUPLE : ORIGINAL_TUPLE; UUID attempt = substitution == 1 ? uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa") : ATTEMPT_ID; long fence = substitution == 2 ? GAME_SESSION_FENCE + 1L : GAME_SESSION_FENCE; when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) @@ -172,14 +182,43 @@ void rejectsAccountTupleAttemptOrFenceSubstitutionBeforeGameSessionRead() { } } + @Test + void rejectsAccountResolvedParticipationIdOrFenceBeforeGameSessionRead() { + for (boolean substituteId : new boolean[] {true, false}) { + Fixture fixture = fixture(false); + var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); + var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) + .thenAnswer( + invocation -> { + var evidence = + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.preparationInputJson()); + if (substituteId) { + when(evidence.accountWorldParticipationId()) + .thenReturn(uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + } else { + when(evidence.accountWorldParticipationFence()).thenReturn(ACCOUNT_FENCE + 1L); + } + return evidence; + }); + + assertDenied(verifier(account, gameSession), fixture.identity()); + verifyNoInteractions(gameSession); + } + } + @Test void rejectsGameSessionTupleAttemptOrFenceSubstitution() { for (int substitution = 0; substitution < 3; substitution++) { Fixture fixture = fixture(false); var account = exactAccountClient(fixture); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); - byte[] tuple = - substitution == 0 ? "changed tuple".getBytes(StandardCharsets.UTF_8) : ORIGINAL_TUPLE; + byte[] tuple = substitution == 0 ? CHANGED_TUPLE : ORIGINAL_TUPLE; UUID attempt = substitution == 1 ? uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa") : ATTEMPT_ID; long fence = substitution == 2 ? GAME_SESSION_FENCE + 1L : GAME_SESSION_FENCE; when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) @@ -197,6 +236,80 @@ void rejectsGameSessionTupleAttemptOrFenceSubstitution() { } } + @Test + void rejectsAccountCaptureFenceOrLinearizationSubstitutionBeforeGameSessionRead() { + for (byte[] substituted : changedCaptureReferences()) { + Fixture fixture = fixture(false); + var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); + var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) + .thenAnswer( + invocation -> + accountEvidence( + invocation.getArgument(0), + substituted, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.preparationInputJson())); + + assertDenied(verifier(account, gameSession), fixture.identity()); + verifyNoInteractions(gameSession); + } + } + + @Test + void rejectsGameSessionCaptureFenceOrLinearizationSubstitution() { + for (byte[] substituted : changedCaptureReferences()) { + Fixture fixture = fixture(false); + var account = exactAccountClient(fixture); + var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); + when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) + .thenAnswer( + invocation -> + gameSessionEvidence( + invocation.getArgument(0), + fixture, + substituted, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.launchAssociation())); + + assertDenied(verifier(account, gameSession), fixture.identity()); + } + } + + private static List changedCaptureReferences() { + var originalReference = ORIGINAL_OPERATION.bundleReference(); + return List.of( + withReference( + new StartSessionAuthorityEvidenceBundle.BundleReference( + originalReference.bundleVersion(), + originalReference.sourceVersion(), + "24", + originalReference.linearization())), + withReference( + new StartSessionAuthorityEvidenceBundle.BundleReference( + originalReference.bundleVersion(), + originalReference.sourceVersion(), + originalReference.sourceFence(), + "18446744073709551614"))); + } + + // Structurally canonical substitutions exercise World comparison of the complete original + // bytes. Mocked owner responses do not establish independent Account capture authentication. + private static byte[] withReference( + StartSessionAuthorityEvidenceBundle.BundleReference reference) { + return StartSessionPostAuthorizationExecutionTuple.createHuman( + ORIGINAL_OPERATION.preAuthorizationTuple(), + ORIGINAL_OPERATION.authenticatedWorkloadIdentity(), + ORIGINAL_OPERATION.authorizationReferenceFingerprint(), + ORIGINAL_OPERATION.reservationOwnerId(), + ORIGINAL_OPERATION.reservationClaimFence(), + ORIGINAL_OPERATION.authorityEvidenceBundleBytes(), + reference) + .canonicalBytes(); + } + @Test void rejectsDescriptorOrSourceAssociationSubstitution() { Fixture exact = fixture(false); @@ -374,6 +487,7 @@ private static Fixture fixture( WorldCanonicalInstanceExecutionIdentity identity = mock(WorldCanonicalInstanceExecutionIdentity.class); when(identity.originalPostAuthorizationTuple()).thenReturn(ORIGINAL_TUPLE.clone()); + when(identity.decodedTuple()).thenReturn(ORIGINAL_OPERATION); when(identity.accountWorldParticipationId()).thenReturn(PARTICIPATION_ID); when(identity.accountWorldParticipationFence()).thenReturn(ACCOUNT_FENCE); when(identity.gameSessionOwnerAttemptId()).thenReturn(ATTEMPT_ID); @@ -772,6 +886,54 @@ private static String preparationInput( return json(root); } + private static StartSessionPostAuthorizationExecutionTuple originalOperation(String requestId) { + var preTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + requestId, + uuid("a4f5f4eb-8243-4d42-903a-33495456a622"), + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT, NAMESPACE), + new StartSessionOperatorAction.Target( + GAME_TEMPLATE_ID, uuid("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a")), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "synthetic historical World recovery carrier test")); + byte[] bundle = + StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + preTuple, + new Values( + uuid("f5d044bd-7e5f-4e2d-9859-9025cbdcc60f"), + "sha256:" + "a".repeat(64), + "17", + "CURRENT", + Instant.parse("2020-01-01T00:00:00Z"), + Instant.parse("2020-01-02T00:00:00Z"), + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + uuid("a681bba7-c215-4cf1-a35b-14348912cbdc"), + "2", + "3")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + preTuple, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + RESERVATION_OWNER, + 19L, + bundle, + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + private static AccountStartSessionWorldParticipationHistoricalReadClient exactAccountClient( Fixture fixture) { var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); @@ -794,8 +956,12 @@ private static AccountStartSessionWorldParticipationHistoricalReadEvidence accou long fence, String preparationInput) { var evidence = mock(AccountStartSessionWorldParticipationHistoricalReadEvidence.class); - when(evidence.request()).thenReturn(request); - when(evidence.originalPostAuthorizationTuple()).thenReturn(tuple.clone()); + var echoedRequest = + new AccountStartSessionWorldParticipationHistoricalReadRequest( + request.readRequestId(), request.targetNamespace(), tuple); + when(evidence.request()).thenReturn(echoedRequest); + when(evidence.accountWorldParticipationId()).thenReturn(PARTICIPATION_ID); + when(evidence.accountWorldParticipationFence()).thenReturn(ACCOUNT_FENCE); when(evidence.gameSessionOwnerAttemptId()).thenReturn(attempt); when(evidence.gameSessionOwnerFence()).thenReturn(fence); when(evidence.canonicalGameInstanceId()).thenReturn(GAME_INSTANCE); From 0285bc38e6234aa2342020d8918e7c54b9f5cd26 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 16:16:36 +1300 Subject: [PATCH 128/129] Record receiving qualification and selected composition limits --- design/project-management/ai-observations.md | 2 ++ .../game-authoring-publishing-and-activation.md | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index f17aeb5cce..d6e56a013b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -358,3 +358,5 @@ Transport outcome (2026-10-13): The actual loopback mTLS probe receives `9007199 Receiving correction outcome (2026-10-13): The exact published #3183 correction at `a66918116e44cd4d19777bff64f6528b87b3ecac` is selectively adopted into #3105. Fresh focused receiving proof passes both formerly failing wide-fence mTLS cases, all eight transport cases, ten shared tuple/projection cases and five native Game Session current-owner/replay PostgreSQL cases. Independent decoded-value assertions confirm the adjacent-wide and maximum decimal strings; no historical bytes, tuple version, authority-map shapes or SQL guards are changed. Broader receiving composition proof remains separate and pending. Physical owner extension (2026-10-13): All three Account PostgreSQL/mTLS cases pass: the original fence-one Logging claim read plus World acquisition and separate adjacent-wide/maximum Account capture, issuance, redemption and Game Session reservation/projection replay. Logging issue and Game Session redemption use production typed clients to the real Account gRPC owner. The physical Logging original reservation schema starts at fence one, so wide claim-reader inputs remain explicitly stipulated; no SQL trigger or mutation guard is bypassed. Creator, legal, signer and custody inputs remain test-only. These focused results do not qualify the complete selected composition or close genuine producer, terminal, placement or region-delivery handoffs. + +Selected receiving-source outcome (2026-10-13): The fresh committed-source check passes 585 Game Design units but fails empty-core at the unchanged five-second Game Design descriptor read and player-created earlier at Account selected-publication settlement. This differs from the preceding run in which both reached descriptor resolution; source-local immutable reuse does not establish a universal deadline repair. The first Gameplay terminal summary incorrectly claimed both descriptor phases before full originating XML inspection; an explicit correction was sent immediately. Read dependent terminal reports before forwarding phase-specific outcomes. Neither timed-out commit outcome nor CPU, nested-read or SQL cause is established; current owner guards and deadlines remain unchanged. 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 bea0243098..6b17279b6f 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 @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -The original StartSession receiving construction locally carries the independently Account-returned full tuple through issue/recovery, Logging completion/handoff, Game Session redemption retention and the fresh native launch-allocation check. Current use rejects scalar-only Account projections; exact historical reads preserve retained legacy bytes without granting new authority. World historical participation lookup uses the complete original tuple and checks Account-returned coordinates against its retained identity. The exact published [PR #3183](https://github.com/benhook1013/FireMUD/pull/3183) correction at `a66918116e44cd4d19777bff64f6528b87b3ecac` is selectively adopted under Overseer decision 1251, preserving Root's combined pin/launch graph and migration history. Receiving focused proof passes ten shared-core cases, eight Logging mTLS cases and five native Game Session owner/replay PostgreSQL cases, with zero failures, errors or skips. Both adjacent-wide and maximum reservation fences retain their exact typed value and canonical decimal-string spelling; safe numeric and byte-preserved historical guards remain. The separate real Account mTLS/storage extension passes all three physical cases: adjacent-wide and maximum fences traverse the production Logging issue and Game Session redemption clients, real Account capture/issuance/redemption storage and Game Session projection retention/replay; the original fence-one case also uses the actual Logging claim reader and World acquisition owner. Broader receiving qualification passes the canonical full checks for Common Platform, Account, Logging, Game Session and World on this selective correction. Fresh originating reports contain 739 Common units; 1,402 Account units and eight selected PostgreSQL cases; 263 Logging units and all 24 PostgreSQL cases; 2,043 Game Session units, 12 selected PostgreSQL cases and 39 cross-service cases; and 691 World units plus all 230 PostgreSQL cases, all with zero failures, errors or skips. Game Design integration compilation, links and Markdown lint also pass; complete Account/Game Session integration suites and the selected Game Design composition are outside this passing aggregate. Logging's physical original reservation schema requires fence 1; wider claim-reader inputs in the Account proof remain explicitly stipulated and do not demonstrate a physical Logging allocator. Prior independent Account, Game Session and World gates qualify their exercised boundaries only. Both prior changed selected-export scenarios reach the unchanged five-second Game Design descriptor-read deadline after Account settlement/retry/readbacks, original ISSUE/REDEEM tuple receiving and initial association assertions; their whole composition remains failed, and the timeout cause remains unestablished. The newly adopted validated immutable-bundle caching will receive a fresh composition check. Donor proof and synthetic upstream fixture authority do not close any genuine owner handoff or runtime activation gate below. +The original StartSession receiving construction locally carries the independently Account-returned full tuple through issue/recovery, Logging completion/handoff, Game Session redemption retention and the fresh native launch-allocation check. Current use rejects scalar-only Account projections; exact historical reads preserve retained legacy bytes without granting new authority. World historical participation lookup uses the complete original tuple and checks Account-returned coordinates against its retained identity. The exact published [PR #3183](https://github.com/benhook1013/FireMUD/pull/3183) correction at `a66918116e44cd4d19777bff64f6528b87b3ecac` is selectively adopted under Overseer decision 1251, preserving Root's combined pin/launch graph and migration history. Receiving focused proof passes ten shared-core cases, eight Logging mTLS cases and five native Game Session owner/replay PostgreSQL cases, with zero failures, errors or skips. Both adjacent-wide and maximum reservation fences retain their exact typed value and canonical decimal-string spelling; safe numeric and byte-preserved historical guards remain. The separate real Account mTLS/storage extension passes all three physical cases: adjacent-wide and maximum fences traverse the production Logging issue and Game Session redemption clients, real Account capture/issuance/redemption storage and Game Session projection retention/replay; the original fence-one case also uses the actual Logging claim reader and World acquisition owner. Broader receiving qualification passes the canonical full checks for Common Platform, Account, Logging, Game Session and World on this selective correction. Fresh originating reports contain 739 Common units; 1,402 Account units and eight selected PostgreSQL cases; 263 Logging units and all 24 PostgreSQL cases; 2,043 Game Session units, 12 selected PostgreSQL cases and 39 cross-service cases; and 691 World units plus all 230 PostgreSQL cases, all with zero failures, errors or skips. Game Design integration compilation, links and Markdown lint also pass; complete Account/Game Session integration suites and the selected Game Design composition are outside this passing aggregate. Logging's physical original reservation schema requires fence 1; wider claim-reader inputs in the Account proof remain explicitly stipulated and do not demonstrate a physical Logging allocator. Prior independent Account, Game Session and World gates qualify their exercised boundaries only. The fresh selected-export check on the committed receiving source passes 585 Game Design units but fails both whole cases: empty-core reaches the unchanged five-second Game Design descriptor deadline after Account settlement/retry/readbacks, original ISSUE/REDEEM tuple receiving and initial association assertions; player-created stops earlier at the unchanged five-second Account settlement deadline. Its later original-tuple and descriptor phases are unrun. The adopted immutable-bundle caching does not prove a universal deadline repair; either timeout’s owner commit outcome and cause remain unestablished. This failing invocation does not reach the full Game Design check or its final documentation tasks. Donor proof and synthetic upstream fixture authority do not close any genuine owner handoff or runtime activation gate below. The existing draft [PR #3105](https://github.com/benhook1013/FireMUD/pull/3105) remains on the approved parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`. Restored local Docker exposes and repairs a concrete Entity setup self-wait: the concurrent V4 index waited on Flyway's own transactional advisory-lock connection. The service startup, shadowing Spring test configuration and direct migration fixtures now select session-level advisory locking. Applied migration bytes, concurrent indexing and constraints remain unchanged. Entity receipt metadata compares PostgreSQL TIMESTAMPTZ values by instant, preserving immutable canonical receipt bytes and all identity/digest guards. The pre-V3 quarantine fixture seeds its retained numeric row using the historical schema before exercising the current writer after migration. From 89cdbf05d080b09412515cd39f6c2c0364037e41 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:49:19 +1300 Subject: [PATCH 129/129] Align Account receiving SQL with the complete original tuple --- design/project-management/ai-observations.md | 4 + ...ame-authoring-publishing-and-activation.md | 2 + ...al_start_session_full_tuple_projection.sql | 62 ++++++ ...tionProtectionPostgresIntegrationTest.java | 54 +++-- ...sionProtectionPostgresIntegrationTest.java | 202 +++++++++++++++--- ...ntialCleanupRepositoryIntegrationTest.java | 8 +- 6 files changed, 287 insertions(+), 45 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V164__original_start_session_full_tuple_projection.sql diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index d6e56a013b..0947b0dc39 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -360,3 +360,7 @@ Receiving correction outcome (2026-10-13): The exact published #3183 correction Physical owner extension (2026-10-13): All three Account PostgreSQL/mTLS cases pass: the original fence-one Logging claim read plus World acquisition and separate adjacent-wide/maximum Account capture, issuance, redemption and Game Session reservation/projection replay. Logging issue and Game Session redemption use production typed clients to the real Account gRPC owner. The physical Logging original reservation schema starts at fence one, so wide claim-reader inputs remain explicitly stipulated; no SQL trigger or mutation guard is bypassed. Creator, legal, signer and custody inputs remain test-only. These focused results do not qualify the complete selected composition or close genuine producer, terminal, placement or region-delivery handoffs. Selected receiving-source outcome (2026-10-13): The fresh committed-source check passes 585 Game Design units but fails empty-core at the unchanged five-second Game Design descriptor read and player-created earlier at Account selected-publication settlement. This differs from the preceding run in which both reached descriptor resolution; source-local immutable reuse does not establish a universal deadline repair. The first Gameplay terminal summary incorrectly claimed both descriptor phases before full originating XML inspection; an explicit correction was sent immediately. Read dependent terminal reports before forwarding phase-specific outcomes. Neither timed-out commit outcome nor CPU, nested-read or SQL cause is established; current owner guards and deadlines remain unchanged. + +Receiving SQL alignment (2026-10-13): Actual published-source Account CI exposes seven acquisition failures after the Java projection converged on full original tuple bytes: applied V133 still expects the historical scalar projection, and V161 repeats that current-use comparison. A narrow forward V164 replaces those shape checks with exact byte binding and retains the independent issuance-operation comparison through the nested Account bundle. Historical settlement, immutable rows and all other source/owner/expiry checks remain separate. The credential cleanup fixture also lacked V163's explicit schema placeholder. An initial upgrade assertion accidentally admitted test-only V1000+ migrations beyond its V163 baseline; the corrected proof targets exactly V164. The first acquisition retry failed during Redis port startup before test methods, so it supplied no repair proof for those cases; its environment cause remains unknown. Current repair qualification is pending, and no genuine producer or runtime authority is inferred. + +Receiving qualification outcome (2026-10-13): The complete local Account gate executes 1,402 passing units and 306 integrations with six failures, all originating in PostgreSQL connection refusal or Redis startup. The repaired nine admission-acquisition, ten admission SQL, two activation SQL and seven credential-cleanup cases pass, including exact V163-to-V164 checksum, function identity, body-delta and row-retention proof. An earlier prepared SQL clause used the wrong issuer JSON path; focused execution caught it, and the corrected nested issuanceOperationIdentity path is physically exercised. Local infrastructure cause is unestablished; do not weaken owner deadlines or infer current genuine handoff proof from prior passing snapshots. 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 6b17279b6f..920c5dfec5 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 @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +Published receiving source `0285bc38e6234aa2342020d8918e7c54b9f5cd26` has failed [automatic source CI](https://github.com/benhook1013/FireMUD/actions/runs/38341051363): the originating Account owner report contains 306 integration cases and eight failures. Credential cleanup cannot initialize without the explicit `serviceSchema` placeholder; seven admission-acquisition cases reach the obsolete scalar-projection SQL check before their intended assertions. The local V164 correction converges the existing admission and activation receiving guards on exact original Account tuple bytes while retaining independent issuance-operation binding. Applied migration bytes, function identities, retained rows, other owner/source/expiry guards and historical settlement remain protected. Updated synthetic SQL fixtures and the exact V163-to-V164 preservation/current-denial test pass. The complete local Account invocation freshly passes 1,402 units and executes 306 integration cases with six failures: two readiness cases and three original World-acquisition cases encounter PostgreSQL connection refusal, and publication authorization fails during Redis startup. The repaired nine admission-acquisition cases, ten admission SQL cases, two activation SQL cases and seven credential-cleanup cases all pass without failures, errors or skips. These establish the receiving repair and preservation boundary, not a passing whole Account gate; fresh physical World-acquisition proof is unavailable in this invocation. Account formatting, Checkstyle, SpotBugs, links and Markdown checks pass separately after the full integration failure. The runtime rollout, four genuine handoffs and broader Unit 1B remain held. + The original StartSession receiving construction locally carries the independently Account-returned full tuple through issue/recovery, Logging completion/handoff, Game Session redemption retention and the fresh native launch-allocation check. Current use rejects scalar-only Account projections; exact historical reads preserve retained legacy bytes without granting new authority. World historical participation lookup uses the complete original tuple and checks Account-returned coordinates against its retained identity. The exact published [PR #3183](https://github.com/benhook1013/FireMUD/pull/3183) correction at `a66918116e44cd4d19777bff64f6528b87b3ecac` is selectively adopted under Overseer decision 1251, preserving Root's combined pin/launch graph and migration history. Receiving focused proof passes ten shared-core cases, eight Logging mTLS cases and five native Game Session owner/replay PostgreSQL cases, with zero failures, errors or skips. Both adjacent-wide and maximum reservation fences retain their exact typed value and canonical decimal-string spelling; safe numeric and byte-preserved historical guards remain. The separate real Account mTLS/storage extension passes all three physical cases: adjacent-wide and maximum fences traverse the production Logging issue and Game Session redemption clients, real Account capture/issuance/redemption storage and Game Session projection retention/replay; the original fence-one case also uses the actual Logging claim reader and World acquisition owner. Broader receiving qualification passes the canonical full checks for Common Platform, Account, Logging, Game Session and World on this selective correction. Fresh originating reports contain 739 Common units; 1,402 Account units and eight selected PostgreSQL cases; 263 Logging units and all 24 PostgreSQL cases; 2,043 Game Session units, 12 selected PostgreSQL cases and 39 cross-service cases; and 691 World units plus all 230 PostgreSQL cases, all with zero failures, errors or skips. Game Design integration compilation, links and Markdown lint also pass; complete Account/Game Session integration suites and the selected Game Design composition are outside this passing aggregate. Logging's physical original reservation schema requires fence 1; wider claim-reader inputs in the Account proof remain explicitly stipulated and do not demonstrate a physical Logging allocator. Prior independent Account, Game Session and World gates qualify their exercised boundaries only. The fresh selected-export check on the committed receiving source passes 585 Game Design units but fails both whole cases: empty-core reaches the unchanged five-second Game Design descriptor deadline after Account settlement/retry/readbacks, original ISSUE/REDEEM tuple receiving and initial association assertions; player-created stops earlier at the unchanged five-second Account settlement deadline. Its later original-tuple and descriptor phases are unrun. The adopted immutable-bundle caching does not prove a universal deadline repair; either timeout’s owner commit outcome and cause remain unestablished. This failing invocation does not reach the full Game Design check or its final documentation tasks. Donor proof and synthetic upstream fixture authority do not close any genuine owner handoff or runtime activation gate below. The existing draft [PR #3105](https://github.com/benhook1013/FireMUD/pull/3105) remains on the approved parent `fe15a31f274b1c9850dd388e83faf540916ee8a3`. Restored local Docker exposes and repairs a concrete Entity setup self-wait: the concurrent V4 index waited on Flyway's own transactional advisory-lock connection. The service startup, shadowing Spring test configuration and direct migration fixtures now select session-level advisory locking. Applied migration bytes, concurrent indexing and constraints remain unchanged. Entity receipt metadata compares PostgreSQL TIMESTAMPTZ values by instant, preserving immutable canonical receipt bytes and all identity/digest guards. The pre-V3 quarantine fixture seeds its retained numeric row using the historical schema before exercising the current writer after migration. diff --git a/services/account-service/src/main/resources/db/migration/V164__original_start_session_full_tuple_projection.sql b/services/account-service/src/main/resources/db/migration/V164__original_start_session_full_tuple_projection.sql new file mode 100644 index 0000000000..6ee2982680 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V164__original_start_session_full_tuple_projection.sql @@ -0,0 +1,62 @@ +-- Current receiving protection retains the exact Account original tuple as its projection. +-- Preserve applied migrations, immutable rows and every other current-source/owner/expiry guard. +-- Historical settlement remains a separate boundary; scalar history grants no current authority. +-- [jooq ignore start] +DO $migration$ +DECLARE + original_function REGPROCEDURE := '"${serviceSchema}".account_ss_admission_assert_current("${serviceSchema}".account_start_session_admission_protections,boolean)'::REGPROCEDURE; + original_definition TEXT; + projection_anchor TEXT := $anchor$ IF projection_value IS DISTINCT FROM jsonb_build_object( + 'projectionSchemaId', 'accountStartSessionRedemptionProjection', + 'projectionSchemaVersion', '1', + 'authorizationReferenceFingerprint', authorization_row.authorization_reference_fingerprint, + 'authorityEvidenceBundle', convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB, + 'issuanceOperationId', authorization_row.issuance_operation_id::TEXT, + 'issuanceFence', authorization_row.issuance_fence)$anchor$; + projection_replacement TEXT := $replacement$ IF original.account_redemption_projection IS DISTINCT FROM original.original_post_authorization_tuple + OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}' + IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT$replacement$; +BEGIN + SELECT pg_get_functiondef(original_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, projection_anchor, ''))) + / length(projection_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact original admission scalar projection guard'; + END IF; + original_definition := replace(original_definition, projection_anchor, projection_replacement); + IF (length(original_definition) - length(replace(original_definition, projection_replacement, ''))) + / length(projection_replacement) <> 1 THEN + RAISE EXCEPTION 'Expected exact full-tuple admission projection guard'; + END IF; + EXECUTE original_definition; +END; +$migration$; + +DO $migration$ +DECLARE + original_function REGPROCEDURE := '"${serviceSchema}".account_ss_activation_assert_current(bytea,bytea,text,boolean)'::REGPROCEDURE; + original_definition TEXT; + projection_anchor TEXT := $anchor$ OR projection_value IS DISTINCT FROM jsonb_build_object( + 'projectionSchemaId', 'accountStartSessionRedemptionProjection', + 'projectionSchemaVersion', '1', + 'authorizationReferenceFingerprint', authorization_row.authorization_reference_fingerprint, + 'authorityEvidenceBundle', convert_from(authorization_row.authority_evidence_bundle, 'UTF8')::JSONB, + 'issuanceOperationId', authorization_row.issuance_operation_id::TEXT, + 'issuanceFence', authorization_row.issuance_fence)$anchor$; + projection_replacement TEXT := $replacement$ OR projection_bytes IS DISTINCT FROM tuple_bytes + OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}' + IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT$replacement$; +BEGIN + SELECT pg_get_functiondef(original_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, projection_anchor, ''))) + / length(projection_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact original activation scalar projection guard'; + END IF; + original_definition := replace(original_definition, projection_anchor, projection_replacement); + IF (length(original_definition) - length(replace(original_definition, projection_replacement, ''))) + / length(projection_replacement) <> 1 THEN + RAISE EXCEPTION 'Expected exact full-tuple activation projection guard'; + END IF; + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java index 70708c0c42..e247a90772 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -419,6 +419,34 @@ void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() thro valid.operationIdentityBytes(), valid.operationIdentityDigest())); + Map changedProjectionRequest = + JSON.readValue(valid.requestBytes(), new tools.jackson.core.type.TypeReference<>() {}); + byte[] originalTuple = + Base64.getDecoder() + .decode( + (String) changedProjectionRequest.get("originalPostAuthorizationTupleBytesBase64")); + byte[] differentSpelling = + (" " + new String(originalTuple, StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8); + changedProjectionRequest.put( + "accountRedemptionProjectionBytesBase64", + Base64.getEncoder().encodeToString(differentSpelling)); + byte[] changedProjection = jsonBytes(changedProjectionRequest); + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + changedProjection, + valid.operationIdentityBytes(), + valid.operationIdentityDigest()))) + .hasMessageContaining( + "Activation protection differs from original Account redemption or capture"); + byte[] changedAttempt = activationRequest(valid, UUID.randomUUID().toString(), valid.expiryText(), "PREPARING"); assertCurrentnessRejected(fixture, changedAttempt, valid.operationIdentityBytes()); @@ -636,7 +664,11 @@ private static CurrentnessCase currentnessCase(Fixture fixture, Instant original .format(normalizedLease); byte[] preAuthorization = bytes("{}"); - byte[] authorityBundle = bytes("{}"); + Map bundleValue = + Map.of( + "issuanceOperationIdentity", + Map.of("issuanceOperationId", issuanceOperationId.toString())); + byte[] authorityBundle = jsonBytes(bundleValue); byte[] tuple = jsonBytes( Map.of( @@ -649,22 +681,10 @@ private static CurrentnessCase currentnessCase(Fixture fixture, Instant original "issuanceFence", Long.toString(issuanceFence), "authorityEvidenceBundle", - Map.of())); - byte[] projection = - jsonBytes( - Map.of( - "projectionSchemaId", - "accountStartSessionRedemptionProjection", - "projectionSchemaVersion", - "1", - "authorizationReferenceFingerprint", - fingerprint, - "authorityEvidenceBundle", - Map.of(), - "issuanceOperationId", - issuanceOperationId.toString(), - "issuanceFence", - issuanceFence)); + bundleValue)); + // Current-use integrity preserves the complete stipulated original tuple without scalarizing + // it. + byte[] projection = tuple.clone(); SourceEvidence sourceEvidence = new SourceEvidence( SourceKind.ACCOUNT, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index 86c4bec005..869f628157 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -27,6 +27,7 @@ import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.SQLDialect; @@ -45,8 +46,8 @@ /** * SQL integrity and source-writer definitions. Upstream Account capture, redeemed authorization, * World settlement and Game Session observation are explicitly stipulated with upstream triggers - * disabled. New V133 guards remain enabled for acquisition and all assertions. These fixtures are - * not genuine authenticated Account/World/Game Session producer or consumer proof. + * disabled. Current admission guards remain enabled for acquisition and all assertions. These + * fixtures are not genuine authenticated Account/World/Game Session producer or consumer proof. */ @Testcontainers(disabledWithoutDocker = true) class AccountStartSessionAdmissionProtectionPostgresIntegrationTest { @@ -54,6 +55,143 @@ class AccountStartSessionAdmissionProtectionPostgresIntegrationTest { static final PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void forwardUpgradePreservesLegacyRowsAndChangesOnlyExactCurrentProjectionChecks() { + Fixture historical = fixture(60_000L, "163", true); + acquire(historical); + String beforeRow = + historical + .dsl() + .fetchSingle( + "SELECT to_jsonb(protection)::text FROM account_start_session_admission_protections protection WHERE protection_id = ?", + historical.protectionId()) + .get(0, String.class); + var checksums = + historical + .dsl() + .fetch( + "SELECT version, checksum FROM flyway_schema_history WHERE success AND version IS NOT NULL ORDER BY installed_rank"); + String admissionSignature = + "account_ss_admission_assert_current(account_start_session_admission_protections,boolean)"; + String activationSignature = "account_ss_activation_assert_current(bytea,bytea,text,boolean)"; + Map beforeDefinitions = new LinkedHashMap<>(); + Map beforeOids = new LinkedHashMap<>(); + for (String signature : List.of(admissionSignature, activationSignature)) { + beforeDefinitions.put( + signature, + historical + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class)); + beforeOids.put( + signature, + historical + .dsl() + .fetchSingle("SELECT ?::regprocedure::oid::bigint", signature) + .get(0, Long.class)); + } + String historicalSettlement = + historical + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef('account_ss_admission_settlement_insert_guard()'::regprocedure)") + .get(0, String.class); + Flyway.configure() + .dataSource(historical.dataSource()) + .schemas(historical.dataSource().getSchema()) + .defaultSchema(historical.dataSource().getSchema()) + .placeholders(Map.of("serviceSchema", historical.dataSource().getSchema())) + .locations("classpath:db/migration") + .target(MigrationVersion.fromVersion("164")) + .load() + .migrate(); + assertThat( + historical + .dsl() + .fetch( + "SELECT version, checksum FROM flyway_schema_history WHERE success AND version IS NOT NULL AND version <> '164' ORDER BY installed_rank")) + .isEqualTo(checksums); + for (String signature : beforeDefinitions.keySet()) { + assertThat( + historical + .dsl() + .fetchSingle("SELECT ?::regprocedure::oid::bigint", signature) + .get(0, Long.class)) + .isEqualTo(beforeOids.get(signature)); + String after = + historical + .dsl() + .fetchSingle("SELECT pg_get_functiondef(?::regprocedure)", signature) + .get(0, String.class); + String before = beforeDefinitions.get(signature); + int start = + before.indexOf( + signature.equals(admissionSignature) + ? " IF projection_value IS DISTINCT FROM jsonb_build_object(" + : " OR projection_value IS DISTINCT FROM jsonb_build_object("); + int end = + signature.equals(admissionSignature) + ? before.indexOf(" THEN", start) + : before.indexOf("\n OR capture.canonical_sha256", start); + assertThat(start).isGreaterThanOrEqualTo(0); + assertThat(end).isGreaterThan(start); + String replacement = + signature.equals(admissionSignature) + ? " IF original.account_redemption_projection IS DISTINCT FROM original.original_post_authorization_tuple\n" + + " OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}'\n" + + " IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT" + : " OR projection_bytes IS DISTINCT FROM tuple_bytes\n" + + " OR projection_value #>> '{authorityEvidenceBundle,issuanceOperationIdentity,issuanceOperationId}'\n" + + " IS DISTINCT FROM authorization_row.issuance_operation_id::TEXT"; + assertThat(after).isEqualTo(before.substring(0, start) + replacement + before.substring(end)); + } + assertThat( + historical + .dsl() + .fetchSingle( + "SELECT pg_get_functiondef('account_ss_admission_settlement_insert_guard()'::regprocedure)") + .get(0, String.class)) + .isEqualTo(historicalSettlement); + assertThat( + historical + .dsl() + .fetchSingle( + "SELECT to_jsonb(protection)::text FROM account_start_session_admission_protections protection WHERE protection_id = ?", + historical.protectionId()) + .get(0, String.class)) + .isEqualTo(beforeRow); + assertThatThrownBy( + () -> + historical + .transaction() + .executeWithoutResult( + status -> + historical + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + historical.protectionId(), + 1L, + historical.request()))) + .hasMessageContaining( + "Admission projection differs from complete original Account redemption"); + assertThatThrownBy( + () -> + historical + .transaction() + .executeWithoutResult( + status -> + historical + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + historical.source().key()))) + .hasMessageContaining("Original StartSession admission protection remains pending"); + Fixture current = fixture(); + acquire(current); + assertThat(current.projection()).containsExactly(current.tuple()); + } + @Test void installsAdditiveHooksWithoutRemovingExistingOwnerChecks() { Fixture fixture = fixture(); @@ -551,19 +689,24 @@ private static Fixture fixture() { } private static Fixture fixture(long leaseMillis) { + return fixture(leaseMillis, null, false); + } + + private static Fixture fixture(long leaseMillis, String target, boolean historicalScalar) { String schema = "ss_admission_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource source = new DriverManagerDataSource( postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); source.setSchema(schema); - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); + var migration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) migration.target(MigrationVersion.fromVersion(target)); + migration.load().migrate(); DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); TransactionTemplate transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); @@ -584,6 +727,8 @@ private static Fixture fixture(long leaseMillis) { SourceEvidence evidence = new SourceEvidence( SourceKind.HOSTED_TERMS, "test-terms", "1", "1", null, null, bytes("terms")); + Map authorityBundle = + Map.of("issuanceOperationIdentity", Map.of("issuanceOperationId", issuance.toString())); byte[] tuple = json( Map.of( @@ -594,22 +739,25 @@ private static Fixture fixture(long leaseMillis) { "issuanceFence", "9", "authorityEvidenceBundle", - Map.of())); + authorityBundle)); + // Upstream authority is explicitly stipulated; current SQL still requires exact tuple bytes. byte[] projection = - json( - Map.of( - "projectionSchemaId", - "accountStartSessionRedemptionProjection", - "projectionSchemaVersion", - "1", - "authorizationReferenceFingerprint", - "arfp/v1/key-1/" + "a".repeat(64), - "authorityEvidenceBundle", - Map.of(), - "issuanceOperationId", - issuance.toString(), - "issuanceFence", - 9L)); + historicalScalar + ? json( + Map.of( + "projectionSchemaId", + "accountStartSessionRedemptionProjection", + "projectionSchemaVersion", + "1", + "authorizationReferenceFingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "authorityEvidenceBundle", + authorityBundle, + "issuanceOperationId", + issuance.toString(), + "issuanceFence", + 9L)) + : tuple.clone(); var holdRequest = new WorldCanonicalInitialAdmissionHold.Request( "test", @@ -781,7 +929,7 @@ private static Fixture fixture(long leaseMillis) { "bundle_linearization", "17", "authority_evidence_bundle", - bytes("{}"), + json(authorityBundle), "authorization_reference_fingerprint", "arfp/v1/key-1/" + "a".repeat(64), "encrypted_response_envelope", @@ -805,7 +953,7 @@ private static Fixture fixture(long leaseMillis) { "redemption_reference_fingerprint", "arfp/v1/key-1/" + "a".repeat(64), "redemption_authority_evidence_bundle", - bytes("{}")); + json(authorityBundle)); insert( dsl, "account_start_session_world_participations", diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java index 8b47064d2b..0fb1f817aa 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CredentialCleanupRepositoryIntegrationTest.java @@ -51,7 +51,13 @@ class CredentialCleanupRepositoryIntegrationTest { @BeforeAll void setUpRepositories() { dataSource = newDataSource(); - Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + Flyway.configure() + .dataSource(dataSource) + .defaultSchema("public") + .placeholders(java.util.Map.of("serviceSchema", "public")) + .locations(MIGRATION_LOCATION) + .load() + .migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); passwordResetTokenRepository = new PasswordResetTokenRepository(dsl); emailVerificationTokenRepository = new EmailVerificationTokenRepository(dsl);